From faf38cc5cf7f657fd16503c5099de82c363fe8f9 Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Thu, 23 May 2019 13:21:25 -0700 Subject: [PATCH 01/27] formatting System.Windows.Forms.Tests --- src/Common/tests/CommonTestHelper.cs | 4 +- .../DataGridViewCellAccessibleObjectTests.cs | 4 +- .../ToolStripItemAccessibleObjectTests.cs | 2 +- .../tests/UnitTests/BindingNavigatorTests.cs | 10 +- .../tests/UnitTests/CheckedListBoxTests.cs | 4 +- .../CommonUnsafeNativeMethodsTests.cs | 2 +- .../tests/UnitTests/DomainUpDownTests.cs | 7 +- .../tests/UnitTests/DpiHelperTests.cs | 2 +- .../tests/UnitTests/ErrorProviderTests.cs | 4 +- .../tests/UnitTests/LinkLabelTests.cs | 2 +- .../UnitTests/MenuItemCollectionTests.cs | 16 +- .../tests/UnitTests/MenuItemTests.cs | 8 +- .../tests/UnitTests/MenuTests.cs | 8 +- .../UnitTests/SRCategoryAttributeTests.cs | 2 +- .../Design/PaintValueEventArgsTests.cs | 44 ++-- .../Design/PropertyValueUIItemTests.cs | 54 ++--- .../System/Windows/Forms/ApplicationTests.cs | 2 +- .../Windows/Forms/BaseCollectionTests.cs | 6 +- .../Windows/Forms/BindingContextTests.cs | 16 +- .../Windows/Forms/BindingManagerBaseTests.cs | 8 +- .../System/Windows/Forms/BindingTests.cs | 8 +- .../Windows/Forms/BindingsCollectionTests.cs | 4 +- .../Forms/ColumnHeaderCollectionTests.cs | 26 +-- .../System/Windows/Forms/ColumnHeaderTests.cs | 8 +- .../System/Windows/Forms/ColumnStyleTests.cs | 2 +- .../System/Windows/Forms/CommonDialogTests.cs | 6 +- .../Windows/Forms/ContainerControlTests.cs | 2 +- .../Forms/ControlBindingsCollectionTests.cs | 10 +- .../System/Windows/Forms/ControlTests.cs | 14 +- .../System/Windows/Forms/CreateParamsTests.cs | 2 +- .../System/Windows/Forms/DataGridCellTests.cs | 4 +- .../Windows/Forms/DataGridColumnStyleTests.cs | 26 +-- .../DataGridViewCellPaintingEventArgsTests.cs | 6 +- .../Forms/DataGridViewCellStyleTests.cs | 2 +- .../Windows/Forms/DataGridViewCellTests.cs | 40 ++-- .../Forms/DataGridViewColumnEventArgsTests.cs | 2 +- .../Windows/Forms/DataGridViewElementTests.cs | 12 +- .../Forms/DataGridViewRowEventArgsTests.cs | 2 +- .../DataGridViewRowPostPaintEventArgsTests.cs | 14 +- .../DataGridViewRowPrePaintEventArgsTests.cs | 14 +- .../Windows/Forms/DataGridViewRowTests.cs | 46 ++--- .../Windows/Forms/Design/EventsTabTests.cs | 2 +- .../Windows/Forms/Design/PropertyTabTests.cs | 8 +- .../Windows/Forms/DockPaddingEdgesTests.cs | 2 +- .../Windows/Forms/DragEventArgsTests.cs | 22 +- .../DrawListViewSubItemEventArgsTests.cs | 4 +- .../Windows/Forms/FeatureSupportTests.cs | 2 +- .../System/Windows/Forms/FileDialogTests.cs | 2 +- .../System/Windows/Forms/HelpProviderTests.cs | 26 +-- .../System/Windows/Forms/ImageListTests.cs | 8 +- .../Forms/Layout/TableLayoutSettingsTests.cs | 6 +- .../System/Windows/Forms/LinkAreaTests.cs | 4 +- .../Windows/Forms/ListBindingHelperTests.cs | 22 +- .../System/Windows/Forms/ListBoxTests.cs | 4 +- .../System/Windows/Forms/ListControlTests.cs | 22 +- .../Forms/ListViewGroupCollectionTests.cs | 24 +-- .../Forms/ListViewGroupConverterTests.cs | 24 +-- .../Windows/Forms/ListViewGroupTests.cs | 2 +- .../Forms/ListViewInsertionMarkTests.cs | 12 +- .../System/Windows/Forms/ListViewItemTests.cs | 2 +- .../Forms/ListViewSubItemCollectionTests.cs | 26 +-- .../Windows/Forms/ListViewSubItemTests.cs | 10 +- .../Forms/MaskInputRejectedEventArgsTests.cs | 2 +- .../Windows/Forms/PaddingConverterTests.cs | 2 +- .../System/Windows/Forms/PaddingTests.cs | 4 +- .../Windows/Forms/PropertyManagerTests.cs | 2 +- .../System/Windows/Forms/RowStyleTests.cs | 2 +- .../Windows/Forms/ScrollableControlTests.cs | 8 +- .../SearchForVirtualItemEventArgsTests.cs | 2 +- .../Forms/SpecialFolderEnumConverterTests.cs | 2 +- .../TableLayoutColumnStyleCollectionTests.cs | 4 +- .../TableLayoutRowStyleCollectionTests.cs | 2 +- .../Forms/TableLayoutStyleCollectionTests.cs | 4 +- .../Windows/Forms/TableLayoutStyleTests.cs | 2 +- .../System/Windows/Forms/TimerTests.cs | 12 +- .../ToolStripItemImageRenderEventArgsTests.cs | 6 +- .../ToolStripItemRenderEventArgsTests.cs | 2 +- .../Windows/Forms/ToolStripItemTests.cs | 18 +- .../ToolStripItemTextRenderEventArgsTests.cs | 2 +- .../Windows/Forms/ToolStripPanelTests.cs | 4 +- .../Forms/ToolStripRenderEventArgsTests.cs | 2 +- .../System/Windows/Forms/ToolStripTests.cs | 2 +- .../Forms/TreeViewCancelEventArgsTests.cs | 2 +- .../Windows/Forms/TreeViewEventArgsTests.cs | 2 +- .../Forms/VisualStyles/TextMetricsTests.cs | 42 ++-- .../tests/UnitTests/TextBoxTests.cs | 2 +- .../tests/UnitTests/ThreadContextTests.cs | 194 +++++++++--------- .../tests/UnitTests/TreeViewTests.cs | 2 +- 88 files changed, 511 insertions(+), 506 deletions(-) diff --git a/src/Common/tests/CommonTestHelper.cs b/src/Common/tests/CommonTestHelper.cs index 9e54f1d4dd4..8facde01930 100644 --- a/src/Common/tests/CommonTestHelper.cs +++ b/src/Common/tests/CommonTestHelper.cs @@ -287,7 +287,7 @@ public static TheoryData GetRightToLeftTheoryData() } public static TheoryData GetPointTheoryData() => GetPointTheoryData(TestIncludeType.All); - + public static TheoryData GetPointTheoryData(TestIncludeType includeType) { var data = new TheoryData(); @@ -313,7 +313,7 @@ public static TheoryData GetSizeTheoryData(TestIncludeType includeType) if (!includeType.HasFlag(TestIncludeType.NoPositives)) { data.Add(new Size()); - data.Add(new Size(new Point(1,1))); + data.Add(new Size(new Point(1, 1))); data.Add(new Size(1, 2)); } if (!includeType.HasFlag(TestIncludeType.NoNegatives)) diff --git a/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/DataGridViewCellAccessibleObjectTests.cs b/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/DataGridViewCellAccessibleObjectTests.cs index 3369dd4e79c..a57668adb37 100644 --- a/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/DataGridViewCellAccessibleObjectTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/DataGridViewCellAccessibleObjectTests.cs @@ -16,7 +16,7 @@ public class DataGridViewCellsAccessibleObjectTests public void DataGridViewCellsAccessibleObject_Ctor_Default(RightToLeft rightToLeft) { DataGridView dataGridView = new DataGridView(); - + dataGridView.RightToLeft = rightToLeft; dataGridView.ColumnCount = 4; dataGridView.Width = 85; @@ -29,7 +29,7 @@ public void DataGridViewCellsAccessibleObject_Ctor_Default(RightToLeft rightToLe AccessibleObject rr = dataGridView.AccessibilityObject; //it is necessary to be in time to initialize elements var accCellWidthSum = 0; - for(int i = 0; i < 4; i++) + for (int i = 0; i < 4; i++) { accCellWidthSum += dataGridView.Rows[0].Cells[i].AccessibilityObject.BoundingRectangle.Width; } diff --git a/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/ToolStripItemAccessibleObjectTests.cs b/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/ToolStripItemAccessibleObjectTests.cs index 586baa01b41..05f724284e5 100644 --- a/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/ToolStripItemAccessibleObjectTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/ToolStripItemAccessibleObjectTests.cs @@ -31,7 +31,7 @@ public void ToolStripItemAccessibleObject_Ctor_ToolStripItem() Assert.Equal(AccessibleRole.MenuBar, accessibleObject.Role); Assert.Equal(AccessibleStates.Focusable, accessibleObject.State); } - + [Fact] public void ToolStripItemAccessibleObject_Ctor_NullOwnerItem_ThrowsArgumentNullException() { diff --git a/src/System.Windows.Forms/tests/UnitTests/BindingNavigatorTests.cs b/src/System.Windows.Forms/tests/UnitTests/BindingNavigatorTests.cs index 35fd8a177f6..cc1135a6934 100644 --- a/src/System.Windows.Forms/tests/UnitTests/BindingNavigatorTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/BindingNavigatorTests.cs @@ -19,8 +19,8 @@ public void BindingNavigator_Constructor() Assert.NotNull(bn); } - - [Fact] + + [Fact] public void BindingNavigator_ConstructorBindingSource() { var bindingSource = new BindingSource(); @@ -31,7 +31,7 @@ public void BindingNavigator_ConstructorBindingSource() Assert.NotNull(bn); Assert.Equal(bindingSource, bn.BindingSource); - + // need more thorough binding source testing } @@ -50,7 +50,7 @@ public void BindingNavigator_ConstructorIContainer() Assert.NotNull(bn); mockContainer.Verify(x => x.Add(bn)); } - + [Fact] public void BindingNavigator_ConstructorBool() { @@ -98,7 +98,7 @@ public void BindingNavigator_ConstructorBool() SR.BindingNavigatorDeleteItemText }; - for (var i=0; i @@ -224,7 +224,7 @@ public void CheckedListBox_SetItemCheckStateInvalid(CheckState expected) var box = new CheckedListBox(); box.Items.Add(new CheckBox(), false); - var ex = Assert.Throws(() => box.SetItemCheckState(0,expected)); + var ex = Assert.Throws(() => box.SetItemCheckState(0, expected)); Assert.Equal("value", ex.ParamName); } diff --git a/src/System.Windows.Forms/tests/UnitTests/CommonUnsafeNativeMethodsTests.cs b/src/System.Windows.Forms/tests/UnitTests/CommonUnsafeNativeMethodsTests.cs index 196a5cfbe22..ad9aab7ff16 100644 --- a/src/System.Windows.Forms/tests/UnitTests/CommonUnsafeNativeMethodsTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/CommonUnsafeNativeMethodsTests.cs @@ -9,7 +9,7 @@ namespace System.Windows.Forms.Tests { public class CommonUnsafeNativeMethodsTests { - + /*/// /// Data for the TryFindDpiAwarenessContextsEqual test diff --git a/src/System.Windows.Forms/tests/UnitTests/DomainUpDownTests.cs b/src/System.Windows.Forms/tests/UnitTests/DomainUpDownTests.cs index cf958622291..6f91d1a11f3 100644 --- a/src/System.Windows.Forms/tests/UnitTests/DomainUpDownTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/DomainUpDownTests.cs @@ -12,7 +12,7 @@ public class DomainUpDownTests public void DomainUpDown_Constructor() { var underTest = GetNewDomainUpDown(); - + Assert.NotNull(underTest); Assert.False(underTest.AllowDrop); Assert.False(underTest.Wrap); @@ -31,7 +31,7 @@ public void DomainUpDown_SelectedIndexGetSet(int indexToSet, int indexAfterSet, Assert.Equal(indexAfterSet, underTest.SelectedIndex); Assert.Equal(value, underTest.SelectedItem); } - + [Fact] public void DomainUpDown_SelectedIndex_ArgumentOutOfRangeException() { @@ -108,7 +108,8 @@ public void DomainUpDown_DownButton(int index, int newIndex) Assert.Equal(expected, actual); } - private DomainUpDown GetNewDomainUpDown(bool sorted = false) { + private DomainUpDown GetNewDomainUpDown(bool sorted = false) + { var domainUpDown = new DomainUpDown(); domainUpDown.Sorted = sorted; var items = domainUpDown.Items; diff --git a/src/System.Windows.Forms/tests/UnitTests/DpiHelperTests.cs b/src/System.Windows.Forms/tests/UnitTests/DpiHelperTests.cs index b595acc14fc..4191201169c 100644 --- a/src/System.Windows.Forms/tests/UnitTests/DpiHelperTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/DpiHelperTests.cs @@ -30,7 +30,7 @@ public void DpiHelper_LogicalToDeviceUnits(int value) [CommonMemberData(nameof(CommonTestHelper.GetSizeTheoryData))] public void DpiHelper_LogicalToDeviceUnitsSize(Size value) { - var expected = new Size ((int)Math.Round(value.Width * (DpiHelper.DeviceDpi / DpiHelper.LogicalDpi)), + var expected = new Size((int)Math.Round(value.Width * (DpiHelper.DeviceDpi / DpiHelper.LogicalDpi)), (int)Math.Round(value.Height * (DpiHelper.DeviceDpi / DpiHelper.LogicalDpi))); Assert.Equal(expected, DpiHelper.LogicalToDeviceUnits(value)); diff --git a/src/System.Windows.Forms/tests/UnitTests/ErrorProviderTests.cs b/src/System.Windows.Forms/tests/UnitTests/ErrorProviderTests.cs index e744fa4f469..0627649f073 100644 --- a/src/System.Windows.Forms/tests/UnitTests/ErrorProviderTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/ErrorProviderTests.cs @@ -18,7 +18,7 @@ public void ErrorProvider_Constructor() Assert.NotNull(ep); Assert.NotNull(ep.Icon); } - + [Fact] public void ErrorProvider_ConstructorContainerControl() { @@ -29,7 +29,7 @@ public void ErrorProvider_ConstructorContainerControl() Assert.NotNull(ep); Assert.NotNull(ep.Icon); } - + [Fact] public void ErrorProvider_ConstructorIContainer() { diff --git a/src/System.Windows.Forms/tests/UnitTests/LinkLabelTests.cs b/src/System.Windows.Forms/tests/UnitTests/LinkLabelTests.cs index dd96dc6d5ec..d5fdcbcc9ea 100644 --- a/src/System.Windows.Forms/tests/UnitTests/LinkLabelTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/LinkLabelTests.cs @@ -14,7 +14,7 @@ public void LinkLabel_Constructor() var label = new LinkLabel(); Assert.NotNull(label); - Assert.True(label.LinkArea.IsEmpty); + Assert.True(label.LinkArea.IsEmpty); Assert.Equal(0, label.LinkArea.Start); Assert.Equal(0, label.LinkArea.Length); } diff --git a/src/System.Windows.Forms/tests/UnitTests/MenuItemCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/MenuItemCollectionTests.cs index f0a661ea937..b5cb415fdc4 100644 --- a/src/System.Windows.Forms/tests/UnitTests/MenuItemCollectionTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/MenuItemCollectionTests.cs @@ -48,7 +48,7 @@ public void MenuItemCollection_Add_String_Success(string caption, string expecte public static IEnumerable Add_StringEventHandler_TestData() { - EventHandler onClick = (sender, e) => {}; + EventHandler onClick = (sender, e) => { }; yield return new object[] { null, null, string.Empty }; yield return new object[] { string.Empty, onClick, string.Empty }; yield return new object[] { "caption", onClick, "caption" }; @@ -152,7 +152,7 @@ public void MenuItemCollection_Add_AlreadyInSameCollection_Success() var collection = new Menu.MenuItemCollection(parent); collection.Add(menuItem1); collection.Add(menuItem2); - + Assert.Equal(0, collection.Add(0, menuItem2)); Assert.Equal(2, collection.Count); Assert.Same(menuItem2, collection[0]); @@ -391,7 +391,7 @@ public void MenuItemCollection_CopyTo_NotEmpty_Success() collection.Add(menuItem); var array = new object[] { 1, 2, 3 }; collection.CopyTo(array, 1); - Assert.Equal(new object[] { 1, menuItem, 3}, array); + Assert.Equal(new object[] { 1, menuItem, 3 }, array); } [Fact] @@ -401,7 +401,7 @@ public void MenuItemCollection_CopyTo_Empty_Nop() var collection = new Menu.MenuItemCollection(menu); var array = new object[] { 1, 2, 3 }; collection.CopyTo(array, 1); - Assert.Equal(new object[] { 1, 2, 3}, array); + Assert.Equal(new object[] { 1, 2, 3 }, array); } public static IEnumerable Contains_TestData() @@ -444,7 +444,7 @@ public void MenuItemCollection_Contains_IListNotMenuItem_ReturnsMinusOne() [InlineData("noSuchName", false)] public void MenuItemCollection_ContainsKey_Invoke_ReturnsExpected(string key, bool expected) { - var menu = new SubMenu(new MenuItem[] { new MenuItem { Name = "name" }}); + var menu = new SubMenu(new MenuItem[] { new MenuItem { Name = "name" } }); var collection = new Menu.MenuItemCollection(menu); Assert.Equal(expected, collection.ContainsKey(key)); } @@ -467,7 +467,7 @@ public static IEnumerable Find_TestData() yield return new object[] { new MenuItem[] { new MenuItem { Name = "name" } }, "noSuchName", false, new MenuItem[0] }; yield return new object[] { new MenuItem[] { new MenuItem("text", new MenuItem[] { new MenuItem { Name = "name2" } }) { Name = "name" }, }, "noSuchName", true, new MenuItem[0] }; yield return new object[] { new MenuItem[] { new MenuItem("text", new MenuItem[] { new MenuItem { Name = "name2" } }) { Name = "name" }, }, "noSuchName", false, new MenuItem[0] }; - + var menuItemChild = new MenuItem { Name = "name" }; yield return new object[] { new MenuItem[] { new MenuItem("text", new MenuItem[] { menuItemChild }) }, "name", true, new MenuItem[] { menuItemChild } }; yield return new object[] { new MenuItem[] { new MenuItem("text", new MenuItem[] { new MenuItem { Name = "name" } }) }, "name", false, new MenuItem[0] }; @@ -532,7 +532,7 @@ public void MenuItemCollection_IndexOf_IListNotMenuItem_ReturnsMinusOne() [InlineData("noSuchName", -1)] public void MenuItemCollection_IndexOfKey_Invoke_ReturnsExpected(string key, int expected) { - var menu = new SubMenu(new MenuItem[] { new MenuItem { Name = "name" }}); + var menu = new SubMenu(new MenuItem[] { new MenuItem { Name = "name" } }); var collection = new Menu.MenuItemCollection(menu); Assert.Equal(expected, collection.IndexOfKey(key)); @@ -703,7 +703,7 @@ public void MenuItemCollection_RemoveAt_Invoke_Success() var menu = new SubMenu(new MenuItem[] { menuItem }); var collection = new Menu.MenuItemCollection(menu); collection.RemoveAt(0); - + Assert.Empty(collection); Assert.Null(menuItem.Parent); Assert.Equal(-1, menuItem.Index); diff --git a/src/System.Windows.Forms/tests/UnitTests/MenuItemTests.cs b/src/System.Windows.Forms/tests/UnitTests/MenuItemTests.cs index 1bf4d763f81..f116ffbf804 100644 --- a/src/System.Windows.Forms/tests/UnitTests/MenuItemTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/MenuItemTests.cs @@ -703,7 +703,7 @@ public void MenuItem_ShowShortcut_Set_GetReturnsExpected(bool value) }; Assert.Equal(value, menuItem.ShowShortcut); } - + [Theory] [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] public void MenuItem_ShowShortcut_SetCreated_GetReturnsExpected(bool value) @@ -736,7 +736,7 @@ public void MenuItem_Shortcut_Set_GetReturnsExpected(Shortcut value) }; Assert.Equal(value, menuItem.Shortcut); } - + [Theory] [InlineData(Shortcut.None)] [InlineData(Shortcut.Ctrl0)] @@ -1098,7 +1098,7 @@ public void MenuItem_OnPopup_InvokeWithChildren_Success(bool mdiList) public void MenuItem_OnPopup_MdiChildrenWithoutParent_DoesNotAddSeparator() { var menuItem = new SubMenuItem("text", new MenuItem[] { new MenuItem("child") }) { MdiList = true }; - + menuItem.OnPopup(null); Assert.Equal(new string[] { "child" }, menuItem.MenuItems.Cast().Select(m => m.Text)); @@ -1141,7 +1141,7 @@ public static IEnumerable OnPopup_MdiChildren_TestData() formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form9" }); formWithManyMdiChildrenClient.Controls.Add(new Form { MdiParent = formWithManyMdiChildren, Visible = true, Text = "Form10" }); yield return new object[] { new SubMenuItem("text", new MenuItem[] { new MenuItem("child") }) { MdiList = true }, formWithManyMdiChildren.Menu, new string[] { "child", "-", "&1 Form1", "&2 Form1", "&3 Form2", "&4 Form2", "&5 Form3", "&6 Form3", "&7 Form4", "&8 Form4", "&9 Form10", "&10 Form10", "&More Windows..." } }; - + var formWithActiveMdiChildren = new SubForm { Menu = new MainMenu(), Visible = true }; var formWithActiveMdiChildrenClient = new MdiClient(); formWithActiveMdiChildren.Controls.Add(formWithActiveMdiChildrenClient); diff --git a/src/System.Windows.Forms/tests/UnitTests/MenuTests.cs b/src/System.Windows.Forms/tests/UnitTests/MenuTests.cs index 0c8b9c7ef6a..6139c3af4c2 100644 --- a/src/System.Windows.Forms/tests/UnitTests/MenuTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/MenuTests.cs @@ -19,7 +19,7 @@ public static IEnumerable Ctor_MenuItemArray_TestData() yield return new object[] { new MenuItem[0], false }; yield return new object[] { new MenuItem[] { new MenuItem() }, true }; } - + [Theory] [MemberData(nameof(Ctor_MenuItemArray_TestData))] public void Menu_Ctor_MenuItemArray(MenuItem[] items, bool expectedIsParent) @@ -140,7 +140,7 @@ public void Menu_Name_GetWithSite_ReturnsExpected(string name, string expected) { var menu = new SubMenu(new MenuItem[0]) { - Site = Mock.Of(s => s.Name ==name) + Site = Mock.Of(s => s.Name == name) }; Assert.Same(expected, menu.Name); } @@ -184,7 +184,7 @@ public static IEnumerable MdiListItem_TestData() yield return new object[] { new MenuItem[] { new MenuItem("parent", new MenuItem[] { listItem2 }) }, listItem2 }; yield return new object[] { new MenuItem[] { new MenuItem("parent", new MenuItem[] { new MenuItem() }) }, null }; } - + [Theory] [MemberData(nameof(MdiListItem_TestData))] public void Menu_MdiListItem_Get_ReturnsExpected(MenuItem[] items, MenuItem expected) @@ -296,7 +296,7 @@ public static IEnumerable ProcessCmdKey_MenuItemParent_TestData() var disabledParentChild = new MenuItem { Shortcut = Shortcut.CtrlA }; var disabledParent = new MenuItem("text", new MenuItem[] { disabledParentChild }) { Enabled = false }; - yield return new object[] { disabledParent, disabledParentChild, false, 0, 0, 0, 0 }; + yield return new object[] { disabledParent, disabledParentChild, false, 0, 0, 0, 0 }; } [Theory] diff --git a/src/System.Windows.Forms/tests/UnitTests/SRCategoryAttributeTests.cs b/src/System.Windows.Forms/tests/UnitTests/SRCategoryAttributeTests.cs index 5902759ee79..42d464fb35b 100644 --- a/src/System.Windows.Forms/tests/UnitTests/SRCategoryAttributeTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/SRCategoryAttributeTests.cs @@ -12,7 +12,7 @@ public class SRCategoryAttributeTests public void VerifyCategoryForValidCategoryAttribute() { SRCategoryAttribute srCategoryAttribute = new SRCategoryAttribute(nameof(SR.CatAccessibility)); - Assert.True(string.Compare(srCategoryAttribute.Category, SR.CatAccessibility, StringComparison.Ordinal) == 0); + Assert.True(string.Compare(srCategoryAttribute.Category, SR.CatAccessibility, StringComparison.Ordinal) == 0); } [Fact] diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Drawing/Design/PaintValueEventArgsTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Drawing/Design/PaintValueEventArgsTests.cs index fee6b8b6301..939398a777c 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Drawing/Design/PaintValueEventArgsTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Drawing/Design/PaintValueEventArgsTests.cs @@ -2,30 +2,30 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. - using Xunit; +using Xunit; - namespace System.Drawing.Design -{ - public class PaintValueEventArgsTests - { - [Fact] - public void Ctor_Throws_ArgumentNullException() - { - AssertExtensions.Throws("graphics", () => new PaintValueEventArgs(null, new object(), null, Rectangle.Empty)); +namespace System.Drawing.Design +{ + public class PaintValueEventArgsTests + { + [Fact] + public void Ctor_Throws_ArgumentNullException() + { + AssertExtensions.Throws("graphics", () => new PaintValueEventArgs(null, new object(), null, Rectangle.Empty)); } [Fact] - public void Ctor_PropertiesAssignedCorrectly() - { - using (var bm = new Bitmap(20, 20)) - using (var graphics = Graphics.FromImage(bm)) - { - var paintValueEventArgs = new PaintValueEventArgs(null, bm, graphics, Rectangle.Empty); - Assert.Null(paintValueEventArgs.Context); - Assert.Equal(bm, paintValueEventArgs.Value); - Assert.Equal(graphics, paintValueEventArgs.Graphics); - Assert.Equal(Rectangle.Empty, Rectangle.Empty); - } - } - } + public void Ctor_PropertiesAssignedCorrectly() + { + using (var bm = new Bitmap(20, 20)) + using (var graphics = Graphics.FromImage(bm)) + { + var paintValueEventArgs = new PaintValueEventArgs(null, bm, graphics, Rectangle.Empty); + Assert.Null(paintValueEventArgs.Context); + Assert.Equal(bm, paintValueEventArgs.Value); + Assert.Equal(graphics, paintValueEventArgs.Graphics); + Assert.Equal(Rectangle.Empty, Rectangle.Empty); + } + } + } } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Drawing/Design/PropertyValueUIItemTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Drawing/Design/PropertyValueUIItemTests.cs index f7034090d22..139aaedf777 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Drawing/Design/PropertyValueUIItemTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Drawing/Design/PropertyValueUIItemTests.cs @@ -2,38 +2,38 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. - using System.ComponentModel; -using System.IO; -using Xunit; +using System.ComponentModel; +using System.IO; +using Xunit; - namespace System.Drawing.Design.Tests -{ - public class PropertyValueUIItemTests - { - private void Dummy_PropertyValueUIItemInvokeHandler(ITypeDescriptorContext context, PropertyDescriptor propDesc, PropertyValueUIItem invokedItem) { } +namespace System.Drawing.Design.Tests +{ + public class PropertyValueUIItemTests + { + private void Dummy_PropertyValueUIItemInvokeHandler(ITypeDescriptorContext context, PropertyDescriptor propDesc, PropertyValueUIItem invokedItem) { } [Fact] - public void Ctor_Throws_ArgumentNullException() - { - AssertExtensions.Throws("uiItemImage", () => new PropertyValueUIItem(null, Dummy_PropertyValueUIItemInvokeHandler, "toolTip")); + public void Ctor_Throws_ArgumentNullException() + { + AssertExtensions.Throws("uiItemImage", () => new PropertyValueUIItem(null, Dummy_PropertyValueUIItemInvokeHandler, "toolTip")); - using (Image img = Image.FromFile(Path.Combine("bitmaps", "nature24bits.jpg"))) - { - AssertExtensions.Throws("handler", () => new PropertyValueUIItem(img, null, "toolTip")); - } + using (Image img = Image.FromFile(Path.Combine("bitmaps", "nature24bits.jpg"))) + { + AssertExtensions.Throws("handler", () => new PropertyValueUIItem(img, null, "toolTip")); + } } [Fact] - public void Ctor_PropertiesAssignedCorrectly() - { - string toolTip = "Custom toolTip"; - using (Image img = Image.FromFile(Path.Combine("bitmaps", "nature24bits.jpg"))) - { - var propertyValue = new PropertyValueUIItem(img, Dummy_PropertyValueUIItemInvokeHandler, toolTip); - Assert.Equal(img, propertyValue.Image); - Assert.Equal(Dummy_PropertyValueUIItemInvokeHandler, propertyValue.InvokeHandler); - Assert.Equal(toolTip, propertyValue.ToolTip); - } - } - } + public void Ctor_PropertiesAssignedCorrectly() + { + string toolTip = "Custom toolTip"; + using (Image img = Image.FromFile(Path.Combine("bitmaps", "nature24bits.jpg"))) + { + var propertyValue = new PropertyValueUIItem(img, Dummy_PropertyValueUIItemInvokeHandler, toolTip); + Assert.Equal(img, propertyValue.Image); + Assert.Equal(Dummy_PropertyValueUIItemInvokeHandler, propertyValue.InvokeHandler); + Assert.Equal(toolTip, propertyValue.ToolTip); + } + } + } } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ApplicationTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ApplicationTests.cs index 936fab7da56..f0f420a60bf 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ApplicationTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ApplicationTests.cs @@ -13,7 +13,7 @@ public class ApplicationTests public void Application_EnableVisualStyles_GetUseVisualStyles_ReturnsTrue() { Application.EnableVisualStyles(); - Assert.True(Application.UseVisualStyles, "New Visual Styles will not be applied on Winforms app. This is a high priority bug and must be looked into"); + Assert.True(Application.UseVisualStyles, "New Visual Styles will not be applied on Winforms app. This is a high priority bug and must be looked into"); } [Fact] diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BaseCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BaseCollectionTests.cs index 95b2b60f384..fe2008ab7e1 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BaseCollectionTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BaseCollectionTests.cs @@ -25,7 +25,7 @@ public void Count_GetWithList_ReturnsExpected() var collection = new SubCollection(new ArrayList { 1, 2, 3 }); Assert.Equal(3, collection.Count); } - + [Fact] public void Count_GetDefault_ThrowsNullReferenceException() { @@ -41,7 +41,7 @@ public void CopyTo_InvokeWithList_Success() collection.CopyTo(array, 1); Assert.Equal(new object[] { 0, 1, 2, 3, 4 }, array); } - + [Fact] public void CopyTo_InvokeDefault_ThrowsNullReferenceException() { @@ -57,7 +57,7 @@ public void GetEnumerator_InvokeWithList_Success() Assert.True(enumerator.MoveNext()); Assert.Equal(1, enumerator.Current); } - + [Fact] public void GetEnumerator_InvokeDefault_ThrowsNullReferenceException() { diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingContextTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingContextTests.cs index ff620eff0a5..adeed9b1ff3 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingContextTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingContextTests.cs @@ -429,7 +429,7 @@ public void BindingContext_Item_GetNoSuchDataSource_AddsToCollection() public void BindingContext_Item_GetIListDataSource_AddsToCollection() { var context = new BindingContext(); - var dataSource = new List { 1, 2, 3}; + var dataSource = new List { 1, 2, 3 }; CurrencyManager manager = Assert.IsType(context[dataSource]); Assert.Same(dataSource, manager.List); Assert.Equal(1, manager.Current); @@ -443,7 +443,7 @@ public void BindingContext_Item_GetIListDataSource_AddsToCollection() public void BindingContext_Item_GetArrayDataSource_AddsToCollection() { var context = new BindingContext(); - var dataSource = new int[] { 1, 2, 3}; + var dataSource = new int[] { 1, 2, 3 }; CurrencyManager manager = Assert.IsType(context[dataSource]); Assert.Same(dataSource, manager.List); Assert.Equal(1, manager.Current); @@ -457,7 +457,7 @@ public void BindingContext_Item_GetArrayDataSource_AddsToCollection() public void BindingContext_Item_GetIListSourceDataSource_AddsToCollection() { var context = new BindingContext(); - var dataSource = new List { 1, 2, 3}; + var dataSource = new List { 1, 2, 3 }; var mockIListSource = new Mock(MockBehavior.Strict); mockIListSource .Setup(s => s.GetList()) @@ -584,7 +584,7 @@ public void BindingContext_Item_GetNoSuchDataSourceNoSuchDataMember_ThrowsArgume public void BindingContext_Item_GetIListWithDataMemberReturningIList_AddsToCollection() { var context = new BindingContext(); - var list = new List { 1, 2, 3}; + var list = new List { 1, 2, 3 }; var dataSource = new IListDataSource(); dataSource.Property = list; @@ -601,7 +601,7 @@ public void BindingContext_Item_GetIListWithDataMemberReturningIList_AddsToColle public void BindingContext_Item_GetIListWithDataMemberReturningNonIList_AddsToCollection() { var context = new BindingContext(); - var list = new List { 1, 2, 3}; + var list = new List { 1, 2, 3 }; var dataSource = new ObjectDataSource(); dataSource.Property = list; @@ -617,7 +617,7 @@ public void BindingContext_Item_GetIListWithDataMemberReturningNonIList_AddsToCo public void BindingContext_Item_GetArrayWithDataMember_AddsToCollection() { var context = new BindingContext(); - var list = new int[] { 1, 2, 3}; + var list = new int[] { 1, 2, 3 }; var dataSource = new IListDataSource(); dataSource.Property = list; @@ -634,7 +634,7 @@ public void BindingContext_Item_GetArrayWithDataMember_AddsToCollection() public void BindingContext_Item_GetIListSourceDataSourceWithDataMemberReturningIList_AddsToCollection() { var context = new BindingContext(); - var list = new List { 1, 2, 3}; + var list = new List { 1, 2, 3 }; var dataSource = new IListDataSource(); var mockIListSource = new Mock(MockBehavior.Strict); mockIListSource @@ -656,7 +656,7 @@ public void BindingContext_Item_GetIListSourceDataSourceWithDataMemberReturningI public void BindingContext_Item_GetIListSourceDataSourceWithDataMemberReturningNonIList_AddsToCollection() { var context = new BindingContext(); - var list = new List { 1, 2, 3}; + var list = new List { 1, 2, 3 }; var dataSource = new IListSourceDataSource(); var mockIListSource = new Mock(MockBehavior.Strict); mockIListSource diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingManagerBaseTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingManagerBaseTests.cs index 2e0f47a484a..ce3214871d0 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingManagerBaseTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingManagerBaseTests.cs @@ -23,7 +23,7 @@ public void Bindings_Add_Success() var manager = new PropertyManager(); BindingsCollection collection = manager.Bindings; var binding = new Binding(null, new object(), "member"); - + collection.Add(binding); Assert.Same(binding, Assert.Single(collection)); Assert.Same(manager, binding.BindingManagerBase); @@ -67,7 +67,7 @@ public void Bindings_Clear_Success() var manager = new PropertyManager(); BindingsCollection collection = manager.Bindings; var binding = new Binding(null, new object(), "member"); - + collection.Add(binding); Assert.Same(binding, Assert.Single(collection)); Assert.Same(manager, binding.BindingManagerBase); @@ -87,7 +87,7 @@ public void Bindings_Remove_Success() var manager = new PropertyManager(); BindingsCollection collection = manager.Bindings; var binding = new Binding(null, new object(), "member"); - + collection.Add(binding); Assert.Same(binding, Assert.Single(collection)); Assert.Same(manager, binding.BindingManagerBase); @@ -145,7 +145,7 @@ public void Bindings_RemoveAt_Success() var manager = new PropertyManager(); BindingsCollection collection = manager.Bindings; var binding = new Binding(null, new object(), "member"); - + collection.Add(binding); Assert.Same(binding, Assert.Single(collection)); Assert.Same(manager, binding.BindingManagerBase); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingTests.cs index e5deaa114b1..38b5a93bb62 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingTests.cs @@ -73,7 +73,7 @@ public void Binding_Ctor_String_Object_String_Bool(string propertyName, object d public static IEnumerable Ctor_String_Object_String_Bool_DataSourceUpdateMode_TestData() { yield return new object[] { null, null, null, true, DataSourceUpdateMode.OnValidation }; - yield return new object[] { string.Empty, new object(), string.Empty, true, DataSourceUpdateMode.OnValidation -1 }; + yield return new object[] { string.Empty, new object(), string.Empty, true, DataSourceUpdateMode.OnValidation - 1 }; yield return new object[] { "propertyName", new object(), "dataMember", false, DataSourceUpdateMode.Never }; yield return new object[] { "propertyName", new object(), "dataMember.subDataMember", false, DataSourceUpdateMode.Never + 1 }; } @@ -102,7 +102,7 @@ public void Binding_Ctor_String_Object_String_Bool_DataSourceUpdateMode(string p public static IEnumerable Ctor_String_Object_String_Bool_DataSourceUpdateMode_Object_TestData() { yield return new object[] { null, null, null, true, DataSourceUpdateMode.OnValidation, null }; - yield return new object[] { string.Empty, new object(), string.Empty, true, DataSourceUpdateMode.OnValidation -1, DBNull.Value }; + yield return new object[] { string.Empty, new object(), string.Empty, true, DataSourceUpdateMode.OnValidation - 1, DBNull.Value }; yield return new object[] { "propertyName", new object(), "dataMember", false, DataSourceUpdateMode.Never, new object() }; yield return new object[] { "propertyName", new object(), "dataMember.subDataMember", false, DataSourceUpdateMode.Never + 1, new object() }; } @@ -131,7 +131,7 @@ public void Binding_Ctor_String_Object_String_Bool_DataSourceUpdateMode_Object(s public static IEnumerable Ctor_String_Object_String_Bool_DataSourceUpdateMode_Object_String_TestData() { yield return new object[] { null, null, null, true, DataSourceUpdateMode.OnValidation, null, null }; - yield return new object[] { string.Empty, new object(), string.Empty, true, DataSourceUpdateMode.OnValidation -1, DBNull.Value, string.Empty }; + yield return new object[] { string.Empty, new object(), string.Empty, true, DataSourceUpdateMode.OnValidation - 1, DBNull.Value, string.Empty }; yield return new object[] { "propertyName", new object(), "dataMember", false, DataSourceUpdateMode.Never, new object(), "formatString" }; yield return new object[] { "propertyName", new object(), "dataMember.subDataMember", false, DataSourceUpdateMode.Never + 1, new object(), "formatString" }; } @@ -160,7 +160,7 @@ public void Binding_Ctor_String_Object_String_Bool_DataSourceUpdateMode_Object_S public static IEnumerable Ctor_String_Object_String_Bool_DataSourceUpdateMode_Object_String_IFormatProvider_TestData() { yield return new object[] { null, null, null, true, DataSourceUpdateMode.OnValidation, null, null, null }; - yield return new object[] { string.Empty, new object(), string.Empty, true, DataSourceUpdateMode.OnValidation -1, DBNull.Value, string.Empty, CultureInfo.CurrentCulture }; + yield return new object[] { string.Empty, new object(), string.Empty, true, DataSourceUpdateMode.OnValidation - 1, DBNull.Value, string.Empty, CultureInfo.CurrentCulture }; yield return new object[] { "propertyName", new object(), "dataMember", false, DataSourceUpdateMode.Never, new object(), "formatString", CultureInfo.InvariantCulture }; yield return new object[] { "propertyName", new object(), "dataMember.subDataMember", false, DataSourceUpdateMode.Never + 1, new object(), "formatString", CultureInfo.CurrentCulture }; } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingsCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingsCollectionTests.cs index 0fe0b8f8269..d76706d3ac6 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingsCollectionTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingsCollectionTests.cs @@ -83,7 +83,7 @@ public void Add_InvokeWithCollectionChanging_CallsHandler() public void Add_NullDataBinding_ThrowsArgumentNullException() { var collection = new BindingsCollection(); - Assert.Throws("dataBinding", () => collection.Add(null)); + Assert.Throws("dataBinding", () => collection.Add(null)); } [Fact] @@ -149,7 +149,7 @@ public void AddCore_InvokeWithCollectionChanging_DoesNotCallHandler() public void AddCore_NullDataBinding_ThrowsArgumentNullException() { var collection = new SubBindingsCollection(); - Assert.Throws("dataBinding", () => collection.AddCore(null)); + Assert.Throws("dataBinding", () => collection.AddCore(null)); } [Fact] diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ColumnHeaderCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ColumnHeaderCollectionTests.cs index 1daf715546d..ae0c8a28d90 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ColumnHeaderCollectionTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ColumnHeaderCollectionTests.cs @@ -112,7 +112,7 @@ public void ColumnHeaderCollection_Item_GetString_ReturnsExpected(string key, in header2.Name = "text"; collection.Add(header1); collection.Add(header2); - + Assert.Equal(expectedIndex != -1 ? collection[expectedIndex] : null, collection[key]); } @@ -520,7 +520,7 @@ public void ColumnHeaderCollection_Contains_Invoke_ReturnsExpected() var collection = new ListView.ColumnHeaderCollection(listView); var header = new ColumnHeader(); collection.Add(header); - + Assert.True(collection.Contains(header)); Assert.False(collection.Contains(new ColumnHeader())); Assert.False(collection.Contains(null)); @@ -531,7 +531,7 @@ public void ColumnHeaderCollection_Contains_Empty_ReturnsFalse() { var listView = new ListView(); var collection = new ListView.ColumnHeaderCollection(listView); - + Assert.False(collection.Contains(new ColumnHeader())); Assert.False(collection.Contains(null)); } @@ -553,7 +553,7 @@ public void ColumnHeaderCollection_ContainsKey_Invoke_ReturnsExpected(string key header2.Name = "text"; collection.Add(header1); collection.Add(header2); - + Assert.Equal(expected, collection.ContainsKey(key)); } @@ -562,7 +562,7 @@ public void ColumnHeaderCollection_ContainsKey_Empty_ReturnsFalse() { var listView = new ListView(); var collection = new ListView.ColumnHeaderCollection(listView); - + Assert.False(collection.ContainsKey("text")); Assert.False(collection.ContainsKey(null)); } @@ -574,7 +574,7 @@ public void ColumnHeaderCollection_IListContains_Invoke_ReturnsExpected() IList collection = new ListView.ColumnHeaderCollection(listView); var header = new ColumnHeader(); collection.Add(header); - + Assert.True(collection.Contains(header)); Assert.False(collection.Contains(new ColumnHeader())); Assert.False(collection.Contains(new object())); @@ -586,7 +586,7 @@ public void ColumnHeaderCollection_IListContains_Empty_ReturnsFalse() { var listView = new ListView(); IList collection = new ListView.ColumnHeaderCollection(listView); - + Assert.False(collection.Contains(new ColumnHeader())); Assert.False(collection.Contains(new object())); Assert.False(collection.Contains(null)); @@ -599,7 +599,7 @@ public void ColumnHeaderCollection_IndexOf_Invoke_ReturnsExpected() var collection = new ListView.ColumnHeaderCollection(listView); var header = new ColumnHeader(); collection.Add(header); - + Assert.Equal(0, collection.IndexOf(header)); Assert.Equal(-1, collection.IndexOf(new ColumnHeader())); Assert.Equal(-1, collection.IndexOf(null)); @@ -610,7 +610,7 @@ public void ColumnHeaderCollection_IndexOf_Empty_ReturnsFalse() { var listView = new ListView(); var collection = new ListView.ColumnHeaderCollection(listView); - + Assert.Equal(-1, collection.IndexOf(new ColumnHeader())); Assert.Equal(-1, collection.IndexOf(null)); } @@ -632,7 +632,7 @@ public void ColumnHeaderCollection_IndexOfKey_Invoke_ReturnsExpected(string key, header2.Name = "text"; collection.Add(header1); collection.Add(header2); - + Assert.Equal(expected, collection.IndexOfKey(key)); // Call again to validate caching behaviour. @@ -645,7 +645,7 @@ public void ColumnHeaderCollection_IndexOfKey_Empty_ReturnsFalse() { var listView = new ListView(); var collection = new ListView.ColumnHeaderCollection(listView); - + Assert.Equal(-1, collection.IndexOfKey("text")); Assert.Equal(-1, collection.IndexOf(null)); } @@ -657,7 +657,7 @@ public void ColumnHeaderCollection_IListIndexOf_Invoke_ReturnsExpected() IList collection = new ListView.ColumnHeaderCollection(listView); var header = new ColumnHeader(); collection.Add(header); - + Assert.Equal(0, collection.IndexOf(header)); Assert.Equal(-1, collection.IndexOf(new ColumnHeader())); Assert.Equal(-1, collection.IndexOf(new object())); @@ -669,7 +669,7 @@ public void ColumnHeaderCollection_IListIndexOf_Empty_ReturnsMinusOne() { var listView = new ListView(); IList collection = new ListView.ColumnHeaderCollection(listView); - + Assert.Equal(-1, collection.IndexOf(new ColumnHeader())); Assert.Equal(-1, collection.IndexOf(new object())); Assert.Equal(-1, collection.IndexOf(null)); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ColumnHeaderTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ColumnHeaderTests.cs index 43821c04395..6beb69d29c8 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ColumnHeaderTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ColumnHeaderTests.cs @@ -641,7 +641,7 @@ public void ColumnHeader_Width_GetWithListView_GetReturnsExpected() var listView = new ListView(); var header = new ColumnHeader(); listView.Columns.Add(header); - + Assert.Equal(60, header.Width); } @@ -652,7 +652,7 @@ public void ColumnHeader_Width_GetWithListViewWithHandle_GetReturnsExpected() var header = new ColumnHeader(); listView.Columns.Add(header); Assert.NotEqual(IntPtr.Zero, listView.Handle); - + Assert.Equal(60, header.Width); } @@ -666,7 +666,7 @@ public void ColumnHeader_Width_GetWithListViewWithHandleWithDetails_GetReturnsEx var header = new ColumnHeader(); listView.Columns.Add(header); Assert.NotEqual(IntPtr.Zero, listView.Handle); - + Assert.Equal(header.Width, header.Width); } @@ -829,7 +829,7 @@ public void ColumnHeader_Dispose_WithListView_Success() header.Dispose(); Assert.Empty(listView.Columns); } - + [Theory] [CommonMemberData(nameof(CommonTestHelper.GetStringWithNullTheoryData))] public void ColumnHeader_ToString_Invoke_ReturnsExpected(string value) diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ColumnStyleTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ColumnStyleTests.cs index 57f07b8db4b..ed8db832612 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ColumnStyleTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ColumnStyleTests.cs @@ -65,7 +65,7 @@ public void ColumnStyle_Width_SetOwned_GetReturnsExpected(float value) var panel = new TableLayoutPanel(); var style = new ColumnStyle(); panel.LayoutSettings.RowStyles.Add(style); - + style.Width = value; Assert.Equal(value, style.Width); } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/CommonDialogTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/CommonDialogTests.cs index 0901e238295..23907e51941 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/CommonDialogTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/CommonDialogTests.cs @@ -74,7 +74,7 @@ public static IEnumerable HookProc_TestData() { yield return new object[] { Interop.WindowMessages.WM_INITDIALOG }; yield return new object[] { Interop.WindowMessages.WM_SETFOCUS }; - + const int CDM_SETDEFAULTFOCUS = Interop.WindowMessages.WM_USER + 0x51; yield return new object[] { CDM_SETDEFAULTFOCUS }; @@ -163,7 +163,7 @@ public void OwnerWndProc_HelpMessage_CallsHelpRequest() var dialog = new SubCommonDialog(); FieldInfo field = typeof(CommonDialog).GetField("s_helpMsg", BindingFlags.NonPublic | BindingFlags.Static); Assert.NotNull(field); - + int callCount = 0; EventHandler handler = (sender, e) => { @@ -183,7 +183,7 @@ public void OwnerWndProc_NonHelpMessage_DoesNotCallHelpRequest() var dialog = new SubCommonDialog(); FieldInfo field = typeof(CommonDialog).GetField("s_helpMsg", BindingFlags.NonPublic | BindingFlags.Static); Assert.NotNull(field); - + int callCount = 0; EventHandler handler = (sender, e) => { diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ContainerControlTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ContainerControlTests.cs index 0f586964ce8..6f5d11b4c82 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ContainerControlTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ContainerControlTests.cs @@ -106,7 +106,7 @@ public void AutoScaleDimensions_SetWithChildren_GetReturnsExpected(Size value) var child = new Control(); var control = new ContainerControl(); control.Controls.Add(child); - + control.AutoScaleDimensions = value; Assert.Equal(value, control.AutoScaleDimensions); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlBindingsCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlBindingsCollectionTests.cs index e3f12ee5a37..674932bd2cc 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlBindingsCollectionTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlBindingsCollectionTests.cs @@ -60,7 +60,7 @@ public void Add_Binding_Success(Binding binding) { var control = new Control(); var collection = new ControlBindingsCollection(control); - + collection.Add(binding); Assert.Same(binding, Assert.Single(collection)); Assert.Same(control, binding.BindableComponent); @@ -107,7 +107,7 @@ public void Add_ControlBindings_Success() var binding3 = new Binding(null, 1, "dataMember"); var binding4 = new Binding("", 1, "dataMember"); var binding5 = new Binding(nameof(SubControl.text), 1, "dataMember"); - + collection.Add(binding1); collection.Add(binding2); collection.Add(binding3); @@ -305,7 +305,7 @@ public void Clear_Invoke_Success() var control = new Control(); var collection = new ControlBindingsCollection(control); var binding = new Binding(null, new object(), "member"); - + collection.Add(binding); Assert.Same(binding, Assert.Single(collection)); Assert.Same(control, binding.BindableComponent); @@ -325,7 +325,7 @@ public void Remove_Invoke_Success() var control = new Control(); var collection = new ControlBindingsCollection(control); var binding = new Binding(null, new object(), "member"); - + collection.Add(binding); Assert.Same(binding, Assert.Single(collection)); Assert.Same(control, binding.BindableComponent); @@ -383,7 +383,7 @@ public void RemoveAt_Invoke_Success() var control = new Control(); var collection = new ControlBindingsCollection(control); var binding = new Binding(null, new object(), "member"); - + collection.Add(binding); Assert.Same(binding, Assert.Single(collection)); Assert.Same(control, binding.BindableComponent); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlTests.cs index 9524e65e19c..7f3b82a30be 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlTests.cs @@ -1348,7 +1348,7 @@ public void Control_FontGetSet(Font value) Font = value }; Assert.Equal(value ?? Control.DefaultFont, control.Font); - + // Set same. control.Font = value; Assert.Equal(value ?? Control.DefaultFont, control.Font); @@ -1383,7 +1383,7 @@ public void Control_WindowText_Set_GetReturnsExpected(string value) Assert.Equal(value ?? string.Empty, control.WindowText); // Set same. - control.WindowText = value; + control.WindowText = value; Assert.Equal(value ?? string.Empty, control.WindowText); } @@ -1393,12 +1393,12 @@ public void Control_WindowText_SetWithHandle_GetReturnsExpected(string value) { var control = new Control(); Assert.NotEqual(IntPtr.Zero, control.Handle); - + control.WindowText = value; Assert.Equal(value ?? string.Empty, control.WindowText); // Set same. - control.WindowText = value; + control.WindowText = value; Assert.Equal(value ?? string.Empty, control.WindowText); } @@ -1413,7 +1413,7 @@ public void Control_Name_Set_GetReturnsExpected(string value) Assert.Equal(value ?? string.Empty, control.Name); // Set same. - control.Name = value; + control.Name = value; Assert.Equal(value ?? string.Empty, control.Name); } @@ -1428,7 +1428,7 @@ public void Control_Text_Set_GetReturnsExpected(string value) Assert.Equal(value ?? string.Empty, control.Text); // Set same. - control.Text = value; + control.Text = value; Assert.Equal(value ?? string.Empty, control.Text); } @@ -1443,7 +1443,7 @@ public void Control_Text_SetWithHandle_GetReturnsExpected(string value) Assert.Equal(value ?? string.Empty, control.Text); // Set same. - control.Text = value; + control.Text = value; Assert.Equal(value ?? string.Empty, control.Text); } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/CreateParamsTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/CreateParamsTests.cs index f7781c92799..c813a810492 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/CreateParamsTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/CreateParamsTests.cs @@ -136,7 +136,7 @@ public void CreateParams_ToString_Invoke_ReturnsExpected() { var createParams = new CreateParams { - ClassName ="className", + ClassName = "className", Caption = "caption", Style = 10, ExStyle = 11, diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridCellTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridCellTests.cs index ce1a5e2fb3e..67b3a895107 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridCellTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridCellTests.cs @@ -41,7 +41,7 @@ public void DataGridCell_RowNumber_Set_GetReturnsExpected(int value) RowNumber = value }; Assert.Equal(value, cell.RowNumber); - + // Set same. cell.RowNumber = value; Assert.Equal(value, cell.RowNumber); @@ -56,7 +56,7 @@ public void DataGridCell_ColumnNumber_Set_GetReturnsExpected(int value) ColumnNumber = value }; Assert.Equal(value, cell.ColumnNumber); - + // Set same. cell.ColumnNumber = value; Assert.Equal(value, cell.ColumnNumber); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridColumnStyleTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridColumnStyleTests.cs index 8953e2a674e..b36975aa1ef 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridColumnStyleTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridColumnStyleTests.cs @@ -74,7 +74,7 @@ public static IEnumerable Ctor_PropertyDescriptor_Bool_TestData() yield return new object[] { TypeDescriptor.GetProperties(typeof(DataClass))[0], true, "Value1", false }; yield return new object[] { TypeDescriptor.GetProperties(typeof(DataClass))[0], false, string.Empty, false }; - + yield return new object[] { TypeDescriptor.GetProperties(typeof(ReadOnlyDataClass))[0], true, "Value1", true }; yield return new object[] { TypeDescriptor.GetProperties(typeof(ReadOnlyDataClass))[0], false, string.Empty, true }; } @@ -586,7 +586,7 @@ public void Width_SetWithTableStyleWithDataGrid_GetReturnsExpected(int value) dataGrid.TableStyles.Add(tableStyle); var style = new SubDataGridColumnStyle(); tableStyle.GridColumnStyles.Add(style); - + style.Width = value; Assert.Equal(value, style.Width); Assert.Equal(1, callCount); @@ -604,7 +604,7 @@ public void Width_SetWithTableStyleWithoutDataGrid_GetReturnsExpected(int value) var tableStyle = new DataGridTableStyle(); var style = new SubDataGridColumnStyle(); tableStyle.GridColumnStyles.Add(style); - + style.Width = value; Assert.Equal(value, style.Width); @@ -684,7 +684,7 @@ public void DataGridColumnStyle_CheckValidDataSource_HasPropertyDescriptor_Nop() var property = TypeDescriptor.GetProperties(typeof(DataClass))[0]; var style = new SubDataGridColumnStyle(property); var context = new BindingContext(); - var dataSource = new List { 1, 2, 3}; + var dataSource = new List { 1, 2, 3 }; CurrencyManager value = Assert.IsType(context[dataSource]); style.CheckValidDataSource(value); } @@ -701,7 +701,7 @@ public void DataGridColumnStyle_CheckValidDataSource_NoPropertyDescriptor_Throws { var style = new SubDataGridColumnStyle(); var context = new BindingContext(); - var dataSource = new List { 1, 2, 3}; + var dataSource = new List { 1, 2, 3 }; CurrencyManager value = Assert.IsType(context[dataSource]); Assert.Throws(() => style.CheckValidDataSource(value)); } @@ -764,7 +764,7 @@ public static IEnumerable Edit_CurrencyManagerIntRectangleBool_TestDat yield return new object[] { null, -2, Rectangle.Empty, false }; var context = new BindingContext(); - var dataSource = new List { 1, 2, 3}; + var dataSource = new List { 1, 2, 3 }; yield return new object[] { context[dataSource], -1, new Rectangle(1, 2, 3, 4), true }; yield return new object[] { context[dataSource], 1, new Rectangle(-1, -2, -3, -4), true }; } @@ -794,7 +794,7 @@ public static IEnumerable Edit_CurrencyManagerIntRectangleBoolString_T yield return new object[] { null, -2, Rectangle.Empty, false, null }; var context = new BindingContext(); - var dataSource = new List { 1, 2, 3}; + var dataSource = new List { 1, 2, 3 }; yield return new object[] { context[dataSource], -1, new Rectangle(1, 2, 3, 4), true, string.Empty }; yield return new object[] { context[dataSource], 1, new Rectangle(-1, -2, -3, -4), true, "displayText" }; } @@ -899,7 +899,7 @@ public void DataGridColumnStyle_GetColumnValueAtRow_NoPropertyDescriptor_ThrowsI { var style = new SubDataGridColumnStyle(); var context = new BindingContext(); - var dataSource = new List { 1, 2, 3}; + var dataSource = new List { 1, 2, 3 }; CurrencyManager source = Assert.IsType(context[dataSource]); Assert.Throws(() => style.GetColumnValueAtRow(source, 0)); } @@ -909,7 +909,7 @@ public void DataGridColumnStyle_GetColumnValueAtRow_NoPropertyDescriptorNoValida { var style = new NullPropertyDescriptorDataGridColumnStyle(1); var context = new BindingContext(); - var dataSource = new List { 1, 2, 3}; + var dataSource = new List { 1, 2, 3 }; CurrencyManager source = Assert.IsType(context[dataSource]); Assert.Throws(() => style.GetColumnValueAtRow(source, 0)); } @@ -1081,7 +1081,7 @@ public void DataGridColumnStyle_SetColumnValueAtRow_NoPropertyDescriptor_ThrowsI { var style = new SubDataGridColumnStyle(); var context = new BindingContext(); - var dataSource = new List { 1, 2, 3}; + var dataSource = new List { 1, 2, 3 }; CurrencyManager source = Assert.IsType(context[dataSource]); Assert.Throws(() => style.SetColumnValueAtRow(source, 0, 1)); } @@ -1091,7 +1091,7 @@ public void DataGridColumnStyle_SetColumnValueAtRow_NoPropertyDescriptorNoValida { var style = new NullPropertyDescriptorDataGridColumnStyle(1); var context = new BindingContext(); - var dataSource = new List { 1, 2, 3}; + var dataSource = new List { 1, 2, 3 }; CurrencyManager source = Assert.IsType(context[dataSource]); Assert.Throws(() => style.SetColumnValueAtRow(source, 0, new object())); } @@ -1322,7 +1322,7 @@ public SubDataGridColumnStyle(PropertyDescriptor prop, bool isDefault) : base(pr public new void SetDataGridInColumn(DataGrid value) => base.SetDataGridInColumn(value); public Action EditAction { get; set; } - + protected internal override void Edit(CurrencyManager source, int rowNum, Rectangle bounds, bool readOnly, string displayText, bool cellIsVisible) { EditAction(source, rowNum, bounds, readOnly, displayText, cellIsVisible); @@ -1349,7 +1349,7 @@ public NullPropertyDescriptorDataGridColumnStyle(PropertyDescriptor prop, int re } public int RequiredCallCount { get; set; } - + private int _callCount = 0; public override PropertyDescriptor PropertyDescriptor diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewCellPaintingEventArgsTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewCellPaintingEventArgsTests.cs index d789d42356a..22c88830baa 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewCellPaintingEventArgsTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewCellPaintingEventArgsTests.cs @@ -76,7 +76,7 @@ public void Ctor_InvalidPaintParts_ThrowsArgumentException(DataGridViewPaintPart Assert.Throws("paintParts", () => new DataGridViewCellPaintingEventArgs(new DataGridView(), graphics, Rectangle.Empty, Rectangle.Empty, -2, -2, DataGridViewElementStates.Displayed, null, null, null, new DataGridViewCellStyle(), null, paintParts)); } } - + [Theory] [InlineData(0, 0)] [InlineData(-1, -1)] @@ -134,7 +134,7 @@ public void Paint_InvalidColumnIndex_ThrowsInvalidOperationException(int columnI Assert.Throws(() => e.Paint(new Rectangle(1, 2, 3, 4), DataGridViewPaintParts.None)); } } - + [Theory] [InlineData(0, 0)] [InlineData(-1, -1)] @@ -192,7 +192,7 @@ public void PaintBackground_InvalidColumnIndex_ThrowsInvalidOperationException(i Assert.Throws(() => e.PaintBackground(new Rectangle(1, 2, 3, 4), true)); } } - + [Theory] [InlineData(0, 0)] [InlineData(-1, -1)] diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewCellStyleTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewCellStyleTests.cs index 2220e05c246..ae63ad0f6b4 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewCellStyleTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewCellStyleTests.cs @@ -845,7 +845,7 @@ public static IEnumerable Equals_TestData() var formatProvider = new NumberFormatInfo(); yield return new object[] { new DataGridViewCellStyle(), new DataGridViewCellStyle(), true }; - + yield return new object[] { new DataGridViewCellStyle { Alignment = DataGridViewContentAlignment.BottomCenter }, diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewCellTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewCellTests.cs index 23abd2feee1..64f4d10bfec 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewCellTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewCellTests.cs @@ -176,11 +176,11 @@ public void DataGridViewCell_Displayed_Get_ReturnsExpected(DataGridViewCell cell { Assert.Equal(expected, cell.Displayed); } - + public static IEnumerable EditedFormattedValue_Get_TestData() { yield return new object[] { new SubDataGridViewCell(), null }; - + var row = new DataGridViewRow(); row.Cells.Add(new SubDataGridViewCell()); yield return new object[] { row.Cells[0], null }; @@ -260,7 +260,7 @@ public void DataGridViewCell_ErrorIconBounds_GetNoDataGridView_ThrowsInvalidOper public static IEnumerable ErrorText_Get_TestData() { yield return new object[] { new SubDataGridViewCell(), string.Empty }; - + var row = new DataGridViewRow(); row.Cells.Add(new SubDataGridViewCell()); yield return new object[] { row.Cells[0], string.Empty }; @@ -285,7 +285,7 @@ public void DataGridViewCell_ErrorText_Get_ReturnsExpected(DataGridViewCell cell public static IEnumerable ErrorText_GetNeedsErrorText_TestData() { yield return new object[] { new DataGridView { ColumnCount = 1, VirtualMode = true } }; - + var bound = new DataGridView { DataSource = new[] { new { Name = "Name" } } }; new Form().Controls.Add(bound); Assert.NotNull(bound.BindingContext); @@ -325,7 +325,7 @@ public static IEnumerable ErrorText_Set_TestData() foreach (string errorText in new string[] { null, "", "reasonable" }) { yield return new object[] { new SubDataGridViewCell(), errorText, errorText ?? string.Empty }; - + var row = new DataGridViewRow(); row.Cells.Add(new SubDataGridViewCell()); yield return new object[] { row.Cells[0], errorText, errorText ?? string.Empty }; @@ -408,11 +408,11 @@ public void DataGridViewCell_ErrorText_SetWithDataGridView_CallsCellErrorTextCha Assert.Equal("errorText", cell.ErrorText); Assert.Equal(3, callCount); } - + public static IEnumerable FormattedValue_Get_TestData() { yield return new object[] { new SubDataGridViewCell(), null }; - + var row = new DataGridViewRow(); row.Cells.Add(new SubDataGridViewCell()); yield return new object[] { row.Cells[0], null }; @@ -484,7 +484,7 @@ public static IEnumerable Frozen_Get_TestData() var frozenColumnDataGridView = new DataGridView { ColumnCount = 1 }; frozenColumnDataGridView.Columns[0].Frozen = true; yield return new object[] { frozenColumnDataGridView.Rows[0].Cells[0], false }; - + var frozenDataGridView = new DataGridView { ColumnCount = 1 }; frozenDataGridView.Columns[0].Frozen = true; frozenDataGridView.Rows[0].Frozen = true; @@ -517,7 +517,7 @@ public static IEnumerable InheritedState_Get_TestData() var column = new DataGridViewColumn(); yield return new object[] { column.HeaderCell, DataGridViewElementStates.ReadOnly | DataGridViewElementStates.ResizableSet | DataGridViewElementStates.Visible }; - + var dataGridView = new DataGridView { ColumnCount = 1 }; dataGridView.Rows.Add(new DataGridViewRow()); dataGridView.Rows.Add(new DataGridViewRow()); @@ -531,7 +531,7 @@ public static IEnumerable InheritedState_Get_TestData() customDataGridViewRow.Resizable = DataGridViewTriState.False; customDataGridViewRow.Visible = false; yield return new object[] { customDataGridViewRow.Cells[0], DataGridViewElementStates.ReadOnly | DataGridViewElementStates.Resizable | DataGridViewElementStates.ResizableSet | DataGridViewElementStates.Selected }; - + DataGridViewCell dataGridViewCustomCell = dataGridView.Rows[2].Cells[0]; dataGridViewCustomCell.ReadOnly = true; dataGridViewCustomCell.Selected = true; @@ -610,7 +610,7 @@ public static IEnumerable ReadOnly_Get_TestData() readOnlyRow2.Cells.Add(readOnlyCell2); readOnlyRow2.ReadOnly = true; yield return new object[] { readOnlyCell2, true }; - + var column = new DataGridViewColumn(); yield return new object[] { column.HeaderCell, true }; @@ -1058,7 +1058,7 @@ public static IEnumerable BorderWidths_TestData() }, new Rectangle(0, 0, 0, 1) }; - + var row = new DataGridViewRow { DividerHeight = 10 }; var cell = new SubDataGridViewCell(); row.Cells.Add(cell); @@ -1290,7 +1290,7 @@ public static IEnumerable GetEditedFormattedValue_TestData() foreach (int rowIndex in new int[] { -2, -1, 0 }) { yield return new object[] { new SubDataGridViewCell(), rowIndex, DataGridViewDataErrorContexts.Formatting, null }; - + var row = new DataGridViewRow(); var cell = new SubDataGridViewCell(); row.Cells.Add(cell); @@ -1319,7 +1319,7 @@ public static IEnumerable GetErrorText_TestData() yield return new object[] { new SubDataGridViewCell(), rowIndex, string.Empty }; yield return new object[] { new SubDataGridViewCell { ErrorText = null }, rowIndex, string.Empty }; yield return new object[] { new SubDataGridViewCell { ErrorText = "errorText" }, rowIndex, "errorText" }; - + var row = new DataGridViewRow(); var cell = new SubDataGridViewCell(); row.Cells.Add(cell); @@ -1340,7 +1340,7 @@ public static IEnumerable GetFormattedValue_TestData() { yield return new object[] { new SubDataGridViewCell(), "value", rowIndex, new DataGridViewCellStyle(), new Int32Converter(), new Int32Converter(), DataGridViewDataErrorContexts.Formatting, null }; yield return new object[] { new SubDataGridViewCell(), null, rowIndex, null, null, null, (DataGridViewDataErrorContexts)(DataGridViewDataErrorContexts.Formatting - 1), null }; - + var row = new DataGridViewRow(); var cell = new SubDataGridViewCell(); row.Cells.Add(cell); @@ -1535,7 +1535,7 @@ public void DataGridViewCell_MeasureTextHeight_NullOrEmptyText_ReturnsExpected(s { int height = DataGridViewCell.MeasureTextHeight(graphics, text, SystemFonts.DefaultFont, 10, TextFormatFlags.Default); Assert.Equal(0, height); - + height = DataGridViewCell.MeasureTextHeight(graphics, text, SystemFonts.DefaultFont, 10, TextFormatFlags.Default, out bool widthTruncated); Assert.Equal(0, height); Assert.False(widthTruncated); @@ -1552,7 +1552,7 @@ public void DataGridViewCell_MeasureTextHeight_NonEmptyText_ReturnsExpected(stri { int height = DataGridViewCell.MeasureTextHeight(graphics, text, SystemFonts.DefaultFont, 20, TextFormatFlags.Default); Assert.NotEqual(0, height); - + height = DataGridViewCell.MeasureTextHeight(graphics, text, SystemFonts.DefaultFont, 20, TextFormatFlags.Default, out bool widthTruncated); Assert.NotEqual(0, height); Assert.Equal(expectedWidthTruncated, widthTruncated); @@ -2110,7 +2110,7 @@ public static IEnumerable ParseFormattedValue_TestData() yield return new object[] { typeof(int?), typeof(int), 123, new DataGridViewCellStyle(), null, null, 123 }; yield return new object[] { typeof(int), typeof(int?), 123, new DataGridViewCellStyle(), null, null, 123 }; yield return new object[] { typeof(string), typeof(int?), 123, new DataGridViewCellStyle(), null, null, "123" }; - + // CheckState. yield return new object[] { typeof(bool), typeof(CheckState), CheckState.Indeterminate, new DataGridViewCellStyle(), null, null, DBNull.Value }; yield return new object[] { typeof(bool), typeof(CheckState), CheckState.Checked, new DataGridViewCellStyle(), null, null, true }; @@ -2273,7 +2273,7 @@ public class SubDataGridViewCell : DataGridViewCell public new bool DoubleClickUnsharesRow(DataGridViewCellEventArgs e) => base.DoubleClickUnsharesRow(e); public new bool EnterUnsharesRow(int rowIndex, bool throughMouseClick) => base.EnterUnsharesRow(rowIndex, throughMouseClick); - + public new object GetClipboardContent(int rowIndex, bool firstCell, bool lastCell, bool inFirstRow, bool inLastRow, string format) { return base.GetClipboardContent(rowIndex, firstCell, lastCell, inFirstRow, inLastRow, format); @@ -2298,7 +2298,7 @@ public class SubDataGridViewCell : DataGridViewCell { return base.GetPreferredSize(graphics, cellStyle, rowIndex, constraintSize); } - + public new Size GetSize(int rowIndex) => base.GetSize(rowIndex); public new object GetValue(int rowIndex) => base.GetValue(rowIndex); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewColumnEventArgsTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewColumnEventArgsTests.cs index f7821d9a6a8..1d685d00512 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewColumnEventArgsTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewColumnEventArgsTests.cs @@ -15,7 +15,7 @@ public void Ctor_DataGridViewColumn() var e = new DataGridViewColumnEventArgs(dataGridViewColumn); Assert.Equal(dataGridViewColumn, e.Column); } - + [Fact] public void Ctor_NullDataGridViewColumn_ThrowsArgumentNullException() { diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewElementTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewElementTests.cs index 1bdbcc98f9b..03ae7299928 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewElementTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewElementTests.cs @@ -68,17 +68,17 @@ public void RaiseMouseWheel_Invoke_Nop() private class SubDataGridViewElement : DataGridViewElement { public new void OnDataGridViewChanged() => base.OnDataGridViewChanged(); - + public new void RaiseCellClick(DataGridViewCellEventArgs e) => base.RaiseCellClick(e); - + public new void RaiseCellContentClick(DataGridViewCellEventArgs e) => base.RaiseCellContentClick(e); - + public new void RaiseCellContentDoubleClick(DataGridViewCellEventArgs e) => base.RaiseCellContentDoubleClick(e); - + public new void RaiseCellValueChanged(DataGridViewCellEventArgs e) => base.RaiseCellValueChanged(e); - + public new void RaiseDataError(DataGridViewDataErrorEventArgs e) => base.RaiseDataError(e); - + public new void RaiseMouseWheel(MouseEventArgs e) => base.RaiseMouseWheel(e); } } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewRowEventArgsTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewRowEventArgsTests.cs index 441f755e845..f0fd4152547 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewRowEventArgsTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewRowEventArgsTests.cs @@ -15,7 +15,7 @@ public void Ctor_DataGridViewRow() var e = new DataGridViewRowEventArgs(dataGridViewRow); Assert.Equal(dataGridViewRow, e.Row); } - + [Fact] public void Ctor_NullDataGridViewRow_ThrowsArgumentNullException() { diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewRowPostPaintEventArgsTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewRowPostPaintEventArgsTests.cs index 1495830b95d..87300ddf878 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewRowPostPaintEventArgsTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewRowPostPaintEventArgsTests.cs @@ -65,7 +65,7 @@ public void Ctor_NullInheritedRowStyle_ThrowsArgumentNullException() public static IEnumerable ClipBounds_TestData() { yield return new object[] { Rectangle.Empty }; - yield return new object[] { new Rectangle(1, 2, 3 ,4) }; + yield return new object[] { new Rectangle(1, 2, 3, 4) }; yield return new object[] { new Rectangle(-1, -2, -3, -4) }; } @@ -83,7 +83,7 @@ public void ClipBounds_Set_GetReturnsExpected(Rectangle value) Assert.Equal(value, e.ClipBounds); } } - + [Fact] public void DrawFocus_ValidRowIndex_Success() { @@ -111,7 +111,7 @@ public void DrawFocus_InvalidRowIndex_ThrowsInvalidOperationException(int rowInd Assert.Throws(() => e.DrawFocus(new Rectangle(1, 2, 3, 4), true)); } } - + [Fact] public void PaintCells_ValidRowIndex_Success() { @@ -139,7 +139,7 @@ public void PaintCells_InvalidRowIndex_ThrowsInvalidOperationException(int rowIn Assert.Throws(() => e.PaintCells(new Rectangle(1, 2, 3, 4), DataGridViewPaintParts.None)); } } - + [Fact] public void PaintCellsBackground_ValidRowIndex_Success() { @@ -167,7 +167,7 @@ public void PaintCellsBackground_InvalidRowIndex_ThrowsInvalidOperationException Assert.Throws(() => e.PaintCellsBackground(new Rectangle(1, 2, 3, 4), true)); } } - + [Fact] public void PaintCellsContent_ValidRowIndex_Success() { @@ -195,7 +195,7 @@ public void PaintCellsContent_InvalidRowIndex_ThrowsInvalidOperationException(in Assert.Throws(() => e.PaintCellsContent(new Rectangle(1, 2, 3, 4))); } } - + [Fact] public void PaintHeader_ValidRowIndexDataGridViewPaintParts_Success() { @@ -208,7 +208,7 @@ public void PaintHeader_ValidRowIndexDataGridViewPaintParts_Success() e.PaintHeader(DataGridViewPaintParts.None); } } - + [Theory] [InlineData(true)] [InlineData(false)] diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewRowPrePaintEventArgsTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewRowPrePaintEventArgsTests.cs index 1ea4617118e..17ec7f07e6a 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewRowPrePaintEventArgsTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewRowPrePaintEventArgsTests.cs @@ -67,7 +67,7 @@ public void Ctor_NullInheritedRowStyle_ThrowsArgumentNullException() public static IEnumerable ClipBounds_TestData() { yield return new object[] { Rectangle.Empty }; - yield return new object[] { new Rectangle(1, 2, 3 ,4) }; + yield return new object[] { new Rectangle(1, 2, 3, 4) }; yield return new object[] { new Rectangle(-1, -2, -3, -4) }; } @@ -113,7 +113,7 @@ public void PaintParts_SetInvalidValue_ThrowsArgumentException(DataGridViewPaint Assert.Throws("value", () => e.PaintParts = value); } } - + [Fact] public void DrawFocus_ValidRowIndex_Success() { @@ -141,7 +141,7 @@ public void DrawFocus_InvalidRowIndex_ThrowsInvalidOperationException(int rowInd Assert.Throws(() => e.DrawFocus(new Rectangle(1, 2, 3, 4), true)); } } - + [Fact] public void PaintCells_ValidRowIndex_Success() { @@ -169,7 +169,7 @@ public void PaintCells_InvalidRowIndex_ThrowsInvalidOperationException(int rowIn Assert.Throws(() => e.PaintCells(new Rectangle(1, 2, 3, 4), DataGridViewPaintParts.None)); } } - + [Fact] public void PaintCellsBackground_ValidRowIndex_Success() { @@ -197,7 +197,7 @@ public void PaintCellsBackground_InvalidRowIndex_ThrowsInvalidOperationException Assert.Throws(() => e.PaintCellsBackground(new Rectangle(1, 2, 3, 4), true)); } } - + [Fact] public void PaintCellsContent_ValidRowIndex_Success() { @@ -225,7 +225,7 @@ public void PaintCellsContent_InvalidRowIndex_ThrowsInvalidOperationException(in Assert.Throws(() => e.PaintCellsContent(new Rectangle(1, 2, 3, 4))); } } - + [Fact] public void PaintHeader_ValidRowIndexDataGridViewPaintParts_Success() { @@ -238,7 +238,7 @@ public void PaintHeader_ValidRowIndexDataGridViewPaintParts_Success() e.PaintHeader(DataGridViewPaintParts.None); } } - + [Theory] [InlineData(true)] [InlineData(false)] diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewRowTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewRowTests.cs index 718d11eec1b..3aa6815b1fe 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewRowTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewRowTests.cs @@ -567,7 +567,7 @@ public void DataGridViewRow_ErrorText_Get_ReturnsExpected(DataGridViewRow row, s public static IEnumerable ErrorText_GetNeedsErrorText_TestData() { yield return new object[] { new DataGridView { ColumnCount = 1, VirtualMode = true } }; - + var bound = new DataGridView { DataSource = new[] { new { Name = "Name" } } }; new Form().Controls.Add(bound); Assert.NotNull(bound.BindingContext); @@ -790,7 +790,7 @@ public void DataGridViewRow_Frozen_SetShared_ThrowsInvalidOperationException(Dat } public static IEnumerable HeaderCell_Get_TestData() - { + { yield return new object[] { new DataGridViewRow() }; var dataGridView = new DataGridView { ColumnCount = 1 }; @@ -951,7 +951,7 @@ public static IEnumerable Height_NeedsHeightInfo_TestData() 22, 0, 22 }; yield return new object[] { new DataGridView { ColumnCount = 1, VirtualMode = true }, 6, 1, 5 }; - + var bound = new DataGridView { DataSource = new[] { new { Name = "Name" } } }; new Form().Controls.Add(bound); Assert.NotNull(bound.BindingContext); @@ -993,7 +993,7 @@ public static IEnumerable Height_Set_TestData() yield return new object[] { new DataGridViewRow(), 1, 3 }; yield return new object[] { new DataGridViewRow(), 3, 3 }; yield return new object[] { new DataGridViewRow(), 4, 4 }; - + var dataGridView = new DataGridView { ColumnCount = 1 }; dataGridView.Rows.Add(new DataGridViewRow()); yield return new object[] { dataGridView.Rows[0], 65536, 65536 }; @@ -1262,7 +1262,7 @@ public static IEnumerable MinimumHeight_NeedsHeightInfo_TestData() 5, 0 }; yield return new object[] { new DataGridView { ColumnCount = 1, VirtualMode = true }, 6, 1 }; - + var bound = new DataGridView { DataSource = new[] { new { Name = "Name" } } }; new Form().Controls.Add(bound); Assert.NotNull(bound.BindingContext); @@ -1303,7 +1303,7 @@ public static IEnumerable MinimumHeight_Set_TestData() yield return new object[] { new DataGridViewRow(), 3, 10 }; yield return new object[] { new DataGridViewRow(), 10, 10 }; yield return new object[] { new DataGridViewRow(), 11, 11 }; - + var dataGridView = new DataGridView { ColumnCount = 1 }; dataGridView.Rows.Add(new DataGridViewRow()); yield return new object[] { dataGridView.Rows[0], 65536, 65536 }; @@ -1401,7 +1401,7 @@ public void DataGridViewRow_ReadOnly_Get_ReturnsExpected(DataGridViewRow row, bo { Assert.Equal(expected, row.ReadOnly); } - + [Theory] [MemberData(nameof(SharedRow_TestData))] public void DataGridViewRow_ReadOnly_GetShared_ThrowsInvalidOperationException(DataGridViewRow row) @@ -1487,7 +1487,7 @@ public void DataGridViewRow_ReadOnly_SetWithDataGridView_CallsRowStateChanged() Assert.True(row.ReadOnly); Assert.Equal(2, callCount); } - + [Theory] [MemberData(nameof(SharedRow_TestData))] public void DataGridViewRow_ReadOnly_SetShared_ThrowsInvalidOperationException(DataGridViewRow row) @@ -1514,7 +1514,7 @@ public void DataGridViewRow_Resizable_Get_ReturnsExpected(DataGridViewRow row, D { Assert.Equal(expected, row.Resizable); } - + [Theory] [MemberData(nameof(SharedRow_TestData))] public void DataGridViewRow_Resizable_GetShared_ThrowsInvalidOperationException(DataGridViewRow row) @@ -1615,7 +1615,7 @@ public void DataGridViewRow_Selected_Get_ReturnsExpected(DataGridViewRow row, bo { Assert.Equal(expected, row.Selected); } - + [Theory] [MemberData(nameof(SharedRow_TestData))] public void DataGridViewRow_Selected_GetShared_ThrowsInvalidOperationException(DataGridViewRow row) @@ -1633,7 +1633,7 @@ public void DataGridViewRow_Selected_SetWithoutDataGridView_ThrowsInvalidOperati row.Selected = false; Assert.False(row.Selected); } - + [Theory] [InlineData(DataGridViewSelectionMode.CellSelect, false)] [InlineData(DataGridViewSelectionMode.FullRowSelect, true)] @@ -1734,7 +1734,7 @@ public void DataGridViewRow_Selected_SetMultipleMultiSelect_Success() Assert.False(row1.Selected); Assert.False(row2.Selected); } - + [Theory] [MemberData(nameof(SharedRow_TestData))] public void DataGridViewRow_Selected_SetShared_ThrowsInvalidOperationException(DataGridViewRow row) @@ -1758,7 +1758,7 @@ public void DataGridViewRow_State_Get_ReturnsExpected(DataGridViewRow row, DataG { Assert.Equal(expected, row.State); } - + [Theory] [MemberData(nameof(SharedRow_TestData))] public void DataGridViewRow_State_GetShared_ThrowsInvalidOperationException(DataGridViewRow row) @@ -1833,7 +1833,7 @@ public void DataGridViewRow_Visible_Get_ReturnsExpected(DataGridViewRow row, boo { Assert.Equal(expected, row.Visible); } - + [Theory] [MemberData(nameof(SharedRow_TestData))] public void DataGridViewRow_Visible_GetShared_ThrowsInvalidOperationException(DataGridViewRow row) @@ -1914,11 +1914,11 @@ public void DataGridViewRow_Visible_SetNewRowIndexDifferent_ThrowsInvalidOperati Assert.Throws(() => row.Visible = false); Assert.True(row.Visible); - + row.Visible = true; Assert.True(row.Visible); } - + [Theory] [MemberData(nameof(SharedRow_TestData))] public void DataGridViewRow_Visible_SetShared_ThrowsInvalidOperationException(DataGridViewRow row) @@ -2735,7 +2735,7 @@ public void DataGridViewRow_GetContextMenuStrip_Invoke_ReturnsExpected(DataGridV public static IEnumerable GetContextMenuStrip_NeedsContextMenuStrip_TestData() { yield return new object[] { new DataGridView { ColumnCount = 1, VirtualMode = true } }; - + var bound = new DataGridView { DataSource = new[] { new { Name = "Name" } } }; new Form().Controls.Add(bound); Assert.NotNull(bound.BindingContext); @@ -2821,7 +2821,7 @@ public void DataGridViewRow_GetErrorText_Invoke_ReturnsExpected(DataGridViewRow public static IEnumerable GetErrorText_NeedsErrorText_TestData() { yield return new object[] { new DataGridView { ColumnCount = 1, VirtualMode = true } }; - + var bound = new DataGridView { DataSource = new[] { new { Name = "Name" } } }; new Form().Controls.Add(bound); Assert.NotNull(bound.BindingContext); @@ -2877,7 +2877,7 @@ public void DataGridViewRow_GetErrorText_SharedRow_ThrowsInvalidOperationExcepti public static IEnumerable GetState_TestData() { yield return new object[] { new DataGridViewRow(), -1, DataGridViewElementStates.Visible }; - + var dataGridView = new DataGridView(); dataGridView.Columns.Add("Column", "Text"); dataGridView.Rows.Add(new SubDataGridViewRow()); @@ -2925,7 +2925,7 @@ public static IEnumerable Paint_TestData() headersInvisibleDataGridView.Rows.Add(new DataGridViewRow()); yield return new object[] { headersInvisibleDataGridView.Rows[1], Rectangle.Empty, new Rectangle(1, 2, 100, 100), -1, DataGridViewElementStates.None, true, true, DataGridViewPaintParts.All }; - + var frozenDataGridView = new DataGridView { ColumnCount = 1 }; frozenDataGridView.Rows.Add(new DataGridViewRow()); frozenDataGridView.Columns[0].Frozen = true; @@ -2935,7 +2935,7 @@ public static IEnumerable Paint_TestData() yield return new object[] { frozenDataGridView.Rows[1], new Rectangle(1, 2, 100, 100), new Rectangle(1, 2, 100, 100), 0, DataGridViewElementStates.Displayed | DataGridViewElementStates.Displayed, false, true, DataGridViewPaintParts.None }; yield return new object[] { frozenDataGridView.Rows[1], new Rectangle(1000, 2000, 100, 100), new Rectangle(1, 2, 100, 100), 1, DataGridViewElementStates.Displayed | DataGridViewElementStates.Displayed, true, false, DataGridViewPaintParts.All }; yield return new object[] { frozenDataGridView.Rows[1], new Rectangle(1, 2, 100, 100), new Rectangle(1, 2, 1000, 1000), 1, DataGridViewElementStates.Displayed | DataGridViewElementStates.Displayed, true, false, DataGridViewPaintParts.All }; - + var leftToRightDataGridView = new DataGridView { ColumnCount = 1, RightToLeft = RightToLeft.Yes }; leftToRightDataGridView.Rows.Add(new DataGridViewRow()); leftToRightDataGridView.Columns[0].Frozen = true; @@ -2945,7 +2945,7 @@ public static IEnumerable Paint_TestData() yield return new object[] { leftToRightDataGridView.Rows[1], new Rectangle(1, 2, 100, 100), new Rectangle(1, 2, 100, 100), 0, DataGridViewElementStates.Displayed | DataGridViewElementStates.Displayed, false, true, DataGridViewPaintParts.None }; yield return new object[] { leftToRightDataGridView.Rows[1], new Rectangle(1000, 2000, 100, 100), new Rectangle(1, 2, 100, 100), 1, DataGridViewElementStates.Displayed | DataGridViewElementStates.Displayed, true, false, DataGridViewPaintParts.All }; yield return new object[] { leftToRightDataGridView.Rows[1], new Rectangle(1, 2, 100, 100), new Rectangle(1, 2, 1000, 1000), 1, DataGridViewElementStates.Displayed | DataGridViewElementStates.Displayed, true, false, DataGridViewPaintParts.All }; - + var singleVerticalBorderAddedDataGridView = new DataGridView { ColumnCount = 1, RowHeadersVisible = false }; singleVerticalBorderAddedDataGridView.Rows.Add(new DataGridViewRow()); singleVerticalBorderAddedDataGridView.Columns[0].Frozen = true; @@ -2955,7 +2955,7 @@ public static IEnumerable Paint_TestData() yield return new object[] { singleVerticalBorderAddedDataGridView.Rows[1], new Rectangle(1, 2, 100, 100), new Rectangle(1, 2, 100, 100), 0, DataGridViewElementStates.Displayed | DataGridViewElementStates.Displayed, false, true, DataGridViewPaintParts.None }; yield return new object[] { singleVerticalBorderAddedDataGridView.Rows[1], new Rectangle(1000, 2000, 100, 100), new Rectangle(1, 2, 100, 100), 1, DataGridViewElementStates.Displayed | DataGridViewElementStates.Displayed, true, false, DataGridViewPaintParts.All }; yield return new object[] { singleVerticalBorderAddedDataGridView.Rows[1], new Rectangle(1, 2, 100, 100), new Rectangle(1, 2, 1000, 1000), 1, DataGridViewElementStates.Displayed | DataGridViewElementStates.Displayed, true, false, DataGridViewPaintParts.All }; - + var singleHorizontalBorderAddedDataGridView = new DataGridView { ColumnCount = 1, ColumnHeadersVisible = false }; singleHorizontalBorderAddedDataGridView.Rows.Add(new DataGridViewRow()); singleHorizontalBorderAddedDataGridView.Columns[0].Frozen = true; diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/Design/EventsTabTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/Design/EventsTabTests.cs index 065db5a8743..6598939d5f6 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/Design/EventsTabTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/Design/EventsTabTests.cs @@ -130,7 +130,7 @@ public void EventsTab_GetDefaultProperty_IDesignerEventService_Success(object ob .Returns(service); var tab = new EventsTab(mockServiceProvider.Object); Assert.Null(tab.GetDefaultProperty(obj)); - + service.OnActiveDesignerChanged(e); Assert.Equal(expected, tab.GetDefaultProperty(obj)); } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/Design/PropertyTabTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/Design/PropertyTabTests.cs index 6019ac8314a..b6a74c55f55 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/Design/PropertyTabTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/Design/PropertyTabTests.cs @@ -56,7 +56,7 @@ public void PropertyTab_Dispose_WithBitmap_Success() tab.Dispose(); Assert.Null(tab.Bitmap); Assert.Throws(null, () => bitmap.Size); - + // Dispose again. tab.Dispose(); Assert.Null(tab.Bitmap); @@ -69,7 +69,7 @@ public void PropertyTab_Dispose_NoBitmap_Success() var tab = new SubPropertyTab(); tab.Dispose(); Assert.Null(tab.Bitmap); - + // Dispose again. tab.Dispose(); Assert.Null(tab.Bitmap); @@ -82,7 +82,7 @@ public void PropertyTab_Dispose_NoBitmapDisposing_Success(bool disposing) var tab = new SubPropertyTab(); tab.Dispose(disposing); Assert.Null(tab.Bitmap); - + // Dispose again. tab.Dispose(disposing); Assert.Null(tab.Bitmap); @@ -105,7 +105,7 @@ public void PropertyTab_Dispose_WithBitmapDisposing_Success(bool disposing) { Assert.Same(bitmap, tab.Bitmap); } - + // Dispose again. tab.Dispose(disposing); if (disposing) diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DockPaddingEdgesTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DockPaddingEdgesTests.cs index 72fb4cb542f..f011929c749 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DockPaddingEdgesTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DockPaddingEdgesTests.cs @@ -21,7 +21,7 @@ public class DockPaddingEdgesTests [InlineData(-1, -1, -1, 0, 0, 0, 0, 0, 0)] [InlineData(0, 0, 0, 0, 0, 0, 0, 0, 0)] [InlineData(1, 1, 1, 1, 1, 1, 1, 1, 1)] - [InlineData(1, 2, 3, 4, 0, 1, 2, 3, 4)] + [InlineData(1, 2, 3, 4, 0, 1, 2, 3, 4)] public void DockPaddingEdges_Properties_Get_ReturnsExpected(int left, int top, int right, int bottom, int expectedAll, int expectedLeft, int expectedTop, int expectedRight, int expectedBottom) { var owner = new ScrollableControl diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DragEventArgsTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DragEventArgsTests.cs index 6fdac344605..bbc45419848 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DragEventArgsTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DragEventArgsTests.cs @@ -30,7 +30,7 @@ public void Ctor_IDataObject_Int_Int_Int_DragDropEffects_DragDropEffects(IDataOb [Theory] [InlineData(DragDropEffects.Copy)] - [InlineData((DragDropEffects)(DragDropEffects.None -1))] + [InlineData((DragDropEffects)(DragDropEffects.None - 1))] public void Effect_Set_GetReturnsExpected(DragDropEffects value) { var e = new DragEventArgs(new CustomDataObject(), 1, 2, 3, DragDropEffects.Copy, DragDropEffects.Move) @@ -43,27 +43,27 @@ public void Effect_Set_GetReturnsExpected(DragDropEffects value) private class CustomDataObject : IDataObject { public object GetData(string format, bool autoConvert) => throw new NotImplementedException(); - + public object GetData(string format) => throw new NotImplementedException(); - + public object GetData(Type format) => throw new NotImplementedException(); - + public void SetData(string format, bool autoConvert, object data) => throw new NotImplementedException(); - + public void SetData(string format, object data) => throw new NotImplementedException(); - + public void SetData(Type format, object data) => throw new NotImplementedException(); - + public void SetData(object data) => throw new NotImplementedException(); - + public bool GetDataPresent(string format, bool autoConvert) => throw new NotImplementedException(); - + public bool GetDataPresent(string format) => throw new NotImplementedException(); - + public bool GetDataPresent(Type format) => throw new NotImplementedException(); public string[] GetFormats(bool autoConvert) => throw new NotImplementedException(); - + public string[] GetFormats() => throw new NotImplementedException(); } } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DrawListViewSubItemEventArgsTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DrawListViewSubItemEventArgsTests.cs index da808658013..adbe5d0ae00 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DrawListViewSubItemEventArgsTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DrawListViewSubItemEventArgsTests.cs @@ -17,8 +17,8 @@ public static IEnumerable Ctor_Graphics_ListViewItem_Rectangle_Int_Lis yield return new object[] { null, Rectangle.Empty, null, null, -2, -2, null, (ListViewItemStates)(ListViewItemStates.Checked - 1) }; yield return new object[] { graphics, new Rectangle(1, 2, 3, 4), new ListViewItem(), null, -1, -1, new ColumnHeader(), ListViewItemStates.Checked }; - yield return new object[] { graphics, new Rectangle(-1, 2, -3, -4), new ListViewItem(), new ListViewItem.ListViewSubItem(), 0, 0, new ColumnHeader(),ListViewItemStates.Focused }; - yield return new object[] { graphics, new Rectangle(1, 2, 3, 4), new ListViewItem(), new ListViewItem.ListViewSubItem(), 1, 2, new ColumnHeader(),ListViewItemStates.Checked }; + yield return new object[] { graphics, new Rectangle(-1, 2, -3, -4), new ListViewItem(), new ListViewItem.ListViewSubItem(), 0, 0, new ColumnHeader(), ListViewItemStates.Focused }; + yield return new object[] { graphics, new Rectangle(1, 2, 3, 4), new ListViewItem(), new ListViewItem.ListViewSubItem(), 1, 2, new ColumnHeader(), ListViewItemStates.Checked }; } [Theory] diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/FeatureSupportTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/FeatureSupportTests.cs index f9a53861e3e..5fda84e7985 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/FeatureSupportTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/FeatureSupportTests.cs @@ -157,7 +157,7 @@ public void FeatureSupport_IsPresent_NonStaticField_ThrowsTargetException(Type f Assert.Throws(() => FeatureSupport.IsPresent(featureClassType.AssemblyQualifiedName, featureConstName)); Assert.Throws(() => FeatureSupport.IsPresent(featureClassType.AssemblyQualifiedName, featureConstName, new Version(1, 2, 3, 4))); } - + private class IFeatureSupportClass : IFeatureSupport { public bool IsPresent(object feature) => throw new NotImplementedException(); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/FileDialogTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/FileDialogTests.cs index c4613d047cf..77da4f33f97 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/FileDialogTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/FileDialogTests.cs @@ -681,7 +681,7 @@ private protected override bool RunFileDialog(NativeMethods.OPENFILENAME_I ofn) private protected override string[] ProcessVistaFiles(FileDialogNative.IFileDialog dialog) => null; public new void OnFileOk(CancelEventArgs e) => base.OnFileOk(e); - + public new bool RunDialog(IntPtr hWndOwner) => base.RunDialog(hWndOwner); } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/HelpProviderTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/HelpProviderTests.cs index ff629dbccdf..02601fd2a66 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/HelpProviderTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/HelpProviderTests.cs @@ -93,7 +93,7 @@ public void HelpProvider_GetHelpKeyword_NoSuchControl_ReturnsNull() var provider = new HelpProvider(); Assert.Null(provider.GetHelpKeyword(new Control())); } - + [Fact] public void HelpProvider_GetHelpKeyword_NullCtl_ThrowsArgumentNullException() { @@ -107,7 +107,7 @@ public void HelpProvider_GetHelpNavigator_NoSuchControl_ReturnsAssociateIndex() var provider = new HelpProvider(); Assert.Equal(HelpNavigator.AssociateIndex, provider.GetHelpNavigator(new Control())); } - + [Fact] public void HelpProvider_GetHelpNavigator_NullCtl_ThrowsArgumentNullException() { @@ -121,7 +121,7 @@ public void HelpProvider_GetHelpString_NoSuchControl_ReturnsNull() var provider = new HelpProvider(); Assert.Null(provider.GetHelpString(new Control())); } - + [Fact] public void HelpProvider_GetHelpString_NullCtl_ThrowsArgumentNullException() { @@ -135,7 +135,7 @@ public void HelpProvider_GetShowHelp_NoSuchControl_ReturnsFalse() var provider = new HelpProvider(); Assert.False(provider.GetShowHelp(new Control())); } - + [Fact] public void HelpProvider_GetShowHelp_NullCtl_ThrowsArgumentNullException() { @@ -190,7 +190,7 @@ public void HelpProvider_SetHelpKeyword_GetHelpKeyword_ReturnsExpected(string ke Assert.Equal(!string.IsNullOrEmpty(keyword), provider.GetShowHelp(control)); Assert.Equal(expectedHelpTopic, control.AccessibilityObject.GetHelpTopic(out string fileName)); Assert.Equal(expectedFileName, fileName); - + // Set same. provider.SetHelpKeyword(control, keyword); Assert.Same(keyword, provider.GetHelpKeyword(control)); @@ -253,7 +253,7 @@ public void HelpProvider_SetHelpKeyword_WithShowHelpFalse_ReturnsExpected(string Assert.Equal(!string.IsNullOrEmpty(keyword), provider.GetShowHelp(control)); Assert.Equal(expectedFileName, fileName); } - + [Fact] public void HelpProvider_SetHelpKeyword_NullCtl_ThrowsArgumentNullException() { @@ -271,7 +271,7 @@ public void HelpProvider_SetHelpNavigator_GetHelpNavigator_ReturnsExpected(HelpN provider.SetHelpNavigator(control, navigator); Assert.Equal(navigator, provider.GetHelpNavigator(control)); Assert.True(provider.GetShowHelp(control)); - + // Set same. provider.SetHelpNavigator(control, navigator); Assert.Equal(navigator, provider.GetHelpNavigator(control)); @@ -313,7 +313,7 @@ public void HelpProvider_SetHelpNavigator_WithShowHelpFalse_ReturnsExpected(Help Assert.Equal(navigator, provider.GetHelpNavigator(control)); Assert.True(provider.GetShowHelp(control)); } - + [Fact] public void HelpProvider_SetHelpNavigator_NullCtl_ThrowsArgumentNullException() { @@ -341,7 +341,7 @@ public void HelpProvider_SetHelpString_GetHelpString_ReturnsExpected(string help Assert.Same(helpString, provider.GetHelpString(control)); Assert.Equal(!string.IsNullOrEmpty(helpString), provider.GetShowHelp(control)); Assert.Equal(string.IsNullOrEmpty(helpString) ? null : helpString, control.AccessibilityObject.Help); - + // Set same. provider.SetHelpString(control, helpString); Assert.Same(helpString, provider.GetHelpString(control)); @@ -388,7 +388,7 @@ public void HelpProvider_SetHelpString_WithShowHelpFalse_ReturnsExpected(string Assert.Equal(!string.IsNullOrEmpty(helpString), provider.GetShowHelp(control)); Assert.Equal(string.IsNullOrEmpty(helpString) ? null : helpString, control.AccessibilityObject.Help); } - + [Fact] public void HelpProvider_SetHelpString_NullCtl_ThrowsArgumentNullException() { @@ -446,21 +446,21 @@ public void HelpProvider_SetShowHelp_SetFalseThenTrue_UnbindsAndBindsControl() Assert.Equal("HelpNamespace", fileName); Assert.Equal("HelpString", control.AccessibilityObject.Help); } - + [Fact] public void HelpProvider_SetShowHelp_NullCtl_ThrowsArgumentNullException() { var provider = new HelpProvider(); Assert.Throws("key", () => provider.SetShowHelp(null, true)); } - + [Fact] public void HelpProvider_ShouldSerializeShowHelp_NoSuchControl_ReturnsFalse() { var provider = new HelpProvider(); Assert.False(provider.ShouldSerializeShowHelp(new Control())); } - + [Fact] public void HelpProvider_ShouldSerializeShowHelp_NullCtl_ThrowsArgumentNullException() { diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ImageListTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ImageListTests.cs index 30fa2c1ec8e..f2fb8fb0f35 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ImageListTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ImageListTests.cs @@ -140,7 +140,7 @@ public void ImageList_ColorDepth_SetWithHandleWithHandler_CallsRecreateHandle() public void ImageList_ColorDepth_SetInvalid_ThrowsInvalidEnumArgumentException(ColorDepth value) { var list = new ImageList(); - Assert.Throws("value", ()=> list.ColorDepth = value); + Assert.Throws("value", () => list.ColorDepth = value); } public static IEnumerable ImageSize_TestData() @@ -257,7 +257,7 @@ public void ImageList_ImageSize_SetWithHandleWithHandler_CallsRecreateHandle() public void ImageList_ImageSize_SetEmpty__ThrowsArgumentException() { var list = new ImageList(); - Assert.Throws("value", ()=> list.ImageSize = Size.Empty); + Assert.Throws("value", () => list.ImageSize = Size.Empty); } public static IEnumerable ImageList_SetInvalidDimension_TestData() @@ -272,7 +272,7 @@ public static IEnumerable ImageList_SetInvalidDimension_TestData() public void ImageList_ImageSize_SetInvalidWidth_ThrowsArgumentOutOfRangeException(int width) { var list = new ImageList(); - Assert.Throws("value", ()=> list.ImageSize = new Size(width, 1)); + Assert.Throws("value", () => list.ImageSize = new Size(width, 1)); } [Theory] @@ -280,7 +280,7 @@ public void ImageList_ImageSize_SetInvalidWidth_ThrowsArgumentOutOfRangeExceptio public void ImageList_ImageSize_SetInvalidHeight_ThrowsArgumentOutOfRangeException(int width) { var list = new ImageList(); - Assert.Throws("value", ()=> list.ImageSize = new Size(width, 1)); + Assert.Throws("value", () => list.ImageSize = new Size(width, 1)); } } } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/Layout/TableLayoutSettingsTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/Layout/TableLayoutSettingsTests.cs index ee1fb18c740..c8c977131e8 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/Layout/TableLayoutSettingsTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/Layout/TableLayoutSettingsTests.cs @@ -161,7 +161,7 @@ public void TableLayoutSettings_GetColumnSpan_InvalidControl_ThrowsNotSupportedE TableLayoutSettings settings = Assert.IsType(toolStrip.LayoutSettings); Assert.Throws(() => settings.GetColumnSpan("control")); } - + [Fact] public void TableLayoutSettings_GetColumnSpan_InvalidControlStub_ReturnsExpected() { @@ -663,7 +663,7 @@ public void TableLayoutSettings_Serialize_Deserialize_Success() TableLayoutSettings settings = Assert.IsType(toolStrip.LayoutSettings); var columnStyle = new ColumnStyle(SizeType.Percent, 1); var rowStyle = new RowStyle(SizeType.Percent, 1); - + var controlWithName = new ScrollableControl { Name = "name" }; settings.SetColumnSpan(controlWithName, 1); settings.SetRowSpan(controlWithName, 2); @@ -677,7 +677,7 @@ public void TableLayoutSettings_Serialize_Deserialize_Success() var formatter = new BinaryFormatter(); formatter.Serialize(stream, settings); stream.Seek(0, SeekOrigin.Begin); - + TableLayoutSettings result = Assert.IsType(formatter.Deserialize(stream)); Assert.Equal(columnStyle.SizeType, ((ColumnStyle)Assert.Single(result.ColumnStyles)).SizeType); Assert.Equal(columnStyle.Width, ((ColumnStyle)Assert.Single(result.ColumnStyles)).Width); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/LinkAreaTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/LinkAreaTests.cs index f529f30c60e..3cf1194e7e7 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/LinkAreaTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/LinkAreaTests.cs @@ -43,7 +43,7 @@ public void LinkArea_Start_Set_GetReturnsExpected(int value) Start = value }; Assert.Equal(value, area.Start); - + // Set same. area.Start = value; Assert.Equal(value, area.Start); @@ -58,7 +58,7 @@ public void LinkArea_Length_Set_GetReturnsExpected(int value) Length = value }; Assert.Equal(value, area.Length); - + // Set same. area.Length = value; Assert.Equal(value, area.Length); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListBindingHelperTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListBindingHelperTests.cs index c4b48c985b9..4e3dd4b0c5b 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListBindingHelperTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListBindingHelperTests.cs @@ -244,19 +244,19 @@ public static IEnumerable GetListItemProperties_Object_TestData() yield return new object[] { string.Empty, new string[] { "Length" } }; yield return new object[] { typeof(string), new string[] { "Length" } }; - yield return new object[] { new DataClass(), new string[] { "Property"} }; - yield return new object[] { typeof(DataClass), new string[] { "Property"} }; + yield return new object[] { new DataClass(), new string[] { "Property" } }; + yield return new object[] { typeof(DataClass), new string[] { "Property" } }; // Lists. - yield return new object[] { new List(), new string[] { "Property"} }; - yield return new object[] { typeof(IList), new string[] { "Property"} }; + yield return new object[] { new List(), new string[] { "Property" } }; + yield return new object[] { typeof(IList), new string[] { "Property" } }; yield return new object[] { new List(), new string[0] }; yield return new object[] { typeof(IList), new string[0] }; // Array. - yield return new object[] { new DataClass[0], new string[] { "Property"} }; - yield return new object[] { typeof(DataClass[]), new string[] { "Property"} }; + yield return new object[] { new DataClass[0], new string[] { "Property" } }; + yield return new object[] { typeof(DataClass[]), new string[] { "Property" } }; yield return new object[] { new object[0], new string[0] }; yield return new object[] { new object[] { new DataClass() }, new string[0] }; @@ -287,7 +287,7 @@ public static IEnumerable GetListItemProperties_Object_TestData() yield return new object[] { new NonEnumerableITypedListImplementor(), new string[] { "Property" } }; yield return new object[] { typeof(NonEnumerableITypedListImplementor), new string[] { "OtherProperty" } }; } - + [Theory] [MemberData(nameof(GetListItemProperties_Object_TestData))] public void ListBindingHelper_GetListItemProperties_InvokeObject_ReturnsExpected(object list, string[] expected) @@ -315,7 +315,7 @@ public void ListBindingHelper_GetListItemProperties_InvokeObject_ReturnsExpected public static IEnumerable GetListItemProperties_Object_PropertyDescriptorArray_TestData() { yield return new object[] { null, TypeDescriptor.GetProperties(typeof(DataClass)).Cast().ToArray(), new string[0] }; - + yield return new object[] { new DataClass(), TypeDescriptor.GetProperties(typeof(DataClass)).Cast().ToArray(), new string[0] }; yield return new object[] { typeof(DataClass), TypeDescriptor.GetProperties(typeof(DataClass)).Cast().ToArray(), new string[0] }; @@ -343,7 +343,7 @@ public static IEnumerable GetListItemProperties_Object_PropertyDescrip yield return new object[] { new IEnumerableWrapper(new ListDataClass[] { null }), descriptors, new string[] { "Property" } }; // Only implements IList. - yield return new object[] { new ArrayList(), descriptors, new string[] { "Property"} }; + yield return new object[] { new ArrayList(), descriptors, new string[] { "Property" } }; yield return new object[] { new ArrayList { new ListDataClass() }, descriptors, new string[] { "Property" } }; yield return new object[] { new ArrayList { new MultiListDataClass() }, inner.Take(0).ToArray(), new string[] { "ParentListProperty" } }; yield return new object[] { new ArrayList { new MultiListDataClass() }, inner.Take(2).ToArray(), new string[] { "Property" } }; @@ -392,7 +392,7 @@ public static IEnumerable GetListItemProperties_Object_PropertyDescrip yield return new object[] { new IEnumerableWrapper(new object[] { new ITypedListDataClass() }), TypeDescriptor.GetProperties(typeof(ITypedListDataClass)).Cast().ToArray(), new string[] { "OtherProperty" } }; yield return new object[] { new IEnumerableWrapper(new object[] { typedListDataClass }), TypeDescriptor.GetProperties(typeof(ITypedListDataClass)).Cast().ToArray(), new string[] { "OtherProperty" } }; yield return new object[] { typeof(ITypedListDataClass[]), TypeDescriptor.GetProperties(typeof(ITypedListDataClass)).Cast().ToArray(), new string[] { "OtherProperty" } }; - + var typedListParent = new ITypedListParent { ListProperty = new EnumerableITypedListImplementor() }; yield return new object[] { new ITypedListParent(), TypeDescriptor.GetProperties(typeof(ITypedListParent)).Cast().ToArray(), new string[] { "OtherProperty" } }; yield return new object[] { typedListParent, TypeDescriptor.GetProperties(typeof(ITypedListParent)).Cast().ToArray(), new string[] { "Property" } }; @@ -465,7 +465,7 @@ public void ListBindingHelper_GetListItemProperties_InvalidListAccessors_ThrowsT public static IEnumerable GetListName_TestData() { yield return new object[] { null, null, string.Empty }; - + var mockTypedList = new Mock(MockBehavior.Strict); mockTypedList.Setup(t => t.GetListName(null)).Returns("Name"); yield return new object[] { mockTypedList.Object, null, "Name" }; diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListBoxTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListBoxTests.cs index 79b1049d0a6..05ef2cbcfb6 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListBoxTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListBoxTests.cs @@ -635,7 +635,7 @@ public static IEnumerable FindString_TestData() yield return new object[] { controlWithItems, null, 1, -1 }; yield return new object[] { controlWithItems, null, 2, -1 }; yield return new object[] { controlWithItems, null, 5, -1 }; - + yield return new object[] { controlWithItems, string.Empty, -1, 0 }; yield return new object[] { controlWithItems, string.Empty, 0, 1 }; yield return new object[] { controlWithItems, string.Empty, 1, 2 }; @@ -739,7 +739,7 @@ public static IEnumerable FindStringExact_TestData() yield return new object[] { controlWithItems, null, 1, -1 }; yield return new object[] { controlWithItems, null, 2, -1 }; yield return new object[] { controlWithItems, null, 5, -1 }; - + yield return new object[] { controlWithItems, string.Empty, -1, 4 }; yield return new object[] { controlWithItems, string.Empty, 0, 4 }; yield return new object[] { controlWithItems, string.Empty, 1, 4 }; diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListControlTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListControlTests.cs index 23db76c5cc1..a76eab22dbb 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListControlTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListControlTests.cs @@ -758,7 +758,7 @@ public void DataSource_SetWithBindingContext_GetReturnsExpected(object value) { BindingContext = context }; - + control.DataSource = value; Assert.Same(value, control.DataSource); Assert.Empty(control.DisplayMember); @@ -795,7 +795,7 @@ public void DataSource_SetWithBindingContextWithDataSource_GetReturnsExpected(ob BindingContext = context, DataSource = new List() }; - + control.DataSource = value; Assert.Same(value, control.DataSource); Assert.Empty(control.DisplayMember); @@ -832,7 +832,7 @@ public void DataSource_SetWithBindingContextWithDisplayMemberCanCreate_GetReturn BindingContext = context, DisplayMember = "Value" }; - + control.DataSource = value; Assert.Same(value, control.DataSource); Assert.Equal("Value", control.DisplayMember); @@ -1035,7 +1035,7 @@ public void DisplayMember_SetWithBindingContext_GetReturnsExpected(string value, { BindingContext = context }; - + control.DisplayMember = value; Assert.Same(expected, control.DisplayMember); Assert.Null(control.DataSource); @@ -1059,7 +1059,7 @@ public void DisplayMember_SetWithBindingContextWithDataSource_GetReturnsExpected BindingContext = context, DataSource = dataSource }; - + control.DisplayMember = value; Assert.Empty(control.DisplayMember); Assert.Same(dataSource, control.DataSource); @@ -1086,7 +1086,7 @@ public void DisplayMember_SetWithBindingContextWithDataSourceCanCreate_GetReturn BindingContext = context, DataSource = dataSource }; - + control.DisplayMember = value; Assert.Equal(expected, control.DisplayMember); Assert.Equal(dataSource, control.DataSource); @@ -1782,9 +1782,9 @@ public void SelectedValue_SetWithMatchingValue_Success(string valueMember) public static IEnumerable SelectedValue_NoMatchingValue_TestData() { yield return new object[] { new List(), "selected" }; - yield return new object[] { new List { new DataClass { Value = "NoSuchValue" }}, string.Empty }; - yield return new object[] { new List { new DataClass { Value = "NoSuchValue" }}, "selected" }; - yield return new object[] { new List { new DataClass { Value = "NoSuchValue" }}, "nosuchvalue" }; + yield return new object[] { new List { new DataClass { Value = "NoSuchValue" } }, string.Empty }; + yield return new object[] { new List { new DataClass { Value = "NoSuchValue" } }, "selected" }; + yield return new object[] { new List { new DataClass { Value = "NoSuchValue" } }, "nosuchvalue" }; } [Theory] @@ -1916,7 +1916,7 @@ public void SelectedValue_SetWithoutValueMember_ThrowsInvalidOperationException( Assert.Equal(0, control.SelectedIndex); Assert.Throws(() => control.SelectedValue); } - + [Theory] [InlineData(Keys.Alt, false)] [InlineData(Keys.Alt | Keys.PageUp, false)] @@ -2745,7 +2745,7 @@ public class SubListControl : ListControl public new void OnBindingContextChanged(EventArgs e) => base.OnBindingContextChanged(e); public new void OnDataSourceChanged(EventArgs e) => base.OnDataSourceChanged(e); - + public new void OnDisplayMemberChanged(EventArgs e) => base.OnDisplayMemberChanged(e); public new void OnFormat(ListControlConvertEventArgs e) => base.OnFormat(e); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewGroupCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewGroupCollectionTests.cs index 45aaa5941fc..d4b8e348723 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewGroupCollectionTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewGroupCollectionTests.cs @@ -274,7 +274,7 @@ public void ListViewGroupCollection_Item_GetStringExists_ReturnsExpected(string group2.Name = "text"; collection.Add(group1); collection.Add(group2); - + Assert.Equal(collection[expectedIndex], collection[key]); } @@ -293,7 +293,7 @@ public void ListViewGroupCollection_Item_GetNoSuchString_ReturnsNull(string key) group2.Name = "text"; collection.Add(group1); collection.Add(group2); - + Assert.Null(collection[key]); } @@ -317,7 +317,7 @@ public void ListViewGroupCollection_Item_SetStringExists_GetReturnsExpected(stri group2.Name = "text"; collection.Add(group1); collection.Add(group2); - + var group3 = new ListViewGroup(); collection[key] = group3; Assert.Same(group3, collection[expectedIndex]); @@ -338,7 +338,7 @@ public void ListViewGroupCollection_Item_SetNoSuchString_Nop(string key) group2.Name = "text"; collection.Add(group1); collection.Add(group2); - + var group3 = new ListViewGroup(); collection[key] = group3; Assert.Same(group1, collection[0]); @@ -375,7 +375,7 @@ public void ListViewGroupCollection_Add_ListViewGroup_Success() // Add another. var group2 = new ListViewGroup(); Assert.Equal(1, collection.Add(group2)); - Assert.Equal(new ListViewGroup[] { group1, group2 } , collection.Cast()); + Assert.Equal(new ListViewGroup[] { group1, group2 }, collection.Cast()); Assert.Same(listView, group2.ListView); } @@ -394,7 +394,7 @@ public void ListViewGroupCollection_Add_ListViewGroupWithHandle_Success() // Add another. var group2 = new ListViewGroup(); Assert.Equal(1, collection.Add(group2)); - Assert.Equal(new ListViewGroup[] { group1, group2 } , collection.Cast()); + Assert.Equal(new ListViewGroup[] { group1, group2 }, collection.Cast()); Assert.Same(listView, group2.ListView); } @@ -642,7 +642,7 @@ public void ListViewGroupCollection_Contains_Invoke_ReturnsExpected() ListViewGroupCollection collection = listView.Groups; var group = new ListViewGroup(); collection.Add(group); - + Assert.True(collection.Contains(group)); Assert.False(collection.Contains(new ListViewGroup())); Assert.False(collection.Contains(null)); @@ -653,7 +653,7 @@ public void ListViewGroupCollection_Contains_Empty_ReturnsFalse() { var listView = new ListView(); ListViewGroupCollection collection = listView.Groups; - + Assert.False(collection.Contains(new ListViewGroup())); Assert.False(collection.Contains(null)); } @@ -665,7 +665,7 @@ public void ListViewGroupCollection_IListContains_Invoke_ReturnsExpected() IList collection = listView.Groups; var group = new ListViewGroup(); collection.Add(group); - + Assert.True(collection.Contains(group)); Assert.False(collection.Contains(new ListViewGroup())); Assert.False(collection.Contains(new object())); @@ -677,7 +677,7 @@ public void ListViewGroupCollection_IListContains_Empty_ReturnsFalse() { var listView = new ListView(); IList collection = listView.Groups; - + Assert.False(collection.Contains(new ListViewGroup())); Assert.False(collection.Contains(new object())); Assert.False(collection.Contains(null)); @@ -690,7 +690,7 @@ public void ListViewGroupCollection_IndexOf_Invoke_ReturnsExpected() ListViewGroupCollection collection = listView.Groups; var group = new ListViewGroup(); collection.Add(group); - + Assert.Equal(0, collection.IndexOf(group)); Assert.Equal(-1, collection.IndexOf(new ListViewGroup())); Assert.Equal(-1, collection.IndexOf(null)); @@ -701,7 +701,7 @@ public void ListViewGroupCollection_IndexOf_Empty_ReturnsFalse() { var listView = new ListView(); ListViewGroupCollection collection = listView.Groups; - + Assert.Equal(-1, collection.IndexOf(new ListViewGroup())); Assert.Equal(-1, collection.IndexOf(null)); } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewGroupConverterTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewGroupConverterTests.cs index 546dbbeaae7..c97e43e7b84 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewGroupConverterTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewGroupConverterTests.cs @@ -29,10 +29,10 @@ public void ListViewGroupConverter_CanConvertFrom_Invoke_ReturnsExpected(Type so public static IEnumerable CanConvertFrom_Context_TestData() { - yield return new object [] { null, false }; - yield return new object [] { new object(), false }; - yield return new object [] { new ListViewItem(), true }; - + yield return new object[] { null, false }; + yield return new object[] { new object(), false }; + yield return new object[] { new ListViewItem(), true }; + var listView = new ListView(); var item1 = new ListViewItem(); listView.Items.Add(item1); @@ -142,10 +142,10 @@ public void ListViewGroupConverter_CanConvertTo_Invoke_ReturnsExpected(Type dest public static IEnumerable CanConvertTo_Context_TestData() { - yield return new object [] { null, true }; - yield return new object [] { new object(), true }; - yield return new object [] { new ListViewItem(), true }; - + yield return new object[] { null, true }; + yield return new object[] { new object(), true }; + yield return new object[] { new ListViewItem(), true }; + var listView = new ListView(); var item1 = new ListViewItem(); listView.Items.Add(item1); @@ -258,10 +258,10 @@ public void ListViewGroupConverter_GetProperties_Invoke_ReturnsNull() public static IEnumerable GetStandardValues_TestData() { - yield return new object [] { null, null }; - yield return new object [] { new object(), null }; - yield return new object [] { new ListViewItem(), null }; - + yield return new object[] { null, null }; + yield return new object[] { new object(), null }; + yield return new object[] { new ListViewItem(), null }; + var listView = new ListView(); var item1 = new ListViewItem(); listView.Items.Add(item1); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewGroupTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewGroupTests.cs index 539d12bdd7b..3df8b52d5c6 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewGroupTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewGroupTests.cs @@ -222,7 +222,7 @@ public void ListViewGroup_Serialize_Deserialize_Success(ListViewGroup group) var formatter = new BinaryFormatter(); formatter.Serialize(stream, group); stream.Seek(0, SeekOrigin.Begin); - + ListViewGroup result = Assert.IsType(formatter.Deserialize(stream)); Assert.Equal(group.Header, result.Header); Assert.Equal(group.HeaderAlignment, result.HeaderAlignment); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewInsertionMarkTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewInsertionMarkTests.cs index 4a0dba15ba8..80b9c8ce3d4 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewInsertionMarkTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewInsertionMarkTests.cs @@ -28,7 +28,7 @@ public void ListViewInsertionMark_AppearsAfterItem_SetWithHandle_ReturnsExpected // Set true. insertionMark.AppearsAfterItem = true; Assert.True(insertionMark.AppearsAfterItem); - + // Set again to test caching behaviour. insertionMark.AppearsAfterItem = true; Assert.True(insertionMark.AppearsAfterItem); @@ -52,7 +52,7 @@ public void ListViewInsertionMark_AppearsAfterItem_SetWithoutHandle_ReturnsExpec // Set true. insertionMark.AppearsAfterItem = true; Assert.True(insertionMark.AppearsAfterItem); - + // Set again to test caching behaviour. insertionMark.AppearsAfterItem = true; Assert.True(insertionMark.AppearsAfterItem); @@ -88,7 +88,7 @@ public void Color_SetWithHandle_ReturnsExpected(Color value) ListViewInsertionMark insertionMark = listView.InsertionMark; insertionMark.Color = value; Assert.Equal(value, insertionMark.Color); - + // Set again to test caching behaviour. insertionMark.Color = value; Assert.Equal(value, insertionMark.Color); @@ -102,7 +102,7 @@ public void ListViewInsertionMark_Color_SetWithoutHandle_ReturnsExpected(Color v ListViewInsertionMark insertionMark = listView.InsertionMark; insertionMark.Color = value; Assert.Equal(value, insertionMark.Color); - + // Set again to test caching behaviour. insertionMark.Color = value; Assert.Equal(value, insertionMark.Color); @@ -126,7 +126,7 @@ public void ListViewInsertionMark_Index_SetWithHandle_GetReturnsExpected(int val ListViewInsertionMark insertionMark = listView.InsertionMark; insertionMark.Index = value; Assert.Equal(value, insertionMark.Index); - + // Set again to test caching behaviour. insertionMark.Index = value; Assert.Equal(value, insertionMark.Index); @@ -140,7 +140,7 @@ public void ListViewInsertionMark_Index_SetWithoutHandle_GetReturnsExpected(int ListViewInsertionMark insertionMark = listView.InsertionMark; insertionMark.Index = value; Assert.Equal(value, insertionMark.Index); - + // Set again to test caching behaviour. insertionMark.Index = value; Assert.Equal(value, insertionMark.Index); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewItemTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewItemTests.cs index 4ad90d40048..3cb9f37f6f1 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewItemTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewItemTests.cs @@ -580,7 +580,7 @@ public static IEnumerable Ctor_StringArray_Int_TestData() yield return new object[] { null, -1, string.Empty }; yield return new object[] { new string[0], 0, string.Empty }; yield return new object[] { new string[] { null }, 1, string.Empty }; - yield return new object[] { new string[] { "text" }, 2, "text" }; + yield return new object[] { new string[] { "text" }, 2, "text" }; } [Theory] diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemCollectionTests.cs index 65bd5be2268..32875dcc4a6 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemCollectionTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemCollectionTests.cs @@ -165,7 +165,7 @@ public void ListViewSubItemCollection_Item_GetString_ReturnsExpected(string key, subItem2.Name = "text"; collection.Add(subItem1); collection.Add(subItem2); - + Assert.Equal(expectedIndex != -1 ? collection[expectedIndex] : null, collection[key]); } @@ -439,7 +439,7 @@ public void ListViewSubItemCollection_Contains_Invoke_ReturnsExpected() var collection = new ListViewItem.ListViewSubItemCollection(item); var subItem = new ListViewItem.ListViewSubItem(); collection.Add(subItem); - + Assert.True(collection.Contains(subItem)); Assert.False(collection.Contains(new ListViewItem.ListViewSubItem())); Assert.False(collection.Contains(null)); @@ -450,7 +450,7 @@ public void ListViewSubItemCollection_Contains_Empty_ReturnsFalse() { var item = new ListViewItem(); var collection = new ListViewItem.ListViewSubItemCollection(item); - + Assert.False(collection.Contains(new ListViewItem.ListViewSubItem())); Assert.False(collection.Contains(null)); } @@ -472,7 +472,7 @@ public void ListViewSubItemCollection_ContainsKey_Invoke_ReturnsExpected(string subItem2.Name = "text"; collection.Add(subItem1); collection.Add(subItem2); - + Assert.Equal(expected, collection.ContainsKey(key)); } @@ -481,7 +481,7 @@ public void ListViewSubItemCollection_ContainsKey_Empty_ReturnsFalse() { var item = new ListViewItem(); var collection = new ListViewItem.ListViewSubItemCollection(item); - + Assert.False(collection.ContainsKey("text")); Assert.False(collection.ContainsKey(null)); } @@ -493,7 +493,7 @@ public void ListViewSubItemCollection_IListContains_Invoke_ReturnsExpected() IList collection = new ListViewItem.ListViewSubItemCollection(item); var subItem = new ListViewItem.ListViewSubItem(); collection.Add(subItem); - + Assert.True(collection.Contains(subItem)); Assert.False(collection.Contains(new ListViewItem.ListViewSubItem())); Assert.False(collection.Contains(new object())); @@ -505,7 +505,7 @@ public void ListViewSubItemCollection_IListContains_Empty_ReturnsFalse() { var item = new ListViewItem(); IList collection = new ListViewItem.ListViewSubItemCollection(item); - + Assert.False(collection.Contains(new ListViewItem.ListViewSubItem())); Assert.False(collection.Contains(new object())); Assert.False(collection.Contains(null)); @@ -518,7 +518,7 @@ public void ListViewSubItemCollection_IndexOf_Invoke_ReturnsExpected() var collection = new ListViewItem.ListViewSubItemCollection(item); var subItem = new ListViewItem.ListViewSubItem(); collection.Add(subItem); - + Assert.Equal(0, collection.IndexOf(subItem)); Assert.Equal(-1, collection.IndexOf(new ListViewItem.ListViewSubItem())); Assert.Equal(-1, collection.IndexOf(null)); @@ -529,7 +529,7 @@ public void ListViewSubItemCollection_IndexOf_Empty_ReturnsFalse() { var item = new ListViewItem(); var collection = new ListViewItem.ListViewSubItemCollection(item); - + Assert.Equal(-1, collection.IndexOf(new ListViewItem.ListViewSubItem())); Assert.Equal(-1, collection.IndexOf(null)); } @@ -551,7 +551,7 @@ public void ListViewSubItemCollection_IndexOfKey_Invoke_ReturnsExpected(string k subItem2.Name = "text"; collection.Add(subItem1); collection.Add(subItem2); - + Assert.Equal(expected, collection.IndexOfKey(key)); // Call again to validate caching behaviour. @@ -564,7 +564,7 @@ public void ListViewSubItemCollection_IndexOfKey_Empty_ReturnsFalse() { var item = new ListViewItem(); var collection = new ListViewItem.ListViewSubItemCollection(item); - + Assert.Equal(-1, collection.IndexOfKey("text")); Assert.Equal(-1, collection.IndexOf(null)); } @@ -576,7 +576,7 @@ public void ListViewSubItemCollection_IListIndexOf_Invoke_ReturnsExpected() IList collection = new ListViewItem.ListViewSubItemCollection(item); var subItem = new ListViewItem.ListViewSubItem(); collection.Add(subItem); - + Assert.Equal(0, collection.IndexOf(subItem)); Assert.Equal(-1, collection.IndexOf(new ListViewItem.ListViewSubItem())); Assert.Equal(-1, collection.IndexOf(new object())); @@ -588,7 +588,7 @@ public void ListViewSubItemCollection_IListIndexOf_Empty_ReturnsMinusOne() { var item = new ListViewItem(); IList collection = new ListViewItem.ListViewSubItemCollection(item); - + Assert.Equal(-1, collection.IndexOf(new ListViewItem.ListViewSubItem())); Assert.Equal(-1, collection.IndexOf(new object())); Assert.Equal(-1, collection.IndexOf(null)); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemTests.cs index 6429a188745..26ee48dd8d5 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemTests.cs @@ -110,7 +110,7 @@ public void ListViewSubItem_BackColor_Set_GetReturnsExpected(Color value, Color BackColor = value }; Assert.Equal(expected, subItem.BackColor); - + // Set same. subItem.BackColor = value; Assert.Equal(expected, subItem.BackColor); @@ -157,7 +157,7 @@ public void ListViewSubItem_Font_Set_GetReturnsExpected(Font value) Font = value }; Assert.Equal(value ?? Control.DefaultFont, subItem.Font); - + // Set same. subItem.Font = value; Assert.Equal(value ?? Control.DefaultFont, subItem.Font); @@ -192,7 +192,7 @@ public void ListViewSubItem_ForeColor_Set_GetReturnsExpected(Color value, Color ForeColor = value }; Assert.Equal(expected, subItem.ForeColor); - + // Set same. subItem.ForeColor = value; Assert.Equal(expected, subItem.ForeColor); @@ -302,7 +302,7 @@ public void ListViewSubItem_ResetStyle_NoStyle_Nop(ListViewItem owner) public void ListViewSubItem_ResetStyle_HasStyleWithOwner_Success(ListViewItem owner) { var subItem = new ListViewItem.ListViewSubItem(owner, "text", Color.Red, Color.Blue, SystemFonts.MenuFont); - + subItem.ResetStyle(); Assert.Equal(SystemColors.Window, subItem.BackColor); Assert.Equal(Control.DefaultFont, subItem.Font); @@ -329,7 +329,7 @@ public void ListViewSubItem_Serialize_Deserialize_Success(ListViewItem.ListViewS var formatter = new BinaryFormatter(); formatter.Serialize(stream, subItem); stream.Seek(0, SeekOrigin.Begin); - + ListViewItem.ListViewSubItem result = Assert.IsType(formatter.Deserialize(stream)); Assert.Equal(subItem.BackColor, result.BackColor); Assert.Equal(subItem.Font, result.Font); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/MaskInputRejectedEventArgsTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/MaskInputRejectedEventArgsTests.cs index 86dc9399737..3d9a2763262 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/MaskInputRejectedEventArgsTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/MaskInputRejectedEventArgsTests.cs @@ -13,7 +13,7 @@ public class MaskInputRejectedEventArgsTests [InlineData(-2, MaskedTextResultHint.Unknown)] [InlineData(-1, MaskedTextResultHint.Success)] [InlineData(0, MaskedTextResultHint.PromptCharNotAllowed)] - [InlineData(1,(MaskedTextResultHint)(MaskedTextResultHint.SignedDigitExpected - 1))] + [InlineData(1, (MaskedTextResultHint)(MaskedTextResultHint.SignedDigitExpected - 1))] [InlineData(1, MaskedTextResultHint.Unknown)] public void Ctor_Int_Int_Bool(int position, MaskedTextResultHint rejectionHint) { diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/PaddingConverterTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/PaddingConverterTests.cs index d29e65305c7..5afa46e9937 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/PaddingConverterTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/PaddingConverterTests.cs @@ -303,7 +303,7 @@ public static IEnumerable CreateInstance_InvalidPropertyValueType_Test {nameof(Padding.Bottom), 4} } }; - + yield return new object[] { new Dictionary diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/PaddingTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/PaddingTests.cs index 8ced8d2e348..9147f516581 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/PaddingTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/PaddingTests.cs @@ -102,7 +102,7 @@ public void Padding_AllPropertyDescriptor_ResetValue_SetsToZero() Assert.False(property.CanResetValue(boxedPadding)); Assert.False(property.ShouldSerializeValue(boxedPadding)); property.ResetValue(boxedPadding); - + Assert.Equal(0, ((Padding)boxedPadding).All); Assert.Equal(0, ((Padding)boxedPadding).Left); Assert.Equal(0, ((Padding)boxedPadding).Top); @@ -122,7 +122,7 @@ public void Padding_AllPropertyDescriptor_ResetValueOnAll_SetsToZero() Assert.True(property.CanResetValue(boxedPadding)); Assert.True(property.ShouldSerializeValue(boxedPadding)); property.ResetValue(boxedPadding); - + Assert.Equal(0, ((Padding)boxedPadding).All); Assert.Equal(0, ((Padding)boxedPadding).Left); Assert.Equal(0, ((Padding)boxedPadding).Top); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/PropertyManagerTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/PropertyManagerTests.cs index cbaccbd01c4..6dd5121bb56 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/PropertyManagerTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/PropertyManagerTests.cs @@ -175,7 +175,7 @@ public void PropertyManager_EndCurrentEdit_IEditableObjectCurrent_CallsEndEdit() // { // e.Cancel = cancel; // }; - + // cancelBinding.BindingComplete += bindingCompleteHandler; // controlBindings.Add(cancelBinding); // manager.Bindings.Add(cancelBinding); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/RowStyleTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/RowStyleTests.cs index 3f00e47ea96..94ebd08f080 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/RowStyleTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/RowStyleTests.cs @@ -65,7 +65,7 @@ public void RowStyle_Height_SetOwned_GetReturnsExpected(float value) var panel = new TableLayoutPanel(); var style = new RowStyle(); panel.LayoutSettings.RowStyles.Add(style); - + style.Height = value; Assert.Equal(value, style.Height); } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ScrollableControlTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ScrollableControlTests.cs index 4de90798b8f..10988121ade 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ScrollableControlTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ScrollableControlTests.cs @@ -529,7 +529,7 @@ public static IEnumerable ScrollControlIntoView_TestData() yield return new object[] { false, true, true, new Size(70, 80), null, new Rectangle(0, 0, 70, 80) }; yield return new object[] { true, true, true, new Size(70, 80), new Control(), new Rectangle(0, 0, 70, 80) }; - + // Can't scroll - not AutoScroll. yield return new object[] { false, true, true, new Size(70, 80), new LargeControl(), new Rectangle(0, 0, 70, 80) }; @@ -602,11 +602,11 @@ private class SmallControl : Control public class SubScrollableControl : ScrollableControl { public new const int ScrollStateAutoScrolling = ScrollableControl.ScrollStateAutoScrolling; - + public new const int ScrollStateHScrollVisible = ScrollableControl.ScrollStateHScrollVisible; - + public new const int ScrollStateVScrollVisible = ScrollableControl.ScrollStateVScrollVisible; - + public new const int ScrollStateUserHasScrolled = ScrollableControl.ScrollStateUserHasScrolled; public new const int ScrollStateFullDrag = ScrollableControl.ScrollStateFullDrag; diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/SearchForVirtualItemEventArgsTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/SearchForVirtualItemEventArgsTests.cs index efbec69435f..1ea28ca0892 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/SearchForVirtualItemEventArgsTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/SearchForVirtualItemEventArgsTests.cs @@ -12,7 +12,7 @@ public class SearchForVirtualItemEventArgsTests { public static IEnumerable Ctor_Bool_Bool_Bool_String_Point_SearchDirectionHint_Int_TestData() { - yield return new object[] { true, false, true, null, Point.Empty, (SearchDirectionHint)(SearchDirectionHint.Down + 1 ), -2 }; + yield return new object[] { true, false, true, null, Point.Empty, (SearchDirectionHint)(SearchDirectionHint.Down + 1), -2 }; yield return new object[] { false, true, false, "", new Point(1, 2), SearchDirectionHint.Down, -1 }; yield return new object[] { false, true, false, "text", new Point(-1, -2), SearchDirectionHint.Down, 0 }; yield return new object[] { false, true, false, "text", new Point(1, 2), SearchDirectionHint.Down, 1 }; diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/SpecialFolderEnumConverterTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/SpecialFolderEnumConverterTests.cs index edc3470c113..d949df81846 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/SpecialFolderEnumConverterTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/SpecialFolderEnumConverterTests.cs @@ -96,7 +96,7 @@ public void SpecialFolderEnumConverter_GetStandardValues_NonSpecialFolderType_Re private TypeConverter GetNewSpecialFolderEnumConverter() { PropertyDescriptor descriptor = TypeDescriptor.GetProperties(new FolderBrowserDialog()).Find(nameof(FolderBrowserDialog.RootFolder), ignoreCase: false); - return (TypeConverter)Activator.CreateInstance(descriptor.Converter.GetType(), new Type[] { typeof(Environment.SpecialFolder )}); + return (TypeConverter)Activator.CreateInstance(descriptor.Converter.GetType(), new Type[] { typeof(Environment.SpecialFolder) }); } private class CustomReflectionType diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TableLayoutColumnStyleCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TableLayoutColumnStyleCollectionTests.cs index 437402edf49..320f5d60a39 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TableLayoutColumnStyleCollectionTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TableLayoutColumnStyleCollectionTests.cs @@ -29,7 +29,7 @@ public void TableLayoutColumnStyleCollection_Add_RowStyle_ThrowsInvalidCastExcep TableLayoutColumnStyleCollection collection = settings.ColumnStyles; var style = new RowStyle(); - Assert.Throws< InvalidCastException>(() => collection.Add(style)); + Assert.Throws(() => collection.Add(style)); Assert.Equal(style, Assert.Single(collection)); } @@ -43,7 +43,7 @@ public void TableLayoutColumnStyleCollection_Insert_ColumnStyle_Success() var style = new ColumnStyle(); collection.Insert(0, style); Assert.Equal(style, Assert.Single(collection)); - } + } [Fact] public void TableLayoutColumnStyleCollection_Item_SetColumnStyle_GetReturnsExpected() diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TableLayoutRowStyleCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TableLayoutRowStyleCollectionTests.cs index ceec02e0e75..7791735d65d 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TableLayoutRowStyleCollectionTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TableLayoutRowStyleCollectionTests.cs @@ -43,7 +43,7 @@ public void TableLayoutRowStyleCollection_Insert_RowStyle_Success() var style = new RowStyle(); collection.Insert(0, style); Assert.Equal(style, Assert.Single(collection)); - } + } [Fact] public void TableLayoutRowStyleCollection_Item_SetRowStyle_GetReturnsExpected() diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TableLayoutStyleCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TableLayoutStyleCollectionTests.cs index 8bdd493d465..c4b4ff2637c 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TableLayoutStyleCollectionTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TableLayoutStyleCollectionTests.cs @@ -197,7 +197,7 @@ public void TableLayoutStyleCollection_Remove_Object_Success() collection.Add(style); Assert.Equal(style, Assert.Single(collection)); } - + [Fact] public void TableLayoutStyleCollection_Remove_Null_Nop() { @@ -289,7 +289,7 @@ public void TableLayoutStyleCollection_CopyTo_Invoke_Success() var style = new RowStyle(); collection.Add(style); - var array = new object[] { 1, 2, 3}; + var array = new object[] { 1, 2, 3 }; collection.CopyTo(array, 1); Assert.Equal(new object[] { 1, style, 3 }, array); } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TableLayoutStyleTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TableLayoutStyleTests.cs index 73a1f2f82e4..f235e59bdb3 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TableLayoutStyleTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TableLayoutStyleTests.cs @@ -40,7 +40,7 @@ public void TableLayoutStyle_SizeType_SetOwned_GetReturnsExpected(SizeType value var panel = new TableLayoutPanel(); var style = new ColumnStyle(); panel.LayoutSettings.RowStyles.Add(style); - + style.SizeType = value; Assert.Equal(value, style.SizeType); } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TimerTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TimerTests.cs index 0e62171978f..f8d07baee66 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TimerTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TimerTests.cs @@ -126,7 +126,7 @@ public void Timer_Interval_SetStarted_GetReturnsExpected(int value) { var timer = new Timer(); timer.Start(); - + timer.Interval = value; Assert.Equal(value, timer.Interval); @@ -143,7 +143,7 @@ public void Timer_Interval_SetStopped_GetReturnsExpected(int value) var timer = new Timer(); timer.Start(); timer.Stop(); - + timer.Interval = value; Assert.Equal(value, timer.Interval); @@ -259,7 +259,7 @@ public void Timer_Start_Stop_Success(bool designMode) // Start timer.Start(); Assert.True(timer.Enabled); - + // Stop. timer.Stop(); Assert.False(timer.Enabled); @@ -280,7 +280,7 @@ public void Timer_Start_MultipleTimes_Success(bool designMode) // Start timer.Start(); Assert.True(timer.Enabled); - + // Start again. timer.Start(); Assert.True(timer.Enabled); @@ -301,7 +301,7 @@ public void Timer_Stop_Restart_Success(bool designMode) // Start timer.Start(); Assert.True(timer.Enabled); - + // Stop. timer.Stop(); Assert.False(timer.Enabled); @@ -330,7 +330,7 @@ public void Timer_Stop_MultipleTimes_Success(bool designMode) // Start timer.Start(); Assert.True(timer.Enabled); - + // Stop. timer.Stop(); Assert.False(timer.Enabled); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripItemImageRenderEventArgsTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripItemImageRenderEventArgsTests.cs index e28b1d231de..a8fcfc5744a 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripItemImageRenderEventArgsTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripItemImageRenderEventArgsTests.cs @@ -26,14 +26,14 @@ public static IEnumerable Ctor_Graphics_ToolStripItem_Rectangle_TestDa Image = image }, new Rectangle(1, 2, 3, 4) }; - yield return new object[] - { + yield return new object[] + { graphics, new ToolStripButton { RightToLeftAutoMirrorImage = true, Image = image }, new Rectangle(1, 2, 3, 4) - }; + }; yield return new object[] { graphics, new ToolStripButton diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripItemRenderEventArgsTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripItemRenderEventArgsTests.cs index dff4ac408b9..b08f1116025 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripItemRenderEventArgsTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripItemRenderEventArgsTests.cs @@ -17,7 +17,7 @@ public static IEnumerable Ctor_Graphics_ToolStripItem_TestData() yield return new object[] { null, null, null }; yield return new object[] { graphics, new ToolStripButton(), null }; - + var toolStripItem = new ToolStripButton(); var toolStrip = new ToolStrip(); toolStrip.Items.Add(toolStripItem); 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 a1061963366..0b7ab816adb 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 @@ -72,7 +72,7 @@ public void ToolStripItem_Ctor_Default() public static IEnumerable Ctor_String_Image_EventHandler_TestData() { - EventHandler onClick = (sender, e) => {}; + EventHandler onClick = (sender, e) => { }; yield return new object[] { null, null, null }; yield return new object[] { string.Empty, new Bitmap(10, 10), onClick }; @@ -138,7 +138,7 @@ public void ToolStripItem_Ctor_String_Image_EventHandler(string text, Image imag public static IEnumerable Ctor_String_Image_EventHandler_String_TestData() { - EventHandler onClick = (sender, e) => {}; + EventHandler onClick = (sender, e) => { }; yield return new object[] { null, null, null, null, string.Empty }; yield return new object[] { string.Empty, new Bitmap(10, 10), onClick, string.Empty, string.Empty }; @@ -1140,7 +1140,7 @@ public void ToolStripItem_ForeColor_SetWithParent_GetReturnsExpected(Color value { Parent = parent }; - + item.ForeColor = value; Assert.Equal(expected, item.ForeColor); @@ -1437,10 +1437,10 @@ public static IEnumerable ImageTransparentColor_TestData() { foreach (Color color in new Color[] { Color.Empty, Color.Red }) { - yield return new object[] { null, color }; - yield return new object[] { new Bitmap(10, 10), color }; - yield return new object[] { Image.FromFile(Path.Combine("bitmaps", "nature24bits.gif")), color }; - yield return new object[] { Image.FromFile(Path.Combine("bitmaps", "10x16_one_entry_32bit.ico")), color }; + yield return new object[] { null, color }; + yield return new object[] { new Bitmap(10, 10), color }; + yield return new object[] { Image.FromFile(Path.Combine("bitmaps", "nature24bits.gif")), color }; + yield return new object[] { Image.FromFile(Path.Combine("bitmaps", "10x16_one_entry_32bit.ico")), color }; } } @@ -4103,7 +4103,7 @@ public static IEnumerable Select_TestData() { yield return new object[] { new SubToolStripItem(), true }; yield return new object[] { new CannotSelectToolStripItem(), false }; - + var toolStrip = new ToolStrip(); var toolStripItem = new SubToolStripItem(); toolStrip.Items.Add(toolStripItem); @@ -4126,7 +4126,7 @@ public static IEnumerable Select_TestData() Parent = toolStripDropDown }; yield return new object[] { toolStripDropDownParentItem, true }; - + var toolStripDropDownWithOwnerItemOwnerItem = new SubToolStripItem(); var toolStripDropDownWithOwnerItem = new ToolStripDropDown { diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripItemTextRenderEventArgsTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripItemTextRenderEventArgsTests.cs index 6d1984c5aee..5cfc92e24e8 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripItemTextRenderEventArgsTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripItemTextRenderEventArgsTests.cs @@ -42,7 +42,7 @@ public static IEnumerable Ctor_Graphics_ToolStripItem_String_Rectangle yield return new object[] { graphics, new ToolStripButton(), null, Rectangle.Empty, Color.Empty, null, (ContentAlignment)(ContentAlignment.TopLeft - 1), TextFormatFlags.Default | TextFormatFlags.Top | TextFormatFlags.HidePrefix }; yield return new object[] { graphics, new ToolStripButton(), "", new Rectangle(1, 2, 3, 4), Color.Red, SystemFonts.DefaultFont, ContentAlignment.MiddleCenter, TextFormatFlags.Default | TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.HidePrefix }; - yield return new object[] { graphics, new ToolStripButton(), "", new Rectangle(1, 2, 3, 4), Color.Red, SystemFonts.DefaultFont, ContentAlignment.BottomRight, TextFormatFlags.Default | TextFormatFlags.Bottom | TextFormatFlags.Right | TextFormatFlags.HidePrefix }; + yield return new object[] { graphics, new ToolStripButton(), "", new Rectangle(1, 2, 3, 4), Color.Red, SystemFonts.DefaultFont, ContentAlignment.BottomRight, TextFormatFlags.Default | TextFormatFlags.Bottom | TextFormatFlags.Right | TextFormatFlags.HidePrefix }; yield return new object[] { graphics, new ToolStripButton() { RightToLeft = RightToLeft.Yes }, "text", new Rectangle(1, 2, 3, 4), Color.Red, SystemFonts.DefaultFont, (ContentAlignment)(-1), TextFormatFlags.Default | TextFormatFlags.Bottom | TextFormatFlags.Right | TextFormatFlags.RightToLeft | TextFormatFlags.HidePrefix }; } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripPanelTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripPanelTests.cs index 3ff0a796ac1..014ecaf5c7c 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripPanelTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripPanelTests.cs @@ -119,7 +119,7 @@ public void AutoSize_Set_GetReturnsExpected(bool value) AutoSize = value }; Assert.Equal(value, panel.AutoSize); - + // Set same. panel.AutoSize = value; Assert.Equal(value, panel.AutoSize); @@ -169,7 +169,7 @@ public void RowMargin_Set_GetReturnsExpected(Padding value) RowMargin = value }; Assert.Equal(value, panel.RowMargin); - + // Set same. panel.RowMargin = value; Assert.Equal(value, panel.RowMargin); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripRenderEventArgsTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripRenderEventArgsTests.cs index 9957f358178..2489b25efcd 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripRenderEventArgsTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripRenderEventArgsTests.cs @@ -96,7 +96,7 @@ public static IEnumerable ConnectedArea_Empty_TestData() yield return new object[] { new ToolStripDropDown() }; yield return new object[] { new ToolStripOverflow(new ToolStripButton()) }; yield return new object[] { new ToolStripOverflow(new ToolStripDropDownButton()) }; - + var ownedDropDownItem = new ToolStripDropDownButton(); var owner = new ToolStrip(); owner.Items.Add(ownedDropDownItem); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripTests.cs index e4eb91b7da2..ab2f034df4d 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ToolStripTests.cs @@ -23,7 +23,7 @@ public void ToolStrip_Constructor() Assert.False(ts.TabStop); Assert.False(ts.MenuAutoExpand); Assert.NotNull(ToolStripManager.ToolStrips); - Assert.True(ToolStripManager.ToolStrips.Contains(ts)); + Assert.True(ToolStripManager.ToolStrips.Contains(ts)); Assert.True(ts.AutoSize); Assert.False(ts.CausesValidation); Assert.Equal(100, ts.Size.Width); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TreeViewCancelEventArgsTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TreeViewCancelEventArgsTests.cs index 803a5d7bd5c..5dcc2dd6d41 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TreeViewCancelEventArgsTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TreeViewCancelEventArgsTests.cs @@ -11,7 +11,7 @@ public class TreeViewCancelEventArgsTests { public static IEnumerable Ctor_TreeNode_Bool_TreeViewAction_TestData() { - yield return new object[] { null, false, (TreeViewAction)(TreeViewAction.Unknown -1) }; + yield return new object[] { null, false, (TreeViewAction)(TreeViewAction.Unknown - 1) }; yield return new object[] { new TreeNode(), true, TreeViewAction.ByKeyboard }; } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TreeViewEventArgsTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TreeViewEventArgsTests.cs index 9cafe667c3d..2f35b8683ee 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TreeViewEventArgsTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/TreeViewEventArgsTests.cs @@ -26,7 +26,7 @@ public void Ctor_TreeNode(TreeNode node) public static IEnumerable Ctor_TreeNode_TreeViewAction_TestData() { - yield return new object[] { null, (TreeViewAction)(TreeViewAction.Unknown -1) }; + yield return new object[] { null, (TreeViewAction)(TreeViewAction.Unknown - 1) }; yield return new object[] { new TreeNode(), TreeViewAction.ByKeyboard }; } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/VisualStyles/TextMetricsTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/VisualStyles/TextMetricsTests.cs index 2e5da67465f..ee5b9f6a66a 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/VisualStyles/TextMetricsTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/VisualStyles/TextMetricsTests.cs @@ -1,4 +1,4 @@ - // Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. @@ -43,7 +43,7 @@ public void TextMetrics_Ascent_Set_GetReturnsExpected(int value) Ascent = value }; Assert.Equal(value, metric.Ascent); - + // Set same. metric.Ascent = value; Assert.Equal(value, metric.Ascent); @@ -58,7 +58,7 @@ public void TextMetrics_AverageCharWidth_Set_GetReturnsExpected(int value) AverageCharWidth = value }; Assert.Equal(value, metric.AverageCharWidth); - + // Set same. metric.AverageCharWidth = value; Assert.Equal(value, metric.AverageCharWidth); @@ -73,7 +73,7 @@ public void TextMetrics_BreakChar_Set_GetReturnsExpected(char value) BreakChar = value }; Assert.Equal(value, metric.BreakChar); - + // Set same. metric.BreakChar = value; Assert.Equal(value, metric.BreakChar); @@ -89,7 +89,7 @@ public void TextMetrics_CharSet_Set_GetReturnsExpected(TextMetricsCharacterSet v CharSet = value }; Assert.Equal(value, metric.CharSet); - + // Set same. metric.CharSet = value; Assert.Equal(value, metric.CharSet); @@ -104,7 +104,7 @@ public void TextMetrics_DefaultChar_Set_GetReturnsExpected(char value) DefaultChar = value }; Assert.Equal(value, metric.DefaultChar); - + // Set same. metric.DefaultChar = value; Assert.Equal(value, metric.DefaultChar); @@ -119,7 +119,7 @@ public void TextMetrics_Descent_Set_GetReturnsExpected(int value) Descent = value }; Assert.Equal(value, metric.Descent); - + // Set same. metric.Descent = value; Assert.Equal(value, metric.Descent); @@ -134,7 +134,7 @@ public void TextMetrics_DigitizedAspectX_Set_GetReturnsExpected(int value) DigitizedAspectX = value }; Assert.Equal(value, metric.DigitizedAspectX); - + // Set same. metric.DigitizedAspectX = value; Assert.Equal(value, metric.DigitizedAspectX); @@ -149,7 +149,7 @@ public void TextMetrics_DigitizedAspectY_Set_GetReturnsExpected(int value) DigitizedAspectY = value }; Assert.Equal(value, metric.DigitizedAspectY); - + // Set same. metric.DigitizedAspectY = value; Assert.Equal(value, metric.DigitizedAspectY); @@ -164,7 +164,7 @@ public void TextMetrics_ExternalLeading_Set_GetReturnsExpected(int value) ExternalLeading = value }; Assert.Equal(value, metric.ExternalLeading); - + // Set same. metric.ExternalLeading = value; Assert.Equal(value, metric.ExternalLeading); @@ -179,7 +179,7 @@ public void TextMetrics_FirstChar_Set_GetReturnsExpected(char value) FirstChar = value }; Assert.Equal(value, metric.FirstChar); - + // Set same. metric.FirstChar = value; Assert.Equal(value, metric.FirstChar); @@ -194,7 +194,7 @@ public void TextMetrics_Height_Set_GetReturnsExpected(int value) Height = value }; Assert.Equal(value, metric.Height); - + // Set same. metric.Height = value; Assert.Equal(value, metric.Height); @@ -209,7 +209,7 @@ public void TextMetrics_InternalLeading_Set_GetReturnsExpected(int value) InternalLeading = value }; Assert.Equal(value, metric.InternalLeading); - + // Set same. metric.InternalLeading = value; Assert.Equal(value, metric.InternalLeading); @@ -224,7 +224,7 @@ public void TextMetrics_Italic_Set_GetReturnsExpected(bool value) Italic = value }; Assert.Equal(value, metric.Italic); - + // Set same. metric.Italic = value; Assert.Equal(value, metric.Italic); @@ -239,7 +239,7 @@ public void TextMetrics_LastChar_Set_GetReturnsExpected(char value) LastChar = value }; Assert.Equal(value, metric.LastChar); - + // Set same. metric.LastChar = value; Assert.Equal(value, metric.LastChar); @@ -254,7 +254,7 @@ public void TextMetrics_MaxCharWidth_Set_GetReturnsExpected(int value) MaxCharWidth = value }; Assert.Equal(value, metric.MaxCharWidth); - + // Set same. metric.MaxCharWidth = value; Assert.Equal(value, metric.MaxCharWidth); @@ -269,7 +269,7 @@ public void TextMetrics_Overhang_Set_GetReturnsExpected(int value) Overhang = value }; Assert.Equal(value, metric.Overhang); - + // Set same. metric.Overhang = value; Assert.Equal(value, metric.Overhang); @@ -285,7 +285,7 @@ public void TextMetrics_PitchAndFamily_GetReturnsExpected(TextMetricsPitchAndFam PitchAndFamily = value }; Assert.Equal(value, metric.PitchAndFamily); - + // Set same. metric.PitchAndFamily = value; Assert.Equal(value, metric.PitchAndFamily); @@ -300,7 +300,7 @@ public void TextMetrics_StruckOut_Set_GetReturnsExpected(bool value) StruckOut = value }; Assert.Equal(value, metric.StruckOut); - + // Set same. metric.StruckOut = value; Assert.Equal(value, metric.StruckOut); @@ -315,7 +315,7 @@ public void TextMetrics_Underlined_Set_GetReturnsExpected(bool value) Underlined = value }; Assert.Equal(value, metric.Underlined); - + // Set same. metric.Underlined = value; Assert.Equal(value, metric.Underlined); @@ -330,7 +330,7 @@ public void TextMetrics_Weight_Set_GetReturnsExpected(int value) Weight = value }; Assert.Equal(value, metric.Weight); - + // Set same. metric.Weight = value; Assert.Equal(value, metric.Weight); diff --git a/src/System.Windows.Forms/tests/UnitTests/TextBoxTests.cs b/src/System.Windows.Forms/tests/UnitTests/TextBoxTests.cs index 3982643f6f2..8c3984f31ba 100644 --- a/src/System.Windows.Forms/tests/UnitTests/TextBoxTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/TextBoxTests.cs @@ -33,7 +33,7 @@ public void TextBox_PlaceholderTextAlignments() tb.PlaceholderText = "Enter your name"; System.Runtime.InteropServices.HandleRef refHandle = new System.Runtime.InteropServices.HandleRef(tb, tb.Handle); - + //Cover the Placeholder draw code path UnsafeNativeMethods.SendMessage(refHandle, Interop.WindowMessages.WM_PAINT, false, 0); tb.TextAlign = HorizontalAlignment.Center; diff --git a/src/System.Windows.Forms/tests/UnitTests/ThreadContextTests.cs b/src/System.Windows.Forms/tests/UnitTests/ThreadContextTests.cs index cefc649cf8a..cce75a4fa46 100644 --- a/src/System.Windows.Forms/tests/UnitTests/ThreadContextTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/ThreadContextTests.cs @@ -10,100 +10,104 @@ namespace System.Windows.Forms.Tests { public class ThreadContextTests { - private delegate bool MessageCallback(ref Message m); - - // WM_USER is 0x400, just need to be above that - const int TestMessageId1 = 0x441; - const int TestMessageId2 = 0x442; - const int TestMessageId3 = 0x443; - - [Fact] - public void ThreadContext_EmptyProcessFiltersWorks() { - // Test that no filters at all does not throw, and that returns false from translation - Application.ThreadContext threadContext = new Application.ThreadContext(); - NativeMethods.MSG msg = new NativeMethods.MSG(); - bool result = threadContext.PreTranslateMessage(ref msg); - Assert.False(result); - } - - [Fact] - public void ThreadContext_WrongProcessFiltersPassesThrough() { - // Test that a filter for the wrong ID returns false, but does get called - Application.ThreadContext threadContext = new Application.ThreadContext(); - - int filterId = TestMessageId2; - var mockContext = new Mock(MockBehavior.Strict); - mockContext.Setup(c => c.PreFilterMessage(ref It.Ref.IsAny)) - .Returns((MessageCallback)((ref Message m) => m.Msg == filterId)); - - threadContext.AddMessageFilter(mockContext.Object); - NativeMethods.MSG msg = new NativeMethods.MSG(); - msg.message = TestMessageId1; - bool result = threadContext.PreTranslateMessage(ref msg); - Assert.False(result); - mockContext.Verify(c => c.PreFilterMessage(ref It.Ref.IsAny), Times.Exactly(1)); - } - - [Fact] - public void ThreadContext_CorrectProcessFiltersProcesses() { - // Test that a filter with the correct ID returns true - Application.ThreadContext threadContext = new Application.ThreadContext(); - - int filterId = TestMessageId2; - var mockContext = new Mock(MockBehavior.Strict); - mockContext.Setup(c => c.PreFilterMessage(ref It.Ref.IsAny)) - .Returns((MessageCallback)((ref Message m) => m.Msg == filterId)); - - threadContext.AddMessageFilter(mockContext.Object); - NativeMethods.MSG msg = new NativeMethods.MSG(); - msg.message = filterId; - bool result = threadContext.PreTranslateMessage(ref msg); - Assert.True(result); - mockContext.Verify(c => c.PreFilterMessage(ref It.Ref.IsAny), Times.Exactly(1)); - } - - [Fact] - public void ThreadContext_MultipleProcessFiltersProcesses() { - // Test that multiple filters work - Application.ThreadContext threadContext = new Application.ThreadContext(); - - int filterId2 = TestMessageId2; - var mockContext2 = new Mock(MockBehavior.Strict); - mockContext2.Setup(c => c.PreFilterMessage(ref It.Ref.IsAny)) - .Returns((MessageCallback)((ref Message m) => m.Msg == filterId2)); - threadContext.AddMessageFilter(mockContext2.Object); - - int filterId3 = TestMessageId3; - var mockContext3 = new Mock(MockBehavior.Strict); - mockContext3.Setup(c => c.PreFilterMessage(ref It.Ref.IsAny)) - .Returns((MessageCallback)((ref Message m) => m.Msg == filterId3)); - threadContext.AddMessageFilter(mockContext3.Object); - - - NativeMethods.MSG msg = new NativeMethods.MSG(); - msg.message = TestMessageId1; - bool result = threadContext.PreTranslateMessage(ref msg); - Assert.False(result); - - mockContext2.Verify(c => c.PreFilterMessage(ref It.Ref.IsAny), Times.Exactly(1)); - mockContext3.Verify(c => c.PreFilterMessage(ref It.Ref.IsAny), Times.Exactly(1)); - - - msg = new NativeMethods.MSG(); - msg.message = TestMessageId2; - result = threadContext.PreTranslateMessage(ref msg); - Assert.True(result); - - mockContext2.Verify(c => c.PreFilterMessage(ref It.Ref.IsAny), Times.Exactly(2)); - mockContext3.Verify(c => c.PreFilterMessage(ref It.Ref.IsAny), Times.Exactly(1)); - - msg = new NativeMethods.MSG(); - msg.message = TestMessageId3; - result = threadContext.PreTranslateMessage(ref msg); - Assert.True(result); - - mockContext2.Verify(c => c.PreFilterMessage(ref It.Ref.IsAny), Times.Exactly(3)); - mockContext3.Verify(c => c.PreFilterMessage(ref It.Ref.IsAny), Times.Exactly(2)); - } + private delegate bool MessageCallback(ref Message m); + + // WM_USER is 0x400, just need to be above that + const int TestMessageId1 = 0x441; + const int TestMessageId2 = 0x442; + const int TestMessageId3 = 0x443; + + [Fact] + public void ThreadContext_EmptyProcessFiltersWorks() + { + // Test that no filters at all does not throw, and that returns false from translation + Application.ThreadContext threadContext = new Application.ThreadContext(); + NativeMethods.MSG msg = new NativeMethods.MSG(); + bool result = threadContext.PreTranslateMessage(ref msg); + Assert.False(result); + } + + [Fact] + public void ThreadContext_WrongProcessFiltersPassesThrough() + { + // Test that a filter for the wrong ID returns false, but does get called + Application.ThreadContext threadContext = new Application.ThreadContext(); + + int filterId = TestMessageId2; + var mockContext = new Mock(MockBehavior.Strict); + mockContext.Setup(c => c.PreFilterMessage(ref It.Ref.IsAny)) + .Returns((MessageCallback)((ref Message m) => m.Msg == filterId)); + + threadContext.AddMessageFilter(mockContext.Object); + NativeMethods.MSG msg = new NativeMethods.MSG(); + msg.message = TestMessageId1; + bool result = threadContext.PreTranslateMessage(ref msg); + Assert.False(result); + mockContext.Verify(c => c.PreFilterMessage(ref It.Ref.IsAny), Times.Exactly(1)); + } + + [Fact] + public void ThreadContext_CorrectProcessFiltersProcesses() + { + // Test that a filter with the correct ID returns true + Application.ThreadContext threadContext = new Application.ThreadContext(); + + int filterId = TestMessageId2; + var mockContext = new Mock(MockBehavior.Strict); + mockContext.Setup(c => c.PreFilterMessage(ref It.Ref.IsAny)) + .Returns((MessageCallback)((ref Message m) => m.Msg == filterId)); + + threadContext.AddMessageFilter(mockContext.Object); + NativeMethods.MSG msg = new NativeMethods.MSG(); + msg.message = filterId; + bool result = threadContext.PreTranslateMessage(ref msg); + Assert.True(result); + mockContext.Verify(c => c.PreFilterMessage(ref It.Ref.IsAny), Times.Exactly(1)); + } + + [Fact] + public void ThreadContext_MultipleProcessFiltersProcesses() + { + // Test that multiple filters work + Application.ThreadContext threadContext = new Application.ThreadContext(); + + int filterId2 = TestMessageId2; + var mockContext2 = new Mock(MockBehavior.Strict); + mockContext2.Setup(c => c.PreFilterMessage(ref It.Ref.IsAny)) + .Returns((MessageCallback)((ref Message m) => m.Msg == filterId2)); + threadContext.AddMessageFilter(mockContext2.Object); + + int filterId3 = TestMessageId3; + var mockContext3 = new Mock(MockBehavior.Strict); + mockContext3.Setup(c => c.PreFilterMessage(ref It.Ref.IsAny)) + .Returns((MessageCallback)((ref Message m) => m.Msg == filterId3)); + threadContext.AddMessageFilter(mockContext3.Object); + + + NativeMethods.MSG msg = new NativeMethods.MSG(); + msg.message = TestMessageId1; + bool result = threadContext.PreTranslateMessage(ref msg); + Assert.False(result); + + mockContext2.Verify(c => c.PreFilterMessage(ref It.Ref.IsAny), Times.Exactly(1)); + mockContext3.Verify(c => c.PreFilterMessage(ref It.Ref.IsAny), Times.Exactly(1)); + + + msg = new NativeMethods.MSG(); + msg.message = TestMessageId2; + result = threadContext.PreTranslateMessage(ref msg); + Assert.True(result); + + mockContext2.Verify(c => c.PreFilterMessage(ref It.Ref.IsAny), Times.Exactly(2)); + mockContext3.Verify(c => c.PreFilterMessage(ref It.Ref.IsAny), Times.Exactly(1)); + + msg = new NativeMethods.MSG(); + msg.message = TestMessageId3; + result = threadContext.PreTranslateMessage(ref msg); + Assert.True(result); + + mockContext2.Verify(c => c.PreFilterMessage(ref It.Ref.IsAny), Times.Exactly(3)); + mockContext3.Verify(c => c.PreFilterMessage(ref It.Ref.IsAny), Times.Exactly(2)); + } } } diff --git a/src/System.Windows.Forms/tests/UnitTests/TreeViewTests.cs b/src/System.Windows.Forms/tests/UnitTests/TreeViewTests.cs index f90a904b24f..d966202c472 100644 --- a/src/System.Windows.Forms/tests/UnitTests/TreeViewTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/TreeViewTests.cs @@ -20,7 +20,7 @@ public void TreeView_Constructor() Assert.NotNull(tv.ImageIndexer); Assert.Equal(0, tv.ImageIndexer.Index); } - + [Fact] public void TreeView_AddExistingNodeAsChild_ThrowsArgumentException() { From f79f41eef2722bb104f8316f76111c29e7aa7f02 Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Thu, 23 May 2019 13:21:56 -0700 Subject: [PATCH 02/27] formatting System.Windows.Forms.IntegrationTests --- .../TestHelpers.cs | 20 +++++++++---------- .../WinformsControlsTest.cs | 8 ++++---- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/System.Windows.Forms/tests/IntegrationTests/System.Windows.Forms.IntegrationTests/TestHelpers.cs b/src/System.Windows.Forms/tests/IntegrationTests/System.Windows.Forms.IntegrationTests/TestHelpers.cs index 6bc4cd7094a..23399e59123 100644 --- a/src/System.Windows.Forms/tests/IntegrationTests/System.Windows.Forms.IntegrationTests/TestHelpers.cs +++ b/src/System.Windows.Forms/tests/IntegrationTests/System.Windows.Forms.IntegrationTests/TestHelpers.cs @@ -8,9 +8,9 @@ using System.Reflection; namespace System.Windows.Forms.Func.Tests -{ +{ public class TestHelpers - { + { /// /// Calls StartProcess for the ProcessStartInfo containing the bin path of this directory plus the given byPathFromBinToExe; also ensures that repo\.dotnet\dotnet.exe exists @@ -24,7 +24,7 @@ public class TestHelpers /// The new Process public static Process StartProcess(string byPathFromBinToExe) { - if(byPathFromBinToExe == null) + if (byPathFromBinToExe == null) { throw new ArgumentNullException(nameof(byPathFromBinToExe)); } @@ -34,10 +34,10 @@ public static Process StartProcess(string byPathFromBinToExe) throw new ArgumentException(nameof(byPathFromBinToExe) + " must end in a .exe"); } - var dotnetPath = DotNetPath(); - if (!Directory.Exists(dotnetPath)) - { - throw new DirectoryNotFoundException(dotnetPath + " directory cannot be found."); + var dotnetPath = DotNetPath(); + if (!Directory.Exists(dotnetPath)) + { + throw new DirectoryNotFoundException(dotnetPath + " directory cannot be found."); } ProcessStartInfo startInfo = new ProcessStartInfo(); @@ -95,7 +95,7 @@ public static string DotNetPath() /// The path as a string; example: example:\Project\bin\ given "bin" if bin is present in the path public static string RelativePathForwardTo(string stop) { - if(string.IsNullOrEmpty(stop)) + if (string.IsNullOrEmpty(stop)) { throw new ArgumentException(nameof(stop) + " must not be null or empty."); } @@ -147,7 +147,7 @@ public static string RelativePathBackwardsUntilFind(string seek) } currentDirectory = Directory.GetParent(currentDirectory).FullName; } - throw new DirectoryNotFoundException($"No {seek} folder was found among siblings of subfolders of {codeBasePath}."); + throw new DirectoryNotFoundException($"No {seek} folder was found among siblings of subfolders of {codeBasePath}."); } /// @@ -274,7 +274,7 @@ internal static bool PressOnProcess(Process process, string keys) if (handle.Equals(ExternalTestHelpers.TryGetForegroundWindow())) { - SendKeys.SendWait(keys); + SendKeys.SendWait(keys); Thread.Sleep(200); diff --git a/src/System.Windows.Forms/tests/IntegrationTests/System.Windows.Forms.IntegrationTests/WinformsControlsTest.cs b/src/System.Windows.Forms/tests/IntegrationTests/System.Windows.Forms.IntegrationTests/WinformsControlsTest.cs index b548c785abe..a2f9686735f 100644 --- a/src/System.Windows.Forms/tests/IntegrationTests/System.Windows.Forms.IntegrationTests/WinformsControlsTest.cs +++ b/src/System.Windows.Forms/tests/IntegrationTests/System.Windows.Forms.IntegrationTests/WinformsControlsTest.cs @@ -13,11 +13,11 @@ public class WinformsControlsTestTests : IFunctionalPathTest public string GetPathToTestFromBin() { - string buildType = "Release"; + string buildType = "Release"; - #if DEBUG - buildType = "Debug"; - #endif +#if DEBUG + buildType = "Debug"; +#endif return "WinformsControlsTest\\" + buildType + "\\netcoreapp3.0\\WinformsControlsTest.exe"; } From fd95ff56fc955ed5a4c9e92b864b0eec631c9a07 Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Thu, 23 May 2019 13:22:39 -0700 Subject: [PATCH 03/27] formatting System.Windows.Forms.Design.Tests --- .../tests/UnitTests/ControlDesignerTests.cs | 4 +- .../TypeCodeDomSerializerTests.cs | 2 +- .../Design/DesignSurfaceTests.cs | 10 ++--- .../DesignerActionItemCollectionTests.cs | 4 +- .../DesignerActionListCollectionTests.cs | 2 +- .../Design/DesignerActionMethodItemTests.cs | 2 +- .../Design/DesignerActionServiceTests.cs | 14 +++---- .../Design/DesignerHostTests.cs | 10 ++--- .../DesignerSerializationManagerTests.cs | 42 ++++++++++--------- .../ComponentModel/Design/UndoUnitTests.cs | 2 +- .../System/Drawing/Design/ToolboxItemTests.cs | 12 +++--- .../Windows/Forms/Design/MenuCommandsTests.cs | 2 +- 12 files changed, 54 insertions(+), 52 deletions(-) diff --git a/src/System.Windows.Forms.Design/tests/UnitTests/ControlDesignerTests.cs b/src/System.Windows.Forms.Design/tests/UnitTests/ControlDesignerTests.cs index 51568c546ab..c0c02f831d7 100644 --- a/src/System.Windows.Forms.Design/tests/UnitTests/ControlDesignerTests.cs +++ b/src/System.Windows.Forms.Design/tests/UnitTests/ControlDesignerTests.cs @@ -36,7 +36,7 @@ public void EnableDragRectProperty() TestControlDesigner controlDesigner = new TestControlDesigner(); Assert.False(controlDesigner.GetEnableDragRectProperty()); } - + [Fact] public void ParticipatesWithSnapLinesProperty() { @@ -56,7 +56,7 @@ public void AutoResizeHandlesProperty() public void SelectionRulesProperty() { TestControlDesigner controlDesigner = new TestControlDesigner(); - Assert.Equal(SelectionRules.Visible ,controlDesigner.SelectionRules); + Assert.Equal(SelectionRules.Visible, controlDesigner.SelectionRules); } [Fact] diff --git a/src/System.Windows.Forms.Design/tests/UnitTests/Serialization/TypeCodeDomSerializerTests.cs b/src/System.Windows.Forms.Design/tests/UnitTests/Serialization/TypeCodeDomSerializerTests.cs index 910eb1b34cf..dd19a74ccf8 100644 --- a/src/System.Windows.Forms.Design/tests/UnitTests/Serialization/TypeCodeDomSerializerTests.cs +++ b/src/System.Windows.Forms.Design/tests/UnitTests/Serialization/TypeCodeDomSerializerTests.cs @@ -19,7 +19,7 @@ public void TypeCodeDomSerializer_Constructor() } [Fact] - public void TypeCodeDomSerializer_Serialize_Manager_Null () + public void TypeCodeDomSerializer_Serialize_Manager_Null() { var underTest = new TypeCodeDomSerializer(); Assert.Throws(() => underTest.Serialize(null, null, null)); diff --git a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignSurfaceTests.cs b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignSurfaceTests.cs index 9db0b46d1dd..114d521eb1c 100644 --- a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignSurfaceTests.cs +++ b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignSurfaceTests.cs @@ -85,11 +85,11 @@ public void DesignSurface_DtelLoading_Set_GetReturnsExpected(bool value) DtelLoading = value }; Assert.Equal(value, surface.DtelLoading); - + // Set same surface.DtelLoading = value; Assert.Equal(value, surface.DtelLoading); - + // Set different surface.DtelLoading = !value; Assert.Equal(!value, surface.DtelLoading); @@ -375,7 +375,7 @@ public void DesignSurface_BeginLoad_InvokeWithLoading_CallsHandler() Assert.Equal(0, unloadedCallCount); Assert.Equal(0, flushedCallCount); mockLoader.Verify(l => l.BeginLoad(host), Times.Once()); - + // Begin again. surface.BeginLoad(mockLoader.Object); Assert.False(surface.IsLoaded); @@ -439,7 +439,7 @@ public void DesignSurface_BeginLoad_InvokeErrorWithUnloading_CallsHandler() Assert.Equal(1, loadedCallCount); Assert.Equal(0, flushedCallCount); mockLoader.Verify(l => l.BeginLoad(host), Times.Once()); - + // Begin again. surface.BeginLoad(mockLoader.Object); Assert.False(surface.IsLoaded); @@ -628,7 +628,7 @@ public void DesignSurface_BeginLoad_DisposeInBeginLoadThrowsException_DoesCallFl Assert.Equal(0, flushedCallCount); mockLoader.Verify(l => l.BeginLoad(host), Times.Once()); } - + [Fact] public void DesignSurface_BeginLoad_NullLoader_ThrowsArgumentNullException() { diff --git a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerActionItemCollectionTests.cs b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerActionItemCollectionTests.cs index 453e955f5b8..1494d26805b 100644 --- a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerActionItemCollectionTests.cs +++ b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerActionItemCollectionTests.cs @@ -15,7 +15,7 @@ public void DesignerActionItemCollection_Ctor_Default() var collection = new DesignerActionItemCollection(); Assert.Empty(collection); } - + [Fact] public void DesignerActionItemCollection_Add_DesignerActionItem_Success() { @@ -41,7 +41,7 @@ public void DesignerActionItemCollection_Add_NullValue_ThrowsArgumentNullExcepti var collection = new DesignerActionItemCollection(); Assert.Throws("value", () => collection.Add(null)); } - + [Fact] public void DesignerActionItemCollection_Insert_DesignerActionItem_Success() { diff --git a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerActionListCollectionTests.cs b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerActionListCollectionTests.cs index 2a5faee57c8..4c7a284520d 100644 --- a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerActionListCollectionTests.cs +++ b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerActionListCollectionTests.cs @@ -86,7 +86,7 @@ public void DesignerActionListCollection_AddRange_DesignerActionListCollection_S collection.AddRange(new DesignerActionListCollection(value)); Assert.Equal(value.Concat(value), collection.Cast()); } - + [Fact] public void DesignerActionListCollection_Insert_DesignerActionList_Success() { diff --git a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerActionMethodItemTests.cs b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerActionMethodItemTests.cs index a07245949e6..7b9097e6f2c 100644 --- a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerActionMethodItemTests.cs +++ b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerActionMethodItemTests.cs @@ -243,7 +243,7 @@ public void Invoke_MemberWithParameters_ThrowsTargetParameterCountException() private class SubDesignerActionList : DesignerActionList { public SubDesignerActionList() : base(null) - { + { } public string CalledMethod { get; set; } diff --git a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerActionServiceTests.cs b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerActionServiceTests.cs index bde0053987f..9b0978a7e9e 100644 --- a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerActionServiceTests.cs +++ b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerActionServiceTests.cs @@ -217,7 +217,7 @@ public void Clear_InvokeWithDesignerActionListsChanged_CallsHandler() callCount++; }; service.DesignerActionListsChanged += handler; - + service.Clear(); Assert.Equal(2, callCount); @@ -694,7 +694,7 @@ public void Remove_InvokeComponentWithDesignerActionListsChanged_CallsHandler() callCount++; }; service.DesignerActionListsChanged += handler; - + service.Remove(component1); Assert.False(service.Contains(component1)); Assert.Equal(1, callCount); @@ -776,7 +776,7 @@ public void Remove_InvokeDesignerActionList_Success() Assert.True(service.Contains(component2)); Assert.True(service.Contains(component3)); Assert.True(service.Contains(component4)); - + // Remove across multiple components. service.Remove(actionList3); Assert.Empty(service.GetComponentActions(component1)); @@ -872,7 +872,7 @@ public void Remove_InvokeDesignerActionListWithDesignerActionListsChanged_CallsH callCount++; }; service.DesignerActionListsChanged += handler; - + service.Remove(actionList1); Assert.False(service.Contains(component1)); Assert.Equal(1, callCount); @@ -939,7 +939,7 @@ public void Remove_InvokeComponentDesignerActionList_Success() Assert.True(service.Contains(component2)); Assert.True(service.Contains(component3)); Assert.True(service.Contains(component4)); - + // Remove across multiple components. service.Remove(component2, actionList3); Assert.Empty(service.GetComponentActions(component1)); @@ -1002,7 +1002,7 @@ public void Remove_InvokeComponentDesignerActionListWithDesignerActionListsChang callCount++; }; service.DesignerActionListsChanged += handler; - + service.Remove(component1, actionList1); Assert.False(service.Contains(component1)); Assert.Equal(1, callCount); @@ -1053,7 +1053,7 @@ public SubDesignerActionService(IServiceProvider serviceProvider) : base(service base.GetComponentServiceActions(component, actionLists); } } - + private class CustomDesignerActionList : DesignerActionList { public CustomDesignerActionList(IComponent component) : base(component) diff --git a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerHostTests.cs b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerHostTests.cs index a83d6fc6d62..945f29351f0 100644 --- a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerHostTests.cs +++ b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerHostTests.cs @@ -112,7 +112,7 @@ public void DesignerHost_Activate_InvokeDisposed_Nop() public static IEnumerable Add_InvalidNameCreationServiceParentProvider_TestData() { yield return new object[] { null }; - + var nullMockServiceProvider = new Mock(MockBehavior.Strict); nullMockServiceProvider .Setup(p => p.GetService(typeof(INameCreationService))) @@ -453,7 +453,7 @@ public void DesignerHost_AddComponentIDictionaryServiceGetKey_NoSuchKeyWithDicti service.SetValue(key1, value1); Assert.Same(key1, service.GetKey(value1)); Assert.Same(value1, service.GetValue(key1)); - + Assert.Null(service.GetKey(null)); Assert.Null(service.GetKey(new object())); } @@ -484,7 +484,7 @@ public void DesignerHost_AddComponentIDictionaryServiceGetValue_NoSuchValueWithD service.SetValue(key1, value1); Assert.Same(key1, service.GetKey(value1)); Assert.Same(value1, service.GetValue(key1)); - + Assert.Null(service.GetValue(new object())); } @@ -514,7 +514,7 @@ public void DesignerHost_AddComponentIDictionaryServiceGetValue_NullValueWithDic service.SetValue(key1, value1); Assert.Same(key1, service.GetKey(value1)); Assert.Same(value1, service.GetValue(key1)); - + Assert.Throws("key", () => service.GetValue(null)); } @@ -1219,7 +1219,7 @@ public void DesignerHost_ChangeActiveDesigner_Invoke_Success(ActiveDesignerEvent Assert.Equal(expectedActivatedCallCount, activatedCallCount); Assert.Equal(expectedDeactivatedCallCount, deactivatedCallCount); Assert.Equal(expectedFlushCount, flushCallCount); - + // Should not invoke if removed. host.Activated -= activatedHandler; host.Deactivated -= deactivatedHandler; diff --git a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/Serialization/DesignerSerializationManagerTests.cs b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/Serialization/DesignerSerializationManagerTests.cs index 3b57b9e314b..6b346bbaaa6 100644 --- a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/Serialization/DesignerSerializationManagerTests.cs +++ b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/Serialization/DesignerSerializationManagerTests.cs @@ -25,7 +25,8 @@ public void DesignerSerializationManager_Ctor_Default() Assert.Same(iManager.Properties, iManager.Properties); Assert.Null(manager.PropertyProvider); Assert.False(manager.RecycleInstances); - Assert.True(manager.ValidateRecycledTypes);; + Assert.True(manager.ValidateRecycledTypes); + ; } public static IEnumerable Ctor_IServiceProvider_TestData() @@ -67,7 +68,8 @@ public void DesignerSerializationManager_Ctor_IServiceProvider(IServiceProvider Assert.Same(iManager.Properties, iManager.Properties); Assert.Null(manager.PropertyProvider); Assert.False(manager.RecycleInstances); - Assert.True(manager.ValidateRecycledTypes);; + Assert.True(manager.ValidateRecycledTypes); + ; } [Fact] @@ -92,7 +94,7 @@ public void DesignerSerializationManager_Container_Set_GetReturnsExpected(IConta }; Assert.Same(value, manager.Container); Assert.Same(value, manager.GetService(typeof(IContainer))); - + // Set same. manager.Container = value; Assert.Same(value, manager.Container); @@ -176,11 +178,11 @@ public void DesignerSerializationManager_PreserveNames_Set_GetReturnsExpected(bo PreserveNames = value }; Assert.Equal(value, manager.PreserveNames); - + // Set same manager.PreserveNames = value; Assert.Equal(value, manager.PreserveNames); - + // Set different manager.PreserveNames = !value; Assert.Equal(!value, manager.PreserveNames); @@ -274,7 +276,7 @@ public void DesignerSerializationManager_PropertyProvider_Set_GetReturnsExpected PropertyProvider = value }; Assert.Same(value, manager.PropertyProvider); - + // Set same manager.PropertyProvider = value; Assert.Same(value, manager.PropertyProvider); @@ -286,10 +288,10 @@ public void DesignerSerializationManager_PropertyProvider_SetWithSession_GetRetu { var manager = new DesignerSerializationManager(); manager.CreateSession(); - + manager.PropertyProvider = value; Assert.Same(value, manager.PropertyProvider); - + // Set same manager.PropertyProvider = value; Assert.Same(value, manager.PropertyProvider); @@ -307,7 +309,7 @@ public void DesignerSerializationManager_Properties_SetWithExistingProperties_Re PropertyDescriptor property = Assert.IsAssignableFrom(Assert.Single(properties)); Assert.Equal(nameof(PropertyProvider.Value), property.Name); Assert.Same(properties, iManager.Properties); - + var provider = new OtherPropertyProvider(); manager.PropertyProvider = provider; Assert.Same(provider, manager.PropertyProvider); @@ -315,7 +317,7 @@ public void DesignerSerializationManager_Properties_SetWithExistingProperties_Re PropertyDescriptor otherProperty = Assert.IsAssignableFrom(Assert.Single(otherProperties)); Assert.Equal(nameof(OtherPropertyProvider.OtherValue), otherProperty.Name); Assert.Same(otherProperties, iManager.Properties); - + // Set same. manager.PropertyProvider = provider; Assert.Same(provider, manager.PropertyProvider); @@ -331,11 +333,11 @@ public void DesignerSerializationManager_RecycleInstances_Set_GetReturnsExpected RecycleInstances = value }; Assert.Equal(value, manager.RecycleInstances); - + // Set same manager.RecycleInstances = value; Assert.Equal(value, manager.RecycleInstances); - + // Set different manager.RecycleInstances = !value; Assert.Equal(!value, manager.RecycleInstances); @@ -360,11 +362,11 @@ public void DesignerSerializationManager_ValidateRecycledTypes_Set_GetReturnsExp ValidateRecycledTypes = value }; Assert.Equal(value, manager.ValidateRecycledTypes); - + // Set same manager.ValidateRecycledTypes = value; Assert.Equal(value, manager.ValidateRecycledTypes); - + // Set different manager.ValidateRecycledTypes = !value; Assert.Equal(!value, manager.ValidateRecycledTypes); @@ -426,7 +428,7 @@ public void DesignerSerializationManager_AddSerializationProvider_NonNullProvide iManager.AddSerializationProvider(mockDesignerSerializationProvider.Object); Assert.Same(expected, iManager.GetSerializer(objectType, mockDesignerSerializationProvider.Object.GetType())); mockDesignerSerializationProvider.Verify(p => p.GetSerializer(manager, null, objectType, mockDesignerSerializationProvider.Object.GetType()), Times.Once()); - + // Call again. Assert.Same(expected, iManager.GetSerializer(objectType, mockDesignerSerializationProvider.Object.GetType())); mockDesignerSerializationProvider.Verify(p => p.GetSerializer(manager, null, objectType, mockDesignerSerializationProvider.Object.GetType()), Times.Exactly(2)); @@ -611,7 +613,7 @@ public void DesignerSerializationManager_CreateSession_Dispose_ClearsResolveName manager.OnResolveName(eventArgs); Assert.Equal(1, callCount); session.Dispose(); - + // Call again. session = manager.CreateSession(); manager.OnResolveName(eventArgs); @@ -986,7 +988,7 @@ public void DesignerSerializationManager_GetService_WithProvider_ReturnsExpected Assert.Same(service, ((IServiceProvider)manager).GetService(serviceType)); mockServiceProvider.Verify(p => p.GetService(serviceType), Times.Exactly(2)); } - + [Theory] [MemberData(nameof(Ctor_IServiceProvider_TestData))] public void DesignerSerializationManager_GetService_IContainer_ReturnsExpected(IServiceProvider provider, object expected) @@ -1039,7 +1041,7 @@ public void DesignerSerializationManager_IDesignerSerializationManagerGetService Assert.Same(service, ((IServiceProvider)iManager).GetService(serviceType)); mockServiceProvider.Verify(p => p.GetService(serviceType), Times.Exactly(2)); } - + [Theory] [MemberData(nameof(Ctor_IServiceProvider_TestData))] public void DesignerSerializationManager_IDesignerSerializationManagerGetService_IContainer_ReturnsExpected(IServiceProvider provider, object expected) @@ -1672,7 +1674,7 @@ public void DesignerSerializationManager_OnResolveName_InvokeWithResolveName_Cal manager.OnResolveName(eventArgs); Assert.Equal(1, callCount); session.Dispose(); - + // Call again. session = manager.CreateSession(); iManager.ResolveName += handler; @@ -1705,7 +1707,7 @@ public void DesignerSerializationManager_OnSessionCreated_InvokeWithSessionCreat // With handler. manager.OnSessionCreated(eventArgs); Assert.Equal(1, callCount); - + // Call again. manager.OnSessionCreated(eventArgs); Assert.Equal(2, callCount); diff --git a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/UndoUnitTests.cs b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/UndoUnitTests.cs index b35da2d0048..4639ff7944f 100644 --- a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/UndoUnitTests.cs +++ b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/UndoUnitTests.cs @@ -9,7 +9,7 @@ namespace System.ComponentModel.Design.Tests { - public class UndoUnitTests: UndoEngine + public class UndoUnitTests : UndoEngine { public UndoUnitTests() : base(GetServiceProvider()) { diff --git a/src/System.Windows.Forms.Design/tests/UnitTests/System/Drawing/Design/ToolboxItemTests.cs b/src/System.Windows.Forms.Design/tests/UnitTests/System/Drawing/Design/ToolboxItemTests.cs index d5295d2a484..c14c317b97f 100644 --- a/src/System.Windows.Forms.Design/tests/UnitTests/System/Drawing/Design/ToolboxItemTests.cs +++ b/src/System.Windows.Forms.Design/tests/UnitTests/System/Drawing/Design/ToolboxItemTests.cs @@ -272,12 +272,12 @@ public void ToolboxItem_Filter_Set_GetReturnsExpected(ICollection value, ICollec { Filter = value }; - Assert.Equal(expected , item.Filter); + Assert.Equal(expected, item.Filter); Assert.Equal(expected, item.Properties["Filter"]); // Set same. item.Filter = value; - Assert.Equal(expected , item.Filter); + Assert.Equal(expected, item.Filter); Assert.Equal(expected, item.Properties["Filter"]); } @@ -296,12 +296,12 @@ public void ToolboxItem_IsTransient_Set_GetReturnsExpected(bool value) { IsTransient = value }; - Assert.Equal(value , item.IsTransient); + Assert.Equal(value, item.IsTransient); Assert.Equal(value, item.Properties["IsTransient"]); // Set same. item.IsTransient = value; - Assert.Equal(value , item.IsTransient); + Assert.Equal(value, item.IsTransient); Assert.Equal(value, item.Properties["IsTransient"]); } @@ -1544,7 +1544,7 @@ public static IEnumerable ValidatePropertyValue_TestData() yield return new object[] { "TypeName", null, string.Empty }; yield return new object[] { "TypeName", "value", "value" }; - var filter = new ToolboxItemFilterAttribute("filter"); + var filter = new ToolboxItemFilterAttribute("filter"); yield return new object[] { "Filter", null, new ToolboxItemFilterAttribute[0] }; yield return new object[] { "Filter", new ToolboxItemFilterAttribute[0], new ToolboxItemFilterAttribute[0] }; yield return new object[] { "Filter", new object[] { null, "value", filter, filter }, new ToolboxItemFilterAttribute[] { filter, filter } }; @@ -1637,7 +1637,7 @@ private class SubToolboxItem : ToolboxItem { return base.CreateComponentsCore(host, defaultValues); } - + public new object FilterPropertyValue(string propertyName, object value) { return base.FilterPropertyValue(propertyName, value); diff --git a/src/System.Windows.Forms.Design/tests/UnitTests/System/Windows/Forms/Design/MenuCommandsTests.cs b/src/System.Windows.Forms.Design/tests/UnitTests/System/Windows/Forms/Design/MenuCommandsTests.cs index a24ce0401f5..6d564d91a1d 100644 --- a/src/System.Windows.Forms.Design/tests/UnitTests/System/Windows/Forms/Design/MenuCommandsTests.cs +++ b/src/System.Windows.Forms.Design/tests/UnitTests/System/Windows/Forms/Design/MenuCommandsTests.cs @@ -56,7 +56,7 @@ public static IEnumerable Commands_TestData() yield return new object[] { MenuCommands.SetStatusText, new CommandID(new Guid("74d21313-2aee-11d1-8bfb-00a0c90f26f7"), 16387) }; yield return new object[] { MenuCommands.TraySelectionMenu, new CommandID(new Guid("74d21312-2aee-11d1-8bfb-00a0c90f26f7"), 1283) }; } - + [Theory] [MemberData(nameof(Commands_TestData))] public void MenuCommands_Commands_Get_ReturnsExected(CommandID command, CommandID expected) From dfda02f8906ff2373225aadf223db3f6eba39081 Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Thu, 23 May 2019 13:23:05 -0700 Subject: [PATCH 04/27] formatting System.Windows.Forms.Design.Editors.Tests --- .../UnitTests/ObjectSelectorEditorTests.cs | 9 +++++--- .../Design/CollectionEditorTests.cs | 22 +++++++++---------- .../Design/CollectionFormTests.cs | 7 +++--- 3 files changed, 21 insertions(+), 17 deletions(-) diff --git a/src/System.Windows.Forms.Design.Editors/tests/UnitTests/ObjectSelectorEditorTests.cs b/src/System.Windows.Forms.Design.Editors/tests/UnitTests/ObjectSelectorEditorTests.cs index 648b877f01f..27890a69936 100644 --- a/src/System.Windows.Forms.Design.Editors/tests/UnitTests/ObjectSelectorEditorTests.cs +++ b/src/System.Windows.Forms.Design.Editors/tests/UnitTests/ObjectSelectorEditorTests.cs @@ -34,7 +34,8 @@ public void ObjectSelectorEditor_CurrentValue() } [Fact] - public void ObjectSelectorEditor_GetEditStyle() { + public void ObjectSelectorEditor_GetEditStyle() + { var underTest = GetNewObjectSelectorEditor(); Assert.Equal(UITypeEditorEditStyle.DropDown, underTest.GetEditStyle(null)); @@ -59,7 +60,8 @@ private ObjectSelectorEditor GetNewObjectSelectorEditor(bool subObjectSelector = return subObjectSelector ? new TestObjectSelectorEditor(subObjectSelector) : new TestObjectSelectorEditor(); } - private class TestObjectSelectorEditor : ObjectSelectorEditor { + private class TestObjectSelectorEditor : ObjectSelectorEditor + { public TestObjectSelectorEditor() { } @@ -68,7 +70,8 @@ public TestObjectSelectorEditor(bool subObjectSelector) : base(subObjectSelector } } - private ObjectSelectorEditor.Selector GetNewSelector() { + private ObjectSelectorEditor.Selector GetNewSelector() + { return new ObjectSelectorEditor.Selector(GetNewObjectSelectorEditor()); } } diff --git a/src/System.Windows.Forms.Design.Editors/tests/UnitTests/System/ComponentModel/Design/CollectionEditorTests.cs b/src/System.Windows.Forms.Design.Editors/tests/UnitTests/System/ComponentModel/Design/CollectionEditorTests.cs index d280b18e4e6..b08699a6257 100644 --- a/src/System.Windows.Forms.Design.Editors/tests/UnitTests/System/ComponentModel/Design/CollectionEditorTests.cs +++ b/src/System.Windows.Forms.Design.Editors/tests/UnitTests/System/ComponentModel/Design/CollectionEditorTests.cs @@ -387,7 +387,7 @@ public void CollectionEditor_CreateNewItemTypes_NullType_ThrowsArgumentNullExcep public static IEnumerable DestroyInstance_NormalObject_TestData() { yield return new object[] { null }; - yield return new object[] { new object() }; + yield return new object[] { new object() }; } [Theory] @@ -435,7 +435,7 @@ public void CollectionEditor_DestroyInstance_WithContextWithInvalidDesignerHot_C editor.DestroyInstance(mockComponent.Object); mockComponent.Verify(c => c.Dispose(), Times.Once()); } - + [Fact] public void CollectionEditor_DestroyInstance_WithContextWithInvalidHost_CallsDestroyComponent() { @@ -493,7 +493,7 @@ public void CollectionEditor_DestroyInstance_IComponentWithoutHost_CallsDispose( mockComponent .Setup(c => c.Dispose()) .Verifiable(); - + var editor = new SubCollectionEditor(null); editor.DestroyInstance(mockComponent.Object); mockComponent.Verify(c => c.Dispose(), Times.Once()); @@ -506,7 +506,7 @@ public void CollectionEditor_DestroyInstance_IDisposable_CallsDispose() mockDisposable .Setup(d => d.Dispose()) .Verifiable(); - + var editor = new SubCollectionEditor(null); editor.DestroyInstance(mockDisposable.Object); mockDisposable.Verify(d => d.Dispose(), Times.Once()); @@ -693,7 +693,7 @@ public void CollectionEditor_EditValue_ValidProviderValidHostWithIComponentChang mockEditorService .Setup(s => s.ShowDialog(It.IsAny
())) .Returns(DialogResult.OK); - + var mockChangeService = new Mock(MockBehavior.Strict); var mockServiceProvider = new Mock(MockBehavior.Strict); @@ -825,12 +825,12 @@ public void CollectionEditor_GetDisplayText_Invoke_ReturnsExpected(Type type, ob var editor = new SubCollectionEditor(type); Assert.Equal(expected, editor.GetDisplayText(value)); } - + [Fact] public void CollectionEditor_GetDisplayText_ValueDoesntMatchCollectionType_ThrowsTargetException() { var editor = new SubCollectionEditor(typeof(ClassWithStringDefaultProperty)); - TargetInvocationException ex = Assert.Throws(() => editor.GetDisplayText(new ClassWithNonStringDefaultProperty())); + TargetInvocationException ex = Assert.Throws(() => editor.GetDisplayText(new ClassWithNonStringDefaultProperty())); Assert.IsType(ex.InnerException); } @@ -840,7 +840,7 @@ public static IEnumerable GetItems_TestData() yield return new object[] { new object(), new object[0] }; yield return new object[] { new ArrayList { 1, 2, 3 }, new object[] { 1, 2, 3, } }; } - + [Theory] [MemberData(nameof(GetItems_TestData))] public void CollectionEditor_GetItems_Invoke_ReturnsExpected(object editValue, object[] expected) @@ -915,12 +915,12 @@ public void CollectionEditor_GetObjectsFromInstance_Invoke_ReturnsExpected(objec public static IEnumerable SetItems_TestData() { - yield return new object[] { null, new object[] { 1, 2, 3}, null }; + yield return new object[] { null, new object[] { 1, 2, 3 }, null }; yield return new object[] { null, new object[0], null }; yield return new object[] { null, null, null }; var o = new object(); - yield return new object[] { o, new object[] { 1, 2, 3}, o }; + yield return new object[] { o, new object[] { 1, 2, 3 }, o }; yield return new object[] { o, new object[0], o }; yield return new object[] { o, null, o }; @@ -1051,7 +1051,7 @@ public SubCollectionEditor(Type type) : base(type) public new Type CreateCollectionItemType() => base.CreateCollectionItemType(); public new object CreateInstance(Type itemType) => base.CreateInstance(itemType); - + public new Type[] CreateNewItemTypes() => base.CreateNewItemTypes(); public new void DestroyInstance(object instance) => base.DestroyInstance(instance); diff --git a/src/System.Windows.Forms.Design.Editors/tests/UnitTests/System/ComponentModel/Design/CollectionFormTests.cs b/src/System.Windows.Forms.Design.Editors/tests/UnitTests/System/ComponentModel/Design/CollectionFormTests.cs index 288692df0f8..3f3b9bdc8d3 100644 --- a/src/System.Windows.Forms.Design.Editors/tests/UnitTests/System/ComponentModel/Design/CollectionFormTests.cs +++ b/src/System.Windows.Forms.Design.Editors/tests/UnitTests/System/ComponentModel/Design/CollectionFormTests.cs @@ -488,7 +488,8 @@ public void CollectionForm_CanSelectMultipleInstances_Invoke_ReturnsFalse() var editor = new SubCollectionEditor(null); var form = new SubCollectionForm(editor); Assert.True(form.CanSelectMultipleInstances()); - } public static IEnumerable InvalidDesignerHost_TestData() + } + public static IEnumerable InvalidDesignerHost_TestData() { yield return new object[] { null }; yield return new object[] { new object() }; @@ -865,7 +866,7 @@ public SubCollectionForm(CollectionEditor editor) : base(editor) public new bool CanRemoveInstance(object value) => base.CanRemoveInstance(value); public new bool CanSelectMultipleInstances() => base.CanSelectMultipleInstances(); - + public new object CreateInstance(Type itemType) => base.CreateInstance(itemType); public new void DestroyInstance(object instance) => base.DestroyInstance(instance); @@ -873,7 +874,7 @@ public SubCollectionForm(CollectionEditor editor) : base(editor) public new void DisplayError(Exception e) => base.DisplayError(e); public new object GetService(Type serviceType) => base.GetService(serviceType); - + public new DialogResult ShowEditorDialog(IWindowsFormsEditorService edSvc) => base.ShowEditorDialog(edSvc); public int OnEditValueChangedCallCount { get; set; } From 37768c024fddd09e51e9b098e8de88926cfb45bf Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Thu, 23 May 2019 13:23:58 -0700 Subject: [PATCH 05/27] formatting System.Windows.Forms --- src/Common/src/ClientUtils.cs | 280 +- src/Common/src/CommonUnsafeNativeMethods.cs | 30 +- src/Common/src/CompModSwitches.cs | 282 +- .../src/DpiHelper.DpiAwarenessContext.cs | 2 +- src/Common/src/DpiHelper.cs | 2 +- src/Common/src/ExternDll.cs | 70 +- .../src/Interop/Interop.EditMessages.cs | 2 +- .../src/Interop/Interop.HandleCollector.cs | 2 +- .../src/Interop/Interop.WindowMessages.cs | 2 +- .../Shell32/Interop.SHBrowseForFolder.cs | 4 +- .../Interop/User32/Interop.GetWindowText.cs | 8 +- src/Common/src/NativeMethods.cs | 3994 ++-- src/Common/src/RTLAwareMessageBox.cs | 20 +- src/Common/src/SafeNativeMethods.cs | 867 +- src/Common/src/UnsafeNativeMethods.cs | 5490 ++--- .../src/Common/System/LocalAppContext.cs | 6 +- .../Drawing/Design/PaintValueEventArgs.cs | 8 +- .../Drawing/Design/PropertyValueUIItem.cs | 4 +- .../src/System/Drawing/Design/UITypeEditor.cs | 6 +- .../src/System/Resources/ResXDataNode.cs | 619 +- .../src/System/Resources/ResXFileRef.cs | 184 +- .../src/System/Resources/ResXNullRef.cs | 6 +- .../System/Resources/ResXResourceReader.cs | 434 +- .../src/System/Resources/ResXResourceSet.cs | 18 +- .../System/Resources/ResXResourceWriter.cs | 324 +- .../System/Windows/Forms/AccessibleEvents.cs | 28 +- .../Windows/Forms/AccessibleNavigation.cs | 6 +- .../System/Windows/Forms/AccessibleObject.cs | 44 +- .../System/Windows/Forms/AccessibleStates.cs | 60 +- .../System/Windows/Forms/AmbientProperties.cs | 4 +- .../src/System/Windows/Forms/Application.cs | 1851 +- .../Windows/Forms/ApplicationContext.cs | 74 +- .../System/Windows/Forms/ArrangeDirection.cs | 2 +- .../System/Windows/Forms/ArrangedElement.cs | 380 +- .../Windows/Forms/AssemblyAttributes.cs | 14 +- .../Windows/Forms/AutoCompleteSource.cs | 2 +- .../Forms/AutoCompleteStringCollection.cs | 105 +- .../AutomationNotificationProcessing.cs | 6 +- .../src/System/Windows/Forms/AxHost.cs | 4502 ++-- .../System/Windows/Forms/BaseCollection.cs | 3 +- .../src/System/Windows/Forms/Binding.cs | 6 +- .../System/Windows/Forms/BindingContext.cs | 2 +- .../Windows/Forms/BindingManagerBase.cs | 4 +- .../BindingManagerDataErrorEventHandler.cs | 3 +- .../System/Windows/Forms/BindingNavigator.cs | 496 +- .../src/System/Windows/Forms/Border3DSide.cs | 2 +- .../src/System/Windows/Forms/Button.cs | 170 +- .../src/System/Windows/Forms/ButtonBase.cs | 814 +- .../Forms/ButtonInternal/ButtonBaseAdapter.cs | 1061 +- .../Forms/ButtonInternal/ButtonFlatAdapter.cs | 201 +- .../ButtonInternal/ButtonPopupAdapter.cs | 95 +- .../ButtonInternal/ButtonStandardAdapter.cs | 158 +- .../ButtonInternal/CheckBoxBaseAdapter.cs | 220 +- .../ButtonInternal/CheckBoxFlatAdapter.cs | 73 +- .../ButtonInternal/CheckBoxPopupAdapter.cs | 73 +- .../ButtonInternal/CheckBoxStandardAdapter.cs | 110 +- .../CheckableControlBaseAdapter.cs | 62 +- .../ButtonInternal/RadioButtonBaseAdapter.cs | 175 +- .../ButtonInternal/RadioButtonFlatAdapter.cs | 63 +- .../ButtonInternal/RadioButtonPopupAdapter.cs | 58 +- .../RadioButtonStandardAdapter.cs | 66 +- .../System/Windows/Forms/ButtonRenderer.cs | 238 +- .../Forms/CacheVirtualItemsEventArgs.cs | 4 +- .../src/System/Windows/Forms/CheckBox.cs | 411 +- .../System/Windows/Forms/CheckBoxRenderer.cs | 620 +- .../System/Windows/Forms/CheckedListBox.cs | 844 +- .../src/System/Windows/Forms/Clipboard.cs | 302 +- .../src/System/Windows/Forms/CloseReason.cs | 2 +- .../src/System/Windows/Forms/ColorDialog.cs | 153 +- .../Windows/Forms/ColumnClickEventArgs.cs | 2 +- .../src/System/Windows/Forms/ColumnHeader.cs | 356 +- .../Windows/Forms/ColumnHeaderConverter.cs | 70 +- .../src/System/Windows/Forms/ComboBox.cs | 3067 ++- .../System/Windows/Forms/ComboBoxRenderer.cs | 71 +- .../src/System/Windows/Forms/Command.cs | 67 +- .../Windows/Forms/ComponentManagerBroker.cs | 352 +- .../COM2Interop/BaseCAMarshaler.cs | 72 +- .../COM2AboutBoxPropertyDescriptor.cs | 146 +- .../COM2Interop/COM2ColorConverter.cs | 96 +- .../COM2Interop/COM2ComponentEditor.cs | 201 +- .../COM2DataTypeToManagedDataTypeConverter.cs | 53 +- .../ComponentModel/COM2Interop/COM2Enum.cs | 94 +- .../COM2Interop/COM2EnumConverter.cs | 87 +- .../COM2ExtendedBrowsingHandler.cs | 56 +- .../COM2Interop/COM2ExtendedTypeConverter.cs | 183 +- .../COM2Interop/COM2ExtendedUITypeEditor.cs | 71 +- .../COM2Interop/COM2FontConverter.cs | 70 +- .../COM2ICategorizePropertiesHandler.cs | 55 +- .../COM2Interop/COM2IDispatchConverter.cs | 88 +- .../COM2IManagedPerPropertyBrowsingHandler.cs | 195 +- .../COM2IPerPropertyBrowsingHandler.cs | 409 +- .../COM2IProvidePropertyBuilderHandler.cs | 68 +- .../COM2IVsPerPropertyBrowsingHandler.cs | 420 +- .../COM2Interop/COM2PictureConverter.cs | 67 +- .../COM2Interop/COM2Properties.cs | 324 +- .../COM2PropertyBuilderUITypeEditor.cs | 59 +- .../COM2Interop/COM2PropertyDescriptor.cs | 1244 +- .../COM2PropertyDescriptorRefresh.cs | 36 +- .../COM2PropertyPageUITypeConverter.cs | 70 +- .../COM2Interop/COM2ShouldRefreshTypes.cs | 6 +- .../COM2Interop/COM2TypeInfoProcessor.cs | 1042 +- .../COM2Interop/ComNativeDescriptor.cs | 383 +- .../COM2Interop/Int32CAMarshaler.cs | 23 +- .../COM2Interop/OleStrCAMarshaler.cs | 23 +- .../ComponentModel/COM2Interop/_CTLBLDTYPE.cs | 12 +- .../System/Windows/Forms/ContainerControl.cs | 827 +- .../Windows/Forms/ContentsResizedEventArgs.cs | 2 +- .../src/System/Windows/Forms/ContextMenu.cs | 114 +- .../System/Windows/Forms/ContextMenuStrip.cs | 125 +- .../src/System/Windows/Forms/Control.cs | 10114 +++++---- .../src/System/Windows/Forms/ControlPaint.cs | 1636 +- .../System/Windows/Forms/ConvertEventArgs.cs | 2 +- .../System/Windows/Forms/CurrencyManager.cs | 581 +- .../src/System/Windows/Forms/Cursor.cs | 394 +- .../System/Windows/Forms/CursorConverter.cs | 109 +- .../src/System/Windows/Forms/Cursors.cs | 304 +- .../src/System/Windows/Forms/DataFormats.cs | 2 +- .../src/System/Windows/Forms/DataGrid.cs | 17399 ++++++++-------- .../System/Windows/Forms/DataGridAddNewRow.cs | 41 +- .../Windows/Forms/DataGridBoolColumn.cs | 238 +- .../System/Windows/Forms/DataGridCaption.cs | 486 +- .../Windows/Forms/DataGridColumnCollection.cs | 216 +- .../Windows/Forms/DataGridColumnStyle.cs | 2 +- ...DataGridDefaultColumnWidthTypeConverter.cs | 10 +- .../Windows/Forms/DataGridParentRows.cs | 553 +- .../Windows/Forms/DataGridRelationshipRow.cs | 471 +- .../src/System/Windows/Forms/DataGridRow.cs | 506 +- .../src/System/Windows/Forms/DataGridState.cs | 113 +- .../src/System/Windows/Forms/DataGridTable.cs | 924 +- .../Windows/Forms/DataGridTableCollection.cs | 156 +- .../System/Windows/Forms/DataGridTextBox.cs | 60 +- .../Windows/Forms/DataGridTextBoxColumn.cs | 239 +- .../System/Windows/Forms/DataGridToolTip.cs | 10 +- .../src/System/Windows/Forms/DataGridView.cs | 708 +- .../Forms/DataGridViewAccessibleObject.cs | 4 +- .../Forms/DataGridViewAdvancedBorderStyle.cs | 66 +- .../System/Windows/Forms/DataGridViewBand.cs | 8 +- .../Windows/Forms/DataGridViewButtonCell.cs | 170 +- .../Windows/Forms/DataGridViewButtonColumn.cs | 12 +- .../System/Windows/Forms/DataGridViewCell.cs | 58 +- .../Forms/DataGridViewCellCollection.cs | 32 +- .../Forms/DataGridViewCellConverter.cs | 21 +- ...ataGridViewCellErrorTextNeededEventArgs.cs | 2 +- .../DataGridViewCellFormattingEventArgs.cs | 4 +- .../Forms/DataGridViewCellMouseEventArgs.cs | 8 +- .../DataGridViewCellPaintingEventArgs.cs | 14 +- .../Windows/Forms/DataGridViewCellStyle.cs | 80 +- .../Forms/DataGridViewCellStyleConverter.cs | 27 +- ...aGridViewCellToolTipTextNeededEventArgs.cs | 2 +- .../Windows/Forms/DataGridViewCheckBoxCell.cs | 185 +- .../Forms/DataGridViewCheckBoxColumn.cs | 30 +- .../Windows/Forms/DataGridViewColumn.cs | 108 +- .../Forms/DataGridViewColumnCollection.cs | 129 +- .../Forms/DataGridViewColumnConverter.cs | 46 +- ...ridViewColumnDesignTimeVisibleAttribute.cs | 38 +- .../Forms/DataGridViewColumnHeaderCell.cs | 439 +- .../Windows/Forms/DataGridViewComboBoxCell.cs | 287 +- .../Forms/DataGridViewComboBoxColumn.cs | 24 +- .../DataGridViewComboBoxEditingControl.cs | 2 +- .../Forms/DataGridViewContentAlignment.cs | 14 +- .../Forms/DataGridViewDataConnection.cs | 20 +- .../Windows/Forms/DataGridViewEditingCell.cs | 2 +- .../Windows/Forms/DataGridViewElement.cs | 2 +- .../Forms/DataGridViewEventHandlers.cs | 2 +- .../Windows/Forms/DataGridViewHeaderCell.cs | 34 +- .../Forms/DataGridViewHitTestCloseEdge.cs | 10 +- .../Windows/Forms/DataGridViewHitTestInfo.cs | 22 +- .../Windows/Forms/DataGridViewImageCell.cs | 66 +- .../Windows/Forms/DataGridViewImageColumn.cs | 18 +- .../Windows/Forms/DataGridViewLinkCell.cs | 132 +- .../Windows/Forms/DataGridViewLinkColumn.cs | 2 +- .../Windows/Forms/DataGridViewMethods.cs | 4022 ++-- .../System/Windows/Forms/DataGridViewRow.cs | 4 +- .../Forms/DataGridViewRowCollection.cs | 442 +- .../Forms/DataGridViewRowHeaderCell.cs | 2 +- .../Forms/DataGridViewRowPrePaintEventArgs.cs | 46 +- .../DataGridViewRowStateChangedEventArgs.cs | 2 +- .../DataGridViewSelectedCellCollection.cs | 6 +- .../DataGridViewSelectedColumnCollection.cs | 6 +- .../DataGridViewSelectedRowCollection.cs | 6 +- .../Forms/DataGridViewSelectionMode.cs | 2 +- .../Forms/DataGridViewSortCompareEventArgs.cs | 4 +- .../Windows/Forms/DataGridViewTextBoxCell.cs | 134 +- .../Forms/DataGridViewTextBoxColumn.cs | 6 +- .../DataGridViewTextBoxEditingControl.cs | 6 +- .../Forms/DataGridViewTopLeftHeaderCell.cs | 20 +- .../DataGridViewTopRowAccessibleObject.cs | 6 +- .../Windows/Forms/DataGridViewUtilities.cs | 238 +- .../System/Windows/Forms/DateBoldEventArgs.cs | 2 +- .../System/Windows/Forms/DateTimePicker.cs | 903 +- .../src/System/Windows/Forms/Day.cs | 2 +- .../Forms/Design/ComponentEditorForm.cs | 289 +- .../Forms/Design/ComponentEditorPage.cs | 121 +- .../Windows/Forms/DisplayInformation.cs | 99 +- .../System/Windows/Forms/DockingAttribute.cs | 32 +- .../src/System/Windows/Forms/DomainUpDown.cs | 526 +- .../src/System/Windows/Forms/DragEventArgs.cs | 5 +- .../src/System/Windows/Forms/DrawItemState.cs | 2 +- .../DrawListViewColumnHeaderEventArgs.cs | 28 +- .../Forms/DrawListViewSubItemEventArgs.cs | 6 +- .../Forms/DrawListViewSubItemEventHandler.cs | 2 +- .../Windows/Forms/DrawTreeNodeEventArgs.cs | 2 +- .../src/System/Windows/Forms/DropSource.cs | 102 +- .../src/System/Windows/Forms/DropTarget.cs | 178 +- .../System/Windows/Forms/ErrorBlinkStyle.cs | 4 +- .../src/System/Windows/Forms/ErrorProvider.cs | 794 +- .../src/System/Windows/Forms/FileDialog.cs | 2 +- .../Windows/Forms/FileDialogCustomPlace.cs | 2 +- .../Forms/FileDialogCustomPlacesCollection.cs | 4 +- .../System/Windows/Forms/FileDialog_Vista.cs | 2 +- .../Windows/Forms/FlatButtonAppearance.cs | 104 +- .../System/Windows/Forms/FlowLayoutPanel.cs | 39 +- .../Windows/Forms/FlowLayoutSettings.cs | 38 +- .../src/System/Windows/Forms/FontDialog.cs | 333 +- .../src/System/Windows/Forms/Form.cs | 2897 ++- .../Windows/Forms/FormClosedEventArgs.cs | 2 +- .../Windows/Forms/FormClosingEventArgs.cs | 2 +- .../System/Windows/Forms/FormCollection.cs | 55 +- .../System/Windows/Forms/FxCopSuppression.cs | 913 +- .../Windows/Forms/GDI/TextFormatFlags.cs | 52 +- .../System/Windows/Forms/GDI/TextRenderer.cs | 113 +- .../Forms/GDI/WindowsGraphicsWrapper.cs | 42 +- .../Windows/Forms/GetChildAtPointSkip.cs | 4 +- .../src/System/Windows/Forms/GridItemType.cs | 2 +- .../src/System/Windows/Forms/GroupBox.cs | 394 +- .../System/Windows/Forms/GroupBoxRenderer.cs | 161 +- .../src/System/Windows/Forms/Help.cs | 290 +- .../src/System/Windows/Forms/HtmlDocument.cs | 56 +- .../src/System/Windows/Forms/HtmlElement.cs | 106 +- .../Windows/Forms/HtmlElementCollection.cs | 122 +- .../Windows/Forms/HtmlElementEventArgs.cs | 18 +- .../src/System/Windows/Forms/HtmlHistory.cs | 48 +- .../src/System/Windows/Forms/HtmlShim.cs | 127 +- .../System/Windows/Forms/HtmlShimManager.cs | 389 +- .../Windows/Forms/HtmlToClrEventProxy.cs | 68 +- .../src/System/Windows/Forms/HtmlWindow.cs | 14 +- .../Windows/Forms/HtmlWindowCollection.cs | 65 +- .../Windows/Forms/IMessageModifyAndFilter.cs | 1 - .../Windows/Forms/ImageIndexConverter.cs | 107 +- .../System/Windows/Forms/ImageKeyConverter.cs | 125 +- .../src/System/Windows/Forms/ImageLayout.cs | 2 +- .../src/System/Windows/Forms/ImageList.cs | 900 +- .../System/Windows/Forms/ImageListStreamer.cs | 199 +- .../src/System/Windows/Forms/InputLanguage.cs | 8 +- .../Windows/Forms/InputLanguageCollection.cs | 38 +- .../src/System/Windows/Forms/InsertKeyMode.cs | 2 +- .../Windows/Forms/ItemCheckedEventArgs.cs | 2 +- .../System/Windows/Forms/ItemDragEventArgs.cs | 4 +- .../src/System/Windows/Forms/KeyEventArgs.cs | 6 +- .../Forms/KeyboardToolTipStateMachine.cs | 225 +- .../src/System/Windows/Forms/Keys.cs | 332 +- .../src/System/Windows/Forms/KeysConverter.cs | 228 +- .../src/System/Windows/Forms/Label.cs | 1072 +- .../Forms/Layout/ArrangedElementCollection.cs | 92 +- .../Windows/Forms/Layout/CommonProperties.cs | 437 +- .../Forms/Layout/DockAndAnchorLayout.cs | 682 +- .../System/Windows/Forms/Layout/FlowLayout.cs | 475 +- .../Windows/Forms/Layout/LayoutEngine.cs | 4 +- .../Windows/Forms/Layout/LayoutSettings.cs | 26 +- .../Windows/Forms/Layout/LayoutUtils.cs | 640 +- .../Windows/Forms/Layout/PropertyNames.cs | 20 +- .../Windows/Forms/Layout/TableLayout.cs | 1501 +- .../src/System/Windows/Forms/LinkConverter.cs | 2 +- .../src/System/Windows/Forms/LinkLabel.cs | 1565 +- .../Forms/LinkLabelLinkClickedEventArgs.cs | 4 +- .../src/System/Windows/Forms/LinkUtilities.cs | 123 +- .../Windows/Forms/ListBindingConverter.cs | 92 +- .../System/Windows/Forms/ListBindingHelper.cs | 276 +- .../src/System/Windows/Forms/ListBox.cs | 2156 +- .../src/System/Windows/Forms/ListControl.cs | 2 +- .../System/Windows/Forms/ListItemConverter.cs | 10 +- .../src/System/Windows/Forms/ListView.cs | 4840 +++-- .../Windows/Forms/ListViewGroupCollection.cs | 6 +- .../Windows/Forms/ListViewGroupConverter.cs | 4 +- .../Windows/Forms/ListViewHitTestInfo.cs | 37 +- .../Windows/Forms/ListViewInsertionMark.cs | 73 +- .../src/System/Windows/Forms/ListViewItem.cs | 2 +- .../Forms/ListViewItemMouseHoverEventArgs.cs | 2 +- .../System/Windows/Forms/ListViewItemState.cs | 2 +- .../ListViewItemStateImageIndexConverter.cs | 85 +- .../Windows/Forms/LocalAppContextSwitches.cs | 54 +- .../src/System/Windows/Forms/MDIClient.cs | 203 +- .../System/Windows/Forms/MDIControlStrip.cs | 405 +- .../System/Windows/Forms/MDIWindowDialog.cs | 78 +- .../src/System/Windows/Forms/MainMenu.cs | 109 +- .../src/System/Windows/Forms/MaskedTextBox.cs | 817 +- .../Forms/MdiWindowListItemConverter.cs | 20 +- .../Windows/Forms/MdiWindowListStrip.cs | 121 +- .../Windows/Forms/MeasureItemEventArgs.cs | 2 +- .../src/System/Windows/Forms/Menu.cs | 703 +- .../src/System/Windows/Forms/MenuItem.cs | 5 +- .../src/System/Windows/Forms/MenuStrip.cs | 195 +- .../src/System/Windows/Forms/Message.cs | 2 +- .../src/System/Windows/Forms/MessageBox.cs | 281 +- .../System/Windows/Forms/MessageBoxIcon.cs | 4 +- .../System/Windows/Forms/MessageDecoder.cs | 7 +- .../src/System/Windows/Forms/MethodInvoker.cs | 5 +- .../src/System/Windows/Forms/MonthCalendar.cs | 1297 +- .../src/System/Windows/Forms/MouseButtons.cs | 8 +- .../src/System/Windows/Forms/NativeWindow.cs | 671 +- .../Forms/NoneExcludedImageIndexConverter.cs | 14 +- .../src/System/Windows/Forms/NotifyIcon.cs | 460 +- .../src/System/Windows/Forms/NumericUpDown.cs | 545 +- .../Forms/NumericUpDownAcceleration.cs | 12 +- .../NumericUpDownAccelerationCollection.cs | 30 +- .../System/Windows/Forms/OpenFileDialog.cs | 6 +- .../src/System/Windows/Forms/Padding.cs | 2 +- .../System/Windows/Forms/PaintEventArgs.cs | 8 +- .../src/System/Windows/Forms/Panel.cs | 117 +- .../src/System/Windows/Forms/PictureBox.cs | 578 +- .../System/Windows/Forms/PopupEventArgs.cs | 10 +- .../Windows/Forms/PreviewKeyDownEventArgs.cs | 8 +- .../Windows/Forms/Printing/PageSetupDialog.cs | 196 +- .../PrintControllerWithStatusDialog.cs | 147 +- .../Windows/Forms/Printing/PrintDialog.cs | 190 +- .../Forms/Printing/PrintPreviewControl.cs | 490 +- .../Forms/Printing/PrintPreviewDialog.cs | 827 +- .../Windows/Forms/ProfessionalColorTable.cs | 1230 +- .../Windows/Forms/ProfessionalColors.cs | 302 +- .../src/System/Windows/Forms/ProgressBar.cs | 422 +- .../Windows/Forms/ProgressBarRenderer.cs | 248 +- .../src/System/Windows/Forms/PropertyGrid.cs | 4249 ++-- .../ArrayElementGridEntry.cs | 56 +- .../PropertyGridInternal/CategoryGridEntry.cs | 223 +- .../Forms/PropertyGridInternal/DocComment.cs | 135 +- .../PropertyGridInternal/DropDownButton.cs | 189 +- .../Forms/PropertyGridInternal/GridEntry.cs | 2131 +- .../PropertyGridInternal/GridErrorDlg.cs | 169 +- .../Forms/PropertyGridInternal/GridToolTip.cs | 247 +- .../Forms/PropertyGridInternal/HotCommands.cs | 148 +- .../ImmutablePropertyDescriptorGridEntry.cs | 57 +- .../MergePropertyDescriptor.cs | 502 +- .../MultiPropertyDescriptorGridEntry.cs | 278 +- .../MultiSelectRootGridEntry.cs | 378 +- .../PropertyGridInternal/PropertiesTab.cs | 82 +- .../PropertyDescriptorGridEntry.cs | 827 +- .../PropertyGridCommands.cs | 14 +- .../PropertyGridInternal/PropertyGridView.cs | 5994 +++--- .../SingleSelectRootGridEntry.cs | 310 +- .../src/System/Windows/Forms/PropertyStore.cs | 4 +- .../Forms/PropertyTabChangedEventArgs.cs | 4 +- .../Forms/PropertyValueChangedEventArgs.cs | 2 +- .../Forms/QueryAccessibilityHelpEventArgs.cs | 2 +- .../src/System/Windows/Forms/RadioButton.cs | 373 +- .../Windows/Forms/RadioButtonRenderer.cs | 507 +- .../Windows/Forms/RelatedCurrencyManager.cs | 107 +- .../Forms/RelatedImageListAttribute.cs | 19 +- .../Windows/Forms/RelatedPropertyManager.cs | 61 +- .../src/System/Windows/Forms/RichTextBox.cs | 1934 +- .../Windows/Forms/RichTextBoxConstants.cs | 628 +- .../System/Windows/Forms/RichTextBoxFinds.cs | 2 +- .../Forms/RichTextBoxLanguageOptions.cs | 4 +- .../System/Windows/Forms/SaveFileDialog.cs | 74 +- .../src/System/Windows/Forms/Screen.cs | 211 +- .../System/Windows/Forms/ScrollBarRenderer.cs | 376 +- .../src/System/Windows/Forms/ScrollBars.cs | 4 +- .../System/Windows/Forms/ScrollEventArgs.cs | 11 +- .../System/Windows/Forms/ScrollableControl.cs | 822 +- .../Forms/SearchForVirtualItemEventArgs.cs | 2 +- .../Forms/SelectedGridItemChangedEventArgs.cs | 2 +- .../System/Windows/Forms/SelectionRange.cs | 46 +- .../Windows/Forms/SelectionRangeConverter.cs | 112 +- .../src/System/Windows/Forms/SendKeys.cs | 400 +- .../System/Windows/Forms/SplitContainer.cs | 1379 +- .../src/System/Windows/Forms/Splitter.cs | 503 +- .../Windows/Forms/SplitterCancelEventArgs.cs | 4 +- .../src/System/Windows/Forms/SplitterPanel.cs | 279 +- .../src/System/Windows/Forms/StatusBar.cs | 992 +- .../System/Windows/Forms/StatusBarPanel.cs | 363 +- .../Forms/StatusBarPanelClickEventHandler.cs | 3 +- .../src/System/Windows/Forms/StatusStrip.cs | 1056 +- .../src/System/Windows/Forms/StringSorter.cs | 128 +- .../src/System/Windows/Forms/StringSource.cs | 47 +- .../System/Windows/Forms/SystemInformation.cs | 2 +- .../src/System/Windows/Forms/TabControl.cs | 1337 +- .../Forms/TabControlCancelEventArgs.cs | 2 +- .../src/System/Windows/Forms/TabPage.cs | 459 +- .../src/System/Windows/Forms/TabRenderer.cs | 363 +- .../Forms/TableLayoutColumnStyleCollection.cs | 20 +- .../System/Windows/Forms/TableLayoutPanel.cs | 418 +- .../Forms/TableLayoutPanelCellPosition.cs | 2 +- .../Forms/TableLayoutRowStyleCollection.cs | 24 +- .../Windows/Forms/TableLayoutSettings.cs | 457 +- .../Forms/TableLayoutSettingsTypeConverter.cs | 202 +- .../System/Windows/Forms/TableLayoutStyle.cs | 54 +- .../Forms/TableLayoutStyleCollection.cs | 4 +- .../src/System/Windows/Forms/TextBox.cs | 427 +- .../TextBoxAutoCompleteSourceConverter.cs | 28 +- .../src/System/Windows/Forms/TextBoxBase.cs | 1117 +- .../System/Windows/Forms/TextBoxRenderer.cs | 51 +- .../Windows/Forms/ThreadExceptionDialog.cs | 161 +- .../src/System/Windows/Forms/ToolBar.cs | 994 +- .../src/System/Windows/Forms/ToolBarButton.cs | 439 +- .../src/System/Windows/Forms/ToolStrip.cs | 4891 +++-- .../System/Windows/Forms/ToolStripButton.cs | 214 +- .../System/Windows/Forms/ToolStripComboBox.cs | 555 +- .../Windows/Forms/ToolStripContainer.cs | 235 +- .../Windows/Forms/ToolStripContentPanel.cs | 323 +- .../Windows/Forms/ToolStripControlHost.cs | 1096 +- .../System/Windows/Forms/ToolStripDropDown.cs | 1806 +- .../Windows/Forms/ToolStripDropDownButton.cs | 301 +- .../Forms/ToolStripDropDownDirection.cs | 12 +- .../Windows/Forms/ToolStripDropDownItem.cs | 824 +- .../Windows/Forms/ToolStripDropDownMenu.cs | 1477 +- .../Forms/ToolStripDropTargetManager.cs | 239 +- .../src/System/Windows/Forms/ToolStripGrip.cs | 265 +- .../Forms/ToolStripHighContrastRenderer.cs | 759 +- .../src/System/Windows/Forms/ToolStripItem.cs | 3587 ++-- .../Windows/Forms/ToolStripItemAlignment.cs | 4 +- .../Windows/Forms/ToolStripItemCollection.cs | 376 +- .../Forms/ToolStripItemDisplayStyle.cs | 8 +- .../Windows/Forms/ToolStripItemEventArgs.cs | 2 +- .../ToolStripItemImageRenderEventArgs.cs | 8 +- .../Forms/ToolStripItemImageScaling.cs | 4 +- .../Forms/ToolStripItemRenderEventArgs.cs | 8 +- .../Windows/Forms/ToolStripItemStates.cs | 10 +- .../Forms/ToolStripItemTextRenderEventArgs.cs | 2 +- .../System/Windows/Forms/ToolStripLabel.cs | 457 +- .../Windows/Forms/ToolStripLayoutStyle.cs | 4 +- .../System/Windows/Forms/ToolStripManager.cs | 1314 +- .../Forms/ToolStripManagerRenderMode.cs | 2 +- .../System/Windows/Forms/ToolStripMenuItem.cs | 1277 +- .../System/Windows/Forms/ToolStripOverflow.cs | 121 +- .../Windows/Forms/ToolStripOverflowButton.cs | 135 +- .../System/Windows/Forms/ToolStripPanel.cs | 1095 +- .../Windows/Forms/ToolStripPanelCell.cs | 335 +- .../System/Windows/Forms/ToolStripPanelRow.cs | 2157 +- ...lStripProfessionalLowResolutionRenderer.cs | 83 +- .../Windows/Forms/ToolStripProgressBar.cs | 223 +- .../Windows/Forms/ToolStripRenderEventArgs.cs | 19 +- .../System/Windows/Forms/ToolStripRenderer.cs | 855 +- .../Forms/ToolStripRendererSwitcher.cs | 184 +- .../Windows/Forms/ToolStripScrollButton.cs | 161 +- .../Windows/Forms/ToolStripSeparator.cs | 886 +- .../System/Windows/Forms/ToolStripSettings.cs | 375 +- .../Windows/Forms/ToolStripSplitButton.cs | 733 +- .../Forms/ToolStripSplitStackLayout.cs | 458 +- .../Windows/Forms/ToolStripStatusLabel.cs | 185 +- .../Windows/Forms/ToolStripSystemRenderer.cs | 808 +- .../System/Windows/Forms/ToolStripTextBox.cs | 986 +- .../src/System/Windows/Forms/ToolTip.cs | 1704 +- .../Forms/ToolstripProfessionalRenderer.cs | 1195 +- .../src/System/Windows/Forms/TrackBar.cs | 583 +- .../System/Windows/Forms/TrackBarRenderer.cs | 504 +- .../src/System/Windows/Forms/TreeNode.cs | 1125 +- .../Windows/Forms/TreeNodeCollection.cs | 386 +- .../System/Windows/Forms/TreeNodeConverter.cs | 70 +- .../Forms/TreeNodeMouseHoverEventArgs.cs | 2 +- .../src/System/Windows/Forms/TreeView.cs | 1661 +- .../System/Windows/Forms/TreeViewAction.cs | 4 +- .../Windows/Forms/TreeViewCancelEventArgs.cs | 25 +- .../System/Windows/Forms/TreeViewEventArgs.cs | 32 +- .../Windows/Forms/TreeViewHitTestInfo.cs | 27 +- .../Windows/Forms/TreeViewHitTestLocation.cs | 4 +- .../Forms/TreeViewImageIndexConverter.cs | 100 +- .../Forms/TreeViewImageKeyConverter.cs | 25 +- .../src/System/Windows/Forms/Triangle.cs | 41 +- .../src/System/Windows/Forms/UICues.cs | 12 +- .../System/Windows/Forms/UICuesEventArgs.cs | 10 +- .../src/System/Windows/Forms/UpDownBase.cs | 871 +- .../src/System/Windows/Forms/UserControl.cs | 156 +- .../Forms/VisualStyles/BackgroundType.cs | 14 +- .../Forms/VisualStyles/BooleanProperty.cs | 26 +- .../Windows/Forms/VisualStyles/BorderType.cs | 14 +- .../Forms/VisualStyles/CheckBoxState.cs | 22 +- .../Forms/VisualStyles/ColorProperty.cs | 92 +- .../Forms/VisualStyles/ContentAlignment.cs | 12 +- .../Windows/Forms/VisualStyles/EdgeEffects.cs | 12 +- .../Windows/Forms/VisualStyles/EdgeStyle.cs | 16 +- .../Windows/Forms/VisualStyles/Edges.cs | 36 +- .../Forms/VisualStyles/EnumProperty.cs | 58 +- .../Forms/VisualStyles/FilenameProperty.cs | 32 +- .../Windows/Forms/VisualStyles/FillType.cs | 22 +- .../Forms/VisualStyles/FontProperty.cs | 4 +- .../Forms/VisualStyles/GlyphFontSizingType.cs | 12 +- .../Windows/Forms/VisualStyles/GlyphType.cs | 12 +- .../Forms/VisualStyles/GroupBoxState.cs | 4 +- .../Windows/Forms/VisualStyles/HitTestCode.cs | 40 +- .../Forms/VisualStyles/HitTestOptions.cs | 90 +- .../Forms/VisualStyles/HorizontalAlign.cs | 12 +- .../Windows/Forms/VisualStyles/IconEffect.cs | 20 +- .../Forms/VisualStyles/ImageOrientation.cs | 10 +- .../Forms/VisualStyles/ImageSelectType.cs | 12 +- .../Forms/VisualStyles/IntegerProperty.cs | 96 +- .../Forms/VisualStyles/MarginProperty.cs | 12 +- .../Windows/Forms/VisualStyles/OffsetType.cs | 56 +- .../Forms/VisualStyles/PointProperty.cs | 32 +- .../Forms/VisualStyles/RadioButtonState.cs | 16 +- .../Windows/Forms/VisualStyles/SizingType.cs | 14 +- .../Forms/VisualStyles/StringProperty.cs | 4 +- .../Windows/Forms/VisualStyles/TextMetrics.cs | 44 +- .../VisualStyles/TextMetricsCharacterSet.cs | 82 +- .../TextMetricsPitchAndFamilyValues.cs | 14 +- .../Forms/VisualStyles/TextShadowType.cs | 12 +- .../Forms/VisualStyles/TrueSizeScalingType.cs | 12 +- .../Forms/VisualStyles/VerticalAlignment.cs | 12 +- .../Forms/VisualStyles/VisualStyleElement.cs | 6799 +++--- .../VisualStyles/VisualStyleInformation.cs | 197 +- .../Forms/VisualStyles/VisualStyleRenderer.cs | 668 +- .../Forms/VisualStyles/VisualStyleState.cs | 4 +- .../src/System/Windows/Forms/WebBrowser.cs | 800 +- .../System/Windows/Forms/WebBrowserBase.cs | 815 +- .../Windows/Forms/WebBrowserContainer.cs | 245 +- .../WebBrowserDocumentCompletedEventArgs.cs | 2 +- .../Forms/WebBrowserEncryptionLevel.cs | 2 +- .../System/Windows/Forms/WebBrowserHelper.cs | 75 +- .../Forms/WebBrowserNavigatedEventArgs.cs | 2 +- .../Forms/WebBrowserNavigatingEventArgs.cs | 6 +- .../WebBrowserProgressChangedEventArgs.cs | 4 +- .../Windows/Forms/WebBrowserSiteBase.cs | 198 +- .../Forms/WebBrowserUriTypeConverter.cs | 10 +- .../Windows/Forms/WinCategoryAttribute.cs | 22 +- .../src/System/Windows/Forms/WinFormsUtils.cs | 6 +- .../Forms/WindowsFormsSectionHandler.cs | 53 +- .../WindowsFormsSynchronizationContext.cs | 113 +- .../src/System/Windows/Forms/control.ime.cs | 887 +- .../src/System/Windows/Forms/formatter.cs | 276 +- .../src/misc/CompatibleIComparer.cs | 30 +- .../src/misc/CoreSwitches.cs | 25 +- src/System.Windows.Forms/src/misc/DbgUtil.cs | 130 +- .../src/misc/GDI/ApplyGraphicsProperties.cs | 8 +- .../src/misc/GDI/DeviceCapabilities.cs | 32 +- .../src/misc/GDI/DeviceContext.cs | 255 +- .../src/misc/GDI/DeviceContext2.cs | 184 +- .../misc/GDI/DeviceContextBackgroundMode.cs | 2 +- .../src/misc/GDI/DeviceContextGraphicsMode.cs | 4 +- .../src/misc/GDI/DeviceContextLayout.cs | 4 +- .../src/misc/GDI/DeviceContextMapMode.cs | 18 +- .../GDI/DeviceContextRasterOperationFlags.cs | 36 +- .../misc/GDI/DeviceContextTextAlignment.cs | 22 +- .../src/misc/GDI/DeviceContextType.cs | 12 +- .../src/misc/GDI/DeviceContexts.cs | 39 +- .../src/misc/GDI/FxCopSuppression.cs | 134 +- .../src/misc/GDI/GdiObjectType.cs | 30 +- .../src/misc/GDI/MeasurementDCInfo.cs | 142 +- .../src/misc/GDI/NativeMethods.cs | 333 +- .../src/misc/GDI/SafeNativeMethods.cs | 52 +- .../src/misc/GDI/TextPaddingOptions.cs | 2 +- .../src/misc/GDI/UnsafeNativeMethods.cs | 357 +- .../src/misc/GDI/WindowsBrush.cs | 30 +- .../src/misc/GDI/WindowsFont.cs | 211 +- .../src/misc/GDI/WindowsFontQuality.cs | 2 +- .../src/misc/GDI/WindowsGraphics.cs | 89 +- .../src/misc/GDI/WindowsGraphics2.cs | 197 +- .../misc/GDI/WindowsGraphicsCacheManager.cs | 83 +- .../src/misc/GDI/WindowsPen.cs | 104 +- .../src/misc/GDI/WindowsPenStyle.cs | 40 +- .../src/misc/GDI/WindowsRegion.cs | 97 +- .../src/misc/GDI/WindowsRegionCombineMode.cs | 12 +- .../src/misc/GDI/WindowsSolidBrush.cs | 30 +- .../src/misc/ImageListUtils.cs | 42 +- .../src/misc/InvariantComparer.cs | 20 +- .../src/misc/MultitargetUtil.cs | 7 +- .../src/misc/WeakHashtable.cs | 15 +- 554 files changed, 121541 insertions(+), 80940 deletions(-) diff --git a/src/Common/src/ClientUtils.cs b/src/Common/src/ClientUtils.cs index 1be61c52421..0913d99e0ed 100644 --- a/src/Common/src/ClientUtils.cs +++ b/src/Common/src/ClientUtils.cs @@ -3,8 +3,8 @@ // See the LICENSE file in the project root for more information. -#if DRAWING_DESIGN_NAMESPACE - namespace System.Windows.Forms +#if DRAWING_DESIGN_NAMESPACE +namespace System.Windows.Forms #elif DRAWING_NAMESPACE namespace System.Drawing #elif WINFORMS_PUBLIC_GRAPHICS_LIBRARY @@ -23,17 +23,19 @@ namespace System.Windows.Forms using System.Reflection; // Miscellaneous utilities - static internal class ClientUtils { + static internal class ClientUtils + { private const int SurrogateRangeStart = 0xD800; private const int SurrogateRangeEnd = 0xDFFF; -// ExecutionEngineException is obsolete and shouldn't be used (to catch, throw or reference) anymore. -// Pragma added to prevent converting the "type is obsolete" warning into build error. -// File owner should fix this. + // ExecutionEngineException is obsolete and shouldn't be used (to catch, throw or reference) anymore. + // Pragma added to prevent converting the "type is obsolete" warning into build error. + // File owner should fix this. #pragma warning disable 618 [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - public static bool IsCriticalException(Exception ex) { + public static bool IsCriticalException(Exception ex) + { return ex is NullReferenceException || ex is StackOverflowException || ex is OutOfMemoryException @@ -45,27 +47,30 @@ public static bool IsCriticalException(Exception ex) { #pragma warning restore 618 [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - public static bool IsSecurityOrCriticalException(Exception ex) { + public static bool IsSecurityOrCriticalException(Exception ex) + { return (ex is System.Security.SecurityException) || IsCriticalException(ex); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - public static int GetBitCount(uint x) { - int count = 0; - while (x > 0){ - x &= x - 1; - count++; - } - return count; + public static int GetBitCount(uint x) + { + int count = 0; + while (x > 0) + { + x &= x - 1; + count++; + } + return count; } - + // Sequential version // assumes sequential enum members 0,1,2,3,4 -etc. // [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool IsEnumValid(Enum enumValue, int value, int minValue, int maxValue) - { + { bool valid = (value >= minValue) && (value <= maxValue); #if DEBUG Debug_SequentialEnumIsDefinedCheck(enumValue, minValue, maxValue); @@ -81,16 +86,17 @@ public static bool IsEnumValid(Enum enumValue, int value, int minValue, int maxV // [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] - public static bool IsEnumValid(Enum enumValue, int value, int minValue, int maxValue, int maxNumberOfBitsOn) { - System.Diagnostics.Debug.Assert(maxNumberOfBitsOn >=0 && maxNumberOfBitsOn<32, "expect this to be greater than zero and less than 32"); + public static bool IsEnumValid(Enum enumValue, int value, int minValue, int maxValue, int maxNumberOfBitsOn) + { + System.Diagnostics.Debug.Assert(maxNumberOfBitsOn >= 0 && maxNumberOfBitsOn < 32, "expect this to be greater than zero and less than 32"); bool valid = (value >= minValue) && (value <= maxValue); //Note: if it's 0, it'll have no bits on. If it's a power of 2, it'll have 1. - valid = (valid && GetBitCount((uint)value) <= maxNumberOfBitsOn); + valid = (valid && GetBitCount((uint)value) <= maxNumberOfBitsOn); #if DEBUG Debug_NonSequentialEnumIsDefinedCheck(enumValue, minValue, maxValue, maxNumberOfBitsOn, valid); #endif - return valid; + return valid; } // Useful for enums that are a subset of a bitmask @@ -101,7 +107,8 @@ public static bool IsEnumValid(Enum enumValue, int value, int minValue, int maxV // [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] - public static bool IsEnumValid_Masked(Enum enumValue, int value, uint mask) { + public static bool IsEnumValid_Masked(Enum enumValue, int value, uint mask) + { bool valid = ((value & mask) == value); #if DEBUG @@ -111,7 +118,7 @@ public static bool IsEnumValid_Masked(Enum enumValue, int value, uint mask) { return valid; } - + @@ -129,14 +136,17 @@ public static bool IsEnumValid_Masked(Enum enumValue, int value, uint mask) { // // PERF tip: put the default value in the enum towards the front of the argument list. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - public static bool IsEnumValid_NotSequential(System.Enum enumValue, int value, params int[] enumValues) { - System.Diagnostics.Debug.Assert(Enum.GetValues(enumValue.GetType()).Length == enumValues.Length, "Not all the enum members were passed in."); - for (int i = 0; i < enumValues.Length; i++){ - if (enumValues[i] == value){ - return true; - } - } - return false; + public static bool IsEnumValid_NotSequential(System.Enum enumValue, int value, params int[] enumValues) + { + System.Diagnostics.Debug.Assert(Enum.GetValues(enumValue.GetType()).Length == enumValues.Length, "Not all the enum members were passed in."); + for (int i = 0; i < enumValues.Length; i++) + { + if (enumValues[i] == value) + { + return true; + } + } + return false; } private enum CharType @@ -179,27 +189,31 @@ public static int GetWordBoundaryStart(char[] text, int endIndex) [ThreadStatic] private static Hashtable enumValueInfo; public const int MAXCACHE = 300; // we think we're going to get O(100) of these, put in a tripwire if it gets larger. - + [SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")] - private class SequentialEnumInfo { + private class SequentialEnumInfo + { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - public SequentialEnumInfo(Type t) { + public SequentialEnumInfo(Type t) + { int actualMinimum = int.MaxValue; int actualMaximum = int.MinValue; int countEnumVals = 0; - - foreach (int iVal in Enum.GetValues(t)){ + + foreach (int iVal in Enum.GetValues(t)) + { actualMinimum = Math.Min(actualMinimum, iVal); actualMaximum = Math.Max(actualMaximum, iVal); countEnumVals++; } - - if (countEnumVals -1 != (actualMaximum - actualMinimum)) { + + if (countEnumVals - 1 != (actualMaximum - actualMinimum)) + { Debug.Fail("this enum cannot be sequential."); } MinValue = actualMinimum; MaxValue = actualMaximum; - + } public int MinValue; public int MaxValue; @@ -209,48 +223,57 @@ public SequentialEnumInfo(Type t) { [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")] - private static void Debug_SequentialEnumIsDefinedCheck(System.Enum value, int minVal, int maxVal) { + private static void Debug_SequentialEnumIsDefinedCheck(System.Enum value, int minVal, int maxVal) + { Type t = value.GetType(); - if (enumValueInfo == null) { + if (enumValueInfo == null) + { enumValueInfo = new Hashtable(); } SequentialEnumInfo sequentialEnumInfo = null; - if (enumValueInfo.ContainsKey(t)) { + if (enumValueInfo.ContainsKey(t)) + { sequentialEnumInfo = enumValueInfo[t] as SequentialEnumInfo; } - if (sequentialEnumInfo == null) { + if (sequentialEnumInfo == null) + { sequentialEnumInfo = new SequentialEnumInfo(t); - if (enumValueInfo.Count > MAXCACHE) { + if (enumValueInfo.Count > MAXCACHE) + { // see comment next to MAXCACHE declaration. Debug.Fail("cache is too bloated, clearing out, we need to revisit this."); enumValueInfo.Clear(); } enumValueInfo[t] = sequentialEnumInfo; - + } - if (minVal != sequentialEnumInfo.MinValue) { + if (minVal != sequentialEnumInfo.MinValue) + { // put string allocation in the IF block so the common case doesnt build up the string. System.Diagnostics.Debug.Fail("Minimum passed in is not the actual minimum for the enum. Consider changing the parameters or using a different function."); } - if (maxVal != sequentialEnumInfo.MaxValue) { + if (maxVal != sequentialEnumInfo.MaxValue) + { // put string allocation in the IF block so the common case doesnt build up the string. Debug.Fail("Maximum passed in is not the actual maximum for the enum. Consider changing the parameters or using a different function."); } } - + [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - private static void Debug_ValidateMask(System.Enum value, uint mask) { + private static void Debug_ValidateMask(System.Enum value, uint mask) + { Type t = value.GetType(); uint newmask = 0; - foreach (int iVal in Enum.GetValues(t)){ + foreach (int iVal in Enum.GetValues(t)) + { newmask = newmask | (uint)iVal; } System.Diagnostics.Debug.Assert(newmask == mask, "Mask not valid in IsEnumValid!"); @@ -310,19 +333,23 @@ private static void Debug_NonSequentialEnumIsDefinedCheck(System.Enum value, int /// /// #if DRAWING_DESIGN_NAMESPACE || WINFORMS_PUBLIC_GRAPHICS_LIBRARY || DRAWING_NAMESPACE - internal class WeakRefCollection : IList { + internal class WeakRefCollection : IList + { private int refCheckThreshold = int.MaxValue; // this means this is disabled by default. private ArrayList _innerList; - internal WeakRefCollection() { + internal WeakRefCollection() + { _innerList = new ArrayList(4); } - internal WeakRefCollection(int size) { + internal WeakRefCollection(int size) + { _innerList = new ArrayList(size); } - internal ArrayList InnerList { + internal ArrayList InnerList + { get { return _innerList; } } @@ -333,59 +360,76 @@ internal ArrayList InnerList { /// removed - Remove(item) and Contains(item) will not find it anymore. /// /// - public int RefCheckThreshold { - get{ + public int RefCheckThreshold + { + get + { return this.refCheckThreshold; } - set { + set + { this.refCheckThreshold = value; } } - public object this[int index] { - get { + public object this[int index] + { + get + { WeakRefObject weakRef = InnerList[index] as WeakRefObject; - if ((weakRef != null) && (weakRef.IsAlive)) { + if ((weakRef != null) && (weakRef.IsAlive)) + { return weakRef.Target; } return null; } - set { + set + { InnerList[index] = CreateWeakRefObject(value); } } - public void ScavengeReferences() { + public void ScavengeReferences() + { int currentIndex = 0; int currentCount = Count; - for (int i = 0; i < currentCount; i++) { + for (int i = 0; i < currentCount; i++) + { object item = this[currentIndex]; - if (item == null) { + if (item == null) + { InnerList.RemoveAt(currentIndex); } - else { // only incriment if we have not removed the item + else + { // only incriment if we have not removed the item currentIndex++; } } } - public override bool Equals(object obj) { + public override bool Equals(object obj) + { WeakRefCollection other = obj as WeakRefCollection; - if (other == this) { + if (other == this) + { return true; } - if (other == null || Count != other.Count) { + if (other == null || Count != other.Count) + { return false; } - for (int i = 0; i < Count; i++) { - if( this.InnerList[i] != other.InnerList[i] ) { - if( this.InnerList[i] == null || !this.InnerList[i].Equals(other.InnerList[i])) { + for (int i = 0; i < Count; i++) + { + if (this.InnerList[i] != other.InnerList[i]) + { + if (this.InnerList[i] == null || !this.InnerList[i].Equals(other.InnerList[i])) + { return false; } } @@ -394,30 +438,38 @@ public override bool Equals(object obj) { return true; } - public override int GetHashCode() { - return base.GetHashCode(); + public override int GetHashCode() + { + return base.GetHashCode(); } - private WeakRefObject CreateWeakRefObject(object value) { - if (value == null) { + private WeakRefObject CreateWeakRefObject(object value) + { + if (value == null) + { return null; } return new WeakRefObject(value); } - private static void Copy(WeakRefCollection sourceList, int sourceIndex, WeakRefCollection destinationList, int destinationIndex, int length) { - if (sourceIndex < destinationIndex) { + private static void Copy(WeakRefCollection sourceList, int sourceIndex, WeakRefCollection destinationList, int destinationIndex, int length) + { + if (sourceIndex < destinationIndex) + { // We need to copy from the back forward to prevent overwrite if source and // destination lists are the same, so we need to flip the source/dest indices // to point at the end of the spans to be copied. sourceIndex = sourceIndex + length; destinationIndex = destinationIndex + length; - for (; length > 0; length--) { + for (; length > 0; length--) + { destinationList.InnerList[--destinationIndex] = sourceList.InnerList[--sourceIndex]; } } - else { - for (; length > 0; length--) { + else + { + for (; length > 0; length--) + { destinationList.InnerList[destinationIndex++] = sourceList.InnerList[sourceIndex++]; } } @@ -430,15 +482,19 @@ private static void Copy(WeakRefCollection sourceList, int sourceIndex, WeakRefC /// it. See WeakRefObject for more info. /// [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - public void RemoveByHashCode(object value) { - if( value == null ) { + public void RemoveByHashCode(object value) + { + if (value == null) + { return; } int hash = value.GetHashCode(); - for( int idx = 0; idx < this.InnerList.Count; idx++ ) { - if(this.InnerList[idx] != null && this.InnerList[idx].GetHashCode() == hash ) { + for (int idx = 0; idx < this.InnerList.Count; idx++) + { + if (this.InnerList[idx] != null && this.InnerList[idx].GetHashCode() == hash) + { this.RemoveAt(idx); return; } @@ -453,27 +509,30 @@ public void RemoveByHashCode(object value) { public void Remove(object value) { InnerList.Remove(CreateWeakRefObject(value)); } public int IndexOf(object value) { return InnerList.IndexOf(CreateWeakRefObject(value)); } public void Insert(int index, object value) { InnerList.Insert(index, CreateWeakRefObject(value)); } - public int Add(object value) { - if (this.Count > RefCheckThreshold) { + public int Add(object value) + { + if (this.Count > RefCheckThreshold) + { ScavengeReferences(); - } + } return InnerList.Add(CreateWeakRefObject(value)); } - #endregion + #endregion - #region ICollection Members + #region ICollection Members public int Count { get { return InnerList.Count; } } object ICollection.SyncRoot { get { return InnerList.SyncRoot; } } public bool IsReadOnly { get { return InnerList.IsReadOnly; } } public void CopyTo(Array array, int index) { InnerList.CopyTo(array, index); } bool ICollection.IsSynchronized { get { return InnerList.IsSynchronized; } } - #endregion + #endregion - #region IEnumerable Members - public IEnumerator GetEnumerator() { - return InnerList.GetEnumerator(); + #region IEnumerable Members + public IEnumerator GetEnumerator() + { + return InnerList.GetEnumerator(); } - #endregion + #endregion /// /// Wraps a weak ref object. @@ -482,43 +541,54 @@ public IEnumerator GetEnumerator() { /// has been added to a collection since Contains(WeakRef(item)) and Remove(WeakRef(item)) would /// not be able to identify the item. /// - internal class WeakRefObject { + internal class WeakRefObject + { int hash; WeakReference weakHolder; - internal WeakRefObject(object obj) { + internal WeakRefObject(object obj) + { Debug.Assert(obj != null, "Unexpected null object!"); weakHolder = new WeakReference(obj); hash = obj.GetHashCode(); } - internal bool IsAlive { + internal bool IsAlive + { get { return weakHolder.IsAlive; } } - internal object Target { - get { + internal object Target + { + get + { return weakHolder.Target; } } - public override int GetHashCode() { + public override int GetHashCode() + { return hash; } - public override bool Equals(object obj) { + public override bool Equals(object obj) + { WeakRefObject other = obj as WeakRefObject; - if( other == this ) { + if (other == this) + { return true; } - if (other == null ){ + if (other == null) + { return false; } - if( other.Target != this.Target ) { - if( this.Target == null || !this.Target.Equals(other.Target) ) { + if (other.Target != this.Target) + { + if (this.Target == null || !this.Target.Equals(other.Target)) + { return false; } } diff --git a/src/Common/src/CommonUnsafeNativeMethods.cs b/src/Common/src/CommonUnsafeNativeMethods.cs index 37a1ceb02b6..b363fff8457 100644 --- a/src/Common/src/CommonUnsafeNativeMethods.cs +++ b/src/Common/src/CommonUnsafeNativeMethods.cs @@ -18,22 +18,22 @@ internal class CommonUnsafeNativeMethods internal const int LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800; [DllImport(ExternDll.Kernel32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Ansi)] - + public static extern IntPtr GetProcAddress(HandleRef hModule, string lpProcName); [DllImport(ExternDll.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] - + public static extern IntPtr GetModuleHandle(string modName); [DllImport(ExternDll.Kernel32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)] - + private static extern IntPtr LoadLibraryEx(string lpModuleName, IntPtr hFile, uint dwFlags); [DllImport(ExternDll.Kernel32, CharSet = CharSet.Auto, SetLastError = true)] - + private static extern IntPtr LoadLibrary(string libname); [DllImport(ExternDll.Kernel32, CharSet = CharSet.Auto, SetLastError = true)] - + public static extern bool FreeLibrary(HandleRef hModule); /// @@ -71,11 +71,11 @@ public static IntPtr LoadLibraryFromSystemPathIfAvailable(string libraryName) // This section could go to Nativemethods.cs or Safenativemethods.cs but we have separate copies of them in each library (System.winforms, System.Design and System.Drawing). // These APIs are available starting Windows 10, version 1607 only. [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] - + internal static extern DpiAwarenessContext GetThreadDpiAwarenessContext(); [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] - + internal static extern DpiAwarenessContext SetThreadDpiAwarenessContext(DpiAwarenessContext dpiContext); [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] @@ -89,7 +89,7 @@ public static IntPtr LoadLibraryFromSystemPathIfAvailable(string libraryName) /// true/false public static bool TryFindDpiAwarenessContextsEqual(DpiAwarenessContext dpiContextA, DpiAwarenessContext dpiContextB) { - if(dpiContextA == DpiAwarenessContext.DPI_AWARENESS_CONTEXT_UNSPECIFIED && dpiContextB == DpiAwarenessContext.DPI_AWARENESS_CONTEXT_UNSPECIFIED) + if (dpiContextA == DpiAwarenessContext.DPI_AWARENESS_CONTEXT_UNSPECIFIED && dpiContextB == DpiAwarenessContext.DPI_AWARENESS_CONTEXT_UNSPECIFIED) { return true; } @@ -138,13 +138,13 @@ public static DpiAwarenessContext TrySetThreadDpiAwarenessContext(DpiAwarenessCo return DpiAwarenessContext.DPI_AWARENESS_CONTEXT_UNSPECIFIED; } } -/* - // Dpi awareness context values. Matching windows values. - public static readonly DPI_AWARENESS_CONTEXT DPI_AWARENESS_CONTEXT_UNAWARE = (-1); - public static readonly DPI_AWARENESS_CONTEXT DPI_AWARENESS_CONTEXT_SYSTEM_AWARE = (-2); - public static readonly DPI_AWARENESS_CONTEXT DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE = (-3); - public static readonly DPI_AWARENESS_CONTEXT DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = (-4); - public static readonly DPI_AWARENESS_CONTEXT DPI_AWARENESS_CONTEXT_UNSPECIFIED = (0);*/ + /* + // Dpi awareness context values. Matching windows values. + public static readonly DPI_AWARENESS_CONTEXT DPI_AWARENESS_CONTEXT_UNAWARE = (-1); + public static readonly DPI_AWARENESS_CONTEXT DPI_AWARENESS_CONTEXT_SYSTEM_AWARE = (-2); + public static readonly DPI_AWARENESS_CONTEXT DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE = (-3); + public static readonly DPI_AWARENESS_CONTEXT DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = (-4); + public static readonly DPI_AWARENESS_CONTEXT DPI_AWARENESS_CONTEXT_UNSPECIFIED = (0);*/ #endregion } } diff --git a/src/Common/src/CompModSwitches.cs b/src/Common/src/CompModSwitches.cs index a02feae0396..dc2beabf9b8 100644 --- a/src/Common/src/CompModSwitches.cs +++ b/src/Common/src/CompModSwitches.cs @@ -2,13 +2,15 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.ComponentModel.CompModSwitches.get_DGEditColumnEditing():System.Diagnostics.TraceSwitch")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.ComponentModel.CompModSwitches.get_LayoutPerformance():System.Diagnostics.TraceSwitch")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.ComponentModel.CompModSwitches.get_DGEditColumnEditing():System.Diagnostics.TraceSwitch")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.ComponentModel.CompModSwitches.get_LayoutPerformance():System.Diagnostics.TraceSwitch")] -namespace System.ComponentModel { +namespace System.ComponentModel +{ using System.Diagnostics; - internal static class CompModSwitches { + internal static class CompModSwitches + { private static TraceSwitch activeX; private static TraceSwitch flowLayout; @@ -44,270 +46,360 @@ internal static class CompModSwitches { private static BooleanSwitch s_traceCollect; private static BooleanSwitch s_commonDesignerServices; - public static TraceSwitch ActiveX { - get { - if (activeX == null) { + public static TraceSwitch ActiveX + { + get + { + if (activeX == null) + { activeX = new TraceSwitch("ActiveX", "Debug ActiveX sourcing"); } return activeX; } } - public static TraceSwitch DataCursor { - get { - if (dataCursor == null) { + public static TraceSwitch DataCursor + { + get + { + if (dataCursor == null) + { dataCursor = new TraceSwitch("Microsoft.WFC.Data.DataCursor", "DataCursor"); } return dataCursor; } } - public static TraceSwitch DataGridCursor { - get { - if (dataGridCursor == null) { + public static TraceSwitch DataGridCursor + { + get + { + if (dataGridCursor == null) + { dataGridCursor = new TraceSwitch("DataGridCursor", "DataGrid cursor tracing"); } return dataGridCursor; } } - public static TraceSwitch DataGridEditing { - get { - if (dataGridEditing == null) { + public static TraceSwitch DataGridEditing + { + get + { + if (dataGridEditing == null) + { dataGridEditing = new TraceSwitch("DataGridEditing", "DataGrid edit related tracing"); } return dataGridEditing; } } - public static TraceSwitch DataGridKeys { - get { - if (dataGridKeys == null) { + public static TraceSwitch DataGridKeys + { + get + { + if (dataGridKeys == null) + { dataGridKeys = new TraceSwitch("DataGridKeys", "DataGrid keystroke management tracing"); } return dataGridKeys; } } - public static TraceSwitch DataGridLayout { - get { - if (dataGridLayout == null) { + public static TraceSwitch DataGridLayout + { + get + { + if (dataGridLayout == null) + { dataGridLayout = new TraceSwitch("DataGridLayout", "DataGrid layout tracing"); } return dataGridLayout; } } - public static TraceSwitch DataGridPainting { - get { - if (dataGridPainting == null) { - dataGridPainting = new TraceSwitch("DataGridPainting" , "DataGrid Painting related tracing"); + public static TraceSwitch DataGridPainting + { + get + { + if (dataGridPainting == null) + { + dataGridPainting = new TraceSwitch("DataGridPainting", "DataGrid Painting related tracing"); } return dataGridPainting; } } - public static TraceSwitch DataGridParents { - get { - if (dataGridParents == null) { + public static TraceSwitch DataGridParents + { + get + { + if (dataGridParents == null) + { dataGridParents = new TraceSwitch("DataGridParents", "DataGrid parent rows"); } return dataGridParents; } } - public static TraceSwitch DataGridScrolling { - get { - if (dataGridScrolling == null) { + public static TraceSwitch DataGridScrolling + { + get + { + if (dataGridScrolling == null) + { dataGridScrolling = new TraceSwitch("DataGridScrolling", "DataGrid scrolling"); } return dataGridScrolling; } } - public static TraceSwitch DataGridSelection { - get { - if (dataGridSelection == null) { + public static TraceSwitch DataGridSelection + { + get + { + if (dataGridSelection == null) + { dataGridSelection = new TraceSwitch("DataGridSelection", "DataGrid selection management tracing"); } return dataGridSelection; } } - public static TraceSwitch DataObject { - get { - if (dataObject == null) { + public static TraceSwitch DataObject + { + get + { + if (dataObject == null) + { dataObject = new TraceSwitch("DataObject", "Enable tracing for the DataObject class."); } return dataObject; } } - public static TraceSwitch DataView { - get { - if (dataView == null) { + public static TraceSwitch DataView + { + get + { + if (dataView == null) + { dataView = new TraceSwitch("DataView", "DataView"); } return dataView; } } - public static TraceSwitch DebugGridView { - get { - if (debugGridView == null) { + public static TraceSwitch DebugGridView + { + get + { + if (debugGridView == null) + { debugGridView = new TraceSwitch("PSDEBUGGRIDVIEW", "Debug PropertyGridView"); } return debugGridView; } } - public static TraceSwitch DGCaptionPaint { - get { - if (dgCaptionPaint == null) { + public static TraceSwitch DGCaptionPaint + { + get + { + if (dgCaptionPaint == null) + { dgCaptionPaint = new TraceSwitch("DGCaptionPaint", "DataGridCaption"); } return dgCaptionPaint; } } - public static TraceSwitch DGEditColumnEditing { - get { - if (dgEditColumnEditing == null) { + public static TraceSwitch DGEditColumnEditing + { + get + { + if (dgEditColumnEditing == null) + { dgEditColumnEditing = new TraceSwitch("DGEditColumnEditing", "Editing related tracing"); } return dgEditColumnEditing; } } - public static TraceSwitch DGRelationShpRowLayout { - get { - if (dgRelationShpRowLayout == null) { + public static TraceSwitch DGRelationShpRowLayout + { + get + { + if (dgRelationShpRowLayout == null) + { dgRelationShpRowLayout = new TraceSwitch("DGRelationShpRowLayout", "Relationship row layout"); } return dgRelationShpRowLayout; } } - public static TraceSwitch DGRelationShpRowPaint { - get { - if (dgRelationShpRowPaint == null) { + public static TraceSwitch DGRelationShpRowPaint + { + get + { + if (dgRelationShpRowPaint == null) + { dgRelationShpRowPaint = new TraceSwitch("DGRelationShpRowPaint", "Relationship row painting"); } return dgRelationShpRowPaint; } } - public static TraceSwitch DGRowPaint { - get { - if (dgRowPaint == null) { + public static TraceSwitch DGRowPaint + { + get + { + if (dgRowPaint == null) + { dgRowPaint = new TraceSwitch("DGRowPaint", "DataGrid Simple Row painting stuff"); } return dgRowPaint; } } - public static TraceSwitch DragDrop { - get { - if (dragDrop == null) { + public static TraceSwitch DragDrop + { + get + { + if (dragDrop == null) + { dragDrop = new TraceSwitch("DragDrop", "Debug OLEDragDrop support in Controls"); } return dragDrop; } } - public static TraceSwitch FlowLayout { - get { - if (flowLayout == null) { + public static TraceSwitch FlowLayout + { + get + { + if (flowLayout == null) + { flowLayout = new TraceSwitch("FlowLayout", "Debug flow layout"); } return flowLayout; } } - public static TraceSwitch ImeMode { - get { - if (imeMode == null) { + public static TraceSwitch ImeMode + { + get + { + if (imeMode == null) + { imeMode = new TraceSwitch("ImeMode", "Debug IME Mode"); } return imeMode; } } - public static TraceSwitch LayoutPerformance { - get { - if (layoutPerformance == null) { + public static TraceSwitch LayoutPerformance + { + get + { + if (layoutPerformance == null) + { layoutPerformance = new TraceSwitch("LayoutPerformance", "Tracks layout events which impact performance."); } return layoutPerformance; } } - public static TraceSwitch LayoutSuspendResume { - get { - if (layoutSuspendResume == null) { + public static TraceSwitch LayoutSuspendResume + { + get + { + if (layoutSuspendResume == null) + { layoutSuspendResume = new TraceSwitch("LayoutSuspendResume", "Tracks SuspendLayout/ResumeLayout."); } return layoutSuspendResume; } } - public static BooleanSwitch LifetimeTracing { - get { - if (lifetimeTracing == null) { + public static BooleanSwitch LifetimeTracing + { + get + { + if (lifetimeTracing == null) + { lifetimeTracing = new BooleanSwitch("LifetimeTracing", "Track lifetime events. This will cause objects to track the stack at creation and dispose."); } return lifetimeTracing; } } - public static TraceSwitch MSAA { - get { - if (msaa == null) { + public static TraceSwitch MSAA + { + get + { + if (msaa == null) + { msaa = new TraceSwitch("MSAA", "Debug Microsoft Active Accessibility"); } return msaa; } } - public static TraceSwitch MSOComponentManager { - get { - if (msoComponentManager == null) { + public static TraceSwitch MSOComponentManager + { + get + { + if (msoComponentManager == null) + { msoComponentManager = new TraceSwitch("MSOComponentManager", "Debug MSO Component Manager support"); } return msoComponentManager; } } - public static TraceSwitch RichLayout { - get { - if (richLayout == null) { + public static TraceSwitch RichLayout + { + get + { + if (richLayout == null) + { richLayout = new TraceSwitch("RichLayout", "Debug layout in RichControls"); } return richLayout; } } - public static TraceSwitch SetBounds { - get { - if (setBounds == null) { + public static TraceSwitch SetBounds + { + get + { + if (setBounds == null) + { setBounds = new TraceSwitch("SetBounds", "Trace changes to control size/position."); } return setBounds; } } - public static TraceSwitch HandleLeak { - get { - if (s_handleLeak == null) { + public static TraceSwitch HandleLeak + { + get + { + if (s_handleLeak == null) + { s_handleLeak = new TraceSwitch("HANDLELEAK", "HandleCollector: Track Win32 Handle Leaks"); } return s_handleLeak; } } - public static BooleanSwitch TraceCollect { - get { - if (s_traceCollect == null) { + public static BooleanSwitch TraceCollect + { + get + { + if (s_traceCollect == null) + { s_traceCollect = new BooleanSwitch("TRACECOLLECT", "HandleCollector: Trace HandleCollector operations"); } return s_traceCollect; diff --git a/src/Common/src/DpiHelper.DpiAwarenessContext.cs b/src/Common/src/DpiHelper.DpiAwarenessContext.cs index 164bdc05712..f29f7696929 100644 --- a/src/Common/src/DpiHelper.DpiAwarenessContext.cs +++ b/src/Common/src/DpiHelper.DpiAwarenessContext.cs @@ -80,7 +80,7 @@ public void Dispose() { ResetDpiAwarenessContextChanges(); } - + /// /// resetting dpiawareness of the thread. /// diff --git a/src/Common/src/DpiHelper.cs b/src/Common/src/DpiHelper.cs index ca30e7a25e2..d0476a2d7a0 100644 --- a/src/Common/src/DpiHelper.cs +++ b/src/Common/src/DpiHelper.cs @@ -346,7 +346,7 @@ public static void ScaleButtonImageLogicalToDevice(Button button) /// Set, when the first (Parking)Window has been created. From that moment on, /// we will not be able nor allow to change the Process' DpiMode. /// - internal static bool FirstParkingWindowCreated {get; set;} + internal static bool FirstParkingWindowCreated { get; set; } /// /// Gets the DPI awareness. diff --git a/src/Common/src/ExternDll.cs b/src/Common/src/ExternDll.cs index 9476a81b2e7..5798cd45ba4 100644 --- a/src/Common/src/ExternDll.cs +++ b/src/Common/src/ExternDll.cs @@ -2,29 +2,31 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System { - internal static class ExternDll { +namespace System +{ + internal static class ExternDll + { #if FEATURE_PAL && !SILVERLIGHT - #if !PLATFORM_UNIX +#if !PLATFORM_UNIX internal const String DLLPREFIX = ""; internal const String DLLSUFFIX = ".dll"; - #else // !PLATFORM_UNIX - #if __APPLE__ +#else // !PLATFORM_UNIX +#if __APPLE__ internal const String DLLPREFIX = "lib"; internal const String DLLSUFFIX = ".dylib"; - #elif _AIX +#elif _AIX internal const String DLLPREFIX = "lib"; internal const String DLLSUFFIX = ".a"; - #elif __hppa__ || IA64 +#elif __hppa__ || IA64 internal const String DLLPREFIX = "lib"; internal const String DLLSUFFIX = ".sl"; - #else +#else internal const String DLLPREFIX = "lib"; internal const String DLLSUFFIX = ".so"; - #endif - #endif // !PLATFORM_UNIX +#endif +#endif // !PLATFORM_UNIX public const string Kernel32 = DLLPREFIX + "rotor_pal" + DLLSUFFIX; public const string User32 = DLLPREFIX + "rotor_pal" + DLLSUFFIX; @@ -41,44 +43,44 @@ internal static class ExternDll { public const string Advapi32 = "advapi32.dll"; public const string Comctl32 = "comctl32.dll"; public const string Comdlg32 = "comdlg32.dll"; - public const string Gdi32 = "gdi32.dll"; - public const string Gdiplus = "gdiplus.dll"; - public const string Hhctrl = "hhctrl.ocx"; - public const string Imm32 = "imm32.dll"; + public const string Gdi32 = "gdi32.dll"; + public const string Gdiplus = "gdiplus.dll"; + public const string Hhctrl = "hhctrl.ocx"; + public const string Imm32 = "imm32.dll"; public const string Kernel32 = "kernel32.dll"; public const string Loadperf = "Loadperf.dll"; - public const string Mscoree = "mscoree.dll"; - public const string Clr = "clr.dll"; - public const string Msi = "msi.dll"; - public const string Mqrt = "mqrt.dll"; - public const string Ntdll = "ntdll.dll"; - public const string Ole32 = "ole32.dll"; - public const string Oleacc = "oleacc.dll"; + public const string Mscoree = "mscoree.dll"; + public const string Clr = "clr.dll"; + public const string Msi = "msi.dll"; + public const string Mqrt = "mqrt.dll"; + public const string Ntdll = "ntdll.dll"; + public const string Ole32 = "ole32.dll"; + public const string Oleacc = "oleacc.dll"; public const string Oleaut32 = "oleaut32.dll"; public const string Olepro32 = "olepro32.dll"; public const string PerfCounter = "perfcounter.dll"; public const string Powrprof = "Powrprof.dll"; - public const string Psapi = "psapi.dll"; - public const string Shell32 = "shell32.dll"; - public const string User32 = "user32.dll"; - public const string Uxtheme = "uxtheme.dll"; - public const string WinMM = "winmm.dll"; + public const string Psapi = "psapi.dll"; + public const string Shell32 = "shell32.dll"; + public const string User32 = "user32.dll"; + public const string Uxtheme = "uxtheme.dll"; + public const string WinMM = "winmm.dll"; public const string Winspool = "winspool.drv"; public const string Wtsapi32 = "wtsapi32.dll"; - public const string Version = "version.dll"; + public const string Version = "version.dll"; public const string Vsassert = "vsassert.dll"; public const string Fxassert = "Fxassert.dll"; - public const string Shlwapi = "shlwapi.dll"; - public const string Crypt32 = "crypt32.dll"; - public const string ShCore = "SHCore.dll"; - public const string Wldp = "wldp.dll"; + public const string Shlwapi = "shlwapi.dll"; + public const string Crypt32 = "crypt32.dll"; + public const string ShCore = "SHCore.dll"; + public const string Wldp = "wldp.dll"; // system.data specific - internal const string Odbc32 = "odbc32.dll"; - internal const string SNI = "System.Data.dll"; + internal const string Odbc32 = "odbc32.dll"; + internal const string SNI = "System.Data.dll"; // system.data.oracleclient specific - internal const string OciDll = "oci.dll"; + internal const string OciDll = "oci.dll"; internal const string OraMtsDll = "oramts.dll"; // UI Automation diff --git a/src/Common/src/Interop/Interop.EditMessages.cs b/src/Common/src/Interop/Interop.EditMessages.cs index cc696a39c72..626eedb5930 100644 --- a/src/Common/src/Interop/Interop.EditMessages.cs +++ b/src/Common/src/Interop/Interop.EditMessages.cs @@ -25,7 +25,7 @@ public static class EditMessages public const int EM_LINEFROMCHAR = 0x00C9; public const int EM_GETFIRSTVISIBLELINE = 0x00CE; public const int EM_LINEINDEX = 0x00BB; - + public const int EM_GETLIMITTEXT = (WindowMessages.WM_USER + 37); public const int EM_POSFROMCHAR = (WindowMessages.WM_USER + 38); diff --git a/src/Common/src/Interop/Interop.HandleCollector.cs b/src/Common/src/Interop/Interop.HandleCollector.cs index 7879d78d694..54116d67c1e 100644 --- a/src/Common/src/Interop/Interop.HandleCollector.cs +++ b/src/Common/src/Interop/Interop.HandleCollector.cs @@ -251,7 +251,7 @@ internal IntPtr Remove(IntPtr handle) { return handle; } - + int currentCount = 0; lock (this) { diff --git a/src/Common/src/Interop/Interop.WindowMessages.cs b/src/Common/src/Interop/Interop.WindowMessages.cs index c65205b6454..003b4e2ad09 100644 --- a/src/Common/src/Interop/Interop.WindowMessages.cs +++ b/src/Common/src/Interop/Interop.WindowMessages.cs @@ -220,6 +220,6 @@ public static class WindowMessages public const int WM_APP = unchecked((int)0x8000); public const int WM_USER = 0x0400; public const int WM_REFLECT = WM_USER + 0x1C00; - public const int WM_CHOOSEFONT_GETLOGFONT = (0x0400+1); + public const int WM_CHOOSEFONT_GETLOGFONT = (0x0400 + 1); } } \ No newline at end of file diff --git a/src/Common/src/Interop/Shell32/Interop.SHBrowseForFolder.cs b/src/Common/src/Interop/Shell32/Interop.SHBrowseForFolder.cs index 19af10c12b0..8cb8027dfb0 100644 --- a/src/Common/src/Interop/Shell32/Interop.SHBrowseForFolder.cs +++ b/src/Common/src/Interop/Shell32/Interop.SHBrowseForFolder.cs @@ -24,7 +24,7 @@ public static class BrowseInfoFlags public const uint BIF_EDITBOX = 0x00000010; public const uint BIF_NEWDIALOGSTYLE = 0x00000040; public const uint BIF_NONEWFOLDERBUTTON = 0x00000200; - + public const uint BIF_BROWSEFORCOMPUTER = 0x00001000; public const uint BIF_BROWSEFORPRINTER = 0x00002000; public const uint BIF_BROWSEFOREVERYTHING = 0x00004000; @@ -37,7 +37,7 @@ public unsafe struct BROWSEINFO public CoTaskMemSafeHandle pidlRoot; - public char *pszDisplayName; + public char* pszDisplayName; public string lpszTitle; diff --git a/src/Common/src/Interop/User32/Interop.GetWindowText.cs b/src/Common/src/Interop/User32/Interop.GetWindowText.cs index db9345fecc1..76526864a18 100644 --- a/src/Common/src/Interop/User32/Interop.GetWindowText.cs +++ b/src/Common/src/Interop/User32/Interop.GetWindowText.cs @@ -13,7 +13,7 @@ public static partial class User32 public static extern int GetWindowTextLengthW(HandleRef hWnd); [DllImport(Libraries.User32, CharSet = CharSet.Unicode)] - private static unsafe extern int GetWindowTextW(HandleRef hWnd, char *lpString, int nMaxCount); + private static unsafe extern int GetWindowTextW(HandleRef hWnd, char* lpString, int nMaxCount); public static unsafe string GetWindowText(HandleRef hWnd) { @@ -24,7 +24,7 @@ public static unsafe string GetWindowText(HandleRef hWnd) int textLengthWithNullTerminator = GetWindowTextLengthW(hWnd) + 1; char[] windowTitleBuffer = ArrayPool.Shared.Rent(textLengthWithNullTerminator); string windowTitle; - fixed (char *pWindowTitle = windowTitleBuffer) + fixed (char* pWindowTitle = windowTitleBuffer) { int actualTextLength = GetWindowTextW(hWnd, pWindowTitle, textLengthWithNullTerminator + 1); @@ -35,10 +35,10 @@ public static unsafe string GetWindowText(HandleRef hWnd) ArrayPool.Shared.Return(windowTitleBuffer); continue; } - + windowTitle = new string(pWindowTitle, 0, actualTextLength); } - + ArrayPool.Shared.Return(windowTitleBuffer); return windowTitle; } diff --git a/src/Common/src/NativeMethods.cs b/src/Common/src/NativeMethods.cs index c502bb7f140..ac72b8afa13 100644 --- a/src/Common/src/NativeMethods.cs +++ b/src/Common/src/NativeMethods.cs @@ -55,11 +55,12 @@ internal static class NativeMethods public static IntPtr InvalidIntPtr = (IntPtr)(-1); public static IntPtr LPSTR_TEXTCALLBACK = (IntPtr)(-1); public static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero); - + public const int BITMAPINFO_MAX_COLORSIZE = 256; - public const int BI_BITFIELDS = 3; + public const int BI_BITFIELDS = 3; - public enum RegionFlags { + public enum RegionFlags + { ERROR = 0, NULLREGION = 1, SIMPLEREGION = 2, @@ -74,20 +75,20 @@ public const int public const int /* FONT WEIGHT (BOLD) VALUES */ - FW_DONTCARE = 0, - FW_NORMAL = 400, - FW_BOLD = 700, + FW_DONTCARE = 0, + FW_NORMAL = 400, + FW_BOLD = 700, // some others... /* FONT CHARACTER SET */ - ANSI_CHARSET = 0, - DEFAULT_CHARSET = 1, + ANSI_CHARSET = 0, + DEFAULT_CHARSET = 1, // plus others .... /* Font OutPrecision */ - OUT_DEFAULT_PRECIS = 0, - OUT_TT_PRECIS = 4, - OUT_TT_ONLY_PRECIS = 7, + OUT_DEFAULT_PRECIS = 0, + OUT_TT_PRECIS = 4, + OUT_TT_ONLY_PRECIS = 7, /* polygon fill mode */ ALTERNATE = 1, @@ -99,32 +100,32 @@ public const int // brush BS_SOLID = 0, HOLLOW_BRUSH = 5, - + // Binary raster operations. - R2_BLACK = 1, /* 0 */ - R2_NOTMERGEPEN = 2, /* DPon */ - R2_MASKNOTPEN = 3, /* DPna */ - R2_NOTCOPYPEN = 4, /* PN */ - R2_MASKPENNOT = 5, /* PDna */ - R2_NOT = 6, /* Dn */ - R2_XORPEN = 7, /* DPx */ - R2_NOTMASKPEN = 8, /* DPan */ - R2_MASKPEN = 9, /* DPa */ - R2_NOTXORPEN = 10, /* DPxn */ - R2_NOP = 11, /* D */ - R2_MERGENOTPEN = 12, /* DPno */ - R2_COPYPEN = 13, /* P */ - R2_MERGEPENNOT = 14, /* PDno */ - R2_MERGEPEN = 15, /* DPo */ - R2_WHITE = 16 /* 1 */; + R2_BLACK = 1, /* 0 */ + R2_NOTMERGEPEN = 2, /* DPon */ + R2_MASKNOTPEN = 3, /* DPna */ + R2_NOTCOPYPEN = 4, /* PN */ + R2_MASKPENNOT = 5, /* PDna */ + R2_NOT = 6, /* Dn */ + R2_XORPEN = 7, /* DPx */ + R2_NOTMASKPEN = 8, /* DPan */ + R2_MASKPEN = 9, /* DPa */ + R2_NOTXORPEN = 10, /* DPxn */ + R2_NOP = 11, /* D */ + R2_MERGENOTPEN = 12, /* DPno */ + R2_COPYPEN = 13, /* P */ + R2_MERGEPENNOT = 14, /* PDno */ + R2_MERGEPEN = 15, /* DPo */ + R2_WHITE = 16 /* 1 */; public const int /* SetGraphicsMode(hdc, iMode ) */ - GM_COMPATIBLE = 1, - GM_ADVANCED = 2, - MWT_IDENTITY = 1; + GM_COMPATIBLE = 1, + GM_ADVANCED = 2, + MWT_IDENTITY = 1; - public const int + public const int PAGE_READONLY = 0x02, PAGE_READWRITE = 0x04, PAGE_WRITECOPY = 0x08, @@ -132,30 +133,30 @@ public const int FILE_MAP_WRITE = 0x0002, FILE_MAP_READ = 0x0004; - public const int SHGFI_ICON = 0x000000100 , // get icon - SHGFI_DISPLAYNAME = 0x000000200, // get display name - SHGFI_TYPENAME = 0x000000400, // get type name - SHGFI_ATTRIBUTES = 0x000000800, // get attributes - SHGFI_ICONLOCATION = 0x000001000, // get icon location - SHGFI_EXETYPE = 0x000002000, // return exe type - SHGFI_SYSICONINDEX = 0x000004000, // get system icon index - SHGFI_LINKOVERLAY = 0x000008000, // put a link overlay on icon - SHGFI_SELECTED = 0x000010000, // show icon in selected state - SHGFI_ATTR_SPECIFIED = 0x000020000, // get only specified attributes - SHGFI_LARGEICON = 0x000000000, // get large icon - SHGFI_SMALLICON = 0x000000001, // get small icon - SHGFI_OPENICON = 0x000000002, // get open icon - SHGFI_SHELLICONSIZE = 0x000000004, // get shell size icon - SHGFI_PIDL = 0x000000008, // pszPath is a pidl + public const int SHGFI_ICON = 0x000000100, // get icon + SHGFI_DISPLAYNAME = 0x000000200, // get display name + SHGFI_TYPENAME = 0x000000400, // get type name + SHGFI_ATTRIBUTES = 0x000000800, // get attributes + SHGFI_ICONLOCATION = 0x000001000, // get icon location + SHGFI_EXETYPE = 0x000002000, // return exe type + SHGFI_SYSICONINDEX = 0x000004000, // get system icon index + SHGFI_LINKOVERLAY = 0x000008000, // put a link overlay on icon + SHGFI_SELECTED = 0x000010000, // show icon in selected state + SHGFI_ATTR_SPECIFIED = 0x000020000, // get only specified attributes + SHGFI_LARGEICON = 0x000000000, // get large icon + SHGFI_SMALLICON = 0x000000001, // get small icon + SHGFI_OPENICON = 0x000000002, // get open icon + SHGFI_SHELLICONSIZE = 0x000000004, // get shell size icon + SHGFI_PIDL = 0x000000008, // pszPath is a pidl SHGFI_USEFILEATTRIBUTES = 0x000000010, // use passed dwFileAttribute - SHGFI_ADDOVERLAYS = 0x000000020, // apply the appropriate overlays - SHGFI_OVERLAYINDEX = 0x000000040; // Get the index of the overlay + SHGFI_ADDOVERLAYS = 0x000000020, // apply the appropriate overlays + SHGFI_OVERLAYINDEX = 0x000000040; // Get the index of the overlay public const int DM_DISPLAYORIENTATION = 0x00000080; - + public const int AUTOSUGGEST = 0x10000000, AUTOSUGGEST_OFF = 0x20000000, - AUTOAPPEND = 0x40000000, + AUTOAPPEND = 0x40000000, AUTOAPPEND_OFF = (unchecked((int)0x80000000)); public const int ARW_BOTTOMLEFT = 0x0000, @@ -167,11 +168,11 @@ public const int ARW_UP = 0x0004, ARW_DOWN = 0x0004, ARW_HIDE = 0x0008, - ACM_OPENA = (0x0400+100), - ACM_OPENW = (0x0400+103), + ACM_OPENA = (0x0400 + 100), + ACM_OPENW = (0x0400 + 103), ADVF_NODATA = 1, ADVF_ONLYONCE = 4, - ADVF_PRIMEFIRST = 2; + ADVF_PRIMEFIRST = 2; // Note: ADVF_ONLYONCE and ADVF_PRIMEFIRST values now conform with objidl.dll but are backwards from // Platform SDK documentation as of 07/21/2003. // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/com/htm/oen_a2z_8jxi.asp. @@ -215,7 +216,7 @@ public const int BN_CLICKED = 0, BM_SETCHECK = 0x00F1, BM_SETSTATE = 0x00F3, - BM_CLICK = 0x00F5; + BM_CLICK = 0x00F5; public const int CDERR_DIALOGFAILURE = 0xFFFF, CDERR_STRUCTSIZE = 0x0001, @@ -276,8 +277,8 @@ public const int CF_ENHMETAFILE = 14, CF_HDROP = 15, CF_LOCALE = 16, - CLSCTX_INPROC_SERVER = 0x1, - CLSCTX_LOCAL_SERVER = 0x4, + CLSCTX_INPROC_SERVER = 0x1, + CLSCTX_LOCAL_SERVER = 0x4, CW_USEDEFAULT = (unchecked((int)0x80000000)), CWP_SKIPINVISIBLE = 0x0001, COLOR_WINDOW = 5, @@ -287,7 +288,7 @@ public const int CBN_EDITCHANGE = 5, CBN_EDITUPDATE = 6, CBN_DROPDOWN = 7, - CBN_CLOSEUP = 8, + CBN_CLOSEUP = 8, CBN_SELENDOK = 9, CBS_SIMPLE = 0x0001, CBS_DROPDOWN = 0x0002, @@ -327,8 +328,8 @@ public const int CDDS_POSTPAINT = 0x00000002, CDDS_ITEM = 0x00010000, CDDS_SUBITEM = 0x00020000, - CDDS_ITEMPREPAINT = (0x00010000|0x00000001), - CDDS_ITEMPOSTPAINT = (0x00010000|0x00000002), + CDDS_ITEMPREPAINT = (0x00010000 | 0x00000001), + CDDS_ITEMPOSTPAINT = (0x00010000 | 0x00000002), CDIS_SELECTED = 0x0001, CDIS_GRAYED = 0x0002, CDIS_DISABLED = 0x0004, @@ -341,19 +342,19 @@ public const int CDIS_SHOWKEYBOARDCUES = 0x0200, CLR_NONE = unchecked((int)0xFFFFFFFF), CLR_DEFAULT = unchecked((int)0xFF000000), - CCM_SETVERSION = (0x2000+0x7), - CCM_GETVERSION = (0x2000+0x8), + CCM_SETVERSION = (0x2000 + 0x7), + CCM_GETVERSION = (0x2000 + 0x8), CCS_NORESIZE = 0x00000004, CCS_NOPARENTALIGN = 0x00000008, CCS_NODIVIDER = 0x00000040, - CBEM_INSERTITEM = (0x0400+11), - CBEM_SETITEM = (0x0400+12), - CBEM_GETITEM = (0x0400+13), - CBEN_ENDEDIT = ((0-800)-6), + CBEM_INSERTITEM = (0x0400 + 11), + CBEM_SETITEM = (0x0400 + 12), + CBEM_GETITEM = (0x0400 + 13), + CBEN_ENDEDIT = ((0 - 800) - 6), CONNECT_E_NOCONNECTION = unchecked((int)0x80040200), CONNECT_E_CANNOTCONNECT = unchecked((int)0x80040202), - CTRLINFO_EATS_RETURN = 1, - CTRLINFO_EATS_ESCAPE = 2; + CTRLINFO_EATS_RETURN = 1, + CTRLINFO_EATS_ESCAPE = 2; public const int DUPLICATE = 0x06, DISPID_UNKNOWN = (-1), @@ -404,30 +405,30 @@ public const int DLGC_WANTTAB = 0x0002, DLGC_WANTALLKEYS = 0x0004, DLGC_WANTCHARS = 0x0080, - DLGC_WANTMESSAGE = 0x0004, /* Pass message to control */ - DLGC_HASSETSEL = 0x0008, /* Understands EM_SETSEL message */ - DTM_GETSYSTEMTIME = (0x1000+1), - DTM_SETSYSTEMTIME = (0x1000+2), - DTM_SETRANGE = (0x1000+4), - DTM_SETFORMAT = (0x1000+50), - DTM_SETMCCOLOR = (0x1000+6), - DTM_GETMONTHCAL = (0x1000+8), - DTM_SETMCFONT = (0x1000+9), + DLGC_WANTMESSAGE = 0x0004, /* Pass message to control */ + DLGC_HASSETSEL = 0x0008, /* Understands EM_SETSEL message */ + DTM_GETSYSTEMTIME = (0x1000 + 1), + DTM_SETSYSTEMTIME = (0x1000 + 2), + DTM_SETRANGE = (0x1000 + 4), + DTM_SETFORMAT = (0x1000 + 50), + DTM_SETMCCOLOR = (0x1000 + 6), + DTM_GETMONTHCAL = (0x1000 + 8), + DTM_SETMCFONT = (0x1000 + 9), DTS_UPDOWN = 0x0001, DTS_SHOWNONE = 0x0002, DTS_LONGDATEFORMAT = 0x0004, DTS_TIMEFORMAT = 0x0009, DTS_RIGHTALIGN = 0x0020, - DTN_DATETIMECHANGE = ((0-760)+1), - DTN_USERSTRING = ((0-760)+15), - DTN_WMKEYDOWN = ((0-760)+16), - DTN_FORMAT = ((0-760)+17), - DTN_FORMATQUERY = ((0-760)+18), - DTN_DROPDOWN = ((0-760)+6), - DTN_CLOSEUP = ((0-760)+7), - DVASPECT_CONTENT = 1, + DTN_DATETIMECHANGE = ((0 - 760) + 1), + DTN_USERSTRING = ((0 - 760) + 15), + DTN_WMKEYDOWN = ((0 - 760) + 16), + DTN_FORMAT = ((0 - 760) + 17), + DTN_FORMATQUERY = ((0 - 760) + 18), + DTN_DROPDOWN = ((0 - 760) + 6), + DTN_CLOSEUP = ((0 - 760) + 7), + DVASPECT_CONTENT = 1, DVASPECT_TRANSPARENT = 32, - DVASPECT_OPAQUE = 16; + DVASPECT_OPAQUE = 16; public const int E_NOTIMPL = unchecked((int)0x80004001), E_OUTOFMEMORY = unchecked((int)0x8007000E), @@ -441,10 +442,10 @@ public const int ETO_OPAQUE = 0x0002, ETO_CLIPPED = 0x0004, EMR_POLYTEXTOUT = 97, - EDGE_RAISED = (0x0001|0x0004), - EDGE_SUNKEN = (0x0002|0x0008), - EDGE_ETCHED = (0x0002|0x0004), - EDGE_BUMP = (0x0001|0x0008), + EDGE_RAISED = (0x0001 | 0x0004), + EDGE_SUNKEN = (0x0002 | 0x0008), + EDGE_ETCHED = (0x0002 | 0x0004), + EDGE_BUMP = (0x0001 | 0x0008), ES_LEFT = 0x0000, ES_CENTER = 0x0001, ES_RIGHT = 0x0002, @@ -516,32 +517,32 @@ public const int GDTR_MIN = 0x0001, GDTR_MAX = 0x0002, GDT_VALID = 0, - GDT_NONE = 1, + GDT_NONE = 1, GA_PARENT = 1, - GA_ROOT = 2; + GA_ROOT = 2; // ImmGetCompostionString index. public const int - GCS_COMPSTR = 0x0008, - GCS_COMPATTR = 0x0010, + GCS_COMPSTR = 0x0008, + GCS_COMPATTR = 0x0010, GCS_RESULTSTR = 0x0800, // attribute for COMPOSITIONSTRING Structure - ATTR_INPUT = 0x00, - ATTR_TARGET_CONVERTED = 0x01, - ATTR_CONVERTED = 0x02, + ATTR_INPUT = 0x00, + ATTR_TARGET_CONVERTED = 0x01, + ATTR_CONVERTED = 0x02, ATTR_TARGET_NOTCONVERTED = 0x03, - ATTR_INPUT_ERROR = 0x04, - ATTR_FIXEDCONVERTED = 0x05, + ATTR_INPUT_ERROR = 0x04, + ATTR_FIXEDCONVERTED = 0x05, // dwAction for ImmNotifyIME NI_COMPOSITIONSTR = 0x0015, // dwIndex for ImmNotifyIME/NI_COMPOSITIONSTR CPS_COMPLETE = 0x01, - CPS_CANCEL = 0x04; + CPS_CANCEL = 0x04; - public const int + public const int HC_ACTION = 0, HC_GETNEXT = 1, HC_SKIP = 2, @@ -557,37 +558,37 @@ public const int HCF_HIGHCONTRASTON = 0x00000001, HDI_ORDER = 0x0080, HDI_WIDTH = 0x0001, - HDM_GETITEMCOUNT = (0x1200+0), - HDM_INSERTITEMW = (0x1200+10), - HDM_GETITEMW = (0x1200+11), - HDM_LAYOUT = (0x1200+5), - HDM_SETITEMW = (0x1200+12), - HDN_ITEMCHANGING = ((0-300)-20), - HDN_ITEMCHANGED = ((0-300)-21), - HDN_ITEMCLICK = ((0-300)-22), - HDN_ITEMDBLCLICK = ((0-300)-23), - HDN_DIVIDERDBLCLICK = ((0-300)-25), - HDN_BEGINTDRAG = ((0-300)-10), - HDN_BEGINTRACK = ((0-300)-26), - HDN_ENDDRAG = ((0-300)-11), - HDN_ENDTRACK = ((0-300)-27), - HDN_TRACK = ((0-300)-28), - HDN_GETDISPINFO = ((0-300)-29); + HDM_GETITEMCOUNT = (0x1200 + 0), + HDM_INSERTITEMW = (0x1200 + 10), + HDM_GETITEMW = (0x1200 + 11), + HDM_LAYOUT = (0x1200 + 5), + HDM_SETITEMW = (0x1200 + 12), + HDN_ITEMCHANGING = ((0 - 300) - 20), + HDN_ITEMCHANGED = ((0 - 300) - 21), + HDN_ITEMCLICK = ((0 - 300) - 22), + HDN_ITEMDBLCLICK = ((0 - 300) - 23), + HDN_DIVIDERDBLCLICK = ((0 - 300) - 25), + HDN_BEGINTDRAG = ((0 - 300) - 10), + HDN_BEGINTRACK = ((0 - 300) - 26), + HDN_ENDDRAG = ((0 - 300) - 11), + HDN_ENDTRACK = ((0 - 300) - 27), + HDN_TRACK = ((0 - 300) - 28), + HDN_GETDISPINFO = ((0 - 300) - 29); // HOVER_DEFAULT = Do not use this value ever! It crashes entire servers. public const int HDS_FULLDRAG = 0x0080; // Corresponds to bitmaps in MENUITEMINFO - public const int HBMMENU_CALLBACK = -1, - HBMMENU_SYSTEM = 1, - HBMMENU_MBAR_RESTORE = 2, - HBMMENU_MBAR_MINIMIZE = 3, - HBMMENU_MBAR_CLOSE = 5, - HBMMENU_MBAR_CLOSE_D = 6, - HBMMENU_MBAR_MINIMIZE_D = 7, - HBMMENU_POPUP_CLOSE = 8, - HBMMENU_POPUP_RESTORE = 9, - HBMMENU_POPUP_MAXIMIZE = 10, + public const int HBMMENU_CALLBACK = -1, + HBMMENU_SYSTEM = 1, + HBMMENU_MBAR_RESTORE = 2, + HBMMENU_MBAR_MINIMIZE = 3, + HBMMENU_MBAR_CLOSE = 5, + HBMMENU_MBAR_CLOSE_D = 6, + HBMMENU_MBAR_MINIMIZE_D = 7, + HBMMENU_POPUP_CLOSE = 8, + HBMMENU_POPUP_RESTORE = 9, + HBMMENU_POPUP_MAXIMIZE = 10, HBMMENU_POPUP_MINIMIZE = 11; @@ -651,7 +652,7 @@ public const int ILS_SHADOW = 0x2, ILS_SATURATE = 0x4, ILS_ALPHA = 0x8; - + public const int IDM_PRINT = 27, IDM_PAGESETUP = 2004, IDM_PRINTPREVIEW = 2003, @@ -678,7 +679,7 @@ public const int public const int STG_E_LOCKVIOLATION = unchecked((int)0x80030021); public const int INPUT_KEYBOARD = 1; - + public const int KEYEVENTF_EXTENDEDKEY = 0x0001; public const int KEYEVENTF_KEYUP = 0x0002; public const int KEYEVENTF_UNICODE = 0x0004; @@ -755,22 +756,22 @@ public const int LVS_OWNERDATA = 0x1000, LVSCW_AUTOSIZE = -1, LVSCW_AUTOSIZE_USEHEADER = -2, - LVM_REDRAWITEMS = (0x1000+21), - LVM_SCROLL=(0x1000+20), - LVM_SETBKCOLOR = (0x1000+1), - LVM_SETBKIMAGE = (0x1000+138), - LVM_SETCALLBACKMASK = (0x1000+11), - LVM_GETCALLBACKMASK = (0x1000+10), - LVM_GETCOLUMNORDERARRAY = (0x1000+59), - LVM_GETITEMCOUNT = (0x1000+4), - LVM_SETCOLUMNORDERARRAY = (0x1000+58), - LVM_SETINFOTIP = (0x1000+173), + LVM_REDRAWITEMS = (0x1000 + 21), + LVM_SCROLL = (0x1000 + 20), + LVM_SETBKCOLOR = (0x1000 + 1), + LVM_SETBKIMAGE = (0x1000 + 138), + LVM_SETCALLBACKMASK = (0x1000 + 11), + LVM_GETCALLBACKMASK = (0x1000 + 10), + LVM_GETCOLUMNORDERARRAY = (0x1000 + 59), + LVM_GETITEMCOUNT = (0x1000 + 4), + LVM_SETCOLUMNORDERARRAY = (0x1000 + 58), + LVM_SETINFOTIP = (0x1000 + 173), LVSIL_NORMAL = 0, LVSIL_SMALL = 1, LVSIL_STATE = 2, - LVM_SETIMAGELIST = (0x1000+3), - LVM_SETSELECTIONMARK = (0x1000+67), - LVM_SETTOOLTIPS = (0x1000+74), + LVM_SETIMAGELIST = (0x1000 + 3), + LVM_SETSELECTIONMARK = (0x1000 + 67), + LVM_SETTOOLTIPS = (0x1000 + 74), LVIF_TEXT = 0x0001, LVIF_IMAGE = 0x0002, LVIF_INDENT = 0x0010, @@ -784,30 +785,30 @@ public const int LVIS_DROPHILITED = 0x0008, LVIS_OVERLAYMASK = 0x0F00, LVIS_STATEIMAGEMASK = 0xF000, - LVM_GETITEM = (0x1000+75), - LVM_SETITEM = (0x1000+76), + LVM_GETITEM = (0x1000 + 75), + LVM_SETITEM = (0x1000 + 76), LVM_SETITEMPOSITION32 = (0x01000 + 49), - LVM_INSERTITEM = (0x1000+77), - LVM_DELETEITEM = (0x1000+8), - LVM_DELETECOLUMN = (0x1000+28), - LVM_DELETEALLITEMS = (0x1000+9), - LVM_UPDATE = (0x1000+42), + LVM_INSERTITEM = (0x1000 + 77), + LVM_DELETEITEM = (0x1000 + 8), + LVM_DELETECOLUMN = (0x1000 + 28), + LVM_DELETEALLITEMS = (0x1000 + 9), + LVM_UPDATE = (0x1000 + 42), LVNI_FOCUSED = 0x0001, LVNI_SELECTED = 0x0002, - LVM_GETNEXTITEM = (0x1000+12), + LVM_GETNEXTITEM = (0x1000 + 12), LVFI_PARAM = 0x0001, LVFI_NEARESTXY = 0x0040, LVFI_PARTIAL = 0x0008, LVFI_STRING = 0x0002, - LVM_FINDITEM = (0x1000+83), + LVM_FINDITEM = (0x1000 + 83), LVIR_BOUNDS = 0, LVIR_ICON = 1, LVIR_LABEL = 2, LVIR_SELECTBOUNDS = 3, - LVM_GETITEMPOSITION = (0x1000+16), - LVM_GETITEMRECT = (0x1000+14), - LVM_GETSUBITEMRECT = (0x1000+56), - LVM_GETSTRINGWIDTH = (0x1000+87), + LVM_GETITEMPOSITION = (0x1000 + 16), + LVM_GETITEMRECT = (0x1000 + 14), + LVM_GETSUBITEMRECT = (0x1000 + 56), + LVM_GETSTRINGWIDTH = (0x1000 + 87), LVHT_NOWHERE = 0x0001, LVHT_ONITEMICON = 0x0002, LVHT_ONITEMLABEL = 0x0004, @@ -815,17 +816,17 @@ public const int LVHT_BELOW = 0x0010, LVHT_RIGHT = 0x0020, LVHT_LEFT = 0x0040, - LVHT_ONITEM = (0x0002|0x0004|0x0008), + LVHT_ONITEM = (0x0002 | 0x0004 | 0x0008), LVHT_ONITEMSTATEICON = 0x0008, LVM_SUBITEMHITTEST = (0x1000 + 57), - LVM_HITTEST = (0x1000+18), - LVM_ENSUREVISIBLE = (0x1000+19), + LVM_HITTEST = (0x1000 + 18), + LVM_ENSUREVISIBLE = (0x1000 + 19), LVA_DEFAULT = 0x0000, LVA_ALIGNLEFT = 0x0001, LVA_ALIGNTOP = 0x0002, LVA_SNAPTOGRID = 0x0005, - LVM_ARRANGE = (0x1000+22), - LVM_EDITLABEL = (0x1000+118), + LVM_ARRANGE = (0x1000 + 22), + LVM_EDITLABEL = (0x1000 + 118), LVCDI_ITEM = 0x0000, LVCDI_GROUP = 0x00000001, LVCF_FMT = 0x0001, @@ -835,48 +836,48 @@ public const int LVCF_IMAGE = 0x0010, LVCF_ORDER = 0x0020, LVCFMT_IMAGE = 0x0800, - LVGA_HEADER_LEFT = 0x00000001, - LVGA_HEADER_CENTER = 0x00000002, - LVGA_HEADER_RIGHT = 0x00000004, - LVGA_FOOTER_LEFT = 0x00000008, - LVGA_FOOTER_CENTER = 0x00000010, - LVGA_FOOTER_RIGHT = 0x00000020, - LVGF_NONE = 0x00000000, - LVGF_HEADER = 0x00000001, - LVGF_FOOTER = 0x00000002, - LVGF_STATE = 0x00000004, - LVGF_ALIGN = 0x00000008, - LVGF_GROUPID = 0x00000010, - LVGS_NORMAL = 0x00000000, - LVGS_COLLAPSED = 0x00000001, - LVGS_HIDDEN = 0x00000002, + LVGA_HEADER_LEFT = 0x00000001, + LVGA_HEADER_CENTER = 0x00000002, + LVGA_HEADER_RIGHT = 0x00000004, + LVGA_FOOTER_LEFT = 0x00000008, + LVGA_FOOTER_CENTER = 0x00000010, + LVGA_FOOTER_RIGHT = 0x00000020, + LVGF_NONE = 0x00000000, + LVGF_HEADER = 0x00000001, + LVGF_FOOTER = 0x00000002, + LVGF_STATE = 0x00000004, + LVGF_ALIGN = 0x00000008, + LVGF_GROUPID = 0x00000010, + LVGS_NORMAL = 0x00000000, + LVGS_COLLAPSED = 0x00000001, + LVGS_HIDDEN = 0x00000002, LVIM_AFTER = 0x00000001, LVTVIF_FIXEDSIZE = 0x00000003, LVTVIM_TILESIZE = 0x00000001, LVTVIM_COLUMNS = 0x00000002, LVM_ENABLEGROUPVIEW = (0x1000 + 157), LVM_MOVEITEMTOGROUP = (0x1000 + 154), - LVM_GETCOLUMN = (0x1000+95), - LVM_SETCOLUMN = (0x1000+96), - LVM_INSERTCOLUMN = (0x1000+97), + LVM_GETCOLUMN = (0x1000 + 95), + LVM_SETCOLUMN = (0x1000 + 96), + LVM_INSERTCOLUMN = (0x1000 + 97), LVM_INSERTGROUP = (0x1000 + 145), LVM_REMOVEGROUP = (0x1000 + 150), LVM_INSERTMARKHITTEST = (0x1000 + 168), LVM_REMOVEALLGROUPS = (0x1000 + 160), - LVM_GETCOLUMNWIDTH = (0x1000+29), - LVM_SETCOLUMNWIDTH = (0x1000+30), + LVM_GETCOLUMNWIDTH = (0x1000 + 29), + LVM_SETCOLUMNWIDTH = (0x1000 + 30), LVM_SETINSERTMARK = (0x1000 + 166), - LVM_GETHEADER = (0x1000+31), - LVM_SETTEXTCOLOR = (0x1000+36), - LVM_SETTEXTBKCOLOR = (0x1000+38), - LVM_GETTOPINDEX = (0x1000+39), - LVM_SETITEMPOSITION = (0x1000+15), - LVM_SETITEMSTATE = (0x1000+43), - LVM_GETITEMSTATE = (0x1000+44), - LVM_GETITEMTEXT = (0x1000+115), - LVM_GETHOTITEM = (0x1000+61), - LVM_SETITEMTEXT = (0x1000+116), - LVM_SETITEMCOUNT = (0x1000+47), + LVM_GETHEADER = (0x1000 + 31), + LVM_SETTEXTCOLOR = (0x1000 + 36), + LVM_SETTEXTBKCOLOR = (0x1000 + 38), + LVM_GETTOPINDEX = (0x1000 + 39), + LVM_SETITEMPOSITION = (0x1000 + 15), + LVM_SETITEMSTATE = (0x1000 + 43), + LVM_GETITEMSTATE = (0x1000 + 44), + LVM_GETITEMTEXT = (0x1000 + 115), + LVM_GETHOTITEM = (0x1000 + 61), + LVM_SETITEMTEXT = (0x1000 + 116), + LVM_SETITEMCOUNT = (0x1000 + 47), LVM_SORTITEMS = (0x1000 + 48), LVM_GETSELECTEDCOUNT = (0x1000 + 50), LVM_GETISEARCHSTRING = (0x1000 + 117), @@ -902,29 +903,29 @@ public const int LVS_EX_INFOTIP = 0x00000400, LVS_EX_UNDERLINEHOT = 0x00000800, LVS_EX_DOUBLEBUFFER = 0x00010000, - LVN_ITEMCHANGING = ((0-100)-0), - LVN_ITEMCHANGED = ((0-100)-1), - LVN_BEGINLABELEDIT = ((0-100)-75), - LVN_ENDLABELEDIT = ((0-100)-76), - LVN_COLUMNCLICK = ((0-100)-8), - LVN_BEGINDRAG = ((0-100)-9), - LVN_BEGINRDRAG = ((0-100)-11), - LVN_ODFINDITEM = ((0-100)-79), - LVN_ITEMACTIVATE = ((0-100)-14), - LVN_GETDISPINFO = ((0-100)-77), - LVN_ODCACHEHINT = ((0-100) - 13), - LVN_ODSTATECHANGED = ((0-100) - 15), - LVN_SETDISPINFO = ((0-100)-78), - LVN_GETINFOTIP = ((0-100)- 58), - LVN_KEYDOWN = ((0-100)-55), - - LWA_COLORKEY = 0x00000001, - LWA_ALPHA = 0x00000002; + LVN_ITEMCHANGING = ((0 - 100) - 0), + LVN_ITEMCHANGED = ((0 - 100) - 1), + LVN_BEGINLABELEDIT = ((0 - 100) - 75), + LVN_ENDLABELEDIT = ((0 - 100) - 76), + LVN_COLUMNCLICK = ((0 - 100) - 8), + LVN_BEGINDRAG = ((0 - 100) - 9), + LVN_BEGINRDRAG = ((0 - 100) - 11), + LVN_ODFINDITEM = ((0 - 100) - 79), + LVN_ITEMACTIVATE = ((0 - 100) - 14), + LVN_GETDISPINFO = ((0 - 100) - 77), + LVN_ODCACHEHINT = ((0 - 100) - 13), + LVN_ODSTATECHANGED = ((0 - 100) - 15), + LVN_SETDISPINFO = ((0 - 100) - 78), + LVN_GETINFOTIP = ((0 - 100) - 58), + LVN_KEYDOWN = ((0 - 100) - 55), + + LWA_COLORKEY = 0x00000001, + LWA_ALPHA = 0x00000002; public const int LANG_NEUTRAL = 0x00, LOCALE_IFIRSTDAYOFWEEK = 0x0000100C; /* first day of week specifier */ - public const int LOCALE_IMEASURE = 0x0000000D; // 0 = metric, 1 = US + public const int LOCALE_IMEASURE = 0x0000000D; // 0 = metric, 1 = US public const int TVM_SETEXTENDEDSTYLE = TV_FIRST + 44; public const int TVM_GETEXTENDEDSTYLE = TV_FIRST + 45; @@ -933,23 +934,26 @@ public const int public const int TVS_EX_DOUBLEBUFFER = 0x0004; public static readonly int LOCALE_USER_DEFAULT = MAKELCID(LANG_USER_DEFAULT); - public static readonly int LANG_USER_DEFAULT = MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT); + public static readonly int LANG_USER_DEFAULT = MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT); - public static int MAKELANGID(int primary, int sub) { + public static int MAKELANGID(int primary, int sub) + { return ((((ushort)(sub)) << 10) | (ushort)(primary)); } - + /// /// Creates an LCID from a LangId /// - public static int MAKELCID(int lgid) { + public static int MAKELCID(int lgid) + { return MAKELCID(lgid, SORT_DEFAULT); } /// /// Creates an LCID from a LangId /// - public static int MAKELCID(int lgid, int sort) { + public static int MAKELCID(int lgid, int sort) + { return ((0xFFFF & lgid) | (((0x000f) & sort) << 16)); } @@ -985,7 +989,7 @@ public static int MAKELCID(int lgid, int sort) { MF_POPUP = 0x00000010, MF_SYSMENU = 0x00002000, MFS_DISABLED = 0x00000003, - MFT_MENUBREAK = 0x00000040, + MFT_MENUBREAK = 0x00000040, MFT_SEPARATOR = 0x00000800, MFT_RIGHTORDER = 0x00002000, MFT_RIGHTJUSTIFY = 0x00004000, @@ -993,47 +997,47 @@ public static int MAKELCID(int lgid, int sort) { MDITILE_VERTICAL = 0x0000, MDITILE_HORIZONTAL = 0x0001, MDITILE_SKIPDISABLED = 0x0002, - MCM_SETMAXSELCOUNT = (0x1000+4), - MCM_SETSELRANGE = (0x1000+6), - MCM_GETMONTHRANGE = (0x1000+7), - MCM_GETMINREQRECT = (0x1000+9), - MCM_SETCOLOR = (0x1000+10), - MCM_SETTODAY = (0x1000+12), - MCM_GETTODAY = (0x1000+13), - MCM_HITTEST = (0x1000+14), - MCM_SETFIRSTDAYOFWEEK = (0x1000+15), - MCM_SETRANGE = (0x1000+18), - MCM_SETMONTHDELTA = (0x1000+20), - MCM_GETMAXTODAYWIDTH = (0x1000+21), + MCM_SETMAXSELCOUNT = (0x1000 + 4), + MCM_SETSELRANGE = (0x1000 + 6), + MCM_GETMONTHRANGE = (0x1000 + 7), + MCM_GETMINREQRECT = (0x1000 + 9), + MCM_SETCOLOR = (0x1000 + 10), + MCM_SETTODAY = (0x1000 + 12), + MCM_GETTODAY = (0x1000 + 13), + MCM_HITTEST = (0x1000 + 14), + MCM_SETFIRSTDAYOFWEEK = (0x1000 + 15), + MCM_SETRANGE = (0x1000 + 18), + MCM_SETMONTHDELTA = (0x1000 + 20), + MCM_GETMAXTODAYWIDTH = (0x1000 + 21), MCHT_TITLE = 0x00010000, MCHT_CALENDAR = 0x00020000, MCHT_TODAYLINK = 0x00030000, MCHT_TITLEBK = (0x00010000), - MCHT_TITLEMONTH = (0x00010000|0x0001), - MCHT_TITLEYEAR = (0x00010000|0x0002), - MCHT_TITLEBTNNEXT = (0x00010000|0x01000000|0x0003), - MCHT_TITLEBTNPREV = (0x00010000|0x02000000|0x0003), + MCHT_TITLEMONTH = (0x00010000 | 0x0001), + MCHT_TITLEYEAR = (0x00010000 | 0x0002), + MCHT_TITLEBTNNEXT = (0x00010000 | 0x01000000 | 0x0003), + MCHT_TITLEBTNPREV = (0x00010000 | 0x02000000 | 0x0003), MCHT_CALENDARBK = (0x00020000), - MCHT_CALENDARDATE = (0x00020000|0x0001), - MCHT_CALENDARDATENEXT = ((0x00020000|0x0001)|0x01000000), - MCHT_CALENDARDATEPREV = ((0x00020000|0x0001)|0x02000000), - MCHT_CALENDARDAY = (0x00020000|0x0002), - MCHT_CALENDARWEEKNUM = (0x00020000|0x0003), + MCHT_CALENDARDATE = (0x00020000 | 0x0001), + MCHT_CALENDARDATENEXT = ((0x00020000 | 0x0001) | 0x01000000), + MCHT_CALENDARDATEPREV = ((0x00020000 | 0x0001) | 0x02000000), + MCHT_CALENDARDAY = (0x00020000 | 0x0002), + MCHT_CALENDARWEEKNUM = (0x00020000 | 0x0003), MCSC_TEXT = 1, MCSC_TITLEBK = 2, MCSC_TITLETEXT = 3, MCSC_MONTHBK = 4, MCSC_TRAILINGTEXT = 5, MCN_VIEWCHANGE = (0 - 750), // MCN_SELECT -4 - give state of calendar view - MCN_SELCHANGE = ((0-750)+1), - MCN_GETDAYSTATE = ((0-750)+3), - MCN_SELECT = ((0-750)+4), + MCN_SELCHANGE = ((0 - 750) + 1), + MCN_GETDAYSTATE = ((0 - 750) + 3), + MCN_SELECT = ((0 - 750) + 4), MCS_DAYSTATE = 0x0001, MCS_MULTISELECT = 0x0002, MCS_WEEKNUMBERS = 0x0004, MCS_NOTODAYCIRCLE = 0x0008, MCS_NOTODAY = 0x0010, - MSAA_MENU_SIG = (unchecked((int) 0xAA0DF00D)); + MSAA_MENU_SIG = (unchecked((int)0xAA0DF00D)); public const int NIM_ADD = 0x00000000, NIM_MODIFY = 0x00000001, @@ -1053,12 +1057,12 @@ public static int MAKELCID(int lgid, int sort) { NIN_BALLOONUSERCLICK = (Interop.WindowMessages.WM_USER + 5), NFR_ANSI = 1, NFR_UNICODE = 2, - NM_CLICK = ((0-0)-2), - NM_DBLCLK = ((0-0)-3), - NM_RCLICK = ((0-0)-5), - NM_RDBLCLK = ((0-0)-6), - NM_CUSTOMDRAW = ((0-0)-12), - NM_RELEASEDCAPTURE = ((0-0)-16), + NM_CLICK = ((0 - 0) - 2), + NM_DBLCLK = ((0 - 0) - 3), + NM_RCLICK = ((0 - 0) - 5), + NM_RDBLCLK = ((0 - 0) - 6), + NM_CUSTOMDRAW = ((0 - 0) - 12), + NM_RELEASEDCAPTURE = ((0 - 0) - 16), NONANTIALIASED_QUALITY = 3; public const int OFN_READONLY = 0x00000001, @@ -1081,7 +1085,7 @@ public static int MAKELCID(int lgid, int sort) { OLEIVERB_HIDE = -3, OLEIVERB_UIACTIVATE = -4, OLEIVERB_INPLACEACTIVATE = -5, - OLEIVERB_DISCARDUNDOSTATE= -6, + OLEIVERB_DISCARDUNDOSTATE = -6, OLEIVERB_PROPERTIES = -7, OLE_E_INVALIDRECT = unchecked((int)0x8004000D), OLE_E_NOCONNECTION = unchecked((int)0x80040004), @@ -1109,10 +1113,10 @@ public static int MAKELCID(int lgid, int sort) { ODS_DISABLED = 0x0004, ODS_FOCUS = 0x0010, ODS_GRAYED = 0x0002, - ODS_HOTLIGHT = 0x0040, - ODS_INACTIVE = 0x0080, - ODS_NOACCEL = 0x0100, - ODS_NOFOCUSRECT = 0x0200, + ODS_HOTLIGHT = 0x0040, + ODS_INACTIVE = 0x0080, + ODS_NOACCEL = 0x0100, + ODS_NOFOCUSRECT = 0x0200, ODS_SELECTED = 0x0001, OLECLOSE_SAVEIFDIRTY = 0, OLECLOSE_PROMPTSAVE = 2; @@ -1178,17 +1182,17 @@ public static int MAKELCID(int lgid, int sort) { PM_NOREMOVE = 0x0000, PM_REMOVE = 0x0001, PM_NOYIELD = 0x0002, - PBM_SETRANGE = (0x0400+1), - PBM_SETPOS = (0x0400+2), - PBM_SETSTEP = (0x0400+4), - PBM_SETRANGE32 = (0x0400+6), - PBM_SETBARCOLOR = (0x0400+9), - PBM_SETMARQUEE = (0x0400+10), - PBM_SETBKCOLOR = (0x2000 +1), - PSM_SETTITLEA = (0x0400+111), - PSM_SETTITLEW = (0x0400+120), - PSM_SETFINISHTEXTA = (0x0400+115), - PSM_SETFINISHTEXTW = (0x0400+121), + PBM_SETRANGE = (0x0400 + 1), + PBM_SETPOS = (0x0400 + 2), + PBM_SETSTEP = (0x0400 + 4), + PBM_SETRANGE32 = (0x0400 + 6), + PBM_SETBARCOLOR = (0x0400 + 9), + PBM_SETMARQUEE = (0x0400 + 10), + PBM_SETBKCOLOR = (0x2000 + 1), + PSM_SETTITLEA = (0x0400 + 111), + PSM_SETTITLEW = (0x0400 + 120), + PSM_SETFINISHTEXTA = (0x0400 + 115), + PSM_SETFINISHTEXTW = (0x0400 + 121), PATCOPY = 0x00F00021, PATINVERT = 0x005A0049; @@ -1209,28 +1213,28 @@ public static int MAKELCID(int lgid, int sort) { QS_ALLEVENTS = QS_INPUT | QS_POSTMESSAGE | QS_TIMER | QS_PAINT | QS_HOTKEY, QS_ALLINPUT = QS_INPUT | QS_POSTMESSAGE | QS_TIMER | QS_PAINT | QS_HOTKEY | QS_SENDMESSAGE; - public const int MWMO_INPUTAVAILABLE = 0x0004; // don't use MWMO_WAITALL, see ddb#176342 - - //public const int RECO_PASTE = 0x00000000; // paste from clipboard - public const int RECO_DROP = 0x00000001; // drop - //public const int RECO_COPY = 0x00000002; // copy to the clipboard - //public const int RECO_CUT = 0x00000003; // cut to the clipboard - //public const int RECO_DRAG = 0x00000004; // drag - - public const int RPC_E_CHANGED_MODE = unchecked((int)0x80010106), - RPC_E_CANTCALLOUT_ININPUTSYNCCALL = unchecked((int)0x8001010D), - RGN_AND = 1, - RGN_XOR = 3, - RGN_DIFF = 4, - RDW_INVALIDATE = 0x0001, - RDW_ERASE = 0x0004, - RDW_ALLCHILDREN = 0x0080, - RDW_ERASENOW = 0x0200, - RDW_UPDATENOW = 0x0100, - RDW_FRAME = 0x0400, - RB_INSERTBANDA = (0x0400+1), - RB_INSERTBANDW = (0x0400+10); - + public const int MWMO_INPUTAVAILABLE = 0x0004; // don't use MWMO_WAITALL, see ddb#176342 + + //public const int RECO_PASTE = 0x00000000; // paste from clipboard + public const int RECO_DROP = 0x00000001; // drop + //public const int RECO_COPY = 0x00000002; // copy to the clipboard + //public const int RECO_CUT = 0x00000003; // cut to the clipboard + //public const int RECO_DRAG = 0x00000004; // drag + + public const int RPC_E_CHANGED_MODE = unchecked((int)0x80010106), + RPC_E_CANTCALLOUT_ININPUTSYNCCALL = unchecked((int)0x8001010D), + RGN_AND = 1, + RGN_XOR = 3, + RGN_DIFF = 4, + RDW_INVALIDATE = 0x0001, + RDW_ERASE = 0x0004, + RDW_ALLCHILDREN = 0x0080, + RDW_ERASENOW = 0x0200, + RDW_UPDATENOW = 0x0100, + RDW_FRAME = 0x0400, + RB_INSERTBANDA = (0x0400 + 1), + RB_INSERTBANDW = (0x0400 + 10); + public const int stc4 = 0x0443, SHGFP_TYPE_CURRENT = 0, STGM_READ = 0x00000000, @@ -1238,9 +1242,9 @@ public static int MAKELCID(int lgid, int sort) { STGM_READWRITE = 0x00000002, STGM_SHARE_EXCLUSIVE = 0x00000010, STGM_CREATE = 0x00001000, - STGM_TRANSACTED = 0x00010000, - STGM_CONVERT = 0x00020000, - STGM_DELETEONRELEASE = 0x04000000, + STGM_TRANSACTED = 0x00010000, + STGM_CONVERT = 0x00020000, + STGM_DELETEONRELEASE = 0x04000000, STARTF_USESHOWWINDOW = 0x00000001, SB_HORZ = 0, SB_VERT = 1, @@ -1263,8 +1267,8 @@ public static int MAKELCID(int lgid, int sort) { SIZE_RESTORED = 0, SIZE_MAXIMIZED = 2, ESB_ENABLE_BOTH = 0x0000, - ESB_DISABLE_BOTH =0x0003, - SORT_DEFAULT =0x0, + ESB_DISABLE_BOTH = 0x0003, + SORT_DEFAULT = 0x0, SUBLANG_DEFAULT = 0x01, SW_HIDE = 0, SW_NORMAL = 1, @@ -1368,14 +1372,14 @@ public static int MAKELCID(int lgid, int sort) { public const int SW_SCROLLCHILDREN = 0x0001, SW_INVALIDATE = 0x0002, SW_ERASE = 0x0004, - SW_SMOOTHSCROLL = 0x0010, + SW_SMOOTHSCROLL = 0x0010, SC_SIZE = 0xF000, SC_MINIMIZE = 0xF020, SC_MAXIMIZE = 0xF030, SC_CLOSE = 0xF060, SC_KEYMENU = 0xF100, SC_RESTORE = 0xF120, - SC_MOVE = 0xF010, + SC_MOVE = 0xF010, SC_CONTEXTHELP = 0xF180, SS_LEFT = 0x00000000, SS_CENTER = 0x00000001, @@ -1389,45 +1393,45 @@ public static int MAKELCID(int lgid, int sort) { SIF_PAGE = 0x0002, SIF_POS = 0x0004, SIF_TRACKPOS = 0x0010, - SIF_ALL = (0x0001|0x0002|0x0004|0x0010), + SIF_ALL = (0x0001 | 0x0002 | 0x0004 | 0x0010), SPI_GETFONTSMOOTHING = 0x004A, SPI_GETDROPSHADOW = 0x1024, - SPI_GETFLATMENU = 0x1022, + SPI_GETFLATMENU = 0x1022, SPI_GETFONTSMOOTHINGTYPE = 0x200A, SPI_GETFONTSMOOTHINGCONTRAST = 0x200C, - SPI_ICONHORIZONTALSPACING = 0x000D, - SPI_ICONVERTICALSPACING = 0x0018, + SPI_ICONHORIZONTALSPACING = 0x000D, + SPI_ICONVERTICALSPACING = 0x0018, // SPI_GETICONMETRICS = 0x002D, - SPI_GETICONTITLEWRAP = 0x0019, - SPI_GETICONTITLELOGFONT = 0x001F, - SPI_GETKEYBOARDCUES = 0x100A, - SPI_GETKEYBOARDDELAY = 0x0016, - SPI_GETKEYBOARDPREF = 0x0044, - SPI_GETKEYBOARDSPEED = 0x000A, - SPI_GETMOUSEHOVERWIDTH = 0x0062, - SPI_GETMOUSEHOVERHEIGHT = 0x0064, - SPI_GETMOUSEHOVERTIME = 0x0066, - SPI_GETMOUSESPEED = 0x0070, - SPI_GETMENUDROPALIGNMENT = 0x001B, - SPI_GETMENUFADE = 0x1012, - SPI_GETMENUSHOWDELAY = 0x006A, - SPI_GETCOMBOBOXANIMATION = 0x1004, - SPI_GETGRADIENTCAPTIONS = 0x1008, - SPI_GETHOTTRACKING = 0x100E, - SPI_GETLISTBOXSMOOTHSCROLLING = 0x1006, - SPI_GETMENUANIMATION = 0x1002, - SPI_GETSELECTIONFADE = 0x1014, - SPI_GETTOOLTIPANIMATION = 0x1016, - SPI_GETUIEFFECTS = 0x103E, - SPI_GETACTIVEWINDOWTRACKING = 0x1000, - SPI_GETACTIVEWNDTRKTIMEOUT = 0x2002, - SPI_GETANIMATION = 0x0048, - SPI_GETBORDER = 0x0005, - SPI_GETCARETWIDTH = 0x2006, - SM_CYFOCUSBORDER = 84, - SM_CXFOCUSBORDER = 83, - SM_CYSIZEFRAME = SM_CYFRAME, - SM_CXSIZEFRAME = SM_CXFRAME, + SPI_GETICONTITLEWRAP = 0x0019, + SPI_GETICONTITLELOGFONT = 0x001F, + SPI_GETKEYBOARDCUES = 0x100A, + SPI_GETKEYBOARDDELAY = 0x0016, + SPI_GETKEYBOARDPREF = 0x0044, + SPI_GETKEYBOARDSPEED = 0x000A, + SPI_GETMOUSEHOVERWIDTH = 0x0062, + SPI_GETMOUSEHOVERHEIGHT = 0x0064, + SPI_GETMOUSEHOVERTIME = 0x0066, + SPI_GETMOUSESPEED = 0x0070, + SPI_GETMENUDROPALIGNMENT = 0x001B, + SPI_GETMENUFADE = 0x1012, + SPI_GETMENUSHOWDELAY = 0x006A, + SPI_GETCOMBOBOXANIMATION = 0x1004, + SPI_GETGRADIENTCAPTIONS = 0x1008, + SPI_GETHOTTRACKING = 0x100E, + SPI_GETLISTBOXSMOOTHSCROLLING = 0x1006, + SPI_GETMENUANIMATION = 0x1002, + SPI_GETSELECTIONFADE = 0x1014, + SPI_GETTOOLTIPANIMATION = 0x1016, + SPI_GETUIEFFECTS = 0x103E, + SPI_GETACTIVEWINDOWTRACKING = 0x1000, + SPI_GETACTIVEWNDTRKTIMEOUT = 0x2002, + SPI_GETANIMATION = 0x0048, + SPI_GETBORDER = 0x0005, + SPI_GETCARETWIDTH = 0x2006, + SM_CYFOCUSBORDER = 84, + SM_CXFOCUSBORDER = 83, + SM_CYSIZEFRAME = SM_CYFRAME, + SM_CXSIZEFRAME = SM_CXFRAME, SPI_GETDRAGFULLWINDOWS = 38, SPI_GETNONCLIENTMETRICS = 41, SPI_GETWORKAREA = 48, @@ -1436,23 +1440,23 @@ public static int MAKELCID(int lgid, int sort) { SPI_GETSNAPTODEFBUTTON = 95, SPI_GETWHEELSCROLLLINES = 104, SBARS_SIZEGRIP = 0x0100, - SB_SETTEXT = (0x0400+11), - SB_GETTEXT = (0x0400+13), - SB_GETTEXTLENGTH = (0x0400+12), - SB_SETPARTS = (0x0400+4), - SB_SIMPLE = (0x0400+9), - SB_GETRECT = (0x0400+10), - SB_SETICON = (0x0400+15), - SB_SETTIPTEXT = (0x0400+17), - SB_GETTIPTEXT = (0x0400+19), + SB_SETTEXT = (0x0400 + 11), + SB_GETTEXT = (0x0400 + 13), + SB_GETTEXTLENGTH = (0x0400 + 12), + SB_SETPARTS = (0x0400 + 4), + SB_SIMPLE = (0x0400 + 9), + SB_GETRECT = (0x0400 + 10), + SB_SETICON = (0x0400 + 15), + SB_SETTIPTEXT = (0x0400 + 17), + SB_GETTIPTEXT = (0x0400 + 19), SBT_OWNERDRAW = 0x1000, SBT_NOBORDERS = 0x0100, SBT_POPOUT = 0x0200, SBT_RTLREADING = 0x0400, SRCCOPY = 0x00CC0020, - SRCAND = 0x008800C6, /* dest = source AND dest */ - SRCPAINT = 0x00EE0086, /* dest = source OR dest */ - NOTSRCCOPY = 0x00330008, /* dest = (NOT source) */ + SRCAND = 0x008800C6, /* dest = source AND dest */ + SRCPAINT = 0x00EE0086, /* dest = source OR dest */ + NOTSRCCOPY = 0x00330008, /* dest = (NOT source) */ STATFLAG_DEFAULT = 0x0, STATFLAG_NONAME = 0x1, STATFLAG_NOOPEN = 0x2, @@ -1464,15 +1468,17 @@ public static int MAKELCID(int lgid, int sort) { STREAM_SEEK_CUR = 0x1, STREAM_SEEK_END = 0x2; - public const int S_OK = 0x00000000; - public const int S_FALSE = 0x00000001; + public const int S_OK = 0x00000000; + public const int S_FALSE = 0x00000001; - public static bool Succeeded(int hr) { - return(hr >= 0); + public static bool Succeeded(int hr) + { + return (hr >= 0); } - public static bool Failed(int hr) { - return(hr < 0); + public static bool Failed(int hr) + { + return (hr < 0); } public const int TRANSPARENT = 1, @@ -1647,7 +1653,7 @@ public static bool Failed(int hr) { TVGN_FIRSTVISIBLE = 0x0005, TVGN_NEXTVISIBLE = 0x0006, TVGN_PREVIOUSVISIBLE = 0x0007, - TVGN_DROPHILITE= 0x0008, + TVGN_DROPHILITE = 0x0008, TVGN_CARET = 0x0009, TVM_SELECTITEM = (0x1100 + 11), TVM_GETITEM = (0x1100 + 62), @@ -1718,18 +1724,18 @@ public static bool Failed(int hr) { TVM_SORTCHILDRENCB = (TV_FIRST + 21), TMPF_FIXED_PITCH = 0x01; - public const int TVHT_NOWHERE = 0x0001, - TVHT_ONITEMICON = 0x0002, - TVHT_ONITEMLABEL = 0x0004, - TVHT_ONITEM = (TVHT_ONITEMICON | TVHT_ONITEMLABEL | TVHT_ONITEMSTATEICON), - TVHT_ONITEMINDENT = 0x0008, - TVHT_ONITEMBUTTON = 0x0010, - TVHT_ONITEMRIGHT = 0x0020, - TVHT_ONITEMSTATEICON = 0x0040, - TVHT_ABOVE = 0x0100, - TVHT_BELOW = 0x0200, - TVHT_TORIGHT = 0x0400, - TVHT_TOLEFT = 0x0800; + public const int TVHT_NOWHERE = 0x0001, + TVHT_ONITEMICON = 0x0002, + TVHT_ONITEMLABEL = 0x0004, + TVHT_ONITEM = (TVHT_ONITEMICON | TVHT_ONITEMLABEL | TVHT_ONITEMSTATEICON), + TVHT_ONITEMINDENT = 0x0008, + TVHT_ONITEMBUTTON = 0x0010, + TVHT_ONITEMRIGHT = 0x0020, + TVHT_ONITEMSTATEICON = 0x0040, + TVHT_ABOVE = 0x0100, + TVHT_BELOW = 0x0200, + TVHT_TORIGHT = 0x0400, + TVHT_TOLEFT = 0x0800; public const int UIS_SET = 1, UIS_CLEAR = 2, @@ -1753,7 +1759,7 @@ public static bool Failed(int hr) { VK_CONTROL = 0x11, VK_MENU = 0x12, VK_CAPITAL = 0x14, - VK_KANA = 0x15, + VK_KANA = 0x15, VK_ESCAPE = 0x1B, VK_END = 0x23, VK_HOME = 0x24, @@ -1802,7 +1808,7 @@ public static bool Failed(int hr) { public const int WS_EX_CONTROLPARENT = 0x00010000; public const int WS_EX_STATICEDGE = 0x00020000; public const int WS_EX_APPWINDOW = 0x00040000; - public const int WS_EX_LAYERED = 0x00080000; + public const int WS_EX_LAYERED = 0x00080000; public const int WS_EX_TOPMOST = 0x00000008; public const int WS_EX_LAYOUTRTL = 0x00400000; public const int WS_EX_NOINHERITLAYOUT = 0x00100000; @@ -1813,13 +1819,13 @@ public static bool Failed(int hr) { // wParam of report message WM_IME_NOTIFY (public\sdk\imm.h) public const int //IMN_CLOSESTATUSWINDOW = 0x0001, - IMN_OPENSTATUSWINDOW = 0x0002, + IMN_OPENSTATUSWINDOW = 0x0002, //IMN_CHANGECANDIDATE = 0x0003, //IMN_CLOSECANDIDATE = 0x0004, //IMN_OPENCANDIDATE = 0x0005, IMN_SETCONVERSIONMODE = 0x0006, //IMN_SETSENTENCEMODE = 0x0007, - IMN_SETOPENSTATUS = 0x0008; + IMN_SETOPENSTATUS = 0x0008; //IMN_SETCANDIDATEPOS = 0x0009, //IMN_SETCOMPOSITIONFONT = 0x000A, //IMN_SETCOMPOSITIONWINDOW = 0x000B, @@ -1828,35 +1834,41 @@ public const int //IMN_PRIVATE = 0x000E; - public static int START_PAGE_GENERAL = unchecked((int)0xffffffff); + public static int START_PAGE_GENERAL = unchecked((int)0xffffffff); // Result action ids for PrintDlgEx. - public const int PD_RESULT_CANCEL = 0; - public const int PD_RESULT_PRINT = 1; - public const int PD_RESULT_APPLY = 2; + public const int PD_RESULT_CANCEL = 0; + public const int PD_RESULT_PRINT = 1; + public const int PD_RESULT_APPLY = 2; private static int wmMouseEnterMessage = -1; - public static int WM_MOUSEENTER { - get { - if (wmMouseEnterMessage == -1) { - wmMouseEnterMessage = SafeNativeMethods.RegisterWindowMessage("WinFormsMouseEnter"); - } - return wmMouseEnterMessage; - } + public static int WM_MOUSEENTER + { + get + { + if (wmMouseEnterMessage == -1) + { + wmMouseEnterMessage = SafeNativeMethods.RegisterWindowMessage("WinFormsMouseEnter"); + } + return wmMouseEnterMessage; + } } private static int wmUnSubclass = -1; - public static int WM_UIUNSUBCLASS { - get { - if (wmUnSubclass == -1) { + public static int WM_UIUNSUBCLASS + { + get + { + if (wmUnSubclass == -1) + { wmUnSubclass = SafeNativeMethods.RegisterWindowMessage("WinFormsUnSubclass"); } return wmUnSubclass; } } - public const int XBUTTON1 = 0x0001; - public const int XBUTTON2 = 0x0002; + public const int XBUTTON1 = 0x0001; + public const int XBUTTON2 = 0x0002; public const string TOOLTIPS_CLASS = "tooltips_class32"; @@ -1877,13 +1889,13 @@ public static int WM_UIUNSUBCLASS { public const int CHILDID_SELF = 0; public const int OBJID_QUERYCLASSNAMEIDX = unchecked(unchecked((int)0xFFFFFFF4)); - public const int OBJID_CLIENT = unchecked(unchecked((int)0xFFFFFFFC)); - public const int OBJID_WINDOW = unchecked(unchecked((int)0x00000000)); + public const int OBJID_CLIENT = unchecked(unchecked((int)0xFFFFFFFC)); + public const int OBJID_WINDOW = unchecked(unchecked((int)0x00000000)); - public const int UiaRootObjectId = -25; - public const int UiaAppendRuntimeId = 3; + public const int UiaRootObjectId = -25; + public const int UiaAppendRuntimeId = 3; - public const string uuid_IAccessible = "{618736E0-3C3D-11CF-810C-00AA00389B71}"; + public const string uuid_IAccessible = "{618736E0-3C3D-11CF-810C-00AA00389B71}"; public const string uuid_IEnumVariant = "{00020404-0000-0000-C000-000000000046}"; /* @@ -1891,28 +1903,29 @@ public static int WM_UIUNSUBCLASS { */ [StructLayout(LayoutKind.Sequential)] - public class OLECMD { + public class OLECMD + { [MarshalAs(UnmanagedType.U4)] - public int cmdID = 0; + public int cmdID = 0; [MarshalAs(UnmanagedType.U4)] - public int cmdf = 0; + public int cmdf = 0; } [ComVisible(true)] [ComImport] [Guid("B722BCCB-4E68-101B-A2BC-00AA00404770")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - public interface IOleCommandTarget + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + public interface IOleCommandTarget { [return: MarshalAs(UnmanagedType.I4)] [PreserveSig] int QueryStatus( ref Guid pguidCmdGroup, int cCmds, - [In, Out] + [In, Out] OLECMD prgCmds, - [In, Out] + [In, Out] IntPtr pCmdText); [return: MarshalAs(UnmanagedType.I4)] @@ -1927,29 +1940,32 @@ int Exec( int pvaOut); } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] - public class FONTDESC { - public int cbSizeOfStruct = Marshal.SizeOf(); - public string lpstrName; - public long cySize; - public short sWeight; - public short sCharset; - public bool fItalic; - public bool fUnderline; - public bool fStrikethrough; + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public class FONTDESC + { + public int cbSizeOfStruct = Marshal.SizeOf(); + public string lpstrName; + public long cySize; + public short sWeight; + public short sCharset; + public bool fItalic; + public bool fUnderline; + public bool fStrikethrough; } /// /// [StructLayout(LayoutKind.Sequential)] - public class PICTDESCbmp { + public class PICTDESCbmp + { internal int cbSizeOfStruct = Marshal.SizeOf(); internal int picType = Ole.PICTYPE_BITMAP; internal IntPtr hbitmap = IntPtr.Zero; internal IntPtr hpalette = IntPtr.Zero; internal int unused = 0; - public PICTDESCbmp(System.Drawing.Bitmap bitmap) { + public PICTDESCbmp(System.Drawing.Bitmap bitmap) + { hbitmap = bitmap.GetHbitmap(); // gpr: What about palettes? } @@ -1958,14 +1974,16 @@ public PICTDESCbmp(System.Drawing.Bitmap bitmap) { /// /// [StructLayout(LayoutKind.Sequential)] - public class PICTDESCicon { + public class PICTDESCicon + { internal int cbSizeOfStruct = Marshal.SizeOf(); internal int picType = Ole.PICTYPE_ICON; internal IntPtr hicon = IntPtr.Zero; internal int unused1 = 0; internal int unused2 = 0; - public PICTDESCicon(System.Drawing.Icon icon) { + public PICTDESCicon(System.Drawing.Icon icon) + { hicon = SafeNativeMethods.CopyImage(new HandleRef(icon, icon.Handle), NativeMethods.IMAGE_ICON, icon.Size.Width, icon.Size.Height, 0); } } @@ -1973,27 +1991,31 @@ public PICTDESCicon(System.Drawing.Icon icon) { /// /// [StructLayout(LayoutKind.Sequential)] - public class PICTDESCemf { + public class PICTDESCemf + { internal int cbSizeOfStruct = Marshal.SizeOf(); internal int picType = Ole.PICTYPE_ENHMETAFILE; internal IntPtr hemf = IntPtr.Zero; internal int unused1 = 0; internal int unused2 = 0; - public PICTDESCemf(System.Drawing.Imaging.Metafile metafile) { + public PICTDESCemf(System.Drawing.Imaging.Metafile metafile) + { //gpr hemf = metafile.CopyHandle(); } } [StructLayout(LayoutKind.Sequential)] - public class USEROBJECTFLAGS { + public class USEROBJECTFLAGS + { public int fInherit = 0; public int fReserved = 0; public int dwFlags = 0; } - [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)] - internal class SYSTEMTIMEARRAY { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + internal class SYSTEMTIMEARRAY + { public short wYear1; public short wMonth1; public short wDayOfWeek1; @@ -2014,78 +2036,85 @@ internal class SYSTEMTIMEARRAY { public delegate bool EnumChildrenCallback(IntPtr hwnd, IntPtr lParam); - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public class HH_AKLINK { - internal int cbStruct=Marshal.SizeOf(); - internal bool fReserved = false; - internal string pszKeywords = null; - internal string pszUrl = null; - internal string pszMsgText = null; - internal string pszMsgTitle = null; - internal string pszWindow = null; - internal bool fIndexOnFail = false; - } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public class HH_POPUP { - internal int cbStruct=Marshal.SizeOf(); - internal IntPtr hinst = IntPtr.Zero; - internal int idString = 0; - internal IntPtr pszText; - internal POINT pt; - internal int clrForeground = -1; - internal int clrBackground = -1; - internal RECT rcMargins = RECT.FromXYWH(-1, -1, -1, -1); // amount of space between edges of window and text, -1 for each member to ignore - internal string pszFont = null; + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class HH_AKLINK + { + internal int cbStruct = Marshal.SizeOf(); + internal bool fReserved = false; + internal string pszKeywords = null; + internal string pszUrl = null; + internal string pszMsgText = null; + internal string pszMsgTitle = null; + internal string pszWindow = null; + internal bool fIndexOnFail = false; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class HH_POPUP + { + internal int cbStruct = Marshal.SizeOf(); + internal IntPtr hinst = IntPtr.Zero; + internal int idString = 0; + internal IntPtr pszText; + internal POINT pt; + internal int clrForeground = -1; + internal int clrBackground = -1; + internal RECT rcMargins = RECT.FromXYWH(-1, -1, -1, -1); // amount of space between edges of window and text, -1 for each member to ignore + internal string pszFont = null; } [SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate")] public const int HH_FTS_DEFAULT_PROXIMITY = -1; - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public class HH_FTS_QUERY { - internal int cbStruct = Marshal.SizeOf(); - internal bool fUniCodeStrings = false; + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class HH_FTS_QUERY + { + internal int cbStruct = Marshal.SizeOf(); + internal bool fUniCodeStrings = false; [MarshalAs(UnmanagedType.LPStr)] - internal string pszSearchQuery = null; - internal int iProximity = NativeMethods.HH_FTS_DEFAULT_PROXIMITY; - internal bool fStemmedSearch = false; - internal bool fTitleOnly = false; - internal bool fExecute = true; + internal string pszSearchQuery = null; + internal int iProximity = NativeMethods.HH_FTS_DEFAULT_PROXIMITY; + internal bool fStemmedSearch = false; + internal bool fTitleOnly = false; + internal bool fExecute = true; [MarshalAs(UnmanagedType.LPStr)] - internal string pszWindow = null; + internal string pszWindow = null; } - [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto, Pack=4)] - public class MONITORINFOEX { - internal int cbSize = Marshal.SizeOf(); - internal RECT rcMonitor = new RECT(); - internal RECT rcWork = new RECT(); - internal int dwFlags = 0; - [MarshalAs(UnmanagedType.ByValArray, SizeConst=32)] - internal char[] szDevice = new char[32]; + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)] + public class MONITORINFOEX + { + internal int cbSize = Marshal.SizeOf(); + internal RECT rcMonitor = new RECT(); + internal RECT rcWork = new RECT(); + internal int dwFlags = 0; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] + internal char[] szDevice = new char[32]; } - [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto, Pack=4)] - public class MONITORINFO { - internal int cbSize = Marshal.SizeOf(); - internal RECT rcMonitor = new RECT(); - internal RECT rcWork = new RECT(); - internal int dwFlags = 0; + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)] + public class MONITORINFO + { + internal int cbSize = Marshal.SizeOf(); + internal RECT rcMonitor = new RECT(); + internal RECT rcWork = new RECT(); + internal int dwFlags = 0; } public delegate int EditStreamCallback(IntPtr dwCookie, IntPtr buf, int cb, out int transferred); [StructLayout(LayoutKind.Sequential)] - public class EDITSTREAM { - public IntPtr dwCookie = IntPtr.Zero; - public int dwError = 0; - public EditStreamCallback pfnCallback = null; + public class EDITSTREAM + { + public IntPtr dwCookie = IntPtr.Zero; + public int dwError = 0; + public EditStreamCallback pfnCallback = null; } [StructLayout(LayoutKind.Sequential)] - public class EDITSTREAM64 { - [MarshalAs(UnmanagedType.ByValArray, SizeConst=20)] + public class EDITSTREAM64 + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)] public byte[] contents = new byte[20]; } @@ -2140,14 +2169,14 @@ public interface IVsPerPropertyBrowsing /// are otherwise browsable. /// [PreserveSig] - int HideProperty(int dispid,ref bool pfHide); + int HideProperty(int dispid, ref bool pfHide); /// /// Will have the "+" expandable glyph next to them and can be expanded or collapsed by the user /// Returning a non-S_OK return code or false for pfDisplay will suppress this feature /// [PreserveSig] - int DisplayChildProperties(int dispid, + int DisplayChildProperties(int dispid, ref bool pfDisplay); /// @@ -2155,9 +2184,9 @@ int DisplayChildProperties(int dispid, /// returning a non-S_OK return code will display the default values /// [PreserveSig] - int GetLocalizedPropertyInfo(int dispid, int localeID, + int GetLocalizedPropertyInfo(int dispid, int localeID, [Out, MarshalAs(UnmanagedType.LPArray)] - string[] pbstrLocalizedName, + string[] pbstrLocalizedName, [Out, MarshalAs(UnmanagedType.LPArray)] string[] pbstrLocalizeDescription); @@ -2173,7 +2202,7 @@ int HasDefaultValue(int dispid, /// Determines if a property should be made read only. This only applies to properties that are writeable, /// [PreserveSig] - int IsPropertyReadOnly(int dispid, + int IsPropertyReadOnly(int dispid, ref bool fReadOnly); /// @@ -2205,8 +2234,8 @@ int IsPropertyReadOnly(int dispid, public interface IManagedPerPropertyBrowsing { [PreserveSig] - int GetPropertyAttributes(int dispid, - ref int pcAttributes, + int GetPropertyAttributes(int dispid, + ref int pcAttributes, ref IntPtr pbstrAttrNames, ref IntPtr pvariantInitValues); } @@ -2233,7 +2262,7 @@ int ExecuteBuilder( string bstrGuidBldr, [In, MarshalAs(UnmanagedType.Interface)] object pdispApp, - + HandleRef hwndBldrOwner, [Out, In, MarshalAs(UnmanagedType.Struct)] ref object pvarValue, @@ -2242,68 +2271,76 @@ int ExecuteBuilder( } [StructLayout(LayoutKind.Sequential)] - public class INITCOMMONCONTROLSEX { - public int dwSize = 8; //ndirect.DllLib.sizeOf(this); - public int dwICC; + public class INITCOMMONCONTROLSEX + { + public int dwSize = 8; //ndirect.DllLib.sizeOf(this); + public int dwICC; } [StructLayout(LayoutKind.Sequential)] - public class IMAGELISTDRAWPARAMS { - public int cbSize = Marshal.SizeOf(); - public IntPtr himl = IntPtr.Zero; - public int i = 0; - public IntPtr hdcDst = IntPtr.Zero; - public int x = 0; - public int y = 0; - public int cx = 0; - public int cy = 0; - public int xBitmap = 0; - public int yBitmap = 0; - public int rgbBk = 0; - public int rgbFg = 0; - public int fStyle = 0; - public int dwRop = 0; - public int fState = 0; - public int Frame = 0; - public int crEffect = 0; + public class IMAGELISTDRAWPARAMS + { + public int cbSize = Marshal.SizeOf(); + public IntPtr himl = IntPtr.Zero; + public int i = 0; + public IntPtr hdcDst = IntPtr.Zero; + public int x = 0; + public int y = 0; + public int cx = 0; + public int cy = 0; + public int xBitmap = 0; + public int yBitmap = 0; + public int rgbBk = 0; + public int rgbFg = 0; + public int fStyle = 0; + public int dwRop = 0; + public int fState = 0; + public int Frame = 0; + public int crEffect = 0; } [StructLayout(LayoutKind.Sequential)] - public class IMAGEINFO { - public IntPtr hbmImage = IntPtr.Zero; - public IntPtr hbmMask = IntPtr.Zero; - public int Unused1 = 0; - public int Unused2 = 0; + public class IMAGEINFO + { + public IntPtr hbmImage = IntPtr.Zero; + public IntPtr hbmMask = IntPtr.Zero; + public int Unused1 = 0; + public int Unused2 = 0; // rcImage was a by-value RECT structure - public int rcImage_left = 0; - public int rcImage_top = 0; - public int rcImage_right = 0; - public int rcImage_bottom = 0; + public int rcImage_left = 0; + public int rcImage_top = 0; + public int rcImage_right = 0; + public int rcImage_bottom = 0; } [StructLayout(LayoutKind.Sequential)] - public class TRACKMOUSEEVENT { - public int cbSize = Marshal.SizeOf(); - public int dwFlags; - public IntPtr hwndTrack; - public int dwHoverTime = 100; // Never set this to field ZERO, or to HOVER_DEFAULT, ever! + public class TRACKMOUSEEVENT + { + public int cbSize = Marshal.SizeOf(); + public int dwFlags; + public IntPtr hwndTrack; + public int dwHoverTime = 100; // Never set this to field ZERO, or to HOVER_DEFAULT, ever! } [StructLayout(LayoutKind.Sequential)] - public class POINT { + public class POINT + { public int x; public int y; - public POINT() { + public POINT() + { } - - public POINT(int x, int y) { + + public POINT(int x, int y) + { this.x = x; this.y = y; } #if DEBUG - public override string ToString() { + public override string ToString() + { return "{x=" + x + ", y=" + y + "}"; } #endif @@ -2312,51 +2349,60 @@ public override string ToString() { // use this in cases where the Native API takes a POINT not a POINT* // classes marshal by ref. [StructLayout(LayoutKind.Sequential)] - public struct POINTSTRUCT { + public struct POINTSTRUCT + { public int x; public int y; - public POINTSTRUCT(int x, int y) { - this.x = x; - this.y = y; + public POINTSTRUCT(int x, int y) + { + this.x = x; + this.y = y; } } public delegate IntPtr WndProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); [StructLayout(LayoutKind.Sequential)] - public struct RECT { + public struct RECT + { public int left; public int top; public int right; public int bottom; - public RECT(int left, int top, int right, int bottom) { + public RECT(int left, int top, int right, int bottom) + { this.left = left; this.top = top; this.right = right; this.bottom = bottom; } - public RECT(System.Drawing.Rectangle r) { + public RECT(System.Drawing.Rectangle r) + { this.left = r.Left; this.top = r.Top; this.right = r.Right; this.bottom = r.Bottom; } - public static RECT FromXYWH(int x, int y, int width, int height) { + public static RECT FromXYWH(int x, int y, int width, int height) + { return new RECT(x, y, x + width, y + height); } - public System.Drawing.Size Size { - get { + public System.Drawing.Size Size + { + get + { return new System.Drawing.Size(this.right - this.left, this.bottom - this.top); } } } [StructLayout(LayoutKind.Sequential)] - public struct MARGINS { + public struct MARGINS + { public int cxLeftWidth; public int cxRightWidth; public int cyTopHeight; @@ -2367,80 +2413,85 @@ public struct MARGINS { public delegate int TreeViewCompareCallback(IntPtr lParam1, IntPtr lParam2, IntPtr lParamSort); - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public class WNDCLASS_I { - public int style = 0; - public IntPtr lpfnWndProc = IntPtr.Zero; - public int cbClsExtra = 0; - public int cbWndExtra = 0; - public IntPtr hInstance = IntPtr.Zero; - public IntPtr hIcon = IntPtr.Zero; - public IntPtr hCursor = IntPtr.Zero; - public IntPtr hbrBackground = IntPtr.Zero; - public IntPtr lpszMenuName = IntPtr.Zero; - public IntPtr lpszClassName = IntPtr.Zero; + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class WNDCLASS_I + { + public int style = 0; + public IntPtr lpfnWndProc = IntPtr.Zero; + public int cbClsExtra = 0; + public int cbWndExtra = 0; + public IntPtr hInstance = IntPtr.Zero; + public IntPtr hIcon = IntPtr.Zero; + public IntPtr hCursor = IntPtr.Zero; + public IntPtr hbrBackground = IntPtr.Zero; + public IntPtr lpszMenuName = IntPtr.Zero; + public IntPtr lpszClassName = IntPtr.Zero; } [StructLayout(LayoutKind.Sequential)] - public class NONCLIENTMETRICS { - public int cbSize = Marshal.SizeOf(); - public int iBorderWidth = 0; - public int iScrollWidth = 0; - public int iScrollHeight = 0; - public int iCaptionWidth = 0; - public int iCaptionHeight = 0; + public class NONCLIENTMETRICS + { + public int cbSize = Marshal.SizeOf(); + public int iBorderWidth = 0; + public int iScrollWidth = 0; + public int iScrollHeight = 0; + public int iCaptionWidth = 0; + public int iCaptionHeight = 0; [MarshalAs(UnmanagedType.Struct)] - public LOGFONT lfCaptionFont = null; - public int iSmCaptionWidth = 0; - public int iSmCaptionHeight = 0; + public LOGFONT lfCaptionFont = null; + public int iSmCaptionWidth = 0; + public int iSmCaptionHeight = 0; [MarshalAs(UnmanagedType.Struct)] - public LOGFONT lfSmCaptionFont = null; - public int iMenuWidth = 0; - public int iMenuHeight = 0; + public LOGFONT lfSmCaptionFont = null; + public int iMenuWidth = 0; + public int iMenuHeight = 0; [MarshalAs(UnmanagedType.Struct)] - public LOGFONT lfMenuFont = null; + public LOGFONT lfMenuFont = null; [MarshalAs(UnmanagedType.Struct)] - public LOGFONT lfStatusFont = null; + public LOGFONT lfStatusFont = null; [MarshalAs(UnmanagedType.Struct)] - public LOGFONT lfMessageFont = null; + public LOGFONT lfMessageFont = null; } [StructLayout(LayoutKind.Sequential)] [Serializable] - public struct MSG { - public IntPtr hwnd; - public int message; - public IntPtr wParam; - public IntPtr lParam; - public int time; + public struct MSG + { + public IntPtr hwnd; + public int message; + public IntPtr wParam; + public IntPtr lParam; + public int time; // pt was a by-value POINT structure - public int pt_x; - public int pt_y; + public int pt_x; + public int pt_y; } - + [StructLayout(LayoutKind.Sequential)] - public struct PAINTSTRUCT { - public IntPtr hdc; - public bool fErase; + public struct PAINTSTRUCT + { + public IntPtr hdc; + public bool fErase; // rcPaint was a by-value RECT structure - public int rcPaint_left; - public int rcPaint_top; - public int rcPaint_right; - public int rcPaint_bottom; - public bool fRestore; - public bool fIncUpdate; - public int reserved1; - public int reserved2; - public int reserved3; - public int reserved4; - public int reserved5; - public int reserved6; - public int reserved7; - public int reserved8; + public int rcPaint_left; + public int rcPaint_top; + public int rcPaint_right; + public int rcPaint_bottom; + public bool fRestore; + public bool fIncUpdate; + public int reserved1; + public int reserved2; + public int reserved3; + public int reserved4; + public int reserved5; + public int reserved6; + public int reserved7; + public int reserved8; } - + [StructLayout(LayoutKind.Sequential)] - public class SCROLLINFO { + public class SCROLLINFO + { public int cbSize = Marshal.SizeOf(); public int fMask; public int nMin; @@ -2449,104 +2500,112 @@ public class SCROLLINFO { public int nPos; public int nTrackPos; - public SCROLLINFO() { + public SCROLLINFO() + { } } [StructLayout(LayoutKind.Sequential)] - public class TPMPARAMS { - public int cbSize = Marshal.SizeOf(); + public class TPMPARAMS + { + public int cbSize = Marshal.SizeOf(); // rcExclude was a by-value RECT structure - public int rcExclude_left; - public int rcExclude_top; - public int rcExclude_right; - public int rcExclude_bottom; + public int rcExclude_left; + public int rcExclude_top; + public int rcExclude_right; + public int rcExclude_bottom; } [StructLayout(LayoutKind.Sequential)] - public class SIZE { + public class SIZE + { public int cx; public int cy; - - public SIZE() { + + public SIZE() + { } - public SIZE(int cx, int cy) { + public SIZE(int cx, int cy) + { this.cx = cx; this.cy = cy; } } - + [StructLayout(LayoutKind.Sequential)] - public struct WINDOWPLACEMENT { - public int length; - public int flags; - public int showCmd; + public struct WINDOWPLACEMENT + { + public int length; + public int flags; + public int showCmd; // ptMinPosition was a by-value POINT structure - public int ptMinPosition_x; - public int ptMinPosition_y; + public int ptMinPosition_x; + public int ptMinPosition_y; // ptMaxPosition was a by-value POINT structure - public int ptMaxPosition_x; - public int ptMaxPosition_y; + public int ptMaxPosition_x; + public int ptMaxPosition_y; // rcNormalPosition was a by-value RECT structure - public int rcNormalPosition_left; - public int rcNormalPosition_top; - public int rcNormalPosition_right; - public int rcNormalPosition_bottom; - } - - [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)] - public class STARTUPINFO_I { - public int cb = 0; - public IntPtr lpReserved = IntPtr.Zero; - public IntPtr lpDesktop = IntPtr.Zero; - public IntPtr lpTitle = IntPtr.Zero; - public int dwX = 0; - public int dwY = 0; - public int dwXSize = 0; - public int dwYSize = 0; - public int dwXCountChars = 0; - public int dwYCountChars = 0; - public int dwFillAttribute = 0; - public int dwFlags = 0; - public short wShowWindow = 0; - public short cbReserved2 = 0; - public IntPtr lpReserved2 = IntPtr.Zero; - public IntPtr hStdInput = IntPtr.Zero; - public IntPtr hStdOutput = IntPtr.Zero; - public IntPtr hStdError = IntPtr.Zero; + public int rcNormalPosition_left; + public int rcNormalPosition_top; + public int rcNormalPosition_right; + public int rcNormalPosition_bottom; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class STARTUPINFO_I + { + public int cb = 0; + public IntPtr lpReserved = IntPtr.Zero; + public IntPtr lpDesktop = IntPtr.Zero; + public IntPtr lpTitle = IntPtr.Zero; + public int dwX = 0; + public int dwY = 0; + public int dwXSize = 0; + public int dwYSize = 0; + public int dwXCountChars = 0; + public int dwYCountChars = 0; + public int dwFillAttribute = 0; + public int dwFlags = 0; + public short wShowWindow = 0; + public short cbReserved2 = 0; + public IntPtr lpReserved2 = IntPtr.Zero; + public IntPtr hStdInput = IntPtr.Zero; + public IntPtr hStdOutput = IntPtr.Zero; + public IntPtr hStdError = IntPtr.Zero; } [StructLayout(LayoutKind.Sequential)] - public class PAGESETUPDLG { - public int lStructSize; - public IntPtr hwndOwner; - public IntPtr hDevMode; - public IntPtr hDevNames; - public int Flags; + public class PAGESETUPDLG + { + public int lStructSize; + public IntPtr hwndOwner; + public IntPtr hDevMode; + public IntPtr hDevNames; + public int Flags; //POINT ptPaperSize; - public int paperSizeX = 0; - public int paperSizeY = 0; + public int paperSizeX = 0; + public int paperSizeY = 0; // RECT rtMinMargin; - public int minMarginLeft; - public int minMarginTop; - public int minMarginRight; - public int minMarginBottom; + public int minMarginLeft; + public int minMarginTop; + public int minMarginRight; + public int minMarginBottom; // RECT rtMargin; - public int marginLeft; - public int marginTop; - public int marginRight; - public int marginBottom; + public int marginLeft; + public int marginTop; + public int marginRight; + public int marginBottom; - public IntPtr hInstance = IntPtr.Zero; - public IntPtr lCustData = IntPtr.Zero; - public WndProc lpfnPageSetupHook = null; - public WndProc lpfnPagePaintHook = null; - public string lpPageSetupTemplateName = null; - public IntPtr hPageSetupTemplate = IntPtr.Zero; + public IntPtr hInstance = IntPtr.Zero; + public IntPtr lCustData = IntPtr.Zero; + public WndProc lpfnPageSetupHook = null; + public WndProc lpfnPagePaintHook = null; + public string lpPageSetupTemplateName = null; + public IntPtr hPageSetupTemplate = IntPtr.Zero; } // Any change in PRINTDLG, should also be in PRINTDLG_32 and PRINTDLG_64 @@ -2582,8 +2641,9 @@ public interface PRINTDLG // Any change in PRINTDLG_32, should also be in PRINTDLG and PRINTDLG_64 // x86 requires EXPLICIT packing of 1. - [StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Auto)] - public class PRINTDLG_32 : PRINTDLG { + [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Auto)] + public class PRINTDLG_32 : PRINTDLG + { int m_lStructSize; IntPtr m_hwndOwner; @@ -2642,7 +2702,8 @@ public class PRINTDLG_32 : PRINTDLG { // Any change in PRINTDLG_64, should also be in PRINTDLG_32 and PRINTDLG // x64 does not require EXPLICIT packing of 1. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] - public class PRINTDLG_64 : PRINTDLG { + public class PRINTDLG_64 : PRINTDLG + { int m_lStructSize; IntPtr m_hwndOwner; @@ -2699,46 +2760,48 @@ public class PRINTDLG_64 : PRINTDLG { } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] - public class PRINTDLGEX { - public int lStructSize; + public class PRINTDLGEX + { + public int lStructSize; - public IntPtr hwndOwner; - public IntPtr hDevMode; - public IntPtr hDevNames; - public IntPtr hDC; + public IntPtr hwndOwner; + public IntPtr hDevMode; + public IntPtr hDevNames; + public IntPtr hDC; - public int Flags; - public int Flags2; + public int Flags; + public int Flags2; - public int ExclusionFlags; + public int ExclusionFlags; - public int nPageRanges; - public int nMaxPageRanges; + public int nPageRanges; + public int nMaxPageRanges; - public IntPtr pageRanges; + public IntPtr pageRanges; - public int nMinPage; - public int nMaxPage; - public int nCopies; + public int nMinPage; + public int nMaxPage; + public int nCopies; - public IntPtr hInstance; + public IntPtr hInstance; [MarshalAs(UnmanagedType.LPStr)] - public string lpPrintTemplateName; + public string lpPrintTemplateName; - public WndProc lpCallback = null; + public WndProc lpCallback = null; - public int nPropertyPages; + public int nPropertyPages; - public IntPtr lphPropertyPages; + public IntPtr lphPropertyPages; + + public int nStartPage; + public int dwResultAction; - public int nStartPage; - public int dwResultAction; - } // x86 requires EXPLICIT packing of 1. - [StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Auto)] - public class PRINTPAGERANGE { + [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Auto)] + public class PRINTPAGERANGE + { public int nFromPage = 0; public int nToPage = 0; } @@ -2752,7 +2815,8 @@ public class PICTDESC internal int union2; internal int union3; - public static PICTDESC CreateBitmapPICTDESC(IntPtr hbitmap, IntPtr hpal) { + public static PICTDESC CreateBitmapPICTDESC(IntPtr hbitmap, IntPtr hpal) + { PICTDESC pictdesc = new PICTDESC(); pictdesc.cbSizeOfStruct = 16; pictdesc.picType = Ole.PICTYPE_BITMAP; @@ -2762,7 +2826,8 @@ public static PICTDESC CreateBitmapPICTDESC(IntPtr hbitmap, IntPtr hpal) { return pictdesc; } - public static PICTDESC CreateIconPICTDESC(IntPtr hicon) { + public static PICTDESC CreateIconPICTDESC(IntPtr hicon) + { PICTDESC pictdesc = new PICTDESC(); pictdesc.cbSizeOfStruct = 12; pictdesc.picType = Ole.PICTYPE_ICON; @@ -2772,51 +2837,54 @@ public static PICTDESC CreateIconPICTDESC(IntPtr hicon) { } [StructLayout(LayoutKind.Sequential)] - public sealed class tagFONTDESC { - public int cbSizeofstruct = Marshal.SizeOf(); - - [MarshalAs(UnmanagedType.LPWStr)] - public string lpstrName; - - [MarshalAs(UnmanagedType.U8)] - public long cySize; - - [MarshalAs(UnmanagedType.U2)] - public short sWeight; - - [MarshalAs(UnmanagedType.U2)] - public short sCharset; - - [MarshalAs(UnmanagedType.Bool)] - public bool fItalic; - - [MarshalAs(UnmanagedType.Bool)] - public bool fUnderline; - - [MarshalAs(UnmanagedType.Bool)] - public bool fStrikethrough; - } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public class CHOOSECOLOR { - public int lStructSize = Marshal.SizeOf(); //ndirect.DllLib.sizeOf(this); - public IntPtr hwndOwner; - public IntPtr hInstance; - public int rgbResult; - public IntPtr lpCustColors; - public int Flags; - public IntPtr lCustData = IntPtr.Zero; - public WndProc lpfnHook; - public string lpTemplateName = null; + public sealed class tagFONTDESC + { + public int cbSizeofstruct = Marshal.SizeOf(); + + [MarshalAs(UnmanagedType.LPWStr)] + public string lpstrName; + + [MarshalAs(UnmanagedType.U8)] + public long cySize; + + [MarshalAs(UnmanagedType.U2)] + public short sWeight; + + [MarshalAs(UnmanagedType.U2)] + public short sCharset; + + [MarshalAs(UnmanagedType.Bool)] + public bool fItalic; + + [MarshalAs(UnmanagedType.Bool)] + public bool fUnderline; + + [MarshalAs(UnmanagedType.Bool)] + public bool fStrikethrough; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class CHOOSECOLOR + { + public int lStructSize = Marshal.SizeOf(); //ndirect.DllLib.sizeOf(this); + public IntPtr hwndOwner; + public IntPtr hInstance; + public int rgbResult; + public IntPtr lpCustColors; + public int Flags; + public IntPtr lCustData = IntPtr.Zero; + public WndProc lpfnHook; + public string lpTemplateName = null; } public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam); [StructLayout(LayoutKind.Sequential)] // This is not our convention for managed resources. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable")] - public class BITMAP { + public class BITMAP + { public int bmType = 0; public int bmWidth = 0; public int bmHeight = 0; @@ -2828,52 +2896,57 @@ public class BITMAP { } [StructLayout(LayoutKind.Sequential)] - public class ICONINFO { - public int fIcon = 0; - public int xHotspot = 0; - public int yHotspot = 0; - public IntPtr hbmMask = IntPtr.Zero; - public IntPtr hbmColor = IntPtr.Zero; + public class ICONINFO + { + public int fIcon = 0; + public int xHotspot = 0; + public int yHotspot = 0; + public IntPtr hbmMask = IntPtr.Zero; + public IntPtr hbmColor = IntPtr.Zero; } [StructLayout(LayoutKind.Sequential)] - public class LOGPEN { - public int lopnStyle = 0; + public class LOGPEN + { + public int lopnStyle = 0; // lopnWidth was a by-value POINT structure - public int lopnWidth_x = 0; - public int lopnWidth_y = 0; - public int lopnColor = 0; + public int lopnWidth_x = 0; + public int lopnWidth_y = 0; + public int lopnColor = 0; } [StructLayout(LayoutKind.Sequential)] - public class LOGBRUSH { - public int lbStyle; - public int lbColor; - public IntPtr lbHatch; + public class LOGBRUSH + { + public int lbStyle; + public int lbColor; + public IntPtr lbHatch; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public class LOGFONT { - public LOGFONT() { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class LOGFONT + { + public LOGFONT() + { } - public LOGFONT( LOGFONT lf ) + public LOGFONT(LOGFONT lf) { - Debug.Assert( lf != null, "lf is null" ); - - this.lfHeight = lf.lfHeight; - this.lfWidth = lf.lfWidth; - this.lfEscapement = lf.lfEscapement; - this.lfOrientation = lf.lfOrientation; - this.lfWeight = lf.lfWeight; - this.lfItalic = lf.lfItalic; - this.lfUnderline = lf.lfUnderline; - this.lfStrikeOut = lf.lfStrikeOut; - this.lfCharSet = lf.lfCharSet; - this.lfOutPrecision = lf.lfOutPrecision; - this.lfClipPrecision = lf.lfClipPrecision; - this.lfQuality = lf.lfQuality; - this.lfPitchAndFamily = lf.lfPitchAndFamily; - this.lfFaceName = lf.lfFaceName; + Debug.Assert(lf != null, "lf is null"); + + this.lfHeight = lf.lfHeight; + this.lfWidth = lf.lfWidth; + this.lfEscapement = lf.lfEscapement; + this.lfOrientation = lf.lfOrientation; + this.lfWeight = lf.lfWeight; + this.lfItalic = lf.lfItalic; + this.lfUnderline = lf.lfUnderline; + this.lfStrikeOut = lf.lfStrikeOut; + this.lfCharSet = lf.lfCharSet; + this.lfOutPrecision = lf.lfOutPrecision; + this.lfClipPrecision = lf.lfClipPrecision; + this.lfQuality = lf.lfQuality; + this.lfPitchAndFamily = lf.lfPitchAndFamily; + this.lfFaceName = lf.lfFaceName; } public int lfHeight; public int lfWidth; @@ -2888,8 +2961,8 @@ public LOGFONT( LOGFONT lf ) public byte lfClipPrecision; public byte lfQuality; public byte lfPitchAndFamily; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] - public string lfFaceName; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] + public string lfFaceName; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] @@ -2917,71 +2990,73 @@ public struct TEXTMETRIC public byte tmCharSet; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public class NOTIFYICONDATA { - public int cbSize = Marshal.SizeOf(); - public IntPtr hWnd; - public int uID; - public int uFlags; - public int uCallbackMessage; - public IntPtr hIcon; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] - public string szTip; - public int dwState = 0; - public int dwStateMask = 0; + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class NOTIFYICONDATA + { + public int cbSize = Marshal.SizeOf(); + public IntPtr hWnd; + public int uID; + public int uFlags; + public int uCallbackMessage; + public IntPtr hIcon; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] + public string szTip; + public int dwState = 0; + public int dwStateMask = 0; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] - public string szInfo; - public int uTimeoutOrVersion; + public string szInfo; + public int uTimeoutOrVersion; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)] - public string szInfoTitle; - public int dwInfoFlags; + public string szInfoTitle; + public int dwInfoFlags; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class MENUITEMINFO_T { - public int cbSize = Marshal.SizeOf(); - public int fMask; - public int fType; - public int fState; - public int wID; - public IntPtr hSubMenu; - public IntPtr hbmpChecked; - public IntPtr hbmpUnchecked; - public IntPtr dwItemData; - public string dwTypeData; - public int cch; + public int cbSize = Marshal.SizeOf(); + public int fMask; + public int fType; + public int fState; + public int wID; + public IntPtr hSubMenu; + public IntPtr hbmpChecked; + public IntPtr hbmpUnchecked; + public IntPtr dwItemData; + public string dwTypeData; + public int cch; } // This version allows you to read the string that's stuffed // in the native menu item. You have to do the marshaling on // your own though. - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class MENUITEMINFO_T_RW { - public int cbSize = Marshal.SizeOf(); - public int fMask = 0; - public int fType = 0; - public int fState = 0; - public int wID = 0; - public IntPtr hSubMenu = IntPtr.Zero; - public IntPtr hbmpChecked = IntPtr.Zero; - public IntPtr hbmpUnchecked = IntPtr.Zero; - public IntPtr dwItemData = IntPtr.Zero; - public IntPtr dwTypeData = IntPtr.Zero; - public int cch = 0; - public IntPtr hbmpItem = IntPtr.Zero; // requires WINVER > 5 - } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] + public int cbSize = Marshal.SizeOf(); + public int fMask = 0; + public int fType = 0; + public int fState = 0; + public int wID = 0; + public IntPtr hSubMenu = IntPtr.Zero; + public IntPtr hbmpChecked = IntPtr.Zero; + public IntPtr hbmpUnchecked = IntPtr.Zero; + public IntPtr dwItemData = IntPtr.Zero; + public IntPtr dwTypeData = IntPtr.Zero; + public int cch = 0; + public IntPtr hbmpItem = IntPtr.Zero; // requires WINVER > 5 + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct MSAAMENUINFO { public int dwMSAASignature; public int cchWText; public string pszWText; - - public MSAAMENUINFO(string text) { - dwMSAASignature = unchecked((int) MSAA_MENU_SIG); + + public MSAAMENUINFO(string text) + { + dwMSAASignature = unchecked((int)MSAA_MENU_SIG); cchWText = text.Length; pszWText = text; } @@ -2989,74 +3064,76 @@ public MSAAMENUINFO(string text) { public delegate bool EnumThreadWindowsCallback(IntPtr hWnd, IntPtr lParam); - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class OPENFILENAME_I { - public int lStructSize = Marshal.SizeOf(); //ndirect.DllLib.sizeOf(this); - public IntPtr hwndOwner; - public IntPtr hInstance; - public string lpstrFilter; // use embedded nulls to separate filters - public IntPtr lpstrCustomFilter = IntPtr.Zero; - public int nMaxCustFilter = 0; - public int nFilterIndex; - public IntPtr lpstrFile; - public int nMaxFile = Interop.Kernel32.MAX_PATH; - public IntPtr lpstrFileTitle = IntPtr.Zero; - public int nMaxFileTitle = Interop.Kernel32.MAX_PATH; - public string lpstrInitialDir; - public string lpstrTitle; - public int Flags; - public short nFileOffset = 0; - public short nFileExtension = 0; - public string lpstrDefExt; - public IntPtr lCustData = IntPtr.Zero; - public WndProc lpfnHook; - public string lpTemplateName = null; - public IntPtr pvReserved = IntPtr.Zero; - public int dwReserved = 0; - public int FlagsEx; - } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public class CHOOSEFONT { - public int lStructSize = Marshal.SizeOf(); // ndirect.DllLib.sizeOf(this); - public IntPtr hwndOwner; - public IntPtr hDC; - public IntPtr lpLogFont; - public int iPointSize = 0; - public int Flags; - public int rgbColors; - public IntPtr lCustData = IntPtr.Zero; - public WndProc lpfnHook; - public string lpTemplateName = null; - public IntPtr hInstance; - public string lpszStyle = null; - public short nFontType = 0; - public short ___MISSING_ALIGNMENT__ = 0; - public int nSizeMin; - public int nSizeMax; + public int lStructSize = Marshal.SizeOf(); //ndirect.DllLib.sizeOf(this); + public IntPtr hwndOwner; + public IntPtr hInstance; + public string lpstrFilter; // use embedded nulls to separate filters + public IntPtr lpstrCustomFilter = IntPtr.Zero; + public int nMaxCustFilter = 0; + public int nFilterIndex; + public IntPtr lpstrFile; + public int nMaxFile = Interop.Kernel32.MAX_PATH; + public IntPtr lpstrFileTitle = IntPtr.Zero; + public int nMaxFileTitle = Interop.Kernel32.MAX_PATH; + public string lpstrInitialDir; + public string lpstrTitle; + public int Flags; + public short nFileOffset = 0; + public short nFileExtension = 0; + public string lpstrDefExt; + public IntPtr lCustData = IntPtr.Zero; + public WndProc lpfnHook; + public string lpTemplateName = null; + public IntPtr pvReserved = IntPtr.Zero; + public int dwReserved = 0; + public int FlagsEx; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class CHOOSEFONT + { + public int lStructSize = Marshal.SizeOf(); // ndirect.DllLib.sizeOf(this); + public IntPtr hwndOwner; + public IntPtr hDC; + public IntPtr lpLogFont; + public int iPointSize = 0; + public int Flags; + public int rgbColors; + public IntPtr lCustData = IntPtr.Zero; + public WndProc lpfnHook; + public string lpTemplateName = null; + public IntPtr hInstance; + public string lpszStyle = null; + public short nFontType = 0; + public short ___MISSING_ALIGNMENT__ = 0; + public int nSizeMin; + public int nSizeMax; } [StructLayout(LayoutKind.Sequential)] - public class BITMAPINFO { + public class BITMAPINFO + { // bmiHeader was a by-value BITMAPINFOHEADER structure - public int bmiHeader_biSize = 40; // ndirect.DllLib.sizeOf( BITMAPINFOHEADER.class ); - public int bmiHeader_biWidth = 0; - public int bmiHeader_biHeight = 0; - public short bmiHeader_biPlanes = 0; - public short bmiHeader_biBitCount = 0; - public int bmiHeader_biCompression = 0; - public int bmiHeader_biSizeImage = 0; - public int bmiHeader_biXPelsPerMeter = 0; - public int bmiHeader_biYPelsPerMeter = 0; - public int bmiHeader_biClrUsed = 0; - public int bmiHeader_biClrImportant = 0; + public int bmiHeader_biSize = 40; // ndirect.DllLib.sizeOf( BITMAPINFOHEADER.class ); + public int bmiHeader_biWidth = 0; + public int bmiHeader_biHeight = 0; + public short bmiHeader_biPlanes = 0; + public short bmiHeader_biBitCount = 0; + public int bmiHeader_biCompression = 0; + public int bmiHeader_biSizeImage = 0; + public int bmiHeader_biXPelsPerMeter = 0; + public int bmiHeader_biYPelsPerMeter = 0; + public int bmiHeader_biClrUsed = 0; + public int bmiHeader_biClrImportant = 0; // bmiColors was an embedded array of RGBQUAD structures - public byte bmiColors_rgbBlue = 0; - public byte bmiColors_rgbGreen = 0; - public byte bmiColors_rgbRed = 0; - public byte bmiColors_rgbReserved = 0; + public byte bmiColors_rgbBlue = 0; + public byte bmiColors_rgbGreen = 0; + public byte bmiColors_rgbRed = 0; + public byte bmiColors_rgbReserved = 0; private BITMAPINFO() { @@ -3065,86 +3142,91 @@ private BITMAPINFO() } [StructLayout(LayoutKind.Sequential)] - public class BITMAPINFOHEADER { - public int biSize = 40; // ndirect.DllLib.sizeOf( this ); - public int biWidth; - public int biHeight; - public short biPlanes; - public short biBitCount; - public int biCompression; - public int biSizeImage = 0; - public int biXPelsPerMeter = 0; - public int biYPelsPerMeter = 0; - public int biClrUsed = 0; - public int biClrImportant = 0; - } - - public class Ole { + public class BITMAPINFOHEADER + { + public int biSize = 40; // ndirect.DllLib.sizeOf( this ); + public int biWidth; + public int biHeight; + public short biPlanes; + public short biBitCount; + public int biCompression; + public int biSizeImage = 0; + public int biXPelsPerMeter = 0; + public int biYPelsPerMeter = 0; + public int biClrUsed = 0; + public int biClrImportant = 0; + } + + public class Ole + { public const int PICTYPE_UNINITIALIZED = -1; - public const int PICTYPE_NONE = 0; - public const int PICTYPE_BITMAP = 1; - public const int PICTYPE_METAFILE = 2; - public const int PICTYPE_ICON = 3; - public const int PICTYPE_ENHMETAFILE = 4; + public const int PICTYPE_NONE = 0; + public const int PICTYPE_BITMAP = 1; + public const int PICTYPE_METAFILE = 2; + public const int PICTYPE_ICON = 3; + public const int PICTYPE_ENHMETAFILE = 4; public const int STATFLAG_DEFAULT = 0; public const int STATFLAG_NONAME = 1; } [StructLayout(LayoutKind.Sequential)] - public class STATSTG { + public class STATSTG + { [MarshalAs(UnmanagedType.LPWStr)] - public string pwcsName = null; - - public int type; + public string pwcsName = null; + + public int type; [MarshalAs(UnmanagedType.I8)] - public long cbSize; + public long cbSize; [MarshalAs(UnmanagedType.I8)] - public long mtime = 0; + public long mtime = 0; [MarshalAs(UnmanagedType.I8)] - public long ctime = 0; + public long ctime = 0; [MarshalAs(UnmanagedType.I8)] - public long atime = 0; + public long atime = 0; [MarshalAs(UnmanagedType.I4)] - public int grfMode = 0; + public int grfMode = 0; [MarshalAs(UnmanagedType.I4)] - public int grfLocksSupported; - - public int clsid_data1 = 0; + public int grfLocksSupported; + + public int clsid_data1 = 0; [MarshalAs(UnmanagedType.I2)] - public short clsid_data2 = 0; + public short clsid_data2 = 0; [MarshalAs(UnmanagedType.I2)] - public short clsid_data3 = 0; + public short clsid_data3 = 0; [MarshalAs(UnmanagedType.U1)] - public byte clsid_b0 = 0; + public byte clsid_b0 = 0; [MarshalAs(UnmanagedType.U1)] - public byte clsid_b1 = 0; + public byte clsid_b1 = 0; [MarshalAs(UnmanagedType.U1)] - public byte clsid_b2 = 0; + public byte clsid_b2 = 0; [MarshalAs(UnmanagedType.U1)] - public byte clsid_b3 = 0; + public byte clsid_b3 = 0; [MarshalAs(UnmanagedType.U1)] - public byte clsid_b4 = 0; + public byte clsid_b4 = 0; [MarshalAs(UnmanagedType.U1)] - public byte clsid_b5 = 0; + public byte clsid_b5 = 0; [MarshalAs(UnmanagedType.U1)] - public byte clsid_b6 = 0; + public byte clsid_b6 = 0; [MarshalAs(UnmanagedType.U1)] - public byte clsid_b7 = 0; + public byte clsid_b7 = 0; [MarshalAs(UnmanagedType.I4)] - public int grfStateBits = 0; + public int grfStateBits = 0; [MarshalAs(UnmanagedType.I4)] - public int reserved = 0; + public int reserved = 0; } - + [StructLayout(LayoutKind.Sequential)] - public class FILETIME { + public class FILETIME + { public uint dwLowDateTime = 0; public uint dwHighDateTime = 0; } [StructLayout(LayoutKind.Sequential)] - public class SYSTEMTIME { + public class SYSTEMTIME + { public short wYear; public short wMonth; public short wDayOfWeek; @@ -3154,70 +3236,81 @@ public class SYSTEMTIME { public short wSecond; public short wMilliseconds; - public override string ToString() { - return "[SYSTEMTIME: " - + wDay.ToString(CultureInfo.InvariantCulture) +"/" + wMonth.ToString(CultureInfo.InvariantCulture) + "/" + wYear.ToString(CultureInfo.InvariantCulture) + public override string ToString() + { + return "[SYSTEMTIME: " + + wDay.ToString(CultureInfo.InvariantCulture) + "/" + wMonth.ToString(CultureInfo.InvariantCulture) + "/" + wYear.ToString(CultureInfo.InvariantCulture) + " " + wHour.ToString(CultureInfo.InvariantCulture) + ":" + wMinute.ToString(CultureInfo.InvariantCulture) + ":" + wSecond.ToString(CultureInfo.InvariantCulture) + "]"; } } [StructLayout(LayoutKind.Sequential)] - public sealed class _POINTL { - public int x; - public int y; + public sealed class _POINTL + { + public int x; + public int y; } [StructLayout(LayoutKind.Sequential)] - public sealed class tagSIZE { - public int cx = 0; - public int cy = 0; + public sealed class tagSIZE + { + public int cx = 0; + public int cy = 0; } [StructLayout(LayoutKind.Sequential)] - public class COMRECT { + public class COMRECT + { public int left; public int top; public int right; public int bottom; - - public COMRECT() { + + public COMRECT() + { } - public COMRECT(System.Drawing.Rectangle r) { + public COMRECT(System.Drawing.Rectangle r) + { this.left = r.X; this.top = r.Y; this.right = r.Right; this.bottom = r.Bottom; } - public COMRECT(int left, int top, int right, int bottom) { + public COMRECT(int left, int top, int right, int bottom) + { this.left = left; this.top = top; this.right = right; this.bottom = bottom; } - public static COMRECT FromXYWH(int x, int y, int width, int height) { + public static COMRECT FromXYWH(int x, int y, int width, int height) + { return new COMRECT(x, y, x + width, y + height); } - public override string ToString() { + public override string ToString() + { return "Left = " + left + " Top " + top + " Right = " + right + " Bottom = " + bottom; } } [StructLayout(LayoutKind.Sequential)/*leftover(noAutoOffset)*/] - public sealed class tagOleMenuGroupWidths { - [MarshalAs(UnmanagedType.ByValArray, SizeConst=6)/*leftover(offset=0, widths)*/] + public sealed class tagOleMenuGroupWidths + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)/*leftover(offset=0, widths)*/] public int[] widths = new int[6]; } [StructLayout(LayoutKind.Sequential)] [Serializable] - public class MSOCRINFOSTRUCT { + public class MSOCRINFOSTRUCT + { public int cbSize = Marshal.SizeOf(); // size of MSOCRINFO structure in bytes. public int uIdleTimeInterval; // If olecrfNeedPeriodicIdleTime is registered // in grfcrf, component needs to perform @@ -3226,42 +3319,42 @@ public class MSOCRINFOSTRUCT { public int grfcrf; // bit flags taken from olecrf values (above) public int grfcadvf; // bit flags taken from olecadvf values (above) } - + [StructLayout(LayoutKind.Sequential)] public struct NMLISTVIEW { public NMHDR hdr; - public int iItem; - public int iSubItem; - public int uNewState; - public int uOldState; - public int uChanged; + public int iItem; + public int iSubItem; + public int uNewState; + public int uOldState; + public int uChanged; public IntPtr lParam; } - + [StructLayout(LayoutKind.Sequential)/*leftover(noAutoOffset)*/] public sealed class tagPOINTF { - [MarshalAs(UnmanagedType.R4)/*leftover(offset=0, x)*/] - public float x; + [MarshalAs(UnmanagedType.R4)/*leftover(offset=0, x)*/] + public float x; - [MarshalAs(UnmanagedType.R4)/*leftover(offset=4, y)*/] - public float y; + [MarshalAs(UnmanagedType.R4)/*leftover(offset=4, y)*/] + public float y; } [StructLayout(LayoutKind.Sequential)/*leftover(noAutoOffset)*/] public sealed class tagOIFI { - [MarshalAs(UnmanagedType.U4)/*leftover(offset=0, cb)*/] - public int cb; - - public bool fMDIApp; - public IntPtr hwndFrame; - public IntPtr hAccel; + [MarshalAs(UnmanagedType.U4)/*leftover(offset=0, cb)*/] + public int cb; - [MarshalAs(UnmanagedType.U4)/*leftover(offset=16, cAccelEntries)*/] - public int cAccelEntries; + public bool fMDIApp; + public IntPtr hwndFrame; + public IntPtr hAccel; + + [MarshalAs(UnmanagedType.U4)/*leftover(offset=16, cAccelEntries)*/] + public int cAccelEntries; } @@ -3353,13 +3446,13 @@ public sealed class tagSIZEL public sealed class tagOLEVERB { public int lVerb; - + [MarshalAs(UnmanagedType.LPWStr)/*leftover(offset=4, customMarshal="UniStringMarshaller", lpszVerbName)*/] public string lpszVerbName; - + [MarshalAs(UnmanagedType.U4)/*leftover(offset=8, fuFlags)*/] public int fuFlags; - + [MarshalAs(UnmanagedType.U4)/*leftover(offset=12, grfAttribs)*/] public int grfAttribs; } @@ -3369,7 +3462,7 @@ public sealed class tagLOGPALETTE { [MarshalAs(UnmanagedType.U2)/*leftover(offset=0, palVersion)*/] public short palVersion = 0; - + [MarshalAs(UnmanagedType.U2)/*leftover(offset=2, palNumEntries)*/] public short palNumEntries = 0; } @@ -3379,25 +3472,26 @@ public sealed class tagCONTROLINFO { [MarshalAs(UnmanagedType.U4)/*leftover(offset=0, cb)*/] public int cb = Marshal.SizeOf(); - + public IntPtr hAccel; - + [MarshalAs(UnmanagedType.U2)/*leftover(offset=8, cAccel)*/] public short cAccel; - + [MarshalAs(UnmanagedType.U4)/*leftover(offset=10, dwFlags)*/] public int dwFlags; } - + [StructLayout(LayoutKind.Sequential)/*leftover(noAutoOffset)*/] public sealed class CA_STRUCT { public int cElems = 0; public IntPtr pElems = IntPtr.Zero; } - + [StructLayout(LayoutKind.Sequential)] - public sealed class VARIANT { + public sealed class VARIANT + { [MarshalAs(UnmanagedType.I2)] public short vt; [MarshalAs(UnmanagedType.I2)] @@ -3411,18 +3505,23 @@ public sealed class VARIANT { public IntPtr data2; - public bool Byref{ - get{ + public bool Byref + { + get + { return 0 != (vt & (int)tagVT.VT_BYREF); } } - public void Clear() { - if ((this.vt == (int)tagVT.VT_UNKNOWN || this.vt == (int)tagVT.VT_DISPATCH) && this.data1 != IntPtr.Zero) { + public void Clear() + { + if ((this.vt == (int)tagVT.VT_UNKNOWN || this.vt == (int)tagVT.VT_DISPATCH) && this.data1 != IntPtr.Zero) + { Marshal.Release(this.data1); } - if (this.vt == (int)tagVT.VT_BSTR && this.data1 != IntPtr.Zero) { + if (this.vt == (int)tagVT.VT_BSTR && this.data1 != IntPtr.Zero) + { SysFreeString(this.data1); } @@ -3430,171 +3529,188 @@ public void Clear() { this.vt = (int)tagVT.VT_EMPTY; } - ~VARIANT() { + ~VARIANT() + { Clear(); } - [DllImport(ExternDll.Oleaut32,CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Oleaut32, CharSet = CharSet.Auto)] + private static extern IntPtr SysAllocString([In, MarshalAs(UnmanagedType.LPWStr)]string s); - [DllImport(ExternDll.Oleaut32,CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Oleaut32, CharSet = CharSet.Auto)] + private static extern void SysFreeString(IntPtr pbstr); - public void SetLong(long lVal) { + public void SetLong(long lVal) + { data1 = (IntPtr)(lVal & 0xFFFFFFFF); data2 = (IntPtr)((lVal >> 32) & 0xFFFFFFFF); } - public object ToObject() { + public object ToObject() + { IntPtr val = data1; long longVal; int vtType = (int)(this.vt & (short)tagVT.VT_TYPEMASK); - switch (vtType) { - case (int)tagVT.VT_EMPTY: - return null; - case (int)tagVT.VT_NULL: - return Convert.DBNull; - - case (int)tagVT.VT_I1: - if (Byref) { - val = (IntPtr) Marshal.ReadByte(val); - } - return (sbyte) (0xFF & (sbyte) val); - - case (int)tagVT.VT_UI1: - if (Byref) { - val = (IntPtr) Marshal.ReadByte(val); - } - - return (byte) (0xFF & (byte) val); - - case (int)tagVT.VT_I2: - if (Byref) { - val = (IntPtr) Marshal.ReadInt16(val); - } - return (short)(0xFFFF & (short) val); - - case (int)tagVT.VT_UI2: - if (Byref) { - val = (IntPtr) Marshal.ReadInt16(val); - } - return (ushort)(0xFFFF & (ushort) val); - - case (int)tagVT.VT_I4: - case (int)tagVT.VT_INT: - if (Byref) { - val = (IntPtr) Marshal.ReadInt32(val); - } - return (int)val; - - case (int)tagVT.VT_UI4: - case (int)tagVT.VT_UINT: - if (Byref) { - val = (IntPtr) Marshal.ReadInt32(val); - } - return (uint)val; - - case (int)tagVT.VT_I8: - case (int)tagVT.VT_UI8: - if (Byref) { - longVal = Marshal.ReadInt64(val); - } - else { - longVal = ((uint)data1 & 0xffffffff) | ((uint)data2 << 32); - } - - if (vt == (int)tagVT.VT_I8) { - return (long)longVal; - } - else { - return (ulong)longVal; - } + switch (vtType) + { + case (int)tagVT.VT_EMPTY: + return null; + case (int)tagVT.VT_NULL: + return Convert.DBNull; + + case (int)tagVT.VT_I1: + if (Byref) + { + val = (IntPtr)Marshal.ReadByte(val); + } + return (sbyte)(0xFF & (sbyte)val); + + case (int)tagVT.VT_UI1: + if (Byref) + { + val = (IntPtr)Marshal.ReadByte(val); + } + + return (byte)(0xFF & (byte)val); + + case (int)tagVT.VT_I2: + if (Byref) + { + val = (IntPtr)Marshal.ReadInt16(val); + } + return (short)(0xFFFF & (short)val); + + case (int)tagVT.VT_UI2: + if (Byref) + { + val = (IntPtr)Marshal.ReadInt16(val); + } + return (ushort)(0xFFFF & (ushort)val); + + case (int)tagVT.VT_I4: + case (int)tagVT.VT_INT: + if (Byref) + { + val = (IntPtr)Marshal.ReadInt32(val); + } + return (int)val; + + case (int)tagVT.VT_UI4: + case (int)tagVT.VT_UINT: + if (Byref) + { + val = (IntPtr)Marshal.ReadInt32(val); + } + return (uint)val; + + case (int)tagVT.VT_I8: + case (int)tagVT.VT_UI8: + if (Byref) + { + longVal = Marshal.ReadInt64(val); + } + else + { + longVal = ((uint)data1 & 0xffffffff) | ((uint)data2 << 32); + } + + if (vt == (int)tagVT.VT_I8) + { + return (long)longVal; + } + else + { + return (ulong)longVal; + } } - if (Byref) { + if (Byref) + { val = GetRefInt(val); } - switch (vtType) { - case (int)tagVT.VT_R4: - case (int)tagVT.VT_R8: - - // can I use unsafe here? - throw new FormatException(SR.CannotConvertIntToFloat); - - case (int)tagVT.VT_CY: - // internally currency is 8-byte int scaled by 10,000 - longVal = ((uint)data1 & 0xffffffff) | ((uint)data2 << 32); - return new decimal(longVal); - case (int)tagVT.VT_DATE: - throw new FormatException(SR.CannotConvertDoubleToDate); - - case (int)tagVT.VT_BSTR: - case (int)tagVT.VT_LPWSTR: - return Marshal.PtrToStringUni(val); - - case (int)tagVT.VT_LPSTR: - return Marshal.PtrToStringAnsi(val); - - case (int)tagVT.VT_DISPATCH: - case (int)tagVT.VT_UNKNOWN: - { - return Marshal.GetObjectForIUnknown(val); - } - - case (int)tagVT.VT_HRESULT: - return val; - - case (int)tagVT.VT_DECIMAL: - longVal = ((uint)data1 & 0xffffffff) | ((uint)data2 << 32); - return new decimal(longVal); - - case (int)tagVT.VT_BOOL: - return (val != IntPtr.Zero); - - case (int)tagVT.VT_VARIANT: - VARIANT varStruct = Marshal.PtrToStructure(val); - return varStruct.ToObject(); - - case (int)tagVT.VT_CLSID: - Guid guid = Marshal.PtrToStructure(val); - return guid; - - case (int)tagVT.VT_FILETIME: - longVal = ((uint)data1 & 0xffffffff) | ((uint)data2 << 32); - return new DateTime(longVal); - - case (int)tagVT.VT_USERDEFINED: - throw new ArgumentException(string.Format(SR.COM2UnhandledVT, "VT_USERDEFINED")); - - case (int)tagVT.VT_ARRAY: - case (int)tagVT.VT_VOID: - case (int)tagVT.VT_PTR: - case (int)tagVT.VT_SAFEARRAY: - case (int)tagVT.VT_CARRAY: - - case (int)tagVT.VT_RECORD: - case (int)tagVT.VT_BLOB: - case (int)tagVT.VT_STREAM: - case (int)tagVT.VT_STORAGE: - case (int)tagVT.VT_STREAMED_OBJECT: - case (int)tagVT.VT_STORED_OBJECT: - case (int)tagVT.VT_BLOB_OBJECT: - case (int)tagVT.VT_CF: - case (int)tagVT.VT_BSTR_BLOB: - case (int)tagVT.VT_VECTOR: - case (int)tagVT.VT_BYREF: - default: - int iVt = this.vt; - throw new ArgumentException(string.Format(SR.COM2UnhandledVT, iVt.ToString(CultureInfo.InvariantCulture))); + switch (vtType) + { + case (int)tagVT.VT_R4: + case (int)tagVT.VT_R8: + + // can I use unsafe here? + throw new FormatException(SR.CannotConvertIntToFloat); + + case (int)tagVT.VT_CY: + // internally currency is 8-byte int scaled by 10,000 + longVal = ((uint)data1 & 0xffffffff) | ((uint)data2 << 32); + return new decimal(longVal); + case (int)tagVT.VT_DATE: + throw new FormatException(SR.CannotConvertDoubleToDate); + + case (int)tagVT.VT_BSTR: + case (int)tagVT.VT_LPWSTR: + return Marshal.PtrToStringUni(val); + + case (int)tagVT.VT_LPSTR: + return Marshal.PtrToStringAnsi(val); + + case (int)tagVT.VT_DISPATCH: + case (int)tagVT.VT_UNKNOWN: + { + return Marshal.GetObjectForIUnknown(val); + } + + case (int)tagVT.VT_HRESULT: + return val; + + case (int)tagVT.VT_DECIMAL: + longVal = ((uint)data1 & 0xffffffff) | ((uint)data2 << 32); + return new decimal(longVal); + + case (int)tagVT.VT_BOOL: + return (val != IntPtr.Zero); + + case (int)tagVT.VT_VARIANT: + VARIANT varStruct = Marshal.PtrToStructure(val); + return varStruct.ToObject(); + + case (int)tagVT.VT_CLSID: + Guid guid = Marshal.PtrToStructure(val); + return guid; + + case (int)tagVT.VT_FILETIME: + longVal = ((uint)data1 & 0xffffffff) | ((uint)data2 << 32); + return new DateTime(longVal); + + case (int)tagVT.VT_USERDEFINED: + throw new ArgumentException(string.Format(SR.COM2UnhandledVT, "VT_USERDEFINED")); + + case (int)tagVT.VT_ARRAY: + case (int)tagVT.VT_VOID: + case (int)tagVT.VT_PTR: + case (int)tagVT.VT_SAFEARRAY: + case (int)tagVT.VT_CARRAY: + + case (int)tagVT.VT_RECORD: + case (int)tagVT.VT_BLOB: + case (int)tagVT.VT_STREAM: + case (int)tagVT.VT_STORAGE: + case (int)tagVT.VT_STREAMED_OBJECT: + case (int)tagVT.VT_STORED_OBJECT: + case (int)tagVT.VT_BLOB_OBJECT: + case (int)tagVT.VT_CF: + case (int)tagVT.VT_BSTR_BLOB: + case (int)tagVT.VT_VECTOR: + case (int)tagVT.VT_BYREF: + default: + int iVt = this.vt; + throw new ArgumentException(string.Format(SR.COM2UnhandledVT, iVt.ToString(CultureInfo.InvariantCulture))); } } - private static IntPtr GetRefInt(IntPtr value) { + private static IntPtr GetRefInt(IntPtr value) + { return Marshal.ReadIntPtr(value); } } @@ -3602,14 +3718,15 @@ private static IntPtr GetRefInt(IntPtr value) { [StructLayout(LayoutKind.Sequential)/*leftover(noAutoOffset)*/] public sealed class tagLICINFO { - [MarshalAs(UnmanagedType.U4)/*leftover(offset=0, cb)*/] - public int cbLicInfo = Marshal.SizeOf(); - - public int fRuntimeAvailable = 0; - public int fLicVerified = 0; + [MarshalAs(UnmanagedType.U4)/*leftover(offset=0, cb)*/] + public int cbLicInfo = Marshal.SizeOf(); + + public int fRuntimeAvailable = 0; + public int fLicVerified = 0; } - public enum tagVT { + public enum tagVT + { VT_EMPTY = 0, VT_NULL = 1, VT_I2 = 2, @@ -3661,62 +3778,64 @@ public enum tagVT { VT_TYPEMASK = 4095 } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public class WNDCLASS_D { - public int style; - public WndProc lpfnWndProc; - public int cbClsExtra = 0; - public int cbWndExtra = 0; - public IntPtr hInstance = IntPtr.Zero; - public IntPtr hIcon = IntPtr.Zero; - public IntPtr hCursor = IntPtr.Zero; - public IntPtr hbrBackground = IntPtr.Zero; - public string lpszMenuName = null; - public string lpszClassName = null; - } - - public class MSOCM { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class WNDCLASS_D + { + public int style; + public WndProc lpfnWndProc; + public int cbClsExtra = 0; + public int cbWndExtra = 0; + public IntPtr hInstance = IntPtr.Zero; + public IntPtr hIcon = IntPtr.Zero; + public IntPtr hCursor = IntPtr.Zero; + public IntPtr hbrBackground = IntPtr.Zero; + public string lpszMenuName = null; + public string lpszClassName = null; + } + + public class MSOCM + { // MSO Component registration flags - public const int msocrfNeedIdleTime = 1; + public const int msocrfNeedIdleTime = 1; public const int msocrfNeedPeriodicIdleTime = 2; - public const int msocrfPreTranslateKeys = 4; - public const int msocrfPreTranslateAll = 8; + public const int msocrfPreTranslateKeys = 4; + public const int msocrfPreTranslateAll = 8; public const int msocrfNeedSpecActiveNotifs = 16; - public const int msocrfNeedAllActiveNotifs = 32; + public const int msocrfNeedAllActiveNotifs = 32; public const int msocrfExclusiveBorderSpace = 64; public const int msocrfExclusiveActivation = 128; public const int msocrfNeedAllMacEvents = 256; - public const int msocrfMaster = 512; - + public const int msocrfMaster = 512; + // MSO Component registration advise flags (see msocstate enumeration) - public const int msocadvfModal = 1; - public const int msocadvfRedrawOff = 2; - public const int msocadvfWarningsOff = 4; - public const int msocadvfRecording = 8; - + public const int msocadvfModal = 1; + public const int msocadvfRedrawOff = 2; + public const int msocadvfWarningsOff = 4; + public const int msocadvfRecording = 8; + // MSO Component Host flags public const int msochostfExclusiveBorderSpace = 1; - + // MSO idle flags, passed to IMsoComponent::FDoIdle and // IMsoStdComponentMgr::FDoIdle. - public const int msoidlefPeriodic = 1; + public const int msoidlefPeriodic = 1; public const int msoidlefNonPeriodic = 2; - public const int msoidlefPriority = 4; - public const int msoidlefAll = -1; - + public const int msoidlefPriority = 4; + public const int msoidlefAll = -1; + // MSO Reasons for pushing a message loop, passed to // IMsoComponentManager::FPushMessageLoop and // IMsoComponentHost::FPushMessageLoop. The host should remain in message // loop until IMsoComponent::FContinueMessageLoop - public const int msoloopDoEventsModal = -2; // Note this is not an official MSO loop -- it just must be distinct. - public const int msoloopMain = -1; // Note this is not an official MSO loop -- it just must be distinct. - public const int msoloopFocusWait = 1; - public const int msoloopDoEvents = 2; - public const int msoloopDebug = 3; - public const int msoloopModalForm = 4; - public const int msoloopModalAlert = 5; - - + public const int msoloopDoEventsModal = -2; // Note this is not an official MSO loop -- it just must be distinct. + public const int msoloopMain = -1; // Note this is not an official MSO loop -- it just must be distinct. + public const int msoloopFocusWait = 1; + public const int msoloopDoEvents = 2; + public const int msoloopDebug = 3; + public const int msoloopModalForm = 4; + public const int msoloopModalAlert = 5; + + /* msocstate values: state IDs passed to IMsoComponent::OnEnterState, IMsoComponentManager::OnComponentEnterState/FOnComponentExitState/FInState, @@ -3742,12 +3861,12 @@ this state. app exits this state. msocstateRecording (Recording state): Used to notify host/component when Recording is turned on or off. */ - public const int msocstateModal = 1; - public const int msocstateRedrawOff = 2; + public const int msocstateModal = 1; + public const int msocstateRedrawOff = 2; public const int msocstateWarningsOff = 3; - public const int msocstateRecording = 4; - - + public const int msocstateRecording = 4; + + /* ** Comments on State Contexts ** IMsoComponentManager::FCreateSubComponentManager allows one to create a hierarchical tree of component managers. This tree is used to maintain @@ -3769,10 +3888,10 @@ state change. In IMsoComponentManager::OnComponentEnterState/FOnComponentExitState, the comp mgr informs only those components/host that are within the specified state context. */ - public const int msoccontextAll = 0; - public const int msoccontextMine = 1; - public const int msoccontextOthers = 2; - + public const int msoccontextAll = 0; + public const int msoccontextMine = 1; + public const int msoccontextOthers = 2; + /* ** WM_MOUSEACTIVATE Note (for top level compoenents and host) ** If the active (or tracking) comp's reg info indicates that it wants mouse messages, then no MA_xxxANDEAT value should be returned @@ -3782,13 +3901,13 @@ to process the resulting mouse message. If one does not want to examine WM_MOUSEACTIVATE if any comp is active (or tracking). One can query the reg info of the active (or tracking) component at any time via IMsoComponentManager::FGetActiveComponent. */ - + /* msogac values: values passed to IMsoComponentManager::FGetActiveComponent. */ - public const int msogacActive = 0; - public const int msogacTracking = 1; - public const int msogacTrackingOrActive = 2; - + public const int msogacActive = 0; + public const int msogacTracking = 1; + public const int msogacTrackingOrActive = 2; + /* msocWindow values: values passed to IMsoComponent::HwndGetWindow. */ public const int msocWindowFrameToplevel = 0; public const int msocWindowFrameOwner = 1; @@ -3796,117 +3915,122 @@ One can query the reg info of the active (or tracking) component at any public const int msocWindowDlgOwner = 3; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class TOOLINFO_T { - public int cbSize = Marshal.SizeOf(); - public int uFlags; - public IntPtr hwnd; - public IntPtr uId; - public RECT rect; - public IntPtr hinst = IntPtr.Zero; - public string lpszText; - public IntPtr lParam = IntPtr.Zero; + public int cbSize = Marshal.SizeOf(); + public int uFlags; + public IntPtr hwnd; + public IntPtr uId; + public RECT rect; + public IntPtr hinst = IntPtr.Zero; + public string lpszText; + public IntPtr lParam = IntPtr.Zero; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class TOOLINFO_TOOLTIP { - public int cbSize = Marshal.SizeOf(); - public int uFlags; - public IntPtr hwnd; - public IntPtr uId; - public RECT rect; - public IntPtr hinst = IntPtr.Zero; - public IntPtr lpszText; - public IntPtr lParam = IntPtr.Zero; + public int cbSize = Marshal.SizeOf(); + public int uFlags; + public IntPtr hwnd; + public IntPtr uId; + public RECT rect; + public IntPtr hinst = IntPtr.Zero; + public IntPtr lpszText; + public IntPtr lParam = IntPtr.Zero; } [StructLayout(LayoutKind.Sequential)] - public sealed class tagDVTARGETDEVICE { + public sealed class tagDVTARGETDEVICE + { [MarshalAs(UnmanagedType.U4)] - public int tdSize = 0; + public int tdSize = 0; [MarshalAs(UnmanagedType.U2)] - public short tdDriverNameOffset = 0; + public short tdDriverNameOffset = 0; [MarshalAs(UnmanagedType.U2)] - public short tdDeviceNameOffset = 0; + public short tdDeviceNameOffset = 0; [MarshalAs(UnmanagedType.U2)] - public short tdPortNameOffset = 0; + public short tdPortNameOffset = 0; [MarshalAs(UnmanagedType.U2)] - public short tdExtDevmodeOffset = 0; + public short tdExtDevmodeOffset = 0; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public struct TV_ITEM { - public int mask; - public IntPtr hItem; - public int state; - public int stateMask; + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct TV_ITEM + { + public int mask; + public IntPtr hItem; + public int state; + public int stateMask; public IntPtr /* LPTSTR */ pszText; - public int cchTextMax; - public int iImage; - public int iSelectedImage; - public int cChildren; - public IntPtr lParam; - } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public struct TV_INSERTSTRUCT { - public IntPtr hParent; - public IntPtr hInsertAfter; - public int item_mask; - public IntPtr item_hItem; - public int item_state; - public int item_stateMask; + public int cchTextMax; + public int iImage; + public int iSelectedImage; + public int cChildren; + public IntPtr lParam; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct TV_INSERTSTRUCT + { + public IntPtr hParent; + public IntPtr hInsertAfter; + public int item_mask; + public IntPtr item_hItem; + public int item_state; + public int item_stateMask; public IntPtr /* LPTSTR */ item_pszText; - public int item_cchTextMax; - public int item_iImage; - public int item_iSelectedImage; - public int item_cChildren; - public IntPtr item_lParam; - public int item_iIntegral; + public int item_cchTextMax; + public int item_iImage; + public int item_iSelectedImage; + public int item_cChildren; + public IntPtr item_lParam; + public int item_iIntegral; } - + [StructLayout(LayoutKind.Sequential)] public struct NMTREEVIEW { - public NMHDR nmhdr; - public int action; - public TV_ITEM itemOld; - public TV_ITEM itemNew; - public int ptDrag_X; // This should be declared as POINT - public int ptDrag_Y; // we use unsafe blocks to manipulate - // NMTREEVIEW quickly, and POINT is declared - // as a class. Too much churn to change POINT - // now. + public NMHDR nmhdr; + public int action; + public TV_ITEM itemOld; + public TV_ITEM itemNew; + public int ptDrag_X; // This should be declared as POINT + public int ptDrag_Y; // we use unsafe blocks to manipulate + // NMTREEVIEW quickly, and POINT is declared + // as a class. Too much churn to change POINT + // now. } [StructLayout(LayoutKind.Sequential)] public struct NMTVGETINFOTIP { - public NMHDR nmhdr; - public string pszText; - public int cchTextMax; - public IntPtr item; - public IntPtr lParam; + public NMHDR nmhdr; + public string pszText; + public int cchTextMax; + public IntPtr item; + public IntPtr lParam; } [StructLayout(LayoutKind.Sequential)] public class NMTVDISPINFO { - public NMHDR hdr; - public TV_ITEM item; + public NMHDR hdr; + public TV_ITEM item; } [StructLayout(LayoutKind.Sequential)] - public sealed class POINTL { - public int x; - public int y; + public sealed class POINTL + { + public int x; + public int y; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public struct HIGHCONTRAST_I { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct HIGHCONTRAST_I + { public int cbSize; public int dwFlags; public IntPtr lpszDefaultScheme; @@ -3921,30 +4045,31 @@ public enum HRESULT : long ERROR_CANCELLED = 0x800704C7 } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class TCITEM_T { - public int mask; - public int dwState = 0; - public int dwStateMask = 0; - public string pszText; - public int cchTextMax; - public int iImage; - public IntPtr lParam; + public int mask; + public int dwState = 0; + public int dwStateMask = 0; + public string pszText; + public int cchTextMax; + public int iImage; + public IntPtr lParam; } [StructLayout(LayoutKind.Sequential)/*leftover(noAutoOffset)*/] public sealed class tagDISPPARAMS { - public IntPtr rgvarg; - public IntPtr rgdispidNamedArgs; - [MarshalAs(UnmanagedType.U4)/*leftover(offset=8, cArgs)*/] - public int cArgs; - [MarshalAs(UnmanagedType.U4)/*leftover(offset=12, cNamedArgs)*/] - public int cNamedArgs; + public IntPtr rgvarg; + public IntPtr rgdispidNamedArgs; + [MarshalAs(UnmanagedType.U4)/*leftover(offset=8, cArgs)*/] + public int cArgs; + [MarshalAs(UnmanagedType.U4)/*leftover(offset=12, cNamedArgs)*/] + public int cNamedArgs; } - public enum tagINVOKEKIND { + public enum tagINVOKEKIND + { INVOKE_FUNC = 1, INVOKE_PROPERTYGET = 2, INVOKE_PROPERTYPUT = 4, @@ -3952,7 +4077,8 @@ public enum tagINVOKEKIND { } [StructLayout(LayoutKind.Sequential)] - public class tagEXCEPINFO { + public class tagEXCEPINFO + { [MarshalAs(UnmanagedType.U2)] public short wCode = 0; [MarshalAs(UnmanagedType.U2)] @@ -3965,15 +4091,16 @@ public class tagEXCEPINFO { public string bstrHelpFile = null; [MarshalAs(UnmanagedType.U4)] public int dwHelpContext = 0; - + public IntPtr pvReserved = IntPtr.Zero; - + public IntPtr pfnDeferredFillIn = IntPtr.Zero; [MarshalAs(UnmanagedType.U4)] public int scode = 0; } - - public enum tagDESCKIND { + + public enum tagDESCKIND + { DESCKIND_NONE = 0, DESCKIND_FUNCDESC = 1, DESCKIND_VARDESC = 2, @@ -3983,9 +4110,10 @@ public enum tagDESCKIND { } [StructLayout(LayoutKind.Sequential)] - public struct tagFUNCDESC { - public int memid; - + public struct tagFUNCDESC + { + public int memid; + public IntPtr lprgscode; // This is marked as NATIVE_TYPE_PTR, @@ -3993,42 +4121,44 @@ public struct tagFUNCDESC { // a ELEMENT_TYPE_VALUECLASS and fails because it // isn't a NATIVE_TYPE_NESTEDSTRUCT /*[MarshalAs(UnmanagedType.PTR)]*/ - + public /*NativeMethods.tagELEMDESC*/ IntPtr lprgelemdescParam; // cpb, Microsoft, the EE chokes on Enums in structs - + public /*NativeMethods.tagFUNCKIND*/ int funckind; - + public /*NativeMethods.tagINVOKEKIND*/ int invkind; - + public /*NativeMethods.tagCALLCONV*/ int callconv; [MarshalAs(UnmanagedType.I2)] - public short cParams; + public short cParams; [MarshalAs(UnmanagedType.I2)] - public short cParamsOpt; + public short cParamsOpt; [MarshalAs(UnmanagedType.I2)] - public short oVft; + public short oVft; [MarshalAs(UnmanagedType.I2)] - public short cScodesi; - public NativeMethods.tagELEMDESC elemdescFunc; + public short cScodesi; + public NativeMethods.tagELEMDESC elemdescFunc; [MarshalAs(UnmanagedType.U2)] - public short wFuncFlags; + public short wFuncFlags; } - + [StructLayout(LayoutKind.Sequential)] - public struct tagVARDESC { - public int memid; - public IntPtr lpstrSchema; - public IntPtr unionMember; - public NativeMethods.tagELEMDESC elemdescVar; + public struct tagVARDESC + { + public int memid; + public IntPtr lpstrSchema; + public IntPtr unionMember; + public NativeMethods.tagELEMDESC elemdescVar; [MarshalAs(UnmanagedType.U2)] - public short wVarFlags; + public short wVarFlags; public /*NativeMethods.tagVARKIND*/ int varkind; } [StructLayout(LayoutKind.Sequential)] - public struct WINDOWPOS { + public struct WINDOWPOS + { public IntPtr hwnd; public IntPtr hwndInsertAfter; public int x; @@ -4039,26 +4169,29 @@ public struct WINDOWPOS { } [StructLayout(LayoutKind.Sequential)] - public unsafe struct HDLAYOUT { - public IntPtr prc; // pointer to a RECT - public IntPtr pwpos; // pointer to a WINDOWPOS + public unsafe struct HDLAYOUT + { + public IntPtr prc; // pointer to a RECT + public IntPtr pwpos; // pointer to a WINDOWPOS } [StructLayout(LayoutKind.Sequential)] - public class DRAWITEMSTRUCT { + public class DRAWITEMSTRUCT + { public int CtlType = 0; public int CtlID = 0; public int itemID = 0; - public int itemAction =0; + public int itemAction = 0; public int itemState = 0; public IntPtr hwndItem = IntPtr.Zero; public IntPtr hDC = IntPtr.Zero; - public RECT rcItem; + public RECT rcItem; public IntPtr itemData = IntPtr.Zero; } [StructLayout(LayoutKind.Sequential)] - public class MEASUREITEMSTRUCT { + public class MEASUREITEMSTRUCT + { public int CtlType = 0; public int CtlID = 0; public int itemID = 0; @@ -4068,29 +4201,32 @@ public class MEASUREITEMSTRUCT { } [StructLayout(LayoutKind.Sequential)] - public class HELPINFO { - public int cbSize = Marshal.SizeOf(); - public int iContextType = 0; - public int iCtrlId = 0; - public IntPtr hItemHandle = IntPtr.Zero; - public IntPtr dwContextId = IntPtr.Zero; - public POINT MousePos = null; + public class HELPINFO + { + public int cbSize = Marshal.SizeOf(); + public int iContextType = 0; + public int iCtrlId = 0; + public IntPtr hItemHandle = IntPtr.Zero; + public IntPtr dwContextId = IntPtr.Zero; + public POINT MousePos = null; } [StructLayout(LayoutKind.Sequential)] - public class ACCEL { + public class ACCEL + { public byte fVirt; public short key; public short cmd; } [StructLayout(LayoutKind.Sequential)] - public class MINMAXINFO { - public POINT ptReserved = null; - public POINT ptMaxSize = null; - public POINT ptMaxPosition = null; - public POINT ptMinTrackSize = null; - public POINT ptMaxTrackSize = null; + public class MINMAXINFO + { + public POINT ptReserved = null; + public POINT ptMaxSize = null; + public POINT ptMaxPosition = null; + public POINT ptMinTrackSize = null; + public POINT ptMaxTrackSize = null; } [ComImport] @@ -4098,8 +4234,8 @@ public class MINMAXINFO { [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface ISpecifyPropertyPages { - void GetPages( - [Out] + void GetPages( + [Out] NativeMethods.tagCAUUID pPages); } @@ -4110,132 +4246,136 @@ public sealed class tagCAUUID public int cElems = 0; public IntPtr pElems = IntPtr.Zero; } - + [StructLayout(LayoutKind.Sequential)] public struct NMTOOLBAR { - public NMHDR hdr; - public int iItem; + public NMHDR hdr; + public int iItem; public TBBUTTON tbButton; - public int cchText; - public IntPtr pszText; + public int cchText; + public IntPtr pszText; } - + [StructLayout(LayoutKind.Sequential)] - public struct TBBUTTON { - public int iBitmap; - public int idCommand; - public byte fsState; - public byte fsStyle; - public byte bReserved0; - public byte bReserved1; - public IntPtr dwData; - public IntPtr iString; + public struct TBBUTTON + { + public int iBitmap; + public int idCommand; + public byte fsState; + public byte fsStyle; + public byte bReserved0; + public byte bReserved1; + public IntPtr dwData; + public IntPtr iString; } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class TOOLTIPTEXT { - public NMHDR hdr; + public NMHDR hdr; public string lpszText; - - [MarshalAs(UnmanagedType.ByValTStr, SizeConst=80)] + + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string szText = null; - + public IntPtr hinst; - public int uFlags; + public int uFlags; } [StructLayout(LayoutKind.Sequential)] public struct NMTBHOTITEM { - public NMHDR hdr; - public int idOld; - public int idNew; - public int dwFlags; - } - - public const int HICF_OTHER = 0x00000000; - public const int HICF_MOUSE = 0x00000001; // Triggered by mouse - public const int HICF_ARROWKEYS = 0x00000002; // Triggered by arrow keys - public const int HICF_ACCELERATOR = 0x00000004; // Triggered by accelerator - public const int HICF_DUPACCEL = 0x00000008; // This accelerator is not unique - public const int HICF_ENTERING = 0x00000010; // idOld is invalid - public const int HICF_LEAVING = 0x00000020; // idNew is invalid - public const int HICF_RESELECT = 0x00000040; // hot item reselected - public const int HICF_LMOUSE = 0x00000080; // left mouse button selected - public const int HICF_TOGGLEDROPDOWN = 0x00000100; // Toggle button's dropdown state - - // HDN_ITEMCHANGING will send us an HDITEM w/ pszText set to some random pointer. - // Marshal.PtrToStructure chokes when it has to convert a random pointer to a string. - // For HDN_ITEMCHANGING map pszText to an IntPtr - [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)] - public class HDITEM2 - { - public int mask = 0; - public int cxy = 0; - public IntPtr pszText_notUsed = IntPtr.Zero; - public IntPtr hbm = IntPtr.Zero; - public int cchTextMax = 0; - public int fmt = 0; - public IntPtr lParam = IntPtr.Zero; - public int iImage = 0; - public int iOrder = 0; - public int type = 0; - public IntPtr pvFilter = IntPtr.Zero; - } + public NMHDR hdr; + public int idOld; + public int idNew; + public int dwFlags; + } - [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)] - public struct TBBUTTONINFO - { - public int cbSize; - public int dwMask; - public int idCommand; - public int iImage; - public byte fsState; - public byte fsStyle; - public short cx; - public IntPtr lParam; - public IntPtr pszText; - public int cchTest; - } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public class TV_HITTESTINFO { - public int pt_x; - public int pt_y; - public int flags = 0; - public IntPtr hItem = IntPtr.Zero; + public const int HICF_OTHER = 0x00000000; + public const int HICF_MOUSE = 0x00000001; // Triggered by mouse + public const int HICF_ARROWKEYS = 0x00000002; // Triggered by arrow keys + public const int HICF_ACCELERATOR = 0x00000004; // Triggered by accelerator + public const int HICF_DUPACCEL = 0x00000008; // This accelerator is not unique + public const int HICF_ENTERING = 0x00000010; // idOld is invalid + public const int HICF_LEAVING = 0x00000020; // idNew is invalid + public const int HICF_RESELECT = 0x00000040; // hot item reselected + public const int HICF_LMOUSE = 0x00000080; // left mouse button selected + public const int HICF_TOGGLEDROPDOWN = 0x00000100; // Toggle button's dropdown state + + // HDN_ITEMCHANGING will send us an HDITEM w/ pszText set to some random pointer. + // Marshal.PtrToStructure chokes when it has to convert a random pointer to a string. + // For HDN_ITEMCHANGING map pszText to an IntPtr + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class HDITEM2 + { + public int mask = 0; + public int cxy = 0; + public IntPtr pszText_notUsed = IntPtr.Zero; + public IntPtr hbm = IntPtr.Zero; + public int cchTextMax = 0; + public int fmt = 0; + public IntPtr lParam = IntPtr.Zero; + public int iImage = 0; + public int iOrder = 0; + public int type = 0; + public IntPtr pvFilter = IntPtr.Zero; } - + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct TBBUTTONINFO + { + public int cbSize; + public int dwMask; + public int idCommand; + public int iImage; + public byte fsState; + public byte fsStyle; + public short cx; + public IntPtr lParam; + public IntPtr pszText; + public int cchTest; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class TV_HITTESTINFO + { + public int pt_x; + public int pt_y; + public int flags = 0; + public IntPtr hItem = IntPtr.Zero; + } + [StructLayout(LayoutKind.Sequential)] public class NMTVCUSTOMDRAW { - public NMCUSTOMDRAW nmcd; + public NMCUSTOMDRAW nmcd; public int clrText; public int clrTextBk; public int iLevel = 0; } - + [StructLayout(LayoutKind.Sequential)] - public struct NMCUSTOMDRAW { - public NMHDR nmcd; - public int dwDrawStage; - public IntPtr hdc; - public RECT rc; - public IntPtr dwItemSpec; - public int uItemState; - public IntPtr lItemlParam; + public struct NMCUSTOMDRAW + { + public NMHDR nmcd; + public int dwDrawStage; + public IntPtr hdc; + public RECT rc; + public IntPtr dwItemSpec; + public int uItemState; + public IntPtr lItemlParam; } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public class MCHITTESTINFO { - public int cbSize = Marshal.SizeOf(); - public int pt_x = 0; - public int pt_y = 0; - public int uHit = 0; + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class MCHITTESTINFO + { + public int cbSize = Marshal.SizeOf(); + public int pt_x = 0; + public int pt_y = 0; + public int uHit = 0; public short st_wYear = 0; public short st_wMonth = 0; public short st_wDayOfWeek = 0; @@ -4245,22 +4385,22 @@ public class MCHITTESTINFO { public short st_wSecond = 0; public short st_wMilliseconds = 0; } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class NMSELCHANGE { - public NMHDR nmhdr; - public SYSTEMTIME stSelStart = null; - public SYSTEMTIME stSelEnd = null; + public NMHDR nmhdr; + public SYSTEMTIME stSelStart = null; + public SYSTEMTIME stSelEnd = null; } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class NMDAYSTATE { - public NMHDR nmhdr; - public SYSTEMTIME stStart = null; - public int cDayState = 0; - public IntPtr prgDayState; + public NMHDR nmhdr; + public SYSTEMTIME stStart = null; + public int cDayState = 0; + public IntPtr prgDayState; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] @@ -4274,7 +4414,7 @@ public class NMVIEWCHANGE [StructLayout(LayoutKind.Sequential)] public struct NMLVCUSTOMDRAW { - public NMCUSTOMDRAW nmcd; + public NMCUSTOMDRAW nmcd; public int clrText; public int clrTextBk; public int iSubItem; @@ -4290,18 +4430,18 @@ public struct NMLVCUSTOMDRAW public uint uAlign; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class NMLVGETINFOTIP { - public NMHDR nmhdr; - public int flags = 0; - public IntPtr lpszText = IntPtr.Zero; - public int cchTextMax = 0; - public int item = 0; - public int subItem = 0; - public IntPtr lParam = IntPtr.Zero; + public NMHDR nmhdr; + public int flags = 0; + public IntPtr lpszText = IntPtr.Zero; + public int cchTextMax = 0; + public int item = 0; + public int subItem = 0; + public IntPtr lParam = IntPtr.Zero; } - + [StructLayout(LayoutKind.Sequential)] public class NMLVKEYDOWN { @@ -4309,17 +4449,18 @@ public class NMLVKEYDOWN public short wVKey = 0; public uint flags = 0; } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public class LVHITTESTINFO { - public int pt_x; - public int pt_y; - public int flags = 0; - public int iItem = 0; - public int iSubItem = 0; + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class LVHITTESTINFO + { + public int pt_x; + public int pt_y; + public int flags = 0; + public int iItem = 0; + public int iSubItem = 0; } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class LVBKIMAGE { public int ulFlags; @@ -4330,46 +4471,49 @@ public class LVBKIMAGE public int yOffset; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class LVCOLUMN_T { - public int mask = 0; - public int fmt = 0; - public int cx = 0; - public string pszText = null; - public int cchTextMax = 0; - public int iSubItem = 0; - public int iImage = 0; - public int iOrder = 0; + public int mask = 0; + public int fmt = 0; + public int cx = 0; + public string pszText = null; + public int cchTextMax = 0; + public int iSubItem = 0; + public int iImage = 0; + public int iOrder = 0; } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public struct LVFINDINFO { - public int flags; - public string psz; - public IntPtr lParam; - public int ptX; // was POINT pt - public int ptY; - public int vkDirection; + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct LVFINDINFO + { + public int flags; + public string psz; + public IntPtr lParam; + public int ptX; // was POINT pt + public int ptY; + public int vkDirection; } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public struct LVITEM { - public int mask; - public int iItem; - public int iSubItem; - public int state; - public int stateMask; - public string pszText; - public int cchTextMax; - public int iImage; - public IntPtr lParam; - public int iIndent; - public int iGroupId; - public int cColumns; // tile view columns - public IntPtr puColumns; - - public unsafe void Reset() { + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct LVITEM + { + public int mask; + public int iItem; + public int iSubItem; + public int state; + public int stateMask; + public string pszText; + public int cchTextMax; + public int iImage; + public IntPtr lParam; + public int iIndent; + public int iGroupId; + public int cColumns; // tile view columns + public IntPtr puColumns; + + public unsafe void Reset() + { pszText = null; mask = 0; iItem = 0; @@ -4385,44 +4529,48 @@ public unsafe void Reset() { puColumns = IntPtr.Zero; } - public override string ToString() { + public override string ToString() + { return "LVITEM: pszText = " + pszText - + ", iItem = " + iItem.ToString(CultureInfo.InvariantCulture) + + ", iItem = " + iItem.ToString(CultureInfo.InvariantCulture) + ", iSubItem = " + iSubItem.ToString(CultureInfo.InvariantCulture) + ", state = " + state.ToString(CultureInfo.InvariantCulture) + ", iGroupId = " + iGroupId.ToString(CultureInfo.InvariantCulture) + ", cColumns = " + cColumns.ToString(CultureInfo.InvariantCulture); } } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public struct LVITEM_NOTEXT { - public int mask; - public int iItem; - public int iSubItem; - public int state; - public int stateMask; + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct LVITEM_NOTEXT + { + public int mask; + public int iItem; + public int iSubItem; + public int state; + public int stateMask; public IntPtr /*string*/ pszText; - public int cchTextMax; - public int iImage; - public IntPtr lParam; - public int iIndent; + public int cchTextMax; + public int iImage; + public IntPtr lParam; + public int iIndent; } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public class LVCOLUMN { - public int mask; - public int fmt; - public int cx = 0; + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class LVCOLUMN + { + public int mask; + public int fmt; + public int cx = 0; public IntPtr /* LPWSTR */ pszText; - public int cchTextMax = 0; - public int iSubItem = 0; - public int iImage; - public int iOrder = 0; + public int cchTextMax = 0; + public int iSubItem = 0; + public int iImage; + public int iOrder = 0; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] - public class LVGROUP { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public class LVGROUP + { public uint cbSize = (uint)Marshal.SizeOf(); public uint mask; public IntPtr pszHeader; @@ -4432,23 +4580,26 @@ public class LVGROUP { public int iGroupId; public uint stateMask = 0; public uint state = 0; - public uint uAlign; + public uint uAlign; - public override string ToString() { + public override string ToString() + { return "LVGROUP: header = " + pszHeader.ToString() + ", iGroupId = " + iGroupId.ToString(CultureInfo.InvariantCulture); } } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public class LVINSERTMARK { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class LVINSERTMARK + { public uint cbSize = (uint)Marshal.SizeOf(); public int dwFlags; public int iItem; public int dwReserved = 0; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public class LVTILEVIEWINFO { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class LVTILEVIEWINFO + { public uint cbSize = (uint)Marshal.SizeOf(); public int dwMask; public int dwFlags; @@ -4456,66 +4607,72 @@ public class LVTILEVIEWINFO { public int cLines; public RECT rcLabelMargin; } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public class NMLVCACHEHINT { + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class NMLVCACHEHINT + { public NMHDR hdr; public int iFrom = 0; public int iTo = 0; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class NMLVDISPINFO { - public NMHDR hdr; + public NMHDR hdr; public LVITEM item; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class NMLVDISPINFO_NOTEXT { - public NMHDR hdr; + public NMHDR hdr; public LVITEM_NOTEXT item; } [StructLayout(LayoutKind.Sequential)] - public class NMLVODSTATECHANGE { - public NMHDR hdr; - public int iFrom = 0; - public int iTo = 0; - public int uNewState = 0; - public int uOldState = 0; - } - + public class NMLVODSTATECHANGE + { + public NMHDR hdr; + public int iFrom = 0; + public int iTo = 0; + public int uNewState = 0; + public int uOldState = 0; + } + [StructLayout(LayoutKind.Sequential)] - public class CLIENTCREATESTRUCT { + public class CLIENTCREATESTRUCT + { public IntPtr hWindowMenu; public int idFirstChild; - - public CLIENTCREATESTRUCT(IntPtr hmenu, int idFirst) { + + public CLIENTCREATESTRUCT(IntPtr hmenu, int idFirst) + { hWindowMenu = hmenu; idFirstChild = idFirst; } } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class NMDATETIMECHANGE { - public NMHDR nmhdr; - public int dwFlags = 0; - public SYSTEMTIME st = null; + public NMHDR nmhdr; + public int dwFlags = 0; + public SYSTEMTIME st = null; } - + [StructLayout(LayoutKind.Sequential)] - public class COPYDATASTRUCT { + public class COPYDATASTRUCT + { public int dwData = 0; public int cbData = 0; public IntPtr lpData = IntPtr.Zero; } [StructLayout(LayoutKind.Sequential)] - public class NMHEADER { + public class NMHEADER + { public NMHDR nmhdr; public int iItem = 0; public int iButton = 0; @@ -4524,13 +4681,14 @@ public class NMHEADER { [SuppressMessage("Microsoft.Design", "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable")] [StructLayout(LayoutKind.Sequential)] - public class MOUSEHOOKSTRUCT { + public class MOUSEHOOKSTRUCT + { // pt was a by-value POINT structure - public int pt_x = 0; - public int pt_y = 0; - public IntPtr hWnd = IntPtr.Zero; - public int wHitTestCode = 0; - public int dwExtraInfo = 0; + public int pt_x = 0; + public int pt_y = 0; + public IntPtr hWnd = IntPtr.Zero; + public int wHitTestCode = 0; + public int dwExtraInfo = 0; } #region SendKeys SendInput functionality @@ -4589,70 +4747,70 @@ public struct INPUTUNION [StructLayout(LayoutKind.Sequential)] public class CHARRANGE { - public int cpMin; - public int cpMax; + public int cpMin; + public int cpMax; } - - [StructLayout(LayoutKind.Sequential, Pack=4)] + + [StructLayout(LayoutKind.Sequential, Pack = 4)] public class CHARFORMATW { - public int cbSize = Marshal.SizeOf(); - public int dwMask; - public int dwEffects; - public int yHeight; - public int yOffset = 0; - public int crTextColor = 0; - public byte bCharSet; - public byte bPitchAndFamily; - [MarshalAs(UnmanagedType.ByValArray, SizeConst=64)] - public byte[] szFaceName = new byte[64]; + public int cbSize = Marshal.SizeOf(); + public int dwMask; + public int dwEffects; + public int yHeight; + public int yOffset = 0; + public int crTextColor = 0; + public byte bCharSet; + public byte bPitchAndFamily; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)] + public byte[] szFaceName = new byte[64]; } - - [StructLayout(LayoutKind.Sequential, Pack=4)] + + [StructLayout(LayoutKind.Sequential, Pack = 4)] public class CHARFORMATA { - public int cbSize = Marshal.SizeOf(); - public int dwMask; - public int dwEffects; - public int yHeight; - public int yOffset; - public int crTextColor; - public byte bCharSet; - public byte bPitchAndFamily; - [MarshalAs(UnmanagedType.ByValArray, SizeConst=32)] - public byte[] szFaceName = new byte[32]; + public int cbSize = Marshal.SizeOf(); + public int dwMask; + public int dwEffects; + public int yHeight; + public int yOffset; + public int crTextColor; + public byte bCharSet; + public byte bPitchAndFamily; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] + public byte[] szFaceName = new byte[32]; } - - [StructLayout(LayoutKind.Sequential, Pack=4)] + + [StructLayout(LayoutKind.Sequential, Pack = 4)] public class CHARFORMAT2A { - public int cbSize = Marshal.SizeOf(); - public int dwMask = 0; - public int dwEffects = 0; - public int yHeight = 0; - public int yOffset = 0; - public int crTextColor = 0; - public byte bCharSet = 0; - public byte bPitchAndFamily = 0; - [MarshalAs(UnmanagedType.ByValArray, SizeConst=32)] - public byte[] szFaceName = new byte[32]; - public short wWeight = 0; - public short sSpacing = 0; - public int crBackColor = 0; - public int lcid = 0; - public int dwReserved = 0; - public short sStyle = 0; - public short wKerning = 0; - public byte bUnderlineType = 0; - public byte bAnimation = 0; - public byte bRevAuthor = 0; + public int cbSize = Marshal.SizeOf(); + public int dwMask = 0; + public int dwEffects = 0; + public int yHeight = 0; + public int yOffset = 0; + public int crTextColor = 0; + public byte bCharSet = 0; + public byte bPitchAndFamily = 0; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] + public byte[] szFaceName = new byte[32]; + public short wWeight = 0; + public short sSpacing = 0; + public int crBackColor = 0; + public int lcid = 0; + public int dwReserved = 0; + public short sStyle = 0; + public short wKerning = 0; + public byte bUnderlineType = 0; + public byte bAnimation = 0; + public byte bRevAuthor = 0; } - + [StructLayout(LayoutKind.Sequential)] public class TEXTRANGE { - public CHARRANGE chrg; - public IntPtr lpstrText; /* allocated by caller, zero terminated by RichEdit */ + public CHARRANGE chrg; + public IntPtr lpstrText; /* allocated by caller, zero terminated by RichEdit */ } [StructLayout(LayoutKind.Sequential)] @@ -4661,46 +4819,47 @@ public class GETTEXTLENGTHEX public uint flags; // Flags (see GTL_XXX defines) public uint codepage; // Code page for translation (CP_ACP for default, 1200 for Unicode) } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=4)] - public class SELCHANGE { + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 4)] + public class SELCHANGE + { public NMHDR nmhdr; public CHARRANGE chrg = null; public int seltyp = 0; } - + [StructLayout(LayoutKind.Sequential)] public class PARAFORMAT { - public int cbSize = Marshal.SizeOf(); - public int dwMask; - public short wNumbering; - public short wReserved = 0; - public int dxStartIndent; - public int dxRightIndent; - public int dxOffset; - public short wAlignment; - public short cTabCount; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst=32)] - public int[] rgxTabs; - } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] + public int cbSize = Marshal.SizeOf(); + public int dwMask; + public short wNumbering; + public short wReserved = 0; + public int dxStartIndent; + public int dxRightIndent; + public int dxOffset; + public short wAlignment; + public short cTabCount; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] + public int[] rgxTabs; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class FINDTEXT { - public CHARRANGE chrg; - public string lpstrText; + public CHARRANGE chrg; + public string lpstrText; } - + [SuppressMessage("Microsoft.Design", "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable")] [StructLayout(LayoutKind.Sequential)] public class ENLINK { - public NMHDR nmhdr; - public int msg = 0; - public IntPtr wParam = IntPtr.Zero; - public IntPtr lParam = IntPtr.Zero; + public NMHDR nmhdr; + public int msg = 0; + public IntPtr wParam = IntPtr.Zero; + public IntPtr lParam = IntPtr.Zero; public CHARRANGE charrange = null; } @@ -4808,245 +4967,260 @@ public enum OLECMDF [StructLayout(LayoutKind.Sequential)] public class ENDROPFILES { - public NMHDR nmhdr; - public IntPtr hDrop = IntPtr.Zero; - public int cp = 0; - public bool fProtected = false; + public NMHDR nmhdr; + public IntPtr hDrop = IntPtr.Zero; + public int cp = 0; + public bool fProtected = false; } - + [StructLayout(LayoutKind.Sequential)] public class REQRESIZE { - public NMHDR nmhdr; - public RECT rc; + public NMHDR nmhdr; + public RECT rc; } - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class ENPROTECTED { - public NMHDR nmhdr; - public int msg; - public IntPtr wParam; - public IntPtr lParam; + public NMHDR nmhdr; + public int msg; + public IntPtr wParam; + public IntPtr lParam; public CHARRANGE chrg; } [StructLayout(LayoutKind.Sequential)] - public class ENPROTECTED64 + public class ENPROTECTED64 { - [MarshalAs(UnmanagedType.ByValArray, SizeConst=56)] + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 56)] public byte[] contents = new byte[56]; } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] public class ActiveX { - public const int OCM__BASE = 0x2000; - public const int DISPID_VALUE = unchecked((int)0x0); - public const int DISPID_UNKNOWN = unchecked((int)0xFFFFFFFF); - public const int DISPID_AUTOSIZE = unchecked((int)0xFFFFFE0C); - public const int DISPID_BACKCOLOR = unchecked((int)0xFFFFFE0B); - public const int DISPID_BACKSTYLE = unchecked((int)0xFFFFFE0A); - public const int DISPID_BORDERCOLOR = unchecked((int)0xFFFFFE09); - public const int DISPID_BORDERSTYLE = unchecked((int)0xFFFFFE08); - public const int DISPID_BORDERWIDTH = unchecked((int)0xFFFFFE07); - public const int DISPID_DRAWMODE = unchecked((int)0xFFFFFE05); - public const int DISPID_DRAWSTYLE = unchecked((int)0xFFFFFE04); - public const int DISPID_DRAWWIDTH = unchecked((int)0xFFFFFE03); - public const int DISPID_FILLCOLOR = unchecked((int)0xFFFFFE02); - public const int DISPID_FILLSTYLE = unchecked((int)0xFFFFFE01); - public const int DISPID_FONT = unchecked((int)0xFFFFFE00); - public const int DISPID_FORECOLOR = unchecked((int)0xFFFFFDFF); - public const int DISPID_ENABLED = unchecked((int)0xFFFFFDFE); - public const int DISPID_HWND = unchecked((int)0xFFFFFDFD); - public const int DISPID_TABSTOP = unchecked((int)0xFFFFFDFC); - public const int DISPID_TEXT = unchecked((int)0xFFFFFDFB); - public const int DISPID_CAPTION = unchecked((int)0xFFFFFDFA); - public const int DISPID_BORDERVISIBLE = unchecked((int)0xFFFFFDF9); - public const int DISPID_APPEARANCE = unchecked((int)0xFFFFFDF8); - public const int DISPID_MOUSEPOINTER = unchecked((int)0xFFFFFDF7); - public const int DISPID_MOUSEICON = unchecked((int)0xFFFFFDF6); - public const int DISPID_PICTURE = unchecked((int)0xFFFFFDF5); - public const int DISPID_VALID = unchecked((int)0xFFFFFDF4); - public const int DISPID_READYSTATE = unchecked((int)0xFFFFFDF3); - public const int DISPID_REFRESH = unchecked((int)0xFFFFFDDA); - public const int DISPID_DOCLICK = unchecked((int)0xFFFFFDD9); - public const int DISPID_ABOUTBOX = unchecked((int)0xFFFFFDD8); - public const int DISPID_CLICK = unchecked((int)0xFFFFFDA8); - public const int DISPID_DBLCLICK = unchecked((int)0xFFFFFDA7); - public const int DISPID_KEYDOWN = unchecked((int)0xFFFFFDA6); - public const int DISPID_KEYPRESS = unchecked((int)0xFFFFFDA5); - public const int DISPID_KEYUP = unchecked((int)0xFFFFFDA4); - public const int DISPID_MOUSEDOWN = unchecked((int)0xFFFFFDA3); - public const int DISPID_MOUSEMOVE = unchecked((int)0xFFFFFDA2); - public const int DISPID_MOUSEUP = unchecked((int)0xFFFFFDA1); - public const int DISPID_ERROREVENT = unchecked((int)0xFFFFFDA0); - public const int DISPID_RIGHTTOLEFT = unchecked((int)0xFFFFFD9D); - public const int DISPID_READYSTATECHANGE = unchecked((int)0xFFFFFD9F); - public const int DISPID_AMBIENT_BACKCOLOR = unchecked((int)0xFFFFFD43); - public const int DISPID_AMBIENT_DISPLAYNAME = unchecked((int)0xFFFFFD42); - public const int DISPID_AMBIENT_FONT = unchecked((int)0xFFFFFD41); - public const int DISPID_AMBIENT_FORECOLOR = unchecked((int)0xFFFFFD40); - public const int DISPID_AMBIENT_LOCALEID = unchecked((int)0xFFFFFD3F); - public const int DISPID_AMBIENT_MESSAGEREFLECT = unchecked((int)0xFFFFFD3E); - public const int DISPID_AMBIENT_SCALEUNITS = unchecked((int)0xFFFFFD3D); - public const int DISPID_AMBIENT_TEXTALIGN = unchecked((int)0xFFFFFD3C); - public const int DISPID_AMBIENT_USERMODE = unchecked((int)0xFFFFFD3B); - public const int DISPID_AMBIENT_UIDEAD = unchecked((int)0xFFFFFD3A); - public const int DISPID_AMBIENT_SHOWGRABHANDLES = unchecked((int)0xFFFFFD39); - public const int DISPID_AMBIENT_SHOWHATCHING = unchecked((int)0xFFFFFD38); - public const int DISPID_AMBIENT_DISPLAYASDEFAULT = unchecked((int)0xFFFFFD37); - public const int DISPID_AMBIENT_SUPPORTSMNEMONICS = unchecked((int)0xFFFFFD36); - public const int DISPID_AMBIENT_AUTOCLIP = unchecked((int)0xFFFFFD35); - public const int DISPID_AMBIENT_APPEARANCE = unchecked((int)0xFFFFFD34); - public const int DISPID_AMBIENT_PALETTE = unchecked((int)0xFFFFFD2A); - public const int DISPID_AMBIENT_TRANSFERPRIORITY = unchecked((int)0xFFFFFD28); - public const int DISPID_AMBIENT_RIGHTTOLEFT = unchecked((int)0xFFFFFD24); - public const int DISPID_Name = unchecked((int)0xFFFFFCE0); - public const int DISPID_Delete = unchecked((int)0xFFFFFCDF); - public const int DISPID_Object = unchecked((int)0xFFFFFCDE); - public const int DISPID_Parent = unchecked((int)0xFFFFFCDD); - public const int DVASPECT_CONTENT = 0x1; - public const int DVASPECT_THUMBNAIL = 0x2; - public const int DVASPECT_ICON = 0x4; - public const int DVASPECT_DOCPRINT = 0x8; - public const int OLEMISC_RECOMPOSEONRESIZE = 0x1; - public const int OLEMISC_ONLYICONIC = 0x2; - public const int OLEMISC_INSERTNOTREPLACE = 0x4; - public const int OLEMISC_STATIC = 0x8; - public const int OLEMISC_CANTLINKINSIDE = 0x10; - public const int OLEMISC_CANLINKBYOLE1 = 0x20; - public const int OLEMISC_ISLINKOBJECT = 0x40; - public const int OLEMISC_INSIDEOUT = 0x80; - public const int OLEMISC_ACTIVATEWHENVISIBLE = 0x100; - public const int OLEMISC_RENDERINGISDEVICEINDEPENDENT = 0x200; - public const int OLEMISC_INVISIBLEATRUNTIME = 0x400; - public const int OLEMISC_ALWAYSRUN = 0x800; - public const int OLEMISC_ACTSLIKEBUTTON = 0x1000; - public const int OLEMISC_ACTSLIKELABEL = 0x2000; - public const int OLEMISC_NOUIACTIVATE = 0x4000; - public const int OLEMISC_ALIGNABLE = 0x8000; - public const int OLEMISC_SIMPLEFRAME = 0x10000; - public const int OLEMISC_SETCLIENTSITEFIRST = 0x20000; - public const int OLEMISC_IMEMODE = 0x40000; - public const int OLEMISC_IGNOREACTIVATEWHENVISIBLE = 0x80000; - public const int OLEMISC_WANTSTOMENUMERGE = 0x100000; - public const int OLEMISC_SUPPORTSMULTILEVELUNDO = 0x200000; - public const int QACONTAINER_SHOWHATCHING = 0x1; - public const int QACONTAINER_SHOWGRABHANDLES = 0x2; - public const int QACONTAINER_USERMODE = 0x4; - public const int QACONTAINER_DISPLAYASDEFAULT = 0x8; - public const int QACONTAINER_UIDEAD = 0x10; - public const int QACONTAINER_AUTOCLIP = 0x20; - public const int QACONTAINER_MESSAGEREFLECT = 0x40; - public const int QACONTAINER_SUPPORTSMNEMONICS = 0x80; - public const int XFORMCOORDS_POSITION = 0x1; - public const int XFORMCOORDS_SIZE = 0x2; - public const int XFORMCOORDS_HIMETRICTOCONTAINER = 0x4; - public const int XFORMCOORDS_CONTAINERTOHIMETRIC = 0x8; - public const int PROPCAT_Nil = unchecked((int)0xFFFFFFFF); - public const int PROPCAT_Misc = unchecked((int)0xFFFFFFFE); - public const int PROPCAT_Font = unchecked((int)0xFFFFFFFD); - public const int PROPCAT_Position = unchecked((int)0xFFFFFFFC); - public const int PROPCAT_Appearance = unchecked((int)0xFFFFFFFB); - public const int PROPCAT_Behavior = unchecked((int)0xFFFFFFFA); - public const int PROPCAT_Data = unchecked((int)0xFFFFFFF9); - public const int PROPCAT_List = unchecked((int)0xFFFFFFF8); - public const int PROPCAT_Text = unchecked((int)0xFFFFFFF7); - public const int PROPCAT_Scale = unchecked((int)0xFFFFFFF6); - public const int PROPCAT_DDE = unchecked((int)0xFFFFFFF5); - public const int GC_WCH_SIBLING = 0x1; - public const int GC_WCH_CONTAINER = 0x2; - public const int GC_WCH_CONTAINED = 0x3; - public const int GC_WCH_ALL = 0x4; - public const int GC_WCH_FREVERSEDIR = 0x8000000; - public const int GC_WCH_FONLYNEXT = 0x10000000; - public const int GC_WCH_FONLYPREV = 0x20000000; - public const int GC_WCH_FSELECTED = 0x40000000; - public const int OLECONTF_EMBEDDINGS = 0x1; - public const int OLECONTF_LINKS = 0x2; - public const int OLECONTF_OTHERS = 0x4; - public const int OLECONTF_ONLYUSER = 0x8; - public const int OLECONTF_ONLYIFRUNNING = 0x10; - public const int ALIGN_MIN = 0x0; - public const int ALIGN_NO_CHANGE = 0x0; - public const int ALIGN_TOP = 0x1; - public const int ALIGN_BOTTOM = 0x2; - public const int ALIGN_LEFT = 0x3; - public const int ALIGN_RIGHT = 0x4; - public const int ALIGN_MAX = 0x4; - public const int OLEVERBATTRIB_NEVERDIRTIES = 0x1; - public const int OLEVERBATTRIB_ONCONTAINERMENU = 0x2; - + public const int OCM__BASE = 0x2000; + public const int DISPID_VALUE = unchecked((int)0x0); + public const int DISPID_UNKNOWN = unchecked((int)0xFFFFFFFF); + public const int DISPID_AUTOSIZE = unchecked((int)0xFFFFFE0C); + public const int DISPID_BACKCOLOR = unchecked((int)0xFFFFFE0B); + public const int DISPID_BACKSTYLE = unchecked((int)0xFFFFFE0A); + public const int DISPID_BORDERCOLOR = unchecked((int)0xFFFFFE09); + public const int DISPID_BORDERSTYLE = unchecked((int)0xFFFFFE08); + public const int DISPID_BORDERWIDTH = unchecked((int)0xFFFFFE07); + public const int DISPID_DRAWMODE = unchecked((int)0xFFFFFE05); + public const int DISPID_DRAWSTYLE = unchecked((int)0xFFFFFE04); + public const int DISPID_DRAWWIDTH = unchecked((int)0xFFFFFE03); + public const int DISPID_FILLCOLOR = unchecked((int)0xFFFFFE02); + public const int DISPID_FILLSTYLE = unchecked((int)0xFFFFFE01); + public const int DISPID_FONT = unchecked((int)0xFFFFFE00); + public const int DISPID_FORECOLOR = unchecked((int)0xFFFFFDFF); + public const int DISPID_ENABLED = unchecked((int)0xFFFFFDFE); + public const int DISPID_HWND = unchecked((int)0xFFFFFDFD); + public const int DISPID_TABSTOP = unchecked((int)0xFFFFFDFC); + public const int DISPID_TEXT = unchecked((int)0xFFFFFDFB); + public const int DISPID_CAPTION = unchecked((int)0xFFFFFDFA); + public const int DISPID_BORDERVISIBLE = unchecked((int)0xFFFFFDF9); + public const int DISPID_APPEARANCE = unchecked((int)0xFFFFFDF8); + public const int DISPID_MOUSEPOINTER = unchecked((int)0xFFFFFDF7); + public const int DISPID_MOUSEICON = unchecked((int)0xFFFFFDF6); + public const int DISPID_PICTURE = unchecked((int)0xFFFFFDF5); + public const int DISPID_VALID = unchecked((int)0xFFFFFDF4); + public const int DISPID_READYSTATE = unchecked((int)0xFFFFFDF3); + public const int DISPID_REFRESH = unchecked((int)0xFFFFFDDA); + public const int DISPID_DOCLICK = unchecked((int)0xFFFFFDD9); + public const int DISPID_ABOUTBOX = unchecked((int)0xFFFFFDD8); + public const int DISPID_CLICK = unchecked((int)0xFFFFFDA8); + public const int DISPID_DBLCLICK = unchecked((int)0xFFFFFDA7); + public const int DISPID_KEYDOWN = unchecked((int)0xFFFFFDA6); + public const int DISPID_KEYPRESS = unchecked((int)0xFFFFFDA5); + public const int DISPID_KEYUP = unchecked((int)0xFFFFFDA4); + public const int DISPID_MOUSEDOWN = unchecked((int)0xFFFFFDA3); + public const int DISPID_MOUSEMOVE = unchecked((int)0xFFFFFDA2); + public const int DISPID_MOUSEUP = unchecked((int)0xFFFFFDA1); + public const int DISPID_ERROREVENT = unchecked((int)0xFFFFFDA0); + public const int DISPID_RIGHTTOLEFT = unchecked((int)0xFFFFFD9D); + public const int DISPID_READYSTATECHANGE = unchecked((int)0xFFFFFD9F); + public const int DISPID_AMBIENT_BACKCOLOR = unchecked((int)0xFFFFFD43); + public const int DISPID_AMBIENT_DISPLAYNAME = unchecked((int)0xFFFFFD42); + public const int DISPID_AMBIENT_FONT = unchecked((int)0xFFFFFD41); + public const int DISPID_AMBIENT_FORECOLOR = unchecked((int)0xFFFFFD40); + public const int DISPID_AMBIENT_LOCALEID = unchecked((int)0xFFFFFD3F); + public const int DISPID_AMBIENT_MESSAGEREFLECT = unchecked((int)0xFFFFFD3E); + public const int DISPID_AMBIENT_SCALEUNITS = unchecked((int)0xFFFFFD3D); + public const int DISPID_AMBIENT_TEXTALIGN = unchecked((int)0xFFFFFD3C); + public const int DISPID_AMBIENT_USERMODE = unchecked((int)0xFFFFFD3B); + public const int DISPID_AMBIENT_UIDEAD = unchecked((int)0xFFFFFD3A); + public const int DISPID_AMBIENT_SHOWGRABHANDLES = unchecked((int)0xFFFFFD39); + public const int DISPID_AMBIENT_SHOWHATCHING = unchecked((int)0xFFFFFD38); + public const int DISPID_AMBIENT_DISPLAYASDEFAULT = unchecked((int)0xFFFFFD37); + public const int DISPID_AMBIENT_SUPPORTSMNEMONICS = unchecked((int)0xFFFFFD36); + public const int DISPID_AMBIENT_AUTOCLIP = unchecked((int)0xFFFFFD35); + public const int DISPID_AMBIENT_APPEARANCE = unchecked((int)0xFFFFFD34); + public const int DISPID_AMBIENT_PALETTE = unchecked((int)0xFFFFFD2A); + public const int DISPID_AMBIENT_TRANSFERPRIORITY = unchecked((int)0xFFFFFD28); + public const int DISPID_AMBIENT_RIGHTTOLEFT = unchecked((int)0xFFFFFD24); + public const int DISPID_Name = unchecked((int)0xFFFFFCE0); + public const int DISPID_Delete = unchecked((int)0xFFFFFCDF); + public const int DISPID_Object = unchecked((int)0xFFFFFCDE); + public const int DISPID_Parent = unchecked((int)0xFFFFFCDD); + public const int DVASPECT_CONTENT = 0x1; + public const int DVASPECT_THUMBNAIL = 0x2; + public const int DVASPECT_ICON = 0x4; + public const int DVASPECT_DOCPRINT = 0x8; + public const int OLEMISC_RECOMPOSEONRESIZE = 0x1; + public const int OLEMISC_ONLYICONIC = 0x2; + public const int OLEMISC_INSERTNOTREPLACE = 0x4; + public const int OLEMISC_STATIC = 0x8; + public const int OLEMISC_CANTLINKINSIDE = 0x10; + public const int OLEMISC_CANLINKBYOLE1 = 0x20; + public const int OLEMISC_ISLINKOBJECT = 0x40; + public const int OLEMISC_INSIDEOUT = 0x80; + public const int OLEMISC_ACTIVATEWHENVISIBLE = 0x100; + public const int OLEMISC_RENDERINGISDEVICEINDEPENDENT = 0x200; + public const int OLEMISC_INVISIBLEATRUNTIME = 0x400; + public const int OLEMISC_ALWAYSRUN = 0x800; + public const int OLEMISC_ACTSLIKEBUTTON = 0x1000; + public const int OLEMISC_ACTSLIKELABEL = 0x2000; + public const int OLEMISC_NOUIACTIVATE = 0x4000; + public const int OLEMISC_ALIGNABLE = 0x8000; + public const int OLEMISC_SIMPLEFRAME = 0x10000; + public const int OLEMISC_SETCLIENTSITEFIRST = 0x20000; + public const int OLEMISC_IMEMODE = 0x40000; + public const int OLEMISC_IGNOREACTIVATEWHENVISIBLE = 0x80000; + public const int OLEMISC_WANTSTOMENUMERGE = 0x100000; + public const int OLEMISC_SUPPORTSMULTILEVELUNDO = 0x200000; + public const int QACONTAINER_SHOWHATCHING = 0x1; + public const int QACONTAINER_SHOWGRABHANDLES = 0x2; + public const int QACONTAINER_USERMODE = 0x4; + public const int QACONTAINER_DISPLAYASDEFAULT = 0x8; + public const int QACONTAINER_UIDEAD = 0x10; + public const int QACONTAINER_AUTOCLIP = 0x20; + public const int QACONTAINER_MESSAGEREFLECT = 0x40; + public const int QACONTAINER_SUPPORTSMNEMONICS = 0x80; + public const int XFORMCOORDS_POSITION = 0x1; + public const int XFORMCOORDS_SIZE = 0x2; + public const int XFORMCOORDS_HIMETRICTOCONTAINER = 0x4; + public const int XFORMCOORDS_CONTAINERTOHIMETRIC = 0x8; + public const int PROPCAT_Nil = unchecked((int)0xFFFFFFFF); + public const int PROPCAT_Misc = unchecked((int)0xFFFFFFFE); + public const int PROPCAT_Font = unchecked((int)0xFFFFFFFD); + public const int PROPCAT_Position = unchecked((int)0xFFFFFFFC); + public const int PROPCAT_Appearance = unchecked((int)0xFFFFFFFB); + public const int PROPCAT_Behavior = unchecked((int)0xFFFFFFFA); + public const int PROPCAT_Data = unchecked((int)0xFFFFFFF9); + public const int PROPCAT_List = unchecked((int)0xFFFFFFF8); + public const int PROPCAT_Text = unchecked((int)0xFFFFFFF7); + public const int PROPCAT_Scale = unchecked((int)0xFFFFFFF6); + public const int PROPCAT_DDE = unchecked((int)0xFFFFFFF5); + public const int GC_WCH_SIBLING = 0x1; + public const int GC_WCH_CONTAINER = 0x2; + public const int GC_WCH_CONTAINED = 0x3; + public const int GC_WCH_ALL = 0x4; + public const int GC_WCH_FREVERSEDIR = 0x8000000; + public const int GC_WCH_FONLYNEXT = 0x10000000; + public const int GC_WCH_FONLYPREV = 0x20000000; + public const int GC_WCH_FSELECTED = 0x40000000; + public const int OLECONTF_EMBEDDINGS = 0x1; + public const int OLECONTF_LINKS = 0x2; + public const int OLECONTF_OTHERS = 0x4; + public const int OLECONTF_ONLYUSER = 0x8; + public const int OLECONTF_ONLYIFRUNNING = 0x10; + public const int ALIGN_MIN = 0x0; + public const int ALIGN_NO_CHANGE = 0x0; + public const int ALIGN_TOP = 0x1; + public const int ALIGN_BOTTOM = 0x2; + public const int ALIGN_LEFT = 0x3; + public const int ALIGN_RIGHT = 0x4; + public const int ALIGN_MAX = 0x4; + public const int OLEVERBATTRIB_NEVERDIRTIES = 0x1; + public const int OLEVERBATTRIB_ONCONTAINERMENU = 0x2; + public static Guid IID_IUnknown = new Guid("{00000000-0000-0000-C000-000000000046}"); private ActiveX() { } } - - public static class Util { - public static int MAKELONG(int low, int high) { + + public static class Util + { + public static int MAKELONG(int low, int high) + { return (high << 16) | (low & 0xffff); } - - public static IntPtr MAKELPARAM(int low, int high) { - return (IntPtr) ((high << 16) | (low & 0xffff)); + + public static IntPtr MAKELPARAM(int low, int high) + { + return (IntPtr)((high << 16) | (low & 0xffff)); } - - public static int HIWORD(int n) { + + public static int HIWORD(int n) + { return (n >> 16) & 0xffff; } - - public static int HIWORD(IntPtr n) { - return HIWORD( unchecked((int)(long)n) ); + + public static int HIWORD(IntPtr n) + { + return HIWORD(unchecked((int)(long)n)); } - - public static int LOWORD(int n) { + + public static int LOWORD(int n) + { return n & 0xffff; } - - public static int LOWORD(IntPtr n) { - return LOWORD( unchecked((int)(long)n) ); + + public static int LOWORD(IntPtr n) + { + return LOWORD(unchecked((int)(long)n)); } - - public static int SignedHIWORD(IntPtr n) { - return SignedHIWORD( unchecked((int)(long)n) ); + + public static int SignedHIWORD(IntPtr n) + { + return SignedHIWORD(unchecked((int)(long)n)); } - public static int SignedLOWORD(IntPtr n) { - return SignedLOWORD( unchecked((int)(long)n) ); + public static int SignedLOWORD(IntPtr n) + { + return SignedLOWORD(unchecked((int)(long)n)); } - - public static int SignedHIWORD(int n) { + + public static int SignedHIWORD(int n) + { int i = (int)(short)((n >> 16) & 0xffff); - + return i; } - - public static int SignedLOWORD(int n) { + + public static int SignedLOWORD(int n) + { int i = (int)(short)(n & 0xFFFF); - + return i; } - private static int GetEmbeddedNullStringLengthAnsi(string s) { + private static int GetEmbeddedNullStringLengthAnsi(string s) + { int n = s.IndexOf('\0'); - if (n > -1) { + if (n > -1) + { string left = s.Substring(0, n); - string right = s.Substring(n+1); + string right = s.Substring(n + 1); return left.Length + GetEmbeddedNullStringLengthAnsi(right) + 1; } - else { + else + { return s.Length; } } - - [DllImport(ExternDll.Kernel32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Kernel32, CharSet = CharSet.Auto)] + private static extern int lstrlen(string s); } - - public enum tagTYPEKIND { + + public enum tagTYPEKIND + { TKIND_ENUM = 0, TKIND_RECORD = 1, TKIND_MODULE = 2, @@ -5059,27 +5233,30 @@ public enum tagTYPEKIND { } [StructLayout(LayoutKind.Sequential)] - public struct tagTYPEDESC { - public IntPtr unionMember; - public short vt; + public struct tagTYPEDESC + { + public IntPtr unionMember; + public short vt; } - + [StructLayout(LayoutKind.Sequential)] - public struct tagPARAMDESC { - public IntPtr pparamdescex; - + public struct tagPARAMDESC + { + public IntPtr pparamdescex; + [MarshalAs(UnmanagedType.U2)] - public short wParamFlags; + public short wParamFlags; } - - public enum tagSYSKIND { + + public enum tagSYSKIND + { SYS_WIN16 = 0, SYS_MAC = 2 } - + public delegate bool MonitorEnumProc(IntPtr monitor, IntPtr hdc, IntPtr lprcMonitor, IntPtr lParam); - + [ComImport] [Guid("A7ABA9C1-8983-11cf-8F20-00805F2CD064")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] @@ -5089,33 +5266,34 @@ public interface IProvideMultipleClassInfo // these are from IProvideClassInfo & IProvideClassInfo2 [PreserveSig] UnsafeNativeMethods.ITypeInfo GetClassInfo(); - + [PreserveSig] int GetGUID(int dwGuidKind, [In, Out] ref Guid pGuid); - + [PreserveSig] int GetMultiTypeInfoCount([In, Out] ref int pcti); - + // we use arrays for most of these since we never use them anyway. [PreserveSig] - int GetInfoOfIndex(int iti, int dwFlags, + int GetInfoOfIndex(int iti, int dwFlags, [In, Out] - ref UnsafeNativeMethods.ITypeInfo pTypeInfo, + ref UnsafeNativeMethods.ITypeInfo pTypeInfo, int pTIFlags, int pcdispidReserved, IntPtr piidPrimary, IntPtr piidSource); } - + [StructLayout(LayoutKind.Sequential)] - public class EVENTMSG { + public class EVENTMSG + { public int message; public int paramL; public int paramH; public int time; public IntPtr hwnd; } - + [ComImport] [Guid("B196B283-BAB4-101A-B69C-00AA00341D07")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] @@ -5124,105 +5302,113 @@ public interface IProvideClassInfo [return: MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.ITypeInfo GetClassInfo(); } - + [StructLayout(LayoutKind.Sequential)] - public struct tagTYPEATTR { + public struct tagTYPEATTR + { public Guid guid; [MarshalAs(UnmanagedType.U4)] - public int lcid; + public int lcid; [MarshalAs(UnmanagedType.U4)] - public int dwReserved; - public int memidConstructor; - public int memidDestructor; - public IntPtr lpstrSchema; + public int dwReserved; + public int memidConstructor; + public int memidDestructor; + public IntPtr lpstrSchema; [MarshalAs(UnmanagedType.U4)] - public int cbSizeInstance; + public int cbSizeInstance; public /*NativeMethods.tagTYPEKIND*/ int typekind; [MarshalAs(UnmanagedType.U2)] - public short cFuncs; + public short cFuncs; [MarshalAs(UnmanagedType.U2)] - public short cVars; + public short cVars; [MarshalAs(UnmanagedType.U2)] - public short cImplTypes; + public short cImplTypes; [MarshalAs(UnmanagedType.U2)] - public short cbSizeVft; + public short cbSizeVft; [MarshalAs(UnmanagedType.U2)] - public short cbAlignment; + public short cbAlignment; [MarshalAs(UnmanagedType.U2)] - public short wTypeFlags; + public short wTypeFlags; [MarshalAs(UnmanagedType.U2)] - public short wMajorVerNum; + public short wMajorVerNum; [MarshalAs(UnmanagedType.U2)] - public short wMinorVerNum; - + public short wMinorVerNum; + //these are inline too //public NativeMethods.tagTYPEDESC tdescAlias; [MarshalAs(UnmanagedType.U4)] - public int tdescAlias_unionMember; - + public int tdescAlias_unionMember; + [MarshalAs(UnmanagedType.U2)] - public short tdescAlias_vt; - + public short tdescAlias_vt; + //public NativeMethods.tagIDLDESC idldescType; [MarshalAs(UnmanagedType.U4)] - public int idldescType_dwReserved; - + public int idldescType_dwReserved; + [MarshalAs(UnmanagedType.U2)] - public short idldescType_wIDLFlags; - - - public tagTYPEDESC Get_tdescAlias(){ + public short idldescType_wIDLFlags; + + + public tagTYPEDESC Get_tdescAlias() + { tagTYPEDESC td; td.unionMember = (IntPtr)this.tdescAlias_unionMember; td.vt = this.tdescAlias_vt; return td; } - - public tagIDLDESC Get_idldescType(){ + + public tagIDLDESC Get_idldescType() + { tagIDLDESC id = new tagIDLDESC(); id.dwReserved = this.idldescType_dwReserved; id.wIDLFlags = this.idldescType_wIDLFlags; return id; - } - } - - public enum tagVARFLAGS { - VARFLAG_FREADONLY = 1, - VARFLAG_FSOURCE = 0x2, - VARFLAG_FBINDABLE = 0x4, - VARFLAG_FREQUESTEDIT = 0x8, - VARFLAG_FDISPLAYBIND = 0x10, - VARFLAG_FDEFAULTBIND = 0x20, - VARFLAG_FHIDDEN = 0x40, - VARFLAG_FDEFAULTCOLLELEM = 0x100, - VARFLAG_FUIDEFAULT = 0x200, - VARFLAG_FNONBROWSABLE = 0x400, - VARFLAG_FREPLACEABLE = 0x800, - VARFLAG_FIMMEDIATEBIND = 0x1000 - } - + } + } + + public enum tagVARFLAGS + { + VARFLAG_FREADONLY = 1, + VARFLAG_FSOURCE = 0x2, + VARFLAG_FBINDABLE = 0x4, + VARFLAG_FREQUESTEDIT = 0x8, + VARFLAG_FDISPLAYBIND = 0x10, + VARFLAG_FDEFAULTBIND = 0x20, + VARFLAG_FHIDDEN = 0x40, + VARFLAG_FDEFAULTCOLLELEM = 0x100, + VARFLAG_FUIDEFAULT = 0x200, + VARFLAG_FNONBROWSABLE = 0x400, + VARFLAG_FREPLACEABLE = 0x800, + VARFLAG_FIMMEDIATEBIND = 0x1000 + } + [StructLayout(LayoutKind.Sequential)] - public unsafe struct tagELEMDESC { - public NativeMethods.tagTYPEDESC* tdesc; - public NativeMethods.tagPARAMDESC paramdesc; + public unsafe struct tagELEMDESC + { + public NativeMethods.tagTYPEDESC* tdesc; + public NativeMethods.tagPARAMDESC paramdesc; } - - public enum tagVARKIND { + + public enum tagVARKIND + { VAR_PERINSTANCE = 0, VAR_STATIC = 1, VAR_CONST = 2, VAR_DISPATCH = 3 } - + [StructLayout(LayoutKind.Sequential)] - public struct tagIDLDESC { + public struct tagIDLDESC + { [MarshalAs(UnmanagedType.U4)] - public int dwReserved; + public int dwReserved; [MarshalAs(UnmanagedType.U2)] - public short wIDLFlags; + public short wIDLFlags; } - public struct RGBQUAD { + public struct RGBQUAD + { public byte rgbBlue; public byte rgbGreen; public byte rgbRed; @@ -5230,7 +5416,8 @@ public struct RGBQUAD { } [StructLayout(LayoutKind.Sequential)] - public struct PALETTEENTRY { + public struct PALETTEENTRY + { public byte peRed; public byte peGreen; public byte peBlue; @@ -5238,20 +5425,21 @@ public struct PALETTEENTRY { } [StructLayout(LayoutKind.Sequential)] - public struct BITMAPINFO_FLAT { - public int bmiHeader_biSize;// = Marshal.SizeOf(); - public int bmiHeader_biWidth; - public int bmiHeader_biHeight; - public short bmiHeader_biPlanes; - public short bmiHeader_biBitCount; - public int bmiHeader_biCompression; - public int bmiHeader_biSizeImage; - public int bmiHeader_biXPelsPerMeter; - public int bmiHeader_biYPelsPerMeter; - public int bmiHeader_biClrUsed; - public int bmiHeader_biClrImportant; - - [MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst=BITMAPINFO_MAX_COLORSIZE*4)] + public struct BITMAPINFO_FLAT + { + public int bmiHeader_biSize;// = Marshal.SizeOf(); + public int bmiHeader_biWidth; + public int bmiHeader_biHeight; + public short bmiHeader_biPlanes; + public short bmiHeader_biBitCount; + public int bmiHeader_biCompression; + public int bmiHeader_biSizeImage; + public int bmiHeader_biXPelsPerMeter; + public int bmiHeader_biYPelsPerMeter; + public int bmiHeader_biClrUsed; + public int bmiHeader_biClrImportant; + + [MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst = BITMAPINFO_MAX_COLORSIZE * 4)] public byte[] bmiColors; // RGBQUAD structs... Blue-Green-Red-Reserved, repeat... } @@ -5260,7 +5448,8 @@ public struct BITMAPINFO_FLAT { /// if there is a '#' in the path, everything after this is treated as a fragment. So /// we need to append the fragment to the end of the path. /// - internal static string GetLocalPath(string fileName) { + internal static string GetLocalPath(string fileName) + { System.Diagnostics.Debug.Assert(fileName != null && fileName.Length > 0, "Cannot get local path, fileName is not valid"); Uri uri = new Uri(fileName); @@ -5268,36 +5457,37 @@ internal static string GetLocalPath(string fileName) { } [StructLayout(LayoutKind.Sequential)] - public struct SYSTEM_POWER_STATUS { - public byte ACLineStatus; - public byte BatteryFlag; - public byte BatteryLifePercent; - public byte Reserved1; - public int BatteryLifeTime; - public int BatteryFullLifeTime; + public struct SYSTEM_POWER_STATUS + { + public byte ACLineStatus; + public byte BatteryFlag; + public byte BatteryLifePercent; + public byte Reserved1; + public int BatteryLifeTime; + public int BatteryFullLifeTime; } [StructLayout(LayoutKind.Sequential)] - internal class DLLVERSIONINFO + internal class DLLVERSIONINFO { - internal uint cbSize = 0; - internal uint dwMajorVersion = 0; - internal uint dwMinorVersion = 0; - internal uint dwBuildNumber = 0; - internal uint dwPlatformID = 0; + internal uint cbSize = 0; + internal uint dwMajorVersion = 0; + internal uint dwMinorVersion = 0; + internal uint dwBuildNumber = 0; + internal uint dwPlatformID = 0; } - public enum OLERENDER - { + public enum OLERENDER + { OLERENDER_NONE = 0, OLERENDER_DRAW = 1, OLERENDER_FORMAT = 2, - OLERENDER_ASIS = 3 + OLERENDER_ASIS = 3 } public enum PROCESS_DPI_AWARENESS { - PROCESS_DPI_UNINITIALIZED = -1, + PROCESS_DPI_UNINITIALIZED = -1, PROCESS_DPI_UNAWARE = 0, PROCESS_SYSTEM_DPI_AWARE = 1, PROCESS_PER_MONITOR_DPI_AWARE = 2 @@ -5318,9 +5508,9 @@ public enum MONTCALENDAR_VIEW_MODE public const int DPI_AWARENESS_CONTEXT_UNAWARE_GDISCALED = -5; // Theming/Visual Styles stuff - public const int STAP_ALLOW_NONCLIENT = (1 << 0); - public const int STAP_ALLOW_CONTROLS = (1 << 1); - public const int STAP_ALLOW_WEBCONTENT = (1 << 2); + public const int STAP_ALLOW_NONCLIENT = (1 << 0); + public const int STAP_ALLOW_CONTROLS = (1 << 1); + public const int STAP_ALLOW_WEBCONTENT = (1 << 2); public const int PS_NULL = 5; public const int PS_INSIDEFRAME = 6; @@ -5337,13 +5527,15 @@ public enum MONTCALENDAR_VIEW_MODE public const uint STILL_ACTIVE = 259; [StructLayout(LayoutKind.Sequential)] - public struct UiaRect { + public struct UiaRect + { public double left; public double top; public double width; public double height; - public UiaRect(System.Drawing.Rectangle r) { + public UiaRect(System.Drawing.Rectangle r) + { this.left = r.Left; this.top = r.Top; this.width = r.Width; diff --git a/src/Common/src/RTLAwareMessageBox.cs b/src/Common/src/RTLAwareMessageBox.cs index 0fc63a706cd..1b68cebe1b6 100644 --- a/src/Common/src/RTLAwareMessageBox.cs +++ b/src/Common/src/RTLAwareMessageBox.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Resources; @@ -11,15 +12,18 @@ namespace System.Windows.Forms { /// The Show method displays a message box that can contain text, buttons, and symbols that inform and instruct the user. /// This MessageBox will be RTL, if the resources for this dll have been localized to a RTL language. /// - internal sealed class RTLAwareMessageBox { + internal sealed class RTLAwareMessageBox + { /// /// Displays a message box with specified text, caption, and style. /// Makes the dialog RTL if the resources for this dll have been localized to a RTL language. /// - public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, - MessageBoxDefaultButton defaultButton, MessageBoxOptions options) { - if (RTLAwareMessageBox.IsRTLResources) { + public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, + MessageBoxDefaultButton defaultButton, MessageBoxOptions options) + { + if (RTLAwareMessageBox.IsRTLResources) + { options |= (MessageBoxOptions.RightAlign | MessageBoxOptions.RtlReading); } return MessageBox.Show(owner, text, caption, buttons, icon, defaultButton, options); @@ -28,8 +32,10 @@ public static DialogResult Show(IWin32Window owner, string text, string caption, /// /// Tells whether the current resources for this dll have been localized for a RTL language. /// - public static bool IsRTLResources { - get { + public static bool IsRTLResources + { + get + { return SR.RTL != "RTL_False"; } } diff --git a/src/Common/src/SafeNativeMethods.cs b/src/Common/src/SafeNativeMethods.cs index 63723daaabc..9c141f87651 100644 --- a/src/Common/src/SafeNativeMethods.cs +++ b/src/Common/src/SafeNativeMethods.cs @@ -5,7 +5,8 @@ ///------------------------------------------------------------------------------ -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System; @@ -13,185 +14,189 @@ namespace System.Windows.Forms { using System.IO; using System.Text; using System.Drawing; - using System.Diagnostics.CodeAnalysis; + using System.Diagnostics.CodeAnalysis; using System.Runtime.Versioning; using IComDataObject = System.Runtime.InteropServices.ComTypes.IDataObject; - internal static class SafeNativeMethods { + internal static class SafeNativeMethods + { [DllImport("shlwapi.dll")] - + public static extern int SHAutoComplete(HandleRef hwndEdit, int flags); -/* -#if DEBUG - [DllImport(ExternDll.Shell32, EntryPoint="SHGetFileInfo")] - private static extern IntPtr IntSHGetFileInfo([MarshalAs(UnmanagedType.LPWStr)]string pszPath, int dwFileAttributes, NativeMethods.SHFILEINFO info, int cbFileInfo, int flags); - public static IntPtr SHGetFileInfo(string pszPath, int dwFileAttributes, NativeMethods.SHFILEINFO info, int cbFileInfo, int flags) { - IntPtr newHandle = IntSHGetFileInfo(pszPath, dwFileAttributes, info, cbFileInfo, flags); - validImageListHandles.Add(newHandle); - return newHandle; - } -#else - [DllImport(ExternDll.Shell32, CharSet=CharSet.Auto)] - public static extern IntPtr SHGetFileInfo(string pszPath, int dwFileAttributes, NativeMethods.SHFILEINFO info, int cbFileInfo, int flags); -#endif -*/ + /* + #if DEBUG + [DllImport(ExternDll.Shell32, EntryPoint="SHGetFileInfo")] + private static extern IntPtr IntSHGetFileInfo([MarshalAs(UnmanagedType.LPWStr)]string pszPath, int dwFileAttributes, NativeMethods.SHFILEINFO info, int cbFileInfo, int flags); + public static IntPtr SHGetFileInfo(string pszPath, int dwFileAttributes, NativeMethods.SHFILEINFO info, int cbFileInfo, int flags) { + IntPtr newHandle = IntSHGetFileInfo(pszPath, dwFileAttributes, info, cbFileInfo, flags); + validImageListHandles.Add(newHandle); + return newHandle; + } + #else + [DllImport(ExternDll.Shell32, CharSet=CharSet.Auto)] + public static extern IntPtr SHGetFileInfo(string pszPath, int dwFileAttributes, NativeMethods.SHFILEINFO info, int cbFileInfo, int flags); + #endif + */ [DllImport(ExternDll.User32)] - + public static extern int OemKeyScan(short wAsciiVal); [DllImport(ExternDll.Gdi32)] - + public static extern int GetSystemPaletteEntries(HandleRef hdc, int iStartIndex, int nEntries, byte[] lppe); [DllImport(ExternDll.Gdi32)] - + public static extern int GetDIBits(HandleRef hdc, HandleRef hbm, int uStartScan, int cScanLines, byte[] lpvBits, ref NativeMethods.BITMAPINFO_FLAT bmi, int uUsage); [DllImport(ExternDll.Gdi32)] - + public static extern int StretchDIBits(HandleRef hdc, int XDest, int YDest, int nDestWidth, int nDestHeight, int XSrc, int YSrc, int nSrcWidth, int nSrcHeight, byte[] lpBits, ref NativeMethods.BITMAPINFO_FLAT lpBitsInfo, int iUsage, int dwRop); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreateCompatibleBitmap", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateCompatibleBitmap", CharSet = CharSet.Auto)] + public static extern IntPtr IntCreateCompatibleBitmap(HandleRef hDC, int width, int height); - - - public static IntPtr CreateCompatibleBitmap(HandleRef hDC, int width, int height) { + + + public static IntPtr CreateCompatibleBitmap(HandleRef hDC, int width, int height) + { return Interop.HandleCollector.Add(IntCreateCompatibleBitmap(hDC, width, height), Interop.CommonHandles.GDI); } - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool GetScrollInfo(HandleRef hWnd, int fnBar, [In, Out] NativeMethods.SCROLLINFO si); - [DllImport(ExternDll.Ole32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Ole32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool IsAccelerator(HandleRef hAccel, int cAccelEntries, [In] ref NativeMethods.MSG lpMsg, short[] lpwCmd); - [DllImport(ExternDll.Comdlg32, SetLastError=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Comdlg32, SetLastError = true, CharSet = CharSet.Auto)] + public static extern bool ChooseFont([In, Out] NativeMethods.CHOOSEFONT cf); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int GetBitmapBits(HandleRef hbmp, int cbBuffer, byte[] lpvBits); - [DllImport(ExternDll.Comdlg32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Comdlg32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int CommDlgExtendedError(); - [DllImport(ExternDll.Oleaut32, ExactSpelling=true, CharSet=CharSet.Unicode)] - + [DllImport(ExternDll.Oleaut32, ExactSpelling = true, CharSet = CharSet.Unicode)] + public static extern void SysFreeString(HandleRef bstr); - [DllImport(ExternDll.Oleaut32, PreserveSig=false)] - + [DllImport(ExternDll.Oleaut32, PreserveSig = false)] + public static extern void OleCreatePropertyFrame(HandleRef hwndOwner, int x, int y, [MarshalAs(UnmanagedType.LPWStr)]string caption, int objects, [MarshalAs(UnmanagedType.Interface)] ref object pobjs, int pages, HandleRef pClsid, int locale, int reserved1, IntPtr reserved2); - [DllImport(ExternDll.Oleaut32, PreserveSig=false)] - + [DllImport(ExternDll.Oleaut32, PreserveSig = false)] + public static extern void OleCreatePropertyFrame(HandleRef hwndOwner, int x, int y, [MarshalAs(UnmanagedType.LPWStr)]string caption, int objects, [MarshalAs(UnmanagedType.Interface)] ref object pobjs, int pages, Guid[] pClsid, int locale, int reserved1, IntPtr reserved2); - [DllImport(ExternDll.Oleaut32, PreserveSig=false)] - + [DllImport(ExternDll.Oleaut32, PreserveSig = false)] + public static extern void OleCreatePropertyFrame(HandleRef hwndOwner, int x, int y, [MarshalAs(UnmanagedType.LPWStr)]string caption, int objects, HandleRef lplpobjs, int pages, HandleRef pClsid, int locale, int reserved1, IntPtr reserved2); - [DllImport(ExternDll.Hhctrl, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Hhctrl, CharSet = CharSet.Auto)] + public static extern int HtmlHelp(HandleRef hwndCaller, [MarshalAs(UnmanagedType.LPTStr)]string pszFile, int uCommand, int dwData); - [DllImport(ExternDll.Hhctrl, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Hhctrl, CharSet = CharSet.Auto)] + public static extern int HtmlHelp(HandleRef hwndCaller, [MarshalAs(UnmanagedType.LPTStr)]string pszFile, int uCommand, string dwData); - [DllImport(ExternDll.Hhctrl, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Hhctrl, CharSet = CharSet.Auto)] + public static extern int HtmlHelp(HandleRef hwndCaller, [MarshalAs(UnmanagedType.LPTStr)]string pszFile, int uCommand, [MarshalAs(UnmanagedType.LPStruct)]NativeMethods.HH_POPUP dwData); - [DllImport(ExternDll.Hhctrl, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Hhctrl, CharSet = CharSet.Auto)] + public static extern int HtmlHelp(HandleRef hwndCaller, [MarshalAs(UnmanagedType.LPTStr)]string pszFile, int uCommand, [MarshalAs(UnmanagedType.LPStruct)]NativeMethods.HH_FTS_QUERY dwData); - [DllImport(ExternDll.Hhctrl, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Hhctrl, CharSet = CharSet.Auto)] + public static extern int HtmlHelp(HandleRef hwndCaller, [MarshalAs(UnmanagedType.LPTStr)]string pszFile, int uCommand, [MarshalAs(UnmanagedType.LPStruct)]NativeMethods.HH_AKLINK dwData); [DllImport(ExternDll.Oleaut32)] - + public static extern void VariantInit(HandleRef pObject); - [ DllImport(ExternDll.Oleaut32, PreserveSig=false)] - + [DllImport(ExternDll.Oleaut32, PreserveSig = false)] + public static extern void VariantClear(HandleRef pObject); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool LineTo(HandleRef hdc, int x, int y); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool MoveToEx(HandleRef hdc, int x, int y, NativeMethods.POINT pt); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool Rectangle( HandleRef hdc, int left, int top, int right, int bottom); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool PatBlt(HandleRef hdc, int left, int top, int width, int height, int rop); - [DllImport(ExternDll.Kernel32, EntryPoint="GetThreadLocale", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Kernel32, EntryPoint = "GetThreadLocale", CharSet = CharSet.Auto)] + public static extern int GetThreadLCID(); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int GetMessagePos(); - [DllImport(ExternDll.User32, SetLastError=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, SetLastError = true, CharSet = CharSet.Auto)] + public static extern int RegisterClipboardFormat(string format); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern int GetClipboardFormatName(int format, StringBuilder lpString, int cchMax); - [DllImport(ExternDll.Comdlg32, SetLastError=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Comdlg32, SetLastError = true, CharSet = CharSet.Auto)] + public static extern bool ChooseColor([In, Out] NativeMethods.CHOOSECOLOR cc); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern int RegisterWindowMessage(string msg); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="DeleteObject", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "DeleteObject", CharSet = CharSet.Auto)] + public static extern bool ExternalDeleteObject(HandleRef hObject); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="DeleteObject", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "DeleteObject", CharSet = CharSet.Auto)] + internal static extern bool IntDeleteObject(HandleRef hObject); - public static bool DeleteObject(HandleRef hObject) { + public static bool DeleteObject(HandleRef hObject) + { Interop.HandleCollector.Remove((IntPtr)hObject, Interop.CommonHandles.GDI); return IntDeleteObject(hObject); } - [DllImport(ExternDll.Oleaut32, EntryPoint="OleCreateFontIndirect", ExactSpelling=true, PreserveSig=false)] - + [DllImport(ExternDll.Oleaut32, EntryPoint = "OleCreateFontIndirect", ExactSpelling = true, PreserveSig = false)] + public static extern SafeNativeMethods.IFontDisp OleCreateIFontDispIndirect(NativeMethods.FONTDESC fd, ref Guid iid); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreateSolidBrush", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateSolidBrush", CharSet = CharSet.Auto)] + private static extern IntPtr IntCreateSolidBrush(int crColor); - - - public static IntPtr CreateSolidBrush(int crColor) { + + + public static IntPtr CreateSolidBrush(int crColor) + { return Interop.HandleCollector.Add(IntCreateSolidBrush(crColor), Interop.CommonHandles.GDI); } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool SetWindowExtEx(HandleRef hDC, int x, int y, [In, Out] NativeMethods.SIZE size); - [DllImport(ExternDll.Kernel32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Kernel32, CharSet = CharSet.Auto)] + public static extern int FormatMessage(int dwFlags, HandleRef lpSource, int dwMessageId, int dwLanguageId, StringBuilder lpBuffer, int nSize, HandleRef arguments); [DllImport(ExternDll.Comctl32)] - + public static extern void InitCommonControls(); [DllImport(ExternDll.Comctl32)] - + public static extern bool InitCommonControlsEx(NativeMethods.INITCOMMONCONTROLSEX icc); #if DEBUG @@ -201,12 +206,13 @@ public static extern int FormatMessage(int dwFlags, HandleRef lpSource, int dwMe // #if DEBUG - [DllImport(ExternDll.Comctl32, EntryPoint="ImageList_Create")] - + [DllImport(ExternDll.Comctl32, EntryPoint = "ImageList_Create")] + private static extern IntPtr IntImageList_Create(int cx, int cy, int flags, int cInitial, int cGrow); - - - public static IntPtr ImageList_Create(int cx, int cy, int flags, int cInitial, int cGrow) { + + + public static IntPtr ImageList_Create(int cx, int cy, int flags, int cInitial, int cGrow) + { IntPtr newHandle = IntImageList_Create(cx, cy, flags, cInitial, cGrow); validImageListHandles.Add(newHandle); return newHandle; @@ -218,10 +224,11 @@ public static IntPtr ImageList_Create(int cx, int cy, int flags, int cInitial, i #endif #if DEBUG - [DllImport(ExternDll.Comctl32, EntryPoint="ImageList_Destroy")] - + [DllImport(ExternDll.Comctl32, EntryPoint = "ImageList_Destroy")] + private static extern bool IntImageList_Destroy(HandleRef himl); - public static bool ImageList_Destroy(HandleRef himl) { + public static bool ImageList_Destroy(HandleRef himl) + { System.Diagnostics.Debug.Assert(validImageListHandles.Contains(himl.Handle), "Invalid ImageList handle"); validImageListHandles.Remove(himl.Handle); return IntImageList_Destroy(himl); @@ -235,41 +242,42 @@ public static bool ImageList_Destroy(HandleRef himl) { // our version of ImageList_Create, which is not always the case for the TreeView's internal // native state image list. Use separate EntryPoint thunk to skip this check: [DllImport(ExternDll.Comctl32, EntryPoint = "ImageList_Destroy")] - + public static extern bool ImageList_Destroy_Native(HandleRef himl); [DllImport(ExternDll.Comctl32)] - + public static extern int ImageList_GetImageCount(HandleRef himl); [DllImport(ExternDll.Comctl32)] - + public static extern int ImageList_Add(HandleRef himl, HandleRef hbmImage, HandleRef hbmMask); [DllImport(ExternDll.Comctl32)] - + public static extern int ImageList_ReplaceIcon(HandleRef himl, int index, HandleRef hicon); [DllImport(ExternDll.Comctl32)] - + public static extern int ImageList_SetBkColor(HandleRef himl, int clrBk); [DllImport(ExternDll.Comctl32)] - + public static extern bool ImageList_Draw(HandleRef himl, int i, HandleRef hdcDst, int x, int y, int fStyle); [DllImport(ExternDll.Comctl32)] - + public static extern bool ImageList_Replace(HandleRef himl, int i, HandleRef hbmImage, HandleRef hbmMask); [DllImport(ExternDll.Comctl32)] - + public static extern bool ImageList_DrawEx(HandleRef himl, int i, HandleRef hdcDst, int x, int y, int dx, int dy, int rgbBk, int rgbFg, int fStyle); [DllImport(ExternDll.Comctl32)] - + public static extern bool ImageList_GetIconSize(HandleRef himl, out int x, out int y); #if DEBUG - [DllImport(ExternDll.Comctl32, EntryPoint="ImageList_Duplicate")] - + [DllImport(ExternDll.Comctl32, EntryPoint = "ImageList_Duplicate")] + private static extern IntPtr IntImageList_Duplicate(HandleRef himl); - - - public static IntPtr ImageList_Duplicate(HandleRef himl) { + + + public static IntPtr ImageList_Duplicate(HandleRef himl) + { IntPtr newHandle = IntImageList_Duplicate(himl); validImageListHandles.Add(newHandle); return newHandle; @@ -281,17 +289,18 @@ public static IntPtr ImageList_Duplicate(HandleRef himl) { #endif [DllImport(ExternDll.Comctl32)] - + public static extern bool ImageList_Remove(HandleRef himl, int i); [DllImport(ExternDll.Comctl32)] - + public static extern bool ImageList_GetImageInfo(HandleRef himl, int i, NativeMethods.IMAGEINFO pImageInfo); #if DEBUG - [DllImport(ExternDll.Comctl32, EntryPoint="ImageList_Read")] - + [DllImport(ExternDll.Comctl32, EntryPoint = "ImageList_Read")] + private static extern IntPtr IntImageList_Read(UnsafeNativeMethods.IStream pstm); - public static IntPtr ImageList_Read(UnsafeNativeMethods.IStream pstm) { + public static IntPtr ImageList_Read(UnsafeNativeMethods.IStream pstm) + { IntPtr newHandle = IntImageList_Read(pstm); validImageListHandles.Add(newHandle); return newHandle; @@ -303,266 +312,277 @@ public static IntPtr ImageList_Read(UnsafeNativeMethods.IStream pstm) { #endif [DllImport(ExternDll.Comctl32)] - + public static extern bool ImageList_Write(HandleRef himl, UnsafeNativeMethods.IStream pstm); [DllImport(ExternDll.Comctl32)] - + public static extern int ImageList_WriteEx(HandleRef himl, int dwFlags, UnsafeNativeMethods.IStream pstm); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool TrackPopupMenuEx(HandleRef hmenu, int fuFlags, int x, int y, HandleRef hwnd, NativeMethods.TPMPARAMS tpm); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr GetKeyboardLayout(int dwLayout); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr ActivateKeyboardLayout(HandleRef hkl, int uFlags); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int GetKeyboardLayoutList(int size, [Out, MarshalAs(UnmanagedType.LPArray)] IntPtr[] hkls); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern bool EnumDisplaySettings(string lpszDeviceName, int iModeNum, ref NativeMethods.DEVMODE lpDevMode); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern bool GetMonitorInfo(HandleRef hmonitor, [In, Out]NativeMethods.MONITORINFOEX info); - [DllImport(ExternDll.User32, ExactSpelling=true)] - + [DllImport(ExternDll.User32, ExactSpelling = true)] + public static extern IntPtr MonitorFromPoint(NativeMethods.POINTSTRUCT pt, int flags); - [DllImport(ExternDll.User32, ExactSpelling=true)] - + [DllImport(ExternDll.User32, ExactSpelling = true)] + public static extern IntPtr MonitorFromRect(ref NativeMethods.RECT rect, int flags); - [DllImport(ExternDll.User32, ExactSpelling=true)] - + [DllImport(ExternDll.User32, ExactSpelling = true)] + public static extern IntPtr MonitorFromWindow(HandleRef handle, int flags); [DllImport(ExternDll.User32, ExactSpelling = true)] - + public static extern bool EnumDisplayMonitors(HandleRef hdc, NativeMethods.COMRECT rcClip, NativeMethods.MonitorEnumProc lpfnEnum, IntPtr dwData); [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateHalftonePalette", CharSet = CharSet.Auto)] - + private static extern IntPtr /*HPALETTE*/ IntCreateHalftonePalette(HandleRef hdc); - public static IntPtr /*HPALETTE*/ CreateHalftonePalette(HandleRef hdc) { + public static IntPtr /*HPALETTE*/ CreateHalftonePalette(HandleRef hdc) + { return Interop.HandleCollector.Add(IntCreateHalftonePalette(hdc), Interop.CommonHandles.GDI); } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int GetPaletteEntries(HandleRef hpal, int iStartIndex, int nEntries, int[] lppe); [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)] public static extern int GetTextMetricsW(HandleRef hDC, ref NativeMethods.TEXTMETRIC lptm); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreateDIBSection", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateDIBSection", CharSet = CharSet.Auto)] + private static extern IntPtr IntCreateDIBSection(HandleRef hdc, HandleRef pbmi, int iUsage, byte[] ppvBits, IntPtr hSection, int dwOffset); - - - public static IntPtr CreateDIBSection(HandleRef hdc, HandleRef pbmi, int iUsage, byte[] ppvBits, IntPtr hSection, int dwOffset) { + + + public static IntPtr CreateDIBSection(HandleRef hdc, HandleRef pbmi, int iUsage, byte[] ppvBits, IntPtr hSection, int dwOffset) + { return Interop.HandleCollector.Add(IntCreateDIBSection(hdc, pbmi, iUsage, ppvBits, hSection, dwOffset), Interop.CommonHandles.GDI); } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreateBitmap", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateBitmap", CharSet = CharSet.Auto)] + private static extern IntPtr /*HBITMAP*/ IntCreateBitmap(int nWidth, int nHeight, int nPlanes, int nBitsPerPixel, IntPtr lpvBits); - - - public static IntPtr /*HBITMAP*/ CreateBitmap(int nWidth, int nHeight, int nPlanes, int nBitsPerPixel, IntPtr lpvBits) { + + + public static IntPtr /*HBITMAP*/ CreateBitmap(int nWidth, int nHeight, int nPlanes, int nBitsPerPixel, IntPtr lpvBits) + { return Interop.HandleCollector.Add(IntCreateBitmap(nWidth, nHeight, nPlanes, nBitsPerPixel, lpvBits), Interop.CommonHandles.GDI); } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreateBitmap", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateBitmap", CharSet = CharSet.Auto)] + private static extern IntPtr /*HBITMAP*/ IntCreateBitmapShort(int nWidth, int nHeight, int nPlanes, int nBitsPerPixel, short[] lpvBits); - - - public static IntPtr /*HBITMAP*/ CreateBitmap(int nWidth, int nHeight, int nPlanes, int nBitsPerPixel, short[] lpvBits) { + + + public static IntPtr /*HBITMAP*/ CreateBitmap(int nWidth, int nHeight, int nPlanes, int nBitsPerPixel, short[] lpvBits) + { return Interop.HandleCollector.Add(IntCreateBitmapShort(nWidth, nHeight, nPlanes, nBitsPerPixel, lpvBits), Interop.CommonHandles.GDI); } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreateBitmap", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateBitmap", CharSet = CharSet.Auto)] + private static extern IntPtr /*HBITMAP*/ IntCreateBitmapByte(int nWidth, int nHeight, int nPlanes, int nBitsPerPixel, byte[] lpvBits); - - - public static IntPtr /*HBITMAP*/ CreateBitmap(int nWidth, int nHeight, int nPlanes, int nBitsPerPixel, byte[] lpvBits) { + + + public static IntPtr /*HBITMAP*/ CreateBitmap(int nWidth, int nHeight, int nPlanes, int nBitsPerPixel, byte[] lpvBits) + { return Interop.HandleCollector.Add(IntCreateBitmapByte(nWidth, nHeight, nPlanes, nBitsPerPixel, lpvBits), Interop.CommonHandles.GDI); } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreatePatternBrush", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreatePatternBrush", CharSet = CharSet.Auto)] + private static extern IntPtr /*HBRUSH*/ IntCreatePatternBrush(HandleRef hbmp); - - - public static IntPtr /*HBRUSH*/ CreatePatternBrush(HandleRef hbmp) { + + + public static IntPtr /*HBRUSH*/ CreatePatternBrush(HandleRef hbmp) + { return Interop.HandleCollector.Add(IntCreatePatternBrush(hbmp), Interop.CommonHandles.GDI); } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreateBrushIndirect", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateBrushIndirect", CharSet = CharSet.Auto)] + private static extern IntPtr IntCreateBrushIndirect(NativeMethods.LOGBRUSH lb); - - - public static IntPtr CreateBrushIndirect(NativeMethods.LOGBRUSH lb) { + + + public static IntPtr CreateBrushIndirect(NativeMethods.LOGBRUSH lb) + { return Interop.HandleCollector.Add(IntCreateBrushIndirect(lb), Interop.CommonHandles.GDI); } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreatePen", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreatePen", CharSet = CharSet.Auto)] + private static extern IntPtr IntCreatePen(int nStyle, int nWidth, int crColor); - - - public static IntPtr CreatePen(int nStyle, int nWidth, int crColor) { + + + public static IntPtr CreatePen(int nStyle, int nWidth, int crColor) + { return Interop.HandleCollector.Add(IntCreatePen(nStyle, nWidth, crColor), Interop.CommonHandles.GDI); } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool SetViewportExtEx(HandleRef hDC, int x, int y, NativeMethods.SIZE size); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr LoadCursor(HandleRef hInst, int iconId); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public extern static bool GetClipCursor([In, Out] ref NativeMethods.RECT lpRect); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr GetCursor(); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool GetIconInfo(HandleRef hIcon, [In, Out] NativeMethods.ICONINFO info); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int IntersectClipRect(HandleRef hDC, int x1, int y1, int x2, int y2); - [DllImport(ExternDll.User32, ExactSpelling=true, EntryPoint="CopyImage", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, EntryPoint = "CopyImage", CharSet = CharSet.Auto)] + private static extern IntPtr IntCopyImage(HandleRef hImage, int uType, int cxDesired, int cyDesired, int fuFlags); - public static IntPtr CopyImage(HandleRef hImage, int uType, int cxDesired, int cyDesired, int fuFlags) { + public static IntPtr CopyImage(HandleRef hImage, int uType, int cxDesired, int cyDesired, int fuFlags) + { return Interop.HandleCollector.Add(IntCopyImage(hImage, uType, cxDesired, cyDesired, fuFlags), Interop.CommonHandles.GDI); } - public static IntPtr CopyImageAsCursor(HandleRef hImage, int uType, int cxDesired, int cyDesired, int fuFlags) { + public static IntPtr CopyImageAsCursor(HandleRef hImage, int uType, int cxDesired, int cyDesired, int fuFlags) + { return Interop.HandleCollector.Add(IntCopyImage(hImage, uType, cxDesired, cyDesired, fuFlags), Interop.CommonHandles.Cursor); } - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool AdjustWindowRectEx(ref NativeMethods.RECT lpRect, int dwStyle, bool bMenu, int dwExStyle); // This API is available only starting Windows 10 RS1 - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - - public static extern bool AdjustWindowRectExForDpi(ref NativeMethods.RECT lpRect, int dwStyle, bool bMenu, int dwExStyle, uint dpi); + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + + public static extern bool AdjustWindowRectExForDpi(ref NativeMethods.RECT lpRect, int dwStyle, bool bMenu, int dwExStyle, uint dpi); + + [DllImport(ExternDll.Ole32, ExactSpelling = true, CharSet = CharSet.Auto)] - [DllImport(ExternDll.Ole32, ExactSpelling=true, CharSet=CharSet.Auto)] - public static extern int DoDragDrop(IComDataObject dataObject, UnsafeNativeMethods.IOleDropSource dropSource, int allowedEffects, int[] finalEffect); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr GetSysColorBrush(int nIndex); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool EnableWindow(HandleRef hWnd, bool enable); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool GetClientRect(HandleRef hWnd, [In, Out] ref NativeMethods.RECT rect); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int GetDoubleClickTime(); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int GetUpdateRgn(HandleRef hwnd, HandleRef hrgn, bool fErase); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool ValidateRect(HandleRef hWnd, [In, Out] ref NativeMethods.RECT rect); [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] public static extern bool ValidateRect(IntPtr hwnd, IntPtr prect); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int FillRect(HandleRef hdc, [In] ref NativeMethods.RECT rect, HandleRef hbrush); - [DllImport(ExternDll.Gdi32,ExactSpelling=true,CharSet=CharSet.Auto)] - - public static extern int /*COLORREF*/ GetTextColor(HandleRef hDC); - + [DllImport(ExternDll.Gdi32, ExactSpelling = true, CharSet = CharSet.Auto)] + + public static extern int /*COLORREF*/ GetTextColor(HandleRef hDC); + + + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, CharSet = CharSet.Auto)] - public static extern int GetBkColor(HandleRef hDC); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int /*COLORREF*/ SetTextColor(HandleRef hDC, int crColor); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int SetBkColor(HandleRef hDC, int clr); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr /* HPALETTE */SelectPalette(HandleRef hdc, HandleRef hpal, int bForceBackground); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool SetViewportOrgEx(HandleRef hDC, int x, int y, [In, Out] NativeMethods.POINT point); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreateRectRgn", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateRectRgn", CharSet = CharSet.Auto)] + private static extern IntPtr IntCreateRectRgn(int x1, int y1, int x2, int y2); - - - public static IntPtr CreateRectRgn(int x1, int y1, int x2, int y2) { + + + public static IntPtr CreateRectRgn(int x1, int y1, int x2, int y2) + { return Interop.HandleCollector.Add(IntCreateRectRgn(x1, y1, x2, y2), Interop.CommonHandles.GDI); } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int CombineRgn(HandleRef hRgn, HandleRef hRgn1, HandleRef hRgn2, int nCombineMode); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int RealizePalette(HandleRef hDC); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool LPtoDP(HandleRef hDC, [In, Out] ref NativeMethods.RECT lpRect, int nCount); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool SetWindowOrgEx(HandleRef hDC, int x, int y, [In, Out] NativeMethods.POINT point); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool GetViewportOrgEx(HandleRef hDC, [In, Out] NativeMethods.POINT point); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int SetMapMode(HandleRef hDC, int nMapMode); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool IsWindowEnabled(HandleRef hWnd); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool IsWindowVisible(HandleRef hWnd); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool ReleaseCapture(); - [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int GetCurrentThreadId(); [DllImport(ExternDll.User32, CharSet = CharSet.Auto, SetLastError = true)] - + public static extern bool EnumWindows(EnumThreadWindowsCallback callback, IntPtr extraData); internal delegate bool EnumThreadWindowsCallback(IntPtr hWnd, IntPtr lParam); [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] - + public static extern int GetWindowThreadProcessId(HandleRef hWnd, out int lpdwProcessId); - [return:MarshalAs(UnmanagedType.Bool)] + [return: MarshalAs(UnmanagedType.Bool)] [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Auto)] - + public static extern bool GetExitCodeThread(HandleRef hWnd, out int lpdwExitCode); [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] - + public static extern bool ShowWindow(HandleRef hWnd, int nCmdShow); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool SetWindowPos(HandleRef hWnd, HandleRef hWndInsertAfter, int x, int y, int cx, int cy, int flags); @@ -571,210 +591,211 @@ public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, int flags); // this is a wrapper that comctl exposes for the NT function since it doesn't exist natively on 95. - [DllImport(ExternDll.Comctl32, ExactSpelling=true)] - + [DllImport(ExternDll.Comctl32, ExactSpelling = true)] + private static extern bool _TrackMouseEvent(NativeMethods.TRACKMOUSEEVENT tme); - public static bool TrackMouseEvent(NativeMethods.TRACKMOUSEEVENT tme) { + public static bool TrackMouseEvent(NativeMethods.TRACKMOUSEEVENT tme) + { // only on NT - not on 95 - comctl32 has a wrapper for 95 and NT. return _TrackMouseEvent(tme); } - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool RedrawWindow(HandleRef hwnd, ref NativeMethods.RECT rcUpdate, HandleRef hrgnUpdate, int flags); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool RedrawWindow(HandleRef hwnd, NativeMethods.COMRECT rcUpdate, HandleRef hrgnUpdate, int flags); [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] public static extern bool RedrawWindow(IntPtr hwnd, NativeMethods.COMRECT rcUpdate, IntPtr hrgnUpdate, int flags); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool InvalidateRect(HandleRef hWnd, ref NativeMethods.RECT rect, bool erase); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool InvalidateRect(HandleRef hWnd, NativeMethods.COMRECT rect, bool erase); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool InvalidateRgn(HandleRef hWnd, HandleRef hrgn, bool erase); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool UpdateWindow(HandleRef hWnd); - [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int GetCurrentProcessId(); - [DllImport(ExternDll.User32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - - public static extern int ScrollWindowEx(HandleRef hWnd, int nXAmount, int nYAmount, NativeMethods.COMRECT rectScrollRegion, ref NativeMethods.RECT rectClip, HandleRef hrgnUpdate, ref NativeMethods.RECT prcUpdate, int flags); - [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + + public static extern int ScrollWindowEx(HandleRef hWnd, int nXAmount, int nYAmount, NativeMethods.COMRECT rectScrollRegion, ref NativeMethods.RECT rectClip, HandleRef hrgnUpdate, ref NativeMethods.RECT prcUpdate, int flags); + [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int GetThreadLocale(); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool MessageBeep(int type); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool DrawMenuBar(HandleRef hWnd); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public extern static bool IsChild(HandleRef parent, HandleRef child); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr SetTimer(HandleRef hWnd, int nIDEvent, int uElapse, IntPtr lpTimerFunc); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool KillTimer(HandleRef hwnd, int idEvent); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto), - SuppressMessage("Microsoft.Usage", "CA2205:UseManagedEquivalentsOfWin32Api")] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto), + SuppressMessage("Microsoft.Usage", "CA2205:UseManagedEquivalentsOfWin32Api")] + public static extern int MessageBox(HandleRef hWnd, string text, string caption, int type); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr SelectObject(HandleRef hDC, HandleRef hObject); - [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int GetTickCount(); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool ScrollWindow(HandleRef hWnd, int nXAmount, int nYAmount, ref NativeMethods.RECT rectScrollRegion, ref NativeMethods.RECT rectClip); - [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr GetCurrentProcess(); - [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr GetCurrentThread(); [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Auto)] - + public extern static bool SetThreadLocale(int Locale); - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] - + public static extern bool IsWindowUnicode(HandleRef hWnd); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool DrawEdge(HandleRef hDC, ref NativeMethods.RECT rect, int edge, int flags); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool DrawFrameControl(HandleRef hDC, ref NativeMethods.RECT rect, int type, int state); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int GetClipRgn(HandleRef hDC, HandleRef hRgn); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int GetRgnBox(HandleRef hRegion, ref NativeMethods.RECT clipRect); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int SelectClipRgn(HandleRef hDC, HandleRef hRgn); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int SetROP2(HandleRef hDC, int nDrawMode); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool DrawIcon(HandleRef hDC, int x, int y, HandleRef hIcon); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool DrawIconEx(HandleRef hDC, int x, int y, HandleRef hIcon, int width, int height, int iStepIfAniCursor, HandleRef hBrushFlickerFree, int diFlags); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int SetBkMode(HandleRef hDC, int nBkMode); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool BitBlt(HandleRef hDC, int x, int y, int nWidth, int nHeight, HandleRef hSrcDC, int xSrc, int ySrc, int dwRop); [DllImport(ExternDll.Gdi32, ExactSpelling = true, CharSet = CharSet.Auto)] public static extern bool BitBlt(IntPtr hDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool ShowCaret(HandleRef hWnd); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool HideCaret(HandleRef hWnd); [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] - + public static extern uint GetCaretBlinkTime(); // Theming/Visual Styles - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern bool IsAppThemed(); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern int GetThemeAppProperties(); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern void SetThemeAppProperties(int Flags); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern IntPtr OpenThemeData(HandleRef hwnd, [MarshalAs(UnmanagedType.LPWStr)] string pszClassList); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern int CloseThemeData(HandleRef hTheme); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern int GetCurrentThemeName(StringBuilder pszThemeFileName, int dwMaxNameChars, StringBuilder pszColorBuff, int dwMaxColorChars, StringBuilder pszSizeBuff, int cchMaxSizeChars); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern bool IsThemePartDefined(HandleRef hTheme, int iPartId, int iStateId); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern int DrawThemeBackground(HandleRef hTheme, HandleRef hdc, int partId, int stateId, [In] NativeMethods.COMRECT pRect, [In] NativeMethods.COMRECT pClipRect); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern int DrawThemeEdge(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, [In] NativeMethods.COMRECT pDestRect, int uEdge, int uFlags, [Out] NativeMethods.COMRECT pContentRect); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern int DrawThemeParentBackground(HandleRef hwnd, HandleRef hdc, [In] NativeMethods.COMRECT prc); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern int DrawThemeText(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, [MarshalAs(UnmanagedType.LPWStr)] string pszText, int iCharCount, int dwTextFlags, int dwTextFlags2, [In] NativeMethods.COMRECT pRect); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern int GetThemeBackgroundContentRect(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, [In] NativeMethods.COMRECT pBoundingRect, [Out] NativeMethods.COMRECT pContentRect); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern int GetThemeBackgroundExtent(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, [In] NativeMethods.COMRECT pContentRect, [Out] NativeMethods.COMRECT pExtentRect); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern int GetThemeBackgroundRegion(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, [In] NativeMethods.COMRECT pRect, ref IntPtr pRegion); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern int GetThemeBool(HandleRef hTheme, int iPartId, int iStateId, int iPropId, ref bool pfVal); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern int GetThemeColor(HandleRef hTheme, int iPartId, int iStateId, int iPropId, ref int pColor); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern int GetThemeEnumValue(HandleRef hTheme, int iPartId, int iStateId, int iPropId, ref int piVal); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern int GetThemeFilename(HandleRef hTheme, int iPartId, int iStateId, int iPropId, StringBuilder pszThemeFilename, int cchMaxBuffChars); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern int GetThemeFont(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, int iPropId, NativeMethods.LOGFONT pFont); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern int GetThemeInt(HandleRef hTheme, int iPartId, int iStateId, int iPropId, ref int piVal); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern int GetThemePartSize(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, [In] NativeMethods.COMRECT prc, System.Windows.Forms.VisualStyles.ThemeSizeType eSize, [Out] NativeMethods.SIZE psz); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern int GetThemePosition(HandleRef hTheme, int iPartId, int iStateId, int iPropId, [Out] NativeMethods.POINT pPoint); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern int GetThemeMargins(HandleRef hTheme, HandleRef hDC, int iPartId, int iStateId, int iPropId, NativeMethods.COMRECT prc, ref NativeMethods.MARGINS margins); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern int GetThemeString(HandleRef hTheme, int iPartId, int iStateId, int iPropId, StringBuilder pszBuff, int cchMaxBuffChars); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] public static extern int GetThemeDocumentationProperty([MarshalAs(UnmanagedType.LPWStr)] string pszThemeName, [MarshalAs(UnmanagedType.LPWStr)] string pszPropertyName, StringBuilder pszValueBuff, int cchMaxValChars); public static class VisualStyleDocProperty @@ -788,22 +809,22 @@ public static class VisualStyleDocProperty public const string Description = "Description"; } - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] public static extern int GetThemeTextExtent(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, [MarshalAs(UnmanagedType.LPWStr)] string pszText, int iCharCount, int dwTextFlags, [In] NativeMethods.COMRECT pBoundingRect, [Out] NativeMethods.COMRECT pExtentRect); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern int GetThemeTextMetrics(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, ref System.Windows.Forms.VisualStyles.TextMetrics ptm); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - - public static extern int HitTestThemeBackground(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, int dwOptions, [In] NativeMethods.COMRECT pRect, HandleRef hrgn, [In] NativeMethods.POINTSTRUCT ptTest, ref int pwHitTestCode); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + + public static extern int HitTestThemeBackground(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, int dwOptions, [In] NativeMethods.COMRECT pRect, HandleRef hrgn, [In] NativeMethods.POINTSTRUCT ptTest, ref int pwHitTestCode); + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] + public static extern bool IsThemeBackgroundPartiallyTransparent(HandleRef hTheme, int iPartId, int iStateId); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] public static extern bool GetThemeSysBool(HandleRef hTheme, int iBoolId); - [DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)] + [DllImport(ExternDll.Uxtheme, CharSet = CharSet.Auto)] public static extern int GetThemeSysInt(HandleRef hTheme, int iIntId, ref int piValue); public static class VisualStyleSystemProperty @@ -813,56 +834,56 @@ public static class VisualStyleSystemProperty } [DllImportAttribute(ExternDll.User32)] - + public static extern IntPtr OpenInputDesktop(int dwFlags, [MarshalAs(UnmanagedType.Bool)] bool fInherit, int dwDesiredAccess); [DllImportAttribute(ExternDll.User32)] - + public static extern bool CloseDesktop(IntPtr hDesktop); // for Windows Windows 7 to Windows 8. [DllImport(ExternDll.User32, SetLastError = true)] - + public static extern bool IsProcessDPIAware(); // for Windows Windows 7 to Windows 8. [DllImport(ExternDll.User32, SetLastError = true)] - + public static extern bool SetProcessDPIAware(); // for Windows 8.1 and above [DllImport(ExternDll.ShCore, SetLastError = true)] - + public static extern int SetProcessDpiAwareness(NativeMethods.PROCESS_DPI_AWARENESS awareness); // for Windows 8.1 and above [DllImport(ExternDll.ShCore, SetLastError = true)] - + public static extern int GetProcessDpiAwareness(IntPtr processHandle, out NativeMethods.PROCESS_DPI_AWARENESS awareness); // for Windows 10 version RS2 and above [DllImport(ExternDll.User32, SetLastError = true)] - + public static extern bool IsValidDpiAwarenessContext(int dpiFlag); // for Windows 10 version RS2 and above [DllImport(ExternDll.User32, SetLastError = true)] - + public static extern bool SetProcessDpiAwarenessContext(int dpiFlag); // Available in Windows 10 version RS1 and above. [DllImport(ExternDll.User32)] - + public static extern int GetThreadDpiAwarenessContext(); // Available in Windows 10 version RS1 and above. [DllImport(ExternDll.User32)] - + public static extern int GetWindowDpiAwarenessContext(IntPtr hWnd); // Available in Windows 10 version RS1 and above. [DllImport(ExternDll.User32)] - + public static extern bool AreDpiAwarenessContextsEqual(int dpiContextA, int dpiContextB); [DllImport(ExternDll.Kernel32, SetLastError = true)] @@ -878,7 +899,8 @@ public static class VisualStyleSystemProperty internal const int PROCESS_VM_READ = 0x0010; // Color conversion - public static int RGBToCOLORREF(int rgbValue) { + public static int RGBToCOLORREF(int rgbValue) + { // clear the A value, swap R & B values int bValue = (rgbValue & 0xFF) << 16; @@ -890,35 +912,38 @@ public static int RGBToCOLORREF(int rgbValue) { return rgbValue; } - public static Color ColorFromCOLORREF(int colorref) { + public static Color ColorFromCOLORREF(int colorref) + { int r = colorref & 0xFF; int g = (colorref >> 8) & 0xFF; int b = (colorref >> 16) & 0xFF; return Color.FromArgb(r, g, b); } - public static int ColorToCOLORREF(Color color) { + public static int ColorToCOLORREF(Color color) + { return (int)color.R | ((int)color.G << 8) | ((int)color.B << 16); } [ComImport(), Guid("BEF6E003-A874-101A-8BBA-00AA00300CAB"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] - public interface IFontDisp { + public interface IFontDisp + { - string Name {get; set;} + string Name { get; set; } - long Size {get;set;} + long Size { get; set; } - bool Bold {get;set;} + bool Bold { get; set; } - bool Italic {get;set;} + bool Italic { get; set; } - bool Underline {get;set;} + bool Underline { get; set; } - bool Strikethrough {get;set;} + bool Strikethrough { get; set; } - short Weight {get;set;} + short Weight { get; set; } - short Charset {get;set;} + short Charset { get; set; } } } } diff --git a/src/Common/src/UnsafeNativeMethods.cs b/src/Common/src/UnsafeNativeMethods.cs index 99b86f99bc6..fb86df877b9 100644 --- a/src/Common/src/UnsafeNativeMethods.cs +++ b/src/Common/src/UnsafeNativeMethods.cs @@ -5,67 +5,68 @@ using System.Diagnostics.CodeAnalysis; using System.Runtime.Versioning; -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Boolean,System.Int32):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Boolean,System.Int32):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32[]):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.IntPtr):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Object&):System.Int32")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Object&):System.Int32")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Runtime.InteropServices.HandleRef):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.String):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Text.StringBuilder):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+CHARFORMAT2A):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+CHARFORMATA):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+CHARFORMATW):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+CHARRANGE):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+EDITSTREAM):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+EDITSTREAM64):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+FINDTEXT):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+HDLAYOUT&):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LOGFONT):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVBKIMAGE):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVCOLUMN):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVCOLUMN_T):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVFINDINFO&):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVGROUP):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVHITTESTINFO&):System.Int32")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVHITTESTINFO&):System.Int32")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVHITTESTINFO):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVINSERTMARK):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVINSERTMARK):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVITEM&):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVTILEVIEWINFO):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVTILEVIEWINFO):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+MCHITTESTINFO):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+MSG):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+MSG):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+PARAFORMAT):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+POINT):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+RECT&):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+SIZE):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+SYSTEMTIME):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+SYSTEMTIMEARRAY):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TBBUTTON&):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TBBUTTONINFO&):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TCITEM_T):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TEXTRANGE):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TOOLINFO_T):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TOOLINFO_TOOLTIP):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TV_HITTESTINFO):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TV_INSERTSTRUCT&):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TV_ITEM&):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Runtime.InteropServices.HandleRef,System.Int32):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Windows.Forms.NativeMethods+GETTEXTLENGTHEX,System.Int32):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Drawing.Rectangle&):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Windows.Forms.NativeMethods+POINT,System.Int32):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.PostMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.IntPtr):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.PostMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.IntPtr):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods..ctor()")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods+SMsoComponentManager..ctor()")] - -namespace System.Windows.Forms { +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Boolean,System.Int32):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Boolean,System.Int32):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32[]):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.IntPtr):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Object&):System.Int32")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Object&):System.Int32")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Runtime.InteropServices.HandleRef):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.String):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Text.StringBuilder):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+CHARFORMAT2A):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+CHARFORMATA):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+CHARFORMATW):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+CHARRANGE):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+EDITSTREAM):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+EDITSTREAM64):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+FINDTEXT):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+HDLAYOUT&):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LOGFONT):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVBKIMAGE):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVCOLUMN):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVCOLUMN_T):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVFINDINFO&):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVGROUP):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVHITTESTINFO&):System.Int32")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVHITTESTINFO&):System.Int32")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVHITTESTINFO):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVINSERTMARK):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVINSERTMARK):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVITEM&):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVTILEVIEWINFO):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVTILEVIEWINFO):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+MCHITTESTINFO):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+MSG):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+MSG):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+PARAFORMAT):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+POINT):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+RECT&):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+SIZE):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+SYSTEMTIME):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+SYSTEMTIMEARRAY):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TBBUTTON&):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TBBUTTONINFO&):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TCITEM_T):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TEXTRANGE):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TOOLINFO_T):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TOOLINFO_TOOLTIP):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TV_HITTESTINFO):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TV_INSERTSTRUCT&):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TV_ITEM&):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Runtime.InteropServices.HandleRef,System.Int32):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Windows.Forms.NativeMethods+GETTEXTLENGTHEX,System.Int32):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Drawing.Rectangle&):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Windows.Forms.NativeMethods+POINT,System.Int32):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.PostMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.IntPtr):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.PostMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.IntPtr):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods..ctor()")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods+SMsoComponentManager..ctor()")] + +namespace System.Windows.Forms +{ using Accessibility; using System.Runtime.CompilerServices; @@ -82,21 +83,22 @@ namespace System.Windows.Forms { using IComDataObject = System.Runtime.InteropServices.ComTypes.IDataObject; - internal static class UnsafeNativeMethods { + internal static class UnsafeNativeMethods + { + + [DllImport(ExternDll.Shlwapi, CharSet = CharSet.Unicode, ExactSpelling = true)] - [DllImport(ExternDll.Shlwapi, CharSet=CharSet.Unicode, ExactSpelling=true)] - internal static extern uint SHLoadIndirectString(string pszSource, StringBuilder pszOutBuf, uint cchOutBuf, IntPtr ppvReserved); - + [DllImport(ExternDll.Ole32)] - + public static extern int ReadClassStg(HandleRef pStg, [In, Out] ref Guid pclsid); [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] public static extern int GetMessageTime(); [DllImport(ExternDll.User32)] - + public static extern int GetClassName(HandleRef hwnd, StringBuilder lpClassName, int nMaxCount); //SetClassLong won't work correctly for 64-bit: we should use SetClassLongPtr instead. On @@ -113,15 +115,15 @@ public static IntPtr SetClassLong(HandleRef hWnd, int nIndex, IntPtr dwNewLong) } [DllImport(ExternDll.User32, CharSet = System.Runtime.InteropServices.CharSet.Auto, EntryPoint = "SetClassLong")] [SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable")] - + public static extern IntPtr SetClassLongPtr32(HandleRef hwnd, int nIndex, IntPtr dwNewLong); [SuppressMessage("Microsoft.Interoperability", "CA1400:PInvokeEntryPointsShouldExist")] [DllImport(ExternDll.User32, CharSet = System.Runtime.InteropServices.CharSet.Auto, EntryPoint = "SetClassLongPtr")] - + public static extern IntPtr SetClassLongPtr64(HandleRef hwnd, int nIndex, IntPtr dwNewLong); - [DllImport(ExternDll.Ole32, ExactSpelling=true, PreserveSig=false)] - + [DllImport(ExternDll.Ole32, ExactSpelling = true, PreserveSig = false)] + public static extern UnsafeNativeMethods.IClassFactory2 CoGetClassObject( [In] ref Guid clsid, @@ -130,8 +132,9 @@ public static extern UnsafeNativeMethods.IClassFactory2 CoGetClassObject( [In] ref Guid refiid); - [return: MarshalAs(UnmanagedType.Interface)][DllImport(ExternDll.Ole32, ExactSpelling=true, PreserveSig=false)] - + [return: MarshalAs(UnmanagedType.Interface)] + [DllImport(ExternDll.Ole32, ExactSpelling = true, PreserveSig = false)] + public static extern object CoCreateInstance( [In] ref Guid clsid, @@ -142,107 +145,114 @@ public static extern object CoCreateInstance( ref Guid iid); //This marshals differently than NativeMethods.POINTSTRUCT - internal struct POINTSTRUCT { + internal struct POINTSTRUCT + { public int x; public int y; - public POINTSTRUCT(int x, int y) { + public POINTSTRUCT(int x, int y) + { this.x = x; this.y = y; } } - [DllImport(ExternDll.Kernel32, CharSet=System.Runtime.InteropServices.CharSet.Auto)] - - public static extern int GetLocaleInfo(int Locale,int LCType,StringBuilder lpLCData,int cchData) ; + [DllImport(ExternDll.Kernel32, CharSet = System.Runtime.InteropServices.CharSet.Auto)] + + public static extern int GetLocaleInfo(int Locale, int LCType, StringBuilder lpLCData, int cchData); [DllImport(ExternDll.Ole32)] - + public static extern int WriteClassStm(IStream pStream, ref Guid clsid); [DllImport(ExternDll.Ole32)] - + public static extern int ReadClassStg(IStorage pStorage, [Out]out Guid clsid); [DllImport(ExternDll.Ole32)] - + public static extern int ReadClassStm(IStream pStream, [Out]out Guid clsid); [DllImport(ExternDll.Ole32)] - + public static extern int OleLoadFromStream(IStream pStorage, ref Guid iid, out IOleObject pObject); [DllImport(ExternDll.Ole32)] - + public static extern int OleSaveToStream(IPersistStream pPersistStream, IStream pStream); [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] public static extern int GetWindowThreadProcessId(HandleRef hWnd, out int lpdwProcessId); - [DllImport(ExternDll.Comdlg32, SetLastError=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Comdlg32, SetLastError = true, CharSet = CharSet.Auto)] + public static extern bool PageSetupDlg([In, Out] NativeMethods.PAGESETUPDLG lppsd); [DllImport(ExternDll.Comdlg32, EntryPoint = "PrintDlg", SetLastError = true, CharSet = CharSet.Auto)] - + public static extern bool PrintDlg_32([In, Out] NativeMethods.PRINTDLG_32 lppd); [DllImport(ExternDll.Comdlg32, EntryPoint = "PrintDlg", SetLastError = true, CharSet = CharSet.Auto)] - + public static extern bool PrintDlg_64([In, Out] NativeMethods.PRINTDLG_64 lppd); - public static bool PrintDlg([In, Out] NativeMethods.PRINTDLG lppd) { - if (IntPtr.Size == 4) { + public static bool PrintDlg([In, Out] NativeMethods.PRINTDLG lppd) + { + if (IntPtr.Size == 4) + { NativeMethods.PRINTDLG_32 lppd_32 = lppd as NativeMethods.PRINTDLG_32; - if (lppd_32 == null) { + if (lppd_32 == null) + { throw new System.NullReferenceException("PRINTDLG data is null"); } return PrintDlg_32(lppd_32); } - else { + else + { NativeMethods.PRINTDLG_64 lppd_64 = lppd as NativeMethods.PRINTDLG_64; - if (lppd_64 == null) { + if (lppd_64 == null) + { throw new System.NullReferenceException("PRINTDLG data is null"); } return PrintDlg_64(lppd_64); } } - [DllImport(ExternDll.Comdlg32, SetLastError=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Comdlg32, SetLastError = true, CharSet = CharSet.Auto)] + public static extern int PrintDlgEx([In, Out] NativeMethods.PRINTDLGEX lppdex); - [DllImport(ExternDll.Ole32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Ole32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int OleGetClipboard(ref IComDataObject data); - [DllImport(ExternDll.Ole32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Ole32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int OleSetClipboard(IComDataObject pDataObj); - [DllImport(ExternDll.Ole32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Ole32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int OleFlushClipboard(); - [DllImport(ExternDll.Oleaut32, ExactSpelling=true)] - + [DllImport(ExternDll.Oleaut32, ExactSpelling = true)] + public static extern void OleCreatePropertyFrameIndirect(NativeMethods.OCPFIPARAMS p); [DllImport(ExternDll.Oleaut32, EntryPoint = "OleCreateFontIndirect", ExactSpelling = true, PreserveSig = false)] - + public static extern UnsafeNativeMethods.IFont OleCreateIFontIndirect(NativeMethods.FONTDESC fd, ref Guid iid); [DllImport(ExternDll.Oleaut32, EntryPoint = "OleCreatePictureIndirect", ExactSpelling = true, PreserveSig = false)] - + public static extern UnsafeNativeMethods.IPicture OleCreateIPictureIndirect([MarshalAs(UnmanagedType.AsAny)]object pictdesc, ref Guid iid, bool fOwn); [DllImport(ExternDll.Oleaut32, EntryPoint = "OleCreatePictureIndirect", ExactSpelling = true, PreserveSig = false)] - + public static extern UnsafeNativeMethods.IPictureDisp OleCreateIPictureDispIndirect([MarshalAs(UnmanagedType.AsAny)] object pictdesc, ref Guid iid, bool fOwn); // cpb: #8309 -- next two methods, refiid arg must be IPicture.iid [DllImport(ExternDll.Oleaut32, PreserveSig = false)] - + public static extern UnsafeNativeMethods.IPicture OleCreatePictureIndirect(NativeMethods.PICTDESC pictdesc, [In]ref Guid refiid, bool fOwn); [DllImport(ExternDll.Oleaut32, PreserveSig = false)] - + public static extern UnsafeNativeMethods.IFont OleCreateFontIndirect(NativeMethods.tagFONTDESC fontdesc, [In]ref Guid refiid); [DllImport(ExternDll.Oleaut32, ExactSpelling = true)] - + public static extern int VarFormat(ref object pvarIn, HandleRef pstrFormat, int iFirstDay, int iFirstWeek, uint dwFlags, [In, Out]ref IntPtr pbstr); - [DllImport(ExternDll.Shell32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Shell32, CharSet = CharSet.Auto)] + public static extern int DragQueryFile(HandleRef hDrop, int iFile, StringBuilder lpszFile, int cch); public static int DragQueryFileLongPath(HandleRef hDrop, int iFile, StringBuilder lpszFile) @@ -277,131 +287,133 @@ public static int DragQueryFileLongPath(HandleRef hDrop, int iFile, StringBuilde return DragQueryFile(hDrop, iFile, lpszFile, lpszFile.Capacity); } } - [DllImport(ExternDll.User32, ExactSpelling=true)] - + [DllImport(ExternDll.User32, ExactSpelling = true)] + public static extern bool EnumChildWindows(HandleRef hwndParent, NativeMethods.EnumChildrenCallback lpEnumFunc, HandleRef lParam); - [DllImport(ExternDll.Shell32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Shell32, CharSet = CharSet.Auto)] + public static extern IntPtr ShellExecute(HandleRef hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd); - [DllImport(ExternDll.Shell32, CharSet=CharSet.Auto, EntryPoint="ShellExecute", BestFitMapping = false)] - + [DllImport(ExternDll.Shell32, CharSet = CharSet.Auto, EntryPoint = "ShellExecute", BestFitMapping = false)] + public static extern IntPtr ShellExecute_NoBFM(HandleRef hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto, SetLastError=true)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)] + public static extern int SetScrollPos(HandleRef hWnd, int nBar, int nPos, bool bRedraw); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto, SetLastError=true)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)] + public static extern bool EnableScrollBar(HandleRef hWnd, int nBar, int value); - [DllImport(ExternDll.Shell32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Shell32, CharSet = CharSet.Auto)] + public static extern int Shell_NotifyIcon(int message, NativeMethods.NOTIFYICONDATA pnid); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public extern static bool InsertMenuItem(HandleRef hMenu, int uItem, bool fByPosition, NativeMethods.MENUITEMINFO_T lpmii); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - - public static extern IntPtr GetMenu(HandleRef hWnd); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + + public static extern IntPtr GetMenu(HandleRef hWnd); + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern bool GetMenuItemInfo(HandleRef hMenu, int uItem, bool fByPosition, [In, Out] NativeMethods.MENUITEMINFO_T lpmii); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern bool GetMenuItemInfo(HandleRef hMenu, int uItem, bool fByPosition, [In, Out] NativeMethods.MENUITEMINFO_T_RW lpmii); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public extern static bool SetMenuItemInfo(HandleRef hMenu, int uItem, bool fByPosition, NativeMethods.MENUITEMINFO_T lpmii); - [DllImport(ExternDll.User32, ExactSpelling=true, EntryPoint="CreateMenu", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, EntryPoint = "CreateMenu", CharSet = CharSet.Auto)] + private static extern IntPtr IntCreateMenu(); - - - public static IntPtr CreateMenu() { + + + public static IntPtr CreateMenu() + { return Interop.HandleCollector.Add(IntCreateMenu(), Interop.CommonHandles.Menu); } - - [DllImport(ExternDll.Comdlg32, SetLastError=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Comdlg32, SetLastError = true, CharSet = CharSet.Auto)] + public static extern bool GetOpenFileName([In, Out] NativeMethods.OPENFILENAME_I ofn); - [DllImport(ExternDll.User32, ExactSpelling=true)] - + [DllImport(ExternDll.User32, ExactSpelling = true)] + public static extern bool EndDialog(HandleRef hWnd, IntPtr result); public const int MB_PRECOMPOSED = 0x00000001; - [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Unicode, SetLastError=true)] - + [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] + public static extern int MultiByteToWideChar(int CodePage, int dwFlags, byte[] lpMultiByteStr, int cchMultiByte, char[] lpWideCharStr, int cchWideChar); - [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Unicode)] - - public static extern int WideCharToMultiByte(int codePage, int flags, [MarshalAs(UnmanagedType.LPWStr)]string wideStr, int chars, [In,Out]byte[] pOutBytes, int bufferBytes, IntPtr defaultChar, IntPtr pDefaultUsed); + [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Unicode)] + + public static extern int WideCharToMultiByte(int codePage, int flags, [MarshalAs(UnmanagedType.LPWStr)]string wideStr, int chars, [In, Out]byte[] pOutBytes, int bufferBytes, IntPtr defaultChar, IntPtr pDefaultUsed); + + [DllImport(ExternDll.Kernel32, SetLastError = true, ExactSpelling = true, EntryPoint = "RtlMoveMemory", CharSet = CharSet.Auto)] - [DllImport(ExternDll.Kernel32, SetLastError=true, ExactSpelling=true, EntryPoint="RtlMoveMemory", CharSet=CharSet.Auto)] - public static extern void CopyMemory(HandleRef destData, HandleRef srcData, int size); - [DllImport(ExternDll.Kernel32, ExactSpelling=true, EntryPoint="RtlMoveMemory")] - + [DllImport(ExternDll.Kernel32, ExactSpelling = true, EntryPoint = "RtlMoveMemory")] + public static extern void CopyMemory(IntPtr pdst, byte[] psrc, int cb); [DllImport(ExternDll.Kernel32, ExactSpelling = true, EntryPoint = "RtlMoveMemory", CharSet = CharSet.Unicode)] - + public static extern void CopyMemoryW(IntPtr pdst, string psrc, int cb); [DllImport(ExternDll.Kernel32, ExactSpelling = true, EntryPoint = "RtlMoveMemory", CharSet = CharSet.Unicode)] - + public static extern void CopyMemoryW(IntPtr pdst, char[] psrc, int cb); [DllImport(ExternDll.Kernel32, ExactSpelling = true, EntryPoint = "RtlMoveMemory", CharSet = CharSet.Ansi)] - + public static extern void CopyMemoryA(IntPtr pdst, string psrc, int cb); [DllImport(ExternDll.Kernel32, ExactSpelling = true, EntryPoint = "RtlMoveMemory", CharSet = CharSet.Ansi)] - + public static extern void CopyMemoryA(IntPtr pdst, char[] psrc, int cb); - - - [DllImport(ExternDll.Kernel32, ExactSpelling=true, EntryPoint="DuplicateHandle", SetLastError=true)] - + + + [DllImport(ExternDll.Kernel32, ExactSpelling = true, EntryPoint = "DuplicateHandle", SetLastError = true)] + private static extern IntPtr IntDuplicateHandle(HandleRef processSource, HandleRef handleSource, HandleRef processTarget, ref IntPtr handleTarget, int desiredAccess, bool inheritHandle, int options); - - - public static IntPtr DuplicateHandle(HandleRef processSource, HandleRef handleSource, HandleRef processTarget, ref IntPtr handleTarget, int desiredAccess, bool inheritHandle, int options) { + + + public static IntPtr DuplicateHandle(HandleRef processSource, HandleRef handleSource, HandleRef processTarget, ref IntPtr handleTarget, int desiredAccess, bool inheritHandle, int options) + { IntPtr ret = IntDuplicateHandle(processSource, handleSource, processTarget, ref handleTarget, desiredAccess, inheritHandle, options); Interop.HandleCollector.Add(handleTarget, Interop.CommonHandles.Kernel); return ret; } - - [DllImport(ExternDll.Ole32, PreserveSig=false)] - + + [DllImport(ExternDll.Ole32, PreserveSig = false)] + public static extern UnsafeNativeMethods.IStorage StgOpenStorageOnILockBytes(UnsafeNativeMethods.ILockBytes iLockBytes, UnsafeNativeMethods.IStorage pStgPriority, int grfMode, int sndExcluded, int reserved); - [DllImport(ExternDll.Ole32, PreserveSig=false)] - + [DllImport(ExternDll.Ole32, PreserveSig = false)] + public static extern IntPtr GetHGlobalFromILockBytes(UnsafeNativeMethods.ILockBytes pLkbyt); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SetWindowsHookEx(int hookid, NativeMethods.HookProc pfnhook, HandleRef hinst, int threadid); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - - public static extern int GetKeyboardState(byte [] keystate); - [DllImport(ExternDll.User32, ExactSpelling=true, EntryPoint="keybd_event", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + + public static extern int GetKeyboardState(byte[] keystate); + [DllImport(ExternDll.User32, ExactSpelling = true, EntryPoint = "keybd_event", CharSet = CharSet.Auto)] + public static extern void Keybd_event(byte vk, byte scan, int flags, int extrainfo); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - - public static extern int SetKeyboardState(byte [] keystate); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + + public static extern int SetKeyboardState(byte[] keystate); + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool UnhookWindowsHookEx(HandleRef hhook); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern short GetAsyncKeyState(int vkey); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr CallNextHookEx(HandleRef hhook, int code, IntPtr wparam, IntPtr lparam); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - - public static extern int ScreenToClient( HandleRef hWnd, [In, Out] NativeMethods.POINT pt ); - [DllImport(ExternDll.Kernel32, CharSet=CharSet.Auto, SetLastError = true)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + + public static extern int ScreenToClient(HandleRef hWnd, [In, Out] NativeMethods.POINT pt); + [DllImport(ExternDll.Kernel32, CharSet = CharSet.Auto, SetLastError = true)] + public static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length); public static StringBuilder GetModuleFileNameLongPath(HandleRef hModule) { @@ -410,8 +422,8 @@ public static StringBuilder GetModuleFileNameLongPath(HandleRef hModule) int length = 0; // Iterating by allocating chunk of memory each time we find the length is not sufficient. // Performance should not be an issue for current MAX_PATH length due to this change. - while (((length = GetModuleFileName(hModule, buffer, buffer.Capacity)) == buffer.Capacity) - && Marshal.GetLastWin32Error() == NativeMethods.ERROR_INSUFFICIENT_BUFFER + while (((length = GetModuleFileName(hModule, buffer, buffer.Capacity)) == buffer.Capacity) + && Marshal.GetLastWin32Error() == NativeMethods.ERROR_INSUFFICIENT_BUFFER && buffer.Capacity < Interop.Kernel32.MAX_UNICODESTRING_LEN) { noOfTimes += 2; // Increasing buffer size by 520 in each iteration. @@ -421,82 +433,87 @@ public static StringBuilder GetModuleFileNameLongPath(HandleRef hModule) buffer.Length = length; return buffer; } - [DllImport(ExternDll.User32, CharSet=CharSet.Unicode)] - - public static extern bool IsDialogMessage(HandleRef hWndDlg, [In, Out] ref NativeMethods.MSG msg); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Unicode)] + + public static extern bool IsDialogMessage(HandleRef hWndDlg, [In, Out] ref NativeMethods.MSG msg); + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool TranslateMessage([In, Out] ref NativeMethods.MSG msg); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr DispatchMessage([In] ref NativeMethods.MSG msg); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Ansi)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Ansi)] + public static extern IntPtr DispatchMessageA([In] ref NativeMethods.MSG msg); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Unicode)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Unicode)] + public static extern IntPtr DispatchMessageW([In] ref NativeMethods.MSG msg); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern int PostThreadMessage(int id, int msg, IntPtr wparam, IntPtr lparam); - [DllImport(ExternDll.Ole32, ExactSpelling=true)] - + [DllImport(ExternDll.Ole32, ExactSpelling = true)] + public static extern int CoRegisterMessageFilter(HandleRef newFilter, ref IntPtr oldMsgFilter); - [DllImport(ExternDll.Ole32, ExactSpelling=true, EntryPoint="OleInitialize", SetLastError=true)] - + [DllImport(ExternDll.Ole32, ExactSpelling = true, EntryPoint = "OleInitialize", SetLastError = true)] + private static extern int IntOleInitialize(int val); - public static int OleInitialize() { + public static int OleInitialize() + { return IntOleInitialize(0); } - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public extern static bool EnumThreadWindows(int dwThreadId, NativeMethods.EnumThreadWindowsCallback lpfn, HandleRef lParam); - [return:MarshalAs(UnmanagedType.Bool)] [DllImport(ExternDll.Kernel32, SetLastError=true)] - + [return: MarshalAs(UnmanagedType.Bool)] + [DllImport(ExternDll.Kernel32, SetLastError = true)] + public extern static bool GetExitCodeThread(IntPtr hThread, out uint lpExitCode); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public extern static IntPtr SendDlgItemMessage(HandleRef hDlg, int nIDDlgItem, int Msg, IntPtr wParam, IntPtr lParam); - [DllImport(ExternDll.Ole32, ExactSpelling=true, CharSet=CharSet.Auto, SetLastError=true)] - + [DllImport(ExternDll.Ole32, ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)] + public static extern int OleUninitialize(); - [DllImport(ExternDll.Comdlg32, SetLastError=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Comdlg32, SetLastError = true, CharSet = CharSet.Auto)] + public static extern bool GetSaveFileName([In, Out] NativeMethods.OPENFILENAME_I ofn); - [DllImport(ExternDll.User32, EntryPoint="ChildWindowFromPointEx", ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, EntryPoint = "ChildWindowFromPointEx", ExactSpelling = true, CharSet = CharSet.Auto)] + private static extern IntPtr _ChildWindowFromPointEx(HandleRef hwndParent, POINTSTRUCT pt, int uFlags); - public static IntPtr ChildWindowFromPointEx(HandleRef hwndParent, int x, int y, int uFlags) { + public static IntPtr ChildWindowFromPointEx(HandleRef hwndParent, int x, int y, int uFlags) + { POINTSTRUCT ps = new POINTSTRUCT(x, y); return _ChildWindowFromPointEx(hwndParent, ps, uFlags); } - [DllImport(ExternDll.Kernel32, EntryPoint="CloseHandle", ExactSpelling=true, CharSet=CharSet.Auto, SetLastError=true)] - + [DllImport(ExternDll.Kernel32, EntryPoint = "CloseHandle", ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)] + private static extern bool IntCloseHandle(HandleRef handle); - public static bool CloseHandle(HandleRef handle) { + public static bool CloseHandle(HandleRef handle) + { Interop.HandleCollector.Remove((IntPtr)handle, Interop.CommonHandles.Kernel); return IntCloseHandle(handle); } - - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreateCompatibleDC", CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateCompatibleDC", CharSet = CharSet.Auto)] + private static extern IntPtr IntCreateCompatibleDC(HandleRef hDC); - - - public static IntPtr CreateCompatibleDC(HandleRef hDC) { + + + public static IntPtr CreateCompatibleDC(HandleRef hDC) + { return Interop.HandleCollector.Add(IntCreateCompatibleDC(hDC), Interop.CommonHandles.CompatibleHDC); } #region SendKeys SendInput functionality [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] - + [return: MarshalAs(UnmanagedType.Bool)] public static extern bool BlockInput([In, MarshalAs(UnmanagedType.Bool)] bool fBlockIt); - [DllImport(ExternDll.User32, ExactSpelling = true, SetLastError=true, CharSet = CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)] + public static extern uint SendInput(uint nInputs, NativeMethods.INPUT[] pInputs, int cbSize); #endregion @@ -515,114 +532,124 @@ public static IntPtr OpenFileMapping(int dwDesiredAccess, bool bInheritHandle, s } */ - [DllImport(ExternDll.Kernel32, EntryPoint = "MapViewOfFile", ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)] - + [DllImport(ExternDll.Kernel32, EntryPoint = "MapViewOfFile", ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)] + [SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable")] private static extern IntPtr IntMapViewOfFile(HandleRef hFileMapping, int dwDesiredAccess, int dwFileOffsetHigh, int dwFileOffsetLow, int dwNumberOfBytesToMap); - - - public static IntPtr MapViewOfFile(HandleRef hFileMapping, int dwDesiredAccess, int dwFileOffsetHigh, int dwFileOffsetLow, int dwNumberOfBytesToMap) { + + + public static IntPtr MapViewOfFile(HandleRef hFileMapping, int dwDesiredAccess, int dwFileOffsetHigh, int dwFileOffsetLow, int dwNumberOfBytesToMap) + { return Interop.HandleCollector.Add(IntMapViewOfFile(hFileMapping, dwDesiredAccess, dwFileOffsetHigh, dwFileOffsetLow, dwNumberOfBytesToMap), Interop.CommonHandles.Kernel); } [DllImport(ExternDll.Kernel32, EntryPoint = "UnmapViewOfFile", ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)] - + private static extern bool IntUnmapViewOfFile(HandleRef pvBaseAddress); - public static bool UnmapViewOfFile(HandleRef pvBaseAddress) { + public static bool UnmapViewOfFile(HandleRef pvBaseAddress) + { Interop.HandleCollector.Remove((IntPtr)pvBaseAddress, Interop.CommonHandles.Kernel); return IntUnmapViewOfFile(pvBaseAddress); } [DllImport(ExternDll.User32, ExactSpelling = true, EntryPoint = "GetDCEx", CharSet = CharSet.Auto)] - + private static extern IntPtr IntGetDCEx(HandleRef hWnd, HandleRef hrgnClip, int flags); - - - public static IntPtr GetDCEx(HandleRef hWnd, HandleRef hrgnClip, int flags) { + + + public static IntPtr GetDCEx(HandleRef hWnd, HandleRef hrgnClip, int flags) + { return Interop.HandleCollector.Add(IntGetDCEx(hWnd, hrgnClip, flags), Interop.CommonHandles.HDC); } - + // GetObject stuff - [DllImport(ExternDll.Gdi32, SetLastError=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, CharSet = CharSet.Auto)] + public static extern int GetObject(HandleRef hObject, int nSize, [In, Out] NativeMethods.BITMAP bm); - [DllImport(ExternDll.Gdi32, SetLastError=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, CharSet = CharSet.Auto)] + public static extern int GetObject(HandleRef hObject, int nSize, [In, Out] NativeMethods.LOGPEN lp); - public static int GetObject(HandleRef hObject, NativeMethods.LOGPEN lp) { + public static int GetObject(HandleRef hObject, NativeMethods.LOGPEN lp) + { return GetObject(hObject, Marshal.SizeOf(), lp); } - - [DllImport(ExternDll.Gdi32, SetLastError=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Gdi32, SetLastError = true, CharSet = CharSet.Auto)] + public static extern int GetObject(HandleRef hObject, int nSize, [In, Out] NativeMethods.LOGBRUSH lb); - public static int GetObject(HandleRef hObject, NativeMethods.LOGBRUSH lb) { + public static int GetObject(HandleRef hObject, NativeMethods.LOGBRUSH lb) + { return GetObject(hObject, Marshal.SizeOf(), lb); } - - [DllImport(ExternDll.Gdi32, SetLastError=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Gdi32, SetLastError = true, CharSet = CharSet.Auto)] + public static extern int GetObject(HandleRef hObject, int nSize, [In, Out] NativeMethods.LOGFONT lf); - public static int GetObject(HandleRef hObject, NativeMethods.LOGFONT lp) { + public static int GetObject(HandleRef hObject, NativeMethods.LOGFONT lp) + { return GetObject(hObject, Marshal.SizeOf(), lp); } - + //HPALETTE - [DllImport(ExternDll.Gdi32, SetLastError=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, CharSet = CharSet.Auto)] + public static extern int GetObject(HandleRef hObject, int nSize, ref int nEntries); - [DllImport(ExternDll.Gdi32, SetLastError=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, CharSet = CharSet.Auto)] + public static extern int GetObject(HandleRef hObject, int nSize, int[] nEntries); [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] - + public static extern int GetObjectType(HandleRef hObject); - [DllImport(ExternDll.User32, EntryPoint="CreateAcceleratorTable", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, EntryPoint = "CreateAcceleratorTable", CharSet = CharSet.Auto)] + private static extern IntPtr IntCreateAcceleratorTable(/*ACCEL*/ HandleRef pentries, int cCount); - - - public static IntPtr CreateAcceleratorTable(/*ACCEL*/ HandleRef pentries, int cCount) { + + + public static IntPtr CreateAcceleratorTable(/*ACCEL*/ HandleRef pentries, int cCount) + { return Interop.HandleCollector.Add(IntCreateAcceleratorTable(pentries, cCount), Interop.CommonHandles.Accelerator); } - [DllImport(ExternDll.User32, ExactSpelling=true, EntryPoint="DestroyAcceleratorTable", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, EntryPoint = "DestroyAcceleratorTable", CharSet = CharSet.Auto)] + private static extern bool IntDestroyAcceleratorTable(HandleRef hAccel); - public static bool DestroyAcceleratorTable(HandleRef hAccel) { + public static bool DestroyAcceleratorTable(HandleRef hAccel) + { Interop.HandleCollector.Remove((IntPtr)hAccel, Interop.CommonHandles.Accelerator); return IntDestroyAcceleratorTable(hAccel); } - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern short VkKeyScan(char key); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr GetCapture(); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr SetCapture(HandleRef hwnd); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr GetFocus(); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool GetCursorPos([In, Out] NativeMethods.POINT pt); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern short GetKeyState(int keyCode); - [DllImport(ExternDll.Kernel32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Kernel32, CharSet = CharSet.Auto)] + [SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments")] public static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, uint cchBuffer); - [DllImport(ExternDll.User32, ExactSpelling=true, EntryPoint="SetWindowRgn", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, EntryPoint = "SetWindowRgn", CharSet = CharSet.Auto)] + private static extern int IntSetWindowRgn(HandleRef hwnd, HandleRef hrgn, bool fRedraw); - public static int SetWindowRgn(HandleRef hwnd, HandleRef hrgn, bool fRedraw) { + public static int SetWindowRgn(HandleRef hwnd, HandleRef hrgn, bool fRedraw) + { int retval = IntSetWindowRgn(hwnd, hrgn, fRedraw); - if (retval != 0) { + if (retval != 0) + { // we do this because after a SetWindowRgn call, the system owns the region // so we don't need to bother cleaning it up. // @@ -631,373 +658,373 @@ public static int SetWindowRgn(HandleRef hwnd, HandleRef hrgn, bool fRedraw) { return retval; } - [DllImport(ExternDll.Kernel32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Kernel32, CharSet = CharSet.Auto)] + [SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable")] public static extern void GetTempFileName(string tempDirName, string prefixName, int unique, StringBuilder sb); - [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr GlobalAlloc(int uFlags, int dwBytes); - - [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr GlobalReAlloc(HandleRef handle, int bytes, int flags); - [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr GlobalLock(HandleRef handle); - - [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool GlobalUnlock(HandleRef handle); - - [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr GlobalFree(HandleRef handle); - - [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int GlobalSize(HandleRef handle); - - [DllImport(ExternDll.Imm32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Imm32, CharSet = CharSet.Auto)] + public static extern bool ImmSetConversionStatus(HandleRef hIMC, int conversion, int sentence); - - [DllImport(ExternDll.Imm32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Imm32, CharSet = CharSet.Auto)] + public static extern bool ImmGetConversionStatus(HandleRef hIMC, ref int conversion, ref int sentence); - - [DllImport(ExternDll.Imm32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Imm32, CharSet = CharSet.Auto)] + public static extern IntPtr ImmGetContext(HandleRef hWnd); - - [DllImport(ExternDll.Imm32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Imm32, CharSet = CharSet.Auto)] + public static extern bool ImmReleaseContext(HandleRef hWnd, HandleRef hIMC); - - [DllImport(ExternDll.Imm32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Imm32, CharSet = CharSet.Auto)] + public static extern IntPtr ImmAssociateContext(HandleRef hWnd, HandleRef hIMC); - - [DllImport(ExternDll.Imm32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Imm32, CharSet = CharSet.Auto)] + public static extern bool ImmDestroyContext(HandleRef hIMC); - - [DllImport(ExternDll.Imm32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Imm32, CharSet = CharSet.Auto)] + public static extern IntPtr ImmCreateContext(); - - [DllImport(ExternDll.Imm32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Imm32, CharSet = CharSet.Auto)] + public static extern bool ImmSetOpenStatus(HandleRef hIMC, bool open); - - [DllImport(ExternDll.Imm32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Imm32, CharSet = CharSet.Auto)] + public static extern bool ImmGetOpenStatus(HandleRef hIMC); [DllImport(ExternDll.Imm32, CharSet = CharSet.Auto)] - + public static extern bool ImmNotifyIME(HandleRef hIMC, int dwAction, int dwIndex, int dwValue); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr SetFocus(HandleRef hWnd); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr GetParent(HandleRef hWnd); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - - public static extern IntPtr GetAncestor(HandleRef hWnd, int flags); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + + public static extern IntPtr GetAncestor(HandleRef hWnd, int flags); + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool IsChild(HandleRef hWndParent, HandleRef hwnd); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool IsZoomed(HandleRef hWnd); - - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr FindWindow(string className, string windowName); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int MapWindowPoints(HandleRef hWndFrom, HandleRef hWndTo, [In, Out] ref NativeMethods.RECT rect, int cPoints); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int MapWindowPoints(HandleRef hWndFrom, HandleRef hWndTo, [In, Out] NativeMethods.POINT pt, int cPoints); [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] - + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, bool wParam, int lParam); - - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, int[] lParam); - - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int[] wParam, int[] lParam); - - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, ref int wParam, ref int lParam); - - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, string lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, IntPtr wParam, string lParam); - - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, StringBuilder lParam); - - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - - public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, NativeMethods.TOOLINFO_T lParam); - - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, NativeMethods.TOOLINFO_T lParam); + + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, NativeMethods.TOOLINFO_TOOLTIP lParam); - - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - - public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, ref NativeMethods.TBBUTTON lParam); - - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - - public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, ref NativeMethods.TBBUTTONINFO lParam); - - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - - public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, ref NativeMethods.TV_ITEM lParam); - - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, ref NativeMethods.TBBUTTON lParam); + + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, ref NativeMethods.TBBUTTONINFO lParam); + + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, ref NativeMethods.TV_ITEM lParam); + + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, ref NativeMethods.TV_INSERTSTRUCT lParam); - - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, NativeMethods.TV_HITTESTINFO lParam); - - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, NativeMethods.LVBKIMAGE lParam); [DllImport(ExternDll.User32, CharSet = System.Runtime.InteropServices.CharSet.Auto)] [SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable")] public static extern IntPtr SendMessage(IntPtr hwnd, int msg, bool wparam, int lparam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern int SendMessage(HandleRef hWnd, int msg, int wParam, ref NativeMethods.LVHITTESTINFO lParam); - - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, NativeMethods.TCITEM_T lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, ref NativeMethods.HDLAYOUT hdlayout); //for Tooltips // - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, HandleRef wParam, int lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - - public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, HandleRef lParam); + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, HandleRef lParam); // For RichTextBox // - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, [In, Out, MarshalAs(UnmanagedType.LPStruct)] NativeMethods.PARAFORMAT lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, [In, Out, MarshalAs(UnmanagedType.LPStruct)] NativeMethods.CHARFORMATA lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, [In, Out, MarshalAs(UnmanagedType.LPStruct)] NativeMethods.CHARFORMAT2A lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, [In, Out, MarshalAs(UnmanagedType.LPStruct)] NativeMethods.CHARFORMATW lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern int SendMessage(HandleRef hWnd, int msg, int wParam, [Out, MarshalAs(UnmanagedType.IUnknown)]out object editOle); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, NativeMethods.CHARRANGE lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, NativeMethods.FINDTEXT lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, NativeMethods.TEXTRANGE lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, NativeMethods.POINT lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, NativeMethods.POINT wParam, int lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, NativeMethods.EDITSTREAM lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, NativeMethods.EDITSTREAM64 lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, NativeMethods.GETTEXTLENGTHEX wParam, int lParam); // For Button // - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - - public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, [In, Out] NativeMethods.SIZE lParam); - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, [In, Out] NativeMethods.SIZE lParam); + // For ListView // - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, [In, Out] ref NativeMethods.LVFINDINFO lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, NativeMethods.LVHITTESTINFO lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, NativeMethods.LVCOLUMN_T lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, [In, Out] ref NativeMethods.LVITEM lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, NativeMethods.LVCOLUMN lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, NativeMethods.LVGROUP lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, NativeMethods.POINT wParam, [In, Out] NativeMethods.LVINSERTMARK lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern bool SendMessage(HandleRef hWnd, int msg, int wParam, NativeMethods.LVINSERTMARK lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - - public static extern bool SendMessage(HandleRef hWnd, int msg, int wParam, [In, Out] NativeMethods.LVTILEVIEWINFO lParam); - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + + public static extern bool SendMessage(HandleRef hWnd, int msg, int wParam, [In, Out] NativeMethods.LVTILEVIEWINFO lParam); + // For MonthCalendar // - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, NativeMethods.MCHITTESTINFO lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, NativeMethods.SYSTEMTIME lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, NativeMethods.SYSTEMTIMEARRAY lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - - public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, [In, Out] NativeMethods.LOGFONT lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, [In, Out] NativeMethods.LOGFONT lParam); + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, NativeMethods.MSG lParam); [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] - + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, int lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(HandleRef hWnd, int msg, IntPtr wParam, IntPtr lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public extern static IntPtr SendMessage(HandleRef hWnd, int Msg, IntPtr wParam, [In, Out] ref NativeMethods.RECT lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public extern static IntPtr SendMessage(HandleRef hWnd, int Msg, ref short wParam, ref short lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public extern static IntPtr SendMessage(HandleRef hWnd, int Msg, [In, Out, MarshalAs(UnmanagedType.Bool)] ref bool wParam, IntPtr lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public extern static IntPtr SendMessage(HandleRef hWnd, int Msg, int wParam, IntPtr lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public extern static IntPtr SendMessage(HandleRef hWnd, int Msg, int wParam, [In, Out] ref NativeMethods.RECT lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public extern static IntPtr SendMessage(HandleRef hWnd, int Msg, int wParam, [In, Out] ref Rectangle lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public extern static IntPtr SendMessage(HandleRef hWnd, int Msg, IntPtr wParam, NativeMethods.ListViewCompareCallback pfnCompare); - - [DllImport(ExternDll.User32, CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + + [DllImport(ExternDll.User32, CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern IntPtr SendMessageTimeout(HandleRef hWnd, int msg, IntPtr wParam, IntPtr lParam, int flags, int timeout, out IntPtr pdwResult); - public const int SMTO_ABORTIFHUNG = 0x0002; + public const int SMTO_ABORTIFHUNG = 0x0002; + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - public static extern IntPtr SetParent(HandleRef hWnd, HandleRef hWndParent); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool GetWindowRect(HandleRef hWnd, [In, Out] ref NativeMethods.RECT rect); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr GetWindow(HandleRef hWnd, int uCmd); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] public static extern IntPtr GetWindow(IntPtr hWnd, int uCmd); [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] public static extern IntPtr GetDlgItem(HandleRef hWnd, int nIDDlgItem); - [DllImport(ExternDll.Kernel32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Kernel32, CharSet = CharSet.Auto)] + public static extern IntPtr GetModuleHandle(string modName); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr DefWindowProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr DefMDIChildProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr CallWindowProc(IntPtr wndProc, IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); - [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern short GlobalDeleteAtom(short atom); - [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Ansi)] - + [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Ansi)] + public static extern IntPtr GetProcAddress(HandleRef hModule, string lpProcName); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern bool GetClassInfo(HandleRef hInst, string lpszClass, [In, Out] NativeMethods.WNDCLASS_I wc); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern bool GetClassInfo(HandleRef hInst, string lpszClass, IntPtr h); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int GetSystemMetrics(int nIndex); - + // This API is available starting Windows10 RS1 - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int GetSystemMetricsForDpi(int nIndex, uint dpi); [DllImport(ExternDll.Gdi32, CharSet = CharSet.Auto)] @@ -1009,154 +1036,162 @@ public static extern IntPtr CallWindowProc(IntPtr wndProc, IntPtr hWnd, int msg, /// index /// dpi requested /// returns system metrics for dpi - public static int TryGetSystemMetricsForDpi(int nIndex, uint dpi) { - if (ApiHelper.IsApiAvailable(ExternDll.User32, nameof(UnsafeNativeMethods.GetSystemMetricsForDpi))) { + public static int TryGetSystemMetricsForDpi(int nIndex, uint dpi) + { + if (ApiHelper.IsApiAvailable(ExternDll.User32, nameof(UnsafeNativeMethods.GetSystemMetricsForDpi))) + { return GetSystemMetricsForDpi(nIndex, dpi); } - else { + else + { Debug.Assert(false, "GetSystemMetricsForDpi() is not available on this OS"); return GetSystemMetrics(nIndex); } } - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern bool SystemParametersInfo(int nAction, int nParam, ref NativeMethods.RECT rc, int nUpdate); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern bool SystemParametersInfo(int nAction, int nParam, ref int value, int ignore); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern bool SystemParametersInfo(int nAction, int nParam, ref bool value, int ignore); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern bool SystemParametersInfo(int nAction, int nParam, ref NativeMethods.HIGHCONTRAST_I rc, int nUpdate); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern bool SystemParametersInfo(int nAction, int nParam, [In, Out] NativeMethods.NONCLIENTMETRICS metrics, int nUpdate); - + // This API is available starting Windows10 RS1 - [DllImport(ExternDll.User32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)] - + [DllImport(ExternDll.User32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] + public static extern bool SystemParametersInfoForDpi(int nAction, int nParam, [In, Out] NativeMethods.NONCLIENTMETRICS metrics, int nUpdate, uint dpi); /// /// Tries to get system parameter info for the dpi. dpi is ignored if "SystemParametersInfoForDpi()" API is not available on the OS that this application is running. /// - public static bool TrySystemParametersInfoForDpi(int nAction, int nParam, [In, Out] NativeMethods.NONCLIENTMETRICS metrics, int nUpdate, uint dpi) { - if(ApiHelper.IsApiAvailable(ExternDll.User32, nameof(UnsafeNativeMethods.SystemParametersInfoForDpi))) { - return SystemParametersInfoForDpi(nAction, nParam, metrics, nUpdate, dpi); + public static bool TrySystemParametersInfoForDpi(int nAction, int nParam, [In, Out] NativeMethods.NONCLIENTMETRICS metrics, int nUpdate, uint dpi) + { + if (ApiHelper.IsApiAvailable(ExternDll.User32, nameof(UnsafeNativeMethods.SystemParametersInfoForDpi))) + { + return SystemParametersInfoForDpi(nAction, nParam, metrics, nUpdate, dpi); } - else { + else + { Debug.Assert(false, "SystemParametersInfoForDpi() is not available on this OS"); return SystemParametersInfo(nAction, nParam, metrics, nUpdate); } } -/* - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - public static extern bool SystemParametersInfo(int nAction, int nParam, [In, Out] NativeMethods.ICONMETRICS iconMetrics, int nUpdate); -*/ - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + /* + [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] + public static extern bool SystemParametersInfo(int nAction, int nParam, [In, Out] NativeMethods.ICONMETRICS iconMetrics, int nUpdate); + */ + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern bool SystemParametersInfo(int nAction, int nParam, [In, Out] NativeMethods.LOGFONT font, int nUpdate); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - - public static extern bool SystemParametersInfo(int nAction, int nParam, bool [] flag, bool nUpdate); - [DllImport(ExternDll.Kernel32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + + public static extern bool SystemParametersInfo(int nAction, int nParam, bool[] flag, bool nUpdate); + [DllImport(ExternDll.Kernel32, CharSet = CharSet.Auto)] + public static extern bool GetComputerName(StringBuilder lpBuffer, int[] nSize); - [DllImport(ExternDll.Advapi32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Advapi32, CharSet = CharSet.Auto)] + public static extern bool GetUserName(StringBuilder lpBuffer, int[] nSize); - [DllImport(ExternDll.User32, ExactSpelling=true)] - + [DllImport(ExternDll.User32, ExactSpelling = true)] + public static extern IntPtr GetProcessWindowStation(); - [DllImport(ExternDll.User32, SetLastError=true)] - + [DllImport(ExternDll.User32, SetLastError = true)] + public static extern bool GetUserObjectInformation(HandleRef hObj, int nIndex, [MarshalAs(UnmanagedType.LPStruct)] NativeMethods.USEROBJECTFLAGS pvBuffer, int nLength, ref int lpnLengthNeeded); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - - public static extern int ClientToScreen( HandleRef hWnd, [In, Out] NativeMethods.POINT pt ); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + + public static extern int ClientToScreen(HandleRef hWnd, [In, Out] NativeMethods.POINT pt); + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr GetForegroundWindow(); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int MsgWaitForMultipleObjectsEx(int nCount, IntPtr pHandles, int dwMilliseconds, int dwWakeMask, int dwFlags); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr GetDesktopWindow(); - [DllImport(ExternDll.Ole32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Ole32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int RegisterDragDrop(HandleRef hwnd, UnsafeNativeMethods.IOleDropTarget target); - [DllImport(ExternDll.Ole32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Ole32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int RevokeDragDrop(HandleRef hwnd); [DllImport(ExternDll.Ole32, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] public static extern int RevokeDragDrop(IntPtr hwnd); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern bool PeekMessage([In, Out] ref NativeMethods.MSG msg, HandleRef hwnd, int msgMin, int msgMax, int remove); - [DllImport(ExternDll.User32, CharSet=CharSet.Unicode)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Unicode)] + public static extern bool PeekMessageW([In, Out] ref NativeMethods.MSG msg, HandleRef hwnd, int msgMin, int msgMax, int remove); - [DllImport(ExternDll.User32, CharSet=CharSet.Ansi)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Ansi)] + public static extern bool PeekMessageA([In, Out] ref NativeMethods.MSG msg, HandleRef hwnd, int msgMin, int msgMax, int remove); - -/* - [DllImport(ExternDll.User32, CharSet=CharSet.Auto), - SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable")] - public static extern bool SetProp(HandleRef hWnd, int atom, HandleRef data); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - public static extern bool SetProp(HandleRef hWnd, string propName, HandleRef data); -*/ - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + + /* + [DllImport(ExternDll.User32, CharSet=CharSet.Auto), + SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable")] + public static extern bool SetProp(HandleRef hWnd, int atom, HandleRef data); + [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] + public static extern bool SetProp(HandleRef hWnd, string propName, HandleRef data); + */ + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern bool PostMessage(HandleRef hwnd, int msg, IntPtr wparam, IntPtr lparam); - [DllImport(ExternDll.Kernel32, CharSet=CharSet.Auto, SetLastError=true)] - + [DllImport(ExternDll.Kernel32, CharSet = CharSet.Auto, SetLastError = true)] + public static extern short GlobalAddAtom(string atomName); - [DllImport(ExternDll.Oleacc, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Oleacc, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr LresultFromObject(ref Guid refiid, IntPtr wParam, HandleRef pAcc); [DllImport(ExternDll.Oleacc, ExactSpelling = true, CharSet = CharSet.Auto)] public static extern IntPtr LresultFromObject(ref Guid refiid, IntPtr wParam, IntPtr pAcc); - [DllImport(ExternDll.Oleacc, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Oleacc, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern int CreateStdAccessibleObject(HandleRef hWnd, int objID, ref Guid refiid, [In, Out, MarshalAs(UnmanagedType.Interface)] ref object pAcc); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern void NotifyWinEvent(int winEvent, HandleRef hwnd, int objType, int objID); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int GetMenuItemID(HandleRef hMenu, int nPos); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr GetSubMenu(HandleRef hwnd, int index); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int GetMenuItemCount(HandleRef hMenu); - [DllImport(ExternDll.Oleaut32, PreserveSig=false)] - + [DllImport(ExternDll.Oleaut32, PreserveSig = false)] + public static extern void GetErrorInfo(int reserved, [In, Out] ref UnsafeNativeMethods.IErrorInfo errorInfo); - [DllImport(ExternDll.User32, ExactSpelling=true, EntryPoint="BeginPaint", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, EntryPoint = "BeginPaint", CharSet = CharSet.Auto)] + private static extern IntPtr IntBeginPaint(HandleRef hWnd, [In, Out] ref NativeMethods.PAINTSTRUCT lpPaint); - public static IntPtr BeginPaint(HandleRef hWnd, [In, Out, MarshalAs(UnmanagedType.LPStruct)] ref NativeMethods.PAINTSTRUCT lpPaint) { + public static IntPtr BeginPaint(HandleRef hWnd, [In, Out, MarshalAs(UnmanagedType.LPStruct)] ref NativeMethods.PAINTSTRUCT lpPaint) + { return Interop.HandleCollector.Add(IntBeginPaint(hWnd, ref lpPaint), Interop.CommonHandles.HDC); } [DllImport(ExternDll.User32, ExactSpelling = true, EntryPoint = "BeginPaint", CharSet = CharSet.Auto)] public static extern IntPtr BeginPaint(IntPtr hWnd, [In, Out] ref NativeMethods.PAINTSTRUCT lpPaint); - [DllImport(ExternDll.User32, ExactSpelling=true, EntryPoint="EndPaint", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, EntryPoint = "EndPaint", CharSet = CharSet.Auto)] + private static extern bool IntEndPaint(HandleRef hWnd, ref NativeMethods.PAINTSTRUCT lpPaint); - public static bool EndPaint(HandleRef hWnd, [In, MarshalAs(UnmanagedType.LPStruct)] ref NativeMethods.PAINTSTRUCT lpPaint) { + public static bool EndPaint(HandleRef hWnd, [In, MarshalAs(UnmanagedType.LPStruct)] ref NativeMethods.PAINTSTRUCT lpPaint) + { Interop.HandleCollector.Remove(lpPaint.hdc, Interop.CommonHandles.HDC); return IntEndPaint(hWnd, ref lpPaint); } @@ -1164,82 +1199,87 @@ public static bool EndPaint(HandleRef hWnd, [In, MarshalAs(UnmanagedType.LPStruc [DllImport(ExternDll.User32, ExactSpelling = true, EntryPoint = "EndPaint", CharSet = CharSet.Auto)] public static extern bool EndPaint(IntPtr hWnd, ref NativeMethods.PAINTSTRUCT lpPaint); - [DllImport(ExternDll.User32, ExactSpelling=true, EntryPoint="GetDC", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, EntryPoint = "GetDC", CharSet = CharSet.Auto)] + private static extern IntPtr IntGetDC(HandleRef hWnd); - - - public static IntPtr GetDC(HandleRef hWnd) { + + + public static IntPtr GetDC(HandleRef hWnd) + { return Interop.HandleCollector.Add(IntGetDC(hWnd), Interop.CommonHandles.HDC); } - [DllImport(ExternDll.User32, ExactSpelling=true, EntryPoint="GetWindowDC", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, EntryPoint = "GetWindowDC", CharSet = CharSet.Auto)] + private static extern IntPtr IntGetWindowDC(HandleRef hWnd); - - - public static IntPtr GetWindowDC(HandleRef hWnd) { + + + public static IntPtr GetWindowDC(HandleRef hWnd) + { return Interop.HandleCollector.Add(IntGetWindowDC(hWnd), Interop.CommonHandles.HDC); } - - [DllImport(ExternDll.User32, ExactSpelling=true, EntryPoint="ReleaseDC", CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, EntryPoint = "ReleaseDC", CharSet = CharSet.Auto)] + private static extern int IntReleaseDC(HandleRef hWnd, HandleRef hDC); - public static int ReleaseDC(HandleRef hWnd, HandleRef hDC) { + public static int ReleaseDC(HandleRef hWnd, HandleRef hDC) + { Interop.HandleCollector.Remove((IntPtr)hDC, Interop.CommonHandles.HDC); return IntReleaseDC(hWnd, hDC); } - [DllImport(ExternDll.Gdi32, SetLastError=true, EntryPoint="CreateDC", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, EntryPoint = "CreateDC", CharSet = CharSet.Auto)] + private static extern IntPtr IntCreateDC(string lpszDriver, string lpszDeviceName, string lpszOutput, HandleRef devMode); - - - - public static IntPtr CreateDC(string lpszDriver) { + + + + public static IntPtr CreateDC(string lpszDriver) + { return Interop.HandleCollector.Add(IntCreateDC(lpszDriver, null, null, NativeMethods.NullHandleRef), Interop.CommonHandles.HDC); } - - - public static IntPtr CreateDC(string lpszDriverName, string lpszDeviceName, string lpszOutput, HandleRef /*DEVMODE*/ lpInitData) { + + + public static IntPtr CreateDC(string lpszDriverName, string lpszDeviceName, string lpszOutput, HandleRef /*DEVMODE*/ lpInitData) + { return Interop.HandleCollector.Add(IntCreateDC(lpszDriverName, lpszDeviceName, lpszOutput, lpInitData), Interop.CommonHandles.HDC); } - - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern bool SystemParametersInfo(int nAction, int nParam, [In, Out] IntPtr[] rc, int nUpdate); - - [DllImport(ExternDll.User32, EntryPoint="SendMessage", CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, EntryPoint = "SendMessage", CharSet = CharSet.Auto)] + //public extern static IntPtr SendCallbackMessage(HandleRef hWnd, int Msg, IntPtr wParam, UnsafeNativeMethods.IRichTextBoxOleCallback lParam); public extern static IntPtr SendCallbackMessage(HandleRef hWnd, int Msg, IntPtr wParam, IntPtr lParam); - - [DllImport(ExternDll.Shell32, ExactSpelling=true, CharSet=CharSet.Ansi)] - + + [DllImport(ExternDll.Shell32, ExactSpelling = true, CharSet = CharSet.Ansi)] + public static extern void DragAcceptFiles(HandleRef hWnd, bool fAccept); - - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int GetDeviceCaps(HandleRef hDC, int nIndex); - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool GetScrollInfo(HandleRef hWnd, int fnBar, NativeMethods.SCROLLINFO si); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int SetScrollInfo(HandleRef hWnd, int fnBar, NativeMethods.SCROLLINFO si, bool redraw); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr GetActiveWindow(); - [DllImport(ExternDll.Kernel32, CharSet=CharSet.Auto, SetLastError=true)] - + [DllImport(ExternDll.Kernel32, CharSet = CharSet.Auto, SetLastError = true)] + private static extern IntPtr LoadLibrary(string libname); - - [DllImport(ExternDll.Kernel32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)] - + + [DllImport(ExternDll.Kernel32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)] + private static extern IntPtr LoadLibraryEx(string lpModuleName, IntPtr hFile, uint dwFlags); //GetWindowLong won't work correctly for 64-bit: we should use GetWindowLongPtr instead. On @@ -1256,19 +1296,19 @@ public static IntPtr GetWindowLong(HandleRef hWnd, int nIndex) } [SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable")] [DllImport(ExternDll.User32, CharSet = CharSet.Auto, EntryPoint = "GetWindowLong")] - + public static extern IntPtr GetWindowLong32(HandleRef hWnd, int nIndex); [SuppressMessage("Microsoft.Interoperability", "CA1400:PInvokeEntryPointsShouldExist")] [DllImport(ExternDll.User32, CharSet = CharSet.Auto, EntryPoint = "GetWindowLongPtr")] - + public static extern IntPtr GetWindowLongPtr64(HandleRef hWnd, int nIndex); //SetWindowLong won't work correctly for 64-bit: we should use SetWindowLongPtr instead. On //32-bit, SetWindowLongPtr is just #defined as SetWindowLong. SetWindowLong really should //take/return int instead of IntPtr/HandleRef, but since we're running this only for 32-bit //it'll be OK. - public static IntPtr SetWindowLong(HandleRef hWnd, int nIndex, HandleRef dwNewLong) + public static IntPtr SetWindowLong(HandleRef hWnd, int nIndex, HandleRef dwNewLong) { if (IntPtr.Size == 4) { @@ -1278,11 +1318,11 @@ public static IntPtr SetWindowLong(HandleRef hWnd, int nIndex, HandleRef dwNewLo } [SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable")] [DllImport(ExternDll.User32, CharSet = CharSet.Auto, EntryPoint = "SetWindowLong")] - + public static extern IntPtr SetWindowLongPtr32(HandleRef hWnd, int nIndex, HandleRef dwNewLong); [SuppressMessage("Microsoft.Interoperability", "CA1400:PInvokeEntryPointsShouldExist")] [DllImport(ExternDll.User32, CharSet = CharSet.Auto, EntryPoint = "SetWindowLongPtr")] - + public static extern IntPtr SetWindowLongPtr64(HandleRef hWnd, int nIndex, HandleRef dwNewLong); public static IntPtr SetWindowLong(HandleRef hWnd, int nIndex, NativeMethods.WndProc wndproc) @@ -1295,131 +1335,136 @@ public static IntPtr SetWindowLong(HandleRef hWnd, int nIndex, NativeMethods.Wnd } [SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable")] [DllImport(ExternDll.User32, CharSet = CharSet.Auto, EntryPoint = "SetWindowLong")] - + public static extern IntPtr SetWindowLongPtr32(HandleRef hWnd, int nIndex, NativeMethods.WndProc wndproc); [SuppressMessage("Microsoft.Interoperability", "CA1400:PInvokeEntryPointsShouldExist")] [DllImport(ExternDll.User32, CharSet = CharSet.Auto, EntryPoint = "SetWindowLongPtr")] - + public static extern IntPtr SetWindowLongPtr64(HandleRef hWnd, int nIndex, NativeMethods.WndProc wndproc); [DllImport(ExternDll.Ole32, PreserveSig = false)] - + public static extern UnsafeNativeMethods.ILockBytes CreateILockBytesOnHGlobal(HandleRef hGlobal, bool fDeleteOnRelease); - [DllImport(ExternDll.Ole32, PreserveSig=false)] - + [DllImport(ExternDll.Ole32, PreserveSig = false)] + public static extern UnsafeNativeMethods.IStorage StgCreateDocfileOnILockBytes(UnsafeNativeMethods.ILockBytes iLockBytes, int grfMode, int reserved); - [DllImport(ExternDll.User32, ExactSpelling=true, EntryPoint="CreatePopupMenu", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, ExactSpelling = true, EntryPoint = "CreatePopupMenu", CharSet = CharSet.Auto)] + private static extern IntPtr IntCreatePopupMenu(); - - - public static IntPtr CreatePopupMenu() { + + + public static IntPtr CreatePopupMenu() + { return Interop.HandleCollector.Add(IntCreatePopupMenu(), Interop.CommonHandles.Menu); } - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool RemoveMenu(HandleRef hMenu, int uPosition, int uFlags); - - [DllImport(ExternDll.User32, ExactSpelling=true, EntryPoint="DestroyMenu", CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, EntryPoint = "DestroyMenu", CharSet = CharSet.Auto)] + private static extern bool IntDestroyMenu(HandleRef hMenu); - public static bool DestroyMenu(HandleRef hMenu) { + public static bool DestroyMenu(HandleRef hMenu) + { Interop.HandleCollector.Remove((IntPtr)hMenu, Interop.CommonHandles.Menu); return IntDestroyMenu(hMenu); } - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool SetForegroundWindow(HandleRef hWnd); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr GetSystemMenu(HandleRef hWnd, bool bRevert); - - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr DefFrameProc(IntPtr hWnd, IntPtr hWndClient, int msg, IntPtr wParam, IntPtr lParam); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool TranslateMDISysAccel(IntPtr hWndClient, [In, Out] ref NativeMethods.MSG msg); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto, SetLastError=true)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)] + public static extern bool SetLayeredWindowAttributes(HandleRef hwnd, int crKey, byte bAlpha, int dwFlags); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public extern static bool SetMenu(HandleRef hWnd, HandleRef hMenu); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int GetWindowPlacement(HandleRef hWnd, ref NativeMethods.WINDOWPLACEMENT placement); - - [DllImport(ExternDll.Kernel32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Kernel32, CharSet = CharSet.Auto)] + public static extern void GetStartupInfo([In, Out] NativeMethods.STARTUPINFO_I startupinfo_i); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool SetMenuDefaultItem(HandleRef hwnd, int nIndex, bool pos); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool EnableMenuItem(HandleRef hMenu, int UIDEnabledItem, int uEnable); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr SetActiveWindow(HandleRef hWnd); - [DllImport(ExternDll.Gdi32, SetLastError=true, EntryPoint="CreateIC", CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, EntryPoint = "CreateIC", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + private static extern IntPtr IntCreateIC(string lpszDriverName, string lpszDeviceName, string lpszOutput, HandleRef /*DEVMODE*/ lpInitData); - - - public static IntPtr CreateIC(string lpszDriverName, string lpszDeviceName, string lpszOutput, HandleRef /*DEVMODE*/ lpInitData) { + + + public static IntPtr CreateIC(string lpszDriverName, string lpszDeviceName, string lpszOutput, HandleRef /*DEVMODE*/ lpInitData) + { return Interop.HandleCollector.Add(IntCreateIC(lpszDriverName, lpszDeviceName, lpszOutput, lpInitData), Interop.CommonHandles.HDC); } - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool ClipCursor(ref NativeMethods.RECT rcClip); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool ClipCursor(NativeMethods.COMRECT rcClip); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr SetCursor(HandleRef hcursor); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool SetCursorPos(int x, int y); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public extern static int ShowCursor(bool bShow); - - [DllImport(ExternDll.User32, ExactSpelling=true, EntryPoint="DestroyCursor", CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, EntryPoint = "DestroyCursor", CharSet = CharSet.Auto)] + private static extern bool IntDestroyCursor(HandleRef hCurs); - public static bool DestroyCursor(HandleRef hCurs) { + public static bool DestroyCursor(HandleRef hCurs) + { Interop.HandleCollector.Remove((IntPtr)hCurs, Interop.CommonHandles.Cursor); return IntDestroyCursor(hCurs); } - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool IsWindow(HandleRef hWnd); - - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="DeleteDC", CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "DeleteDC", CharSet = CharSet.Auto)] + private static extern bool IntDeleteDC(HandleRef hDC); - public static bool DeleteDC(HandleRef hDC) { + public static bool DeleteDC(HandleRef hDC) + { Interop.HandleCollector.Remove((IntPtr)hDC, Interop.CommonHandles.HDC); return IntDeleteDC(hDC); } @@ -1431,124 +1476,132 @@ public static bool DeleteCompatibleDC(HandleRef hDC) } public const int LAYOUT_RTL = 0x00000001; - public const int LAYOUT_BITMAPORIENTATIONPRESERVED = 0x00000008; + public const int LAYOUT_BITMAPORIENTATIONPRESERVED = 0x00000008; + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Ansi)] - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Ansi)] - public static extern bool GetMessageA([In, Out] ref NativeMethods.MSG msg, HandleRef hWnd, int uMsgFilterMin, int uMsgFilterMax); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Unicode)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Unicode)] + public static extern bool GetMessageW([In, Out] ref NativeMethods.MSG msg, HandleRef hWnd, int uMsgFilterMin, int uMsgFilterMax); - - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr PostMessage(HandleRef hwnd, int msg, int wparam, int lparam); - [DllImport(ExternDll.User32, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.User32, CharSet = CharSet.Auto)] + public static extern IntPtr PostMessage(HandleRef hwnd, int msg, int wparam, IntPtr lparam); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool GetClientRect(HandleRef hWnd, [In, Out] ref NativeMethods.RECT rect); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool GetClientRect(HandleRef hWnd, IntPtr rect); - - [DllImport(ExternDll.User32, EntryPoint="WindowFromPoint", ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, EntryPoint = "WindowFromPoint", ExactSpelling = true, CharSet = CharSet.Auto)] + private static extern IntPtr _WindowFromPoint(POINTSTRUCT pt); - - - public static IntPtr WindowFromPoint(int x, int y) { + + + public static IntPtr WindowFromPoint(int x, int y) + { POINTSTRUCT ps = new POINTSTRUCT(x, y); return _WindowFromPoint(ps); } - [DllImport(ExternDll.User32, SetLastError=true, ExactSpelling = true)] - - public static extern IntPtr WindowFromDC( HandleRef hDC ); - [DllImport(ExternDll.User32, EntryPoint="CreateWindowEx", CharSet=CharSet.Auto, SetLastError=true)] - - public static extern IntPtr IntCreateWindowEx(int dwExStyle, string lpszClassName, + [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true)] + + public static extern IntPtr WindowFromDC(HandleRef hDC); + [DllImport(ExternDll.User32, EntryPoint = "CreateWindowEx", CharSet = CharSet.Auto, SetLastError = true)] + + public static extern IntPtr IntCreateWindowEx(int dwExStyle, string lpszClassName, string lpszWindowName, int style, int x, int y, int width, int height, HandleRef hWndParent, HandleRef hMenu, HandleRef hInst, [MarshalAs(UnmanagedType.AsAny)] object pvParam); - - - public static IntPtr CreateWindowEx(int dwExStyle, string lpszClassName, + + + public static IntPtr CreateWindowEx(int dwExStyle, string lpszClassName, string lpszWindowName, int style, int x, int y, int width, int height, - HandleRef hWndParent, HandleRef hMenu, HandleRef hInst, [MarshalAs(UnmanagedType.AsAny)]object pvParam) { + HandleRef hWndParent, HandleRef hMenu, HandleRef hInst, [MarshalAs(UnmanagedType.AsAny)]object pvParam) + { return IntCreateWindowEx(dwExStyle, lpszClassName, lpszWindowName, style, x, y, width, height, hWndParent, hMenu, hInst, pvParam); } - - [DllImport(ExternDll.User32, ExactSpelling=true, EntryPoint="DestroyWindow", CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, EntryPoint = "DestroyWindow", CharSet = CharSet.Auto)] + public static extern bool IntDestroyWindow(HandleRef hWnd); - public static bool DestroyWindow(HandleRef hWnd) { + public static bool DestroyWindow(HandleRef hWnd) + { return IntDestroyWindow(hWnd); } - - [DllImport(ExternDll.User32, CharSet=CharSet.Auto, SetLastError=true)] - + + [DllImport(ExternDll.User32, CharSet = CharSet.Auto, SetLastError = true)] + public static extern bool UnregisterClass(string className, HandleRef hInstance); - - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern IntPtr GetStockObject(int nIndex); - - [DllImport(ExternDll.User32, CharSet=CharSet.Auto, SetLastError=true)] - + + [DllImport(ExternDll.User32, CharSet = CharSet.Auto, SetLastError = true)] + public static extern short RegisterClass(NativeMethods.WNDCLASS_D wc); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern void PostQuitMessage(int nExitCode); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern void WaitMessage(); - - [DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)] - + + [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool SetWindowPlacement(HandleRef hWnd, [In] ref NativeMethods.WINDOWPLACEMENT placement); // This method is not available until Windows 8.1 - [DllImport(ExternDll.User32, ExactSpelling=true, SetLastError = true)] - + [DllImport(ExternDll.User32, ExactSpelling = true, SetLastError = true)] + public static extern uint GetDpiForWindow(HandleRef hWnd); // For system power status // - [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool GetSystemPowerStatus([In, Out] ref NativeMethods.SYSTEM_POWER_STATUS systemPowerStatus); - [DllImport(ExternDll.Powrprof, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Powrprof, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern bool SetSuspendState(bool hiberate, bool forceCritical, bool disableWakeEvent); //for RegionData [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + public static extern int GetRegionData(HandleRef hRgn, int size, IntPtr lpRgnData); - public unsafe static NativeMethods.RECT[] GetRectsFromRegion(IntPtr hRgn) { + public unsafe static NativeMethods.RECT[] GetRectsFromRegion(IntPtr hRgn) + { NativeMethods.RECT[] regionRects = null; IntPtr pBytes = IntPtr.Zero; - try { + try + { // see how much memory we need to allocate int regionDataSize = GetRegionData(new HandleRef(null, hRgn), 0, IntPtr.Zero); - if (regionDataSize != 0) { + if (regionDataSize != 0) + { pBytes = Marshal.AllocCoTaskMem(regionDataSize); // get the data int ret = GetRegionData(new HandleRef(null, hRgn), regionDataSize, pBytes); - if (ret == regionDataSize) { + if (ret == regionDataSize) + { // cast to the structure NativeMethods.RGNDATAHEADER* pRgnDataHeader = (NativeMethods.RGNDATAHEADER*)pBytes; - if (pRgnDataHeader->iType == 1) { // expecting RDH_RECTANGLES + if (pRgnDataHeader->iType == 1) + { // expecting RDH_RECTANGLES regionRects = new NativeMethods.RECT[pRgnDataHeader->nCount]; Debug.Assert(regionDataSize == pRgnDataHeader->cbSizeOfStruct + pRgnDataHeader->nCount * pRgnDataHeader->nRgnSize); @@ -1556,7 +1609,8 @@ public unsafe static NativeMethods.RECT[] GetRectsFromRegion(IntPtr hRgn) { // use the header size as the offset, and cast each rect in. int rectStart = pRgnDataHeader->cbSizeOfStruct; - for (int i = 0; i < pRgnDataHeader->nCount; i++) { + for (int i = 0; i < pRgnDataHeader->nCount; i++) + { // use some fancy pointer math to just copy the rect bits directly into the array. regionRects[i] = *((NativeMethods.RECT*)((byte*)pBytes + rectStart + (Marshal.SizeOf() * i))); } @@ -1564,8 +1618,10 @@ public unsafe static NativeMethods.RECT[] GetRectsFromRegion(IntPtr hRgn) { } } } - finally { - if (pBytes != IntPtr.Zero) { + finally + { + if (pBytes != IntPtr.Zero) + { Marshal.FreeCoTaskMem(pBytes); } } @@ -1597,7 +1653,8 @@ public enum EXTENDED_NAME_FORMAT { */ [ComImport(), Guid("00000122-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IOleDropTarget { + public interface IOleDropTarget + { [PreserveSig] int OleDragEnter( [In, MarshalAs(UnmanagedType.Interface)] @@ -1608,7 +1665,7 @@ int OleDragEnter( POINTSTRUCT pt, [In, Out] ref int pdwEffect); - + [PreserveSig] int OleDragOver( [In, MarshalAs(UnmanagedType.U4)] @@ -1617,10 +1674,10 @@ int OleDragOver( POINTSTRUCT pt, [In, Out] ref int pdwEffect); - + [PreserveSig] int OleDragLeave(); - + [PreserveSig] int OleDrop( [In, MarshalAs(UnmanagedType.Interface)] @@ -1632,10 +1689,11 @@ int OleDrop( [In, Out] ref int pdwEffect); } - + [ComImport(), Guid("00000121-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IOleDropSource { - + public interface IOleDropSource + { + [PreserveSig] int OleQueryContinueDrag( int fEscapePressed, @@ -1647,10 +1705,11 @@ int OleGiveFeedback( [In, MarshalAs(UnmanagedType.U4)] int dwEffect); } - + [ComImport(), Guid("00000016-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IOleMessageFilter { - + public interface IOleMessageFilter + { + [PreserveSig] int HandleInComingCall( int dwCallType, @@ -1663,32 +1722,33 @@ int RetryRejectedCall( IntPtr hTaskCallee, int dwTickCount, int dwRejectType); - + [PreserveSig] int MessagePending( IntPtr hTaskCallee, int dwTickCount, int dwPendingType); } - + [ - ComImport(), + ComImport(), Guid("B196B289-BAB4-101A-B69C-00AA00341D07"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown) ] - public interface IOleControlSite { - + public interface IOleControlSite + { + [PreserveSig] int OnControlInfoChanged(); - + [PreserveSig] int LockInPlaceActive(int fLock); - + [PreserveSig] int GetExtendedControl( [Out, MarshalAs(UnmanagedType.IDispatch)] out object ppDisp); - + [PreserveSig] int TransformCoords( [In, Out] @@ -1697,7 +1757,7 @@ int TransformCoords( NativeMethods.tagPOINTF pPtfContainer, [In, MarshalAs(UnmanagedType.U4)] int dwFlags); - + [PreserveSig] int TranslateAccelerator( [In] @@ -1707,15 +1767,16 @@ int TranslateAccelerator( [PreserveSig] int OnFocus(int fGotFocus); - + [PreserveSig] int ShowPropertyFrame(); } - + [ComImport(), Guid("00000118-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IOleClientSite { - + public interface IOleClientSite + { + [PreserveSig] int SaveObject(); @@ -1730,135 +1791,141 @@ int GetMoniker( [PreserveSig] int GetContainer(out IOleContainer container); - + [PreserveSig] int ShowObject(); - + [PreserveSig] int OnShowWindow(int fShow); - + [PreserveSig] int RequestNewObjectLayout(); } - + [ComImport(), Guid("00000119-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IOleInPlaceSite { - + public interface IOleInPlaceSite + { + IntPtr GetWindow(); - + [PreserveSig] int ContextSensitiveHelp(int fEnterMode); - + [PreserveSig] int CanInPlaceActivate(); - + [PreserveSig] int OnInPlaceActivate(); - + [PreserveSig] int OnUIActivate(); - + [PreserveSig] int GetWindowContext( - [Out, MarshalAs(UnmanagedType.Interface)] + [Out, MarshalAs(UnmanagedType.Interface)] out UnsafeNativeMethods.IOleInPlaceFrame ppFrame, - [Out, MarshalAs(UnmanagedType.Interface)] + [Out, MarshalAs(UnmanagedType.Interface)] out UnsafeNativeMethods.IOleInPlaceUIWindow ppDoc, - [Out] + [Out] NativeMethods.COMRECT lprcPosRect, - [Out] + [Out] NativeMethods.COMRECT lprcClipRect, - [In, Out] + [In, Out] NativeMethods.tagOIFI lpFrameInfo); - + [PreserveSig] int Scroll( NativeMethods.tagSIZE scrollExtant); - + [PreserveSig] int OnUIDeactivate( int fUndoable); - + [PreserveSig] int OnInPlaceDeactivate(); - + [PreserveSig] int DiscardUndoState(); - + [PreserveSig] int DeactivateAndUndo(); - + [PreserveSig] int OnPosRectChange( - [In] + [In] NativeMethods.COMRECT lprcPosRect); } - + [ComImport(), Guid("742B0E01-14E6-101B-914E-00AA00300CAB"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface ISimpleFrameSite { + public interface ISimpleFrameSite + { [PreserveSig] - int PreMessageFilter( + int PreMessageFilter( IntPtr hwnd, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int msg, IntPtr wp, IntPtr lp, - [In, Out] + [In, Out] ref IntPtr plResult, - [In, Out, MarshalAs(UnmanagedType.U4)] + [In, Out, MarshalAs(UnmanagedType.U4)] ref int pdwCookie); - + [PreserveSig] int PostMessageFilter( IntPtr hwnd, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int msg, IntPtr wp, IntPtr lp, - [In, Out] + [In, Out] ref IntPtr plResult, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int dwCookie); } - + [ComImport(), Guid("40A050A0-3C31-101B-A82E-08002B2B2337"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IVBGetControl { - + public interface IVBGetControl + { + [PreserveSig] int EnumControls( int dwOleContF, int dwWhich, - [Out] + [Out] out IEnumUnknown ppenum); } - + [ComImport(), Guid("91733A60-3F4C-101B-A3F6-00AA0034E4E9"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IGetVBAObject { - - [PreserveSig] - int GetObject( - [In] + public interface IGetVBAObject + { + + [PreserveSig] + int GetObject( + [In] ref Guid riid, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] IVBFormat[] rval, - int dwReserved); + int dwReserved); } - + [ComImport(), Guid("9BFBBC02-EFF1-101A-84ED-00AA00341D07"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IPropertyNotifySink { + public interface IPropertyNotifySink + { void OnChanged(int dispID); - + [PreserveSig] int OnRequestEdit(int dispID); } - + [ComImport(), Guid("9849FD60-3768-101B-8D72-AE6164FFE3CF"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IVBFormat { - + public interface IVBFormat + { + [PreserveSig] int Format( - [In] + [In] ref object var, IntPtr pszFormat, IntPtr lpBuffer, @@ -1866,96 +1933,99 @@ int Format( int lcid, short firstD, short firstW, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] short[] result); } - + [ComImport(), Guid("00000100-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IEnumUnknown { - + public interface IEnumUnknown + { + [PreserveSig] int Next( - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int celt, - [Out] + [Out] IntPtr rgelt, IntPtr pceltFetched); - + [PreserveSig] - int Skip( - [In, MarshalAs(UnmanagedType.U4)] + int Skip( + [In, MarshalAs(UnmanagedType.U4)] int celt); - + void Reset(); - + void Clone( - [Out] + [Out] out IEnumUnknown ppenum); } - + [ComImport(), Guid("0000011B-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IOleContainer { - + public interface IOleContainer + { + [PreserveSig] int ParseDisplayName( - [In, MarshalAs(UnmanagedType.Interface)] + [In, MarshalAs(UnmanagedType.Interface)] object pbc, - [In, MarshalAs(UnmanagedType.BStr)] + [In, MarshalAs(UnmanagedType.BStr)] string pszDisplayName, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] int[] pchEaten, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] object[] ppmkOut); - + [PreserveSig] int EnumObjects( - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int grfFlags, - [Out] + [Out] out IEnumUnknown ppenum); - + [PreserveSig] int LockContainer( bool fLock); } - + [ComImport(), Guid("00000116-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IOleInPlaceFrame { - + public interface IOleInPlaceFrame + { + IntPtr GetWindow(); - + [PreserveSig] int ContextSensitiveHelp(int fEnterMode); - + [PreserveSig] int GetBorder( [Out] NativeMethods.COMRECT lprectBorder); - + [PreserveSig] int RequestBorderSpace( [In] NativeMethods.COMRECT pborderwidths); - + [PreserveSig] int SetBorderSpace( [In] NativeMethods.COMRECT pborderwidths); - + [PreserveSig] - int SetActiveObject( + int SetActiveObject( [In, MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.IOleInPlaceActiveObject pActiveObject, [In, MarshalAs(UnmanagedType.LPWStr)] string pszObjName); - + [PreserveSig] int InsertMenus( [In] IntPtr hmenuShared, [In, Out] NativeMethods.tagOleMenuGroupWidths lpMenuWidths); - + [PreserveSig] int SetMenu( [In] @@ -1964,33 +2034,34 @@ int SetMenu( IntPtr holemenu, [In] IntPtr hwndActiveObject); - + [PreserveSig] int RemoveMenus( [In] IntPtr hmenuShared); - + [PreserveSig] int SetStatusText( [In, MarshalAs(UnmanagedType.LPWStr)] string pszStatusText); - + [PreserveSig] int EnableModeless( bool fEnable); - + [PreserveSig] - int TranslateAccelerator( + int TranslateAccelerator( [In] ref NativeMethods.MSG lpmsg, [In, MarshalAs(UnmanagedType.U2)] short wID); } - + // Used to control the webbrowser appearance and provide DTE to script via window.external [ComVisible(true), ComImport(), Guid("BD3F23C0-D43E-11CF-893B-00AA00BDCE1A"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IDocHostUIHandler { + public interface IDocHostUIHandler + { [return: MarshalAs(UnmanagedType.I4)] [PreserveSig] @@ -2110,74 +2181,80 @@ int FilterDataObject( [ComImport(), Guid("D30C1661-CDAF-11d0-8A3E-00C04FC9E26E"), TypeLibType(TypeLibTypeFlags.FHidden | TypeLibTypeFlags.FDual | TypeLibTypeFlags.FOleAutomation)] - public interface IWebBrowser2 { + public interface IWebBrowser2 + { // // IWebBrowser members [DispId(100)] void GoBack(); [DispId(101)] void GoForward(); [DispId(102)] void GoHome(); [DispId(103)] void GoSearch(); - [DispId(104)] void Navigate([In] string Url, [In] ref object flags, + [DispId(104)] + void Navigate([In] string Url, [In] ref object flags, [In] ref object targetFrameName, [In] ref object postData, [In] ref object headers); [DispId(-550)] void Refresh(); [DispId(105)] void Refresh2([In] ref object level); [DispId(106)] void Stop(); - [DispId(200)] object Application {[return: MarshalAs(UnmanagedType.IDispatch)]get;} - [DispId(201)] object Parent {[return: MarshalAs(UnmanagedType.IDispatch)]get;} - [DispId(202)] object Container {[return: MarshalAs(UnmanagedType.IDispatch)]get;} - [DispId(203)] object Document {[return: MarshalAs(UnmanagedType.IDispatch)]get;} - [DispId(204)] bool TopLevelContainer {get;} - [DispId(205)] string Type {get;} - [DispId(206)] int Left {get; set;} - [DispId(207)] int Top {get; set;} - [DispId(208)] int Width {get; set;} - [DispId(209)] int Height {get; set;} - [DispId(210)] string LocationName {get;} - [DispId(211)] string LocationURL {get;} - [DispId(212)] bool Busy {get;} + [DispId(200)] object Application { [return: MarshalAs(UnmanagedType.IDispatch)]get; } + [DispId(201)] object Parent { [return: MarshalAs(UnmanagedType.IDispatch)]get; } + [DispId(202)] object Container { [return: MarshalAs(UnmanagedType.IDispatch)]get; } + [DispId(203)] object Document { [return: MarshalAs(UnmanagedType.IDispatch)]get; } + [DispId(204)] bool TopLevelContainer { get; } + [DispId(205)] string Type { get; } + [DispId(206)] int Left { get; set; } + [DispId(207)] int Top { get; set; } + [DispId(208)] int Width { get; set; } + [DispId(209)] int Height { get; set; } + [DispId(210)] string LocationName { get; } + [DispId(211)] string LocationURL { get; } + [DispId(212)] bool Busy { get; } // // IWebBrowserApp members [DispId(300)] void Quit(); [DispId(301)] void ClientToWindow([Out]out int pcx, [Out]out int pcy); [DispId(302)] void PutProperty([In] string property, [In] object vtValue); [DispId(303)] object GetProperty([In] string property); - [DispId(0)] string Name {get;} - [DispId(-515)] int HWND {get;} - [DispId(400)] string FullName {get;} - [DispId(401)] string Path {get;} - [DispId(402)] bool Visible {get; set;} - [DispId(403)] bool StatusBar {get; set;} - [DispId(404)] string StatusText {get; set;} - [DispId(405)] int ToolBar {get; set;} - [DispId(406)] bool MenuBar {get; set;} - [DispId(407)] bool FullScreen {get; set;} + [DispId(0)] string Name { get; } + [DispId(-515)] int HWND { get; } + [DispId(400)] string FullName { get; } + [DispId(401)] string Path { get; } + [DispId(402)] bool Visible { get; set; } + [DispId(403)] bool StatusBar { get; set; } + [DispId(404)] string StatusText { get; set; } + [DispId(405)] int ToolBar { get; set; } + [DispId(406)] bool MenuBar { get; set; } + [DispId(407)] bool FullScreen { get; set; } // // IWebBrowser2 members - [DispId(500)] void Navigate2([In] ref object URL, [In] ref object flags, + [DispId(500)] + void Navigate2([In] ref object URL, [In] ref object flags, [In] ref object targetFrameName, [In] ref object postData, [In] ref object headers); [DispId(501)] NativeMethods.OLECMDF QueryStatusWB([In] NativeMethods.OLECMDID cmdID); - [DispId(502)] void ExecWB([In] NativeMethods.OLECMDID cmdID, + [DispId(502)] + void ExecWB([In] NativeMethods.OLECMDID cmdID, [In] NativeMethods.OLECMDEXECOPT cmdexecopt, ref object pvaIn, IntPtr pvaOut); - [DispId(503)] void ShowBrowserBar([In] ref object pvaClsid, [In] ref object pvarShow, + [DispId(503)] + void ShowBrowserBar([In] ref object pvaClsid, [In] ref object pvarShow, [In] ref object pvarSize); - [DispId(-525)] WebBrowserReadyState ReadyState {get;} - [DispId(550)] bool Offline {get; set;} - [DispId(551)] bool Silent {get; set;} - [DispId(552)] bool RegisterAsBrowser {get; set;} - [DispId(553)] bool RegisterAsDropTarget {get; set;} - [DispId(554)] bool TheaterMode {get; set;} - [DispId(555)] bool AddressBar {get; set;} - [DispId(556)] bool Resizable {get; set;} + [DispId(-525)] WebBrowserReadyState ReadyState { get; } + [DispId(550)] bool Offline { get; set; } + [DispId(551)] bool Silent { get; set; } + [DispId(552)] bool RegisterAsBrowser { get; set; } + [DispId(553)] bool RegisterAsDropTarget { get; set; } + [DispId(554)] bool TheaterMode { get; set; } + [DispId(555)] bool AddressBar { get; set; } + [DispId(556)] bool Resizable { get; set; } } [ComImport(), Guid("34A715A0-6587-11D0-924A-0020AFC7AC4D"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DWebBrowserEvents2 { + public interface DWebBrowserEvents2 + { [DispId(102)] void StatusTextChange([In] string text); [DispId(108)] void ProgressChange([In] int progress, [In] int progressMax); [DispId(105)] void CommandStateChange([In] long command, [In] bool enable); @@ -2185,15 +2262,19 @@ public interface DWebBrowserEvents2 { [DispId(104)] void DownloadComplete(); [DispId(113)] void TitleChange([In] string text); [DispId(112)] void PropertyChange([In] string szProperty); - [DispId(250)] void BeforeNavigate2([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp, + [DispId(250)] + void BeforeNavigate2([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp, [In] ref object URL, [In] ref object flags, [In] ref object targetFrameName, [In] ref object postData, [In] ref object headers, [In, Out] ref bool cancel); - [DispId(251)] void NewWindow2([In, Out, MarshalAs(UnmanagedType.IDispatch)] ref object pDisp, + [DispId(251)] + void NewWindow2([In, Out, MarshalAs(UnmanagedType.IDispatch)] ref object pDisp, [In, Out] ref bool cancel); - [DispId(252)] void NavigateComplete2([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp, + [DispId(252)] + void NavigateComplete2([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp, [In] ref object URL); - [DispId(259)] void DocumentComplete([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp, + [DispId(259)] + void DocumentComplete([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp, [In] ref object URL); [DispId(253)] void OnQuit(); [DispId(254)] void OnVisible([In] bool visible); @@ -2211,24 +2292,28 @@ public interface DWebBrowserEvents2 { [DispId(268)] void ClientToHostWindow([In, Out] ref long cx, [In, Out] ref long cy); [DispId(269)] void SetSecureLockIcon([In] int secureLockIcon); [DispId(270)] void FileDownload([In, Out] ref bool cancel); - [DispId(271)] void NavigateError([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp, + [DispId(271)] + void NavigateError([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp, [In] ref object URL, [In] ref object frame, [In] ref object statusCode, [In, Out] ref bool cancel); [DispId(225)] void PrintTemplateInstantiation([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp); [DispId(226)] void PrintTemplateTeardown([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp); - [DispId(227)] void UpdatePageStatus([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp, + [DispId(227)] + void UpdatePageStatus([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp, [In] ref object nPage, [In] ref object fDone); [DispId(272)] void PrivacyImpactedStateChange([In] bool bImpacted); } [ComVisible(true), Guid("626FC520-A41E-11cf-A731-00A0C9082637"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] - internal interface IHTMLDocument { + internal interface IHTMLDocument + { [return: MarshalAs(UnmanagedType.IDispatch)] object GetScript(); } - + [ComVisible(true), Guid("332C4425-26CB-11D0-B483-00C04FD90119"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] - internal interface IHTMLDocument2 { + internal interface IHTMLDocument2 + { [return: MarshalAs(UnmanagedType.IDispatch)] object GetScript(); IHTMLElementCollection GetAll(); IHTMLElement GetBody(); @@ -2339,12 +2424,13 @@ bool ExecCommand(string cmdID, void SetOnerrorupdate(object p); object GetOnerrorupdate(); string toString(); - [return: MarshalAs(UnmanagedType.Interface)] object CreateStyleSheet(string bstrHref,int lIndex); + [return: MarshalAs(UnmanagedType.Interface)] object CreateStyleSheet(string bstrHref, int lIndex); } [ComVisible(true), Guid("3050F485-98B5-11CF-BB82-00AA00BDCE0B"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] - internal interface IHTMLDocument3 { + internal interface IHTMLDocument3 + { void ReleaseCapture(); void Recalc([In] bool fForce); object CreateTextNode([In] string text); @@ -2390,7 +2476,8 @@ internal interface IHTMLDocument3 { [ComVisible(true), Guid("3050F69A-98B5-11CF-BB82-00AA00BDCE0B"), InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsDual)] - internal interface IHTMLDocument4 { + internal interface IHTMLDocument4 + { void Focus(); bool HasFocus(); void SetOnselectionchange(object p); @@ -2406,12 +2493,13 @@ internal interface IHTMLDocument4 { object GetOncontrolselect(); string GetURLUnencoded(); } - + [ComImport(), Guid("3050f613-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLDocumentEvents2 { + public interface DHTMLDocumentEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -2455,14 +2543,16 @@ public interface DHTMLDocumentEvents2 { [ComVisible(true), Guid("332C4426-26CB-11D0-B483-00C04FD90119"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] - internal interface IHTMLFramesCollection2 { + internal interface IHTMLFramesCollection2 + { object Item(ref object idOrName); int GetLength(); } [ComVisible(true), Guid("332C4427-26CB-11D0-B483-00C04FD90119"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] - public interface IHTMLWindow2 { + public interface IHTMLWindow2 + { [return: MarshalAs(UnmanagedType.IDispatch)] object Item([In] ref object pvarIndex); int GetLength(); [return: MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.IHTMLFramesCollection2 GetFrames(); @@ -2537,7 +2627,8 @@ public interface IHTMLWindow2 { [ComVisible(true), Guid("3050f4ae-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] - public interface IHTMLWindow3 { + public interface IHTMLWindow3 + { int GetScreenLeft(); int GetScreenTop(); bool AttachEvent(string ev, [In, MarshalAs(UnmanagedType.IDispatch)] object pdisp); @@ -2552,19 +2643,21 @@ public interface IHTMLWindow3 { object GetClipboardData(); object ShowModelessDialog(string url, object varArgIn, object options); } - + [ComVisible(true), Guid("3050f6cf-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] - public interface IHTMLWindow4 { + public interface IHTMLWindow4 + { [return: MarshalAs(UnmanagedType.IDispatch)] object CreatePopup([In] ref object reserved); [return: MarshalAs(UnmanagedType.Interface)] object frameElement(); } - + [ComImport(), Guid("3050f625-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLWindowEvents2 { + public interface DHTMLWindowEvents2 + { [DispId(1003)] void onload(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(1008)] void onunload(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -2581,16 +2674,18 @@ public interface DHTMLWindowEvents2 { [ComVisible(true), Guid("3050f666-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] - public interface IHTMLPopup { + public interface IHTMLPopup + { void show(int x, int y, int w, int h, ref object element); void hide(); [return: MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.IHTMLDocument GetDocument(); bool IsOpen(); } - + [ComVisible(true), Guid("3050f35c-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] - public interface IHTMLScreen { + public interface IHTMLScreen + { int GetColorDepth(); void SetBufferDepth(int d); int GetBufferDepth(); @@ -2606,7 +2701,8 @@ public interface IHTMLScreen { [ComVisible(true), Guid("163BB1E0-6E00-11CF-837A-48DC04C10000"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] - internal interface IHTMLLocation { + internal interface IHTMLLocation + { void SetHref([In] string p); string GetHref(); void SetProtocol([In] string p); @@ -2630,7 +2726,8 @@ internal interface IHTMLLocation { [ComVisible(true), Guid("FECEAAA2-8405-11CF-8BA1-00AA00476DA6"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] - internal interface IOmHistory { + internal interface IOmHistory + { short GetLength(); void Back(); void Forward(); @@ -2639,7 +2736,8 @@ internal interface IOmHistory { [ComVisible(true), Guid("FECEAAA5-8405-11CF-8BA1-00AA00476DA6"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] - internal interface IOmNavigator { + internal interface IOmNavigator + { string GetAppCodeName(); string GetAppName(); string GetAppVersion(); @@ -2663,7 +2761,8 @@ internal interface IOmNavigator { [ComVisible(true), Guid("3050F32D-98B5-11CF-BB82-00AA00BDCE0B"), InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsDual)] - internal interface IHTMLEventObj { + internal interface IHTMLEventObj + { [return: MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.IHTMLElement GetSrcElement(); bool GetAltKey(); bool GetCtrlKey(); @@ -2693,7 +2792,8 @@ internal interface IHTMLEventObj { [ComVisible(true), Guid("3050f48B-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsDual)] - internal interface IHTMLEventObj2 { + internal interface IHTMLEventObj2 + { void SetAttribute(string attributeName, object attributeValue, int lFlags); object GetAttribute(string attributeName, int lFlags); bool RemoveAttribute(string attributeName, int lFlags); @@ -2754,13 +2854,15 @@ internal interface IHTMLEventObj2 { [ComVisible(true), Guid("3050f814-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsDual)] - internal interface IHTMLEventObj4 { + internal interface IHTMLEventObj4 + { int GetWheelDelta(); }; - + [ComVisible(true), Guid("3050F21F-98B5-11CF-BB82-00AA00BDCE0B"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] - internal interface IHTMLElementCollection { + internal interface IHTMLElementCollection + { string toString(); void SetLength(int p); int GetLength(); @@ -2768,10 +2870,11 @@ internal interface IHTMLElementCollection { [return: MarshalAs(UnmanagedType.IDispatch)] object Item(object idOrName, object index); [return: MarshalAs(UnmanagedType.Interface)] object Tags(object tagName); } - + [ComVisible(true), Guid("3050F1FF-98B5-11CF-BB82-00AA00BDCE0B"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] - internal interface IHTMLElement { + internal interface IHTMLElement + { void SetAttribute(string attributeName, object attributeValue, int lFlags); object GetAttribute(string attributeName, int lFlags); bool RemoveAttribute(string strAttributeName, int lFlags); @@ -2862,11 +2965,12 @@ void InsertAdjacentText(string @where, [return: MarshalAs(UnmanagedType.IDispatch)] object GetChildren(); [return: MarshalAs(UnmanagedType.IDispatch)] object GetAll(); } - + [ComVisible(true), Guid("3050f434-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] - internal interface IHTMLElement2 { + internal interface IHTMLElement2 + { string ScopeName(); void SetCapture(bool containerCapture); void ReleaseCapture(); @@ -2950,14 +3054,16 @@ internal interface IHTMLElement2 { void MergeAttributes(object mergeThis); void SetOnContextMenu(object v); object GetOnContextMenu(); - [return: MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.IHTMLElement + [return: MarshalAs(UnmanagedType.Interface)] + UnsafeNativeMethods.IHTMLElement InsertAdjacentElement(string @where, [In, MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.IHTMLElement insertedElement); - [return: MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.IHTMLElement + [return: MarshalAs(UnmanagedType.Interface)] + UnsafeNativeMethods.IHTMLElement applyElement([In, MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.IHTMLElement apply, string @where); string GetAdjacentText(string @where); - string ReplaceAdjacentText(string @where,string newText); + string ReplaceAdjacentText(string @where, string newText); bool CanHaveChildren(); int AddBehavior(string url, ref object oFactory); bool RemoveBehavior(int cookie); @@ -2973,7 +3079,8 @@ internal interface IHTMLElement2 { [ComVisible(true), Guid("3050f673-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] - internal interface IHTMLElement3 { + internal interface IHTMLElement3 + { void MergeAttributes(object mergeThis, object pvarFlags); bool IsMultiLine(); bool CanHaveHTML(); @@ -3021,7 +3128,8 @@ internal interface IHTMLElement3 { [ComVisible(true), Guid("3050f5da-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] - public interface IHTMLDOMNode { + public interface IHTMLDOMNode + { long GetNodeType(); IHTMLDOMNode GetParentNode(); bool HasChildNodes(); @@ -3043,11 +3151,12 @@ public interface IHTMLDOMNode { IHTMLDOMNode PreviousSibling(); IHTMLDOMNode NextSibling(); }; - + [ComImport(), Guid("3050f60f-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLElementEvents2 { + public interface DHTMLElementEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3064,7 +3173,7 @@ public interface DHTMLElementEvents2 { [DispId(-2147418101)] bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418108)] bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418107)] void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418106)] bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418105)] void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418098)] void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3079,7 +3188,7 @@ public interface DHTMLElementEvents2 { [DispId(-2147418092)] bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418091)] void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418090)] bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418088)] void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418087)] bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418083)] bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3115,7 +3224,8 @@ public interface DHTMLElementEvents2 { [ComImport(), Guid("3050f610-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLAnchorEvents2 { + public interface DHTMLAnchorEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3132,7 +3242,7 @@ public interface DHTMLAnchorEvents2 { [DispId(-2147418101)] bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418108)] bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418107)] void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418106)] bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418105)] void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418098)] void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3147,7 +3257,7 @@ public interface DHTMLAnchorEvents2 { [DispId(-2147418092)] bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418091)] void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418090)] bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418088)] void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418087)] bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418083)] bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3183,7 +3293,8 @@ public interface DHTMLAnchorEvents2 { [ComImport(), Guid("3050f611-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLAreaEvents2 { + public interface DHTMLAreaEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3200,7 +3311,7 @@ public interface DHTMLAreaEvents2 { [DispId(-2147418101)] bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418108)] bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418107)] void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418106)] bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418105)] void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418098)] void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3215,7 +3326,7 @@ public interface DHTMLAreaEvents2 { [DispId(-2147418092)] bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418091)] void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418090)] bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418088)] void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418087)] bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418083)] bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3251,7 +3362,8 @@ public interface DHTMLAreaEvents2 { [ComImport(), Guid("3050f617-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLButtonElementEvents2 { + public interface DHTMLButtonElementEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3268,7 +3380,7 @@ public interface DHTMLButtonElementEvents2 { [DispId(-2147418101)] bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418108)] bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418107)] void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418106)] bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418105)] void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418098)] void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3283,7 +3395,7 @@ public interface DHTMLButtonElementEvents2 { [DispId(-2147418092)] bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418091)] void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418090)] bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418088)] void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418087)] bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418083)] bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3319,7 +3431,8 @@ public interface DHTMLButtonElementEvents2 { [ComImport(), Guid("3050f612-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLControlElementEvents2 { + public interface DHTMLControlElementEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3336,7 +3449,7 @@ public interface DHTMLControlElementEvents2 { [DispId(-2147418101)] bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418108)] bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418107)] void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418106)] bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418105)] void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418098)] void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3351,7 +3464,7 @@ public interface DHTMLControlElementEvents2 { [DispId(-2147418092)] bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418091)] void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418090)] bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418088)] void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418087)] bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418083)] bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3387,7 +3500,8 @@ public interface DHTMLControlElementEvents2 { [ComImport(), Guid("3050f614-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLFormElementEvents2 { + public interface DHTMLFormElementEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3404,7 +3518,7 @@ public interface DHTMLFormElementEvents2 { [DispId(-2147418101)] bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418108)] bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418107)] void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418106)] bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418105)] void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418098)] void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3419,7 +3533,7 @@ public interface DHTMLFormElementEvents2 { [DispId(-2147418092)] bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418091)] void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418090)] bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418088)] void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418087)] bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418083)] bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3457,7 +3571,8 @@ public interface DHTMLFormElementEvents2 { [ComImport(), Guid("3050f7ff-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLFrameSiteEvents2 { + public interface DHTMLFrameSiteEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3474,7 +3589,7 @@ public interface DHTMLFrameSiteEvents2 { [DispId(-2147418101)] bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418108)] bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418107)] void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418106)] bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418105)] void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418098)] void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3489,7 +3604,7 @@ public interface DHTMLFrameSiteEvents2 { [DispId(-2147418092)] bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418091)] void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418090)] bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418088)] void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418087)] bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418083)] bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3526,7 +3641,8 @@ public interface DHTMLFrameSiteEvents2 { [ComImport(), Guid("3050f616-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLImgEvents2 { + public interface DHTMLImgEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3543,7 +3659,7 @@ public interface DHTMLImgEvents2 { [DispId(-2147418101)] bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418108)] bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418107)] void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418106)] bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418105)] void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418098)] void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3558,7 +3674,7 @@ public interface DHTMLImgEvents2 { [DispId(-2147418092)] bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418091)] void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418090)] bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418088)] void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418087)] bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418083)] bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3597,7 +3713,8 @@ public interface DHTMLImgEvents2 { [ComImport(), Guid("3050f61a-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLInputFileElementEvents2 { + public interface DHTMLInputFileElementEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3614,7 +3731,7 @@ public interface DHTMLInputFileElementEvents2 { [DispId(-2147418101)] bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418108)] bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418107)] void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418106)] bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418105)] void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418098)] void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3629,7 +3746,7 @@ public interface DHTMLInputFileElementEvents2 { [DispId(-2147418092)] bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418091)] void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418090)] bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418088)] void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418087)] bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418083)] bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3670,7 +3787,8 @@ public interface DHTMLInputFileElementEvents2 { [ComImport(), Guid("3050f61b-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLInputImageEvents2 { + public interface DHTMLInputImageEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3687,7 +3805,7 @@ public interface DHTMLInputImageEvents2 { [DispId(-2147418101)] bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418108)] bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418107)] void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418106)] bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418105)] void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418098)] void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3702,7 +3820,7 @@ public interface DHTMLInputImageEvents2 { [DispId(-2147418092)] bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418091)] void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418090)] bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418088)] void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418087)] bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418083)] bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3741,7 +3859,8 @@ public interface DHTMLInputImageEvents2 { [ComImport(), Guid("3050f618-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLInputTextElementEvents2 { + public interface DHTMLInputTextElementEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3758,7 +3877,7 @@ public interface DHTMLInputTextElementEvents2 { [DispId(-2147418101)] bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418108)] bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418107)] void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418106)] bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418105)] void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418098)] void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3773,7 +3892,7 @@ public interface DHTMLInputTextElementEvents2 { [DispId(-2147418092)] bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418091)] void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418090)] bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418088)] void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418087)] bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418083)] bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3814,7 +3933,8 @@ public interface DHTMLInputTextElementEvents2 { [ComImport(), Guid("3050f61c-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLLabelEvents2 { + public interface DHTMLLabelEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3831,7 +3951,7 @@ public interface DHTMLLabelEvents2 { [DispId(-2147418101)] bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418108)] bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418107)] void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418106)] bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418105)] void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418098)] void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3846,7 +3966,7 @@ public interface DHTMLLabelEvents2 { [DispId(-2147418092)] bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418091)] void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418090)] bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418088)] void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418087)] bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418083)] bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3882,7 +4002,8 @@ public interface DHTMLLabelEvents2 { [ComImport(), Guid("3050f61d-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLLinkElementEvents2 { + public interface DHTMLLinkElementEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3899,7 +4020,7 @@ public interface DHTMLLinkElementEvents2 { [DispId(-2147418101)] bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418108)] bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418107)] void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418106)] bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418105)] void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418098)] void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3914,7 +4035,7 @@ public interface DHTMLLinkElementEvents2 { [DispId(-2147418092)] bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418091)] void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418090)] bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418088)] void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418087)] bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418083)] bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3952,7 +4073,8 @@ public interface DHTMLLinkElementEvents2 { [ComImport(), Guid("3050f61e-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLMapEvents2 { + public interface DHTMLMapEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3969,7 +4091,7 @@ public interface DHTMLMapEvents2 { [DispId(-2147418101)] bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418108)] bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418107)] void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418106)] bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418105)] void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418098)] void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -3984,7 +4106,7 @@ public interface DHTMLMapEvents2 { [DispId(-2147418092)] bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418091)] void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418090)] bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418088)] void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418087)] bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418083)] bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4020,7 +4142,8 @@ public interface DHTMLMapEvents2 { [ComImport(), Guid("3050f61f-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLMarqueeElementEvents2 { + public interface DHTMLMarqueeElementEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4037,7 +4160,7 @@ public interface DHTMLMarqueeElementEvents2 { [DispId(-2147418101)] bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418108)] bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418107)] void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418106)] bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418105)] void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418098)] void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4052,7 +4175,7 @@ public interface DHTMLMarqueeElementEvents2 { [DispId(-2147418092)] bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418091)] void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418090)] bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418088)] void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418087)] bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418083)] bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4091,7 +4214,8 @@ public interface DHTMLMarqueeElementEvents2 { [ComImport(), Guid("3050f619-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLOptionButtonElementEvents2 { + public interface DHTMLOptionButtonElementEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4108,7 +4232,7 @@ public interface DHTMLOptionButtonElementEvents2 { [DispId(-2147418101)] bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418108)] bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418107)] void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418106)] bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418105)] void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418098)] void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4123,7 +4247,7 @@ public interface DHTMLOptionButtonElementEvents2 { [DispId(-2147418092)] bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418091)] void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418090)] bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418088)] void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418087)] bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418083)] bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4160,7 +4284,8 @@ public interface DHTMLOptionButtonElementEvents2 { [ComImport(), Guid("3050f622-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLSelectElementEvents2 { + public interface DHTMLSelectElementEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4177,7 +4302,7 @@ public interface DHTMLSelectElementEvents2 { [DispId(-2147418101)] bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418108)] bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418107)] void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418106)] bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418105)] void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418098)] void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4192,7 +4317,7 @@ public interface DHTMLSelectElementEvents2 { [DispId(-2147418092)] bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418091)] void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418090)] bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418088)] void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418087)] bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418083)] bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4229,7 +4354,8 @@ public interface DHTMLSelectElementEvents2 { [ComImport(), Guid("3050f615-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLStyleElementEvents2 { + public interface DHTMLStyleElementEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4246,7 +4372,7 @@ public interface DHTMLStyleElementEvents2 { [DispId(-2147418101)] bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418108)] bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418107)] void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418106)] bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418105)] void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418098)] void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4261,7 +4387,7 @@ public interface DHTMLStyleElementEvents2 { [DispId(-2147418092)] bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418091)] void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418090)] bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418088)] void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418087)] bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418083)] bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4295,11 +4421,12 @@ public interface DHTMLStyleElementEvents2 { [DispId(1003)] void onload(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(1002)] void onerror(UnsafeNativeMethods.IHTMLEventObj evtObj); } - + [ComImport(), Guid("3050f623-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLTableEvents2 { + public interface DHTMLTableEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4316,7 +4443,7 @@ public interface DHTMLTableEvents2 { [DispId(-2147418101)] bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418108)] bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418107)] void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418106)] bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418105)] void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418098)] void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4331,7 +4458,7 @@ public interface DHTMLTableEvents2 { [DispId(-2147418092)] bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418091)] void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418090)] bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418088)] void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418087)] bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418083)] bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4367,7 +4494,8 @@ public interface DHTMLTableEvents2 { [ComImport(), Guid("3050f624-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLTextContainerEvents2 { + public interface DHTMLTextContainerEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4384,7 +4512,7 @@ public interface DHTMLTextContainerEvents2 { [DispId(-2147418101)] bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418108)] bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418107)] void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418106)] bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418105)] void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418098)] void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4399,7 +4527,7 @@ public interface DHTMLTextContainerEvents2 { [DispId(-2147418092)] bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418091)] void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418090)] bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418088)] void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418087)] bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418083)] bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4433,11 +4561,12 @@ public interface DHTMLTextContainerEvents2 { [DispId(1001)] void onchange_void(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(1006)] void onselect(UnsafeNativeMethods.IHTMLEventObj evtObj); } - + [ComImport(), Guid("3050f621-98b5-11cf-bb82-00aa00bdce0b"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FHidden)] - public interface DHTMLScriptEvents2 { + public interface DHTMLScriptEvents2 + { [DispId(-2147418102)] bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-600)] bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-601)] bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4454,7 +4583,7 @@ public interface DHTMLScriptEvents2 { [DispId(-2147418101)] bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418108)] bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418107)] void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418099)] bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418106)] bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418105)] void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418098)] void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4469,7 +4598,7 @@ public interface DHTMLScriptEvents2 { [DispId(-2147418092)] bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418091)] void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418090)] bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(-2147418089)] bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418088)] void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418087)] bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(-2147418083)] bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj); @@ -4500,12 +4629,13 @@ public interface DHTMLScriptEvents2 { [DispId(1040)] bool onresizestart(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(1041)] void onresizeend(UnsafeNativeMethods.IHTMLEventObj evtObj); [DispId(1033)] bool onmousewheel(UnsafeNativeMethods.IHTMLEventObj evtObj); - [DispId(1002)]void onerror(UnsafeNativeMethods.IHTMLEventObj evtObj); + [DispId(1002)] void onerror(UnsafeNativeMethods.IHTMLEventObj evtObj); } [ComVisible(true), Guid("3050F25E-98B5-11CF-BB82-00AA00BDCE0B"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] - internal interface IHTMLStyle { + internal interface IHTMLStyle + { void SetFontFamily(string p); string GetFontFamily(); void SetFontStyle(string p); @@ -4685,53 +4815,55 @@ internal interface IHTMLStyle { object GetAttribute(string strAttributeName, int lFlags); bool RemoveAttribute(string strAttributeName, int lFlags); } - + [ComImport(), Guid("39088D7E-B71E-11D1-8F39-00C04FD946D0"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown) ] - public interface IExtender { - - int Align {get; set;} - - bool Enabled {get; set;} - - int Height {get; set;} - - int Left {get; set;} - - bool TabStop {get; set;} - - int Top {get; set;} - - bool Visible {get; set;} - - int Width {get; set;} - - string Name {[return: MarshalAs(UnmanagedType.BStr)]get;} - - object Parent {[return: MarshalAs(UnmanagedType.Interface)]get;} - - IntPtr Hwnd {get;} - - object Container {[return: MarshalAs(UnmanagedType.Interface)]get;} - + public interface IExtender + { + + int Align { get; set; } + + bool Enabled { get; set; } + + int Height { get; set; } + + int Left { get; set; } + + bool TabStop { get; set; } + + int Top { get; set; } + + bool Visible { get; set; } + + int Width { get; set; } + + string Name { [return: MarshalAs(UnmanagedType.BStr)]get; } + + object Parent { [return: MarshalAs(UnmanagedType.Interface)]get; } + + IntPtr Hwnd { get; } + + object Container { [return: MarshalAs(UnmanagedType.Interface)]get; } + void Move( - [In, MarshalAs(UnmanagedType.Interface)] + [In, MarshalAs(UnmanagedType.Interface)] object left, - [In, MarshalAs(UnmanagedType.Interface)] + [In, MarshalAs(UnmanagedType.Interface)] object top, - [In, MarshalAs(UnmanagedType.Interface)] + [In, MarshalAs(UnmanagedType.Interface)] object width, - [In, MarshalAs(UnmanagedType.Interface)] + [In, MarshalAs(UnmanagedType.Interface)] object height); } - - [ComImport(), - Guid("8A701DA0-4FEB-101B-A82E-08002B2B2337"), + + [ComImport(), + Guid("8A701DA0-4FEB-101B-A82E-08002B2B2337"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown) ] - public interface IGetOleObject { + public interface IGetOleObject + { [return: MarshalAs(UnmanagedType.Interface)] object GetOleObject(ref Guid riid); } @@ -4740,25 +4872,30 @@ public interface IGetOleObject { ComImport(), Guid("CB2F6722-AB3A-11d2-9C40-00C04FA30A3E"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown) - ] - internal interface ICorRuntimeHost { + ] + internal interface ICorRuntimeHost + { [PreserveSig()] int CreateLogicalThreadState(); [PreserveSig()] int DeleteLogicalThreadState(); - [PreserveSig()] int SwitchInLogicalThreadState( + [PreserveSig()] + int SwitchInLogicalThreadState( [In] ref uint pFiberCookie); // [in] Cookie that indicates the fiber to use. - - [PreserveSig()] int SwitchOutLogicalThreadState( + + [PreserveSig()] + int SwitchOutLogicalThreadState( out uint FiberCookie); // [out] Cookie that indicates the fiber being switched out. - - [PreserveSig()] int LocksHeldByLogicalThread( // Return code. + + [PreserveSig()] + int LocksHeldByLogicalThread( // Return code. out uint pCount // [out] Number of locks that the current thread holds. ); - - [PreserveSig()] int MapFile( - IntPtr hFile, // [in] HANDLE for file - out IntPtr hMapAddress); // [out] HINSTANCE for mapped file - + + [PreserveSig()] + int MapFile( + IntPtr hFile, // [in] HANDLE for file + out IntPtr hMapAddress); // [out] HINSTANCE for mapped file + //================================================================= // // New hosting methods @@ -4767,46 +4904,49 @@ out uint pCount // [out] Number of locks that the current // it starting. If the runtime has been initialized this // routine returns an error. See ICorConfiguration. [PreserveSig()] int GetConfiguration([MarshalAs(UnmanagedType.IUnknown)] out object pConfiguration); - + // Starts the runtime. This is equivalent to CoInitializeCor(); [PreserveSig()] int Start(); - + // Terminates the runtime, This is equivalent CoUninitializeCor(); [PreserveSig()] int Stop(); - + // Creates a domain in the runtime. The identity array is // a pointer to an array TYPE containing IIdentity objects defining // the security identity. - [PreserveSig()] int CreateDomain(string pwzFriendlyName, + [PreserveSig()] + int CreateDomain(string pwzFriendlyName, [MarshalAs(UnmanagedType.IUnknown)] object pIdentityArray, // Optional [MarshalAs(UnmanagedType.IUnknown)] out object pAppDomain); - + // Returns the default domain. [PreserveSig()] int GetDefaultDomain([MarshalAs(UnmanagedType.IUnknown)] out object pAppDomain); - - + + // Enumerate currently existing domains. [PreserveSig()] int EnumDomains(out IntPtr hEnum); - + // Returns S_FALSE when there are no more domains. A domain // is passed out only when S_OK is returned. - [PreserveSig()] int NextDomain(IntPtr hEnum, + [PreserveSig()] + int NextDomain(IntPtr hEnum, [MarshalAs(UnmanagedType.IUnknown)] out object pAppDomain); - + // Close the enumeration, releasing resources [PreserveSig()] int CloseEnum(IntPtr hEnum); - - [PreserveSig()] int CreateDomainEx(string pwzFriendlyName, // Optional + + [PreserveSig()] + int CreateDomainEx(string pwzFriendlyName, // Optional [MarshalAs(UnmanagedType.IUnknown)] object pSetup, // Optional [MarshalAs(UnmanagedType.IUnknown)] object pEvidence, // Optional [MarshalAs(UnmanagedType.IUnknown)] out object pAppDomain); - + [PreserveSig()] int CreateDomainSetup([MarshalAs(UnmanagedType.IUnknown)] out object pAppDomainSetup); - + [PreserveSig()] int CreateEvidence([MarshalAs(UnmanagedType.IUnknown)] out object pEvidence); - + [PreserveSig()] int UnloadDomain([MarshalAs(UnmanagedType.IUnknown)] object pAppDomain); - + // Returns the thread's domain. [PreserveSig()] int CurrentDomain([MarshalAs(UnmanagedType.IUnknown)] out object pAppDomain); } @@ -4819,266 +4959,268 @@ internal class CorRuntimeHost { } - [ComImport(), - Guid("000C0601-0000-0000-C000-000000000046"), + [ComImport(), + Guid("000C0601-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown) ] - public interface IMsoComponentManager { + public interface IMsoComponentManager + { - /// - /// Return in *ppvObj an implementation of interface iid for service - /// guidService (same as IServiceProvider::QueryService). - /// Return NOERROR if the requested service is supported, otherwise return - /// NULL in *ppvObj and an appropriate error (eg E_FAIL, E_NOINTERFACE). - /// - [PreserveSig] - int QueryService( - ref Guid guidService, - ref Guid iid, - [MarshalAs(UnmanagedType.Interface)] + /// + /// Return in *ppvObj an implementation of interface iid for service + /// guidService (same as IServiceProvider::QueryService). + /// Return NOERROR if the requested service is supported, otherwise return + /// NULL in *ppvObj and an appropriate error (eg E_FAIL, E_NOINTERFACE). + /// + [PreserveSig] + int QueryService( + ref Guid guidService, + ref Guid iid, + [MarshalAs(UnmanagedType.Interface)] out object ppvObj); - /// - /// Standard FDebugMessage method. - /// Since IMsoComponentManager is a reference counted interface, - /// MsoDWGetChkMemCounter should be used when processing the - /// msodmWriteBe message. - /// - [PreserveSig] - bool FDebugMessage( - IntPtr hInst, - int msg, - IntPtr wParam, - IntPtr lParam); + /// + /// Standard FDebugMessage method. + /// Since IMsoComponentManager is a reference counted interface, + /// MsoDWGetChkMemCounter should be used when processing the + /// msodmWriteBe message. + /// + [PreserveSig] + bool FDebugMessage( + IntPtr hInst, + int msg, + IntPtr wParam, + IntPtr lParam); - /// - /// Register component piComponent and its registration info pcrinfo with - /// this component manager. Return in *pdwComponentID a cookie which will - /// identify the component when it calls other IMsoComponentManager - /// methods. - /// Return TRUE if successful, FALSE otherwise. - /// - [PreserveSig] - bool FRegisterComponent( - IMsoComponent component, - NativeMethods.MSOCRINFOSTRUCT pcrinfo, - out IntPtr dwComponentID); + /// + /// Register component piComponent and its registration info pcrinfo with + /// this component manager. Return in *pdwComponentID a cookie which will + /// identify the component when it calls other IMsoComponentManager + /// methods. + /// Return TRUE if successful, FALSE otherwise. + /// + [PreserveSig] + bool FRegisterComponent( + IMsoComponent component, + NativeMethods.MSOCRINFOSTRUCT pcrinfo, + out IntPtr dwComponentID); - /// - /// Undo the registration of the component identified by dwComponentID - /// (the cookie returned from the FRegisterComponent method). - /// Return TRUE if successful, FALSE otherwise. - /// - [PreserveSig] - bool FRevokeComponent(IntPtr dwComponentID); + /// + /// Undo the registration of the component identified by dwComponentID + /// (the cookie returned from the FRegisterComponent method). + /// Return TRUE if successful, FALSE otherwise. + /// + [PreserveSig] + bool FRevokeComponent(IntPtr dwComponentID); - /// - /// Update the registration info of the component identified by - /// dwComponentID (the cookie returned from FRegisterComponent) with the - /// new registration information pcrinfo. - /// Typically this is used to update the idle time registration data, but - /// can be used to update other registration data as well. - /// Return TRUE if successful, FALSE otherwise. - /// - [PreserveSig] - bool FUpdateComponentRegistration(IntPtr dwComponentID,NativeMethods.MSOCRINFOSTRUCT pcrinfo); + /// + /// Update the registration info of the component identified by + /// dwComponentID (the cookie returned from FRegisterComponent) with the + /// new registration information pcrinfo. + /// Typically this is used to update the idle time registration data, but + /// can be used to update other registration data as well. + /// Return TRUE if successful, FALSE otherwise. + /// + [PreserveSig] + bool FUpdateComponentRegistration(IntPtr dwComponentID, NativeMethods.MSOCRINFOSTRUCT pcrinfo); - /// - /// Notify component manager that component identified by dwComponentID - /// (cookie returned from FRegisterComponent) has been activated. - /// The active component gets the chance to process messages before they - /// are dispatched (via IMsoComponent::FPreTranslateMessage) and typically - /// gets first chance at idle time after the host. - /// This method fails if another component is already Exclusively Active. - /// In this case, FALSE is returned and SetLastError is set to - /// msoerrACompIsXActive (comp usually need not take any special action - /// in this case). - /// Return TRUE if successful. - /// - [PreserveSig] - bool FOnComponentActivate(IntPtr dwComponentID); + /// + /// Notify component manager that component identified by dwComponentID + /// (cookie returned from FRegisterComponent) has been activated. + /// The active component gets the chance to process messages before they + /// are dispatched (via IMsoComponent::FPreTranslateMessage) and typically + /// gets first chance at idle time after the host. + /// This method fails if another component is already Exclusively Active. + /// In this case, FALSE is returned and SetLastError is set to + /// msoerrACompIsXActive (comp usually need not take any special action + /// in this case). + /// Return TRUE if successful. + /// + [PreserveSig] + bool FOnComponentActivate(IntPtr dwComponentID); - /// - /// Called to inform component manager that component identified by - /// dwComponentID (cookie returned from FRegisterComponent) wishes - /// to perform a tracking operation (such as mouse tracking). - /// The component calls this method with fTrack == TRUE to begin the - /// tracking operation and with fTrack == FALSE to end the operation. - /// During the tracking operation the component manager routes messages - /// to the tracking component (via IMsoComponent::FPreTranslateMessage) - /// rather than to the active component. When the tracking operation ends, - /// the component manager should resume routing messages to the active - /// component. - /// Note: component manager should perform no idle time processing during a - /// tracking operation other than give the tracking component idle - /// time via IMsoComponent::FDoIdle. - /// Note: there can only be one tracking component at a time. - /// Return TRUE if successful, FALSE otherwise. - /// - [PreserveSig] - bool FSetTrackingComponent(IntPtr dwComponentID, [In, MarshalAs(UnmanagedType.Bool)] bool fTrack); + /// + /// Called to inform component manager that component identified by + /// dwComponentID (cookie returned from FRegisterComponent) wishes + /// to perform a tracking operation (such as mouse tracking). + /// The component calls this method with fTrack == TRUE to begin the + /// tracking operation and with fTrack == FALSE to end the operation. + /// During the tracking operation the component manager routes messages + /// to the tracking component (via IMsoComponent::FPreTranslateMessage) + /// rather than to the active component. When the tracking operation ends, + /// the component manager should resume routing messages to the active + /// component. + /// Note: component manager should perform no idle time processing during a + /// tracking operation other than give the tracking component idle + /// time via IMsoComponent::FDoIdle. + /// Note: there can only be one tracking component at a time. + /// Return TRUE if successful, FALSE otherwise. + /// + [PreserveSig] + bool FSetTrackingComponent(IntPtr dwComponentID, [In, MarshalAs(UnmanagedType.Bool)] bool fTrack); - /// - /// Notify component manager that component identified by dwComponentID - /// (cookie returned from FRegisterComponent) is entering the state - /// identified by uStateID (msocstateXXX value). (For convenience when - /// dealing with sub CompMgrs, the host can call this method passing 0 for - /// dwComponentID.) - /// Component manager should notify all other interested components within - /// the state context indicated by uContext (a msoccontextXXX value), - /// excluding those within the state context of a CompMgr in rgpicmExclude, - /// via IMsoComponent::OnEnterState (see "Comments on State Contexts", - /// above). - /// Component Manager should also take appropriate action depending on the - /// value of uStateID (see msocstate comments, above). - /// dwReserved is reserved for future use and should be zero. - /// - /// rgpicmExclude (can be NULL) is an array of cpicmExclude CompMgrs (can - /// include root CompMgr and/or sub CompMgrs); components within the state - /// context of a CompMgr appearing in this array should NOT be notified of - /// the state change (note: if uContext is msoccontextMine, the only - /// CompMgrs in rgpicmExclude that are checked for exclusion are those that - /// are sub CompMgrs of this Component Manager, since all other CompMgrs - /// are outside of this Component Manager's state context anyway.) - /// - /// Note: Calls to this method are symmetric with calls to - /// FOnComponentExitState. - /// That is, if n OnComponentEnterState calls are made, the component is - /// considered to be in the state until n FOnComponentExitState calls are - /// made. Before revoking its registration a component must make a - /// sufficient number of FOnComponentExitState calls to offset any - /// outstanding OnComponentEnterState calls it has made. - /// - /// Note: inplace objects should not call this method with - /// uStateID == msocstateModal when entering modal state. Such objects - /// should call IOleInPlaceFrame::EnableModeless instead. - /// - [PreserveSig] - void OnComponentEnterState(IntPtr dwComponentID,int uStateID,int uContext,int cpicmExclude,/* IMsoComponentManger** */ int rgpicmExclude,int dwReserved); + /// + /// Notify component manager that component identified by dwComponentID + /// (cookie returned from FRegisterComponent) is entering the state + /// identified by uStateID (msocstateXXX value). (For convenience when + /// dealing with sub CompMgrs, the host can call this method passing 0 for + /// dwComponentID.) + /// Component manager should notify all other interested components within + /// the state context indicated by uContext (a msoccontextXXX value), + /// excluding those within the state context of a CompMgr in rgpicmExclude, + /// via IMsoComponent::OnEnterState (see "Comments on State Contexts", + /// above). + /// Component Manager should also take appropriate action depending on the + /// value of uStateID (see msocstate comments, above). + /// dwReserved is reserved for future use and should be zero. + /// + /// rgpicmExclude (can be NULL) is an array of cpicmExclude CompMgrs (can + /// include root CompMgr and/or sub CompMgrs); components within the state + /// context of a CompMgr appearing in this array should NOT be notified of + /// the state change (note: if uContext is msoccontextMine, the only + /// CompMgrs in rgpicmExclude that are checked for exclusion are those that + /// are sub CompMgrs of this Component Manager, since all other CompMgrs + /// are outside of this Component Manager's state context anyway.) + /// + /// Note: Calls to this method are symmetric with calls to + /// FOnComponentExitState. + /// That is, if n OnComponentEnterState calls are made, the component is + /// considered to be in the state until n FOnComponentExitState calls are + /// made. Before revoking its registration a component must make a + /// sufficient number of FOnComponentExitState calls to offset any + /// outstanding OnComponentEnterState calls it has made. + /// + /// Note: inplace objects should not call this method with + /// uStateID == msocstateModal when entering modal state. Such objects + /// should call IOleInPlaceFrame::EnableModeless instead. + /// + [PreserveSig] + void OnComponentEnterState(IntPtr dwComponentID, int uStateID, int uContext, int cpicmExclude,/* IMsoComponentManger** */ int rgpicmExclude, int dwReserved); - /// - /// Notify component manager that component identified by dwComponentID - /// (cookie returned from FRegisterComponent) is exiting the state - /// identified by uStateID (a msocstateXXX value). (For convenience when - /// dealing with sub CompMgrs, the host can call this method passing 0 for - /// dwComponentID.) - /// uContext, cpicmExclude, and rgpicmExclude are as they are in - /// OnComponentEnterState. - /// Component manager should notify all appropriate interested components - /// (taking into account uContext, cpicmExclude, rgpicmExclude) via - /// IMsoComponent::OnEnterState (see "Comments on State Contexts", above). - /// Component Manager should also take appropriate action depending on - /// the value of uStateID (see msocstate comments, above). - /// Return TRUE if, at the end of this call, the state is still in effect - /// at the root of this component manager's state context - /// (because the host or some other component is still in the state), - /// otherwise return FALSE (ie. return what FInState would return). - /// Caller can normally ignore the return value. - /// - /// Note: n calls to this method are symmetric with n calls to - /// OnComponentEnterState (see OnComponentEnterState comments, above). - /// - [PreserveSig] - bool FOnComponentExitState( - IntPtr dwComponentID, - int uStateID, - int uContext, - int cpicmExclude, - /* IMsoComponentManager** */ int rgpicmExclude); + /// + /// Notify component manager that component identified by dwComponentID + /// (cookie returned from FRegisterComponent) is exiting the state + /// identified by uStateID (a msocstateXXX value). (For convenience when + /// dealing with sub CompMgrs, the host can call this method passing 0 for + /// dwComponentID.) + /// uContext, cpicmExclude, and rgpicmExclude are as they are in + /// OnComponentEnterState. + /// Component manager should notify all appropriate interested components + /// (taking into account uContext, cpicmExclude, rgpicmExclude) via + /// IMsoComponent::OnEnterState (see "Comments on State Contexts", above). + /// Component Manager should also take appropriate action depending on + /// the value of uStateID (see msocstate comments, above). + /// Return TRUE if, at the end of this call, the state is still in effect + /// at the root of this component manager's state context + /// (because the host or some other component is still in the state), + /// otherwise return FALSE (ie. return what FInState would return). + /// Caller can normally ignore the return value. + /// + /// Note: n calls to this method are symmetric with n calls to + /// OnComponentEnterState (see OnComponentEnterState comments, above). + /// + [PreserveSig] + bool FOnComponentExitState( + IntPtr dwComponentID, + int uStateID, + int uContext, + int cpicmExclude, + /* IMsoComponentManager** */ int rgpicmExclude); - /// - /// Return TRUE if the state identified by uStateID (a msocstateXXX value) - /// is in effect at the root of this component manager's state context, - /// FALSE otherwise (see "Comments on State Contexts", above). - /// pvoid is reserved for future use and should be NULL. - /// - [PreserveSig] - bool FInState(int uStateID,/* PVOID */ IntPtr pvoid); + /// + /// Return TRUE if the state identified by uStateID (a msocstateXXX value) + /// is in effect at the root of this component manager's state context, + /// FALSE otherwise (see "Comments on State Contexts", above). + /// pvoid is reserved for future use and should be NULL. + /// + [PreserveSig] + bool FInState(int uStateID,/* PVOID */ IntPtr pvoid); - /// - /// Called periodically by a component during IMsoComponent::FDoIdle. - /// Return TRUE if component can continue its idle time processing, - /// FALSE if not (in which case component returns from FDoIdle.) - /// - [PreserveSig] - bool FContinueIdle(); + /// + /// Called periodically by a component during IMsoComponent::FDoIdle. + /// Return TRUE if component can continue its idle time processing, + /// FALSE if not (in which case component returns from FDoIdle.) + /// + [PreserveSig] + bool FContinueIdle(); - /// - /// Component identified by dwComponentID (cookie returned from - /// FRegisterComponent) wishes to push a message loop for reason uReason. - /// uReason is one the values from the msoloop enumeration (above). - /// pvLoopData is data private to the component. - /// The component manager should push its message loop, - /// calling IMsoComponent::FContinueMessageLoop(uReason, pvLoopData) - /// during each loop iteration (see IMsoComponent::FContinueMessageLoop - /// comments). When IMsoComponent::FContinueMessageLoop returns FALSE, the - /// component manager terminates the loop. - /// Returns TRUE if component manager terminates loop because component - /// told it to (by returning FALSE from IMsoComponent::FContinueMessageLoop), - /// FALSE if it had to terminate the loop for some other reason. In the - /// latter case, component should perform any necessary action (such as - /// cleanup). - /// - [PreserveSig] - bool FPushMessageLoop(IntPtr dwComponentID,int uReason,/* PVOID */ int pvLoopData); + /// + /// Component identified by dwComponentID (cookie returned from + /// FRegisterComponent) wishes to push a message loop for reason uReason. + /// uReason is one the values from the msoloop enumeration (above). + /// pvLoopData is data private to the component. + /// The component manager should push its message loop, + /// calling IMsoComponent::FContinueMessageLoop(uReason, pvLoopData) + /// during each loop iteration (see IMsoComponent::FContinueMessageLoop + /// comments). When IMsoComponent::FContinueMessageLoop returns FALSE, the + /// component manager terminates the loop. + /// Returns TRUE if component manager terminates loop because component + /// told it to (by returning FALSE from IMsoComponent::FContinueMessageLoop), + /// FALSE if it had to terminate the loop for some other reason. In the + /// latter case, component should perform any necessary action (such as + /// cleanup). + /// + [PreserveSig] + bool FPushMessageLoop(IntPtr dwComponentID, int uReason,/* PVOID */ int pvLoopData); - /// - /// Cause the component manager to create a "sub" component manager, which - /// will be one of its children in the hierarchical tree of component - /// managers used to maintiain state contexts (see "Comments on State - /// Contexts", above). - /// piunkOuter is the controlling unknown (can be NULL), riid is the - /// desired IID, and *ppvObj returns the created sub component manager. - /// piunkServProv (can be NULL) is a ptr to an object supporting - /// IServiceProvider interface to which the created sub component manager - /// will delegate its IMsoComponentManager::QueryService calls. - /// (see objext.h or docobj.h for definition of IServiceProvider). - /// Returns TRUE if successful. - /// - [PreserveSig] - bool FCreateSubComponentManager( - [MarshalAs(UnmanagedType.Interface)] + /// + /// Cause the component manager to create a "sub" component manager, which + /// will be one of its children in the hierarchical tree of component + /// managers used to maintiain state contexts (see "Comments on State + /// Contexts", above). + /// piunkOuter is the controlling unknown (can be NULL), riid is the + /// desired IID, and *ppvObj returns the created sub component manager. + /// piunkServProv (can be NULL) is a ptr to an object supporting + /// IServiceProvider interface to which the created sub component manager + /// will delegate its IMsoComponentManager::QueryService calls. + /// (see objext.h or docobj.h for definition of IServiceProvider). + /// Returns TRUE if successful. + /// + [PreserveSig] + bool FCreateSubComponentManager( + [MarshalAs(UnmanagedType.Interface)] object punkOuter, - [MarshalAs(UnmanagedType.Interface)] + [MarshalAs(UnmanagedType.Interface)] object punkServProv, - ref Guid riid, - out IntPtr ppvObj); + ref Guid riid, + out IntPtr ppvObj); - /// - /// Return in *ppicm an AddRef'ed ptr to this component manager's parent - /// in the hierarchical tree of component managers used to maintain state - /// contexts (see "Comments on State Contexts", above). - /// Returns TRUE if the parent is returned, FALSE if no parent exists or - /// some error occurred. - /// - [PreserveSig] - bool FGetParentComponentManager( - out IMsoComponentManager ppicm); + /// + /// Return in *ppicm an AddRef'ed ptr to this component manager's parent + /// in the hierarchical tree of component managers used to maintain state + /// contexts (see "Comments on State Contexts", above). + /// Returns TRUE if the parent is returned, FALSE if no parent exists or + /// some error occurred. + /// + [PreserveSig] + bool FGetParentComponentManager( + out IMsoComponentManager ppicm); - /// - /// Return in *ppic an AddRef'ed ptr to the current active or tracking - /// component (as indicated by dwgac (a msogacXXX value)), and - /// its registration information in *pcrinfo. ppic and/or pcrinfo can be - /// NULL if caller is not interested these values. If pcrinfo is not NULL, - /// caller should set pcrinfo->cbSize before calling this method. - /// Returns TRUE if the component indicated by dwgac exists, FALSE if no - /// such component exists or some error occurred. - /// dwReserved is reserved for future use and should be zero. - /// - [PreserveSig] - bool FGetActiveComponent( - int dwgac, - [Out, MarshalAs(UnmanagedType.LPArray)] + /// + /// Return in *ppic an AddRef'ed ptr to the current active or tracking + /// component (as indicated by dwgac (a msogacXXX value)), and + /// its registration information in *pcrinfo. ppic and/or pcrinfo can be + /// NULL if caller is not interested these values. If pcrinfo is not NULL, + /// caller should set pcrinfo->cbSize before calling this method. + /// Returns TRUE if the component indicated by dwgac exists, FALSE if no + /// such component exists or some error occurred. + /// dwReserved is reserved for future use and should be zero. + /// + [PreserveSig] + bool FGetActiveComponent( + int dwgac, + [Out, MarshalAs(UnmanagedType.LPArray)] IMsoComponent[] ppic, - NativeMethods.MSOCRINFOSTRUCT pcrinfo, - int dwReserved); + NativeMethods.MSOCRINFOSTRUCT pcrinfo, + int dwReserved); } - - [ComImport(), + + [ComImport(), Guid("000C0600-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown) ] - public interface IMsoComponent { + public interface IMsoComponent + { /// /// Standard FDebugMessage method. @@ -5088,9 +5230,9 @@ public interface IMsoComponent { /// [PreserveSig] bool FDebugMessage( - IntPtr hInst, - int msg, - IntPtr wParam, + IntPtr hInst, + int msg, + IntPtr wParam, IntPtr lParam); /// @@ -5100,7 +5242,7 @@ bool FDebugMessage( /// Return TRUE if the message is consumed, FALSE otherwise. /// [PreserveSig] - bool FPreTranslateMessage(ref NativeMethods.MSG msg); + bool FPreTranslateMessage(ref NativeMethods.MSG msg); /// /// Notify component when app enters or exits (as indicated by fEnter) @@ -5136,7 +5278,7 @@ void OnEnterState( [PreserveSig] void OnAppActivate( bool fActive, - int dwOtherThreadID); + int dwOtherThreadID); /// /// Notify the active component that it has lost its active status because @@ -5206,7 +5348,7 @@ void OnActivationChange( /// [PreserveSig] bool FDoIdle( - int grfidlef); + int grfidlef); /// @@ -5227,7 +5369,7 @@ bool FDoIdle( bool FContinueMessageLoop( int uReason, int pvLoopData, - [MarshalAs(UnmanagedType.LPArray)] NativeMethods.MSG[] pMsgPeeked); + [MarshalAs(UnmanagedType.LPArray)] NativeMethods.MSG[] pMsgPeeked); /// @@ -5260,7 +5402,7 @@ bool FQueryTerminate( /// Component should return the desired window or NULL if no such window /// exists. /// - + [PreserveSig] IntPtr HwndGetWindow( int dwWhich, @@ -5269,7 +5411,8 @@ IntPtr HwndGetWindow( [ComVisible(true), Guid("8CC497C0-A1DF-11ce-8098-00AA0047BE5D"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] - public interface ITextDocument { + public interface ITextDocument + { string GetName(); object GetSelection(); int GetStoryCount(); @@ -5293,7 +5436,8 @@ public interface ITextDocument { [ComVisible(true), Guid("8CC497C2-A1DF-11ce-8098-00AA0047BE5D"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] - public interface ITextRange { + public interface ITextRange + { string GetText(); void SetText(string text); object GetChar(); @@ -5348,70 +5492,72 @@ public interface ITextRange { }; [ComImport(), Guid("00020D03-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IRichEditOleCallback { + public interface IRichEditOleCallback + { [PreserveSig] int GetNewStorage(out IStorage ret); - + [PreserveSig] int GetInPlaceContext(IntPtr lplpFrame, IntPtr lplpDoc, IntPtr lpFrameInfo); - + [PreserveSig] int ShowContainerUI(int fShow); - + [PreserveSig] int QueryInsertObject(ref Guid lpclsid, IntPtr lpstg, int cp); - + [PreserveSig] int DeleteObject(IntPtr lpoleobj); - + [PreserveSig] int QueryAcceptData(IComDataObject lpdataobj, /* CLIPFORMAT* */ IntPtr lpcfFormat, int reco, int fReally, IntPtr hMetaPict); - + [PreserveSig] int ContextSensitiveHelp(int fEnterMode); - + [PreserveSig] int GetClipboardData(NativeMethods.CHARRANGE lpchrg, int reco, IntPtr lplpdataobj); [PreserveSig] int GetDragDropEffect(bool fDrag, int grfKeyState, ref int pdwEffect); - + [PreserveSig] int GetContextMenu(short seltype, IntPtr lpoleobj, NativeMethods.CHARRANGE lpchrg, out IntPtr hmenu); } - + [ComImport(), Guid("00000115-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IOleInPlaceUIWindow { - IntPtr GetWindow(); - - [PreserveSig] - int ContextSensitiveHelp( - - int fEnterMode); - - - [PreserveSig] - int GetBorder( - [Out] + public interface IOleInPlaceUIWindow + { + IntPtr GetWindow(); + + [PreserveSig] + int ContextSensitiveHelp( + + int fEnterMode); + + + [PreserveSig] + int GetBorder( + [Out] NativeMethods.COMRECT lprectBorder); - - [PreserveSig] - int RequestBorderSpace( - [In] + + [PreserveSig] + int RequestBorderSpace( + [In] NativeMethods.COMRECT pborderwidths); - - [PreserveSig] - int SetBorderSpace( - [In] + + [PreserveSig] + int SetBorderSpace( + [In] NativeMethods.COMRECT pborderwidths); - - void SetActiveObject( - [In, MarshalAs(UnmanagedType.Interface)] + + void SetActiveObject( + [In, MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.IOleInPlaceActiveObject pActiveObject, - [In, MarshalAs(UnmanagedType.LPWStr)] + [In, MarshalAs(UnmanagedType.LPWStr)] string pszObjName); @@ -5419,402 +5565,410 @@ void SetActiveObject( [ComImport(), Guid("00000117-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IOleInPlaceActiveObject { + public interface IOleInPlaceActiveObject + { - [PreserveSig] - int GetWindow( out IntPtr hwnd ); + [PreserveSig] + int GetWindow(out IntPtr hwnd); - - void ContextSensitiveHelp( - - int fEnterMode); - - [PreserveSig] - int TranslateAccelerator( - [In] + void ContextSensitiveHelp( + + int fEnterMode); + + + [PreserveSig] + int TranslateAccelerator( + [In] ref NativeMethods.MSG lpmsg); - - void OnFrameWindowActivate( - - bool fActivate); - - void OnDocWindowActivate( - - int fActivate); + void OnFrameWindowActivate( - - void ResizeBorder( - [In] + bool fActivate); + + + void OnDocWindowActivate( + + int fActivate); + + + void ResizeBorder( + [In] NativeMethods.COMRECT prcBorder, - [In] + [In] UnsafeNativeMethods.IOleInPlaceUIWindow pUIWindow, - - bool fFrameWindow); - - void EnableModeless( - - int fEnable); + bool fFrameWindow); + + + void EnableModeless( + + int fEnable); } [ComImport(), Guid("00000114-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IOleWindow { + public interface IOleWindow + { + + [PreserveSig] + int GetWindow([Out]out IntPtr hwnd); - [PreserveSig] - int GetWindow( [Out]out IntPtr hwnd ); - - void ContextSensitiveHelp( - - int fEnterMode); + void ContextSensitiveHelp( + + int fEnterMode); } [ComImport(), Guid("00000113-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IOleInPlaceObject { + public interface IOleInPlaceObject + { - [PreserveSig] - int GetWindow( [Out]out IntPtr hwnd ); + [PreserveSig] + int GetWindow([Out]out IntPtr hwnd); + + + void ContextSensitiveHelp( + + int fEnterMode); - - void ContextSensitiveHelp( - - int fEnterMode); - - void InPlaceDeactivate(); + void InPlaceDeactivate(); - - [PreserveSig] - int UIDeactivate(); - - void SetObjectRects( - [In] + [PreserveSig] + int UIDeactivate(); + + + void SetObjectRects( + [In] NativeMethods.COMRECT lprcPosRect, - [In] + [In] NativeMethods.COMRECT lprcClipRect); - - void ReactivateAndUndo(); + + void ReactivateAndUndo(); } [ComImport(), Guid("00000112-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IOleObject { + public interface IOleObject + { - [PreserveSig] - int SetClientSite( - [In, MarshalAs(UnmanagedType.Interface)] + [PreserveSig] + int SetClientSite( + [In, MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.IOleClientSite pClientSite); - - UnsafeNativeMethods.IOleClientSite GetClientSite(); - [PreserveSig] - int SetHostNames( - [In, MarshalAs(UnmanagedType.LPWStr)] + UnsafeNativeMethods.IOleClientSite GetClientSite(); + + [PreserveSig] + int SetHostNames( + [In, MarshalAs(UnmanagedType.LPWStr)] string szContainerApp, - [In, MarshalAs(UnmanagedType.LPWStr)] + [In, MarshalAs(UnmanagedType.LPWStr)] string szContainerObj); - [PreserveSig] - int Close( - - int dwSaveOption); + [PreserveSig] + int Close( + + int dwSaveOption); - [PreserveSig] - int SetMoniker( - [In, MarshalAs(UnmanagedType.U4)] + [PreserveSig] + int SetMoniker( + [In, MarshalAs(UnmanagedType.U4)] int dwWhichMoniker, - [In, MarshalAs(UnmanagedType.Interface)] + [In, MarshalAs(UnmanagedType.Interface)] object pmk); - [PreserveSig] - int GetMoniker( - [In, MarshalAs(UnmanagedType.U4)] + [PreserveSig] + int GetMoniker( + [In, MarshalAs(UnmanagedType.U4)] int dwAssign, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int dwWhichMoniker, - [Out, MarshalAs(UnmanagedType.Interface)] + [Out, MarshalAs(UnmanagedType.Interface)] out object moniker); - [PreserveSig] - int InitFromData( - [In, MarshalAs(UnmanagedType.Interface)] + [PreserveSig] + int InitFromData( + [In, MarshalAs(UnmanagedType.Interface)] IComDataObject pDataObject, - - int fCreation, - [In, MarshalAs(UnmanagedType.U4)] + + int fCreation, + [In, MarshalAs(UnmanagedType.U4)] int dwReserved); - [PreserveSig] - int GetClipboardData( - [In, MarshalAs(UnmanagedType.U4)] + [PreserveSig] + int GetClipboardData( + [In, MarshalAs(UnmanagedType.U4)] int dwReserved, - out IComDataObject data); + out IComDataObject data); - [PreserveSig] - int DoVerb( - - int iVerb, - [In] + [PreserveSig] + int DoVerb( + + int iVerb, + [In] IntPtr lpmsg, - [In, MarshalAs(UnmanagedType.Interface)] + [In, MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.IOleClientSite pActiveSite, - - int lindex, - - IntPtr hwndParent, - [In] + + int lindex, + + IntPtr hwndParent, + [In] NativeMethods.COMRECT lprcPosRect); - [PreserveSig] - int EnumVerbs(out UnsafeNativeMethods.IEnumOLEVERB e); + [PreserveSig] + int EnumVerbs(out UnsafeNativeMethods.IEnumOLEVERB e); - [PreserveSig] - int OleUpdate(); + [PreserveSig] + int OleUpdate(); - [PreserveSig] - int IsUpToDate(); + [PreserveSig] + int IsUpToDate(); - [PreserveSig] - int GetUserClassID( - [In, Out] + [PreserveSig] + int GetUserClassID( + [In, Out] ref Guid pClsid); - [PreserveSig] - int GetUserType( - [In, MarshalAs(UnmanagedType.U4)] + [PreserveSig] + int GetUserType( + [In, MarshalAs(UnmanagedType.U4)] int dwFormOfType, - [Out, MarshalAs(UnmanagedType.LPWStr)] + [Out, MarshalAs(UnmanagedType.LPWStr)] out string userType); - [PreserveSig] - int SetExtent( - [In, MarshalAs(UnmanagedType.U4)] + [PreserveSig] + int SetExtent( + [In, MarshalAs(UnmanagedType.U4)] int dwDrawAspect, - [In] + [In] NativeMethods.tagSIZEL pSizel); - [PreserveSig] - int GetExtent( - [In, MarshalAs(UnmanagedType.U4)] + [PreserveSig] + int GetExtent( + [In, MarshalAs(UnmanagedType.U4)] int dwDrawAspect, - [Out] + [Out] NativeMethods.tagSIZEL pSizel); - [PreserveSig] - int Advise( - IAdviseSink pAdvSink, - out int cookie); + [PreserveSig] + int Advise( + IAdviseSink pAdvSink, + out int cookie); - [PreserveSig] - int Unadvise( - [In, MarshalAs(UnmanagedType.U4)] + [PreserveSig] + int Unadvise( + [In, MarshalAs(UnmanagedType.U4)] int dwConnection); - [PreserveSig] - int EnumAdvise(out IEnumSTATDATA e); + [PreserveSig] + int EnumAdvise(out IEnumSTATDATA e); - [PreserveSig] - int GetMiscStatus( - [In, MarshalAs(UnmanagedType.U4)] + [PreserveSig] + int GetMiscStatus( + [In, MarshalAs(UnmanagedType.U4)] int dwAspect, - out int misc); + out int misc); - [PreserveSig] - int SetColorScheme( - [In] + [PreserveSig] + int SetColorScheme( + [In] NativeMethods.tagLOGPALETTE pLogpal); } - + [ComImport(), Guid("1C2056CC-5EF4-101B-8BC8-00AA003E3B29"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IOleInPlaceObjectWindowless { + public interface IOleInPlaceObjectWindowless + { - [PreserveSig] - int SetClientSite( - [In, MarshalAs(UnmanagedType.Interface)] + [PreserveSig] + int SetClientSite( + [In, MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.IOleClientSite pClientSite); - [PreserveSig] - int GetClientSite(out UnsafeNativeMethods.IOleClientSite site); + [PreserveSig] + int GetClientSite(out UnsafeNativeMethods.IOleClientSite site); - [PreserveSig] - int SetHostNames( - [In, MarshalAs(UnmanagedType.LPWStr)] + [PreserveSig] + int SetHostNames( + [In, MarshalAs(UnmanagedType.LPWStr)] string szContainerApp, - [In, MarshalAs(UnmanagedType.LPWStr)] + [In, MarshalAs(UnmanagedType.LPWStr)] string szContainerObj); - [PreserveSig] - int Close( - - int dwSaveOption); + [PreserveSig] + int Close( - [PreserveSig] - int SetMoniker( - [In, MarshalAs(UnmanagedType.U4)] + int dwSaveOption); + + [PreserveSig] + int SetMoniker( + [In, MarshalAs(UnmanagedType.U4)] int dwWhichMoniker, - [In, MarshalAs(UnmanagedType.Interface)] + [In, MarshalAs(UnmanagedType.Interface)] object pmk); - [PreserveSig] - int GetMoniker( - [In, MarshalAs(UnmanagedType.U4)] + [PreserveSig] + int GetMoniker( + [In, MarshalAs(UnmanagedType.U4)] int dwAssign, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int dwWhichMoniker, - [Out, MarshalAs(UnmanagedType.Interface)] + [Out, MarshalAs(UnmanagedType.Interface)] out object moniker); - [PreserveSig] - int InitFromData( - [In, MarshalAs(UnmanagedType.Interface)] + [PreserveSig] + int InitFromData( + [In, MarshalAs(UnmanagedType.Interface)] IComDataObject pDataObject, - - int fCreation, - [In, MarshalAs(UnmanagedType.U4)] + + int fCreation, + [In, MarshalAs(UnmanagedType.U4)] int dwReserved); - [PreserveSig] - int GetClipboardData( - [In, MarshalAs(UnmanagedType.U4)] + [PreserveSig] + int GetClipboardData( + [In, MarshalAs(UnmanagedType.U4)] int dwReserved, - out IComDataObject data); + out IComDataObject data); - [PreserveSig] - int DoVerb( - - int iVerb, - [In] + [PreserveSig] + int DoVerb( + + int iVerb, + [In] IntPtr lpmsg, - [In, MarshalAs(UnmanagedType.Interface)] + [In, MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.IOleClientSite pActiveSite, - - int lindex, - - IntPtr hwndParent, - [In] + + int lindex, + + IntPtr hwndParent, + [In] NativeMethods.COMRECT lprcPosRect); - [PreserveSig] - int EnumVerbs(out UnsafeNativeMethods.IEnumOLEVERB e); + [PreserveSig] + int EnumVerbs(out UnsafeNativeMethods.IEnumOLEVERB e); - [PreserveSig] - int OleUpdate(); + [PreserveSig] + int OleUpdate(); - [PreserveSig] - int IsUpToDate(); + [PreserveSig] + int IsUpToDate(); - [PreserveSig] - int GetUserClassID( - [In, Out] + [PreserveSig] + int GetUserClassID( + [In, Out] ref Guid pClsid); - [PreserveSig] - int GetUserType( - [In, MarshalAs(UnmanagedType.U4)] + [PreserveSig] + int GetUserType( + [In, MarshalAs(UnmanagedType.U4)] int dwFormOfType, - [Out, MarshalAs(UnmanagedType.LPWStr)] + [Out, MarshalAs(UnmanagedType.LPWStr)] out string userType); - [PreserveSig] - int SetExtent( - [In, MarshalAs(UnmanagedType.U4)] + [PreserveSig] + int SetExtent( + [In, MarshalAs(UnmanagedType.U4)] int dwDrawAspect, - [In] + [In] NativeMethods.tagSIZEL pSizel); - [PreserveSig] - int GetExtent( - [In, MarshalAs(UnmanagedType.U4)] + [PreserveSig] + int GetExtent( + [In, MarshalAs(UnmanagedType.U4)] int dwDrawAspect, - [Out] + [Out] NativeMethods.tagSIZEL pSizel); - [PreserveSig] - int Advise( - [In, MarshalAs(UnmanagedType.Interface)] + [PreserveSig] + int Advise( + [In, MarshalAs(UnmanagedType.Interface)] IAdviseSink pAdvSink, - out int cookie); + out int cookie); - [PreserveSig] - int Unadvise( - [In, MarshalAs(UnmanagedType.U4)] + [PreserveSig] + int Unadvise( + [In, MarshalAs(UnmanagedType.U4)] int dwConnection); - [PreserveSig] - int EnumAdvise(out IEnumSTATDATA e); + [PreserveSig] + int EnumAdvise(out IEnumSTATDATA e); - [PreserveSig] - int GetMiscStatus( - [In, MarshalAs(UnmanagedType.U4)] + [PreserveSig] + int GetMiscStatus( + [In, MarshalAs(UnmanagedType.U4)] int dwAspect, - out int misc); + out int misc); - [PreserveSig] - int SetColorScheme( - [In] + [PreserveSig] + int SetColorScheme( + [In] NativeMethods.tagLOGPALETTE pLogpal); - - [PreserveSig] - int OnWindowMessage( - [In, MarshalAs(UnmanagedType.U4)] int msg, - [In, MarshalAs(UnmanagedType.U4)] int wParam, - [In, MarshalAs(UnmanagedType.U4)] int lParam, - [Out, MarshalAs(UnmanagedType.U4)] int plResult); - - [PreserveSig] - int GetDropTarget( - [Out, MarshalAs(UnmanagedType.Interface)] object ppDropTarget); + + [PreserveSig] + int OnWindowMessage( + [In, MarshalAs(UnmanagedType.U4)] int msg, + [In, MarshalAs(UnmanagedType.U4)] int wParam, + [In, MarshalAs(UnmanagedType.U4)] int lParam, + [Out, MarshalAs(UnmanagedType.U4)] int plResult); + + [PreserveSig] + int GetDropTarget( + [Out, MarshalAs(UnmanagedType.Interface)] object ppDropTarget); }; - + [ComImport(), Guid("B196B288-BAB4-101A-B69C-00AA00341D07"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IOleControl { - [PreserveSig] - int GetControlInfo( - [Out] + public interface IOleControl + { + [PreserveSig] + int GetControlInfo( + [Out] NativeMethods.tagCONTROLINFO pCI); - [PreserveSig] - int OnMnemonic( - [In] + [PreserveSig] + int OnMnemonic( + [In] ref NativeMethods.MSG pMsg); - [PreserveSig] - int OnAmbientPropertyChange( - - int dispID); + [PreserveSig] + int OnAmbientPropertyChange( + + int dispID); + + [PreserveSig] + int FreezeEvents( - [PreserveSig] - int FreezeEvents( - - int bFreeze); + int bFreeze); } [ComImport(), Guid("6D5140C1-7436-11CE-8034-00AA006009FA"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IOleServiceProvider { - [PreserveSig] - int QueryService( - [In] + public interface IOleServiceProvider + { + [PreserveSig] + int QueryService( + [In] ref Guid guidService, - [In] + [In] ref Guid riid, - out IntPtr ppvObject); + out IntPtr ppvObject); } [ComImport(), Guid("0000010d-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IViewObject { + public interface IViewObject + { [PreserveSig] int Draw( [In, MarshalAs(UnmanagedType.U4)] @@ -5838,7 +5992,7 @@ int Draw( [In] int dwContinue); - + [PreserveSig] int GetColorSet( [In, MarshalAs(UnmanagedType.U4)] @@ -5870,7 +6024,7 @@ int Unfreeze( [In, MarshalAs(UnmanagedType.U4)] int dwFreeze); - + void SetAdvise( [In, MarshalAs(UnmanagedType.U4)] int aspects, @@ -5879,7 +6033,7 @@ void SetAdvise( [In, MarshalAs(UnmanagedType.Interface)] IAdviseSink pAdvSink); - + void GetAdvise( // These can be NULL if caller doesn't want them [In, Out, MarshalAs(UnmanagedType.LPArray)] @@ -5892,7 +6046,8 @@ void GetAdvise( IAdviseSink[] pAdvSink); } [ComImport(), Guid("00000127-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IViewObject2 /* : IViewObject */ { + public interface IViewObject2 /* : IViewObject */ + { void Draw( [In, MarshalAs(UnmanagedType.U4)] int dwDrawAspect, @@ -5915,7 +6070,7 @@ void Draw( [In] int dwContinue); - + [PreserveSig] int GetColorSet( [In, MarshalAs(UnmanagedType.U4)] @@ -5931,7 +6086,7 @@ int GetColorSet( [Out] NativeMethods.tagLOGPALETTE ppColorSet); - + [PreserveSig] int Freeze( [In, MarshalAs(UnmanagedType.U4)] @@ -5943,13 +6098,13 @@ int Freeze( [Out] IntPtr pdwFreeze); - + [PreserveSig] int Unfreeze( [In, MarshalAs(UnmanagedType.U4)] int dwFreeze); - + void SetAdvise( [In, MarshalAs(UnmanagedType.U4)] int aspects, @@ -5958,7 +6113,7 @@ void SetAdvise( [In, MarshalAs(UnmanagedType.Interface)] IAdviseSink pAdvSink); - + void GetAdvise( // These can be NULL if caller doesn't want them [In, Out, MarshalAs(UnmanagedType.LPArray)] @@ -5970,7 +6125,7 @@ void GetAdvise( [In, Out, MarshalAs(UnmanagedType.LPArray)] IAdviseSink[] pAdvSink); - + void GetExtent( [In, MarshalAs(UnmanagedType.U4)] int dwDrawAspect, @@ -5983,30 +6138,32 @@ void GetExtent( } [ComImport(), Guid("0000010C-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IPersist { + public interface IPersist + { void GetClassID( - [Out] + [Out] out Guid pClassID); } [ComImport(), Guid("37D84F60-42CB-11CE-8135-00AA004BB851"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IPersistPropertyBag { + public interface IPersistPropertyBag + { void GetClassID( [Out] out Guid pClassID); - + void InitNew(); - + void Load( [In, MarshalAs(UnmanagedType.Interface)] IPropertyBag pPropBag, [In, MarshalAs(UnmanagedType.Interface)] IErrorLog pErrorLog); - + void Save( [In, MarshalAs(UnmanagedType.Interface)] IPropertyBag pPropBag, @@ -6016,25 +6173,26 @@ void Save( bool fSaveAllProperties); } [ - ComImport(), + ComImport(), Guid("CF51ED10-62FE-11CF-BF86-00A0C9034836"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown) ] - public interface IQuickActivate { + public interface IQuickActivate + { void QuickActivate( - [In] + [In] UnsafeNativeMethods.tagQACONTAINER pQaContainer, - [Out] + [Out] UnsafeNativeMethods.tagQACONTROL pQaControl); - + void SetContentExtent( - [In] + [In] NativeMethods.tagSIZEL pSizel); - + void GetContentExtent( - [Out] + [Out] NativeMethods.tagSIZEL pSizel); } @@ -6045,10 +6203,11 @@ public class SMsoComponentManager { } - [ComImport(), Guid("55272A00-42CB-11CE-8135-00AA004BB851"), + [ComImport(), Guid("55272A00-42CB-11CE-8135-00AA004BB851"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown) ] - public interface IPropertyBag { + public interface IPropertyBag + { [PreserveSig] int Read( [In, MarshalAs(UnmanagedType.LPWStr)] @@ -6066,825 +6225,880 @@ int Write( ref object pVar); } - [ComImport(), Guid("3127CA40-446E-11CE-8135-00AA004BB851"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IErrorLog { - void AddError( - [In, MarshalAs(UnmanagedType.LPWStr)] + [ComImport(), Guid("3127CA40-446E-11CE-8135-00AA004BB851"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + public interface IErrorLog + { + void AddError( + [In, MarshalAs(UnmanagedType.LPWStr)] string pszPropName_p0, - [In, MarshalAs(UnmanagedType.Struct)] + [In, MarshalAs(UnmanagedType.Struct)] NativeMethods.tagEXCEPINFO pExcepInfo_p1); - } + } - [ComImport(), Guid("00000109-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IPersistStream { + [ComImport(), Guid("00000109-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + public interface IPersistStream + { - void GetClassID([Out] out Guid pClassId); + void GetClassID([Out] out Guid pClassId); - [PreserveSig] - int IsDirty(); + [PreserveSig] + int IsDirty(); - - void Load( - [In, MarshalAs(UnmanagedType.Interface)] + + void Load( + [In, MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.IStream pstm); - - void Save( - [In, MarshalAs(UnmanagedType.Interface)] + + void Save( + [In, MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.IStream pstm, - [In, MarshalAs(UnmanagedType.Bool)] + [In, MarshalAs(UnmanagedType.Bool)] bool fClearDirty); - - long GetSizeMax(); + long GetSizeMax(); - } - [ComImport(), - Guid("7FD52380-4E07-101B-AE2D-08002B2EC713"), - InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IPersistStreamInit { - void GetClassID( - [Out] + } + + [ComImport(), + Guid("7FD52380-4E07-101B-AE2D-08002B2EC713"), + InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + public interface IPersistStreamInit + { + void GetClassID( + [Out] out Guid pClassID); - [PreserveSig] - int IsDirty(); + [PreserveSig] + int IsDirty(); + - - void Load( - [In, MarshalAs(UnmanagedType.Interface)] + void Load( + [In, MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.IStream pstm); - - void Save( - [In, MarshalAs(UnmanagedType.Interface)] + + void Save( + [In, MarshalAs(UnmanagedType.Interface)] IStream pstm, - [In, MarshalAs(UnmanagedType.Bool)] + [In, MarshalAs(UnmanagedType.Bool)] bool fClearDirty); - - void GetSizeMax( - [Out, MarshalAs(UnmanagedType.LPArray)] + + void GetSizeMax( + [Out, MarshalAs(UnmanagedType.LPArray)] long pcbSize); - - void InitNew(); + void InitNew(); - } - [ComImport(), - Guid("B196B286-BAB4-101A-B69C-00AA00341D07"), - InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IConnectionPoint { + } - [PreserveSig] - int GetConnectionInterface(out Guid iid); + [ComImport(), + Guid("B196B286-BAB4-101A-B69C-00AA00341D07"), + InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + public interface IConnectionPoint + { + [PreserveSig] + int GetConnectionInterface(out Guid iid); - [PreserveSig] - int GetConnectionPointContainer( - [MarshalAs(UnmanagedType.Interface)] + + [PreserveSig] + int GetConnectionPointContainer( + [MarshalAs(UnmanagedType.Interface)] ref IConnectionPointContainer pContainer); - [PreserveSig] - int Advise( - [In, MarshalAs(UnmanagedType.Interface)] + [PreserveSig] + int Advise( + [In, MarshalAs(UnmanagedType.Interface)] object pUnkSink, - ref int cookie); + ref int cookie); - [PreserveSig] - int Unadvise( + [PreserveSig] + int Unadvise( - int cookie); + int cookie); - [PreserveSig] - int EnumConnections(out object pEnum); + [PreserveSig] + int EnumConnections(out object pEnum); - } + } - [ComImport(), Guid("0000010A-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IPersistStorage { - void GetClassID( - [Out] + [ComImport(), Guid("0000010A-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + public interface IPersistStorage + { + void GetClassID( + [Out] out Guid pClassID); - [PreserveSig] - int IsDirty(); - - void InitNew(IStorage pstg); - - [PreserveSig] - int Load(IStorage pstg); - - void Save(IStorage pStgSave, bool fSameAsLoad); - - void SaveCompleted(IStorage pStgNew); - - void HandsOffStorage(); - } + [PreserveSig] + int IsDirty(); + + void InitNew(IStorage pstg); + + [PreserveSig] + int Load(IStorage pstg); + + void Save(IStorage pStgSave, bool fSameAsLoad); - [ComImport(), Guid("00020404-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IEnumVariant { - [PreserveSig] - int Next( - [In, MarshalAs(UnmanagedType.U4)] + void SaveCompleted(IStorage pStgNew); + + void HandsOffStorage(); + } + + [ComImport(), Guid("00020404-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + public interface IEnumVariant + { + [PreserveSig] + int Next( + [In, MarshalAs(UnmanagedType.U4)] int celt, - [In, Out] + [In, Out] IntPtr rgvar, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] int[] pceltFetched); - - void Skip( - [In, MarshalAs(UnmanagedType.U4)] + + void Skip( + [In, MarshalAs(UnmanagedType.U4)] int celt); - void Reset(); - - void Clone( - [Out, MarshalAs(UnmanagedType.LPArray)] + void Reset(); + + void Clone( + [Out, MarshalAs(UnmanagedType.LPArray)] UnsafeNativeMethods.IEnumVariant[] ppenum); - } + } - [ComImport(), Guid("00000104-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IEnumOLEVERB { + [ComImport(), Guid("00000104-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + public interface IEnumOLEVERB + { - [PreserveSig] - int Next( - [MarshalAs(UnmanagedType.U4)] + [PreserveSig] + int Next( + [MarshalAs(UnmanagedType.U4)] int celt, - [Out] + [Out] NativeMethods.tagOLEVERB rgelt, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] int[] pceltFetched); - [PreserveSig] - int Skip( - [In, MarshalAs(UnmanagedType.U4)] + [PreserveSig] + int Skip( + [In, MarshalAs(UnmanagedType.U4)] int celt); - - void Reset(); - - void Clone( - out IEnumOLEVERB ppenum); - } + void Reset(); - // INTERFACE: IEnumACString - - // This interface was implemented to return autocomplete strings - // into the caller's buffer (to reduce the number of memory allocations - // A sort index is also returned to control the order of items displayed - // by autocomplete. The sort index should be set to zero if unused - // The NextItem method increments the current index by one (similar to Next - // when one item is requested - - //public interface IEnumString - //Do not declare IEnumString here -- use IEnumString from interopservices. - // even if it looks like it works, if you declaring the marshalling incorrectly, it will have issues with appverifier. - - - //------------------------------------------------------------------------- - // IAutoComplete interface - // [Member functions] - // IAutoComplete::Init(hwndEdit, punkACL, pwszRegKeyPath, pwszQuickComplete) - // This function initializes an AutoComplete object, telling it - // what control to subclass, and what list of strings to process. - // IAutoComplete::Enable(fEnable) - // This function enables or disables the AutoComplete functionality. - //------------------------------------------------------------------------- - - [ComImport(), Guid("00bb2762-6a77-11d0-a535-00c04fd7d062"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IAutoComplete - { - - int Init( - [In] HandleRef hwndEdit, // hwnd of editbox or editbox deriviative. - [In] System.Runtime.InteropServices.ComTypes.IEnumString punkACL, // Pointer to object containing string to complete from. (IEnumString *) - [In] string pwszRegKeyPath, // - [In] string pwszQuickComplete - ); - void Enable([In] bool fEnable); // Is it enabled? - } - - - [ComImport(), Guid("EAC04BC0-3791-11d2-BB95-0060977B464C"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - - public interface IAutoComplete2 - { - int Init( - [In] HandleRef hwndEdit, // hwnd of editbox or editbox deriviative. - [In] System.Runtime.InteropServices.ComTypes.IEnumString punkACL, // Pointer to object containing string to complete from. (IEnumString *) - [In] string pwszRegKeyPath, // - [In] string pwszQuickComplete - ); - void Enable([In] bool fEnable); // Is it enabled? - - int SetOptions([In] int dwFlag); - void GetOptions([Out] IntPtr pdwFlag); - } - [ComImport(), Guid("0000000C-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IStream { + void Clone( + out IEnumOLEVERB ppenum); + } + + // INTERFACE: IEnumACString + + // This interface was implemented to return autocomplete strings + // into the caller's buffer (to reduce the number of memory allocations + // A sort index is also returned to control the order of items displayed + // by autocomplete. The sort index should be set to zero if unused + // The NextItem method increments the current index by one (similar to Next + // when one item is requested + + //public interface IEnumString + //Do not declare IEnumString here -- use IEnumString from interopservices. + // even if it looks like it works, if you declaring the marshalling incorrectly, it will have issues with appverifier. + + + //------------------------------------------------------------------------- + // IAutoComplete interface + // [Member functions] + // IAutoComplete::Init(hwndEdit, punkACL, pwszRegKeyPath, pwszQuickComplete) + // This function initializes an AutoComplete object, telling it + // what control to subclass, and what list of strings to process. + // IAutoComplete::Enable(fEnable) + // This function enables or disables the AutoComplete functionality. + //------------------------------------------------------------------------- + + [ComImport(), Guid("00bb2762-6a77-11d0-a535-00c04fd7d062"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + public interface IAutoComplete + { + + int Init( + [In] HandleRef hwndEdit, // hwnd of editbox or editbox deriviative. + [In] System.Runtime.InteropServices.ComTypes.IEnumString punkACL, // Pointer to object containing string to complete from. (IEnumString *) + [In] string pwszRegKeyPath, // + [In] string pwszQuickComplete + ); + void Enable([In] bool fEnable); // Is it enabled? + } - int Read( - IntPtr buf, + [ComImport(), Guid("EAC04BC0-3791-11d2-BB95-0060977B464C"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - int len); + public interface IAutoComplete2 + { + int Init( + [In] HandleRef hwndEdit, // hwnd of editbox or editbox deriviative. + [In] System.Runtime.InteropServices.ComTypes.IEnumString punkACL, // Pointer to object containing string to complete from. (IEnumString *) + [In] string pwszRegKeyPath, // + [In] string pwszQuickComplete + ); + void Enable([In] bool fEnable); // Is it enabled? - - int Write( + int SetOptions([In] int dwFlag); + void GetOptions([Out] IntPtr pdwFlag); + } - IntPtr buf, + [ComImport(), Guid("0000000C-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + public interface IStream + { + + int Read( - int len); + IntPtr buf, - [return: MarshalAs(UnmanagedType.I8)] - long Seek( - [In, MarshalAs(UnmanagedType.I8)] + int len); + + + int Write( + + IntPtr buf, + + int len); + + [return: MarshalAs(UnmanagedType.I8)] + long Seek( + [In, MarshalAs(UnmanagedType.I8)] long dlibMove, - int dwOrigin); + int dwOrigin); + - - void SetSize( - [In, MarshalAs(UnmanagedType.I8)] + void SetSize( + [In, MarshalAs(UnmanagedType.I8)] long libNewSize); - [return: MarshalAs(UnmanagedType.I8)] - long CopyTo( - [In, MarshalAs(UnmanagedType.Interface)] + [return: MarshalAs(UnmanagedType.I8)] + long CopyTo( + [In, MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.IStream pstm, - [In, MarshalAs(UnmanagedType.I8)] + [In, MarshalAs(UnmanagedType.I8)] long cb, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] long[] pcbRead); - - void Commit( - int grfCommitFlags); + void Commit( + + int grfCommitFlags); + - - void Revert(); + void Revert(); - - void LockRegion( - [In, MarshalAs(UnmanagedType.I8)] + + void LockRegion( + [In, MarshalAs(UnmanagedType.I8)] long libOffset, - [In, MarshalAs(UnmanagedType.I8)] + [In, MarshalAs(UnmanagedType.I8)] long cb, - int dwLockType); + int dwLockType); + - - void UnlockRegion( - [In, MarshalAs(UnmanagedType.I8)] + void UnlockRegion( + [In, MarshalAs(UnmanagedType.I8)] long libOffset, - [In, MarshalAs(UnmanagedType.I8)] + [In, MarshalAs(UnmanagedType.I8)] long cb, - int dwLockType); + int dwLockType); - - void Stat( - [Out] - NativeMethods.STATSTG pStatstg, - int grfStatFlag); - [return: MarshalAs(UnmanagedType.Interface)] - UnsafeNativeMethods.IStream Clone(); - } + void Stat( + [Out] + NativeMethods.STATSTG pStatstg, + int grfStatFlag); - public abstract class CharBuffer - { + [return: MarshalAs(UnmanagedType.Interface)] + UnsafeNativeMethods.IStream Clone(); + } - public static CharBuffer CreateBuffer(int size) + public abstract class CharBuffer { - return new UnicodeCharBuffer(size); + + public static CharBuffer CreateBuffer(int size) + { + return new UnicodeCharBuffer(size); + } + + public abstract IntPtr AllocCoTaskMem(); + public abstract string GetString(); + public abstract void PutCoTaskMem(IntPtr ptr); + public abstract void PutString(string s); } - public abstract IntPtr AllocCoTaskMem(); - public abstract string GetString(); - public abstract void PutCoTaskMem(IntPtr ptr); - public abstract void PutString(string s); - } + public class UnicodeCharBuffer : CharBuffer + { - public class UnicodeCharBuffer : CharBuffer - { + internal char[] buffer; + internal int offset; - internal char[] buffer; - internal int offset; + public UnicodeCharBuffer(int size) + { + buffer = new char[size]; + } - public UnicodeCharBuffer(int size) - { - buffer = new char[size]; - } + public override IntPtr AllocCoTaskMem() + { + IntPtr result = Marshal.AllocCoTaskMem(buffer.Length * 2); + Marshal.Copy(buffer, 0, result, buffer.Length); + return result; + } - public override IntPtr AllocCoTaskMem() - { - IntPtr result = Marshal.AllocCoTaskMem(buffer.Length * 2); - Marshal.Copy(buffer, 0, result, buffer.Length); - return result; - } + public override string GetString() + { + int i = offset; + while (i < buffer.Length && buffer[i] != 0) + i++; + string result = new string(buffer, offset, i - offset); + if (i < buffer.Length) + i++; + offset = i; + return result; + } - public override string GetString() - { - int i = offset; - while (i < buffer.Length && buffer[i] != 0) i++; - string result = new string(buffer, offset, i - offset); - if (i < buffer.Length) i++; - offset = i; - return result; - } + public override void PutCoTaskMem(IntPtr ptr) + { + Marshal.Copy(ptr, buffer, 0, buffer.Length); + offset = 0; + } - public override void PutCoTaskMem(IntPtr ptr) - { - Marshal.Copy(ptr, buffer, 0, buffer.Length); - offset = 0; + public override void PutString(string s) + { + int count = Math.Min(s.Length, buffer.Length - offset); + s.CopyTo(0, buffer, offset, count); + offset += count; + if (offset < buffer.Length) + buffer[offset++] = (char)0; + } } - public override void PutString(string s) + public class ComStreamFromDataStream : IStream { - int count = Math.Min(s.Length, buffer.Length - offset); - s.CopyTo(0, buffer, offset, count); - offset += count; - if (offset < buffer.Length) buffer[offset++] = (char)0; - } - } + protected Stream dataStream; - public class ComStreamFromDataStream : IStream { - protected Stream dataStream; + // to support seeking ahead of the stream length... + private long virtualPosition = -1; - // to support seeking ahead of the stream length... - private long virtualPosition = -1; + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + public ComStreamFromDataStream(Stream dataStream) + { + if (dataStream == null) + throw new ArgumentNullException(nameof(dataStream)); + this.dataStream = dataStream; + } - [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - public ComStreamFromDataStream(Stream dataStream) - { - if (dataStream == null) throw new ArgumentNullException(nameof(dataStream)); - this.dataStream = dataStream; - } - - private void ActualizeVirtualPosition() { - if (virtualPosition == -1) return; - - if (virtualPosition > dataStream.Length) - dataStream.SetLength(virtualPosition); - - dataStream.Position = virtualPosition; - - virtualPosition = -1; - } + private void ActualizeVirtualPosition() + { + if (virtualPosition == -1) + return; - public IStream Clone() { - NotImplemented(); - return null; - } + if (virtualPosition > dataStream.Length) + dataStream.SetLength(virtualPosition); - public void Commit(int grfCommitFlags) { - dataStream.Flush(); - // Extend the length of the file if needed. - ActualizeVirtualPosition(); - } + dataStream.Position = virtualPosition; - public long CopyTo(IStream pstm, long cb, long[] pcbRead) { - int bufsize = 4096; // one page - IntPtr buffer = Marshal.AllocHGlobal(bufsize); - if (buffer == IntPtr.Zero) throw new OutOfMemoryException(); - long written = 0; - try { - while (written < cb) { - int toRead = bufsize; - if (written + toRead > cb) toRead = (int) (cb - written); - int read = Read(buffer, toRead); - if (read == 0) break; - if (pstm.Write(buffer, read) != read) { - throw EFail("Wrote an incorrect number of bytes"); - } - written += read; - } - } - finally { - Marshal.FreeHGlobal(buffer); + virtualPosition = -1; } - if (pcbRead != null && pcbRead.Length > 0) { - pcbRead[0] = written; + + public IStream Clone() + { + NotImplemented(); + return null; } - return written; - } + public void Commit(int grfCommitFlags) + { + dataStream.Flush(); + // Extend the length of the file if needed. + ActualizeVirtualPosition(); + } - public Stream GetDataStream() { - return dataStream; - } + public long CopyTo(IStream pstm, long cb, long[] pcbRead) + { + int bufsize = 4096; // one page + IntPtr buffer = Marshal.AllocHGlobal(bufsize); + if (buffer == IntPtr.Zero) + throw new OutOfMemoryException(); + long written = 0; + try + { + while (written < cb) + { + int toRead = bufsize; + if (written + toRead > cb) + toRead = (int)(cb - written); + int read = Read(buffer, toRead); + if (read == 0) + break; + if (pstm.Write(buffer, read) != read) + { + throw EFail("Wrote an incorrect number of bytes"); + } + written += read; + } + } + finally + { + Marshal.FreeHGlobal(buffer); + } + if (pcbRead != null && pcbRead.Length > 0) + { + pcbRead[0] = written; + } - public void LockRegion(long libOffset, long cb, int dwLockType) { - } + return written; + } - protected static ExternalException EFail(string msg) { - ExternalException e = new ExternalException(msg, NativeMethods.E_FAIL); - throw e; - } - - protected static void NotImplemented() { - ExternalException e = new ExternalException(SR.UnsafeNativeMethodsNotImplemented, NativeMethods.E_NOTIMPL); - throw e; - } + public Stream GetDataStream() + { + return dataStream; + } - public int Read(IntPtr buf, /* cpr: int offset,*/ int length) { - // System.Text.Out.WriteLine("IStream::Read(" + length + ")"); - byte[] buffer = new byte[length]; - int count = Read(buffer, length); - Marshal.Copy(buffer, 0, buf, count); - return count; - } + public void LockRegion(long libOffset, long cb, int dwLockType) + { + } - public int Read(byte[] buffer, /* cpr: int offset,*/ int length) { - ActualizeVirtualPosition(); - return dataStream.Read(buffer, 0, length); - } + protected static ExternalException EFail(string msg) + { + ExternalException e = new ExternalException(msg, NativeMethods.E_FAIL); + throw e; + } - public void Revert() { - NotImplemented(); - } + protected static void NotImplemented() + { + ExternalException e = new ExternalException(SR.UnsafeNativeMethodsNotImplemented, NativeMethods.E_NOTIMPL); + throw e; + } - public long Seek(long offset, int origin) { - // Console.WriteLine("IStream::Seek("+ offset + ", " + origin + ")"); - long pos = virtualPosition; - if (virtualPosition == -1) { - pos = dataStream.Position; + public int Read(IntPtr buf, /* cpr: int offset,*/ int length) + { + // System.Text.Out.WriteLine("IStream::Read(" + length + ")"); + byte[] buffer = new byte[length]; + int count = Read(buffer, length); + Marshal.Copy(buffer, 0, buf, count); + return count; } - long len = dataStream.Length; - switch (origin) { - case NativeMethods.STREAM_SEEK_SET: - if (offset <= len) { - dataStream.Position = offset; - virtualPosition = -1; - } - else { - virtualPosition = offset; - } - break; - case NativeMethods.STREAM_SEEK_END: - if (offset <= 0) { - dataStream.Position = len + offset; - virtualPosition = -1; - } - else { - virtualPosition = len + offset; - } - break; - case NativeMethods.STREAM_SEEK_CUR: - if (offset+pos <= len) { - dataStream.Position = pos + offset; - virtualPosition = -1; - } - else { - virtualPosition = offset + pos; - } - break; + + public int Read(byte[] buffer, /* cpr: int offset,*/ int length) + { + ActualizeVirtualPosition(); + return dataStream.Read(buffer, 0, length); } - if (virtualPosition != -1) { - return virtualPosition; + + public void Revert() + { + NotImplemented(); } - else { - return dataStream.Position; + + public long Seek(long offset, int origin) + { + // Console.WriteLine("IStream::Seek("+ offset + ", " + origin + ")"); + long pos = virtualPosition; + if (virtualPosition == -1) + { + pos = dataStream.Position; + } + long len = dataStream.Length; + switch (origin) + { + case NativeMethods.STREAM_SEEK_SET: + if (offset <= len) + { + dataStream.Position = offset; + virtualPosition = -1; + } + else + { + virtualPosition = offset; + } + break; + case NativeMethods.STREAM_SEEK_END: + if (offset <= 0) + { + dataStream.Position = len + offset; + virtualPosition = -1; + } + else + { + virtualPosition = len + offset; + } + break; + case NativeMethods.STREAM_SEEK_CUR: + if (offset + pos <= len) + { + dataStream.Position = pos + offset; + virtualPosition = -1; + } + else + { + virtualPosition = offset + pos; + } + break; + } + if (virtualPosition != -1) + { + return virtualPosition; + } + else + { + return dataStream.Position; + } } - } - public void SetSize(long value) { - dataStream.SetLength(value); - } + public void SetSize(long value) + { + dataStream.SetLength(value); + } - public void Stat(NativeMethods.STATSTG pstatstg, int grfStatFlag) { - pstatstg.type = 2; // STGTY_STREAM - pstatstg.cbSize = dataStream.Length; - pstatstg.grfLocksSupported = 2; //LOCK_EXCLUSIVE - } + public void Stat(NativeMethods.STATSTG pstatstg, int grfStatFlag) + { + pstatstg.type = 2; // STGTY_STREAM + pstatstg.cbSize = dataStream.Length; + pstatstg.grfLocksSupported = 2; //LOCK_EXCLUSIVE + } - public void UnlockRegion(long libOffset, long cb, int dwLockType) { - } + public void UnlockRegion(long libOffset, long cb, int dwLockType) + { + } - public int Write(IntPtr buf, /* cpr: int offset,*/ int length) { - byte[] buffer = new byte[length]; - Marshal.Copy(buf, buffer, 0, length); - return Write(buffer, length); - } + public int Write(IntPtr buf, /* cpr: int offset,*/ int length) + { + byte[] buffer = new byte[length]; + Marshal.Copy(buf, buffer, 0, length); + return Write(buffer, length); + } - public int Write(byte[] buffer, /* cpr: int offset,*/ int length) { - ActualizeVirtualPosition(); - dataStream.Write(buffer, 0, length); - return length; + public int Write(byte[] buffer, /* cpr: int offset,*/ int length) + { + ActualizeVirtualPosition(); + dataStream.Write(buffer, 0, length); + return length; + } } - } - [ComImport(), Guid("0000000B-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IStorage { + [ComImport(), Guid("0000000B-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + public interface IStorage + { - [return: MarshalAs(UnmanagedType.Interface)] - UnsafeNativeMethods.IStream CreateStream( - [In, MarshalAs(UnmanagedType.BStr)] + [return: MarshalAs(UnmanagedType.Interface)] + UnsafeNativeMethods.IStream CreateStream( + [In, MarshalAs(UnmanagedType.BStr)] string pwcsName, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int grfMode, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int reserved1, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int reserved2); - [return: MarshalAs(UnmanagedType.Interface)] - UnsafeNativeMethods.IStream OpenStream( - [In, MarshalAs(UnmanagedType.BStr)] + [return: MarshalAs(UnmanagedType.Interface)] + UnsafeNativeMethods.IStream OpenStream( + [In, MarshalAs(UnmanagedType.BStr)] string pwcsName, - IntPtr reserved1, - [In, MarshalAs(UnmanagedType.U4)] + IntPtr reserved1, + [In, MarshalAs(UnmanagedType.U4)] int grfMode, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int reserved2); - [return: MarshalAs(UnmanagedType.Interface)] - UnsafeNativeMethods.IStorage CreateStorage( - [In, MarshalAs(UnmanagedType.BStr)] + [return: MarshalAs(UnmanagedType.Interface)] + UnsafeNativeMethods.IStorage CreateStorage( + [In, MarshalAs(UnmanagedType.BStr)] string pwcsName, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int grfMode, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int reserved1, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int reserved2); - [return: MarshalAs(UnmanagedType.Interface)] - UnsafeNativeMethods.IStorage OpenStorage( - [In, MarshalAs(UnmanagedType.BStr)] + [return: MarshalAs(UnmanagedType.Interface)] + UnsafeNativeMethods.IStorage OpenStorage( + [In, MarshalAs(UnmanagedType.BStr)] string pwcsName, - IntPtr pstgPriority, // must be null - [In, MarshalAs(UnmanagedType.U4)] + IntPtr pstgPriority, // must be null + [In, MarshalAs(UnmanagedType.U4)] int grfMode, - IntPtr snbExclude, - [In, MarshalAs(UnmanagedType.U4)] + IntPtr snbExclude, + [In, MarshalAs(UnmanagedType.U4)] int reserved); - - void CopyTo( - int ciidExclude, - [In, MarshalAs(UnmanagedType.LPArray)] + void CopyTo( + + int ciidExclude, + [In, MarshalAs(UnmanagedType.LPArray)] Guid[] pIIDExclude, - IntPtr snbExclude, - [In, MarshalAs(UnmanagedType.Interface)] + IntPtr snbExclude, + [In, MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.IStorage stgDest); - - void MoveElementTo( - [In, MarshalAs(UnmanagedType.BStr)] + + void MoveElementTo( + [In, MarshalAs(UnmanagedType.BStr)] string pwcsName, - [In, MarshalAs(UnmanagedType.Interface)] + [In, MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.IStorage stgDest, - [In, MarshalAs(UnmanagedType.BStr)] + [In, MarshalAs(UnmanagedType.BStr)] string pwcsNewName, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int grfFlags); - - void Commit( - int grfCommitFlags); + void Commit( + + int grfCommitFlags); - - void Revert(); - - void EnumElements( - [In, MarshalAs(UnmanagedType.U4)] + void Revert(); + + + void EnumElements( + [In, MarshalAs(UnmanagedType.U4)] int reserved1, - // void * - IntPtr reserved2, - [In, MarshalAs(UnmanagedType.U4)] + // void * + IntPtr reserved2, + [In, MarshalAs(UnmanagedType.U4)] int reserved3, - [Out, MarshalAs(UnmanagedType.Interface)] + [Out, MarshalAs(UnmanagedType.Interface)] out object ppVal); // IEnumSTATSTG - - void DestroyElement( - [In, MarshalAs(UnmanagedType.BStr)] + + void DestroyElement( + [In, MarshalAs(UnmanagedType.BStr)] string pwcsName); - - void RenameElement( - [In, MarshalAs(UnmanagedType.BStr)] + + void RenameElement( + [In, MarshalAs(UnmanagedType.BStr)] string pwcsOldName, - [In, MarshalAs(UnmanagedType.BStr)] + [In, MarshalAs(UnmanagedType.BStr)] string pwcsNewName); - - void SetElementTimes( - [In, MarshalAs(UnmanagedType.BStr)] + + void SetElementTimes( + [In, MarshalAs(UnmanagedType.BStr)] string pwcsName, - [In] + [In] NativeMethods.FILETIME pctime, - [In] + [In] NativeMethods.FILETIME patime, - [In] + [In] NativeMethods.FILETIME pmtime); - - void SetClass( - [In] + + void SetClass( + [In] ref Guid clsid); - - void SetStateBits( - int grfStateBits, + void SetStateBits( + + int grfStateBits, - int grfMask); + int grfMask); - - void Stat( - [Out] + + void Stat( + [Out] NativeMethods.STATSTG pStatStg, - int grfStatFlag); - } + int grfStatFlag); + } + + [ComImport(), Guid("B196B28F-BAB4-101A-B69C-00AA00341D07"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + public interface IClassFactory2 + { - [ComImport(), Guid("B196B28F-BAB4-101A-B69C-00AA00341D07"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IClassFactory2 { - - void CreateInstance( - [In, MarshalAs(UnmanagedType.Interface)] + void CreateInstance( + [In, MarshalAs(UnmanagedType.Interface)] object unused, - [In] + [In] ref Guid refiid, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] object[] ppunk); - - void LockServer( - int fLock); + void LockServer( + + int fLock); + - - void GetLicInfo( - [Out] + void GetLicInfo( + [Out] NativeMethods.tagLICINFO licInfo); - - void RequestLicKey( - [In, MarshalAs(UnmanagedType.U4)] + + void RequestLicKey( + [In, MarshalAs(UnmanagedType.U4)] int dwReserved, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] string[] pBstrKey); - - void CreateInstanceLic( - [In, MarshalAs(UnmanagedType.Interface)] + + void CreateInstanceLic( + [In, MarshalAs(UnmanagedType.Interface)] object pUnkOuter, - [In, MarshalAs(UnmanagedType.Interface)] + [In, MarshalAs(UnmanagedType.Interface)] object pUnkReserved, - [In] + [In] ref Guid riid, - [In, MarshalAs(UnmanagedType.BStr)] + [In, MarshalAs(UnmanagedType.BStr)] string bstrKey, - [Out, MarshalAs(UnmanagedType.Interface)] + [Out, MarshalAs(UnmanagedType.Interface)] out object ppVal); - } - [ComImport(), - Guid("B196B284-BAB4-101A-B69C-00AA00341D07"), - InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IConnectionPointContainer { + } + [ComImport(), + Guid("B196B284-BAB4-101A-B69C-00AA00341D07"), + InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + public interface IConnectionPointContainer + { - [return: MarshalAs(UnmanagedType.Interface)] - object EnumConnectionPoints(); + [return: MarshalAs(UnmanagedType.Interface)] + object EnumConnectionPoints(); + + [PreserveSig] + int FindConnectionPoint([In] ref Guid guid, [Out, MarshalAs(UnmanagedType.Interface)]out IConnectionPoint ppCP); - [PreserveSig] - int FindConnectionPoint([In] ref Guid guid, [Out, MarshalAs(UnmanagedType.Interface)]out IConnectionPoint ppCP); + } - } + [ComImport(), Guid("B196B285-BAB4-101A-B69C-00AA00341D07"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + public interface IEnumConnectionPoints + { + [PreserveSig] + int Next(int cConnections, out IConnectionPoint pCp, out int pcFetched); - [ComImport(), Guid("B196B285-BAB4-101A-B69C-00AA00341D07"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IEnumConnectionPoints { - [PreserveSig] - int Next(int cConnections, out IConnectionPoint pCp, out int pcFetched); - - [PreserveSig] - int Skip(int cSkip); + [PreserveSig] + int Skip(int cSkip); - void Reset(); + void Reset(); - IEnumConnectionPoints Clone(); - } + IEnumConnectionPoints Clone(); + } - [ComImport(), Guid("00020400-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IDispatch { - int GetTypeInfoCount(); + [ComImport(), Guid("00020400-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + public interface IDispatch + { + int GetTypeInfoCount(); - [return: MarshalAs(UnmanagedType.Interface)] - ITypeInfo GetTypeInfo( - [In, MarshalAs(UnmanagedType.U4)] + [return: MarshalAs(UnmanagedType.Interface)] + ITypeInfo GetTypeInfo( + [In, MarshalAs(UnmanagedType.U4)] int iTInfo, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int lcid); - [PreserveSig] - int GetIDsOfNames( - [In] + [PreserveSig] + int GetIDsOfNames( + [In] ref Guid riid, - [In, MarshalAs(UnmanagedType.LPArray)] + [In, MarshalAs(UnmanagedType.LPArray)] string[] rgszNames, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int cNames, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int lcid, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] int[] rgDispId); - [PreserveSig] - int Invoke( + [PreserveSig] + int Invoke( - int dispIdMember, - [In] + int dispIdMember, + [In] ref Guid riid, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int lcid, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int dwFlags, - [Out, In] + [Out, In] NativeMethods.tagDISPPARAMS pDispParams, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] object[] pVarResult, - [Out, In] + [Out, In] NativeMethods.tagEXCEPINFO pExcepInfo, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] IntPtr [] pArgErr); - } + } - [ComImport(), Guid("00020401-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface ITypeInfo { + [ComImport(), Guid("00020401-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + public interface ITypeInfo + { [PreserveSig] int GetTypeAttr(ref IntPtr pTypeAttr); [PreserveSig] int GetTypeComp( - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] UnsafeNativeMethods.ITypeComp[] ppTComp); [PreserveSig] int GetFuncDesc( - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int index, ref IntPtr pFuncDesc); - [PreserveSig] - int GetVarDesc( - [In, MarshalAs(UnmanagedType.U4)] + [PreserveSig] + int GetVarDesc( + [In, MarshalAs(UnmanagedType.U4)] int index, ref IntPtr pVarDesc); - [PreserveSig] - int GetNames( + [PreserveSig] + int GetNames( - int memid, - [Out, MarshalAs(UnmanagedType.LPArray)] + int memid, + [Out, MarshalAs(UnmanagedType.LPArray)] string[] rgBstrNames, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int cMaxNames, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] int[] pcNames); [PreserveSig] int GetRefTypeOfImplType( - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int index, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] int[] pRefType); [PreserveSig] int GetImplTypeFlags( - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int index, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] int[] pImplTypeFlags); @@ -6902,9 +7116,9 @@ int GetDocumentation( int memid, ref string pBstrName, ref string pBstrDocString, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] int[] pdwHelpContext, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] string[] pBstrHelpFile); @@ -6914,19 +7128,19 @@ int GetDllEntry( int memid, NativeMethods.tagINVOKEKIND invkind, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] string[] pBstrDllName, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] string[] pBstrName, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] short[] pwOrdinal); - [PreserveSig] - int GetRefTypeInfo( + [PreserveSig] + int GetRefTypeInfo( - IntPtr hreftype, - ref ITypeInfo pTypeInfo); + IntPtr hreftype, + ref ITypeInfo pTypeInfo); [PreserveSig] @@ -6935,307 +7149,312 @@ int GetRefTypeInfo( [PreserveSig] int CreateInstance( - [In] + [In] ref Guid riid, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] object[] ppvObj); - [PreserveSig] - int GetMops( + [PreserveSig] + int GetMops( - int memid, - [Out, MarshalAs(UnmanagedType.LPArray)] + int memid, + [Out, MarshalAs(UnmanagedType.LPArray)] string[] pBstrMops); [PreserveSig] int GetContainingTypeLib( - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] UnsafeNativeMethods.ITypeLib[] ppTLib, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] int[] pIndex); - [PreserveSig] - void ReleaseTypeAttr(IntPtr typeAttr); + [PreserveSig] + void ReleaseTypeAttr(IntPtr typeAttr); - [PreserveSig] - void ReleaseFuncDesc(IntPtr funcDesc); + [PreserveSig] + void ReleaseFuncDesc(IntPtr funcDesc); - [PreserveSig] - void ReleaseVarDesc(IntPtr varDesc); + [PreserveSig] + void ReleaseVarDesc(IntPtr varDesc); - } - [ComImport(), Guid("00020403-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface ITypeComp { - unsafe void RemoteBind( - [In, MarshalAs(UnmanagedType.LPWStr)] + } + [ComImport(), Guid("00020403-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + public interface ITypeComp + { + unsafe void RemoteBind( + [In, MarshalAs(UnmanagedType.LPWStr)] string szName, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int lHashVal, - [In, MarshalAs(UnmanagedType.U2)] + [In, MarshalAs(UnmanagedType.U2)] short wFlags, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] UnsafeNativeMethods.ITypeInfo[] ppTInfo, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] NativeMethods.tagDESCKIND[] pDescKind, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] NativeMethods.tagFUNCDESC*[] ppFuncDesc, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] NativeMethods.tagVARDESC*[] ppVarDesc, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] UnsafeNativeMethods.ITypeComp[] ppTypeComp, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] int[] pDummy); - - void RemoteBindType( - [In, MarshalAs(UnmanagedType.LPWStr)] + + void RemoteBindType( + [In, MarshalAs(UnmanagedType.LPWStr)] string szName, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int lHashVal, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] UnsafeNativeMethods.ITypeInfo[] ppTInfo); - } + } - [ComImport(), Guid("00020402-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface ITypeLib { + [ComImport(), Guid("00020402-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + public interface ITypeLib + { - void RemoteGetTypeInfoCount( - [Out, MarshalAs(UnmanagedType.LPArray)] + void RemoteGetTypeInfoCount( + [Out, MarshalAs(UnmanagedType.LPArray)] int[] pcTInfo); - - void GetTypeInfo( - [In, MarshalAs(UnmanagedType.U4)] + + void GetTypeInfo( + [In, MarshalAs(UnmanagedType.U4)] int index, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] UnsafeNativeMethods.ITypeInfo[] ppTInfo); - - void GetTypeInfoType( - [In, MarshalAs(UnmanagedType.U4)] + + void GetTypeInfoType( + [In, MarshalAs(UnmanagedType.U4)] int index, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] NativeMethods.tagTYPEKIND[] pTKind); - - void GetTypeInfoOfGuid( - [In] + + void GetTypeInfoOfGuid( + [In] ref Guid guid, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] UnsafeNativeMethods.ITypeInfo[] ppTInfo); - - void RemoteGetLibAttr( - IntPtr ppTLibAttr, - [Out, MarshalAs(UnmanagedType.LPArray)] + + void RemoteGetLibAttr( + IntPtr ppTLibAttr, + [Out, MarshalAs(UnmanagedType.LPArray)] int[] pDummy); - - void GetTypeComp( - [Out, MarshalAs(UnmanagedType.LPArray)] + + void GetTypeComp( + [Out, MarshalAs(UnmanagedType.LPArray)] UnsafeNativeMethods.ITypeComp[] ppTComp); - - void RemoteGetDocumentation( - - int index, - [In, MarshalAs(UnmanagedType.U4)] + + void RemoteGetDocumentation( + + int index, + [In, MarshalAs(UnmanagedType.U4)] int refPtrFlags, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] string[] pBstrName, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] string[] pBstrDocString, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] int[] pdwHelpContext, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] string[] pBstrHelpFile); - - void RemoteIsName( - [In, MarshalAs(UnmanagedType.LPWStr)] + + void RemoteIsName( + [In, MarshalAs(UnmanagedType.LPWStr)] string szNameBuf, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int lHashVal, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] IntPtr [] pfName, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] string[] pBstrLibName); - - void RemoteFindName( - [In, MarshalAs(UnmanagedType.LPWStr)] + + void RemoteFindName( + [In, MarshalAs(UnmanagedType.LPWStr)] string szNameBuf, - [In, MarshalAs(UnmanagedType.U4)] + [In, MarshalAs(UnmanagedType.U4)] int lHashVal, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] UnsafeNativeMethods.ITypeInfo[] ppTInfo, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] int[] rgMemId, - [In, Out, MarshalAs(UnmanagedType.LPArray)] + [In, Out, MarshalAs(UnmanagedType.LPArray)] short[] pcFound, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] string[] pBstrLibName); - - void LocalReleaseTLibAttr(); - } - [ComImport(), - Guid("DF0B3D60-548F-101B-8E65-08002B2BD119"), - InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface ISupportErrorInfo { + void LocalReleaseTLibAttr(); + } - int InterfaceSupportsErrorInfo( - [In] ref Guid riid); + [ComImport(), + Guid("DF0B3D60-548F-101B-8E65-08002B2BD119"), + InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + public interface ISupportErrorInfo + { + int InterfaceSupportsErrorInfo( + [In] ref Guid riid); - } - [ComImport(), - Guid("1CF2B120-547D-101B-8E65-08002B2BD119"), - InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IErrorInfo { + } - [PreserveSig] - int GetGUID( - [Out] + [ComImport(), + Guid("1CF2B120-547D-101B-8E65-08002B2BD119"), + InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + public interface IErrorInfo + { + + [PreserveSig] + int GetGUID( + [Out] out Guid pguid); - [PreserveSig] - int GetSource( - [In, Out, MarshalAs(UnmanagedType.BStr)] + [PreserveSig] + int GetSource( + [In, Out, MarshalAs(UnmanagedType.BStr)] ref string pBstrSource); - [PreserveSig] - int GetDescription( - [In, Out, MarshalAs(UnmanagedType.BStr)] + [PreserveSig] + int GetDescription( + [In, Out, MarshalAs(UnmanagedType.BStr)] ref string pBstrDescription); - [PreserveSig] - int GetHelpFile( - [In, Out, MarshalAs(UnmanagedType.BStr)] + [PreserveSig] + int GetHelpFile( + [In, Out, MarshalAs(UnmanagedType.BStr)] ref string pBstrHelpFile); - [PreserveSig] - int GetHelpContext( - [In, Out, MarshalAs(UnmanagedType.U4)] + [PreserveSig] + int GetHelpContext( + [In, Out, MarshalAs(UnmanagedType.U4)] ref int pdwHelpContext); - } + } - [StructLayout(LayoutKind.Sequential)] - public sealed class tagQACONTAINER - { - [MarshalAs(UnmanagedType.U4)] - public int cbSize = Marshal.SizeOf(); + [StructLayout(LayoutKind.Sequential)] + public sealed class tagQACONTAINER + { + [MarshalAs(UnmanagedType.U4)] + public int cbSize = Marshal.SizeOf(); - public UnsafeNativeMethods.IOleClientSite pClientSite; + public UnsafeNativeMethods.IOleClientSite pClientSite; - [MarshalAs(UnmanagedType.Interface)] - public object pAdviseSink = null; + [MarshalAs(UnmanagedType.Interface)] + public object pAdviseSink = null; - public UnsafeNativeMethods.IPropertyNotifySink pPropertyNotifySink; + public UnsafeNativeMethods.IPropertyNotifySink pPropertyNotifySink; - [MarshalAs(UnmanagedType.Interface)] - public object pUnkEventSink = null; + [MarshalAs(UnmanagedType.Interface)] + public object pUnkEventSink = null; - [MarshalAs(UnmanagedType.U4)] - public int dwAmbientFlags; + [MarshalAs(UnmanagedType.U4)] + public int dwAmbientFlags; - [MarshalAs(UnmanagedType.U4)] - public uint colorFore; + [MarshalAs(UnmanagedType.U4)] + public uint colorFore; - [MarshalAs(UnmanagedType.U4)] - public uint colorBack; + [MarshalAs(UnmanagedType.U4)] + public uint colorBack; - [MarshalAs(UnmanagedType.Interface)] - public object pFont; + [MarshalAs(UnmanagedType.Interface)] + public object pFont; - [MarshalAs(UnmanagedType.Interface)] - public object pUndoMgr = null; + [MarshalAs(UnmanagedType.Interface)] + public object pUndoMgr = null; - [MarshalAs(UnmanagedType.U4)] - public int dwAppearance; + [MarshalAs(UnmanagedType.U4)] + public int dwAppearance; - public int lcid; + public int lcid; - public IntPtr hpal = IntPtr.Zero; + public IntPtr hpal = IntPtr.Zero; - [MarshalAs(UnmanagedType.Interface)] - public object pBindHost = null; - - // visual basic6 uses a old version of the struct that is missing these two fields. - // So, ActiveX sourcing does not work, with the EE trying to read off the - // end of the stack to get to these variables. If I do not define these, - // Office or any of the other hosts will hopefully get nulls, otherwise they - // will crash. - // - //public UnsafeNativeMethods.IOleControlSite pControlSite; - - //public UnsafeNativeMethods.IOleServiceProvider pServiceProvider; - } + [MarshalAs(UnmanagedType.Interface)] + public object pBindHost = null; - [StructLayout(LayoutKind.Sequential)/*leftover(noAutoOffset)*/] - public sealed class tagQACONTROL - { - [MarshalAs(UnmanagedType.U4)/*leftover(offset=0, cbSize)*/] - public int cbSize = Marshal.SizeOf(); + // visual basic6 uses a old version of the struct that is missing these two fields. + // So, ActiveX sourcing does not work, with the EE trying to read off the + // end of the stack to get to these variables. If I do not define these, + // Office or any of the other hosts will hopefully get nulls, otherwise they + // will crash. + // + //public UnsafeNativeMethods.IOleControlSite pControlSite; + + //public UnsafeNativeMethods.IOleServiceProvider pServiceProvider; + } + + [StructLayout(LayoutKind.Sequential)/*leftover(noAutoOffset)*/] + public sealed class tagQACONTROL + { + [MarshalAs(UnmanagedType.U4)/*leftover(offset=0, cbSize)*/] + public int cbSize = Marshal.SizeOf(); - [MarshalAs(UnmanagedType.U4)/*leftover(offset=4, dwMiscStatus)*/] - public int dwMiscStatus = 0; + [MarshalAs(UnmanagedType.U4)/*leftover(offset=4, dwMiscStatus)*/] + public int dwMiscStatus = 0; - [MarshalAs(UnmanagedType.U4)/*leftover(offset=8, dwViewStatus)*/] - public int dwViewStatus = 0; + [MarshalAs(UnmanagedType.U4)/*leftover(offset=8, dwViewStatus)*/] + public int dwViewStatus = 0; - [MarshalAs(UnmanagedType.U4)/*leftover(offset=12, dwEventCookie)*/] - public int dwEventCookie = 0; + [MarshalAs(UnmanagedType.U4)/*leftover(offset=12, dwEventCookie)*/] + public int dwEventCookie = 0; - [MarshalAs(UnmanagedType.U4)/*leftover(offset=16, dwPropNotifyCookie)*/] - public int dwPropNotifyCookie = 0; + [MarshalAs(UnmanagedType.U4)/*leftover(offset=16, dwPropNotifyCookie)*/] + public int dwPropNotifyCookie = 0; - [MarshalAs(UnmanagedType.U4)/*leftover(offset=20, dwPointerActivationPolicy)*/] - public int dwPointerActivationPolicy = 0; + [MarshalAs(UnmanagedType.U4)/*leftover(offset=20, dwPointerActivationPolicy)*/] + public int dwPointerActivationPolicy = 0; - } + } - [ComImport()] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - [Guid("E44C3566-915D-4070-99C6-047BFF5A08F5")] - [ComVisible(true)] - public interface ILegacyIAccessibleProvider { + [ComImport()] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + [Guid("E44C3566-915D-4070-99C6-047BFF5A08F5")] + [ComVisible(true)] + public interface ILegacyIAccessibleProvider + { - void Select(int flagsSelect); + void Select(int flagsSelect); - void DoDefaultAction(); + void DoDefaultAction(); - void SetValue([MarshalAs(UnmanagedType.LPWStr)] string szValue); + void SetValue([MarshalAs(UnmanagedType.LPWStr)] string szValue); - [return: MarshalAs(UnmanagedType.Interface)] - Accessibility.IAccessible GetIAccessible(); + [return: MarshalAs(UnmanagedType.Interface)] + Accessibility.IAccessible GetIAccessible(); - int ChildId { get; } + int ChildId { get; } - string Name { get; } + string Name { get; } - string Value { get; } + string Value { get; } - string Description { get; } + string Description { get; } - uint Role { get; } + uint Role { get; } - uint State { get; } + uint State { get; } - string Help { get; } + string Help { get; } - string KeyboardShortcut { get; } + string KeyboardShortcut { get; } - object[] /* IRawElementProviderSimple[] */ GetSelection(); + object[] /* IRawElementProviderSimple[] */ GetSelection(); - string DefaultAction { get; } - } + string DefaultAction { get; } + } [ComImport] [Guid("0000000A-0000-0000-C000-000000000046")] @@ -7291,7 +7510,7 @@ public class OFNOTIFY } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] - internal class Shell32 + internal class Shell32 { [DllImport(ExternDll.Shell32, PreserveSig = true)] public static extern int SHCreateShellItem(IntPtr pidlParent, IntPtr psfParent, IntPtr pidl, out FileDialogNative.IShellItem ppsi); @@ -7300,143 +7519,144 @@ internal class Shell32 public static extern int SHILCreateFromPath([MarshalAs(UnmanagedType.LPWStr)]string pszPath, out IntPtr ppIdl, ref uint rgflnOut); } - [ComVisible(true), Guid("B722BCC6-4E68-101B-A2BC-00AA00404770"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - public interface IOleDocumentView - { - - void SetInPlaceSite( - [In, MarshalAs(UnmanagedType.Interface)] + [ComVisible(true), Guid("B722BCC6-4E68-101B-A2BC-00AA00404770"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + public interface IOleDocumentView + { + + void SetInPlaceSite( + [In, MarshalAs(UnmanagedType.Interface)] IOleInPlaceSite pIPSite); - - [return: MarshalAs(UnmanagedType.Interface)] - IOleInPlaceSite GetInPlaceSite(); - - [return: MarshalAs(UnmanagedType.Interface)] - object GetDocument(); - - - void SetRect( - [In] + + [return: MarshalAs(UnmanagedType.Interface)] + IOleInPlaceSite GetInPlaceSite(); + + [return: MarshalAs(UnmanagedType.Interface)] + object GetDocument(); + + + void SetRect( + [In] ref NativeMethods.RECT prcView); - - - void GetRect( - [In, Out] + + + void GetRect( + [In, Out] ref NativeMethods.RECT prcView); - - - void SetRectComplex( - [In] + + + void SetRectComplex( + [In] NativeMethods.RECT prcView, - [In] + [In] NativeMethods.RECT prcHScroll, - [In] + [In] NativeMethods.RECT prcVScroll, - [In] + [In] NativeMethods.RECT prcSizeBox); - - - void Show(bool fShow); - - - [PreserveSig] - int UIActivate(bool fUIActivate); - - - void Open(); - - [PreserveSig] - int Close( - [In, MarshalAs(UnmanagedType.U4)] + + + void Show(bool fShow); + + + [PreserveSig] + int UIActivate(bool fUIActivate); + + + void Open(); + + [PreserveSig] + int Close( + [In, MarshalAs(UnmanagedType.U4)] int dwReserved); - - - void SaveViewState( - [In, MarshalAs(UnmanagedType.Interface)] + + + void SaveViewState( + [In, MarshalAs(UnmanagedType.Interface)] IStream pstm); - - - void ApplyViewState( - [In, MarshalAs(UnmanagedType.Interface)] + + + void ApplyViewState( + [In, MarshalAs(UnmanagedType.Interface)] IStream pstm); - - - void Clone( - [In, MarshalAs(UnmanagedType.Interface)] + + + void Clone( + [In, MarshalAs(UnmanagedType.Interface)] IOleInPlaceSite pIPSiteNew, - [Out, MarshalAs(UnmanagedType.LPArray)] + [Out, MarshalAs(UnmanagedType.LPArray)] IOleDocumentView[] ppViewNew); - - - } + + + } [ ComImport, Guid("b722bcc5-4e68-101b-a2bc-00aa00404770"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown) ] - public interface IOleDocument - { - - [PreserveSig] - int CreateView(IOleInPlaceSite pIPSite, - IStream pstm, - int dwReserved, - out IOleDocumentView ppView); - - [PreserveSig] - int GetDocMiscStatus( - out int pdwStatus); - - int EnumViews( - out object ppEnum, - out IOleDocumentView ppView); - } + public interface IOleDocument + { + + [PreserveSig] + int CreateView(IOleInPlaceSite pIPSite, + IStream pstm, + int dwReserved, + out IOleDocumentView ppView); + + [PreserveSig] + int GetDocMiscStatus( + out int pdwStatus); + + int EnumViews( + out object ppEnum, + out IOleDocumentView ppView); + } [ - Guid("0000011e-0000-0000-C000-000000000046"), ComImport, InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown) + Guid("0000011e-0000-0000-C000-000000000046"), ComImport, InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown) ] public interface IOleCache { - int Cache(ref FORMATETC pformatetc,int advf); - - void Uncache(int dwConnection); - + int Cache(ref FORMATETC pformatetc, int advf); + + void Uncache(int dwConnection); + object EnumCache(/*[out] IEnumSTATDATA **ppenumSTATDATA*/); - + void InitCache(IComDataObject pDataObject); - + void SetData(ref FORMATETC pformatetc, ref STGMEDIUM pmedium, bool fRelease); } - - + + [ComImport, TypeLibType(0x1050), Guid("618736E0-3C3D-11CF-810C-00AA00389B71"), ] - public interface IAccessibleInternal { + public interface IAccessibleInternal + { [return: MarshalAs(UnmanagedType.IDispatch)] [DispId(unchecked((int)0xFFFFEC78))] [TypeLibFunc(0x0040)] object get_accParent(); - + [DispId(unchecked((int)0xFFFFEC77))] [TypeLibFunc(0x0040)] int get_accChildCount(); - + [return: MarshalAs(UnmanagedType.IDispatch)] [TypeLibFunc(0x0040)] [DispId(unchecked((int)0xFFFFEC76))] object get_accChild([In][MarshalAs(UnmanagedType.Struct)] object varChild); - + [return: MarshalAs(UnmanagedType.BStr)] [DispId(unchecked((int)0xFFFFEC75))] [TypeLibFunc(0x0040)] string get_accName([In][Optional][MarshalAs(UnmanagedType.Struct)] object varChild); - + [return: MarshalAs(UnmanagedType.BStr)] [TypeLibFunc(0x0040)] [DispId(unchecked((int)0xFFFFEC74))] @@ -7476,22 +7696,22 @@ int get_accHelpTopic([Out][MarshalAs(UnmanagedType.BStr)] out string pszHelpFile [DispId(unchecked((int)0xFFFFEC6D))] [TypeLibFunc(0x0040)] object get_accFocus(); - + [return: MarshalAs(UnmanagedType.Struct)] [DispId(unchecked((int)0xFFFFEC6C))] [TypeLibFunc(0x0040)] object get_accSelection(); - + [return: MarshalAs(UnmanagedType.BStr)] [TypeLibFunc(0x0040)] [DispId(unchecked((int)0xFFFFEC6B))] string get_accDefaultAction([In][Optional][MarshalAs(UnmanagedType.Struct)] object varChild); - + [DispId(unchecked((int)0xFFFFEC6A))] [TypeLibFunc(0x0040)] void accSelect([In] int flagsSelect, [In][Optional][MarshalAs(UnmanagedType.Struct)] object varChild); - + [DispId(unchecked((int)0xFFFFEC69))] [TypeLibFunc(0x0040)] void accLocation([Out] out int pxLeft, @@ -7499,13 +7719,13 @@ void accLocation([Out] out int pxLeft, [Out] out int pcxWidth, [Out] out int pcyHeight, [In][Optional][MarshalAs(UnmanagedType.Struct)] object varChild); - + [return: MarshalAs(UnmanagedType.Struct)] [TypeLibFunc(0x0040)] [DispId(unchecked((int)0xFFFFEC68))] object accNavigate([In] int navDir, [In][Optional][MarshalAs(UnmanagedType.Struct)] object varStart); - + [return: MarshalAs(UnmanagedType.Struct)] [TypeLibFunc(0x0040)] [DispId(unchecked((int)0xFFFFEC67))] @@ -7515,12 +7735,12 @@ object accHitTest([In] int xLeft, [TypeLibFunc(0x0040)] [DispId(unchecked((int)0xFFFFEC66))] void accDoDefaultAction([In][Optional][MarshalAs(UnmanagedType.Struct)] object varChild); - + [TypeLibFunc(0x0040)] [DispId(unchecked((int)0xFFFFEC75))] void set_accName([In][Optional][MarshalAs(UnmanagedType.Struct)] object varChild, [In][MarshalAs(UnmanagedType.BStr)] string pszName); - + [TypeLibFunc(0x0040)] [DispId(unchecked((int)0xFFFFEC74))] void set_accValue([In][Optional][MarshalAs(UnmanagedType.Struct)] object varChild, @@ -7679,15 +7899,15 @@ int SaveAsFile( [ComImport(), Guid("7BF80981-BF32-101A-8BBB-00AA00300CAB"), System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIDispatch)] public interface IPictureDisp { - IntPtr Handle { get;} + IntPtr Handle { get; } - IntPtr HPal { get;} + IntPtr HPal { get; } - short PictureType { get;} + short PictureType { get; } - int Width { get;} + int Width { get; } - int Height { get;} + int Height { get; } void Render( IntPtr hdc, @@ -7715,8 +7935,8 @@ internal class ThemingScope /// We now use explicitactivate everywhere and use this method to determine if we /// really need to activate the activationcontext. This should be pretty fast. /// - - + + private static bool IsContextActive() { IntPtr current = IntPtr.Zero; @@ -7734,8 +7954,8 @@ private static bool IsContextActive() /// on the stack even if one is already present. In such cases, this method helps - you get to manage /// the cookie yourself though. /// - - + + public static IntPtr Activate() { IntPtr userCookie = IntPtr.Zero; @@ -7777,8 +7997,8 @@ public static IntPtr Deactivate(IntPtr userCookie) // and ThemingScope class is not public so external code can't lock on typeof(ThemingScope). System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2002:DoNotLockOnObjectsWithWeakIdentity") ] - - + + public static bool CreateActivationContext(string dllPath, int nativeResourceManifestID) { lock (typeof(ThemingScope)) @@ -7803,16 +8023,16 @@ public static bool CreateActivationContext(string dllPath, int nativeResourceMan // All the pinvoke goo... [DllImport(ExternDll.Kernel32)] - + private extern static IntPtr CreateActCtx(ref ACTCTX actctx); [DllImport(ExternDll.Kernel32)] - + private extern static bool ActivateActCtx(IntPtr hActCtx, out IntPtr lpCookie); [DllImport(ExternDll.Kernel32)] - + private extern static bool DeactivateActCtx(int dwFlags, IntPtr lpCookie); [DllImport(ExternDll.Kernel32)] - + private extern static bool GetCurrentActCtx(out IntPtr handle); private const int ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID = 0x004; @@ -7871,13 +8091,13 @@ internal void Close() [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); - [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Auto, SetLastError=true)] - + [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)] + private static extern bool CloseHandle(HandleRef handle); } - [DllImport(ExternDll.Clr, CharSet=CharSet.Unicode, PreserveSig=false, SetLastError=false, BestFitMapping=false, ExactSpelling=true)] - + [DllImport(ExternDll.Clr, CharSet = CharSet.Unicode, PreserveSig = false, SetLastError = false, BestFitMapping = false, ExactSpelling = true)] + internal static extern void CorLaunchApplication(uint hostType, string applicationFullName, int manifestPathsCount, @@ -7940,7 +8160,8 @@ public enum StructureChangeType [ComVisible(true)] [Guid("76d12d7e-b227-4417-9ce2-42642ffa896a")] - public enum ExpandCollapseState { + public enum ExpandCollapseState + { /// No children are showing Collapsed, /// All children are showing @@ -7952,7 +8173,8 @@ public enum ExpandCollapseState { } [Flags] - public enum ProviderOptions { + public enum ProviderOptions + { /// Indicates that this is a client-side provider ClientSideProvider = 0x0001, /// Indicates that this is a server-side provider @@ -7987,20 +8209,23 @@ public enum ProviderOptions { [ComVisible(true)] [Guid("fb8b03af-3bdf-48d4-bd36-1a65793be168")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - public interface ISelectionProvider { + public interface ISelectionProvider + { /// /// Get the currently selected elements /// /// An AutomationElement array containing the currently selected elements [return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UNKNOWN)] - /* IRawElementProviderSimple */ object[] GetSelection(); + /* IRawElementProviderSimple */ + object[] GetSelection(); /// /// Indicates whether the control allows more than one element to be selected /// /// Boolean indicating whether the control allows more than one element to be selected /// If this is false, then the control is a single-select ccntrol - bool CanSelectMultiple { + bool CanSelectMultiple + { [return: MarshalAs(UnmanagedType.Bool)] get; } @@ -8010,7 +8235,8 @@ bool CanSelectMultiple { /// /// Boolean indicating whether the control requires at least one element to be selected /// If this is false, then the control allows all elements to be unselected - bool IsSelectionRequired { + bool IsSelectionRequired + { [return: MarshalAs(UnmanagedType.Bool)] get; } @@ -8063,7 +8289,8 @@ public interface ISelectionItemProvider [ComVisible(true)] [Guid("1d5df27c-8947-4425-b8d9-79787bb460b8")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - public interface IRawElementProviderHwndOverride : IRawElementProviderSimple { + public interface IRawElementProviderHwndOverride : IRawElementProviderSimple + { /// /// Request a provider for the specified component. The returned provider can supply additional /// properties or override properties of the specified component. @@ -8077,16 +8304,18 @@ public interface IRawElementProviderHwndOverride : IRawElementProviderSimple { [ComImport()] [Guid("6D5140C1-7436-11CE-8034-00AA006009FA")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IServiceProvider { + internal interface IServiceProvider + { [PreserveSig] int QueryService(ref Guid service, ref Guid riid, out IntPtr ppvObj); } [ComVisible(true)] [ComImport()] - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [Guid("F8B80ADA-2C44-48D0-89BE-5FF23C9CD875")] - internal interface IAccessibleEx { + internal interface IAccessibleEx + { // Returns the IAccessibleEx for specified child. Returns // S_OK/NULL if this implementation does not use child ids, // or does not have an IAccessibleEx for the specified child, @@ -8139,7 +8368,8 @@ int ConvertReturnedElement( [ComImport()] [Guid("d847d3a5-cab0-4a98-8c32-ecb45c59ad24")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - public interface IExpandCollapseProvider { + public interface IExpandCollapseProvider + { /// /// Blocking method that returns after the element has been expanded. /// @@ -8151,7 +8381,8 @@ public interface IExpandCollapseProvider { void Collapse(); ///indicates an element's current Collapsed or Expanded state - ExpandCollapseState ExpandCollapseState { + ExpandCollapseState ExpandCollapseState + { get; } } @@ -8160,7 +8391,8 @@ ExpandCollapseState ExpandCollapseState { [ComImport()] [Guid("c7935180-6fb3-4201-b174-7df73adbf64a")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - public interface IValueProvider { + public interface IValueProvider + { /// /// Request to set the value that this UI element is representing /// @@ -8168,13 +8400,15 @@ public interface IValueProvider { void SetValue([MarshalAs(UnmanagedType.LPWStr)] string value); ///Value of a value control, as a a string. - string Value { + string Value + { get; } ///Indicates that the value can only be read, not modified. ///returns True if the control is read-only - bool IsReadOnly { + bool IsReadOnly + { [return: MarshalAs(UnmanagedType.Bool)] // CLR get; } @@ -8184,7 +8418,8 @@ bool IsReadOnly { [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("36dc7aef-33e6-4691-afe1-2be7274b3d33")] - public interface IRangeValueProvider { + public interface IRangeValueProvider + { void SetValue(double value); double Value { get; } @@ -8204,7 +8439,8 @@ public interface IRangeValueProvider { [ComVisible(true)] [Guid("D6DD68D1-86FD-4332-8666-9ABEDEA2D24C")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - public interface IRawElementProviderSimple { + public interface IRawElementProviderSimple + { /// /// Indicates the type of provider this is, for example, whether it is a client-side /// or server-side provider. @@ -8217,7 +8453,8 @@ public interface IRawElementProviderSimple { /// differently - for example, events from server-side provider are broadcast to all listening /// clients, whereas events from client-side providers remain in that client. /// - ProviderOptions ProviderOptions { + ProviderOptions ProviderOptions + { get; } @@ -8247,7 +8484,8 @@ ProviderOptions ProviderOptions { /// Typically only used by elements that correspond directly to a Win32 Window Handle, /// in which case the implementation returns AutomationInteropProvider.BaseElementFromHandle( hwnd ). /// - IRawElementProviderSimple HostRawElementProvider { + IRawElementProviderSimple HostRawElementProvider + { get; } } @@ -8257,7 +8495,8 @@ IRawElementProviderSimple HostRawElementProvider { /// [ComVisible(true)] [Guid("670c3006-bf4c-428b-8534-e1848f645122")] - public enum NavigateDirection { + public enum NavigateDirection + { /// Navigate to parent Parent, /// Navigate to next sibling @@ -8283,7 +8522,8 @@ public enum NavigateDirection { [Guid("f7063da8-8359-439c-9297-bbc5299a7d87")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport()] - public interface IRawElementProviderFragment : IRawElementProviderSimple { + public interface IRawElementProviderFragment : IRawElementProviderSimple + { /// /// Request to return the element in the specified direction /// @@ -8308,7 +8548,8 @@ public interface IRawElementProviderFragment : IRawElementProviderSimple { /// /// Return a bounding rectangle of this element /// - NativeMethods.UiaRect BoundingRectangle { + NativeMethods.UiaRect BoundingRectangle + { get; } @@ -8333,7 +8574,8 @@ NativeMethods.UiaRect BoundingRectangle { /// /// Return the element that is the root node of this fragment of UI. /// - IRawElementProviderFragmentRoot FragmentRoot { + IRawElementProviderFragmentRoot FragmentRoot + { [return: MarshalAs(UnmanagedType.Interface)] get; } @@ -8348,7 +8590,8 @@ IRawElementProviderFragmentRoot FragmentRoot { [Guid("620ce2a5-ab8f-40a9-86cb-de3c75599b58")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport()] - public interface IRawElementProviderFragmentRoot : IRawElementProviderFragment { + public interface IRawElementProviderFragmentRoot : IRawElementProviderFragment + { /// /// Return the child element at the specified point, if one exists, /// otherwise return this element if the point is on this element, @@ -8373,7 +8616,8 @@ public interface IRawElementProviderFragmentRoot : IRawElementProviderFragment { } [Flags] - public enum ToggleState { + public enum ToggleState + { ToggleState_Off = 0, ToggleState_On = 1, ToggleState_Indeterminate = 2 @@ -8383,17 +8627,20 @@ public enum ToggleState { [ComVisible(true)] [Guid("56D00BD0-C4F4-433C-A836-1A52A57E0892")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - public interface IToggleProvider { + public interface IToggleProvider + { void Toggle(); ///indicates an element's current on or off state - ToggleState ToggleState { + ToggleState ToggleState + { get; } } - [Flags] - public enum RowOrColumnMajor { + [Flags] + public enum RowOrColumnMajor + { RowOrColumnMajor_RowMajor = 0, RowOrColumnMajor_ColumnMajor = 1, RowOrColumnMajor_Indeterminate = 2 @@ -8402,15 +8649,17 @@ public enum RowOrColumnMajor { [ComImport()] [ComVisible(true)] [Guid("9c860395-97b3-490a-b52a-858cc22af166")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - public interface ITableProvider { + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + public interface ITableProvider + { [return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UNKNOWN)] object[] /*IRawElementProviderSimple[]*/ GetRowHeaders(); [return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UNKNOWN)] object[] /*IRawElementProviderSimple[]*/ GetColumnHeaders(); - RowOrColumnMajor RowOrColumnMajor { + RowOrColumnMajor RowOrColumnMajor + { get; } } @@ -8419,59 +8668,69 @@ RowOrColumnMajor RowOrColumnMajor { [ComVisible(true)] [Guid("b9734fa6-771f-4d78-9c90-2517999349cd")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - public interface ITableItemProvider { + public interface ITableItemProvider + { [return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UNKNOWN)] object[] /*IRawElementProviderSimple[]*/ GetRowHeaderItems(); [return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UNKNOWN)] object[] /*IRawElementProviderSimple[]*/ GetColumnHeaderItems(); } - + [ComImport()] [ComVisible(true)] [Guid("b17d6187-0907-464b-a168-0ef17a1572b1")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - public interface IGridProvider { + public interface IGridProvider + { [return: MarshalAs(UnmanagedType.IUnknown)] object /*IRawElementProviderSimple*/ GetItem(int row, int column); - int RowCount { + int RowCount + { [return: MarshalAs(UnmanagedType.I4)] get; } - int ColumnCount { + int ColumnCount + { [return: MarshalAs(UnmanagedType.I4)] get; } } - + [ComImport()] [ComVisible(true)] [Guid("d02541f1-fb81-4d64-ae32-f520f8a6dbd1")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - public interface IGridItemProvider { - int Row { + public interface IGridItemProvider + { + int Row + { [return: MarshalAs(UnmanagedType.I4)] get; } - int Column { + int Column + { [return: MarshalAs(UnmanagedType.I4)] get; } - int RowSpan { + int RowSpan + { [return: MarshalAs(UnmanagedType.I4)] get; } - int ColumnSpan { + int ColumnSpan + { [return: MarshalAs(UnmanagedType.I4)] get; } - IRawElementProviderSimple ContainingGrid { + IRawElementProviderSimple ContainingGrid + { [return: MarshalAs(UnmanagedType.Interface)] get; } @@ -8491,7 +8750,8 @@ IRawElementProviderSimple ContainingGrid { [ComVisible(true)] [Guid("54fcb24b-e18e-47a2-b4d3-eccbe77599a2")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - public interface IInvokeProvider { + public interface IInvokeProvider + { /// /// Request that the control initiate its action. /// Should return immediately without blocking. @@ -8509,7 +8769,8 @@ public interface IInvokeProvider { [ComVisible(true)] [Guid("2360c714-4bf1-4b26-ba65-9b21316127eb")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - public interface IScrollItemProvider { + public interface IScrollItemProvider + { /// /// Scrolls the windows containing this automation element to make this element visible. /// InvalidOperationException should be thrown if item becomes unable to be scrolled. Makes @@ -8518,17 +8779,22 @@ public interface IScrollItemProvider { void ScrollIntoView(); } - public static IntPtr LoadLibraryFromSystemPathIfAvailable(string libraryName) { + public static IntPtr LoadLibraryFromSystemPathIfAvailable(string libraryName) + { IntPtr module = IntPtr.Zero; // introduced the LOAD_LIBRARY_SEARCH_SYSTEM32 flag. It also introduced // the AddDllDirectory function. We test for presence of AddDllDirectory as an // indirect evidence for the support of LOAD_LIBRARY_SEARCH_SYSTEM32 flag. IntPtr kernel32 = GetModuleHandle(ExternDll.Kernel32); - if (kernel32 != IntPtr.Zero) { - if (GetProcAddress(new HandleRef(null, kernel32), "AddDllDirectory") != IntPtr.Zero) { + if (kernel32 != IntPtr.Zero) + { + if (GetProcAddress(new HandleRef(null, kernel32), "AddDllDirectory") != IntPtr.Zero) + { module = LoadLibraryEx(libraryName, IntPtr.Zero, NativeMethods.LOAD_LIBRARY_SEARCH_SYSTEM32); - } else { + } + else + { // LOAD_LIBRARY_SEARCH_SYSTEM32 is not supported on this OS. // Fall back to using plain ol' LoadLibrary module = LoadLibrary(libraryName); diff --git a/src/System.Windows.Forms/src/Common/System/LocalAppContext.cs b/src/System.Windows.Forms/src/Common/System/LocalAppContext.cs index 042367594c7..2a9dc22d1a7 100644 --- a/src/System.Windows.Forms/src/Common/System/LocalAppContext.cs +++ b/src/System.Windows.Forms/src/Common/System/LocalAppContext.cs @@ -16,8 +16,10 @@ internal partial class LocalAppContext [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool GetCachedSwitchValue(string switchName, ref int switchValue) { - if (switchValue < 0) return false; - if (switchValue > 0) return true; + if (switchValue < 0) + return false; + if (switchValue > 0) + return true; return GetCachedSwitchValueInternal(switchName, ref switchValue); } diff --git a/src/System.Windows.Forms/src/System/Drawing/Design/PaintValueEventArgs.cs b/src/System.Windows.Forms/src/System/Drawing/Design/PaintValueEventArgs.cs index fcc1e623095..9fd16cc5ca3 100644 --- a/src/System.Windows.Forms/src/System/Drawing/Design/PaintValueEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Drawing/Design/PaintValueEventArgs.cs @@ -25,22 +25,22 @@ public PaintValueEventArgs(ITypeDescriptorContext context, object value, Graphic Graphics = graphics ?? throw new ArgumentNullException(nameof(graphics)); Bounds = bounds; } - + /// /// outlining the area in which the painting should be done. /// public Rectangle Bounds { get; } - + /// /// object for additional information about the context this value appears in. /// public ITypeDescriptorContext Context { get; } - + /// /// object with which painting should be done. /// public Graphics Graphics { get; } - + /// /// Value to paint. /// diff --git a/src/System.Windows.Forms/src/System/Drawing/Design/PropertyValueUIItem.cs b/src/System.Windows.Forms/src/System/Drawing/Design/PropertyValueUIItem.cs index 9178092ce07..7005a983c70 100644 --- a/src/System.Windows.Forms/src/System/Drawing/Design/PropertyValueUIItem.cs +++ b/src/System.Windows.Forms/src/System/Drawing/Design/PropertyValueUIItem.cs @@ -22,10 +22,10 @@ public PropertyValueUIItem(Image uiItemImage, PropertyValueUIItemInvokeHandler h /// Gets the 8 x 8 pixel image that will be drawn on the properties window. public virtual Image Image { get; } - + /// Gets the handler that will be raised when this item is double clicked. public virtual PropertyValueUIItemInvokeHandler InvokeHandler { get; } - + /// Gets the ToolTip to display for this item. public virtual string ToolTip { get; } diff --git a/src/System.Windows.Forms/src/System/Drawing/Design/UITypeEditor.cs b/src/System.Windows.Forms/src/System/Drawing/Design/UITypeEditor.cs index 01fabffcc80..a21fd7f4547 100644 --- a/src/System.Windows.Forms/src/System/Drawing/Design/UITypeEditor.cs +++ b/src/System.Windows.Forms/src/System/Drawing/Design/UITypeEditor.cs @@ -33,7 +33,7 @@ static UITypeEditor() // Add our intrinsic editors to TypeDescriptor. TypeDescriptor.AddEditorTable(typeof(UITypeEditor), intrinsicEditors); } - + /// /// Determines if drop-down editors should be resizable by the user. /// @@ -53,12 +53,12 @@ static UITypeEditor() /// The that this editor can use to obtain services. /// The object to edit. public virtual object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) => value; - + /// /// Gets the of the Edit method. /// public UITypeEditorEditStyle GetEditStyle() => GetEditStyle(null); - + /// /// Gets a value indicating whether this editor supports painting a representation of an object's value. /// diff --git a/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs b/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs index 81bc61be60f..c381e96caff 100644 --- a/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs +++ b/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Resources { +namespace System.Resources +{ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -30,9 +31,10 @@ namespace System.Resources { /// /// [Serializable] - public sealed class ResXDataNode : ISerializable { + public sealed class ResXDataNode : ISerializable + { - private static readonly char[] SpecialChars = new char[] {' ', '\r', '\n'}; + private static readonly char[] SpecialChars = new char[] { ' ', '\r', '\n' }; private DataNodeInfo nodeInfo; @@ -60,14 +62,16 @@ public sealed class ResXDataNode : ISerializable { private Func typeNameConverter; // constructors - - private ResXDataNode() { + + private ResXDataNode() + { } // // this is a deep clone // - internal ResXDataNode DeepClone() { + internal ResXDataNode DeepClone() + { return new ResXDataNode { // nodeinfo is just made up of immutable objects, we don't need to clone it @@ -84,44 +88,51 @@ internal ResXDataNode DeepClone() { typeNameConverter = this.typeNameConverter }; } - + /// /// /// - public ResXDataNode(string name, object value) : this(name, value, null) { + public ResXDataNode(string name, object value) : this(name, value, null) + { } [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] [ SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // "name" is the name of the param passed in. - // So we don't have to localize it. + // So we don't have to localize it. ] - public ResXDataNode(string name, object value, Func typeNameConverter) { - if(name == null) { + public ResXDataNode(string name, object value, Func typeNameConverter) + { + if (name == null) + { throw (new ArgumentNullException(nameof(name))); } - if(name.Length == 0) { + if (name.Length == 0) + { throw (new ArgumentException(nameof(name))); } this.typeNameConverter = typeNameConverter; Type valueType = (value == null) ? typeof(object) : value.GetType(); - if (value != null && !valueType.IsSerializable) { + if (value != null && !valueType.IsSerializable) + { throw new InvalidOperationException(string.Format(SR.NotSerializableType, name, valueType.FullName)); } - if (value != null) { + if (value != null) + { this.typeName = MultitargetUtil.GetAssemblyQualifiedName(valueType, this.typeNameConverter); - } - + } + this.name = name; this.value = value; } - + /// /// /// - public ResXDataNode(string name, ResXFileRef fileRef) : this(name, fileRef, null) { + public ResXDataNode(string name, ResXFileRef fileRef) : this(name, fileRef, null) + { } [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] @@ -129,11 +140,14 @@ public ResXDataNode(string name, ResXFileRef fileRef) : this(name, fileRef, null SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // "name" is the name of the param passed in. // So we don't have to localize it. ] - public ResXDataNode(string name, ResXFileRef fileRef, Func typeNameConverter) { - if(string.IsNullOrEmpty(name)) { + public ResXDataNode(string name, ResXFileRef fileRef, Func typeNameConverter) + { + if (string.IsNullOrEmpty(name)) + { throw new ArgumentNullException(nameof(name)); } - if(fileRef == null) { + if (fileRef == null) + { throw new ArgumentNullException(nameof(fileRef)); } this.name = name; @@ -141,31 +155,39 @@ public ResXDataNode(string name, ResXFileRef fileRef, Func typeNam this.typeNameConverter = typeNameConverter; } - internal ResXDataNode(DataNodeInfo nodeInfo, string basePath) { + internal ResXDataNode(DataNodeInfo nodeInfo, string basePath) + { this.nodeInfo = nodeInfo; InitializeDataNode(basePath); } - private void InitializeDataNode(string basePath) { + private void InitializeDataNode(string basePath) + { // we can only use our internal type resolver here // because we only want to check if this is a ResXFileRef node // and we can't be sure that we have a typeResolutionService that can // recognize this. It's not very clean but this should work. Type nodeType = null; - if(!string.IsNullOrEmpty(nodeInfo.TypeName)) // can be null if we have a string (default for string is TypeName == null) + if (!string.IsNullOrEmpty(nodeInfo.TypeName)) // can be null if we have a string (default for string is TypeName == null) nodeType = internalTypeResolver.GetType(nodeInfo.TypeName, false, true); - if(nodeType != null && nodeType.Equals(typeof(ResXFileRef))) { + if (nodeType != null && nodeType.Equals(typeof(ResXFileRef))) + { // we have a fileref, split the value data and populate the fields string[] fileRefDetails = ResXFileRef.Converter.ParseResxFileRefString(nodeInfo.ValueData); - if(fileRefDetails != null && fileRefDetails.Length > 1) { - if(!Path.IsPathRooted(fileRefDetails[0]) && basePath != null) { + if (fileRefDetails != null && fileRefDetails.Length > 1) + { + if (!Path.IsPathRooted(fileRefDetails[0]) && basePath != null) + { fileRefFullPath = Path.Combine(basePath, fileRefDetails[0]); - } else { + } + else + { fileRefFullPath = fileRefDetails[0]; } fileRefType = fileRefDetails[1]; - if(fileRefDetails.Length > 2) { + if (fileRefDetails.Length > 2) + { fileRefTextEncoding = fileRefDetails[2]; } } @@ -176,15 +198,19 @@ private void InitializeDataNode(string basePath) { /// /// /// - public string Comment { - get { + public string Comment + { + get + { string result = comment; - if(result == null && nodeInfo != null) { + if (result == null && nodeInfo != null) + { result = nodeInfo.Comment; } return result ?? string.Empty; } - set { + set + { comment = value; } } @@ -192,10 +218,13 @@ public string Comment { /// /// /// - public string Name { - get { + public string Name + { + get + { string result = name; - if(result == null && nodeInfo != null) { + if (result == null && nodeInfo != null) + { result = nodeInfo.Name; } return result; @@ -204,64 +233,79 @@ public string Name { SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // "Name" is the name of the property. // So we don't have to localize it. ] - set { - if(value == null) { + set + { + if (value == null) + { throw new ArgumentNullException(nameof(Name)); } - if(value.Length == 0) { + if (value.Length == 0) + { throw new ArgumentException(nameof(Name)); } name = value; } } - + /// /// /// - public ResXFileRef FileRef { - get { - if(FileRefFullPath == null) { + public ResXFileRef FileRef + { + get + { + if (FileRefFullPath == null) + { return null; } - if(fileRef == null) + if (fileRef == null) { - fileRef = - String.IsNullOrEmpty(fileRefTextEncoding) - ? new ResXFileRef(FileRefFullPath, FileRefType) + fileRef = + String.IsNullOrEmpty(fileRefTextEncoding) + ? new ResXFileRef(FileRefFullPath, FileRefType) : new ResXFileRef(FileRefFullPath, FileRefType, Encoding.GetEncoding(FileRefTextEncoding)); } return fileRef; } } - - private string FileRefFullPath { - get { + + private string FileRefFullPath + { + get + { return fileRef?.FileName ?? fileRefFullPath; } } - private string FileRefType { - get { + private string FileRefType + { + get + { return fileRef?.TypeName ?? fileRefType; } } - private string FileRefTextEncoding { - get { + private string FileRefTextEncoding + { + get + { return fileRef?.TextFileEncoding?.BodyName ?? fileRefTextEncoding; } } - private static string ToBase64WrappedString(byte[] data) { + private static string ToBase64WrappedString(byte[] data) + { const int lineWrap = 80; const string crlf = "\r\n"; const string prefix = " "; string raw = Convert.ToBase64String(data); - if (raw.Length > lineWrap) { + if (raw.Length > lineWrap) + { StringBuilder output = new StringBuilder(raw.Length + (raw.Length / lineWrap) * 3); // word wrap on lineWrap chars, \r\n int current = 0; - for (; current < raw.Length - lineWrap; current+=lineWrap) { + for (; current < raw.Length - lineWrap; current += lineWrap) + { output.Append(crlf); output.Append(prefix); output.Append(raw, current, lineWrap); @@ -272,50 +316,61 @@ private static string ToBase64WrappedString(byte[] data) { output.Append(crlf); return output.ToString(); } - + return raw; } - private void FillDataNodeInfoFromObject(DataNodeInfo nodeInfo, object value) { - if(value is CultureInfo ci) { // special-case CultureInfo, cannot use CultureInfoConverter for serialization + private void FillDataNodeInfoFromObject(DataNodeInfo nodeInfo, object value) + { + if (value is CultureInfo ci) + { // special-case CultureInfo, cannot use CultureInfoConverter for serialization nodeInfo.ValueData = ci.Name; nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(typeof(CultureInfo), this.typeNameConverter); } - else if (value is string str) { + else if (value is string str) + { nodeInfo.ValueData = str; } - else if (value is byte[] bytes) { + else if (value is byte[] bytes) + { nodeInfo.ValueData = ToBase64WrappedString(bytes); nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(typeof(byte[]), this.typeNameConverter); } - else { + else + { Type valueType = (value == null) ? typeof(object) : value.GetType(); - if (value != null && !valueType.IsSerializable) { + if (value != null && !valueType.IsSerializable) + { throw new InvalidOperationException(string.Format(SR.NotSerializableType, name, valueType.FullName)); } TypeConverter tc = TypeDescriptor.GetConverter(valueType); bool toString = tc.CanConvertTo(typeof(string)); bool fromString = tc.CanConvertFrom(typeof(string)); - try { - if (toString && fromString) { + try + { + if (toString && fromString) + { nodeInfo.ValueData = tc.ConvertToInvariantString(value); nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(valueType, this.typeNameConverter); return; } } - catch (Exception ex) { + catch (Exception ex) + { // Some custom type converters will throw in ConvertTo(string) // to indicate that this object should be serialized through ISeriazable // instead of as a string. This is semi-wrong, but something we will have to // live with to allow user created Cursors to be serializable. - if (ClientUtils.IsSecurityOrCriticalException(ex)) { + if (ClientUtils.IsSecurityOrCriticalException(ex)) + { throw; } } bool toByteArray = tc.CanConvertTo(typeof(byte[])); bool fromByteArray = tc.CanConvertFrom(typeof(byte[])); - if (toByteArray && fromByteArray) { + if (toByteArray && fromByteArray) + { byte[] data = (byte[])tc.ConvertTo(value, typeof(byte[])); nodeInfo.ValueData = ToBase64WrappedString(data); nodeInfo.MimeType = ResXResourceWriter.ByteArraySerializedObjectMimeType; @@ -323,12 +378,15 @@ private void FillDataNodeInfoFromObject(DataNodeInfo nodeInfo, object value) { return; } - if (value == null) { + if (value == null) + { nodeInfo.ValueData = string.Empty; nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXNullRef), this.typeNameConverter); } - else { - if (binaryFormatter == null) { + else + { + if (binaryFormatter == null) + { binaryFormatter = new BinaryFormatter { Binder = new ResXSerializationBinder(this.typeNameConverter) @@ -344,55 +402,67 @@ private void FillDataNodeInfoFromObject(DataNodeInfo nodeInfo, object value) { nodeInfo.MimeType = ResXResourceWriter.DefaultSerializedObjectMimeType; } } - + } - - private object GenerateObjectFromDataNodeInfo(DataNodeInfo dataNodeInfo, ITypeResolutionService typeResolver) { + + private object GenerateObjectFromDataNodeInfo(DataNodeInfo dataNodeInfo, ITypeResolutionService typeResolver) + { object result = null; string mimeTypeName = dataNodeInfo.MimeType; // default behavior: if we dont have a type name, it's a string - string typeName = - string.IsNullOrEmpty(dataNodeInfo.TypeName) - ? MultitargetUtil.GetAssemblyQualifiedName(typeof(string), this.typeNameConverter) + string typeName = + string.IsNullOrEmpty(dataNodeInfo.TypeName) + ? MultitargetUtil.GetAssemblyQualifiedName(typeof(string), this.typeNameConverter) : dataNodeInfo.TypeName; - - if (!string.IsNullOrEmpty(mimeTypeName)) { + + if (!string.IsNullOrEmpty(mimeTypeName)) + { if (string.Equals(mimeTypeName, ResXResourceWriter.BinSerializedObjectMimeType) || string.Equals(mimeTypeName, ResXResourceWriter.Beta2CompatSerializedObjectMimeType) - || string.Equals(mimeTypeName, ResXResourceWriter.CompatBinSerializedObjectMimeType)) { + || string.Equals(mimeTypeName, ResXResourceWriter.CompatBinSerializedObjectMimeType)) + { string text = dataNodeInfo.ValueData; byte[] serializedData = FromBase64WrappedString(text); - if (binaryFormatter == null) { + if (binaryFormatter == null) + { binaryFormatter = new BinaryFormatter { Binder = new ResXSerializationBinder(typeResolver) }; } IFormatter formatter = binaryFormatter; - if (serializedData != null && serializedData.Length > 0) { + if (serializedData != null && serializedData.Length > 0) + { result = formatter.Deserialize(new MemoryStream(serializedData)); - if (result is ResXNullRef) { + if (result is ResXNullRef) + { result = null; } } } - - else if (string.Equals(mimeTypeName, ResXResourceWriter.ByteArraySerializedObjectMimeType)) { - if (!string.IsNullOrEmpty(typeName)) { + + else if (string.Equals(mimeTypeName, ResXResourceWriter.ByteArraySerializedObjectMimeType)) + { + if (!string.IsNullOrEmpty(typeName)) + { Type type = ResolveType(typeName, typeResolver); - if (type != null) { + if (type != null) + { TypeConverter tc = TypeDescriptor.GetConverter(type); - if (tc.CanConvertFrom(typeof(byte[]))) { + if (tc.CanConvertFrom(typeof(byte[]))) + { string text = dataNodeInfo.ValueData; byte[] serializedData = FromBase64WrappedString(text); - - if (serializedData != null) { + + if (serializedData != null) + { result = tc.ConvertFrom(serializedData); } } } - else { + else + { string newMessage = string.Format(SR.TypeLoadException, typeName, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X); XmlException xml = new XmlException(newMessage, null, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X); TypeLoadException newTle = new TypeLoadException(newMessage, xml); @@ -402,37 +472,48 @@ private object GenerateObjectFromDataNodeInfo(DataNodeInfo dataNodeInfo, ITypeRe } } } - else if (!string.IsNullOrEmpty(typeName)) { + else if (!string.IsNullOrEmpty(typeName)) + { Type type = ResolveType(typeName, typeResolver); - if (type != null) { - if (type == typeof(ResXNullRef)) { + if (type != null) + { + if (type == typeof(ResXNullRef)) + { result = null; } - else if (typeName.IndexOf("System.Byte[]") != -1 && typeName.IndexOf("mscorlib") != -1) { + else if (typeName.IndexOf("System.Byte[]") != -1 && typeName.IndexOf("mscorlib") != -1) + { // Handle byte[]'s, which are stored as base-64 encoded strings. // We can't hard-code byte[] type name due to version number // updates & potential whitespace issues with ResX files. result = FromBase64WrappedString(dataNodeInfo.ValueData); } - else { + else + { TypeConverter tc = TypeDescriptor.GetConverter(type); - if (tc.CanConvertFrom(typeof(string))) { + if (tc.CanConvertFrom(typeof(string))) + { string text = dataNodeInfo.ValueData; - try { - result = tc.ConvertFromInvariantString(text); - } catch (NotSupportedException nse) { + try + { + result = tc.ConvertFromInvariantString(text); + } + catch (NotSupportedException nse) + { string newMessage = string.Format(SR.NotSupported, typeName, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X, nse.Message); XmlException xml = new XmlException(newMessage, nse, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X); NotSupportedException newNse = new NotSupportedException(newMessage, xml); throw newNse; } } - else { + else + { Debug.WriteLine("Converter for " + type.FullName + " doesn't support string conversion"); } } } - else { + else + { string newMessage = string.Format(SR.TypeLoadException, typeName, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X); XmlException xml = new XmlException(newMessage, null, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X); TypeLoadException newTle = new TypeLoadException(newMessage, xml); @@ -440,18 +521,23 @@ private object GenerateObjectFromDataNodeInfo(DataNodeInfo dataNodeInfo, ITypeRe throw newTle; } } - else { + else + { // if mimeTypeName and typeName are not filled in, the value must be a string Debug.Assert(value is string, "Resource entries with no Type or MimeType must be encoded as strings"); } return result; } - internal DataNodeInfo GetDataNodeInfo() { + internal DataNodeInfo GetDataNodeInfo() + { bool shouldSerialize = true; - if(nodeInfo != null) { + if (nodeInfo != null) + { shouldSerialize = false; - } else { + } + else + { nodeInfo = new DataNodeInfo(); } nodeInfo.Name = Name; @@ -459,18 +545,22 @@ internal DataNodeInfo GetDataNodeInfo() { // We always serialize if this node represents a FileRef. This is because FileRef is a public property, // so someone could have modified it. - if(shouldSerialize || FileRefFullPath != null) { + if (shouldSerialize || FileRefFullPath != null) + { // if we dont have a datanodeinfo it could be either // a direct object OR a fileref - if(FileRefFullPath != null) { + if (FileRefFullPath != null) + { nodeInfo.ValueData = FileRef.ToString(); nodeInfo.MimeType = null; nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXFileRef), this.typeNameConverter); - } else { + } + else + { // serialize to string inside the nodeInfo FillDataNodeInfoFromObject(nodeInfo, value); } - + } return nodeInfo; } @@ -488,37 +578,47 @@ public Point GetNodePosition() /// Get the FQ type name for this datanode. /// We return typeof(object) for ResXNullRef /// - public string GetValueTypeName(ITypeResolutionService typeResolver) { + public string GetValueTypeName(ITypeResolutionService typeResolver) + { // the type name here is always a FQN - if(!string.IsNullOrEmpty(typeName)) + if (!string.IsNullOrEmpty(typeName)) { - return - typeName == MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXNullRef), this.typeNameConverter) - ? MultitargetUtil.GetAssemblyQualifiedName(typeof(object), this.typeNameConverter) + return + typeName == MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXNullRef), this.typeNameConverter) + ? MultitargetUtil.GetAssemblyQualifiedName(typeof(object), this.typeNameConverter) : typeName; } string result = FileRefType; Type objectType = null; // do we have a fileref? - if(result != null) { + if (result != null) + { // try to resolve this type objectType = ResolveType(FileRefType, typeResolver); - } else if(nodeInfo != null) { - + } + else if (nodeInfo != null) + { + // we dont have a fileref, try to resolve the type of the datanode result = nodeInfo.TypeName; // if typename is null, the default is just a string - if(string.IsNullOrEmpty(result)) { + if (string.IsNullOrEmpty(result)) + { // we still dont know... do we have a mimetype? if yes, our only option is to // deserialize to know what we're dealing with... very inefficient... - if(!string.IsNullOrEmpty(nodeInfo.MimeType)) { + if (!string.IsNullOrEmpty(nodeInfo.MimeType)) + { object insideObject = null; - try { + try + { insideObject = GenerateObjectFromDataNodeInfo(nodeInfo, typeResolver); - } catch (Exception ex) { // it'd be better to catch SerializationException but the underlying type resolver - // can throw things like FileNotFoundException which is kinda confusing, so I am catching all here.. - if(ClientUtils.IsCriticalException(ex)) { + } + catch (Exception ex) + { // it'd be better to catch SerializationException but the underlying type resolver + // can throw things like FileNotFoundException which is kinda confusing, so I am catching all here.. + if (ClientUtils.IsCriticalException(ex)) + { throw; } // something went wrong, type is not specified at all or stream is corrupted @@ -526,21 +626,30 @@ public string GetValueTypeName(ITypeResolutionService typeResolver) { result = MultitargetUtil.GetAssemblyQualifiedName(typeof(object), this.typeNameConverter); } - if(insideObject != null) { + if (insideObject != null) + { result = MultitargetUtil.GetAssemblyQualifiedName(insideObject.GetType(), this.typeNameConverter); } - } else { + } + else + { // no typename, no mimetype, we have a string... result = MultitargetUtil.GetAssemblyQualifiedName(typeof(string), this.typeNameConverter); } - } else { - objectType = ResolveType(nodeInfo.TypeName, typeResolver); + } + else + { + objectType = ResolveType(nodeInfo.TypeName, typeResolver); } } - if(objectType != null) { - if(objectType == typeof(ResXNullRef)) { + if (objectType != null) + { + if (objectType == typeof(ResXNullRef)) + { result = MultitargetUtil.GetAssemblyQualifiedName(typeof(object), this.typeNameConverter); - } else { + } + else + { result = MultitargetUtil.GetAssemblyQualifiedName(objectType, this.typeNameConverter); } } @@ -550,61 +659,76 @@ public string GetValueTypeName(ITypeResolutionService typeResolver) { /// /// Get the FQ type name for this datanode /// - public string GetValueTypeName(AssemblyName[] names) { + public string GetValueTypeName(AssemblyName[] names) + { return GetValueTypeName(new AssemblyNamesTypeResolutionService(names)); } /// /// Get the value contained in this datanode /// - public object GetValue(ITypeResolutionService typeResolver) { + public object GetValue(ITypeResolutionService typeResolver) + { - if(value != null) { + if (value != null) + { return value; } object result = null; - if(FileRefFullPath != null) { - Type objectType = ResolveType(FileRefType , typeResolver); - if(objectType != null) { + if (FileRefFullPath != null) + { + Type objectType = ResolveType(FileRefType, typeResolver); + if (objectType != null) + { // we have the FQN for this type - fileRef = - FileRefTextEncoding != null - ? new ResXFileRef(FileRefFullPath, FileRefType, Encoding.GetEncoding(FileRefTextEncoding)) + fileRef = + FileRefTextEncoding != null + ? new ResXFileRef(FileRefFullPath, FileRefType, Encoding.GetEncoding(FileRefTextEncoding)) : new ResXFileRef(FileRefFullPath, FileRefType); TypeConverter tc = TypeDescriptor.GetConverter(typeof(ResXFileRef)); result = tc.ConvertFrom(fileRef.ToString()); - } else { + } + else + { string newMessage = string.Format(SR.TypeLoadExceptionShort, FileRefType); TypeLoadException newTle = new TypeLoadException(newMessage); throw (newTle); } - } else if(nodeInfo.ValueData != null) { + } + else if (nodeInfo.ValueData != null) + { // it's embedded, we deserialize it result = GenerateObjectFromDataNodeInfo(nodeInfo, typeResolver); - } else { + } + else + { // schema is wrong and say minOccur for Value is 0, // but it's too late to change it... // we need to return null here return null; - } + } return result; } /// /// Get the value contained in this datanode /// - public object GetValue(AssemblyName[] names) { + public object GetValue(AssemblyName[] names) + { return GetValue(new AssemblyNamesTypeResolutionService(names)); } - private static byte[] FromBase64WrappedString(string text) { + private static byte[] FromBase64WrappedString(string text) + { - if (text.IndexOfAny(SpecialChars) != -1) { + if (text.IndexOfAny(SpecialChars) != -1) + { StringBuilder sb = new StringBuilder(text.Length); foreach (var ch in text) { - switch (ch) { + switch (ch) + { case ' ': case '\r': case '\n': @@ -616,13 +740,15 @@ private static byte[] FromBase64WrappedString(string text) { } return Convert.FromBase64String(sb.ToString()); } - + return Convert.FromBase64String(text); } - private Type ResolveType(string typeName, ITypeResolutionService typeResolver) { - Type resolvedType = null; - if (typeResolver != null) { + private Type ResolveType(string typeName, ITypeResolutionService typeResolver) + { + Type resolvedType = null; + if (typeResolver != null) + { // If we cannot find the strong-named type, then try to see // if the TypeResolver can bind to partial names. For this, @@ -630,32 +756,36 @@ private Type ResolveType(string typeName, ITypeResolutionService typeResolver) { // strong-name information to try again. resolvedType = typeResolver.GetType(typeName, false); - if (resolvedType == null) { - + if (resolvedType == null) + { + string[] typeParts = typeName.Split(','); // Break up the type name from the rest of the assembly strong name. - if (typeParts != null && typeParts.Length >= 2) { + if (typeParts != null && typeParts.Length >= 2) + { string partialName = typeParts[0].Trim(); - string assemblyName = typeParts[1].Trim(); + string assemblyName = typeParts[1].Trim(); partialName = partialName + ", " + assemblyName; resolvedType = typeResolver.GetType(partialName, false); } } } - if (resolvedType == null) { + if (resolvedType == null) + { resolvedType = Type.GetType(typeName, false); } - + return resolvedType; } - + /// /// Get the value contained in this datanode /// - void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) { + void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) + { DataNodeInfo nodeInfo = GetDataNodeInfo(); si.AddValue("Name", nodeInfo.Name, typeof(string)); si.AddValue("Comment", nodeInfo.Comment, typeof(string)); @@ -664,7 +794,8 @@ void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) si.AddValue("ValueData", nodeInfo.ValueData, typeof(string)); } - private ResXDataNode(SerializationInfo info, StreamingContext context) { + private ResXDataNode(SerializationInfo info, StreamingContext context) + { this.nodeInfo = new DataNodeInfo { Name = (string)info.GetValue("Name", typeof(string)), @@ -677,7 +808,8 @@ private ResXDataNode(SerializationInfo info, StreamingContext context) { } } - internal class DataNodeInfo { + internal class DataNodeInfo + { internal string Name; internal string Comment; internal string TypeName; @@ -685,7 +817,8 @@ internal class DataNodeInfo { internal string ValueData; internal Point ReaderPosition; //only used to track position in the reader - internal DataNodeInfo Clone() { + internal DataNodeInfo Clone() + { return new DataNodeInfo { Name = this.Name, @@ -702,42 +835,52 @@ internal DataNodeInfo Clone() { // This is needed to be able to read binary serialized content from older // NDP types and map them to newer versions. // - internal class ResXSerializationBinder : SerializationBinder { + internal class ResXSerializationBinder : SerializationBinder + { private ITypeResolutionService typeResolver; private Func typeNameConverter; - internal ResXSerializationBinder(ITypeResolutionService typeResolver) { + internal ResXSerializationBinder(ITypeResolutionService typeResolver) + { this.typeResolver = typeResolver; } - internal ResXSerializationBinder(Func typeNameConverter) { + internal ResXSerializationBinder(Func typeNameConverter) + { this.typeNameConverter = typeNameConverter; } - public override Type BindToType(string assemblyName, string typeName) { - if (typeResolver == null) { + public override Type BindToType(string assemblyName, string typeName) + { + if (typeResolver == null) + { return null; } typeName = typeName + ", " + assemblyName; Type type = typeResolver.GetType(typeName); - if (type == null) { + if (type == null) + { string[] typeParts = typeName.Split(','); // Break up the assembly name from the rest of the assembly strong name. // we try 1) FQN 2) FQN without a version 3) just the short name - if (typeParts != null && typeParts.Length > 2) { + if (typeParts != null && typeParts.Length > 2) + { string partialName = typeParts[0].Trim(); - for (int i = 1; i < typeParts.Length; ++i) { + for (int i = 1; i < typeParts.Length; ++i) + { string typePart = typeParts[i].Trim(); - if (!typePart.StartsWith("Version=") && !typePart.StartsWith("version=")) { + if (!typePart.StartsWith("Version=") && !typePart.StartsWith("version=")) + { partialName = partialName + ", " + typePart; } } type = typeResolver.GetType(partialName); - if(type == null) { + if (type == null) + { type = typeResolver.GetType(typeParts[0].Trim()); } } @@ -749,7 +892,8 @@ public override Type BindToType(string assemblyName, string typeName) { // // Get the multitarget-aware string representation for the give type. - public override void BindToName(Type serializedType, out string assemblyName, out string typeName) { + public override void BindToName(Type serializedType, out string assemblyName, out string typeName) + { // Normally we don't change typeName when changing the target framework, // only assembly version or assembly name might change, thus we are setting // typeName only if it changed with the framework version. @@ -764,14 +908,18 @@ public override void BindToName(Type serializedType, out string assemblyName, ou // // another example are singleton objects like DBNull.Value which are serialized by System.UnitySerializationHolder typeName = null; - if (typeNameConverter != null) { + if (typeNameConverter != null) + { string assemblyQualifiedTypeName = MultitargetUtil.GetAssemblyQualifiedName(serializedType, typeNameConverter); - if (!string.IsNullOrEmpty(assemblyQualifiedTypeName)) { + if (!string.IsNullOrEmpty(assemblyQualifiedTypeName)) + { int pos = assemblyQualifiedTypeName.IndexOf(','); - if (pos > 0 && pos < assemblyQualifiedTypeName.Length - 1) { + if (pos > 0 && pos < assemblyQualifiedTypeName.Length - 1) + { assemblyName = assemblyQualifiedTypeName.Substring(pos + 1).TrimStart(); string newTypeName = assemblyQualifiedTypeName.Substring(0, pos); - if (!string.Equals(newTypeName, serializedType.FullName, StringComparison.InvariantCulture)) { + if (!string.Equals(newTypeName, serializedType.FullName, StringComparison.InvariantCulture)) + { typeName = newTypeName; } return; @@ -783,115 +931,141 @@ public override void BindToName(Type serializedType, out string assemblyName, ou } } - internal class AssemblyNamesTypeResolutionService : ITypeResolutionService { + internal class AssemblyNamesTypeResolutionService : ITypeResolutionService + { private AssemblyName[] names; private Hashtable cachedAssemblies; private Hashtable cachedTypes; private static string NetFrameworkPath = Path.Combine(Environment.GetEnvironmentVariable("SystemRoot"), "Microsoft.Net\\Framework"); - internal AssemblyNamesTypeResolutionService(AssemblyName[] names) { + internal AssemblyNamesTypeResolutionService(AssemblyName[] names) + { this.names = names; } - - public Assembly GetAssembly(AssemblyName name) { + + public Assembly GetAssembly(AssemblyName name) + { return GetAssembly(name, true); } // [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] - public Assembly GetAssembly(AssemblyName name, bool throwOnError) { + public Assembly GetAssembly(AssemblyName name, bool throwOnError) + { Assembly result = null; - if (cachedAssemblies == null) { + if (cachedAssemblies == null) + { cachedAssemblies = Hashtable.Synchronized(new Hashtable()); } - if (cachedAssemblies.Contains(name)) { + if (cachedAssemblies.Contains(name)) + { result = cachedAssemblies[name] as Assembly; } - - if (result == null) { + + if (result == null) + { result = Assembly.Load(name.FullName); - if(result != null) { + if (result != null) + { cachedAssemblies[name] = result; - } + } else if (names != null) { foreach (AssemblyName asmName in names.Where(an => an.Equals(name))) { - try { + try + { result = Assembly.LoadFrom(GetPathOfAssembly(asmName)); - if(result != null) { + if (result != null) + { cachedAssemblies[asmName] = result; } } - catch { - if(throwOnError) { + catch + { + if (throwOnError) + { throw; } } } } } - + return result; } - public string GetPathOfAssembly(AssemblyName name) { + public string GetPathOfAssembly(AssemblyName name) + { return name.CodeBase; } - public Type GetType(string name) { + public Type GetType(string name) + { return GetType(name, true); } - public Type GetType(string name, bool throwOnError) { + public Type GetType(string name, bool throwOnError) + { return GetType(name, throwOnError, false); } - public Type GetType(string name, bool throwOnError, bool ignoreCase) { + public Type GetType(string name, bool throwOnError, bool ignoreCase) + { Type result = null; // Check type cache first - if (cachedTypes == null) { + if (cachedTypes == null) + { cachedTypes = Hashtable.Synchronized(new Hashtable(StringComparer.Ordinal)); } - if (cachedTypes.Contains(name)) { + if (cachedTypes.Contains(name)) + { result = cachedTypes[name] as Type; return result; } // Missed in cache, try to resolve the type from the reference assemblies. - if(name.IndexOf(',') != -1) { + if (name.IndexOf(',') != -1) + { result = Type.GetType(name, false, ignoreCase); } - if(result == null && names != null) { + if (result == null && names != null) + { // // If the type is assembly qualified name, we sort the assembly names // to put assemblies with same name in the front so that they can // be searched first. int pos = name.IndexOf(','); - if (pos > 0 && pos < name.Length - 1) { + if (pos > 0 && pos < name.Length - 1) + { string fullName = name.Substring(pos + 1).Trim(); AssemblyName assemblyName = null; - try { + try + { assemblyName = new AssemblyName(fullName); } - catch { + catch + { } - if (assemblyName != null) { + if (assemblyName != null) + { List assemblyList = new List(names.Length); foreach (AssemblyName asmName in names) { - if (string.Compare(assemblyName.Name, asmName.Name, StringComparison.OrdinalIgnoreCase) == 0) { + if (string.Compare(assemblyName.Name, asmName.Name, StringComparison.OrdinalIgnoreCase) == 0) + { assemblyList.Insert(0, asmName); } - else { + else + { assemblyList.Add(asmName); } } @@ -903,30 +1077,36 @@ public Type GetType(string name, bool throwOnError, bool ignoreCase) { foreach (AssemblyName asmName in names) { Assembly asm = GetAssembly(asmName, false); - if (asm != null) { + if (asm != null) + { result = asm.GetType(name, false, ignoreCase); - if(result == null) { + if (result == null) + { int indexOfComma = name.IndexOf(','); - if(indexOfComma != -1) { - string shortName = name.Substring(0, indexOfComma ); + if (indexOfComma != -1) + { + string shortName = name.Substring(0, indexOfComma); result = asm.GetType(shortName, false, ignoreCase); } } } - if(result != null) + if (result != null) break; } } - if(result == null && throwOnError) { + if (result == null && throwOnError) + { throw new ArgumentException(string.Format(SR.InvalidResXNoType, name)); } - if(result != null) { + if (result != null) + { // Only cache types from .Net framework because they don't need to update. // For simplicity, don't cache custom types - if (IsNetFrameworkAssembly(result.Assembly.Location)) { + if (IsNetFrameworkAssembly(result.Assembly.Location)) + { cachedTypes[name] = result; } } @@ -942,9 +1122,10 @@ private bool IsNetFrameworkAssembly(string assemblyPath) return assemblyPath != null && assemblyPath.StartsWith(NetFrameworkPath, StringComparison.OrdinalIgnoreCase); } - public void ReferenceAssembly(AssemblyName name) { + public void ReferenceAssembly(AssemblyName name) + { throw new NotSupportedException(); } - + } } diff --git a/src/System.Windows.Forms/src/System/Resources/ResXFileRef.cs b/src/System.Windows.Forms/src/System/Resources/ResXFileRef.cs index 2ff53c2d756..723d8bd2cc5 100644 --- a/src/System.Windows.Forms/src/System/Resources/ResXFileRef.cs +++ b/src/System.Windows.Forms/src/System/Resources/ResXFileRef.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Resources { +namespace System.Resources +{ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -26,7 +27,8 @@ namespace System.Resources { /// for the value of the resource item, the external resource is loaded. /// [TypeConverterAttribute(typeof(ResXFileRef.Converter)), Serializable] - public class ResXFileRef { + public class ResXFileRef + { private string fileName; private string typeName; [OptionalField(VersionAdded = 2)] @@ -37,19 +39,22 @@ public class ResXFileRef { /// The type refered to by typeName must support a constructor /// that accepts a System.IO.Stream as a parameter. /// - public ResXFileRef(string fileName, string typeName) { + public ResXFileRef(string fileName, string typeName) + { this.fileName = fileName ?? throw new ArgumentNullException(nameof(fileName)); this.typeName = typeName ?? throw new ArgumentNullException(nameof(typeName)); } - [OnDeserializing] - private void OnDeserializing(StreamingContext ctx) { + [OnDeserializing] + private void OnDeserializing(StreamingContext ctx) + { textFileEncoding = null; } [SuppressMessage("Microsoft.Performance", "CA1822:MarkMethodsAsStatic")] - [OnDeserialized] - private void OnDeserialized(StreamingContext ctx) { + [OnDeserialized] + private void OnDeserialized(StreamingContext ctx) + { } /// @@ -57,28 +62,36 @@ private void OnDeserialized(StreamingContext ctx) { /// The type refered to by typeName must support a constructor /// that accepts a System.IO.Stream as a parameter. /// - public ResXFileRef(string fileName, string typeName, Encoding textFileEncoding) : this(fileName, typeName) { + public ResXFileRef(string fileName, string typeName, Encoding textFileEncoding) : this(fileName, typeName) + { this.textFileEncoding = textFileEncoding; } - - internal ResXFileRef Clone() { + + internal ResXFileRef Clone() + { return new ResXFileRef(fileName, typeName, textFileEncoding); } - public string FileName { - get { + public string FileName + { + get + { return fileName; } } - public string TypeName { - get { + public string TypeName + { + get + { return typeName; } } - public Encoding TextFileEncoding { - get { + public Encoding TextFileEncoding + { + get + { return textFileEncoding; } } @@ -89,82 +102,101 @@ public Encoding TextFileEncoding { /// path2 such that if path1 and the calculated difference are used /// as arguments to Combine(), path2 is returned /// - private static string PathDifference(string path1, string path2, bool compareCase) { + private static string PathDifference(string path1, string path2, bool compareCase) + { int i; int si = -1; - for (i = 0; (i < path1.Length) && (i < path2.Length); ++i) { + for (i = 0; (i < path1.Length) && (i < path2.Length); ++i) + { if ((path1[i] != path2[i]) && (compareCase || (char.ToLower(path1[i], CultureInfo.InvariantCulture) != char.ToLower(path2[i], CultureInfo.InvariantCulture)))) { break; } - if (path1[i] == Path.DirectorySeparatorChar) { + if (path1[i] == Path.DirectorySeparatorChar) + { si = i; } } - if (i == 0) { + if (i == 0) + { return path2; } - if ((i == path1.Length) && (i == path2.Length)) { + if ((i == path1.Length) && (i == path2.Length)) + { return string.Empty; } StringBuilder relPath = new StringBuilder(); - for (; i < path1.Length; ++i) { - if (path1[i] == Path.DirectorySeparatorChar) { - relPath.Append(".."+Path.DirectorySeparatorChar); + for (; i < path1.Length; ++i) + { + if (path1[i] == Path.DirectorySeparatorChar) + { + relPath.Append(".." + Path.DirectorySeparatorChar); } } return relPath.ToString() + path2.Substring(si + 1); } - internal void MakeFilePathRelative(string basePath) { - - if(string.IsNullOrEmpty(basePath)) { + internal void MakeFilePathRelative(string basePath) + { + + if (string.IsNullOrEmpty(basePath)) + { return; } fileName = PathDifference(basePath, fileName, false); } - public override string ToString() { + public override string ToString() + { string result = string.Empty; - - if(fileName.IndexOf(';') != -1 || fileName.IndexOf('\"') != -1) { - result += ("\""+ fileName + "\";"); - } else { + + if (fileName.IndexOf(';') != -1 || fileName.IndexOf('\"') != -1) + { + result += ("\"" + fileName + "\";"); + } + else + { result += (fileName + ";"); } result += typeName; - if(textFileEncoding != null) { + if (textFileEncoding != null) + { result += (";" + textFileEncoding.WebName); } return result; } - public class Converter : TypeConverter { + public class Converter : TypeConverter + { public override bool CanConvertFrom(ITypeDescriptorContext context, - Type sourceType) { - if (sourceType == typeof(string)) { + Type sourceType) + { + if (sourceType == typeof(string)) + { return true; } return false; } - public override bool CanConvertTo(ITypeDescriptorContext context, + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof(string); } - public override object ConvertTo(ITypeDescriptorContext context, + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, - object value, - Type destinationType) { + object value, + Type destinationType) + { object created = null; - if (destinationType == typeof(string)) { + if (destinationType == typeof(string)) + { created = ((ResXFileRef)value).ToString(); } return created; @@ -172,87 +204,105 @@ public override object ConvertTo(ITypeDescriptorContext context, // "value" is the parameter name of ConvertFrom, which calls this method. [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] - internal static string[] ParseResxFileRefString(string stringValue) { + internal static string[] ParseResxFileRefString(string stringValue) + { string[] result = null; - if(stringValue != null ) { + if (stringValue != null) + { stringValue = stringValue.Trim(); string fileName; string remainingString; - if(stringValue.StartsWith("\"")) { + if (stringValue.StartsWith("\"")) + { int lastIndexOfQuote = stringValue.LastIndexOf('\"'); if (lastIndexOfQuote - 1 < 0) throw new ArgumentException(nameof(stringValue)); fileName = stringValue.Substring(1, lastIndexOfQuote - 1); // remove the quotes in" ..... " - if(lastIndexOfQuote + 2 > stringValue.Length) + if (lastIndexOfQuote + 2 > stringValue.Length) throw new ArgumentException(nameof(stringValue)); remainingString = stringValue.Substring(lastIndexOfQuote + 2); - } else { + } + else + { int nextSemiColumn = stringValue.IndexOf(';'); - if(nextSemiColumn == -1) + if (nextSemiColumn == -1) throw new ArgumentException(nameof(stringValue)); fileName = stringValue.Substring(0, nextSemiColumn); - if(nextSemiColumn + 1 > stringValue.Length) + if (nextSemiColumn + 1 > stringValue.Length) throw new ArgumentException(nameof(stringValue)); remainingString = stringValue.Substring(nextSemiColumn + 1); } string[] parts = remainingString.Split(';'); - if(parts.Length > 1) { + if (parts.Length > 1) + { result = new string[] { fileName, parts[0], parts[1] }; - } else if(parts.Length > 0) { + } + else if (parts.Length > 0) + { result = new string[] { fileName, parts[0] }; - } else { + } + else + { result = new string[] { fileName }; } } - return result; + return result; } - public override object ConvertFrom(ITypeDescriptorContext context, + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, - object value) { - if (value is string stringValue) { + object value) + { + if (value is string stringValue) + { string[] parts = ParseResxFileRefString(stringValue); string fileName = parts[0]; Type toCreate = Type.GetType(parts[1], true); // special case string and byte[] - if(toCreate == typeof(string)) { + if (toCreate == typeof(string)) + { // we have a string, now we need to check the encoding - Encoding textFileEncoding = + Encoding textFileEncoding = parts.Length > 2 - ? Encoding.GetEncoding(parts[2]) + ? Encoding.GetEncoding(parts[2]) : Encoding.Default; - using (StreamReader sr = new StreamReader(fileName, textFileEncoding)) { + using (StreamReader sr = new StreamReader(fileName, textFileEncoding)) + { return sr.ReadToEnd(); } } - + // this is a regular file, we call it's constructor with a stream as a parameter // or if it's a byte array we just return that byte[] temp = null; - using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { + using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) + { Debug.Assert(fileStream != null, "Couldn't open " + fileName); temp = new byte[fileStream.Length]; fileStream.Read(temp, 0, (int)fileStream.Length); } - if(toCreate == typeof(byte[])) { + if (toCreate == typeof(byte[])) + { return temp; } - + MemoryStream memStream = new MemoryStream(temp); - if(toCreate == typeof(MemoryStream)) { + if (toCreate == typeof(MemoryStream)) + { return memStream; } - if(toCreate == typeof(Bitmap) && fileName.EndsWith(".ico")) { + if (toCreate == typeof(Bitmap) && fileName.EndsWith(".ico")) + { // we special case the .ico bitmaps because GDI+ destroy the alpha channel component and // we don't want that to happen Icon ico = new Icon(memStream); return ico.ToBitmap(); } - - return Activator.CreateInstance(toCreate, BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance, null, new object[] {memStream}, null); + + return Activator.CreateInstance(toCreate, BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance, null, new object[] { memStream }, null); } return null; } diff --git a/src/System.Windows.Forms/src/System/Resources/ResXNullRef.cs b/src/System.Windows.Forms/src/System/Resources/ResXNullRef.cs index 8cda5148f2a..16939fa53cd 100644 --- a/src/System.Windows.Forms/src/System/Resources/ResXNullRef.cs +++ b/src/System.Windows.Forms/src/System/Resources/ResXNullRef.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Resources { +namespace System.Resources +{ using System.Diagnostics; using System; @@ -22,7 +23,8 @@ namespace System.Resources { /// with null. /// [Serializable] - internal sealed class ResXNullRef { + internal sealed class ResXNullRef + { } } diff --git a/src/System.Windows.Forms/src/System/Resources/ResXResourceReader.cs b/src/System.Windows.Forms/src/System/Resources/ResXResourceReader.cs index e216cb71aeb..6ea4244301f 100644 --- a/src/System.Windows.Forms/src/System/Resources/ResXResourceReader.cs +++ b/src/System.Windows.Forms/src/System/Resources/ResXResourceReader.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Resources { +namespace System.Resources +{ using System.Diagnostics; using System.Runtime.Serialization; @@ -21,11 +22,12 @@ namespace System.Resources { using System.Xml; using System.ComponentModel.Design; using System.Globalization; - + /// /// ResX resource reader. /// - public class ResXResourceReader : IResourceReader { + public class ResXResourceReader : IResourceReader + { string fileName = null; TextReader reader = null; Stream stream = null; @@ -35,7 +37,7 @@ public class ResXResourceReader : IResourceReader { bool isReaderDirty = false; ITypeResolutionService typeResolver; - IAliasResolver aliasResolver =null; + IAliasResolver aliasResolver = null; ListDictionary resData = null; ListDictionary resMetadata = null; @@ -46,87 +48,109 @@ public class ResXResourceReader : IResourceReader { bool useResXDataNodes = false; - private ResXResourceReader(ITypeResolutionService typeResolver) { + private ResXResourceReader(ITypeResolutionService typeResolver) + { this.typeResolver = typeResolver; this.aliasResolver = new ReaderAliasResolver(); } - private ResXResourceReader(AssemblyName[] assemblyNames) { + private ResXResourceReader(AssemblyName[] assemblyNames) + { this.assemblyNames = assemblyNames; this.aliasResolver = new ReaderAliasResolver(); } - public ResXResourceReader(string fileName) : this(fileName, (ITypeResolutionService)null, (IAliasResolver)null) { + public ResXResourceReader(string fileName) : this(fileName, (ITypeResolutionService)null, (IAliasResolver)null) + { } - public ResXResourceReader(string fileName, ITypeResolutionService typeResolver) : this(fileName, typeResolver, (IAliasResolver)null) { + public ResXResourceReader(string fileName, ITypeResolutionService typeResolver) : this(fileName, typeResolver, (IAliasResolver)null) + { } - internal ResXResourceReader(string fileName, ITypeResolutionService typeResolver, IAliasResolver aliasResolver) { + internal ResXResourceReader(string fileName, ITypeResolutionService typeResolver, IAliasResolver aliasResolver) + { this.fileName = fileName; this.typeResolver = typeResolver; this.aliasResolver = aliasResolver ?? new ReaderAliasResolver(); } - public ResXResourceReader(TextReader reader) : this(reader, (ITypeResolutionService)null, (IAliasResolver)null) { + public ResXResourceReader(TextReader reader) : this(reader, (ITypeResolutionService)null, (IAliasResolver)null) + { } - public ResXResourceReader(TextReader reader, ITypeResolutionService typeResolver) : this(reader, typeResolver, (IAliasResolver)null) { + public ResXResourceReader(TextReader reader, ITypeResolutionService typeResolver) : this(reader, typeResolver, (IAliasResolver)null) + { } - internal ResXResourceReader(TextReader reader, ITypeResolutionService typeResolver, IAliasResolver aliasResolver) { + internal ResXResourceReader(TextReader reader, ITypeResolutionService typeResolver, IAliasResolver aliasResolver) + { this.reader = reader; this.typeResolver = typeResolver; this.aliasResolver = aliasResolver ?? new ReaderAliasResolver(); } - - public ResXResourceReader(Stream stream) : this(stream, (ITypeResolutionService)null, (IAliasResolver)null) { + + public ResXResourceReader(Stream stream) : this(stream, (ITypeResolutionService)null, (IAliasResolver)null) + { } - public ResXResourceReader(Stream stream, ITypeResolutionService typeResolver) : this(stream, typeResolver, (IAliasResolver)null) { + public ResXResourceReader(Stream stream, ITypeResolutionService typeResolver) : this(stream, typeResolver, (IAliasResolver)null) + { } - internal ResXResourceReader(Stream stream, ITypeResolutionService typeResolver, IAliasResolver aliasResolver) { + internal ResXResourceReader(Stream stream, ITypeResolutionService typeResolver, IAliasResolver aliasResolver) + { this.stream = stream; this.typeResolver = typeResolver; this.aliasResolver = aliasResolver ?? new ReaderAliasResolver(); } - public ResXResourceReader(Stream stream, AssemblyName[] assemblyNames) : this(stream, assemblyNames, (IAliasResolver)null){ + public ResXResourceReader(Stream stream, AssemblyName[] assemblyNames) : this(stream, assemblyNames, (IAliasResolver)null) + { } - internal ResXResourceReader(Stream stream, AssemblyName[] assemblyNames, IAliasResolver aliasResolver) { + internal ResXResourceReader(Stream stream, AssemblyName[] assemblyNames, IAliasResolver aliasResolver) + { this.stream = stream; this.assemblyNames = assemblyNames; this.aliasResolver = aliasResolver ?? new ReaderAliasResolver(); } - public ResXResourceReader(TextReader reader, AssemblyName[] assemblyNames) : this(reader, assemblyNames, (IAliasResolver)null){ + public ResXResourceReader(TextReader reader, AssemblyName[] assemblyNames) : this(reader, assemblyNames, (IAliasResolver)null) + { } - internal ResXResourceReader(TextReader reader, AssemblyName[] assemblyNames, IAliasResolver aliasResolver) { + internal ResXResourceReader(TextReader reader, AssemblyName[] assemblyNames, IAliasResolver aliasResolver) + { this.reader = reader; this.assemblyNames = assemblyNames; this.aliasResolver = aliasResolver ?? new ReaderAliasResolver(); } - public ResXResourceReader(string fileName, AssemblyName[] assemblyNames) : this(fileName, assemblyNames, (IAliasResolver)null){ + public ResXResourceReader(string fileName, AssemblyName[] assemblyNames) : this(fileName, assemblyNames, (IAliasResolver)null) + { } - internal ResXResourceReader(string fileName, AssemblyName[] assemblyNames, IAliasResolver aliasResolver) { + internal ResXResourceReader(string fileName, AssemblyName[] assemblyNames, IAliasResolver aliasResolver) + { this.fileName = fileName; this.assemblyNames = assemblyNames; this.aliasResolver = aliasResolver ?? new ReaderAliasResolver(); } - - ~ResXResourceReader() { + + ~ResXResourceReader() + { Dispose(false); } /// /// BasePath for relatives filepaths with ResXFileRefs. /// - public string BasePath { - get { + public string BasePath + { + get + { return basePath; } - set { - if(isReaderDirty) { + set + { + if (isReaderDirty) + { throw new InvalidOperationException(SR.InvalidResXBasePathOperation); } basePath = value; @@ -139,12 +163,16 @@ public string BasePath { /// happen, or a ResXFileRef object should be returned. Default is true for backward compat and common case /// scenario. /// - public bool UseResXDataNodes { - get { + public bool UseResXDataNodes + { + get + { return this.useResXDataNodes; } - set { - if(isReaderDirty) { + set + { + if (isReaderDirty) + { throw new InvalidOperationException(SR.InvalidResXBasePathOperation); } this.useResXDataNodes = value; @@ -155,31 +183,38 @@ public bool UseResXDataNodes { /// Closes and files or streams being used by the reader. /// // NOTE: Part of IResourceReader - not protected by class level LinkDemand. - public void Close() { + public void Close() + { ((IDisposable)this).Dispose(); } // NOTE: Part of IDisposable - not protected by class level LinkDemand. - void IDisposable.Dispose() { + void IDisposable.Dispose() + { GC.SuppressFinalize(this); Dispose(true); } - protected virtual void Dispose(bool disposing) { - if (disposing) { - if (fileName != null && stream != null) { + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + if (fileName != null && stream != null) + { stream.Close(); stream = null; } - if (reader != null) { + if (reader != null) + { reader.Close(); reader = null; } } } - private void SetupNameTable(XmlReader reader) { + private void SetupNameTable(XmlReader reader) + { reader.NameTable.Add(ResXResourceWriter.TypeStr); reader.NameTable.Add(ResXResourceWriter.NameStr); reader.NameTable.Add(ResXResourceWriter.DataStr); @@ -200,23 +235,30 @@ private void SetupNameTable(XmlReader reader) { /// /// Demand loads the resource data. /// - private void EnsureResData() { - if (resData == null) { + private void EnsureResData() + { + if (resData == null) + { resData = new ListDictionary(); resMetadata = new ListDictionary(); XmlTextReader contentReader = null; - try { + try + { // Read data in any which way - if (fileContents != null) { + if (fileContents != null) + { contentReader = new XmlTextReader(new StringReader(fileContents)); } - else if (reader != null) { + else if (reader != null) + { contentReader = new XmlTextReader(reader); } - else if (fileName != null || stream != null) { - if (stream == null) { + else if (fileName != null || stream != null) + { + if (stream == null) + { stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); } @@ -227,28 +269,32 @@ private void EnsureResData() { contentReader.WhitespaceHandling = WhitespaceHandling.None; ParseXml(contentReader); } - finally { - if (fileName != null && stream != null) { + finally + { + if (fileName != null && stream != null) + { stream.Close(); stream = null; } } } - } + } /// /// Creates a reader with the specified file contents. /// - public static ResXResourceReader FromFileContents(string fileContents) { + public static ResXResourceReader FromFileContents(string fileContents) + { return FromFileContents(fileContents, (ITypeResolutionService)null); } /// /// Creates a reader with the specified file contents. /// - public static ResXResourceReader FromFileContents(string fileContents, ITypeResolutionService typeResolver) { + public static ResXResourceReader FromFileContents(string fileContents, ITypeResolutionService typeResolver) + { return new ResXResourceReader(typeResolver) { fileContents = fileContents @@ -258,7 +304,8 @@ public static ResXResourceReader FromFileContents(string fileContents, ITypeReso /// /// Creates a reader with the specified file contents. /// - public static ResXResourceReader FromFileContents(string fileContents, AssemblyName[] assemblyNames) { + public static ResXResourceReader FromFileContents(string fileContents, AssemblyName[] assemblyNames) + { return new ResXResourceReader(assemblyNames) { fileContents = fileContents @@ -266,12 +313,14 @@ public static ResXResourceReader FromFileContents(string fileContents, AssemblyN } // NOTE: Part of IEnumerable - not protected by class level LinkDemand. - IEnumerator IEnumerable.GetEnumerator() { + IEnumerator IEnumerable.GetEnumerator() + { return GetEnumerator(); } // NOTE: Part of IResourceReader - not protected by class level LinkDemand. - public IDictionaryEnumerator GetEnumerator() { + public IDictionaryEnumerator GetEnumerator() + { isReaderDirty = true; EnsureResData(); return resData.GetEnumerator(); @@ -280,7 +329,8 @@ public IDictionaryEnumerator GetEnumerator() { /// /// Returns a dictionary enumerator that can be used to enumerate the elements in the .resx file. /// - public IDictionaryEnumerator GetMetadataEnumerator() { + public IDictionaryEnumerator GetMetadataEnumerator() + { EnsureResData(); return resMetadata.GetEnumerator(); } @@ -288,10 +338,12 @@ public IDictionaryEnumerator GetMetadataEnumerator() { /// /// Attempts to return the line and column (Y, X) of the XML reader. /// - private Point GetPosition(XmlReader reader) { + private Point GetPosition(XmlReader reader) + { Point pt = new Point(0, 0); - if (reader is IXmlLineInfo lineInfo) { + if (reader is IXmlLineInfo lineInfo) + { pt.Y = lineInfo.LineNumber; pt.X = lineInfo.LinePosition; } @@ -300,24 +352,33 @@ private Point GetPosition(XmlReader reader) { } - private void ParseXml(XmlTextReader reader) { + private void ParseXml(XmlTextReader reader) + { bool success = false; - try { - try { - while (reader.Read()) { - if (reader.NodeType == XmlNodeType.Element) { + try + { + try + { + while (reader.Read()) + { + if (reader.NodeType == XmlNodeType.Element) + { string s = reader.LocalName; - - if (reader.LocalName.Equals(ResXResourceWriter.AssemblyStr)) { + + if (reader.LocalName.Equals(ResXResourceWriter.AssemblyStr)) + { ParseAssemblyNode(reader); } - else if (reader.LocalName.Equals(ResXResourceWriter.DataStr)) { + else if (reader.LocalName.Equals(ResXResourceWriter.DataStr)) + { ParseDataNode(reader, false); } - else if (reader.LocalName.Equals(ResXResourceWriter.ResHeaderStr)) { + else if (reader.LocalName.Equals(ResXResourceWriter.ResHeaderStr)) + { ParseResHeaderNode(reader); } - else if (reader.LocalName.Equals(ResXResourceWriter.MetadataStr)) { + else if (reader.LocalName.Equals(ResXResourceWriter.MetadataStr)) + { ParseDataNode(reader, true); } } @@ -325,7 +386,8 @@ private void ParseXml(XmlTextReader reader) { success = true; } - catch (SerializationException se) { + catch (SerializationException se) + { Point pt = GetPosition(reader); string newMessage = string.Format(SR.SerializationException, reader[ResXResourceWriter.TypeStr], pt.Y, pt.X, se.Message); XmlException xml = new XmlException(newMessage, se, pt.Y, pt.X); @@ -333,7 +395,8 @@ private void ParseXml(XmlTextReader reader) { throw newSe; } - catch (TargetInvocationException tie) { + catch (TargetInvocationException tie) + { Point pt = GetPosition(reader); string newMessage = string.Format(SR.InvocationException, reader[ResXResourceWriter.TypeStr], pt.Y, pt.X, tie.InnerException.Message); XmlException xml = new XmlException(newMessage, tie.InnerException, pt.Y, pt.X); @@ -341,21 +404,28 @@ private void ParseXml(XmlTextReader reader) { throw newTie; } - catch (XmlException e) { + catch (XmlException e) + { throw new ArgumentException(string.Format(SR.InvalidResXFile, e.Message), e); } - catch (Exception e) { - if (ClientUtils.IsSecurityOrCriticalException(e)) { + catch (Exception e) + { + if (ClientUtils.IsSecurityOrCriticalException(e)) + { throw; - } else { + } + else + { Point pt = GetPosition(reader); XmlException xmlEx = new XmlException(e.Message, e, pt.Y, pt.X); throw new ArgumentException(string.Format(SR.InvalidResXFile, xmlEx.Message), xmlEx); } } } - finally { - if (!success) { + finally + { + if (!success) + { resData = null; resMetadata = null; } @@ -363,38 +433,45 @@ private void ParseXml(XmlTextReader reader) { bool validFile = false; - if (resHeaderMimeType == ResXResourceWriter.ResMimeType) { + if (resHeaderMimeType == ResXResourceWriter.ResMimeType) + { Type readerType = typeof(ResXResourceReader); Type writerType = typeof(ResXResourceWriter); string readerTypeName = resHeaderReaderType; string writerTypeName = resHeaderWriterType; - if (readerTypeName != null &&readerTypeName.IndexOf(',') != -1) { + if (readerTypeName != null && readerTypeName.IndexOf(',') != -1) + { readerTypeName = readerTypeName.Split(',')[0].Trim(); } - if (writerTypeName != null && writerTypeName.IndexOf(',') != -1) { + if (writerTypeName != null && writerTypeName.IndexOf(',') != -1) + { writerTypeName = writerTypeName.Split(',')[0].Trim(); } - if (readerTypeName != null && - writerTypeName != null && - readerTypeName.Equals(readerType.FullName) && - writerTypeName.Equals(writerType.FullName)) { + if (readerTypeName != null && + writerTypeName != null && + readerTypeName.Equals(readerType.FullName) && + writerTypeName.Equals(writerType.FullName)) + { validFile = true; } } - if (!validFile) { + if (!validFile) + { resData = null; resMetadata = null; throw new ArgumentException(SR.InvalidResXFileReaderWriterTypes); } } - private void ParseResHeaderNode(XmlReader reader) { + private void ParseResHeaderNode(XmlReader reader) + { string name = reader[ResXResourceWriter.NameStr]; - if (name != null) { + if (name != null) + { reader.ReadStartElement(); // The "1.1" schema requires the correct casing of the strings @@ -403,69 +480,91 @@ private void ParseResHeaderNode(XmlReader reader) { // see significant performance improvements. // - if (name == ResXResourceWriter.VersionStr) { - if (reader.NodeType == XmlNodeType.Element) { + if (name == ResXResourceWriter.VersionStr) + { + if (reader.NodeType == XmlNodeType.Element) + { resHeaderVersion = reader.ReadElementString(); } - else { + else + { resHeaderVersion = reader.Value.Trim(); } } - else if (name == ResXResourceWriter.ResMimeTypeStr) { - if (reader.NodeType == XmlNodeType.Element) { + else if (name == ResXResourceWriter.ResMimeTypeStr) + { + if (reader.NodeType == XmlNodeType.Element) + { resHeaderMimeType = reader.ReadElementString(); } - else { + else + { resHeaderMimeType = reader.Value.Trim(); } } - else if (name == ResXResourceWriter.ReaderStr) { - if (reader.NodeType == XmlNodeType.Element) { + else if (name == ResXResourceWriter.ReaderStr) + { + if (reader.NodeType == XmlNodeType.Element) + { resHeaderReaderType = reader.ReadElementString(); } - else { + else + { resHeaderReaderType = reader.Value.Trim(); } } - else if (name == ResXResourceWriter.WriterStr) { - if (reader.NodeType == XmlNodeType.Element) { + else if (name == ResXResourceWriter.WriterStr) + { + if (reader.NodeType == XmlNodeType.Element) + { resHeaderWriterType = reader.ReadElementString(); } - else { + else + { resHeaderWriterType = reader.Value.Trim(); } } - else { - switch (name.ToLower(CultureInfo.InvariantCulture)) { + else + { + switch (name.ToLower(CultureInfo.InvariantCulture)) + { case ResXResourceWriter.VersionStr: - if (reader.NodeType == XmlNodeType.Element) { + if (reader.NodeType == XmlNodeType.Element) + { resHeaderVersion = reader.ReadElementString(); } - else { + else + { resHeaderVersion = reader.Value.Trim(); } break; case ResXResourceWriter.ResMimeTypeStr: - if (reader.NodeType == XmlNodeType.Element) { + if (reader.NodeType == XmlNodeType.Element) + { resHeaderMimeType = reader.ReadElementString(); } - else { + else + { resHeaderMimeType = reader.Value.Trim(); } break; case ResXResourceWriter.ReaderStr: - if (reader.NodeType == XmlNodeType.Element) { + if (reader.NodeType == XmlNodeType.Element) + { resHeaderReaderType = reader.ReadElementString(); } - else { + else + { resHeaderReaderType = reader.Value.Trim(); } break; case ResXResourceWriter.WriterStr: - if (reader.NodeType == XmlNodeType.Element) { + if (reader.NodeType == XmlNodeType.Element) + { resHeaderWriterType = reader.ReadElementString(); } - else { + else + { resHeaderWriterType = reader.Value.Trim(); } break; @@ -480,15 +579,17 @@ private void ParseAssemblyNode(XmlReader reader) string typeName = reader[ResXResourceWriter.NameStr]; AssemblyName assemblyName = new AssemblyName(typeName); - - if (string.IsNullOrEmpty(alias)) { + + if (string.IsNullOrEmpty(alias)) + { alias = assemblyName.Name; } aliasResolver.PushAlias(alias, assemblyName); } - - private void ParseDataNode(XmlTextReader reader, bool isMetaData) { + + private void ParseDataNode(XmlTextReader reader, bool isMetaData) + { DataNodeInfo nodeInfo = new DataNodeInfo { Name = reader[ResXResourceWriter.NameStr] @@ -498,35 +599,45 @@ private void ParseDataNode(XmlTextReader reader, bool isMetaData) { string alias = null; AssemblyName assemblyName = null; - - if (!string.IsNullOrEmpty(typeName)) { - alias = GetAliasFromTypeName(typeName); + + if (!string.IsNullOrEmpty(typeName)) + { + alias = GetAliasFromTypeName(typeName); } - if (!string.IsNullOrEmpty(alias)) { + if (!string.IsNullOrEmpty(alias)) + { assemblyName = aliasResolver.ResolveAlias(alias); } - if (assemblyName != null ) + if (assemblyName != null) { nodeInfo.TypeName = GetTypeFromTypeName(typeName) + ", " + assemblyName.FullName; } - else { + else + { nodeInfo.TypeName = reader[ResXResourceWriter.TypeStr]; } - + nodeInfo.MimeType = reader[ResXResourceWriter.MimeTypeStr]; bool finishedReadingDataNode = false; nodeInfo.ReaderPosition = GetPosition(reader); - while(!finishedReadingDataNode && reader.Read()) { - if(reader.NodeType == XmlNodeType.EndElement && ( reader.LocalName.Equals(ResXResourceWriter.DataStr) || reader.LocalName.Equals(ResXResourceWriter.MetadataStr) )) { + while (!finishedReadingDataNode && reader.Read()) + { + if (reader.NodeType == XmlNodeType.EndElement && (reader.LocalName.Equals(ResXResourceWriter.DataStr) || reader.LocalName.Equals(ResXResourceWriter.MetadataStr))) + { // we just found , quit or finishedReadingDataNode = true; - } else { + } + else + { // could be a or a - if (reader.NodeType == XmlNodeType.Element) { - if (reader.Name.Equals(ResXResourceWriter.ValueStr)) { + if (reader.NodeType == XmlNodeType.Element) + { + if (reader.Name.Equals(ResXResourceWriter.ValueStr)) + { WhitespaceHandling oldValue = reader.WhitespaceHandling; - try { + try + { // based on the documentation at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemxmlxmltextreaderclasswhitespacehandlingtopic.asp // this is ok because: // "Because the XmlTextReader does not have DTD information available to it, @@ -538,74 +649,95 @@ private void ParseDataNode(XmlTextReader reader, bool isMetaData) { // of xml:space=preserve might have different consequences... reader.WhitespaceHandling = WhitespaceHandling.Significant; nodeInfo.ValueData = reader.ReadString(); - } finally { + } + finally + { reader.WhitespaceHandling = oldValue; } - } else if (reader.Name.Equals(ResXResourceWriter.CommentStr)) { + } + else if (reader.Name.Equals(ResXResourceWriter.CommentStr)) + { nodeInfo.Comment = reader.ReadString(); } - } else { + } + else + { // weird, no tag, just the inside of as text nodeInfo.ValueData = reader.Value.Trim(); } } - } + } - if (nodeInfo.Name == null) { + if (nodeInfo.Name == null) + { throw new ArgumentException(string.Format(SR.InvalidResXResourceNoName, nodeInfo.ValueData)); } ResXDataNode dataNode = new ResXDataNode(nodeInfo, BasePath); - if(UseResXDataNodes) { + if (UseResXDataNodes) + { resData[nodeInfo.Name] = dataNode; - } else { + } + else + { IDictionary data = (isMetaData ? resMetadata : resData); - if(assemblyNames == null) { + if (assemblyNames == null) + { data[nodeInfo.Name] = dataNode.GetValue(typeResolver); - } else { + } + else + { data[nodeInfo.Name] = dataNode.GetValue(assemblyNames); } } } - private string GetAliasFromTypeName(string typeName) { - - int indexStart = typeName.IndexOf(','); - return typeName.Substring(indexStart + 2); - + private string GetAliasFromTypeName(string typeName) + { + + int indexStart = typeName.IndexOf(','); + return typeName.Substring(indexStart + 2); + } - private string GetTypeFromTypeName(string typeName) { - - int indexStart = typeName.IndexOf(','); - return typeName.Substring(0, indexStart); - + private string GetTypeFromTypeName(string typeName) + { + + int indexStart = typeName.IndexOf(','); + return typeName.Substring(0, indexStart); + } - private sealed class ReaderAliasResolver : IAliasResolver { + private sealed class ReaderAliasResolver : IAliasResolver + { private Hashtable cachedAliases; - internal ReaderAliasResolver() { + internal ReaderAliasResolver() + { this.cachedAliases = new Hashtable(); } - public AssemblyName ResolveAlias(string alias) { + public AssemblyName ResolveAlias(string alias) + { AssemblyName result = null; - if(cachedAliases != null) { + if (cachedAliases != null) + { result = (AssemblyName)cachedAliases[alias]; - } + } return result; } - public void PushAlias(string alias, AssemblyName name) { - if (this.cachedAliases != null && !string.IsNullOrEmpty(alias)) { + public void PushAlias(string alias, AssemblyName name) + { + if (this.cachedAliases != null && !string.IsNullOrEmpty(alias)) + { cachedAliases[alias] = name; } } - + } } } diff --git a/src/System.Windows.Forms/src/System/Resources/ResXResourceSet.cs b/src/System.Windows.Forms/src/System/Resources/ResXResourceSet.cs index ac19c275446..febd09ae5c6 100644 --- a/src/System.Windows.Forms/src/System/Resources/ResXResourceSet.cs +++ b/src/System.Windows.Forms/src/System/Resources/ResXResourceSet.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Resources { +namespace System.Resources +{ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -20,7 +21,8 @@ namespace System.Resources { /// /// ResX resource set. /// - public class ResXResourceSet : ResourceSet { + public class ResXResourceSet : ResourceSet + { /// /// Creates a resource set for the specified file. @@ -28,7 +30,8 @@ public class ResXResourceSet : ResourceSet { [ SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // Shipped like this in Everett. ] - public ResXResourceSet(string fileName) : base(new ResXResourceReader(fileName)) { + public ResXResourceSet(string fileName) : base(new ResXResourceReader(fileName)) + { ReadResources(); } @@ -38,21 +41,24 @@ public ResXResourceSet(string fileName) : base(new ResXResourceReader(fileName)) [ SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // Shipped like this in Everett. ] - public ResXResourceSet(Stream stream) : base(new ResXResourceReader(stream)) { + public ResXResourceSet(Stream stream) : base(new ResXResourceReader(stream)) + { ReadResources(); } /// /// Gets the default reader type associated with this set. /// - public override Type GetDefaultReader() { + public override Type GetDefaultReader() + { return typeof(ResXResourceReader); } /// /// Gets the default writer type associated with this set. /// - public override Type GetDefaultWriter() { + public override Type GetDefaultWriter() + { return typeof(ResXResourceWriter); } } diff --git a/src/System.Windows.Forms/src/System/Resources/ResXResourceWriter.cs b/src/System.Windows.Forms/src/System/Resources/ResXResourceWriter.cs index 40edb22d82e..35271c029dd 100644 --- a/src/System.Windows.Forms/src/System/Resources/ResXResourceWriter.cs +++ b/src/System.Windows.Forms/src/System/Resources/ResXResourceWriter.cs @@ -2,12 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Resources { +namespace System.Resources +{ using System.Diagnostics; using System.Reflection; using System; - using System.Windows.Forms; + using System.Windows.Forms; using Microsoft.Win32; using System.Drawing; using System.IO; @@ -23,7 +24,8 @@ namespace System.Resources { /// ResX resource writer. See the text in "ResourceSchema" for more /// information. /// - public class ResXResourceWriter : IResourceWriter { + public class ResXResourceWriter : IResourceWriter + { internal const string TypeStr = "type"; internal const string NameStr = "name"; internal const string DataStr = "data"; @@ -36,8 +38,8 @@ public class ResXResourceWriter : IResourceWriter { internal const string ReaderStr = "reader"; internal const string WriterStr = "writer"; internal const string CommentStr = "comment"; - internal const string AssemblyStr ="assembly"; - internal const string AliasStr= "alias" ; + internal const string AssemblyStr = "assembly"; + internal const string AliasStr = "alias"; private Hashtable cachedAliases; @@ -111,7 +113,7 @@ public class ResXResourceWriter : IResourceWriter { "; - + string fileName; Stream stream; TextWriter textWriter; @@ -121,7 +123,7 @@ public class ResXResourceWriter : IResourceWriter { bool initialized; private Func typeNameConverter; // no public property to be consistent with ResXDataNode class. - + /// /// Base Path for ResXFileRefs. /// @@ -130,10 +132,12 @@ public class ResXResourceWriter : IResourceWriter { /// /// Creates a new ResXResourceWriter that will write to the specified file. /// - public ResXResourceWriter(string fileName) { + public ResXResourceWriter(string fileName) + { this.fileName = fileName; } - public ResXResourceWriter(string fileName, Func typeNameConverter) { + public ResXResourceWriter(string fileName, Func typeNameConverter) + { this.fileName = fileName; this.typeNameConverter = typeNameConverter; } @@ -141,10 +145,12 @@ public ResXResourceWriter(string fileName, Func typeNameConverter) /// /// Creates a new ResXResourceWriter that will write to the specified stream. /// - public ResXResourceWriter(Stream stream) { + public ResXResourceWriter(Stream stream) + { this.stream = stream; } - public ResXResourceWriter(Stream stream, Func typeNameConverter) { + public ResXResourceWriter(Stream stream, Func typeNameConverter) + { this.stream = stream; this.typeNameConverter = typeNameConverter; } @@ -152,45 +158,55 @@ public ResXResourceWriter(Stream stream, Func typeNameConverter) { /// /// Creates a new ResXResourceWriter that will write to the specified TextWriter. /// - public ResXResourceWriter(TextWriter textWriter) { + public ResXResourceWriter(TextWriter textWriter) + { this.textWriter = textWriter; } - public ResXResourceWriter(TextWriter textWriter, Func typeNameConverter) { + public ResXResourceWriter(TextWriter textWriter, Func typeNameConverter) + { this.textWriter = textWriter; this.typeNameConverter = typeNameConverter; } - ~ResXResourceWriter() { + ~ResXResourceWriter() + { Dispose(false); } - private void InitializeWriter() { - if (xmlTextWriter == null) { + private void InitializeWriter() + { + if (xmlTextWriter == null) + { // bool writeHeaderRequired = false; - if (textWriter != null) { + if (textWriter != null) + { textWriter.WriteLine(""); writeHeaderRequired = true; xmlTextWriter = new XmlTextWriter(textWriter); } - else if (stream != null) { + else if (stream != null) + { xmlTextWriter = new XmlTextWriter(stream, System.Text.Encoding.UTF8); } - else { + else + { Debug.Assert(fileName != null, "Nothing to output to"); xmlTextWriter = new XmlTextWriter(fileName, System.Text.Encoding.UTF8); } xmlTextWriter.Formatting = Formatting.Indented; xmlTextWriter.Indentation = 2; - if (!writeHeaderRequired) { + if (!writeHeaderRequired) + { xmlTextWriter.WriteStartDocument(); // writes } } - else { + else + { xmlTextWriter.WriteStartDocument(); } @@ -199,33 +215,41 @@ private void InitializeWriter() { reader.WhitespaceHandling = WhitespaceHandling.None; xmlTextWriter.WriteNode(reader, true); - xmlTextWriter.WriteStartElement(ResHeaderStr); { + xmlTextWriter.WriteStartElement(ResHeaderStr); + { xmlTextWriter.WriteAttributeString(NameStr, ResMimeTypeStr); - xmlTextWriter.WriteStartElement(ValueStr); { + xmlTextWriter.WriteStartElement(ValueStr); + { xmlTextWriter.WriteString(ResMimeType); } xmlTextWriter.WriteEndElement(); } xmlTextWriter.WriteEndElement(); - xmlTextWriter.WriteStartElement(ResHeaderStr); { + xmlTextWriter.WriteStartElement(ResHeaderStr); + { xmlTextWriter.WriteAttributeString(NameStr, VersionStr); - xmlTextWriter.WriteStartElement(ValueStr); { + xmlTextWriter.WriteStartElement(ValueStr); + { xmlTextWriter.WriteString(Version); } xmlTextWriter.WriteEndElement(); } xmlTextWriter.WriteEndElement(); - xmlTextWriter.WriteStartElement(ResHeaderStr); { + xmlTextWriter.WriteStartElement(ResHeaderStr); + { xmlTextWriter.WriteAttributeString(NameStr, ReaderStr); - xmlTextWriter.WriteStartElement(ValueStr); { + xmlTextWriter.WriteStartElement(ValueStr); + { xmlTextWriter.WriteString(MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXResourceReader), this.typeNameConverter)); } xmlTextWriter.WriteEndElement(); } xmlTextWriter.WriteEndElement(); - xmlTextWriter.WriteStartElement(ResHeaderStr); { + xmlTextWriter.WriteStartElement(ResHeaderStr); + { xmlTextWriter.WriteAttributeString(NameStr, WriterStr); - xmlTextWriter.WriteStartElement(ValueStr); { + xmlTextWriter.WriteStartElement(ValueStr); + { xmlTextWriter.WriteString(MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXResourceWriter), this.typeNameConverter)); } xmlTextWriter.WriteEndElement(); @@ -235,9 +259,12 @@ private void InitializeWriter() { initialized = true; } - private XmlWriter Writer { - get { - if (!initialized) { + private XmlWriter Writer + { + get + { + if (!initialized) + { InitializeWriter(); } return xmlTextWriter; @@ -247,24 +274,28 @@ private XmlWriter Writer { /// /// Adds aliases to the resource file... /// - public virtual void AddAlias(string aliasName, AssemblyName assemblyName) { - if (assemblyName == null) { - throw new ArgumentNullException(nameof(assemblyName)); - } + public virtual void AddAlias(string aliasName, AssemblyName assemblyName) + { + if (assemblyName == null) + { + throw new ArgumentNullException(nameof(assemblyName)); + } - if (cachedAliases == null) { - cachedAliases = new Hashtable(); - } + if (cachedAliases == null) + { + cachedAliases = new Hashtable(); + } - cachedAliases[assemblyName.FullName] = aliasName; - } + cachedAliases[assemblyName.FullName] = aliasName; + } /// /// Adds the given value to the collection of metadata. These name/value pairs /// will be emitted to the elements in the .resx file. /// - public void AddMetadata(string name, byte[] value) { + public void AddMetadata(string name, byte[] value) + { AddDataRow(MetadataStr, name, value); } @@ -272,7 +303,8 @@ public void AddMetadata(string name, byte[] value) { /// Adds the given value to the collection of metadata. These name/value pairs /// will be emitted to the elements in the .resx file. /// - public void AddMetadata(string name, string value) { + public void AddMetadata(string name, string value) + { AddDataRow(MetadataStr, name, value); } @@ -280,7 +312,8 @@ public void AddMetadata(string name, string value) { /// Adds the given value to the collection of metadata. These name/value pairs /// will be emitted to the elements in the .resx file. /// - public void AddMetadata(string name, object value) { + public void AddMetadata(string name, object value) + { AddDataRow(MetadataStr, name, value); } @@ -288,7 +321,8 @@ public void AddMetadata(string name, object value) { /// Adds a blob resource to the resources. /// // NOTE: Part of IResourceWriter - not protected by class level LinkDemand. - public void AddResource(string name, byte[] value) { + public void AddResource(string name, byte[] value) + { AddDataRow(DataStr, name, value); } @@ -298,11 +332,14 @@ public void AddResource(string name, byte[] value) { /// and stored as in binary. /// // NOTE: Part of IResourceWriter - not protected by class level LinkDemand. - public void AddResource(string name, object value) { - if (value is ResXDataNode node) { + public void AddResource(string name, object value) + { + if (value is ResXDataNode node) + { AddResource(node); } - else { + else + { AddDataRow(DataStr, name, value); } } @@ -311,23 +348,26 @@ public void AddResource(string name, object value) { /// Adds a string resource to the resources. /// // NOTE: Part of IResourceWriter - not protected by class level LinkDemand. - public void AddResource(string name, string value) { + public void AddResource(string name, string value) + { AddDataRow(DataStr, name, value); } /// /// Adds a string resource to the resources. /// - public void AddResource(ResXDataNode node) { + public void AddResource(ResXDataNode node) + { // we're modifying the node as we're adding it to the resxwriter // this is BAD, so we clone it. adding it to a writer doesnt change it // we're messing with a copy ResXDataNode nodeClone = node.DeepClone(); - + ResXFileRef fileRef = nodeClone.FileRef; string modifiedBasePath = BasePath; - - if (!string.IsNullOrEmpty(modifiedBasePath)) { + + if (!string.IsNullOrEmpty(modifiedBasePath)) + { if (!modifiedBasePath.EndsWith("\\")) { modifiedBasePath += "\\"; @@ -342,7 +382,8 @@ public void AddResource(ResXDataNode node) { /// /// Adds a blob resource to the resources. /// - private void AddDataRow(string elementName, string name, byte[] value) { + private void AddDataRow(string elementName, string name, byte[] value) + { AddDataRow(elementName, name, ToBase64WrappedString(value), TypeNameWithAssembly(typeof(byte[])), null, null); } @@ -363,21 +404,21 @@ private void AddDataRow(string elementName, string name, object value) AddDataRow(elementName, name, bytes); break; case ResXFileRef fileRef: - { - ResXDataNode node = new ResXDataNode(name, fileRef, this.typeNameConverter); - DataNodeInfo info = node.GetDataNodeInfo(); - AddDataRow(elementName, info.Name, info.ValueData, info.TypeName, info.MimeType, info.Comment); - break; - } + { + ResXDataNode node = new ResXDataNode(name, fileRef, this.typeNameConverter); + DataNodeInfo info = node.GetDataNodeInfo(); + AddDataRow(elementName, info.Name, info.ValueData, info.TypeName, info.MimeType, info.Comment); + break; + } default: - { - ResXDataNode node = new ResXDataNode(name, value, this.typeNameConverter); - DataNodeInfo info = node.GetDataNodeInfo(); - AddDataRow(elementName, info.Name, info.ValueData, info.TypeName, info.MimeType, info.Comment); - break; - } + { + ResXDataNode node = new ResXDataNode(name, value, this.typeNameConverter); + DataNodeInfo info = node.GetDataNodeInfo(); + AddDataRow(elementName, info.Name, info.ValueData, info.TypeName, info.MimeType, info.Comment); + break; + } } - } + } /// /// Adds a string resource to the resources. @@ -389,7 +430,7 @@ private void AddDataRow(string elementName, string name, string value) value == null ? MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXNullRef), this.typeNameConverter) : null; - AddDataRow(elementName, name, value, typeName, null, null); + AddDataRow(elementName, name, value, typeName, null, null); } /// @@ -397,64 +438,83 @@ private void AddDataRow(string elementName, string name, string value) /// we want to always late bind to the columns for greater flexibility. /// [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] - private void AddDataRow(string elementName, string name, string value, string type, string mimeType, string comment) { + private void AddDataRow(string elementName, string name, string value, string type, string mimeType, string comment) + { if (hasBeenSaved) throw new InvalidOperationException(SR.ResXResourceWriterSaved); - + string alias = null; if (!string.IsNullOrEmpty(type) && elementName == DataStr) { string assemblyName = GetFullName(type); - if(string.IsNullOrEmpty(assemblyName)) { - try { + if (string.IsNullOrEmpty(assemblyName)) + { + try + { Type typeObject = Type.GetType(type); - if(typeObject == typeof(string)) { + if (typeObject == typeof(string)) + { type = null; - } else if(typeObject != null) { + } + else if (typeObject != null) + { assemblyName = GetFullName(MultitargetUtil.GetAssemblyQualifiedName(typeObject, this.typeNameConverter)); alias = GetAliasFromName(new AssemblyName(assemblyName)); } - } catch { } - } else { + catch + { + } + } + else + { alias = GetAliasFromName(new AssemblyName(GetFullName(type))); } //AddAssemblyRow(AssemblyStr, alias, GetFullName(type)); } - - Writer.WriteStartElement(elementName); { + + Writer.WriteStartElement(elementName); + { Writer.WriteAttributeString(NameStr, name); - - if (!string.IsNullOrEmpty(alias) && !string.IsNullOrEmpty(type) && elementName == DataStr) { - // CHANGE: we still output version information. This might have + + if (!string.IsNullOrEmpty(alias) && !string.IsNullOrEmpty(type) && elementName == DataStr) + { + // CHANGE: we still output version information. This might have // to change in 3.2 string typeName = GetTypeName(type); string typeValue = typeName + ", " + alias; Writer.WriteAttributeString(TypeStr, typeValue); } - else { - if (type != null) - { + else + { + if (type != null) + { Writer.WriteAttributeString(TypeStr, type); - } + } } - if (mimeType != null) { + if (mimeType != null) + { Writer.WriteAttributeString(MimeTypeStr, mimeType); } - - if((type == null && mimeType == null) || (type != null && type.StartsWith("System.Char", StringComparison.Ordinal))) { + + if ((type == null && mimeType == null) || (type != null && type.StartsWith("System.Char", StringComparison.Ordinal))) + { Writer.WriteAttributeString("xml", "space", null, "preserve"); } - - Writer.WriteStartElement(ValueStr); { - if(!string.IsNullOrEmpty(value)) { + + Writer.WriteStartElement(ValueStr); + { + if (!string.IsNullOrEmpty(value)) + { Writer.WriteString(value); } } Writer.WriteEndElement(); - if(!string.IsNullOrEmpty(comment)) { - Writer.WriteStartElement(CommentStr); { + if (!string.IsNullOrEmpty(comment)) + { + Writer.WriteStartElement(CommentStr); + { Writer.WriteString(comment); } Writer.WriteEndElement(); @@ -466,12 +526,15 @@ private void AddDataRow(string elementName, string name, string value, string ty private void AddAssemblyRow(string elementName, string alias, string name) { - Writer.WriteStartElement(elementName); { - if (!string.IsNullOrEmpty(alias)) { - Writer.WriteAttributeString(AliasStr, alias); + Writer.WriteStartElement(elementName); + { + if (!string.IsNullOrEmpty(alias)) + { + Writer.WriteAttributeString(AliasStr, alias); } - - if (!string.IsNullOrEmpty(name)) { + + if (!string.IsNullOrEmpty(name)) + { Writer.WriteAttributeString(NameStr, name); } //Writer.WriteEndElement(); @@ -485,11 +548,11 @@ private string GetAliasFromName(AssemblyName assemblyName) { cachedAliases = new Hashtable(); } - string alias = (string)cachedAliases[assemblyName.FullName]; + string alias = (string)cachedAliases[assemblyName.FullName]; if (string.IsNullOrEmpty(alias)) { - alias = assemblyName.Name; - AddAlias(alias, assemblyName); + alias = assemblyName.Name; + AddAlias(alias, assemblyName); AddAssemblyRow(AssemblyStr, alias, assemblyName.FullName); } return alias; @@ -499,57 +562,70 @@ private string GetAliasFromName(AssemblyName assemblyName) /// Closes any files or streams locked by the writer. /// // NOTE: Part of IResourceWriter - not protected by class level LinkDemand. - public void Close() { + public void Close() + { Dispose(); } // NOTE: Part of IDisposable - not protected by class level LinkDemand. - public virtual void Dispose() { + public virtual void Dispose() + { Dispose(true); GC.SuppressFinalize(this); } - protected virtual void Dispose(bool disposing) { - if (disposing) { - if (!hasBeenSaved) { + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + if (!hasBeenSaved) + { Generate(); } - if (xmlTextWriter != null) { + if (xmlTextWriter != null) + { xmlTextWriter.Close(); xmlTextWriter = null; } - if (stream != null) { + if (stream != null) + { stream.Close(); stream = null; } - if (textWriter != null) { + if (textWriter != null) + { textWriter.Close(); textWriter = null; } } } - private string GetTypeName(string typeName) { - int indexStart = typeName.IndexOf(','); - return ((indexStart == -1) ? typeName : typeName.Substring(0, indexStart)); + private string GetTypeName(string typeName) + { + int indexStart = typeName.IndexOf(','); + return ((indexStart == -1) ? typeName : typeName.Substring(0, indexStart)); } - private string GetFullName(string typeName) { - int indexStart = typeName.IndexOf(','); - if(indexStart == -1) + private string GetFullName(string typeName) + { + int indexStart = typeName.IndexOf(','); + if (indexStart == -1) return null; - return typeName.Substring(indexStart + 2); - } + return typeName.Substring(indexStart + 2); + } - static string ToBase64WrappedString(byte[] data) { + static string ToBase64WrappedString(byte[] data) + { const int lineWrap = 80; const string crlf = "\r\n"; const string prefix = " "; string raw = Convert.ToBase64String(data); - if (raw.Length > lineWrap) { + if (raw.Length > lineWrap) + { StringBuilder output = new StringBuilder(raw.Length + (raw.Length / lineWrap) * 3); // word wrap on lineWrap chars, \r\n int current = 0; - for (; current < raw.Length - lineWrap; current+=lineWrap) { + for (; current < raw.Length - lineWrap; current += lineWrap) + { output.Append(crlf); output.Append(prefix); output.Append(raw, current, lineWrap); @@ -560,11 +636,12 @@ static string ToBase64WrappedString(byte[] data) { output.Append(crlf); return output.ToString(); } - + return raw; } - private string TypeNameWithAssembly(Type type) { + private string TypeNameWithAssembly(Type type) + { string result = MultitargetUtil.GetAssemblyQualifiedName(type, this.typeNameConverter); return result; } @@ -573,7 +650,8 @@ private string TypeNameWithAssembly(Type type) { /// Writes the resources out to the file or stream. /// // NOTE: Part of IResourceWriter - not protected by class level LinkDemand. - public void Generate() { + public void Generate() + { if (hasBeenSaved) throw new InvalidOperationException(SR.ResXResourceWriterSaved); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleEvents.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleEvents.cs index 210e8701367..030d9be8886 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleEvents.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleEvents.cs @@ -148,10 +148,10 @@ public enum AccessibleEvents // of the child identified by the VARIANT. In other words, the // child in this case is accessible but not a full object. // Like a button on a titlebar which is 'small' and has no children. - Create = 0x8000, // hwnd + ID + idChild is created item + Create = 0x8000, // hwnd + ID + idChild is created item Destroy = 0x8001, // hwnd + ID + idChild is destroyed item - Show = 0x8002, // hwnd + ID + idChild is shown item - Hide = 0x8003, // hwnd + ID + idChild is hidden item + Show = 0x8002, // hwnd + ID + idChild is shown item + Hide = 0x8003, // hwnd + ID + idChild is hidden item Reorder = 0x8004, // hwnd + ID + idChild is parent of zordering children /// @@ -161,9 +161,9 @@ public enum AccessibleEvents /// but are not truly visible. Hence do not send HIDE notifications for the /// children also. One implies all. The same goes for SHOW. /// - Focus = 0x8005, // hwnd + ID + idChild is focused item - Selection = 0x8006, // hwnd + ID + idChild is selected item (if only one), or idChild is OBJID_WINDOW if complex - SelectionAdd = 0x8007, // hwnd + ID + idChild is item added + Focus = 0x8005, // hwnd + ID + idChild is focused item + Selection = 0x8006, // hwnd + ID + idChild is selected item (if only one), or idChild is OBJID_WINDOW if complex + SelectionAdd = 0x8007, // hwnd + ID + idChild is item added SelectionRemove = 0x8008, // hwnd + ID + idChild is item removed SelectionWithin = 0x8009, // hwnd + ID + idChild is parent of changed selected items @@ -201,14 +201,14 @@ public enum AccessibleEvents /// query the container control what the new bunch of selected items /// are. /// - StateChange = 0x800A, // hwnd + ID + idChild is item w/ state change - LocationChange = 0x800B, // hwnd + ID + idChild is moved/sized item - NameChange = 0x800C, // hwnd + ID + idChild is item w/ name change - DescriptionChange = 0x800D, // hwnd + ID + idChild is item w/ desc change - ValueChange = 0x800E, // hwnd + ID + idChild is item w/ value change - ParentChange = 0x800F, // hwnd + ID + idChild is item w/ new parent - HelpChange = 0x8010, // hwnd + ID + idChild is item w/ help change + StateChange = 0x800A, // hwnd + ID + idChild is item w/ state change + LocationChange = 0x800B, // hwnd + ID + idChild is moved/sized item + NameChange = 0x800C, // hwnd + ID + idChild is item w/ name change + DescriptionChange = 0x800D, // hwnd + ID + idChild is item w/ desc change + ValueChange = 0x800E, // hwnd + ID + idChild is item w/ value change + ParentChange = 0x800F, // hwnd + ID + idChild is item w/ new parent + HelpChange = 0x8010, // hwnd + ID + idChild is item w/ help change DefaultActionChange = 0x8011, // hwnd + ID + idChild is item w/ def action change - AcceleratorChange = 0x8012, // hwnd + ID + idChild is item w/ keybd accel change + AcceleratorChange = 0x8012, // hwnd + ID + idChild is item w/ keybd accel change } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleNavigation.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleNavigation.cs index ff948ae2ee1..1d996b392ed 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleNavigation.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleNavigation.cs @@ -35,19 +35,19 @@ public enum AccessibleNavigation /// object to a sibling object. /// Next = 0x5, - + /// /// Navigation to the previous logical object, generally from a sibling /// object to the starting object. /// Previous = 0x6, - + /// /// Navigation to the sibling object located to the right of the /// starting object. /// Right = 0x4, - + /// /// Navigation to a sibling object located above the starting object. /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleObject.cs index a7ae29b1cee..d09ba604c7a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleObject.cs @@ -206,7 +206,8 @@ public virtual string KeyboardShortcut public virtual string Name { // Does nothing by default - get { + get + { if (systemIAccessible != null) { try @@ -385,7 +386,7 @@ public virtual AccessibleObject GetFocused() if (GetChildCount() >= 0) { int count = GetChildCount(); - for(int index=0; index < count; ++index) + for (int index = 0; index < count; ++index) { AccessibleObject child = GetChild(index); Debug.Assert(child != null, "GetChild(" + index.ToString(CultureInfo.InvariantCulture) + ") returned null!"); @@ -446,7 +447,7 @@ public virtual AccessibleObject GetSelected() if (GetChildCount() >= 0) { int count = GetChildCount(); - for(int index=0; index < count; ++index) + for (int index = 0; index < count; ++index) { AccessibleObject child = GetChild(index); Debug.Assert(child != null, "GetChild(" + index.ToString(CultureInfo.InvariantCulture) + ") returned null!"); @@ -487,7 +488,7 @@ public virtual AccessibleObject HitTest(int x, int y) if (GetChildCount() >= 0) { int count = GetChildCount(); - for(int index=0; index < count; ++index) + for (int index = 0; index < count; ++index) { AccessibleObject child = GetChild(index); Debug.Assert(child != null, "GetChild(" + index.ToString(CultureInfo.InvariantCulture) + ") returned null!"); @@ -835,7 +836,7 @@ int UnsafeNativeMethods.IAccessibleEx.ConvertReturnedElement(object pIn, out obj UnsafeNativeMethods.ProviderOptions UnsafeNativeMethods.IRawElementProviderSimple.ProviderOptions { - get => (UnsafeNativeMethods.ProviderOptions) ProviderOptions; + get => (UnsafeNativeMethods.ProviderOptions)ProviderOptions; } UnsafeNativeMethods.IRawElementProviderSimple UnsafeNativeMethods.IRawElementProviderSimple.HostRawElementProvider @@ -1953,7 +1954,7 @@ public virtual AccessibleObject Navigate(AccessibleNavigation navdir) // Some default behavior for objects with AccessibleObject children if (GetChildCount() >= 0) { - switch(navdir) + switch (navdir) { case AccessibleNavigation.FirstChild: return GetChild(0); @@ -2122,7 +2123,7 @@ private bool SysNavigate(int navDir, object childID, out object retObject) // Perform any supported navigation operation (fall back on system for unsupported navigation ops) AccessibleObject newObject; - if (!GetSysChild((AccessibleNavigation) navDir, out newObject)) + if (!GetSysChild((AccessibleNavigation)navDir, out newObject)) { return false; } @@ -2602,7 +2603,7 @@ private void NextFromChildCollection(int n, IntPtr rgvar, int[] ns, int childCou for (i = 0; i < n && currentChild < childCount; ++i) { ++currentChild; - Marshal.GetNativeVariantForObject(((object) currentChild), GetAddressOfVariantAtIndex(rgvar, i)); + Marshal.GetNativeVariantForObject(((object)currentChild), GetAddressOfVariantAtIndex(rgvar, i)); Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "AccessibleObject.IEV.Next: adding own child " + currentChild + " of " + childCount); } @@ -2641,7 +2642,7 @@ private static bool GotoItem(UnsafeNativeMethods.IEnumVariant iev, int index, In private static IntPtr GetAddressOfVariantAtIndex(IntPtr variantArrayPtr, int index) { int variantSize = 8 + (IntPtr.Size * 2); - return (IntPtr) ((ulong) variantArrayPtr + ((ulong) index) * ((ulong) variantSize)); + return (IntPtr)((ulong)variantArrayPtr + ((ulong)index) * ((ulong)variantSize)); } } @@ -2673,7 +2674,8 @@ internal sealed class InternalAccessibleObject : StandardOleMarshalObject, UnsafeNativeMethods.ILegacyIAccessibleProvider, UnsafeNativeMethods.ISelectionProvider, UnsafeNativeMethods.ISelectionItemProvider, - UnsafeNativeMethods.IRawElementProviderHwndOverride { + UnsafeNativeMethods.IRawElementProviderHwndOverride + { private IAccessible publicIAccessible; // AccessibleObject as IAccessible private UnsafeNativeMethods.IEnumVariant publicIEnumVariant; // AccessibleObject as IEnumVariant @@ -2707,19 +2709,19 @@ internal sealed class InternalAccessibleObject : StandardOleMarshalObject, internal InternalAccessibleObject(AccessibleObject accessibleImplemention) { // Get all the casts done here to catch any issues early - publicIAccessible = (IAccessible) accessibleImplemention; - publicIEnumVariant = (UnsafeNativeMethods.IEnumVariant) accessibleImplemention; - publicIOleWindow = (UnsafeNativeMethods.IOleWindow) accessibleImplemention; - publicIReflect = (IReflect) accessibleImplemention; - publicIServiceProvider = (UnsafeNativeMethods.IServiceProvider) accessibleImplemention; - publicIAccessibleEx = (UnsafeNativeMethods.IAccessibleEx) accessibleImplemention; - publicIRawElementProviderSimple = (UnsafeNativeMethods.IRawElementProviderSimple) accessibleImplemention; + publicIAccessible = (IAccessible)accessibleImplemention; + publicIEnumVariant = (UnsafeNativeMethods.IEnumVariant)accessibleImplemention; + publicIOleWindow = (UnsafeNativeMethods.IOleWindow)accessibleImplemention; + publicIReflect = (IReflect)accessibleImplemention; + publicIServiceProvider = (UnsafeNativeMethods.IServiceProvider)accessibleImplemention; + publicIAccessibleEx = (UnsafeNativeMethods.IAccessibleEx)accessibleImplemention; + publicIRawElementProviderSimple = (UnsafeNativeMethods.IRawElementProviderSimple)accessibleImplemention; publicIRawElementProviderFragment = (UnsafeNativeMethods.IRawElementProviderFragment)accessibleImplemention; publicIRawElementProviderFragmentRoot = (UnsafeNativeMethods.IRawElementProviderFragmentRoot)accessibleImplemention; publicIInvokeProvider = (UnsafeNativeMethods.IInvokeProvider)accessibleImplemention; - publicIValueProvider = (UnsafeNativeMethods.IValueProvider) accessibleImplemention; + publicIValueProvider = (UnsafeNativeMethods.IValueProvider)accessibleImplemention; publicIRangeValueProvider = (UnsafeNativeMethods.IRangeValueProvider)accessibleImplemention; - publicIExpandCollapseProvider = (UnsafeNativeMethods.IExpandCollapseProvider) accessibleImplemention; + publicIExpandCollapseProvider = (UnsafeNativeMethods.IExpandCollapseProvider)accessibleImplemention; publicIToggleProvider = (UnsafeNativeMethods.IToggleProvider)accessibleImplemention; publicITableProvider = (UnsafeNativeMethods.ITableProvider)accessibleImplemention; publicITableItemProvider = (UnsafeNativeMethods.ITableItemProvider)accessibleImplemention; @@ -2840,8 +2842,8 @@ object UnsafeNativeMethods.IAccessibleInternal.get_accParent() object UnsafeNativeMethods.IAccessibleInternal.get_accRole(object childID) { - return publicIAccessible.get_accRole(childID); - } + return publicIAccessible.get_accRole(childID); + } object UnsafeNativeMethods.IAccessibleInternal.get_accSelection() { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleStates.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleStates.cs index 3d7a162144b..4a87a64d071 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleStates.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleStates.cs @@ -18,46 +18,46 @@ public enum AccessibleStates /// /// An unavailable object. /// - Unavailable = 0x1, + Unavailable = 0x1, /// /// A selected object. /// - Selected = 0x2, + Selected = 0x2, /// /// An object with the keyboard focus. /// - Focused = 0x4, + Focused = 0x4, /// /// A pressed object. /// - Pressed = 0x8, + Pressed = 0x8, /// /// An object with a selected check box. /// - Checked = 0x10, + Checked = 0x10, /// /// A three-state check box or toolbar button whose state is indeterminate. /// The check box is neither checked nor unchecked and it is in the third /// or mixed state. /// - Mixed = 0x20, + Mixed = 0x20, /// /// A three-state check box or toolbar button whose state is indeterminate. /// The check box is neither checked nor unchecked and it is in the third /// or mixed state. /// - Indeterminate = Mixed, + Indeterminate = Mixed, /// /// A read-only object. /// - ReadOnly = 0x40, + ReadOnly = 0x40, /// /// The object is hot-tracked by the mouse, meaning its appearance is @@ -68,35 +68,35 @@ public enum AccessibleStates /// /// The default button or menu item. /// - Default = 0x100, + Default = 0x100, /// /// Children of the object that are items in an outline or tree structure /// are displayed. /// - Expanded = 0x200, + Expanded = 0x200, /// /// Children of the object that are items in an outline or tree structure /// are hidden. /// - Collapsed = 0x400, + Collapsed = 0x400, /// /// A control that cannot accept input in its current condition. /// - Busy = 0x800, + Busy = 0x800, /// /// The object is not fixed to the boundary of its parent object, and /// does not move automatically along with the parent. /// - Floating = 0x1000, + Floating = 0x1000, /// /// An object with scrolling or moving text or graphics. /// - Marqueed = 0x2000, + Marqueed = 0x2000, /// /// The object has a rapidly or constantly changing appearance. Graphics @@ -105,28 +105,28 @@ public enum AccessibleStates /// This state should not be used to indicate that the object's location /// is changing. /// - Animated = 0x4000, + Animated = 0x4000, /// /// An object that is currently invisible. /// - Invisible = 0x8000, + Invisible = 0x8000, /// /// No on-screen representation. A sound or alert object would have this /// state, or a hidden window that is never made visible. /// - Offscreen = 0x10000, + Offscreen = 0x10000, /// /// A sizable object. /// - Sizeable = 0x20000, + Sizeable = 0x20000, /// /// A movable object. /// - Moveable = 0x40000, + Moveable = 0x40000, /// /// The object or child can use text-to-speech (TTS) to describe itself. A @@ -134,12 +134,12 @@ public enum AccessibleStates /// object with this state has the focus because the object will /// automatically announce information about itself. /// - SelfVoicing = 0x80000, + SelfVoicing = 0x80000, /// /// The object is on the active window and can receive keyboard focus. /// - Focusable = 0x100000, + Focusable = 0x100000, /// /// An object that can accept selection. @@ -149,17 +149,17 @@ public enum AccessibleStates /// /// A linked object that has not been previously selected. /// - Linked = 0x400000, + Linked = 0x400000, /// /// A linked object that has previously been selected. /// - Traversed = 0x800000, + Traversed = 0x800000, /// /// An object that accepts multiple selected items. /// - MultiSelectable = 0x1000000, + MultiSelectable = 0x1000000, /// /// Alters the selection so that all objects between the selection anchor, @@ -177,12 +177,12 @@ public enum AccessibleStates /// the SHIFT key and clicking an unselected object. /// This flag may not be combined with . /// - ExtSelectable = 0x2000000, + ExtSelectable = 0x2000000, /// /// Low-priority information that may not be important to the user. /// - AlertLow = 0x4000000, + AlertLow = 0x4000000, /// /// Important information that does not need to be conveyed to the user @@ -193,7 +193,7 @@ public enum AccessibleStates /// user's work. The user could then query the alert information at their /// leisure. /// - AlertMedium = 0x8000000, + AlertMedium = 0x8000000, /// /// Important information that should be conveyed to the user immediately. @@ -210,14 +210,14 @@ public enum AccessibleStates /// /// A password-protected edit control. /// - Protected = 0x20000000, + Protected = 0x20000000, /// /// Object displays a pop-up menu or window when invoked. /// - HasPopup = 0x40000000, + HasPopup = 0x40000000, [Obsolete("This enumeration value has been deprecated. There is no replacement. http://go.microsoft.com/fwlink/?linkid=14202")] - Valid = 0x3fffffff, + Valid = 0x3fffffff, } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AmbientProperties.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AmbientProperties.cs index 101a9cd0d4b..5a8b2062bcc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AmbientProperties.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AmbientProperties.cs @@ -12,7 +12,7 @@ namespace System.Windows.Forms /// Control's inherited properties. /// public sealed class AmbientProperties - { + { /// /// Gets the ambient BackColor, or Color.Empty if there is none. /// @@ -27,7 +27,7 @@ public sealed class AmbientProperties /// Gets the ambient Font, or null if there is none. /// public Font Font { get; set; } - + /// /// Gets the ambient ForeColor, or Color.Empty if there is none. /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs index 8bd0e0a052e..0fad31aee88 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Text; using System.Threading; using System.Runtime.InteropServices; @@ -35,7 +36,8 @@ namespace System.Windows.Forms { /// to process Windows messages, and properties to get information about an application. This /// class cannot be inherited. /// - public sealed class Application { + public sealed class Application + { /// /// Hash table for our event list /// @@ -68,7 +70,7 @@ public sealed class Application { /// Events the user can hook into /// private static readonly object EVENT_APPLICATIONEXIT = new object(); - private static readonly object EVENT_THREADEXIT = new object(); + private static readonly object EVENT_THREADEXIT = new object(); // Constant string used in Application.Restart() private const string IEEXEC = "ieexec.exe"; @@ -83,7 +85,8 @@ public sealed class Application { /// /// This class is static, there is no need to ever create it. /// - private Application() { + private Application() + { } /// @@ -94,8 +97,10 @@ private Application() { /// /// /// - public static bool AllowQuit { - get { + public static bool AllowQuit + { + get + { return ThreadContext.FromCurrent().GetAllowQuit(); } } @@ -112,9 +117,12 @@ internal static bool CanContinueIdle } /// Typically, you shouldn't need to use this directly - use RenderWithVisualStyles instead. - internal static bool ComCtlSupportsVisualStyles { - get { - if (!comCtlSupportsVisualStylesInitialized) { + internal static bool ComCtlSupportsVisualStyles + { + get + { + if (!comCtlSupportsVisualStylesInitialized) + { comCtlSupportsVisualStyles = InitializeComCtlSupportsVisualStyles(); comCtlSupportsVisualStylesInitialized = true; } @@ -122,8 +130,10 @@ internal static bool ComCtlSupportsVisualStyles { } } - private static bool InitializeComCtlSupportsVisualStyles() { - if (s_useVisualStyles && OSFeature.Feature.IsPresent(OSFeature.Themes)) { + private static bool InitializeComCtlSupportsVisualStyles() + { + if (s_useVisualStyles && OSFeature.Feature.IsPresent(OSFeature.Themes)) + { //NOTE: At this point, we may not have loaded ComCtl6 yet, but it will eventually // be loaded, so we return true here. This works because UseVisualStyles, once // set, cannot be turned off. If that changes (unlikely), this may not work. @@ -136,16 +146,23 @@ private static bool InitializeComCtlSupportsVisualStyles() { // The GetModuleHandle function returns a handle to a mapped module without incrementing its reference count. IntPtr hModule = UnsafeNativeMethods.GetModuleHandle(ExternDll.Comctl32); - if (hModule != IntPtr.Zero) { - try { + if (hModule != IntPtr.Zero) + { + try + { IntPtr pFunc = UnsafeNativeMethods.GetProcAddress(new HandleRef(null, hModule), "ImageList_WriteEx"); return (pFunc != IntPtr.Zero); - } catch { } - } else { + catch + { + } + } + else + { // Load comctl since GetModuleHandle failed to find it hModule = UnsafeNativeMethods.LoadLibraryFromSystemPathIfAvailable(ExternDll.Comctl32); - if (hModule != IntPtr.Zero) { + if (hModule != IntPtr.Zero) + { IntPtr pFunc = UnsafeNativeMethods.GetProcAddress(new HandleRef(null, hModule), "ImageList_WriteEx"); return (pFunc != IntPtr.Zero); } @@ -157,14 +174,18 @@ private static bool InitializeComCtlSupportsVisualStyles() { /// Gets the registry /// key for the application data that is shared among all users. /// - public static RegistryKey CommonAppDataRegistry { - get { + public static RegistryKey CommonAppDataRegistry + { + get + { return Registry.LocalMachine.CreateSubKey(CommonAppDataRegistryKeyName); } } - internal static string CommonAppDataRegistryKeyName { - get { + internal static string CommonAppDataRegistryKeyName + { + get + { string template = @"Software\{0}\{1}\{2}"; return string.Format(CultureInfo.CurrentCulture, template, CompanyName, @@ -173,27 +194,35 @@ internal static string CommonAppDataRegistryKeyName { } } - internal static bool UseEverettThreadAffinity { - get { - if (!checkedThreadAffinity) { + internal static bool UseEverettThreadAffinity + { + get + { + if (!checkedThreadAffinity) + { checkedThreadAffinity = true; - try { + try + { //We need access to be able to read from the registry here. We're not creating a //registry key, nor are we returning information from the registry to the user. RegistryKey key = Registry.LocalMachine.OpenSubKey(CommonAppDataRegistryKeyName); - if (key != null) { + if (key != null) + { object value = key.GetValue(everettThreadAffinityValue); key.Close(); - if (value != null && (int)value != 0) { + if (value != null && (int)value != 0) + { useEverettThreadAffinity = true; } } } - catch (System.Security.SecurityException) { + catch (System.Security.SecurityException) + { // Can't read the key: use default value (false) } - catch (InvalidCastException) { + catch (InvalidCastException) + { // Key is of wrong type: use default value (false) } } @@ -234,48 +263,62 @@ public static string CommonAppDataPath /// /// Gets the company name associated with the application. /// - public static string CompanyName { - get { - lock(internalSyncObject) { - if (companyName == null) { + public static string CompanyName + { + get + { + lock (internalSyncObject) + { + if (companyName == null) + { // custom attribute // Assembly entryAssembly = Assembly.GetEntryAssembly(); - if (entryAssembly != null) { + if (entryAssembly != null) + { object[] attrs = entryAssembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false); - if (attrs != null && attrs.Length > 0) { + if (attrs != null && attrs.Length > 0) + { companyName = ((AssemblyCompanyAttribute)attrs[0]).Company; } } // win32 version // - if (companyName == null || companyName.Length == 0) { + if (companyName == null || companyName.Length == 0) + { companyName = GetAppFileVersionInfo().CompanyName; - if (companyName != null) { + if (companyName != null) + { companyName = companyName.Trim(); } } // fake it with a namespace // won't work with MC++ see GetAppMainType. - if (companyName == null || companyName.Length == 0) { + if (companyName == null || companyName.Length == 0) + { Type t = GetAppMainType(); - if (t != null) { + if (t != null) + { string ns = t.Namespace; - if (!string.IsNullOrEmpty(ns)){ + if (!string.IsNullOrEmpty(ns)) + { int firstDot = ns.IndexOf('.'); - if( firstDot != -1 ){ + if (firstDot != -1) + { companyName = ns.Substring(0, firstDot); } - else{ + else + { companyName = ns; } } - else { + else + { // last ditch... no namespace, use product name... // companyName = ProductName; @@ -292,11 +335,14 @@ public static string CompanyName { /// Gets /// or sets the locale information for the current thread. /// - public static CultureInfo CurrentCulture { - get { + public static CultureInfo CurrentCulture + { + get + { return Thread.CurrentThread.CurrentCulture; } - set { + set + { Thread.CurrentThread.CurrentCulture = value; } } @@ -305,17 +351,22 @@ public static CultureInfo CurrentCulture { /// Gets or /// sets the current input language for the current thread. /// - public static InputLanguage CurrentInputLanguage { - get { + public static InputLanguage CurrentInputLanguage + { + get + { return InputLanguage.CurrentInputLanguage; } - set { + set + { InputLanguage.CurrentInputLanguage = value; } } - internal static bool CustomThreadExceptionHandlerAttached { - get { + internal static bool CustomThreadExceptionHandlerAttached + { + get + { return ThreadContext.FromCurrent().CustomThreadExceptionHandlerAttached; } } @@ -328,21 +379,29 @@ internal static bool CustomThreadExceptionHandlerAttached { /// /// [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - public static string ExecutablePath { - get { - if (executablePath == null) { + public static string ExecutablePath + { + get + { + if (executablePath == null) + { Assembly asm = Assembly.GetEntryAssembly(); - if (asm == null) { + if (asm == null) + { StringBuilder sb = UnsafeNativeMethods.GetModuleFileNameLongPath(NativeMethods.NullHandleRef); executablePath = Path.GetFullPath(sb.ToString()); } - else { + else + { string cb = asm.CodeBase; Uri codeBase = new Uri(cb); - if (codeBase.IsFile) { - executablePath = codeBase.LocalPath + Uri.UnescapeDataString(codeBase.Fragment); ; + if (codeBase.IsFile) + { + executablePath = codeBase.LocalPath + Uri.UnescapeDataString(codeBase.Fragment); + ; } - else { + else + { executablePath = codeBase.ToString(); } } @@ -413,8 +472,10 @@ public static string LocalUserAppDataPath /// Determines if a message loop exists on this thread. /// /// - public static bool MessageLoop { - get { + public static bool MessageLoop + { + get + { return ThreadContext.FromCurrent().GetMessageLoop(); } } @@ -430,47 +491,61 @@ public static bool MessageLoop { /// the product name associated with this application. /// /// - public static string ProductName { - get { - lock(internalSyncObject) { - if (productName == null) { + public static string ProductName + { + get + { + lock (internalSyncObject) + { + if (productName == null) + { // custom attribute // Assembly entryAssembly = Assembly.GetEntryAssembly(); - if (entryAssembly != null) { + if (entryAssembly != null) + { object[] attrs = entryAssembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false); - if (attrs != null && attrs.Length > 0) { + if (attrs != null && attrs.Length > 0) + { productName = ((AssemblyProductAttribute)attrs[0]).Product; } } // win32 version info // - if (productName == null || productName.Length == 0) { + if (productName == null || productName.Length == 0) + { productName = GetAppFileVersionInfo().ProductName; - if (productName != null) { + if (productName != null) + { productName = productName.Trim(); } } // fake it with namespace // won't work with MC++ see GetAppMainType. - if (productName == null || productName.Length == 0) { + if (productName == null || productName.Length == 0) + { Type t = GetAppMainType(); - if (t != null) { + if (t != null) + { string ns = t.Namespace; - if (!string.IsNullOrEmpty(ns)) { + if (!string.IsNullOrEmpty(ns)) + { int lastDot = ns.LastIndexOf('.'); - if (lastDot != -1 && lastDot < ns.Length - 1) { - productName = ns.Substring(lastDot+1); + if (lastDot != -1 && lastDot < ns.Length - 1) + { + productName = ns.Substring(lastDot + 1); } - else { + else + { productName = ns; } } - else{ + else + { // last ditch... use the main type // productName = t.Name; @@ -490,33 +565,42 @@ public static string ProductName { /// the product version associated with this application. /// /// - public static string ProductVersion { - get { - lock(internalSyncObject) { - if (productVersion == null) { + public static string ProductVersion + { + get + { + lock (internalSyncObject) + { + if (productVersion == null) + { // custom attribute // Assembly entryAssembly = Assembly.GetEntryAssembly(); - if (entryAssembly != null) { + if (entryAssembly != null) + { object[] attrs = entryAssembly.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false); - if (attrs != null && attrs.Length > 0) { + if (attrs != null && attrs.Length > 0) + { productVersion = ((AssemblyInformationalVersionAttribute)attrs[0]).InformationalVersion; } } // win32 version info // - if (productVersion == null || productVersion.Length == 0) { + if (productVersion == null || productVersion.Length == 0) + { productVersion = GetAppFileVersionInfo().ProductVersion; - if (productVersion != null) { + if (productVersion != null) + { productVersion = productVersion.Trim(); } } // fake it // - if (productVersion == null || productVersion.Length == 0) { + if (productVersion == null || productVersion.Length == 0) + { productVersion = "1.0.0.0"; } } @@ -529,17 +613,20 @@ public static string ProductVersion { [ EditorBrowsable(EditorBrowsableState.Advanced) ] - public static void RegisterMessageLoop(MessageLoopCallback callback) { + public static void RegisterMessageLoop(MessageLoopCallback callback) + { ThreadContext.FromCurrent().RegisterMessageLoop(callback); } - + /// /// Magic property that answers a simple question - are my controls currently going to render with // visual styles? If you are doing visual styles rendering, use this to be consistent with the rest // of the controls in your app. /// - public static bool RenderWithVisualStyles { - get { + public static bool RenderWithVisualStyles + { + get + { return (ComCtlSupportsVisualStyles && VisualStyles.VisualStyleRenderer.IsSupported); } } @@ -548,15 +635,20 @@ public static bool RenderWithVisualStyles { /// Gets or sets the format string to apply to top level window captions /// when they are displayed with a warning banner. /// - public static string SafeTopLevelCaptionFormat { - get { - if (safeTopLevelCaptionSuffix == null) { + public static string SafeTopLevelCaptionFormat + { + get + { + if (safeTopLevelCaptionSuffix == null) + { safeTopLevelCaptionSuffix = SR.SafeTopLevelCaptionFormat; // 0 - original, 1 - zone, 2 - site } return safeTopLevelCaptionSuffix; } - set { - if (value == null) value = string.Empty; + set + { + if (value == null) + value = string.Empty; safeTopLevelCaptionSuffix = value; } } @@ -570,9 +662,12 @@ public static string SafeTopLevelCaptionFormat { /// [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - public static string StartupPath { - get { - if (startupPath == null) { + public static string StartupPath + { + get + { + if (startupPath == null) + { // StringBuilder sb = UnsafeNativeMethods.GetModuleFileNameLongPath(NativeMethods.NullHandleRef); // startupPath = Path.GetDirectoryName(sb.ToString()); startupPath = AppContext.BaseDirectory; @@ -585,7 +680,8 @@ public static string StartupPath { [ EditorBrowsable(EditorBrowsableState.Advanced) ] - public static void UnregisterMessageLoop() { + public static void UnregisterMessageLoop() + { ThreadContext.FromCurrent().RegisterMessageLoop(null); } @@ -593,12 +689,15 @@ public static void UnregisterMessageLoop() { /// Gets /// or sets whether the wait cursor is used for all open forms of the application. /// - public static bool UseWaitCursor { - get { + public static bool UseWaitCursor + { + get + { return useWaitCursor; } - set { - lock (FormCollection.CollectionSyncRoot) + set + { + lock (FormCollection.CollectionSyncRoot) { useWaitCursor = value; // Set the WaitCursor of all forms. @@ -644,8 +743,10 @@ public static string UserAppDataPath /// Gets the registry key of /// the application data specific to the roaming user. /// - public static RegistryKey UserAppDataRegistry { - get { + public static RegistryKey UserAppDataRegistry + { + get + { string template = @"Software\{0}\{1}\{2}"; return Registry.CurrentUser.CreateSubKey(string.Format(CultureInfo.CurrentCulture, template, CompanyName, ProductName, ProductVersion)); } @@ -673,21 +774,26 @@ public static RegistryKey UserAppDataRegistry { /// This property can be set only to one of the S.W.F.VisualStyles.VisualStyleState enum values. /// /// - public static VisualStyleState VisualStyleState { - get { - if (!VisualStyleInformation.IsSupportedByOS) { + public static VisualStyleState VisualStyleState + { + get + { + if (!VisualStyleInformation.IsSupportedByOS) + { return VisualStyleState.NoneEnabled; } - VisualStyleState vState = (VisualStyleState) SafeNativeMethods.GetThemeAppProperties(); + VisualStyleState vState = (VisualStyleState)SafeNativeMethods.GetThemeAppProperties(); return vState; } - set { + set + { if (VisualStyleInformation.IsSupportedByOS) - { + { if (!ClientUtils.IsEnumValid(value, (int)value, (int)VisualStyleState.NoneEnabled, (int)VisualStyleState.ClientAndNonClientAreasEnabled) - && LocalAppContextSwitches.EnableVisualStyleValidation) { + && LocalAppContextSwitches.EnableVisualStyleValidation) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(VisualStyleState)); } @@ -706,11 +812,13 @@ public static VisualStyleState VisualStyleState { /// /// This helper broadcasts out a WM_THEMECHANGED to appropriate top level windows of this app. /// - private static bool SendThemeChanged(IntPtr handle, IntPtr extraParameter) { + private static bool SendThemeChanged(IntPtr handle, IntPtr extraParameter) + { int processId; int thisPID = SafeNativeMethods.GetCurrentProcessId(); SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(null, handle), out processId); - if (processId == thisPID && SafeNativeMethods.IsWindowVisible(new HandleRef(null, handle))) { + if (processId == thisPID && SafeNativeMethods.IsWindowVisible(new HandleRef(null, handle))) + { SendThemeChangedRecursive(handle, IntPtr.Zero); SafeNativeMethods.RedrawWindow(new HandleRef(null, handle), @@ -727,7 +835,8 @@ private static bool SendThemeChanged(IntPtr handle, IntPtr extraParameter) { /// This helper broadcasts out a WM_THEMECHANGED this window and all children. /// it is assumed at this point that the handle belongs to the current process and has a visible top level window. /// - private static bool SendThemeChangedRecursive(IntPtr handle, IntPtr lparam) { + private static bool SendThemeChangedRecursive(IntPtr handle, IntPtr lparam) + { //first send to all children... UnsafeNativeMethods.EnumChildWindows(new HandleRef(null, handle), new NativeMethods.EnumChildrenCallback(Application.SendThemeChangedRecursive), @@ -742,22 +851,29 @@ private static bool SendThemeChangedRecursive(IntPtr handle, IntPtr lparam) { /// /// Occurs when the application is about to shut down. /// - public static event EventHandler ApplicationExit { + public static event EventHandler ApplicationExit + { add => AddEventHandler(EVENT_APPLICATIONEXIT, value); remove => RemoveEventHandler(EVENT_APPLICATIONEXIT, value); } - private static void AddEventHandler(object key, Delegate value) { - lock(internalSyncObject) { - if (null == eventHandlers) { + private static void AddEventHandler(object key, Delegate value) + { + lock (internalSyncObject) + { + if (null == eventHandlers) + { eventHandlers = new EventHandlerList(); } eventHandlers.AddHandler(key, value); } } - private static void RemoveEventHandler(object key, Delegate value) { - lock(internalSyncObject) { - if (null == eventHandlers) { + private static void RemoveEventHandler(object key, Delegate value) + { + lock (internalSyncObject) + { + if (null == eventHandlers) + { return; } eventHandlers.RemoveHandler(key, value); @@ -768,35 +884,38 @@ private static void RemoveEventHandler(object key, Delegate value) { /// Adds a message filter to monitor Windows messages as they are routed to their /// destinations. /// - public static void AddMessageFilter(IMessageFilter value) { + public static void AddMessageFilter(IMessageFilter value) + { ThreadContext.FromCurrent().AddMessageFilter(value); } /// /// Processes all message filters for given message /// - [EditorBrowsable(EditorBrowsableState.Advanced), + [EditorBrowsable(EditorBrowsableState.Advanced), SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference") // using ref is OK. ] - public static bool FilterMessage(ref Message message) { + public static bool FilterMessage(ref Message message) + { bool modified; // Create copy of MSG structure - NativeMethods.MSG msg = new NativeMethods.MSG(); + NativeMethods.MSG msg = new NativeMethods.MSG(); msg.hwnd = message.HWnd; msg.message = message.Msg; msg.wParam = message.WParam; msg.lParam = message.LParam; bool processed = ThreadContext.FromCurrent().ProcessFilters(ref msg, out modified); - if (modified) { + if (modified) + { message.HWnd = msg.hwnd; message.Msg = msg.message; message.WParam = msg.wParam; message.LParam = msg.lParam; } - + return processed; } @@ -806,10 +925,13 @@ public static bool FilterMessage(ref Message message) { /// idle state. /// /// - public static event EventHandler Idle { - add { + public static event EventHandler Idle + { + add + { ThreadContext current = ThreadContext.FromCurrent(); - lock(current) { + lock (current) + { current.idleHandler += value; // This just ensures that the component manager is hooked up. We // need it for idle time processing. @@ -817,9 +939,11 @@ public static event EventHandler Idle { object o = current.ComponentManager; } } - remove { + remove + { ThreadContext current = ThreadContext.FromCurrent(); - lock(current) { + lock (current) + { current.idleHandler -= value; } } @@ -831,16 +955,21 @@ public static event EventHandler Idle { /// /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static event EventHandler EnterThreadModal { - add { + public static event EventHandler EnterThreadModal + { + add + { ThreadContext current = ThreadContext.FromCurrent(); - lock(current) { + lock (current) + { current.enterModalHandler += value; } - } - remove { + } + remove + { ThreadContext current = ThreadContext.FromCurrent(); - lock(current) { + lock (current) + { current.enterModalHandler -= value; } } @@ -852,16 +981,21 @@ public static event EventHandler EnterThreadModal { /// /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static event EventHandler LeaveThreadModal { - add { + public static event EventHandler LeaveThreadModal + { + add + { ThreadContext current = ThreadContext.FromCurrent(); - lock(current) { + lock (current) + { current.leaveModalHandler += value; } } - remove { + remove + { ThreadContext current = ThreadContext.FromCurrent(); - lock(current) { + lock (current) + { current.leaveModalHandler -= value; } } @@ -870,16 +1004,21 @@ public static event EventHandler LeaveThreadModal { /// /// Occurs when an untrapped thread exception is thrown. /// - public static event ThreadExceptionEventHandler ThreadException { - add { + public static event ThreadExceptionEventHandler ThreadException + { + add + { ThreadContext current = ThreadContext.FromCurrent(); - lock(current) { + lock (current) + { current.threadExceptionHandler = value; } } - remove { + remove + { ThreadContext current = ThreadContext.FromCurrent(); - lock(current) { + lock (current) + { current.threadExceptionHandler -= value; } } @@ -891,7 +1030,8 @@ public static event ThreadExceptionEventHandler ThreadException { /// this event will be raised first, followed by an ApplicationExit /// event. /// - public static event EventHandler ThreadExit { + public static event EventHandler ThreadExit + { add => AddEventHandler(EVENT_THREADEXIT, value); remove => RemoveEventHandler(EVENT_THREADEXIT, value); } @@ -900,7 +1040,8 @@ public static event EventHandler ThreadExit { /// Called immediately before we begin pumping messages for a modal message loop. /// Does not actually start a message pump; that's the caller's responsibility. /// - internal static void BeginModalMessageLoop() { + internal static void BeginModalMessageLoop() + { ThreadContext.FromCurrent().BeginModalMessageLoop(null); } @@ -908,13 +1049,15 @@ internal static void BeginModalMessageLoop() { /// Processes /// all Windows messages currently in the message queue. /// - public static void DoEvents() { + public static void DoEvents() + { ThreadContext.FromCurrent().RunMessageLoop(NativeMethods.MSOCM.msoloopDoEvents, null); } /// /// - internal static void DoEventsModal() { + internal static void DoEventsModal() + { ThreadContext.FromCurrent().RunMessageLoop(NativeMethods.MSOCM.msoloopDoEventsModal, null); } @@ -938,15 +1081,17 @@ public static void EnableVisualStyles() /// Called immediately after we stop pumping messages for a modal message loop. /// Does not actually end the message pump itself. /// - internal static void EndModalMessageLoop() { + internal static void EndModalMessageLoop() + { ThreadContext.FromCurrent().EndModalMessageLoop(null); } /// /// Overload of Exit that does not care about e.Cancel. /// - public static void Exit() { - Exit(null); + public static void Exit() + { + Exit(null); } /// @@ -958,9 +1103,11 @@ public static void Exit() { EditorBrowsable(EditorBrowsableState.Advanced), SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers") ] - public static void Exit(CancelEventArgs e) { + public static void Exit(CancelEventArgs e) + { bool cancelExit = ExitInternal(); - if (e != null) { + if (e != null) + { e.Cancel = cancelExit; } } @@ -968,10 +1115,13 @@ public static void Exit(CancelEventArgs e) { /// /// Private version of Exit which does not do any security checks. /// - private static bool ExitInternal() { + private static bool ExitInternal() + { bool cancelExit = false; - lock (internalSyncObject) { - if (exiting) { + lock (internalSyncObject) + { + if (exiting) + { return false; } exiting = true; @@ -979,24 +1129,31 @@ private static bool ExitInternal() { try { // Raise the FormClosing and FormClosed events for each open form - if (s_forms != null) { - foreach (Form f in OpenForms) { - if (f.RaiseFormClosingOnAppExit()) { + if (s_forms != null) + { + foreach (Form f in OpenForms) + { + if (f.RaiseFormClosingOnAppExit()) + { cancelExit = true; break; // quit the loop as soon as one form refuses to close } } } - if (!cancelExit) { - if (s_forms != null) { - while (OpenForms.Count > 0) { + if (!cancelExit) + { + if (s_forms != null) + { + while (OpenForms.Count > 0) + { OpenForms[0].RaiseFormClosedOnAppExit(); // OnFormClosed removes the form from the FormCollection } } ThreadContext.ExitApplication(); } } - finally { + finally + { exiting = false; } } @@ -1007,7 +1164,8 @@ private static bool ExitInternal() { /// Exits the message loop on the /// current thread and closes all windows on the thread. /// - public static void ExitThread() { + public static void ExitThread() + { ThreadContext context = ThreadContext.FromCurrent(); if (context.ApplicationContext != null) { @@ -1021,8 +1179,10 @@ public static void ExitThread() { // When a Form receives a WM_ACTIVATE message, it calls this method so we can do the // appropriate MsoComponentManager activation magic - internal static void FormActivated(bool modal, bool activated) { - if (modal) { + internal static void FormActivated(bool modal, bool activated) + { + if (modal) + { return; } @@ -1033,33 +1193,42 @@ internal static void FormActivated(bool modal, bool activated) { /// Retrieves the FileVersionInfo associated with the main module for /// the application. /// - private static FileVersionInfo GetAppFileVersionInfo() { - lock (internalSyncObject) { - if (appFileVersion == null) { + private static FileVersionInfo GetAppFileVersionInfo() + { + lock (internalSyncObject) + { + if (appFileVersion == null) + { Type t = GetAppMainType(); - if (t != null) { + if (t != null) + { appFileVersion = FileVersionInfo.GetVersionInfo(t.Module.FullyQualifiedName); } - else { + else + { appFileVersion = FileVersionInfo.GetVersionInfo(ExecutablePath); } } } - return(FileVersionInfo)appFileVersion; + return (FileVersionInfo)appFileVersion; } /// /// Retrieves the Type that contains the "Main" method. /// - private static Type GetAppMainType() { - lock(internalSyncObject) { - if (mainType == null) { + private static Type GetAppMainType() + { + lock (internalSyncObject) + { + if (mainType == null) + { Assembly exe = Assembly.GetEntryAssembly(); // Get Main type...This doesn't work in MC++ because Main is a global function and not // a class static method (it doesn't belong to a Type). - if (exe != null) { + if (exe != null) + { mainType = exe.EntryPoint.ReflectedType; } } @@ -1071,7 +1240,8 @@ private static Type GetAppMainType() { /// /// Locates a thread context given a window handle. /// - private static ThreadContext GetContextForHandle(HandleRef handle) { + private static ThreadContext GetContextForHandle(HandleRef handle) + { int pid; int id = SafeNativeMethods.GetWindowThreadProcessId(handle, out pid); @@ -1085,16 +1255,19 @@ private static ThreadContext GetContextForHandle(HandleRef handle) { /// basePath + CompanyName + ProducName + ProductVersion. This /// will also create the directory if it doesn't exist. /// - private static string GetDataPath(string basePath) { + private static string GetDataPath(string basePath) + { string template = @"{0}\{1}\{2}\{3}"; string company = CompanyName; string product = ProductName; string version = ProductVersion; - string path = string.Format(CultureInfo.CurrentCulture, template, new object[] {basePath, company, product, version}); - lock(internalSyncObject) { - if (!Directory.Exists(path)) { + string path = string.Format(CultureInfo.CurrentCulture, template, new object[] { basePath, company, product, version }); + lock (internalSyncObject) + { + if (!Directory.Exists(path)) + { Directory.CreateDirectory(path); } } @@ -1105,8 +1278,10 @@ private static string GetDataPath(string basePath) { /// /// Called by the last thread context before it shuts down. /// - private static void RaiseExit() { - if (eventHandlers != null) { + private static void RaiseExit() + { + if (eventHandlers != null) + { Delegate exit = eventHandlers[EVENT_APPLICATIONEXIT]; if (exit != null) ((EventHandler)exit)(null, EventArgs.Empty); @@ -1116,10 +1291,13 @@ private static void RaiseExit() { /// /// Called by the each thread context before it shuts down. /// - private static void RaiseThreadExit() { - if (eventHandlers != null) { + private static void RaiseThreadExit() + { + if (eventHandlers != null) + { Delegate exit = eventHandlers[EVENT_THREADEXIT]; - if (exit != null) { + if (exit != null) + { ((EventHandler)exit)(null, EventArgs.Empty); } } @@ -1130,12 +1308,14 @@ private static void RaiseThreadExit() { /// "Parks" the given HWND to a temporary HWND. This allows WS_CHILD windows to /// be parked. /// - internal static void ParkHandle(HandleRef handle, DpiAwarenessContext dpiAwarenessContext = DpiAwarenessContext.DPI_AWARENESS_CONTEXT_UNSPECIFIED) { + internal static void ParkHandle(HandleRef handle, DpiAwarenessContext dpiAwarenessContext = DpiAwarenessContext.DPI_AWARENESS_CONTEXT_UNSPECIFIED) + { Debug.Assert(UnsafeNativeMethods.IsWindow(handle), "Handle being parked is not a valid window handle"); Debug.Assert(((int)UnsafeNativeMethods.GetWindowLong(handle, NativeMethods.GWL_STYLE) & NativeMethods.WS_CHILD) != 0, "Only WS_CHILD windows should be parked."); ThreadContext cxt = GetContextForHandle(handle); - if (cxt != null) { + if (cxt != null) + { cxt.GetParkingWindow(dpiAwarenessContext).ParkHandle(handle); } } @@ -1145,10 +1325,12 @@ internal static void ParkHandle(HandleRef handle, DpiAwarenessContext dpiAwarene /// /// create params for control handle /// dpi awareness - internal static void ParkHandle(CreateParams cp, DpiAwarenessContext dpiAwarenessContext = DpiAwarenessContext.DPI_AWARENESS_CONTEXT_UNSPECIFIED) { + internal static void ParkHandle(CreateParams cp, DpiAwarenessContext dpiAwarenessContext = DpiAwarenessContext.DPI_AWARENESS_CONTEXT_UNSPECIFIED) + { ThreadContext cxt = ThreadContext.FromCurrent(); - if (cxt != null) { + if (cxt != null) + { cp.Parent = cxt.GetParkingWindow(dpiAwarenessContext).Handle; } } @@ -1158,14 +1340,16 @@ internal static void ParkHandle(CreateParams cp, DpiAwarenessContext dpiAwarenes /// Initializes OLE on the current thread. /// /// - public static System.Threading.ApartmentState OleRequired() { + public static System.Threading.ApartmentState OleRequired() + { return ThreadContext.FromCurrent().OleRequired(); } /// /// Raises the event. /// - public static void OnThreadException(Exception t) { + public static void OnThreadException(Exception t) + { ThreadContext.FromCurrent().OnThreadException(t); } @@ -1173,9 +1357,11 @@ public static void OnThreadException(Exception t) { /// "Unparks" the given HWND to a temporary HWND. This allows WS_CHILD windows to /// be parked. /// - internal static void UnparkHandle(HandleRef handle, DpiAwarenessContext context) { + internal static void UnparkHandle(HandleRef handle, DpiAwarenessContext context) + { ThreadContext cxt = GetContextForHandle(handle); - if (cxt != null) { + if (cxt != null) + { cxt.GetParkingWindow(context).UnparkHandle(handle); } } @@ -1188,9 +1374,11 @@ internal static void UnparkHandle(HandleRef handle, DpiAwarenessContext context) SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers"), SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate") ] - public static void RaiseIdle(EventArgs e) { + public static void RaiseIdle(EventArgs e) + { ThreadContext current = ThreadContext.FromCurrent(); - if (current.idleHandler != null) { + if (current.idleHandler != null) + { current.idleHandler(Thread.CurrentThread, e); } } @@ -1199,7 +1387,8 @@ public static void RaiseIdle(EventArgs e) { /// Removes a message /// filter from the application's message pump. /// - public static void RemoveMessageFilter(IMessageFilter value) { + public static void RemoveMessageFilter(IMessageFilter value) + { ThreadContext.FromCurrent().RemoveMessageFilter(value); } @@ -1282,7 +1471,8 @@ public static void Restart() /// application message loop on the current thread, /// without a form. /// - public static void Run() { + public static void Run() + { ThreadContext.FromCurrent().RunMessageLoop(NativeMethods.MSOCM.msoloopMain, new ApplicationContext()); } @@ -1290,7 +1480,8 @@ public static void Run() { /// Begins running a standard application message loop on the current /// thread, and makes the specified form visible. /// - public static void Run(Form mainForm) { + public static void Run(Form mainForm) + { ThreadContext.FromCurrent().RunMessageLoop(NativeMethods.MSOCM.msoloopMain, new ApplicationContext(mainForm)); } @@ -1300,7 +1491,8 @@ public static void Run(Form mainForm) { /// application message loop on the current thread, /// without a form. /// - public static void Run(ApplicationContext context) { + public static void Run(ApplicationContext context) + { ThreadContext.FromCurrent().RunMessageLoop(NativeMethods.MSOCM.msoloopMain, context); } @@ -1309,7 +1501,8 @@ public static void Run(ApplicationContext context) { /// the dialog has a valid DialogResult. This is called internally by a form /// when an application calls System.Windows.Forms.Form.ShowDialog(). /// - internal static void RunDialog(Form form) { + internal static void RunDialog(Form form) + { ThreadContext.FromCurrent().RunMessageLoop(NativeMethods.MSOCM.msoloopModalForm, new ModalApplicationContext(form)); } @@ -1332,7 +1525,8 @@ public static void SetCompatibleTextRenderingDefault(bool defaultValue) /// Sets the suspend/hibernate state of the machine. /// Returns true if the call succeeded, else false. /// - public static bool SetSuspendState(PowerState state, bool force, bool disableWakeEvent) { + public static bool SetSuspendState(PowerState state, bool force, bool disableWakeEvent) + { return UnsafeNativeMethods.SetSuspendState(state == PowerState.Hibernate, force, disableWakeEvent); } @@ -1364,7 +1558,8 @@ public static void SetUnhandledExceptionMode(UnhandledExceptionMode mode) /// When a thread exception mode isn't UnhandledExceptionMode.Automatic, it takes /// precedence over the application exception mode. /// - public static void SetUnhandledExceptionMode(UnhandledExceptionMode mode, bool threadScope) { + public static void SetUnhandledExceptionMode(UnhandledExceptionMode mode, bool threadScope) + { NativeWindow.SetUnhandledExceptionModeInternal(mode, threadScope); } @@ -1384,7 +1579,8 @@ private class ComponentManager : UnsafeNativeMethods.IMsoComponentManager // ComponentManager instance data. // - private class ComponentHashtableEntry { + private class ComponentHashtableEntry + { public UnsafeNativeMethods.IMsoComponent component; public NativeMethods.MSOCRINFOSTRUCT componentInfo; } @@ -1395,9 +1591,12 @@ private class ComponentHashtableEntry { private UnsafeNativeMethods.IMsoComponent trackingComponent = null; private int currentState = 0; - private Hashtable OleComponents { - get { - if (oleComponents == null) { + private Hashtable OleComponents + { + get + { + if (oleComponents == null) + { oleComponents = new Hashtable(); cookieCounter = 0; } @@ -1415,7 +1614,8 @@ private Hashtable OleComponents { int UnsafeNativeMethods.IMsoComponentManager.QueryService( ref Guid guidService, ref Guid iid, - out object ppvObj) { + out object ppvObj) + { ppvObj = null; return NativeMethods.E_NOINTERFACE; @@ -1432,7 +1632,8 @@ bool UnsafeNativeMethods.IMsoComponentManager.FDebugMessage( IntPtr hInst, int msg, IntPtr wparam, - IntPtr lparam) { + IntPtr lparam) + { return true; } @@ -1446,7 +1647,8 @@ bool UnsafeNativeMethods.IMsoComponentManager.FDebugMessage( /// bool UnsafeNativeMethods.IMsoComponentManager.FRegisterComponent(UnsafeNativeMethods.IMsoComponent component, NativeMethods.MSOCRINFOSTRUCT pcrinfo, - out IntPtr dwComponentID) { + out IntPtr dwComponentID) + { // Construct Hashtable entry for this component // @@ -1467,21 +1669,25 @@ bool UnsafeNativeMethods.IMsoComponentManager.FRegisterComponent(UnsafeNativeMet /// (the cookie returned from the FRegisterComponent method). /// Return TRUE if successful, FALSE otherwise. /// - bool UnsafeNativeMethods.IMsoComponentManager.FRevokeComponent(IntPtr dwComponentID) { + bool UnsafeNativeMethods.IMsoComponentManager.FRevokeComponent(IntPtr dwComponentID) + { int dwLocalComponentID = unchecked((int)(long)dwComponentID); Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ComponentManager: Revoking component " + dwLocalComponentID.ToString(CultureInfo.InvariantCulture)); ComponentHashtableEntry entry = (ComponentHashtableEntry)OleComponents[dwLocalComponentID]; - if (entry == null) { + if (entry == null) + { Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "Compoenent not registered."); return false; } - if (entry.component == activeComponent) { + if (entry.component == activeComponent) + { activeComponent = null; } - if (entry.component == trackingComponent) { + if (entry.component == trackingComponent) + { trackingComponent = null; } @@ -1502,12 +1708,14 @@ bool UnsafeNativeMethods.IMsoComponentManager.FRevokeComponent(IntPtr dwComponen bool UnsafeNativeMethods.IMsoComponentManager.FUpdateComponentRegistration( IntPtr dwComponentID, NativeMethods.MSOCRINFOSTRUCT info - ) { + ) + { int dwLocalComponentID = unchecked((int)(long)dwComponentID); // Update the registration info // ComponentHashtableEntry entry = (ComponentHashtableEntry)OleComponents[dwLocalComponentID]; - if (entry == null) { + if (entry == null) + { return false; } @@ -1528,13 +1736,15 @@ NativeMethods.MSOCRINFOSTRUCT info /// in this case). /// Return TRUE if successful. /// - bool UnsafeNativeMethods.IMsoComponentManager.FOnComponentActivate(IntPtr dwComponentID) { + bool UnsafeNativeMethods.IMsoComponentManager.FOnComponentActivate(IntPtr dwComponentID) + { int dwLocalComponentID = unchecked((int)(long)dwComponentID); Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ComponentManager: Component activated. ID: " + dwLocalComponentID.ToString(CultureInfo.InvariantCulture)); ComponentHashtableEntry entry = (ComponentHashtableEntry)OleComponents[dwLocalComponentID]; - if (entry == null) { + if (entry == null) + { Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "*** Component not registered ***"); return false; } @@ -1561,22 +1771,27 @@ bool UnsafeNativeMethods.IMsoComponentManager.FOnComponentActivate(IntPtr dwComp /// Note: there can only be one tracking component at a time. /// Return TRUE if successful, FALSE otherwise. /// - bool UnsafeNativeMethods.IMsoComponentManager.FSetTrackingComponent(IntPtr dwComponentID, bool fTrack) { + bool UnsafeNativeMethods.IMsoComponentManager.FSetTrackingComponent(IntPtr dwComponentID, bool fTrack) + { int dwLocalComponentID = unchecked((int)(long)dwComponentID); ComponentHashtableEntry entry = (ComponentHashtableEntry)OleComponents[dwLocalComponentID]; - if (entry == null) { + if (entry == null) + { return false; } - if (entry.component == trackingComponent ^ fTrack) { + if (entry.component == trackingComponent ^ fTrack) + { return false; } - if (fTrack) { + if (fTrack) + { trackingComponent = entry.component; } - else { + else + { trackingComponent = null; } @@ -1624,20 +1839,23 @@ void UnsafeNativeMethods.IMsoComponentManager.OnComponentEnterState( int uContext, int cpicmExclude, int rgpicmExclude, // IMsoComponentManger** - int dwReserved) { + int dwReserved) + { int dwLocalComponentID = unchecked((int)(long)dwComponentID); currentState |= uStateID; Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ComponentManager: Component enter state. ID: " + dwLocalComponentID.ToString(CultureInfo.InvariantCulture) + " state: " + uStateID.ToString(CultureInfo.InvariantCulture)); - if (uContext == NativeMethods.MSOCM.msoccontextAll || uContext == NativeMethods.MSOCM.msoccontextMine) { + if (uContext == NativeMethods.MSOCM.msoccontextAll || uContext == NativeMethods.MSOCM.msoccontextMine) + { Debug.Indent(); // We should notify all components we contain that the state has changed. // - foreach (ComponentHashtableEntry entry in OleComponents.Values) { + foreach (ComponentHashtableEntry entry in OleComponents.Values) + { Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "Notifying " + entry.component.ToString()); entry.component.OnEnterState(uStateID, true); } @@ -1674,19 +1892,22 @@ bool UnsafeNativeMethods.IMsoComponentManager.FOnComponentExitState( int uContext, int cpicmExclude, int rgpicmExclude // IMsoComponentManager** - ) { + ) + { int dwLocalComponentID = unchecked((int)(long)dwComponentID); currentState &= ~uStateID; Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ComponentManager: Component exit state. ID: " + dwLocalComponentID.ToString(CultureInfo.InvariantCulture) + " state: " + uStateID.ToString(CultureInfo.InvariantCulture)); - if (uContext == NativeMethods.MSOCM.msoccontextAll || uContext == NativeMethods.MSOCM.msoccontextMine) { + if (uContext == NativeMethods.MSOCM.msoccontextAll || uContext == NativeMethods.MSOCM.msoccontextMine) + { Debug.Indent(); // We should notify all components we contain that the state has changed. // - foreach (ComponentHashtableEntry entry in OleComponents.Values) { + foreach (ComponentHashtableEntry entry in OleComponents.Values) + { Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "Notifying " + entry.component.ToString()); entry.component.OnEnterState(uStateID, false); } @@ -1703,8 +1924,9 @@ int rgpicmExclude // IMsoComponentManager** /// FALSE otherwise (see "Comments on State Contexts", above). /// pvoid is reserved for future use and should be NULL. /// - bool UnsafeNativeMethods.IMsoComponentManager.FInState(int uStateID, IntPtr pvoid) { - return(currentState & uStateID) != 0; + bool UnsafeNativeMethods.IMsoComponentManager.FInState(int uStateID, IntPtr pvoid) + { + return (currentState & uStateID) != 0; } /// @@ -1712,7 +1934,8 @@ bool UnsafeNativeMethods.IMsoComponentManager.FInState(int uStateID, IntPtr pvoi /// Return TRUE if component can continue its idle time processing, /// FALSE if not (in which case component returns from FDoIdle.) /// - bool UnsafeNativeMethods.IMsoComponentManager.FContinueIdle() { + bool UnsafeNativeMethods.IMsoComponentManager.FContinueIdle() + { // Essentially, if we have a message on queue, then don't continue // idle processing. @@ -1741,7 +1964,8 @@ bool UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop( IntPtr dwComponentID, int reason, int pvLoopData // PVOID - ) { + ) + { int dwLocalComponentID = unchecked((int)(long)dwComponentID); // Hold onto old state to allow restore before we exit... @@ -1749,22 +1973,25 @@ int pvLoopData // PVOID int currentLoopState = currentState; bool continueLoop = true; - if (!OleComponents.ContainsKey(dwLocalComponentID)) { + if (!OleComponents.ContainsKey(dwLocalComponentID)) + { return false; } UnsafeNativeMethods.IMsoComponent prevActive = this.activeComponent; - try { + try + { // Execute the message loop until the active component tells us to stop. // NativeMethods.MSG msg = new NativeMethods.MSG(); - NativeMethods.MSG[] rgmsg = new NativeMethods.MSG[] {msg}; + NativeMethods.MSG[] rgmsg = new NativeMethods.MSG[] { msg }; bool unicodeWindow = false; UnsafeNativeMethods.IMsoComponent requestingComponent; ComponentHashtableEntry entry = (ComponentHashtableEntry)OleComponents[dwLocalComponentID]; - if (entry == null) { + if (entry == null) + { return false; } @@ -1775,25 +2002,30 @@ int pvLoopData // PVOID Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ComponentManager : Pushing message loop " + reason.ToString(CultureInfo.InvariantCulture)); Debug.Indent(); - while (continueLoop) { + while (continueLoop) + { // Determine the component to route the message to // UnsafeNativeMethods.IMsoComponent component; - if (trackingComponent != null) { + if (trackingComponent != null) + { component = trackingComponent; } - else if (activeComponent != null) { + else if (activeComponent != null) + { component = activeComponent; } - else { + else + { component = requestingComponent; } bool peeked = UnsafeNativeMethods.PeekMessage(ref msg, NativeMethods.NullHandleRef, 0, 0, NativeMethods.PM_NOREMOVE); - if (peeked) { + if (peeked) + { rgmsg[0] = msg; continueLoop = component.FContinueMessageLoop(reason, pvLoopData, rgmsg); @@ -1802,22 +2034,27 @@ int pvLoopData // PVOID // The component manager hosts windows from many places. We must be sensitive // to ansi / Unicode windows here. // - if (continueLoop) { - if (msg.hwnd != IntPtr.Zero && SafeNativeMethods.IsWindowUnicode(new HandleRef(null, msg.hwnd))) { + if (continueLoop) + { + if (msg.hwnd != IntPtr.Zero && SafeNativeMethods.IsWindowUnicode(new HandleRef(null, msg.hwnd))) + { unicodeWindow = true; UnsafeNativeMethods.GetMessageW(ref msg, NativeMethods.NullHandleRef, 0, 0); } - else { + else + { unicodeWindow = false; UnsafeNativeMethods.GetMessageA(ref msg, NativeMethods.NullHandleRef, 0, 0); } - if (msg.message == Interop.WindowMessages.WM_QUIT) { + if (msg.message == Interop.WindowMessages.WM_QUIT) + { Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ComponentManager : Normal message loop termination"); Application.ThreadContext.FromCurrent().DisposeThreadWindows(); - if (reason != NativeMethods.MSOCM.msoloopMain) { + if (reason != NativeMethods.MSOCM.msoloopMain) + { UnsafeNativeMethods.PostQuitMessage((int)msg.wParam); } @@ -1830,24 +2067,29 @@ int pvLoopData // PVOID // Reading through the rather sparse documentation, // it seems we should only call FPreTranslateMessage // on the active component. - if (!component.FPreTranslateMessage(ref msg)) { + if (!component.FPreTranslateMessage(ref msg)) + { UnsafeNativeMethods.TranslateMessage(ref msg); - if (unicodeWindow) { + if (unicodeWindow) + { UnsafeNativeMethods.DispatchMessageW(ref msg); } - else { + else + { UnsafeNativeMethods.DispatchMessageA(ref msg); } } } } - else { + else + { // If this is a DoEvents loop, then get out. There's nothing left // for us to do. // if (reason == NativeMethods.MSOCM.msoloopDoEvents || - reason == NativeMethods.MSOCM.msoloopDoEventsModal) { + reason == NativeMethods.MSOCM.msoloopDoEventsModal) + { break; } @@ -1856,10 +2098,12 @@ int pvLoopData // PVOID // bool continueIdle = false; - if (OleComponents != null) { + if (OleComponents != null) + { IEnumerator enumerator = OleComponents.Values.GetEnumerator(); - while (enumerator.MoveNext()) { + while (enumerator.MoveNext()) + { ComponentHashtableEntry idleEntry = (ComponentHashtableEntry)enumerator.Current; continueIdle |= idleEntry.component.FDoIdle(-1); } @@ -1870,8 +2114,10 @@ int pvLoopData // PVOID // continueLoop = component.FContinueMessageLoop(reason, pvLoopData, null); - if (continueLoop) { - if (continueIdle) { + if (continueLoop) + { + if (continueIdle) + { // If someone has asked for idle time, give it to them. However, // don't cycle immediately; wait up to 100ms. Why? Because we don't // want someone to attach to idle, forget to detach, and then cause @@ -1879,7 +2125,8 @@ int pvLoopData // PVOID // our component always returns false from its idle request UnsafeNativeMethods.MsgWaitForMultipleObjectsEx(0, IntPtr.Zero, 100, NativeMethods.QS_ALLINPUT, NativeMethods.MWMO_INPUTAVAILABLE); } - else { + else + { // We should call GetMessage here, but we cannot because // the component manager requires that we notify the // active component before we pull the message off the @@ -1889,7 +2136,8 @@ int pvLoopData // PVOID // would wait for the next message. We minimize this here // by calling PeekMessage. // - if (!UnsafeNativeMethods.PeekMessage(ref msg, NativeMethods.NullHandleRef, 0, 0, NativeMethods.PM_NOREMOVE)) { + if (!UnsafeNativeMethods.PeekMessage(ref msg, NativeMethods.NullHandleRef, 0, 0, NativeMethods.PM_NOREMOVE)) + { UnsafeNativeMethods.WaitMessage(); } } @@ -1900,7 +2148,8 @@ int pvLoopData // PVOID Debug.Unindent(); Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ComponentManager : message loop " + reason.ToString(CultureInfo.InvariantCulture) + " complete."); } - finally { + finally + { currentState = currentLoopState; this.activeComponent = prevActive; } @@ -1925,7 +2174,8 @@ bool UnsafeNativeMethods.IMsoComponentManager.FCreateSubComponentManager( object punkOuter, object punkServProv, ref Guid riid, - out IntPtr ppvObj) { + out IntPtr ppvObj) + { // We do not support sub component managers. // @@ -1940,7 +2190,8 @@ bool UnsafeNativeMethods.IMsoComponentManager.FCreateSubComponentManager( /// Returns TRUE if the parent is returned, FALSE if no parent exists or /// some error occurred. /// - bool UnsafeNativeMethods.IMsoComponentManager.FGetParentComponentManager(out UnsafeNativeMethods.IMsoComponentManager ppicm) { + bool UnsafeNativeMethods.IMsoComponentManager.FGetParentComponentManager(out UnsafeNativeMethods.IMsoComponentManager ppicm) + { ppicm = null; return false; } @@ -1959,34 +2210,45 @@ bool UnsafeNativeMethods.IMsoComponentManager.FGetActiveComponent( int dwgac, UnsafeNativeMethods.IMsoComponent[] ppic, NativeMethods.MSOCRINFOSTRUCT info, - int dwReserved) { + int dwReserved) + { UnsafeNativeMethods.IMsoComponent component = null; - if (dwgac == NativeMethods.MSOCM.msogacActive) { + if (dwgac == NativeMethods.MSOCM.msogacActive) + { component = activeComponent; } - else if (dwgac == NativeMethods.MSOCM.msogacTracking) { + else if (dwgac == NativeMethods.MSOCM.msogacTracking) + { component = trackingComponent; } - else if (dwgac == NativeMethods.MSOCM.msogacTrackingOrActive) { - if (trackingComponent != null) { + else if (dwgac == NativeMethods.MSOCM.msogacTrackingOrActive) + { + if (trackingComponent != null) + { component = trackingComponent; } - else { + else + { component = activeComponent; } } - else { + else + { Debug.Fail("Unknown dwgac in FGetActiveComponent"); } - if (ppic != null) { + if (ppic != null) + { ppic[0] = component; } - if (info != null && component != null) { - foreach(ComponentHashtableEntry entry in OleComponents.Values) { - if (entry.component == component) { + if (info != null && component != null) + { + foreach (ComponentHashtableEntry entry in OleComponents.Values) + { + if (entry.component == component) + { info = entry.componentInfo; break; } @@ -2002,51 +2264,52 @@ bool UnsafeNativeMethods.IMsoComponentManager.FGetActiveComponent( /// TLS is really just an unfortunate artifact of using Win 32. We want the world to be free /// threaded. /// - internal sealed class ThreadContext : MarshalByRefObject, UnsafeNativeMethods.IMsoComponent { + internal sealed class ThreadContext : MarshalByRefObject, UnsafeNativeMethods.IMsoComponent + { - private const int STATE_OLEINITIALIZED = 0x00000001; - private const int STATE_EXTERNALOLEINIT = 0x00000002; - private const int STATE_INTHREADEXCEPTION = 0x00000004; - private const int STATE_POSTEDQUIT = 0x00000008; - private const int STATE_FILTERSNAPSHOTVALID = 0x00000010; - private const int STATE_TRACKINGCOMPONENT = 0x00000020; + private const int STATE_OLEINITIALIZED = 0x00000001; + private const int STATE_EXTERNALOLEINIT = 0x00000002; + private const int STATE_INTHREADEXCEPTION = 0x00000004; + private const int STATE_POSTEDQUIT = 0x00000008; + private const int STATE_FILTERSNAPSHOTVALID = 0x00000010; + private const int STATE_TRACKINGCOMPONENT = 0x00000020; private const int INVALID_ID = unchecked((int)0xFFFFFFFF); - private static Hashtable contextHash = new Hashtable(); + private static Hashtable contextHash = new Hashtable(); // When this gets to zero, we'll invoke a full garbage // collect and check for root/window leaks. // - private static object tcInternalSyncObject = new object(); + private static object tcInternalSyncObject = new object(); - private static int totalMessageLoopCount; - private static int baseLoopReason; + private static int totalMessageLoopCount; + private static int baseLoopReason; - [ ThreadStatic ] - private static ThreadContext currentThreadContext; + [ThreadStatic] + private static ThreadContext currentThreadContext; internal ThreadExceptionEventHandler threadExceptionHandler; - internal EventHandler idleHandler; - internal EventHandler enterModalHandler; - internal EventHandler leaveModalHandler; - private ApplicationContext applicationContext; + internal EventHandler idleHandler; + internal EventHandler enterModalHandler; + internal EventHandler leaveModalHandler; + private ApplicationContext applicationContext; // Parking window list private List parkingWindows = new List(); - private Control marshalingControl; - private CultureInfo culture; - private List messageFilters; - private List messageFilterSnapshot; - private int inProcessFilters = 0; - private IntPtr handle; - private int id; - private int messageLoopCount; - private int threadState; - private int modalCount; + private Control marshalingControl; + private CultureInfo culture; + private List messageFilters; + private List messageFilterSnapshot; + private int inProcessFilters = 0; + private IntPtr handle; + private int id; + private int messageLoopCount; + private int threadState; + private int modalCount; // used for correct restoration of focus after modality - private WeakReference activatingControlRef; - + private WeakReference activatingControlRef; + // IMsoComponentManager stuff // private UnsafeNativeMethods.IMsoComponentManager componentManager; @@ -2075,7 +2338,8 @@ [ ThreadStatic ] /// /// Creates a new thread context object. /// - public ThreadContext() { + public ThreadContext() + { IntPtr address = IntPtr.Zero; UnsafeNativeMethods.DuplicateHandle(new HandleRef(null, SafeNativeMethods.GetCurrentProcess()), new HandleRef(null, SafeNativeMethods.GetCurrentThread()), @@ -2083,15 +2347,17 @@ public ThreadContext() { NativeMethods.DUPLICATE_SAME_ACCESS); handle = address; - + id = SafeNativeMethods.GetCurrentThreadId(); messageLoopCount = 0; currentThreadContext = this; contextHash[id] = this; } - public ApplicationContext ApplicationContext { - get { + public ApplicationContext ApplicationContext + { + get + { return applicationContext; } } @@ -2100,12 +2366,15 @@ public ApplicationContext ApplicationContext { /// Retrieves the component manager for this process. If there is no component manager /// currently installed, we install our own. /// - internal UnsafeNativeMethods.IMsoComponentManager ComponentManager { - get { + internal UnsafeNativeMethods.IMsoComponentManager ComponentManager + { + get + { Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "Application.ComponentManager.Get:"); - if (componentManager == null) { + if (componentManager == null) + { // The CLR is a good COM citizen and will pump messages when things are waiting. // This is nice; it keeps the world responsive. But, it is also very hard for @@ -2115,12 +2384,14 @@ internal UnsafeNativeMethods.IMsoComponentManager ComponentManager { // later on as we come out of the recursion. So, we guard it here and return // null. EVERYONE who accesses the component manager must handle a NULL return! // - if (fetchingComponentManager) { + if (fetchingComponentManager) + { return null; } fetchingComponentManager = true; - try { + try + { UnsafeNativeMethods.IMsoComponentManager msocm = null; Application.OleRequired(); @@ -2128,7 +2399,8 @@ internal UnsafeNativeMethods.IMsoComponentManager ComponentManager { // IntPtr msgFilterPtr = (IntPtr)0; - if (NativeMethods.Succeeded(UnsafeNativeMethods.CoRegisterMessageFilter(NativeMethods.NullHandleRef, ref msgFilterPtr)) && msgFilterPtr != (IntPtr)0) { + if (NativeMethods.Succeeded(UnsafeNativeMethods.CoRegisterMessageFilter(NativeMethods.NullHandleRef, ref msgFilterPtr)) && msgFilterPtr != (IntPtr)0) + { IntPtr dummy = (IntPtr)0; UnsafeNativeMethods.CoRegisterMessageFilter(new HandleRef(null, msgFilterPtr), ref dummy); @@ -2137,8 +2409,10 @@ internal UnsafeNativeMethods.IMsoComponentManager ComponentManager { Marshal.Release(msgFilterPtr); UnsafeNativeMethods.IOleServiceProvider sp = msgFilterObj as UnsafeNativeMethods.IOleServiceProvider; - if (sp != null) { - try { + if (sp != null) + { + try + { IntPtr retval = IntPtr.Zero; // Using typeof() of COM object spins up COM at JIT time. @@ -2151,40 +2425,48 @@ internal UnsafeNativeMethods.IMsoComponentManager ComponentManager { ref iid, out retval); - if (NativeMethods.Succeeded(hr) && retval != IntPtr.Zero) { + if (NativeMethods.Succeeded(hr) && retval != IntPtr.Zero) + { // Now query for hte message filter. IntPtr pmsocm; - try { + try + { Guid IID_IMsoComponentManager = typeof(UnsafeNativeMethods.IMsoComponentManager).GUID; hr = Marshal.QueryInterface(retval, ref IID_IMsoComponentManager, out pmsocm); } - finally { + finally + { Marshal.Release(retval); } - if (NativeMethods.Succeeded(hr) && pmsocm != IntPtr.Zero) { + if (NativeMethods.Succeeded(hr) && pmsocm != IntPtr.Zero) + { // Ok, we have a native component manager. Hand this over to // our broker object to get a proxy we can use - try { + try + { msocm = ComponentManagerBroker.GetComponentManager(pmsocm); } - finally { + finally + { Marshal.Release(pmsocm); } } - if (msocm != null) { + if (msocm != null) + { // If the resulting service is the same pUnk as the // message filter (a common implementation technique), // then we want to null msgFilterObj at this point so // we don't call RelaseComObject on it below. That would // also release the RCW for the component manager pointer. - if (msgFilterPtr == retval) { + if (msgFilterPtr == retval) + { msgFilterObj = null; } @@ -2199,18 +2481,21 @@ internal UnsafeNativeMethods.IMsoComponentManager ComponentManager { } } } - catch { + catch + { } } - if (msgFilterObj != null && Marshal.IsComObject(msgFilterObj)) { + if (msgFilterObj != null && Marshal.IsComObject(msgFilterObj)) + { Marshal.ReleaseComObject(msgFilterObj); } } // Otherwise, we implement component manager ourselves // - if (msocm == null) { + if (msocm == null) + { msocm = new ComponentManager(); externalComponentManager = false; @@ -2220,7 +2505,8 @@ internal UnsafeNativeMethods.IMsoComponentManager ComponentManager { Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "Using our own component manager"); } - if (msocm != null && componentID == INVALID_ID) { + if (msocm != null && componentID == INVALID_ID) + { // Finally, if we got a compnent manager, register ourselves with it. // Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "Registering MSO component with the component manager"); @@ -2235,7 +2521,8 @@ internal UnsafeNativeMethods.IMsoComponentManager ComponentManager { componentID = unchecked((int)(long)localComponentID); Debug.Assert(componentID != INVALID_ID, "Our ID sentinel was returned as a valid ID"); - if (result && !(msocm is ComponentManager)) { + if (result && !(msocm is ComponentManager)) + { messageLoopCount++; } @@ -2245,7 +2532,8 @@ internal UnsafeNativeMethods.IMsoComponentManager ComponentManager { componentManager = msocm; } } - finally { + finally + { fetchingComponentManager = false; } } @@ -2254,9 +2542,11 @@ internal UnsafeNativeMethods.IMsoComponentManager ComponentManager { } } - internal bool CustomThreadExceptionHandlerAttached { - get { - return threadExceptionHandler != null; + internal bool CustomThreadExceptionHandlerAttached + { + get + { + return threadExceptionHandler != null; } } @@ -2264,20 +2554,25 @@ internal bool CustomThreadExceptionHandlerAttached { /// Retrieves the actual parking form. This will demand create the parking window /// if it needs to. /// - internal ParkingWindow GetParkingWindow(DpiAwarenessContext context) { + internal ParkingWindow GetParkingWindow(DpiAwarenessContext context) + { // Locking 'this' here is ok since this is an internal class. - lock(this) { + lock (this) + { var parkingWindow = GetParkingWindowForContext(context); - if (parkingWindow == null) { + if (parkingWindow == null) + { #if DEBUG - if (CoreSwitches.PerfTrack.Enabled) { + if (CoreSwitches.PerfTrack.Enabled) + { Debug.WriteLine("Creating parking form!"); Debug.WriteLine(CoreSwitches.PerfTrack.Enabled, Environment.StackTrace); } #endif - using (DpiHelper.EnterDpiAwarenessScope(context)) { + using (DpiHelper.EnterDpiAwarenessScope(context)) + { parkingWindow = new ParkingWindow(); } @@ -2291,24 +2586,29 @@ internal ParkingWindow GetParkingWindow(DpiAwarenessContext context) { /// Returns parking window that matches dpi awareness context. return null if not found. /// /// return matching parking window from list. returns null if not found - internal ParkingWindow GetParkingWindowForContext(DpiAwarenessContext context) { + internal ParkingWindow GetParkingWindowForContext(DpiAwarenessContext context) + { - if (parkingWindows.Count == 0) { + if (parkingWindows.Count == 0) + { return null; } // Legacy OS/target framework scenario where ControlDpiContext is set to DPI_AWARENESS_CONTEXT.DPI_AWARENESS_CONTEXT_UNSPECIFIED // because of 'ThreadContextDpiAwareness' API unavailability or this feature is not enabled. - if (!DpiHelper.IsScalingRequirementMet || CommonUnsafeNativeMethods.TryFindDpiAwarenessContextsEqual(context, DpiAwarenessContext.DPI_AWARENESS_CONTEXT_UNSPECIFIED)) { + if (!DpiHelper.IsScalingRequirementMet || CommonUnsafeNativeMethods.TryFindDpiAwarenessContextsEqual(context, DpiAwarenessContext.DPI_AWARENESS_CONTEXT_UNSPECIFIED)) + { Debug.Assert(parkingWindows.Count == 1, "parkingWindows count can not be > 1 for legacy OS/target framework versions"); return parkingWindows[0]; } // Supported OS scenario. - foreach (var p in parkingWindows) { - if (CommonUnsafeNativeMethods.TryFindDpiAwarenessContextsEqual(p.DpiAwarenessContext, context)) { + foreach (var p in parkingWindows) + { + if (CommonUnsafeNativeMethods.TryFindDpiAwarenessContextsEqual(p.DpiAwarenessContext, context)) + { return p; } } @@ -2317,18 +2617,24 @@ internal ParkingWindow GetParkingWindowForContext(DpiAwarenessContext context) { return null; } - internal Control ActivatingControl { - get { - if ((activatingControlRef != null) && (activatingControlRef.IsAlive)) { + internal Control ActivatingControl + { + get + { + if ((activatingControlRef != null) && (activatingControlRef.IsAlive)) + { return activatingControlRef.Target as Control; } return null; } - set { - if (value != null) { + set + { + if (value != null) + { activatingControlRef = new WeakReference(value); } - else { + else + { activatingControlRef = null; } } @@ -2339,12 +2645,17 @@ internal Control ActivatingControl { /// Retrieves the actual parking form. This will demand create the MarshalingControl window /// if it needs to. /// - internal Control MarshalingControl { - get { - lock (this) { - if (marshalingControl == null) { + internal Control MarshalingControl + { + get + { + lock (this) + { + if (marshalingControl == null) + { #if DEBUG - if (CoreSwitches.PerfTrack.Enabled) { + if (CoreSwitches.PerfTrack.Enabled) + { Debug.WriteLine("Creating marshalling control!"); Debug.WriteLine(CoreSwitches.PerfTrack.Enabled, Environment.StackTrace); } @@ -2361,27 +2672,34 @@ internal Control MarshalingControl { /// Allows you to setup a message filter for the application's message pump. This /// installs the filter on the current thread. /// - internal void AddMessageFilter(IMessageFilter f) { - if (messageFilters == null) { + internal void AddMessageFilter(IMessageFilter f) + { + if (messageFilters == null) + { messageFilters = new List(); } - if (messageFilterSnapshot == null) { + if (messageFilterSnapshot == null) + { messageFilterSnapshot = new List(); } - if (f != null) { + if (f != null) + { SetState(STATE_FILTERSNAPSHOTVALID, false); - if (messageFilters.Count > 0 && f is IMessageModifyAndFilter) { + if (messageFilters.Count > 0 && f is IMessageModifyAndFilter) + { // insert the IMessageModifyAndFilter filters first messageFilters.Insert(0, f); } - else { + else + { messageFilters.Add(f); } } } // Called immediately before we begin pumping messages for a modal message loop. - internal void BeginModalMessageLoop(ApplicationContext context) { + internal void BeginModalMessageLoop(ApplicationContext context) + { #if DEBUG debugModalCounter++; #endif @@ -2391,7 +2709,8 @@ internal void BeginModalMessageLoop(ApplicationContext context) { try { UnsafeNativeMethods.IMsoComponentManager cm = ComponentManager; - if (cm != null) { + if (cm != null) + { cm.OnComponentEnterState((IntPtr)componentID, NativeMethods.MSOCM.msocstateModal, NativeMethods.MSOCM.msoccontextAll, 0, 0, 0); } } @@ -2403,17 +2722,19 @@ internal void BeginModalMessageLoop(ApplicationContext context) { DisableWindowsForModalLoop(false, context); // onlyWinForms = false modalCount++; - - if (enterModalHandler != null && modalCount == 1) { + + if (enterModalHandler != null && modalCount == 1) + { enterModalHandler(Thread.CurrentThread, EventArgs.Empty); } - + } // Disables windows in preparation of going modal. If parameter is true, we disable all // windows, if false, only windows forms windows (i.e., windows controlled by this MsoComponent). // See also IMsoComponent.OnEnterState. - internal void DisableWindowsForModalLoop(bool onlyWinForms, ApplicationContext context) { + internal void DisableWindowsForModalLoop(bool onlyWinForms, ApplicationContext context) + { Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ComponentManager : Entering modal state"); ThreadWindows old = threadWindows; threadWindows = new ThreadWindows(onlyWinForms); @@ -2421,7 +2742,8 @@ internal void DisableWindowsForModalLoop(bool onlyWinForms, ApplicationContext c threadWindows.previousThreadWindows = old; ModalApplicationContext modalContext = context as ModalApplicationContext; - if (modalContext != null) { + if (modalContext != null) + { modalContext.DisableThreadWindows(true, onlyWinForms); } } @@ -2429,66 +2751,85 @@ internal void DisableWindowsForModalLoop(bool onlyWinForms, ApplicationContext c /// /// Disposes this thread context object. Note that this will marshal to the owning thread. /// - internal void Dispose(bool postQuit) { + internal void Dispose(bool postQuit) + { // need to avoid multiple threads coming in here or we'll leak the thread // handle. // - lock (this) { - try { - if (disposeCount++ == 0) { // make sure that we are not reentrant + lock (this) + { + try + { + if (disposeCount++ == 0) + { // make sure that we are not reentrant // Unravel our message loop. this will marshal us over to // the right thread, making the dispose() method async. - if (messageLoopCount > 0 && postQuit) { + if (messageLoopCount > 0 && postQuit) + { PostQuit(); } - else { + else + { bool ourThread = SafeNativeMethods.GetCurrentThreadId() == id; - try { + try + { // We can only clean up if we're being called on our // own thread. // - if (ourThread) { + if (ourThread) + { // If we had a component manager, detach from it. // - if (componentManager != null) { + if (componentManager != null) + { RevokeComponent(); } - // DisposeAssociatedComponents(); + // DisposeAssociatedComponents(); DisposeThreadWindows(); - try { + try + { Application.RaiseThreadExit(); } - finally { - if (GetState(STATE_OLEINITIALIZED) && !GetState(STATE_EXTERNALOLEINIT)) { + finally + { + if (GetState(STATE_OLEINITIALIZED) && !GetState(STATE_EXTERNALOLEINIT)) + { SetState(STATE_OLEINITIALIZED, false); UnsafeNativeMethods.OleUninitialize(); } } } } - finally { + finally + { // We can always clean up this handle, though // - if (handle != IntPtr.Zero) { + if (handle != IntPtr.Zero) + { UnsafeNativeMethods.CloseHandle(new HandleRef(this, handle)); handle = IntPtr.Zero; } - try { - if (totalMessageLoopCount == 0) { + try + { + if (totalMessageLoopCount == 0) + { Application.RaiseExit(); } } - finally { - lock (tcInternalSyncObject) { + finally + { + lock (tcInternalSyncObject) + { contextHash.Remove((object)id); } - if (currentThreadContext == this) { + if (currentThreadContext == this) + { currentThreadContext = null; } } @@ -2498,7 +2839,8 @@ internal void Dispose(bool postQuit) { GC.SuppressFinalize(this); } } - finally { + finally + { disposeCount--; } } @@ -2507,8 +2849,10 @@ internal void Dispose(bool postQuit) { /// /// Disposes of this thread's parking form. /// - private void DisposeParkingWindow() { - if (parkingWindows.Count != 0) { + private void DisposeParkingWindow() + { + if (parkingWindows.Count != 0) + { // We take two paths here. If we are on the same thread as // the parking window, we can destroy its handle. If not, @@ -2523,11 +2867,14 @@ private void DisposeParkingWindow() { int hwndThread = SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(parkingWindows[0], parkingWindows[0].Handle), out pid); int currentThread = SafeNativeMethods.GetCurrentThreadId(); - for(int i=0; i< parkingWindows.Count; i++) { - if (hwndThread == currentThread) { + for (int i = 0; i < parkingWindows.Count; i++) + { + if (hwndThread == currentThread) + { parkingWindows[i].Destroy(); } - else { + else + { parkingWindows[i] = null; } } @@ -2539,13 +2886,16 @@ private void DisposeParkingWindow() { /// Gets rid of all windows in this thread context. Nulls out /// window objects that we hang on to. /// - internal void DisposeThreadWindows() { + internal void DisposeThreadWindows() + { // We dispose the main window first, so it can perform any // cleanup that it may need to do. // - try { - if (applicationContext != null) { + try + { + if (applicationContext != null) + { applicationContext.Dispose(); applicationContext = null; } @@ -2559,29 +2909,34 @@ internal void DisposeThreadWindows() { // DisposeParkingWindow(); } - catch { + catch + { } } // Enables windows in preparation of stopping modal. If parameter is true, we enable all windows, // if false, only windows forms windows (i.e., windows controlled by this MsoComponent). // See also IMsoComponent.OnEnterState. - internal void EnableWindowsForModalLoop(bool onlyWinForms, ApplicationContext context) { + internal void EnableWindowsForModalLoop(bool onlyWinForms, ApplicationContext context) + { Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ComponentManager : Leaving modal state"); - if (threadWindows != null) { + if (threadWindows != null) + { threadWindows.Enable(true); Debug.Assert(threadWindows != null, "OnEnterState recursed, but it's not supposed to be reentrant"); threadWindows = threadWindows.previousThreadWindows; } ModalApplicationContext modalContext = context as ModalApplicationContext; - if (modalContext != null) { + if (modalContext != null) + { modalContext.DisableThreadWindows(false, onlyWinForms); } } // Called immediately after we end pumping messages for a modal message loop. - internal void EndModalMessageLoop(ApplicationContext context) { + internal void EndModalMessageLoop(ApplicationContext context) + { #if DEBUG debugModalCounter--; Debug.Assert(debugModalCounter >= 0, "Mis-matched calls to Application.BeginModalMessageLoop() and Application.EndModalMessageLoop()"); @@ -2591,11 +2946,13 @@ internal void EndModalMessageLoop(ApplicationContext context) { bool wasOurLoop = ourModalLoop; ourModalLoop = true; - try { + try + { // If We started the ModalMessageLoop .. this will call us back on the IMSOComponent.OnStateEnter and not do anything ... UnsafeNativeMethods.IMsoComponentManager cm = ComponentManager; - if (cm != null) { + if (cm != null) + { cm.FOnComponentExitState((IntPtr)componentID, NativeMethods.MSOCM.msocstateModal, NativeMethods.MSOCM.msoccontextAll, 0, 0); } } @@ -2607,7 +2964,8 @@ internal void EndModalMessageLoop(ApplicationContext context) { modalCount--; - if (leaveModalHandler != null && modalCount == 0) { + if (leaveModalHandler != null && modalCount == 0) + { leaveModalHandler(Thread.CurrentThread, EventArgs.Empty); } } @@ -2615,20 +2973,27 @@ internal void EndModalMessageLoop(ApplicationContext context) { /// /// Exits the program by disposing of all thread contexts and message loops. /// - internal static void ExitApplication() { + internal static void ExitApplication() + { ExitCommon(true /*disposing*/); } - private static void ExitCommon(bool disposing) { - lock(tcInternalSyncObject) { - if (contextHash != null) { + private static void ExitCommon(bool disposing) + { + lock (tcInternalSyncObject) + { + if (contextHash != null) + { ThreadContext[] ctxs = new ThreadContext[contextHash.Values.Count]; contextHash.Values.CopyTo(ctxs, 0); - for (int i = 0; i < ctxs.Length; ++i) { - if (ctxs[i].ApplicationContext != null) { + for (int i = 0; i < ctxs.Length; ++i) + { + if (ctxs[i].ApplicationContext != null) + { ctxs[i].ApplicationContext.ExitThread(); } - else { + else + { ctxs[i].Dispose(disposing); } } @@ -2639,14 +3004,16 @@ private static void ExitCommon(bool disposing) { /// /// Exits the program by disposing of all thread contexts and message loops. /// - internal static void ExitDomain() { + internal static void ExitDomain() + { ExitCommon(false /*disposing*/); } /// /// Our finalization. Minimal stuff... this shouldn't be called... We should always be disposed. /// - ~ThreadContext() { + ~ThreadContext() + { // We used to call OleUninitialize() here if we were // still STATE_OLEINITIALIZED, but that's never the correct thing to do. @@ -2655,7 +3022,8 @@ internal static void ExitDomain() { // We can always clean up this handle, though // - if (handle != IntPtr.Zero) { + if (handle != IntPtr.Zero) + { UnsafeNativeMethods.CloseHandle(new HandleRef(this, handle)); handle = IntPtr.Zero; } @@ -2663,10 +3031,13 @@ internal static void ExitDomain() { // When a Form receives a WM_ACTIVATE message, it calls this method so we can do the // appropriate MsoComponentManager activation magic - internal void FormActivated(bool activate) { - if (activate) { + internal void FormActivated(bool activate) + { + if (activate) + { UnsafeNativeMethods.IMsoComponentManager cm = ComponentManager; - if (cm != null && !(cm is ComponentManager)) { + if (cm != null && !(cm is ComponentManager)) + { cm.FOnComponentActivate((IntPtr)componentID); } } @@ -2674,24 +3045,29 @@ internal void FormActivated(bool activate) { // Sets this component as the tracking component - trumping any active component // for message filtering. - internal void TrackInput(bool track) { + internal void TrackInput(bool track) + { // protect against double setting, as this causes asserts in the VS component manager. - if (track != GetState(STATE_TRACKINGCOMPONENT)) { + if (track != GetState(STATE_TRACKINGCOMPONENT)) + { UnsafeNativeMethods.IMsoComponentManager cm = ComponentManager; - if (cm != null && !(cm is ComponentManager)) { + if (cm != null && !(cm is ComponentManager)) + { cm.FSetTrackingComponent((IntPtr)componentID, track); SetState(STATE_TRACKINGCOMPONENT, track); - } + } } } /// /// Retrieves a ThreadContext object for the current thread /// - internal static ThreadContext FromCurrent() { + internal static ThreadContext FromCurrent() + { ThreadContext context = currentThreadContext; - if (context == null) { + if (context == null) + { context = new ThreadContext(); } @@ -2701,9 +3077,11 @@ internal static ThreadContext FromCurrent() { /// /// Retrieves a ThreadContext object for the given thread ID /// - internal static ThreadContext FromId(int id) { + internal static ThreadContext FromId(int id) + { ThreadContext context = (ThreadContext)contextHash[(object)id]; - if (context == null && id == SafeNativeMethods.GetCurrentThreadId()) { + if (context == null && id == SafeNativeMethods.GetCurrentThreadId()) + { context = new ThreadContext(); } @@ -2714,28 +3092,32 @@ internal static ThreadContext FromId(int id) { /// Determines if it is OK to allow an application to quit and shutdown /// the runtime. We only allow this if we own the base message pump. /// - internal bool GetAllowQuit() { + internal bool GetAllowQuit() + { return totalMessageLoopCount > 0 && baseLoopReason == NativeMethods.MSOCM.msoloopMain; } /// /// Retrieves the handle to this thread. /// - internal IntPtr GetHandle() { + internal IntPtr GetHandle() + { return handle; } /// /// Retrieves the ID of this thread. /// - internal int GetId() { + internal int GetId() + { return id; } /// /// Retrieves the culture for this thread. /// - internal CultureInfo GetCulture() { + internal CultureInfo GetCulture() + { if (culture == null || culture.LCID != SafeNativeMethods.GetThreadLocale()) culture = new CultureInfo(SafeNativeMethods.GetThreadLocale()); return culture; @@ -2744,14 +3126,16 @@ internal CultureInfo GetCulture() { /// /// Determines if a message loop exists on this thread. /// - internal bool GetMessageLoop() { + internal bool GetMessageLoop() + { return GetMessageLoop(false); } /// /// Determines if a message loop exists on this thread. /// - internal bool GetMessageLoop(bool mustBeActive) { + internal bool GetMessageLoop(bool mustBeActive) + { // If we are already running a loop, we're fine. // If we are running in external manager we may need to make sure first the loop is active @@ -2764,21 +3148,25 @@ internal bool GetMessageLoop(bool mustBeActive) { // Also, access the ComponentManager property to demand create it, and we're also // fine if it is an external manager, because it has already pushed a loop. // - if (ComponentManager != null && externalComponentManager) { - if (mustBeActive == false) { + if (ComponentManager != null && externalComponentManager) + { + if (mustBeActive == false) + { return true; } UnsafeNativeMethods.IMsoComponent[] activeComponents = new UnsafeNativeMethods.IMsoComponent[1]; if (ComponentManager.FGetActiveComponent(NativeMethods.MSOCM.msogacActive, activeComponents, null, 0) && - activeComponents[0] == this) { + activeComponents[0] == this) + { return true; } } // Finally, check if a message loop has been registered MessageLoopCallback callback = messageLoopCallback; - if (callback != null) { + if (callback != null) + { return callback(); } @@ -2787,8 +3175,9 @@ internal bool GetMessageLoop(bool mustBeActive) { return false; } - private bool GetState(int bit) { - return(threadState & bit) != 0; + private bool GetState(int bit) + { + return (threadState & bit) != 0; } /// @@ -2796,13 +3185,16 @@ private bool GetState(int bit) { /// the componentmanager /// /// - internal bool IsValidComponentId() { + internal bool IsValidComponentId() + { return (componentID != INVALID_ID); } - internal System.Threading.ApartmentState OleRequired() { + internal System.Threading.ApartmentState OleRequired() + { Thread current = Thread.CurrentThread; - if (!GetState(STATE_OLEINITIALIZED)) { + if (!GetState(STATE_OLEINITIALIZED)) + { int ret = UnsafeNativeMethods.OleInitialize(); @@ -2815,7 +3207,8 @@ internal System.Threading.ApartmentState OleRequired() { #endif SetState(STATE_OLEINITIALIZED, true); - if (ret == NativeMethods.RPC_E_CHANGED_MODE) { + if (ret == NativeMethods.RPC_E_CHANGED_MODE) + { // This could happen if the thread was already initialized for MTA // and then we call OleInitialize which tries to initialized it for STA // This currently happens while profiling... @@ -2824,15 +3217,18 @@ internal System.Threading.ApartmentState OleRequired() { } - if ( GetState( STATE_EXTERNALOLEINIT )) { + if (GetState(STATE_EXTERNALOLEINIT)) + { return System.Threading.ApartmentState.MTA; } - else { + else + { return System.Threading.ApartmentState.STA; } } - private void OnAppThreadExit(object sender, EventArgs e) { + private void OnAppThreadExit(object sender, EventArgs e) + { Dispose(true); } @@ -2840,7 +3236,8 @@ private void OnAppThreadExit(object sender, EventArgs e) { /// Revokes our component if needed. /// [PrePrepareMethod] - private void OnDomainUnload(object sender, EventArgs e) { + private void OnDomainUnload(object sender, EventArgs e) + { RevokeComponent(); ExitDomain(); } @@ -2850,26 +3247,35 @@ private void OnDomainUnload(object sender, EventArgs e) { /// programmer to trap these, and, if left untrapped, throws a standard error /// dialog. /// - internal void OnThreadException(Exception t) { - if (GetState(STATE_INTHREADEXCEPTION)) return; + internal void OnThreadException(Exception t) + { + if (GetState(STATE_INTHREADEXCEPTION)) + return; SetState(STATE_INTHREADEXCEPTION, true); - try { - if (threadExceptionHandler != null) { + try + { + if (threadExceptionHandler != null) + { threadExceptionHandler(Thread.CurrentThread, new ThreadExceptionEventArgs(t)); } - else { - if (SystemInformation.UserInteractive) { + else + { + if (SystemInformation.UserInteractive) + { ThreadExceptionDialog td = new ThreadExceptionDialog(t); DialogResult result = DialogResult.OK; - try { + try + { result = td.ShowDialog(); } - finally { + finally + { td.Dispose(); } - switch (result) { + switch (result) + { case DialogResult.Abort: Application.ExitInternal(); @@ -2878,13 +3284,15 @@ internal void OnThreadException(Exception t) { break; case DialogResult.Yes: WarningException w = t as WarningException; - if (w != null) { + if (w != null) + { Help.ShowHelp(null, w.HelpUrl, w.HelpTopic); } break; } } - else { + else + { // Ignore unhandled thread exceptions. The user can // override if they really care. // @@ -2892,12 +3300,14 @@ internal void OnThreadException(Exception t) { } } - finally { + finally + { SetState(STATE_INTHREADEXCEPTION, false); } } - internal void PostQuit() { + internal void PostQuit() + { Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ComponentManager : Attempting to terminate message loop"); // Per http://support.microsoft.com/support/kb/articles/Q183/1/16.ASP @@ -2914,15 +3324,18 @@ internal void PostQuit() { } // Allows the hosting environment to register a callback - internal void RegisterMessageLoop(MessageLoopCallback callback) { + internal void RegisterMessageLoop(MessageLoopCallback callback) + { messageLoopCallback = callback; } /// /// Removes a message filter previously installed with addMessageFilter. /// - internal void RemoveMessageFilter(IMessageFilter f) { - if (messageFilters != null) { + internal void RemoveMessageFilter(IMessageFilter f) + { + if (messageFilters != null) + { SetState(STATE_FILTERSNAPSHOTVALID, false); messageFilters.Remove(f); } @@ -2931,29 +3344,35 @@ internal void RemoveMessageFilter(IMessageFilter f) { /// /// Starts a message loop for the given reason. /// - internal void RunMessageLoop(int reason, ApplicationContext context) { + internal void RunMessageLoop(int reason, ApplicationContext context) + { // Ensure that we attempt to apply theming before doing anything // that might create a window. IntPtr userCookie = IntPtr.Zero; - if (s_useVisualStyles) { + if (s_useVisualStyles) + { userCookie = UnsafeNativeMethods.ThemingScope.Activate(); } - try { - RunMessageLoopInner(reason, context); + try + { + RunMessageLoopInner(reason, context); } - finally { + finally + { UnsafeNativeMethods.ThemingScope.Deactivate(userCookie); } - } + } - private void RunMessageLoopInner(int reason, ApplicationContext context) { + private void RunMessageLoopInner(int reason, ApplicationContext context) + { Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ThreadContext.PushMessageLoop {"); Debug.Indent(); - if (reason == NativeMethods.MSOCM.msoloopModalForm && !SystemInformation.UserInteractive) { + if (reason == NativeMethods.MSOCM.msoloopModalForm && !SystemInformation.UserInteractive) + { throw new InvalidOperationException(SR.CantShowModalOnNonInteractive); } @@ -2961,20 +3380,24 @@ private void RunMessageLoopInner(int reason, ApplicationContext context) { // (different than a modal message loop or DoEVents loop) // then clear the QUIT flag to allow normal processing. // this flag gets set during loop teardown for another form. - if (reason == NativeMethods.MSOCM.msoloopMain) { + if (reason == NativeMethods.MSOCM.msoloopMain) + { SetState(STATE_POSTEDQUIT, false); } - if (totalMessageLoopCount++ == 0) { + if (totalMessageLoopCount++ == 0) + { baseLoopReason = reason; } messageLoopCount++; - if (reason == NativeMethods.MSOCM.msoloopMain) { + if (reason == NativeMethods.MSOCM.msoloopMain) + { // If someone has tried to push another main message loop on this thread, ignore // it. - if (messageLoopCount != 1) { + if (messageLoopCount != 1) + { throw new InvalidOperationException(SR.CantNestMessageLoops); } @@ -2982,7 +3405,8 @@ private void RunMessageLoopInner(int reason, ApplicationContext context) { applicationContext.ThreadExit += new EventHandler(OnAppThreadExit); - if (applicationContext.MainForm != null) { + if (applicationContext.MainForm != null) + { applicationContext.MainForm.Visible = true; } @@ -2990,7 +3414,8 @@ private void RunMessageLoopInner(int reason, ApplicationContext context) { } Form oldForm = currentForm; - if (context != null) { + if (context != null) + { currentForm = context.MainForm; } @@ -2998,11 +3423,13 @@ private void RunMessageLoopInner(int reason, ApplicationContext context) { bool localModal = false; HandleRef hwndOwner = new HandleRef(null, IntPtr.Zero); - if (reason == NativeMethods.MSOCM.msoloopDoEventsModal) { + if (reason == NativeMethods.MSOCM.msoloopDoEventsModal) + { localModal = true; } - if (reason == NativeMethods.MSOCM.msoloopModalForm || reason == NativeMethods.MSOCM.msoloopModalAlert) { + if (reason == NativeMethods.MSOCM.msoloopModalForm || reason == NativeMethods.MSOCM.msoloopModalAlert) + { fullModal = true; // We're about to disable all windows in the thread so our modal dialog can be the top dog. Because this can interact @@ -3020,11 +3447,14 @@ private void RunMessageLoopInner(int reason, ApplicationContext context) { // This can happen if the owner window is from a different thread or // process. hwndOwner = new HandleRef(null, UnsafeNativeMethods.GetWindowLong(new HandleRef(currentForm, currentForm.Handle), NativeMethods.GWL_HWNDPARENT)); - if (hwndOwner.Handle != IntPtr.Zero) { - if (SafeNativeMethods.IsWindowEnabled(hwndOwner)) { + if (hwndOwner.Handle != IntPtr.Zero) + { + if (SafeNativeMethods.IsWindowEnabled(hwndOwner)) + { SafeNativeMethods.EnableWindow(hwndOwner, false); } - else { + else + { // reset hwndOwner so we are not tempted to // fiddle with it hwndOwner = new HandleRef(null, IntPtr.Zero); @@ -3036,12 +3466,14 @@ private void RunMessageLoopInner(int reason, ApplicationContext context) { // if (currentForm != null && currentForm.IsHandleCreated && - SafeNativeMethods.IsWindowEnabled(new HandleRef(currentForm, currentForm.Handle)) != modalEnabled) { + SafeNativeMethods.IsWindowEnabled(new HandleRef(currentForm, currentForm.Handle)) != modalEnabled) + { SafeNativeMethods.EnableWindow(new HandleRef(currentForm, currentForm.Handle), modalEnabled); } } - try { + try + { Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "[0x" + Convert.ToString(componentID, 16) + "] Calling ComponentManager.FPushMessageLoop..."); bool result; @@ -3049,36 +3481,44 @@ private void RunMessageLoopInner(int reason, ApplicationContext context) { // need to be able to successfully get the handle to the // parking window. Only do it when we're entering the first // message loop for this thread. - if (messageLoopCount == 1) { + if (messageLoopCount == 1) + { WindowsFormsSynchronizationContext.InstallIfNeeded(); } //need to do this in a try/finally. Also good to do after we installed the synch context. - if (fullModal && currentForm != null) { + if (fullModal && currentForm != null) + { currentForm.Visible = true; } - if ((!fullModal && !localModal) || ComponentManager is ComponentManager) { + if ((!fullModal && !localModal) || ComponentManager is ComponentManager) + { result = ComponentManager.FPushMessageLoop((IntPtr)componentID, reason, 0); } else if (reason == NativeMethods.MSOCM.msoloopDoEvents || - reason == NativeMethods.MSOCM.msoloopDoEventsModal) { + reason == NativeMethods.MSOCM.msoloopDoEventsModal) + { result = LocalModalMessageLoop(null); } - else { + else + { result = LocalModalMessageLoop(currentForm); } Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "[0x" + Convert.ToString(componentID, 16) + "] ComponentManager.FPushMessageLoop returned " + result.ToString()); } - finally { + finally + { - if (fullModal) { + if (fullModal) + { Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "[0x" + Convert.ToString(componentID, 16) + "] Notifying component manager that we are exiting a modal loop"); EndModalMessageLoop(context); // Again, if the hwndOwner was valid and disabled above, re-enable it. - if (hwndOwner.Handle != IntPtr.Zero) { + if (hwndOwner.Handle != IntPtr.Zero) + { SafeNativeMethods.EnableWindow(hwndOwner, true); } } @@ -3087,17 +3527,20 @@ private void RunMessageLoopInner(int reason, ApplicationContext context) { totalMessageLoopCount--; messageLoopCount--; - if (messageLoopCount == 0) { + if (messageLoopCount == 0) + { // If last message loop shutting down, install the // previous op sync context in place before we started the first // message loop. WindowsFormsSynchronizationContext.Uninstall(false); } - if (reason == NativeMethods.MSOCM.msoloopMain) { + if (reason == NativeMethods.MSOCM.msoloopMain) + { Dispose(true); } - else if (messageLoopCount == 0 && componentManager != null) { + else if (messageLoopCount == 0 && componentManager != null) + { // If we had a component manager, detach from it. // RevokeComponent(); @@ -3108,67 +3551,83 @@ private void RunMessageLoopInner(int reason, ApplicationContext context) { Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "}"); } - private bool LocalModalMessageLoop(Form form) { - try { + private bool LocalModalMessageLoop(Form form) + { + try + { // Execute the message loop until the active component tells us to stop. // NativeMethods.MSG msg = new NativeMethods.MSG(); bool unicodeWindow = false; bool continueLoop = true; - while (continueLoop) { + while (continueLoop) + { bool peeked = UnsafeNativeMethods.PeekMessage(ref msg, NativeMethods.NullHandleRef, 0, 0, NativeMethods.PM_NOREMOVE); - if (peeked) { + if (peeked) + { // If the component wants us to process the message, do it. // The component manager hosts windows from many places. We must be sensitive // to ansi / Unicode windows here. // - if (msg.hwnd != IntPtr.Zero && SafeNativeMethods.IsWindowUnicode(new HandleRef(null, msg.hwnd))) { + if (msg.hwnd != IntPtr.Zero && SafeNativeMethods.IsWindowUnicode(new HandleRef(null, msg.hwnd))) + { unicodeWindow = true; - if (!UnsafeNativeMethods.GetMessageW(ref msg, NativeMethods.NullHandleRef, 0, 0)) { + if (!UnsafeNativeMethods.GetMessageW(ref msg, NativeMethods.NullHandleRef, 0, 0)) + { continue; } } - else { + else + { unicodeWindow = false; - if (!UnsafeNativeMethods.GetMessageA(ref msg, NativeMethods.NullHandleRef, 0, 0)) { + if (!UnsafeNativeMethods.GetMessageA(ref msg, NativeMethods.NullHandleRef, 0, 0)) + { continue; } } - if (!PreTranslateMessage(ref msg)) { + if (!PreTranslateMessage(ref msg)) + { UnsafeNativeMethods.TranslateMessage(ref msg); - if (unicodeWindow) { + if (unicodeWindow) + { UnsafeNativeMethods.DispatchMessageW(ref msg); } - else { + else + { UnsafeNativeMethods.DispatchMessageA(ref msg); } } - if (form != null) { + if (form != null) + { continueLoop = !form.CheckCloseDialog(false); } } - else if (form == null) { + else if (form == null) + { break; } - else if (!UnsafeNativeMethods.PeekMessage(ref msg, NativeMethods.NullHandleRef, 0, 0, NativeMethods.PM_NOREMOVE)) { + else if (!UnsafeNativeMethods.PeekMessage(ref msg, NativeMethods.NullHandleRef, 0, 0, NativeMethods.PM_NOREMOVE)) + { UnsafeNativeMethods.WaitMessage(); } } return continueLoop; } - catch { + catch + { return false; } } - internal bool ProcessFilters(ref NativeMethods.MSG msg, out bool modified) { + internal bool ProcessFilters(ref NativeMethods.MSG msg, out bool modified) + { bool filtered = false; modified = false; @@ -3179,28 +3638,34 @@ internal bool ProcessFilters(ref NativeMethods.MSG msg, out bool modified) { // If message filter is added or removed inside the user-provided PreFilterMessage function, // and user code pumps messages, we might re-enter ProcessFilter on the same stack, we // should not update the snapshot until the next message. - if (messageFilters != null && !GetState(STATE_FILTERSNAPSHOTVALID) && (LocalAppContextSwitches.DontSupportReentrantFilterMessage || inProcessFilters == 0)) { + if (messageFilters != null && !GetState(STATE_FILTERSNAPSHOTVALID) && (LocalAppContextSwitches.DontSupportReentrantFilterMessage || inProcessFilters == 0)) + { messageFilterSnapshot.Clear(); - if (messageFilters.Count > 0) { + if (messageFilters.Count > 0) + { messageFilterSnapshot.AddRange(messageFilters); } SetState(STATE_FILTERSNAPSHOTVALID, true); } inProcessFilters++; - try { - if (messageFilterSnapshot != null && messageFilterSnapshot.Count != 0) { + try + { + if (messageFilterSnapshot != null && messageFilterSnapshot.Count != 0) + { IMessageFilter f; int count = messageFilterSnapshot.Count; Message m = Message.Create(msg.hwnd, msg.message, msg.wParam, msg.lParam); - for (int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) + { f = messageFilterSnapshot[i]; bool filterMessage = f.PreFilterMessage(ref m); // make sure that we update the msg struct with the new result after the call to // PreFilterMessage. - if (f is IMessageModifyAndFilter) { + if (f is IMessageModifyAndFilter) + { msg.hwnd = m.HWnd; msg.message = m.Msg; msg.wParam = m.WParam; @@ -3208,14 +3673,16 @@ internal bool ProcessFilters(ref NativeMethods.MSG msg, out bool modified) { modified = true; } - if (filterMessage) { + if (filterMessage) + { filtered = true; break; } } } } - finally { + finally + { inProcessFilters--; } @@ -3228,22 +3695,28 @@ internal bool ProcessFilters(ref NativeMethods.MSG msg, out bool modified) { /// false, the message should be allowed to continue through the dispatch /// mechanism. /// - internal bool PreTranslateMessage(ref NativeMethods.MSG msg) { + internal bool PreTranslateMessage(ref NativeMethods.MSG msg) + { bool modified = false; - if (ProcessFilters(ref msg, out modified)) { + if (ProcessFilters(ref msg, out modified)) + { return true; } - + if (msg.message >= Interop.WindowMessages.WM_KEYFIRST - && msg.message <= Interop.WindowMessages.WM_KEYLAST) { - if (msg.message == Interop.WindowMessages.WM_CHAR) { + && msg.message <= Interop.WindowMessages.WM_KEYLAST) + { + if (msg.message == Interop.WindowMessages.WM_CHAR) + { int breakLParamMask = 0x1460000; // 1 = extended keyboard, 46 = scan code - if (unchecked( (int) (long)msg.wParam) == 3 && ( unchecked( (int) (long)msg.lParam) & breakLParamMask) == breakLParamMask) { // ctrl-brk + if (unchecked((int)(long)msg.wParam) == 3 && (unchecked((int)(long)msg.lParam) & breakLParamMask) == breakLParamMask) + { // ctrl-brk // wParam is the key character, which for ctrl-brk is the same as ctrl-C. // So we need to go to the lparam to distinguish the two cases. // You might also be able to do this with WM_KEYDOWN (again with wParam=3) - if (Debugger.IsAttached) { + if (Debugger.IsAttached) + { Debugger.Break(); } } @@ -3255,22 +3728,27 @@ internal bool PreTranslateMessage(ref NativeMethods.MSG msg) { if (target != null) { - if (NativeWindow.WndProcShouldBeDebuggable) { + if (NativeWindow.WndProcShouldBeDebuggable) + { // we don't want to do a catch in the debuggable case. // - if (Control.PreProcessControlMessageInternal(target, ref m) == PreProcessControlState.MessageProcessed) { + if (Control.PreProcessControlMessageInternal(target, ref m) == PreProcessControlState.MessageProcessed) + { retValue = true; - } + } } - else { + else + { try { - if (Control.PreProcessControlMessageInternal(target, ref m) == PreProcessControlState.MessageProcessed) { + if (Control.PreProcessControlMessageInternal(target, ref m) == PreProcessControlState.MessageProcessed) + { retValue = true; } } - catch (Exception e) { - OnThreadException(e); + catch (Exception e) + { + OnThreadException(e); } } } @@ -3296,7 +3774,8 @@ internal bool PreTranslateMessage(ref NativeMethods.MSG msg) { msg.wParam = m.WParam; msg.lParam = m.LParam; - if (retValue) { + if (retValue) + { return true; } } @@ -3309,18 +3788,23 @@ internal bool PreTranslateMessage(ref NativeMethods.MSG msg) { /// nothing if there is no active component manager or we are /// already invoked. /// - private void RevokeComponent() { - if (componentManager != null && componentID != INVALID_ID) { + private void RevokeComponent() + { + if (componentManager != null && componentID != INVALID_ID) + { int id = componentID; UnsafeNativeMethods.IMsoComponentManager msocm = componentManager; - try { + try + { msocm.FRevokeComponent((IntPtr)id); - if (Marshal.IsComObject(msocm)) { + if (Marshal.IsComObject(msocm)) + { Marshal.ReleaseComObject(msocm); } } - finally { + finally + { componentManager = null; componentID = INVALID_ID; } @@ -3330,17 +3814,22 @@ private void RevokeComponent() { /// /// Sets the culture for this thread. /// - internal void SetCulture(CultureInfo culture) { - if (culture != null && culture.LCID != SafeNativeMethods.GetThreadLocale()) { + internal void SetCulture(CultureInfo culture) + { + if (culture != null && culture.LCID != SafeNativeMethods.GetThreadLocale()) + { SafeNativeMethods.SetThreadLocale(culture.LCID); } } - private void SetState(int bit, bool value) { - if (value) { + private void SetState(int bit, bool value) + { + if (value) + { threadState |= bit; } - else { + else + { threadState &= (~bit); } } @@ -3382,7 +3871,8 @@ bool UnsafeNativeMethods.IMsoComponent.FDebugMessage(IntPtr hInst, int msg, IntP /// do IsDialogMessage, modify pMsg, or take some other action. /// Return TRUE if the message is consumed, FALSE otherwise. /// - bool UnsafeNativeMethods.IMsoComponent.FPreTranslateMessage(ref NativeMethods.MSG msg) { + bool UnsafeNativeMethods.IMsoComponent.FPreTranslateMessage(ref NativeMethods.MSG msg) + { return PreTranslateMessage(ref msg); } @@ -3402,7 +3892,8 @@ bool UnsafeNativeMethods.IMsoComponent.FPreTranslateMessage(ref NativeMethods.MS /// when called with FALSE fEnter), the counter should not be decremented /// for FALSE fEnter if it is already at zero.) /// - void UnsafeNativeMethods.IMsoComponent.OnEnterState(int uStateID, bool fEnter) { + void UnsafeNativeMethods.IMsoComponent.OnEnterState(int uStateID, bool fEnter) + { Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ComponentManager : OnEnterState(" + uStateID + ", " + fEnter + ")"); @@ -3411,12 +3902,15 @@ void UnsafeNativeMethods.IMsoComponent.OnEnterState(int uStateID, bool fEnter) { { return; } - if (uStateID == NativeMethods.MSOCM.msocstateModal) { + if (uStateID == NativeMethods.MSOCM.msocstateModal) + { // We should only be messing with windows we own. See the "ctrl-shift-N" test above. - if (fEnter) { + if (fEnter) + { DisableWindowsForModalLoop(true, null); // WinFormsOnly = true } - else { + else + { EnableWindowsForModalLoop(true, null); // WinFormsOnly = true } } @@ -3432,14 +3926,16 @@ void UnsafeNativeMethods.IMsoComponent.OnEnterState(int uStateID, bool fEnter) { /// Note: this method is not called when both the window being activated /// and the one being deactivated belong to the host app. /// - void UnsafeNativeMethods.IMsoComponent.OnAppActivate(bool fActive, int dwOtherThreadID) { + void UnsafeNativeMethods.IMsoComponent.OnAppActivate(bool fActive, int dwOtherThreadID) + { } /// /// Notify the active component that it has lost its active status because /// the host or another component has become active. /// - void UnsafeNativeMethods.IMsoComponent.OnLoseActivation() { + void UnsafeNativeMethods.IMsoComponent.OnLoseActivation() + { Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ComponentManager : Our component is losing activation."); } @@ -3481,7 +3977,8 @@ void UnsafeNativeMethods.IMsoComponent.OnActivationChange(UnsafeNativeMethods.IM int pcrinfo, bool fHostIsActivating, int pchostinfo, - int dwReserved) { + int dwReserved) + { Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ComponentManager : OnActivationChange"); } @@ -3501,11 +3998,13 @@ void UnsafeNativeMethods.IMsoComponent.OnActivationChange(UnsafeNativeMethods.IM /// tracking operation, component should only perform idle time tasks that /// it deems are appropriate to perform during tracking. /// - bool UnsafeNativeMethods.IMsoComponent.FDoIdle(int grfidlef) { - if (idleHandler != null) { - idleHandler(Thread.CurrentThread, EventArgs.Empty); - } - return false; + bool UnsafeNativeMethods.IMsoComponent.FDoIdle(int grfidlef) + { + if (idleHandler != null) + { + idleHandler(Thread.CurrentThread, EventArgs.Empty); + } + return false; } /// @@ -3522,26 +4021,31 @@ bool UnsafeNativeMethods.IMsoComponent.FDoIdle(int grfidlef) { /// If FALSE is returned, the component manager terminates the loop without /// removing pMsgPeeked from the queue. /// - bool UnsafeNativeMethods.IMsoComponent.FContinueMessageLoop(int reason, int pvLoopData, NativeMethods.MSG[] msgPeeked) { + bool UnsafeNativeMethods.IMsoComponent.FContinueMessageLoop(int reason, int pvLoopData, NativeMethods.MSG[] msgPeeked) + { bool continueLoop = true; // If we get a null message, and we have previously posted the WM_QUIT message, // then someone ate the message... // - if (msgPeeked == null && GetState(STATE_POSTEDQUIT)) { + if (msgPeeked == null && GetState(STATE_POSTEDQUIT)) + { Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ComponentManager : Abnormal loop termination, no WM_QUIT received"); continueLoop = false; } - else { - switch (reason) { + else + { + switch (reason) + { case NativeMethods.MSOCM.msoloopFocusWait: // For focus wait, check to see if we are now the active application. // int pid; SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(null, UnsafeNativeMethods.GetActiveWindow()), out pid); - if (pid == SafeNativeMethods.GetCurrentProcessId()) { + if (pid == SafeNativeMethods.GetCurrentProcessId()) + { continueLoop = false; } break; @@ -3553,7 +4057,8 @@ bool UnsafeNativeMethods.IMsoComponent.FContinueMessageLoop(int reason, int pvLo // dismissed. If there is no active form, then it is an error that // we got into here, so we terminate the loop. // - if (currentForm == null || currentForm.CheckCloseDialog(false)) { + if (currentForm == null || currentForm.CheckCloseDialog(false)) + { continueLoop = false; } break; @@ -3562,7 +4067,8 @@ bool UnsafeNativeMethods.IMsoComponent.FContinueMessageLoop(int reason, int pvLo case NativeMethods.MSOCM.msoloopDoEventsModal: // For DoEvents, just see if there are more messages on the queue. // - if (!UnsafeNativeMethods.PeekMessage(ref tempMsg, NativeMethods.NullHandleRef, 0, 0, NativeMethods.PM_NOREMOVE)) { + if (!UnsafeNativeMethods.PeekMessage(ref tempMsg, NativeMethods.NullHandleRef, 0, 0, NativeMethods.PM_NOREMOVE)) + { continueLoop = false; } @@ -3584,7 +4090,8 @@ bool UnsafeNativeMethods.IMsoComponent.FContinueMessageLoop(int reason, int pvLo /// or FALSE appropriately, or 2.) giving an indication as to why it /// cannot terminate and returning FALSE. /// - bool UnsafeNativeMethods.IMsoComponent.FQueryTerminate(bool fPromptUser) { + bool UnsafeNativeMethods.IMsoComponent.FQueryTerminate(bool fPromptUser) + { return true; } @@ -3594,8 +4101,10 @@ bool UnsafeNativeMethods.IMsoComponent.FQueryTerminate(bool fPromptUser) { /// manager, release references to component manager and perform any /// necessary cleanup. /// - void UnsafeNativeMethods.IMsoComponent.Terminate() { - if (this.messageLoopCount > 0 && !(ComponentManager is ComponentManager)) { + void UnsafeNativeMethods.IMsoComponent.Terminate() + { + if (this.messageLoopCount > 0 && !(ComponentManager is ComponentManager)) + { this.messageLoopCount--; } @@ -3609,7 +4118,8 @@ void UnsafeNativeMethods.IMsoComponent.Terminate() { /// Component should return the desired window or NULL if no such window /// exists. /// - IntPtr UnsafeNativeMethods.IMsoComponent.HwndGetWindow(int dwWhich, int dwReserved) { + IntPtr UnsafeNativeMethods.IMsoComponent.HwndGetWindow(int dwWhich, int dwReserved) + { return IntPtr.Zero; } } @@ -3618,9 +4128,11 @@ IntPtr UnsafeNativeMethods.IMsoComponent.HwndGetWindow(int dwWhich, int dwReserv /// This class allows us to handle sends/posts in our winformssynchcontext on the correct thread via /// control.invoke(). /// - internal sealed class MarshalingControl : Control { + internal sealed class MarshalingControl : Control + { internal MarshalingControl() - : base(false) { + : base(false) + { Visible = false; SetState2(STATE2_INTERESTEDINUSERPREFERENCECHANGED, false); SetTopLevel(true); @@ -3640,10 +4152,12 @@ protected override CreateParams CreateParams } } - protected override void OnLayout(LayoutEventArgs levent) { + protected override void OnLayout(LayoutEventArgs levent) + { } - protected override void OnSizeChanged(EventArgs e) { + protected override void OnSizeChanged(EventArgs e) + { // don't do anything here -- small perf game of avoiding layout, etc. } @@ -3653,7 +4167,8 @@ protected override void OnSizeChanged(EventArgs e) { /// This class embodies our parking window, which we create when the /// first message loop is pushed onto the thread. /// - internal sealed class ParkingWindow : ContainerControl, IArrangedElement { + internal sealed class ParkingWindow : ContainerControl, IArrangedElement + { // WHIDBEY CHANGES // in whidbey we now aggressively tear down the parking window @@ -3667,7 +4182,8 @@ internal sealed class ParkingWindow : ContainerControl, IArrangedElement { SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // The parking window is invisible. // So we don't have to localize its Text. ] - public ParkingWindow() { + public ParkingWindow() + { SetState2(STATE2_INTERESTEDINUSERPREFERENCECHANGED, false); SetState(STATE_TOPLEVEL, true); Text = "WindowsFormsParkingWindow"; @@ -3688,22 +4204,28 @@ protected override CreateParams CreateParams } } - internal override void AddReflectChild() { - if (childCount < 0) { + internal override void AddReflectChild() + { + if (childCount < 0) + { Debug.Fail("How did parkingwindow childcount go negative???"); childCount = 0; } childCount++; } - internal override void RemoveReflectChild() { + internal override void RemoveReflectChild() + { childCount--; - if (childCount < 0) { + if (childCount < 0) + { Debug.Fail("How did parkingwindow childcount go negative???"); childCount = 0; } - if (childCount == 0) { - if (IsHandleCreated) { + if (childCount == 0) + { + if (IsHandleCreated) + { //check to see if we are running on the thread that owns the parkingwindow. //if so, we can destroy immediately. //This is important for scenarios where apps leak controls until after the @@ -3716,26 +4238,32 @@ internal override void RemoveReflectChild() { //We only do this if the ThreadContext tells us that we are currently //handling a window message. if (ctx == null || - !Object.ReferenceEquals(ctx, Application.ThreadContext.FromCurrent())) { + !Object.ReferenceEquals(ctx, Application.ThreadContext.FromCurrent())) + { UnsafeNativeMethods.PostMessage(new HandleRef(this, HandleInternal), WM_CHECKDESTROY, IntPtr.Zero, IntPtr.Zero); } - else { + else + { CheckDestroy(); } } } } - - private void CheckDestroy() { - if (childCount == 0) { + + private void CheckDestroy() + { + if (childCount == 0) + { IntPtr hwndChild = UnsafeNativeMethods.GetWindow(new HandleRef(this, Handle), NativeMethods.GW_CHILD); - if (hwndChild == IntPtr.Zero) { + if (hwndChild == IntPtr.Zero) + { DestroyHandle(); } } } - public void Destroy() { + public void Destroy() + { DestroyHandle(); } @@ -3743,8 +4271,10 @@ public void Destroy() { /// "Parks" the given HWND to a temporary HWND. This allows WS_CHILD windows to /// be parked. /// - internal void ParkHandle(HandleRef handle) { - if (!IsHandleCreated) { + internal void ParkHandle(HandleRef handle) + { + if (!IsHandleCreated) + { CreateHandle(); } @@ -3755,8 +4285,10 @@ internal void ParkHandle(HandleRef handle) { /// "Unparks" the given HWND to a temporary HWND. This allows WS_CHILD windows to /// be parked. /// - internal void UnparkHandle(HandleRef handle) { - if (IsHandleCreated) { + internal void UnparkHandle(HandleRef handle) + { + if (IsHandleCreated) + { Debug.Assert(UnsafeNativeMethods.GetParent(handle) != Handle, "Always set the handle's parent to someone else before calling UnparkHandle"); // If there are no child windows in this handle any longer, destroy the parking window. CheckDestroy(); @@ -3764,18 +4296,23 @@ internal void UnparkHandle(HandleRef handle) { } // Do nothing on layout to reduce the calls into the LayoutEngine while debugging. - protected override void OnLayout(LayoutEventArgs levent) {} - void IArrangedElement.PerformLayout(IArrangedElement affectedElement, string affectedProperty) {} + protected override void OnLayout(LayoutEventArgs levent) { } + void IArrangedElement.PerformLayout(IArrangedElement affectedElement, string affectedProperty) { } - protected override void WndProc(ref Message m) { - if (m.Msg != Interop.WindowMessages.WM_SHOWWINDOW) { + protected override void WndProc(ref Message m) + { + if (m.Msg != Interop.WindowMessages.WM_SHOWWINDOW) + { base.WndProc(ref m); - if (m.Msg == Interop.WindowMessages.WM_PARENTNOTIFY) { - if (NativeMethods.Util.LOWORD(unchecked( (int) (long)m.WParam)) == Interop.WindowMessages.WM_DESTROY) { + if (m.Msg == Interop.WindowMessages.WM_PARENTNOTIFY) + { + if (NativeMethods.Util.LOWORD(unchecked((int)(long)m.WParam)) == Interop.WindowMessages.WM_DESTROY) + { UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), WM_CHECKDESTROY, IntPtr.Zero, IntPtr.Zero); } } - else if (m.Msg == WM_CHECKDESTROY) { + else if (m.Msg == WM_CHECKDESTROY) + { CheckDestroy(); } } @@ -3788,7 +4325,8 @@ protected override void WndProc(ref Message m) { /// be used to dispose all windows in a thread, which we do before returning from a message /// loop. /// - private sealed class ThreadWindows { + private sealed class ThreadWindows + { private IntPtr[] windows; private int windowCount; private IntPtr activeHwnd; @@ -3796,7 +4334,8 @@ private sealed class ThreadWindows { internal ThreadWindows previousThreadWindows; private bool onlyWinForms = true; - internal ThreadWindows(bool onlyWinForms) { + internal ThreadWindows(bool onlyWinForms) + { windows = new IntPtr[16]; this.onlyWinForms = onlyWinForms; UnsafeNativeMethods.EnumThreadWindows(SafeNativeMethods.GetCurrentThreadId(), @@ -3804,22 +4343,28 @@ internal ThreadWindows(bool onlyWinForms) { NativeMethods.NullHandleRef); } - private bool Callback(IntPtr hWnd, IntPtr lparam) { + private bool Callback(IntPtr hWnd, IntPtr lparam) + { // We only do visible and enabled windows. Also, we only do top level windows. // Finally, we only include windows that are DNA windows, since other MSO components // will be responsible for disabling their own windows. // - if (SafeNativeMethods.IsWindowVisible(new HandleRef(null, hWnd)) && SafeNativeMethods.IsWindowEnabled(new HandleRef(null, hWnd))) { + if (SafeNativeMethods.IsWindowVisible(new HandleRef(null, hWnd)) && SafeNativeMethods.IsWindowEnabled(new HandleRef(null, hWnd))) + { bool add = true; - if (onlyWinForms) { + if (onlyWinForms) + { Control c = Control.FromHandle(hWnd); - if (c == null) add = false; + if (c == null) + add = false; } - if (add) { - if (windowCount == windows.Length) { + if (add) + { + if (windowCount == windows.Length) + { IntPtr[] newWindows = new IntPtr[windowCount * 2]; Array.Copy(windows, 0, newWindows, 0, windowCount); windows = newWindows; @@ -3831,12 +4376,16 @@ private bool Callback(IntPtr hWnd, IntPtr lparam) { } // Disposes all top-level Controls on this thread - internal void Dispose() { - for (int i = 0; i < windowCount; i++) { + internal void Dispose() + { + for (int i = 0; i < windowCount; i++) + { IntPtr hWnd = windows[i]; - if (UnsafeNativeMethods.IsWindow(new HandleRef(null, hWnd))) { + if (UnsafeNativeMethods.IsWindow(new HandleRef(null, hWnd))) + { Control c = Control.FromHandle(hWnd); - if (c != null) { + if (c != null) + { c.Dispose(); } } @@ -3844,23 +4393,29 @@ internal void Dispose() { } // Enables/disables all top-level Controls on this thread - internal void Enable(bool state) { + internal void Enable(bool state) + { - if (!onlyWinForms && !state) { + if (!onlyWinForms && !state) + { activeHwnd = UnsafeNativeMethods.GetActiveWindow(); Control activatingControl = Application.ThreadContext.FromCurrent().ActivatingControl; - if (activatingControl != null) { + if (activatingControl != null) + { focusedHwnd = activatingControl.Handle; } - else { + else + { focusedHwnd = UnsafeNativeMethods.GetFocus(); } } - for (int i = 0; i < windowCount; i++) { + for (int i = 0; i < windowCount; i++) + { IntPtr hWnd = windows[i]; Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ComponentManager : Changing enabled on window: " + hWnd.ToString() + " : " + state.ToString()); - if (UnsafeNativeMethods.IsWindow(new HandleRef(null, hWnd))) SafeNativeMethods.EnableWindow(new HandleRef(null, hWnd), state); + if (UnsafeNativeMethods.IsWindow(new HandleRef(null, hWnd))) + SafeNativeMethods.EnableWindow(new HandleRef(null, hWnd), state); } // OpenFileDialog is not returning the focus the way other dialogs do. @@ -3871,36 +4426,43 @@ internal void Enable(bool state) { // But, DON'T change other people's state when we're simply // responding to external MSOCM events about modality. When we are, // we are created with a TRUE for onlyWinForms. - if (!onlyWinForms && state) { - if (activeHwnd != IntPtr.Zero && UnsafeNativeMethods.IsWindow(new HandleRef(null, activeHwnd))) { + if (!onlyWinForms && state) + { + if (activeHwnd != IntPtr.Zero && UnsafeNativeMethods.IsWindow(new HandleRef(null, activeHwnd))) + { UnsafeNativeMethods.SetActiveWindow(new HandleRef(null, activeHwnd)); } - if (focusedHwnd != IntPtr.Zero && UnsafeNativeMethods.IsWindow(new HandleRef(null, focusedHwnd))) { + if (focusedHwnd != IntPtr.Zero && UnsafeNativeMethods.IsWindow(new HandleRef(null, focusedHwnd))) + { UnsafeNativeMethods.SetFocus(new HandleRef(null, focusedHwnd)); } } } } - private class ModalApplicationContext : ApplicationContext { + private class ModalApplicationContext : ApplicationContext + { private ThreadContext parentWindowContext; private delegate void ThreadWindowCallback(ThreadContext context, bool onlyWinForms); - - public ModalApplicationContext(Form modalForm) : base(modalForm) { - } - public void DisableThreadWindows(bool disable, bool onlyWinForms) { + public ModalApplicationContext(Form modalForm) : base(modalForm) + { + } + + public void DisableThreadWindows(bool disable, bool onlyWinForms) + { Control parentControl = null; - + // Get ahold of the parent HWND -- if it's a different thread we need to do // do the disable over there too. Note we only do this if we're parented by a Windows Forms // parent. // - if (MainForm != null && MainForm.IsHandleCreated) { + if (MainForm != null && MainForm.IsHandleCreated) + { // get ahold of the parenting control // @@ -3908,43 +4470,52 @@ public void DisableThreadWindows(bool disable, bool onlyWinForms) { parentControl = Control.FromHandle(parentHandle); - if (parentControl != null && parentControl.InvokeRequired) { - parentWindowContext = GetContextForHandle(new HandleRef(this, parentHandle)); + if (parentControl != null && parentControl.InvokeRequired) + { + parentWindowContext = GetContextForHandle(new HandleRef(this, parentHandle)); } - else { + else + { parentWindowContext = null; } } // if we got a thread context, that means our parent is in a different thread, make the call on that thread. // - if (parentWindowContext != null) { + if (parentWindowContext != null) + { // in case we've already torn down, ask the context for this. // - if (parentControl == null) { + if (parentControl == null) + { parentControl = parentWindowContext.ApplicationContext.MainForm; } - - if (disable) { - parentControl.Invoke(new ThreadWindowCallback(DisableThreadWindowsCallback), new object[]{parentWindowContext, onlyWinForms}); + + if (disable) + { + parentControl.Invoke(new ThreadWindowCallback(DisableThreadWindowsCallback), new object[] { parentWindowContext, onlyWinForms }); + } + else + { + parentControl.Invoke(new ThreadWindowCallback(EnableThreadWindowsCallback), new object[] { parentWindowContext, onlyWinForms }); } - else { - parentControl.Invoke(new ThreadWindowCallback(EnableThreadWindowsCallback), new object[]{parentWindowContext, onlyWinForms}); - } } } - private void DisableThreadWindowsCallback(ThreadContext context, bool onlyWinForms) { - context.DisableWindowsForModalLoop(onlyWinForms, this); + private void DisableThreadWindowsCallback(ThreadContext context, bool onlyWinForms) + { + context.DisableWindowsForModalLoop(onlyWinForms, this); } - private void EnableThreadWindowsCallback(ThreadContext context, bool onlyWinForms) { - context.EnableWindowsForModalLoop(onlyWinForms, this); + private void EnableThreadWindowsCallback(ThreadContext context, bool onlyWinForms) + { + context.EnableWindowsForModalLoop(onlyWinForms, this); } - protected override void ExitThreadCore() { + protected override void ExitThreadCore() + { // do nothing... modal dialogs exit by setting dialog result } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ApplicationContext.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ApplicationContext.cs index b786656f38d..a1d24ab7fd9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ApplicationContext.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ApplicationContext.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Diagnostics; using System.ComponentModel; @@ -14,14 +15,16 @@ namespace System.Windows.Forms { /// context listens to the close event on the mainForm, then exits the /// thread's message loop. /// - public class ApplicationContext : IDisposable { + public class ApplicationContext : IDisposable + { Form mainForm; object userData; /// /// Creates a new ApplicationContext with no mainForm. /// - public ApplicationContext() : this(null) { + public ApplicationContext() : this(null) + { } /// @@ -29,11 +32,13 @@ public ApplicationContext() : this(null) { /// If OnMainFormClosed is not overriden, the thread's message /// loop will be terminated when mainForm is closed. /// - public ApplicationContext(Form mainForm) { + public ApplicationContext(Form mainForm) + { this.MainForm = mainForm; } - ~ApplicationContext() { + ~ApplicationContext() + { Dispose(false); } @@ -43,19 +48,24 @@ public ApplicationContext(Form mainForm) { /// If OnMainFormClosed is not overriden, the thread's message /// loop will be terminated when mainForm is closed. /// - public Form MainForm { - get { + public Form MainForm + { + get + { return mainForm; } - set { + set + { EventHandler onClose = new EventHandler(OnMainFormDestroy); - if (mainForm != null) { + if (mainForm != null) + { mainForm.HandleDestroyed -= onClose; } mainForm = value; - if (mainForm != null) { + if (mainForm != null) + { mainForm.HandleDestroyed += onClose; } } @@ -69,11 +79,14 @@ public Form MainForm { DefaultValue(null), TypeConverter(typeof(StringConverter)), ] - public object Tag { - get { + public object Tag + { + get + { return userData; } - set { + set + { userData = value; } } @@ -89,15 +102,20 @@ public object Tag { /// called immediately after the thread's message loop is terminated. /// Application will dispose all forms on this thread by default. /// - public void Dispose() { + public void Dispose() + { Dispose(true); GC.SuppressFinalize(this); } - protected virtual void Dispose(bool disposing) { - if (disposing) { - if (mainForm != null) { - if (!mainForm.IsDisposed) { + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + if (mainForm != null) + { + if (!mainForm.IsDisposed) + { mainForm.Dispose(); } mainForm = null; @@ -109,15 +127,18 @@ protected virtual void Dispose(bool disposing) { /// Causes the thread's message loop to be terminated. This /// will call ExitThreadCore. /// - public void ExitThread() { + public void ExitThread() + { ExitThreadCore(); } /// /// Causes the thread's message loop to be terminated. /// - protected virtual void ExitThreadCore() { - if (ThreadExit != null) { + protected virtual void ExitThreadCore() + { + if (ThreadExit != null) + { ThreadExit(this, EventArgs.Empty); } } @@ -126,17 +147,20 @@ protected virtual void ExitThreadCore() { /// Called when the mainForm is closed. The default implementation /// of this will call ExitThreadCore. /// - protected virtual void OnMainFormClosed(object sender, EventArgs e) { + protected virtual void OnMainFormClosed(object sender, EventArgs e) + { ExitThreadCore(); } - + /// /// Called when the mainForm is closed. The default implementation /// of this will call ExitThreadCore. /// - private void OnMainFormDestroy(object sender, EventArgs e) { + private void OnMainFormDestroy(object sender, EventArgs e) + { Form form = (Form)sender; - if (!form.RecreatingHandle) { + if (!form.RecreatingHandle) + { form.HandleDestroyed -= new EventHandler(OnMainFormDestroy); OnMainFormClosed(sender, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ArrangeDirection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ArrangeDirection.cs index 6022a6f2a97..1e15c210e61 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ArrangeDirection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ArrangeDirection.cs @@ -12,7 +12,7 @@ namespace System.Windows.Forms /// [ComVisible(true)] [Flags] - [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "Maps to native enum")] + [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "Maps to native enum")] public enum ArrangeDirection { /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ArrangedElement.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ArrangedElement.cs index ae2f91f8eb0..854fbdb3181 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ArrangedElement.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ArrangedElement.cs @@ -2,179 +2,219 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { - - - - using System.Drawing; - using System.Windows.Forms.Layout; - using System.Collections.Specialized; - using System.Collections; - using System.ComponentModel; - using System.Diagnostics; - - - internal abstract class ArrangedElement : Component, IArrangedElement { - - /// - /// - - private Rectangle bounds = Rectangle.Empty; - private IArrangedElement parent = null; - private BitVector32 state = new BitVector32(); - private PropertyStore propertyStore = new PropertyStore(); // Contains all properties that are not always set. - private int suspendCount = 0; - - private static readonly int stateVisible = BitVector32.CreateMask(); - private static readonly int stateDisposing = BitVector32.CreateMask(stateVisible); - private static readonly int stateLocked = BitVector32.CreateMask(stateDisposing); - - - private static readonly int PropControlsCollection = PropertyStore.CreateKey(); - private Control spacer = new Control(); - - internal ArrangedElement() { +namespace System.Windows.Forms +{ + + + + using System.Drawing; + using System.Windows.Forms.Layout; + using System.Collections.Specialized; + using System.Collections; + using System.ComponentModel; + using System.Diagnostics; + + + internal abstract class ArrangedElement : Component, IArrangedElement + { + + /// + /// + + private Rectangle bounds = Rectangle.Empty; + private IArrangedElement parent = null; + private BitVector32 state = new BitVector32(); + private PropertyStore propertyStore = new PropertyStore(); // Contains all properties that are not always set. + private int suspendCount = 0; + + private static readonly int stateVisible = BitVector32.CreateMask(); + private static readonly int stateDisposing = BitVector32.CreateMask(stateVisible); + private static readonly int stateLocked = BitVector32.CreateMask(stateDisposing); + + + private static readonly int PropControlsCollection = PropertyStore.CreateKey(); + private Control spacer = new Control(); + + internal ArrangedElement() + { this.Padding = DefaultPadding; - this.Margin = DefaultMargin; + this.Margin = DefaultMargin; state[stateVisible] = true; - } - - public Rectangle Bounds { - get { - return bounds; - } - } - - ArrangedElementCollection IArrangedElement.Children { - get { return GetChildren(); } - } - - IArrangedElement IArrangedElement.Container { - get { return GetContainer(); } - } - - protected virtual Padding DefaultMargin { - get { return Padding.Empty; } - } - - protected virtual Padding DefaultPadding { - get { return Padding.Empty; } - } - - public virtual Rectangle DisplayRectangle { - get { - Rectangle displayRectangle = this.Bounds; - return displayRectangle; - } - } - - public abstract LayoutEngine LayoutEngine { - get; - } - - public Padding Margin { - get { return CommonProperties.GetMargin(this); } - set { - - Debug.Assert((value.Right >= 0 && value.Left >= 0 && value.Top >= 0 && value.Bottom >=0), "who's setting margin negative?"); + } + + public Rectangle Bounds + { + get + { + return bounds; + } + } + + ArrangedElementCollection IArrangedElement.Children + { + get { return GetChildren(); } + } + + IArrangedElement IArrangedElement.Container + { + get { return GetContainer(); } + } + + protected virtual Padding DefaultMargin + { + get { return Padding.Empty; } + } + + protected virtual Padding DefaultPadding + { + get { return Padding.Empty; } + } + + public virtual Rectangle DisplayRectangle + { + get + { + Rectangle displayRectangle = this.Bounds; + return displayRectangle; + } + } + + public abstract LayoutEngine LayoutEngine + { + get; + } + + public Padding Margin + { + get { return CommonProperties.GetMargin(this); } + set + { + + Debug.Assert((value.Right >= 0 && value.Left >= 0 && value.Top >= 0 && value.Bottom >= 0), "who's setting margin negative?"); + value = LayoutUtils.ClampNegativePaddingToZero(value); + if (Margin != value) + { CommonProperties.SetMargin(this, value); } + + } + } + + public virtual Padding Padding + { + get { return CommonProperties.GetPadding(this, DefaultPadding); } + set + { + Debug.Assert((value.Right >= 0 && value.Left >= 0 && value.Top >= 0 && value.Bottom >= 0), "who's setting padding negative?"); value = LayoutUtils.ClampNegativePaddingToZero(value); - if (Margin != value ) { CommonProperties.SetMargin(this, value); } - - } - } - - public virtual Padding Padding { - get { return CommonProperties.GetPadding(this, DefaultPadding); } - set { - Debug.Assert((value.Right >= 0 && value.Left >= 0 && value.Top >= 0 && value.Bottom >=0), "who's setting padding negative?"); - value = LayoutUtils.ClampNegativePaddingToZero(value); - if (Padding != value) { CommonProperties.SetPadding(this, value); } - } - } - - public virtual IArrangedElement Parent { - get { - return parent; - } - set { - parent = value as IArrangedElement; - } - } - - public virtual bool ParticipatesInLayout { - get { - return Visible; - } - } - - PropertyStore IArrangedElement.Properties { - get { - return this.Properties; - } - } - - - private PropertyStore Properties { - get { - return propertyStore; - } - } - - public virtual bool Visible { - get { - return state[stateVisible]; - } - set { - if ( state[stateVisible] != value) { - state[stateVisible] = value; - if (Parent != null){ - LayoutTransaction.DoLayout(this.Parent, this, PropertyNames.Visible); - } - } - } - } - - protected abstract IArrangedElement GetContainer(); - - protected abstract ArrangedElementCollection GetChildren(); - - public virtual Size GetPreferredSize(Size constrainingSize) { - Size preferredSize = LayoutEngine.GetPreferredSize(this, constrainingSize - Padding.Size) + Padding.Size; - - return preferredSize; - } - - public virtual void PerformLayout(IArrangedElement container, string propertyName) { - if (suspendCount <= 0) { - OnLayout(new LayoutEventArgs(container, propertyName)); - } - } - - protected virtual void OnLayout(LayoutEventArgs e) { - bool parentNeedsLayout = LayoutEngine.Layout(this, e); - } - - protected virtual void OnBoundsChanged(Rectangle oldBounds, Rectangle newBounds) { - ((IArrangedElement)this).PerformLayout((IArrangedElement)this, PropertyNames.Size); - } - - public void SetBounds(Rectangle bounds, BoundsSpecified specified) { - // in this case the parent is telling us to refresh our bounds - dont - // call PerformLayout - SetBoundsCore(bounds, specified); - } - - - protected virtual void SetBoundsCore(Rectangle bounds, BoundsSpecified specified) { - if (bounds != this.bounds) { - Rectangle oldBounds = this.bounds; - - this.bounds = bounds; - OnBoundsChanged(oldBounds, bounds); - } - } - - } + if (Padding != value) + { CommonProperties.SetPadding(this, value); } + } + } + + public virtual IArrangedElement Parent + { + get + { + return parent; + } + set + { + parent = value as IArrangedElement; + } + } + + public virtual bool ParticipatesInLayout + { + get + { + return Visible; + } + } + + PropertyStore IArrangedElement.Properties + { + get + { + return this.Properties; + } + } + + + private PropertyStore Properties + { + get + { + return propertyStore; + } + } + + public virtual bool Visible + { + get + { + return state[stateVisible]; + } + set + { + if (state[stateVisible] != value) + { + state[stateVisible] = value; + if (Parent != null) + { + LayoutTransaction.DoLayout(this.Parent, this, PropertyNames.Visible); + } + } + } + } + + protected abstract IArrangedElement GetContainer(); + + protected abstract ArrangedElementCollection GetChildren(); + + public virtual Size GetPreferredSize(Size constrainingSize) + { + Size preferredSize = LayoutEngine.GetPreferredSize(this, constrainingSize - Padding.Size) + Padding.Size; + + return preferredSize; + } + + public virtual void PerformLayout(IArrangedElement container, string propertyName) + { + if (suspendCount <= 0) + { + OnLayout(new LayoutEventArgs(container, propertyName)); + } + } + + protected virtual void OnLayout(LayoutEventArgs e) + { + bool parentNeedsLayout = LayoutEngine.Layout(this, e); + } + + protected virtual void OnBoundsChanged(Rectangle oldBounds, Rectangle newBounds) + { + ((IArrangedElement)this).PerformLayout((IArrangedElement)this, PropertyNames.Size); + } + + public void SetBounds(Rectangle bounds, BoundsSpecified specified) + { + // in this case the parent is telling us to refresh our bounds - dont + // call PerformLayout + SetBoundsCore(bounds, specified); + } + + + protected virtual void SetBoundsCore(Rectangle bounds, BoundsSpecified specified) + { + if (bounds != this.bounds) + { + Rectangle oldBounds = this.bounds; + + this.bounds = bounds; + OnBoundsChanged(oldBounds, bounds); + } + } + + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AssemblyAttributes.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AssemblyAttributes.cs index 43c789b56b4..48adf2ce627 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AssemblyAttributes.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AssemblyAttributes.cs @@ -6,14 +6,14 @@ using System.Runtime.CompilerServices; -[assembly:DependencyAttribute("System,", LoadHint.Always)] -[assembly:DependencyAttribute("System.Drawing,", LoadHint.Always)] -[assembly:DependencyAttribute("System.Core", LoadHint.Sometimes)] +[assembly: DependencyAttribute("System,", LoadHint.Always)] +[assembly: DependencyAttribute("System.Drawing,", LoadHint.Always)] +[assembly: DependencyAttribute("System.Core", LoadHint.Sometimes)] // This is now trun on by default, use source file NO_RUNTIMECOMPATIBILITY_ATTRIBUTE flag to control this // [assembly:RuntimeCompatibility(WrapNonExceptionThrows = true)] -[assembly:System.Runtime.CompilerServices.StringFreezingAttribute()] -[assembly:System.Runtime.InteropServices.TypeLibVersion(2, 4)] - +[assembly: System.Runtime.CompilerServices.StringFreezingAttribute()] +[assembly: System.Runtime.InteropServices.TypeLibVersion(2, 4)] + // Opts into the VS loading icons from the Icon Satellite assembly: System.Windows.Forms.VisualStudio..0.dll -[assembly:System.Drawing.BitmapSuffixInSatelliteAssemblyAttribute()] +[assembly: System.Drawing.BitmapSuffixInSatelliteAssemblyAttribute()] diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AutoCompleteSource.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AutoCompleteSource.cs index 13a79a63eaa..8bf234429ae 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AutoCompleteSource.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AutoCompleteSource.cs @@ -30,7 +30,7 @@ public enum AutoCompleteSource /// /// This option is equivalent to HistoryList | RecentlyUsedList. /// - AllUrl = HistoryList | RecentlyUsedList, + AllUrl = HistoryList | RecentlyUsedList, /// /// This option is equivalent to FILESYSTEM | AllUrl. This is the default diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AutoCompleteStringCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AutoCompleteStringCollection.cs index a0582487268..60ed252ff31 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AutoCompleteStringCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AutoCompleteStringCollection.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -12,25 +13,29 @@ namespace System.Windows.Forms { /// /// Represents a collection of strings. /// - public class AutoCompleteStringCollection : IList { + public class AutoCompleteStringCollection : IList + { CollectionChangeEventHandler onCollectionChanged; private ArrayList data = new ArrayList(); - + public AutoCompleteStringCollection() { - + } /// /// Represents the entry at the specified index of the . /// - public string this[int index] { - get { + public string this[int index] + { + get + { return ((string)data[index]); } - set { - OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, data[index])); + set + { + OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, data[index])); data[index] = value; OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, value)); } @@ -40,8 +45,10 @@ public string this[int index] { /// Gets the number of strings in the /// . /// - public int Count { - get { + public int Count + { + get + { return data.Count; } } @@ -82,8 +89,9 @@ protected void OnCollectionChanged(CollectionChangeEventArgs e) /// Adds a string with the specified value to the /// . /// - public int Add(string value) { - int index = data.Add(value); + public int Add(string value) + { + int index = data.Add(value); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, value)); return index; } @@ -91,8 +99,10 @@ public int Add(string value) { /// /// Copies the elements of a string array to the end of the . /// - public void AddRange(string[] value) { - if (value == null) { + public void AddRange(string[] value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } data.AddRange(value); @@ -103,7 +113,8 @@ public void AddRange(string[] value) { /// Removes all the strings from the /// . /// - public void Clear() { + public void Clear() + { data.Clear(); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null)); } @@ -113,7 +124,8 @@ public void Clear() { /// contains a string with the specified /// value. /// - public bool Contains(string value) { + public bool Contains(string value) + { return data.Contains(value); } @@ -121,7 +133,8 @@ public bool Contains(string value) { /// Copies the values to a one-dimensional instance at the /// specified index. /// - public void CopyTo(string[] array, int index) { + public void CopyTo(string[] array, int index) + { data.CopyTo(array, index); } @@ -129,7 +142,8 @@ public void CopyTo(string[] array, int index) { /// Returns the index of the first occurrence of a string in /// the . /// - public int IndexOf(string value) { + public int IndexOf(string value) + { return data.IndexOf(value); } @@ -137,7 +151,8 @@ public int IndexOf(string value) { /// Inserts a string into the at the specified /// index. /// - public void Insert(int index, string value) { + public void Insert(int index, string value) + { data.Insert(index, value); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, value)); } @@ -145,8 +160,10 @@ public void Insert(int index, string value) { /// /// Gets a value indicating whether the is read-only. /// - public bool IsReadOnly { - get { + public bool IsReadOnly + { + get + { return false; } } @@ -156,8 +173,10 @@ public bool IsReadOnly { /// /// is synchronized (thread-safe). /// - public bool IsSynchronized { - get { + public bool IsSynchronized + { + get + { return false; } } @@ -166,7 +185,8 @@ public bool IsSynchronized { /// Removes a specific string from the /// . /// - public void Remove(string value) { + public void Remove(string value) + { data.Remove(value); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, value)); } @@ -174,7 +194,8 @@ public void Remove(string value) { /// /// Removes the string at the specified index of the . /// - public void RemoveAt(int index) { + public void RemoveAt(int index) + { string value = (string)data[index]; data.RemoveAt(index); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, value)); @@ -185,43 +206,53 @@ public void RemoveAt(int index) { /// public object SyncRoot => this; - object IList.this[int index] { - get { + object IList.this[int index] + { + get + { return this[index]; } - set { + set + { this[index] = (string)value; } } - int IList.Add(object value) { + int IList.Add(object value) + { return Add((string)value); } - bool IList.Contains(object value) { - return Contains((string) value); + bool IList.Contains(object value) + { + return Contains((string)value); } - int IList.IndexOf(object value) { + int IList.IndexOf(object value) + { return IndexOf((string)value); } - void IList.Insert(int index, object value) { + void IList.Insert(int index, object value) + { Insert(index, (string)value); } - void IList.Remove(object value) { + void IList.Remove(object value) + { Remove((string)value); } - void ICollection.CopyTo(Array array, int index) { + void ICollection.CopyTo(Array array, int index) + { data.CopyTo(array, index); } - public IEnumerator GetEnumerator() { + public IEnumerator GetEnumerator() + { return data.GetEnumerator(); } - + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Automation/AutomationNotificationProcessing.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Automation/AutomationNotificationProcessing.cs index 539f2df8501..7609e7f2979 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Automation/AutomationNotificationProcessing.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Automation/AutomationNotificationProcessing.cs @@ -2,12 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.Automation { +namespace System.Windows.Forms.Automation +{ /// /// Specifies the order in which to process a notification. /// - public enum AutomationNotificationProcessing { + public enum AutomationNotificationProcessing + { /// /// These notifications should be presented to the user as soon as possible. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs index caafbcbc709..808f08b0674 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System; using System.Collections; @@ -14,7 +15,7 @@ namespace System.Windows.Forms { using System.Configuration.Assemblies; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; - using System.Drawing; + using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Design; using System.Globalization; @@ -44,11 +45,12 @@ namespace System.Windows.Forms { DefaultEvent(nameof(Enter)), Designer("System.Windows.Forms.Design.AxHostDesigner, " + AssemblyRef.SystemDesign), ] - public abstract class AxHost : Control, ISupportInitialize, ICustomTypeDescriptor { + public abstract class AxHost : Control, ISupportInitialize, ICustomTypeDescriptor + { - private static TraceSwitch AxHTraceSwitch = new TraceSwitch("AxHTrace", "ActiveX handle tracing"); - private static TraceSwitch AxPropTraceSwitch = new TraceSwitch("AxPropTrace", "ActiveX property tracing"); - private static TraceSwitch AxHostSwitch = new TraceSwitch("AxHost", "ActiveX host creation"); + private static TraceSwitch AxHTraceSwitch = new TraceSwitch("AxHTrace", "ActiveX handle tracing"); + private static TraceSwitch AxPropTraceSwitch = new TraceSwitch("AxPropTrace", "ActiveX property tracing"); + private static TraceSwitch AxHostSwitch = new TraceSwitch("AxHost", "ActiveX host creation"); private static BooleanSwitch AxIgnoreTMSwitch = new BooleanSwitch("AxIgnoreTM", "ActiveX switch to ignore thread models"); private static BooleanSwitch AxAlwaysSaveSwitch = new BooleanSwitch("AxAlwaysSave", "ActiveX to save all controls regardless of their IsDirty function return value"); @@ -56,13 +58,14 @@ public abstract class AxHost : Control, ISupportInitialize, ICustomTypeDescripto /// Flags which may be passed to the AxHost constructor /// [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] - internal class AxFlags { + internal class AxFlags + { /// /// Indicates that the context menu for the control should not contain an /// "Edit" verb unless the activeX controls itself decides to proffer it. /// By default, all wrapped activeX controls will contain an edit verb. /// - internal const int PreventEditMode = 0x1; + internal const int PreventEditMode = 0x1; /// /// Indicated that the context menu for the control should contain @@ -75,15 +78,15 @@ internal class AxFlags { /// this flag.] /// internal const int IncludePropertiesVerb = 0x2; - + /// /// - internal const int IgnoreThreadModel = 0x10000000; + internal const int IgnoreThreadModel = 0x10000000; } private static COMException E_NOTIMPL = new COMException(SR.AXNotImplemented, unchecked((int)0x80000001)); private static COMException E_INVALIDARG = new COMException(SR.AXInvalidArgument, unchecked((int)0x80070057)); - private static COMException E_FAIL = new COMException(SR.AXUnknownError, unchecked((int)0x80004005)); + private static COMException E_FAIL = new COMException(SR.AXUnknownError, unchecked((int)0x80004005)); private static COMException E_NOINTERFACE = new COMException(SR.AxInterfaceNotSupported, unchecked((int)0x80004002)); private const int INPROC_SERVER = 1; @@ -106,7 +109,7 @@ internal class AxFlags { private const int OLEIVERB_SHOW = -1; private const int OLEIVERB_HIDE = -3; private const int OLEIVERB_UIACTIVATE = -4; - private const int OLEIVERB_INPLACEACTIVATE =-5; + private const int OLEIVERB_INPLACEACTIVATE = -5; private const int OLEIVERB_PROPERTIES = -7; private const int OLEIVERB_PRIMARY = 0; @@ -116,17 +119,17 @@ internal class AxFlags { private static int logPixelsX = -1; private static int logPixelsY = -1; - private static Guid icf2_Guid = typeof(UnsafeNativeMethods.IClassFactory2).GUID; - private static Guid ifont_Guid = typeof(UnsafeNativeMethods.IFont).GUID; - private static Guid ifontDisp_Guid = typeof(SafeNativeMethods.IFontDisp).GUID; - private static Guid ipicture_Guid = typeof(UnsafeNativeMethods.IPicture).GUID; - private static Guid ipictureDisp_Guid = typeof(UnsafeNativeMethods.IPictureDisp).GUID; - private static Guid ivbformat_Guid = typeof(UnsafeNativeMethods.IVBFormat).GUID; - private static Guid ioleobject_Guid = typeof(UnsafeNativeMethods.IOleObject).GUID; - private static Guid dataSource_Guid = new Guid("{7C0FFAB3-CD84-11D0-949A-00A0C91110ED}"); - private static Guid windowsMediaPlayer_Clsid = new Guid("{22d6f312-b0f6-11d0-94ab-0080c74c7e95}"); - private static Guid comctlImageCombo_Clsid = new Guid("{a98a24c0-b06f-3684-8c12-c52ae341e0bc}"); - private static Guid maskEdit_Clsid = new Guid("{c932ba85-4374-101b-a56c-00aa003668dc}"); + private static Guid icf2_Guid = typeof(UnsafeNativeMethods.IClassFactory2).GUID; + private static Guid ifont_Guid = typeof(UnsafeNativeMethods.IFont).GUID; + private static Guid ifontDisp_Guid = typeof(SafeNativeMethods.IFontDisp).GUID; + private static Guid ipicture_Guid = typeof(UnsafeNativeMethods.IPicture).GUID; + private static Guid ipictureDisp_Guid = typeof(UnsafeNativeMethods.IPictureDisp).GUID; + private static Guid ivbformat_Guid = typeof(UnsafeNativeMethods.IVBFormat).GUID; + private static Guid ioleobject_Guid = typeof(UnsafeNativeMethods.IOleObject).GUID; + private static Guid dataSource_Guid = new Guid("{7C0FFAB3-CD84-11D0-949A-00A0C91110ED}"); + private static Guid windowsMediaPlayer_Clsid = new Guid("{22d6f312-b0f6-11d0-94ab-0080c74c7e95}"); + private static Guid comctlImageCombo_Clsid = new Guid("{a98a24c0-b06f-3684-8c12-c52ae341e0bc}"); + private static Guid maskEdit_Clsid = new Guid("{c932ba85-4374-101b-a56c-00aa003668dc}"); // Static state for perf optimization // @@ -134,35 +137,35 @@ internal class AxFlags { // BitVector32 masks for various internal state flags. // - private static readonly int ocxStateSet = BitVector32.CreateMask(); - private static readonly int editorRefresh = BitVector32.CreateMask(ocxStateSet); - private static readonly int listeningToIdle = BitVector32.CreateMask(editorRefresh); - private static readonly int refreshProperties = BitVector32.CreateMask(listeningToIdle); - - private static readonly int checkedIppb = BitVector32.CreateMask(refreshProperties); - private static readonly int checkedCP = BitVector32.CreateMask(checkedIppb); - private static readonly int fNeedOwnWindow = BitVector32.CreateMask(checkedCP); - private static readonly int fOwnWindow = BitVector32.CreateMask(fNeedOwnWindow); - - private static readonly int fSimpleFrame = BitVector32.CreateMask(fOwnWindow); - private static readonly int fFakingWindow = BitVector32.CreateMask(fSimpleFrame); - private static readonly int rejectSelection = BitVector32.CreateMask(fFakingWindow); - private static readonly int ownDisposing = BitVector32.CreateMask(rejectSelection); - - private static readonly int sinkAttached = BitVector32.CreateMask(ownDisposing); - private static readonly int disposed = BitVector32.CreateMask(sinkAttached); - private static readonly int manualUpdate = BitVector32.CreateMask(disposed); - private static readonly int addedSelectionHandler = BitVector32.CreateMask(manualUpdate); - - private static readonly int valueChanged = BitVector32.CreateMask(addedSelectionHandler); - private static readonly int handlePosRectChanged = BitVector32.CreateMask(valueChanged); - private static readonly int siteProcessedInputKey = BitVector32.CreateMask(handlePosRectChanged); - private static readonly int needLicenseKey = BitVector32.CreateMask(siteProcessedInputKey); - - private static readonly int inTransition = BitVector32.CreateMask(needLicenseKey); - private static readonly int processingKeyUp = BitVector32.CreateMask(inTransition); - private static readonly int assignUniqueID = BitVector32.CreateMask(processingKeyUp); - private static readonly int renameEventHooked = BitVector32.CreateMask(assignUniqueID); + private static readonly int ocxStateSet = BitVector32.CreateMask(); + private static readonly int editorRefresh = BitVector32.CreateMask(ocxStateSet); + private static readonly int listeningToIdle = BitVector32.CreateMask(editorRefresh); + private static readonly int refreshProperties = BitVector32.CreateMask(listeningToIdle); + + private static readonly int checkedIppb = BitVector32.CreateMask(refreshProperties); + private static readonly int checkedCP = BitVector32.CreateMask(checkedIppb); + private static readonly int fNeedOwnWindow = BitVector32.CreateMask(checkedCP); + private static readonly int fOwnWindow = BitVector32.CreateMask(fNeedOwnWindow); + + private static readonly int fSimpleFrame = BitVector32.CreateMask(fOwnWindow); + private static readonly int fFakingWindow = BitVector32.CreateMask(fSimpleFrame); + private static readonly int rejectSelection = BitVector32.CreateMask(fFakingWindow); + private static readonly int ownDisposing = BitVector32.CreateMask(rejectSelection); + + private static readonly int sinkAttached = BitVector32.CreateMask(ownDisposing); + private static readonly int disposed = BitVector32.CreateMask(sinkAttached); + private static readonly int manualUpdate = BitVector32.CreateMask(disposed); + private static readonly int addedSelectionHandler = BitVector32.CreateMask(manualUpdate); + + private static readonly int valueChanged = BitVector32.CreateMask(addedSelectionHandler); + private static readonly int handlePosRectChanged = BitVector32.CreateMask(valueChanged); + private static readonly int siteProcessedInputKey = BitVector32.CreateMask(handlePosRectChanged); + private static readonly int needLicenseKey = BitVector32.CreateMask(siteProcessedInputKey); + + private static readonly int inTransition = BitVector32.CreateMask(needLicenseKey); + private static readonly int processingKeyUp = BitVector32.CreateMask(inTransition); + private static readonly int assignUniqueID = BitVector32.CreateMask(processingKeyUp); + private static readonly int renameEventHooked = BitVector32.CreateMask(assignUniqueID); private BitVector32 axState = new BitVector32(); @@ -175,10 +178,10 @@ internal class AxFlags { private int selectionStyle = 0; private int editMode = EDITM_NONE; private int noComponentChange = 0; - + private IntPtr wndprocAddr = IntPtr.Zero; - private Guid clsid; + private Guid clsid; private string text = string.Empty; private string licenseKey = null; @@ -212,7 +215,7 @@ internal class AxFlags { private UnsafeNativeMethods.IPersistStream iPersistStream; private UnsafeNativeMethods.IPersistStreamInit iPersistStreamInit; private UnsafeNativeMethods.IPersistStorage iPersistStorage; - + private AboutBoxDelegate aboutBoxDelegate = null; private EventHandler selectionChangeHandler; @@ -220,11 +223,11 @@ internal class AxFlags { private bool ignoreDialogKeys; private EventHandler onContainerVisibleChanged; - + // These should be in the order given by the PROPCAT_X values // Also, note that they are not to be localized... - private static CategoryAttribute[] categoryNames = new CategoryAttribute [] { + private static CategoryAttribute[] categoryNames = new CategoryAttribute[] { null, new WinCategoryAttribute("Default"), new WinCategoryAttribute("Default"), @@ -242,12 +245,13 @@ internal class AxFlags { private Hashtable objectDefinedCategoryNames = null; // Integer -> String #if DEBUG - static AxHost() { - Debug.Assert((int)DockStyle.None == (int)NativeMethods.ActiveX.ALIGN_NO_CHANGE,"align value mismatch"); - Debug.Assert((int)DockStyle.Top == (int)NativeMethods.ActiveX.ALIGN_TOP,"align value mismatch"); - Debug.Assert((int)DockStyle.Bottom == (int)NativeMethods.ActiveX.ALIGN_BOTTOM,"align value mismatch"); - Debug.Assert((int)DockStyle.Left == (int)NativeMethods.ActiveX.ALIGN_LEFT,"align value mismatch"); - Debug.Assert((int)DockStyle.Right == (int)NativeMethods.ActiveX.ALIGN_RIGHT,"align value mismatch"); + static AxHost() + { + Debug.Assert((int)DockStyle.None == (int)NativeMethods.ActiveX.ALIGN_NO_CHANGE, "align value mismatch"); + Debug.Assert((int)DockStyle.Top == (int)NativeMethods.ActiveX.ALIGN_TOP, "align value mismatch"); + Debug.Assert((int)DockStyle.Bottom == (int)NativeMethods.ActiveX.ALIGN_BOTTOM, "align value mismatch"); + Debug.Assert((int)DockStyle.Left == (int)NativeMethods.ActiveX.ALIGN_LEFT, "align value mismatch"); + Debug.Assert((int)DockStyle.Right == (int)NativeMethods.ActiveX.ALIGN_RIGHT, "align value mismatch"); Debug.Assert((int)MouseButtons.Left == 0x00100000, "mb.left mismatch"); Debug.Assert((int)MouseButtons.Right == 0x00200000, "mb.right mismatch"); Debug.Assert((int)MouseButtons.Middle == 0x00400000, "mb.middle mismatch"); @@ -261,15 +265,18 @@ static AxHost() { /// Creates a new instance of a control which wraps an activeX control given by the /// clsid parameter and flags of 0. /// - protected AxHost(string clsid) : this(clsid, 0) { + protected AxHost(string clsid) : this(clsid, 0) + { } /// /// Creates a new instance of a control which wraps an activeX control given by the /// clsid and flags parameters. /// - protected AxHost(string clsid, int flags) : base() { - if (Application.OleRequired() != ApartmentState.STA) { + protected AxHost(string clsid, int flags) : base() + { + if (Application.OleRequired() != ApartmentState.STA) + { throw new ThreadStateException(string.Format(SR.AXMTAThread, clsid)); } @@ -286,8 +293,10 @@ protected AxHost(string clsid, int flags) : base() { this.onContainerVisibleChanged = new EventHandler(this.OnContainerVisibleChanged); } - private bool CanUIActivate { - get { + private bool CanUIActivate + { + get + { return IsUserMode() || editMode != EDITM_NONE; } } @@ -295,21 +304,26 @@ private bool CanUIActivate { /// /// Returns the CreateParams used to create the handle for this control. /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; - if (axState[fOwnWindow] && IsUserMode()) { + if (axState[fOwnWindow] && IsUserMode()) + { cp.Style = cp.Style & (~NativeMethods.WS_VISIBLE); } return cp; } } - private bool GetAxState(int mask) { + private bool GetAxState(int mask) + { return this.axState[mask]; } - - private void SetAxState(int mask, bool value) { + + private void SetAxState(int mask, bool value) + { this.axState[mask] = value; } @@ -319,14 +333,17 @@ private void SetAxState(int mask, bool value) { /// their own interfaces. getOcx() should not usually be called before this function. /// Note: calling begin will result in a call to this function. /// - protected virtual void AttachInterfaces() { + protected virtual void AttachInterfaces() + { } - private void RealizeStyles() { + private void RealizeStyles() + { SetStyle(ControlStyles.UserPaint, false); int bits = 0; int hr = GetOleObject().GetMiscStatus(NativeMethods.ActiveX.DVASPECT_CONTENT, out bits); - if (!NativeMethods.Failed(hr)) { + if (!NativeMethods.Failed(hr)) + { miscStatusBits = bits; ParseMiscBits(miscStatusBits); } @@ -335,36 +352,45 @@ private void RealizeStyles() { // Control overrides: [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Color BackColor { - get { + public override Color BackColor + { + get + { return base.BackColor; } - set { + set + { base.BackColor = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } @@ -387,35 +413,43 @@ public override ImageLayout BackgroundImageLayout { } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler MouseClick { + new public event EventHandler MouseClick + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "MouseClick")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler MouseDoubleClick { + new public event EventHandler MouseDoubleClick + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "MouseDoubleClick")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Cursor Cursor { - get { + public override Cursor Cursor + { + get + { return base.Cursor; } - set { + set + { base.Cursor = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ContextMenu ContextMenu { - get { + public override ContextMenu ContextMenu + { + get + { return base.ContextMenu; } - set { + set + { base.ContextMenu = value; } } @@ -424,89 +458,110 @@ public override ContextMenu ContextMenu { /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(75, 23); } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public virtual new bool Enabled { - get { + public virtual new bool Enabled + { + get + { return base.Enabled; } - set { + set + { base.Enabled = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Font Font { - get { + public override Font Font + { + get + { return base.Font; } - set { + set + { base.Font = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Color ForeColor { - get { + public override Color ForeColor + { + get + { return base.ForeColor; } - set { + set + { base.ForeColor = value; } } [ - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Localizable(true) ] - public new virtual bool RightToLeft { - get { + public new virtual bool RightToLeft + { + get + { RightToLeft rtol = base.RightToLeft; return rtol == System.Windows.Forms.RightToLeft.Yes; } - set { + set + { base.RightToLeft = (value) ? System.Windows.Forms.RightToLeft.Yes : System.Windows.Forms.RightToLeft.No; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override string Text { - get { + public override string Text + { + get + { return text; } - set { + set + { text = value; } } - internal override bool CanAccessProperties { - get { + internal override bool CanAccessProperties + { + get + { int ocState = GetOcState(); - return(axState[fOwnWindow] && + return (axState[fOwnWindow] && (ocState > OC_RUNNING || (IsUserMode() && ocState >= OC_RUNNING)) || ocState >= OC_INPLACE); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected bool PropsValid() { + protected bool PropsValid() + { return CanAccessProperties; } [EditorBrowsable(EditorBrowsableState.Advanced)] - public void BeginInit() { + public void BeginInit() + { } /// @@ -517,27 +572,35 @@ public void BeginInit() { /// handle, therefore, this control must be parented before begin is called /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public void EndInit() { - if (ParentInternal != null) { + public void EndInit() + { + if (ParentInternal != null) + { ParentInternal.CreateControl(true); ContainerControl f = ContainingControl; - if (f != null) { + if (f != null) + { f.VisibleChanged += this.onContainerVisibleChanged; } } } - private void OnContainerVisibleChanged(object sender, EventArgs e) { + private void OnContainerVisibleChanged(object sender, EventArgs e) + { ContainerControl f = ContainingControl; - if (f != null) { - if (f.Visible && Visible && !axState[fOwnWindow]) { + if (f != null) + { + if (f.Visible && Visible && !axState[fOwnWindow]) + { MakeVisibleWithShow(); } - else if (!f.Visible && Visible && IsHandleCreated && GetOcState() >= OC_INPLACE) { + else if (!f.Visible && Visible && IsHandleCreated && GetOcState() >= OC_INPLACE) + { HideAxControl(); } - else if (f.Visible && !GetState(STATE_VISIBLE) && IsHandleCreated && GetOcState() >= OC_INPLACE) { + else if (f.Visible && !GetState(STATE_VISIBLE) && IsHandleCreated && GetOcState() >= OC_INPLACE) + { HideAxControl(); } } @@ -547,11 +610,13 @@ private void OnContainerVisibleChanged(object sender, EventArgs e) { /// /// Determines if the control is in edit mode. /// - [ Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), + [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public bool EditMode { - get { + public bool EditMode + { + get + { return editMode != EDITM_NONE; } } @@ -559,21 +624,26 @@ public bool EditMode { /// /// Determines if this control has an about box. /// - [ Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), + [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public bool HasAboutBox { - get { + public bool HasAboutBox + { + get + { return aboutBoxDelegate != null; } } - private int NoComponentChangeEvents { - get { + private int NoComponentChangeEvents + { + get + { return noComponentChange; } - set { + set + { noComponentChange = value; } } @@ -582,8 +652,10 @@ private int NoComponentChangeEvents { /// /// Shows the about box for this control. /// - public void ShowAboutBox() { - if (aboutBoxDelegate != null) { + public void ShowAboutBox() + { + if (aboutBoxDelegate != null) + { aboutBoxDelegate(); } } @@ -605,37 +677,43 @@ private int OcxFlags { #endif [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackColorChanged { + new public event EventHandler BackColorChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "BackColorChanged")); remove { } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged { + new public event EventHandler BackgroundImageChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "BackgroundImageChanged")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { + new public event EventHandler BackgroundImageLayoutChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "BackgroundImageLayoutChanged")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BindingContextChanged { + new public event EventHandler BindingContextChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "BindingContextChanged")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler ContextMenuChanged { + new public event EventHandler ContextMenuChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "ContextMenuChanged")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler CursorChanged { + new public event EventHandler CursorChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "CursorChanged")); remove { } } @@ -644,31 +722,36 @@ private int OcxFlags { /// Occurs when the control is enabled. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler EnabledChanged { + new public event EventHandler EnabledChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "EnabledChanged")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler FontChanged { + new public event EventHandler FontChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "FontChanged")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler ForeColorChanged { + new public event EventHandler ForeColorChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "ForeColorChanged")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler RightToLeftChanged { + new public event EventHandler RightToLeftChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "RightToLeftChanged")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TextChanged { + new public event EventHandler TextChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "TextChanged")); remove { } } @@ -677,63 +760,73 @@ private int OcxFlags { /// Occurs when the control is clicked. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler Click { + new public event EventHandler Click + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "Click")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event DragEventHandler DragDrop { + new public event DragEventHandler DragDrop + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "DragDrop")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event DragEventHandler DragEnter { + new public event DragEventHandler DragEnter + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "DragEnter")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event DragEventHandler DragOver { + new public event DragEventHandler DragOver + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "DragOver")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler DragLeave { + new public event EventHandler DragLeave + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "DragLeave")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event GiveFeedbackEventHandler GiveFeedback { + new public event GiveFeedbackEventHandler GiveFeedback + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "GiveFeedback")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event HelpEventHandler HelpRequested { + new public event HelpEventHandler HelpRequested + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "HelpRequested")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event PaintEventHandler Paint { + new public event PaintEventHandler Paint + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "Paint")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event QueryContinueDragEventHandler QueryContinueDrag { + new public event QueryContinueDragEventHandler QueryContinueDrag + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "QueryContinueDrag")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event QueryAccessibilityHelpEventHandler QueryAccessibilityHelp { + new public event QueryAccessibilityHelpEventHandler QueryAccessibilityHelp + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "QueryAccessibilityHelp")); remove { } } @@ -742,13 +835,15 @@ private int OcxFlags { /// Occurs when the control is double clicked. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler DoubleClick { + new public event EventHandler DoubleClick + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "DoubleClick")); remove { } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler ImeModeChanged { + new public event EventHandler ImeModeChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "ImeModeChanged")); remove { } } @@ -758,7 +853,8 @@ private int OcxFlags { /// Occurs when a key is pressed down while the control has focus. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event KeyEventHandler KeyDown { + new public event KeyEventHandler KeyDown + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "KeyDown")); remove { } } @@ -768,7 +864,8 @@ private int OcxFlags { /// Occurs when a key is pressed while the control has focus. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event KeyPressEventHandler KeyPress { + new public event KeyPressEventHandler KeyPress + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "KeyPress")); remove { } } @@ -778,7 +875,8 @@ private int OcxFlags { /// Occurs when a key is released while the control has focus. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event KeyEventHandler KeyUp { + new public event KeyEventHandler KeyUp + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "KeyUp")); remove { } } @@ -787,7 +885,8 @@ private int OcxFlags { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event LayoutEventHandler Layout { + new public event LayoutEventHandler Layout + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "Layout")); remove { } } @@ -797,7 +896,8 @@ private int OcxFlags { /// pressed. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event MouseEventHandler MouseDown { + new public event MouseEventHandler MouseDown + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "MouseDown")); remove { } } @@ -806,7 +906,8 @@ private int OcxFlags { /// Occurs when the mouse pointer enters the AxHost. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler MouseEnter { + new public event EventHandler MouseEnter + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "MouseEnter")); remove { } } @@ -815,7 +916,8 @@ private int OcxFlags { /// Occurs when the mouse pointer leaves the AxHost. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler MouseLeave { + new public event EventHandler MouseLeave + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "MouseLeave")); remove { } } @@ -824,7 +926,8 @@ private int OcxFlags { /// Occurs when the mouse pointer hovers over the contro. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler MouseHover { + new public event EventHandler MouseHover + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "MouseHover")); remove { } } @@ -833,7 +936,8 @@ private int OcxFlags { /// Occurs when the mouse pointer is moved over the AxHost. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event MouseEventHandler MouseMove { + new public event MouseEventHandler MouseMove + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "MouseMove")); remove { } } @@ -842,7 +946,8 @@ private int OcxFlags { /// Occurs when the mouse pointer is over the control and a mouse button is released. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event MouseEventHandler MouseUp { + new public event MouseEventHandler MouseUp + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "MouseUp")); remove { } } @@ -851,66 +956,82 @@ private int OcxFlags { /// Occurs when the mouse wheel moves while the control has focus. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event MouseEventHandler MouseWheel { + new public event MouseEventHandler MouseWheel + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "MouseWheel")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event UICuesEventHandler ChangeUICues { + new public event UICuesEventHandler ChangeUICues + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "ChangeUICues")); remove { } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler StyleChanged { + new public event EventHandler StyleChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "StyleChanged")); remove { } } - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { base.OnFontChanged(e); AmbientChanged(NativeMethods.ActiveX.DISPID_AMBIENT_FONT); } - protected override void OnForeColorChanged(EventArgs e) { + protected override void OnForeColorChanged(EventArgs e) + { base.OnForeColorChanged(e); AmbientChanged(NativeMethods.ActiveX.DISPID_AMBIENT_FORECOLOR); } - protected override void OnBackColorChanged(EventArgs e) { + protected override void OnBackColorChanged(EventArgs e) + { base.OnBackColorChanged(e); AmbientChanged(NativeMethods.ActiveX.DISPID_AMBIENT_BACKCOLOR); } - private void AmbientChanged(int dispid) { - if (GetOcx() != null) { - try { + private void AmbientChanged(int dispid) + { + if (GetOcx() != null) + { + try + { Invalidate(); GetOleControl().OnAmbientPropertyChange(dispid); } - catch (Exception t) { + catch (Exception t) + { Debug.Fail(t.ToString()); } } } - private bool OwnWindow() { + private bool OwnWindow() + { return axState[fOwnWindow] || axState[fFakingWindow]; } - private IntPtr GetHandleNoCreate() { - if (IsHandleCreated) return Handle; + private IntPtr GetHandleNoCreate() + { + if (IsHandleCreated) + return Handle; return IntPtr.Zero; } - private ISelectionService GetSelectionService() { + private ISelectionService GetSelectionService() + { return GetSelectionService(this); } - private static ISelectionService GetSelectionService(Control ctl) { + private static ISelectionService GetSelectionService(Control ctl) + { ISite site = ctl.Site; - if (site != null) { + if (site != null) + { object o = site.GetService(typeof(ISelectionService)); Debug.Assert(o == null || o is ISelectionService, "service must implement ISelectionService"); //Note: if o is null, we want to return null anyway. Happy day. @@ -919,57 +1040,66 @@ private static ISelectionService GetSelectionService(Control ctl) { return null; } - private void AddSelectionHandler() { - if (axState[addedSelectionHandler]) return; + private void AddSelectionHandler() + { + if (axState[addedSelectionHandler]) + return; ISelectionService iss = GetSelectionService(); - if (iss != null) { + if (iss != null) + { iss.SelectionChanging += selectionChangeHandler; } axState[addedSelectionHandler] = true; } - private void OnComponentRename(object sender, ComponentRenameEventArgs e) + private void OnComponentRename(object sender, ComponentRenameEventArgs e) { // When we're notified of a rename, see if this is the componnent that is being // renamed. // - if (e.Component == this) + if (e.Component == this) { // if it is, call DISPID_AMBIENT_DISPLAYNAME directly on the // control itself. // UnsafeNativeMethods.IOleControl oleCtl = this.GetOcx() as UnsafeNativeMethods.IOleControl; - if (oleCtl != null) - { + if (oleCtl != null) + { oleCtl.OnAmbientPropertyChange(NativeMethods.ActiveX.DISPID_AMBIENT_DISPLAYNAME); } } } - private bool RemoveSelectionHandler() { - if (!axState[addedSelectionHandler]) return false; + private bool RemoveSelectionHandler() + { + if (!axState[addedSelectionHandler]) + return false; ISelectionService iss = GetSelectionService(); - if (iss != null) { + if (iss != null) + { iss.SelectionChanging -= selectionChangeHandler; } axState[addedSelectionHandler] = false; return true; } - private void SyncRenameNotification(bool hook) { - if (DesignMode && hook != axState[renameEventHooked]) + private void SyncRenameNotification(bool hook) + { + if (DesignMode && hook != axState[renameEventHooked]) { // if we're in design mode, listen to the following events from the component change service // IComponentChangeService changeService = (IComponentChangeService)GetService(typeof(IComponentChangeService)); - - if (changeService != null) + + if (changeService != null) { - if (hook) { + if (hook) + { changeService.ComponentRename += new ComponentRenameEventHandler(OnComponentRename); } - else { + else + { changeService.ComponentRename -= new ComponentRenameEventHandler(OnComponentRename); } axState[renameEventHooked] = hook; @@ -982,8 +1112,10 @@ private void SyncRenameNotification(bool hook) { /// component has been added to a container, and a null value indicates that /// the component is being removed from a container. /// - public override ISite Site { - set { + public override ISite Site + { + set + { // If we are disposed then just return. if (axState[disposed]) { @@ -998,8 +1130,10 @@ public override ISite Site { base.Site = value; bool newuMode = IsUserMode(); - if (!newuMode) GetOcxCreate(); - if (reAddHandler) AddSelectionHandler(); + if (!newuMode) + GetOcxCreate(); + if (reAddHandler) + AddSelectionHandler(); SyncRenameNotification(value != null); @@ -1007,7 +1141,8 @@ public override ISite Site { // and then we get sited. At that time, we have to re-activate // the OCX by transitioning down to and up to the current state. // - if (value != null && !newuMode && olduMode != newuMode && GetOcState() > OC_LOADED) { + if (value != null && !newuMode && olduMode != newuMode && GetOcState() > OC_LOADED) + { TransitionDownTo(OC_LOADED); TransitionUpTo(OC_INPLACE); ContainerControl f = ContainingControl; @@ -1015,12 +1150,15 @@ public override ISite Site { MakeVisibleWithShow(); } - if (olduMode != newuMode && !IsHandleCreated && !axState[disposed]) { - if (GetOcx() != null) { + if (olduMode != newuMode && !IsHandleCreated && !axState[disposed]) + { + if (GetOcx() != null) + { RealizeStyles(); } } - if (!newuMode) { + if (!newuMode) + { //SetupClass_Info(this); } } @@ -1030,7 +1168,8 @@ public override ISite Site { /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnLostFocus(EventArgs e) { + protected override void OnLostFocus(EventArgs e) + { // Office WebControl and MS DDS control create a child window that gains // focus in order to handle keyboard input. Since, UIDeactivate() could // destroy that window, these controls will crash trying to process WM_CHAR. @@ -1040,33 +1179,42 @@ protected override void OnLostFocus(EventArgs e) { bool uiDeactivate = (GetHandleNoCreate() != hwndFocus); - if (uiDeactivate && IsHandleCreated) { + if (uiDeactivate && IsHandleCreated) + { uiDeactivate = !UnsafeNativeMethods.IsChild(new HandleRef(this, GetHandleNoCreate()), new HandleRef(null, hwndFocus)); } base.OnLostFocus(e); - if (uiDeactivate) { + if (uiDeactivate) + { UiDeactivate(); } } - private void OnNewSelection(object sender, EventArgs e) { - if (IsUserMode()) return; + private void OnNewSelection(object sender, EventArgs e) + { + if (IsUserMode()) + return; ISelectionService iss = GetSelectionService(); // What we care about: // if we are uiactive and we lose selection, then we need to uideactivate ourselves... - if (iss != null) { - if (GetOcState() >= OC_UIACTIVE && !iss.GetComponentSelected(this)) { + if (iss != null) + { + if (GetOcState() >= OC_UIACTIVE && !iss.GetComponentSelected(this)) + { // need to deactivate... int hr = UiDeactivate(); - if (NativeMethods.Failed(hr)) { + if (NativeMethods.Failed(hr)) + { // not much we can do here... Debug.Fail("Failed to UiDeactivate: " + hr.ToString(CultureInfo.InvariantCulture)); } } - if (!iss.GetComponentSelected(this)) { - if (editMode != EDITM_NONE) { + if (!iss.GetComponentSelected(this)) + { + if (editMode != EDITM_NONE) + { GetParentContainer().OnExitEditMode(this); editMode = EDITM_NONE; } @@ -1074,14 +1222,17 @@ private void OnNewSelection(object sender, EventArgs e) { SetSelectionStyle(1); RemoveSelectionHandler(); } - else { + else + { // The AX Host designer will offer an extender property called "SelectionStyle" // PropertyDescriptor prop = TypeDescriptor.GetProperties(this)["SelectionStyle"]; - - if (prop != null && prop.PropertyType == typeof(int)) { + + if (prop != null && prop.PropertyType == typeof(int)) + { int curSelectionStyle = (int)prop.GetValue(this); - if (curSelectionStyle != this.selectionStyle) { + if (curSelectionStyle != this.selectionStyle) + { prop.SetValue(this, selectionStyle); } } @@ -1101,12 +1252,16 @@ private void OnNewSelection(object sender, EventArgs e) { /// Creates a handle for this control. This method is called by the .NET framework, this should /// not be called. /// - protected override void CreateHandle() { - if (!IsHandleCreated) { + protected override void CreateHandle() + { + if (!IsHandleCreated) + { TransitionUpTo(OC_RUNNING); - if (!axState[fOwnWindow]) { - if (axState[fNeedOwnWindow]) { + if (!axState[fOwnWindow]) + { + if (axState[fNeedOwnWindow]) + { Debug.Assert(!Visible, "if we were visible we would not be needing a fake window..."); axState[fNeedOwnWindow] = false; axState[fFakingWindow] = true; @@ -1114,20 +1269,23 @@ protected override void CreateHandle() { // note that we do not need to attach the handle because the work usually done in there // will be done in Control's wndProc on WM_CREATE... } - else { + else + { TransitionUpTo(OC_INPLACE); // it is possible that we were hidden while in place activating, in which case we don't // really have a handle now because the act of hiding could have destroyed it // so, just call ourselves again recursively, and if we dont't have a handle, we will // just take the "axState[fNeedOwnWindow]" path above... - if (axState[fNeedOwnWindow]) { + if (axState[fNeedOwnWindow]) + { Debug.Assert(!IsHandleCreated, "if we need a fake window, we can't have a real one"); CreateHandle(); return; } } } - else { + else + { SetState(STATE_VISIBLE, false); base.CreateHandle(); } @@ -1135,28 +1293,33 @@ protected override void CreateHandle() { } } - private NativeMethods.COMRECT GetClipRect(NativeMethods.COMRECT clipRect) { - if (clipRect != null) { + private NativeMethods.COMRECT GetClipRect(NativeMethods.COMRECT clipRect) + { + if (clipRect != null) + { FillInRect(clipRect, new Rectangle(0, 0, 32000, 32000)); } return clipRect; } - private static int SetupLogPixels(bool force) { - if (logPixelsX == -1 || force) { + private static int SetupLogPixels(bool force) + { + if (logPixelsX == -1 || force) + { IntPtr hDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef); if (hDC == IntPtr.Zero) return NativeMethods.E_FAIL; logPixelsX = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, hDC), NativeMethods.LOGPIXELSX); logPixelsY = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, hDC), NativeMethods.LOGPIXELSY); - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "log pixels are: "+logPixelsX.ToString(CultureInfo.InvariantCulture)+" "+logPixelsY.ToString(CultureInfo.InvariantCulture)); + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "log pixels are: " + logPixelsX.ToString(CultureInfo.InvariantCulture) + " " + logPixelsY.ToString(CultureInfo.InvariantCulture)); UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, hDC)); } - + return NativeMethods.S_OK; } - private void HiMetric2Pixel(NativeMethods.tagSIZEL sz, NativeMethods.tagSIZEL szout) { + private void HiMetric2Pixel(NativeMethods.tagSIZEL sz, NativeMethods.tagSIZEL szout) + { NativeMethods._POINTL phm = new NativeMethods._POINTL(); phm.x = sz.cx; phm.y = sz.cy; @@ -1166,62 +1329,73 @@ private void HiMetric2Pixel(NativeMethods.tagSIZEL sz, NativeMethods.tagSIZEL sz szout.cy = (int)pcont.y; } - private void Pixel2hiMetric(NativeMethods.tagSIZEL sz, NativeMethods.tagSIZEL szout) { + private void Pixel2hiMetric(NativeMethods.tagSIZEL sz, NativeMethods.tagSIZEL szout) + { NativeMethods.tagPOINTF pcont = new NativeMethods.tagPOINTF(); - pcont.x = (float) sz.cx; - pcont.y = (float) sz.cy; + pcont.x = (float)sz.cx; + pcont.y = (float)sz.cy; NativeMethods._POINTL phm = new NativeMethods._POINTL(); ((UnsafeNativeMethods.IOleControlSite)oleSite).TransformCoords(phm, pcont, NativeMethods.ActiveX.XFORMCOORDS_SIZE | NativeMethods.ActiveX.XFORMCOORDS_CONTAINERTOHIMETRIC); szout.cx = phm.x; szout.cy = phm.y; } - private static int Pixel2Twip(int v, bool xDirection) { + private static int Pixel2Twip(int v, bool xDirection) + { SetupLogPixels(false); int logP = xDirection ? logPixelsX : logPixelsY; - return(int) ((((double)v) / logP) * 72.0 * 20.0); + return (int)((((double)v) / logP) * 72.0 * 20.0); } - private static int Twip2Pixel(double v, bool xDirection) { + private static int Twip2Pixel(double v, bool xDirection) + { SetupLogPixels(false); int logP = xDirection ? logPixelsX : logPixelsY; - return(int) (((v / 20.0) / 72.0) * logP); + return (int)(((v / 20.0) / 72.0) * logP); } - private static int Twip2Pixel(int v, bool xDirection) { + private static int Twip2Pixel(int v, bool xDirection) + { SetupLogPixels(false); int logP = xDirection ? logPixelsX : logPixelsY; - return(int) (((((double) v) / 20.0) / 72.0) * logP); + return (int)(((((double)v) / 20.0) / 72.0) * logP); } - private Size SetExtent(int width, int height) { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "setting extent to "+width.ToString(CultureInfo.InvariantCulture)+" "+height.ToString(CultureInfo.InvariantCulture)); + private Size SetExtent(int width, int height) + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "setting extent to " + width.ToString(CultureInfo.InvariantCulture) + " " + height.ToString(CultureInfo.InvariantCulture)); NativeMethods.tagSIZEL sz = new NativeMethods.tagSIZEL(); sz.cx = width; sz.cy = height; bool resetExtents = !IsUserMode(); - try { + try + { Pixel2hiMetric(sz, sz); GetOleObject().SetExtent(NativeMethods.ActiveX.DVASPECT_CONTENT, sz); } - catch (COMException) { + catch (COMException) + { resetExtents = true; } - if (resetExtents) { + if (resetExtents) + { GetOleObject().GetExtent(NativeMethods.ActiveX.DVASPECT_CONTENT, sz); - try { + try + { GetOleObject().SetExtent(NativeMethods.ActiveX.DVASPECT_CONTENT, sz); } - catch (COMException e) { + catch (COMException e) + { Debug.Fail(e.ToString()); } } - return GetExtent(); + return GetExtent(); } - private Size GetExtent() { + private Size GetExtent() + { NativeMethods.tagSIZEL sz = new NativeMethods.tagSIZEL(); GetOleObject().GetExtent(NativeMethods.ActiveX.DVASPECT_CONTENT, sz); HiMetric2Pixel(sz, sz); @@ -1233,12 +1407,15 @@ private Size GetExtent() { /// original unscaled bounds. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override Rectangle GetScaledBounds(Rectangle bounds, SizeF factor, BoundsSpecified specified) { + protected override Rectangle GetScaledBounds(Rectangle bounds, SizeF factor, BoundsSpecified specified) + { return bounds; } - private void SetObjectRects(Rectangle bounds) { - if (GetOcState() < OC_INPLACE) return; + private void SetObjectRects(Rectangle bounds) + { + if (GetOcState() < OC_INPLACE) + return; GetInPlaceObject().SetObjectRects(FillInRect(new NativeMethods.COMRECT(), bounds), GetClipRect(new NativeMethods.COMRECT())); } @@ -1246,10 +1423,11 @@ private void SetObjectRects(Rectangle bounds) { /// Performs the work of setting the bounds of this control. /// User code should usually not call this function. /// - protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { + protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) + { // We have already been in this Code so please avoid re-entering this CODE PATH or else the // IOleObject will "give a Catastrophic error" in SetObjectRects( ). - + if (GetAxState(AxHost.handlePosRectChanged)) return; @@ -1260,53 +1438,66 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound width = adjustedSize.Width; height = adjustedSize.Height; - try { - if (axState[fFakingWindow]) { + try + { + if (axState[fFakingWindow]) + { base.SetBoundsCore(x, y, width, height, specified); return; } Rectangle oldBounds = Bounds; if (oldBounds.X == x && oldBounds.Y == y && oldBounds.Width == width && - oldBounds.Height == height) { + oldBounds.Height == height) + { return; } - if (!IsHandleCreated) { + if (!IsHandleCreated) + { UpdateBounds(x, y, width, height); return; } - if (GetOcState() > OC_RUNNING) { + if (GetOcState() > OC_RUNNING) + { CheckSubclassing(); - if (width != oldBounds.Width || height != oldBounds.Height) { + if (width != oldBounds.Width || height != oldBounds.Height) + { Size p = SetExtent(width, height); width = p.Width; height = p.Height; } } - if (axState[manualUpdate]) { + if (axState[manualUpdate]) + { SetObjectRects(new Rectangle(x, y, width, height)); CheckSubclassing(); UpdateBounds(); } - else { + else + { SetObjectRects(new Rectangle(x, y, width, height)); base.SetBoundsCore(x, y, width, height, specified); Invalidate(); } } - finally { + finally + { axState[handlePosRectChanged] = false; } } - private bool CheckSubclassing() { - if (!IsHandleCreated || wndprocAddr == IntPtr.Zero) return true; - IntPtr handle = Handle; + private bool CheckSubclassing() + { + if (!IsHandleCreated || wndprocAddr == IntPtr.Zero) + return true; + IntPtr handle = Handle; IntPtr currentWndproc = UnsafeNativeMethods.GetWindowLong(new HandleRef(this, handle), NativeMethods.GWL_WNDPROC); - if (currentWndproc == wndprocAddr) return true; - if (unchecked( (int) (long)SendMessage(REGMSG_MSG, 0, 0)) == REGMSG_RETVAL) { + if (currentWndproc == wndprocAddr) + return true; + if (unchecked((int)(long)SendMessage(REGMSG_MSG, 0, 0)) == REGMSG_RETVAL) + { wndprocAddr = currentWndproc; return true; } @@ -1326,12 +1517,16 @@ private bool CheckSubclassing() { /// Destroys the handle associated with this control. /// User code should in general not call this function. /// - protected override void DestroyHandle() { - if (axState[fOwnWindow]) { + protected override void DestroyHandle() + { + if (axState[fOwnWindow]) + { base.DestroyHandle(); } - else { - if (IsHandleCreated) { + else + { + if (IsHandleCreated) + { TransitionDownTo(OC_RUNNING); } } @@ -1349,17 +1544,22 @@ private void TransitionTo(int state) { } #endif - private void TransitionDownTo(int state) { - if (axState[inTransition]) { + private void TransitionDownTo(int state) + { + if (axState[inTransition]) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Recursively entering TransitionDownTo..."); return; } - try { + try + { axState[inTransition] = true; - while (state < GetOcState()) { - switch (GetOcState()) { + while (state < GetOcState()) + { + switch (GetOcState()) + { case OC_OPEN: Debug.Fail("how did we ever get into the open state?"); SetOcState(OC_UIACTIVE); @@ -1371,11 +1571,13 @@ private void TransitionDownTo(int state) { SetOcState(OC_INPLACE); break; case OC_INPLACE: - if (axState[fFakingWindow]) { + if (axState[fFakingWindow]) + { DestroyFakeWindow(); SetOcState(OC_RUNNING); } - else { + else + { InPlaceDeactivate(); } Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose && GetOcState() == OC_RUNNING, "failed transition"); @@ -1384,12 +1586,12 @@ private void TransitionDownTo(int state) { case OC_RUNNING: StopEvents(); DisposeAxControl(); - Debug.Assert(GetOcState() == OC_LOADED," failed transition"); + Debug.Assert(GetOcState() == OC_LOADED, " failed transition"); SetOcState(OC_LOADED); break; case OC_LOADED: ReleaseAxControl(); - Debug.Assert(GetOcState() == OC_PASSIVE," failed transition"); + Debug.Assert(GetOcState() == OC_PASSIVE, " failed transition"); SetOcState(OC_PASSIVE); break; default: @@ -1399,23 +1601,29 @@ private void TransitionDownTo(int state) { } } } - finally { + finally + { axState[inTransition] = false; } } - private void TransitionUpTo(int state) { - if (axState[inTransition]) { + private void TransitionUpTo(int state) + { + if (axState[inTransition]) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Recursively entering TransitionUpTo..."); return; } - try { + try + { axState[inTransition] = true; - while (state > GetOcState()) { + while (state > GetOcState()) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Transitioning up from: " + GetOcState().ToString(CultureInfo.InvariantCulture) + " to: " + state.ToString(CultureInfo.InvariantCulture)); - switch (GetOcState()) { + switch (GetOcState()) + { case OC_PASSIVE: axState[disposed] = false; GetOcxCreate(); @@ -1426,7 +1634,8 @@ private void TransitionUpTo(int state) { ActivateAxControl(); Debug.Assert(GetOcState() == OC_RUNNING, " failed transition"); SetOcState(OC_RUNNING); - if (IsUserMode()) { + if (IsUserMode()) + { // start the events flowing! //createSink(); StartEvents(); @@ -1435,13 +1644,16 @@ private void TransitionUpTo(int state) { case OC_RUNNING: axState[ownDisposing] = false; Debug.Assert(!axState[fOwnWindow], "If we are invis at runtime, we should never be going beynd OC_RUNNING"); - if (!axState[fOwnWindow]) { + if (!axState[fOwnWindow]) + { InPlaceActivate(); - if (!Visible && ContainingControl != null && ContainingControl.Visible) { + if (!Visible && ContainingControl != null && ContainingControl.Visible) + { HideAxControl(); } - else { + else + { // if we do this in both codepaths, then we will force handle creation of the fake window // even if we don't need it... // This optimization will break, however, if: @@ -1456,11 +1668,13 @@ private void TransitionUpTo(int state) { // also from GetWindowContext) so we don't poke in a new value. // The reason to do this at design time is that that's the only way we // can find out if the control has a default which we have to obey. - if (!IsUserMode() && !axState[ocxStateSet]) { + if (!IsUserMode() && !axState[ocxStateSet]) + { Size p = GetExtent(); Rectangle b = Bounds; - if ((b.Size.Equals(DefaultSize)) && (!b.Size.Equals(p))) { + if ((b.Size.Equals(DefaultSize)) && (!b.Size.Equals(p))) + { b.Width = p.Width; b.Height = p.Height; Bounds = b; @@ -1468,9 +1682,10 @@ private void TransitionUpTo(int state) { } } } - + //Debug.Assert(GetOcState() == OC_INPLACE, " failed transition"); - if (GetOcState() < OC_INPLACE) { + if (GetOcState() < OC_INPLACE) + { SetOcState(OC_INPLACE); } OnInPlaceActive(); @@ -1487,53 +1702,66 @@ private void TransitionUpTo(int state) { } } } - finally { + finally + { axState[inTransition] = false; } } - protected virtual void OnInPlaceActive() { + protected virtual void OnInPlaceActive() + { } - private void InPlaceActivate() { - try { + private void InPlaceActivate() + { + try + { DoVerb(OLEIVERB_INPLACEACTIVATE); } - catch (Exception t) { + catch (Exception t) + { Debug.Fail(t.ToString()); - throw new TargetInvocationException(string.Format(SR.AXNohWnd,GetType().Name), t); + throw new TargetInvocationException(string.Format(SR.AXNohWnd, GetType().Name), t); } EnsureWindowPresent(); } - private void InPlaceDeactivate() { + private void InPlaceDeactivate() + { axState[ownDisposing] = true; ContainerControl f = ContainingControl; - if (f != null) { - if (f.ActiveControl == this) { + if (f != null) + { + if (f.ActiveControl == this) + { f.ActiveControl = null; } } - try { + try + { GetInPlaceObject().InPlaceDeactivate(); } - catch(Exception e) { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Exception calling InPlaceDeactivate: "+ e.ToString()); + catch (Exception e) + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Exception calling InPlaceDeactivate: " + e.ToString()); } } - private void UiActivate() { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "calling uiActivate for "+this.ToString()); + private void UiActivate() + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "calling uiActivate for " + this.ToString()); Debug.Assert(GetOcState() >= OC_INPLACE, "we have to be in place in order to ui activate..."); Debug.Assert(CanUIActivate, "we have to be able to uiactivate"); - if (CanUIActivate) { + if (CanUIActivate) + { DoVerb(OLEIVERB_UIACTIVATE); } } - private void DestroyFakeWindow() { + private void DestroyFakeWindow() + { Debug.Assert(axState[fFakingWindow], "have to be faking it in order to destroy it..."); // The problem seems to be that when we try to destroy the fake window, @@ -1546,67 +1774,86 @@ private void DestroyFakeWindow() { base.DestroyHandle(); } - private void EnsureWindowPresent() { + private void EnsureWindowPresent() + { // if the ctl didn't call showobject, we need to do it for it... - if (!IsHandleCreated) { + if (!IsHandleCreated) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Naughty control didn't call showObject..."); - try { + try + { ((UnsafeNativeMethods.IOleClientSite)oleSite).ShowObject(); } - catch { + catch + { // The exception, if any was already dumped in ShowObject } } - if (IsHandleCreated) return; + if (IsHandleCreated) + return; - if (ParentInternal != null) { // ==> we are in a valid state + if (ParentInternal != null) + { // ==> we are in a valid state Debug.Fail("extremely naughty ctl is refusing to give us an hWnd... giving up..."); - throw new NotSupportedException(string.Format(SR.AXNohWnd,GetType().Name)); + throw new NotSupportedException(string.Format(SR.AXNohWnd, GetType().Name)); } } - protected override void SetVisibleCore(bool value) { - if (GetState(STATE_VISIBLE) != value) { + protected override void SetVisibleCore(bool value) + { + if (GetState(STATE_VISIBLE) != value) + { bool oldVisible = Visible; - if ((IsHandleCreated || value) && ParentInternal != null && ParentInternal.Created) { - if (!axState[fOwnWindow]) { + if ((IsHandleCreated || value) && ParentInternal != null && ParentInternal.Created) + { + if (!axState[fOwnWindow]) + { TransitionUpTo(OC_RUNNING); - if (value) { - if (axState[fFakingWindow]) { + if (value) + { + if (axState[fFakingWindow]) + { // first we need to destroy the fake window... DestroyFakeWindow(); } // We want to avoid using SHOW since that may uiactivate us, and we don't // want that... - if (!IsHandleCreated) { + if (!IsHandleCreated) + { // So, if we don't have a handle, we just try to create it and hope that this will make // us appear... - try { + try + { SetExtent(Width, Height); InPlaceActivate(); CreateControl(true); } - catch { + catch + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Could not make ctl visible by using INPLACE. Will try SHOW"); MakeVisibleWithShow(); } } - else { + else + { // if, otoh, we had a handle to begin with, we need to use show since INPLACE is just // a noop... MakeVisibleWithShow(); } } - else { + else + { Debug.Assert(!axState[fFakingWindow], "if we were visible, we could not have had a fake window..."); HideAxControl(); } } } - if (!value) { + if (!value) + { axState[fNeedOwnWindow] = false; } - if (!axState[fOwnWindow]) { + if (!axState[fOwnWindow]) + { SetState(STATE_VISIBLE, value); if (Visible != oldVisible) OnVisibleChanged(EventArgs.Empty); @@ -1614,31 +1861,37 @@ protected override void SetVisibleCore(bool value) { } } - private void MakeVisibleWithShow() { + private void MakeVisibleWithShow() + { ContainerControl f = ContainingControl; Control ctl = f == null ? null : f.ActiveControl; - try { + try + { DoVerb(OLEIVERB_SHOW); } - catch (Exception t) { + catch (Exception t) + { Debug.Fail(t.ToString()); - throw new TargetInvocationException(string.Format(SR.AXNohWnd,GetType().Name), t); + throw new TargetInvocationException(string.Format(SR.AXNohWnd, GetType().Name), t); } EnsureWindowPresent(); CreateControl(true); - if (f != null && f.ActiveControl != ctl) { + if (f != null && f.ActiveControl != ctl) + { f.ActiveControl = ctl; } } - private void HideAxControl() { + private void HideAxControl() + { Debug.Assert(!axState[fOwnWindow], "can't own our window when hiding"); Debug.Assert(IsHandleCreated, "gotta have a window to hide"); Debug.Assert(GetOcState() >= OC_INPLACE, "have to be in place in order to hide."); - + DoVerb(OLEIVERB_HIDE); - if (GetOcState() < OC_INPLACE) { + if (GetOcState() < OC_INPLACE) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Naughty control inplace deactivated on a hide verb..."); Debug.Assert(!IsHandleCreated, "if we are inplace deactivated we should not have a window."); // all we do here is set a flag saying that we need the window to be created if @@ -1662,11 +1915,12 @@ private void HideAxControl() { /// pre-processing of a character includes checking whether the character /// is a mnemonic of another control. /// - protected override bool IsInputChar(char charCode) { + protected override bool IsInputChar(char charCode) + { return true; } - protected override bool ProcessDialogKey(Keys keyData) + protected override bool ProcessDialogKey(Keys keyData) { if (ignoreDialogKeys) { @@ -1675,7 +1929,7 @@ protected override bool ProcessDialogKey(Keys keyData) return base.ProcessDialogKey(keyData); } - + /// /// This method is called by the application's message loop to pre-process /// input messages before they are dispatched. Possible values for the @@ -1699,11 +1953,14 @@ protected override bool ProcessDialogKey(Keys keyData) /// -- If this returns S_FALSE, then it means that the control did not process this message, /// but we did, and so we should route it through our PreProcessMessage(). /// - public override bool PreProcessMessage(ref Message msg) { + public override bool PreProcessMessage(ref Message msg) + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "AxHost.PreProcessMessage " + msg.ToString()); - - if (IsUserMode()) { - if (axState[siteProcessedInputKey]) { + + if (IsUserMode()) + { + if (axState[siteProcessedInputKey]) + { // In this case, the control called the us back through the IControlSite // and giving us a chance to see if we want to process it. We in turn // call the base implementation which normally would call the control's @@ -1719,9 +1976,10 @@ public override bool PreProcessMessage(ref Message msg) { win32Message.wParam = msg.WParam; win32Message.lParam = msg.LParam; win32Message.hwnd = msg.HWnd; - + axState[siteProcessedInputKey] = false; - try { + try + { UnsafeNativeMethods.IOleInPlaceActiveObject activeObj = GetInPlaceActiveObject(); if (activeObj != null) { @@ -1732,37 +1990,44 @@ public override bool PreProcessMessage(ref Message msg) { msg.LParam = win32Message.lParam; msg.HWnd = win32Message.hwnd; - if (hr == NativeMethods.S_OK) { + if (hr == NativeMethods.S_OK) + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "\t Message translated by control to " + msg); return true; } - else if (hr == NativeMethods.S_FALSE) { + else if (hr == NativeMethods.S_FALSE) + { bool ret = false; ignoreDialogKeys = true; - try { + try + { ret = base.PreProcessMessage(ref msg); } - finally { + finally + { ignoreDialogKeys = false; } return ret; } - else if (axState[siteProcessedInputKey]) { + else if (axState[siteProcessedInputKey]) + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "\t Message processed by site. Calling base.PreProcessMessage() " + msg); - return base.PreProcessMessage (ref msg); + return base.PreProcessMessage(ref msg); } - else { + else + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "\t Message not processed by site. Returning false. " + msg); return false; } } } - finally { + finally + { axState[siteProcessedInputKey] = false; } } - + return false; } @@ -1771,13 +2036,17 @@ public override bool PreProcessMessage(ref Message msg) { /// This is done by manufacturing a WM_SYSKEYDOWN message and passing it to the /// ActiveX control. /// - protected internal override bool ProcessMnemonic(char charCode) { + protected internal override bool ProcessMnemonic(char charCode) + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "In AxHost.ProcessMnemonic: " + (int)charCode); - if (CanSelect) { - try { + if (CanSelect) + { + try + { NativeMethods.tagCONTROLINFO ctlInfo = new NativeMethods.tagCONTROLINFO(); int hr = GetOleControl().GetControlInfo(ctlInfo); - if (NativeMethods.Failed(hr)) { + if (NativeMethods.Failed(hr)) + { return false; } NativeMethods.MSG msg = new NativeMethods.MSG(); @@ -1787,20 +2056,22 @@ protected internal override bool ProcessMnemonic(char charCode) { msg.hwnd = (ContainingControl == null) ? IntPtr.Zero : ContainingControl.Handle; msg.message = Interop.WindowMessages.WM_SYSKEYDOWN; msg.wParam = (IntPtr)char.ToUpper(charCode, CultureInfo.CurrentCulture); - msg.lParam = (IntPtr) 0x20180001; + msg.lParam = (IntPtr)0x20180001; msg.time = SafeNativeMethods.GetTickCount(); NativeMethods.POINT p = new NativeMethods.POINT(); UnsafeNativeMethods.GetCursorPos(p); msg.pt_x = p.x; msg.pt_y = p.y; - if (SafeNativeMethods.IsAccelerator(new HandleRef(ctlInfo, ctlInfo.hAccel), ctlInfo.cAccel, ref msg, null)) { + if (SafeNativeMethods.IsAccelerator(new HandleRef(ctlInfo, ctlInfo.hAccel), ctlInfo.cAccel, ref msg, null)) + { GetOleControl().OnMnemonic(ref msg); Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "\t Processed mnemonic " + msg); Focus(); return true; } } - catch (Exception t) { + catch (Exception t) + { Debug.Fail("error in processMnemonic"); Debug.Fail(t.ToString()); return false; @@ -1815,7 +2086,8 @@ protected internal override bool ProcessMnemonic(char charCode) { /// Sets the delegate which will be called when the user selects the "About..." /// entry on the context menu. /// - protected void SetAboutBoxDelegate(AboutBoxDelegate d) { + protected void SetAboutBoxDelegate(AboutBoxDelegate d) + { aboutBoxDelegate += d; } @@ -1835,93 +2107,115 @@ protected void SetAboutBoxDelegate(AboutBoxDelegate d) { RefreshProperties(RefreshProperties.All), Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced) ] - public State OcxState { - get { - if (IsDirty() || ocxState == null) { + public State OcxState + { + get + { + if (IsDirty() || ocxState == null) + { Debug.Assert(!axState[disposed], "we chould not be asking for the object when we are axState[disposed]..."); ocxState = CreateNewOcxState(ocxState); } return ocxState; } - set { + set + { axState[ocxStateSet] = true; - if (value == null) return; + if (value == null) + return; - if (storageType != STG_UNKNOWN && storageType != value.type) { + if (storageType != STG_UNKNOWN && storageType != value.type) + { Debug.Fail("Trying to reload with a OcxState that is of a different type."); throw new InvalidOperationException(SR.AXOcxStateLoaded); } - + if (this.ocxState == value) return; - + this.ocxState = value; - - if (this.ocxState != null) { + + if (this.ocxState != null) + { this.axState[manualUpdate] = ocxState._GetManualUpdate(); this.licenseKey = ocxState._GetLicenseKey(); } - else { + else + { this.axState[manualUpdate] = false; this.licenseKey = null; } - if (this.ocxState != null && GetOcState() >= OC_RUNNING) { + if (this.ocxState != null && GetOcState() >= OC_RUNNING) + { DepersistControl(); } } } - private State CreateNewOcxState(State oldOcxState) { + private State CreateNewOcxState(State oldOcxState) + { NoComponentChangeEvents++; - try { - if (GetOcState() < OC_RUNNING) { + try + { + if (GetOcState() < OC_RUNNING) + { return null; } - try { + try + { PropertyBagStream propBag = null; - if (iPersistPropBag != null) { + if (iPersistPropBag != null) + { propBag = new PropertyBagStream(); iPersistPropBag.Save(propBag, true, true); } MemoryStream ms = null; - switch (storageType) { + switch (storageType) + { case STG_STREAM: case STG_STREAMINIT: ms = new MemoryStream(); - if (storageType == STG_STREAM) { + if (storageType == STG_STREAM) + { iPersistStream.Save(new UnsafeNativeMethods.ComStreamFromDataStream(ms), true); } - else { + else + { iPersistStreamInit.Save(new UnsafeNativeMethods.ComStreamFromDataStream(ms), true); } break; case STG_STORAGE: Debug.Assert(oldOcxState != null, "we got to have an old state which holds out scribble storage..."); - if (oldOcxState != null) return oldOcxState.RefreshStorage(iPersistStorage); + if (oldOcxState != null) + return oldOcxState.RefreshStorage(iPersistStorage); return null; default: Debug.Fail("unknown storage type."); return null; } - if (ms != null) { + if (ms != null) + { return new State(ms, storageType, this, propBag); } - else if (propBag != null) { + else if (propBag != null) + { return new State(propBag); } } - catch (Exception e) { + catch (Exception e) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Could not create new OCX State: " + e.ToString()); } } - finally { + finally + { NoComponentChangeEvents--; } @@ -1947,16 +2241,20 @@ private State CreateNewOcxState(State oldOcxState) { EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public ContainerControl ContainingControl { - get { - if (containingControl == null) { + public ContainerControl ContainingControl + { + get + { + if (containingControl == null) + { containingControl = FindContainerControlInternal(); } - + return containingControl; } - set { + set + { containingControl = value; } } @@ -1965,12 +2263,15 @@ public ContainerControl ContainingControl { /// Determines if the Text property needs to be persisted. /// [EditorBrowsable(EditorBrowsableState.Never)] - internal override bool ShouldSerializeText() { + internal override bool ShouldSerializeText() + { bool ret = false; - try { + try + { ret = (Text.Length != 0); } - catch (COMException) { + catch (COMException) + { } return ret; } @@ -1979,14 +2280,18 @@ internal override bool ShouldSerializeText() { /// Determines whether to persist the ContainingControl property. /// [EditorBrowsable(EditorBrowsableState.Never)] - private bool ShouldSerializeContainingControl() { + private bool ShouldSerializeContainingControl() + { return ContainingControl != ParentInternal; } - private ContainerControl FindContainerControlInternal() { - if (Site != null) { + private ContainerControl FindContainerControlInternal() + { + if (Site != null) + { IDesignerHost host = (IDesignerHost)Site.GetService(typeof(IDesignerHost)); - if (host != null) { + if (host != null) + { ContainerControl rootControl = host.RootComponent as ContainerControl; if (rootControl != null) { @@ -1997,7 +2302,8 @@ private ContainerControl FindContainerControlInternal() { ContainerControl cc = null; Control control = this; - while (control != null) { + while (control != null) + { ContainerControl tempCC = control as ContainerControl; if (tempCC != null) { @@ -2009,20 +2315,25 @@ private ContainerControl FindContainerControlInternal() { return cc; } - private bool IsDirty() { - if (GetOcState() < OC_RUNNING) return false; + private bool IsDirty() + { + if (GetOcState() < OC_RUNNING) + return false; Debug.Assert(storageType != STG_UNKNOWN, "if we are loaded, out storage type must be set!"); - if (axState[valueChanged]) { + if (axState[valueChanged]) + { axState[valueChanged] = false; return true; } #if DEBUG - if (AxAlwaysSaveSwitch.Enabled) return true; + if (AxAlwaysSaveSwitch.Enabled) + return true; #endif int hr = NativeMethods.E_FAIL; - switch (storageType) { + switch (storageType) + { case STG_STREAM: hr = iPersistStream.IsDirty(); break; @@ -2036,7 +2347,8 @@ private bool IsDirty() { Debug.Fail("unknown storage type"); return true; } - if (hr == NativeMethods.S_FALSE) { + if (hr == NativeMethods.S_FALSE) + { // NOTE: This was a note from the old AxHost codebase. The problem // with doing this is that the some controls that do not run in // unlicensed mode (e.g. ProtoView ScheduleX pvtaskpad.ocx) will @@ -2047,23 +2359,27 @@ private bool IsDirty() { // dirty at least once... return false; } - else if (NativeMethods.Failed(hr)) { + else if (NativeMethods.Failed(hr)) + { return true; } return true; } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] - internal bool IsUserMode() { + internal bool IsUserMode() + { ISite site = Site; return site == null || !site.DesignMode; } - private object GetAmbientProperty(int dispid) { + private object GetAmbientProperty(int dispid) + { Control richParent = ParentInternal; - switch (dispid) { + switch (dispid) + { case NativeMethods.ActiveX.DISPID_AMBIENT_USERMODE: Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "asked for usermode"); return IsUserMode(); @@ -2081,7 +2397,8 @@ private object GetAmbientProperty(int dispid) { return false; case NativeMethods.ActiveX.DISPID_AMBIENT_FONT: Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "asked for font"); - if (richParent != null) { + if (richParent != null) + { return GetIFontFromFont(richParent.Font); } return null; @@ -2092,18 +2409,21 @@ private object GetAmbientProperty(int dispid) { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "asked for showHatching"); return false; case NativeMethods.ActiveX.DISPID_AMBIENT_BACKCOLOR: - if (richParent != null) { + if (richParent != null) + { return GetOleColorFromColor(richParent.BackColor); } return null; case NativeMethods.ActiveX.DISPID_AMBIENT_FORECOLOR: - if (richParent != null) { + if (richParent != null) + { return GetOleColorFromColor(richParent.ForeColor); } return null; case NativeMethods.ActiveX.DISPID_AMBIENT_DISPLAYNAME: string rval = GetParentContainer().GetNameForControl(this); - if (rval == null) rval = string.Empty; + if (rval == null) + rval = string.Empty; return rval; case NativeMethods.ActiveX.DISPID_AMBIENT_LOCALEID: Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "asked for localeid"); @@ -2111,7 +2431,8 @@ private object GetAmbientProperty(int dispid) { case NativeMethods.ActiveX.DISPID_AMBIENT_RIGHTTOLEFT: Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "asked for right to left"); Control ctl = this; - while (ctl != null) { + while (ctl != null) + { if (ctl.RightToLeft == System.Windows.Forms.RightToLeft.No) return false; if (ctl.RightToLeft == System.Windows.Forms.RightToLeft.Yes) @@ -2121,102 +2442,125 @@ private object GetAmbientProperty(int dispid) { } return null; default: - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "unsupported ambient "+dispid.ToString(CultureInfo.InvariantCulture)); + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "unsupported ambient " + dispid.ToString(CultureInfo.InvariantCulture)); return null; } } - public void DoVerb(int verb) { + public void DoVerb(int verb) + { Control parent = ParentInternal; GetOleObject().DoVerb(verb, IntPtr.Zero, oleSite, -1, parent != null ? parent.Handle : IntPtr.Zero, FillInRect(new NativeMethods.COMRECT(), Bounds)); } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] - private bool AwaitingDefreezing() { + private bool AwaitingDefreezing() + { return freezeCount > 0; } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] - private void Freeze(bool v) { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "freezing "+v.ToString()); - if (v) { - try { + private void Freeze(bool v) + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "freezing " + v.ToString()); + if (v) + { + try + { GetOleControl().FreezeEvents(-1); } - catch (COMException t) { + catch (COMException t) + { Debug.Fail(t.ToString()); } - freezeCount ++; + freezeCount++; } - else { - try { + else + { + try + { GetOleControl().FreezeEvents(0); } - catch (COMException t) { + catch (COMException t) + { Debug.Fail(t.ToString()); } - freezeCount --; + freezeCount--; } - Debug.Assert(freezeCount >=0, "invalid freeze count!"); + Debug.Assert(freezeCount >= 0, "invalid freeze count!"); } - private int UiDeactivate() { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "calling uiDeactivate for "+this.ToString()); + private int UiDeactivate() + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "calling uiDeactivate for " + this.ToString()); bool ownDispose = this.axState[ownDisposing]; this.axState[ownDisposing] = true; int hr = 0; - try { + try + { hr = GetInPlaceObject().UIDeactivate(); } - finally { + finally + { this.axState[ownDisposing] = ownDispose; } return hr; } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] - private int GetOcState() { + private int GetOcState() + { return ocState; } - private void SetOcState(int nv) { + private void SetOcState(int nv) + { ocState = nv; } - private string GetLicenseKey() { + private string GetLicenseKey() + { return GetLicenseKey(this.clsid); } - private string GetLicenseKey(Guid clsid) { - if (licenseKey != null || !axState[needLicenseKey]) { + private string GetLicenseKey(Guid clsid) + { + if (licenseKey != null || !axState[needLicenseKey]) + { return licenseKey; } - try { + try + { UnsafeNativeMethods.IClassFactory2 icf2 = UnsafeNativeMethods.CoGetClassObject(ref clsid, INPROC_SERVER, 0, ref icf2_Guid); NativeMethods.tagLICINFO licInfo = new NativeMethods.tagLICINFO(); icf2.GetLicInfo(licInfo); - if (licInfo.fRuntimeAvailable != 0) { + if (licInfo.fRuntimeAvailable != 0) + { string[] rval = new string[1]; icf2.RequestLicKey(0, rval); licenseKey = rval[0]; return licenseKey; } } - catch (COMException e) { - if (e.ErrorCode == E_NOINTERFACE.ErrorCode) return null; + catch (COMException e) + { + if (e.ErrorCode == E_NOINTERFACE.ErrorCode) + return null; Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Failed to get the license key: " + e.ToString()); axState[needLicenseKey] = false; } - catch (Exception t) { + catch (Exception t) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Failed to get the license key: " + t.ToString()); axState[needLicenseKey] = false; } return null; } - private void CreateWithoutLicense(Guid clsid) { + private void CreateWithoutLicense(Guid clsid) + { object ret = null; Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Creating object without license: " + clsid.ToString()); ret = UnsafeNativeMethods.CoCreateInstance(ref clsid, null, INPROC_SERVER, ref NativeMethods.ActiveX.IID_IUnknown); @@ -2224,39 +2568,49 @@ private void CreateWithoutLicense(Guid clsid) { instance = ret; } - private void CreateWithLicense(string license, Guid clsid) { - if (license != null) { - try { + private void CreateWithLicense(string license, Guid clsid) + { + if (license != null) + { + try + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Creating object with license: " + clsid.ToString()); UnsafeNativeMethods.IClassFactory2 icf2 = UnsafeNativeMethods.CoGetClassObject(ref clsid, INPROC_SERVER, 0, ref icf2_Guid); - - if (icf2 != null) { + + if (icf2 != null) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "\tClassFactory" + (icf2 != null).ToString()); icf2.CreateInstanceLic(null, null, ref NativeMethods.ActiveX.IID_IUnknown, license, out instance); Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "\t" + (instance != null).ToString()); } } - catch (Exception t) { + catch (Exception t) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Failed to create with license: " + t.ToString()); } } - - if (instance == null) { + + if (instance == null) + { CreateWithoutLicense(clsid); } } - private void CreateInstance() { + private void CreateInstance() + { Debug.Assert(instance == null, "instance must be null"); //Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "before created "+Windows.GetCurrentThreadId()); //Debug.WriteStackTraceIf("AxHTrace"); //checkThreadingModel(); - try { + try + { instance = CreateInstanceCore(this.clsid); Debug.Assert(instance != null, "w/o an exception being thrown we must have an object..."); } - catch (ExternalException e) { - if (e.ErrorCode == unchecked((int)0x80040112)) { // CLASS_E_NOTLICENSED + catch (ExternalException e) + { + if (e.ErrorCode == unchecked((int)0x80040112)) + { // CLASS_E_NOTLICENSED throw new LicenseException(GetType(), this, SR.AXNoLicenseToUse); } throw; @@ -2271,41 +2625,53 @@ private void CreateInstance() { /// Called to create the ActiveX control. Override this member to perform your own creation logic /// or call base to do the default creation logic. /// - protected virtual object CreateInstanceCore(Guid clsid) { - if (IsUserMode()) { + protected virtual object CreateInstanceCore(Guid clsid) + { + if (IsUserMode()) + { CreateWithLicense(licenseKey, clsid); } - else { + else + { CreateWithoutLicense(clsid); } return instance; } - private CategoryAttribute GetCategoryForDispid(int dispid) { + private CategoryAttribute GetCategoryForDispid(int dispid) + { NativeMethods.ICategorizeProperties icp = GetCategorizeProperties(); - if (icp == null) return null; + if (icp == null) + return null; CategoryAttribute rval = null; int propcat = 0; - try { + try + { icp.MapPropertyToCategory(dispid, ref propcat); - if (propcat != 0) { + if (propcat != 0) + { int cat = -propcat; - if (cat > 0 && cat < categoryNames.Length && categoryNames[cat] != null) { + if (cat > 0 && cat < categoryNames.Length && categoryNames[cat] != null) + { return categoryNames[cat]; } - cat = - cat; + cat = -cat; int key = cat; - if (objectDefinedCategoryNames != null) { - rval = (CategoryAttribute) objectDefinedCategoryNames[key]; - if (rval != null) return rval; + if (objectDefinedCategoryNames != null) + { + rval = (CategoryAttribute)objectDefinedCategoryNames[key]; + if (rval != null) + return rval; } - + string name = null; int hr = icp.GetCategoryName(cat, CultureInfo.CurrentCulture.LCID, out name); - if (hr == NativeMethods.S_OK && name != null) { + if (hr == NativeMethods.S_OK && name != null) + { rval = new CategoryAttribute(name); - if (objectDefinedCategoryNames == null) { + if (objectDefinedCategoryNames == null) + { objectDefinedCategoryNames = new Hashtable(); } objectDefinedCategoryNames.Add(key, rval); @@ -2313,24 +2679,29 @@ private CategoryAttribute GetCategoryForDispid(int dispid) { } } } - catch (Exception t) { + catch (Exception t) + { Debug.Fail(t.ToString()); } return null; } - private void SetSelectionStyle(int selectionStyle) { - if (!this.IsUserMode()) { + private void SetSelectionStyle(int selectionStyle) + { + if (!this.IsUserMode()) + { // selectionStyle can be 0 (not selected), 1 (selected) or 2 (active) Debug.Assert(selectionStyle >= 0 && selectionStyle <= 2, "Invalid selection style"); ISelectionService iss = GetSelectionService(); this.selectionStyle = selectionStyle; - if (iss != null && iss.GetComponentSelected(this)) { + if (iss != null && iss.GetComponentSelected(this)) + { // The AX Host designer will offer an extender property called "SelectionStyle" // PropertyDescriptor prop = TypeDescriptor.GetProperties(this)["SelectionStyle"]; - if (prop != null && prop.PropertyType == typeof(int)) { + if (prop != null && prop.PropertyType == typeof(int)) + { prop.SetValue(this, selectionStyle); } } @@ -2338,18 +2709,22 @@ private void SetSelectionStyle(int selectionStyle) { } [EditorBrowsable(EditorBrowsableState.Advanced)] - public void InvokeEditMode() { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "invoking EditMode for "+this.ToString()); + public void InvokeEditMode() + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "invoking EditMode for " + this.ToString()); Debug.Assert((flags & AxFlags.PreventEditMode) == 0, "edit mode should have been disabled"); - if (editMode != EDITM_NONE) return; + if (editMode != EDITM_NONE) + return; AddSelectionHandler(); editMode = EDITM_HOST; SetSelectionStyle(2); IntPtr hwndFocus = UnsafeNativeMethods.GetFocus(); - try { + try + { UiActivate(); } - catch (Exception t) { + catch (Exception t) + { Debug.Fail(t.ToString()); } // It so happens that some controls don't get focus in this case, so @@ -2369,8 +2744,10 @@ public void InvokeEditMode() { // [EditorBrowsable(EditorBrowsableState.Advanced)] - AttributeCollection ICustomTypeDescriptor.GetAttributes() { - if (!axState[editorRefresh] && HasPropertyPages()) { + AttributeCollection ICustomTypeDescriptor.GetAttributes() + { + if (!axState[editorRefresh] && HasPropertyPages()) + { axState[editorRefresh] = true; TypeDescriptor.Refresh(this.GetType()); } @@ -2382,7 +2759,8 @@ AttributeCollection ICustomTypeDescriptor.GetAttributes() { /// the type name is used. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - string ICustomTypeDescriptor.GetClassName() { + string ICustomTypeDescriptor.GetClassName() + { return null; } @@ -2391,7 +2769,8 @@ string ICustomTypeDescriptor.GetClassName() { /// the default is used. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - string ICustomTypeDescriptor.GetComponentName() { + string ICustomTypeDescriptor.GetComponentName() + { return null; } @@ -2399,17 +2778,20 @@ string ICustomTypeDescriptor.GetComponentName() { /// Retrieves the type converter for this object. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - TypeConverter ICustomTypeDescriptor.GetConverter() { + TypeConverter ICustomTypeDescriptor.GetConverter() + { return null; } [EditorBrowsable(EditorBrowsableState.Advanced)] - EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { + EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() + { return TypeDescriptor.GetDefaultEvent(this, true); } [EditorBrowsable(EditorBrowsableState.Advanced)] - PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { + PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() + { return TypeDescriptor.GetDefaultProperty(this, true); } @@ -2417,74 +2799,92 @@ PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { /// Retrieves the an editor for this object. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { + object ICustomTypeDescriptor.GetEditor(Type editorBaseType) + { if (editorBaseType != typeof(ComponentEditor)) return null; - + if (editor != null) return editor; if (editor == null && HasPropertyPages()) editor = new AxComponentEditor(); - + return editor; } [EditorBrowsable(EditorBrowsableState.Advanced)] - EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { + EventDescriptorCollection ICustomTypeDescriptor.GetEvents() + { return TypeDescriptor.GetEvents(this, true); } [EditorBrowsable(EditorBrowsableState.Advanced)] - EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { + EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) + { return TypeDescriptor.GetEvents(this, attributes, true); } - private void OnIdle(object sender, EventArgs e) { - if (axState[refreshProperties]) { + private void OnIdle(object sender, EventArgs e) + { + if (axState[refreshProperties]) + { TypeDescriptor.Refresh(this.GetType()); } } - private bool RefreshAllProperties { - get { + private bool RefreshAllProperties + { + get + { return axState[refreshProperties]; } - set { + set + { axState[refreshProperties] = value; - if (value && !axState[listeningToIdle]) { + if (value && !axState[listeningToIdle]) + { Application.Idle += new EventHandler(this.OnIdle); axState[listeningToIdle] = true; } - else if (!value && axState[listeningToIdle]) { + else if (!value && axState[listeningToIdle]) + { Application.Idle -= new EventHandler(this.OnIdle); axState[listeningToIdle] = false; } } } - private PropertyDescriptorCollection FillProperties(Attribute[] attributes) { - if (RefreshAllProperties) { + private PropertyDescriptorCollection FillProperties(Attribute[] attributes) + { + if (RefreshAllProperties) + { RefreshAllProperties = false; propsStash = null; attribsStash = null; } - else if (propsStash != null) { - if (attributes == null && attribsStash == null) { + else if (propsStash != null) + { + if (attributes == null && attribsStash == null) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Returning stashed values for : " + ""); return propsStash; } - else if (attributes != null && attribsStash != null && attributes.Length == attribsStash.Length) { + else if (attributes != null && attribsStash != null && attributes.Length == attribsStash.Length) + { bool attribsEqual = true; int i = 0; - foreach(Attribute attrib in attributes) { - if (!attrib.Equals(attribsStash[i++])) { + foreach (Attribute attrib in attributes) + { + if (!attrib.Equals(attribsStash[i++])) + { attribsEqual = false; break; } } - if (attribsEqual) { + if (attribsEqual) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Returning stashed values for : " + attributes.Length); return propsStash; } @@ -2496,21 +2896,25 @@ private PropertyDescriptorCollection FillProperties(Attribute[] attributes) { if (properties == null) properties = new Hashtable(); - if (propertyInfos == null) { + if (propertyInfos == null) + { propertyInfos = new Hashtable(); PropertyInfo[] propInfos = this.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance); - foreach(PropertyInfo propInfo in propInfos) + foreach (PropertyInfo propInfo in propInfos) propertyInfos.Add(propInfo.Name, propInfo); } PropertyDescriptorCollection baseProps = TypeDescriptor.GetProperties(this, null, true); - if (baseProps != null) { - for (int i = 0; i < baseProps.Count; ++i) { + if (baseProps != null) + { + for (int i = 0; i < baseProps.Count; ++i) + { Debug.Assert(baseProps[i] != null, "Null base prop at location: " + i.ToString(CultureInfo.InvariantCulture)); - if (baseProps[i].DesignTimeOnly) { + if (baseProps[i].DesignTimeOnly) + { retProps.Add(baseProps[i]); continue; } @@ -2523,29 +2927,36 @@ private PropertyDescriptorCollection FillProperties(Attribute[] attributes) { if (propInfo != null && !propInfo.CanRead) continue; - if (!properties.ContainsKey(propName)) { - if (propInfo != null) { + if (!properties.ContainsKey(propName)) + { + if (propInfo != null) + { Debug.WriteLineIf(AxPropTraceSwitch.TraceVerbose, "Added AxPropertyDescriptor for: " + propName); prop = new AxPropertyDescriptor(baseProps[i], this); ((AxPropertyDescriptor)prop).UpdateAttributes(); } - else { + else + { Debug.WriteLineIf(AxPropTraceSwitch.TraceVerbose, "Added PropertyDescriptor for: " + propName); prop = baseProps[i]; } properties.Add(propName, prop); retProps.Add(prop); } - else { + else + { PropertyDescriptor propDesc = (PropertyDescriptor)properties[propName]; Debug.Assert(propDesc != null, "Cannot find cached entry for: " + propName); AxPropertyDescriptor axPropDesc = propDesc as AxPropertyDescriptor; - if ((propInfo == null && axPropDesc != null) || (propInfo != null && axPropDesc == null)) { + if ((propInfo == null && axPropDesc != null) || (propInfo != null && axPropDesc == null)) + { Debug.Fail("Duplicate property with same name: " + propName); Debug.WriteLineIf(AxPropTraceSwitch.TraceVerbose, "Duplicate property with same name: " + propName); } - else { - if (axPropDesc != null) { + else + { + if (axPropDesc != null) + { axPropDesc.UpdateAttributes(); } retProps.Add(propDesc); @@ -2556,22 +2967,30 @@ private PropertyDescriptorCollection FillProperties(Attribute[] attributes) { // Filter only the Browsable attribute, since that is the only // one we mess with. // - if (attributes != null) { + if (attributes != null) + { Attribute browse = null; - foreach(Attribute attr in attributes) { - if (attr is BrowsableAttribute) { + foreach (Attribute attr in attributes) + { + if (attr is BrowsableAttribute) + { browse = attr; } } - if (browse != null) { + if (browse != null) + { ArrayList removeList = null; - foreach(PropertyDescriptor prop in retProps) { - if (prop is AxPropertyDescriptor) { + foreach (PropertyDescriptor prop in retProps) + { + if (prop is AxPropertyDescriptor) + { Attribute attr = prop.Attributes[typeof(BrowsableAttribute)]; - if (attr != null && !attr.Equals(browse)) { - if (removeList == null) { + if (attr != null && !attr.Equals(browse)) + { + if (removeList == null) + { removeList = new ArrayList(); } removeList.Add(prop); @@ -2579,8 +2998,9 @@ private PropertyDescriptorCollection FillProperties(Attribute[] attributes) { } } - if (removeList != null) { - foreach(object prop in removeList) + if (removeList != null) + { + foreach (object prop in removeList) retProps.Remove(prop); } } @@ -2589,39 +3009,45 @@ private PropertyDescriptorCollection FillProperties(Attribute[] attributes) { PropertyDescriptor[] temp = new PropertyDescriptor[retProps.Count]; retProps.CopyTo(temp, 0); - + // Update our stashed values. // Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Updating stashed values for : " + ((attributes != null) ? attributes.Length.ToString(CultureInfo.InvariantCulture) : "")); propsStash = new PropertyDescriptorCollection(temp); attribsStash = attributes; - + return propsStash; } [EditorBrowsable(EditorBrowsableState.Advanced)] - PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { + PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() + { return FillProperties(null); } [EditorBrowsable(EditorBrowsableState.Advanced)] - PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { + PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) + { return FillProperties(attributes); } [EditorBrowsable(EditorBrowsableState.Advanced)] - object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { + object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) + { return this; } - private AxPropertyDescriptor GetPropertyDescriptorFromDispid(int dispid) { + private AxPropertyDescriptor GetPropertyDescriptorFromDispid(int dispid) + { Debug.Assert(dispid != NativeMethods.ActiveX.DISPID_UNKNOWN, "Wrong dispid sent to GetPropertyDescriptorFromDispid"); PropertyDescriptorCollection props = FillProperties(null); - foreach (PropertyDescriptor prop in props) { + foreach (PropertyDescriptor prop in props) + { AxPropertyDescriptor axprop = prop as AxPropertyDescriptor; - if (axprop != null && axprop.Dispid == dispid) { - return axprop; + if (axprop != null && axprop.Dispid == dispid) + { + return axprop; } } @@ -2663,11 +3089,14 @@ private void CheckThreadingModel() { } #endif - private void ActivateAxControl() { - if (QuickActivate()) { + private void ActivateAxControl() + { + if (QuickActivate()) + { DepersistControl(); } - else { + else + { SlowActivate(); } @@ -2675,21 +3104,25 @@ private void ActivateAxControl() { } - private void DepersistFromIPropertyBag(UnsafeNativeMethods.IPropertyBag propBag) { + private void DepersistFromIPropertyBag(UnsafeNativeMethods.IPropertyBag propBag) + { iPersistPropBag.Load(propBag, null); } - private void DepersistFromIStream(UnsafeNativeMethods.IStream istream) { + private void DepersistFromIStream(UnsafeNativeMethods.IStream istream) + { storageType = STG_STREAM; iPersistStream.Load(istream); } - private void DepersistFromIStreamInit(UnsafeNativeMethods.IStream istream) { + private void DepersistFromIStreamInit(UnsafeNativeMethods.IStream istream) + { storageType = STG_STREAMINIT; iPersistStreamInit.Load(istream); } - private void DepersistFromIStorage(UnsafeNativeMethods.IStorage storage) { + private void DepersistFromIStorage(UnsafeNativeMethods.IStorage storage) + { storageType = STG_STORAGE; // Looks like MapPoint control does not create a valid IStorage @@ -2697,112 +3130,138 @@ private void DepersistFromIStorage(UnsafeNativeMethods.IStorage storage) { // storage, we end up not being able to re-create a valid one and this would // fail. // - if (storage != null) { + if (storage != null) + { int hr = iPersistStorage.Load(storage); - if (hr != NativeMethods.S_OK) { + if (hr != NativeMethods.S_OK) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Error trying load depersist from IStorage: " + hr); } } } - private void DepersistControl() { + private void DepersistControl() + { Freeze(true); - if (ocxState == null) { + if (ocxState == null) + { // must init new: // - if (instance is UnsafeNativeMethods.IPersistStreamInit) { - iPersistStreamInit = (UnsafeNativeMethods.IPersistStreamInit) instance; - try { + if (instance is UnsafeNativeMethods.IPersistStreamInit) + { + iPersistStreamInit = (UnsafeNativeMethods.IPersistStreamInit)instance; + try + { storageType = STG_STREAMINIT; iPersistStreamInit.InitNew(); } - catch (Exception e1) { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Exception thrown trying to IPersistStreamInit.InitNew(). Is this good?" + e1.ToString()); + catch (Exception e1) + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Exception thrown trying to IPersistStreamInit.InitNew(). Is this good?" + e1.ToString()); } return; } - if (instance is UnsafeNativeMethods.IPersistStream) { + if (instance is UnsafeNativeMethods.IPersistStream) + { storageType = STG_STREAM; - iPersistStream = (UnsafeNativeMethods.IPersistStream) instance; + iPersistStream = (UnsafeNativeMethods.IPersistStream)instance; return; } - if (instance is UnsafeNativeMethods.IPersistStorage) { + if (instance is UnsafeNativeMethods.IPersistStorage) + { storageType = STG_STORAGE; ocxState = new State(this); - iPersistStorage = (UnsafeNativeMethods.IPersistStorage) instance; - try { + iPersistStorage = (UnsafeNativeMethods.IPersistStorage)instance; + try + { iPersistStorage.InitNew(ocxState.GetStorage()); } - catch (Exception e2) { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Exception thrown trying to IPersistStorage.InitNew(). Is this good?" + e2.ToString()); + catch (Exception e2) + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Exception thrown trying to IPersistStorage.InitNew(). Is this good?" + e2.ToString()); } return; } - if (instance is UnsafeNativeMethods.IPersistPropertyBag) { + if (instance is UnsafeNativeMethods.IPersistPropertyBag) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, this + " supports IPersistPropertyBag."); - iPersistPropBag = (UnsafeNativeMethods.IPersistPropertyBag) instance; - try { + iPersistPropBag = (UnsafeNativeMethods.IPersistPropertyBag)instance; + try + { iPersistPropBag.InitNew(); } - catch (Exception e1) { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Exception thrown trying to IPersistPropertyBag.InitNew(). Is this good?" + e1.ToString()); + catch (Exception e1) + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Exception thrown trying to IPersistPropertyBag.InitNew(). Is this good?" + e1.ToString()); } } - + Debug.Fail("no implemented persitance interfaces on object"); throw new InvalidOperationException(SR.UnableToInitComponent); } - + // Otherwise, we have state to deperist from: - switch (ocxState.Type) { + switch (ocxState.Type) + { case STG_STREAM: - try { - iPersistStream = (UnsafeNativeMethods.IPersistStream) instance; + try + { + iPersistStream = (UnsafeNativeMethods.IPersistStream)instance; DepersistFromIStream(ocxState.GetStream()); } - catch (Exception e) { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Exception thrown trying to IPersistStream.DepersistFromIStream(). Is this good?" + e.ToString()); + catch (Exception e) + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Exception thrown trying to IPersistStream.DepersistFromIStream(). Is this good?" + e.ToString()); } break; case STG_STREAMINIT: - if (instance is UnsafeNativeMethods.IPersistStreamInit) { - try { - iPersistStreamInit = (UnsafeNativeMethods.IPersistStreamInit) instance; + if (instance is UnsafeNativeMethods.IPersistStreamInit) + { + try + { + iPersistStreamInit = (UnsafeNativeMethods.IPersistStreamInit)instance; DepersistFromIStreamInit(ocxState.GetStream()); } - catch (Exception e) { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Exception thrown trying to IPersistStreamInit.DepersistFromIStreamInit(). Is this good?" + e.ToString()); + catch (Exception e) + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Exception thrown trying to IPersistStreamInit.DepersistFromIStreamInit(). Is this good?" + e.ToString()); } GetControlEnabled(); } - else { + else + { ocxState.Type = STG_STREAM; DepersistControl(); return; } break; case STG_STORAGE: - try { - iPersistStorage = (UnsafeNativeMethods.IPersistStorage) instance; + try + { + iPersistStorage = (UnsafeNativeMethods.IPersistStorage)instance; DepersistFromIStorage(ocxState.GetStorage()); } - catch (Exception e) { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Exception thrown trying to IPersistStorage.DepersistFromIStorage(). Is this good?" + e.ToString()); + catch (Exception e) + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Exception thrown trying to IPersistStorage.DepersistFromIStorage(). Is this good?" + e.ToString()); } break; default: Debug.Fail("unknown storage type."); throw new InvalidOperationException(SR.UnableToInitComponent); } - - if (ocxState.GetPropBag() != null) { - try { + + if (ocxState.GetPropBag() != null) + { + try + { iPersistPropBag = (UnsafeNativeMethods.IPersistPropertyBag)instance; DepersistFromIPropertyBag(ocxState.GetPropBag()); } - catch (Exception e) { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Exception thrown trying to IPersistPropertyBag.DepersistFromIPropertyBag(). Is this good?" + e.ToString()); + catch (Exception e) + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Exception thrown trying to IPersistPropertyBag.DepersistFromIPropertyBag(). Is this good?" + e.ToString()); } } } @@ -2812,13 +3271,16 @@ private void DepersistControl() { /// [EditorBrowsable(EditorBrowsableState.Advanced)] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] - public object GetOcx() { + public object GetOcx() + { return instance; } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] - private object GetOcxCreate() { - if (instance == null) { + private object GetOcxCreate() + { + if (instance == null) + { CreateInstance(); RealizeStyles(); AttachInterfaces(); @@ -2827,26 +3289,34 @@ private object GetOcxCreate() { return instance; } - private void StartEvents() { - if (!axState[sinkAttached]) { - try { + private void StartEvents() + { + if (!axState[sinkAttached]) + { + try + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Creating sink for events..."); CreateSink(); oleSite.StartEvents(); } - catch (Exception t) { + catch (Exception t) + { Debug.Fail(t.ToString()); } axState[sinkAttached] = true; } } - private void StopEvents() { - if (axState[sinkAttached]) { - try { + private void StopEvents() + { + if (axState[sinkAttached]) + { + try + { DetachSink(); } - catch (Exception t) { + catch (Exception t) + { Debug.Fail(t.ToString()); } axState[sinkAttached] = false; @@ -2855,89 +3325,114 @@ private void StopEvents() { } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void CreateSink() { - // nop... windows forms wrapper will override... + protected virtual void CreateSink() + { + // nop... windows forms wrapper will override... } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void DetachSink() { - // nop... windows forms wrapper will override... + protected virtual void DetachSink() + { + // nop... windows forms wrapper will override... } - private bool CanShowPropertyPages() { - if (GetOcState() < OC_RUNNING) return false; - return(GetOcx() is NativeMethods.ISpecifyPropertyPages); + private bool CanShowPropertyPages() + { + if (GetOcState() < OC_RUNNING) + return false; + return (GetOcx() is NativeMethods.ISpecifyPropertyPages); } - public bool HasPropertyPages() { - if (!CanShowPropertyPages()) return false; - NativeMethods.ISpecifyPropertyPages ispp = (NativeMethods.ISpecifyPropertyPages) GetOcx(); - try { + public bool HasPropertyPages() + { + if (!CanShowPropertyPages()) + return false; + NativeMethods.ISpecifyPropertyPages ispp = (NativeMethods.ISpecifyPropertyPages)GetOcx(); + try + { NativeMethods.tagCAUUID uuids = new NativeMethods.tagCAUUID(); - try { + try + { ispp.GetPages(uuids); - if (uuids.cElems > 0) return true; + if (uuids.cElems > 0) + return true; } - finally { - if (uuids.pElems != IntPtr.Zero) { + finally + { + if (uuids.pElems != IntPtr.Zero) + { Marshal.FreeCoTaskMem(uuids.pElems); } } } - catch { + catch + { } return false; } - unsafe private void ShowPropertyPageForDispid(int dispid, Guid guid) { - try { + unsafe private void ShowPropertyPageForDispid(int dispid, Guid guid) + { + try + { IntPtr pUnk = Marshal.GetIUnknownForObject(GetOcx()); NativeMethods.OCPFIPARAMS opcparams = new NativeMethods.OCPFIPARAMS(); opcparams.hwndOwner = (ContainingControl == null) ? IntPtr.Zero : ContainingControl.Handle; opcparams.lpszCaption = Name; - opcparams.ppUnk = (IntPtr) (long) &pUnk; - opcparams.uuid = (IntPtr)(long) &guid; + opcparams.ppUnk = (IntPtr)(long)&pUnk; + opcparams.uuid = (IntPtr)(long)&guid; opcparams.dispidInitial = dispid; UnsafeNativeMethods.OleCreatePropertyFrameIndirect(opcparams); } - catch (Exception t) { + catch (Exception t) + { Debug.Fail(t.ToString()); throw t; } } [EditorBrowsable(EditorBrowsableState.Advanced)] - public void MakeDirty() { + public void MakeDirty() + { ISite isite = Site; if (isite == null) return; - + IComponentChangeService ccs = (IComponentChangeService)isite.GetService(typeof(IComponentChangeService)); if (ccs == null) return; - + ccs.OnComponentChanging(this, null); - + ccs.OnComponentChanged(this, null, null, null); } - public void ShowPropertyPages() { - if (ParentInternal == null) return; - if (!ParentInternal.IsHandleCreated) return; + public void ShowPropertyPages() + { + if (ParentInternal == null) + return; + if (!ParentInternal.IsHandleCreated) + return; ShowPropertyPages(ParentInternal); } - public void ShowPropertyPages(Control control) { - try { - if (!CanShowPropertyPages()) return; - NativeMethods.ISpecifyPropertyPages ispp = (NativeMethods.ISpecifyPropertyPages) GetOcx(); + public void ShowPropertyPages(Control control) + { + try + { + if (!CanShowPropertyPages()) + return; + NativeMethods.ISpecifyPropertyPages ispp = (NativeMethods.ISpecifyPropertyPages)GetOcx(); NativeMethods.tagCAUUID uuids = new NativeMethods.tagCAUUID(); - try { + try + { ispp.GetPages(uuids); - if (uuids.cElems <= 0) return; + if (uuids.cElems <= 0) + return; } - catch { + catch + { return; } @@ -2946,9 +3441,10 @@ public void ShowPropertyPages(Control control) { IDesignerHost host = null; if (Site != null) host = (IDesignerHost)Site.GetService(typeof(IDesignerHost)); - + DesignerTransaction trans = null; - try { + try + { if (host != null) trans = host.CreateTransaction(SR.AXEditProperties); @@ -2957,7 +3453,8 @@ public void ShowPropertyPages(Control control) { IntPtr handle = (ContainingControl == null) ? IntPtr.Zero : ContainingControl.Handle; SafeNativeMethods.OleCreatePropertyFrame(new HandleRef(this, handle), 0, 0, name, 1, ref o, uuids.cElems, new HandleRef(null, uuids.pElems), Application.CurrentCulture.LCID, 0, IntPtr.Zero); } - finally { + finally + { if (oleSite != null) ((UnsafeNativeMethods.IPropertyNotifySink)oleSite).OnChanged(NativeMethods.MEMBERID_NIL); @@ -2968,22 +3465,25 @@ public void ShowPropertyPages(Control control) { Marshal.FreeCoTaskMem(uuids.pElems); } } - catch (Exception t) { + catch (Exception t) + { Debug.Fail(t.ToString()); throw t; } } - internal override IntPtr InitializeDCForWmCtlColor (IntPtr dc, int msg) + internal override IntPtr InitializeDCForWmCtlColor(IntPtr dc, int msg) { - if (isMaskEdit) { + if (isMaskEdit) + { return base.InitializeDCForWmCtlColor(dc, msg); } - else { + else + { return IntPtr.Zero; // bypass Control's anti-reflect logic } } - + /// /// AxHost wndProc. All messages are sent to wndProc after getting filtered /// through the preProcessMessage function. @@ -2991,20 +3491,23 @@ internal override IntPtr InitializeDCForWmCtlColor (IntPtr dc, int msg) /// others are first processed by the wndProc of Control /// - protected override void WndProc(ref Message m) { + protected override void WndProc(ref Message m) + { #pragma warning disable 162, 429 -// Ignore the warnings generated by the following code (unreachable code, and unreachable expression) - if (false && (axState[manualUpdate] && IsUserMode())) { + // Ignore the warnings generated by the following code (unreachable code, and unreachable expression) + if (false && (axState[manualUpdate] && IsUserMode())) + { DefWndProc(ref m); return; } #pragma warning restore 162, 429 - switch (m.Msg) { + switch (m.Msg) + { // Things we explicitly ignore and pass to the ocx's windproc case Interop.WindowMessages.WM_ERASEBKGND: - + case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_NOTIFYFORMAT: case Interop.WindowMessages.WM_SETCURSOR: @@ -3015,7 +3518,7 @@ protected override void WndProc(ref Message m) { // through. // case Interop.WindowMessages.WM_DRAWITEM: - + case Interop.WindowMessages.WM_LBUTTONDBLCLK: case Interop.WindowMessages.WM_LBUTTONUP: case Interop.WindowMessages.WM_MBUTTONDBLCLK: @@ -3028,23 +3531,26 @@ protected override void WndProc(ref Message m) { case Interop.WindowMessages.WM_LBUTTONDOWN: case Interop.WindowMessages.WM_MBUTTONDOWN: case Interop.WindowMessages.WM_RBUTTONDOWN: - if (IsUserMode()) { + if (IsUserMode()) + { Focus(); } DefWndProc(ref m); break; case Interop.WindowMessages.WM_KILLFOCUS: - { - hwndFocus = m.WParam; - try { - base.WndProc(ref m); - } - finally { - hwndFocus = IntPtr.Zero; + { + hwndFocus = m.WParam; + try + { + base.WndProc(ref m); + } + finally + { + hwndFocus = IntPtr.Zero; + } + break; } - break; - } case Interop.WindowMessages.WM_COMMAND: if (!ReflectMessage(m.LParam, ref m)) @@ -3052,14 +3558,15 @@ protected override void WndProc(ref Message m) { DefWndProc(ref m); } break; - + case Interop.WindowMessages.WM_CONTEXTMENU: DefWndProc(ref m); break; case Interop.WindowMessages.WM_DESTROY: #if DEBUG - if (!OwnWindow()) { + if (!OwnWindow()) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "WM_DESTROY naughty control is destroying the window from under us..." + GetType().ToString()); } #endif @@ -3070,20 +3577,23 @@ protected override void WndProc(ref Message m) { // Otherwise we face all sorts of problems when we try to // transition back to a state >= InPlaceActive. // - if (GetOcState() >= OC_INPLACE) { + if (GetOcState() >= OC_INPLACE) + { UnsafeNativeMethods.IOleInPlaceObject ipo = GetInPlaceObject(); IntPtr hwnd; - if (NativeMethods.Succeeded(ipo.GetWindow(out hwnd))) { + if (NativeMethods.Succeeded(ipo.GetWindow(out hwnd))) + { Application.ParkHandle(new HandleRef(ipo, hwnd)); } } - + bool visible = GetState(STATE_VISIBLE); TransitionDownTo(OC_RUNNING); DetachAndForward(ref m); - if (visible != GetState(STATE_VISIBLE)) { + if (visible != GetState(STATE_VISIBLE)) + { SetState(STATE_VISIBLE, visible); } @@ -3097,13 +3607,15 @@ protected override void WndProc(ref Message m) { case Interop.WindowMessages.WM_KEYUP: if (axState[processingKeyUp]) break; - + axState[processingKeyUp] = true; - try { + try + { if (PreProcessControlMessage(ref m) != PreProcessControlState.MessageProcessed) DefWndProc(ref m); } - finally { + finally + { axState[processingKeyUp] = false; } @@ -3111,7 +3623,8 @@ protected override void WndProc(ref Message m) { case Interop.WindowMessages.WM_NCDESTROY: #if DEBUG - if (!OwnWindow()) { + if (!OwnWindow()) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "WM_NCDESTROY naughty control is destroying the window from under us..." + GetType().ToString()); } #endif @@ -3120,7 +3633,8 @@ protected override void WndProc(ref Message m) { break; default: - if (m.Msg == REGMSG_MSG) { + if (m.Msg == REGMSG_MSG) + { m.Result = (IntPtr)REGMSG_RETVAL; return; } @@ -3130,19 +3644,24 @@ protected override void WndProc(ref Message m) { } } - private void DetachAndForward(ref Message m) { + private void DetachAndForward(ref Message m) + { IntPtr handle = GetHandleNoCreate(); DetachWindow(); - if (handle != IntPtr.Zero) { + if (handle != IntPtr.Zero) + { IntPtr wndProc = UnsafeNativeMethods.GetWindowLong(new HandleRef(this, handle), NativeMethods.GWL_WNDPROC); m.Result = UnsafeNativeMethods.CallWindowProc(wndProc, handle, m.Msg, m.WParam, m.LParam); } } - private void DetachWindow() { - if (IsHandleCreated) { + private void DetachWindow() + { + if (IsHandleCreated) + { OnHandleDestroyed(EventArgs.Empty); - for (Control c = this; c != null; c = c.ParentInternal) { + for (Control c = this; c != null; c = c.ParentInternal) + { /* NOT NEEDED if (c.GetAxState(STATE_HANDLEHOOK)) { ((IHandleHook)c.Site.GetService(IHandleHook.class)).OnDestroyHandle(GetHandle()); @@ -3154,9 +3673,11 @@ private void DetachWindow() { } } - private void InformOfNewHandle() { + private void InformOfNewHandle() + { Debug.Assert(IsHandleCreated, "we got to have a handle to be here..."); - for (Control c = this; c != null; c = c.ParentInternal) { + for (Control c = this; c != null; c = c.ParentInternal) + { /* NOT NEEDED if (c.GetAxState(STATE_HANDLEHOOK)) { ((IHandleHook)c.Site.GetService(IHandleHook.class)).OnCreateHandle(GetHandle()); @@ -3170,9 +3691,11 @@ private void InformOfNewHandle() { */ } - private void AttachWindow(IntPtr hwnd) { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "attaching window for "+this.ToString()+" "+hwnd.ToString()); - if (!axState[fFakingWindow]) { + private void AttachWindow(IntPtr hwnd) + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "attaching window for " + this.ToString() + " " + hwnd.ToString()); + if (!axState[fFakingWindow]) + { this.WindowAssignHandle(hwnd, axState[assignUniqueID]); } UpdateZOrder(); @@ -3191,9 +3714,11 @@ private void AttachWindow(IntPtr hwnd) { // Choose the setBounds unless it is smaller than the default bounds. if (setExtent.Width < ocxExtent.Width || setExtent.Height < ocxExtent.Height) Bounds = new Rectangle(location.X, location.Y, ocxExtent.Width, ocxExtent.Height); - else { + else + { Size newSize = SetExtent(setExtent.Width, setExtent.Height); - if (!newSize.Equals(setExtent)) { + if (!newSize.Equals(setExtent)) + { Bounds = new Rectangle(location.X, location.Y, newSize.Width, newSize.Height); } } @@ -3207,13 +3732,15 @@ private void AttachWindow(IntPtr hwnd) { /// handle has been created. /// Call base.OnHandleCreated first. /// - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { // This is needed to prevent some controls (for e.g. Office Web Components) from // failing to InPlaceActivate() when they call RegisterDragDrop() but do not call // OleInitialize(). The EE calls CoInitializeEx() on the thread, but I believe // that is not good enough for DragDrop. // - if (Application.OleRequired() != System.Threading.ApartmentState.STA) { + if (Application.OleRequired() != System.Threading.ApartmentState.STA) + { throw new ThreadStateException(SR.ThreadMustBeSTA); } @@ -3221,37 +3748,46 @@ protected override void OnHandleCreated(EventArgs e) { RaiseCreateHandleEvent(e); } - [AttributeUsage(AttributeTargets.Class, Inherited = false)] - public sealed class ClsidAttribute : Attribute { + [AttributeUsage(AttributeTargets.Class, Inherited = false)] + public sealed class ClsidAttribute : Attribute + { private string val; - public ClsidAttribute(string clsid) { + public ClsidAttribute(string clsid) + { val = clsid; } - - public string Value { - get { + + public string Value + { + get + { return val; - } + } } - } + } - [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] - public sealed class TypeLibraryTimeStampAttribute : Attribute { + [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] + public sealed class TypeLibraryTimeStampAttribute : Attribute + { private DateTime val; - public TypeLibraryTimeStampAttribute(string timestamp) { + public TypeLibraryTimeStampAttribute(string timestamp) + { val = DateTime.Parse(timestamp, CultureInfo.InvariantCulture); } - - public DateTime Value { - get { + + public DateTime Value + { + get + { return val; } - } - } + } + } - public class ConnectionPointCookie { + public class ConnectionPointCookie + { private UnsafeNativeMethods.IConnectionPoint connectionPoint; private int cookie; internal int threadId; @@ -3262,61 +3798,80 @@ public class ConnectionPointCookie { /// Creates a connection point to of the given interface type. /// which will call on a managed code sink that implements that interface. /// - public ConnectionPointCookie(object source, object sink, Type eventInterface) - : this(source, sink, eventInterface, true) { + public ConnectionPointCookie(object source, object sink, Type eventInterface) + : this(source, sink, eventInterface, true) + { } - internal ConnectionPointCookie(object source, object sink, Type eventInterface, bool throwException) { - if (source is UnsafeNativeMethods.IConnectionPointContainer) { + internal ConnectionPointCookie(object source, object sink, Type eventInterface, bool throwException) + { + if (source is UnsafeNativeMethods.IConnectionPointContainer) + { UnsafeNativeMethods.IConnectionPointContainer cpc = (UnsafeNativeMethods.IConnectionPointContainer)source; - try { + try + { Guid tmp = eventInterface.GUID; - if (cpc.FindConnectionPoint(ref tmp, out connectionPoint) != NativeMethods.S_OK) { + if (cpc.FindConnectionPoint(ref tmp, out connectionPoint) != NativeMethods.S_OK) + { connectionPoint = null; } } - catch { + catch + { connectionPoint = null; } - if (connectionPoint == null) { - if (throwException) { + if (connectionPoint == null) + { + if (throwException) + { throw new ArgumentException(string.Format(SR.AXNoEventInterface, eventInterface.Name)); } } - else if (sink == null || !eventInterface.IsInstanceOfType(sink)) { - if (throwException) { + else if (sink == null || !eventInterface.IsInstanceOfType(sink)) + { + if (throwException) + { throw new InvalidCastException(string.Format(SR.AXNoSinkImplementation, eventInterface.Name)); } } - else { + else + { int hr = connectionPoint.Advise(sink, ref cookie); - if (hr == NativeMethods.S_OK) { + if (hr == NativeMethods.S_OK) + { threadId = Thread.CurrentThread.ManagedThreadId; } - else { + else + { cookie = 0; Marshal.ReleaseComObject(connectionPoint); connectionPoint = null; - if (throwException) { + if (throwException) + { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, string.Format(SR.AXNoSinkAdvise, eventInterface.Name), hr)); } } } } - else { - if (throwException) { + else + { + if (throwException) + { throw new InvalidCastException(SR.AXNoConnectionPointContainer); } } - if (connectionPoint == null || cookie == 0) { - if (connectionPoint != null) { + if (connectionPoint == null || cookie == 0) + { + if (connectionPoint != null) + { Marshal.ReleaseComObject(connectionPoint); } - if (throwException) { + if (throwException) + { throw new ArgumentException(string.Format(SR.AXNoConnectionPoint, eventInterface.Name)); } } @@ -3329,59 +3884,79 @@ internal ConnectionPointCookie(object source, object sink, Type eventInterface, /// Disconnect the current connection point. If the object is not connected, /// this method will do nothing. /// - public void Disconnect() { - if (connectionPoint != null && cookie != 0) { - try { + public void Disconnect() + { + if (connectionPoint != null && cookie != 0) + { + try + { connectionPoint.Unadvise(cookie); } - catch (Exception ex) { - if (ClientUtils.IsCriticalException(ex)) { + catch (Exception ex) + { + if (ClientUtils.IsCriticalException(ex)) + { throw; } } - finally { + finally + { cookie = 0; } - - try { + + try + { Marshal.ReleaseComObject(connectionPoint); } - catch (Exception ex) { - if (ClientUtils.IsCriticalException(ex)) { + catch (Exception ex) + { + if (ClientUtils.IsCriticalException(ex)) + { throw; } } - finally { + finally + { connectionPoint = null; } } } - ~ConnectionPointCookie(){ - if (connectionPoint != null && cookie != 0) { - if (!AppDomain.CurrentDomain.IsFinalizingForUnload()) { + ~ConnectionPointCookie() + { + if (connectionPoint != null && cookie != 0) + { + if (!AppDomain.CurrentDomain.IsFinalizingForUnload()) + { SynchronizationContext context = SynchronizationContext.Current; - if (context == null) { + if (context == null) + { Debug.Fail("Attempted to disconnect ConnectionPointCookie from the finalizer with no SynchronizationContext."); } - else { + else + { context.Post(new SendOrPostCallback(AttemptDisconnect), null); } } } } - void AttemptDisconnect(object trash) { - if (threadId == Thread.CurrentThread.ManagedThreadId) { + void AttemptDisconnect(object trash) + { + if (threadId == Thread.CurrentThread.ManagedThreadId) + { Disconnect(); } - else { + else + { Debug.Fail("Attempted to disconnect ConnectionPointCookie from the wrong thread (finalizer)."); } } - internal bool Connected { - get { + internal bool Connected + { + get + { return connectionPoint != null && cookie != 0; } } @@ -3394,20 +3969,25 @@ public enum ActiveXInvokeKind PropertySet } - public class InvalidActiveXStateException : Exception { + public class InvalidActiveXStateException : Exception + { private string name; private ActiveXInvokeKind kind; - - public InvalidActiveXStateException(string name, ActiveXInvokeKind kind) { + + public InvalidActiveXStateException(string name, ActiveXInvokeKind kind) + { this.name = name; this.kind = kind; } - public InvalidActiveXStateException() { + public InvalidActiveXStateException() + { } - - public override string ToString() { - switch (kind) { + + public override string ToString() + { + switch (kind) + { case ActiveXInvokeKind.MethodInvoke: return string.Format(SR.AXInvalidMethodInvoke, name); case ActiveXInvokeKind.PropertyGet: @@ -3419,79 +3999,98 @@ public override string ToString() { } } } - + // This private class encapsulates all of the ole interfaces so that users // will not be able to access and call them directly... /// /// private class OleInterfaces - : UnsafeNativeMethods.IOleControlSite, UnsafeNativeMethods.IOleClientSite, UnsafeNativeMethods.IOleInPlaceSite, UnsafeNativeMethods.ISimpleFrameSite, UnsafeNativeMethods.IVBGetControl, UnsafeNativeMethods.IGetVBAObject, UnsafeNativeMethods.IPropertyNotifySink, IReflect, IDisposable { + : UnsafeNativeMethods.IOleControlSite, UnsafeNativeMethods.IOleClientSite, UnsafeNativeMethods.IOleInPlaceSite, UnsafeNativeMethods.ISimpleFrameSite, UnsafeNativeMethods.IVBGetControl, UnsafeNativeMethods.IGetVBAObject, UnsafeNativeMethods.IPropertyNotifySink, IReflect, IDisposable + { private AxHost host; private ConnectionPointCookie connectionPoint; - internal OleInterfaces(AxHost host) { + internal OleInterfaces(AxHost host) + { if (host == null) throw new ArgumentNullException(nameof(host)); this.host = host; } - private void Dispose(bool disposing) { - if (disposing) { - if (!AppDomain.CurrentDomain.IsFinalizingForUnload()) { + private void Dispose(bool disposing) + { + if (disposing) + { + if (!AppDomain.CurrentDomain.IsFinalizingForUnload()) + { SynchronizationContext context = SynchronizationContext.Current; - if (context == null) { + if (context == null) + { Debug.Fail("Attempted to disconnect ConnectionPointCookie from the finalizer with no SynchronizationContext."); } - else { + else + { context.Post(new SendOrPostCallback(AttemptStopEvents), null); } } } } - public void Dispose() { + public void Dispose() + { Dispose(true); GC.SuppressFinalize(this); } - internal AxHost GetAxHost() { + internal AxHost GetAxHost() + { return host; } - internal void OnOcxCreate() { + internal void OnOcxCreate() + { StartEvents(); } - internal void StartEvents() { + internal void StartEvents() + { if (connectionPoint != null) return; object nativeObject = host.GetOcx(); - try { + try + { connectionPoint = new ConnectionPointCookie(nativeObject, this, typeof(UnsafeNativeMethods.IPropertyNotifySink)); } - catch { + catch + { } } - void AttemptStopEvents(object trash) { - if( connectionPoint == null ){ + void AttemptStopEvents(object trash) + { + if (connectionPoint == null) + { return; } - if (connectionPoint.threadId == Thread.CurrentThread.ManagedThreadId) { + if (connectionPoint.threadId == Thread.CurrentThread.ManagedThreadId) + { StopEvents(); } - else { + else + { Debug.Fail("Attempted to disconnect ConnectionPointCookie from the wrong thread (finalizer)."); } } - internal void StopEvents() { - if (connectionPoint != null) { + internal void StopEvents() + { + if (connectionPoint != null) + { connectionPoint.Disconnect(); connectionPoint = null; } @@ -3499,17 +4098,20 @@ internal void StopEvents() { // IGetVBAObject methods: - int UnsafeNativeMethods.IGetVBAObject.GetObject(ref Guid riid, UnsafeNativeMethods.IVBFormat[] rval, int dwReserved) { + int UnsafeNativeMethods.IGetVBAObject.GetObject(ref Guid riid, UnsafeNativeMethods.IVBFormat[] rval, int dwReserved) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in GetObject"); - + if (rval == null || riid.Equals(Guid.Empty)) return NativeMethods.E_INVALIDARG; - - if (riid.Equals(ivbformat_Guid)) { + + if (riid.Equals(ivbformat_Guid)) + { rval[0] = new VBFormat(); return NativeMethods.S_OK; } - else { + else + { rval[0] = null; return NativeMethods.E_NOINTERFACE; } @@ -3517,7 +4119,8 @@ int UnsafeNativeMethods.IGetVBAObject.GetObject(ref Guid riid, UnsafeNativeMetho // IVBGetControl methods: - int UnsafeNativeMethods.IVBGetControl.EnumControls(int dwOleContF, int dwWhich, out UnsafeNativeMethods.IEnumUnknown ppenum) { + int UnsafeNativeMethods.IVBGetControl.EnumControls(int dwOleContF, int dwWhich, out UnsafeNativeMethods.IEnumUnknown ppenum) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in EnumControls"); ppenum = null; ppenum = host.GetParentContainer().EnumControls(host, dwOleContF, dwWhich); @@ -3526,87 +4129,107 @@ int UnsafeNativeMethods.IVBGetControl.EnumControls(int dwOleContF, int dwWhich, // ISimpleFrameSite methods: - int UnsafeNativeMethods.ISimpleFrameSite.PreMessageFilter(IntPtr hwnd, int msg, IntPtr wp, IntPtr lp, ref IntPtr plResult, ref int pdwCookie) { + int UnsafeNativeMethods.ISimpleFrameSite.PreMessageFilter(IntPtr hwnd, int msg, IntPtr wp, IntPtr lp, ref IntPtr plResult, ref int pdwCookie) + { return NativeMethods.S_OK; } - int UnsafeNativeMethods.ISimpleFrameSite.PostMessageFilter(IntPtr hwnd, int msg, IntPtr wp, IntPtr lp, ref IntPtr plResult, int dwCookie) { + int UnsafeNativeMethods.ISimpleFrameSite.PostMessageFilter(IntPtr hwnd, int msg, IntPtr wp, IntPtr lp, ref IntPtr plResult, int dwCookie) + { return NativeMethods.S_FALSE; } // IReflect methods: - MethodInfo IReflect.GetMethod(string name,BindingFlags bindingAttr,Binder binder, Type[] types,ParameterModifier[] modifiers) { + MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) + { return null; } - MethodInfo IReflect.GetMethod(string name,BindingFlags bindingAttr) { + MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr) + { return null; } - MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr) { + MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr) + { return new MethodInfo[0]; } - FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr) { + FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr) + { return null; } - FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr) { + FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr) + { return new FieldInfo[0]; } - PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr) { + PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr) + { return null; } - PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { + PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) + { return null; } - PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr) { + PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr) + { return new PropertyInfo[0]; } - MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr) { + MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr) + { return new MemberInfo[0]; } - MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr) { + MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr) + { return new MemberInfo[0]; } object IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder binder, - object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) { - if (name.StartsWith("[DISPID=")) { + object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) + { + if (name.StartsWith("[DISPID=")) + { int endIndex = name.IndexOf(']'); int dispid = int.Parse(name.Substring(8, endIndex - 8), CultureInfo.InvariantCulture); object ambient = host.GetAmbientProperty(dispid); - if (ambient != null) return ambient; + if (ambient != null) + return ambient; } throw E_FAIL; } - Type IReflect.UnderlyingSystemType { - get { + Type IReflect.UnderlyingSystemType + { + get + { return null; } - } + } // IOleControlSite methods: - int UnsafeNativeMethods.IOleControlSite.OnControlInfoChanged() { + int UnsafeNativeMethods.IOleControlSite.OnControlInfoChanged() + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in OnControlInfoChanged"); return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleControlSite.LockInPlaceActive(int fLock) { + int UnsafeNativeMethods.IOleControlSite.LockInPlaceActive(int fLock) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in LockInPlaceActive"); return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleControlSite.GetExtendedControl(out object ppDisp) { + int UnsafeNativeMethods.IOleControlSite.GetExtendedControl(out object ppDisp) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in GetExtendedControl " + host.ToString()); ppDisp = host.GetParentContainer().GetProxyForControl(host); if (ppDisp == null) @@ -3615,40 +4238,50 @@ int UnsafeNativeMethods.IOleControlSite.GetExtendedControl(out object ppDisp) { return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleControlSite.TransformCoords(NativeMethods._POINTL pPtlHimetric, NativeMethods.tagPOINTF pPtfContainer, int dwFlags) { + int UnsafeNativeMethods.IOleControlSite.TransformCoords(NativeMethods._POINTL pPtlHimetric, NativeMethods.tagPOINTF pPtfContainer, int dwFlags) + { int hr = SetupLogPixels(false); if (NativeMethods.Failed(hr)) return hr; - if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_HIMETRICTOCONTAINER) != 0) { - if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_SIZE) != 0) { - pPtfContainer.x = (float) host.HM2Pix(pPtlHimetric.x, logPixelsX); - pPtfContainer.y = (float) host.HM2Pix(pPtlHimetric.y, logPixelsY); + if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_HIMETRICTOCONTAINER) != 0) + { + if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_SIZE) != 0) + { + pPtfContainer.x = (float)host.HM2Pix(pPtlHimetric.x, logPixelsX); + pPtfContainer.y = (float)host.HM2Pix(pPtlHimetric.y, logPixelsY); } - else if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_POSITION) != 0) { - pPtfContainer.x = (float) host.HM2Pix(pPtlHimetric.x, logPixelsX); - pPtfContainer.y = (float) host.HM2Pix(pPtlHimetric.y, logPixelsY); + else if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_POSITION) != 0) + { + pPtfContainer.x = (float)host.HM2Pix(pPtlHimetric.x, logPixelsX); + pPtfContainer.y = (float)host.HM2Pix(pPtlHimetric.y, logPixelsY); } - else { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose,"\t dwFlags not supported: " + dwFlags); + else + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "\t dwFlags not supported: " + dwFlags); return NativeMethods.E_INVALIDARG; } } - else if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_CONTAINERTOHIMETRIC) != 0) { - if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_SIZE) != 0) { + else if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_CONTAINERTOHIMETRIC) != 0) + { + if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_SIZE) != 0) + { pPtlHimetric.x = host.Pix2HM((int)pPtfContainer.x, logPixelsX); pPtlHimetric.y = host.Pix2HM((int)pPtfContainer.y, logPixelsY); } - else if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_POSITION) != 0) { + else if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_POSITION) != 0) + { pPtlHimetric.x = host.Pix2HM((int)pPtfContainer.x, logPixelsX); pPtlHimetric.y = host.Pix2HM((int)pPtfContainer.y, logPixelsY); } - else { + else + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "\t dwFlags not supported: " + dwFlags); return NativeMethods.E_INVALIDARG; } } - else { + else + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "\t dwFlags not supported: " + dwFlags); return NativeMethods.E_INVALIDARG; } @@ -3656,7 +4289,8 @@ int UnsafeNativeMethods.IOleControlSite.TransformCoords(NativeMethods._POINTL pP return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleControlSite.TranslateAccelerator(ref NativeMethods.MSG pMsg, int grfModifiers) { + int UnsafeNativeMethods.IOleControlSite.TranslateAccelerator(ref NativeMethods.MSG pMsg, int grfModifiers) + { Debug.Assert(!host.GetAxState(AxHost.siteProcessedInputKey), "Re-entering UnsafeNativeMethods.IOleControlSite.TranslateAccelerator!!!"); host.SetAxState(AxHost.siteProcessedInputKey, true); @@ -3665,23 +4299,28 @@ int UnsafeNativeMethods.IOleControlSite.TranslateAccelerator(ref NativeMethods.M msg.WParam = pMsg.wParam; msg.LParam = pMsg.lParam; msg.HWnd = pMsg.hwnd; - - try { + + try + { bool f = ((Control)host).PreProcessMessage(ref msg); return f ? NativeMethods.S_OK : NativeMethods.S_FALSE; } - finally { + finally + { host.SetAxState(AxHost.siteProcessedInputKey, false); } } - int UnsafeNativeMethods.IOleControlSite.OnFocus(int fGotFocus) { + int UnsafeNativeMethods.IOleControlSite.OnFocus(int fGotFocus) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in OnFocus " + ((fGotFocus == 0) ? "lost" : "gained")); return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleControlSite.ShowPropertyFrame() { - if (host.CanShowPropertyPages()) { + int UnsafeNativeMethods.IOleControlSite.ShowPropertyFrame() + { + if (host.CanShowPropertyPages()) + { host.ShowPropertyPages(); return NativeMethods.S_OK; } @@ -3689,30 +4328,36 @@ int UnsafeNativeMethods.IOleControlSite.ShowPropertyFrame() { } // IOleClientSite methods: - int UnsafeNativeMethods.IOleClientSite.SaveObject() { + int UnsafeNativeMethods.IOleClientSite.SaveObject() + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in SaveObject"); return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleClientSite.GetMoniker(int dwAssign, int dwWhichMoniker, out object moniker) { + int UnsafeNativeMethods.IOleClientSite.GetMoniker(int dwAssign, int dwWhichMoniker, out object moniker) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:GetMoniker"); moniker = null; return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleClientSite.GetContainer(out UnsafeNativeMethods.IOleContainer container) { + int UnsafeNativeMethods.IOleClientSite.GetContainer(out UnsafeNativeMethods.IOleContainer container) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getContainer"); container = host.GetParentContainer(); return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleClientSite.ShowObject() { + int UnsafeNativeMethods.IOleClientSite.ShowObject() + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in ShowObject"); - if (host.GetAxState(AxHost.fOwnWindow)) { + if (host.GetAxState(AxHost.fOwnWindow)) + { Debug.Fail("we can't be in showobject if we own our window..."); return NativeMethods.S_OK; } - if (host.GetAxState(AxHost.fFakingWindow)) { + if (host.GetAxState(AxHost.fFakingWindow)) + { // we really should not be here... // this means that the ctl inplace deactivated and didn't call on inplace activate before calling showobject // so we need to destroy our fake window first... @@ -3728,15 +4373,19 @@ int UnsafeNativeMethods.IOleClientSite.ShowObject() { return NativeMethods.S_OK; IntPtr hwnd; - if (NativeMethods.Succeeded(host.GetInPlaceObject().GetWindow(out hwnd))) { - if (host.GetHandleNoCreate() != hwnd) { + if (NativeMethods.Succeeded(host.GetInPlaceObject().GetWindow(out hwnd))) + { + if (host.GetHandleNoCreate() != hwnd) + { host.DetachWindow(); - if (hwnd != IntPtr.Zero) { + if (hwnd != IntPtr.Zero) + { host.AttachWindow(hwnd); } } } - else if (host.GetInPlaceObject() is UnsafeNativeMethods.IOleInPlaceObjectWindowless) { + else if (host.GetInPlaceObject() is UnsafeNativeMethods.IOleInPlaceObjectWindowless) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Windowless control."); throw new InvalidOperationException(SR.AXWindowlessControl); } @@ -3744,41 +4393,49 @@ int UnsafeNativeMethods.IOleClientSite.ShowObject() { return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleClientSite.OnShowWindow(int fShow) { + int UnsafeNativeMethods.IOleClientSite.OnShowWindow(int fShow) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in OnShowWindow"); return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleClientSite.RequestNewObjectLayout() { + int UnsafeNativeMethods.IOleClientSite.RequestNewObjectLayout() + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in RequestNewObjectLayout"); return NativeMethods.E_NOTIMPL; } // IOleInPlaceSite methods: - IntPtr UnsafeNativeMethods.IOleInPlaceSite.GetWindow() { - try { + IntPtr UnsafeNativeMethods.IOleInPlaceSite.GetWindow() + { + try + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in GetWindow"); Control parent = host.ParentInternal; return parent != null ? parent.Handle : IntPtr.Zero; } - catch (Exception t) { + catch (Exception t) + { Debug.Fail(t.ToString()); throw t; } } - int UnsafeNativeMethods.IOleInPlaceSite.ContextSensitiveHelp(int fEnterMode) { + int UnsafeNativeMethods.IOleInPlaceSite.ContextSensitiveHelp(int fEnterMode) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in ContextSensitiveHelp"); return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleInPlaceSite.CanInPlaceActivate() { + int UnsafeNativeMethods.IOleInPlaceSite.CanInPlaceActivate() + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in CanInPlaceActivate"); return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleInPlaceSite.OnInPlaceActivate() { + int UnsafeNativeMethods.IOleInPlaceSite.OnInPlaceActivate() + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in OnInPlaceActivate"); host.SetAxState(AxHost.ownDisposing, false); host.SetAxState(AxHost.rejectSelection, false); @@ -3786,7 +4443,8 @@ int UnsafeNativeMethods.IOleInPlaceSite.OnInPlaceActivate() { return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleInPlaceSite.OnUIActivate() { + int UnsafeNativeMethods.IOleInPlaceSite.OnUIActivate() + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in OnUIActivate for " + host.ToString()); host.SetOcState(OC_UIACTIVE); host.GetParentContainer().OnUIActivate(host); @@ -3794,12 +4452,14 @@ int UnsafeNativeMethods.IOleInPlaceSite.OnUIActivate() { } int UnsafeNativeMethods.IOleInPlaceSite.GetWindowContext(out UnsafeNativeMethods.IOleInPlaceFrame ppFrame, out UnsafeNativeMethods.IOleInPlaceUIWindow ppDoc, - NativeMethods.COMRECT lprcPosRect, NativeMethods.COMRECT lprcClipRect, NativeMethods.tagOIFI lpFrameInfo) { + NativeMethods.COMRECT lprcPosRect, NativeMethods.COMRECT lprcClipRect, NativeMethods.tagOIFI lpFrameInfo) + { ppDoc = null; ppFrame = host.GetParentContainer(); FillInRect(lprcPosRect, host.Bounds); host.GetClipRect(lprcClipRect); - if (lpFrameInfo != null) { + if (lpFrameInfo != null) + { lpFrameInfo.cb = Marshal.SizeOf(); lpFrameInfo.fMDIApp = false; lpFrameInfo.hAccel = IntPtr.Zero; @@ -3809,29 +4469,36 @@ int UnsafeNativeMethods.IOleInPlaceSite.GetWindowContext(out UnsafeNativeMethods return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleInPlaceSite.Scroll(NativeMethods.tagSIZE scrollExtant) { - try { + int UnsafeNativeMethods.IOleInPlaceSite.Scroll(NativeMethods.tagSIZE scrollExtant) + { + try + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in Scroll"); } - catch (Exception t) { + catch (Exception t) + { Debug.Fail(t.ToString()); throw t; } - return(NativeMethods.S_FALSE); + return (NativeMethods.S_FALSE); } - int UnsafeNativeMethods.IOleInPlaceSite.OnUIDeactivate(int fUndoable) { + int UnsafeNativeMethods.IOleInPlaceSite.OnUIDeactivate(int fUndoable) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in OnUIDeactivate for " + host.ToString()); host.GetParentContainer().OnUIDeactivate(host); - if (host.GetOcState() > OC_INPLACE) { + if (host.GetOcState() > OC_INPLACE) + { host.SetOcState(OC_INPLACE); } return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleInPlaceSite.OnInPlaceDeactivate() { + int UnsafeNativeMethods.IOleInPlaceSite.OnInPlaceDeactivate() + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in OnInPlaceDeactivate"); - if (host.GetOcState() == OC_UIACTIVE) { + if (host.GetOcState() == OC_UIACTIVE) + { ((UnsafeNativeMethods.IOleInPlaceSite)this).OnUIDeactivate(0); } @@ -3841,17 +4508,20 @@ int UnsafeNativeMethods.IOleInPlaceSite.OnInPlaceDeactivate() { return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleInPlaceSite.DiscardUndoState() { + int UnsafeNativeMethods.IOleInPlaceSite.DiscardUndoState() + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in DiscardUndoState"); return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleInPlaceSite.DeactivateAndUndo() { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in DeactivateAndUndo for "+host.ToString()); + int UnsafeNativeMethods.IOleInPlaceSite.DeactivateAndUndo() + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in DeactivateAndUndo for " + host.ToString()); return host.GetInPlaceObject().UIDeactivate(); } - int UnsafeNativeMethods.IOleInPlaceSite.OnPosRectChange(NativeMethods.COMRECT lprcPosRect) { + int UnsafeNativeMethods.IOleInPlaceSite.OnPosRectChange(NativeMethods.COMRECT lprcPosRect) + { // The MediaPlayer control has a AllowChangeDisplaySize property that users // can set to control size changes at runtime, but the control itself ignores that and sets the new size. // We prevent this by not allowing controls to call OnPosRectChange(), unless we instantiated the resize. @@ -3860,21 +4530,24 @@ int UnsafeNativeMethods.IOleInPlaceSite.OnPosRectChange(NativeMethods.COMRECT lp bool useRect = true; if (AxHost.windowsMediaPlayer_Clsid.Equals(host.clsid)) useRect = host.GetAxState(AxHost.handlePosRectChanged); - - if (useRect) { + + if (useRect) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in OnPosRectChange" + lprcPosRect.ToString()); host.GetInPlaceObject().SetObjectRects(lprcPosRect, host.GetClipRect(new NativeMethods.COMRECT())); host.MakeDirty(); } - else { + else + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Control directly called OnPosRectChange... ignoring the new size"); } return NativeMethods.S_OK; } // IPropertyNotifySink methods - - void UnsafeNativeMethods.IPropertyNotifySink.OnChanged(int dispid) { + + void UnsafeNativeMethods.IPropertyNotifySink.OnChanged(int dispid) + { // Some controls fire OnChanged() notifications when getting values of some properties. // To prevent this kind of recursion, we check to see if we are already inside a OnChanged() call. // @@ -3882,42 +4555,54 @@ void UnsafeNativeMethods.IPropertyNotifySink.OnChanged(int dispid) { return; host.NoComponentChangeEvents++; - try { + try + { AxPropertyDescriptor prop = null; Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in OnChanged"); - if (dispid != NativeMethods.ActiveX.DISPID_UNKNOWN) { + if (dispid != NativeMethods.ActiveX.DISPID_UNKNOWN) + { prop = host.GetPropertyDescriptorFromDispid(dispid); - if (prop != null) { + if (prop != null) + { prop.OnValueChanged(this.host); - if (!prop.SettingValue) { + if (!prop.SettingValue) + { prop.UpdateTypeConverterAndTypeEditor(true); - } + } } } - else { + else + { // update them all for DISPID_UNKNOWN. // PropertyDescriptorCollection props = ((ICustomTypeDescriptor)host).GetProperties(); - foreach(PropertyDescriptor p in props) { + foreach (PropertyDescriptor p in props) + { prop = p as AxPropertyDescriptor; - if (prop != null && !prop.SettingValue) { + if (prop != null && !prop.SettingValue) + { prop.UpdateTypeConverterAndTypeEditor(true); } } - } + } ISite site = host.Site; - if (site != null) { + if (site != null) + { IComponentChangeService changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); - if (changeService != null) { - try { + if (changeService != null) + { + try + { changeService.OnComponentChanging(host, prop); } - catch (CheckoutException coEx) { - if (coEx == CheckoutException.Canceled) { + catch (CheckoutException coEx) + { + if (coEx == CheckoutException.Canceled) + { return; } throw coEx; @@ -3929,33 +4614,40 @@ void UnsafeNativeMethods.IPropertyNotifySink.OnChanged(int dispid) { } } } - catch (Exception t) { + catch (Exception t) + { Debug.Fail(t.ToString()); throw t; } - finally { + finally + { host.NoComponentChangeEvents--; } } - int UnsafeNativeMethods.IPropertyNotifySink.OnRequestEdit(int dispid) { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in OnRequestEdit for "+host.ToString()); + int UnsafeNativeMethods.IPropertyNotifySink.OnRequestEdit(int dispid) + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in OnRequestEdit for " + host.ToString()); return NativeMethods.S_OK; } } private const int HMperInch = 2540; - private int Pix2HM(int pix, int logP) { - return(HMperInch * pix + ( logP >> 1)) / logP; + private int Pix2HM(int pix, int logP) + { + return (HMperInch * pix + (logP >> 1)) / logP; } - private int HM2Pix(int hm, int logP) { - return(logP * hm + HMperInch / 2) / HMperInch; + private int HM2Pix(int hm, int logP) + { + return (logP * hm + HMperInch / 2) / HMperInch; } - private bool QuickActivate() { - if (!(instance is UnsafeNativeMethods.IQuickActivate)) return false; - UnsafeNativeMethods.IQuickActivate iqa = (UnsafeNativeMethods.IQuickActivate) instance; + private bool QuickActivate() + { + if (!(instance is UnsafeNativeMethods.IQuickActivate)) + return false; + UnsafeNativeMethods.IQuickActivate iqa = (UnsafeNativeMethods.IQuickActivate)instance; UnsafeNativeMethods.tagQACONTAINER qaContainer = new UnsafeNativeMethods.tagQACONTAINER(); UnsafeNativeMethods.tagQACONTROL qaControl = new UnsafeNativeMethods.tagQACONTROL(); @@ -3975,20 +4667,24 @@ private bool QuickActivate() { Control p = ParentInternal; - if (p != null) { + if (p != null) + { qaContainer.colorFore = GetOleColorFromColor(p.ForeColor); qaContainer.colorBack = GetOleColorFromColor(p.BackColor); } - else { + else + { qaContainer.colorFore = GetOleColorFromColor(SystemColors.WindowText); qaContainer.colorBack = GetOleColorFromColor(SystemColors.Window); } qaContainer.dwAmbientFlags = NativeMethods.ActiveX.QACONTAINER_AUTOCLIP | NativeMethods.ActiveX.QACONTAINER_MESSAGEREFLECT | NativeMethods.ActiveX.QACONTAINER_SUPPORTSMNEMONICS; - if (IsUserMode()) { + if (IsUserMode()) + { qaContainer.dwAmbientFlags |= NativeMethods.ActiveX.QACONTAINER_USERMODE; } - else { + else + { // Can't set ui dead becuase MFC controls return NOWHERE on NCHITTEST which // messes up the designer... // But, without this the FarPoint SpreadSheet and the Office SpreadSheet @@ -3997,10 +4693,12 @@ private bool QuickActivate() { // qaContainer.dwAmbientFlags |= ActiveX.QACONTAINER_SHOWHATCHING; } - try { + try + { iqa.QuickActivate(qaContainer, qaControl); } - catch (Exception t) { + catch (Exception t) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Failed to QuickActivate: " + t.ToString()); DisposeAxControl(); return false; @@ -4010,24 +4708,30 @@ private bool QuickActivate() { return true; } - internal override void DisposeAxControls() { + internal override void DisposeAxControls() + { axState[rejectSelection] = true; base.DisposeAxControls(); TransitionDownTo(OC_PASSIVE); } - private bool GetControlEnabled() { - try { + private bool GetControlEnabled() + { + try + { return IsHandleCreated; } - catch (Exception t) { + catch (Exception t) + { Debug.Fail(t.ToString()); return true; } } - internal override bool CanSelectCore() { - if (!GetControlEnabled() || axState[rejectSelection]) return false; + internal override bool CanSelectCore() + { + if (!GetControlEnabled() || axState[rejectSelection]) + return false; return base.CanSelectCore(); } @@ -4037,9 +4741,11 @@ internal override bool CanSelectCore() { /// be released when the control is garbage collected. Inheriting classes should always /// call base.dispose. /// - protected override void Dispose(bool disposing) { - - if (disposing) { + protected override void Dispose(bool disposing) + { + + if (disposing) + { TransitionDownTo(OC_PASSIVE); if (newParent != null) { @@ -4054,22 +4760,27 @@ protected override void Dispose(bool disposing) { base.Dispose(disposing); } - private bool GetSiteOwnsDeactivation() { + private bool GetSiteOwnsDeactivation() + { return axState[ownDisposing]; } - private void DisposeAxControl() { - if (GetParentContainer() != null) { + private void DisposeAxControl() + { + if (GetParentContainer() != null) + { GetParentContainer().RemoveControl(this); } TransitionDownTo(OC_RUNNING); - if (GetOcState() == OC_RUNNING) { + if (GetOcState() == OC_RUNNING) + { GetOleObject().SetClientSite(null); SetOcState(OC_LOADED); } } - private void ReleaseAxControl() { + private void ReleaseAxControl() + { // This line is like a bit of magic... // sometimes, we crash with it on, // sometimes, with it off... @@ -4080,14 +4791,17 @@ private void ReleaseAxControl() { this.NoComponentChangeEvents++; ContainerControl f = ContainingControl; - if (f != null) { + if (f != null) + { f.VisibleChanged -= this.onContainerVisibleChanged; } - try { - if (instance != null) { + try + { + if (instance != null) + { Marshal.FinalReleaseComObject(instance); - instance = null; + instance = null; iOleInPlaceObject = null; iOleObject = null; iOleControl = null; @@ -4099,7 +4813,7 @@ private void ReleaseAxControl() { iPersistStreamInit = null; iPersistStorage = null; } - + axState[checkedIppb] = false; axState[checkedCP] = false; axState[disposed] = true; @@ -4110,33 +4824,39 @@ private void ReleaseAxControl() { SetOcState(OC_PASSIVE); } - finally { + finally + { this.NoComponentChangeEvents--; } } - private void ParseMiscBits(int bits) { + private void ParseMiscBits(int bits) + { axState[fOwnWindow] = ((bits & NativeMethods.ActiveX.OLEMISC_INVISIBLEATRUNTIME) != 0) && IsUserMode(); axState[fSimpleFrame] = ((bits & NativeMethods.ActiveX.OLEMISC_SIMPLEFRAME) != 0); } - private void SlowActivate() { + private void SlowActivate() + { bool setClientSite = false; - if ((miscStatusBits & NativeMethods.ActiveX.OLEMISC_SETCLIENTSITEFIRST) != 0) { + if ((miscStatusBits & NativeMethods.ActiveX.OLEMISC_SETCLIENTSITEFIRST) != 0) + { GetOleObject().SetClientSite(oleSite); setClientSite = true; } DepersistControl(); - if (!setClientSite) { + if (!setClientSite) + { GetOleObject().SetClientSite(oleSite); } } - private static NativeMethods.COMRECT FillInRect(NativeMethods.COMRECT dest, Rectangle source) { + private static NativeMethods.COMRECT FillInRect(NativeMethods.COMRECT dest, Rectangle source) + { dest.left = source.X; dest.top = source.Y; dest.right = source.Width + source.X; @@ -4144,13 +4864,17 @@ private static NativeMethods.COMRECT FillInRect(NativeMethods.COMRECT dest, Rect return dest; } - private AxContainer GetParentContainer() { - if (container == null) { + private AxContainer GetParentContainer() + { + if (container == null) + { container = AxContainer.FindContainerForControl(this); } - if (container == null) { + if (container == null) + { ContainerControl f = ContainingControl; - if (f == null) { + if (f == null) + { // ContainingCointrol can be null if the AxHost is still not parented to a containerControl // In everett we used to return a parking window. // now we just set the containingControl to a dummyValue. @@ -4162,8 +4886,9 @@ private AxContainer GetParentContainer() { } return axContainer; } - else { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "calling upon "+f.ToString()+" to create a container"); + else + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "calling upon " + f.ToString() + " to create a container"); container = f.CreateAxContainer(); container.AddControl(this); containingControl = f; @@ -4172,46 +4897,57 @@ private AxContainer GetParentContainer() { return container; } - private UnsafeNativeMethods.IOleControl GetOleControl() { - if (iOleControl == null) { + private UnsafeNativeMethods.IOleControl GetOleControl() + { + if (iOleControl == null) + { Debug.Assert(instance != null, "must have the ocx"); - iOleControl = (UnsafeNativeMethods.IOleControl) instance; + iOleControl = (UnsafeNativeMethods.IOleControl)instance; } return iOleControl; } - private UnsafeNativeMethods.IOleInPlaceActiveObject GetInPlaceActiveObject() { + private UnsafeNativeMethods.IOleInPlaceActiveObject GetInPlaceActiveObject() + { // if our AxContainer was set an external active object then use it. - if(iOleInPlaceActiveObjectExternal != null) { + if (iOleInPlaceActiveObjectExternal != null) + { return iOleInPlaceActiveObjectExternal; } // otherwise use our instance. - if (iOleInPlaceActiveObject == null) { + if (iOleInPlaceActiveObject == null) + { Debug.Assert(instance != null, "must have the ocx"); - try { + try + { iOleInPlaceActiveObject = (UnsafeNativeMethods.IOleInPlaceActiveObject)instance; } - catch (InvalidCastException e) { + catch (InvalidCastException e) + { Debug.Fail("Invalid cast in GetInPlaceActiveObject: " + e.ToString()); } } return iOleInPlaceActiveObject; } - private UnsafeNativeMethods.IOleObject GetOleObject() { - if (iOleObject == null) { + private UnsafeNativeMethods.IOleObject GetOleObject() + { + if (iOleObject == null) + { Debug.Assert(instance != null, "must have the ocx"); - iOleObject = (UnsafeNativeMethods.IOleObject) instance; + iOleObject = (UnsafeNativeMethods.IOleObject)instance; } return iOleObject; } - private UnsafeNativeMethods.IOleInPlaceObject GetInPlaceObject() { - if (iOleInPlaceObject == null) { + private UnsafeNativeMethods.IOleInPlaceObject GetInPlaceObject() + { + if (iOleInPlaceObject == null) + { Debug.Assert(instance != null, "must have the ocx"); - iOleInPlaceObject = (UnsafeNativeMethods.IOleInPlaceObject) instance; - + iOleInPlaceObject = (UnsafeNativeMethods.IOleInPlaceObject)instance; + #if DEBUG if (iOleInPlaceObject is UnsafeNativeMethods.IOleInPlaceObjectWindowless) Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, GetType().FullName + " Can also be a Windowless control."); @@ -4220,21 +4956,27 @@ private UnsafeNativeMethods.IOleInPlaceObject GetInPlaceObject() { return iOleInPlaceObject; } - private NativeMethods.ICategorizeProperties GetCategorizeProperties() { - if (iCategorizeProperties == null && !axState[checkedCP] && instance != null) { + private NativeMethods.ICategorizeProperties GetCategorizeProperties() + { + if (iCategorizeProperties == null && !axState[checkedCP] && instance != null) + { axState[checkedCP] = true; - if (instance is NativeMethods.ICategorizeProperties) { - iCategorizeProperties = (NativeMethods.ICategorizeProperties) instance; + if (instance is NativeMethods.ICategorizeProperties) + { + iCategorizeProperties = (NativeMethods.ICategorizeProperties)instance; } } return iCategorizeProperties; } - private NativeMethods.IPerPropertyBrowsing GetPerPropertyBrowsing() { - if (iPerPropertyBrowsing == null && !axState[checkedIppb] && instance != null) { + private NativeMethods.IPerPropertyBrowsing GetPerPropertyBrowsing() + { + if (iPerPropertyBrowsing == null && !axState[checkedIppb] && instance != null) + { axState[checkedIppb] = true; - if (instance is NativeMethods.IPerPropertyBrowsing) { - iPerPropertyBrowsing = (NativeMethods.IPerPropertyBrowsing) instance; + if (instance is NativeMethods.IPerPropertyBrowsing) + { + iPerPropertyBrowsing = (NativeMethods.IPerPropertyBrowsing)instance; } } return iPerPropertyBrowsing; @@ -4264,9 +5006,11 @@ private static IntPtr CopyPalette(IntPtr hPal) { } #endif - private static object GetPICTDESCFromPicture(Image image) { + private static object GetPICTDESCFromPicture(Image image) + { Bitmap bmp = image as Bitmap; - if (bmp != null) { + if (bmp != null) + { return new NativeMethods.PICTDESCbmp(bmp); } @@ -4282,8 +5026,10 @@ private static object GetPICTDESCFromPicture(Image image) { /// Maps from a System.Drawing.Image to an OLE IPicture /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected static object GetIPictureFromPicture(Image image) { - if (image == null) return null; + protected static object GetIPictureFromPicture(Image image) + { + if (image == null) + return null; object pictdesc = GetPICTDESCFromPicture(image); return UnsafeNativeMethods.OleCreateIPictureIndirect(pictdesc, ref ipicture_Guid, true); } @@ -4292,8 +5038,10 @@ protected static object GetIPictureFromPicture(Image image) { /// Maps from a System.Drawing.Cursor to an OLE IPicture /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected static object GetIPictureFromCursor(Cursor cursor) { - if (cursor == null) return null; + protected static object GetIPictureFromCursor(Cursor cursor) + { + if (cursor == null) + return null; NativeMethods.PICTDESCicon pictdesc = new NativeMethods.PICTDESCicon(Icon.FromHandle(cursor.Handle)); return UnsafeNativeMethods.OleCreateIPictureIndirect(pictdesc, ref ipicture_Guid, true); } @@ -4302,8 +5050,10 @@ protected static object GetIPictureFromCursor(Cursor cursor) { /// Maps from a System.Drawing.Image to an OLE IPictureDisp /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected static object GetIPictureDispFromPicture(Image image) { - if (image == null) return null; + protected static object GetIPictureDispFromPicture(Image image) + { + if (image == null) + return null; object pictdesc = GetPICTDESCFromPicture(image); return UnsafeNativeMethods.OleCreateIPictureDispIndirect(pictdesc, ref ipictureDisp_Guid, true); } @@ -4312,16 +5062,21 @@ protected static object GetIPictureDispFromPicture(Image image) { /// Maps from an OLE IPicture to a System.Drawing.Image /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected static Image GetPictureFromIPicture(object picture) { - if (picture == null) return null; + protected static Image GetPictureFromIPicture(object picture) + { + if (picture == null) + return null; IntPtr hPal = IntPtr.Zero; UnsafeNativeMethods.IPicture pict = (UnsafeNativeMethods.IPicture)picture; int type = pict.GetPictureType(); - if (type == NativeMethods.Ole.PICTYPE_BITMAP) { - try { + if (type == NativeMethods.Ole.PICTYPE_BITMAP) + { + try + { hPal = pict.GetHPal(); } - catch (COMException) { + catch (COMException) + { } } return GetPictureFromParams(pict, pict.GetHandle(), type, hPal, pict.GetWidth(), pict.GetHeight()); @@ -4331,32 +5086,39 @@ protected static Image GetPictureFromIPicture(object picture) { /// Maps from an OLE IPictureDisp to a System.Drawing.Image /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected static Image GetPictureFromIPictureDisp(object picture) { - if (picture == null) return null; + protected static Image GetPictureFromIPictureDisp(object picture) + { + if (picture == null) + return null; IntPtr hPal = IntPtr.Zero; UnsafeNativeMethods.IPictureDisp pict = (UnsafeNativeMethods.IPictureDisp)picture; int type = pict.PictureType; - if (type == NativeMethods.Ole.PICTYPE_BITMAP) { - try { + if (type == NativeMethods.Ole.PICTYPE_BITMAP) + { + try + { hPal = pict.HPal; } - catch (COMException) { + catch (COMException) + { } } return GetPictureFromParams(pict, pict.Handle, type, hPal, pict.Width, pict.Height); } - private static Image GetPictureFromParams(object pict, IntPtr handle, int type, IntPtr paletteHandle, int width, int height) { - switch (type) { + private static Image GetPictureFromParams(object pict, IntPtr handle, int type, IntPtr paletteHandle, int width, int height) + { + switch (type) + { case NativeMethods.Ole.PICTYPE_ICON: - return(Image)(Icon.FromHandle(handle)).Clone(); + return (Image)(Icon.FromHandle(handle)).Clone(); case NativeMethods.Ole.PICTYPE_METAFILE: WmfPlaceableFileHeader header = new WmfPlaceableFileHeader(); header.BboxRight = (short)width; header.BboxBottom = (short)height; - return(Image)(new Metafile(handle, header, false)).Clone(); + return (Image)(new Metafile(handle, header, false)).Clone(); case NativeMethods.Ole.PICTYPE_ENHMETAFILE: - return(Image)(new Metafile(handle, false)).Clone(); + return (Image)(new Metafile(handle, false)).Clone(); case NativeMethods.Ole.PICTYPE_BITMAP: return Image.FromHbitmap(handle, paletteHandle); case NativeMethods.Ole.PICTYPE_NONE: @@ -4365,28 +5127,32 @@ private static Image GetPictureFromParams(object pict, IntPtr handle, int type, case NativeMethods.Ole.PICTYPE_UNINITIALIZED: return null; default: - Debug.Fail("Invalid image type "+ type.ToString(CultureInfo.InvariantCulture)); + Debug.Fail("Invalid image type " + type.ToString(CultureInfo.InvariantCulture)); throw new ArgumentException(SR.AXUnknownImage, "type"); } } - private static NativeMethods.FONTDESC GetFONTDESCFromFont(Font font) { + private static NativeMethods.FONTDESC GetFONTDESCFromFont(Font font) + { NativeMethods.FONTDESC fdesc = null; - if (fontTable == null) { + if (fontTable == null) + { fontTable = new Hashtable(); } - else { + else + { fdesc = (NativeMethods.FONTDESC)fontTable[font]; } - if (fdesc == null) { + if (fdesc == null) + { fdesc = new NativeMethods.FONTDESC(); fdesc.lpstrName = font.Name; fdesc.cySize = (long)(font.SizeInPoints * 10000); NativeMethods.LOGFONT logfont = new NativeMethods.LOGFONT(); font.ToLogFont(logfont); - fdesc.sWeight = (short) logfont.lfWeight; + fdesc.sWeight = (short)logfont.lfWeight; fdesc.sCharset = logfont.lfCharSet; fdesc.fItalic = font.Italic; fdesc.fUnderline = font.Underline; @@ -4403,7 +5169,8 @@ private static NativeMethods.FONTDESC GetFONTDESCFromFont(Font font) { /// [CLSCompliantAttribute(false)] [EditorBrowsable(EditorBrowsableState.Advanced)] - protected static Color GetColorFromOleColor(uint color) { + protected static Color GetColorFromOleColor(uint color) + { return ColorTranslator.FromOle((int)color); } @@ -4412,7 +5179,8 @@ protected static Color GetColorFromOleColor(uint color) { /// [CLSCompliantAttribute(false)] [EditorBrowsable(EditorBrowsableState.Advanced)] - protected static uint GetOleColorFromColor(Color color) { + protected static uint GetOleColorFromColor(Color color) + { return (uint)ColorTranslator.ToOle(color); } @@ -4420,16 +5188,20 @@ protected static uint GetOleColorFromColor(Color color) { /// Maps from a System.Drawing.Font object to an OLE IFont /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected static object GetIFontFromFont(Font font) { - if (font == null) return null; + protected static object GetIFontFromFont(Font font) + { + if (font == null) + return null; if (font.Unit != GraphicsUnit.Point) throw new ArgumentException(SR.AXFontUnitNotPoint, "font"); - try { + try + { return (UnsafeNativeMethods.IFont)UnsafeNativeMethods.OleCreateIFontIndirect(GetFONTDESCFromFont(font), ref ifont_Guid); } - catch { + catch + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Failed to create IFrom from font: " + font.ToString()); return null; } @@ -4440,11 +5212,14 @@ protected static object GetIFontFromFont(Font font) { /// Maps from an OLE IFont to a System.Drawing.Font object /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected static Font GetFontFromIFont(object font) { - if (font == null) return null; + protected static Font GetFontFromIFont(object font) + { + if (font == null) + return null; UnsafeNativeMethods.IFont oleFont = (UnsafeNativeMethods.IFont)font; - try { + try + { Font f = Font.FromHfont(oleFont.GetHFont()); if (f.Unit != GraphicsUnit.Point) @@ -4452,7 +5227,8 @@ protected static Font GetFontFromIFont(object font) { return f; } - catch (Exception e) { + catch (Exception e) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Could not create font." + e.Message); return DefaultFont; } @@ -4463,9 +5239,11 @@ protected static Font GetFontFromIFont(object font) { /// Maps from a System.Drawing.Font object to an OLE IFontDisp /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected static object GetIFontDispFromFont(Font font) { - if (font == null) return null; - + protected static object GetIFontDispFromFont(Font font) + { + if (font == null) + return null; + if (font.Unit != GraphicsUnit.Point) throw new ArgumentException(SR.AXFontUnitNotPoint, "font"); @@ -4477,7 +5255,8 @@ protected static object GetIFontDispFromFont(Font font) { /// Maps from an IFontDisp to a System.Drawing.Font object /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected static Font GetFontFromIFontDisp(object font) { + protected static Font GetFontFromIFontDisp(object font) + { if (font == null) { return null; @@ -4491,28 +5270,30 @@ protected static Font GetFontFromIFontDisp(object font) { SafeNativeMethods.IFontDisp oleFont = (SafeNativeMethods.IFontDisp)font; FontStyle style = FontStyle.Regular; - + Font f = null; - try { + try + { if (oleFont.Bold) style |= FontStyle.Bold; - + if (oleFont.Italic) style |= FontStyle.Italic; - + if (oleFont.Underline) style |= FontStyle.Underline; - + if (oleFont.Strikethrough) style |= FontStyle.Strikeout; - - if ((int) oleFont.Weight >= 700) // bold + + if ((int)oleFont.Weight >= 700) // bold style |= FontStyle.Bold; - f = new Font(oleFont.Name, (float)oleFont.Size/(float)10000, style, GraphicsUnit.Point, (byte)oleFont.Charset); + f = new Font(oleFont.Name, (float)oleFont.Size / (float)10000, style, GraphicsUnit.Point, (byte)oleFont.Charset); return f; } - catch(Exception e) { + catch (Exception e) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Could not create font from: " + oleFont.Name + ". " + e.Message); return DefaultFont; } @@ -4523,7 +5304,8 @@ protected static Font GetFontFromIFontDisp(object font) { /// Maps from a DateTime object to an OLE DATE (expressed as a double) /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected static double GetOADateFromTime(DateTime time) { + protected static double GetOADateFromTime(DateTime time) + { return time.ToOADate(); } @@ -4531,18 +5313,21 @@ protected static double GetOADateFromTime(DateTime time) { /// Maps from an OLE DATE (expressed as a double) to a DateTime object /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected static DateTime GetTimeFromOADate(double date) { + protected static DateTime GetTimeFromOADate(double date) + { return DateTime.FromOADate(date); } /// /// - private int Convert2int(object o, bool xDirection) { + private int Convert2int(object o, bool xDirection) + { o = ((Array)o).GetValue(0); // yacky yacky yacky... // so, usercontrols & other visual basic related controls give us coords as floats in twips // but mfc controls give us integers as pixels... - if (o.GetType() == typeof(float)) { + if (o.GetType() == typeof(float)) + { return Twip2Pixel(Convert.ToDouble(o, CultureInfo.InvariantCulture), xDirection); } return Convert.ToInt32(o, CultureInfo.InvariantCulture); @@ -4550,7 +5335,8 @@ private int Convert2int(object o, bool xDirection) { /// /// - private short Convert2short(object o) { + private short Convert2short(object o) + { o = ((Array)o).GetValue(0); return Convert.ToInt16(o, CultureInfo.InvariantCulture); } @@ -4558,73 +5344,84 @@ private short Convert2short(object o) { /// /// [EditorBrowsable(EditorBrowsableState.Advanced), SuppressMessage("Microsoft.Design", "CA1025:ReplaceRepetitiveArgumentsWithParamsArray")] - protected void RaiseOnMouseMove(object o1, object o2, object o3, object o4) { + protected void RaiseOnMouseMove(object o1, object o2, object o3, object o4) + { RaiseOnMouseMove(Convert2short(o1), Convert2short(o2), Convert2int(o3, true), Convert2int(o4, false)); } /// /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected void RaiseOnMouseMove(short button, short shift, float x, float y) { - RaiseOnMouseMove(button, shift, Twip2Pixel((int) x, true), Twip2Pixel((int) y, false)); + protected void RaiseOnMouseMove(short button, short shift, float x, float y) + { + RaiseOnMouseMove(button, shift, Twip2Pixel((int)x, true), Twip2Pixel((int)y, false)); } /// /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected void RaiseOnMouseMove(short button, short shift, int x, int y) { - base.OnMouseMove(new MouseEventArgs( (MouseButtons)(((int)button) << 20), 1, x, y, 0)); + protected void RaiseOnMouseMove(short button, short shift, int x, int y) + { + base.OnMouseMove(new MouseEventArgs((MouseButtons)(((int)button) << 20), 1, x, y, 0)); } /// /// [EditorBrowsable(EditorBrowsableState.Advanced), SuppressMessage("Microsoft.Design", "CA1025:ReplaceRepetitiveArgumentsWithParamsArray")] - protected void RaiseOnMouseUp(object o1, object o2, object o3, object o4) { + protected void RaiseOnMouseUp(object o1, object o2, object o3, object o4) + { RaiseOnMouseUp(Convert2short(o1), Convert2short(o2), Convert2int(o3, true), Convert2int(o4, false)); } /// /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected void RaiseOnMouseUp(short button, short shift, float x, float y) { - RaiseOnMouseUp(button, shift, Twip2Pixel((int) x, true), Twip2Pixel((int) y, false)); + protected void RaiseOnMouseUp(short button, short shift, float x, float y) + { + RaiseOnMouseUp(button, shift, Twip2Pixel((int)x, true), Twip2Pixel((int)y, false)); } /// /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected void RaiseOnMouseUp(short button, short shift, int x, int y) { + protected void RaiseOnMouseUp(short button, short shift, int x, int y) + { base.OnMouseUp(new MouseEventArgs((MouseButtons)(((int)button) << 20), 1, x, y, 0)); } /// /// - [EditorBrowsable(EditorBrowsableState.Advanced), SuppressMessage("Microsoft.Design", "CA1025:ReplaceRepetitiveArgumentsWithParamsArray")] - protected void RaiseOnMouseDown(object o1, object o2, object o3, object o4) { + [EditorBrowsable(EditorBrowsableState.Advanced), SuppressMessage("Microsoft.Design", "CA1025:ReplaceRepetitiveArgumentsWithParamsArray")] + protected void RaiseOnMouseDown(object o1, object o2, object o3, object o4) + { RaiseOnMouseDown(Convert2short(o1), Convert2short(o2), Convert2int(o3, true), Convert2int(o4, false)); } /// /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected void RaiseOnMouseDown(short button, short shift, float x, float y) { - RaiseOnMouseDown(button, shift, Twip2Pixel((int) x,true), Twip2Pixel((int) y, false)); + protected void RaiseOnMouseDown(short button, short shift, float x, float y) + { + RaiseOnMouseDown(button, shift, Twip2Pixel((int)x, true), Twip2Pixel((int)y, false)); } /// /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected void RaiseOnMouseDown(short button, short shift, int x, int y) { + protected void RaiseOnMouseDown(short button, short shift, int x, int y) + { base.OnMouseDown(new MouseEventArgs((MouseButtons)(((int)button) << 20), 1, x, y, 0)); } /// /// - private class VBFormat : UnsafeNativeMethods.IVBFormat { + private class VBFormat : UnsafeNativeMethods.IVBFormat + { // IVBFormat methods: // - int UnsafeNativeMethods.IVBFormat.Format(ref object var, IntPtr pszFormat, IntPtr lpBuffer, short cpBuffer, int lcid, short firstD, short firstW, short[] result) { + int UnsafeNativeMethods.IVBFormat.Format(ref object var, IntPtr pszFormat, IntPtr lpBuffer, short cpBuffer, int lcid, short firstD, short firstW, short[] result) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in Format"); if (result == null) return NativeMethods.E_INVALIDARG; @@ -4635,20 +5432,24 @@ int UnsafeNativeMethods.IVBFormat.Format(ref object var, IntPtr pszFormat, IntPt IntPtr pbstr = IntPtr.Zero; int hr = UnsafeNativeMethods.VarFormat(ref var, new HandleRef(null, pszFormat), firstD, firstW, 32 /* VAR_FORMAT_NOSUBSTITUTE */, ref pbstr); - - try { + + try + { int i = 0; - if (pbstr != IntPtr.Zero) { + if (pbstr != IntPtr.Zero) + { short ch = 0; - cpBuffer --; - for (;i < cpBuffer && (ch = Marshal.ReadInt16(pbstr, i * 2)) != 0; i++) { + cpBuffer--; + for (; i < cpBuffer && (ch = Marshal.ReadInt16(pbstr, i * 2)) != 0; i++) + { Marshal.WriteInt16(lpBuffer, i * 2, ch); } } - Marshal.WriteInt16(lpBuffer, i * 2, (short) 0); - result[0] = (short) i; + Marshal.WriteInt16(lpBuffer, i * 2, (short)0); + result[0] = (short)i; } - finally { + finally + { SafeNativeMethods.SysFreeString(new HandleRef(null, pbstr)); } @@ -4658,73 +5459,88 @@ int UnsafeNativeMethods.IVBFormat.Format(ref object var, IntPtr pszFormat, IntPt /// /// - internal class EnumUnknown : UnsafeNativeMethods.IEnumUnknown { + internal class EnumUnknown : UnsafeNativeMethods.IEnumUnknown + { private object[] arr; private int loc; private int size; - internal EnumUnknown(object[] arr) { + internal EnumUnknown(object[] arr) + { //if (AxHTraceSwitch.TraceVerbose) Debug.WriteObject(arr); this.arr = arr; loc = 0; size = (arr == null) ? 0 : arr.Length; } - private EnumUnknown(object[] arr, int loc) : this(arr) { + private EnumUnknown(object[] arr, int loc) : this(arr) + { this.loc = loc; } - unsafe int UnsafeNativeMethods.IEnumUnknown.Next(int celt, IntPtr rgelt, IntPtr pceltFetched) { + unsafe int UnsafeNativeMethods.IEnumUnknown.Next(int celt, IntPtr rgelt, IntPtr pceltFetched) + { if (pceltFetched != IntPtr.Zero) Marshal.WriteInt32(pceltFetched, 0, 0); - if (celt < 0) { + if (celt < 0) + { return NativeMethods.E_INVALIDARG; } - + int fetched = 0; - if (loc >= size) { + if (loc >= size) + { fetched = 0; } - else { - for (; loc < size && fetched < celt; ++loc) { - if (arr[loc] != null) { + else + { + for (; loc < size && fetched < celt; ++loc) + { + if (arr[loc] != null) + { Marshal.WriteIntPtr(rgelt, Marshal.GetIUnknownForObject(arr[loc])); rgelt = (IntPtr)((long)rgelt + (long)sizeof(IntPtr)); ++fetched; } } } - + if (pceltFetched != IntPtr.Zero) Marshal.WriteInt32(pceltFetched, 0, fetched); - if (fetched != celt) { - return(NativeMethods.S_FALSE); + if (fetched != celt) + { + return (NativeMethods.S_FALSE); } return NativeMethods.S_OK; } - int UnsafeNativeMethods.IEnumUnknown.Skip(int celt) { + int UnsafeNativeMethods.IEnumUnknown.Skip(int celt) + { loc += celt; - if (loc >= size) { - return(NativeMethods.S_FALSE); + if (loc >= size) + { + return (NativeMethods.S_FALSE); } return NativeMethods.S_OK; } - void UnsafeNativeMethods.IEnumUnknown.Reset() { + void UnsafeNativeMethods.IEnumUnknown.Reset() + { loc = 0; } - void UnsafeNativeMethods.IEnumUnknown.Clone(out UnsafeNativeMethods.IEnumUnknown ppenum) { + void UnsafeNativeMethods.IEnumUnknown.Clone(out UnsafeNativeMethods.IEnumUnknown ppenum) + { ppenum = new EnumUnknown(arr, loc); } } /// /// - internal class AxContainer : UnsafeNativeMethods.IOleContainer, UnsafeNativeMethods.IOleInPlaceFrame, IReflect { + internal class AxContainer : UnsafeNativeMethods.IOleContainer, UnsafeNativeMethods.IOleInPlaceFrame, IReflect + { internal ContainerControl parent; private IContainer assocContainer; // associated IContainer... // the assocContainer may be null, in which case all this container does is @@ -4745,165 +5561,207 @@ internal class AxContainer : UnsafeNativeMethods.IOleContainer, UnsafeNativeMeth private const int GC_PREVSIBLING = 0x40; private const int GC_NEXTSIBLING = 0x80; - internal AxContainer(ContainerControl parent) { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in constructor. Parent created : "+parent.Created.ToString()); + internal AxContainer(ContainerControl parent) + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in constructor. Parent created : " + parent.Created.ToString()); this.parent = parent; - if (parent.Created) FormCreated(); + if (parent.Created) + FormCreated(); } // IReflect methods: - MethodInfo IReflect.GetMethod(string name,BindingFlags bindingAttr,Binder binder, Type[] types,ParameterModifier[] modifiers) { + MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) + { return null; } - MethodInfo IReflect.GetMethod(string name,BindingFlags bindingAttr) { + MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr) + { return null; } - MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr) { + MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr) + { return new MethodInfo[0]; } - FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr) { + FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr) + { return null; } - FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr) { + FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr) + { return new FieldInfo[0]; } - PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr) { + PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr) + { return null; } - PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { + PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) + { return null; } - PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr) { + PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr) + { return new PropertyInfo[0]; } - MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr) { + MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr) + { return new MemberInfo[0]; } - MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr) { + MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr) + { return new MemberInfo[0]; } object IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder binder, - object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) { - - foreach(DictionaryEntry e in containerCache) { + object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) + { + + foreach (DictionaryEntry e in containerCache) + { string ctlName = GetNameForControl((Control)e.Key); - if (ctlName.Equals(name)) { + if (ctlName.Equals(name)) + { return GetProxyForControl((Control)e.Value); } } - + throw E_FAIL; } - Type IReflect.UnderlyingSystemType { - get { + Type IReflect.UnderlyingSystemType + { + get + { return null; } - } + } - internal UnsafeNativeMethods.IExtender GetProxyForControl(Control ctl) { + internal UnsafeNativeMethods.IExtender GetProxyForControl(Control ctl) + { UnsafeNativeMethods.IExtender rval = null; - if (proxyCache == null) { + if (proxyCache == null) + { proxyCache = new Hashtable(); } - else { - rval = (UnsafeNativeMethods.IExtender) proxyCache[ctl]; + else + { + rval = (UnsafeNativeMethods.IExtender)proxyCache[ctl]; } - if (rval == null) { - if (ctl != parent && !GetControlBelongs(ctl)) { + if (rval == null) + { + if (ctl != parent && !GetControlBelongs(ctl)) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "!parent || !belongs NYI"); AxContainer c = FindContainerForControl(ctl); - if (c != null) { + if (c != null) + { rval = new ExtenderProxy(ctl, c); } - else { + else + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "unable to find proxy, returning null"); return null; } } - else { + else + { rval = new ExtenderProxy(ctl, this); } proxyCache.Add(ctl, rval); } - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "found proxy "+rval.ToString()); + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "found proxy " + rval.ToString()); return rval; } - internal string GetNameForControl(Control ctl) { + internal string GetNameForControl(Control ctl) + { string name = (ctl.Site != null) ? ctl.Site.Name : ctl.Name; return (name == null) ? "" : name; } - internal object GetProxyForContainer() { + internal object GetProxyForContainer() + { return this; } - internal void AddControl(Control ctl) { + internal void AddControl(Control ctl) + { // - lock(this) { + lock (this) + { if (containerCache.Contains(ctl)) throw new ArgumentException(string.Format(SR.AXDuplicateControl, GetNameForControl(ctl)), "ctl"); containerCache.Add(ctl, ctl); - - if (assocContainer == null) { + + if (assocContainer == null) + { ISite site = ctl.Site; - if (site != null) { + if (site != null) + { assocContainer = site.Container; IComponentChangeService ccs = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); - if (ccs != null) { + if (ccs != null) + { ccs.ComponentRemoved += new ComponentEventHandler(this.OnComponentRemoved); } } } - else { + else + { #if DEBUG - ISite site = ctl.Site; - if (site != null && assocContainer != site.Container) { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "mismatch between assoc container & added control"); - } + ISite site = ctl.Site; + if (site != null && assocContainer != site.Container) + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "mismatch between assoc container & added control"); + } #endif } } } - internal void RemoveControl(Control ctl) { + internal void RemoveControl(Control ctl) + { // - lock(this) { - if (containerCache.Contains(ctl)) { + lock (this) + { + if (containerCache.Contains(ctl)) + { containerCache.Remove(ctl); } } } - private void LockComponents() { + private void LockComponents() + { lockCount++; } - private void UnlockComponents() { + private void UnlockComponents() + { lockCount--; - if (lockCount == 0) { + if (lockCount == 0) + { components = null; } } - internal UnsafeNativeMethods.IEnumUnknown EnumControls(Control ctl, int dwOleContF, int dwWhich) { + internal UnsafeNativeMethods.IEnumUnknown EnumControls(Control ctl, int dwOleContF, int dwWhich) + { GetComponents(); LockComponents(); - try { + try + { ArrayList l = null; bool selected = (dwWhich & NativeMethods.ActiveX.GC_WCH_FSELECTED) != 0; bool reverse = (dwWhich & NativeMethods.ActiveX.GC_WCH_FREVERSEDIR) != 0; @@ -4912,20 +5770,24 @@ internal UnsafeNativeMethods.IEnumUnknown EnumControls(Control ctl, int dwOleCon bool onlyPrev = (dwWhich & NativeMethods.ActiveX.GC_WCH_FONLYPREV) != 0; dwWhich = dwWhich & ~(NativeMethods.ActiveX.GC_WCH_FSELECTED | NativeMethods.ActiveX.GC_WCH_FREVERSEDIR | NativeMethods.ActiveX.GC_WCH_FONLYNEXT | NativeMethods.ActiveX.GC_WCH_FONLYPREV); - if (onlyNext && onlyPrev) { + if (onlyNext && onlyPrev) + { Debug.Fail("onlyNext && onlyPrev are both set!"); throw E_INVALIDARG; } - if (dwWhich == NativeMethods.ActiveX.GC_WCH_CONTAINER || dwWhich == NativeMethods.ActiveX.GC_WCH_CONTAINED) { - if (onlyNext || onlyPrev) { + if (dwWhich == NativeMethods.ActiveX.GC_WCH_CONTAINER || dwWhich == NativeMethods.ActiveX.GC_WCH_CONTAINED) + { + if (onlyNext || onlyPrev) + { Debug.Fail("GC_WCH_FONLYNEXT or FONLYPREV used with CONTANER or CONATINED"); throw E_INVALIDARG; } } int first = 0; int last = -1; // meaning all - Control[] ctls = null; - switch (dwWhich) { + Control[] ctls = null; + switch (dwWhich) + { default: Debug.Fail("Bad GC_WCH"); throw E_INVALIDARG; @@ -4935,16 +5797,20 @@ internal UnsafeNativeMethods.IEnumUnknown EnumControls(Control ctl, int dwOleCon break; case NativeMethods.ActiveX.GC_WCH_SIBLING: Control p = ctl.ParentInternal; - if (p != null) { + if (p != null) + { ctls = p.GetChildControlsInTabOrder(false); - if (onlyPrev) { + if (onlyPrev) + { last = ctl.TabIndex; } - else if (onlyNext) { + else if (onlyNext) + { first = ctl.TabIndex + 1; } } - else { + else + { ctls = new Control[0]; } ctl = null; @@ -4952,13 +5818,16 @@ internal UnsafeNativeMethods.IEnumUnknown EnumControls(Control ctl, int dwOleCon case NativeMethods.ActiveX.GC_WCH_CONTAINER: l = new ArrayList(); MaybeAdd(l, ctl, selected, dwOleContF, false); - while (ctl != null) { + while (ctl != null) + { AxContainer cont = FindContainerForControl(ctl); - if (cont != null) { + if (cont != null) + { MaybeAdd(l, cont.parent, selected, dwOleContF, true); ctl = cont.parent; } - else { + else + { break; } } @@ -4970,18 +5839,24 @@ internal UnsafeNativeMethods.IEnumUnknown EnumControls(Control ctl, int dwOleCon ctl = parent; break; } - if (l == null) { + if (l == null) + { l = new ArrayList(); - if (last == -1 && ctls != null) last = ctls.Length; - if (ctl != null) MaybeAdd(l, ctl, selected, dwOleContF, false); - for (int i = first; i < last; i++) { + if (last == -1 && ctls != null) + last = ctls.Length; + if (ctl != null) + MaybeAdd(l, ctl, selected, dwOleContF, false); + for (int i = first; i < last; i++) + { MaybeAdd(l, ctls[i], selected, dwOleContF, false); } } object[] rval = new object[l.Count]; l.CopyTo(rval, 0); - if (reverse) { - for (int i = 0, j = rval.Length - 1; i < j; i++, j--) { + if (reverse) + { + for (int i = 0, j = rval.Length - 1; i < j; i++, j--) + { object temp = rval[i]; rval[i] = rval[j]; rval[j] = temp; @@ -4989,34 +5864,47 @@ internal UnsafeNativeMethods.IEnumUnknown EnumControls(Control ctl, int dwOleCon } return new EnumUnknown(rval); } - finally { + finally + { UnlockComponents(); } } - private void MaybeAdd(ArrayList l, Control ctl, bool selected, int dwOleContF, bool ignoreBelong) { - if (!ignoreBelong && ctl != parent && !GetControlBelongs(ctl)) return; - if (selected) { + private void MaybeAdd(ArrayList l, Control ctl, bool selected, int dwOleContF, bool ignoreBelong) + { + if (!ignoreBelong && ctl != parent && !GetControlBelongs(ctl)) + return; + if (selected) + { ISelectionService iss = GetSelectionService(ctl); - if (iss == null || !iss.GetComponentSelected(this)) return; + if (iss == null || !iss.GetComponentSelected(this)) + return; } AxHost hostctl = ctl as AxHost; - if (hostctl != null && (dwOleContF & NativeMethods.ActiveX.OLECONTF_EMBEDDINGS) != 0) { + if (hostctl != null && (dwOleContF & NativeMethods.ActiveX.OLECONTF_EMBEDDINGS) != 0) + { l.Add(hostctl.GetOcx()); } - else if ((dwOleContF & NativeMethods.ActiveX.OLECONTF_OTHERS) != 0) { + else if ((dwOleContF & NativeMethods.ActiveX.OLECONTF_OTHERS) != 0) + { object item = GetProxyForControl(ctl); - if (item != null) l.Add(item); + if (item != null) + l.Add(item); } } - private void FillComponentsTable(IContainer container) { - if (container != null) { + private void FillComponentsTable(IContainer container) + { + if (container != null) + { ComponentCollection comps = container.Components; - if (comps != null) { + if (comps != null) + { components = new Hashtable(); - foreach (IComponent comp in comps) { - if (comp is Control && comp != parent && comp.Site != null) { + foreach (IComponent comp in comps) + { + if (comp is Control && comp != parent && comp.Site != null) + { components.Add(comp, comp); } } @@ -5030,13 +5918,17 @@ private void FillComponentsTable(IContainer container) { bool checkHashTable = true; Control[] ctls = new Control[containerCache.Values.Count]; containerCache.Values.CopyTo(ctls, 0); - if (ctls != null) { - if (ctls.Length > 0 && components == null) { + if (ctls != null) + { + if (ctls.Length > 0 && components == null) + { components = new Hashtable(); checkHashTable = false; } - for (int i = 0; i < ctls.Length; i ++) { - if (checkHashTable && !components.Contains(ctls[i])) { + for (int i = 0; i < ctls.Length; i++) + { + if (checkHashTable && !components.Contains(ctls[i])) + { components.Add(ctls[i], ctls[i]); } } @@ -5045,63 +5937,79 @@ private void FillComponentsTable(IContainer container) { GetAllChildren(this.parent); } - private void GetAllChildren(Control ctl) { + private void GetAllChildren(Control ctl) + { if (ctl == null) return; - if (components == null) { + if (components == null) + { components = new Hashtable(); } if (ctl != this.parent && !components.Contains(ctl)) components.Add(ctl, ctl); - foreach(Control c in ctl.Controls) { + foreach (Control c in ctl.Controls) + { GetAllChildren(c); } } - private Hashtable GetComponents() { + private Hashtable GetComponents() + { return GetComponents(GetParentsContainer()); } - private Hashtable GetComponents(IContainer cont) { - if (lockCount == 0) { + private Hashtable GetComponents(IContainer cont) + { + if (lockCount == 0) + { FillComponentsTable(cont); } return components; } - private bool GetControlBelongs(Control ctl) { + private bool GetControlBelongs(Control ctl) + { Hashtable comps = GetComponents(); return comps[ctl] != null; } - private IContainer GetParentIsDesigned() { + private IContainer GetParentIsDesigned() + { ISite site = parent.Site; - if (site != null && site.DesignMode) return site.Container; + if (site != null && site.DesignMode) + return site.Container; return null; } - private IContainer GetParentsContainer() { + private IContainer GetParentsContainer() + { IContainer rval = GetParentIsDesigned(); Debug.Assert(rval == null || assocContainer == null || (rval == assocContainer), "mismatch between getIPD & aContainer"); return rval == null ? assocContainer : rval; } - private bool RegisterControl(AxHost ctl) { + private bool RegisterControl(AxHost ctl) + { ISite site = ctl.Site; - if (site != null) { + if (site != null) + { IContainer cont = site.Container; - if (cont != null) { - if (assocContainer != null) { + if (cont != null) + { + if (assocContainer != null) + { return cont == assocContainer; } - else { + else + { assocContainer = cont; IComponentChangeService ccs = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); - if (ccs != null) { + if (ccs != null) + { ccs.ComponentRemoved += new ComponentEventHandler(this.OnComponentRemoved); } return true; @@ -5111,22 +6019,28 @@ private bool RegisterControl(AxHost ctl) { return false; } - private void OnComponentRemoved(object sender, ComponentEventArgs e) { + private void OnComponentRemoved(object sender, ComponentEventArgs e) + { Control c = e.Component as Control; - if (sender == assocContainer && c != null) { + if (sender == assocContainer && c != null) + { RemoveControl(c); } } - internal static AxContainer FindContainerForControl(Control ctl) { + internal static AxContainer FindContainerForControl(Control ctl) + { AxHost axctl = ctl as AxHost; if (axctl != null) { - if (axctl.container != null) return axctl.container; + if (axctl.container != null) + return axctl.container; ContainerControl f = axctl.ContainingControl; - if (f != null) { + if (f != null) + { AxContainer container = f.CreateAxContainer(); - if (container.RegisterControl(axctl)) { + if (container.RegisterControl(axctl)) + { container.AddControl(axctl); return container; } @@ -5203,20 +6117,25 @@ private void OnNewActiveControlInternal(AxHost value) { } #endif - internal void OnInPlaceDeactivate(AxHost site) { - if (siteActive == site) { + internal void OnInPlaceDeactivate(AxHost site) + { + if (siteActive == site) + { siteActive = null; - if (site.GetSiteOwnsDeactivation()) { + if (site.GetSiteOwnsDeactivation()) + { parent.ActiveControl = null; } - else { + else + { // we need to tell the form to switch activation to the next thingie... Debug.Fail("what pathological control is calling inplacedeactivate by itself?"); } } } - internal void OnUIDeactivate(AxHost site) { + internal void OnUIDeactivate(AxHost site) + { #if DEBUG if (siteUIActive != null) Debug.Assert(siteUIActive == site, "deactivating when not active..."); @@ -5226,59 +6145,73 @@ internal void OnUIDeactivate(AxHost site) { site.RemoveSelectionHandler(); site.SetSelectionStyle(1); site.editMode = EDITM_NONE; - if (site.GetSiteOwnsDeactivation()) { + if (site.GetSiteOwnsDeactivation()) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, " our site owns deactivation "); ContainerControl f = site.ContainingControl; Debug.Assert(f != null, "a control has to be on a ContainerControl..."); - if (f != null) { + if (f != null) + { // f.setActiveControl(null); } } } - internal void OnUIActivate(AxHost site) { + internal void OnUIActivate(AxHost site) + { // The ShDocVw control repeatedly calls OnUIActivate() with the same // site. This causes the assert below to fire. // if (siteUIActive == site) return; - if (siteUIActive != null && siteUIActive != site) { + if (siteUIActive != null && siteUIActive != site) + { AxHost tempSite = siteUIActive; bool ownDisposing = tempSite.GetAxState(AxHost.ownDisposing); - try { + try + { tempSite.SetAxState(AxHost.ownDisposing, true); tempSite.GetInPlaceObject().UIDeactivate(); } - finally { + finally + { tempSite.SetAxState(AxHost.ownDisposing, ownDisposing); } } site.AddSelectionHandler(); Debug.Assert(siteUIActive == null, "Object did not call OnUIDeactivate"); - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "active Object is now "+site.ToString()); + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "active Object is now " + site.ToString()); siteUIActive = site; ContainerControl f = site.ContainingControl; Debug.Assert(f != null, "a control has to be on a ContainerControl..."); - if (f != null) { + if (f != null) + { f.ActiveControl = site; } } - private void ListAxControls(ArrayList list, bool fuseOcx) { + private void ListAxControls(ArrayList list, bool fuseOcx) + { Hashtable components = GetComponents(); - if (components == null) return; + if (components == null) + return; Control[] ctls = new Control[components.Keys.Count]; components.Keys.CopyTo(ctls, 0); - if (ctls != null) { - for (int i = 0; i < ctls.Length; i++) { + if (ctls != null) + { + for (int i = 0; i < ctls.Length; i++) + { Control ctl = ctls[i]; AxHost hostctl = ctl as AxHost; - if (hostctl != null) { - if (fuseOcx) { + if (hostctl != null) + { + if (fuseOcx) + { list.Add(hostctl.GetOcx()); } - else { + else + { list.Add(ctl); } } @@ -5286,29 +6219,37 @@ private void ListAxControls(ArrayList list, bool fuseOcx) { } } - internal void ControlCreated(AxHost invoker) { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in controlCreated for "+invoker.ToString()+" fAC: "+formAlreadyCreated.ToString()); - if (formAlreadyCreated) { - if (invoker.IsUserMode() && invoker.AwaitingDefreezing()) { + internal void ControlCreated(AxHost invoker) + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in controlCreated for " + invoker.ToString() + " fAC: " + formAlreadyCreated.ToString()); + if (formAlreadyCreated) + { + if (invoker.IsUserMode() && invoker.AwaitingDefreezing()) + { invoker.Freeze(false); } } - else { + else + { // the form will be created in the future parent.CreateAxContainer(); } } - internal void FormCreated() { - if (formAlreadyCreated) return; + internal void FormCreated() + { + if (formAlreadyCreated) + return; formAlreadyCreated = true; ArrayList l = new ArrayList(); ListAxControls(l, false); AxHost[] axControls = new AxHost[l.Count]; l.CopyTo(axControls, 0); - for (int i = 0; i < axControls.Length; i++) { + for (int i = 0; i < axControls.Length; i++) + { AxHost control = axControls[i]; - if (control.GetOcState() >= OC_RUNNING && control.IsUserMode() && control.AwaitingDefreezing()) { + if (control.GetOcState() >= OC_RUNNING && control.IsUserMode() && control.AwaitingDefreezing()) + { control.Freeze(false); } } @@ -5317,21 +6258,25 @@ internal void FormCreated() { // IOleContainer methods: - int UnsafeNativeMethods.IOleContainer.ParseDisplayName(object pbc, string pszDisplayName, int[] pchEaten, object[] ppmkOut) { + int UnsafeNativeMethods.IOleContainer.ParseDisplayName(object pbc, string pszDisplayName, int[] pchEaten, object[] ppmkOut) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in ParseDisplayName"); if (ppmkOut != null) ppmkOut[0] = null; - return NativeMethods.E_NOTIMPL; + return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleContainer.EnumObjects(int grfFlags, out UnsafeNativeMethods.IEnumUnknown ppenum) { + int UnsafeNativeMethods.IOleContainer.EnumObjects(int grfFlags, out UnsafeNativeMethods.IEnumUnknown ppenum) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in EnumObjects"); ppenum = null; - if ((grfFlags & 1) != 0) { // 1 == OLECONTF_EMBEDDINGS + if ((grfFlags & 1) != 0) + { // 1 == OLECONTF_EMBEDDINGS Debug.Assert(parent != null, "gotta have it..."); ArrayList list = new ArrayList(); ListAxControls(list, true); - if (list.Count > 0) { + if (list.Count > 0) + { object[] temp = new object[list.Count]; list.CopyTo(temp, 0); ppenum = new EnumUnknown(temp); @@ -5342,87 +6287,109 @@ int UnsafeNativeMethods.IOleContainer.EnumObjects(int grfFlags, out UnsafeNative return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleContainer.LockContainer(bool fLock) { + int UnsafeNativeMethods.IOleContainer.LockContainer(bool fLock) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in LockContainer"); return NativeMethods.E_NOTIMPL; } // IOleInPlaceFrame methods: - IntPtr UnsafeNativeMethods.IOleInPlaceFrame.GetWindow() { + IntPtr UnsafeNativeMethods.IOleInPlaceFrame.GetWindow() + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in GetWindow"); return parent.Handle; } - int UnsafeNativeMethods.IOleInPlaceFrame.ContextSensitiveHelp(int fEnterMode) { + int UnsafeNativeMethods.IOleInPlaceFrame.ContextSensitiveHelp(int fEnterMode) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in ContextSensitiveHelp"); return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleInPlaceFrame.GetBorder(NativeMethods.COMRECT lprectBorder) { + int UnsafeNativeMethods.IOleInPlaceFrame.GetBorder(NativeMethods.COMRECT lprectBorder) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in GetBorder"); return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleInPlaceFrame.RequestBorderSpace(NativeMethods.COMRECT pborderwidths) { + int UnsafeNativeMethods.IOleInPlaceFrame.RequestBorderSpace(NativeMethods.COMRECT pborderwidths) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in RequestBorderSpace"); return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleInPlaceFrame.SetBorderSpace(NativeMethods.COMRECT pborderwidths) { + int UnsafeNativeMethods.IOleInPlaceFrame.SetBorderSpace(NativeMethods.COMRECT pborderwidths) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in SetBorderSpace"); return NativeMethods.E_NOTIMPL; } - internal void OnExitEditMode(AxHost ctl) { + internal void OnExitEditMode(AxHost ctl) + { Debug.Assert(ctlInEditMode == null || ctlInEditMode == ctl, "who is exiting edit mode?"); - if (ctlInEditMode == null || ctlInEditMode != ctl) return; + if (ctlInEditMode == null || ctlInEditMode != ctl) + return; ctlInEditMode = null; } - int UnsafeNativeMethods.IOleInPlaceFrame.SetActiveObject(UnsafeNativeMethods.IOleInPlaceActiveObject pActiveObject, string pszObjName) { + int UnsafeNativeMethods.IOleInPlaceFrame.SetActiveObject(UnsafeNativeMethods.IOleInPlaceActiveObject pActiveObject, string pszObjName) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in SetActiveObject " + ((pszObjName == null) ? "" : pszObjName)); - if (siteUIActive != null) { - if (siteUIActive.iOleInPlaceActiveObjectExternal != pActiveObject) { - if (siteUIActive.iOleInPlaceActiveObjectExternal != null) { + if (siteUIActive != null) + { + if (siteUIActive.iOleInPlaceActiveObjectExternal != pActiveObject) + { + if (siteUIActive.iOleInPlaceActiveObjectExternal != null) + { Marshal.ReleaseComObject(siteUIActive.iOleInPlaceActiveObjectExternal); } siteUIActive.iOleInPlaceActiveObjectExternal = pActiveObject; } } - if (pActiveObject == null) { - if (ctlInEditMode != null) { + if (pActiveObject == null) + { + if (ctlInEditMode != null) + { ctlInEditMode.editMode = EDITM_NONE; ctlInEditMode = null; } return NativeMethods.S_OK; } AxHost ctl = null; - if (pActiveObject is UnsafeNativeMethods.IOleObject) { - UnsafeNativeMethods.IOleObject oleObject = (UnsafeNativeMethods.IOleObject) pActiveObject; + if (pActiveObject is UnsafeNativeMethods.IOleObject) + { + UnsafeNativeMethods.IOleObject oleObject = (UnsafeNativeMethods.IOleObject)pActiveObject; UnsafeNativeMethods.IOleClientSite clientSite = null; - try { + try + { clientSite = oleObject.GetClientSite(); - if (clientSite is OleInterfaces) { + if (clientSite is OleInterfaces) + { ctl = ((OleInterfaces)(clientSite)).GetAxHost(); } } - catch (COMException t) { + catch (COMException t) + { Debug.Fail(t.ToString()); } - if (ctlInEditMode != null) { + if (ctlInEditMode != null) + { Debug.Fail("control " + ctlInEditMode.ToString() + " did not reset its edit mode to null"); ctlInEditMode.SetSelectionStyle(1); ctlInEditMode.editMode = EDITM_NONE; } - - if (ctl == null) { + + if (ctl == null) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "control w/o a valid site called setactiveobject"); ctlInEditMode = null; } - else { + else + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "resolved to " + ctl.ToString()); - if (!ctl.IsUserMode()) { + if (!ctl.IsUserMode()) + { ctlInEditMode = ctl; ctl.editMode = EDITM_OBJECT; ctl.AddSelectionHandler(); @@ -5433,31 +6400,37 @@ int UnsafeNativeMethods.IOleInPlaceFrame.SetActiveObject(UnsafeNativeMethods.IOl return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleInPlaceFrame.InsertMenus(IntPtr hmenuShared, NativeMethods.tagOleMenuGroupWidths lpMenuWidths) { + int UnsafeNativeMethods.IOleInPlaceFrame.InsertMenus(IntPtr hmenuShared, NativeMethods.tagOleMenuGroupWidths lpMenuWidths) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in InsertMenus"); return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleInPlaceFrame.SetMenu(IntPtr hmenuShared, IntPtr holemenu, IntPtr hwndActiveObject) { + int UnsafeNativeMethods.IOleInPlaceFrame.SetMenu(IntPtr hmenuShared, IntPtr holemenu, IntPtr hwndActiveObject) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in SetMenu"); return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleInPlaceFrame.RemoveMenus(IntPtr hmenuShared) { + int UnsafeNativeMethods.IOleInPlaceFrame.RemoveMenus(IntPtr hmenuShared) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in RemoveMenus"); return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleInPlaceFrame.SetStatusText(string pszStatusText) { + int UnsafeNativeMethods.IOleInPlaceFrame.SetStatusText(string pszStatusText) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in SetStatusText"); return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleInPlaceFrame.EnableModeless(bool fEnable) { + int UnsafeNativeMethods.IOleInPlaceFrame.EnableModeless(bool fEnable) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in EnableModeless"); return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleInPlaceFrame.TranslateAccelerator(ref NativeMethods.MSG lpmsg, short wID) { + int UnsafeNativeMethods.IOleInPlaceFrame.TranslateAccelerator(ref NativeMethods.MSG lpmsg, short wID) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in IOleInPlaceFrame.TranslateAccelerator"); return NativeMethods.S_FALSE; } @@ -5466,301 +6439,372 @@ int UnsafeNativeMethods.IOleInPlaceFrame.TranslateAccelerator(ref NativeMethods. /// /// - private class ExtenderProxy : UnsafeNativeMethods.IExtender, UnsafeNativeMethods.IVBGetControl, UnsafeNativeMethods.IGetVBAObject, UnsafeNativeMethods.IGetOleObject, IReflect { + private class ExtenderProxy : UnsafeNativeMethods.IExtender, UnsafeNativeMethods.IVBGetControl, UnsafeNativeMethods.IGetVBAObject, UnsafeNativeMethods.IGetOleObject, IReflect + { private WeakReference pRef; private WeakReference pContainer; - internal ExtenderProxy(Control principal, AxContainer container) { + internal ExtenderProxy(Control principal, AxContainer container) + { pRef = new WeakReference(principal); pContainer = new WeakReference(container); } - private Control GetP() { - return(Control) pRef.Target; + private Control GetP() + { + return (Control)pRef.Target; } - private AxContainer GetC() { - return(AxContainer) pContainer.Target; + private AxContainer GetC() + { + return (AxContainer)pContainer.Target; } - int UnsafeNativeMethods.IVBGetControl.EnumControls(int dwOleContF, int dwWhich, out UnsafeNativeMethods.IEnumUnknown ppenum) { + int UnsafeNativeMethods.IVBGetControl.EnumControls(int dwOleContF, int dwWhich, out UnsafeNativeMethods.IEnumUnknown ppenum) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in EnumControls for proxy"); ppenum = GetC().EnumControls(GetP(), dwOleContF, dwWhich); return NativeMethods.S_OK; } - object UnsafeNativeMethods.IGetOleObject.GetOleObject(ref Guid riid) { + object UnsafeNativeMethods.IGetOleObject.GetOleObject(ref Guid riid) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in GetOleObject for proxy"); if (!riid.Equals(ioleobject_Guid)) throw E_INVALIDARG; Control ctl = GetP(); - if (ctl != null && ctl is AxHost) { + if (ctl != null && ctl is AxHost) + { return ((AxHost)ctl).GetOcx(); } throw E_FAIL; } - int UnsafeNativeMethods.IGetVBAObject.GetObject(ref Guid riid, UnsafeNativeMethods.IVBFormat[] rval, int dwReserved) { + int UnsafeNativeMethods.IGetVBAObject.GetObject(ref Guid riid, UnsafeNativeMethods.IVBFormat[] rval, int dwReserved) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in GetObject for proxy"); if (rval == null || riid.Equals(Guid.Empty)) return NativeMethods.E_INVALIDARG; - if (riid.Equals(ivbformat_Guid)) { + if (riid.Equals(ivbformat_Guid)) + { rval[0] = new VBFormat(); return NativeMethods.S_OK; } - else { + else + { rval[0] = null; return NativeMethods.E_NOINTERFACE; } } - public int Align { - get { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getAlign for proxy for "+ GetP().ToString()); + public int Align + { + get + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getAlign for proxy for " + GetP().ToString()); int rval = (int)((Control)GetP()).Dock; - if (rval < NativeMethods.ActiveX.ALIGN_MIN || rval > NativeMethods.ActiveX.ALIGN_MAX) { + if (rval < NativeMethods.ActiveX.ALIGN_MIN || rval > NativeMethods.ActiveX.ALIGN_MAX) + { rval = NativeMethods.ActiveX.ALIGN_NO_CHANGE; } return rval; } - set { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setAlign for proxy for "+ GetP().ToString()+" "+ + set + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setAlign for proxy for " + GetP().ToString() + " " + value.ToString(CultureInfo.InvariantCulture)); GetP().Dock = (DockStyle)value; } } - public uint BackColor { - get { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getBackColor for proxy for "+ GetP().ToString()); + public uint BackColor + { + get + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getBackColor for proxy for " + GetP().ToString()); return AxHost.GetOleColorFromColor(((Control)GetP()).BackColor); } - set { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setBackColor for proxy for "+ GetP().ToString()+" "+ + set + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setBackColor for proxy for " + GetP().ToString() + " " + value.ToString(CultureInfo.InvariantCulture)); GetP().BackColor = AxHost.GetColorFromOleColor(value); } } - public bool Enabled { - get { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getEnabled for proxy for "+ GetP().ToString()); + public bool Enabled + { + get + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getEnabled for proxy for " + GetP().ToString()); return GetP().Enabled; } - set { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setEnabled for proxy for "+ GetP().ToString()+" "+value.ToString()); + set + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setEnabled for proxy for " + GetP().ToString() + " " + value.ToString()); GetP().Enabled = value; } } - public uint ForeColor { - get { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getForeColor for proxy for "+ GetP().ToString()); + public uint ForeColor + { + get + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getForeColor for proxy for " + GetP().ToString()); return AxHost.GetOleColorFromColor(((Control)GetP()).ForeColor); } - set { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setForeColor for proxy for "+ GetP().ToString()+" "+ + set + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setForeColor for proxy for " + GetP().ToString() + " " + value.ToString(CultureInfo.InvariantCulture)); GetP().ForeColor = AxHost.GetColorFromOleColor(value); } } - public int Height { - get { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getHeight for proxy for "+ GetP().ToString()); + public int Height + { + get + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getHeight for proxy for " + GetP().ToString()); return Pixel2Twip(GetP().Height, false); } - set { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setHeight for proxy for "+ GetP().ToString()+" "+ - Twip2Pixel(value,false).ToString(CultureInfo.InvariantCulture)); + set + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setHeight for proxy for " + GetP().ToString() + " " + + Twip2Pixel(value, false).ToString(CultureInfo.InvariantCulture)); GetP().Height = Twip2Pixel(value, false); } } - public int Left { - get { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getLeft for proxy for "+ GetP().ToString()); + public int Left + { + get + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getLeft for proxy for " + GetP().ToString()); return Pixel2Twip(GetP().Left, true); } - set { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setLeft for proxy for "+ GetP().ToString()+" "+ + set + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setLeft for proxy for " + GetP().ToString() + " " + Twip2Pixel(value, true).ToString(CultureInfo.InvariantCulture)); GetP().Left = Twip2Pixel(value, true); } } - public object Parent { - get { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getParent for proxy for "+ GetP().ToString()); + public object Parent + { + get + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getParent for proxy for " + GetP().ToString()); return GetC().GetProxyForControl(GetC().parent); } } - public short TabIndex { - get { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getTabIndex for proxy for "+ GetP().ToString()); + public short TabIndex + { + get + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getTabIndex for proxy for " + GetP().ToString()); return (short)GetP().TabIndex; } - set { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setTabIndex for proxy for "+ GetP().ToString()+" "+ + set + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setTabIndex for proxy for " + GetP().ToString() + " " + value.ToString(CultureInfo.InvariantCulture)); GetP().TabIndex = (int)value; } } - public bool TabStop { - get { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getTabStop for proxy for "+ GetP().ToString()); + public bool TabStop + { + get + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getTabStop for proxy for " + GetP().ToString()); return GetP().TabStop; } - set { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setTabStop for proxy for "+ GetP().ToString()+" "+value.ToString()); + set + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setTabStop for proxy for " + GetP().ToString() + " " + value.ToString()); GetP().TabStop = value; } } - public int Top { - get { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getTop for proxy for "+ GetP().ToString()); + public int Top + { + get + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getTop for proxy for " + GetP().ToString()); return Pixel2Twip(GetP().Top, false); } - set { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setTop for proxy for "+ GetP().ToString()+" "+ + set + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setTop for proxy for " + GetP().ToString() + " " + Twip2Pixel(value, false).ToString(CultureInfo.InvariantCulture)); GetP().Top = Twip2Pixel(value, false); } } - public bool Visible { - get { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getVisible for proxy for "+ GetP().ToString()); + public bool Visible + { + get + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getVisible for proxy for " + GetP().ToString()); return GetP().Visible; } - set { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setVisible for proxy for "+ GetP().ToString()+" "+value.ToString()); + set + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setVisible for proxy for " + GetP().ToString() + " " + value.ToString()); GetP().Visible = value; } } - public int Width { - get { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getWidth for proxy for "+ GetP().ToString()); - return Pixel2Twip(GetP().Width,true); + public int Width + { + get + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getWidth for proxy for " + GetP().ToString()); + return Pixel2Twip(GetP().Width, true); } - set { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setWidth for proxy for "+ GetP().ToString()+" "+ + set + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setWidth for proxy for " + GetP().ToString() + " " + Twip2Pixel(value, true).ToString(CultureInfo.InvariantCulture)); GetP().Width = Twip2Pixel(value, true); } } - public string Name { - get { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getName for proxy for "+ GetP().ToString()); + public string Name + { + get + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getName for proxy for " + GetP().ToString()); return GetC().GetNameForControl(GetP()); } } - public IntPtr Hwnd { - get { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getHwnd for proxy for "+ GetP().ToString()); + public IntPtr Hwnd + { + get + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getHwnd for proxy for " + GetP().ToString()); return GetP().Handle; } } - public object Container { - get { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getContainer for proxy for "+ GetP().ToString()); + public object Container + { + get + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getContainer for proxy for " + GetP().ToString()); return GetC().GetProxyForContainer(); } } - public string Text { - get { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getText for proxy for "+ GetP().ToString()); + public string Text + { + get + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in getText for proxy for " + GetP().ToString()); return GetP().Text; } - set { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setText for proxy for "+ GetP().ToString()); + set + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in setText for proxy for " + GetP().ToString()); GetP().Text = value; } } - public void Move(object left, object top, object width, object height) { + public void Move(object left, object top, object width, object height) + { } // IReflect methods: - MethodInfo IReflect.GetMethod(string name,BindingFlags bindingAttr,Binder binder, Type[] types,ParameterModifier[] modifiers) { + MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) + { return null; } - MethodInfo IReflect.GetMethod(string name,BindingFlags bindingAttr) { + MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr) + { return null; } - MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr) { - return new MethodInfo[] {this.GetType().GetMethod("Move")}; + MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr) + { + return new MethodInfo[] { this.GetType().GetMethod("Move") }; } - FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr) { + FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr) + { return null; } - FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr) { + FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr) + { return new FieldInfo[0]; } - PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr) { + PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr) + { PropertyInfo prop = GetP().GetType().GetProperty(name, bindingAttr); - if (prop == null) { + if (prop == null) + { prop = this.GetType().GetProperty(name, bindingAttr); } return prop; } - PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder,Type returnType, Type[] types, ParameterModifier[] modifiers) { + PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) + { PropertyInfo prop = GetP().GetType().GetProperty(name, bindingAttr, binder, returnType, types, modifiers); - if (prop == null) { + if (prop == null) + { prop = this.GetType().GetProperty(name, bindingAttr, binder, returnType, types, modifiers); } return prop; } - PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr) { + PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr) + { PropertyInfo[] extenderProps = this.GetType().GetProperties(bindingAttr); PropertyInfo[] ctlProps = GetP().GetType().GetProperties(bindingAttr); - if (extenderProps == null) { + if (extenderProps == null) + { return ctlProps; } - else if (ctlProps == null) { + else if (ctlProps == null) + { return extenderProps; } - else { + else + { int iProp = 0; PropertyInfo[] props = new PropertyInfo[extenderProps.Length + ctlProps.Length]; - - foreach(PropertyInfo prop in extenderProps) { + + foreach (PropertyInfo prop in extenderProps) + { props[iProp++] = prop; } - foreach(PropertyInfo prop in ctlProps) { + foreach (PropertyInfo prop in ctlProps) + { props[iProp++] = prop; } @@ -5768,27 +6812,33 @@ PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr) { } } - MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr) { + MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr) + { MemberInfo[] memb = GetP().GetType().GetMember(name, bindingAttr); - if (memb == null) { + if (memb == null) + { memb = this.GetType().GetMember(name, bindingAttr); } return memb; } - MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr) { + MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr) + { MemberInfo[] extenderMembs = this.GetType().GetMembers(bindingAttr); MemberInfo[] ctlMembs = GetP().GetType().GetMembers(bindingAttr); - if (extenderMembs == null) { + if (extenderMembs == null) + { return ctlMembs; } - else if (ctlMembs == null) { + else if (ctlMembs == null) + { return extenderMembs; } - else { + else + { MemberInfo[] membs = new MemberInfo[extenderMembs.Length + ctlMembs.Length]; - + Array.Copy(extenderMembs, 0, membs, 0, extenderMembs.Length); Array.Copy(ctlMembs, 0, membs, extenderMembs.Length, ctlMembs.Length); @@ -5797,21 +6847,26 @@ MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr) { } object IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder binder, - object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) { - try { + object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) + { + try + { return this.GetType().InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters); } - catch(MissingMethodException) { + catch (MissingMethodException) + { return this.GetP().GetType().InvokeMember(name, invokeAttr, binder, GetP(), args, modifiers, culture, namedParameters); } } - Type IReflect.UnderlyingSystemType { - get { + Type IReflect.UnderlyingSystemType + { + get + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "In UnderlyingSystemType"); return null; } - } + } } } @@ -5820,15 +6875,18 @@ Type IReflect.UnderlyingSystemType { /// State from one data type to another. Access this /// class through the TypeDescriptor. /// - public class StateConverter : TypeConverter { + public class StateConverter : TypeConverter + { /// /// Gets a value indicating whether this converter can /// convert an object in the given source type to the native type of the converter /// using the context. /// - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { - if (sourceType == typeof(byte[])) { + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + { + if (sourceType == typeof(byte[])) + { return true; } @@ -5839,8 +6897,10 @@ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceT /// Gets a value indicating whether this converter can /// convert an object to the given destination type using the context. /// - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { - if (destinationType == typeof(byte[])) { + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) + { + if (destinationType == typeof(byte[])) + { return true; } @@ -5850,8 +6910,10 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati /// /// Converts the given object to the converter's native type. /// - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - if (value is byte[]) { + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + { + if (value is byte[]) + { MemoryStream ms = new MemoryStream((byte[])value); return new State(ms); } @@ -5866,20 +6928,24 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) { + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == null) + { throw new ArgumentNullException(nameof(destinationType)); } - if (destinationType == typeof(byte[])) { - if (value != null) { + if (destinationType == typeof(byte[])) + { + if (value != null) + { MemoryStream ms = new MemoryStream(); State state = (State)value; state.Save(ms); ms.Close(); return ms.ToArray(); } - else + else return new byte[0]; } @@ -5896,8 +6962,9 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul TypeConverterAttribute(typeof(TypeConverter)), Serializable ] - [SuppressMessage("Microsoft.Usage", "CA2240:ImplementISerializableCorrectly")] - public class State : ISerializable { + [SuppressMessage("Microsoft.Usage", "CA2240:ImplementISerializableCorrectly")] + public class State : ISerializable + { private int VERSION = 1; private int length; private byte[] buffer; @@ -5908,9 +6975,10 @@ public class State : ISerializable { private bool manualUpdate = false; private string licenseKey = null; private PropertyBagStream propBag; - + // create on save from ipersist stream - internal State(MemoryStream ms, int storageType, AxHost ctl, PropertyBagStream propBag) { + internal State(MemoryStream ms, int storageType, AxHost ctl, PropertyBagStream propBag) + { type = storageType; this.propBag = propBag; // dangerous? @@ -5920,25 +6988,29 @@ internal State(MemoryStream ms, int storageType, AxHost ctl, PropertyBagStream p this.licenseKey = ctl.GetLicenseKey(); } - internal State(PropertyBagStream propBag) { + internal State(PropertyBagStream propBag) + { this.propBag = propBag; } - internal State(MemoryStream ms) { + internal State(MemoryStream ms) + { this.ms = ms; this.length = (int)ms.Length; InitializeFromStream(ms); } // create on init new w/ storage... - internal State(AxHost ctl) { + internal State(AxHost ctl) + { CreateStorage(); manualUpdate = ctl.GetAxState(AxHost.manualUpdate); licenseKey = ctl.GetLicenseKey(); type = STG_STORAGE; } - public State(Stream ms, int storageType, bool manualUpdate, string licKey) { + public State(Stream ms, int storageType, bool manualUpdate, string licKey) + { type = storageType; // dangerous? length = (int)ms.Length; @@ -5951,143 +7023,181 @@ public State(Stream ms, int storageType, bool manualUpdate, string licKey) { /** * Constructor used in deserialization */ - protected State(SerializationInfo info, StreamingContext context) { + protected State(SerializationInfo info, StreamingContext context) + { SerializationInfoEnumerator sie = info.GetEnumerator(); - if (sie == null) { + if (sie == null) + { return; } - for (; sie.MoveNext();) { - if (string.Compare(sie.Name, "Data", true, CultureInfo.InvariantCulture) == 0) { - try { + for (; sie.MoveNext();) + { + if (string.Compare(sie.Name, "Data", true, CultureInfo.InvariantCulture) == 0) + { + try + { byte[] dat = (byte[])sie.Value; - if (dat != null) { + if (dat != null) + { InitializeFromStream(new MemoryStream(dat)); } } - catch (Exception e) { + catch (Exception e) + { Debug.Fail("failure: " + e.ToString()); } } - else if (string.Compare(sie.Name, "PropertyBagBinary", true, CultureInfo.InvariantCulture) == 0) { - try { + else if (string.Compare(sie.Name, "PropertyBagBinary", true, CultureInfo.InvariantCulture) == 0) + { + try + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Loading up property bag from stream..."); byte[] dat = (byte[])sie.Value; - if (dat != null) { + if (dat != null) + { this.propBag = new PropertyBagStream(); propBag.Read(new MemoryStream(dat)); } } - catch (Exception e) { + catch (Exception e) + { Debug.Fail("failure: " + e.ToString()); } } } } - internal int Type { - get { + internal int Type + { + get + { return type; } - set { + set + { type = value; } } - internal bool _GetManualUpdate() { + internal bool _GetManualUpdate() + { return manualUpdate; } - internal string _GetLicenseKey() { + internal string _GetLicenseKey() + { return licenseKey; } - private void CreateStorage() { + private void CreateStorage() + { Debug.Assert(storage == null, "but we already have a storage!!!"); IntPtr hglobal = IntPtr.Zero; - if (buffer != null) { + if (buffer != null) + { hglobal = UnsafeNativeMethods.GlobalAlloc(NativeMethods.GMEM_MOVEABLE, length); IntPtr pointer = UnsafeNativeMethods.GlobalLock(new HandleRef(null, hglobal)); - try { - if (pointer != IntPtr.Zero) { + try + { + if (pointer != IntPtr.Zero) + { Marshal.Copy(buffer, 0, pointer, length); } } - finally { + finally + { UnsafeNativeMethods.GlobalUnlock(new HandleRef(null, hglobal)); } } bool failed = false; - try { + try + { iLockBytes = UnsafeNativeMethods.CreateILockBytesOnHGlobal(new HandleRef(null, hglobal), true); - if (buffer == null) { + if (buffer == null) + { storage = UnsafeNativeMethods.StgCreateDocfileOnILockBytes(iLockBytes, NativeMethods.STGM_CREATE | NativeMethods.STGM_READWRITE | NativeMethods.STGM_SHARE_EXCLUSIVE, 0); } - else { + else + { storage = UnsafeNativeMethods.StgOpenStorageOnILockBytes(iLockBytes, null, NativeMethods.STGM_READWRITE | NativeMethods.STGM_SHARE_EXCLUSIVE, 0, 0); } } - catch (Exception t) { + catch (Exception t) + { Debug.Fail(t.ToString()); failed = true; } - if (failed) { - if (iLockBytes == null && hglobal != IntPtr.Zero) { + if (failed) + { + if (iLockBytes == null && hglobal != IntPtr.Zero) + { UnsafeNativeMethods.GlobalFree(new HandleRef(null, hglobal)); } - else { + else + { iLockBytes = null; } storage = null; } } - internal UnsafeNativeMethods.IPropertyBag GetPropBag() { + internal UnsafeNativeMethods.IPropertyBag GetPropBag() + { return propBag; } - internal UnsafeNativeMethods.IStorage GetStorage() { + internal UnsafeNativeMethods.IStorage GetStorage() + { if (storage == null) CreateStorage(); return storage; } - internal UnsafeNativeMethods.IStream GetStream() { - if (ms == null) { + internal UnsafeNativeMethods.IStream GetStream() + { + if (ms == null) + { Debug.Assert(buffer != null, "gotta have the buffer already..."); - if (buffer == null) return null; + if (buffer == null) + return null; ms = new MemoryStream(buffer); } - else { + else + { ms.Seek(0, SeekOrigin.Begin); } return new UnsafeNativeMethods.ComStreamFromDataStream(ms); } - private void InitializeFromStream(Stream ids) { - BinaryReader br = new BinaryReader(ids); - - type = br.ReadInt32(); - int version = br.ReadInt32(); - manualUpdate = br.ReadBoolean(); - int cc = br.ReadInt32(); - if (cc != 0) { - licenseKey = new string(br.ReadChars(cc)); - } - for (int skipUnits = br.ReadInt32(); skipUnits > 0; skipUnits --) { - int len = br.ReadInt32(); - ids.Position = ids.Position + len; - } - - length = br.ReadInt32(); - if (length > 0) - buffer = br.ReadBytes(length); + private void InitializeFromStream(Stream ids) + { + BinaryReader br = new BinaryReader(ids); + + type = br.ReadInt32(); + int version = br.ReadInt32(); + manualUpdate = br.ReadBoolean(); + int cc = br.ReadInt32(); + if (cc != 0) + { + licenseKey = new string(br.ReadChars(cc)); + } + for (int skipUnits = br.ReadInt32(); skipUnits > 0; skipUnits--) + { + int len = br.ReadInt32(); + ids.Position = ids.Position + len; + } + + length = br.ReadInt32(); + if (length > 0) + buffer = br.ReadBytes(length); } - private void InitializeBufferFromStream(Stream ids) { + private void InitializeBufferFromStream(Stream ids) + { BinaryReader br = new BinaryReader(ids); length = br.ReadInt32(); @@ -6095,64 +7205,78 @@ private void InitializeBufferFromStream(Stream ids) { buffer = br.ReadBytes(length); } - internal State RefreshStorage(UnsafeNativeMethods.IPersistStorage iPersistStorage) { + internal State RefreshStorage(UnsafeNativeMethods.IPersistStorage iPersistStorage) + { Debug.Assert(storage != null, "how can we not have a storage object?"); Debug.Assert(iLockBytes != null, "how can we have a storage w/o ILockBytes?"); - if (storage == null || iLockBytes == null) return null; + if (storage == null || iLockBytes == null) + return null; iPersistStorage.Save(storage, true); storage.Commit(0); iPersistStorage.HandsOffStorage(); - try { + try + { buffer = null; ms = null; NativeMethods.STATSTG stat = new NativeMethods.STATSTG(); iLockBytes.Stat(stat, NativeMethods.Ole.STATFLAG_NONAME); - length = (int) stat.cbSize; + length = (int)stat.cbSize; buffer = new byte[length]; IntPtr hglobal = UnsafeNativeMethods.GetHGlobalFromILockBytes(iLockBytes); IntPtr pointer = UnsafeNativeMethods.GlobalLock(new HandleRef(null, hglobal)); - try { - if (pointer != IntPtr.Zero) { + try + { + if (pointer != IntPtr.Zero) + { Marshal.Copy(pointer, buffer, 0, length); } - else { + else + { length = 0; buffer = null; } } - finally { + finally + { UnsafeNativeMethods.GlobalUnlock(new HandleRef(null, hglobal)); } } - finally { + finally + { iPersistStorage.SaveCompleted(storage); } return this; } - internal void Save(MemoryStream stream) { + internal void Save(MemoryStream stream) + { BinaryWriter bw = new BinaryWriter(stream); bw.Write(type); bw.Write(VERSION); bw.Write(manualUpdate); - if (licenseKey != null) { + if (licenseKey != null) + { bw.Write(licenseKey.Length); bw.Write(licenseKey.ToCharArray()); } - else { + else + { bw.Write((int)0); } bw.Write((int)0); // skip units bw.Write(length); - if (buffer != null) { + if (buffer != null) + { bw.Write(buffer); } - else if (ms != null) { + else if (ms != null) + { ms.Position = 0; ms.WriteTo(stream); } - else { + else + { Debug.Assert(length == 0, "if we have no data, then our length has to be 0"); } } @@ -6160,42 +7284,51 @@ internal void Save(MemoryStream stream) { /// /// ISerializable private implementation /// - void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) { + void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) + { MemoryStream stream = new MemoryStream(); Save(stream); si.AddValue("Data", stream.ToArray()); - if (propBag != null) { - try { + if (propBag != null) + { + try + { stream = new MemoryStream(); propBag.Write(stream); si.AddValue("PropertyBagBinary", stream.ToArray()); } - catch (Exception e) { + catch (Exception e) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Failed to serialize the property bag into ResX : " + e.ToString()); } } } } - internal class PropertyBagStream : UnsafeNativeMethods.IPropertyBag { + internal class PropertyBagStream : UnsafeNativeMethods.IPropertyBag + { private Hashtable bag = new Hashtable(); - internal void Read(Stream stream) { + internal void Read(Stream stream) + { BinaryFormatter formatter = new BinaryFormatter(); - try { + try + { bag = (Hashtable)formatter.Deserialize(stream); } - catch { + catch + { // Error reading. Just init an empty hashtable. bag = new Hashtable(); } } - int UnsafeNativeMethods.IPropertyBag.Read(string pszPropName, ref object pVar, UnsafeNativeMethods.IErrorLog pErrorLog) { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Reading property " + pszPropName + " from OCXState propertybag."); - + int UnsafeNativeMethods.IPropertyBag.Read(string pszPropName, ref object pVar, UnsafeNativeMethods.IErrorLog pErrorLog) + { + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Reading property " + pszPropName + " from OCXState propertybag."); + if (!bag.Contains(pszPropName)) return NativeMethods.E_INVALIDARG; @@ -6210,18 +7343,21 @@ int UnsafeNativeMethods.IPropertyBag.Read(string pszPropName, ref object pVar, U return (pVar == null) ? NativeMethods.E_INVALIDARG : NativeMethods.S_OK; } - int UnsafeNativeMethods.IPropertyBag.Write(string pszPropName, ref object pVar) { + int UnsafeNativeMethods.IPropertyBag.Write(string pszPropName, ref object pVar) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Writing property " + pszPropName + " [" + pVar + "] into OCXState propertybag."); - if (pVar != null && !pVar.GetType().IsSerializable) { + if (pVar != null && !pVar.GetType().IsSerializable) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "\t " + pVar.GetType().FullName + " is not serializable."); return NativeMethods.S_OK; } - + bag[pszPropName] = pVar; return NativeMethods.S_OK; } - internal void Write(Stream stream) { + internal void Write(Stream stream) + { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, bag); } @@ -6230,17 +7366,21 @@ internal void Write(Stream stream) { protected delegate void AboutBoxDelegate(); [ComVisible(false)] - public class AxComponentEditor : WindowsFormsComponentEditor { - public override bool EditComponent(ITypeDescriptorContext context, object obj, IWin32Window parent) { + public class AxComponentEditor : WindowsFormsComponentEditor + { + public override bool EditComponent(ITypeDescriptorContext context, object obj, IWin32Window parent) + { AxHost host = obj as AxHost; if (host != null) { - try { + try + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in AxComponentEditor.EditComponent"); ((UnsafeNativeMethods.IOleControlSite)host.oleSite).ShowPropertyFrame(); return true; } - catch (Exception t) { + catch (Exception t) + { Debug.Fail(t.ToString()); throw; } @@ -6251,160 +7391,197 @@ public override bool EditComponent(ITypeDescriptorContext context, object obj, I /// /// - internal class AxPropertyDescriptor : PropertyDescriptor { - private PropertyDescriptor baseProp; - internal AxHost owner; - private DispIdAttribute dispid; - - private TypeConverter converter; - private UITypeEditor editor; - private ArrayList updateAttrs = new ArrayList(); - private int flags = 0; - - private const int FlagUpdatedEditorAndConverter = 0x00000001; - private const int FlagCheckGetter = 0x00000002; - private const int FlagGettterThrew = 0x00000004; - private const int FlagIgnoreCanAccessProperties = 0x00000008; - private const int FlagSettingValue = 0x00000010; - + internal class AxPropertyDescriptor : PropertyDescriptor + { + private PropertyDescriptor baseProp; + internal AxHost owner; + private DispIdAttribute dispid; + + private TypeConverter converter; + private UITypeEditor editor; + private ArrayList updateAttrs = new ArrayList(); + private int flags = 0; + + private const int FlagUpdatedEditorAndConverter = 0x00000001; + private const int FlagCheckGetter = 0x00000002; + private const int FlagGettterThrew = 0x00000004; + private const int FlagIgnoreCanAccessProperties = 0x00000008; + private const int FlagSettingValue = 0x00000010; + [ SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // Shipped in Everett ] - internal AxPropertyDescriptor(PropertyDescriptor baseProp, AxHost owner) : base(baseProp) { + internal AxPropertyDescriptor(PropertyDescriptor baseProp, AxHost owner) : base(baseProp) + { this.baseProp = baseProp; this.owner = owner; // Get the category for this dispid. // dispid = (DispIdAttribute)baseProp.Attributes[typeof(DispIdAttribute)]; - if (dispid != null) { + if (dispid != null) + { // Look to see if this property has a property page. // If it does, then it needs to be Browsable(true). // - if (!this.IsBrowsable && !this.IsReadOnly) { + if (!this.IsBrowsable && !this.IsReadOnly) + { Guid g = GetPropertyPage(dispid.Value); - - if (!Guid.Empty.Equals(g)) { - Debug.WriteLineIf(AxPropTraceSwitch.TraceVerbose, "Making property: " + this.Name + " browsable because we found an property page."); - AddAttribute(new BrowsableAttribute(true)); + + if (!Guid.Empty.Equals(g)) + { + Debug.WriteLineIf(AxPropTraceSwitch.TraceVerbose, "Making property: " + this.Name + " browsable because we found an property page."); + AddAttribute(new BrowsableAttribute(true)); } } - + // Use the CategoryAttribute provided by the OCX. // CategoryAttribute cat = owner.GetCategoryForDispid(dispid.Value); - if (cat != null) { + if (cat != null) + { AddAttribute(cat); } // Check to see if this a DataSource property. // If it is, we can always get and set the value of this property. // - if (this.PropertyType.GUID.Equals(dataSource_Guid)) { + if (this.PropertyType.GUID.Equals(dataSource_Guid)) + { SetFlag(FlagIgnoreCanAccessProperties, true); } } } - - public override Type ComponentType { - get { + + public override Type ComponentType + { + get + { return baseProp.ComponentType; } } - public override TypeConverter Converter { - get { + public override TypeConverter Converter + { + get + { - if (dispid != null) { - UpdateTypeConverterAndTypeEditorInternal(false, Dispid); + if (dispid != null) + { + UpdateTypeConverterAndTypeEditorInternal(false, Dispid); } return (converter != null) ? converter : base.Converter; } } - internal int Dispid { - get { + internal int Dispid + { + get + { DispIdAttribute dispid = (DispIdAttribute)baseProp.Attributes[typeof(DispIdAttribute)]; - if (dispid != null) { + if (dispid != null) + { return dispid.Value; } return NativeMethods.ActiveX.DISPID_UNKNOWN; } } - - public override bool IsReadOnly { - get { + + public override bool IsReadOnly + { + get + { return baseProp.IsReadOnly; } } - - public override Type PropertyType { - get { + + public override Type PropertyType + { + get + { return baseProp.PropertyType; } } - internal bool SettingValue { - get { + internal bool SettingValue + { + get + { return GetFlag(FlagSettingValue); } } - - private void AddAttribute(Attribute attr) { + + private void AddAttribute(Attribute attr) + { updateAttrs.Add(attr); } - public override bool CanResetValue(object o) { + public override bool CanResetValue(object o) + { return baseProp.CanResetValue(o); } - public override object GetEditor(Type editorBaseType) { - + public override object GetEditor(Type editorBaseType) + { + UpdateTypeConverterAndTypeEditorInternal(false, dispid.Value); - if (editorBaseType.Equals(typeof(UITypeEditor)) && editor != null) { + if (editorBaseType.Equals(typeof(UITypeEditor)) && editor != null) + { return editor; } return base.GetEditor(editorBaseType); } - private bool GetFlag(int flagValue) { + private bool GetFlag(int flagValue) + { return ((flags & flagValue) == flagValue); } - private Guid GetPropertyPage(int dispid) { - try { + private Guid GetPropertyPage(int dispid) + { + try + { NativeMethods.IPerPropertyBrowsing ippb = owner.GetPerPropertyBrowsing(); - if (ippb == null) return Guid.Empty; + if (ippb == null) + return Guid.Empty; Guid rval; - if (NativeMethods.Succeeded(ippb.MapPropertyToPage(dispid, out rval))) { + if (NativeMethods.Succeeded(ippb.MapPropertyToPage(dispid, out rval))) + { return rval; } } - catch (COMException) { + catch (COMException) + { } - catch (Exception t) { + catch (Exception t) + { Debug.Fail(t.ToString()); } return Guid.Empty; } - public override object GetValue(object component) { - if ((!GetFlag(FlagIgnoreCanAccessProperties) && !owner.CanAccessProperties) || GetFlag(FlagGettterThrew)) { + public override object GetValue(object component) + { + if ((!GetFlag(FlagIgnoreCanAccessProperties) && !owner.CanAccessProperties) || GetFlag(FlagGettterThrew)) + { return null; } - try { + try + { // Some controls fire OnChanged() notifications when getting values of some properties. // To prevent this kind of recursion, we check to see if we are already inside a OnChanged() call. // owner.NoComponentChangeEvents++; return baseProp.GetValue(component); } - catch (Exception e) { - if (!GetFlag(FlagCheckGetter)) { + catch (Exception e) + { + if (!GetFlag(FlagCheckGetter)) + { Debug.WriteLineIf(AxPropTraceSwitch.TraceVerbose, "Get failed for : " + Name + " with exception: " + e.Message + " .Making property non-browsable."); SetFlag(FlagCheckGetter, true); AddAttribute(new BrowsableAttribute(false)); @@ -6413,71 +7590,87 @@ public override object GetValue(object component) { } throw e; } - finally { + finally + { owner.NoComponentChangeEvents--; } } - public void OnValueChanged(object component) { + public void OnValueChanged(object component) + { this.OnValueChanged(component, EventArgs.Empty); } - - public override void ResetValue(object o) { + + public override void ResetValue(object o) + { baseProp.ResetValue(o); } - private void SetFlag(int flagValue, bool value) { - if (value) { + private void SetFlag(int flagValue, bool value) + { + if (value) + { flags |= flagValue; } - else { + else + { flags &= ~flagValue; } } - public override void SetValue(object component, object value) { - if (!GetFlag(FlagIgnoreCanAccessProperties) && !owner.CanAccessProperties) { + public override void SetValue(object component, object value) + { + if (!GetFlag(FlagIgnoreCanAccessProperties) && !owner.CanAccessProperties) + { return; } // State oldOcxState = owner.OcxState; - try { + try + { SetFlag(FlagSettingValue, true); - if (this.PropertyType.IsEnum && (value.GetType() != this.PropertyType)) { + if (this.PropertyType.IsEnum && (value.GetType() != this.PropertyType)) + { baseProp.SetValue(component, Enum.ToObject(this.PropertyType, value)); } - else { + else + { baseProp.SetValue(component, value); } } - finally { + finally + { SetFlag(FlagSettingValue, false); } OnValueChanged(component); - if (owner == component) { + if (owner == component) + { owner.SetAxState(AxHost.valueChanged, true); } } - - public override bool ShouldSerializeValue(object o) { + + public override bool ShouldSerializeValue(object o) + { return baseProp.ShouldSerializeValue(o); } - internal void UpdateAttributes() { + internal void UpdateAttributes() + { if (updateAttrs.Count == 0) return; - + ArrayList attributes = new ArrayList(AttributeArray); - foreach(Attribute attr in updateAttrs) { + foreach (Attribute attr in updateAttrs) + { attributes.Add(attr); } - + Attribute[] temp = new Attribute[attributes.Count]; attributes.CopyTo(temp, 0); AttributeArray = temp; - + updateAttrs.Clear(); } @@ -6487,10 +7680,12 @@ internal void UpdateAttributes() { /// This simply sets flags so this will happen, it doesn't actually to the update... /// we wait and do that on-demand for perf. /// - internal void UpdateTypeConverterAndTypeEditor(bool force) { + internal void UpdateTypeConverterAndTypeEditor(bool force) + { // if this is an external request, flip the flag to false so we do the update on demand. // - if (GetFlag(FlagUpdatedEditorAndConverter) && force) { + if (GetFlag(FlagUpdatedEditorAndConverter) && force) + { SetFlag(FlagUpdatedEditorAndConverter, false); } } @@ -6500,23 +7695,28 @@ internal void UpdateTypeConverterAndTypeEditor(bool force) { /// This simply sets flags so this will happen, it doesn't actually to the update... /// we wait and do that on-demand for perf. /// - internal void UpdateTypeConverterAndTypeEditorInternal(bool force, int dispid) { + internal void UpdateTypeConverterAndTypeEditorInternal(bool force, int dispid) + { // check to see if we're being forced here or if the work really // needs to be done. // - if (GetFlag(FlagUpdatedEditorAndConverter) && !force) { + if (GetFlag(FlagUpdatedEditorAndConverter) && !force) + { return; } - - if (owner.GetOcx() == null) { + + if (owner.GetOcx() == null) + { return; } - try { + try + { NativeMethods.IPerPropertyBrowsing ppb = owner.GetPerPropertyBrowsing(); - if (ppb != null) { + if (ppb != null) + { bool hasStrings = false; // check for enums @@ -6525,51 +7725,63 @@ internal void UpdateTypeConverterAndTypeEditorInternal(bool force, int dispid) { int hr = NativeMethods.S_OK; - try { + try + { hr = ppb.GetPredefinedStrings(dispid, caStrings, caCookies); } - catch(ExternalException ex) { + catch (ExternalException ex) + { hr = ex.ErrorCode; Debug.Fail("An exception occurred inside IPerPropertyBrowsing::GetPredefinedStrings(dispid=" + dispid + "), object type=" + new ComNativeDescriptor().GetClassName(ppb)); } - if (hr != NativeMethods.S_OK) { + if (hr != NativeMethods.S_OK) + { hasStrings = false; // Destroy the existing editor if we created the current one // so if the items have disappeared, we don't hold onto the old // items. - if (converter is Com2EnumConverter) { + if (converter is Com2EnumConverter) + { converter = null; } } - else { + else + { hasStrings = true; } - if (hasStrings) { + if (hasStrings) + { OleStrCAMarshaler stringMarshaler = new OleStrCAMarshaler(caStrings); - Int32CAMarshaler intMarshaler = new Int32CAMarshaler(caCookies); + Int32CAMarshaler intMarshaler = new Int32CAMarshaler(caCookies); - if (stringMarshaler.Count > 0 && intMarshaler.Count > 0) { - if (converter == null) { + if (stringMarshaler.Count > 0 && intMarshaler.Count > 0) + { + if (converter == null) + { converter = new AxEnumConverter(this, new AxPerPropertyBrowsingEnum(this, owner, stringMarshaler, intMarshaler, true)); } - else if (converter is AxEnumConverter){ + else if (converter is AxEnumConverter) + { ((AxEnumConverter)converter).RefreshValues(); AxPerPropertyBrowsingEnum axEnum = ((AxEnumConverter)converter).com2Enum as AxPerPropertyBrowsingEnum; - if (axEnum != null) { + if (axEnum != null) + { axEnum.RefreshArrays(stringMarshaler, intMarshaler); } } - + } - else { + else + { //hasStrings = false; } } - else { + else + { // if we didn't get any strings, try the proppage edtior // // Check to see if this is a property that we have already massaged to be a @@ -6577,37 +7789,43 @@ internal void UpdateTypeConverterAndTypeEditorInternal(bool force, int dispid) { // have a .Net Editor for this type. // ComAliasNameAttribute comAlias = (ComAliasNameAttribute)baseProp.Attributes[typeof(ComAliasNameAttribute)]; - if (comAlias == null) { + if (comAlias == null) + { Guid g = GetPropertyPage(dispid); - if (!Guid.Empty.Equals(g)) { - editor = new AxPropertyTypeEditor(this, g); - - // Show any non-browsable property that has an editor through a - // property page. - // - if (!this.IsBrowsable) { - Debug.WriteLineIf(AxPropTraceSwitch.TraceVerbose, "Making property: " + this.Name + " browsable because we found an editor."); - AddAttribute(new BrowsableAttribute(true)); - } + if (!Guid.Empty.Equals(g)) + { + editor = new AxPropertyTypeEditor(this, g); + + // Show any non-browsable property that has an editor through a + // property page. + // + if (!this.IsBrowsable) + { + Debug.WriteLineIf(AxPropTraceSwitch.TraceVerbose, "Making property: " + this.Name + " browsable because we found an editor."); + AddAttribute(new BrowsableAttribute(true)); + } } } } } SetFlag(FlagUpdatedEditorAndConverter, true); - } - catch (Exception e) { - Debug.WriteLineIf(AxPropTraceSwitch.TraceVerbose, "could not get the type editor for property: " + this.Name + " Exception: " + e); - } + } + catch (Exception e) + { + Debug.WriteLineIf(AxPropTraceSwitch.TraceVerbose, "could not get the type editor for property: " + this.Name + " Exception: " + e); + } } } - private class AxPropertyTypeEditor : UITypeEditor { + private class AxPropertyTypeEditor : UITypeEditor + { private AxPropertyDescriptor propDesc; private Guid guid; - public AxPropertyTypeEditor(AxPropertyDescriptor pd, Guid guid) { + public AxPropertyTypeEditor(AxPropertyDescriptor pd, Guid guid) + { propDesc = pd; this.guid = guid; } @@ -6619,17 +7837,22 @@ public AxPropertyTypeEditor(AxPropertyDescriptor pd, Guid guid) { /// the user to modify the value. Host assistance in presenting UI to the user /// can be found through the valueAccess.getService function. /// - public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { - try { + public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) + { + try + { object instance = context.Instance; propDesc.owner.ShowPropertyPageForDispid(propDesc.Dispid, this.guid); } - catch (Exception ex1) { - if (provider != null) { - IUIService uiSvc = (IUIService)provider.GetService(typeof(IUIService)); - if (uiSvc != null){ + catch (Exception ex1) + { + if (provider != null) + { + IUIService uiSvc = (IUIService)provider.GetService(typeof(IUIService)); + if (uiSvc != null) + { uiSvc.ShowError(ex1, SR.ErrorTypeConverterFailed); - } + } } } return value; @@ -6639,7 +7862,8 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide /// Retrieves the editing style of the Edit method. If the method /// is not supported, this will return None. /// - public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { + public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) + { return UITypeEditorEditStyle.Modal; } } @@ -6648,15 +7872,18 @@ public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext contex /// simple derivation of the com2enumconverter that allows us to intercept /// the call to GetStandardValues so we can on-demand update the enum values. /// - private class AxEnumConverter : Com2EnumConverter { + private class AxEnumConverter : Com2EnumConverter + { private AxPropertyDescriptor target; - public AxEnumConverter(AxPropertyDescriptor target, Com2Enum com2Enum) : base(com2Enum) { - this.target = target; + public AxEnumConverter(AxPropertyDescriptor target, Com2Enum com2Enum) : base(com2Enum) + { + this.target = target; } - public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { - + public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) + { + // make sure the converter has been properly refreshed -- calling // the Converter property does this. // @@ -6667,108 +7894,124 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex } } - + // This exists for perf reasons. We delay doing this until we // are actually asked for the array of values. // - private class AxPerPropertyBrowsingEnum : Com2Enum { + private class AxPerPropertyBrowsingEnum : Com2Enum + { private AxPropertyDescriptor target; - private AxHost owner; - private OleStrCAMarshaler nameMarshaller; - private Int32CAMarshaler valueMarshaller; - private bool arraysFetched; - - public AxPerPropertyBrowsingEnum(AxPropertyDescriptor targetObject, AxHost owner, OleStrCAMarshaler names, Int32CAMarshaler values, bool allowUnknowns) : base(new string[0], new object[0], allowUnknowns) { + private AxHost owner; + private OleStrCAMarshaler nameMarshaller; + private Int32CAMarshaler valueMarshaller; + private bool arraysFetched; + + public AxPerPropertyBrowsingEnum(AxPropertyDescriptor targetObject, AxHost owner, OleStrCAMarshaler names, Int32CAMarshaler values, bool allowUnknowns) : base(new string[0], new object[0], allowUnknowns) + { this.target = targetObject; this.nameMarshaller = names; this.valueMarshaller = values; this.owner = owner; this.arraysFetched = false; } - + /// /// Retrieve a copy of the value array /// - public override object[] Values { - get { + public override object[] Values + { + get + { EnsureArrays(); return base.Values; } } - + /// /// Retrieve a copy of the nme array. /// - public override string[] Names { - get { + public override string[] Names + { + get + { EnsureArrays(); return base.Names; } } - + // ensure that we have processed the caStructs into arrays // of values and strings // - private void EnsureArrays() { - if (this.arraysFetched) { + private void EnsureArrays() + { + if (this.arraysFetched) + { return; } - + this.arraysFetched = true; - - try { - + + try + { + // marshal the items. object[] nameItems = nameMarshaller.Items; - object[] cookieItems= valueMarshaller.Items; + object[] cookieItems = valueMarshaller.Items; NativeMethods.IPerPropertyBrowsing ppb = (NativeMethods.IPerPropertyBrowsing)owner.GetPerPropertyBrowsing(); int itemCount = 0; - + Debug.Assert(cookieItems != null && nameItems != null, "An item array is null"); - - if (nameItems.Length > 0) { + + if (nameItems.Length > 0) + { object[] valueItems = new object[cookieItems.Length]; NativeMethods.VARIANT var = new NativeMethods.VARIANT(); int cookie; - + Debug.Assert(cookieItems.Length == nameItems.Length, "Got uneven names and cookies"); - + // for each name item, we ask the object for it's corresponding value. // - for (int i = 0; i < nameItems.Length; i++) { + for (int i = 0; i < nameItems.Length; i++) + { cookie = (int)cookieItems[i]; - if (nameItems[i] == null || !(nameItems[i] is string)) { + if (nameItems[i] == null || !(nameItems[i] is string)) + { Debug.Fail("Bad IPerPropertyBrowsing item [" + i.ToString(CultureInfo.InvariantCulture) + "], name=" + (nameItems == null ? "(unknown)" : nameItems[i].ToString())); continue; } var.vt = (short)NativeMethods.tagVT.VT_EMPTY; int hr = ppb.GetPredefinedValue(target.Dispid, cookie, var); - if (hr == NativeMethods.S_OK && var.vt != (short)NativeMethods.tagVT.VT_EMPTY) { + if (hr == NativeMethods.S_OK && var.vt != (short)NativeMethods.tagVT.VT_EMPTY) + { valueItems[i] = var.ToObject(); } var.Clear(); itemCount++; } - + // pass this data down to the base Com2Enum object... - if (itemCount > 0) { + if (itemCount > 0) + { string[] strings = new string[itemCount]; Array.Copy(nameItems, 0, strings, 0, itemCount); base.PopulateArrays(strings, valueItems); } } } - catch (Exception ex) { + catch (Exception ex) + { Debug.Fail("Failed to build IPerPropertyBrowsing editor. " + ex.GetType().Name + ", " + ex.Message); } } - - internal void RefreshArrays( OleStrCAMarshaler names, Int32CAMarshaler values) { + + internal void RefreshArrays(OleStrCAMarshaler names, Int32CAMarshaler values) + { this.nameMarshaller = names; this.valueMarshaller = values; this.arraysFetched = false; } - + #if false // FxCop: Currently not used private string GetDisplayString(int dispid, ref bool success) { @@ -6786,17 +8029,20 @@ private string GetDisplayString(int dispid, ref bool success) { return null; } #endif - - protected override void PopulateArrays(string[] names, object[] values) { + + protected override void PopulateArrays(string[] names, object[] values) + { // we call base.PopulateArrays directly when we actually want to do this. } - - public override object FromString(string s) { + + public override object FromString(string s) + { EnsureArrays(); return base.FromString(s); } - - public override string ToString(object v) { + + public override string ToString(object v) + { EnsureArrays(); return base.ToString(v); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/BaseCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/BaseCollection.cs index 05619635063..f3c46f4739d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/BaseCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/BaseCollection.cs @@ -10,7 +10,8 @@ namespace System.Windows.Forms /// /// Provides the base functionality for creating collections. /// - public class BaseCollection : MarshalByRefObject, ICollection { + public class BaseCollection : MarshalByRefObject, ICollection + { /// /// Gets the total number of elements in a collection. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Binding.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Binding.cs index abfb5e87846..52a4501a9e1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Binding.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Binding.cs @@ -525,7 +525,7 @@ private object GetPropValue() { return DataSourceNullValue; } - + return _propInfo.GetValue(_control) ?? DataSourceNullValue; } @@ -750,7 +750,7 @@ private object FormatObject(object value) /// method, which in turn calls PullData. PullData is also called by the binding manager when pulling data /// from all bounds properties in one go. /// - internal bool PullData() => PullData(reformat: true, force: false); + internal bool PullData() => PullData(reformat: true, force: false); internal bool PullData(bool reformat) => PullData(reformat, force: false); @@ -1235,7 +1235,7 @@ internal Type BindToType } return type; } - + return _fieldInfo?.PropertyType; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/BindingContext.cs b/src/System.Windows.Forms/src/System/Windows/Forms/BindingContext.cs index 35ca091eae7..2b465cd8cf3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/BindingContext.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/BindingContext.cs @@ -213,7 +213,7 @@ public override bool Equals(object target) { return false; } - + return _wRef.Target == keyTarget._wRef.Target && _dataMember == keyTarget._dataMember; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/BindingManagerBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/BindingManagerBase.cs index 9aab2c00605..5cd173a0710 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/BindingManagerBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/BindingManagerBase.cs @@ -107,7 +107,7 @@ protected virtual PropertyDescriptorCollection GetItemProperties(Type listType, { return TypeDescriptor.GetProperties(listType); } - + foreach (PropertyInfo property in listType.GetProperties()) { if (property.Name == "Item" && property.PropertyType != typeof(object)) @@ -180,7 +180,7 @@ protected virtual PropertyDescriptorCollection GetItemProperties(Type listType, } } } - + return null; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/BindingManagerDataErrorEventHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/BindingManagerDataErrorEventHandler.cs index 577b8d0115b..b816c4a9c70 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/BindingManagerDataErrorEventHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/BindingManagerDataErrorEventHandler.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs b/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs index fadf3a1433c..52605a4abd5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.ComponentModel; @@ -20,7 +21,8 @@ namespace System.Windows.Forms { Designer("System.Windows.Forms.Design.BindingNavigatorDesigner, " + AssemblyRef.SystemDesign), SRDescription(nameof(SR.DescriptionBindingNavigator)) ] - public class BindingNavigator : ToolStrip, ISupportInitialize { + public class BindingNavigator : ToolStrip, ISupportInitialize + { private BindingSource bindingSource; @@ -47,13 +49,15 @@ public class BindingNavigator : ToolStrip, ISupportInitialize { /// Call AddStandardItems() to add standard tool strip items. /// [EditorBrowsable(EditorBrowsableState.Never)] - public BindingNavigator() : this(false) { + public BindingNavigator() : this(false) + { } /// /// Creates a BindingNavigator strip containing standard items, bound to the specified BindingSource. /// - public BindingNavigator(BindingSource bindingSource) : this(true) { + public BindingNavigator(BindingSource bindingSource) : this(true) + { BindingSource = bindingSource; } @@ -62,8 +66,10 @@ public BindingNavigator(BindingSource bindingSource) : this(true) { /// Call AddStandardItems() to add standard tool strip items. /// [EditorBrowsable(EditorBrowsableState.Never)] - public BindingNavigator(IContainer container) : this(false) { - if (container == null) { + public BindingNavigator(IContainer container) : this(false) + { + if (container == null) + { throw new ArgumentNullException(nameof(container)); } @@ -73,8 +79,10 @@ public BindingNavigator(IContainer container) : this(false) { /// /// Creates a BindingNavigator strip, optionally containing a set of standard tool strip items. /// - public BindingNavigator(bool addStandardItems) { - if (addStandardItems) { + public BindingNavigator(bool addStandardItems) + { + if (addStandardItems) + { AddStandardItems(); } } @@ -82,14 +90,16 @@ public BindingNavigator(bool addStandardItems) { /// /// ISupportInitialize support. Disables updates to tool strip items during initialization. /// - public void BeginInit() { + public void BeginInit() + { initializing = true; } /// /// ISupportInitialize support. Enables updates to tool strip items after initialization. /// - public void EndInit() { + public void EndInit() + { initializing = false; RefreshItemsInternal(); } @@ -97,8 +107,10 @@ public void EndInit() { /// /// Unhooks the BindingNavigator from the BindingSource. /// - protected override void Dispose(bool disposing) { - if (disposing) { + protected override void Dispose(bool disposing) + { + if (disposing) + { BindingSource = null; // ...unwires from events of any prior BindingSource } @@ -122,20 +134,21 @@ protected override void Dispose(bool disposing) { /// Note: This method does NOT remove any previous items from the strip, or suspend /// layout while items are being added. Those are responsibilities of the caller. /// - public virtual void AddStandardItems() { + public virtual void AddStandardItems() + { // // Create items // - MoveFirstItem = new System.Windows.Forms.ToolStripButton(); + MoveFirstItem = new System.Windows.Forms.ToolStripButton(); MovePreviousItem = new System.Windows.Forms.ToolStripButton(); - MoveNextItem = new System.Windows.Forms.ToolStripButton(); - MoveLastItem = new System.Windows.Forms.ToolStripButton(); - PositionItem = new System.Windows.Forms.ToolStripTextBox(); - CountItem = new System.Windows.Forms.ToolStripLabel(); - AddNewItem = new System.Windows.Forms.ToolStripButton(); - DeleteItem = new System.Windows.Forms.ToolStripButton(); + MoveNextItem = new System.Windows.Forms.ToolStripButton(); + MoveLastItem = new System.Windows.Forms.ToolStripButton(); + PositionItem = new System.Windows.Forms.ToolStripTextBox(); + CountItem = new System.Windows.Forms.ToolStripLabel(); + AddNewItem = new System.Windows.Forms.ToolStripButton(); + DeleteItem = new System.Windows.Forms.ToolStripButton(); ToolStripSeparator separator1 = new System.Windows.Forms.ToolStripSeparator(); ToolStripSeparator separator2 = new System.Windows.Forms.ToolStripSeparator(); @@ -149,28 +162,28 @@ public virtual void AddStandardItems() { // vb dev. char ch = string.IsNullOrEmpty(Name) || char.IsLower(Name[0]) ? 'b' : 'B'; - MoveFirstItem.Name = ch + "indingNavigatorMoveFirstItem"; + MoveFirstItem.Name = ch + "indingNavigatorMoveFirstItem"; MovePreviousItem.Name = ch + "indingNavigatorMovePreviousItem"; - MoveNextItem.Name = ch + "indingNavigatorMoveNextItem"; - MoveLastItem.Name = ch + "indingNavigatorMoveLastItem"; - PositionItem.Name = ch + "indingNavigatorPositionItem"; - CountItem.Name = ch + "indingNavigatorCountItem"; - AddNewItem.Name = ch + "indingNavigatorAddNewItem"; - DeleteItem.Name = ch + "indingNavigatorDeleteItem"; - separator1.Name = ch + "indingNavigatorSeparator"; - separator2.Name = ch + "indingNavigatorSeparator"; - separator3.Name = ch + "indingNavigatorSeparator"; - - MoveFirstItem.Text = SR.BindingNavigatorMoveFirstItemText; + MoveNextItem.Name = ch + "indingNavigatorMoveNextItem"; + MoveLastItem.Name = ch + "indingNavigatorMoveLastItem"; + PositionItem.Name = ch + "indingNavigatorPositionItem"; + CountItem.Name = ch + "indingNavigatorCountItem"; + AddNewItem.Name = ch + "indingNavigatorAddNewItem"; + DeleteItem.Name = ch + "indingNavigatorDeleteItem"; + separator1.Name = ch + "indingNavigatorSeparator"; + separator2.Name = ch + "indingNavigatorSeparator"; + separator3.Name = ch + "indingNavigatorSeparator"; + + MoveFirstItem.Text = SR.BindingNavigatorMoveFirstItemText; MovePreviousItem.Text = SR.BindingNavigatorMovePreviousItemText; - MoveNextItem.Text = SR.BindingNavigatorMoveNextItemText; - MoveLastItem.Text = SR.BindingNavigatorMoveLastItemText; - AddNewItem.Text = SR.BindingNavigatorAddNewItemText; - DeleteItem.Text = SR.BindingNavigatorDeleteItemText; + MoveNextItem.Text = SR.BindingNavigatorMoveNextItemText; + MoveLastItem.Text = SR.BindingNavigatorMoveLastItemText; + AddNewItem.Text = SR.BindingNavigatorAddNewItemText; + DeleteItem.Text = SR.BindingNavigatorDeleteItemText; - CountItem.ToolTipText = SR.BindingNavigatorCountItemTip; + CountItem.ToolTipText = SR.BindingNavigatorCountItemTip; PositionItem.ToolTipText = SR.BindingNavigatorPositionItemTip; - CountItem.AutoToolTip = false; + CountItem.AutoToolTip = false; PositionItem.AutoToolTip = false; PositionItem.AccessibleName = SR.BindingNavigatorPositionAccessibleName; @@ -178,20 +191,20 @@ public virtual void AddStandardItems() { // Set up images // - Bitmap moveFirstImage = DpiHelper.GetBitmapFromIcon(typeof(BindingNavigator), "BindingNavigator.MoveFirst"); + Bitmap moveFirstImage = DpiHelper.GetBitmapFromIcon(typeof(BindingNavigator), "BindingNavigator.MoveFirst"); Bitmap movePreviousImage = DpiHelper.GetBitmapFromIcon(typeof(BindingNavigator), "BindingNavigator.MovePrevious"); - Bitmap moveNextImage = DpiHelper.GetBitmapFromIcon(typeof(BindingNavigator), "BindingNavigator.MoveNext"); - Bitmap moveLastImage = DpiHelper.GetBitmapFromIcon(typeof(BindingNavigator), "BindingNavigator.MoveLast"); - Bitmap addNewImage = DpiHelper.GetBitmapFromIcon(typeof(BindingNavigator), "BindingNavigator.AddNew"); - Bitmap deleteImage = DpiHelper.GetBitmapFromIcon(typeof(BindingNavigator), "BindingNavigator.Delete"); + Bitmap moveNextImage = DpiHelper.GetBitmapFromIcon(typeof(BindingNavigator), "BindingNavigator.MoveNext"); + Bitmap moveLastImage = DpiHelper.GetBitmapFromIcon(typeof(BindingNavigator), "BindingNavigator.MoveLast"); + Bitmap addNewImage = DpiHelper.GetBitmapFromIcon(typeof(BindingNavigator), "BindingNavigator.AddNew"); + Bitmap deleteImage = DpiHelper.GetBitmapFromIcon(typeof(BindingNavigator), "BindingNavigator.Delete"); - MoveFirstItem.Image = moveFirstImage; + MoveFirstItem.Image = moveFirstImage; MovePreviousItem.Image = movePreviousImage; - MoveNextItem.Image = moveNextImage; - MoveLastItem.Image = moveLastImage; - AddNewItem.Image = addNewImage; - DeleteItem.Image = deleteImage; + MoveNextItem.Image = moveNextImage; + MoveLastItem.Image = moveLastImage; + AddNewItem.Image = addNewImage; + DeleteItem.Image = deleteImage; MoveFirstItem.RightToLeftAutoMirrorImage = true; MovePreviousItem.RightToLeftAutoMirrorImage = true; @@ -200,12 +213,12 @@ public virtual void AddStandardItems() { AddNewItem.RightToLeftAutoMirrorImage = true; DeleteItem.RightToLeftAutoMirrorImage = true; - MoveFirstItem.DisplayStyle = ToolStripItemDisplayStyle.Image; + MoveFirstItem.DisplayStyle = ToolStripItemDisplayStyle.Image; MovePreviousItem.DisplayStyle = ToolStripItemDisplayStyle.Image; - MoveNextItem.DisplayStyle = ToolStripItemDisplayStyle.Image; - MoveLastItem.DisplayStyle = ToolStripItemDisplayStyle.Image; - AddNewItem.DisplayStyle = ToolStripItemDisplayStyle.Image; - DeleteItem.DisplayStyle = ToolStripItemDisplayStyle.Image; + MoveNextItem.DisplayStyle = ToolStripItemDisplayStyle.Image; + MoveLastItem.DisplayStyle = ToolStripItemDisplayStyle.Image; + AddNewItem.DisplayStyle = ToolStripItemDisplayStyle.Image; + DeleteItem.DisplayStyle = ToolStripItemDisplayStyle.Image; // // Set other random properties @@ -242,12 +255,15 @@ public virtual void AddStandardItems() { TypeConverter(typeof(ReferenceConverter)), SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly") ] - public BindingSource BindingSource { - get { + public BindingSource BindingSource + { + get + { return bindingSource; } - set { + set + { WireUpBindingSource(ref bindingSource, value); } } @@ -260,15 +276,19 @@ public BindingSource BindingSource { SRCategory(nameof(SR.CatItems)), SRDescription(nameof(SR.BindingNavigatorMoveFirstItemPropDescr)) ] - public ToolStripItem MoveFirstItem { - get { - if (moveFirstItem != null && moveFirstItem.IsDisposed) { + public ToolStripItem MoveFirstItem + { + get + { + if (moveFirstItem != null && moveFirstItem.IsDisposed) + { moveFirstItem = null; } return moveFirstItem; } - set { + set + { WireUpButton(ref moveFirstItem, value, new EventHandler(OnMoveFirst)); } } @@ -281,17 +301,21 @@ public ToolStripItem MoveFirstItem { SRCategory(nameof(SR.CatItems)), SRDescription(nameof(SR.BindingNavigatorMovePreviousItemPropDescr)) ] - public ToolStripItem MovePreviousItem { - get { + public ToolStripItem MovePreviousItem + { + get + { - if (movePreviousItem != null && movePreviousItem.IsDisposed) { + if (movePreviousItem != null && movePreviousItem.IsDisposed) + { movePreviousItem = null; } - + return movePreviousItem; } - set { + set + { WireUpButton(ref movePreviousItem, value, new EventHandler(OnMovePrevious)); } } @@ -304,15 +328,19 @@ public ToolStripItem MovePreviousItem { SRCategory(nameof(SR.CatItems)), SRDescription(nameof(SR.BindingNavigatorMoveNextItemPropDescr)) ] - public ToolStripItem MoveNextItem { - get { - if (moveNextItem != null && moveNextItem.IsDisposed) { + public ToolStripItem MoveNextItem + { + get + { + if (moveNextItem != null && moveNextItem.IsDisposed) + { moveNextItem = null; } return moveNextItem; } - set { + set + { WireUpButton(ref moveNextItem, value, new EventHandler(OnMoveNext)); } } @@ -325,15 +353,19 @@ public ToolStripItem MoveNextItem { SRCategory(nameof(SR.CatItems)), SRDescription(nameof(SR.BindingNavigatorMoveLastItemPropDescr)) ] - public ToolStripItem MoveLastItem { - get { - if (moveLastItem != null && moveLastItem.IsDisposed) { + public ToolStripItem MoveLastItem + { + get + { + if (moveLastItem != null && moveLastItem.IsDisposed) + { moveLastItem = null; } return moveLastItem; } - set { + set + { WireUpButton(ref moveLastItem, value, new EventHandler(OnMoveLast)); } } @@ -346,16 +378,21 @@ public ToolStripItem MoveLastItem { SRCategory(nameof(SR.CatItems)), SRDescription(nameof(SR.BindingNavigatorAddNewItemPropDescr)) ] - public ToolStripItem AddNewItem { - get { - if (addNewItem != null && addNewItem.IsDisposed) { + public ToolStripItem AddNewItem + { + get + { + if (addNewItem != null && addNewItem.IsDisposed) + { addNewItem = null; } return addNewItem; } - set { - if (addNewItem != value && value != null) { + set + { + if (addNewItem != value && value != null) + { value.InternalEnabledChanged += new System.EventHandler(OnAddNewItemEnabledChanged); addNewItemUserEnabled = value.Enabled; } @@ -371,16 +408,21 @@ public ToolStripItem AddNewItem { SRCategory(nameof(SR.CatItems)), SRDescription(nameof(SR.BindingNavigatorDeleteItemPropDescr)) ] - public ToolStripItem DeleteItem { - get { - if (deleteItem != null && deleteItem.IsDisposed) { + public ToolStripItem DeleteItem + { + get + { + if (deleteItem != null && deleteItem.IsDisposed) + { deleteItem = null; } return deleteItem; } - set { - if (deleteItem != value && value != null) { + set + { + if (deleteItem != value && value != null) + { value.InternalEnabledChanged += new System.EventHandler(OnDeleteItemEnabledChanged); deleteItemUserEnabled = value.Enabled; } @@ -397,15 +439,19 @@ public ToolStripItem DeleteItem { SRCategory(nameof(SR.CatItems)), SRDescription(nameof(SR.BindingNavigatorPositionItemPropDescr)) ] - public ToolStripItem PositionItem { - get { - if (positionItem != null && positionItem.IsDisposed) { + public ToolStripItem PositionItem + { + get + { + if (positionItem != null && positionItem.IsDisposed) + { positionItem = null; } return positionItem; } - set { + set + { WireUpTextBox(ref positionItem, value, new KeyEventHandler(OnPositionKey), new EventHandler(OnPositionLostFocus)); } } @@ -418,15 +464,19 @@ public ToolStripItem PositionItem { SRCategory(nameof(SR.CatItems)), SRDescription(nameof(SR.BindingNavigatorCountItemPropDescr)) ] - public ToolStripItem CountItem { - get { - if (countItem != null && countItem.IsDisposed) { + public ToolStripItem CountItem + { + get + { + if (countItem != null && countItem.IsDisposed) + { countItem = null; } return countItem; } - set { + set + { WireUpLabel(ref countItem, value); } } @@ -438,13 +488,17 @@ public ToolStripItem CountItem { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.BindingNavigatorCountItemFormatPropDescr)) ] - public string CountItemFormat { - get { + public string CountItemFormat + { + get + { return countItemFormat; } - set { - if (countItemFormat != value) { + set + { + if (countItemFormat != value) + { countItemFormat = value; RefreshItemsInternal(); } @@ -459,27 +513,31 @@ public string CountItemFormat { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.BindingNavigatorRefreshItemsEventDescr)) ] - public event EventHandler RefreshItems { + public event EventHandler RefreshItems + { add => onRefreshItems += value; remove => onRefreshItems -= value; } - + /// /// Refreshes the state of the standard items to reflect the current state of the data. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void RefreshItemsCore() { + protected virtual void RefreshItemsCore() + { int count, position; bool allowNew, allowRemove; // Get state info from the binding source (if any) - if (bindingSource == null) { + if (bindingSource == null) + { count = 0; position = 0; allowNew = false; allowRemove = false; } - else { + else + { count = bindingSource.Count; position = bindingSource.Position + 1; allowNew = (bindingSource as IBindingList).AllowNew; @@ -487,37 +545,48 @@ protected virtual void RefreshItemsCore() { } // Enable or disable items (except when in design mode) - if (!DesignMode) { - if (MoveFirstItem != null) moveFirstItem.Enabled = (position > 1); - if (MovePreviousItem != null) movePreviousItem.Enabled = (position > 1); - if (MoveNextItem != null) moveNextItem.Enabled = (position < count); - if (MoveLastItem != null) moveLastItem.Enabled = (position < count); - - if (AddNewItem != null) { - System.EventHandler handler = new System.EventHandler(OnAddNewItemEnabledChanged); - addNewItem.InternalEnabledChanged -= handler; - addNewItem.Enabled = (addNewItemUserEnabled && allowNew); - addNewItem.InternalEnabledChanged += handler; + if (!DesignMode) + { + if (MoveFirstItem != null) + moveFirstItem.Enabled = (position > 1); + if (MovePreviousItem != null) + movePreviousItem.Enabled = (position > 1); + if (MoveNextItem != null) + moveNextItem.Enabled = (position < count); + if (MoveLastItem != null) + moveLastItem.Enabled = (position < count); + + if (AddNewItem != null) + { + System.EventHandler handler = new System.EventHandler(OnAddNewItemEnabledChanged); + addNewItem.InternalEnabledChanged -= handler; + addNewItem.Enabled = (addNewItemUserEnabled && allowNew); + addNewItem.InternalEnabledChanged += handler; } - if (DeleteItem != null) { - System.EventHandler handler = new System.EventHandler(OnDeleteItemEnabledChanged); - deleteItem.InternalEnabledChanged -= handler; - deleteItem.Enabled = (deleteItemUserEnabled && allowRemove && count > 0); - deleteItem.InternalEnabledChanged += handler; + if (DeleteItem != null) + { + System.EventHandler handler = new System.EventHandler(OnDeleteItemEnabledChanged); + deleteItem.InternalEnabledChanged -= handler; + deleteItem.Enabled = (deleteItemUserEnabled && allowRemove && count > 0); + deleteItem.InternalEnabledChanged += handler; } - if (PositionItem != null) positionItem.Enabled = (position > 0 && count > 0); - if (CountItem != null) countItem.Enabled = (count > 0); + if (PositionItem != null) + positionItem.Enabled = (position > 0 && count > 0); + if (CountItem != null) + countItem.Enabled = (count > 0); } // Update current position indicator - if (positionItem != null) { + if (positionItem != null) + { positionItem.Text = position.ToString(CultureInfo.CurrentCulture); } // Update record count indicator - if (countItem != null) { + if (countItem != null) + { countItem.Text = DesignMode ? CountItemFormat : string.Format(CultureInfo.CurrentCulture, CountItemFormat, count); } } @@ -526,12 +595,14 @@ protected virtual void RefreshItemsCore() { /// Called when the state of the tool strip items needs to be refreshed to reflect the current state of the data. /// Calls to refresh the state of the standard items, then raises the RefreshItems event. /// - protected virtual void OnRefreshItems() { + protected virtual void OnRefreshItems() + { // Refresh all the standard items RefreshItemsCore(); // Raise the public event - if (onRefreshItems != null) { + if (onRefreshItems != null) + { onRefreshItems(this, EventArgs.Empty); } } @@ -541,7 +612,8 @@ protected virtual void OnRefreshItems() { /// on the form, focus remains on the active control and the standard item does not perform its standard click action. /// Custom items may also use this method to trigger form validation and check for success before performing an action. /// - public bool Validate() { + public bool Validate() + { bool validatedControlAllowsFocusChange; return this.ValidateActiveControl(out validatedControlAllowsFocusChange); } @@ -549,29 +621,35 @@ public bool Validate() { /// /// Accept new row position entered into PositionItem. /// - private void AcceptNewPosition() { + private void AcceptNewPosition() + { // If no position item or binding source, do nothing - if (positionItem == null || bindingSource == null) { + if (positionItem == null || bindingSource == null) + { return; } // Default to old position, in case new position turns out to be garbage int newPosition = bindingSource.Position; - try { + try + { // Read new position from item text (and subtract one!) newPosition = Convert.ToInt32(positionItem.Text, CultureInfo.CurrentCulture) - 1; } - catch (System.FormatException) { + catch (System.FormatException) + { // Ignore bad user input } - catch (System.OverflowException) { + catch (System.OverflowException) + { // Ignore bad user input } // If user has managed to enter a valid number, that is not the same as the current position, try // navigating to that position. Let the BindingSource validate the new position to keep it in range. - if (newPosition != bindingSource.Position) { + if (newPosition != bindingSource.Position) + { bindingSource.Position = newPosition; } @@ -583,18 +661,22 @@ private void AcceptNewPosition() { /// /// Cancel new row position entered into PositionItem. /// - private void CancelNewPosition() { + private void CancelNewPosition() + { // Just refresh state of all items to reflect current position // (causing position item's new value to get blasted away) RefreshItemsInternal(); } - + /// /// Navigates to first item in BindingSource's list when the MoveFirstItem is clicked. /// - private void OnMoveFirst(object sender, EventArgs e) { - if (Validate()) { - if (bindingSource != null) { + private void OnMoveFirst(object sender, EventArgs e) + { + if (Validate()) + { + if (bindingSource != null) + { bindingSource.MoveFirst(); RefreshItemsInternal(); } @@ -604,9 +686,12 @@ private void OnMoveFirst(object sender, EventArgs e) { /// /// Navigates to previous item in BindingSource's list when the MovePreviousItem is clicked. /// - private void OnMovePrevious(object sender, EventArgs e) { - if (Validate()) { - if (bindingSource != null) { + private void OnMovePrevious(object sender, EventArgs e) + { + if (Validate()) + { + if (bindingSource != null) + { bindingSource.MovePrevious(); RefreshItemsInternal(); } @@ -616,9 +701,12 @@ private void OnMovePrevious(object sender, EventArgs e) { /// /// Navigates to next item in BindingSource's list when the MoveNextItem is clicked. /// - private void OnMoveNext(object sender, EventArgs e) { - if (Validate()) { - if (bindingSource != null) { + private void OnMoveNext(object sender, EventArgs e) + { + if (Validate()) + { + if (bindingSource != null) + { bindingSource.MoveNext(); RefreshItemsInternal(); } @@ -628,9 +716,12 @@ private void OnMoveNext(object sender, EventArgs e) { /// /// Navigates to last item in BindingSource's list when the MoveLastItem is clicked. /// - private void OnMoveLast(object sender, EventArgs e) { - if (Validate()) { - if (bindingSource != null) { + private void OnMoveLast(object sender, EventArgs e) + { + if (Validate()) + { + if (bindingSource != null) + { bindingSource.MoveLast(); RefreshItemsInternal(); } @@ -640,9 +731,12 @@ private void OnMoveLast(object sender, EventArgs e) { /// /// Adds new item to BindingSource's list when the AddNewItem is clicked. /// - private void OnAddNew(object sender, EventArgs e) { - if (Validate()) { - if (bindingSource != null) { + private void OnAddNew(object sender, EventArgs e) + { + if (Validate()) + { + if (bindingSource != null) + { bindingSource.AddNew(); RefreshItemsInternal(); } @@ -652,9 +746,12 @@ private void OnAddNew(object sender, EventArgs e) { /// /// Deletes current item from BindingSource's list when the DeleteItem is clicked. /// - private void OnDelete(object sender, EventArgs e) { - if (Validate()) { - if (bindingSource != null) { + private void OnDelete(object sender, EventArgs e) + { + if (Validate()) + { + if (bindingSource != null) + { bindingSource.RemoveCurrent(); RefreshItemsInternal(); } @@ -664,8 +761,10 @@ private void OnDelete(object sender, EventArgs e) { /// /// Navigates to specific item in BindingSource's list when a value is entered into the PositionItem. /// - private void OnPositionKey(object sender, KeyEventArgs e) { - switch (e.KeyCode) { + private void OnPositionKey(object sender, KeyEventArgs e) + { + switch (e.KeyCode) + { case Keys.Enter: AcceptNewPosition(); break; @@ -678,30 +777,35 @@ private void OnPositionKey(object sender, KeyEventArgs e) { /// /// Navigates to specific item in BindingSource's list when a value is entered into the PositionItem. /// - private void OnPositionLostFocus(object sender, EventArgs e) { + private void OnPositionLostFocus(object sender, EventArgs e) + { AcceptNewPosition(); } /// /// Refresh tool strip items when something changes in the BindingSource. /// - private void OnBindingSourceStateChanged(object sender, EventArgs e) { + private void OnBindingSourceStateChanged(object sender, EventArgs e) + { RefreshItemsInternal(); } /// /// Refresh tool strip items when something changes in the BindingSource's list. /// - private void OnBindingSourceListChanged(object sender, ListChangedEventArgs e) { + private void OnBindingSourceListChanged(object sender, ListChangedEventArgs e) + { RefreshItemsInternal(); } /// /// Refresh the state of the items when the state of the data changes. /// - private void RefreshItemsInternal() { + private void RefreshItemsInternal() + { // Block all updates during initialization - if (initializing) { + if (initializing) + { return; } @@ -709,22 +813,28 @@ private void RefreshItemsInternal() { OnRefreshItems(); } - private void ResetCountItemFormat() { + private void ResetCountItemFormat() + { countItemFormat = SR.BindingNavigatorCountItemFormat; } - private bool ShouldSerializeCountItemFormat() { + private bool ShouldSerializeCountItemFormat() + { return countItemFormat != SR.BindingNavigatorCountItemFormat; } - private void OnAddNewItemEnabledChanged(object sender, EventArgs e) { - if (AddNewItem != null) { + private void OnAddNewItemEnabledChanged(object sender, EventArgs e) + { + if (AddNewItem != null) + { addNewItemUserEnabled = addNewItem.Enabled; } } - private void OnDeleteItemEnabledChanged(object sender, EventArgs e) { - if (DeleteItem != null) { + private void OnDeleteItemEnabledChanged(object sender, EventArgs e) + { + if (DeleteItem != null) + { deleteItemUserEnabled = deleteItem.Enabled; } } @@ -733,16 +843,20 @@ private void OnDeleteItemEnabledChanged(object sender, EventArgs e) { /// Wire up some member variable to the specified button item, hooking events /// on the new button and unhooking them from the previous button, if required. /// - private void WireUpButton(ref ToolStripItem oldButton, ToolStripItem newButton, EventHandler clickHandler) { - if (oldButton == newButton) { + private void WireUpButton(ref ToolStripItem oldButton, ToolStripItem newButton, EventHandler clickHandler) + { + if (oldButton == newButton) + { return; } - if (oldButton != null) { + if (oldButton != null) + { oldButton.Click -= clickHandler; } - if (newButton != null) { + if (newButton != null) + { newButton.Click += clickHandler; } @@ -754,17 +868,21 @@ private void WireUpButton(ref ToolStripItem oldButton, ToolStripItem newButton, /// Wire up some member variable to the specified text box item, hooking events /// on the new text box and unhooking them from the previous text box, if required. /// - private void WireUpTextBox(ref ToolStripItem oldTextBox, ToolStripItem newTextBox, KeyEventHandler keyUpHandler, EventHandler lostFocusHandler) { - if (oldTextBox != newTextBox) { + private void WireUpTextBox(ref ToolStripItem oldTextBox, ToolStripItem newTextBox, KeyEventHandler keyUpHandler, EventHandler lostFocusHandler) + { + if (oldTextBox != newTextBox) + { ToolStripControlHost oldCtrl = oldTextBox as ToolStripControlHost; ToolStripControlHost newCtrl = newTextBox as ToolStripControlHost; - if (oldCtrl != null) { + if (oldCtrl != null) + { oldCtrl.KeyUp -= keyUpHandler; oldCtrl.LostFocus -= lostFocusHandler; } - if (newCtrl != null) { + if (newCtrl != null) + { newCtrl.KeyUp += keyUpHandler; newCtrl.LostFocus += lostFocusHandler; } @@ -778,8 +896,10 @@ private void WireUpTextBox(ref ToolStripItem oldTextBox, ToolStripItem newTextBo /// Wire up some member variable to the specified label item, hooking events /// on the new label and unhooking them from the previous label, if required. /// - private void WireUpLabel(ref ToolStripItem oldLabel, ToolStripItem newLabel) { - if (oldLabel != newLabel) { + private void WireUpLabel(ref ToolStripItem oldLabel, ToolStripItem newLabel) + { + if (oldLabel != newLabel) + { oldLabel = newLabel; RefreshItemsInternal(); } @@ -789,24 +909,28 @@ private void WireUpLabel(ref ToolStripItem oldLabel, ToolStripItem newLabel) { /// Wire up some member variable to the specified binding source, hooking events /// on the new binding source and unhooking them from the previous one, if required. /// - private void WireUpBindingSource(ref BindingSource oldBindingSource, BindingSource newBindingSource) { - if (oldBindingSource != newBindingSource) { - if (oldBindingSource != null) { - oldBindingSource.PositionChanged -= new EventHandler(OnBindingSourceStateChanged); - oldBindingSource.CurrentChanged -= new EventHandler(OnBindingSourceStateChanged); + private void WireUpBindingSource(ref BindingSource oldBindingSource, BindingSource newBindingSource) + { + if (oldBindingSource != newBindingSource) + { + if (oldBindingSource != null) + { + oldBindingSource.PositionChanged -= new EventHandler(OnBindingSourceStateChanged); + oldBindingSource.CurrentChanged -= new EventHandler(OnBindingSourceStateChanged); oldBindingSource.CurrentItemChanged -= new EventHandler(OnBindingSourceStateChanged); - oldBindingSource.DataSourceChanged -= new EventHandler(OnBindingSourceStateChanged); - oldBindingSource.DataMemberChanged -= new EventHandler(OnBindingSourceStateChanged); - oldBindingSource.ListChanged -= new ListChangedEventHandler(OnBindingSourceListChanged); + oldBindingSource.DataSourceChanged -= new EventHandler(OnBindingSourceStateChanged); + oldBindingSource.DataMemberChanged -= new EventHandler(OnBindingSourceStateChanged); + oldBindingSource.ListChanged -= new ListChangedEventHandler(OnBindingSourceListChanged); } - if (newBindingSource != null) { - newBindingSource.PositionChanged += new EventHandler(OnBindingSourceStateChanged); - newBindingSource.CurrentChanged += new EventHandler(OnBindingSourceStateChanged); + if (newBindingSource != null) + { + newBindingSource.PositionChanged += new EventHandler(OnBindingSourceStateChanged); + newBindingSource.CurrentChanged += new EventHandler(OnBindingSourceStateChanged); newBindingSource.CurrentItemChanged += new EventHandler(OnBindingSourceStateChanged); - newBindingSource.DataSourceChanged += new EventHandler(OnBindingSourceStateChanged); - newBindingSource.DataMemberChanged += new EventHandler(OnBindingSourceStateChanged); - newBindingSource.ListChanged += new ListChangedEventHandler(OnBindingSourceListChanged); + newBindingSource.DataSourceChanged += new EventHandler(OnBindingSourceStateChanged); + newBindingSource.DataMemberChanged += new EventHandler(OnBindingSourceStateChanged); + newBindingSource.ListChanged += new ListChangedEventHandler(OnBindingSourceListChanged); } oldBindingSource = newBindingSource; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Border3DSide.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Border3DSide.cs index 500b79161af..f815afb12ff 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Border3DSide.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Border3DSide.cs @@ -43,6 +43,6 @@ public enum Border3DSide /// A three-dimensional border on all four edges and fill the middle of /// the rectangle with the color defeined for three-dimensional controls. /// - All = Left | Top | Right | Bottom | Middle, + All = Left | Top | Right | Bottom | Middle, } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Button.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Button.cs index 44e290b9c2f..153983228fa 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Button.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Button.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; @@ -28,7 +29,8 @@ namespace System.Windows.Forms { SRDescription(nameof(SR.DescriptionButton)), Designer("System.Windows.Forms.Design.ButtonBaseDesigner, " + AssemblyRef.SystemDesign) ] - public class Button : ButtonBase, IButtonControl { + public class Button : ButtonBase, IButtonControl + { /// /// The dialog result that will be sent to the parent dialog form when @@ -50,7 +52,8 @@ public class Button : ButtonBase, IButtonControl { /// class. /// /// - public Button() : base() { + public Button() : base() + { // Buttons shouldn't respond to right clicks, so we need to do all our own click logic SetStyle(ControlStyles.StandardClick | ControlStyles.StandardDoubleClick, @@ -67,23 +70,30 @@ public Button() : base() { Localizable(true), SRDescription(nameof(SR.ControlAutoSizeModeDescr)) ] - public AutoSizeMode AutoSizeMode { - get { + public AutoSizeMode AutoSizeMode + { + get + { return GetAutoSizeMode(); } - set { + set + { - if (!ClientUtils.IsEnumValid(value, (int)value, (int)AutoSizeMode.GrowAndShrink, (int)AutoSizeMode.GrowOnly)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)AutoSizeMode.GrowAndShrink, (int)AutoSizeMode.GrowOnly)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AutoSizeMode)); } - - if (GetAutoSizeMode() != value) { + + if (GetAutoSizeMode() != value) + { SetAutoSizeMode(value); - if(ParentInternal != null) { + 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(ParentInternal.LayoutEngine == DefaultLayout.Instance) { + if (ParentInternal.LayoutEngine == DefaultLayout.Instance) + { ParentInternal.LayoutEngine.InitLayout(this, BoundsSpecified.Size); } LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.AutoSize); @@ -92,25 +102,31 @@ public AutoSizeMode AutoSizeMode { } } - internal override ButtonBaseAdapter CreateFlatAdapter() { + internal override ButtonBaseAdapter CreateFlatAdapter() + { return new ButtonFlatAdapter(this); } - internal override ButtonBaseAdapter CreatePopupAdapter() { + internal override ButtonBaseAdapter CreatePopupAdapter() + { return new ButtonPopupAdapter(this); } - - internal override ButtonBaseAdapter CreateStandardAdapter() { + + internal override ButtonBaseAdapter CreateStandardAdapter() + { return new ButtonStandardAdapter(this); } - internal override Size GetPreferredSizeCore(Size proposedConstraints) { - if(FlatStyle != FlatStyle.System) { + internal override Size GetPreferredSizeCore(Size proposedConstraints) + { + if (FlatStyle != FlatStyle.System) + { Size prefSize = base.GetPreferredSizeCore(proposedConstraints); - return AutoSizeMode == AutoSizeMode.GrowAndShrink ? prefSize : LayoutUtils.UnionSizes(prefSize, Size); + return AutoSizeMode == AutoSizeMode.GrowAndShrink ? prefSize : LayoutUtils.UnionSizes(prefSize, Size); } - if (systemSize.Width == InvalidDimensionValue) { + if (systemSize.Width == InvalidDimensionValue) + { Size requiredSize; // Note: The result from the BCM_GETIDEALSIZE message isn't accurate if the font has been // changed, because this method is called before the font is set into the device context. @@ -124,7 +140,7 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) { requiredSize.Height += 9; systemSize = requiredSize; } - Size paddedSize = systemSize + Padding.Size; + Size paddedSize = systemSize + Padding.Size; return AutoSizeMode == AutoSizeMode.GrowAndShrink ? paddedSize : LayoutUtils.UnionSizes(paddedSize, Size); } @@ -137,16 +153,21 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) { /// /// /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; - cp.ClassName = "BUTTON"; - if (GetStyle(ControlStyles.UserPaint)) { + cp.ClassName = "BUTTON"; + if (GetStyle(ControlStyles.UserPaint)) + { cp.Style |= NativeMethods.BS_OWNERDRAW; } - else { + else + { cp.Style |= NativeMethods.BS_PUSHBUTTON; - if (IsDefault) { + if (IsDefault) + { cp.Style |= NativeMethods.BS_DEFPUSHBUTTON; } } @@ -166,13 +187,17 @@ protected override CreateParams CreateParams { DefaultValue(DialogResult.None), SRDescription(nameof(SR.ButtonDialogResultDescr)) ] - public virtual DialogResult DialogResult { - get { + public virtual DialogResult DialogResult + { + get + { return dialogResult; } - set { - if (!ClientUtils.IsEnumValid(value, (int)value, (int)DialogResult.None, (int) DialogResult.No)) { + set + { + if (!ClientUtils.IsEnumValid(value, (int)value, (int)DialogResult.None, (int)DialogResult.No)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DialogResult)); } dialogResult = value; @@ -184,7 +209,8 @@ public virtual DialogResult DialogResult { /// Raises the event. /// /// - protected override void OnMouseEnter(EventArgs e) { + protected override void OnMouseEnter(EventArgs e) + { base.OnMouseEnter(e); } @@ -193,20 +219,23 @@ protected override void OnMouseEnter(EventArgs e) { /// Raises the event. /// /// - protected override void OnMouseLeave(EventArgs e) { + protected override void OnMouseLeave(EventArgs e) + { base.OnMouseLeave(e); } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event EventHandler DoubleClick { + public new event EventHandler DoubleClick + { add => base.DoubleClick += value; remove => base.DoubleClick -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event MouseEventHandler MouseDoubleClick { + public new event MouseEventHandler MouseDoubleClick + { add => base.MouseDoubleClick += value; remove => base.MouseDoubleClick -= value; } @@ -219,9 +248,11 @@ protected override void OnMouseLeave(EventArgs e) { /// /// /// - public virtual void NotifyDefault(bool value) { - if (IsDefault != value) { - IsDefault = value; + public virtual void NotifyDefault(bool value) + { + if (IsDefault != value) + { + IsDefault = value; } } @@ -235,9 +266,11 @@ public virtual void NotifyDefault(bool value) { /// /// /// - protected override void OnClick(EventArgs e) { + protected override void OnClick(EventArgs e) + { Form form = FindForm(); - if (form != null) form.DialogResult = dialogResult; + if (form != null) + form.DialogResult = dialogResult; // accessibility stuff @@ -248,7 +281,8 @@ protected override void OnClick(EventArgs e) { base.OnClick(e); } - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { systemSize = new Size(InvalidDimensionValue, InvalidDimensionValue); base.OnFontChanged(e); } @@ -259,18 +293,24 @@ protected override void OnFontChanged(EventArgs e) { /// /// /// - protected override void OnMouseUp(MouseEventArgs mevent) { - if (mevent.Button == MouseButtons.Left && MouseIsPressed) { + protected override void OnMouseUp(MouseEventArgs mevent) + { + if (mevent.Button == MouseButtons.Left && MouseIsPressed) + { bool isMouseDown = base.MouseIsDown; - if (GetStyle(ControlStyles.UserPaint)) { + if (GetStyle(ControlStyles.UserPaint)) + { //Paint in raised state... ResetFlagsandPaint(); } - if (isMouseDown) { + if (isMouseDown) + { Point pt = PointToScreen(new Point(mevent.X, mevent.Y)); - if (UnsafeNativeMethods.WindowFromPoint(pt.X, pt.Y) == Handle && !ValidationCancelled) { - if (GetStyle(ControlStyles.UserPaint)) { + if (UnsafeNativeMethods.WindowFromPoint(pt.X, pt.Y) == Handle && !ValidationCancelled) + { + if (GetStyle(ControlStyles.UserPaint)) + { OnClick(mevent); } OnMouseClick(mevent); @@ -280,7 +320,8 @@ protected override void OnMouseUp(MouseEventArgs mevent) { base.OnMouseUp(mevent); } - protected override void OnTextChanged(EventArgs e) { + protected override void OnTextChanged(EventArgs e) + { systemSize = new Size(InvalidDimensionValue, InvalidDimensionValue); base.OnTextChanged(e); } @@ -293,10 +334,12 @@ protected override void OnTextChanged(EventArgs e) { /// /// Old DPI value /// New DPI value - protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) { + protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) + { base.RescaleConstantsForDpi(deviceDpiOld, deviceDpiNew); - if (DpiHelper.IsScalingRequirementMet) { + if (DpiHelper.IsScalingRequirementMet) + { // reset cached boundary size - it needs to be recalculated for new DPI systemSize = new Size(InvalidDimensionValue, InvalidDimensionValue); } @@ -308,8 +351,10 @@ protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNe /// button. /// /// - public void PerformClick() { - if (CanSelect) { + public void PerformClick() + { + if (CanSelect) + { bool validatedControlAllowsFocusChange; bool validate = ValidateActiveControl(out validatedControlAllowsFocusChange); if (!ValidationCancelled && (validate || validatedControlAllowsFocusChange)) @@ -331,8 +376,10 @@ public void PerformClick() { /// /// /// - protected internal override bool ProcessMnemonic(char charCode) { - if (UseMnemonic && CanProcessMnemonic() && IsMnemonic(charCode, Text)) { + protected internal override bool ProcessMnemonic(char charCode) + { + if (UseMnemonic && CanProcessMnemonic() && IsMnemonic(charCode, Text)) + { PerformClick(); return true; } @@ -345,7 +392,8 @@ protected internal override bool ProcessMnemonic(char charCode) { /// String form. /// /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); return s + ", Text: " + Text; @@ -356,14 +404,18 @@ public override string ToString() { /// to add extra functionality, but should not forget to call /// base.wndProc(m); to ensure the button continues to function properly. /// - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_COMMAND: - if (NativeMethods.Util.HIWORD(m.WParam) == NativeMethods.BN_CLICKED) { + if (NativeMethods.Util.HIWORD(m.WParam) == NativeMethods.BN_CLICKED) + { Debug.Assert(!GetStyle(ControlStyles.UserPaint), "Shouldn't get BN_CLICKED when UserPaint"); - if (!ValidationCancelled) { + if (!ValidationCancelled) + { OnClick(EventArgs.Empty); - } + } } break; case Interop.WindowMessages.WM_ERASEBKGND: diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonBase.cs index 973ff78c585..addd8222578 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonBase.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.Diagnostics; @@ -28,54 +29,56 @@ namespace System.Windows.Forms { ClassInterface(ClassInterfaceType.AutoDispatch), Designer("System.Windows.Forms.Design.ButtonBaseDesigner, " + AssemblyRef.SystemDesign) ] - public abstract class ButtonBase : Control { - - private FlatStyle flatStyle = System.Windows.Forms.FlatStyle.Standard; - private ContentAlignment imageAlign = ContentAlignment.MiddleCenter; - private ContentAlignment textAlign = ContentAlignment.MiddleCenter; - private TextImageRelation textImageRelation = TextImageRelation.Overlay; - private ImageList.Indexer imageIndex = new ImageList.Indexer(); + public abstract class ButtonBase : Control + { + + private FlatStyle flatStyle = System.Windows.Forms.FlatStyle.Standard; + private ContentAlignment imageAlign = ContentAlignment.MiddleCenter; + private ContentAlignment textAlign = ContentAlignment.MiddleCenter; + private TextImageRelation textImageRelation = TextImageRelation.Overlay; + private ImageList.Indexer imageIndex = new ImageList.Indexer(); private FlatButtonAppearance flatAppearance; private ImageList imageList; private Image image; - - private const int FlagMouseOver = 0x0001; - private const int FlagMouseDown = 0x0002; - private const int FlagMousePressed = 0x0004; - private const int FlagInButtonUp = 0x0008; - private const int FlagCurrentlyAnimating = 0x0010; - private const int FlagAutoEllipsis = 0x0020; - private const int FlagIsDefault = 0x0040; - private const int FlagUseMnemonic = 0x0080; - private const int FlagShowToolTip = 0x0100; - private int state = 0; + + private const int FlagMouseOver = 0x0001; + private const int FlagMouseDown = 0x0002; + private const int FlagMousePressed = 0x0004; + private const int FlagInButtonUp = 0x0008; + private const int FlagCurrentlyAnimating = 0x0010; + private const int FlagAutoEllipsis = 0x0020; + private const int FlagIsDefault = 0x0040; + private const int FlagUseMnemonic = 0x0080; + private const int FlagShowToolTip = 0x0100; + private int state = 0; private ToolTip textToolTip; //this allows the user to disable visual styles for the button so that it inherits its background color - private bool enableVisualStyleBackground = true; + private bool enableVisualStyleBackground = true; private bool isEnableVisualStyleBackgroundSet = false; - + /// /// /// Initializes a new instance of the class. /// /// /// - protected ButtonBase() { + protected ButtonBase() + { // If Button doesn't want double-clicks, we should introduce a StandardDoubleClick style. // Checkboxes probably want double-click's, and RadioButtons certainly do // (useful e.g. on a Wizard). - SetStyle( ControlStyles.SupportsTransparentBackColor | - ControlStyles.Opaque | + SetStyle(ControlStyles.SupportsTransparentBackColor | + ControlStyles.Opaque | ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer | ControlStyles.CacheText | // We gain about 2% in painting by avoiding extra GetWindowText calls ControlStyles.StandardClick, true); // this class overrides GetPreferredSizeCore, let Control automatically cache the result - SetState2(STATE2_USEPREFERREDSIZECACHE, true); + SetState2(STATE2_USEPREFERREDSIZECACHE, true); SetStyle(ControlStyles.UserMouse | ControlStyles.UserPaint, OwnerDraw); @@ -90,24 +93,30 @@ protected ButtonBase() { [ SRCategory(nameof(SR.CatBehavior)), DefaultValue(false), - Browsable(true), + Browsable(true), EditorBrowsable(EditorBrowsableState.Always), SRDescription(nameof(SR.ButtonAutoEllipsisDescr)) ] - public bool AutoEllipsis { - get { + public bool AutoEllipsis + { + get + { return GetFlag(FlagAutoEllipsis); } - set { - if (AutoEllipsis != value) { + set + { + if (AutoEllipsis != value) + { SetFlag(FlagAutoEllipsis, value); - if (value) { - if (textToolTip == null) { - textToolTip = new ToolTip(); + if (value) + { + if (textToolTip == null) + { + textToolTip = new ToolTip(); } } - Invalidate(); + Invalidate(); } } } @@ -117,14 +126,18 @@ public bool AutoEllipsis { /// [Browsable(true), EditorBrowsable(EditorBrowsableState.Always), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] - public override bool AutoSize { - get { + public override bool AutoSize + { + get + { return base.AutoSize; } - set { + set + { base.AutoSize = value; //don't show ellipsis if the control is autosized - if (value) { + if (value) + { AutoEllipsis = false; } } @@ -146,21 +159,28 @@ public override bool AutoSize { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ControlBackColorDescr)) ] - public override Color BackColor { - get { + public override Color BackColor + { + get + { return base.BackColor; } - set { - if (DesignMode) { - if (value != Color.Empty) { + set + { + if (DesignMode) + { + if (value != Color.Empty) + { PropertyDescriptor pd = TypeDescriptor.GetProperties(this)["UseVisualStyleBackColor"]; Debug.Assert(pd != null); - if (pd != null) { + if (pd != null) + { pd.SetValue(this, false); } } } - else { + else + { UseVisualStyleBackColor = false; } @@ -172,75 +192,96 @@ public override Color BackColor { /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(75, 23); } } - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; - if (!OwnerDraw) { + if (!OwnerDraw) + { cp.ExStyle &= ~NativeMethods.WS_EX_RIGHT; // WS_EX_RIGHT overrides the BS_XXXX alignment styles - + cp.Style |= NativeMethods.BS_MULTILINE; - - if (IsDefault) { + + if (IsDefault) + { cp.Style |= NativeMethods.BS_DEFPUSHBUTTON; } - ContentAlignment align = RtlTranslateContent(TextAlign); - - if ((int)(align & WindowsFormsUtils.AnyLeftAlign) != 0) { + ContentAlignment align = RtlTranslateContent(TextAlign); + + if ((int)(align & WindowsFormsUtils.AnyLeftAlign) != 0) + { cp.Style |= NativeMethods.BS_LEFT; } - else if ((int)(align & WindowsFormsUtils.AnyRightAlign) != 0) { + else if ((int)(align & WindowsFormsUtils.AnyRightAlign) != 0) + { cp.Style |= NativeMethods.BS_RIGHT; } - else { + else + { cp.Style |= NativeMethods.BS_CENTER; - + } - if ((int)(align & WindowsFormsUtils.AnyTopAlign) != 0) { + if ((int)(align & WindowsFormsUtils.AnyTopAlign) != 0) + { cp.Style |= NativeMethods.BS_TOP; } - else if ((int)(align & WindowsFormsUtils.AnyBottomAlign) != 0) { + else if ((int)(align & WindowsFormsUtils.AnyBottomAlign) != 0) + { cp.Style |= NativeMethods.BS_BOTTOM; } - else { + else + { cp.Style |= NativeMethods.BS_VCENTER; } } return cp; } } - - protected override ImeMode DefaultImeMode { - get { + + protected override ImeMode DefaultImeMode + { + get + { return ImeMode.Disable; } } - protected internal bool IsDefault { - get { + protected internal bool IsDefault + { + get + { return GetFlag(FlagIsDefault); } - set { - if (GetFlag(FlagIsDefault) != value) { + set + { + if (GetFlag(FlagIsDefault) != value) + { SetFlag(FlagIsDefault, value); - if (IsHandleCreated) { - if (OwnerDraw) { + if (IsHandleCreated) + { + if (OwnerDraw) + { Invalidate(); } - else { + else + { UpdateStyles(); } } } } } - + /// /// /// Gets or @@ -254,16 +295,20 @@ protected internal bool IsDefault { Localizable(true), SRDescription(nameof(SR.ButtonFlatStyleDescr)) ] - public FlatStyle FlatStyle { - get { + public FlatStyle FlatStyle + { + get + { return flatStyle; } - set { - if (!ClientUtils.IsEnumValid(value, (int)value, (int)FlatStyle.Flat, (int)FlatStyle.System)){ + set + { + if (!ClientUtils.IsEnumValid(value, (int)value, (int)FlatStyle.Flat, (int)FlatStyle.System)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(FlatStyle)); } flatStyle = value; - LayoutTransaction.DoLayoutIf(AutoSize,ParentInternal, this, PropertyNames.FlatStyle); + LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.FlatStyle); Invalidate(); UpdateOwnerDraw(); } @@ -277,9 +322,12 @@ public FlatStyle FlatStyle { SRDescription(nameof(SR.ButtonFlatAppearance)), DesignerSerializationVisibility(DesignerSerializationVisibility.Content) ] - public FlatButtonAppearance FlatAppearance { - get { - if (flatAppearance == null) { + public FlatButtonAppearance FlatAppearance + { + get + { + if (flatAppearance == null) + { flatAppearance = new FlatButtonAppearance(this); } @@ -298,9 +346,12 @@ public FlatButtonAppearance FlatAppearance { Localizable(true), SRCategory(nameof(SR.CatAppearance)) ] - public Image Image { - get { - if (image == null && imageList != null) { + public Image Image + { + get + { + if (image == null && imageList != null) + { int actualIndex = imageIndex.ActualIndex; // Pre-whidbey we used to use ImageIndex rather than ImageIndexer.ActualIndex. @@ -308,23 +359,28 @@ public Image Image { // this logic here for backwards compatibility. // We do not bake this into ImageIndexer because different controls // treat this scenario differently. - if(actualIndex >= imageList.Images.Count) { + if (actualIndex >= imageList.Images.Count) + { actualIndex = imageList.Images.Count - 1; } - if (actualIndex >= 0) { + if (actualIndex >= 0) + { return imageList.Images[actualIndex]; } Debug.Assert(image == null, "We expect to be returning null."); } return image; } - set { - if (Image != value) { + set + { + if (Image != value) + { StopAnimate(); image = value; - if (image != null) { + if (image != null) + { ImageIndex = -1; ImageList = null; } @@ -347,15 +403,20 @@ public Image Image { SRDescription(nameof(SR.ButtonImageAlignDescr)), SRCategory(nameof(SR.CatAppearance)) ] - public ContentAlignment ImageAlign { - get { + public ContentAlignment ImageAlign + { + get + { return imageAlign; } - set { - if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) { + set + { + if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ContentAlignment)); } - if(value != imageAlign) { + if (value != imageAlign) + { imageAlign = value; LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.ImageAlign); Invalidate(); @@ -378,19 +439,26 @@ public ContentAlignment ImageAlign { SRDescription(nameof(SR.ButtonImageIndexDescr)), SRCategory(nameof(SR.CatAppearance)) ] - public int ImageIndex { - get { - if (imageIndex.Index != -1 && imageList != null && imageIndex.Index >= imageList.Images.Count) { + public int ImageIndex + { + get + { + if (imageIndex.Index != -1 && imageList != null && imageIndex.Index >= imageList.Images.Count) + { return imageList.Images.Count - 1; } return imageIndex.Index; } - set { - if (value < -1) { + set + { + if (value < -1) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(ImageIndex), value, -1)); } - if (imageIndex.Index != value) { - if (value != -1) { + if (imageIndex.Index != value) + { + if (value != -1) + { // Image.set calls ImageIndex = -1 image = null; } @@ -417,13 +485,18 @@ public int ImageIndex { SRDescription(nameof(SR.ButtonImageIndexDescr)), SRCategory(nameof(SR.CatAppearance)) ] - public string ImageKey { - get { + public string ImageKey + { + get + { return imageIndex.Key; } - set { - if (imageIndex.Key != value) { - if (value != null) { + set + { + if (imageIndex.Key != value) + { + if (value != null) + { // Image.set calls ImageIndex = -1 image = null; } @@ -444,28 +517,34 @@ public string ImageKey { [ DefaultValue(null), SRDescription(nameof(SR.ButtonImageListDescr)), - RefreshProperties(RefreshProperties.Repaint), + RefreshProperties(RefreshProperties.Repaint), SRCategory(nameof(SR.CatAppearance)) ] - public ImageList ImageList { - get { + public ImageList ImageList + { + get + { return imageList; } - set { - if (imageList != value) { + set + { + if (imageList != value) + { EventHandler recreateHandler = new EventHandler(ImageListRecreateHandle); EventHandler disposedHandler = new EventHandler(DetachImageList); // Detach old event handlers // - if (imageList != null) { + if (imageList != null) + { imageList.RecreateHandle -= recreateHandler; - imageList.Disposed -= disposedHandler; + imageList.Disposed -= disposedHandler; } // Make sure we don't have an Image as well as an ImageList // - if (value != null) { + if (value != null) + { image = null; // Image.set calls ImageList = null } @@ -474,28 +553,33 @@ public ImageList ImageList { // Wire up new event handlers // - if (value != null) { + if (value != null) + { value.RecreateHandle += recreateHandler; - value.Disposed += disposedHandler; - } + value.Disposed += disposedHandler; + } Invalidate(); } } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public ImeMode ImeMode { - get { + new public ImeMode ImeMode + { + get + { return base.ImeMode; } - set { + set + { base.ImeMode = value; } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler ImeModeChanged { + public new event EventHandler ImeModeChanged + { add => base.ImeModeChanged += value; remove => base.ImeModeChanged -= value; } @@ -503,9 +587,10 @@ public ImageList ImageList { /// /// Specifies whether the control is willing to process mnemonics when hosted in an container ActiveX (Ax Sourcing). /// - internal override bool IsMnemonicsListenerAxSourced + internal override bool IsMnemonicsListenerAxSourced { - get{ + get + { return true; } } @@ -521,21 +606,27 @@ internal override bool IsMnemonicsListenerAxSourced /// ClientRectangle is safe for correct painting but may still cause flicker. /// /// - internal virtual Rectangle OverChangeRectangle { - get { - if (FlatStyle == FlatStyle.Standard) { + internal virtual Rectangle OverChangeRectangle + { + get + { + if (FlatStyle == FlatStyle.Standard) + { // this Rectangle will cause no Invalidation // can't use Rectangle.Empty because it will cause Invalidate(ClientRectangle) return new Rectangle(-1, -1, 1, 1); } - else { + else + { return ClientRectangle; } } } - - internal bool OwnerDraw { - get { + + internal bool OwnerDraw + { + get + { return FlatStyle != FlatStyle.System; } } @@ -551,43 +642,54 @@ internal bool OwnerDraw { /// ClientRectangle is safe for correct painting but may still cause flicker. /// /// - internal virtual Rectangle DownChangeRectangle { - get { + internal virtual Rectangle DownChangeRectangle + { + get + { return ClientRectangle; } } - internal bool MouseIsPressed { - get { + internal bool MouseIsPressed + { + get + { return GetFlag(FlagMousePressed); } } // a "smart" version of mouseDown for Appearance.Button CheckBoxes & RadioButtons // for these, instead of being based on the actual mouse state, it's based on the appropriate button state - internal bool MouseIsDown { - get { + internal bool MouseIsDown + { + get + { return GetFlag(FlagMouseDown); } } // a "smart" version of mouseOver for Appearance.Button CheckBoxes & RadioButtons // for these, instead of being based on the actual mouse state, it's based on the appropriate button state - internal bool MouseIsOver { - get { + internal bool MouseIsOver + { + get + { return GetFlag(FlagMouseOver); } } - + /// /// Indicates whether the tooltip should be shown /// - internal bool ShowToolTip { - get { + internal bool ShowToolTip + { + get + { return GetFlag(FlagShowToolTip); } - set { + set + { SetFlag(FlagShowToolTip, value); } } @@ -596,11 +698,14 @@ internal bool ShowToolTip { Editor("System.ComponentModel.Design.MultilineStringEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), SettingsBindable(true) ] - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; } } @@ -616,21 +721,28 @@ public override string Text { SRDescription(nameof(SR.ButtonTextAlignDescr)), SRCategory(nameof(SR.CatAppearance)) ] - public virtual ContentAlignment TextAlign { - get { + public virtual ContentAlignment TextAlign + { + get + { return textAlign; } - set { - if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) { + set + { + if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ContentAlignment)); } - if(value != textAlign) { + if (value != textAlign) + { textAlign = value; LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.TextAlign); - if (OwnerDraw) { + if (OwnerDraw) + { Invalidate(); } - else { + else + { UpdateStyles(); } } @@ -646,17 +758,17 @@ public TextImageRelation TextImageRelation get => textImageRelation; set { - if (!ClientUtils.IsEnumValid(value, (int)value, (int)TextImageRelation.Overlay, (int)TextImageRelation.TextBeforeImage,1)) + if (!ClientUtils.IsEnumValid(value, (int)value, (int)TextImageRelation.Overlay, (int)TextImageRelation.TextBeforeImage, 1)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(TextImageRelation)); } - if(value != TextImageRelation) + if (value != TextImageRelation) { textImageRelation = value; LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.TextImageRelation); Invalidate(); - } + } } } @@ -669,61 +781,78 @@ public TextImageRelation TextImageRelation DefaultValue(true), SRCategory(nameof(SR.CatAppearance)) ] - public bool UseMnemonic { - get { + public bool UseMnemonic + { + get + { return GetFlag(FlagUseMnemonic); } - - set { + + set + { SetFlag(FlagUseMnemonic, value); LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.Text); Invalidate(); } } - private void Animate() { + private void Animate() + { Animate(!DesignMode && Visible && Enabled && ParentInternal != null); } - private void StopAnimate() { + private void StopAnimate() + { Animate(false); } - private void Animate(bool animate) { - if (animate != GetFlag(FlagCurrentlyAnimating)) { - if (animate) { - if (this.image != null) { + private void Animate(bool animate) + { + if (animate != GetFlag(FlagCurrentlyAnimating)) + { + if (animate) + { + if (this.image != null) + { ImageAnimator.Animate(this.image, new EventHandler(this.OnFrameChanged)); SetFlag(FlagCurrentlyAnimating, animate); } } - else { - if (this.image != null) { + else + { + if (this.image != null) + { ImageAnimator.StopAnimate(this.image, new EventHandler(this.OnFrameChanged)); SetFlag(FlagCurrentlyAnimating, animate); } } } } - - protected override AccessibleObject CreateAccessibilityInstance() { + + protected override AccessibleObject CreateAccessibilityInstance() + { return new ButtonBaseAccessibleObject(this); } - private void DetachImageList(object sender, EventArgs e) { + private void DetachImageList(object sender, EventArgs e) + { ImageList = null; } /// /// - protected override void Dispose(bool disposing) { - if (disposing) { + protected override void Dispose(bool disposing) + { + if (disposing) + { StopAnimate(); - if (imageList != null) { + if (imageList != null) + { imageList.Disposed -= new EventHandler(this.DetachImageList); } //Dipose the tooltip if one present.. - if (textToolTip != null) { + if (textToolTip != null) + { textToolTip.Dispose(); textToolTip = null; } @@ -731,22 +860,26 @@ protected override void Dispose(bool disposing) { base.Dispose(disposing); } - private bool GetFlag(int flag) { + private bool GetFlag(int flag) + { return ((state & flag) == flag); } - private void ImageListRecreateHandle(object sender, EventArgs e) { - if (IsHandleCreated) { + private void ImageListRecreateHandle(object sender, EventArgs e) + { + if (IsHandleCreated) + { Invalidate(); } } - + /// /// /// Raises the event. /// /// - protected override void OnGotFocus(EventArgs e) { + protected override void OnGotFocus(EventArgs e) + { base.OnGotFocus(e); Invalidate(); } @@ -756,7 +889,8 @@ protected override void OnGotFocus(EventArgs e) { /// Raises the event. /// /// - protected override void OnLostFocus(EventArgs e) { + protected override void OnLostFocus(EventArgs e) + { base.OnLostFocus(e); // Hitting tab while holding down the space key. @@ -771,11 +905,13 @@ protected override void OnLostFocus(EventArgs e) { /// Raises the event. /// /// - protected override void OnMouseEnter(EventArgs eventargs) { + protected override void OnMouseEnter(EventArgs eventargs) + { Debug.Assert(Enabled, "ButtonBase.OnMouseEnter should not be called if the button is disabled"); SetFlag(FlagMouseOver, true); Invalidate(); - if (!DesignMode && AutoEllipsis && ShowToolTip && textToolTip != null) { + if (!DesignMode && AutoEllipsis && ShowToolTip && textToolTip != null) + { textToolTip.Show(WindowsFormsUtils.TextWithoutMnemonics(Text), this); } // call base last, so if it invokes any listeners that disable the button, we @@ -788,9 +924,11 @@ protected override void OnMouseEnter(EventArgs eventargs) { /// Raises the event. /// /// - protected override void OnMouseLeave(EventArgs eventargs) { - SetFlag(FlagMouseOver, false); - if (textToolTip != null) { + protected override void OnMouseLeave(EventArgs eventargs) + { + SetFlag(FlagMouseOver, false); + if (textToolTip != null) + { textToolTip.Hide(this); } Invalidate(); @@ -804,18 +942,24 @@ protected override void OnMouseLeave(EventArgs eventargs) { /// Raises the event. /// /// - protected override void OnMouseMove(MouseEventArgs mevent) { + protected override void OnMouseMove(MouseEventArgs mevent) + { Debug.Assert(Enabled, "ButtonBase.OnMouseMove should not be called if the button is disabled"); - if (mevent.Button != MouseButtons.None && GetFlag(FlagMousePressed)) { + if (mevent.Button != MouseButtons.None && GetFlag(FlagMousePressed)) + { Rectangle r = ClientRectangle; - if (!r.Contains(mevent.X, mevent.Y)) { - if (GetFlag(FlagMouseDown)) { + if (!r.Contains(mevent.X, mevent.Y)) + { + if (GetFlag(FlagMouseDown)) + { SetFlag(FlagMouseDown, false); Invalidate(DownChangeRectangle); } } - else { - if (!GetFlag(FlagMouseDown)) { + else + { + if (!GetFlag(FlagMouseDown)) + { SetFlag(FlagMouseDown, true); Invalidate(DownChangeRectangle); } @@ -831,9 +975,11 @@ protected override void OnMouseMove(MouseEventArgs mevent) { /// Raises the event. /// /// - protected override void OnMouseDown(MouseEventArgs mevent) { + protected override void OnMouseDown(MouseEventArgs mevent) + { Debug.Assert(Enabled, "ButtonBase.OnMouseDown should not be called if the button is disabled"); - if (mevent.Button == MouseButtons.Left) { + if (mevent.Button == MouseButtons.Left) + { SetFlag(FlagMouseDown, true); SetFlag(FlagMousePressed, true); Invalidate(DownChangeRectangle); @@ -849,7 +995,8 @@ protected override void OnMouseDown(MouseEventArgs mevent) { /// /// /// - protected override void OnMouseUp(MouseEventArgs mevent) { + protected override void OnMouseUp(MouseEventArgs mevent) + { base.OnMouseUp(mevent); } @@ -858,7 +1005,8 @@ protected override void OnMouseUp(MouseEventArgs mevent) { /// Used for quick re-painting of the button after the pressed state. /// /// - protected void ResetFlagsandPaint() { + protected void ResetFlagsandPaint() + { SetFlag(FlagMousePressed, false); SetFlag(FlagMouseDown, false); Invalidate(DownChangeRectangle); @@ -868,37 +1016,46 @@ protected void ResetFlagsandPaint() { /// /// Central paint dispatcher to one of the three styles of painting. /// - private void PaintControl(PaintEventArgs pevent) { + private void PaintControl(PaintEventArgs pevent) + { Debug.Assert(GetStyle(ControlStyles.UserPaint), "Shouldn't be in PaintControl when control is not UserPaint style"); Adapter.Paint(pevent); } - public override Size GetPreferredSize( Size proposedSize ) { + public override Size GetPreferredSize(Size proposedSize) + { // TableLayoutPanel passes width = 1 to get the minimum autosize width, since Buttons word-break text // that width would be the size of the widest caracter in the text. We need to make the proposed size // unbounded. // This is the same as what Label does. - if( proposedSize.Width == 1 ) { + if (proposedSize.Width == 1) + { proposedSize.Width = 0; } - if( proposedSize.Height == 1 ) { + if (proposedSize.Height == 1) + { proposedSize.Height = 0; } - return base.GetPreferredSize( proposedSize ); + return base.GetPreferredSize(proposedSize); } - internal override Size GetPreferredSizeCore(Size proposedConstraints) { + internal override Size GetPreferredSizeCore(Size proposedConstraints) + { Size prefSize = Adapter.GetPreferredSizeCore(proposedConstraints); return LayoutUtils.UnionSizes(prefSize + Padding.Size, MinimumSize); } - private ButtonBaseAdapter _adapter = null; - private FlatStyle _cachedAdapterType; + private ButtonBaseAdapter _adapter = null; + private FlatStyle _cachedAdapterType; - internal ButtonBaseAdapter Adapter { - get { - if(_adapter == null || FlatStyle != _cachedAdapterType) { - switch (FlatStyle) { + internal ButtonBaseAdapter Adapter + { + get + { + if (_adapter == null || FlatStyle != _cachedAdapterType) + { + switch (FlatStyle) + { case FlatStyle.Standard: _adapter = CreateStandardAdapter(); break; @@ -906,7 +1063,8 @@ internal ButtonBaseAdapter Adapter { _adapter = CreatePopupAdapter(); break; case FlatStyle.Flat: - _adapter = CreateFlatAdapter();; + _adapter = CreateFlatAdapter(); + ; break; default: Debug.Fail("Unsupported FlatStyle: '" + FlatStyle + '"'); @@ -918,53 +1076,65 @@ internal ButtonBaseAdapter Adapter { } } - internal virtual ButtonBaseAdapter CreateFlatAdapter() { + internal virtual ButtonBaseAdapter CreateFlatAdapter() + { Debug.Fail("Derived classes need to provide a meaningful implementation."); return null; } - internal virtual ButtonBaseAdapter CreatePopupAdapter() { + internal virtual ButtonBaseAdapter CreatePopupAdapter() + { Debug.Fail("Derived classes need to provide a meaningful implementation."); return null; } - - internal virtual ButtonBaseAdapter CreateStandardAdapter() { + + internal virtual ButtonBaseAdapter CreateStandardAdapter() + { Debug.Fail("Derived classes need to provide a meaningful implementation."); return null; } - - internal virtual StringFormat CreateStringFormat() { - if( Adapter == null ) { + + internal virtual StringFormat CreateStringFormat() + { + if (Adapter == null) + { Debug.Fail("Adapter not expected to be null at this point"); return new StringFormat(); } return Adapter.CreateStringFormat(); } - internal virtual TextFormatFlags CreateTextFormatFlags() { - if( Adapter == null ) { - Debug.Fail( "Adapter not expected to be null at this point" ); + internal virtual TextFormatFlags CreateTextFormatFlags() + { + if (Adapter == null) + { + Debug.Fail("Adapter not expected to be null at this point"); return TextFormatFlags.Default; } return Adapter.CreateTextFormatFlags(); } - private void OnFrameChanged(object o, EventArgs e) { - if (Disposing || IsDisposed) { + private void OnFrameChanged(object o, EventArgs e) + { + if (Disposing || IsDisposed) + { return; } - if (IsHandleCreated && InvokeRequired) { - BeginInvoke(new EventHandler(this.OnFrameChanged), new object[]{o,e}); + if (IsHandleCreated && InvokeRequired) + { + BeginInvoke(new EventHandler(this.OnFrameChanged), new object[] { o, e }); return; } Invalidate(); } - protected override void OnEnabledChanged(EventArgs e) { + protected override void OnEnabledChanged(EventArgs e) + { base.OnEnabledChanged(e); Animate(); - if (!Enabled) { + if (!Enabled) + { // disabled button is always "up" SetFlag(FlagMouseDown, false); SetFlag(FlagMouseOver, false); @@ -972,8 +1142,10 @@ protected override void OnEnabledChanged(EventArgs e) { } } - protected override void OnTextChanged(EventArgs e) { - using(LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.Text)) { + protected override void OnTextChanged(EventArgs e) + { + using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.Text)) + { base.OnTextChanged(e); Invalidate(); } @@ -985,16 +1157,20 @@ protected override void OnTextChanged(EventArgs e) { /// /// /// - protected override void OnKeyDown(KeyEventArgs kevent) { + protected override void OnKeyDown(KeyEventArgs kevent) + { Debug.Assert(Enabled, "ButtonBase.OnKeyDown should not be called if the button is disabled"); - if (kevent.KeyData == Keys.Space) { - if (!GetFlag(FlagMouseDown)) { + if (kevent.KeyData == Keys.Space) + { + if (!GetFlag(FlagMouseDown)) + { SetFlag(FlagMouseDown, true); // It looks like none of the "SPACE" key downs generate the BM_SETSTATE. // This causes to not draw the focus rectangle inside the button and also // not paint the button as "un-depressed". // - if(!OwnerDraw) { + if (!OwnerDraw) + { SendMessage(NativeMethods.BM_SETSTATE, 1, 0); } Invalidate(DownChangeRectangle); @@ -1012,19 +1188,24 @@ protected override void OnKeyDown(KeyEventArgs kevent) { /// /// /// - protected override void OnKeyUp(KeyEventArgs kevent) { - if (GetFlag(FlagMouseDown) && !ValidationCancelled) { - if (OwnerDraw) { + protected override void OnKeyUp(KeyEventArgs kevent) + { + if (GetFlag(FlagMouseDown) && !ValidationCancelled) + { + if (OwnerDraw) + { ResetFlagsandPaint(); } - else { + else + { SetFlag(FlagMousePressed, false); SetFlag(FlagMouseDown, false); SendMessage(NativeMethods.BM_SETSTATE, 0, 0); } // Breaking change: specifically filter out Keys.Enter and Keys.Space as the only // two keystrokes to execute OnClick. - if (kevent.KeyCode == Keys.Enter || kevent.KeyCode == Keys.Space) { + if (kevent.KeyCode == Keys.Enter || kevent.KeyCode == Keys.Space) + { OnClick(EventArgs.Empty); } kevent.Handled = true; @@ -1032,7 +1213,7 @@ protected override void OnKeyUp(KeyEventArgs kevent) { // call base last, so if it invokes any listeners that disable the button, we // don't have to recheck base.OnKeyUp(kevent); - + } /// @@ -1041,16 +1222,20 @@ protected override void OnKeyUp(KeyEventArgs kevent) { /// /// /// - protected override void OnPaint(PaintEventArgs pevent) { - if( AutoEllipsis ){ + protected override void OnPaint(PaintEventArgs pevent) + { + if (AutoEllipsis) + { Size preferredSize = PreferredSize; ShowToolTip = (this.ClientRectangle.Width < preferredSize.Width || this.ClientRectangle.Height < preferredSize.Height); } - else { + else + { ShowToolTip = false; } - if (GetStyle(ControlStyles.UserPaint)) { + if (GetStyle(ControlStyles.UserPaint)) + { Animate(); ImageAnimator.UpdateFrames(this.Image); @@ -1059,41 +1244,51 @@ protected override void OnPaint(PaintEventArgs pevent) { base.OnPaint(pevent); } - protected override void OnParentChanged(EventArgs e) { + protected override void OnParentChanged(EventArgs e) + { base.OnParentChanged(e); Animate(); } - protected override void OnVisibleChanged(EventArgs e) { + protected override void OnVisibleChanged(EventArgs e) + { base.OnVisibleChanged(e); Animate(); } - private void ResetImage() { + private void ResetImage() + { Image = null; } - private void SetFlag(int flag, bool value) { + private void SetFlag(int flag, bool value) + { bool oldValue = ((state & flag) != 0); - if (value) { + if (value) + { state |= flag; } - else { + else + { state &= ~flag; } - if (OwnerDraw && (flag & FlagMouseDown) != 0 && value != oldValue) { + if (OwnerDraw && (flag & FlagMouseDown) != 0 && value != oldValue) + { AccessibilityNotifyClients(AccessibleEvents.StateChange, -1); } } - - private bool ShouldSerializeImage() { + + private bool ShouldSerializeImage() + { return image != null; } - - private void UpdateOwnerDraw() { - if (OwnerDraw != GetStyle(ControlStyles.UserPaint)) { + + private void UpdateOwnerDraw() + { + if (OwnerDraw != GetStyle(ControlStyles.UserPaint)) + { SetStyle(ControlStyles.UserMouse | ControlStyles.UserPaint, OwnerDraw); RecreateHandle(); } @@ -1107,11 +1302,14 @@ private void UpdateOwnerDraw() { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.UseCompatibleTextRenderingDescr)) ] - public bool UseCompatibleTextRendering { - get{ + public bool UseCompatibleTextRendering + { + get + { return base.UseCompatibleTextRenderingInt; } - set{ + set + { base.UseCompatibleTextRenderingInt = value; } } @@ -1121,8 +1319,10 @@ public bool UseCompatibleTextRendering { /// This is provided for container controls to iterate through its children to set UseCompatibleTextRendering to the same /// value if the child control supports it. /// - internal override bool SupportsUseCompatibleTextRendering { - get { + internal override bool SupportsUseCompatibleTextRendering + { + get + { return true; } } @@ -1131,55 +1331,66 @@ internal override bool SupportsUseCompatibleTextRendering { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ButtonUseVisualStyleBackColorDescr)) ] - public bool UseVisualStyleBackColor { - get { + public bool UseVisualStyleBackColor + { + get + { if (isEnableVisualStyleBackgroundSet || ((RawBackColor.IsEmpty) && (BackColor == SystemColors.Control))) { - return enableVisualStyleBackground; + return enableVisualStyleBackground; } else { - return false; + return false; } - } - set { - isEnableVisualStyleBackgroundSet = true; + } + set + { + isEnableVisualStyleBackgroundSet = true; enableVisualStyleBackground = value; this.Invalidate(); } } - private void ResetUseVisualStyleBackColor() { + private void ResetUseVisualStyleBackColor() + { isEnableVisualStyleBackgroundSet = false; enableVisualStyleBackground = true; this.Invalidate(); } - private bool ShouldSerializeUseVisualStyleBackColor() { + private bool ShouldSerializeUseVisualStyleBackColor() + { return isEnableVisualStyleBackgroundSet; } - - - protected override void WndProc(ref Message m) { - switch (m.Msg) { + + protected override void WndProc(ref Message m) + { + + switch (m.Msg) + { // we don't respect this because the code below eats BM_SETSTATE. // so we just invoke the click. // case NativeMethods.BM_CLICK: - if (this is IButtonControl) { + if (this is IButtonControl) + { ((IButtonControl)this).PerformClick(); } - else { + else + { OnClick(EventArgs.Empty); } return; } - if (OwnerDraw) { - switch (m.Msg) { + if (OwnerDraw) + { + switch (m.Msg) + { case NativeMethods.BM_SETSTATE: // Ignore BM_SETSTATE -- Windows gets confused and paints // things, even though we are ownerdraw. @@ -1188,10 +1399,12 @@ protected override void WndProc(ref Message m) { case Interop.WindowMessages.WM_KILLFOCUS: case Interop.WindowMessages.WM_CANCELMODE: case Interop.WindowMessages.WM_CAPTURECHANGED: - if (!GetFlag(FlagInButtonUp) && GetFlag(FlagMousePressed)) { + if (!GetFlag(FlagInButtonUp) && GetFlag(FlagMousePressed)) + { SetFlag(FlagMousePressed, false); - if (GetFlag(FlagMouseDown)) { + if (GetFlag(FlagMouseDown)) + { SetFlag(FlagMouseDown, false); Invalidate(DownChangeRectangle); } @@ -1202,11 +1415,13 @@ protected override void WndProc(ref Message m) { case Interop.WindowMessages.WM_LBUTTONUP: case Interop.WindowMessages.WM_MBUTTONUP: case Interop.WindowMessages.WM_RBUTTONUP: - try { + try + { SetFlag(FlagInButtonUp, true); base.WndProc(ref m); } - finally { + finally + { SetFlag(FlagInButtonUp, false); } break; @@ -1216,10 +1431,13 @@ protected override void WndProc(ref Message m) { break; } } - else { - switch (m.Msg) { + else + { + switch (m.Msg) + { case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_COMMAND: - if (NativeMethods.Util.HIWORD(m.WParam) == NativeMethods.BN_CLICKED && !ValidationCancelled) { + if (NativeMethods.Util.HIWORD(m.WParam) == NativeMethods.BN_CLICKED && !ValidationCancelled) + { OnClick(EventArgs.Empty); } break; @@ -1229,29 +1447,35 @@ protected override void WndProc(ref Message m) { } } } - - [System.Runtime.InteropServices.ComVisible(true)] - public class ButtonBaseAccessibleObject : ControlAccessibleObject { - - public ButtonBaseAccessibleObject(Control owner) : base(owner) { + + [System.Runtime.InteropServices.ComVisible(true)] + public class ButtonBaseAccessibleObject : ControlAccessibleObject + { + + public ButtonBaseAccessibleObject(Control owner) : base(owner) + { } - public override void DoDefaultAction() { + public override void DoDefaultAction() + { ((ButtonBase)Owner).OnClick(EventArgs.Empty); } - - public override AccessibleStates State { - get { + + public override AccessibleStates State + { + get + { AccessibleStates state = base.State; - ButtonBase owner = (ButtonBase) Owner; - if (owner.OwnerDraw && owner.MouseIsDown) { + ButtonBase owner = (ButtonBase)Owner; + if (owner.OwnerDraw && owner.MouseIsDown) + { state |= AccessibleStates.Pressed; } return state; } - } + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonBaseAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonBaseAdapter.cs index c2231e660c1..119b6923805 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonBaseAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonBaseAdapter.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ButtonInternal { +namespace System.Windows.Forms.ButtonInternal +{ using System; using System.Collections.Specialized; using System.Diagnostics; @@ -23,40 +24,50 @@ namespace System.Windows.Forms.ButtonInternal { /// it's used for things that derive from ButtonBase, /// parts of ToolStripItem, and parts of the DataGridView. /// - internal abstract class ButtonBaseAdapter { + internal abstract class ButtonBaseAdapter + { private ButtonBase control; // SystemInformation.Border3DSize + 2 pixels for focus rect protected static int buttonBorderSize = 4; - internal ButtonBaseAdapter(ButtonBase control) { + internal ButtonBaseAdapter(ButtonBase control) + { this.control = control; } - protected ButtonBase Control { + protected ButtonBase Control + { get { return this.control; } } - internal void Paint(PaintEventArgs pevent) { - if (Control.MouseIsDown) { + internal void Paint(PaintEventArgs pevent) + { + if (Control.MouseIsDown) + { PaintDown(pevent, CheckState.Unchecked); } - else if (Control.MouseIsOver) { + else if (Control.MouseIsOver) + { PaintOver(pevent, CheckState.Unchecked); } - else { - PaintUp(pevent, CheckState.Unchecked); + else + { + PaintUp(pevent, CheckState.Unchecked); } } - internal virtual Size GetPreferredSizeCore(Size proposedSize) { + internal virtual Size GetPreferredSizeCore(Size proposedSize) + { // this is a shared cached graphics, therefore it does not require dispose. - using (Graphics measurementGraphics = WindowsFormsUtils.CreateMeasurementGraphics()) { - using (PaintEventArgs pe = new PaintEventArgs(measurementGraphics, new Rectangle())) { + using (Graphics measurementGraphics = WindowsFormsUtils.CreateMeasurementGraphics()) + { + using (PaintEventArgs pe = new PaintEventArgs(measurementGraphics, new Rectangle())) + { LayoutOptions options = Layout(pe); return options.GetPreferredSizeCore(proposedSize); } - } + } } protected abstract LayoutOptions Layout(PaintEventArgs e); @@ -70,16 +81,18 @@ internal virtual Size GetPreferredSizeCore(Size proposedSize) { #region Accessibility Helpers [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected bool IsHighContrastHighlighted() { + protected bool IsHighContrastHighlighted() + { return SystemInformation.HighContrast && Application.RenderWithVisualStyles && (Control.Focused || Control.MouseIsOver || (Control.IsDefault && Control.Enabled)); } -#endregion + #endregion #region Drawing Helpers - internal static Color MixedColor(Color color1, Color color2) { + internal static Color MixedColor(Color color1, Color color2) + { byte a1 = color1.A; byte r1 = color1.R; byte g1 = color1.G; @@ -97,13 +110,15 @@ internal static Color MixedColor(Color color1, Color color2) { return Color.FromArgb(a3, r3, g3, b3); } - - internal static Brush CreateDitherBrush(Color color1, Color color2) { + + internal static Brush CreateDitherBrush(Color color1, Color color2) + { // Note: Don't dispose the bitmap here. The texture brush will take ownership // of the bitmap. So the bitmap will get disposed by the brush's Dispose(). - using (Bitmap b = new Bitmap(2, 2)) { + using (Bitmap b = new Bitmap(2, 2)) + { b.SetPixel(0, 0, color1); b.SetPixel(0, 1, color2); b.SetPixel(1, 1, color1); @@ -116,166 +131,203 @@ internal static Brush CreateDitherBrush(Color color1, Color color2) { /// /// Get StringFormat object for rendering text using GDI+ (Graphics). /// - internal virtual StringFormat CreateStringFormat() { - return ControlPaint.CreateStringFormat( Control, Control.TextAlign, Control.ShowToolTip, Control.UseMnemonic ); + internal virtual StringFormat CreateStringFormat() + { + return ControlPaint.CreateStringFormat(Control, Control.TextAlign, Control.ShowToolTip, Control.UseMnemonic); } /// /// Get TextFormatFlags flags for rendering text using GDI (TextRenderer). /// - internal virtual TextFormatFlags CreateTextFormatFlags(){ - return ControlPaint.CreateTextFormatFlags( Control, Control.TextAlign, Control.ShowToolTip, Control.UseMnemonic ); + internal virtual TextFormatFlags CreateTextFormatFlags() + { + return ControlPaint.CreateTextFormatFlags(Control, Control.TextAlign, Control.ShowToolTip, Control.UseMnemonic); } - internal static void DrawDitheredFill(Graphics g, Color color1, Color color2, Rectangle bounds) { - using (Brush brush = CreateDitherBrush(color1, color2)) { + internal static void DrawDitheredFill(Graphics g, Color color1, Color color2, Rectangle bounds) + { + using (Brush brush = CreateDitherBrush(color1, color2)) + { g.FillRectangle(brush, bounds); } } - protected void Draw3DBorder(Graphics g, Rectangle bounds, ColorData colors, bool raised) { - if (Control.BackColor != SystemColors.Control && SystemInformation.HighContrast) { - if (raised) { + protected void Draw3DBorder(Graphics g, Rectangle bounds, ColorData colors, bool raised) + { + if (Control.BackColor != SystemColors.Control && SystemInformation.HighContrast) + { + if (raised) + { Draw3DBorderHighContrastRaised(g, ref bounds, colors); } - else { + else + { ControlPaint.DrawBorder(g, bounds, ControlPaint.Dark(Control.BackColor), ButtonBorderStyle.Solid); } } - else { - if (raised) { + else + { + if (raised) + { Draw3DBorderRaised(g, ref bounds, colors); } - else { + else + { Draw3DBorderNormal(g, ref bounds, colors); } } } - - private void Draw3DBorderHighContrastRaised(Graphics g, ref Rectangle bounds, ColorData colors) { + + private void Draw3DBorderHighContrastRaised(Graphics g, ref Rectangle bounds, ColorData colors) + { bool stockColor = colors.buttonFace.ToKnownColor() == SystemColors.Control.ToKnownColor(); bool disabledHighContrast = (!Control.Enabled) && SystemInformation.HighContrast; - using ( WindowsGraphics wg = WindowsGraphics.FromGraphics(g) ) { - + using (WindowsGraphics wg = WindowsGraphics.FromGraphics(g)) + { + // Draw counter-clock-wise. - Point p1 = new Point(bounds.X + bounds.Width - 1, bounds.Y ); // upper inner right. - Point p2 = new Point(bounds.X , bounds.Y ); // upper left. - Point p3 = new Point(bounds.X , bounds.Y + bounds.Height - 1 ); // bottom inner left. - Point p4 = new Point(bounds.X + bounds.Width - 1, bounds.Y + bounds.Height - 1 ); // inner bottom right. + Point p1 = new Point(bounds.X + bounds.Width - 1, bounds.Y); // upper inner right. + Point p2 = new Point(bounds.X, bounds.Y); // upper left. + Point p3 = new Point(bounds.X, bounds.Y + bounds.Height - 1); // bottom inner left. + Point p4 = new Point(bounds.X + bounds.Width - 1, bounds.Y + bounds.Height - 1); // inner bottom right. WindowsPen penTopLeft = null; WindowsPen penBottomRight = null; WindowsPen insetPen = null; WindowsPen bottomRightInsetPen = null; - try { + try + { // top + left - if (disabledHighContrast) { + if (disabledHighContrast) + { penTopLeft = new WindowsPen(wg.DeviceContext, colors.windowDisabled); } - else { + else + { penTopLeft = stockColor ? new WindowsPen(wg.DeviceContext, SystemColors.ControlLightLight) : new WindowsPen(wg.DeviceContext, colors.highlight); } wg.DrawLine(penTopLeft, p1, p2); // top (right-left) wg.DrawLine(penTopLeft, p2, p3); // left (up-down) // bottom + right - if (disabledHighContrast) { + if (disabledHighContrast) + { penBottomRight = new WindowsPen(wg.DeviceContext, colors.windowDisabled); } - else { + else + { penBottomRight = stockColor ? new WindowsPen(wg.DeviceContext, SystemColors.ControlDarkDark) : new WindowsPen(wg.DeviceContext, colors.buttonShadowDark); } - p1.Offset(0,-1); // need to paint last pixel too. + p1.Offset(0, -1); // need to paint last pixel too. wg.DrawLine(penBottomRight, p3, p4); // bottom (left-right) wg.DrawLine(penBottomRight, p4, p1); // right (bottom-up ) // Draw inset using the background color to make the top and left lines thinner - if (stockColor) { - if (SystemInformation.HighContrast) { + if (stockColor) + { + if (SystemInformation.HighContrast) + { insetPen = new WindowsPen(wg.DeviceContext, SystemColors.ControlLight); } - else { + else + { insetPen = new WindowsPen(wg.DeviceContext, SystemColors.Control); } } - else { - if (SystemInformation.HighContrast) { + else + { + if (SystemInformation.HighContrast) + { insetPen = new WindowsPen(wg.DeviceContext, colors.highlight); } - else { + else + { insetPen = new WindowsPen(wg.DeviceContext, colors.buttonFace); } } - p1.Offset(-1, 2); - p2.Offset( 1, 1); - p3.Offset( 1,-1); - p4.Offset(-1,-1); + p1.Offset(-1, 2); + p2.Offset(1, 1); + p3.Offset(1, -1); + p4.Offset(-1, -1); // top + left inset wg.DrawLine(insetPen, p1, p2); // top (right-left) wg.DrawLine(insetPen, p2, p3); // left( up-down) - + // Bottom + right inset - if (disabledHighContrast) { + if (disabledHighContrast) + { bottomRightInsetPen = new WindowsPen(wg.DeviceContext, colors.windowDisabled); } - else { + else + { bottomRightInsetPen = stockColor ? new WindowsPen(wg.DeviceContext, SystemColors.ControlDark) : new WindowsPen(wg.DeviceContext, colors.buttonShadow); } - p1.Offset(0,-1); // need to paint last pixel too. + p1.Offset(0, -1); // need to paint last pixel too. wg.DrawLine(bottomRightInsetPen, p3, p4); // bottom (left-right) wg.DrawLine(bottomRightInsetPen, p4, p1); // right (bottom-up) } - finally { - if (penTopLeft != null) { + finally + { + if (penTopLeft != null) + { penTopLeft.Dispose(); } - if (penBottomRight != null) { + if (penBottomRight != null) + { penBottomRight.Dispose(); } - if (insetPen != null) { + if (insetPen != null) + { insetPen.Dispose(); } - if (bottomRightInsetPen != null) { + if (bottomRightInsetPen != null) + { bottomRightInsetPen.Dispose(); } } } } - - private void Draw3DBorderNormal(Graphics g, ref Rectangle bounds, ColorData colors) { - using( WindowsGraphics wg = WindowsGraphics.FromGraphics(g) ) { + + private void Draw3DBorderNormal(Graphics g, ref Rectangle bounds, ColorData colors) + { + using (WindowsGraphics wg = WindowsGraphics.FromGraphics(g)) + { // Draw counter-clock-wise. - Point p1 = new Point(bounds.X + bounds.Width - 1, bounds.Y ); // upper inner right. - Point p2 = new Point(bounds.X , bounds.Y ); // upper left. - Point p3 = new Point(bounds.X , bounds.Y + bounds.Height - 1 ); // bottom inner left. - Point p4 = new Point(bounds.X + bounds.Width - 1, bounds.Y + bounds.Height - 1 ); // inner bottom right. + Point p1 = new Point(bounds.X + bounds.Width - 1, bounds.Y); // upper inner right. + Point p2 = new Point(bounds.X, bounds.Y); // upper left. + Point p3 = new Point(bounds.X, bounds.Y + bounds.Height - 1); // bottom inner left. + Point p4 = new Point(bounds.X + bounds.Width - 1, bounds.Y + bounds.Height - 1); // inner bottom right. // top + left WindowsPen pen = new WindowsPen(wg.DeviceContext, colors.buttonShadowDark); - try { + try + { wg.DrawLine(pen, p1, p2); // top (right-left) wg.DrawLine(pen, p2, p3); // left(up-down) } - finally { - pen.Dispose(); + finally + { + pen.Dispose(); } - + // bottom + right pen = new WindowsPen(wg.DeviceContext, colors.highlight); - try { - p1.Offset(0,-1); // need to paint last pixel too. + try + { + p1.Offset(0, -1); // need to paint last pixel too. wg.DrawLine(pen, p3, p4); // bottom(left-right) wg.DrawLine(pen, p4, p1); // right (bottom-up) } - finally { + finally + { pen.Dispose(); } @@ -283,90 +335,108 @@ private void Draw3DBorderNormal(Graphics g, ref Rectangle bounds, ColorData colo pen = new WindowsPen(wg.DeviceContext, colors.buttonFace); - p1.Offset(-1, 2); - p2.Offset( 1, 1); - p3.Offset( 1,-1); - p4.Offset(-1,-1); + p1.Offset(-1, 2); + p2.Offset(1, 1); + p3.Offset(1, -1); + p4.Offset(-1, -1); // top + left inset - try { + try + { wg.DrawLine(pen, p1, p2); // top (right-left) wg.DrawLine(pen, p2, p3); // left(up-down) } - finally { - pen.Dispose(); + finally + { + pen.Dispose(); } // bottom + right inset - if (colors.buttonFace.ToKnownColor() == SystemColors.Control.ToKnownColor()) { + if (colors.buttonFace.ToKnownColor() == SystemColors.Control.ToKnownColor()) + { pen = new WindowsPen(wg.DeviceContext, SystemColors.ControlLight); } - else { + else + { pen = new WindowsPen(wg.DeviceContext, colors.buttonFace); } - try { - p1.Offset(0,-1); // need to paint last pixel too. + try + { + p1.Offset(0, -1); // need to paint last pixel too. wg.DrawLine(pen, p3, p4); // bottom(left-right) wg.DrawLine(pen, p4, p1); // right (bottom-up) } - finally { + finally + { pen.Dispose(); } } } - - private void Draw3DBorderRaised(Graphics g, ref Rectangle bounds, ColorData colors) { + + private void Draw3DBorderRaised(Graphics g, ref Rectangle bounds, ColorData colors) + { bool stockColor = colors.buttonFace.ToKnownColor() == SystemColors.Control.ToKnownColor(); bool disabledHighContrast = (!Control.Enabled) && SystemInformation.HighContrast; - using( WindowsGraphics wg = WindowsGraphics.FromGraphics(g) ) { + using (WindowsGraphics wg = WindowsGraphics.FromGraphics(g)) + { // Draw counter-clock-wise. - Point p1 = new Point(bounds.X + bounds.Width - 1, bounds.Y ); // upper inner right. - Point p2 = new Point(bounds.X , bounds.Y ); // upper left. - Point p3 = new Point(bounds.X , bounds.Y + bounds.Height - 1 ); // bottom inner left. - Point p4 = new Point(bounds.X + bounds.Width - 1, bounds.Y + bounds.Height - 1 ); // inner bottom right. + Point p1 = new Point(bounds.X + bounds.Width - 1, bounds.Y); // upper inner right. + Point p2 = new Point(bounds.X, bounds.Y); // upper left. + Point p3 = new Point(bounds.X, bounds.Y + bounds.Height - 1); // bottom inner left. + Point p4 = new Point(bounds.X + bounds.Width - 1, bounds.Y + bounds.Height - 1); // inner bottom right. // Draw counter-clock-wise. // top + left WindowsPen pen; - if (disabledHighContrast) { + if (disabledHighContrast) + { pen = new WindowsPen(wg.DeviceContext, colors.windowDisabled); } - else if (stockColor) { + else if (stockColor) + { pen = new WindowsPen(wg.DeviceContext, SystemColors.ControlLightLight); } - else { + else + { pen = new WindowsPen(wg.DeviceContext, colors.highlight); } - try { + try + { wg.DrawLine(pen, p1, p2); // top (right-left) wg.DrawLine(pen, p2, p3); // left(up-down) } - finally { + finally + { pen.Dispose(); } // bottom + right - if (disabledHighContrast) { + if (disabledHighContrast) + { pen = new WindowsPen(wg.DeviceContext, colors.windowDisabled); } - else if (stockColor) { + else if (stockColor) + { pen = new WindowsPen(wg.DeviceContext, SystemColors.ControlDarkDark); } - else { + else + { pen = new WindowsPen(wg.DeviceContext, colors.buttonShadowDark); } - try { + try + { p1.Offset(0, -1); // need to paint last pixel too. wg.DrawLine(pen, p3, p4); // bottom(left-right) wg.DrawLine(pen, p4, p1); // right (bottom-up) } - finally { + finally + { pen.Dispose(); } @@ -376,44 +446,55 @@ private void Draw3DBorderRaised(Graphics g, ref Rectangle bounds, ColorData colo p3.Offset(1, -1); p4.Offset(-1, -1); - if (stockColor) { - if (SystemInformation.HighContrast) { + if (stockColor) + { + if (SystemInformation.HighContrast) + { pen = new WindowsPen(wg.DeviceContext, SystemColors.ControlLight); } - else { + else + { pen = new WindowsPen(wg.DeviceContext, SystemColors.Control); } } - else { + else + { pen = new WindowsPen(wg.DeviceContext, colors.buttonFace); } // top + left inset - try { + try + { wg.DrawLine(pen, p1, p2); // top (right-left) wg.DrawLine(pen, p2, p3); // left(up-down) } - finally { + finally + { pen.Dispose(); } // Bottom + right inset - if (disabledHighContrast) { + if (disabledHighContrast) + { pen = new WindowsPen(wg.DeviceContext, colors.windowDisabled); } - else if (stockColor) { + else if (stockColor) + { pen = new WindowsPen(wg.DeviceContext, SystemColors.ControlDark); } - else { + else + { pen = new WindowsPen(wg.DeviceContext, colors.buttonShadow); } - try { + try + { p1.Offset(0, -1); // need to paint last pixel too. wg.DrawLine(pen, p3, p4); // bottom(left-right) wg.DrawLine(pen, p4, p1); // right (bottom-up) } - finally { + finally + { pen.Dispose(); } } @@ -422,67 +503,80 @@ private void Draw3DBorderRaised(Graphics g, ref Rectangle bounds, ColorData colo /// /// Draws a border for the in the 3D style of the popup button. /// - protected internal static void Draw3DLiteBorder(Graphics g, Rectangle r, ColorData colors, bool up) { - using( WindowsGraphics wg = WindowsGraphics.FromGraphics(g) ) { + protected internal static void Draw3DLiteBorder(Graphics g, Rectangle r, ColorData colors, bool up) + { + using (WindowsGraphics wg = WindowsGraphics.FromGraphics(g)) + { // Draw counter-clock-wise. - Point p1 = new Point(r.Right - 1, r.Top ); // upper inner right. - Point p2 = new Point(r.Left , r.Top ); // upper left. - Point p3 = new Point(r.Left , r.Bottom - 1); // bottom inner left. + Point p1 = new Point(r.Right - 1, r.Top); // upper inner right. + Point p2 = new Point(r.Left, r.Top); // upper left. + Point p3 = new Point(r.Left, r.Bottom - 1); // bottom inner left. Point p4 = new Point(r.Right - 1, r.Bottom - 1); // inner bottom right. // top, left WindowsPen pen = up ? new WindowsPen(wg.DeviceContext, colors.highlight) : new WindowsPen(wg.DeviceContext, colors.buttonShadow); - try { + try + { wg.DrawLine(pen, p1, p2); // top (right-left) wg.DrawLine(pen, p2, p3); // left (top-down) } - finally { + finally + { pen.Dispose(); } // bottom, right pen = up ? new WindowsPen(wg.DeviceContext, colors.buttonShadow) : new WindowsPen(wg.DeviceContext, colors.highlight); - try { - p1.Offset(0,-1); // need to paint last pixel too. + try + { + p1.Offset(0, -1); // need to paint last pixel too. wg.DrawLine(pen, p3, p4); // bottom (left-right) wg.DrawLine(pen, p4, p1); // right(bottom-up) } - finally { + finally + { pen.Dispose(); } } } - - internal static void DrawFlatBorder(Graphics g, Rectangle r, Color c) { + + internal static void DrawFlatBorder(Graphics g, Rectangle r, Color c) + { ControlPaint.DrawBorder(g, r, c, ButtonBorderStyle.Solid); } - + /// /// /// Draws the flat border with specified bordersize. /// This function gets called only for Flatstyle == Flatstyle.Flat. /// /// - internal static void DrawFlatBorderWithSize(Graphics g, Rectangle r, Color c, int size) { + internal static void DrawFlatBorderWithSize(Graphics g, Rectangle r, Color c, int size) + { bool stockBorder = c.IsSystemColor; SolidBrush brush = null; - - if (size > 1) { + + if (size > 1) + { brush = new SolidBrush(c); } - else { - if (stockBorder) { + else + { + if (stockBorder) + { brush = (SolidBrush)SystemBrushes.FromSystemColor(c); } - else { + else + { brush = new SolidBrush(c); } } - try { + try + { size = System.Math.Min(size, System.Math.Min(r.Width, r.Height)); // ...truncate pen width to button size, to avoid overflow if border size is huge! @@ -498,16 +592,21 @@ internal static void DrawFlatBorderWithSize(Graphics g, Rectangle r, Color c, in //Bottom Border g.FillRectangle(brush, (r.X + size), (r.Y + r.Height - size), (r.Width - size * 2), size); } - finally { - if (!stockBorder && brush != null) { + finally + { + if (!stockBorder && brush != null) + { brush.Dispose(); } } } - internal static void DrawFlatFocus(Graphics g, Rectangle r, Color c) { - using(WindowsGraphics wg = WindowsGraphics.FromGraphics(g)) { - using (WindowsPen focus = new WindowsPen(wg.DeviceContext, c)) { + internal static void DrawFlatFocus(Graphics g, Rectangle r, Color c) + { + using (WindowsGraphics wg = WindowsGraphics.FromGraphics(g)) + { + using (WindowsPen focus = new WindowsPen(wg.DeviceContext, c)) + { wg.DrawRectangle(focus, r); } } @@ -519,27 +618,33 @@ internal static void DrawFlatFocus(Graphics g, Rectangle r, Color c) { /// /// /// - void DrawFocus(Graphics g, Rectangle r) { - if (Control.Focused && Control.ShowFocusCues) { + void DrawFocus(Graphics g, Rectangle r) + { + if (Control.Focused && Control.ShowFocusCues) + { ControlPaint.DrawFocusRectangle(g, r, Control.ForeColor, Control.BackColor); } } - + /// /// Draws the button's image. /// - void DrawImage(Graphics graphics, LayoutData layout) { - if (Control.Image != null) { + void DrawImage(Graphics graphics, LayoutData layout) + { + if (Control.Image != null) + { //setup new clip region & draw DrawImageCore(graphics, Control.Image, layout.imageBounds, layout.imageStart, layout); } } // here for DropDownButton - internal virtual void DrawImageCore(Graphics graphics, Image image, Rectangle imageBounds, Point imageStart, LayoutData layout) { + internal virtual void DrawImageCore(Graphics graphics, Image image, Rectangle imageBounds, Point imageStart, LayoutData layout) + { Region oldClip = graphics.Clip; - - if (!layout.options.everettButtonCompat) { // FOR EVERETT COMPATIBILITY - DO NOT CHANGE + + if (!layout.options.everettButtonCompat) + { // FOR EVERETT COMPATIBILITY - DO NOT CHANGE Rectangle bounds = new Rectangle(buttonBorderSize, buttonBorderSize, this.Control.Width - (2 * buttonBorderSize), this.Control.Height - (2 * buttonBorderSize)); Region newClip = oldClip.Clone(); @@ -550,42 +655,52 @@ internal virtual void DrawImageCore(Graphics graphics, Image image, Rectangle im newClip.Intersect(imageBounds); graphics.Clip = newClip; } - else { + else + { imageBounds.Width++; imageBounds.Height++; imageBounds.X = imageStart.X + 1; imageBounds.Y = imageStart.Y + 1; } - try { + try + { if (!Control.Enabled) // need to specify width and height ControlPaint.DrawImageDisabled(graphics, image, imageBounds, Control.BackColor, true /* unscaled image*/); - else { + else + { graphics.DrawImage(image, imageBounds.X, imageBounds.Y, image.Width, image.Height); } } - finally { - if (!layout.options.everettButtonCompat) {// FOR EVERETT COMPATIBILITY - DO NOT CHANGE + finally + { + if (!layout.options.everettButtonCompat) + {// FOR EVERETT COMPATIBILITY - DO NOT CHANGE graphics.Clip = oldClip; } } } - internal static void DrawDefaultBorder(Graphics g, Rectangle r, Color c, bool isDefault) { - if (isDefault) { + internal static void DrawDefaultBorder(Graphics g, Rectangle r, Color c, bool isDefault) + { + if (isDefault) + { r.Inflate(1, 1); Pen pen; - if (c.IsSystemColor) { + if (c.IsSystemColor) + { pen = SystemPens.FromSystemColor(c); } - else { + else + { pen = new Pen(c); } g.DrawRectangle(pen, r.X, r.Y, r.Width - 1, r.Height - 1); - if (!c.IsSystemColor) { + if (!c.IsSystemColor) + { pen.Dispose(); } } @@ -599,15 +714,20 @@ void DrawText(Graphics g, LayoutData layout, Color c, ColorData colors) Rectangle r = layout.textBounds; bool disabledText3D = layout.options.shadowedText; - if (Control.UseCompatibleTextRendering) { // Draw text using GDI+ - using (StringFormat stringFormat = CreateStringFormat()) { + if (Control.UseCompatibleTextRendering) + { // Draw text using GDI+ + using (StringFormat stringFormat = CreateStringFormat()) + { // DrawString doesn't seem to draw where it says it does - if ((Control.TextAlign & LayoutUtils.AnyCenter) == 0) { + if ((Control.TextAlign & LayoutUtils.AnyCenter) == 0) + { r.X -= 1; } r.Width += 1; - if (disabledText3D && !Control.Enabled && !colors.options.highContrast) { - using (SolidBrush brush = new SolidBrush(colors.highlight)) { + if (disabledText3D && !Control.Enabled && !colors.options.highContrast) + { + using (SolidBrush brush = new SolidBrush(colors.highlight)) + { r.Offset(1, 1); g.DrawString(Control.Text, Control.Font, brush, r, stringFormat); @@ -616,31 +736,39 @@ void DrawText(Graphics g, LayoutData layout, Color c, ColorData colors) g.DrawString(Control.Text, Control.Font, brush, r, stringFormat); } } - else { + else + { Brush brush; - if (c.IsSystemColor) { + if (c.IsSystemColor) + { brush = SystemBrushes.FromSystemColor(c); } - else { + else + { brush = new SolidBrush(c); } g.DrawString(Control.Text, Control.Font, brush, r, stringFormat); - if (!c.IsSystemColor) { + if (!c.IsSystemColor) + { brush.Dispose(); } } } } - else { // Draw text using GDI (Whidbey+ feature). + else + { // Draw text using GDI (Whidbey+ feature). TextFormatFlags formatFlags = CreateTextFormatFlags(); - if (disabledText3D && !Control.Enabled && !colors.options.highContrast) { - if (Application.RenderWithVisualStyles) { + if (disabledText3D && !Control.Enabled && !colors.options.highContrast) + { + if (Application.RenderWithVisualStyles) + { //don't draw chiseled text if themed as win32 app does. TextRenderer.DrawText(g, Control.Text, Control.Font, r, colors.buttonShadow, formatFlags); } - else { + else + { r.Offset(1, 1); TextRenderer.DrawText(g, Control.Text, Control.Font, r, colors.highlight, formatFlags); @@ -648,35 +776,41 @@ void DrawText(Graphics g, LayoutData layout, Color c, ColorData colors) TextRenderer.DrawText(g, Control.Text, Control.Font, r, colors.buttonShadow, formatFlags); } } - else { + else + { TextRenderer.DrawText(g, Control.Text, Control.Font, r, c, formatFlags); } } } -#endregion Drawing Helpers + #endregion Drawing Helpers -#region Draw Content Helpers + #region Draw Content Helpers // the DataGridViewButtonCell uses this method - internal static void PaintButtonBackground(WindowsGraphics wg, Rectangle bounds, WindowsBrush background) { + internal static void PaintButtonBackground(WindowsGraphics wg, Rectangle bounds, WindowsBrush background) + { wg.FillRectangle(background, bounds); } - internal void PaintButtonBackground(PaintEventArgs e, Rectangle bounds, Brush background) { - if (background == null) { + internal void PaintButtonBackground(PaintEventArgs e, Rectangle bounds, Brush background) + { + if (background == null) + { Control.PaintBackground(e, bounds); } - else { + else + { e.Graphics.FillRectangle(background, bounds); } } - internal void PaintField(PaintEventArgs e, - LayoutData layout, + internal void PaintField(PaintEventArgs e, + LayoutData layout, ColorData colors, - Color foreColor, - bool drawFocus) { + Color foreColor, + bool drawFocus) + { Graphics g = e.Graphics; @@ -684,60 +818,71 @@ internal void PaintField(PaintEventArgs e, DrawText(g, layout, foreColor, colors); - if (drawFocus) { + if (drawFocus) + { DrawFocus(g, maxFocus); } } - - internal void PaintImage(PaintEventArgs e, LayoutData layout) { + + internal void PaintImage(PaintEventArgs e, LayoutData layout) + { Graphics g = e.Graphics; DrawImage(g, layout); } -#endregion + #endregion -#region Color + #region Color - internal class ColorOptions { + internal class ColorOptions + { internal Color backColor; internal Color foreColor; internal bool enabled; internal bool highContrast; internal Graphics graphics; - internal ColorOptions(Graphics graphics, Color foreColor, Color backColor) { + internal ColorOptions(Graphics graphics, Color foreColor, Color backColor) + { this.graphics = graphics; this.backColor = backColor; this.foreColor = foreColor; highContrast = SystemInformation.HighContrast; } - internal static int Adjust255(float percentage, int value) { + internal static int Adjust255(float percentage, int value) + { int v = (int)(percentage * value); - if (v > 255) { + if (v > 255) + { return 255; } return v; } - - internal ColorData Calculate() { + + internal ColorData Calculate() + { ColorData colors = new ColorData(this); - + colors.buttonFace = backColor; - if (backColor == SystemColors.Control) { + if (backColor == SystemColors.Control) + { colors.buttonShadow = SystemColors.ControlDark; colors.buttonShadowDark = SystemColors.ControlDarkDark; colors.highlight = SystemColors.ControlLightLight; } - else { - if (!highContrast) { + else + { + if (!highContrast) + { colors.buttonShadow = ControlPaint.Dark(backColor); colors.buttonShadowDark = ControlPaint.DarkDark(backColor); colors.highlight = ControlPaint.LightLight(backColor); } - else { + else + { colors.buttonShadow = ControlPaint.Dark(backColor); colors.buttonShadowDark = ControlPaint.LightLight(backColor); colors.highlight = ControlPaint.LightLight(backColor); @@ -748,22 +893,25 @@ internal ColorData Calculate() { const float lowlight = .1f; float adjust = 1 - lowlight; - if (colors.buttonFace.GetBrightness() < .5) { + if (colors.buttonFace.GetBrightness() < .5) + { adjust = 1 + lowlight * 2; } - colors.lowButtonFace = Color.FromArgb(Adjust255(adjust, colors.buttonFace.R), - Adjust255(adjust, colors.buttonFace.G), + colors.lowButtonFace = Color.FromArgb(Adjust255(adjust, colors.buttonFace.R), + Adjust255(adjust, colors.buttonFace.G), Adjust255(adjust, colors.buttonFace.B)); adjust = 1 - lowlight; - if (colors.highlight.GetBrightness() < .5) { + if (colors.highlight.GetBrightness() < .5) + { adjust = 1 + lowlight * 2; } - colors.lowHighlight = Color.FromArgb(Adjust255(adjust, colors.highlight.R), - Adjust255(adjust, colors.highlight.G), + colors.lowHighlight = Color.FromArgb(Adjust255(adjust, colors.highlight.R), + Adjust255(adjust, colors.highlight.G), Adjust255(adjust, colors.highlight.B)); - - if (highContrast && backColor != SystemColors.Control) { + + if (highContrast && backColor != SystemColors.Control) + { colors.highlight = colors.lowHighlight; } @@ -779,21 +927,26 @@ internal ColorData Calculate() { colors.windowText = Color.Green; / * debug */ - if (colors.buttonFace.GetBrightness() < .5) { + if (colors.buttonFace.GetBrightness() < .5) + { colors.constrastButtonShadow = colors.lowHighlight; } - else { + else + { colors.constrastButtonShadow = colors.buttonShadow; } - - if (!enabled) { + + if (!enabled) + { colors.windowText = colors.windowDisabled; - if (highContrast) { + if (highContrast) + { colors.windowFrame = colors.windowDisabled; colors.buttonShadow = colors.windowDisabled; } } - else { + else + { colors.windowText = colors.windowFrame; } @@ -801,7 +954,8 @@ internal ColorData Calculate() { try { - using (WindowsGraphics wg = WindowsGraphics.FromHdc(hdc)) { + using (WindowsGraphics wg = WindowsGraphics.FromHdc(hdc)) + { colors.buttonFace = wg.GetNearestColor(colors.buttonFace); colors.buttonShadow = wg.GetNearestColor(colors.buttonShadow); colors.buttonShadowDark = wg.GetNearestColor(colors.buttonShadowDark); @@ -823,7 +977,8 @@ internal ColorData Calculate() { } } - internal class ColorData { + internal class ColorData + { internal Color buttonFace; internal Color buttonShadow; internal Color buttonShadowDark; @@ -837,16 +992,18 @@ internal class ColorData { internal ColorOptions options; - internal ColorData(ColorOptions options) { + internal ColorData(ColorOptions options) + { this.options = options; } } -#endregion + #endregion -#region Layout + #region Layout - internal class LayoutOptions { + internal class LayoutOptions + { internal Rectangle client; internal bool growBorderBy1PxWhenDefault; internal bool isDefault; @@ -870,7 +1027,7 @@ internal class LayoutOptions { internal bool verticalText = false; internal bool useCompatibleTextRendering = false; internal bool everettButtonCompat = true; - internal TextFormatFlags gdiTextFormatFlags = TextFormatFlags.WordBreak | TextFormatFlags.TextBoxControl; + internal TextFormatFlags gdiTextFormatFlags = TextFormatFlags.WordBreak | TextFormatFlags.TextBoxControl; internal StringFormatFlags gdipFormatFlags; internal StringTrimming gdipTrimming; internal HotkeyPrefix gdipHotkeyPrefix; @@ -882,36 +1039,43 @@ internal class LayoutOptions { /// We don't cache the StringFormat itself because we don't have a deterministic way of disposing it, instead /// we cache the flags that make it up and create it on demand so it can be disposed by calling code. /// - public StringFormat StringFormat { - get { + public StringFormat StringFormat + { + get + { StringFormat format = new StringFormat(); - format.FormatFlags = this.gdipFormatFlags; - format.Trimming = this.gdipTrimming; - format.HotkeyPrefix = this.gdipHotkeyPrefix; - format.Alignment = this.gdipAlignment; + format.FormatFlags = this.gdipFormatFlags; + format.Trimming = this.gdipTrimming; + format.HotkeyPrefix = this.gdipHotkeyPrefix; + format.Alignment = this.gdipAlignment; format.LineAlignment = this.gdipLineAlignment; - if (disableWordWrapping) { + if (disableWordWrapping) + { format.FormatFlags |= StringFormatFlags.NoWrap; } return format; } - set { - this.gdipFormatFlags = value.FormatFlags; - this.gdipTrimming = value.Trimming; - this.gdipHotkeyPrefix = value.HotkeyPrefix; - this.gdipAlignment = value.Alignment; - this.gdipLineAlignment = value.LineAlignment; + set + { + this.gdipFormatFlags = value.FormatFlags; + this.gdipTrimming = value.Trimming; + this.gdipHotkeyPrefix = value.HotkeyPrefix; + this.gdipAlignment = value.Alignment; + this.gdipLineAlignment = value.LineAlignment; } } /// /// - public TextFormatFlags TextFormatFlags { - get { - if (disableWordWrapping) { + public TextFormatFlags TextFormatFlags + { + get + { + if (disableWordWrapping) + { return gdiTextFormatFlags & ~TextFormatFlags.WordBreak; } @@ -928,12 +1092,13 @@ public TextFormatFlags TextFormatFlags { internal int textImageInset = 2; internal Padding padding; - + #region PreferredSize private static readonly int combineCheck = BitVector32.CreateMask(); private static readonly int combineImageText = BitVector32.CreateMask(combineCheck); - private enum Composition { + private enum Composition + { NoneCombined = 0x00, CheckCombined = 0x01, TextImageCombined = 0x02, @@ -942,7 +1107,8 @@ private enum Composition { // Uses checkAlign, imageAlign, and textAlign to figure out how to compose // checkSize, imageSize, and textSize into the preferredSize. - private Size Compose(Size checkSize, Size imageSize, Size textSize) { + private Size Compose(Size checkSize, Size imageSize, Size textSize) + { Composition hComposition = GetHorizontalComposition(); Composition vComposition = GetVerticalComposition(); return new Size( @@ -951,8 +1117,10 @@ private Size Compose(Size checkSize, Size imageSize, Size textSize) { ); } - private int xCompose(Composition composition, int checkSize, int imageSize, int textSize) { - switch(composition) { + private int xCompose(Composition composition, int checkSize, int imageSize, int textSize) + { + switch (composition) + { case Composition.NoneCombined: return checkSize + imageSize + textSize; case Composition.CheckCombined: @@ -969,7 +1137,8 @@ private int xCompose(Composition composition, int checkSize, int imageSize, int // Uses checkAlign, imageAlign, and textAlign to figure out how to decompose // proposedSize into just the space left over for text. - private Size Decompose(Size checkSize, Size imageSize, Size proposedSize) { + private Size Decompose(Size checkSize, Size imageSize, Size proposedSize) + { Composition hComposition = GetHorizontalComposition(); Composition vComposition = GetVerticalComposition(); return new Size( @@ -977,9 +1146,11 @@ private Size Decompose(Size checkSize, Size imageSize, Size proposedSize) { xDecompose(vComposition, checkSize.Height, imageSize.Height, proposedSize.Height) ); } - - private int xDecompose(Composition composition, int checkSize, int imageSize, int proposedSize) { - switch(composition) { + + private int xDecompose(Composition composition, int checkSize, int imageSize, int proposedSize) + { + switch (composition) + { case Composition.NoneCombined: return proposedSize - (checkSize + imageSize); case Composition.CheckCombined: @@ -994,20 +1165,23 @@ private int xDecompose(Composition composition, int checkSize, int imageSize, in } } - private Composition GetHorizontalComposition() { + private Composition GetHorizontalComposition() + { BitVector32 action = new BitVector32(); // Checks reserve space horizontally if possible, so only AnyLeft/AnyRight prevents combination. action[combineCheck] = checkAlign == ContentAlignment.MiddleCenter || !LayoutUtils.IsHorizontalAlignment(checkAlign); action[combineImageText] = !LayoutUtils.IsHorizontalRelation(textImageRelation); - return (Composition) action.Data; + return (Composition)action.Data; } - internal Size GetPreferredSizeCore(Size proposedSize) { + internal Size GetPreferredSizeCore(Size proposedSize) + { // Get space required for border and padding // - int linearBorderAndPadding = borderSize*2 + paddingSize*2; - if(growBorderBy1PxWhenDefault) { + int linearBorderAndPadding = borderSize * 2 + paddingSize * 2; + if (growBorderBy1PxWhenDefault) + { linearBorderAndPadding += 2; } Size bordersAndPadding = new Size(linearBorderAndPadding, linearBorderAndPadding); @@ -1030,15 +1204,18 @@ internal Size GetPreferredSizeCore(Size proposedSize) { Size textSize = Size.Empty; - if (!string.IsNullOrEmpty(text)) { + if (!string.IsNullOrEmpty(text)) + { // When Button.AutoSizeMode is set to GrowOnly TableLayoutPanel expects buttons not to automatically wrap on word break. If // there's enough room for the text to word-wrap then it will happen but the layout would not be adjusted to allow text wrapping. // If someone has a carriage return in the text we'll honor that for preferred size, but we wont wrap based on constraints. - try { + try + { this.disableWordWrapping = true; textSize = GetTextSize(proposedSize) + textImageInsetSize; } - finally { + finally + { this.disableWordWrapping = false; } } @@ -1051,38 +1228,44 @@ internal Size GetPreferredSizeCore(Size proposedSize) { return requiredSize; } - private Composition GetVerticalComposition() { + private Composition GetVerticalComposition() + { BitVector32 action = new BitVector32(); // Checks reserve space horizontally if possible, so only Top/Bottom prevents combination. action[combineCheck] = checkAlign == ContentAlignment.MiddleCenter || !LayoutUtils.IsVerticalAlignment(checkAlign); action[combineImageText] = !LayoutUtils.IsVerticalRelation(textImageRelation); - return (Composition) action.Data; + return (Composition)action.Data; } #endregion PreferredSize - private int FullBorderSize { - get { + private int FullBorderSize + { + get + { int result = borderSize; - if (OnePixExtraBorder) { + if (OnePixExtraBorder) + { borderSize++; } return borderSize; } } - private bool OnePixExtraBorder { + private bool OnePixExtraBorder + { get { return growBorderBy1PxWhenDefault && isDefault; } } - internal LayoutData Layout() { + internal LayoutData Layout() + { LayoutData layout = new LayoutData(this); layout.client = this.client; // subtract border size from layout area int fullBorderSize = FullBorderSize; layout.face = Rectangle.Inflate(layout.client, -fullBorderSize, -fullBorderSize); - + // checkBounds, checkArea, field // CalcCheckmarkRectangle(layout); @@ -1092,29 +1275,36 @@ internal LayoutData Layout() { // focus // - if (maxFocus) { + if (maxFocus) + { layout.focus = layout.field; layout.focus.Inflate(-1, -1); // Adjust for padding. layout.focus = LayoutUtils.InflateRect(layout.focus, this.padding); } - else { + else + { Rectangle textAdjusted = new Rectangle(layout.textBounds.X - 1, layout.textBounds.Y - 1, layout.textBounds.Width + 2, layout.textBounds.Height + 3); - if (imageSize != Size.Empty) { + if (imageSize != Size.Empty) + { layout.focus = Rectangle.Union(textAdjusted, layout.imageBounds); } - else { + else + { layout.focus = textAdjusted; } } - if (focusOddEvenFixup) { - if (layout.focus.Height % 2 == 0) { + if (focusOddEvenFixup) + { + if (layout.focus.Height % 2 == 0) + { layout.focus.Y++; layout.focus.Height--; } - if (layout.focus.Width % 2 == 0) { + if (layout.focus.Width % 2 == 0) + { layout.focus.X++; layout.focus.Width--; } @@ -1123,10 +1313,13 @@ internal LayoutData Layout() { return layout; } - TextImageRelation RtlTranslateRelation(TextImageRelation relation) { + TextImageRelation RtlTranslateRelation(TextImageRelation relation) + { // If RTL, we swap ImageBeforeText and TextBeforeImage - if (layoutRTL) { - switch(relation) { + if (layoutRTL) + { + switch (relation) + { case TextImageRelation.ImageBeforeText: return TextImageRelation.TextBeforeImage; case TextImageRelation.TextBeforeImage: @@ -1136,19 +1329,24 @@ TextImageRelation RtlTranslateRelation(TextImageRelation relation) { return relation; } - internal ContentAlignment RtlTranslateContent(ContentAlignment align) { - - if (layoutRTL) { + internal ContentAlignment RtlTranslateContent(ContentAlignment align) + { + + if (layoutRTL) + { ContentAlignment[][] mapping = new ContentAlignment[3][]; mapping[0] = new ContentAlignment[2] { ContentAlignment.TopLeft, ContentAlignment.TopRight }; mapping[1] = new ContentAlignment[2] { ContentAlignment.MiddleLeft, ContentAlignment.MiddleRight }; mapping[2] = new ContentAlignment[2] { ContentAlignment.BottomLeft, ContentAlignment.BottomRight }; - - for(int i=0; i < 3; ++i) { - if (mapping[i][0] == align) { + + for (int i = 0; i < 3; ++i) + { + if (mapping[i][0] == align) + { return mapping[i][1]; } - else if (mapping[i][1] == align) { + else if (mapping[i][1] == align) + { return mapping[i][0]; } } @@ -1156,13 +1354,16 @@ internal ContentAlignment RtlTranslateContent(ContentAlignment align) { return align; } - private int FullCheckSize { - get { + private int FullCheckSize + { + get + { return checkSize + checkPaddingSize; } } - void CalcCheckmarkRectangle(LayoutData layout) { + void CalcCheckmarkRectangle(LayoutData layout) + { int checkSizeFull = FullCheckSize; layout.checkBounds = new Rectangle(client.X, client.Y, checkSizeFull, checkSizeFull); @@ -1173,25 +1374,32 @@ void CalcCheckmarkRectangle(LayoutData layout) { layout.field = field; - if (checkSizeFull > 0) { - if ((align & LayoutUtils.AnyRight) != 0) { - layout.checkBounds.X = (field.X+field.Width) - layout.checkBounds.Width; + if (checkSizeFull > 0) + { + if ((align & LayoutUtils.AnyRight) != 0) + { + layout.checkBounds.X = (field.X + field.Width) - layout.checkBounds.Width; } - else if ((align & LayoutUtils.AnyCenter) != 0) { - layout.checkBounds.X = field.X + (field.Width - layout.checkBounds.Width)/2; + else if ((align & LayoutUtils.AnyCenter) != 0) + { + layout.checkBounds.X = field.X + (field.Width - layout.checkBounds.Width) / 2; } - if ((align & LayoutUtils.AnyBottom) != 0) { - layout.checkBounds.Y = (field.Y+field.Height)-layout.checkBounds.Height; + if ((align & LayoutUtils.AnyBottom) != 0) + { + layout.checkBounds.Y = (field.Y + field.Height) - layout.checkBounds.Height; } - else if ((align & LayoutUtils.AnyTop) != 0) { + else if ((align & LayoutUtils.AnyTop) != 0) + { layout.checkBounds.Y = field.Y + 2; // + 2: this needs to be aligned to the text ( } - else { - layout.checkBounds.Y = field.Y + (field.Height - layout.checkBounds.Height)/2; + else + { + layout.checkBounds.Y = field.Y + (field.Height - layout.checkBounds.Height) / 2; } - switch (align) { + switch (align) + { case ContentAlignment.TopLeft: case ContentAlignment.MiddleLeft: case ContentAlignment.BottomLeft: @@ -1263,15 +1471,18 @@ void CalcCheckmarkRectangle(LayoutData layout) { /* BottomRight = */ TextImageRelation.TextAboveImage | TextImageRelation.TextBeforeImage }; - private static TextImageRelation ImageAlignToRelation(ContentAlignment alignment) { + private static TextImageRelation ImageAlignToRelation(ContentAlignment alignment) + { return _imageAlignToRelation[LayoutUtils.ContentAlignmentToIndex(alignment)]; } - private static TextImageRelation TextAlignToRelation(ContentAlignment alignment) { + private static TextImageRelation TextAlignToRelation(ContentAlignment alignment) + { return LayoutUtils.GetOppositeTextImageRelation(ImageAlignToRelation(alignment)); } - internal void LayoutTextAndImage(LayoutData layout) { + internal void LayoutTextAndImage(LayoutData layout) + { // Translate for Rtl applications. This intentially shadows the member variables. ContentAlignment imageAlign = RtlTranslateContent(this.imageAlign); ContentAlignment textAlign = RtlTranslateContent(this.textAlign); @@ -1279,25 +1490,30 @@ internal void LayoutTextAndImage(LayoutData layout) { // Figure out the maximum bounds for text & image Rectangle maxBounds = Rectangle.Inflate(layout.field, -textImageInset, -textImageInset); - if(OnePixExtraBorder) { + if (OnePixExtraBorder) + { maxBounds.Inflate(1, 1); } // Compute the final image and text bounds. - if(imageSize == Size.Empty || text == null || text.Length == 0 || textImageRelation == TextImageRelation.Overlay) { + if (imageSize == Size.Empty || text == null || text.Length == 0 || textImageRelation == TextImageRelation.Overlay) + { // Do not worry about text/image overlaying Size textSize = GetTextSize(maxBounds.Size); // FOR EVERETT COMPATIBILITY - DO NOT CHANGE Size size = imageSize; - if (layout.options.everettButtonCompat && imageSize != Size.Empty) { + if (layout.options.everettButtonCompat && imageSize != Size.Empty) + { size = new Size(size.Width + 1, size.Height + 1); } - + layout.imageBounds = LayoutUtils.Align(size, maxBounds, imageAlign); layout.textBounds = LayoutUtils.Align(textSize, maxBounds, textAlign); - } else { + } + else + { // Rearrage text/image to prevent overlay. Pack text into maxBounds - space reserved for image Size maxTextSize = LayoutUtils.SubAlignedRegion(maxBounds.Size, imageSize, textImageRelation); Size textSize = GetTextSize(maxTextSize); @@ -1316,23 +1532,28 @@ internal void LayoutTextAndImage(LayoutData layout) { // the text along the edge of the control. If so, we can increase the space for image. bool textEdge = (AnchorStyles)(TextAlignToRelation(textAlign) & textImageRelation) != AnchorStyles.None; - if(imageEdge) { + if (imageEdge) + { // If imageEdge, just split imageSize off of maxCombinedBounds. - LayoutUtils.SplitRegion(maxCombinedBounds, imageSize, (AnchorStyles) textImageRelation, out layout.imageBounds, out layout.textBounds); - } else if(textEdge) { + LayoutUtils.SplitRegion(maxCombinedBounds, imageSize, (AnchorStyles)textImageRelation, out layout.imageBounds, out layout.textBounds); + } + else if (textEdge) + { // Else if textEdge, just split textSize off of maxCombinedBounds. - LayoutUtils.SplitRegion(maxCombinedBounds, textSize, (AnchorStyles) LayoutUtils.GetOppositeTextImageRelation(textImageRelation), out layout.textBounds, out layout.imageBounds); - } else { + LayoutUtils.SplitRegion(maxCombinedBounds, textSize, (AnchorStyles)LayoutUtils.GetOppositeTextImageRelation(textImageRelation), out layout.textBounds, out layout.imageBounds); + } + else + { // Expand the adjacent regions to maxCombinedBounds (centered) and split the rectangle into imageBounds and textBounds. - LayoutUtils.SplitRegion(combinedBounds, imageSize, (AnchorStyles) textImageRelation, out layout.imageBounds, out layout.textBounds); - LayoutUtils.ExpandRegionsToFillBounds(maxCombinedBounds, (AnchorStyles) textImageRelation, ref layout.imageBounds, ref layout.textBounds); + LayoutUtils.SplitRegion(combinedBounds, imageSize, (AnchorStyles)textImageRelation, out layout.imageBounds, out layout.textBounds); + LayoutUtils.ExpandRegionsToFillBounds(maxCombinedBounds, (AnchorStyles)textImageRelation, ref layout.imageBounds, ref layout.textBounds); } // align text/image within their regions. layout.imageBounds = LayoutUtils.Align(imageSize, layout.imageBounds, imageAlign); layout.textBounds = LayoutUtils.Align(textSize, layout.textBounds, textAlign); } - + //Don't call "layout.imageBounds = Rectangle.Intersect(layout.imageBounds, maxBounds);" // because that is a breaking change that causes images to be scaled to the dimensions of the control. //adjust textBounds so that the text is still visible even if the image is larger than the button's size @@ -1341,43 +1562,51 @@ internal void LayoutTextAndImage(LayoutData layout) { //this is because there are some legacy code which squeezes the button so small that text will get clipped //if we intersect with maxBounds. Have to do this for backward compatibility. - if (textImageRelation == TextImageRelation.TextBeforeImage || textImageRelation == TextImageRelation.ImageBeforeText) { + if (textImageRelation == TextImageRelation.TextBeforeImage || textImageRelation == TextImageRelation.ImageBeforeText) + { //adjust the vertical position of textBounds so that the text doesn't fall off the boundary of the button int textBottom = Math.Min(layout.textBounds.Bottom, layout.field.Bottom); - layout.textBounds.Y = Math.Max(Math.Min(layout.textBounds.Y, layout.field.Y + (layout.field.Height - layout.textBounds.Height)/2), layout.field.Y); + layout.textBounds.Y = Math.Max(Math.Min(layout.textBounds.Y, layout.field.Y + (layout.field.Height - layout.textBounds.Height) / 2), layout.field.Y); layout.textBounds.Height = textBottom - layout.textBounds.Y; } - if (textImageRelation == TextImageRelation.TextAboveImage || textImageRelation == TextImageRelation.ImageAboveText) { + if (textImageRelation == TextImageRelation.TextAboveImage || textImageRelation == TextImageRelation.ImageAboveText) + { //adjust the horizontal position of textBounds so that the text doesn't fall off the boundary of the button int textRight = Math.Min(layout.textBounds.Right, layout.field.Right); - layout.textBounds.X = Math.Max(Math.Min(layout.textBounds.X, layout.field.X + (layout.field.Width - layout.textBounds.Width)/2), layout.field.X); + layout.textBounds.X = Math.Max(Math.Min(layout.textBounds.X, layout.field.X + (layout.field.Width - layout.textBounds.Width) / 2), layout.field.X); layout.textBounds.Width = textRight - layout.textBounds.X; } - if (textImageRelation == TextImageRelation.ImageBeforeText && layout.imageBounds.Size.Width != 0) { + if (textImageRelation == TextImageRelation.ImageBeforeText && layout.imageBounds.Size.Width != 0) + { //squeezes imageBounds.Width so that text is visible layout.imageBounds.Width = Math.Max(0, Math.Min(maxBounds.Width - layout.textBounds.Width, layout.imageBounds.Width)); layout.textBounds.X = layout.imageBounds.X + layout.imageBounds.Width; } - if (textImageRelation == TextImageRelation.ImageAboveText && layout.imageBounds.Size.Height != 0) { + if (textImageRelation == TextImageRelation.ImageAboveText && layout.imageBounds.Size.Height != 0) + { //squeezes imageBounds.Height so that the text is visible layout.imageBounds.Height = Math.Max(0, Math.Min(maxBounds.Height - layout.textBounds.Height, layout.imageBounds.Height)); layout.textBounds.Y = layout.imageBounds.Y + layout.imageBounds.Height; } //make sure that textBound is contained in layout.field layout.textBounds = Rectangle.Intersect(layout.textBounds, layout.field); - if (hintTextUp) { + if (hintTextUp) + { layout.textBounds.Y--; } - if (textOffset) { + if (textOffset) + { layout.textBounds.Offset(1, 1); } - + // FOR EVERETT COMPATIBILITY - DO NOT CHANGE - if (layout.options.everettButtonCompat) { + if (layout.options.everettButtonCompat) + { layout.imageStart = layout.imageBounds.Location; layout.imageBounds = Rectangle.Intersect(layout.imageBounds, layout.field); } - else if (!Application.RenderWithVisualStyles) { + else if (!Application.RenderWithVisualStyles) + { // Not sure why this is here, but we can't remove it, since it might break // ToolStrips on non-themed machines layout.textBounds.X++; @@ -1389,18 +1618,20 @@ internal void LayoutTextAndImage(LayoutData layout) { // If we are using GDI to measure text, then we can get into a situation, where // the proposed height is ignore. In this case, we want to clip it against // maxbounds. - if (!useCompatibleTextRendering) { + if (!useCompatibleTextRendering) + { bottom = Math.Min(layout.textBounds.Bottom, maxBounds.Bottom); layout.textBounds.Y = Math.Max(layout.textBounds.Y, maxBounds.Y); } - else { + else + { // If we are using GDI+ (like Everett), then use the old Everett code // This ensures that we have pixel-level rendering compatibility bottom = Math.Min(layout.textBounds.Bottom, layout.field.Bottom); layout.textBounds.Y = Math.Max(layout.textBounds.Y, layout.field.Y); } - layout.textBounds.Height = bottom - layout.textBounds.Y; - + layout.textBounds.Height = bottom - layout.textBounds.Y; + //This causes a breaking change because images get shrunk to the new clipped size instead of clipped. //********** bottom = Math.Min(layout.imageBounds.Bottom, maxBounds.Bottom); //********** layout.imageBounds.Y = Math.Max(layout.imageBounds.Y, maxBounds.Y); @@ -1408,19 +1639,24 @@ internal void LayoutTextAndImage(LayoutData layout) { } - protected virtual Size GetTextSize(Size proposedSize) { + protected virtual Size GetTextSize(Size proposedSize) + { //set the Prefix field of TextFormatFlags proposedSize = LayoutUtils.FlipSizeIf(verticalText, proposedSize); Size textSize = Size.Empty; - if (useCompatibleTextRendering) { // GDI+ text rendering. - using (Graphics g = WindowsFormsUtils.CreateMeasurementGraphics()) { - using ( StringFormat gdipStringFormat = this.StringFormat ) { + if (useCompatibleTextRendering) + { // GDI+ text rendering. + using (Graphics g = WindowsFormsUtils.CreateMeasurementGraphics()) + { + using (StringFormat gdipStringFormat = this.StringFormat) + { textSize = Size.Ceiling(g.MeasureString(text, font, new SizeF(proposedSize.Width, proposedSize.Height), gdipStringFormat)); } } } - else if (!string.IsNullOrEmpty(text)) { // GDI text rendering (Whidbey feature). + else if (!string.IsNullOrEmpty(text)) + { // GDI text rendering (Whidbey feature). textSize = TextRenderer.MeasureText(text, font, proposedSize, this.TextFormatFlags); } //else skip calling MeasureText, it should return 0,0 @@ -1429,30 +1665,32 @@ protected virtual Size GetTextSize(Size proposedSize) { } #if DEBUG - public override string ToString() { - return - "{ client = " + client + "\n" + - "OnePixExtraBorder = " + OnePixExtraBorder + "\n" + - "borderSize = " + borderSize + "\n" + - "paddingSize = " + paddingSize + "\n" + - "maxFocus = " + maxFocus + "\n" + - "font = " + font + "\n" + - "text = " + text + "\n" + - "imageSize = " + imageSize + "\n" + - "checkSize = " + checkSize + "\n" + - "checkPaddingSize = " + checkPaddingSize + "\n" + - "checkAlign = " + checkAlign + "\n" + - "imageAlign = " + imageAlign + "\n" + - "textAlign = " + textAlign + "\n" + - "textOffset = " + textOffset + "\n" + - "shadowedText = " + shadowedText + "\n" + - "textImageRelation = " + textImageRelation + "\n" + + public override string ToString() + { + return + "{ client = " + client + "\n" + + "OnePixExtraBorder = " + OnePixExtraBorder + "\n" + + "borderSize = " + borderSize + "\n" + + "paddingSize = " + paddingSize + "\n" + + "maxFocus = " + maxFocus + "\n" + + "font = " + font + "\n" + + "text = " + text + "\n" + + "imageSize = " + imageSize + "\n" + + "checkSize = " + checkSize + "\n" + + "checkPaddingSize = " + checkPaddingSize + "\n" + + "checkAlign = " + checkAlign + "\n" + + "imageAlign = " + imageAlign + "\n" + + "textAlign = " + textAlign + "\n" + + "textOffset = " + textOffset + "\n" + + "shadowedText = " + shadowedText + "\n" + + "textImageRelation = " + textImageRelation + "\n" + "layoutRTL = " + layoutRTL + " }"; } #endif } - internal class LayoutData { + internal class LayoutData + { internal Rectangle client; internal Rectangle face; internal Rectangle checkArea; @@ -1464,118 +1702,131 @@ internal class LayoutData { internal Point imageStart; // FOR EVERETT COMPATIBILITY - DO NOT CHANGE internal LayoutOptions options; - internal LayoutData(LayoutOptions options) { + internal LayoutData(LayoutOptions options) + { Debug.Assert(options != null, "must have options"); this.options = options; } } -#endregion + #endregion -#region Layout + #region Layout // used by the DataGridViewButtonCell internal static LayoutOptions CommonLayout(Rectangle clientRectangle, Padding padding, bool isDefault, Font font, string text, bool enabled, ContentAlignment textAlign, RightToLeft rtl) { LayoutOptions layout = new LayoutOptions(); - layout.client = LayoutUtils.DeflateRect(clientRectangle, padding); - layout.padding = padding; + layout.client = LayoutUtils.DeflateRect(clientRectangle, padding); + layout.padding = padding; layout.growBorderBy1PxWhenDefault = true; - layout.isDefault = isDefault; - layout.borderSize = 2; - layout.paddingSize = 0; - layout.maxFocus = true; - layout.focusOddEvenFixup = false; - layout.font = font; - layout.text = text; - layout.imageSize = Size.Empty; - layout.checkSize = 0; - layout.checkPaddingSize = 0; - layout.checkAlign = ContentAlignment.TopLeft; - layout.imageAlign = ContentAlignment.MiddleCenter; - layout.textAlign = textAlign; - layout.hintTextUp = false; - layout.shadowedText = !enabled; - layout.layoutRTL = RightToLeft.Yes == rtl; - layout.textImageRelation = TextImageRelation.Overlay; + layout.isDefault = isDefault; + layout.borderSize = 2; + layout.paddingSize = 0; + layout.maxFocus = true; + layout.focusOddEvenFixup = false; + layout.font = font; + layout.text = text; + layout.imageSize = Size.Empty; + layout.checkSize = 0; + layout.checkPaddingSize = 0; + layout.checkAlign = ContentAlignment.TopLeft; + layout.imageAlign = ContentAlignment.MiddleCenter; + layout.textAlign = textAlign; + layout.hintTextUp = false; + layout.shadowedText = !enabled; + layout.layoutRTL = RightToLeft.Yes == rtl; + layout.textImageRelation = TextImageRelation.Overlay; layout.useCompatibleTextRendering = false; return layout; } - internal virtual LayoutOptions CommonLayout() { + internal virtual LayoutOptions CommonLayout() + { LayoutOptions layout = new LayoutOptions(); - layout.client = LayoutUtils.DeflateRect(Control.ClientRectangle, Control.Padding); - layout.padding = Control.Padding; + layout.client = LayoutUtils.DeflateRect(Control.ClientRectangle, Control.Padding); + layout.padding = Control.Padding; layout.growBorderBy1PxWhenDefault = true; - layout.isDefault = Control.IsDefault; - layout.borderSize = 2; - layout.paddingSize = 0; - layout.maxFocus = true; - layout.focusOddEvenFixup = false; - layout.font = Control.Font; - layout.text = Control.Text; - layout.imageSize = (Control.Image == null) ? Size.Empty : Control.Image.Size; - layout.checkSize = 0; - layout.checkPaddingSize = 0; - layout.checkAlign = ContentAlignment.TopLeft; - layout.imageAlign = Control.ImageAlign; - layout.textAlign = Control.TextAlign; - layout.hintTextUp = false; - layout.shadowedText = !Control.Enabled; - layout.layoutRTL = RightToLeft.Yes == Control.RightToLeft; - layout.textImageRelation = Control.TextImageRelation; + layout.isDefault = Control.IsDefault; + layout.borderSize = 2; + layout.paddingSize = 0; + layout.maxFocus = true; + layout.focusOddEvenFixup = false; + layout.font = Control.Font; + layout.text = Control.Text; + layout.imageSize = (Control.Image == null) ? Size.Empty : Control.Image.Size; + layout.checkSize = 0; + layout.checkPaddingSize = 0; + layout.checkAlign = ContentAlignment.TopLeft; + layout.imageAlign = Control.ImageAlign; + layout.textAlign = Control.TextAlign; + layout.hintTextUp = false; + layout.shadowedText = !Control.Enabled; + layout.layoutRTL = RightToLeft.Yes == Control.RightToLeft; + layout.textImageRelation = Control.TextImageRelation; layout.useCompatibleTextRendering = Control.UseCompatibleTextRendering; - if( Control.FlatStyle != FlatStyle.System ) { - if( layout.useCompatibleTextRendering ) { - using( StringFormat format = Control.CreateStringFormat() ) { + if (Control.FlatStyle != FlatStyle.System) + { + if (layout.useCompatibleTextRendering) + { + using (StringFormat format = Control.CreateStringFormat()) + { layout.StringFormat = format; } } - else { + else + { layout.gdiTextFormatFlags = Control.CreateTextFormatFlags(); } } - + return layout; } // used by the DataGridViewButtonCell - static ColorOptions CommonRender(Graphics g, Color foreColor, Color backColor, bool enabled) { + static ColorOptions CommonRender(Graphics g, Color foreColor, Color backColor, bool enabled) + { ColorOptions colors = new ColorOptions(g, foreColor, backColor); colors.enabled = enabled; return colors; } - ColorOptions CommonRender(Graphics g) { + ColorOptions CommonRender(Graphics g) + { ColorOptions colors = new ColorOptions(g, Control.ForeColor, Control.BackColor); colors.enabled = Control.Enabled; return colors; } - protected ColorOptions PaintRender(Graphics g) { + protected ColorOptions PaintRender(Graphics g) + { return CommonRender(g); } // used by the DataGridViewButtonCell - internal static ColorOptions PaintFlatRender(Graphics g, Color foreColor, Color backColor, bool enabled) { + internal static ColorOptions PaintFlatRender(Graphics g, Color foreColor, Color backColor, bool enabled) + { return CommonRender(g, foreColor, backColor, enabled); } - protected ColorOptions PaintFlatRender(Graphics g) { + protected ColorOptions PaintFlatRender(Graphics g) + { return CommonRender(g); } // used by the DataGridViewButtonCell - internal static ColorOptions PaintPopupRender(Graphics g, Color foreColor, Color backColor, bool enabled) { + internal static ColorOptions PaintPopupRender(Graphics g, Color foreColor, Color backColor, bool enabled) + { return CommonRender(g, foreColor, backColor, enabled); } - protected ColorOptions PaintPopupRender(Graphics g) { + protected ColorOptions PaintPopupRender(Graphics g) + { return CommonRender(g); } -#endregion + #endregion } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonFlatAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonFlatAdapter.cs index c25df63eaee..f2c6c667e82 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonFlatAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonFlatAdapter.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ButtonInternal { +namespace System.Windows.Forms.ButtonInternal +{ using System; using System.Diagnostics; using System.Drawing; @@ -13,34 +14,38 @@ namespace System.Windows.Forms.ButtonInternal { using System.Windows.Forms; using System.Windows.Forms.Layout; using System.Diagnostics.CodeAnalysis; - - internal class ButtonFlatAdapter : ButtonBaseAdapter { + + internal class ButtonFlatAdapter : ButtonBaseAdapter + { private const int BORDERSIZE = 1; - internal ButtonFlatAdapter(ButtonBase control) : base(control) {} + internal ButtonFlatAdapter(ButtonBase control) : base(control) { } - private void PaintBackground(PaintEventArgs e, Rectangle r, Color backColor) { + private void PaintBackground(PaintEventArgs e, Rectangle r, Color backColor) + { Rectangle rect = r; - rect.Inflate(-Control.FlatAppearance.BorderSize,-Control.FlatAppearance.BorderSize); + rect.Inflate(-Control.FlatAppearance.BorderSize, -Control.FlatAppearance.BorderSize); Control.PaintBackground(e, rect, backColor, rect.Location); } - internal override void PaintUp(PaintEventArgs e, CheckState state) { + internal override void PaintUp(PaintEventArgs e, CheckState state) + { bool hasCustomBorder = (Control.FlatAppearance.BorderSize != BORDERSIZE || !Control.FlatAppearance.BorderColor.IsEmpty); ColorData colors = PaintFlatRender(e.Graphics).Calculate(); - LayoutData layout = PaintFlatLayout(e, + LayoutData layout = PaintFlatLayout(e, !Control.FlatAppearance.CheckedBackColor.IsEmpty || (SystemInformation.HighContrast ? state != CheckState.Indeterminate : state == CheckState.Unchecked), !hasCustomBorder && SystemInformation.HighContrast && state == CheckState.Checked, Control.FlatAppearance.BorderSize).Layout(); //Paint with the BorderColor if Set. /// - if (!Control.FlatAppearance.BorderColor.IsEmpty) { + if (!Control.FlatAppearance.BorderColor.IsEmpty) + { colors.windowFrame = Control.FlatAppearance.BorderColor; } - + Graphics g = e.Graphics; //Region original = g.Clip; @@ -48,8 +53,10 @@ internal override void PaintUp(PaintEventArgs e, CheckState state) { Color backColor = Control.BackColor; - if (!Control.FlatAppearance.CheckedBackColor.IsEmpty) { - switch (state) { + if (!Control.FlatAppearance.CheckedBackColor.IsEmpty) + { + switch (state) + { case CheckState.Checked: backColor = Control.FlatAppearance.CheckedBackColor; break; @@ -58,8 +65,10 @@ internal override void PaintUp(PaintEventArgs e, CheckState state) { break; } } - else { - switch (state) { + else + { + switch (state) + { case CheckState.Checked: backColor = colors.highlight; break; @@ -71,57 +80,68 @@ internal override void PaintUp(PaintEventArgs e, CheckState state) { PaintBackground(e, r, IsHighContrastHighlighted() ? SystemColors.Highlight : backColor); - if (Control.IsDefault) { + if (Control.IsDefault) + { r.Inflate(-1, -1); } PaintImage(e, layout); PaintField(e, layout, colors, IsHighContrastHighlighted() ? SystemColors.HighlightText : colors.windowText, false); - if (Control.Focused && Control.ShowFocusCues) { + if (Control.Focused && Control.ShowFocusCues) + { DrawFlatFocus(g, layout.focus, colors.options.highContrast ? colors.windowText : colors.constrastButtonShadow); } - if (!(Control.IsDefault && Control.Focused && (Control.FlatAppearance.BorderSize == 0))) { + if (!(Control.IsDefault && Control.Focused && (Control.FlatAppearance.BorderSize == 0))) + { DrawDefaultBorder(g, r, colors.windowFrame, this.Control.IsDefault); } //Always check if the BorderSize is not the default.If not, we need to paint with the BorderSize set by the user. - if (hasCustomBorder) { - if (Control.FlatAppearance.BorderSize != BORDERSIZE) { - DrawFlatBorderWithSize(g, r, colors.windowFrame, Control.FlatAppearance.BorderSize); + if (hasCustomBorder) + { + if (Control.FlatAppearance.BorderSize != BORDERSIZE) + { + DrawFlatBorderWithSize(g, r, colors.windowFrame, Control.FlatAppearance.BorderSize); } - else { + else + { DrawFlatBorder(g, r, colors.windowFrame); } } - else if (state == CheckState.Checked && SystemInformation.HighContrast) { + else if (state == CheckState.Checked && SystemInformation.HighContrast) + { DrawFlatBorder(g, r, colors.windowFrame); DrawFlatBorder(g, r, colors.buttonShadow); } - else if (state == CheckState.Indeterminate) { + else if (state == CheckState.Indeterminate) + { Draw3DLiteBorder(g, r, colors, false); } - else { + else + { DrawFlatBorder(g, r, colors.windowFrame); } } - internal override void PaintDown(PaintEventArgs e, CheckState state) { + internal override void PaintDown(PaintEventArgs e, CheckState state) + { bool hasCustomBorder = (Control.FlatAppearance.BorderSize != BORDERSIZE || !Control.FlatAppearance.BorderColor.IsEmpty); ColorData colors = PaintFlatRender(e.Graphics).Calculate(); - LayoutData layout = PaintFlatLayout(e, + LayoutData layout = PaintFlatLayout(e, !Control.FlatAppearance.CheckedBackColor.IsEmpty || (SystemInformation.HighContrast ? state != CheckState.Indeterminate : state == CheckState.Unchecked), !hasCustomBorder && SystemInformation.HighContrast && state == CheckState.Checked, Control.FlatAppearance.BorderSize).Layout(); //Paint with the BorderColor if Set. - if (!Control.FlatAppearance.BorderColor.IsEmpty) { + if (!Control.FlatAppearance.BorderColor.IsEmpty) + { colors.windowFrame = Control.FlatAppearance.BorderColor; } - + Graphics g = e.Graphics; //Region original = g.Clip; @@ -129,11 +149,14 @@ internal override void PaintDown(PaintEventArgs e, CheckState state) { Color backColor = Control.BackColor; - if (!Control.FlatAppearance.MouseDownBackColor.IsEmpty) { + if (!Control.FlatAppearance.MouseDownBackColor.IsEmpty) + { backColor = Control.FlatAppearance.MouseDownBackColor; } - else { - switch (state) { + else + { + switch (state) + { case CheckState.Unchecked: case CheckState.Checked: backColor = colors.options.highContrast ? colors.buttonShadow : colors.lowHighlight; @@ -146,47 +169,59 @@ internal override void PaintDown(PaintEventArgs e, CheckState state) { PaintBackground(e, r, backColor); - if (Control.IsDefault) { + if (Control.IsDefault) + { r.Inflate(-1, -1); } PaintImage(e, layout); PaintField(e, layout, colors, colors.windowText, false); - if (Control.Focused && Control.ShowFocusCues) { + if (Control.Focused && Control.ShowFocusCues) + { DrawFlatFocus(g, layout.focus, colors.options.highContrast ? colors.windowText : colors.constrastButtonShadow); } - if (!(Control.IsDefault && Control.Focused && (Control.FlatAppearance.BorderSize == 0))) { + if (!(Control.IsDefault && Control.Focused && (Control.FlatAppearance.BorderSize == 0))) + { DrawDefaultBorder(g, r, colors.windowFrame, this.Control.IsDefault); } //Always check if the BorderSize is not the default.If not, we need to paint with the BorderSize set by the user. - if (hasCustomBorder) { - if (Control.FlatAppearance.BorderSize != BORDERSIZE) { - DrawFlatBorderWithSize(g, r, colors.windowFrame, Control.FlatAppearance.BorderSize); + if (hasCustomBorder) + { + if (Control.FlatAppearance.BorderSize != BORDERSIZE) + { + DrawFlatBorderWithSize(g, r, colors.windowFrame, Control.FlatAppearance.BorderSize); } - else { + else + { DrawFlatBorder(g, r, colors.windowFrame); } } - else if (state == CheckState.Checked && SystemInformation.HighContrast) { + else if (state == CheckState.Checked && SystemInformation.HighContrast) + { DrawFlatBorder(g, r, colors.windowFrame); DrawFlatBorder(g, r, colors.buttonShadow); } - else if (state == CheckState.Indeterminate) { + else if (state == CheckState.Indeterminate) + { Draw3DLiteBorder(g, r, colors, false); } - else { + else + { DrawFlatBorder(g, r, colors.windowFrame); } } - - internal override void PaintOver(PaintEventArgs e, CheckState state) { - if (SystemInformation.HighContrast) { + + internal override void PaintOver(PaintEventArgs e, CheckState state) + { + if (SystemInformation.HighContrast) + { PaintUp(e, state); } - else { + else + { bool hasCustomBorder = (Control.FlatAppearance.BorderSize != BORDERSIZE || !Control.FlatAppearance.BorderColor.IsEmpty); ColorData colors = PaintFlatRender(e.Graphics).Calculate(); @@ -197,10 +232,11 @@ internal override void PaintOver(PaintEventArgs e, CheckState state) { //Paint with the BorderColor if Set. /// - if (!Control.FlatAppearance.BorderColor.IsEmpty) { + if (!Control.FlatAppearance.BorderColor.IsEmpty) + { colors.windowFrame = Control.FlatAppearance.BorderColor; } - + Graphics g = e.Graphics; //Region original = g.Clip; @@ -208,56 +244,71 @@ internal override void PaintOver(PaintEventArgs e, CheckState state) { Color backColor = Control.BackColor; - if (!Control.FlatAppearance.MouseOverBackColor.IsEmpty) { + if (!Control.FlatAppearance.MouseOverBackColor.IsEmpty) + { backColor = Control.FlatAppearance.MouseOverBackColor; } - else if (!Control.FlatAppearance.CheckedBackColor.IsEmpty) { - if (state == CheckState.Checked || state == CheckState.Indeterminate) { + else if (!Control.FlatAppearance.CheckedBackColor.IsEmpty) + { + if (state == CheckState.Checked || state == CheckState.Indeterminate) + { backColor = MixedColor(Control.FlatAppearance.CheckedBackColor, colors.lowButtonFace); } - else { + else + { backColor = colors.lowButtonFace; } } - else { - if (state == CheckState.Indeterminate) { + else + { + if (state == CheckState.Indeterminate) + { backColor = MixedColor(colors.buttonFace, colors.lowButtonFace); } - else { + else + { backColor = colors.lowButtonFace; } } PaintBackground(e, r, IsHighContrastHighlighted() ? SystemColors.Highlight : backColor); - if (Control.IsDefault) { + if (Control.IsDefault) + { r.Inflate(-1, -1); } PaintImage(e, layout); PaintField(e, layout, colors, IsHighContrastHighlighted() ? SystemColors.HighlightText : colors.windowText, false); - if (Control.Focused && Control.ShowFocusCues) { + if (Control.Focused && Control.ShowFocusCues) + { DrawFlatFocus(g, layout.focus, colors.constrastButtonShadow); } - if (!(Control.IsDefault && Control.Focused && (Control.FlatAppearance.BorderSize == 0))) { + if (!(Control.IsDefault && Control.Focused && (Control.FlatAppearance.BorderSize == 0))) + { DrawDefaultBorder(g, r, colors.windowFrame, this.Control.IsDefault); } //Always check if the BorderSize is not the default.If not, we need to paint with the BorderSize set by the user. - if (hasCustomBorder) { - if (Control.FlatAppearance.BorderSize != BORDERSIZE) { - DrawFlatBorderWithSize(g, r, colors.windowFrame, Control.FlatAppearance.BorderSize); + if (hasCustomBorder) + { + if (Control.FlatAppearance.BorderSize != BORDERSIZE) + { + DrawFlatBorderWithSize(g, r, colors.windowFrame, Control.FlatAppearance.BorderSize); } - else { + else + { DrawFlatBorder(g, r, colors.windowFrame); } } - else if (state == CheckState.Unchecked) { + else if (state == CheckState.Unchecked) + { DrawFlatBorder(g, r, colors.windowFrame); } - else { + else + { Draw3DLiteBorder(g, r, colors, false); } } @@ -266,7 +317,8 @@ internal override void PaintOver(PaintEventArgs e, CheckState state) { #region LayoutData - protected override LayoutOptions Layout(PaintEventArgs e) { + protected override LayoutOptions Layout(PaintEventArgs e) + { LayoutOptions layout = PaintFlatLayout(e, /* up = */ false, /* check = */ true, Control.FlatAppearance.BorderSize); #if DEBUG Size prefSize = layout.GetPreferredSizeCore(LayoutUtils.MaxSize); @@ -278,7 +330,7 @@ protected override LayoutOptions Layout(PaintEventArgs e) { #endif return layout; } - + // used by DataGridViewButtonCell [SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters")] // removed graphics, may have to put it back @@ -286,24 +338,25 @@ internal static LayoutOptions PaintFlatLayout(Graphics g, bool up, bool check, i bool isDefault, Font font, string text, bool enabled, ContentAlignment textAlign, RightToLeft rtl) { LayoutOptions layout = CommonLayout(clientRectangle, padding, isDefault, font, text, enabled, textAlign, rtl); - layout.borderSize = borderSize + (check ? 1 : 0); - layout.paddingSize = check ? 1 : 2; + layout.borderSize = borderSize + (check ? 1 : 0); + layout.paddingSize = check ? 1 : 2; layout.focusOddEvenFixup = false; - layout.textOffset = !up; - layout.shadowedText = SystemInformation.HighContrast; + layout.textOffset = !up; + layout.shadowedText = SystemInformation.HighContrast; return layout; } [SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters")] // removed graphics, may have to put it back - private LayoutOptions PaintFlatLayout(PaintEventArgs e, bool up, bool check, int borderSize) { + private LayoutOptions PaintFlatLayout(PaintEventArgs e, bool up, bool check, int borderSize) + { LayoutOptions layout = CommonLayout(); - layout.borderSize = borderSize + (check ? 1 : 0); - layout.paddingSize = check ? 1 : 2; + layout.borderSize = borderSize + (check ? 1 : 0); + layout.paddingSize = check ? 1 : 2; layout.focusOddEvenFixup = false; - layout.textOffset = !up; - layout.shadowedText = SystemInformation.HighContrast; + layout.textOffset = !up; + layout.shadowedText = SystemInformation.HighContrast; return layout; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonPopupAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonPopupAdapter.cs index 3752e910bb9..42a888c6756 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonPopupAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonPopupAdapter.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ButtonInternal { +namespace System.Windows.Forms.ButtonInternal +{ using System; using System.Diagnostics; using System.Drawing; @@ -13,13 +14,15 @@ namespace System.Windows.Forms.ButtonInternal { using System.Windows.Forms; using System.Windows.Forms.Layout; using System.Diagnostics.CodeAnalysis; - - internal class ButtonPopupAdapter : ButtonBaseAdapter { - internal ButtonPopupAdapter(ButtonBase control) : base(control) {} + internal class ButtonPopupAdapter : ButtonBaseAdapter + { - internal override void PaintUp(PaintEventArgs e, CheckState state) { + internal ButtonPopupAdapter(ButtonBase control) : base(control) { } + + internal override void PaintUp(PaintEventArgs e, CheckState state) + { ColorData colors = PaintPopupRender(e.Graphics).Calculate(); LayoutData layout = PaintPopupLayout(e, state == CheckState.Unchecked, 1).Layout(); @@ -27,21 +30,26 @@ internal override void PaintUp(PaintEventArgs e, CheckState state) { Rectangle r = Control.ClientRectangle; - if (state == CheckState.Indeterminate) { + if (state == CheckState.Indeterminate) + { Brush backbrush = CreateDitherBrush(colors.highlight, colors.buttonFace); - try { + try + { PaintButtonBackground(e, r, backbrush); } - finally { + finally + { backbrush.Dispose(); backbrush = null; } } - else { + else + { Control.PaintBackground(e, r, IsHighContrastHighlighted() ? SystemColors.Highlight : Control.BackColor, r.Location); } - if (Control.IsDefault) { + if (Control.IsDefault) + { r.Inflate(-1, -1); } @@ -50,15 +58,18 @@ internal override void PaintUp(PaintEventArgs e, CheckState state) { DrawDefaultBorder(g, r, colors.options.highContrast ? colors.windowText : colors.buttonShadow, this.Control.IsDefault); - if (state == CheckState.Unchecked) { + if (state == CheckState.Unchecked) + { DrawFlatBorder(g, r, colors.options.highContrast ? colors.windowText : colors.buttonShadow); } - else { + else + { Draw3DLiteBorder(g, r, colors, false); } } - internal override void PaintOver(PaintEventArgs e, CheckState state) { + internal override void PaintOver(PaintEventArgs e, CheckState state) + { ColorData colors = PaintPopupRender(e.Graphics).Calculate(); LayoutData layout = PaintPopupLayout(e, state == CheckState.Unchecked, SystemInformation.HighContrast ? 2 : 1).Layout(); @@ -67,21 +78,26 @@ internal override void PaintOver(PaintEventArgs e, CheckState state) { Rectangle r = Control.ClientRectangle; - if (state == CheckState.Indeterminate) { + if (state == CheckState.Indeterminate) + { Brush backbrush = CreateDitherBrush(colors.highlight, colors.buttonFace); - try { + try + { PaintButtonBackground(e, r, backbrush); } - finally { + finally + { backbrush.Dispose(); backbrush = null; } } - else { + else + { Control.PaintBackground(e, r, IsHighContrastHighlighted() ? SystemColors.Highlight : Control.BackColor, r.Location); } - if (Control.IsDefault) { + if (Control.IsDefault) + { r.Inflate(-1, -1); } @@ -90,10 +106,12 @@ internal override void PaintOver(PaintEventArgs e, CheckState state) { DrawDefaultBorder(g, r, colors.options.highContrast ? colors.windowText : colors.buttonShadow, this.Control.IsDefault); - if (SystemInformation.HighContrast) { + if (SystemInformation.HighContrast) + { using (Pen windowFrame = new Pen(colors.windowFrame), highlight = new Pen(colors.highlight), - buttonShadow = new Pen(colors.buttonShadow)) { + buttonShadow = new Pen(colors.buttonShadow)) + { // top, left white g.DrawLine(windowFrame, r.Left + 1, r.Top + 1, r.Right - 2, r.Top + 1); @@ -114,12 +132,14 @@ internal override void PaintOver(PaintEventArgs e, CheckState state) { r.Inflate(-2, -2); } - else { + else + { Draw3DLiteBorder(g, r, colors, true); } } - internal override void PaintDown(PaintEventArgs e, CheckState state) { + internal override void PaintDown(PaintEventArgs e, CheckState state) + { ColorData colors = PaintPopupRender(e.Graphics).Calculate(); LayoutData layout = PaintPopupLayout(e, false, SystemInformation.HighContrast ? 2 : 1).Layout(); @@ -128,14 +148,15 @@ internal override void PaintDown(PaintEventArgs e, CheckState state) { Rectangle r = Control.ClientRectangle; PaintButtonBackground(e, r, null); - if (Control.IsDefault) { + if (Control.IsDefault) + { r.Inflate(-1, -1); } r.Inflate(-1, -1); PaintImage(e, layout); PaintField(e, layout, colors, colors.windowText, true); - + r.Inflate(1, 1); DrawDefaultBorder(g, r, colors.options.highContrast ? colors.windowText : colors.windowFrame, this.Control.IsDefault); ControlPaint.DrawBorder(g, r, colors.options.highContrast ? colors.windowText : colors.buttonShadow, ButtonBorderStyle.Solid); @@ -143,7 +164,8 @@ internal override void PaintDown(PaintEventArgs e, CheckState state) { #region Layout - protected override LayoutOptions Layout(PaintEventArgs e) { + protected override LayoutOptions Layout(PaintEventArgs e) + { LayoutOptions layout = PaintPopupLayout(e, /* up = */ false, 0); Debug.Assert(layout.GetPreferredSizeCore(LayoutUtils.MaxSize) == PaintPopupLayout(e, /* up = */ true, 2).GetPreferredSizeCore(LayoutUtils.MaxSize), @@ -158,11 +180,11 @@ internal static LayoutOptions PaintPopupLayout(Graphics g, bool up, int paintedB bool isDefault, Font font, string text, bool enabled, ContentAlignment textAlign, RightToLeft rtl) { LayoutOptions layout = CommonLayout(clientRectangle, padding, isDefault, font, text, enabled, textAlign, rtl); - layout.borderSize = paintedBorder; - layout.paddingSize = 2 - paintedBorder; - layout.hintTextUp = false; - layout.textOffset = !up; - layout.shadowedText = SystemInformation.HighContrast; + layout.borderSize = paintedBorder; + layout.paddingSize = 2 - paintedBorder; + layout.hintTextUp = false; + layout.textOffset = !up; + layout.shadowedText = SystemInformation.HighContrast; Debug.Assert(layout.borderSize + layout.paddingSize == 2, "It is assemed borderSize + paddingSize will always be 2. Bad value for paintedBorder?"); @@ -172,14 +194,15 @@ internal static LayoutOptions PaintPopupLayout(Graphics g, bool up, int paintedB [SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters")] // removed graphics, may have to put it back - private LayoutOptions PaintPopupLayout(PaintEventArgs e, bool up, int paintedBorder) { + private LayoutOptions PaintPopupLayout(PaintEventArgs e, bool up, int paintedBorder) + { LayoutOptions layout = CommonLayout(); - layout.borderSize = paintedBorder; - layout.paddingSize = 2 - paintedBorder;//3 - paintedBorder - (Control.IsDefault ? 1 : 0); - layout.hintTextUp = false; - layout.textOffset = !up; - layout.shadowedText = SystemInformation.HighContrast; + layout.borderSize = paintedBorder; + layout.paddingSize = 2 - paintedBorder;//3 - paintedBorder - (Control.IsDefault ? 1 : 0); + layout.hintTextUp = false; + layout.textOffset = !up; + layout.shadowedText = SystemInformation.HighContrast; Debug.Assert(layout.borderSize + layout.paddingSize == 2, "borderSize + paddingSize will always be 2. Bad value for paintedBorder?"); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonStandardAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonStandardAdapter.cs index bcf517f5232..ce6fe9aec8f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonStandardAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonStandardAdapter.cs @@ -2,11 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ButtonInternal { +namespace System.Windows.Forms.ButtonInternal +{ using System; using System.Diagnostics; using System.Drawing; - using System.Windows.Forms.Internal; + using System.Windows.Forms.Internal; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Drawing.Text; @@ -16,59 +17,72 @@ namespace System.Windows.Forms.ButtonInternal { using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; - - internal class ButtonStandardAdapter : ButtonBaseAdapter { + + internal class ButtonStandardAdapter : ButtonBaseAdapter + { private const int borderWidth = 2; - internal ButtonStandardAdapter(ButtonBase control) : base(control) {} + internal ButtonStandardAdapter(ButtonBase control) : base(control) { } - private PushButtonState DetermineState(bool up) { + private PushButtonState DetermineState(bool up) + { PushButtonState state = PushButtonState.Normal; - - if (!up) { + + if (!up) + { state = PushButtonState.Pressed; } - else if (Control.MouseIsOver) { + else if (Control.MouseIsOver) + { state = PushButtonState.Hot; } - else if (!Control.Enabled) { + else if (!Control.Enabled) + { state = PushButtonState.Disabled; } - else if (Control.Focused || Control.IsDefault) { + else if (Control.Focused || Control.IsDefault) + { state = PushButtonState.Default; } return state; } - internal override void PaintUp(PaintEventArgs e, CheckState state) { + internal override void PaintUp(PaintEventArgs e, CheckState state) + { PaintWorker(e, true, state); } - internal override void PaintDown(PaintEventArgs e, CheckState state) { + internal override void PaintDown(PaintEventArgs e, CheckState state) + { PaintWorker(e, false, state); } - internal override void PaintOver(PaintEventArgs e, CheckState state) { + internal override void PaintOver(PaintEventArgs e, CheckState state) + { PaintUp(e, state); } - private void PaintThemedButtonBackground(PaintEventArgs e, Rectangle bounds, bool up) { + private void PaintThemedButtonBackground(PaintEventArgs e, Rectangle bounds, bool up) + { PushButtonState pbState = DetermineState(up); // First handle transparent case - if (ButtonRenderer.IsBackgroundPartiallyTransparent(pbState)) { + if (ButtonRenderer.IsBackgroundPartiallyTransparent(pbState)) + { ButtonRenderer.DrawParentBackground(e.Graphics, bounds, Control); } // Now draw the actual themed background - if (!DpiHelper.IsScalingRequirementMet) { + if (!DpiHelper.IsScalingRequirementMet) + { ButtonRenderer.DrawButton(e.Graphics, Control.ClientRectangle, false, pbState); } - else { + else + { ButtonRenderer.DrawButtonForHandle(e.Graphics, Control.ClientRectangle, false, pbState, this.Control.HandleInternal); } @@ -79,38 +93,45 @@ private void PaintThemedButtonBackground(PaintEventArgs e, Rectangle bounds, boo // work in some cases. bounds.Inflate(-buttonBorderSize, -buttonBorderSize); - + //only paint if the user said not to use the themed backcolor. - if (!Control.UseVisualStyleBackColor) { + if (!Control.UseVisualStyleBackColor) + { bool painted = false; bool isHighContrastHighlighted = up && IsHighContrastHighlighted(); Color color = isHighContrastHighlighted ? SystemColors.Highlight : Control.BackColor; // Note: PaintEvent.HDC == 0 if GDI+ has used the HDC -- it wouldn't be safe for us // to use it without enough bookkeeping to negate any performance gain of using GDI. - if (color.A == 255 && e.HDC != IntPtr.Zero) { + if (color.A == 255 && e.HDC != IntPtr.Zero) + { - if (DisplayInformation.BitsPerPixel > 8) { + if (DisplayInformation.BitsPerPixel > 8) + { NativeMethods.RECT r = new NativeMethods.RECT(bounds.X, bounds.Y, bounds.Right, bounds.Bottom); // SysColorBrush does not have to be deleted. - SafeNativeMethods.FillRect(new HandleRef(e, e.HDC), ref r, new HandleRef(this, + SafeNativeMethods.FillRect(new HandleRef(e, e.HDC), ref r, new HandleRef(this, isHighContrastHighlighted ? SafeNativeMethods.GetSysColorBrush(ColorTranslator.ToOle(color) & 0xFF) : Control.BackColorBrush)); painted = true; } } - if (!painted) { + if (!painted) + { // don't paint anything from 100% transparent background // - if (color.A > 0) { - if (color.A == 255) { - color = e.Graphics.GetNearestColor(color); + if (color.A > 0) + { + if (color.A == 255) + { + color = e.Graphics.GetNearestColor(color); } // Color has some transparency or we have no HDC, so we must // fall back to using GDI+. // - using (Brush brush = new SolidBrush(color)) { + using (Brush brush = new SolidBrush(color)) + { e.Graphics.FillRectangle(brush, bounds); } } @@ -118,52 +139,64 @@ private void PaintThemedButtonBackground(PaintEventArgs e, Rectangle bounds, boo } //This code is mostly taken from the non-themed rendering code path. - if (Control.BackgroundImage != null && !DisplayInformation.HighContrast) { + if (Control.BackgroundImage != null && !DisplayInformation.HighContrast) + { ControlPaint.DrawBackgroundImage(e.Graphics, Control.BackgroundImage, Color.Transparent, Control.BackgroundImageLayout, Control.ClientRectangle, bounds, Control.DisplayRectangle.Location, Control.RightToLeft); } } - void PaintWorker(PaintEventArgs e, bool up, CheckState state) { + void PaintWorker(PaintEventArgs e, bool up, CheckState state) + { up = up && state == CheckState.Unchecked; ColorData colors = PaintRender(e.Graphics).Calculate(); LayoutData layout; - if (Application.RenderWithVisualStyles) { + if (Application.RenderWithVisualStyles) + { //don't have the text-pressed-down effect when we use themed painting //this is for consistency with win32 app. layout = PaintLayout(e, true).Layout(); } - else { + else + { layout = PaintLayout(e, up).Layout(); } Graphics g = e.Graphics; - + Button thisbutton = this.Control as Button; - if (Application.RenderWithVisualStyles) { + if (Application.RenderWithVisualStyles) + { PaintThemedButtonBackground(e, Control.ClientRectangle, up); } - else { + else + { Brush backbrush = null; - if (state == CheckState.Indeterminate) { + if (state == CheckState.Indeterminate) + { backbrush = CreateDitherBrush(colors.highlight, colors.buttonFace); } - - try { + + try + { Rectangle bounds = Control.ClientRectangle; - if (up) { + if (up) + { // We are going to draw a 2 pixel border bounds.Inflate(-borderWidth, -borderWidth); } - else { + else + { // We are going to draw a 1 pixel border. bounds.Inflate(-1, -1); } - + PaintButtonBackground(e, bounds, backbrush); } - finally { - if (backbrush != null) { + finally + { + if (backbrush != null) + { backbrush.Dispose(); backbrush = null; } @@ -172,38 +205,47 @@ void PaintWorker(PaintEventArgs e, bool up, CheckState state) { PaintImage(e, layout); //inflate the focus rectangle to be consistent with the behavior of Win32 app - if (Application.RenderWithVisualStyles) { + if (Application.RenderWithVisualStyles) + { layout.focus.Inflate(1, 1); } - if (up & IsHighContrastHighlighted()) { + if (up & IsHighContrastHighlighted()) + { var highlightTextColor = SystemColors.HighlightText; PaintField(e, layout, colors, highlightTextColor, false); - if (Control.Focused && Control.ShowFocusCues) { + if (Control.Focused && Control.ShowFocusCues) + { // drawing focus rectangle of HighlightText color ControlPaint.DrawHighContrastFocusRectangle(g, layout.focus, highlightTextColor); } } - else if (up & IsHighContrastHighlighted()) { + else if (up & IsHighContrastHighlighted()) + { PaintField(e, layout, colors, SystemColors.HighlightText, true); } - else { + else + { PaintField(e, layout, colors, colors.windowText, true); } - if (!Application.RenderWithVisualStyles) { + if (!Application.RenderWithVisualStyles) + { Rectangle r = Control.ClientRectangle; - if (Control.IsDefault) { + if (Control.IsDefault) + { r.Inflate(-1, -1); } DrawDefaultBorder(g, r, colors.windowFrame, this.Control.IsDefault); - if (up) { + if (up) + { Draw3DBorder(g, r, colors, up); } - else { + else + { // contrary to popular belief, not Draw3DBorder(..., false); // ControlPaint.DrawBorder(g, r, colors.buttonShadow, ButtonBorderStyle.Solid); @@ -213,7 +255,8 @@ void PaintWorker(PaintEventArgs e, bool up, CheckState state) { #region Layout - protected override LayoutOptions Layout(PaintEventArgs e) { + protected override LayoutOptions Layout(PaintEventArgs e) + { LayoutOptions layout = PaintLayout(e, /* up = */ false); Debug.Assert(layout.GetPreferredSizeCore(LayoutUtils.MaxSize) == PaintLayout(e, /* up = */ true).GetPreferredSizeCore(LayoutUtils.MaxSize), "The state of up should not effect PreferredSize"); @@ -221,14 +264,15 @@ protected override LayoutOptions Layout(PaintEventArgs e) { } [SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters")] // removed graphics, may have to put it back - private LayoutOptions PaintLayout(PaintEventArgs e, bool up) { + private LayoutOptions PaintLayout(PaintEventArgs e, bool up) + { LayoutOptions layout = CommonLayout(); - layout.textOffset = !up; - layout.everettButtonCompat = !Application.RenderWithVisualStyles; + layout.textOffset = !up; + layout.everettButtonCompat = !Application.RenderWithVisualStyles; return layout; } #endregion - } + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckBoxBaseAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckBoxBaseAdapter.cs index b8b4e76bbfa..b008e56ed5e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckBoxBaseAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckBoxBaseAdapter.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ButtonInternal { +namespace System.Windows.Forms.ButtonInternal +{ using System; using System.Diagnostics; using System.Drawing; @@ -14,60 +15,72 @@ namespace System.Windows.Forms.ButtonInternal { using System.Windows.Forms.VisualStyles; using System.Runtime.InteropServices; - internal abstract class CheckBoxBaseAdapter : CheckableControlBaseAdapter { + internal abstract class CheckBoxBaseAdapter : CheckableControlBaseAdapter + { protected const int flatCheckSize = 11; [ThreadStatic] private static Bitmap checkImageChecked = null; [ThreadStatic] - private static Color checkImageCheckedBackColor = Color.Empty; + private static Color checkImageCheckedBackColor = Color.Empty; [ThreadStatic] - private static Bitmap checkImageIndeterminate = null; + private static Bitmap checkImageIndeterminate = null; [ThreadStatic] - private static Color checkImageIndeterminateBackColor = Color.Empty; + private static Color checkImageIndeterminateBackColor = Color.Empty; - internal CheckBoxBaseAdapter(ButtonBase control) : base(control) {} + internal CheckBoxBaseAdapter(ButtonBase control) : base(control) { } - protected new CheckBox Control { - get { + protected new CheckBox Control + { + get + { return ((CheckBox)base.Control); } } #region Drawing Helpers - protected void DrawCheckFlat(PaintEventArgs e, LayoutData layout, Color checkColor, Color checkBackground, Color checkBorder, ColorData colors) { + protected void DrawCheckFlat(PaintEventArgs e, LayoutData layout, Color checkColor, Color checkBackground, Color checkBorder, ColorData colors) + { Rectangle bounds = layout.checkBounds; // Removed subtracting one for Width and Height. In Everett we needed to do this, // since we were using GDI+ to draw the border. Now that we are using GDI, // we should not do before drawing the border. - if (!layout.options.everettButtonCompat) { + if (!layout.options.everettButtonCompat) + { bounds.Width--; - bounds.Height--; + bounds.Height--; } - using (WindowsGraphics wg = WindowsGraphics.FromGraphics( e.Graphics )) { - using(WindowsPen pen = new WindowsPen(wg.DeviceContext, checkBorder)){ + using (WindowsGraphics wg = WindowsGraphics.FromGraphics(e.Graphics)) + { + using (WindowsPen pen = new WindowsPen(wg.DeviceContext, checkBorder)) + { wg.DrawRectangle(pen, bounds); } // Now subtract, since the rest of the code is like Everett. - if (layout.options.everettButtonCompat) { + if (layout.options.everettButtonCompat) + { bounds.Width--; - bounds.Height--; - } + bounds.Height--; + } bounds.Inflate(-1, -1); } - if (Control.CheckState == CheckState.Indeterminate) { + if (Control.CheckState == CheckState.Indeterminate) + { bounds.Width++; bounds.Height++; DrawDitheredFill(e.Graphics, colors.buttonFace, checkBackground, bounds); } - else { - using( WindowsGraphics wg = WindowsGraphics.FromGraphics( e.Graphics )) { - using (WindowsBrush brush = new WindowsSolidBrush(wg.DeviceContext, checkBackground)) { + else + { + using (WindowsGraphics wg = WindowsGraphics.FromGraphics(e.Graphics)) + { + using (WindowsBrush brush = new WindowsSolidBrush(wg.DeviceContext, checkBackground)) + { // Even though we are using GDI here as opposed to GDI+ in Everett, we still need to add 1. bounds.Width++; bounds.Height++; @@ -76,18 +89,21 @@ protected void DrawCheckFlat(PaintEventArgs e, LayoutData layout, Color checkCol } } DrawCheckOnly(e, layout, colors, checkColor, checkBackground); - + } // used by DataGridViewCheckBoxCell internal static void DrawCheckBackground(bool controlEnabled, CheckState controlCheckState, Graphics g, Rectangle bounds, Color checkColor, Color checkBackground, bool disabledColors, ColorData colors) - { - using ( WindowsGraphics wg = WindowsGraphics.FromGraphics( g )) { + { + using (WindowsGraphics wg = WindowsGraphics.FromGraphics(g)) + { WindowsBrush brush; - if (!controlEnabled && disabledColors) { + if (!controlEnabled && disabledColors) + { brush = new WindowsSolidBrush(wg.DeviceContext, SystemColors.Control); } - else if (controlCheckState == CheckState.Indeterminate && checkBackground == SystemColors.Window && disabledColors) { + else if (controlCheckState == CheckState.Indeterminate && checkBackground == SystemColors.Window && disabledColors) + { Color comboColor = SystemInformation.HighContrast ? SystemColors.ControlDark : SystemColors.Control; byte R = (byte)((comboColor.R + SystemColors.Window.R) / 2); @@ -95,53 +111,66 @@ internal static void DrawCheckBackground(bool controlEnabled, CheckState control byte B = (byte)((comboColor.B + SystemColors.Window.B) / 2); brush = new WindowsSolidBrush(wg.DeviceContext, Color.FromArgb(R, G, B)); } - else { + else + { brush = new WindowsSolidBrush(wg.DeviceContext, checkBackground); } - - try { + + try + { wg.FillRectangle(brush, bounds); } - finally { - if (brush != null) { + finally + { + if (brush != null) + { brush.Dispose(); } } } } - protected void DrawCheckBackground(PaintEventArgs e, Rectangle bounds, Color checkColor, Color checkBackground, bool disabledColors, ColorData colors) { + protected void DrawCheckBackground(PaintEventArgs e, Rectangle bounds, Color checkColor, Color checkBackground, bool disabledColors, ColorData colors) + { // area behind check // - if (Control.CheckState == CheckState.Indeterminate) { + if (Control.CheckState == CheckState.Indeterminate) + { DrawDitheredFill(e.Graphics, colors.buttonFace, checkBackground, bounds); } - else { + else + { DrawCheckBackground(Control.Enabled, Control.CheckState, e.Graphics, bounds, checkColor, checkBackground, disabledColors, colors); } } - protected void DrawCheckOnly(PaintEventArgs e, LayoutData layout, ColorData colors, Color checkColor, Color checkBackground) { + protected void DrawCheckOnly(PaintEventArgs e, LayoutData layout, ColorData colors, Color checkColor, Color checkBackground) + { DrawCheckOnly(flatCheckSize, Control.Checked, Control.Enabled, Control.CheckState, e.Graphics, layout, colors, checkColor, checkBackground); } - + // used by DataGridViewCheckBoxCell - internal static void DrawCheckOnly(int checkSize, bool controlChecked, bool controlEnabled, CheckState controlCheckState, Graphics g, LayoutData layout, ColorData colors, Color checkColor, Color checkBackground) { + internal static void DrawCheckOnly(int checkSize, bool controlChecked, bool controlEnabled, CheckState controlCheckState, Graphics g, LayoutData layout, ColorData colors, Color checkColor, Color checkBackground) + { // check // - if (controlChecked) { - if (!controlEnabled) { + if (controlChecked) + { + if (!controlEnabled) + { checkColor = colors.buttonShadow; } - else if (controlCheckState == CheckState.Indeterminate) { + else if (controlCheckState == CheckState.Indeterminate) + { checkColor = SystemInformation.HighContrast ? colors.highlight : colors.buttonShadow; } - + Rectangle fullSize = layout.checkBounds; - - if (fullSize.Width == checkSize) { + + if (fullSize.Width == checkSize) + { fullSize.Width++; fullSize.Height++; } @@ -150,36 +179,44 @@ internal static void DrawCheckOnly(int checkSize, bool controlChecked, bool cont fullSize.Height++; Bitmap checkImage = null; - if (controlCheckState == CheckState.Checked) { + if (controlCheckState == CheckState.Checked) + { checkImage = GetCheckBoxImage(checkColor, fullSize, ref checkImageCheckedBackColor, ref checkImageChecked); - } else { + } + else + { Debug.Assert(controlCheckState == CheckState.Indeterminate, "we want to paint the check box only if the item is checked or indeterminate"); checkImage = GetCheckBoxImage(checkColor, fullSize, ref checkImageIndeterminateBackColor, ref checkImageIndeterminate); } - if (layout.options.everettButtonCompat) { + if (layout.options.everettButtonCompat) + { fullSize.Y -= 1; } - else { + else + { fullSize.Y -= 2; } ControlPaint.DrawImageColorized(g, checkImage, fullSize, checkColor); } } - - internal static Rectangle DrawPopupBorder(Graphics g, Rectangle r, ColorData colors) { - using (WindowsGraphics wg = WindowsGraphics.FromGraphics( g )) { - - using( WindowsPen high = new WindowsPen(wg.DeviceContext, colors.highlight), + + internal static Rectangle DrawPopupBorder(Graphics g, Rectangle r, ColorData colors) + { + using (WindowsGraphics wg = WindowsGraphics.FromGraphics(g)) + { + + using (WindowsPen high = new WindowsPen(wg.DeviceContext, colors.highlight), shadow = new WindowsPen(wg.DeviceContext, colors.buttonShadow), - face = new WindowsPen(wg.DeviceContext, colors.buttonFace)) { - - wg.DrawLine(high, r.Right-1 , r.Top, r.Right-1, r.Bottom); - wg.DrawLine(high, r.Left, r.Bottom-1, r.Right, r.Bottom-1); + face = new WindowsPen(wg.DeviceContext, colors.buttonFace)) + { - wg.DrawLine(shadow, r.Left, r.Top, r.Left , r.Bottom); - wg.DrawLine(shadow, r.Left, r.Top, r.Right- 1, r.Top); + wg.DrawLine(high, r.Right - 1, r.Top, r.Right - 1, r.Bottom); + wg.DrawLine(high, r.Left, r.Bottom - 1, r.Right, r.Bottom - 1); + + wg.DrawLine(shadow, r.Left, r.Top, r.Left, r.Bottom); + wg.DrawLine(shadow, r.Left, r.Top, r.Right - 1, r.Top); wg.DrawLine(face, r.Right - 2, r.Top + 1, r.Right - 2, r.Bottom - 1); wg.DrawLine(face, r.Left + 1, r.Bottom - 2, r.Right - 1, r.Bottom - 2); @@ -189,50 +226,62 @@ internal static Rectangle DrawPopupBorder(Graphics g, Rectangle r, ColorData col return r; } - protected ButtonState GetState() { + protected ButtonState GetState() + { ButtonState style = (ButtonState)0; - if (Control.CheckState == CheckState.Unchecked) { + if (Control.CheckState == CheckState.Unchecked) + { style |= ButtonState.Normal; } - else { + else + { style |= ButtonState.Checked; } - if (!Control.Enabled) { + if (!Control.Enabled) + { style |= ButtonState.Inactive; } - if (Control.MouseIsDown) { + if (Control.MouseIsDown) + { style |= ButtonState.Pushed; } return style; } - - protected void DrawCheckBox(PaintEventArgs e, LayoutData layout) { + + protected void DrawCheckBox(PaintEventArgs e, LayoutData layout) + { Graphics g = e.Graphics; - + ButtonState style = GetState(); - if (Control.CheckState == CheckState.Indeterminate) { - if (Application.RenderWithVisualStyles) { + if (Control.CheckState == CheckState.Indeterminate) + { + if (Application.RenderWithVisualStyles) + { CheckBoxRenderer.DrawCheckBox(g, new Point(layout.checkBounds.Left, layout.checkBounds.Top), CheckBoxRenderer.ConvertFromButtonState(style, true, Control.MouseIsOver), Control.HandleInternal); } - else { + else + { ControlPaint.DrawMixedCheckBox(g, layout.checkBounds, style); } } - else { - if (Application.RenderWithVisualStyles) { + else + { + if (Application.RenderWithVisualStyles) + { CheckBoxRenderer.DrawCheckBox(g, new Point(layout.checkBounds.Left, layout.checkBounds.Top), CheckBoxRenderer.ConvertFromButtonState(style, false, Control.MouseIsOver), Control.HandleInternal); } - else { + else + { ControlPaint.DrawCheckBox(g, layout.checkBounds, style); } } } - + #endregion private static Bitmap GetCheckBoxImage(Color checkColor, Rectangle fullSize, ref Color cacheCheckColor, ref Bitmap cacheCheckImage) @@ -240,7 +289,8 @@ private static Bitmap GetCheckBoxImage(Color checkColor, Rectangle fullSize, ref if (cacheCheckImage != null && cacheCheckColor.Equals(checkColor) && cacheCheckImage.Width == fullSize.Width && - cacheCheckImage.Height == fullSize.Height) { + cacheCheckImage.Height == fullSize.Height) + { return cacheCheckImage; } @@ -257,10 +307,13 @@ private static Bitmap GetCheckBoxImage(Color checkColor, Rectangle fullSize, ref Graphics offscreen = Graphics.FromImage(bitmap); offscreen.Clear(Color.Transparent); IntPtr dc = offscreen.GetHdc(); - try { + try + { SafeNativeMethods.DrawFrameControl(new HandleRef(offscreen, dc), ref rcCheck, NativeMethods.DFC_MENU, NativeMethods.DFCS_MENUCHECK); - } finally { + } + finally + { offscreen.ReleaseHdcInternal(dc); offscreen.Dispose(); } @@ -272,8 +325,10 @@ private static Bitmap GetCheckBoxImage(Color checkColor, Rectangle fullSize, ref return cacheCheckImage; } - protected void AdjustFocusRectangle(LayoutData layout) { - if (string.IsNullOrEmpty(Control.Text)) { + protected void AdjustFocusRectangle(LayoutData layout) + { + if (string.IsNullOrEmpty(Control.Text)) + { // When a CheckBox has no text, AutoSize sets the size to zero // and thus there's no place around which to draw the focus rectangle. // So, when AutoSize == true we want the focus rectangle to be rendered inside the box. @@ -282,12 +337,13 @@ protected void AdjustFocusRectangle(LayoutData layout) { } } - internal override LayoutOptions CommonLayout() { + internal override LayoutOptions CommonLayout() + { LayoutOptions layout = base.CommonLayout(); - layout.checkAlign = Control.CheckAlign; - layout.textOffset = false; - layout.shadowedText = !Control.Enabled; - layout.layoutRTL = RightToLeft.Yes == Control.RightToLeft; + layout.checkAlign = Control.CheckAlign; + layout.textOffset = false; + layout.shadowedText = !Control.Enabled; + layout.layoutRTL = RightToLeft.Yes == Control.RightToLeft; return layout; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckBoxFlatAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckBoxFlatAdapter.cs index a5768f640f4..8719026cc97 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckBoxFlatAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckBoxFlatAdapter.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ButtonInternal { +namespace System.Windows.Forms.ButtonInternal +{ using System; using System.Diagnostics; using System.Drawing; @@ -11,56 +12,70 @@ namespace System.Windows.Forms.ButtonInternal { using System.Drawing.Text; using System.Windows.Forms; - internal class CheckBoxFlatAdapter : CheckBoxBaseAdapter { + internal class CheckBoxFlatAdapter : CheckBoxBaseAdapter + { - internal CheckBoxFlatAdapter(ButtonBase control) : base(control) {} - - internal override void PaintDown(PaintEventArgs e, CheckState state) { - if (Control.Appearance == Appearance.Button) { + internal CheckBoxFlatAdapter(ButtonBase control) : base(control) { } + + internal override void PaintDown(PaintEventArgs e, CheckState state) + { + if (Control.Appearance == Appearance.Button) + { ButtonAdapter.PaintDown(e, Control.CheckState); return; } ColorData colors = PaintFlatRender(e.Graphics).Calculate(); - if (Control.Enabled) { + if (Control.Enabled) + { PaintFlatWorker(e, colors.windowText, colors.highlight, colors.windowFrame, colors); } - else { + else + { PaintFlatWorker(e, colors.buttonShadow, colors.buttonFace, colors.buttonShadow, colors); } - } - - internal override void PaintOver(PaintEventArgs e, CheckState state) { - if (Control.Appearance == Appearance.Button) { + } + + internal override void PaintOver(PaintEventArgs e, CheckState state) + { + if (Control.Appearance == Appearance.Button) + { ButtonAdapter.PaintOver(e, Control.CheckState); return; } ColorData colors = PaintFlatRender(e.Graphics).Calculate(); - if (Control.Enabled) { + if (Control.Enabled) + { PaintFlatWorker(e, colors.windowText, colors.lowHighlight, colors.windowFrame, colors); } - else { + else + { PaintFlatWorker(e, colors.buttonShadow, colors.buttonFace, colors.buttonShadow, colors); } } - - internal override void PaintUp(PaintEventArgs e, CheckState state) { - if (Control.Appearance == Appearance.Button) { + + internal override void PaintUp(PaintEventArgs e, CheckState state) + { + if (Control.Appearance == Appearance.Button) + { ButtonAdapter.PaintUp(e, Control.CheckState); return; } ColorData colors = PaintFlatRender(e.Graphics).Calculate(); - if (Control.Enabled) { + if (Control.Enabled) + { PaintFlatWorker(e, colors.windowText, colors.highlight, colors.windowFrame, colors); } - else { + else + { PaintFlatWorker(e, colors.buttonShadow, colors.buttonFace, colors.buttonShadow, colors); } } - - private void PaintFlatWorker(PaintEventArgs e, Color checkColor, Color checkBackground, Color checkBorder, ColorData colors) { + + private void PaintFlatWorker(PaintEventArgs e, Color checkColor, Color checkBackground, Color checkBorder, ColorData colors) + { System.Drawing.Graphics g = e.Graphics; LayoutData layout = Layout(e).Layout(); PaintButtonBackground(e, Control.ClientRectangle, null); @@ -73,20 +88,24 @@ private void PaintFlatWorker(PaintEventArgs e, Color checkColor, Color checkBack #region Layout - private new ButtonFlatAdapter ButtonAdapter { - get { + private new ButtonFlatAdapter ButtonAdapter + { + get + { return ((ButtonFlatAdapter)base.ButtonAdapter); } } - protected override ButtonBaseAdapter CreateButtonAdapter() { + protected override ButtonBaseAdapter CreateButtonAdapter() + { return new ButtonFlatAdapter(Control); } - protected override LayoutOptions Layout(PaintEventArgs e) { + protected override LayoutOptions Layout(PaintEventArgs e) + { LayoutOptions layout = CommonLayout(); - layout.checkSize = (int)(flatCheckSize * GetDpiScaleRatio(e.Graphics)); - layout.shadowedText = false; + layout.checkSize = (int)(flatCheckSize * GetDpiScaleRatio(e.Graphics)); + layout.shadowedText = false; return layout; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckBoxPopupAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckBoxPopupAdapter.cs index 7726504239b..d1b7be9c040 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckBoxPopupAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckBoxPopupAdapter.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ButtonInternal { +namespace System.Windows.Forms.ButtonInternal +{ using System; using System.Diagnostics; using System.Drawing; @@ -12,18 +13,22 @@ namespace System.Windows.Forms.ButtonInternal { using System.Windows.Forms; using System.Windows.Forms.Layout; using System.Diagnostics.CodeAnalysis; - - internal class CheckBoxPopupAdapter : CheckBoxBaseAdapter { - internal CheckBoxPopupAdapter(ButtonBase control) : base(control) {} + internal class CheckBoxPopupAdapter : CheckBoxBaseAdapter + { - internal override void PaintUp(PaintEventArgs e, CheckState state) { - if (Control.Appearance == Appearance.Button) { + internal CheckBoxPopupAdapter(ButtonBase control) : base(control) { } + + internal override void PaintUp(PaintEventArgs e, CheckState state) + { + if (Control.Appearance == Appearance.Button) + { ButtonPopupAdapter adapter = new ButtonPopupAdapter(Control); adapter.PaintUp(e, Control.CheckState); } - else { + else + { System.Drawing.Graphics g = e.Graphics; ColorData colors = PaintPopupRender(e.Graphics).Calculate(); LayoutData layout = PaintPopupLayout(e, false).Layout(); @@ -32,9 +37,9 @@ internal override void PaintUp(PaintEventArgs e, CheckState state) { PaintButtonBackground(e, Control.ClientRectangle, null); PaintImage(e, layout); - + DrawCheckBackground(e, layout.checkBounds, colors.windowText, colors.options.highContrast ? colors.buttonFace : colors.highlight, true, colors); - DrawFlatBorder(e.Graphics, layout.checkBounds, + DrawFlatBorder(e.Graphics, layout.checkBounds, (colors.options.highContrast && !Control.Enabled) ? colors.windowFrame : colors.buttonShadow); DrawCheckOnly(e, layout, colors, colors.windowText, colors.highlight); @@ -42,14 +47,17 @@ internal override void PaintUp(PaintEventArgs e, CheckState state) { PaintField(e, layout, colors, colors.windowText, true); } } - - internal override void PaintOver(PaintEventArgs e, CheckState state) { + + internal override void PaintOver(PaintEventArgs e, CheckState state) + { System.Drawing.Graphics g = e.Graphics; - if (Control.Appearance == Appearance.Button) { + if (Control.Appearance == Appearance.Button) + { ButtonPopupAdapter adapter = new ButtonPopupAdapter(Control); adapter.PaintOver(e, Control.CheckState); } - else { + else + { ColorData colors = PaintPopupRender(e.Graphics).Calculate(); LayoutData layout = PaintPopupLayout(e, true).Layout(); @@ -57,12 +65,13 @@ internal override void PaintOver(PaintEventArgs e, CheckState state) { PaintButtonBackground(e, Control.ClientRectangle, null); PaintImage(e, layout); - + DrawCheckBackground(e, layout.checkBounds, colors.windowText, colors.options.highContrast ? colors.buttonFace : colors.highlight, true, colors); DrawPopupBorder(g, layout.checkBounds, colors); DrawCheckOnly(e, layout, colors, colors.windowText, colors.highlight); - if (!string.IsNullOrEmpty(Control.Text)) { + if (!string.IsNullOrEmpty(Control.Text)) + { e.Graphics.Clip = original; e.Graphics.ExcludeClip(layout.checkArea); } @@ -71,13 +80,16 @@ internal override void PaintOver(PaintEventArgs e, CheckState state) { PaintField(e, layout, colors, colors.windowText, true); } } - - internal override void PaintDown(PaintEventArgs e, CheckState state) { - if (Control.Appearance == Appearance.Button) { + + internal override void PaintDown(PaintEventArgs e, CheckState state) + { + if (Control.Appearance == Appearance.Button) + { ButtonPopupAdapter adapter = new ButtonPopupAdapter(Control); adapter.PaintDown(e, Control.CheckState); } - else { + else + { System.Drawing.Graphics g = e.Graphics; ColorData colors = PaintPopupRender(e.Graphics).Calculate(); LayoutData layout = PaintPopupLayout(e, true).Layout(); @@ -86,7 +98,7 @@ internal override void PaintDown(PaintEventArgs e, CheckState state) { PaintButtonBackground(e, Control.ClientRectangle, null); PaintImage(e, layout); - + DrawCheckBackground(e, layout.checkBounds, colors.windowText, colors.buttonFace, true, colors); DrawPopupBorder(g, layout.checkBounds, colors); DrawCheckOnly(e, layout, colors, colors.windowText, colors.buttonFace); @@ -98,11 +110,13 @@ internal override void PaintDown(PaintEventArgs e, CheckState state) { #region Layout - protected override ButtonBaseAdapter CreateButtonAdapter() { + protected override ButtonBaseAdapter CreateButtonAdapter() + { return new ButtonPopupAdapter(Control); } - protected override LayoutOptions Layout(PaintEventArgs e) { + protected override LayoutOptions Layout(PaintEventArgs e) + { LayoutOptions layout = PaintPopupLayout(e, /* up = */ true); Debug.Assert(layout.GetPreferredSizeCore(LayoutUtils.MaxSize) == PaintPopupLayout(e, /* up = */ false).GetPreferredSizeCore(LayoutUtils.MaxSize), @@ -118,10 +132,12 @@ internal static LayoutOptions PaintPopupLayout(Graphics g, bool show3D, int chec { LayoutOptions layout = CommonLayout(clientRectangle, padding, isDefault, font, text, enabled, textAlign, rtl); layout.shadowedText = false; - if (show3D) { + if (show3D) + { layout.checkSize = (int)(checkSize * GetDpiScaleRatio(g, control) + 1); } - else { + else + { layout.checkSize = (int)(checkSize * GetDpiScaleRatio(g, control)); layout.checkPaddingSize = 1; } @@ -129,13 +145,16 @@ internal static LayoutOptions PaintPopupLayout(Graphics g, bool show3D, int chec } [SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters")] // removed graphics, may have to put it back - private LayoutOptions PaintPopupLayout(PaintEventArgs e, bool show3D) { + private LayoutOptions PaintPopupLayout(PaintEventArgs e, bool show3D) + { LayoutOptions layout = CommonLayout(); layout.shadowedText = false; - if (show3D) { + if (show3D) + { layout.checkSize = (int)(flatCheckSize * GetDpiScaleRatio(e.Graphics) + 1); } - else { + else + { layout.checkSize = (int)(flatCheckSize * GetDpiScaleRatio(e.Graphics)); layout.checkPaddingSize = 1; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckBoxStandardAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckBoxStandardAdapter.cs index cd9f7ec627e..5846461c966 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckBoxStandardAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckBoxStandardAdapter.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ButtonInternal { +namespace System.Windows.Forms.ButtonInternal +{ using System; using System.Diagnostics; using System.Drawing; @@ -12,38 +13,45 @@ namespace System.Windows.Forms.ButtonInternal { using System.Windows.Forms; using System.Windows.Forms.Layout; - internal sealed class CheckBoxStandardAdapter : CheckBoxBaseAdapter { + internal sealed class CheckBoxStandardAdapter : CheckBoxBaseAdapter + { - internal CheckBoxStandardAdapter(ButtonBase control) : base(control) {} + internal CheckBoxStandardAdapter(ButtonBase control) : base(control) { } internal override void PaintUp(PaintEventArgs e, CheckState state) { - if (Control.Appearance == Appearance.Button) { - ButtonAdapter.PaintUp(e, Control.CheckState); + if (Control.Appearance == Appearance.Button) + { + ButtonAdapter.PaintUp(e, Control.CheckState); } - else { + else + { ColorData colors = PaintRender(e.Graphics).Calculate(); LayoutData layout = Layout(e).Layout(); PaintButtonBackground(e, Control.ClientRectangle, null); - if (!layout.options.everettButtonCompat) { - layout.textBounds.Offset(-1, -1); + if (!layout.options.everettButtonCompat) + { + layout.textBounds.Offset(-1, -1); } layout.imageBounds.Offset(-1, -1); AdjustFocusRectangle(layout); - if (!string.IsNullOrEmpty(Control.Text)) { + if (!string.IsNullOrEmpty(Control.Text)) + { //minor adjustment to make sure the appearance is exactly the same as Win32 app. int focusRectFixup = layout.focus.X & 0x1; // if it's odd, subtract one pixel for fixup. - if (!Application.RenderWithVisualStyles) { + if (!Application.RenderWithVisualStyles) + { focusRectFixup = 1 - focusRectFixup; } layout.focus.Offset(-(focusRectFixup + 1), -2); layout.focus.Width = layout.textBounds.Width + layout.imageBounds.Width - 1; layout.focus.Intersect(layout.textBounds); - if (layout.options.textAlign != LayoutUtils.AnyLeft && layout.options.useCompatibleTextRendering && layout.options.font.Italic) { + if (layout.options.textAlign != LayoutUtils.AnyLeft && layout.options.useCompatibleTextRendering && layout.options.font.Italic) + { // fixup for GDI+ text rendering. layout.focus.Width += 2; } @@ -54,35 +62,46 @@ internal override void PaintUp(PaintEventArgs e, CheckState state) PaintField(e, layout, colors, colors.windowText, true); } } - - internal override void PaintDown(PaintEventArgs e, CheckState state) { - if (Control.Appearance == Appearance.Button) { - ButtonAdapter.PaintDown(e, Control.CheckState); + + internal override void PaintDown(PaintEventArgs e, CheckState state) + { + if (Control.Appearance == Appearance.Button) + { + ButtonAdapter.PaintDown(e, Control.CheckState); } - else { + else + { PaintUp(e, state); } } - - internal override void PaintOver(PaintEventArgs e, CheckState state) { - if (Control.Appearance == Appearance.Button) { - ButtonAdapter.PaintOver(e, Control.CheckState); + + internal override void PaintOver(PaintEventArgs e, CheckState state) + { + if (Control.Appearance == Appearance.Button) + { + ButtonAdapter.PaintOver(e, Control.CheckState); } - else { + else + { PaintUp(e, state); } - } + } - internal override Size GetPreferredSizeCore(Size proposedSize) { - if (Control.Appearance == Appearance.Button) { - ButtonStandardAdapter adapter = new ButtonStandardAdapter(Control); + internal override Size GetPreferredSizeCore(Size proposedSize) + { + if (Control.Appearance == Appearance.Button) + { + ButtonStandardAdapter adapter = new ButtonStandardAdapter(Control); return adapter.GetPreferredSizeCore(proposedSize); - } - else { - using (Graphics measurementGraphics = WindowsFormsUtils.CreateMeasurementGraphics()) { - using (PaintEventArgs pe = new PaintEventArgs(measurementGraphics, new Rectangle())) { + } + else + { + using (Graphics measurementGraphics = WindowsFormsUtils.CreateMeasurementGraphics()) + { + using (PaintEventArgs pe = new PaintEventArgs(measurementGraphics, new Rectangle())) + { LayoutOptions options = Layout(pe); - + return options.GetPreferredSizeCore(proposedSize); } } @@ -91,31 +110,40 @@ internal override Size GetPreferredSizeCore(Size proposedSize) { #region Layout - private new ButtonStandardAdapter ButtonAdapter { - get { + private new ButtonStandardAdapter ButtonAdapter + { + get + { return ((ButtonStandardAdapter)base.ButtonAdapter); } } - protected override ButtonBaseAdapter CreateButtonAdapter() { + protected override ButtonBaseAdapter CreateButtonAdapter() + { return new ButtonStandardAdapter(Control); } - protected override LayoutOptions Layout(PaintEventArgs e) { + protected override LayoutOptions Layout(PaintEventArgs e) + { LayoutOptions layout = CommonLayout(); - layout.checkPaddingSize = 1; - layout.everettButtonCompat = !Application.RenderWithVisualStyles; + layout.checkPaddingSize = 1; + layout.everettButtonCompat = !Application.RenderWithVisualStyles; - if (Application.RenderWithVisualStyles) { - using (Graphics g = WindowsFormsUtils.CreateMeasurementGraphics()) { + if (Application.RenderWithVisualStyles) + { + using (Graphics g = WindowsFormsUtils.CreateMeasurementGraphics()) + { layout.checkSize = CheckBoxRenderer.GetGlyphSize(g, CheckBoxRenderer.ConvertFromButtonState(GetState(), true, Control.MouseIsOver), Control.HandleInternal).Width; } } - else { - if (DpiHelper.IsPerMonitorV2Awareness) { + else + { + if (DpiHelper.IsPerMonitorV2Awareness) + { layout.checkSize = Control.LogicalToDeviceUnits(layout.checkSize); } - else { + else + { layout.checkSize = (int)(layout.checkSize * GetDpiScaleRatio(e.Graphics)); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckableControlBaseAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckableControlBaseAdapter.cs index e95cf4d17ff..2b6b401a1fc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckableControlBaseAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckableControlBaseAdapter.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ButtonInternal { +namespace System.Windows.Forms.ButtonInternal +{ using System; using System.Diagnostics; using System.Drawing; @@ -14,45 +15,57 @@ namespace System.Windows.Forms.ButtonInternal { /// /// Common class for RadioButtonBaseAdapter and CheckBoxBaseAdapter /// - internal abstract class CheckableControlBaseAdapter : ButtonBaseAdapter { + internal abstract class CheckableControlBaseAdapter : ButtonBaseAdapter + { private const int standardCheckSize = 13; private ButtonBaseAdapter buttonAdapter; - internal CheckableControlBaseAdapter(ButtonBase control) : base(control) {} + internal CheckableControlBaseAdapter(ButtonBase control) : base(control) { } - protected ButtonBaseAdapter ButtonAdapter { - get { - if (buttonAdapter == null) { + protected ButtonBaseAdapter ButtonAdapter + { + get + { + if (buttonAdapter == null) + { buttonAdapter = CreateButtonAdapter(); } return buttonAdapter; } } - internal override Size GetPreferredSizeCore(Size proposedSize) { - if (Appearance == Appearance.Button) { + internal override Size GetPreferredSizeCore(Size proposedSize) + { + if (Appearance == Appearance.Button) + { return ButtonAdapter.GetPreferredSizeCore(proposedSize); } - using (Graphics measurementGraphics = WindowsFormsUtils.CreateMeasurementGraphics()) { - using (PaintEventArgs pe = new PaintEventArgs(measurementGraphics, new Rectangle())) { + using (Graphics measurementGraphics = WindowsFormsUtils.CreateMeasurementGraphics()) + { + using (PaintEventArgs pe = new PaintEventArgs(measurementGraphics, new Rectangle())) + { LayoutOptions options = Layout(pe); return options.GetPreferredSizeCore(proposedSize); } - } + } } - + protected abstract ButtonBaseAdapter CreateButtonAdapter(); - private Appearance Appearance { - get { + private Appearance Appearance + { + get + { CheckBox checkBox = Control as CheckBox; - if(checkBox != null) { + if (checkBox != null) + { return checkBox.Appearance; } RadioButton radioButton = Control as RadioButton; - if(radioButton != null) { + if (radioButton != null) + { return radioButton.Appearance; } @@ -61,22 +74,25 @@ private Appearance Appearance { } } - internal override LayoutOptions CommonLayout() { + internal override LayoutOptions CommonLayout() + { LayoutOptions layout = base.CommonLayout(); layout.growBorderBy1PxWhenDefault = false; - layout.borderSize = 0; - layout.paddingSize = 0; - layout.maxFocus = false; + layout.borderSize = 0; + layout.paddingSize = 0; + layout.maxFocus = false; layout.focusOddEvenFixup = true; - layout.checkSize = standardCheckSize; + layout.checkSize = standardCheckSize; return layout; } - internal double GetDpiScaleRatio(Graphics g) { + internal double GetDpiScaleRatio(Graphics g) + { return GetDpiScaleRatio(g, Control); } - internal static double GetDpiScaleRatio(Graphics g, Control control) { + internal static double GetDpiScaleRatio(Graphics g, Control control) + { if (DpiHelper.IsPerMonitorV2Awareness && control != null && control.IsHandleCreated) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/RadioButtonBaseAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/RadioButtonBaseAdapter.cs index 3d2a5d0dada..c4f1d50ca1b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/RadioButtonBaseAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/RadioButtonBaseAdapter.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ButtonInternal { +namespace System.Windows.Forms.ButtonInternal +{ using System; using System.Diagnostics; using System.Drawing; @@ -13,34 +14,42 @@ namespace System.Windows.Forms.ButtonInternal { using System.Windows.Forms; using System.Windows.Forms.VisualStyles; - internal abstract class RadioButtonBaseAdapter : CheckableControlBaseAdapter { + internal abstract class RadioButtonBaseAdapter : CheckableControlBaseAdapter + { - internal RadioButtonBaseAdapter(ButtonBase control) : base(control) {} + internal RadioButtonBaseAdapter(ButtonBase control) : base(control) { } - protected new RadioButton Control { - get { + protected new RadioButton Control + { + get + { return ((RadioButton)base.Control); } } #region Drawing helpers - protected void DrawCheckFlat(PaintEventArgs e, LayoutData layout, Color checkColor, Color checkBackground, Color checkBorder) { + protected void DrawCheckFlat(PaintEventArgs e, LayoutData layout, Color checkColor, Color checkBackground, Color checkBorder) + { DrawCheckBackgroundFlat(e, layout.checkBounds, checkBorder, checkBackground); DrawCheckOnly(e, layout, checkColor, checkBackground, true); } - protected void DrawCheckBackground3DLite(PaintEventArgs e, Rectangle bounds, Color checkColor, Color checkBackground, ColorData colors, bool disabledColors) { - Graphics g = e.Graphics; - + protected void DrawCheckBackground3DLite(PaintEventArgs e, Rectangle bounds, Color checkColor, Color checkBackground, ColorData colors, bool disabledColors) + { + Graphics g = e.Graphics; + Color field = checkBackground; - if (!Control.Enabled && disabledColors) { + if (!Control.Enabled && disabledColors) + { field = SystemColors.Control; } - using (Brush fieldBrush = new SolidBrush(field)) { + using (Brush fieldBrush = new SolidBrush(field)) + { using (Pen dark = new Pen(colors.buttonShadow), light = new Pen(colors.buttonFace), - lightlight = new Pen(colors.highlight)) { + lightlight = new Pen(colors.highlight)) + { bounds.Width--; bounds.Height--; @@ -56,13 +65,16 @@ protected void DrawCheckBackground3DLite(PaintEventArgs e, Rectangle bounds, Col } } - protected void DrawCheckBackgroundFlat(PaintEventArgs e, Rectangle bounds, Color borderColor, Color checkBackground) { + protected void DrawCheckBackgroundFlat(PaintEventArgs e, Rectangle bounds, Color borderColor, Color checkBackground) + { Color field = checkBackground; Color border = borderColor; - - if (!Control.Enabled) { + + if (!Control.Enabled) + { // if we are not in HighContrast mode OR we opted into the legacy behavior - if (!SystemInformation.HighContrast) { + if (!SystemInformation.HighContrast) + { border = ControlPaint.ContrastControlDark; } // otherwise we are in HighContrast mode @@ -71,18 +83,23 @@ protected void DrawCheckBackgroundFlat(PaintEventArgs e, Rectangle bounds, Color double scale = GetDpiScaleRatio(e.Graphics); - using( WindowsGraphics wg = WindowsGraphics.FromGraphics(e.Graphics) ) { - using( WindowsPen borderPen = new WindowsPen(wg.DeviceContext, border) ) { - using( WindowsBrush fieldBrush = new WindowsSolidBrush(wg.DeviceContext, field) ) { + using (WindowsGraphics wg = WindowsGraphics.FromGraphics(e.Graphics)) + { + using (WindowsPen borderPen = new WindowsPen(wg.DeviceContext, border)) + { + using (WindowsBrush fieldBrush = new WindowsSolidBrush(wg.DeviceContext, field)) + { // In high DPI mode when we draw ellipse as three rectantles, // the quality of ellipse is poor. Draw it directly as ellipse - if(scale > 1.1) { + if (scale > 1.1) + { bounds.Width--; bounds.Height--; wg.DrawAndFillEllipse(borderPen, fieldBrush, bounds); bounds.Inflate(-1, -1); } - else { + else + { DrawAndFillEllipse(wg, borderPen, fieldBrush, bounds); } } @@ -90,109 +107,126 @@ protected void DrawCheckBackgroundFlat(PaintEventArgs e, Rectangle bounds, Color } } - // Helper method to overcome the poor GDI ellipse drawing routine - private static void DrawAndFillEllipse(WindowsGraphics wg, WindowsPen borderPen, WindowsBrush fieldBrush, Rectangle bounds) - { - Debug.Assert(wg != null,"Calling DrawAndFillEllipse with null wg"); - if (wg == null) { + // Helper method to overcome the poor GDI ellipse drawing routine + private static void DrawAndFillEllipse(WindowsGraphics wg, WindowsPen borderPen, WindowsBrush fieldBrush, Rectangle bounds) + { + Debug.Assert(wg != null, "Calling DrawAndFillEllipse with null wg"); + if (wg == null) + { return; - } - - wg.FillRectangle(fieldBrush, new Rectangle(bounds.X + 2, bounds.Y + 2, 8, 8)); - wg.FillRectangle(fieldBrush, new Rectangle(bounds.X + 4, bounds.Y + 1, 4, 10)); - wg.FillRectangle(fieldBrush, new Rectangle(bounds.X + 1, bounds.Y + 4, 10, 4)); + } - wg.DrawLine(borderPen, new Point(bounds.X + 4, bounds.Y + 0), new Point(bounds.X + 8, bounds.Y + 0)); - wg.DrawLine(borderPen, new Point(bounds.X + 4, bounds.Y + 11), new Point(bounds.X + 8, bounds.Y + 11)); + wg.FillRectangle(fieldBrush, new Rectangle(bounds.X + 2, bounds.Y + 2, 8, 8)); + wg.FillRectangle(fieldBrush, new Rectangle(bounds.X + 4, bounds.Y + 1, 4, 10)); + wg.FillRectangle(fieldBrush, new Rectangle(bounds.X + 1, bounds.Y + 4, 10, 4)); - wg.DrawLine(borderPen, new Point(bounds.X + 2, bounds.Y + 1), new Point(bounds.X + 4, bounds.Y + 1)); - wg.DrawLine(borderPen, new Point(bounds.X + 8, bounds.Y + 1), new Point(bounds.X + 10, bounds.Y + 1)); + wg.DrawLine(borderPen, new Point(bounds.X + 4, bounds.Y + 0), new Point(bounds.X + 8, bounds.Y + 0)); + wg.DrawLine(borderPen, new Point(bounds.X + 4, bounds.Y + 11), new Point(bounds.X + 8, bounds.Y + 11)); - wg.DrawLine(borderPen, new Point(bounds.X + 2, bounds.Y + 10), new Point(bounds.X + 4, bounds.Y + 10)); - wg.DrawLine(borderPen, new Point(bounds.X + 8, bounds.Y + 10), new Point(bounds.X + 10, bounds.Y + 10)); + wg.DrawLine(borderPen, new Point(bounds.X + 2, bounds.Y + 1), new Point(bounds.X + 4, bounds.Y + 1)); + wg.DrawLine(borderPen, new Point(bounds.X + 8, bounds.Y + 1), new Point(bounds.X + 10, bounds.Y + 1)); - wg.DrawLine(borderPen, new Point(bounds.X + 0, bounds.Y + 4), new Point(bounds.X + 0, bounds.Y + 8)); - wg.DrawLine(borderPen, new Point(bounds.X + 11, bounds.Y + 4), new Point(bounds.X + 11, bounds.Y + 8)); + wg.DrawLine(borderPen, new Point(bounds.X + 2, bounds.Y + 10), new Point(bounds.X + 4, bounds.Y + 10)); + wg.DrawLine(borderPen, new Point(bounds.X + 8, bounds.Y + 10), new Point(bounds.X + 10, bounds.Y + 10)); - wg.DrawLine(borderPen, new Point(bounds.X + 1, bounds.Y + 2), new Point(bounds.X + 1, bounds.Y + 4)); - wg.DrawLine(borderPen, new Point(bounds.X + 1, bounds.Y + 8), new Point(bounds.X + 1, bounds.Y + 10)); + wg.DrawLine(borderPen, new Point(bounds.X + 0, bounds.Y + 4), new Point(bounds.X + 0, bounds.Y + 8)); + wg.DrawLine(borderPen, new Point(bounds.X + 11, bounds.Y + 4), new Point(bounds.X + 11, bounds.Y + 8)); - wg.DrawLine(borderPen, new Point(bounds.X + 10, bounds.Y + 2), new Point(bounds.X + 10, bounds.Y + 4)); - wg.DrawLine(borderPen, new Point(bounds.X + 10, bounds.Y + 8), new Point(bounds.X + 10, bounds.Y + 10)); - } + wg.DrawLine(borderPen, new Point(bounds.X + 1, bounds.Y + 2), new Point(bounds.X + 1, bounds.Y + 4)); + wg.DrawLine(borderPen, new Point(bounds.X + 1, bounds.Y + 8), new Point(bounds.X + 1, bounds.Y + 10)); + + wg.DrawLine(borderPen, new Point(bounds.X + 10, bounds.Y + 2), new Point(bounds.X + 10, bounds.Y + 4)); + wg.DrawLine(borderPen, new Point(bounds.X + 10, bounds.Y + 8), new Point(bounds.X + 10, bounds.Y + 10)); + } private static int GetScaledNumber(int n, double scale) { return (int)(n * scale); } - protected void DrawCheckOnly(PaintEventArgs e, LayoutData layout, Color checkColor, Color checkBackground, bool disabledColors) { + protected void DrawCheckOnly(PaintEventArgs e, LayoutData layout, Color checkColor, Color checkBackground, bool disabledColors) + { // check // - if (Control.Checked) { - if (!Control.Enabled && disabledColors) { + if (Control.Checked) + { + if (!Control.Enabled && disabledColors) + { checkColor = SystemColors.ControlDark; } double scale = GetDpiScaleRatio(e.Graphics); - using( WindowsGraphics wg = WindowsGraphics.FromGraphics(e.Graphics) ) { - using (WindowsBrush brush = new WindowsSolidBrush(wg.DeviceContext, checkColor)) { + using (WindowsGraphics wg = WindowsGraphics.FromGraphics(e.Graphics)) + { + using (WindowsBrush brush = new WindowsSolidBrush(wg.DeviceContext, checkColor)) + { // circle drawing doesn't work at this size - int offset = 5; - Rectangle vCross = new Rectangle (layout.checkBounds.X + GetScaledNumber(offset, scale), layout.checkBounds.Y + GetScaledNumber(offset - 1, scale), GetScaledNumber(2, scale), GetScaledNumber(4, scale)); + int offset = 5; + Rectangle vCross = new Rectangle(layout.checkBounds.X + GetScaledNumber(offset, scale), layout.checkBounds.Y + GetScaledNumber(offset - 1, scale), GetScaledNumber(2, scale), GetScaledNumber(4, scale)); wg.FillRectangle(brush, vCross); - Rectangle hCross = new Rectangle (layout.checkBounds.X + GetScaledNumber(offset - 1, scale), layout.checkBounds.Y + GetScaledNumber(offset, scale), GetScaledNumber(4, scale), GetScaledNumber(2, scale)); + Rectangle hCross = new Rectangle(layout.checkBounds.X + GetScaledNumber(offset - 1, scale), layout.checkBounds.Y + GetScaledNumber(offset, scale), GetScaledNumber(4, scale), GetScaledNumber(2, scale)); wg.FillRectangle(brush, hCross); } } } } - protected ButtonState GetState() { + protected ButtonState GetState() + { ButtonState style = (ButtonState)0; - if (Control.Checked) { + if (Control.Checked) + { style |= ButtonState.Checked; } - else { + else + { style |= ButtonState.Normal; } - if (!Control.Enabled) { + if (!Control.Enabled) + { style |= ButtonState.Inactive; } - if (Control.MouseIsDown) { + if (Control.MouseIsDown) + { style |= ButtonState.Pushed; } return style; } - - protected void DrawCheckBox(PaintEventArgs e, LayoutData layout) { + + protected void DrawCheckBox(PaintEventArgs e, LayoutData layout) + { Graphics g = e.Graphics; - + Rectangle check = layout.checkBounds; - if (!Application.RenderWithVisualStyles) { + if (!Application.RenderWithVisualStyles) + { check.X--; // compensate for Windows drawing slightly offset to right } ButtonState style = GetState(); - - if (Application.RenderWithVisualStyles) { + + if (Application.RenderWithVisualStyles) + { RadioButtonRenderer.DrawRadioButton(g, new Point(check.Left, check.Top), RadioButtonRenderer.ConvertFromButtonState(style, Control.MouseIsOver), Control.HandleInternal); - } - else { + } + else + { ControlPaint.DrawRadioButton(g, check, style); } } #endregion - protected void AdjustFocusRectangle(LayoutData layout) { - if (string.IsNullOrEmpty(Control.Text)) { + protected void AdjustFocusRectangle(LayoutData layout) + { + if (string.IsNullOrEmpty(Control.Text)) + { // When a RadioButton has no text, AutoSize sets the size to zero // and thus there's no place around which to draw the focus rectangle. // So, when AutoSize == true we want the focus rectangle to be rendered around the circle area. @@ -201,12 +235,13 @@ protected void AdjustFocusRectangle(LayoutData layout) { } } - internal override LayoutOptions CommonLayout() { + internal override LayoutOptions CommonLayout() + { LayoutOptions layout = base.CommonLayout(); - layout.checkAlign = Control.CheckAlign; + layout.checkAlign = Control.CheckAlign; return layout; } - + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/RadioButtonFlatAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/RadioButtonFlatAdapter.cs index 01831de7d5f..bb2fea18b7e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/RadioButtonFlatAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/RadioButtonFlatAdapter.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ButtonInternal { +namespace System.Windows.Forms.ButtonInternal +{ using System; using System.Diagnostics; using System.Drawing; @@ -11,61 +12,75 @@ namespace System.Windows.Forms.ButtonInternal { using System.Drawing.Text; using System.Windows.Forms; - internal class RadioButtonFlatAdapter : RadioButtonBaseAdapter { - + internal class RadioButtonFlatAdapter : RadioButtonBaseAdapter + { + protected const int flatCheckSize = 12; - - internal RadioButtonFlatAdapter(ButtonBase control) : base(control) {} - internal override void PaintDown(PaintEventArgs e, CheckState state) { - if (Control.Appearance == Appearance.Button) { + internal RadioButtonFlatAdapter(ButtonBase control) : base(control) { } + + internal override void PaintDown(PaintEventArgs e, CheckState state) + { + if (Control.Appearance == Appearance.Button) + { ButtonFlatAdapter adapter = new ButtonFlatAdapter(Control); adapter.PaintDown(e, Control.Checked ? CheckState.Checked : CheckState.Unchecked); return; } ColorData colors = PaintFlatRender(e.Graphics).Calculate(); - if (Control.Enabled) { + if (Control.Enabled) + { PaintFlatWorker(e, colors.windowText, colors.highlight, colors.windowFrame, colors); } - else { + else + { PaintFlatWorker(e, colors.buttonShadow, colors.buttonFace, colors.buttonShadow, colors); } - } + } - internal override void PaintOver(PaintEventArgs e, CheckState state) { - if (Control.Appearance == Appearance.Button) { + internal override void PaintOver(PaintEventArgs e, CheckState state) + { + if (Control.Appearance == Appearance.Button) + { ButtonFlatAdapter adapter = new ButtonFlatAdapter(Control); adapter.PaintOver(e, Control.Checked ? CheckState.Checked : CheckState.Unchecked); return; } ColorData colors = PaintFlatRender(e.Graphics).Calculate(); - if (Control.Enabled) { + if (Control.Enabled) + { PaintFlatWorker(e, colors.windowText, colors.lowHighlight, colors.windowFrame, colors); } - else { + else + { PaintFlatWorker(e, colors.buttonShadow, colors.buttonFace, colors.buttonShadow, colors); } } - internal override void PaintUp(PaintEventArgs e, CheckState state) { - if (Control.Appearance == Appearance.Button) { + internal override void PaintUp(PaintEventArgs e, CheckState state) + { + if (Control.Appearance == Appearance.Button) + { ButtonFlatAdapter adapter = new ButtonFlatAdapter(Control); adapter.PaintUp(e, Control.Checked ? CheckState.Checked : CheckState.Unchecked); return; } ColorData colors = PaintFlatRender(e.Graphics).Calculate(); - if (Control.Enabled) { + if (Control.Enabled) + { PaintFlatWorker(e, colors.windowText, colors.highlight, colors.windowFrame, colors); } - else { + else + { PaintFlatWorker(e, colors.buttonShadow, colors.buttonFace, colors.buttonShadow, colors); } } - void PaintFlatWorker(PaintEventArgs e, Color checkColor, Color checkBackground, Color checkBorder, ColorData colors) { + void PaintFlatWorker(PaintEventArgs e, Color checkColor, Color checkBackground, Color checkBorder, ColorData colors) + { System.Drawing.Graphics g = e.Graphics; LayoutData layout = Layout(e).Layout(); PaintButtonBackground(e, Control.ClientRectangle, null); @@ -78,15 +93,17 @@ void PaintFlatWorker(PaintEventArgs e, Color checkColor, Color checkBackground, #region Layout - protected override ButtonBaseAdapter CreateButtonAdapter() { + protected override ButtonBaseAdapter CreateButtonAdapter() + { return new ButtonFlatAdapter(Control); } // RadioButtonPopupLayout also uses this layout for down and over - protected override LayoutOptions Layout(PaintEventArgs e) { + protected override LayoutOptions Layout(PaintEventArgs e) + { LayoutOptions layout = CommonLayout(); - layout.checkSize = (int)(flatCheckSize * GetDpiScaleRatio(e.Graphics)); - layout.shadowedText = false; + layout.checkSize = (int)(flatCheckSize * GetDpiScaleRatio(e.Graphics)); + layout.shadowedText = false; return layout; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/RadioButtonPopupAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/RadioButtonPopupAdapter.cs index 59bfdabcb7b..40402299be8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/RadioButtonPopupAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/RadioButtonPopupAdapter.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ButtonInternal { +namespace System.Windows.Forms.ButtonInternal +{ using System; using System.Diagnostics; using System.Drawing; @@ -11,24 +12,28 @@ namespace System.Windows.Forms.ButtonInternal { using System.Drawing.Text; using System.Windows.Forms; - internal class RadioButtonPopupAdapter : RadioButtonFlatAdapter { + internal class RadioButtonPopupAdapter : RadioButtonFlatAdapter + { - internal RadioButtonPopupAdapter(ButtonBase control) : base(control) {} + internal RadioButtonPopupAdapter(ButtonBase control) : base(control) { } - internal override void PaintUp(PaintEventArgs e, CheckState state) { + internal override void PaintUp(PaintEventArgs e, CheckState state) + { System.Drawing.Graphics g = e.Graphics; - if (Control.Appearance == Appearance.Button) { + if (Control.Appearance == Appearance.Button) + { ButtonPopupAdapter adapter = new ButtonPopupAdapter(Control); adapter.PaintUp(e, Control.Checked ? CheckState.Checked : CheckState.Unchecked); } - else { + else + { ColorData colors = PaintPopupRender(e.Graphics).Calculate(); LayoutData layout = Layout(e).Layout(); PaintButtonBackground(e, Control.ClientRectangle, null); - + PaintImage(e, layout); - + DrawCheckBackgroundFlat(e, layout.checkBounds, colors.buttonShadow, colors.options.highContrast ? colors.buttonFace : colors.highlight); DrawCheckOnly(e, layout, colors.windowText, colors.highlight, true); @@ -37,20 +42,23 @@ internal override void PaintUp(PaintEventArgs e, CheckState state) { } } - internal override void PaintOver(PaintEventArgs e, CheckState state) { + internal override void PaintOver(PaintEventArgs e, CheckState state) + { System.Drawing.Graphics g = e.Graphics; - if (Control.Appearance == Appearance.Button) { + if (Control.Appearance == Appearance.Button) + { ButtonPopupAdapter adapter = new ButtonPopupAdapter(Control); adapter.PaintOver(e, Control.Checked ? CheckState.Checked : CheckState.Unchecked); } - else { + else + { ColorData colors = PaintPopupRender(e.Graphics).Calculate(); LayoutData layout = Layout(e).Layout(); PaintButtonBackground(e, Control.ClientRectangle, null); - + PaintImage(e, layout); - + Color checkBackgroundColor = colors.options.highContrast ? colors.buttonFace : colors.highlight; DrawCheckBackground3DLite(e, layout.checkBounds, colors.windowText, checkBackgroundColor, colors, true); DrawCheckOnly(e, layout, colors.windowText, colors.highlight, true); @@ -60,20 +68,23 @@ internal override void PaintOver(PaintEventArgs e, CheckState state) { } } - internal override void PaintDown(PaintEventArgs e, CheckState state) { + internal override void PaintDown(PaintEventArgs e, CheckState state) + { System.Drawing.Graphics g = e.Graphics; - if (Control.Appearance == Appearance.Button) { + if (Control.Appearance == Appearance.Button) + { ButtonPopupAdapter adapter = new ButtonPopupAdapter(Control); adapter.PaintDown(e, Control.Checked ? CheckState.Checked : CheckState.Unchecked); } - else { + else + { ColorData colors = PaintPopupRender(e.Graphics).Calculate(); LayoutData layout = Layout(e).Layout(); PaintButtonBackground(e, Control.ClientRectangle, null); - + PaintImage(e, layout); - + DrawCheckBackground3DLite(e, layout.checkBounds, colors.windowText, colors.highlight, colors, true); DrawCheckOnly(e, layout, colors.buttonShadow, colors.highlight, true); @@ -84,17 +95,20 @@ internal override void PaintDown(PaintEventArgs e, CheckState state) { #region Layout - protected override ButtonBaseAdapter CreateButtonAdapter() { + protected override ButtonBaseAdapter CreateButtonAdapter() + { return new ButtonPopupAdapter(Control); } - protected override LayoutOptions Layout(PaintEventArgs e) { + protected override LayoutOptions Layout(PaintEventArgs e) + { LayoutOptions layout = base.Layout(e); - if (!Control.MouseIsDown && !Control.MouseIsOver) { + if (!Control.MouseIsDown && !Control.MouseIsOver) + { layout.shadowedText = true; } - + return layout; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/RadioButtonStandardAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/RadioButtonStandardAdapter.cs index 894c3e83c5f..dac40136cc7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/RadioButtonStandardAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/RadioButtonStandardAdapter.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ButtonInternal { +namespace System.Windows.Forms.ButtonInternal +{ using System; using System.Diagnostics; using System.Drawing; @@ -11,15 +12,19 @@ namespace System.Windows.Forms.ButtonInternal { using System.Drawing.Text; using System.Windows.Forms; - internal class RadioButtonStandardAdapter : RadioButtonBaseAdapter { + internal class RadioButtonStandardAdapter : RadioButtonBaseAdapter + { - internal RadioButtonStandardAdapter(ButtonBase control) : base(control) {} + internal RadioButtonStandardAdapter(ButtonBase control) : base(control) { } - internal override void PaintUp(PaintEventArgs e, CheckState state) { - if (Control.Appearance == Appearance.Button) { + internal override void PaintUp(PaintEventArgs e, CheckState state) + { + if (Control.Appearance == Appearance.Button) + { ButtonAdapter.PaintUp(e, Control.Checked ? CheckState.Checked : CheckState.Unchecked); } - else { + else + { ColorData colors = PaintRender(e.Graphics).Calculate(); LayoutData layout = Layout(e).Layout(); PaintButtonBackground(e, Control.ClientRectangle, null); @@ -31,51 +36,64 @@ internal override void PaintUp(PaintEventArgs e, CheckState state) { } } - internal override void PaintDown(PaintEventArgs e, CheckState state) { - if (Control.Appearance == Appearance.Button) { + internal override void PaintDown(PaintEventArgs e, CheckState state) + { + if (Control.Appearance == Appearance.Button) + { ButtonAdapter.PaintDown(e, Control.Checked ? CheckState.Checked : CheckState.Unchecked); } - else { + else + { PaintUp(e, state); } } - internal override void PaintOver(PaintEventArgs e, CheckState state) { - if (Control.Appearance == Appearance.Button) { + internal override void PaintOver(PaintEventArgs e, CheckState state) + { + if (Control.Appearance == Appearance.Button) + { ButtonAdapter.PaintOver(e, Control.Checked ? CheckState.Checked : CheckState.Unchecked); } - else { + else + { PaintUp(e, state); } - } + } - private new ButtonStandardAdapter ButtonAdapter { - get { + private new ButtonStandardAdapter ButtonAdapter + { + get + { return ((ButtonStandardAdapter)base.ButtonAdapter); } } - protected override ButtonBaseAdapter CreateButtonAdapter() { + protected override ButtonBaseAdapter CreateButtonAdapter() + { return new ButtonStandardAdapter(Control); } #region Temp - protected override LayoutOptions Layout(PaintEventArgs e) { + protected override LayoutOptions Layout(PaintEventArgs e) + { LayoutOptions layout = CommonLayout(); - layout.hintTextUp = false; - layout.everettButtonCompat = !Application.RenderWithVisualStyles; + layout.hintTextUp = false; + layout.everettButtonCompat = !Application.RenderWithVisualStyles; - if (Application.RenderWithVisualStyles) { - ButtonBase b = Control; - using (Graphics g = WindowsFormsUtils.CreateMeasurementGraphics()) { + if (Application.RenderWithVisualStyles) + { + ButtonBase b = Control; + using (Graphics g = WindowsFormsUtils.CreateMeasurementGraphics()) + { layout.checkSize = RadioButtonRenderer.GetGlyphSize(g, RadioButtonRenderer.ConvertFromButtonState(GetState(), b.MouseIsOver), b.HandleInternal).Width; } } - else { + else + { layout.checkSize = (int)(layout.checkSize * GetDpiScaleRatio(e.Graphics)); } - + return layout; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonRenderer.cs index 50d318525be..1fef2a06d26 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonRenderer.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Drawing; @@ -17,7 +18,8 @@ namespace System.Windows.Forms { /// without visual styles applied.) /// /// - public sealed class ButtonRenderer { + public sealed class ButtonRenderer + { //Make this per-thread, so that different threads can safely use these methods. [ThreadStatic] @@ -26,7 +28,8 @@ public sealed class ButtonRenderer { private static bool renderMatchingApplicationState = true; //cannot instantiate - private ButtonRenderer() { + private ButtonRenderer() + { } /// @@ -36,17 +39,22 @@ private ButtonRenderer() { /// If this property is false, the renderer will always render with visualstyles. /// /// - public static bool RenderMatchingApplicationState { - get { + public static bool RenderMatchingApplicationState + { + get + { return renderMatchingApplicationState; } - set { + set + { renderMatchingApplicationState = value; } } - private static bool RenderWithVisualStyles { - get { + private static bool RenderWithVisualStyles + { + get + { return (!renderMatchingApplicationState || Application.RenderWithVisualStyles); } } @@ -56,13 +64,16 @@ private static bool RenderWithVisualStyles { /// Returns true if the background corresponding to the given state is partially transparent, else false. /// /// - public static bool IsBackgroundPartiallyTransparent(PushButtonState state) { - if (RenderWithVisualStyles) { + public static bool IsBackgroundPartiallyTransparent(PushButtonState state) + { + if (RenderWithVisualStyles) + { InitializeRenderer((int)state); return visualStyleRenderer.IsBackgroundPartiallyTransparent(); } - else { + else + { return false; //for downlevel, this is false } } @@ -74,8 +85,10 @@ public static bool IsBackgroundPartiallyTransparent(PushButtonState state) { /// /// [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public static void DrawParentBackground(Graphics g, Rectangle bounds, Control childControl) { - if (RenderWithVisualStyles) { + public static void DrawParentBackground(Graphics g, Rectangle bounds, Control childControl) + { + if (RenderWithVisualStyles) + { InitializeRenderer(0); visualStyleRenderer.DrawParentBackground(g, bounds, childControl); } @@ -86,15 +99,18 @@ public static void DrawParentBackground(Graphics g, Rectangle bounds, Control ch /// Renders a Button control. /// /// - public static void DrawButton(Graphics g, Rectangle bounds, PushButtonState state) { - if (RenderWithVisualStyles) { - InitializeRenderer((int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - } - else { - ControlPaint.DrawButton(g, bounds, ConvertToButtonState(state)); - } + public static void DrawButton(Graphics g, Rectangle bounds, PushButtonState state) + { + if (RenderWithVisualStyles) + { + InitializeRenderer((int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + } + else + { + ControlPaint.DrawButton(g, bounds, ConvertToButtonState(state)); + } } /// @@ -105,21 +121,25 @@ public static void DrawButton(Graphics g, Rectangle bounds, PushButtonState stat /// is focused? /// state /// handle to the control - internal static void DrawButtonForHandle(Graphics g, Rectangle bounds, bool focused, PushButtonState state, IntPtr handle) { + internal static void DrawButtonForHandle(Graphics g, Rectangle bounds, bool focused, PushButtonState state, IntPtr handle) + { Rectangle contentBounds; - if (RenderWithVisualStyles) { + if (RenderWithVisualStyles) + { InitializeRenderer((int)state); visualStyleRenderer.DrawBackground(g, bounds, handle); contentBounds = visualStyleRenderer.GetBackgroundContentRectangle(g, bounds); } - else { + else + { ControlPaint.DrawButton(g, bounds, ConvertToButtonState(state)); contentBounds = Rectangle.Inflate(bounds, -3, -3); } - if (focused) { + if (focused) + { ControlPaint.DrawFocusRectangle(g, contentBounds); } } @@ -129,7 +149,8 @@ internal static void DrawButtonForHandle(Graphics g, Rectangle bounds, bool focu /// Renders a Button control. /// /// - public static void DrawButton(Graphics g, Rectangle bounds, bool focused, PushButtonState state) { + public static void DrawButton(Graphics g, Rectangle bounds, bool focused, PushButtonState state) + { DrawButtonForHandle(g, bounds, focused, state, IntPtr.Zero); } @@ -138,7 +159,8 @@ public static void DrawButton(Graphics g, Rectangle bounds, bool focused, PushBu /// Renders a Button control. /// /// - public static void DrawButton(Graphics g, Rectangle bounds, string buttonText, Font font, bool focused, PushButtonState state) { + public static void DrawButton(Graphics g, Rectangle bounds, string buttonText, Font font, bool focused, PushButtonState state) + { DrawButton(g, bounds, buttonText, font, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine, focused, state); @@ -150,28 +172,32 @@ public static void DrawButton(Graphics g, Rectangle bounds, string buttonText, F /// Renders a Button control. /// /// - public static void DrawButton(Graphics g, Rectangle bounds, string buttonText, Font font, TextFormatFlags flags, bool focused, PushButtonState state) { - Rectangle contentBounds; - Color textColor; - - if (RenderWithVisualStyles) { - InitializeRenderer((int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - contentBounds = visualStyleRenderer.GetBackgroundContentRectangle(g, bounds); - textColor = visualStyleRenderer.GetColor(ColorProperty.TextColor); - } - else { - ControlPaint.DrawButton(g, bounds, ConvertToButtonState(state)); - contentBounds = Rectangle.Inflate(bounds, -3, -3); - textColor = SystemColors.ControlText; - } - - TextRenderer.DrawText(g, buttonText, font, contentBounds, textColor, flags); - - if (focused) { - ControlPaint.DrawFocusRectangle(g, contentBounds); - } + public static void DrawButton(Graphics g, Rectangle bounds, string buttonText, Font font, TextFormatFlags flags, bool focused, PushButtonState state) + { + Rectangle contentBounds; + Color textColor; + + if (RenderWithVisualStyles) + { + InitializeRenderer((int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + contentBounds = visualStyleRenderer.GetBackgroundContentRectangle(g, bounds); + textColor = visualStyleRenderer.GetColor(ColorProperty.TextColor); + } + else + { + ControlPaint.DrawButton(g, bounds, ConvertToButtonState(state)); + contentBounds = Rectangle.Inflate(bounds, -3, -3); + textColor = SystemColors.ControlText; + } + + TextRenderer.DrawText(g, buttonText, font, contentBounds, textColor, flags); + + if (focused) + { + ControlPaint.DrawFocusRectangle(g, contentBounds); + } } /// @@ -179,25 +205,29 @@ public static void DrawButton(Graphics g, Rectangle bounds, string buttonText, F /// Renders a Button control. /// /// - public static void DrawButton(Graphics g, Rectangle bounds, Image image, Rectangle imageBounds, bool focused, PushButtonState state) { - Rectangle contentBounds; - - if (RenderWithVisualStyles) { - InitializeRenderer((int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - visualStyleRenderer.DrawImage(g, imageBounds, image); - contentBounds = visualStyleRenderer.GetBackgroundContentRectangle(g, bounds); - } - else { - ControlPaint.DrawButton(g, bounds, ConvertToButtonState(state)); - g.DrawImage(image, imageBounds); - contentBounds = Rectangle.Inflate(bounds, -3, -3); - } - - if (focused) { - ControlPaint.DrawFocusRectangle(g, contentBounds); - } + public static void DrawButton(Graphics g, Rectangle bounds, Image image, Rectangle imageBounds, bool focused, PushButtonState state) + { + Rectangle contentBounds; + + if (RenderWithVisualStyles) + { + InitializeRenderer((int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + visualStyleRenderer.DrawImage(g, imageBounds, image); + contentBounds = visualStyleRenderer.GetBackgroundContentRectangle(g, bounds); + } + else + { + ControlPaint.DrawButton(g, bounds, ConvertToButtonState(state)); + g.DrawImage(image, imageBounds); + contentBounds = Rectangle.Inflate(bounds, -3, -3); + } + + if (focused) + { + ControlPaint.DrawFocusRectangle(g, contentBounds); + } } /// @@ -205,7 +235,8 @@ public static void DrawButton(Graphics g, Rectangle bounds, Image image, Rectang /// Renders a Button control. /// /// - public static void DrawButton(Graphics g, Rectangle bounds, string buttonText, Font font, Image image, Rectangle imageBounds, bool focused, PushButtonState state) { + public static void DrawButton(Graphics g, Rectangle bounds, string buttonText, Font font, Image image, Rectangle imageBounds, bool focused, PushButtonState state) + { DrawButton(g, bounds, buttonText, font, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine, image, imageBounds, focused, state); @@ -216,34 +247,40 @@ public static void DrawButton(Graphics g, Rectangle bounds, string buttonText, F /// Renders a Button control. /// /// - public static void DrawButton(Graphics g, Rectangle bounds, string buttonText, Font font, TextFormatFlags flags, Image image, Rectangle imageBounds, bool focused, PushButtonState state) { - Rectangle contentBounds; - Color textColor; - - if (RenderWithVisualStyles) { - InitializeRenderer((int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - visualStyleRenderer.DrawImage(g, imageBounds, image); - contentBounds = visualStyleRenderer.GetBackgroundContentRectangle(g, bounds); - textColor = visualStyleRenderer.GetColor(ColorProperty.TextColor); - } - else { - ControlPaint.DrawButton(g, bounds, ConvertToButtonState(state)); - g.DrawImage(image, imageBounds); - contentBounds = Rectangle.Inflate(bounds, -3, -3); - textColor = SystemColors.ControlText; - } - - TextRenderer.DrawText(g, buttonText, font, contentBounds, textColor, flags); - - if (focused) { - ControlPaint.DrawFocusRectangle(g, contentBounds); - } + public static void DrawButton(Graphics g, Rectangle bounds, string buttonText, Font font, TextFormatFlags flags, Image image, Rectangle imageBounds, bool focused, PushButtonState state) + { + Rectangle contentBounds; + Color textColor; + + if (RenderWithVisualStyles) + { + InitializeRenderer((int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + visualStyleRenderer.DrawImage(g, imageBounds, image); + contentBounds = visualStyleRenderer.GetBackgroundContentRectangle(g, bounds); + textColor = visualStyleRenderer.GetColor(ColorProperty.TextColor); + } + else + { + ControlPaint.DrawButton(g, bounds, ConvertToButtonState(state)); + g.DrawImage(image, imageBounds); + contentBounds = Rectangle.Inflate(bounds, -3, -3); + textColor = SystemColors.ControlText; + } + + TextRenderer.DrawText(g, buttonText, font, contentBounds, textColor, flags); + + if (focused) + { + ControlPaint.DrawFocusRectangle(g, contentBounds); + } } - internal static ButtonState ConvertToButtonState(PushButtonState state) { - switch (state) { + internal static ButtonState ConvertToButtonState(PushButtonState state) + { + switch (state) + { case PushButtonState.Pressed: return ButtonState.Pushed; @@ -255,11 +292,14 @@ internal static ButtonState ConvertToButtonState(PushButtonState state) { } } - private static void InitializeRenderer(int state) { - if (visualStyleRenderer == null) { + private static void InitializeRenderer(int state) + { + if (visualStyleRenderer == null) + { visualStyleRenderer = new VisualStyleRenderer(ButtonElement.ClassName, ButtonElement.Part, state); } - else { + else + { visualStyleRenderer.SetParameters(ButtonElement.ClassName, ButtonElement.Part, state); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/CacheVirtualItemsEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/CacheVirtualItemsEventArgs.cs index 6a8cb731222..060f4599e8e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/CacheVirtualItemsEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/CacheVirtualItemsEventArgs.cs @@ -11,9 +11,9 @@ public CacheVirtualItemsEventArgs(int startIndex, int endIndex) StartIndex = startIndex; EndIndex = endIndex; } - + public int StartIndex { get; } - + public int EndIndex { get; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/CheckBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/CheckBox.cs index ebffd7f9154..7c03d19e039 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/CheckBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/CheckBox.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; @@ -35,11 +36,12 @@ namespace System.Windows.Forms { ToolboxItem("System.Windows.Forms.Design.AutoSizeToolboxItem," + AssemblyRef.SystemDesign), SRDescription(nameof(SR.DescriptionCheckBox)) ] - public class CheckBox : ButtonBase { + public class CheckBox : ButtonBase + { private static readonly object EVENT_CHECKEDCHANGED = new object(); private static readonly object EVENT_CHECKSTATECHANGED = new object(); private static readonly object EVENT_APPEARANCECHANGED = new object(); - static readonly ContentAlignment anyRight = ContentAlignment.TopRight | ContentAlignment.MiddleRight | ContentAlignment.BottomRight; + static readonly ContentAlignment anyRight = ContentAlignment.TopRight | ContentAlignment.MiddleRight | ContentAlignment.BottomRight; private bool autoCheck; private bool threeState; @@ -61,9 +63,11 @@ public class CheckBox : ButtonBase { /// /// public CheckBox() - : base() { + : base() + { - if (DpiHelper.IsScalingRequirementMet) { + if (DpiHelper.IsScalingRequirementMet) + { flatSystemStylePaddingWidth = LogicalToDeviceUnits(FlatSystemStylePaddingWidth); flatSystemStyleMinimumHeight = LogicalToDeviceUnits(FlatSystemStyleMinimumHeight); } @@ -73,17 +77,20 @@ public CheckBox() ControlStyles.StandardDoubleClick, false); SetAutoSizeMode(AutoSizeMode.GrowAndShrink); - + autoCheck = true; - TextAlign = ContentAlignment.MiddleLeft; - + TextAlign = ContentAlignment.MiddleLeft; + } - - private bool AccObjDoDefaultAction { - get { + + private bool AccObjDoDefaultAction + { + get + { return this.accObjDoDefaultAction; } - set { + set + { this.accObjDoDefaultAction = value; } } @@ -99,24 +106,32 @@ private bool AccObjDoDefaultAction { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.CheckBoxAppearanceDescr)) ] - public Appearance Appearance { - get { + public Appearance Appearance + { + get + { return appearance; } - set { + set + { //valid values are 0x0 to 0x1 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)Appearance.Normal, (int)Appearance.Button)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)Appearance.Normal, (int)Appearance.Button)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(Appearance)); } - if (appearance != value) { - using (LayoutTransaction.CreateTransactionIf(AutoSize, this.ParentInternal, this, PropertyNames.Appearance)) { + if (appearance != value) + { + using (LayoutTransaction.CreateTransactionIf(AutoSize, this.ParentInternal, this, PropertyNames.Appearance)) + { appearance = value; - if (OwnerDraw) { + if (OwnerDraw) + { Refresh(); } - else { + else + { UpdateStyles(); } OnAppearanceChanged(EventArgs.Empty); @@ -126,7 +141,8 @@ public Appearance Appearance { } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.CheckBoxOnAppearanceChangedDescr))] - public event EventHandler AppearanceChanged { + public event EventHandler AppearanceChanged + { add => Events.AddHandler(EVENT_APPEARANCECHANGED, value); remove => Events.RemoveHandler(EVENT_APPEARANCECHANGED, value); } @@ -141,12 +157,15 @@ public event EventHandler AppearanceChanged { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.CheckBoxAutoCheckDescr)) ] - public bool AutoCheck { - get { + public bool AutoCheck + { + get + { return autoCheck; } - set { + set + { autoCheck = value; } } @@ -166,22 +185,29 @@ public bool AutoCheck { DefaultValue(ContentAlignment.MiddleLeft), SRDescription(nameof(SR.CheckBoxCheckAlignDescr)) ] - public ContentAlignment CheckAlign { - get { + public ContentAlignment CheckAlign + { + get + { return checkAlign; } - set { - if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) { + set + { + if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ContentAlignment)); } - if (checkAlign != value) { + if (checkAlign != value) + { checkAlign = value; LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.CheckAlign); - if (OwnerDraw) { + if (OwnerDraw) + { Invalidate(); } - else { + else + { UpdateStyles(); } } @@ -204,13 +230,17 @@ public ContentAlignment CheckAlign { RefreshProperties(RefreshProperties.All), SRDescription(nameof(SR.CheckBoxCheckedDescr)) ] - public bool Checked { - get { + public bool Checked + { + get + { return checkState != CheckState.Unchecked; } - set { - if (value != Checked) { + set + { + if (value != Checked) + { CheckState = value ? CheckState.Checked : CheckState.Unchecked; } } @@ -227,28 +257,35 @@ public bool Checked { RefreshProperties(RefreshProperties.All), SRDescription(nameof(SR.CheckBoxCheckStateDescr)) ] - public CheckState CheckState { - get { + public CheckState CheckState + { + get + { return checkState; } - set { + set + { // valid values are 0-2 inclusive. - if (!ClientUtils.IsEnumValid(value, (int)value, (int)CheckState.Unchecked, (int)CheckState.Indeterminate)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)CheckState.Unchecked, (int)CheckState.Indeterminate)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(CheckState)); } - if (checkState != value) { - + if (checkState != value) + { + bool oldChecked = Checked; - + checkState = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(NativeMethods.BM_SETCHECK, (int)checkState, 0); } - - if (oldChecked != Checked) { + + if (oldChecked != Checked) + { OnCheckedChanged(EventArgs.Empty); } OnCheckStateChanged(EventArgs.Empty); @@ -258,14 +295,16 @@ public CheckState CheckState { /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler DoubleClick { + public new event EventHandler DoubleClick + { add => base.DoubleClick += value; remove => base.DoubleClick -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event MouseEventHandler MouseDoubleClick { + public new event MouseEventHandler MouseDoubleClick + { add => base.MouseDoubleClick += value; remove => base.MouseDoubleClick -= value; } @@ -277,23 +316,29 @@ public CheckState CheckState { /// control. /// /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ClassName = "BUTTON"; - if (OwnerDraw) { + if (OwnerDraw) + { cp.Style |= NativeMethods.BS_OWNERDRAW; } - else { + else + { cp.Style |= NativeMethods.BS_3STATE; - if (Appearance == Appearance.Button) { + if (Appearance == Appearance.Button) + { cp.Style |= NativeMethods.BS_PUSHLIKE; } - + // Determine the alignment of the check box // - ContentAlignment align = RtlTranslateContent(CheckAlign); - if ((int)(align & anyRight) != 0) { + ContentAlignment align = RtlTranslateContent(CheckAlign); + if ((int)(align & anyRight) != 0) + { cp.Style |= NativeMethods.BS_RIGHTBUTTON; } @@ -302,13 +347,15 @@ protected override CreateParams CreateParams { return cp; } } - + /// /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(104, 24); } } @@ -322,20 +369,24 @@ protected override Size DefaultSize { /// /// Old DPI value /// New DPI value - protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) { + protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) + { base.RescaleConstantsForDpi(deviceDpiOld, deviceDpiNew); flatSystemStylePaddingWidth = LogicalToDeviceUnits(FlatSystemStylePaddingWidth); flatSystemStyleMinimumHeight = LogicalToDeviceUnits(FlatSystemStyleMinimumHeight); } - internal override Size GetPreferredSizeCore(Size proposedConstraints) { - if (Appearance == Appearance.Button) { + internal override Size GetPreferredSizeCore(Size proposedConstraints) + { + if (Appearance == Appearance.Button) + { ButtonStandardAdapter adapter = new ButtonStandardAdapter(this); return adapter.GetPreferredSizeCore(proposedConstraints); - } + } - if(FlatStyle != FlatStyle.System) { + if (FlatStyle != FlatStyle.System) + { return base.GetPreferredSizeCore(proposedConstraints); } @@ -348,39 +399,49 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) { /// /// - internal override Rectangle OverChangeRectangle { - get { - if (Appearance == Appearance.Button) { + internal override Rectangle OverChangeRectangle + { + get + { + if (Appearance == Appearance.Button) + { return base.OverChangeRectangle; } - else { - if (FlatStyle == FlatStyle.Standard) { + else + { + if (FlatStyle == FlatStyle.Standard) + { // this Rectangle will cause no Invalidation // can't use Rectangle.Empty because it will cause Invalidate(ClientRectangle) return new Rectangle(-1, -1, 1, 1); } - else { + else + { // Popup mouseover rectangle is actually bigger than GetCheckmarkRectangle return Adapter.CommonLayout().Layout().checkBounds; } } } } - + /// /// - internal override Rectangle DownChangeRectangle { - get { - if (Appearance == Appearance.Button || FlatStyle == FlatStyle.System) { + internal override Rectangle DownChangeRectangle + { + get + { + if (Appearance == Appearance.Button || FlatStyle == FlatStyle.System) + { return base.DownChangeRectangle; } - else { + else + { // Popup mouseover rectangle is actually bigger than GetCheckmarkRectangle() return Adapter.CommonLayout().Layout().checkBounds; } } } - + /// /// /// Gets or sets a value indicating the alignment of the @@ -392,11 +453,14 @@ internal override Rectangle DownChangeRectangle { Localizable(true), DefaultValue(ContentAlignment.MiddleLeft) ] - public override ContentAlignment TextAlign { - get { + public override ContentAlignment TextAlign + { + get + { return base.TextAlign; } - set { + set + { base.TextAlign = value; } } @@ -410,11 +474,14 @@ public override ContentAlignment TextAlign { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.CheckBoxThreeStateDescr)) ] - public bool ThreeState { - get { + public bool ThreeState + { + get + { return threeState; } - set { + set + { threeState = value; } } @@ -425,18 +492,20 @@ public bool ThreeState { /// property changes. /// [SRDescription(nameof(SR.CheckBoxOnCheckedChangedDescr))] - public event EventHandler CheckedChanged { + public event EventHandler CheckedChanged + { add => Events.AddHandler(EVENT_CHECKEDCHANGED, value); remove => Events.RemoveHandler(EVENT_CHECKEDCHANGED, value); } - + /// /// Occurs when the /// value of the /// property changes. /// [SRDescription(nameof(SR.CheckBoxOnCheckStateChangedDescr))] - public event EventHandler CheckStateChanged { + public event EventHandler CheckStateChanged + { add => Events.AddHandler(EVENT_CHECKSTATECHANGED, value); remove => Events.RemoveHandler(EVENT_CHECKSTATECHANGED, value); } @@ -447,14 +516,17 @@ public event EventHandler CheckStateChanged { /// should not call base.CreateAccessibilityObject. /// /// - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new CheckBoxAccessibleObject(this); } - - protected virtual void OnAppearanceChanged(EventArgs e) { + + protected virtual void OnAppearanceChanged(EventArgs e) + { EventHandler eh = Events[EVENT_APPEARANCECHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } @@ -462,33 +534,40 @@ protected virtual void OnAppearanceChanged(EventArgs e) { /// Raises the /// event. /// - protected virtual void OnCheckedChanged(EventArgs e) { + protected virtual void OnCheckedChanged(EventArgs e) + { // accessibility stuff - if (this.FlatStyle == FlatStyle.System) { + if (this.FlatStyle == FlatStyle.System) + { AccessibilityNotifyClients(AccessibleEvents.SystemCaptureStart, -1); } AccessibilityNotifyClients(AccessibleEvents.StateChange, -1); AccessibilityNotifyClients(AccessibleEvents.NameChange, -1); - if (this.FlatStyle == FlatStyle.System) { + if (this.FlatStyle == FlatStyle.System) + { AccessibilityNotifyClients(AccessibleEvents.SystemCaptureEnd, -1); } EventHandler handler = (EventHandler)Events[EVENT_CHECKEDCHANGED]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// /// Raises the event. /// - protected virtual void OnCheckStateChanged(EventArgs e) { - if (OwnerDraw) { + protected virtual void OnCheckStateChanged(EventArgs e) + { + if (OwnerDraw) + { Refresh(); } - + EventHandler handler = (EventHandler)Events[EVENT_CHECKSTATECHANGED]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// @@ -500,24 +579,30 @@ protected virtual void OnCheckStateChanged(EventArgs e) { /// /// /// - protected override void OnClick(EventArgs e) { - if (autoCheck) { - switch (CheckState) { + protected override void OnClick(EventArgs e) + { + if (autoCheck) + { + switch (CheckState) + { case CheckState.Unchecked: CheckState = CheckState.Checked; break; case CheckState.Checked: - if (threeState) { + if (threeState) + { CheckState = CheckState.Indeterminate; // If the check box is clicked as a result of AccObj::DoDefaultAction // then the native check box does not fire OBJ_STATE_CHANGE event when going to Indeterminate state. // So the WinForms layer fires the OBJ_STATE_CHANGE event. - if (this.AccObjDoDefaultAction) { + if (this.AccObjDoDefaultAction) + { AccessibilityNotifyClients(AccessibleEvents.StateChange, -1); } } - else { + else + { CheckState = CheckState.Unchecked; } break; @@ -533,14 +618,16 @@ protected override void OnClick(EventArgs e) { /// We override this to ensure that the control's click values are set up /// correctly. /// - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { base.OnHandleCreated(e); - + // Since this is a protected override... // this can be directly called in by a overriden class.. // and the Handle need not be created... // So Check for the handle - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(NativeMethods.BM_SETCHECK, (int)checkState, 0); } } @@ -549,7 +636,8 @@ protected override void OnHandleCreated(EventArgs e) { /// We override this to ensure that press '+' or '=' checks the box, /// while pressing '-' unchecks the box /// - protected override void OnKeyDown(KeyEventArgs e) { + protected override void OnKeyDown(KeyEventArgs e) + { /* if (Enabled) { if (e.KeyCode == Keys.Oemplus || e.KeyCode == Keys.Add) { @@ -562,23 +650,29 @@ protected override void OnKeyDown(KeyEventArgs e) { */ base.OnKeyDown(e); } - + /// /// /// Raises the event. /// /// /// - protected override void OnMouseUp(MouseEventArgs mevent) { - if (mevent.Button == MouseButtons.Left && MouseIsPressed) { + protected override void OnMouseUp(MouseEventArgs mevent) + { + if (mevent.Button == MouseButtons.Left && MouseIsPressed) + { // It's best not to have the mouse captured while running Click events - if (base.MouseIsDown) { + if (base.MouseIsDown) + { Point pt = PointToScreen(new Point(mevent.X, mevent.Y)); - if (UnsafeNativeMethods.WindowFromPoint(pt.X, pt.Y) == Handle) { + if (UnsafeNativeMethods.WindowFromPoint(pt.X, pt.Y) == Handle) + { //Paint in raised state... ResetFlagsandPaint(); - if (!ValidationCancelled) { - if (this.Capture) { + if (!ValidationCancelled) + { + if (this.Capture) + { OnClick(mevent); } OnMouseClick(mevent); @@ -589,31 +683,38 @@ protected override void OnMouseUp(MouseEventArgs mevent) { base.OnMouseUp(mevent); } - internal override ButtonBaseAdapter CreateFlatAdapter() { + internal override ButtonBaseAdapter CreateFlatAdapter() + { return new CheckBoxFlatAdapter(this); } - internal override ButtonBaseAdapter CreatePopupAdapter() { + internal override ButtonBaseAdapter CreatePopupAdapter() + { return new CheckBoxPopupAdapter(this); } - - internal override ButtonBaseAdapter CreateStandardAdapter() { + + internal override ButtonBaseAdapter CreateStandardAdapter() + { return new CheckBoxStandardAdapter(this); } /// /// Overridden to handle mnemonics properly. /// - protected internal override bool ProcessMnemonic(char charCode) { - if (UseMnemonic && IsMnemonic(charCode, Text) && CanSelect) { - if (Focus()) { + protected internal override bool ProcessMnemonic(char charCode) + { + if (UseMnemonic && IsMnemonic(charCode, Text) && CanSelect) + { + if (Focus()) + { //Paint in raised state... // ResetFlagsandPaint(); - if (!ValidationCancelled) { + if (!ValidationCancelled) + { OnClick(EventArgs.Empty); } - + } return true; } @@ -624,7 +725,8 @@ protected internal override bool ProcessMnemonic(char charCode) { /// Provides some interesting information for the CheckBox control in /// String form. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); // We shouldn't need to convert the enum to int @@ -634,41 +736,54 @@ public override string ToString() { /// /// - [System.Runtime.InteropServices.ComVisible(true)] - public class CheckBoxAccessibleObject : ButtonBaseAccessibleObject { + [System.Runtime.InteropServices.ComVisible(true)] + public class CheckBoxAccessibleObject : ButtonBaseAccessibleObject + { - public CheckBoxAccessibleObject(Control owner) : base(owner) { + public CheckBoxAccessibleObject(Control owner) : base(owner) + { } - public override string DefaultAction { - get { + public override string DefaultAction + { + get + { string defaultAction = Owner.AccessibleDefaultActionDescription; - if (defaultAction != null) { + if (defaultAction != null) + { return defaultAction; } - if (((CheckBox)Owner).Checked) { + if (((CheckBox)Owner).Checked) + { return SR.AccessibleActionUncheck; } - else { + else + { return SR.AccessibleActionCheck; } } } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { AccessibleRole role = Owner.AccessibleRole; - if (role != AccessibleRole.Default) { + if (role != AccessibleRole.Default) + { return role; } return AccessibleRole.CheckButton; } } - - public override AccessibleStates State { - get { - switch (((CheckBox)Owner).CheckState) { + + public override AccessibleStates State + { + get + { + switch (((CheckBox)Owner).CheckState) + { case CheckState.Checked: return AccessibleStates.Checked | base.State; case CheckState.Indeterminate: @@ -677,19 +792,25 @@ public override AccessibleStates State { return base.State; } - } + } - public override void DoDefaultAction() { + public override void DoDefaultAction() + { CheckBox cb = this.Owner as CheckBox; - if (cb != null) { + if (cb != null) + { cb.AccObjDoDefaultAction = true; } - try { + try + { base.DoDefaultAction(); - } finally { - if (cb != null) { + } + finally + { + if (cb != null) + { cb.AccObjDoDefaultAction = false; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/CheckBoxRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/CheckBoxRenderer.cs index 98b55fed601..40986674652 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/CheckBoxRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/CheckBoxRenderer.cs @@ -2,14 +2,15 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ -using System; -using System.Drawing; -using System.Diagnostics.CodeAnalysis; -using System.Windows.Forms.Internal; -using System.Windows.Forms.VisualStyles; -using Microsoft.Win32; + using System; + using System.Drawing; + using System.Diagnostics.CodeAnalysis; + using System.Windows.Forms.Internal; + using System.Windows.Forms.VisualStyles; + using Microsoft.Win32; /// @@ -18,195 +19,228 @@ namespace System.Windows.Forms { /// without visual styles applied.) /// /// - public sealed class CheckBoxRenderer { + public sealed class CheckBoxRenderer + { - //Make this per-thread, so that different threads can safely use these methods. - [ThreadStatic] - private static VisualStyleRenderer visualStyleRenderer = null; - private static readonly VisualStyleElement CheckBoxElement = VisualStyleElement.Button.CheckBox.UncheckedNormal; + //Make this per-thread, so that different threads can safely use these methods. + [ThreadStatic] + private static VisualStyleRenderer visualStyleRenderer = null; + private static readonly VisualStyleElement CheckBoxElement = VisualStyleElement.Button.CheckBox.UncheckedNormal; private static bool renderMatchingApplicationState = true; //cannot instantiate - private CheckBoxRenderer() { - } - - /// - /// - /// If this property is true, then the renderer will use the setting from Application.RenderWithVisualStyles to - /// determine how to render. - /// If this property is false, the renderer will always render with visualstyles. - /// - /// - public static bool RenderMatchingApplicationState { - get { - return renderMatchingApplicationState; - } - set { - renderMatchingApplicationState = value; - } - } - - private static bool RenderWithVisualStyles { - get { - return (!renderMatchingApplicationState || Application.RenderWithVisualStyles); - } - } - - /// - /// - /// Returns true if the background corresponding to the given state is partially transparent, else false. - /// - /// - public static bool IsBackgroundPartiallyTransparent(CheckBoxState state) { - if (RenderWithVisualStyles) { - InitializeRenderer((int)state); - - return visualStyleRenderer.IsBackgroundPartiallyTransparent(); - } - else { - return false; //for downlevel, this is false - } - } - - /// - /// - /// This is just a convenience wrapper for VisualStyleRenderer.DrawThemeParentBackground. For downlevel, - /// this isn't required and does nothing. - /// - /// - [ - SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally - ] - public static void DrawParentBackground(Graphics g, Rectangle bounds, Control childControl) { - if (RenderWithVisualStyles) { - InitializeRenderer(0); - - visualStyleRenderer.DrawParentBackground(g, bounds, childControl); - } - } + private CheckBoxRenderer() + { + } + + /// + /// + /// If this property is true, then the renderer will use the setting from Application.RenderWithVisualStyles to + /// determine how to render. + /// If this property is false, the renderer will always render with visualstyles. + /// + /// + public static bool RenderMatchingApplicationState + { + get + { + return renderMatchingApplicationState; + } + set + { + renderMatchingApplicationState = value; + } + } + + private static bool RenderWithVisualStyles + { + get + { + return (!renderMatchingApplicationState || Application.RenderWithVisualStyles); + } + } + + /// + /// + /// Returns true if the background corresponding to the given state is partially transparent, else false. + /// + /// + public static bool IsBackgroundPartiallyTransparent(CheckBoxState state) + { + if (RenderWithVisualStyles) + { + InitializeRenderer((int)state); + + return visualStyleRenderer.IsBackgroundPartiallyTransparent(); + } + else + { + return false; //for downlevel, this is false + } + } + + /// + /// + /// This is just a convenience wrapper for VisualStyleRenderer.DrawThemeParentBackground. For downlevel, + /// this isn't required and does nothing. + /// + /// + [ + SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally + ] + public static void DrawParentBackground(Graphics g, Rectangle bounds, Control childControl) + { + if (RenderWithVisualStyles) + { + InitializeRenderer(0); + + visualStyleRenderer.DrawParentBackground(g, bounds, childControl); + } + } /// /// /// Renders a CheckBox control. /// /// - public static void DrawCheckBox(Graphics g, Point glyphLocation, CheckBoxState state) { + public static void DrawCheckBox(Graphics g, Point glyphLocation, CheckBoxState state) + { DrawCheckBox(g, glyphLocation, state, IntPtr.Zero); } - internal static void DrawCheckBox(Graphics g, Point glyphLocation, CheckBoxState state, IntPtr hWnd) { - Rectangle glyphBounds = new Rectangle(glyphLocation, GetGlyphSize(g, state, hWnd)); - - if (RenderWithVisualStyles) { - InitializeRenderer((int)state); - - visualStyleRenderer.DrawBackground(g, glyphBounds, hWnd); - } - else { - if (IsMixed(state)) { - ControlPaint.DrawMixedCheckBox(g, glyphBounds, ConvertToButtonState(state)); - } - else { - ControlPaint.DrawCheckBox(g, glyphBounds, ConvertToButtonState(state)); - } - } - - } - - /// - /// - /// Renders a CheckBox control. - /// - /// - public static void DrawCheckBox(Graphics g, Point glyphLocation, Rectangle textBounds, string checkBoxText, Font font, bool focused, CheckBoxState state) { - DrawCheckBox(g, glyphLocation, textBounds, checkBoxText, font, - TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine, - focused, state); - } + internal static void DrawCheckBox(Graphics g, Point glyphLocation, CheckBoxState state, IntPtr hWnd) + { + Rectangle glyphBounds = new Rectangle(glyphLocation, GetGlyphSize(g, state, hWnd)); + + if (RenderWithVisualStyles) + { + InitializeRenderer((int)state); + + visualStyleRenderer.DrawBackground(g, glyphBounds, hWnd); + } + else + { + if (IsMixed(state)) + { + ControlPaint.DrawMixedCheckBox(g, glyphBounds, ConvertToButtonState(state)); + } + else + { + ControlPaint.DrawCheckBox(g, glyphBounds, ConvertToButtonState(state)); + } + } + + } /// /// /// Renders a CheckBox control. /// /// - public static void DrawCheckBox(Graphics g, Point glyphLocation, Rectangle textBounds, string checkBoxText, Font font, TextFormatFlags flags, bool focused, CheckBoxState state) { + public static void DrawCheckBox(Graphics g, Point glyphLocation, Rectangle textBounds, string checkBoxText, Font font, bool focused, CheckBoxState state) + { + DrawCheckBox(g, glyphLocation, textBounds, checkBoxText, font, + TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine, + focused, state); + } + + /// + /// + /// Renders a CheckBox control. + /// + /// + public static void DrawCheckBox(Graphics g, Point glyphLocation, Rectangle textBounds, string checkBoxText, Font font, TextFormatFlags flags, bool focused, CheckBoxState state) + { DrawCheckBox(g, glyphLocation, textBounds, checkBoxText, font, flags, focused, state, IntPtr.Zero); } - internal static void DrawCheckBox(Graphics g, Point glyphLocation, Rectangle textBounds, string checkBoxText, Font font, TextFormatFlags flags, bool focused, CheckBoxState state, IntPtr hWnd) { - Rectangle glyphBounds = new Rectangle(glyphLocation, GetGlyphSize(g, state, hWnd)); - Color textColor; - - if (RenderWithVisualStyles) { - InitializeRenderer((int)state); - - visualStyleRenderer.DrawBackground(g, glyphBounds); - textColor = visualStyleRenderer.GetColor(ColorProperty.TextColor); - } - else { - if (IsMixed(state)) { - ControlPaint.DrawMixedCheckBox(g, glyphBounds, ConvertToButtonState(state)); - } - else { - ControlPaint.DrawCheckBox(g, glyphBounds, ConvertToButtonState(state)); - } - - textColor = SystemColors.ControlText; - } - - TextRenderer.DrawText(g, checkBoxText, font, textBounds, textColor, flags); - - if (focused) { - ControlPaint.DrawFocusRectangle(g, textBounds); - } - } - - /// - /// - /// Renders a CheckBox control. - /// - /// - public static void DrawCheckBox(Graphics g, Point glyphLocation, Rectangle textBounds, string checkBoxText, Font font, Image image, Rectangle imageBounds, bool focused, CheckBoxState state) { - DrawCheckBox(g, glyphLocation, textBounds, checkBoxText, font, - TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine, - image, imageBounds, focused, state); - } - - /// - /// - /// Renders a CheckBox control. - /// - /// - public static void DrawCheckBox(Graphics g, Point glyphLocation, Rectangle textBounds, string checkBoxText, Font font, TextFormatFlags flags, Image image, Rectangle imageBounds, bool focused, CheckBoxState state) { - Rectangle glyphBounds = new Rectangle(glyphLocation, GetGlyphSize(g, state)); - Color textColor; - - if (RenderWithVisualStyles) { - InitializeRenderer((int)state); - - //Keep this drawing order! It matches default drawing order. - visualStyleRenderer.DrawImage(g, imageBounds, image); - visualStyleRenderer.DrawBackground(g, glyphBounds); - textColor = visualStyleRenderer.GetColor(ColorProperty.TextColor); - } - else { - g.DrawImage(image, imageBounds); - if (IsMixed(state)) { - ControlPaint.DrawMixedCheckBox(g, glyphBounds, ConvertToButtonState(state)); - } - else { - ControlPaint.DrawCheckBox(g, glyphBounds, ConvertToButtonState(state)); - } - - textColor = SystemColors.ControlText; - } - - TextRenderer.DrawText(g, checkBoxText, font, textBounds, textColor, flags); - - if (focused) { - ControlPaint.DrawFocusRectangle(g, textBounds); - } - } + internal static void DrawCheckBox(Graphics g, Point glyphLocation, Rectangle textBounds, string checkBoxText, Font font, TextFormatFlags flags, bool focused, CheckBoxState state, IntPtr hWnd) + { + Rectangle glyphBounds = new Rectangle(glyphLocation, GetGlyphSize(g, state, hWnd)); + Color textColor; + + if (RenderWithVisualStyles) + { + InitializeRenderer((int)state); + + visualStyleRenderer.DrawBackground(g, glyphBounds); + textColor = visualStyleRenderer.GetColor(ColorProperty.TextColor); + } + else + { + if (IsMixed(state)) + { + ControlPaint.DrawMixedCheckBox(g, glyphBounds, ConvertToButtonState(state)); + } + else + { + ControlPaint.DrawCheckBox(g, glyphBounds, ConvertToButtonState(state)); + } + + textColor = SystemColors.ControlText; + } + + TextRenderer.DrawText(g, checkBoxText, font, textBounds, textColor, flags); + + if (focused) + { + ControlPaint.DrawFocusRectangle(g, textBounds); + } + } + + /// + /// + /// Renders a CheckBox control. + /// + /// + public static void DrawCheckBox(Graphics g, Point glyphLocation, Rectangle textBounds, string checkBoxText, Font font, Image image, Rectangle imageBounds, bool focused, CheckBoxState state) + { + DrawCheckBox(g, glyphLocation, textBounds, checkBoxText, font, + TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine, + image, imageBounds, focused, state); + } + + /// + /// + /// Renders a CheckBox control. + /// + /// + public static void DrawCheckBox(Graphics g, Point glyphLocation, Rectangle textBounds, string checkBoxText, Font font, TextFormatFlags flags, Image image, Rectangle imageBounds, bool focused, CheckBoxState state) + { + Rectangle glyphBounds = new Rectangle(glyphLocation, GetGlyphSize(g, state)); + Color textColor; + + if (RenderWithVisualStyles) + { + InitializeRenderer((int)state); + + //Keep this drawing order! It matches default drawing order. + visualStyleRenderer.DrawImage(g, imageBounds, image); + visualStyleRenderer.DrawBackground(g, glyphBounds); + textColor = visualStyleRenderer.GetColor(ColorProperty.TextColor); + } + else + { + g.DrawImage(image, imageBounds); + if (IsMixed(state)) + { + ControlPaint.DrawMixedCheckBox(g, glyphBounds, ConvertToButtonState(state)); + } + else + { + ControlPaint.DrawCheckBox(g, glyphBounds, ConvertToButtonState(state)); + } + + textColor = SystemColors.ControlText; + } + + TextRenderer.DrawText(g, checkBoxText, font, textBounds, textColor, flags); + + if (focused) + { + ControlPaint.DrawFocusRectangle(g, textBounds); + } + } /// /// @@ -216,108 +250,130 @@ public static void DrawCheckBox(Graphics g, Point glyphLocation, Rectangle textB [ SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally ] - public static Size GetGlyphSize(Graphics g, CheckBoxState state) { + public static Size GetGlyphSize(Graphics g, CheckBoxState state) + { return GetGlyphSize(g, state, IntPtr.Zero); } - internal static Size GetGlyphSize(Graphics g, CheckBoxState state, IntPtr hWnd) { - if (RenderWithVisualStyles) { - InitializeRenderer((int)state); - - return visualStyleRenderer.GetPartSize(g, ThemeSizeType.Draw, hWnd); - } - - return new Size(13, 13); - } - - internal static ButtonState ConvertToButtonState(CheckBoxState state) { - switch (state) { - - case CheckBoxState.CheckedNormal: - case CheckBoxState.CheckedHot: - return ButtonState.Checked; - case CheckBoxState.CheckedPressed: - return (ButtonState.Checked | ButtonState.Pushed); - case CheckBoxState.CheckedDisabled: - return (ButtonState.Checked | ButtonState.Inactive); - - case CheckBoxState.UncheckedPressed: - return ButtonState.Pushed; - case CheckBoxState.UncheckedDisabled: - return ButtonState.Inactive; - - //Downlevel mixed drawing works only if ButtonState.Checked is set - case CheckBoxState.MixedNormal: - case CheckBoxState.MixedHot: - return ButtonState.Checked; - case CheckBoxState.MixedPressed: - return (ButtonState.Checked | ButtonState.Pushed); - case CheckBoxState.MixedDisabled: - return (ButtonState.Checked | ButtonState.Inactive); - - default: - return ButtonState.Normal; - } - } - - internal static CheckBoxState ConvertFromButtonState(ButtonState state, bool isMixed, bool isHot) { - if (isMixed) { - if ((state & ButtonState.Pushed) == ButtonState.Pushed) { - return CheckBoxState.MixedPressed; - } - else if ((state & ButtonState.Inactive) == ButtonState.Inactive) { - return CheckBoxState.MixedDisabled; - } - else if (isHot) { - return CheckBoxState.MixedHot; - } - - return CheckBoxState.MixedNormal; - } - else if ((state & ButtonState.Checked) == ButtonState.Checked) { - if ((state & ButtonState.Pushed) == ButtonState.Pushed) { - return CheckBoxState.CheckedPressed; - } - else if ((state & ButtonState.Inactive) == ButtonState.Inactive) { - return CheckBoxState.CheckedDisabled; - } - else if (isHot) { - return CheckBoxState.CheckedHot; - } - - return CheckBoxState.CheckedNormal; - } - else { //unchecked - if ((state & ButtonState.Pushed) == ButtonState.Pushed) { - return CheckBoxState.UncheckedPressed; - } - else if ((state & ButtonState.Inactive) == ButtonState.Inactive) { - return CheckBoxState.UncheckedDisabled; - } - else if (isHot) { - return CheckBoxState.UncheckedHot; - } - - return CheckBoxState.UncheckedNormal; - } - } - - private static bool IsMixed(CheckBoxState state) { - switch (state) { - - case CheckBoxState.MixedNormal: - case CheckBoxState.MixedHot: - case CheckBoxState.MixedPressed: - case CheckBoxState.MixedDisabled: - return true; - - default: - return false; - } - } - - private static bool IsDisabled(CheckBoxState state) { - switch (state) { + internal static Size GetGlyphSize(Graphics g, CheckBoxState state, IntPtr hWnd) + { + if (RenderWithVisualStyles) + { + InitializeRenderer((int)state); + + return visualStyleRenderer.GetPartSize(g, ThemeSizeType.Draw, hWnd); + } + + return new Size(13, 13); + } + + internal static ButtonState ConvertToButtonState(CheckBoxState state) + { + switch (state) + { + + case CheckBoxState.CheckedNormal: + case CheckBoxState.CheckedHot: + return ButtonState.Checked; + case CheckBoxState.CheckedPressed: + return (ButtonState.Checked | ButtonState.Pushed); + case CheckBoxState.CheckedDisabled: + return (ButtonState.Checked | ButtonState.Inactive); + + case CheckBoxState.UncheckedPressed: + return ButtonState.Pushed; + case CheckBoxState.UncheckedDisabled: + return ButtonState.Inactive; + + //Downlevel mixed drawing works only if ButtonState.Checked is set + case CheckBoxState.MixedNormal: + case CheckBoxState.MixedHot: + return ButtonState.Checked; + case CheckBoxState.MixedPressed: + return (ButtonState.Checked | ButtonState.Pushed); + case CheckBoxState.MixedDisabled: + return (ButtonState.Checked | ButtonState.Inactive); + + default: + return ButtonState.Normal; + } + } + + internal static CheckBoxState ConvertFromButtonState(ButtonState state, bool isMixed, bool isHot) + { + if (isMixed) + { + if ((state & ButtonState.Pushed) == ButtonState.Pushed) + { + return CheckBoxState.MixedPressed; + } + else if ((state & ButtonState.Inactive) == ButtonState.Inactive) + { + return CheckBoxState.MixedDisabled; + } + else if (isHot) + { + return CheckBoxState.MixedHot; + } + + return CheckBoxState.MixedNormal; + } + else if ((state & ButtonState.Checked) == ButtonState.Checked) + { + if ((state & ButtonState.Pushed) == ButtonState.Pushed) + { + return CheckBoxState.CheckedPressed; + } + else if ((state & ButtonState.Inactive) == ButtonState.Inactive) + { + return CheckBoxState.CheckedDisabled; + } + else if (isHot) + { + return CheckBoxState.CheckedHot; + } + + return CheckBoxState.CheckedNormal; + } + else + { //unchecked + if ((state & ButtonState.Pushed) == ButtonState.Pushed) + { + return CheckBoxState.UncheckedPressed; + } + else if ((state & ButtonState.Inactive) == ButtonState.Inactive) + { + return CheckBoxState.UncheckedDisabled; + } + else if (isHot) + { + return CheckBoxState.UncheckedHot; + } + + return CheckBoxState.UncheckedNormal; + } + } + + private static bool IsMixed(CheckBoxState state) + { + switch (state) + { + + case CheckBoxState.MixedNormal: + case CheckBoxState.MixedHot: + case CheckBoxState.MixedPressed: + case CheckBoxState.MixedDisabled: + return true; + + default: + return false; + } + } + + private static bool IsDisabled(CheckBoxState state) + { + switch (state) + { case CheckBoxState.CheckedDisabled: case CheckBoxState.UncheckedDisabled: case CheckBoxState.MixedDisabled: @@ -328,19 +384,23 @@ private static bool IsDisabled(CheckBoxState state) { } } - private static void InitializeRenderer(int state) { + private static void InitializeRenderer(int state) + { int part = CheckBoxElement.Part; if (SystemInformation.HighContrast && IsDisabled((CheckBoxState)state) - && VisualStyleRenderer.IsCombinationDefined(CheckBoxElement.ClassName, VisualStyleElement.Button.CheckBox.HighContrastDisabledPart)) { - part = VisualStyleElement.Button.CheckBox.HighContrastDisabledPart; + && VisualStyleRenderer.IsCombinationDefined(CheckBoxElement.ClassName, VisualStyleElement.Button.CheckBox.HighContrastDisabledPart)) + { + part = VisualStyleElement.Button.CheckBox.HighContrastDisabledPart; } - if (visualStyleRenderer == null) { - visualStyleRenderer = new VisualStyleRenderer(CheckBoxElement.ClassName, part, state); + if (visualStyleRenderer == null) + { + visualStyleRenderer = new VisualStyleRenderer(CheckBoxElement.ClassName, part, state); } - else { - visualStyleRenderer.SetParameters(CheckBoxElement.ClassName, part, state); + else + { + visualStyleRenderer.SetParameters(CheckBoxElement.ClassName, part, state); } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/CheckedListBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/CheckedListBox.cs index 1c2ce05c116..e2f417480c2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/CheckedListBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/CheckedListBox.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Accessibility; using System.Text; @@ -26,7 +27,7 @@ namespace System.Windows.Forms { using System.Drawing.Design; using System.Globalization; using System.Drawing.Text; - + /// /// @@ -43,7 +44,8 @@ namespace System.Windows.Forms { LookupBindingProperties(), // ...overrides equivalent attribute in ListControl SRDescription(nameof(SR.DescriptionCheckedListBox)) ] - public class CheckedListBox : ListBox { + public class CheckedListBox : ListBox + { private int idealCheckSize = 13; @@ -92,7 +94,8 @@ public class CheckedListBox : ListBox { private static int LBC_GETCHECKSTATE; private static int LBC_SETCHECKSTATE; - static CheckedListBox() { + static CheckedListBox() + { LBC_GETCHECKSTATE = SafeNativeMethods.RegisterWindowMessage("LBC_GETCHECKSTATE"); LBC_SETCHECKSTATE = SafeNativeMethods.RegisterWindowMessage("LBC_SETCHECKSTATE"); } @@ -100,15 +103,16 @@ static CheckedListBox() { /// /// Creates a new CheckedListBox for the user. /// - public CheckedListBox() : base() { + public CheckedListBox() : base() + { // If we eat WM_ERASEBKGRND messages, the background will be // painted sometimes but not others. // SetStyle(ControlStyles.Opaque, true); // If a long item is drawn with ellipsis, we must redraw the ellipsed part // as well as the newly uncovered region. - SetStyle(ControlStyles.ResizeRedraw, true); - + SetStyle(ControlStyles.ResizeRedraw, true); + } /// @@ -122,12 +126,15 @@ public CheckedListBox() : base() { DefaultValue(false), SRDescription(nameof(SR.CheckedListBoxCheckOnClickDescr)) ] - public bool CheckOnClick { - get { + public bool CheckOnClick + { + get + { return checkOnClick; } - set { + set + { checkOnClick = value; } } @@ -139,9 +146,12 @@ public bool CheckOnClick { Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public CheckedIndexCollection CheckedIndices { - get { - if (checkedIndexCollection == null) { + public CheckedIndexCollection CheckedIndices + { + get + { + if (checkedIndexCollection == null) + { checkedIndexCollection = new CheckedIndexCollection(this); } return checkedIndexCollection; @@ -155,9 +165,12 @@ public CheckedIndexCollection CheckedIndices { Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public CheckedItemCollection CheckedItems { - get { - if (checkedItemCollection == null) { + public CheckedItemCollection CheckedItems + { + get + { + if (checkedItemCollection == null) + { checkedItemCollection = new CheckedItemCollection(this); } return checkedItemCollection; @@ -170,8 +183,10 @@ public CheckedItemCollection CheckedItems { /// base.CreateParams() to make sure the control continues to work /// correctly. /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.Style |= NativeMethods.LBS_OWNERDRAWFIXED | NativeMethods.LBS_WANTKEYBOARDINPUT; return cp; @@ -184,11 +199,14 @@ protected override CreateParams CreateParams { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new object DataSource { - get { + public new object DataSource + { + get + { return base.DataSource; } - set { + set + { base.DataSource = value; } } @@ -198,11 +216,14 @@ protected override CreateParams CreateParams { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new string DisplayMember { - get { - return base.DisplayMember ; + public new string DisplayMember + { + get + { + return base.DisplayMember; } - set { + set + { base.DisplayMember = value; } } @@ -211,11 +232,14 @@ protected override CreateParams CreateParams { Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public override DrawMode DrawMode { - get { + public override DrawMode DrawMode + { + get + { return DrawMode.Normal; } - set { + set + { } } @@ -223,12 +247,15 @@ public override DrawMode DrawMode { Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public override int ItemHeight { - get { + public override int ItemHeight + { + get + { // this should take FontHeight + buffer into Consideration. return Font.Height + scaledListItemBordersHeight; } - set { + set + { } } @@ -242,16 +269,20 @@ public override int ItemHeight { SRDescription(nameof(SR.ListBoxItemsDescr)), Editor("System.Windows.Forms.Design.ListControlStringCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)) ] - new public CheckedListBox.ObjectCollection Items { - get { - return(CheckedListBox.ObjectCollection)base.Items; + new public CheckedListBox.ObjectCollection Items + { + get + { + return (CheckedListBox.ObjectCollection)base.Items; } } // Computes the maximum width of all items in the ListBox // - internal override int MaxItemWidth { - get { + internal override int MaxItemWidth + { + get + { // Overridden to include the size of the checkbox // Allows for one pixel either side of the checkbox, plus another 1 pixel buffer = 3 pixels // @@ -263,21 +294,27 @@ internal override int MaxItemWidth { /// For CheckedListBoxes, multi-selection is not supported. You can set /// selection to be able to select one item or no items. /// - public override SelectionMode SelectionMode { - get { + public override SelectionMode SelectionMode + { + get + { return base.SelectionMode; } - set { + set + { //valid values are 0x0 to 0x3 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)SelectionMode.None, (int)SelectionMode.MultiExtended)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)SelectionMode.None, (int)SelectionMode.MultiExtended)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(SelectionMode)); } if (value != SelectionMode.One - && value != SelectionMode.None) { + && value != SelectionMode.None) + { throw new ArgumentException(SR.CheckedListBoxInvalidSelectionMode); } - if (value != SelectionMode) { + if (value != SelectionMode) + { base.SelectionMode = value; RecreateHandle(); } @@ -292,19 +329,24 @@ public override SelectionMode SelectionMode { DefaultValue(false), SRDescription(nameof(SR.CheckedListBoxThreeDCheckBoxesDescr)) ] - public bool ThreeDCheckBoxes { - get { + public bool ThreeDCheckBoxes + { + get + { return !flat; } - set { + set + { // change the style and repaint. // - if (flat == value) { + if (flat == value) + { flat = !value; // see if we have some items, and only invalidate if we do. - CheckedListBox.ObjectCollection items = (CheckedListBox.ObjectCollection) Items; - if ((items != null) && (items.Count > 0)) { + CheckedListBox.ObjectCollection items = (CheckedListBox.ObjectCollection)Items; + if ((items != null) && (items.Count > 0)) + { this.Invalidate(); } } @@ -319,11 +361,14 @@ public bool ThreeDCheckBoxes { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.UseCompatibleTextRenderingDescr)) ] - public bool UseCompatibleTextRendering { - get{ + public bool UseCompatibleTextRendering + { + get + { return base.UseCompatibleTextRenderingInt; } - set{ + set + { base.UseCompatibleTextRenderingInt = value; } } @@ -333,8 +378,10 @@ public bool UseCompatibleTextRendering { /// This is provided for container controls to iterate through its children to set UseCompatibleTextRendering to the same /// value if the child control supports it. /// - internal override bool SupportsUseCompatibleTextRendering { - get { + internal override bool SupportsUseCompatibleTextRendering + { + get + { return true; } } @@ -344,58 +391,68 @@ internal override bool SupportsUseCompatibleTextRendering { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new string ValueMember { - get { + public new string ValueMember + { + get + { return base.ValueMember; } - set { + set + { base.ValueMember = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler DataSourceChanged { + new public event EventHandler DataSourceChanged + { add => base.DataSourceChanged += value; remove => base.DataSourceChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler DisplayMemberChanged { + new public event EventHandler DisplayMemberChanged + { add => base.DisplayMemberChanged += value; remove => base.DisplayMemberChanged -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.CheckedListBoxItemCheckDescr))] - public event ItemCheckEventHandler ItemCheck { + public event ItemCheckEventHandler ItemCheck + { add => onItemCheck += value; remove => onItemCheck -= value; } /// [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] - public new event EventHandler Click { + public new event EventHandler Click + { add => base.Click += value; remove => base.Click -= value; } /// [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] - public new event MouseEventHandler MouseClick { + public new event MouseEventHandler MouseClick + { add => base.MouseClick += value; remove => base.MouseClick -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event DrawItemEventHandler DrawItem { + public new event DrawItemEventHandler DrawItem + { add => base.DrawItem += value; remove => base.DrawItem -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event MeasureItemEventHandler MeasureItem { + public new event MeasureItemEventHandler MeasureItem + { add => base.MeasureItem += value; remove => base.MeasureItem -= value; } @@ -405,13 +462,15 @@ public event ItemCheckEventHandler ItemCheck { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Padding Padding { + public new Padding Padding + { get { return base.Padding; } - set { base.Padding = value;} + set { base.Padding = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler ValueMemberChanged { + new public event EventHandler ValueMemberChanged + { add => base.ValueMemberChanged += value; remove => base.ValueMemberChanged -= value; } @@ -420,11 +479,13 @@ public event ItemCheckEventHandler ItemCheck { /// Constructs the new instance of the accessibility object for this control. Subclasses /// should not call base.CreateAccessibilityObject. /// - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new CheckedListBoxAccessibleObject(this); } - protected override ListBox.ObjectCollection CreateItemCollection() { + protected override ListBox.ObjectCollection CreateItemCollection() + { return new ObjectCollection(this); } @@ -432,7 +493,8 @@ protected override ListBox.ObjectCollection CreateItemCollection() { /// Gets the check value of the current item. This value will be from the /// System.Windows.Forms.CheckState enumeration. /// - public CheckState GetItemCheckState(int index) { + public CheckState GetItemCheckState(int index) + { if (index < 0 || index >= Items.Count) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); @@ -443,15 +505,18 @@ public CheckState GetItemCheckState(int index) { /// Indicates if the given item is, in any way, shape, or form, checked. /// This will return true if the item is fully or indeterminately checked. /// - public bool GetItemChecked(int index) { - return(GetItemCheckState(index) != CheckState.Unchecked); + public bool GetItemChecked(int index) + { + return (GetItemCheckState(index) != CheckState.Unchecked); } /// /// Invalidates the given item in the listbox /// - private void InvalidateItem(int index) { - if (IsHandleCreated) { + private void InvalidateItem(int index) + { + if (IsHandleCreated) + { NativeMethods.RECT rect = new NativeMethods.RECT(); SendMessage(NativeMethods.LB_GETITEMRECT, index, ref rect); SafeNativeMethods.InvalidateRect(new HandleRef(this, Handle), ref rect, false); @@ -461,7 +526,8 @@ private void InvalidateItem(int index) { /// /// A redirected LBN_SELCHANGE message notification. /// - private void LbnSelChange() { + private void LbnSelChange() + { // prepare to change the selection. we'll fire an event for // this. Note that we'll only change the selection when the @@ -486,7 +552,8 @@ private void LbnSelChange() { //# VS7 86 - if (!killnextselect && (index == lastSelected || checkOnClick == true)) { + if (!killnextselect && (index == lastSelected || checkOnClick == true)) + { CheckState currentValue = CheckedItems.GetCheckedState(index); CheckState newValue = (currentValue != CheckState.Unchecked) ? CheckState.Unchecked @@ -511,19 +578,21 @@ private void LbnSelChange() { /// /// Ensures that mouse clicks can toggle... /// - protected override void OnClick(EventArgs e) { + protected override void OnClick(EventArgs e) + { killnextselect = false; base.OnClick(e); } - + /// /// When the handle is created we can dump any cached item-check pairs. /// - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { base.OnHandleCreated(e); SendMessage(NativeMethods.LB_SETITEMHEIGHT, 0, ItemHeight); - + } /// @@ -533,7 +602,8 @@ protected override void OnHandleCreated(EventArgs e) { /// however, remember to call base.OnDrawItem(e); to ensure the event is /// still fired to external listeners /// - protected override void OnDrawItem(DrawItemEventArgs e) { + protected override void OnDrawItem(DrawItemEventArgs e) + { object item; if (Font.Height < 0) @@ -541,11 +611,14 @@ protected override void OnDrawItem(DrawItemEventArgs e) { this.Font = Control.DefaultFont; } - if (e.Index >= 0) { - if (e.Index < Items.Count) { + if (e.Index >= 0) + { + if (e.Index < Items.Count) + { item = Items[e.Index]; } - else { + else + { // If the item is not part of our collection, we will just // get the string for it and display it. // @@ -558,11 +631,14 @@ protected override void OnDrawItem(DrawItemEventArgs e) { // set up the appearance of the checkbox // ButtonState state = ButtonState.Normal; - if (flat) { + if (flat) + { state |= ButtonState.Flat; } - if (e.Index < Items.Count) { - switch (CheckedItems.GetCheckedState(e.Index)) { + if (e.Index < Items.Count) + { + switch (CheckedItems.GetCheckedState(e.Index)) + { case CheckState.Checked: state |= ButtonState.Checked; break; @@ -574,9 +650,10 @@ protected override void OnDrawItem(DrawItemEventArgs e) { // If we are drawing themed CheckBox .. get the size from renderer.. // the Renderer might return a different size in different DPI modes.. - if (Application.RenderWithVisualStyles) { - VisualStyles.CheckBoxState cbState = CheckBoxRenderer.ConvertFromButtonState(state, false, ((e.State & DrawItemState.HotLight) == DrawItemState.HotLight)); - idealCheckSize = (int)(CheckBoxRenderer.GetGlyphSize(e.Graphics, cbState, HandleInternal)).Width; + if (Application.RenderWithVisualStyles) + { + VisualStyles.CheckBoxState cbState = CheckBoxRenderer.ConvertFromButtonState(state, false, ((e.State & DrawItemState.HotLight) == DrawItemState.HotLight)); + idealCheckSize = (int)(CheckBoxRenderer.GetGlyphSize(e.Graphics, cbState, HandleInternal)).Width; } // Determine bounds for the checkbox @@ -584,7 +661,8 @@ protected override void OnDrawItem(DrawItemEventArgs e) { int centeringFactor = Math.Max((height - idealCheckSize) / 2, 0); // Keep the checkbox within the item's upper and lower bounds - if (centeringFactor + idealCheckSize > bounds.Height) { + if (centeringFactor + idealCheckSize > bounds.Height) + { centeringFactor = bounds.Height - idealCheckSize; } @@ -593,22 +671,25 @@ protected override void OnDrawItem(DrawItemEventArgs e) { idealCheckSize, idealCheckSize); - if (RightToLeft == RightToLeft.Yes) { + if (RightToLeft == RightToLeft.Yes) + { // For a RightToLeft checked list box, we want the checkbox // to be drawn at the right. // So we override the X position. box.X = bounds.X + bounds.Width - idealCheckSize - scaledListItemStartPosition; } - + // Draw the checkbox. // - if (Application.RenderWithVisualStyles) { + if (Application.RenderWithVisualStyles) + { VisualStyles.CheckBoxState cbState = CheckBoxRenderer.ConvertFromButtonState(state, false, ((e.State & DrawItemState.HotLight) == DrawItemState.HotLight)); CheckBoxRenderer.DrawCheckBox(e.Graphics, new Point(box.X, box.Y), cbState, HandleInternal); } - else { + else + { ControlPaint.DrawCheckBox(e.Graphics, box, state); } @@ -619,7 +700,8 @@ protected override void OnDrawItem(DrawItemEventArgs e) { bounds.Y, bounds.Width - (idealCheckSize + (scaledListItemStartPosition * 2)), bounds.Height); - if (RightToLeft == RightToLeft.Yes) { + if (RightToLeft == RightToLeft.Yes) + { // For a RightToLeft checked list box, we want the text // to be drawn at the left. // So we override the X position. @@ -631,14 +713,16 @@ protected override void OnDrawItem(DrawItemEventArgs e) { string text = string.Empty; Color backColor = (SelectionMode != SelectionMode.None) ? e.BackColor : BackColor; Color foreColor = (SelectionMode != SelectionMode.None) ? e.ForeColor : ForeColor; - if (!Enabled) { + if (!Enabled) + { foreColor = SystemColors.GrayText; - } + } Font font = Font; text = GetItemText(item); - if (SelectionMode != SelectionMode.None && (e.State & DrawItemState.Selected) == DrawItemState.Selected) { + if (SelectionMode != SelectionMode.None && (e.State & DrawItemState.Selected) == DrawItemState.Selected) + { if (Enabled) { backColor = SystemColors.Highlight; @@ -656,7 +740,8 @@ protected override void OnDrawItem(DrawItemEventArgs e) { // Due to some sort of unpredictable painting optimization in the Windows ListBox control, // we need to always paint the background rectangle for the current line. - using (Brush b = new SolidBrush(backColor)) { + using (Brush b = new SolidBrush(backColor)) + { e.Graphics.FillRectangle(b, textBounds); } @@ -666,26 +751,32 @@ protected override void OnDrawItem(DrawItemEventArgs e) { textBounds.Width - BORDER_SIZE, textBounds.Height - 2 * BORDER_SIZE); // minus borders - if( UseCompatibleTextRendering ){ - using (StringFormat format = new StringFormat()) { - if (UseTabStops) { + if (UseCompatibleTextRendering) + { + using (StringFormat format = new StringFormat()) + { + if (UseTabStops) + { // Set tab stops so it looks similar to a ListBox, at least with the default font size. float tabDistance = 3.6f * Font.Height; // about 7 characters float[] tabStops = new float[15]; - float tabOffset = -(idealCheckSize + (scaledListItemStartPosition * 2)); + float tabOffset = -(idealCheckSize + (scaledListItemStartPosition * 2)); for (int i = 1; i < tabStops.Length; i++) tabStops[i] = tabDistance; //( - if (Math.Abs(tabOffset) < tabDistance) { - tabStops[0] = tabDistance +tabOffset; + if (Math.Abs(tabOffset) < tabDistance) + { + tabStops[0] = tabDistance + tabOffset; } - else { - tabStops[0] = tabDistance; + else + { + tabStops[0] = tabDistance; } format.SetTabStops(0, tabStops); } - else if (UseCustomTabOffsets) { + else if (UseCustomTabOffsets) + { //Set TabStops to userDefined values int wpar = CustomTabOffsets.Count; float[] tabStops = new float[wpar]; @@ -694,7 +785,8 @@ protected override void OnDrawItem(DrawItemEventArgs e) { } // Adjust string format for Rtl controls - if (RightToLeft == RightToLeft.Yes) { + if (RightToLeft == RightToLeft.Yes) + { format.FormatFlags |= StringFormatFlags.DirectionRightToLeft; } @@ -707,39 +799,45 @@ protected override void OnDrawItem(DrawItemEventArgs e) { format.Trimming = StringTrimming.None; // Do actual drawing - using (SolidBrush brush = new SolidBrush(foreColor)) { + using (SolidBrush brush = new SolidBrush(foreColor)) + { e.Graphics.DrawString(text, font, brush, stringBounds, format); } } } - else{ + else + { TextFormatFlags flags = TextFormatFlags.Default; flags |= TextFormatFlags.NoPrefix; - if (UseTabStops || UseCustomTabOffsets) { + if (UseTabStops || UseCustomTabOffsets) + { flags |= TextFormatFlags.ExpandTabs; } // Adjust string format for Rtl controls - if (RightToLeft == RightToLeft.Yes) { + if (RightToLeft == RightToLeft.Yes) + { flags |= TextFormatFlags.RightToLeft; flags |= TextFormatFlags.Right; } // Do actual drawing - TextRenderer.DrawText(e.Graphics, text, font, stringBounds, foreColor, flags ); + TextRenderer.DrawText(e.Graphics, text, font, stringBounds, foreColor, flags); } // Draw the focus rect if required // if ((e.State & DrawItemState.Focus) == DrawItemState.Focus && - (e.State & DrawItemState.NoFocusRect) != DrawItemState.NoFocusRect) { + (e.State & DrawItemState.NoFocusRect) != DrawItemState.NoFocusRect) + { ControlPaint.DrawFocusRectangle(e.Graphics, textBounds, foreColor, backColor); } } if (Items.Count == 0 && - e.Bounds.Width > 2 * BORDER_SIZE && e.Bounds.Height > 2 * BORDER_SIZE) { + e.Bounds.Width > 2 * BORDER_SIZE && e.Bounds.Height > 2 * BORDER_SIZE) + { Color backColor = (SelectionMode != SelectionMode.None) ? e.BackColor : BackColor; Rectangle bounds = e.Bounds; Rectangle emptyRectangle = new Rectangle( @@ -747,38 +845,46 @@ protected override void OnDrawItem(DrawItemEventArgs e) { bounds.Y, bounds.Width - BORDER_SIZE, bounds.Height - 2 * BORDER_SIZE); // Upper and lower borders. - if (Focused) { + if (Focused) + { // Draw focus rectangle for virtual first item in the list if there are no items in the list. Color foreColor = (SelectionMode != SelectionMode.None) ? e.ForeColor : ForeColor; - if (!Enabled) { + if (!Enabled) + { foreColor = SystemColors.GrayText; } ControlPaint.DrawFocusRectangle(e.Graphics, emptyRectangle, foreColor, backColor); } - else if (!Application.RenderWithVisualStyles) { + else if (!Application.RenderWithVisualStyles) + { // If VisualStyles are off, rectangle needs to be explicitly erased, when focus is lost. // This is because of persisting empty focus rectangle when VisualStyles are off. - using (Brush brush = new SolidBrush(backColor)) { + using (Brush brush = new SolidBrush(backColor)) + { e.Graphics.FillRectangle(brush, emptyRectangle); } } } } - protected override void OnBackColorChanged(EventArgs e) { + protected override void OnBackColorChanged(EventArgs e) + { base.OnBackColorChanged(e); - if (IsHandleCreated) { + if (IsHandleCreated) + { SafeNativeMethods.InvalidateRect(new HandleRef(this, Handle), null, true); } } - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { // Update the item height // - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(NativeMethods.LB_SETITEMHEIGHT, 0, ItemHeight); } @@ -794,9 +900,11 @@ protected override void OnFontChanged(EventArgs e) { /// forget to call base.OnKeyPress() to ensure that KeyPrese events /// are correctly fired for all other keys. /// - protected override void OnKeyPress(KeyPressEventArgs e) { - if (e.KeyChar == ' ' && SelectionMode != SelectionMode.None) { - LbnSelChange(); + protected override void OnKeyPress(KeyPressEventArgs e) + { + if (e.KeyChar == ' ' && SelectionMode != SelectionMode.None) + { + LbnSelChange(); } if (FormattingEnabled) //We want to fire KeyPress only when FormattingEnabled (this is a whidbey property) { @@ -809,17 +917,21 @@ protected override void OnKeyPress(KeyPressEventArgs e) { /// forget to call base.onItemCheck() to ensure that itemCheck vents /// are correctly fired for all other keys. /// - protected virtual void OnItemCheck(ItemCheckEventArgs ice) { - if (onItemCheck != null) onItemCheck(this, ice); + protected virtual void OnItemCheck(ItemCheckEventArgs ice) + { + if (onItemCheck != null) + onItemCheck(this, ice); } - protected override void OnMeasureItem(MeasureItemEventArgs e) { + protected override void OnMeasureItem(MeasureItemEventArgs e) + { base.OnMeasureItem(e); // we'll use the ideal checkbox size plus enough for padding on the top // and bottom // - if (e.ItemHeight < idealCheckSize + 2) { + if (e.ItemHeight < idealCheckSize + 2) + { e.ItemHeight = idealCheckSize + 2; } } @@ -831,7 +943,8 @@ protected override void OnMeasureItem(MeasureItemEventArgs e) { /// however, remember to call base.OnSelectedIndexChanged(e); to ensure the event is /// still fired to external listeners /// - protected override void OnSelectedIndexChanged(EventArgs e) { + protected override void OnSelectedIndexChanged(EventArgs e) + { base.OnSelectedIndexChanged(e); lastSelected = SelectedIndex; @@ -839,22 +952,23 @@ protected override void OnSelectedIndexChanged(EventArgs e) { } - + /// /// Reparses the objects, getting new text strings for them. /// - protected override void RefreshItems() { + protected override void RefreshItems() + { Hashtable savedcheckedItems = new Hashtable(); - for (int i =0; i < Items.Count ; i ++) + for (int i = 0; i < Items.Count; i++) { savedcheckedItems[i] = CheckedItems.GetCheckedState(i); } - + //call the base base.RefreshItems(); // restore the checkedItems... - for (int j =0; j < Items.Count; j++) + for (int j = 0; j < Items.Count; j++) { CheckedItems.SetCheckedState(j, (CheckState)savedcheckedItems[j]); } @@ -864,21 +978,26 @@ protected override void RefreshItems() { /// Sets the checked value of the given item. This value should be from /// the System.Windows.Forms.CheckState enumeration. /// - public void SetItemCheckState(int index, CheckState value) { - if (index < 0 || index >= Items.Count) { + public void SetItemCheckState(int index, CheckState value) + { + if (index < 0 || index >= Items.Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } // valid values are 0-2 inclusive. - if (!ClientUtils.IsEnumValid(value,(int)value, (int)CheckState.Unchecked, (int)CheckState.Indeterminate)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)CheckState.Unchecked, (int)CheckState.Indeterminate)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(CheckState)); } CheckState currentValue = CheckedItems.GetCheckedState(index); - if (value != currentValue) { + if (value != currentValue) + { ItemCheckEventArgs itemCheckEvent = new ItemCheckEventArgs(index, value, currentValue); OnItemCheck(itemCheckEvent); - if (itemCheckEvent.NewValue != currentValue) { + if (itemCheckEvent.NewValue != currentValue) + { CheckedItems.SetCheckedState(index, itemCheckEvent.NewValue); InvalidateItem(index); } @@ -889,15 +1008,18 @@ public void SetItemCheckState(int index, CheckState value) { /// Sets the checked value of the given item. This value should be a /// boolean. /// - public void SetItemChecked(int index, bool value) { + public void SetItemChecked(int index, bool value) + { SetItemCheckState(index, value ? CheckState.Checked : CheckState.Unchecked); } /// /// We need to get LBN_SELCHANGE notifications /// - protected override void WmReflectCommand(ref Message m) { - switch (NativeMethods.Util.HIWORD(m.WParam)) { + protected override void WmReflectCommand(ref Message m) + { + switch (NativeMethods.Util.HIWORD(m.WParam)) + { case NativeMethods.LBN_SELCHANGE: LbnSelChange(); // finally, fire the OnSelectionChange event. @@ -921,9 +1043,11 @@ protected override void WmReflectCommand(ref Message m) { /// Handle keyboard input to prevent arrow keys from toggling /// checkboxes in CheckOnClick mode. /// - private void WmReflectVKeyToItem(ref Message m) { + private void WmReflectVKeyToItem(ref Message m) + { int keycode = NativeMethods.Util.LOWORD(m.WParam); - switch ((Keys)keycode) { + switch ((Keys)keycode) + { case Keys.Up: case Keys.Down: case Keys.PageUp: @@ -946,48 +1070,59 @@ private void WmReflectVKeyToItem(ref Message m) { /// to add extra functionality, but should not forget to call /// base.wndProc(m); to ensure the button continues to function properly. /// - protected override void WndProc(ref Message m) { + protected override void WndProc(ref Message m) + { - switch (m.Msg) { + switch (m.Msg) + { case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_CHARTOITEM: m.Result = NativeMethods.InvalidIntPtr; break; case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_VKEYTOITEM: WmReflectVKeyToItem(ref m); break; - default: - if (m.Msg == LBC_GETCHECKSTATE) { - int item = unchecked( (int) (long)m.WParam); - if (item < 0 || item >= Items.Count) { + default: + if (m.Msg == LBC_GETCHECKSTATE) + { + int item = unchecked((int)(long)m.WParam); + if (item < 0 || item >= Items.Count) + { m.Result = (IntPtr)LB_ERROR; } - else { + else + { m.Result = (IntPtr)(GetItemChecked(item) ? LB_CHECKED : LB_UNCHECKED); } } - else if (m.Msg == LBC_SETCHECKSTATE) { - int item = unchecked( (int) (long)m.WParam); - int state = unchecked( (int) (long)m.LParam); - if (item < 0 || item >= Items.Count || (state != LB_CHECKED && state != LB_UNCHECKED)) { + else if (m.Msg == LBC_SETCHECKSTATE) + { + int item = unchecked((int)(long)m.WParam); + int state = unchecked((int)(long)m.LParam); + if (item < 0 || item >= Items.Count || (state != LB_CHECKED && state != LB_UNCHECKED)) + { m.Result = IntPtr.Zero; } - else { + else + { SetItemChecked(item, (state == LB_CHECKED)); m.Result = (IntPtr)1; } } - else { + else + { base.WndProc(ref m); } break; } } - new public class ObjectCollection : ListBox.ObjectCollection { + new public class ObjectCollection : ListBox.ObjectCollection + { private CheckedListBox owner; public ObjectCollection(CheckedListBox owner) - : base(owner) { + : base(owner) + { this.owner = owner; } @@ -995,7 +1130,8 @@ public ObjectCollection(CheckedListBox owner) /// Lets the user add an item to the listbox with the given initial value /// for the Checked portion of the item. /// - public int Add(object item, bool isChecked) { + public int Add(object item, bool isChecked) + { return Add(item, isChecked ? CheckState.Checked : CheckState.Unchecked); } @@ -1003,12 +1139,14 @@ public int Add(object item, bool isChecked) { /// Lets the user add an item to the listbox with the given initial value /// for the Checked portion of the item. /// - public int Add(object item, CheckState check) { + public int Add(object item, CheckState check) + { //validate the enum that's passed in here // // Valid values are 0-2 inclusive. - if (!ClientUtils.IsEnumValid(check, (int)check, (int)CheckState.Unchecked, (int)CheckState.Indeterminate)){ + if (!ClientUtils.IsEnumValid(check, (int)check, (int)CheckState.Unchecked, (int)CheckState.Indeterminate)) + { throw new InvalidEnumArgumentException(nameof(check), (int)check, typeof(CheckState)); } @@ -1019,42 +1157,54 @@ public int Add(object item, CheckState check) { } } - public class CheckedIndexCollection : IList { + public class CheckedIndexCollection : IList + { private CheckedListBox owner; - internal CheckedIndexCollection(CheckedListBox owner) { + internal CheckedIndexCollection(CheckedListBox owner) + { this.owner = owner; } /// /// Number of current checked items. /// - public int Count { - get { + public int Count + { + get + { return owner.CheckedItems.Count; } } - object ICollection.SyncRoot { - get { + object ICollection.SyncRoot + { + get + { return this; } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return false; } } - bool IList.IsFixedSize { - get { + bool IList.IsFixedSize + { + get + { return true; } } - public bool IsReadOnly { - get { + public bool IsReadOnly + { + get + { return true; } } @@ -1063,58 +1213,74 @@ public bool IsReadOnly { /// Retrieves the specified checked item. /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public int this[int index] { - get { + public int this[int index] + { + get + { object identifier = InnerArray.GetEntryObject(index, CheckedItemCollection.AnyMask); return InnerArray.IndexOfIdentifier(identifier, 0); } } - object IList.this[int index] { - get { + object IList.this[int index] + { + get + { return this[index]; } - set { + set + { throw new NotSupportedException(SR.CheckedListBoxCheckedIndexCollectionIsReadOnly); } } - int IList.Add(object value) { + int IList.Add(object value) + { throw new NotSupportedException(SR.CheckedListBoxCheckedIndexCollectionIsReadOnly); } - void IList.Clear() { + void IList.Clear() + { throw new NotSupportedException(SR.CheckedListBoxCheckedIndexCollectionIsReadOnly); } - void IList.Insert(int index, object value) { + void IList.Insert(int index, object value) + { throw new NotSupportedException(SR.CheckedListBoxCheckedIndexCollectionIsReadOnly); } - void IList.Remove(object value) { + void IList.Remove(object value) + { throw new NotSupportedException(SR.CheckedListBoxCheckedIndexCollectionIsReadOnly); } - void IList.RemoveAt(int index) { + void IList.RemoveAt(int index) + { throw new NotSupportedException(SR.CheckedListBoxCheckedIndexCollectionIsReadOnly); } - public bool Contains(int index) { - return (IndexOf(index) != -1); + public bool Contains(int index) + { + return (IndexOf(index) != -1); } - bool IList.Contains(object index) { - if (index is int) { + bool IList.Contains(object index) + { + if (index is int) + { return Contains((int)index); } - else { + else + { return false; } } - public void CopyTo(Array dest, int index) { + public void CopyTo(Array dest, int index) + { int cnt = owner.CheckedItems.Count; - for (int i = 0; i < cnt; i++) { + for (int i = 0; i < cnt; i++) + { dest.SetValue(this[i], i + index); } } @@ -1123,38 +1289,47 @@ public void CopyTo(Array dest, int index) { /// This is the item array that stores our data. We share this backing store /// with the main object collection. /// - private ItemArray InnerArray { - get { + private ItemArray InnerArray + { + get + { return ((ObjectCollection)owner.Items).InnerArray; } } - public IEnumerator GetEnumerator() { + public IEnumerator GetEnumerator() + { int[] indices = new int[this.Count]; CopyTo(indices, 0); return indices.GetEnumerator(); } - public int IndexOf(int index) { - if (index >= 0 && index < owner.Items.Count) { + public int IndexOf(int index) + { + if (index >= 0 && index < owner.Items.Count) + { object value = InnerArray.GetEntryObject(index, 0); return owner.CheckedItems.IndexOfIdentifier(value); } return -1; } - int IList.IndexOf(object index) { - if (index is int) { + int IList.IndexOf(object index) + { + if (index is int) + { return IndexOf((int)index); } - else { + else + { return -1; } } } - public class CheckedItemCollection : IList { + public class CheckedItemCollection : IList + { internal static int CheckedItemMask = ItemArray.CreateMask(); internal static int IndeterminateItemMask = ItemArray.CreateMask(); @@ -1162,15 +1337,18 @@ public class CheckedItemCollection : IList { private CheckedListBox owner; - internal CheckedItemCollection(CheckedListBox owner) { + internal CheckedItemCollection(CheckedListBox owner) + { this.owner = owner; } /// /// Number of current checked items. /// - public int Count { - get { + public int Count + { + get + { return InnerArray.GetCount(AnyMask); } } @@ -1179,8 +1357,10 @@ public int Count { /// This is the item array that stores our data. We share this backing store /// with the main object collection. /// - private ItemArray InnerArray { - get { + private ItemArray InnerArray + { + get + { return ((ListBox.ObjectCollection)owner.Items).InnerArray; } } @@ -1189,74 +1369,95 @@ private ItemArray InnerArray { /// Retrieves the specified checked item. /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public object this[int index] { - get { + public object this[int index] + { + get + { return InnerArray.GetItem(index, AnyMask); } - set { + set + { throw new NotSupportedException(SR.CheckedListBoxCheckedItemCollectionIsReadOnly); } } - object ICollection.SyncRoot { - get { + object ICollection.SyncRoot + { + get + { return this; } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return false; } } - bool IList.IsFixedSize { - get { + bool IList.IsFixedSize + { + get + { return true; } } - public bool IsReadOnly { - get { + public bool IsReadOnly + { + get + { return true; } } - public bool Contains(object item) { + public bool Contains(object item) + { return IndexOf(item) != -1; } - public int IndexOf(object item) { + public int IndexOf(object item) + { return InnerArray.IndexOf(item, AnyMask); } - internal int IndexOfIdentifier(object item) { + internal int IndexOfIdentifier(object item) + { return InnerArray.IndexOfIdentifier(item, AnyMask); } - int IList.Add(object value) { + int IList.Add(object value) + { throw new NotSupportedException(SR.CheckedListBoxCheckedItemCollectionIsReadOnly); } - void IList.Clear() { + void IList.Clear() + { throw new NotSupportedException(SR.CheckedListBoxCheckedItemCollectionIsReadOnly); } - void IList.Insert(int index, object value) { + void IList.Insert(int index, object value) + { throw new NotSupportedException(SR.CheckedListBoxCheckedItemCollectionIsReadOnly); } - void IList.Remove(object value) { + void IList.Remove(object value) + { throw new NotSupportedException(SR.CheckedListBoxCheckedItemCollectionIsReadOnly); } - void IList.RemoveAt(int index) { + void IList.RemoveAt(int index) + { throw new NotSupportedException(SR.CheckedListBoxCheckedItemCollectionIsReadOnly); } - public void CopyTo(Array dest, int index) { + public void CopyTo(Array dest, int index) + { int cnt = InnerArray.GetCount(AnyMask); - for (int i = 0; i < cnt; i++) { + for (int i = 0; i < cnt; i++) + { dest.SetValue(InnerArray.GetItem(i, AnyMask), i + index); } } @@ -1265,32 +1466,38 @@ public void CopyTo(Array dest, int index) { /// This method returns if the actual item index is checked. The index is the index to the MAIN /// collection, not this one. /// - internal CheckState GetCheckedState(int index) { + internal CheckState GetCheckedState(int index) + { bool isChecked = InnerArray.GetState(index, CheckedItemMask); bool isIndeterminate = InnerArray.GetState(index, IndeterminateItemMask); Debug.Assert(!isChecked || !isIndeterminate, "Can't be both checked and indeterminate. Somebody broke our state."); - if (isIndeterminate) { + if (isIndeterminate) + { return CheckState.Indeterminate; } - else if (isChecked) { + else if (isChecked) + { return CheckState.Checked; } return CheckState.Unchecked; } - public IEnumerator GetEnumerator() { + public IEnumerator GetEnumerator() + { return InnerArray.GetEnumerator(AnyMask, true); } /// /// Same thing for GetChecked. /// - internal void SetCheckedState(int index, CheckState value) { + internal void SetCheckedState(int index, CheckState value) + { bool isChecked; bool isIndeterminate; - switch(value) { + switch (value) + { case CheckState.Checked: isChecked = true; isIndeterminate = false; @@ -1313,7 +1520,8 @@ internal void SetCheckedState(int index, CheckState value) { InnerArray.SetState(index, CheckedItemMask, isChecked); InnerArray.SetState(index, IndeterminateItemMask, isIndeterminate); - if (wasChecked != isChecked || wasIndeterminate != isIndeterminate) { + if (wasChecked != isChecked || wasIndeterminate != isIndeterminate) + { // Raise a notify event that this item has changed. owner.AccessibilityNotifyClients(AccessibleEvents.StateChange, index); } @@ -1323,81 +1531,101 @@ internal void SetCheckedState(int index, CheckState value) { /// /// [System.Runtime.InteropServices.ComVisible(true)] - internal class CheckedListBoxAccessibleObject : ControlAccessibleObject { + internal class CheckedListBoxAccessibleObject : ControlAccessibleObject + { /// /// - public CheckedListBoxAccessibleObject(CheckedListBox owner) : base(owner) { + public CheckedListBoxAccessibleObject(CheckedListBox owner) : base(owner) + { } - private CheckedListBox CheckedListBox { - get { + private CheckedListBox CheckedListBox + { + get + { return (CheckedListBox)Owner; } } /// /// - public override AccessibleObject GetChild(int index) { - if (index >= 0 && index < CheckedListBox.Items.Count) { + public override AccessibleObject GetChild(int index) + { + if (index >= 0 && index < CheckedListBox.Items.Count) + { return new CheckedListBoxItemAccessibleObject(this.CheckedListBox.GetItemText(CheckedListBox.Items[index]), index, this); } - else { + else + { return null; } } /// /// - public override int GetChildCount() { + public override int GetChildCount() + { return CheckedListBox.Items.Count; } - public override AccessibleObject GetFocused() { + public override AccessibleObject GetFocused() + { int index = CheckedListBox.FocusedIndex; - if (index >= 0) { + if (index >= 0) + { return GetChild(index); } return null; } - public override AccessibleObject GetSelected() { + public override AccessibleObject GetSelected() + { int index = CheckedListBox.SelectedIndex; - if (index >= 0) { + if (index >= 0) + { return GetChild(index); } return null; } - public override AccessibleObject HitTest(int x, int y) { + public override AccessibleObject HitTest(int x, int y) + { // Within a child element? // int count = GetChildCount(); - for(int index=0; index < count; ++index) { + for (int index = 0; index < count; ++index) + { AccessibleObject child = GetChild(index); - if (child.Bounds.Contains(x, y)) { + if (child.Bounds.Contains(x, y)) + { return child; } } // Within the CheckedListBox bounds? // - if (this.Bounds.Contains(x, y)) { + if (this.Bounds.Contains(x, y)) + { return this; } return null; } - public override AccessibleObject Navigate(AccessibleNavigation direction) { - if (GetChildCount() > 0) { - if (direction == AccessibleNavigation.FirstChild) { + public override AccessibleObject Navigate(AccessibleNavigation direction) + { + if (GetChildCount() > 0) + { + if (direction == AccessibleNavigation.FirstChild) + { return GetChild(0); } - if (direction == AccessibleNavigation.LastChild) { + if (direction == AccessibleNavigation.LastChild) + { return GetChild(GetChildCount() - 1); } } @@ -1408,20 +1636,24 @@ public override AccessibleObject Navigate(AccessibleNavigation direction) { /// /// [System.Runtime.InteropServices.ComVisible(true)] - internal class CheckedListBoxItemAccessibleObject : AccessibleObject { + internal class CheckedListBoxItemAccessibleObject : AccessibleObject + { private string name; private int index; private CheckedListBoxAccessibleObject parent; - public CheckedListBoxItemAccessibleObject(string name, int index, CheckedListBoxAccessibleObject parent) : base() { + public CheckedListBoxItemAccessibleObject(string name, int index, CheckedListBoxAccessibleObject parent) : base() + { this.name = name; this.parent = parent; this.index = index; } - public override Rectangle Bounds { - get { + public override Rectangle Bounds + { + get + { Rectangle rect = ParentCheckedListBox.GetItemRectangle(index); // Translate rect to screen coordinates @@ -1433,51 +1665,67 @@ public override Rectangle Bounds { } } - public override string DefaultAction { - get { - if (ParentCheckedListBox.GetItemChecked(index)) { + public override string DefaultAction + { + get + { + if (ParentCheckedListBox.GetItemChecked(index)) + { return SR.AccessibleActionUncheck; } - else { + else + { return SR.AccessibleActionCheck; } } } - private CheckedListBox ParentCheckedListBox { - get { - return(CheckedListBox)parent.Owner; + private CheckedListBox ParentCheckedListBox + { + get + { + return (CheckedListBox)parent.Owner; } } - public override string Name { - get { + public override string Name + { + get + { return name; } - set { + set + { name = value; } } - public override AccessibleObject Parent { - get { + public override AccessibleObject Parent + { + get + { return parent; } } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { return AccessibleRole.CheckButton; } } - public override AccessibleStates State { - get { + public override AccessibleStates State + { + get + { AccessibleStates state = AccessibleStates.Selectable | AccessibleStates.Focusable; // Checked state // - switch (ParentCheckedListBox.GetItemCheckState(index)) { + switch (ParentCheckedListBox.GetItemCheckState(index)) + { case CheckState.Checked: state |= AccessibleStates.Checked; break; @@ -1491,11 +1739,13 @@ public override AccessibleStates State { // Selected state // - if (ParentCheckedListBox.SelectedIndex == index) { + if (ParentCheckedListBox.SelectedIndex == index) + { state |= AccessibleStates.Selected | AccessibleStates.Focused; } - if (ParentCheckedListBox.Focused && ParentCheckedListBox.SelectedIndex == -1) { + if (ParentCheckedListBox.Focused && ParentCheckedListBox.SelectedIndex == -1) + { state |= AccessibleStates.Focused; } @@ -1504,22 +1754,28 @@ public override AccessibleStates State { } } - public override string Value { - get { + public override string Value + { + get + { return ParentCheckedListBox.GetItemChecked(index).ToString(); } } - public override void DoDefaultAction() { + public override void DoDefaultAction() + { ParentCheckedListBox.SetItemChecked(index, !ParentCheckedListBox.GetItemChecked(index)); } - public override AccessibleObject Navigate(AccessibleNavigation direction) { + public override AccessibleObject Navigate(AccessibleNavigation direction) + { // Down/Next // if (direction == AccessibleNavigation.Down || - direction == AccessibleNavigation.Next) { - if (index < parent.GetChildCount() - 1) { + direction == AccessibleNavigation.Next) + { + if (index < parent.GetChildCount() - 1) + { return parent.GetChild(index + 1); } } @@ -1527,8 +1783,10 @@ public override AccessibleObject Navigate(AccessibleNavigation direction) { // Up/Previous // if (direction == AccessibleNavigation.Up || - direction == AccessibleNavigation.Previous) { - if (index > 0) { + direction == AccessibleNavigation.Previous) + { + if (index > 0) + { return parent.GetChild(index - 1); } } @@ -1536,10 +1794,14 @@ public override AccessibleObject Navigate(AccessibleNavigation direction) { return base.Navigate(direction); } - public override void Select(AccessibleSelection flags) { - try { - ParentCheckedListBox.AccessibilityObject.GetSystemIAccessibleInternal().accSelect((int) flags, index + 1); - } catch (ArgumentException) { + public override void Select(AccessibleSelection flags) + { + try + { + ParentCheckedListBox.AccessibilityObject.GetSystemIAccessibleInternal().accSelect((int)flags, index + 1); + } + catch (ArgumentException) + { // In Everett, the CheckedListBox accessible children did not have any selection capability. // In Whidbey, they delegate the selection capability to OLEACC. // However, OLEACC does not deal w/ several Selection flags: ExtendSelection, AddSelection, RemoveSelection. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Clipboard.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Clipboard.cs index 00dd5cc07ad..11a7e51f7d4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Clipboard.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Clipboard.cs @@ -3,8 +3,9 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { - +namespace System.Windows.Forms +{ + using System; using System.Collections.Specialized; using System.ComponentModel; @@ -17,31 +18,39 @@ namespace System.Windows.Forms { using IComDataObject = System.Runtime.InteropServices.ComTypes.IDataObject; using System.Globalization; using System.Collections; - + /// /// Provides methods to place data on and retrieve data from the system clipboard. This class cannot be inherited. /// - public sealed class Clipboard { + public sealed class Clipboard + { // not creatable... // - private Clipboard() { + private Clipboard() + { } // // Checks the validity of format while setting data into ClipBoard // - private static bool IsFormatValid(DataObject data) { + private static bool IsFormatValid(DataObject data) + { return IsFormatValid(data.GetFormats()); } - internal static bool IsFormatValid(string[] formats) { + internal static bool IsFormatValid(string[] formats) + { Debug.Assert(formats != null, "Null returned from GetFormats"); - if (formats != null) { - if (formats.Length <= 4) { - for (int i = 0; i < formats.Length; i++) { - switch (formats[i]) { + if (formats != null) + { + if (formats.Length <= 4) + { + for (int i = 0; i < formats.Length; i++) + { + switch (formats[i]) + { case "Text": case "UnicodeText": case "System.String": @@ -58,18 +67,23 @@ internal static bool IsFormatValid(string[] formats) { return false; } - internal static bool IsFormatValid(FORMATETC[] formats) { + internal static bool IsFormatValid(FORMATETC[] formats) + { Debug.Assert(formats != null, "Null returned from GetFormats"); - if (formats != null) { - if (formats.Length <= 4) { - for (int i = 0; i < formats.Length; i++) { + if (formats != null) + { + if (formats.Length <= 4) + { + for (int i = 0; i < formats.Length; i++) + { short format = formats[i].cfFormat; if (format != NativeMethods.CF_TEXT && - format != NativeMethods.CF_UNICODETEXT && - format != DataFormats.GetFormat("System.String").Id && - format != DataFormats.GetFormat("Csv").Id) { - return false; + format != NativeMethods.CF_UNICODETEXT && + format != DataFormats.GetFormat("System.String").Id && + format != DataFormats.GetFormat("Csv").Id) + { + return false; } } return true; @@ -81,14 +95,16 @@ internal static bool IsFormatValid(FORMATETC[] formats) { /// /// Places nonpersistent data on the system . /// - public static void SetDataObject(object data) { + public static void SetDataObject(object data) + { SetDataObject(data, false); } /// /// Overload that uses default values for retryTimes and retryDelay. /// - public static void SetDataObject(object data, bool copy) { + public static void SetDataObject(object data, bool copy) + { SetDataObject(data, copy, 10 /*retryTimes*/, 100 /*retryDelay*/); } @@ -97,45 +113,57 @@ public static void SetDataObject(object data, bool copy) { /// should remain on the /// after the application exits. /// - public static void SetDataObject(object data, bool copy, int retryTimes, int retryDelay) { - if (Application.OleRequired() != System.Threading.ApartmentState.STA) { + public static void SetDataObject(object data, bool copy, int retryTimes, int retryDelay) + { + if (Application.OleRequired() != System.Threading.ApartmentState.STA) + { throw new System.Threading.ThreadStateException(SR.ThreadMustBeSTA); } - if (data == null) { + if (data == null) + { throw new ArgumentNullException(nameof(data)); } - if (retryTimes < 0) { + if (retryTimes < 0) + { throw new ArgumentOutOfRangeException(nameof(retryTimes), retryTimes, string.Format(SR.InvalidLowBoundArgumentEx, nameof(retryTimes), retryTimes, 0)); } - if (retryDelay < 0) { + if (retryDelay < 0) + { throw new ArgumentOutOfRangeException(nameof(retryDelay), retryDelay, string.Format(SR.InvalidLowBoundArgumentEx, nameof(retryDelay), retryDelay, 0)); } - + DataObject dataObject = null; - if (!(data is IComDataObject)) { + if (!(data is IComDataObject)) + { dataObject = new DataObject(data); } // Compute the format of the "data" passed in iff setText == true; - - if (dataObject != null) { + + if (dataObject != null) + { dataObject.RestrictedFormats = false; } int hr, retry = retryTimes; - - do { - if (data is IComDataObject) { + + do + { + if (data is IComDataObject) + { hr = UnsafeNativeMethods.OleSetClipboard((IComDataObject)data); } - else { + else + { hr = UnsafeNativeMethods.OleSetClipboard(dataObject); } - if (hr != 0) { - if (retry == 0) { + if (hr != 0) + { + if (retry == 0) + { ThrowIfFailed(hr); } retry--; @@ -144,12 +172,16 @@ public static void SetDataObject(object data, bool copy, int retryTimes, int ret } while (hr != 0); - if (copy) { + if (copy) + { retry = retryTimes; - do { + do + { hr = UnsafeNativeMethods.OleFlushClipboard(); - if (hr != 0) { - if (retry == 0) { + if (hr != 0) + { + if (retry == 0) + { ThrowIfFailed(hr); } retry--; @@ -164,8 +196,10 @@ public static void SetDataObject(object data, bool copy, int retryTimes, int ret /// Retrieves the data that is currently on the system /// . /// - public static IDataObject GetDataObject() { - if (Application.OleRequired() != System.Threading.ApartmentState.STA) { + public static IDataObject GetDataObject() + { + if (Application.OleRequired() != System.Threading.ApartmentState.STA) + { // only throw if a message loop was started. This makes the case of trying // to query the clipboard from your finalizer or non-ui MTA thread @@ -175,10 +209,12 @@ public static IDataObject GetDataObject() { // forget to set the STAThread attribute, we will correctly report // an error to aid in debugging. // - if (Application.MessageLoop) { + if (Application.MessageLoop) + { throw new System.Threading.ThreadStateException(SR.ThreadMustBeSTA); } - else { + else + { return null; } } @@ -191,10 +227,13 @@ private static IDataObject GetDataObject(int retryTimes, int retryDelay) { IComDataObject dataObject = null; int hr, retry = retryTimes; - do { + do + { hr = UnsafeNativeMethods.OleGetClipboard(ref dataObject); - if (hr != 0) { - if (retry == 0) { + if (hr != 0) + { + if (retry == 0) + { ThrowIfFailed(hr); } retry--; @@ -203,11 +242,14 @@ private static IDataObject GetDataObject(int retryTimes, int retryDelay) } while (hr != 0); - if (dataObject != null) { - if (dataObject is IDataObject && !Marshal.IsComObject(dataObject)) { + if (dataObject != null) + { + if (dataObject is IDataObject && !Marshal.IsComObject(dataObject)) + { return (IDataObject)dataObject; } - else { + else + { return new DataObject(dataObject); } } @@ -216,40 +258,49 @@ private static IDataObject GetDataObject(int retryTimes, int retryDelay) // <-- WHIDBEY ADDITIONS - public static void Clear() { + public static void Clear() + { Clipboard.SetDataObject(new DataObject()); } - public static bool ContainsAudio() { + public static bool ContainsAudio() + { IDataObject dataObject = Clipboard.GetDataObject(); - if (dataObject != null) { + if (dataObject != null) + { return dataObject.GetDataPresent(DataFormats.WaveAudio, false); } return false; } - public static bool ContainsData(string format) { + public static bool ContainsData(string format) + { IDataObject dataObject = Clipboard.GetDataObject(); - if (dataObject != null) { + if (dataObject != null) + { return dataObject.GetDataPresent(format, false); } return false; } - public static bool ContainsFileDropList() { + public static bool ContainsFileDropList() + { IDataObject dataObject = Clipboard.GetDataObject(); - if (dataObject != null) { + if (dataObject != null) + { return dataObject.GetDataPresent(DataFormats.FileDrop, true); } return false; } - public static bool ContainsImage() { + public static bool ContainsImage() + { IDataObject dataObject = Clipboard.GetDataObject(); - if (dataObject != null) { + if (dataObject != null) + { return dataObject.GetDataPresent(DataFormats.Bitmap, true); } @@ -258,45 +309,55 @@ public static bool ContainsImage() { public static bool ContainsText() => ContainsText(TextDataFormat.UnicodeText); - public static bool ContainsText(TextDataFormat format) { + public static bool ContainsText(TextDataFormat format) + { // valid values are 0x0-0x4 inclusive - if (!ClientUtils.IsEnumValid(format, (int)format, (int)TextDataFormat.Text, (int)TextDataFormat.CommaSeparatedValue)){ + if (!ClientUtils.IsEnumValid(format, (int)format, (int)TextDataFormat.Text, (int)TextDataFormat.CommaSeparatedValue)) + { throw new InvalidEnumArgumentException(nameof(format), (int)format, typeof(TextDataFormat)); } IDataObject dataObject = Clipboard.GetDataObject(); - if (dataObject != null) { + if (dataObject != null) + { return dataObject.GetDataPresent(ConvertToDataFormats(format), false); } return false; } - public static Stream GetAudioStream() { + public static Stream GetAudioStream() + { IDataObject dataObject = Clipboard.GetDataObject(); - if (dataObject != null) { + if (dataObject != null) + { return dataObject.GetData(DataFormats.WaveAudio, false) as Stream; } return null; } - public static object GetData(string format) { + public static object GetData(string format) + { IDataObject dataObject = Clipboard.GetDataObject(); - if (dataObject != null) { + if (dataObject != null) + { return dataObject.GetData(format); } return null; } - public static StringCollection GetFileDropList() { + public static StringCollection GetFileDropList() + { IDataObject dataObject = Clipboard.GetDataObject(); StringCollection retVal = new StringCollection(); - if (dataObject != null) { + if (dataObject != null) + { string[] strings = dataObject.GetData(DataFormats.FileDrop, true) as string[]; - if (strings != null) { + if (strings != null) + { retVal.AddRange(strings); } } @@ -304,9 +365,11 @@ public static StringCollection GetFileDropList() { return retVal; } - public static Image GetImage() { + public static Image GetImage() + { IDataObject dataObject = Clipboard.GetDataObject(); - if (dataObject != null) { + if (dataObject != null) + { return dataObject.GetData(DataFormats.Bitmap, true) as Image; } @@ -315,7 +378,8 @@ public static Image GetImage() { public static string GetText() => GetText(TextDataFormat.UnicodeText); - public static string GetText(TextDataFormat format) { + public static string GetText(TextDataFormat format) + { // valid values are 0x0 to 0x4 inclusive if (!ClientUtils.IsEnumValid(format, (int)format, (int)TextDataFormat.Text, (int)TextDataFormat.CommaSeparatedValue)) { @@ -323,9 +387,11 @@ public static string GetText(TextDataFormat format) { } IDataObject dataObject = Clipboard.GetDataObject(); - if (dataObject != null) { + if (dataObject != null) + { string text = dataObject.GetData(ConvertToDataFormats(format), false) as string; - if (text != null) { + if (text != null) + { return text; } } @@ -333,15 +399,19 @@ public static string GetText(TextDataFormat format) { return string.Empty; } - public static void SetAudio(byte[] audioBytes) { - if (audioBytes == null) { + public static void SetAudio(byte[] audioBytes) + { + if (audioBytes == null) + { throw new ArgumentNullException(nameof(audioBytes)); } SetAudio(new MemoryStream(audioBytes)); } - public static void SetAudio(Stream audioStream) { - if (audioStream == null) { + public static void SetAudio(Stream audioStream) + { + if (audioStream == null) + { throw new ArgumentNullException(nameof(audioStream)); } IDataObject dataObject = new DataObject(); @@ -349,15 +419,18 @@ public static void SetAudio(Stream audioStream) { Clipboard.SetDataObject(dataObject, true); } - public static void SetData(string format, object data) { + public static void SetData(string format, object data) + { //Note: We delegate argument checking to IDataObject.SetData, if it wants to do so. IDataObject dataObject = new DataObject(); dataObject.SetData(format, data); Clipboard.SetDataObject(dataObject, true); } - public static void SetFileDropList(StringCollection filePaths) { - if (filePaths == null) { + public static void SetFileDropList(StringCollection filePaths) + { + if (filePaths == null) + { throw new ArgumentNullException(nameof(filePaths)); } // throw Argument exception for zero-length filepath collection. @@ -367,12 +440,16 @@ public static void SetFileDropList(StringCollection filePaths) { } //Validate the paths to make sure they don't contain invalid characters - foreach (string path in filePaths) { - try { + foreach (string path in filePaths) + { + try + { string temp = Path.GetFullPath(path); } - catch (Exception e) { - if (ClientUtils.IsSecurityOrCriticalException(e)) { + catch (Exception e) + { + if (ClientUtils.IsSecurityOrCriticalException(e)) + { throw; } @@ -380,7 +457,8 @@ public static void SetFileDropList(StringCollection filePaths) { } } - if (filePaths.Count > 0) { + if (filePaths.Count > 0) + { IDataObject dataObject = new DataObject(); string[] strings = new string[filePaths.Count]; filePaths.CopyTo(strings, 0); @@ -389,8 +467,10 @@ public static void SetFileDropList(StringCollection filePaths) { } } - public static void SetImage(Image image) { - if (image == null) { + public static void SetImage(Image image) + { + if (image == null) + { throw new ArgumentNullException(nameof(image)); } IDataObject dataObject = new DataObject(); @@ -400,8 +480,10 @@ public static void SetImage(Image image) { public static void SetText(string text) => SetText(text, TextDataFormat.UnicodeText); - public static void SetText(string text, TextDataFormat format) { - if (string.IsNullOrEmpty(text)) { + public static void SetText(string text, TextDataFormat format) + { + if (string.IsNullOrEmpty(text)) + { throw new ArgumentNullException(nameof(text)); } @@ -416,22 +498,24 @@ public static void SetText(string text, TextDataFormat format) { Clipboard.SetDataObject(dataObject, true); } - private static string ConvertToDataFormats(TextDataFormat format) { - switch (format) { - case TextDataFormat.Text: - return DataFormats.Text; - - case TextDataFormat.UnicodeText: - return DataFormats.UnicodeText; - - case TextDataFormat.Rtf: - return DataFormats.Rtf; - - case TextDataFormat.Html: - return DataFormats.Html; - - case TextDataFormat.CommaSeparatedValue: - return DataFormats.CommaSeparatedValue; + private static string ConvertToDataFormats(TextDataFormat format) + { + switch (format) + { + case TextDataFormat.Text: + return DataFormats.Text; + + case TextDataFormat.UnicodeText: + return DataFormats.UnicodeText; + + case TextDataFormat.Rtf: + return DataFormats.Rtf; + + case TextDataFormat.Html: + return DataFormats.Html; + + case TextDataFormat.CommaSeparatedValue: + return DataFormats.CommaSeparatedValue; } return DataFormats.UnicodeText; @@ -439,9 +523,11 @@ private static string ConvertToDataFormats(TextDataFormat format) { // END - WHIDBEY ADDITIONS --> - private static void ThrowIfFailed(int hr) { + private static void ThrowIfFailed(int hr) + { // - if (hr != 0) { + if (hr != 0) + { ExternalException e = new ExternalException(SR.ClipboardOperationFailed, hr); throw e; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/CloseReason.cs b/src/System.Windows.Forms/src/System/Windows/Forms/CloseReason.cs index 23af95f1c4a..93e7285916f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/CloseReason.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/CloseReason.cs @@ -15,7 +15,7 @@ public enum CloseReason /// No reason for closure of the Form. /// None = 0, - + /// /// In the process of shutting down, Windows has closed the application. /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ColorDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ColorDialog.cs index 6903b9b478b..af56f0cb0c2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ColorDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ColorDialog.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics; @@ -26,7 +27,8 @@ namespace System.Windows.Forms { [DefaultProperty(nameof(Color))] [SRDescription(nameof(SR.DescriptionColorDialog))] // The only event this dialog has is HelpRequest, which isn't very useful - public class ColorDialog : CommonDialog { + public class ColorDialog : CommonDialog + { private int options; private int[] customColors; @@ -45,7 +47,8 @@ public class ColorDialog : CommonDialog { SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // If the constructor does not call Reset // it would be a breaking change. ] - public ColorDialog() { + public ColorDialog() + { customColors = new int[16]; Reset(); } @@ -57,16 +60,19 @@ public ColorDialog() { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(true), SRDescription(nameof(SR.CDallowFullOpenDescr)) ] - public virtual bool AllowFullOpen { - get { + public virtual bool AllowFullOpen + { + get + { return !GetOption(NativeMethods.CC_PREVENTFULLOPEN); } - set { + set + { SetOption(NativeMethods.CC_PREVENTFULLOPEN, !value); } } @@ -78,16 +84,19 @@ public virtual bool AllowFullOpen { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(false), SRDescription(nameof(SR.CDanyColorDescr)) ] - public virtual bool AnyColor { - get { + public virtual bool AnyColor + { + get + { return GetOption(NativeMethods.CC_ANYCOLOR); } - set { + set + { SetOption(NativeMethods.CC_ANYCOLOR, value); } } @@ -98,18 +107,23 @@ public virtual bool AnyColor { /// /// [ - SRCategory(nameof(SR.CatData)), + SRCategory(nameof(SR.CatData)), SRDescription(nameof(SR.CDcolorDescr)) ] - public Color Color { - get { + public Color Color + { + get + { return color; } - set { - if (!value.IsEmpty) { + set + { + if (!value.IsEmpty) + { color = value; } - else { + else + { color = Color.Black; } } @@ -126,12 +140,16 @@ public Color Color { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.CDcustomColorsDescr)) ] - public int[] CustomColors { - get { return(int[]) customColors.Clone();} - set { - int length = value == null? 0: Math.Min(value.Length, 16); - if (length > 0) Array.Copy(value, 0, customColors, 0, length); - for (int i = length; i < 16; i++) customColors[i] = 0x00FFFFFF; + public int[] CustomColors + { + get { return (int[])customColors.Clone(); } + set + { + int length = value == null ? 0 : Math.Min(value.Length, 16); + if (length > 0) + Array.Copy(value, 0, customColors, 0, length); + for (int i = length; i < 16; i++) + customColors[i] = 0x00FFFFFF; } } @@ -142,16 +160,19 @@ public int[] CustomColors { /// /// [ - SRCategory(nameof(SR.CatAppearance)), + SRCategory(nameof(SR.CatAppearance)), DefaultValue(false), SRDescription(nameof(SR.CDfullOpenDescr)) ] - public virtual bool FullOpen { - get { + public virtual bool FullOpen + { + get + { return GetOption(NativeMethods.CC_FULLOPEN); } - set { + set + { SetOption(NativeMethods.CC_FULLOPEN, value); } } @@ -161,15 +182,18 @@ public virtual bool FullOpen { /// Our HINSTANCE from Windows. /// /// - protected virtual IntPtr Instance { - get { return UnsafeNativeMethods.GetModuleHandle(null);} + protected virtual IntPtr Instance + { + get { return UnsafeNativeMethods.GetModuleHandle(null); } } /// /// Returns our CHOOSECOLOR options. /// - protected virtual int Options { - get { + protected virtual int Options + { + get + { return options; } } @@ -181,15 +205,18 @@ protected virtual int Options { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(false), SRDescription(nameof(SR.CDshowHelpDescr)) ] - public virtual bool ShowHelp { - get { + public virtual bool ShowHelp + { + get + { return GetOption(NativeMethods.CC_SHOWHELP); } - set { + set + { SetOption(NativeMethods.CC_SHOWHELP, value); } } @@ -203,15 +230,18 @@ public virtual bool ShowHelp { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(false), SRDescription(nameof(SR.CDsolidColorOnlyDescr)) ] - public virtual bool SolidColorOnly { - get { + public virtual bool SolidColorOnly + { + get + { return GetOption(NativeMethods.CC_SOLIDCOLOR); } - set { + set + { SetOption(NativeMethods.CC_SOLIDCOLOR, value); } } @@ -219,8 +249,9 @@ public virtual bool SolidColorOnly { /// /// Lets us control the CHOOSECOLOR options. /// - private bool GetOption(int option) { - return(options & option) != 0; + private bool GetOption(int option) + { + return (options & option) != 0; } /// @@ -231,24 +262,28 @@ private bool GetOption(int option) { /// colors to their default values. /// /// - public override void Reset() { + public override void Reset() + { options = 0; color = Color.Black; CustomColors = null; } - private void ResetColor() { - Color = Color.Black; - } + private void ResetColor() + { + Color = Color.Black; + } /// /// - protected override bool RunDialog(IntPtr hwndOwner) { + protected override bool RunDialog(IntPtr hwndOwner) + { NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(this.HookProc); NativeMethods.CHOOSECOLOR cc = new NativeMethods.CHOOSECOLOR(); IntPtr custColorPtr = Marshal.AllocCoTaskMem(64); - try { + try + { Marshal.Copy(customColors, 0, custColorPtr, 16); cc.hwndOwner = hwndOwner; cc.hInstance = Instance; @@ -262,12 +297,15 @@ protected override bool RunDialog(IntPtr hwndOwner) { cc.Flags = flags; cc.lpfnHook = hookProcPtr; - if (!SafeNativeMethods.ChooseColor(cc)) return false; - if (cc.rgbResult != ColorTranslator.ToWin32(color)) color = ColorTranslator.FromOle(cc.rgbResult); + if (!SafeNativeMethods.ChooseColor(cc)) + return false; + if (cc.rgbResult != ColorTranslator.ToWin32(color)) + color = ColorTranslator.FromOle(cc.rgbResult); Marshal.Copy(custColorPtr, customColors, 0, 16); return true; } - finally { + finally + { Marshal.FreeCoTaskMem(custColorPtr); } } @@ -275,11 +313,14 @@ protected override bool RunDialog(IntPtr hwndOwner) { /// /// Allows us to manipulate the CHOOSECOLOR options /// - private void SetOption(int option, bool value) { - if (value) { + private void SetOption(int option, bool value) + { + if (value) + { options |= option; } - else { + else + { options &= ~option; } } @@ -290,7 +331,8 @@ private void SetOption(int option, bool value) { /// persisted. /// /// - private bool ShouldSerializeColor() { + private bool ShouldSerializeColor() + { return !Color.Equals(Color.Black); } @@ -299,7 +341,8 @@ private bool ShouldSerializeColor() { /// Provides a string version of this object. /// /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); return s + ", Color: " + Color.ToString(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ColumnClickEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ColumnClickEventArgs.cs index 0ac5c68258c..37235104739 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ColumnClickEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ColumnClickEventArgs.cs @@ -13,7 +13,7 @@ public ColumnClickEventArgs(int column) { Column = column; } - + public int Column { get; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeader.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeader.cs index 569a7d13bb4..785e125125a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeader.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeader.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System; @@ -13,9 +14,9 @@ namespace System.Windows.Forms { using System.Drawing; using System.IO; using System.Runtime.InteropServices; - using System.Windows.Forms; + using System.Windows.Forms; using System.Globalization; - + /// /// /// Displays a single column header in a @@ -29,9 +30,10 @@ namespace System.Windows.Forms { DefaultProperty(nameof(Text)), TypeConverterAttribute(typeof(ColumnHeaderConverter)) ] - public class ColumnHeader : Component, ICloneable { + public class ColumnHeader : Component, ICloneable + { -// disable csharp compiler warning #0414: field assigned unused value + // disable csharp compiler warning #0414: field assigned unused value #pragma warning disable 0414 internal int index = -1; #pragma warning restore 0414 @@ -59,7 +61,7 @@ internal ListView OwnerListview int width = this.Width; listview = value; - + // The below properties are set into the listview. this.Width = width; } @@ -68,61 +70,74 @@ internal ListView OwnerListview /// /// Creates a new ColumnHeader object /// - public ColumnHeader() { + public ColumnHeader() + { imageIndexer = new ColumnHeaderImageListIndexer(this); } /// /// Creates a new ColumnHeader object /// - public ColumnHeader(int imageIndex) : this () { + public ColumnHeader(int imageIndex) : this() + { this.ImageIndex = imageIndex; } /// /// Creates a new ColumnHeader object /// - public ColumnHeader(string imageKey) : this () { + public ColumnHeader(string imageKey) : this() + { this.ImageKey = imageKey; } - internal int ActualImageIndex_Internal { - get { + internal int ActualImageIndex_Internal + { + get + { int imgIndex = this.imageIndexer.ActualIndex; - if (this.ImageList == null || this.ImageList.Images == null || imgIndex >= this.ImageList.Images.Count) { + if (this.ImageList == null || this.ImageList.Images == null || imgIndex >= this.ImageList.Images.Count) + { // the ImageIndex equivalent of a ImageKey that does not exist in the ImageList return -1; - } else { + } + else + { return imgIndex; } } } - [ - Localizable(true), - RefreshProperties(RefreshProperties.Repaint), - SRCategory(nameof(SR.CatBehavior)), - SRDescription(nameof(SR.ColumnHeaderDisplayIndexDescr)) - ] - public int DisplayIndex { - get { + [ + Localizable(true), + RefreshProperties(RefreshProperties.Repaint), + SRCategory(nameof(SR.CatBehavior)), + SRDescription(nameof(SR.ColumnHeaderDisplayIndexDescr)) + ] + public int DisplayIndex + { + get + { return this.DisplayIndexInternal; } - - set { + + set + { // When the list is being deserialized we need // to take the display index as is. ListView // does correctly synchronize the indices. - if (this.listview == null) { - this.DisplayIndexInternal = value; - return; + if (this.listview == null) + { + this.DisplayIndexInternal = value; + return; } - if (value < 0 || value> (this.listview.Columns.Count - 1)) { + if (value < 0 || value > (this.listview.Columns.Count - 1)) + { throw new ArgumentOutOfRangeException(nameof(DisplayIndex), SR.ColumnHeaderBadDisplayIndex); - } + } int lowDI = Math.Min(this.DisplayIndexInternal, value); int hiDI = Math.Max(this.DisplayIndexInternal, value); @@ -132,30 +147,38 @@ public int DisplayIndex { // we only set an integer in the column header class bool hdrMovedForward = value > this.DisplayIndexInternal; ColumnHeader movedHdr = null; - for (int i = 0; i < this.listview.Columns.Count; i ++) { + for (int i = 0; i < this.listview.Columns.Count; i++) + { ColumnHeader hdr = this.listview.Columns[i]; - if (hdr.DisplayIndex == this.DisplayIndexInternal) { + if (hdr.DisplayIndex == this.DisplayIndexInternal) + { movedHdr = hdr; - } else if (hdr.DisplayIndex >= lowDI && hdr.DisplayIndex <= hiDI) { + } + else if (hdr.DisplayIndex >= lowDI && hdr.DisplayIndex <= hiDI) + { hdr.DisplayIndexInternal -= hdrMovedForward ? 1 : -1; } - if (i != this.Index) { - colsOrder[ hdr.DisplayIndexInternal ] = i; + if (i != this.Index) + { + colsOrder[hdr.DisplayIndexInternal] = i; } } movedHdr.DisplayIndexInternal = value; - colsOrder[ movedHdr.DisplayIndexInternal ] = movedHdr.Index; - SetDisplayIndices( colsOrder ); - } - } + colsOrder[movedHdr.DisplayIndexInternal] = movedHdr.Index; + SetDisplayIndices(colsOrder); + } + } - internal int DisplayIndexInternal { - get { + internal int DisplayIndexInternal + { + get + { return this.displayIndexInternal; } - set { + set + { this.displayIndexInternal = value; } } @@ -165,12 +188,14 @@ internal int DisplayIndexInternal { /// to the current visual position of the column in the ListView, because the /// user may orerder columns if the allowColumnReorder property is true. /// - [ Browsable(false)] - public int Index { - get { + [Browsable(false)] + public int Index + { + get + { if (listview != null) return listview.GetColumnIndex(this); - return -1; + return -1; } } @@ -181,22 +206,29 @@ public int Index { RefreshProperties(RefreshProperties.Repaint), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public int ImageIndex { - get { - if (imageIndexer.Index != -1 && ImageList != null && imageIndexer.Index >= ImageList.Images.Count) { + public int ImageIndex + { + get + { + if (imageIndexer.Index != -1 && ImageList != null && imageIndexer.Index >= ImageList.Images.Count) + { return ImageList.Images.Count - 1; - } + } return imageIndexer.Index; } - set { - if (value < -1) { + set + { + if (value < -1) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(ImageIndex), value, -1)); } - if (imageIndexer.Index != value) { + if (imageIndexer.Index != value) + { imageIndexer.Index = value; - if (ListView != null && ListView.IsHandleCreated) { + if (ListView != null && ListView.IsHandleCreated) + { ListView.SetColumnInfo(NativeMethods.LVCF_IMAGE, this); } } @@ -204,9 +236,11 @@ public int ImageIndex { } [Browsable(false)] - public ImageList ImageList { + public ImageList ImageList + { // we added the ImageList property so that the ImageIndexConverter can find our image list - get { + get + { return this.imageIndexer.ImageList; } } @@ -218,15 +252,20 @@ public ImageList ImageList { RefreshProperties(RefreshProperties.Repaint), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public string ImageKey { - get { + public string ImageKey + { + get + { return imageIndexer.Key; } - set { - if (value != imageIndexer.Key) { + set + { + if (value != imageIndexer.Key) + { imageIndexer.Key = value; - if (ListView != null && ListView.IsHandleCreated) { + if (ListView != null && ListView.IsHandleCreated) + { ListView.SetColumnInfo(NativeMethods.LVCF_IMAGE, this); } } @@ -236,9 +275,11 @@ public string ImageKey { /// /// Returns the ListView control that this column is displayed in. May be null /// - [ Browsable(false) ] - public ListView ListView { - get { + [Browsable(false)] + public ListView ListView + { + get + { return this.listview; } } @@ -250,18 +291,24 @@ public ListView ListView { Browsable(false), SRDescription(nameof(SR.ColumnHeaderNameDescr)) ] - public string Name { - get { - return WindowsFormsUtils.GetComponentName(this,name); + public string Name + { + get + { + return WindowsFormsUtils.GetComponentName(this, name); } - set { - if (value == null) { + set + { + if (value == null) + { this.name = string.Empty; } - else { + else + { this.name = value; } - if(Site != null) { + if (Site != null) + { Site.Name = value; } } @@ -275,18 +322,24 @@ public string Name { Localizable(true), SRDescription(nameof(SR.ColumnCaption)) ] - public string Text { - get { - return(text != null ? text : "ColumnHeader"); + public string Text + { + get + { + return (text != null ? text : "ColumnHeader"); } - set { - if (value == null) { + set + { + if (value == null) + { this.text = string.Empty; } - else { + else + { this.text = value; } - if (listview != null) { + if (listview != null) + { listview.SetColumnInfo(NativeMethods.LVCF_TEXT, this); } } @@ -301,34 +354,40 @@ public string Text { Localizable(true), DefaultValue(HorizontalAlignment.Left) ] - public HorizontalAlignment TextAlign { - get { + public HorizontalAlignment TextAlign + { + get + { if (!textAlignInitialized && (listview != null)) { - textAlignInitialized = true; - // See below for an explanation of (Index != 0) - //Added !IsMirrored - if ((Index != 0) && (listview.RightToLeft == RightToLeft.Yes) && !listview.IsMirrored) - { - this.textAlign = HorizontalAlignment.Right; - } + textAlignInitialized = true; + // See below for an explanation of (Index != 0) + //Added !IsMirrored + if ((Index != 0) && (listview.RightToLeft == RightToLeft.Yes) && !listview.IsMirrored) + { + this.textAlign = HorizontalAlignment.Right; + } } return this.textAlign; } - set { + set + { //valid values are 0x0 to 0x2. - if (!ClientUtils.IsEnumValid(value, (int)value, (int)HorizontalAlignment.Left, (int)HorizontalAlignment.Center)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)HorizontalAlignment.Left, (int)HorizontalAlignment.Center)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(HorizontalAlignment)); } this.textAlign = value; - + // The first column must be left-aligned - if (Index == 0 && this.textAlign != HorizontalAlignment.Left) { + if (Index == 0 && this.textAlign != HorizontalAlignment.Left) + { this.textAlign = HorizontalAlignment.Left; } - if (listview != null) { + if (listview != null) + { listview.SetColumnInfo(NativeMethods.LVCF_FMT, this); listview.Invalidate(); } @@ -343,17 +402,22 @@ public HorizontalAlignment TextAlign { DefaultValue(null), TypeConverter(typeof(StringConverter)), ] - public object Tag { - get { + public object Tag + { + get + { return userData; } - set { + set + { userData = value; } } - internal int WidthInternal { - get { + internal int WidthInternal + { + get + { return width; } } @@ -365,20 +429,25 @@ internal int WidthInternal { Localizable(true), DefaultValue(60) ] - public int Width { - get { + public int Width + { + get + { // Since we can't keep our private width in sync with the real width because // we don't get notified when the user changes it, we need to get this info // from the underlying control every time we're asked. // The underlying control will only report the correct width if it's in Report view - if (listview != null && listview.IsHandleCreated && !listview.Disposing && listview.View == View.Details) { - + if (listview != null && listview.IsHandleCreated && !listview.Disposing && listview.View == View.Details) + { + // Make sure this column has already been added to the ListView, else just return width // IntPtr hwndHdr = UnsafeNativeMethods.SendMessage(new HandleRef(listview, listview.Handle), NativeMethods.LVM_GETHEADER, 0, 0); - if (hwndHdr != IntPtr.Zero) { + if (hwndHdr != IntPtr.Zero) + { int nativeColumnCount = (int)UnsafeNativeMethods.SendMessage(new HandleRef(listview, hwndHdr), NativeMethods.HDM_GETITEMCOUNT, 0, 0); - if (Index < nativeColumnCount) { + if (Index < nativeColumnCount) + { width = (int)UnsafeNativeMethods.SendMessage(new HandleRef(listview, listview.Handle), NativeMethods.LVM_GETCOLUMNWIDTH, Index, 0); } } @@ -386,36 +455,43 @@ public int Width { return width; } - set { + set + { this.width = value; if (listview != null) listview.SetColumnWidth(Index, ColumnHeaderAutoResizeStyle.None); - } + } } - public void AutoResize(ColumnHeaderAutoResizeStyle headerAutoResize) { + public void AutoResize(ColumnHeaderAutoResizeStyle headerAutoResize) + { - if (headerAutoResize < ColumnHeaderAutoResizeStyle.None || headerAutoResize > ColumnHeaderAutoResizeStyle.ColumnContent) { + if (headerAutoResize < ColumnHeaderAutoResizeStyle.None || headerAutoResize > ColumnHeaderAutoResizeStyle.ColumnContent) + { throw new InvalidEnumArgumentException(nameof(headerAutoResize), (int)headerAutoResize, typeof(ColumnHeaderAutoResizeStyle)); } - if (this.listview != null) { + if (this.listview != null) + { this.listview.AutoResizeColumn(this.Index, headerAutoResize); } } - + /// /// Creates an identical ColumnHeader, unattached to any ListView /// - public object Clone() { + public object Clone() + { Type clonedType = this.GetType(); ColumnHeader columnHeader = null; - if (clonedType == typeof(ColumnHeader)) { + if (clonedType == typeof(ColumnHeader)) + { columnHeader = new ColumnHeader(); } - else { + else + { columnHeader = (ColumnHeader)Activator.CreateInstance(clonedType); } @@ -425,11 +501,15 @@ public object Clone() { return columnHeader; } - protected override void Dispose(bool disposing) { - if (disposing) { - if (listview != null) { + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (listview != null) + { int index = Index; - if (index != -1) { + if (index != -1) + { listview.Columns.RemoveAt(index); } } @@ -437,48 +517,60 @@ protected override void Dispose(bool disposing) { base.Dispose(disposing); } - private void ResetText() { - Text = null; - } + private void ResetText() + { + Text = null; + } // Set the display indices of the listview columns - private void SetDisplayIndices(int[] cols) { + private void SetDisplayIndices(int[] cols) + { - if (this.listview.IsHandleCreated && !this.listview.Disposing) { - UnsafeNativeMethods.SendMessage(new HandleRef(this.listview, this.listview.Handle), NativeMethods.LVM_SETCOLUMNORDERARRAY, cols.Length, cols); - } + if (this.listview.IsHandleCreated && !this.listview.Disposing) + { + UnsafeNativeMethods.SendMessage(new HandleRef(this.listview, this.listview.Handle), NativeMethods.LVM_SETCOLUMNORDERARRAY, cols.Length, cols); + } } - private bool ShouldSerializeName() { + private bool ShouldSerializeName() + { return !string.IsNullOrEmpty(this.name); } - private bool ShouldSerializeDisplayIndex() { + private bool ShouldSerializeDisplayIndex() + { return this.DisplayIndex != this.Index; } - internal bool ShouldSerializeText() { - return(text != null); + internal bool ShouldSerializeText() + { + return (text != null); } - + /// /// Returns a string representation of this column header /// - public override string ToString() { + public override string ToString() + { return "ColumnHeader: Text: " + Text; } - internal class ColumnHeaderImageListIndexer : ImageList.Indexer { + internal class ColumnHeaderImageListIndexer : ImageList.Indexer + { private ColumnHeader owner = null; - public ColumnHeaderImageListIndexer(ColumnHeader ch) { + public ColumnHeaderImageListIndexer(ColumnHeader ch) + { owner = ch; } - public override ImageList ImageList { - get { + public override ImageList ImageList + { + get + { return owner.ListView?.SmallImageList; } - set { + set + { Debug.Assert(false, "We should never set the image list"); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeaderConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeaderConverter.cs index bd9eb9dfa4f..537d573279b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeaderConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeaderConverter.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; @@ -18,19 +19,22 @@ namespace System.Windows.Forms { /// /// - public class ColumnHeaderConverter : ExpandableObjectConverter { - + public class ColumnHeaderConverter : ExpandableObjectConverter + { + /// /// Gets a value indicating whether this converter can /// convert an object to the given destination type using the context. /// - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { - if (destinationType == typeof(InstanceDescriptor)) { + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) + { + if (destinationType == typeof(InstanceDescriptor)) + { return true; } return base.CanConvertTo(context, destinationType); } - + /// /// Converts the given object to another type. The most common types to convert /// are to and from a string object. The default implementation will make a call @@ -38,47 +42,57 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) { + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == null) + { throw new ArgumentNullException(nameof(destinationType)); } - if (destinationType == typeof(InstanceDescriptor) && value is ColumnHeader) { - ColumnHeader col = (ColumnHeader) value; + if (destinationType == typeof(InstanceDescriptor) && value is ColumnHeader) + { + ColumnHeader col = (ColumnHeader)value; ConstructorInfo ctor; Type t = TypeDescriptor.GetReflectionType(value); InstanceDescriptor id = null; - - if (col.ImageIndex != -1) { - ctor = t.GetConstructor(new Type[]{typeof(int)}); - if (ctor != null) { - id = new InstanceDescriptor(ctor, new object[]{col.ImageIndex}, false); + + if (col.ImageIndex != -1) + { + ctor = t.GetConstructor(new Type[] { typeof(int) }); + if (ctor != null) + { + id = new InstanceDescriptor(ctor, new object[] { col.ImageIndex }, false); } - - } - if (id == null && !string.IsNullOrEmpty(col.ImageKey)) { - ctor = t.GetConstructor(new Type[]{typeof(string)}); - if (ctor != null) { - id = new InstanceDescriptor(ctor, new object[]{col.ImageKey}, false); + } + + if (id == null && !string.IsNullOrEmpty(col.ImageKey)) + { + ctor = t.GetConstructor(new Type[] { typeof(string) }); + if (ctor != null) + { + id = new InstanceDescriptor(ctor, new object[] { col.ImageKey }, false); } - } + } - if (id == null) { + if (id == null) + { ctor = t.GetConstructor(new Type[0]); - if (ctor != null) { + if (ctor != null) + { return new InstanceDescriptor(ctor, new object[0], false); } - else { + else + { throw new ArgumentException(string.Format(SR.NoDefaultConstructor, t.FullName)); } } - return id; + return id; } - + return base.ConvertTo(context, culture, value, destinationType); } - } + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs index 33401cdd84d..006336fe149 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Accessibility; using System.Runtime.Serialization.Formatters; using System.Threading; @@ -44,7 +45,8 @@ namespace System.Windows.Forms { Designer("System.Windows.Forms.Design.ComboBoxDesigner, " + AssemblyRef.SystemDesign), SRDescription(nameof(SR.DescriptionComboBox)) ] - public class ComboBox : ListControl { + public class ComboBox : ListControl + { private static readonly object EVENT_DROPDOWN = new object(); private static readonly object EVENT_DRAWITEM = new object(); @@ -151,15 +153,16 @@ public class ComboBox : ListControl { /// Creates a new ComboBox control. The default style for the combo is /// a regular DropDown Combo. /// - public ComboBox() { + public ComboBox() + { SetStyle(ControlStyles.UserPaint | ControlStyles.UseTextForAccessibility | ControlStyles.StandardClick, false); requestedHeight = DefaultSimpleStyleHeight; - + // this class overrides GetPreferredSizeCore, let Control automatically cache the result - SetState2(STATE2_USEPREFERREDSIZECACHE, true); + SetState2(STATE2_USEPREFERREDSIZECACHE, true); } /// @@ -172,25 +175,32 @@ public ComboBox() { SRDescription(nameof(SR.ComboBoxAutoCompleteModeDescr)), Browsable(true), EditorBrowsable(EditorBrowsableState.Always) ] - public AutoCompleteMode AutoCompleteMode { - get { + public AutoCompleteMode AutoCompleteMode + { + get + { return autoCompleteMode; } - set { + set + { //valid values are 0x0 to 0x3 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)AutoCompleteMode.None, (int)AutoCompleteMode.SuggestAppend)) { + if (!ClientUtils.IsEnumValid(value, (int)value, (int)AutoCompleteMode.None, (int)AutoCompleteMode.SuggestAppend)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AutoCompleteMode)); } if (this.DropDownStyle == ComboBoxStyle.DropDownList && this.AutoCompleteSource != AutoCompleteSource.ListItems && - value != AutoCompleteMode.None) { + value != AutoCompleteMode.None) + { throw new NotSupportedException(SR.ComboBoxAutoCompleteModeOnlyNoneAllowed); } - if (Application.OleRequired() != System.Threading.ApartmentState.STA) { + if (Application.OleRequired() != System.Threading.ApartmentState.STA) + { throw new ThreadStateException(SR.ThreadMustBeSTA); } bool resetAutoComplete = false; - if (autoCompleteMode != AutoCompleteMode.None && value == AutoCompleteMode.None) { + if (autoCompleteMode != AutoCompleteMode.None && value == AutoCompleteMode.None) + { resetAutoComplete = true; } autoCompleteMode = value; @@ -208,11 +218,14 @@ public AutoCompleteMode AutoCompleteMode { SRDescription(nameof(SR.ComboBoxAutoCompleteSourceDescr)), Browsable(true), EditorBrowsable(EditorBrowsableState.Always) ] - public AutoCompleteSource AutoCompleteSource { - get { + public AutoCompleteSource AutoCompleteSource + { + get + { return autoCompleteSource; } - set { + set + { // FxCop: Avoid usage of Enum.IsDefined - this looks like an enum that could grow if (!ClientUtils.IsEnumValid_NotSequential(value, (int)value, (int)AutoCompleteSource.None, @@ -230,10 +243,12 @@ public AutoCompleteSource AutoCompleteSource { if (this.DropDownStyle == ComboBoxStyle.DropDownList && this.AutoCompleteMode != AutoCompleteMode.None && - value != AutoCompleteSource.ListItems) { + value != AutoCompleteSource.ListItems) + { throw new NotSupportedException(SR.ComboBoxAutoCompleteSourceOnlyListItemsAllowed); } - if (Application.OleRequired() != System.Threading.ApartmentState.STA) { + if (Application.OleRequired() != System.Threading.ApartmentState.STA) + { throw new ThreadStateException(SR.ThreadMustBeSTA); } @@ -253,24 +268,31 @@ public AutoCompleteSource AutoCompleteSource { Editor("System.Windows.Forms.Design.ListControlStringCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), Browsable(true), EditorBrowsable(EditorBrowsableState.Always) ] - public AutoCompleteStringCollection AutoCompleteCustomSource { - get { - if (autoCompleteCustomSource == null) { + public AutoCompleteStringCollection AutoCompleteCustomSource + { + get + { + if (autoCompleteCustomSource == null) + { autoCompleteCustomSource = new AutoCompleteStringCollection(); autoCompleteCustomSource.CollectionChanged += new CollectionChangeEventHandler(this.OnAutoCompleteCustomSourceChanged); } return autoCompleteCustomSource; } - set { - if (autoCompleteCustomSource != value) { + set + { + if (autoCompleteCustomSource != value) + { - if (autoCompleteCustomSource != null) { + if (autoCompleteCustomSource != null) + { autoCompleteCustomSource.CollectionChanged -= new CollectionChangeEventHandler(this.OnAutoCompleteCustomSourceChanged); } autoCompleteCustomSource = value; - if (autoCompleteCustomSource != null) { + if (autoCompleteCustomSource != null) + { autoCompleteCustomSource.CollectionChanged += new CollectionChangeEventHandler(this.OnAutoCompleteCustomSourceChanged); } SetAutoComplete(false, true); @@ -282,55 +304,71 @@ public AutoCompleteStringCollection AutoCompleteCustomSource { /// The background color of this control. This is an ambient property and /// will always return a non-null value. /// - public override Color BackColor { - get { - if (ShouldSerializeBackColor()) { + public override Color BackColor + { + get + { + if (ShouldSerializeBackColor()) + { return base.BackColor; } - else { + else + { return SystemColors.Window; } } - set { + set + { base.BackColor = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged { + new public event EventHandler BackgroundImageChanged + { add => base.BackgroundImageChanged += value; remove => base.BackgroundImageChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { + new public event EventHandler BackgroundImageLayoutChanged + { add => base.BackgroundImageLayoutChanged += value; remove => base.BackgroundImageLayoutChanged -= value; } - internal ChildAccessibleObject ChildEditAccessibleObject { - get { - if (childEditAccessibleObject == null) { + internal ChildAccessibleObject ChildEditAccessibleObject + { + get + { + if (childEditAccessibleObject == null) + { childEditAccessibleObject = new ComboBoxChildEditUiaProvider(this, childEdit.Handle); } @@ -338,9 +376,12 @@ internal ChildAccessibleObject ChildEditAccessibleObject { } } - internal ChildAccessibleObject ChildListAccessibleObject { - get { - if (childListAccessibleObject == null) { + internal ChildAccessibleObject ChildListAccessibleObject + { + get + { + if (childListAccessibleObject == null) + { childListAccessibleObject = new ComboBoxChildListUiaProvider(this, DropDownStyle == ComboBoxStyle.Simple ? childListBox.Handle : dropDownHandle); } @@ -349,9 +390,12 @@ internal ChildAccessibleObject ChildListAccessibleObject { } } - internal AccessibleObject ChildTextAccessibleObject { - get { - if (childTextAccessibleObject == null) { + internal AccessibleObject ChildTextAccessibleObject + { + get + { + if (childTextAccessibleObject == null) + { childTextAccessibleObject = new ComboBoxChildTextUiaProvider(this); } @@ -365,15 +409,19 @@ internal AccessibleObject ChildTextAccessibleObject { /// however, forget to call base.CreateParams() first to get the struct /// filled up with the basic info. /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ClassName = "COMBOBOX"; cp.Style |= NativeMethods.WS_VSCROLL | NativeMethods.CBS_HASSTRINGS | NativeMethods.CBS_AUTOHSCROLL; cp.ExStyle |= NativeMethods.WS_EX_CLIENTEDGE; - if (!integralHeight) cp.Style |= NativeMethods.CBS_NOINTEGRALHEIGHT; + if (!integralHeight) + cp.Style |= NativeMethods.CBS_NOINTEGRALHEIGHT; - switch (DropDownStyle) { + switch (DropDownStyle) + { case ComboBoxStyle.Simple: cp.Style |= NativeMethods.CBS_SIMPLE; break; @@ -388,7 +436,8 @@ protected override CreateParams CreateParams { cp.Height = PreferredHeight; break; } - switch (DrawMode) { + switch (DrawMode) + { case DrawMode.OwnerDrawFixed: cp.Style |= NativeMethods.CBS_OWNERDRAWFIXED; @@ -406,8 +455,10 @@ protected override CreateParams CreateParams { /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(121, PreferredHeight); } } @@ -423,11 +474,14 @@ protected override Size DefaultSize { AttributeProvider(typeof(IListSource)), SRDescription(nameof(SR.ListControlDataSourceDescr)) ] - public new object DataSource { - get { + public new object DataSource + { + get + { return base.DataSource; } - set { + set + { base.DataSource = value; } } @@ -443,20 +497,26 @@ protected override Size DefaultSize { SRDescription(nameof(SR.ComboBoxDrawModeDescr)), RefreshProperties(RefreshProperties.Repaint) ] - public DrawMode DrawMode { - get { + public DrawMode DrawMode + { + get + { bool found; int drawMode = Properties.GetInteger(PropDrawMode, out found); - if (found) { + if (found) + { return (DrawMode)drawMode; } return DrawMode.Normal; } - set { - if (DrawMode != value) { + set + { + if (DrawMode != value) + { //valid values are 0x0 to 0x2. - if (!ClientUtils.IsEnumValid(value, (int)value, (int)DrawMode.Normal, (int)DrawMode.OwnerDrawVariable)) { + if (!ClientUtils.IsEnumValid(value, (int)value, (int)DrawMode.Normal, (int)DrawMode.OwnerDrawVariable)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DrawMode)); } ResetHeightCache(); @@ -473,26 +533,34 @@ public DrawMode DrawMode { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ComboBoxDropDownWidthDescr)) ] - public int DropDownWidth { - get { + public int DropDownWidth + { + get + { bool found; int dropDownWidth = Properties.GetInteger(PropDropDownWidth, out found); - if (found) { + if (found) + { return dropDownWidth; } - else { + else + { return Width; } } - set { - if (value < 1) { + set + { + if (value < 1) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(DropDownWidth), value)); } - if (Properties.GetInteger(PropDropDownWidth) != value) { + if (Properties.GetInteger(PropDropDownWidth) != value) + { Properties.SetInteger(PropDropDownWidth, value); - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(NativeMethods.CB_SETDROPPEDWIDTH, value, 0); } @@ -509,22 +577,29 @@ public int DropDownWidth { Browsable(true), EditorBrowsable(EditorBrowsableState.Always), DefaultValue(106) ] - public int DropDownHeight { - get { + public int DropDownHeight + { + get + { bool found; int dropDownHeight = Properties.GetInteger(PropDropDownHeight, out found); - if (found) { + if (found) + { return dropDownHeight; } - else { + else + { return DefaultDropDownHeight; } } - set { - if (value < 1) { + set + { + if (value < 1) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(DropDownHeight), value)); } - if (Properties.GetInteger(PropDropDownHeight) != value) { + if (Properties.GetInteger(PropDropDownHeight) != value) + { Properties.SetInteger(PropDropDownHeight, value); // The dropDownHeight is not reflected unless the @@ -542,19 +617,25 @@ public int DropDownHeight { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ComboBoxDroppedDownDescr)) ] - public bool DroppedDown { - get { - if (IsHandleCreated) { - return unchecked( (int) (long)SendMessage(NativeMethods.CB_GETDROPPEDSTATE, 0, 0) ) != 0; + public bool DroppedDown + { + get + { + if (IsHandleCreated) + { + return unchecked((int)(long)SendMessage(NativeMethods.CB_GETDROPPEDSTATE, 0, 0)) != 0; } - else { + else + { return false; } } - set { + set + { - if (!IsHandleCreated) { + if (!IsHandleCreated) + { CreateHandle(); } @@ -575,13 +656,17 @@ public bool DroppedDown { Localizable(true), SRDescription(nameof(SR.ComboBoxFlatStyleDescr)) ] - public FlatStyle FlatStyle { - get { + public FlatStyle FlatStyle + { + get + { return flatStyle; } - set { + set + { //valid values are 0x0 to 0x3 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)FlatStyle.Flat, (int)FlatStyle.System)) { + if (!ClientUtils.IsEnumValid(value, (int)value, (int)FlatStyle.Flat, (int)FlatStyle.System)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(FlatStyle)); } flatStyle = value; @@ -592,9 +677,12 @@ public FlatStyle FlatStyle { /// /// Returns true if this control has focus. /// - public override bool Focused { - get { - if (base.Focused) return true; + public override bool Focused + { + get + { + if (base.Focused) + return true; IntPtr focus = UnsafeNativeMethods.GetFocus(); return focus != IntPtr.Zero && ((childEdit != null && focus == childEdit.Handle) || (childListBox != null && focus == childListBox.Handle)); } @@ -605,16 +693,21 @@ public override bool Focused { /// Gets or sets the foreground color of the control. /// /// - public override Color ForeColor { - get { - if (ShouldSerializeForeColor()) { + public override Color ForeColor + { + get + { + if (ShouldSerializeForeColor()) + { return base.ForeColor; } - else { + else + { return SystemColors.WindowText; } } - set { + set + { base.ForeColor = value; } } @@ -631,13 +724,17 @@ public override Color ForeColor { Localizable(true), SRDescription(nameof(SR.ComboBoxIntegralHeightDescr)) ] - public bool IntegralHeight { - get { + public bool IntegralHeight + { + get + { return integralHeight; } - set { - if (integralHeight != value) { + set + { + if (integralHeight != value) + { integralHeight = value; RecreateHandle(); } @@ -656,20 +753,25 @@ public bool IntegralHeight { Localizable(true), SRDescription(nameof(SR.ComboBoxItemHeightDescr)) ] - public int ItemHeight { - get { + public int ItemHeight + { + get + { DrawMode drawMode = DrawMode; if (drawMode == DrawMode.OwnerDrawFixed || drawMode == DrawMode.OwnerDrawVariable || - !IsHandleCreated) { + !IsHandleCreated) + { bool found; int itemHeight = Properties.GetInteger(PropItemHeight, out found); - if (found) { + if (found) + { return itemHeight; } - else { + else + { return FontHeight + 2; // } } @@ -677,23 +779,28 @@ public int ItemHeight { // Note that the above if clause deals with the case when the handle has not yet been created Debug.Assert(IsHandleCreated, "Handle should be created at this point"); - int h = unchecked( (int) (long)SendMessage(NativeMethods.CB_GETITEMHEIGHT, 0, 0) ); - if (h == -1) { + int h = unchecked((int)(long)SendMessage(NativeMethods.CB_GETITEMHEIGHT, 0, 0)); + if (h == -1) + { throw new Win32Exception(); } return h; } - set { - if (value < 1) { + set + { + if (value < 1) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(ItemHeight), value)); } ResetHeightCache(); - if (Properties.GetInteger(PropItemHeight) != value) { + if (Properties.GetInteger(PropItemHeight) != value) + { Properties.SetInteger(PropItemHeight, value); - if (DrawMode != DrawMode.Normal) { + if (DrawMode != DrawMode.Normal) + { UpdateItemHeight(); } } @@ -711,9 +818,12 @@ public int ItemHeight { Editor("System.Windows.Forms.Design.ListControlStringCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), MergableProperty(false) ] - public ObjectCollection Items { - get { - if (itemsCollection == null) { + public ObjectCollection Items + { + get + { + if (itemsCollection == null) + { itemsCollection = new ObjectCollection(this); } return itemsCollection; @@ -722,13 +832,17 @@ public ObjectCollection Items { // Text used to match an item in the list when auto-completion // is used in DropDownList style. - private string MatchingText { - get { + private string MatchingText + { + get + { string matchingText = (string)Properties.GetObject(PropMatchingText); return (matchingText == null) ? string.Empty : matchingText; } - set { - if (value != null || this.Properties.ContainsObject(PropMatchingText)) { + set + { + if (value != null || this.Properties.ContainsObject(PropMatchingText)) + { Properties.SetObject(PropMatchingText, value); } } @@ -744,28 +858,36 @@ private string MatchingText { Localizable(true), SRDescription(nameof(SR.ComboBoxMaxDropDownItemsDescr)) ] - public int MaxDropDownItems { - get { + public int MaxDropDownItems + { + get + { return maxDropDownItems; } - set { - if (value < 1 || value > 100) { + set + { + if (value < 1 || value > 100) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidBoundArgument, nameof(MaxDropDownItems), value, 1, 100)); } maxDropDownItems = (short)value; } } - public override Size MaximumSize { + public override Size MaximumSize + { get { return base.MaximumSize; } - set { + set + { base.MaximumSize = new Size(value.Width, 0); } } - public override Size MinimumSize { + public override Size MinimumSize + { get { return base.MinimumSize; } - set { + set + { base.MinimumSize = new Size(value.Width, 0); } } @@ -780,15 +902,21 @@ public override Size MinimumSize { Localizable(true), SRDescription(nameof(SR.ComboBoxMaxLengthDescr)) ] - public int MaxLength { - get { + public int MaxLength + { + get + { return Properties.GetInteger(PropMaxLength); } - set { - if (value < 0) value = 0; - if (MaxLength != value) { + set + { + if (value < 0) + value = 0; + if (MaxLength != value) + { Properties.SetInteger(PropMaxLength, value); - if (IsHandleCreated) SendMessage(NativeMethods.CB_LIMITTEXT, value, 0); + if (IsHandleCreated) + SendMessage(NativeMethods.CB_LIMITTEXT, value, 0); } } } @@ -796,15 +924,19 @@ public int MaxLength { /// /// If the mouse is over the combobox, draw selection rect. /// - internal bool MouseIsOver { + internal bool MouseIsOver + { get { return mouseOver; } - set { - if (mouseOver != value) { + set + { + if (mouseOver != value) + { mouseOver = value; // Nothing to see here... Just keep on walking... // Turns out that with Theming off, we don't get quite the same messages as with theming on, so // our drawing gets a little messed up. So in case theming is off, force a draw here. - if ((!ContainsFocus || !Application.RenderWithVisualStyles) && this.FlatStyle == FlatStyle.Popup) { + if ((!ContainsFocus || !Application.RenderWithVisualStyles) && this.FlatStyle == FlatStyle.Popup) + { Invalidate(); Update(); } @@ -817,7 +949,8 @@ internal bool MouseIsOver { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Padding Padding { + public new Padding Padding + { get { return base.Padding; } set { base.Padding = value; } } @@ -826,10 +959,12 @@ internal bool MouseIsOver { Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public new event EventHandler PaddingChanged { - add => base.PaddingChanged += value; - remove => base.PaddingChanged -= value; } - + public new event EventHandler PaddingChanged + { + add => base.PaddingChanged += value; + remove => base.PaddingChanged -= value; + } + /// /// ApplySizeConstraints calls into this method when DropDownStyles is DropDown and DropDownList. @@ -840,9 +975,12 @@ internal bool MouseIsOver { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ComboBoxPreferredHeightDescr)) ] - public int PreferredHeight { - get { - if (!FormattingEnabled) { + public int PreferredHeight + { + get + { + if (!FormattingEnabled) + { //do preferred height the old broken way for everett apps //we need this for compat reasons because (get this) @@ -864,22 +1002,26 @@ public int PreferredHeight { Size textSize = TextRenderer.MeasureText(LayoutUtils.TestString, this.Font, new Size(short.MaxValue, (int)(FontHeight * 1.25)), TextFormatFlags.SingleLine); prefHeightCache = (short)(textSize.Height + SystemInformation.BorderSize.Height * 8 + Padding.Size.Height); - return prefHeightCache ; + return prefHeightCache; } - else { + else + { // Normally we do this sort of calculation in GetPreferredSizeCore which has builtin // caching, but in this case we can not because PreferredHeight is used in ApplySizeConstraints // which is used by GetPreferredSize (infinite loop). - if (prefHeightCache < 0) { + if (prefHeightCache < 0) + { Size textSize = TextRenderer.MeasureText(LayoutUtils.TestString, this.Font, new Size(short.MaxValue, (int)(FontHeight * 1.25)), TextFormatFlags.SingleLine); // For a "simple" style combobox, the preferred height depends on the // number of items in the combobox. - if (DropDownStyle == ComboBoxStyle.Simple) { + if (DropDownStyle == ComboBoxStyle.Simple) + { int itemCount = Items.Count + 1; prefHeightCache = (short)(textSize.Height * itemCount + SystemInformation.BorderSize.Height * 16 + Padding.Size.Height); } - else { + else + { // We do this old school rather than use SizeFromClientSize because CreateParams calls this // method and SizeFromClientSize calls CreateParams (another infinite loop.) prefHeightCache = (short)GetComboHeight(); @@ -895,7 +1037,8 @@ public int PreferredHeight { // This is translated from windows implementation. Since we cannot control the size // of the combo box, we need to use the same calculation they do. [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] // "0" is what Windows uses in all languages. - private int GetComboHeight() { + private int GetComboHeight() + { int cyCombo = 0; // Add on CYEDGE just for some extra space in the edit field/static item. @@ -903,14 +1046,16 @@ private int GetComboHeight() { // controls to be the same height. Size textExtent = Size.Empty; - using (WindowsFont font = WindowsFont.FromFont(this.Font)) { + using (WindowsFont font = WindowsFont.FromFont(this.Font)) + { // this is the character that Windows uses to determine the extent textExtent = WindowsGraphicsCacheManager.MeasurementGraphics.GetTextExtent("0", font); } int dyEdit = textExtent.Height + SystemInformation.Border3DSize.Height; - if (DrawMode != DrawMode.Normal) { + if (DrawMode != DrawMode.Normal) + { // This is an ownerdraw combo. Have the owner tell us how tall this // item is. dyEdit = ItemHeight; @@ -928,20 +1073,22 @@ private string[] GetStringsForAutoComplete(IList collection) if (collection is AutoCompleteStringCollection) { string[] strings = new string[AutoCompleteCustomSource.Count]; - for (int i = 0; i < AutoCompleteCustomSource.Count; i++) { + for (int i = 0; i < AutoCompleteCustomSource.Count; i++) + { strings[i] = AutoCompleteCustomSource[i]; } return strings; - + } else if (collection is ObjectCollection) { string[] strings = new string[itemsCollection.Count]; - for (int i = 0; i < itemsCollection.Count; i++) { + for (int i = 0; i < itemsCollection.Count; i++) + { strings[i] = GetItemText(itemsCollection[i]); } return strings; - + } return new string[0]; } @@ -957,38 +1104,49 @@ private string[] GetStringsForAutoComplete(IList collection) DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ComboBoxSelectedIndexDescr)) ] - public override int SelectedIndex { - get { - if (IsHandleCreated) { + public override int SelectedIndex + { + get + { + if (IsHandleCreated) + { - return unchecked( (int) (long)SendMessage(NativeMethods.CB_GETCURSEL, 0, 0) ); + return unchecked((int)(long)SendMessage(NativeMethods.CB_GETCURSEL, 0, 0)); } - else { + else + { return selectedIndex; } } - set { - if (SelectedIndex != value) { + set + { + if (SelectedIndex != value) + { int itemCount = 0; - if (itemsCollection != null) { + if (itemsCollection != null) + { itemCount = itemsCollection.Count; } - if (value < -1 || value >= itemCount) { + if (value < -1 || value >= itemCount) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(SelectedIndex), value)); } - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(NativeMethods.CB_SETCURSEL, value, 0); } - else { + else + { selectedIndex = value; } UpdateText(); - if (IsHandleCreated) { + if (IsHandleCreated) + { OnTextChanged(EventArgs.Empty); } @@ -1008,15 +1166,19 @@ public override int SelectedIndex { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ComboBoxSelectedItemDescr)) ] - public object SelectedItem { - get { + public object SelectedItem + { + get + { int index = SelectedIndex; return (index == -1) ? null : Items[index]; } - set { + set + { int x = -1; - if (itemsCollection != null) { + if (itemsCollection != null) + { // if (value != null) x = itemsCollection.IndexOf(value); @@ -1024,7 +1186,8 @@ public object SelectedItem { SelectedIndex = -1; } - if (x != -1) { + if (x != -1) + { SelectedIndex = x; } } @@ -1040,20 +1203,27 @@ public object SelectedItem { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ComboBoxSelectedTextDescr)) ] - public string SelectedText { - get { - if (DropDownStyle == ComboBoxStyle.DropDownList) return ""; + public string SelectedText + { + get + { + if (DropDownStyle == ComboBoxStyle.DropDownList) + return ""; return Text.Substring(SelectionStart, SelectionLength); } - set { - if (DropDownStyle != ComboBoxStyle.DropDownList) { + set + { + if (DropDownStyle != ComboBoxStyle.DropDownList) + { //guard against null string, since otherwise we will throw an //AccessViolation exception, which is bad string str = (value == null ? "" : value); CreateControl(); - if (IsHandleCreated) { + if (IsHandleCreated) + { Debug.Assert(childEdit != null); - if (childEdit != null) { + if (childEdit != null) + { UnsafeNativeMethods.SendMessage(new HandleRef(this, childEdit.Handle), Interop.EditMessages.EM_REPLACESEL, NativeMethods.InvalidIntPtr, str); } } @@ -1069,14 +1239,17 @@ public string SelectedText { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ComboBoxSelectionLengthDescr)) ] - public int SelectionLength { - get { + public int SelectionLength + { + get + { int[] end = new int[] { 0 }; int[] start = new int[] { 0 }; UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.CB_GETEDITSEL, start, end); return end[0] - start[0]; } - set { + set + { // SelectionLength can be negtive... Select(SelectionStart, value); } @@ -1090,14 +1263,18 @@ public int SelectionLength { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ComboBoxSelectionStartDescr)) ] - public int SelectionStart { - get { + public int SelectionStart + { + get + { int[] value = new int[] { 0 }; UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.CB_GETEDITSEL, value, (int[])null); return value[0]; } - set { - if (value < 0) { + set + { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(SelectionStart), value)); } Select(value, SelectionLength); @@ -1112,13 +1289,18 @@ public int SelectionStart { DefaultValue(false), SRDescription(nameof(SR.ComboBoxSortedDescr)) ] - public bool Sorted { - get { + public bool Sorted + { + get + { return sorted; } - set { - if (sorted != value) { - if (this.DataSource != null && value) { + set + { + if (sorted != value) + { + if (this.DataSource != null && value) + { throw new ArgumentException(SR.ComboBoxSortWithDataSource); } @@ -1139,18 +1321,23 @@ public bool Sorted { SRDescription(nameof(SR.ComboBoxStyleDescr)), RefreshPropertiesAttribute(RefreshProperties.Repaint) ] - public ComboBoxStyle DropDownStyle { - get { + public ComboBoxStyle DropDownStyle + { + get + { bool found; int style = Properties.GetInteger(PropStyle, out found); - if (found) { + if (found) + { return (ComboBoxStyle)style; } return ComboBoxStyle.DropDown; } - set { - if (DropDownStyle != value) { + set + { + if (DropDownStyle != value) + { // verify that 'value' is a valid enum type... //valid values are 0x0 to 0x2 @@ -1161,7 +1348,8 @@ public ComboBoxStyle DropDownStyle { if (value == ComboBoxStyle.DropDownList && this.AutoCompleteSource != AutoCompleteSource.ListItems && - this.AutoCompleteMode != AutoCompleteMode.None) { + this.AutoCompleteMode != AutoCompleteMode.None) + { this.AutoCompleteMode = AutoCompleteMode.None; } @@ -1170,7 +1358,8 @@ public ComboBoxStyle DropDownStyle { Properties.SetInteger(PropStyle, (int)value); - if (IsHandleCreated) { + if (IsHandleCreated) + { RecreateHandle(); } @@ -1183,26 +1372,34 @@ public ComboBoxStyle DropDownStyle { Localizable(true), Bindable(true) ] - public override string Text { - get { - if (SelectedItem != null && !BindingFieldEmpty) { + public override string Text + { + get + { + if (SelectedItem != null && !BindingFieldEmpty) + { //preserve everett behavior if "formatting enabled == false" -- just return selecteditem text. - if (FormattingEnabled) { + if (FormattingEnabled) + { string candidate = GetItemText(SelectedItem); - if (!string.IsNullOrEmpty(candidate)) { - if (string.Compare(candidate, base.Text, true, CultureInfo.CurrentCulture) == 0) { + if (!string.IsNullOrEmpty(candidate)) + { + if (string.Compare(candidate, base.Text, true, CultureInfo.CurrentCulture) == 0) + { return candidate; //for whidbey, if we only differ by case -- return the candidate; } } } - else { + else + { return FilterItemOnProperty(SelectedItem).ToString(); //heinous. } } return base.Text; } - set { + set + { if (DropDownStyle == ComboBoxStyle.DropDownList && !IsHandleCreated && !string.IsNullOrEmpty(value) && FindStringExact(value) == -1) return; @@ -1211,20 +1408,24 @@ public override string Text { selectedItem = SelectedItem; - if (!DesignMode) { + if (!DesignMode) + { // - if (value == null) { + if (value == null) + { SelectedIndex = -1; } else if (value != null && - (selectedItem == null || (string.Compare(value, GetItemText(selectedItem), false, CultureInfo.CurrentCulture) != 0))) { + (selectedItem == null || (string.Compare(value, GetItemText(selectedItem), false, CultureInfo.CurrentCulture) != 0))) + { int index = FindStringIgnoreCase(value); //we cannot set the index to -1 unless we want to do something unusual and save/restore text //because the native control will erase the text when we change the index to -1 - if (index != -1) { + if (index != -1) + { SelectedIndex = index; } } @@ -1233,11 +1434,13 @@ public override string Text { } - private int FindStringIgnoreCase(string value) { + private int FindStringIgnoreCase(string value) + { //look for an exact match and then a case insensitive match if that fails. int index = FindStringExact(value, -1, false); - if (index == -1) { + if (index == -1) + { index = FindStringExact(value, -1, true); } @@ -1247,25 +1450,29 @@ private int FindStringIgnoreCase(string value) { // Special AutoComplete notification handling // If the text changed, this will fire TextChanged // If it matches an item in the list, this will fire SIC and SVC - private void NotifyAutoComplete() { + private void NotifyAutoComplete() + { NotifyAutoComplete(true); } // Special AutoComplete notification handling // If the text changed, this will fire TextChanged // If it matches an item in the list, this will fire SIC and SVC - private void NotifyAutoComplete(bool setSelectedIndex) { + private void NotifyAutoComplete(bool setSelectedIndex) + { string text = this.Text; bool textChanged = (text != this.lastTextChangedValue); bool selectedIndexSet = false; - if (setSelectedIndex) { + if (setSelectedIndex) + { // Process return key. This is sent by the AutoComplete DropDown when a // selection is made from the DropDown // Check to see if the Text Changed. If so, at least fire a TextChanged int index = FindStringIgnoreCase(text); - if ((index != -1) && (index != SelectedIndex)) { + if ((index != -1) && (index != SelectedIndex)) + { // We found a match, do the full monty SelectedIndex = index; @@ -1278,7 +1485,8 @@ private void NotifyAutoComplete(bool setSelectedIndex) { } //don't fire textch if we had set the selectedindex -- because it was already fired if so. - if (textChanged && !selectedIndexSet) { + if (textChanged && !selectedIndexSet) + { // No match, just fire a TextChagned OnTextChanged(EventArgs.Empty); } @@ -1290,39 +1498,47 @@ private void NotifyAutoComplete(bool setSelectedIndex) { internal override bool SupportsUiaProviders => true; // Returns true if using System AutoComplete - private bool SystemAutoCompleteEnabled { - get { + private bool SystemAutoCompleteEnabled + { + get + { return ((this.autoCompleteMode != AutoCompleteMode.None) && (this.DropDownStyle != ComboBoxStyle.DropDownList)); } } // Prevent this event from being displayed in the Property Grid. [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler DoubleClick { + public new event EventHandler DoubleClick + { add => base.DoubleClick += value; remove => base.DoubleClick -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.drawItemEventDescr))] - public event DrawItemEventHandler DrawItem { + public event DrawItemEventHandler DrawItem + { add => Events.AddHandler(EVENT_DRAWITEM, value); remove => Events.RemoveHandler(EVENT_DRAWITEM, value); } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ComboBoxOnDropDownDescr))] - public event EventHandler DropDown { + public event EventHandler DropDown + { add => Events.AddHandler(EVENT_DROPDOWN, value); remove => Events.RemoveHandler(EVENT_DROPDOWN, value); } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.measureItemEventDescr))] - public event MeasureItemEventHandler MeasureItem { - add { + public event MeasureItemEventHandler MeasureItem + { + add + { Events.AddHandler(EVENT_MEASUREITEM, value); UpdateItemHeight(); } - remove { + remove + { Events.RemoveHandler(EVENT_MEASUREITEM, value); UpdateItemHeight(); } @@ -1330,19 +1546,22 @@ public event MeasureItemEventHandler MeasureItem { [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.selectedIndexChangedEventDescr))] - public event EventHandler SelectedIndexChanged { + public event EventHandler SelectedIndexChanged + { add => Events.AddHandler(EVENT_SELECTEDINDEXCHANGED, value); remove => Events.RemoveHandler(EVENT_SELECTEDINDEXCHANGED, value); } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.selectionChangeCommittedEventDescr))] - public event EventHandler SelectionChangeCommitted { + public event EventHandler SelectionChangeCommitted + { add => Events.AddHandler(EVENT_SELECTIONCHANGECOMMITTED, value); remove => Events.RemoveHandler(EVENT_SELECTIONCHANGECOMMITTED, value); } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ComboBoxDropDownStyleChangedDescr))] - public event EventHandler DropDownStyleChanged { + public event EventHandler DropDownStyleChanged + { add => Events.AddHandler(EVENT_DROPDOWNSTYLE, value); remove => Events.RemoveHandler(EVENT_DROPDOWNSTYLE, value); } @@ -1352,7 +1571,8 @@ public event EventHandler DropDownStyleChanged { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event PaintEventHandler Paint { + public new event PaintEventHandler Paint + { add => base.Paint += value; remove => base.Paint -= value; } @@ -1363,7 +1583,8 @@ public event EventHandler DropDownStyleChanged { // /// [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ComboBoxOnTextUpdateDescr))] - public event EventHandler TextUpdate { + public event EventHandler TextUpdate + { add => Events.AddHandler(EVENT_TEXTUPDATE, value); remove => Events.RemoveHandler(EVENT_TEXTUPDATE, value); } @@ -1375,7 +1596,8 @@ public event EventHandler TextUpdate { // /// [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ComboBoxOnDropDownClosedDescr))] - public event EventHandler DropDownClosed { + public event EventHandler DropDownClosed + { add => Events.AddHandler(EVENT_DROPDOWNCLOSED, value); remove => Events.RemoveHandler(EVENT_DROPDOWNCLOSED, value); } @@ -1384,17 +1606,21 @@ public event EventHandler DropDownClosed { /// Performs the work of adding the specified items to the combobox /// [Obsolete("This method has been deprecated. There is no replacement. http://go.microsoft.com/fwlink/?linkid=14202")] - protected virtual void AddItemsCore(object[] value) { + protected virtual void AddItemsCore(object[] value) + { int count = value == null ? 0 : value.Length; - if (count == 0) { + if (count == 0) + { return; } BeginUpdate(); - try { + try + { Items.AddRangeInternal(value); } - finally { + finally + { EndUpdate(); } } @@ -1405,24 +1631,28 @@ protected virtual void AddItemsCore(object[] value) { /// beginUpdate(), any redrawing caused by operations performed on the /// combo box is deferred until the call to endUpdate(). /// - public void BeginUpdate() { + public void BeginUpdate() + { updateCount++; BeginUpdateInternal(); } - private void CheckNoDataSource() { - if (DataSource != null) { + private void CheckNoDataSource() + { + if (DataSource != null) + { throw new ArgumentException(SR.DataSourceLocksItems); } } /// /// - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new ComboBoxAccessibleObject(this); } - /// + /// /// internal bool UpdateNeeded() { @@ -1433,8 +1663,10 @@ internal bool UpdateNeeded() /// /// This procedure takes in the message, converts the Edit handle coordinates into Combo Box Coordinates /// - internal Point EditToComboboxMapping(Message m) { - if (childEdit == null) { + internal Point EditToComboboxMapping(Message m) + { + if (childEdit == null) + { return new Point(0, 0); } // Get the Combox Rect ... @@ -1460,16 +1692,22 @@ internal Point EditToComboboxMapping(Message m) { /// Subclassed window procedure for the edit and list child controls of the /// combo box. /// - private void ChildWndProc(ref Message m) { + private void ChildWndProc(ref Message m) + { - switch (m.Msg) { + switch (m.Msg) + { case Interop.WindowMessages.WM_CHAR: - if (DropDownStyle == ComboBoxStyle.Simple && m.HWnd == childListBox.Handle) { + if (DropDownStyle == ComboBoxStyle.Simple && m.HWnd == childListBox.Handle) + { DefChildWndProc(ref m); } - else { - if (PreProcessControlMessage(ref m) != PreProcessControlState.MessageProcessed) { - if (ProcessKeyMessage(ref m)) { + else + { + if (PreProcessControlMessage(ref m) != PreProcessControlState.MessageProcessed) + { + if (ProcessKeyMessage(ref m)) + { return; } DefChildWndProc(ref m); @@ -1477,42 +1715,54 @@ private void ChildWndProc(ref Message m) { } break; case Interop.WindowMessages.WM_SYSCHAR: - if (DropDownStyle == ComboBoxStyle.Simple && m.HWnd == childListBox.Handle) { + if (DropDownStyle == ComboBoxStyle.Simple && m.HWnd == childListBox.Handle) + { DefChildWndProc(ref m); } - else { - if (PreProcessControlMessage(ref m) != PreProcessControlState.MessageProcessed) { - if (ProcessKeyEventArgs(ref m)) { - return; - } + else + { + if (PreProcessControlMessage(ref m) != PreProcessControlState.MessageProcessed) + { + if (ProcessKeyEventArgs(ref m)) + { + return; + } DefChildWndProc(ref m); } } break; case Interop.WindowMessages.WM_KEYDOWN: case Interop.WindowMessages.WM_SYSKEYDOWN: - if (SystemAutoCompleteEnabled && !ACNativeWindow.AutoCompleteActive) { + if (SystemAutoCompleteEnabled && !ACNativeWindow.AutoCompleteActive) + { finder.FindDropDowns(false); } - if (AutoCompleteMode != AutoCompleteMode.None) { + if (AutoCompleteMode != AutoCompleteMode.None) + { char keyChar = unchecked((char)(long)m.WParam); - if (keyChar == (char)(int)Keys.Escape) { + if (keyChar == (char)(int)Keys.Escape) + { this.DroppedDown = false; } - else if (keyChar == (char)(int)Keys.Return && this.DroppedDown) { + else if (keyChar == (char)(int)Keys.Return && this.DroppedDown) + { UpdateText(); OnSelectionChangeCommittedInternal(EventArgs.Empty); this.DroppedDown = false; } } - - if (DropDownStyle == ComboBoxStyle.Simple && m.HWnd == childListBox.Handle) { + + if (DropDownStyle == ComboBoxStyle.Simple && m.HWnd == childListBox.Handle) + { DefChildWndProc(ref m); } - else { - if (PreProcessControlMessage(ref m) != PreProcessControlState.MessageProcessed) { - if (ProcessKeyMessage(ref m)) { + else + { + if (PreProcessControlMessage(ref m) != PreProcessControlState.MessageProcessed) + { + if (ProcessKeyMessage(ref m)) + { return; } DefChildWndProc(ref m); @@ -1521,23 +1771,28 @@ private void ChildWndProc(ref Message m) { break; case Interop.WindowMessages.WM_INPUTLANGCHANGE: - DefChildWndProc( ref m ); + DefChildWndProc(ref m); break; case Interop.WindowMessages.WM_KEYUP: case Interop.WindowMessages.WM_SYSKEYUP: - if (DropDownStyle == ComboBoxStyle.Simple && m.HWnd == childListBox.Handle) { + if (DropDownStyle == ComboBoxStyle.Simple && m.HWnd == childListBox.Handle) + { DefChildWndProc(ref m); } - else { - if (PreProcessControlMessage(ref m) != PreProcessControlState.MessageProcessed) { - if (ProcessKeyMessage(ref m)) { + else + { + if (PreProcessControlMessage(ref m) != PreProcessControlState.MessageProcessed) + { + if (ProcessKeyMessage(ref m)) + { return; } DefChildWndProc(ref m); } } - if (SystemAutoCompleteEnabled && !ACNativeWindow.AutoCompleteActive) { + if (SystemAutoCompleteEnabled && !ACNativeWindow.AutoCompleteActive) + { finder.FindDropDowns(); } @@ -1545,18 +1800,21 @@ private void ChildWndProc(ref Message m) { case Interop.WindowMessages.WM_KILLFOCUS: // Consider - If we dont' have a childwndproc, then we don't get here, so we don't // update the cache. Do we need to? This happens when we have a DropDownList. - if (!DesignMode) { - OnImeContextStatusChanged( m.HWnd ); + if (!DesignMode) + { + OnImeContextStatusChanged(m.HWnd); } DefChildWndProc(ref m); // We don't want to fire the focus events twice - // once in the combobox and once here. - if (fireLostFocus) { + if (fireLostFocus) + { this.InvokeLostFocus(this, EventArgs.Empty); } - if (FlatStyle == FlatStyle.Popup) { + if (FlatStyle == FlatStyle.Popup) + { this.Invalidate(); } @@ -1565,16 +1823,21 @@ private void ChildWndProc(ref Message m) { // Consider - If we dont' have a childwndproc, then we don't get here, so we don't // set the status. Do we need to? This happens when we have a DropDownList. - if (!DesignMode) { + if (!DesignMode) + { ImeContext.SetImeStatus(CachedImeMode, m.HWnd); } - if (!HostedInWin32DialogManager) { + if (!HostedInWin32DialogManager) + { IContainerControl c = GetContainerControl(); - if (c != null) { + if (c != null) + { ContainerControl container = c as ContainerControl; - if (container != null) { - if (!container.ActivateControlInternal(this, false)) { + if (container != null) + { + if (!container.ActivateControlInternal(this, false)) + { return; } } @@ -1585,18 +1848,21 @@ private void ChildWndProc(ref Message m) { // We don't want to fire the focus events twice - // once in the combobox and once here. - if (fireSetFocus) { + if (fireSetFocus) + { this.InvokeGotFocus(this, EventArgs.Empty); } - if (FlatStyle == FlatStyle.Popup) { + if (FlatStyle == FlatStyle.Popup) + { this.Invalidate(); } break; case Interop.WindowMessages.WM_SETFONT: DefChildWndProc(ref m); - if (childEdit != null && m.HWnd == childEdit.Handle) { + if (childEdit != null && m.HWnd == childEdit.Handle) + { UnsafeNativeMethods.SendMessage(new HandleRef(this, childEdit.Handle), Interop.EditMessages.EM_SETMARGINS, NativeMethods.EC_LEFTMARGIN | NativeMethods.EC_RIGHTMARGIN, 0); } @@ -1676,15 +1942,19 @@ private void ChildWndProc(ref Message m) { pt = PointToScreen(pt); // combo box gets a WM_LBUTTONUP for focus change ... // So check MouseEvents.... - if (mouseEvents && !ValidationCancelled) { + if (mouseEvents && !ValidationCancelled) + { mouseEvents = false; - if (mousePressed) { - if (ClientRect.Contains(pt)) { + if (mousePressed) + { + if (ClientRect.Contains(pt)) + { mousePressed = false; OnClick(new MouseEventArgs(MouseButtons.Left, 1, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); OnMouseClick(new MouseEventArgs(MouseButtons.Left, 1, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); } - else { + else + { mousePressed = false; mouseInEdit = false; OnMouseLeave(EventArgs.Empty); @@ -1757,10 +2027,12 @@ private void ChildWndProc(ref Message m) { case Interop.WindowMessages.WM_CONTEXTMENU: // Forward context menu messages to the parent control - if (this.ContextMenu != null || this.ContextMenuStrip != null) { + if (this.ContextMenu != null || this.ContextMenuStrip != null) + { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.WindowMessages.WM_CONTEXTMENU, m.WParam, m.LParam); } - else { + else + { DefChildWndProc(ref m); } break; @@ -1775,10 +2047,12 @@ private void ChildWndProc(ref Message m) { break; case Interop.WindowMessages.WM_SETCURSOR: - if (Cursor != DefaultCursor && childEdit != null && m.HWnd == childEdit.Handle && NativeMethods.Util.LOWORD(m.LParam) == NativeMethods.HTCLIENT) { + if (Cursor != DefaultCursor && childEdit != null && m.HWnd == childEdit.Handle && NativeMethods.Util.LOWORD(m.LParam) == NativeMethods.HTCLIENT) + { Cursor.CurrentInternal = Cursor; } - else { + else + { DefChildWndProc(ref m); } break; @@ -1798,8 +2072,10 @@ private void ChildWndProc(ref Message m) { /// Helper to handle MouseEnter. /// /// - private void OnMouseEnterInternal(EventArgs args) { - if (!mouseInEdit) { + private void OnMouseEnterInternal(EventArgs args) + { + if (!mouseInEdit) + { OnMouseEnter(args); mouseInEdit = true; } @@ -1809,12 +2085,14 @@ private void OnMouseEnterInternal(EventArgs args) { /// Helper to handle mouseleave /// /// - private void OnMouseLeaveInternal(EventArgs args) { + private void OnMouseLeaveInternal(EventArgs args) + { NativeMethods.RECT rect = new NativeMethods.RECT(); UnsafeNativeMethods.GetWindowRect(new HandleRef(this, Handle), ref rect); Rectangle Rect = new Rectangle(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top); Point p = MousePosition; - if (!Rect.Contains(p)) { + if (!Rect.Contains(p)) + { OnMouseLeave(args); mouseInEdit = false; } @@ -1822,30 +2100,40 @@ private void OnMouseLeaveInternal(EventArgs args) { /// /// - private void DefChildWndProc(ref Message m) { - if (childEdit != null) { + private void DefChildWndProc(ref Message m) + { + if (childEdit != null) + { NativeWindow childWindow; - if (m.HWnd == childEdit.Handle) { + if (m.HWnd == childEdit.Handle) + { childWindow = childEdit; - } else if (m.HWnd == dropDownHandle) { + } + else if (m.HWnd == dropDownHandle) + { childWindow = childDropDown; } - else { + else + { childWindow = childListBox; } //childwindow could be null if the handle was recreated while within a message handler // and then whoever recreated the handle allowed the message to continue to be processed //we cannot really be sure the new child will properly handle this window message, so we eat it. - if (childWindow != null) { + if (childWindow != null) + { childWindow.DefWndProc(ref m); } } } - protected override void Dispose(bool disposing) { - if (disposing) { - if (autoCompleteCustomSource != null) { + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (autoCompleteCustomSource != null) + { autoCompleteCustomSource.CollectionChanged -= new CollectionChangeEventHandler(this.OnAutoCompleteCustomSourceChanged); } if (stringSource != null) @@ -1866,17 +2154,21 @@ protected override void Dispose(bool disposing) { /// beginUpdate(), any redrawing caused by operations performed on the /// combo box is deferred until the call to endUpdate(). /// - public void EndUpdate() { + public void EndUpdate() + { updateCount--; if (updateCount == 0 && AutoCompleteSource == AutoCompleteSource.ListItems) { SetAutoComplete(false, false); } - if (EndUpdateInternal()) { - if (childEdit != null && childEdit.Handle != IntPtr.Zero) { + if (EndUpdateInternal()) + { + if (childEdit != null && childEdit.Handle != IntPtr.Zero) + { SafeNativeMethods.InvalidateRect(new HandleRef(this, childEdit.Handle), null, false); } - if (childListBox != null && childListBox.Handle != IntPtr.Zero) { + if (childListBox != null && childListBox.Handle != IntPtr.Zero) + { SafeNativeMethods.InvalidateRect(new HandleRef(this, childListBox.Handle), null, false); } } @@ -1901,7 +2193,7 @@ public int FindString(string s, int startIndex) /// Finds the first item in the combo box that matches the given string. /// The strings must match exactly, except for differences in casing. /// - public int FindStringExact(string s) + public int FindStringExact(string s) { return FindStringExact(s, startIndex: -1, ignoreCase: true); } @@ -1926,20 +2218,24 @@ internal int FindStringExact(string s, int startIndex, bool ignoreCase) // GetPreferredSize and SetBoundsCore call this method to allow controls to self impose // constraints on their size. - internal override Rectangle ApplyBoundsConstraints(int suggestedX, int suggestedY, int proposedWidth, int proposedHeight) { + internal override Rectangle ApplyBoundsConstraints(int suggestedX, int suggestedY, int proposedWidth, int proposedHeight) + { if (DropDownStyle == ComboBoxStyle.DropDown - || DropDownStyle == ComboBoxStyle.DropDownList) { + || DropDownStyle == ComboBoxStyle.DropDownList) + { proposedHeight = PreferredHeight; } - return base.ApplyBoundsConstraints(suggestedX,suggestedY, proposedWidth, proposedHeight); + return base.ApplyBoundsConstraints(suggestedX, suggestedY, proposedWidth, proposedHeight); } - [SuppressMessage("Microsoft.Portability", "CA1902:AvoidTestingForFloatingPointEquality")] - protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { - - if (factor.Width != 1F && factor.Height != 1F) { + [SuppressMessage("Microsoft.Portability", "CA1902:AvoidTestingForFloatingPointEquality")] + protected override void ScaleControl(SizeF factor, BoundsSpecified specified) + { + + if (factor.Width != 1F && factor.Height != 1F) + { // we get called on scale before we get a notification that our font has changed. // in this case, we need to reset our height cache. ResetHeightCache(); @@ -1952,21 +2248,26 @@ protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { /// combo box. This method should not be used for Normal or OwnerDrawFixed /// style combo boxes. /// - public int GetItemHeight(int index) { + public int GetItemHeight(int index) + { // This function is only relevant for OwnerDrawVariable - if (DrawMode != DrawMode.OwnerDrawVariable) { + if (DrawMode != DrawMode.OwnerDrawVariable) + { return ItemHeight; } - if (index < 0 || itemsCollection == null || index >= itemsCollection.Count) { + if (index < 0 || itemsCollection == null || index >= itemsCollection.Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - if (IsHandleCreated) { + if (IsHandleCreated) + { - int h = unchecked( (int) (long)SendMessage(NativeMethods.CB_GETITEMHEIGHT, index, 0) ); - if (h == -1) { + int h = unchecked((int)(long)SendMessage(NativeMethods.CB_GETITEMHEIGHT, index, 0)); + if (h == -1) + { throw new Win32Exception(); } return h; @@ -1975,27 +2276,33 @@ public int GetItemHeight(int index) { return ItemHeight; } - internal IntPtr GetListHandle() { + internal IntPtr GetListHandle() + { return DropDownStyle == ComboBoxStyle.Simple ? childListBox.Handle : dropDownHandle; } - internal NativeWindow GetListNativeWindow() { + internal NativeWindow GetListNativeWindow() + { return DropDownStyle == ComboBoxStyle.Simple ? childListBox : childDropDown; } - internal int GetListNativeWindowRuntimeIdPart() { + internal int GetListNativeWindowRuntimeIdPart() + { var listNativeWindow = GetListNativeWindow(); return listNativeWindow != null ? listNativeWindow.GetHashCode() : 0; } - internal override IntPtr InitializeDCForWmCtlColor(IntPtr dc, int msg) { - if ((msg == Interop.WindowMessages.WM_CTLCOLORSTATIC) && !ShouldSerializeBackColor()) { + internal override IntPtr InitializeDCForWmCtlColor(IntPtr dc, int msg) + { + if ((msg == Interop.WindowMessages.WM_CTLCOLORSTATIC) && !ShouldSerializeBackColor()) + { // Let the Win32 Edit control handle background colors itself. // This is necessary because a disabled edit control will display a different // BackColor than when enabled. return IntPtr.Zero; } - else if ((msg == Interop.WindowMessages.WM_CTLCOLORLISTBOX) && GetStyle(ControlStyles.UserPaint)) { + else if ((msg == Interop.WindowMessages.WM_CTLCOLORLISTBOX) && GetStyle(ControlStyles.UserPaint)) + { // Base class returns hollow brush when UserPaint style is set, to avoid flicker in // main control. But when returning colors for child dropdown list, return normal ForeColor/BackColor, // since hollow brush leaves the list background unpainted. @@ -2003,40 +2310,50 @@ internal override IntPtr InitializeDCForWmCtlColor(IntPtr dc, int msg) { SafeNativeMethods.SetBkColor(new HandleRef(null, dc), ColorTranslator.ToWin32(BackColor)); return BackColorBrush; } - else { + else + { return base.InitializeDCForWmCtlColor(dc, msg); } } // Returns true when the key processing needs to be intercepted to allow // auto-completion in DropDownList style. - private bool InterceptAutoCompleteKeystroke(Message m) { - if (m.Msg == Interop.WindowMessages.WM_KEYDOWN) { + private bool InterceptAutoCompleteKeystroke(Message m) + { + if (m.Msg == Interop.WindowMessages.WM_KEYDOWN) + { Debug.Assert((ModifierKeys & Keys.Alt) == 0); // Keys.Delete only triggers a WM_KEYDOWN and WM_KEYUP, and no WM_CHAR. That's why it's treated separately. - if ((Keys)unchecked( (int) (long)m.WParam) == Keys.Delete) { + if ((Keys)unchecked((int)(long)m.WParam) == Keys.Delete) + { // Reset matching text and remove any selection this.MatchingText = string.Empty; this.autoCompleteTimeStamp = DateTime.Now.Ticks; - if (this.Items.Count > 0) { + if (this.Items.Count > 0) + { SelectedIndex = 0; } return false; } } - else if (m.Msg == Interop.WindowMessages.WM_CHAR) { + else if (m.Msg == Interop.WindowMessages.WM_CHAR) + { Debug.Assert((ModifierKeys & Keys.Alt) == 0); char keyChar = unchecked((char)(long)m.WParam); - if (keyChar == (char)Keys.Back) { + if (keyChar == (char)Keys.Back) + { if (DateTime.Now.Ticks - this.autoCompleteTimeStamp > AutoCompleteTimeout || - this.MatchingText.Length <= 1) { + this.MatchingText.Length <= 1) + { // Reset matching text and remove any selection this.MatchingText = string.Empty; - if (this.Items.Count > 0) { + if (this.Items.Count > 0) + { SelectedIndex = 0; } } - else { + else + { // Remove one character from matching text and rematch this.MatchingText = this.MatchingText.Remove(this.MatchingText.Length - 1); this.SelectedIndex = FindString(this.MatchingText); @@ -2044,30 +2361,37 @@ private bool InterceptAutoCompleteKeystroke(Message m) { this.autoCompleteTimeStamp = DateTime.Now.Ticks; return false; } - else if (keyChar == (char)Keys.Escape) { + else if (keyChar == (char)Keys.Escape) + { this.MatchingText = string.Empty; } string newMatchingText; if (keyChar != (char)Keys.Escape && keyChar != (char)Keys.Return && !DroppedDown - && AutoCompleteMode != AutoCompleteMode.Append) { + && AutoCompleteMode != AutoCompleteMode.Append) + { DroppedDown = true; } - if (DateTime.Now.Ticks - this.autoCompleteTimeStamp > AutoCompleteTimeout) { + if (DateTime.Now.Ticks - this.autoCompleteTimeStamp > AutoCompleteTimeout) + { newMatchingText = new string(keyChar, 1); - if (FindString(newMatchingText) != -1) { + if (FindString(newMatchingText) != -1) + { this.MatchingText = newMatchingText; // Select the found item } this.autoCompleteTimeStamp = DateTime.Now.Ticks; return false; } - else { + else + { newMatchingText = this.MatchingText + keyChar; int itemFound = FindString(newMatchingText); - if (itemFound != -1) { + if (itemFound != -1) + { this.MatchingText = newMatchingText; - if (itemFound != this.SelectedIndex) { + if (itemFound != this.SelectedIndex) + { this.SelectedIndex = itemFound; } } @@ -2080,7 +2404,8 @@ private bool InterceptAutoCompleteKeystroke(Message m) { } // Invalidate the entire control, including child HWNDs and non-client areas - private void InvalidateEverything() { + private void InvalidateEverything() + { SafeNativeMethods.RedrawWindow(new HandleRef(this, Handle), null, NativeMethods.NullHandleRef, NativeMethods.RDW_INVALIDATE | @@ -2094,15 +2419,19 @@ private void InvalidateEverything() { /// Overridden to return true for RETURN and ESCAPE when the combo box is /// dropped down. /// - protected override bool IsInputKey(Keys keyData) { + protected override bool IsInputKey(Keys keyData) + { Keys keyCode = keyData & (Keys.KeyCode | Keys.Alt); - if (keyCode == Keys.Return || keyCode == Keys.Escape) { - if (this.DroppedDown || autoCompleteDroppedDown) { + if (keyCode == Keys.Return || keyCode == Keys.Escape) + { + if (this.DroppedDown || autoCompleteDroppedDown) + { //old behavior return true; } - else if (SystemAutoCompleteEnabled && ACNativeWindow.AutoCompleteActive) { + else if (SystemAutoCompleteEnabled && ACNativeWindow.AutoCompleteActive) + { autoCompleteDroppedDown = true; return true; } @@ -2115,10 +2444,12 @@ protected override bool IsInputKey(Keys keyData) { /// Adds the given item to the native combo box. This asserts if the handle hasn't been /// created. /// - private int NativeAdd(object item) { + private int NativeAdd(object item) + { Debug.Assert(IsHandleCreated, "Shouldn't be calling Native methods before the handle is created."); - int insertIndex = unchecked( (int) (long)SendMessage(NativeMethods.CB_ADDSTRING, 0, GetItemText(item))); - if (insertIndex < 0) { + int insertIndex = unchecked((int)(long)SendMessage(NativeMethods.CB_ADDSTRING, 0, GetItemText(item))); + if (insertIndex < 0) + { throw new OutOfMemoryException(SR.ComboBoxItemOverflow); } return insertIndex; @@ -2127,14 +2458,17 @@ private int NativeAdd(object item) { /// /// Clears the contents of the combo box. /// - private void NativeClear() { + private void NativeClear() + { Debug.Assert(IsHandleCreated, "Shouldn't be calling Native methods before the handle is created."); string saved = null; - if (DropDownStyle != ComboBoxStyle.DropDownList) { + if (DropDownStyle != ComboBoxStyle.DropDownList) + { saved = WindowText; } SendMessage(NativeMethods.CB_RESETCONTENT, 0, 0); - if (saved != null) { + if (saved != null) + { WindowText = saved; } } @@ -2142,8 +2476,9 @@ private void NativeClear() { /// /// Get the text stored by the native control for the specified list item. /// - private string NativeGetItemText(int index) { - int len = unchecked( (int) (long)SendMessage(NativeMethods.CB_GETLBTEXTLEN, index, 0)); + private string NativeGetItemText(int index) + { + int len = unchecked((int)(long)SendMessage(NativeMethods.CB_GETLBTEXTLEN, index, 0)); StringBuilder sb = new StringBuilder(len + 1); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.CB_GETLBTEXT, index, sb); return sb.ToString(); @@ -2153,10 +2488,12 @@ private string NativeGetItemText(int index) { /// Inserts the given item to the native combo box at the index. This asserts if the handle hasn't been /// created or if the resulting insert index doesn't match the passed in index. /// - private int NativeInsert(int index, object item) { + private int NativeInsert(int index, object item) + { Debug.Assert(IsHandleCreated, "Shouldn't be calling Native methods before the handle is created."); - int insertIndex = unchecked( (int) (long)SendMessage(NativeMethods.CB_INSERTSTRING, index, GetItemText(item))); - if (insertIndex < 0) { + int insertIndex = unchecked((int)(long)SendMessage(NativeMethods.CB_INSERTSTRING, index, GetItemText(item))); + if (insertIndex < 0) + { throw new OutOfMemoryException(SR.ComboBoxItemOverflow); } Debug.Assert(insertIndex == index, "NativeComboBox inserted at " + insertIndex + " not the requested index of " + index); @@ -2166,7 +2503,8 @@ private int NativeInsert(int index, object item) { /// /// Removes the native item from the given index. /// - private void NativeRemoveAt(int index) { + private void NativeRemoveAt(int index) + { Debug.Assert(IsHandleCreated, "Shouldn't be calling Native methods before the handle is created."); // Windows combo does not invalidate the selected region if you remove the @@ -2174,18 +2512,21 @@ private void NativeRemoveAt(int index) { // invalidate will lazy-paint we can actually invalidate before we send the // delete message. // - if (DropDownStyle == ComboBoxStyle.DropDownList && SelectedIndex == index) { + if (DropDownStyle == ComboBoxStyle.DropDownList && SelectedIndex == index) + { Invalidate(); } SendMessage(NativeMethods.CB_DELETESTRING, index, 0); } - internal override void RecreateHandleCore() { - + internal override void RecreateHandleCore() + { + string oldText = WindowText; base.RecreateHandleCore(); - if (!string.IsNullOrEmpty(oldText) && string.IsNullOrEmpty(WindowText)) { + if (!string.IsNullOrEmpty(oldText) && string.IsNullOrEmpty(WindowText)) + { WindowText = oldText; //restore the window text } } @@ -2206,11 +2547,13 @@ protected override void CreateHandle() /// Inheriting classes should not forget to call /// base.OnHandleCreated() /// - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { base.OnHandleCreated(e); - if (MaxLength > 0) { + if (MaxLength > 0) + { SendMessage(NativeMethods.CB_LIMITTEXT, MaxLength, 0); } @@ -2221,13 +2564,16 @@ protected override void OnHandleCreated(EventArgs e) { bool ok = childEdit == null && childListBox == null; - if (ok && DropDownStyle != ComboBoxStyle.DropDownList) { + if (ok && DropDownStyle != ComboBoxStyle.DropDownList) + { IntPtr hwnd = UnsafeNativeMethods.GetWindow(new HandleRef(this, Handle), NativeMethods.GW_CHILD); - if (hwnd != IntPtr.Zero) { + if (hwnd != IntPtr.Zero) + { // if it's a simple dropdown list, the first HWND is the list box. // - if (DropDownStyle == ComboBoxStyle.Simple) { + if (DropDownStyle == ComboBoxStyle.Simple) + { childListBox = new ComboBoxChildNativeWindow(this, ChildWindowType.ListBox); childListBox.AssignHandle(hwnd); @@ -2248,20 +2594,23 @@ protected override void OnHandleCreated(EventArgs e) { bool found; int dropDownWidth = Properties.GetInteger(PropDropDownWidth, out found); - if (found) { + if (found) + { SendMessage(NativeMethods.CB_SETDROPPEDWIDTH, dropDownWidth, 0); } found = false; int itemHeight = Properties.GetInteger(PropItemHeight, out found); - if (found) { + if (found) + { // someone has set the item height - update it UpdateItemHeight(); } // Resize a simple style combobox on handle creation // to respect the requested height. // - if (DropDownStyle == ComboBoxStyle.Simple) { + if (DropDownStyle == ComboBoxStyle.Simple) + { Height = requestedHeight; } @@ -2278,14 +2627,17 @@ protected override void OnHandleCreated(EventArgs e) { } - if (itemsCollection != null) { - foreach (object item in itemsCollection) { + if (itemsCollection != null) + { + foreach (object item in itemsCollection) + { NativeAdd(item); } // Now udpate the current selection. // - if (selectedIndex >= 0) { + if (selectedIndex >= 0) + { SendMessage(NativeMethods.CB_SETCURSEL, selectedIndex, 0); UpdateText(); selectedIndex = -1; @@ -2299,13 +2651,16 @@ protected override void OnHandleCreated(EventArgs e) { /// We need to un-subclasses everything here. Inheriting classes should /// not forget to call base.OnHandleDestroyed() /// - protected override void OnHandleDestroyed(EventArgs e) { + protected override void OnHandleDestroyed(EventArgs e) + { dropDownHandle = IntPtr.Zero; - if (Disposing) { + if (Disposing) + { itemsCollection = null; selectedIndex = -1; } - else { + else + { selectedIndex = SelectedIndex; } if (stringSource != null) @@ -2321,9 +2676,11 @@ protected override void OnHandleDestroyed(EventArgs e) { /// forget to call base.onDrawItem() to ensure that drawItem events /// are correctly fired at all other times. /// - protected virtual void OnDrawItem(DrawItemEventArgs e) { + protected virtual void OnDrawItem(DrawItemEventArgs e) + { DrawItemEventHandler handler = (DrawItemEventHandler)Events[EVENT_DRAWITEM]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// @@ -2331,9 +2688,11 @@ protected virtual void OnDrawItem(DrawItemEventArgs e) { /// forget to call base.onDropDown() to ensure that dropDown events /// are correctly fired at all other times. /// - protected virtual void OnDropDown(EventArgs e) { + protected virtual void OnDropDown(EventArgs e) + { EventHandler handler = (EventHandler)Events[EVENT_DROPDOWN]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); // Notify collapsed/expanded property change. AccessibilityObject.RaiseAutomationPropertyChangedEvent( @@ -2342,7 +2701,8 @@ protected virtual void OnDropDown(EventArgs e) { UnsafeNativeMethods.ExpandCollapseState.Expanded); var accessibleObject = AccessibilityObject as ComboBoxAccessibleObject; - if (accessibleObject != null) { + if (accessibleObject != null) + { accessibleObject.SetComboBoxItemFocus(); } } @@ -2351,14 +2711,18 @@ protected virtual void OnDropDown(EventArgs e) { /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnKeyDown(KeyEventArgs e) { + protected override void OnKeyDown(KeyEventArgs e) + { // Do Return/ESC handling - if (SystemAutoCompleteEnabled) { - if (e.KeyCode == Keys.Return) { + if (SystemAutoCompleteEnabled) + { + if (e.KeyCode == Keys.Return) + { // Set SelectedIndex NotifyAutoComplete(true); } - else if ((e.KeyCode == Keys.Escape) && autoCompleteDroppedDown) { + else if ((e.KeyCode == Keys.Escape) && autoCompleteDroppedDown) + { // Fire TextChanged Only NotifyAutoComplete(false); } @@ -2373,21 +2737,25 @@ protected override void OnKeyDown(KeyEventArgs e) { /// Key press event handler. Overridden to close up the combo box when the /// user presses RETURN or ESCAPE. /// - protected override void OnKeyPress(KeyPressEventArgs e) { + protected override void OnKeyPress(KeyPressEventArgs e) + { base.OnKeyPress(e); //return when dropped down already fires commit. if (!e.Handled && (e.KeyChar == (char)(int)Keys.Return || e.KeyChar == (char)(int)Keys.Escape) - && DroppedDown) { + && DroppedDown) + { dropDown = false; - if (FormattingEnabled) { + if (FormattingEnabled) + { //Set the Text which would Compare the WindowText with the TEXT and change SelectedIndex. Text = WindowText; SelectAll(); e.Handled = false; } - else { + else + { DroppedDown = false; e.Handled = true; } @@ -2399,22 +2767,26 @@ protected override void OnKeyPress(KeyPressEventArgs e) { /// forget to call base.onMeasureItem() to ensure that measureItem /// events are correctly fired at all other times. /// - protected virtual void OnMeasureItem(MeasureItemEventArgs e) { + protected virtual void OnMeasureItem(MeasureItemEventArgs e) + { MeasureItemEventHandler handler = (MeasureItemEventHandler)Events[EVENT_MEASUREITEM]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// If we have the style set to popup show mouse over /// - protected override void OnMouseEnter(EventArgs e) { + protected override void OnMouseEnter(EventArgs e) + { base.OnMouseEnter(e); MouseIsOver = true; } /// /// If we have the style set to popup show mouse over /// - protected override void OnMouseLeave(EventArgs e) { + protected override void OnMouseLeave(EventArgs e) + { base.OnMouseLeave(e); MouseIsOver = false; } @@ -2422,15 +2794,19 @@ protected override void OnMouseLeave(EventArgs e) { /// /// This internal helper allows us to call the committed function multiple times without worrying about double firing. /// - private void OnSelectionChangeCommittedInternal(EventArgs e) { + private void OnSelectionChangeCommittedInternal(EventArgs e) + { //There are cases where if we disable the combo while in this event handler, it sends the message again. //This is a recursion gaurd to ensure we only send one commit per user action. - if (allowCommit) { - try { + if (allowCommit) + { + try + { allowCommit = false; OnSelectionChangeCommitted(e); } - finally { + finally + { allowCommit = true; } } @@ -2441,14 +2817,17 @@ private void OnSelectionChangeCommittedInternal(EventArgs e) { /// Don't forget to call base.OnSelectionChangeCommitted() to ensure /// that SelectionChangeCommitted events are correctly fired at all other times. /// - protected virtual void OnSelectionChangeCommitted(EventArgs e) { + protected virtual void OnSelectionChangeCommitted(EventArgs e) + { EventHandler handler = (EventHandler)Events[EVENT_SELECTIONCHANGECOMMITTED]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); // The user selects a list item or selects an item and then closes the list. // It indicates that the user's selection is to be processed but should not // be focused after closing the list. - if (dropDown) { + if (dropDown) + { dropDownWillBeClosed = true; } } @@ -2458,25 +2837,32 @@ protected virtual void OnSelectionChangeCommitted(EventArgs e) { /// Don't forget to call base.onSelectedIndexChanged() to ensure /// that selectedIndexChanged events are correctly fired at all other times. /// - protected override void OnSelectedIndexChanged(EventArgs e) { + protected override void OnSelectedIndexChanged(EventArgs e) + { base.OnSelectedIndexChanged(e); EventHandler handler = (EventHandler)Events[EVENT_SELECTEDINDEXCHANGED]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); - if (dropDownWillBeClosed) { + if (dropDownWillBeClosed) + { // This is after-closing selection - do not focus on the list item // and reset the state to announce the selections later. dropDownWillBeClosed = false; } - else { + else + { var accessibleObject = AccessibilityObject as ComboBoxAccessibleObject; - if (accessibleObject != null) { + if (accessibleObject != null) + { // Announce DropDown- and DropDownList-styled ComboBox item selection using keyboard // in case when Level 3 is enabled and DropDown is not in expanded state. Simple-styled // ComboBox selection is announced by TextProvider. - if (DropDownStyle == ComboBoxStyle.DropDownList || DropDownStyle == ComboBoxStyle.DropDown) { - if (dropDown) { + if (DropDownStyle == ComboBoxStyle.DropDownList || DropDownStyle == ComboBoxStyle.DropDown) + { + if (dropDown) + { accessibleObject.SetComboBoxItemFocus(); } @@ -2492,15 +2878,18 @@ protected override void OnSelectedIndexChanged(EventArgs e) { // into the backEnd. We do not need to do that. // // don't change the position if SelectedIndex is -1 because this indicates a selection not from the list. - if (this.DataManager != null && DataManager.Position != SelectedIndex) { + if (this.DataManager != null && DataManager.Position != SelectedIndex) + { //read this as "if everett or (whidbey and selindex is valid)" - if (!FormattingEnabled || SelectedIndex != -1) { + if (!FormattingEnabled || SelectedIndex != -1) + { this.DataManager.Position = this.SelectedIndex; } } } - protected override void OnSelectedValueChanged(EventArgs e) { + protected override void OnSelectedValueChanged(EventArgs e) + { base.OnSelectedValueChanged(e); selectedValueChangedFired = true; } @@ -2510,17 +2899,21 @@ protected override void OnSelectedValueChanged(EventArgs e) { /// Don't forget to call base.onSelectedItemChanged() to ensure /// that selectedItemChanged events are correctly fired at all other times. /// - protected virtual void OnSelectedItemChanged(EventArgs e) { + protected virtual void OnSelectedItemChanged(EventArgs e) + { EventHandler handler = (EventHandler)Events[EVENT_SELECTEDITEMCHANGED]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// This is the code that actually fires the DropDownStyleChanged event. /// - protected virtual void OnDropDownStyleChanged(EventArgs e) { + protected virtual void OnDropDownStyleChanged(EventArgs e) + { EventHandler handler = (EventHandler)Events[EVENT_DROPDOWNSTYLE]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// @@ -2528,23 +2921,28 @@ protected virtual void OnDropDownStyleChanged(EventArgs e) { /// changes on the parent. This can be overriden by inheriting /// classes, however they must call base.OnParentPropertyChanged. /// - protected override void OnParentBackColorChanged(EventArgs e) { + protected override void OnParentBackColorChanged(EventArgs e) + { base.OnParentBackColorChanged(e); - if (DropDownStyle == ComboBoxStyle.Simple) Invalidate(); + if (DropDownStyle == ComboBoxStyle.Simple) + Invalidate(); } /// /// Indicates that a critical property, such as color or font has /// changed. /// - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { base.OnFontChanged(e); ResetHeightCache(); - if (this.AutoCompleteMode == AutoCompleteMode.None) { + if (this.AutoCompleteMode == AutoCompleteMode.None) + { UpdateControl(true); } - else { + else + { //we always will recreate the handle when autocomplete mode is on RecreateHandle(); } @@ -2552,9 +2950,10 @@ protected override void OnFontChanged(EventArgs e) { } - private void OnAutoCompleteCustomSourceChanged(object sender, CollectionChangeEventArgs e) { + private void OnAutoCompleteCustomSourceChanged(object sender, CollectionChangeEventArgs e) + { if (AutoCompleteSource == AutoCompleteSource.CustomSource) - { + { if (AutoCompleteCustomSource.Count == 0) { SetAutoComplete(true, true /*recreate handle*/); @@ -2563,7 +2962,7 @@ private void OnAutoCompleteCustomSourceChanged(object sender, CollectionChangeEv { SetAutoComplete(true, false); } - + } } @@ -2571,7 +2970,8 @@ private void OnAutoCompleteCustomSourceChanged(object sender, CollectionChangeEv /// Indicates that a critical property, such as color or font has /// changed. /// - protected override void OnBackColorChanged(EventArgs e) { + protected override void OnBackColorChanged(EventArgs e) + { base.OnBackColorChanged(e); UpdateControl(false); } @@ -2580,25 +2980,31 @@ protected override void OnBackColorChanged(EventArgs e) { /// Indicates that a critical property, such as color or font has /// changed. /// - protected override void OnForeColorChanged(EventArgs e) { + protected override void OnForeColorChanged(EventArgs e) + { base.OnForeColorChanged(e); UpdateControl(false); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnGotFocus(EventArgs e) { - if (!canFireLostFocus) { + protected override void OnGotFocus(EventArgs e) + { + if (!canFireLostFocus) + { base.OnGotFocus(e); canFireLostFocus = true; } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnLostFocus(EventArgs e) { - if (canFireLostFocus) { + protected override void OnLostFocus(EventArgs e) + { + if (canFireLostFocus) + { if (this.AutoCompleteMode != AutoCompleteMode.None && this.AutoCompleteSource == AutoCompleteSource.ListItems && - this.DropDownStyle == ComboBoxStyle.DropDownList) { + this.DropDownStyle == ComboBoxStyle.DropDownList) + { this.MatchingText = string.Empty; } base.OnLostFocus(e); @@ -2607,12 +3013,15 @@ protected override void OnLostFocus(EventArgs e) { } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnTextChanged(EventArgs e) { - if (SystemAutoCompleteEnabled) { + protected override void OnTextChanged(EventArgs e) + { + if (SystemAutoCompleteEnabled) + { string text = this.Text; // Prevent multiple TextChanges... - if (text != this.lastTextChangedValue) { + if (text != this.lastTextChangedValue) + { // Need to still fire a TextChanged base.OnTextChanged(e); @@ -2620,7 +3029,8 @@ protected override void OnTextChanged(EventArgs e) { this.lastTextChangedValue = text; } } - else { + else + { // Call the base base.OnTextChanged(e); } @@ -2631,8 +3041,10 @@ protected override void OnTextChanged(EventArgs e) { /// event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnValidating(CancelEventArgs e) { - if (SystemAutoCompleteEnabled) { + protected override void OnValidating(CancelEventArgs e) + { + if (SystemAutoCompleteEnabled) + { // Handle AutoComplete notification NotifyAutoComplete(); } @@ -2642,16 +3054,20 @@ protected override void OnValidating(CancelEventArgs e) { } - private void UpdateControl(bool recreate) { + private void UpdateControl(bool recreate) + { //clear the pref height cache ResetHeightCache(); - if (IsHandleCreated) { - if (DropDownStyle == ComboBoxStyle.Simple && recreate) { + if (IsHandleCreated) + { + if (DropDownStyle == ComboBoxStyle.Simple && recreate) + { // Control forgets to add a scrollbar. RecreateHandle(); } - else { + else + { UpdateItemHeight(); // Force everything to repaint. InvalidateEverything(); @@ -2662,24 +3078,30 @@ private void UpdateControl(bool recreate) { /// /// Raises the event. /// - protected override void OnResize(EventArgs e) { + protected override void OnResize(EventArgs e) + { base.OnResize(e); - if (DropDownStyle == ComboBoxStyle.Simple) { + if (DropDownStyle == ComboBoxStyle.Simple) + { // simple style combo boxes have more painting problems than you can shake a stick at InvalidateEverything(); } } - protected override void OnDataSourceChanged(EventArgs e) { - if (Sorted) { - if (DataSource != null && Created) { + protected override void OnDataSourceChanged(EventArgs e) + { + if (Sorted) + { + if (DataSource != null && Created) + { // we will only throw the exception when the control is already on the form. Debug.Assert(DisplayMember.Equals(string.Empty), "if this list is sorted it means that dataSource was null when Sorted first became true. at that point DisplayMember had to be String.Empty"); DataSource = null; throw new InvalidOperationException(SR.ComboBoxDataSourceWithSort); } } - if (DataSource == null) { + if (DataSource == null) + { BeginUpdate(); SelectedIndex = -1; Items.ClearInternal(); @@ -2690,7 +3112,8 @@ protected override void OnDataSourceChanged(EventArgs e) { RefreshItems(); } - protected override void OnDisplayMemberChanged(EventArgs e) { + protected override void OnDisplayMemberChanged(EventArgs e) + { base.OnDisplayMemberChanged(e); // @@ -2702,14 +3125,17 @@ protected override void OnDisplayMemberChanged(EventArgs e) { /// /// This event is fired when the dropdown portion of the combobox is hidden. /// - protected virtual void OnDropDownClosed(EventArgs e) { + protected virtual void OnDropDownClosed(EventArgs e) + { EventHandler handler = (EventHandler)Events[EVENT_DROPDOWNCLOSED]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); // Need to announce the focus on combo-box with new selected value on drop-down close. // If do not do this focus in Level 3 stays on list item of unvisible list. // This is necessary for DropDown style as edit should not take focus. - if (DropDownStyle == ComboBoxStyle.DropDown) { + if (DropDownStyle == ComboBoxStyle.DropDown) + { AccessibilityObject.RaiseAutomationEvent(NativeMethods.UIA_AutomationFocusChangedEventId); } @@ -2728,9 +3154,11 @@ protected virtual void OnDropDownClosed(EventArgs e) { /// This event is fired when the edit portion of a combobox is about to display altered text. /// This event is NOT fired if the TEXT property is programatically changed. /// - protected virtual void OnTextUpdate(EventArgs e) { + protected virtual void OnTextUpdate(EventArgs e) + { EventHandler handler = (EventHandler)Events[EVENT_TEXTUPDATE]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } protected override bool ProcessCmdKey(ref Message msg, Keys keyData) @@ -2764,21 +3192,25 @@ protected override bool ProcessKeyEventArgs(ref Message m) { if (this.AutoCompleteMode != AutoCompleteMode.None && this.AutoCompleteSource == AutoCompleteSource.ListItems && this.DropDownStyle == ComboBoxStyle.DropDownList && - InterceptAutoCompleteKeystroke(m)) { + InterceptAutoCompleteKeystroke(m)) + { return true; } - else { + else + { return base.ProcessKeyEventArgs(ref m); } } - private void ResetHeightCache() { + private void ResetHeightCache() + { prefHeightCache = -1; } /// /// Reparses the objects, getting new text strings for them. /// - protected override void RefreshItems() { + protected override void RefreshItems() + { // Save off the selection and the current collection. // @@ -2793,13 +3225,16 @@ protected override void RefreshItems() { // if we have a dataSource and a DisplayMember, then use it // to populate the Items collection // - if (this.DataManager != null && this.DataManager.Count != -1) { + if (this.DataManager != null && this.DataManager.Count != -1) + { newItems = new object[this.DataManager.Count]; - for (int i = 0; i < newItems.Length; i++) { + for (int i = 0; i < newItems.Length; i++) + { newItems[i] = this.DataManager[i]; } } - else if (savedItems != null) { + else if (savedItems != null) + { newItems = new object[savedItems.Count]; savedItems.CopyTo(newItems, 0); } @@ -2837,7 +3272,8 @@ protected override void RefreshItems() { /// /// Reparses the object at the given index, getting new text string for it. /// - protected override void RefreshItem(int index) { + protected override void RefreshItem(int index) + { Items.SetItemInternal(index, Items[index]); } @@ -2845,16 +3281,19 @@ protected override void RefreshItem(int index) { /// Release the ChildWindow object by un-subclassing the child edit and /// list controls and freeing the root of the ChildWindow object. /// - private void ReleaseChildWindow() { + private void ReleaseChildWindow() + { - if (childEdit != null) { + if (childEdit != null) + { // We do not use UI Automation provider for child edit, so do not need to release providers. childEdit.ReleaseHandle(); childEdit = null; } - if (childListBox != null) { + if (childListBox != null) + { // Need to notify UI Automation that it can safely remove all map entries that refer to the specified window. ReleaseUiaProvider(childListBox.Handle); @@ -2863,7 +3302,8 @@ private void ReleaseChildWindow() { childListBox = null; } - if (childDropDown != null) { + if (childDropDown != null) + { // Need to notify UI Automation that it can safely remove all map entries that refer to the specified window. ReleaseUiaProvider(childDropDown.Handle); @@ -2873,26 +3313,31 @@ private void ReleaseChildWindow() { } } - internal override void ReleaseUiaProvider(IntPtr handle) { + internal override void ReleaseUiaProvider(IntPtr handle) + { base.ReleaseUiaProvider(handle); var uiaProvider = AccessibilityObject as ComboBoxAccessibleObject; uiaProvider?.ResetListItemAccessibleObjects(); } - private void ResetAutoCompleteCustomSource() { + private void ResetAutoCompleteCustomSource() + { AutoCompleteCustomSource = null; } - private void ResetDropDownWidth() { + private void ResetDropDownWidth() + { Properties.RemoveInteger(PropDropDownWidth); } - private void ResetItemHeight() { + private void ResetItemHeight() + { Properties.RemoveInteger(PropItemHeight); } - public override void ResetText() { + public override void ResetText() + { base.ResetText(); } @@ -2900,13 +3345,16 @@ public override void ResetText() { /// Enables the AutoComplete feature for combobox depending on the properties set. /// These properties are namely AutoCompleteMode, AutoCompleteSource and AutoCompleteCustomSource. /// - [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] - private void SetAutoComplete(bool reset, bool recreate) { - if (!IsHandleCreated || childEdit == null) { + [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] + private void SetAutoComplete(bool reset, bool recreate) + { + if (!IsHandleCreated || childEdit == null) + { return; } - if (AutoCompleteMode != AutoCompleteMode.None) { + if (AutoCompleteMode != AutoCompleteMode.None) + { if (!fromHandleCreate && recreate && IsHandleCreated) { //RecreateHandle to avoid Leak. @@ -2916,19 +3364,24 @@ private void SetAutoComplete(bool reset, bool recreate) { RecreateHandle(); autoCompleteMode = backUpMode; } - - if (AutoCompleteSource == AutoCompleteSource.CustomSource) { - if (AutoCompleteCustomSource != null) { - if (AutoCompleteCustomSource.Count == 0) { + + if (AutoCompleteSource == AutoCompleteSource.CustomSource) + { + if (AutoCompleteCustomSource != null) + { + if (AutoCompleteCustomSource.Count == 0) + { int mode = NativeMethods.AUTOSUGGEST_OFF | NativeMethods.AUTOAPPEND_OFF; SafeNativeMethods.SHAutoComplete(new HandleRef(this, childEdit.Handle), mode); } - else { + else + { if (stringSource == null) { stringSource = new StringSource(GetStringsForAutoComplete(AutoCompleteCustomSource)); - if (!stringSource.Bind(new HandleRef(this, childEdit.Handle), (int)AutoCompleteMode)) { + if (!stringSource.Bind(new HandleRef(this, childEdit.Handle), (int)AutoCompleteMode)) + { throw new ArgumentException(SR.AutoCompleteFailure); } } @@ -2936,23 +3389,29 @@ private void SetAutoComplete(bool reset, bool recreate) { { stringSource.RefreshList(GetStringsForAutoComplete(AutoCompleteCustomSource)); } - + } } } - else if (AutoCompleteSource == AutoCompleteSource.ListItems) { - if (DropDownStyle != ComboBoxStyle.DropDownList) { - if (itemsCollection != null) { - if (itemsCollection.Count == 0) { + else if (AutoCompleteSource == AutoCompleteSource.ListItems) + { + if (DropDownStyle != ComboBoxStyle.DropDownList) + { + if (itemsCollection != null) + { + if (itemsCollection.Count == 0) + { int mode = NativeMethods.AUTOSUGGEST_OFF | NativeMethods.AUTOAPPEND_OFF; SafeNativeMethods.SHAutoComplete(new HandleRef(this, childEdit.Handle), mode); } - else { + else + { if (stringSource == null) { stringSource = new StringSource(GetStringsForAutoComplete(Items)); - if (!stringSource.Bind(new HandleRef(this, childEdit.Handle), (int)AutoCompleteMode)) { + if (!stringSource.Bind(new HandleRef(this, childEdit.Handle), (int)AutoCompleteMode)) + { throw new ArgumentException(SR.AutoCompleteFailureListItems); } } @@ -2960,34 +3419,40 @@ private void SetAutoComplete(bool reset, bool recreate) { { stringSource.RefreshList(GetStringsForAutoComplete(Items)); } - + } } } - else { + else + { // Drop Down List special handling Debug.Assert(DropDownStyle == ComboBoxStyle.DropDownList); int mode = NativeMethods.AUTOSUGGEST_OFF | NativeMethods.AUTOAPPEND_OFF; SafeNativeMethods.SHAutoComplete(new HandleRef(this, childEdit.Handle), mode); } } - else { + else + { int mode = 0; - if (AutoCompleteMode == AutoCompleteMode.Suggest) { + if (AutoCompleteMode == AutoCompleteMode.Suggest) + { mode |= NativeMethods.AUTOSUGGEST | NativeMethods.AUTOAPPEND_OFF; } - if (AutoCompleteMode == AutoCompleteMode.Append) { + if (AutoCompleteMode == AutoCompleteMode.Append) + { mode |= NativeMethods.AUTOAPPEND | NativeMethods.AUTOSUGGEST_OFF; } - if (AutoCompleteMode == AutoCompleteMode.SuggestAppend) { + if (AutoCompleteMode == AutoCompleteMode.SuggestAppend) + { mode |= NativeMethods.AUTOSUGGEST; mode |= NativeMethods.AUTOAPPEND; } int ret = SafeNativeMethods.SHAutoComplete(new HandleRef(this, childEdit.Handle), (int)AutoCompleteSource | mode); } } - else if (reset) { + else if (reset) + { int mode = NativeMethods.AUTOSUGGEST_OFF | NativeMethods.AUTOAPPEND_OFF; SafeNativeMethods.SHAutoComplete(new HandleRef(this, childEdit.Handle), mode); } @@ -2997,15 +3462,18 @@ private void SetAutoComplete(bool reset, bool recreate) { /// Selects the text in the editable portion of the ComboBox at the /// from the given start index to the given end index. /// - public void Select(int start, int length) { - if (start < 0) { + public void Select(int start, int length) + { + if (start < 0) + { throw new ArgumentOutOfRangeException(nameof(start), start, string.Format(SR.InvalidArgument, nameof(start), start)); } // the Length can be negative to support Selecting in the "reverse" direction.. int end = start + length; // but end cannot be negative... this means Length is far negative... - if (end < 0) { + if (end < 0) + { throw new ArgumentOutOfRangeException(nameof(length), length, string.Format(SR.InvalidArgument, nameof(length), length)); } @@ -3015,15 +3483,18 @@ public void Select(int start, int length) { /// /// Selects all the text in the editable portion of the ComboBox. /// - public void SelectAll() { + public void SelectAll() + { Select(0, int.MaxValue); } - protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { + protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) + { // If we are changing height, store the requested height. // Requested height is used if the style is changed to simple. // ( - if ((specified & BoundsSpecified.Height) != BoundsSpecified.None) { + if ((specified & BoundsSpecified.Height) != BoundsSpecified.None) + { requestedHeight = height; } @@ -3033,7 +3504,8 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound /// /// Performs the work of setting the specified items to the combobox /// - protected override void SetItemsCore(IList value) { + protected override void SetItemsCore(IList value) + { BeginUpdate(); Items.ClearInternal(); Items.AddRangeInternal(value); @@ -3041,21 +3513,26 @@ protected override void SetItemsCore(IList value) { // if the list changed, we want to keep the same selected index // CurrencyManager will provide the PositionChanged event // it will be provided before changing the list though... - if (this.DataManager != null) { - if (this.DataSource is ICurrencyManagerProvider) { + if (this.DataManager != null) + { + if (this.DataSource is ICurrencyManagerProvider) + { this.selectedValueChangedFired = false; } - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(NativeMethods.CB_SETCURSEL, DataManager.Position, 0); } - else { - selectedIndex = DataManager.Position; + else + { + selectedIndex = DataManager.Position; } // if set_SelectedIndexChanged did not fire OnSelectedValueChanged // then we have to fire it ourselves, cos the list changed anyway - if (!selectedValueChangedFired) { + if (!selectedValueChangedFired) + { OnSelectedValueChanged(EventArgs.Empty); selectedValueChangedFired = false; } @@ -3064,36 +3541,42 @@ protected override void SetItemsCore(IList value) { EndUpdate(); } - protected override void SetItemCore(int index, object value) { + protected override void SetItemCore(int index, object value) + { Items.SetItemInternal(index, value); } - private bool ShouldSerializeAutoCompleteCustomSource() { + private bool ShouldSerializeAutoCompleteCustomSource() + { return autoCompleteCustomSource != null && autoCompleteCustomSource.Count > 0; } - internal bool ShouldSerializeDropDownWidth() { + internal bool ShouldSerializeDropDownWidth() + { return (Properties.ContainsInteger(PropDropDownWidth)); } /// /// Indicates whether the itemHeight property should be persisted. /// - internal bool ShouldSerializeItemHeight() { + internal bool ShouldSerializeItemHeight() + { return (Properties.ContainsInteger(PropItemHeight)); } /// /// Determines if the Text property needs to be persisted. /// - internal override bool ShouldSerializeText() { + internal override bool ShouldSerializeText() + { return SelectedIndex == -1 && base.ShouldSerializeText(); } /// /// Provides some interesting info about this control in String form. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); return s + ", Items.Count: " + ((itemsCollection == null) ? "0" : itemsCollection.Count.ToString(CultureInfo.CurrentCulture)); @@ -3101,11 +3584,14 @@ public override string ToString() { /// /// - private void UpdateDropDownHeight() { - if (dropDownHandle != IntPtr.Zero) { + private void UpdateDropDownHeight() + { + if (dropDownHandle != IntPtr.Zero) + { //Now use the DropDownHeight property instead of calculating the Height... int height = DropDownHeight; - if (height == DefaultDropDownHeight) { + if (height == DefaultDropDownHeight) + { int itemCount = (itemsCollection == null) ? 0 : itemsCollection.Count; int count = Math.Min(Math.Max(itemCount, 1), maxDropDownItems); height = (ItemHeight * count + 2); @@ -3120,23 +3606,29 @@ private void UpdateDropDownHeight() { /// the combobox requesting the info. This gives the effect of allowing the /// measureitem info to be updated at anytime. /// - private void UpdateItemHeight() { - if (!IsHandleCreated) { + private void UpdateItemHeight() + { + if (!IsHandleCreated) + { // if we don't create control here we report item heights incorrectly later on. CreateControl(); } - if (DrawMode == DrawMode.OwnerDrawFixed) { + if (DrawMode == DrawMode.OwnerDrawFixed) + { SendMessage(NativeMethods.CB_SETITEMHEIGHT, -1, ItemHeight); SendMessage(NativeMethods.CB_SETITEMHEIGHT, 0, ItemHeight); } - else if (DrawMode == DrawMode.OwnerDrawVariable) { + else if (DrawMode == DrawMode.OwnerDrawVariable) + { SendMessage(NativeMethods.CB_SETITEMHEIGHT, -1, ItemHeight); Graphics graphics = CreateGraphicsInternal(); - for (int i = 0; i < Items.Count; i++) { - int original = unchecked( (int) (long)SendMessage(NativeMethods.CB_GETITEMHEIGHT, i, 0)); + for (int i = 0; i < Items.Count; i++) + { + int original = unchecked((int)(long)SendMessage(NativeMethods.CB_GETITEMHEIGHT, i, 0)); MeasureItemEventArgs mievent = new MeasureItemEventArgs(graphics, i, original); OnMeasureItem(mievent); - if (mievent.ItemHeight != original) { + if (mievent.ItemHeight != original) + { SendMessage(NativeMethods.CB_SETITEMHEIGHT, i, mievent.ItemHeight); } } @@ -3147,13 +3639,14 @@ private void UpdateItemHeight() { /// /// Forces the text to be updated based on the current selection. /// - private void UpdateText() { + private void UpdateText() + { // Fire text changed for dropdown combos when the selection // changes, since the text really does change. We've got // to do this asynchronously because the actual edit text // isn't updated until a bit later // - + // v1.0 - ComboBox::set_Text compared items w/ "value" and set the SelectedIndex accordingly // v1.0 - null values can't correspond to String.Empty // v1.0 - SelectedIndex == -1 corresponds to Text == String.Emtpy @@ -3163,17 +3656,21 @@ private void UpdateText() { // v1.1 - SelectedIndex == -1 corresponds to Text == null string s = null; - if (SelectedIndex != -1) { + if (SelectedIndex != -1) + { object item = Items[SelectedIndex]; - if (item != null) { + if (item != null) + { s = GetItemText(item); } } Text = s; - if (DropDownStyle == ComboBoxStyle.DropDown) { - if (childEdit != null && childEdit.Handle != IntPtr.Zero) { + if (DropDownStyle == ComboBoxStyle.DropDown) + { + if (childEdit != null && childEdit.Handle != IntPtr.Zero) + { UnsafeNativeMethods.SendMessage(new HandleRef(this, childEdit.Handle), Interop.WindowMessages.WM_SETTEXT, IntPtr.Zero, s); } } @@ -3181,19 +3678,23 @@ private void UpdateText() { /// /// - private void WmEraseBkgnd(ref Message m) { - if ((DropDownStyle == ComboBoxStyle.Simple) && ParentInternal != null) { + private void WmEraseBkgnd(ref Message m) + { + if ((DropDownStyle == ComboBoxStyle.Simple) && ParentInternal != null) + { NativeMethods.RECT rect = new NativeMethods.RECT(); SafeNativeMethods.GetClientRect(new HandleRef(this, Handle), ref rect); Control p = ParentInternal; Graphics graphics = Graphics.FromHdcInternal(m.WParam); - if (p != null) { + if (p != null) + { Brush brush = new SolidBrush(p.BackColor); graphics.FillRectangle(brush, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top); brush.Dispose(); } - else { + else + { graphics.FillRectangle(SystemBrushes.Control, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top); } @@ -3206,14 +3707,17 @@ private void WmEraseBkgnd(ref Message m) { /// /// - private void WmParentNotify(ref Message m) { + private void WmParentNotify(ref Message m) + { base.WndProc(ref m); - if (unchecked((int)(long)m.WParam) == (Interop.WindowMessages.WM_CREATE | 1000 << 16)) { + if (unchecked((int)(long)m.WParam) == (Interop.WindowMessages.WM_CREATE | 1000 << 16)) + { dropDownHandle = m.LParam; // By some reason WmParentNotify with WM_DESTROY is not called before recreation. // So release the old references here. - if (childDropDown != null) { + if (childDropDown != null) + { // Need to notify UI Automation that it can safely remove all map entries that refer to the specified window. ReleaseUiaProvider(childListBox.Handle); @@ -3292,8 +3796,10 @@ private void WmParentNotify(ref Message m) { /// /// - private void WmReflectCommand(ref Message m) { - switch (NativeMethods.Util.HIWORD(m.WParam)) { + private void WmReflectCommand(ref Message m) + { + switch (NativeMethods.Util.HIWORD(m.WParam)) + { case NativeMethods.CBN_DBLCLK: //OnDoubleClick(EventArgs.Empty); break; @@ -3301,9 +3807,10 @@ private void WmReflectCommand(ref Message m) { OnTextUpdate(EventArgs.Empty); break; case NativeMethods.CBN_CLOSEUP: - + OnDropDownClosed(EventArgs.Empty); - if (FormattingEnabled && Text != currentText && dropDown) { + if (FormattingEnabled && Text != currentText && dropDown) + { OnTextChanged(EventArgs.Empty); } dropDown = false; @@ -3313,7 +3820,7 @@ private void WmReflectCommand(ref Message m) { dropDown = true; OnDropDown(EventArgs.Empty); UpdateDropDownHeight(); - + break; case NativeMethods.CBN_EDITCHANGE: OnTextChanged(EventArgs.Empty); @@ -3330,22 +3837,28 @@ private void WmReflectCommand(ref Message m) { /// /// - private void WmReflectDrawItem(ref Message m) { + private void WmReflectDrawItem(ref Message m) + { NativeMethods.DRAWITEMSTRUCT dis = (NativeMethods.DRAWITEMSTRUCT)m.GetLParam(typeof(NativeMethods.DRAWITEMSTRUCT)); IntPtr oldPal = SetUpPalette(dis.hDC, false /*force*/, false /*realize*/); - try { + try + { Graphics g = Graphics.FromHdcInternal(dis.hDC); - try { + try + { OnDrawItem(new DrawItemEventArgs(g, Font, Rectangle.FromLTRB(dis.rcItem.left, dis.rcItem.top, dis.rcItem.right, dis.rcItem.bottom), dis.itemID, (DrawItemState)dis.itemState, ForeColor, BackColor)); } - finally { + finally + { g.Dispose(); } } - finally { - if (oldPal != IntPtr.Zero) { + finally + { + if (oldPal != IntPtr.Zero) + { SafeNativeMethods.SelectPalette(new HandleRef(this, dis.hDC), new HandleRef(null, oldPal), 0); } } @@ -3354,18 +3867,21 @@ private void WmReflectDrawItem(ref Message m) { /// /// - private void WmReflectMeasureItem(ref Message m) { + private void WmReflectMeasureItem(ref Message m) + { NativeMethods.MEASUREITEMSTRUCT mis = (NativeMethods.MEASUREITEMSTRUCT)m.GetLParam(typeof(NativeMethods.MEASUREITEMSTRUCT)); // Determine if message was sent by a combo item or the combo edit field - if (DrawMode == DrawMode.OwnerDrawVariable && mis.itemID >= 0) { + if (DrawMode == DrawMode.OwnerDrawVariable && mis.itemID >= 0) + { Graphics graphics = CreateGraphicsInternal(); MeasureItemEventArgs mie = new MeasureItemEventArgs(graphics, mis.itemID, ItemHeight); OnMeasureItem(mie); mis.itemHeight = mie.ItemHeight; graphics.Dispose(); } - else { + else + { // Message was sent by the combo edit field mis.itemHeight = ItemHeight; } @@ -3378,27 +3894,32 @@ private void WmReflectMeasureItem(ref Message m) { /// to add extra functionality, but should not forget to call /// base.wndProc(m); to ensure the combo continues to function properly. /// - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { // We don't want to fire the focus events twice - // once in the combobox and once in the ChildWndProc. case Interop.WindowMessages.WM_SETFOCUS: - try { + try + { fireSetFocus = false; base.WndProc(ref m); } - - finally { + + finally + { fireSetFocus = true; } break; case Interop.WindowMessages.WM_KILLFOCUS: - try { + try + { fireLostFocus = false; base.WndProc(ref m); // Nothing to see here... Just keep on walking... // Turns out that with Theming off, we don't get quite the same messages as with theming on. - + // With theming on we get a WM_MOUSELEAVE after a WM_KILLFOCUS even if you use the Tab key // to move focus. Our response to WM_MOUSELEAVE causes us to repaint everything correctly. @@ -3406,13 +3927,15 @@ protected override void WndProc(ref Message m) { // when we are a Flat DropDownList, we need to force a repaint. The easiest way to do this is to send a // WM_MOUSELEAVE to ourselves, since that also sets up the right state. Or... at least the state is the same // as with Theming on. - - if (!Application.RenderWithVisualStyles && GetStyle(ControlStyles.UserPaint) == false && this.DropDownStyle == ComboBoxStyle.DropDownList && (FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup)) { - UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), Interop.WindowMessages.WM_MOUSELEAVE, 0, 0); + + if (!Application.RenderWithVisualStyles && GetStyle(ControlStyles.UserPaint) == false && this.DropDownStyle == ComboBoxStyle.DropDownList && (FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup)) + { + UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), Interop.WindowMessages.WM_MOUSELEAVE, 0, 0); } } - finally { + finally + { fireLostFocus = true; } break; @@ -3454,17 +3977,20 @@ protected override void WndProc(ref Message m) { //WM_LBUTTONDOWN or WM_LBUTTONDBLBCLK // combo box gets a WM_LBUTTONUP for focus change ... // - if (mouseEvents && !ValidationCancelled) { + if (mouseEvents && !ValidationCancelled) + { mouseEvents = false; bool captured = Capture; - if (captured && ClientRect.Contains(pt)) { + if (captured && ClientRect.Contains(pt)) + { OnClick(new MouseEventArgs(MouseButtons.Left, 1, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); OnMouseClick(new MouseEventArgs(MouseButtons.Left, 1, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); } base.WndProc(ref m); } - else { + else + { CaptureInternal = false; DefWndProc(ref m); } @@ -3476,10 +4002,13 @@ protected override void WndProc(ref Message m) { break; case Interop.WindowMessages.WM_PAINT: - if (GetStyle(ControlStyles.UserPaint) == false && (FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup)) { + if (GetStyle(ControlStyles.UserPaint) == false && (FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup)) + { - using (WindowsRegion dr = new WindowsRegion(FlatComboBoxAdapter.dropDownRect)) { - using (WindowsRegion wr = new WindowsRegion(this.Bounds)) { + using (WindowsRegion dr = new WindowsRegion(FlatComboBoxAdapter.dropDownRect)) + { + using (WindowsRegion wr = new WindowsRegion(this.Bounds)) + { // Stash off the region we have to update (the base is going to clear this off in BeginPaint) NativeMethods.RegionFlags updateRegionFlags = (NativeMethods.RegionFlags)SafeNativeMethods.GetUpdateRgn(new HandleRef(this, this.Handle), new HandleRef(this, wr.HRegion), true); @@ -3493,31 +4022,39 @@ protected override void WndProc(ref Message m) { NativeMethods.PAINTSTRUCT ps = new NativeMethods.PAINTSTRUCT(); IntPtr dc; bool disposeDc = false; - if (m.WParam == IntPtr.Zero) { + if (m.WParam == IntPtr.Zero) + { dc = UnsafeNativeMethods.BeginPaint(new HandleRef(this, Handle), ref ps); disposeDc = true; } - else { + else + { dc = m.WParam; } - using (DeviceContext mDC = DeviceContext.FromHdc(dc)) { - using (WindowsGraphics wg = new WindowsGraphics(mDC)) { - if (updateRegionFlags != NativeMethods.RegionFlags.ERROR) { + using (DeviceContext mDC = DeviceContext.FromHdc(dc)) + { + using (WindowsGraphics wg = new WindowsGraphics(mDC)) + { + if (updateRegionFlags != NativeMethods.RegionFlags.ERROR) + { wg.DeviceContext.SetClip(dr); } m.WParam = dc; DefWndProc(ref m); - if (updateRegionFlags != NativeMethods.RegionFlags.ERROR) { + if (updateRegionFlags != NativeMethods.RegionFlags.ERROR) + { wg.DeviceContext.SetClip(wr); } - using (Graphics g = Graphics.FromHdcInternal(dc)) { + using (Graphics g = Graphics.FromHdcInternal(dc)) + { FlatComboBoxAdapter.DrawFlatCombo(this, g); } } } - if (disposeDc) { + if (disposeDc) + { UnsafeNativeMethods.EndPaint(new HandleRef(this, Handle), ref ps); } @@ -3525,32 +4062,37 @@ protected override void WndProc(ref Message m) { return; } } - + base.WndProc(ref m); break; - case Interop.WindowMessages.WM_PRINTCLIENT: + case Interop.WindowMessages.WM_PRINTCLIENT: // all the fancy stuff we do in OnPaint has to happen again in OnPrint. - if (GetStyle(ControlStyles.UserPaint) == false && FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup) { + if (GetStyle(ControlStyles.UserPaint) == false && FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup) + { DefWndProc(ref m); - - if ((unchecked( (int) (long)m.LParam) & NativeMethods.PRF_CLIENT) == NativeMethods.PRF_CLIENT) { - if (GetStyle(ControlStyles.UserPaint) == false && FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup) { - using (Graphics g = Graphics.FromHdcInternal(m.WParam)) { - FlatComboBoxAdapter.DrawFlatCombo(this,g); + + if ((unchecked((int)(long)m.LParam) & NativeMethods.PRF_CLIENT) == NativeMethods.PRF_CLIENT) + { + if (GetStyle(ControlStyles.UserPaint) == false && FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup) + { + using (Graphics g = Graphics.FromHdcInternal(m.WParam)) + { + FlatComboBoxAdapter.DrawFlatCombo(this, g); } } return; } } base.WndProc(ref m); - return; + return; case Interop.WindowMessages.WM_SETCURSOR: base.WndProc(ref m); break; case Interop.WindowMessages.WM_SETFONT: //( - if (Width == 0) { + if (Width == 0) + { suppressNextWindosPos = true; } base.WndProc(ref m); @@ -3558,7 +4100,8 @@ protected override void WndProc(ref Message m) { case Interop.WindowMessages.WM_WINDOWPOSCHANGED: - if (!suppressNextWindosPos) { + if (!suppressNextWindosPos) + { base.WndProc(ref m); } suppressNextWindosPos = false; @@ -3568,9 +4111,10 @@ protected override void WndProc(ref Message m) { base.WndProc(ref m); ReleaseChildWindow(); break; - + default: - if (m.Msg == NativeMethods.WM_MOUSEENTER) { + if (m.Msg == NativeMethods.WM_MOUSEENTER) + { DefWndProc(ref m); OnMouseEnterInternal(EventArgs.Empty); break; @@ -3583,23 +4127,28 @@ protected override void WndProc(ref Message m) { /// /// [ComVisible(true)] - private class ComboBoxChildNativeWindow : NativeWindow { + private class ComboBoxChildNativeWindow : NativeWindow + { private ComboBox _owner; private InternalAccessibleObject _accessibilityObject; private ChildWindowType _childWindowType; - public ComboBoxChildNativeWindow(ComboBox comboBox, ChildWindowType childWindowType) { + public ComboBoxChildNativeWindow(ComboBox comboBox, ChildWindowType childWindowType) + { _owner = comboBox; _childWindowType = childWindowType; } - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { case Interop.WindowMessages.WM_GETOBJECT: WmGetObject(ref m); return; case Interop.WindowMessages.WM_MOUSEMOVE: - if (_childWindowType == ChildWindowType.DropDownList) { + if (_childWindowType == ChildWindowType.DropDownList) + { // Need to track the selection change via mouse over to // raise focus changed event for the items. Monitoring @@ -3608,33 +4157,41 @@ protected override void WndProc(ref Message m) { object before = _owner.SelectedItem; DefWndProc(ref m); object after = _owner.SelectedItem; - if (before != after) { + if (before != after) + { (_owner.AccessibilityObject as ComboBoxAccessibleObject).SetComboBoxItemFocus(); } } break; default: - if (_childWindowType == ChildWindowType.DropDownList) { + if (_childWindowType == ChildWindowType.DropDownList) + { DefWndProc(ref m); // Drop Down window should behave by its own. - } else { + } + else + { _owner.ChildWndProc(ref m); } break; } } - private ChildAccessibleObject GetChildAccessibleObject(ChildWindowType childWindowType) { - if (childWindowType == ChildWindowType.Edit) { + private ChildAccessibleObject GetChildAccessibleObject(ChildWindowType childWindowType) + { + if (childWindowType == ChildWindowType.Edit) + { return _owner.ChildEditAccessibleObject; } - else if (childWindowType == ChildWindowType.ListBox || childWindowType == ChildWindowType.DropDownList) { + else if (childWindowType == ChildWindowType.ListBox || childWindowType == ChildWindowType.DropDownList) + { return _owner.ChildListAccessibleObject; } return new ChildAccessibleObject(_owner, Handle); } - private void WmGetObject(ref Message m) { + private void WmGetObject(ref Message m) + { if (m.LParam == (IntPtr)NativeMethods.UiaRootObjectId && // Managed UIAutomation providers are supplied for child list windows but not for the child edit window. // Child list accessibility object provides all necessary patterns and UIAutomation notifications, @@ -3642,7 +4199,8 @@ private void WmGetObject(ref Message m) { // Child edit accessibility object has only partial support of edit box accessibility, most of the patterns // and notifications for child edit window are supplied by native providers, so here is no need to // override root UIA object for child edit window. - (_childWindowType == ChildWindowType.ListBox || _childWindowType == ChildWindowType.DropDownList)) { + (_childWindowType == ChildWindowType.ListBox || _childWindowType == ChildWindowType.DropDownList)) + { AccessibleObject uiaProvider = GetChildAccessibleObject(_childWindowType); // If the requested object identifier is UiaRootObjectId, @@ -3659,7 +4217,8 @@ private void WmGetObject(ref Message m) { // See "How to Handle WM_GETOBJECT" in MSDN // - if (NativeMethods.OBJID_CLIENT == unchecked((int)(long)m.LParam)) { + if (NativeMethods.OBJID_CLIENT == unchecked((int)(long)m.LParam)) + { // Get the IAccessible GUID // @@ -3668,11 +4227,13 @@ private void WmGetObject(ref Message m) { // Get an Lresult for the accessibility Object for this control // IntPtr punkAcc; - try { + try + { AccessibleObject wfAccessibleObject = null; UnsafeNativeMethods.IAccessibleInternal iacc = null; - if (_accessibilityObject == null) { + if (_accessibilityObject == null) + { wfAccessibleObject = GetChildAccessibleObject(_childWindowType); _accessibilityObject = new InternalAccessibleObject(wfAccessibleObject); } @@ -3682,33 +4243,41 @@ private void WmGetObject(ref Message m) { // punkAcc = Marshal.GetIUnknownForObject(iacc); - try { + try + { m.Result = UnsafeNativeMethods.LresultFromObject(ref IID_IAccessible, m.WParam, new HandleRef(this, punkAcc)); } - finally { + finally + { Marshal.Release(punkAcc); } } - catch (Exception e) { + catch (Exception e) + { throw new InvalidOperationException(SR.RichControlLresult, e); } } - else { // m.lparam != OBJID_CLIENT, so do default message processing + else + { // m.lparam != OBJID_CLIENT, so do default message processing DefWndProc(ref m); } } } - private sealed class ItemComparer : System.Collections.IComparer { + private sealed class ItemComparer : System.Collections.IComparer + { private ComboBox comboBox; - public ItemComparer(ComboBox comboBox) { + public ItemComparer(ComboBox comboBox) + { this.comboBox = comboBox; } - public int Compare(object item1, object item2) { - if (item1 == null) { + public int Compare(object item1, object item2) + { + if (item1 == null) + { if (item2 == null) return 0; //both null, then they are equal @@ -3726,28 +4295,36 @@ public int Compare(object item1, object item2) { } [ListBindable(false)] - public class ObjectCollection : IList { + public class ObjectCollection : IList + { private ComboBox owner; private ArrayList innerList; private IComparer comparer; - public ObjectCollection(ComboBox owner) { + public ObjectCollection(ComboBox owner) + { this.owner = owner; } - private IComparer Comparer { - get { - if (comparer == null) { + private IComparer Comparer + { + get + { + if (comparer == null) + { comparer = new ItemComparer(owner); } return comparer; } } - private ArrayList InnerList { - get { - if (innerList == null) { + private ArrayList InnerList + { + get + { + if (innerList == null) + { innerList = new ArrayList(); } return innerList; @@ -3757,32 +4334,42 @@ private ArrayList InnerList { /// /// Retrieves the number of items. /// - public int Count { - get { + public int Count + { + get + { return InnerList.Count; } } - object ICollection.SyncRoot { - get { + object ICollection.SyncRoot + { + get + { return this; } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return false; } } - bool IList.IsFixedSize { - get { + bool IList.IsFixedSize + { + get + { return false; } } - public bool IsReadOnly { - get { + public bool IsReadOnly + { + get + { return false; } } @@ -3808,10 +4395,12 @@ public int Add(object item) return index; } - - private int AddInternal(object item) { - - if (item == null) { + + private int AddInternal(object item) + { + + if (item == null) + { throw new ArgumentNullException(nameof(item)); } int index = -1; @@ -3827,27 +4416,34 @@ private int AddInternal(object item) { index = ~index; // getting the index of the first element that is larger than the search value } - Debug.Assert(index>=0 && index <= InnerList.Count, "Wrong index for insert"); + Debug.Assert(index >= 0 && index <= InnerList.Count, "Wrong index for insert"); InnerList.Insert(index, item); } bool successful = false; - try { - if (owner.sorted) { - if (owner.IsHandleCreated) { + try + { + if (owner.sorted) + { + if (owner.IsHandleCreated) + { owner.NativeInsert(index, item); } } - else { - index = InnerList.Count-1; - if (owner.IsHandleCreated) { + else + { + index = InnerList.Count - 1; + if (owner.IsHandleCreated) + { owner.NativeAdd(item); } } successful = true; } - finally { - if (!successful) { + finally + { + if (!successful) + { InnerList.Remove(item); } } @@ -3855,11 +4451,13 @@ private int AddInternal(object item) { return index; } - int IList.Add(object item) { + int IList.Add(object item) + { return Add(item); } - public void AddRange(object[] items) { + public void AddRange(object[] items) + { owner.CheckNoDataSource(); owner.BeginUpdate(); try @@ -3871,14 +4469,16 @@ public void AddRange(object[] items) { owner.EndUpdate(); } } - - internal void AddRangeInternal(IList items) { + + internal void AddRangeInternal(IList items) + { if (items == null) { throw new ArgumentNullException(nameof(items)); } - foreach (object item in items) { + foreach (object item in items) + { // adding items one-by-one for performance (especially for sorted combobox) // we can not rely on ArrayList.Sort since its worst case complexity is n*n // AddInternal is based on BinarySearch and ensures n*log(n) complexity @@ -3894,15 +4494,19 @@ internal void AddRangeInternal(IList items) { /// Retrieves the item with the specified index. /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public virtual object this[int index] { - get { - if (index < 0 || index >= InnerList.Count) { + public virtual object this[int index] + { + get + { + if (index < 0 || index >= InnerList.Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } return InnerList[index]; } - set { + set + { owner.CheckNoDataSource(); SetItemInternal(index, value); } @@ -3911,14 +4515,17 @@ public virtual object this[int index] { /// /// Removes all items from the ComboBox. /// - public void Clear() { + public void Clear() + { owner.CheckNoDataSource(); ClearInternal(); } - internal void ClearInternal() { + internal void ClearInternal() + { - if (owner.IsHandleCreated) { + if (owner.IsHandleCreated) + { owner.NativeClear(); } @@ -3930,30 +4537,36 @@ internal void ClearInternal() { } } - public bool Contains(object value) { + public bool Contains(object value) + { return IndexOf(value) != -1; } /// /// Copies the ComboBox Items collection to a destination array. /// - public void CopyTo(object[] destination, int arrayIndex) { + public void CopyTo(object[] destination, int arrayIndex) + { InnerList.CopyTo(destination, arrayIndex); } - void ICollection.CopyTo(Array destination, int index) { + void ICollection.CopyTo(Array destination, int index) + { InnerList.CopyTo(destination, index); } /// /// Returns an enumerator for the ComboBox Items collection. /// - public IEnumerator GetEnumerator() { + public IEnumerator GetEnumerator() + { return InnerList.GetEnumerator(); } - public int IndexOf(object value) { - if (value == null) { + public int IndexOf(object value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } @@ -3969,41 +4582,51 @@ public int IndexOf(object value) { /// A SystemException occurs if there is insufficient space available to /// store the new item. /// - public void Insert(int index, object item) { + public void Insert(int index, object item) + { owner.CheckNoDataSource(); - if (item == null) { + if (item == null) + { throw new ArgumentNullException(nameof(item)); } - if (index < 0 || index > InnerList.Count) { + if (index < 0 || index > InnerList.Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } // If the combo box is sorted, then nust treat this like an add // because we are going to twiddle the index anyway. // - if (owner.sorted) { + if (owner.sorted) + { Add(item); } - else { + else + { InnerList.Insert(index, item); - if (owner.IsHandleCreated) { + if (owner.IsHandleCreated) + { bool successful = false; - try { + try + { owner.NativeInsert(index, item); successful = true; } - finally { - if (successful) { + finally + { + if (successful) + { if (owner.AutoCompleteSource == AutoCompleteSource.ListItems) { owner.SetAutoComplete(false, false); } } - else { + else + { InnerList.RemoveAt(index); } } @@ -4014,19 +4637,23 @@ public void Insert(int index, object item) { /// /// Removes an item from the ComboBox at the given index. /// - public void RemoveAt(int index) { + public void RemoveAt(int index) + { owner.CheckNoDataSource(); - if (index < 0 || index >= InnerList.Count) { + if (index < 0 || index >= InnerList.Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - if (owner.IsHandleCreated) { + if (owner.IsHandleCreated) + { owner.NativeRemoveAt(index); } InnerList.RemoveAt(index); - if (!owner.IsHandleCreated && index < owner.selectedIndex) { + if (!owner.IsHandleCreated && index < owner.selectedIndex) + { owner.selectedIndex--; } if (owner.AutoCompleteSource == AutoCompleteSource.ListItems) @@ -4039,21 +4666,26 @@ public void RemoveAt(int index) { /// Removes the given item from the ComboBox, provided that it is /// actually in the list. /// - public void Remove(object value) { + public void Remove(object value) + { int index = InnerList.IndexOf(value); - if (index != -1) { + if (index != -1) + { RemoveAt(index); } } - internal void SetItemInternal(int index, object value) { - if (value == null) { + internal void SetItemInternal(int index, object value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } - if (index < 0 || index >= InnerList.Count) { + if (index < 0 || index >= InnerList.Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } @@ -4061,13 +4693,16 @@ internal void SetItemInternal(int index, object value) { // If the native control has been created, and the display text of the new list item object // is different to the current text in the native list item, recreate the native list item... - if (owner.IsHandleCreated) { + if (owner.IsHandleCreated) + { bool selected = (index == owner.SelectedIndex); - if (string.Compare(this.owner.GetItemText(value), this.owner.NativeGetItemText(index), true, CultureInfo.CurrentCulture) != 0) { + if (string.Compare(this.owner.GetItemText(value), this.owner.NativeGetItemText(index), true, CultureInfo.CurrentCulture) != 0) + { owner.NativeRemoveAt(index); owner.NativeInsert(index, value); - if (selected) { + if (selected) + { owner.SelectedIndex = index; owner.UpdateText(); } @@ -4076,10 +4711,12 @@ internal void SetItemInternal(int index, object value) { owner.SetAutoComplete(false, false); } } - else { + else + { // NEW - FOR COMPATIBILITY REASONS // Minimum compatibility fix - if (selected) { + if (selected) + { owner.OnSelectedItemChanged(EventArgs.Empty); //we do this because set_SelectedIndex does this. (for consistency) owner.OnSelectedIndexChanged(EventArgs.Empty); } @@ -4090,19 +4727,23 @@ internal void SetItemInternal(int index, object value) { } // end ObjectCollection [ComVisible(true)] - public class ChildAccessibleObject : AccessibleObject { + public class ChildAccessibleObject : AccessibleObject + { ComboBox owner; - public ChildAccessibleObject(ComboBox owner, IntPtr handle) { + public ChildAccessibleObject(ComboBox owner, IntPtr handle) + { Debug.Assert(owner != null && owner.Handle != IntPtr.Zero, "ComboBox's handle hasn't been created"); this.owner = owner; UseStdAccessibleObjects(handle); } - public override string Name { - get { + public override string Name + { + get + { return owner.AccessibilityObject.Name; } } @@ -4112,7 +4753,8 @@ public override string Name { /// Represents the ComboBox item accessible object. /// [ComVisible(true)] - internal class ComboBoxItemAccessibleObject : AccessibleObject { + internal class ComboBoxItemAccessibleObject : AccessibleObject + { private ComboBox _owningComboBox; private object _owningItem; @@ -4123,7 +4765,8 @@ internal class ComboBoxItemAccessibleObject : AccessibleObject { /// /// The owning ComboBox. /// The owning ComboBox item. - public ComboBoxItemAccessibleObject(ComboBox owningComboBox, object owningItem) { + public ComboBoxItemAccessibleObject(ComboBox owningComboBox, object owningItem) + { _owningComboBox = owningComboBox; _owningItem = owningItem; @@ -4133,8 +4776,10 @@ public ComboBoxItemAccessibleObject(ComboBox owningComboBox, object owningItem) /// /// Gets the ComboBox Item bounds. /// - public override Rectangle Bounds { - get { + public override Rectangle Bounds + { + get + { var listAccessibleObject = _owningComboBox.ChildListAccessibleObject; int currentIndex = GetCurrentIndex(); @@ -4151,23 +4796,29 @@ public override Rectangle Bounds { /// /// Gets the ComboBox item default action. /// - public override string DefaultAction { - get { + public override string DefaultAction + { + get + { return _systemIAccessible.accDefaultAction[GetChildId()]; } } - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - switch (direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { + switch (direction) + { case UnsafeNativeMethods.NavigateDirection.Parent: return _owningComboBox.ChildListAccessibleObject; case UnsafeNativeMethods.NavigateDirection.NextSibling: int currentIndex = GetCurrentIndex(); var comboBoxChildListUiaProvider = _owningComboBox.ChildListAccessibleObject as ComboBoxChildListUiaProvider; - if (comboBoxChildListUiaProvider != null) { + if (comboBoxChildListUiaProvider != null) + { int itemsCount = comboBoxChildListUiaProvider.GetChildFragmentCount(); int nextItemIndex = currentIndex + 1; - if (itemsCount > nextItemIndex) { + if (itemsCount > nextItemIndex) + { return comboBoxChildListUiaProvider.GetChildFragment(nextItemIndex); } } @@ -4175,36 +4826,44 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga case UnsafeNativeMethods.NavigateDirection.PreviousSibling: currentIndex = GetCurrentIndex(); comboBoxChildListUiaProvider = _owningComboBox.ChildListAccessibleObject as ComboBoxChildListUiaProvider; - if (comboBoxChildListUiaProvider != null) { + if (comboBoxChildListUiaProvider != null) + { var itemsCount = comboBoxChildListUiaProvider.GetChildFragmentCount(); int previousItemIndex = currentIndex - 1; - if (previousItemIndex >= 0) { + if (previousItemIndex >= 0) + { return comboBoxChildListUiaProvider.GetChildFragment(previousItemIndex); } } - + break; } return base.FragmentNavigate(direction); } - internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot { - get { + internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot + { + get + { return _owningComboBox.AccessibilityObject; } } - private int GetCurrentIndex() { + private int GetCurrentIndex() + { return _owningComboBox.Items.IndexOf(_owningItem); } - - internal override int GetChildId() { + + internal override int GetChildId() + { return GetCurrentIndex() + 1; // Index is zero-based, Child ID is 1-based. } - internal override object GetPropertyValue(int propertyID) { - switch (propertyID) { + internal override object GetPropertyValue(int propertyID) + { + switch (propertyID) + { case NativeMethods.UIA_RuntimeIdPropertyId: return RuntimeId; case NativeMethods.UIA_BoundingRectanglePropertyId: @@ -4246,8 +4905,10 @@ internal override object GetPropertyValue(int propertyID) { /// /// Gets the help text. /// - public override string Help { - get { + public override string Help + { + get + { return _systemIAccessible.accHelp[GetChildId()]; } } @@ -4257,29 +4918,35 @@ public override string Help { /// /// The pattern ID. /// True if specified - internal override bool IsPatternSupported(int patternId) { + internal override bool IsPatternSupported(int patternId) + { if (patternId == NativeMethods.UIA_LegacyIAccessiblePatternId || patternId == NativeMethods.UIA_InvokePatternId || - patternId == NativeMethods.UIA_SelectionItemPatternId) { + patternId == NativeMethods.UIA_SelectionItemPatternId) + { return true; } return base.IsPatternSupported(patternId); } - + /// /// Gets or sets the accessible name. /// - public override string Name { - get { - if (_owningComboBox != null) { + public override string Name + { + get + { + if (_owningComboBox != null) + { return _owningItem.ToString(); } return base.Name; } - set { + set + { base.Name = value; } } @@ -4287,17 +4954,21 @@ public override string Name { /// /// Gets the accessible role. /// - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { return (AccessibleRole)_systemIAccessible.get_accRole(GetChildId()); } } - + /// /// Gets the runtime ID. /// - internal override int[] RuntimeId { - get { + internal override int[] RuntimeId + { + get + { var runtimeId = new int[4]; runtimeId[0] = RuntimeIDFirstItem; runtimeId[1] = (int)(long)_owningComboBox.Handle; @@ -4313,58 +4984,73 @@ internal override int[] RuntimeId { /// /// Gets the accessible state. /// - public override AccessibleStates State { - get { + public override AccessibleStates State + { + get + { return (AccessibleStates)_systemIAccessible.get_accState(GetChildId()); } } - internal override void SetFocus() { + internal override void SetFocus() + { RaiseAutomationEvent(NativeMethods.UIA_AutomationFocusChangedEventId); base.SetFocus(); } - internal override void SelectItem() { + internal override void SelectItem() + { _owningComboBox.SelectedIndex = GetCurrentIndex(); SafeNativeMethods.InvalidateRect(new HandleRef(this, _owningComboBox.GetListHandle()), null, false); } - internal override void AddToSelection() { + internal override void AddToSelection() + { SelectItem(); } - internal override void RemoveFromSelection() { + internal override void RemoveFromSelection() + { // Do nothing, C++ implementation returns UIA_E_INVALIDOPERATION 0x80131509 } - internal override bool IsItemSelected { - get { + internal override bool IsItemSelected + { + get + { return (State & AccessibleStates.Selected) != 0; } } - internal override UnsafeNativeMethods.IRawElementProviderSimple ItemSelectionContainer { - get { + internal override UnsafeNativeMethods.IRawElementProviderSimple ItemSelectionContainer + { + get + { return _owningComboBox.ChildListAccessibleObject; } } } - internal class ComboBoxItemAccessibleObjectCollection : Hashtable { + internal class ComboBoxItemAccessibleObjectCollection : Hashtable + { private ComboBox _owningComboBoxBox; private readonly ObjectIDGenerator _idGenerator = new ObjectIDGenerator(); - public ComboBoxItemAccessibleObjectCollection(ComboBox owningComboBoxBox) { + public ComboBoxItemAccessibleObjectCollection(ComboBox owningComboBoxBox) + { _owningComboBoxBox = owningComboBoxBox; } - public override object this[object key] { - get { + public override object this[object key] + { + get + { int id = GetId(key); - if (!ContainsKey(id)) { + if (!ContainsKey(id)) + { var itemAccessibleObject = new ComboBoxItemAccessibleObject(_owningComboBoxBox, key); base[id] = itemAccessibleObject; } @@ -4372,13 +5058,15 @@ public override object this[object key] { return base[id]; } - set { + set + { int id = GetId(key); base[id] = value; } } - public int GetId(object item) { + public int GetId(object item) + { return unchecked((int)_idGenerator.GetId(item, out var _)); } } @@ -4389,7 +5077,8 @@ public int GetId(object item) { /// to have all base functionality. /// [ComVisible(true)] - internal class ComboBoxAccessibleObject : ControlAccessibleObject { + internal class ComboBoxAccessibleObject : ControlAccessibleObject + { private const int COMBOBOX_ACC_ITEM_INDEX = 1; private ComboBoxChildDropDownButtonUiaProvider _dropDownButtonUiaProvider; @@ -4514,8 +5203,10 @@ internal override string get_accKeyboardShortcutInternal(object childID) /// /// Gets the collection of item accessible objects. /// - public ComboBoxItemAccessibleObjectCollection ItemAccessibleObjects { - get { + public ComboBoxItemAccessibleObjectCollection ItemAccessibleObjects + { + get + { return _itemAccessibleObjects; } } @@ -4523,8 +5214,10 @@ public ComboBoxItemAccessibleObjectCollection ItemAccessibleObjects { /// /// Gets the DropDown button accessible object. (UI Automation provider) /// - public ComboBoxChildDropDownButtonUiaProvider DropDownButtonUiaProvider { - get { + public ComboBoxChildDropDownButtonUiaProvider DropDownButtonUiaProvider + { + get + { if (_dropDownButtonUiaProvider == null) { _dropDownButtonUiaProvider = new ComboBoxChildDropDownButtonUiaProvider(_owningComboBox, _owningComboBox.Handle); @@ -4539,13 +5232,17 @@ public ComboBoxChildDropDownButtonUiaProvider DropDownButtonUiaProvider { /// /// Indicates the direction in which to navigate. /// Returns the element in the specified direction. - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - if (direction == UnsafeNativeMethods.NavigateDirection.FirstChild) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { + if (direction == UnsafeNativeMethods.NavigateDirection.FirstChild) + { return GetChildFragment(0); } - else if (direction == UnsafeNativeMethods.NavigateDirection.LastChild) { + else if (direction == UnsafeNativeMethods.NavigateDirection.LastChild) + { var childFragmentCount = GetChildFragmentCount(); - if (childFragmentCount > 0) { + if (childFragmentCount > 0) + { return GetChildFragment(childFragmentCount - 1); } } @@ -4553,19 +5250,24 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga return base.FragmentNavigate(direction); } - internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot { - get { + internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot + { + get + { return this; } } - internal override UnsafeNativeMethods.IRawElementProviderSimple GetOverrideProviderForHwnd(IntPtr hwnd) { - if (hwnd == _owningComboBox.childEdit.Handle) { + internal override UnsafeNativeMethods.IRawElementProviderSimple GetOverrideProviderForHwnd(IntPtr hwnd) + { + if (hwnd == _owningComboBox.childEdit.Handle) + { return _owningComboBox.ChildEditAccessibleObject; } else if ( hwnd == _owningComboBox.childListBox.Handle || - hwnd == _owningComboBox.dropDownHandle) { + hwnd == _owningComboBox.dropDownHandle) + { return _owningComboBox.ChildListAccessibleObject; } @@ -4580,16 +5282,20 @@ internal override UnsafeNativeMethods.IRawElementProviderSimple GetOverrideProvi /// /// GetChild method should be unchanged to not break the MSAA scenarios. /// - internal AccessibleObject GetChildFragment(int index) { - if (_owningComboBox.DropDownStyle == ComboBoxStyle.DropDownList) { - if (index == 0) { + internal AccessibleObject GetChildFragment(int index) + { + if (_owningComboBox.DropDownStyle == ComboBoxStyle.DropDownList) + { + if (index == 0) + { return _owningComboBox.ChildTextAccessibleObject; } index--; } - if (index == 0 && _owningComboBox.DropDownStyle != ComboBoxStyle.Simple) { + if (index == 0 && _owningComboBox.DropDownStyle != ComboBoxStyle.Simple) + { return DropDownButtonUiaProvider; } @@ -4603,14 +5309,17 @@ internal AccessibleObject GetChildFragment(int index) { /// /// GetChildCount method should be unchanged to not break the MSAA scenarios. /// - internal int GetChildFragmentCount() { + internal int GetChildFragmentCount() + { int childFragmentCount = 0; - if (_owningComboBox.DropDownStyle == ComboBoxStyle.DropDownList) { + if (_owningComboBox.DropDownStyle == ComboBoxStyle.DropDownList) + { childFragmentCount++; // Text instead of edit for style is DropDownList but not DropDown. } - if (_owningComboBox.DropDownStyle != ComboBoxStyle.Simple) { + if (_owningComboBox.DropDownStyle != ComboBoxStyle.Simple) + { childFragmentCount++; // DropDown button. } @@ -4622,8 +5331,10 @@ internal int GetChildFragmentCount() { /// /// The accessible property ID. /// The accessible property value. - internal override object GetPropertyValue(int propertyID) { - switch (propertyID) { + internal override object GetPropertyValue(int propertyID) + { + switch (propertyID) + { case NativeMethods.UIA_ControlTypePropertyId: return NativeMethods.UIA_ComboBoxControlTypeId; case NativeMethods.UIA_NamePropertyId: @@ -4642,35 +5353,43 @@ internal override object GetPropertyValue(int propertyID) { } } - internal void ResetListItemAccessibleObjects() { + internal void ResetListItemAccessibleObjects() + { _itemAccessibleObjects.Clear(); } - internal void SetComboBoxItemFocus() { + internal void SetComboBoxItemFocus() + { var selectedItem = _owningComboBox.SelectedItem; - if (selectedItem == null) { + if (selectedItem == null) + { return; } var itemAccessibleObject = ItemAccessibleObjects[selectedItem] as ComboBoxItemAccessibleObject; - if (itemAccessibleObject != null) { + if (itemAccessibleObject != null) + { itemAccessibleObject.SetFocus(); } } - internal void SetComboBoxItemSelection() { + internal void SetComboBoxItemSelection() + { var selectedItem = _owningComboBox.SelectedItem; - if (selectedItem == null) { + if (selectedItem == null) + { return; } var itemAccessibleObject = ItemAccessibleObjects[selectedItem] as ComboBoxItemAccessibleObject; - if (itemAccessibleObject != null) { + if (itemAccessibleObject != null) + { itemAccessibleObject.RaiseAutomationEvent(NativeMethods.UIA_SelectionItem_ElementSelectedEventId); } } - internal override void SetFocus() { + internal override void SetFocus() + { base.SetFocus(); RaiseAutomationEvent(NativeMethods.UIA_AutomationFocusChangedEventId); @@ -4680,7 +5399,8 @@ internal override void SetFocus() { /// /// Represents the ComboBox's child (inner) edit native window control accessible object with UI Automation provider functionality. /// - internal class ComboBoxChildEditUiaProvider : ChildAccessibleObject { + internal class ComboBoxChildEditUiaProvider : ChildAccessibleObject + { private const string COMBO_BOX_EDIT_AUTOMATION_ID = "1001"; private ComboBox _owner; @@ -4691,7 +5411,8 @@ internal class ComboBoxChildEditUiaProvider : ChildAccessibleObject { /// /// The ComboBox owning control. /// The child edit native window handle. - public ComboBoxChildEditUiaProvider(ComboBox owner, IntPtr childEditControlhandle) : base(owner, childEditControlhandle) { + public ComboBoxChildEditUiaProvider(ComboBox owner, IntPtr childEditControlhandle) : base(owner, childEditControlhandle) + { _owner = owner; _handle = childEditControlhandle; } @@ -4701,20 +5422,25 @@ public ComboBoxChildEditUiaProvider(ComboBox owner, IntPtr childEditControlhandl /// /// Indicates the direction in which to navigate. /// Returns the element in the specified direction. - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - switch (direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { + switch (direction) + { case UnsafeNativeMethods.NavigateDirection.Parent: Debug.WriteLine("Edit parent " + _owner.AccessibilityObject.GetPropertyValue(NativeMethods.UIA_ControlTypePropertyId)); return _owner.AccessibilityObject; case UnsafeNativeMethods.NavigateDirection.NextSibling: - if (_owner.DropDownStyle == ComboBoxStyle.Simple) { + if (_owner.DropDownStyle == ComboBoxStyle.Simple) + { return null; } var comboBoxAccessibleObject = _owner.AccessibilityObject as ComboBoxAccessibleObject; - if (comboBoxAccessibleObject != null) { + if (comboBoxAccessibleObject != null) + { int comboBoxChildFragmentCount = comboBoxAccessibleObject.GetChildFragmentCount(); - if (comboBoxChildFragmentCount > 1) { // DropDown button is next; + if (comboBoxChildFragmentCount > 1) + { // DropDown button is next; return comboBoxAccessibleObject.GetChildFragment(comboBoxChildFragmentCount - 1); } } @@ -4722,9 +5448,11 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga return null; case UnsafeNativeMethods.NavigateDirection.PreviousSibling: comboBoxAccessibleObject = _owner.AccessibilityObject as ComboBoxAccessibleObject; - if (comboBoxAccessibleObject != null) { + if (comboBoxAccessibleObject != null) + { var firstComboBoxChildFragment = comboBoxAccessibleObject.GetChildFragment(0); - if (RuntimeId != firstComboBoxChildFragment.RuntimeId) { + if (RuntimeId != firstComboBoxChildFragment.RuntimeId) + { return firstComboBoxChildFragment; } } @@ -4738,8 +5466,10 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga /// /// Gets the top level element. /// - internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot { - get { + internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot + { + get + { return _owner.AccessibilityObject; } } @@ -4749,9 +5479,11 @@ internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRo /// /// The accessible property ID. /// The accessible property value. - internal override object GetPropertyValue(int propertyID) { - switch (propertyID) { - case NativeMethods.UIA_RuntimeIdPropertyId: + internal override object GetPropertyValue(int propertyID) + { + switch (propertyID) + { + case NativeMethods.UIA_RuntimeIdPropertyId: return RuntimeId; case NativeMethods.UIA_BoundingRectanglePropertyId: return Bounds; @@ -4783,8 +5515,10 @@ internal override object GetPropertyValue(int propertyID) { } } - internal override UnsafeNativeMethods.IRawElementProviderSimple HostRawElementProvider { - get { + internal override UnsafeNativeMethods.IRawElementProviderSimple HostRawElementProvider + { + get + { UnsafeNativeMethods.IRawElementProviderSimple provider; UnsafeNativeMethods.UiaHostProviderFromHwnd(new HandleRef(this, _handle), out provider); return provider; @@ -4796,8 +5530,10 @@ internal override UnsafeNativeMethods.IRawElementProviderSimple HostRawElementPr /// /// Gets the runtime ID. /// - internal override int[] RuntimeId { - get { + internal override int[] RuntimeId + { + get + { var runtimeId = new int[2]; runtimeId[0] = RuntimeIDFirstItem; runtimeId[1] = GetHashCode(); @@ -4811,7 +5547,8 @@ internal override int[] RuntimeId { /// Represents the ComboBox's child (inner) list native window control accessible object with UI Automation provider functionality. /// [ComVisible(true)] - internal class ComboBoxChildListUiaProvider : ChildAccessibleObject { + internal class ComboBoxChildListUiaProvider : ChildAccessibleObject + { private const string COMBO_BOX_LIST_AUTOMATION_ID = "1000"; private ComboBox _owningComboBox; @@ -4822,7 +5559,8 @@ internal class ComboBoxChildListUiaProvider : ChildAccessibleObject { /// /// /// - public ComboBoxChildListUiaProvider(ComboBox owningComboBox, IntPtr childListControlhandle) : base(owningComboBox, childListControlhandle) { + public ComboBoxChildListUiaProvider(ComboBox owningComboBox, IntPtr childListControlhandle) : base(owningComboBox, childListControlhandle) + { _owningComboBox = owningComboBox; _childListControlhandle = childListControlhandle; } @@ -4833,15 +5571,19 @@ public ComboBoxChildListUiaProvider(ComboBox owningComboBox, IntPtr childListCon /// X coordinate. /// Y coordinate. /// The accessible object of corresponding element in the provided coordinates. - internal override UnsafeNativeMethods.IRawElementProviderFragment ElementProviderFromPoint(double x, double y) { + internal override UnsafeNativeMethods.IRawElementProviderFragment ElementProviderFromPoint(double x, double y) + { var systemIAccessible = GetSystemIAccessibleInternal(); - if (systemIAccessible != null) { + if (systemIAccessible != null) + { object result = systemIAccessible.accHitTest((int)x, (int)y); - if (result is int) { + if (result is int) + { int childId = (int)result; return GetChildFragment(childId - 1); } - else { + else + { return null; } } @@ -4854,13 +5596,16 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment ElementProvide /// /// Indicates the direction in which to navigate. /// Returns the element in the specified direction. - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - switch (direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { + switch (direction) + { case UnsafeNativeMethods.NavigateDirection.FirstChild: return GetChildFragment(0); case UnsafeNativeMethods.NavigateDirection.LastChild: var childFragmentCount = GetChildFragmentCount(); - if (childFragmentCount > 0) { + if (childFragmentCount > 0) + { return GetChildFragment(childFragmentCount - 1); } @@ -4873,14 +5618,18 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga /// /// Gets the top level element. /// - internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot { - get { + internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot + { + get + { return _owningComboBox.AccessibilityObject; } } - public AccessibleObject GetChildFragment(int index) { - if (index < 0 || index >= _owningComboBox.Items.Count) { + public AccessibleObject GetChildFragment(int index) + { + if (index < 0 || index >= _owningComboBox.Items.Count) + { return null; } @@ -4889,7 +5638,8 @@ public AccessibleObject GetChildFragment(int index) { return comboBoxAccessibleObject.ItemAccessibleObjects[item] as AccessibleObject; } - public int GetChildFragmentCount() { + public int GetChildFragmentCount() + { return _owningComboBox.Items.Count; } @@ -4898,8 +5648,10 @@ public int GetChildFragmentCount() { /// /// The accessible property ID. /// The accessible property value. - internal override object GetPropertyValue(int propertyID) { - switch (propertyID) { + internal override object GetPropertyValue(int propertyID) + { + switch (propertyID) + { case NativeMethods.UIA_RuntimeIdPropertyId: return RuntimeId; case NativeMethods.UIA_BoundingRectanglePropertyId: @@ -4938,20 +5690,24 @@ internal override object GetPropertyValue(int propertyID) { } } - internal override UnsafeNativeMethods.IRawElementProviderFragment GetFocus() { + internal override UnsafeNativeMethods.IRawElementProviderFragment GetFocus() + { return GetFocused(); } - public override AccessibleObject GetFocused() { + public override AccessibleObject GetFocused() + { int selectedIndex = _owningComboBox.SelectedIndex; return GetChildFragment(selectedIndex); } - internal override UnsafeNativeMethods.IRawElementProviderSimple[] GetSelection() { + internal override UnsafeNativeMethods.IRawElementProviderSimple[] GetSelection() + { int selectedIndex = _owningComboBox.SelectedIndex; AccessibleObject itemAccessibleObject = GetChildFragment(selectedIndex); - if (itemAccessibleObject != null) { + if (itemAccessibleObject != null) + { return new UnsafeNativeMethods.IRawElementProviderSimple[] { itemAccessibleObject }; @@ -4960,14 +5716,18 @@ internal override UnsafeNativeMethods.IRawElementProviderSimple[] GetSelection() return new UnsafeNativeMethods.IRawElementProviderSimple[0]; } - internal override bool CanSelectMultiple { - get { + internal override bool CanSelectMultiple + { + get + { return false; } } - - internal override bool IsSelectionRequired { - get { + + internal override bool IsSelectionRequired + { + get + { return true; } } @@ -4980,15 +5740,18 @@ internal override bool IsSelectionRequired { internal override bool IsPatternSupported(int patternId) { if (patternId == NativeMethods.UIA_LegacyIAccessiblePatternId || - patternId == NativeMethods.UIA_SelectionPatternId) { + patternId == NativeMethods.UIA_SelectionPatternId) + { return true; } return base.IsPatternSupported(patternId); } - internal override UnsafeNativeMethods.IRawElementProviderSimple HostRawElementProvider { - get { + internal override UnsafeNativeMethods.IRawElementProviderSimple HostRawElementProvider + { + get + { UnsafeNativeMethods.IRawElementProviderSimple provider; UnsafeNativeMethods.UiaHostProviderFromHwnd(new HandleRef(this, _childListControlhandle), out provider); return provider; @@ -4998,8 +5761,10 @@ internal override UnsafeNativeMethods.IRawElementProviderSimple HostRawElementPr /// /// Gets the runtime ID. /// - internal override int[] RuntimeId { - get { + internal override int[] RuntimeId + { + get + { var runtimeId = new int[3]; runtimeId[0] = RuntimeIDFirstItem; runtimeId[1] = (int)(long)_owningComboBox.Handle; @@ -5012,10 +5777,13 @@ internal override int[] RuntimeId { /// /// Gets the accessible state. /// - public override AccessibleStates State { - get { + public override AccessibleStates State + { + get + { AccessibleStates state = AccessibleStates.Focusable; - if (_owningComboBox.Focused) { + if (_owningComboBox.Focused) + { state |= AccessibleStates.Focused; } @@ -5028,7 +5796,8 @@ public override AccessibleStates State { /// Represents the ComboBox's child text (is used instead of inner Edit when style is DropDownList but not DropDown) accessible object. /// [ComVisible(true)] - internal class ComboBoxChildTextUiaProvider : AccessibleObject { + internal class ComboBoxChildTextUiaProvider : AccessibleObject + { private const int COMBOBOX_TEXT_ACC_ITEM_INDEX = 1; @@ -5038,15 +5807,18 @@ internal class ComboBoxChildTextUiaProvider : AccessibleObject { /// Initializes new instance of ComboBoxChildTextUiaProvider. /// /// The owning ComboBox control. - public ComboBoxChildTextUiaProvider(ComboBox owner) { + public ComboBoxChildTextUiaProvider(ComboBox owner) + { _owner = owner; } /// /// Gets the bounds. /// - public override Rectangle Bounds { - get { + public override Rectangle Bounds + { + get + { return _owner.AccessibilityObject.Bounds; } } @@ -5055,18 +5827,22 @@ public override Rectangle Bounds { /// Gets the child ID. /// /// The child ID. - internal override int GetChildId() { + internal override int GetChildId() + { return COMBOBOX_TEXT_ACC_ITEM_INDEX; } /// /// Gets or sets the accessible Name of ComboBox's child text element. /// - public override string Name { - get { + public override string Name + { + get + { return _owner.AccessibilityObject.Name ?? string.Empty; } - set { + set + { // Do nothing. } } @@ -5076,15 +5852,19 @@ public override string Name { /// /// Indicates the direction in which to navigate. /// Returns the element in the specified direction. - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - switch (direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { + switch (direction) + { case UnsafeNativeMethods.NavigateDirection.Parent: return _owner.AccessibilityObject; case UnsafeNativeMethods.NavigateDirection.NextSibling: var comboBoxAccessibleObject = _owner.AccessibilityObject as ComboBoxAccessibleObject; - if (comboBoxAccessibleObject != null) { + if (comboBoxAccessibleObject != null) + { int comboBoxChildFragmentCount = comboBoxAccessibleObject.GetChildFragmentCount(); - if (comboBoxChildFragmentCount > 1) { // DropDown button is next; + if (comboBoxChildFragmentCount > 1) + { // DropDown button is next; return comboBoxAccessibleObject.GetChildFragment(comboBoxChildFragmentCount - 1); } } @@ -5092,9 +5872,11 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga return null; case UnsafeNativeMethods.NavigateDirection.PreviousSibling: comboBoxAccessibleObject = _owner.AccessibilityObject as ComboBoxAccessibleObject; - if (comboBoxAccessibleObject != null) { + if (comboBoxAccessibleObject != null) + { var firstComboBoxChildFragment = comboBoxAccessibleObject.GetChildFragment(0); - if (RuntimeId != firstComboBoxChildFragment.RuntimeId) { + if (RuntimeId != firstComboBoxChildFragment.RuntimeId) + { return firstComboBoxChildFragment; } } @@ -5108,8 +5890,10 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga /// /// Gets the top level element. /// - internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot { - get { + internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot + { + get + { return _owner.AccessibilityObject; } } @@ -5119,8 +5903,10 @@ internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRo /// /// The accessible property ID. /// The accessible property value. - internal override object GetPropertyValue(int propertyID) { - switch (propertyID) { + internal override object GetPropertyValue(int propertyID) + { + switch (propertyID) + { case NativeMethods.UIA_RuntimeIdPropertyId: return RuntimeId; case NativeMethods.UIA_BoundingRectanglePropertyId: @@ -5150,8 +5936,10 @@ internal override object GetPropertyValue(int propertyID) { /// /// Gets the runtime ID. /// - internal override int[] RuntimeId { - get { + internal override int[] RuntimeId + { + get + { var runtimeId = new int[5]; runtimeId[0] = RuntimeIDFirstItem; runtimeId[1] = (int)(long)_owner.Handle; @@ -5166,10 +5954,13 @@ internal override int[] RuntimeId { /// /// Gets the accessible state. /// - public override AccessibleStates State { - get { + public override AccessibleStates State + { + get + { AccessibleStates state = AccessibleStates.Focusable; - if (_owner.Focused) { + if (_owner.Focused) + { state |= AccessibleStates.Focused; } @@ -5182,7 +5973,8 @@ public override AccessibleStates State { /// Represents the ComboBox child (inner) DropDown button accessible object with UI Automation functionality. /// [ComVisible(true)] - internal class ComboBoxChildDropDownButtonUiaProvider : AccessibleObject { + internal class ComboBoxChildDropDownButtonUiaProvider : AccessibleObject + { private const int COMBOBOX_DROPDOWN_BUTTON_ACC_ITEM_INDEX = 2; private ComboBox _owner; @@ -5192,7 +5984,8 @@ internal class ComboBoxChildDropDownButtonUiaProvider : AccessibleObject { /// /// The owning ComboBox control. /// The owning ComboBox control's handle. - public ComboBoxChildDropDownButtonUiaProvider(ComboBox owner, IntPtr comboBoxControlhandle) { + public ComboBoxChildDropDownButtonUiaProvider(ComboBox owner, IntPtr comboBoxControlhandle) + { _owner = owner; UseStdAccessibleObjects(comboBoxControlhandle); } @@ -5200,11 +5993,14 @@ public ComboBoxChildDropDownButtonUiaProvider(ComboBox owner, IntPtr comboBoxCon /// /// Gets or sets the accessible Name of ComboBox's child DropDown button. ("Open" or "Close" depending on stat of the DropDown) /// - public override string Name { - get { + public override string Name + { + get + { return get_accNameInternal(COMBOBOX_DROPDOWN_BUTTON_ACC_ITEM_INDEX); } - set { + set + { var systemIAccessible = GetSystemIAccessibleInternal(); systemIAccessible.set_accName(COMBOBOX_DROPDOWN_BUTTON_ACC_ITEM_INDEX, value); } @@ -5213,8 +6009,10 @@ public override string Name { /// /// Gets the DropDown button bounds. /// - public override Rectangle Bounds { - get { + public override Rectangle Bounds + { + get + { int left; int top; int width; @@ -5228,8 +6026,10 @@ public override Rectangle Bounds { /// /// Gets the DropDown button default action. /// - public override string DefaultAction { - get { + public override string DefaultAction + { + get + { var systemIAccessible = GetSystemIAccessibleInternal(); return systemIAccessible.accDefaultAction[COMBOBOX_DROPDOWN_BUTTON_ACC_ITEM_INDEX]; } @@ -5240,15 +6040,20 @@ public override string DefaultAction { /// /// Indicates the direction in which to navigate. /// Returns the element in the specified direction. - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - if (direction == UnsafeNativeMethods.NavigateDirection.Parent) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { + if (direction == UnsafeNativeMethods.NavigateDirection.Parent) + { return _owner.AccessibilityObject; } - else if (direction == UnsafeNativeMethods.NavigateDirection.PreviousSibling) { + else if (direction == UnsafeNativeMethods.NavigateDirection.PreviousSibling) + { var comboBoxAccessibleObject = _owner.AccessibilityObject as ComboBoxAccessibleObject; - if (comboBoxAccessibleObject != null) { + if (comboBoxAccessibleObject != null) + { int comboBoxChildFragmentCount = comboBoxAccessibleObject.GetChildFragmentCount(); - if (comboBoxChildFragmentCount > 1) { // Text or edit is previous; + if (comboBoxChildFragmentCount > 1) + { // Text or edit is previous; return comboBoxAccessibleObject.GetChildFragment(comboBoxChildFragmentCount - 1); } } @@ -5262,8 +6067,10 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga /// /// Gets the top level element. /// - internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot { - get { + internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot + { + get + { return _owner.AccessibilityObject; } } @@ -5272,7 +6079,8 @@ internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRo /// Gets the child accessible object ID. /// /// The child accessible object ID. - internal override int GetChildId() { + internal override int GetChildId() + { return COMBOBOX_DROPDOWN_BUTTON_ACC_ITEM_INDEX; } @@ -5281,8 +6089,10 @@ internal override int GetChildId() { /// /// The accessible property ID. /// The accessible property value. - internal override object GetPropertyValue(int propertyID) { - switch (propertyID) { + internal override object GetPropertyValue(int propertyID) + { + switch (propertyID) + { case NativeMethods.UIA_RuntimeIdPropertyId: return RuntimeId; case NativeMethods.UIA_BoundingRectanglePropertyId: @@ -5313,8 +6123,10 @@ internal override object GetPropertyValue(int propertyID) { /// /// Gets the help text. /// - public override string Help { - get { + public override string Help + { + get + { var systemIAccessible = GetSystemIAccessibleInternal(); return systemIAccessible.accHelp[COMBOBOX_DROPDOWN_BUTTON_ACC_ITEM_INDEX]; } @@ -5323,8 +6135,10 @@ public override string Help { /// /// Gets the keyboard shortcut. /// - public override string KeyboardShortcut { - get { + public override string KeyboardShortcut + { + get + { var systemIAccessible = GetSystemIAccessibleInternal(); return systemIAccessible.get_accKeyboardShortcut(COMBOBOX_DROPDOWN_BUTTON_ACC_ITEM_INDEX); } @@ -5335,9 +6149,11 @@ public override string KeyboardShortcut { /// /// The pattern ID. /// True if specified - internal override bool IsPatternSupported(int patternId) { + internal override bool IsPatternSupported(int patternId) + { if (patternId == NativeMethods.UIA_LegacyIAccessiblePatternId || - patternId == NativeMethods.UIA_InvokePatternId) { + patternId == NativeMethods.UIA_InvokePatternId) + { return true; } @@ -5347,8 +6163,10 @@ internal override bool IsPatternSupported(int patternId) { /// /// Gets the accessible role. /// - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { var systemIAccessible = GetSystemIAccessibleInternal(); return (AccessibleRole)systemIAccessible.get_accRole(COMBOBOX_DROPDOWN_BUTTON_ACC_ITEM_INDEX); } @@ -5357,8 +6175,10 @@ public override AccessibleRole Role { /// /// Gets the runtime ID. /// - internal override int[] RuntimeId { - get { + internal override int[] RuntimeId + { + get + { var runtimeId = new int[5]; runtimeId[0] = RuntimeIDFirstItem; runtimeId[1] = (int)(long)_owner.Handle; @@ -5376,8 +6196,10 @@ internal override int[] RuntimeId { /// /// Gets the accessible state. /// - public override AccessibleStates State { - get { + public override AccessibleStates State + { + get + { var systemIAccessible = GetSystemIAccessibleInternal(); return (AccessibleStates)systemIAccessible.get_accState(COMBOBOX_DROPDOWN_BUTTON_ACC_ITEM_INDEX); } @@ -5387,7 +6209,8 @@ public override AccessibleStates State { /// /// This subclasses an autocomplete window so that we can determine if control is inside the AC wndproc. /// - private sealed class ACNativeWindow : NativeWindow { + private sealed class ACNativeWindow : NativeWindow + { static internal int inWndProcCnt; //this hashtable can contain null for those ACWindows we find, but are sure are not ours. static private Hashtable ACWindows = new Hashtable(); @@ -5395,7 +6218,8 @@ private sealed class ACNativeWindow : NativeWindow { [ SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") ] - internal ACNativeWindow(IntPtr acHandle) { + internal ACNativeWindow(IntPtr acHandle) + { Debug.Assert(!ACWindows.ContainsKey(acHandle)); this.AssignHandle(acHandle); ACWindows.Add(acHandle, this); @@ -5405,27 +6229,36 @@ internal ACNativeWindow(IntPtr acHandle) { } [SuppressMessage("Microsoft.Performance", "CA1806:DoNotIgnoreMethodResults")] - private static bool RegisterACWindowRecursive(IntPtr handle, IntPtr lparam) { - if (!ACWindows.ContainsKey(handle)) { + private static bool RegisterACWindowRecursive(IntPtr handle, IntPtr lparam) + { + if (!ACWindows.ContainsKey(handle)) + { ACNativeWindow newAC = new ACNativeWindow(handle); } return true; } - internal bool Visible { - get { + internal bool Visible + { + get + { return SafeNativeMethods.IsWindowVisible(new HandleRef(this, Handle)); } } - static internal bool AutoCompleteActive { - get { - if (inWndProcCnt>0) { + static internal bool AutoCompleteActive + { + get + { + if (inWndProcCnt > 0) + { return true; } - foreach(object o in ACWindows.Values) { + foreach (object o in ACWindows.Values) + { ACNativeWindow window = o as ACNativeWindow; - if (window != null && window.Visible) { + if (window != null && window.Visible) + { return true; } } @@ -5433,34 +6266,44 @@ static internal bool AutoCompleteActive { } } - protected override void WndProc(ref Message m) { + protected override void WndProc(ref Message m) + { inWndProcCnt++; - try { + try + { base.WndProc(ref m); } - finally { + finally + { inWndProcCnt--; } - if (m.Msg == Interop.WindowMessages.WM_NCDESTROY) { + if (m.Msg == Interop.WindowMessages.WM_NCDESTROY) + { Debug.Assert(ACWindows.ContainsKey(this.Handle)); ACWindows.Remove(this.Handle); //so we do not leak ac windows. } } [SuppressMessage("Microsoft.Performance", "CA1806:DoNotIgnoreMethodResults")] - internal static void RegisterACWindow(IntPtr acHandle, bool subclass) { - if (subclass && ACWindows.ContainsKey(acHandle)) { - if (ACWindows[acHandle] == null) { + internal static void RegisterACWindow(IntPtr acHandle, bool subclass) + { + if (subclass && ACWindows.ContainsKey(acHandle)) + { + if (ACWindows[acHandle] == null) + { ACWindows.Remove(acHandle); //if an external handle got destroyed, dont let it stop us. } } - if (!ACWindows.ContainsKey(acHandle)) { - if (subclass) { + if (!ACWindows.ContainsKey(acHandle)) + { + if (subclass) + { ACNativeWindow newAC = new ACNativeWindow(acHandle); } - else { + else + { ACWindows.Add(acHandle, null); } } @@ -5471,14 +6314,18 @@ internal static void RegisterACWindow(IntPtr acHandle, bool subclass) { /// null entries are ACWindows that belong to someone else. /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")] // Perfectly acceptible when dealing with PropertyDescriptors - internal static void ClearNullACWindows() { + internal static void ClearNullACWindows() + { ArrayList nulllist = new ArrayList(); - foreach (DictionaryEntry e in ACWindows) { - if (e.Value == null) { + foreach (DictionaryEntry e in ACWindows) + { + if (e.Value == null) + { nulllist.Add(e.Key); } } - foreach (IntPtr handle in nulllist) { + foreach (IntPtr handle in nulllist) + { ACWindows.Remove(handle); } } @@ -5487,17 +6334,21 @@ internal static void ClearNullACWindows() { /// /// This finds all autcomplete windows that belong to the active thread. /// - private class AutoCompleteDropDownFinder { + private class AutoCompleteDropDownFinder + { private const int MaxClassName = 256; private const string AutoCompleteClassName = "Auto-Suggest Dropdown"; bool shouldSubClass = false; //nonstatic - internal void FindDropDowns() { + internal void FindDropDowns() + { FindDropDowns(true); } - internal void FindDropDowns(bool subclass) { - if (!subclass) { + internal void FindDropDowns(bool subclass) + { + if (!subclass) + { //generating a before snapshot -- lets lose the null handles ACNativeWindow.ClearNullACWindows(); } @@ -5506,56 +6357,65 @@ internal void FindDropDowns(bool subclass) { UnsafeNativeMethods.EnumThreadWindows(SafeNativeMethods.GetCurrentThreadId(), new NativeMethods.EnumThreadWindowsCallback(this.Callback), new HandleRef(null, IntPtr.Zero)); } - private bool Callback(IntPtr hWnd, IntPtr lParam) { + private bool Callback(IntPtr hWnd, IntPtr lParam) + { HandleRef hRef = new HandleRef(null, hWnd); // Check class name and see if it's visible - if (GetClassName(hRef) == AutoCompleteClassName) { + if (GetClassName(hRef) == AutoCompleteClassName) + { ACNativeWindow.RegisterACWindow(hRef.Handle, shouldSubClass); } return true; } - static string GetClassName(HandleRef hRef) { + static string GetClassName(HandleRef hRef) + { StringBuilder sb = new StringBuilder(MaxClassName); UnsafeNativeMethods.GetClassName(hRef, sb, MaxClassName); return sb.ToString(); } } - - private FlatComboAdapter FlatComboBoxAdapter { - get { - FlatComboAdapter comboAdapter = Properties.GetObject(PropFlatComboAdapter) as FlatComboAdapter; - if (comboAdapter == null || !comboAdapter.IsValid(this)) { + + private FlatComboAdapter FlatComboBoxAdapter + { + get + { + FlatComboAdapter comboAdapter = Properties.GetObject(PropFlatComboAdapter) as FlatComboAdapter; + if (comboAdapter == null || !comboAdapter.IsValid(this)) + { comboAdapter = CreateFlatComboAdapterInstance(); Properties.SetObject(PropFlatComboAdapter, comboAdapter); - } - return comboAdapter; - } + } + return comboAdapter; + } } - internal virtual FlatComboAdapter CreateFlatComboAdapterInstance() { + internal virtual FlatComboAdapter CreateFlatComboAdapterInstance() + { return new FlatComboAdapter(this,/*smallButton=*/false); } - - internal class FlatComboAdapter { - Rectangle outerBorder; - Rectangle innerBorder; - Rectangle innerInnerBorder; - internal Rectangle dropDownRect; - Rectangle whiteFillRect; - Rectangle clientRect; - RightToLeft origRightToLeft; // The combo box's RTL value when we were created + internal class FlatComboAdapter + { + Rectangle outerBorder; + Rectangle innerBorder; + Rectangle innerInnerBorder; + internal Rectangle dropDownRect; + Rectangle whiteFillRect; + Rectangle clientRect; + + RightToLeft origRightToLeft; // The combo box's RTL value when we were created - private const int WhiteFillRectWidth = 5; // used for making the button look smaller than it is + private const int WhiteFillRectWidth = 5; // used for making the button look smaller than it is - private static int OFFSET_2PIXELS = 2; - protected static int Offset2Pixels = OFFSET_2PIXELS; + private static int OFFSET_2PIXELS = 2; + protected static int Offset2Pixels = OFFSET_2PIXELS; - public FlatComboAdapter(ComboBox comboBox, bool smallButton) { + public FlatComboAdapter(ComboBox comboBox, bool smallButton) + { // adapter is re-created when combobox is resized, see IsValid method, thus we don't need to handle DPI changed explicitly Offset2Pixels = comboBox.LogicalToDeviceUnits(OFFSET_2PIXELS); @@ -5568,7 +6428,8 @@ public FlatComboAdapter(ComboBox comboBox, bool smallButton) { // fill in several pixels of the dropdown rect with white so that it looks like the combo button is thinner. - if (smallButton) { + if (smallButton) + { whiteFillRect = dropDownRect; whiteFillRect.Width = WhiteFillRectWidth; dropDownRect.X += WhiteFillRectWidth; @@ -5578,7 +6439,8 @@ public FlatComboAdapter(ComboBox comboBox, bool smallButton) { origRightToLeft = comboBox.RightToLeft; - if (origRightToLeft == RightToLeft.Yes) { + if (origRightToLeft == RightToLeft.Yes) + { innerBorder.X = clientRect.Width - innerBorder.Right; innerInnerBorder.X = clientRect.Width - innerInnerBorder.Right; dropDownRect.X = clientRect.Width - dropDownRect.Right; @@ -5586,180 +6448,213 @@ public FlatComboAdapter(ComboBox comboBox, bool smallButton) { } } - - public bool IsValid(ComboBox combo) { - return (combo.ClientRectangle == clientRect && combo.RightToLeft == origRightToLeft); - } - - /// - /// Paints over the edges of the combo box to make it appear flat. - /// - public virtual void DrawFlatCombo(ComboBox comboBox, Graphics g) { - if (comboBox.DropDownStyle == ComboBoxStyle.Simple){ - return; - } - - Color outerBorderColor = GetOuterBorderColor(comboBox); - Color innerBorderColor = GetInnerBorderColor(comboBox); - bool rightToLeft = comboBox.RightToLeft == RightToLeft.Yes; - - // draw the drop down - DrawFlatComboDropDown(comboBox, g, dropDownRect); - - // when we are disabled there is one line of color that seems to eek through if backcolor is set - // so lets erase it. - if (!LayoutUtils.IsZeroWidthOrHeight(whiteFillRect)) { + + public bool IsValid(ComboBox combo) + { + return (combo.ClientRectangle == clientRect && combo.RightToLeft == origRightToLeft); + } + + /// + /// Paints over the edges of the combo box to make it appear flat. + /// + public virtual void DrawFlatCombo(ComboBox comboBox, Graphics g) + { + if (comboBox.DropDownStyle == ComboBoxStyle.Simple) + { + return; + } + + Color outerBorderColor = GetOuterBorderColor(comboBox); + Color innerBorderColor = GetInnerBorderColor(comboBox); + bool rightToLeft = comboBox.RightToLeft == RightToLeft.Yes; + + // draw the drop down + DrawFlatComboDropDown(comboBox, g, dropDownRect); + + // when we are disabled there is one line of color that seems to eek through if backcolor is set + // so lets erase it. + if (!LayoutUtils.IsZeroWidthOrHeight(whiteFillRect)) + { // fill in two more pixels with white so it looks smaller. - using (Brush b = new SolidBrush(innerBorderColor)) { - g.FillRectangle(b, whiteFillRect); + using (Brush b = new SolidBrush(innerBorderColor)) + { + g.FillRectangle(b, whiteFillRect); } - } - - - - // Draw the outer border - if (outerBorderColor.IsSystemColor) { - Pen outerBorderPen = SystemPens.FromSystemColor(outerBorderColor); - g.DrawRectangle(outerBorderPen, outerBorder); - if (rightToLeft) { - g.DrawRectangle(outerBorderPen, new Rectangle(outerBorder.X, outerBorder.Y, dropDownRect.Width + 1, outerBorder.Height)); - } - else { - g.DrawRectangle(outerBorderPen, new Rectangle(dropDownRect.X, outerBorder.Y, outerBorder.Right - dropDownRect.X, outerBorder.Height)); - } - } - else { - using (Pen outerBorderPen = new Pen(outerBorderColor)) { - g.DrawRectangle(outerBorderPen, outerBorder); - if (rightToLeft) { - g.DrawRectangle(outerBorderPen, new Rectangle(outerBorder.X, outerBorder.Y, dropDownRect.Width + 1, outerBorder.Height)); - } - else { - g.DrawRectangle(outerBorderPen, new Rectangle(dropDownRect.X, outerBorder.Y, outerBorder.Right - dropDownRect.X, outerBorder.Height)); - } - } - } - - // Draw the inner border - if (innerBorderColor.IsSystemColor) { - Pen innerBorderPen = SystemPens.FromSystemColor(innerBorderColor); - g.DrawRectangle(innerBorderPen, innerBorder); - g.DrawRectangle(innerBorderPen, innerInnerBorder); - } - else { - using (Pen innerBorderPen = new Pen(innerBorderColor)) { - g.DrawRectangle(innerBorderPen, innerBorder); - g.DrawRectangle(innerBorderPen, innerInnerBorder); - } - } - - - - // Draw a dark border around everything if we're in popup mode - if ((!comboBox.Enabled) ||(comboBox.FlatStyle == FlatStyle.Popup)) { - bool focused = comboBox.ContainsFocus || comboBox.MouseIsOver; - Color borderPenColor = GetPopupOuterBorderColor(comboBox, focused); - - using (Pen borderPen = new Pen(borderPenColor)) { - - Pen innerPen = (comboBox.Enabled) ? borderPen : SystemPens.Control; - - // around the dropdown - if (rightToLeft) { - g.DrawRectangle(innerPen, new Rectangle(outerBorder.X, outerBorder.Y, dropDownRect.Width + 1, outerBorder.Height)); - } - else { - g.DrawRectangle(innerPen, new Rectangle(dropDownRect.X, outerBorder.Y, outerBorder.Right - dropDownRect.X, outerBorder.Height)); - } - - // around the whole combobox. - g.DrawRectangle(borderPen, outerBorder); - - } - } - - } - - /// - /// Paints over the edges of the combo box to make it appear flat. - /// - - protected virtual void DrawFlatComboDropDown(ComboBox comboBox, Graphics g, Rectangle dropDownRect) { - + } + + + + // Draw the outer border + if (outerBorderColor.IsSystemColor) + { + Pen outerBorderPen = SystemPens.FromSystemColor(outerBorderColor); + g.DrawRectangle(outerBorderPen, outerBorder); + if (rightToLeft) + { + g.DrawRectangle(outerBorderPen, new Rectangle(outerBorder.X, outerBorder.Y, dropDownRect.Width + 1, outerBorder.Height)); + } + else + { + g.DrawRectangle(outerBorderPen, new Rectangle(dropDownRect.X, outerBorder.Y, outerBorder.Right - dropDownRect.X, outerBorder.Height)); + } + } + else + { + using (Pen outerBorderPen = new Pen(outerBorderColor)) + { + g.DrawRectangle(outerBorderPen, outerBorder); + if (rightToLeft) + { + g.DrawRectangle(outerBorderPen, new Rectangle(outerBorder.X, outerBorder.Y, dropDownRect.Width + 1, outerBorder.Height)); + } + else + { + g.DrawRectangle(outerBorderPen, new Rectangle(dropDownRect.X, outerBorder.Y, outerBorder.Right - dropDownRect.X, outerBorder.Height)); + } + } + } + + // Draw the inner border + if (innerBorderColor.IsSystemColor) + { + Pen innerBorderPen = SystemPens.FromSystemColor(innerBorderColor); + g.DrawRectangle(innerBorderPen, innerBorder); + g.DrawRectangle(innerBorderPen, innerInnerBorder); + } + else + { + using (Pen innerBorderPen = new Pen(innerBorderColor)) + { + g.DrawRectangle(innerBorderPen, innerBorder); + g.DrawRectangle(innerBorderPen, innerInnerBorder); + } + } + + + + // Draw a dark border around everything if we're in popup mode + if ((!comboBox.Enabled) || (comboBox.FlatStyle == FlatStyle.Popup)) + { + bool focused = comboBox.ContainsFocus || comboBox.MouseIsOver; + Color borderPenColor = GetPopupOuterBorderColor(comboBox, focused); + + using (Pen borderPen = new Pen(borderPenColor)) + { + + Pen innerPen = (comboBox.Enabled) ? borderPen : SystemPens.Control; + + // around the dropdown + if (rightToLeft) + { + g.DrawRectangle(innerPen, new Rectangle(outerBorder.X, outerBorder.Y, dropDownRect.Width + 1, outerBorder.Height)); + } + else + { + g.DrawRectangle(innerPen, new Rectangle(dropDownRect.X, outerBorder.Y, outerBorder.Right - dropDownRect.X, outerBorder.Height)); + } + + // around the whole combobox. + g.DrawRectangle(borderPen, outerBorder); + + } + } + + } + + /// + /// Paints over the edges of the combo box to make it appear flat. + /// + + protected virtual void DrawFlatComboDropDown(ComboBox comboBox, Graphics g, Rectangle dropDownRect) + { + g.FillRectangle(SystemBrushes.Control, dropDownRect); Brush brush = (comboBox.Enabled) ? SystemBrushes.ControlText : SystemBrushes.ControlDark; - - Point middle = new Point(dropDownRect.Left + dropDownRect.Width / 2, dropDownRect.Top + dropDownRect.Height / 2); - if (origRightToLeft == RightToLeft.Yes) { - // if the width is odd - favor pushing it over one pixel left. + + Point middle = new Point(dropDownRect.Left + dropDownRect.Width / 2, dropDownRect.Top + dropDownRect.Height / 2); + if (origRightToLeft == RightToLeft.Yes) + { + // if the width is odd - favor pushing it over one pixel left. middle.X -= (dropDownRect.Width % 2); - } - else { - // if the width is odd - favor pushing it over one pixel right. - middle.X += (dropDownRect.Width % 2); - } - - g.FillPolygon(brush, new Point[] { + } + else + { + // if the width is odd - favor pushing it over one pixel right. + middle.X += (dropDownRect.Width % 2); + } + + g.FillPolygon(brush, new Point[] { new Point(middle.X - Offset2Pixels, middle.Y - 1), new Point(middle.X + Offset2Pixels + 1, middle.Y - 1), new Point(middle.X, middle.Y + Offset2Pixels) }); - } - - protected virtual Color GetOuterBorderColor(ComboBox comboBox) { + } + + protected virtual Color GetOuterBorderColor(ComboBox comboBox) + { return (comboBox.Enabled) ? SystemColors.Window : SystemColors.ControlDark; - } + } - protected virtual Color GetPopupOuterBorderColor(ComboBox comboBox, bool focused) { - if (!comboBox.Enabled) { + protected virtual Color GetPopupOuterBorderColor(ComboBox comboBox, bool focused) + { + if (!comboBox.Enabled) + { return SystemColors.ControlDark; } return (focused) ? SystemColors.ControlDark : SystemColors.Window; - } - - protected virtual Color GetInnerBorderColor(ComboBox comboBox) { + } + + protected virtual Color GetInnerBorderColor(ComboBox comboBox) + { return (comboBox.Enabled) ? comboBox.BackColor : SystemColors.Control; - } - - // this eliminates flicker by removing the pieces we're going to paint ourselves from - // the update region. Note the UpdateRegionBox is the bounding box of the actual update region. - // this is just here so we can quickly eliminate rectangles that arent in the update region. - public void ValidateOwnerDrawRegions(ComboBox comboBox, Rectangle updateRegionBox) { - NativeMethods.RECT validRect; - if (comboBox != null) { return; } - Rectangle topOwnerDrawArea = new Rectangle(0,0,comboBox.Width, innerBorder.Top); - Rectangle bottomOwnerDrawArea = new Rectangle(0,innerBorder.Bottom,comboBox.Width, comboBox.Height-innerBorder.Bottom); - Rectangle leftOwnerDrawArea = new Rectangle(0,0,innerBorder.Left, comboBox.Height); - Rectangle rightOwnerDrawArea = new Rectangle(innerBorder.Right,0,comboBox.Width - innerBorder.Right,comboBox.Height); - - if (topOwnerDrawArea.IntersectsWith(updateRegionBox)) { - validRect = new NativeMethods.RECT(topOwnerDrawArea); - SafeNativeMethods.ValidateRect(new HandleRef(comboBox, comboBox.Handle), ref validRect); - } - - if (bottomOwnerDrawArea.IntersectsWith(updateRegionBox)) { - validRect = new NativeMethods.RECT(bottomOwnerDrawArea); - SafeNativeMethods.ValidateRect(new HandleRef(comboBox, comboBox.Handle), ref validRect); - } - - if (leftOwnerDrawArea.IntersectsWith(updateRegionBox)) { - validRect = new NativeMethods.RECT(leftOwnerDrawArea); - SafeNativeMethods.ValidateRect(new HandleRef(comboBox, comboBox.Handle), ref validRect); - } - - if (rightOwnerDrawArea.IntersectsWith(updateRegionBox)) { - validRect = new NativeMethods.RECT(rightOwnerDrawArea); - SafeNativeMethods.ValidateRect(new HandleRef(comboBox, comboBox.Handle), ref validRect); - } - - } + } + + // this eliminates flicker by removing the pieces we're going to paint ourselves from + // the update region. Note the UpdateRegionBox is the bounding box of the actual update region. + // this is just here so we can quickly eliminate rectangles that arent in the update region. + public void ValidateOwnerDrawRegions(ComboBox comboBox, Rectangle updateRegionBox) + { + NativeMethods.RECT validRect; + if (comboBox != null) + { return; } + Rectangle topOwnerDrawArea = new Rectangle(0, 0, comboBox.Width, innerBorder.Top); + Rectangle bottomOwnerDrawArea = new Rectangle(0, innerBorder.Bottom, comboBox.Width, comboBox.Height - innerBorder.Bottom); + Rectangle leftOwnerDrawArea = new Rectangle(0, 0, innerBorder.Left, comboBox.Height); + Rectangle rightOwnerDrawArea = new Rectangle(innerBorder.Right, 0, comboBox.Width - innerBorder.Right, comboBox.Height); + + if (topOwnerDrawArea.IntersectsWith(updateRegionBox)) + { + validRect = new NativeMethods.RECT(topOwnerDrawArea); + SafeNativeMethods.ValidateRect(new HandleRef(comboBox, comboBox.Handle), ref validRect); + } + + if (bottomOwnerDrawArea.IntersectsWith(updateRegionBox)) + { + validRect = new NativeMethods.RECT(bottomOwnerDrawArea); + SafeNativeMethods.ValidateRect(new HandleRef(comboBox, comboBox.Handle), ref validRect); + } + + if (leftOwnerDrawArea.IntersectsWith(updateRegionBox)) + { + validRect = new NativeMethods.RECT(leftOwnerDrawArea); + SafeNativeMethods.ValidateRect(new HandleRef(comboBox, comboBox.Handle), ref validRect); + } + + if (rightOwnerDrawArea.IntersectsWith(updateRegionBox)) + { + validRect = new NativeMethods.RECT(rightOwnerDrawArea); + SafeNativeMethods.ValidateRect(new HandleRef(comboBox, comboBox.Handle), ref validRect); + } + + } } /// /// Represents the ComboBox child native window type. /// - private enum ChildWindowType { + private enum ChildWindowType + { ListBox, Edit, DropDownList diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBoxRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBoxRenderer.cs index 504721829d3..c4e5fde21bc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBoxRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBoxRenderer.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Drawing; @@ -17,7 +18,8 @@ namespace System.Windows.Forms { /// This is a rendering class for the ComboBox control. /// /// - public sealed class ComboBoxRenderer { + public sealed class ComboBoxRenderer + { //Make this per-thread, so that different threads can safely use these methods. [ThreadStatic] @@ -26,7 +28,8 @@ public sealed class ComboBoxRenderer { private static readonly VisualStyleElement TextBoxElement = VisualStyleElement.TextBox.TextEdit.Normal; //cannot instantiate - private ComboBoxRenderer() { + private ComboBoxRenderer() + { } /// @@ -35,19 +38,24 @@ private ComboBoxRenderer() { /// otherwise returns false. /// /// - public static bool IsSupported { - get { + public static bool IsSupported + { + get + { return VisualStyleRenderer.IsSupported; // no downlevel support } } - private static void DrawBackground(Graphics g, Rectangle bounds, ComboBoxState state) { + private static void DrawBackground(Graphics g, Rectangle bounds, ComboBoxState state) + { visualStyleRenderer.DrawBackground(g, bounds); //for disabled comboboxes, comctl does not use the window backcolor, so // we don't refill here in that case. - if (state != ComboBoxState.Disabled) { + if (state != ComboBoxState.Disabled) + { Color windowColor = visualStyleRenderer.GetColor(ColorProperty.FillColor); - if (windowColor != SystemColors.Window) { + if (windowColor != SystemColors.Window) + { Rectangle fillRect = visualStyleRenderer.GetBackgroundContentRectangle(g, bounds); fillRect.Inflate(-2, -2); //then we need to re-fill the background. @@ -64,11 +72,14 @@ private static void DrawBackground(Graphics g, Rectangle bounds, ComboBoxState s [ SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally ] - public static void DrawTextBox(Graphics g, Rectangle bounds, ComboBoxState state) { - if (visualStyleRenderer == null) { + public static void DrawTextBox(Graphics g, Rectangle bounds, ComboBoxState state) + { + if (visualStyleRenderer == null) + { visualStyleRenderer = new VisualStyleRenderer(TextBoxElement.ClassName, TextBoxElement.Part, (int)state); } - else { + else + { visualStyleRenderer.SetParameters(TextBoxElement.ClassName, TextBoxElement.Part, (int)state); } @@ -80,7 +91,8 @@ public static void DrawTextBox(Graphics g, Rectangle bounds, ComboBoxState state /// Renders the textbox part of a ComboBox control. /// /// - public static void DrawTextBox(Graphics g, Rectangle bounds, string comboBoxText, Font font, ComboBoxState state) { + public static void DrawTextBox(Graphics g, Rectangle bounds, string comboBoxText, Font font, ComboBoxState state) + { DrawTextBox(g, bounds, comboBoxText, font, TextFormatFlags.TextBoxControl, state); } @@ -89,7 +101,8 @@ public static void DrawTextBox(Graphics g, Rectangle bounds, string comboBoxText /// Renders the textbox part of a ComboBox control. /// /// - public static void DrawTextBox(Graphics g, Rectangle bounds, string comboBoxText, Font font, Rectangle textBounds, ComboBoxState state) { + public static void DrawTextBox(Graphics g, Rectangle bounds, string comboBoxText, Font font, Rectangle textBounds, ComboBoxState state) + { DrawTextBox(g, bounds, comboBoxText, font, textBounds, TextFormatFlags.TextBoxControl, state); } @@ -98,16 +111,19 @@ public static void DrawTextBox(Graphics g, Rectangle bounds, string comboBoxText /// Renders the textbox part of a ComboBox control. /// /// - public static void DrawTextBox(Graphics g, Rectangle bounds, string comboBoxText, Font font, TextFormatFlags flags, ComboBoxState state) { - if (visualStyleRenderer == null) { + public static void DrawTextBox(Graphics g, Rectangle bounds, string comboBoxText, Font font, TextFormatFlags flags, ComboBoxState state) + { + if (visualStyleRenderer == null) + { visualStyleRenderer = new VisualStyleRenderer(TextBoxElement.ClassName, TextBoxElement.Part, (int)state); } - else { + else + { visualStyleRenderer.SetParameters(TextBoxElement.ClassName, TextBoxElement.Part, (int)state); } Rectangle textBounds = visualStyleRenderer.GetBackgroundContentRectangle(g, bounds); - textBounds.Inflate(-2,-2); + textBounds.Inflate(-2, -2); DrawTextBox(g, bounds, comboBoxText, font, textBounds, flags, state); } @@ -119,11 +135,14 @@ public static void DrawTextBox(Graphics g, Rectangle bounds, string comboBoxText [ SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally ] - public static void DrawTextBox(Graphics g, Rectangle bounds, string comboBoxText, Font font, Rectangle textBounds, TextFormatFlags flags, ComboBoxState state) { - if (visualStyleRenderer == null) { + public static void DrawTextBox(Graphics g, Rectangle bounds, string comboBoxText, Font font, Rectangle textBounds, TextFormatFlags flags, ComboBoxState state) + { + if (visualStyleRenderer == null) + { visualStyleRenderer = new VisualStyleRenderer(TextBoxElement.ClassName, TextBoxElement.Part, (int)state); } - else { + else + { visualStyleRenderer.SetParameters(TextBoxElement.ClassName, TextBoxElement.Part, (int)state); } @@ -140,7 +159,8 @@ public static void DrawTextBox(Graphics g, Rectangle bounds, string comboBoxText [ SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally ] - public static void DrawDropDownButton(Graphics g, Rectangle bounds, ComboBoxState state) { + public static void DrawDropDownButton(Graphics g, Rectangle bounds, ComboBoxState state) + { DrawDropDownButtonForHandle(g, bounds, state, IntPtr.Zero); } @@ -154,11 +174,14 @@ public static void DrawDropDownButton(Graphics g, Rectangle bounds, ComboBoxStat [ SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally ] - internal static void DrawDropDownButtonForHandle(Graphics g, Rectangle bounds, ComboBoxState state, IntPtr handle) { - if (visualStyleRenderer == null) { + internal static void DrawDropDownButtonForHandle(Graphics g, Rectangle bounds, ComboBoxState state, IntPtr handle) + { + if (visualStyleRenderer == null) + { visualStyleRenderer = new VisualStyleRenderer(ComboBoxElement.ClassName, ComboBoxElement.Part, (int)state); } - else { + else + { visualStyleRenderer.SetParameters(ComboBoxElement.ClassName, ComboBoxElement.Part, (int)state); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Command.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Command.cs index 1794e7a9f09..4941ad5170d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Command.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Command.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -12,10 +13,11 @@ namespace System.Windows.Forms { using System.ComponentModel; using System.Windows.Forms; using System.Drawing; - + using Microsoft.Win32; - internal class Command : WeakReference { + internal class Command : WeakReference + { private static Command[] cmds; private static int icmdTry; @@ -26,26 +28,33 @@ internal class Command : WeakReference { internal int id; public Command(ICommandExecutor target) - : base(target, false) { + : base(target, false) + { AssignID(this); } - public virtual int ID { - get { + public virtual int ID + { + get + { return id; } } [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] - protected static void AssignID(Command cmd) { - lock(internalSyncObject) { + protected static void AssignID(Command cmd) + { + lock (internalSyncObject) + { int icmd; - if (null == cmds) { + if (null == cmds) + { cmds = new Command[20]; icmd = 0; } - else { + else + { Debug.Assert(cmds.Length > 0, "why is cmds.Length zero?"); Debug.Assert(icmdTry >= 0, "why is icmdTry negative?"); @@ -56,36 +65,42 @@ protected static void AssignID(Command cmd) { // First look for an empty slot (starting at icmdTry). for (icmd = icmdTry; icmd < icmdLim; icmd++) - if (null == cmds[icmd]) goto FindSlotComplete; + if (null == cmds[icmd]) + goto FindSlotComplete; for (icmd = 0; icmd < icmdTry; icmd++) - if (null == cmds[icmd]) goto FindSlotComplete; + if (null == cmds[icmd]) + goto FindSlotComplete; // All slots have Command objects in them. Look for a command // with a null referent. for (icmd = 0; icmd < icmdLim; icmd++) - if (null == cmds[icmd].Target) goto FindSlotComplete; + if (null == cmds[icmd].Target) + goto FindSlotComplete; // Grow the array. icmd = cmds.Length; icmdLim = Math.Min(idLim - idMin, 2 * icmd); - if (icmdLim <= icmd) { + if (icmdLim <= icmd) + { // Already at maximal size. Do a garbage collect and look again. GC.Collect(); - for (icmd = 0; icmd < icmdLim; icmd++) { + for (icmd = 0; icmd < icmdLim; icmd++) + { if (null == cmds[icmd] || null == cmds[icmd].Target) goto FindSlotComplete; } throw new ArgumentException(SR.CommandIdNotAllocated); } - else { + else + { Command[] newCmds = new Command[icmdLim]; Array.Copy(cmds, 0, newCmds, 0, icmd); cmds = newCmds; } } -FindSlotComplete: + FindSlotComplete: cmd.id = icmd + idMin; Debug.Assert(cmd.id >= idMin && cmd.id < idLim, "generated command id out of range"); @@ -95,17 +110,20 @@ protected static void AssignID(Command cmd) { } } - public static bool DispatchID(int id) { + public static bool DispatchID(int id) + { Command cmd = GetCommandFromID(id); if (null == cmd) return false; return cmd.Invoke(); } - protected static void Dispose(Command cmd) { + protected static void Dispose(Command cmd) + { lock (internalSyncObject) { - if (cmd.id >= idMin) { + if (cmd.id >= idMin) + { cmd.Target = null; if (cmds[cmd.id - idMin] == cmd) cmds[cmd.id - idMin] = null; @@ -114,12 +132,14 @@ protected static void Dispose(Command cmd) { } } - public virtual void Dispose() { + public virtual void Dispose() + { if (id >= idMin) Dispose(this); } - public static Command GetCommandFromID(int id) { + public static Command GetCommandFromID(int id) + { lock (internalSyncObject) { if (null == cmds) @@ -131,7 +151,8 @@ public static Command GetCommandFromID(int id) { } } - public virtual bool Invoke() { + public virtual bool Invoke() + { object target = Target; if (!(target is ICommandExecutor)) return false; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentManagerBroker.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentManagerBroker.cs index 28506df5399..a741bce1bed 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentManagerBroker.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentManagerBroker.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System; @@ -78,7 +79,8 @@ namespace System.Windows.Forms { /// CMProxy: IMsoComponentManager half of ComponentManagerProxy /// AC: Application's IMsoComponent implementation /// - internal sealed class ComponentManagerBroker : MarshalByRefObject { + internal sealed class ComponentManagerBroker : MarshalByRefObject + { // These are constants per process and are initialized in // a class cctor below. @@ -101,7 +103,8 @@ internal sealed class ComponentManagerBroker : MarshalByRefObject { /// /// Static ctor. We just set up a few per-process globals here /// - static ComponentManagerBroker() { + static ComponentManagerBroker() + { int pid = SafeNativeMethods.GetCurrentProcessId(); _syncObject = new object(); _remoteObjectName = string.Format(CultureInfo.CurrentCulture, "ComponentManagerBroker.{0}.{1:X}", Application.WindowsFormsVersion, pid); @@ -121,11 +124,13 @@ static ComponentManagerBroker() { /// to extract the actual _broker value. /// NOTE: ctor must be public here for remoting to grab hold. /// - public ComponentManagerBroker() { + public ComponentManagerBroker() + { // Note that we only ever configure a single broker object. // We could be extremely transient here. - if (_broker == null) { + if (_broker == null) + { _broker = this; } } @@ -135,24 +140,29 @@ public ComponentManagerBroker() { /// broker that was never remoted. We try not to remote the broker /// until we need to because it is very expensive. /// - internal ComponentManagerBroker Singleton { - get { + internal ComponentManagerBroker Singleton + { + get + { return _broker; } } /// /// - internal void ClearComponentManager() { + internal void ClearComponentManager() + { _proxy = null; } #region Instance API only callable from a proxied object - + /// /// - public UnsafeNativeMethods.IMsoComponentManager GetProxy(long pCM) { - if (_proxy == null) { + public UnsafeNativeMethods.IMsoComponentManager GetProxy(long pCM) + { + if (_proxy == null) + { UnsafeNativeMethods.IMsoComponentManager original = (UnsafeNativeMethods.IMsoComponentManager)Marshal.GetObjectForIUnknown((IntPtr)pCM); _proxy = new ComponentManagerProxy(this, original); } @@ -161,7 +171,7 @@ public UnsafeNativeMethods.IMsoComponentManager GetProxy(long pCM) { } #endregion - + #region Static API callable from any domain /// @@ -170,22 +180,26 @@ public UnsafeNativeMethods.IMsoComponentManager GetProxy(long pCM) { /// creates an instance of ComponentManagerProxy for the calling thread /// and returns it. /// - internal static UnsafeNativeMethods.IMsoComponentManager GetComponentManager(IntPtr pOriginal) { + internal static UnsafeNativeMethods.IMsoComponentManager GetComponentManager(IntPtr pOriginal) + { - lock(_syncObject) { + lock (_syncObject) + { - if (_broker == null) { + if (_broker == null) + { // We need the default domain for the process. That's the domain we will use // for all component managers. There is no managed way to get this domain, however, // so we use ICorRuntimeHost. - UnsafeNativeMethods.ICorRuntimeHost host = (UnsafeNativeMethods.ICorRuntimeHost) RuntimeEnvironment.GetRuntimeInterfaceAsObject(typeof(UnsafeNativeMethods.CorRuntimeHost).GUID, typeof(UnsafeNativeMethods.ICorRuntimeHost).GUID); + UnsafeNativeMethods.ICorRuntimeHost host = (UnsafeNativeMethods.ICorRuntimeHost)RuntimeEnvironment.GetRuntimeInterfaceAsObject(typeof(UnsafeNativeMethods.CorRuntimeHost).GUID, typeof(UnsafeNativeMethods.ICorRuntimeHost).GUID); object domainObj; int hr = host.GetDefaultDomain(out domainObj); Debug.Assert(NativeMethods.Succeeded(hr), "ICorRuntimeHost failed to return the default domain. The only way that should happen is if it hasn't been started yet, but if it hasn't been started how are we running managed code?"); AppDomain domain = domainObj as AppDomain; - if (domain == null) { + if (domain == null) + { Debug.Assert(NativeMethods.Failed(hr) || domain != null, "ICorRuntimeHost::GetDefaultDomain succeeded but didn't retrn us an app domain."); domain = AppDomain.CurrentDomain; } @@ -200,7 +214,8 @@ internal static UnsafeNativeMethods.IMsoComponentManager GetComponentManager(Int // is a "Singleton" property on the broker -- just in case we had to create // a temporary broker during CreateInstanceAndUnwrap. - if (domain == AppDomain.CurrentDomain) { + if (domain == AppDomain.CurrentDomain) + { _broker = new ComponentManagerBroker(); } } @@ -218,7 +233,8 @@ internal static UnsafeNativeMethods.IMsoComponentManager GetComponentManager(Int /// The proxy object. This acts as, well, a proxy between the unmanaged IMsoComponentManager and zero or more /// managed components. /// - internal class ComponentManagerProxy : MarshalByRefObject, UnsafeNativeMethods.IMsoComponentManager, UnsafeNativeMethods.IMsoComponent { + internal class ComponentManagerProxy : MarshalByRefObject, UnsafeNativeMethods.IMsoComponentManager, UnsafeNativeMethods.IMsoComponent + { private ComponentManagerBroker _broker; private UnsafeNativeMethods.IMsoComponentManager _original; @@ -232,15 +248,18 @@ internal class ComponentManagerProxy : MarshalByRefObject, UnsafeNativeMethods.I private UnsafeNativeMethods.IMsoComponent _trackingComponent; private int _trackingComponentId; - internal ComponentManagerProxy(ComponentManagerBroker broker, UnsafeNativeMethods.IMsoComponentManager original) { + internal ComponentManagerProxy(ComponentManagerBroker broker, UnsafeNativeMethods.IMsoComponentManager original) + { _broker = broker; _original = original; _creationThread = SafeNativeMethods.GetCurrentThreadId(); _refCount = 0; } - private void Dispose() { - if (_original != null) { + private void Dispose() + { + if (_original != null) + { Marshal.ReleaseComObject(_original); _original = null; _components = null; @@ -250,74 +269,97 @@ private void Dispose() { } } - private bool RevokeComponent() { + private bool RevokeComponent() + { return _original.FRevokeComponent(_componentId); } - private UnsafeNativeMethods.IMsoComponent Component { - get { - if (_trackingComponent != null) return _trackingComponent; - if (_activeComponent != null) return _activeComponent; + private UnsafeNativeMethods.IMsoComponent Component + { + get + { + if (_trackingComponent != null) + return _trackingComponent; + if (_activeComponent != null) + return _activeComponent; return null; } } #region IMsoComponent Implementation - bool UnsafeNativeMethods.IMsoComponent.FDebugMessage(IntPtr hInst, int msg, IntPtr wparam, IntPtr lparam) { + bool UnsafeNativeMethods.IMsoComponent.FDebugMessage(IntPtr hInst, int msg, IntPtr wparam, IntPtr lparam) + { UnsafeNativeMethods.IMsoComponent c = Component; - if (c != null) { + if (c != null) + { return c.FDebugMessage(hInst, msg, wparam, lparam); } return false; } - bool UnsafeNativeMethods.IMsoComponent.FPreTranslateMessage(ref NativeMethods.MSG msg) { + bool UnsafeNativeMethods.IMsoComponent.FPreTranslateMessage(ref NativeMethods.MSG msg) + { UnsafeNativeMethods.IMsoComponent c = Component; - if (c != null) { + if (c != null) + { return c.FPreTranslateMessage(ref msg); } return false; } - void UnsafeNativeMethods.IMsoComponent.OnEnterState(int uStateID, bool fEnter) { - if (_components != null) { - foreach (UnsafeNativeMethods.IMsoComponent c in _components.Values) { + void UnsafeNativeMethods.IMsoComponent.OnEnterState(int uStateID, bool fEnter) + { + if (_components != null) + { + foreach (UnsafeNativeMethods.IMsoComponent c in _components.Values) + { c.OnEnterState(uStateID, fEnter); } } } - void UnsafeNativeMethods.IMsoComponent.OnAppActivate(bool fActive, int dwOtherThreadID) { - if (_components != null) { - foreach (UnsafeNativeMethods.IMsoComponent c in _components.Values) { + void UnsafeNativeMethods.IMsoComponent.OnAppActivate(bool fActive, int dwOtherThreadID) + { + if (_components != null) + { + foreach (UnsafeNativeMethods.IMsoComponent c in _components.Values) + { c.OnAppActivate(fActive, dwOtherThreadID); } } } - void UnsafeNativeMethods.IMsoComponent.OnLoseActivation() { - if (_activeComponent != null) { + void UnsafeNativeMethods.IMsoComponent.OnLoseActivation() + { + if (_activeComponent != null) + { _activeComponent.OnLoseActivation(); } } - void UnsafeNativeMethods.IMsoComponent.OnActivationChange(UnsafeNativeMethods.IMsoComponent component, bool fSameComponent, int pcrinfo, bool fHostIsActivating, int pchostinfo, int dwReserved) { - if (_components != null) { - foreach (UnsafeNativeMethods.IMsoComponent c in _components.Values) { + void UnsafeNativeMethods.IMsoComponent.OnActivationChange(UnsafeNativeMethods.IMsoComponent component, bool fSameComponent, int pcrinfo, bool fHostIsActivating, int pchostinfo, int dwReserved) + { + if (_components != null) + { + foreach (UnsafeNativeMethods.IMsoComponent c in _components.Values) + { c.OnActivationChange(component, fSameComponent, pcrinfo, fHostIsActivating, pchostinfo, dwReserved); } } } - bool UnsafeNativeMethods.IMsoComponent.FDoIdle(int grfidlef) { + bool UnsafeNativeMethods.IMsoComponent.FDoIdle(int grfidlef) + { bool cont = false; - if (_components != null) { - foreach (UnsafeNativeMethods.IMsoComponent c in _components.Values) { + if (_components != null) + { + foreach (UnsafeNativeMethods.IMsoComponent c in _components.Values) + { cont |= c.FDoIdle(grfidlef); } } @@ -325,18 +367,23 @@ bool UnsafeNativeMethods.IMsoComponent.FDoIdle(int grfidlef) { return cont; } - bool UnsafeNativeMethods.IMsoComponent.FContinueMessageLoop(int reason, int pvLoopData, NativeMethods.MSG[] msgPeeked) { + bool UnsafeNativeMethods.IMsoComponent.FContinueMessageLoop(int reason, int pvLoopData, NativeMethods.MSG[] msgPeeked) + { bool cont = false; - if (_refCount == 0 && _componentId != (IntPtr)0) { - if (RevokeComponent()) { + if (_refCount == 0 && _componentId != (IntPtr)0) + { + if (RevokeComponent()) + { _components.Clear(); _componentId = (IntPtr)0; } } - if (_components != null) { - foreach (UnsafeNativeMethods.IMsoComponent c in _components.Values) { + if (_components != null) + { + foreach (UnsafeNativeMethods.IMsoComponent c in _components.Values) + { cont |= c.FContinueMessageLoop(reason, pvLoopData, msgPeeked); } } @@ -344,30 +391,37 @@ bool UnsafeNativeMethods.IMsoComponent.FContinueMessageLoop(int reason, int pvLo return cont; } - bool UnsafeNativeMethods.IMsoComponent.FQueryTerminate(bool fPromptUser) { + bool UnsafeNativeMethods.IMsoComponent.FQueryTerminate(bool fPromptUser) + { return true; } - void UnsafeNativeMethods.IMsoComponent.Terminate() { - if (_components != null && _components.Values.Count>0) { + void UnsafeNativeMethods.IMsoComponent.Terminate() + { + if (_components != null && _components.Values.Count > 0) + { UnsafeNativeMethods.IMsoComponent[] components = new UnsafeNativeMethods.IMsoComponent[_components.Values.Count]; _components.Values.CopyTo(components, 0); - foreach (UnsafeNativeMethods.IMsoComponent c in components) { + foreach (UnsafeNativeMethods.IMsoComponent c in components) + { c.Terminate(); } } - if (_original != null) { + if (_original != null) + { RevokeComponent(); } Dispose(); } - IntPtr UnsafeNativeMethods.IMsoComponent.HwndGetWindow(int dwWhich, int dwReserved) { + IntPtr UnsafeNativeMethods.IMsoComponent.HwndGetWindow(int dwWhich, int dwReserved) + { UnsafeNativeMethods.IMsoComponent c = Component; - if (c != null) { + if (c != null) + { return c.HwndGetWindow(dwWhich, dwReserved); } @@ -376,45 +430,56 @@ IntPtr UnsafeNativeMethods.IMsoComponent.HwndGetWindow(int dwWhich, int dwReserv #endregion #region IMsoComponentManager Implementation - int UnsafeNativeMethods.IMsoComponentManager.QueryService(ref Guid guidService, ref Guid iid, out object ppvObj) { + int UnsafeNativeMethods.IMsoComponentManager.QueryService(ref Guid guidService, ref Guid iid, out object ppvObj) + { return _original.QueryService(ref guidService, ref iid, out ppvObj); } - bool UnsafeNativeMethods.IMsoComponentManager.FDebugMessage(IntPtr hInst, int msg, IntPtr wparam, IntPtr lparam) { + bool UnsafeNativeMethods.IMsoComponentManager.FDebugMessage(IntPtr hInst, int msg, IntPtr wparam, IntPtr lparam) + { return _original.FDebugMessage(hInst, msg, wparam, lparam); } - bool UnsafeNativeMethods.IMsoComponentManager.FRegisterComponent(UnsafeNativeMethods.IMsoComponent component, NativeMethods.MSOCRINFOSTRUCT pcrinfo, out IntPtr dwComponentID) { - if (component == null) { + bool UnsafeNativeMethods.IMsoComponentManager.FRegisterComponent(UnsafeNativeMethods.IMsoComponent component, NativeMethods.MSOCRINFOSTRUCT pcrinfo, out IntPtr dwComponentID) + { + if (component == null) + { throw new ArgumentNullException(nameof(component)); } dwComponentID = (IntPtr)0; - if (_refCount == 0) { + if (_refCount == 0) + { // Our first time hooking up to the real component manager - if (!_original.FRegisterComponent(this, pcrinfo, out _componentId)) { + if (!_original.FRegisterComponent(this, pcrinfo, out _componentId)) + { return false; } } _refCount++; - if (_components == null) { + if (_components == null) + { _components = new Dictionary(); } _nextComponentId++; - if (_nextComponentId == int.MaxValue) { + if (_nextComponentId == int.MaxValue) + { _nextComponentId = 1; } bool outofMemory = false; //just in case we wrap, lets search for a free ID - while (_components.ContainsKey(_nextComponentId)) { + while (_components.ContainsKey(_nextComponentId)) + { _nextComponentId++; - if (_nextComponentId == int.MaxValue) { - if (outofMemory) { + if (_nextComponentId == int.MaxValue) + { + if (outofMemory) + { throw new InvalidOperationException(SR.ComponentManagerProxyOutOfMemory); } outofMemory = true; @@ -424,19 +489,24 @@ bool UnsafeNativeMethods.IMsoComponentManager.FRegisterComponent(UnsafeNativeMet _components.Add(_nextComponentId, component); dwComponentID = (IntPtr)_nextComponentId; - + return true; } - bool UnsafeNativeMethods.IMsoComponentManager.FRevokeComponent(IntPtr dwComponentID) { + bool UnsafeNativeMethods.IMsoComponentManager.FRevokeComponent(IntPtr dwComponentID) + { int dwLocalComponentID = unchecked((int)(long)dwComponentID); - if (_original == null) return false; - if (_components == null || dwLocalComponentID <= 0 || !_components.ContainsKey(dwLocalComponentID)) { + if (_original == null) + return false; + if (_components == null || dwLocalComponentID <= 0 || !_components.ContainsKey(dwLocalComponentID)) + { return false; } - if (_refCount == 1 && SafeNativeMethods.GetCurrentThreadId() == _creationThread) { - if (!RevokeComponent()) { + if (_refCount == 1 && SafeNativeMethods.GetCurrentThreadId() == _creationThread) + { + if (!RevokeComponent()) + { return false; } } @@ -445,15 +515,18 @@ bool UnsafeNativeMethods.IMsoComponentManager.FRevokeComponent(IntPtr dwComponen _components.Remove(dwLocalComponentID); Debug.Assert(_refCount >= 0, "underflow on ref count"); - if (_refCount <= 0) { + if (_refCount <= 0) + { Dispose(); } - if (dwLocalComponentID == _activeComponentId) { + if (dwLocalComponentID == _activeComponentId) + { _activeComponent = null; _activeComponentId = 0; } - if (dwLocalComponentID == _trackingComponentId) { + if (dwLocalComponentID == _trackingComponentId) + { _trackingComponent = null; _trackingComponentId = 0; } @@ -461,51 +534,63 @@ bool UnsafeNativeMethods.IMsoComponentManager.FRevokeComponent(IntPtr dwComponen return true; } - bool UnsafeNativeMethods.IMsoComponentManager.FUpdateComponentRegistration(IntPtr dwComponentID, NativeMethods.MSOCRINFOSTRUCT info) { - if (_original == null) return false; + bool UnsafeNativeMethods.IMsoComponentManager.FUpdateComponentRegistration(IntPtr dwComponentID, NativeMethods.MSOCRINFOSTRUCT info) + { + if (_original == null) + return false; // We assume that all winforms domains use the same registration. return _original.FUpdateComponentRegistration(_componentId, info); } - bool UnsafeNativeMethods.IMsoComponentManager.FOnComponentActivate(IntPtr dwComponentID) { + bool UnsafeNativeMethods.IMsoComponentManager.FOnComponentActivate(IntPtr dwComponentID) + { int dwLocalComponentID = unchecked((int)(long)dwComponentID); - if (_original == null) return false; + if (_original == null) + return false; // Activation requres us to store the currently active component. We will send data to it - if (_components == null || dwLocalComponentID <= 0 || !_components.ContainsKey(dwLocalComponentID)) { + if (_components == null || dwLocalComponentID <= 0 || !_components.ContainsKey(dwLocalComponentID)) + { return false; } - if (!_original.FOnComponentActivate(_componentId)) { + if (!_original.FOnComponentActivate(_componentId)) + { return false; } - + _activeComponent = _components[dwLocalComponentID]; _activeComponentId = dwLocalComponentID; return true; } - bool UnsafeNativeMethods.IMsoComponentManager.FSetTrackingComponent(IntPtr dwComponentID, bool fTrack) { + bool UnsafeNativeMethods.IMsoComponentManager.FSetTrackingComponent(IntPtr dwComponentID, bool fTrack) + { // Tracking requres us to store the current tracking component. We will send data to it int dwLocalComponentID = unchecked((int)(long)dwComponentID); - if (_original == null) { + if (_original == null) + { return false; } - if (_components == null || dwLocalComponentID <= 0 || !_components.ContainsKey(dwLocalComponentID)) { + if (_components == null || dwLocalComponentID <= 0 || !_components.ContainsKey(dwLocalComponentID)) + { return false; } - if (!_original.FSetTrackingComponent(_componentId, fTrack)) { + if (!_original.FSetTrackingComponent(_componentId, fTrack)) + { return false; } - if (fTrack) { + if (fTrack) + { _trackingComponent = _components[dwLocalComponentID]; _trackingComponentId = dwLocalComponentID; } - else { + else + { _trackingComponent = null; _trackingComponentId = 0; } @@ -513,11 +598,16 @@ bool UnsafeNativeMethods.IMsoComponentManager.FSetTrackingComponent(IntPtr dwCom return true; } - void UnsafeNativeMethods.IMsoComponentManager.OnComponentEnterState(IntPtr dwComponentID, int uStateID, int uContext, int cpicmExclude, int rgpicmExclude, int dwReserved) { - if (_original == null) return; - if (uContext == NativeMethods.MSOCM.msoccontextAll || uContext == NativeMethods.MSOCM.msoccontextMine) { - if (_components != null) { - foreach (UnsafeNativeMethods.IMsoComponent comp in _components.Values) { + void UnsafeNativeMethods.IMsoComponentManager.OnComponentEnterState(IntPtr dwComponentID, int uStateID, int uContext, int cpicmExclude, int rgpicmExclude, int dwReserved) + { + if (_original == null) + return; + if (uContext == NativeMethods.MSOCM.msoccontextAll || uContext == NativeMethods.MSOCM.msoccontextMine) + { + if (_components != null) + { + foreach (UnsafeNativeMethods.IMsoComponent comp in _components.Values) + { comp.OnEnterState(uStateID, true); } } @@ -526,11 +616,16 @@ void UnsafeNativeMethods.IMsoComponentManager.OnComponentEnterState(IntPtr dwCom _original.OnComponentEnterState(_componentId, uStateID, uContext, cpicmExclude, rgpicmExclude, dwReserved); } - bool UnsafeNativeMethods.IMsoComponentManager.FOnComponentExitState(IntPtr dwComponentID, int uStateID, int uContext, int cpicmExclude, int rgpicmExclude ) { - if (_original == null) return false; - if (uContext == NativeMethods.MSOCM.msoccontextAll || uContext == NativeMethods.MSOCM.msoccontextMine) { - if (_components != null) { - foreach (UnsafeNativeMethods.IMsoComponent comp in _components.Values) { + bool UnsafeNativeMethods.IMsoComponentManager.FOnComponentExitState(IntPtr dwComponentID, int uStateID, int uContext, int cpicmExclude, int rgpicmExclude) + { + if (_original == null) + return false; + if (uContext == NativeMethods.MSOCM.msoccontextAll || uContext == NativeMethods.MSOCM.msoccontextMine) + { + if (_components != null) + { + foreach (UnsafeNativeMethods.IMsoComponent comp in _components.Values) + { comp.OnEnterState(uStateID, false); } } @@ -539,47 +634,65 @@ bool UnsafeNativeMethods.IMsoComponentManager.FOnComponentExitState(IntPtr dwCom return _original.FOnComponentExitState(_componentId, uStateID, uContext, cpicmExclude, rgpicmExclude); } - bool UnsafeNativeMethods.IMsoComponentManager.FInState(int uStateID, IntPtr pvoid) { - if (_original == null) return false; + bool UnsafeNativeMethods.IMsoComponentManager.FInState(int uStateID, IntPtr pvoid) + { + if (_original == null) + return false; return _original.FInState(uStateID, pvoid); } - bool UnsafeNativeMethods.IMsoComponentManager.FContinueIdle() { - if (_original == null) return false; + bool UnsafeNativeMethods.IMsoComponentManager.FContinueIdle() + { + if (_original == null) + return false; return _original.FContinueIdle(); } - bool UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, int reason, int pvLoopData) { - if (_original == null) return false; + bool UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, int reason, int pvLoopData) + { + if (_original == null) + return false; return _original.FPushMessageLoop(_componentId, reason, pvLoopData); } - bool UnsafeNativeMethods.IMsoComponentManager.FCreateSubComponentManager(object punkOuter, object punkServProv, ref Guid riid, out IntPtr ppvObj) { - if (_original == null) { ppvObj = IntPtr.Zero; return false; } + bool UnsafeNativeMethods.IMsoComponentManager.FCreateSubComponentManager(object punkOuter, object punkServProv, ref Guid riid, out IntPtr ppvObj) + { + if (_original == null) + { ppvObj = IntPtr.Zero; return false; } return _original.FCreateSubComponentManager(punkOuter, punkServProv, ref riid, out ppvObj); } - bool UnsafeNativeMethods.IMsoComponentManager.FGetParentComponentManager(out UnsafeNativeMethods.IMsoComponentManager ppicm) { - if (_original == null) { ppicm = null; return false; } + bool UnsafeNativeMethods.IMsoComponentManager.FGetParentComponentManager(out UnsafeNativeMethods.IMsoComponentManager ppicm) + { + if (_original == null) + { ppicm = null; return false; } return _original.FGetParentComponentManager(out ppicm); } - bool UnsafeNativeMethods.IMsoComponentManager.FGetActiveComponent(int dwgac, UnsafeNativeMethods.IMsoComponent[] ppic, NativeMethods.MSOCRINFOSTRUCT info, int dwReserved) { - if (_original == null) return false; - if (_original.FGetActiveComponent(dwgac, ppic, info, dwReserved)) { + bool UnsafeNativeMethods.IMsoComponentManager.FGetActiveComponent(int dwgac, UnsafeNativeMethods.IMsoComponent[] ppic, NativeMethods.MSOCRINFOSTRUCT info, int dwReserved) + { + if (_original == null) + return false; + if (_original.FGetActiveComponent(dwgac, ppic, info, dwReserved)) + { // We got a component. See if it's our proxy, and if it is, // return what we think is currently active. We need only // check for "this", because we only have one of these // doo jabbers per process. - if (ppic[0] == this) { - if (dwgac == NativeMethods.MSOCM.msogacActive) { + if (ppic[0] == this) + { + if (dwgac == NativeMethods.MSOCM.msogacActive) + { ppic[0] = _activeComponent; } - else if (dwgac == NativeMethods.MSOCM.msogacTracking) { + else if (dwgac == NativeMethods.MSOCM.msogacTracking) + { ppic[0] = _trackingComponent; } - else if (dwgac == NativeMethods.MSOCM.msogacTrackingOrActive) { - if (_trackingComponent != null) { + else if (dwgac == NativeMethods.MSOCM.msogacTrackingOrActive) + { + if (_trackingComponent != null) + { ppic[0] = _trackingComponent; } } @@ -587,7 +700,8 @@ bool UnsafeNativeMethods.IMsoComponentManager.FGetActiveComponent(int dwgac, Uns return ppic[0] != null; } - else { + else + { return false; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/BaseCAMarshaler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/BaseCAMarshaler.cs index fb78977259d..aae4fb87b22 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/BaseCAMarshaler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/BaseCAMarshaler.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; @@ -18,7 +19,8 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop { /// and the second is a pointer to an array of such elements. /// /// - internal abstract class BaseCAMarshaler { + internal abstract class BaseCAMarshaler + { private static TraceSwitch CAMarshalSwitch = new TraceSwitch("CAMarshal", "BaseCAMarshaler: Debug CA* struct marshaling"); @@ -29,8 +31,10 @@ internal abstract class BaseCAMarshaler { /// /// Base ctor /// - protected BaseCAMarshaler(NativeMethods.CA_STRUCT caStruct) : base() { - if (caStruct == null) { + protected BaseCAMarshaler(NativeMethods.CA_STRUCT caStruct) : base() + { + if (caStruct == null) + { count = 0; Debug.WriteLineIf(CAMarshalSwitch.TraceVerbose, "BaseCAMarshaler: null passed in!"); } @@ -41,13 +45,17 @@ protected BaseCAMarshaler(NativeMethods.CA_STRUCT caStruct) : base() { Debug.WriteLineIf(CAMarshalSwitch.TraceVerbose, "Marshaling " + count.ToString(CultureInfo.InvariantCulture) + " items of type " + ItemType.Name); } - ~BaseCAMarshaler() { - try { - if (itemArray == null && caArrayAddress != IntPtr.Zero) { - object[] items = Items; + ~BaseCAMarshaler() + { + try + { + if (itemArray == null && caArrayAddress != IntPtr.Zero) + { + object[] items = Items; } } - catch { + catch + { } } @@ -57,7 +65,8 @@ protected BaseCAMarshaler(NativeMethods.CA_STRUCT caStruct) : base() { /// Returns the type of item this marshaler will /// return in the items array. /// - public abstract Type ItemType { + public abstract Type ItemType + { get; } @@ -66,8 +75,10 @@ public abstract Type ItemType { /// Returns the count of items that will be or have been /// marshaled. /// - public int Count { - get { + public int Count + { + get + { return count; } } @@ -77,18 +88,24 @@ public int Count { /// /// The marshaled items. /// - public virtual object[] Items { - get { - try { - if (itemArray == null) { + public virtual object[] Items + { + get + { + try + { + if (itemArray == null) + { itemArray = Get_Items(); } } - catch (Exception ex) { + catch (Exception ex) + { Debug.WriteLineIf(CAMarshalSwitch.TraceVerbose, "Marshaling failed: " + ex.GetType().Name + ", " + ex.Message); } #if DEBUG - if (itemArray != null) { + if (itemArray != null) + { Debug.WriteLineIf(CAMarshalSwitch.TraceVerbose, "Marshaled: " + itemArray.Length.ToString(CultureInfo.InvariantCulture) + " items, array type=" + itemArray.GetType().Name); } #endif @@ -104,28 +121,33 @@ public virtual object[] Items { protected abstract object GetItemFromAddress(IntPtr addr); // Retrieve the items - private object[] Get_Items() { + private object[] Get_Items() + { // cycle through the addresses and get an item for each addr IntPtr addr; Array items = new object[Count]; //cpb vs38262 System.Array.CreateInstance(this.ItemType,count); object curItem; - for (int i = 0; i < count; i++) { - try { + for (int i = 0; i < count; i++) + { + try + { addr = Marshal.ReadIntPtr(caArrayAddress, i * IntPtr.Size); curItem = GetItemFromAddress(addr); - if (curItem != null && ItemType.IsInstanceOfType(curItem)) { + if (curItem != null && ItemType.IsInstanceOfType(curItem)) + { items.SetValue(curItem, i); } Debug.WriteLineIf(CAMarshalSwitch.TraceVerbose, "Marshaled " + ItemType.Name + " item, value=" + (curItem == null ? "(null)" : curItem.ToString())); } - catch (Exception ex) { - Debug.WriteLineIf(CAMarshalSwitch.TraceVerbose, "Failed to marshal " + ItemType.Name + " item, exception=" + ex.GetType().Name +", " +ex.Message); + catch (Exception ex) + { + Debug.WriteLineIf(CAMarshalSwitch.TraceVerbose, "Failed to marshal " + ItemType.Name + " item, exception=" + ex.GetType().Name + ", " + ex.Message); } } // free the array Marshal.FreeCoTaskMem(caArrayAddress); caArrayAddress = IntPtr.Zero; - return(object[])items; + return (object[])items; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2AboutBoxPropertyDescriptor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2AboutBoxPropertyDescriptor.cs index e94da6abc55..42903ad95d2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2AboutBoxPropertyDescriptor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2AboutBoxPropertyDescriptor.cs @@ -2,67 +2,79 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System; - using System.ComponentModel.Design; + using System.ComponentModel.Design; using Microsoft.Win32; using System.Collections; using System.Drawing.Design; - - internal class Com2AboutBoxPropertyDescriptor : Com2PropertyDescriptor { + + internal class Com2AboutBoxPropertyDescriptor : Com2PropertyDescriptor + { private TypeConverter converter; - private UITypeEditor editor; - - public Com2AboutBoxPropertyDescriptor() : base(NativeMethods.ActiveX.DISPID_ABOUTBOX, "About", new Attribute[]{new DispIdAttribute(NativeMethods.ActiveX.DISPID_ABOUTBOX), - DesignerSerializationVisibilityAttribute.Hidden, - new DescriptionAttribute(SR.AboutBoxDesc), - new ParenthesizePropertyNameAttribute(true)}, true, typeof(string), null, false) { + private UITypeEditor editor; + + public Com2AboutBoxPropertyDescriptor() : base(NativeMethods.ActiveX.DISPID_ABOUTBOX, "About", new Attribute[]{new DispIdAttribute(NativeMethods.ActiveX.DISPID_ABOUTBOX), + DesignerSerializationVisibilityAttribute.Hidden, + new DescriptionAttribute(SR.AboutBoxDesc), + new ParenthesizePropertyNameAttribute(true)}, true, typeof(string), null, false) + { } - + /// /// Retrieves the type of the component this PropertyDescriptor is bound to. /// - public override Type ComponentType { - get { - return typeof(UnsafeNativeMethods.IDispatch); + public override Type ComponentType + { + get + { + return typeof(UnsafeNativeMethods.IDispatch); } } - - + + /// /// Retrieves the type converter for this property. /// - public override TypeConverter Converter { - get { - if (converter == null) { + public override TypeConverter Converter + { + get + { + if (converter == null) + { converter = new TypeConverter(); - } + } return converter; } } /// /// Indicates whether this property is read only. /// - public override bool IsReadOnly { - get { - return true; + public override bool IsReadOnly + { + get + { + return true; } } /// /// Retrieves the type of the property. /// - public override Type PropertyType { - get { - return typeof(string); + public override Type PropertyType + { + get + { + return typeof(string); } } - + /// /// Indicates whether reset will change the value of the component. If there /// is a DefaultValueAttribute, then this will return true if getValue returns @@ -71,20 +83,24 @@ public override Type PropertyType { /// If there is just a reset method, this always returns true. If none of these /// cases apply, this returns false. /// - public override bool CanResetValue(object component) { + public override bool CanResetValue(object component) + { return false; } - + /// /// Retrieves an editor of the requested type. /// - public override object GetEditor(Type editorBaseType) { - if (editorBaseType == typeof(UITypeEditor)) { - if (editor == null) { + public override object GetEditor(Type editorBaseType) + { + if (editorBaseType == typeof(UITypeEditor)) + { + if (editor == null) + { editor = new AboutBoxUITypeEditor(); } } - + return editor; } @@ -93,7 +109,8 @@ public override object GetEditor(Type editorBaseType) { /// invoking the getXXX method. An exception in the getXXX /// method will pass through. /// - public override object GetValue(object component) { + public override object GetValue(object component) + { return ""; } @@ -105,7 +122,8 @@ public override object GetValue(object component) { /// for. If one is found, it will be invoked. If one is not found, this /// is a nop. /// - public override void ResetValue(object component){ + public override void ResetValue(object component) + { } /// @@ -117,7 +135,8 @@ public override void ResetValue(object component){ /// passed in if no exception was thrown in the setXXX call. /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] - public override void SetValue(object component, object value) { + public override void SetValue(object component, object value) + { throw new ArgumentException(); } @@ -132,43 +151,48 @@ public override void SetValue(object component, object value) { /// /// If this returns false, a tool should not persist this property's value. /// - public override bool ShouldSerializeValue(object component) { + public override bool ShouldSerializeValue(object component) + { return false; } - - public class AboutBoxUITypeEditor : UITypeEditor { + + public class AboutBoxUITypeEditor : UITypeEditor + { /// /// Edits the given object value using the editor style provided by /// GetEditorStyle. A service provider is provided so that any /// required editing services can be obtained. /// - public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { - object component = context.Instance; - - if (Marshal.IsComObject(component) && component is UnsafeNativeMethods.IDispatch) { - UnsafeNativeMethods.IDispatch pDisp = (UnsafeNativeMethods.IDispatch)component; - NativeMethods.tagEXCEPINFO pExcepInfo = new NativeMethods.tagEXCEPINFO(); - Guid g = Guid.Empty; - - int hr = pDisp.Invoke(NativeMethods.ActiveX.DISPID_ABOUTBOX, - ref g, - SafeNativeMethods.GetThreadLCID(), - NativeMethods.DISPATCH_METHOD, - new NativeMethods.tagDISPPARAMS(), - null, - pExcepInfo, null); - - Debug.Assert(NativeMethods.Succeeded(hr), "Failed to launch about box."); - } - return value; + public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) + { + object component = context.Instance; + + if (Marshal.IsComObject(component) && component is UnsafeNativeMethods.IDispatch) + { + UnsafeNativeMethods.IDispatch pDisp = (UnsafeNativeMethods.IDispatch)component; + NativeMethods.tagEXCEPINFO pExcepInfo = new NativeMethods.tagEXCEPINFO(); + Guid g = Guid.Empty; + + int hr = pDisp.Invoke(NativeMethods.ActiveX.DISPID_ABOUTBOX, + ref g, + SafeNativeMethods.GetThreadLCID(), + NativeMethods.DISPATCH_METHOD, + new NativeMethods.tagDISPPARAMS(), + null, + pExcepInfo, null); + + Debug.Assert(NativeMethods.Succeeded(hr), "Failed to launch about box."); + } + return value; } - + /// /// Retrieves the editing style of the Edit method. If the method /// is not supported, this will return None. /// - public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { - return UITypeEditorEditStyle.Modal; + public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) + { + return UITypeEditorEditStyle.Modal; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ColorConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ColorConverter.cs index 0efefe2ba7d..38370645393 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ColorConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ColorConverter.cs @@ -2,71 +2,79 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.Runtime.Serialization.Formatters; using System.ComponentModel; using System.Diagnostics; using System; - - using System.Drawing; + + using System.Drawing; using System.Collections; using Microsoft.Win32; /// /// This class maps an OLE_COLOR to a managed Color editor. /// - internal class Com2ColorConverter : Com2DataTypeToManagedDataTypeConverter{ + internal class Com2ColorConverter : Com2DataTypeToManagedDataTypeConverter + { - /// - /// Returns the managed type that this editor maps the property type to. - /// - public override Type ManagedType{ - get{ - return typeof(Color); + /// + /// Returns the managed type that this editor maps the property type to. + /// + public override Type ManagedType + { + get + { + return typeof(Color); } - } + } - /// - /// Converts the native value into a managed value - /// - public override object ConvertNativeToManaged(object nativeValue, Com2PropertyDescriptor pd){ - object baseValue = nativeValue; - int intVal = 0; + /// + /// Converts the native value into a managed value + /// + public override object ConvertNativeToManaged(object nativeValue, Com2PropertyDescriptor pd) + { + object baseValue = nativeValue; + int intVal = 0; - // get the integer value out of the native... - // - if (nativeValue is uint) + // get the integer value out of the native... + // + if (nativeValue is uint) { - intVal = (int)(uint)nativeValue; - } - else if (nativeValue is int) + intVal = (int)(uint)nativeValue; + } + else if (nativeValue is int) { - intVal = (int)nativeValue; - } + intVal = (int)nativeValue; + } - return ColorTranslator.FromOle(intVal); - } + return ColorTranslator.FromOle(intVal); + } - /// - /// Converts the managed value into a native value - /// - public override object ConvertManagedToNative(object managedValue, Com2PropertyDescriptor pd, ref bool cancelSet){ - // don't cancel the set - cancelSet = false; + /// + /// Converts the managed value into a native value + /// + public override object ConvertManagedToNative(object managedValue, Com2PropertyDescriptor pd, ref bool cancelSet) + { + // don't cancel the set + cancelSet = false; - // we default to black. - // - if (managedValue == null){ - managedValue = Color.Black; - } + // we default to black. + // + if (managedValue == null) + { + managedValue = Color.Black; + } - if (managedValue is Color){ - return ColorTranslator.ToOle(((Color)managedValue)); + if (managedValue is Color) + { + return ColorTranslator.ToOle(((Color)managedValue)); - } - Debug.Fail("Don't know how to set type:" + managedValue.GetType().Name); - return 0; - } + } + Debug.Fail("Don't know how to set type:" + managedValue.GetType().Name); + return 0; + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ComponentEditor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ComponentEditor.cs index ef4e8602bdf..a59d2f72882 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ComponentEditor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ComponentEditor.cs @@ -2,125 +2,154 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; - using System; + using System; using System.Collections; using Microsoft.Win32; using System.Windows.Forms.Design; - internal class Com2ComponentEditor : WindowsFormsComponentEditor { - - public static bool NeedsComponentEditor(object obj) { - if (obj is NativeMethods.IPerPropertyBrowsing) { - // check for a property page - Guid guid = Guid.Empty; - int hr = ((NativeMethods.IPerPropertyBrowsing)obj).MapPropertyToPage(NativeMethods.MEMBERID_NIL, out guid); - if ((hr == NativeMethods.S_OK) && !guid.Equals(Guid.Empty)) { - return true; - } + internal class Com2ComponentEditor : WindowsFormsComponentEditor + { + + public static bool NeedsComponentEditor(object obj) + { + if (obj is NativeMethods.IPerPropertyBrowsing) + { + // check for a property page + Guid guid = Guid.Empty; + int hr = ((NativeMethods.IPerPropertyBrowsing)obj).MapPropertyToPage(NativeMethods.MEMBERID_NIL, out guid); + if ((hr == NativeMethods.S_OK) && !guid.Equals(Guid.Empty)) + { + return true; + } } - - if (obj is NativeMethods.ISpecifyPropertyPages) { - try { + + if (obj is NativeMethods.ISpecifyPropertyPages) + { + try + { NativeMethods.tagCAUUID uuids = new NativeMethods.tagCAUUID(); - try { + try + { ((NativeMethods.ISpecifyPropertyPages)obj).GetPages(uuids); - if (uuids.cElems > 0) { - return true; + if (uuids.cElems > 0) + { + return true; } } - finally { - if (uuids.pElems != IntPtr.Zero) { + finally + { + if (uuids.pElems != IntPtr.Zero) + { Marshal.FreeCoTaskMem(uuids.pElems); } } - } - catch { - } - - return false; + } + catch + { + } + + return false; } return false; } - + [ SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // This was shipped in Everett. ] - public override bool EditComponent(ITypeDescriptorContext context, object obj, IWin32Window parent) { - - IntPtr handle = (parent == null ? IntPtr.Zero : parent.Handle); - - // try to get the page guid - if (obj is NativeMethods.IPerPropertyBrowsing) { - // check for a property page - Guid guid = Guid.Empty; - int hr = ((NativeMethods.IPerPropertyBrowsing)obj).MapPropertyToPage(NativeMethods.MEMBERID_NIL, out guid); - if (hr == NativeMethods.S_OK) { - if (!guid.Equals(Guid.Empty)) { - object o = obj; - SafeNativeMethods.OleCreatePropertyFrame(new HandleRef(parent, handle), 0, 0, "PropertyPages", 1, ref o, 1, new Guid[]{guid}, Application.CurrentCulture.LCID, 0, IntPtr.Zero); - return true; + public override bool EditComponent(ITypeDescriptorContext context, object obj, IWin32Window parent) + { + + IntPtr handle = (parent == null ? IntPtr.Zero : parent.Handle); + + // try to get the page guid + if (obj is NativeMethods.IPerPropertyBrowsing) + { + // check for a property page + Guid guid = Guid.Empty; + int hr = ((NativeMethods.IPerPropertyBrowsing)obj).MapPropertyToPage(NativeMethods.MEMBERID_NIL, out guid); + if (hr == NativeMethods.S_OK) + { + if (!guid.Equals(Guid.Empty)) + { + object o = obj; + SafeNativeMethods.OleCreatePropertyFrame(new HandleRef(parent, handle), 0, 0, "PropertyPages", 1, ref o, 1, new Guid[] { guid }, Application.CurrentCulture.LCID, 0, IntPtr.Zero); + return true; + } + } + } + + if (obj is NativeMethods.ISpecifyPropertyPages) + { + bool failed = false; + Exception failureException; + + try + { + NativeMethods.tagCAUUID uuids = new NativeMethods.tagCAUUID(); + try + { + ((NativeMethods.ISpecifyPropertyPages)obj).GetPages(uuids); + if (uuids.cElems <= 0) + { + return false; } } - } - - if (obj is NativeMethods.ISpecifyPropertyPages) { - bool failed = false; - Exception failureException; - - try { - NativeMethods.tagCAUUID uuids = new NativeMethods.tagCAUUID(); - try { - ((NativeMethods.ISpecifyPropertyPages)obj).GetPages(uuids); - if (uuids.cElems <= 0) { - return false; - } - } - catch { - return false; - } - try { - object o = obj; - SafeNativeMethods.OleCreatePropertyFrame(new HandleRef(parent, handle), 0, 0, "PropertyPages", 1, ref o, uuids.cElems, new HandleRef(uuids, uuids.pElems), Application.CurrentCulture.LCID, 0, IntPtr.Zero); - return true; - } - finally { - if (uuids.pElems != IntPtr.Zero) { - Marshal.FreeCoTaskMem(uuids.pElems); - } - } - + catch + { + return false; + } + try + { + object o = obj; + SafeNativeMethods.OleCreatePropertyFrame(new HandleRef(parent, handle), 0, 0, "PropertyPages", 1, ref o, uuids.cElems, new HandleRef(uuids, uuids.pElems), Application.CurrentCulture.LCID, 0, IntPtr.Zero); + return true; } - catch (Exception ex1) { - failed = true; - failureException = ex1; + finally + { + if (uuids.pElems != IntPtr.Zero) + { + Marshal.FreeCoTaskMem(uuids.pElems); + } } - if (failed) { + } + catch (Exception ex1) + { + failed = true; + failureException = ex1; + } + + if (failed) + { string errString = SR.ErrorPropertyPageFailed; - IUIService uiSvc = (context != null) ? ((IUIService) context.GetService(typeof(IUIService))) : null; - - if (uiSvc == null) { - RTLAwareMessageBox.Show(null, errString, SR.PropertyGridTitle, - MessageBoxButtons.OK, MessageBoxIcon.Error, - MessageBoxDefaultButton.Button1, 0); - } - else if (failureException != null) { - uiSvc.ShowError(failureException, errString); - } - else { - uiSvc.ShowError(errString); - } + IUIService uiSvc = (context != null) ? ((IUIService)context.GetService(typeof(IUIService))) : null; + + if (uiSvc == null) + { + RTLAwareMessageBox.Show(null, errString, SR.PropertyGridTitle, + MessageBoxButtons.OK, MessageBoxIcon.Error, + MessageBoxDefaultButton.Button1, 0); + } + else if (failureException != null) + { + uiSvc.ShowError(failureException, errString); + } + else + { + uiSvc.ShowError(errString); } } - return false; } + return false; + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2DataTypeToManagedDataTypeConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2DataTypeToManagedDataTypeConverter.cs index 70277d3efa7..391289c920d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2DataTypeToManagedDataTypeConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2DataTypeToManagedDataTypeConverter.cs @@ -2,13 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.Runtime.Serialization.Formatters; using System.ComponentModel; using System.Diagnostics; using System; using System.Drawing; - using System.ComponentModel.Design; + using System.ComponentModel.Design; using System.Collections; using Microsoft.Win32; @@ -16,31 +17,35 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop { /// This base class maps an ole defined data type (OLE_COLOR, IFont, etc.), /// /// - internal abstract class Com2DataTypeToManagedDataTypeConverter{ - - - public virtual bool AllowExpand { - get { - return false; - } - } - - /// - /// Returns the managed type that this editor maps the property type to. - /// - public abstract Type ManagedType{ + internal abstract class Com2DataTypeToManagedDataTypeConverter + { + + + public virtual bool AllowExpand + { + get + { + return false; + } + } + + /// + /// Returns the managed type that this editor maps the property type to. + /// + public abstract Type ManagedType + { get; - } + } - /// - /// Converts the native value into a managed value - /// - public abstract object ConvertNativeToManaged(object nativeValue, Com2PropertyDescriptor pd); + /// + /// Converts the native value into a managed value + /// + public abstract object ConvertNativeToManaged(object nativeValue, Com2PropertyDescriptor pd); - /// - /// Converts the managed value into a native value - /// - public abstract object ConvertManagedToNative(object managedValue, Com2PropertyDescriptor pd, ref bool cancelSet); + /// + /// Converts the managed value into a native value + /// + public abstract object ConvertManagedToNative(object managedValue, Com2PropertyDescriptor pd, ref bool cancelSet); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Enum.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Enum.cs index 09c0a46c48e..e649d41d0b0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Enum.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Enum.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.ComponentModel; using System.Diagnostics; using System; @@ -23,7 +24,8 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop { /// mistake), they won't compare properly and values can't be updated. /// By comparing strings, we avoid this problem and add flexiblity to the system. /// - internal class Com2Enum { + internal class Com2Enum + { /// /// Our array of value string names @@ -46,19 +48,21 @@ internal class Com2Enum { /// /// Should we allow values besides what's in the listbox? /// - private bool allowUnknownValues; + private bool allowUnknownValues; /// /// Our one and only ctor /// - public Com2Enum(string[] names, object[] values, bool allowUnknownValues) { + public Com2Enum(string[] names, object[] values, bool allowUnknownValues) + { this.allowUnknownValues = allowUnknownValues; // these have to be null and the same length if (names == null || values == null || - names.Length != values.Length) { + names.Length != values.Length) + { throw new ArgumentException(SR.COM2NamesAndValuesNotEqual); } @@ -68,8 +72,10 @@ public Com2Enum(string[] names, object[] values, bool allowUnknownValues) { /// /// Can this enum be values other than the strict enum? /// - public bool IsStrictEnum { - get { + public bool IsStrictEnum + { + get + { return !this.allowUnknownValues; } } @@ -77,56 +83,68 @@ public bool IsStrictEnum { /// /// Retrieve a copy of the value array /// - public virtual object[] Values { - get { - return(object[])this.values.Clone(); + public virtual object[] Values + { + get + { + return (object[])this.values.Clone(); } } /// /// Retrieve a copy of the nme array. /// - public virtual string[] Names { - get { - return(string[])this.names.Clone(); + public virtual string[] Names + { + get + { + return (string[])this.names.Clone(); } } /// /// Associate a string to the appropriate value. /// - public virtual object FromString(string s) { + public virtual object FromString(string s) + { int bestMatch = -1; - - for (int i = 0; i < stringValues.Length; i++) { + + for (int i = 0; i < stringValues.Length; i++) + { if (string.Compare(names[i], s, true, CultureInfo.InvariantCulture) == 0 || - string.Compare(stringValues[i], s, true, CultureInfo.InvariantCulture) == 0) { + string.Compare(stringValues[i], s, true, CultureInfo.InvariantCulture) == 0) + { return values[i]; } - - if (bestMatch == -1 && 0 == string.Compare(names[i], s, true, CultureInfo.InvariantCulture)) { + + if (bestMatch == -1 && 0 == string.Compare(names[i], s, true, CultureInfo.InvariantCulture)) + { bestMatch = i; } } - - if (bestMatch != -1) { - return values[bestMatch]; + + if (bestMatch != -1) + { + return values[bestMatch]; } - + return allowUnknownValues ? s : null; } - protected virtual void PopulateArrays(string[] names, object[] values) { + protected virtual void PopulateArrays(string[] names, object[] values) + { // setup our values...since we have to walk through // them anyway to do the ToString, we just copy them here. this.names = new string[names.Length]; this.stringValues = new string[names.Length]; this.values = new object[names.Length]; - for (int i = 0; i < names.Length; i++) { + for (int i = 0; i < names.Length; i++) + { //Debug.WriteLine(names[i] + ": item " + i.ToString() + ",type=" + values[i].GetType().Name + ", value=" + values[i].ToString()); this.names[i] = names[i]; this.values[i] = values[i]; - if (values[i] != null) { + if (values[i] != null) + { this.stringValues[i] = values[i].ToString(); } } @@ -135,16 +153,21 @@ protected virtual void PopulateArrays(string[] names, object[] values) { /// /// Retrieves the string name of a given value. /// - public virtual string ToString(object v) { - if (v != null) { + public virtual string ToString(object v) + { + if (v != null) + { // in case this is a real enum...try to convert it. // - if (values.Length > 0 && v.GetType() != values[0].GetType()) { - try { + if (values.Length > 0 && v.GetType() != values[0].GetType()) + { + try + { v = Convert.ChangeType(v, values[0].GetType(), CultureInfo.InvariantCulture); } - catch{ + catch + { } } @@ -152,12 +175,15 @@ public virtual string ToString(object v) { // in a lot of objects in COM2 (DWORD -> VT_IU4, value we get is VT_I4, which // convert to Int32, UInt32 respectively string strVal = v.ToString(); - for (int i = 0; i < values.Length; i++) { - if (string.Compare(stringValues[i], strVal, true, CultureInfo.InvariantCulture) == 0) { + for (int i = 0; i < values.Length; i++) + { + if (string.Compare(stringValues[i], strVal, true, CultureInfo.InvariantCulture) == 0) + { return names[i]; } } - if (allowUnknownValues) { + if (allowUnknownValues) + { return strVal; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2EnumConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2EnumConverter.cs index 7cd8314f3ec..1a78d2a6c0a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2EnumConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2EnumConverter.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.Diagnostics; using System; @@ -13,44 +14,52 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop { using Microsoft.Win32; using System.Globalization; - internal class Com2EnumConverter : TypeConverter { + internal class Com2EnumConverter : TypeConverter + { internal readonly Com2Enum com2Enum; - private StandardValuesCollection values; + private StandardValuesCollection values; - public Com2EnumConverter(Com2Enum enumObj) { + public Com2EnumConverter(Com2Enum enumObj) + { com2Enum = enumObj; } - + /// /// Determines if this converter can convert an object in the given source /// type to the native type of the converter. /// - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { - if (sourceType == typeof(string)) { + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + { + if (sourceType == typeof(string)) + { return true; } return base.CanConvertFrom(context, sourceType); } - public override bool CanConvertTo(ITypeDescriptorContext context, Type destType) { - if (base.CanConvertTo(context, destType)) { - return true; - } - return destType.IsEnum; - } + public override bool CanConvertTo(ITypeDescriptorContext context, Type destType) + { + if (base.CanConvertTo(context, destType)) + { + return true; + } + return destType.IsEnum; + } /// /// Converts the given object to the converter's native type. /// - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - if (value is string) { - return com2Enum.FromString((string)value); + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + { + if (value is string) + { + return com2Enum.FromString((string)value); } return base.ConvertFrom(context, culture, value); } - + /// /// Converts the given object to another type. The most common types to convert /// are to and from a string object. The default implementation will make a call @@ -58,40 +67,48 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) { + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == null) + { throw new ArgumentNullException(nameof(destinationType)); } - if (destinationType == typeof(string)) { - if (value != null) { + if (destinationType == typeof(string)) + { + if (value != null) + { string str = com2Enum.ToString(value); return (str == null ? "" : str); } } - if (destinationType.IsEnum) { + if (destinationType.IsEnum) + { return Enum.ToObject(destinationType, value); } return base.ConvertTo(context, culture, value, destinationType); } - + /// /// Retrieves a collection containing a set of standard values /// for the data type this validator is designed for. This /// will return null if the data type does not support a /// standard set of values. /// - public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { - if (values == null) { + public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) + { + if (values == null) + { object[] objValues = com2Enum.Values; - if (objValues != null) { + if (objValues != null) + { values = new StandardValuesCollection(objValues); } } return values; } - + /// /// Determines if the list of standard values returned from /// GetStandardValues is an exclusive list. If the list @@ -100,27 +117,31 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex /// then there are other valid values besides the list of /// standard values GetStandardValues provides. /// - public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { + public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) + { return com2Enum.IsStrictEnum; } - + /// /// Determines if this object supports a standard set of values /// that can be picked from a list. /// - public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { + public override bool GetStandardValuesSupported(ITypeDescriptorContext context) + { return true; } - + /// /// Determines if the given object value is valid for this type. /// - public override bool IsValid(ITypeDescriptorContext context, object value) { + public override bool IsValid(ITypeDescriptorContext context, object value) + { string strValue = com2Enum.ToString(value); return strValue != null && strValue.Length > 0; } - public void RefreshValues() { + public void RefreshValues() + { this.values = null; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedBrowsingHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedBrowsingHandler.cs index fa0d08eece8..1308a8219af 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedBrowsingHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedBrowsingHandler.cs @@ -2,12 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.ComponentModel; using System.Diagnostics; using System; - + /// /// This is the base class for handlers for COM2 extended browsing interface /// such as IPerPropertyBrowsing, etc. @@ -19,30 +20,33 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop { /// See COM2Properties for the array of handler classes to interface classes /// where handlers should be registered. /// - internal abstract class Com2ExtendedBrowsingHandler{ - - /// - /// The interface that this handler managers - /// such as IPerPropertyBrowsing, IProvidePropertyBuilder, etc. - /// - public abstract Type Interface{ + internal abstract class Com2ExtendedBrowsingHandler + { + + /// + /// The interface that this handler managers + /// such as IPerPropertyBrowsing, IProvidePropertyBuilder, etc. + /// + public abstract Type Interface + { get; - } - - /// - /// Called to setup the property handlers on a given property - /// In this method, the handler will add listeners to the events that - /// the COM2PropertyDescriptor surfaces that it cares about. - /// - public virtual void SetupPropertyHandlers(Com2PropertyDescriptor propDesc){ - SetupPropertyHandlers(new Com2PropertyDescriptor[]{propDesc}); - } - - /// - /// Called to setup the property handlers on a given properties - /// In this method, the handler will add listeners to the events that - /// the Com2PropertyDescriptor surfaces that it cares about. - /// - public abstract void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc); + } + + /// + /// Called to setup the property handlers on a given property + /// In this method, the handler will add listeners to the events that + /// the COM2PropertyDescriptor surfaces that it cares about. + /// + public virtual void SetupPropertyHandlers(Com2PropertyDescriptor propDesc) + { + SetupPropertyHandlers(new Com2PropertyDescriptor[] { propDesc }); + } + + /// + /// Called to setup the property handlers on a given properties + /// In this method, the handler will add listeners to the events that + /// the Com2PropertyDescriptor surfaces that it cares about. + /// + public abstract void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedTypeConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedTypeConverter.cs index 95593254990..81a3901ff30 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedTypeConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedTypeConverter.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.Diagnostics; @@ -12,82 +13,98 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop { using System.Drawing; using Microsoft.Win32; using System.Globalization; - + using System.Collections; /// /// Base class for value editors that extend basic functionality. /// calls will be delegated to the "base value editor". /// - internal class Com2ExtendedTypeConverter : TypeConverter { - private TypeConverter innerConverter; - - public Com2ExtendedTypeConverter(TypeConverter innerConverter) { + internal class Com2ExtendedTypeConverter : TypeConverter + { + private TypeConverter innerConverter; + + public Com2ExtendedTypeConverter(TypeConverter innerConverter) + { this.innerConverter = innerConverter; - } - - public Com2ExtendedTypeConverter(Type baseType) { + } + + public Com2ExtendedTypeConverter(Type baseType) + { this.innerConverter = TypeDescriptor.GetConverter(baseType); - } - - public TypeConverter InnerConverter { - get { - return innerConverter; + } + + public TypeConverter InnerConverter + { + get + { + return innerConverter; } - } - - public TypeConverter GetWrappedConverter(Type t) { - + } + + public TypeConverter GetWrappedConverter(Type t) + { + TypeConverter converter = innerConverter; - - while (converter != null) { - if (t.IsInstanceOfType(converter)) { + + while (converter != null) + { + if (t.IsInstanceOfType(converter)) + { return converter; } - - if (converter is Com2ExtendedTypeConverter) { + + if (converter is Com2ExtendedTypeConverter) + { converter = ((Com2ExtendedTypeConverter)converter).InnerConverter; } - else { + else + { break; } } return null; - } - - + } + + /// /// Determines if this converter can convert an object in the given source /// type to the native type of the converter. /// - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { - if (innerConverter != null) { - return innerConverter.CanConvertFrom(context, sourceType); + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + { + if (innerConverter != null) + { + return innerConverter.CanConvertFrom(context, sourceType); } return base.CanConvertFrom(context, sourceType); } - + /// /// Determines if this converter can convert an object to the given destination /// type. /// - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { - if (innerConverter != null) { - return innerConverter.CanConvertTo(context, destinationType); + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) + { + if (innerConverter != null) + { + return innerConverter.CanConvertTo(context, destinationType); } return base.CanConvertTo(context, destinationType); } - + /// /// Converts the given object to the converter's native type. /// - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - if (innerConverter != null) { - return innerConverter.ConvertFrom(context, culture, value); + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + { + if (innerConverter != null) + { + return innerConverter.ConvertFrom(context, culture, value); } return base.ConvertFrom(context, culture, value); } - + /// /// Converts the given object to another type. The most common types to convert /// are to and from a string object. The default implementation will make a call @@ -95,72 +112,84 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (innerConverter != null) { - return innerConverter.ConvertTo(context, culture, value, destinationType); + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (innerConverter != null) + { + return innerConverter.ConvertTo(context, culture, value, destinationType); } return base.ConvertTo(context, culture, value, destinationType); } - + /// /// Creates an instance of this type given a set of property values /// for the object. This is useful for objects that are immutable, but still /// want to provide changable properties. /// - public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) { - if (innerConverter != null) { - return innerConverter.CreateInstance(context, propertyValues); + public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) + { + if (innerConverter != null) + { + return innerConverter.CreateInstance(context, propertyValues); } return base.CreateInstance(context, propertyValues); } - + /// /// Determines if changing a value on this object should require a call to /// CreateInstance to create a new value. /// - public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) { - if (innerConverter != null) { - return innerConverter.GetCreateInstanceSupported(context); + public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) + { + if (innerConverter != null) + { + return innerConverter.GetCreateInstanceSupported(context); } return base.GetCreateInstanceSupported(context); } - + /// /// Retrieves the set of properties for this type. By default, a type has /// does not return any properties. An easy implementation of this method /// can just call TypeDescriptor.GetProperties for the correct data type. /// - public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { - if (innerConverter != null) { - return innerConverter.GetProperties(context, value, attributes); + public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) + { + if (innerConverter != null) + { + return innerConverter.GetProperties(context, value, attributes); } return base.GetProperties(context, value, attributes); } - + /// /// Determines if this object supports properties. By default, this /// is false. /// - public override bool GetPropertiesSupported(ITypeDescriptorContext context) { - if (innerConverter != null) { - return innerConverter.GetPropertiesSupported(context); + public override bool GetPropertiesSupported(ITypeDescriptorContext context) + { + if (innerConverter != null) + { + return innerConverter.GetPropertiesSupported(context); } return base.GetPropertiesSupported(context); } - + /// /// Retrieves a collection containing a set of standard values /// for the data type this validator is designed for. This /// will return null if the data type does not support a /// standard set of values. /// - public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { - if (innerConverter != null) { - return innerConverter.GetStandardValues(context); + public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) + { + if (innerConverter != null) + { + return innerConverter.GetStandardValues(context); } return base.GetStandardValues(context); } - + /// /// Determines if the list of standard values returned from /// GetStandardValues is an exclusive list. If the list @@ -169,30 +198,36 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex /// then there are other valid values besides the list of /// standard values GetStandardValues provides. /// - public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { - if (innerConverter != null) { - return innerConverter.GetStandardValuesExclusive(context); + public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) + { + if (innerConverter != null) + { + return innerConverter.GetStandardValuesExclusive(context); } return base.GetStandardValuesExclusive(context); } - + /// /// Determines if this object supports a standard set of values /// that can be picked from a list. /// - public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { - if (innerConverter != null) { - return innerConverter.GetStandardValuesSupported(context); + public override bool GetStandardValuesSupported(ITypeDescriptorContext context) + { + if (innerConverter != null) + { + return innerConverter.GetStandardValuesSupported(context); } return base.GetStandardValuesSupported(context); } - + /// /// Determines if the given object value is valid for this type. /// - public override bool IsValid(ITypeDescriptorContext context, object value) { - if (innerConverter != null) { - return innerConverter.IsValid(context, value); + public override bool IsValid(ITypeDescriptorContext context, object value) + { + if (innerConverter != null) + { + return innerConverter.IsValid(context, value); } return base.IsValid(context, value); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedUITypeEditor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedUITypeEditor.cs index a91a344da35..0b6ae896036 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedUITypeEditor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedUITypeEditor.cs @@ -2,10 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Drawing.Design.Com2ExtendedUITypeEditor..ctor(System.Type)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.Design.Com2ExtendedUITypeEditor..ctor(System.Type)")] -namespace System.Drawing.Design { +namespace System.Drawing.Design +{ using System.Diagnostics; @@ -20,45 +21,55 @@ namespace System.Drawing.Design { /// Provides an editor that provides a way to visually edit the values of a COM2 /// type. /// - internal class Com2ExtendedUITypeEditor : UITypeEditor { - + internal class Com2ExtendedUITypeEditor : UITypeEditor + { + private UITypeEditor innerEditor; - - public Com2ExtendedUITypeEditor(UITypeEditor baseTypeEditor) { + + public Com2ExtendedUITypeEditor(UITypeEditor baseTypeEditor) + { this.innerEditor = baseTypeEditor; } - - public Com2ExtendedUITypeEditor(Type baseType) { + + public Com2ExtendedUITypeEditor(Type baseType) + { this.innerEditor = (UITypeEditor)TypeDescriptor.GetEditor(baseType, typeof(UITypeEditor)); } - - public UITypeEditor InnerEditor { - get { - return innerEditor; + + public UITypeEditor InnerEditor + { + get + { + return innerEditor; } } - + /// /// Edits the given object value using the editor style provided by /// GetEditorStyle. A service provider is provided so that any /// required editing services can be obtained. /// - public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { - if (innerEditor != null) { - return innerEditor.EditValue(context, provider, value); + public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) + { + if (innerEditor != null) + { + return innerEditor.EditValue(context, provider, value); } - else { - return base.EditValue(context, provider, value); + else + { + return base.EditValue(context, provider, value); } } - + /// /// Determines if this editor supports the painting of a representation /// of an object's value. /// - public override bool GetPaintValueSupported(ITypeDescriptorContext context) { - if (innerEditor != null) { - return innerEditor.GetPaintValueSupported(context); + public override bool GetPaintValueSupported(ITypeDescriptorContext context) + { + if (innerEditor != null) + { + return innerEditor.GetPaintValueSupported(context); } return base.GetPaintValueSupported(context); } @@ -67,9 +78,11 @@ public override bool GetPaintValueSupported(ITypeDescriptorContext context) { /// Retrieves the editing style of the Edit method. If the method /// is not supported, this will return None. /// - public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { - if (innerEditor != null) { - return innerEditor.GetEditStyle(context); + public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) + { + if (innerEditor != null) + { + return innerEditor.GetEditStyle(context); } return base.GetEditStyle(context); } @@ -79,9 +92,11 @@ public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext contex /// canvas. Painting should be done within the boundaries of the /// provided rectangle. /// - public override void PaintValue(PaintValueEventArgs e) { - if (innerEditor != null) { - innerEditor.PaintValue(e); + public override void PaintValue(PaintValueEventArgs e) + { + if (innerEditor != null) + { + innerEditor.PaintValue(e); } base.PaintValue(e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2FontConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2FontConverter.cs index dcfb2545ce6..5d1bd14412a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2FontConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2FontConverter.cs @@ -2,12 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; - using System; + using System; using System.Drawing; using System.Collections; using Microsoft.Win32; @@ -16,22 +17,27 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop { /// /// This class maps an OLE_COLOR to a managed Color editor. /// - internal class Com2FontConverter : Com2DataTypeToManagedDataTypeConverter { + internal class Com2FontConverter : Com2DataTypeToManagedDataTypeConverter + { private IntPtr lastHandle = IntPtr.Zero; - private Font lastFont = null; + private Font lastFont = null; - public override bool AllowExpand { - get { - return true; - } - } + public override bool AllowExpand + { + get + { + return true; + } + } /// /// Returns the managed type that this editor maps the property type to. /// - public override Type ManagedType { - get { + public override Type ManagedType + { + get + { return typeof(Font); } } @@ -39,11 +45,13 @@ public override Type ManagedType { /// /// Converts the native value into a managed value /// - public override object ConvertNativeToManaged(object nativeValue, Com2PropertyDescriptor pd) { + public override object ConvertNativeToManaged(object nativeValue, Com2PropertyDescriptor pd) + { // we're getting an IFont thing here UnsafeNativeMethods.IFont nativeFont = nativeValue as UnsafeNativeMethods.IFont; - if (nativeFont == null) { + if (nativeFont == null) + { lastHandle = IntPtr.Zero; lastFont = Control.DefaultFont; return lastFont; @@ -52,47 +60,55 @@ public override object ConvertNativeToManaged(object nativeValue, Com2PropertyDe IntPtr fontHandle = nativeFont.GetHFont(); // see if we have this guy cached - if (fontHandle == lastHandle && lastFont != null) { + if (fontHandle == lastHandle && lastFont != null) + { return lastFont; } lastHandle = fontHandle; - - try { + + try + { // this wasn't working because it was converting everything to // world units. // Font font = Font.FromHfont(lastHandle); - try { + try + { lastFont = ControlPaint.FontInPoints(font); - } - finally { + } + finally + { font.Dispose(); } } - catch(ArgumentException) { + catch (ArgumentException) + { // we will fail on non-truetype fonts, so // just use the default font. lastFont = Control.DefaultFont; } - + return lastFont; } /// /// Converts the managed value into a native value /// - public override object ConvertManagedToNative(object managedValue, Com2PropertyDescriptor pd, ref bool cancelSet) { + public override object ConvertManagedToNative(object managedValue, Com2PropertyDescriptor pd, ref bool cancelSet) + { // we default to black. // - if (managedValue == null) { + if (managedValue == null) + { managedValue = Control.DefaultFont; } cancelSet = true; - if (lastFont != null && lastFont.Equals(managedValue)) { + if (lastFont != null && lastFont.Equals(managedValue)) + { // don't do anything here. return null; } @@ -101,10 +117,12 @@ public override object ConvertManagedToNative(object managedValue, Com2PropertyD UnsafeNativeMethods.IFont nativeFont = (UnsafeNativeMethods.IFont)pd.GetNativeValue(pd.TargetObject); // now, push all the values into the native side - if (nativeFont != null) { + if (nativeFont != null) + { bool changed = ControlPaint.FontToIFont(lastFont, nativeFont); - if (changed) { + if (changed) + { // here, we want to pick up a new font from the handle lastFont = null; ConvertNativeToManaged(nativeFont, pd); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ICategorizePropertiesHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ICategorizePropertiesHandler.cs index bd0267e1863..7547690756d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ICategorizePropertiesHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ICategorizePropertiesHandler.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System; using System.Collections; using System.ComponentModel; @@ -10,29 +11,38 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop { using System.Globalization; using Microsoft.Win32; - internal class Com2ICategorizePropertiesHandler : Com2ExtendedBrowsingHandler { + internal class Com2ICategorizePropertiesHandler : Com2ExtendedBrowsingHandler + { - public override Type Interface { - get { + public override Type Interface + { + get + { return typeof(NativeMethods.ICategorizeProperties); } } - private string GetCategoryFromObject(object obj, int dispid) { - if (obj == null) { + private string GetCategoryFromObject(object obj, int dispid) + { + if (obj == null) + { return null; } - if (obj is NativeMethods.ICategorizeProperties) { + if (obj is NativeMethods.ICategorizeProperties) + { NativeMethods.ICategorizeProperties catObj = (NativeMethods.ICategorizeProperties)obj; - try { + try + { int categoryID = 0; - if (NativeMethods.S_OK == catObj.MapPropertyToCategory(dispid, ref categoryID)) { + if (NativeMethods.S_OK == catObj.MapPropertyToCategory(dispid, ref categoryID)) + { string categoryName = null; - - switch (categoryID) { + + switch (categoryID) + { case NativeMethods.ActiveX.PROPCAT_Nil: return ""; case NativeMethods.ActiveX.PROPCAT_Misc: @@ -56,32 +66,39 @@ private string GetCategoryFromObject(object obj, int dispid) { case NativeMethods.ActiveX.PROPCAT_DDE: return SR.PropertyCategoryDDE; } - - if (NativeMethods.S_OK == catObj.GetCategoryName(categoryID, CultureInfo.CurrentCulture.LCID, out categoryName)) { + + if (NativeMethods.S_OK == catObj.GetCategoryName(categoryID, CultureInfo.CurrentCulture.LCID, out categoryName)) + { return categoryName; } } } - catch { + catch + { } } return null; } - public override void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc) { - if (propDesc == null) { + public override void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc) + { + if (propDesc == null) + { return; } - for (int i = 0; i < propDesc.Length; i++) { + for (int i = 0; i < propDesc.Length; i++) + { propDesc[i].QueryGetBaseAttributes += new GetAttributesEventHandler(this.OnGetAttributes); } } - private void OnGetAttributes(Com2PropertyDescriptor sender, GetAttributesEvent attrEvent) { + private void OnGetAttributes(Com2PropertyDescriptor sender, GetAttributesEvent attrEvent) + { string cat = GetCategoryFromObject(sender.TargetObject, sender.DISPID); - if (cat != null && cat.Length > 0) { + if (cat != null && cat.Length > 0) + { attrEvent.Add(new CategoryAttribute(cat)); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IDispatchConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IDispatchConverter.cs index 674414c6df5..7074c126e7c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IDispatchConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IDispatchConverter.cs @@ -2,17 +2,19 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.Diagnostics; using System; - + using System.ComponentModel; using System.Collections; using Microsoft.Win32; using System.Globalization; - internal class Com2IDispatchConverter : Com2ExtendedTypeConverter{ + internal class Com2IDispatchConverter : Com2ExtendedTypeConverter + { Com2PropertyDescriptor propDesc; /// @@ -23,34 +25,38 @@ internal class Com2IDispatchConverter : Com2ExtendedTypeConverter{ private bool allowExpand; - public Com2IDispatchConverter(Com2PropertyDescriptor propDesc, bool allowExpand, TypeConverter baseConverter) : base(baseConverter){ - this.propDesc = propDesc; - this.allowExpand = allowExpand; + public Com2IDispatchConverter(Com2PropertyDescriptor propDesc, bool allowExpand, TypeConverter baseConverter) : base(baseConverter) + { + this.propDesc = propDesc; + this.allowExpand = allowExpand; } - public Com2IDispatchConverter(Com2PropertyDescriptor propDesc, bool allowExpand) : base(propDesc.PropertyType){ - this.propDesc = propDesc; - this.allowExpand = allowExpand; + public Com2IDispatchConverter(Com2PropertyDescriptor propDesc, bool allowExpand) : base(propDesc.PropertyType) + { + this.propDesc = propDesc; + this.allowExpand = allowExpand; } - + /// /// Determines if this converter can convert an object in the given source /// type to the native type of the converter. /// - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + { return false; } - + /// /// Determines if this converter can convert an object to the given destination /// type. /// - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) + { return destinationType == typeof(string); } - - + + /// /// Converts the given object to another type. The most common types to convert /// are to and from a string object. The default implementation will make a call @@ -58,41 +64,49 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == typeof(string)){ - if (value == null){ - return none; - } - - string text = ComNativeDescriptor.Instance.GetName(value); - - if (text == null || text.Length == 0){ - text = ComNativeDescriptor.Instance.GetClassName(value); - } - - if (text == null){ - return "(Object)"; - } - return text; + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == typeof(string)) + { + if (value == null) + { + return none; + } + + string text = ComNativeDescriptor.Instance.GetName(value); + + if (text == null || text.Length == 0) + { + text = ComNativeDescriptor.Instance.GetClassName(value); + } + + if (text == null) + { + return "(Object)"; + } + return text; } return base.ConvertTo(context, culture, value, destinationType); } - - public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { + + public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) + { return TypeDescriptor.GetProperties(value, attributes); } - + /// /// Determines if this object supports properties. By default, this /// is false. /// - public override bool GetPropertiesSupported(ITypeDescriptorContext context) { + public override bool GetPropertiesSupported(ITypeDescriptorContext context) + { return this.allowExpand; } - + // no dropdown, please! // - public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { + public override bool GetStandardValuesSupported(ITypeDescriptorContext context) + { return false; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IManagedPerPropertyBrowsingHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IManagedPerPropertyBrowsingHandler.cs index 01ea2069b3a..3145fffa20c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IManagedPerPropertyBrowsingHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IManagedPerPropertyBrowsingHandler.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; @@ -12,19 +13,25 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop { using System.Collections; using System.Globalization; - internal class Com2IManagedPerPropertyBrowsingHandler : Com2ExtendedBrowsingHandler { + internal class Com2IManagedPerPropertyBrowsingHandler : Com2ExtendedBrowsingHandler + { - public override Type Interface { - get { + public override Type Interface + { + get + { return typeof(NativeMethods.IManagedPerPropertyBrowsing); } } - public override void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc) { - if (propDesc == null) { + public override void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc) + { + if (propDesc == null) + { return; } - for (int i = 0; i < propDesc.Length; i++) { + for (int i = 0; i < propDesc.Length; i++) + { propDesc[i].QueryGetDynamicAttributes += new GetAttributesEventHandler(this.OnGetAttributes); } } @@ -33,27 +40,33 @@ public override void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc) { /// Here is where we handle IVsPerPropertyBrowsing.GetLocalizedPropertyInfo and IVsPerPropertyBrowsing. HideProperty /// such as IPerPropertyBrowsing, IProvidePropertyBuilder, etc. /// - private void OnGetAttributes(Com2PropertyDescriptor sender, GetAttributesEvent attrEvent) { + private void OnGetAttributes(Com2PropertyDescriptor sender, GetAttributesEvent attrEvent) + { object target = sender.TargetObject; - if (target is NativeMethods.IManagedPerPropertyBrowsing) { - Attribute[] attrs = GetComponentAttributes((NativeMethods.IManagedPerPropertyBrowsing)target,sender.DISPID); - if (attrs != null) { - for (int i = 0; i < attrs.Length; i++) { + if (target is NativeMethods.IManagedPerPropertyBrowsing) + { + Attribute[] attrs = GetComponentAttributes((NativeMethods.IManagedPerPropertyBrowsing)target, sender.DISPID); + if (attrs != null) + { + for (int i = 0; i < attrs.Length; i++) + { attrEvent.Add(attrs[i]); } } } } - internal static Attribute[] GetComponentAttributes(NativeMethods.IManagedPerPropertyBrowsing target, int dispid) { + internal static Attribute[] GetComponentAttributes(NativeMethods.IManagedPerPropertyBrowsing target, int dispid) + { int cItems = 0; IntPtr pbstrs = IntPtr.Zero; IntPtr pvars = IntPtr.Zero; int hr = target.GetPropertyAttributes(dispid, ref cItems, ref pbstrs, ref pvars); - if (hr != NativeMethods.S_OK || cItems == 0) { + if (hr != NativeMethods.S_OK || cItems == 0) + { return new Attribute[0]; } @@ -63,25 +76,29 @@ internal static Attribute[] GetComponentAttributes(NativeMethods.IManagedPerProp object[] varParams = GetVariantsFromPtr(pvars, cItems); Debug.Assert(attrTypeNames.Length == varParams.Length, "Mismatched parameter and attribute name length"); - if (attrTypeNames.Length != varParams.Length) { + if (attrTypeNames.Length != varParams.Length) + { return new Attribute[0]; } // get the types Type[] types = new Type[attrTypeNames.Length]; - for (int i = 0; i < attrTypeNames.Length; i++) { - + for (int i = 0; i < attrTypeNames.Length; i++) + { + string attrName = attrTypeNames[i]; - + // try the name first Type t = Type.GetType(attrName); Assembly a = null; - - if (t != null) { - a = t.Assembly; + + if (t != null) + { + a = t.Assembly; } - if (t == null) { + if (t == null) + { // check for an assembly name. @@ -90,61 +107,73 @@ internal static Attribute[] GetComponentAttributes(NativeMethods.IManagedPerProp int comma = attrName.LastIndexOf(','); - if (comma != -1) { + if (comma != -1) + { assemblyName = attrName.Substring(comma); attrName = attrName.Substring(0, comma); } string fieldName; int lastDot = attrName.LastIndexOf('.'); - if (lastDot != -1) { + if (lastDot != -1) + { fieldName = attrName.Substring(lastDot + 1); } - else { + else + { // somethings odd Debug.Fail("No dot in class name?"); continue; } // try to get the field value - if (a == null) { - t = Type.GetType(attrName.Substring(0,lastDot) + assemblyName); + if (a == null) + { + t = Type.GetType(attrName.Substring(0, lastDot) + assemblyName); } - else { - t = a.GetType(attrName.Substring(0,lastDot) + assemblyName); + else + { + t = a.GetType(attrName.Substring(0, lastDot) + assemblyName); } - if (t == null){ + if (t == null) + { Debug.Fail("Failed load attribute '" + attrName + assemblyName + "'. It's Type could not be found."); continue; } Debug.Assert(typeof(Attribute).IsAssignableFrom(t), "Attribute type " + t.FullName + " does not derive from Attribute"); - if (!typeof(Attribute).IsAssignableFrom(t)) { + if (!typeof(Attribute).IsAssignableFrom(t)) + { continue; } - if (t != null) { + if (t != null) + { FieldInfo fi = t.GetField(fieldName); // only if it's static - if (fi != null && fi.IsStatic) { + if (fi != null && fi.IsStatic) + { object fieldValue = fi.GetValue(null); - if (fieldValue is Attribute) { + if (fieldValue is Attribute) + { // add it to the list attrs.Add(fieldValue); continue; } } - else { - Debug.Fail("Couldn't load field '" + fieldName + "' from type '" + attrName.Substring(0,lastDot) + "'. It does not exist or is not static"); + else + { + Debug.Fail("Couldn't load field '" + fieldName + "' from type '" + attrName.Substring(0, lastDot) + "'. It does not exist or is not static"); } } } Debug.Assert(typeof(Attribute).IsAssignableFrom(t), "Attribute type " + t.FullName + " does not derive from Attribute"); - if (!typeof(Attribute).IsAssignableFrom(t)) { + if (!typeof(Attribute).IsAssignableFrom(t)) + { continue; } @@ -153,18 +182,23 @@ internal static Attribute[] GetComponentAttributes(NativeMethods.IManagedPerProp // okay, if we got here, we need to build the attribute... // get the initalizer value if we've got a one item ctor - if (!Convert.IsDBNull(varParams[i]) && varParams[i] != null) { + if (!Convert.IsDBNull(varParams[i]) && varParams[i] != null) + { ConstructorInfo[] ctors = t.GetConstructors(); - for (int c=0; c < ctors.Length; c++) { + for (int c = 0; c < ctors.Length; c++) + { ParameterInfo[] pis = ctors[c].GetParameters(); - if (pis.Length == 1 && pis[0].ParameterType.IsAssignableFrom(varParams[i].GetType())) { + if (pis.Length == 1 && pis[0].ParameterType.IsAssignableFrom(varParams[i].GetType())) + { // found a one-parameter ctor, use it // try to construct a default one - try { - attr = (Attribute)Activator.CreateInstance(t, new object[]{varParams[i]}); + try + { + attr = (Attribute)Activator.CreateInstance(t, new object[] { varParams[i] }); attrs.Add(attr); } - catch { + catch + { // nevermind Debug.Fail("Attribute " + t.FullName + " did not have a initalizer specified and has no default constructor"); continue; @@ -172,13 +206,16 @@ internal static Attribute[] GetComponentAttributes(NativeMethods.IManagedPerProp } } } - else { + else + { // try to construct a default one - try { + try + { attr = (Attribute)Activator.CreateInstance(t); attrs.Add(attr); } - catch { + catch + { // nevermind Debug.Fail("Attribute " + t.FullName + " did not have a initalizer specified and has no default constructor"); continue; @@ -191,67 +228,87 @@ internal static Attribute[] GetComponentAttributes(NativeMethods.IManagedPerProp return temp; } - private static string[] GetStringsFromPtr(IntPtr ptr, int cStrings) { - if (ptr != IntPtr.Zero) { + private static string[] GetStringsFromPtr(IntPtr ptr, int cStrings) + { + if (ptr != IntPtr.Zero) + { string[] strs = new string[cStrings]; IntPtr bstr; - for (int i = 0; i < cStrings; i++) { - try{ - bstr = Marshal.ReadIntPtr(ptr, i*4); - if (bstr != IntPtr.Zero) { + for (int i = 0; i < cStrings; i++) + { + try + { + bstr = Marshal.ReadIntPtr(ptr, i * 4); + if (bstr != IntPtr.Zero) + { strs[i] = Marshal.PtrToStringUni(bstr); SafeNativeMethods.SysFreeString(new HandleRef(null, bstr)); } - else { + else + { strs[i] = string.Empty; } } - catch (Exception ex) { + catch (Exception ex) + { Debug.Fail("Failed to marshal component attribute BSTR " + i.ToString(CultureInfo.InvariantCulture), ex.ToString()); } } - try{ + try + { Marshal.FreeCoTaskMem(ptr); } - catch (Exception ex) { + catch (Exception ex) + { Debug.Fail("Failed to free BSTR array memory", ex.ToString()); } return strs; } - else { + else + { return new string[0]; } } - private static object[] GetVariantsFromPtr(IntPtr ptr, int cVariants) { - if (ptr != IntPtr.Zero) { + private static object[] GetVariantsFromPtr(IntPtr ptr, int cVariants) + { + if (ptr != IntPtr.Zero) + { object[] objects = new object[cVariants]; IntPtr curVariant; - - for (int i = 0; i < cVariants; i++) { - try{ - curVariant = (IntPtr)((long)ptr + (i* 16 /*sizeof(VARIANT)*/)); - if (curVariant != IntPtr.Zero) { + + for (int i = 0; i < cVariants; i++) + { + try + { + curVariant = (IntPtr)((long)ptr + (i * 16 /*sizeof(VARIANT)*/)); + if (curVariant != IntPtr.Zero) + { objects[i] = Marshal.GetObjectForNativeVariant(curVariant); SafeNativeMethods.VariantClear(new HandleRef(null, curVariant)); } - else { + else + { objects[i] = Convert.DBNull; } } - catch (Exception ex) { + catch (Exception ex) + { Debug.Fail("Failed to marshal component attribute VARIANT " + i.ToString(CultureInfo.InvariantCulture), ex.ToString()); } } - try{ + try + { Marshal.FreeCoTaskMem(ptr); } - catch (Exception ex) { + catch (Exception ex) + { Debug.Fail("Failed to free VARIANT array memory", ex.ToString()); } return objects; } - else { + else + { return new object[cVariants]; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs index 890d09b4f0f..b7a41fd4e77 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; @@ -12,46 +13,57 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop { using System.Globalization; using System.Drawing.Design; - internal class Com2IPerPropertyBrowsingHandler : Com2ExtendedBrowsingHandler { - public override Type Interface { - get { + internal class Com2IPerPropertyBrowsingHandler : Com2ExtendedBrowsingHandler + { + public override Type Interface + { + get + { return typeof(NativeMethods.IPerPropertyBrowsing); } } - public override void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc) { - if (propDesc == null) { + public override void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc) + { + if (propDesc == null) + { return; } - for (int i = 0; i < propDesc.Length; i++) { + for (int i = 0; i < propDesc.Length; i++) + { propDesc[i].QueryGetBaseAttributes += new GetAttributesEventHandler(this.OnGetBaseAttributes); propDesc[i].QueryGetDisplayValue += new GetNameItemEventHandler(this.OnGetDisplayValue); - + propDesc[i].QueryGetTypeConverterAndTypeEditor += new GetTypeConverterAndTypeEditorEventHandler(this.OnGetTypeConverterAndTypeEditor); } } - private Guid GetPropertyPageGuid(NativeMethods.IPerPropertyBrowsing target, int dispid) { + private Guid GetPropertyPageGuid(NativeMethods.IPerPropertyBrowsing target, int dispid) + { // check for a property page Guid guid; int hr = target.MapPropertyToPage(dispid, out guid); - if (hr == NativeMethods.S_OK) { + if (hr == NativeMethods.S_OK) + { return guid; } return Guid.Empty; } - - internal static string GetDisplayString(NativeMethods.IPerPropertyBrowsing ppb, int dispid, ref bool success) { + + internal static string GetDisplayString(NativeMethods.IPerPropertyBrowsing ppb, int dispid, ref bool success) + { string[] strVal = new string[1]; int hr = ppb.GetDisplayString(dispid, strVal); - if (hr == NativeMethods.S_OK) { + if (hr == NativeMethods.S_OK) + { success = (strVal[0] != null); //Debug.Assert(success, "IPerPropertyBrowsing::GetDisplayString returned NULL and S_OK -- this is not a valid state. This component does not property implement IPerPropertyBrowsing. (component class=" + TypeDescriptor.GetClassName(ppb) + ")"); return strVal[0]; } - else { + else + { success = false; - } + } return null; } @@ -59,47 +71,59 @@ internal static string GetDisplayString(NativeMethods.IPerPropertyBrowsing ppb, /// Here is where we handle IVsPerPropertyBrowsing.GetLocalizedPropertyInfo and IVsPerPropertyBrowsing. HideProperty /// such as IPerPropertyBrowsing, IProvidePropertyBuilder, etc. /// - private void OnGetBaseAttributes(Com2PropertyDescriptor sender, GetAttributesEvent attrEvent) { + private void OnGetBaseAttributes(Com2PropertyDescriptor sender, GetAttributesEvent attrEvent) + { NativeMethods.IPerPropertyBrowsing target = sender.TargetObject as NativeMethods.IPerPropertyBrowsing; - if (target != null) { + if (target != null) + { // we hide IDispatch props by default, we we need to force showing them here - + bool validPropPage = !Guid.Empty.Equals(GetPropertyPageGuid(target, sender.DISPID)); - - if (sender.CanShow && validPropPage) { - if (typeof(UnsafeNativeMethods.IDispatch).IsAssignableFrom(sender.PropertyType)) { + + if (sender.CanShow && validPropPage) + { + if (typeof(UnsafeNativeMethods.IDispatch).IsAssignableFrom(sender.PropertyType)) + { attrEvent.Add(BrowsableAttribute.Yes); } } } } - private void OnGetDisplayValue(Com2PropertyDescriptor sender, GetNameItemEvent gnievent) { - try { - if (sender.TargetObject is NativeMethods.IPerPropertyBrowsing) { + private void OnGetDisplayValue(Com2PropertyDescriptor sender, GetNameItemEvent gnievent) + { + try + { + if (sender.TargetObject is NativeMethods.IPerPropertyBrowsing) + { // if we are using the dropdown, don't convert the value // or the values will change when we select them and call back // for the display value. - if (sender.Converter is Com2IPerPropertyEnumConverter || sender.ConvertingNativeType) { + if (sender.Converter is Com2IPerPropertyEnumConverter || sender.ConvertingNativeType) + { return; } - + bool success = true; - + string displayString = GetDisplayString((NativeMethods.IPerPropertyBrowsing)sender.TargetObject, sender.DISPID, ref success); - - if (success) { + + if (success) + { gnievent.Name = displayString; } } } - catch { + catch + { } } - private void OnGetTypeConverterAndTypeEditor(Com2PropertyDescriptor sender, GetTypeConverterAndTypeEditorEvent gveevent) { - if (sender.TargetObject is NativeMethods.IPerPropertyBrowsing) { + private void OnGetTypeConverterAndTypeEditor(Com2PropertyDescriptor sender, GetTypeConverterAndTypeEditorEvent gveevent) + { + if (sender.TargetObject is NativeMethods.IPerPropertyBrowsing) + { NativeMethods.IPerPropertyBrowsing ppb = (NativeMethods.IPerPropertyBrowsing)sender.TargetObject; bool hasStrings = false; @@ -110,10 +134,12 @@ private void OnGetTypeConverterAndTypeEditor(Com2PropertyDescriptor sender, GetT int hr = NativeMethods.S_OK; - try { + try + { hr = ppb.GetPredefinedStrings(sender.DISPID, caStrings, caCookies); } - catch(ExternalException ex){ + catch (ExternalException ex) + { hr = ex.ErrorCode; Debug.Fail("An exception occurred inside IPerPropertyBrowsing::GetPredefinedStrings(dispid=" + sender.DISPID + "), object type=" + new ComNativeDescriptor().GetClassName(ppb) + ". This is caused by an exception (usually an AV) inside the object being browsed, and is not a problem in the properties window."); } @@ -121,198 +147,233 @@ private void OnGetTypeConverterAndTypeEditor(Com2PropertyDescriptor sender, GetT // Terminate the existing editor if we created the current one // so if the items have disappeared, we don't hold onto the old // items. - if (gveevent.TypeConverter is Com2IPerPropertyEnumConverter) { + if (gveevent.TypeConverter is Com2IPerPropertyEnumConverter) + { gveevent.TypeConverter = null; } - if (hr != NativeMethods.S_OK) { + if (hr != NativeMethods.S_OK) + { hasStrings = false; } - else { + else + { hasStrings = true; } - if (hasStrings) { + if (hasStrings) + { OleStrCAMarshaler stringMarshaler = new OleStrCAMarshaler(caStrings); - Int32CAMarshaler intMarshaler = new Int32CAMarshaler(caCookies); - + Int32CAMarshaler intMarshaler = new Int32CAMarshaler(caCookies); - if (stringMarshaler.Count > 0 && intMarshaler.Count > 0) { + + if (stringMarshaler.Count > 0 && intMarshaler.Count > 0) + { gveevent.TypeConverter = new Com2IPerPropertyEnumConverter(new Com2IPerPropertyBrowsingEnum(sender, this, stringMarshaler, intMarshaler, true)); } - else { + else + { //hasStrings = false; } } - // if we didn't get any strings, try the proppage edtior - // - if (!hasStrings){ - - // this is a _bit_ of a backwards-compat work around... - // many older ActiveX controls will show a property page - // for all properties since the old grid would only put up the - // [...] button for "(Custom)". If we have a conversion editor, - // don't allow this to override it... - // - if (sender.ConvertingNativeType){ - return; - } - - Guid g = GetPropertyPageGuid(ppb, sender.DISPID); - - if (!Guid.Empty.Equals(g)){ - gveevent.TypeEditor = new Com2PropertyPageUITypeEditor(sender, g, (UITypeEditor)gveevent.TypeEditor); - } - } + // if we didn't get any strings, try the proppage edtior + // + if (!hasStrings) + { + + // this is a _bit_ of a backwards-compat work around... + // many older ActiveX controls will show a property page + // for all properties since the old grid would only put up the + // [...] button for "(Custom)". If we have a conversion editor, + // don't allow this to override it... + // + if (sender.ConvertingNativeType) + { + return; + } + + Guid g = GetPropertyPageGuid(ppb, sender.DISPID); + + if (!Guid.Empty.Equals(g)) + { + gveevent.TypeEditor = new Com2PropertyPageUITypeEditor(sender, g, (UITypeEditor)gveevent.TypeEditor); + } + } } } - - // this is just here so we can identify the enums that we added - private class Com2IPerPropertyEnumConverter : Com2EnumConverter { - private Com2IPerPropertyBrowsingEnum itemsEnum; - public Com2IPerPropertyEnumConverter(Com2IPerPropertyBrowsingEnum items) : base(items) { + + // this is just here so we can identify the enums that we added + private class Com2IPerPropertyEnumConverter : Com2EnumConverter + { + private Com2IPerPropertyBrowsingEnum itemsEnum; + public Com2IPerPropertyEnumConverter(Com2IPerPropertyBrowsingEnum items) : base(items) + { this.itemsEnum = items; - } - - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destType) { - - if (destType == typeof(string) && !itemsEnum.arraysFetched) { - object curValue = itemsEnum.target.GetValue(itemsEnum.target.TargetObject); - if (curValue == value || (curValue != null && curValue.Equals(value))) { - bool success = false; - string val = GetDisplayString((NativeMethods.IPerPropertyBrowsing)itemsEnum.target.TargetObject, itemsEnum.target.DISPID, ref success); - if (success) { - return val; - } - } - } - return base.ConvertTo(context, culture, value, destType); - } - } - - - // This exists for perf reasons. We delay doing this until we - // are actually asked for the array of values. - // - private class Com2IPerPropertyBrowsingEnum : Com2Enum { - - internal Com2PropertyDescriptor target; - private Com2IPerPropertyBrowsingHandler handler; - private OleStrCAMarshaler nameMarshaller; - private Int32CAMarshaler valueMarshaller; - internal bool arraysFetched; - //private bool standardValuesQueried; - - public Com2IPerPropertyBrowsingEnum(Com2PropertyDescriptor targetObject, Com2IPerPropertyBrowsingHandler handler, OleStrCAMarshaler names, Int32CAMarshaler values, bool allowUnknowns) : base(new string[0], new object[0], allowUnknowns) { + } + + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destType) + { + + if (destType == typeof(string) && !itemsEnum.arraysFetched) + { + object curValue = itemsEnum.target.GetValue(itemsEnum.target.TargetObject); + if (curValue == value || (curValue != null && curValue.Equals(value))) + { + bool success = false; + string val = GetDisplayString((NativeMethods.IPerPropertyBrowsing)itemsEnum.target.TargetObject, itemsEnum.target.DISPID, ref success); + if (success) + { + return val; + } + } + } + return base.ConvertTo(context, culture, value, destType); + } + } + + + // This exists for perf reasons. We delay doing this until we + // are actually asked for the array of values. + // + private class Com2IPerPropertyBrowsingEnum : Com2Enum + { + + internal Com2PropertyDescriptor target; + private Com2IPerPropertyBrowsingHandler handler; + private OleStrCAMarshaler nameMarshaller; + private Int32CAMarshaler valueMarshaller; + internal bool arraysFetched; + //private bool standardValuesQueried; + + public Com2IPerPropertyBrowsingEnum(Com2PropertyDescriptor targetObject, Com2IPerPropertyBrowsingHandler handler, OleStrCAMarshaler names, Int32CAMarshaler values, bool allowUnknowns) : base(new string[0], new object[0], allowUnknowns) + { this.target = targetObject; this.nameMarshaller = names; this.valueMarshaller = values; this.handler = handler; this.arraysFetched = false; - } + } - /// - /// Retrieve a copy of the value array - /// - public override object[] Values { - get { + /// + /// Retrieve a copy of the value array + /// + public override object[] Values + { + get + { EnsureArrays(); return base.Values; } - } - - /// - /// Retrieve a copy of the nme array. - /// - public override string[] Names { - get { + } + + /// + /// Retrieve a copy of the nme array. + /// + public override string[] Names + { + get + { EnsureArrays(); return base.Names; } - } - - /*internal bool StandardValuesQueried { - get { - this.standardValuesQueried = value; - } - } */ - - - // ensure that we have processed the caStructs into arrays - // of values and strings - // - private void EnsureArrays() { - if (this.arraysFetched) { + } + + /*internal bool StandardValuesQueried { + get { + this.standardValuesQueried = value; + } + } */ + + + // ensure that we have processed the caStructs into arrays + // of values and strings + // + private void EnsureArrays() + { + if (this.arraysFetched) + { return; } - + this.arraysFetched = true; - try { + try + { // marshal the items. object[] nameItems = nameMarshaller.Items; - object[] cookieItems= valueMarshaller.Items; + object[] cookieItems = valueMarshaller.Items; NativeMethods.IPerPropertyBrowsing ppb = (NativeMethods.IPerPropertyBrowsing)target.TargetObject; int itemCount = 0; - + Debug.Assert(cookieItems != null && nameItems != null, "An item array is null"); - - - if (nameItems.Length > 0){ - + + + if (nameItems.Length > 0) + { + object[] valueItems = new object[cookieItems.Length]; NativeMethods.VARIANT var = new NativeMethods.VARIANT(); int cookie; - + Debug.Assert(cookieItems.Length == nameItems.Length, "Got uneven names and cookies"); - + // for each name item, we ask the object for it's corresponding value. // Type targetType = target.PropertyType; - for (int i = nameItems.Length - 1; i >= 0; i--) { + for (int i = nameItems.Length - 1; i >= 0; i--) + { cookie = (int)cookieItems[i]; - if (nameItems[i] == null || !(nameItems[i] is string)) { + if (nameItems[i] == null || !(nameItems[i] is string)) + { Debug.Fail("Bad IPerPropertyBrowsing item [" + i.ToString(CultureInfo.InvariantCulture) + "], name=" + (nameItems == null ? "(unknown)" : nameItems[i].ToString())); continue; } var.vt = (short)NativeMethods.tagVT.VT_EMPTY; int hr = ppb.GetPredefinedValue(target.DISPID, cookie, var); - if (hr == NativeMethods.S_OK && var.vt != (short)NativeMethods.tagVT.VT_EMPTY) { + if (hr == NativeMethods.S_OK && var.vt != (short)NativeMethods.tagVT.VT_EMPTY) + { valueItems[i] = var.ToObject(); - if (valueItems[i].GetType() != targetType) { - if (targetType.IsEnum) { + if (valueItems[i].GetType() != targetType) + { + if (targetType.IsEnum) + { valueItems[i] = Enum.ToObject(targetType, valueItems[i]); } - else { - try { + else + { + try + { valueItems[i] = Convert.ChangeType(valueItems[i], targetType, CultureInfo.InvariantCulture); } - catch { + catch + { // oh well... } } } } - + var.Clear(); - if (hr == NativeMethods.S_OK) { + if (hr == NativeMethods.S_OK) + { itemCount++; continue; } - else if (itemCount > 0){ + else if (itemCount > 0) + { // shorten the arrays to ignore the failed ones. this isn't terribly // efficient but shouldn't happen very often. It's rare for these to fail. // - Array.Copy(nameItems, i, nameItems, i+1, itemCount); - Array.Copy(valueItems, i, valueItems, i+1, itemCount); + Array.Copy(nameItems, i, nameItems, i + 1, itemCount); + Array.Copy(valueItems, i, valueItems, i + 1, itemCount); } - + } - + // pass this data down to the base Com2Enum object... string[] strings = new string[itemCount]; Array.Copy(nameItems, 0, strings, 0, itemCount); @@ -320,45 +381,51 @@ private void EnsureArrays() { } } - catch (Exception ex) { + catch (Exception ex) + { base.PopulateArrays(new string[0], new object[0]); Debug.Fail("Failed to build IPerPropertyBrowsing editor. " + ex.GetType().Name + ", " + ex.Message); } - } - - protected override void PopulateArrays(string[] names, object[] values) { + } + + protected override void PopulateArrays(string[] names, object[] values) + { // we call base.PopulateArrays directly when we actually want to do this. - } - - public override object FromString(string s) { + } + + public override object FromString(string s) + { EnsureArrays(); return base.FromString(s); - } - - public override string ToString(object v) { - + } + + public override string ToString(object v) + { + // If the value is the object's current value, then // ask GetDisplay string first. This is a perf improvement // because this way we don't populate the arrays when an object is selected, only // when the dropdown is actually opened. // - if (target.IsCurrentValue(v)) { - + if (target.IsCurrentValue(v)) + { + bool success = false; - + string displayString = Com2IPerPropertyBrowsingHandler.GetDisplayString((NativeMethods.IPerPropertyBrowsing)target.TargetObject, target.DISPID, ref success); - - if (success) { + + if (success) + { return displayString; } } - + // couldn't get a display string...do the normal thing. // EnsureArrays(); return base.ToString(v); - } - } - + } + } + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IProvidePropertyBuilderHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IProvidePropertyBuilderHandler.cs index 11c067d1348..8600b67d6c4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IProvidePropertyBuilderHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IProvidePropertyBuilderHandler.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.ComponentModel; using System.Diagnostics; using System; @@ -10,48 +11,60 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop { using Microsoft.Win32; using System.Drawing.Design; - internal class Com2IProvidePropertyBuilderHandler : Com2ExtendedBrowsingHandler { + internal class Com2IProvidePropertyBuilderHandler : Com2ExtendedBrowsingHandler + { - public override Type Interface { - get { + public override Type Interface + { + get + { return typeof(NativeMethods.IProvidePropertyBuilder); } } - private bool GetBuilderGuidString(NativeMethods.IProvidePropertyBuilder target, int dispid, ref string strGuidBldr, int[] bldrType) { + private bool GetBuilderGuidString(NativeMethods.IProvidePropertyBuilder target, int dispid, ref string strGuidBldr, int[] bldrType) + { bool valid = false; string[] pGuidBldr = new string[1]; - if (NativeMethods.Failed(target.MapPropertyToBuilder(dispid, bldrType, pGuidBldr, ref valid))) { + if (NativeMethods.Failed(target.MapPropertyToBuilder(dispid, bldrType, pGuidBldr, ref valid))) + { valid = false; } - - if (valid && (bldrType[0] & _CTLBLDTYPE.CTLBLDTYPE_FINTERNALBUILDER) == 0) { + + if (valid && (bldrType[0] & _CTLBLDTYPE.CTLBLDTYPE_FINTERNALBUILDER) == 0) + { valid = false; Debug.Fail("Property Browser doesn't support standard builders -- NYI"); } - if (!valid) { + if (!valid) + { return false; } - if (pGuidBldr[0] == null) { + if (pGuidBldr[0] == null) + { strGuidBldr = Guid.Empty.ToString(); } - else { + else + { strGuidBldr = pGuidBldr[0]; } return true; } - public override void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc) { - if (propDesc == null) { + public override void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc) + { + if (propDesc == null) + { return; } - for (int i = 0; i < propDesc.Length; i++) { + for (int i = 0; i < propDesc.Length; i++) + { propDesc[i].QueryGetBaseAttributes += new GetAttributesEventHandler(this.OnGetBaseAttributes); - + propDesc[i].QueryGetTypeConverterAndTypeEditor += new GetTypeConverterAndTypeEditorEventHandler(this.OnGetTypeConverterAndTypeEditor); - + } } @@ -60,30 +73,37 @@ public override void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc) { /// Here is where we handle IVsPerPropertyBrowsing.GetLocalizedPropertyInfo and IVsPerPropertyBrowsing. HideProperty /// such as IPerPropertyBrowsing, IProvidePropertyBuilder, etc. /// - private void OnGetBaseAttributes(Com2PropertyDescriptor sender, GetAttributesEvent attrEvent) { + private void OnGetBaseAttributes(Com2PropertyDescriptor sender, GetAttributesEvent attrEvent) + { NativeMethods.IProvidePropertyBuilder target = sender.TargetObject as NativeMethods.IProvidePropertyBuilder; - if (target != null ) { + if (target != null) + { string s = null; bool builderValid = GetBuilderGuidString(target, sender.DISPID, ref s, new int[1]); // we hide IDispatch props by default, we we need to force showing them here - if (sender.CanShow && builderValid) { - if (typeof(UnsafeNativeMethods.IDispatch).IsAssignableFrom(sender.PropertyType)) { + if (sender.CanShow && builderValid) + { + if (typeof(UnsafeNativeMethods.IDispatch).IsAssignableFrom(sender.PropertyType)) + { attrEvent.Add(BrowsableAttribute.Yes); } } } } - - private void OnGetTypeConverterAndTypeEditor(Com2PropertyDescriptor sender, GetTypeConverterAndTypeEditorEvent gveevent) { + + private void OnGetTypeConverterAndTypeEditor(Com2PropertyDescriptor sender, GetTypeConverterAndTypeEditorEvent gveevent) + { object target = sender.TargetObject; - if (target is NativeMethods.IProvidePropertyBuilder) { + if (target is NativeMethods.IProvidePropertyBuilder) + { NativeMethods.IProvidePropertyBuilder propBuilder = (NativeMethods.IProvidePropertyBuilder)target; int[] pctlBldType = new int[1]; string guidString = null; - if (GetBuilderGuidString(propBuilder, sender.DISPID, ref guidString, pctlBldType)) { + if (GetBuilderGuidString(propBuilder, sender.DISPID, ref guidString, pctlBldType)) + { gveevent.TypeEditor = new Com2PropertyBuilderUITypeEditor(sender, guidString, pctlBldType[0], (UITypeEditor)gveevent.TypeEditor); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IVsPerPropertyBrowsingHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IVsPerPropertyBrowsingHandler.cs index 04313583bdd..a42c1a98c7a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IVsPerPropertyBrowsingHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IVsPerPropertyBrowsingHandler.cs @@ -2,8 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { - using System; +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ + using System; using System.ComponentModel; using System.Diagnostics; using System.Globalization; @@ -20,206 +21,243 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop { /// See Com2Properties for the array of handler classes to interface classes /// where handlers should be registered. /// - internal class Com2IVsPerPropertyBrowsingHandler: Com2ExtendedBrowsingHandler { - - /// - /// The interface that this handler managers - /// such as IPerPropertyBrowsing, IProvidePropertyBuilder, etc. - /// - public override Type Interface { - get { - return typeof(NativeMethods.IVsPerPropertyBrowsing); + internal class Com2IVsPerPropertyBrowsingHandler : Com2ExtendedBrowsingHandler + { + + /// + /// The interface that this handler managers + /// such as IPerPropertyBrowsing, IProvidePropertyBuilder, etc. + /// + public override Type Interface + { + get + { + return typeof(NativeMethods.IVsPerPropertyBrowsing); } - } - - public static bool AllowChildProperties(Com2PropertyDescriptor propDesc) { - if (propDesc.TargetObject is NativeMethods.IVsPerPropertyBrowsing) { - bool pfHide = false; - int hr = ((NativeMethods.IVsPerPropertyBrowsing)propDesc.TargetObject).DisplayChildProperties(propDesc.DISPID, ref pfHide); - return (hr == NativeMethods.S_OK && pfHide); + } + + public static bool AllowChildProperties(Com2PropertyDescriptor propDesc) + { + if (propDesc.TargetObject is NativeMethods.IVsPerPropertyBrowsing) + { + bool pfHide = false; + int hr = ((NativeMethods.IVsPerPropertyBrowsing)propDesc.TargetObject).DisplayChildProperties(propDesc.DISPID, ref pfHide); + return (hr == NativeMethods.S_OK && pfHide); } return false; - } - - /// - /// Called to setup the property handlers on a given properties - /// In this method, the handler will add listeners to the events that - /// the Com2PropertyDescriptor surfaces that it cares about. - /// - public override void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc){ - if (propDesc == null){ - return; - } - for (int i = 0; i < propDesc.Length; i++){ - propDesc[i].QueryGetDynamicAttributes += new GetAttributesEventHandler(this.OnGetDynamicAttributes); - propDesc[i].QueryGetBaseAttributes += new GetAttributesEventHandler(this.OnGetBaseAttributes); - propDesc[i].QueryGetDisplayName += new GetNameItemEventHandler(this.OnGetDisplayName); - propDesc[i].QueryGetIsReadOnly += new GetBoolValueEventHandler(this.OnGetIsReadOnly); - - propDesc[i].QueryShouldSerializeValue += new GetBoolValueEventHandler(this.OnShouldSerializeValue); - propDesc[i].QueryCanResetValue += new GetBoolValueEventHandler(this.OnCanResetPropertyValue); - propDesc[i].QueryResetValue += new Com2EventHandler(this.OnResetPropertyValue); - - propDesc[i].QueryGetTypeConverterAndTypeEditor += new GetTypeConverterAndTypeEditorEventHandler(this.OnGetTypeConverterAndTypeEditor); - - } - } - - private void OnGetBaseAttributes(Com2PropertyDescriptor sender, GetAttributesEvent attrEvent){ - NativeMethods.IVsPerPropertyBrowsing vsObj = sender.TargetObject as NativeMethods.IVsPerPropertyBrowsing; - - if (vsObj == null) { - return; - } - - // should we localize this? - string[] pHelpString = new string[1]; - int hr = vsObj.GetLocalizedPropertyInfo(sender.DISPID, CultureInfo.CurrentCulture.LCID, null, pHelpString); - if (hr == NativeMethods.S_OK && pHelpString[0] != null){ + } + + /// + /// Called to setup the property handlers on a given properties + /// In this method, the handler will add listeners to the events that + /// the Com2PropertyDescriptor surfaces that it cares about. + /// + public override void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc) + { + if (propDesc == null) + { + return; + } + for (int i = 0; i < propDesc.Length; i++) + { + propDesc[i].QueryGetDynamicAttributes += new GetAttributesEventHandler(this.OnGetDynamicAttributes); + propDesc[i].QueryGetBaseAttributes += new GetAttributesEventHandler(this.OnGetBaseAttributes); + propDesc[i].QueryGetDisplayName += new GetNameItemEventHandler(this.OnGetDisplayName); + propDesc[i].QueryGetIsReadOnly += new GetBoolValueEventHandler(this.OnGetIsReadOnly); + + propDesc[i].QueryShouldSerializeValue += new GetBoolValueEventHandler(this.OnShouldSerializeValue); + propDesc[i].QueryCanResetValue += new GetBoolValueEventHandler(this.OnCanResetPropertyValue); + propDesc[i].QueryResetValue += new Com2EventHandler(this.OnResetPropertyValue); + + propDesc[i].QueryGetTypeConverterAndTypeEditor += new GetTypeConverterAndTypeEditorEventHandler(this.OnGetTypeConverterAndTypeEditor); + + } + } + + private void OnGetBaseAttributes(Com2PropertyDescriptor sender, GetAttributesEvent attrEvent) + { + NativeMethods.IVsPerPropertyBrowsing vsObj = sender.TargetObject as NativeMethods.IVsPerPropertyBrowsing; + + if (vsObj == null) + { + return; + } + + // should we localize this? + string[] pHelpString = new string[1]; + int hr = vsObj.GetLocalizedPropertyInfo(sender.DISPID, CultureInfo.CurrentCulture.LCID, null, pHelpString); + if (hr == NativeMethods.S_OK && pHelpString[0] != null) + { attrEvent.Add(new DescriptionAttribute(pHelpString[0])); - } - } - - - /// - /// Here is where we handle IVsPerPropertyBrowsing.GetLocalizedPropertyInfo and IVsPerPropertyBrowsing. HideProperty - /// such as IPerPropertyBrowsing, IProvidePropertyBuilder, etc. - /// - private void OnGetDynamicAttributes(Com2PropertyDescriptor sender, GetAttributesEvent attrEvent){ - - if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing){ - NativeMethods.IVsPerPropertyBrowsing vsObj = (NativeMethods.IVsPerPropertyBrowsing)sender.TargetObject; - - int hr = NativeMethods.S_OK; - - // we want to avoid allowing clients to force a bad property to be browsable, - // so we don't allow things that are marked as non browsable to become browsable, - // only the other way around. - // - if (sender.CanShow) { + } + } + + + /// + /// Here is where we handle IVsPerPropertyBrowsing.GetLocalizedPropertyInfo and IVsPerPropertyBrowsing. HideProperty + /// such as IPerPropertyBrowsing, IProvidePropertyBuilder, etc. + /// + private void OnGetDynamicAttributes(Com2PropertyDescriptor sender, GetAttributesEvent attrEvent) + { + + if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing) + { + NativeMethods.IVsPerPropertyBrowsing vsObj = (NativeMethods.IVsPerPropertyBrowsing)sender.TargetObject; + + int hr = NativeMethods.S_OK; + + // we want to avoid allowing clients to force a bad property to be browsable, + // so we don't allow things that are marked as non browsable to become browsable, + // only the other way around. + // + if (sender.CanShow) + { // should we hide this? bool pfHide = sender.Attributes[typeof(BrowsableAttribute)].Equals(BrowsableAttribute.No); - + hr = vsObj.HideProperty(sender.DISPID, ref pfHide); - if (hr == NativeMethods.S_OK){ - attrEvent.Add(pfHide ? BrowsableAttribute.No : BrowsableAttribute.Yes); + if (hr == NativeMethods.S_OK) + { + attrEvent.Add(pfHide ? BrowsableAttribute.No : BrowsableAttribute.Yes); } - } - - // should we show this - if (typeof(UnsafeNativeMethods.IDispatch).IsAssignableFrom(sender.PropertyType) && sender.CanShow){ - bool pfDisplay = false; - hr = vsObj.DisplayChildProperties(sender.DISPID, ref pfDisplay); - if (hr == NativeMethods.S_OK && pfDisplay){ - attrEvent.Add(BrowsableAttribute.Yes); - } - } - } - Debug.Assert(sender.TargetObject == null || sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing, "Object is not " + Interface.Name + "!"); - } - - private void OnCanResetPropertyValue(Com2PropertyDescriptor sender, GetBoolValueEvent boolEvent) { - if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing) { - NativeMethods.IVsPerPropertyBrowsing target = (NativeMethods.IVsPerPropertyBrowsing)sender.TargetObject; - bool canReset = boolEvent.Value; - int hr = target.CanResetPropertyValue(sender.DISPID, ref canReset); - - if (NativeMethods.Succeeded(hr)){ - boolEvent.Value = canReset; + } + + // should we show this + if (typeof(UnsafeNativeMethods.IDispatch).IsAssignableFrom(sender.PropertyType) && sender.CanShow) + { + bool pfDisplay = false; + hr = vsObj.DisplayChildProperties(sender.DISPID, ref pfDisplay); + if (hr == NativeMethods.S_OK && pfDisplay) + { + attrEvent.Add(BrowsableAttribute.Yes); } - } - Debug.Assert(sender.TargetObject == null || sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing, "Object is not " + Interface.Name + "!"); - } - - /// - /// Here is where we handle IVsPerPropertyBrowsing.GetLocalizedPropertyInfo (part 2) - /// - private void OnGetDisplayName(Com2PropertyDescriptor sender, GetNameItemEvent nameItem){ - if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing){ - NativeMethods.IVsPerPropertyBrowsing vsObj = (NativeMethods.IVsPerPropertyBrowsing)sender.TargetObject; - - // get the localized name, if applicable - string[] pNameString = new string[1]; - int hr = vsObj.GetLocalizedPropertyInfo(sender.DISPID, CultureInfo.CurrentCulture.LCID, pNameString, null); - if (hr == NativeMethods.S_OK && pNameString[0] != null){ - nameItem.Name = pNameString[0]; - } - } - Debug.Assert(sender.TargetObject == null || sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing, "Object is not " + Interface.Name + "!"); - } - - /// - /// Here is where we handle IVsPerPropertyBrowsing.IsPropertyReadOnly - /// - private void OnGetIsReadOnly(Com2PropertyDescriptor sender, GetBoolValueEvent gbvevent){ - if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing){ - NativeMethods.IVsPerPropertyBrowsing vsObj = (NativeMethods.IVsPerPropertyBrowsing)sender.TargetObject; - - // should we make this read only? - bool pfResult = false; - int hr = vsObj.IsPropertyReadOnly(sender.DISPID, ref pfResult); - - if (hr == NativeMethods.S_OK){ - gbvevent.Value = pfResult; - } - } - } - - /// - /// Here is where we handle IVsPerPropertyBrowsing.DisplayChildProperties - /// - private void OnGetTypeConverterAndTypeEditor(Com2PropertyDescriptor sender, GetTypeConverterAndTypeEditorEvent gveevent) { - if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing){ - - // we only do this for IDispatch types - if (sender.CanShow && typeof(UnsafeNativeMethods.IDispatch).IsAssignableFrom(sender.PropertyType)){ - NativeMethods.IVsPerPropertyBrowsing vsObj = (NativeMethods.IVsPerPropertyBrowsing)sender.TargetObject; - - // should we make this read only? - bool pfResult = false; - int hr = vsObj.DisplayChildProperties(sender.DISPID, ref pfResult); - - if (gveevent.TypeConverter is Com2IDispatchConverter){ + } + } + Debug.Assert(sender.TargetObject == null || sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing, "Object is not " + Interface.Name + "!"); + } + + private void OnCanResetPropertyValue(Com2PropertyDescriptor sender, GetBoolValueEvent boolEvent) + { + if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing) + { + NativeMethods.IVsPerPropertyBrowsing target = (NativeMethods.IVsPerPropertyBrowsing)sender.TargetObject; + bool canReset = boolEvent.Value; + int hr = target.CanResetPropertyValue(sender.DISPID, ref canReset); + + if (NativeMethods.Succeeded(hr)) + { + boolEvent.Value = canReset; + } + } + Debug.Assert(sender.TargetObject == null || sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing, "Object is not " + Interface.Name + "!"); + } + + /// + /// Here is where we handle IVsPerPropertyBrowsing.GetLocalizedPropertyInfo (part 2) + /// + private void OnGetDisplayName(Com2PropertyDescriptor sender, GetNameItemEvent nameItem) + { + if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing) + { + NativeMethods.IVsPerPropertyBrowsing vsObj = (NativeMethods.IVsPerPropertyBrowsing)sender.TargetObject; + + // get the localized name, if applicable + string[] pNameString = new string[1]; + int hr = vsObj.GetLocalizedPropertyInfo(sender.DISPID, CultureInfo.CurrentCulture.LCID, pNameString, null); + if (hr == NativeMethods.S_OK && pNameString[0] != null) + { + nameItem.Name = pNameString[0]; + } + } + Debug.Assert(sender.TargetObject == null || sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing, "Object is not " + Interface.Name + "!"); + } + + /// + /// Here is where we handle IVsPerPropertyBrowsing.IsPropertyReadOnly + /// + private void OnGetIsReadOnly(Com2PropertyDescriptor sender, GetBoolValueEvent gbvevent) + { + if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing) + { + NativeMethods.IVsPerPropertyBrowsing vsObj = (NativeMethods.IVsPerPropertyBrowsing)sender.TargetObject; + + // should we make this read only? + bool pfResult = false; + int hr = vsObj.IsPropertyReadOnly(sender.DISPID, ref pfResult); + + if (hr == NativeMethods.S_OK) + { + gbvevent.Value = pfResult; + } + } + } + + /// + /// Here is where we handle IVsPerPropertyBrowsing.DisplayChildProperties + /// + private void OnGetTypeConverterAndTypeEditor(Com2PropertyDescriptor sender, GetTypeConverterAndTypeEditorEvent gveevent) + { + if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing) + { + + // we only do this for IDispatch types + if (sender.CanShow && typeof(UnsafeNativeMethods.IDispatch).IsAssignableFrom(sender.PropertyType)) + { + NativeMethods.IVsPerPropertyBrowsing vsObj = (NativeMethods.IVsPerPropertyBrowsing)sender.TargetObject; + + // should we make this read only? + bool pfResult = false; + int hr = vsObj.DisplayChildProperties(sender.DISPID, ref pfResult); + + if (gveevent.TypeConverter is Com2IDispatchConverter) + { gveevent.TypeConverter = new Com2IDispatchConverter(sender, (hr == NativeMethods.S_OK && pfResult)); - } - else{ + } + else + { gveevent.TypeConverter = new Com2IDispatchConverter(sender, (hr == NativeMethods.S_OK && pfResult), gveevent.TypeConverter); - } - } - } - Debug.Assert(sender.TargetObject == null || sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing, "Object is not " + Interface.Name + "!"); - } - - private void OnResetPropertyValue(Com2PropertyDescriptor sender, EventArgs e) { - if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing) { - - - NativeMethods.IVsPerPropertyBrowsing target = (NativeMethods.IVsPerPropertyBrowsing)sender.TargetObject; - int dispid = sender.DISPID; - bool canReset = false; - int hr = target.CanResetPropertyValue(dispid, ref canReset); - - if (NativeMethods.Succeeded(hr)){ - target.ResetPropertyValue(dispid); } - } - Debug.Assert(sender.TargetObject == null || sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing, "Object is not " + Interface.Name + "!"); - } - - private void OnShouldSerializeValue(Com2PropertyDescriptor sender, GetBoolValueEvent gbvevent){ - if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing){ - NativeMethods.IVsPerPropertyBrowsing vsObj = (NativeMethods.IVsPerPropertyBrowsing)sender.TargetObject; - - // by default we say it's default - bool pfResult = true; - int hr = vsObj.HasDefaultValue(sender.DISPID,ref pfResult); - - if (hr == NativeMethods.S_OK && !pfResult){ - // specify a default value editor - gbvevent.Value = true; - } - } - Debug.Assert(sender.TargetObject == null || sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing, "Object is not " + Interface.Name + "!"); - } + } + } + Debug.Assert(sender.TargetObject == null || sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing, "Object is not " + Interface.Name + "!"); + } + + private void OnResetPropertyValue(Com2PropertyDescriptor sender, EventArgs e) + { + if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing) + { + + + NativeMethods.IVsPerPropertyBrowsing target = (NativeMethods.IVsPerPropertyBrowsing)sender.TargetObject; + int dispid = sender.DISPID; + bool canReset = false; + int hr = target.CanResetPropertyValue(dispid, ref canReset); + + if (NativeMethods.Succeeded(hr)) + { + target.ResetPropertyValue(dispid); + } + } + Debug.Assert(sender.TargetObject == null || sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing, "Object is not " + Interface.Name + "!"); + } + + private void OnShouldSerializeValue(Com2PropertyDescriptor sender, GetBoolValueEvent gbvevent) + { + if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing) + { + NativeMethods.IVsPerPropertyBrowsing vsObj = (NativeMethods.IVsPerPropertyBrowsing)sender.TargetObject; + + // by default we say it's default + bool pfResult = true; + int hr = vsObj.HasDefaultValue(sender.DISPID, ref pfResult); + + if (hr == NativeMethods.S_OK && !pfResult) + { + // specify a default value editor + gbvevent.Value = true; + } + } + Debug.Assert(sender.TargetObject == null || sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing, "Object is not " + Interface.Name + "!"); + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PictureConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PictureConverter.cs index 68fc976905d..33205b17296 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PictureConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PictureConverter.cs @@ -2,12 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.Runtime.Serialization.Formatters; using System.ComponentModel; using System.Diagnostics; - using System; - using System.Drawing; + using System; + using System.Drawing; using System.Collections; using Microsoft.Win32; using System.Runtime.Versioning; @@ -15,7 +16,8 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop { /// /// This class maps an IPicture to a System.Drawing.Image. /// - internal class Com2PictureConverter : Com2DataTypeToManagedDataTypeConverter { + internal class Com2PictureConverter : Com2DataTypeToManagedDataTypeConverter + { object lastManaged; IntPtr lastNativeHandle; @@ -24,8 +26,10 @@ internal class Com2PictureConverter : Com2DataTypeToManagedDataTypeConverter { Type pictureType = typeof(Bitmap); - public Com2PictureConverter(Com2PropertyDescriptor pd) { - if (pd.DISPID == NativeMethods.ActiveX.DISPID_MOUSEICON || pd.Name.IndexOf("Icon") != -1) { + public Com2PictureConverter(Com2PropertyDescriptor pd) + { + if (pd.DISPID == NativeMethods.ActiveX.DISPID_MOUSEICON || pd.Name.IndexOf("Icon") != -1) + { pictureType = typeof(Icon); } } @@ -33,8 +37,10 @@ public Com2PictureConverter(Com2PropertyDescriptor pd) { /// /// Returns the managed type that this editor maps the property type to. /// - public override Type ManagedType { - get { + public override Type ManagedType + { + get + { return pictureType; } } @@ -42,9 +48,11 @@ public override Type ManagedType { /// /// Converts the native value into a managed value /// - public override object ConvertNativeToManaged(object nativeValue, Com2PropertyDescriptor pd) { + public override object ConvertNativeToManaged(object nativeValue, Com2PropertyDescriptor pd) + { - if (nativeValue == null) { + if (nativeValue == null) + { return null; } @@ -53,29 +61,33 @@ public override object ConvertNativeToManaged(object nativeValue, Com2PropertyDe UnsafeNativeMethods.IPicture nativePicture = (UnsafeNativeMethods.IPicture)nativeValue; IntPtr handle = nativePicture.GetHandle(); - if (lastManaged != null && handle == lastNativeHandle) { + if (lastManaged != null && handle == lastNativeHandle) + { return lastManaged; } lastNativeHandle = handle; //lastPalette = nativePicture.GetHPal(); - if (handle != IntPtr.Zero) { - switch (nativePicture.GetPictureType()) { - case NativeMethods.Ole.PICTYPE_ICON: + if (handle != IntPtr.Zero) + { + switch (nativePicture.GetPictureType()) + { + case NativeMethods.Ole.PICTYPE_ICON: pictureType = typeof(Icon); lastManaged = Icon.FromHandle(handle); break; - case NativeMethods.Ole.PICTYPE_BITMAP: + case NativeMethods.Ole.PICTYPE_BITMAP: pictureType = typeof(Bitmap); lastManaged = Image.FromHbitmap(handle); break; default: Debug.Fail("Unknown picture type"); - break; + break; } pictureRef = new WeakReference(nativePicture); } - else { + else + { lastManaged = null; pictureRef = null; } @@ -85,30 +97,36 @@ public override object ConvertNativeToManaged(object nativeValue, Com2PropertyDe /// /// Converts the managed value into a native value /// - public override object ConvertManagedToNative(object managedValue, Com2PropertyDescriptor pd, ref bool cancelSet) { + public override object ConvertManagedToNative(object managedValue, Com2PropertyDescriptor pd, ref bool cancelSet) + { // don't cancel the set cancelSet = false; - if (lastManaged != null && lastManaged.Equals(managedValue) && pictureRef != null && pictureRef.IsAlive) { + if (lastManaged != null && lastManaged.Equals(managedValue) && pictureRef != null && pictureRef.IsAlive) + { return pictureRef.Target; } // we have to build an IPicture lastManaged = managedValue; - if (managedValue != null) { + if (managedValue != null) + { Guid g = typeof(UnsafeNativeMethods.IPicture).GUID; NativeMethods.PICTDESC pictdesc = null; bool own = false; - if (lastManaged is Icon) { + if (lastManaged is Icon) + { pictdesc = NativeMethods.PICTDESC.CreateIconPICTDESC(((Icon)lastManaged).Handle); } - else if (lastManaged is Bitmap) { + else if (lastManaged is Bitmap) + { pictdesc = NativeMethods.PICTDESC.CreateBitmapPICTDESC(((Bitmap)lastManaged).GetHbitmap(), lastPalette); own = true; } - else { + else + { Debug.Fail("Unknown Image type: " + managedValue.GetType().Name); } @@ -117,7 +135,8 @@ public override object ConvertManagedToNative(object managedValue, Com2PropertyD pictureRef = new WeakReference(pict); return pict; } - else { + else + { lastManaged = null; lastNativeHandle = lastPalette = IntPtr.Zero; pictureRef = null; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Properties.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Properties.cs index 5b3b343b2df..129a037f779 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Properties.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Properties.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; @@ -16,12 +17,13 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop { /// This class is responsible for managing a set or properties for a native object. It determines /// when the properties need to be refreshed, and owns the extended handlers for those properties. /// - internal class Com2Properties { - + internal class Com2Properties + { + private static TraceSwitch DbgCom2PropertiesSwitch = new TraceSwitch("DbgCom2Properties", "Com2Properties: debug Com2 properties manager"); - - - + + + /// /// This is the interval that we'll hold props for. If someone doesn't touch an object /// for this amount of time, we'll dump the properties from our cache. @@ -30,42 +32,42 @@ internal class Com2Properties { /// private static long AGE_THRESHHOLD = (long)(10000000L * 60L * 5L); - + /// /// This is the object that gave us the properties. We hold a WeakRef so we don't addref the object. /// internal WeakReference weakObjRef; - + /// /// This is our list of properties. /// private Com2PropertyDescriptor[] props; - + /// /// The index of the default property /// - private int defaultIndex = -1; - - + private int defaultIndex = -1; + + /// /// The timestamp of the last operation on this property manager, usually /// when the property list was fetched. /// - private long touchedTime; + private long touchedTime; /// /// For non-IProvideMultipleClassInfo ITypeInfos, this is the version number on the last /// ITypeInfo we looked at. If this changes, we know we need to dump the cache. /// - private long[] typeInfoVersions; - + private long[] typeInfoVersions; + #if DEBUG - private string dbgObjName; - private string dbgObjClass; + private string dbgObjName; + private string dbgObjClass; #endif - private int alwaysValid = 0; + private int alwaysValid = 0; /// /// These are the interfaces we recognize for extended browsing. @@ -87,7 +89,7 @@ internal class Com2Properties { typeof(Com2IPerPropertyBrowsingHandler), typeof(Com2IVsPerPropertyBrowsingHandler), typeof(Com2IManagedPerPropertyBrowsingHandler)}; - + public event EventHandler Disposed; @@ -96,20 +98,24 @@ internal class Com2Properties { /// /// Default ctor. /// - public Com2Properties(object obj, Com2PropertyDescriptor[] props, int defaultIndex) { + public Com2Properties(object obj, Com2PropertyDescriptor[] props, int defaultIndex) + { #if DEBUG ComNativeDescriptor cnd = new ComNativeDescriptor(); this.dbgObjName = cnd.GetName(obj); - if (this.dbgObjName == null) { + if (this.dbgObjName == null) + { this.dbgObjName = "(null)"; } this.dbgObjClass = cnd.GetClassName(obj); - if (this.dbgObjClass == null) { + if (this.dbgObjClass == null) + { this.dbgObjClass = "(null)"; } - if (DbgCom2PropertiesSwitch.TraceVerbose) Debug.WriteLine("Creating Com2Properties for object " + dbgObjName + ", class=" + dbgObjClass); + if (DbgCom2PropertiesSwitch.TraceVerbose) + Debug.WriteLine("Creating Com2Properties for object " + dbgObjName + ", class=" + dbgObjClass); #endif - + // set up our variables SetProps(props); weakObjRef = new WeakReference(obj); @@ -122,19 +128,26 @@ public Com2Properties(object obj, Com2PropertyDescriptor[] props, int defaultInd } - internal bool AlwaysValid { - get { + internal bool AlwaysValid + { + get + { return this.alwaysValid > 0; } - set { - if (value) { - if (alwaysValid == 0 && !CheckValid()) { + set + { + if (value) + { + if (alwaysValid == 0 && !CheckValid()) + { return; } this.alwaysValid++; } - else { - if (alwaysValid > 0) { + else + { + if (alwaysValid > 0) + { this.alwaysValid--; } } @@ -144,16 +157,22 @@ internal bool AlwaysValid { /// /// Retrieve the default property. /// - public Com2PropertyDescriptor DefaultProperty{ - get{ - if (!CheckValid(true)) { + public Com2PropertyDescriptor DefaultProperty + { + get + { + if (!CheckValid(true)) + { return null; } - if (defaultIndex == -1) { - if (props.Length > 0) { + if (defaultIndex == -1) + { + if (props.Length > 0) + { return props[0]; } - else { + else + { return null; } } @@ -166,11 +185,15 @@ public Com2PropertyDescriptor DefaultProperty{ /// The object that created the list of properties. This will /// return null if the timeout has passed or the ref has died. /// - public object TargetObject{ - get{ - if (!CheckValid(false) || touchedTime == 0) { + public object TargetObject + { + get + { + if (!CheckValid(false) || touchedTime == 0) + { #if DEBUG - if (DbgCom2PropertiesSwitch.TraceVerbose) Debug.WriteLine("CheckValid called on dead object!"); + if (DbgCom2PropertiesSwitch.TraceVerbose) + Debug.WriteLine("CheckValid called on dead object!"); #endif return null; } @@ -181,9 +204,12 @@ public object TargetObject{ /// /// How long since these props have been queried. /// - public long TicksSinceTouched{ - get{ - if (touchedTime == 0) { + public long TicksSinceTouched + { + get + { + if (touchedTime == 0) + { return 0; } return DateTime.Now.Ticks - touchedTime; @@ -193,21 +219,26 @@ public long TicksSinceTouched{ /// /// Returns the list of properties /// - public Com2PropertyDescriptor[] Properties{ - get{ + public Com2PropertyDescriptor[] Properties + { + get + { CheckValid(true); - if (touchedTime == 0 || props == null) { + if (touchedTime == 0 || props == null) + { return null; } touchedTime = DateTime.Now.Ticks; // refresh everyone! - for (int i = 0; i < props.Length; i++) { + for (int i = 0; i < props.Length; i++) + { props[i].SetNeedsRefresh(Com2PropertyDescriptorRefresh.All, true); } #if DEBUG - if (DbgCom2PropertiesSwitch.TraceVerbose) Debug.WriteLine("Returning prop array for object " + dbgObjName + ", class=" + dbgObjClass); + if (DbgCom2PropertiesSwitch.TraceVerbose) + Debug.WriteLine("Returning prop array for object " + dbgObjName + ", class=" + dbgObjClass); #endif return props; } @@ -216,11 +247,14 @@ public Com2PropertyDescriptor[] Properties{ /// /// Should this guy be refreshed because of old age? /// - public bool TooOld{ - get{ + public bool TooOld + { + get + { // check if the property is valid but don't dispose it if it's not CheckValid(false, false); - if (touchedTime == 0) { + if (touchedTime == 0) + { return false; } return TicksSinceTouched > AGE_THRESHHOLD; @@ -232,69 +266,82 @@ public bool TooOld{ /// listed in extendedInterfaces and creates a handler from extendedInterfaceHandlerTypes /// to handle it. /// - public void AddExtendedBrowsingHandlers(Hashtable handlers) { + public void AddExtendedBrowsingHandlers(Hashtable handlers) + { object target = this.TargetObject; - if (target == null) { + if (target == null) + { return; } // process all our registered types Type t; - for (int i = 0; i < extendedInterfaces.Length; i++) { + for (int i = 0; i < extendedInterfaces.Length; i++) + { t = extendedInterfaces[i]; - + // is this object an implementor of the interface? // - if (t.IsInstanceOfType(target)) { - + if (t.IsInstanceOfType(target)) + { + // since handlers must be stateless, check to see if we've already // created one of this type // Com2ExtendedBrowsingHandler handler = (Com2ExtendedBrowsingHandler)handlers[t]; - if (handler == null) { + if (handler == null) + { handler = (Com2ExtendedBrowsingHandler)Activator.CreateInstance(extendedInterfaceHandlerTypes[i]); handlers[t] = handler; } - + // make sure we got the right one // - if (t.IsAssignableFrom(handler.Interface)) { + if (t.IsAssignableFrom(handler.Interface)) + { #if DEBUG - if (DbgCom2PropertiesSwitch.TraceVerbose) Debug.WriteLine("Adding browsing handler type " + handler.Interface.Name + " to object " + dbgObjName + ", class=" + dbgObjClass); + if (DbgCom2PropertiesSwitch.TraceVerbose) + Debug.WriteLine("Adding browsing handler type " + handler.Interface.Name + " to object " + dbgObjName + ", class=" + dbgObjClass); #endif // allow the handler to attach itself to the appropriate properties // handler.SetupPropertyHandlers(props); } - else { + else + { throw new ArgumentException(string.Format(SR.COM2BadHandlerType, t.Name, handler.Interface.Name)); } } } } - - public void Dispose() { + + public void Dispose() + { #if DEBUG - if (DbgCom2PropertiesSwitch.TraceVerbose) Debug.WriteLine("Disposing property manager for " + dbgObjName + ", class=" + dbgObjClass); + if (DbgCom2PropertiesSwitch.TraceVerbose) + Debug.WriteLine("Disposing property manager for " + dbgObjName + ", class=" + dbgObjClass); #endif - if (props != null) { + if (props != null) + { - if (Disposed != null) { + if (Disposed != null) + { Disposed(this, EventArgs.Empty); } - + weakObjRef = null; props = null; touchedTime = 0; - } + } } - public bool CheckValid() { + public bool CheckValid() + { return CheckValid(false); } @@ -304,17 +351,19 @@ public bool CheckValid() { /// 1) WeakRef is still alive /// 2) Our timeout hasn't passed /// - public bool CheckValid(bool checkVersions) { + public bool CheckValid(bool checkVersions) + { return CheckValid(checkVersions, true); } - + /// /// Gets a list of version longs for each type info in the COM object /// representing hte current version stamp, function and variable count. /// If any of these things change, we'll re-fetch the properties. /// - private long[] GetTypeInfoVersions(object comObject) { + private long[] GetTypeInfoVersions(object comObject) + { // get type infos // @@ -323,9 +372,10 @@ private long[] GetTypeInfoVersions(object comObject) { // build up the info. // long[] versions = new long[pTypeInfos.Length]; - for (int i = 0; i < pTypeInfos.Length; i++) { - versions [i] = GetTypeInfoVersion(pTypeInfos[i]); - } + for (int i = 0; i < pTypeInfos.Length; i++) + { + versions[i] = GetTypeInfoVersion(pTypeInfos[i]); + } return versions; } @@ -363,45 +413,56 @@ private long[] GetTypeInfoVersions(object comObject) { // the offset of the cFunc member in the TYPEATTR structure. // - private static int CountMemberOffset { - - get { - if (countOffset == -1) { - countOffset = Marshal.SizeOf() + IntPtr.Size + 24; - } - return countOffset; + private static int CountMemberOffset + { + + get + { + if (countOffset == -1) + { + countOffset = Marshal.SizeOf() + IntPtr.Size + 24; } + return countOffset; + } } // the offset of the cMajorVerNum member in the TYPEATTR structure. // - private static int VersionOffset { - get { - if (versionOffset == -1) { - versionOffset = CountMemberOffset + 12; - } - return versionOffset; + private static int VersionOffset + { + get + { + if (versionOffset == -1) + { + versionOffset = CountMemberOffset + 12; } - + return versionOffset; + } + } - private unsafe long GetTypeInfoVersion(UnsafeNativeMethods.ITypeInfo pTypeInfo) { + private unsafe long GetTypeInfoVersion(UnsafeNativeMethods.ITypeInfo pTypeInfo) + { IntPtr pTypeAttr = IntPtr.Zero; int hr = pTypeInfo.GetTypeAttr(ref pTypeAttr); - if (!NativeMethods.Succeeded(hr)) { + if (!NativeMethods.Succeeded(hr)) + { return 0; } System.Runtime.InteropServices.ComTypes.TYPEATTR pTAStruct; - try { - try { + try + { + try + { // just access directly...no marshalling needed! // pTAStruct = *(System.Runtime.InteropServices.ComTypes.TYPEATTR*)pTypeAttr; } - catch { + catch + { return 0; } @@ -434,14 +495,17 @@ private unsafe long GetTypeInfoVersion(UnsafeNativeMethods.ITypeInfo pTypeInfo) // return result; } - finally { - pTypeInfo.ReleaseTypeAttr(pTypeAttr); + finally + { + pTypeInfo.ReleaseTypeAttr(pTypeAttr); } } - internal bool CheckValid(bool checkVersions, bool callDispose) { + internal bool CheckValid(bool checkVersions, bool callDispose) + { - if (this.AlwaysValid) { + if (this.AlwaysValid) + { return true; } @@ -449,38 +513,47 @@ internal bool CheckValid(bool checkVersions, bool callDispose) { // check the version information for each ITypeInfo the object exposes. // - if (valid && checkVersions) { + if (valid && checkVersions) + { - // - long[] newTypeInfoVersions = GetTypeInfoVersions(weakObjRef.Target); + // + long[] newTypeInfoVersions = GetTypeInfoVersions(weakObjRef.Target); - if (newTypeInfoVersions.Length != typeInfoVersions.Length) { - valid = false; - } else { - // compare each version number to the old one. - // - for (int i = 0; i < newTypeInfoVersions.Length; i++) { + if (newTypeInfoVersions.Length != typeInfoVersions.Length) + { + valid = false; + } + else + { + // compare each version number to the old one. + // + for (int i = 0; i < newTypeInfoVersions.Length; i++) + { - if (newTypeInfoVersions[i] != typeInfoVersions[i]) { + if (newTypeInfoVersions[i] != typeInfoVersions[i]) + { valid = false; break; } - } - } + } + } - if (!valid) { + if (!valid) + { - // update to the new version list we have. - // - typeInfoVersions = newTypeInfoVersions; - } + // update to the new version list we have. + // + typeInfoVersions = newTypeInfoVersions; + } } - - if (!valid && callDispose) { + + if (!valid && callDispose) + { // weak ref has died, so remove this from the hash table // #if DEBUG - if (DbgCom2PropertiesSwitch.TraceVerbose) Debug.WriteLine("Disposing reference to object " + dbgObjName + ", class=" + dbgObjClass + " (weakRef " + (weakObjRef == null ? "null" : "dead") + ")"); + if (DbgCom2PropertiesSwitch.TraceVerbose) + Debug.WriteLine("Disposing reference to object " + dbgObjName + ", class=" + dbgObjClass + " (weakRef " + (weakObjRef == null ? "null" : "dead") + ")"); #endif Dispose(); @@ -493,13 +566,16 @@ internal bool CheckValid(bool checkVersions, bool callDispose) { /// Set the props for this object, and notify each property /// that we are now it's manager /// - internal void SetProps(Com2PropertyDescriptor[] props) { + internal void SetProps(Com2PropertyDescriptor[] props) + { this.props = props; - if (props != null) { - for (int i = 0; i < props.Length; i++) { + if (props != null) + { + for (int i = 0; i < props.Length; i++) + { props[i].PropertyManager = this; } } - } + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyBuilderUITypeEditor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyBuilderUITypeEditor.cs index 4892154b58e..2aaf928a256 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyBuilderUITypeEditor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyBuilderUITypeEditor.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using Microsoft.Win32; using System; @@ -17,13 +18,15 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop { /// /// - internal class Com2PropertyBuilderUITypeEditor : Com2ExtendedUITypeEditor { + internal class Com2PropertyBuilderUITypeEditor : Com2ExtendedUITypeEditor + { private Com2PropertyDescriptor propDesc; - string guidString; - int bldrType; + string guidString; + int bldrType; - public Com2PropertyBuilderUITypeEditor(Com2PropertyDescriptor pd, string guidString, int type, UITypeEditor baseEditor) : base(baseEditor) { + public Com2PropertyBuilderUITypeEditor(Com2PropertyDescriptor pd, string guidString, int type, UITypeEditor baseEditor) : base(baseEditor) + { propDesc = pd; this.guidString = guidString; this.bldrType = type; @@ -36,31 +39,36 @@ public Com2PropertyBuilderUITypeEditor(Com2PropertyDescriptor pd, string guidStr /// the user to modify the value. Host assistance in presenting UI to the user /// can be found through the valueAccess.getService function. /// - public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { + public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) + { IntPtr parentHandle = (IntPtr)UnsafeNativeMethods.GetFocus(); IUIService uiSvc = (IUIService)provider.GetService(typeof(IUIService)); - if (uiSvc != null) { + if (uiSvc != null) + { IWin32Window parent = uiSvc.GetDialogOwnerWindow(); - if (parent != null) { + if (parent != null) + { parentHandle = parent.Handle; } } - + bool useValue = false; //VARIANT pValue = null; object pValue = value; - try{ - object obj = propDesc.TargetObject; - - - if (obj is ICustomTypeDescriptor) { - obj = ((ICustomTypeDescriptor)obj).GetPropertyOwner(propDesc); - } + try + { + object obj = propDesc.TargetObject; + + + if (obj is ICustomTypeDescriptor) + { + obj = ((ICustomTypeDescriptor)obj).GetPropertyOwner(propDesc); + } + - Debug.Assert(obj is NativeMethods.IProvidePropertyBuilder, "object is not IProvidePropertyBuilder"); NativeMethods.IProvidePropertyBuilder propBuilder = (NativeMethods.IProvidePropertyBuilder)obj; @@ -68,17 +76,21 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide guidString, null, new HandleRef(null, parentHandle), - ref pValue, ref useValue))){ + ref pValue, ref useValue))) + { useValue = false; } - }catch(ExternalException ex) { + } + catch (ExternalException ex) + { Debug.Fail("Failed to show property frame: " + ex.ErrorCode.ToString(CultureInfo.InvariantCulture)); } - if (useValue && (bldrType & _CTLBLDTYPE.CTLBLDTYPE_FEDITSOBJDIRECTLY) == 0){ - - return pValue;//pValue.ToVariant(); + if (useValue && (bldrType & _CTLBLDTYPE.CTLBLDTYPE_FEDITSOBJDIRECTLY) == 0) + { + + return pValue;//pValue.ToVariant(); } return value; } @@ -87,7 +99,8 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide /// Retrieves the editing style of the Edit method. If the method /// is not supported, this will return None. /// - public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { + public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) + { return UITypeEditorEditStyle.Modal; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs index 70641e371d6..92f6699c189 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.ComponentModel; @@ -26,7 +27,8 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop { /// It also allows other objects to register listeners to add extended /// information at runtime such as attributes of TypeConverters. /// - internal class Com2PropertyDescriptor : PropertyDescriptor, ICloneable{ + internal class Com2PropertyDescriptor : PropertyDescriptor, ICloneable + { private EventHandlerList events; /// @@ -44,10 +46,10 @@ internal class Com2PropertyDescriptor : PropertyDescriptor, ICloneable{ /// The dispid. This is also in a DispIDAttiribute, but we /// need it a lot. /// - private int dispid; - - private TypeConverter converter; - private object editor; + private int dispid; + + private TypeConverter converter; + private object editor; /// /// The current display name to show for this property @@ -63,8 +65,8 @@ internal class Com2PropertyDescriptor : PropertyDescriptor, ICloneable{ /// /// Keeps track of which data members need to be refreshed. /// - private int refreshState; - + private int refreshState; + /// /// Should we bother asking if refresh is needed? /// @@ -89,45 +91,46 @@ internal class Com2PropertyDescriptor : PropertyDescriptor, ICloneable{ /// /// For Object and dispatch types, we hide them by default. /// - private bool typeHide; + private bool typeHide; /// /// Set if the metadata causes this property to always be hidden /// - private bool canShow; + private bool canShow; /// /// This property is hidden because its get didn't return S_OK /// - private bool hrHidden; + private bool hrHidden; /// /// Set if we are in the process of asking handlers for attributes /// - private bool inAttrQuery; + private bool inAttrQuery; /// /// Our event signitures. /// - private static readonly object EventGetBaseAttributes = new object(); - private static readonly object EventGetDynamicAttributes = new object(); - private static readonly object EventShouldRefresh = new object(); - private static readonly object EventGetDisplayName = new object(); - private static readonly object EventGetDisplayValue = new object(); - private static readonly object EventGetIsReadOnly = new object(); - private static readonly object EventGetTypeConverterAndTypeEditor = new object(); + private static readonly object EventGetBaseAttributes = new object(); + private static readonly object EventGetDynamicAttributes = new object(); + private static readonly object EventShouldRefresh = new object(); + private static readonly object EventGetDisplayName = new object(); + private static readonly object EventGetDisplayValue = new object(); + private static readonly object EventGetIsReadOnly = new object(); + private static readonly object EventGetTypeConverterAndTypeEditor = new object(); private static readonly object EventShouldSerializeValue = new object(); - private static readonly object EventCanResetValue = new object(); - private static readonly object EventResetValue = new object(); + private static readonly object EventCanResetValue = new object(); + private static readonly object EventResetValue = new object(); private static readonly Guid GUID_COLOR = new Guid("{66504301-BE0F-101A-8BBB-00AA00300CAB}"); - + /// /// Our map of native types that we can map to managed types for editors /// private static IDictionary oleConverters; - static Com2PropertyDescriptor() { + static Com2PropertyDescriptor() + { oleConverters = new SortedList(); oleConverters[GUID_COLOR] = typeof(Com2ColorConverter); oleConverters[typeof(SafeNativeMethods.IFontDisp).GUID] = typeof(Com2FontConverter); @@ -135,7 +138,7 @@ static Com2PropertyDescriptor() { oleConverters[typeof(UnsafeNativeMethods.IPictureDisp).GUID] = typeof(Com2PictureConverter); oleConverters[typeof(UnsafeNativeMethods.IPicture).GUID] = typeof(Com2PictureConverter); } - + /// /// Should we convert our type? /// @@ -145,7 +148,8 @@ static Com2PropertyDescriptor() { /// Ctor. /// public Com2PropertyDescriptor(int dispid, string name, Attribute[] attrs, bool readOnly, Type propType, object typeData, bool hrHidden) - : base(name, attrs) { + : base(name, attrs) + { this.baseReadOnly = readOnly; this.readOnly = readOnly; @@ -158,67 +162,82 @@ public Com2PropertyDescriptor(int dispid, string name, Attribute[] attrs, bool r SetNeedsRefresh(Com2PropertyDescriptorRefresh.ReadOnly, readOnly); this.propertyType = propType; - + this.dispid = dispid; - if (typeData != null) { + if (typeData != null) + { this.typeData = typeData; - if (typeData is Com2Enum) { - converter = new Com2EnumConverter((Com2Enum)typeData); + if (typeData is Com2Enum) + { + converter = new Com2EnumConverter((Com2Enum)typeData); } - else if (typeData is Guid) { - valueConverter = CreateOleTypeConverter((Type)oleConverters[(Guid)typeData]); + else if (typeData is Guid) + { + valueConverter = CreateOleTypeConverter((Type)oleConverters[(Guid)typeData]); } } // check if this thing is hidden from metadata this.canShow = true; - if (attrs != null) { - for (int i = 0; i < attrs.Length; i++) { - if (attrs[i].Equals(BrowsableAttribute.No) && !hrHidden) { + if (attrs != null) + { + for (int i = 0; i < attrs.Length; i++) + { + if (attrs[i].Equals(BrowsableAttribute.No) && !hrHidden) + { this.canShow = false; break; } } } - - if (this.canShow && (propType == typeof(object) || (valueConverter == null && propType == typeof(UnsafeNativeMethods.IDispatch)))) { + + if (this.canShow && (propType == typeof(object) || (valueConverter == null && propType == typeof(UnsafeNativeMethods.IDispatch)))) + { this.typeHide = true; } } - protected Attribute[] BaseAttributes { - get { + protected Attribute[] BaseAttributes + { + get + { - if (GetNeedsRefresh(Com2PropertyDescriptorRefresh.BaseAttributes)) { + if (GetNeedsRefresh(Com2PropertyDescriptorRefresh.BaseAttributes)) + { SetNeedsRefresh(Com2PropertyDescriptorRefresh.BaseAttributes, false); int baseCount = baseAttrs == null ? 0 : baseAttrs.Length; ArrayList attrList = new ArrayList(); - if (baseCount != 0) { + if (baseCount != 0) + { attrList.AddRange(baseAttrs); } OnGetBaseAttributes(new GetAttributesEvent(attrList)); - if (attrList.Count != baseCount) { + if (attrList.Count != baseCount) + { this.baseAttrs = new Attribute[attrList.Count]; } - - if (baseAttrs != null) { + + if (baseAttrs != null) + { attrList.CopyTo(this.baseAttrs, 0); } - else { + else + { baseAttrs = new Attribute[0]; } } return baseAttrs; } - set { + set + { baseAttrs = value; } } @@ -226,9 +245,12 @@ protected Attribute[] BaseAttributes { /// /// Attributes /// - public override AttributeCollection Attributes { - get { - if (this.AttributesValid || this.InAttrQuery) { + public override AttributeCollection Attributes + { + get + { + if (this.AttributesValid || this.InAttrQuery) + { return base.Attributes; } @@ -238,22 +260,28 @@ public override AttributeCollection Attributes { ArrayList newAttributes = null; // if we are forcing a hide - if (typeHide && canShow) { - if (newAttributes == null) { + if (typeHide && canShow) + { + if (newAttributes == null) + { newAttributes = new ArrayList(AttributeArray); } newAttributes.Add(new BrowsableAttribute(false)); } - else if (hrHidden) { + else if (hrHidden) + { // check to see if the get still fails object target = this.TargetObject; - if (target != null) { + if (target != null) + { int hr = new ComNativeDescriptor().GetPropertyValue(target, this.dispid, new object[1]); // if not, go ahead and make this a browsable item - if (NativeMethods.Succeeded(hr)) { + if (NativeMethods.Succeeded(hr)) + { // make it browsable - if (newAttributes == null) { + if (newAttributes == null) + { newAttributes = new ArrayList(AttributeArray); } newAttributes.Add(new BrowsableAttribute(true)); @@ -261,9 +289,10 @@ public override AttributeCollection Attributes { } } } - + this.inAttrQuery = true; - try { + try + { // demand get any extended attributes ArrayList attrList = new ArrayList(); @@ -271,32 +300,36 @@ public override AttributeCollection Attributes { OnGetDynamicAttributes(new GetAttributesEvent(attrList)); Attribute ma; - - if (attrList.Count != 0 && newAttributes == null) { + + if (attrList.Count != 0 && newAttributes == null) + { newAttributes = new ArrayList(AttributeArray); } // push any new attributes into the base type - for (int i=0; i < attrList.Count; i++) { + for (int i = 0; i < attrList.Count; i++) + { ma = (Attribute)attrList[i]; newAttributes.Add(ma); } } - finally { + finally + { this.inAttrQuery = false; } // these are now valid. SetNeedsRefresh(Com2PropertyDescriptorRefresh.Attributes, false); - + // If we reconfigured attributes, then poke the new set back in. // - if (newAttributes != null) { + if (newAttributes != null) + { Attribute[] temp = new Attribute[newAttributes.Count]; newAttributes.CopyTo(temp, 0); AttributeArray = temp; } - + return base.Attributes; } @@ -306,10 +339,13 @@ public override AttributeCollection Attributes { /// Checks if the attributes are valid. Asks any clients if they /// would like attributes requeried. /// - protected bool AttributesValid{ - get{ + protected bool AttributesValid + { + get + { bool currentRefresh = !GetNeedsRefresh(Com2PropertyDescriptorRefresh.Attributes); - if (queryRefresh) { + if (queryRefresh) + { GetRefreshStateEvent rse = new GetRefreshStateEvent(Com2ShouldRefreshTypes.Attributes, !currentRefresh); OnShouldRefresh(rse); currentRefresh = !rse.Value; @@ -322,8 +358,10 @@ protected bool AttributesValid{ /// /// Checks if this item can be shown. /// - public bool CanShow{ - get{ + public bool CanShow + { + get + { return this.canShow; } } @@ -331,49 +369,59 @@ public bool CanShow{ /// /// Retrieves the type of the component this PropertyDescriptor is bound to. /// - public override Type ComponentType { - get { + public override Type ComponentType + { + get + { return typeof(UnsafeNativeMethods.IDispatch); } } - + /// /// Retrieves the type converter for this property. /// - public override TypeConverter Converter { - get { - if (TypeConverterValid) { - return converter; - } + public override TypeConverter Converter + { + get + { + if (TypeConverterValid) + { + return converter; + } object typeEd = null; - - GetTypeConverterAndTypeEditor(ref converter, typeof(UITypeEditor), ref typeEd); - - if (!TypeEditorValid) { - this.editor = typeEd; - SetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeEditor, false); - } - SetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeConverter, false); - - return converter; + + GetTypeConverterAndTypeEditor(ref converter, typeof(UITypeEditor), ref typeEd); + + if (!TypeEditorValid) + { + this.editor = typeEd; + SetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeEditor, false); + } + SetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeConverter, false); + + return converter; } } /// /// Retrieves whether this component is applying a type conversion... /// - public bool ConvertingNativeType { - get { - return(valueConverter != null); + public bool ConvertingNativeType + { + get + { + return (valueConverter != null); } - } + } /// /// Retrieves the default value for this property. /// - protected virtual object DefaultValue { - get { + protected virtual object DefaultValue + { + get + { return null; } } @@ -381,8 +429,10 @@ protected virtual object DefaultValue { /// /// Retrieves the DISPID for this item /// - public int DISPID{ - get{ + public int DISPID + { + get + { return this.dispid; } } @@ -391,9 +441,12 @@ public int DISPID{ /// Gets the friendly name that should be displayed to the user in a window like /// the Property Browser. /// - public override string DisplayName { - get { - if (!this.DisplayNameValid) { + public override string DisplayName + { + get + { + if (!this.DisplayNameValid) + { GetNameItemEvent gni = new GetNameItemEvent(base.DisplayName); OnGetDisplayName(gni); this.displayName = gni.NameString; @@ -407,10 +460,13 @@ public override string DisplayName { /// Checks if the property display name is valid /// asks clients if they would like display name requeried. /// - protected bool DisplayNameValid{ - get{ + protected bool DisplayNameValid + { + get + { bool currentRefresh = !(displayName == null || GetNeedsRefresh(Com2PropertyDescriptorRefresh.DisplayName)); - if (queryRefresh) { + if (queryRefresh) + { GetRefreshStateEvent rse = new GetRefreshStateEvent(Com2ShouldRefreshTypes.DisplayName, !currentRefresh); OnShouldRefresh(rse); SetNeedsRefresh(Com2PropertyDescriptorRefresh.DisplayName, rse.Value); @@ -420,17 +476,22 @@ protected bool DisplayNameValid{ } } - protected EventHandlerList Events { - get { - if (events == null) { + protected EventHandlerList Events + { + get + { + if (events == null) + { events = new EventHandlerList(); } return events; } } - protected bool InAttrQuery{ - get{ + protected bool InAttrQuery + { + get + { return this.inAttrQuery; } } @@ -438,9 +499,12 @@ protected bool InAttrQuery{ /// /// Indicates whether this property is read only. /// - public override bool IsReadOnly { - get { - if (!this.ReadOnlyValid) { + public override bool IsReadOnly + { + get + { + if (!this.ReadOnlyValid) + { this.readOnly |= (this.Attributes[typeof(ReadOnlyAttribute)].Equals(ReadOnlyAttribute.Yes)); GetBoolValueEvent gbv = new GetBoolValueEvent(this.readOnly); OnGetIsReadOnly(gbv); @@ -451,11 +515,14 @@ public override bool IsReadOnly { } } - internal Com2Properties PropertyManager{ - set{ + internal Com2Properties PropertyManager + { + set + { this.com2props = value; } - get{ + get + { return this.com2props; } } @@ -463,13 +530,17 @@ internal Com2Properties PropertyManager{ /// /// Retrieves the type of the property. /// - public override Type PropertyType { - get { + public override Type PropertyType + { + get + { // replace the type with the mapped converter type - if (valueConverter != null) { + if (valueConverter != null) + { return valueConverter.ManagedType; } - else { + else + { return propertyType; } } @@ -479,15 +550,19 @@ public override Type PropertyType { /// Checks if the read only state is valid. /// Asks clients if they would like read-only requeried. /// - protected bool ReadOnlyValid{ - get{ - if (baseReadOnly) { + protected bool ReadOnlyValid + { + get + { + if (baseReadOnly) + { return true; } - + bool currentRefresh = !GetNeedsRefresh(Com2PropertyDescriptorRefresh.ReadOnly); - - if (queryRefresh) { + + if (queryRefresh) + { GetRefreshStateEvent rse = new GetRefreshStateEvent(Com2ShouldRefreshTypes.ReadOnly, !currentRefresh); OnShouldRefresh(rse); SetNeedsRefresh(Com2PropertyDescriptorRefresh.ReadOnly, rse.Value); @@ -503,18 +578,23 @@ protected bool ReadOnlyValid{ /// public virtual object TargetObject { - get{ - if (com2props != null) { + get + { + if (com2props != null) + { return com2props.TargetObject; } return null; } } - - protected bool TypeConverterValid { - get { - bool currentRefresh =!(converter == null || GetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeConverter)); - if (queryRefresh) { + + protected bool TypeConverterValid + { + get + { + bool currentRefresh = !(converter == null || GetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeConverter)); + if (queryRefresh) + { GetRefreshStateEvent rse = new GetRefreshStateEvent(Com2ShouldRefreshTypes.TypeConverter, !currentRefresh); OnShouldRefresh(rse); SetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeConverter, rse.Value); @@ -523,12 +603,15 @@ protected bool TypeConverterValid { return currentRefresh; } } - - protected bool TypeEditorValid { - get { + + protected bool TypeEditorValid + { + get + { bool currentRefresh = !(editor == null || GetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeEditor)); - - if (queryRefresh) { + + if (queryRefresh) + { GetRefreshStateEvent rse = new GetRefreshStateEvent(Com2ShouldRefreshTypes.TypeEditor, !currentRefresh); OnShouldRefresh(rse); SetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeEditor, rse.Value); @@ -538,47 +621,56 @@ protected bool TypeEditorValid { } } - public event GetBoolValueEventHandler QueryCanResetValue { + public event GetBoolValueEventHandler QueryCanResetValue + { add => Events.AddHandler(EventCanResetValue, value); remove => Events.RemoveHandler(EventCanResetValue, value); } - public event GetAttributesEventHandler QueryGetBaseAttributes { + public event GetAttributesEventHandler QueryGetBaseAttributes + { add => Events.AddHandler(EventGetBaseAttributes, value); remove => Events.RemoveHandler(EventGetBaseAttributes, value); } - public event GetAttributesEventHandler QueryGetDynamicAttributes { + public event GetAttributesEventHandler QueryGetDynamicAttributes + { add => Events.AddHandler(EventGetDynamicAttributes, value); remove => Events.RemoveHandler(EventGetDynamicAttributes, value); } - public event GetNameItemEventHandler QueryGetDisplayName { + public event GetNameItemEventHandler QueryGetDisplayName + { add => Events.AddHandler(EventGetDisplayName, value); remove => Events.RemoveHandler(EventGetDisplayName, value); } - public event GetNameItemEventHandler QueryGetDisplayValue { - add => Events.AddHandler(EventGetDisplayValue, value); + public event GetNameItemEventHandler QueryGetDisplayValue + { + add => Events.AddHandler(EventGetDisplayValue, value); remove => Events.RemoveHandler(EventGetDisplayValue, value); } - public event GetBoolValueEventHandler QueryGetIsReadOnly { + public event GetBoolValueEventHandler QueryGetIsReadOnly + { add => Events.AddHandler(EventGetIsReadOnly, value); remove => Events.RemoveHandler(EventGetIsReadOnly, value); } - public event GetTypeConverterAndTypeEditorEventHandler QueryGetTypeConverterAndTypeEditor { + public event GetTypeConverterAndTypeEditorEventHandler QueryGetTypeConverterAndTypeEditor + { add => Events.AddHandler(EventGetTypeConverterAndTypeEditor, value); remove => Events.RemoveHandler(EventGetTypeConverterAndTypeEditor, value); } - - public event Com2EventHandler QueryResetValue { + + public event Com2EventHandler QueryResetValue + { add => Events.AddHandler(EventResetValue, value); remove => Events.RemoveHandler(EventResetValue, value); } - public event GetBoolValueEventHandler QueryShouldSerializeValue { + public event GetBoolValueEventHandler QueryShouldSerializeValue + { add => Events.AddHandler(EventShouldSerializeValue, value); remove => Events.RemoveHandler(EventShouldSerializeValue, value); } @@ -591,13 +683,16 @@ public event GetBoolValueEventHandler QueryShouldSerializeValue { /// If there is just a reset method, this always returns true. If none of these /// cases apply, this returns false. /// - public override bool CanResetValue(object component) { + public override bool CanResetValue(object component) + { - if (component is ICustomTypeDescriptor) { + if (component is ICustomTypeDescriptor) + { component = ((ICustomTypeDescriptor)component).GetPropertyOwner(this); } - - if (component == this.TargetObject) { + + if (component == this.TargetObject) + { GetBoolValueEvent gbv = new GetBoolValueEvent(false); OnCanResetValue(gbv); return gbv.Value; @@ -605,7 +700,8 @@ public override bool CanResetValue(object component) { return false; } - public object Clone() { + public object Clone() + { return new Com2PropertyDescriptor(this.dispid, this.Name, (Attribute[])this.baseAttrs.Clone(), this.readOnly, this.propertyType, this.typeData, this.hrHidden); } @@ -613,18 +709,22 @@ public object Clone() { /// Creates a converter Object, first by looking for a ctor with a Com2ProeprtyDescriptor /// parameter, then using the default ctor if it is not found. /// - private Com2DataTypeToManagedDataTypeConverter CreateOleTypeConverter(Type t) { + private Com2DataTypeToManagedDataTypeConverter CreateOleTypeConverter(Type t) + { - if (t == null) { + if (t == null) + { return null; } - ConstructorInfo ctor = t.GetConstructor(new Type[]{typeof(Com2PropertyDescriptor)}); + ConstructorInfo ctor = t.GetConstructor(new Type[] { typeof(Com2PropertyDescriptor) }); Com2DataTypeToManagedDataTypeConverter converter; - if (ctor != null) { - converter = (Com2DataTypeToManagedDataTypeConverter)ctor.Invoke(new object[]{this}); + if (ctor != null) + { + converter = (Com2DataTypeToManagedDataTypeConverter)ctor.Invoke(new object[] { this }); } - else { + else + { converter = (Com2DataTypeToManagedDataTypeConverter)Activator.CreateInstance(t); } return converter; @@ -634,87 +734,110 @@ private Com2DataTypeToManagedDataTypeConverter CreateOleTypeConverter(Type t) { /// Creates an instance of the member attribute collection. This can /// be overriden by subclasses to return a subclass of AttributeCollection. /// - protected override AttributeCollection CreateAttributeCollection() { + protected override AttributeCollection CreateAttributeCollection() + { return new AttributeCollection(AttributeArray); } - - private TypeConverter GetBaseTypeConverter() { - - if (PropertyType == null) { + + private TypeConverter GetBaseTypeConverter() + { + + if (PropertyType == null) + { return new TypeConverter(); } - + TypeConverter localConverter = null; - + TypeConverterAttribute attr = (TypeConverterAttribute)Attributes[typeof(TypeConverterAttribute)]; - if (attr != null) { - string converterTypeName = attr.ConverterTypeName; - if (converterTypeName != null && converterTypeName.Length > 0) { - Type converterType = Type.GetType(converterTypeName); - if (converterType != null && typeof(TypeConverter).IsAssignableFrom(converterType)) { - try { - localConverter = (TypeConverter)Activator.CreateInstance(converterType); - if (localConverter != null) { - refreshState |= Com2PropertyDescriptorRefresh.TypeConverterAttr; - } - } - catch (Exception ex) { - Debug.Fail("Failed to create TypeConverter of type '" + attr.ConverterTypeName + "' from Attribute", ex.ToString()); - } - } - } - } - + if (attr != null) + { + string converterTypeName = attr.ConverterTypeName; + if (converterTypeName != null && converterTypeName.Length > 0) + { + Type converterType = Type.GetType(converterTypeName); + if (converterType != null && typeof(TypeConverter).IsAssignableFrom(converterType)) + { + try + { + localConverter = (TypeConverter)Activator.CreateInstance(converterType); + if (localConverter != null) + { + refreshState |= Com2PropertyDescriptorRefresh.TypeConverterAttr; + } + } + catch (Exception ex) + { + Debug.Fail("Failed to create TypeConverter of type '" + attr.ConverterTypeName + "' from Attribute", ex.ToString()); + } + } + } + } + // if we didn't get one from the attribute, ask the type descriptor - if (localConverter == null) { - // we don't want to create the value editor for the IDispatch props because + if (localConverter == null) + { + // we don't want to create the value editor for the IDispatch props because // that will create the reference editor. We don't want that guy! // - if (!typeof(UnsafeNativeMethods.IDispatch).IsAssignableFrom(this.PropertyType)) { - localConverter = base.Converter; + if (!typeof(UnsafeNativeMethods.IDispatch).IsAssignableFrom(this.PropertyType)) + { + localConverter = base.Converter; } - else { - localConverter = new Com2IDispatchConverter(this, false); + else + { + localConverter = new Com2IDispatchConverter(this, false); } } - - if (localConverter == null) { + + if (localConverter == null) + { localConverter = new TypeConverter(); } return localConverter; } - - private object GetBaseTypeEditor(Type editorBaseType) { - - if (PropertyType == null) { + + private object GetBaseTypeEditor(Type editorBaseType) + { + + if (PropertyType == null) + { return null; } object localEditor = null; EditorAttribute attr = (EditorAttribute)Attributes[typeof(EditorAttribute)]; - if (attr != null) { - string editorTypeName = attr.EditorBaseTypeName; - - if (editorTypeName != null && editorTypeName.Length > 0) { - Type attrEditorBaseType = Type.GetType(editorTypeName); - if (attrEditorBaseType != null && attrEditorBaseType == editorBaseType) { + if (attr != null) + { + string editorTypeName = attr.EditorBaseTypeName; + + if (editorTypeName != null && editorTypeName.Length > 0) + { + Type attrEditorBaseType = Type.GetType(editorTypeName); + if (attrEditorBaseType != null && attrEditorBaseType == editorBaseType) + { Type type = Type.GetType(attr.EditorTypeName); - if (type != null) { - try { - localEditor = Activator.CreateInstance(type); - if (localEditor != null) { - refreshState |= Com2PropertyDescriptorRefresh.TypeEditorAttr; - } + if (type != null) + { + try + { + localEditor = Activator.CreateInstance(type); + if (localEditor != null) + { + refreshState |= Com2PropertyDescriptorRefresh.TypeEditorAttr; + } } - catch (Exception ex) { - Debug.Fail("Failed to create edtior of type '" + attr.EditorTypeName + "' from Attribute", ex.ToString()); + catch (Exception ex) + { + Debug.Fail("Failed to create edtior of type '" + attr.EditorTypeName + "' from Attribute", ex.ToString()); } } - } - } + } + } } - if (localEditor == null) { - localEditor = base.GetEditor(editorBaseType); + if (localEditor == null) + { + localEditor = base.GetEditor(editorBaseType); } return localEditor; } @@ -723,7 +846,8 @@ private object GetBaseTypeEditor(Type editorBaseType) { /// Gets the value that should be displayed to the user, such as in /// the Property Browser. /// - public virtual string GetDisplayValue(string defaultValue) { + public virtual string GetDisplayValue(string defaultValue) + { GetNameItemEvent nie = new GetNameItemEvent(defaultValue); OnGetDisplayValue(nie); @@ -735,30 +859,36 @@ public virtual string GetDisplayValue(string defaultValue) { /// /// Retrieves an editor of the requested type. /// - public override object GetEditor(Type editorBaseType) { - if (TypeEditorValid) { - return editor; - } - - if (PropertyType == null) { - return null; - } - - if (editorBaseType == typeof(UITypeEditor)) { - TypeConverter c = null; - GetTypeConverterAndTypeEditor(ref c, editorBaseType, ref editor); - - if (!TypeConverterValid) { - this.converter = c; - SetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeConverter, false); - } - SetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeEditor, false); - } - else { - editor = base.GetEditor(editorBaseType); - } - return editor; - + public override object GetEditor(Type editorBaseType) + { + if (TypeEditorValid) + { + return editor; + } + + if (PropertyType == null) + { + return null; + } + + if (editorBaseType == typeof(UITypeEditor)) + { + TypeConverter c = null; + GetTypeConverterAndTypeEditor(ref c, editorBaseType, ref editor); + + if (!TypeConverterValid) + { + this.converter = c; + SetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeConverter, false); + } + SetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeEditor, false); + } + else + { + editor = base.GetEditor(editorBaseType); + } + return editor; + } /// @@ -766,11 +896,13 @@ public override object GetEditor(Type editorBaseType) { /// invoking the getXXX method. An exception in the getXXX /// method will pass through. /// - public object GetNativeValue(object component){ + public object GetNativeValue(object component) + { if (component == null) return null; - if (component is ICustomTypeDescriptor) { + if (component is ICustomTypeDescriptor) + { component = ((ICustomTypeDescriptor)component).GetPropertyOwner(this); } @@ -790,30 +922,34 @@ public object GetNativeValue(object component){ pVarResult, pExcepInfo, null); - switch (hr) { - case NativeMethods.S_OK: - case NativeMethods.S_FALSE: + switch (hr) + { + case NativeMethods.S_OK: + case NativeMethods.S_FALSE: - if (pVarResult[0] == null || Convert.IsDBNull(pVarResult[0])) { - lastValue = null; - } - else { - lastValue = pVarResult[0]; - } - return lastValue; - case NativeMethods.DISP_E_EXCEPTION: - //PrintExceptionInfo(pExcepInfo); - return null; - default: - throw new ExternalException(string.Format(SR.DispInvokeFailed, "GetValue" , hr), hr); + if (pVarResult[0] == null || Convert.IsDBNull(pVarResult[0])) + { + lastValue = null; + } + else + { + lastValue = pVarResult[0]; + } + return lastValue; + case NativeMethods.DISP_E_EXCEPTION: + //PrintExceptionInfo(pExcepInfo); + return null; + default: + throw new ExternalException(string.Format(SR.DispInvokeFailed, "GetValue", hr), hr); } } /// /// Checks whether the particular item(s) need refreshing. /// - private bool GetNeedsRefresh(int mask){ - return(refreshState & mask) != 0; + private bool GetNeedsRefresh(int mask) + { + return (refreshState & mask) != 0; } @@ -822,25 +958,30 @@ private bool GetNeedsRefresh(int mask){ /// invoking the getXXX method. An exception in the getXXX /// method will pass through. /// - public override object GetValue(object component) { + public override object GetValue(object component) + { lastValue = GetNativeValue(component); // do we need to convert the type? - if (this.ConvertingNativeType && lastValue != null) { + if (this.ConvertingNativeType && lastValue != null) + { lastValue = valueConverter.ConvertNativeToManaged(lastValue, this); } - else if (lastValue != null && propertyType != null && propertyType.IsEnum && lastValue.GetType().IsPrimitive) { + else if (lastValue != null && propertyType != null && propertyType.IsEnum && lastValue.GetType().IsPrimitive) + { // we've got to convert the value here -- we built the enum but the native object returns // us values as integers // - try { + try + { lastValue = Enum.ToObject(propertyType, lastValue); } - catch { + catch + { } } return lastValue; } - + /// /// Retrieves the value editor for the property. If a value editor is passed /// in as a TypeConverterAttribute, that value editor will be instantiated. @@ -849,120 +990,141 @@ public override object GetValue(object component) { /// If there is no system value editor, null is returned. If the value editor found /// takes an IEditorSite in its constructor, the parameter will be passed in. /// - public void GetTypeConverterAndTypeEditor(ref TypeConverter typeConverter, Type editorBaseType, ref object typeEditor) { - - // get the base editor and converter, attributes first - TypeConverter localConverter = typeConverter; - object localEditor = typeEditor; - - if (localConverter == null) { - localConverter = GetBaseTypeConverter(); - } - - if (localEditor == null) { - localEditor = GetBaseTypeEditor(editorBaseType); - } - - // if this is a object, get the value and attempt to create the correct value editor based on that value. - // we don't do this if the state came from an attribute - // - if (0 == (refreshState & Com2PropertyDescriptorRefresh.TypeConverterAttr) && this.PropertyType == typeof(Com2Variant)) { - Type editorType = PropertyType; + public void GetTypeConverterAndTypeEditor(ref TypeConverter typeConverter, Type editorBaseType, ref object typeEditor) + { + + // get the base editor and converter, attributes first + TypeConverter localConverter = typeConverter; + object localEditor = typeEditor; + + if (localConverter == null) + { + localConverter = GetBaseTypeConverter(); + } + + if (localEditor == null) + { + localEditor = GetBaseTypeEditor(editorBaseType); + } + + // if this is a object, get the value and attempt to create the correct value editor based on that value. + // we don't do this if the state came from an attribute + // + if (0 == (refreshState & Com2PropertyDescriptorRefresh.TypeConverterAttr) && this.PropertyType == typeof(Com2Variant)) + { + Type editorType = PropertyType; object value = GetValue(TargetObject); - if (value != null) { - editorType = value.GetType(); - } - ComNativeDescriptor.ResolveVariantTypeConverterAndTypeEditor(value, ref localConverter, editorBaseType, ref localEditor); - } - - // now see if someone else would like to serve up a value editor - // - - // unwrap the editor if it's one of ours. - if (localConverter is Com2PropDescMainConverter) { - localConverter = ((Com2PropDescMainConverter)localConverter).InnerConverter; - } - - GetTypeConverterAndTypeEditorEvent e = new GetTypeConverterAndTypeEditorEvent(localConverter, localEditor); - OnGetTypeConverterAndTypeEditor(e); - localConverter = e.TypeConverter; - localEditor = e.TypeEditor; - - // just in case one of the handlers removed our editor... - // - if (localConverter == null) { - localConverter = GetBaseTypeConverter(); + if (value != null) + { + editorType = value.GetType(); } - - if (localEditor == null) { - localEditor = GetBaseTypeEditor(editorBaseType); - } - - // wrap the value editor in our main value editor, but only if it isn't "TypeConverter" or already a Com2PropDescMainTypeConverter - // - Type localConverterType = localConverter.GetType(); - if (localConverterType != typeof(TypeConverter) && localConverterType != (typeof(Com2PropDescMainConverter))) { - localConverter = new Com2PropDescMainConverter(this, localConverter); - } - - // save the values back to the variables. - // - typeConverter = localConverter; - typeEditor = localEditor; + ComNativeDescriptor.ResolveVariantTypeConverterAndTypeEditor(value, ref localConverter, editorBaseType, ref localEditor); + } + + // now see if someone else would like to serve up a value editor + // + + // unwrap the editor if it's one of ours. + if (localConverter is Com2PropDescMainConverter) + { + localConverter = ((Com2PropDescMainConverter)localConverter).InnerConverter; + } + + GetTypeConverterAndTypeEditorEvent e = new GetTypeConverterAndTypeEditorEvent(localConverter, localEditor); + OnGetTypeConverterAndTypeEditor(e); + localConverter = e.TypeConverter; + localEditor = e.TypeEditor; + + // just in case one of the handlers removed our editor... + // + if (localConverter == null) + { + localConverter = GetBaseTypeConverter(); + } + + if (localEditor == null) + { + localEditor = GetBaseTypeEditor(editorBaseType); + } + + // wrap the value editor in our main value editor, but only if it isn't "TypeConverter" or already a Com2PropDescMainTypeConverter + // + Type localConverterType = localConverter.GetType(); + if (localConverterType != typeof(TypeConverter) && localConverterType != (typeof(Com2PropDescMainConverter))) + { + localConverter = new Com2PropDescMainConverter(this, localConverter); + } + + // save the values back to the variables. + // + typeConverter = localConverter; + typeEditor = localEditor; } - + /// /// Is the given value equal to the last known value for this object? /// - public bool IsCurrentValue(object value) { + public bool IsCurrentValue(object value) + { return (value == lastValue || (lastValue != null && lastValue.Equals(value))); } /// /// Raises the appropriate event /// - protected void OnCanResetValue(GetBoolValueEvent gvbe) { + protected void OnCanResetValue(GetBoolValueEvent gvbe) + { RaiseGetBoolValueEvent(EventCanResetValue, gvbe); } - protected void OnGetBaseAttributes(GetAttributesEvent e) { - - try { + protected void OnGetBaseAttributes(GetAttributesEvent e) + { + + try + { com2props.AlwaysValid = com2props.CheckValid(); - + GetAttributesEventHandler handler = (GetAttributesEventHandler)Events[EventGetBaseAttributes]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } - finally { + finally + { com2props.AlwaysValid = false; } } - + /// /// Raises the appropriate event /// - protected void OnGetDisplayName(GetNameItemEvent gnie) { + protected void OnGetDisplayName(GetNameItemEvent gnie) + { RaiseGetNameItemEvent(EventGetDisplayName, gnie); } /// /// Raises the appropriate event /// - protected void OnGetDisplayValue(GetNameItemEvent gnie) { + protected void OnGetDisplayValue(GetNameItemEvent gnie) + { RaiseGetNameItemEvent(EventGetDisplayValue, gnie); } /// /// Raises the appropriate event /// - protected void OnGetDynamicAttributes(GetAttributesEvent e) { + protected void OnGetDynamicAttributes(GetAttributesEvent e) + { - try { + try + { com2props.AlwaysValid = com2props.CheckValid(); GetAttributesEventHandler handler = (GetAttributesEventHandler)Events[EventGetDynamicAttributes]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } - finally { + finally + { com2props.AlwaysValid = false; } } @@ -970,32 +1132,39 @@ protected void OnGetDynamicAttributes(GetAttributesEvent e) { /// /// Raises the appropriate event /// - protected void OnGetIsReadOnly(GetBoolValueEvent gvbe) { + protected void OnGetIsReadOnly(GetBoolValueEvent gvbe) + { RaiseGetBoolValueEvent(EventGetIsReadOnly, gvbe); } - protected void OnGetTypeConverterAndTypeEditor(GetTypeConverterAndTypeEditorEvent e) { - try { + protected void OnGetTypeConverterAndTypeEditor(GetTypeConverterAndTypeEditorEvent e) + { + try + { com2props.AlwaysValid = com2props.CheckValid(); GetTypeConverterAndTypeEditorEventHandler handler = (GetTypeConverterAndTypeEditorEventHandler)Events[EventGetTypeConverterAndTypeEditor]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } - finally { + finally + { com2props.AlwaysValid = false; } } - + /// /// Raises the appropriate event /// - protected void OnResetValue(EventArgs e) { + protected void OnResetValue(EventArgs e) + { RaiseCom2Event(EventResetValue, e); } /// /// Raises the appropriate event /// - protected void OnShouldSerializeValue(GetBoolValueEvent gvbe) { + protected void OnShouldSerializeValue(GetBoolValueEvent gvbe) + { RaiseGetBoolValueEvent(EventShouldSerializeValue, gvbe); } @@ -1003,20 +1172,25 @@ protected void OnShouldSerializeValue(GetBoolValueEvent gvbe) { /// /// Raises the appropriate event /// - protected void OnShouldRefresh(GetRefreshStateEvent gvbe) { + protected void OnShouldRefresh(GetRefreshStateEvent gvbe) + { RaiseGetBoolValueEvent(EventShouldRefresh, gvbe); } /// /// Raises the appropriate event /// - private void RaiseGetBoolValueEvent(object key, GetBoolValueEvent e) { - try { + private void RaiseGetBoolValueEvent(object key, GetBoolValueEvent e) + { + try + { com2props.AlwaysValid = com2props.CheckValid(); GetBoolValueEventHandler handler = (GetBoolValueEventHandler)Events[key]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } - finally { + finally + { com2props.AlwaysValid = false; } } @@ -1024,13 +1198,17 @@ private void RaiseGetBoolValueEvent(object key, GetBoolValueEvent e) { /// /// Raises the appropriate event /// - private void RaiseCom2Event(object key, EventArgs e) { - try { + private void RaiseCom2Event(object key, EventArgs e) + { + try + { com2props.AlwaysValid = com2props.CheckValid(); Com2EventHandler handler = (Com2EventHandler)Events[key]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } - finally { + finally + { com2props.AlwaysValid = false; } } @@ -1038,13 +1216,17 @@ private void RaiseCom2Event(object key, EventArgs e) { /// /// Raises the appropriate event /// - private void RaiseGetNameItemEvent(object key, GetNameItemEvent e) { - try { - com2props.AlwaysValid = com2props.CheckValid(); + private void RaiseGetNameItemEvent(object key, GetNameItemEvent e) + { + try + { + com2props.AlwaysValid = com2props.CheckValid(); GetNameItemEventHandler handler = (GetNameItemEventHandler)Events[key]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } - finally { + finally + { com2props.AlwaysValid = false; } } @@ -1057,12 +1239,15 @@ private void RaiseGetNameItemEvent(object key, GetNameItemEvent e) { /// for. If one is found, it will be invoked. If one is not found, this /// is a nop. /// - public override void ResetValue(object component) { - if (component is ICustomTypeDescriptor) { + public override void ResetValue(object component) + { + if (component is ICustomTypeDescriptor) + { component = ((ICustomTypeDescriptor)component).GetPropertyOwner(this); } - - if (component == this.TargetObject) { + + if (component == this.TargetObject) + { OnResetValue(EventArgs.Empty); } } @@ -1070,11 +1255,14 @@ public override void ResetValue(object component) { /// /// Sets whether the particular item(s) need refreshing. /// - internal void SetNeedsRefresh(int mask, bool value){ - if (value) { + internal void SetNeedsRefresh(int mask, bool value) + { + if (value) + { refreshState |= mask; } - else { + else + { refreshState &= ~mask; } } @@ -1087,26 +1275,32 @@ internal void SetNeedsRefresh(int mask, bool value){ /// property so that getXXX following a setXXX should return the value /// passed in if no exception was thrown in the setXXX call. /// - public override void SetValue(object component, object value) { + public override void SetValue(object component, object value) + { - if (this.readOnly) { - throw new NotSupportedException(string.Format(SR.COM2ReadonlyProperty, this.Name )); + if (this.readOnly) + { + throw new NotSupportedException(string.Format(SR.COM2ReadonlyProperty, this.Name)); } object owner = component; - if (owner is ICustomTypeDescriptor) { + if (owner is ICustomTypeDescriptor) + { owner = ((ICustomTypeDescriptor)owner).GetPropertyOwner(this); } - if (owner == null || !Marshal.IsComObject(owner) || !(owner is UnsafeNativeMethods.IDispatch)) { + if (owner == null || !Marshal.IsComObject(owner) || !(owner is UnsafeNativeMethods.IDispatch)) + { return; } // do we need to convert the type? - if (valueConverter != null) { + if (valueConverter != null) + { bool cancel = false; value = valueConverter.ConvertManagedToNative(value, this, ref cancel); - if (cancel) { + if (cancel) + { return; } } @@ -1117,10 +1311,11 @@ public override void SetValue(object component, object value) { NativeMethods.tagEXCEPINFO excepInfo = new NativeMethods.tagEXCEPINFO(); dp.cArgs = 1; dp.cNamedArgs = 1; - int[] namedArgs = new int[]{NativeMethods.DISPID_PROPERTYPUT}; + int[] namedArgs = new int[] { NativeMethods.DISPID_PROPERTYPUT }; GCHandle gcHandle = GCHandle.Alloc(namedArgs, GCHandleType.Pinned); - try { + try + { dp.rgdispidNamedArgs = Marshal.UnsafeAddrOfPinnedArrayElement(namedArgs, 0); const int SizeOfVariant = 16; Debug.Assert(SizeOfVariant == Marshal.SizeOf()); @@ -1128,7 +1323,8 @@ public override void SetValue(object component, object value) { SafeNativeMethods.VariantInit(new HandleRef(null, mem)); Marshal.GetNativeVariantForObject(value, mem); dp.rgvarg = mem; - try { + try + { Guid g = Guid.Empty; int hr = pDisp.Invoke(this.dispid, @@ -1141,74 +1337,86 @@ public override void SetValue(object component, object value) { string errorInfo = null; - if (hr == NativeMethods.DISP_E_EXCEPTION && excepInfo.scode != 0) { + if (hr == NativeMethods.DISP_E_EXCEPTION && excepInfo.scode != 0) + { hr = excepInfo.scode; errorInfo = excepInfo.bstrDescription; } - switch (hr) { - case NativeMethods.E_ABORT: - case NativeMethods.OLE_E_PROMPTSAVECANCELLED: - // cancelled checkout, etc. - return; - case NativeMethods.S_OK: - case NativeMethods.S_FALSE: - OnValueChanged(component, EventArgs.Empty); - lastValue = value; - return; - default: - - //Debug.Fail(String.Format("IDispatch::Invoke(INVOKE_PROPPUT) returned hr=0x{0:X}", hr)); - - if (pDisp is UnsafeNativeMethods.ISupportErrorInfo) { - g = typeof(UnsafeNativeMethods.IDispatch).GUID; - if (NativeMethods.Succeeded(((UnsafeNativeMethods.ISupportErrorInfo)pDisp).InterfaceSupportsErrorInfo(ref g))) { - UnsafeNativeMethods.IErrorInfo pErrorInfo = null; - UnsafeNativeMethods.GetErrorInfo(0, ref pErrorInfo); - string info= null; - if (pErrorInfo != null) { - if (NativeMethods.Succeeded(pErrorInfo.GetDescription(ref info))) { - errorInfo = info; + switch (hr) + { + case NativeMethods.E_ABORT: + case NativeMethods.OLE_E_PROMPTSAVECANCELLED: + // cancelled checkout, etc. + return; + case NativeMethods.S_OK: + case NativeMethods.S_FALSE: + OnValueChanged(component, EventArgs.Empty); + lastValue = value; + return; + default: + + //Debug.Fail(String.Format("IDispatch::Invoke(INVOKE_PROPPUT) returned hr=0x{0:X}", hr)); + + if (pDisp is UnsafeNativeMethods.ISupportErrorInfo) + { + g = typeof(UnsafeNativeMethods.IDispatch).GUID; + if (NativeMethods.Succeeded(((UnsafeNativeMethods.ISupportErrorInfo)pDisp).InterfaceSupportsErrorInfo(ref g))) + { + UnsafeNativeMethods.IErrorInfo pErrorInfo = null; + UnsafeNativeMethods.GetErrorInfo(0, ref pErrorInfo); + string info = null; + if (pErrorInfo != null) + { + if (NativeMethods.Succeeded(pErrorInfo.GetDescription(ref info))) + { + errorInfo = info; + } } + } - - } - } - else if (errorInfo == null) { - StringBuilder strMessage = new StringBuilder(256); - - int result = SafeNativeMethods.FormatMessage(NativeMethods.FORMAT_MESSAGE_FROM_SYSTEM | - NativeMethods.FORMAT_MESSAGE_IGNORE_INSERTS, - NativeMethods.NullHandleRef, - hr, - CultureInfo.CurrentCulture.LCID, - strMessage, - 255, - NativeMethods.NullHandleRef); - - - if (result == 0) { - errorInfo = string.Format(CultureInfo.CurrentCulture, string.Format(SR.DispInvokeFailed, "SetValue", hr)); } - else { - errorInfo = strMessage.ToString(); - // strip of any trailing cr/lf - while (errorInfo.Length > 0 && - errorInfo[errorInfo.Length -1] == '\n' || - errorInfo[errorInfo.Length -1] == '\r') { - errorInfo = errorInfo.Substring(0, errorInfo.Length-1); - } + else if (errorInfo == null) + { + StringBuilder strMessage = new StringBuilder(256); + + int result = SafeNativeMethods.FormatMessage(NativeMethods.FORMAT_MESSAGE_FROM_SYSTEM | + NativeMethods.FORMAT_MESSAGE_IGNORE_INSERTS, + NativeMethods.NullHandleRef, + hr, + CultureInfo.CurrentCulture.LCID, + strMessage, + 255, + NativeMethods.NullHandleRef); + + + if (result == 0) + { + errorInfo = string.Format(CultureInfo.CurrentCulture, string.Format(SR.DispInvokeFailed, "SetValue", hr)); + } + else + { + errorInfo = strMessage.ToString(); + // strip of any trailing cr/lf + while (errorInfo.Length > 0 && + errorInfo[errorInfo.Length - 1] == '\n' || + errorInfo[errorInfo.Length - 1] == '\r') + { + errorInfo = errorInfo.Substring(0, errorInfo.Length - 1); + } + } } - } - throw new ExternalException(errorInfo, hr); + throw new ExternalException(errorInfo, hr); } } - finally { + finally + { SafeNativeMethods.VariantClear(new HandleRef(null, mem)); Marshal.FreeCoTaskMem(mem); } } - finally { + finally + { gcHandle.Free(); } } @@ -1224,7 +1432,8 @@ public override void SetValue(object component, object value) { /// /// If this returns false, a tool should not persist this property's value. /// - public override bool ShouldSerializeValue(object component) { + public override bool ShouldSerializeValue(object component) + { GetBoolValueEvent gbv = new GetBoolValueEvent(false); OnShouldSerializeValue(gbv); return gbv.Value; @@ -1234,46 +1443,56 @@ public override bool ShouldSerializeValue(object component) { /// the GetTextFromValue calls for objects that would like /// to modify the display name /// - private class Com2PropDescMainConverter : Com2ExtendedTypeConverter { + private class Com2PropDescMainConverter : Com2ExtendedTypeConverter + { Com2PropertyDescriptor pd; - + private const int CheckSubprops = 0; private const int AllowSubprops = 1; private const int SupressSubprops = 2; - - + + private int subprops = CheckSubprops; - - public Com2PropDescMainConverter(Com2PropertyDescriptor pd, TypeConverter baseConverter) : base(baseConverter) { - this.pd = pd; + + public Com2PropDescMainConverter(Com2PropertyDescriptor pd, TypeConverter baseConverter) : base(baseConverter) + { + this.pd = pd; } - - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { + + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { object baseConversion = base.ConvertTo(context, culture, value, destinationType); - if (destinationType == typeof(string)) { - // if this is our current value, ask if it should be changed for display, - // otherwise we'll ask for our enum drop downs, which we don't wanna do! - // - if (pd.IsCurrentValue(value)) { - // don't ever do this for enum types - if (!pd.PropertyType.IsEnum) { - Com2EnumConverter baseConverter = (Com2EnumConverter)GetWrappedConverter(typeof(Com2EnumConverter)); - if (baseConverter == null) { + if (destinationType == typeof(string)) + { + // if this is our current value, ask if it should be changed for display, + // otherwise we'll ask for our enum drop downs, which we don't wanna do! + // + if (pd.IsCurrentValue(value)) + { + // don't ever do this for enum types + if (!pd.PropertyType.IsEnum) + { + Com2EnumConverter baseConverter = (Com2EnumConverter)GetWrappedConverter(typeof(Com2EnumConverter)); + if (baseConverter == null) + { return pd.GetDisplayValue((string)baseConversion); - } - else { - return baseConverter.ConvertTo(value, destinationType); - } - } - } - } - return baseConversion; - } - - public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { + } + else + { + return baseConverter.ConvertTo(value, destinationType); + } + } + } + } + return baseConversion; + } + + public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) + { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(value, attributes); - if (props != null && props.Count > 0) { + if (props != null && props.Count > 0) + { // Return sorted read-only collection (can't sort original because its read-only) props = props.Sort(); PropertyDescriptor[] descs = new PropertyDescriptor[props.Count]; @@ -1282,35 +1501,43 @@ public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContex } return props; - } - - public override bool GetPropertiesSupported(ITypeDescriptorContext context) { - if (subprops == CheckSubprops) { - if (!base.GetPropertiesSupported(context)){ + } + + public override bool GetPropertiesSupported(ITypeDescriptorContext context) + { + if (subprops == CheckSubprops) + { + if (!base.GetPropertiesSupported(context)) + { subprops = SupressSubprops; - } - else { + } + else + { // special case the font converter here. // - if ((pd.valueConverter != null && pd.valueConverter.AllowExpand) || Com2IVsPerPropertyBrowsingHandler.AllowChildProperties(this.pd)) { - subprops = AllowSubprops; + if ((pd.valueConverter != null && pd.valueConverter.AllowExpand) || Com2IVsPerPropertyBrowsingHandler.AllowChildProperties(this.pd)) + { + subprops = AllowSubprops; } - } - } - return (subprops == AllowSubprops); + } + } + return (subprops == AllowSubprops); } } } - internal class GetAttributesEvent : EventArgs { + internal class GetAttributesEvent : EventArgs + { private ArrayList attrList; - public GetAttributesEvent(ArrayList attrList) { + public GetAttributesEvent(ArrayList attrList) + { this.attrList = attrList; } - public void Add(Attribute attribute) { + public void Add(Attribute attribute) + { attrList.Add(attribute); } } @@ -1319,26 +1546,33 @@ public void Add(Attribute attribute) { internal delegate void GetAttributesEventHandler(Com2PropertyDescriptor sender, GetAttributesEvent gaevent); - internal class GetNameItemEvent : EventArgs { + internal class GetNameItemEvent : EventArgs + { private object nameItem; - public GetNameItemEvent(object defName) { + public GetNameItemEvent(object defName) + { this.nameItem = defName; } public object Name { - get{ + get + { return nameItem; } - set{ + set + { nameItem = value; } } - public string NameString{ - get{ - if (nameItem != null) { + public string NameString + { + get + { + if (nameItem != null) + { return nameItem.ToString(); } return ""; @@ -1348,18 +1582,23 @@ public string NameString{ internal delegate void GetNameItemEventHandler(Com2PropertyDescriptor sender, GetNameItemEvent gnievent); - internal class GetBoolValueEvent : EventArgs { + internal class GetBoolValueEvent : EventArgs + { private bool value; - public GetBoolValueEvent(bool defValue) { - this.value= defValue; + public GetBoolValueEvent(bool defValue) + { + this.value = defValue; } - public bool Value{ - get{ + public bool Value + { + get + { return value; } - set{ + set + { this.value = value; } } @@ -1367,41 +1606,50 @@ public bool Value{ internal delegate void GetBoolValueEventHandler(Com2PropertyDescriptor sender, GetBoolValueEvent gbeevent); - internal class GetRefreshStateEvent : GetBoolValueEvent { + internal class GetRefreshStateEvent : GetBoolValueEvent + { Com2ShouldRefreshTypes item; - public GetRefreshStateEvent(Com2ShouldRefreshTypes item, bool defValue) : base(defValue) { + public GetRefreshStateEvent(Com2ShouldRefreshTypes item, bool defValue) : base(defValue) + { this.item = item; } } internal delegate void GetTypeConverterAndTypeEditorEventHandler(Com2PropertyDescriptor sender, GetTypeConverterAndTypeEditorEvent e); - - internal class GetTypeConverterAndTypeEditorEvent : EventArgs { + + internal class GetTypeConverterAndTypeEditorEvent : EventArgs + { private TypeConverter typeConverter; private object typeEditor; - public GetTypeConverterAndTypeEditorEvent(TypeConverter typeConverter, object typeEditor) { + public GetTypeConverterAndTypeEditorEvent(TypeConverter typeConverter, object typeEditor) + { this.typeEditor = typeEditor; this.typeConverter = typeConverter; } - - public TypeConverter TypeConverter{ - get{ + + public TypeConverter TypeConverter + { + get + { return typeConverter; } - set{ + set + { typeConverter = value; } } - + public object TypeEditor { - get{ + get + { return typeEditor; } - set{ + set + { typeEditor = value; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptorRefresh.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptorRefresh.cs index e01848f1bf0..c50950b6f94 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptorRefresh.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptorRefresh.cs @@ -2,24 +2,26 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; - - [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] - internal class Com2PropertyDescriptorRefresh{ - public const int Attributes = 0x0001; - public const int DisplayName = 0x0002; - public const int ReadOnly = 0x0004; - public const int TypeConverter = 0x0020; - public const int TypeEditor = 0x0040; - - public const int All = 0x00FF; - - public const int TypeConverterAttr = 0x2000; - public const int TypeEditorAttr = 0x4000; - public const int BaseAttributes = 0x8000; - - } + + [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] + internal class Com2PropertyDescriptorRefresh + { + public const int Attributes = 0x0001; + public const int DisplayName = 0x0002; + public const int ReadOnly = 0x0004; + public const int TypeConverter = 0x0020; + public const int TypeEditor = 0x0040; + + public const int All = 0x00FF; + + public const int TypeConverterAttr = 0x2000; + public const int TypeEditorAttr = 0x4000; + public const int BaseAttributes = 0x8000; + + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyPageUITypeConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyPageUITypeConverter.cs index 3904db8adc1..c9ddea2ad41 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyPageUITypeConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyPageUITypeConverter.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using Microsoft.Win32; using System; @@ -16,12 +17,14 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop { /// /// - internal class Com2PropertyPageUITypeEditor : Com2ExtendedUITypeEditor, ICom2PropertyPageDisplayService { + internal class Com2PropertyPageUITypeEditor : Com2ExtendedUITypeEditor, ICom2PropertyPageDisplayService + { private Com2PropertyDescriptor propDesc; private Guid guid; - public Com2PropertyPageUITypeEditor(Com2PropertyDescriptor pd, Guid guid, UITypeEditor baseEditor) : base(baseEditor){ + public Com2PropertyPageUITypeEditor(Com2PropertyDescriptor pd, Guid guid, UITypeEditor baseEditor) : base(baseEditor) + { propDesc = pd; this.guid = guid; } @@ -33,24 +36,29 @@ public Com2PropertyPageUITypeEditor(Com2PropertyDescriptor pd, Guid guid, UIType /// the user to modify the value. Host assistance in presenting UI to the user /// can be found through the valueAccess.getService function. /// - public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { + public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) + { IntPtr hWndParent = UnsafeNativeMethods.GetFocus(); // Windows.GetForegroundWindow - try { + try + { ICom2PropertyPageDisplayService propPageSvc = (ICom2PropertyPageDisplayService)provider.GetService(typeof(ICom2PropertyPageDisplayService)); - if (propPageSvc == null) { + if (propPageSvc == null) + { propPageSvc = this; } object instance = context.Instance; - if (!instance.GetType().IsArray) { + if (!instance.GetType().IsArray) + { instance = propDesc.TargetObject; - if (instance is ICustomTypeDescriptor) { + if (instance is ICustomTypeDescriptor) + { instance = ((ICustomTypeDescriptor)instance).GetPropertyOwner(propDesc); } } @@ -58,12 +66,15 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide propPageSvc.ShowPropertyPage(propDesc.Name, instance, propDesc.DISPID, this.guid, hWndParent); } - catch (Exception ex1) { - if (provider != null) { - IUIService uiSvc = (IUIService)provider.GetService(typeof(IUIService)); - if (uiSvc != null){ + catch (Exception ex1) + { + if (provider != null) + { + IUIService uiSvc = (IUIService)provider.GetService(typeof(IUIService)); + if (uiSvc != null) + { uiSvc.ShowError(ex1, SR.ErrorTypeConverterFailed); - } + } } } return value; @@ -73,25 +84,30 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide /// Retrieves the editing style of the Edit method. If the method /// is not supported, this will return None. /// - public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { + public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) + { return UITypeEditorEditStyle.Modal; } - public unsafe void ShowPropertyPage(string title, object component, int dispid, Guid pageGuid, IntPtr parentHandle){ - Guid[] guids = new Guid[]{pageGuid}; + public unsafe void ShowPropertyPage(string title, object component, int dispid, Guid pageGuid, IntPtr parentHandle) + { + Guid[] guids = new Guid[] { pageGuid }; IntPtr guidsAddr = Marshal.UnsafeAddrOfPinnedArrayElement(guids, 0); - object[] objs = component.GetType().IsArray ? (object[])component : new object[]{component}; + object[] objs = component.GetType().IsArray ? (object[])component : new object[] { component }; - int nObjs = objs.Length; + int nObjs = objs.Length; IntPtr[] objAddrs = new IntPtr[nObjs]; - try { - for (int i=0; i < nObjs; i++) { + try + { + for (int i = 0; i < nObjs; i++) + { objAddrs[i] = Marshal.GetIUnknownForObject(objs[i]); } - fixed (IntPtr* pAddrs = objAddrs) { + fixed (IntPtr* pAddrs = objAddrs) + { SafeNativeMethods.OleCreatePropertyFrame(new HandleRef(null, parentHandle), 0, 0, title, @@ -100,11 +116,15 @@ public unsafe void ShowPropertyPage(string title, object component, int dispid, 1, new HandleRef(null, guidsAddr), SafeNativeMethods.GetThreadLCID(), - 0, IntPtr.Zero ); + 0, IntPtr.Zero); } - } finally { - for (int i=0; i < nObjs; i++) { - if (objAddrs[i] != IntPtr.Zero) { + } + finally + { + for (int i = 0; i < nObjs; i++) + { + if (objAddrs[i] != IntPtr.Zero) + { Marshal.Release(objAddrs[i]); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ShouldRefreshTypes.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ShouldRefreshTypes.cs index d3f2f2b3c0d..f09acaa05d1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ShouldRefreshTypes.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ShouldRefreshTypes.cs @@ -2,12 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.ComponentModel; using System.Diagnostics; - internal enum Com2ShouldRefreshTypes{ + internal enum Com2ShouldRefreshTypes + { Attributes, DisplayName, ReadOnly, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs index 51fd2162202..08d2506cbae 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; @@ -10,11 +11,11 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop { using System.Windows.Forms; using System.Collections; using Hashtable = System.Collections.Hashtable; - + using System.Reflection.Emit; using System.Reflection; using System.Globalization; - + /// /// This is the main worker class of Com2 property interop. It takes an IDispatch Object @@ -24,36 +25,42 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop { /// This class only knows how to process things that are natively in the typeinfo. Other property /// information such as IPerPropertyBrowsing is handled elsewhere. /// - internal class Com2TypeInfoProcessor { - + internal class Com2TypeInfoProcessor + { + private static TraceSwitch DbgTypeInfoProcessorSwitch = new TraceSwitch("DbgTypeInfoProcessor", "Com2TypeInfoProcessor: debug Com2 type info processing"); - - private Com2TypeInfoProcessor() { + + private Com2TypeInfoProcessor() + { } - + private static ModuleBuilder moduleBuilder = null; - - private static ModuleBuilder ModuleBuilder { - get { - if (moduleBuilder == null) { - AssemblyName assemblyName = new AssemblyName(); - assemblyName.Name = "COM2InteropEmit"; - AssemblyBuilder aBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); - moduleBuilder = aBuilder.DefineDynamicModule("COM2Interop.Emit"); - } - return moduleBuilder; + + private static ModuleBuilder ModuleBuilder + { + get + { + if (moduleBuilder == null) + { + AssemblyName assemblyName = new AssemblyName(); + assemblyName.Name = "COM2InteropEmit"; + AssemblyBuilder aBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); + moduleBuilder = aBuilder.DefineDynamicModule("COM2Interop.Emit"); + } + return moduleBuilder; } } - + private static Hashtable builtEnums; private static Hashtable processedLibraries; - - + + /// /// Given an Object, this attempts to locate its type ifo /// - public static UnsafeNativeMethods.ITypeInfo FindTypeInfo(object obj, bool wantCoClass) { - UnsafeNativeMethods.ITypeInfo pTypeInfo = null; + public static UnsafeNativeMethods.ITypeInfo FindTypeInfo(object obj, bool wantCoClass) + { + UnsafeNativeMethods.ITypeInfo pTypeInfo = null; // this is kind of odd. What's going on here is that // if we want the CoClass (e.g. for the interface name), @@ -66,28 +73,37 @@ public static UnsafeNativeMethods.ITypeInfo FindTypeInfo(object obj, bool wantCo // the CoClass if it's available. // - for (int i = 0; pTypeInfo == null && i < 2; i++) { + for (int i = 0; pTypeInfo == null && i < 2; i++) + { - if (wantCoClass == (i == 0)){ - if (obj is NativeMethods.IProvideClassInfo) { - NativeMethods.IProvideClassInfo pProvideClassInfo = (NativeMethods.IProvideClassInfo)obj; - try { - pTypeInfo = pProvideClassInfo.GetClassInfo(); - } - catch { - } + if (wantCoClass == (i == 0)) + { + if (obj is NativeMethods.IProvideClassInfo) + { + NativeMethods.IProvideClassInfo pProvideClassInfo = (NativeMethods.IProvideClassInfo)obj; + try + { + pTypeInfo = pProvideClassInfo.GetClassInfo(); } - } - else { - if (obj is UnsafeNativeMethods.IDispatch) { - UnsafeNativeMethods.IDispatch iDispatch = (UnsafeNativeMethods.IDispatch)obj; - try { - pTypeInfo = iDispatch.GetTypeInfo(0, SafeNativeMethods.GetThreadLCID()); - } - catch { - } - } - } + catch + { + } + } + } + else + { + if (obj is UnsafeNativeMethods.IDispatch) + { + UnsafeNativeMethods.IDispatch iDispatch = (UnsafeNativeMethods.IDispatch)obj; + try + { + pTypeInfo = iDispatch.GetTypeInfo(0, SafeNativeMethods.GetThreadLCID()); + } + catch + { + } + } + } } return pTypeInfo; @@ -98,82 +114,98 @@ public static UnsafeNativeMethods.ITypeInfo FindTypeInfo(object obj, bool wantCo /// Given an Object, this attempts to locate its type info. If it implementes IProvideMultipleClassInfo /// all available type infos will be returned, otherwise the primary one will be alled. /// - public static UnsafeNativeMethods.ITypeInfo[] FindTypeInfos(object obj, bool wantCoClass){ - + public static UnsafeNativeMethods.ITypeInfo[] FindTypeInfos(object obj, bool wantCoClass) + { + UnsafeNativeMethods.ITypeInfo[] typeInfos = null; int n = 0; UnsafeNativeMethods.ITypeInfo temp = null; - if (obj is NativeMethods.IProvideMultipleClassInfo) { - NativeMethods.IProvideMultipleClassInfo pCI = (NativeMethods.IProvideMultipleClassInfo)obj; - if (!NativeMethods.Succeeded(pCI.GetMultiTypeInfoCount(ref n)) || n == 0) { - n = 0; - } - - if (n > 0){ - typeInfos = new UnsafeNativeMethods.ITypeInfo[n]; - - for (int i = 0; i < n; i++){ - if (NativeMethods.Failed(pCI.GetInfoOfIndex(i, 1 /*MULTICLASSINFO_GETTYPEINFO*/, ref temp, 0, 0, IntPtr.Zero, IntPtr.Zero))){ - continue; - } - Debug.Assert(temp != null, "IProvideMultipleClassInfo::GetInfoOfIndex returned S_OK for ITypeInfo index " + i + ", this is a issue in the object that's being browsed, NOT the property browser."); - typeInfos[i] = temp; - } - } + if (obj is NativeMethods.IProvideMultipleClassInfo) + { + NativeMethods.IProvideMultipleClassInfo pCI = (NativeMethods.IProvideMultipleClassInfo)obj; + if (!NativeMethods.Succeeded(pCI.GetMultiTypeInfoCount(ref n)) || n == 0) + { + n = 0; + } + + if (n > 0) + { + typeInfos = new UnsafeNativeMethods.ITypeInfo[n]; + + for (int i = 0; i < n; i++) + { + if (NativeMethods.Failed(pCI.GetInfoOfIndex(i, 1 /*MULTICLASSINFO_GETTYPEINFO*/, ref temp, 0, 0, IntPtr.Zero, IntPtr.Zero))) + { + continue; + } + Debug.Assert(temp != null, "IProvideMultipleClassInfo::GetInfoOfIndex returned S_OK for ITypeInfo index " + i + ", this is a issue in the object that's being browsed, NOT the property browser."); + typeInfos[i] = temp; + } + } } - if (typeInfos == null || typeInfos.Length == 0){ - temp = FindTypeInfo(obj, wantCoClass); - if (temp != null) { - typeInfos = new UnsafeNativeMethods.ITypeInfo[]{temp}; - } + if (typeInfos == null || typeInfos.Length == 0) + { + temp = FindTypeInfo(obj, wantCoClass); + if (temp != null) + { + typeInfos = new UnsafeNativeMethods.ITypeInfo[] { temp }; + } } return typeInfos; } - + /// /// Retrieve the dispid of the property that we are to use as the name /// member. In this case, the grid will put parens around the name. /// - public static int GetNameDispId(UnsafeNativeMethods.IDispatch obj){ + public static int GetNameDispId(UnsafeNativeMethods.IDispatch obj) + { int dispid = NativeMethods.DISPID_UNKNOWN; string[] names = null; - + ComNativeDescriptor cnd = ComNativeDescriptor.Instance; bool succeeded = false; // first try to find one with a valid value cnd.GetPropertyValue(obj, "__id", ref succeeded); - - if (succeeded) { - names = new string[]{"__id"}; + + if (succeeded) + { + names = new string[] { "__id" }; } - else { - cnd.GetPropertyValue(obj, NativeMethods.ActiveX.DISPID_Name, ref succeeded); - if (succeeded) { - dispid = NativeMethods.ActiveX.DISPID_Name; - } - else { - cnd.GetPropertyValue(obj, "Name", ref succeeded); - if (succeeded) { - names = new string[]{"Name"}; - } - } + else + { + cnd.GetPropertyValue(obj, NativeMethods.ActiveX.DISPID_Name, ref succeeded); + if (succeeded) + { + dispid = NativeMethods.ActiveX.DISPID_Name; + } + else + { + cnd.GetPropertyValue(obj, "Name", ref succeeded); + if (succeeded) + { + names = new string[] { "Name" }; + } + } } - + // now get the dispid of the one that worked... - if (names != null) { - int[] pDispid = new int[]{NativeMethods.DISPID_UNKNOWN}; - Guid g = Guid.Empty; - int hr = obj.GetIDsOfNames(ref g, names, 1, SafeNativeMethods.GetThreadLCID(), pDispid); - if (NativeMethods.Succeeded(hr)){ - - dispid = pDispid[0]; - } + if (names != null) + { + int[] pDispid = new int[] { NativeMethods.DISPID_UNKNOWN }; + Guid g = Guid.Empty; + int hr = obj.GetIDsOfNames(ref g, names, 1, SafeNativeMethods.GetThreadLCID(), pDispid); + if (NativeMethods.Succeeded(hr)) + { + + dispid = pDispid[0]; + } } - + return dispid; } @@ -182,11 +214,13 @@ public static int GetNameDispId(UnsafeNativeMethods.IDispatch obj){ /// Gets the properties for a given Com2 Object. The returned Com2Properties /// Object contains the properties and relevant data about them. /// - public static Com2Properties GetProperties(object obj) { + public static Com2Properties GetProperties(object obj) + { Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "Com2TypeInfoProcessor.GetProperties"); - - if (obj == null || !Marshal.IsComObject(obj)) { + + if (obj == null || !Marshal.IsComObject(obj)) + { Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "Com2TypeInfoProcessor.GetProperties returning null: Object is not a com Object"); return null; } @@ -195,7 +229,8 @@ public static Com2Properties GetProperties(object obj) { // oops, looks like this guy doesn't surface any type info // this is okay, so we just say it has no props - if (typeInfos == null || typeInfos.Length == 0) { + if (typeInfos == null || typeInfos.Length == 0) + { Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "Com2TypeInfoProcessor.GetProperties :: Didn't get typeinfo"); return null; } @@ -206,52 +241,63 @@ public static Com2Properties GetProperties(object obj) { ArrayList propList = new ArrayList(); Guid[] typeGuids = new Guid[typeInfos.Length]; - for (int i = 0; i < typeInfos.Length; i++) { - UnsafeNativeMethods.ITypeInfo ti = typeInfos[i]; + for (int i = 0; i < typeInfos.Length; i++) + { + UnsafeNativeMethods.ITypeInfo ti = typeInfos[i]; - if (ti == null) { - continue; - } + if (ti == null) + { + continue; + } - int[] versions = new int[2]; - Guid typeGuid = GetGuidForTypeInfo(ti, versions); - PropertyDescriptor[] props = null; - bool dontProcess = typeGuid != Guid.Empty && processedLibraries != null && processedLibraries.Contains(typeGuid); + int[] versions = new int[2]; + Guid typeGuid = GetGuidForTypeInfo(ti, versions); + PropertyDescriptor[] props = null; + bool dontProcess = typeGuid != Guid.Empty && processedLibraries != null && processedLibraries.Contains(typeGuid); - if (dontProcess) { + if (dontProcess) + { CachedProperties cp = (CachedProperties)processedLibraries[typeGuid]; - - if (versions[0] == cp.MajorVersion && versions[1] == cp.MinorVersion) { + + if (versions[0] == cp.MajorVersion && versions[1] == cp.MinorVersion) + { props = cp.Properties; - if (i == 0 && cp.DefaultIndex != -1) { + if (i == 0 && cp.DefaultIndex != -1) + { defaultProp = cp.DefaultIndex; } } - else { + else + { dontProcess = false; } - } - - if (!dontProcess) { - props = InternalGetProperties(obj, ti, NativeMethods.MEMBERID_NIL, ref temp); - - // only save the default property from the first type Info - if (i == 0 && temp != -1) { - defaultProp = temp; - } - - if (processedLibraries == null) { + } + + if (!dontProcess) + { + props = InternalGetProperties(obj, ti, NativeMethods.MEMBERID_NIL, ref temp); + + // only save the default property from the first type Info + if (i == 0 && temp != -1) + { + defaultProp = temp; + } + + if (processedLibraries == null) + { processedLibraries = new Hashtable(); - } - - if (typeGuid != Guid.Empty) { + } + + if (typeGuid != Guid.Empty) + { processedLibraries[typeGuid] = new CachedProperties(props, i == 0 ? defaultProp : -1, versions[0], versions[1]); - } - } + } + } - if (props != null){ - propList.AddRange(props); - } + if (props != null) + { + propList.AddRange(props); + } } Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "Com2TypeInfoProcessor.GetProperties : returning " + propList.Count.ToString(CultureInfo.InvariantCulture) + " properties"); @@ -263,23 +309,28 @@ public static Com2Properties GetProperties(object obj) { return new Com2Properties(obj, temp2, defaultProp); } - private static Guid GetGuidForTypeInfo(UnsafeNativeMethods.ITypeInfo typeInfo, int[] versions) { + private static Guid GetGuidForTypeInfo(UnsafeNativeMethods.ITypeInfo typeInfo, int[] versions) + { IntPtr pTypeAttr = IntPtr.Zero; int hr = typeInfo.GetTypeAttr(ref pTypeAttr); - if (!NativeMethods.Succeeded(hr)) { + if (!NativeMethods.Succeeded(hr)) + { throw new ExternalException(string.Format(SR.TYPEINFOPROCESSORGetTypeAttrFailed, hr), hr); } - try { + try + { ref readonly NativeMethods.tagTYPEATTR typeAttr = ref UnsafeNativeMethods.PtrToRef(pTypeAttr); - if (versions != null) { + if (versions != null) + { versions[0] = typeAttr.wMajorVerNum; versions[1] = typeAttr.wMinorVerNum; } return typeAttr.guid; } - finally { + finally + { typeInfo.ReleaseTypeAttr(pTypeAttr); } } @@ -290,126 +341,144 @@ private static Guid GetGuidForTypeInfo(UnsafeNativeMethods.ITypeInfo typeInfo, i /// user defined, which and may be aliased into other type infos. This function /// will recusively walk the ITypeInfos to resolve the type to a clr Type. /// - private static Type GetValueTypeFromTypeDesc(in NativeMethods.tagTYPEDESC typeDesc, UnsafeNativeMethods.ITypeInfo typeInfo, object[] typeData) { + private static Type GetValueTypeFromTypeDesc(in NativeMethods.tagTYPEDESC typeDesc, UnsafeNativeMethods.ITypeInfo typeInfo, object[] typeData) + { IntPtr hreftype; int hr = 0; - switch ((NativeMethods.tagVT)typeDesc.vt) { - default: - return VTToType((NativeMethods.tagVT)typeDesc.vt); - - case NativeMethods.tagVT.VT_UNKNOWN: - case NativeMethods.tagVT.VT_DISPATCH: - // get the guid - typeData[0] = GetGuidForTypeInfo(typeInfo, null); - - // return the type - return VTToType((NativeMethods.tagVT)typeDesc.vt); - - case NativeMethods.tagVT.VT_USERDEFINED: - // we'll need to recurse into a user defined reference typeinfo - Debug.Assert(typeDesc.unionMember != IntPtr.Zero, "typeDesc doesn't contain an hreftype!"); - hreftype = typeDesc.unionMember; - break; - - case NativeMethods.tagVT.VT_PTR: - // we'll need to recurse into a user defined reference typeinfo - Debug.Assert(typeDesc.unionMember != IntPtr.Zero, "typeDesc doesn't contain an refTypeDesc!"); - ref readonly NativeMethods.tagTYPEDESC refTypeDesc = ref UnsafeNativeMethods.PtrToRef(typeDesc.unionMember); - - if (refTypeDesc.vt == (int)NativeMethods.tagVT.VT_VARIANT) { - return VTToType((NativeMethods.tagVT)refTypeDesc.vt); - } + switch ((NativeMethods.tagVT)typeDesc.vt) + { + default: + return VTToType((NativeMethods.tagVT)typeDesc.vt); + + case NativeMethods.tagVT.VT_UNKNOWN: + case NativeMethods.tagVT.VT_DISPATCH: + // get the guid + typeData[0] = GetGuidForTypeInfo(typeInfo, null); + + // return the type + return VTToType((NativeMethods.tagVT)typeDesc.vt); + + case NativeMethods.tagVT.VT_USERDEFINED: + // we'll need to recurse into a user defined reference typeinfo + Debug.Assert(typeDesc.unionMember != IntPtr.Zero, "typeDesc doesn't contain an hreftype!"); + hreftype = typeDesc.unionMember; + break; + + case NativeMethods.tagVT.VT_PTR: + // we'll need to recurse into a user defined reference typeinfo + Debug.Assert(typeDesc.unionMember != IntPtr.Zero, "typeDesc doesn't contain an refTypeDesc!"); + ref readonly NativeMethods.tagTYPEDESC refTypeDesc = ref UnsafeNativeMethods.PtrToRef(typeDesc.unionMember); + + if (refTypeDesc.vt == (int)NativeMethods.tagVT.VT_VARIANT) + { + return VTToType((NativeMethods.tagVT)refTypeDesc.vt); + } - hreftype = refTypeDesc.unionMember; - break; + hreftype = refTypeDesc.unionMember; + break; } // get the reference type info UnsafeNativeMethods.ITypeInfo refTypeInfo = null; hr = typeInfo.GetRefTypeInfo(hreftype, ref refTypeInfo); - if (!NativeMethods.Succeeded(hr)) { + if (!NativeMethods.Succeeded(hr)) + { throw new ExternalException(string.Format(SR.TYPEINFOPROCESSORGetRefTypeInfoFailed, hr), hr); } - try { + try + { // here is where we look at the next level type info. // if we get an enum, process it, otherwise we will recurse // or get a dispatch. // - if (refTypeInfo != null) { + if (refTypeInfo != null) + { IntPtr pRefTypeAttr = IntPtr.Zero; hr = refTypeInfo.GetTypeAttr(ref pRefTypeAttr); - if (!NativeMethods.Succeeded(hr)) { - + if (!NativeMethods.Succeeded(hr)) + { + throw new ExternalException(string.Format(SR.TYPEINFOPROCESSORGetTypeAttrFailed, hr), hr); } - try { + try + { ref readonly NativeMethods.tagTYPEATTR refTypeAttr = ref UnsafeNativeMethods.PtrToRef(pRefTypeAttr); Guid g = refTypeAttr.guid; // save the guid if we've got one here - if (!Guid.Empty.Equals(g)){ + if (!Guid.Empty.Equals(g)) + { typeData[0] = g; } - switch ((NativeMethods.tagTYPEKIND)refTypeAttr.typekind) { + switch ((NativeMethods.tagTYPEKIND)refTypeAttr.typekind) + { case NativeMethods.tagTYPEKIND.TKIND_ENUM: return ProcessTypeInfoEnum(refTypeInfo); - //return VTToType(tagVT.VT_I4); + //return VTToType(tagVT.VT_I4); case NativeMethods.tagTYPEKIND.TKIND_ALIAS: // recurse here return GetValueTypeFromTypeDesc(refTypeAttr.Get_tdescAlias(), refTypeInfo, typeData); case NativeMethods.tagTYPEKIND.TKIND_DISPATCH: return VTToType(NativeMethods.tagVT.VT_DISPATCH); - case NativeMethods.tagTYPEKIND.TKIND_INTERFACE: - case NativeMethods.tagTYPEKIND.TKIND_COCLASS: + case NativeMethods.tagTYPEKIND.TKIND_INTERFACE: + case NativeMethods.tagTYPEKIND.TKIND_COCLASS: return VTToType(NativeMethods.tagVT.VT_UNKNOWN); default: return null; } } - finally { + finally + { refTypeInfo.ReleaseTypeAttr(pRefTypeAttr); } } } - finally { + finally + { refTypeInfo = null; } return null; } - private static PropertyDescriptor[] InternalGetProperties(object obj, UnsafeNativeMethods.ITypeInfo typeInfo, int dispidToGet, ref int defaultIndex) { - - if (typeInfo == null) { + private static PropertyDescriptor[] InternalGetProperties(object obj, UnsafeNativeMethods.ITypeInfo typeInfo, int dispidToGet, ref int defaultIndex) + { + + if (typeInfo == null) + { return null; } - + Hashtable propInfos = new Hashtable(); - + int nameDispID = GetNameDispId((UnsafeNativeMethods.IDispatch)obj); bool addAboutBox = false; - + // properties can live as functions with get_ and put_ or // as variables, so we do two steps here. - try { + try + { // DO FUNCDESC things ProcessFunctions(typeInfo, propInfos, dispidToGet, nameDispID, ref addAboutBox); } - catch (ExternalException ex) { + catch (ExternalException ex) + { Debug.Fail("ProcessFunctions failed with hr=" + ex.ErrorCode.ToString(CultureInfo.InvariantCulture) + ", message=" + ex.ToString()); } - try { + try + { // DO VARDESC things. ProcessVariables(typeInfo, propInfos, dispidToGet, nameDispID); } - catch (ExternalException ex) { + catch (ExternalException ex) + { Debug.Fail("ProcessVariables failed with hr=" + ex.ErrorCode.ToString(CultureInfo.InvariantCulture) + ", message=" + ex.ToString()); } @@ -419,39 +488,46 @@ private static PropertyDescriptor[] InternalGetProperties(object obj, UnsafeNati // now we take the propertyInfo structures we built up // and use them to create the actual descriptors. int cProps = propInfos.Count; - - if (addAboutBox) { - cProps++; + + if (addAboutBox) + { + cProps++; } - + PropertyDescriptor[] props = new PropertyDescriptor[cProps]; int defaultProp = -1; - + int hr = NativeMethods.S_OK; object[] pvar = new object[1]; ComNativeDescriptor cnd = ComNativeDescriptor.Instance; // for each item in uur list, create the descriptor an check // if it's the default one. - foreach (PropInfo pi in propInfos.Values){ - if (!pi.NonBrowsable) { + foreach (PropInfo pi in propInfos.Values) + { + if (!pi.NonBrowsable) + { // finally, for each property, make sure we can get the value // if we can't then we should mark it non-browsable - try { + try + { hr = cnd.GetPropertyValue(obj, pi.DispId, pvar); } - catch (ExternalException ex) { + catch (ExternalException ex) + { hr = ex.ErrorCode; - Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "IDispatch::Invoke(PROPGET, " + pi.Name + ") threw an exception :" + ex.ToString()); + Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "IDispatch::Invoke(PROPGET, " + pi.Name + ") threw an exception :" + ex.ToString()); } - if (!NativeMethods.Succeeded(hr)) { + if (!NativeMethods.Succeeded(hr)) + { Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "Adding Browsable(false) to property '" + pi.Name + "' because Invoke(dispid=0x{0:X} ,DISPATCH_PROPERTYGET) returned hr=0x{1:X}. Properties that do not return S_OK are hidden by default.", pi.DispId, hr)); pi.Attributes.Add(new BrowsableAttribute(false)); pi.NonBrowsable = true; } } - else { + else + { hr = NativeMethods.S_OK; } @@ -459,21 +535,24 @@ private static PropertyDescriptor[] InternalGetProperties(object obj, UnsafeNati pi.Attributes.CopyTo(temp, 0); //Debug.Assert(pi.nonbrowsable || pi.valueType != null, "Browsable property '" + pi.name + "' has a null type"); props[pi.Index] = new Com2PropertyDescriptor(pi.DispId, pi.Name, temp, pi.ReadOnly != PropInfo.ReadOnlyFalse, pi.ValueType, pi.TypeData, !NativeMethods.Succeeded(hr)); - if (pi.IsDefault) { + if (pi.IsDefault) + { defaultProp = pi.Index; } } - - if (addAboutBox) { - props[props.Length-1] = new Com2AboutBoxPropertyDescriptor(); + + if (addAboutBox) + { + props[props.Length - 1] = new Com2AboutBoxPropertyDescriptor(); } return props; } - private static PropInfo ProcessDataCore(UnsafeNativeMethods.ITypeInfo typeInfo, IDictionary propInfoList, int dispid, int nameDispID, in NativeMethods.tagTYPEDESC typeDesc, int flags) { - string pPropName = null; - string pPropDesc = null; + private static PropInfo ProcessDataCore(UnsafeNativeMethods.ITypeInfo typeInfo, IDictionary propInfoList, int dispid, int nameDispID, in NativeMethods.tagTYPEDESC typeDesc, int flags) + { + string pPropName = null; + string pPropDesc = null; // get the name and the helpstring @@ -482,19 +561,22 @@ private static PropInfo ProcessDataCore(UnsafeNativeMethods.ITypeInfo typeInfo, ComNativeDescriptor cnd = ComNativeDescriptor.Instance; - if (!NativeMethods.Succeeded(hr)) { + if (!NativeMethods.Succeeded(hr)) + { throw new COMException(string.Format(SR.TYPEINFOPROCESSORGetDocumentationFailed, dispid, hr, cnd.GetClassName(typeInfo)), hr); } - if (pPropName == null){ - Debug.Fail(string.Format(CultureInfo.CurrentCulture, "ITypeInfo::GetDocumentation didn't return a name for DISPID 0x{0:X} but returned SUCEEDED(hr), Component=" + cnd.GetClassName(typeInfo), dispid)); - return null; + if (pPropName == null) + { + Debug.Fail(string.Format(CultureInfo.CurrentCulture, "ITypeInfo::GetDocumentation didn't return a name for DISPID 0x{0:X} but returned SUCEEDED(hr), Component=" + cnd.GetClassName(typeInfo), dispid)); + return null; } // now we can create our struct... make sure we don't already have one PropInfo pi = (PropInfo)propInfoList[pPropName]; - if (pi == null) { + if (pi == null) + { pi = new PropInfo(); pi.Index = propInfoList.Count; propInfoList[pPropName] = pi; @@ -503,62 +585,74 @@ private static PropInfo ProcessDataCore(UnsafeNativeMethods.ITypeInfo typeInfo, pi.Attributes.Add(new DispIdAttribute(pi.DispId)); } - if (pPropDesc != null) { + if (pPropDesc != null) + { pi.Attributes.Add(new DescriptionAttribute(pPropDesc)); } // figure out the value type - if (pi.ValueType == null) { + if (pi.ValueType == null) + { object[] pTypeData = new object[1]; - try { + try + { pi.ValueType = GetValueTypeFromTypeDesc(in typeDesc, typeInfo, pTypeData); } - catch (Exception ex) { + catch (Exception ex) + { Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "Hiding property " + pi.Name + " because value Type could not be resolved: " + ex.ToString()); } // if we can't resolve the type, mark the property as nonbrowsable // from the browser // - if (pi.ValueType == null) { + if (pi.ValueType == null) + { pi.NonBrowsable = true; } - if (pi.NonBrowsable) { + if (pi.NonBrowsable) + { flags |= (int)NativeMethods.tagVARFLAGS.VARFLAG_FNONBROWSABLE; } - if (pTypeData[0] != null) { + if (pTypeData[0] != null) + { pi.TypeData = pTypeData[0]; } } // check the flags - if ((flags & (int)NativeMethods.tagVARFLAGS.VARFLAG_FREADONLY) != 0) { + if ((flags & (int)NativeMethods.tagVARFLAGS.VARFLAG_FREADONLY) != 0) + { pi.ReadOnly = PropInfo.ReadOnlyTrue; } if ((flags & (int)NativeMethods.tagVARFLAGS.VARFLAG_FHIDDEN) != 0 || (flags & (int)NativeMethods.tagVARFLAGS.VARFLAG_FNONBROWSABLE) != 0 || pi.Name[0] == '_' || - dispid == NativeMethods.ActiveX.DISPID_HWND) { + dispid == NativeMethods.ActiveX.DISPID_HWND) + { pi.Attributes.Add(new BrowsableAttribute(false)); pi.NonBrowsable = true; } - if ((flags & (int)NativeMethods.tagVARFLAGS.VARFLAG_FUIDEFAULT) != 0) { + if ((flags & (int)NativeMethods.tagVARFLAGS.VARFLAG_FUIDEFAULT) != 0) + { pi.IsDefault = true; } if ((flags & (int)NativeMethods.tagVARFLAGS.VARFLAG_FBINDABLE) != 0 && - (flags & (int)NativeMethods.tagVARFLAGS.VARFLAG_FDISPLAYBIND) != 0) { + (flags & (int)NativeMethods.tagVARFLAGS.VARFLAG_FDISPLAYBIND) != 0) + { pi.Attributes.Add(new BindableAttribute(true)); } // lastly, if it's DISPID_Name, add the ParenthesizeNameAttribute - if (dispid == nameDispID){ + if (dispid == nameDispID) + { pi.Attributes.Add(new ParenthesizePropertyNameAttribute(true)); - + // don't allow merges on the name pi.Attributes.Add(new MergablePropertyAttribute(false)); } @@ -566,36 +660,44 @@ private static PropInfo ProcessDataCore(UnsafeNativeMethods.ITypeInfo typeInfo, return pi; } - private static void ProcessFunctions(UnsafeNativeMethods.ITypeInfo typeInfo, IDictionary propInfoList, int dispidToGet, int nameDispID, ref bool addAboutBox) { + private static void ProcessFunctions(UnsafeNativeMethods.ITypeInfo typeInfo, IDictionary propInfoList, int dispidToGet, int nameDispID, ref bool addAboutBox) + { IntPtr pTypeAttr = IntPtr.Zero; int hr = typeInfo.GetTypeAttr(ref pTypeAttr); - if (!NativeMethods.Succeeded(hr) || pTypeAttr == IntPtr.Zero) { + if (!NativeMethods.Succeeded(hr) || pTypeAttr == IntPtr.Zero) + { throw new ExternalException(string.Format(SR.TYPEINFOPROCESSORGetTypeAttrFailed, hr), hr); } - try { + try + { ref readonly NativeMethods.tagTYPEATTR typeAttr = ref UnsafeNativeMethods.PtrToRef(pTypeAttr); - - bool isPropGet; - PropInfo pi; - for (int i = 0; i < typeAttr.cFuncs; i++) { + bool isPropGet; + PropInfo pi; + + for (int i = 0; i < typeAttr.cFuncs; i++) + { IntPtr pFuncDesc = IntPtr.Zero; hr = typeInfo.GetFuncDesc(i, ref pFuncDesc); - if (!NativeMethods.Succeeded(hr) || pFuncDesc == IntPtr.Zero) { + if (!NativeMethods.Succeeded(hr) || pFuncDesc == IntPtr.Zero) + { Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "ProcessTypeInfoEnum: ignoring function item 0x{0:X} because ITypeInfo::GetFuncDesc returned hr=0x{1:X} or NULL", i, hr)); continue; } - try { + try + { ref readonly NativeMethods.tagFUNCDESC funcDesc = ref UnsafeNativeMethods.PtrToRef(pFuncDesc); if (funcDesc.invkind == (int)NativeMethods.tagINVOKEKIND.INVOKE_FUNC || - (dispidToGet != NativeMethods.MEMBERID_NIL && funcDesc.memid != dispidToGet)) { - - if (funcDesc.memid == NativeMethods.ActiveX.DISPID_ABOUTBOX) { - addAboutBox = true; + (dispidToGet != NativeMethods.MEMBERID_NIL && funcDesc.memid != dispidToGet)) + { + + if (funcDesc.memid == NativeMethods.ActiveX.DISPID_ABOUTBOX) + { + addAboutBox = true; } continue; } @@ -605,10 +707,12 @@ private static void ProcessFunctions(UnsafeNativeMethods.ITypeInfo typeInfo, IDi // is this a get or a put? isPropGet = (funcDesc.invkind == (int)NativeMethods.tagINVOKEKIND.INVOKE_PROPERTYGET); - if (isPropGet) { + if (isPropGet) + { + + if (funcDesc.cParams != 0) + { - if (funcDesc.cParams != 0) { - continue; } @@ -617,10 +721,12 @@ private static void ProcessFunctions(UnsafeNativeMethods.ITypeInfo typeInfo, IDi typeDesc = *funcDesc.elemdescFunc.tdesc; } } - else { + else + { Debug.Assert(funcDesc.lprgelemdescParam != IntPtr.Zero, "ELEMDESC param is null!"); - if (funcDesc.lprgelemdescParam == IntPtr.Zero || funcDesc.cParams != 1) { - + if (funcDesc.lprgelemdescParam == IntPtr.Zero || funcDesc.cParams != 1) + { + continue; } @@ -633,16 +739,19 @@ private static void ProcessFunctions(UnsafeNativeMethods.ITypeInfo typeInfo, IDi pi = ProcessDataCore(typeInfo, propInfoList, funcDesc.memid, nameDispID, in typeDesc, funcDesc.wFuncFlags); // if we got a setmethod, it's not readonly - if (pi != null && !isPropGet) { + if (pi != null && !isPropGet) + { pi.ReadOnly = PropInfo.ReadOnlyFalse; } } - finally { + finally + { typeInfo.ReleaseFuncDesc(pFuncDesc); } } } - finally { + finally + { typeInfo.ReleaseTypeAttr(pTypeAttr); } } @@ -651,24 +760,29 @@ private static void ProcessFunctions(UnsafeNativeMethods.ITypeInfo typeInfo, IDi /// This converts a type info that describes a IDL defined enum /// into one we can use /// - private static Type ProcessTypeInfoEnum(UnsafeNativeMethods.ITypeInfo enumTypeInfo) { + private static Type ProcessTypeInfoEnum(UnsafeNativeMethods.ITypeInfo enumTypeInfo) + { Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "ProcessTypeInfoEnum entered"); - if (enumTypeInfo == null) { + if (enumTypeInfo == null) + { Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "ProcessTypeInfoEnum got a NULL enumTypeInfo"); return null; } - try { + try + { IntPtr pTypeAttr = IntPtr.Zero; int hr = enumTypeInfo.GetTypeAttr(ref pTypeAttr); - if (!NativeMethods.Succeeded(hr) || pTypeAttr == IntPtr.Zero) { - throw new ExternalException(string.Format(SR.TYPEINFOPROCESSORGetTypeAttrFailed, hr), hr); + if (!NativeMethods.Succeeded(hr) || pTypeAttr == IntPtr.Zero) + { + throw new ExternalException(string.Format(SR.TYPEINFOPROCESSORGetTypeAttrFailed, hr), hr); } - try { + try + { ref readonly NativeMethods.tagTYPEATTR typeAttr = ref UnsafeNativeMethods.PtrToRef(pTypeAttr); int nItems = typeAttr.cVars; @@ -684,24 +798,28 @@ private static Type ProcessTypeInfoEnum(UnsafeNativeMethods.ITypeInfo enumTypeIn string helpstr = null; enumTypeInfo.GetDocumentation(NativeMethods.MEMBERID_NIL, ref enumName, ref helpstr, null, null); - - // For each item in the enum type info, + + // For each item in the enum type info, // we just need it's name and value, and helpstring if it's there. // - for (int i = 0; i < nItems; i++) { + for (int i = 0; i < nItems; i++) + { IntPtr pVarDesc = IntPtr.Zero; hr = enumTypeInfo.GetVarDesc(i, ref pVarDesc); - if (!NativeMethods.Succeeded(hr) || pVarDesc == IntPtr.Zero) { + if (!NativeMethods.Succeeded(hr) || pVarDesc == IntPtr.Zero) + { Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "ProcessTypeInfoEnum: ignoring item 0x{0:X} because ITypeInfo::GetVarDesc returned hr=0x{1:X} or NULL", hr)); continue; } - try { + try + { ref readonly NativeMethods.tagVARDESC varDesc = ref UnsafeNativeMethods.PtrToRef(pVarDesc); if (varDesc.varkind != (int)NativeMethods.tagVARKIND.VAR_CONST || - varDesc.unionMember == IntPtr.Zero) { + varDesc.unionMember == IntPtr.Zero) + { continue; } @@ -710,10 +828,11 @@ private static Type ProcessTypeInfoEnum(UnsafeNativeMethods.ITypeInfo enumTypeIn // get the name and the helpstring - hr = enumTypeInfo.GetDocumentation(varDesc.memid, ref name, ref helpstr, null, null); + hr = enumTypeInfo.GetDocumentation(varDesc.memid, ref name, ref helpstr, null, null); - if (!NativeMethods.Succeeded(hr)) { + if (!NativeMethods.Succeeded(hr)) + { Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "ProcessTypeInfoEnum: ignoring item 0x{0:X} because ITypeInfo::GetDocumentation returned hr=0x{1:X} or NULL", hr)); continue; } @@ -721,10 +840,12 @@ private static Type ProcessTypeInfoEnum(UnsafeNativeMethods.ITypeInfo enumTypeIn Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "ProcessTypeInfoEnum got name=" + (name == null ? "(null)" : name) + ", helpstring=" + (helpstr == null ? "(null)" : helpstr)); // get the value - try { + try + { varValue = Marshal.GetObjectForNativeVariant(varDesc.unionMember); } - catch (Exception ex) { + catch (Exception ex) + { Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "ProcessTypeInfoEnum: PtrtoStructFailed " + ex.GetType().Name + "," + ex.Message); } @@ -733,18 +854,22 @@ private static Type ProcessTypeInfoEnum(UnsafeNativeMethods.ITypeInfo enumTypeIn // if we have a helpstring, use it, otherwise use name string nameString; - if (helpstr != null) { + if (helpstr != null) + { nameString = helpstr; } - else { + else + { Debug.Assert(name != null, "No name for VARDESC member, but GetDocumentation returned S_OK!"); nameString = name; } Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "ProcessTypeInfoEnum: adding name value=" + nameString); strs.Add(nameString); } - finally { - if (pVarDesc != IntPtr.Zero) { + finally + { + if (pVarDesc != IntPtr.Zero) + { enumTypeInfo.ReleaseVarDesc(pVarDesc); } } @@ -753,197 +878,221 @@ private static Type ProcessTypeInfoEnum(UnsafeNativeMethods.ITypeInfo enumTypeIn Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "ProcessTypeInfoEnum: returning enum with " + strs.Count.ToString(CultureInfo.InvariantCulture) + " items"); // just build our enumerator - if (strs.Count > 0) { - + if (strs.Count > 0) + { + // get the IUnknown value of the ITypeInfo IntPtr pTypeInfoUnk = Marshal.GetIUnknownForObject(enumTypeInfo); - - try { - enumName = pTypeInfoUnk.ToString() + "_" + enumName; - - if (builtEnums == null) { - builtEnums = new Hashtable(); - } - else if (builtEnums.ContainsKey(enumName)) { - return (Type)builtEnums[enumName]; - } - - Type enumType = typeof(int); - - if (vars.Count > 0 && vars[0] != null) { - enumType = vars[0].GetType(); - } - - EnumBuilder enumBuilder = ModuleBuilder.DefineEnum(enumName, TypeAttributes.Public, enumType); - for (int i = 0; i < strs.Count; i++) { - enumBuilder.DefineLiteral((string)strs[i], vars[i]); - } - Type t = enumBuilder.CreateTypeInfo().AsType(); - builtEnums[enumName] = t; - return t; + + try + { + enumName = pTypeInfoUnk.ToString() + "_" + enumName; + + if (builtEnums == null) + { + builtEnums = new Hashtable(); + } + else if (builtEnums.ContainsKey(enumName)) + { + return (Type)builtEnums[enumName]; + } + + Type enumType = typeof(int); + + if (vars.Count > 0 && vars[0] != null) + { + enumType = vars[0].GetType(); + } + + EnumBuilder enumBuilder = ModuleBuilder.DefineEnum(enumName, TypeAttributes.Public, enumType); + for (int i = 0; i < strs.Count; i++) + { + enumBuilder.DefineLiteral((string)strs[i], vars[i]); + } + Type t = enumBuilder.CreateTypeInfo().AsType(); + builtEnums[enumName] = t; + return t; } - finally { - if (pTypeInfoUnk != IntPtr.Zero) { - Marshal.Release(pTypeInfoUnk); - } + finally + { + if (pTypeInfoUnk != IntPtr.Zero) + { + Marshal.Release(pTypeInfoUnk); + } } } } - finally { + finally + { enumTypeInfo.ReleaseTypeAttr(pTypeAttr); } } - catch { + catch + { } return null; } - private static void ProcessVariables(UnsafeNativeMethods.ITypeInfo typeInfo, IDictionary propInfoList, int dispidToGet, int nameDispID) { + private static void ProcessVariables(UnsafeNativeMethods.ITypeInfo typeInfo, IDictionary propInfoList, int dispidToGet, int nameDispID) + { IntPtr pTypeAttr = IntPtr.Zero; int hr = typeInfo.GetTypeAttr(ref pTypeAttr); - if (!NativeMethods.Succeeded(hr) || pTypeAttr == IntPtr.Zero) { + if (!NativeMethods.Succeeded(hr) || pTypeAttr == IntPtr.Zero) + { throw new ExternalException(string.Format(SR.TYPEINFOPROCESSORGetTypeAttrFailed, hr), hr); } - try { + try + { ref readonly NativeMethods.tagTYPEATTR typeAttr = ref UnsafeNativeMethods.PtrToRef(pTypeAttr); - for (int i = 0; i < typeAttr.cVars; i++) { + for (int i = 0; i < typeAttr.cVars; i++) + { IntPtr pVarDesc = IntPtr.Zero; hr = typeInfo.GetVarDesc(i, ref pVarDesc); - if (!NativeMethods.Succeeded(hr) || pVarDesc == IntPtr.Zero) { + if (!NativeMethods.Succeeded(hr) || pVarDesc == IntPtr.Zero) + { Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "ProcessTypeInfoEnum: ignoring variable item 0x{0:X} because ITypeInfo::GetFuncDesc returned hr=0x{1:X} or NULL", hr)); continue; } - try { + try + { ref readonly NativeMethods.tagVARDESC varDesc = ref UnsafeNativeMethods.PtrToRef(pVarDesc); if (varDesc.varkind == (int)NativeMethods.tagVARKIND.VAR_CONST || - (dispidToGet != NativeMethods.MEMBERID_NIL && varDesc.memid != dispidToGet)) { + (dispidToGet != NativeMethods.MEMBERID_NIL && varDesc.memid != dispidToGet)) + { continue; } unsafe { PropInfo pi = ProcessDataCore(typeInfo, propInfoList, varDesc.memid, nameDispID, in *varDesc.elemdescVar.tdesc, varDesc.wVarFlags); - if (pi.ReadOnly != PropInfo.ReadOnlyTrue) { + if (pi.ReadOnly != PropInfo.ReadOnlyTrue) + { pi.ReadOnly = PropInfo.ReadOnlyFalse; } } } - finally { - if (pVarDesc != IntPtr.Zero) { + finally + { + if (pVarDesc != IntPtr.Zero) + { typeInfo.ReleaseVarDesc(pVarDesc); } } } } - finally { + finally + { typeInfo.ReleaseTypeAttr(pTypeAttr); } } - private static Type VTToType(NativeMethods.tagVT vt) { - switch (vt) { - case NativeMethods.tagVT.VT_EMPTY: - case NativeMethods.tagVT.VT_NULL: - return null; - case NativeMethods.tagVT.VT_I1: - return typeof(sbyte); - case NativeMethods.tagVT.VT_UI1: - return typeof(byte); - - case NativeMethods.tagVT.VT_I2: - return typeof(short); - case NativeMethods.tagVT.VT_UI2: - return typeof(ushort); - - - case NativeMethods.tagVT.VT_I4: - case NativeMethods.tagVT.VT_INT: - return typeof(int); - - case NativeMethods.tagVT.VT_UI4: - case NativeMethods.tagVT.VT_UINT: - return typeof(uint); - - case NativeMethods.tagVT.VT_I8: - return typeof(long); - case NativeMethods.tagVT.VT_UI8: - return typeof(ulong); - - case NativeMethods.tagVT.VT_R4: - return typeof(float); - - case NativeMethods.tagVT.VT_R8: - return typeof(double); - - case NativeMethods.tagVT.VT_CY: - return typeof(decimal); - case NativeMethods.tagVT.VT_DATE: - return typeof(DateTime); - case NativeMethods.tagVT.VT_BSTR: - case NativeMethods.tagVT.VT_LPSTR: - case NativeMethods.tagVT.VT_LPWSTR: - return typeof(string); - - case NativeMethods.tagVT.VT_DISPATCH: - return typeof(UnsafeNativeMethods.IDispatch); - case NativeMethods.tagVT.VT_UNKNOWN: - return typeof(object); - - case NativeMethods.tagVT.VT_ERROR: - case NativeMethods.tagVT.VT_HRESULT: - return typeof(int); - - case NativeMethods.tagVT.VT_BOOL: - return typeof(bool); - - case NativeMethods.tagVT.VT_VARIANT: - return typeof(Com2Variant); - case NativeMethods.tagVT.VT_CLSID: - return typeof(Guid); - - case NativeMethods.tagVT.VT_FILETIME: - return typeof(NativeMethods.FILETIME); - - case NativeMethods.tagVT.VT_USERDEFINED: - throw new ArgumentException(string.Format(SR.COM2UnhandledVT, "VT_USERDEFINED")); + private static Type VTToType(NativeMethods.tagVT vt) + { + switch (vt) + { + case NativeMethods.tagVT.VT_EMPTY: + case NativeMethods.tagVT.VT_NULL: + return null; + case NativeMethods.tagVT.VT_I1: + return typeof(sbyte); + case NativeMethods.tagVT.VT_UI1: + return typeof(byte); + + case NativeMethods.tagVT.VT_I2: + return typeof(short); + case NativeMethods.tagVT.VT_UI2: + return typeof(ushort); + + + case NativeMethods.tagVT.VT_I4: + case NativeMethods.tagVT.VT_INT: + return typeof(int); + + case NativeMethods.tagVT.VT_UI4: + case NativeMethods.tagVT.VT_UINT: + return typeof(uint); + + case NativeMethods.tagVT.VT_I8: + return typeof(long); + case NativeMethods.tagVT.VT_UI8: + return typeof(ulong); + + case NativeMethods.tagVT.VT_R4: + return typeof(float); + + case NativeMethods.tagVT.VT_R8: + return typeof(double); + + case NativeMethods.tagVT.VT_CY: + return typeof(decimal); + case NativeMethods.tagVT.VT_DATE: + return typeof(DateTime); + case NativeMethods.tagVT.VT_BSTR: + case NativeMethods.tagVT.VT_LPSTR: + case NativeMethods.tagVT.VT_LPWSTR: + return typeof(string); + + case NativeMethods.tagVT.VT_DISPATCH: + return typeof(UnsafeNativeMethods.IDispatch); + case NativeMethods.tagVT.VT_UNKNOWN: + return typeof(object); + + case NativeMethods.tagVT.VT_ERROR: + case NativeMethods.tagVT.VT_HRESULT: + return typeof(int); + + case NativeMethods.tagVT.VT_BOOL: + return typeof(bool); + + case NativeMethods.tagVT.VT_VARIANT: + return typeof(Com2Variant); + case NativeMethods.tagVT.VT_CLSID: + return typeof(Guid); + + case NativeMethods.tagVT.VT_FILETIME: + return typeof(NativeMethods.FILETIME); + + case NativeMethods.tagVT.VT_USERDEFINED: + throw new ArgumentException(string.Format(SR.COM2UnhandledVT, "VT_USERDEFINED")); /*case VT_ENUM: if (enumNames != null || null != pPropertyInfo.GetEnum()) { return typeof(IEnum); } goto default;*/ - case NativeMethods.tagVT.VT_VOID: - case NativeMethods.tagVT.VT_PTR: - case NativeMethods.tagVT.VT_SAFEARRAY: - case NativeMethods.tagVT.VT_CARRAY: - - case NativeMethods.tagVT.VT_RECORD: - case NativeMethods.tagVT.VT_BLOB: - case NativeMethods.tagVT.VT_STREAM: - case NativeMethods.tagVT.VT_STORAGE: - case NativeMethods.tagVT.VT_STREAMED_OBJECT: - case NativeMethods.tagVT.VT_STORED_OBJECT: - case NativeMethods.tagVT.VT_BLOB_OBJECT: - case NativeMethods.tagVT.VT_CF: - case NativeMethods.tagVT.VT_BSTR_BLOB: - case NativeMethods.tagVT.VT_VECTOR: - case NativeMethods.tagVT.VT_ARRAY: - case NativeMethods.tagVT.VT_BYREF: - case NativeMethods.tagVT.VT_RESERVED: - default: - throw new ArgumentException(string.Format(SR.COM2UnhandledVT, ((int)vt).ToString(CultureInfo.InvariantCulture))); + case NativeMethods.tagVT.VT_VOID: + case NativeMethods.tagVT.VT_PTR: + case NativeMethods.tagVT.VT_SAFEARRAY: + case NativeMethods.tagVT.VT_CARRAY: + + case NativeMethods.tagVT.VT_RECORD: + case NativeMethods.tagVT.VT_BLOB: + case NativeMethods.tagVT.VT_STREAM: + case NativeMethods.tagVT.VT_STORAGE: + case NativeMethods.tagVT.VT_STREAMED_OBJECT: + case NativeMethods.tagVT.VT_STORED_OBJECT: + case NativeMethods.tagVT.VT_BLOB_OBJECT: + case NativeMethods.tagVT.VT_CF: + case NativeMethods.tagVT.VT_BSTR_BLOB: + case NativeMethods.tagVT.VT_VECTOR: + case NativeMethods.tagVT.VT_ARRAY: + case NativeMethods.tagVT.VT_BYREF: + case NativeMethods.tagVT.VT_RESERVED: + default: + throw new ArgumentException(string.Format(SR.COM2UnhandledVT, ((int)vt).ToString(CultureInfo.InvariantCulture))); } } - internal class CachedProperties { + internal class CachedProperties + { private PropertyDescriptor[] props; @@ -951,32 +1100,42 @@ internal class CachedProperties { public readonly int MinorVersion; private int defaultIndex; - internal CachedProperties(PropertyDescriptor[] props, int defIndex, int majVersion, int minVersion) { + internal CachedProperties(PropertyDescriptor[] props, int defIndex, int majVersion, int minVersion) + { this.props = ClonePropertyDescriptors(props); this.MajorVersion = majVersion; this.MinorVersion = minVersion; this.defaultIndex = defIndex; } - public PropertyDescriptor[] Properties { - get { + public PropertyDescriptor[] Properties + { + get + { return ClonePropertyDescriptors(props); } } - public int DefaultIndex { - get { + public int DefaultIndex + { + get + { return defaultIndex; } } - private PropertyDescriptor[] ClonePropertyDescriptors(PropertyDescriptor[] props) { + private PropertyDescriptor[] ClonePropertyDescriptors(PropertyDescriptor[] props) + { PropertyDescriptor[] retProps = new PropertyDescriptor[props.Length]; - for (int i = 0; i < props.Length; i++) { - if (props[i] is ICloneable) { - retProps[i] = (PropertyDescriptor)((ICloneable)props[i]).Clone();; + for (int i = 0; i < props.Length; i++) + { + if (props[i] is ICloneable) + { + retProps[i] = (PropertyDescriptor)((ICloneable)props[i]).Clone(); + ; } - else { + else + { retProps[i] = props[i]; } } @@ -984,70 +1143,83 @@ private PropertyDescriptor[] ClonePropertyDescriptors(PropertyDescriptor[] props } } - private class PropInfo { + private class PropInfo + { - public const int ReadOnlyUnknown = 0; - public const int ReadOnlyTrue = 1; - public const int ReadOnlyFalse = 2; + public const int ReadOnlyUnknown = 0; + public const int ReadOnlyTrue = 1; + public const int ReadOnlyFalse = 2; - string name = null; - int dispid = -1; - Type valueType = null; - readonly ArrayList attributes = new ArrayList(); - int readOnly = ReadOnlyUnknown; - bool isDefault; + string name = null; + int dispid = -1; + Type valueType = null; + readonly ArrayList attributes = new ArrayList(); + int readOnly = ReadOnlyUnknown; + bool isDefault; object typeData; - bool nonbrowsable = false; - int index; + bool nonbrowsable = false; + int index; - public string Name { + public string Name + { get { return name; } set { name = value; } } - public int DispId { + public int DispId + { get { return dispid; } set { dispid = value; } } - public Type ValueType { + public Type ValueType + { get { return valueType; } set { valueType = value; } } - public ArrayList Attributes { + public ArrayList Attributes + { get { return attributes; } } - public int ReadOnly { + public int ReadOnly + { get { return readOnly; } set { readOnly = value; } } - public bool IsDefault { + public bool IsDefault + { get { return isDefault; } set { isDefault = value; } } - public object TypeData { + public object TypeData + { get { return typeData; } set { typeData = value; } } - public bool NonBrowsable { + public bool NonBrowsable + { get { return nonbrowsable; } set { nonbrowsable = value; } } - public int Index{ - get {return index;} - set {index = value;} + public int Index + { + get { return index; } + set { index = value; } } - public override int GetHashCode() { - if (name != null) { + public override int GetHashCode() + { + if (name != null) + { return name.GetHashCode(); } return base.GetHashCode(); } } } - - + + // just so we can recognize a variant properly... - public class Com2Variant { + public class Com2Variant + { } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/ComNativeDescriptor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/ComNativeDescriptor.cs index 0d3fc7efb16..7988368488c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/ComNativeDescriptor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/ComNativeDescriptor.cs @@ -2,15 +2,16 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System; - using System.Collections; - using System.Collections.Generic; + using System.Collections; + using System.Collections.Generic; using System.ComponentModel.Design; using Microsoft.Win32; @@ -18,38 +19,42 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop { /// Top level mapping layer between COM Object and TypeDescriptor. /// /// - internal class ComNativeDescriptor : TypeDescriptionProvider { - + internal class ComNativeDescriptor : TypeDescriptionProvider + { + private static ComNativeDescriptor handler = null; - private AttributeCollection staticAttrs = new AttributeCollection(new Attribute[]{BrowsableAttribute.Yes, DesignTimeVisibleAttribute.No}); + private AttributeCollection staticAttrs = new AttributeCollection(new Attribute[] { BrowsableAttribute.Yes, DesignTimeVisibleAttribute.No }); /// /// Our collection of Object managers (Com2Properties) for native properties /// - private WeakHashtable nativeProps = new WeakHashtable(); - + private WeakHashtable nativeProps = new WeakHashtable(); + /// /// Our collection of browsing handlers, which are stateless and shared across objects. /// - private Hashtable extendedBrowsingHandlers = new Hashtable(); - + private Hashtable extendedBrowsingHandlers = new Hashtable(); + /// /// We increment this every time we look at an Object, at specified /// intervals, we run through the properies list to see if we should /// delete any. /// - private int clearCount = 0; - private const int CLEAR_INTERVAL = 25; + private int clearCount = 0; + private const int CLEAR_INTERVAL = 25; - internal static ComNativeDescriptor Instance { - get { - if (handler == null) { + internal static ComNativeDescriptor Instance + { + get + { + if (handler == null) + { handler = new ComNativeDescriptor(); } return handler; } - } + } [ @@ -57,7 +62,7 @@ internal static ComNativeDescriptor Instance { ] // called via reflection for AutomationExtender stuff. Don't delete! // - public static object GetNativePropertyValue(object component, string propertyName, ref bool succeeded) + public static object GetNativePropertyValue(object component, string propertyName, ref bool succeeded) { return Instance.GetPropertyValue(component, propertyName, ref succeeded); } @@ -81,143 +86,173 @@ public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object return new ComTypeDescriptor(this, instance); } - internal string GetClassName(object component) { + internal string GetClassName(object component) + { string name = null; // does IVsPerPropretyBrowsing supply us a name? - if (component is NativeMethods.IVsPerPropertyBrowsing) { - int hr = ((NativeMethods.IVsPerPropertyBrowsing)component).GetClassName(ref name); - if (NativeMethods.Succeeded(hr) && name != null) { - return name; - } - // otherwise fall through... + if (component is NativeMethods.IVsPerPropertyBrowsing) + { + int hr = ((NativeMethods.IVsPerPropertyBrowsing)component).GetClassName(ref name); + if (NativeMethods.Succeeded(hr) && name != null) + { + return name; + } + // otherwise fall through... } - UnsafeNativeMethods.ITypeInfo pTypeInfo = Com2TypeInfoProcessor.FindTypeInfo(component, true); + UnsafeNativeMethods.ITypeInfo pTypeInfo = Com2TypeInfoProcessor.FindTypeInfo(component, true); - if (pTypeInfo == null) { + if (pTypeInfo == null) + { //Debug.Fail("The current component failed to return an ITypeInfo"); return ""; } - if (pTypeInfo != null) { + if (pTypeInfo != null) + { string desc = null; - try { + try + { pTypeInfo.GetDocumentation(NativeMethods.MEMBERID_NIL, ref name, ref desc, null, null); - + // strip the leading underscores - while (name != null && name.Length > 0 && name[0] == '_') { + while (name != null && name.Length > 0 && name[0] == '_') + { name = name.Substring(1); } return name; } - catch { + catch + { } } return ""; } - - internal TypeConverter GetConverter(object component) { + + internal TypeConverter GetConverter(object component) + { return TypeDescriptor.GetConverter(typeof(IComponent)); } - - internal object GetEditor(object component, Type baseEditorType) { + + internal object GetEditor(object component, Type baseEditorType) + { return TypeDescriptor.GetEditor(component.GetType(), baseEditorType); } - internal string GetName(object component) { + internal string GetName(object component) + { - if (!(component is UnsafeNativeMethods.IDispatch)) { + if (!(component is UnsafeNativeMethods.IDispatch)) + { return ""; } - + int dispid = Com2TypeInfoProcessor.GetNameDispId((UnsafeNativeMethods.IDispatch)component); - if (dispid != NativeMethods.MEMBERID_NIL) { + if (dispid != NativeMethods.MEMBERID_NIL) + { bool success = false; object value = GetPropertyValue(component, dispid, ref success); - - if (success && value != null) { + + if (success && value != null) + { return value.ToString(); } } return ""; } - internal object GetPropertyValue(object component, string propertyName, ref bool succeeded) { + internal object GetPropertyValue(object component, string propertyName, ref bool succeeded) + { - if (!(component is UnsafeNativeMethods.IDispatch)) { + if (!(component is UnsafeNativeMethods.IDispatch)) + { return null; } UnsafeNativeMethods.IDispatch iDispatch = (UnsafeNativeMethods.IDispatch)component; - string[] names = new string[]{propertyName}; + string[] names = new string[] { propertyName }; int[] dispid = new int[1]; dispid[0] = NativeMethods.DISPID_UNKNOWN; Guid g = Guid.Empty; - try { - int hr = iDispatch.GetIDsOfNames(ref g, names, 1, SafeNativeMethods.GetThreadLCID(), dispid); - - if (dispid[0] == NativeMethods.DISPID_UNKNOWN || NativeMethods.Failed(hr)) { - return null; - } + try + { + int hr = iDispatch.GetIDsOfNames(ref g, names, 1, SafeNativeMethods.GetThreadLCID(), dispid); + + if (dispid[0] == NativeMethods.DISPID_UNKNOWN || NativeMethods.Failed(hr)) + { + return null; + } } - catch { - return null; + catch + { + return null; } return GetPropertyValue(component, dispid[0], ref succeeded); } - internal object GetPropertyValue(object component, int dispid, ref bool succeeded) { - if (!(component is UnsafeNativeMethods.IDispatch)) { + internal object GetPropertyValue(object component, int dispid, ref bool succeeded) + { + if (!(component is UnsafeNativeMethods.IDispatch)) + { return null; } object[] pVarResult = new object[1]; - if (GetPropertyValue(component, dispid, pVarResult) == NativeMethods.S_OK) { + if (GetPropertyValue(component, dispid, pVarResult) == NativeMethods.S_OK) + { succeeded = true; return pVarResult[0]; } - else { + else + { succeeded = false; return null; } } - internal int GetPropertyValue(object component, int dispid, object[] retval) { - if (!(component is UnsafeNativeMethods.IDispatch)) { + internal int GetPropertyValue(object component, int dispid, object[] retval) + { + if (!(component is UnsafeNativeMethods.IDispatch)) + { return NativeMethods.E_NOINTERFACE; } UnsafeNativeMethods.IDispatch iDispatch = (UnsafeNativeMethods.IDispatch)component; - try { + try + { Guid g = Guid.Empty; NativeMethods.tagEXCEPINFO pExcepInfo = new NativeMethods.tagEXCEPINFO(); int hr; - try{ + try + { - hr = iDispatch.Invoke(dispid, - ref g, - SafeNativeMethods.GetThreadLCID(), - NativeMethods.DISPATCH_PROPERTYGET, - new NativeMethods.tagDISPPARAMS(), - retval, - pExcepInfo, null); + hr = iDispatch.Invoke(dispid, + ref g, + SafeNativeMethods.GetThreadLCID(), + NativeMethods.DISPATCH_PROPERTYGET, + new NativeMethods.tagDISPPARAMS(), + retval, + pExcepInfo, null); - /*if (hr != NativeMethods.S_OK){ - Com2PropertyDescriptor.PrintExceptionInfo(pExcepInfo); + /*if (hr != NativeMethods.S_OK){ + Com2PropertyDescriptor.PrintExceptionInfo(pExcepInfo); - } */ - if (hr == NativeMethods.DISP_E_EXCEPTION) { - hr = pExcepInfo.scode; - } + } */ + if (hr == NativeMethods.DISP_E_EXCEPTION) + { + hr = pExcepInfo.scode; + } } - catch (ExternalException ex){ + catch (ExternalException ex) + { hr = ex.ErrorCode; } return hr; } - catch { + catch + { //Debug.Fail(e.ToString() + " " + component.GetType().GUID.ToString() + " " + component.ToString()); } return NativeMethods.E_FAIL; @@ -227,8 +262,10 @@ internal int GetPropertyValue(object component, int dispid, object[] retval) { /// Checks if the given dispid matches the dispid that the Object would like to specify /// as its identification proeprty (Name, ID, etc). /// - internal bool IsNameDispId(object obj, int dispid) { - if (obj == null || !obj.GetType().IsCOMObject) { + internal bool IsNameDispId(object obj, int dispid) + { + if (obj == null || !obj.GetType().IsCOMObject) + { return false; } return dispid == Com2TypeInfoProcessor.GetNameDispId((UnsafeNativeMethods.IDispatch)obj); @@ -237,48 +274,57 @@ internal bool IsNameDispId(object obj, int dispid) { /// /// Checks all our property manages to see if any have become invalid. /// - private void CheckClear(object component) { - + private void CheckClear(object component) + { + // walk the list every so many calls - if ((++clearCount % CLEAR_INTERVAL) == 0) { - - lock(nativeProps) { - clearCount = 0; + if ((++clearCount % CLEAR_INTERVAL) == 0) + { + + lock (nativeProps) + { + clearCount = 0; - List disposeList = null; - Com2Properties entry; + List disposeList = null; + Com2Properties entry; - // first walk the list looking for items that need to be - // cleaned out. - // - foreach(DictionaryEntry de in nativeProps) { + // first walk the list looking for items that need to be + // cleaned out. + // + foreach (DictionaryEntry de in nativeProps) + { entry = de.Value as Com2Properties; - if (entry != null && entry.TooOld) { - if (disposeList == null) { + if (entry != null && entry.TooOld) + { + if (disposeList == null) + { disposeList = new List(3); } disposeList.Add(de.Key); } - } - - // now run through the ones that are dead and dispose them. - // there's going to be a very small number of these. - // - if (disposeList != null) { - object oldKey; - for (int i = disposeList.Count - 1; i >= 0; i--) { - oldKey = disposeList[i]; - entry = nativeProps[oldKey] as Com2Properties; - - if (entry != null) { - entry.Disposed -= new EventHandler(OnPropsInfoDisposed); - entry.Dispose(); - nativeProps.Remove(oldKey); - } - } - } + } + + // now run through the ones that are dead and dispose them. + // there's going to be a very small number of these. + // + if (disposeList != null) + { + object oldKey; + for (int i = disposeList.Count - 1; i >= 0; i--) + { + oldKey = disposeList[i]; + entry = nativeProps[oldKey] as Com2Properties; + + if (entry != null) + { + entry.Disposed -= new EventHandler(OnPropsInfoDisposed); + entry.Dispose(); + nativeProps.Remove(oldKey); + } + } + } } } } @@ -286,7 +332,8 @@ private void CheckClear(object component) { /// /// Gets the properties manager for an Object. /// - private Com2Properties GetPropsInfo(object component) { + private Com2Properties GetPropsInfo(object component) + { // check caches if necessary // CheckClear(component); @@ -294,13 +341,15 @@ private Com2Properties GetPropsInfo(object component) { // Get the property info Object // Com2Properties propsInfo = (Com2Properties)nativeProps[component]; - + // if we dont' have one, create one and set it up // - if (propsInfo == null || !propsInfo.CheckValid()) { + if (propsInfo == null || !propsInfo.CheckValid()) + { propsInfo = Com2TypeInfoProcessor.GetProperties(component); - if (propsInfo != null) { - propsInfo.Disposed += new EventHandler(OnPropsInfoDisposed); + if (propsInfo != null) + { + propsInfo.Disposed += new EventHandler(OnPropsInfoDisposed); nativeProps.SetWeak(component, propsInfo); propsInfo.AddExtendedBrowsingHandlers(extendedBrowsingHandlers); } @@ -311,26 +360,32 @@ private Com2Properties GetPropsInfo(object component) { /// /// Got attributes? /// - internal AttributeCollection GetAttributes(object component) { + internal AttributeCollection GetAttributes(object component) + { ArrayList attrs = new ArrayList(); - if (component is NativeMethods.IManagedPerPropertyBrowsing) { + if (component is NativeMethods.IManagedPerPropertyBrowsing) + { object[] temp = Com2IManagedPerPropertyBrowsingHandler.GetComponentAttributes((NativeMethods.IManagedPerPropertyBrowsing)component, NativeMethods.MEMBERID_NIL); - for (int i = 0; i < temp.Length; ++i) { + for (int i = 0; i < temp.Length; ++i) + { attrs.Add(temp[i]); } } - - if (Com2ComponentEditor.NeedsComponentEditor(component)) { + + if (Com2ComponentEditor.NeedsComponentEditor(component)) + { EditorAttribute a = new EditorAttribute(typeof(Com2ComponentEditor), typeof(ComponentEditor)); attrs.Add(a); } - if (attrs == null || attrs.Count == 0) { + if (attrs == null || attrs.Count == 0) + { return staticAttrs; } - else { + else + { Attribute[] temp = new Attribute[attrs.Count]; attrs.CopyTo(temp, 0); return new AttributeCollection(temp); @@ -340,25 +395,30 @@ internal AttributeCollection GetAttributes(object component) { /// /// Default Property, please /// - internal PropertyDescriptor GetDefaultProperty(object component) { + internal PropertyDescriptor GetDefaultProperty(object component) + { CheckClear(component); Com2Properties propsInfo = GetPropsInfo(component); - if (propsInfo != null) { + if (propsInfo != null) + { return propsInfo.DefaultProperty; } return null; } - internal EventDescriptorCollection GetEvents(object component) { + internal EventDescriptorCollection GetEvents(object component) + { return new EventDescriptorCollection(null); } - internal EventDescriptorCollection GetEvents(object component, Attribute[] attributes) { + internal EventDescriptorCollection GetEvents(object component, Attribute[] attributes) + { return new EventDescriptorCollection(null); } - internal EventDescriptor GetDefaultEvent(object component) { + internal EventDescriptor GetDefaultEvent(object component) + { return null; } @@ -366,22 +426,26 @@ internal EventDescriptor GetDefaultEvent(object component) { /// Props! /// [SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters")] - internal PropertyDescriptorCollection GetProperties(object component, Attribute[] attributes) { - + internal PropertyDescriptorCollection GetProperties(object component, Attribute[] attributes) + { + Com2Properties propsInfo = GetPropsInfo(component); - if (propsInfo == null) { + if (propsInfo == null) + { return PropertyDescriptorCollection.Empty; } - try { + try + { propsInfo.AlwaysValid = true; PropertyDescriptor[] props = propsInfo.Properties; - + //Debug.Assert(propDescList.Count > 0, "Didn't add any properties! (propInfos=0)"); return new PropertyDescriptorCollection(props); } - finally { + finally + { propsInfo.AlwaysValid = false; } } @@ -389,40 +453,47 @@ internal PropertyDescriptorCollection GetProperties(object component, Attribute[ /// /// Fired when the property info gets disposed. /// - private void OnPropsInfoDisposed(object sender, EventArgs e) { + private void OnPropsInfoDisposed(object sender, EventArgs e) + { Com2Properties propsInfo = sender as Com2Properties; - if (propsInfo != null) { + if (propsInfo != null) + { propsInfo.Disposed -= new EventHandler(OnPropsInfoDisposed); - lock(nativeProps) { + lock (nativeProps) + { // find the key object key = propsInfo.TargetObject; - if (key == null && nativeProps.ContainsValue(propsInfo)) { + if (key == null && nativeProps.ContainsValue(propsInfo)) + { // need to find it - the target object has probably been cleaned out // of the Com2Properties object already, so we run through the // hashtable looking for the value, so we know what key to remove. // - foreach (DictionaryEntry de in nativeProps) { + foreach (DictionaryEntry de in nativeProps) + { - if (de.Value == propsInfo) { + if (de.Value == propsInfo) + { key = de.Key; - break; + break; } } - if (key == null) { + if (key == null) + { Debug.Fail("Failed to find Com2 properties key on dispose."); return; } } - + nativeProps.Remove(key); - } + } } } @@ -430,19 +501,23 @@ private void OnPropsInfoDisposed(object sender, EventArgs e) { /// Looks at at value's type and creates an editor based on that. We use this to decide which editor to use /// for a generic variant. /// - internal static void ResolveVariantTypeConverterAndTypeEditor(object propertyValue, ref TypeConverter currentConverter, Type editorType, ref object currentEditor) { + internal static void ResolveVariantTypeConverterAndTypeEditor(object propertyValue, ref TypeConverter currentConverter, Type editorType, ref object currentEditor) + { object curValue = propertyValue; - if (curValue != null && curValue != null && !Convert.IsDBNull(curValue)){ - Type t = curValue.GetType(); - TypeConverter subConverter = TypeDescriptor.GetConverter(t); - if (subConverter != null && subConverter.GetType() != typeof(TypeConverter)){ - currentConverter = subConverter; - } + if (curValue != null && curValue != null && !Convert.IsDBNull(curValue)) + { + Type t = curValue.GetType(); + TypeConverter subConverter = TypeDescriptor.GetConverter(t); + if (subConverter != null && subConverter.GetType() != typeof(TypeConverter)) + { + currentConverter = subConverter; + } object subEditor = TypeDescriptor.GetEditor(t, editorType); - if (subEditor != null) { - currentEditor = subEditor; - } + if (subEditor != null) + { + currentEditor = subEditor; + } } } @@ -451,8 +526,8 @@ internal static void ResolveVariantTypeConverterAndTypeEditor(object propertyVal /// private sealed class ComTypeDescriptor : ICustomTypeDescriptor { - private ComNativeDescriptor _handler; - private object _instance; + private ComNativeDescriptor _handler; + private object _instance; /// /// Creates a new WalkingTypeDescriptor. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/Int32CAMarshaler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/Int32CAMarshaler.cs index 9abceb11086..fe51bfda081 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/Int32CAMarshaler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/Int32CAMarshaler.cs @@ -2,19 +2,22 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; using System; - + /// /// This class performs marshaling on a CADWORD struct given /// from native code. /// - internal class Int32CAMarshaler : BaseCAMarshaler { - public Int32CAMarshaler(NativeMethods.CA_STRUCT caStruct) : base(caStruct) { + internal class Int32CAMarshaler : BaseCAMarshaler + { + public Int32CAMarshaler(NativeMethods.CA_STRUCT caStruct) : base(caStruct) + { } @@ -22,13 +25,16 @@ public Int32CAMarshaler(NativeMethods.CA_STRUCT caStruct) : base(caStruct) { /// Returns the type of item this marshaler will /// return in the items array. In this case, the type is int. /// - public override Type ItemType { - get { + public override Type ItemType + { + get + { return typeof(int); } } - protected override Array CreateArray() { + protected override Array CreateArray() + { return new int[Count]; } @@ -36,7 +42,8 @@ protected override Array CreateArray() { /// Override this member to perform marshalling of a single item /// given it's native address. /// - protected override object GetItemFromAddress(IntPtr addr) { + protected override object GetItemFromAddress(IntPtr addr) + { return addr.ToInt32(); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/OleStrCAMarshaler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/OleStrCAMarshaler.cs index dc23c8ff85e..7b4faee57e3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/OleStrCAMarshaler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/OleStrCAMarshaler.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; @@ -13,21 +14,26 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop { /// This class performs marshaling on a CALPOLESTR struct given /// from native code. /// - internal class OleStrCAMarshaler: BaseCAMarshaler { - public OleStrCAMarshaler(NativeMethods.CA_STRUCT caAddr) : base(caAddr) { + internal class OleStrCAMarshaler : BaseCAMarshaler + { + public OleStrCAMarshaler(NativeMethods.CA_STRUCT caAddr) : base(caAddr) + { } /// /// Returns the type of item this marshaler will /// return in the items array. In this case, the type is string. /// - public override Type ItemType { - get { + public override Type ItemType + { + get + { return typeof(string); } } - protected override Array CreateArray() { + protected override Array CreateArray() + { return new string[Count]; } @@ -35,8 +41,9 @@ protected override Array CreateArray() { /// Override this member to perform marshalling of a single item /// given it's native address. /// - protected override object GetItemFromAddress(IntPtr addr) { - string item = Marshal.PtrToStringUni(addr); + protected override object GetItemFromAddress(IntPtr addr) + { + string item = Marshal.PtrToStringUni(addr); // free the memory Marshal.FreeCoTaskMem(addr); return item; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/_CTLBLDTYPE.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/_CTLBLDTYPE.cs index 44da9298a77..1ea80542178 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/_CTLBLDTYPE.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/_CTLBLDTYPE.cs @@ -2,14 +2,16 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.ComponentModel.Com2Interop { +namespace System.Windows.Forms.ComponentModel.Com2Interop +{ using System.ComponentModel; using System.Diagnostics.CodeAnalysis; - + [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] - internal class _CTLBLDTYPE { - public const int CTLBLDTYPE_FSTDPROPBUILDER = 0x00000001; - public const int CTLBLDTYPE_FINTERNALBUILDER = 0x00000002; + internal class _CTLBLDTYPE + { + public const int CTLBLDTYPE_FSTDPROPBUILDER = 0x00000001; + public const int CTLBLDTYPE_FINTERNALBUILDER = 0x00000002; public const int CTLBLDTYPE_FEDITSOBJDIRECTLY = 0x00000004; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs index ddbf4824aca..196a6e1a6a5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Threading; using System.Runtime.InteropServices; using System.Collections.Specialized; @@ -25,7 +26,8 @@ namespace System.Windows.Forms { [ComVisible(true), ClassInterface(ClassInterfaceType.AutoDispatch) ] - public class ContainerControl : ScrollableControl, IContainerControl { + public class ContainerControl : ScrollableControl, IContainerControl + { private Control activeControl; // current active control private Control focusedControl; // Current focused control. Do not directly edit this value. private Control unvalidatedControl; // The last control that requires validation. Do not directly edit this value. @@ -39,23 +41,24 @@ public class ContainerControl : ScrollableControl, IContainerControl { private BitVector32 state = new BitVector32(); private static readonly int stateScalingNeededOnLayout = BitVector32.CreateMask(); // True if we need to perform scaling when layout resumes - private static readonly int stateValidating = BitVector32.CreateMask(stateScalingNeededOnLayout); // Indicates whether we're currently state[stateValidating]. - private static readonly int stateProcessingMnemonic = BitVector32.CreateMask(stateValidating); // Indicates whether we or one of our children is currently processing a mnemonic. - private static readonly int stateScalingChild = BitVector32.CreateMask(stateProcessingMnemonic); // True while we are scaling a child control - private static readonly int stateParentChanged = BitVector32.CreateMask(stateScalingChild); // Flagged when a parent changes so we can adpat our scaling logic to match + private static readonly int stateValidating = BitVector32.CreateMask(stateScalingNeededOnLayout); // Indicates whether we're currently state[stateValidating]. + private static readonly int stateProcessingMnemonic = BitVector32.CreateMask(stateValidating); // Indicates whether we or one of our children is currently processing a mnemonic. + private static readonly int stateScalingChild = BitVector32.CreateMask(stateProcessingMnemonic); // True while we are scaling a child control + private static readonly int stateParentChanged = BitVector32.CreateMask(stateScalingChild); // Flagged when a parent changes so we can adpat our scaling logic to match - private static readonly int PropAxContainer = PropertyStore.CreateKey(); - private const string fontMeasureString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + private static readonly int PropAxContainer = PropertyStore.CreateKey(); + private const string fontMeasureString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; /// /// Initializes a new instance of the /// class. /// - public ContainerControl() : base() { + public ContainerControl() : base() + { SetStyle(ControlStyles.AllPaintingInWmPaint, false); - + // this class overrides GetPreferredSizeCore, let Control automatically cache the result - SetState2(STATE2_USEPREFERREDSIZECACHE, true); + SetState2(STATE2_USEPREFERREDSIZECACHE, true); } /// @@ -71,20 +74,25 @@ public ContainerControl() : base() { [SRCategory(nameof(SR.CatLayout))] [EditorBrowsable(EditorBrowsableState.Advanced)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public SizeF AutoScaleDimensions { - get { + public SizeF AutoScaleDimensions + { + get + { return autoScaleDimensions; } [ SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // value is the name of the param passed in. // So we don't have to localize it. ] - set { - if (value.Width < 0 || value.Height < 0) { + set + { + if (value.Width < 0 || value.Height < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, SR.ContainerControlInvalidAutoScaleDimensions); } autoScaleDimensions = value; - if (!autoScaleDimensions.IsEmpty) { + if (!autoScaleDimensions.IsEmpty) + { LayoutScalingNeeded(); } } @@ -96,14 +104,17 @@ public SizeF AutoScaleDimensions { /// calculated on the fly. Eg: If CurrentAutoScaleDimensions is 192, 192 /// and AutoScaleDimensions is 96, 96 then the AutoScaleFactor is 2.0, 2.0 /// - protected SizeF AutoScaleFactor { - get { + protected SizeF AutoScaleFactor + { + get + { SizeF current = CurrentAutoScaleDimensions; SizeF saved = AutoScaleDimensions; // If no one has configured auto scale dimensions yet, the scaling factor // is unity. - if (saved.IsEmpty) { + if (saved.IsEmpty) + { return new SizeF(1.0F, 1.0F); } @@ -127,25 +138,31 @@ protected SizeF AutoScaleFactor { [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Advanced)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public AutoScaleMode AutoScaleMode { - get { + public AutoScaleMode AutoScaleMode + { + get + { return autoScaleMode; } - set { + set + { //valid values are 0x0 to 0x3 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)AutoScaleMode.None, (int)AutoScaleMode.Inherit)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)AutoScaleMode.None, (int)AutoScaleMode.Inherit)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AutoScaleMode)); } bool scalingNeeded = false; - if (value != autoScaleMode) { - + if (value != autoScaleMode) + { + // Invalidate any current scaling factors. If we // are changing AutoScaleMode to anything other than // its default, we should clear out autoScaleDimensions as it is // nonsensical. - if (autoScaleMode != AutoScaleMode.Inherit) { + if (autoScaleMode != AutoScaleMode.Inherit) + { autoScaleDimensions = SizeF.Empty; } @@ -156,7 +173,8 @@ public AutoScaleMode AutoScaleMode { OnAutoScaleModeChanged(); - if (scalingNeeded) { + if (scalingNeeded) + { LayoutScalingNeeded(); } } @@ -172,28 +190,35 @@ public AutoScaleMode AutoScaleMode { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ContainerControlAutoValidate)), ] - public virtual AutoValidate AutoValidate { - get { - if (autoValidate == AutoValidate.Inherit) { + public virtual AutoValidate AutoValidate + { + get + { + if (autoValidate == AutoValidate.Inherit) + { return GetAutoValidateForControl(this); } - else { + else + { return autoValidate; } } - set { + set + { // PERF/FXCop: dont use Enum.IsDefined. - switch (value) { + switch (value) + { case AutoValidate.Disable: case AutoValidate.EnablePreventFocusChange: case AutoValidate.EnableAllowFocusChange: case AutoValidate.Inherit: break; default: - throw new InvalidEnumArgumentException(nameof(value), (int) value, typeof(AutoValidate)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AutoValidate)); } - if (autoValidate != value) { + if (autoValidate != value) + { autoValidate = value; OnAutoValidateChanged(EventArgs.Empty); } @@ -206,7 +231,8 @@ public virtual AutoValidate AutoValidate { SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ContainerControlOnAutoValidateChangedDescr)), ] - public event EventHandler AutoValidateChanged { + public event EventHandler AutoValidateChanged + { add => this.autoValidateChanged += value; remove => this.autoValidateChanged -= value; } @@ -220,16 +246,20 @@ public event EventHandler AutoValidateChanged { Browsable(false), SRDescription(nameof(SR.ContainerControlBindingContextDescr)) ] - public override BindingContext BindingContext { - get { + public override BindingContext BindingContext + { + get + { BindingContext bm = base.BindingContext; - if (bm == null) { + if (bm == null) + { bm = new BindingContext(); BindingContext = bm; } return bm; } - set { + set + { base.BindingContext = value; } } @@ -237,12 +267,14 @@ public override BindingContext BindingContext { /// /// Container controls support ImeMode only to allow child controls to inherit it from their parents. /// - protected override bool CanEnableIme { - get { + protected override bool CanEnableIme + { + get + { // Note: If overriding this property make sure to copy the Debug code and call this method. Debug.Indent(); - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_CanEnableIme(), value = false" + ", this = " + this ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_CanEnableIme(), value = false" + ", this = " + this); Debug.Unindent(); return false; @@ -258,18 +290,23 @@ protected override bool CanEnableIme { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ContainerControlActiveControlDescr)) ] - public Control ActiveControl { - get { + public Control ActiveControl + { + get + { return activeControl; } - set { + set + { SetActiveControl(value); } } - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ExStyle |= NativeMethods.WS_EX_CONTROLPARENT; return cp; @@ -284,20 +321,26 @@ protected override CreateParams CreateParams { [Browsable(false)] [SRCategory(nameof(SR.CatLayout))] [EditorBrowsable(EditorBrowsableState.Advanced)] - public SizeF CurrentAutoScaleDimensions { - get { - if (currentAutoScaleDimensions.IsEmpty) { - switch (AutoScaleMode) { + public SizeF CurrentAutoScaleDimensions + { + get + { + if (currentAutoScaleDimensions.IsEmpty) + { + switch (AutoScaleMode) + { case AutoScaleMode.Font: currentAutoScaleDimensions = GetFontAutoScaleDimensions(); break; case AutoScaleMode.Dpi: // Screen Dpi - if (DpiHelper.IsPerMonitorV2Awareness) { + if (DpiHelper.IsPerMonitorV2Awareness) + { currentAutoScaleDimensions = new SizeF((float)deviceDpi, (float)deviceDpi); } - else { + else + { // this DPI value comes from the primary monitor. currentAutoScaleDimensions = WindowsGraphicsCacheManager.MeasurementGraphics.DeviceContext.Dpi; } @@ -322,19 +365,26 @@ public SizeF CurrentAutoScaleDimensions { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ContainerControlParentFormDescr)) ] - public Form ParentForm { - get { + public Form ParentForm + { + get + { return ParentFormInternal; } } - internal Form ParentFormInternal { - get { - if (ParentInternal != null) { + internal Form ParentFormInternal + { + get + { + if (ParentInternal != null) + { return ParentInternal.FindForm(); } - else { - if (this is Form) { + else + { + if (this is Form) + { return null; } @@ -347,15 +397,18 @@ internal Form ParentFormInternal { /// /// Activates the specified control. /// - bool IContainerControl.ActivateControl(Control control) { + bool IContainerControl.ActivateControl(Control control) + { return ActivateControlInternal(control, true); } - internal bool ActivateControlInternal(Control control) { + internal bool ActivateControlInternal(Control control) + { return ActivateControlInternal(control, true); } - internal bool ActivateControlInternal(Control control, bool originator) { + internal bool ActivateControlInternal(Control control, bool originator) + { Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "ContainerControl::ActivateControlInternal(" + (control == null ? "null" : control.Name) + "," + originator.ToString() + ") - " + this.Name); // Recursive function that makes sure that the chain of active controls // is coherent. @@ -383,7 +436,8 @@ internal bool ActivateControlInternal(Control control, bool originator) { ret = AssignActiveControlInternal((control == this) ? null : control); } - if (originator) { + if (originator) + { ScrollActiveControlIntoView(); } return ret; @@ -396,7 +450,8 @@ internal bool ActivateControlInternal(Control control, bool originator) { internal bool HasFocusableChild() { Control ctl = null; - do { + do + { ctl = GetNextControl(ctl, true); if (ctl != null && ctl.CanSelect && @@ -411,10 +466,12 @@ internal bool HasFocusableChild() /// /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void AdjustFormScrollbars(bool displayScrollbars) { + protected override void AdjustFormScrollbars(bool displayScrollbars) + { base.AdjustFormScrollbars(displayScrollbars); - if (!GetScrollState(ScrollStateUserHasScrolled)) { + if (!GetScrollState(ScrollStateUserHasScrolled)) + { ScrollActiveControlIntoView(); } } @@ -423,11 +480,13 @@ protected override void AdjustFormScrollbars(bool displayScrollbars) { /// Cleans up form state after a control has been removed. /// Package scope for Control /// - internal virtual void AfterControlRemoved(Control control, Control oldParent) { + internal virtual void AfterControlRemoved(Control control, Control oldParent) + { ContainerControl cc; Debug.Assert(control != null); Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "ContainerControl::AfterControlRemoved(" + control.Name + ") - " + this.Name); - if (control == activeControl || control.Contains(activeControl)) { + if (control == activeControl || control.Contains(activeControl)) + { bool selected = SelectNextControl(control, true, true, true, true); if (selected && this.activeControl != control) @@ -435,8 +494,8 @@ internal virtual void AfterControlRemoved(Control control, Control oldParent) { // Add the check. If it is set to true, do not call into FocusActiveControlInternal(). // The TOP MDI window could be gone and CreateHandle method will fail // because it try to create a parking window Parent for the MDI children - if (!this.activeControl.Parent.IsTopMdiWindowClosing) - { + if (!this.activeControl.Parent.IsTopMdiWindowClosing) + { FocusActiveControlInternal(); } } @@ -465,12 +524,15 @@ internal virtual void AfterControlRemoved(Control control, Control oldParent) { // container potentially, but the unvalidatedControl of all its container parents, up the chain, needs to // now point to the old parent of the disappearing control. cc = this; - while (cc != null) { + while (cc != null) + { Control parent = cc.ParentInternal; - if (parent == null) { + if (parent == null) + { break; } - else { + else + { cc = parent.GetContainerControl() as ContainerControl; } if (cc != null && @@ -481,21 +543,24 @@ internal virtual void AfterControlRemoved(Control control, Control oldParent) { } } - if (control == unvalidatedControl || control.Contains(unvalidatedControl)) { + if (control == unvalidatedControl || control.Contains(unvalidatedControl)) + { unvalidatedControl = null; } } - private bool AssignActiveControlInternal(Control value) { + private bool AssignActiveControlInternal(Control value) + { #if DEBUG if (value == null || (value != null && value.ParentInternal != null && !value.ParentInternal.IsContainerControl)) { Debug.Assert(value == null || (value.ParentInternal != null && this == value.ParentInternal.GetContainerControl())); } #endif - + Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "ContainerControl::AssignActiveControlInternal(" + (value == null ? "null" : value.Name) + ") - " + this.Name); - if (activeControl != value) { + if (activeControl != value) + { // cpb: #7318 #if FALSE if (activeControl != null) { @@ -505,19 +570,24 @@ private bool AssignActiveControlInternal(Control value) { } } #endif - try { - if (value != null) { + try + { + if (value != null) + { value.BecomingActiveControl = true; } activeControl = value; UpdateFocusedControl(); } - finally { - if (value != null) { + finally + { + if (value != null) + { value.BecomingActiveControl = false; } } - if (activeControl == value) { + if (activeControl == value) + { // cpb: #7318 #if FALSE AxHost.Container cont = FindAxContainer(); @@ -532,10 +602,11 @@ private bool AssignActiveControlInternal(Control value) { } } } - else { + else + { focusedControl = activeControl; } - return(activeControl == value); + return (activeControl == value); } /// @@ -543,31 +614,36 @@ private bool AssignActiveControlInternal(Control value) { /// has been created. This should only be called if /// there is an AX container. /// - private void AxContainerFormCreated() { + private void AxContainerFormCreated() + { ((AxHost.AxContainer)Properties.GetObject(PropAxContainer)).FormCreated(); } /// /// Specifies whether this control can process the mnemonic or not. /// - internal override bool CanProcessMnemonic() { + internal override bool CanProcessMnemonic() + { #if DEBUG TraceCanProcessMnemonic(); #endif - if( this.state[stateProcessingMnemonic]){ + if (this.state[stateProcessingMnemonic]) + { return true; } return base.CanProcessMnemonic(); } - internal AxHost.AxContainer CreateAxContainer() { + internal AxHost.AxContainer CreateAxContainer() + { object aXContainer = Properties.GetObject(PropAxContainer); - if (aXContainer == null) { + if (aXContainer == null) + { aXContainer = new AxHost.AxContainer(this); Properties.SetObject(PropAxContainer, aXContainer); } - return(AxHost.AxContainer)aXContainer; + return (AxHost.AxContainer)aXContainer; } /// @@ -575,11 +651,13 @@ internal AxHost.AxContainer CreateAxContainer() { /// the /// . /// - protected override void Dispose(bool disposing) { - if (disposing) { + protected override void Dispose(bool disposing) + { + if (disposing) + { activeControl = null; } - + base.Dispose(disposing); focusedControl = null; @@ -589,9 +667,11 @@ protected override void Dispose(bool disposing) { /// /// Recursively enables required scaling from the given control /// - private void EnableRequiredScaling(Control start, bool enable) { + private void EnableRequiredScaling(Control start, bool enable) + { start.RequiredScalingEnabled = enable; - foreach(Control c in start.Controls) { + foreach (Control c in start.Controls) + { EnableRequiredScaling(c, enable); } } @@ -601,7 +681,8 @@ private void EnableRequiredScaling(Control start, bool enable) { /// focus is given to the form. /// package scope for Form /// - internal void FocusActiveControlInternal() { + internal void FocusActiveControlInternal() + { Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "ContainerControl::FocusActiveControlInternal() - " + this.Name); #if DEBUG // Things really get ugly if you try to pop up an assert dialog here @@ -609,14 +690,17 @@ internal void FocusActiveControlInternal() { Debug.WriteLine("ActiveControl is not a child of this ContainerControl"); #endif - if (activeControl != null && activeControl.Visible) { + if (activeControl != null && activeControl.Visible) + { // Avoid focus loops, especially with ComboBoxes. IntPtr focusHandle = UnsafeNativeMethods.GetFocus(); - if (focusHandle == IntPtr.Zero || Control.FromChildHandle(focusHandle) != activeControl) { + if (focusHandle == IntPtr.Zero || Control.FromChildHandle(focusHandle) != activeControl) + { UnsafeNativeMethods.SetFocus(new HandleRef(activeControl, activeControl.Handle)); } } - else { + else + { // Determine and focus closest visible parent ContainerControl cc = this; while (cc != null && !cc.Visible) @@ -626,7 +710,8 @@ internal void FocusActiveControlInternal() { { cc = parent.GetContainerControl() as ContainerControl; } - else { + else + { break; } } @@ -638,7 +723,8 @@ internal void FocusActiveControlInternal() { } - internal override Size GetPreferredSizeCore(Size proposedSize) { + internal override Size GetPreferredSizeCore(Size proposedSize) + { // Translating 0,0 from ClientSize to actual Size tells us how much space // is required for the borders. Size borderSize = SizeFromClientSize(Size.Empty); @@ -646,8 +732,10 @@ internal override Size GetPreferredSizeCore(Size proposedSize) { return LayoutEngine.GetPreferredSize(this, proposedSize - totalPadding) + totalPadding; } - internal override Rectangle GetToolNativeScreenRectangle() { - if (this.GetTopLevel()) { + internal override Rectangle GetToolNativeScreenRectangle() + { + if (this.GetTopLevel()) + { // Get window's client rectangle (i.e. without chrome) expressed in screen coordinates NativeMethods.RECT clientRectangle = new NativeMethods.RECT(); UnsafeNativeMethods.GetClientRect(new HandleRef(this, this.Handle), ref clientRectangle); @@ -655,7 +743,8 @@ internal override Rectangle GetToolNativeScreenRectangle() { UnsafeNativeMethods.ClientToScreen(new HandleRef(this, this.Handle), topLeftPoint); return new Rectangle(topLeftPoint.x, topLeftPoint.y, clientRectangle.right, clientRectangle.bottom); } - else { + else + { return base.GetToolNativeScreenRectangle(); } } @@ -666,7 +755,7 @@ internal override Rectangle GetToolNativeScreenRectangle() { /// [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] // Refers to 'fontMeasureString'. [SuppressMessage("Microsoft.Usage", "CA2204:LiteralsShouldBeSpelledCorrectly")] - private SizeF GetFontAutoScaleDimensions() + private SizeF GetFontAutoScaleDimensions() { SizeF retval = SizeF.Empty; @@ -674,13 +763,15 @@ private SizeF GetFontAutoScaleDimensions() // memory DC for the monitor the application is currently // on. IntPtr dc = UnsafeNativeMethods.CreateCompatibleDC(NativeMethods.NullHandleRef); - if (dc == IntPtr.Zero) { + if (dc == IntPtr.Zero) + { throw new Win32Exception(); } HandleRef hdc = new HandleRef(this, dc); - try { + try + { // We clone the Windows scaling function here as closely as // possible. They use textmetric for height, and textmetric // for width of fixed width fonts. For variable width fonts @@ -691,28 +782,33 @@ private SizeF GetFontAutoScaleDimensions() HandleRef hfont = new HandleRef(this, FontHandle); HandleRef hfontOld = new HandleRef(this, SafeNativeMethods.SelectObject(hdc, hfont)); - try { + try + { NativeMethods.TEXTMETRIC tm = new NativeMethods.TEXTMETRIC(); SafeNativeMethods.GetTextMetricsW(hdc, ref tm); retval.Height = tm.tmHeight; - if ((tm.tmPitchAndFamily & NativeMethods.TMPF_FIXED_PITCH) != 0) { + if ((tm.tmPitchAndFamily & NativeMethods.TMPF_FIXED_PITCH) != 0) + { IntNativeMethods.SIZE size = new IntNativeMethods.SIZE(); IntUnsafeNativeMethods.GetTextExtentPoint32(hdc, fontMeasureString, size); // Note: intentional integer round off here for Win32 compat //retval.Width = (float)(((size.cx / 26) + 1) / 2); retval.Width = (int)Math.Round(((float)size.cx) / ((float)fontMeasureString.Length)); } - else { + else + { retval.Width = tm.tmAveCharWidth; } } - finally { + finally + { SafeNativeMethods.SelectObject(hdc, hfontOld); } } - finally { + finally + { UnsafeNativeMethods.DeleteCompatibleDC(hdc); } @@ -723,14 +819,16 @@ private SizeF GetFontAutoScaleDimensions() /// This method is called when one of the auto scale properties changes, indicating /// that we should scale controls on the next layout. /// - private void LayoutScalingNeeded() { + private void LayoutScalingNeeded() + { EnableRequiredScaling(this, true); state[stateScalingNeededOnLayout] = true; // If layout is not currently suspended, then perform a layout now, // as otherwise we don't know when one will happen. - if (!IsLayoutSuspended) { + if (!IsLayoutSuspended) + { LayoutTransaction.DoLayout(this, this, PropertyNames.Bounds); } } @@ -740,50 +838,61 @@ private void LayoutScalingNeeded() { /// two models from conflicting. This method is only here for Form to override /// it and update its AutoScale property appropriately. /// - internal virtual void OnAutoScaleModeChanged() { + internal virtual void OnAutoScaleModeChanged() + { } /// /// Raises the AutoValidateChanged event. /// - protected virtual void OnAutoValidateChanged(EventArgs e) { - if (autoValidateChanged != null) { + protected virtual void OnAutoValidateChanged(EventArgs e) + { + if (autoValidateChanged != null) + { autoValidateChanged(this, e); } } - - internal override void OnFrameWindowActivate(bool fActivate) { - if (fActivate) { - if (ActiveControl == null) { + + internal override void OnFrameWindowActivate(bool fActivate) + { + if (fActivate) + { + if (ActiveControl == null) + { SelectNextControl(null, true, true, true, false); } InnerMostActiveContainerControl.FocusActiveControlInternal(); - } - } + } + } /// /// Called when a child is about to resume its layout. The default implementation /// calls OnChildLayoutResuming on the parent. /// - internal override void OnChildLayoutResuming(Control child, bool performLayout) { + internal override void OnChildLayoutResuming(Control child, bool performLayout) + { base.OnChildLayoutResuming(child, performLayout); // do not scale children if AutoScaleMode is set to Dpi - if (AutoScaleMode == AutoScaleMode.Dpi) { + if (AutoScaleMode == AutoScaleMode.Dpi) + { return; } - + // We need to scale children before their layout engines get to them. // We don't have a lot of opportunity for that because the code // generator always generates a PerformLayout() right after a // ResumeLayout(false), so this seems to be the most opportune place // for this. - if (!state[stateScalingChild] && !performLayout && AutoScaleMode != AutoScaleMode.None && AutoScaleMode != AutoScaleMode.Inherit && state[stateScalingNeededOnLayout]) { + if (!state[stateScalingChild] && !performLayout && AutoScaleMode != AutoScaleMode.None && AutoScaleMode != AutoScaleMode.Inherit && state[stateScalingNeededOnLayout]) + { state[stateScalingChild] = true; - try { + try + { child.Scale(AutoScaleFactor, SizeF.Empty, this); } - finally { + finally + { state[stateScalingChild] = false; } } @@ -792,10 +901,12 @@ internal override void OnChildLayoutResuming(Control child, bool performLayout) /// /// Raises the CreateControl event. /// - protected override void OnCreateControl() { + protected override void OnCreateControl() + { base.OnCreateControl(); - if (Properties.GetObject(PropAxContainer) != null) { + if (Properties.GetObject(PropAxContainer) != null) + { AxContainerFormCreated(); } OnBindingContextChanged(EventArgs.Empty); @@ -805,8 +916,10 @@ protected override void OnCreateControl() { /// We override this to clear the current autoscale cache. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnFontChanged(EventArgs e) { - if (AutoScaleMode == AutoScaleMode.Font) { + protected override void OnFontChanged(EventArgs e) + { + if (AutoScaleMode == AutoScaleMode.Font) + { currentAutoScaleDimensions = SizeF.Empty; // If the font changes and we are going to autoscale @@ -816,10 +929,12 @@ protected override void OnFontChanged(EventArgs e) { // work. SuspendAllLayout(this); - try { + try + { PerformAutoScale(!RequiredScalingEnabled, true); } - finally { + finally + { ResumeAllLayout(this, false); } } @@ -830,17 +945,20 @@ protected override void OnFontChanged(EventArgs e) { /// /// This is called by the top level form to clear the current autoscale cache. /// - internal void FormDpiChanged(float factor) { + internal void FormDpiChanged(float factor) + { Debug.Assert(this is Form); currentAutoScaleDimensions = SizeF.Empty; SuspendAllLayout(this); SizeF factorSize = new SizeF(factor, factor); - try { + try + { ScaleChildControls(factorSize, factorSize, this, true); } - finally { + finally + { ResumeAllLayout(this, false); } } @@ -848,7 +966,8 @@ internal void FormDpiChanged(float factor) { /// /// Container controls scale during layout. /// - protected override void OnLayout(LayoutEventArgs e) { + protected override void OnLayout(LayoutEventArgs e) + { PerformNeededAutoScaleOnLayout(); base.OnLayout(e); } @@ -859,7 +978,8 @@ protected override void OnLayout(LayoutEventArgs e) { /// still suspended when this call is made. The default implementation /// calls OnChildLayoutResuming on the parent, if it exists. /// - internal override void OnLayoutResuming(bool performLayout) { + internal override void OnLayoutResuming(bool performLayout) + { PerformNeededAutoScaleOnLayout(); base.OnLayoutResuming(performLayout); } @@ -872,7 +992,8 @@ internal override void OnLayoutResuming(bool performLayout) { /// required scaling is disabled: if it is enabled we are still initializing and /// parent changes are normal. /// - protected override void OnParentChanged(EventArgs e) { + protected override void OnParentChanged(EventArgs e) + { state[stateParentChanged] = !RequiredScalingEnabled; base.OnParentChanged(e); } @@ -882,7 +1003,8 @@ protected override void OnParentChanged(EventArgs e) { /// Those children that are ContainerControls will have their PerformAutoScale method called /// so they can scale their children. /// - public void PerformAutoScale() { + public void PerformAutoScale() + { PerformAutoScale(true, true); } @@ -900,12 +1022,15 @@ public void PerformAutoScale() { /// 1. If AutoScaleDimensions are set, includedBounds is set to true. /// 2. If a font change occurred, excludedBounds is set to true. /// - private void PerformAutoScale(bool includedBounds, bool excludedBounds) { + private void PerformAutoScale(bool includedBounds, bool excludedBounds) + { bool suspended = false; - try { - if (AutoScaleMode != AutoScaleMode.None && AutoScaleMode != AutoScaleMode.Inherit) { + try + { + if (AutoScaleMode != AutoScaleMode.None && AutoScaleMode != AutoScaleMode.Inherit) + { SuspendAllLayout(this); suspended = true; @@ -917,21 +1042,26 @@ private void PerformAutoScale(bool includedBounds, bool excludedBounds) { SizeF included = SizeF.Empty; SizeF excluded = SizeF.Empty; - if (includedBounds) included = AutoScaleFactor; - if (excludedBounds) excluded = AutoScaleFactor; + if (includedBounds) + included = AutoScaleFactor; + if (excludedBounds) + excluded = AutoScaleFactor; Scale(included, excluded, this); autoScaleDimensions = CurrentAutoScaleDimensions; } } - finally { - if (includedBounds) { + finally + { + if (includedBounds) + { state[stateScalingNeededOnLayout] = false; EnableRequiredScaling(this, false); } state[stateParentChanged] = false; - if (suspended) { + if (suspended) + { ResumeAllLayout(this, false); } } @@ -941,8 +1071,10 @@ private void PerformAutoScale(bool includedBounds, bool excludedBounds) { /// Checks to see if we need to perform an autoscale in /// response to a layout. /// - private void PerformNeededAutoScaleOnLayout() { - if (state[stateScalingNeededOnLayout]) { + private void PerformNeededAutoScaleOnLayout() + { + if (state[stateScalingNeededOnLayout]) + { PerformAutoScale(state[stateScalingNeededOnLayout], false); } } @@ -950,14 +1082,16 @@ private void PerformNeededAutoScaleOnLayout() { /// /// Recursively resumes all layout. /// - internal void ResumeAllLayout(Control start, bool performLayout) { + internal void ResumeAllLayout(Control start, bool performLayout) + { ControlCollection controlsCollection = start.Controls; // 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++) { + for (int i = 0; i < controlsCollection.Count; i++) + { ResumeAllLayout(controlsCollection[i], performLayout); } @@ -967,7 +1101,8 @@ internal void ResumeAllLayout(Control start, bool performLayout) { /// /// Recursively suspends all layout. /// - internal void SuspendAllLayout(Control start) { + internal void SuspendAllLayout(Control start) + { start.SuspendLayout(); CommonProperties.xClearPreferredSizeCache(start); @@ -976,7 +1111,8 @@ internal void SuspendAllLayout(Control start) { // 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++) { + for (int i = 0; i < controlsCollection.Count; i++) + { SuspendAllLayout(controlsCollection[i]); } } @@ -987,33 +1123,39 @@ internal void SuspendAllLayout(Control start) { /// according to the container control's AutoScaleFactor. Any changed controls are /// scaled according to the provided scaling factor. /// - internal override void Scale(SizeF includedFactor, SizeF excludedFactor, Control requestingControl) { + internal override void Scale(SizeF includedFactor, SizeF excludedFactor, Control requestingControl) + { // If we're inhieriting our scaling from our parent, Scale is really easy: just do the // base class implementation. - if (AutoScaleMode == AutoScaleMode.Inherit) { + if (AutoScaleMode == AutoScaleMode.Inherit) + { base.Scale(includedFactor, excludedFactor, requestingControl); } - else { + else + { // We scale our controls based on our own auto scaling // factor, not the one provided to us. We only do this for // controls that are not required to be scaled (excluded controls). SizeF ourExcludedFactor = excludedFactor; SizeF childIncludedFactor = includedFactor; - if (!ourExcludedFactor.IsEmpty) { + if (!ourExcludedFactor.IsEmpty) + { ourExcludedFactor = AutoScaleFactor; } // If we're not supposed to be scaling, don't scale the internal // ones either. - if (AutoScaleMode == AutoScaleMode.None) { + if (AutoScaleMode == AutoScaleMode.None) + { childIncludedFactor = AutoScaleFactor; } // When we scale, we are establishing new baselines for the // positions of all controls. Therefore, we should resume(false). - using (new LayoutTransaction(this, this, PropertyNames.Bounds, false)) { + using (new LayoutTransaction(this, this, PropertyNames.Bounds, false)) + { // Our own container control poses a problem. We want // an outer control to be responsible for scaling it, @@ -1022,28 +1164,34 @@ internal override void Scale(SizeF includedFactor, SizeF excludedFactor, Control // scaling occur. SizeF ourExternalContainerFactor = ourExcludedFactor; - if (!excludedFactor.IsEmpty && ParentInternal != null) { + if (!excludedFactor.IsEmpty && ParentInternal != null) + { ourExternalContainerFactor = SizeF.Empty; bool scaleUs = (requestingControl != this || state[stateParentChanged]); // For design time support: we may be parented within another form // that is not part of the designer. - if (!scaleUs) { + if (!scaleUs) + { bool dt = false; bool parentDt = false; ISite site = Site; ISite parentSite = ParentInternal.Site; - if (site != null) dt = site.DesignMode; - if (parentSite != null) parentDt = parentSite.DesignMode; + if (site != null) + dt = site.DesignMode; + if (parentSite != null) + parentDt = parentSite.DesignMode; - if (dt && !parentDt) { + if (dt && !parentDt) + { scaleUs = true; } } - if (scaleUs) { + if (scaleUs) + { ourExternalContainerFactor = excludedFactor; } } @@ -1058,9 +1206,11 @@ internal override void Scale(SizeF includedFactor, SizeF excludedFactor, Control /// Process an arrowKey press by selecting the next control in the group /// that the activeControl belongs to. /// - private bool ProcessArrowKey(bool forward) { + private bool ProcessArrowKey(bool forward) + { Control group = this; - if (activeControl != null) { + if (activeControl != null) + { group = activeControl.ParentInternal; } return group.SelectNextControl(activeControl, forward, false, false, true); @@ -1074,14 +1224,16 @@ private bool ProcessArrowKey(bool forward) { /// called. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override bool ProcessDialogChar(char charCode) { + protected override bool ProcessDialogChar(char charCode) + { #if DEBUG Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "ContainerControl.ProcessDialogChar [" + charCode.ToString() + "]"); #endif // If we're the top-level form or control, we need to do the mnemonic handling // ContainerControl parent = GetContainerControl() as ContainerControl; - if (parent != null && charCode != ' ' && ProcessMnemonic(charCode)) return true; + if (parent != null && charCode != ' ' && ProcessMnemonic(charCode)) + return true; return base.ProcessDialogChar(charCode); } @@ -1094,22 +1246,27 @@ protected override bool ProcessDialogChar(char charCode) { /// on the form. For the arrow keys, /// !!! /// - protected override bool ProcessDialogKey(Keys keyData) { + protected override bool ProcessDialogKey(Keys keyData) + { #if DEBUG Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "ContainerControl.ProcessDialogKey [" + keyData.ToString() + "]"); #endif - if ((keyData & (Keys.Alt | Keys.Control)) == Keys.None) { + if ((keyData & (Keys.Alt | Keys.Control)) == Keys.None) + { Keys keyCode = (Keys)keyData & Keys.KeyCode; - switch (keyCode) { + switch (keyCode) + { case Keys.Tab: - if (ProcessTabKey((keyData & Keys.Shift) == Keys.None)) return true; + if (ProcessTabKey((keyData & Keys.Shift) == Keys.None)) + return true; break; case Keys.Left: case Keys.Right: case Keys.Up: case Keys.Down: if (ProcessArrowKey(keyCode == Keys.Right || - keyCode == Keys.Down)) return true; + keyCode == Keys.Down)) + return true; break; } } @@ -1117,13 +1274,16 @@ protected override bool ProcessDialogKey(Keys keyData) { } - protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "ContainerControl.ProcessCmdKey " + msg.ToString()); - if (base.ProcessCmdKey(ref msg, keyData)) { - return true; + if (base.ProcessCmdKey(ref msg, keyData)) + { + return true; } - if (ParentInternal == null) { + if (ParentInternal == null) + { // unfortunately, we have to stick this here for the case where we're hosted without // a form in the chain. This would be something like a context menu strip with shortcuts // hosted within Office, VS or IE. @@ -1135,17 +1295,20 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { return false; } - protected internal override bool ProcessMnemonic(char charCode) { + protected internal override bool ProcessMnemonic(char charCode) + { #if DEBUG Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "ContainerControl.ProcessMnemonic [" + charCode.ToString() + "]"); Debug.Indent(); Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "this == " + ToString()); #endif - if( !CanProcessMnemonic() ){ + if (!CanProcessMnemonic()) + { return false; } - if (Controls.Count == 0) { + if (Controls.Count == 0) + { Debug.Unindent(); return false; } @@ -1164,34 +1327,39 @@ protected internal override bool ProcessMnemonic(char charCode) { bool processed = false; - try { + try + { // safety flag to avoid infinite loop when testing controls in a container. bool wrapped = false; Control ctl = start; Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "Check starting at '" + ((start != null) ? start.ToString() : "") + "'"); - do { + do + { // Loop through the controls starting at the control next to the current Active control in the Tab order // till we find someone willing to process this mnemonic. // We don't start the search on the Active control to allow controls in the same container with the same // mnemonic (bad UI design but supported) to be processed sequentially #if DEBUG - count++; - if (count > 9999) { - Debug.Fail("Infinite loop trying to find controls which can ProcessMnemonic()!!!"); - } + count++; + if (count > 9999) + { + Debug.Fail("Infinite loop trying to find controls which can ProcessMnemonic()!!!"); + } #endif //DEBUG ctl = GetNextControl(ctl, true); - if ( ctl != null ) { + if (ctl != null) + { #if DEBUG Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, " ...checking for mnemonics on " + ctl.ToString()); // Control.TraceMnemonicProcessing.Enabled disables CanProcessMnemonic consistency check. bool canProcess = Control.TraceMnemonicProcessing.Enabled ? true : ctl.CanProcessMnemonic(); // Processing the mnemonic can change the value of CanProcessMnemonic. #endif // Processing the mnemonic can change the value of CanProcessMnemonic. - if (ctl.ProcessMnemonic(charCode)) { + if (ctl.ProcessMnemonic(charCode)) + { #if DEBUG Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, " ...mnemonics found"); Debug.Assert((Control.TraceMnemonicProcessing.Enabled || canProcess), "ProcessMnemonic returned true, even though CanProcessMnemonic() is false. Someone probably overrode ProcessMnemonic and forgot to test CanSelect or CanProcessMnemonic()."); @@ -1201,8 +1369,10 @@ protected internal override bool ProcessMnemonic(char charCode) { break; } } - else { // ctl is null - if( wrapped ){ + else + { // ctl is null + if (wrapped) + { break; // This avoids infinite loops } @@ -1210,7 +1380,8 @@ protected internal override bool ProcessMnemonic(char charCode) { } } while (ctl != start); } - finally { + finally + { this.state[stateProcessingMnemonic] = false; } @@ -1221,28 +1392,36 @@ protected internal override bool ProcessMnemonic(char charCode) { /// /// Selects the next available control and makes it the active control. /// - protected virtual bool ProcessTabKey(bool forward) { - if (SelectNextControl(activeControl, forward, true, true, false)) return true; + protected virtual bool ProcessTabKey(bool forward) + { + if (SelectNextControl(activeControl, forward, true, true, false)) + return true; return false; } - private ScrollableControl FindScrollableParent(Control ctl) { + private ScrollableControl FindScrollableParent(Control ctl) + { Control current = ctl.ParentInternal; - while (current != null && !(current is ScrollableControl)) { + while (current != null && !(current is ScrollableControl)) + { current = current.ParentInternal; } - if (current != null) { - return(ScrollableControl)current; + if (current != null) + { + return (ScrollableControl)current; } return null; } - private void ScrollActiveControlIntoView() { + private void ScrollActiveControlIntoView() + { Control last = activeControl; - if (last != null) { + if (last != null) + { ScrollableControl scrollParent = FindScrollableParent(last); - while (scrollParent != null) { + while (scrollParent != null) + { scrollParent.ScrollControlIntoView(activeControl); last = scrollParent; scrollParent = FindScrollableParent(scrollParent); @@ -1250,7 +1429,8 @@ private void ScrollActiveControlIntoView() { } } - protected override void Select(bool directed, bool forward) { + protected override void Select(bool directed, bool forward) + { bool correctParentActiveControl = true; if (ParentInternal != null) { @@ -1270,11 +1450,14 @@ protected override void Select(bool directed, bool forward) { /// /// Implements ActiveControl property setter. /// - internal void SetActiveControl(Control value) { + internal void SetActiveControl(Control value) + { Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "ContainerControl::SetActiveControl(" + (value == null ? "null" : value.Name) + ") - " + Name); - if (activeControl != value || (value != null && !value.Focused)) { - if (value != null && !Contains(value)) { + if (activeControl != value || (value != null && !value.Focused)) + { + if (value != null && !Contains(value)) + { throw new ArgumentException(SR.CannotActivateControl, nameof(value)); } @@ -1324,7 +1507,7 @@ internal ContainerControl InnerMostActiveContainerControl ContainerControl ret = this; while (ret.ActiveControl is ContainerControl) { - ret = (ContainerControl) ret.ActiveControl; + ret = (ContainerControl)ret.ActiveControl; } return ret; } @@ -1337,7 +1520,7 @@ internal ContainerControl InnerMostFocusedContainerControl ContainerControl ret = this; while (ret.focusedControl is ContainerControl) { - ret = (ContainerControl) ret.focusedControl; + ret = (ContainerControl)ret.focusedControl; } return ret; } @@ -1347,7 +1530,8 @@ internal ContainerControl InnerMostFocusedContainerControl /// Updates the default button based on current selection, and the /// acceptButton property. /// - protected virtual void UpdateDefaultButton() { + protected virtual void UpdateDefaultButton() + { // hook for form } @@ -1356,18 +1540,22 @@ protected virtual void UpdateDefaultButton() { /// activeControl variable, firing enter and leave events and validation /// as necessary. /// - internal void UpdateFocusedControl() { + internal void UpdateFocusedControl() + { Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "ContainerControl::UpdateFocusedControl() - " + this.Name); // Capture the current focusedControl as the unvalidatedControl if we don't have one/are not validating. EnsureUnvalidatedControl(focusedControl); Control pathControl = focusedControl; - while (activeControl != pathControl) { - if (pathControl == null || pathControl.IsDescendant(activeControl)) { + while (activeControl != pathControl) + { + if (pathControl == null || pathControl.IsDescendant(activeControl)) + { // heading down. find next control on path. Control nextControlDown = activeControl; - while (true) { + while (true) + { Control parent = nextControlDown.ParentInternal; if (parent == this || parent == pathControl) break; @@ -1377,25 +1565,31 @@ internal void UpdateFocusedControl() { Control priorFocusedControl = focusedControl = pathControl; EnterValidation(nextControlDown); // If validation changed position, then jump back to the loop. - if (focusedControl != priorFocusedControl) { + if (focusedControl != priorFocusedControl) + { pathControl = focusedControl; continue; } pathControl = nextControlDown; - if (NativeWindow.WndProcShouldBeDebuggable) { + if (NativeWindow.WndProcShouldBeDebuggable) + { pathControl.NotifyEnter(); } - else { - try { + else + { + try + { pathControl.NotifyEnter(); } - catch (Exception e) { + catch (Exception e) + { Application.OnThreadException(e); } } } - else { + else + { // heading up. ContainerControl innerMostFCC = InnerMostFocusedContainerControl; Control stopControl = null; @@ -1447,14 +1641,18 @@ internal void UpdateFocusedControl() { if (leaveControl != null) { - if (NativeWindow.WndProcShouldBeDebuggable) { + if (NativeWindow.WndProcShouldBeDebuggable) + { leaveControl.NotifyLeave(); } - else { - try { + else + { + try + { leaveControl.NotifyLeave(); } - catch (Exception e) { + catch (Exception e) + { Application.OnThreadException(e); } } @@ -1473,7 +1671,8 @@ internal void UpdateFocusedControl() { } #endif focusedControl = activeControl; - if (activeControl != null) { + if (activeControl != null) + { EnterValidation(activeControl); } } @@ -1481,24 +1680,29 @@ internal void UpdateFocusedControl() { /// /// Make sure we have a valid choice of last unvalidated control if at all possible. /// - private void EnsureUnvalidatedControl(Control candidate) { + private void EnsureUnvalidatedControl(Control candidate) + { // Don't change the unvalidated control while in the middle of validation (re-entrancy) - if (state[stateValidating]) { + if (state[stateValidating]) + { return; } // Don't change the existing unvalidated control - if (unvalidatedControl != null) { + if (unvalidatedControl != null) + { return; } // No new choice of unvalidated control was specified - leave unvalidated control blank - if (candidate == null) { + if (candidate == null) + { return; } // Specified control has auto-validation disabled - leave unvalidated control blank - if (!candidate.ShouldAutoValidate) { + if (!candidate.ShouldAutoValidate) + { return; } @@ -1508,16 +1712,20 @@ private void EnsureUnvalidatedControl(Control candidate) { // In the case of nested container controls, try to pick the deepest possible unvalidated // control. For a container with no unvalidated control, use the active control instead. // Stop as soon as we encounter any control that has auto-validation turned off. - while (unvalidatedControl is ContainerControl) { + while (unvalidatedControl is ContainerControl) + { ContainerControl container = unvalidatedControl as ContainerControl; - if (container.unvalidatedControl != null && container.unvalidatedControl.ShouldAutoValidate) { + if (container.unvalidatedControl != null && container.unvalidatedControl.ShouldAutoValidate) + { unvalidatedControl = container.unvalidatedControl; } - else if (container.activeControl != null && container.activeControl.ShouldAutoValidate) { + else if (container.activeControl != null && container.activeControl.ShouldAutoValidate) + { unvalidatedControl = container.activeControl; } - else { + else + { break; } } @@ -1527,14 +1735,17 @@ private void EnsureUnvalidatedControl(Control candidate) { /// Validates the last unvalidated control and its ancestors (up through the ancestor in common /// with enterControl) if enterControl causes validation. /// - private void EnterValidation(Control enterControl) { + private void EnterValidation(Control enterControl) + { // No unvalidated control to validate - stop now - if (unvalidatedControl == null) { + if (unvalidatedControl == null) + { return; } // Entered control does not trigger validation - stop now - if (!enterControl.CausesValidation) { + if (!enterControl.CausesValidation) + { return; } @@ -1542,13 +1753,15 @@ private void EnterValidation(Control enterControl) { AutoValidate autoValidateMode = Control.GetAutoValidateForControl(unvalidatedControl); // Auto-validate has been turned off in container of unvalidated control - stop now - if (autoValidateMode == AutoValidate.Disable) { + if (autoValidateMode == AutoValidate.Disable) + { return; } // Find common ancestor of entered control and unvalidated control Control commonAncestor = enterControl; - while (commonAncestor != null && !commonAncestor.IsDescendant(unvalidatedControl)) { + while (commonAncestor != null && !commonAncestor.IsDescendant(unvalidatedControl)) + { commonAncestor = commonAncestor.ParentInternal; } @@ -1573,7 +1786,8 @@ private void EnterValidation(Control enterControl) { // Validate(true) rather than Validate(), so that you will be sensitive to the current auto-validation setting. // ------------------------------- // - public bool Validate() { + public bool Validate() + { return Validate(false); } @@ -1585,24 +1799,31 @@ public bool Validate() { /// determined by the control's parent, is AutoValidate.Disable. /// /// - public bool Validate(bool checkAutoValidate) { + public bool Validate(bool checkAutoValidate) + { bool validatedControlAllowsFocusChange; return ValidateInternal(checkAutoValidate, out validatedControlAllowsFocusChange); } - internal bool ValidateInternal(bool checkAutoValidate, out bool validatedControlAllowsFocusChange) { + internal bool ValidateInternal(bool checkAutoValidate, out bool validatedControlAllowsFocusChange) + { validatedControlAllowsFocusChange = false; if (this.AutoValidate == AutoValidate.EnablePreventFocusChange || - (activeControl != null && activeControl.CausesValidation)) { - if (unvalidatedControl == null) { - if (focusedControl is ContainerControl && focusedControl.CausesValidation) { + (activeControl != null && activeControl.CausesValidation)) + { + if (unvalidatedControl == null) + { + if (focusedControl is ContainerControl && focusedControl.CausesValidation) + { ContainerControl c = (ContainerControl)focusedControl; - if( !c.ValidateInternal(checkAutoValidate, out validatedControlAllowsFocusChange) ){ + if (!c.ValidateInternal(checkAutoValidate, out validatedControlAllowsFocusChange)) + { return false; } } - else { + else + { unvalidatedControl = focusedControl; } } @@ -1637,7 +1858,8 @@ internal bool ValidateInternal(bool checkAutoValidate, out bool validatedControl /// for details of exactly which child controls will be validated. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public virtual bool ValidateChildren() { + public virtual bool ValidateChildren() + { return ValidateChildren(ValidationConstraints.Selectable); } @@ -1646,18 +1868,20 @@ public virtual bool ValidateChildren() { /// validated and which controls are skipped is determined by . /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public virtual bool ValidateChildren(ValidationConstraints validationConstraints) { + public virtual bool ValidateChildren(ValidationConstraints validationConstraints) + { // validationConstraints must be a combination of // None = 0x00, Selectable = 0x01, Enabled = 0x02, Visible = 0x04, TabStop = 0x08, ImmediateChildren = 0x10 // Not using ClientUtils.IsValidEnum here because this is a flags enum and everything is valid between 0x00 and 0x1F. if ((int)validationConstraints < 0x00 || (int)validationConstraints > 0x1F) { - throw new InvalidEnumArgumentException(nameof(validationConstraints), (int)validationConstraints, typeof(ValidationConstraints)); + throw new InvalidEnumArgumentException(nameof(validationConstraints), (int)validationConstraints, typeof(ValidationConstraints)); } return !PerformContainerValidation(validationConstraints); } - - private bool ValidateThroughAncestor(Control ancestorControl, bool preventFocusChangeOnError) { + + private bool ValidateThroughAncestor(Control ancestorControl, bool preventFocusChangeOnError) + { if (ancestorControl == null) ancestorControl = this; if (state[stateValidating]) @@ -1673,35 +1897,43 @@ private bool ValidateThroughAncestor(Control ancestorControl, bool preventFocusC this.state[stateValidating] = true; bool cancel = false; - + Control currentActiveControl = activeControl; Control currentValidatingControl = unvalidatedControl; - if (currentActiveControl != null) { + if (currentActiveControl != null) + { currentActiveControl.ValidationCancelled = false; - if (currentActiveControl is ContainerControl) { + if (currentActiveControl is ContainerControl) + { ContainerControl currentActiveContainerControl = currentActiveControl as ContainerControl; currentActiveContainerControl.ResetValidationFlag(); } } - try { - while (currentValidatingControl != null && currentValidatingControl != ancestorControl) { - try { + try + { + while (currentValidatingControl != null && currentValidatingControl != ancestorControl) + { + try + { cancel = currentValidatingControl.PerformControlValidation(false); } - catch { + catch + { cancel = true; throw; } - if (cancel) { + if (cancel) + { break; } currentValidatingControl = currentValidatingControl.ParentInternal; } - if (cancel && preventFocusChangeOnError) { + if (cancel && preventFocusChangeOnError) + { if (unvalidatedControl == null && currentValidatingControl != null && ancestorControl.IsDescendant(currentValidatingControl)) { @@ -1709,14 +1941,18 @@ private bool ValidateThroughAncestor(Control ancestorControl, bool preventFocusC } // This bit 'marks' the control that was going to get the focus, so that it will ignore any pending // mouse or key events. Otherwise it would still perform its default 'click' action or whatever. - if (currentActiveControl == activeControl) { - if (currentActiveControl != null) { + if (currentActiveControl == activeControl) + { + if (currentActiveControl != null) + { CancelEventArgs ev = new CancelEventArgs(); ev.Cancel = true; currentActiveControl.NotifyValidationResult(currentValidatingControl, ev); - if (currentActiveControl is ContainerControl) { + if (currentActiveControl is ContainerControl) + { ContainerControl currentActiveContainerControl = currentActiveControl as ContainerControl; - if (currentActiveContainerControl.focusedControl != null) { + if (currentActiveContainerControl.focusedControl != null) + { currentActiveContainerControl.focusedControl.ValidationCancelled = true; } currentActiveContainerControl.ResetActiveAndFocusedControlsRecursive(); @@ -1727,21 +1963,24 @@ private bool ValidateThroughAncestor(Control ancestorControl, bool preventFocusC SetActiveControl(unvalidatedControl); } } - finally { + finally + { unvalidatedControl = null; state[stateValidating] = false; } - + return !cancel; } - private void ResetValidationFlag() { + private void ResetValidationFlag() + { // PERFNOTE: This is more efficient than using Foreach. Foreach // forces the creation of an array subset enum each time we // enumerate Control.ControlCollection children = this.Controls; int count = children.Count; - for(int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) + { children[i].ValidationCancelled = false; } } @@ -1750,46 +1989,57 @@ internal void ResetActiveAndFocusedControlsRecursive() { if (activeControl is ContainerControl) { - ((ContainerControl) activeControl).ResetActiveAndFocusedControlsRecursive(); + ((ContainerControl)activeControl).ResetActiveAndFocusedControlsRecursive(); } activeControl = null; focusedControl = null; } [EditorBrowsable(EditorBrowsableState.Never)] - internal virtual bool ShouldSerializeAutoValidate() { + internal virtual bool ShouldSerializeAutoValidate() + { return autoValidate != AutoValidate.Inherit; } /// /// WM_SETFOCUS handler /// - private void WmSetFocus(ref Message m) { + private void WmSetFocus(ref Message m) + { Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "ContainerControl::WmSetFocus() - " + this.Name); - if (!HostedInWin32DialogManager) { - if (ActiveControl != null) { + if (!HostedInWin32DialogManager) + { + if (ActiveControl != null) + { WmImeSetFocus(); // Microsoft: Do not raise GotFocus event since the focus // is given to the visible ActiveControl - if (!ActiveControl.Visible) { + if (!ActiveControl.Visible) + { this.InvokeGotFocus(this, EventArgs.Empty); } FocusActiveControlInternal(); } - else { - if (ParentInternal != null) { + else + { + if (ParentInternal != null) + { IContainerControl c = ParentInternal.GetContainerControl(); - if (c != null) { + if (c != null) + { bool succeeded = false; ContainerControl knowncontainer = c as ContainerControl; - if (knowncontainer != null) { + if (knowncontainer != null) + { succeeded = knowncontainer.ActivateControlInternal(this); } - else { + else + { succeeded = c.ActivateControl(this); } - if (!succeeded) { + if (!succeeded) + { return; } } @@ -1797,7 +2047,8 @@ private void WmSetFocus(ref Message m) { base.WndProc(ref m); } } - else { + else + { base.WndProc(ref m); } } @@ -1805,8 +2056,10 @@ private void WmSetFocus(ref Message m) { /// /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { case Interop.WindowMessages.WM_SETFOCUS: WmSetFocus(ref m); break; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ContentsResizedEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ContentsResizedEventArgs.cs index 0fd68827d23..8f855592763 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ContentsResizedEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ContentsResizedEventArgs.cs @@ -19,7 +19,7 @@ public ContentsResizedEventArgs(Rectangle newRectangle) { NewRectangle = newRectangle; } - + /// /// Represents the requested size of the control. /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenu.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenu.cs index d5e96cfa356..bc2bb83dcb3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenu.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenu.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System; @@ -19,26 +20,29 @@ namespace System.Windows.Forms { [ DefaultEvent(nameof(Popup)), ] - public class ContextMenu : Menu { + public class ContextMenu : Menu + { private EventHandler onPopup; private EventHandler onCollapse; internal Control sourceControl; - + private RightToLeft rightToLeft = System.Windows.Forms.RightToLeft.Inherit; - + /// /// Creates a new ContextMenu object with no items in it by default. /// public ContextMenu() - : base(null) { + : base(null) + { } /// /// Creates a ContextMenu object with the given MenuItems. /// public ContextMenu(MenuItem[] menuItems) - : base(menuItems) { + : base(menuItems) + { } /// @@ -50,27 +54,31 @@ public ContextMenu(MenuItem[] menuItems) DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ContextMenuSourceControlDescr)) ] - public Control SourceControl { - get { + public Control SourceControl + { + get + { return sourceControl; } } [SRDescription(nameof(SR.MenuItemOnInitDescr))] - public event EventHandler Popup { + public event EventHandler Popup + { add => onPopup += value; remove => onPopup -= value; } - + /// /// Fires when the context menu collapses. /// [SRDescription(nameof(SR.ContextMenuCollapseDescr))] - public event EventHandler Collapse { + public event EventHandler Collapse + { add => onCollapse += value; remove => onCollapse -= value; } - + /// /// This is used for international applications where the language /// is written from RightToLeft. When this property is true, @@ -83,44 +91,57 @@ public event EventHandler Collapse { DefaultValue(RightToLeft.No), SRDescription(nameof(SR.MenuRightToLeftDescr)) ] - public virtual RightToLeft RightToLeft { - get { - if (System.Windows.Forms.RightToLeft.Inherit == rightToLeft) { - if (sourceControl != null) { + public virtual RightToLeft RightToLeft + { + get + { + if (System.Windows.Forms.RightToLeft.Inherit == rightToLeft) + { + if (sourceControl != null) + { return ((Control)sourceControl).RightToLeft; } - else { + else + { return RightToLeft.No; } } - else { + else + { return rightToLeft; } } - set { - + set + { + //valid values are 0x0 to 0x2. - if (!ClientUtils.IsEnumValid(value, (int)value, (int)RightToLeft.No, (int)RightToLeft.Inherit)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)RightToLeft.No, (int)RightToLeft.Inherit)) + { throw new InvalidEnumArgumentException(nameof(RightToLeft), (int)value, typeof(RightToLeft)); } - if (RightToLeft != value) { + if (RightToLeft != value) + { rightToLeft = value; UpdateRtl((value == System.Windows.Forms.RightToLeft.Yes)); } } - } + } - internal override bool RenderIsRightToLeft { - get { + internal override bool RenderIsRightToLeft + { + get + { return (rightToLeft == System.Windows.Forms.RightToLeft.Yes); } } /// /// Fires the popup event /// - protected internal virtual void OnPopup(EventArgs e) { - if (onPopup != null) { + protected internal virtual void OnPopup(EventArgs e) + { + if (onPopup != null) + { onPopup(this, e); } } @@ -128,28 +149,34 @@ protected internal virtual void OnPopup(EventArgs e) { /// /// Fires the collapse event /// - protected internal virtual void OnCollapse(EventArgs e) { - if (onCollapse != null) { + protected internal virtual void OnCollapse(EventArgs e) + { + if (onCollapse != null) + { onCollapse(this, e); } } /// /// - protected internal virtual bool ProcessCmdKey(ref Message msg, Keys keyData, Control control) { + protected internal virtual bool ProcessCmdKey(ref Message msg, Keys keyData, Control control) + { sourceControl = control; return ProcessCmdKey(ref msg, keyData); } - private void ResetRightToLeft() { - RightToLeft = RightToLeft.No; + private void ResetRightToLeft() + { + RightToLeft = RightToLeft.No; } - + /// /// Returns true if the RightToLeft should be persisted in code gen. /// - internal virtual bool ShouldSerializeRightToLeft() { - if (System.Windows.Forms.RightToLeft.Inherit == rightToLeft) { + internal virtual bool ShouldSerializeRightToLeft() + { + if (System.Windows.Forms.RightToLeft.Inherit == rightToLeft) + { return false; } return true; @@ -159,7 +186,8 @@ internal virtual bool ShouldSerializeRightToLeft() { /// Displays the context menu at the specified position. This method /// doesn't return until the menu is dismissed. /// - public void Show(Control control, Point pos) { + public void Show(Control control, Point pos) + { Show(control, pos, NativeMethods.TPM_VERTICAL | NativeMethods.TPM_RIGHTBUTTON); } @@ -167,21 +195,25 @@ public void Show(Control control, Point pos) { /// Displays the context menu at the specified position. This method /// doesn't return until the menu is dismissed. /// - public void Show(Control control, Point pos, LeftRightAlignment alignment) { + public void Show(Control control, Point pos, LeftRightAlignment alignment) + { // This code below looks wrong but it's correct. // WinForms Left alignment means we want the menu to show up left of the point it is invoked from. // We specify TPM_RIGHTALIGN which tells win32 to align the right side of this // menu with the point (which aligns it Left visually) - if (alignment == LeftRightAlignment.Left) { + if (alignment == LeftRightAlignment.Left) + { Show(control, pos, NativeMethods.TPM_VERTICAL | NativeMethods.TPM_RIGHTBUTTON | NativeMethods.TPM_RIGHTALIGN); } - else { + else + { Show(control, pos, NativeMethods.TPM_VERTICAL | NativeMethods.TPM_RIGHTBUTTON | NativeMethods.TPM_LEFTALIGN); } } - private void Show(Control control, Point pos, int flags) { + private void Show(Control control, Point pos, int flags) + { if (control == null) throw new ArgumentNullException(nameof(control)); @@ -199,6 +231,6 @@ private void Show(Control control, Point pos, int flags) { new HandleRef(control, control.Handle), null); } - + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenuStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenuStrip.cs index 308e4b323b0..855f2b10782 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenuStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenuStrip.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.ComponentModel; @@ -15,23 +16,28 @@ namespace System.Windows.Forms { DefaultEvent(nameof(Opening)), SRDescription(nameof(SR.DescriptionContextMenuStrip)) ] - public class ContextMenuStrip : ToolStripDropDownMenu { + public class ContextMenuStrip : ToolStripDropDownMenu + { /// /// Summary of ContextMenuStrip. /// - public ContextMenuStrip(IContainer container) : base() { + public ContextMenuStrip(IContainer container) : base() + { // this constructor ensures ContextMenuStrip is disposed properly since its not parented to the form. - if (container == null) { + if (container == null) + { throw new ArgumentNullException(nameof(container)); } container.Add(this); } - public ContextMenuStrip(){ + public ContextMenuStrip() + { } - protected override void Dispose(bool disposing) { + protected override void Dispose(bool disposing) + { base.Dispose(disposing); } @@ -40,78 +46,91 @@ protected override void Dispose(bool disposing) { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ContextMenuStripSourceControlDescr)) ] - public Control SourceControl { - get { + public Control SourceControl + { + get + { return SourceControlInternal; } } // minimal Clone implementation for DGV support only. - internal ContextMenuStrip Clone() { - - // VERY limited support for cloning. - - ContextMenuStrip contextMenuStrip = new ContextMenuStrip(); - - // copy over events - contextMenuStrip.Events.AddHandlers(this.Events); - - contextMenuStrip.AutoClose = AutoClose; - contextMenuStrip.AutoSize = AutoSize; - contextMenuStrip.Bounds = Bounds; - contextMenuStrip.ImageList = ImageList; - contextMenuStrip.ShowCheckMargin = ShowCheckMargin; - contextMenuStrip.ShowImageMargin = ShowImageMargin; - - - // copy over relevant properties - - for (int i = 0; i < Items.Count; i++) { - ToolStripItem item = Items[i]; - - if (item is ToolStripSeparator) { - contextMenuStrip.Items.Add(new ToolStripSeparator()); - } - else if (item is ToolStripMenuItem) { - ToolStripMenuItem menuItem = item as ToolStripMenuItem; - contextMenuStrip.Items.Add(menuItem.Clone()); - } - - } - return contextMenuStrip; + internal ContextMenuStrip Clone() + { + + // VERY limited support for cloning. + + ContextMenuStrip contextMenuStrip = new ContextMenuStrip(); + + // copy over events + contextMenuStrip.Events.AddHandlers(this.Events); + + contextMenuStrip.AutoClose = AutoClose; + contextMenuStrip.AutoSize = AutoSize; + contextMenuStrip.Bounds = Bounds; + contextMenuStrip.ImageList = ImageList; + contextMenuStrip.ShowCheckMargin = ShowCheckMargin; + contextMenuStrip.ShowImageMargin = ShowImageMargin; + + + // copy over relevant properties + + for (int i = 0; i < Items.Count; i++) + { + ToolStripItem item = Items[i]; + + if (item is ToolStripSeparator) + { + contextMenuStrip.Items.Add(new ToolStripSeparator()); + } + else if (item is ToolStripMenuItem) + { + ToolStripMenuItem menuItem = item as ToolStripMenuItem; + contextMenuStrip.Items.Add(menuItem.Clone()); + } + + } + return contextMenuStrip; } // internal overload so we know whether or not to show mnemonics. - internal void ShowInternal(Control source, Point location, bool isKeyboardActivated) { + internal void ShowInternal(Control source, Point location, bool isKeyboardActivated) + { Show(source, location); // if we were activated by keyboard - show mnemonics. - if (isKeyboardActivated) { + if (isKeyboardActivated) + { ToolStripManager.ModalMenuFilter.Instance.ShowUnderlines = true; } } - - internal void ShowInTaskbar(int x, int y) { + + internal void ShowInTaskbar(int x, int y) + { // we need to make ourselves a topmost window WorkingAreaConstrained = false; - Rectangle bounds = CalculateDropDownLocation(new Point(x,y), ToolStripDropDownDirection.AboveLeft); + Rectangle bounds = CalculateDropDownLocation(new Point(x, y), ToolStripDropDownDirection.AboveLeft); Rectangle screenBounds = Screen.FromRectangle(bounds).Bounds; - if (bounds.Y < screenBounds.Y) { - bounds = CalculateDropDownLocation(new Point(x,y), ToolStripDropDownDirection.BelowLeft); + if (bounds.Y < screenBounds.Y) + { + bounds = CalculateDropDownLocation(new Point(x, y), ToolStripDropDownDirection.BelowLeft); } - else if (bounds.X < screenBounds.X) { - bounds = CalculateDropDownLocation(new Point(x,y), ToolStripDropDownDirection.AboveRight); + else if (bounds.X < screenBounds.X) + { + bounds = CalculateDropDownLocation(new Point(x, y), ToolStripDropDownDirection.AboveRight); } bounds = WindowsFormsUtils.ConstrainToBounds(screenBounds, bounds); - + Show(bounds.X, bounds.Y); } - protected override void SetVisibleCore(bool visible) { - if (!visible) { + protected override void SetVisibleCore(bool visible) + { + if (!visible) + { WorkingAreaConstrained = true; } base.SetVisibleCore(visible); } } -} +} 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 63008c2205d..24b69e378ca 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs @@ -4,11 +4,12 @@ // #define DEBUG_PREFERREDSIZE -[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")] +[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 { +namespace System.Windows.Forms +{ using Accessibility; using Microsoft.Win32; using System; @@ -77,7 +78,8 @@ public partial class Control : IWin32Window, IArrangedElement, IBindableComponent, - IKeyboardToolTip { + IKeyboardToolTip + { #if FINALIZATION_WATCH static readonly TraceSwitch ControlFinalization = new TraceSwitch("ControlFinalization", "Tracks the creation and destruction of finalization"); @@ -101,32 +103,40 @@ internal static string GetAllocationStack() { 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 ); + 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) { + if (maxFrameCount > 5) + { maxFrameCount = 5; } int frameIndex = 1; - while( frameIndex < maxFrameCount) { + 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. + 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. + if (frameIndex > 2) + { // new CanProcessMnemonic virtual/recursive call stack. str = "\r\n" + str; } } - catch (Exception ex) { + catch (Exception ex) + { str = ex.ToString(); } - Debug.WriteLine( str ); + Debug.WriteLine(str); } } #else @@ -145,43 +155,44 @@ internal void TraceCanProcessMnemonic(){ private static int WM_GETCONTROLNAME; private static int WM_GETCONTROLTYPE; - static Control() { + 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_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; + 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; // 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 @@ -191,94 +202,94 @@ static Control() { // 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. + 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(); + 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(); private static int mouseWheelMessage = Interop.WindowMessages.WM_MOUSEWHEEL; private static bool mouseWheelRoutingNeeded; @@ -292,12 +303,12 @@ static Control() { private static bool checkForIllegalCrossThreadCalls = Debugger.IsAttached; private static ContextCallback invokeMarshaledCallbackHelperDelegate; - [ ThreadStatic ] + [ThreadStatic] private static bool inCrossThreadSafeCall = false; -// disable csharp compiler warning #0414: field assigned unused value + // disable csharp compiler warning #0414: field assigned unused value #pragma warning disable 0414 - [ ThreadStatic ] + [ThreadStatic] internal static HelpInfo currentHelpInfo = null; #pragma warning restore 0414 @@ -317,53 +328,53 @@ [ ThreadStatic ] // 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 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; @@ -388,30 +399,30 @@ [ ThreadStatic ] // 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; // - 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 ControlNativeWindow window; + + private Control parent; + private Control reflectParent; + private CreateParams createParams; + private int x; // + 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; + 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 @@ -419,12 +430,12 @@ [ ThreadStatic ] // 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; + 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; @@ -433,38 +444,43 @@ [ ThreadStatic ] /////////////////////////////////////////////////////////////////////// #if DEBUG - internal int LayoutSuspendCount { + internal int LayoutSuspendCount + { get { return layoutSuspendCount; } } - internal void AssertLayoutSuspendCount(int value) { + internal void AssertLayoutSuspendCount(int value) + { Debug.Assert(value == layoutSuspendCount, "Suspend/Resume layout mismatch!"); } -/* -example usage + /* + example usage -#if DEBUG - int dbgLayoutCheck = LayoutSuspendCount; -#endif -#if DEBUG - AssertLayoutSuspendCount(dbgLayoutCheck); -#endif -*/ + #if DEBUG + int dbgLayoutCheck = LayoutSuspendCount; + #endif + #if DEBUG + AssertLayoutSuspendCount(dbgLayoutCheck); + #endif + */ #endif /// /// Initializes a new instance of the class. /// - public Control() : this(true) { + public Control() : this(true) + { } /// /// - internal Control(bool autoInstallSyncContext) : base() { + internal Control(bool autoInstallSyncContext) : base() + { #if DEBUG - if (AssertOnControlCreateSwitch.Enabled) { + 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!"); } @@ -487,7 +503,7 @@ internal Control(bool autoInstallSyncContext) : base() { ControlStyles.StandardClick | ControlStyles.StandardDoubleClick | ControlStyles.UseTextForAccessibility | - ControlStyles.Selectable,true); + ControlStyles.Selectable, true); InitMouseWheelSupport(); @@ -496,13 +512,16 @@ internal Control(bool autoInstallSyncContext) : base() { // someone overrides these Default* methads, we need to write the default // value into the PropertyStore in the ctor. // - if(DefaultMargin != CommonProperties.DefaultMargin) { + if (DefaultMargin != CommonProperties.DefaultMargin) + { Margin = DefaultMargin; } - if(DefaultMinimumSize != CommonProperties.DefaultMinimumSize) { + if (DefaultMinimumSize != CommonProperties.DefaultMinimumSize) + { MinimumSize = DefaultMinimumSize; } - if(DefaultMaximumSize != CommonProperties.DefaultMaximumSize) { + if (DefaultMaximumSize != CommonProperties.DefaultMaximumSize) + { MaximumSize = DefaultMaximumSize; } @@ -517,7 +536,8 @@ internal Control(bool autoInstallSyncContext) : base() { // not happen, so we need to clear the preferredSize cache manually. CommonProperties.xClearPreferredSizeCache(this); - if (width != 0 && height != 0) { + if (width != 0 && height != 0) + { NativeMethods.RECT rect = new NativeMethods.RECT(); rect.left = rect.right = rect.top = rect.bottom = 0; @@ -529,7 +549,8 @@ internal Control(bool autoInstallSyncContext) : base() { } // Set up for async operations on this thread. - if (autoInstallSyncContext) { + if (autoInstallSyncContext) + { WindowsFormsSynchronizationContext.InstallIfNeeded(); } } @@ -537,20 +558,23 @@ internal Control(bool autoInstallSyncContext) : base() { /// /// Initializes a new instance of the class. /// - public Control( string text ) : this( (Control) null, text ) { + public Control(string text) : this((Control)null, text) + { } /// /// Initializes a new instance of the class. /// - public Control( string text, int left, int top, int width, int height ) : - this( (Control) null, text, left, top, width, height ) { + public Control(string text, int left, int top, int width, int height) : + this((Control)null, text, left, top, width, height) + { } /// /// Initializes a new instance of the class. /// - public Control( Control parent, string text ) : this() { + public Control(Control parent, string text) : this() + { this.Parent = parent; this.Text = text; } @@ -558,16 +582,19 @@ public Control( Control parent, string text ) : this() { /// /// Initializes a new instance of the class. /// - 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 ); + 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); } /// /// gets or sets control Dpi awareness context value. /// - internal DpiAwarenessContext DpiAwarenessContext { - get { + internal DpiAwarenessContext DpiAwarenessContext + { + get + { return window.DpiAwarenessContext; } } @@ -580,14 +607,18 @@ internal DpiAwarenessContext DpiAwarenessContext { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlAccessibilityObjectDescr)) ] - public AccessibleObject AccessibilityObject { - get { + public AccessibleObject AccessibilityObject + { + get + { AccessibleObject accessibleObject = (AccessibleObject)Properties.GetObject(PropAccessibility); - if (accessibleObject == null) { + 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)) { + if (!(accessibleObject is ControlAccessibleObject)) + { Debug.Fail("Accessible objects for controls must be derived from ControlAccessibleObject."); return null; } @@ -603,10 +634,13 @@ public AccessibleObject AccessibilityObject { /// Private accessibility object for control, used to wrap the object that /// OLEACC.DLL creates to represent the control's non-client (NC) region. /// - private AccessibleObject NcAccessibilityObject { - get { + private AccessibleObject NcAccessibilityObject + { + get + { AccessibleObject ncAccessibleObject = (AccessibleObject)Properties.GetObject(PropNcAccessibility); - if (ncAccessibleObject == null) { + if (ncAccessibleObject == null) + { ncAccessibleObject = new ControlAccessibleObject(this, NativeMethods.OBJID_WINDOW); Properties.SetObject(PropNcAccessibility, ncAccessibleObject); } @@ -620,10 +654,12 @@ private AccessibleObject NcAccessibilityObject { /// Returns a specific AccessibleObject associated with this /// control, based on standard "accessibile object id". /// - private AccessibleObject GetAccessibilityObject(int accObjId) { + private AccessibleObject GetAccessibilityObject(int accObjId) + { AccessibleObject accessibleObject; - switch (accObjId) { + switch (accObjId) + { case NativeMethods.OBJID_CLIENT: accessibleObject = this.AccessibilityObject; break; @@ -631,9 +667,12 @@ private AccessibleObject GetAccessibilityObject(int accObjId) { accessibleObject = this.NcAccessibilityObject; break; default: - if (accObjId > 0) { + if (accObjId > 0) + { accessibleObject = this.GetAccessibilityObjectById(accObjId); - } else { + } + else + { accessibleObject = null; } break; @@ -645,8 +684,10 @@ private AccessibleObject GetAccessibilityObject(int accObjId) { /// /// Returns a specific AccessibleObbject associated w/ the objectID /// - protected virtual AccessibleObject GetAccessibilityObjectById(int objectId) { - if (this is IAutomationLiveRegion) { + protected virtual AccessibleObject GetAccessibilityObjectById(int objectId) + { + if (this is IAutomationLiveRegion) + { return this.AccessibilityObject; } @@ -662,11 +703,14 @@ protected virtual AccessibleObject GetAccessibilityObjectById(int objectId) { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlAccessibleDefaultActionDescr)) ] - public string AccessibleDefaultActionDescription { - get { + public string AccessibleDefaultActionDescription + { + get + { return (string)Properties.GetObject(PropAccessibleDefaultActionDescription); } - set { + set + { Properties.SetObject(PropAccessibleDefaultActionDescription, value); } } @@ -680,11 +724,14 @@ public string AccessibleDefaultActionDescription { Localizable(true), SRDescription(nameof(SR.ControlAccessibleDescriptionDescr)) ] - public string AccessibleDescription { - get { + public string AccessibleDescription + { + get + { return (string)Properties.GetObject(PropAccessibleDescription); } - set { + set + { Properties.SetObject(PropAccessibleDescription, value); } } @@ -698,12 +745,15 @@ public string AccessibleDescription { Localizable(true), SRDescription(nameof(SR.ControlAccessibleNameDescr)) ] - public string AccessibleName { - get { + public string AccessibleName + { + get + { return (string)Properties.GetObject(PropAccessibleName); } - set { + set + { Properties.SetObject(PropAccessibleName, value); } } @@ -716,22 +766,28 @@ public string AccessibleName { DefaultValue(AccessibleRole.Default), SRDescription(nameof(SR.ControlAccessibleRoleDescr)) ] - public AccessibleRole AccessibleRole { + public AccessibleRole AccessibleRole + { - get { + get + { bool found; int role = Properties.GetInteger(PropAccessibleRole, out found); - if (found) { + if (found) + { return (AccessibleRole)role; } - else { + else + { return AccessibleRole.Default; } } - set { + set + { //valid values are -1 to 0x40 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)AccessibleRole.Default, (int)AccessibleRole.OutlineButton)) { + if (!ClientUtils.IsEnumValid(value, (int)value, (int)AccessibleRole.Default, (int)AccessibleRole.OutlineButton)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AccessibleRole)); } Properties.SetInteger(PropAccessibleRole, (int)value); @@ -742,8 +798,10 @@ public AccessibleRole AccessibleRole { /// Helper method for retrieving an ActiveX property. We abstract these /// to another method so we do not force JIT the ActiveX codebase. /// - private Color ActiveXAmbientBackColor { - get { + private Color ActiveXAmbientBackColor + { + get + { return ActiveXInstance.AmbientBackColor; } } @@ -752,8 +810,10 @@ private Color ActiveXAmbientBackColor { /// Helper method for retrieving an ActiveX property. We abstract these /// to another method so we do not force JIT the ActiveX codebase. /// - private Color ActiveXAmbientForeColor { - get { + private Color ActiveXAmbientForeColor + { + get + { return ActiveXInstance.AmbientForeColor; } } @@ -762,8 +822,10 @@ private Color ActiveXAmbientForeColor { /// Helper method for retrieving an ActiveX property. We abstract these /// to another method so we do not force JIT the ActiveX codebase. /// - private Font ActiveXAmbientFont { - get { + private Font ActiveXAmbientFont + { + get + { return ActiveXInstance.AmbientFont; } } @@ -772,8 +834,10 @@ private Font ActiveXAmbientFont { /// Helper method for retrieving an ActiveX property. We abstract these /// to another method so we do not force JIT the ActiveX codebase. /// - private bool ActiveXEventsFrozen { - get { + private bool ActiveXEventsFrozen + { + get + { return ActiveXInstance.EventsFrozen; } } @@ -782,8 +846,10 @@ private bool ActiveXEventsFrozen { /// Helper method for retrieving an ActiveX property. We abstract these /// to another method so we do not force JIT the ActiveX codebase. /// - private IntPtr ActiveXHWNDParent { - get { + private IntPtr ActiveXHWNDParent + { + get + { return ActiveXInstance.HWNDParent; } } @@ -793,20 +859,24 @@ private IntPtr ActiveXHWNDParent { /// this control. This will demand create the implementation /// if it does not already exist. /// - private ActiveXImpl ActiveXInstance { - get { + private ActiveXImpl ActiveXInstance + { + get + { ActiveXImpl activeXImpl = (ActiveXImpl)Properties.GetObject(PropActiveXImpl); - if (activeXImpl == null) { + if (activeXImpl == null) + { // Don't allow top level objects to be hosted // as activeX controls. // - if (GetState(STATE_TOPLEVEL)) { + if (GetState(STATE_TOPLEVEL)) + { 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 PropActiveXImpl instead of fetching from the property store. SetState2(STATE2_ISACTIVEX, true); @@ -826,20 +896,27 @@ private ActiveXImpl ActiveXInstance { DefaultValue(false), SRDescription(nameof(SR.ControlAllowDropDescr)) ] - public virtual bool AllowDrop { - get { + public virtual bool AllowDrop + { + get + { return GetState(STATE_ALLOWDROP); } - set { - if (GetState(STATE_ALLOWDROP) != value) { + set + { + if (GetState(STATE_ALLOWDROP) != value) + { SetState(STATE_ALLOWDROP, value); - if (IsHandleCreated) { - try { + if (IsHandleCreated) + { + try + { SetAcceptDrops(value); } - catch { + catch + { // If there is an error, back out the AllowDrop state... // SetState(STATE_ALLOWDROP, !value); @@ -853,19 +930,25 @@ public virtual bool AllowDrop { // 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 { + private AmbientProperties AmbientPropertiesService + { + get + { bool contains; AmbientProperties props = (AmbientProperties)Properties.GetObject(PropAmbientPropertiesService, out contains); - if (!contains) { - if (Site != null) { + if (!contains) + { + if (Site != null) + { props = (AmbientProperties)Site.GetService(typeof(AmbientProperties)); } - else { + else + { props = (AmbientProperties)GetService(typeof(AmbientProperties)); } - if (props != null) { + if (props != null) + { Properties.SetObject(PropAmbientPropertiesService, props); } } @@ -885,11 +968,14 @@ private AmbientProperties AmbientPropertiesService { SRDescription(nameof(SR.ControlAnchorDescr)), RefreshProperties(RefreshProperties.Repaint) ] - public virtual AnchorStyles Anchor { - get { + public virtual AnchorStyles Anchor + { + get + { return DefaultLayout.GetAnchor(this); } - set { + set + { DefaultLayout.SetAnchor(ParentInternal, this, value); } } @@ -901,16 +987,21 @@ public virtual AnchorStyles Anchor { [SRDescription(nameof(SR.ControlAutoSizeDescr))] [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public virtual bool AutoSize { + public virtual bool AutoSize + { get { return CommonProperties.GetAutoSize(this); } - set { - if(value != AutoSize) { + set + { + if (value != AutoSize) + { CommonProperties.SetAutoSize(this, value); - if(ParentInternal != null) { + 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) { + if (value && ParentInternal.LayoutEngine == DefaultLayout.Instance) + { ParentInternal.LayoutEngine.InitLayout(this, BoundsSpecified.Size); } LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.AutoSize); @@ -924,7 +1015,8 @@ public virtual bool AutoSize { [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnAutoSizeChangedDescr))] [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public event EventHandler AutoSizeChanged { + public event EventHandler AutoSizeChanged + { add => Events.AddHandler(EventAutoSizeChanged, value); remove => Events.RemoveHandler(EventAutoSizeChanged, value); } @@ -938,31 +1030,39 @@ public event EventHandler AutoSizeChanged { EditorBrowsable(EditorBrowsableState.Advanced), DefaultValue(typeof(Point), "0, 0") ] - public virtual Point AutoScrollOffset { - get { - if (Properties.ContainsObject(PropAutoScrollOffset)) { + public virtual Point AutoScrollOffset + { + get + { + if (Properties.ContainsObject(PropAutoScrollOffset)) + { return (Point)Properties.GetObject(PropAutoScrollOffset); } return Point.Empty; } - set { - if (AutoScrollOffset != value) { + set + { + if (AutoScrollOffset != value) + { Properties.SetObject(PropAutoScrollOffset, value); } } } - protected void SetAutoSizeMode(AutoSizeMode mode) { + protected void SetAutoSizeMode(AutoSizeMode mode) + { CommonProperties.SetAutoSizeMode(this, mode); } - protected AutoSizeMode GetAutoSizeMode() { + protected AutoSizeMode GetAutoSizeMode() + { return CommonProperties.GetAutoSizeMode(this); } // Public because this is interesting for ControlDesigners. [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public virtual LayoutEngine LayoutEngine { + public virtual LayoutEngine LayoutEngine + { get { return DefaultLayout.Instance; } } @@ -971,23 +1071,28 @@ public virtual LayoutEngine LayoutEngine { /// 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. /// - internal IntPtr BackColorBrush { - get { + internal IntPtr BackColorBrush + { + get + { object customBackBrush = Properties.GetObject(PropBackBrush); - if (customBackBrush != null) { + if (customBackBrush != null) + { // We already have a valid brush. Unbox, and return. // return (IntPtr)customBackBrush; } - if (!Properties.ContainsObject(PropBackColor)) { + 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) { + if (parent != null && parent.BackColor == BackColor) + { return parent.BackColorBrush; } } @@ -998,11 +1103,13 @@ internal IntPtr BackColorBrush { Color color = BackColor; IntPtr backBrush; - if (ColorTranslator.ToOle(color) < 0) { + if (ColorTranslator.ToOle(color) < 0) + { backBrush = SafeNativeMethods.GetSysColorBrush(ColorTranslator.ToOle(color) & 0xFF); SetState(STATE_OWNCTLBRUSH, false); } - else { + else + { backBrush = SafeNativeMethods.CreateSolidBrush(ColorTranslator.ToWin32(color)); SetState(STATE_OWNCTLBRUSH, true); } @@ -1023,15 +1130,19 @@ internal IntPtr BackColorBrush { DispId(NativeMethods.ActiveX.DISPID_BACKCOLOR), SRDescription(nameof(SR.ControlBackColorDescr)) ] - public virtual Color BackColor { - get { + public virtual Color BackColor + { + get + { Color c = RawBackColor; // inheritedProperties.BackColor - if (!c.IsEmpty) { + if (!c.IsEmpty) + { return c; } Control p = ParentInternal; - if (p != null && p.CanAccessProperties) { + if (p != null && p.CanAccessProperties) + { c = p.BackColor; if (IsValidBackColor(c)) { @@ -1040,11 +1151,13 @@ public virtual Color BackColor { } - if (IsActiveX) { + if (IsActiveX) + { c = ActiveXAmbientBackColor; } - if (c.IsEmpty) { + if (c.IsEmpty) + { AmbientProperties ambient = AmbientPropertiesService; if (ambient != null) c = ambient.BackColor; @@ -1056,23 +1169,27 @@ public virtual Color BackColor { return DefaultBackColor; } - set { + set + { if (!value.Equals(Color.Empty) && !GetStyle(ControlStyles.SupportsTransparentBackColor) && value.A < 255) throw new ArgumentException(SR.TransparentBackColorNotAllowed); Color c = BackColor; - if (!value.IsEmpty || Properties.ContainsObject(PropBackColor)) { + if (!value.IsEmpty || Properties.ContainsObject(PropBackColor)) + { Properties.SetColor(PropBackColor, value); } - if (!c.Equals(BackColor)) { + if (!c.Equals(BackColor)) + { OnBackColorChanged(EventArgs.Empty); } } } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnBackColorChangedDescr))] - public event EventHandler BackColorChanged { + public event EventHandler BackColorChanged + { add => Events.AddHandler(EventBackColor, value); remove => Events.RemoveHandler(EventBackColor, value); } @@ -1086,12 +1203,16 @@ public event EventHandler BackColorChanged { Localizable(true), SRDescription(nameof(SR.ControlBackgroundImageDescr)) ] - public virtual Image BackgroundImage { - get { + public virtual Image BackgroundImage + { + get + { return (Image)Properties.GetObject(PropBackgroundImage); } - set { - if (BackgroundImage != value) { + set + { + if (BackgroundImage != value) + { Properties.SetObject(PropBackgroundImage, value); OnBackgroundImageChanged(EventArgs.Empty); } @@ -1099,7 +1220,8 @@ public virtual Image BackgroundImage { } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnBackgroundImageChangedDescr))] - public event EventHandler BackgroundImageChanged { + public event EventHandler BackgroundImageChanged + { add => Events.AddHandler(EventBackgroundImage, value); remove => Events.RemoveHandler(EventBackgroundImage, value); } @@ -1113,29 +1235,37 @@ public event EventHandler BackgroundImageChanged { Localizable(true), SRDescription(nameof(SR.ControlBackgroundImageLayoutDescr)) ] - public virtual ImageLayout BackgroundImageLayout { - get { + public virtual ImageLayout BackgroundImageLayout + { + get + { bool found = Properties.ContainsObject(PropBackgroundImageLayout); - if (!found) { + if (!found) + { return ImageLayout.Tile; } - else { + else + { return ((ImageLayout)Properties.GetObject(PropBackgroundImageLayout)); - } + } } - set { - if (BackgroundImageLayout != value) { + set + { + if (BackgroundImageLayout != value) + { //valid values are 0x0 to 0x4 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)ImageLayout.None, (int)ImageLayout.Zoom)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)ImageLayout.None, (int)ImageLayout.Zoom)) + { throw new InvalidEnumArgumentException(nameof(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) { + 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; + DoubleBuffered = true; } } Properties.SetObject(PropBackgroundImageLayout, value); @@ -1145,7 +1275,8 @@ public virtual ImageLayout BackgroundImageLayout { } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnBackgroundImageLayoutChangedDescr))] - public event EventHandler BackgroundImageLayoutChanged { + public event EventHandler BackgroundImageLayoutChanged + { add => Events.AddHandler(EventBackgroundImageLayout, value); remove => Events.RemoveHandler(EventBackgroundImageLayout, value); } @@ -1160,22 +1291,25 @@ internal bool BecomingActiveControl set { if (value != this.BecomingActiveControl) - { + { Application.ThreadContext.FromCurrent().ActivatingControl = (value) ? this : null; SetState2(STATE2_BECOMINGACTIVECONTROL, value); } } } - private bool ShouldSerializeAccessibleName() { + private bool ShouldSerializeAccessibleName() + { string accName = this.AccessibleName; return accName != null && accName.Length > 0; } [EditorBrowsable(EditorBrowsableState.Never)] - public void ResetBindings() { + public void ResetBindings() + { ControlBindingsCollection bindings = (ControlBindingsCollection)Properties.GetObject(PropBindings); - if (bindings != null) { + if (bindings != null) + { bindings.Clear(); } } @@ -1191,15 +1325,17 @@ internal BindingContext BindingContextInternal { // See if we have locally overridden the binding manager. // - BindingContext context = (BindingContext) Properties.GetObject(PropBindingManager); - if (context != null) { + 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) { + if (p != null && p.CanAccessProperties) + { return p.BindingContext; } @@ -1209,10 +1345,11 @@ internal BindingContext BindingContextInternal } set { - BindingContext oldContext = (BindingContext) Properties.GetObject(PropBindingManager); + BindingContext oldContext = (BindingContext)Properties.GetObject(PropBindingManager); BindingContext newContext = value; - if (oldContext != newContext) { + if (oldContext != newContext) + { Properties.SetObject(PropBindingManager, newContext); // the property change will wire up the bindings. @@ -1227,17 +1364,21 @@ internal BindingContext BindingContextInternal DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlBindingContextDescr)) ] - public virtual BindingContext BindingContext { - get { + public virtual BindingContext BindingContext + { + get + { return BindingContextInternal; } - set { + set + { BindingContextInternal = value; } } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnBindingContextChangedDescr))] - public event EventHandler BindingContextChanged { + public event EventHandler BindingContextChanged + { add => Events.AddHandler(EventBindingContext, value); remove => Events.RemoveHandler(EventBindingContext, value); } @@ -1251,8 +1392,10 @@ public event EventHandler BindingContextChanged { SRDescription(nameof(SR.ControlBottomDescr)), SRCategory(nameof(SR.CatLayout)) ] - public int Bottom { - get { + public int Bottom + { + get + { return y + height; } } @@ -1267,20 +1410,25 @@ public int Bottom { SRDescription(nameof(SR.ControlBoundsDescr)), SRCategory(nameof(SR.CatLayout)) ] - public Rectangle Bounds { - get { + public Rectangle Bounds + { + get + { return new Rectangle(x, y, width, height); } - set { + set + { SetBounds(value.X, value.Y, value.Width, value.Height, BoundsSpecified.All); } } /// /// - internal virtual bool CanAccessProperties { - get { + internal virtual bool CanAccessProperties + { + get + { return true; } } @@ -1295,9 +1443,12 @@ internal virtual bool CanAccessProperties { SRCategory(nameof(SR.CatFocus)), SRDescription(nameof(SR.ControlCanFocusDescr)) ] - public bool CanFocus { - get { - if (!IsHandleCreated) { + public bool CanFocus + { + get + { + if (!IsHandleCreated) + { return false; } bool visible = SafeNativeMethods.IsWindowVisible(new HandleRef(window, Handle)); @@ -1311,9 +1462,12 @@ public bool CanFocus { /// hosted as an ActiveX control, this property will return false if the ActiveX /// control has its events frozen. /// - protected override bool CanRaiseEvents { - get { - if (IsActiveX) { + protected override bool CanRaiseEvents + { + get + { + if (IsActiveX) + { return !ActiveXEventsFrozen; } @@ -1332,11 +1486,13 @@ protected override bool CanRaiseEvents { SRCategory(nameof(SR.CatFocus)), SRDescription(nameof(SR.ControlCanSelectDescr)) ] - public bool CanSelect { + public bool CanSelect + { // We implement this to allow only AxHost to override canSelectCore, but still // expose the method publicly // - get { + get + { return CanSelectCore(); } } @@ -1350,26 +1506,35 @@ public bool CanSelect { SRCategory(nameof(SR.CatFocus)), SRDescription(nameof(SR.ControlCaptureDescr)) ] - public bool Capture { - get { + public bool Capture + { + get + { return CaptureInternal; } - set { + set + { CaptureInternal = value; } } - - internal bool CaptureInternal { - get { + + internal bool CaptureInternal + { + get + { return IsHandleCreated && UnsafeNativeMethods.GetCapture() == Handle; } - set { - if (CaptureInternal != value) { - if (value) { + set + { + if (CaptureInternal != value) + { + if (value) + { UnsafeNativeMethods.SetCapture(new HandleRef(this, Handle)); } - else { + else + { SafeNativeMethods.ReleaseCapture(); } } @@ -1385,12 +1550,16 @@ internal bool CaptureInternal { DefaultValue(true), SRDescription(nameof(SR.ControlCausesValidationDescr)) ] - public bool CausesValidation { - get { + public bool CausesValidation + { + get + { return GetState(STATE_CAUSESVALIDATION); } - set { - if (value != this.CausesValidation) { + set + { + if (value != this.CausesValidation) + { SetState(STATE_CAUSESVALIDATION, value); OnCausesValidationChanged(EventArgs.Empty); } @@ -1399,7 +1568,8 @@ public bool CausesValidation { [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnCausesValidationChangedDescr))] - public event EventHandler CausesValidationChanged { + public event EventHandler CausesValidationChanged + { add => Events.AddHandler(EventCausesValidation, value); remove => Events.RemoveHandler(EventCausesValidation, value); } @@ -1410,8 +1580,10 @@ public event EventHandler CausesValidationChanged { /// cache if it does) but prevents us from sending a ton of messages turing layout. See the PaintWithErrorHandling /// function. /// - internal bool CacheTextInternal { - get { + internal bool CacheTextInternal + { + get + { // check if we're caching text. // @@ -1420,45 +1592,53 @@ internal bool CacheTextInternal { return cacheTextCounter > 0 || GetStyle(ControlStyles.CacheText); } - set { + set + { // if this control always cachest text or the handle hasn't been created, // just bail. // - if (GetStyle(ControlStyles.CacheText) || !IsHandleCreated) { + 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) { + int cacheTextCounter = Properties.GetInteger(PropCacheTextCount, out found); + + if (value) + { + if (cacheTextCounter == 0) + { Properties.SetObject(PropCacheTextField, text); - if (text == null) { + if (text == null) + { text = WindowText; - } + } } cacheTextCounter++; } - else { + else + { cacheTextCounter--; - if (cacheTextCounter == 0) { + if (cacheTextCounter == 0) + { text = (string)Properties.GetObject(PropCacheTextField, out found); } - } + } Properties.SetInteger(PropCacheTextCount, cacheTextCounter); - } + } } - [ + [ Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), SRDescription(nameof(SR.ControlCheckForIllegalCrossThreadCalls)), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public static bool CheckForIllegalCrossThreadCalls { + public static bool CheckForIllegalCrossThreadCalls + { get { return checkForIllegalCrossThreadCalls; } set { checkForIllegalCrossThreadCalls = value; } } @@ -1472,8 +1652,10 @@ public static bool CheckForIllegalCrossThreadCalls { SRCategory(nameof(SR.CatLayout)), SRDescription(nameof(SR.ControlClientRectangleDescr)) ] - public Rectangle ClientRectangle { - get { + public Rectangle ClientRectangle + { + get + { return new Rectangle(0, 0, clientWidth, clientHeight); } } @@ -1487,12 +1669,15 @@ public Rectangle ClientRectangle { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlClientSizeDescr)) ] - public Size ClientSize { - get { + public Size ClientSize + { + get + { return new Size(clientWidth, clientHeight); } - set { + set + { SetClientSizeCore(value.Width, value.Height); } } @@ -1501,7 +1686,8 @@ public Size ClientSize { /// Fired when ClientSize changes. /// [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnClientSizeChangedDescr))] - public event EventHandler ClientSizeChanged { + public event EventHandler ClientSizeChanged + { add => Events.AddHandler(EventClientSize, value); remove => Events.RemoveHandler(EventClientSize, value); } @@ -1514,10 +1700,12 @@ public event EventHandler ClientSizeChanged { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DescriptionAttribute(nameof(SR.ControlCompanyNameDescr)) ] - public string CompanyName { - - - get { + public string CompanyName + { + + + get + { return VersionInfo.CompanyName; } } @@ -1531,23 +1719,29 @@ public string CompanyName { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlContainsFocusDescr)) ] - public bool ContainsFocus { - get { - if (!IsHandleCreated) { + public bool ContainsFocus + { + get + { + if (!IsHandleCreated) + { return false; } IntPtr focusHwnd = UnsafeNativeMethods.GetFocus(); - if (focusHwnd == IntPtr.Zero) { + if (focusHwnd == IntPtr.Zero) + { return false; - } + } - if (focusHwnd == this.Handle) { + if (focusHwnd == this.Handle) + { return true; } - if (UnsafeNativeMethods.IsChild(new HandleRef(this, this.Handle), new HandleRef(this, focusHwnd))) { + if (UnsafeNativeMethods.IsChild(new HandleRef(this, this.Handle), new HandleRef(this, focusHwnd))) + { return true; } @@ -1568,23 +1762,29 @@ public bool ContainsFocus { SRDescription(nameof(SR.ControlContextMenuDescr)), Browsable(false) ] - public virtual ContextMenu ContextMenu { - get { + public virtual ContextMenu ContextMenu + { + get + { return (ContextMenu)Properties.GetObject(PropContextMenu); } - set { + set + { ContextMenu oldValue = (ContextMenu)Properties.GetObject(PropContextMenu); - if (oldValue != value) { + if (oldValue != value) + { EventHandler disposedHandler = new EventHandler(DetachContextMenu); - if (oldValue != null) { + if (oldValue != null) + { oldValue.Disposed -= disposedHandler; } Properties.SetObject(PropContextMenu, value); - if (value != null) { + if (value != null) + { value.Disposed += disposedHandler; } @@ -1598,49 +1798,57 @@ public virtual ContextMenu ContextMenu { SRDescription(nameof(SR.ControlOnContextMenuChangedDescr)), Browsable(false) ] - public event EventHandler ContextMenuChanged { + public event EventHandler ContextMenuChanged + { add => Events.AddHandler(EventContextMenu, value); remove => Events.RemoveHandler(EventContextMenu, value); } - /// - /// 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. - /// + /// + /// 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. + /// [ SRCategory(nameof(SR.CatBehavior)), DefaultValue(null), SRDescription(nameof(SR.ControlContextMenuDescr)) ] - public virtual ContextMenuStrip ContextMenuStrip { - get { - return (ContextMenuStrip)Properties.GetObject(PropContextMenuStrip); - } - set { - ContextMenuStrip oldValue = Properties.GetObject(PropContextMenuStrip) as ContextMenuStrip; + 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 != value) + { + EventHandler disposedHandler = new EventHandler(DetachContextMenuStrip); - if (oldValue != null) { - oldValue.Disposed -= disposedHandler; - } + if (oldValue != null) + { + oldValue.Disposed -= disposedHandler; + } - Properties.SetObject(PropContextMenuStrip, value); + Properties.SetObject(PropContextMenuStrip, value); - if (value != null) { - value.Disposed += disposedHandler; - } + if (value != null) + { + value.Disposed += disposedHandler; + } - OnContextMenuStripChanged(EventArgs.Empty); - } - } + OnContextMenuStripChanged(EventArgs.Empty); + } + } } - + [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlContextMenuStripChangedDescr))] - public event EventHandler ContextMenuStripChanged { + public event EventHandler ContextMenuStripChanged + { add => Events.AddHandler(EventContextMenuStrip, value); remove => Events.RemoveHandler(EventContextMenuStrip, value); } @@ -1653,11 +1861,14 @@ public event EventHandler ContextMenuStripChanged { DesignerSerializationVisibility(DesignerSerializationVisibility.Content), SRDescription(nameof(SR.ControlControlsDescr)) ] - public ControlCollection Controls { - get { + public ControlCollection Controls + { + get + { ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection == null) { + if (controlsCollection == null) + { controlsCollection = CreateControlsInstance(); Properties.SetObject(PropControlsCollection, controlsCollection); } @@ -1673,9 +1884,11 @@ public ControlCollection Controls { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlCreatedDescr)) ] - public bool Created { - get { - return(state & STATE_CREATED) != 0; + public bool Created + { + get + { + return (state & STATE_CREATED) != 0; } } @@ -1684,15 +1897,21 @@ public bool Created { /// Inheriting classes should call base.CreateParams in the manor /// below: /// - protected virtual CreateParams CreateParams { - get { + protected virtual CreateParams CreateParams + { + get + { // CLR4.0 or later, comctl32.dll needs to be loaded explicitly. - if (needToLoadComCtl) { + if (needToLoadComCtl) + { if ((UnsafeNativeMethods.GetModuleHandle(ExternDll.Comctl32) != IntPtr.Zero) - || (UnsafeNativeMethods.LoadLibraryFromSystemPathIfAvailable(ExternDll.Comctl32) != IntPtr.Zero)) { + || (UnsafeNativeMethods.LoadLibraryFromSystemPathIfAvailable(ExternDll.Comctl32) != IntPtr.Zero)) + { needToLoadComCtl = false; - } else { + } + else + { int lastWin32Error = Marshal.GetLastWin32Error(); throw new Win32Exception(lastWin32Error, string.Format(SR.LoadDLLError, ExternDll.Comctl32)); } @@ -1701,7 +1920,8 @@ protected virtual CreateParams CreateParams { // 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) { + if (createParams == null) + { createParams = new CreateParams(); } @@ -1717,38 +1937,46 @@ protected virtual CreateParams CreateParams { cp.Height = height; cp.Style = NativeMethods.WS_CLIPCHILDREN; - if (GetStyle(ControlStyles.ContainerControl)) { + if (GetStyle(ControlStyles.ContainerControl)) + { cp.ExStyle |= NativeMethods.WS_EX_CONTROLPARENT; } cp.ClassStyle = NativeMethods.CS_DBLCLKS; - if ((state & STATE_TOPLEVEL) == 0) { + 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 { + 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; + 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 (!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) { + if (cp.Parent == IntPtr.Zero && IsActiveX) + { cp.Parent = ActiveXHWNDParent; } // Set Rtl bits - if (RightToLeft == RightToLeft.Yes) { + if (RightToLeft == RightToLeft.Yes) + { cp.ExStyle |= NativeMethods.WS_EX_RTLREADING; cp.ExStyle |= NativeMethods.WS_EX_RIGHT; cp.ExStyle |= NativeMethods.WS_EX_LEFTSCROLLBAR; @@ -1758,8 +1986,9 @@ protected virtual CreateParams CreateParams { } } - internal virtual void NotifyValidationResult(object sender, CancelEventArgs ev) { - this.ValidationCancelled = ev.Cancel ; + internal virtual void NotifyValidationResult(object sender, CancelEventArgs ev) + { + this.ValidationCancelled = ev.Cancel; } /// @@ -1773,26 +2002,34 @@ internal virtual void NotifyValidationResult(object sender, CancelEventArgs ev) /// 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. /// - internal bool ValidateActiveControl(out bool validatedControlAllowsFocusChange) { + internal bool ValidateActiveControl(out bool validatedControlAllowsFocusChange) + { bool valid = true; validatedControlAllowsFocusChange = false; IContainerControl c = GetContainerControl(); - if (c != null && this.CausesValidation) { + if (c != null && this.CausesValidation) + { ContainerControl container = c as ContainerControl; - if (container != null) { - while (container.ActiveControl == null) { + if (container != null) + { + while (container.ActiveControl == null) + { ContainerControl cc; Control parent = container.ParentInternal; - if (parent != null) { + if (parent != null) + { cc = parent.GetContainerControl() as ContainerControl; - if (cc != null) { + if (cc != null) + { container = cc; } - else { + else + { break; } } - else { + else + { break; } } @@ -1804,17 +2041,23 @@ internal bool ValidateActiveControl(out bool validatedControlAllowsFocusChange) return valid; } - internal bool ValidationCancelled { - set { + internal bool ValidationCancelled + { + set + { SetState(STATE_VALIDATIONCANCELLED, value); } - get { - if (GetState(STATE_VALIDATIONCANCELLED)) { + get + { + if (GetState(STATE_VALIDATIONCANCELLED)) + { return true; } - else { + else + { Control parent = this.ParentInternal; - if (parent != null) { + if (parent != null) + { return parent.ValidationCancelled; } @@ -1828,11 +2071,14 @@ internal bool ValidationCancelled { /// 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. /// - internal bool IsTopMdiWindowClosing { - set { + internal bool IsTopMdiWindowClosing + { + set + { SetState2(STATE2_TOPMDIWINDOWCLOSING, value); } - get { + get + { return GetState2(STATE2_TOPMDIWINDOWCLOSING); } } @@ -1841,11 +2087,14 @@ internal bool IsTopMdiWindowClosing { /// 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. /// - internal bool IsCurrentlyBeingScaled { - private set { + internal bool IsCurrentlyBeingScaled + { + private set + { SetState2(STATE2_CURRENTLYBEINGSCALED, value); } - get { + get + { return GetState2(STATE2_CURRENTLYBEINGSCALED); } } @@ -1855,13 +2104,17 @@ private set { /// handle for this control. If the control's handle hasn't been /// created yet, this method will return the current thread's ID. /// - internal int CreateThreadId { - get { - if (IsHandleCreated) { + internal int CreateThreadId + { + get + { + if (IsHandleCreated) + { int pid; return SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(this, Handle), out pid); } - else { + else + { return SafeNativeMethods.GetCurrentThreadId(); } } @@ -1876,15 +2129,18 @@ internal int CreateThreadId { SRDescription(nameof(SR.ControlCursorDescr)), AmbientValue(null) ] - public virtual Cursor Cursor { - get { + public virtual Cursor Cursor + { + get + { if (GetState(STATE_USEWAITCURSOR)) { return Cursors.WaitCursor; } Cursor cursor = (Cursor)Properties.GetObject(PropCursor); - if (cursor != null) { + if (cursor != null) + { return cursor; } @@ -1892,12 +2148,14 @@ public virtual Cursor Cursor { // as their default. // Cursor localDefault = DefaultCursor; - if (localDefault != Cursors.Default) { + if (localDefault != Cursors.Default) + { return localDefault; } Control p = ParentInternal; - if (p != null) { + if (p != null) + { return p.Cursor; } @@ -1907,18 +2165,21 @@ public virtual Cursor Cursor { return localDefault; } - set { + set + { Cursor localCursor = (Cursor)Properties.GetObject(PropCursor); Cursor resolvedCursor = Cursor; - if (localCursor != value) { + if (localCursor != value) + { Properties.SetObject(PropCursor, value); } // Other things can change the cursor... we // really want to force the correct cursor always... // - if (IsHandleCreated) { + 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(); @@ -1930,14 +2191,16 @@ public virtual Cursor Cursor { SendMessage(Interop.WindowMessages.WM_SETCURSOR, Handle, (IntPtr)NativeMethods.HTCLIENT); } - if (!resolvedCursor.Equals(value)) { + if (!resolvedCursor.Equals(value)) + { OnCursorChanged(EventArgs.Empty); } } } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnCursorChangedDescr))] - public event EventHandler CursorChanged { + public event EventHandler CursorChanged + { add => Events.AddHandler(EventCursor, value); remove => Events.RemoveHandler(EventCursor, value); } @@ -1970,8 +2233,9 @@ public ControlBindingsCollection DataBindings /// The default BackColor of a generic top-level Control. Subclasses may have /// different defaults. /// - public static Color DefaultBackColor { - get { return SystemColors.Control;} + public static Color DefaultBackColor + { + get { return SystemColors.Control; } } /// @@ -1979,8 +2243,10 @@ public static Color DefaultBackColor { /// This is more efficient than setting the cursor in the control's constructor, /// and gives automatic support for ShouldSerialize and Reset in the designer. /// - protected virtual Cursor DefaultCursor { - get { + protected virtual Cursor DefaultCursor + { + get + { return Cursors.Default; } } @@ -1989,9 +2255,12 @@ protected virtual Cursor DefaultCursor { /// The default Font of a generic top-level Control. Subclasses may have /// different defaults. /// - public static Font DefaultFont { - get { - if (defaultFont == null) { + public static Font DefaultFont + { + get + { + if (defaultFont == null) + { defaultFont = SystemFonts.DefaultFont; Debug.Assert(defaultFont != null, "defaultFont wasn't set!"); } @@ -2004,27 +2273,33 @@ public static Font DefaultFont { /// The default ForeColor of a generic top-level Control. Subclasses may have /// different defaults. /// - public static Color DefaultForeColor { - get { return SystemColors.ControlText;} + public static Color DefaultForeColor + { + get { return SystemColors.ControlText; } } - protected virtual Padding DefaultMargin { + protected virtual Padding DefaultMargin + { get { return CommonProperties.DefaultMargin; } } - protected virtual Size DefaultMaximumSize { + protected virtual Size DefaultMaximumSize + { get { return CommonProperties.DefaultMaximumSize; } } - protected virtual Size DefaultMinimumSize { + protected virtual Size DefaultMinimumSize + { get { return CommonProperties.DefaultMinimumSize; } } - protected virtual Padding DefaultPadding { + protected virtual Padding DefaultPadding + { get { return Padding.Empty; } } - private RightToLeft DefaultRightToLeft { + private RightToLeft DefaultRightToLeft + { get { return RightToLeft.No; } } @@ -2032,15 +2307,18 @@ private RightToLeft DefaultRightToLeft { /// 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. /// - protected virtual Size DefaultSize { + protected virtual Size DefaultSize + { get { return Size.Empty; } } - private void DetachContextMenu(object sender, EventArgs e) { + private void DetachContextMenu(object sender, EventArgs e) + { ContextMenu = null; } - private void DetachContextMenuStrip(object sender, EventArgs e) { + private void DetachContextMenuStrip(object sender, EventArgs e) + { ContextMenuStrip = null; } @@ -2053,9 +2331,12 @@ private void DetachContextMenuStrip(object sender, EventArgs e) { EditorBrowsable(EditorBrowsableState.Always), // do show in the intellisense DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) // do not serialize ] - public int DeviceDpi { - get { - if (DpiHelper.IsPerMonitorV2Awareness) { + public int DeviceDpi + { + get + { + if (DpiHelper.IsPerMonitorV2Awareness) + { // deviceDpi may change in WmDpiChangedBeforeParent in PmV2 scenarios, so we can't cache statically. return deviceDpi; } @@ -2065,13 +2346,18 @@ public int 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 { + internal Color DisabledColor + { + get + { Color color = BackColor; - if (color.A == 0) { + if (color.A == 0) + { Control control = ParentInternal; - while (color.A == 0) { - if (control == null) { + while (color.A == 0) + { + if (control == null) + { // Don't know what to do, this seems good as anything color = SystemColors.Control; break; @@ -2095,9 +2381,11 @@ internal Color DisabledColor { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlDisplayRectangleDescr)) ] - public virtual Rectangle DisplayRectangle { + public virtual Rectangle DisplayRectangle + { [SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces")] - get { + get + { return new Rectangle(0, 0, clientWidth, clientHeight); } } @@ -2111,8 +2399,10 @@ public virtual Rectangle DisplayRectangle { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlDisposedDescr)) ] - public bool IsDisposed { - get { + public bool IsDisposed + { + get + { return GetState(STATE_DISPOSED); } } @@ -2120,10 +2410,13 @@ public bool IsDisposed { /// /// Disposes of the currently selected font handle (if cached). /// - private void DisposeFontHandle() { - if (Properties.ContainsObject(PropFontHandleWrapper)) { + private void DisposeFontHandle() + { + if (Properties.ContainsObject(PropFontHandleWrapper)) + { FontHandleWrapper fontHandle = Properties.GetObject(PropFontHandleWrapper) as FontHandleWrapper; - if( fontHandle != null ){ + if (fontHandle != null) + { fontHandle.Dispose(); } Properties.SetObject(PropFontHandleWrapper, null); @@ -2139,8 +2432,10 @@ private void DisposeFontHandle() { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlDisposingDescr)) ] - public bool Disposing { - get { + public bool Disposing + { + get + { return GetState(STATE_DISPOSING); } } @@ -2158,20 +2453,27 @@ public bool Disposing { DefaultValue(CommonProperties.DefaultDock), SRDescription(nameof(SR.ControlDockDescr)) ] - public virtual DockStyle Dock { - get { + public virtual DockStyle Dock + { + get + { return DefaultLayout.GetDock(this); } - set { - if(value != Dock) { + set + { + if (value != Dock) + { #if DEBUG int dbgLayoutCheck = LayoutSuspendCount; #endif SuspendLayout(); - try { + try + { DefaultLayout.SetDock(this, value); OnDockChanged(EventArgs.Empty); - } finally { + } + finally + { ResumeLayout(); } #if DEBUG @@ -2182,7 +2484,8 @@ public virtual DockStyle Dock { } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnDockChangedDescr))] - public event EventHandler DockChanged { + public event EventHandler DockChanged + { add => Events.AddHandler(EventDock, value); remove => Events.RemoveHandler(EventDock, value); } @@ -2194,25 +2497,33 @@ public event EventHandler DockChanged { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ControlDoubleBufferedDescr)) ] - protected virtual bool DoubleBuffered { - get { + protected virtual bool DoubleBuffered + { + get + { return GetStyle(ControlStyles.OptimizedDoubleBuffer); } - set { - if (value != DoubleBuffered) { - if (value) { + set + { + if (value != DoubleBuffered) + { + if (value) + { SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, value); } - else { + else + { SetStyle(ControlStyles.OptimizedDoubleBuffer, value); } } } } - private bool DoubleBufferingEnabled { - get { -#pragma warning disable 618 + private bool DoubleBufferingEnabled + { + get + { +#pragma warning disable 618 return GetStyle(ControlStyles.DoubleBuffer | ControlStyles.UserPaint); #pragma warning restore 618 } @@ -2227,8 +2538,10 @@ private bool DoubleBufferingEnabled { DispId(NativeMethods.ActiveX.DISPID_ENABLED), SRDescription(nameof(SR.ControlEnabledDescr)) ] - public bool Enabled { - get { + public bool Enabled + { + get + { // We are only enabled if our parent is enabled if (!GetState(STATE_ENABLED)) return false; @@ -2238,12 +2551,15 @@ public bool Enabled { return ParentInternal.Enabled; } - set { + set + { bool oldValue = Enabled; SetState(STATE_ENABLED, value); - if (oldValue != value) { - if (!value) { + if (oldValue != value) + { + if (!value) + { SelectNextIfFocused(); } @@ -2257,7 +2573,8 @@ public bool Enabled { /// Occurs when the control is enabled. /// [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnEnabledChangedDescr))] - public event EventHandler EnabledChanged { + public event EventHandler EnabledChanged + { add => Events.AddHandler(EventEnabled, value); remove => Events.RemoveHandler(EventEnabled, value); } @@ -2270,8 +2587,10 @@ public event EventHandler EnabledChanged { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlFocusedDescr)) ] - public virtual bool Focused { - get { + public virtual bool Focused + { + get + { return IsHandleCreated && UnsafeNativeMethods.GetFocus() == Handle; } } @@ -2287,54 +2606,68 @@ public virtual bool Focused { AmbientValue(null), SRDescription(nameof(SR.ControlFontDescr)) ] - public virtual Font Font { - [return : MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(ActiveXFontMarshaler))] - get { + public virtual Font Font + { + [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(ActiveXFontMarshaler))] + get + { Font font = (Font)Properties.GetObject(PropFont); - if (font != null) { + if (font != null) + { return font; } Font f = GetParentFont(); - if (f != null) { + if (f != null) + { return f; } - if (IsActiveX) { + if (IsActiveX) + { f = ActiveXAmbientFont; - if (f != null) { + if (f != null) + { return f; } } AmbientProperties ambient = AmbientPropertiesService; - if (ambient != null && ambient.Font != null) { + if (ambient != null && ambient.Font != null) + { return ambient.Font; } return DefaultFont; } - [param : MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(ActiveXFontMarshaler))] - set { + [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) { + if (value == null) + { + if (local != null) + { localChanged = true; } } - else { - if (local == null) { + else + { + if (local == null) + { localChanged = true; } - else { + else + { localChanged = !value.Equals(local); } } - if (localChanged) { + if (localChanged) + { // Store new local value // Properties.SetObject(PropFont, value); @@ -2343,12 +2676,14 @@ public virtual Font Font { // changed, however we must update the font if the local // value changed... // - if (!resolved.Equals(value)) { + if (!resolved.Equals(value)) + { // Cleanup any font handle wrapper... // DisposeFontHandle(); - if (Properties.ContainsInteger(PropFontHeight)) { + if (Properties.ContainsInteger(PropFontHeight)) + { Properties.SetInteger(PropFontHeight, (value == null) ? -1 : value.Height); } @@ -2356,12 +2691,15 @@ public virtual Font Font { // 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)) { + using (new LayoutTransaction(ParentInternal, this, PropertyNames.Font)) + { OnFontChanged(EventArgs.Empty); } } - else { - if (IsHandleCreated && !GetStyle(ControlStyles.UserPaint)) { + else + { + if (IsHandleCreated && !GetStyle(ControlStyles.UserPaint)) + { DisposeFontHandle(); SetWindowFont(); } @@ -2370,18 +2708,22 @@ public virtual Font Font { } } - internal void ScaleFont(float factor) { + internal void ScaleFont(float factor) + { Font local = (Font)Properties.GetObject(PropFont); Font resolved = Font; Font newFont = new Font(this.Font.FontFamily, this.Font.Size * factor, this.Font.Style); - if ((local == null) || !local.Equals(newFont)) { + if ((local == null) || !local.Equals(newFont)) + { Properties.SetObject(PropFont, newFont); - if (!resolved.Equals(newFont)) { + if (!resolved.Equals(newFont)) + { DisposeFontHandle(); - if (Properties.ContainsInteger(PropFontHeight)) { + if (Properties.ContainsInteger(PropFontHeight)) + { Properties.SetInteger(PropFontHeight, newFont.Height); } } @@ -2389,18 +2731,23 @@ internal void ScaleFont(float factor) { } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnFontChangedDescr))] - public event EventHandler FontChanged { + public event EventHandler FontChanged + { add => Events.AddHandler(EventFont, value); remove => Events.RemoveHandler(EventFont, value); } - internal IntPtr FontHandle { - get { + internal IntPtr FontHandle + { + get + { Font font = (Font)Properties.GetObject(PropFont); - if (font != null) { + if (font != null) + { FontHandleWrapper fontHandle = (FontHandleWrapper)Properties.GetObject(PropFontHandleWrapper); - if (fontHandle == null) { + if (fontHandle == null) + { fontHandle = new FontHandleWrapper(font); Properties.SetObject(PropFontHandleWrapper, fontHandle); @@ -2409,27 +2756,32 @@ internal IntPtr FontHandle { return fontHandle.Handle; } - if (parent != null) { + if (parent != null) + { return parent.FontHandle; } AmbientProperties ambient = AmbientPropertiesService; - if (ambient != null && ambient.Font != null) { + if (ambient != null && ambient.Font != null) + { FontHandleWrapper fontHandle = null; Font currentAmbient = (Font)Properties.GetObject(PropCurrentAmbientFont); - if (currentAmbient != null && currentAmbient == ambient.Font) { + if (currentAmbient != null && currentAmbient == ambient.Font) + { fontHandle = (FontHandleWrapper)Properties.GetObject(PropFontHandleWrapper); } - else { + else + { Properties.SetObject(PropCurrentAmbientFont, ambient.Font); } - if (fontHandle == null) { - font = ambient.Font; + if (fontHandle == null) + { + font = ambient.Font; fontHandle = new FontHandleWrapper(font); Properties.SetObject(PropFontHandleWrapper, fontHandle); @@ -2442,16 +2794,21 @@ internal IntPtr FontHandle { } } - protected int FontHeight { - get { + protected int FontHeight + { + get + { bool found; int fontHeight = Properties.GetInteger(PropFontHeight, out found); - if (found && fontHeight != -1) { + if (found && fontHeight != -1) + { return fontHeight; } - else { + else + { Font font = (Font)Properties.GetObject(PropFont); - if (font != null) { + if (font != null) + { fontHeight = font.Height; Properties.SetInteger(PropFontHeight, fontHeight); return fontHeight; @@ -2461,19 +2818,22 @@ protected int FontHeight { //ask the parent if it has the font height int localFontHeight = -1; - if (ParentInternal != null && ParentInternal.CanAccessProperties) { + if (ParentInternal != null && ParentInternal.CanAccessProperties) + { localFontHeight = ParentInternal.FontHeight; } //if we still have a bad value, then get the actual font height - if (localFontHeight == -1) { + if (localFontHeight == -1) + { localFontHeight = Font.Height; Properties.SetInteger(PropFontHeight, localFontHeight); } return localFontHeight; } - set { + set + { Properties.SetInteger(PropFontHeight, value); } } @@ -2486,25 +2846,31 @@ protected int FontHeight { DispId(NativeMethods.ActiveX.DISPID_FORECOLOR), SRDescription(nameof(SR.ControlForeColorDescr)) ] - public virtual Color ForeColor { - get { - Color color = Properties.GetColor(PropForeColor); - if (!color.IsEmpty) { - return color; + public virtual Color ForeColor + { + get + { + Color color = Properties.GetColor(PropForeColor); + if (!color.IsEmpty) + { + return color; } Control p = ParentInternal; - if (p != null && p.CanAccessProperties) { + if (p != null && p.CanAccessProperties) + { return p.ForeColor; } Color c = Color.Empty; - if (IsActiveX) { + if (IsActiveX) + { c = ActiveXAmbientForeColor; } - if (c.IsEmpty) { + if (c.IsEmpty) + { AmbientProperties ambient = AmbientPropertiesService; if (ambient != null) c = ambient.ForeColor; @@ -2516,24 +2882,29 @@ public virtual Color ForeColor { return DefaultForeColor; } - set { + set + { Color c = ForeColor; - if (!value.IsEmpty || Properties.ContainsObject(PropForeColor)) { + if (!value.IsEmpty || Properties.ContainsObject(PropForeColor)) + { Properties.SetColor(PropForeColor, value); } - if (!c.Equals(ForeColor)) { + if (!c.Equals(ForeColor)) + { OnForeColorChanged(EventArgs.Empty); } } } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnForeColorChangedDescr))] - public event EventHandler ForeColorChanged { + public event EventHandler ForeColorChanged + { add => Events.AddHandler(EventForeColor, value); remove => Events.RemoveHandler(EventForeColor, value); } - private Font GetParentFont() { + private Font GetParentFont() + { if (ParentInternal != null && ParentInternal.CanAccessProperties) return ParentInternal.Font; else @@ -2542,27 +2913,32 @@ private Font GetParentFont() { [EditorBrowsable(EditorBrowsableState.Advanced)] [SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces")] - public virtual Size GetPreferredSize(Size proposedSize) { + public virtual Size GetPreferredSize(Size proposedSize) + { Size prefSize; - if (GetState(STATE_DISPOSING| STATE_DISPOSED)) { + 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 + 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)) { + 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 (!cachedSize.IsEmpty && (proposedSize == LayoutUtils.MaxSize)) + { + #if DEBUG #if DEBUG_PREFERREDSIZE Size newPreferredSize = ApplySizeConstraints(GetPreferredSizeCore(proposedSize)); @@ -2574,27 +2950,30 @@ public virtual Size GetPreferredSize(Size proposedSize) { +". 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; +#endif + return cachedSize; } } - + CacheTextInternal = true; - try { + try + { prefSize = GetPreferredSizeCore(proposedSize); } - finally { + 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) { + if (GetState2(STATE2_USEPREFERREDSIZECACHE) && proposedSize == LayoutUtils.MaxSize) + { CommonProperties.xSetPreferredSizeCache(this, prefSize); } } @@ -2603,7 +2982,8 @@ public virtual Size GetPreferredSize(Size proposedSize) { // 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) { + internal virtual Size GetPreferredSizeCore(Size proposedSize) + { return CommonProperties.GetSpecifiedBounds(this).Size; } @@ -2617,11 +2997,14 @@ internal virtual Size GetPreferredSizeCore(Size proposedSize) { DispId(NativeMethods.ActiveX.DISPID_HWND), SRDescription(nameof(SR.ControlHandleDescr)) ] - public IntPtr Handle { - get { + public IntPtr Handle + { + get + { if (checkForIllegalCrossThreadCalls && !inCrossThreadSafeCall && - InvokeRequired) { + InvokeRequired) + { throw new InvalidOperationException(string.Format(SR.IllegalCrossThreadCall, Name)); } @@ -2635,8 +3018,10 @@ public IntPtr Handle { } } - internal IntPtr HandleInternal { - get { + internal IntPtr HandleInternal + { + get + { return window.Handle; } } @@ -2651,15 +3036,19 @@ internal IntPtr HandleInternal { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlHasChildrenDescr)) ] - public bool HasChildren { - get { + public bool HasChildren + { + get + { ControlCollection controls = (ControlCollection)Properties.GetObject(PropControlsCollection); return controls != null && controls.Count > 0; } } - internal virtual bool HasMenu { - get { + internal virtual bool HasMenu + { + get + { return false; } } @@ -2673,23 +3062,31 @@ internal virtual bool HasMenu { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlHeightDescr)) ] - public int Height { - get { + public int Height + { + get + { return height; } - set{ + set + { SetBounds(x, y, width, value, BoundsSpecified.Height); } } - internal bool HostedInWin32DialogManager { - get { - if (!GetState(STATE_CHECKEDHOST)) { + internal bool HostedInWin32DialogManager + { + get + { + if (!GetState(STATE_CHECKEDHOST)) + { Control topMost = TopMostParent; - if (this != topMost) { + if (this != topMost) + { SetState(STATE_HOSTEDINDIALOG, topMost.HostedInWin32DialogManager); } - else { + else + { IntPtr parentHandle = UnsafeNativeMethods.GetParent(new HandleRef(this, Handle)); IntPtr lastParentHandle = parentHandle; @@ -2697,14 +3094,17 @@ internal bool HostedInWin32DialogManager { SetState(STATE_HOSTEDINDIALOG, false); - while (parentHandle != IntPtr.Zero) { + while (parentHandle != IntPtr.Zero) + { int len = UnsafeNativeMethods.GetClassName(new HandleRef(null, lastParentHandle), null, 0); - if (len > sb.Capacity) { + if (len > sb.Capacity) + { sb.Capacity = len + 5; } UnsafeNativeMethods.GetClassName(new HandleRef(null, lastParentHandle), sb, sb.Capacity); - if (sb.ToString() == "#32770") { + if (sb.ToString() == "#32770") + { SetState(STATE_HOSTEDINDIALOG, true); break; } @@ -2730,22 +3130,28 @@ internal bool HostedInWin32DialogManager { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlHandleCreatedDescr)) ] - public bool IsHandleCreated { + public bool IsHandleCreated + { get { return window.Handle != IntPtr.Zero; } } /// /// Determines if layout is currently suspended. /// - internal bool IsLayoutSuspended { - get { + internal bool IsLayoutSuspended + { + get + { return layoutSuspendCount > 0; } } - internal bool IsWindowObscured { - get { - if (!IsHandleCreated || !Visible) { + internal bool IsWindowObscured + { + get + { + if (!IsHandleCreated || !Visible) + { return false; } @@ -2754,8 +3160,10 @@ internal bool IsWindowObscured { NativeMethods.RECT temp = new NativeMethods.RECT(); Region working; Control parent = ParentInternal; - if (parent != null) { - while (parent.ParentInternal != null ) { + if (parent != null) + { + while (parent.ParentInternal != null) + { parent = parent.ParentInternal; } } @@ -2763,38 +3171,46 @@ internal bool IsWindowObscured { UnsafeNativeMethods.GetWindowRect(new HandleRef(this, Handle), ref temp); working = new Region(Rectangle.FromLTRB(temp.left, temp.top, temp.right, temp.bottom)); - try { + try + { IntPtr prev; IntPtr next; IntPtr start; - if (parent != null) { + if (parent != null) + { start = parent.Handle; } - else { + else + { start = Handle; } for (prev = start; (next = UnsafeNativeMethods.GetWindow(new HandleRef(null, prev), NativeMethods.GW_HWNDPREV)) != IntPtr.Zero; - prev = next) { + 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))) { + if (SafeNativeMethods.IsWindowVisible(new HandleRef(null, next))) + { working.Exclude(current); } } Graphics g = CreateGraphics(); - try { + try + { emptyRegion = working.IsEmpty(g); } - finally { + finally + { g.Dispose(); } } - finally { + finally + { working.Dispose(); } @@ -2806,8 +3222,10 @@ internal bool IsWindowObscured { /// Returns the current value of the handle. This may be zero if the handle /// has not been created. /// - internal IntPtr InternalHandle { - get { + internal IntPtr InternalHandle + { + get + { if (!IsHandleCreated) { return IntPtr.Zero; @@ -2838,18 +3256,23 @@ internal IntPtr InternalHandle { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlInvokeRequiredDescr)) ] - public bool InvokeRequired { - get { + public bool InvokeRequired + { + get + { using (new MultithreadSafeCallScope()) { HandleRef hwnd; - if (IsHandleCreated) { + if (IsHandleCreated) + { hwnd = new HandleRef(this, Handle); } - else { + else + { Control marshalingControl = FindMarshalingControl(); - if (!marshalingControl.IsHandleCreated) { + if (!marshalingControl.IsHandleCreated) + { return false; } @@ -2859,7 +3282,7 @@ public bool InvokeRequired { int pid; int hwndThread = SafeNativeMethods.GetWindowThreadProcessId(hwnd, out pid); int currentThread = SafeNativeMethods.GetCurrentThreadId(); - return(hwndThread != currentThread); + return (hwndThread != currentThread); } } } @@ -2874,11 +3297,14 @@ public bool InvokeRequired { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlIsAccessibleDescr)) ] - public bool IsAccessible { - get { + public bool IsAccessible + { + get + { return GetState(STATE_ISACCESSIBLE); } - set { + set + { SetState(STATE_ISACCESSIBLE, value); } } @@ -2886,8 +3312,10 @@ public bool IsAccessible { /// /// Used to tell if this control is being hosted as an ActiveX control. /// - internal bool IsActiveX { - get { + internal bool IsActiveX + { + get + { return GetState2(STATE2_ISACTIVEX); } } @@ -2908,8 +3336,10 @@ internal virtual bool IsContainerControl /// /// Used to tell if this control is being hosted in IE. /// - internal bool IsIEParent { - get { + internal bool IsIEParent + { + get + { return IsActiveX ? ActiveXInstance.IsIE : false; } } @@ -2920,15 +3350,18 @@ internal bool IsIEParent { /// since we might call CreateParams here - you dig! /// [ - SRCategory(nameof(SR.CatLayout)), + SRCategory(nameof(SR.CatLayout)), Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - SRDescription(nameof(SR.IsMirroredDescr)) + SRDescription(nameof(SR.IsMirroredDescr)) ] - public bool IsMirrored { - get { - if (!IsHandleCreated) { + public bool IsMirrored + { + get + { + if (!IsHandleCreated) + { CreateParams cp = CreateParams; SetState(STATE_MIRRORED, (cp.ExStyle & NativeMethods.WS_EX_LAYOUTRTL) != 0); } @@ -2946,16 +3379,17 @@ internal virtual bool IsMnemonicsListenerAxSourced return false; } } - + /// /// Used to tell if this BackColor is Supported /// - private bool IsValidBackColor (Color c){ - if (!c.IsEmpty && !GetStyle(ControlStyles.SupportsTransparentBackColor) && c.A < 255) - { + private bool IsValidBackColor(Color c) + { + if (!c.IsEmpty && !GetStyle(ControlStyles.SupportsTransparentBackColor) && c.A < 255) + { return false; - } - return true; + } + return true; } @@ -2968,11 +3402,14 @@ private bool IsValidBackColor (Color c){ DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlLeftDescr)) ] - public int Left { - get { + public int Left + { + get + { return x; } - set { + set + { SetBounds(value, y, width, height, BoundsSpecified.X); } } @@ -2985,17 +3422,21 @@ public int Left { Localizable(true), SRDescription(nameof(SR.ControlLocationDescr)) ] - public Point Location { - get { + public Point Location + { + get + { return new Point(x, y); } - set { + set + { SetBounds(value.X, value.Y, width, height, BoundsSpecified.Location); } } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnLocationChangedDescr))] - public event EventHandler LocationChanged { + public event EventHandler LocationChanged + { add => Events.AddHandler(EventLocation, value); remove => Events.RemoveHandler(EventLocation, value); } @@ -3035,14 +3476,18 @@ public event EventHandler MarginChanged [Localizable(true)] [SRDescription(nameof(SR.ControlMaximumSizeDescr))] [AmbientValue(typeof(Size), "0, 0")] - public virtual Size MaximumSize { + public virtual Size MaximumSize + { get { return CommonProperties.GetMaximumSize(this, DefaultMaximumSize); } - set { - if (value == Size.Empty) { + set + { + if (value == Size.Empty) + { CommonProperties.ClearMaximumSize(this); Debug.Assert(MaximumSize == DefaultMaximumSize, "Error detected while resetting MaximumSize."); } - else if (value != 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."); @@ -3054,10 +3499,13 @@ public virtual Size MaximumSize { [SRCategory(nameof(SR.CatLayout))] [Localizable(true)] [SRDescription(nameof(SR.ControlMinimumSizeDescr))] - public virtual Size MinimumSize { + public virtual Size MinimumSize + { get { return CommonProperties.GetMinimumSize(this, DefaultMinimumSize); } - set { - if (value != MinimumSize) { + set + { + if (value != MinimumSize) + { // SetMinimumSize causes a layout as a side effect. CommonProperties.SetMinimumSize(this, value); } @@ -3069,14 +3517,19 @@ public virtual Size MinimumSize { /// Retrieves the current state of the modifier keys. This will check the /// current state of the shift, control, and alt keys. /// - public static Keys ModifierKeys { - get { + 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; + 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; } } @@ -3085,16 +3538,23 @@ public static Keys ModifierKeys { /// The current state of the mouse buttons. This will check the /// current state of the left, right, and middle mouse buttons. /// - public static MouseButtons MouseButtons { - get { + 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; + 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; } } @@ -3118,26 +3578,34 @@ public static Point MousePosition /// used as a key into the ControlCollection. /// [Browsable(false)] - public string Name { - get { + public string Name + { + get + { string name = (string)Properties.GetObject(PropName); - if (string.IsNullOrEmpty(name)) { - if (Site != null) { + if (string.IsNullOrEmpty(name)) + { + if (Site != null) + { name = Site.Name; } - if (name == null) { + if (name == null) + { name = string.Empty; } } return name; } - set { - if (string.IsNullOrEmpty(value)) { + set + { + if (string.IsNullOrEmpty(value)) + { Properties.SetObject(PropName, null); } - else { + else + { Properties.SetObject(PropName, value); } } @@ -3152,25 +3620,34 @@ public string Name { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlParentDescr)) ] - public Control Parent { - get { + public Control Parent + { + get + { return ParentInternal; } - set { + set + { ParentInternal = value; } } - internal virtual Control ParentInternal { - get { + internal virtual Control ParentInternal + { + get + { return parent; } - set { - if (parent != value) { - if (value != null) { + set + { + if (parent != value) + { + if (value != null) + { value.Controls.Add(this); } - else { + else + { parent.Controls.Remove(this); } } @@ -3185,10 +3662,12 @@ internal virtual Control ParentInternal { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlProductNameDescr)) ] - public string ProductName { - - - get { + public string ProductName + { + + + get + { return VersionInfo.ProductName; } } @@ -3201,10 +3680,12 @@ public string ProductName { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlProductVersionDescr)) ] - public string ProductVersion { - - - get { + public string ProductVersion + { + + + get + { return VersionInfo.ProductVersion; } } @@ -3214,15 +3695,19 @@ public string ProductVersion { /// whose value is not always set, you should store it in here to save /// space. /// - internal PropertyStore Properties { - get { + 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 { + internal Color RawBackColor + { + get + { return Properties.GetColor(PropBackColor); } } @@ -3237,30 +3722,39 @@ internal Color RawBackColor { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlRecreatingHandleDescr)) ] - public bool RecreatingHandle { - get { - return(state & STATE_RECREATE) != 0; + public bool RecreatingHandle + { + get + { + return (state & STATE_RECREATE) != 0; } } - internal virtual void AddReflectChild() { + internal virtual void AddReflectChild() + { } - internal virtual void RemoveReflectChild() { + internal virtual void RemoveReflectChild() + { } - private Control ReflectParent { - get { + private Control ReflectParent + { + get + { return reflectParent; } - set { - if (value != null) { + set + { + if (value != null) + { value.AddReflectChild(); } Control c = ReflectParent as Control; reflectParent = value; - if (c != null) { + if (c != null) + { c.RemoveReflectChild(); } } @@ -3276,38 +3770,50 @@ private Control ReflectParent { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlRegionDescr)) ] - public Region Region { - get { + public Region Region + { + get + { return (Region)Properties.GetObject(PropRegion); } - set { + set + { Region oldRegion = Region; - if (oldRegion != value) { + if (oldRegion != value) + { Properties.SetObject(PropRegion, value); - if (oldRegion != null) { + if (oldRegion != null) + { oldRegion.Dispose(); } - if (IsHandleCreated) { + if (IsHandleCreated) + { IntPtr regionHandle = IntPtr.Zero; - try { - if (value != null) { + try + { + if (value != null) + { regionHandle = GetHRgn(value); } - if (IsActiveX) { + if (IsActiveX) + { regionHandle = ActiveXMergeRegion(regionHandle); } - if (UnsafeNativeMethods.SetWindowRgn(new HandleRef(this, Handle), new HandleRef(this, regionHandle), SafeNativeMethods.IsWindowVisible(new HandleRef(this, Handle))) != 0) { + 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) { + finally + { + if (regionHandle != IntPtr.Zero) + { SafeNativeMethods.DeleteObject(new HandleRef(null, regionHandle)); } } @@ -3322,7 +3828,8 @@ public Region Region { /// Event fired when the value of Region property is changed on Control /// [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlRegionChangedDescr))] - public event EventHandler RegionChanged { + public event EventHandler RegionChanged + { add => Events.AddHandler(EventRegionChanged, value); remove => Events.RemoveHandler(EventRegionChanged, value); } @@ -3331,7 +3838,8 @@ public event EventHandler RegionChanged { [Obsolete("This property has been deprecated. Please use RightToLeft instead. http://go.microsoft.com/fwlink/?linkid=14202")] protected internal bool RenderRightToLeft { - get { + get + { return true; } } @@ -3339,15 +3847,18 @@ protected internal bool RenderRightToLeft /// /// Determines if the parent's background will be rendered on the label control. /// - internal bool RenderTransparent { - get { + internal bool RenderTransparent + { + get + { return GetStyle(ControlStyles.SupportsTransparentBackColor) && this.BackColor.A < 255; } } /// /// - private bool RenderColorTransparent(Color c) { + private bool RenderColorTransparent(Color c) + { return GetStyle(ControlStyles.SupportsTransparentBackColor) && c.A < 255; } @@ -3356,8 +3867,10 @@ private bool RenderColorTransparent(Color c) { /// 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. /// - internal virtual bool RenderTransparencyWithVisualStyles { - get { + internal virtual bool RenderTransparencyWithVisualStyles + { + get + { return false; } } @@ -3367,14 +3880,18 @@ internal virtual bool RenderTransparencyWithVisualStyles { /// need to be scaled until ScaleControl is called. They need to be scaled again /// if their bounds change after ScaleControl is called. /// - internal BoundsSpecified RequiredScaling { - get { - if ((requiredScaling & RequiredScalingEnabledMask) != 0) { + internal BoundsSpecified RequiredScaling + { + get + { + if ((requiredScaling & RequiredScalingEnabledMask) != 0) + { return (BoundsSpecified)(requiredScaling & RequiredScalingMask); } return BoundsSpecified.None; } - set { + set + { byte enableBit = (byte)(requiredScaling & RequiredScalingEnabledMask); requiredScaling = (byte)(((int)value & RequiredScalingMask) | enableBit); } @@ -3384,14 +3901,18 @@ internal BoundsSpecified RequiredScaling { /// Determines if the required scaling property is enabled. If not, /// RequiredScaling always returns None. /// - internal bool RequiredScalingEnabled { - get { + internal bool RequiredScalingEnabled + { + get + { return (requiredScaling & RequiredScalingEnabledMask) != 0; } - set { + set + { byte scaling = (byte)(requiredScaling & RequiredScalingMask); requiredScaling = scaling; - if (value) requiredScaling |= RequiredScalingEnabledMask; + if (value) + requiredScaling |= RequiredScalingEnabledMask; } } @@ -3401,12 +3922,15 @@ internal bool RequiredScalingEnabled { [ SRDescription(nameof(SR.ControlResizeRedrawDescr)) ] - protected bool ResizeRedraw { - get { - return GetStyle( ControlStyles.ResizeRedraw ); + protected bool ResizeRedraw + { + get + { + return GetStyle(ControlStyles.ResizeRedraw); } - set { - SetStyle( ControlStyles.ResizeRedraw, value ); + set + { + SetStyle(ControlStyles.ResizeRedraw, value); } } @@ -3419,8 +3943,10 @@ protected bool ResizeRedraw { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlRightDescr)) ] - public int Right { - get { + public int Right + { + get + { return x + width; } } @@ -3436,52 +3962,64 @@ public int Right { AmbientValue(RightToLeft.Inherit), SRDescription(nameof(SR.ControlRightToLeftDescr)) ] - public virtual RightToLeft RightToLeft { - get { + public virtual RightToLeft RightToLeft + { + get + { bool found; int rightToLeft = Properties.GetInteger(PropRightToLeft, out found); - if (!found) { + if (!found) + { rightToLeft = (int)RightToLeft.Inherit; } - if (((RightToLeft)rightToLeft) == RightToLeft.Inherit) { + if (((RightToLeft)rightToLeft) == RightToLeft.Inherit) + { Control parent = ParentInternal; - if (parent != null) { + if (parent != null) + { rightToLeft = (int)parent.RightToLeft; } - else { + else + { rightToLeft = (int)DefaultRightToLeft; } } return (RightToLeft)rightToLeft; } - set { + set + { //valid values are 0x0 to 0x2. - if (!ClientUtils.IsEnumValid(value, (int)value, (int)RightToLeft.No, (int)RightToLeft.Inherit)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)RightToLeft.No, (int)RightToLeft.Inherit)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(RightToLeft)); } RightToLeft oldValue = RightToLeft; - if (Properties.ContainsInteger(PropRightToLeft) || value != RightToLeft.Inherit) { + if (Properties.ContainsInteger(PropRightToLeft) || value != RightToLeft.Inherit) + { Properties.SetInteger(PropRightToLeft, (int)value); } - if (oldValue != RightToLeft) { + 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)) { + using (new LayoutTransaction(this, this, PropertyNames.RightToLeft)) + { OnRightToLeftChanged(EventArgs.Empty); } } } - } + } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnRightToLeftChangedDescr))] - public event EventHandler RightToLeftChanged { + public event EventHandler RightToLeftChanged + { add => Events.AddHandler(EventRightToLeft, value); remove => Events.RemoveHandler(EventRightToLeft, value); } @@ -3494,29 +4032,36 @@ public event EventHandler RightToLeftChanged { /// this property to provide a different value. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual bool ScaleChildren { - get { + protected virtual bool ScaleChildren + { + get + { return true; } } [EditorBrowsable(EditorBrowsableState.Advanced)] - public override ISite Site { - get { + public override ISite Site + { + get + { return base.Site; } - set { + set + { AmbientProperties oldAmbients = AmbientPropertiesService; AmbientProperties newAmbients = null; - if (value != null) { + if (value != null) + { newAmbients = (AmbientProperties)value.GetService(typeof(AmbientProperties)); } // If the ambients changed, compare each property. // - if (oldAmbients != newAmbients) { + if (oldAmbients != newAmbients) + { bool checkFont = !Properties.ContainsObject(PropFont); bool checkBackColor = !Properties.ContainsObject(PropBackColor); bool checkForeColor = !Properties.ContainsObject(PropForeColor); @@ -3527,39 +4072,48 @@ public override ISite Site { Color oldForeColor = Color.Empty; Cursor oldCursor = null; - if (checkFont) { + if (checkFont) + { oldFont = Font; } - if (checkBackColor) { + if (checkBackColor) + { oldBackColor = BackColor; } - if (checkForeColor) { + if (checkForeColor) + { oldForeColor = ForeColor; } - if (checkCursor) { + if (checkCursor) + { oldCursor = Cursor; } Properties.SetObject(PropAmbientPropertiesService, newAmbients); base.Site = value; - if (checkFont && !oldFont.Equals(Font)) { + if (checkFont && !oldFont.Equals(Font)) + { OnFontChanged(EventArgs.Empty); } - if (checkForeColor && !oldForeColor.Equals(ForeColor)) { + if (checkForeColor && !oldForeColor.Equals(ForeColor)) + { OnForeColorChanged(EventArgs.Empty); } - if (checkBackColor && !oldBackColor.Equals(BackColor)) { + if (checkBackColor && !oldBackColor.Equals(BackColor)) + { OnBackColorChanged(EventArgs.Empty); } - if (checkCursor && oldCursor.Equals(Cursor)) { + if (checkCursor && oldCursor.Equals(Cursor)) + { OnCursorChanged(EventArgs.Empty); } } - else { + else + { // If the ambients haven't changed, we just set a new site. // base.Site = value; @@ -3575,17 +4129,21 @@ public override ISite Site { Localizable(true), SRDescription(nameof(SR.ControlSizeDescr)) ] - public Size Size { - get { + public Size Size + { + get + { return new Size(width, height); } - set { + set + { SetBounds(x, y, value.Width, value.Height, BoundsSpecified.Size); } } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnSizeChangedDescr))] - public event EventHandler SizeChanged { + public event EventHandler SizeChanged + { add => Events.AddHandler(EventSize, value); remove => Events.RemoveHandler(EventSize, value); } @@ -3601,16 +4159,21 @@ public event EventHandler SizeChanged { MergableProperty(false), SRDescription(nameof(SR.ControlTabIndexDescr)) ] - public int TabIndex { - get { + public int TabIndex + { + get + { return tabIndex == -1 ? 0 : tabIndex; } - set { - if (value < 0) { + set + { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(TabIndex), value, 0)); } - if (tabIndex != value) { + if (tabIndex != value) + { tabIndex = value; OnTabIndexChanged(EventArgs.Empty); } @@ -3619,7 +4182,8 @@ public int TabIndex { [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnTabIndexChangedDescr))] - public event EventHandler TabIndexChanged { + public event EventHandler TabIndexChanged + { add => Events.AddHandler(EventTabIndex, value); remove => Events.RemoveHandler(EventTabIndex, value); } @@ -3634,33 +4198,43 @@ public event EventHandler TabIndexChanged { DispId(NativeMethods.ActiveX.DISPID_TABSTOP), SRDescription(nameof(SR.ControlTabStopDescr)) ] - public bool TabStop { - get { + public bool TabStop + { + get + { return TabStopInternal; } - set { - if (TabStop != value) { + set + { + if (TabStop != value) + { TabStopInternal = value; - if (IsHandleCreated) SetWindowStyle(NativeMethods.WS_TABSTOP, 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 { + internal bool TabStopInternal + { + get + { return (state & STATE_TABSTOP) != 0; } - set { - if (TabStopInternal != value) { + set + { + if (TabStopInternal != value) + { SetState(STATE_TABSTOP, value); } } } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnTabStopChangedDescr))] - public event EventHandler TabStopChanged { + public event EventHandler TabStopChanged + { add => Events.AddHandler(EventTabStop, value); remove => Events.RemoveHandler(EventTabStop, value); } @@ -3675,11 +4249,14 @@ public event EventHandler TabStopChanged { DefaultValue(null), TypeConverter(typeof(StringConverter)), ] - public object Tag { - get { + public object Tag + { + get + { return Properties.GetObject(PropUserData); } - set { + set + { Properties.SetObject(PropUserData, value); } } @@ -3694,46 +4271,58 @@ public object Tag { DispId(NativeMethods.ActiveX.DISPID_TEXT), SRDescription(nameof(SR.ControlTextDescr)) ] - public virtual string Text { - get { - if (CacheTextInternal) { - return(text == null) ? "" : text; + public virtual string Text + { + get + { + if (CacheTextInternal) + { + return (text == null) ? "" : text; } - else { + else + { return WindowText; } } - set { - if (value == null) { + set + { + if (value == null) + { value = string.Empty; } - if (value == Text) { + if (value == Text) + { return; } - if (CacheTextInternal) { + if (CacheTextInternal) + { text = value; } WindowText = value; OnTextChanged(EventArgs.Empty); - if( this.IsMnemonicsListenerAxSourced ){ - for( Control ctl = this; ctl != null; ctl = ctl.ParentInternal ) { + if (this.IsMnemonicsListenerAxSourced) + { + for (Control ctl = this; ctl != null; ctl = ctl.ParentInternal) + { ActiveXImpl activeXImpl = (ActiveXImpl)ctl.Properties.GetObject(PropActiveXImpl); - if( activeXImpl != null ) { + if (activeXImpl != null) + { activeXImpl.UpdateAccelTable(); break; } } } - + } } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnTextChangedDescr))] - public event EventHandler TextChanged { + public event EventHandler TextChanged + { add => Events.AddHandler(EventText, value); remove => Events.RemoveHandler(EventText, value); } @@ -3747,11 +4336,14 @@ public event EventHandler TextChanged { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlTopDescr)) ] - public int Top { - get { + public int Top + { + get + { return y; } - set { + set + { SetBounds(x, value, width, height, BoundsSpecified.Y); } } @@ -3767,26 +4359,34 @@ public int Top { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlTopLevelControlDescr)) ] - public Control TopLevelControl { - get { + public Control TopLevelControl + { + get + { return TopLevelControlInternal; } } - internal Control TopLevelControlInternal { - get { + internal Control TopLevelControlInternal + { + get + { Control control = this; - while (control != null && !control.GetTopLevel()) { + while (control != null && !control.GetTopLevel()) + { control = control.ParentInternal; } return control; } } - internal Control TopMostParent { - get { + internal Control TopMostParent + { + get + { Control control = this; - while (control.ParentInternal != null) { + while (control.ParentInternal != null) + { control = control.ParentInternal; } return control; @@ -3794,8 +4394,10 @@ internal Control TopMostParent { } - private BufferedGraphicsContext BufferContext { - get { + private BufferedGraphicsContext BufferContext + { + get + { //This auto upgraged v1 client to per-process doublebuffering logic // return BufferedGraphicsManager.Current; @@ -3807,10 +4409,13 @@ private BufferedGraphicsContext BufferContext { /// accelerators. This property is read-only. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - protected internal virtual bool ShowKeyboardCues { - get { + protected internal virtual bool ShowKeyboardCues + { + get + { // Controls in design mode always draw their accellerators. - if (!IsHandleCreated || DesignMode) { + 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 @@ -3818,7 +4423,7 @@ protected internal virtual bool ShowKeyboardCues { } // 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, @@ -3832,7 +4437,7 @@ protected internal virtual bool ShowKeyboardCues { // 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 @@ -3842,25 +4447,28 @@ protected internal virtual bool ShowKeyboardCues { // 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) { - 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 << 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), - Interop.WindowMessages.WM_CHANGEUISTATE, - (IntPtr)(actionMask | NativeMethods.UIS_SET), - IntPtr.Zero); - } - } - return (uiCuesState & UISTATE_KEYBOARD_CUES_MASK) == UISTATE_KEYBOARD_CUES_SHOW; + if ((uiCuesState & UISTATE_KEYBOARD_CUES_MASK) == 0) + { + 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 << 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), + Interop.WindowMessages.WM_CHANGEUISTATE, + (IntPtr)(actionMask | NativeMethods.UIS_SET), + IntPtr.Zero); + } + } + return (uiCuesState & UISTATE_KEYBOARD_CUES_MASK) == UISTATE_KEYBOARD_CUES_SHOW; } } @@ -3869,9 +4477,12 @@ protected internal virtual bool ShowKeyboardCues { /// rectangles. This property is read-only. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - protected internal virtual bool ShowFocusCues { - get { - if (!IsHandleCreated) { + 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 @@ -3880,11 +4491,14 @@ protected internal virtual bool ShowFocusCues { // See "How this all works" in ShowKeyboardCues - if ((uiCuesState & UISTATE_FOCUS_CUES_MASK) == 0) { - if (SystemInformation.MenuAccessKeysUnderlined) { + if ((uiCuesState & UISTATE_FOCUS_CUES_MASK) == 0) + { + if (SystemInformation.MenuAccessKeysUnderlined) + { uiCuesState |= UISTATE_FOCUS_CUES_SHOW; } - else { + else + { uiCuesState |= UISTATE_FOCUS_CUES_HIDDEN; // if we're in the hidden state, we need to manufacture an update message so everyone knows it. @@ -3906,8 +4520,10 @@ protected internal virtual bool ShowFocusCues { // The parameter used in the call to ShowWindow for this control // - internal virtual int ShowParams { - get { + internal virtual int ShowParams + { + get + { return NativeMethods.SW_SHOW; } } @@ -3924,18 +4540,23 @@ internal virtual int ShowParams { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ControlUseWaitCursorDescr)), ] - public bool UseWaitCursor { + public bool UseWaitCursor + { get { return GetState(STATE_USEWAITCURSOR); } - set { - if (GetState(STATE_USEWAITCURSOR) != value) { + set + { + if (GetState(STATE_USEWAITCURSOR) != value) + { SetState(STATE_USEWAITCURSOR, value); ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection != null) { + 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++) { + for (int i = 0; i < controlsCollection.Count; i++) + { controlsCollection[i].UseWaitCursor = value; } } @@ -3950,20 +4571,26 @@ public bool UseWaitCursor { /// 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). /// - internal bool UseCompatibleTextRenderingInt { - get{ - if (Properties.ContainsInteger(PropUseCompatibleTextRendering)){ + internal bool UseCompatibleTextRenderingInt + { + get + { + if (Properties.ContainsInteger(PropUseCompatibleTextRendering)) + { bool found; int value = Properties.GetInteger(PropUseCompatibleTextRendering, out found); - if( found ){ + if (found) + { return value == 1; } } return Control.UseCompatibleTextRenderingDefault; } - set{ - if( SupportsUseCompatibleTextRendering && UseCompatibleTextRenderingInt != value ){ + 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); @@ -3977,16 +4604,21 @@ internal bool UseCompatibleTextRenderingInt { /// 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. /// - internal virtual bool SupportsUseCompatibleTextRendering { - get { + internal virtual bool SupportsUseCompatibleTextRendering + { + get + { return false; } } - private ControlVersionInfo VersionInfo { - get { + private ControlVersionInfo VersionInfo + { + get + { ControlVersionInfo info = (ControlVersionInfo)Properties.GetObject(PropControlVersionInfo); - if (info == null) { + if (info == null) + { info = new ControlVersionInfo(this); Properties.SetObject(PropControlVersionInfo, info); } @@ -4002,11 +4634,14 @@ private ControlVersionInfo VersionInfo { Localizable(true), SRDescription(nameof(SR.ControlVisibleDescr)) ] - public bool Visible { - get { + public bool Visible + { + get + { return GetVisibleCore(); } - set { + set + { SetVisibleCore(value); } } @@ -4015,7 +4650,8 @@ public bool Visible { /// Occurs when the control becomes visible. /// [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnVisibleChangedDescr))] - public event EventHandler VisibleChanged { + public event EventHandler VisibleChanged + { add => Events.AddHandler(EventVisible, value); remove => Events.RemoveHandler(EventVisible, value); } @@ -4023,10 +4659,12 @@ public event EventHandler VisibleChanged { /// /// Wait for the wait handle to receive a signal: throw an exception if the thread is no longer with us. /// - private void WaitForWaitHandle(WaitHandle waitHandle) { + private void WaitForWaitHandle(WaitHandle waitHandle) + { int threadId = CreateThreadId; Application.ThreadContext ctx = Application.ThreadContext.FromId(threadId); - if (ctx == null) { + if (ctx == null) + { // Couldn't find the thread context, so we don't know the state. We shouldn't throw. return; } @@ -4035,26 +4673,33 @@ private void WaitForWaitHandle(WaitHandle waitHandle) { // 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) { + while (!processed) + { //Get the thread's exit code, if we found the thread as expected - if (threadHandle != null) { + 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) || + if ((returnValue && exitCode != NativeMethods.STILL_ACTIVE) || (!returnValue && Marshal.GetLastWin32Error() == NativeMethods.ERROR_INVALID_HANDLE) || - AppDomain.CurrentDomain.IsFinalizingForUnload()) { - if (waitHandle.WaitOne(1, false)) { + AppDomain.CurrentDomain.IsFinalizingForUnload()) + { + if (waitHandle.WaitOne(1, false)) + { break; } throw new InvalidAsynchronousStateException(SR.ThreadNoLongerValid); } - if (IsDisposed && threadCallbackList != null && threadCallbackList.Count > 0) { - lock (threadCallbackList) { + if (IsDisposed && threadCallbackList != null && threadCallbackList.Count > 0) + { + lock (threadCallbackList) + { Exception ex = new System.ObjectDisposedException(GetType().Name); - while (threadCallbackList.Count > 0) { + while (threadCallbackList.Count > 0) + { ThreadMethodEntry entry = (ThreadMethodEntry)threadCallbackList.Dequeue(); entry.exception = ex; entry.Complete(); @@ -4076,11 +4721,14 @@ private void WaitForWaitHandle(WaitHandle waitHandle) { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlWidthDescr)) ] - public int Width { - get { + public int Width + { + get + { return width; } - set { + set + { SetBounds(x, y, value, height, BoundsSpecified.Width); } } @@ -4088,11 +4736,14 @@ public int Width { /// /// The current exStyle of the hWnd /// - private int WindowExStyle { - get { + private int WindowExStyle + { + get + { return unchecked((int)(long)UnsafeNativeMethods.GetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_EXSTYLE)); } - set { + set + { UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_EXSTYLE, new HandleRef(null, (IntPtr)value)); } } @@ -4100,11 +4751,14 @@ private int WindowExStyle { /// /// The current style of the hWnd /// - internal int WindowStyle { - get { + internal int WindowStyle + { + get + { return unchecked((int)(long)UnsafeNativeMethods.GetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_STYLE)); } - set { + set + { UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_STYLE, new HandleRef(null, (IntPtr)value)); } } @@ -4118,11 +4772,14 @@ internal int WindowStyle { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlWindowTargetDescr)) ] - public IWindowTarget WindowTarget { - get { + public IWindowTarget WindowTarget + { + get + { return window.WindowTarget; } - set { + set + { window.WindowTarget = value; } } @@ -4134,14 +4791,19 @@ public IWindowTarget WindowTarget { /// 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. /// - internal virtual string WindowText { - get { + internal virtual string WindowText + { + get + { - if (!IsHandleCreated) { - if (text == null) { + if (!IsHandleCreated) + { + if (text == null) + { return ""; } - else { + else + { return text; } } @@ -4151,17 +4813,24 @@ internal virtual string WindowText { return Interop.User32.GetWindowText(new HandleRef(window, Handle)); } } - set { - if (value == null) value = string.Empty; - if (!WindowText.Equals(value)) { - if (IsHandleCreated) { + set + { + if (value == null) + value = string.Empty; + if (!WindowText.Equals(value)) + { + if (IsHandleCreated) + { Interop.User32.SetWindowTextW(new HandleRef(window, Handle), value); } - else { - if (value.Length == 0) { + else + { + if (value.Length == 0) + { text = null; } - else { + else + { text = value; } } @@ -4175,7 +4844,8 @@ internal virtual string WindowText { /// Occurs when the control is clicked. /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ControlOnClickDescr))] - public event EventHandler Click { + public event EventHandler Click + { add => Events.AddHandler(EventClick, value); remove => Events.RemoveHandler(EventClick, value); } @@ -4191,7 +4861,8 @@ public event EventHandler Click { EditorBrowsable(EditorBrowsableState.Advanced), SRDescription(nameof(SR.ControlOnControlAddedDescr)) ] - public event ControlEventHandler ControlAdded { + public event ControlEventHandler ControlAdded + { add => Events.AddHandler(EventControlAdded, value); remove => Events.RemoveHandler(EventControlAdded, value); } @@ -4206,40 +4877,46 @@ public event ControlEventHandler ControlAdded { EditorBrowsable(EditorBrowsableState.Advanced), SRDescription(nameof(SR.ControlOnControlRemovedDescr)) ] - public event ControlEventHandler ControlRemoved { + public event ControlEventHandler ControlRemoved + { add => Events.AddHandler(EventControlRemoved, value); remove => Events.RemoveHandler(EventControlRemoved, value); } [SRCategory(nameof(SR.CatDragDrop)), SRDescription(nameof(SR.ControlOnDragDropDescr))] - public event DragEventHandler DragDrop { + public event DragEventHandler DragDrop + { add => Events.AddHandler(EventDragDrop, value); remove => Events.RemoveHandler(EventDragDrop, value); } [SRCategory(nameof(SR.CatDragDrop)), SRDescription(nameof(SR.ControlOnDragEnterDescr))] - public event DragEventHandler DragEnter { + public event DragEventHandler DragEnter + { add => Events.AddHandler(EventDragEnter, value); remove => Events.RemoveHandler(EventDragEnter, value); } [SRCategory(nameof(SR.CatDragDrop)), SRDescription(nameof(SR.ControlOnDragOverDescr))] - public event DragEventHandler DragOver { + public event DragEventHandler DragOver + { add => Events.AddHandler(EventDragOver, value); remove => Events.RemoveHandler(EventDragOver, value); } [SRCategory(nameof(SR.CatDragDrop)), SRDescription(nameof(SR.ControlOnDragLeaveDescr))] - public event EventHandler DragLeave { + public event EventHandler DragLeave + { add => Events.AddHandler(EventDragLeave, value); remove => Events.RemoveHandler(EventDragLeave, value); } [SRCategory(nameof(SR.CatDragDrop)), SRDescription(nameof(SR.ControlOnGiveFeedbackDescr))] - public event GiveFeedbackEventHandler GiveFeedback { + public event GiveFeedbackEventHandler GiveFeedback + { add => Events.AddHandler(EventGiveFeedback, value); remove => Events.RemoveHandler(EventGiveFeedback, value); } @@ -4249,7 +4926,8 @@ public event GiveFeedbackEventHandler GiveFeedback { /// Occurs when a handle is created for the control. /// [SRCategory(nameof(SR.CatPrivate)), Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), SRDescription(nameof(SR.ControlOnCreateHandleDescr))] - public event EventHandler HandleCreated { + public event EventHandler HandleCreated + { add => Events.AddHandler(EventHandleCreated, value); remove => Events.RemoveHandler(EventHandleCreated, value); } @@ -4259,27 +4937,31 @@ public event EventHandler HandleCreated { /// Occurs when the control's handle is destroyed. /// [SRCategory(nameof(SR.CatPrivate)), Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), SRDescription(nameof(SR.ControlOnDestroyHandleDescr))] - public event EventHandler HandleDestroyed { + public event EventHandler HandleDestroyed + { add => Events.AddHandler(EventHandleDestroyed, value); remove => Events.RemoveHandler(EventHandleDestroyed, value); } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ControlOnHelpDescr))] - public event HelpEventHandler HelpRequested { + public event HelpEventHandler HelpRequested + { add => Events.AddHandler(EventHelpRequested, value); remove => Events.RemoveHandler(EventHelpRequested, value); } [SRCategory(nameof(SR.CatAppearance)), Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), SRDescription(nameof(SR.ControlOnInvalidateDescr))] - public event InvalidateEventHandler Invalidated { + public event InvalidateEventHandler Invalidated + { add => Events.AddHandler(EventInvalidated, value); remove => Events.RemoveHandler(EventInvalidated, value); } [Browsable(false)] - public Size PreferredSize { + public Size PreferredSize + { get { return GetPreferredSize(Size.Empty); } } @@ -4288,50 +4970,59 @@ public Size PreferredSize { SRCategory(nameof(SR.CatLayout)), Localizable(true) ] - public Padding Padding { + public Padding Padding + { get { return CommonProperties.GetPadding(this, DefaultPadding); } - set { - if (value != Padding) { + 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)) { + using (new LayoutTransaction(ParentInternal, this, PropertyNames.Padding)) + { OnPaddingChanged(EventArgs.Empty); } - if(GetState(STATE_LAYOUTISDIRTY)) { + 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); + LayoutTransaction.DoLayout(this, this, PropertyNames.Padding); } } } } [SRCategory(nameof(SR.CatLayout)), SRDescription(nameof(SR.ControlOnPaddingChangedDescr))] - public event EventHandler PaddingChanged { + public event EventHandler PaddingChanged + { add => Events.AddHandler(EventPaddingChanged, value); remove => Events.RemoveHandler(EventPaddingChanged, value); } [SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ControlOnPaintDescr))] - public event PaintEventHandler Paint { + public event PaintEventHandler Paint + { add => Events.AddHandler(EventPaint, value); remove => Events.RemoveHandler(EventPaint, value); } [SRCategory(nameof(SR.CatDragDrop)), SRDescription(nameof(SR.ControlOnQueryContinueDragDescr))] - public event QueryContinueDragEventHandler QueryContinueDrag { + public event QueryContinueDragEventHandler QueryContinueDrag + { add => Events.AddHandler(EventQueryContinueDrag, value); remove => Events.RemoveHandler(EventQueryContinueDrag, value); } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ControlOnQueryAccessibilityHelpDescr))] - public event QueryAccessibilityHelpEventHandler QueryAccessibilityHelp { + public event QueryAccessibilityHelpEventHandler QueryAccessibilityHelp + { add => Events.AddHandler(EventQueryAccessibilityHelp, value); remove => Events.RemoveHandler(EventQueryAccessibilityHelp, value); } @@ -4340,7 +5031,8 @@ public event QueryAccessibilityHelpEventHandler QueryAccessibilityHelp { /// Occurs when the control is double clicked. /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ControlOnDoubleClickDescr))] - public event EventHandler DoubleClick { + public event EventHandler DoubleClick + { add => Events.AddHandler(EventDoubleClick, value); remove => Events.RemoveHandler(EventDoubleClick, value); } @@ -4349,7 +5041,8 @@ public event EventHandler DoubleClick { /// Occurs when the control is entered. /// [SRCategory(nameof(SR.CatFocus)), SRDescription(nameof(SR.ControlOnEnterDescr))] - public event EventHandler Enter { + public event EventHandler Enter + { add => Events.AddHandler(EventEnter, value); remove => Events.RemoveHandler(EventEnter, value); } @@ -4358,7 +5051,8 @@ public event EventHandler Enter { /// Occurs when the control receives focus. /// [SRCategory(nameof(SR.CatFocus)), SRDescription(nameof(SR.ControlOnGotFocusDescr)), Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public event EventHandler GotFocus { + public event EventHandler GotFocus + { add => Events.AddHandler(EventGotFocus, value); remove => Events.RemoveHandler(EventGotFocus, value); } @@ -4367,7 +5061,8 @@ public event EventHandler GotFocus { /// Occurs when a key is pressed down while the control has focus. /// [SRCategory(nameof(SR.CatKey)), SRDescription(nameof(SR.ControlOnKeyDownDescr))] - public event KeyEventHandler KeyDown { + public event KeyEventHandler KeyDown + { add => Events.AddHandler(EventKeyDown, value); remove => Events.RemoveHandler(EventKeyDown, value); } @@ -4377,7 +5072,8 @@ public event KeyEventHandler KeyDown { /// Occurs when a key is pressed while the control has focus. /// [SRCategory(nameof(SR.CatKey)), SRDescription(nameof(SR.ControlOnKeyPressDescr))] - public event KeyPressEventHandler KeyPress { + public event KeyPressEventHandler KeyPress + { add => Events.AddHandler(EventKeyPress, value); remove => Events.RemoveHandler(EventKeyPress, value); } @@ -4387,7 +5083,8 @@ public event KeyPressEventHandler KeyPress { /// Occurs when a key is released while the control has focus. /// [SRCategory(nameof(SR.CatKey)), SRDescription(nameof(SR.ControlOnKeyUpDescr))] - public event KeyEventHandler KeyUp { + public event KeyEventHandler KeyUp + { add => Events.AddHandler(EventKeyUp, value); remove => Events.RemoveHandler(EventKeyUp, value); } @@ -4396,7 +5093,8 @@ public event KeyEventHandler KeyUp { /// /// [SRCategory(nameof(SR.CatLayout)), SRDescription(nameof(SR.ControlOnLayoutDescr))] - public event LayoutEventHandler Layout { + public event LayoutEventHandler Layout + { add => Events.AddHandler(EventLayout, value); remove => Events.RemoveHandler(EventLayout, value); } @@ -4406,7 +5104,8 @@ public event LayoutEventHandler Layout { /// Occurs when the control is left. /// [SRCategory(nameof(SR.CatFocus)), SRDescription(nameof(SR.ControlOnLeaveDescr))] - public event EventHandler Leave { + public event EventHandler Leave + { add => Events.AddHandler(EventLeave, value); remove => Events.RemoveHandler(EventLeave, value); } @@ -4415,7 +5114,8 @@ public event EventHandler Leave { /// Occurs when the control loses focus. /// [SRCategory(nameof(SR.CatFocus)), SRDescription(nameof(SR.ControlOnLostFocusDescr)), Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public event EventHandler LostFocus { + public event EventHandler LostFocus + { add => Events.AddHandler(EventLostFocus, value); remove => Events.RemoveHandler(EventLostFocus, value); } @@ -4424,7 +5124,8 @@ public event EventHandler LostFocus { /// Occurs when the control is mouse clicked. /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ControlOnMouseClickDescr))] - public event MouseEventHandler MouseClick { + public event MouseEventHandler MouseClick + { add => Events.AddHandler(EventMouseClick, value); remove => Events.RemoveHandler(EventMouseClick, value); } @@ -4434,7 +5135,8 @@ public event MouseEventHandler MouseClick { /// Occurs when the control is mouse double clicked. /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ControlOnMouseDoubleClickDescr))] - public event MouseEventHandler MouseDoubleClick { + public event MouseEventHandler MouseDoubleClick + { add => Events.AddHandler(EventMouseDoubleClick, value); remove => Events.RemoveHandler(EventMouseDoubleClick, value); } @@ -4444,7 +5146,8 @@ public event MouseEventHandler MouseDoubleClick { /// Occurs when the control loses mouse Capture. /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ControlOnMouseCaptureChangedDescr))] - public event EventHandler MouseCaptureChanged { + public event EventHandler MouseCaptureChanged + { add => Events.AddHandler(EventMouseCaptureChanged, value); remove => Events.RemoveHandler(EventMouseCaptureChanged, value); } @@ -4454,7 +5157,8 @@ public event EventHandler MouseCaptureChanged { /// pressed. /// [SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.ControlOnMouseDownDescr))] - public event MouseEventHandler MouseDown { + public event MouseEventHandler MouseDown + { add => Events.AddHandler(EventMouseDown, value); remove => Events.RemoveHandler(EventMouseDown, value); } @@ -4464,7 +5168,8 @@ public event MouseEventHandler MouseDown { /// Occurs when the mouse pointer enters the control. /// [SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.ControlOnMouseEnterDescr))] - public event EventHandler MouseEnter { + public event EventHandler MouseEnter + { add => Events.AddHandler(EventMouseEnter, value); remove => Events.RemoveHandler(EventMouseEnter, value); } @@ -4473,7 +5178,8 @@ public event EventHandler MouseEnter { /// Occurs when the mouse pointer leaves the control. /// [SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.ControlOnMouseLeaveDescr))] - public event EventHandler MouseLeave { + public event EventHandler MouseLeave + { add => Events.AddHandler(EventMouseLeave, value); remove => Events.RemoveHandler(EventMouseLeave, value); } @@ -4485,7 +5191,8 @@ public event EventHandler MouseLeave { /// /// [SRCategory(nameof(SR.CatLayout)), SRDescription(nameof(SR.ControlOnDpiChangedBeforeParentDescr))] - public event EventHandler DpiChangedBeforeParent { + public event EventHandler DpiChangedBeforeParent + { add => Events.AddHandler(EventDpiChangedBeforeParent, value); remove => Events.RemoveHandler(EventDpiChangedBeforeParent, value); } @@ -4497,7 +5204,8 @@ public event EventHandler DpiChangedBeforeParent { /// /// [SRCategory(nameof(SR.CatLayout)), SRDescription(nameof(SR.ControlOnDpiChangedAfterParentDescr))] - public event EventHandler DpiChangedAfterParent { + public event EventHandler DpiChangedAfterParent + { add => Events.AddHandler(EventDpiChangedAfterParent, value); remove => Events.RemoveHandler(EventDpiChangedAfterParent, value); } @@ -4506,7 +5214,8 @@ public event EventHandler DpiChangedAfterParent { /// Occurs when the mouse pointer hovers over the contro. /// [SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.ControlOnMouseHoverDescr))] - public event EventHandler MouseHover { + public event EventHandler MouseHover + { add => Events.AddHandler(EventMouseHover, value); remove => Events.RemoveHandler(EventMouseHover, value); } @@ -4516,7 +5225,8 @@ public event EventHandler MouseHover { /// Occurs when the mouse pointer is moved over the control. /// [SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.ControlOnMouseMoveDescr))] - public event MouseEventHandler MouseMove { + public event MouseEventHandler MouseMove + { add => Events.AddHandler(EventMouseMove, value); remove => Events.RemoveHandler(EventMouseMove, value); } @@ -4526,7 +5236,8 @@ public event MouseEventHandler MouseMove { /// Occurs when the mouse pointer is over the control and a mouse button is released. /// [SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.ControlOnMouseUpDescr))] - public event MouseEventHandler MouseUp { + public event MouseEventHandler MouseUp + { add => Events.AddHandler(EventMouseUp, value); remove => Events.RemoveHandler(EventMouseUp, value); } @@ -4536,7 +5247,8 @@ public event MouseEventHandler MouseUp { /// Occurs when the mouse wheel moves while the control has focus. /// [SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.ControlOnMouseWheelDescr)), Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public event MouseEventHandler MouseWheel { + public event MouseEventHandler MouseWheel + { add => Events.AddHandler(EventMouseWheel, value); remove => Events.RemoveHandler(EventMouseWheel, value); } @@ -4546,7 +5258,8 @@ public event MouseEventHandler MouseWheel { /// Occurs when the control is moved. /// [SRCategory(nameof(SR.CatLayout)), SRDescription(nameof(SR.ControlOnMoveDescr))] - public event EventHandler Move { + public event EventHandler Move + { add => Events.AddHandler(EventMove, value); remove => Events.RemoveHandler(EventMove, value); } @@ -4555,7 +5268,8 @@ public event EventHandler Move { /// Raised to preview a key down event /// [SRCategory(nameof(SR.CatKey)), SRDescription(nameof(SR.PreviewKeyDownDescr))] - public event PreviewKeyDownEventHandler PreviewKeyDown { + public event PreviewKeyDownEventHandler PreviewKeyDown + { add => Events.AddHandler(EventPreviewKeyDown, value); remove => Events.RemoveHandler(EventPreviewKeyDown, value); } @@ -4566,25 +5280,29 @@ public event PreviewKeyDownEventHandler PreviewKeyDown { /// [SRCategory(nameof(SR.CatLayout)), SRDescription(nameof(SR.ControlOnResizeDescr)), EditorBrowsable(EditorBrowsableState.Advanced)] - public event EventHandler Resize { + public event EventHandler Resize + { add => Events.AddHandler(EventResize, value); remove => Events.RemoveHandler(EventResize, value); } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ControlOnChangeUICuesDescr))] - public event UICuesEventHandler ChangeUICues { + public event UICuesEventHandler ChangeUICues + { add => Events.AddHandler(EventChangeUICues, value); remove => Events.RemoveHandler(EventChangeUICues, value); } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ControlOnStyleChangedDescr))] - public event EventHandler StyleChanged { + public event EventHandler StyleChanged + { add => Events.AddHandler(EventStyleChanged, value); remove => Events.RemoveHandler(EventStyleChanged, value); } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ControlOnSystemColorsChangedDescr))] - public event EventHandler SystemColorsChanged { + public event EventHandler SystemColorsChanged + { add => Events.AddHandler(EventSystemColorsChanged, value); remove => Events.RemoveHandler(EventSystemColorsChanged, value); } @@ -4593,7 +5311,8 @@ public event EventHandler SystemColorsChanged { /// Occurs when the control is validating. /// [SRCategory(nameof(SR.CatFocus)), SRDescription(nameof(SR.ControlOnValidatingDescr))] - public event CancelEventHandler Validating { + public event CancelEventHandler Validating + { add => Events.AddHandler(EventValidating, value); remove => Events.RemoveHandler(EventValidating, value); } @@ -4603,19 +5322,23 @@ public event CancelEventHandler Validating { /// Occurs when the control is done validating. /// [SRCategory(nameof(SR.CatFocus)), SRDescription(nameof(SR.ControlOnValidatedDescr))] - public event EventHandler Validated { + public event EventHandler Validated + { add => Events.AddHandler(EventValidated, value); remove => Events.RemoveHandler(EventValidated, value); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected internal void AccessibilityNotifyClients(AccessibleEvents accEvent, int childID) { + protected internal void AccessibilityNotifyClients(AccessibleEvents accEvent, int childID) + { AccessibilityNotifyClients(accEvent, NativeMethods.OBJID_CLIENT, childID); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected void AccessibilityNotifyClients(AccessibleEvents accEvent, int objectID, int childID) { - if (IsHandleCreated) { + protected void AccessibilityNotifyClients(AccessibleEvents accEvent, int objectID, int childID) + { + if (IsHandleCreated) + { UnsafeNativeMethods.NotifyWinEvent((int)accEvent, new HandleRef(this, Handle), objectID, childID + 1); } } @@ -4624,9 +5347,10 @@ protected void AccessibilityNotifyClients(AccessibleEvents accEvent, int objectI /// Helper method for retrieving an ActiveX property. We abstract these /// to another method so we do not force JIT the ActiveX codebase. /// - - - private IntPtr ActiveXMergeRegion(IntPtr region) { + + + private IntPtr ActiveXMergeRegion(IntPtr region) + { return ActiveXInstance.MergeRegion(region); } @@ -4634,7 +5358,8 @@ private IntPtr ActiveXMergeRegion(IntPtr region) { /// Helper method for retrieving an ActiveX property. We abstract these /// to another method so we do not force JIT the ActiveX codebase. /// - private void ActiveXOnFocus(bool focus) { + private void ActiveXOnFocus(bool focus) + { ActiveXInstance.OnFocus(focus); } @@ -4642,11 +5367,12 @@ private void ActiveXOnFocus(bool focus) { /// Helper method for retrieving an ActiveX property. We abstract these /// to another method so we do not force JIT the ActiveX codebase. /// - private void ActiveXViewChanged() { + private void ActiveXViewChanged() + { ActiveXInstance.ViewChangedInternal(); } - #if ACTIVEX_SOURCING +#if ACTIVEX_SOURCING // // This has been cut from the product. @@ -4714,17 +5440,18 @@ protected static void ActiveXRegister(Type type) { clsidKey.Close(); } - #endif +#endif /// /// Helper method for retrieving an ActiveX property. We abstract these /// to another method so we do not force JIT the ActiveX codebase. /// - private void ActiveXUpdateBounds(ref int x, ref int y, ref int width, ref int height, int flags) { + 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 +#if ACTIVEX_SOURCING // // This has been cut from the product. @@ -4781,20 +5508,23 @@ protected static void ActiveXUnregister(Type type) { } } } - #endif +#endif /// /// Assigns a new parent control. Sends out the appropriate property change /// notifications for properties that are affected by the change of parent. /// - internal virtual void AssignParent(Control value) { + internal virtual void AssignParent(Control value) + { // Adopt the parent's required scaling bits - if (value != null) { + if (value != null) + { RequiredScalingEnabled = value.RequiredScalingEnabled; } - if (CanAccessProperties) { + if (CanAccessProperties) + { // Store the old values for these properties // Font oldFont = Font; @@ -4807,38 +5537,46 @@ internal virtual void AssignParent(Control value) { // Update the parent // parent = value; - OnParentChanged(EventArgs.Empty); + OnParentChanged(EventArgs.Empty); - if (GetAnyDisposingInHierarchy()) { + if (GetAnyDisposingInHierarchy()) + { return; - } + } // Compare property values with new parent to old values // - if (oldEnabled != Enabled) { + if (oldEnabled != Enabled) + { OnEnabledChanged(EventArgs.Empty); } // 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())) { + + if (oldVisible != newVisible && !(!oldVisible && newVisible && parent == null && !GetTopLevel())) + { OnVisibleChanged(EventArgs.Empty); } - if (!oldFont.Equals(Font)) { + if (!oldFont.Equals(Font)) + { OnFontChanged(EventArgs.Empty); } - if (!oldForeColor.Equals(ForeColor)) { + if (!oldForeColor.Equals(ForeColor)) + { OnForeColorChanged(EventArgs.Empty); } - if (!oldBackColor.Equals(BackColor)) { + if (!oldBackColor.Equals(BackColor)) + { OnBackColorChanged(EventArgs.Empty); } - if (oldRtl != RightToLeft) { + if (oldRtl != RightToLeft) + { OnRightToLeftChanged(EventArgs.Empty); } - if (Properties.GetObject(PropBindingManager) == null && this.Created) { + 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 @@ -4848,17 +5586,20 @@ internal virtual void AssignParent(Control value) { OnBindingContextChanged(EventArgs.Empty); } } - else { + else + { parent = value; OnParentChanged(EventArgs.Empty); } SetState(STATE_CHECKEDHOST, false); - if (ParentInternal != null) ParentInternal.LayoutEngine.InitLayout(this, BoundsSpecified.All); + if (ParentInternal != null) + ParentInternal.LayoutEngine.InitLayout(this, BoundsSpecified.All); } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnParentChangedDescr))] - public event EventHandler ParentChanged { + public event EventHandler ParentChanged + { add => Events.AddHandler(EventParent, value); remove => Events.RemoveHandler(EventParent, value); } @@ -4880,7 +5621,8 @@ public event EventHandler ParentChanged { /// the call to the control's thread. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public IAsyncResult BeginInvoke(Delegate method) { + public IAsyncResult BeginInvoke(Delegate method) + { return BeginInvoke(method, null); } @@ -4900,30 +5642,38 @@ public IAsyncResult BeginInvoke(Delegate method) { /// For all other method calls, you should use one of the invoke methods to marshal /// the call to the control's thread. /// - [EditorBrowsable(EditorBrowsableState.Advanced)] - public IAsyncResult BeginInvoke(Delegate method, params object[] args) { - using (new MultithreadSafeCallScope()) { + [EditorBrowsable(EditorBrowsableState.Advanced)] + public IAsyncResult BeginInvoke(Delegate method, params object[] args) + { + using (new MultithreadSafeCallScope()) + { Control marshaler = FindMarshalingControl(); - return(IAsyncResult)marshaler.MarshaledInvoke(this, method, args, false); + return (IAsyncResult)marshaler.MarshaledInvoke(this, method, args, false); } } - internal void BeginUpdateInternal() { - if (!IsHandleCreated) { + internal void BeginUpdateInternal() + { + if (!IsHandleCreated) + { return; } - if (updateCount == 0) SendMessage(Interop.WindowMessages.WM_SETREDRAW, 0, 0); + if (updateCount == 0) + SendMessage(Interop.WindowMessages.WM_SETREDRAW, 0, 0); updateCount++; } /// /// Brings this control to the front of the zorder. /// - public void BringToFront() { - if (parent != null) { + public void BringToFront() + { + if (parent != null) + { parent.Controls.SetChildIndex(this, 0); } - else if (IsHandleCreated && GetTopLevel() && SafeNativeMethods.IsWindowEnabled(new HandleRef(window, Handle))) { + 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); } @@ -4934,15 +5684,18 @@ public void BringToFront() { /// 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). /// - internal virtual bool CanProcessMnemonic() { + internal virtual bool CanProcessMnemonic() + { #if DEBUG TraceCanProcessMnemonic(); #endif - if( !this.Enabled || !this.Visible) { + if (!this.Enabled || !this.Visible) + { return false; } - if( this.parent != null ){ + if (this.parent != null) + { return this.parent.CanProcessMnemonic(); } @@ -4951,13 +5704,17 @@ internal virtual bool CanProcessMnemonic() { // Package scope to allow AxHost to override // - internal virtual bool CanSelectCore() { - if ((controlStyle & ControlStyles.Selectable) != ControlStyles.Selectable) { + 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) { + for (Control ctl = this; ctl != null; ctl = ctl.parent) + { + if (!ctl.Enabled || !ctl.Visible) + { return false; } } @@ -4969,42 +5726,54 @@ internal virtual bool CanSelectCore() { /// Searches the parent/owner tree for bottom to find any instance /// of toFind in the parent/owner tree. /// - internal static void CheckParentingCycle(Control bottom, Control toFind) { + internal static void CheckParentingCycle(Control bottom, Control toFind) + { Form lastOwner = null; Control lastParent = null; - for (Control ctl = bottom; ctl != null; ctl = ctl.ParentInternal) { + for (Control ctl = bottom; ctl != null; ctl = ctl.ParentInternal) + { lastParent = ctl; - if (ctl == toFind) { + if (ctl == toFind) + { throw new ArgumentException(SR.CircularOwner); } } - if (lastParent != null) { - if (lastParent is Form) { + if (lastParent != null) + { + if (lastParent is Form) + { Form f = (Form)lastParent; - for (Form form = f; form != null; form = form.OwnerInternal) { + for (Form form = f; form != null; form = form.OwnerInternal) + { lastOwner = form; - if (form == toFind) { + if (form == toFind) + { throw new ArgumentException(SR.CircularOwner); } } } } - if (lastOwner != null) { - if (lastOwner.ParentInternal != null) { + if (lastOwner != null) + { + if (lastOwner.ParentInternal != null) + { CheckParentingCycle(lastOwner.ParentInternal, toFind); } } } /// /// - private void ChildGotFocus(Control child) { - if (IsActiveX) { + private void ChildGotFocus(Control child) + { + if (IsActiveX) + { ActiveXOnFocus(true); } - if (parent != null) { + if (parent != null) + { parent.ChildGotFocus(child); } } @@ -5012,13 +5781,17 @@ private void ChildGotFocus(Control child) { /// /// Verifies if a control is a child of this control. /// - public bool Contains(Control ctl) { - while (ctl != null) { + public bool Contains(Control ctl) + { + while (ctl != null) + { ctl = ctl.ParentInternal; - if (ctl == null) { + if (ctl == null) + { return false; } - if (ctl == this) { + if (ctl == this) + { return true; } } @@ -5030,7 +5803,8 @@ public bool Contains(Control ctl) { /// should not call base.CreateAccessibilityObject. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual AccessibleObject CreateAccessibilityInstance() { + protected virtual AccessibleObject CreateAccessibilityInstance() + { return new ControlAccessibleObject(this); } @@ -5039,7 +5813,8 @@ protected virtual AccessibleObject CreateAccessibilityInstance() { /// should not call base.CreateControlsInstance. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual ControlCollection CreateControlsInstance() { + protected virtual ControlCollection CreateControlsInstance() + { return new System.Windows.Forms.Control.ControlCollection(this); } @@ -5050,19 +5825,21 @@ protected virtual ControlCollection CreateControlsInstance() { /// method when it is no longer needed. The Graphics Object is only valid for /// the duration of the current window's message. /// - - - public System.Drawing.Graphics CreateGraphics() { + + + public System.Drawing.Graphics CreateGraphics() + { using (new MultithreadSafeCallScope()) { return CreateGraphicsInternal(); } } - - - - internal System.Drawing.Graphics CreateGraphicsInternal() { + + + + internal System.Drawing.Graphics CreateGraphicsInternal() + { return Graphics.FromHwndInternal(this.Handle); } @@ -5074,25 +5851,30 @@ internal System.Drawing.Graphics CreateGraphicsInternal() { [ EditorBrowsable(EditorBrowsableState.Advanced), ] - protected virtual void CreateHandle() { + protected virtual void CreateHandle() + { IntPtr userCookie = IntPtr.Zero; - if (GetState(STATE_DISPOSED)) { + if (GetState(STATE_DISPOSED)) + { throw new System.ObjectDisposedException(GetType().Name); } - if (GetState(STATE_CREATINGHANDLE)) { + if (GetState(STATE_CREATINGHANDLE)) + { return; } Rectangle originalBounds; - try { + try + { SetState(STATE_CREATINGHANDLE, true); originalBounds = this.Bounds; - if (Application.UseVisualStyles) { + 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(); @@ -5103,14 +5885,18 @@ protected virtual void CreateHandle() { // Adjust for scrolling of parent... // - if (parent != null) { + if (parent != null) + { Rectangle parentClient = parent.ClientRectangle; - if (!parentClient.IsEmpty) { - if (cp.X != NativeMethods.CW_USEDEFAULT) { + if (!parentClient.IsEmpty) + { + if (cp.X != NativeMethods.CW_USEDEFAULT) + { cp.X -= parentClient.X; } - if (cp.Y != NativeMethods.CW_USEDEFAULT) { + if (cp.Y != NativeMethods.CW_USEDEFAULT) + { cp.Y -= parentClient.Y; } } @@ -5118,7 +5904,8 @@ protected virtual void CreateHandle() { // And if we are WS_CHILD, ensure we have a parent handle. // - if (cp.Parent == IntPtr.Zero && (cp.Style & NativeMethods.WS_CHILD) != 0) { + 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); } @@ -5128,7 +5915,8 @@ protected virtual void CreateHandle() { UpdateReflectParent(true); } - finally { + finally + { SetState(STATE_CREATINGHANDLE, false); UnsafeNativeMethods.ThemingScope.Deactivate(userCookie); } @@ -5136,7 +5924,8 @@ protected virtual void CreateHandle() { // 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) { + if (this.Bounds != originalBounds) + { LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.Bounds); } } @@ -5145,11 +5934,13 @@ protected virtual void CreateHandle() { /// Forces the creation of the control. This includes the creation of the handle, /// and any child controls. /// - public void CreateControl() { + public void CreateControl() + { bool controlIsAlreadyCreated = this.Created; CreateControl(false); - if (Properties.GetObject(PropBindingManager) == null && ParentInternal != null && !controlIsAlreadyCreated) { + 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 @@ -5167,7 +5958,8 @@ public void CreateControl() { /// property of the control or not. /// /// - internal void CreateControl(bool fIgnoreVisible) { + internal void CreateControl(bool fIgnoreVisible) + { bool ready = (state & STATE_CREATED) == 0; // PERF: Only "create" the control if it is @@ -5176,23 +5968,29 @@ internal void CreateControl(bool fIgnoreVisible) { // ready = ready && Visible; - if (ready || fIgnoreVisible) { + if (ready || fIgnoreVisible) + { state |= STATE_CREATED; bool createdOK = false; - try { - if (!IsHandleCreated) CreateHandle(); + try + { + if (!IsHandleCreated) + CreateHandle(); // must snapshot this array because // z-order updates from Windows may rearrange it! // ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection != null) { + if (controlsCollection != null) + { Control[] controlSnapshot = new Control[controlsCollection.Count]; controlsCollection.CopyTo(controlSnapshot, 0); - foreach(Control ctl in controlSnapshot) { - if (ctl.IsHandleCreated) { + foreach (Control ctl in controlSnapshot) + { + if (ctl.IsHandleCreated) + { ctl.SetParentHandle(Handle); } ctl.CreateControl(fIgnoreVisible); @@ -5201,7 +5999,8 @@ internal void CreateControl(bool fIgnoreVisible) { createdOK = true; } - finally { + finally + { if (!createdOK) state &= (~STATE_CREATED); } @@ -5217,7 +6016,8 @@ internal void CreateControl(bool fIgnoreVisible) { [ EditorBrowsable(EditorBrowsableState.Advanced) ] - protected virtual void DefWndProc(ref Message m) { + protected virtual void DefWndProc(ref Message m) + { window.DefWndProc(ref m); } @@ -5229,18 +6029,24 @@ protected virtual void DefWndProc(ref Message m) { [ EditorBrowsable(EditorBrowsableState.Advanced) ] - protected virtual void DestroyHandle() { + protected virtual void DestroyHandle() + { - if (RecreatingHandle) { - if (threadCallbackList != null) { + 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) { + 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)) { + threadCallbackMessage, NativeMethods.PM_NOREMOVE)) + { SetState(STATE_THREADMARSHALLPENDING, true); } @@ -5255,12 +6061,16 @@ protected virtual void DestroyHandle() { // 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) { + if (!RecreatingHandle) + { + if (threadCallbackList != null) + { + lock (threadCallbackList) + { Exception ex = new System.ObjectDisposedException(GetType().Name); - while (threadCallbackList.Count > 0) { + while (threadCallbackList.Count > 0) + { ThreadMethodEntry entry = (ThreadMethodEntry)threadCallbackList.Dequeue(); entry.exception = ex; entry.Complete(); @@ -5269,10 +6079,12 @@ protected virtual void DestroyHandle() { } } - if (0 != (NativeMethods.WS_EX_MDICHILD & (int)(long)UnsafeNativeMethods.GetWindowLong(new HandleRef(window, InternalHandle), NativeMethods.GWL_EXSTYLE))) { + if (0 != (NativeMethods.WS_EX_MDICHILD & (int)(long)UnsafeNativeMethods.GetWindowLong(new HandleRef(window, InternalHandle), NativeMethods.GWL_EXSTYLE))) + { UnsafeNativeMethods.DefMDIChildProc(InternalHandle, Interop.WindowMessages.WM_CLOSE, IntPtr.Zero, IntPtr.Zero); } - else { + else + { window.DestroyHandle(); } @@ -5284,12 +6096,16 @@ protected virtual void DestroyHandle() { /// /// . /// - protected override void Dispose(bool disposing) { - if (GetState(STATE_OWNCTLBRUSH)) { + protected override void Dispose(bool disposing) + { + if (GetState(STATE_OWNCTLBRUSH)) + { object backBrush = Properties.GetObject(PropBackBrush); - if (backBrush != null) { + if (backBrush != null) + { IntPtr p = (IntPtr)backBrush; - if (p != IntPtr.Zero) { + if (p != IntPtr.Zero) + { SafeNativeMethods.DeleteObject(new HandleRef(this, p)); } Properties.SetObject(PropBackBrush, null); @@ -5298,12 +6114,15 @@ protected override void Dispose(bool disposing) { //set reflectparent = null regardless of whether we are in the finalizer thread or not. UpdateReflectParent(false); - if (disposing) { - if (GetState(STATE_DISPOSING)) { + if (disposing) + { + if (GetState(STATE_DISPOSING)) + { return; } - if (GetState(STATE_CREATINGHANDLE)) { + if (GetState(STATE_CREATINGHANDLE)) + { throw new InvalidOperationException(string.Format(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, @@ -5312,30 +6131,36 @@ protected override void Dispose(bool disposing) { SetState(STATE_DISPOSING, true); this.SuspendLayout(); - try { + try + { DisposeAxControls(); ContextMenu contextMenu = (ContextMenu)Properties.GetObject(PropContextMenu); - if (contextMenu != null) { + if (contextMenu != null) + { contextMenu.Disposed -= new EventHandler(DetachContextMenu); } ResetBindings(); - if (IsHandleCreated) DestroyHandle(); + if (IsHandleCreated) + DestroyHandle(); - if (parent != null) { + if (parent != null) + { parent.Controls.Remove(this); } ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection != null) { + 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++) { + for (int i = 0; i < controlsCollection.Count; i++) + { Control ctl = controlsCollection[i]; ctl.parent = null; ctl.Dispose(); @@ -5345,13 +6170,15 @@ protected override void Dispose(bool disposing) { base.Dispose(disposing); } - finally { + finally + { this.ResumeLayout(false); SetState(STATE_DISPOSING, false); SetState(STATE_DISPOSED, true); } } - else { + else + { #if FINALIZATION_WATCH if (!GetState(STATE_DISPOSED)) { @@ -5361,7 +6188,8 @@ protected override void Dispose(bool disposing) { // This same post is done in NativeWindow's finalize method, so if you change // it, change it there too. // - if (window != null) { + if (window != null) + { window.ForceExitMessageLoop(); } base.Dispose(disposing); @@ -5370,14 +6198,17 @@ protected override void Dispose(bool disposing) { // Package scope to allow AxHost to override. // - internal virtual void DisposeAxControls() { + internal virtual void DisposeAxControls() + { ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection != null) { + 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++) { + for (int i = 0; i < controlsCollection.Count; i++) + { controlsCollection[i].DisposeAxControls(); } } @@ -5391,37 +6222,45 @@ internal virtual void DisposeAxControls() { /// that implements System.Runtime.Serialization.ISerializable. data can also be any Object that /// implements System.Windows.Forms.IDataObject. /// - public DragDropEffects DoDragDrop(object data, DragDropEffects allowedEffects) { - int[] finalEffect = new int[] {(int)DragDropEffects.None}; - UnsafeNativeMethods.IOleDropSource dropSource = new DropSource( this ); + 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) { + if (data is IComDataObject) + { dataObject = (IComDataObject)data; } - else { + else + { DataObject iwdata = null; - if (data is IDataObject) { + if (data is IDataObject) + { iwdata = new DataObject((IDataObject)data); } - else { + else + { iwdata = new DataObject(); iwdata.SetData(data); } dataObject = (IComDataObject)iwdata; } - try { + try + { SafeNativeMethods.DoDragDrop(dataObject, dropSource, (int)allowedEffects, finalEffect); } - catch (Exception e) { - if (ClientUtils.IsSecurityOrCriticalException(e)) { + catch (Exception e) + { + if (ClientUtils.IsSecurityOrCriticalException(e)) + { throw; } } - return(DragDropEffects)finalEffect[0]; + return (DragDropEffects)finalEffect[0]; } /// @@ -5437,18 +6276,22 @@ public DragDropEffects DoDragDrop(object data, DragDropEffects allowedEffects) { SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters"), // targetBounds is the name of the param passed in. // So we don't have to localize it. ] - public void DrawToBitmap(Bitmap bitmap, Rectangle targetBounds) { + public void DrawToBitmap(Bitmap bitmap, Rectangle targetBounds) + { - if (bitmap == null) { + if (bitmap == null) + { throw new ArgumentNullException(nameof(bitmap)); } if (targetBounds.Width <= 0 || targetBounds.Height <= 0 - || targetBounds.X < 0 || targetBounds.Y < 0) { + || targetBounds.X < 0 || targetBounds.Y < 0) + { throw new ArgumentException(nameof(targetBounds)); } - if (!IsHandleCreated) { + if (!IsHandleCreated) + { CreateHandle(); } @@ -5456,15 +6299,18 @@ public void DrawToBitmap(Bitmap bitmap, Rectangle targetBounds) { 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)) { + 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), Interop.WindowMessages.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)) { + 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); @@ -5483,57 +6329,70 @@ public void DrawToBitmap(Bitmap bitmap, Rectangle targetBounds) { /// block until the result is available. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public object EndInvoke(IAsyncResult asyncResult) { + public object EndInvoke(IAsyncResult asyncResult) + { using (new MultithreadSafeCallScope()) { - if (asyncResult == null) { + if (asyncResult == null) + { throw new ArgumentNullException(nameof(asyncResult)); } ThreadMethodEntry entry = asyncResult as ThreadMethodEntry; - if (entry == null) { - throw new ArgumentException(SR.ControlBadAsyncResult,"asyncResult"); + if (entry == null) + { + throw new ArgumentException(SR.ControlBadAsyncResult, "asyncResult"); } Debug.Assert(this == entry.caller, "Called BeginInvoke on one control, and the corresponding EndInvoke on a different control"); - if (!asyncResult.IsCompleted) { + if (!asyncResult.IsCompleted) + { int pid; // ignored Control marshaler = FindMarshalingControl(); - if (SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(marshaler, marshaler.Handle), out pid) == SafeNativeMethods.GetCurrentThreadId()) { + if (SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(marshaler, marshaler.Handle), out pid) == SafeNativeMethods.GetCurrentThreadId()) + { marshaler.InvokeMarshaledCallbacks(); } - else { + else + { marshaler = entry.marshaler; marshaler.WaitForWaitHandle(asyncResult.AsyncWaitHandle); } } Debug.Assert(asyncResult.IsCompleted, "Why isn't this asyncResult done yet?"); - if (entry.exception != null) { + if (entry.exception != null) + { throw entry.exception; } return entry.retVal; } } - internal bool EndUpdateInternal() { + internal bool EndUpdateInternal() + { return EndUpdateInternal(true); } - internal bool EndUpdateInternal(bool invalidate) { - if (updateCount > 0) { + internal bool EndUpdateInternal(bool invalidate) + { + if (updateCount > 0) + { Debug.Assert(IsHandleCreated, "Handle should be created by now"); updateCount--; - if (updateCount == 0) { + if (updateCount == 0) + { SendMessage(Interop.WindowMessages.WM_SETREDRAW, -1, 0); - if (invalidate) { + if (invalidate) + { Invalidate(); } } return true; } - else { + else + { return false; } } @@ -5559,17 +6418,21 @@ public Form FindForm() /// handle, so we traverse up the parent chain until we find one. /// Failing that, we just return ouselves. /// - private Control FindMarshalingControl() { + private Control FindMarshalingControl() + { // - lock(this) { + lock (this) + { Control c = this; - while (c != null && !c.IsHandleCreated) { + while (c != null && !c.IsHandleCreated) + { Control p = c.ParentInternal; c = p; } - if (c == null) { + if (c == null) + { // No control with a created handle. We // just use our own control. MarshaledInvoke // will throw an exception because there @@ -5577,24 +6440,28 @@ private Control FindMarshalingControl() { // c = this; } - else { + else + { Debug.Assert(c.IsHandleCreated, "FindMarshalingControl chose a bad control."); } - return(Control)c; + return (Control)c; } } - protected bool GetTopLevel() { - return(state & STATE_TOPLEVEL) != 0; + protected bool GetTopLevel() + { + return (state & STATE_TOPLEVEL) != 0; } /// /// Used by AxHost to fire the CreateHandle event. /// - internal void RaiseCreateHandleEvent(EventArgs e) { + internal void RaiseCreateHandleEvent(EventArgs e) + { EventHandler handler = (EventHandler)Events[EventHandleCreated]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// @@ -5602,9 +6469,11 @@ internal void RaiseCreateHandleEvent(EventArgs e) { /// e and a sender of this control. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected void RaiseKeyEvent(object key, KeyEventArgs e) { + protected void RaiseKeyEvent(object key, KeyEventArgs e) + { KeyEventHandler handler = (KeyEventHandler)Events[key]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// @@ -5612,9 +6481,11 @@ protected void RaiseKeyEvent(object key, KeyEventArgs e) { /// e and a sender of this control. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected void RaiseMouseEvent(object key, MouseEventArgs e) { + protected void RaiseMouseEvent(object key, MouseEventArgs e) + { MouseEventHandler handler = (MouseEventHandler)Events[key]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// @@ -5634,19 +6505,25 @@ public bool Focus() /// Form overrides this method - because MDI child forms /// need to be focused by calling the MDIACTIVATE message. /// - private protected virtual bool FocusInternal() { + private protected virtual bool FocusInternal() + { Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Control::FocusInternal - " + this.Name); - if (CanFocus){ + if (CanFocus) + { UnsafeNativeMethods.SetFocus(new HandleRef(this, Handle)); } - if (Focused && this.ParentInternal != null) { + if (Focused && this.ParentInternal != null) + { IContainerControl c = this.ParentInternal.GetContainerControl(); - if (c != null) { - if (c is ContainerControl) { + if (c != null) + { + if (c is ContainerControl) + { ((ContainerControl)c).SetActiveControl(this); } - else { + else + { c.ActiveControl = this; } } @@ -5700,29 +6577,33 @@ public static Control FromHandle(IntPtr handle) // 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; + 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 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) { + internal virtual Rectangle ApplyBoundsConstraints(int suggestedX, int suggestedY, int proposedWidth, int proposedHeight) + { // COMPAT: 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) { + if (MaximumSize != Size.Empty || MinimumSize != Size.Empty) + { Size maximumSize = LayoutUtils.ConvertZeroToUnbounded(MaximumSize); - Rectangle newBounds = new Rectangle(suggestedX, suggestedY, 0,0); - + 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.IntersectSizes(new Size(proposedWidth, proposedHeight), maximumSize); newBounds.Size = LayoutUtils.UnionSizes(newBounds.Size, MinimumSize); - + return newBounds; } @@ -5733,10 +6614,11 @@ internal virtual Rectangle ApplyBoundsConstraints(int suggestedX, int suggestedY /// Retrieves the child control that is located at the specified client /// coordinates. /// - public Control GetChildAtPoint(Point pt, GetChildAtPointSkip skipValue) { + 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) + if (value < 0 || value > 7) { throw new InvalidEnumArgumentException(nameof(skipValue), value, typeof(GetChildAtPointSkip)); } @@ -5744,14 +6626,15 @@ public Control GetChildAtPoint(Point pt, GetChildAtPointSkip skipValue) { IntPtr hwnd = UnsafeNativeMethods.ChildWindowFromPointEx(new HandleRef(null, Handle), pt.X, pt.Y, value); Control ctl = FromChildHandle(hwnd); - return(ctl == this) ? null : ctl; + return (ctl == this) ? null : ctl; } /// /// Retrieves the child control that is located at the specified client /// coordinates. /// - public Control GetChildAtPoint(Point pt) { + public Control GetChildAtPoint(Point pt) + { return GetChildAtPoint(pt, GetChildAtPointSkip.None); } @@ -5762,9 +6645,9 @@ public Control GetChildAtPoint(Point pt) { public IContainerControl GetContainerControl() { Control c = this; - + // Refer to IsContainerControl property for more details. - if (c != null && IsContainerControl) + if (c != null && IsContainerControl) { c = c.ParentInternal; } @@ -5776,11 +6659,12 @@ public IContainerControl GetContainerControl() return (IContainerControl)c; } - private static bool IsFocusManagingContainerControl(Control ctl) { + private static bool IsFocusManagingContainerControl(Control ctl) + { return ((ctl.controlStyle & ControlStyles.ContainerControl) == ControlStyles.ContainerControl && ctl is IContainerControl); } - /// + /// /// This new Internal method checks the updateCount to signify that the control is within the "BeginUpdate" and "EndUpdate" cycle. /// Check out : 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. @@ -5791,15 +6675,18 @@ internal bool IsUpdating() } // Essentially an Hfont; see inner class for details. - private static FontHandleWrapper GetDefaultFontHandleWrapper() { - if (defaultFontHandleWrapper == null) { + private static FontHandleWrapper GetDefaultFontHandleWrapper() + { + if (defaultFontHandleWrapper == null) + { defaultFontHandleWrapper = new FontHandleWrapper(DefaultFont); } return defaultFontHandleWrapper; } - internal IntPtr GetHRgn(Region region) { + internal IntPtr GetHRgn(Region region) + { Graphics graphics = CreateGraphicsInternal(); IntPtr handle = region.GetHrgn(graphics); Interop.HandleCollector.Add(handle, Interop.CommonHandles.GDI); @@ -5816,7 +6703,8 @@ internal IntPtr GetHRgn(Region region) { /// the control is fixed width or auto size, and any adornments the control may have. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual Rectangle GetScaledBounds(Rectangle bounds, SizeF factor, BoundsSpecified specified) { + 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. @@ -5833,22 +6721,28 @@ protected virtual Rectangle GetScaledBounds(Rectangle bounds, SizeF factor, Boun // 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) { + if (scaleLoc) + { ISite site = Site; - if (site != null && site.DesignMode) { + if (site != null && site.DesignMode) + { IDesignerHost host = site.GetService(typeof(IDesignerHost)) as IDesignerHost; - if (host != null && host.RootComponent == this) { + if (host != null && host.RootComponent == this) + { scaleLoc = false; } } } - if (scaleLoc) { - if ((specified & BoundsSpecified.X) != 0) { + if (scaleLoc) + { + if ((specified & BoundsSpecified.X) != 0) + { sx = (int)Math.Round(bounds.X * dx); } - if ((specified & BoundsSpecified.Y) != 0) { + if ((specified & BoundsSpecified.Y) != 0) + { sy = (int)Math.Round(bounds.Y * dy); } } @@ -5858,12 +6752,14 @@ protected virtual Rectangle GetScaledBounds(Rectangle bounds, SizeF factor, Boun // 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) { + 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) { + 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; @@ -5872,18 +6768,21 @@ protected virtual Rectangle GetScaledBounds(Rectangle bounds, SizeF factor, Boun 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; + 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() { + internal virtual bool GetVisibleCore() + { // We are only visible if our parent is visible if (!GetState(STATE_VISIBLE)) return false; @@ -5893,11 +6792,14 @@ internal virtual bool GetVisibleCore() { return ParentInternal.GetVisibleCore(); } - internal bool GetAnyDisposingInHierarchy() { + internal bool GetAnyDisposingInHierarchy() + { Control up = this; bool isDisposing = false; - while (up != null) { - if (up.Disposing) { + while (up != null) + { + if (up.Disposing) + { isDisposing = true; break; } @@ -5906,19 +6808,24 @@ internal bool GetAnyDisposingInHierarchy() { return isDisposing; } - private MenuItem GetMenuItemFromHandleId(IntPtr hmenu, int item) { + private MenuItem GetMenuItemFromHandleId(IntPtr hmenu, int item) + { MenuItem mi = null; int id = UnsafeNativeMethods.GetMenuItemID(new HandleRef(null, hmenu), item); - if (id == unchecked((int)0xFFFFFFFF)) { + 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 - private ArrayList GetChildControlsTabOrderList(bool handleCreatedOnly) { + private ArrayList GetChildControlsTabOrderList(bool handleCreatedOnly) + { ArrayList holders = new ArrayList(); - foreach (Control c in Controls) { - if (!handleCreatedOnly || c.IsHandleCreated) { + foreach (Control c in Controls) + { + if (!handleCreatedOnly || c.IsHandleCreated) + { holders.Add(new ControlTabOrderHolder(holders.Count, c.TabIndex, c)); } } @@ -5967,13 +6880,15 @@ private ArrayList GetChildControlsTabOrderList(bool handleCreatedOnly) { /// - This version returns a sorted array of integers, representing the original z-order /// based indexes of the native child windows. /// - private int[] GetChildWindowsInTabOrder() { + 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; + for (int i = 0; i < holders.Count; i++) + { + indexes[i] = ((ControlTabOrderHolder)holders[i]).oldOrder; } return indexes; @@ -5984,13 +6899,15 @@ private int[] GetChildWindowsInTabOrder() { /// - Controls with the same TabIndex remain in original relative child index order (= z-order). /// - This version returns a sorted array of control references. /// - internal Control[] GetChildControlsInTabOrder(bool handleCreatedOnly) { + 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; + for (int i = 0; i < holders.Count; i++) + { + ctls[i] = ((ControlTabOrderHolder)holders[i]).control; } return ctls; @@ -6001,25 +6918,29 @@ internal Control[] GetChildControlsInTabOrder(bool handleCreatedOnly) { /// This is used when sorting controls based on tab index first, /// z-order second. /// - private class ControlTabOrderHolder { + private class ControlTabOrderHolder + { internal readonly int oldOrder; internal readonly int newOrder; internal readonly Control control; - internal ControlTabOrderHolder(int oldOrder, int newOrder, Control control) { + internal ControlTabOrderHolder(int oldOrder, int newOrder, Control control) + { this.oldOrder = oldOrder; this.newOrder = newOrder; - this.control = control; + this.control = control; } } /// /// Used to sort controls based on tab index and z-order. /// - private class ControlTabOrderComparer : IComparer { - int IComparer.Compare(object x, object y) { - ControlTabOrderHolder hx = (ControlTabOrderHolder) x; - ControlTabOrderHolder hy = (ControlTabOrderHolder) y; + 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) @@ -6032,12 +6953,14 @@ int IComparer.Compare(object x, object y) { /// /// Given a native window handle, returns array of handles to window's children (in z-order). /// - private static ArrayList GetChildWindows(IntPtr hWndParent) { + 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)) { + hWndChild = UnsafeNativeMethods.GetWindow(new HandleRef(null, hWndChild), NativeMethods.GW_HWNDNEXT)) + { windows.Add(hWndChild); } @@ -6051,11 +6974,13 @@ private static ArrayList GetChildWindows(IntPtr hWndParent) { /// 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. /// - private ArrayList GetChildWindowsTabOrderList() { + private ArrayList GetChildWindowsTabOrderList() + { ArrayList holders = new ArrayList(); ArrayList windows = GetChildWindows(this.Handle); - foreach (IntPtr hWnd in windows) { + foreach (IntPtr hWnd in windows) + { Control ctl = FromHandle(hWnd); int tabIndex = (ctl == null) ? -1 : ctl.TabIndex; holders.Add(new ControlTabOrderHolder(holders.Count, tabIndex, ctl)); @@ -6066,30 +6991,38 @@ private ArrayList GetChildWindowsTabOrderList() { return holders; } - internal virtual Control GetFirstChildControlInTabOrder(bool forward) { - + 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) { + 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 { - + } + 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) { + for (int c = ctlControls.Count - 1; c >= 0; c--) + { + if (found == null || found.tabIndex < ctlControls[c].tabIndex) + { found = ctlControls[c]; } } - } + } } return found; @@ -6098,22 +7031,28 @@ internal virtual Control GetFirstChildControlInTabOrder(bool forward) { /// /// Retrieves the next control in the tab order of child controls. /// - public Control GetNextControl(Control ctl, bool forward) { - if (!Contains(ctl)) { + public Control GetNextControl(Control ctl, bool forward) + { + if (!Contains(ctl)) + { ctl = this; } - if (forward) { + if (forward) + { ControlCollection ctlControls = (ControlCollection)ctl.Properties.GetObject(PropControlsCollection); - if (ctlControls != null && ctlControls.Count > 0 && (ctl == this || !IsFocusManagingContainerControl(ctl))) { + if (ctlControls != null && ctlControls.Count > 0 && (ctl == this || !IsFocusManagingContainerControl(ctl))) + { Control found = ctl.GetFirstChildControlInTabOrder(/*forward=*/true); - if (found != null) { + if (found != null) + { return found; } } - while (ctl != this) { + while (ctl != this) + { int targetIndex = ctl.tabIndex; bool hitCtl = false; Control found = null; @@ -6127,40 +7066,47 @@ public Control GetNextControl(Control ctl, bool forward) { ControlCollection parentControls = (ControlCollection)p.Properties.GetObject(PropControlsCollection); - if (parentControls != null) { + if (parentControls != null) + { parentControlCount = parentControls.Count; } - for (int c = 0; c < parentControlCount; c++) { + 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) { + 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) { + 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) { + 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) { + if (parentControls[c].tabIndex != targetIndex || hitCtl) + { found = parentControls[c]; } } } } - else { + 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. // @@ -6168,15 +7114,18 @@ public Control GetNextControl(Control ctl, bool forward) { } } - if (found != null) { + if (found != null) + { return found; } ctl = ctl.parent; } } - else { - if (ctl != this) { + else + { + if (ctl != this) + { int targetIndex = ctl.tabIndex; bool hitCtl = false; @@ -6190,40 +7139,47 @@ public Control GetNextControl(Control ctl, bool forward) { ControlCollection parentControls = (ControlCollection)p.Properties.GetObject(PropControlsCollection); - if (parentControls != null) { + if (parentControls != null) + { parentControlCount = parentControls.Count; } - for (int c = parentControlCount - 1; c >= 0; c--) { + 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) { + 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) { + 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) { + 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) { + if (parentControls[c].tabIndex != targetIndex || hitCtl) + { found = parentControls[c]; } } } } - else { + 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. // @@ -6234,14 +7190,18 @@ public Control GetNextControl(Control ctl, bool forward) { // 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) { + if (found != null) + { ctl = found; } - else { - if (p == this) { + else + { + if (p == this) + { return null; } - else { + else + { return p; } } @@ -6251,19 +7211,22 @@ public Control GetNextControl(Control ctl, bool forward) { // ControlCollection ctlControls = (ControlCollection)ctl.Properties.GetObject(PropControlsCollection); - while (ctlControls != null && ctlControls.Count > 0 && (ctl == this || !IsFocusManagingContainerControl(ctl))) { + while (ctlControls != null && ctlControls.Count > 0 && (ctl == this || !IsFocusManagingContainerControl(ctl))) + { Control found = ctl.GetFirstChildControlInTabOrder(/*forward=*/false); - if (found != null) { + if (found != null) + { ctl = found; ctlControls = (ControlCollection)ctl.Properties.GetObject(PropControlsCollection); } - else { + else + { break; } } } - return ctl == this? null: ctl; + return ctl == this ? null : ctl; } /// @@ -6294,8 +7257,9 @@ internal static IntPtr GetSafeHandle(IWin32Window window) /// /// Retrieves the current value of the specified bit in the control's state. /// - internal bool GetState(int flag) { - return(state & flag) != 0; + internal bool GetState(int flag) + { + return (state & flag) != 0; } /// @@ -6310,14 +7274,16 @@ private bool GetState2(int flag) /// 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. /// - protected bool GetStyle(ControlStyles flag) { + protected bool GetStyle(ControlStyles flag) + { return (controlStyle & flag) == flag; } /// /// Hides the control by setting the visible property to false; /// - public void Hide() { + public void Hide() + { Visible = false; } @@ -6325,11 +7291,14 @@ public void Hide() { /// Sets up the TrackMouseEvent for listening for the /// mouse leave event. /// - private void HookMouseEvent() { - if (!GetState(STATE_TRACKINGMOUSEEVENT)) { + private void HookMouseEvent() + { + if (!GetState(STATE_TRACKINGMOUSEEVENT)) + { SetState(STATE_TRACKINGMOUSEEVENT, true); - if (trackMouseEvent == null) { + if (trackMouseEvent == null) + { trackMouseEvent = new NativeMethods.TRACKMOUSEEVENT(); trackMouseEvent.dwFlags = NativeMethods.TME_LEAVE | NativeMethods.TME_HOVER; trackMouseEvent.hwndTrack = Handle; @@ -6343,7 +7312,8 @@ private void HookMouseEvent() { /// Called after the control has been added to another container. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void InitLayout() { + protected virtual void InitLayout() + { LayoutEngine.InitLayout(this, BoundsSpecified.All); } @@ -6351,7 +7321,8 @@ protected virtual void InitLayout() { /// This method initializes the scaling bits for this control based on /// the bounds. /// - private void InitScaling(BoundsSpecified specified) { + private void InitScaling(BoundsSpecified specified) + { requiredScaling |= (byte)((int)specified & RequiredScalingMask); } @@ -6361,13 +7332,16 @@ private void InitScaling(BoundsSpecified specified) { // // NOTE: this message may not have originally been sent to this HWND. // - internal virtual IntPtr InitializeDCForWmCtlColor (IntPtr dc, int msg) { - if (!GetStyle(ControlStyles.UserPaint)) { + 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 { + else + { return UnsafeNativeMethods.GetStockObject(NativeMethods.HOLLOW_BRUSH); } } @@ -6376,13 +7350,16 @@ internal virtual IntPtr InitializeDCForWmCtlColor (IntPtr dc, int msg) { /// Initializes mouse wheel support. This may involve registering some windows /// messages on older operating systems. /// - private void InitMouseWheelSupport() { - if (!mouseWheelInit) { + private void InitMouseWheelSupport() + { + if (!mouseWheelInit) + { // If we are running on a system without a mouse wheel then we must use // manual mousewheel routines. mouseWheelRoutingNeeded = !SystemInformation.NativeMouseWheelSupport; - if (mouseWheelRoutingNeeded) { + if (mouseWheelRoutingNeeded) + { IntPtr hwndMouseWheel = IntPtr.Zero; // Check for the MouseZ "service". This is a little app that generated the @@ -6391,14 +7368,16 @@ private void InitMouseWheelSupport() { // hwndMouseWheel = UnsafeNativeMethods.FindWindow(NativeMethods.MOUSEZ_CLASSNAME, NativeMethods.MOUSEZ_TITLE); - if (hwndMouseWheel != IntPtr.Zero) { + 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) { + if (message != 0) + { mouseWheelMessage = message; } } @@ -6413,7 +7392,8 @@ private void InitMouseWheelSupport() { /// occur, calling update after invalidate will force a /// synchronous paint. /// - public void Invalidate(Region region) { + public void Invalidate(Region region) + { Invalidate(region, false); } @@ -6423,23 +7403,29 @@ public void Invalidate(Region region) { /// occur, calling update after invalidate will force a /// synchronous paint. /// - public void Invalidate(Region region, bool invalidateChildren) { - if (region == null) { + public void Invalidate(Region region, bool invalidateChildren) + { + if (region == null) + { Invalidate(invalidateChildren); } - else if (IsHandleCreated) { + else if (IsHandleCreated) + { IntPtr regionHandle = GetHRgn(region); - try { + try + { Debug.Assert(regionHandle != IntPtr.Zero, "Region wasn't null but HRGN is?"); - if (invalidateChildren) { + if (invalidateChildren) + { SafeNativeMethods.RedrawWindow(new HandleRef(this, Handle), null, new HandleRef(region, regionHandle), NativeMethods.RDW_INVALIDATE | NativeMethods.RDW_ERASE | NativeMethods.RDW_ALLCHILDREN); } - else { + else + { // It's safe to invoke InvalidateRgn from a separate thread. using (new MultithreadSafeCallScope()) { @@ -6449,17 +7435,19 @@ public void Invalidate(Region region, bool invalidateChildren) { } } } - finally { + 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()) { + using (Graphics graphics = CreateGraphicsInternal()) + { bounds = Rectangle.Ceiling(region.GetBounds(graphics)); } - + OnInvalidated(new InvalidateEventArgs(bounds)); } } @@ -6469,7 +7457,8 @@ public void Invalidate(Region region, bool invalidateChildren) { /// This will not force a synchronous paint to occur, calling update after /// invalidate will force a synchronous paint. /// - public void Invalidate() { + public void Invalidate() + { Invalidate(false); } @@ -6478,16 +7467,20 @@ public void Invalidate() { /// This will not force a synchronous paint to occur, calling update after /// invalidate will force a synchronous paint. /// - public void Invalidate(bool invalidateChildren) { - if (IsHandleCreated) { - if (invalidateChildren) { + 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 { + else + { // It's safe to invoke InvalidateRect from a separate thread. using (new MultithreadSafeCallScope()) { @@ -6507,7 +7500,8 @@ public void Invalidate(bool invalidateChildren) { /// occur, calling update after invalidate will force a /// synchronous paint. /// - public void Invalidate(Rectangle rc) { + public void Invalidate(Rectangle rc) + { Invalidate(rc, false); } @@ -6517,12 +7511,16 @@ public void Invalidate(Rectangle rc) { /// occur, calling update after invalidate will force a /// synchronous paint. /// - public void Invalidate(Rectangle rc, bool invalidateChildren) { - if (rc.IsEmpty) { + public void Invalidate(Rectangle rc, bool invalidateChildren) + { + if (rc.IsEmpty) + { Invalidate(invalidateChildren); } - else if (IsHandleCreated) { - if (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, @@ -6530,7 +7528,8 @@ public void Invalidate(Rectangle rc, bool invalidateChildren) { NativeMethods.RDW_ERASE | NativeMethods.RDW_ALLCHILDREN); } - else { + else + { NativeMethods.RECT rcArea = NativeMethods.RECT.FromXYWH(rc.X, rc.Y, rc.Width, rc.Height); @@ -6560,7 +7559,8 @@ public void Invalidate(Rectangle rc, bool invalidateChildren) { /// For all other method calls, you should use one of the invoke methods to marshal /// the call to the control's thread. /// - public object Invoke(Delegate method) { + public object Invoke(Delegate method) + { return Invoke(method, null); } @@ -6578,8 +7578,10 @@ public object Invoke(Delegate method) { /// For all other method calls, you should use one of the invoke methods to marshal /// the call to the control's thread. /// - public object Invoke(Delegate method, params object[] args) { - using (new MultithreadSafeCallScope()) { + public object Invoke(Delegate method, params object[] args) + { + using (new MultithreadSafeCallScope()) + { Control marshaler = FindMarshalingControl(); return marshaler.MarshaledInvoke(this, method, args, true); } @@ -6599,21 +7601,26 @@ public object Invoke(Delegate method, params object[] args) { /// When the invoke request comes from this thread, there won't be an ExecutionContext so we just invoke /// the callback as is. /// - private void InvokeMarshaledCallback(ThreadMethodEntry tme){ - if (tme.executionContext != null) { - if (invokeMarshaledCallbackHelperDelegate == null) { + 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) { + if (SynchronizationContext.Current == null) + { WindowsFormsSynchronizationContext.InstallIfNeeded(); } tme.syncContext = SynchronizationContext.Current; ExecutionContext.Run(tme.executionContext, invokeMarshaledCallbackHelperDelegate, tme); } - else { + else + { InvokeMarshaledCallbackHelper(tme); } } @@ -6623,21 +7630,25 @@ private void InvokeMarshaledCallback(ThreadMethodEntry tme){ /// private static void InvokeMarshaledCallbackHelper(object obj) { - ThreadMethodEntry tme = (ThreadMethodEntry) obj; + ThreadMethodEntry tme = (ThreadMethodEntry)obj; - if (tme.syncContext != null) { + if (tme.syncContext != null) + { SynchronizationContext oldContext = SynchronizationContext.Current; - try { + try + { SynchronizationContext.SetSynchronizationContext(tme.syncContext); InvokeMarshaledCallbackDo(tme); } - finally { + finally + { SynchronizationContext.SetSynchronizationContext(oldContext); } } - else { + else + { InvokeMarshaledCallbackDo(tme); } } @@ -6648,18 +7659,23 @@ 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) { + 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) { + else if (tme.args.Length < 2) + { ((EventHandler)tme.method)(tme.args[0], EventArgs.Empty); } - else { + else + { ((EventHandler)tme.method)(tme.args[0], (EventArgs)tme.args[1]); } } - else if (tme.method is MethodInvoker) { + else if (tme.method is MethodInvoker) + { ((MethodInvoker)tme.method)(); } else if (tme.method is WaitCallback) @@ -6668,7 +7684,8 @@ private static void InvokeMarshaledCallbackDo(ThreadMethodEntry tme) "Arguments are wrong for WaitCallback"); ((WaitCallback)tme.method)(tme.args[0]); } - else { + else + { tme.retVal = tme.method.DynamicInvoke(tme.args); } } @@ -6678,73 +7695,92 @@ private static void InvokeMarshaledCallbackDo(ThreadMethodEntry tme) /// This empties this control's callback queue, propagating any exceptions /// back as needed. /// - private void InvokeMarshaledCallbacks() { + private void InvokeMarshaledCallbacks() + { ThreadMethodEntry current = null; - lock(threadCallbackList) { - if (threadCallbackList.Count > 0) { + lock (threadCallbackList) + { + if (threadCallbackList.Count > 0) + { current = (ThreadMethodEntry)threadCallbackList.Dequeue(); } } // Now invoke on all the queued items. // - while (current != null) { - if (current.method != null) { + while (current != null) + { + if (current.method != null) + { - try { + 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) { + if (NativeWindow.WndProcShouldBeDebuggable && !current.synchronous) + { InvokeMarshaledCallback(current); } - else { - try { + else + { + try + { InvokeMarshaledCallback(current); } - catch (Exception t) { + catch (Exception t) + { current.exception = t.GetBaseException(); } } } - finally { + 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) { + current.exception != null && !current.synchronous) + { Application.OnThreadException(current.exception); } } } - lock (threadCallbackList) { - if (threadCallbackList.Count > 0) { + lock (threadCallbackList) + { + if (threadCallbackList.Count > 0) + { current = (ThreadMethodEntry)threadCallbackList.Dequeue(); } - else { + else + { current = null; } } } } - protected void InvokePaint(Control c, PaintEventArgs e) { + protected void InvokePaint(Control c, PaintEventArgs e) + { c.OnPaint(e); } - protected void InvokePaintBackground(Control c, PaintEventArgs e) { - c.OnPaintBackground(e); + protected void InvokePaintBackground(Control c, PaintEventArgs e) + { + c.OnPaintBackground(e); } /// /// determines whether the font is set /// - internal bool IsFontSet() { + internal bool IsFontSet() + { Font font = (Font)Properties.GetObject(PropFont); - if (font != null) { + if (font != null) + { return true; } return false; @@ -6755,9 +7791,11 @@ internal bool IsFontSet() { /// 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. /// - internal bool IsDescendant(Control descendant) { + internal bool IsDescendant(Control descendant) + { Control control = descendant; - while (control != null) { + while (control != null) + { if (control == this) return true; control = control.ParentInternal; @@ -6768,8 +7806,10 @@ internal bool IsDescendant(Control descendant) { /// /// This Function will return a Boolean as to whether the Key value passed in is Locked... /// - public static bool IsKeyLocked(Keys keyVal) { - if (keyVal == Keys.Insert || keyVal == Keys.NumLock || keyVal == Keys.CapsLock || keyVal == Keys.Scroll) { + 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. @@ -6779,7 +7819,7 @@ public static bool IsKeyLocked(Keys keyVal) { // and off when the key is untoggled. // Toggle keys (only low bit is of interest). - if( keyVal == Keys.Insert || keyVal == Keys.CapsLock ) + if (keyVal == Keys.Insert || keyVal == Keys.CapsLock) { return (result & 0x1) != 0x0; } @@ -6803,17 +7843,20 @@ public static bool IsKeyLocked(Keys keyVal) { /// pre-processing of a character includes checking whether the character /// is a mnemonic of another control. /// - protected virtual bool IsInputChar(char charCode) { + 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) { + if (charCode == (char)(int)Keys.Tab) + { mask = NativeMethods.DLGC_WANTCHARS | NativeMethods.DLGC_WANTALLKEYS | NativeMethods.DLGC_WANTTAB; } - else { + else + { mask = NativeMethods.DLGC_WANTCHARS | NativeMethods.DLGC_WANTALLKEYS; } - return(unchecked( (int) (long)SendMessage(Interop.WindowMessages.WM_GETDLGCODE, 0, 0)) & mask) != 0; + return (unchecked((int)(long)SendMessage(Interop.WindowMessages.WM_GETDLGCODE, 0, 0)) & mask) != 0; } /// @@ -6826,12 +7869,15 @@ protected virtual bool IsInputChar(char charCode) { /// pre-processing phase. Keys that are pre-processed include TAB, RETURN, /// ESCAPE, and arrow keys. /// - protected virtual bool IsInputKey(Keys keyData) { + protected virtual bool IsInputKey(Keys keyData) + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "Control.IsInputKey " + keyData.ToString()); - if ((keyData & Keys.Alt) == Keys.Alt) return false; + if ((keyData & Keys.Alt) == Keys.Alt) + return false; int mask = NativeMethods.DLGC_WANTALLKEYS; - switch (keyData & Keys.KeyCode) { + switch (keyData & Keys.KeyCode) + { case Keys.Tab: mask = NativeMethods.DLGC_WANTALLKEYS | NativeMethods.DLGC_WANTTAB; break; @@ -6843,10 +7889,12 @@ protected virtual bool IsInputKey(Keys keyData) { break; } - if (IsHandleCreated) { - return(unchecked( (int) (long)SendMessage(Interop.WindowMessages.WM_GETDLGCODE, 0, 0)) & mask) != 0; + if (IsHandleCreated) + { + return (unchecked((int)(long)SendMessage(Interop.WindowMessages.WM_GETDLGCODE, 0, 0)) & mask) != 0; } - else { + else + { return false; } } @@ -6856,15 +7904,19 @@ protected virtual bool IsInputKey(Keys keyData) { /// The mnemonic character is the character imediately following the first /// instance of "&" in text /// - public static bool IsMnemonic(char charCode, string text) { + public static bool IsMnemonic(char charCode, string text) + { #if DEBUG - if (ControlKeyboardRouting.TraceVerbose) { + if (ControlKeyboardRouting.TraceVerbose) + { Debug.Write("Control.IsMnemonic(" + charCode.ToString() + ", "); - if (text != null) { + if (text != null) + { Debug.Write(text); } - else { + else + { Debug.Write("null"); } Debug.WriteLine(")"); @@ -6872,15 +7924,18 @@ public static bool IsMnemonic(char charCode, string text) { #endif //Special case handling: - if (charCode=='&') { + if (charCode == '&') + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, " ...returning false"); return false; } //if - if (text != null) { + if (text != null) + { int pos = -1; // start with -1 to handle double &'s char c2 = char.ToUpper(charCode, CultureInfo.CurrentCulture); - for (;;) { + for (; ; ) + { if (pos + 1 >= text.Length) break; pos = text.IndexOf('&', pos + 1) + 1; @@ -6888,7 +7943,8 @@ public static bool IsMnemonic(char charCode, string text) { 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)) { + if (c1 == c2 || char.ToLower(c1, CultureInfo.CurrentCulture) == char.ToLower(c2, CultureInfo.CurrentCulture)) + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, " ...returning true"); return true; } @@ -6899,14 +7955,18 @@ public static bool IsMnemonic(char charCode, string text) { return false; } - private void ListenToUserPreferenceChanged(bool listen) { - if (GetState2(STATE2_LISTENINGTOUSERPREFERENCECHANGED)) { - if (!listen) { + private void ListenToUserPreferenceChanged(bool listen) + { + if (GetState2(STATE2_LISTENINGTOUSERPREFERENCECHANGED)) + { + if (!listen) + { SetState2(STATE2_LISTENINGTOUSERPREFERENCECHANGED, false); SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(this.UserPreferenceChanged); } } - else if (listen) { + else if (listen) + { SetState2(STATE2_LISTENINGTOUSERPREFERENCECHANGED, true); SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(this.UserPreferenceChanged); } @@ -6916,7 +7976,8 @@ private void ListenToUserPreferenceChanged(bool listen) { /// Transforms an integer coordinate from logical to device units /// by scaling it for the current DPI and rounding down to the nearest integer value. /// - public int LogicalToDeviceUnits(int value) { + public int LogicalToDeviceUnits(int value) + { return DpiHelper.LogicalToDeviceUnits(value, DeviceDpi); } @@ -6926,7 +7987,8 @@ public int LogicalToDeviceUnits(int value) { /// /// size to be scaled /// scaled size - public Size LogicalToDeviceUnits(Size value) { + public Size LogicalToDeviceUnits(Size value) + { return DpiHelper.LogicalToDeviceUnits(value, DeviceDpi); } @@ -6935,20 +7997,25 @@ public Size LogicalToDeviceUnits(Size value) { /// When displayed on the device, the scaled image will have same size as the original image would have when displayed at 96dpi. /// /// The image to scale from logical units to device units - public void ScaleBitmapLogicalToDevice(ref Bitmap logicalBitmap) { + 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.IsPerMonitorV2Awareness) { + internal void AdjustWindowRectEx(ref NativeMethods.RECT rect, int style, bool bMenu, int exStyle) + { + if (DpiHelper.IsPerMonitorV2Awareness) + { SafeNativeMethods.AdjustWindowRectExForDpi(ref rect, style, bMenu, exStyle, (uint)deviceDpi); } - else { + else + { SafeNativeMethods.AdjustWindowRectEx(ref rect, style, bMenu, exStyle); } } - private object MarshaledInvoke(Control caller, Delegate method, object[] args, bool synchronous) { + private object MarshaledInvoke(Control caller, Delegate method, object[] args, bool synchronous) + { // Marshaling an invoke occurs in three steps: // @@ -6966,7 +8033,8 @@ private object MarshaledInvoke(Control caller, Delegate method, object[] args, b // types of calls if we're within a SendMessage. // - if (!IsHandleCreated) { + if (!IsHandleCreated) + { throw new InvalidOperationException(SR.ErrorNoMarshalingThread); } @@ -6977,7 +8045,8 @@ private object MarshaledInvoke(Control caller, Delegate method, object[] args, b // bool syncSameThread = false; int pid; // ignored - if (SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(this, Handle), out pid) == SafeNativeMethods.GetCurrentThreadId()) { + if (SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(this, Handle), out pid) == SafeNativeMethods.GetCurrentThreadId()) + { if (synchronous) syncSameThread = true; } @@ -6987,43 +8056,55 @@ private object MarshaledInvoke(Control caller, Delegate method, object[] args, b // the delegate being passed. // ExecutionContext executionContext = null; - if (!syncSameThread) { + if (!syncSameThread) + { executionContext = ExecutionContext.Capture(); } ThreadMethodEntry tme = new ThreadMethodEntry(caller, this, method, args, synchronous, executionContext); - lock (this) { - if (threadCallbackList == null) { + lock (this) + { + if (threadCallbackList == null) + { threadCallbackList = new Queue(); } } - lock (threadCallbackList) { - if (threadCallbackMessage == 0) { + lock (threadCallbackList) + { + if (threadCallbackMessage == 0) + { threadCallbackMessage = SafeNativeMethods.RegisterWindowMessage(Application.WindowMessagesVersion + "_ThreadCallbackMessage"); } threadCallbackList.Enqueue(tme); } - if (syncSameThread) { + if (syncSameThread) + { InvokeMarshaledCallbacks(); - } else { + } + else + { // UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), threadCallbackMessage, IntPtr.Zero, IntPtr.Zero); } - if (synchronous) { - if (!tme.IsCompleted) { + if (synchronous) + { + if (!tme.IsCompleted) + { WaitForWaitHandle(tme.AsyncWaitHandle); } - if (tme.exception != null) { + if (tme.exception != null) + { throw tme.exception; } return tme.retVal; } - else { - return(IAsyncResult)tme; + else + { + return (IAsyncResult)tme; } } @@ -7034,20 +8115,23 @@ private object MarshaledInvoke(Control caller, Delegate method, object[] args, b /// buffer needed. If a buffer was passed, it fills the buffer. /// If the passed buffer is not long enough it will return -1. /// - private void MarshalStringToMessage(string value, ref Message m) { - if (m.LParam == IntPtr.Zero) { + private void MarshalStringToMessage(string value, ref Message m) + { + if (m.LParam == IntPtr.Zero) + { m.Result = (IntPtr)((value.Length + 1) * sizeof(char)); return; } - if (unchecked((int)(long)m.WParam) < value.Length + 1) { + 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}; + char[] nullChar = new char[] { (char)0 }; byte[] nullBytes; byte[] bytes; @@ -7061,13 +8145,15 @@ private void MarshalStringToMessage(string value, ref Message m) { } // Used by form to notify the control that it has been "entered" - internal void NotifyEnter() { + 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() { + internal void NotifyLeave() + { Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Control::NotifyLeave() - " + this.Name); OnLeave(EventArgs.Empty); } @@ -7078,19 +8164,22 @@ internal void NotifyLeave() { /// to repaint. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void NotifyInvalidate(Rectangle invalidatedArea) { + protected virtual void NotifyInvalidate(Rectangle invalidatedArea) + { OnInvalidated(new InvalidateEventArgs(invalidatedArea)); } // Used by form to notify the control that it is validating. - private bool NotifyValidating() { + 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() { + private void NotifyValidated() + { OnValidated(EventArgs.Empty); } @@ -7098,32 +8187,41 @@ private void NotifyValidated() { /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected void InvokeOnClick(Control toInvoke, EventArgs e) { - if (toInvoke != null) { + protected void InvokeOnClick(Control toInvoke, EventArgs e) + { + if (toInvoke != null) + { toInvoke.OnClick(e); } } - protected virtual void OnAutoSizeChanged(EventArgs e) { + protected virtual void OnAutoSizeChanged(EventArgs e) + { Contract.Requires(e != null); EventHandler eh = Events[EventAutoSizeChanged] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnBackColorChanged(EventArgs e) { + protected virtual void OnBackColorChanged(EventArgs e) + { Contract.Requires(e != null); - if (GetAnyDisposingInHierarchy()) { + if (GetAnyDisposingInHierarchy()) + { return; } object backBrush = Properties.GetObject(PropBackBrush); - if (backBrush != null) { - if (GetState(STATE_OWNCTLBRUSH)) { + if (backBrush != null) + { + if (GetState(STATE_OWNCTLBRUSH)) + { IntPtr p = (IntPtr)backBrush; - if (p != IntPtr.Zero) { + if (p != IntPtr.Zero) + { SafeNativeMethods.DeleteObject(new HandleRef(this, p)); } } @@ -7133,90 +8231,108 @@ protected virtual void OnBackColorChanged(EventArgs e) { Invalidate(); EventHandler eh = Events[EventBackColor] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection != null) { + 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++) { + for (int i = 0; i < controlsCollection.Count; i++) + { controlsCollection[i].OnParentBackColorChanged(e); } } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnBackgroundImageChanged(EventArgs e) { + protected virtual void OnBackgroundImageChanged(EventArgs e) + { Contract.Requires(e != null); - if (GetAnyDisposingInHierarchy()) { + if (GetAnyDisposingInHierarchy()) + { return; } Invalidate(); EventHandler eh = Events[EventBackgroundImage] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection != null) { + 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++) { + for (int i = 0; i < controlsCollection.Count; i++) + { controlsCollection[i].OnParentBackgroundImageChanged(e); } } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnBackgroundImageLayoutChanged(EventArgs e) { + protected virtual void OnBackgroundImageLayoutChanged(EventArgs e) + { Contract.Requires(e != null); - if (GetAnyDisposingInHierarchy()) { + if (GetAnyDisposingInHierarchy()) + { return; } Invalidate(); EventHandler eh = Events[EventBackgroundImageLayout] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnBindingContextChanged(EventArgs e) { + protected virtual void OnBindingContextChanged(EventArgs e) + { Contract.Requires(e != null); - if (Properties.GetObject(PropBindings) != null) { + if (Properties.GetObject(PropBindings) != null) + { UpdateBindings(); } EventHandler eh = Events[EventBindingContext] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection != null) { + 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++) { + for (int i = 0; i < controlsCollection.Count; i++) + { controlsCollection[i].OnParentBindingContextChanged(e); } } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnCausesValidationChanged(EventArgs e) { + protected virtual void OnCausesValidationChanged(EventArgs e) + { Contract.Requires(e != null); EventHandler eh = Events[EventCausesValidation] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } @@ -7224,55 +8340,67 @@ protected virtual void OnCausesValidationChanged(EventArgs e) { /// Called when a child is about to resume its layout. The default implementation /// calls OnChildLayoutResuming on the parent. /// - internal virtual void OnChildLayoutResuming(Control child, bool performLayout) { - if (ParentInternal != null) { + internal virtual void OnChildLayoutResuming(Control child, bool performLayout) + { + if (ParentInternal != null) + { ParentInternal.OnChildLayoutResuming(child, performLayout); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnContextMenuChanged(EventArgs e) { + protected virtual void OnContextMenuChanged(EventArgs e) + { Contract.Requires(e != null); EventHandler eh = Events[EventContextMenu] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnContextMenuStripChanged(EventArgs e) { + protected virtual void OnContextMenuStripChanged(EventArgs e) + { Contract.Requires(e != null); EventHandler eh = Events[EventContextMenuStrip] as EventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnCursorChanged(EventArgs e) { + protected virtual void OnCursorChanged(EventArgs e) + { Contract.Requires(e != null); EventHandler eh = Events[EventCursor] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection != null) { + 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++) { + for (int i = 0; i < controlsCollection.Count; i++) + { controlsCollection[i].OnParentCursorChanged(e); } } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnDockChanged(EventArgs e) { + protected virtual void OnDockChanged(EventArgs e) + { Contract.Requires(e != null); EventHandler eh = Events[EventDock] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } @@ -7282,117 +8410,140 @@ protected virtual void OnDockChanged(EventArgs e) { /// Call base.OnEnabled to send this event to any registered event listeners. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnEnabledChanged(EventArgs e) { + protected virtual void OnEnabledChanged(EventArgs e) + { Contract.Requires(e != null); - if (GetAnyDisposingInHierarchy()) { + if (GetAnyDisposingInHierarchy()) + { return; } - if (IsHandleCreated) { + if (IsHandleCreated) + { SafeNativeMethods.EnableWindow(new HandleRef(this, Handle), Enabled); // User-paint controls should repaint when their enabled state changes // - if (GetStyle(ControlStyles.UserPaint)) { + if (GetStyle(ControlStyles.UserPaint)) + { Invalidate(); Update(); } } EventHandler eh = Events[EventEnabled] as EventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); } ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection != null) { + 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++) { + for (int i = 0; i < controlsCollection.Count; i++) + { controlsCollection[i].OnParentEnabledChanged(e); } } } - internal virtual void OnFrameWindowActivate(bool fActivate) { + internal virtual void OnFrameWindowActivate(bool fActivate) + { } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnFontChanged(EventArgs e) { + protected virtual void OnFontChanged(EventArgs e) + { Contract.Requires(e != null); // bail if disposing // - if (GetAnyDisposingInHierarchy()) { + if (GetAnyDisposingInHierarchy()) + { return; } Invalidate(); - if (Properties.ContainsInteger(PropFontHeight)) { + if (Properties.ContainsInteger(PropFontHeight)) + { Properties.SetInteger(PropFontHeight, -1); } // Cleanup any font handle wrapper... DisposeFontHandle(); - if (IsHandleCreated && !GetStyle(ControlStyles.UserPaint)) { + if (IsHandleCreated && !GetStyle(ControlStyles.UserPaint)) + { SetWindowFont(); } EventHandler eh = Events[EventFont] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - using(new LayoutTransaction(this, this, PropertyNames.Font, false)) { - if (controlsCollection != null) { + 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++) { + for (int i = 0; i < controlsCollection.Count; i++) + { controlsCollection[i].OnParentFontChanged(e); } } } - LayoutTransaction.DoLayout(this,this,PropertyNames.Font); + LayoutTransaction.DoLayout(this, this, PropertyNames.Font); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnForeColorChanged(EventArgs e) { + protected virtual void OnForeColorChanged(EventArgs e) + { Contract.Requires(e != null); - if (GetAnyDisposingInHierarchy()) { + if (GetAnyDisposingInHierarchy()) + { return; } Invalidate(); EventHandler eh = Events[EventForeColor] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection != null) { + 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++) { + for (int i = 0; i < controlsCollection.Count; i++) + { controlsCollection[i].OnParentForeColorChanged(e); } } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnRightToLeftChanged(EventArgs e) { + protected virtual void OnRightToLeftChanged(EventArgs e) + { Contract.Requires(e != null); - if (GetAnyDisposingInHierarchy()) { + if (GetAnyDisposingInHierarchy()) + { return; } - + // update the scroll position when the handle has been created // MUST SET THIS BEFORE CALLING RecreateHandle!!! SetState2(STATE2_SETSCROLLPOS, true); @@ -7400,16 +8551,19 @@ protected virtual void OnRightToLeftChanged(EventArgs e) { RecreateHandle(); EventHandler eh = Events[EventRightToLeft] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection != null) { + 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++) { + for (int i = 0; i < controlsCollection.Count; i++) + { controlsCollection[i].OnParentRightToLeftChanged(e); } } @@ -7426,48 +8580,59 @@ protected virtual void OnNotifyMessage(Message m) } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnParentBackColorChanged(EventArgs e) { + protected virtual void OnParentBackColorChanged(EventArgs e) + { Contract.Requires(e != null); Color backColor = Properties.GetColor(PropBackColor); - if (backColor.IsEmpty) { + if (backColor.IsEmpty) + { OnBackColorChanged(e); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnParentBackgroundImageChanged(EventArgs e) { + protected virtual void OnParentBackgroundImageChanged(EventArgs e) + { Contract.Requires(e != null); OnBackgroundImageChanged(e); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnParentBindingContextChanged(EventArgs e) { + protected virtual void OnParentBindingContextChanged(EventArgs e) + { Contract.Requires(e != null); - if (Properties.GetObject(PropBindingManager) == null) { + if (Properties.GetObject(PropBindingManager) == null) + { OnBindingContextChanged(e); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnParentCursorChanged(EventArgs e) { + protected virtual void OnParentCursorChanged(EventArgs e) + { Contract.Requires(e != null); - if (Properties.GetObject(PropCursor) == null) { + if (Properties.GetObject(PropCursor) == null) + { OnCursorChanged(e); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnParentEnabledChanged(EventArgs e) { + protected virtual void OnParentEnabledChanged(EventArgs e) + { Contract.Requires(e != null); - if (GetState(STATE_ENABLED)) { + if (GetState(STATE_ENABLED)) + { OnEnabledChanged(e); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnParentFontChanged(EventArgs e) { + protected virtual void OnParentFontChanged(EventArgs e) + { Contract.Requires(e != null); - if (Properties.GetObject(PropFont) == null) { + if (Properties.GetObject(PropFont) == null) + { OnFontChanged(e); } } @@ -7476,12 +8641,15 @@ protected virtual void OnParentFontChanged(EventArgs e) { // its handle. // presently internal as we feel this will be rare to // require override - internal virtual void OnParentHandleRecreated() { + 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) { + if (parent != null) + { + if (IsHandleCreated) + { UnsafeNativeMethods.SetParent(new HandleRef(this, this.Handle), new HandleRef(parent, parent.Handle)); UpdateZOrder(); } @@ -7490,8 +8658,9 @@ internal virtual void OnParentHandleRecreated() { // 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(); + if (ReflectParent == ParentInternal) + { + RecreateHandle(); } } @@ -7499,7 +8668,8 @@ internal virtual void OnParentHandleRecreated() { // its handle. // presently internal as we feel this will be rare to // require override - internal virtual void OnParentHandleRecreating() { + internal virtual void OnParentHandleRecreating() + { SetState(STATE_PARENTRECREATING, true); // swoop this control over to the parking window. @@ -7509,93 +8679,114 @@ internal virtual void OnParentHandleRecreating() { // should help improve recreate perf. // use SetParent directly so as to not raise ParentChanged events - if (IsHandleCreated) { + if (IsHandleCreated) + { Application.ParkHandle(new HandleRef(this, this.Handle)); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnParentForeColorChanged(EventArgs e) { + protected virtual void OnParentForeColorChanged(EventArgs e) + { Contract.Requires(e != null); Color foreColor = Properties.GetColor(PropForeColor); - if (foreColor.IsEmpty) { + if (foreColor.IsEmpty) + { OnForeColorChanged(e); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnParentRightToLeftChanged(EventArgs e) { + protected virtual void OnParentRightToLeftChanged(EventArgs e) + { Contract.Requires(e != null); - if (!Properties.ContainsInteger(PropRightToLeft) || ((RightToLeft)Properties.GetInteger(PropRightToLeft)) == RightToLeft.Inherit) { + if (!Properties.ContainsInteger(PropRightToLeft) || ((RightToLeft)Properties.GetInteger(PropRightToLeft)) == RightToLeft.Inherit) + { OnRightToLeftChanged(e); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnParentVisibleChanged(EventArgs e) { + protected virtual void OnParentVisibleChanged(EventArgs e) + { Contract.Requires(e != null); - if (GetState(STATE_VISIBLE)) { + if (GetState(STATE_VISIBLE)) + { OnVisibleChanged(e); } } // OnVisibleChanged/OnParentVisibleChanged is not called when a parent becomes invisible - internal virtual void OnParentBecameInvisible() { - if (GetState(STATE_VISIBLE)) { + internal virtual void OnParentBecameInvisible() + { + if (GetState(STATE_VISIBLE)) + { // This control became invisible too - notify its children ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection != null) { - for(int i = 0; i < controlsCollection.Count; i++) { + if (controlsCollection != null) + { + for (int i = 0; i < controlsCollection.Count; i++) + { Control ctl = controlsCollection[i]; - ctl.OnParentBecameInvisible(); + ctl.OnParentBecameInvisible(); } } } } - + /// /// Inheriting classes should override this method to handle this event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnPrint(PaintEventArgs e) { - if (e == null) { + protected virtual void OnPrint(PaintEventArgs e) + { + if (e == null) + { throw new ArgumentNullException(nameof(e)); } Contract.EndContractBlock(); - if (GetStyle(ControlStyles.UserPaint)) { + if (GetStyle(ControlStyles.UserPaint)) + { // Theme support requires that we paint the background // and foreground to support semi-transparent children PaintWithErrorHandling(e, PaintLayerBackground); e.ResetGraphics(); PaintWithErrorHandling(e, PaintLayerForeground); } - else { + else + { PrintPaintEventArgs ppev = e as PrintPaintEventArgs; Message m; bool releaseDC = false; IntPtr hdc = IntPtr.Zero; - if (ppev == null) { + if (ppev == null) + { IntPtr flags = (IntPtr)(NativeMethods.PRF_CHILDREN | NativeMethods.PRF_CLIENT | NativeMethods.PRF_ERASEBKGND | NativeMethods.PRF_NONCLIENT); hdc = e.HDC; - if (hdc == IntPtr.Zero) { + if (hdc == IntPtr.Zero) + { // a manually created paintevent args hdc = e.Graphics.GetHdc(); releaseDC = true; } m = Message.Create(this.Handle, Interop.WindowMessages.WM_PRINTCLIENT, hdc, flags); } - else { + else + { m = ppev.Message; } - try { + try + { DefWndProc(ref m); } - finally { - if (releaseDC) { + finally + { + if (releaseDC) + { e.Graphics.ReleaseHdcInternal(hdc); } } @@ -7603,29 +8794,35 @@ protected virtual void OnPrint(PaintEventArgs e) { } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnTabIndexChanged(EventArgs e) { + protected virtual void OnTabIndexChanged(EventArgs e) + { Contract.Requires(e != null); EventHandler eh = Events[EventTabIndex] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnTabStopChanged(EventArgs e) { + protected virtual void OnTabStopChanged(EventArgs e) + { Contract.Requires(e != null); EventHandler eh = Events[EventTabStop] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnTextChanged(EventArgs e) { + protected virtual void OnTextChanged(EventArgs e) + { Contract.Requires(e != null); EventHandler eh = Events[EventText] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } @@ -7635,16 +8832,20 @@ protected virtual void OnTextChanged(EventArgs e) { /// Call base.OnVisible to send this event to any registered event listeners. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnVisibleChanged(EventArgs e) { + protected virtual void OnVisibleChanged(EventArgs e) + { Contract.Requires(e != null); bool visible = this.Visible; - if (visible) { + if (visible) + { UnhookMouseEvent(); trackMouseEvent = null; } - if (parent != null && visible && !Created) { + if (parent != null && visible && !Created) + { bool isDisposing = GetAnyDisposingInHierarchy(); - if (!isDisposing) { + if (!isDisposing) + { // Usually the control is created by now, but in a few corner cases // exercised by the PropertyGrid dropdowns, it isn't CreateControl(); @@ -7652,51 +8853,62 @@ protected virtual void OnVisibleChanged(EventArgs e) { } EventHandler eh = Events[EventVisible] as EventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); } ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection != null) { + 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++) { + for (int i = 0; i < controlsCollection.Count; i++) + { Control ctl = controlsCollection[i]; - if (ctl.Visible) { + if (ctl.Visible) + { ctl.OnParentVisibleChanged(e); } - if (!visible) { + if (!visible) + { ctl.OnParentBecameInvisible(); } } } } - internal virtual void OnTopMostActiveXParentChanged(EventArgs e) { + internal virtual void OnTopMostActiveXParentChanged(EventArgs e) + { Contract.Requires(e != null); ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection != null) { + 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++) { + for (int i = 0; i < controlsCollection.Count; i++) + { controlsCollection[i].OnTopMostActiveXParentChanged(e); } } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnParentChanged(EventArgs e) { + protected virtual void OnParentChanged(EventArgs e) + { Contract.Requires(e != null); EventHandler eh = Events[EventParent] as EventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); } // // Inform the control that the topmost control is now an ActiveX control - if (TopMostParent.IsActiveX) { + if (TopMostParent.IsActiveX) + { OnTopMostActiveXParentChanged(EventArgs.Empty); } } @@ -7706,18 +8918,22 @@ protected virtual void OnParentChanged(EventArgs e) { /// event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnClick(EventArgs e) { + protected virtual void OnClick(EventArgs e) + { Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventClick]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnClientSizeChanged(EventArgs e) { + protected virtual void OnClientSizeChanged(EventArgs e) + { Contract.Requires(e != null); EventHandler eh = Events[EventClientSize] as EventHandler; - if (eh != null) { - eh(this,e); + if (eh != null) + { + eh(this, e); } } @@ -7725,27 +8941,32 @@ protected virtual void OnClientSizeChanged(EventArgs e) { /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnControlAdded(ControlEventArgs e) { + protected virtual void OnControlAdded(ControlEventArgs e) + { Contract.Requires(e != null); ControlEventHandler handler = (ControlEventHandler)Events[EventControlAdded]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnControlRemoved(ControlEventArgs e) { + protected virtual void OnControlRemoved(ControlEventArgs e) + { Contract.Requires(e != null); ControlEventHandler handler = (ControlEventHandler)Events[EventControlRemoved]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// Called when the control is first created. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnCreateControl() { + protected virtual void OnCreateControl() + { } /// @@ -7754,20 +8975,25 @@ protected virtual void OnCreateControl() { /// Call base.OnHandleCreated first. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnHandleCreated(EventArgs e) { + protected virtual void OnHandleCreated(EventArgs e) + { Contract.Requires(e != null); - if (this.IsHandleCreated) { - + if (this.IsHandleCreated) + { + // Setting fonts is for some reason incredibly expensive. // (Even if you exclude font handle creation) - if (!GetStyle(ControlStyles.UserPaint)){ + if (!GetStyle(ControlStyles.UserPaint)) + { SetWindowFont(); } - if (DpiHelper.IsPerMonitorV2Awareness && !(typeof(Form).IsAssignableFrom(this.GetType()))) { + if (DpiHelper.IsPerMonitorV2Awareness && !(typeof(Form).IsAssignableFrom(this.GetType()))) + { int old = deviceDpi; deviceDpi = (int)UnsafeNativeMethods.GetDpiForWindow(new HandleRef(this, HandleInternal)); - if (old != deviceDpi) { + if (old != deviceDpi) + { RescaleConstantsForDpi(old, deviceDpi); } } @@ -7778,21 +9004,27 @@ protected virtual void OnHandleCreated(EventArgs e) { SetAcceptDrops(AllowDrop); Region region = (Region)Properties.GetObject(PropRegion); - if (region != null) { + if (region != null) + { IntPtr regionHandle = GetHRgn(region); - try { - if (IsActiveX) { + try + { + if (IsActiveX) + { regionHandle = ActiveXMergeRegion(regionHandle); } - if (UnsafeNativeMethods.SetWindowRgn(new HandleRef(this, Handle), new HandleRef(this, regionHandle), SafeNativeMethods.IsWindowVisible(new HandleRef(this, Handle))) != 0) { + 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) { + finally + { + if (regionHandle != IntPtr.Zero) + { SafeNativeMethods.DeleteObject(new HandleRef(null, regionHandle)); } } @@ -7804,33 +9036,39 @@ protected virtual void OnHandleCreated(EventArgs e) { // Cache Handle in a local before asserting so we minimize code running under the Assert. IntPtr handle = Handle; - - if (accObj != null) { + + if (accObj != null) + { accObj.Handle = handle; } - if (ncAccObj != null) { + if (ncAccObj != null) + { ncAccObj.Handle = handle; } // Set the window text from the Text property. - if (text != null && text.Length != 0) { + if (text != null && text.Length != 0) + { Interop.User32.SetWindowTextW(new HandleRef(this, Handle), text); } - if (!(this is ScrollableControl) && !IsMirrored && GetState2(STATE2_SETSCROLLPOS) && !GetState2(STATE2_HAVEINVOKED)) { + if (!(this is ScrollableControl) && !IsMirrored && GetState2(STATE2_SETSCROLLPOS) && !GetState2(STATE2_HAVEINVOKED)) + { BeginInvoke(new EventHandler(this.OnSetScrollPosition)); SetState2(STATE2_HAVEINVOKED, true); SetState2(STATE2_SETSCROLLPOS, false); } // Listen to UserPreferenceChanged if the control is top level and interested in the notification. - if (GetState2(STATE2_INTERESTEDINUSERPREFERENCECHANGED)) { + if (GetState2(STATE2_INTERESTEDINUSERPREFERENCECHANGED)) + { ListenToUserPreferenceChanged(GetTopLevel()); } } EventHandler handler = (EventHandler)Events[EventHandleCreated]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); if (this.IsHandleCreated) { @@ -7838,38 +9076,45 @@ protected virtual void OnHandleCreated(EventArgs e) { // this last, so we're as close to the same state as when the message // was placed. // - if (GetState(STATE_THREADMARSHALLPENDING)) { + if (GetState(STATE_THREADMARSHALLPENDING)) + { UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), threadCallbackMessage, IntPtr.Zero, IntPtr.Zero); SetState(STATE_THREADMARSHALLPENDING, false); } } } - - private void OnSetScrollPosition(object sender, EventArgs e) { + + private void OnSetScrollPosition(object sender, EventArgs e) + { SetState2(STATE2_HAVEINVOKED, false); OnInvokedSetScrollPosition(sender, e); } - - internal virtual void OnInvokedSetScrollPosition(object sender, EventArgs e) { - if (!(this is ScrollableControl) && !IsMirrored) { + + internal virtual void OnInvokedSetScrollPosition(object sender, EventArgs e) + { + if (!(this is ScrollableControl) && !IsMirrored) + { NativeMethods.SCROLLINFO si = new NativeMethods.SCROLLINFO(); si.cbSize = Marshal.SizeOf(); si.fMask = NativeMethods.SIF_RANGE; - if (UnsafeNativeMethods.GetScrollInfo(new HandleRef(this, Handle), NativeMethods.SB_HORZ,si) != false) { + if (UnsafeNativeMethods.GetScrollInfo(new HandleRef(this, Handle), NativeMethods.SB_HORZ, si) != false) + { si.nPos = (RightToLeft == RightToLeft.Yes) ? si.nMax : si.nMin; SendMessage(Interop.WindowMessages.WM_HSCROLL, NativeMethods.Util.MAKELPARAM(NativeMethods.SB_THUMBPOSITION, si.nPos), 0); - } - } + } + } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnLocationChanged(EventArgs e) { + protected virtual void OnLocationChanged(EventArgs e) + { Contract.Requires(e != null); OnMove(EventArgs.Empty); EventHandler eh = Events[EventLocation] as EventHandler; - if (eh != null) { - eh(this,e); + if (eh != null) + { + eh(this, e); } } @@ -7880,19 +9125,25 @@ protected virtual void OnLocationChanged(EventArgs e) { /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnHandleDestroyed(EventArgs e) { + protected virtual void OnHandleDestroyed(EventArgs e) + { Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventHandleDestroyed]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); UpdateReflectParent(false); - if (!RecreatingHandle) { - if (GetState(STATE_OWNCTLBRUSH)) { + if (!RecreatingHandle) + { + if (GetState(STATE_OWNCTLBRUSH)) + { object backBrush = Properties.GetObject(PropBackBrush); - if (backBrush != null) { + if (backBrush != null) + { IntPtr p = (IntPtr)backBrush; - if (p != IntPtr.Zero) { + if (p != IntPtr.Zero) + { SafeNativeMethods.DeleteObject(new HandleRef(this, p)); } Properties.SetObject(PropBackBrush, null); @@ -7906,15 +9157,20 @@ protected virtual void OnHandleDestroyed(EventArgs e) { // label, etc. Without this processing, any time you change a // property that forces handle recreation, you lose your text! // See the above code in wmCreate - try { - if (!GetAnyDisposingInHierarchy()) { + try + { + if (!GetAnyDisposingInHierarchy()) + { text = Text; - if (text != null && text.Length == 0) text = null; + if (text != null && text.Length == 0) + text = null; } SetAcceptDrops(false); } - catch (Exception ex) { - if (ClientUtils.IsSecurityOrCriticalException(ex)) { + catch (Exception ex) + { + if (ClientUtils.IsSecurityOrCriticalException(ex)) + { throw; } @@ -7929,10 +9185,12 @@ protected virtual void OnHandleDestroyed(EventArgs e) { /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnDoubleClick(EventArgs e) { + protected virtual void OnDoubleClick(EventArgs e) + { Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventDoubleClick]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// @@ -7945,10 +9203,12 @@ protected virtual void OnDoubleClick(EventArgs e) { /// Call base.onDragEnter to send this event to any registered event listeners. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnDragEnter(DragEventArgs drgevent) { + protected virtual void OnDragEnter(DragEventArgs drgevent) + { Contract.Requires(drgevent != null); DragEventHandler handler = (DragEventHandler)Events[EventDragEnter]; - if (handler != null) handler(this,drgevent); + if (handler != null) + handler(this, drgevent); } /// @@ -7956,10 +9216,12 @@ protected virtual void OnDragEnter(DragEventArgs drgevent) { /// Call base.onDragOver to send this event to any registered event listeners. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnDragOver(DragEventArgs drgevent) { + protected virtual void OnDragOver(DragEventArgs drgevent) + { Contract.Requires(drgevent != null); DragEventHandler handler = (DragEventHandler)Events[EventDragOver]; - if (handler != null) handler(this,drgevent); + if (handler != null) + handler(this, drgevent); } /// @@ -7967,10 +9229,12 @@ protected virtual void OnDragOver(DragEventArgs drgevent) { /// Call base.onDragLeave to send this event to any registered event listeners. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnDragLeave(EventArgs e) { + protected virtual void OnDragLeave(EventArgs e) + { Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventDragLeave]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// @@ -7978,10 +9242,12 @@ protected virtual void OnDragLeave(EventArgs e) { /// Call base.onDragDrop to send this event to any registered event listeners. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnDragDrop(DragEventArgs drgevent) { + protected virtual void OnDragDrop(DragEventArgs drgevent) + { Contract.Requires(drgevent != null); DragEventHandler handler = (DragEventHandler)Events[EventDragDrop]; - if (handler != null) handler(this,drgevent); + if (handler != null) + handler(this, drgevent); } /// @@ -7990,25 +9256,31 @@ protected virtual void OnDragDrop(DragEventArgs drgevent) { /// [EditorBrowsable(EditorBrowsableState.Advanced)] [SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces")] - protected virtual void OnGiveFeedback(GiveFeedbackEventArgs gfbevent) { + protected virtual void OnGiveFeedback(GiveFeedbackEventArgs gfbevent) + { Contract.Requires(gfbevent != null); GiveFeedbackEventHandler handler = (GiveFeedbackEventHandler)Events[EventGiveFeedback]; - if (handler != null) handler(this,gfbevent); + if (handler != null) + handler(this, gfbevent); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnEnter(EventArgs e) { + protected virtual void OnEnter(EventArgs e) + { Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventEnter]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected void InvokeGotFocus(Control toInvoke, EventArgs e) { - if (toInvoke != null) { + protected void InvokeGotFocus(Control toInvoke, EventArgs e) + { + if (toInvoke != null) + { toInvoke.OnGotFocus(e); KeyboardToolTipStateMachine.Instance.NotifyAboutGotFocus(toInvoke); } @@ -8018,18 +9290,22 @@ protected void InvokeGotFocus(Control toInvoke, EventArgs e) { /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnGotFocus(EventArgs e) { + protected virtual void OnGotFocus(EventArgs e) + { Contract.Requires(e != null); - if (IsActiveX) { + if (IsActiveX) + { ActiveXOnFocus(true); } - - if (parent != null) { + + if (parent != null) + { parent.ChildGotFocus(this); } EventHandler handler = (EventHandler)Events[EventGotFocus]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// @@ -8042,7 +9318,7 @@ protected virtual void OnHelpRequested(HelpEventArgs hevent) HelpEventHandler handler = (HelpEventHandler)Events[EventHelpRequested]; if (handler != null) { - handler(this,hevent); + handler(this, hevent); // Mark the event as handled so that the event isn't raised for the // control's parent. if (hevent != null) @@ -8062,56 +9338,67 @@ protected virtual void OnHelpRequested(HelpEventArgs hevent) /// Call base.OnInvalidate to send this event to any registered event listeners. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnInvalidated(InvalidateEventArgs e) { + protected virtual void OnInvalidated(InvalidateEventArgs e) + { Contract.Requires(e != null); // Ask the site to change the view... - if (IsActiveX) { + if (IsActiveX) + { ActiveXViewChanged(); } - + // Transparent control support ControlCollection controls = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controls != null) { + if (controls != 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 < controls.Count; i++) { + for (int i = 0; i < controls.Count; i++) + { controls[i].OnParentInvalidated(e); } } InvalidateEventHandler handler = (InvalidateEventHandler)Events[EventInvalidated]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnKeyDown(KeyEventArgs e) { + protected virtual void OnKeyDown(KeyEventArgs e) + { Contract.Requires(e != null); KeyEventHandler handler = (KeyEventHandler)Events[EventKeyDown]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnKeyPress(KeyPressEventArgs e) { + protected virtual void OnKeyPress(KeyPressEventArgs e) + { Contract.Requires(e != null); KeyPressEventHandler handler = (KeyPressEventHandler)Events[EventKeyPress]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnKeyUp(KeyEventArgs e) { + protected virtual void OnKeyUp(KeyEventArgs e) + { Contract.Requires(e != null); KeyEventHandler handler = (KeyEventHandler)Events[EventKeyUp]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// @@ -8122,18 +9409,22 @@ protected virtual void OnKeyUp(KeyEventArgs e) { /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnLayout(LayoutEventArgs levent) { + protected virtual void OnLayout(LayoutEventArgs levent) + { Contract.Requires(levent != null); // Ask the site to change the view... - if (IsActiveX) { + if (IsActiveX) + { ActiveXViewChanged(); } LayoutEventHandler handler = (LayoutEventHandler)Events[EventLayout]; - if (handler != null) handler(this, levent); + if (handler != null) + handler(this, levent); bool parentRequiresLayout = LayoutEngine.Layout(this, levent); - if(parentRequiresLayout && ParentInternal != null) { + if (parentRequiresLayout && ParentInternal != null) + { // LayoutEngine.Layout can return true to request that our parent resize us because // we did not have enough room for our contents. We can not just call PerformLayout // because this container is currently suspended. PerformLayout will check this state @@ -8148,28 +9439,35 @@ protected virtual void OnLayout(LayoutEventArgs levent) { /// still suspended when this call is made. The default implementation /// calls OnChildLayoutResuming on the parent, if it exists. /// - internal virtual void OnLayoutResuming(bool performLayout) { - if (ParentInternal != null) { + internal virtual void OnLayoutResuming(bool performLayout) + { + if (ParentInternal != null) + { ParentInternal.OnChildLayoutResuming(this, performLayout); } } - - internal virtual void OnLayoutSuspended() { + + internal virtual void OnLayoutSuspended() + { } /// /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnLeave(EventArgs e) { + protected virtual void OnLeave(EventArgs e) + { Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventLeave]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected void InvokeLostFocus(Control toInvoke, EventArgs e) { - if (toInvoke != null) { + protected void InvokeLostFocus(Control toInvoke, EventArgs e) + { + if (toInvoke != null) + { toInvoke.OnLostFocus(e); KeyboardToolTipStateMachine.Instance.NotifyAboutLostFocus(toInvoke); } @@ -8179,80 +9477,97 @@ protected void InvokeLostFocus(Control toInvoke, EventArgs e) { /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnLostFocus(EventArgs e) { + protected virtual void OnLostFocus(EventArgs e) + { Contract.Requires(e != null); - if (IsActiveX) { + if (IsActiveX) + { ActiveXOnFocus(false); } EventHandler handler = (EventHandler)Events[EventLostFocus]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } - protected virtual void OnMarginChanged(EventArgs e) { + protected virtual void OnMarginChanged(EventArgs e) + { Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventMarginChanged]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnMouseDoubleClick(MouseEventArgs e) { + protected virtual void OnMouseDoubleClick(MouseEventArgs e) + { Contract.Requires(e != null); MouseEventHandler handler = (MouseEventHandler)Events[EventMouseDoubleClick]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnMouseClick(MouseEventArgs e) { + protected virtual void OnMouseClick(MouseEventArgs e) + { Contract.Requires(e != null); MouseEventHandler handler = (MouseEventHandler)Events[EventMouseClick]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnMouseCaptureChanged(EventArgs e) { + protected virtual void OnMouseCaptureChanged(EventArgs e) + { Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventMouseCaptureChanged]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnMouseDown(MouseEventArgs e) { + protected virtual void OnMouseDown(MouseEventArgs e) + { Contract.Requires(e != null); MouseEventHandler handler = (MouseEventHandler)Events[EventMouseDown]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnMouseEnter(EventArgs e) { + protected virtual void OnMouseEnter(EventArgs e) + { Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventMouseEnter]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnMouseLeave(EventArgs e) { + protected virtual void OnMouseLeave(EventArgs e) + { Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventMouseLeave]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// @@ -8264,10 +9579,11 @@ protected virtual void OnMouseLeave(EventArgs e) { /// /// [ - Browsable(true), + Browsable(true), EditorBrowsable(EditorBrowsableState.Always) ] - protected virtual void OnDpiChangedBeforeParent(EventArgs e) { + protected virtual void OnDpiChangedBeforeParent(EventArgs e) + { Contract.Requires(e != null); ((EventHandler)Events[EventDpiChangedBeforeParent])?.Invoke(this, e); } @@ -8281,10 +9597,11 @@ protected virtual void OnDpiChangedBeforeParent(EventArgs e) { /// /// [ - Browsable(true), + Browsable(true), EditorBrowsable(EditorBrowsableState.Always) ] - protected virtual void OnDpiChangedAfterParent(EventArgs e) { + protected virtual void OnDpiChangedAfterParent(EventArgs e) + { Contract.Requires(e != null); ((EventHandler)Events[EventDpiChangedAfterParent])?.Invoke(this, e); } @@ -8293,50 +9610,60 @@ protected virtual void OnDpiChangedAfterParent(EventArgs e) { /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnMouseHover(EventArgs e) { + protected virtual void OnMouseHover(EventArgs e) + { Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventMouseHover]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnMouseMove(MouseEventArgs e) { + protected virtual void OnMouseMove(MouseEventArgs e) + { Contract.Requires(e != null); MouseEventHandler handler = (MouseEventHandler)Events[EventMouseMove]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnMouseUp(MouseEventArgs e) { + protected virtual void OnMouseUp(MouseEventArgs e) + { Contract.Requires(e != null); MouseEventHandler handler = (MouseEventHandler)Events[EventMouseUp]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnMouseWheel(MouseEventArgs e) { + protected virtual void OnMouseWheel(MouseEventArgs e) + { Contract.Requires(e != null); MouseEventHandler handler = (MouseEventHandler)Events[EventMouseWheel]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnMove(EventArgs e) { + protected virtual void OnMove(EventArgs e) + { Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventMove]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); if (RenderTransparent) Invalidate(); } @@ -8346,19 +9673,24 @@ protected virtual void OnMove(EventArgs e) { /// Call base.onPaint to send this event to any registered event listeners. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnPaint(PaintEventArgs e) { + protected virtual void OnPaint(PaintEventArgs e) + { Contract.Requires(e != null); PaintEventHandler handler = (PaintEventHandler)Events[EventPaint]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } - protected virtual void OnPaddingChanged(EventArgs e) { + protected virtual void OnPaddingChanged(EventArgs e) + { Contract.Requires(e != null); - if (GetStyle(ControlStyles.ResizeRedraw)) { + if (GetStyle(ControlStyles.ResizeRedraw)) + { Invalidate(); } EventHandler handler = (EventHandler)Events[EventPaddingChanged]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// @@ -8368,30 +9700,35 @@ protected virtual void OnPaddingChanged(EventArgs e) { /// Windows behavior you must set event.handled to true. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnPaintBackground(PaintEventArgs pevent) { + protected virtual void OnPaintBackground(PaintEventArgs pevent) + { Contract.Requires(pevent != null); // We need the true client rectangle as clip rectangle causes // problems on "Windows Classic" theme. NativeMethods.RECT rect = new NativeMethods.RECT(); UnsafeNativeMethods.GetClientRect(new HandleRef(window, InternalHandle), ref rect); - + PaintBackground(pevent, new Rectangle(rect.left, rect.top, rect.right, rect.bottom)); } // Transparent control support - private void OnParentInvalidated(InvalidateEventArgs e) { + private void OnParentInvalidated(InvalidateEventArgs e) + { Contract.Requires(e != null); - if (!RenderTransparent) return; + if (!RenderTransparent) + return; - if (this.IsHandleCreated) { + if (this.IsHandleCreated) + { // move invalid rect into child space Rectangle cliprect = e.InvalidRect; Point offs = this.Location; - cliprect.Offset(-offs.X,-offs.Y); + cliprect.Offset(-offs.X, -offs.Y); cliprect = Rectangle.Intersect(this.ClientRectangle, cliprect); // if we don't intersect at all, do nothing - if (cliprect.IsEmpty) return; + if (cliprect.IsEmpty) + return; this.Invalidate(cliprect); } } @@ -8402,37 +9739,44 @@ private void OnParentInvalidated(InvalidateEventArgs e) { /// [EditorBrowsable(EditorBrowsableState.Advanced)] [SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces")] - protected virtual void OnQueryContinueDrag(QueryContinueDragEventArgs qcdevent) { + protected virtual void OnQueryContinueDrag(QueryContinueDragEventArgs qcdevent) + { Contract.Requires(qcdevent != null); QueryContinueDragEventHandler handler = (QueryContinueDragEventHandler)Events[EventQueryContinueDrag]; - if (handler != null) handler(this, qcdevent); + if (handler != null) + handler(this, qcdevent); } /// /// Raises the event when the Region property has changed. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnRegionChanged(EventArgs e) { - Contract.Requires(e != null); - EventHandler eh = Events[EventRegionChanged] as EventHandler; - if (eh != null) { + protected virtual void OnRegionChanged(EventArgs e) + { + Contract.Requires(e != null); + EventHandler eh = Events[EventRegionChanged] as EventHandler; + if (eh != null) + { eh(this, e); - } + } } /// /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnResize(EventArgs e) { + protected virtual void OnResize(EventArgs e) + { Contract.Requires(e != null); if ((controlStyle & ControlStyles.ResizeRedraw) == ControlStyles.ResizeRedraw - || GetState(STATE_EXCEPTIONWHILEPAINTING)) { + || GetState(STATE_EXCEPTIONWHILEPAINTING)) + { Invalidate(); } LayoutTransaction.DoLayout(this, this, PropertyNames.Bounds); EventHandler handler = (EventHandler)Events[EventResize]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// @@ -8442,22 +9786,26 @@ protected virtual void OnResize(EventArgs e) { EditorBrowsable(EditorBrowsableState.Advanced), SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers") ] - protected virtual void OnPreviewKeyDown(PreviewKeyDownEventArgs e) { + protected virtual void OnPreviewKeyDown(PreviewKeyDownEventArgs e) + { Contract.Requires(e != null); PreviewKeyDownEventHandler handler = (PreviewKeyDownEventHandler)Events[EventPreviewKeyDown]; - if (handler != null) { + if (handler != null) + { handler(this, e); } } - + [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnSizeChanged(EventArgs e) { + protected virtual void OnSizeChanged(EventArgs e) + { Contract.Requires(e != null); OnResize(EventArgs.Empty); EventHandler eh = Events[EventSize] as EventHandler; - if (eh != null) { - eh(this,e); + if (eh != null) + { + eh(this, e); } } @@ -8466,10 +9814,12 @@ protected virtual void OnSizeChanged(EventArgs e) { /// event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnChangeUICues(UICuesEventArgs e) { + protected virtual void OnChangeUICues(UICuesEventArgs e) + { Contract.Requires(e != null); UICuesEventHandler handler = (UICuesEventHandler)Events[EventChangeUICues]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// @@ -8477,10 +9827,12 @@ protected virtual void OnChangeUICues(UICuesEventArgs e) { /// event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnStyleChanged(EventArgs e) { + protected virtual void OnStyleChanged(EventArgs e) + { Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventStyleChanged]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// @@ -8488,21 +9840,25 @@ protected virtual void OnStyleChanged(EventArgs e) { /// event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnSystemColorsChanged(EventArgs e) { + protected virtual void OnSystemColorsChanged(EventArgs e) + { Contract.Requires(e != null); ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection != null) { + 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++) { + for (int i = 0; i < controlsCollection.Count; i++) + { controlsCollection[i].OnSystemColorsChanged(EventArgs.Empty); } } Invalidate(); EventHandler handler = (EventHandler)Events[EventSystemColorsChanged]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// @@ -8510,20 +9866,24 @@ protected virtual void OnSystemColorsChanged(EventArgs e) { /// event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnValidating(CancelEventArgs e) { + protected virtual void OnValidating(CancelEventArgs e) + { Contract.Requires(e != null); CancelEventHandler handler = (CancelEventHandler)Events[EventValidating]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnValidated(EventArgs e) { + protected virtual void OnValidated(EventArgs e) + { Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventValidated]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// @@ -8532,24 +9892,29 @@ protected virtual void OnValidated(EventArgs e) { /// The derived class can choose to not call the base class implementation. /// [ - Browsable(true), + Browsable(true), EditorBrowsable(EditorBrowsableState.Advanced) ] - protected virtual void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) { + protected virtual void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) + { } // This is basically OnPaintBackground, put in a separate method for ButtonBase, // which does all painting under OnPaint, and tries very hard to avoid double-painting the border pixels. - internal void PaintBackground(PaintEventArgs e, Rectangle rectangle) { + internal void PaintBackground(PaintEventArgs e, Rectangle rectangle) + { PaintBackground(e, rectangle, this.BackColor, Point.Empty); } - internal void PaintBackground(PaintEventArgs e, Rectangle rectangle, Color backColor) { + internal void PaintBackground(PaintEventArgs e, Rectangle rectangle, Color backColor) + { PaintBackground(e, rectangle, backColor, Point.Empty); } - internal void PaintBackground(PaintEventArgs e, Rectangle rectangle, Color backColor, Point scrollOffset) { - if (RenderColorTransparent(backColor)) { + internal void PaintBackground(PaintEventArgs e, Rectangle rectangle, Color backColor, Point scrollOffset) + { + if (RenderColorTransparent(backColor)) + { PaintTransparentBackground(e, rectangle); } @@ -8559,31 +9924,38 @@ internal void PaintBackground(PaintEventArgs e, Rectangle rectangle, Color backC // The rest of this won't do much if BackColor is transparent and there is no BackgroundImage, // but we need to call it in the partial alpha case. - if (BackgroundImage != null && !DisplayInformation.HighContrast && !formRTL) { + if (BackgroundImage != null && !DisplayInformation.HighContrast && !formRTL) + { - if (BackgroundImageLayout == ImageLayout.Tile) { - if (ControlPaint.IsImageTransparent(BackgroundImage)) { + if (BackgroundImageLayout == ImageLayout.Tile) + { + if (ControlPaint.IsImageTransparent(BackgroundImage)) + { PaintTransparentBackground(e, rectangle); } } Point scrollLocation = scrollOffset; ScrollableControl scrollControl = this as ScrollableControl; - if (scrollControl != null && scrollLocation != Point.Empty) { + if (scrollControl != null && scrollLocation != Point.Empty) + { scrollLocation = ((ScrollableControl)this).AutoScrollPosition; } - if (ControlPaint.IsImageTransparent(BackgroundImage)) { + if (ControlPaint.IsImageTransparent(BackgroundImage)) + { PaintBackColor(e, rectangle, backColor); } ControlPaint.DrawBackgroundImage(e.Graphics, BackgroundImage, backColor, BackgroundImageLayout, ClientRectangle, rectangle, scrollLocation, RightToLeft); } - else { + else + { PaintBackColor(e, rectangle, backColor); } } - private static void PaintBackColor(PaintEventArgs e, Rectangle rectangle, Color backColor) { + private static void PaintBackColor(PaintEventArgs e, Rectangle rectangle, Color backColor) + { // Common case of just painting the background. For this, we // use GDI because it is faster for simple things than creating // a graphics object, brush, etc. Also, we may be able to @@ -8593,24 +9965,30 @@ private static void PaintBackColor(PaintEventArgs e, Rectangle rectangle, Color // Note: PaintEvent.HDC == 0 if GDI+ has used the HDC -- it wouldn't be safe for us // to use it without enough bookkeeping to negate any performance gain of using GDI. - if (color.A == 255) { - using (WindowsGraphics wg = (e.HDC != IntPtr.Zero && DisplayInformation.BitsPerPixel > 8) ? - WindowsGraphics.FromHdc(e.HDC) : WindowsGraphics.FromGraphics(e.Graphics)) { + if (color.A == 255) + { + using (WindowsGraphics wg = (e.HDC != IntPtr.Zero && DisplayInformation.BitsPerPixel > 8) ? + WindowsGraphics.FromHdc(e.HDC) : WindowsGraphics.FromGraphics(e.Graphics)) + { color = wg.GetNearestColor(color); - using (WindowsBrush brush = new WindowsSolidBrush(wg.DeviceContext, color)) { + using (WindowsBrush brush = new WindowsSolidBrush(wg.DeviceContext, color)) + { wg.FillRectangle(brush, rectangle); } } } - else { + else + { // don't paint anything from 100% transparent background // - if (color.A > 0) { + if (color.A > 0) + { // Color has some transparency or we have no HDC, so we must // fall back to using GDI+. // - using (Brush brush = new SolidBrush(color)) { + using (Brush brush = new SolidBrush(color)) + { e.Graphics.FillRectangle(brush, rectangle); } } @@ -8618,7 +9996,8 @@ private static void PaintBackColor(PaintEventArgs e, Rectangle rectangle, Color } // Paints a red rectangle with a red X, painted on a white background - private void PaintException(PaintEventArgs e) { + private void PaintException(PaintEventArgs e) + { #if false StringFormat stringFormat = ControlPaint.StringFormatForAlignment(ContentAlignment.TopLeft); string exceptionText = Properties.GetObject(PropPaintingException).ToString(); @@ -8685,14 +10064,15 @@ private void PaintException(PaintEventArgs e) { } #else int penThickness = 2; - using (Pen pen = new Pen(Color.Red, penThickness)) { + using (Pen pen = new Pen(Color.Red, penThickness)) + { Rectangle clientRectangle = ClientRectangle; Rectangle rectangle = clientRectangle; rectangle.X++; rectangle.Y++; rectangle.Width--; rectangle.Height--; - + e.Graphics.DrawRectangle(pen, rectangle.X, rectangle.Y, rectangle.Width - 1, rectangle.Height - 1); rectangle.Inflate(-1, -1); e.Graphics.FillRectangle(Brushes.White, rectangle); @@ -8704,8 +10084,9 @@ private void PaintException(PaintEventArgs e) { #endif } - internal void PaintTransparentBackground(PaintEventArgs e, Rectangle rectangle) { - PaintTransparentBackground(e,rectangle,null); + internal void PaintTransparentBackground(PaintEventArgs e, Rectangle rectangle) + { + PaintTransparentBackground(e, rectangle, null); } // Trick our parent into painting our background for us, or paint some default // color if that doesn't work. @@ -8715,66 +10096,82 @@ internal void PaintTransparentBackground(PaintEventArgs e, Rectangle rectangle) // // If you only want a region of the control to be transparent, pass in a region into the // last parameter. A null region implies that you want the entire rectangle to be transparent. - internal void PaintTransparentBackground(PaintEventArgs e, Rectangle rectangle, Region transparentRegion) { + internal void PaintTransparentBackground(PaintEventArgs e, Rectangle rectangle, Region transparentRegion) + { Graphics g = e.Graphics; Control parent = this.ParentInternal; - if (parent != null) { + if (parent != null) + { // We need to use themeing painting for certain controls (like TabPage) when they parent other controls. // But we dont want to to this always as this causes serious preformance (at Runtime and DesignTime) // so checking for RenderTransparencyWithVisualStyles which is TRUE for TabPage and false by default. - if (Application.RenderWithVisualStyles && parent.RenderTransparencyWithVisualStyles) { + if (Application.RenderWithVisualStyles && parent.RenderTransparencyWithVisualStyles) + { // When we are rendering with visual styles, we can use the cool DrawThemeParentBackground function // that UxTheme provides to render the parent's background. This function is control agnostic, so // we use the wrapper in ButtonRenderer - this should do the right thing for all controls, // not just Buttons. - + GraphicsState graphicsState = null; - if (transparentRegion != null) { + if (transparentRegion != null) + { graphicsState = g.Save(); } - try { - if (transparentRegion != null) { + try + { + if (transparentRegion != null) + { g.Clip = transparentRegion; } ButtonRenderer.DrawParentBackground(g, rectangle, this); } - finally { - if (graphicsState != null) { - g.Restore(graphicsState); + finally + { + if (graphicsState != null) + { + g.Restore(graphicsState); } - } + } } - else { + else + { // how to move the rendering area and setup it's size // (we want to translate it to the parent's origin) - Rectangle shift = new Rectangle(-this.Left,-this.Top, parent.Width, parent.Height); + Rectangle shift = new Rectangle(-this.Left, -this.Top, parent.Width, parent.Height); // moving the clipping rectangle to the parent coordinate system Rectangle newClipRect = new Rectangle(rectangle.Left + this.Left, rectangle.Top + this.Top, rectangle.Width, rectangle.Height); - - using (WindowsGraphics wg = WindowsGraphics.FromGraphics(g)) { + + using (WindowsGraphics wg = WindowsGraphics.FromGraphics(g)) + { wg.DeviceContext.TranslateTransform(-this.Left, -this.Top); - using (PaintEventArgs np = new PaintEventArgs(wg.GetHdc(), newClipRect)) { - if (transparentRegion != null) { - np.Graphics.Clip = transparentRegion; + using (PaintEventArgs np = new PaintEventArgs(wg.GetHdc(), newClipRect)) + { + if (transparentRegion != null) + { + np.Graphics.Clip = transparentRegion; np.Graphics.TranslateClip(-shift.X, -shift.Y); } - try { + try + { InvokePaintBackground(parent, np); InvokePaint(parent, np); } - finally { - if (transparentRegion != null) { + finally + { + if (transparentRegion != null) + { // restore region back to original state. np.Graphics.TranslateClip(shift.X, shift.Y); } } } } - } + } } - else { + else + { // For whatever reason, our parent can't paint our background, but we need some kind of background // since we're transparent. g.FillRectangle(SystemBrushes.Control, rectangle); @@ -8785,22 +10182,29 @@ internal void PaintTransparentBackground(PaintEventArgs e, Rectangle rectangle, // So if user painting code has an issue, we make sure never to call it again, // so as not to spam the end-user with exception dialogs. // - private void PaintWithErrorHandling(PaintEventArgs e, short layer) { - try { + private void PaintWithErrorHandling(PaintEventArgs e, short layer) + { + try + { CacheTextInternal = true; - if (GetState(STATE_EXCEPTIONWHILEPAINTING)) { + if (GetState(STATE_EXCEPTIONWHILEPAINTING)) + { if (layer == PaintLayerBackground) PaintException(e); } - else { + else + { bool exceptionThrown = true; - try { - switch (layer) { + try + { + switch (layer) + { case PaintLayerForeground: OnPaint(e); break; case PaintLayerBackground: - if (!GetStyle(ControlStyles.Opaque)) { + if (!GetStyle(ControlStyles.Opaque)) + { OnPaintBackground(e); } break; @@ -8810,15 +10214,18 @@ private void PaintWithErrorHandling(PaintEventArgs e, short layer) { } exceptionThrown = false; } - finally { - if (exceptionThrown) { + finally + { + if (exceptionThrown) + { SetState(STATE_EXCEPTIONWHILEPAINTING, true); Invalidate(); } } } } - finally { + finally + { CacheTextInternal = false; } } @@ -8826,10 +10233,14 @@ private void PaintWithErrorHandling(PaintEventArgs e, short layer) { /// /// Find ContainerControl that is the container of this control. /// - internal ContainerControl ParentContainerControl { - get { - for (Control c = this.ParentInternal; c != null; c = c.ParentInternal) { - if (c is ContainerControl) { + internal ContainerControl ParentContainerControl + { + get + { + for (Control c = this.ParentInternal; c != null; c = c.ParentInternal) + { + if (c is ContainerControl) + { return c as ContainerControl; } } @@ -8842,8 +10253,10 @@ internal ContainerControl ParentContainerControl { /// Forces the control to apply layout logic to all of the child controls. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public void PerformLayout() { - if (cachedLayoutEventArgs != null) { + public void PerformLayout() + { + if (cachedLayoutEventArgs != null) + { PerformLayout(cachedLayoutEventArgs); cachedLayoutEventArgs = null; @@ -8852,7 +10265,8 @@ public void PerformLayout() { // SuspendLayout, PerformLayout, ResumeLayout() sequences. SetState2(STATE2_CLEARLAYOUTARGS, false); } - else { + else + { PerformLayout(null, null); } } @@ -8861,33 +10275,40 @@ public void PerformLayout() { /// Forces the control to apply layout logic to all of the child controls. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public void PerformLayout(Control affectedControl, string affectedProperty) { + public void PerformLayout(Control affectedControl, string affectedProperty) + { PerformLayout(new LayoutEventArgs(affectedControl, affectedProperty)); } - internal void PerformLayout(LayoutEventArgs args) { - if (GetAnyDisposingInHierarchy()) { + internal void PerformLayout(LayoutEventArgs args) + { + if (GetAnyDisposingInHierarchy()) + { return; } - if (layoutSuspendCount > 0) { + if (layoutSuspendCount > 0) + { SetState(STATE_LAYOUTDEFERRED, true); - if (cachedLayoutEventArgs == null || (GetState2(STATE2_CLEARLAYOUTARGS) && args != null)) { - cachedLayoutEventArgs = args; - if (GetState2(STATE2_CLEARLAYOUTARGS)) { - SetState2(STATE2_CLEARLAYOUTARGS, false); - } + if (cachedLayoutEventArgs == null || (GetState2(STATE2_CLEARLAYOUTARGS) && args != null)) + { + cachedLayoutEventArgs = args; + if (GetState2(STATE2_CLEARLAYOUTARGS)) + { + SetState2(STATE2_CLEARLAYOUTARGS, false); + } } - + LayoutEngine.ProcessSuspendedLayoutEventArgs(this, args); - + return; } // (Essentially the same as suspending layout while we layout, but we clear differently below.) layoutSuspendCount = 1; - try { + try + { CacheTextInternal = true; OnLayout(args); @@ -8908,7 +10329,8 @@ internal void PerformLayout(LayoutEventArgs args) { #endif #endif } - finally { + finally + { CacheTextInternal = false; // Rather than resume layout (which will could allow a deferred layout to layout the // the container we just finished laying out) we set layoutSuspendCount back to zero @@ -8919,7 +10341,8 @@ internal void PerformLayout(LayoutEventArgs args) { // LayoutEngine.Layout can return true to request that our parent resize us because // we did not have enough room for our contents. Now that we are unsuspended, // see if this happened and layout parent if necessary. (See also OnLayout) - if(ParentInternal != null && ParentInternal.GetState(STATE_LAYOUTISDIRTY)) { + if (ParentInternal != null && ParentInternal.GetState(STATE_LAYOUTISDIRTY)) + { LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.PreferredSize); } } @@ -8936,30 +10359,37 @@ internal void PerformLayout(LayoutEventArgs args) { /// for the context in which the validation is occuring, eg. change of focus /// between controls in a container. Stuff like that is handled by the caller. /// - internal bool PerformControlValidation(bool bulkValidation) { + internal bool PerformControlValidation(bool bulkValidation) + { // Skip validation for controls that don't support it - if (!this.CausesValidation) { + if (!this.CausesValidation) + { return false; } // Raise the 'Validating' event. Stop now if handler cancels (ie. control is invalid). // NOTE: Handler may throw an exception here, but we must not attempt to catch it. - if (this.NotifyValidating()) { + if (this.NotifyValidating()) + { return true; } // Raise the 'Validated' event. Handlers may throw exceptions here too - but // convert these to ThreadException events, unless the app is being debugged, // or the control is being validated as part of a bulk validation operation. - if (bulkValidation || NativeWindow.WndProcShouldBeDebuggable) { + if (bulkValidation || NativeWindow.WndProcShouldBeDebuggable) + { this.NotifyValidated(); } - else { - try { + else + { + try + { this.NotifyValidated(); } - catch (Exception e) { + catch (Exception e) + { Application.OnThreadException(e); } } @@ -8973,29 +10403,34 @@ internal bool PerformControlValidation(bool bulkValidation) { /// Return value indicates whether validation failed for any of the controls validated. /// Calling function is responsible for checking the correctness of the validationConstraints argument. /// - internal bool PerformContainerValidation(ValidationConstraints validationConstraints) { + internal bool PerformContainerValidation(ValidationConstraints validationConstraints) + { bool failed = false; // For every child control of this container control... - foreach (Control c in Controls) { + foreach (Control c in Controls) + { // First, if the control is a container, recurse into its descendants. if ((validationConstraints & ValidationConstraints.ImmediateChildren) != ValidationConstraints.ImmediateChildren && c.ShouldPerformContainerValidation() && - c.PerformContainerValidation(validationConstraints)) { + c.PerformContainerValidation(validationConstraints)) + { failed = true; } // Next, use input flags to decide whether to validate the control itself if ((validationConstraints & ValidationConstraints.Selectable) == ValidationConstraints.Selectable && !c.GetStyle(ControlStyles.Selectable) || - (validationConstraints & ValidationConstraints.Enabled) == ValidationConstraints.Enabled && !c.Enabled || - (validationConstraints & ValidationConstraints.Visible) == ValidationConstraints.Visible && !c.Visible || - (validationConstraints & ValidationConstraints.TabStop) == ValidationConstraints.TabStop && !c.TabStop) { + (validationConstraints & ValidationConstraints.Enabled) == ValidationConstraints.Enabled && !c.Enabled || + (validationConstraints & ValidationConstraints.Visible) == ValidationConstraints.Visible && !c.Visible || + (validationConstraints & ValidationConstraints.TabStop) == ValidationConstraints.TabStop && !c.TabStop) + { continue; } // Finally, perform validation on the control itself - if (c.PerformControlValidation(true)) { + if (c.PerformControlValidation(true)) + { failed = true; } } @@ -9061,38 +10496,48 @@ public Point PointToScreen(Point p) /// preProcessMessage(). /// /// - public virtual bool PreProcessMessage(ref Message msg) { - // Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "Control.PreProcessMessage " + msg.ToString()); + public virtual bool PreProcessMessage(ref Message msg) + { + // Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "Control.PreProcessMessage " + msg.ToString()); bool ret; - if (msg.Msg == Interop.WindowMessages.WM_KEYDOWN || msg.Msg == Interop.WindowMessages.WM_SYSKEYDOWN) { - if (!GetState2(STATE2_UICUES)) { + if (msg.Msg == Interop.WindowMessages.WM_KEYDOWN || msg.Msg == Interop.WindowMessages.WM_SYSKEYDOWN) + { + if (!GetState2(STATE2_UICUES)) + { ProcessUICues(ref msg); } Keys keyData = (Keys)(unchecked((int)(long)msg.WParam) | (int)ModifierKeys); - if (ProcessCmdKey(ref msg, keyData)) { + if (ProcessCmdKey(ref msg, keyData)) + { ret = true; } - else if (IsInputKey(keyData)) { + else if (IsInputKey(keyData)) + { SetState2(STATE2_INPUTKEY, true); ret = false; } - else { + else + { ret = ProcessDialogKey(keyData); } } - else if (msg.Msg == Interop.WindowMessages.WM_CHAR || msg.Msg == Interop.WindowMessages.WM_SYSCHAR) { - if (msg.Msg == Interop.WindowMessages.WM_CHAR && IsInputChar((char)msg.WParam)) { + else if (msg.Msg == Interop.WindowMessages.WM_CHAR || msg.Msg == Interop.WindowMessages.WM_SYSCHAR) + { + if (msg.Msg == Interop.WindowMessages.WM_CHAR && IsInputChar((char)msg.WParam)) + { SetState2(STATE2_INPUTCHAR, true); ret = false; } - else { + else + { ret = ProcessDialogChar((char)msg.WParam); } } - else { + else + { ret = false; } @@ -9105,7 +10550,8 @@ public virtual bool PreProcessMessage(ref Message msg) { SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters"), SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference") ] // using ref is OK. - public PreProcessControlState PreProcessControlMessage(ref Message msg) { + public PreProcessControlState PreProcessControlMessage(ref Message msg) + { return PreProcessControlMessageInternal(null, ref msg); } @@ -9125,70 +10571,83 @@ public PreProcessControlState PreProcessControlMessage(ref Message msg) { /// return false. /// [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] - internal static PreProcessControlState PreProcessControlMessageInternal(Control target, ref Message msg) { - if (target == null) { + internal static PreProcessControlState PreProcessControlMessageInternal(Control target, ref Message msg) + { + if (target == null) + { target = Control.FromChildHandle(msg.HWnd); } - if (target == null) { + if (target == null) + { return PreProcessControlState.MessageNotNeeded; } // reset state that is used to make sure IsInputChar, IsInputKey and // ProcessUICues are not called multiple times. // ISSUE: Which control should these state bits be set on? probably the target. - target.SetState2(STATE2_INPUTKEY, false); + target.SetState2(STATE2_INPUTKEY, false); target.SetState2(STATE2_INPUTCHAR, false); - target.SetState2(STATE2_UICUES, true); + target.SetState2(STATE2_UICUES, true); Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "Control.PreProcessControlMessageInternal " + msg.ToString()); - - try { + + try + { Keys keyData = (Keys)(unchecked((int)(long)msg.WParam) | (int)ModifierKeys); // Allow control to preview key down message. - if (msg.Msg == Interop.WindowMessages.WM_KEYDOWN || msg.Msg == Interop.WindowMessages.WM_SYSKEYDOWN) { - target.ProcessUICues(ref msg); + if (msg.Msg == Interop.WindowMessages.WM_KEYDOWN || msg.Msg == Interop.WindowMessages.WM_SYSKEYDOWN) + { + target.ProcessUICues(ref msg); PreviewKeyDownEventArgs args = new PreviewKeyDownEventArgs(keyData); target.OnPreviewKeyDown(args); - - if (args.IsInputKey) { + + if (args.IsInputKey) + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "PreviewKeyDown indicated this is an input key."); // Control wants this message - indicate it should be dispatched. return PreProcessControlState.MessageNeeded; - } + } } PreProcessControlState state = PreProcessControlState.MessageNotNeeded; - - if (!target.PreProcessMessage(ref msg)) { - if (msg.Msg == Interop.WindowMessages.WM_KEYDOWN || msg.Msg == Interop.WindowMessages.WM_SYSKEYDOWN) { + + if (!target.PreProcessMessage(ref msg)) + { + if (msg.Msg == Interop.WindowMessages.WM_KEYDOWN || msg.Msg == Interop.WindowMessages.WM_SYSKEYDOWN) + { // check if IsInputKey has already procssed this message // or if it is safe to call - we only want it to be called once. - if (target.GetState2(STATE2_INPUTKEY) || target.IsInputKey(keyData)) { + if (target.GetState2(STATE2_INPUTKEY) || target.IsInputKey(keyData)) + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "Control didn't preprocess this message but it needs to be dispatched"); state = PreProcessControlState.MessageNeeded; } } - else if (msg.Msg == Interop.WindowMessages.WM_CHAR || msg.Msg == Interop.WindowMessages.WM_SYSCHAR) { + else if (msg.Msg == Interop.WindowMessages.WM_CHAR || msg.Msg == Interop.WindowMessages.WM_SYSCHAR) + { // check if IsInputChar has already procssed this message // or if it is safe to call - we only want it to be called once. - if (target.GetState2(STATE2_INPUTCHAR) || target.IsInputChar((char)msg.WParam)) { + if (target.GetState2(STATE2_INPUTCHAR) || target.IsInputChar((char)msg.WParam)) + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "Control didn't preprocess this message but it needs to be dispatched"); state = PreProcessControlState.MessageNeeded; } - } + } } - else { + else + { state = PreProcessControlState.MessageProcessed; } return state; } - finally { + finally + { target.SetState2(STATE2_UICUES, false); } } @@ -9218,28 +10677,32 @@ internal static PreProcessControlState PreProcessControlMessageInternal(Control /// Controls will seldom, if ever, need to override this method. /// /// - protected virtual bool ProcessCmdKey(ref Message msg, Keys keyData) { + protected virtual bool ProcessCmdKey(ref Message msg, Keys keyData) + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "Control.ProcessCmdKey " + msg.ToString()); ContextMenu contextMenu = (ContextMenu)Properties.GetObject(PropContextMenu); - if (contextMenu != null && contextMenu.ProcessCmdKey(ref msg, keyData, this)) { + if (contextMenu != null && contextMenu.ProcessCmdKey(ref msg, keyData, this)) + { return true; } - if (parent != null) { + if (parent != null) + { return parent.ProcessCmdKey(ref msg, keyData); } return false; } - private void PrintToMetaFile(HandleRef hDC, IntPtr lParam) { + private void PrintToMetaFile(HandleRef hDC, IntPtr lParam) + { Debug.Assert(UnsafeNativeMethods.GetObjectType(hDC) == NativeMethods.OBJ_ENHMETADC, "PrintToMetaFile() called with a non-Enhanced MetaFile DC."); - Debug.Assert(((long) lParam & NativeMethods.PRF_CHILDREN) != 0, + Debug.Assert(((long)lParam & NativeMethods.PRF_CHILDREN) != 0, "PrintToMetaFile() called without PRF_CHILDREN."); // Strip the PRF_CHILDREN flag. We will manually walk our children and print them. - lParam = (IntPtr)((long) lParam & ~NativeMethods.PRF_CHILDREN); + lParam = (IntPtr)((long)lParam & ~NativeMethods.PRF_CHILDREN); // We're the root contol, so we need to set up our clipping region. Retrieve the // x-coordinates and y-coordinates of the viewport origin for the specified device context. @@ -9247,10 +10710,11 @@ private void PrintToMetaFile(HandleRef hDC, IntPtr lParam) { bool success = SafeNativeMethods.GetViewportOrgEx(hDC, viewportOrg); Debug.Assert(success, "GetViewportOrgEx() failed."); - HandleRef hClippingRegion = new HandleRef(null, SafeNativeMethods.CreateRectRgn(viewportOrg.x,viewportOrg.y, viewportOrg.x + this.Width, viewportOrg.y + this.Height)); + HandleRef hClippingRegion = new HandleRef(null, SafeNativeMethods.CreateRectRgn(viewportOrg.x, viewportOrg.y, viewportOrg.x + this.Width, viewportOrg.y + this.Height)); Debug.Assert(hClippingRegion.Handle != IntPtr.Zero, "CreateRectRgn() failed."); - try { + try + { // Select the new clipping region; make sure it's a SIMPLEREGION or NULLREGION NativeMethods.RegionFlags selectResult = (NativeMethods.RegionFlags)SafeNativeMethods.SelectClipRgn(hDC, hClippingRegion); Debug.Assert((selectResult == NativeMethods.RegionFlags.SIMPLEREGION || @@ -9259,16 +10723,19 @@ private void PrintToMetaFile(HandleRef hDC, IntPtr lParam) { PrintToMetaFileRecursive(hDC, lParam, new Rectangle(Point.Empty, this.Size)); } - finally { + finally + { success = SafeNativeMethods.DeleteObject(hClippingRegion); Debug.Assert(success, "DeleteObject() failed."); } } - internal virtual void PrintToMetaFileRecursive(HandleRef hDC, IntPtr lParam, Rectangle bounds) { + internal virtual void PrintToMetaFileRecursive(HandleRef hDC, IntPtr lParam, Rectangle bounds) + { // We assume the target does not want us to offset the root control in the metafile. - using (WindowsFormsUtils.DCMapping mapping = new WindowsFormsUtils.DCMapping(hDC, bounds)) { + using (WindowsFormsUtils.DCMapping mapping = new WindowsFormsUtils.DCMapping(hDC, bounds)) + { // print the non-client area PrintToMetaFile_SendPrintMessage(hDC, (IntPtr)((long)lParam & ~NativeMethods.PRF_CLIENT)); @@ -9280,15 +10747,18 @@ internal virtual void PrintToMetaFileRecursive(HandleRef hDC, IntPtr lParam, Rec clientOffset = new Point(clientOffset.X - windowRect.left, clientOffset.Y - windowRect.top); Rectangle clientBounds = new Rectangle(clientOffset, ClientSize); - using (WindowsFormsUtils.DCMapping clientMapping = new WindowsFormsUtils.DCMapping(hDC, clientBounds)) { + using (WindowsFormsUtils.DCMapping clientMapping = new WindowsFormsUtils.DCMapping(hDC, clientBounds)) + { // print the client area PrintToMetaFile_SendPrintMessage(hDC, (IntPtr)((long)lParam & ~NativeMethods.PRF_NONCLIENT)); // Paint children in reverse Z-Order int count = Controls.Count; - for (int i = count - 1; i >= 0; i--) { + for (int i = count - 1; i >= 0; i--) + { Control child = Controls[i]; - if(child.Visible) { + if (child.Visible) + { child.PrintToMetaFileRecursive(hDC, lParam, child.Bounds); } } @@ -9296,24 +10766,29 @@ internal virtual void PrintToMetaFileRecursive(HandleRef hDC, IntPtr lParam, Rec } } - private void PrintToMetaFile_SendPrintMessage(HandleRef hDC, IntPtr lParam) { - if(GetStyle(ControlStyles.UserPaint)) { + private void PrintToMetaFile_SendPrintMessage(HandleRef hDC, IntPtr lParam) + { + if (GetStyle(ControlStyles.UserPaint)) + { // We let user paint controls paint directly into the metafile SendMessage(Interop.WindowMessages.WM_PRINT, hDC.Handle, lParam); } - else { + else + { // If a system control has no children in the Controls collection we // restore the the PRF_CHILDREN flag because it may internally // have nested children we do not know about. ComboBox is a // good example. - if(Controls.Count == 0) { - lParam = (IntPtr)((long) lParam | NativeMethods.PRF_CHILDREN); + if (Controls.Count == 0) + { + lParam = (IntPtr)((long)lParam | NativeMethods.PRF_CHILDREN); } // System controls must be painted into a temporary bitmap // which is then copied into the metafile. (Old GDI line drawing // is 1px thin, which causes borders to disappear, etc.) - using (MetafileDCWrapper dcWrapper = new MetafileDCWrapper(hDC, this.Size)) { + using (MetafileDCWrapper dcWrapper = new MetafileDCWrapper(hDC, this.Size)) + { SendMessage(Interop.WindowMessages.WM_PRINT, dcWrapper.HDC, lParam); } } @@ -9342,9 +10817,10 @@ private void PrintToMetaFile_SendPrintMessage(HandleRef hDC, IntPtr lParam) { /// Controls will seldom, if ever, need to override this method. /// /// - protected virtual bool ProcessDialogChar(char charCode) { + protected virtual bool ProcessDialogChar(char charCode) + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "Control.ProcessDialogChar [" + charCode.ToString() + "]"); - return parent == null? false: parent.ProcessDialogChar(charCode); + return parent == null ? false : parent.ProcessDialogChar(charCode); } /// @@ -9370,9 +10846,10 @@ protected virtual bool ProcessDialogChar(char charCode) { /// Controls will seldom, if ever, need to override this method. /// /// - protected virtual bool ProcessDialogKey(Keys keyData) { + protected virtual bool ProcessDialogKey(Keys keyData) + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "Control.ProcessDialogKey " + keyData.ToString()); - return parent == null? false: parent.ProcessDialogKey(keyData); + return parent == null ? false : parent.ProcessDialogKey(keyData); } /// @@ -9394,29 +10871,34 @@ protected virtual bool ProcessDialogKey(Keys keyData) { /// Controls will seldom, if ever, need to override this method. /// /// - protected virtual bool ProcessKeyEventArgs(ref Message m) { + protected virtual bool ProcessKeyEventArgs(ref Message m) + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "Control.ProcessKeyEventArgs " + m.ToString()); KeyEventArgs ke = null; KeyPressEventArgs kpe = null; IntPtr newWParam = IntPtr.Zero; - if (m.Msg == Interop.WindowMessages.WM_CHAR || m.Msg == Interop.WindowMessages.WM_SYSCHAR) { + if (m.Msg == Interop.WindowMessages.WM_CHAR || m.Msg == Interop.WindowMessages.WM_SYSCHAR) + { int charsToIgnore = this.ImeWmCharsToIgnore; - if (charsToIgnore > 0) { + if (charsToIgnore > 0) + { charsToIgnore--; Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "charsToIgnore decreased, new val = " + charsToIgnore + ", this=" + this); this.ImeWmCharsToIgnore = charsToIgnore; return false; } - else { + else + { kpe = new KeyPressEventArgs(unchecked((char)(long)m.WParam)); OnKeyPress(kpe); - newWParam = (IntPtr) kpe.KeyChar; + newWParam = (IntPtr)kpe.KeyChar; } } - else if (m.Msg == Interop.WindowMessages.WM_IME_CHAR) { + else if (m.Msg == Interop.WindowMessages.WM_IME_CHAR) + { int charsToIgnore = this.ImeWmCharsToIgnore; charsToIgnore += (3 - sizeof(char)); @@ -9428,33 +10910,41 @@ protected virtual bool ProcessKeyEventArgs(ref Message m) { OnKeyPress(kpe); //If the character wasn't changed, just use the original value rather than round tripping. - if (kpe.KeyChar == preEventCharacter) { + if (kpe.KeyChar == preEventCharacter) + { newWParam = m.WParam; } - else { + else + { newWParam = (IntPtr)kpe.KeyChar; } } - else { + else + { ke = new KeyEventArgs((Keys)(unchecked((int)(long)m.WParam)) | ModifierKeys); - if (m.Msg == Interop.WindowMessages.WM_KEYDOWN || m.Msg == Interop.WindowMessages.WM_SYSKEYDOWN) { + if (m.Msg == Interop.WindowMessages.WM_KEYDOWN || m.Msg == Interop.WindowMessages.WM_SYSKEYDOWN) + { OnKeyDown(ke); } - else { + else + { OnKeyUp(ke); } } - if (kpe != null) { + if (kpe != null) + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, " processkeyeventarg returning: " + kpe.Handled); m.WParam = newWParam; return kpe.Handled; } - else { + else + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, " processkeyeventarg returning: " + ke.Handled); - if (ke.SuppressKeyPress) { - RemovePendingMessages(Interop.WindowMessages.WM_CHAR, Interop.WindowMessages.WM_CHAR); - RemovePendingMessages(Interop.WindowMessages.WM_SYSCHAR, Interop.WindowMessages.WM_SYSCHAR); + if (ke.SuppressKeyPress) + { + RemovePendingMessages(Interop.WindowMessages.WM_CHAR, Interop.WindowMessages.WM_CHAR); + RemovePendingMessages(Interop.WindowMessages.WM_SYSCHAR, Interop.WindowMessages.WM_SYSCHAR); RemovePendingMessages(Interop.WindowMessages.WM_IME_CHAR, Interop.WindowMessages.WM_IME_CHAR); } return ke.Handled; @@ -9476,9 +10966,11 @@ protected virtual bool ProcessKeyEventArgs(ref Message m) { /// returned. /// Controls will seldom, if ever, need to override this method. /// - protected internal virtual bool ProcessKeyMessage(ref Message m) { + protected internal virtual bool ProcessKeyMessage(ref Message m) + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "Control.ProcessKeyMessage " + m.ToString()); - if (parent != null && parent.ProcessKeyPreview(ref m)) return true; + if (parent != null && parent.ProcessKeyPreview(ref m)) + return true; return ProcessKeyEventArgs(ref m); } @@ -9506,9 +10998,10 @@ protected internal virtual bool ProcessKeyMessage(ref Message m) { /// returned. /// /// - protected virtual bool ProcessKeyPreview(ref Message m) { + protected virtual bool ProcessKeyPreview(ref Message m) + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "Control.ProcessKeyPreview " + m.ToString()); - return parent == null? false: parent.ProcessKeyPreview(ref m); + return parent == null ? false : parent.ProcessKeyPreview(ref m); } /// @@ -9535,86 +11028,98 @@ protected virtual bool ProcessKeyPreview(ref Message m) { /// to indicate that the control has no mnemonic. /// /// - protected internal virtual bool ProcessMnemonic(char charCode) { + protected internal virtual bool ProcessMnemonic(char charCode) + { #if DEBUG Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "Control.ProcessMnemonic [0x" + ((int)charCode).ToString("X", CultureInfo.InvariantCulture) + "]"); #endif return false; } - /// - /// Preprocess keys which affect focus indicators and keyboard cues. - /// - internal void ProcessUICues(ref Message msg) { - Keys keyCode = (Keys)((int)msg.WParam) & Keys.KeyCode; - - if (keyCode != Keys.F10 && keyCode != Keys.Menu && keyCode != Keys.Tab) { - return; // PERF: dont WM_QUERYUISTATE if we dont have to. - } - - Control topMostParent = null; - int current = unchecked( (int) (long)SendMessage(Interop.WindowMessages.WM_QUERYUISTATE, 0, 0)); - - // dont trust when a control says the accelerators are showing. - // make sure the topmost parent agrees with this as we could be in a mismatched state. - if (current == 0 /*accelerator and focus cues are showing*/) { - topMostParent = this.TopMostParent; - current = (int)topMostParent.SendMessage(Interop.WindowMessages.WM_QUERYUISTATE, 0, 0); - } - int toClear = 0; + /// + /// Preprocess keys which affect focus indicators and keyboard cues. + /// + internal void ProcessUICues(ref Message msg) + { + Keys keyCode = (Keys)((int)msg.WParam) & Keys.KeyCode; + + if (keyCode != Keys.F10 && keyCode != Keys.Menu && keyCode != Keys.Tab) + { + return; // PERF: dont WM_QUERYUISTATE if we dont have to. + } + + Control topMostParent = null; + int current = unchecked((int)(long)SendMessage(Interop.WindowMessages.WM_QUERYUISTATE, 0, 0)); + + // dont trust when a control says the accelerators are showing. + // make sure the topmost parent agrees with this as we could be in a mismatched state. + if (current == 0 /*accelerator and focus cues are showing*/) + { + topMostParent = this.TopMostParent; + current = (int)topMostParent.SendMessage(Interop.WindowMessages.WM_QUERYUISTATE, 0, 0); + } + int toClear = 0; // if we are here, a key or tab has been pressed on this control. // now that we know the state of accelerators, check to see if we need // to show them. NOTE: due to the strangeness of the API we OR in // the opposite of what we want to do. So if we want to show accelerators, // we OR in UISF_HIDEACCEL, then call UIS_CLEAR to clear the "hidden" state. - - if (keyCode == Keys.F10 || keyCode == Keys.Menu) { - if ((current & NativeMethods.UISF_HIDEACCEL) != 0) { - // Keyboard accelerators are hidden, they need to be shown - toClear |= NativeMethods.UISF_HIDEACCEL; - } - } - - if (keyCode == Keys.Tab) { - if ((current & NativeMethods.UISF_HIDEFOCUS) != 0) { - // Focus indicators are hidden, they need to be shown - toClear |= NativeMethods.UISF_HIDEFOCUS; - } - } - - if (toClear != 0) { - // We've detected some state we need to unset, usually clearing the hidden state of - // the accelerators. We need to get the topmost parent and call CHANGEUISTATE so - // that the entire tree of controls is - if (topMostParent == null) { - topMostParent = this.TopMostParent; - } - - // A) if we're parented to a native dialog - REFRESH our child states ONLY - // Then we've got to send a WM_UPDATEUISTATE to the topmost managed control (which will be non-toplevel) - // (we assume here the root native window has changed UI state, and we're not to manage the UI state for it) - // - // B) if we're totally managed - CHANGE the root window state AND REFRESH our child states. - // Then we've got to send a WM_CHANGEUISTATE to the topmost managed control (which will be toplevel) - // According to MSDN, WM_CHANGEUISTATE will generate WM_UPDATEUISTATE messages for all immediate children (via DefWndProc) - // (we're in charge here, we've got to change the state of the root window) - UnsafeNativeMethods.SendMessage( - new HandleRef(topMostParent, topMostParent.Handle), - UnsafeNativeMethods.GetParent(new HandleRef(null, topMostParent.Handle)) == IntPtr.Zero ? Interop.WindowMessages.WM_CHANGEUISTATE : Interop.WindowMessages.WM_UPDATEUISTATE, - (IntPtr)(NativeMethods.UIS_CLEAR | (toClear << 16)), - IntPtr.Zero); - } - } - + + if (keyCode == Keys.F10 || keyCode == Keys.Menu) + { + if ((current & NativeMethods.UISF_HIDEACCEL) != 0) + { + // Keyboard accelerators are hidden, they need to be shown + toClear |= NativeMethods.UISF_HIDEACCEL; + } + } + + if (keyCode == Keys.Tab) + { + if ((current & NativeMethods.UISF_HIDEFOCUS) != 0) + { + // Focus indicators are hidden, they need to be shown + toClear |= NativeMethods.UISF_HIDEFOCUS; + } + } + + if (toClear != 0) + { + // We've detected some state we need to unset, usually clearing the hidden state of + // the accelerators. We need to get the topmost parent and call CHANGEUISTATE so + // that the entire tree of controls is + if (topMostParent == null) + { + topMostParent = this.TopMostParent; + } + + // A) if we're parented to a native dialog - REFRESH our child states ONLY + // Then we've got to send a WM_UPDATEUISTATE to the topmost managed control (which will be non-toplevel) + // (we assume here the root native window has changed UI state, and we're not to manage the UI state for it) + // + // B) if we're totally managed - CHANGE the root window state AND REFRESH our child states. + // Then we've got to send a WM_CHANGEUISTATE to the topmost managed control (which will be toplevel) + // According to MSDN, WM_CHANGEUISTATE will generate WM_UPDATEUISTATE messages for all immediate children (via DefWndProc) + // (we're in charge here, we've got to change the state of the root window) + UnsafeNativeMethods.SendMessage( + new HandleRef(topMostParent, topMostParent.Handle), + UnsafeNativeMethods.GetParent(new HandleRef(null, topMostParent.Handle)) == IntPtr.Zero ? Interop.WindowMessages.WM_CHANGEUISTATE : Interop.WindowMessages.WM_UPDATEUISTATE, + (IntPtr)(NativeMethods.UIS_CLEAR | (toClear << 16)), + IntPtr.Zero); + } + } + /// /// Raises the event associated with key with the event data of /// e and a sender of this control. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected void RaiseDragEvent(object key, DragEventArgs e) { + protected void RaiseDragEvent(object key, DragEventArgs e) + { DragEventHandler handler = (DragEventHandler)Events[key]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// @@ -9622,18 +11127,23 @@ protected void RaiseDragEvent(object key, DragEventArgs e) { /// e and a sender of this control. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected void RaisePaintEvent(object key, PaintEventArgs e) { + protected void RaisePaintEvent(object key, PaintEventArgs e) + { PaintEventHandler handler = (PaintEventHandler)Events[EventPaint]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } - private void RemovePendingMessages(int msgMin, int msgMax) { - if (!this.IsDisposed) { + private void RemovePendingMessages(int msgMin, int msgMax) + { + if (!this.IsDisposed) + { NativeMethods.MSG msg = new NativeMethods.MSG(); IntPtr hwnd = this.Handle; while (UnsafeNativeMethods.PeekMessage(ref msg, new HandleRef(this, hwnd), msgMin, msgMax, - NativeMethods.PM_REMOVE)) { + NativeMethods.PM_REMOVE)) + { ; // NULL loop } } @@ -9643,16 +11153,19 @@ private void RemovePendingMessages(int msgMin, int msgMax) { /// Resets the back color to be based on the parent's back color. /// [EditorBrowsable(EditorBrowsableState.Never)] - public virtual void ResetBackColor() { + public virtual void ResetBackColor() + { BackColor = Color.Empty; } [EditorBrowsable(EditorBrowsableState.Never)] - public virtual void ResetCursor() { + public virtual void ResetCursor() + { Cursor = null; } - private void ResetEnabled() { + private void ResetEnabled() + { Enabled = true; } @@ -9660,7 +11173,8 @@ private void ResetEnabled() { /// Resets the font to be based on the parent's font. /// [EditorBrowsable(EditorBrowsableState.Never)] - public virtual void ResetFont() { + public virtual void ResetFont() + { Font = null; } @@ -9668,35 +11182,42 @@ public virtual void ResetFont() { /// Resets the fore color to be based on the parent's fore color. /// [EditorBrowsable(EditorBrowsableState.Never)] - public virtual void ResetForeColor() { + public virtual void ResetForeColor() + { ForeColor = Color.Empty; } - private void ResetLocation() { - Location = new Point(0,0); + private void ResetLocation() + { + Location = new Point(0, 0); } - private void ResetMargin() { + private void ResetMargin() + { Margin = DefaultMargin; } - private void ResetMinimumSize() { + private void ResetMinimumSize() + { MinimumSize = DefaultMinimumSize; } - private void ResetPadding() { - CommonProperties.ResetPadding(this); - } + private void ResetPadding() + { + CommonProperties.ResetPadding(this); + } - private void ResetSize() { + private void ResetSize() + { Size = DefaultSize; - } + } /// /// Resets the RightToLeft to be the default. /// [EditorBrowsable(EditorBrowsableState.Never)] - public virtual void ResetRightToLeft() { + public virtual void ResetRightToLeft() + { RightToLeft = RightToLeft.Inherit; } @@ -9705,19 +11226,24 @@ public virtual void ResetRightToLeft() { /// must call base.RecreateHandle. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected void RecreateHandle() { + protected void RecreateHandle() + { RecreateHandleCore(); } - internal virtual void RecreateHandleCore() { + internal virtual void RecreateHandleCore() + { // - lock(this) { - if (IsHandleCreated) { + lock (this) + { + if (IsHandleCreated) + { bool focused = ContainsFocus; #if DEBUG - if (CoreSwitches.PerfTrack.Enabled) { + if (CoreSwitches.PerfTrack.Enabled) + { Debug.Write("RecreateHandle: "); Debug.Write(GetType().FullName); Debug.Write(" [Text="); @@ -9727,18 +11253,21 @@ internal virtual void RecreateHandleCore() { } #endif bool created = (state & STATE_CREATED) != 0; - if (GetState(STATE_TRACKINGMOUSEEVENT)) { + if (GetState(STATE_TRACKINGMOUSEEVENT)) + { SetState(STATE_MOUSEENTERPENDING, true); UnhookMouseEvent(); } HandleRef parentHandle = new HandleRef(this, UnsafeNativeMethods.GetParent(new HandleRef(this, this.Handle))); - try { - Control [] controlSnapshot = null; + try + { + Control[] controlSnapshot = null; state |= STATE_RECREATE; - try { + try + { // Inform child controls that their parent is recreating handle. // The default behavior is to now SetParent to parking window, then @@ -9747,11 +11276,14 @@ internal virtual void RecreateHandleCore() { //fish out control collection w/o demand creating one. ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection != null && controlsCollection.Count > 0) { + if (controlsCollection != null && controlsCollection.Count > 0) + { controlSnapshot = new Control[controlsCollection.Count]; - for (int i = 0; i < controlsCollection.Count; i++) { + for (int i = 0; i < controlsCollection.Count; i++) + { Control childControl = controlsCollection[i]; - if (childControl != null && childControl.IsHandleCreated) { + if (childControl != null && childControl.IsHandleCreated) + { // SetParent to parking window childControl.OnParentHandleRecreating(); @@ -9759,7 +11291,8 @@ internal virtual void RecreateHandleCore() { // so we can raise OnParentHandleRecreated controlSnapshot[i] = childControl; } - else { + else + { // put in a null slot which we'll skip over later. controlSnapshot[i] = null; } @@ -9770,37 +11303,45 @@ internal virtual void RecreateHandleCore() { DestroyHandle(); CreateHandle(); } - finally { + finally + { state &= ~STATE_RECREATE; // inform children that their parent's handle has recreated - if (controlSnapshot != null) { - for (int i = 0; i < controlSnapshot.Length; i++) { + if (controlSnapshot != null) + { + for (int i = 0; i < controlSnapshot.Length; i++) + { Control childControl = controlSnapshot[i]; - if (childControl != null && childControl.IsHandleCreated) { + if (childControl != null && childControl.IsHandleCreated) + { // SetParent back to the new Parent handle childControl.OnParentHandleRecreated(); } } } } - if (created) { + if (created) + { CreateControl(); } } - finally { + finally + { if (parentHandle.Handle != IntPtr.Zero // the parent was not null && (Control.FromHandle(parentHandle.Handle) == null || this.parent == null) // but wasnt a windows forms window - && UnsafeNativeMethods.IsWindow(parentHandle)) { // and still is a window + && UnsafeNativeMethods.IsWindow(parentHandle)) + { // and still is a window // correctly parent back up to where we were before. // if we were parented to a proper windows forms control, CreateControl would have properly parented // us back. UnsafeNativeMethods.SetParent(new HandleRef(this, this.Handle), parentHandle); } } - + // Restore control focus - if (focused) { + if (focused) + { Focus(); } } @@ -9847,7 +11388,8 @@ protected static bool ReflectMessage(IntPtr hWnd, ref Message m) /// Forces the control to invalidate and immediately /// repaint itself and any children. /// - public virtual void Refresh() { + public virtual void Refresh() + { Invalidate(true); Update(); } @@ -9856,7 +11398,8 @@ public virtual void Refresh() { /// /Releases UI Automation provinder for specified window. /// /// The window handle. - internal virtual void ReleaseUiaProvider(IntPtr handle) { + internal virtual void ReleaseUiaProvider(IntPtr handle) + { // When a window that previously returned providers has been destroyed, // you should notify UI Automation by calling the UiaReturnRawElementProvider // as follows: UiaReturnRawElementProvider(hwnd, 0, 0, NULL). This call tells @@ -9868,8 +11411,10 @@ internal virtual void ReleaseUiaProvider(IntPtr handle) { /// Resets the mouse leave listeners. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected void ResetMouseEventArgs() { - if (GetState(STATE_TRACKINGMOUSEEVENT)) { + protected void ResetMouseEventArgs() + { + if (GetState(STATE_TRACKINGMOUSEEVENT)) + { UnhookMouseEvent(); HookMouseEvent(); } @@ -9878,11 +11423,13 @@ protected void ResetMouseEventArgs() { /// /// Resets the text to it's default value. /// - public virtual void ResetText() { + public virtual void ResetText() + { Text = string.Empty; } - private void ResetVisible() { + private void ResetVisible() + { Visible = true; } @@ -9890,7 +11437,8 @@ private void ResetVisible() { /// Resumes normal layout logic. This will force a layout immediately /// if there are any pending layout requests. /// - public void ResumeLayout() { + public void ResumeLayout() + { ResumeLayout(true); } @@ -9898,9 +11446,11 @@ public void ResumeLayout() { /// Resumes normal layout logic. If performLayout is set to true then /// this will force a layout immediately if there are any pending layout requests. /// - public void ResumeLayout(bool performLayout) { + public void ResumeLayout(bool performLayout) + { #if DEBUG - if (CompModSwitches.LayoutSuspendResume.TraceInfo) { + if (CompModSwitches.LayoutSuspendResume.TraceInfo) + { Debug.WriteLine(GetType().Name + "::ResumeLayout( preformLayout = " + performLayout + ", newCount = " + Math.Max(0, layoutSuspendCount - 1) + ")"); } #endif @@ -9908,13 +11458,17 @@ public void ResumeLayout(bool performLayout) { bool performedLayout = false; - if (layoutSuspendCount > 0) { - if (layoutSuspendCount == 1) { + if (layoutSuspendCount > 0) + { + if (layoutSuspendCount == 1) + { layoutSuspendCount++; - try { + try + { OnLayoutResuming(performLayout); } - finally { + finally + { layoutSuspendCount--; } } @@ -9922,16 +11476,18 @@ public void ResumeLayout(bool performLayout) { layoutSuspendCount--; if (layoutSuspendCount == 0 && GetState(STATE_LAYOUTDEFERRED) - && performLayout) { - PerformLayout(); - performedLayout = true; + && performLayout) + { + PerformLayout(); + performedLayout = true; } } - if (!performedLayout) { + if (!performedLayout) + { SetState2(STATE2_CLEARLAYOUTARGS, true); } - + /* We've had this since Everett,but it seems wrong, redundant and a performance hit. The @@ -9941,16 +11497,19 @@ public void ResumeLayout(bool performLayout) { but we break things at every step. */ - if (!performLayout) { - + if (!performLayout) + { + CommonProperties.xClearPreferredSizeCache(this); ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); // PERFNOTE: This is more efficient than using Foreach. Foreach // forces the creation of an array subset enum each time we // enumerate - if (controlsCollection != null) { - for (int i = 0; i < controlsCollection.Count; i++) { + if (controlsCollection != null) + { + for (int i = 0; i < controlsCollection.Count; i++) + { LayoutEngine.InitLayout(controlsCollection[i], BoundsSpecified.All); CommonProperties.xClearPreferredSizeCache(controlsCollection[i]); } @@ -9962,34 +11521,43 @@ but we break things at every step. /// /// Used to actually register the control as a drop target. /// - internal void SetAcceptDrops(bool accept) { - if (accept != GetState(STATE_DROPTARGET) && IsHandleCreated) { - try { - if (Application.OleRequired() != System.Threading.ApartmentState.STA) { + internal void SetAcceptDrops(bool accept) + { + if (accept != GetState(STATE_DROPTARGET) && IsHandleCreated) + { + try + { + if (Application.OleRequired() != System.Threading.ApartmentState.STA) + { throw new ThreadStateException(SR.ThreadMustBeSTA); } - if (accept) { + if (accept) + { Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "Registering as drop target: " + Handle.ToString()); // Register int n = UnsafeNativeMethods.RegisterDragDrop(new HandleRef(this, Handle), (UnsafeNativeMethods.IOleDropTarget)(new DropTarget(this))); Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, " ret:" + n.ToString(CultureInfo.CurrentCulture)); - if (n != 0 && n != NativeMethods.DRAGDROP_E_ALREADYREGISTERED) { + if (n != 0 && n != NativeMethods.DRAGDROP_E_ALREADYREGISTERED) + { throw new Win32Exception(n); } } - else { + else + { Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "Revoking drop target: " + Handle.ToString()); // Revoke int n = UnsafeNativeMethods.RevokeDragDrop(new HandleRef(this, Handle)); Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, " ret:" + n.ToString(CultureInfo.InvariantCulture)); - if (n != 0 && n != NativeMethods.DRAGDROP_E_NOTREGISTERED) { + if (n != 0 && n != NativeMethods.DRAGDROP_E_NOTREGISTERED) + { throw new Win32Exception(n); } } SetState(STATE_DROPTARGET, accept); } - catch (Exception e) { + catch (Exception e) + { throw new InvalidOperationException(SR.DragDropRegFailed, e); } } @@ -10000,7 +11568,8 @@ internal void SetAcceptDrops(bool accept) { /// [Obsolete("This method has been deprecated. Use the Scale(SizeF ratio) method instead. http://go.microsoft.com/fwlink/?linkid=14202")] [EditorBrowsable(EditorBrowsableState.Never)] - public void Scale(float ratio) { + public void Scale(float ratio) + { ScaleCore(ratio, ratio); } @@ -10009,15 +11578,18 @@ public void Scale(float ratio) { /// [Obsolete("This method has been deprecated. Use the Scale(SizeF ratio) method instead. http://go.microsoft.com/fwlink/?linkid=14202")] [EditorBrowsable(EditorBrowsableState.Never)] - public void Scale(float dx, float dy) { + public void Scale(float dx, float dy) + { #if DEBUG int dbgLayoutCheck = LayoutSuspendCount; #endif SuspendLayout(); - try { + try + { ScaleCore(dx, dy); } - finally { + finally + { ResumeLayout(); #if DEBUG AssertLayoutSuspendCount(dbgLayoutCheck); @@ -10029,27 +11601,32 @@ public void Scale(float dx, float dy) { /// Scales a control and its children given a scaling factor. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public void Scale(SizeF factor) { + public void Scale(SizeF factor) + { // manually call ScaleControl recursively instead of the internal scale method // when someone calls this method, they really do want to do some sort of // zooming feature, as opposed to AutoScale. - using (new LayoutTransaction(this, this, PropertyNames.Bounds, false)) { + using (new LayoutTransaction(this, this, PropertyNames.Bounds, false)) + { ScaleControl(factor, factor, this); - if (ScaleChildren) { + if (ScaleChildren) + { ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection != null) { + 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++) { + for (int i = 0; i < controlsCollection.Count; i++) + { Control c = controlsCollection[i]; c.Scale(factor); } } } - } - - LayoutTransaction.DoLayout(this, this, PropertyNames.Bounds); + } + + LayoutTransaction.DoLayout(this, this, PropertyNames.Bounds); } @@ -10069,10 +11646,12 @@ public void Scale(SizeF factor) { /// The requestingControl property indicates which control has requested /// the scaling function. /// - internal virtual void Scale(SizeF includedFactor, SizeF excludedFactor, Control requestingControl) { + internal virtual void Scale(SizeF includedFactor, SizeF excludedFactor, Control requestingControl) + { // When we scale, we are establishing new baselines for the // positions of all controls. Therefore, we should resume(false). - using (new LayoutTransaction(this, this, PropertyNames.Bounds, false)) { + using (new LayoutTransaction(this, this, PropertyNames.Bounds, false)) + { ScaleControl(includedFactor, excludedFactor, requestingControl); ScaleChildControls(includedFactor, excludedFactor, requestingControl); } @@ -10100,20 +11679,25 @@ internal virtual void Scale(SizeF includedFactor, SizeF excludedFactor, Control /// font for controls that need it, i.e. controls using default or inherited font, /// that are also not user-painted. /// - internal void ScaleChildControls(SizeF includedFactor, SizeF excludedFactor, Control requestingControl, bool updateWindowFontIfNeeded = false) { + internal void ScaleChildControls(SizeF includedFactor, SizeF excludedFactor, Control requestingControl, bool updateWindowFontIfNeeded = false) + { - if (ScaleChildren) { + if (ScaleChildren) + { ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection != null) { + 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++) { + for (int i = 0; i < controlsCollection.Count; i++) + { Control c = controlsCollection[i]; // Update window font before scaling, as controls often use font metrics during scaling. - if (updateWindowFontIfNeeded) { + if (updateWindowFontIfNeeded) + { c.UpdateWindowFontIfNeeded(); } @@ -10127,8 +11711,10 @@ internal void ScaleChildControls(SizeF includedFactor, SizeF excludedFactor, Con /// Calls SetWindowFont if DpiHelper.IsPerMonitorV2Awareness is true, /// control uses default or inherited font and is not user-painted. /// - internal void UpdateWindowFontIfNeeded() { - if (DpiHelper.IsScalingRequirementMet && !GetStyle(ControlStyles.UserPaint) && (Properties.GetObject(PropFont) == null)) { + internal void UpdateWindowFontIfNeeded() + { + if (DpiHelper.IsScalingRequirementMet && !GetStyle(ControlStyles.UserPaint) && (Properties.GetObject(PropFont) == null)) + { SetWindowFont(); } } @@ -10150,40 +11736,49 @@ internal void UpdateWindowFontIfNeeded() { /// The requestingControl property indicates which control has requested /// the scaling function. /// - internal void ScaleControl(SizeF includedFactor, SizeF excludedFactor, Control requestingControl) { - try { + internal void ScaleControl(SizeF includedFactor, SizeF excludedFactor, Control requestingControl) + { + try + { IsCurrentlyBeingScaled = true; BoundsSpecified includedSpecified = BoundsSpecified.None; BoundsSpecified excludedSpecified = BoundsSpecified.None; - if (!includedFactor.IsEmpty) { + if (!includedFactor.IsEmpty) + { includedSpecified = RequiredScaling; } - if (!excludedFactor.IsEmpty) { + if (!excludedFactor.IsEmpty) + { excludedSpecified |= (~RequiredScaling & BoundsSpecified.All); } #if DEBUG - if (CompModSwitches.RichLayout.TraceInfo) { + if (CompModSwitches.RichLayout.TraceInfo) + { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "Scaling {0} Included: {1}, Excluded: {2}", this, includedFactor, excludedFactor)); } #endif - if (includedSpecified != BoundsSpecified.None) { + if (includedSpecified != BoundsSpecified.None) + { ScaleControl(includedFactor, includedSpecified); } - if (excludedSpecified != BoundsSpecified.None) { + if (excludedSpecified != BoundsSpecified.None) + { ScaleControl(excludedFactor, excludedSpecified); } - if (!includedFactor.IsEmpty) { + if (!includedFactor.IsEmpty) + { RequiredScaling = BoundsSpecified.None; } } - finally { + finally + { IsCurrentlyBeingScaled = false; } } @@ -10198,18 +11793,19 @@ internal void ScaleControl(SizeF includedFactor, SizeF excludedFactor, Control r /// BoundsSpecified.None. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void ScaleControl(SizeF factor, BoundsSpecified specified) { + protected virtual void ScaleControl(SizeF factor, BoundsSpecified specified) + { CreateParams cp = CreateParams; NativeMethods.RECT adornments = new NativeMethods.RECT(0, 0, 0, 0); AdjustWindowRectEx(ref adornments, cp.Style, HasMenu, cp.ExStyle); Size minSize = MinimumSize; Size maxSize = MaximumSize; - + // clear out min and max size, otherwise this could affect the scaling logic. MinimumSize = Size.Empty; MaximumSize = Size.Empty; - + // this is raw because Min/Max size have been cleared at this point. Rectangle rawScaledBounds = GetScaledBounds(Bounds, factor, specified); @@ -10223,17 +11819,21 @@ protected virtual void ScaleControl(SizeF factor, BoundsSpecified specified) { Padding margins = Margin; // Clear off specified bits for 1.0 scaling factors - if (dx == 1.0F) specified &= ~(BoundsSpecified.X | BoundsSpecified.Width); - if (dy == 1.0F) specified &= ~(BoundsSpecified.Y | BoundsSpecified.Height); + if (dx == 1.0F) + specified &= ~(BoundsSpecified.X | BoundsSpecified.Width); + if (dy == 1.0F) + specified &= ~(BoundsSpecified.Y | BoundsSpecified.Height); - if (dx != 1.0F) { + if (dx != 1.0F) + { padding.Left = (int)Math.Round(padding.Left * dx); padding.Right = (int)Math.Round(padding.Right * dx); margins.Left = (int)Math.Round(margins.Left * dx); margins.Right = (int)Math.Round(margins.Right * dx); } - if (dy != 1.0F) { + if (dy != 1.0F) + { padding.Top = (int)Math.Round(padding.Top * dy); padding.Bottom = (int)Math.Round(padding.Bottom * dy); margins.Top = (int)Math.Round(margins.Top * dy); @@ -10247,39 +11847,42 @@ protected virtual void ScaleControl(SizeF factor, BoundsSpecified specified) { // // Scale Min/Max size // - + // make sure we consider the andornments as fixed. rather than scaling the entire size, // we should pull out the fixed things such as the border, scale the rest, then apply the fixed // adornment size. Size adornmentSize = adornments.Size; - if (!minSize.IsEmpty) { - minSize -= adornmentSize; + if (!minSize.IsEmpty) + { + minSize -= adornmentSize; minSize = ScaleSize(LayoutUtils.UnionSizes(Size.Empty, minSize), // make sure we dont go below 0. - factor.Width, + factor.Width, factor.Height) + adornmentSize; } - if (!maxSize.IsEmpty) { + if (!maxSize.IsEmpty) + { maxSize -= adornmentSize; maxSize = ScaleSize(LayoutUtils.UnionSizes(Size.Empty, maxSize), // make sure we dont go below 0. - factor.Width, + factor.Width, factor.Height) + adornmentSize; } - + // Apply the min/max size constraints - dont call ApplySizeConstraints // as MinimumSize/MaximumSize are currently cleared out. Size maximumSize = LayoutUtils.ConvertZeroToUnbounded(maxSize); Size scaledSize = LayoutUtils.IntersectSizes(rawScaledBounds.Size, maximumSize); scaledSize = LayoutUtils.UnionSizes(scaledSize, minSize); - if (DpiHelper.IsScalingRequirementMet && (ParentInternal != null) && (ParentInternal.LayoutEngine == DefaultLayout.Instance)) { + if (DpiHelper.IsScalingRequirementMet && (ParentInternal != null) && (ParentInternal.LayoutEngine == DefaultLayout.Instance)) + { // We need to scale AnchorInfo to update distances to container edges DefaultLayout.ScaleAnchorInfo((IArrangedElement)this, factor); } // Set in the scaled bounds as constrained by the newly scaled min/max size. SetBoundsCore(rawScaledBounds.X, rawScaledBounds.Y, scaledSize.Width, scaledSize.Height, BoundsSpecified.All); - + MaximumSize = maxSize; MinimumSize = minSize; } @@ -10288,22 +11891,26 @@ protected virtual void ScaleControl(SizeF factor, BoundsSpecified specified) { /// Performs the work of scaling the entire control and any child controls. /// [EditorBrowsable(EditorBrowsableState.Never)] - protected virtual void ScaleCore(float dx, float dy) { + protected virtual void ScaleCore(float dx, float dy) + { Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, GetType().Name + "::ScaleCore(" + dx + ", " + dy + ")"); #if DEBUG int dbgLayoutCheck = LayoutSuspendCount; #endif SuspendLayout(); - try { + try + { int sx = (int)Math.Round(x * dx); int sy = (int)Math.Round(y * dy); int sw = width; - if ((controlStyle & ControlStyles.FixedWidth) != ControlStyles.FixedWidth) { + if ((controlStyle & ControlStyles.FixedWidth) != ControlStyles.FixedWidth) + { sw = (int)(Math.Round((x + width) * dx)) - sx; } int sh = height; - if ((controlStyle & ControlStyles.FixedHeight) != ControlStyles.FixedHeight) { + if ((controlStyle & ControlStyles.FixedHeight) != ControlStyles.FixedHeight) + { sh = (int)(Math.Round((y + height) * dy)) - sy; } @@ -10311,34 +11918,40 @@ protected virtual void ScaleCore(float dx, float dy) { ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection != null) { + 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++) { + for (int i = 0; i < controlsCollection.Count; i++) + { #pragma warning disable 618 controlsCollection[i].Scale(dx, dy); #pragma warning restore 618 } } } - finally { + finally + { ResumeLayout(); #if DEBUG AssertLayoutSuspendCount(dbgLayoutCheck); #endif } - } + } /// /// Scales a given size with the provided values. /// - internal Size ScaleSize(Size startSize, float x, float y) { + internal Size ScaleSize(Size startSize, float x, float y) + { Size size = startSize; - if (!GetStyle(ControlStyles.FixedWidth)) { + if (!GetStyle(ControlStyles.FixedWidth)) + { size.Width = (int)Math.Round((float)size.Width * x); } - if (!GetStyle(ControlStyles.FixedHeight)) { + if (!GetStyle(ControlStyles.FixedHeight)) + { size.Height = (int)Math.Round((float)size.Height * y); } return size; @@ -10347,15 +11960,18 @@ internal Size ScaleSize(Size startSize, float x, float y) { /// /// Activates this control. /// - public void Select() { + public void Select() + { Select(false, false); } // used by Form - protected virtual void Select(bool directed, bool forward) { + protected virtual void Select(bool directed, bool forward) + { IContainerControl c = GetContainerControl(); - if (c != null) { + if (c != null) + { c.ActiveControl = this; } } @@ -10363,37 +11979,49 @@ protected virtual void Select(bool directed, bool forward) { /// /// Selects the next control following ctl. /// - public bool SelectNextControl(Control ctl, bool forward, bool tabStopOnly, bool nested, bool wrap) { + public bool SelectNextControl(Control ctl, bool forward, bool tabStopOnly, bool nested, bool wrap) + { Control nextSelectableControl = this.GetNextSelectableControl(ctl, forward, tabStopOnly, nested, wrap); - if (nextSelectableControl != null) { + if (nextSelectableControl != null) + { nextSelectableControl.Select(true, forward); return true; } - else { + else + { return false; } } - private Control GetNextSelectableControl(Control ctl, bool forward, bool tabStopOnly, bool nested, bool wrap) { - if (!Contains(ctl) || !nested && ctl.parent != this) ctl = null; + private Control GetNextSelectableControl(Control ctl, bool forward, bool tabStopOnly, bool nested, bool wrap) + { + if (!Contains(ctl) || !nested && ctl.parent != this) + ctl = null; bool alreadyWrapped = false; Control start = ctl; - do { + do + { ctl = GetNextControl(ctl, forward); - if (ctl == null) { - if (!wrap) break; - if (alreadyWrapped) { + if (ctl == null) + { + if (!wrap) + break; + if (alreadyWrapped) + { return null; //prevent infinite wrapping. } alreadyWrapped = true; } - else { + else + { if (ctl.CanSelect && (!tabStopOnly || ctl.TabStop) - && (nested || ctl.parent == this)) { + && (nested || ctl.parent == this)) + { - if (ctl.parent is ToolStrip) { + if (ctl.parent is ToolStrip) + { continue; } return ctl; @@ -10407,14 +12035,17 @@ private Control GetNextSelectableControl(Control ctl, bool forward, bool tabStop /// This is called recursively when visibility is changed for a control, this /// forces focus to be moved to a visible control. /// - private void SelectNextIfFocused() { + private void SelectNextIfFocused() + { // We want to move focus away from hidden controls, so this // function was added. // - if (ContainsFocus && ParentInternal != null) { + if (ContainsFocus && ParentInternal != null) + { IContainerControl c = ParentInternal.GetContainerControl(); - if (c != null) { + if (c != null) + { ((Control)c).SelectNextControl(this, true, true, true, true); } } @@ -10424,7 +12055,8 @@ private void SelectNextIfFocused() { /// Sends a Win32 message to this control. If the control does not yet /// have a handle, it will be created. /// - internal IntPtr SendMessage(int msg, int wparam, int lparam) { + internal IntPtr SendMessage(int msg, int wparam, int lparam) + { return UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), msg, wparam, lparam); } @@ -10432,22 +12064,26 @@ internal IntPtr SendMessage(int msg, int wparam, int lparam) { /// Sends a Win32 message to this control. If the control does not yet /// have a handle, it will be created. /// - internal IntPtr SendMessage(int msg, ref int wparam, ref int lparam) { + internal IntPtr SendMessage(int msg, ref int wparam, ref int lparam) + { Debug.Assert(IsHandleCreated, "Performance alert! Calling Control::SendMessage and forcing handle creation. Re-work control so handle creation is not required to set properties. If there is no work around, wrap the call in an IsHandleCreated check."); return UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), msg, ref wparam, ref lparam); } - - internal IntPtr SendMessage(int msg, int wparam, IntPtr lparam) { + + internal IntPtr SendMessage(int msg, int wparam, IntPtr lparam) + { Debug.Assert(IsHandleCreated, "Performance alert! Calling Control::SendMessage and forcing handle creation. Re-work control so handle creation is not required to set properties. If there is no work around, wrap the call in an IsHandleCreated check."); return UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), msg, (IntPtr)wparam, lparam); } - internal IntPtr SendMessage(int msg, IntPtr wparam, IntPtr lparam) { + internal IntPtr SendMessage(int msg, IntPtr wparam, IntPtr lparam) + { Debug.Assert(IsHandleCreated, "Performance alert! Calling Control::SendMessage and forcing handle creation. Re-work control so handle creation is not required to set properties. If there is no work around, wrap the call in an IsHandleCreated check."); return UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), msg, wparam, lparam); } - internal IntPtr SendMessage(int msg, IntPtr wparam, int lparam) { + internal IntPtr SendMessage(int msg, IntPtr wparam, int lparam) + { Debug.Assert(IsHandleCreated, "Performance alert! Calling Control::SendMessage and forcing handle creation. Re-work control so handle creation is not required to set properties. If there is no work around, wrap the call in an IsHandleCreated check."); return UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), msg, wparam, (IntPtr)lparam); } @@ -10456,7 +12092,8 @@ internal IntPtr SendMessage(int msg, IntPtr wparam, int lparam) { /// Sends a Win32 message to this control. If the control does not yet /// have a handle, it will be created. /// - internal IntPtr SendMessage(int msg, int wparam, ref NativeMethods.RECT lparam) { + internal IntPtr SendMessage(int msg, int wparam, ref NativeMethods.RECT lparam) + { return UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), msg, wparam, ref lparam); } @@ -10464,7 +12101,8 @@ internal IntPtr SendMessage(int msg, int wparam, ref NativeMethods.RECT lparam) /// Sends a Win32 message to this control. If the control does not yet /// have a handle, it will be created. /// - internal IntPtr SendMessage(int msg, bool wparam, int lparam) { + internal IntPtr SendMessage(int msg, bool wparam, int lparam) + { Debug.Assert(IsHandleCreated, "Performance alert! Calling Control::SendMessage and forcing handle creation. Re-work control so handle creation is not required to set properties. If there is no work around, wrap the call in an IsHandleCreated check."); return UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), msg, wparam, lparam); } @@ -10473,19 +12111,23 @@ internal IntPtr SendMessage(int msg, bool wparam, int lparam) { /// Sends a Win32 message to this control. If the control does not yet /// have a handle, it will be created. /// - internal IntPtr SendMessage(int msg, int wparam, string lparam) { + internal IntPtr SendMessage(int msg, int wparam, string lparam) + { Debug.Assert(IsHandleCreated, "Performance alert! Calling Control::SendMessage and forcing handle creation. Re-work control so handle creation is not required to set properties. If there is no work around, wrap the call in an IsHandleCreated check."); return UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), msg, wparam, lparam); } - + /// /// sends this control to the back of the z-order /// - public void SendToBack() { - if (parent != null) { + public void SendToBack() + { + if (parent != null) + { parent.Controls.SetChildIndex(this, -1); } - else if (IsHandleCreated && GetTopLevel()) { + else if (IsHandleCreated && GetTopLevel()) + { SafeNativeMethods.SetWindowPos(new HandleRef(window, Handle), NativeMethods.HWND_BOTTOM, 0, 0, 0, 0, NativeMethods.SWP_NOMOVE | NativeMethods.SWP_NOSIZE); } @@ -10494,16 +12136,19 @@ public void SendToBack() { /// /// Sets the bounds of the control. /// - public void SetBounds(int x, int y, int width, int height) { + public void SetBounds(int x, int y, int width, int height) + { if (this.x != x || this.y != y || this.width != width || - this.height != height) { + this.height != height) + { SetBoundsCore(x, y, width, height, BoundsSpecified.All); // WM_WINDOWPOSCHANGED will trickle down to an OnResize() which will // have refreshed the interior layout. We only need to layout the parent. LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.Bounds); } - else { + else + { // Still need to init scaling. InitScaling(BoundsSpecified.All); } @@ -10512,13 +12157,19 @@ public void SetBounds(int x, int y, int width, int height) { /// /// Sets the bounds of the control. /// - public void SetBounds(int x, int y, int width, int height, BoundsSpecified specified) { - if ((specified & BoundsSpecified.X) == BoundsSpecified.None) x = this.x; - if ((specified & BoundsSpecified.Y) == BoundsSpecified.None) y = this.y; - if ((specified & BoundsSpecified.Width) == BoundsSpecified.None) width = this.width; - if ((specified & BoundsSpecified.Height) == BoundsSpecified.None) height = this.height; + public void SetBounds(int x, int y, int width, int height, BoundsSpecified specified) + { + if ((specified & BoundsSpecified.X) == BoundsSpecified.None) + x = this.x; + if ((specified & BoundsSpecified.Y) == BoundsSpecified.None) + y = this.y; + if ((specified & BoundsSpecified.Width) == BoundsSpecified.None) + width = this.width; + if ((specified & BoundsSpecified.Height) == BoundsSpecified.None) + height = this.height; if (this.x != x || this.y != y || this.width != width || - this.height != height) { + this.height != height) + { SetBoundsCore(x, y, width, height, specified); // WM_WINDOWPOSCHANGED will trickle down to an OnResize() which will @@ -10526,7 +12177,8 @@ public void SetBounds(int x, int y, int width, int height, BoundsSpecified speci // the parent. This happens after InitLayout has been invoked. LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.Bounds); } - else { + else + { // Still need to init scaling. InitScaling(specified); } @@ -10539,9 +12191,11 @@ public void SetBounds(int x, int y, int width, int height, BoundsSpecified speci /// of the control to change. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { + protected virtual void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) + { #if DEBUG - if (CompModSwitches.SetBounds.TraceInfo) { + if (CompModSwitches.SetBounds.TraceInfo) + { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0}::SetBoundsCore(x={1} y={2} width={3} height={4} specified={5}", Name, x, y, width, height, specified)); } #endif @@ -10552,34 +12206,43 @@ protected virtual void SetBoundsCore(int x, int y, int width, int height, Bounds #if DEBUG int suspendCount = -44371; // Arbitrary negative prime to surface bugs. #endif - if (ParentInternal != null) { + if (ParentInternal != null) + { #if DEBUG suspendCount = ParentInternal.LayoutSuspendCount; #endif ParentInternal.SuspendLayout(); } - try { - if (this.x != x || this.y != y || this.width != width || this.height != height) { + try + { + if (this.x != x || this.y != y || this.width != width || this.height != height) + { CommonProperties.UpdateSpecifiedBounds(this, x, y, width, height, specified); // Provide control with an opportunity to apply self imposed constraints on its size. - Rectangle adjustedBounds = ApplyBoundsConstraints(x,y, width, height); + Rectangle adjustedBounds = ApplyBoundsConstraints(x, y, width, height); width = adjustedBounds.Width; height = adjustedBounds.Height; x = adjustedBounds.X; y = adjustedBounds.Y; - if (!IsHandleCreated) { + if (!IsHandleCreated) + { // Handle is not created, just record our new position and we're done. UpdateBounds(x, y, width, height); - } else { - if (!GetState(STATE_SIZELOCKEDBYOS)) { + } + else + { + if (!GetState(STATE_SIZELOCKEDBYOS)) + { int flags = NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE; - if (this.x == x && this.y == y) { + if (this.x == x && this.y == y) + { flags |= NativeMethods.SWP_NOMOVE; } - if (this.width == width && this.height == height) { + if (this.width == width && this.height == height) + { flags |= NativeMethods.SWP_NOSIZE; } @@ -10598,12 +12261,14 @@ protected virtual void SetBoundsCore(int x, int y, int width, int height, Bounds } } } - finally { + finally + { // Initialize the scaling engine. InitScaling(specified); - if (ParentInternal != null) { + if (ParentInternal != null) + { // Some layout engines (DefaultLayout) base their PreferredSize on // the bounds of their children. If we change change the child bounds, we // need to clear their PreferredSize cache. The semantics of SetBoundsCore @@ -10615,7 +12280,7 @@ protected virtual void SetBoundsCore(int x, int y, int width, int height, Bounds // LayoutEngine which manages your layout, so we call into the parent's // LayoutEngine. ParentInternal.LayoutEngine.InitLayout(this, specified); - ParentInternal.ResumeLayout( /* performLayout = */ true ); + ParentInternal.ResumeLayout( /* performLayout = */ true); #if DEBUG Debug.Assert(ParentInternal.LayoutSuspendCount == suspendCount, "Suspend/Resume layout mismatch!"); #endif @@ -10627,7 +12292,8 @@ protected virtual void SetBoundsCore(int x, int y, int width, int height, Bounds /// Performs the work of setting the size of the client area of the control. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void SetClientSizeCore(int x, int y) { + protected virtual void SetClientSizeCore(int x, int y) + { Size = SizeFromClientSize(x, y); clientWidth = x; clientHeight = y; @@ -10635,42 +12301,52 @@ protected virtual void SetClientSizeCore(int x, int y) { } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual Size SizeFromClientSize(Size clientSize) { + protected virtual Size SizeFromClientSize(Size clientSize) + { return SizeFromClientSize(clientSize.Width, clientSize.Height); } - internal Size SizeFromClientSize(int width, int height) { + internal Size SizeFromClientSize(int width, int height) + { NativeMethods.RECT rect = new NativeMethods.RECT(0, 0, width, height); CreateParams cp = CreateParams; AdjustWindowRectEx(ref rect, cp.Style, HasMenu, cp.ExStyle); return rect.Size; } - private void SetHandle(IntPtr value) { - if (value == IntPtr.Zero) { + private void SetHandle(IntPtr value) + { + if (value == IntPtr.Zero) + { SetState(STATE_CREATED, false); } UpdateRoot(); } - private void SetParentHandle(IntPtr value) { + private void SetParentHandle(IntPtr value) + { Debug.Assert(value != NativeMethods.InvalidIntPtr, "Outdated call to SetParentHandle"); - if (IsHandleCreated) { + if (IsHandleCreated) + { IntPtr parentHandle = UnsafeNativeMethods.GetParent(new HandleRef(window, Handle)); bool topLevel = GetTopLevel(); - if (parentHandle != value || (parentHandle == IntPtr.Zero && !topLevel)) { + if (parentHandle != value || (parentHandle == IntPtr.Zero && !topLevel)) + { Debug.Assert(Handle != value, "Cycle created in SetParentHandle"); - + bool recreate = (parentHandle == IntPtr.Zero && !topLevel) || (value == IntPtr.Zero && topLevel); - if (recreate) { + if (recreate) + { // We will recreate later, when the MdiChild's visibility // is set to true (see Form f = this as Form; - if (f != null) { - if (!f.CanRecreateHandle()) { + if (f != null) + { + if (!f.CanRecreateHandle()) + { recreate = false; // we don't want to recreate - but our styles may have changed. // before we unpark the window below we need to update @@ -10679,24 +12355,30 @@ private void SetParentHandle(IntPtr value) { } } - if (recreate) { + if (recreate) + { RecreateHandle(); } - if (!GetTopLevel()) { - if (value == IntPtr.Zero) { + if (!GetTopLevel()) + { + if (value == IntPtr.Zero) + { Application.ParkHandle(new HandleRef(window, Handle)); UpdateRoot(); } - else { + else + { UnsafeNativeMethods.SetParent(new HandleRef(window, Handle), new HandleRef(null, value)); - if (parent != null) { + if (parent != null) + { parent.UpdateChildZOrder(this); } Application.UnparkHandle(new HandleRef(window, Handle), window.DpiAwarenessContext); } } } - else if (value == IntPtr.Zero && parentHandle == IntPtr.Zero && topLevel) { + else if (value == IntPtr.Zero && parentHandle == IntPtr.Zero && topLevel) + { // The handle was previously parented to the parking window. Its TopLevel property was // then changed to true so the above call to GetParent returns null even though the parent of the control is // not null. We need to explicitly set the parent to null. @@ -10707,12 +12389,14 @@ private void SetParentHandle(IntPtr value) { } // Form, UserControl, AxHost usage - internal void SetState(int flag, bool value) { - state = value? state | flag: state & ~flag; + internal void SetState(int flag, bool value) + { + state = value ? state | flag : state & ~flag; } // Application, SKWindow usage - internal void SetState2(int flag, bool value) { + internal void SetState2(int flag, bool value) + { state2 = value ? state2 | flag : state2 & ~flag; } @@ -10721,13 +12405,15 @@ internal void SetState2(int flag, bool value) { /// NOTE: This is control style, not the Win32 style of the hWnd. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected void SetStyle(ControlStyles flag, bool value) { + protected void SetStyle(ControlStyles flag, bool value) + { // WARNING: if we ever add argument checking to "flag", we will need // to move private styles like Layered to State. - controlStyle = value? controlStyle | flag: controlStyle & ~flag; + controlStyle = value ? controlStyle | flag : controlStyle & ~flag; } - internal static IntPtr SetUpPalette(IntPtr dc, bool force, bool realizePalette) { + internal static IntPtr SetUpPalette(IntPtr dc, bool force, bool realizePalette) + { Debug.WriteLineIf(Control.PaletteTracing.TraceVerbose, "SetUpPalette(force:=" + force + ", ralizePalette:=" + realizePalette + ")"); IntPtr halftonePalette = Graphics.GetHalftonePalette(); @@ -10735,64 +12421,79 @@ internal static IntPtr SetUpPalette(IntPtr dc, bool force, bool realizePalette) Debug.WriteLineIf(Control.PaletteTracing.TraceVerbose, "select palette " + !force); IntPtr result = SafeNativeMethods.SelectPalette(new HandleRef(null, dc), new HandleRef(null, halftonePalette), (force ? 0 : 1)); - if (result != IntPtr.Zero && realizePalette) { + if (result != IntPtr.Zero && realizePalette) + { SafeNativeMethods.RealizePalette(new HandleRef(null, dc)); } return result; } - protected void SetTopLevel(bool value) { - if (value && IsActiveX) { + protected void SetTopLevel(bool value) + { + if (value && IsActiveX) + { throw new InvalidOperationException(SR.TopLevelNotAllowedIfActiveX); } - else { + else + { SetTopLevelInternal(value); } } private protected void SetTopLevelInternal(bool value) { - if (GetTopLevel() != value) { - if (parent != null) { + if (GetTopLevel() != value) + { + if (parent != null) + { throw new ArgumentException(SR.TopLevelParentedControl, "value"); } SetState(STATE_TOPLEVEL, value); // make sure the handle is created before hooking, otherwise a toplevel control that never // creates its handle will leak. - if (IsHandleCreated && GetState2(STATE2_INTERESTEDINUSERPREFERENCECHANGED)) { + if (IsHandleCreated && GetState2(STATE2_INTERESTEDINUSERPREFERENCECHANGED)) + { ListenToUserPreferenceChanged(value); } UpdateStyles(); SetParentHandle(IntPtr.Zero); - if (value && Visible) { + if (value && Visible) + { CreateControl(); } UpdateRoot(); } } - protected virtual void SetVisibleCore(bool value) { - try { + protected virtual void SetVisibleCore(bool value) + { + try + { Interop.HandleCollector.SuspendCollect(); - if (GetVisibleCore() != value) { - if (!value) { + if (GetVisibleCore() != value) + { + if (!value) + { SelectNextIfFocused(); } bool fireChange = false; - if (GetTopLevel()) { + if (GetTopLevel()) + { // The processing of WmShowWindow will set the visibility // bit and call CreateControl() // - if (IsHandleCreated || value) { - SafeNativeMethods.ShowWindow(new HandleRef(this, Handle), value ? ShowParams : NativeMethods.SW_HIDE); + if (IsHandleCreated || value) + { + SafeNativeMethods.ShowWindow(new HandleRef(this, Handle), value ? ShowParams : NativeMethods.SW_HIDE); } } - else if (IsHandleCreated || value && parent != null && parent.Created) { + else if (IsHandleCreated || value && parent != null && parent.Created) + { // We want to mark the control as visible so that CreateControl // knows that we are going to be displayed... however in case @@ -10800,8 +12501,10 @@ protected virtual void SetVisibleCore(bool value) { // SetState(STATE_VISIBLE, value); fireChange = true; - try { - if (value) CreateControl(); + try + { + if (value) + CreateControl(); SafeNativeMethods.SetWindowPos(new HandleRef(window, Handle), NativeMethods.NullHandleRef, 0, 0, 0, 0, @@ -10811,17 +12514,20 @@ protected virtual void SetVisibleCore(bool value) { | NativeMethods.SWP_NOACTIVATE | (value ? NativeMethods.SWP_SHOWWINDOW : NativeMethods.SWP_HIDEWINDOW)); } - catch { + catch + { SetState(STATE_VISIBLE, !value); throw; } } - if (GetVisibleCore() != value) { + if (GetVisibleCore() != value) + { SetState(STATE_VISIBLE, value); fireChange = true; } - if (fireChange) { + if (fireChange) + { // We do not do this in the OnPropertyChanged event for visible // Lots of things could cause us to become visible, including a // parent window. We do not want to indescriminiately layout @@ -10829,32 +12535,37 @@ protected virtual void SetVisibleCore(bool value) { // our visibility. // - using (new LayoutTransaction(parent, this, PropertyNames.Visible)) { + using (new LayoutTransaction(parent, this, PropertyNames.Visible)) + { OnVisibleChanged(EventArgs.Empty); } } UpdateRoot(); } - else { // value of Visible property not changed, but raw bit may have + else + { // value of Visible property not changed, but raw bit may have - if (!GetState(STATE_VISIBLE) && !value && IsHandleCreated) { + if (!GetState(STATE_VISIBLE) && !value && IsHandleCreated) + { // PERF - setting Visible=false twice can get us into this else block // which makes us process WM_WINDOWPOS* messages - make sure we've already // visible=false - if not, make it so. - if (!SafeNativeMethods.IsWindowVisible(new HandleRef(this,this.Handle))) { + if (!SafeNativeMethods.IsWindowVisible(new HandleRef(this, this.Handle))) + { // we're already invisible - bail. return; - } + } } - + SetState(STATE_VISIBLE, value); // If the handle is already created, we need to update the window style. // This situation occurs when the parent control is not currently visible, // but the child control has already been created. // - if (IsHandleCreated) { - + if (IsHandleCreated) + { + SafeNativeMethods.SetWindowPos( new HandleRef(window, Handle), NativeMethods.NullHandleRef, 0, 0, 0, 0, NativeMethods.SWP_NOSIZE | NativeMethods.SWP_NOMOVE | NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE | @@ -10862,7 +12573,8 @@ protected virtual void SetVisibleCore(bool value) { } } } - finally { + finally + { Interop.HandleCollector.ResumeCollect(); } } @@ -10872,7 +12584,8 @@ protected virtual void SetVisibleCore(bool value) { /// of its containing control. Defaults to 'EnablePreventFocusChange' if there is no containing control /// (eg. because this control is a top-level container). /// - internal static AutoValidate GetAutoValidateForControl(Control control) { + internal static AutoValidate GetAutoValidateForControl(Control control) + { ContainerControl parent = control.ParentContainerControl; return (parent != null) ? parent.AutoValidate : AutoValidate.EnablePreventFocusChange; } @@ -10882,15 +12595,18 @@ internal static AutoValidate GetAutoValidateForControl(Control control) { /// Depends on the AutoValidate property of the containing control. /// [EditorBrowsable(EditorBrowsableState.Never)] - internal bool ShouldAutoValidate { - get { + internal bool ShouldAutoValidate + { + get + { return GetAutoValidateForControl(this) != AutoValidate.Disable; } } // This method is called in PerformContainerValidation to check if this control supports containerValidation. // TabControl overrides this method to return true. - internal virtual bool ShouldPerformContainerValidation() { + internal virtual bool ShouldPerformContainerValidation() + { return GetStyle(ControlStyles.ContainerControl); } @@ -10898,7 +12614,8 @@ internal virtual bool ShouldPerformContainerValidation() { /// Returns true if the backColor should be persisted in code gen. /// [EditorBrowsable(EditorBrowsableState.Never)] - internal virtual bool ShouldSerializeBackColor() { + internal virtual bool ShouldSerializeBackColor() + { Color backColor = Properties.GetColor(PropBackColor); return !backColor.IsEmpty; } @@ -10907,7 +12624,8 @@ internal virtual bool ShouldSerializeBackColor() { /// Returns true if the cursor should be persisted in code gen. /// [EditorBrowsable(EditorBrowsableState.Never)] - internal virtual bool ShouldSerializeCursor() { + internal virtual bool ShouldSerializeCursor() + { bool found; object cursor = Properties.GetObject(PropCursor, out found); return (found && cursor != null); @@ -10917,7 +12635,8 @@ internal virtual bool ShouldSerializeCursor() { /// Returns true if the enabled property should be persisted in code gen. /// [EditorBrowsable(EditorBrowsableState.Never)] - private bool ShouldSerializeEnabled() { + private bool ShouldSerializeEnabled() + { return (!GetState(STATE_ENABLED)); } @@ -10925,7 +12644,8 @@ private bool ShouldSerializeEnabled() { /// Returns true if the foreColor should be persisted in code gen. /// [EditorBrowsable(EditorBrowsableState.Never)] - internal virtual bool ShouldSerializeForeColor() { + internal virtual bool ShouldSerializeForeColor() + { Color foreColor = Properties.GetColor(PropForeColor); return !foreColor.IsEmpty; } @@ -10934,7 +12654,8 @@ internal virtual bool ShouldSerializeForeColor() { /// Returns true if the font should be persisted in code gen. /// [EditorBrowsable(EditorBrowsableState.Never)] - internal virtual bool ShouldSerializeFont() { + internal virtual bool ShouldSerializeFont() + { bool found; object font = Properties.GetObject(PropFont, out found); return (found && font != null); @@ -10944,7 +12665,8 @@ internal virtual bool ShouldSerializeFont() { /// Returns true if the RightToLeft should be persisted in code gen. /// [EditorBrowsable(EditorBrowsableState.Never)] - internal virtual bool ShouldSerializeRightToLeft() { + internal virtual bool ShouldSerializeRightToLeft() + { bool found; int rtl = Properties.GetInteger(PropRightToLeft, out found); return (found && rtl != (int)RightToLeft.Inherit); @@ -10954,35 +12676,43 @@ internal virtual bool ShouldSerializeRightToLeft() { /// Returns true if the visible property should be persisted in code gen. /// [EditorBrowsable(EditorBrowsableState.Never)] - private bool ShouldSerializeVisible() { + private bool ShouldSerializeVisible() + { return (!GetState(STATE_VISIBLE)); } // Helper function - translates text alignment for Rtl controls // Read TextAlign as Left == Near, Right == Far [EditorBrowsable(EditorBrowsableState.Advanced)] - protected HorizontalAlignment RtlTranslateAlignment(HorizontalAlignment align) { + protected HorizontalAlignment RtlTranslateAlignment(HorizontalAlignment align) + { return RtlTranslateHorizontal(align); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected LeftRightAlignment RtlTranslateAlignment(LeftRightAlignment align) { + protected LeftRightAlignment RtlTranslateAlignment(LeftRightAlignment align) + { return RtlTranslateLeftRight(align); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected ContentAlignment RtlTranslateAlignment(ContentAlignment align) { + protected ContentAlignment RtlTranslateAlignment(ContentAlignment align) + { return RtlTranslateContent(align); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected HorizontalAlignment RtlTranslateHorizontal(HorizontalAlignment align) { + protected HorizontalAlignment RtlTranslateHorizontal(HorizontalAlignment align) + { - if (RightToLeft.Yes == RightToLeft) { - if (HorizontalAlignment.Left == align) { + if (RightToLeft.Yes == RightToLeft) + { + if (HorizontalAlignment.Left == align) + { return HorizontalAlignment.Right; } - else if (HorizontalAlignment.Right == align) { + else if (HorizontalAlignment.Right == align) + { return HorizontalAlignment.Left; } } @@ -10991,13 +12721,17 @@ protected HorizontalAlignment RtlTranslateHorizontal(HorizontalAlignment align) } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected LeftRightAlignment RtlTranslateLeftRight(LeftRightAlignment align) { + protected LeftRightAlignment RtlTranslateLeftRight(LeftRightAlignment align) + { - if (RightToLeft.Yes == RightToLeft) { - if (LeftRightAlignment.Left == align) { + if (RightToLeft.Yes == RightToLeft) + { + if (LeftRightAlignment.Left == align) + { return LeftRightAlignment.Right; } - else if (LeftRightAlignment.Right == align) { + else if (LeftRightAlignment.Right == align) + { return LeftRightAlignment.Left; } } @@ -11006,71 +12740,86 @@ protected LeftRightAlignment RtlTranslateLeftRight(LeftRightAlignment align) { } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected internal ContentAlignment RtlTranslateContent(ContentAlignment align) { - if (RightToLeft.Yes == RightToLeft) { + protected internal ContentAlignment RtlTranslateContent(ContentAlignment align) + { + if (RightToLeft.Yes == RightToLeft) + { - if ((align & WindowsFormsUtils.AnyTopAlign) != 0) { - switch (align) { + if ((align & WindowsFormsUtils.AnyTopAlign) != 0) + { + switch (align) + { case ContentAlignment.TopLeft: return ContentAlignment.TopRight; case ContentAlignment.TopRight: - return ContentAlignment.TopLeft; + return ContentAlignment.TopLeft; } } - if ((align & WindowsFormsUtils.AnyMiddleAlign) != 0 ) { - switch (align) { + if ((align & WindowsFormsUtils.AnyMiddleAlign) != 0) + { + switch (align) + { case ContentAlignment.MiddleLeft: return ContentAlignment.MiddleRight; case ContentAlignment.MiddleRight: - return ContentAlignment.MiddleLeft; + return ContentAlignment.MiddleLeft; } } - if ((align & WindowsFormsUtils.AnyBottomAlign) != 0 ) { - switch (align) { + if ((align & WindowsFormsUtils.AnyBottomAlign) != 0) + { + switch (align) + { case ContentAlignment.BottomLeft: return ContentAlignment.BottomRight; case ContentAlignment.BottomRight: - return ContentAlignment.BottomLeft; + return ContentAlignment.BottomLeft; } - } + } } return align; } - private void SetWindowFont(){ + private void SetWindowFont() + { SendMessage(Interop.WindowMessages.WM_SETFONT, FontHandle, 0 /*redraw = false*/); } - private void SetWindowStyle(int flag, bool value) { + private void SetWindowStyle(int flag, bool value) + { int styleFlags = unchecked((int)((long)UnsafeNativeMethods.GetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_STYLE))); - UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_STYLE, new HandleRef(null, (IntPtr)(value? styleFlags | flag: styleFlags & ~flag))); + UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_STYLE, new HandleRef(null, (IntPtr)(value ? styleFlags | flag : styleFlags & ~flag))); } /// /// Makes the control display by setting the visible property to true /// - public void Show() { + public void Show() + { Visible = true; } [EditorBrowsable(EditorBrowsableState.Never)] - internal bool ShouldSerializeMargin() { + internal bool ShouldSerializeMargin() + { return !Margin.Equals(DefaultMargin); } [EditorBrowsable(EditorBrowsableState.Never)] - internal virtual bool ShouldSerializeMaximumSize() { + internal virtual bool ShouldSerializeMaximumSize() + { return MaximumSize != DefaultMaximumSize; } [EditorBrowsable(EditorBrowsableState.Never)] - internal virtual bool ShouldSerializeMinimumSize() { + internal virtual bool ShouldSerializeMinimumSize() + { return MinimumSize != DefaultMinimumSize; } [EditorBrowsable(EditorBrowsableState.Never)] - internal bool ShouldSerializePadding() { + internal bool ShouldSerializePadding() + { return !Padding.Equals(DefaultPadding); } @@ -11078,7 +12827,8 @@ internal bool ShouldSerializePadding() { /// Determines if the property needs to be persisted. /// [EditorBrowsable(EditorBrowsableState.Never)] - internal virtual bool ShouldSerializeSize() { + internal virtual bool ShouldSerializeSize() + { // In Whidbey the ControlDesigner class will always serialize size as it replaces the Size // property descriptor with its own. This is here for compat. Size s = DefaultSize; @@ -11089,22 +12839,26 @@ internal virtual bool ShouldSerializeSize() { /// Determines if the property needs to be persisted. /// [EditorBrowsable(EditorBrowsableState.Never)] - internal virtual bool ShouldSerializeText() { + internal virtual bool ShouldSerializeText() + { return Text.Length != 0; } /// /// Suspends the layout logic for the control. /// - public void SuspendLayout() { + public void SuspendLayout() + { layoutSuspendCount++; - if (layoutSuspendCount == 1) { + if (layoutSuspendCount == 1) + { OnLayoutSuspended(); } #if DEBUG Debug.Assert(layoutSuspendCount > 0, "SuspendLayout: layoutSuspendCount overflowed."); - if (CompModSwitches.LayoutSuspendResume.TraceInfo) { + if (CompModSwitches.LayoutSuspendResume.TraceInfo) + { Debug.WriteLine(GetType().Name + "::SuspendLayout( newCount = " + layoutSuspendCount + ")"); } #endif @@ -11113,14 +12867,16 @@ public void SuspendLayout() { /// /// Stops listening for the mouse leave event. /// - private void UnhookMouseEvent() { + private void UnhookMouseEvent() + { SetState(STATE_TRACKINGMOUSEEVENT, false); } /// /// Forces the control to paint any currently invalid areas. /// - public void Update() { + public void Update() + { SafeNativeMethods.UpdateWindow(new HandleRef(window, InternalHandle)); } @@ -11130,13 +12886,15 @@ public void Update() { /// // Internal for ScrollableControl [EditorBrowsable(EditorBrowsableState.Advanced)] - protected internal void UpdateBounds() { + protected internal void UpdateBounds() + { NativeMethods.RECT rect = new NativeMethods.RECT(); UnsafeNativeMethods.GetClientRect(new HandleRef(window, InternalHandle), ref rect); int clientWidth = rect.right; int clientHeight = rect.bottom; UnsafeNativeMethods.GetWindowRect(new HandleRef(window, InternalHandle), ref rect); - if (!GetTopLevel()) { + if (!GetTopLevel()) + { UnsafeNativeMethods.MapWindowPoints(NativeMethods.NullHandleRef, new HandleRef(null, UnsafeNativeMethods.GetParent(new HandleRef(window, InternalHandle))), ref rect, 2); } @@ -11148,7 +12906,8 @@ protected internal void UpdateBounds() { /// Updates the bounds of the control based on the bounds passed in. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected void UpdateBounds(int x, int y, int width, int height) { + protected void UpdateBounds(int x, int y, int width, int height) + { Debug.Assert(!IsHandleCreated, "Don't call this method when handle is created!!"); // reverse-engineer the AdjustWindowRectEx call to figure out @@ -11168,14 +12927,16 @@ protected void UpdateBounds(int x, int y, int width, int height) { /// Updates the bounds of the control based on the bounds passed in. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected void UpdateBounds(int x, int y, int width, int height, int clientWidth, int clientHeight) { + protected void UpdateBounds(int x, int y, int width, int height, int clientWidth, int clientHeight) + { #if DEBUG - if (CompModSwitches.SetBounds.TraceVerbose){ - Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0}::UpdateBounds(", Name)); - Debug.Indent(); - Debug.WriteLine(string.Format( - CultureInfo.CurrentCulture, "oldBounds={{x={0} y={1} width={2} height={3} clientWidth={4} clientHeight={5}}}", - this.x, this.y, this.width, this.height, this.clientWidth, this.clientHeight)); + if (CompModSwitches.SetBounds.TraceVerbose) + { + Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0}::UpdateBounds(", Name)); + Debug.Indent(); + Debug.WriteLine(string.Format( + CultureInfo.CurrentCulture, "oldBounds={{x={0} y={1} width={2} height={3} clientWidth={4} clientHeight={5}}}", + this.x, this.y, this.width, this.height, this.clientWidth, this.clientHeight)); } #endif // DEBUG @@ -11191,18 +12952,21 @@ protected void UpdateBounds(int x, int y, int width, int height, int clientWidth this.clientWidth = clientWidth; this.clientHeight = clientHeight; - if (newLocation) { + if (newLocation) + { #if DEBUG Rectangle originalBounds = this.Bounds; #endif OnLocationChanged(EventArgs.Empty); #if DEBUG - if (this.Bounds != originalBounds && CompModSwitches.SetBounds.TraceWarning) { + if (this.Bounds != originalBounds && CompModSwitches.SetBounds.TraceWarning) + { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "WARNING: Bounds changed during OnLocationChanged()\r\nbefore={0} after={1}", originalBounds, this.Bounds)); } #endif } - if (newSize) { + if (newSize) + { #if DEBUG Rectangle originalBounds = this.Bounds; #endif @@ -11214,16 +12978,18 @@ protected void UpdateBounds(int x, int y, int width, int height, int clientWidth LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.Bounds); #if DEBUG - if (this.Bounds != originalBounds && CompModSwitches.SetBounds.TraceWarning) { + if (this.Bounds != originalBounds && CompModSwitches.SetBounds.TraceWarning) + { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "WARNING: Bounds changed during OnSizeChanged()\r\nbefore={0} after={1}", originalBounds, this.Bounds)); } #endif } - + #if DEBUG - if (CompModSwitches.SetBounds.TraceVerbose) { - Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "newBounds={{x={0} y={1} width={2} height={3} clientWidth={4} clientHeight={5}}}",x, y, width, height, clientWidth, clientHeight)); + if (CompModSwitches.SetBounds.TraceVerbose) + { + Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "newBounds={{x={0} y={1} width={2} height={3} clientWidth={4} clientHeight={5}}}", x, y, width, height, clientWidth, clientHeight)); Debug.Unindent(); } #endif @@ -11234,8 +13000,10 @@ protected void UpdateBounds(int x, int y, int width, int height, int clientWidth /// We have the code here, rather than in PropertyChagned, so we don't pull /// in the data assembly if it's not used. /// - private void UpdateBindings() { - for (int i = 0; i < DataBindings.Count; i++) { + private void UpdateBindings() + { + for (int i = 0; i < DataBindings.Count; i++) + { BindingContext.UpdateBinding(BindingContext, DataBindings[i]); } } @@ -11244,11 +13012,14 @@ private void UpdateBindings() { /// Updates the child control's position in the control array to correctly /// reflect it's index. /// - private void UpdateChildControlIndex(Control ctl) { + private void UpdateChildControlIndex(Control ctl) + { // Don't reorder the child control array for tab controls. Implemented as a special case // in order to keep the method private. - if (!LocalAppContextSwitches.AllowUpdateChildControlIndexForTabControls) { - if (this.GetType().IsAssignableFrom(typeof(TabControl))) { + if (!LocalAppContextSwitches.AllowUpdateChildControlIndexForTabControls) + { + if (this.GetType().IsAssignableFrom(typeof(TabControl))) + { return; } } @@ -11256,14 +13027,17 @@ private void UpdateChildControlIndex(Control ctl) { int newIndex = 0; int curIndex = this.Controls.GetChildIndex(ctl); IntPtr hWnd = ctl.InternalHandle; - while ((hWnd = UnsafeNativeMethods.GetWindow(new HandleRef(null, hWnd), NativeMethods.GW_HWNDPREV)) != IntPtr.Zero) { + while ((hWnd = UnsafeNativeMethods.GetWindow(new HandleRef(null, hWnd), NativeMethods.GW_HWNDPREV)) != IntPtr.Zero) + { Control c = FromHandle(hWnd); - if (c != null) { + if (c != null) + { newIndex = this.Controls.GetChildIndex(c, false) + 1; break; } } - if (newIndex > curIndex) { + if (newIndex > curIndex) + { newIndex--; } if (newIndex != curIndex) @@ -11282,10 +13056,13 @@ private void UpdateChildControlIndex(Control ctl) { // Scenario is when you've got a control in one parent, you move it to another, then destroy the first parent. It'll stop // getting any reflected messages because Windows will send them to the original parent. // - private void UpdateReflectParent(bool findNewParent) { - if (!Disposing && findNewParent && IsHandleCreated) { + private void UpdateReflectParent(bool findNewParent) + { + if (!Disposing && findNewParent && IsHandleCreated) + { IntPtr parentHandle = UnsafeNativeMethods.GetParent(new HandleRef(this, Handle)); - if (parentHandle != IntPtr.Zero) { + if (parentHandle != IntPtr.Zero) + { ReflectParent = Control.FromHandle(parentHandle); return; } @@ -11297,8 +13074,10 @@ private void UpdateReflectParent(bool findNewParent) { /// Updates this control in it's parent's zorder. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected void UpdateZOrder() { - if (parent != null) { + protected void UpdateZOrder() + { + if (parent != null) + { parent.UpdateChildZOrder(this); } } @@ -11306,23 +13085,30 @@ protected void UpdateZOrder() { /// /// Syncs the ZOrder of child control to the index we want it to be. /// - private void UpdateChildZOrder(Control ctl) { - if (!IsHandleCreated || !ctl.IsHandleCreated || ctl.parent != this) return; + private void UpdateChildZOrder(Control ctl) + { + if (!IsHandleCreated || !ctl.IsHandleCreated || ctl.parent != this) + return; IntPtr prevHandle = (IntPtr)NativeMethods.HWND_TOP; - for (int i = this.Controls.GetChildIndex(ctl); --i >= 0;) { + for (int i = this.Controls.GetChildIndex(ctl); --i >= 0;) + { Control c = Controls[i]; - if (c.IsHandleCreated && c.parent == this) { + if (c.IsHandleCreated && c.parent == this) + { prevHandle = c.Handle; break; } } - if (UnsafeNativeMethods.GetWindow(new HandleRef(ctl.window, ctl.Handle), NativeMethods.GW_HWNDPREV) != prevHandle) { + if (UnsafeNativeMethods.GetWindow(new HandleRef(ctl.window, ctl.Handle), NativeMethods.GW_HWNDPREV) != prevHandle) + { state |= STATE_NOZORDER; - try { + try + { SafeNativeMethods.SetWindowPos(new HandleRef(ctl.window, ctl.Handle), new HandleRef(null, prevHandle), 0, 0, 0, 0, NativeMethods.SWP_NOMOVE | NativeMethods.SWP_NOSIZE); } - finally { + finally + { state &= ~STATE_NOZORDER; } } @@ -11332,7 +13118,8 @@ private void UpdateChildZOrder(Control ctl) { /// Updates the rootReference in the bound window. /// (Used to prevent visible top-level controls from being garbage collected) /// - private void UpdateRoot() { + private void UpdateRoot() + { window.LockReference(GetTopLevel() && Visible); } @@ -11341,26 +13128,32 @@ private void UpdateRoot() { /// CreateParams to get the styles to apply. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected void UpdateStyles() { + protected void UpdateStyles() + { UpdateStylesCore(); OnStyleChanged(EventArgs.Empty); } - internal virtual void UpdateStylesCore() { - if (IsHandleCreated) { + internal virtual void UpdateStylesCore() + { + if (IsHandleCreated) + { CreateParams cp = CreateParams; int winStyle = WindowStyle; int exStyle = WindowExStyle; // resolve the Form's lazy visibility. - if ((state & STATE_VISIBLE) != 0){ + if ((state & STATE_VISIBLE) != 0) + { cp.Style |= NativeMethods.WS_VISIBLE; } - if (winStyle != cp.Style) { + if (winStyle != cp.Style) + { WindowStyle = cp.Style; } - if (exStyle != cp.ExStyle) { + if (exStyle != cp.ExStyle) + { WindowExStyle = cp.ExStyle; SetState(STATE_MIRRORED, (cp.ExStyle & NativeMethods.WS_EX_LAYOUTRTL) != 0); } @@ -11373,9 +13166,11 @@ internal virtual void UpdateStylesCore() { Invalidate(true); } } - - private void UserPreferenceChanged(object sender, UserPreferenceChangedEventArgs pref) { - if (pref.Category == UserPreferenceCategory.Color) { + + private void UserPreferenceChanged(object sender, UserPreferenceChangedEventArgs pref) + { + if (pref.Category == UserPreferenceCategory.Color) + { defaultFont = null; OnSystemColorsChanged(EventArgs.Empty); } @@ -11399,25 +13194,30 @@ internal void WindowReleaseHandle() window.ReleaseHandle(); } - private void WmClose(ref Message m) { - - if (ParentInternal != null) { + private void WmClose(ref Message m) + { + + if (ParentInternal != null) + { IntPtr parentHandle = Handle; IntPtr lastParentHandle = parentHandle; - while (parentHandle != IntPtr.Zero) { + while (parentHandle != IntPtr.Zero) + { lastParentHandle = parentHandle; parentHandle = UnsafeNativeMethods.GetParent(new HandleRef(null, parentHandle)); int style = unchecked((int)((long)UnsafeNativeMethods.GetWindowLong(new HandleRef(null, lastParentHandle), NativeMethods.GWL_STYLE))); - if ((style & NativeMethods.WS_CHILD) == 0) { + if ((style & NativeMethods.WS_CHILD) == 0) + { break; } } - if (lastParentHandle != IntPtr.Zero) { + if (lastParentHandle != IntPtr.Zero) + { UnsafeNativeMethods.PostMessage(new HandleRef(null, lastParentHandle), Interop.WindowMessages.WM_CLOSE, IntPtr.Zero, IntPtr.Zero); } } @@ -11428,20 +13228,25 @@ private void WmClose(ref Message m) { /// /// Handles the WM_CAPTURECHANGED message /// - private void WmCaptureChanged(ref Message m) { + private void WmCaptureChanged(ref Message m) + { OnMouseCaptureChanged(EventArgs.Empty); DefWndProc(ref m); } - + /// /// Handles the WM_COMMAND message /// - private void WmCommand(ref Message m) { - if (IntPtr.Zero == m.LParam) { - if (Command.DispatchID(NativeMethods.Util.LOWORD(m.WParam))) return; + private void WmCommand(ref Message m) + { + if (IntPtr.Zero == m.LParam) + { + if (Command.DispatchID(NativeMethods.Util.LOWORD(m.WParam))) + return; } - else { + else + { if (ReflectMessage(m.LParam, ref m)) { return; @@ -11451,19 +13256,22 @@ private void WmCommand(ref Message m) { } // overridable so nested controls can provide a different source control. - internal virtual void WmContextMenu(ref Message m) { + internal virtual void WmContextMenu(ref Message m) + { WmContextMenu(ref m, this); } - + /// /// Handles the WM_CONTEXTMENU message /// - internal void WmContextMenu(ref Message m, Control sourceControl) { - ContextMenu contextMenu = Properties.GetObject(PropContextMenu) as ContextMenu; - ContextMenuStrip contextMenuStrip = (contextMenu != null) ? null /*save ourselves a property fetch*/ + internal void WmContextMenu(ref Message m, Control sourceControl) + { + ContextMenu contextMenu = Properties.GetObject(PropContextMenu) as ContextMenu; + ContextMenuStrip contextMenuStrip = (contextMenu != null) ? null /*save ourselves a property fetch*/ : Properties.GetObject(PropContextMenuStrip) as ContextMenuStrip; - if (contextMenu != null || contextMenuStrip != null) { + if (contextMenu != null || contextMenuStrip != null) + { int x = NativeMethods.Util.SignedLOWORD(m.LParam); int y = NativeMethods.Util.SignedHIWORD(m.LParam); Point client; @@ -11471,32 +13279,40 @@ internal void WmContextMenu(ref Message m, Control sourceControl) { // lparam will be exactly -1 when the user invokes the context menu // with the keyboard. // - if (unchecked((int)(long)m.LParam) == -1) { + if (unchecked((int)(long)m.LParam) == -1) + { keyboardActivated = true; - client = new Point(Width/2, Height/2); + client = new Point(Width / 2, Height / 2); } - else { + else + { client = PointToClient(new Point(x, y)); } // VisualStudio7 # 156, only show the context menu when clicked in the client area - if (ClientRectangle.Contains( client )) { - if (contextMenu != null) { + if (ClientRectangle.Contains(client)) + { + if (contextMenu != null) + { contextMenu.Show(sourceControl, client); } - else if (contextMenuStrip != null) { + else if (contextMenuStrip != null) + { contextMenuStrip.ShowInternal(sourceControl, client, keyboardActivated); } - else { - Debug.Fail("contextmenu and contextmenustrip are both null... hmm how did we get here?"); - DefWndProc( ref m ); + else + { + Debug.Fail("contextmenu and contextmenustrip are both null... hmm how did we get here?"); + DefWndProc(ref m); } } - else { - DefWndProc( ref m ); + else + { + DefWndProc(ref m); } } - else { + else + { DefWndProc(ref m); } } @@ -11504,20 +13320,24 @@ internal void WmContextMenu(ref Message m, Control sourceControl) { /// /// Handles the WM_CTLCOLOR message /// - private void WmCtlColorControl(ref Message m) { + private void WmCtlColorControl(ref Message m) + { // We could simply reflect the message, but it's faster to handle it here if possible. Control control = Control.FromHandle(m.LParam); - if (control != null) { + if (control != null) + { m.Result = control.InitializeDCForWmCtlColor(m.WParam, m.Msg); - if (m.Result != IntPtr.Zero) { + if (m.Result != IntPtr.Zero) + { return; } - } + } DefWndProc(ref m); } - private void WmDisplayChange(ref Message m) { + private void WmDisplayChange(ref Message m) + { BufferedGraphicsManager.Current.Invalidate(); DefWndProc(ref m); } @@ -11525,19 +13345,23 @@ private void WmDisplayChange(ref Message m) { /// /// WM_DRAWITEM handler /// - private void WmDrawItem(ref Message m) { + private void WmDrawItem(ref Message m) + { // If the wparam is zero, then the message was sent by a menu. // See WM_DRAWITEM in MSDN. - if (m.WParam == IntPtr.Zero) { + if (m.WParam == IntPtr.Zero) + { WmDrawItemMenuItem(ref m); } - else { + else + { WmOwnerDraw(ref m); } } - private void WmDrawItemMenuItem(ref Message m) { + private void WmDrawItemMenuItem(ref Message m) + { // Obtain the menu item object NativeMethods.DRAWITEMSTRUCT dis = (NativeMethods.DRAWITEMSTRUCT)m.GetLParam(typeof(NativeMethods.DRAWITEMSTRUCT)); @@ -11547,7 +13371,8 @@ private void WmDrawItemMenuItem(ref Message m) { MenuItem menuItem = MenuItem.GetMenuItemFromItemData(dis.itemData); // Delegate this message to the menu item - if (menuItem != null) { + if (menuItem != null) + { menuItem.WmDrawItem(ref m); } } @@ -11555,25 +13380,31 @@ private void WmDrawItemMenuItem(ref Message m) { /// /// Handles the WM_ERASEBKGND message /// - private void WmEraseBkgnd(ref Message m) { - if (GetStyle(ControlStyles.UserPaint)) { + private void WmEraseBkgnd(ref Message m) + { + if (GetStyle(ControlStyles.UserPaint)) + { // When possible, it's best to do all painting directly from WM_PAINT. // OptimizedDoubleBuffer is the "same" as turning on AllPaintingInWMPaint - if (!(GetStyle(ControlStyles.AllPaintingInWmPaint))) { + if (!(GetStyle(ControlStyles.AllPaintingInWmPaint))) + { IntPtr dc = m.WParam; - if (dc == IntPtr.Zero) { // This happens under extreme stress conditions + if (dc == IntPtr.Zero) + { // This happens under extreme stress conditions m.Result = (IntPtr)0; return; } NativeMethods.RECT rc = new NativeMethods.RECT(); UnsafeNativeMethods.GetClientRect(new HandleRef(this, Handle), ref rc); - using (PaintEventArgs pevent = new PaintEventArgs(dc, Rectangle.FromLTRB(rc.left, rc.top, rc.right, rc.bottom))) { + using (PaintEventArgs pevent = new PaintEventArgs(dc, Rectangle.FromLTRB(rc.left, rc.top, rc.right, rc.bottom))) + { PaintWithErrorHandling(pevent, PaintLayerBackground); } } m.Result = (IntPtr)1; } - else { + else + { DefWndProc(ref m); } } @@ -11582,12 +13413,15 @@ private void WmEraseBkgnd(ref Message m) { /// Handles the WM_EXITMENULOOP message. If this control has a context menu, its /// Collapse event is raised. /// - private void WmExitMenuLoop(ref Message m) { + private void WmExitMenuLoop(ref Message m) + { bool isContextMenu = (unchecked((int)(long)m.WParam) == 0) ? false : true; - if (isContextMenu) { + if (isContextMenu) + { ContextMenu contextMenu = (ContextMenu)Properties.GetObject(PropContextMenu); - if (contextMenu != null) { + if (contextMenu != null) + { contextMenu.OnCollapse(EventArgs.Empty); } } @@ -11598,13 +13432,16 @@ private void WmExitMenuLoop(ref Message m) { /// /// Handles the WM_GETCONTROLNAME message. Returns the name of the control. /// - private void WmGetControlName(ref Message m) { + private void WmGetControlName(ref Message m) + { string name; - if (this.Site != null) { + if (this.Site != null) + { name = this.Site.Name; } - else { + else + { name = this.Name; } @@ -11618,7 +13455,8 @@ private void WmGetControlName(ref Message m) { /// /// Handles the WM_GETCONTROLTYPE message. Returns the name of the control. /// - private void WmGetControlType(ref Message m) { + private void WmGetControlType(ref Message m) + { string type = GetType().AssemblyQualifiedName; MarshalStringToMessage(type, ref m); } @@ -11626,12 +13464,14 @@ private void WmGetControlType(ref Message m) { /// /// Handles the WM_GETOBJECT message. Used for accessibility. /// - private void WmGetObject(ref Message m) { + private void WmGetObject(ref Message m) + { Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "In WmGetObject, this = " + this.GetType().FullName + ", lParam = " + m.LParam.ToString()); InternalAccessibleObject intAccessibleObject = null; - if (m.Msg == Interop.WindowMessages.WM_GETOBJECT && m.LParam == (IntPtr)NativeMethods.UiaRootObjectId && this.SupportsUiaProviders) { + if (m.Msg == Interop.WindowMessages.WM_GETOBJECT && m.LParam == (IntPtr)NativeMethods.UiaRootObjectId && this.SupportsUiaProviders) + { // If the requested object identifier is UiaRootObjectId, // we should return an UI Automation provider using the UiaReturnRawElementProvider function. intAccessibleObject = new InternalAccessibleObject(this.AccessibilityObject); @@ -11646,12 +13486,14 @@ private void WmGetObject(ref Message m) { AccessibleObject ctrlAccessibleObject = GetAccessibilityObject(unchecked((int)(long)m.LParam)); - if (ctrlAccessibleObject != null) { + if (ctrlAccessibleObject != null) + { intAccessibleObject = new InternalAccessibleObject(ctrlAccessibleObject); } // See "How to Handle WM_GETOBJECT" in MSDN - if (intAccessibleObject != null) { + if (intAccessibleObject != null) + { // Get the IAccessible GUID // @@ -11660,7 +13502,8 @@ private void WmGetObject(ref Message m) { // Get an Lresult for the accessibility Object for this control // IntPtr punkAcc; - try { + try + { // It is critical that we never pass out a raw IAccessible object here, // but always pass out an IAccessibleInternal wrapper. This may not be possible in the current implementation // of WmGetObject - but its important enough to keep this check here in case the code changes in the future in @@ -11668,38 +13511,45 @@ private void WmGetObject(ref Message m) { object tempObject = intAccessibleObject; IAccessible iAccCheck = tempObject as IAccessible; - if (iAccCheck != null) { + if (iAccCheck != null) + { throw new InvalidOperationException(SR.ControlAccessibileObjectInvalid); } // Check that we have an IAccessibleInternal implementation and return this - UnsafeNativeMethods.IAccessibleInternal iacc = (UnsafeNativeMethods.IAccessibleInternal) intAccessibleObject; + UnsafeNativeMethods.IAccessibleInternal iacc = (UnsafeNativeMethods.IAccessibleInternal)intAccessibleObject; - if (iacc == null) { + if (iacc == null) + { // Accessibility is not supported on this control // Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "AccessibilityObject returned null"); m.Result = (IntPtr)0; } - else { + else + { // Obtain the Lresult // punkAcc = Marshal.GetIUnknownForObject(iacc); - try { + try + { m.Result = UnsafeNativeMethods.LresultFromObject(ref IID_IAccessible, m.WParam, new HandleRef(ctrlAccessibleObject, punkAcc)); Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "LresultFromObject returned " + m.Result.ToString()); } - finally { + finally + { Marshal.Release(punkAcc); } } } - catch (Exception e) { + catch (Exception e) + { throw new InvalidOperationException(SR.RichControlLresult, e); } } - else { // some accessible object requested that we don't care about, so do default message processing + else + { // some accessible object requested that we don't care about, so do default message processing DefWndProc(ref m); } } @@ -11707,20 +13557,27 @@ private void WmGetObject(ref Message m) { /// /// Handles the WM_HELP message /// - private void WmHelp(ref Message m) { + private void WmHelp(ref Message m) + { // if there's currently a message box open - grab the help info from it. HelpInfo hpi = MessageBox.HelpInfo; - if (hpi != null) { - switch (hpi.Option) { - case NativeMethods.HLP_FILE : Help.ShowHelp (this, hpi.HelpFilePath); - break; - case NativeMethods.HLP_KEYWORD : Help.ShowHelp (this, hpi.HelpFilePath, hpi.Keyword); - break; - case NativeMethods.HLP_NAVIGATOR : Help.ShowHelp (this, hpi.HelpFilePath, hpi.Navigator); - break; - case NativeMethods.HLP_OBJECT : Help.ShowHelp (this, hpi.HelpFilePath, hpi.Navigator, hpi.Param); - break; + if (hpi != null) + { + switch (hpi.Option) + { + case NativeMethods.HLP_FILE: + Help.ShowHelp(this, hpi.HelpFilePath); + break; + case NativeMethods.HLP_KEYWORD: + Help.ShowHelp(this, hpi.HelpFilePath, hpi.Keyword); + break; + case NativeMethods.HLP_NAVIGATOR: + Help.ShowHelp(this, hpi.HelpFilePath, hpi.Navigator); + break; + case NativeMethods.HLP_OBJECT: + Help.ShowHelp(this, hpi.HelpFilePath, hpi.Navigator, hpi.Param); + break; } } @@ -11729,7 +13586,8 @@ private void WmHelp(ref Message m) { HelpEventArgs hevent = new HelpEventArgs(new Point(info.MousePos.x, info.MousePos.y)); OnHelpRequested(hevent); - if (!hevent.Handled) { + if (!hevent.Handled) + { DefWndProc(ref m); } @@ -11738,9 +13596,11 @@ private void WmHelp(ref Message m) { /// /// Handles the WM_INITMENUPOPUP message /// - private void WmInitMenuPopup(ref Message m) { + private void WmInitMenuPopup(ref Message m) + { ContextMenu contextMenu = (ContextMenu)Properties.GetObject(PropContextMenu); - if (contextMenu != null) { + if (contextMenu != null) + { if (contextMenu.ProcessInitMenuPopup(m.WParam)) return; @@ -11751,11 +13611,13 @@ private void WmInitMenuPopup(ref Message m) { /// /// WM_MEASUREITEM handler /// - private void WmMeasureItem(ref Message m) { + private void WmMeasureItem(ref Message m) + { // If the wparam is zero, then the message was sent by a menu. // See WM_MEASUREITEM in MSDN. - if (m.WParam == IntPtr.Zero) { + if (m.WParam == IntPtr.Zero) + { // Obtain the menu item object NativeMethods.MEASUREITEMSTRUCT mis = (NativeMethods.MEASUREITEMSTRUCT)m.GetLParam(typeof(NativeMethods.MEASUREITEMSTRUCT)); @@ -11769,11 +13631,13 @@ private void WmMeasureItem(ref Message m) { Debug.Assert(menuItem != null, "UniqueID is not associated with a menu item"); // Delegate this message to the menu item - if (menuItem != null) { + if (menuItem != null) + { menuItem.WmMeasureItem(ref m); } } - else { + else + { WmOwnerDraw(ref m); } } @@ -11781,11 +13645,14 @@ private void WmMeasureItem(ref Message m) { /// /// Handles the WM_MENUCHAR message /// - private void WmMenuChar(ref Message m) { + private void WmMenuChar(ref Message m) + { Menu menu = ContextMenu; - if (menu != null) { + if (menu != null) + { menu.WmMenuChar(ref m); - if (m.Result != IntPtr.Zero) { + if (m.Result != IntPtr.Zero) + { // This char is a mnemonic on our menu. return; } @@ -11795,29 +13662,36 @@ private void WmMenuChar(ref Message m) { /// /// Handles the WM_MENUSELECT message /// - private void WmMenuSelect(ref Message m) { + private void WmMenuSelect(ref Message m) + { int item = NativeMethods.Util.LOWORD(m.WParam); int flags = NativeMethods.Util.HIWORD(m.WParam); IntPtr hmenu = m.LParam; MenuItem mi = null; - if ((flags & NativeMethods.MF_SYSMENU) != 0) { + if ((flags & NativeMethods.MF_SYSMENU) != 0) + { // nothing } - else if ((flags & NativeMethods.MF_POPUP) == 0) { + else if ((flags & NativeMethods.MF_POPUP) == 0) + { Command cmd = Command.GetCommandFromID(item); - if (cmd != null) { + if (cmd != null) + { object reference = cmd.Target; - if (reference != null && reference is MenuItem.MenuItemData) { + if (reference != null && reference is MenuItem.MenuItemData) + { mi = ((MenuItem.MenuItemData)reference).baseItem; } } } - else { + else + { mi = GetMenuItemFromHandleId(hmenu, item); } - if (mi != null) { + if (mi != null) + { mi.PerformSelect(); } @@ -11827,11 +13701,13 @@ private void WmMenuSelect(ref Message m) { /// /// Handles the WM_CREATE message /// - private void WmCreate(ref Message m) { + private void WmCreate(ref Message m) + { DefWndProc(ref m); - if (parent != null) { + if (parent != null) + { parent.UpdateChildZOrder(this); } UpdateBounds(); @@ -11846,7 +13722,8 @@ private void WmCreate(ref Message m) { // property that forces handle recreation, you lose your text! // See the below code in wmDestroy // - if (!GetStyle(ControlStyles.CacheText)) { + if (!GetStyle(ControlStyles.CacheText)) + { text = null; } } @@ -11854,7 +13731,8 @@ private void WmCreate(ref Message m) { /// /// Handles the WM_DESTROY message /// - private void WmDestroy(ref Message m) { + private void WmDestroy(ref Message m) + { // Let any interested sites know that we're destroying our handle // @@ -11875,15 +13753,18 @@ private void WmDestroy(ref Message m) { OnHandleDestroyed(EventArgs.Empty); - if (!Disposing) { + if (!Disposing) + { // If we are not recreating the handle, set our created state // back to false so we can be rebuilt if we need to be. // - if (!RecreatingHandle) { + if (!RecreatingHandle) + { SetState(STATE_CREATED, false); } } - else { + else + { SetState(STATE_VISIBLE, false); } @@ -11894,15 +13775,18 @@ private void WmDestroy(ref Message m) { /// Handles the WM_CHAR, WM_KEYDOWN, WM_SYSKEYDOWN, WM_KEYUP, and /// WM_SYSKEYUP messages. /// - private void WmKeyChar(ref Message m) { - if (ProcessKeyMessage(ref m)) return; + private void WmKeyChar(ref Message m) + { + if (ProcessKeyMessage(ref m)) + return; DefWndProc(ref m); } /// /// Handles the WM_KILLFOCUS message /// - private void WmKillFocus(ref Message m) { + private void WmKillFocus(ref Message m) + { Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Control::WmKillFocus - " + this.Name); WmImeKillFocus(); DefWndProc(ref m); @@ -11912,7 +13796,8 @@ private void WmKillFocus(ref Message m) { /// /// Handles the WM_MOUSEDOWN message /// - private void WmMouseDown(ref Message m, MouseButtons button, int clicks) { + private void WmMouseDown(ref Message m, MouseButtons button, int clicks) + { // If this is a "real" mouse event (not just WM_LBUTTONDOWN, etc) then // we need to see if something happens during processing of // user code that changed the state of the buttons (i.e. bringing up @@ -11924,37 +13809,45 @@ private void WmMouseDown(ref Message m, MouseButtons button, int clicks) { // If the UserMouse style is set, the control does its own processing // of mouse messages // - if (!GetStyle(ControlStyles.UserMouse)) { + if (!GetStyle(ControlStyles.UserMouse)) + { DefWndProc(ref m); // we might had re-entered the message loop and processed a WM_CLOSE message - if (IsDisposed) { - return; - } + if (IsDisposed) + { + return; + } } - else { + else + { // DefWndProc would normally set the focus to this control, but // since we're skipping DefWndProc, we need to do it ourselves. - if (button == MouseButtons.Left && GetStyle(ControlStyles.Selectable)) { + if (button == MouseButtons.Left && GetStyle(ControlStyles.Selectable)) + { Focus(); } } - if (realState != MouseButtons) { + if (realState != MouseButtons) + { return; } - if (!GetState2(STATE2_MAINTAINSOWNCAPTUREMODE)) { + if (!GetState2(STATE2_MAINTAINSOWNCAPTUREMODE)) + { //CaptureInternal is set usually in MouseDown (ToolStrip main exception) CaptureInternal = true; } - if (realState != MouseButtons) { + if (realState != MouseButtons) + { return; } // control should be enabled when this method is entered, but may have become // disabled during its lifetime (e.g. through a Click or Focus listener) - if (Enabled) { + if (Enabled) + { OnMouseDown(new MouseEventArgs(button, clicks, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); } } @@ -11962,7 +13855,8 @@ private void WmMouseDown(ref Message m, MouseButtons button, int clicks) { /// /// Handles the WM_MOUSEENTER message /// - private void WmMouseEnter(ref Message m) { + private void WmMouseEnter(ref Message m) + { DefWndProc(ref m); KeyboardToolTipStateMachine.Instance.NotifyAboutMouseEnter(this); OnMouseEnter(EventArgs.Empty); @@ -11971,7 +13865,8 @@ private void WmMouseEnter(ref Message m) { /// /// Handles the WM_MOUSELEAVE message /// - private void WmMouseLeave(ref Message m) { + private void WmMouseLeave(ref Message m) + { DefWndProc(ref m); OnMouseLeave(EventArgs.Empty); } @@ -11979,19 +13874,23 @@ private void WmMouseLeave(ref Message m) { /// /// Handles the WM_DPICHANGED_BEFOREPARENT message. This message is not sent to top level windows. /// - private void WmDpiChangedBeforeParent(ref Message m) { + private void WmDpiChangedBeforeParent(ref Message m) + { DefWndProc(ref m); - if (IsHandleCreated) { + if (IsHandleCreated) + { int deviceDpiOld = deviceDpi; deviceDpi = (int)UnsafeNativeMethods.GetDpiForWindow(new HandleRef(this, HandleInternal)); // Controls are by default font scaled. // Dpi change requires font to be recalculated inorder to get controls scaled with right dpi. - if (deviceDpiOld != deviceDpi) { + if (deviceDpiOld != deviceDpi) + { // Checking if font was inherited from parent. Font inherited from parent will receive OnParentFontChanged() events to scale those controls. Font local = (Font)Properties.GetObject(PropFont); - if (local != null) { + if (local != null) + { var factor = (float)deviceDpi / deviceDpiOld; this.Font = new Font(local.FontFamily, local.Size * factor, local.Style, local.Unit, local.GdiCharSet, local.GdiVerticalFont); } @@ -12006,7 +13905,8 @@ private void WmDpiChangedBeforeParent(ref Message m) { /// /// Handles the WM_DPICHANGED_AFTERPARENT message /// - private void WmDpiChangedAfterParent(ref Message m) { + private void WmDpiChangedAfterParent(ref Message m) + { DefWndProc(ref m); OnDpiChangedAfterParent(EventArgs.Empty); @@ -12016,7 +13916,8 @@ private void WmDpiChangedAfterParent(ref Message m) { /// Handles the "WM_MOUSEHOVER" message... until we get actuall OS support /// for this, it is implemented as a custom message. /// - private void WmMouseHover(ref Message m) { + private void WmMouseHover(ref Message m) + { DefWndProc(ref m); OnMouseHover(EventArgs.Empty); } @@ -12024,11 +13925,13 @@ private void WmMouseHover(ref Message m) { /// /// Handles the WM_MOUSEMOVE message /// - private void WmMouseMove(ref Message m) { + private void WmMouseMove(ref Message m) + { // If the UserMouse style is set, the control does its own processing // of mouse messages // - if (!GetStyle(ControlStyles.UserMouse)) { + if (!GetStyle(ControlStyles.UserMouse)) + { DefWndProc(ref m); } OnMouseMove(new MouseEventArgs(MouseButtons, 0, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); @@ -12037,40 +13940,49 @@ private void WmMouseMove(ref Message m) { /// /// Handles the WM_MOUSEUP message /// - private void WmMouseUp(ref Message m, MouseButtons button, int clicks) { + private void WmMouseUp(ref Message m, MouseButtons button, int clicks) + { // Get the mouse location // - try { + try + { int x = NativeMethods.Util.SignedLOWORD(m.LParam); int y = NativeMethods.Util.SignedHIWORD(m.LParam); - Point pt = new Point(x,y); + Point pt = new Point(x, y); pt = PointToScreen(pt); // If the UserMouse style is set, the control does its own processing // of mouse messages // - if (!GetStyle(ControlStyles.UserMouse)) { + if (!GetStyle(ControlStyles.UserMouse)) + { DefWndProc(ref m); } - else { + else + { // DefWndProc would normally trigger a context menu here // (for a right button click), but since we're skipping DefWndProc // we have to do it ourselves. - if (button == MouseButtons.Right) { + if (button == MouseButtons.Right) + { SendMessage(Interop.WindowMessages.WM_CONTEXTMENU, this.Handle, NativeMethods.Util.MAKELPARAM(pt.X, pt.Y)); } } bool fireClick = false; - if ((controlStyle & ControlStyles.StandardClick) == ControlStyles.StandardClick) { - if (GetState(STATE_MOUSEPRESSED) && !IsDisposed && UnsafeNativeMethods.WindowFromPoint(pt.X, pt.Y) == Handle) { - fireClick = true; + if ((controlStyle & ControlStyles.StandardClick) == ControlStyles.StandardClick) + { + if (GetState(STATE_MOUSEPRESSED) && !IsDisposed && UnsafeNativeMethods.WindowFromPoint(pt.X, pt.Y) == Handle) + { + fireClick = true; } } - if (fireClick && !ValidationCancelled) { - if (!GetState(STATE_DOUBLECLICKFIRED)) { + if (fireClick && !ValidationCancelled) + { + if (!GetState(STATE_DOUBLECLICKFIRED)) + { //OnClick(EventArgs.Empty); //In Whidbey .. if the click in by MOUSE then pass the MouseEventArgs... OnClick(new MouseEventArgs(button, clicks, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); @@ -12078,7 +13990,8 @@ private void WmMouseUp(ref Message m, MouseButtons button, int clicks) { } - else { + else + { //OnDoubleClick(EventArgs.Empty); OnDoubleClick(new MouseEventArgs(button, 2, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); OnMouseDoubleClick(new MouseEventArgs(button, 2, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); @@ -12088,7 +14001,8 @@ private void WmMouseUp(ref Message m, MouseButtons button, int clicks) { //call the MouseUp Finally... OnMouseUp(new MouseEventArgs(button, clicks, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); } - finally { + finally + { //Always Reset the STATE_DOUBLECLICKFIRED in UP.. Since we get UP - DOWN - DBLCLK - UP sequqnce //The Flag is set in L_BUTTONDBLCLK in the controls WndProc() ... // @@ -12103,7 +14017,8 @@ private void WmMouseUp(ref Message m, MouseButtons button, int clicks) { /// /// Handles the WM_MOUSEWHEEL message /// - private void WmMouseWheel(ref Message m) { + private void WmMouseWheel(ref Message m) + { Point p = new Point(NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam)); p = PointToClient(p); HandledMouseEventArgs e = new HandledMouseEventArgs(MouseButtons.None, @@ -12112,7 +14027,7 @@ private void WmMouseWheel(ref Message m) { p.Y, NativeMethods.Util.SignedHIWORD(m.WParam)); OnMouseWheel(e); - m.Result = (IntPtr) (e.Handled ? 0 : 1); + m.Result = (IntPtr)(e.Handled ? 0 : 1); if (!e.Handled) { // Forwarding the message to the parent window @@ -12125,7 +14040,8 @@ private void WmMouseWheel(ref Message m) { /// addition to WM_WINDOWPOSCHANGED because windows may /// send WM_MOVE directly. /// - private void WmMove(ref Message m) { + private void WmMove(ref Message m) + { DefWndProc(ref m); UpdateBounds(); } @@ -12133,17 +14049,21 @@ private void WmMove(ref Message m) { /// /// Handles the WM_NOTIFY message /// - private unsafe void WmNotify(ref Message m) { + private unsafe void WmNotify(ref Message m) + { NativeMethods.NMHDR* nmhdr = (NativeMethods.NMHDR*)m.LParam; - if (!ReflectMessage(nmhdr->hwndFrom,ref m)) { - if(nmhdr->code == NativeMethods.TTN_SHOW) { + if (!ReflectMessage(nmhdr->hwndFrom, ref m)) + { + if (nmhdr->code == NativeMethods.TTN_SHOW) + { m.Result = UnsafeNativeMethods.SendMessage(new HandleRef(null, nmhdr->hwndFrom), Interop.WindowMessages.WM_REFLECT + m.Msg, m.WParam, m.LParam); return; } - if(nmhdr->code == NativeMethods.TTN_POP) { + if (nmhdr->code == NativeMethods.TTN_POP) + { UnsafeNativeMethods.SendMessage(new HandleRef(null, nmhdr->hwndFrom), Interop.WindowMessages.WM_REFLECT + m.Msg, m.WParam, m.LParam); } - + DefWndProc(ref m); } } @@ -12151,8 +14071,10 @@ private unsafe void WmNotify(ref Message m) { /// /// Handles the WM_NOTIFYFORMAT message /// - private void WmNotifyFormat(ref Message m) { - if (!ReflectMessage(m.WParam, ref m)) { + private void WmNotifyFormat(ref Message m) + { + if (!ReflectMessage(m.WParam, ref m)) + { DefWndProc(ref m); } } @@ -12160,36 +14082,43 @@ private void WmNotifyFormat(ref Message m) { /// /// Handles the WM_DRAWITEM\WM_MEASUREITEM messages for controls other than menus /// - private void WmOwnerDraw(ref Message m) { + private void WmOwnerDraw(ref Message m) + { bool reflectCalled = false; int ctrlId = unchecked((int)(long)m.WParam); IntPtr p = UnsafeNativeMethods.GetDlgItem(new HandleRef(null, m.HWnd), ctrlId); - if (p == IntPtr.Zero) { + if (p == IntPtr.Zero) + { // On 64-bit platforms wParam is already 64 bit but the control ID stored in it is only 32-bit // Empirically, we have observed that the 64 bit HWND is just a sign extension of the 32-bit ctrl ID // Since WParam is already 64-bit, we need to discard the high dword first and then re-extend the 32-bit value // treating it as signed p = (IntPtr)(long)ctrlId; } - if (!ReflectMessage(p, ref m)) { + if (!ReflectMessage(p, ref m)) + { //Additional Check For Control .... TabControl truncates the Hwnd value... IntPtr handle = window.GetHandleFromID((short)NativeMethods.Util.LOWORD(m.WParam)); - if (handle != IntPtr.Zero) { + if (handle != IntPtr.Zero) + { Control control = Control.FromHandle(handle); - if (control != null) { + if (control != null) + { m.Result = control.SendMessage(Interop.WindowMessages.WM_REFLECT + m.Msg, handle, m.LParam); reflectCalled = true; } } } - else { + else + { reflectCalled = true; } - if (!reflectCalled) { - DefWndProc(ref m); + if (!reflectCalled) + { + DefWndProc(ref m); } } @@ -12197,10 +14126,12 @@ private void WmOwnerDraw(ref Message m) { /// Handles the WM_PAINT messages. This should only be called /// for userpaint controls. /// - private void WmPaint(ref Message m) { + private void WmPaint(ref Message m) + { bool doubleBuffered = DoubleBuffered || (GetStyle(ControlStyles.AllPaintingInWmPaint) && DoubleBufferingEnabled); #if DEBUG - if (BufferDisabled.Enabled) { + if (BufferDisabled.Enabled) + { doubleBuffered = false; } #endif @@ -12210,13 +14141,16 @@ private void WmPaint(ref Message m) { NativeMethods.PAINTSTRUCT ps = new NativeMethods.PAINTSTRUCT(); bool needDisposeDC = false; - try { - if (m.WParam == IntPtr.Zero) { + try + { + if (m.WParam == IntPtr.Zero) + { // Cache Handle not only for perf but to avoid object disposed exception in case the window // is destroyed in an event handler. hWnd = this.Handle; dc = UnsafeNativeMethods.BeginPaint(new HandleRef(this, hWnd), ref ps); - if (dc == IntPtr.Zero) { + if (dc == IntPtr.Zero) + { return; } needDisposeDC = true; @@ -12224,39 +14158,48 @@ private void WmPaint(ref Message m) { ps.rcPaint_right - ps.rcPaint_left, ps.rcPaint_bottom - ps.rcPaint_top); } - else { + else + { dc = m.WParam; clip = ClientRectangle; } // Consider: Why don't check the clip condition when non-doubleBuffered? // we should probably get rid of the !doubleBuffered condition. - if (!doubleBuffered || (clip.Width > 0 && clip.Height > 0)) { + if (!doubleBuffered || (clip.Width > 0 && clip.Height > 0)) + { IntPtr oldPal = IntPtr.Zero; BufferedGraphics bufferedGraphics = null; PaintEventArgs pevent = null; GraphicsState state = null; - try { - if (doubleBuffered || m.WParam == IntPtr.Zero) { + try + { + if (doubleBuffered || m.WParam == IntPtr.Zero) + { oldPal = SetUpPalette(dc, false, false); } - if (doubleBuffered) { - try { + if (doubleBuffered) + { + try + { bufferedGraphics = BufferContext.Allocate(dc, ClientRectangle); #if DEBUG - if (BufferPinkRect.Enabled) { - Rectangle band = ClientRectangle; - using( BufferedGraphics bufferedGraphics2 = BufferContext.Allocate( dc, band ) ) { - bufferedGraphics2.Graphics.FillRectangle( new SolidBrush( Color.Red ), band ); - bufferedGraphics2.Render(); + if (BufferPinkRect.Enabled) + { + Rectangle band = ClientRectangle; + using (BufferedGraphics bufferedGraphics2 = BufferContext.Allocate(dc, band)) + { + bufferedGraphics2.Graphics.FillRectangle(new SolidBrush(Color.Red), band); + bufferedGraphics2.Render(); } Thread.Sleep(50); } #endif } - catch (Exception ex) { + catch (Exception ex) + { // BufferContext.Allocate will throw out of memory exceptions // when it fails to create a device dependent bitmap while trying to // get information about the device we are painting on. @@ -12266,64 +14209,80 @@ private void WmPaint(ref Message m) { // We could set a specific string when throwing the exception and check for it here // to distinguish between that case and real out of memory exceptions but we // see no reasons justifying the additional complexity. - if (ClientUtils.IsCriticalException(ex) && !(ex is OutOfMemoryException)) { + if (ClientUtils.IsCriticalException(ex) && !(ex is OutOfMemoryException)) + { throw; } #if DEBUG - if( BufferPinkRect.Enabled ) { - Debug.WriteLine("Could not create buffered graphics, will paint in the surface directly" ); + if (BufferPinkRect.Enabled) + { + Debug.WriteLine("Could not create buffered graphics, will paint in the surface directly"); } #endif doubleBuffered = false; // paint directly on the window DC. } } - if (bufferedGraphics != null) { + if (bufferedGraphics != null) + { bufferedGraphics.Graphics.SetClip(clip); pevent = new PaintEventArgs(bufferedGraphics.Graphics, clip); state = pevent.Graphics.Save(); } - else { + else + { pevent = new PaintEventArgs(dc, clip); } - using (pevent) { - try { - if ((m.WParam == IntPtr.Zero) && GetStyle(ControlStyles.AllPaintingInWmPaint) || doubleBuffered) { + using (pevent) + { + try + { + if ((m.WParam == IntPtr.Zero) && GetStyle(ControlStyles.AllPaintingInWmPaint) || doubleBuffered) + { PaintWithErrorHandling(pevent, PaintLayerBackground); // Consider: This condition could be elimiated, // do we have to save/restore the state of the buffered graphics? } } - finally { - if (state != null) { + finally + { + if (state != null) + { pevent.Graphics.Restore(state); } - else { + else + { pevent.ResetGraphics(); } } PaintWithErrorHandling(pevent, PaintLayerForeground); - if (bufferedGraphics != null) { + if (bufferedGraphics != null) + { bufferedGraphics.Render(); } } } - finally { - if (oldPal != IntPtr.Zero) { + finally + { + if (oldPal != IntPtr.Zero) + { SafeNativeMethods.SelectPalette(new HandleRef(null, dc), new HandleRef(null, oldPal), 0); } - if (bufferedGraphics != null) { + if (bufferedGraphics != null) + { bufferedGraphics.Dispose(); } } } } - finally { - if (needDisposeDC) { + finally + { + if (needDisposeDC) + { UnsafeNativeMethods.EndPaint(new HandleRef(this, hWnd), ref ps); } } @@ -12332,19 +14291,24 @@ private void WmPaint(ref Message m) { /// /// Handles the WM_PRINTCLIENT messages. /// - private void WmPrintClient(ref Message m) { - using (PaintEventArgs e = new PrintPaintEventArgs(m, m.WParam, ClientRectangle)) { + private void WmPrintClient(ref Message m) + { + using (PaintEventArgs e = new PrintPaintEventArgs(m, m.WParam, ClientRectangle)) + { OnPrint(e); } } - private void WmQueryNewPalette(ref Message m) { + private void WmQueryNewPalette(ref Message m) + { Debug.WriteLineIf(Control.PaletteTracing.TraceVerbose, Handle + ": WM_QUERYNEWPALETTE"); IntPtr dc = UnsafeNativeMethods.GetDC(new HandleRef(this, Handle)); - try { + try + { SetUpPalette(dc, true /*force*/, true/*realize*/); } - finally { + finally + { // Let WmPaletteChanged do any necessary invalidation UnsafeNativeMethods.ReleaseDC(new HandleRef(this, Handle), new HandleRef(null, dc)); } @@ -12357,15 +14321,18 @@ private void WmQueryNewPalette(ref Message m) { /// /// Handles the WM_SETCURSOR message /// - private void WmSetCursor(ref Message m) { + private void WmSetCursor(ref Message m) + { // Accessing through the Handle property has side effects that break this // logic. You must use InternalHandle. // - if (m.WParam == InternalHandle && NativeMethods.Util.LOWORD(m.LParam) == NativeMethods.HTCLIENT) { + if (m.WParam == InternalHandle && NativeMethods.Util.LOWORD(m.LParam) == NativeMethods.HTCLIENT) + { Cursor.CurrentInternal = Cursor; } - else { + else + { DefWndProc(ref m); } @@ -12374,26 +14341,31 @@ private void WmSetCursor(ref Message m) { /// /// Handles the WM_WINDOWPOSCHANGING message /// - private unsafe void WmWindowPosChanging(ref Message m) { + private unsafe void WmWindowPosChanging(ref Message m) + { // We let this fall through to defwndproc unless we are being surfaced as // an ActiveX control. In that case, we must let the ActiveX side of things // manipulate our bounds here. // - if (IsActiveX) { - NativeMethods.WINDOWPOS* wp = (NativeMethods.WINDOWPOS *)m.LParam; + if (IsActiveX) + { + NativeMethods.WINDOWPOS* wp = (NativeMethods.WINDOWPOS*)m.LParam; // Only call UpdateBounds if the new bounds are different. // bool different = false; - if ((wp->flags & NativeMethods.SWP_NOMOVE) == 0 && (wp->x != Left || wp->y != Top)) { + if ((wp->flags & NativeMethods.SWP_NOMOVE) == 0 && (wp->x != Left || wp->y != Top)) + { different = true; } - if ((wp->flags & NativeMethods.SWP_NOSIZE) == 0 && (wp->cx != Width || wp->cy != Height)) { + if ((wp->flags & NativeMethods.SWP_NOSIZE) == 0 && (wp->cx != Width || wp->cy != Height)) + { different = true; } - if (different) { + if (different) + { ActiveXUpdateBounds(ref wp->x, ref wp->y, ref wp->cx, ref wp->cy, wp->flags); } } @@ -12405,10 +14377,12 @@ private unsafe void WmWindowPosChanging(ref Message m) { /// /// Handles the WM_PARENTNOTIFY message /// - private void WmParentNotify(ref Message m) { + private void WmParentNotify(ref Message m) + { int msg = NativeMethods.Util.LOWORD(m.WParam); IntPtr hWnd = IntPtr.Zero; - switch (msg) { + switch (msg) + { case Interop.WindowMessages.WM_CREATE: hWnd = m.LParam; break; @@ -12418,7 +14392,8 @@ private void WmParentNotify(ref Message m) { hWnd = UnsafeNativeMethods.GetDlgItem(new HandleRef(this, Handle), NativeMethods.Util.HIWORD(m.WParam)); break; } - if (hWnd == IntPtr.Zero || !ReflectMessage(hWnd, ref m)) { + if (hWnd == IntPtr.Zero || !ReflectMessage(hWnd, ref m)) + { DefWndProc(ref m); } } @@ -12426,27 +14401,33 @@ private void WmParentNotify(ref Message m) { /// /// Handles the WM_SETFOCUS message /// - private void WmSetFocus(ref Message m) { + private void WmSetFocus(ref Message m) + { Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Control::WmSetFocus - " + this.Name); WmImeSetFocus(); - if (!HostedInWin32DialogManager) { + if (!HostedInWin32DialogManager) + { IContainerControl c = GetContainerControl(); - if (c != null) { + if (c != null) + { bool activateSucceed; ContainerControl knowncontainer = c as ContainerControl; - if (knowncontainer != null) { + if (knowncontainer != null) + { activateSucceed = knowncontainer.ActivateControlInternal(this); } - else { + else + { // Reviewed : Taking focus and activating a control in response // : to a user gesture (WM_SETFOCUS) is OK. // activateSucceed = c.ActivateControl(this); } - if (!activateSucceed) { + if (!activateSucceed) + { return; } } @@ -12459,34 +14440,41 @@ private void WmSetFocus(ref Message m) { /// /// Handles the WM_SHOWWINDOW message /// - private void WmShowWindow(ref Message m) { + private void WmShowWindow(ref Message m) + { // We get this message for each control, even if their parent is not visible. DefWndProc(ref m); - if ((state & STATE_RECREATE) == 0) { + if ((state & STATE_RECREATE) == 0) + { bool visible = m.WParam != IntPtr.Zero; bool oldVisibleProperty = Visible; - if (visible) { + if (visible) + { bool oldVisibleBit = GetState(STATE_VISIBLE); SetState(STATE_VISIBLE, true); bool executedOk = false; - try { + try + { CreateControl(); executedOk = true; } - finally { - if (!executedOk) { + finally + { + if (!executedOk) + { // We do it this way instead of a try/catch because catching and rethrowing // an exception loses call stack information SetState(STATE_VISIBLE, oldVisibleBit); } } } - else { // not visible + else + { // not visible // If Windows tells us it's visible, that's pretty unambiguous. // But if it tells us it's not visible, there's more than one explanation -- // maybe the container control became invisible. So we look at the parent @@ -12494,16 +14482,19 @@ private void WmShowWindow(ref Message m) { // We do not want to update state if we are on the parking window. bool parentVisible = GetTopLevel(); - if (ParentInternal != null) { + if (ParentInternal != null) + { parentVisible = ParentInternal.Visible; } - if (parentVisible) { + if (parentVisible) + { SetState(STATE_VISIBLE, false); } } - if (!GetState(STATE_PARENTRECREATING) && (oldVisibleProperty != visible)) { + if (!GetState(STATE_PARENTRECREATING) && (oldVisibleProperty != visible)) + { OnVisibleChanged(EventArgs.Empty); } } @@ -12512,7 +14503,8 @@ private void WmShowWindow(ref Message m) { /// /// Handles the WM_UPDATEUISTATE message /// - private void WmUpdateUIState(ref Message m) { + private void WmUpdateUIState(ref Message m) + { // See "How this all works" in ShowKeyboardCues @@ -12523,26 +14515,29 @@ private void WmUpdateUIState(ref Message m) { bool keyboardInitialized = (uiCuesState & UISTATE_KEYBOARD_CUES_MASK) != 0; bool focusInitialized = (uiCuesState & UISTATE_FOCUS_CUES_MASK) != 0; - if (keyboardInitialized) { + if (keyboardInitialized) + { keyboard = ShowKeyboardCues; } - if (focusInitialized) { + if (focusInitialized) + { focus = ShowFocusCues; - } + } DefWndProc(ref m); int cmd = NativeMethods.Util.LOWORD(m.WParam); // if we're initializing, dont bother updating the uiCuesState/Firing the event. - - if (cmd == NativeMethods.UIS_INITIALIZE) { + + if (cmd == NativeMethods.UIS_INITIALIZE) + { return; } // Set in the cached value for uiCuesState... - + // Windows stores the opposite of what you would think, it has bit // flags for the "Hidden" state, the presence of this flag means its // hidden, the absence thereof means it's shown. @@ -12550,51 +14545,58 @@ private void WmUpdateUIState(ref Message m) { // When we're called here with a UIS_CLEAR and the hidden state is set // that means we want to show the accelerator. UICues UIcues = UICues.None; - if ((NativeMethods.Util.HIWORD(m.WParam) & NativeMethods.UISF_HIDEACCEL) != 0) { + if ((NativeMethods.Util.HIWORD(m.WParam) & NativeMethods.UISF_HIDEACCEL) != 0) + { // yes, clear means show. nice api, guys. // bool showKeyboard = (cmd == NativeMethods.UIS_CLEAR); - if (showKeyboard != keyboard || !keyboardInitialized ) { + if (showKeyboard != keyboard || !keyboardInitialized) + { - UIcues |= UICues.ChangeKeyboard; + UIcues |= UICues.ChangeKeyboard; // clear the old state. // - uiCuesState &= ~UISTATE_KEYBOARD_CUES_MASK; - uiCuesState |= (showKeyboard ? UISTATE_KEYBOARD_CUES_SHOW : UISTATE_KEYBOARD_CUES_HIDDEN) ; + uiCuesState &= ~UISTATE_KEYBOARD_CUES_MASK; + uiCuesState |= (showKeyboard ? UISTATE_KEYBOARD_CUES_SHOW : UISTATE_KEYBOARD_CUES_HIDDEN); } - if (showKeyboard) { - UIcues |= UICues.ShowKeyboard; - } + if (showKeyboard) + { + UIcues |= UICues.ShowKeyboard; + } } // Same deal for the Focus cues as the keyboard cues. - if ((NativeMethods.Util.HIWORD(m.WParam) & NativeMethods.UISF_HIDEFOCUS) != 0) { + if ((NativeMethods.Util.HIWORD(m.WParam) & NativeMethods.UISF_HIDEFOCUS) != 0) + { // yes, clear means show. nice api, guys. // bool showFocus = (cmd == NativeMethods.UIS_CLEAR); - if (showFocus != focus || !focusInitialized) { - UIcues |= UICues.ChangeFocus; + if (showFocus != focus || !focusInitialized) + { + UIcues |= UICues.ChangeFocus; // clear the old state. // - uiCuesState &= ~UISTATE_FOCUS_CUES_MASK; - uiCuesState |= (showFocus ? UISTATE_FOCUS_CUES_SHOW : UISTATE_FOCUS_CUES_HIDDEN) ; + uiCuesState &= ~UISTATE_FOCUS_CUES_MASK; + uiCuesState |= (showFocus ? UISTATE_FOCUS_CUES_SHOW : UISTATE_FOCUS_CUES_HIDDEN); } - if (showFocus) { - UIcues |= UICues.ShowFocus; + if (showFocus) + { + UIcues |= UICues.ShowFocus; } } // fire the UI cues state changed event. - if ((UIcues & UICues.Changed) != 0) { + if ((UIcues & UICues.Changed) != 0) + { OnChangeUICues(new UICuesEventArgs(UIcues)); Invalidate(true); } @@ -12603,15 +14605,18 @@ private void WmUpdateUIState(ref Message m) { /// /// Handles the WM_WINDOWPOSCHANGED message /// - private unsafe void WmWindowPosChanged(ref Message m) { + private unsafe void WmWindowPosChanged(ref Message m) + { DefWndProc(ref m); // Update new size / position UpdateBounds(); if (parent != null && UnsafeNativeMethods.GetParent(new HandleRef(window, InternalHandle)) == parent.InternalHandle && - (state & STATE_NOZORDER) == 0) { + (state & STATE_NOZORDER) == 0) + { - NativeMethods.WINDOWPOS* wp = (NativeMethods.WINDOWPOS *)m.LParam; - if ((wp->flags & NativeMethods.SWP_NOZORDER) == 0) { + NativeMethods.WINDOWPOS* wp = (NativeMethods.WINDOWPOS*)m.LParam; + if ((wp->flags & NativeMethods.SWP_NOZORDER) == 0) + { parent.UpdateChildControlIndex(this); } } @@ -12622,7 +14627,8 @@ private unsafe void WmWindowPosChanged(ref Message m) { /// through the preProcessMessage function. Inheriting controls should /// call base.wndProc for any messages that they don't handle. /// - protected virtual void WndProc(ref Message m) { + protected virtual void WndProc(ref Message m) + { /* if( GetState(STATE_DISPOSED)) @@ -12636,7 +14642,8 @@ protected virtual void WndProc(ref Message m) { // inlined code from GetStyle(...) to ensure no perf hit // for a method call... // - if ((controlStyle & ControlStyles.EnableNotifyMessage) == ControlStyles.EnableNotifyMessage) { + if ((controlStyle & ControlStyles.EnableNotifyMessage) == ControlStyles.EnableNotifyMessage) + { // pass message *by value* to avoid the possibility // of the OnNotifyMessage modifying the message. // @@ -12648,10 +14655,11 @@ protected virtual void WndProc(ref Message m) { * please make sure that you also modify AxHost.wndProc to do the right thing and intercept * messages which the Ocx would own before passing them onto Control.wndProc. */ - switch (m.Msg) { + switch (m.Msg) + { case Interop.WindowMessages.WM_CAPTURECHANGED: - WmCaptureChanged(ref m); - break; + WmCaptureChanged(ref m); + break; case Interop.WindowMessages.WM_GETOBJECT: WmGetObject(ref m); @@ -12660,23 +14668,23 @@ protected virtual void WndProc(ref Message m) { case Interop.WindowMessages.WM_COMMAND: WmCommand(ref m); break; - + case Interop.WindowMessages.WM_CLOSE: WmClose(ref m); break; - + case Interop.WindowMessages.WM_CONTEXTMENU: WmContextMenu(ref m); break; - + case Interop.WindowMessages.WM_DISPLAYCHANGE: WmDisplayChange(ref m); break; - + case Interop.WindowMessages.WM_DRAWITEM: WmDrawItem(ref m); break; - + case Interop.WindowMessages.WM_ERASEBKGND: WmEraseBkgnd(ref m); break; @@ -12690,19 +14698,23 @@ protected virtual void WndProc(ref Message m) { break; case Interop.WindowMessages.WM_PAINT: - if (GetStyle(ControlStyles.UserPaint)) { + if (GetStyle(ControlStyles.UserPaint)) + { WmPaint(ref m); } - else { + else + { DefWndProc(ref m); } break; case Interop.WindowMessages.WM_PRINTCLIENT: - if (GetStyle(ControlStyles.UserPaint)) { + if (GetStyle(ControlStyles.UserPaint)) + { WmPrintClient(ref m); } - else { + else + { DefWndProc(ref m); } break; @@ -12712,10 +14724,12 @@ protected virtual void WndProc(ref Message m) { break; case Interop.WindowMessages.WM_SYSCOMMAND: - if ((unchecked((int)(long)m.WParam) & 0xFFF0) == NativeMethods.SC_KEYMENU) { + if ((unchecked((int)(long)m.WParam) & 0xFFF0) == NativeMethods.SC_KEYMENU) + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "Control.WndProc processing " + m.ToString()); - if (ToolStripManager.ProcessMenuKey(ref m)) { + if (ToolStripManager.ProcessMenuKey(ref m)) + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "Control.WndProc ToolStripManager.ProcessMenuKey returned true" + m.ToString()); m.Result = IntPtr.Zero; return; @@ -12723,7 +14737,7 @@ protected virtual void WndProc(ref Message m) { } DefWndProc(ref m); break; - + case Interop.WindowMessages.WM_INPUTLANGCHANGE: WmInputLangChange(ref m); break; @@ -12735,7 +14749,7 @@ protected virtual void WndProc(ref Message m) { case Interop.WindowMessages.WM_MEASUREITEM: WmMeasureItem(ref m); break; - + case Interop.WindowMessages.WM_MENUCHAR: WmMenuChar(ref m); break; @@ -12759,11 +14773,11 @@ protected virtual void WndProc(ref Message m) { case Interop.WindowMessages.WM_SYSKEYUP: WmKeyChar(ref m); break; - + case Interop.WindowMessages.WM_CREATE: WmCreate(ref m); break; - + case Interop.WindowMessages.WM_DESTROY: WmDestroy(ref m); break; @@ -12789,179 +14803,187 @@ protected virtual void WndProc(ref Message m) { case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_CTLCOLORSCROLLBAR: case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_CTLCOLOREDIT: case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_CTLCOLORLISTBOX: - case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_CTLCOLORSTATIC: + case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_CTLCOLORSTATIC: WmCtlColorControl(ref m); break; - + case Interop.WindowMessages.WM_HSCROLL: case Interop.WindowMessages.WM_VSCROLL: case Interop.WindowMessages.WM_DELETEITEM: case Interop.WindowMessages.WM_VKEYTOITEM: case Interop.WindowMessages.WM_CHARTOITEM: case Interop.WindowMessages.WM_COMPAREITEM: - if (!ReflectMessage(m.LParam, ref m)) { + if (!ReflectMessage(m.LParam, ref m)) + { DefWndProc(ref m); } break; - + case Interop.WindowMessages.WM_IME_CHAR: WmImeChar(ref m); break; - + case Interop.WindowMessages.WM_IME_STARTCOMPOSITION: WmImeStartComposition(ref m); break; - + case Interop.WindowMessages.WM_IME_ENDCOMPOSITION: WmImeEndComposition(ref m); break; - + case Interop.WindowMessages.WM_IME_NOTIFY: WmImeNotify(ref m); break; - + case Interop.WindowMessages.WM_KILLFOCUS: WmKillFocus(ref m); break; - + case Interop.WindowMessages.WM_LBUTTONDBLCLK: WmMouseDown(ref m, MouseButtons.Left, 2); - if (GetStyle(ControlStyles.StandardDoubleClick)) { + if (GetStyle(ControlStyles.StandardDoubleClick)) + { SetState(STATE_DOUBLECLICKFIRED, true); } break; - + case Interop.WindowMessages.WM_LBUTTONDOWN: WmMouseDown(ref m, MouseButtons.Left, 1); break; - + case Interop.WindowMessages.WM_LBUTTONUP: WmMouseUp(ref m, MouseButtons.Left, 1); break; - + case Interop.WindowMessages.WM_MBUTTONDBLCLK: WmMouseDown(ref m, MouseButtons.Middle, 2); - if (GetStyle(ControlStyles.StandardDoubleClick)) { + if (GetStyle(ControlStyles.StandardDoubleClick)) + { SetState(STATE_DOUBLECLICKFIRED, true); } break; - + case Interop.WindowMessages.WM_MBUTTONDOWN: WmMouseDown(ref m, MouseButtons.Middle, 1); break; - + case Interop.WindowMessages.WM_MBUTTONUP: WmMouseUp(ref m, MouseButtons.Middle, 1); break; - + case Interop.WindowMessages.WM_XBUTTONDOWN: WmMouseDown(ref m, GetXButton(NativeMethods.Util.HIWORD(m.WParam)), 1); break; - + case Interop.WindowMessages.WM_XBUTTONUP: WmMouseUp(ref m, GetXButton(NativeMethods.Util.HIWORD(m.WParam)), 1); break; - + case Interop.WindowMessages.WM_XBUTTONDBLCLK: WmMouseDown(ref m, GetXButton(NativeMethods.Util.HIWORD(m.WParam)), 2); - if (GetStyle(ControlStyles.StandardDoubleClick)) { + if (GetStyle(ControlStyles.StandardDoubleClick)) + { SetState(STATE_DOUBLECLICKFIRED, true); } break; - + case Interop.WindowMessages.WM_MOUSELEAVE: WmMouseLeave(ref m); break; - + case Interop.WindowMessages.WM_DPICHANGED_BEFOREPARENT: WmDpiChangedBeforeParent(ref m); m.Result = IntPtr.Zero; break; - + case Interop.WindowMessages.WM_DPICHANGED_AFTERPARENT: WmDpiChangedAfterParent(ref m); m.Result = IntPtr.Zero; break; - + case Interop.WindowMessages.WM_MOUSEMOVE: WmMouseMove(ref m); break; - + case Interop.WindowMessages.WM_MOUSEWHEEL: WmMouseWheel(ref m); break; - + case Interop.WindowMessages.WM_MOVE: WmMove(ref m); break; - + case Interop.WindowMessages.WM_NOTIFY: WmNotify(ref m); break; - + case Interop.WindowMessages.WM_NOTIFYFORMAT: WmNotifyFormat(ref m); break; - + case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_NOTIFYFORMAT: m.Result = (IntPtr)(NativeMethods.NFR_UNICODE); break; - + case Interop.WindowMessages.WM_SHOWWINDOW: WmShowWindow(ref m); break; - + case Interop.WindowMessages.WM_RBUTTONDBLCLK: WmMouseDown(ref m, MouseButtons.Right, 2); - if (GetStyle(ControlStyles.StandardDoubleClick)) { + if (GetStyle(ControlStyles.StandardDoubleClick)) + { SetState(STATE_DOUBLECLICKFIRED, true); } break; - + case Interop.WindowMessages.WM_RBUTTONDOWN: WmMouseDown(ref m, MouseButtons.Right, 1); break; - + case Interop.WindowMessages.WM_RBUTTONUP: WmMouseUp(ref m, MouseButtons.Right, 1); break; - + case Interop.WindowMessages.WM_SETFOCUS: WmSetFocus(ref m); break; - + case Interop.WindowMessages.WM_MOUSEHOVER: WmMouseHover(ref m); break; - + case Interop.WindowMessages.WM_WINDOWPOSCHANGED: WmWindowPosChanged(ref m); break; - + case Interop.WindowMessages.WM_QUERYNEWPALETTE: WmQueryNewPalette(ref m); break; - + case Interop.WindowMessages.WM_UPDATEUISTATE: WmUpdateUIState(ref m); break; - + case Interop.WindowMessages.WM_PARENTNOTIFY: WmParentNotify(ref m); break; - + default: // If we received a thread execute message, then execute it. // - if (m.Msg == threadCallbackMessage && m.Msg != 0) { + if (m.Msg == threadCallbackMessage && m.Msg != 0) + { InvokeMarshaledCallbacks(); return; } - else if (m.Msg == Control.WM_GETCONTROLNAME) { + else if (m.Msg == Control.WM_GETCONTROLNAME) + { WmGetControlName(ref m); return; } - else if (m.Msg == Control.WM_GETCONTROLTYPE) { + else if (m.Msg == Control.WM_GETCONTROLTYPE) + { WmGetControlType(ref m); return; } @@ -12969,22 +14991,27 @@ protected virtual void WndProc(ref Message m) { // If we have to route the mousewheel messages, do it (this logic was taken // from the MFC sources...) // - if (mouseWheelRoutingNeeded) { - if (m.Msg == mouseWheelMessage) { + if (mouseWheelRoutingNeeded) + { + if (m.Msg == mouseWheelMessage) + { Keys keyState = Keys.None; keyState |= (Keys)((UnsafeNativeMethods.GetKeyState((int)Keys.ControlKey) < 0) ? NativeMethods.MK_CONTROL : 0); keyState |= (Keys)((UnsafeNativeMethods.GetKeyState((int)Keys.ShiftKey) < 0) ? NativeMethods.MK_SHIFT : 0); IntPtr hwndFocus = UnsafeNativeMethods.GetFocus(); - if (hwndFocus == IntPtr.Zero) { + if (hwndFocus == IntPtr.Zero) + { SendMessage(m.Msg, (IntPtr)((unchecked((int)(long)m.WParam) << 16) | (int)keyState), m.LParam); } - else { + else + { IntPtr result = IntPtr.Zero; IntPtr hwndDesktop = UnsafeNativeMethods.GetDesktopWindow(); - while (result == IntPtr.Zero && hwndFocus != IntPtr.Zero && hwndFocus != hwndDesktop) { + while (result == IntPtr.Zero && hwndFocus != IntPtr.Zero && hwndFocus != hwndDesktop) + { result = UnsafeNativeMethods.SendMessage(new HandleRef(null, hwndFocus), Interop.WindowMessages.WM_MOUSEWHEEL, (unchecked((int)(long)m.WParam) << 16) | (int)keyState, @@ -12995,7 +15022,8 @@ protected virtual void WndProc(ref Message m) { } } - if (m.Msg == NativeMethods.WM_MOUSEENTER) { + if (m.Msg == NativeMethods.WM_MOUSEENTER) + { WmMouseEnter(ref m); break; } @@ -13010,41 +15038,51 @@ protected virtual void WndProc(ref Message m) { /// Called when an exception occurs in dispatching messages through /// the main window procedure. /// - private void WndProcException(Exception e) { + private void WndProcException(Exception e) + { Application.OnThreadException(e); } - ArrangedElementCollection IArrangedElement.Children { - get { + ArrangedElementCollection IArrangedElement.Children + { + get + { ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection == null) { + if (controlsCollection == null) + { return ArrangedElementCollection.Empty; } return controlsCollection; } } - IArrangedElement IArrangedElement.Container { - get { + IArrangedElement IArrangedElement.Container + { + get + { // This is safe because the IArrangedElement interface is internal return ParentInternal; } } - bool IArrangedElement.ParticipatesInLayout { + bool IArrangedElement.ParticipatesInLayout + { get { return GetState(STATE_VISIBLE); } } - void IArrangedElement.PerformLayout(IArrangedElement affectedElement, string affectedProperty) { + void IArrangedElement.PerformLayout(IArrangedElement affectedElement, string affectedProperty) + { PerformLayout(new LayoutEventArgs(affectedElement, affectedProperty)); } - PropertyStore IArrangedElement.Properties { + PropertyStore IArrangedElement.Properties + { get { return Properties; } } // CAREFUL: This really calls SetBoundsCore, not SetBounds. - void IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) { + void IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) + { ISite site = Site; IComponentChangeService ccs = null; PropertyDescriptor sizeProperty = null; @@ -13052,22 +15090,27 @@ void IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) { bool sizeChanged = false; bool locationChanged = false; - if (site != null && site.DesignMode) { + if (site != null && site.DesignMode) + { ccs = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); - if(ccs != null) { + if (ccs != null) + { sizeProperty = TypeDescriptor.GetProperties(this)[PropertyNames.Size]; locationProperty = TypeDescriptor.GetProperties(this)[PropertyNames.Location]; Debug.Assert(sizeProperty != null && locationProperty != null, "Error retrieving Size/Location properties on Control."); - try { - if (sizeProperty != null && !sizeProperty.IsReadOnly && (bounds.Width != this.Width || bounds.Height != this.Height)) { + try + { + if (sizeProperty != null && !sizeProperty.IsReadOnly && (bounds.Width != this.Width || bounds.Height != this.Height)) + { if (!(site is INestedSite)) { ccs.OnComponentChanging(this, sizeProperty); } sizeChanged = true; } - if (locationProperty != null && !locationProperty.IsReadOnly && (bounds.X != this.x || bounds.Y != this.y)) { + if (locationProperty != null && !locationProperty.IsReadOnly && (bounds.X != this.x || bounds.Y != this.y)) + { if (!(site is INestedSite)) { ccs.OnComponentChanging(this, locationProperty); @@ -13075,7 +15118,8 @@ void IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) { locationChanged = true; } } - catch (InvalidOperationException) { + catch (InvalidOperationException) + { // The component change events can throw InvalidOperationException if a change is // currently not allowed (typically because the doc data in VS is locked). // When this happens, we just eat the exception and proceed with the change. @@ -13085,15 +15129,20 @@ void IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) { SetBoundsCore(bounds.X, bounds.Y, bounds.Width, bounds.Height, specified); - if (site != null && ccs != null) { - try { - if (sizeChanged) ccs.OnComponentChanged(this, sizeProperty, null, null); - if (locationChanged) ccs.OnComponentChanged(this, locationProperty, null, null); + if (site != null && ccs != null) + { + try + { + if (sizeChanged) + ccs.OnComponentChanged(this, sizeProperty, null, null); + if (locationChanged) + ccs.OnComponentChanged(this, locationProperty, null, null); } - catch (InvalidOperationException) { - // The component change events can throw InvalidOperationException if a change is - // currently not allowed (typically because the doc data in VS is locked). - // When this happens, we just eat the exception and proceed with the change. + catch (InvalidOperationException) + { + // The component change events can throw InvalidOperationException if a change is + // currently not allowed (typically because the doc data in VS is locked). + // When this happens, we just eat the exception and proceed with the change. } } } @@ -13102,98 +15151,122 @@ void IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) { /// Indicates whether or not the control supports UIA Providers via /// IRawElementProviderFragment/IRawElementProviderFragmentRoot interfaces /// - internal virtual bool SupportsUiaProviders { - get { + internal virtual bool SupportsUiaProviders + { + get + { return false; } } - + /// /// - internal sealed class ControlNativeWindow : NativeWindow, IWindowTarget { - private Control control; - private GCHandle rootRef; // We will root the control when we do not want to be elligible for garbage collection. - internal IWindowTarget target; + internal sealed class ControlNativeWindow : NativeWindow, IWindowTarget + { + private Control control; + private GCHandle rootRef; // We will root the control when we do not want to be elligible for garbage collection. + internal IWindowTarget target; - internal ControlNativeWindow(Control control) { + internal ControlNativeWindow(Control control) + { this.control = control; target = this; } - internal Control GetControl() { + internal Control GetControl() + { return control; - } - - protected override void OnHandleChange() { + } + + protected override void OnHandleChange() + { target.OnHandleChange(this.Handle); } // IWindowTarget method - public void OnHandleChange(IntPtr newHandle) { + public void OnHandleChange(IntPtr newHandle) + { control.SetHandle(newHandle); } - internal void LockReference(bool locked) { - if (locked) { - if (!rootRef.IsAllocated) { + internal void LockReference(bool locked) + { + if (locked) + { + if (!rootRef.IsAllocated) + { rootRef = GCHandle.Alloc(GetControl(), GCHandleType.Normal); } } - else { - if (rootRef.IsAllocated) { + else + { + if (rootRef.IsAllocated) + { rootRef.Free(); } } } - protected override void OnThreadException(Exception e) { + protected override void OnThreadException(Exception e) + { control.WndProcException(e); } // IWindowTarget method - public void OnMessage(ref Message m) { + public void OnMessage(ref Message m) + { control.WndProc(ref m); } - internal IWindowTarget WindowTarget { - get { + internal IWindowTarget WindowTarget + { + get + { return target; } - set { + set + { target = value; } } - #if DEBUG +#if DEBUG // We override ToString so in debug asserts that fire for // non-released controls will show what control wasn't released. // - public override string ToString() { - if (control != null) { + public override string ToString() + { + if (control != null) + { return control.GetType().FullName; } return base.ToString(); } - #endif +#endif - protected override void WndProc(ref Message m) { + protected override void WndProc(ref Message m) + { // There are certain messages that we want to process // regardless of what window target we are using. These // messages cause other messages or state transitions // to occur within control. // - switch (m.Msg) { + switch (m.Msg) + { case Interop.WindowMessages.WM_MOUSELEAVE: control.UnhookMouseEvent(); break; case Interop.WindowMessages.WM_MOUSEMOVE: - if (!control.GetState(Control.STATE_TRACKINGMOUSEEVENT)) { + if (!control.GetState(Control.STATE_TRACKINGMOUSEEVENT)) + { control.HookMouseEvent(); - if (!control.GetState(Control.STATE_MOUSEENTERPENDING)) { + if (!control.GetState(Control.STATE_MOUSEENTERPENDING)) + { control.SendMessage(NativeMethods.WM_MOUSEENTER, 0, 0); } - else { + else + { control.SetState(Control.STATE_MOUSEENTERPENDING, false); } } @@ -13204,7 +15277,7 @@ protected override void WndProc(ref Message m) { // correctly... // control.ResetMouseEventArgs(); - break; + break; } target.OnMessage(ref m); @@ -13214,38 +15287,45 @@ protected override void WndProc(ref Message m) { /// /// Explicit support of DropTarget /// - void IDropTarget.OnDragEnter(DragEventArgs drgEvent) { - OnDragEnter(drgEvent); + void IDropTarget.OnDragEnter(DragEventArgs drgEvent) + { + OnDragEnter(drgEvent); } - - void IDropTarget.OnDragOver(DragEventArgs drgEvent) { - OnDragOver(drgEvent); + + void IDropTarget.OnDragOver(DragEventArgs drgEvent) + { + OnDragOver(drgEvent); } - - void IDropTarget.OnDragLeave(EventArgs e) { - OnDragLeave(e); + + void IDropTarget.OnDragLeave(EventArgs e) + { + OnDragLeave(e); } - - void IDropTarget.OnDragDrop(DragEventArgs drgEvent) { - OnDragDrop(drgEvent); + + void IDropTarget.OnDragDrop(DragEventArgs drgEvent) + { + OnDragDrop(drgEvent); } /// /// Explicit support of DropSource /// - void ISupportOleDropSource.OnGiveFeedback(GiveFeedbackEventArgs giveFeedbackEventArgs) { - OnGiveFeedback(giveFeedbackEventArgs); + void ISupportOleDropSource.OnGiveFeedback(GiveFeedbackEventArgs giveFeedbackEventArgs) + { + OnGiveFeedback(giveFeedbackEventArgs); } - - void ISupportOleDropSource.OnQueryContinueDrag(QueryContinueDragEventArgs queryContinueDragEventArgs) { - OnQueryContinueDrag(queryContinueDragEventArgs); + + void ISupportOleDropSource.OnQueryContinueDrag(QueryContinueDragEventArgs queryContinueDragEventArgs) + { + OnQueryContinueDrag(queryContinueDragEventArgs); } /// /// Collection of controls... /// [ListBindable(false), ComVisible(false)] - public class ControlCollection : ArrangedElementCollection, IList, ICloneable { + public class ControlCollection : ArrangedElementCollection, IList, ICloneable + { private Control owner; @@ -13256,15 +15336,17 @@ public class ControlCollection : ArrangedElementCollection, IList, ICloneable { private int lastAccessedIndex = -1; - public ControlCollection(Control owner) { + public ControlCollection(Control owner) + { this.owner = owner; } /// /// Returns true if the collection contains an item with the specified key, false otherwise. /// - public virtual bool ContainsKey(string key) { - return IsValidIndex(IndexOfKey(key)); + public virtual bool ContainsKey(string key) + { + return IsValidIndex(IndexOfKey(key)); } /// @@ -13272,30 +15354,35 @@ public virtual bool ContainsKey(string key) { /// the child control list. If the control is already a child of another control it /// is first removed from that control. /// - public virtual void Add(Control value) { + public virtual void Add(Control value) + { if (value == null) return; - if (value.GetTopLevel()) { + if (value.GetTopLevel()) + { throw new ArgumentException(SR.TopLevelControlAdd); } // Verify that the control being added is on the same thread as // us...or our parent chain. // - if (owner.CreateThreadId != value.CreateThreadId) { + if (owner.CreateThreadId != value.CreateThreadId) + { throw new ArgumentException(SR.AddDifferentThreads); } CheckParentingCycle(owner, value); - if (value.parent == owner) { + if (value.parent == owner) + { value.SendToBack(); return; } // Remove the new control from its old parent (if any) // - if (value.parent != null) { + if (value.parent != null) + { value.parent.Controls.Remove(value); } @@ -13303,14 +15390,17 @@ public virtual void Add(Control value) { // InnerList.Add(value); - if (value.tabIndex == -1) { + if (value.tabIndex == -1) + { // Find the next highest tab index // int nextTabIndex = 0; - for (int c = 0; c < (Count - 1); c++) { + for (int c = 0; c < (Count - 1); c++) + { int t = this[c].TabIndex; - if (nextTabIndex <= t) { + if (nextTabIndex <= t) + { nextTabIndex = t + 1; } } @@ -13325,18 +15415,23 @@ public virtual void Add(Control value) { #endif owner.SuspendLayout(); - try { + try + { Control oldParent = value.parent; - try { + try + { // AssignParent calls into user code - this could throw, which // would make us short-circuit the rest of the reparenting logic. // you could end up with a control half reparented. value.AssignParent(owner); } - finally { - if (oldParent != value.parent && (owner.state & STATE_CREATED) != 0) { + finally + { + if (oldParent != value.parent && (owner.state & STATE_CREATED) != 0) + { value.SetParentHandle(owner.InternalHandle); - if (value.Visible) { + if (value.Visible) + { value.CreateControl(); } } @@ -13344,12 +15439,13 @@ public virtual void Add(Control value) { value.InitLayout(); } - finally { + finally + { owner.ResumeLayout(false); #if DEBUG owner.AssertLayoutSuspendCount(dbgLayoutCheck); #endif - + } // Not putting in the finally block, as it would eat the original @@ -13358,32 +15454,41 @@ public virtual void Add(Control value) { owner.OnControlAdded(new ControlEventArgs(value)); } - int IList.Add(object control) { - if (control is Control) { + int IList.Add(object control) + { + if (control is Control) + { Add((Control)control); return IndexOf((Control)control); } - else { + else + { throw new ArgumentException(SR.ControlBadControl, "control"); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public virtual void AddRange(Control[] controls) { - if (controls == null) { + public virtual void AddRange(Control[] controls) + { + if (controls == null) + { throw new ArgumentNullException(nameof(controls)); } - if (controls.Length > 0) { + if (controls.Length > 0) + { #if DEBUG int dbgLayoutCheck = owner.LayoutSuspendCount; #endif owner.SuspendLayout(); - try { - for(int i=0;i < controls.Length; ++i) { + try + { + for (int i = 0; i < controls.Length; ++i) + { Add(controls[i]); } } - finally { + finally + { owner.ResumeLayout(true); } #if DEBUG @@ -13392,7 +15497,8 @@ public virtual void AddRange(Control[] controls) { } } - object ICloneable.Clone() { + object ICloneable.Clone() + { // Use CreateControlInstance so we get the same type of ControlCollection, but whack the // owner so adding controls to this new collection does not affect the control we cloned from. ControlCollection ccOther = owner.CreateControlsInstance(); @@ -13402,7 +15508,8 @@ object ICloneable.Clone() { return ccOther; } - public bool Contains(Control control) { + public bool Contains(Control control) + { return InnerList.Contains(control); } @@ -13411,12 +15518,14 @@ public bool Contains(Control control) { /// of all the controls that match. /// /// - public Control[] Find(string key, bool searchAllChildren) { - if (string.IsNullOrEmpty(key)) { - throw new System.ArgumentNullException(nameof(key), SR.FindKeyMayNotBeEmptyOrNull); + public Control[] Find(string key, bool searchAllChildren) + { + if (string.IsNullOrEmpty(key)) + { + throw new System.ArgumentNullException(nameof(key), SR.FindKeyMayNotBeEmptyOrNull); } - ArrayList foundControls = FindInternal(key, searchAllChildren, this, new ArrayList()); + ArrayList foundControls = FindInternal(key, searchAllChildren, this, new ArrayList()); // Make this a stongly typed collection. Control[] stronglyTypedFoundControls = new Control[foundControls.Count]; @@ -13430,75 +15539,94 @@ public Control[] Find(string key, bool searchAllChildren) { /// of all the controls that match. /// /// - private ArrayList FindInternal(string key, bool searchAllChildren, ControlCollection controlsToLookIn, ArrayList foundControls) { - if ((controlsToLookIn == null) || (foundControls == null)) { + private ArrayList FindInternal(string key, bool searchAllChildren, ControlCollection controlsToLookIn, ArrayList foundControls) + { + if ((controlsToLookIn == null) || (foundControls == null)) + { return null; } - try { + try + { // Perform breadth first search - as it's likely people will want controls belonging // to the same parent close to each other. - for (int i = 0; i < controlsToLookIn.Count; i++) { - if (controlsToLookIn[i] == null){ - continue; - } + for (int i = 0; i < controlsToLookIn.Count; i++) + { + if (controlsToLookIn[i] == null) + { + continue; + } - if (WindowsFormsUtils.SafeCompareStrings(controlsToLookIn[i].Name, key, /* ignoreCase = */ true)) { - foundControls.Add(controlsToLookIn[i]); - } + if (WindowsFormsUtils.SafeCompareStrings(controlsToLookIn[i].Name, key, /* ignoreCase = */ true)) + { + foundControls.Add(controlsToLookIn[i]); + } } // Optional recurive search for controls in child collections. - if (searchAllChildren){ - for (int i = 0; i < controlsToLookIn.Count; i++) { - if (controlsToLookIn[i] == null){ + if (searchAllChildren) + { + for (int i = 0; i < controlsToLookIn.Count; i++) + { + if (controlsToLookIn[i] == null) + { continue; } - if ((controlsToLookIn[i].Controls != null) && controlsToLookIn[i].Controls.Count > 0){ + if ((controlsToLookIn[i].Controls != null) && controlsToLookIn[i].Controls.Count > 0) + { // if it has a valid child collecion, append those results to our collection foundControls = FindInternal(key, searchAllChildren, controlsToLookIn[i].Controls, foundControls); } } } } - catch (Exception e) { - if (ClientUtils.IsSecurityOrCriticalException(e)) { + catch (Exception e) + { + if (ClientUtils.IsSecurityOrCriticalException(e)) + { throw; } } return foundControls; } - - public override IEnumerator GetEnumerator() { - return new ControlCollectionEnumerator(this); + + public override IEnumerator GetEnumerator() + { + return new ControlCollectionEnumerator(this); } - public int IndexOf(Control control) { + public int IndexOf(Control control) + { return InnerList.IndexOf(control); } /// /// The zero-based index of the first occurrence of value within the entire CollectionBase, if found; otherwise, -1. /// - public virtual int IndexOfKey(string key) { + public virtual int IndexOfKey(string key) + { // Step 0 - Arg validation - if (string.IsNullOrEmpty(key)) { + if (string.IsNullOrEmpty(key)) + { return -1; // we dont support empty or null keys. } // step 1 - check the last cached item if (IsValidIndex(lastAccessedIndex)) { - if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) { + if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) + { return lastAccessedIndex; } } // step 2 - search for the item - for (int i = 0; i < this.Count; i ++) { - if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { + for (int i = 0; i < this.Count; i++) + { + if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) + { lastAccessedIndex = i; return i; } @@ -13512,15 +15640,18 @@ public virtual int IndexOfKey(string key) { /// /// Determines if the index is valid for the collection. /// - private bool IsValidIndex(int index) { + private bool IsValidIndex(int index) + { return ((index >= 0) && (index < this.Count)); } /// /// Who owns this control collection. /// - public Control Owner { - get { + public Control Owner + { + get + { return owner; } } @@ -13529,15 +15660,18 @@ public Control Owner { /// Removes control from this control. Inheriting controls should call /// base.remove to ensure that the control is removed. /// - public virtual void Remove(Control value) { + public virtual void Remove(Control value) + { // Sanity check parameter // - if (value == null) { + if (value == null) + { return; // Don't do anything } - if (value.ParentInternal == owner) { + if (value.ParentInternal == owner) + { Debug.Assert(owner != null); value.SetParentHandle(IntPtr.Zero); @@ -13558,22 +15692,27 @@ public virtual void Remove(Control value) { } } - void IList.Remove(object control) { - if (control is Control) { + void IList.Remove(object control) + { + if (control is Control) + { Remove((Control)control); } } - public void RemoveAt(int index) { + public void RemoveAt(int index) + { Remove(this[index]); } /// /// Removes the child control with the specified key. /// - public virtual void RemoveByKey(string key) { + public virtual void RemoveByKey(string key) + { int index = IndexOfKey(key); - if (IsValidIndex(index)) { + if (IsValidIndex(index)) + { RemoveAt(index); } } @@ -13581,14 +15720,17 @@ public virtual void RemoveByKey(string key) { /// /// Retrieves the child control with the specified index. /// - public new virtual Control this[int index] { - get { + public new virtual Control this[int index] + { + get + { //do some bounds checking here... - if (index < 0 || index >= Count) { + if (index < 0 || index >= Count) + { throw new ArgumentOutOfRangeException(nameof(index), string.Format(SR.IndexOutOfRange, index.ToString(CultureInfo.CurrentCulture))); } - Control control = (Control) InnerList[index]; + Control control = (Control)InnerList[index]; Debug.Assert(control != null, "Why are we returning null controls from a valid index?"); return control; } @@ -13597,26 +15739,32 @@ public virtual void RemoveByKey(string key) { /// /// Retrieves the child control with the specified key. /// - public virtual Control this[string key] { - get { + public virtual Control this[string key] + { + get + { // We do not support null and empty string as valid keys. - if (string.IsNullOrEmpty(key)) { + if (string.IsNullOrEmpty(key)) + { return null; } // Search for the key in our collection int index = IndexOfKey(key); - if (IsValidIndex(index)) { + if (IsValidIndex(index)) + { return this[index]; } - else { + else + { return null; } } } - public virtual void Clear() { + public virtual void Clear() + { #if DEBUG int layoutSuspendCount = owner.LayoutSuspendCount; #endif @@ -13625,10 +15773,13 @@ public virtual void Clear() { // inherited fonts could go away, etc. CommonProperties.xClearAllPreferredSizeCaches(owner); - try { + try + { while (Count != 0) RemoveAt(Count - 1); - } finally { + } + finally + { owner.ResumeLayout(); #if DEBUG Debug.Assert(owner.LayoutSuspendCount == layoutSuspendCount, "Suspend/Resume layout mismatch!"); @@ -13642,7 +15793,8 @@ public virtual void Clear() { /// is thrown if child is not parented to this /// Control. /// - public int GetChildIndex(Control child) { + public int GetChildIndex(Control child) + { return GetChildIndex(child, true); } @@ -13652,9 +15804,11 @@ public int GetChildIndex(Control child) { /// is thrown if child is not parented to this /// Control. /// - public virtual int GetChildIndex(Control child, bool throwException) { + public virtual int GetChildIndex(Control child, bool throwException) + { int index = IndexOf(child); - if (index == -1 && throwException) { + if (index == -1 && throwException) + { throw new ArgumentException(SR.ControlNotChild); } return index; @@ -13668,17 +15822,20 @@ internal virtual void SetChildIndexInternal(Control child, int newIndex) { // Sanity check parameters // - if (child == null) { + if (child == null) + { throw new ArgumentNullException(nameof(child)); } int currentIndex = GetChildIndex(child); - if (currentIndex == newIndex) { + if (currentIndex == newIndex) + { return; } - if (newIndex >= Count || newIndex == -1) { + if (newIndex >= Count || newIndex == -1) + { newIndex = Count - 1; } @@ -13695,25 +15852,29 @@ internal virtual void SetChildIndexInternal(Control child, int newIndex) /// is thrown if child is not parented to this /// Control. /// - public virtual void SetChildIndex(Control child, int newIndex) { + public virtual void SetChildIndex(Control child, int newIndex) + { SetChildIndexInternal(child, newIndex); } // This is the same as WinformsUtils.ArraySubsetEnumerator // however since we're no longer an array, we've gotta employ a // special version of this. - private class ControlCollectionEnumerator : IEnumerator { - private ControlCollection controls; + private class ControlCollectionEnumerator : IEnumerator + { + private ControlCollection controls; private int current; private int originalCount; - - public ControlCollectionEnumerator(ControlCollection controls) { + + public ControlCollectionEnumerator(ControlCollection controls) + { this.controls = controls; this.originalCount = controls.Count; current = -1; } - - public bool MoveNext() { + + public bool MoveNext() + { // We have to use Controls.Count here because someone could have deleted // an item from the array. // @@ -13725,25 +15886,32 @@ public bool MoveNext() { // this can happen if someone does // foreach (Control c in Controls) { c.Controls.Add(new Label()); } - if (current < controls.Count - 1 && current < originalCount - 1) { + if (current < controls.Count - 1 && current < originalCount - 1) + { current++; return true; } - else { + else + { return false; } } - - public void Reset() { + + public void Reset() + { current = -1; } - public object Current { - get { - if (current == -1) { + public object Current + { + get + { + if (current == -1) + { return null; } - else { + else + { return controls[current]; } } @@ -13754,7 +15922,8 @@ public object Current { /// /// - int UnsafeNativeMethods.IOleControl.GetControlInfo(NativeMethods.tagCONTROLINFO pCI) { + int UnsafeNativeMethods.IOleControl.GetControlInfo(NativeMethods.tagCONTROLINFO pCI) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:GetControlInfo"); pCI.cb = Marshal.SizeOf(); @@ -13762,10 +15931,12 @@ int UnsafeNativeMethods.IOleControl.GetControlInfo(NativeMethods.tagCONTROLINFO pCI.cAccel = 0; pCI.dwFlags = 0; - if (IsInputKey(Keys.Return)) { + if (IsInputKey(Keys.Return)) + { pCI.dwFlags |= NativeMethods.CTRLINFO_EATS_RETURN; } - if (IsInputKey(Keys.Escape)) { + if (IsInputKey(Keys.Escape)) + { pCI.dwFlags |= NativeMethods.CTRLINFO_EATS_ESCAPE; } @@ -13775,7 +15946,8 @@ int UnsafeNativeMethods.IOleControl.GetControlInfo(NativeMethods.tagCONTROLINFO /// /// - int UnsafeNativeMethods.IOleControl.OnMnemonic(ref NativeMethods.MSG pMsg) { + int UnsafeNativeMethods.IOleControl.OnMnemonic(ref NativeMethods.MSG pMsg) + { // If we got a mnemonic here, then the appropriate control will focus itself which // will cause us to become UI active. @@ -13787,7 +15959,8 @@ int UnsafeNativeMethods.IOleControl.OnMnemonic(ref NativeMethods.MSG pMsg) { /// /// - int UnsafeNativeMethods.IOleControl.OnAmbientPropertyChange(int dispID) { + int UnsafeNativeMethods.IOleControl.OnAmbientPropertyChange(int dispID) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:OnAmbientPropertyChange. Dispid: " + dispID); Debug.Indent(); ActiveXInstance.OnAmbientPropertyChange(dispID); @@ -13797,7 +15970,8 @@ int UnsafeNativeMethods.IOleControl.OnAmbientPropertyChange(int dispID) { /// /// - int UnsafeNativeMethods.IOleControl.FreezeEvents(int bFreeze) { + int UnsafeNativeMethods.IOleControl.FreezeEvents(int bFreeze) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:FreezeEvents. Freeze: " + bFreeze); ActiveXInstance.EventsFrozen = (bFreeze != 0); Debug.Assert(ActiveXInstance.EventsFrozen == (bFreeze != 0), "Failed to set EventsFrozen correctly"); @@ -13806,25 +15980,29 @@ int UnsafeNativeMethods.IOleControl.FreezeEvents(int bFreeze) { /// /// - int UnsafeNativeMethods.IOleInPlaceActiveObject.GetWindow(out IntPtr hwnd) { - return((UnsafeNativeMethods.IOleInPlaceObject)this).GetWindow(out hwnd); + int UnsafeNativeMethods.IOleInPlaceActiveObject.GetWindow(out IntPtr hwnd) + { + return ((UnsafeNativeMethods.IOleInPlaceObject)this).GetWindow(out hwnd); } /// /// - void UnsafeNativeMethods.IOleInPlaceActiveObject.ContextSensitiveHelp(int fEnterMode) { + void UnsafeNativeMethods.IOleInPlaceActiveObject.ContextSensitiveHelp(int fEnterMode) + { ((UnsafeNativeMethods.IOleInPlaceObject)this).ContextSensitiveHelp(fEnterMode); } /// /// - int UnsafeNativeMethods.IOleInPlaceActiveObject.TranslateAccelerator(ref NativeMethods.MSG lpmsg) { + int UnsafeNativeMethods.IOleInPlaceActiveObject.TranslateAccelerator(ref NativeMethods.MSG lpmsg) + { return ActiveXInstance.TranslateAccelerator(ref lpmsg); } /// /// - void UnsafeNativeMethods.IOleInPlaceActiveObject.OnFrameWindowActivate(bool fActivate) { + void UnsafeNativeMethods.IOleInPlaceActiveObject.OnFrameWindowActivate(bool fActivate) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:OnFrameWindowActivate"); OnFrameWindowActivate(fActivate); // return NativeMethods.S_OK; @@ -13832,7 +16010,8 @@ void UnsafeNativeMethods.IOleInPlaceActiveObject.OnFrameWindowActivate(bool fAct /// /// - void UnsafeNativeMethods.IOleInPlaceActiveObject.OnDocWindowActivate(int fActivate) { + void UnsafeNativeMethods.IOleInPlaceActiveObject.OnDocWindowActivate(int fActivate) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:OnDocWindowActivate. Activate: " + fActivate.ToString(CultureInfo.InvariantCulture)); Debug.Indent(); ActiveXInstance.OnDocWindowActivate(fActivate); @@ -13841,21 +16020,24 @@ void UnsafeNativeMethods.IOleInPlaceActiveObject.OnDocWindowActivate(int fActiva /// /// - void UnsafeNativeMethods.IOleInPlaceActiveObject.ResizeBorder(NativeMethods.COMRECT prcBorder, UnsafeNativeMethods.IOleInPlaceUIWindow pUIWindow, bool fFrameWindow) { + void UnsafeNativeMethods.IOleInPlaceActiveObject.ResizeBorder(NativeMethods.COMRECT prcBorder, UnsafeNativeMethods.IOleInPlaceUIWindow pUIWindow, bool fFrameWindow) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:ResizesBorder"); // return NativeMethods.S_OK; } /// /// - void UnsafeNativeMethods.IOleInPlaceActiveObject.EnableModeless(int fEnable) { + void UnsafeNativeMethods.IOleInPlaceActiveObject.EnableModeless(int fEnable) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:EnableModeless"); // return NativeMethods.S_OK; } /// /// - int UnsafeNativeMethods.IOleInPlaceObject.GetWindow(out IntPtr hwnd) { + int UnsafeNativeMethods.IOleInPlaceObject.GetWindow(out IntPtr hwnd) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:GetWindow"); int hr = ActiveXInstance.GetWindow(out hwnd); Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "\twin == " + hwnd); @@ -13864,16 +16046,19 @@ int UnsafeNativeMethods.IOleInPlaceObject.GetWindow(out IntPtr hwnd) { /// /// - void UnsafeNativeMethods.IOleInPlaceObject.ContextSensitiveHelp(int fEnterMode) { + void UnsafeNativeMethods.IOleInPlaceObject.ContextSensitiveHelp(int fEnterMode) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:ContextSensitiveHelp. Mode: " + fEnterMode.ToString(CultureInfo.InvariantCulture)); - if (fEnterMode != 0) { + if (fEnterMode != 0) + { OnHelpRequested(new HelpEventArgs(Control.MousePosition)); } } /// /// - void UnsafeNativeMethods.IOleInPlaceObject.InPlaceDeactivate() { + void UnsafeNativeMethods.IOleInPlaceObject.InPlaceDeactivate() + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:InPlaceDeactivate"); Debug.Indent(); ActiveXInstance.InPlaceDeactivate(); @@ -13882,14 +16067,16 @@ void UnsafeNativeMethods.IOleInPlaceObject.InPlaceDeactivate() { /// /// - int UnsafeNativeMethods.IOleInPlaceObject.UIDeactivate() { + int UnsafeNativeMethods.IOleInPlaceObject.UIDeactivate() + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:UIDeactivate"); return ActiveXInstance.UIDeactivate(); } /// /// - void UnsafeNativeMethods.IOleInPlaceObject.SetObjectRects(NativeMethods.COMRECT lprcPosRect, NativeMethods.COMRECT lprcClipRect) { + void UnsafeNativeMethods.IOleInPlaceObject.SetObjectRects(NativeMethods.COMRECT lprcPosRect, NativeMethods.COMRECT lprcClipRect) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:SetObjectRects(" + lprcClipRect.left + ", " + lprcClipRect.top + ", " + lprcClipRect.right + ", " + lprcClipRect.bottom + ")"); Debug.Indent(); ActiveXInstance.SetObjectRects(lprcPosRect, lprcClipRect); @@ -13898,14 +16085,16 @@ void UnsafeNativeMethods.IOleInPlaceObject.SetObjectRects(NativeMethods.COMRECT /// /// - void UnsafeNativeMethods.IOleInPlaceObject.ReactivateAndUndo() { + void UnsafeNativeMethods.IOleInPlaceObject.ReactivateAndUndo() + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:ReactivateAndUndo"); // return NativeMethods.S_OK; } /// /// - int UnsafeNativeMethods.IOleObject.SetClientSite(UnsafeNativeMethods.IOleClientSite pClientSite) { + int UnsafeNativeMethods.IOleObject.SetClientSite(UnsafeNativeMethods.IOleClientSite pClientSite) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:SetClientSite"); ActiveXInstance.SetClientSite(pClientSite); return NativeMethods.S_OK; @@ -13913,14 +16102,16 @@ int UnsafeNativeMethods.IOleObject.SetClientSite(UnsafeNativeMethods.IOleClientS /// /// - UnsafeNativeMethods.IOleClientSite UnsafeNativeMethods.IOleObject.GetClientSite() { + UnsafeNativeMethods.IOleClientSite UnsafeNativeMethods.IOleObject.GetClientSite() + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:GetClientSite"); return ActiveXInstance.GetClientSite(); } /// /// - int UnsafeNativeMethods.IOleObject.SetHostNames(string szContainerApp, string szContainerObj) { + int UnsafeNativeMethods.IOleObject.SetHostNames(string szContainerApp, string szContainerObj) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:SetHostNames"); // Since ActiveX controls never "open" for editing, we shouldn't need // to store these. @@ -13929,7 +16120,8 @@ int UnsafeNativeMethods.IOleObject.SetHostNames(string szContainerApp, string sz /// /// - int UnsafeNativeMethods.IOleObject.Close(int dwSaveOption) { + int UnsafeNativeMethods.IOleObject.Close(int dwSaveOption) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:Close. Save option: " + dwSaveOption); ActiveXInstance.Close(dwSaveOption); return NativeMethods.S_OK; @@ -13937,14 +16129,16 @@ int UnsafeNativeMethods.IOleObject.Close(int dwSaveOption) { /// /// - int UnsafeNativeMethods.IOleObject.SetMoniker(int dwWhichMoniker, object pmk) { + int UnsafeNativeMethods.IOleObject.SetMoniker(int dwWhichMoniker, object pmk) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:SetMoniker"); return NativeMethods.E_NOTIMPL; } /// /// - int UnsafeNativeMethods.IOleObject.GetMoniker(int dwAssign, int dwWhichMoniker, out object moniker) { + int UnsafeNativeMethods.IOleObject.GetMoniker(int dwAssign, int dwWhichMoniker, out object moniker) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:GetMoniker"); moniker = null; return NativeMethods.E_NOTIMPL; @@ -13952,14 +16146,16 @@ int UnsafeNativeMethods.IOleObject.GetMoniker(int dwAssign, int dwWhichMoniker, /// /// - int UnsafeNativeMethods.IOleObject.InitFromData(IComDataObject pDataObject, int fCreation, int dwReserved) { + int UnsafeNativeMethods.IOleObject.InitFromData(IComDataObject pDataObject, int fCreation, int dwReserved) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:InitFromData"); return NativeMethods.E_NOTIMPL; } /// /// - int UnsafeNativeMethods.IOleObject.GetClipboardData(int dwReserved, out IComDataObject data) { + int UnsafeNativeMethods.IOleObject.GetClipboardData(int dwReserved, out IComDataObject data) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:GetClipboardData"); data = null; return NativeMethods.E_NOTIMPL; @@ -13967,7 +16163,8 @@ int UnsafeNativeMethods.IOleObject.GetClipboardData(int dwReserved, out IComData /// /// - int UnsafeNativeMethods.IOleObject.DoVerb(int iVerb, IntPtr lpmsg, UnsafeNativeMethods.IOleClientSite pActiveSite, int lindex, IntPtr hwndParent, NativeMethods.COMRECT lprcPosRect) { + int UnsafeNativeMethods.IOleObject.DoVerb(int iVerb, IntPtr lpmsg, UnsafeNativeMethods.IOleClientSite pActiveSite, int lindex, IntPtr hwndParent, NativeMethods.COMRECT lprcPosRect) + { // In Office they are internally casting an iverb to a short and not // doing the proper sign extension. So, we do it here. @@ -13976,7 +16173,8 @@ int UnsafeNativeMethods.IOleObject.DoVerb(int iVerb, IntPtr lpmsg, UnsafeNativeM iVerb = (int)sVerb; #if DEBUG - if (CompModSwitches.ActiveX.TraceInfo) { + if (CompModSwitches.ActiveX.TraceInfo) + { Debug.WriteLine("AxSource:DoVerb {"); Debug.WriteLine(" verb: " + iVerb); Debug.WriteLine(" msg: " + lpmsg); @@ -13987,14 +16185,17 @@ int UnsafeNativeMethods.IOleObject.DoVerb(int iVerb, IntPtr lpmsg, UnsafeNativeM } #endif Debug.Indent(); - try { + try + { ActiveXInstance.DoVerb(iVerb, lpmsg, pActiveSite, lindex, hwndParent, lprcPosRect); } - catch (Exception e) { + catch (Exception e) + { Debug.Fail("Exception occurred during DoVerb(" + iVerb + ") " + e.ToString()); throw; } - finally { + finally + { Debug.Unindent(); Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "}"); } @@ -14003,28 +16204,32 @@ int UnsafeNativeMethods.IOleObject.DoVerb(int iVerb, IntPtr lpmsg, UnsafeNativeM /// /// - int UnsafeNativeMethods.IOleObject.EnumVerbs(out UnsafeNativeMethods.IEnumOLEVERB e) { + int UnsafeNativeMethods.IOleObject.EnumVerbs(out UnsafeNativeMethods.IEnumOLEVERB e) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:EnumVerbs"); return ActiveXImpl.EnumVerbs(out e); } /// /// - int UnsafeNativeMethods.IOleObject.OleUpdate() { + int UnsafeNativeMethods.IOleObject.OleUpdate() + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:OleUpdate"); return NativeMethods.S_OK; } /// /// - int UnsafeNativeMethods.IOleObject.IsUpToDate() { + int UnsafeNativeMethods.IOleObject.IsUpToDate() + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:IsUpToDate"); return NativeMethods.S_OK; } /// /// - int UnsafeNativeMethods.IOleObject.GetUserClassID(ref Guid pClsid) { + int UnsafeNativeMethods.IOleObject.GetUserClassID(ref Guid pClsid) + { pClsid = GetType().GUID; Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:GetUserClassID. ClassID: " + pClsid.ToString()); return NativeMethods.S_OK; @@ -14032,12 +16237,15 @@ int UnsafeNativeMethods.IOleObject.GetUserClassID(ref Guid pClsid) { /// /// - int UnsafeNativeMethods.IOleObject.GetUserType(int dwFormOfType, out string userType) { + int UnsafeNativeMethods.IOleObject.GetUserType(int dwFormOfType, out string userType) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:GetUserType"); - if (dwFormOfType == NativeMethods.USERCLASSTYPE_FULL) { + if (dwFormOfType == NativeMethods.USERCLASSTYPE_FULL) + { userType = GetType().FullName; } - else { + else + { userType = GetType().Name; } return NativeMethods.S_OK; @@ -14045,7 +16253,8 @@ int UnsafeNativeMethods.IOleObject.GetUserType(int dwFormOfType, out string user /// /// - int UnsafeNativeMethods.IOleObject.SetExtent(int dwDrawAspect, NativeMethods.tagSIZEL pSizel) { + int UnsafeNativeMethods.IOleObject.SetExtent(int dwDrawAspect, NativeMethods.tagSIZEL pSizel) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:SetExtent(" + pSizel.cx + ", " + pSizel.cy + ")"); Debug.Indent(); ActiveXInstance.SetExtent(dwDrawAspect, pSizel); @@ -14055,7 +16264,8 @@ int UnsafeNativeMethods.IOleObject.SetExtent(int dwDrawAspect, NativeMethods.tag /// /// - int UnsafeNativeMethods.IOleObject.GetExtent(int dwDrawAspect, NativeMethods.tagSIZEL pSizel) { + int UnsafeNativeMethods.IOleObject.GetExtent(int dwDrawAspect, NativeMethods.tagSIZEL pSizel) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:GetExtent. Aspect: " + dwDrawAspect.ToString(CultureInfo.InvariantCulture)); Debug.Indent(); ActiveXInstance.GetExtent(dwDrawAspect, pSizel); @@ -14066,7 +16276,8 @@ int UnsafeNativeMethods.IOleObject.GetExtent(int dwDrawAspect, NativeMethods.tag /// /// - int UnsafeNativeMethods.IOleObject.Advise(IAdviseSink pAdvSink, out int cookie) { + int UnsafeNativeMethods.IOleObject.Advise(IAdviseSink pAdvSink, out int cookie) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:Advise"); cookie = ActiveXInstance.Advise(pAdvSink); return NativeMethods.S_OK; @@ -14074,7 +16285,8 @@ int UnsafeNativeMethods.IOleObject.Advise(IAdviseSink pAdvSink, out int cookie) /// /// - int UnsafeNativeMethods.IOleObject.Unadvise(int dwConnection) { + int UnsafeNativeMethods.IOleObject.Unadvise(int dwConnection) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:Unadvise"); Debug.Indent(); ActiveXInstance.Unadvise(dwConnection); @@ -14084,7 +16296,8 @@ int UnsafeNativeMethods.IOleObject.Unadvise(int dwConnection) { /// /// - int UnsafeNativeMethods.IOleObject.EnumAdvise(out IEnumSTATDATA e) { + int UnsafeNativeMethods.IOleObject.EnumAdvise(out IEnumSTATDATA e) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:EnumAdvise"); e = null; return NativeMethods.E_NOTIMPL; @@ -14092,22 +16305,27 @@ int UnsafeNativeMethods.IOleObject.EnumAdvise(out IEnumSTATDATA e) { /// /// - int UnsafeNativeMethods.IOleObject.GetMiscStatus(int dwAspect, out int cookie) { - if ((dwAspect & NativeMethods.DVASPECT_CONTENT) != 0) { + int UnsafeNativeMethods.IOleObject.GetMiscStatus(int dwAspect, out int cookie) + { + if ((dwAspect & NativeMethods.DVASPECT_CONTENT) != 0) + { int status = NativeMethods.OLEMISC_ACTIVATEWHENVISIBLE | NativeMethods.OLEMISC_INSIDEOUT | NativeMethods.OLEMISC_SETCLIENTSITEFIRST; - if (GetStyle(ControlStyles.ResizeRedraw)) { + if (GetStyle(ControlStyles.ResizeRedraw)) + { status |= NativeMethods.OLEMISC_RECOMPOSEONRESIZE; } - if (this is IButtonControl) { + if (this is IButtonControl) + { status |= NativeMethods.OLEMISC_ACTSLIKEBUTTON; } Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:GetMiscStatus. Status: " + status.ToString(CultureInfo.InvariantCulture)); cookie = status; } - else { + else + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:GetMiscStatus. Status: ERROR, wrong aspect."); cookie = 0; return NativeMethods.DV_E_DVASPECT; @@ -14117,46 +16335,53 @@ int UnsafeNativeMethods.IOleObject.GetMiscStatus(int dwAspect, out int cookie) { /// /// - int UnsafeNativeMethods.IOleObject.SetColorScheme(NativeMethods.tagLOGPALETTE pLogpal) { + int UnsafeNativeMethods.IOleObject.SetColorScheme(NativeMethods.tagLOGPALETTE pLogpal) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:SetColorScheme"); return NativeMethods.S_OK; } /// /// - int UnsafeNativeMethods.IOleWindow.GetWindow(out IntPtr hwnd) { - return((UnsafeNativeMethods.IOleInPlaceObject)this).GetWindow(out hwnd); + int UnsafeNativeMethods.IOleWindow.GetWindow(out IntPtr hwnd) + { + return ((UnsafeNativeMethods.IOleInPlaceObject)this).GetWindow(out hwnd); } /// /// - void UnsafeNativeMethods.IOleWindow.ContextSensitiveHelp(int fEnterMode) { + void UnsafeNativeMethods.IOleWindow.ContextSensitiveHelp(int fEnterMode) + { ((UnsafeNativeMethods.IOleInPlaceObject)this).ContextSensitiveHelp(fEnterMode); } /// /// - void UnsafeNativeMethods.IPersist.GetClassID(out Guid pClassID) { + void UnsafeNativeMethods.IPersist.GetClassID(out Guid pClassID) + { pClassID = GetType().GUID; Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:IPersist.GetClassID. ClassID: " + pClassID.ToString()); } /// /// - void UnsafeNativeMethods.IPersistPropertyBag.InitNew() { + void UnsafeNativeMethods.IPersistPropertyBag.InitNew() + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:IPersistPropertyBag.InitNew"); } /// /// - void UnsafeNativeMethods.IPersistPropertyBag.GetClassID(out Guid pClassID) { + void UnsafeNativeMethods.IPersistPropertyBag.GetClassID(out Guid pClassID) + { pClassID = GetType().GUID; Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:IPersistPropertyBag.GetClassID. ClassID: " + pClassID.ToString()); } /// /// - void UnsafeNativeMethods.IPersistPropertyBag.Load(UnsafeNativeMethods.IPropertyBag pPropBag, UnsafeNativeMethods.IErrorLog pErrorLog) { + void UnsafeNativeMethods.IPersistPropertyBag.Load(UnsafeNativeMethods.IPropertyBag pPropBag, UnsafeNativeMethods.IErrorLog pErrorLog) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:Load (IPersistPropertyBag)"); Debug.Indent(); ActiveXInstance.Load(pPropBag, pErrorLog); @@ -14165,7 +16390,8 @@ void UnsafeNativeMethods.IPersistPropertyBag.Load(UnsafeNativeMethods.IPropertyB /// /// - void UnsafeNativeMethods.IPersistPropertyBag.Save(UnsafeNativeMethods.IPropertyBag pPropBag, bool fClearDirty, bool fSaveAllProperties) { + void UnsafeNativeMethods.IPersistPropertyBag.Save(UnsafeNativeMethods.IPropertyBag pPropBag, bool fClearDirty, bool fSaveAllProperties) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:Save (IPersistPropertyBag)"); Debug.Indent(); ActiveXInstance.Save(pPropBag, fClearDirty, fSaveAllProperties); @@ -14174,27 +16400,31 @@ void UnsafeNativeMethods.IPersistPropertyBag.Save(UnsafeNativeMethods.IPropertyB /// /// - void UnsafeNativeMethods.IPersistStorage.GetClassID(out Guid pClassID) { + void UnsafeNativeMethods.IPersistStorage.GetClassID(out Guid pClassID) + { pClassID = GetType().GUID; Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:IPersistStorage.GetClassID. ClassID: " + pClassID.ToString()); } /// /// - int UnsafeNativeMethods.IPersistStorage.IsDirty() { + int UnsafeNativeMethods.IPersistStorage.IsDirty() + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:IPersistStorage.IsDirty"); return ActiveXInstance.IsDirty(); } /// /// - void UnsafeNativeMethods.IPersistStorage.InitNew(UnsafeNativeMethods.IStorage pstg) { + void UnsafeNativeMethods.IPersistStorage.InitNew(UnsafeNativeMethods.IStorage pstg) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:IPersistStorage.InitNew"); } /// /// - int UnsafeNativeMethods.IPersistStorage.Load(UnsafeNativeMethods.IStorage pstg) { + int UnsafeNativeMethods.IPersistStorage.Load(UnsafeNativeMethods.IStorage pstg) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:IPersistStorage.Load"); Debug.Indent(); ActiveXInstance.Load(pstg); @@ -14204,7 +16434,8 @@ int UnsafeNativeMethods.IPersistStorage.Load(UnsafeNativeMethods.IStorage pstg) /// /// - void UnsafeNativeMethods.IPersistStorage.Save(UnsafeNativeMethods.IStorage pstg, bool fSameAsLoad) { + void UnsafeNativeMethods.IPersistStorage.Save(UnsafeNativeMethods.IStorage pstg, bool fSameAsLoad) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:IPersistStorage.Save"); Debug.Indent(); ActiveXInstance.Save(pstg, fSameAsLoad); @@ -14213,33 +16444,38 @@ void UnsafeNativeMethods.IPersistStorage.Save(UnsafeNativeMethods.IStorage pstg, /// /// - void UnsafeNativeMethods.IPersistStorage.SaveCompleted(UnsafeNativeMethods.IStorage pStgNew) { + void UnsafeNativeMethods.IPersistStorage.SaveCompleted(UnsafeNativeMethods.IStorage pStgNew) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:IPersistStorage.SaveCompleted"); } /// /// - void UnsafeNativeMethods.IPersistStorage.HandsOffStorage() { + void UnsafeNativeMethods.IPersistStorage.HandsOffStorage() + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:IPersistStorage.HandsOffStorage"); } /// /// - void UnsafeNativeMethods.IPersistStreamInit.GetClassID(out Guid pClassID) { + void UnsafeNativeMethods.IPersistStreamInit.GetClassID(out Guid pClassID) + { pClassID = GetType().GUID; Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:IPersistStreamInit.GetClassID. ClassID: " + pClassID.ToString()); } /// /// - int UnsafeNativeMethods.IPersistStreamInit.IsDirty() { + int UnsafeNativeMethods.IPersistStreamInit.IsDirty() + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:IPersistStreamInit.IsDirty"); return ActiveXInstance.IsDirty(); } /// /// - void UnsafeNativeMethods.IPersistStreamInit.Load(UnsafeNativeMethods.IStream pstm) { + void UnsafeNativeMethods.IPersistStreamInit.Load(UnsafeNativeMethods.IStream pstm) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:IPersistStreamInit.Load"); Debug.Indent(); ActiveXInstance.Load(pstm); @@ -14248,7 +16484,8 @@ void UnsafeNativeMethods.IPersistStreamInit.Load(UnsafeNativeMethods.IStream pst /// /// - void UnsafeNativeMethods.IPersistStreamInit.Save(UnsafeNativeMethods.IStream pstm, bool fClearDirty) { + void UnsafeNativeMethods.IPersistStreamInit.Save(UnsafeNativeMethods.IStream pstm, bool fClearDirty) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:IPersistStreamInit.Save"); Debug.Indent(); ActiveXInstance.Save(pstm, fClearDirty); @@ -14257,19 +16494,22 @@ void UnsafeNativeMethods.IPersistStreamInit.Save(UnsafeNativeMethods.IStream pst /// /// - void UnsafeNativeMethods.IPersistStreamInit.GetSizeMax(long pcbSize) { + void UnsafeNativeMethods.IPersistStreamInit.GetSizeMax(long pcbSize) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:GetSizeMax"); } /// /// - void UnsafeNativeMethods.IPersistStreamInit.InitNew() { + void UnsafeNativeMethods.IPersistStreamInit.InitNew() + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:IPersistStreamInit.InitNew"); } /// /// - void UnsafeNativeMethods.IQuickActivate.QuickActivate(UnsafeNativeMethods.tagQACONTAINER pQaContainer, UnsafeNativeMethods.tagQACONTROL pQaControl) { + void UnsafeNativeMethods.IQuickActivate.QuickActivate(UnsafeNativeMethods.tagQACONTAINER pQaContainer, UnsafeNativeMethods.tagQACONTROL pQaControl) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:QuickActivate"); Debug.Indent(); ActiveXInstance.QuickActivate(pQaContainer, pQaControl); @@ -14278,7 +16518,8 @@ void UnsafeNativeMethods.IQuickActivate.QuickActivate(UnsafeNativeMethods.tagQAC /// /// - void UnsafeNativeMethods.IQuickActivate.SetContentExtent(NativeMethods.tagSIZEL pSizel) { + void UnsafeNativeMethods.IQuickActivate.SetContentExtent(NativeMethods.tagSIZEL pSizel) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:SetContentExtent"); Debug.Indent(); ActiveXInstance.SetExtent(NativeMethods.DVASPECT_CONTENT, pSizel); @@ -14287,7 +16528,8 @@ void UnsafeNativeMethods.IQuickActivate.SetContentExtent(NativeMethods.tagSIZEL /// /// - void UnsafeNativeMethods.IQuickActivate.GetContentExtent(NativeMethods.tagSIZEL pSizel) { + void UnsafeNativeMethods.IQuickActivate.GetContentExtent(NativeMethods.tagSIZEL pSizel) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:GetContentExtent"); Debug.Indent(); ActiveXInstance.GetExtent(NativeMethods.DVASPECT_CONTENT, pSizel); @@ -14298,20 +16540,24 @@ void UnsafeNativeMethods.IQuickActivate.GetContentExtent(NativeMethods.tagSIZEL /// int UnsafeNativeMethods.IViewObject.Draw(int dwDrawAspect, int lindex, IntPtr pvAspect, NativeMethods.tagDVTARGETDEVICE ptd, IntPtr hdcTargetDev, IntPtr hdcDraw, NativeMethods.COMRECT lprcBounds, NativeMethods.COMRECT lprcWBounds, - IntPtr pfnContinue, int dwContinue) { + IntPtr pfnContinue, int dwContinue) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:Draw"); Debug.Indent(); - try { + try + { ActiveXInstance.Draw(dwDrawAspect, lindex, pvAspect, ptd, hdcTargetDev, hdcDraw, lprcBounds, lprcWBounds, pfnContinue, dwContinue); } - catch(ExternalException ex) { + catch (ExternalException ex) + { return ex.ErrorCode; } - finally { + finally + { Debug.Unindent(); } return NativeMethods.S_OK; @@ -14320,7 +16566,8 @@ int UnsafeNativeMethods.IViewObject.Draw(int dwDrawAspect, int lindex, IntPtr pv /// /// int UnsafeNativeMethods.IViewObject.GetColorSet(int dwDrawAspect, int lindex, IntPtr pvAspect, NativeMethods.tagDVTARGETDEVICE ptd, - IntPtr hicTargetDev, NativeMethods.tagLOGPALETTE ppColorSet) { + IntPtr hicTargetDev, NativeMethods.tagLOGPALETTE ppColorSet) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:GetColorSet"); @@ -14331,28 +16578,32 @@ int UnsafeNativeMethods.IViewObject.GetColorSet(int dwDrawAspect, int lindex, In /// /// - int UnsafeNativeMethods.IViewObject.Freeze(int dwDrawAspect, int lindex, IntPtr pvAspect, IntPtr pdwFreeze) { + int UnsafeNativeMethods.IViewObject.Freeze(int dwDrawAspect, int lindex, IntPtr pvAspect, IntPtr pdwFreeze) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:Freezes"); return NativeMethods.E_NOTIMPL; } /// /// - int UnsafeNativeMethods.IViewObject.Unfreeze(int dwFreeze) { + int UnsafeNativeMethods.IViewObject.Unfreeze(int dwFreeze) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:Unfreeze"); return NativeMethods.E_NOTIMPL; } /// /// - void UnsafeNativeMethods.IViewObject.SetAdvise(int aspects, int advf, IAdviseSink pAdvSink) { + void UnsafeNativeMethods.IViewObject.SetAdvise(int aspects, int advf, IAdviseSink pAdvSink) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:SetAdvise"); ActiveXInstance.SetAdvise(aspects, advf, pAdvSink); } /// /// - void UnsafeNativeMethods.IViewObject.GetAdvise(int[] paspects, int[] padvf, IAdviseSink[] pAdvSink) { + void UnsafeNativeMethods.IViewObject.GetAdvise(int[] paspects, int[] padvf, IAdviseSink[] pAdvSink) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:GetAdvise"); ActiveXInstance.GetAdvise(paspects, padvf, pAdvSink); } @@ -14361,7 +16612,8 @@ void UnsafeNativeMethods.IViewObject.GetAdvise(int[] paspects, int[] padvf, IAdv /// void UnsafeNativeMethods.IViewObject2.Draw(int dwDrawAspect, int lindex, IntPtr pvAspect, NativeMethods.tagDVTARGETDEVICE ptd, IntPtr hdcTargetDev, IntPtr hdcDraw, NativeMethods.COMRECT lprcBounds, NativeMethods.COMRECT lprcWBounds, - IntPtr pfnContinue, int dwContinue) { + IntPtr pfnContinue, int dwContinue) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:Draw"); Debug.Indent(); ActiveXInstance.Draw(dwDrawAspect, lindex, pvAspect, ptd, hdcTargetDev, @@ -14372,7 +16624,8 @@ void UnsafeNativeMethods.IViewObject2.Draw(int dwDrawAspect, int lindex, IntPtr /// /// int UnsafeNativeMethods.IViewObject2.GetColorSet(int dwDrawAspect, int lindex, IntPtr pvAspect, NativeMethods.tagDVTARGETDEVICE ptd, - IntPtr hicTargetDev, NativeMethods.tagLOGPALETTE ppColorSet) { + IntPtr hicTargetDev, NativeMethods.tagLOGPALETTE ppColorSet) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:GetColorSet"); @@ -14383,35 +16636,40 @@ int UnsafeNativeMethods.IViewObject2.GetColorSet(int dwDrawAspect, int lindex, I /// /// - int UnsafeNativeMethods.IViewObject2.Freeze(int dwDrawAspect, int lindex, IntPtr pvAspect, IntPtr pdwFreeze) { + int UnsafeNativeMethods.IViewObject2.Freeze(int dwDrawAspect, int lindex, IntPtr pvAspect, IntPtr pdwFreeze) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:Freezes"); return NativeMethods.E_NOTIMPL; } /// /// - int UnsafeNativeMethods.IViewObject2.Unfreeze(int dwFreeze) { + int UnsafeNativeMethods.IViewObject2.Unfreeze(int dwFreeze) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:Unfreeze"); return NativeMethods.E_NOTIMPL; } /// /// - void UnsafeNativeMethods.IViewObject2.SetAdvise(int aspects, int advf, IAdviseSink pAdvSink) { + void UnsafeNativeMethods.IViewObject2.SetAdvise(int aspects, int advf, IAdviseSink pAdvSink) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:SetAdvise"); ActiveXInstance.SetAdvise(aspects, advf, pAdvSink); } /// /// - void UnsafeNativeMethods.IViewObject2.GetAdvise(int[] paspects, int[] padvf, IAdviseSink[] pAdvSink) { + void UnsafeNativeMethods.IViewObject2.GetAdvise(int[] paspects, int[] padvf, IAdviseSink[] pAdvSink) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:GetAdvise"); ActiveXInstance.GetAdvise(paspects, padvf, pAdvSink); } /// /// - void UnsafeNativeMethods.IViewObject2.GetExtent(int dwDrawAspect, int lindex, NativeMethods.tagDVTARGETDEVICE ptd, NativeMethods.tagSIZEL lpsizel) { + void UnsafeNativeMethods.IViewObject2.GetExtent(int dwDrawAspect, int lindex, NativeMethods.tagDVTARGETDEVICE ptd, NativeMethods.tagSIZEL lpsizel) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:GetExtent (IViewObject2)"); // we already have an implementation of this [from IOleObject] // @@ -14420,79 +16678,98 @@ void UnsafeNativeMethods.IViewObject2.GetExtent(int dwDrawAspect, int lindex, Na #region IKeyboardToolTip implementation - bool IKeyboardToolTip.CanShowToolTipsNow() { + bool IKeyboardToolTip.CanShowToolTipsNow() + { IKeyboardToolTip host = this.ToolStripControlHost; return this.IsHandleCreated && this.Visible && (host == null || host.CanShowToolTipsNow()); } - Rectangle IKeyboardToolTip.GetNativeScreenRectangle() { + Rectangle IKeyboardToolTip.GetNativeScreenRectangle() + { return this.GetToolNativeScreenRectangle(); } - IList IKeyboardToolTip.GetNeighboringToolsRectangles() { + IList IKeyboardToolTip.GetNeighboringToolsRectangles() + { IKeyboardToolTip host = this.ToolStripControlHost; - if (host == null) { + if (host == null) + { return this.GetOwnNeighboringToolsRectangles(); } - else { + else + { return host.GetNeighboringToolsRectangles(); } } - bool IKeyboardToolTip.IsHoveredWithMouse() { + bool IKeyboardToolTip.IsHoveredWithMouse() + { return this.ClientRectangle.Contains(this.PointToClient(Control.MousePosition)); } - bool IKeyboardToolTip.HasRtlModeEnabled() { + bool IKeyboardToolTip.HasRtlModeEnabled() + { Control topLevelControl = TopLevelControlInternal; return topLevelControl != null && topLevelControl.RightToLeft == RightToLeft.Yes && !this.IsMirrored; } - bool IKeyboardToolTip.AllowsToolTip() { + bool IKeyboardToolTip.AllowsToolTip() + { IKeyboardToolTip host = this.ToolStripControlHost; return (host == null || host.AllowsToolTip()) && this.AllowsKeyboardToolTip(); } - IWin32Window IKeyboardToolTip.GetOwnerWindow() { + IWin32Window IKeyboardToolTip.GetOwnerWindow() + { return this; } - void IKeyboardToolTip.OnHooked(ToolTip toolTip) { + void IKeyboardToolTip.OnHooked(ToolTip toolTip) + { this.OnKeyboardToolTipHook(toolTip); } - void IKeyboardToolTip.OnUnhooked(ToolTip toolTip) { + void IKeyboardToolTip.OnUnhooked(ToolTip toolTip) + { this.OnKeyboardToolTipUnhook(toolTip); } - string IKeyboardToolTip.GetCaptionForTool(ToolTip toolTip) { - IKeyboardToolTip host = this.ToolStripControlHost; - if (host == null) { + string IKeyboardToolTip.GetCaptionForTool(ToolTip toolTip) + { + IKeyboardToolTip host = this.ToolStripControlHost; + if (host == null) + { return toolTip.GetCaptionForTool(this); } - else { + else + { return host.GetCaptionForTool(toolTip); } } - bool IKeyboardToolTip.ShowsOwnToolTip() { + bool IKeyboardToolTip.ShowsOwnToolTip() + { IKeyboardToolTip host = this.ToolStripControlHost; return (host == null || host.ShowsOwnToolTip()) && this.ShowsOwnKeyboardToolTip(); } - bool IKeyboardToolTip.IsBeingTabbedTo() { + bool IKeyboardToolTip.IsBeingTabbedTo() + { return Control.AreCommonNavigationalKeysDown(); } - bool IKeyboardToolTip.AllowsChildrenToShowToolTips() { + bool IKeyboardToolTip.AllowsChildrenToShowToolTips() + { return this.AllowsChildrenToShowToolTips(); } #endregion - private IList GetOwnNeighboringToolsRectangles() { + private IList GetOwnNeighboringToolsRectangles() + { Control controlParent = this.ParentInternal; - if (controlParent != null) { + if (controlParent != null) + { Control[] neighboringControls = new Control[4] { // Next and previous control which are accessible with Tab and Shift+Tab controlParent.GetNextSelectableControl(this, true, true, true, false), @@ -14503,36 +16780,44 @@ private IList GetOwnNeighboringToolsRectangles() { }; List neighboringControlsRectangles = new List(4); - foreach (Control neighboringControl in neighboringControls) { - if (neighboringControl != null && neighboringControl.IsHandleCreated) { + foreach (Control neighboringControl in neighboringControls) + { + if (neighboringControl != null && neighboringControl.IsHandleCreated) + { neighboringControlsRectangles.Add(((IKeyboardToolTip)neighboringControl).GetNativeScreenRectangle()); } } return neighboringControlsRectangles; } - else { + else + { return new Rectangle[0]; } } - internal virtual bool ShowsOwnKeyboardToolTip() { + internal virtual bool ShowsOwnKeyboardToolTip() + { return true; } - internal virtual void OnKeyboardToolTipHook(ToolTip toolTip) { + internal virtual void OnKeyboardToolTipHook(ToolTip toolTip) + { } - internal virtual void OnKeyboardToolTipUnhook(ToolTip toolTip) { + internal virtual void OnKeyboardToolTipUnhook(ToolTip toolTip) + { } - internal virtual Rectangle GetToolNativeScreenRectangle() { + internal virtual Rectangle GetToolNativeScreenRectangle() + { NativeMethods.RECT rectangle = new NativeMethods.RECT(); UnsafeNativeMethods.GetWindowRect(new HandleRef(this, this.Handle), ref rectangle); return Rectangle.FromLTRB(rectangle.left, rectangle.top, rectangle.right, rectangle.bottom); } - internal virtual bool AllowsKeyboardToolTip() { + internal virtual bool AllowsKeyboardToolTip() + { // This internal method enables keyboard ToolTips for all controls including the foreign descendants of Control unless this method is overridden in a child class belonging to this assembly. // ElementHost is one such control which is located in a different assembly. // This control doesn't show a mouse ToolTip when hovered and thus should not have a keyboard ToolTip as well. @@ -14540,12 +16825,15 @@ internal virtual bool AllowsKeyboardToolTip() { return true; } - private static bool IsKeyDown(Keys key) { + private static bool IsKeyDown(Keys key) + { return (tempKeyboardStateArray[(int)key] & Control.HighOrderBitMask) != 0; } - internal static bool AreCommonNavigationalKeysDown() { - if(tempKeyboardStateArray == null) { + internal static bool AreCommonNavigationalKeysDown() + { + if (tempKeyboardStateArray == null) + { tempKeyboardStateArray = new byte[256]; } UnsafeNativeMethods.GetKeyboardState(tempKeyboardStateArray); @@ -14562,18 +16850,22 @@ internal static bool AreCommonNavigationalKeysDown() { private readonly WeakReference toolStripControlHostReference = new WeakReference(null); - internal ToolStripControlHost ToolStripControlHost { - get { + internal ToolStripControlHost ToolStripControlHost + { + get + { ToolStripControlHost value; this.toolStripControlHostReference.TryGetTarget(out value); return value; } - set { + set + { this.toolStripControlHostReference.SetTarget(value); } } - internal virtual bool AllowsChildrenToShowToolTips() { + internal virtual bool AllowsChildrenToShowToolTips() + { return true; } @@ -14581,33 +16873,34 @@ internal virtual bool AllowsChildrenToShowToolTips() { /// This class holds all of the state data for an ActiveX control and /// supplies the implementation for many of the non-trivial methods. /// - private class ActiveXImpl : MarshalByRefObject, IWindowTarget { + private class ActiveXImpl : MarshalByRefObject, IWindowTarget + { // SECUNDONE : This call is private and is only used to expose a WinForm control as // : an ActiveX control. This class needs more review. // - private static readonly int hiMetricPerInch = 2540; - private static readonly int viewAdviseOnlyOnce = BitVector32.CreateMask(); - private static readonly int viewAdvisePrimeFirst = BitVector32.CreateMask(viewAdviseOnlyOnce); - private static readonly int eventsFrozen = BitVector32.CreateMask(viewAdvisePrimeFirst); - private static readonly int changingExtents = BitVector32.CreateMask(eventsFrozen); - private static readonly int saving = BitVector32.CreateMask(changingExtents); - private static readonly int isDirty = BitVector32.CreateMask(saving); - private static readonly int inPlaceActive = BitVector32.CreateMask(isDirty); - private static readonly int inPlaceVisible = BitVector32.CreateMask(inPlaceActive); - private static readonly int uiActive = BitVector32.CreateMask(inPlaceVisible); - private static readonly int uiDead = BitVector32.CreateMask(uiActive); - private static readonly int adjustingRect = BitVector32.CreateMask(uiDead); + private static readonly int hiMetricPerInch = 2540; + private static readonly int viewAdviseOnlyOnce = BitVector32.CreateMask(); + private static readonly int viewAdvisePrimeFirst = BitVector32.CreateMask(viewAdviseOnlyOnce); + private static readonly int eventsFrozen = BitVector32.CreateMask(viewAdvisePrimeFirst); + private static readonly int changingExtents = BitVector32.CreateMask(eventsFrozen); + private static readonly int saving = BitVector32.CreateMask(changingExtents); + private static readonly int isDirty = BitVector32.CreateMask(saving); + private static readonly int inPlaceActive = BitVector32.CreateMask(isDirty); + private static readonly int inPlaceVisible = BitVector32.CreateMask(inPlaceActive); + private static readonly int uiActive = BitVector32.CreateMask(inPlaceVisible); + private static readonly int uiDead = BitVector32.CreateMask(uiActive); + private static readonly int adjustingRect = BitVector32.CreateMask(uiDead); - private static Point logPixels = Point.Empty; - private static NativeMethods.tagOLEVERB[] axVerbs; + private static Point logPixels = Point.Empty; + private static NativeMethods.tagOLEVERB[] axVerbs; - private static int globalActiveXCount = 0; - private static bool checkedIE; - private static bool isIE; + private static int globalActiveXCount = 0; + private static bool checkedIE; + private static bool isIE; - #if ACTIVEX_SOURCING +#if ACTIVEX_SOURCING // // This has been cut from the product. @@ -14615,27 +16908,28 @@ private class ActiveXImpl : MarshalByRefObject, IWindowTarget { private static ActiveXPropPage propPage; - #endif - - private Control control; - private IWindowTarget controlWindowTarget; - private IntPtr clipRegion; - private UnsafeNativeMethods.IOleClientSite clientSite; - private UnsafeNativeMethods.IOleInPlaceUIWindow inPlaceUiWindow; - private UnsafeNativeMethods.IOleInPlaceFrame inPlaceFrame; - private ArrayList adviseList; - private IAdviseSink viewAdviseSink; - private BitVector32 activeXState; - private AmbientProperty[] ambientProperties; - private IntPtr hwndParent; - private IntPtr accelTable; - private short accelCount = -1; - private NativeMethods.COMRECT adjustRect; // temporary rect used during OnPosRectChange && SetObjectRects +#endif + + private Control control; + private IWindowTarget controlWindowTarget; + private IntPtr clipRegion; + private UnsafeNativeMethods.IOleClientSite clientSite; + private UnsafeNativeMethods.IOleInPlaceUIWindow inPlaceUiWindow; + private UnsafeNativeMethods.IOleInPlaceFrame inPlaceFrame; + private ArrayList adviseList; + private IAdviseSink viewAdviseSink; + private BitVector32 activeXState; + private AmbientProperty[] ambientProperties; + private IntPtr hwndParent; + private IntPtr accelTable; + private short accelCount = -1; + private NativeMethods.COMRECT adjustRect; // temporary rect used during OnPosRectChange && SetObjectRects /// /// Creates a new ActiveXImpl. /// - internal ActiveXImpl(Control control) { + internal ActiveXImpl(Control control) + { this.control = control; // We replace the control's window target with our own. We @@ -14657,22 +16951,30 @@ internal ActiveXImpl(Control control) { /// Retrieves the ambient back color for the control. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - internal Color AmbientBackColor { - get { + internal Color AmbientBackColor + { + get + { AmbientProperty prop = LookupAmbient(NativeMethods.ActiveX.DISPID_AMBIENT_BACKCOLOR); - if (prop.Empty) { + if (prop.Empty) + { object obj = null; - if (GetAmbientProperty(NativeMethods.ActiveX.DISPID_AMBIENT_BACKCOLOR, ref obj)) { - if (obj != null) { - try { + if (GetAmbientProperty(NativeMethods.ActiveX.DISPID_AMBIENT_BACKCOLOR, ref obj)) + { + if (obj != null) + { + try + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "Object color type=" + obj.GetType().FullName); prop.Value = ColorTranslator.FromOle(Convert.ToInt32(obj, CultureInfo.InvariantCulture)); } - catch (Exception e) { + catch (Exception e) + { Debug.Fail("Failed to massage ambient back color to a Color", e.ToString()); - if (ClientUtils.IsSecurityOrCriticalException(e)) { + if (ClientUtils.IsSecurityOrCriticalException(e)) + { throw; } } @@ -14680,11 +16982,13 @@ internal Color AmbientBackColor { } } - if (prop.Value == null) { + if (prop.Value == null) + { return Color.Empty; } - else { - return(Color)prop.Value; + else + { + return (Color)prop.Value; } } } @@ -14693,14 +16997,19 @@ internal Color AmbientBackColor { /// Retrieves the ambient font for the control. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - internal Font AmbientFont { - get { + internal Font AmbientFont + { + get + { AmbientProperty prop = LookupAmbient(NativeMethods.ActiveX.DISPID_AMBIENT_FONT); - if (prop.Empty) { + if (prop.Empty) + { object obj = null; - if (GetAmbientProperty(NativeMethods.ActiveX.DISPID_AMBIENT_FONT, ref obj)) { - try { + if (GetAmbientProperty(NativeMethods.ActiveX.DISPID_AMBIENT_FONT, ref obj)) + { + try + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "Object font type=" + obj.GetType().FullName); Debug.Assert(obj != null, "GetAmbientProperty failed"); IntPtr hfont = IntPtr.Zero; @@ -14712,8 +17021,10 @@ internal Font AmbientFont { font = Font.FromHfont(hfont); prop.Value = font; } - catch (Exception e) { - if (ClientUtils.IsSecurityOrCriticalException(e)) { + catch (Exception e) + { + if (ClientUtils.IsSecurityOrCriticalException(e)) + { throw; } @@ -14723,7 +17034,7 @@ internal Font AmbientFont { } } - return(Font)prop.Value; + return (Font)prop.Value; } } @@ -14731,22 +17042,30 @@ internal Font AmbientFont { /// Retrieves the ambient back color for the control. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - internal Color AmbientForeColor { - get { + internal Color AmbientForeColor + { + get + { AmbientProperty prop = LookupAmbient(NativeMethods.ActiveX.DISPID_AMBIENT_FORECOLOR); - if (prop.Empty) { + if (prop.Empty) + { object obj = null; - if (GetAmbientProperty(NativeMethods.ActiveX.DISPID_AMBIENT_FORECOLOR, ref obj)) { - if (obj != null) { - try { + if (GetAmbientProperty(NativeMethods.ActiveX.DISPID_AMBIENT_FORECOLOR, ref obj)) + { + if (obj != null) + { + try + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "Object color type=" + obj.GetType().FullName); prop.Value = ColorTranslator.FromOle(Convert.ToInt32(obj, CultureInfo.InvariantCulture)); } - catch (Exception e) { + catch (Exception e) + { Debug.Fail("Failed to massage ambient fore color to a Color", e.ToString()); - if (ClientUtils.IsSecurityOrCriticalException(e)) { + if (ClientUtils.IsSecurityOrCriticalException(e)) + { throw; } } @@ -14754,11 +17073,13 @@ internal Color AmbientForeColor { } } - if (prop.Value == null) { + if (prop.Value == null) + { return Color.Empty; } - else { - return(Color)prop.Value; + else + { + return (Color)prop.Value; } } } @@ -14767,11 +17088,14 @@ internal Color AmbientForeColor { /// Determines if events should be frozen. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - internal bool EventsFrozen { - get { + internal bool EventsFrozen + { + get + { return activeXState[eventsFrozen]; } - set { + set + { activeXState[eventsFrozen] = value; } } @@ -14780,8 +17104,10 @@ internal bool EventsFrozen { /// Provides access to the parent window handle /// when we are UI active /// - internal IntPtr HWNDParent { - get { + internal IntPtr HWNDParent + { + get + { return hwndParent; } } @@ -14791,26 +17117,33 @@ internal IntPtr HWNDParent { /// control must be sited for this to succeed (it will assert and /// return false if the control is not sited). /// - internal bool IsIE { - get { - if (!checkedIE) { - if (clientSite == null) { + internal bool IsIE + { + get + { + if (!checkedIE) + { + if (clientSite == null) + { Debug.Fail("Do not reference IsIE property unless control is sited."); return false; } // First, is this a managed EXE? If so, it will correctly shut down // the runtime. - if (Assembly.GetEntryAssembly() == null) { + if (Assembly.GetEntryAssembly() == null) + { // Now check for IHTMLDocument2 UnsafeNativeMethods.IOleContainer container; - if (NativeMethods.Succeeded(clientSite.GetContainer(out container)) && container is NativeMethods.IHTMLDocument) { + if (NativeMethods.Succeeded(clientSite.GetContainer(out container)) && container is NativeMethods.IHTMLDocument) + { isIE = true; Debug.WriteLineIf(CompModSwitches.ActiveX.TraceVerbose, "AxSource:IsIE running under IE"); } - if (container != null && Marshal.IsComObject(container)) { + if (container != null && Marshal.IsComObject(container)) + { Marshal.ReleaseComObject(container); } } @@ -14826,9 +17159,12 @@ internal bool IsIE { /// Retrieves the number of logical pixels per inch on the /// primary monitor. /// - private Point LogPixels { - get { - if (logPixels.IsEmpty) { + private Point LogPixels + { + get + { + if (logPixels.IsEmpty) + { logPixels = new Point(); IntPtr dc = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef); logPixels.X = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, dc), NativeMethods.LOGPIXELSX); @@ -14842,7 +17178,8 @@ private Point LogPixels { /// /// Implements IOleObject::Advise /// - internal int Advise(IAdviseSink pAdvSink) { + internal int Advise(IAdviseSink pAdvSink) + { adviseList.Add(pAdvSink); return adviseList.Count; } @@ -14850,16 +17187,20 @@ internal int Advise(IAdviseSink pAdvSink) { /// /// Implements IOleObject::Close /// - internal void Close(int dwSaveOption) { - if (activeXState[inPlaceActive]) { + internal void Close(int dwSaveOption) + { + if (activeXState[inPlaceActive]) + { InPlaceDeactivate(); } if ((dwSaveOption == NativeMethods.OLECLOSE_SAVEIFDIRTY || dwSaveOption == NativeMethods.OLECLOSE_PROMPTSAVE) && - activeXState[isDirty]) { + activeXState[isDirty]) + { - if (clientSite != null) { + if (clientSite != null) + { clientSite.SaveObject(); } SendOnSave(); @@ -14869,9 +17210,11 @@ internal void Close(int dwSaveOption) { /// /// Implements IOleObject::DoVerb /// - internal void DoVerb(int iVerb, IntPtr lpmsg, UnsafeNativeMethods.IOleClientSite pActiveSite, int lindex, IntPtr hwndParent, NativeMethods.COMRECT lprcPosRect) { + internal void DoVerb(int iVerb, IntPtr lpmsg, UnsafeNativeMethods.IOleClientSite pActiveSite, int lindex, IntPtr hwndParent, NativeMethods.COMRECT lprcPosRect) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceVerbose, "AxSource:ActiveXImpl:DoVerb(" + iVerb + ")"); - switch (iVerb) { + switch (iVerb) + { case NativeMethods.OLEIVERB_SHOW: case NativeMethods.OLEIVERB_INPLACEACTIVATE: case NativeMethods.OLEIVERB_UIACTIVATE: @@ -14882,11 +17225,13 @@ internal void DoVerb(int iVerb, IntPtr lpmsg, UnsafeNativeMethods.IOleClientSite // Now that we're active, send the lpmsg to the control if it // is valid. // - if (lpmsg != IntPtr.Zero) { + if (lpmsg != IntPtr.Zero) + { NativeMethods.MSG msg = Marshal.PtrToStructure(lpmsg); Control target = control; - if (msg.hwnd != control.Handle && msg.message >= Interop.WindowMessages.WM_MOUSEFIRST && msg.message <= Interop.WindowMessages.WM_MOUSELAST) { + if (msg.hwnd != control.Handle && msg.message >= Interop.WindowMessages.WM_MOUSEFIRST && msg.message <= Interop.WindowMessages.WM_MOUSELAST) + { // Must translate message coordniates over to our HWND. We first try // @@ -14901,7 +17246,8 @@ internal void DoVerb(int iVerb, IntPtr lpmsg, UnsafeNativeMethods.IOleClientSite // coordinates // Control realTarget = target.GetChildAtPoint(new Point(pt.x, pt.y)); - if (realTarget != null && realTarget != target) { + if (realTarget != null && realTarget != target) + { UnsafeNativeMethods.MapWindowPoints(new HandleRef(target, target.Handle), new HandleRef(realTarget, realTarget.Handle), pt, 1); target = realTarget; } @@ -14910,33 +17256,37 @@ internal void DoVerb(int iVerb, IntPtr lpmsg, UnsafeNativeMethods.IOleClientSite } #if DEBUG - if (CompModSwitches.ActiveX.TraceVerbose) { + if (CompModSwitches.ActiveX.TraceVerbose) + { Message m = Message.Create(msg.hwnd, msg.message, msg.wParam, msg.lParam); Debug.WriteLine("Valid message pointer passed, sending to control: " + m.ToString()); } #endif // DEBUG - if (msg.message == Interop.WindowMessages.WM_KEYDOWN && msg.wParam == (IntPtr)NativeMethods.VK_TAB) { + if (msg.message == Interop.WindowMessages.WM_KEYDOWN && msg.wParam == (IntPtr)NativeMethods.VK_TAB) + { target.SelectNextControl(null, Control.ModifierKeys != Keys.Shift, true, true, true); } - else { + else + { target.SendMessage(msg.message, msg.wParam, msg.lParam); } } break; - // These affect our visibility - // + // These affect our visibility + // case NativeMethods.OLEIVERB_HIDE: Debug.WriteLineIf(CompModSwitches.ActiveX.TraceVerbose, "DoVerb:Hide"); UIDeactivate(); InPlaceDeactivate(); - if (activeXState[inPlaceVisible]) { + if (activeXState[inPlaceVisible]) + { SetInPlaceVisible(false); } break; - #if ACTIVEX_SOURCING +#if ACTIVEX_SOURCING // // This has been cut from the product. @@ -14949,10 +17299,10 @@ internal void DoVerb(int iVerb, IntPtr lpmsg, UnsafeNativeMethods.IOleClientSite ShowProperties(); break; - #endif +#endif - // All other verbs are notimpl. - // + // All other verbs are notimpl. + // default: Debug.WriteLineIf(CompModSwitches.ActiveX.TraceVerbose, "DoVerb:Other"); ThrowHr(NativeMethods.E_NOTIMPL); @@ -14965,11 +17315,13 @@ internal void DoVerb(int iVerb, IntPtr lpmsg, UnsafeNativeMethods.IOleClientSite /// internal void Draw(int dwDrawAspect, int lindex, IntPtr pvAspect, NativeMethods.tagDVTARGETDEVICE ptd, IntPtr hdcTargetDev, IntPtr hdcDraw, NativeMethods.COMRECT prcBounds, NativeMethods.COMRECT lprcWBounds, - IntPtr pfnContinue, int dwContinue) { + IntPtr pfnContinue, int dwContinue) + { // support the aspects required for multi-pass drawing // - switch (dwDrawAspect) { + switch (dwDrawAspect) + { case NativeMethods.DVASPECT_CONTENT: case NativeMethods.DVASPECT_OPAQUE: case NativeMethods.DVASPECT_TRANSPARENT: @@ -14984,24 +17336,27 @@ internal void Draw(int dwDrawAspect, int lindex, IntPtr pvAspect, NativeMethods. // the caller figures it out and sends us a different DC. // int hdcType = UnsafeNativeMethods.GetObjectType(new HandleRef(null, hdcDraw)); - if (hdcType == NativeMethods.OBJ_METADC) { + if (hdcType == NativeMethods.OBJ_METADC) + { ThrowHr(NativeMethods.VIEW_E_DRAW); } NativeMethods.RECT rc; NativeMethods.POINT pVp = new NativeMethods.POINT(); NativeMethods.POINT pW = new NativeMethods.POINT(); - NativeMethods.SIZE sWindowExt = new NativeMethods.SIZE(); - NativeMethods.SIZE sViewportExt = new NativeMethods.SIZE(); - int iMode = NativeMethods.MM_TEXT; + NativeMethods.SIZE sWindowExt = new NativeMethods.SIZE(); + NativeMethods.SIZE sViewportExt = new NativeMethods.SIZE(); + int iMode = NativeMethods.MM_TEXT; - if (!control.IsHandleCreated) { + if (!control.IsHandleCreated) + { control.CreateHandle(); } // if they didn't give us a rectangle, just copy over ours // - if (prcBounds != null) { + if (prcBounds != null) + { rc = new NativeMethods.RECT(prcBounds.left, prcBounds.top, prcBounds.right, prcBounds.bottom); // To draw to a given rect, we scale the DC in such a way as to @@ -15020,24 +17375,30 @@ internal void Draw(int dwDrawAspect, int lindex, IntPtr pvAspect, NativeMethods. } // Now do the actual drawing. We must ask all of our children to draw as well. - try { + try + { IntPtr flags = (IntPtr)(NativeMethods.PRF_CHILDREN | NativeMethods.PRF_CLIENT | NativeMethods.PRF_ERASEBKGND | NativeMethods.PRF_NONCLIENT); - //| NativeMethods.PRF_CHECKVISIBLE - //| NativeMethods.PRF_OWNED)); + //| NativeMethods.PRF_CHECKVISIBLE + //| NativeMethods.PRF_OWNED)); - if(hdcType != NativeMethods.OBJ_ENHMETADC) { + if (hdcType != NativeMethods.OBJ_ENHMETADC) + { control.SendMessage(Interop.WindowMessages.WM_PRINT, hdcDraw, flags); - } else { + } + else + { control.PrintToMetaFile(new HandleRef(null, hdcDraw), flags); } } - finally { + finally + { // And clean up the DC // - if (prcBounds != null) { + if (prcBounds != null) + { SafeNativeMethods.SetWindowOrgEx(new HandleRef(null, hdcDraw), pW.x, pW.y, null); SafeNativeMethods.SetWindowExtEx(new HandleRef(null, hdcDraw), sWindowExt.cx, sWindowExt.cy, null); SafeNativeMethods.SetViewportOrgEx(new HandleRef(null, hdcDraw), pVp.x, pVp.y, null); @@ -15050,14 +17411,16 @@ internal void Draw(int dwDrawAspect, int lindex, IntPtr pvAspect, NativeMethods. /// /// Returns a new verb enumerator. /// - internal static int EnumVerbs(out UnsafeNativeMethods.IEnumOLEVERB e) { - if (axVerbs == null) { - NativeMethods.tagOLEVERB verbShow = new NativeMethods.tagOLEVERB(); - NativeMethods.tagOLEVERB verbInplaceActivate = new NativeMethods.tagOLEVERB(); - NativeMethods.tagOLEVERB verbUIActivate = new NativeMethods.tagOLEVERB(); - NativeMethods.tagOLEVERB verbHide = new NativeMethods.tagOLEVERB(); - NativeMethods.tagOLEVERB verbPrimary = new NativeMethods.tagOLEVERB(); - NativeMethods.tagOLEVERB verbProperties = new NativeMethods.tagOLEVERB(); + internal static int EnumVerbs(out UnsafeNativeMethods.IEnumOLEVERB e) + { + if (axVerbs == null) + { + NativeMethods.tagOLEVERB verbShow = new NativeMethods.tagOLEVERB(); + NativeMethods.tagOLEVERB verbInplaceActivate = new NativeMethods.tagOLEVERB(); + NativeMethods.tagOLEVERB verbUIActivate = new NativeMethods.tagOLEVERB(); + NativeMethods.tagOLEVERB verbHide = new NativeMethods.tagOLEVERB(); + NativeMethods.tagOLEVERB verbPrimary = new NativeMethods.tagOLEVERB(); + NativeMethods.tagOLEVERB verbProperties = new NativeMethods.tagOLEVERB(); verbShow.lVerb = NativeMethods.OLEIVERB_SHOW; verbInplaceActivate.lVerb = NativeMethods.OLEIVERB_INPLACEACTIVATE; @@ -15087,11 +17450,15 @@ internal static int EnumVerbs(out UnsafeNativeMethods.IEnumOLEVERB e) { /// /// Converts the given string to a byte array. /// - private static byte[] FromBase64WrappedString(string text) { - if (text.IndexOfAny(new char[] {' ', '\r', '\n'}) != -1) { + private static byte[] FromBase64WrappedString(string text) + { + if (text.IndexOfAny(new char[] { ' ', '\r', '\n' }) != -1) + { StringBuilder sb = new StringBuilder(text.Length); - for (int i=0; i /// Implements IViewObject2::GetAdvise. /// - internal void GetAdvise(int[] paspects, int[] padvf, IAdviseSink[] pAdvSink) { + internal void GetAdvise(int[] paspects, int[] padvf, IAdviseSink[] pAdvSink) + { // if they want it, give it to them // - if (paspects != null) { + if (paspects != null) + { paspects[0] = NativeMethods.DVASPECT_CONTENT; } - if (padvf != null) { + if (padvf != null) + { padvf[0] = 0; - if (activeXState[viewAdviseOnlyOnce]) padvf[0] |= NativeMethods.ADVF_ONLYONCE; - if (activeXState[viewAdvisePrimeFirst]) padvf[0] |= NativeMethods.ADVF_PRIMEFIRST; + if (activeXState[viewAdviseOnlyOnce]) + padvf[0] |= NativeMethods.ADVF_ONLYONCE; + if (activeXState[viewAdvisePrimeFirst]) + padvf[0] |= NativeMethods.ADVF_PRIMEFIRST; } - if (pAdvSink != null) { + if (pAdvSink != null) + { pAdvSink[0] = viewAdviseSink; } } @@ -15134,11 +17508,13 @@ internal void GetAdvise(int[] paspects, int[] padvf, IAdviseSink[] pAdvSink) { /// Helper function to retrieve an ambient property. Returns false if the /// property wasn't found. /// - private bool GetAmbientProperty(int dispid, ref object obj) { + private bool GetAmbientProperty(int dispid, ref object obj) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource:GetAmbientProperty"); Debug.Indent(); - if (clientSite is UnsafeNativeMethods.IDispatch) { + if (clientSite is UnsafeNativeMethods.IDispatch) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "clientSite implements IDispatch"); UnsafeNativeMethods.IDispatch disp = (UnsafeNativeMethods.IDispatch)clientSite; @@ -15147,13 +17523,15 @@ private bool GetAmbientProperty(int dispid, ref object obj) { int hr = disp.Invoke(dispid, ref g, NativeMethods.LOCALE_USER_DEFAULT, NativeMethods.DISPATCH_PROPERTYGET, new NativeMethods.tagDISPPARAMS(), pvt, null, null); - if (NativeMethods.Succeeded(hr)) { + if (NativeMethods.Succeeded(hr)) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "IDispatch::Invoke succeeded. VT=" + pvt[0].GetType().FullName); obj = pvt[0]; Debug.Unindent(); return true; } - else { + else + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "IDispatch::Invoke failed. HR: 0x" + string.Format(CultureInfo.CurrentCulture, "{0:X}", hr)); } } @@ -15165,20 +17543,24 @@ private bool GetAmbientProperty(int dispid, ref object obj) { /// /// Implements IOleObject::GetClientSite. /// - internal UnsafeNativeMethods.IOleClientSite GetClientSite() { + internal UnsafeNativeMethods.IOleClientSite GetClientSite() + { return clientSite; } /// /// - internal int GetControlInfo(NativeMethods.tagCONTROLINFO pCI) { - if (accelCount == -1) { + internal int GetControlInfo(NativeMethods.tagCONTROLINFO pCI) + { + if (accelCount == -1) + { ArrayList mnemonicList = new ArrayList(); GetMnemonicList(control, mnemonicList); accelCount = (short)mnemonicList.Count; - if (accelCount > 0) { + if (accelCount > 0) + { int accelSize = Marshal.SizeOf(); // In the worst case we may have two accelerators per mnemonic: one lower case and @@ -15186,7 +17568,8 @@ internal int GetControlInfo(NativeMethods.tagCONTROLINFO pCI) { // IntPtr accelBlob = Marshal.AllocHGlobal(accelSize * accelCount * 2); - try { + try + { NativeMethods.ACCEL accel = new NativeMethods.ACCEL(); accel.cmd = 0; @@ -15194,12 +17577,14 @@ internal int GetControlInfo(NativeMethods.tagCONTROLINFO pCI) { accelCount = 0; - foreach(char ch in mnemonicList) { + foreach (char ch in mnemonicList) + { IntPtr structAddr = (IntPtr)((long)accelBlob + accelCount * accelSize); Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "Mnemonic: " + ch.ToString()); - if (ch >= 'A' && ch <= 'Z') { + if (ch >= 'A' && ch <= 'Z') + { // Lower case letter // @@ -15214,12 +17599,14 @@ internal int GetControlInfo(NativeMethods.tagCONTROLINFO pCI) { accel.fVirt = NativeMethods.FALT | NativeMethods.FVIRTKEY | NativeMethods.FSHIFT; Marshal.StructureToPtr(accel, structAddr, false); } - else { + else + { // Some non-printable character. // accel.fVirt = NativeMethods.FALT | NativeMethods.FVIRTKEY; short scan = (short)(UnsafeNativeMethods.VkKeyScan(ch)); - if ((scan & 0x0100) != 0) { + if ((scan & 0x0100) != 0) + { accel.fVirt |= NativeMethods.FSHIFT; } accel.key = (short)(scan & 0x00FF); @@ -15235,15 +17622,18 @@ internal int GetControlInfo(NativeMethods.tagCONTROLINFO pCI) { // Now create an accelerator table and then free our memory. // - if (accelTable != IntPtr.Zero) { - UnsafeNativeMethods.DestroyAcceleratorTable(new HandleRef(this, accelTable)); - accelTable = IntPtr.Zero; - } - + if (accelTable != IntPtr.Zero) + { + UnsafeNativeMethods.DestroyAcceleratorTable(new HandleRef(this, accelTable)); + accelTable = IntPtr.Zero; + } + accelTable = UnsafeNativeMethods.CreateAcceleratorTable(new HandleRef(null, accelBlob), accelCount); } - finally { - if (accelBlob != IntPtr.Zero) { + finally + { + if (accelBlob != IntPtr.Zero) + { Marshal.FreeHGlobal(accelBlob); } } @@ -15258,15 +17648,18 @@ internal int GetControlInfo(NativeMethods.tagCONTROLINFO pCI) { /// /// Implements IOleObject::GetExtent. /// - internal void GetExtent(int dwDrawAspect, NativeMethods.tagSIZEL pSizel) { - if ((dwDrawAspect & NativeMethods.DVASPECT_CONTENT) != 0) { + internal void GetExtent(int dwDrawAspect, NativeMethods.tagSIZEL pSizel) + { + if ((dwDrawAspect & NativeMethods.DVASPECT_CONTENT) != 0) + { Size size = control.Size; Point pt = PixelToHiMetric(size.Width, size.Height); pSizel.cx = pt.X; pSizel.cy = pt.Y; } - else { + else + { ThrowHr(NativeMethods.DV_E_DVASPECT); } } @@ -15276,18 +17669,22 @@ internal void GetExtent(int dwDrawAspect, NativeMethods.tagSIZEL pSizel) { /// the mnemonics for each control to mnemonicList. Each mnemonic /// is added as a char to the list. /// - private void GetMnemonicList(Control control, ArrayList mnemonicList) { + private void GetMnemonicList(Control control, ArrayList mnemonicList) + { // Get the mnemonic for our control // char mnemonic = WindowsFormsUtils.GetMnemonic(control.Text, true); - if (mnemonic != 0) { + if (mnemonic != 0) + { mnemonicList.Add(mnemonic); } // And recurse for our children. // - foreach(Control c in control.Controls) { - if (c != null) GetMnemonicList(c, mnemonicList); + foreach (Control c in control.Controls) + { + if (c != null) + GetMnemonicList(c, mnemonicList); } } @@ -15309,8 +17706,10 @@ private string GetStreamName() /// /// Implements IOleWindow::GetWindow /// - internal int GetWindow(out IntPtr hwnd) { - if (!activeXState[inPlaceActive]) { + internal int GetWindow(out IntPtr hwnd) + { + if (!activeXState[inPlaceActive]) + { hwnd = IntPtr.Zero; return NativeMethods.E_FAIL; } @@ -15321,7 +17720,8 @@ internal int GetWindow(out IntPtr hwnd) { /// /// Converts coordinates in HiMetric to pixels. Used for ActiveX sourcing. /// - private Point HiMetricToPixel(int x, int y) { + private Point HiMetricToPixel(int x, int y) + { Point pt = new Point(); pt.X = (LogPixels.X * x + hiMetricPerInch / 2) / hiMetricPerInch; pt.Y = (LogPixels.Y * y + hiMetricPerInch / 2) / hiMetricPerInch; @@ -15345,13 +17745,16 @@ internal void InPlaceActivate(int verb) // If we're not already active, go and do it. // - if (!activeXState[inPlaceActive]) { + if (!activeXState[inPlaceActive]) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceVerbose, "\tActiveXImpl:InPlaceActivate --> inplaceactive"); int hr = inPlaceSite.CanInPlaceActivate(); - if (hr != NativeMethods.S_OK) { - if (NativeMethods.Succeeded(hr)) { + if (hr != NativeMethods.S_OK) + { + if (NativeMethods.Succeeded(hr)) + { hr = NativeMethods.E_FAIL; } ThrowHr(hr); @@ -15365,7 +17768,8 @@ internal void InPlaceActivate(int verb) // And if we're not visible, do that too. // - if (!activeXState[inPlaceVisible]) { + if (!activeXState[inPlaceVisible]) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceVerbose, "\tActiveXImpl:InPlaceActivate --> inplacevisible"); NativeMethods.tagOIFI inPlaceFrameInfo = new NativeMethods.tagOIFI(); inPlaceFrameInfo.cb = Marshal.SizeOf(); @@ -15380,12 +17784,14 @@ internal void InPlaceActivate(int verb) NativeMethods.COMRECT posRect = new NativeMethods.COMRECT(); NativeMethods.COMRECT clipRect = new NativeMethods.COMRECT(); - if (inPlaceUiWindow != null && Marshal.IsComObject(inPlaceUiWindow)) { + if (inPlaceUiWindow != null && Marshal.IsComObject(inPlaceUiWindow)) + { Marshal.ReleaseComObject(inPlaceUiWindow); inPlaceUiWindow = null; } - if (inPlaceFrame != null && Marshal.IsComObject(inPlaceFrame)) { + if (inPlaceFrame != null && Marshal.IsComObject(inPlaceFrame)) + { Marshal.ReleaseComObject(inPlaceFrame); inPlaceFrame = null; } @@ -15419,14 +17825,16 @@ internal void InPlaceActivate(int verb) // if we weren't asked to UIActivate, then we're done. // - if (verb != NativeMethods.OLEIVERB_PRIMARY && verb != NativeMethods.OLEIVERB_UIACTIVATE) { + if (verb != NativeMethods.OLEIVERB_PRIMARY && verb != NativeMethods.OLEIVERB_UIACTIVATE) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceVerbose, "\tActiveXImpl:InPlaceActivate --> not becoming UIActive"); return; } // if we're not already UI active, do sow now. // - if (!activeXState[uiActive]) { + if (!activeXState[uiActive]) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceVerbose, "\tActiveXImpl:InPlaceActivate --> uiactive"); activeXState[uiActive] = true; @@ -15436,13 +17844,15 @@ internal void InPlaceActivate(int verb) // take the focus [which is what UI Activation is all about !] // - if (!control.ContainsFocus) control.Focus(); + if (!control.ContainsFocus) + control.Focus(); // set ourselves up in the host. // Debug.Assert(inPlaceFrame != null, "Setting us to visible should have created the in place frame"); inPlaceFrame.SetActiveObject(control, null); - if (inPlaceUiWindow != null) { + if (inPlaceUiWindow != null) + { inPlaceUiWindow.SetActiveObject(control, null); } @@ -15450,19 +17860,23 @@ internal void InPlaceActivate(int verb) // int hr = inPlaceFrame.SetBorderSpace(null); if (NativeMethods.Failed(hr) && hr != NativeMethods.OLE_E_INVALIDRECT && - hr != NativeMethods.INPLACE_E_NOTOOLSPACE && hr != NativeMethods.E_NOTIMPL) { + hr != NativeMethods.INPLACE_E_NOTOOLSPACE && hr != NativeMethods.E_NOTIMPL) + { Marshal.ThrowExceptionForHR(hr); } - if (inPlaceUiWindow != null) { + if (inPlaceUiWindow != null) + { hr = inPlaceFrame.SetBorderSpace(null); if (NativeMethods.Failed(hr) && hr != NativeMethods.OLE_E_INVALIDRECT && - hr != NativeMethods.INPLACE_E_NOTOOLSPACE && hr != NativeMethods.E_NOTIMPL) { + hr != NativeMethods.INPLACE_E_NOTOOLSPACE && hr != NativeMethods.E_NOTIMPL) + { Marshal.ThrowExceptionForHR(hr); } } } - else { + else + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceVerbose, "\tActiveXImpl:InPlaceActivate --> already uiactive"); } } @@ -15470,17 +17884,20 @@ internal void InPlaceActivate(int verb) /// /// Implements IOleInPlaceObject::InPlaceDeactivate. /// - internal void InPlaceDeactivate() { + internal void InPlaceDeactivate() + { // Only do this if we're already in place active. // - if (!activeXState[inPlaceActive]) { + if (!activeXState[inPlaceActive]) + { return; } // Deactivate us if we're UI active // - if (activeXState[uiActive]) { + if (activeXState[uiActive]) + { UIDeactivate(); } @@ -15494,19 +17911,22 @@ internal void InPlaceDeactivate() { // Notify our site of our deactivation. // UnsafeNativeMethods.IOleInPlaceSite oleClientSite = clientSite as UnsafeNativeMethods.IOleInPlaceSite; - if (oleClientSite != null) { + if (oleClientSite != null) + { oleClientSite.OnInPlaceDeactivate(); } control.Visible = false; hwndParent = IntPtr.Zero; - if (inPlaceUiWindow != null && Marshal.IsComObject(inPlaceUiWindow)) { + if (inPlaceUiWindow != null && Marshal.IsComObject(inPlaceUiWindow)) + { Marshal.ReleaseComObject(inPlaceUiWindow); inPlaceUiWindow = null; } - if (inPlaceFrame != null && Marshal.IsComObject(inPlaceFrame)) { + if (inPlaceFrame != null && Marshal.IsComObject(inPlaceFrame)) + { Marshal.ReleaseComObject(inPlaceFrame); inPlaceFrame = null; } @@ -15515,11 +17935,14 @@ internal void InPlaceDeactivate() { /// /// Implements IPersistStreamInit::IsDirty. /// - internal int IsDirty() { - if (activeXState[isDirty]) { + internal int IsDirty() + { + if (activeXState[isDirty]) + { return NativeMethods.S_OK; } - else { + else + { return NativeMethods.S_FALSE; } } @@ -15528,15 +17951,18 @@ internal int IsDirty() { /// Looks at the property to see if it should be loaded / saved as a resource or /// through a type converter. /// - private bool IsResourceProp(PropertyDescriptor prop) { + private bool IsResourceProp(PropertyDescriptor prop) + { TypeConverter converter = prop.Converter; Type[] convertTypes = new Type[] { typeof(string), typeof(byte[]) }; - foreach (Type t in convertTypes) { - if (converter.CanConvertTo(t) && converter.CanConvertFrom(t)) { + foreach (Type t in convertTypes) + { + if (converter.CanConvertTo(t) && converter.CanConvertFrom(t)) + { return false; } } @@ -15549,26 +17975,32 @@ private bool IsResourceProp(PropertyDescriptor prop) { /// /// Implements IPersistStorage::Load /// - internal void Load(UnsafeNativeMethods.IStorage stg) { + internal void Load(UnsafeNativeMethods.IStorage stg) + { UnsafeNativeMethods.IStream stream = null; - try { + try + { stream = stg.OpenStream(this.GetStreamName(), IntPtr.Zero, NativeMethods.STGM_READ | NativeMethods.STGM_SHARE_EXCLUSIVE, 0); } - catch (COMException e) { - if (e.ErrorCode == NativeMethods.STG_E_FILENOTFOUND) { + catch (COMException e) + { + if (e.ErrorCode == NativeMethods.STG_E_FILENOTFOUND) + { // For backward compatibility: We were earlier using GetType().FullName // as the stream name in v1. Lets see if a stream by that name exists. stream = stg.OpenStream(GetType().FullName, IntPtr.Zero, NativeMethods.STGM_READ | NativeMethods.STGM_SHARE_EXCLUSIVE, 0); } - else { + else + { throw; } } Load(stream); stream = null; - if (Marshal.IsComObject(stg)) { + if (Marshal.IsComObject(stg)) + { Marshal.ReleaseComObject(stg); } } @@ -15576,7 +18008,8 @@ internal void Load(UnsafeNativeMethods.IStorage stg) { /// /// Implements IPersistStreamInit::Load /// - internal void Load(UnsafeNativeMethods.IStream stream) { + internal void Load(UnsafeNativeMethods.IStream stream) + { // We do everything through property bags because we support full fidelity // in them. So, load through that method. // @@ -15584,7 +18017,8 @@ internal void Load(UnsafeNativeMethods.IStream stream) { bag.Read(stream); Load(bag, null); - if (Marshal.IsComObject(stream)) { + if (Marshal.IsComObject(stream)) + { Marshal.ReleaseComObject(stream); } } @@ -15592,33 +18026,40 @@ internal void Load(UnsafeNativeMethods.IStream stream) { /// /// Implements IPersistPropertyBag::Load /// - internal void Load(UnsafeNativeMethods.IPropertyBag pPropBag, UnsafeNativeMethods.IErrorLog pErrorLog) { + internal void Load(UnsafeNativeMethods.IPropertyBag pPropBag, UnsafeNativeMethods.IErrorLog pErrorLog) + { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(control, - new Attribute[] {DesignerSerializationVisibilityAttribute.Visible}); + new Attribute[] { DesignerSerializationVisibilityAttribute.Visible }); - for (int i = 0; i < props.Count; i++) { + for (int i = 0; i < props.Count; i++) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "Loading property " + props[i].Name); - try { + try + { object obj = null; int hr = pPropBag.Read(props[i].Name, ref obj, pErrorLog); - if (NativeMethods.Succeeded(hr) && obj != null) { + if (NativeMethods.Succeeded(hr) && obj != null) + { Debug.Indent(); Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "Property was in bag"); string errorString = null; int errorCode = 0; - try { - if (obj.GetType() != typeof(string)) { + try + { + if (obj.GetType() != typeof(string)) + { Debug.Fail("Expected property " + props[i].Name + " to be stored in IPropertyBag as a string. Attempting to coerce"); obj = Convert.ToString(obj, CultureInfo.InvariantCulture); } // Determine if this is a resource property or was persisted via a type converter. // - if (IsResourceProp(props[i])) { + if (IsResourceProp(props[i])) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "It's a resource property"); // Resource property. We encode these as base 64 strings. To load them, we convert @@ -15629,7 +18070,8 @@ internal void Load(UnsafeNativeMethods.IPropertyBag pPropBag, UnsafeNativeMethod BinaryFormatter formatter = new BinaryFormatter(); props[i].SetValue(control, formatter.Deserialize(stream)); } - else { + else + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "It's a standard property"); // Not a resource property. Use TypeConverters to convert the string back to the data type. We do @@ -15646,10 +18088,12 @@ internal void Load(UnsafeNativeMethods.IPropertyBag pPropBag, UnsafeNativeMethod // object value = null; - if (converter.CanConvertFrom(typeof(string))) { + if (converter.CanConvertFrom(typeof(string))) + { value = converter.ConvertFromInvariantString(obj.ToString()); } - else if (converter.CanConvertFrom(typeof(byte[]))) { + else if (converter.CanConvertFrom(typeof(byte[]))) + { string objString = obj.ToString(); value = converter.ConvertFrom(null, CultureInfo.InvariantCulture, FromBase64WrappedString(objString)); } @@ -15657,18 +18101,23 @@ internal void Load(UnsafeNativeMethods.IPropertyBag pPropBag, UnsafeNativeMethod props[i].SetValue(control, value); } } - catch (Exception e) { + catch (Exception e) + { errorString = e.ToString(); - if (e is ExternalException) { - errorCode = ((ExternalException) e).ErrorCode; + if (e is ExternalException) + { + errorCode = ((ExternalException)e).ErrorCode; } - else { + else + { errorCode = NativeMethods.E_FAIL; } } - if (errorString != null) { + if (errorString != null) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "Exception converting property: " + errorString); - if (pErrorLog != null) { + if (pErrorLog != null) + { NativeMethods.tagEXCEPINFO err = new NativeMethods.tagEXCEPINFO(); err.bstrSource = control.GetType().FullName; err.bstrDescription = errorString; @@ -15679,15 +18128,18 @@ internal void Load(UnsafeNativeMethods.IPropertyBag pPropBag, UnsafeNativeMethod Debug.Unindent(); } } - catch (Exception ex) { + catch (Exception ex) + { Debug.Fail("Unexpected failure reading property", ex.ToString()); - if (ClientUtils.IsSecurityOrCriticalException(ex)) { + if (ClientUtils.IsSecurityOrCriticalException(ex)) + { throw; } } } - if (Marshal.IsComObject(pPropBag)) { + if (Marshal.IsComObject(pPropBag)) + { Marshal.ReleaseComObject(pPropBag); } } @@ -15696,9 +18148,12 @@ internal void Load(UnsafeNativeMethods.IPropertyBag pPropBag, UnsafeNativeMethod /// Simple lookup to find the AmbientProperty corresponding to the given /// dispid. /// - private AmbientProperty LookupAmbient(int dispid) { - for (int i = 0; i < ambientProperties.Length; i++) { - if (ambientProperties[i].DispID == dispid) { + private AmbientProperty LookupAmbient(int dispid) + { + for (int i = 0; i < ambientProperties.Length; i++) + { + if (ambientProperties[i].DispID == dispid) + { return ambientProperties[i]; } } @@ -15712,29 +18167,37 @@ private AmbientProperty LookupAmbient(int dispid) { /// to SetWindowRgn. The region does not have to be destroyed. /// The original region is destroyed if a new region is returned. /// - internal IntPtr MergeRegion(IntPtr region) { - if (clipRegion == IntPtr.Zero) { + internal IntPtr MergeRegion(IntPtr region) + { + if (clipRegion == IntPtr.Zero) + { return region; } - if (region == IntPtr.Zero) { + if (region == IntPtr.Zero) + { return clipRegion; } - try { + try + { IntPtr newRegion = SafeNativeMethods.CreateRectRgn(0, 0, 0, 0); - try { + try + { SafeNativeMethods.CombineRgn(new HandleRef(null, newRegion), new HandleRef(null, region), new HandleRef(this, clipRegion), NativeMethods.RGN_DIFF); SafeNativeMethods.DeleteObject(new HandleRef(null, region)); } - catch { + catch + { SafeNativeMethods.DeleteObject(new HandleRef(null, newRegion)); throw; } return newRegion; } - catch (Exception e) { - if (ClientUtils.IsSecurityOrCriticalException(e)) { + catch (Exception e) + { + if (ClientUtils.IsSecurityOrCriticalException(e)) + { throw; } @@ -15743,37 +18206,39 @@ internal IntPtr MergeRegion(IntPtr region) { } } - private void CallParentPropertyChanged(Control control, string propName) { - switch (propName) { - case "BackColor" : + private void CallParentPropertyChanged(Control control, string propName) + { + switch (propName) + { + case "BackColor": control.OnParentBackColorChanged(EventArgs.Empty); break; - case "BackgroundImage" : + case "BackgroundImage": control.OnParentBackgroundImageChanged(EventArgs.Empty); break; - case "BindingContext" : + case "BindingContext": control.OnParentBindingContextChanged(EventArgs.Empty); break; - case "Enabled" : + case "Enabled": control.OnParentEnabledChanged(EventArgs.Empty); break; - case "Font" : + case "Font": control.OnParentFontChanged(EventArgs.Empty); break; - case "ForeColor" : + case "ForeColor": control.OnParentForeColorChanged(EventArgs.Empty); break; - case "RightToLeft" : + case "RightToLeft": control.OnParentRightToLeftChanged(EventArgs.Empty); break; - case "Visible" : + case "Visible": control.OnParentVisibleChanged(EventArgs.Empty); break; @@ -15786,13 +18251,17 @@ private void CallParentPropertyChanged(Control control, string propName) { /// /// Implements IOleControl::OnAmbientPropertyChanged /// - internal void OnAmbientPropertyChange(int dispID) { - if (dispID != NativeMethods.ActiveX.DISPID_UNKNOWN) { + internal void OnAmbientPropertyChange(int dispID) + { + if (dispID != NativeMethods.ActiveX.DISPID_UNKNOWN) + { // Look for a specific property that has changed. // - for (int i = 0; i < ambientProperties.Length; i++) { - if (ambientProperties[i].DispID == dispID) { + for (int i = 0; i < ambientProperties.Length; i++) + { + if (ambientProperties[i].DispID == dispID) + { ambientProperties[i].ResetValue(); CallParentPropertyChanged(control, ambientProperties[i].Name); return; @@ -15802,26 +18271,31 @@ internal void OnAmbientPropertyChange(int dispID) { // Special properties that we care about object obj = new object(); - switch (dispID) { + switch (dispID) + { case NativeMethods.ActiveX.DISPID_AMBIENT_UIDEAD: - if (GetAmbientProperty(NativeMethods.ActiveX.DISPID_AMBIENT_UIDEAD, ref obj)) { + if (GetAmbientProperty(NativeMethods.ActiveX.DISPID_AMBIENT_UIDEAD, ref obj)) + { activeXState[uiDead] = (bool)obj; } break; case NativeMethods.ActiveX.DISPID_AMBIENT_DISPLAYASDEFAULT: IButtonControl ibuttonControl = control as IButtonControl; - if (ibuttonControl != null && GetAmbientProperty(NativeMethods.ActiveX.DISPID_AMBIENT_DISPLAYASDEFAULT, ref obj)) { + if (ibuttonControl != null && GetAmbientProperty(NativeMethods.ActiveX.DISPID_AMBIENT_DISPLAYASDEFAULT, ref obj)) + { ibuttonControl.NotifyDefault((bool)obj); } break; } } - else { + else + { // Invalidate all properties. Ideally we should be checking each one, but // that's pretty expensive too. // - for (int i = 0; i < ambientProperties.Length; i++) { + for (int i = 0; i < ambientProperties.Length; i++) + { ambientProperties[i].ResetValue(); CallParentPropertyChanged(control, ambientProperties[i].Name); } @@ -15831,13 +18305,16 @@ internal void OnAmbientPropertyChange(int dispID) { /// /// Implements IOleInPlaceActiveObject::OnDocWindowActivate. /// - internal void OnDocWindowActivate(int fActivate) { - if (activeXState[uiActive] && fActivate != 0 && inPlaceFrame != null) { + internal void OnDocWindowActivate(int fActivate) + { + if (activeXState[uiActive] && fActivate != 0 && inPlaceFrame != null) + { // we have to explicitly say we don't wany any border space. // int hr = inPlaceFrame.SetBorderSpace(null); - if (NativeMethods.Failed(hr) && hr != NativeMethods.INPLACE_E_NOTOOLSPACE && hr != NativeMethods.E_NOTIMPL) { + if (NativeMethods.Failed(hr) && hr != NativeMethods.INPLACE_E_NOTOOLSPACE && hr != NativeMethods.E_NOTIMPL) + { Marshal.ThrowExceptionForHR(hr); } } @@ -15846,13 +18323,16 @@ internal void OnDocWindowActivate(int fActivate) { /// /// Called by Control when it gets the focus. /// - internal void OnFocus(bool focus) { + internal void OnFocus(bool focus) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AXSource: SetFocus: " + focus.ToString()); - if (activeXState[inPlaceActive] && clientSite is UnsafeNativeMethods.IOleControlSite) { + if (activeXState[inPlaceActive] && clientSite is UnsafeNativeMethods.IOleControlSite) + { ((UnsafeNativeMethods.IOleControlSite)clientSite).OnFocus(focus ? 1 : 0); } - if (focus && activeXState[inPlaceActive] && !activeXState[uiActive]) { + if (focus && activeXState[inPlaceActive] && !activeXState[uiActive]) + { InPlaceActivate(NativeMethods.OLEIVERB_UIACTIVATE); } } @@ -15860,7 +18340,8 @@ internal void OnFocus(bool focus) { /// /// Converts coordinates in pixels to HiMetric. /// - private Point PixelToHiMetric(int x, int y) { + private Point PixelToHiMetric(int x, int y) + { Point pt = new Point(); pt.X = (hiMetricPerInch * x + (LogPixels.X >> 1)) / LogPixels.X; pt.Y = (hiMetricPerInch * y + (LogPixels.Y >> 1)) / LogPixels.Y; @@ -15870,7 +18351,8 @@ private Point PixelToHiMetric(int x, int y) { /// /// Our implementation of IQuickActivate::QuickActivate /// - internal void QuickActivate(UnsafeNativeMethods.tagQACONTAINER pQaContainer, UnsafeNativeMethods.tagQACONTROL pQaControl) { + internal void QuickActivate(UnsafeNativeMethods.tagQACONTAINER pQaContainer, UnsafeNativeMethods.tagQACONTROL pQaControl) + { // Hookup our ambient colors // AmbientProperty prop = LookupAmbient(NativeMethods.ActiveX.DISPID_AMBIENT_BACKCOLOR); @@ -15881,7 +18363,8 @@ internal void QuickActivate(UnsafeNativeMethods.tagQACONTAINER pQaContainer, Uns // And our ambient font // - if (pQaContainer.pFont != null) { + if (pQaContainer.pFont != null) + { prop = LookupAmbient(NativeMethods.ActiveX.DISPID_AMBIENT_FONT); @@ -15894,8 +18377,10 @@ internal void QuickActivate(UnsafeNativeMethods.tagQACONTAINER pQaContainer, Uns Font font = Font.FromHfont(hfont); prop.Value = font; } - catch (Exception e) { - if (ClientUtils.IsSecurityOrCriticalException(e)) { + catch (Exception e) + { + if (ClientUtils.IsSecurityOrCriticalException(e)) + { throw; } @@ -15912,10 +18397,11 @@ internal void QuickActivate(UnsafeNativeMethods.tagQACONTAINER pQaContainer, Uns SetClientSite(pQaContainer.pClientSite); - if (pQaContainer.pAdviseSink != null) { + if (pQaContainer.pAdviseSink != null) + { SetAdvise(NativeMethods.DVASPECT_CONTENT, 0, (IAdviseSink)pQaContainer.pAdviseSink); } - + ((UnsafeNativeMethods.IOleObject)control).GetMiscStatus(NativeMethods.DVASPECT_CONTENT, out status); pQaControl.dwMiscStatus = status; @@ -15928,30 +18414,37 @@ internal void QuickActivate(UnsafeNativeMethods.tagQACONTAINER pQaContainer, Uns // Note that the AdviseHelper handles some non-standard COM interop that is required in order to access // the events on the CLR-supplied CCW (COM-callable Wrapper. - if ((pQaContainer.pUnkEventSink != null) && (control is UserControl)) { + if ((pQaContainer.pUnkEventSink != null) && (control is UserControl)) + { // Check if this control exposes events to COM. Type eventInterface = GetDefaultEventsInterface(control.GetType()); - if (eventInterface != null) { + if (eventInterface != null) + { - try { + try + { // For the default source interface, call IConnectionPoint.Advise with the supplied event sink. // This is easier said than done. See notes in AdviseHelper.AdviseConnectionPoint. AdviseHelper.AdviseConnectionPoint(control, pQaContainer.pUnkEventSink, eventInterface, out pQaControl.dwEventCookie); } - catch (Exception e) { - if (ClientUtils.IsSecurityOrCriticalException(e)) { + catch (Exception e) + { + if (ClientUtils.IsSecurityOrCriticalException(e)) + { throw; } } } } - if (pQaContainer.pPropertyNotifySink != null && Marshal.IsComObject(pQaContainer.pPropertyNotifySink)) { + if (pQaContainer.pPropertyNotifySink != null && Marshal.IsComObject(pQaContainer.pPropertyNotifySink)) + { Marshal.ReleaseComObject(pQaContainer.pPropertyNotifySink); } - if (pQaContainer.pUnkEventSink != null && Marshal.IsComObject(pQaContainer.pUnkEventSink)) { + if (pQaContainer.pUnkEventSink != null && Marshal.IsComObject(pQaContainer.pUnkEventSink)) + { Marshal.ReleaseComObject(pQaContainer.pUnkEventSink); } } @@ -15961,12 +18454,14 @@ internal void QuickActivate(UnsafeNativeMethods.tagQACONTAINER pQaContainer, Uns /// to a manage .NET event interface. /// The events are exposed to COM by the CLR-supplied COM-callable Wrapper (CCW). /// - internal static class AdviseHelper { + internal static class AdviseHelper + { /// /// Get the COM connection point container from the CLR's CCW and advise for the given event id. /// - public static bool AdviseConnectionPoint(object connectionPoint, object sink, Type eventInterface, out int cookie) { - + public static bool AdviseConnectionPoint(object connectionPoint, object sink, Type eventInterface, out int cookie) + { + // Note that we cannot simply cast the connectionPoint object to // System.Runtime.InteropServices.ComTypes.IConnectionPointContainer because the .NET // object doesn't implement it directly. When the object is exposed to COM, the CLR @@ -15975,7 +18470,8 @@ public static bool AdviseConnectionPoint(object connectionPoint, object sink, Ty // to to call the interface. // It is critical to call Dispose to ensure that the IUnknown is released. - using (ComConnectionPointContainer cpc = new ComConnectionPointContainer(connectionPoint, true)) { + using (ComConnectionPointContainer cpc = new ComConnectionPointContainer(connectionPoint, true)) + { return AdviseConnectionPoint(cpc, sink, eventInterface, out cookie); } } @@ -15984,16 +18480,19 @@ public static bool AdviseConnectionPoint(object connectionPoint, object sink, Ty /// Find the COM connection point and call Advise for the given event id. /// [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Runtime.InteropServices.SafeHandle.DangerousGetHandle")] - internal static bool AdviseConnectionPoint(ComConnectionPointContainer cpc, object sink, Type eventInterface, out int cookie) { - + internal static bool AdviseConnectionPoint(ComConnectionPointContainer cpc, object sink, Type eventInterface, out int cookie) + { + // Note that we cannot simply cast the returned IConnectionPoint to // System.Runtime.InteropServices.ComTypes.IConnectionPoint because the .NET // object doesn't implement it directly. When the object is exposed to COM, the CLR // implements IConnectionPoint for the proxy object via the CCW or COM-callable wrapper. // We use the helper class ComConnectionPoint to get to the CCW directly to to call the interface. // It is critical to call Dispose to ensure that the IUnknown is released. - using (ComConnectionPoint cp = cpc.FindConnectionPoint(eventInterface)) { - using (SafeIUnknown punkEventsSink = new SafeIUnknown(sink, true)) { + using (ComConnectionPoint cp = cpc.FindConnectionPoint(eventInterface)) + { + using (SafeIUnknown punkEventsSink = new SafeIUnknown(sink, true)) + { // Finally...we can call IConnectionPoint.Advise to hook up a native COM event sink // to a managed .NET event interface. return cp.Advise(punkEventsSink.DangerousGetHandle(), out cookie); @@ -16005,13 +18504,15 @@ internal static bool AdviseConnectionPoint(ComConnectionPointContainer cpc, obje /// Wraps a native IUnknown in a SafeHandle. /// See similar implementaton in the class. /// - internal class SafeIUnknown : SafeHandle { + internal class SafeIUnknown : SafeHandle + { /// /// Wrap an incomoing unknown or get the unknown for the CCW (COM-callable wrapper). /// public SafeIUnknown(object obj, bool addRefIntPtr) - : this(obj, addRefIntPtr, Guid.Empty) { + : this(obj, addRefIntPtr, Guid.Empty) + { } /// @@ -16019,42 +18520,52 @@ public SafeIUnknown(object obj, bool addRefIntPtr) /// If an iid is supplied, QI for the interface and wrap that unknonwn instead. /// public SafeIUnknown(object obj, bool addRefIntPtr, Guid iid) - : base(IntPtr.Zero, true) { + : base(IntPtr.Zero, true) + { System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { // Set this.handle in a finally block to ensure the com ptr is set in the SafeHandle // even if the runtime throws a exception (such as ThreadAbortException) during the call. // This ensures that the finalizer will clean up the COM reference. } - finally { - + finally + { + // Get a raw IUnknown for this object. // We are responsible for releasing the IUnknown ourselves. IntPtr unknown; - - if (obj is IntPtr) { + + if (obj is IntPtr) + { unknown = (IntPtr)obj; // The incoming IntPtr may already be reference counted or not, depending on // where it came from. The caller needs to tell us whether to add-ref or not. - if (addRefIntPtr) { + if (addRefIntPtr) + { Marshal.AddRef(unknown); } - } else { + } + else + { // GetIUnknownForObject will return a reference-counted object unknown = Marshal.GetIUnknownForObject(obj); } - + // Attempt QueryInterface if an iid is specified. - if (iid != Guid.Empty) { + if (iid != Guid.Empty) + { IntPtr oldUnknown = unknown; - try { + try + { unknown = InternalQueryInterface(unknown, ref iid); } - finally { + finally + { // It is critical to release the original unknown if // InternalQueryInterface throws out so we don't leak ref counts. Marshal.Release(oldUnknown); @@ -16069,10 +18580,12 @@ public SafeIUnknown(object obj, bool addRefIntPtr, Guid iid) /// /// Helper function for QueryInterface. /// - private static IntPtr InternalQueryInterface(IntPtr pUnk, ref Guid iid) { + private static IntPtr InternalQueryInterface(IntPtr pUnk, ref Guid iid) + { IntPtr ppv; int hresult = Marshal.QueryInterface(pUnk, ref iid, out ppv); - if (hresult != 0 || ppv == IntPtr.Zero) { + if (hresult != 0 || ppv == IntPtr.Zero) + { throw new InvalidCastException(SR.AxInterfaceNotSupported); } return ppv; @@ -16081,9 +18594,12 @@ private static IntPtr InternalQueryInterface(IntPtr pUnk, ref Guid iid) { /// /// Return whether the handle is invalid. /// - public sealed override bool IsInvalid { - get { - if (!base.IsClosed) { + public sealed override bool IsInvalid + { + get + { + if (!base.IsClosed) + { return (IntPtr.Zero == base.handle); } return true; @@ -16093,10 +18609,12 @@ public sealed override bool IsInvalid { /// /// Release the IUnknown. /// - protected sealed override bool ReleaseHandle() { + protected sealed override bool ReleaseHandle() + { IntPtr ptr1 = base.handle; base.handle = IntPtr.Zero; - if (IntPtr.Zero != ptr1) { + if (IntPtr.Zero != ptr1) + { Marshal.Release(ptr1); } return true; @@ -16105,7 +18623,8 @@ protected sealed override bool ReleaseHandle() { /// /// Helper function to load a COM v-table from a com object pointer. /// - protected V LoadVtable() { + protected V LoadVtable() + { IntPtr vtblptr = Marshal.ReadIntPtr(this.handle, 0); return Marshal.PtrToStructure(vtblptr); } @@ -16115,11 +18634,13 @@ protected V LoadVtable() { /// Helper class to access IConnectionPointContainer from a .NET COM-callable wrapper. /// The IConnectionPointContainer COM pointer is wrapped in a SafeHandle. /// - internal sealed class ComConnectionPointContainer - : SafeIUnknown { + internal sealed class ComConnectionPointContainer + : SafeIUnknown + { public ComConnectionPointContainer(object obj, bool addRefIntPtr) - : base(obj, addRefIntPtr, typeof(System.Runtime.InteropServices.ComTypes.IConnectionPointContainer).GUID) { + : base(obj, addRefIntPtr, typeof(System.Runtime.InteropServices.ComTypes.IConnectionPointContainer).GUID) + { this.vtbl = base.LoadVtable(); } @@ -16127,7 +18648,8 @@ public ComConnectionPointContainer(object obj, bool addRefIntPtr) [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] [StructLayout(LayoutKind.Sequential)] - private class VTABLE { + private class VTABLE + { public IntPtr QueryInterfacePtr; public IntPtr AddRefPtr; public IntPtr ReleasePtr; @@ -16138,13 +18660,15 @@ private class VTABLE { /// /// Call IConnectionPointContainer.FindConnectionPoint using Delegate.Invoke on the v-table slot. /// - public ComConnectionPoint FindConnectionPoint(Type eventInterface) { + public ComConnectionPoint FindConnectionPoint(Type eventInterface) + { FindConnectionPointD findConnectionPoint = (FindConnectionPointD)Marshal.GetDelegateForFunctionPointer(this.vtbl.FindConnectionPointPtr, typeof(FindConnectionPointD)); IntPtr result = IntPtr.Zero; Guid iid = eventInterface.GUID; int hresult = findConnectionPoint.Invoke(this.handle, ref iid, out result); - if (hresult != 0 || result == IntPtr.Zero) { + if (hresult != 0 || result == IntPtr.Zero) + { throw new ArgumentException(string.Format(SR.AXNoConnectionPoint, eventInterface.Name)); } @@ -16159,17 +18683,20 @@ public ComConnectionPoint FindConnectionPoint(Type eventInterface) { /// Helper class to access IConnectionPoint from a .NET COM-callable wrapper. /// The IConnectionPoint COM pointer is wrapped in a SafeHandle. /// - internal sealed class ComConnectionPoint - : SafeIUnknown { + internal sealed class ComConnectionPoint + : SafeIUnknown + { public ComConnectionPoint(object obj, bool addRefIntPtr) - : base(obj, addRefIntPtr, typeof(System.Runtime.InteropServices.ComTypes.IConnectionPoint).GUID) { + : base(obj, addRefIntPtr, typeof(System.Runtime.InteropServices.ComTypes.IConnectionPoint).GUID) + { this.vtbl = this.LoadVtable(); } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] [StructLayout(LayoutKind.Sequential)] - private class VTABLE { + private class VTABLE + { public IntPtr QueryInterfacePtr; public IntPtr AddRefPtr; public IntPtr ReleasePtr; @@ -16185,9 +18712,11 @@ private class VTABLE { /// /// Call IConnectioinPoint.Advise using Delegate.Invoke on the v-table slot. /// - public bool Advise(IntPtr punkEventSink, out int cookie) { + public bool Advise(IntPtr punkEventSink, out int cookie) + { AdviseD advise = (AdviseD)Marshal.GetDelegateForFunctionPointer(this.vtbl.AdvisePtr, typeof(AdviseD)); - if (advise.Invoke(this.handle, punkEventSink, out cookie) == 0) { + if (advise.Invoke(this.handle, punkEventSink, out cookie) == 0) + { return true; } return false; @@ -16204,16 +18733,19 @@ public bool Advise(IntPtr punkEventSink, out int cookie) { /// This looks for the ComSourceInterfacesAttribute and returns the .NET /// interface type of the first interface declared. /// - private static Type GetDefaultEventsInterface(Type controlType) { - + private static Type GetDefaultEventsInterface(Type controlType) + { + Type eventInterface = null; object[] custom = controlType.GetCustomAttributes(typeof(ComSourceInterfacesAttribute), false); - if (custom.Length > 0) { + if (custom.Length > 0) + { ComSourceInterfacesAttribute coms = (ComSourceInterfacesAttribute)custom[0]; string eventName = coms.Value.Split(new char[] { '\0' })[0]; eventInterface = controlType.Module.Assembly.GetType(eventName, false); - if (eventInterface == null) { + if (eventInterface == null) + { eventInterface = Type.GetType(eventName, false); } } @@ -16225,7 +18757,8 @@ private static Type GetDefaultEventsInterface(Type controlType) { /// /// Implements IPersistStorage::Save /// - internal void Save(UnsafeNativeMethods.IStorage stg, bool fSameAsLoad) { + internal void Save(UnsafeNativeMethods.IStorage stg, bool fSameAsLoad) + { UnsafeNativeMethods.IStream stream = stg.CreateStream(this.GetStreamName(), NativeMethods.STGM_WRITE | NativeMethods.STGM_SHARE_EXCLUSIVE | NativeMethods.STGM_CREATE, 0, 0); Debug.Assert(stream != null, "Stream should be non-null, or an exception should have been thrown."); Save(stream, true); @@ -16235,7 +18768,8 @@ internal void Save(UnsafeNativeMethods.IStorage stg, bool fSameAsLoad) { /// /// Implements IPersistStreamInit::Save /// - internal void Save(UnsafeNativeMethods.IStream stream, bool fClearDirty) { + internal void Save(UnsafeNativeMethods.IStream stream, bool fClearDirty) + { // We do everything through property bags because we support full fidelity // in them. So, save through that method. // @@ -16243,7 +18777,8 @@ internal void Save(UnsafeNativeMethods.IStream stream, bool fClearDirty) { Save(bag, fClearDirty, false); bag.Write(stream); - if (Marshal.IsComObject(stream)) { + if (Marshal.IsComObject(stream)) + { Marshal.ReleaseComObject(stream); } } @@ -16251,17 +18786,21 @@ internal void Save(UnsafeNativeMethods.IStream stream, bool fClearDirty) { /// /// Implements IPersistPropertyBag::Save /// - internal void Save(UnsafeNativeMethods.IPropertyBag pPropBag, bool fClearDirty, bool fSaveAllProperties) { + internal void Save(UnsafeNativeMethods.IPropertyBag pPropBag, bool fClearDirty, bool fSaveAllProperties) + { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(control, - new Attribute[] {DesignerSerializationVisibilityAttribute.Visible}); + new Attribute[] { DesignerSerializationVisibilityAttribute.Visible }); - for (int i = 0; i < props.Count; i++) { - if (fSaveAllProperties || props[i].ShouldSerializeValue(control)) { + for (int i = 0; i < props.Count; i++) + { + if (fSaveAllProperties || props[i].ShouldSerializeValue(control)) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "Saving property " + props[i].Name); object propValue; - if (IsResourceProp(props[i])) { + if (IsResourceProp(props[i])) + { // Resource property. Save this to the bag as a 64bit encoded string. // @@ -16274,18 +18813,21 @@ internal void Save(UnsafeNativeMethods.IPropertyBag pPropBag, bool fClearDirty, propValue = Convert.ToBase64String(bytes); pPropBag.Write(props[i].Name, ref propValue); } - else { + else + { // Not a resource property. Persist this using standard type converters. // TypeConverter converter = props[i].Converter; Debug.Assert(converter != null, "No type converter for property '" + props[i].Name + "' on class " + control.GetType().FullName); - if (converter.CanConvertFrom(typeof(string))) { + if (converter.CanConvertFrom(typeof(string))) + { propValue = converter.ConvertToInvariantString(props[i].GetValue(control)); pPropBag.Write(props[i].Name, ref propValue); } - else if (converter.CanConvertFrom(typeof(byte[]))) { + else if (converter.CanConvertFrom(typeof(byte[]))) + { byte[] data = (byte[])converter.ConvertTo(null, CultureInfo.InvariantCulture, props[i].GetValue(control), typeof(byte[])); propValue = Convert.ToBase64String(data); pPropBag.Write(props[i].Name, ref propValue); @@ -16294,11 +18836,13 @@ internal void Save(UnsafeNativeMethods.IPropertyBag pPropBag, bool fClearDirty, } } - if (Marshal.IsComObject(pPropBag)) { + if (Marshal.IsComObject(pPropBag)) + { Marshal.ReleaseComObject(pPropBag); } - if (fClearDirty) { + if (fClearDirty) + { activeXState[isDirty] = false; } } @@ -16307,9 +18851,11 @@ internal void Save(UnsafeNativeMethods.IPropertyBag pPropBag, bool fClearDirty, /// Fires the OnSave event to all of our IAdviseSink /// listeners. Used for ActiveXSourcing. /// - private void SendOnSave() { + private void SendOnSave() + { int cnt = adviseList.Count; - for (int i = 0; i < cnt; i++) { + for (int i = 0; i < cnt; i++) + { IAdviseSink s = (IAdviseSink)adviseList[i]; Debug.Assert(s != null, "NULL in our advise list"); s.OnSave(); @@ -16319,10 +18865,12 @@ private void SendOnSave() { /// /// Implements IViewObject2::SetAdvise. /// - internal void SetAdvise(int aspects, int advf, IAdviseSink pAdvSink) { + internal void SetAdvise(int aspects, int advf, IAdviseSink pAdvSink) + { // if it's not a content aspect, we don't support it. // - if ((aspects & NativeMethods.DVASPECT_CONTENT) == 0) { + if ((aspects & NativeMethods.DVASPECT_CONTENT) == 0) + { ThrowHr(NativeMethods.DV_E_DVASPECT); } @@ -16331,7 +18879,8 @@ internal void SetAdvise(int aspects, int advf, IAdviseSink pAdvSink) { activeXState[viewAdvisePrimeFirst] = (advf & NativeMethods.ADVF_PRIMEFIRST) != 0 ? true : false; activeXState[viewAdviseOnlyOnce] = (advf & NativeMethods.ADVF_ONLYONCE) != 0 ? true : false; - if (viewAdviseSink != null && Marshal.IsComObject(viewAdviseSink)) { + if (viewAdviseSink != null && Marshal.IsComObject(viewAdviseSink)) + { Marshal.ReleaseComObject(viewAdviseSink); } @@ -16339,7 +18888,8 @@ internal void SetAdvise(int aspects, int advf, IAdviseSink pAdvSink) { // prime them if they want it [we need to store this so they can get flags later] // - if (activeXState[viewAdvisePrimeFirst]) { + if (activeXState[viewAdvisePrimeFirst]) + { ViewChanged(); } } @@ -16347,13 +18897,17 @@ internal void SetAdvise(int aspects, int advf, IAdviseSink pAdvSink) { /// /// Implements IOleObject::SetClientSite. /// - internal void SetClientSite(UnsafeNativeMethods.IOleClientSite value) { - if (clientSite != null) { + internal void SetClientSite(UnsafeNativeMethods.IOleClientSite value) + { + if (clientSite != null) + { - if (value == null) { + if (value == null) + { globalActiveXCount--; - if (globalActiveXCount == 0 && IsIE) { + if (globalActiveXCount == 0 && IsIE) + { // This the last ActiveX control and we are // being hosted in IE. Use private reflection @@ -16364,52 +18918,63 @@ internal void SetClientSite(UnsafeNativeMethods.IOleClientSite value) { BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, new Type[0], new ParameterModifier[0]); Debug.Assert(method != null, "No Shutdown method on SystemEvents"); - if (method != null) { + if (method != null) + { method.Invoke(null, null); } } } - if (Marshal.IsComObject(clientSite)) { + if (Marshal.IsComObject(clientSite)) + { Marshal.FinalReleaseComObject(clientSite); } } clientSite = value; - if (clientSite != null) { + if (clientSite != null) + { control.Site = new AxSourcingSite(control, clientSite, "ControlAxSourcingSite"); } - else { + else + { control.Site = null; } // Get the ambient properties that effect us... // object obj = new object(); - if (GetAmbientProperty(NativeMethods.ActiveX.DISPID_AMBIENT_UIDEAD, ref obj)) { + if (GetAmbientProperty(NativeMethods.ActiveX.DISPID_AMBIENT_UIDEAD, ref obj)) + { activeXState[uiDead] = (bool)obj; } - if (control is IButtonControl && GetAmbientProperty(NativeMethods.ActiveX.DISPID_AMBIENT_UIDEAD, ref obj)) { + if (control is IButtonControl && GetAmbientProperty(NativeMethods.ActiveX.DISPID_AMBIENT_UIDEAD, ref obj)) + { ((IButtonControl)control).NotifyDefault((bool)obj); } - if (clientSite == null) { - if (accelTable != IntPtr.Zero) { + if (clientSite == null) + { + if (accelTable != IntPtr.Zero) + { UnsafeNativeMethods.DestroyAcceleratorTable(new HandleRef(this, accelTable)); accelTable = IntPtr.Zero; accelCount = -1; } - if (IsIE) { + if (IsIE) + { this.control.Dispose(); } } - else { + else + { globalActiveXCount++; - if (globalActiveXCount == 1 && IsIE) { + if (globalActiveXCount == 1 && IsIE) + { // This the first ActiveX control and we are // being hosted in IE. Use private reflection @@ -16423,7 +18988,8 @@ internal void SetClientSite(UnsafeNativeMethods.IOleClientSite value) { BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, new Type[0], new ParameterModifier[0]); Debug.Assert(method != null, "No Startup method on SystemEvents"); - if (method != null) { + if (method != null) + { method.Invoke(null, null); } } @@ -16434,25 +19000,31 @@ internal void SetClientSite(UnsafeNativeMethods.IOleClientSite value) { /// /// Implements IOleObject::SetExtent /// - internal void SetExtent(int dwDrawAspect, NativeMethods.tagSIZEL pSizel) { - if ((dwDrawAspect & NativeMethods.DVASPECT_CONTENT) != 0) { + internal void SetExtent(int dwDrawAspect, NativeMethods.tagSIZEL pSizel) + { + if ((dwDrawAspect & NativeMethods.DVASPECT_CONTENT) != 0) + { - if (activeXState[changingExtents]) { + if (activeXState[changingExtents]) + { return; } activeXState[changingExtents] = true; - try { + try + { Size size = new Size(HiMetricToPixel(pSizel.cx, pSizel.cy)); Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "SetExtent : new size:" + size.ToString()); // If we're in place active, let the in place site set our bounds. // Otherwise, just set it on our control directly. // - if (activeXState[inPlaceActive]) { + if (activeXState[inPlaceActive]) + { UnsafeNativeMethods.IOleInPlaceSite ioleClientSite = clientSite as UnsafeNativeMethods.IOleInPlaceSite; - if (ioleClientSite != null) { + if (ioleClientSite != null) + { Rectangle bounds = control.Bounds; bounds.Location = new Point(bounds.X, bounds.Y); Size adjusted = new Size(size.Width, size.Height); @@ -16471,30 +19043,35 @@ internal void SetExtent(int dwDrawAspect, NativeMethods.tagSIZEL pSizel) { // Check to see if the control overwrote our size with // its own values. // - if (!control.Size.Equals(size)) { + if (!control.Size.Equals(size)) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "SetExtent : Control has changed size. Setting dirty bit"); activeXState[isDirty] = true; // If we're not inplace active, then anounce that the view changed. // - if (!activeXState[inPlaceActive]) { + if (!activeXState[inPlaceActive]) + { ViewChanged(); } // We need to call RequestNewObjectLayout // here so we visually display our new extents. // - if (!activeXState[inPlaceActive] && clientSite != null) { + if (!activeXState[inPlaceActive] && clientSite != null) + { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "SetExtent : Requesting new Object layout."); clientSite.RequestNewObjectLayout(); } } } - finally { + finally + { activeXState[changingExtents] = false; } } - else { + else + { // We don't support any other aspects // ThrowHr(NativeMethods.DV_E_DVASPECT); @@ -16504,7 +19081,8 @@ internal void SetExtent(int dwDrawAspect, NativeMethods.tagSIZEL pSizel) { /// /// Marks our state as in place visible. /// - private void SetInPlaceVisible(bool visible) { + private void SetInPlaceVisible(bool visible) + { activeXState[inPlaceVisible] = visible; control.Visible = visible; } @@ -16512,21 +19090,25 @@ private void SetInPlaceVisible(bool visible) { /// /// Implements IOleInPlaceObject::SetObjectRects. /// - internal void SetObjectRects(NativeMethods.COMRECT lprcPosRect, NativeMethods.COMRECT lprcClipRect) { + internal void SetObjectRects(NativeMethods.COMRECT lprcPosRect, NativeMethods.COMRECT lprcClipRect) + { #if DEBUG - if (CompModSwitches.ActiveX.TraceInfo) { + if (CompModSwitches.ActiveX.TraceInfo) + { Debug.WriteLine("SetObjectRects:"); Debug.Indent(); - if (lprcPosRect != null) { + if (lprcPosRect != null) + { Debug.WriteLine("PosLeft: " + lprcPosRect.left.ToString(CultureInfo.InvariantCulture)); Debug.WriteLine("PosTop: " + lprcPosRect.top.ToString(CultureInfo.InvariantCulture)); Debug.WriteLine("PosRight: " + lprcPosRect.right.ToString(CultureInfo.InvariantCulture)); Debug.WriteLine("PosBottom: " + lprcPosRect.bottom.ToString(CultureInfo.InvariantCulture)); } - if (lprcClipRect != null) { + if (lprcClipRect != null) + { Debug.WriteLine("ClipLeft: " + lprcClipRect.left.ToString(CultureInfo.InvariantCulture)); Debug.WriteLine("ClipTop: " + lprcClipRect.top.ToString(CultureInfo.InvariantCulture)); Debug.WriteLine("ClipRight: " + lprcClipRect.right.ToString(CultureInfo.InvariantCulture)); @@ -16552,32 +19134,38 @@ internal void SetObjectRects(NativeMethods.COMRECT lprcPosRect, NativeMethods.CO // for the actual window change. // Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "Old Control Bounds: " + control.Bounds); - if (activeXState[adjustingRect]) { + if (activeXState[adjustingRect]) + { adjustRect.left = posRect.X; adjustRect.top = posRect.Y; adjustRect.right = posRect.Width + posRect.X; adjustRect.bottom = posRect.Height + posRect.Y; } - else { + else + { activeXState[adjustingRect] = true; - try { + try + { control.Bounds = posRect; } - finally { + finally + { activeXState[adjustingRect] = false; } } bool setRegion = false; - if (clipRegion != IntPtr.Zero) { + if (clipRegion != IntPtr.Zero) + { // Bad -- after calling SetWindowReg, windows owns the region. //SafeNativeMethods.DeleteObject(clipRegion); clipRegion = IntPtr.Zero; setRegion = true; } - if (lprcClipRect != null) { + if (lprcClipRect != null) + { // The container wants us to clip, so figure out if we really // need to. @@ -16594,19 +19182,20 @@ internal void SetObjectRects(NativeMethods.COMRECT lprcPosRect, NativeMethods.CO else intersect = posRect; - if (!intersect.Equals(posRect)) { + if (!intersect.Equals(posRect)) + { // Offset the rectangle back to client coordinates // NativeMethods.RECT rcIntersect = NativeMethods.RECT.FromXYWH(intersect.X, intersect.Y, intersect.Width, intersect.Height); IntPtr hWndParent = UnsafeNativeMethods.GetParent(new HandleRef(control, control.Handle)); - Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "Old Intersect: " + new Rectangle(rcIntersect.left, rcIntersect.top, rcIntersect.right-rcIntersect.left, rcIntersect.bottom-rcIntersect.top)); + Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "Old Intersect: " + new Rectangle(rcIntersect.left, rcIntersect.top, rcIntersect.right - rcIntersect.left, rcIntersect.bottom - rcIntersect.top)); Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "New Control Bounds: " + posRect); UnsafeNativeMethods.MapWindowPoints(new HandleRef(null, hWndParent), new HandleRef(control, control.Handle), ref rcIntersect, 2); - Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "New Intersect: " + new Rectangle(rcIntersect.left, rcIntersect.top, rcIntersect.right-rcIntersect.left, rcIntersect.bottom-rcIntersect.top)); + Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "New Intersect: " + new Rectangle(rcIntersect.left, rcIntersect.top, rcIntersect.right - rcIntersect.left, rcIntersect.bottom - rcIntersect.top)); // Create a Win32 region for it // @@ -16621,11 +19210,13 @@ internal void SetObjectRects(NativeMethods.COMRECT lprcPosRect, NativeMethods.CO // the handle has been created, since otherwise the control will // merge our region automatically. // - if (setRegion && control.IsHandleCreated) { + if (setRegion && control.IsHandleCreated) + { IntPtr finalClipRegion = clipRegion; Region controlRegion = control.Region; - if (controlRegion != null) { + if (controlRegion != null) + { IntPtr rgn = control.GetHRgn(controlRegion); finalClipRegion = MergeRegion(rgn); } @@ -16639,7 +19230,7 @@ internal void SetObjectRects(NativeMethods.COMRECT lprcPosRect, NativeMethods.CO control.Invalidate(); } - #if ACTIVEX_SOURCING +#if ACTIVEX_SOURCING // // This has been cut from the product. @@ -16665,12 +19256,13 @@ private void ShowProperties() { } } } - #endif +#endif /// /// Throws the given hresult. This is used by ActiveX sourcing. /// - internal static void ThrowHr(int hr) { + internal static void ThrowHr(int hr) + { ExternalException e = new ExternalException(SR.ExternalException, hr); throw e; } @@ -16678,14 +19270,18 @@ internal static void ThrowHr(int hr) { /// /// Handles IOleControl::TranslateAccelerator /// - internal int TranslateAccelerator(ref NativeMethods.MSG lpmsg) { - + internal int TranslateAccelerator(ref NativeMethods.MSG lpmsg) + { + #if DEBUG - if (CompModSwitches.ActiveX.TraceInfo) { - if (!control.IsHandleCreated) { + if (CompModSwitches.ActiveX.TraceInfo) + { + if (!control.IsHandleCreated) + { Debug.WriteLine("AxSource: TranslateAccelerator before handle creation"); } - else { + else + { Message m = Message.Create(lpmsg.hwnd, lpmsg.message, lpmsg.wParam, lpmsg.lParam); Debug.WriteLine("AxSource: TranslateAccelerator : " + m.ToString()); } @@ -16694,7 +19290,8 @@ internal int TranslateAccelerator(ref NativeMethods.MSG lpmsg) { bool needPreProcess = false; - switch (lpmsg.message) { + switch (lpmsg.message) + { case Interop.WindowMessages.WM_KEYDOWN: case Interop.WindowMessages.WM_SYSKEYDOWN: case Interop.WindowMessages.WM_CHAR: @@ -16705,11 +19302,14 @@ internal int TranslateAccelerator(ref NativeMethods.MSG lpmsg) { Message msg = Message.Create(lpmsg.hwnd, lpmsg.message, lpmsg.wParam, lpmsg.lParam); - if (needPreProcess) { + if (needPreProcess) + { Control target = Control.FromChildHandle(lpmsg.hwnd); - if (target != null && (control == target || control.Contains(target))) { + if (target != null && (control == target || control.Contains(target))) + { PreProcessControlState messageState = PreProcessControlMessageInternal(target, ref msg); - switch (messageState) { + switch (messageState) + { case PreProcessControlState.MessageProcessed: // someone returned true from PreProcessMessage // no need to dispatch the message, its already been coped with. @@ -16720,13 +19320,15 @@ internal int TranslateAccelerator(ref NativeMethods.MSG lpmsg) { case PreProcessControlState.MessageNeeded: // Here we need to dispatch the message ourselves // otherwise the host may never send the key to our wndproc. - + // Someone returned true from IsInputKey or IsInputChar UnsafeNativeMethods.TranslateMessage(ref lpmsg); - if (SafeNativeMethods.IsWindowUnicode(new HandleRef(null, lpmsg.hwnd))) { + if (SafeNativeMethods.IsWindowUnicode(new HandleRef(null, lpmsg.hwnd))) + { UnsafeNativeMethods.DispatchMessageW(ref lpmsg); } - else { + else + { UnsafeNativeMethods.DispatchMessageA(ref lpmsg); } return NativeMethods.S_OK; @@ -16738,32 +19340,38 @@ internal int TranslateAccelerator(ref NativeMethods.MSG lpmsg) { } // SITE processing. We're not interested in the message, but the site may be. - + int hr = NativeMethods.S_FALSE; Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource: Control did not process accelerator, handing to site"); - + UnsafeNativeMethods.IOleControlSite ioleClientSite = clientSite as UnsafeNativeMethods.IOleControlSite; - if (ioleClientSite != null) { + if (ioleClientSite != null) + { int keyState = 0; - - if (UnsafeNativeMethods.GetKeyState(NativeMethods.VK_SHIFT) < 0) keyState |= 1; - if (UnsafeNativeMethods.GetKeyState(NativeMethods.VK_CONTROL) < 0) keyState |= 2; - if (UnsafeNativeMethods.GetKeyState(NativeMethods.VK_MENU) < 0) keyState |= 4; + + if (UnsafeNativeMethods.GetKeyState(NativeMethods.VK_SHIFT) < 0) + keyState |= 1; + if (UnsafeNativeMethods.GetKeyState(NativeMethods.VK_CONTROL) < 0) + keyState |= 2; + if (UnsafeNativeMethods.GetKeyState(NativeMethods.VK_MENU) < 0) + keyState |= 4; hr = ioleClientSite.TranslateAccelerator(ref lpmsg, keyState); } - + return hr; } /// /// Implements IOleInPlaceObject::UIDeactivate. /// - internal int UIDeactivate() { + internal int UIDeactivate() + { // Only do this if we're UI active // - if (!activeXState[uiActive]) { + if (!activeXState[uiActive]) + { return NativeMethods.S_OK; } @@ -16771,7 +19379,8 @@ internal int UIDeactivate() { // Notify frame windows, if appropriate, that we're no longer ui-active. // - if (inPlaceUiWindow != null) { + if (inPlaceUiWindow != null) + { inPlaceUiWindow.SetActiveObject(null, null); } @@ -16780,7 +19389,8 @@ internal int UIDeactivate() { inPlaceFrame.SetActiveObject(null, null); UnsafeNativeMethods.IOleInPlaceSite ioleClientSite = clientSite as UnsafeNativeMethods.IOleInPlaceSite; - if (ioleClientSite != null) { + if (ioleClientSite != null) + { ioleClientSite.OnUIDeactivate(0); } @@ -16790,14 +19400,17 @@ internal int UIDeactivate() { /// /// Implements IOleObject::Unadvise /// - internal void Unadvise(int dwConnection) { - if (dwConnection > adviseList.Count || adviseList[dwConnection - 1] == null) { + internal void Unadvise(int dwConnection) + { + if (dwConnection > adviseList.Count || adviseList[dwConnection - 1] == null) + { ThrowHr(NativeMethods.OLE_E_NOCONNECTION); } IAdviseSink sink = (IAdviseSink)adviseList[dwConnection - 1]; adviseList.RemoveAt(dwConnection - 1); - if (sink != null && Marshal.IsComObject(sink)) { + if (sink != null && Marshal.IsComObject(sink)) + { Marshal.ReleaseComObject(sink); } } @@ -16805,26 +19418,33 @@ internal void Unadvise(int dwConnection) { /// /// Notifies our site that we have changed our size and location. /// - internal void UpdateBounds(ref int x, ref int y, ref int width, ref int height, int flags) { - if (!activeXState[adjustingRect] && activeXState[inPlaceVisible]) { + internal void UpdateBounds(ref int x, ref int y, ref int width, ref int height, int flags) + { + if (!activeXState[adjustingRect] && activeXState[inPlaceVisible]) + { UnsafeNativeMethods.IOleInPlaceSite ioleClientSite = clientSite as UnsafeNativeMethods.IOleInPlaceSite; - if (ioleClientSite != null) { + if (ioleClientSite != null) + { NativeMethods.COMRECT rc = new NativeMethods.COMRECT(); - if ((flags & NativeMethods.SWP_NOMOVE) != 0) { + if ((flags & NativeMethods.SWP_NOMOVE) != 0) + { rc.left = control.Left; rc.top = control.Top; } - else { + else + { rc.left = x; rc.top = y; } - if ((flags & NativeMethods.SWP_NOSIZE) != 0) { + if ((flags & NativeMethods.SWP_NOSIZE) != 0) + { rc.right = rc.left + control.Width; rc.bottom = rc.top + control.Height; } - else { + else + { rc.right = rc.left + width; rc.bottom = rc.top + height; } @@ -16833,20 +19453,24 @@ internal void UpdateBounds(ref int x, ref int y, ref int width, ref int height, adjustRect = rc; activeXState[adjustingRect] = true; - try { + try + { ioleClientSite.OnPosRectChange(rc); } - finally { + finally + { adjustRect = null; activeXState[adjustingRect] = false; } // On output, the new bounds will be reflected in rc - if ((flags & NativeMethods.SWP_NOMOVE) == 0) { + if ((flags & NativeMethods.SWP_NOMOVE) == 0) + { x = rc.left; y = rc.top; } - if ((flags & NativeMethods.SWP_NOSIZE) == 0) { + if ((flags & NativeMethods.SWP_NOSIZE) == 0) + { width = rc.right - rc.left; height = rc.bottom - rc.top; } @@ -16857,12 +19481,14 @@ internal void UpdateBounds(ref int x, ref int y, ref int width, ref int height, /// /// Notifies that the accelerator table needs to be updated due to a change in a control mnemonic. /// - internal void UpdateAccelTable(){ + internal void UpdateAccelTable() + { // Setting the count to -1 will recreate the table on demand (when GetControlInfo is called). this.accelCount = -1; UnsafeNativeMethods.IOleControlSite ioleClientSite = clientSite as UnsafeNativeMethods.IOleControlSite; - if (ioleClientSite != null) { + if (ioleClientSite != null) + { ioleClientSite.OnControlInfoChanged(); } } @@ -16877,18 +19503,22 @@ internal void ViewChangedInternal() /// Notifies our view advise sink (if it exists) that the view has /// changed. /// - private void ViewChanged() { + private void ViewChanged() + { // send the view change notification to anybody listening. // // Note: Word2000 won't resize components correctly if an OnViewChange notification // is sent while the component is persisting it's state. The !m_fSaving check // is to make sure we don't call OnViewChange in this case. // - if (viewAdviseSink != null && !activeXState[saving]) { + if (viewAdviseSink != null && !activeXState[saving]) + { viewAdviseSink.OnViewChange(NativeMethods.DVASPECT_CONTENT, -1); - if (activeXState[viewAdviseOnlyOnce]) { - if (Marshal.IsComObject(viewAdviseSink)) { + if (activeXState[viewAdviseOnlyOnce]) + { + if (Marshal.IsComObject(viewAdviseSink)) + { Marshal.ReleaseComObject(viewAdviseSink); } viewAdviseSink = null; @@ -16899,22 +19529,28 @@ private void ViewChanged() { /// /// Called when the window handle of the control has changed. /// - void IWindowTarget.OnHandleChange(IntPtr newHandle) { + void IWindowTarget.OnHandleChange(IntPtr newHandle) + { controlWindowTarget.OnHandleChange(newHandle); } /// /// Called to do control-specific processing for this window. /// - void IWindowTarget.OnMessage(ref Message m) { - if (activeXState[uiDead]) { - if (m.Msg >= Interop.WindowMessages.WM_MOUSEFIRST && m.Msg <= Interop.WindowMessages.WM_MOUSELAST) { + void IWindowTarget.OnMessage(ref Message m) + { + if (activeXState[uiDead]) + { + if (m.Msg >= Interop.WindowMessages.WM_MOUSEFIRST && m.Msg <= Interop.WindowMessages.WM_MOUSELAST) + { return; } - if (m.Msg >= Interop.WindowMessages.WM_NCLBUTTONDOWN && m.Msg <= Interop.WindowMessages.WM_NCMBUTTONDBLCLK) { + if (m.Msg >= Interop.WindowMessages.WM_NCLBUTTONDOWN && m.Msg <= Interop.WindowMessages.WM_NCMBUTTONDBLCLK) + { return; } - if (m.Msg >= Interop.WindowMessages.WM_KEYFIRST && m.Msg <= Interop.WindowMessages.WM_KEYLAST) { + if (m.Msg >= Interop.WindowMessages.WM_KEYFIRST && m.Msg <= Interop.WindowMessages.WM_KEYLAST) + { return; } } @@ -16926,10 +19562,12 @@ void IWindowTarget.OnMessage(ref Message m) { /// This is a property bag implementation that sits on a stream. It can /// read and write the bag to the stream. /// - private class PropertyBagStream : UnsafeNativeMethods.IPropertyBag { + private class PropertyBagStream : UnsafeNativeMethods.IPropertyBag + { private Hashtable bag = new Hashtable(); - internal void Read(UnsafeNativeMethods.IStream istream) { + internal void Read(UnsafeNativeMethods.IStream istream) + { // visual basic's memory streams don't support seeking, so we have to // work around this limitation here. We do this by copying // the contents of the stream into a MemoryStream object. @@ -16942,7 +19580,8 @@ internal void Read(UnsafeNativeMethods.IStream istream) { int count = stream.Read(streamData, offset, PAGE_SIZE); int totalCount = count; - while (count == PAGE_SIZE) { + while (count == PAGE_SIZE) + { byte[] newChunk = new byte[streamData.Length + PAGE_SIZE]; Array.Copy(streamData, newChunk, streamData.Length); streamData = newChunk; @@ -16955,11 +19594,14 @@ internal void Read(UnsafeNativeMethods.IStream istream) { stream = new MemoryStream(streamData); BinaryFormatter formatter = new BinaryFormatter(); - try { + try + { bag = (Hashtable)formatter.Deserialize(stream); } - catch (Exception e) { - if (ClientUtils.IsSecurityOrCriticalException(e)) { + catch (Exception e) + { + if (ClientUtils.IsSecurityOrCriticalException(e)) + { throw; } @@ -16992,44 +19634,54 @@ internal void Write(UnsafeNativeMethods.IStream istream) } } - private class AxSourcingSite : ISite { + private class AxSourcingSite : ISite + { private IComponent component; private UnsafeNativeMethods.IOleClientSite clientSite; private string name; private HtmlShimManager shimManager; - internal AxSourcingSite(IComponent component, UnsafeNativeMethods.IOleClientSite clientSite, string name) { + internal AxSourcingSite(IComponent component, UnsafeNativeMethods.IOleClientSite clientSite, string name) + { this.component = component; this.clientSite = clientSite; this.name = name; } /** The component sited by this component site. */ - public IComponent Component { - get { + public IComponent Component + { + get + { return component; } } /** The container in which the component is sited. */ - public IContainer Container { - get { + public IContainer Container + { + get + { return null; } } - public object GetService(Type service) { + public object GetService(Type service) + { object retVal = null; - if (service == typeof(HtmlDocument)) { + if (service == typeof(HtmlDocument)) + { UnsafeNativeMethods.IOleContainer iOlecontainer; int hr = clientSite.GetContainer(out iOlecontainer); if (NativeMethods.Succeeded(hr) - && (iOlecontainer is UnsafeNativeMethods.IHTMLDocument)) { - if (shimManager == null) { + && (iOlecontainer is UnsafeNativeMethods.IHTMLDocument)) + { + if (shimManager == null) + { shimManager = new HtmlShimManager(); } @@ -17037,7 +19689,8 @@ public object GetService(Type service) { } } - else if (clientSite.GetType().IsAssignableFrom(service)) { + else if (clientSite.GetType().IsAssignableFrom(service)) + { retVal = clientSite; } @@ -17045,8 +19698,10 @@ public object GetService(Type service) { } /** Indicates whether the component is in design mode. */ - public bool DesignMode { - get { + public bool DesignMode + { + get + { return false; } } @@ -17054,10 +19709,13 @@ public bool DesignMode { /** * The name of the component. */ - public string Name { - get { return name;} - set { - if (value == null || name == null) { + public string Name + { + get { return name; } + set + { + if (value == null || name == null) + { name = value; } } @@ -17069,28 +19727,35 @@ public string Name { /// and back. /// [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] - private class ActiveXFontMarshaler : ICustomMarshaler { + private class ActiveXFontMarshaler : ICustomMarshaler + { private static ActiveXFontMarshaler instance; - public void CleanUpManagedData(object obj) { + public void CleanUpManagedData(object obj) + { } - public void CleanUpNativeData(IntPtr pObj) { + public void CleanUpNativeData(IntPtr pObj) + { Marshal.Release(pObj); } - internal static ICustomMarshaler GetInstance(string cookie) { - if (instance == null) { + internal static ICustomMarshaler GetInstance(string cookie) + { + if (instance == null) + { instance = new ActiveXFontMarshaler(); } return instance; } - public int GetNativeDataSize() { + public int GetNativeDataSize() + { return -1; // not a value type, so use -1 } - public IntPtr MarshalManagedToNative(object obj) { + public IntPtr MarshalManagedToNative(object obj) + { Font font = (Font)obj; NativeMethods.tagFONTDESC fontDesc = new NativeMethods.tagFONTDESC(); NativeMethods.LOGFONT logFont = new NativeMethods.LOGFONT(); @@ -17115,24 +19780,29 @@ public IntPtr MarshalManagedToNative(object obj) { Marshal.Release(pFont); - if (NativeMethods.Failed(hr)) { + if (NativeMethods.Failed(hr)) + { Marshal.ThrowExceptionForHR(hr); } return pIFont; } - public object MarshalNativeToManaged(IntPtr pObj) { + public object MarshalNativeToManaged(IntPtr pObj) + { UnsafeNativeMethods.IFont nativeFont = (UnsafeNativeMethods.IFont)Marshal.GetObjectForIUnknown(pObj); IntPtr hfont = nativeFont.GetHFont(); Font font = null; - try { + try + { font = Font.FromHfont(hfont); } - catch (Exception e) { - if (ClientUtils.IsSecurityOrCriticalException(e)) { + catch (Exception e) + { + if (ClientUtils.IsSecurityOrCriticalException(e)) + { throw; } @@ -17146,24 +19816,29 @@ public object MarshalNativeToManaged(IntPtr pObj) { /// /// Simple verb enumerator. /// - private class ActiveXVerbEnum : UnsafeNativeMethods.IEnumOLEVERB { + private class ActiveXVerbEnum : UnsafeNativeMethods.IEnumOLEVERB + { private NativeMethods.tagOLEVERB[] verbs; private int current; - internal ActiveXVerbEnum(NativeMethods.tagOLEVERB[] verbs) { + internal ActiveXVerbEnum(NativeMethods.tagOLEVERB[] verbs) + { this.verbs = verbs; current = 0; } - public int Next(int celt, NativeMethods.tagOLEVERB rgelt, int[] pceltFetched) { + public int Next(int celt, NativeMethods.tagOLEVERB rgelt, int[] pceltFetched) + { int fetched = 0; - if (celt != 1) { + if (celt != 1) + { Debug.Fail("Caller of IEnumOLEVERB requested celt > 1, but clr marshalling does not support this."); celt = 1; } - while (celt > 0 && current < verbs.Length) { + while (celt > 0 && current < verbs.Length) + { rgelt.lVerb = verbs[current].lVerb; rgelt.lpszVerbName = verbs[current].lpszVerbName; rgelt.fuFlags = verbs[current].fuFlags; @@ -17173,39 +19848,47 @@ public int Next(int celt, NativeMethods.tagOLEVERB rgelt, int[] pceltFetched) { fetched++; } - if (pceltFetched != null) { + if (pceltFetched != null) + { pceltFetched[0] = fetched; } #if DEBUG - if (CompModSwitches.ActiveX.TraceInfo) { + if (CompModSwitches.ActiveX.TraceInfo) + { Debug.WriteLine("AxSource:IEnumOLEVERB::Next returning " + fetched.ToString(CultureInfo.InvariantCulture) + " verbs:"); Debug.Indent(); - for (int i = current - fetched; i < current; i++) { + for (int i = current - fetched; i < current; i++) + { Debug.WriteLine(i.ToString(CultureInfo.InvariantCulture) + ": " + verbs[i].lVerb + " " + (verbs[i].lpszVerbName == null ? string.Empty : verbs[i].lpszVerbName)); } Debug.Unindent(); } #endif - return(celt == 0 ? NativeMethods.S_OK : NativeMethods.S_FALSE); + return (celt == 0 ? NativeMethods.S_OK : NativeMethods.S_FALSE); } - public int Skip(int celt) { - if (current + celt < verbs.Length) { + public int Skip(int celt) + { + if (current + celt < verbs.Length) + { current += celt; return NativeMethods.S_OK; } - else { + else + { current = verbs.Length; return NativeMethods.S_FALSE; } } - public void Reset() { + public void Reset() + { current = 0; } - public void Clone(out UnsafeNativeMethods.IEnumOLEVERB ppenum) { + public void Clone(out UnsafeNativeMethods.IEnumOLEVERB ppenum) + { ppenum = new ActiveXVerbEnum(verbs); } } @@ -17264,7 +19947,8 @@ internal void Edit(object editingObject) { /// /// Contains a single ambient property, including DISPID, name and value. /// - private class AmbientProperty { + private class AmbientProperty + { private string name; private int dispID; private object value; @@ -17273,7 +19957,8 @@ private class AmbientProperty { /// /// Creates a new, empty ambient property. ///> - internal AmbientProperty(string name, int dispID) { + internal AmbientProperty(string name, int dispID) + { this.name = name; this.dispID = dispID; this.value = null; @@ -17283,8 +19968,10 @@ internal AmbientProperty(string name, int dispID) { /// /// The windows forms property name. /// - internal string Name { - get { + internal string Name + { + get + { return name; } } @@ -17292,8 +19979,10 @@ internal string Name { /// /// The DispID for the property. /// - internal int DispID { - get { + internal int DispID + { + get + { return dispID; } } @@ -17301,8 +19990,10 @@ internal int DispID { /// /// Returns true if this property has not been set. /// - internal bool Empty { - get { + internal bool Empty + { + get + { return empty; } } @@ -17310,11 +20001,14 @@ internal bool Empty { /// /// The current value of the property. /// - internal object Value { - get { + internal object Value + { + get + { return value; } - set { + set + { this.value = value; empty = false; } @@ -17323,7 +20017,8 @@ internal object Value { /// /// Resets the property. /// - internal void ResetValue() { + internal void ResetValue() + { empty = true; value = null; } @@ -17341,21 +20036,24 @@ internal void ResetValue() { /// } /// /// - private class MetafileDCWrapper : IDisposable { + private class MetafileDCWrapper : IDisposable + { - HandleRef hBitmapDC = NativeMethods.NullHandleRef; - HandleRef hBitmap = NativeMethods.NullHandleRef; - HandleRef hOriginalBmp = NativeMethods.NullHandleRef; - HandleRef hMetafileDC = NativeMethods.NullHandleRef; + HandleRef hBitmapDC = NativeMethods.NullHandleRef; + HandleRef hBitmap = NativeMethods.NullHandleRef; + HandleRef hOriginalBmp = NativeMethods.NullHandleRef; + HandleRef hMetafileDC = NativeMethods.NullHandleRef; NativeMethods.RECT destRect; [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] - internal MetafileDCWrapper(HandleRef hOriginalDC, Size size) { + internal MetafileDCWrapper(HandleRef hOriginalDC, Size size) + { Debug.Assert(UnsafeNativeMethods.GetObjectType(hOriginalDC) == NativeMethods.OBJ_ENHMETADC, "Why wrap a non-Enhanced MetaFile DC?"); // Security fix: make sure the size has non-negative width and height. - if (size.Width < 0 || size.Height < 0) { + if (size.Width < 0 || size.Height < 0) + { throw new ArgumentException(nameof(size), SR.ControlMetaFileDCWrapperSizeInvalid); } @@ -17370,18 +20068,22 @@ internal MetafileDCWrapper(HandleRef hOriginalDC, Size size) { hOriginalBmp = new HandleRef(this, SafeNativeMethods.SelectObject(hBitmapDC, hBitmap)); } - ~MetafileDCWrapper() { - ((IDisposable) this).Dispose(); + ~MetafileDCWrapper() + { + ((IDisposable)this).Dispose(); } - void IDisposable.Dispose() { - if (hBitmapDC.Handle == IntPtr.Zero || hMetafileDC.Handle == IntPtr.Zero || hBitmap.Handle == IntPtr.Zero) { + void IDisposable.Dispose() + { + if (hBitmapDC.Handle == IntPtr.Zero || hMetafileDC.Handle == IntPtr.Zero || hBitmap.Handle == IntPtr.Zero) + { return; } bool success; - try { + try + { success = DICopy(hMetafileDC, hBitmapDC, destRect, true); Debug.Assert(success, "DICopy() failed."); SafeNativeMethods.SelectObject(hBitmapDC, hOriginalBmp); @@ -17389,8 +20091,9 @@ void IDisposable.Dispose() { Debug.Assert(success, "DeleteObject() failed."); success = UnsafeNativeMethods.DeleteCompatibleDC(hBitmapDC); Debug.Assert(success, "DeleteObject() failed."); - } - finally { + } + finally + { // Dispose is done. Set all the handles to IntPtr.Zero so this way the Dispose method executes only once. hBitmapDC = NativeMethods.NullHandleRef; @@ -17401,12 +20104,14 @@ void IDisposable.Dispose() { } } - internal IntPtr HDC { + internal IntPtr HDC + { get { return hBitmapDC.Handle; } } // ported form VB6 (Ctls\PortUtil\StdCtl.cpp:6176) - private unsafe bool DICopy(HandleRef hdcDest, HandleRef hdcSrc, NativeMethods.RECT rect, bool bStretch) { + private unsafe bool DICopy(HandleRef hdcDest, HandleRef hdcSrc, NativeMethods.RECT rect, bool bStretch) + { long i; bool fSuccess = false; // Assume failure @@ -17414,11 +20119,14 @@ private unsafe bool DICopy(HandleRef hdcDest, HandleRef hdcSrc, NativeMethods.RE // // Get the bitmap from the DC by selecting in a 1x1 pixel temp bitmap HandleRef hNullBitmap = new HandleRef(this, SafeNativeMethods.CreateBitmap(1, 1, 1, 1, IntPtr.Zero)); - if (hNullBitmap.Handle == IntPtr.Zero) return fSuccess; + if (hNullBitmap.Handle == IntPtr.Zero) + return fSuccess; - try { + try + { HandleRef hBitmap = new HandleRef(this, SafeNativeMethods.SelectObject(hdcSrc, hNullBitmap)); - if (hBitmap.Handle == IntPtr.Zero) return fSuccess; + if (hBitmap.Handle == IntPtr.Zero) + return fSuccess; // // Restore original bitmap @@ -17426,7 +20134,8 @@ private unsafe bool DICopy(HandleRef hdcDest, HandleRef hdcSrc, NativeMethods.RE NativeMethods.BITMAP bmp = new NativeMethods.BITMAP(); - if (UnsafeNativeMethods.GetObject(hBitmap, Marshal.SizeOf(bmp), bmp) == 0) { + if (UnsafeNativeMethods.GetObject(hBitmap, Marshal.SizeOf(bmp), bmp) == 0) + { return fSuccess; } @@ -17442,22 +20151,26 @@ private unsafe bool DICopy(HandleRef hdcDest, HandleRef hdcSrc, NativeMethods.RE lpbmi.bmiHeader_biYPelsPerMeter = 0; lpbmi.bmiHeader_biClrUsed = 0; lpbmi.bmiHeader_biClrImportant = 0; - lpbmi.bmiColors = new byte[NativeMethods.BITMAPINFO_MAX_COLORSIZE*4]; + lpbmi.bmiColors = new byte[NativeMethods.BITMAPINFO_MAX_COLORSIZE * 4]; // // Include the palette for 256 color bitmaps long iColors = 1 << (bmp.bmBitsPixel * bmp.bmPlanes); - if (iColors <= 256) { + if (iColors <= 256) + { byte[] aj = new byte[Marshal.SizeOf() * 256]; SafeNativeMethods.GetSystemPaletteEntries(hdcSrc, 0, (int)iColors, aj); - fixed (byte* pcolors = lpbmi.bmiColors) { - fixed (byte* ppal = aj) { + fixed (byte* pcolors = lpbmi.bmiColors) + { + fixed (byte* ppal = aj) + { NativeMethods.RGBQUAD* prgb = (NativeMethods.RGBQUAD*)pcolors; NativeMethods.PALETTEENTRY* lppe = (NativeMethods.PALETTEENTRY*)ppal; // // Convert the palette entries to RGB quad entries - for (i = 0; i < (int)iColors; i++) { + for (i = 0; i < (int)iColors; i++) + { prgb[i].rgbRed = lppe[i].peRed; prgb[i].rgbBlue = lppe[i].peBlue; prgb[i].rgbGreen = lppe[i].peGreen; @@ -17477,7 +20190,8 @@ private unsafe bool DICopy(HandleRef hdcDest, HandleRef hdcSrc, NativeMethods.RE // Get the bitmap bits int diRet = SafeNativeMethods.GetDIBits(hdcSrc, hBitmap, 0, bmp.bmHeight, lpBits, ref lpbmi, NativeMethods.DIB_RGB_COLORS); - if (diRet == 0) return fSuccess; + if (diRet == 0) + return fSuccess; // // Set the destination coordiates depending on whether stretch-to-fit was chosen @@ -17501,11 +20215,13 @@ private unsafe bool DICopy(HandleRef hdcDest, HandleRef hdcSrc, NativeMethods.RE int iRet = SafeNativeMethods.StretchDIBits(hdcDest, xDest, yDest, cxDest, cyDest, 0, 0, bmp.bmWidth, bmp.bmHeight, lpBits, ref lpbmi, NativeMethods.DIB_RGB_COLORS, NativeMethods.SRCCOPY); - if (iRet == NativeMethods.GDI_ERROR) return fSuccess; + if (iRet == NativeMethods.GDI_ERROR) + return fSuccess; fSuccess = true; } - finally { + finally + { SafeNativeMethods.DeleteObject(hNullBitmap); } return fSuccess; @@ -17516,7 +20232,8 @@ private unsafe bool DICopy(HandleRef hdcDest, HandleRef hdcSrc, NativeMethods.RE /// An implementation of AccessibleChild for use with Controls /// [System.Runtime.InteropServices.ComVisible(true)] - public class ControlAccessibleObject : AccessibleObject { + public class ControlAccessibleObject : AccessibleObject + { private static IntPtr oleAccAvailable = NativeMethods.InvalidIntPtr; @@ -17528,10 +20245,12 @@ public class ControlAccessibleObject : AccessibleObject { // constructors - public ControlAccessibleObject(Control ownerControl) { + public ControlAccessibleObject(Control ownerControl) + { Debug.Assert(ownerControl != null, "Cannot construct a ControlAccessibleObject with a null ownerControl"); - if (ownerControl == null) { + if (ownerControl == null) + { throw new ArgumentNullException(nameof(ownerControl)); } @@ -17542,10 +20261,12 @@ public ControlAccessibleObject(Control ownerControl) { this.Handle = handle; } - internal ControlAccessibleObject(Control ownerControl, int accObjId) { + internal ControlAccessibleObject(Control ownerControl, int accObjId) + { Debug.Assert(ownerControl != null, "Cannot construct a ControlAccessibleObject with a null ownerControl"); - if (ownerControl == null) { + if (ownerControl == null) + { throw new ArgumentNullException(nameof(ownerControl)); } @@ -17564,7 +20285,8 @@ internal ControlAccessibleObject(Control ownerControl, int accObjId) { /// the user. The system defaults to z-order, which is bad for us because /// that is usually the reverse of tab order! /// - internal override int[] GetSysChildOrder() { + internal override int[] GetSysChildOrder() + { if (ownerControl.GetStyle(ControlStyles.ContainerControl)) return ownerControl.GetChildWindowsInTabOrder(); @@ -17602,37 +20324,42 @@ internal override int[] GetSysChildOrder() { /// allows us to present the end user with the illusion of accessible objects in /// tab index order, even though the system behavior only supports z-order. /// - internal override bool GetSysChild(AccessibleNavigation navdir, out AccessibleObject accessibleObject) { + internal override bool GetSysChild(AccessibleNavigation navdir, out AccessibleObject accessibleObject) + { // Clear the out parameter accessibleObject = null; // Get the owning control's parent, if it has one - Control parentControl = ownerControl.ParentInternal; + Control parentControl = ownerControl.ParentInternal; // ctrls[index] will indicate the control at the destination of this navigation operation int index = -1; Control[] ctrls = null; // Now handle any 'appropriate' navigation requests... - switch (navdir) { + switch (navdir) + { case AccessibleNavigation.FirstChild: - if (IsClientObject) { + if (IsClientObject) + { ctrls = ownerControl.GetChildControlsInTabOrder(true); index = 0; } break; case AccessibleNavigation.LastChild: - if (IsClientObject) { + if (IsClientObject) + { ctrls = ownerControl.GetChildControlsInTabOrder(true); index = ctrls.Length - 1; } break; case AccessibleNavigation.Previous: - if (IsNonClientObject && parentControl != null) { + if (IsNonClientObject && parentControl != null) + { ctrls = parentControl.GetChildControlsInTabOrder(true); index = Array.IndexOf(ctrls, ownerControl); if (index != -1) @@ -17641,7 +20368,8 @@ internal override bool GetSysChild(AccessibleNavigation navdir, out AccessibleOb break; case AccessibleNavigation.Next: - if (IsNonClientObject && parentControl != null) { + if (IsNonClientObject && parentControl != null) + { ctrls = parentControl.GetChildControlsInTabOrder(true); index = Array.IndexOf(ctrls, ownerControl); if (index != -1) @@ -17664,22 +20392,29 @@ internal override bool GetSysChild(AccessibleNavigation navdir, out AccessibleOb return true; } - public override string DefaultAction { - get { + public override string DefaultAction + { + get + { string defaultAction = ownerControl.AccessibleDefaultActionDescription; - if (defaultAction != null) { + if (defaultAction != null) + { return defaultAction; } - else { + else + { return base.DefaultAction; } } } // This is used only if control supports IAccessibleEx - internal override int[] RuntimeId { - get { - if (runtimeId == null) { + internal override int[] RuntimeId + { + get + { + if (runtimeId == null) + { runtimeId = new int[2]; runtimeId[0] = 0x2a; runtimeId[1] = (int)(long)this.Handle; @@ -17689,35 +20424,45 @@ internal override int[] RuntimeId { } } - public override string Description { - get { + public override string Description + { + get + { string description = ownerControl.AccessibleDescription; - if (description != null) { + if (description != null) + { return description; } - else { + else + { return base.Description; } } } - public IntPtr Handle { + public IntPtr Handle + { - get { + get + { return handle; } - set { - if (handle != value) { + set + { + if (handle != value) + { handle = value; - if (oleAccAvailable == IntPtr.Zero) { + if (oleAccAvailable == IntPtr.Zero) + { return; } bool freeLib = false; - if (oleAccAvailable == NativeMethods.InvalidIntPtr) { + if (oleAccAvailable == NativeMethods.InvalidIntPtr) + { oleAccAvailable = UnsafeNativeMethods.LoadLibraryFromSystemPathIfAvailable("oleacc.dll"); freeLib = (oleAccAvailable != IntPtr.Zero); } @@ -17726,11 +20471,13 @@ public IntPtr Handle { // We need to store internally the system provided // IAccessible, because some windows forms controls use it // as the default IAccessible implementation. - if (handle != IntPtr.Zero && oleAccAvailable != IntPtr.Zero) { + if (handle != IntPtr.Zero && oleAccAvailable != IntPtr.Zero) + { UseStdAccessibleObjects(handle); } - if (freeLib) { + if (freeLib) + { CommonUnsafeNativeMethods.FreeLibrary(new HandleRef(null, oleAccAvailable)); } @@ -17739,37 +20486,46 @@ public IntPtr Handle { } // end Handle - public override string Help { - get { + public override string Help + { + get + { QueryAccessibilityHelpEventHandler handler = (QueryAccessibilityHelpEventHandler)Owner.Events[EventQueryAccessibilityHelp]; - if (handler != null) { + if (handler != null) + { QueryAccessibilityHelpEventArgs args = new QueryAccessibilityHelpEventArgs(); handler(Owner, args); return args.HelpString; } - else { + else + { return base.Help; } } } - public override string KeyboardShortcut { - get { + public override string KeyboardShortcut + { + get + { // For controls, the default keyboard shortcut comes directly from the accessible // name property. This matches the default behavior of OLEACC.DLL exactly. char mnemonic = WindowsFormsUtils.GetMnemonic(this.TextLabel, false); - return (mnemonic == (char) 0) ? null : ("Alt+" + mnemonic); + return (mnemonic == (char)0) ? null : ("Alt+" + mnemonic); } } - public override string Name { - get { + public override string Name + { + get + { // Special case: If an explicit name has been set in the AccessibleName property, use that. // Note: Any non-null value in AccessibleName overrides the default accessible name logic, // even an empty string (this is the only way to *force* the accessible name to be blank). string name = ownerControl.AccessibleName; - if (name != null) { + if (name != null) + { return name; } @@ -17777,7 +20533,8 @@ public override string Name { return WindowsFormsUtils.TextWithoutMnemonics(TextLabel); } - set { + set + { // If anyone tries to set the accessible name, just cache the value in the control's // AccessibleName property. This value will then end up overriding the normal accessible // name logic, until such time as AccessibleName is set back to null. @@ -17785,8 +20542,10 @@ public override string Name { } } - public override AccessibleObject Parent { - get { + public override AccessibleObject Parent + { + get + { return base.Parent; } } @@ -17798,21 +20557,27 @@ public override AccessibleObject Parent { // except that OLEACC searches for preceding labels using z-order, and we want to search for labels using // TabIndex order. // - internal string TextLabel { - get { + internal string TextLabel + { + get + { // If owning control allows, use its Text property - but only if that Text is not empty - if (ownerControl.GetStyle(ControlStyles.UseTextForAccessibility)) { + if (ownerControl.GetStyle(ControlStyles.UseTextForAccessibility)) + { string text = ownerControl.Text; - if (!string.IsNullOrEmpty(text)) { + if (!string.IsNullOrEmpty(text)) + { return text; } } // Otherwise use the text of the preceding Label control, if there is one Label previousLabel = PreviousLabel; - if (previousLabel != null) { + if (previousLabel != null) + { string text = previousLabel.Text; - if (!string.IsNullOrEmpty(text)) { + if (!string.IsNullOrEmpty(text)) + { return text; } } @@ -17822,8 +20587,10 @@ internal string TextLabel { } } - public Control Owner { - get { + public Control Owner + { + get + { return ownerControl; } } @@ -17834,33 +20601,40 @@ public Control Owner { // This method aims to emulate the equivalent behavior in OLEACC.DLL, // but walking controls in TabIndex order rather than native z-order. // - internal Label PreviousLabel { - get { + internal Label PreviousLabel + { + get + { // Try to get to the parent of this control. - Control parent = Owner.ParentInternal; + Control parent = Owner.ParentInternal; - if (parent == null) { + if (parent == null) + { return null; } // Find this control's containing control ContainerControl container = parent.GetContainerControl() as ContainerControl; - if (container == null) { + if (container == null) + { return null; } // Walk backwards through peer controls... for (Control previous = container.GetNextControl(Owner, false); previous != null; - previous = container.GetNextControl(previous, false)) { + previous = container.GetNextControl(previous, false)) + { // Stop when we hit a Label (whether visible or invisible) - if (previous is Label) { + if (previous is Label) + { return previous as Label; } // Stop at any *visible* tab stop - if (previous.Visible && previous.TabStop) { + if (previous.Visible && previous.TabStop) + { break; } } @@ -17869,68 +20643,81 @@ internal Label PreviousLabel { } } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { AccessibleRole role = ownerControl.AccessibleRole; - if (role != AccessibleRole.Default) { + if (role != AccessibleRole.Default) + { return role; } - else { + else + { return base.Role; } } } - public override int GetHelpTopic(out string fileName) { + public override int GetHelpTopic(out string fileName) + { int topic = 0; QueryAccessibilityHelpEventHandler handler = (QueryAccessibilityHelpEventHandler)Owner.Events[EventQueryAccessibilityHelp]; - if (handler != null) { + if (handler != null) + { QueryAccessibilityHelpEventArgs args = new QueryAccessibilityHelpEventArgs(); handler(Owner, args); fileName = args.HelpNamespace; - try { + try + { topic = int.Parse(args.HelpKeyword, CultureInfo.InvariantCulture); } - catch (Exception e) { - if (ClientUtils.IsSecurityOrCriticalException(e)) { + catch (Exception e) + { + if (ClientUtils.IsSecurityOrCriticalException(e)) + { throw; } } return topic; } - else { + else + { return base.GetHelpTopic(out fileName); } } - public void NotifyClients(AccessibleEvents accEvent) { + public void NotifyClients(AccessibleEvents accEvent) + { Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "Control.NotifyClients: this = " + this.ToString() + ", accEvent = " + accEvent.ToString() + ", childID = self"); UnsafeNativeMethods.NotifyWinEvent((int)accEvent, new HandleRef(this, Handle), NativeMethods.OBJID_CLIENT, 0); } - public void NotifyClients(AccessibleEvents accEvent, int childID) { + public void NotifyClients(AccessibleEvents accEvent, int childID) + { Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "Control.NotifyClients: this = " + - this.ToString() + - ", accEvent = " + accEvent.ToString() + + this.ToString() + + ", accEvent = " + accEvent.ToString() + ", childID = " + childID.ToString(CultureInfo.InvariantCulture)); UnsafeNativeMethods.NotifyWinEvent((int)accEvent, new HandleRef(this, Handle), NativeMethods.OBJID_CLIENT, childID + 1); } - public void NotifyClients(AccessibleEvents accEvent, int objectID, int childID) { + public void NotifyClients(AccessibleEvents accEvent, int objectID, int childID) + { Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "Control.NotifyClients: this = " + - this.ToString() + - ", accEvent = " + accEvent.ToString() + + this.ToString() + + ", accEvent = " + accEvent.ToString() + ", childID = " + childID.ToString(CultureInfo.InvariantCulture)); UnsafeNativeMethods.NotifyWinEvent((int)accEvent, new HandleRef(this, Handle), objectID, childID + 1); @@ -17943,29 +20730,37 @@ public void NotifyClients(AccessibleEvents accEvent, int objectID, int childID) /// In addition, the applications must be recompiled to target .NET Framework 4.7.3 or opt in into this feature using compatibility switches. /// /// True if operation succeeds, False otherwise. - public override bool RaiseLiveRegionChanged() { - if (!(this.Owner is IAutomationLiveRegion)) { + public override bool RaiseLiveRegionChanged() + { + if (!(this.Owner is IAutomationLiveRegion)) + { throw new InvalidOperationException(SR.OwnerControlIsNotALiveRegion); } return RaiseAutomationEvent(NativeMethods.UIA_LiveRegionChangedEventId); } - internal override bool IsIAccessibleExSupported() { - if (this.Owner is IAutomationLiveRegion) { + internal override bool IsIAccessibleExSupported() + { + if (this.Owner is IAutomationLiveRegion) + { return true; } return base.IsIAccessibleExSupported(); } - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_LiveSettingPropertyId && Owner is IAutomationLiveRegion) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_LiveSettingPropertyId && Owner is IAutomationLiveRegion) + { return ((IAutomationLiveRegion)Owner).LiveSetting; } - if (Owner.SupportsUiaProviders) { - switch (propertyID) { + if (Owner.SupportsUiaProviders) + { + switch (propertyID) + { case NativeMethods.UIA_IsKeyboardFocusablePropertyId: return Owner.CanSelect; case NativeMethods.UIA_IsOffscreenPropertyId: @@ -17981,19 +20776,24 @@ internal override object GetPropertyValue(int propertyID) { return base.GetPropertyValue(propertyID); } - internal override UnsafeNativeMethods.IRawElementProviderSimple HostRawElementProvider { - get { + internal override UnsafeNativeMethods.IRawElementProviderSimple HostRawElementProvider + { + get + { UnsafeNativeMethods.IRawElementProviderSimple provider; UnsafeNativeMethods.UiaHostProviderFromHwnd(new HandleRef(this, Handle), out provider); return provider; } } - public override string ToString() { - if (Owner != null) { + public override string ToString() + { + if (Owner != null) + { return "ControlAccessibleObject: Owner = " + Owner.ToString(); } - else { + else + { return "ControlAccessibleObject: Owner = null"; } } @@ -18002,7 +20802,8 @@ public override string ToString() { // Fonts can be a pain to track, so we wrap Hfonts in this class to get a Finalize method. // - internal sealed class FontHandleWrapper : MarshalByRefObject, IDisposable { + internal sealed class FontHandleWrapper : MarshalByRefObject, IDisposable + { #if DEBUG private string stackOnCreate = null; private string stackOnDispose = null; @@ -18010,35 +20811,43 @@ internal sealed class FontHandleWrapper : MarshalByRefObject, IDisposable { #endif private IntPtr handle; - internal FontHandleWrapper(Font font) { + internal FontHandleWrapper(Font font) + { #if DEBUG - if (CompModSwitches.LifetimeTracing.Enabled) stackOnCreate = new System.Diagnostics.StackTrace().ToString(); + if (CompModSwitches.LifetimeTracing.Enabled) + stackOnCreate = new System.Diagnostics.StackTrace().ToString(); #endif handle = font.ToHfont(); Interop.HandleCollector.Add(handle, Interop.CommonHandles.GDI); } - internal IntPtr Handle { - get { + internal IntPtr Handle + { + get + { Debug.Assert(handle != IntPtr.Zero, "FontHandleWrapper disposed, but still being accessed"); return handle; } } - public void Dispose() { + public void Dispose() + { Dispose(true); GC.SuppressFinalize(this); } - private void Dispose(bool disposing) { + private void Dispose(bool disposing) + { #if DEBUG Debug.Assert(finalizing || this != defaultFontHandleWrapper, "Don't dispose the defaultFontHandleWrapper"); #endif - if (handle != IntPtr.Zero) { + if (handle != IntPtr.Zero) + { #if DEBUG - if (CompModSwitches.LifetimeTracing.Enabled) stackOnDispose = new System.Diagnostics.StackTrace().ToString(); + if (CompModSwitches.LifetimeTracing.Enabled) + stackOnDispose = new System.Diagnostics.StackTrace().ToString(); #endif SafeNativeMethods.DeleteObject(new HandleRef(this, handle)); handle = IntPtr.Zero; @@ -18046,7 +20855,8 @@ private void Dispose(bool disposing) { } - ~FontHandleWrapper() { + ~FontHandleWrapper() + { #if DEBUG finalizing = true; #endif @@ -18057,14 +20867,15 @@ private void Dispose(bool disposing) { /// /// Used with BeginInvoke/EndInvoke /// - private class ThreadMethodEntry : IAsyncResult { - internal Control caller; - internal Control marshaler; - internal Delegate method; + private class ThreadMethodEntry : IAsyncResult + { + internal Control caller; + internal Control marshaler; + internal Delegate method; internal object[] args; internal object retVal; internal Exception exception; - internal bool synchronous; + internal bool synchronous; private bool isCompleted; private ManualResetEvent resetEvent; private object invokeSyncObject = new object(); @@ -18079,7 +20890,8 @@ private class ThreadMethodEntry : IAsyncResult { // internal SynchronizationContext syncContext = null; - internal ThreadMethodEntry(Control caller, Control marshaler, Delegate method, object[] args, bool synchronous, ExecutionContext executionContext) { + internal ThreadMethodEntry(Control caller, Control marshaler, Delegate method, object[] args, bool synchronous, ExecutionContext executionContext) + { this.caller = caller; this.marshaler = marshaler; this.method = method; @@ -18100,34 +20912,44 @@ internal ThreadMethodEntry(Control caller, Control marshaler, Delegate method, o } } - public object AsyncState { - get { + public object AsyncState + { + get + { return null; } } - public WaitHandle AsyncWaitHandle { - get { - if (this.resetEvent == null) { + public WaitHandle AsyncWaitHandle + { + get + { + if (this.resetEvent == null) + { // Locking 'this' here is ok since this is an internal class. - lock (invokeSyncObject) { + lock (invokeSyncObject) + { // BeginInvoke hangs on Multi-proc system: // taking the lock prevents a race condition between IsCompleted // boolean flag and resetEvent mutex in multiproc scenarios. - if (this.resetEvent == null) { + if (this.resetEvent == null) + { this.resetEvent = new ManualResetEvent(false); - if (this.isCompleted) { + if (this.isCompleted) + { this.resetEvent.Set(); } - } + } } } - return(WaitHandle)this.resetEvent; + return (WaitHandle)this.resetEvent; } } - public bool CompletedSynchronously { - get { + public bool CompletedSynchronously + { + get + { if (this.isCompleted && this.synchronous) return true; @@ -18135,63 +20957,80 @@ public bool CompletedSynchronously { } } - public bool IsCompleted { - get { + public bool IsCompleted + { + get + { return this.isCompleted; } } - internal void Complete() { - lock (invokeSyncObject) { + internal void Complete() + { + lock (invokeSyncObject) + { this.isCompleted = true; - if (this.resetEvent != null) { + if (this.resetEvent != null) + { this.resetEvent.Set(); } } } } - private class ControlVersionInfo { + private class ControlVersionInfo + { private string companyName = null; private string productName = null; private string productVersion = null; private FileVersionInfo versionInfo = null; private Control owner; - internal ControlVersionInfo(Control owner) { + internal ControlVersionInfo(Control owner) + { this.owner = owner; } /// /// The company name associated with the component. /// - internal string CompanyName { - get { - if (companyName == null) { + internal string CompanyName + { + get + { + if (companyName == null) + { object[] attrs = owner.GetType().Module.Assembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false); - if (attrs != null && attrs.Length > 0) { + if (attrs != null && attrs.Length > 0) + { companyName = ((AssemblyCompanyAttribute)attrs[0]).Company; } - if (companyName == null || companyName.Length == 0) { + if (companyName == null || companyName.Length == 0) + { companyName = GetFileVersionInfo().CompanyName; - if (companyName != null) { + if (companyName != null) + { companyName = companyName.Trim(); } } - if (companyName == null || companyName.Length == 0) { + if (companyName == null || companyName.Length == 0) + { string ns = owner.GetType().Namespace; - if (ns == null) { + if (ns == null) + { ns = string.Empty; } int firstDot = ns.IndexOf('/'); - if (firstDot != -1) { + if (firstDot != -1) + { companyName = ns.Substring(0, firstDot); } - else { + else + { companyName = ns; } } @@ -18203,32 +21042,42 @@ internal string CompanyName { /// /// The product name associated with this component. /// - internal string ProductName { - get { - if (productName == null) { + internal string ProductName + { + get + { + if (productName == null) + { object[] attrs = owner.GetType().Module.Assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false); - if (attrs != null && attrs.Length > 0) { + if (attrs != null && attrs.Length > 0) + { productName = ((AssemblyProductAttribute)attrs[0]).Product; } - if (productName == null || productName.Length == 0) { + if (productName == null || productName.Length == 0) + { productName = GetFileVersionInfo().ProductName; - if (productName != null) { + if (productName != null) + { productName = productName.Trim(); } } - if (productName == null || productName.Length == 0) { + if (productName == null || productName.Length == 0) + { string ns = owner.GetType().Namespace; - if (ns == null) { + if (ns == null) + { ns = string.Empty; } int firstDot = ns.IndexOf('.'); - if (firstDot != -1) { - productName = ns.Substring(firstDot+1); + if (firstDot != -1) + { + productName = ns.Substring(firstDot + 1); } - else { + else + { productName = ns; } } @@ -18242,28 +21091,35 @@ internal string ProductName { /// /// The product version associated with this component. /// - internal string ProductVersion { - get { - if (productVersion == null) { + internal string ProductVersion + { + get + { + if (productVersion == null) + { // custom attribute // object[] attrs = owner.GetType().Module.Assembly.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false); - if (attrs != null && attrs.Length > 0) { + if (attrs != null && attrs.Length > 0) + { productVersion = ((AssemblyInformationalVersionAttribute)attrs[0]).InformationalVersion; } // win32 version info // - if (productVersion == null || productVersion.Length == 0) { + if (productVersion == null || productVersion.Length == 0) + { productVersion = GetFileVersionInfo().ProductVersion; - if (productVersion != null) { + if (productVersion != null) + { productVersion = productVersion.Trim(); } } // fake it // - if (productVersion == null || productVersion.Length == 0) { + if (productVersion == null || productVersion.Length == 0) + { productVersion = "1.0.0.0"; } } @@ -18275,8 +21131,10 @@ internal string ProductVersion { /// Retrieves the FileVersionInfo associated with the main module for /// the component. /// - private FileVersionInfo GetFileVersionInfo() { - if (versionInfo == null) { + private FileVersionInfo GetFileVersionInfo() + { + if (versionInfo == null) + { string path = owner.GetType().Module.FullyQualifiedName; versionInfo = FileVersionInfo.GetVersionInfo(path); @@ -18316,16 +21174,20 @@ void IDisposable.Dispose() } } - private sealed class PrintPaintEventArgs : PaintEventArgs { + private sealed class PrintPaintEventArgs : PaintEventArgs + { Message m; internal PrintPaintEventArgs(Message m, IntPtr dc, Rectangle clipRect) - : base(dc, clipRect) { + : base(dc, clipRect) + { this.m = m; } - internal Message Message { - get { + internal Message Message + { + get + { return m; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ControlPaint.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ControlPaint.cs index dcdf2d9cfa6..c51d1cbaac1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ControlPaint.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ControlPaint.cs @@ -6,7 +6,8 @@ -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.ComponentModel; using System.Diagnostics; @@ -22,115 +23,127 @@ namespace System.Windows.Forms { /// paint common Windows UI pieces. Many windows forms controls use this class to paint /// their UI elements. /// - public sealed class ControlPaint { + public sealed class ControlPaint + { [ThreadStatic] - private static Bitmap checkImage; // image used to render checkmarks + private static Bitmap checkImage; // image used to render checkmarks [ThreadStatic] - private static Pen focusPen; // pen used to draw a focus rectangle + private static Pen focusPen; // pen used to draw a focus rectangle [ThreadStatic] - private static Pen focusPenInvert; // pen used to draw a focus rectangle + private static Pen focusPenInvert; // pen used to draw a focus rectangle [ThreadStatic] - private static Color focusPenColor; // the last background color the focus pen was created with + private static Color focusPenColor; // the last background color the focus pen was created with [ThreadStatic] - private static bool hcFocusPen; // cached focus pen intended for high contrast mode - private static Pen grabPenPrimary; // pen used for primary grab handles - private static Pen grabPenSecondary; // pen used for secondary grab handles - private static Brush grabBrushPrimary; // brush used for primary grab handles - private static Brush grabBrushSecondary; // brush used for secondary grab handles + private static bool hcFocusPen; // cached focus pen intended for high contrast mode + private static Pen grabPenPrimary; // pen used for primary grab handles + private static Pen grabPenSecondary; // pen used for secondary grab handles + private static Brush grabBrushPrimary; // brush used for primary grab handles + private static Brush grabBrushSecondary; // brush used for secondary grab handles [ThreadStatic] - private static Brush frameBrushActive; // brush used for the active selection frame - private static Color frameColorActive; // color of active frame brush + private static Brush frameBrushActive; // brush used for the active selection frame + private static Color frameColorActive; // color of active frame brush [ThreadStatic] - private static Brush frameBrushSelected; // brush used for the inactive selection frame - private static Color frameColorSelected; // color of selected frame brush + private static Brush frameBrushSelected; // brush used for the inactive selection frame + private static Color frameColorSelected; // color of selected frame brush [ThreadStatic] - private static Brush gridBrush; // brush used to draw a grid - private static Size gridSize; // the dimensions of the grid dots - private static bool gridInvert; // true if the grid color is inverted + private static Brush gridBrush; // brush used to draw a grid + private static Size gridSize; // the dimensions of the grid dots + private static bool gridInvert; // true if the grid color is inverted [ThreadStatic] private static ImageAttributes disabledImageAttr; // ImageAttributes used to render disabled images //use these value to signify ANY of the right, top, left, center, or bottom alignments with the ContentAlignment enum. - private static readonly ContentAlignment anyRight = ContentAlignment.TopRight | ContentAlignment.MiddleRight | ContentAlignment.BottomRight; + private static readonly ContentAlignment anyRight = ContentAlignment.TopRight | ContentAlignment.MiddleRight | ContentAlignment.BottomRight; private static readonly ContentAlignment anyBottom = ContentAlignment.BottomLeft | ContentAlignment.BottomCenter | ContentAlignment.BottomRight; private static readonly ContentAlignment anyCenter = ContentAlignment.TopCenter | ContentAlignment.MiddleCenter | ContentAlignment.BottomCenter; private static readonly ContentAlignment anyMiddle = ContentAlignment.MiddleLeft | ContentAlignment.MiddleCenter | ContentAlignment.MiddleRight; - + // not creatable... // - private ControlPaint() { + private ControlPaint() + { } - internal static Rectangle CalculateBackgroundImageRectangle(Rectangle bounds, Image backgroundImage, ImageLayout imageLayout) { + internal static Rectangle CalculateBackgroundImageRectangle(Rectangle bounds, Image backgroundImage, ImageLayout imageLayout) + { - Rectangle result = bounds; + Rectangle result = bounds; - if (backgroundImage != null) { - switch (imageLayout) { - case ImageLayout.Stretch: - result.Size = bounds.Size; - break; + if (backgroundImage != null) + { + switch (imageLayout) + { + case ImageLayout.Stretch: + result.Size = bounds.Size; + break; - case ImageLayout.None: - result.Size = backgroundImage.Size; - break; + case ImageLayout.None: + result.Size = backgroundImage.Size; + break; - case ImageLayout.Center: - result.Size = backgroundImage.Size; - Size szCtl = bounds.Size; - - if (szCtl.Width > result.Width) { - result.X = (szCtl.Width - result.Width) / 2; - } - if (szCtl.Height > result.Height) { - result.Y = (szCtl.Height - result.Height) / 2; - } - break; + case ImageLayout.Center: + result.Size = backgroundImage.Size; + Size szCtl = bounds.Size; + + if (szCtl.Width > result.Width) + { + result.X = (szCtl.Width - result.Width) / 2; + } + if (szCtl.Height > result.Height) + { + result.Y = (szCtl.Height - result.Height) / 2; + } + break; - case ImageLayout.Zoom: + case ImageLayout.Zoom: Size imageSize = backgroundImage.Size; float xRatio = (float)bounds.Width / (float)imageSize.Width; float yRatio = (float)bounds.Height / (float)imageSize.Height; - if (xRatio < yRatio) { + if (xRatio < yRatio) + { //width should fill the entire bounds. result.Width = bounds.Width; // preserve the aspect ratio by multiplying the xRatio by the height // adding .5 to round to the nearest pixel - result.Height = (int) ((imageSize.Height * xRatio) +.5); + result.Height = (int)((imageSize.Height * xRatio) + .5); if (bounds.Y >= 0) - { - result.Y = (bounds.Height - result.Height) /2; + { + result.Y = (bounds.Height - result.Height) / 2; } } - else { + else + { // width should fill the entire bounds - result.Height = bounds.Height; + result.Height = bounds.Height; // preserve the aspect ratio by multiplying the xRatio by the height // adding .5 to round to the nearest pixel - result.Width = (int) ((imageSize.Width * yRatio) +.5); + result.Width = (int)((imageSize.Width * yRatio) + .5); if (bounds.X >= 0) { - result.X = (bounds.Width - result.Width) /2; + result.X = (bounds.Width - result.Width) / 2; } } - + break; - } - } - return result; - } + } + } + return result; + } // a color appropriate for certain elements that are ControlDark in normal color schemes, // but for which ControlDark does not work in high contrast color schemes - public static Color ContrastControlDark { - get { + public static Color ContrastControlDark + { + get + { return SystemInformation.HighContrast ? SystemColors.WindowFrame : SystemColors.ControlDark; } } // Returns address of a BITMAPINFO for use by CreateHBITMAP16Bit. // The caller is resposible for freeing the memory returned by this method. - private static IntPtr CreateBitmapInfo(Bitmap bitmap, IntPtr hdcS) { + private static IntPtr CreateBitmapInfo(Bitmap bitmap, IntPtr hdcS) + { NativeMethods.BITMAPINFOHEADER header = new NativeMethods.BITMAPINFOHEADER(); header.biSize = Marshal.SizeOf(header); header.biWidth = bitmap.Width; @@ -147,7 +160,8 @@ private static IntPtr CreateBitmapInfo(Bitmap bitmap, IntPtr hdcS) { int[] entries = new int[entryCount]; SafeNativeMethods.GetPaletteEntries(new HandleRef(null, palette), 0, entryCount, entries); int[] colors = new int[entryCount]; - for (int i = 0; i < entryCount; i++) { + for (int i = 0; i < entryCount; i++) + { int entry = entries[i]; colors[i] = (entry & unchecked((int)0xff000000)) >> 6 // red @@ -156,7 +170,7 @@ private static IntPtr CreateBitmapInfo(Bitmap bitmap, IntPtr hdcS) { } SafeNativeMethods.DeleteObject(new HandleRef(null, palette)); - IntPtr address = Marshal.AllocCoTaskMem(Marshal.SizeOf(header) + entryCount*4); + IntPtr address = Marshal.AllocCoTaskMem(Marshal.SizeOf(header) + entryCount * 4); Marshal.StructureToPtr(header, address, false); Marshal.Copy(colors, 0, (IntPtr)((long)address + Marshal.SizeOf(header)), entryCount); return address; @@ -168,14 +182,17 @@ private static IntPtr CreateBitmapInfo(Bitmap bitmap, IntPtr hdcS) { /// From MSDN: /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// - public static IntPtr CreateHBitmap16Bit(Bitmap bitmap, Color background) { + public static IntPtr CreateHBitmap16Bit(Bitmap bitmap, Color background) + { IntPtr hBitmap; Size size = bitmap.Size; - using( DeviceContext screenDc = DeviceContext.ScreenDC ){ + using (DeviceContext screenDc = DeviceContext.ScreenDC) + { IntPtr hdcS = screenDc.Hdc; - using( DeviceContext compatDc = DeviceContext.FromCompatibleDC( hdcS ) ){ + using (DeviceContext compatDc = DeviceContext.FromCompatibleDC(hdcS)) + { IntPtr dc = compatDc.Hdc; byte[] enoughBits = new byte[bitmap.Width * bitmap.Height]; @@ -185,27 +202,33 @@ public static IntPtr CreateHBitmap16Bit(Bitmap bitmap, Color background) { Marshal.FreeCoTaskMem(bitmapInfo); - if (hBitmap == IntPtr.Zero) { + if (hBitmap == IntPtr.Zero) + { throw new Win32Exception(); } - - try { + + try + { IntPtr previousBitmap = SafeNativeMethods.SelectObject(new HandleRef(null, dc), new HandleRef(null, hBitmap)); - if (previousBitmap == IntPtr.Zero) { + if (previousBitmap == IntPtr.Zero) + { throw new Win32Exception(); } - SafeNativeMethods.DeleteObject( new HandleRef( null, previousBitmap ) ); + SafeNativeMethods.DeleteObject(new HandleRef(null, previousBitmap)); - using( Graphics graphics = Graphics.FromHdcInternal(dc) ) { - using( Brush brush = new SolidBrush(background) ) { + using (Graphics graphics = Graphics.FromHdcInternal(dc)) + { + using (Brush brush = new SolidBrush(background)) + { graphics.FillRectangle(brush, 0, 0, size.Width, size.Height); } graphics.DrawImage(bitmap, 0, 0, size.Width, size.Height); } } - catch{ - SafeNativeMethods.DeleteObject( new HandleRef( null, hBitmap ) ); + catch + { + SafeNativeMethods.DeleteObject(new HandleRef(null, hBitmap)); throw; } } @@ -221,8 +244,10 @@ public static IntPtr CreateHBitmap16Bit(Bitmap bitmap, Color background) { /// From MSDN: /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// - public static IntPtr CreateHBitmapTransparencyMask(Bitmap bitmap) { - if (bitmap == null) { + public static IntPtr CreateHBitmapTransparencyMask(Bitmap bitmap) + { + if (bitmap == null) + { throw new ArgumentNullException(nameof(bitmap)); } Size size = bitmap.Size; @@ -238,20 +263,23 @@ public static IntPtr CreateHBitmapTransparencyMask(Bitmap bitmap) { monochromeStride++; byte[] bits = new byte[monochromeStride * height]; - BitmapData data = bitmap.LockBits(new Rectangle(0,0, width, height), + BitmapData data = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); Debug.Assert(data.Scan0 != IntPtr.Zero, "BitmapData.Scan0 is null; check marshalling"); - for (int y = 0; y < height; y++) { + for (int y = 0; y < height; y++) + { IntPtr scan = (IntPtr)((long)data.Scan0 + y * data.Stride); - for (int x = 0; x < width; x++) { - int color = Marshal.ReadInt32(scan, x*4); - if (color >> 24 == 0) { + for (int x = 0; x < width; x++) + { + int color = Marshal.ReadInt32(scan, x * 4); + if (color >> 24 == 0) + { // pixel is transparent; set bit to 1 int index = monochromeStride * y + x / 8; - bits[index] |= (byte) (0x80 >> (x % 8)); + bits[index] |= (byte)(0x80 >> (x % 8)); } } } @@ -270,7 +298,8 @@ public static IntPtr CreateHBitmapTransparencyMask(Bitmap bitmap) { /// From MSDN: /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// - public static IntPtr CreateHBitmapColorMask(Bitmap bitmap, IntPtr monochromeMask) { + public static IntPtr CreateHBitmapColorMask(Bitmap bitmap, IntPtr monochromeMask) + { Size size = bitmap.Size; IntPtr colorMask = bitmap.GetHbitmap(); @@ -301,7 +330,8 @@ public static IntPtr CreateHBitmapColorMask(Bitmap bitmap, IntPtr monochromeMask return Interop.HandleCollector.Add(colorMask, Interop.CommonHandles.GDI); } - internal static IntPtr CreateHalftoneHBRUSH() { + internal static IntPtr CreateHalftoneHBRUSH() + { short[] grayPattern = new short[8]; for (int i = 0; i < 8; i++) grayPattern[i] = (short)(0x5555 << (i & 1)); @@ -318,25 +348,29 @@ internal static IntPtr CreateHalftoneHBRUSH() { } // roughly the same code as in Graphics.cs - internal static void CopyPixels(IntPtr sourceHwnd, IDeviceContext targetDC, Point sourceLocation, Point destinationLocation, Size blockRegionSize, CopyPixelOperation copyPixelOperation) { + internal static void CopyPixels(IntPtr sourceHwnd, IDeviceContext targetDC, Point sourceLocation, Point destinationLocation, Size blockRegionSize, CopyPixelOperation copyPixelOperation) + { int destWidth = blockRegionSize.Width; int destHeight = blockRegionSize.Height; DeviceContext dc = DeviceContext.FromHwnd(sourceHwnd); - HandleRef targetHDC = new HandleRef( null, targetDC.GetHdc()); - HandleRef screenHDC = new HandleRef( null, dc.Hdc ); - - try { - bool result = SafeNativeMethods.BitBlt(targetHDC, destinationLocation.X, destinationLocation.Y, destWidth, destHeight, + HandleRef targetHDC = new HandleRef(null, targetDC.GetHdc()); + HandleRef screenHDC = new HandleRef(null, dc.Hdc); + + try + { + bool result = SafeNativeMethods.BitBlt(targetHDC, destinationLocation.X, destinationLocation.Y, destWidth, destHeight, screenHDC, - sourceLocation.X, sourceLocation.Y, (int) copyPixelOperation); - + sourceLocation.X, sourceLocation.Y, (int)copyPixelOperation); + //a zero result indicates a win32 exception has been thrown - if (!result) { + if (!result) + { throw new Win32Exception(); } } - finally { + finally + { targetDC.ReleaseHdc(); dc.Dispose(); } @@ -345,40 +379,49 @@ internal static void CopyPixels(IntPtr sourceHwnd, IDeviceContext targetDC, Poin /// /// Draws a border of the specified style and color to the given graphics. /// - private static DashStyle BorderStyleToDashStyle(ButtonBorderStyle borderStyle) { - switch (borderStyle) { - case ButtonBorderStyle.Dotted: return DashStyle.Dot; - case ButtonBorderStyle.Dashed: return DashStyle.Dash; - case ButtonBorderStyle.Solid: return DashStyle.Solid; + private static DashStyle BorderStyleToDashStyle(ButtonBorderStyle borderStyle) + { + switch (borderStyle) + { + case ButtonBorderStyle.Dotted: + return DashStyle.Dot; + case ButtonBorderStyle.Dashed: + return DashStyle.Dash; + case ButtonBorderStyle.Solid: + return DashStyle.Solid; default: Debug.Fail("border style has no corresponding dash style"); return DashStyle.Solid; } - } + } /// /// Creates a new color that is a object of the given color. /// - public static Color Dark(Color baseColor, float percOfDarkDark) { + public static Color Dark(Color baseColor, float percOfDarkDark) + { return new HLSColor(baseColor).Darker(percOfDarkDark); } /// /// Creates a new color that is a object of the given color. /// - public static Color Dark(Color baseColor) { + public static Color Dark(Color baseColor) + { return new HLSColor(baseColor).Darker(0.5f); } /// /// Creates a new color that is a object of the given color. /// - public static Color DarkDark(Color baseColor) { + public static Color DarkDark(Color baseColor) + { return new HLSColor(baseColor).Darker(1.0f); } //returns true if the luminosity of c1 is less than c2. - internal static bool IsDarker(Color c1, Color c2) { + internal static bool IsDarker(Color c1, Color c2) + { HLSColor hc1 = new HLSColor(c1); HLSColor hc2 = new HLSColor(c2); return (hc1.Luminosity < hc2.Luminosity); @@ -389,11 +432,14 @@ internal static bool IsDarker(Color c1, Color c2) { /// paint borders for UserPaint controls that were relying on /// their window style to provide their borders. /// - internal static void PrintBorder(Graphics graphics, Rectangle bounds, BorderStyle style, Border3DStyle b3dStyle) { - if (graphics == null) { + internal static void PrintBorder(Graphics graphics, Rectangle bounds, BorderStyle style, Border3DStyle b3dStyle) + { + if (graphics == null) + { throw new ArgumentNullException(nameof(graphics)); } - switch (style) { + switch (style) + { case BorderStyle.FixedSingle: ControlPaint.DrawBorder(graphics, bounds, Color.FromKnownColor(KnownColor.WindowFrame), ButtonBorderStyle.Solid); break; @@ -407,42 +453,51 @@ internal static void PrintBorder(Graphics graphics, Rectangle bounds, BorderStyl break; } } - internal static void DrawBackgroundImage(Graphics g, Image backgroundImage, Color backColor, ImageLayout backgroundImageLayout, Rectangle bounds, Rectangle clipRect) { - DrawBackgroundImage(g, backgroundImage, backColor, backgroundImageLayout, bounds, clipRect, Point.Empty, RightToLeft.No); + internal static void DrawBackgroundImage(Graphics g, Image backgroundImage, Color backColor, ImageLayout backgroundImageLayout, Rectangle bounds, Rectangle clipRect) + { + DrawBackgroundImage(g, backgroundImage, backColor, backgroundImageLayout, bounds, clipRect, Point.Empty, RightToLeft.No); } - internal static void DrawBackgroundImage(Graphics g, Image backgroundImage, Color backColor, ImageLayout backgroundImageLayout, Rectangle bounds, Rectangle clipRect, Point scrollOffset) { - DrawBackgroundImage(g, backgroundImage, backColor, backgroundImageLayout, bounds, clipRect, scrollOffset, RightToLeft.No); + internal static void DrawBackgroundImage(Graphics g, Image backgroundImage, Color backColor, ImageLayout backgroundImageLayout, Rectangle bounds, Rectangle clipRect, Point scrollOffset) + { + DrawBackgroundImage(g, backgroundImage, backColor, backgroundImageLayout, bounds, clipRect, scrollOffset, RightToLeft.No); } - - internal static void DrawBackgroundImage(Graphics g, Image backgroundImage, Color backColor, ImageLayout backgroundImageLayout, Rectangle bounds, Rectangle clipRect, Point scrollOffset, RightToLeft rightToLeft) { - if (g == null) { + + internal static void DrawBackgroundImage(Graphics g, Image backgroundImage, Color backColor, ImageLayout backgroundImageLayout, Rectangle bounds, Rectangle clipRect, Point scrollOffset, RightToLeft rightToLeft) + { + if (g == null) + { throw new ArgumentNullException(nameof(g)); } - - if(backgroundImageLayout == ImageLayout.Tile) { + + if (backgroundImageLayout == ImageLayout.Tile) + { // tile - - using (TextureBrush textureBrush = new TextureBrush(backgroundImage,WrapMode.Tile)) { - // Make sure the brush origin matches the display rectangle, not the client rectangle, - // so the background image scrolls on AutoScroll forms. - if (scrollOffset != Point.Empty) { - Matrix transform = textureBrush.Transform; - transform.Translate(scrollOffset.X,scrollOffset.Y); - textureBrush.Transform = transform; - } - g.FillRectangle(textureBrush, clipRect); - } - } - - else { + + using (TextureBrush textureBrush = new TextureBrush(backgroundImage, WrapMode.Tile)) + { + // Make sure the brush origin matches the display rectangle, not the client rectangle, + // so the background image scrolls on AutoScroll forms. + if (scrollOffset != Point.Empty) + { + Matrix transform = textureBrush.Transform; + transform.Translate(scrollOffset.X, scrollOffset.Y); + textureBrush.Transform = transform; + } + g.FillRectangle(textureBrush, clipRect); + } + } + + else + { // Center, Stretch, Zoom - + Rectangle imageRectangle = CalculateBackgroundImageRectangle(bounds, backgroundImage, backgroundImageLayout); //flip the coordinates only if we don't do any layout, since otherwise the image should be at the center of the //displayRectangle anyway. - - if (rightToLeft == RightToLeft.Yes && backgroundImageLayout == ImageLayout.None) { + + if (rightToLeft == RightToLeft.Yes && backgroundImageLayout == ImageLayout.None) + { imageRectangle.X += clipRect.Width - imageRectangle.Width; } @@ -450,16 +505,20 @@ internal static void DrawBackgroundImage(Graphics g, Image backgroundImage, Colo // Also, if gdi+ can't quite fill the rect with the image, they will interpolate the remaining // pixels, and make them semi-transparent. This is another reason why we need to fill the entire rect. // If we didn't where ever the image was transparent, we would get garbage. - using (SolidBrush brush = new SolidBrush(backColor)) { + using (SolidBrush brush = new SolidBrush(backColor)) + { g.FillRectangle(brush, clipRect); } - if (!clipRect.Contains(imageRectangle)) { - if (backgroundImageLayout == ImageLayout.Stretch || backgroundImageLayout == ImageLayout.Zoom) { + if (!clipRect.Contains(imageRectangle)) + { + if (backgroundImageLayout == ImageLayout.Stretch || backgroundImageLayout == ImageLayout.Zoom) + { imageRectangle.Intersect(clipRect); g.DrawImage(backgroundImage, imageRectangle); } - else if (backgroundImageLayout == ImageLayout.None) { + else if (backgroundImageLayout == ImageLayout.None) + { imageRectangle.Offset(clipRect.Location); Rectangle imageRect = imageRectangle; imageRect.Intersect(clipRect); @@ -467,7 +526,8 @@ internal static void DrawBackgroundImage(Graphics g, Image backgroundImage, Colo g.DrawImage(backgroundImage, imageRect, partOfImageToDraw.X, partOfImageToDraw.Y, partOfImageToDraw.Width, partOfImageToDraw.Height, GraphicsUnit.Pixel); } - else { + else + { Rectangle imageRect = imageRectangle; imageRect.Intersect(clipRect); Rectangle partOfImageToDraw = new Rectangle(new Point(imageRect.X - imageRectangle.X, imageRect.Y - imageRectangle.Y) @@ -477,23 +537,26 @@ internal static void DrawBackgroundImage(Graphics g, Image backgroundImage, Colo partOfImageToDraw.Height, GraphicsUnit.Pixel); } } - else { + else + { ImageAttributes imageAttrib = new ImageAttributes(); imageAttrib.SetWrapMode(WrapMode.TileFlipXY); g.DrawImage(backgroundImage, imageRectangle, 0, 0, backgroundImage.Width, backgroundImage.Height, GraphicsUnit.Pixel, imageAttrib); imageAttrib.Dispose(); - + } - } + } } - public static void DrawBorder(Graphics graphics, Rectangle bounds, Color color, ButtonBorderStyle style) { + public static void DrawBorder(Graphics graphics, Rectangle bounds, Color color, ButtonBorderStyle style) + { // Optimized version - switch (style) { + switch (style) + { case ButtonBorderStyle.None: // nothing break; - + case ButtonBorderStyle.Dotted: case ButtonBorderStyle.Dashed: case ButtonBorderStyle.Solid: @@ -518,9 +581,11 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, Color leftColor, int leftWidth, ButtonBorderStyle leftStyle, Color topColor, int topWidth, ButtonBorderStyle topStyle, Color rightColor, int rightWidth, ButtonBorderStyle rightStyle, - Color bottomColor, int bottomWidth, ButtonBorderStyle bottomStyle) { + Color bottomColor, int bottomWidth, ButtonBorderStyle bottomStyle) + { // Very general, and very slow - if (graphics == null) { + if (graphics == null) + { throw new ArgumentNullException(nameof(graphics)); } @@ -535,15 +600,17 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, float topToLeft = 0.0f; float bottomToLeft = 0.0f; - if (leftWidth > 0) { - topToLeft = ((float)topWidth)/((float)leftWidth); - bottomToLeft = ((float)bottomWidth)/((float)leftWidth); + if (leftWidth > 0) + { + topToLeft = ((float)topWidth) / ((float)leftWidth); + bottomToLeft = ((float)bottomWidth) / ((float)leftWidth); } float topToRight = 0.0f; float bottomToRight = 0.0f; - if (rightWidth > 0) { - topToRight = ((float)topWidth)/((float)rightWidth); - bottomToRight = ((float)bottomWidth)/((float)rightWidth); + if (rightWidth > 0) + { + topToRight = ((float)topWidth) / ((float)rightWidth); + bottomToRight = ((float)bottomWidth) / ((float)rightWidth); } HLSColor topHLSColor = new HLSColor(topColor); @@ -551,74 +618,96 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, HLSColor bottomHLSColor = new HLSColor(bottomColor); HLSColor rightHLSColor = new HLSColor(rightColor); - if (topWidth > 0) { - int i=0; - for (; i 0) + { + int i = 0; + for (; i < topWidth; i++) + { int leftOffset = 0; - if (topToLeft > 0) { + if (topToLeft > 0) + { leftOffset = (int)(((float)i) / topToLeft); } int rightOffset = 0; - if (topToRight > 0) { + if (topToRight > 0) + { rightOffset = (int)(((float)i) / topToRight); } topLineLefts[i] = bounds.X + leftOffset; topLineRights[i] = bounds.X + bounds.Width - rightOffset - 1; - if (leftWidth > 0) { + if (leftWidth > 0) + { leftLineTops[leftOffset] = bounds.Y + i + 1; } - if (rightWidth > 0) { + if (rightWidth > 0) + { rightLineTops[rightOffset] = bounds.Y + i; } } - for (int j=i; j 0) { - int i=0; - for (; i 0) + { + int i = 0; + for (; i < bottomWidth; i++) + { int leftOffset = 0; - if (bottomToLeft > 0) { + if (bottomToLeft > 0) + { leftOffset = (int)(((float)i) / bottomToLeft); } int rightOffset = 0; - if (bottomToRight > 0) { + if (bottomToRight > 0) + { rightOffset = (int)(((float)i) / bottomToRight); } bottomLineLefts[i] = bounds.X + leftOffset; bottomLineRights[i] = bounds.X + bounds.Width - rightOffset - 1; - if (leftWidth > 0) { + if (leftWidth > 0) + { leftLineBottoms[leftOffset] = bounds.Y + bounds.Height - i - 1; } - if (rightWidth > 0) { + if (rightWidth > 0) + { rightLineBottoms[rightOffset] = bounds.Y + bounds.Height - i - 1; } } - for (int j=i; j - public static void DrawBorder3D(Graphics graphics, Rectangle rectangle) { + public static void DrawBorder3D(Graphics graphics, Rectangle rectangle) + { DrawBorder3D(graphics, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, Border3DStyle.Etched, Border3DSide.Left | Border3DSide.Top | Border3DSide.Right | Border3DSide.Bottom); } @@ -856,7 +978,8 @@ public static void DrawBorder3D(Graphics graphics, Rectangle rectangle) { /// Draws a 3D style border at the given rectangle. You may specify the style /// of the 3D appearance. /// - public static void DrawBorder3D(Graphics graphics, Rectangle rectangle, Border3DStyle style) { + public static void DrawBorder3D(Graphics graphics, Rectangle rectangle, Border3DStyle style) + { DrawBorder3D(graphics, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, style, Border3DSide.Left | Border3DSide.Top | Border3DSide.Right | Border3DSide.Bottom); } @@ -866,7 +989,8 @@ public static void DrawBorder3D(Graphics graphics, Rectangle rectangle, Border3D /// of the 3D appearance, and which sides of the 3D rectangle you wish to /// draw. /// - public static void DrawBorder3D(Graphics graphics, Rectangle rectangle, Border3DStyle style, Border3DSide sides) { + public static void DrawBorder3D(Graphics graphics, Rectangle rectangle, Border3DStyle style, Border3DSide sides) + { DrawBorder3D(graphics, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, style, sides); } @@ -874,7 +998,8 @@ public static void DrawBorder3D(Graphics graphics, Rectangle rectangle, Border3D /// Draws a 3D style border at the given rectangle. The default 3D style of /// ETCHED is used. /// - public static void DrawBorder3D(Graphics graphics, int x, int y, int width, int height) { + public static void DrawBorder3D(Graphics graphics, int x, int y, int width, int height) + { DrawBorder3D(graphics, x, y, width, height, Border3DStyle.Etched, Border3DSide.Left | Border3DSide.Top | Border3DSide.Right | Border3DSide.Bottom); } @@ -883,7 +1008,8 @@ public static void DrawBorder3D(Graphics graphics, int x, int y, int width, int /// Draws a 3D style border at the given rectangle. You may specify the style /// of the 3D appearance. /// - public static void DrawBorder3D(Graphics graphics, int x, int y, int width, int height, Border3DStyle style) { + public static void DrawBorder3D(Graphics graphics, int x, int y, int width, int height, Border3DStyle style) + { DrawBorder3D(graphics, x, y, width, height, style, Border3DSide.Left | Border3DSide.Top | Border3DSide.Right | Border3DSide.Bottom); } @@ -893,8 +1019,10 @@ public static void DrawBorder3D(Graphics graphics, int x, int y, int width, int /// of the 3D appearance, and which sides of the 3D rectangle you wish to /// draw. /// - public static void DrawBorder3D(Graphics graphics, int x, int y, int width, int height, Border3DStyle style, Border3DSide sides) { - if (graphics == null) { + public static void DrawBorder3D(Graphics graphics, int x, int y, int width, int height, Border3DStyle style, Border3DSide sides) + { + if (graphics == null) + { throw new ArgumentNullException(nameof(graphics)); } @@ -910,7 +1038,8 @@ public static void DrawBorder3D(Graphics graphics, int x, int y, int width, int // and enlarge the rectangle so the client size is // preserved. // - if ((flags & (int)Border3DStyle.Adjust) == (int)Border3DStyle.Adjust) { + if ((flags & (int)Border3DStyle.Adjust) == (int)Border3DStyle.Adjust) + { Size sz = SystemInformation.Border3DSize; rc.left -= sz.Width; rc.right += sz.Width; @@ -919,35 +1048,39 @@ public static void DrawBorder3D(Graphics graphics, int x, int y, int width, int flags &= ~((int)Border3DStyle.Adjust); } - using( WindowsGraphics wg = WindowsGraphics.FromGraphics(graphics)) { // Get Win32 dc with Graphics properties applied to it. + using (WindowsGraphics wg = WindowsGraphics.FromGraphics(graphics)) + { // Get Win32 dc with Graphics properties applied to it. SafeNativeMethods.DrawEdge(new HandleRef(wg, wg.DeviceContext.Hdc), ref rc, edge, flags); } } - + /// /// Helper function that draws a more complex border. This is used by DrawBorder for less common /// rendering cases. We split DrawBorder into DrawBorderSimple and DrawBorderComplex so we maximize /// the % of the function call. It is less performant to have large functions that do many things. /// - private static void DrawBorderComplex(Graphics graphics, Rectangle bounds, Color color, ButtonBorderStyle style) { - if (graphics == null) { + private static void DrawBorderComplex(Graphics graphics, Rectangle bounds, Color color, ButtonBorderStyle style) + { + if (graphics == null) + { throw new ArgumentNullException(nameof(graphics)); } - if (style == ButtonBorderStyle.Inset) { // button being pushed + if (style == ButtonBorderStyle.Inset) + { // button being pushed HLSColor hls = new HLSColor(color); // top + left Pen pen = new Pen(hls.Darker(1.0f)); - graphics.DrawLine(pen, bounds.X, bounds.Y, + graphics.DrawLine(pen, bounds.X, bounds.Y, bounds.X + bounds.Width - 1, bounds.Y); - graphics.DrawLine(pen, bounds.X, bounds.Y, + graphics.DrawLine(pen, bounds.X, bounds.Y, bounds.X, bounds.Y + bounds.Height - 1); // bottom + right pen.Color = hls.Lighter(1.0f); - graphics.DrawLine(pen, bounds.X, bounds.Y + bounds.Height - 1, + graphics.DrawLine(pen, bounds.X, bounds.Y + bounds.Height - 1, bounds.X + bounds.Width - 1, bounds.Y + bounds.Height - 1); - graphics.DrawLine(pen, bounds.X + bounds.Width - 1, bounds.Y, + graphics.DrawLine(pen, bounds.X + bounds.Width - 1, bounds.Y, bounds.X + bounds.Width - 1, bounds.Y + bounds.Height - 1); // Top + left inset @@ -958,7 +1091,8 @@ private static void DrawBorderComplex(Graphics graphics, Rectangle bounds, Color bounds.X + 1, bounds.Y + bounds.Height - 2); // bottom + right inset - if (color.ToKnownColor() == SystemColors.Control.ToKnownColor()) { + if (color.ToKnownColor() == SystemColors.Control.ToKnownColor()) + { pen.Color = SystemColors.ControlLight; graphics.DrawLine(pen, bounds.X + 1, bounds.Y + bounds.Height - 2, bounds.X + bounds.Width - 2, bounds.Y + bounds.Height - 2); @@ -968,9 +1102,10 @@ private static void DrawBorderComplex(Graphics graphics, Rectangle bounds, Color pen.Dispose(); } - else { // Standard button + else + { // Standard button Debug.Assert(style == ButtonBorderStyle.Outset, "Caller should have known how to use us."); - + bool stockColor = color.ToKnownColor() == SystemColors.Control.ToKnownColor(); HLSColor hls = new HLSColor(color); @@ -978,29 +1113,35 @@ private static void DrawBorderComplex(Graphics graphics, Rectangle bounds, Color Pen pen = stockColor ? SystemPens.ControlLightLight : new Pen(hls.Lighter(1.0f)); graphics.DrawLine(pen, bounds.X, bounds.Y, bounds.X + bounds.Width - 1, bounds.Y); - graphics.DrawLine(pen, bounds.X, bounds.Y, + graphics.DrawLine(pen, bounds.X, bounds.Y, bounds.X, bounds.Y + bounds.Height - 1); // bottom + right - if (stockColor) { + if (stockColor) + { pen = SystemPens.ControlDarkDark; } - else { + else + { pen.Color = hls.Darker(1.0f); } - graphics.DrawLine(pen, bounds.X, bounds.Y + bounds.Height - 1, + graphics.DrawLine(pen, bounds.X, bounds.Y + bounds.Height - 1, bounds.X + bounds.Width - 1, bounds.Y + bounds.Height - 1); - graphics.DrawLine(pen, bounds.X + bounds.Width - 1, bounds.Y, + graphics.DrawLine(pen, bounds.X + bounds.Width - 1, bounds.Y, bounds.X + bounds.Width - 1, bounds.Y + bounds.Height - 1); // top + left inset - if (stockColor) { - if (SystemInformation.HighContrast) { + if (stockColor) + { + if (SystemInformation.HighContrast) + { pen = SystemPens.ControlLight; } - else { + else + { pen = SystemPens.Control; } } - else { + else + { pen.Color = color; } graphics.DrawLine(pen, bounds.X + 1, bounds.Y + 1, @@ -1009,10 +1150,12 @@ private static void DrawBorderComplex(Graphics graphics, Rectangle bounds, Color bounds.X + 1, bounds.Y + bounds.Height - 2); // Bottom + right inset - if (stockColor) { + if (stockColor) + { pen = SystemPens.ControlDark; } - else { + else + { pen.Color = hls.Darker(0.5f); } @@ -1020,127 +1163,146 @@ private static void DrawBorderComplex(Graphics graphics, Rectangle bounds, Color bounds.X + bounds.Width - 2, bounds.Y + bounds.Height - 2); graphics.DrawLine(pen, bounds.X + bounds.Width - 2, bounds.Y + 1, bounds.X + bounds.Width - 2, bounds.Y + bounds.Height - 2); - - if (!stockColor) { + + if (!stockColor) + { pen.Dispose(); } } } - + /// /// Helper function that draws a simple border. This is used by DrawBorder for the most common rendering cases. /// - private static void DrawBorderSimple(Graphics graphics, Rectangle bounds, Color color, ButtonBorderStyle style) { + private static void DrawBorderSimple(Graphics graphics, Rectangle bounds, Color color, ButtonBorderStyle style) + { // Common case: system color with solid pen - if (graphics == null) { + if (graphics == null) + { throw new ArgumentNullException(nameof(graphics)); } bool stockBorder = (style == ButtonBorderStyle.Solid && color.IsSystemColor); Pen pen; - if (stockBorder) { + if (stockBorder) + { pen = SystemPens.FromSystemColor(color); } - else { + else + { pen = new Pen(color); - if (style != ButtonBorderStyle.Solid) { + if (style != ButtonBorderStyle.Solid) + { pen.DashStyle = BorderStyleToDashStyle(style); } } - + graphics.DrawRectangle(pen, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); - - if (!stockBorder) { + + if (!stockBorder) + { pen.Dispose(); } - } + } /// /// Draws a Win32 button control in the given rectangle with the given state. /// - public static void DrawButton(Graphics graphics, Rectangle rectangle, ButtonState state) { + public static void DrawButton(Graphics graphics, Rectangle rectangle, ButtonState state) + { DrawButton(graphics, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, state); } /// /// Draws a Win32 button control in the given rectangle with the given state. /// - public static void DrawButton(Graphics graphics, int x, int y, int width, int height, ButtonState state) { + public static void DrawButton(Graphics graphics, int x, int y, int width, int height, ButtonState state) + { DrawFrameControl(graphics, x, y, width, height, NativeMethods.DFC_BUTTON, - NativeMethods.DFCS_BUTTONPUSH | (int) state, Color.Empty, Color.Empty); + NativeMethods.DFCS_BUTTONPUSH | (int)state, Color.Empty, Color.Empty); } /// /// Draws a Win32 window caption button in the given rectangle with the given state. /// - public static void DrawCaptionButton(Graphics graphics, Rectangle rectangle, CaptionButton button, ButtonState state) { + public static void DrawCaptionButton(Graphics graphics, Rectangle rectangle, CaptionButton button, ButtonState state) + { DrawCaptionButton(graphics, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, button, state); } /// /// Draws a Win32 window caption button in the given rectangle with the given state. /// - public static void DrawCaptionButton(Graphics graphics, int x, int y, int width, int height, CaptionButton button, ButtonState state) { + public static void DrawCaptionButton(Graphics graphics, int x, int y, int width, int height, CaptionButton button, ButtonState state) + { DrawFrameControl(graphics, x, y, width, height, NativeMethods.DFC_CAPTION, - (int) button | (int) state, Color.Empty, Color.Empty); + (int)button | (int)state, Color.Empty, Color.Empty); } /// /// Draws a Win32 checkbox control in the given rectangle with the given state. /// - public static void DrawCheckBox(Graphics graphics, Rectangle rectangle, ButtonState state) { + public static void DrawCheckBox(Graphics graphics, Rectangle rectangle, ButtonState state) + { DrawCheckBox(graphics, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, state); } /// /// Draws a Win32 checkbox control in the given rectangle with the given state. /// - public static void DrawCheckBox(Graphics graphics, int x, int y, int width, int height, ButtonState state) { + public static void DrawCheckBox(Graphics graphics, int x, int y, int width, int height, ButtonState state) + { // We overwrite the windows checkbox - if ((state & ButtonState.Flat) == ButtonState.Flat) { + if ((state & ButtonState.Flat) == ButtonState.Flat) + { DrawFlatCheckBox(graphics, new Rectangle(x, y, width, height), state); } - else { + else + { DrawFrameControl(graphics, x, y, width, height, NativeMethods.DFC_BUTTON, - NativeMethods.DFCS_BUTTONCHECK | (int) state, Color.Empty, Color.Empty); + NativeMethods.DFCS_BUTTONCHECK | (int)state, Color.Empty, Color.Empty); } } /// /// Draws the drop down button of a Win32 combo box in the given rectangle with the given state. /// - public static void DrawComboButton(Graphics graphics, Rectangle rectangle, ButtonState state) { + public static void DrawComboButton(Graphics graphics, Rectangle rectangle, ButtonState state) + { DrawComboButton(graphics, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, state); } /// /// Draws the drop down button of a Win32 combo box in the given rectangle with the given state. /// - public static void DrawComboButton(Graphics graphics, int x, int y, int width, int height, ButtonState state) { + public static void DrawComboButton(Graphics graphics, int x, int y, int width, int height, ButtonState state) + { DrawFrameControl(graphics, x, y, width, height, NativeMethods.DFC_SCROLL, - NativeMethods.DFCS_SCROLLCOMBOBOX | (int) state, Color.Empty, Color.Empty); + NativeMethods.DFCS_SCROLLCOMBOBOX | (int)state, Color.Empty, Color.Empty); } /// /// Draws a container control grab handle glyph inside the given rectangle. /// - public static void DrawContainerGrabHandle(Graphics graphics, Rectangle bounds) { + public static void DrawContainerGrabHandle(Graphics graphics, Rectangle bounds) + { - if (graphics == null) { + if (graphics == null) + { throw new ArgumentNullException(nameof(graphics)); } Brush brush = Brushes.White; Pen pen = Pens.Black; graphics.FillRectangle(brush, bounds.Left + 1, bounds.Top + 1, bounds.Width - 2, bounds.Height - 2); - + //draw the bounding rect w/o the four corners - graphics.DrawLine(pen, bounds.X + 1, bounds.Y, bounds.Right -2, bounds.Y); - graphics.DrawLine(pen, bounds.X + 1, bounds.Bottom - 1, bounds.Right -2, bounds.Bottom - 1); - graphics.DrawLine(pen, bounds.X, bounds.Y + 1, bounds.X, bounds.Bottom -2); - graphics.DrawLine(pen, bounds.Right - 1, bounds.Y + 1, bounds.Right - 1, bounds.Bottom -2); + graphics.DrawLine(pen, bounds.X + 1, bounds.Y, bounds.Right - 2, bounds.Y); + graphics.DrawLine(pen, bounds.X + 1, bounds.Bottom - 1, bounds.Right - 2, bounds.Bottom - 1); + graphics.DrawLine(pen, bounds.X, bounds.Y + 1, bounds.X, bounds.Bottom - 2); + graphics.DrawLine(pen, bounds.Right - 1, bounds.Y + 1, bounds.Right - 1, bounds.Bottom - 2); - int midx = bounds.X + bounds.Width/2; - int midy = bounds.Y + bounds.Height/2; + int midx = bounds.X + bounds.Width / 2; + int midy = bounds.Y + bounds.Height / 2; // vert line graphics.DrawLine(pen, midx, bounds.Y, midx, bounds.Bottom - 2); @@ -1149,29 +1311,31 @@ public static void DrawContainerGrabHandle(Graphics graphics, Rectangle bounds) graphics.DrawLine(pen, bounds.X, midy, bounds.Right - 2, midy); // top hash - graphics.DrawLine(pen, midx - 1, bounds.Y+2, midx+1, bounds.Y+2); - graphics.DrawLine(pen, midx - 2, bounds.Y+3, midx+2, bounds.Y+3); + graphics.DrawLine(pen, midx - 1, bounds.Y + 2, midx + 1, bounds.Y + 2); + graphics.DrawLine(pen, midx - 2, bounds.Y + 3, midx + 2, bounds.Y + 3); // left hash - graphics.DrawLine(pen, bounds.X+2, midy - 1, bounds.X + 2, midy + 1); - graphics.DrawLine(pen, bounds.X+3, midy - 2, bounds.X + 3, midy + 2); + graphics.DrawLine(pen, bounds.X + 2, midy - 1, bounds.X + 2, midy + 1); + graphics.DrawLine(pen, bounds.X + 3, midy - 2, bounds.X + 3, midy + 2); // right hash graphics.DrawLine(pen, bounds.Right - 3, midy - 1, bounds.Right - 3, midy + 1); graphics.DrawLine(pen, bounds.Right - 4, midy - 2, bounds.Right - 4, midy + 2); // bottom hash - graphics.DrawLine(pen, midx - 1, bounds.Bottom - 3, midx+1, bounds.Bottom - 3); - graphics.DrawLine(pen, midx - 2, bounds.Bottom - 4, midx+2, bounds.Bottom - 4); + graphics.DrawLine(pen, midx - 1, bounds.Bottom - 3, midx + 1, bounds.Bottom - 3); + graphics.DrawLine(pen, midx - 2, bounds.Bottom - 4, midx + 2, bounds.Bottom - 4); } /// /// Draws a flat checkbox. /// - private static void DrawFlatCheckBox(Graphics graphics, Rectangle rectangle, ButtonState state) { + private static void DrawFlatCheckBox(Graphics graphics, Rectangle rectangle, ButtonState state) + { // Background color of checkbox // - if (graphics == null) { + if (graphics == null) + { throw new ArgumentNullException(nameof(graphics)); } Brush background = ((state & ButtonState.Inactive) == ButtonState.Inactive) ? @@ -1188,11 +1352,14 @@ private static void DrawFlatCheckBox(Graphics graphics, Rectangle rectangle, But /// draws a flat looking check box that is suitable for use in list boxes, etc. We /// custom draw this because the windows version is soooo ugly. /// - private static void DrawFlatCheckBox(Graphics graphics, Rectangle rectangle, Color foreground, Brush background, ButtonState state) { - if (graphics == null) { + private static void DrawFlatCheckBox(Graphics graphics, Rectangle rectangle, Color foreground, Brush background, ButtonState state) + { + if (graphics == null) + { throw new ArgumentNullException(nameof(graphics)); } - if (rectangle.Width < 0 || rectangle.Height < 0) { + if (rectangle.Width < 0 || rectangle.Height < 0) + { throw new ArgumentOutOfRangeException(nameof(rectangle)); } @@ -1202,10 +1369,13 @@ private static void DrawFlatCheckBox(Graphics graphics, Rectangle rectangle, Col // Checkmark // - if ((state & ButtonState.Checked) == ButtonState.Checked) { - if (checkImage == null || checkImage.Width != rectangle.Width || checkImage.Height != rectangle.Height) { + if ((state & ButtonState.Checked) == ButtonState.Checked) + { + if (checkImage == null || checkImage.Width != rectangle.Width || checkImage.Height != rectangle.Height) + { - if (checkImage != null) { + if (checkImage != null) + { checkImage.Dispose(); checkImage = null; } @@ -1214,14 +1384,17 @@ private static void DrawFlatCheckBox(Graphics graphics, Rectangle rectangle, Col // and compensate below NativeMethods.RECT rcCheck = NativeMethods.RECT.FromXYWH(0, 0, rectangle.Width, rectangle.Height); Bitmap bitmap = new Bitmap(rectangle.Width, rectangle.Height); - using (Graphics g2 = Graphics.FromImage(bitmap)) { + using (Graphics g2 = Graphics.FromImage(bitmap)) + { g2.Clear(Color.Transparent); IntPtr dc = g2.GetHdc(); - try { + try + { SafeNativeMethods.DrawFrameControl(new HandleRef(null, dc), ref rcCheck, NativeMethods.DFC_MENU, NativeMethods.DFCS_MENUCHECK); } - finally { + finally + { g2.ReleaseHdcInternal(dc); } } @@ -1245,7 +1418,8 @@ private static void DrawFlatCheckBox(Graphics graphics, Rectangle rectangle, Col /// Draws a focus rectangle. A focus rectangle is a dotted rectangle that Windows /// uses to indicate what control has the current keyboard focus. /// - public static void DrawFocusRectangle(Graphics graphics, Rectangle rectangle) { + public static void DrawFocusRectangle(Graphics graphics, Rectangle rectangle) + { DrawFocusRectangle(graphics, rectangle, SystemColors.ControlText, SystemColors.Control); } @@ -1253,16 +1427,20 @@ public static void DrawFocusRectangle(Graphics graphics, Rectangle rectangle) { /// Draws a focus rectangle. A focus rectangle is a dotted rectangle that Windows /// uses to indicate what control has the current keyboard focus. /// - public static void DrawFocusRectangle(Graphics graphics, Rectangle rectangle, Color foreColor, Color backColor) { + public static void DrawFocusRectangle(Graphics graphics, Rectangle rectangle, Color foreColor, Color backColor) + { DrawFocusRectangle(graphics, rectangle, backColor, false); } - internal static void DrawHighContrastFocusRectangle(Graphics graphics, Rectangle rectangle, Color color) { + internal static void DrawHighContrastFocusRectangle(Graphics graphics, Rectangle rectangle, Color color) + { DrawFocusRectangle(graphics, rectangle, color, true); } - private static void DrawFocusRectangle(Graphics graphics, Rectangle rectangle, Color color, bool highContrast) { - if (graphics == null) { + private static void DrawFocusRectangle(Graphics graphics, Rectangle rectangle, Color color, bool highContrast) + { + if (graphics == null) + { throw new ArgumentNullException(nameof(graphics)); } rectangle.Width--; @@ -1270,7 +1448,7 @@ private static void DrawFocusRectangle(Graphics graphics, Rectangle rectangle, C graphics.DrawRectangle(GetFocusPen(color, // we want the corner to be penned // see GetFocusPen for more explanation - (rectangle.X + rectangle.Y) % 2 == 1, + (rectangle.X + rectangle.Y) % 2 == 1, highContrast), rectangle); } @@ -1278,31 +1456,40 @@ private static void DrawFocusRectangle(Graphics graphics, Rectangle rectangle, C /// /// Draws a win32 frame control. /// - private static void DrawFrameControl(Graphics graphics, int x, int y, int width, int height, - int kind, int state, Color foreColor, Color backColor) { - if (graphics == null) { + private static void DrawFrameControl(Graphics graphics, int x, int y, int width, int height, + int kind, int state, Color foreColor, Color backColor) + { + if (graphics == null) + { throw new ArgumentNullException(nameof(graphics)); } - if (width < 0) { + if (width < 0) + { throw new ArgumentOutOfRangeException(nameof(width)); } - if (height < 0) { + if (height < 0) + { throw new ArgumentOutOfRangeException(nameof(height)); } NativeMethods.RECT rcFrame = NativeMethods.RECT.FromXYWH(0, 0, width, height); - using (Bitmap bitmap = new Bitmap(width, height)) { - using( Graphics g2 = Graphics.FromImage(bitmap) ) { + using (Bitmap bitmap = new Bitmap(width, height)) + { + using (Graphics g2 = Graphics.FromImage(bitmap)) + { g2.Clear(Color.Transparent); - using( WindowsGraphics wg = WindowsGraphics.FromGraphics(g2) ){ // Get Win32 dc with Graphics properties applied to it. - SafeNativeMethods.DrawFrameControl(new HandleRef(wg, wg.DeviceContext.Hdc), ref rcFrame, kind, (int) state); + using (WindowsGraphics wg = WindowsGraphics.FromGraphics(g2)) + { // Get Win32 dc with Graphics properties applied to it. + SafeNativeMethods.DrawFrameControl(new HandleRef(wg, wg.DeviceContext.Hdc), ref rcFrame, kind, (int)state); } - - if (foreColor == Color.Empty || backColor == Color.Empty) { + + if (foreColor == Color.Empty || backColor == Color.Empty) + { graphics.DrawImage(bitmap, x, y); } - else { + else + { // Replace black/white with foreColor/backColor. ImageAttributes attrs = new ImageAttributes(); ColorMap cm1 = new ColorMap(); @@ -1323,50 +1510,62 @@ private static void DrawFrameControl(Graphics graphics, int x, int y, int width, /// handles are used by components to indicate to the user that they can /// be directly maniupulated. /// - public static void DrawGrabHandle(Graphics graphics, Rectangle rectangle, bool primary, bool enabled) { + public static void DrawGrabHandle(Graphics graphics, Rectangle rectangle, bool primary, bool enabled) + { Pen pen; Brush brush; - - if (graphics == null) { + + if (graphics == null) + { throw new ArgumentNullException(nameof(graphics)); } - if (primary) { - if (null == grabPenPrimary) { + if (primary) + { + if (null == grabPenPrimary) + { grabPenPrimary = Pens.Black; } pen = grabPenPrimary; - if (enabled) { - if (null == grabBrushPrimary) { + if (enabled) + { + if (null == grabBrushPrimary) + { grabBrushPrimary = Brushes.White; } brush = grabBrushPrimary; } - else { + else + { brush = SystemBrushes.Control; } } - else { - if (null == grabPenSecondary) { + else + { + if (null == grabPenSecondary) + { grabPenSecondary = Pens.White; } pen = grabPenSecondary; - if (enabled) { - if (null == grabBrushSecondary) { + if (enabled) + { + if (null == grabBrushSecondary) + { grabBrushSecondary = Brushes.Black; } brush = grabBrushSecondary; } - else { + else + { brush = SystemBrushes.Control; } } Rectangle fillRect = new Rectangle(rectangle.X + 1, rectangle.Y + 1, rectangle.Width - 1, rectangle.Height - 1); graphics.FillRectangle(brush, fillRect); - rectangle.Width --; + rectangle.Width--; rectangle.Height--; graphics.DrawRectangle(pen, rectangle); } @@ -1374,22 +1573,27 @@ public static void DrawGrabHandle(Graphics graphics, Rectangle rectangle, bool p /// /// Draws a grid of one pixel dots in the given rectangle. /// - public static void DrawGrid(Graphics graphics, Rectangle area, Size pixelsBetweenDots, Color backColor) { + public static void DrawGrid(Graphics graphics, Rectangle area, Size pixelsBetweenDots, Color backColor) + { - if (graphics == null) { + if (graphics == null) + { throw new ArgumentNullException(nameof(graphics)); } - if (pixelsBetweenDots.Width <= 0 || pixelsBetweenDots.Height <= 0) { + if (pixelsBetweenDots.Width <= 0 || pixelsBetweenDots.Height <= 0) + { throw new ArgumentOutOfRangeException(nameof(pixelsBetweenDots)); } float intensity = backColor.GetBrightness(); bool invert = (intensity < .5); - - if (gridBrush == null || gridSize.Width != pixelsBetweenDots.Width - || gridSize.Height != pixelsBetweenDots.Height || invert != gridInvert) { - if (gridBrush != null) { + if (gridBrush == null || gridSize.Width != pixelsBetweenDots.Width + || gridSize.Height != pixelsBetweenDots.Height || invert != gridInvert) + { + + if (gridBrush != null) + { gridBrush.Dispose(); gridBrush = null; } @@ -1427,14 +1631,17 @@ internal static void DrawImageColorized(Graphics graphics, Image image, Rectangl */ // Takes a black and transparent image, turns black pixels into some other color, and leaves transparent pixels alone - internal static void DrawImageColorized(Graphics graphics, Image image, Rectangle destination, - Color replaceBlack) { - DrawImageColorized(graphics, image, destination, + internal static void DrawImageColorized(Graphics graphics, Image image, Rectangle destination, + Color replaceBlack) + { + DrawImageColorized(graphics, image, destination, RemapBlackAndWhitePreserveTransparentMatrix(replaceBlack, Color.White)); } - internal static bool IsImageTransparent(Image backgroundImage) { - if (backgroundImage != null && (backgroundImage.Flags & (int)ImageFlags.HasAlpha) > 0) { + internal static bool IsImageTransparent(Image backgroundImage) + { + if (backgroundImage != null && (backgroundImage.Flags & (int)ImageFlags.HasAlpha) > 0) + { return true; } return false; @@ -1442,28 +1649,31 @@ internal static bool IsImageTransparent(Image backgroundImage) { // takes an image and replaces all the pixels of oldColor with newColor, drawing the new image into the rectangle on // the supplied Graphics object. - internal static void DrawImageReplaceColor(Graphics g, Image image, Rectangle dest, Color oldColor, Color newColor) { + internal static void DrawImageReplaceColor(Graphics g, Image image, Rectangle dest, Color oldColor, Color newColor) + { ImageAttributes attrs = new ImageAttributes(); ColorMap cm = new ColorMap(); cm.OldColor = oldColor; cm.NewColor = newColor; - attrs.SetRemapTable(new ColorMap[]{cm}, ColorAdjustType.Bitmap); + attrs.SetRemapTable(new ColorMap[] { cm }, ColorAdjustType.Bitmap); g.DrawImage(image, dest, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attrs, null, IntPtr.Zero); attrs.Dispose(); } // Takes a black and white image, and paints it in color - private static void DrawImageColorized(Graphics graphics, Image image, Rectangle destination, - ColorMatrix matrix) { - if (graphics == null) { + private static void DrawImageColorized(Graphics graphics, Image image, Rectangle destination, + ColorMatrix matrix) + { + if (graphics == null) + { throw new ArgumentNullException(nameof(graphics)); } ImageAttributes attributes = new ImageAttributes(); attributes.SetColorMatrix(matrix); - graphics.DrawImage(image, destination, 0,0, image.Width, image.Height, + graphics.DrawImage(image, destination, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes, null, IntPtr.Zero); attributes.Dispose(); } @@ -1471,25 +1681,30 @@ private static void DrawImageColorized(Graphics graphics, Image image, Rectangle /// /// Draws an image and makes it look disabled. /// - public static void DrawImageDisabled(Graphics graphics, Image image, int x, int y, Color background) { + public static void DrawImageDisabled(Graphics graphics, Image image, int x, int y, Color background) + { DrawImageDisabled(graphics, image, new Rectangle(x, y, image.Width, image.Height), background, false); } /// /// Draws an image and makes it look disabled. /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters")] - internal static void DrawImageDisabled(Graphics graphics, Image image, Rectangle imageBounds, Color background, bool unscaledImage) { - if (graphics == null) { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters")] + internal static void DrawImageDisabled(Graphics graphics, Image image, Rectangle imageBounds, Color background, bool unscaledImage) + { + if (graphics == null) + { throw new ArgumentNullException(nameof(graphics)); } - if (image == null) { + if (image == null) + { throw new ArgumentNullException(nameof(image)); } #if GRAYSCALE_DISABLED Size imageSize = image.Size; - if (disabledImageAttr == null) { + if (disabledImageAttr == null) + { // This is how I came up with this somewhat random ColorMatrix. // Its set to resemble Office10 commandbars, but still be able to // deal with hi-color (256+) icons and images. @@ -1505,13 +1720,13 @@ internal static void DrawImageDisabled(Graphics graphics, Image image, Rectangle // Black becomes a shade of gray as well. // // btw, if you do come up with something better let me know - Microsoft - + float[][] array = new float[5][]; - array[0] = new float[5] {0.2125f, 0.2125f, 0.2125f, 0, 0}; - array[1] = new float[5] {0.2577f, 0.2577f, 0.2577f, 0, 0}; - array[2] = new float[5] {0.0361f, 0.0361f, 0.0361f, 0, 0}; - array[3] = new float[5] {0, 0, 0, 1, 0}; - array[4] = new float[5] {0.38f, 0.38f, 0.38f, 0, 1}; + array[0] = new float[5] { 0.2125f, 0.2125f, 0.2125f, 0, 0 }; + array[1] = new float[5] { 0.2577f, 0.2577f, 0.2577f, 0, 0 }; + array[2] = new float[5] { 0.0361f, 0.0361f, 0.0361f, 0, 0 }; + array[3] = new float[5] { 0, 0, 0, 1, 0 }; + array[4] = new float[5] { 0.38f, 0.38f, 0.38f, 0, 1 }; ColorMatrix grayMatrix = new ColorMatrix(array); @@ -1520,23 +1735,27 @@ internal static void DrawImageDisabled(Graphics graphics, Image image, Rectangle disabledImageAttr.SetColorMatrix(grayMatrix); } - if (unscaledImage) { - using (Bitmap bmp = new Bitmap(image.Width, image.Height)) { - using (Graphics g = Graphics.FromImage(bmp)) { - g.DrawImage(image, + if (unscaledImage) + { + using (Bitmap bmp = new Bitmap(image.Width, image.Height)) + { + using (Graphics g = Graphics.FromImage(bmp)) + { + g.DrawImage(image, new Rectangle(0, 0, imageSize.Width, imageSize.Height), 0, 0, imageSize.Width, imageSize.Height, - GraphicsUnit.Pixel, + GraphicsUnit.Pixel, disabledImageAttr); } graphics.DrawImageUnscaled(bmp, imageBounds); } } - else { - graphics.DrawImage(image, - imageBounds, + else + { + graphics.DrawImage(image, + imageBounds, 0, 0, imageSize.Width, imageSize.Height, - GraphicsUnit.Pixel, + GraphicsUnit.Pixel, disabledImageAttr); } #else @@ -1586,17 +1805,21 @@ internal static void DrawImageDisabled(Graphics graphics, Image image, Rectangle /// /// Draws a locked selection frame around the given rectangle. /// - public static void DrawLockedFrame(Graphics graphics, Rectangle rectangle, bool primary) { + public static void DrawLockedFrame(Graphics graphics, Rectangle rectangle, bool primary) + { Pen pen; - if (graphics == null) { + if (graphics == null) + { throw new ArgumentNullException(nameof(graphics)); } - if (primary) { + if (primary) + { pen = Pens.White; } - else { + else + { pen = Pens.Black; } @@ -1604,10 +1827,12 @@ public static void DrawLockedFrame(Graphics graphics, Rectangle rectangle, bool rectangle.Inflate(-1, -1); graphics.DrawRectangle(pen, rectangle.X, rectangle.Y, rectangle.Width - 1, rectangle.Height - 1); - if (primary) { + if (primary) + { pen = Pens.Black; } - else { + else + { pen = Pens.White; } rectangle.Inflate(-1, -1); @@ -1617,7 +1842,8 @@ public static void DrawLockedFrame(Graphics graphics, Rectangle rectangle, bool /// /// Draws a menu glyph for a Win32 menu in the given rectangle with the given state. /// - public static void DrawMenuGlyph(Graphics graphics, Rectangle rectangle, MenuGlyph glyph) { + public static void DrawMenuGlyph(Graphics graphics, Rectangle rectangle, MenuGlyph glyph) + { DrawMenuGlyph(graphics, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, glyph); } @@ -1633,9 +1859,10 @@ public static void DrawMenuGlyph(Graphics graphics, Rectangle rectangle, MenuGly /// /// Draws a menu glyph for a Win32 menu in the given rectangle with the given state. /// - public static void DrawMenuGlyph(Graphics graphics, int x, int y, int width, int height, MenuGlyph glyph) { - DrawFrameControl(graphics, x, y, width, height, NativeMethods.DFC_MENU, - (int) glyph, Color.Empty, Color.Empty); + public static void DrawMenuGlyph(Graphics graphics, int x, int y, int width, int height, MenuGlyph glyph) + { + DrawFrameControl(graphics, x, y, width, height, NativeMethods.DFC_MENU, + (int)glyph, Color.Empty, Color.Empty); } /// @@ -1650,26 +1877,30 @@ public static void DrawMenuGlyph(Graphics graphics, int x, int y, int width, int /// /// Draws a Win32 3-state checkbox control in the given rectangle with the given state. /// - public static void DrawMixedCheckBox(Graphics graphics, Rectangle rectangle, ButtonState state) { + public static void DrawMixedCheckBox(Graphics graphics, Rectangle rectangle, ButtonState state) + { DrawMixedCheckBox(graphics, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, state); } - public static void DrawMixedCheckBox(Graphics graphics, int x, int y, int width, int height, ButtonState state) { + public static void DrawMixedCheckBox(Graphics graphics, int x, int y, int width, int height, ButtonState state) + { DrawFrameControl(graphics, x, y, width, height, NativeMethods.DFC_BUTTON, - NativeMethods.DFCS_BUTTON3STATE | (int) state, Color.Empty, Color.Empty); + NativeMethods.DFCS_BUTTON3STATE | (int)state, Color.Empty, Color.Empty); } /// /// Draws a Win32 radio button in the given rectangle with the given state. /// - public static void DrawRadioButton(Graphics graphics, Rectangle rectangle, ButtonState state) { + public static void DrawRadioButton(Graphics graphics, Rectangle rectangle, ButtonState state) + { DrawRadioButton(graphics, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, state); } /// /// Draws a Win32 radio button in the given rectangle with the given state. /// - public static void DrawRadioButton(Graphics graphics, int x, int y, int width, int height, ButtonState state) { + public static void DrawRadioButton(Graphics graphics, int x, int y, int width, int height, ButtonState state) + { DrawFrameControl(graphics, x, y, width, height, NativeMethods.DFC_BUTTON, NativeMethods.DFCS_BUTTONRADIO | ((int)state), Color.Empty, Color.Empty); } @@ -1680,15 +1911,18 @@ public static void DrawRadioButton(Graphics graphics, int x, int y, int width, i /// inverting a region of the screen except that it behaves better for /// a wider variety of colors. /// - public static void DrawReversibleFrame(Rectangle rectangle, Color backColor, FrameStyle style) { + public static void DrawReversibleFrame(Rectangle rectangle, Color backColor, FrameStyle style) + { int rop2; Color graphicsColor; - if (backColor.GetBrightness() < .5) { + if (backColor.GetBrightness() < .5) + { rop2 = 0xA; // RasterOp.PEN.Invert().XorWith(RasterOp.TARGET); graphicsColor = Color.White; } - else { + else + { rop2 = 0x7; // RasterOp.PEN.XorWith(RasterOp.TARGET); graphicsColor = Color.Black; } @@ -1696,7 +1930,8 @@ public static void DrawReversibleFrame(Rectangle rectangle, Color backColor, Fra IntPtr dc = UnsafeNativeMethods.GetDCEx(new HandleRef(null, UnsafeNativeMethods.GetDesktopWindow()), NativeMethods.NullHandleRef, NativeMethods.DCX_WINDOW | NativeMethods.DCX_LOCKWINDOWUPDATE | NativeMethods.DCX_CACHE); IntPtr pen; - switch (style) { + switch (style) + { case FrameStyle.Dashed: pen = SafeNativeMethods.CreatePen(NativeMethods.PS_DOT, 1, ColorTranslator.ToWin32(backColor)); break; @@ -1718,7 +1953,7 @@ public static void DrawReversibleFrame(Rectangle rectangle, Color backColor, Fra SafeNativeMethods.SelectObject(new HandleRef(null, dc), new HandleRef(null, oldPen)); if (pen != IntPtr.Zero) - { + { SafeNativeMethods.DeleteObject(new HandleRef(null, pen)); } @@ -1729,8 +1964,9 @@ public static void DrawReversibleFrame(Rectangle rectangle, Color backColor, Fra /// Draws a reversible line on the screen. A reversible line can /// be erased by just drawing over it again. /// - public static void DrawReversibleLine(Point start, Point end, Color backColor) { - int rop2 = GetColorRop(backColor, + public static void DrawReversibleLine(Point start, Point end, Color backColor) + { + int rop2 = GetColorRop(backColor, 0xA, // RasterOp.PEN.Invert().XorWith(RasterOp.TARGET), 0x7); //RasterOp.PEN.XorWith(RasterOp.TARGET)); @@ -1755,14 +1991,16 @@ public static void DrawReversibleLine(Point start, Point end, Color backColor) { /// /// Draws a button for a Win32 scroll bar in the given rectangle with the given state. /// - public static void DrawScrollButton(Graphics graphics, Rectangle rectangle, ScrollButton button, ButtonState state) { + public static void DrawScrollButton(Graphics graphics, Rectangle rectangle, ScrollButton button, ButtonState state) + { DrawScrollButton(graphics, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, button, state); } /// /// Draws a button for a Win32 scroll bar in the given rectangle with the given state. /// - public static void DrawScrollButton(Graphics graphics, int x, int y, int width, int height, ScrollButton button, ButtonState state) { + public static void DrawScrollButton(Graphics graphics, int x, int y, int width, int height, ScrollButton button, ButtonState state) + { DrawFrameControl(graphics, x, y, width, height, NativeMethods.DFC_SCROLL, (int)button | (int)state, Color.Empty, Color.Empty); } @@ -1771,16 +2009,20 @@ public static void DrawScrollButton(Graphics graphics, int x, int y, int width, /// Draws a standard selection frame. A selection frame is a frame that is /// drawn around a selected component at design time. /// - public static void DrawSelectionFrame(Graphics graphics, bool active, Rectangle outsideRect, Rectangle insideRect, Color backColor) { - if (graphics == null) { + public static void DrawSelectionFrame(Graphics graphics, bool active, Rectangle outsideRect, Rectangle insideRect, Color backColor) + { + if (graphics == null) + { throw new ArgumentNullException(nameof(graphics)); } - Brush frameBrush; - if (active) { + Brush frameBrush; + if (active) + { frameBrush = GetActiveBrush(backColor); } - else { + else + { frameBrush = GetSelectedBrush(backColor); } @@ -1794,7 +2036,8 @@ public static void DrawSelectionFrame(Graphics graphics, bool active, Rectangle /// Draws a size grip at the given location. The color of the size grip is based /// on the given background color. /// - public static void DrawSizeGrip(Graphics graphics, Color backColor, Rectangle bounds) { + public static void DrawSizeGrip(Graphics graphics, Color backColor, Rectangle bounds) + { DrawSizeGrip(graphics, backColor, bounds.X, bounds.Y, bounds.Width, bounds.Height); } @@ -1802,22 +2045,27 @@ public static void DrawSizeGrip(Graphics graphics, Color backColor, Rectangle bo /// Draws a size grip at the given location. The color of the size grip is based /// on the given background color. /// - public static void DrawSizeGrip(Graphics graphics, Color backColor, int x, int y, int width, int height) { + public static void DrawSizeGrip(Graphics graphics, Color backColor, int x, int y, int width, int height) + { // Note: We don't paint any background to facilitate transparency, background images, etc... // - if (graphics == null) { + if (graphics == null) + { throw new ArgumentNullException(nameof(graphics)); } - using( Pen bright = new Pen(LightLight(backColor)) ) { - using ( Pen dark = new Pen(Dark(backColor)) ) { + using (Pen bright = new Pen(LightLight(backColor))) + { + using (Pen dark = new Pen(Dark(backColor))) + { int minDim = Math.Min(width, height); - int right = x+width-1; - int bottom = y+height-2; + int right = x + width - 1; + int bottom = y + height - 2; - for (int i=0; i public static void DrawStringDisabled(Graphics graphics, string s, Font font, Color color, RectangleF layoutRectangle, - StringFormat format) { + StringFormat format) + { - if (graphics == null) { + if (graphics == null) + { throw new ArgumentNullException(nameof(graphics)); } - if (SystemInformation.HighContrast) { + if (SystemInformation.HighContrast) + { // Ignore the foreground color argument and don't do shading in high contrast, // as colors should match the OS-defined ones. graphics.DrawString(s, font, SystemBrushes.GrayText, layoutRectangle, format); } - else { + else + { layoutRectangle.Offset(1, 1); - using (SolidBrush brush = new SolidBrush(LightLight(color))) { + using (SolidBrush brush = new SolidBrush(LightLight(color))) + { graphics.DrawString(s, font, brush, layoutRectangle, format); layoutRectangle.Offset(-1, -1); @@ -1858,20 +2111,24 @@ public static void DrawStringDisabled(Graphics graphics, string s, Font font, /// /// Draws a string in the style appropriate for disabled items, using GDI-based TextRenderer. /// - public static void DrawStringDisabled(IDeviceContext dc, string s, Font font, + public static void DrawStringDisabled(IDeviceContext dc, string s, Font font, Color color, Rectangle layoutRectangle, - TextFormatFlags format) { - if (dc == null) { + TextFormatFlags format) + { + if (dc == null) + { throw new ArgumentNullException(nameof(dc)); } - if (SystemInformation.HighContrast) { + if (SystemInformation.HighContrast) + { TextRenderer.DrawText(dc, s, font, layoutRectangle, SystemColors.GrayText, format); } - else { + else + { layoutRectangle.Offset(1, 1); Color paintcolor = LightLight(color); - + TextRenderer.DrawText(dc, s, font, layoutRectangle, paintcolor, format); layoutRectangle.Offset(-1, -1); paintcolor = Dark(color); @@ -1882,11 +2139,14 @@ public static void DrawStringDisabled(IDeviceContext dc, string s, Font font, /// /// Draws a string in the style appropriate for disabled items. /// - public static void DrawVisualStyleBorder(Graphics graphics, Rectangle bounds) { - if (graphics == null) { + public static void DrawVisualStyleBorder(Graphics graphics, Rectangle bounds) + { + if (graphics == null) + { throw new ArgumentNullException(nameof(graphics)); } - using (Pen borderPen = new Pen(System.Windows.Forms.VisualStyles.VisualStyleInformation.TextControlBorder)) { + using (Pen borderPen = new Pen(System.Windows.Forms.VisualStyles.VisualStyleInformation.TextControlBorder)) + { graphics.DrawRectangle(borderPen, bounds); } } @@ -1897,11 +2157,12 @@ public static void DrawVisualStyleBorder(Graphics graphics, Rectangle bounds) { /// inverting a region of the screen except that it behaves better for /// a wider variety of colors. /// - public static void FillReversibleRectangle(Rectangle rectangle, Color backColor) { - int rop3 = GetColorRop(backColor, + public static void FillReversibleRectangle(Rectangle rectangle, Color backColor) + { + int rop3 = GetColorRop(backColor, 0xa50065, // RasterOp.BRUSH.Invert().XorWith(RasterOp.TARGET), 0x5a0049); // RasterOp.BRUSH.XorWith(RasterOp.TARGET)); - int rop2 = GetColorRop(backColor, + int rop2 = GetColorRop(backColor, 0x6, // RasterOp.BRUSH.Invert().XorWith(RasterOp.TARGET), 0x6); // RasterOp.BRUSH.XorWith(RasterOp.TARGET)); @@ -1926,20 +2187,23 @@ public static void FillReversibleRectangle(Rectangle rectangle, Color backColor) // // This is not really a general-purpose function -- when used on something // not obtained from ChooseFont, it may round away some precision. - internal static Font FontInPoints(Font font) { + internal static Font FontInPoints(Font font) + { return new Font(font.FontFamily, font.SizeInPoints, font.Style, GraphicsUnit.Point, font.GdiCharSet, font.GdiVerticalFont); } // Returns whether or not target was changed - internal static bool FontToIFont(Font source, UnsafeNativeMethods.IFont target) { - bool changed = false; + internal static bool FontToIFont(Font source, UnsafeNativeMethods.IFont target) + { + bool changed = false; // we need to go through all the pain of the diff here because // it looks like setting them all has different results based on the // order and each individual IFont implementor... // string fontName = target.GetName(); - if (!source.Name.Equals(fontName)) { + if (!source.Name.Equals(fontName)) + { target.SetName(source.Name); changed = true; } @@ -1958,7 +2222,8 @@ internal static bool FontToIFont(Font source, UnsafeNativeMethods.IFont target) // size must be in points float winformsSize = source.SizeInPoints; - if (winformsSize != fontSize) { + if (winformsSize != fontSize) + { target.SetSize((long)(winformsSize * 10000)); changed = true; } @@ -1968,37 +2233,43 @@ internal static bool FontToIFont(Font source, UnsafeNativeMethods.IFont target) source.ToLogFont(logfont); short fontWeight = target.GetWeight(); - if (fontWeight != logfont.lfWeight) { + if (fontWeight != logfont.lfWeight) + { target.SetWeight((short)logfont.lfWeight); changed = true; } bool fontBold = target.GetBold(); - if (fontBold != (logfont.lfWeight >= 700)) { + if (fontBold != (logfont.lfWeight >= 700)) + { target.SetBold(logfont.lfWeight >= 700); changed = true; } bool fontItalic = target.GetItalic(); - if (fontItalic != (0 != logfont.lfItalic)) { + if (fontItalic != (0 != logfont.lfItalic)) + { target.SetItalic(0 != logfont.lfItalic); changed = true; } bool fontUnderline = target.GetUnderline(); - if (fontUnderline != (0 != logfont.lfUnderline)) { + if (fontUnderline != (0 != logfont.lfUnderline)) + { target.SetUnderline(0 != logfont.lfUnderline); changed = true; } bool fontStrike = target.GetStrikethrough(); - if (fontStrike != (0 != logfont.lfStrikeOut)) { + if (fontStrike != (0 != logfont.lfStrikeOut)) + { target.SetStrikethrough(0 != logfont.lfStrikeOut); changed = true; } short fontCharset = target.GetCharset(); - if (fontCharset != logfont.lfCharSet) { + if (fontCharset != logfont.lfCharSet) + { target.SetCharset(logfont.lfCharSet); changed = true; } @@ -2010,8 +2281,10 @@ internal static bool FontToIFont(Font source, UnsafeNativeMethods.IFont target) /// This makes a choice from a set of raster op codes, based on the color given. If the /// color is considered to be "dark", the raster op provided by dark will be returned. /// - private static int GetColorRop(Color color, int darkROP, int lightROP) { - if (color.GetBrightness() < .5) { + private static int GetColorRop(Color color, int darkROP, int lightROP) + { + if (color.GetBrightness() < .5) + { return darkROP; } return lightROP; @@ -2020,20 +2293,25 @@ private static int GetColorRop(Color color, int darkROP, int lightROP) { /// /// Retrieves the brush used to draw active objects. /// - private static Brush GetActiveBrush(Color backColor) { + private static Brush GetActiveBrush(Color backColor) + { Color brushColor; - if (backColor.GetBrightness() <= .5) { + if (backColor.GetBrightness() <= .5) + { brushColor = SystemColors.ControlLight; } - else { + else + { brushColor = SystemColors.ControlDark; } - + if (frameBrushActive == null || - !frameColorActive.Equals(brushColor)) { + !frameColorActive.Equals(brushColor)) + { - if (frameBrushActive != null) { + if (frameBrushActive != null) + { frameBrushActive.Dispose(); frameBrushActive = null; } @@ -2046,15 +2324,20 @@ private static Brush GetActiveBrush(Color backColor) { // gpr : bitmap does not initialize itself to be zero? // - for (int x = 0; x < patternSize; x++) { - for (int y = 0; y < patternSize; y++) { + for (int x = 0; x < patternSize; x++) + { + for (int y = 0; y < patternSize; y++) + { bitmap.SetPixel(x, y, Color.Transparent); } } - for (int y = 0; y < patternSize; y++) { - for (int x = -y; x < patternSize; x += 4) { - if (x >= 0) { + for (int y = 0; y < patternSize; y++) + { + for (int x = -y; x < patternSize; x += 4) + { + if (x >= 0) + { bitmap.SetPixel(x, y, brushColor); } } @@ -2071,13 +2354,16 @@ private static Brush GetActiveBrush(Color backColor) { /// Retrieves the pen used to draw a focus rectangle around a control. The focus /// rectangle is typically drawn when the control has keyboard focus. /// - private static Pen GetFocusPen(Color baseColor, bool odds, bool highContrast) { + private static Pen GetFocusPen(Color baseColor, bool odds, bool highContrast) + { if (focusPen == null || (!highContrast && focusPenColor.GetBrightness() <= .5 && baseColor.GetBrightness() <= .5) || focusPenColor.ToArgb() != baseColor.ToArgb() || - hcFocusPen != highContrast) { + hcFocusPen != highContrast) + { - if (focusPen != null) { + if (focusPen != null) + { focusPen.Dispose(); focusPen = null; focusPenInvert.Dispose(); @@ -2087,23 +2373,27 @@ private static Pen GetFocusPen(Color baseColor, bool odds, bool highContrast) { focusPenColor = baseColor; hcFocusPen = highContrast; - Bitmap b = new Bitmap(2,2); + Bitmap b = new Bitmap(2, 2); Color color1 = Color.Transparent; Color color2; - if (highContrast) { + if (highContrast) + { // in highcontrast mode "baseColor" itself is used as the focus pen color color2 = baseColor; } - else { + else + { // in non-highcontrast mode "baseColor" is used to calculate the focus pen colors // in this mode "baseColor" is expected to contain background color of the control to do this calculation properly color2 = Color.Black; - if (baseColor.GetBrightness() <= .5) { + if (baseColor.GetBrightness() <= .5) + { color1 = color2; color2 = InvertColor(baseColor); } - else if (baseColor == Color.Transparent) { + else if (baseColor == Color.Transparent) + { color1 = Color.White; } } @@ -2135,19 +2425,24 @@ private static Pen GetFocusPen(Color baseColor, bool odds, bool highContrast) { /// /// Retrieves the brush used to draw selected objects. /// - private static Brush GetSelectedBrush(Color backColor) { + private static Brush GetSelectedBrush(Color backColor) + { Color brushColor; - if (backColor.GetBrightness() <= .5) { + if (backColor.GetBrightness() <= .5) + { brushColor = SystemColors.ControlLight; } - else { + else + { brushColor = SystemColors.ControlDark; } if (frameBrushSelected == null || - !frameColorSelected.Equals(brushColor)) { + !frameColorSelected.Equals(brushColor)) + { - if (frameBrushSelected != null) { + if (frameBrushSelected != null) + { frameBrushSelected.Dispose(); frameBrushSelected = null; } @@ -2160,16 +2455,20 @@ private static Brush GetSelectedBrush(Color backColor) { // gpr : bitmap does not initialize itself to be zero? // - for (int x = 0; x < patternSize; x++) { - for (int y = 0; y < patternSize; y++) { + for (int x = 0; x < patternSize; x++) + { + for (int y = 0; y < patternSize; y++) + { bitmap.SetPixel(x, y, Color.Transparent); } } int start = 0; - for (int x = 0; x < patternSize; x += 2) { - for (int y = start; y < patternSize; y += 2) { + for (int x = 0; x < patternSize; x += 2) + { + for (int y = start; y < patternSize; y += 2) + { bitmap.SetPixel(x, y, brushColor); } @@ -2186,8 +2485,10 @@ private static Brush GetSelectedBrush(Color backColor) { /// /// Converts an infinite value to "1". /// - private static float InfinityToOne(float value) { - if (value == float.NegativeInfinity || value == float.PositiveInfinity) { + private static float InfinityToOne(float value) + { + if (value == float.NegativeInfinity || value == float.PositiveInfinity) + { return 1.0f; } return value; @@ -2196,28 +2497,32 @@ private static float InfinityToOne(float value) { /// /// Inverts the given color. /// - private static Color InvertColor(Color color) { + private static Color InvertColor(Color color) + { return Color.FromArgb(color.A, (byte)~color.R, (byte)~color.G, (byte)~color.B); } /// /// Creates a new color that is a object of the given color. /// - public static Color Light(Color baseColor, float percOfLightLight) { + public static Color Light(Color baseColor, float percOfLightLight) + { return new HLSColor(baseColor).Lighter(percOfLightLight); } /// /// Creates a new color that is a object of the given color. /// - public static Color Light(Color baseColor) { + public static Color Light(Color baseColor) + { return new HLSColor(baseColor).Lighter(0.5f); } /// /// Creates a new color that is a object of the given color. /// - public static Color LightLight(Color baseColor) { + public static Color LightLight(Color baseColor) + { return new HLSColor(baseColor).Lighter(1.0f); } @@ -2258,82 +2563,95 @@ private static Bitmap MakeMonochrome(Bitmap input, Color color) { } #endif - internal static ColorMatrix MultiplyColorMatrix(float[][] matrix1, float[][] matrix2) { + internal static ColorMatrix MultiplyColorMatrix(float[][] matrix1, float[][] matrix2) + { int size = 5; // multiplies 2 5x5 matrices. // build up an empty 5x5 array for results float[][] result = new float[size][]; - for (int row = 0; row < size; row++){ - result[row] = new float[size]; + for (int row = 0; row < size; row++) + { + result[row] = new float[size]; } - + float[] column = new float[size]; - for (int j = 0; j < size; j++) { - for (int k = 0; k < size; k++) { + for (int j = 0; j < size; j++) + { + for (int k = 0; k < size; k++) + { column[k] = matrix1[k][j]; } - for (int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) + { float[] row = matrix2[i]; float s = 0; - for (int k = 0; k < size; k++) { + for (int k = 0; k < size; k++) + { s += row[k] * column[k]; } result[i][j] = s; - } + } } - + return new ColorMatrix(result); } //paint the border of the table - internal static void PaintTableControlBorder(TableLayoutPanelCellBorderStyle borderStyle, Graphics g, Rectangle bound) { + internal static void PaintTableControlBorder(TableLayoutPanelCellBorderStyle borderStyle, Graphics g, Rectangle bound) + { int x = bound.X; int y = bound.Y; int right = bound.Right; int bottom = bound.Bottom; //draw the outside bounding rectangle - switch(borderStyle) { + switch (borderStyle) + { case TableLayoutPanelCellBorderStyle.None: case TableLayoutPanelCellBorderStyle.Single: break; - + case TableLayoutPanelCellBorderStyle.Inset: case TableLayoutPanelCellBorderStyle.InsetDouble: g.DrawLine(SystemPens.ControlDark, x, y, right - 1, y); g.DrawLine(SystemPens.ControlDark, x, y, x, bottom - 1); - using (Pen pen = new Pen(SystemColors.Window)) { + using (Pen pen = new Pen(SystemColors.Window)) + { g.DrawLine(pen, right - 1, y, right - 1, bottom - 1); g.DrawLine(pen, x, bottom - 1, right - 1, bottom - 1); } break; - + case TableLayoutPanelCellBorderStyle.Outset: case TableLayoutPanelCellBorderStyle.OutsetDouble: case TableLayoutPanelCellBorderStyle.OutsetPartial: - using (Pen pen = new Pen(SystemColors.Window)) { + using (Pen pen = new Pen(SystemColors.Window)) + { g.DrawLine(pen, x, y, right - 1, y); g.DrawLine(pen, x, y, x, bottom - 1); } g.DrawLine(SystemPens.ControlDark, right - 1, y, right - 1, bottom - 1); g.DrawLine(SystemPens.ControlDark, x, bottom - 1, right - 1, bottom - 1); - break; - } + break; + } } //paint individual cell of the table - internal static void PaintTableCellBorder(TableLayoutPanelCellBorderStyle borderStyle, Graphics g, Rectangle bound) { - + internal static void PaintTableCellBorder(TableLayoutPanelCellBorderStyle borderStyle, Graphics g, Rectangle bound) + { + //next, paint the cell border - switch (borderStyle) { - case TableLayoutPanelCellBorderStyle.None : + switch (borderStyle) + { + case TableLayoutPanelCellBorderStyle.None: break; - case TableLayoutPanelCellBorderStyle.Single : + case TableLayoutPanelCellBorderStyle.Single: g.DrawRectangle(SystemPens.ControlDark, bound); break; - case TableLayoutPanelCellBorderStyle.Inset : - using (Pen pen = new Pen(SystemColors.Window)) { + case TableLayoutPanelCellBorderStyle.Inset: + using (Pen pen = new Pen(SystemColors.Window)) + { g.DrawLine(pen, bound.X, bound.Y, bound.X + bound.Width - 1, bound.Y); g.DrawLine(pen, bound.X, bound.Y, bound.X, bound.Y + bound.Height - 1); } @@ -2342,12 +2660,13 @@ internal static void PaintTableCellBorder(TableLayoutPanelCellBorderStyle border g.DrawLine(SystemPens.ControlDark, bound.X, bound.Y + bound.Height - 1, bound.X + bound.Width - 1, bound.Y + bound.Height - 1); break; - case TableLayoutPanelCellBorderStyle.InsetDouble : + case TableLayoutPanelCellBorderStyle.InsetDouble: g.DrawRectangle(SystemPens.Control, bound); //draw the shadow bound = new Rectangle(bound.X + 1, bound.Y + 1, bound.Width - 1, bound.Height - 1); - using (Pen pen = new Pen(SystemColors.Window)) { + using (Pen pen = new Pen(SystemColors.Window)) + { g.DrawLine(pen, bound.X, bound.Y, bound.X + bound.Width - 1, bound.Y); g.DrawLine(pen, bound.X, bound.Y, bound.X, bound.Y + bound.Height - 1); } @@ -2356,25 +2675,27 @@ internal static void PaintTableCellBorder(TableLayoutPanelCellBorderStyle border g.DrawLine(SystemPens.ControlDark, bound.X, bound.Y + bound.Height - 1, bound.X + bound.Width - 1, bound.Y + bound.Height - 1); break; - case TableLayoutPanelCellBorderStyle.Outset : + case TableLayoutPanelCellBorderStyle.Outset: g.DrawLine(SystemPens.ControlDark, bound.X, bound.Y, bound.X + bound.Width - 1, bound.Y); g.DrawLine(SystemPens.ControlDark, bound.X, bound.Y, bound.X, bound.Y + bound.Height - 1); - using (Pen pen = new Pen(SystemColors.Window)) { + using (Pen pen = new Pen(SystemColors.Window)) + { g.DrawLine(pen, bound.X + bound.Width - 1, bound.Y, bound.X + bound.Width - 1, bound.Y + bound.Height - 1); g.DrawLine(pen, bound.X, bound.Y + bound.Height - 1, bound.X + bound.Width - 1, bound.Y + bound.Height - 1); } break; - case TableLayoutPanelCellBorderStyle.OutsetDouble : - case TableLayoutPanelCellBorderStyle.OutsetPartial : + case TableLayoutPanelCellBorderStyle.OutsetDouble: + case TableLayoutPanelCellBorderStyle.OutsetPartial: g.DrawRectangle(SystemPens.Control, bound); //draw the shadow bound = new Rectangle(bound.X + 1, bound.Y + 1, bound.Width - 1, bound.Height - 1); g.DrawLine(SystemPens.ControlDark, bound.X, bound.Y, bound.X + bound.Width - 1, bound.Y); g.DrawLine(SystemPens.ControlDark, bound.X, bound.Y, bound.X, bound.Y + bound.Height - 1); - using (Pen pen = new Pen(SystemColors.Window)) { + using (Pen pen = new Pen(SystemColors.Window)) + { g.DrawLine(pen, bound.X + bound.Width - 1, bound.Y, bound.X + bound.Width - 1, bound.Y + bound.Height - 1); g.DrawLine(pen, bound.X, bound.Y + bound.Height - 1, bound.X + bound.Width - 1, bound.Y + bound.Height - 1); } @@ -2443,21 +2764,22 @@ private static ColorMatrix RemapBlackAndWhiteAndTransparentMatrix(Color replaceB // Takes a black and white image, and replaces those colors with the colors of your choice. // The replaceBlack and replaceWhite colors must have alpha = 255, because the alpha value // of the bitmap is preserved. - private static ColorMatrix RemapBlackAndWhitePreserveTransparentMatrix(Color replaceBlack, Color replaceWhite) { + private static ColorMatrix RemapBlackAndWhitePreserveTransparentMatrix(Color replaceBlack, Color replaceWhite) + { Debug.Assert(replaceBlack.A == 255, "replaceBlack.Alpha is ignored, so please set it to 255 so I know you know what you're doing"); Debug.Assert(replaceWhite.A == 255, "replaceWhite.Alpha is ignored, so please set it to 255 so I know you know what you're doing"); // Normalize the colors to 1.0. - float normBlackRed = ((float)replaceBlack.R)/(float)255.0; - float normBlackGreen = ((float)replaceBlack.G)/(float)255.0; - float normBlackBlue = ((float)replaceBlack.B)/(float)255.0; - float normBlackAlpha = ((float)replaceBlack.A)/(float)255.0; + float normBlackRed = ((float)replaceBlack.R) / (float)255.0; + float normBlackGreen = ((float)replaceBlack.G) / (float)255.0; + float normBlackBlue = ((float)replaceBlack.B) / (float)255.0; + float normBlackAlpha = ((float)replaceBlack.A) / (float)255.0; - float normWhiteRed = ((float)replaceWhite.R)/(float)255.0; - float normWhiteGreen = ((float)replaceWhite.G)/(float)255.0; - float normWhiteBlue = ((float)replaceWhite.B)/(float)255.0; - float normWhiteAlpha = ((float)replaceWhite.A)/(float)255.0; + float normWhiteRed = ((float)replaceWhite.R) / (float)255.0; + float normWhiteGreen = ((float)replaceWhite.G) / (float)255.0; + float normWhiteBlue = ((float)replaceWhite.B) / (float)255.0; + float normWhiteAlpha = ((float)replaceWhite.A) / (float)255.0; // Set up a matrix that will map white to replaceWhite and // black to replaceBlack, using the source bitmap's alpha value for the output @@ -2483,20 +2805,20 @@ private static ColorMatrix RemapBlackAndWhitePreserveTransparentMatrix(Color rep matrix.Matrix01 = -normBlackGreen; matrix.Matrix02 = -normBlackBlue; - matrix.Matrix10 = normWhiteRed; - matrix.Matrix11 = normWhiteGreen; - matrix.Matrix12 = normWhiteBlue; + matrix.Matrix10 = normWhiteRed; + matrix.Matrix11 = normWhiteGreen; + matrix.Matrix12 = normWhiteBlue; - matrix.Matrix33 = 1.0f; + matrix.Matrix33 = 1.0f; - matrix.Matrix40 = normBlackRed; - matrix.Matrix41 = normBlackGreen; - matrix.Matrix42 = normBlackBlue; - matrix.Matrix44 = 1.0f; + matrix.Matrix40 = normBlackRed; + matrix.Matrix41 = normBlackGreen; + matrix.Matrix42 = normBlackBlue; + matrix.Matrix44 = 1.0f; return matrix; } - + /* Unused internal static StringAlignment TranslateAlignment(HorizontalAlignment align) { StringAlignment result; @@ -2517,14 +2839,16 @@ internal static StringAlignment TranslateAlignment(HorizontalAlignment align) { } */ - internal static TextFormatFlags TextFormatFlagsForAlignmentGDI(ContentAlignment align) { + internal static TextFormatFlags TextFormatFlagsForAlignmentGDI(ContentAlignment align) + { TextFormatFlags output = new TextFormatFlags(); output |= TranslateAlignmentForGDI(align); output |= TranslateLineAlignmentForGDI(align); return output; } - internal static StringAlignment TranslateAlignment(ContentAlignment align) { + internal static StringAlignment TranslateAlignment(ContentAlignment align) + { StringAlignment result; if ((align & anyRight) != 0) result = StringAlignment.Far; @@ -2535,7 +2859,8 @@ internal static StringAlignment TranslateAlignment(ContentAlignment align) { return result; } - internal static TextFormatFlags TranslateAlignmentForGDI(ContentAlignment align) { + internal static TextFormatFlags TranslateAlignmentForGDI(ContentAlignment align) + { TextFormatFlags result; if ((align & anyBottom) != 0) result = TextFormatFlags.Bottom; @@ -2546,22 +2871,27 @@ internal static TextFormatFlags TranslateAlignmentForGDI(ContentAlignment align) return result; } - internal static StringAlignment TranslateLineAlignment(ContentAlignment align) { + internal static StringAlignment TranslateLineAlignment(ContentAlignment align) + { StringAlignment result; - if ((align & anyBottom) != 0) { + if ((align & anyBottom) != 0) + { result = StringAlignment.Far; } - else if ((align & anyMiddle) != 0) { + else if ((align & anyMiddle) != 0) + { result = StringAlignment.Center; } - else { + else + { result = StringAlignment.Near; } return result; } - internal static TextFormatFlags TranslateLineAlignmentForGDI(ContentAlignment align) { - TextFormatFlags result; + internal static TextFormatFlags TranslateLineAlignmentForGDI(ContentAlignment align) + { + TextFormatFlags result; if ((align & anyRight) != 0) result = TextFormatFlags.Right; else if ((align & anyCenter) != 0) @@ -2571,7 +2901,8 @@ internal static TextFormatFlags TranslateLineAlignmentForGDI(ContentAlignment al return result; } - internal static StringFormat StringFormatForAlignment(ContentAlignment align) { + internal static StringFormat StringFormatForAlignment(ContentAlignment align) + { StringFormat output = new StringFormat(); output.Alignment = TranslateAlignment(align); output.LineAlignment = TranslateLineAlignment(align); @@ -2589,33 +2920,40 @@ internal static StringFormat StringFormatForAlignment(HorizontalAlignment align) /// /// Get StringFormat object for rendering text using GDI+ (Graphics). /// - internal static StringFormat CreateStringFormat( Control ctl, ContentAlignment textAlign, bool showEllipsis, bool useMnemonic ) { + internal static StringFormat CreateStringFormat(Control ctl, ContentAlignment textAlign, bool showEllipsis, bool useMnemonic) + { - StringFormat stringFormat = ControlPaint.StringFormatForAlignment( textAlign ); + StringFormat stringFormat = ControlPaint.StringFormatForAlignment(textAlign); // make sure that the text is contained within the label // Adjust string format for Rtl controls - if( ctl.RightToLeft == RightToLeft.Yes ) { + if (ctl.RightToLeft == RightToLeft.Yes) + { stringFormat.FormatFlags |= StringFormatFlags.DirectionRightToLeft; } - if( showEllipsis ) { + if (showEllipsis) + { stringFormat.Trimming = StringTrimming.EllipsisCharacter; stringFormat.FormatFlags |= StringFormatFlags.LineLimit; } - if( !useMnemonic ) { + if (!useMnemonic) + { stringFormat.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.None; } - else if( ctl.ShowKeyboardCues ) { + else if (ctl.ShowKeyboardCues) + { stringFormat.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.Show; } - else { + else + { stringFormat.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.Hide; } - if( ctl.AutoSize ) { + if (ctl.AutoSize) + { stringFormat.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces; } @@ -2625,32 +2963,37 @@ internal static StringFormat CreateStringFormat( Control ctl, ContentAlignment t /// /// Get TextFormatFlags flags for rendering text using GDI (TextRenderer). /// - internal static TextFormatFlags CreateTextFormatFlags(Control ctl, ContentAlignment textAlign, bool showEllipsis, bool useMnemonic ) { + internal static TextFormatFlags CreateTextFormatFlags(Control ctl, ContentAlignment textAlign, bool showEllipsis, bool useMnemonic) + { - textAlign = ctl.RtlTranslateContent( textAlign ); - TextFormatFlags flags = ControlPaint.TextFormatFlagsForAlignmentGDI( textAlign ); + textAlign = ctl.RtlTranslateContent(textAlign); + TextFormatFlags flags = ControlPaint.TextFormatFlagsForAlignmentGDI(textAlign); // The effect of the TextBoxControl flag is that in-word line breaking will occur if needed, this happens when AutoSize // is false and a one-word line still doesn't fit the binding box (width). The other effect is that partially visible // lines are clipped; this is how GDI+ works by default. flags |= TextFormatFlags.WordBreak | TextFormatFlags.TextBoxControl; - if( showEllipsis ) { + if (showEllipsis) + { flags |= TextFormatFlags.EndEllipsis; } // Adjust string format for Rtl controls - if( ctl.RightToLeft == RightToLeft.Yes ) { + if (ctl.RightToLeft == RightToLeft.Yes) + { flags |= TextFormatFlags.RightToLeft; } //if we don't use mnemonic, set formatFlag to NoPrefix as this will show the ampersand - if( !useMnemonic ) { + if (!useMnemonic) + { flags |= TextFormatFlags.NoPrefix; } //else if we don't show keyboard cues, set formatFlag to HidePrefix as this will hide //the ampersand if we don't press down the alt key - else if( !ctl.ShowKeyboardCues ) { + else if (!ctl.ShowKeyboardCues) + { flags |= TextFormatFlags.HidePrefix; } @@ -2660,15 +3003,16 @@ internal static TextFormatFlags CreateTextFormatFlags(Control ctl, ContentAlignm /// /// Logic copied from Windows sources to copy the lightening and darkening of colors. /// - private struct HLSColor { - private const int ShadowAdj = -333; - private const int HilightAdj = 500; - private const int WatermarkAdj = -50; + private struct HLSColor + { + private const int ShadowAdj = -333; + private const int HilightAdj = 500; + private const int WatermarkAdj = -50; private const int Range = 240; private const int HLSMax = Range; private const int RGBMax = 255; - private const int Undefined = HLSMax*2/3; + private const int Undefined = HLSMax * 2 / 3; private int hue; private int saturation; @@ -2678,45 +3022,48 @@ private struct HLSColor { /// /// - public HLSColor(Color color) { + public HLSColor(Color color) + { isSystemColors_Control = (color.ToKnownColor() == SystemColors.Control.ToKnownColor()); int r = color.R; int g = color.G; int b = color.B; int max, min; /* max and min RGB values */ int sum, dif; - int Rdelta,Gdelta,Bdelta; /* intermediate value: % of spread from max */ + int Rdelta, Gdelta, Bdelta; /* intermediate value: % of spread from max */ /* calculate lightness */ - max = Math.Max( Math.Max(r,g), b); - min = Math.Min( Math.Min(r,g), b); + max = Math.Max(Math.Max(r, g), b); + min = Math.Min(Math.Min(r, g), b); sum = max + min; - luminosity = (((sum * HLSMax) + RGBMax)/(2*RGBMax)); + luminosity = (((sum * HLSMax) + RGBMax) / (2 * RGBMax)); dif = max - min; - if (dif == 0) { /* r=g=b --> achromatic case */ + if (dif == 0) + { /* r=g=b --> achromatic case */ saturation = 0; /* saturation */ hue = Undefined; /* hue */ } - else { /* chromatic case */ + else + { /* chromatic case */ /* saturation */ - if (luminosity <= (HLSMax/2)) - saturation = (int) (((dif * (int) HLSMax) + (sum / 2) ) / sum); + if (luminosity <= (HLSMax / 2)) + saturation = (int)(((dif * (int)HLSMax) + (sum / 2)) / sum); else - saturation = (int) ((int) ((dif * (int) HLSMax) + (int)((2*RGBMax-sum)/2) ) - / (2*RGBMax-sum)); + saturation = (int)((int)((dif * (int)HLSMax) + (int)((2 * RGBMax - sum) / 2)) + / (2 * RGBMax - sum)); /* hue */ - Rdelta = (int) (( ((max-r)*(int)(HLSMax/6)) + (dif / 2) ) / dif); - Gdelta = (int) (( ((max-g)*(int)(HLSMax/6)) + (dif / 2) ) / dif); - Bdelta = (int) (( ((max-b)*(int)(HLSMax/6)) + (dif / 2) ) / dif); + Rdelta = (int)((((max - r) * (int)(HLSMax / 6)) + (dif / 2)) / dif); + Gdelta = (int)((((max - g) * (int)(HLSMax / 6)) + (dif / 2)) / dif); + Bdelta = (int)((((max - b) * (int)(HLSMax / 6)) + (dif / 2)) / dif); - if ((int) r == max) + if ((int)r == max) hue = Bdelta - Gdelta; else if ((int)g == max) - hue = (HLSMax/3) + Rdelta - Bdelta; + hue = (HLSMax / 3) + Rdelta - Bdelta; else /* B == cMax */ - hue = ((2*HLSMax)/3) + Gdelta - Rdelta; + hue = ((2 * HLSMax) / 3) + Gdelta - Rdelta; if (hue < 0) hue += HLSMax; @@ -2737,8 +3084,10 @@ public int Hue { /// /// - public int Luminosity { - get { + public int Luminosity + { + get + { return luminosity; } } @@ -2755,17 +3104,22 @@ public int Saturation { /// /// - public Color Darker(float percDarker) { - if (isSystemColors_Control) { + public Color Darker(float percDarker) + { + if (isSystemColors_Control) + { // With the usual color scheme, ControlDark/DarkDark is not exactly // what we would otherwise calculate - if (percDarker == 0.0f) { + if (percDarker == 0.0f) + { return SystemColors.ControlDark; } - else if (percDarker == 1.0f) { + else if (percDarker == 1.0f) + { return SystemColors.ControlDarkDark; } - else { + else + { Color dark = SystemColors.ControlDark; Color darkDark = SystemColors.ControlDarkDark; @@ -2778,7 +3132,8 @@ public Color Darker(float percDarker) { (byte)(dark.B - (byte)(db * percDarker))); } } - else { + else + { int oneLum = 0; int zeroLum = NewLuma(ShadowAdj, true); @@ -2794,44 +3149,54 @@ public Color Darker(float percDarker) { return ColorFromHLS(hue, zeroLum - (int)((zeroLum - oneLum) * percDarker), saturation); } } - - public override bool Equals(object o) { - if (!(o is HLSColor)) { + + public override bool Equals(object o) + { + if (!(o is HLSColor)) + { return false; } - + HLSColor c = (HLSColor)o; - return hue == c.hue && - saturation == c.saturation && - luminosity == c.luminosity && + return hue == c.hue && + saturation == c.saturation && + luminosity == c.luminosity && isSystemColors_Control == c.isSystemColors_Control; } - public static bool operator ==(HLSColor a, HLSColor b) { + public static bool operator ==(HLSColor a, HLSColor b) + { return a.Equals(b); } - public static bool operator !=(HLSColor a, HLSColor b) { + public static bool operator !=(HLSColor a, HLSColor b) + { return !a.Equals(b); } - public override int GetHashCode() { + public override int GetHashCode() + { return hue << 6 | saturation << 2 | luminosity; } - + /// /// - public Color Lighter(float percLighter) { - if (isSystemColors_Control) { + public Color Lighter(float percLighter) + { + if (isSystemColors_Control) + { // With the usual color scheme, ControlLight/LightLight is not exactly // what we would otherwise calculate - if (percLighter == 0.0f) { + if (percLighter == 0.0f) + { return SystemColors.ControlLight; } - else if (percLighter == 1.0f) { + else if (percLighter == 1.0f) + { return SystemColors.ControlLightLight; } - else { + else + { Color light = SystemColors.ControlLight; Color lightLight = SystemColors.ControlLightLight; @@ -2844,7 +3209,8 @@ public Color Lighter(float percLighter) { (byte)(light.B - (byte)(db * percLighter))); } } - else { + else + { int zeroLum = luminosity; int oneLum = NewLuma(HilightAdj, true); @@ -2858,29 +3224,34 @@ public Color Lighter(float percLighter) { oneLum = NewLuma(HilightAdj, true); } */ - + return ColorFromHLS(hue, zeroLum + (int)((oneLum - zeroLum) * percLighter), saturation); } } /// /// - private int NewLuma(int n, bool scale) { + private int NewLuma(int n, bool scale) + { return NewLuma(luminosity, n, scale); } /// /// - private int NewLuma(int luminosity, int n, bool scale) { + private int NewLuma(int luminosity, int n, bool scale) + { if (n == 0) return luminosity; - if (scale) { - if (n > 0) { - return(int)(((int)luminosity * (1000 - n) + (Range + 1L) * n) / 1000); + if (scale) + { + if (n > 0) + { + return (int)(((int)luminosity * (1000 - n) + (Range + 1L) * n) / 1000); } - else { - return(int)(((int)luminosity * (n + 1000)) / 1000); + else + { + return (int)(((int)luminosity * (n + 1000)) / 1000); } } @@ -2897,35 +3268,40 @@ private int NewLuma(int luminosity, int n, bool scale) { /// /// - private Color ColorFromHLS(int hue, int luminosity, int saturation) { - byte r,g,b; /* RGB component values */ - int magic1,magic2; /* calculated magic numbers (really!) */ + private Color ColorFromHLS(int hue, int luminosity, int saturation) + { + byte r, g, b; /* RGB component values */ + int magic1, magic2; /* calculated magic numbers (really!) */ - if (saturation == 0) { /* achromatic case */ + if (saturation == 0) + { /* achromatic case */ r = g = b = (byte)((luminosity * RGBMax) / HLSMax); - if (hue != Undefined) { + if (hue != Undefined) + { /* ERROR */ } } - else { /* chromatic case */ + else + { /* chromatic case */ /* set up magic numbers */ - if (luminosity <= (HLSMax/2)) - magic2 = (int)((luminosity * ((int)HLSMax + saturation) + (HLSMax/2))/HLSMax); + if (luminosity <= (HLSMax / 2)) + magic2 = (int)((luminosity * ((int)HLSMax + saturation) + (HLSMax / 2)) / HLSMax); else - magic2 = luminosity + saturation - (int)(((luminosity*saturation) + (int)(HLSMax/2))/HLSMax); - magic1 = 2*luminosity-magic2; + magic2 = luminosity + saturation - (int)(((luminosity * saturation) + (int)(HLSMax / 2)) / HLSMax); + magic1 = 2 * luminosity - magic2; /* get RGB, change units from HLSMax to RGBMax */ - r = (byte)(((HueToRGB(magic1,magic2,(int)(hue+(int)(HLSMax/3)))*(int)RGBMax + (HLSMax/2))) / (int)HLSMax); - g = (byte)(((HueToRGB(magic1,magic2,hue)*(int)RGBMax + (HLSMax/2))) / HLSMax); - b = (byte)(((HueToRGB(magic1,magic2,(int)(hue-(int)(HLSMax/3)))*(int)RGBMax + (HLSMax/2))) / (int)HLSMax); + r = (byte)(((HueToRGB(magic1, magic2, (int)(hue + (int)(HLSMax / 3))) * (int)RGBMax + (HLSMax / 2))) / (int)HLSMax); + g = (byte)(((HueToRGB(magic1, magic2, hue) * (int)RGBMax + (HLSMax / 2))) / HLSMax); + b = (byte)(((HueToRGB(magic1, magic2, (int)(hue - (int)(HLSMax / 3))) * (int)RGBMax + (HLSMax / 2))) / (int)HLSMax); } - return Color.FromArgb(r,g,b); + return Color.FromArgb(r, g, b); } /// /// - private int HueToRGB(int n1, int n2, int hue) { + private int HueToRGB(int n1, int n2, int hue) + { /* range check: note values passed add/subtract thirds of range */ /* The following is redundant for WORD (unsigned int) */ @@ -2936,14 +3312,14 @@ private int HueToRGB(int n1, int n2, int hue) { hue -= HLSMax; /* return r,g, or b value from this tridrant */ - if (hue < (HLSMax/6)) - return( n1 + (((n2-n1)*hue+(HLSMax/12))/(HLSMax/6)) ); - if (hue < (HLSMax/2)) - return( n2 ); - if (hue < ((HLSMax*2)/3)) - return( n1 + (((n2-n1)*(((HLSMax*2)/3)-hue)+(HLSMax/12)) / (HLSMax/6)) ); + if (hue < (HLSMax / 6)) + return (n1 + (((n2 - n1) * hue + (HLSMax / 12)) / (HLSMax / 6))); + if (hue < (HLSMax / 2)) + return (n2); + if (hue < ((HLSMax * 2) / 3)) + return (n1 + (((n2 - n1) * (((HLSMax * 2) / 3) - hue) + (HLSMax / 12)) / (HLSMax / 6))); else - return( n1 ); + return (n1); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ConvertEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ConvertEventArgs.cs index 18b0c7f231f..ff2d751d4d0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ConvertEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ConvertEventArgs.cs @@ -11,7 +11,7 @@ public ConvertEventArgs(object value, Type desiredType) Value = value; DesiredType = desiredType; } - + public object Value { get; set; } public Type DesiredType { get; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs index 278a43aab60..1603d0b3fc4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs @@ -2,11 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using Microsoft.Win32; - using System.Diagnostics; + using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.ComponentModel; using System.Collections; @@ -17,14 +18,15 @@ namespace System.Windows.Forms { /// Manages the position and bindings of a /// list. /// - public class CurrencyManager : BindingManagerBase { + public class CurrencyManager : BindingManagerBase + { private object dataSource; private IList list; - + private bool bound = false; private bool shouldBind = true; - + /// /// [ @@ -57,12 +59,14 @@ public class CurrencyManager : BindingManagerBase { /// altered. /// [SRCategory(nameof(SR.CatData))] - public event ItemChangedEventHandler ItemChanged { + public event ItemChangedEventHandler ItemChanged + { add => onItemChanged += value; remove => onItemChanged -= value; } - public event ListChangedEventHandler ListChanged { + public event ListChangedEventHandler ListChanged + { add => onListChanged += value; remove => onListChanged -= value; } @@ -73,7 +77,8 @@ public event ListChangedEventHandler ListChanged { SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // If the constructor does not set the dataSource // it would be a breaking change. ] - internal CurrencyManager(object dataSource) { + internal CurrencyManager(object dataSource) + { SetDataSource(dataSource); } @@ -81,9 +86,12 @@ internal CurrencyManager(object dataSource) { /// Gets a value indicating /// whether items can be added to the list. /// - internal bool AllowAdd { - get { - if (list is IBindingList) { + internal bool AllowAdd + { + get + { + if (list is IBindingList) + { return ((IBindingList)list).AllowNew; } if (list == null) @@ -91,14 +99,17 @@ internal bool AllowAdd { return !list.IsReadOnly && !list.IsFixedSize; } } - + /// /// Gets a value /// indicating whether edits to the list are allowed. /// - internal bool AllowEdit { - get { - if (list is IBindingList) { + internal bool AllowEdit + { + get + { + if (list is IBindingList) + { return ((IBindingList)list).AllowEdit; } if (list == null) @@ -106,13 +117,16 @@ internal bool AllowEdit { return !list.IsReadOnly; } } - + /// /// Gets a value indicating whether items can be removed from the list. /// - internal bool AllowRemove { - get { - if (list is IBindingList) { + internal bool AllowRemove + { + get + { + if (list is IBindingList) + { return ((IBindingList)list).AllowRemove; } if (list == null) @@ -120,67 +134,81 @@ internal bool AllowRemove { return !list.IsReadOnly && !list.IsFixedSize; } } - + /// /// Gets the number of items in the list. /// - public override int Count { - get { + public override int Count + { + get + { if (list == null) return 0; else return list.Count; } } - + /// /// Gets the current item in the list. /// - public override object Current { - get { + public override object Current + { + get + { return this[Position]; } } - internal override Type BindType { - get { + internal override Type BindType + { + get + { return ListBindingHelper.GetListItemType(this.List); } } - + /// /// Gets the data source of the list. /// - internal override object DataSource { - get { + internal override object DataSource + { + get + { return dataSource; } } - private protected override void SetDataSource(object dataSource) { - if (this.dataSource != dataSource) { + private protected override void SetDataSource(object dataSource) + { + if (this.dataSource != dataSource) + { Release(); this.dataSource = dataSource; this.list = null; this.finalType = null; object tempList = dataSource; - if (tempList is Array) { + if (tempList is Array) + { finalType = tempList.GetType(); tempList = (Array)tempList; } - - if (tempList is IListSource) { - tempList = ((IListSource)tempList).GetList(); + + if (tempList is IListSource) + { + tempList = ((IListSource)tempList).GetList(); } - - if (tempList is IList) { - if (finalType == null) { + + if (tempList is IList) + { + if (finalType == null) + { finalType = tempList.GetType(); } this.list = (IList)tempList; WireEvents(list); - if (list.Count > 0 ) + if (list.Count > 0) listposition = 0; else listposition = -1; @@ -188,8 +216,10 @@ private protected override void SetDataSource(object dataSource) { OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1, -1)); UpdateIsBinding(); } - else { - if (tempList == null) { + else + { + if (tempList == null) + { throw new ArgumentNullException(nameof(dataSource)); } throw new ArgumentException(string.Format(SR.ListManagerSetDataSource, tempList.GetType().FullName), "dataSource"); @@ -201,15 +231,19 @@ private protected override void SetDataSource(object dataSource) { /// /// Gets a value indicating whether the list is bound to a data source. /// - internal override bool IsBinding { - get { + internal override bool IsBinding + { + get + { return bound; } } // The DataGridView needs this. - internal bool ShouldBind { - get { + internal bool ShouldBind + { + get + { return shouldBind; } } @@ -217,8 +251,10 @@ internal bool ShouldBind { /// /// Gets the list as an object. /// - public IList List { - get { + public IList List + { + get + { // NOTE: do not change this to throw an exception if the list is not IBindingList. // doing this will cause a major performance hit when wiring the // dataGrid to listen for MetaDataChanged events from the IBindingList @@ -232,11 +268,14 @@ public IList List { /// /// Gets or sets the position you are at within the list. /// - public override int Position { - get { + public override int Position + { + get + { return listposition; } - set { + set + { if (listposition == -1) return; @@ -255,71 +294,88 @@ public override int Position { /// /// Gets or sets the object at the specified index. /// - internal object this[int index] { - get { - if (index < 0 || index >= list.Count) { + internal object this[int index] + { + get + { + if (index < 0 || index >= list.Count) + { throw new IndexOutOfRangeException(string.Format(SR.ListManagerNoValue, index.ToString(CultureInfo.CurrentCulture))); } return list[index]; } - set { - if (index < 0 || index >= list.Count) { + set + { + if (index < 0 || index >= list.Count) + { throw new IndexOutOfRangeException(string.Format(SR.ListManagerNoValue, index.ToString(CultureInfo.CurrentCulture))); } list[index] = value; } } - - public override void AddNew() { + + public override void AddNew() + { IBindingList ibl = list as IBindingList; - if (ibl != null) { + if (ibl != null) + { ibl.AddNew(); } - else { + else + { // If the list is not IBindingList, then throw an exception: throw new NotSupportedException(SR.CurrencyManagerCantAddNew); } ChangeRecordState(list.Count - 1, (Position != list.Count - 1), (Position != list.Count - 1), true, true); // true for firingPositionChangeNotification - // true for pulling data from the controls + // true for pulling data from the controls } /// /// Cancels the current edit operation. /// - public override void CancelCurrentEdit() { - if (Count > 0) { + public override void CancelCurrentEdit() + { + if (Count > 0) + { object item = (Position >= 0 && Position < list.Count) ? list[Position] : null; // onItemChangedCalled = false; IEditableObject iEditableItem = item as IEditableObject; - if (iEditableItem != null) { + if (iEditableItem != null) + { iEditableItem.CancelEdit(); } ICancelAddNew iListWithCancelAddNewSupport = list as ICancelAddNew; - if (iListWithCancelAddNewSupport != null) { + if (iListWithCancelAddNewSupport != null) + { iListWithCancelAddNewSupport.CancelNew(this.Position); } OnItemChanged(new ItemChangedEventArgs(Position)); - if (this.Position != -1) { + if (this.Position != -1) + { OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, this.Position)); } } } - private void ChangeRecordState(int newPosition, bool validating, bool endCurrentEdit, bool firePositionChange, bool pullData) { - if (newPosition == -1 && list.Count == 0) { - if (listposition != -1) { + private void ChangeRecordState(int newPosition, bool validating, bool endCurrentEdit, bool firePositionChange, bool pullData) + { + if (newPosition == -1 && list.Count == 0) + { + if (listposition != -1) + { this.listposition = -1; OnPositionChanged(EventArgs.Empty); } return; } - - if ((newPosition < 0 || newPosition >= Count) && this.IsBinding) { + + if ((newPosition < 0 || newPosition >= Count) && this.IsBinding) + { throw new IndexOutOfRangeException(SR.ListManagerBadPosition); } @@ -329,55 +385,68 @@ private void ChangeRecordState(int newPosition, bool validating, bool endCurrent // this is why we have to cache the old position and compare that w/ the position that // the user will want to navigate to int oldPosition = listposition; - if (endCurrentEdit) { + if (endCurrentEdit) + { // Do not PushData when pro. inChangeRecordState = true; - try { + try + { EndCurrentEdit(); - } finally { + } + finally + { inChangeRecordState = false; } } // we pull the data from the controls only when the ListManager changes the list. when the backEnd changes the list we do not // pull the data from the controls - if (validating && pullData) { + if (validating && pullData) + { CurrencyManager_PullData(); } // EndCurrentEdit or PullData can cause the list managed by the CurrencyManager to shrink. this.listposition = Math.Min(newPosition, Count - 1); - if (validating) { + if (validating) + { OnCurrentChanged(EventArgs.Empty); } - + bool positionChanging = (oldPosition != listposition); - if (positionChanging && firePositionChange) { + if (positionChanging && firePositionChange) + { OnPositionChanged(EventArgs.Empty); - } + } } /// /// Throws an exception if there is no list. /// - protected void CheckEmpty() { - if (dataSource == null || list == null || list.Count == 0) { + protected void CheckEmpty() + { + if (dataSource == null || list == null || list.Count == 0) + { throw new InvalidOperationException(SR.ListManagerEmptyList); } } // will return true if this function changes the position in the list - private bool CurrencyManager_PushData() { + private bool CurrencyManager_PushData() + { if (pullingData) return false; int initialPosition = listposition; - if (lastGoodKnownRow == -1) { - try { + if (lastGoodKnownRow == -1) + { + try + { PushData(); } - catch (Exception ex) { + catch (Exception ex) + { OnDataError(ex); // get the first item in the list that is good to push data @@ -386,11 +455,15 @@ private bool CurrencyManager_PushData() { FindGoodRow(); } lastGoodKnownRow = listposition; - } else { - try { + } + else + { + try + { PushData(); } - catch (Exception ex) { + catch (Exception ex) + { OnDataError(ex); listposition = lastGoodKnownRow; @@ -402,54 +475,68 @@ private bool CurrencyManager_PushData() { return initialPosition != listposition; } - private bool CurrencyManager_PullData() { + private bool CurrencyManager_PullData() + { bool success = true; pullingData = true; - try { + try + { PullData(out success); - } finally { + } + finally + { pullingData = false; } return success; } - public override void RemoveAt(int index) { + public override void RemoveAt(int index) + { list.RemoveAt(index); } /// /// Ends the current edit operation. /// - public override void EndCurrentEdit() { - if (Count > 0) { + public override void EndCurrentEdit() + { + if (Count > 0) + { bool success = CurrencyManager_PullData(); - if (success) { + if (success) + { object item = (Position >= 0 && Position < list.Count) ? list[Position] : null; IEditableObject iEditableItem = item as IEditableObject; - if (iEditableItem != null) { + if (iEditableItem != null) + { iEditableItem.EndEdit(); } ICancelAddNew iListWithCancelAddNewSupport = list as ICancelAddNew; - if (iListWithCancelAddNewSupport != null) { + if (iListWithCancelAddNewSupport != null) + { iListWithCancelAddNewSupport.EndNew(this.Position); } } } } - private void FindGoodRow() { + private void FindGoodRow() + { int rowCount = this.list.Count; - for (int i = 0; i < rowCount; i++) { + for (int i = 0; i < rowCount; i++) + { listposition = i; - try { + try + { PushData(); } - catch (Exception ex) { + catch (Exception ex) + { OnDataError(ex); continue; } @@ -465,17 +552,21 @@ private void FindGoodRow() { /// /// Sets the column to sort by, and the direction of the sort. /// - internal void SetSort(PropertyDescriptor property, ListSortDirection sortDirection) { - if (list is IBindingList && ((IBindingList)list).SupportsSorting) { + internal void SetSort(PropertyDescriptor property, ListSortDirection sortDirection) + { + if (list is IBindingList && ((IBindingList)list).SupportsSorting) + { ((IBindingList)list).ApplySort(property, sortDirection); } } - + /// /// Gets a for a CurrencyManager. /// - internal PropertyDescriptor GetSortProperty() { - if ((list is IBindingList) && ((IBindingList)list).SupportsSorting) { + internal PropertyDescriptor GetSortProperty() + { + if ((list is IBindingList) && ((IBindingList)list).SupportsSorting) + { return ((IBindingList)list).SortProperty; } return null; @@ -484,28 +575,35 @@ internal PropertyDescriptor GetSortProperty() { /// /// Gets the sort direction of a list. /// - internal ListSortDirection GetSortDirection() { - if ((list is IBindingList) && ((IBindingList)list).SupportsSorting) { + internal ListSortDirection GetSortDirection() + { + if ((list is IBindingList) && ((IBindingList)list).SupportsSorting) + { return ((IBindingList)list).SortDirection; } return ListSortDirection.Ascending; } - + /// /// Find the position of a desired list item. /// - internal int Find(PropertyDescriptor property, object key, bool keepIndex) { + internal int Find(PropertyDescriptor property, object key, bool keepIndex) + { if (key == null) throw new ArgumentNullException(nameof(key)); - if (property != null && (list is IBindingList) && ((IBindingList)list).SupportsSearching) { + if (property != null && (list is IBindingList) && ((IBindingList)list).SupportsSearching) + { return ((IBindingList)list).Find(property, key); } - if (property != null) { - for (int i = 0; i < list.Count; i++) { + if (property != null) + { + for (int i = 0; i < list.Count; i++) + { object value = property.GetValue(list[i]); - if (key.Equals(value)) { + if (key.Equals(value)) + { return i; } } @@ -517,11 +615,14 @@ internal int Find(PropertyDescriptor property, object key, bool keepIndex) { /// /// Gets the name of the list. /// - internal override string GetListName() { - if (list is ITypedList) { + internal override string GetListName() + { + if (list is ITypedList) + { return ((ITypedList)list).GetListName(null); } - else { + else + { return finalType.Name; } } @@ -529,18 +630,21 @@ internal override string GetListName() { /// /// Gets the name of the specified list. /// - protected internal override string GetListName(ArrayList listAccessors) { - if (list is ITypedList) { + protected internal override string GetListName(ArrayList listAccessors) + { + if (list is ITypedList) + { PropertyDescriptor[] properties = new PropertyDescriptor[listAccessors.Count]; listAccessors.CopyTo(properties, 0); return ((ITypedList)list).GetListName(properties); } - return ""; + return ""; } - + /// /// - internal override PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors) { + internal override PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors) + { return ListBindingHelper.GetListItemProperties(this.list, listAccessors); } @@ -548,14 +652,16 @@ internal override PropertyDescriptorCollection GetItemProperties(PropertyDescrip /// Gets the for /// the list. /// - public override PropertyDescriptorCollection GetItemProperties() { + public override PropertyDescriptorCollection GetItemProperties() + { return GetItemProperties(null); } /// /// Gets the for the specified list. /// - private void List_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e) { + private void List_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e) + { // If you change the assert below, better change the // code in the OnCurrentChanged that deals w/ firing the OnCurrentChanged event Debug.Assert(lastGoodKnownRow == -1 || lastGoodKnownRow == listposition, "if we have a valid lastGoodKnownRow, then it should equal the position in the list"); @@ -568,11 +674,16 @@ private void List_ListChanged(object sender, System.ComponentModel.ListChangedEv ListChangedEventArgs dbe; - if (e.ListChangedType == ListChangedType.ItemMoved && e.OldIndex < 0) { + if (e.ListChangedType == ListChangedType.ItemMoved && e.OldIndex < 0) + { dbe = new ListChangedEventArgs(ListChangedType.ItemAdded, e.NewIndex, e.OldIndex); - } else if (e.ListChangedType == ListChangedType.ItemMoved && e.NewIndex < 0) { + } + else if (e.ListChangedType == ListChangedType.ItemMoved && e.NewIndex < 0) + { dbe = new ListChangedEventArgs(ListChangedType.ItemDeleted, e.OldIndex, e.NewIndex); - } else { + } + else + { dbe = e; } @@ -581,21 +692,25 @@ private void List_ListChanged(object sender, System.ComponentModel.ListChangedEv UpdateLastGoodKnownRow(dbe); UpdateIsBinding(); - if (list.Count == 0) { + if (list.Count == 0) + { listposition = -1; - if (oldposition != -1) { + if (oldposition != -1) + { // if we used to have a current row, but not any more, then report current as changed OnPositionChanged(EventArgs.Empty); OnCurrentChanged(EventArgs.Empty); } - if (dbe.ListChangedType == System.ComponentModel.ListChangedType.Reset && e.NewIndex == -1) { + if (dbe.ListChangedType == System.ComponentModel.ListChangedType.Reset && e.NewIndex == -1) + { // if the list is reset, then let our users know about it. OnItemChanged(resetEvent); } - if (dbe.ListChangedType == System.ComponentModel.ListChangedType.ItemDeleted) { + if (dbe.ListChangedType == System.ComponentModel.ListChangedType.ItemDeleted) + { // if the list is reset, then let our users know about it. OnItemChanged(resetEvent); } @@ -612,22 +727,25 @@ private void List_ListChanged(object sender, System.ComponentModel.ListChangedEv OnListChanged(dbe); return; } - + suspendPushDataInCurrentChanged = true; - try { - switch (dbe.ListChangedType) { + try + { + switch (dbe.ListChangedType) + { case System.ComponentModel.ListChangedType.Reset: Debug.WriteLineIf(CompModSwitches.DataCursor.TraceVerbose, "System.ComponentModel.ListChangedType.Reset Position: " + Position + " Count: " + list.Count); if (listposition == -1 && list.Count > 0) ChangeRecordState(0, true, false, true, false); // last false: we don't pull the data from the control when DM changes - else - ChangeRecordState(Math.Min(listposition,list.Count - 1), true, false, true, false); + else + ChangeRecordState(Math.Min(listposition, list.Count - 1), true, false, true, false); UpdateIsBinding(/*raiseItemChangedEvent:*/ false); OnItemChanged(resetEvent); break; case System.ComponentModel.ListChangedType.ItemAdded: Debug.WriteLineIf(CompModSwitches.DataCursor.TraceVerbose, "System.ComponentModel.ListChangedType.ItemAdded " + dbe.NewIndex.ToString(CultureInfo.InvariantCulture)); - if (dbe.NewIndex <= listposition && listposition < list.Count - 1) { + if (dbe.NewIndex <= listposition && listposition < list.Count - 1) + { // this means the current row just moved down by one. // the position changes, so end the current edit ChangeRecordState(listposition + 1, true, true, listposition != list.Count - 2, false); @@ -639,7 +757,9 @@ private void List_ListChanged(object sender, System.ComponentModel.ListChangedEv if (listposition == list.Count - 1) OnPositionChanged(EventArgs.Empty); break; - } else if (dbe.NewIndex == this.listposition && this.listposition == list.Count - 1 && this.listposition != -1) { + } + else if (dbe.NewIndex == this.listposition && this.listposition == list.Count - 1 && this.listposition != -1) + { // The CurrencyManager has a non-empty list. // The position inside the currency manager is at the end of the list and the list still fired an ItemAdded event. // This could be the second ItemAdded event that the DataView fires to signal that the AddNew operation was commited. @@ -647,7 +767,8 @@ private void List_ListChanged(object sender, System.ComponentModel.ListChangedEv OnCurrentItemChanged(EventArgs.Empty); } - if (listposition == -1) { + if (listposition == -1) + { // do not call EndEdit on a row that was not there ( position == -1) ChangeRecordState(0, false, false, true, false); } @@ -661,7 +782,8 @@ private void List_ListChanged(object sender, System.ComponentModel.ListChangedEv break; case System.ComponentModel.ListChangedType.ItemDeleted: Debug.WriteLineIf(CompModSwitches.DataCursor.TraceVerbose, "System.ComponentModel.ListChangedType.ItemDeleted " + dbe.NewIndex.ToString(CultureInfo.InvariantCulture)); - if (dbe.NewIndex == listposition) { + if (dbe.NewIndex == listposition) + { // this means that the current row got deleted. // cannot end an edit on a row that does not exist anymore ChangeRecordState(Math.Min(listposition, Count - 1), true, false, true, false); @@ -669,9 +791,10 @@ private void List_ListChanged(object sender, System.ComponentModel.ListChangedEv // in the currencyManager, so controls will use the actual position OnItemChanged(resetEvent); break; - + } - if (dbe.NewIndex < listposition) { + if (dbe.NewIndex < listposition) + { // this means the current row just moved up by one. // cannot end an edit on a row that does not exist anymore ChangeRecordState(listposition - 1, true, false, true, false); @@ -685,7 +808,8 @@ private void List_ListChanged(object sender, System.ComponentModel.ListChangedEv case System.ComponentModel.ListChangedType.ItemChanged: Debug.WriteLineIf(CompModSwitches.DataCursor.TraceVerbose, "System.ComponentModel.ListChangedType.ItemChanged " + dbe.NewIndex.ToString(CultureInfo.InvariantCulture)); // the current item changed - if (dbe.NewIndex == this.listposition) { + if (dbe.NewIndex == this.listposition) + { OnCurrentItemChanged(EventArgs.Empty); } @@ -693,11 +817,13 @@ private void List_ListChanged(object sender, System.ComponentModel.ListChangedEv break; case System.ComponentModel.ListChangedType.ItemMoved: Debug.WriteLineIf(CompModSwitches.DataCursor.TraceVerbose, "System.ComponentModel.ListChangedType.ItemMoved " + dbe.NewIndex.ToString(CultureInfo.InvariantCulture)); - if (dbe.OldIndex == listposition) { // current got moved. + if (dbe.OldIndex == listposition) + { // current got moved. // the position changes, so end the current edit. Make sure there is something that we can end edit... ChangeRecordState(dbe.NewIndex, true, this.Position > -1 && this.Position < list.Count, true, false); } - else if (dbe.NewIndex == listposition) { // current was moved + else if (dbe.NewIndex == listposition) + { // current was moved // the position changes, so end the current edit. Make sure there is something that we can end edit ChangeRecordState(dbe.OldIndex, true, this.Position > -1 && this.Position < list.Count, true, false); } @@ -725,7 +851,9 @@ private void List_ListChanged(object sender, System.ComponentModel.ListChangedEv OnListChanged(dbe); - } finally { + } + finally + { suspendPushDataInCurrentChanged = false; } Debug.Assert(lastGoodKnownRow == -1 || listposition == lastGoodKnownRow, "how did they get out of sync?"); @@ -733,7 +861,8 @@ private void List_ListChanged(object sender, System.ComponentModel.ListChangedEv [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] //Exists in Everett [SRCategory(nameof(SR.CatData))] - public event EventHandler MetaDataChanged { + public event EventHandler MetaDataChanged + { add => onMetaDataChangedHandler += value; remove => onMetaDataChangedHandler -= value; } @@ -741,47 +870,56 @@ public event EventHandler MetaDataChanged { /// /// Causes the CurrentChanged event to occur. /// - internal protected override void OnCurrentChanged(EventArgs e) { - if (!inChangeRecordState) { + internal protected override void OnCurrentChanged(EventArgs e) + { + if (!inChangeRecordState) + { Debug.WriteLineIf(CompModSwitches.DataView.TraceVerbose, "OnCurrentChanged() " + e.ToString()); int curLastGoodKnownRow = lastGoodKnownRow; bool positionChanged = false; if (!suspendPushDataInCurrentChanged) positionChanged = CurrencyManager_PushData(); - if (Count > 0) { + if (Count > 0) + { object item = list[Position]; - if (item is IEditableObject) { + if (item is IEditableObject) + { ((IEditableObject)item).BeginEdit(); } } - try { + try + { // if currencyManager changed position then we have two cases: // 1. the previous lastGoodKnownRow was valid: in that case we fell back so do not fire onCurrentChanged // 2. the previous lastGoodKnownRow was invalid: we have two cases: // a. FindGoodRow actually found a good row, so it can't be the one before the user changed the position: fire the onCurrentChanged // b. FindGoodRow did not find a good row: we should have gotten an exception so we should not even execute this code - if (!positionChanged ||(positionChanged && curLastGoodKnownRow != -1)) { + if (!positionChanged || (positionChanged && curLastGoodKnownRow != -1)) + { onCurrentChangedHandler?.Invoke(this, e); // we fire OnCurrentItemChanged event every time we fire the CurrentChanged + when a property of the Current item changed _onCurrentItemChangedHandler?.Invoke(this, e); } } - catch (Exception ex) { + catch (Exception ex) + { OnDataError(ex); - } + } } } // this method should only be called when the currency manager receives the ListChangedType.ItemChanged event // and when the index of the ListChangedEventArgs == the position in the currency manager - protected internal override void OnCurrentItemChanged(EventArgs e) { + protected internal override void OnCurrentItemChanged(EventArgs e) + { _onCurrentItemChangedHandler?.Invoke(this, e); } - + /// /// - protected virtual void OnItemChanged(ItemChangedEventArgs e) { + protected virtual void OnItemChanged(ItemChangedEventArgs e) + { // It is possible that CurrencyManager_PushData will change the position // in the list. in that case we have to fire OnPositionChanged event bool positionChanged = false; @@ -791,11 +929,13 @@ protected virtual void OnItemChanged(ItemChangedEventArgs e) { if ((e.Index == listposition || (e.Index == -1 && Position < Count)) && !inChangeRecordState) positionChanged = CurrencyManager_PushData(); Debug.WriteLineIf(CompModSwitches.DataView.TraceVerbose, "OnItemChanged(" + e.Index.ToString(CultureInfo.InvariantCulture) + ") " + e.ToString()); - try { + try + { if (onItemChanged != null) onItemChanged(this, e); } - catch (Exception ex) { + catch (Exception ex) + { OnDataError(ex); } @@ -804,7 +944,8 @@ protected virtual void OnItemChanged(ItemChangedEventArgs e) { // onItemChangedCalled = true; } - private void OnListChanged(ListChangedEventArgs e) { + private void OnListChanged(ListChangedEventArgs e) + { if (onListChanged != null) onListChanged(this, e); } @@ -813,21 +954,24 @@ private void OnListChanged(ListChangedEventArgs e) { internal protected void OnMetaDataChanged(EventArgs e) { if (onMetaDataChangedHandler != null) - onMetaDataChangedHandler(this,e); + onMetaDataChangedHandler(this, e); } /// /// - protected virtual void OnPositionChanged(EventArgs e) { + protected virtual void OnPositionChanged(EventArgs e) + { // if (!inChangeRecordState) { - Debug.WriteLineIf(CompModSwitches.DataView.TraceVerbose, "OnPositionChanged(" + listposition.ToString(CultureInfo.InvariantCulture) + ") " + e.ToString()); - try { - if (onPositionChangedHandler != null) - onPositionChangedHandler(this, e); - } - catch (Exception ex) { - OnDataError(ex); - } + Debug.WriteLineIf(CompModSwitches.DataView.TraceVerbose, "OnPositionChanged(" + listposition.ToString(CultureInfo.InvariantCulture) + ") " + e.ToString()); + try + { + if (onPositionChangedHandler != null) + onPositionChangedHandler(this, e); + } + catch (Exception ex) + { + OnDataError(ex); + } // } } @@ -836,36 +980,46 @@ protected virtual void OnPositionChanged(EventArgs e) { /// Forces a repopulation of the CurrencyManager /// /// - public void Refresh() { - if (list.Count > 0 ) { - if (listposition >= list.Count) { + public void Refresh() + { + if (list.Count > 0) + { + if (listposition >= list.Count) + { lastGoodKnownRow = -1; listposition = 0; } - } else { + } + else + { listposition = -1; } List_ListChanged(list, new System.ComponentModel.ListChangedEventArgs(System.ComponentModel.ListChangedType.Reset, -1)); } - internal void Release() { + internal void Release() + { UnwireEvents(list); } /// /// Resumes binding of component properties to list items. /// - public override void ResumeBinding() { + public override void ResumeBinding() + { lastGoodKnownRow = -1; - try { - if (!shouldBind) { + try + { + if (!shouldBind) + { shouldBind = true; // we need to put the listPosition at the beginning of the list if the list is not empty - this.listposition = (this.list != null && this.list.Count != 0) ? 0:-1; + this.listposition = (this.list != null && this.list.Count != 0) ? 0 : -1; UpdateIsBinding(); } } - catch { + catch + { shouldBind = false; UpdateIsBinding(); throw; @@ -875,16 +1029,20 @@ public override void ResumeBinding() { /// /// Suspends binding. /// - public override void SuspendBinding() { + public override void SuspendBinding() + { lastGoodKnownRow = -1; - if (shouldBind) { + if (shouldBind) + { shouldBind = false; UpdateIsBinding(); } } - internal void UnwireEvents(IList list) { - if ((list is IBindingList) && ((IBindingList)list).SupportsChangeNotification) { + internal void UnwireEvents(IList list) + { + if ((list is IBindingList) && ((IBindingList)list).SupportsChangeNotification) + { ((IBindingList)list).ListChanged -= new System.ComponentModel.ListChangedEventHandler(List_ListChanged); /* ILiveList liveList = (ILiveList) list; @@ -892,34 +1050,41 @@ internal void UnwireEvents(IList list) { */ } } - - protected override void UpdateIsBinding() { + + protected override void UpdateIsBinding() + { UpdateIsBinding(true); } - private void UpdateIsBinding(bool raiseItemChangedEvent) { + private void UpdateIsBinding(bool raiseItemChangedEvent) + { bool newBound = list != null && list.Count > 0 && shouldBind && listposition != -1; if (list != null) - if (bound != newBound) { - // we will call end edit when moving from bound state to unbounded state - // - //bool endCurrentEdit = bound && !newBound; - bound = newBound; - int newPos = newBound ? 0 : -1; - ChangeRecordState(newPos, bound, (Position != newPos), true, false); - int numLinks = Bindings.Count; - for (int i = 0; i < numLinks; i++) { - Bindings[i].UpdateIsBinding(); - } + if (bound != newBound) + { + // we will call end edit when moving from bound state to unbounded state + // + //bool endCurrentEdit = bound && !newBound; + bound = newBound; + int newPos = newBound ? 0 : -1; + ChangeRecordState(newPos, bound, (Position != newPos), true, false); + int numLinks = Bindings.Count; + for (int i = 0; i < numLinks; i++) + { + Bindings[i].UpdateIsBinding(); + } - if (raiseItemChangedEvent) { - OnItemChanged(resetEvent); + if (raiseItemChangedEvent) + { + OnItemChanged(resetEvent); + } } - } } - private void UpdateLastGoodKnownRow(System.ComponentModel.ListChangedEventArgs e) { - switch (e.ListChangedType) { + private void UpdateLastGoodKnownRow(System.ComponentModel.ListChangedEventArgs e) + { + switch (e.ListChangedType) + { case System.ComponentModel.ListChangedType.ItemDeleted: if (e.NewIndex == lastGoodKnownRow) lastGoodKnownRow = -1; @@ -929,7 +1094,7 @@ private void UpdateLastGoodKnownRow(System.ComponentModel.ListChangedEventArgs e break; case System.ComponentModel.ListChangedType.ItemAdded: if (e.NewIndex <= lastGoodKnownRow && lastGoodKnownRow < this.List.Count - 1) - lastGoodKnownRow ++; + lastGoodKnownRow++; break; case System.ComponentModel.ListChangedType.ItemMoved: if (e.OldIndex == lastGoodKnownRow) @@ -942,8 +1107,10 @@ private void UpdateLastGoodKnownRow(System.ComponentModel.ListChangedEventArgs e } } - internal void WireEvents(IList list) { - if ((list is IBindingList) && ((IBindingList)list).SupportsChangeNotification) { + internal void WireEvents(IList list) + { + if ((list is IBindingList) && ((IBindingList)list).SupportsChangeNotification) + { ((IBindingList)list).ListChanged += new System.ComponentModel.ListChangedEventHandler(List_ListChanged); /* ILiveList liveList = (ILiveList) list; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Cursor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Cursor.cs index 46abc79bff4..9ebabdbc022 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Cursor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Cursor.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.InteropServices; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -30,33 +31,40 @@ namespace System.Windows.Forms { Serializable, Editor("System.Drawing.Design.CursorEditor, " + AssemblyRef.SystemDrawingDesign, typeof(UITypeEditor)) ] - public sealed class Cursor : IDisposable, ISerializable { + public sealed class Cursor : IDisposable, ISerializable + { private static Size cursorSize = System.Drawing.Size.Empty; private byte[] cursorData; private IntPtr handle = IntPtr.Zero; // handle to loaded image private bool ownHandle = true; - private int resourceId = 0; + private int resourceId = 0; private object userData; /** * Constructor used in deserialization */ - internal Cursor(SerializationInfo info, StreamingContext context) { + internal Cursor(SerializationInfo info, StreamingContext context) + { SerializationInfoEnumerator sie = info.GetEnumerator(); - if (sie == null) { + if (sie == null) + { return; } - for (; sie.MoveNext();) { + for (; sie.MoveNext();) + { // Dont catch any exceptions while Deserialising objects from stream. - if (string.Equals(sie.Name, "CursorData", StringComparison.OrdinalIgnoreCase) ){ + if (string.Equals(sie.Name, "CursorData", StringComparison.OrdinalIgnoreCase)) + { cursorData = (byte[])sie.Value; - if (cursorData != null) { + if (cursorData != null) + { LoadPicture(new UnsafeNativeMethods.ComStreamFromDataStream(new MemoryStream(cursorData))); } } - else if (string.Compare(sie.Name, "CursorResourceId", true, CultureInfo.InvariantCulture) == 0) { + else if (string.Compare(sie.Name, "CursorResourceId", true, CultureInfo.InvariantCulture) == 0) + { LoadFromResourceId((int)sie.Value); } } @@ -67,7 +75,8 @@ internal Cursor(SerializationInfo info, StreamingContext context) { /// definitions in the Cursors class. /// // - internal Cursor(int nResourceId, int dummy) { + internal Cursor(int nResourceId, int dummy) + { LoadFromResourceId(nResourceId); } @@ -78,7 +87,8 @@ internal Cursor(int nResourceId, int dummy) { // throwing in is really rude and will prevent any of windows forms // from initializing. This seems extreme just because we fail to // load a cursor. - internal Cursor(string resource, int dummy) { + internal Cursor(string resource, int dummy) + { Stream stream = typeof(Cursor).Module.Assembly.GetManifestResourceStream(typeof(Cursor), resource); Debug.Assert(stream != null, "couldn't get stream for resource " + resource); cursorData = new byte[stream.Length]; @@ -91,8 +101,10 @@ internal Cursor(string resource, int dummy) { /// Initializes a new instance of the class with the specified handle. /// /// - public Cursor(IntPtr handle) { - if (handle == IntPtr.Zero) { + public Cursor(IntPtr handle) + { + if (handle == IntPtr.Zero) + { throw new ArgumentException(string.Format(SR.InvalidGDIHandle, (typeof(Cursor)).Name)); } @@ -107,15 +119,18 @@ public Cursor(IntPtr handle) { /// the specified filename. /// /// - public Cursor(string fileName) { + public Cursor(string fileName) + { //Filestream demands the correct FILEIO access here // FileStream f = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); - try { + try + { cursorData = new byte[f.Length]; f.Read(cursorData, 0, Convert.ToInt32(f.Length)); // assume that a cursor is less than 4gig... } - finally { + finally + { f.Close(); } LoadPicture(new UnsafeNativeMethods.ComStreamFromDataStream(new MemoryStream(cursorData))); @@ -126,7 +141,8 @@ public Cursor(string fileName) { /// Initializes a new instance of the class from the specified resource. /// /// - public Cursor(Type type, string resource) : this(type.Module.Assembly.GetManifestResourceStream(type,resource)) { + public Cursor(Type type, string resource) : this(type.Module.Assembly.GetManifestResourceStream(type, resource)) + { } /// @@ -135,13 +151,14 @@ public Cursor(Type type, string resource) : this(type.Module.Assembly.GetManifes /// specified data stream. /// /// - public Cursor(Stream stream) { + public Cursor(Stream stream) + { cursorData = new byte[stream.Length]; stream.Read(cursorData, 0, Convert.ToInt32(stream.Length));// assume that a cursor is less than 4gig... LoadPicture(new UnsafeNativeMethods.ComStreamFromDataStream(new MemoryStream(cursorData))); } - + /// /// /// Gets or @@ -149,11 +166,14 @@ public Cursor(Stream stream) { /// screen coordinates. /// /// - public static Rectangle Clip { - get { + public static Rectangle Clip + { + get + { return ClipInternal; } - set { + set + { ClipInternal = value; } } @@ -163,16 +183,20 @@ public static Rectangle Clip { /// internal static Rectangle ClipInternal { - get { + get + { NativeMethods.RECT r = new NativeMethods.RECT(); SafeNativeMethods.GetClipCursor(ref r); return Rectangle.FromLTRB(r.left, r.top, r.right, r.bottom); } - set { - if (value.IsEmpty) { + set + { + if (value.IsEmpty) + { UnsafeNativeMethods.ClipCursor(null); } - else { + else + { NativeMethods.RECT rcClip = NativeMethods.RECT.FromXYWH(value.X, value.Y, value.Width, value.Height); UnsafeNativeMethods.ClipCursor(ref rcClip); } @@ -186,23 +210,29 @@ internal static Rectangle ClipInternal /// represents the current mouse cursor. The value is NULL if the current mouse cursor is not visible. /// /// - public static Cursor Current { - get { + public static Cursor Current + { + get + { return CurrentInternal; } - set { + set + { CurrentInternal = value; } } - internal static Cursor CurrentInternal { - get { + internal static Cursor CurrentInternal + { + get + { IntPtr curHandle = SafeNativeMethods.GetCursor(); - return Cursors.KnownCursorFromHCursor( curHandle ); + return Cursors.KnownCursorFromHCursor(curHandle); } - set { + set + { IntPtr handle = (value == null) ? IntPtr.Zero : value.handle; UnsafeNativeMethods.SetCursor(new HandleRef(value, handle)); } @@ -214,9 +244,12 @@ internal static Cursor CurrentInternal { /// the Win32 handle for this . /// /// - public IntPtr Handle { - get { - if (handle == IntPtr.Zero) { + public IntPtr Handle + { + get + { + if (handle == IntPtr.Zero) + { throw new ObjectDisposedException(string.Format(SR.ObjectDisposed, GetType().Name)); } return handle; @@ -231,30 +264,35 @@ public IntPtr Handle { [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] //Minor, not worth breaking change public Point HotSpot { - get { + get + { Point hotSpot = Point.Empty; NativeMethods.ICONINFO info = new NativeMethods.ICONINFO(); Icon currentIcon = null; currentIcon = Icon.FromHandle(this.Handle); - try { + try + { SafeNativeMethods.GetIconInfo(new HandleRef(this, currentIcon.Handle), info); hotSpot = new Point(info.xHotspot, info.yHotspot); } - finally { + finally + { // GetIconInfo creates bitmaps for the hbmMask and hbmColor members of ICONINFO. // The calling application must manage these bitmaps and delete them when they are no longer necessary. - - if (info.hbmMask != IntPtr.Zero) { - // ExternalDelete to prevent Handle underflow - SafeNativeMethods.ExternalDeleteObject(new HandleRef(null, info.hbmMask)); - info.hbmMask = IntPtr.Zero; + + if (info.hbmMask != IntPtr.Zero) + { + // ExternalDelete to prevent Handle underflow + SafeNativeMethods.ExternalDeleteObject(new HandleRef(null, info.hbmMask)); + info.hbmMask = IntPtr.Zero; } - if (info.hbmColor != IntPtr.Zero) { - // ExternalDelete to prevent Handle underflow - SafeNativeMethods.ExternalDeleteObject(new HandleRef(null, info.hbmColor)); - info.hbmColor = IntPtr.Zero; + if (info.hbmColor != IntPtr.Zero) + { + // ExternalDelete to prevent Handle underflow + SafeNativeMethods.ExternalDeleteObject(new HandleRef(null, info.hbmColor)); + info.hbmColor = IntPtr.Zero; } currentIcon.Dispose(); @@ -269,13 +307,16 @@ public Point HotSpot /// position in screen coordinates. /// /// - public static Point Position { - get { + public static Point Position + { + get + { NativeMethods.POINT p = new NativeMethods.POINT(); UnsafeNativeMethods.GetCursorPos(p); return new Point(p.x, p.y); } - set { + set + { UnsafeNativeMethods.SetCursorPos(value.X, value.Y); } } @@ -286,13 +327,16 @@ public static Point Position { /// the size of this object. /// /// - public Size Size { - get { - if (cursorSize.IsEmpty) { - cursorSize = new Size( - UnsafeNativeMethods.GetSystemMetrics(NativeMethods.SM_CXCURSOR), - UnsafeNativeMethods.GetSystemMetrics(NativeMethods.SM_CYCURSOR) - ); + public Size Size + { + get + { + if (cursorSize.IsEmpty) + { + cursorSize = new Size( + UnsafeNativeMethods.GetSystemMetrics(NativeMethods.SM_CXCURSOR), + UnsafeNativeMethods.GetSystemMetrics(NativeMethods.SM_CYCURSOR) + ); } return cursorSize; @@ -307,11 +351,14 @@ public Size Size { DefaultValue(null), TypeConverter(typeof(StringConverter)), ] - public object Tag { - get { + public object Tag + { + get + { return userData; } - set { + set + { userData = value; } } @@ -319,7 +366,8 @@ public object Tag { /// /// Duplicates this the Win32 handle of this . /// - public IntPtr CopyHandle() { + public IntPtr CopyHandle() + { Size sz = Size; return SafeNativeMethods.CopyImage(new HandleRef(this, Handle), NativeMethods.IMAGE_CURSOR, sz.Width, sz.Height, 0); } @@ -329,8 +377,10 @@ public IntPtr CopyHandle() { /// /// owns the handle /// - private void DestroyHandle() { - if (ownHandle) { + private void DestroyHandle() + { + if (ownHandle) + { UnsafeNativeMethods.DestroyCursor(new HandleRef(this, handle)); } } @@ -339,12 +389,14 @@ private void DestroyHandle() { /// Cleans up the resources allocated by this object. Once called, the cursor /// object is no longer useful. /// - public void Dispose() { + public void Dispose() + { Dispose(true); GC.SuppressFinalize(this); } - void Dispose(bool disposing) { + void Dispose(bool disposing) + { /*if (picture != null) { picture = null; @@ -355,7 +407,8 @@ void Dispose(bool disposing) { UnsafeNativeMethods.PeekMessage(ref msg, NativeMethods.NullHandleRef, 0, 0, NativeMethods.PM_NOREMOVE | NativeMethods.PM_NOYIELD); }*/ // do we still keep that? - if (handle != IntPtr.Zero) { + if (handle != IntPtr.Zero) + { DestroyHandle(); handle = IntPtr.Zero; } @@ -368,15 +421,17 @@ void Dispose(bool disposing) { /// dimensions and allows the user to specify a rectangle within the image to draw. /// // This method is way more powerful than what we expose, but I'll leave it in place. - private void DrawImageCore(Graphics graphics, Rectangle imageRect, Rectangle targetRect, bool stretch) { + private void DrawImageCore(Graphics graphics, Rectangle imageRect, Rectangle targetRect, bool stretch) + { // Support GDI+ Translate method - targetRect.X += (int) graphics.Transform.OffsetX; - targetRect.Y += (int) graphics.Transform.OffsetY; + targetRect.X += (int)graphics.Transform.OffsetX; + targetRect.Y += (int)graphics.Transform.OffsetY; int rop = 0xcc0020; // RasterOp.SOURCE.GetRop(); IntPtr dc = graphics.GetHdc(); - try { // want finally clause to release dc + try + { // want finally clause to release dc int imageX = 0; int imageY = 0; int imageWidth; @@ -390,24 +445,28 @@ private void DrawImageCore(Graphics graphics, Rectangle imageRect, Rectangle tar // compute the dimensions of the icon, if needed // - if (!imageRect.IsEmpty) { + if (!imageRect.IsEmpty) + { imageX = imageRect.X; imageY = imageRect.Y; imageWidth = imageRect.Width; imageHeight = imageRect.Height; } - else { + else + { imageWidth = cursorSize.Width; imageHeight = cursorSize.Height; } - if (!targetRect.IsEmpty) { + if (!targetRect.IsEmpty) + { targetX = targetRect.X; targetY = targetRect.Y; targetWidth = targetRect.Width; targetHeight = targetRect.Height; } - else { + else + { targetWidth = cursorSize.Width; targetHeight = cursorSize.Height; } @@ -415,13 +474,15 @@ private void DrawImageCore(Graphics graphics, Rectangle imageRect, Rectangle tar int drawWidth, drawHeight; int clipWidth, clipHeight; - if (stretch) { + if (stretch) + { // Short circuit the simple case of blasting an icon to the // screen // if (targetWidth == imageWidth && targetHeight == imageHeight && imageX == 0 && imageY == 0 && rop == NativeMethods.SRCCOPY - && imageWidth == cursorSize.Width && imageHeight == cursorSize.Height) { + && imageWidth == cursorSize.Width && imageHeight == cursorSize.Height) + { SafeNativeMethods.DrawIcon(new HandleRef(graphics, dc), targetX, targetY, new HandleRef(this, handle)); return; } @@ -431,13 +492,15 @@ private void DrawImageCore(Graphics graphics, Rectangle imageRect, Rectangle tar clipWidth = targetWidth; clipHeight = targetHeight; } - else { + else + { // Short circuit the simple case of blasting an icon to the // screen // if (imageX == 0 && imageY == 0 && rop == NativeMethods.SRCCOPY && cursorSize.Width <= targetWidth && cursorSize.Height <= targetHeight - && cursorSize.Width == imageWidth && cursorSize.Height == imageHeight) { + && cursorSize.Width == imageWidth && cursorSize.Height == imageHeight) + { SafeNativeMethods.DrawIcon(new HandleRef(graphics, dc), targetX, targetY, new HandleRef(this, handle)); return; } @@ -448,12 +511,13 @@ private void DrawImageCore(Graphics graphics, Rectangle imageRect, Rectangle tar clipHeight = targetHeight < imageHeight ? targetHeight : imageHeight; } - if (rop == NativeMethods.SRCCOPY) { + if (rop == NativeMethods.SRCCOPY) + { // The ROP is SRCCOPY, so we can be simple here and take // advantage of clipping regions. Drawing the cursor // is merely a matter of offsetting and clipping. // - SafeNativeMethods.IntersectClipRect(new HandleRef(this, Handle), targetX, targetY, targetX+clipWidth, targetY+clipHeight); + SafeNativeMethods.IntersectClipRect(new HandleRef(this, Handle), targetX, targetY, targetX + clipWidth, targetY + clipHeight); SafeNativeMethods.DrawIconEx(new HandleRef(graphics, dc), targetX - imageX, targetY - imageY, new HandleRef(this, handle), drawWidth, drawHeight, 0, NativeMethods.NullHandleRef, NativeMethods.DI_NORMAL); // Let GDI+ restore clipping @@ -462,7 +526,8 @@ private void DrawImageCore(Graphics graphics, Rectangle imageRect, Rectangle tar Debug.Fail("Cursor.Draw does not support raster ops. How did you even pass one in?"); } - finally { + finally + { graphics.ReleaseHdcInternal(dc); } } @@ -472,35 +537,42 @@ private void DrawImageCore(Graphics graphics, Rectangle imageRect, Rectangle tar /// Draws this to a . /// /// - public void Draw(Graphics g, Rectangle targetRect) { + public void Draw(Graphics g, Rectangle targetRect) + { DrawImageCore(g, Rectangle.Empty, targetRect, false); } /// /// Draws this to a . /// - public void DrawStretched(Graphics g, Rectangle targetRect) { + public void DrawStretched(Graphics g, Rectangle targetRect) + { DrawImageCore(g, Rectangle.Empty, targetRect, true); } /// /// Cleans up Windows resources for this object. /// - ~Cursor() { + ~Cursor() + { Dispose(false); } /// /// ISerializable private implementation /// - void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) { - if (cursorData != null) { + void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) + { + if (cursorData != null) + { si.AddValue("CursorData", cursorData, typeof(byte[])); } - else if (resourceId != 0) { + else if (resourceId != 0) + { si.AddValue("CursorResourceId", resourceId, typeof(int)); } - else { + else + { Debug.Fail("Why are we trying to serialize an empty cursor?"); throw new SerializationException(SR.CursorNonSerializableHandle); } @@ -512,49 +584,57 @@ void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) /// balancing call to Cursor.show(). /// /// - public static void Hide() { + public static void Hide() + { UnsafeNativeMethods.ShowCursor(false); } - private void LoadFromResourceId(int nResourceId) { + private void LoadFromResourceId(int nResourceId) + { ownHandle = false; // we don't delete stock cursors. - // We assert here on exception -- this constructor is used during clinit, - // and it would be a shame if we failed to initialize all of windows forms just - // just because a cursor couldn't load. - // - try { - resourceId = nResourceId; - handle = SafeNativeMethods.LoadCursor(NativeMethods.NullHandleRef, nResourceId); - } - catch (Exception e) { - handle = IntPtr.Zero; - Debug.Fail(e.ToString()); - } + // We assert here on exception -- this constructor is used during clinit, + // and it would be a shame if we failed to initialize all of windows forms just + // just because a cursor couldn't load. + // + try + { + resourceId = nResourceId; + handle = SafeNativeMethods.LoadCursor(NativeMethods.NullHandleRef, nResourceId); + } + catch (Exception e) + { + handle = IntPtr.Zero; + Debug.Fail(e.ToString()); + } } // this code is adapted from Icon.GetIconSize please take this into account when changing this - private Size GetIconSize(IntPtr iconHandle) { + private Size GetIconSize(IntPtr iconHandle) + { Size iconSize = Size; NativeMethods.ICONINFO info = new NativeMethods.ICONINFO(); SafeNativeMethods.GetIconInfo(new HandleRef(this, iconHandle), info); NativeMethods.BITMAP bmp = new NativeMethods.BITMAP(); - if (info.hbmColor != IntPtr.Zero) { + if (info.hbmColor != IntPtr.Zero) + { UnsafeNativeMethods.GetObject(new HandleRef(null, info.hbmColor), Marshal.SizeOf(), bmp); SafeNativeMethods.IntDeleteObject(new HandleRef(null, info.hbmColor)); iconSize = new Size(bmp.bmWidth, bmp.bmHeight); } - else if (info.hbmMask != IntPtr.Zero) { + else if (info.hbmMask != IntPtr.Zero) + { UnsafeNativeMethods.GetObject(new HandleRef(null, info.hbmMask), Marshal.SizeOf(), bmp); iconSize = new Size(bmp.bmWidth, bmp.bmHeight / 2); } - - if (info.hbmMask != IntPtr.Zero) { + + if (info.hbmMask != IntPtr.Zero) + { SafeNativeMethods.IntDeleteObject(new HandleRef(null, info.hbmMask)); } - return iconSize; + return iconSize; } @@ -562,24 +642,30 @@ private Size GetIconSize(IntPtr iconHandle) { /// /// Loads a picture from the requested stream. /// - private void LoadPicture(UnsafeNativeMethods.IStream stream) { + private void LoadPicture(UnsafeNativeMethods.IStream stream) + { - if (stream == null) { + if (stream == null) + { throw new ArgumentNullException(nameof(stream)); } - try { + try + { Guid g = typeof(UnsafeNativeMethods.IPicture).GUID; UnsafeNativeMethods.IPicture picture = null; - - try { + + try + { picture = UnsafeNativeMethods.OleCreateIPictureIndirect(null, ref g, true); UnsafeNativeMethods.IPersistStream ipictureAsIPersist = (UnsafeNativeMethods.IPersistStream)picture; ipictureAsIPersist.Load(stream); - - if (picture != null && picture.GetPictureType() == NativeMethods.Ole.PICTYPE_ICON) { + + if (picture != null && picture.GetPictureType() == NativeMethods.Ole.PICTYPE_ICON) + { IntPtr cursorHandle = picture.GetHandle(); Size picSize = GetIconSize(cursorHandle); - if (DpiHelper.IsScalingRequired) { + if (DpiHelper.IsScalingRequired) + { picSize = DpiHelper.LogicalToDeviceUnits(picSize); } @@ -587,20 +673,24 @@ private void LoadPicture(UnsafeNativeMethods.IStream stream) { picSize.Width, picSize.Height, 0); ownHandle = true; } - else { + else + { throw new ArgumentException(string.Format(SR.InvalidPictureType, "picture", "Cursor"), "picture"); } } - finally { + finally + { // destroy the picture... - if(picture != null) { + if (picture != null) + { Marshal.ReleaseComObject(picture); } } } - catch (COMException e) { + catch (COMException e) + { Debug.Fail(e.ToString()); throw new ArgumentException(SR.InvalidPictureFormat, "stream", e); } @@ -609,21 +699,27 @@ private void LoadPicture(UnsafeNativeMethods.IStream stream) { /// /// Saves a picture from the requested stream. /// - internal void SavePicture(Stream stream) { - if (stream == null) { + internal void SavePicture(Stream stream) + { + if (stream == null) + { throw new ArgumentNullException(nameof(stream)); } - if(this.resourceId != 0) { + if (this.resourceId != 0) + { throw new FormatException(SR.CursorCannotCovertToBytes); } - try { + try + { stream.Write(cursorData, 0, cursorData.Length); } - catch (System.Security.SecurityException) { + catch (System.Security.SecurityException) + { // dont eat security exceptions. throw; } - catch (Exception e) { + catch (Exception e) + { Debug.Fail(e.ToString()); throw new InvalidOperationException(SR.InvalidPictureFormat); } @@ -635,7 +731,8 @@ internal void SavePicture(Stream stream) { /// a previous call to Cursor.hide(). /// /// - public static void Show() { + public static void Show() + { UnsafeNativeMethods.ShowCursor(true); } @@ -646,41 +743,50 @@ public static void Show() { /// . /// /// - public override string ToString() { + public override string ToString() + { string s = null; - + if (!this.ownHandle) s = TypeDescriptor.GetConverter(typeof(Cursor)).ConvertToString(this); else s = base.ToString(); - + return "[Cursor: " + s + "]"; } - - public static bool operator ==(Cursor left, Cursor right) { - if (object.ReferenceEquals(left, null) != object.ReferenceEquals(right, null)) { + + public static bool operator ==(Cursor left, Cursor right) + { + if (object.ReferenceEquals(left, null) != object.ReferenceEquals(right, null)) + { return false; } - - if (!object.ReferenceEquals(left, null)) { + + if (!object.ReferenceEquals(left, null)) + { return (left.handle == right.handle); } - else { + else + { return true; } } - - public static bool operator !=(Cursor left, Cursor right) { + + public static bool operator !=(Cursor left, Cursor right) + { return !(left == right); } - - public override int GetHashCode() { + + public override int GetHashCode() + { // Handle is a 64-bit value in 64-bit machines, uncheck here to avoid overflow exceptions. return unchecked((int)handle); } - - public override bool Equals(object obj) { - if (!(obj is Cursor)) { + + public override bool Equals(object obj) + { + if (!(obj is Cursor)) + { return false; } return (this == (Cursor)obj); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/CursorConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/CursorConverter.cs index 58645bbcd06..2a347b17172 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/CursorConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/CursorConverter.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; using Microsoft.Win32; @@ -19,16 +20,19 @@ namespace System.Windows.Forms { /// colors from one data type to another. Access this /// class through the TypeDescriptor. /// - public class CursorConverter : TypeConverter { - + public class CursorConverter : TypeConverter + { + private StandardValuesCollection values; /// /// Determines if this converter can convert an object in the given source /// type to the native type of the converter. /// - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { - if (sourceType == typeof(string) || sourceType == typeof(byte[])) { + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + { + if (sourceType == typeof(string) || sourceType == typeof(byte[])) + { return true; } return base.CanConvertFrom(context, sourceType); @@ -38,33 +42,40 @@ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceT /// Gets a value indicating whether this converter can /// convert an object to the given destination type using the context. /// - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { - if (destinationType == typeof(InstanceDescriptor) || destinationType == typeof(byte[])) { + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) + { + if (destinationType == typeof(InstanceDescriptor) || destinationType == typeof(byte[])) + { return true; } return base.CanConvertTo(context, destinationType); } - + /// /// Converts the given object to the converter's native type. /// - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - - if (value is string) { + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + { + + if (value is string) + { string text = ((string)value).Trim(); - + PropertyInfo[] props = GetProperties(); - for (int i = 0; i < props.Length; i++) { + for (int i = 0; i < props.Length; i++) + { PropertyInfo prop = props[i]; - if (string.Equals(prop.Name, text, StringComparison.OrdinalIgnoreCase) ){ + if (string.Equals(prop.Name, text, StringComparison.OrdinalIgnoreCase)) + { object[] tempIndex = null; return prop.GetValue(null, tempIndex); } } } - - if (value is byte[]) { + + if (value is byte[]) + { MemoryStream ms = new MemoryStream((byte[])value); return new Cursor(ms); } @@ -79,33 +90,41 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) { + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == null) + { throw new ArgumentNullException(nameof(destinationType)); } - if (destinationType == typeof(string) && value != null) { + if (destinationType == typeof(string) && value != null) + { PropertyInfo[] props = GetProperties(); int bestMatch = -1; - for (int i = 0; i < props.Length; i++) { + for (int i = 0; i < props.Length; i++) + { PropertyInfo prop = props[i]; object[] tempIndex = null; Cursor c = (Cursor)prop.GetValue(null, tempIndex); - if (c == (Cursor)value) { - if (Object.ReferenceEquals(c, value)) { + if (c == (Cursor)value) + { + if (Object.ReferenceEquals(c, value)) + { return prop.Name; } - else { + else + { bestMatch = i; } } } - if (bestMatch != -1) { + if (bestMatch != -1) + { return props[bestMatch].Name; } - + // We throw here because we cannot meaningfully convert a custom // cursor into a string. In fact, the ResXResourceWriter will use // this exception to indicate to itself that this object should @@ -114,34 +133,40 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul throw new FormatException(SR.CursorCannotCovertToString); } - if (destinationType == typeof(InstanceDescriptor) && value is Cursor) { + if (destinationType == typeof(InstanceDescriptor) && value is Cursor) + { PropertyInfo[] props = GetProperties(); - foreach(PropertyInfo prop in props) { - if (prop.GetValue(null, null) == value) { + foreach (PropertyInfo prop in props) + { + if (prop.GetValue(null, null) == value) + { return new InstanceDescriptor(prop, null); } } } - - if (destinationType == typeof(byte[])) { - if (value != null) { + + if (destinationType == typeof(byte[])) + { + if (value != null) + { MemoryStream ms = new MemoryStream(); Cursor cursor = (Cursor)value; cursor.SavePicture(ms); ms.Close(); return ms.ToArray(); } - else + else return new byte[0]; } return base.ConvertTo(context, culture, value, destinationType); } - + /// /// Retrieves the properties for the available cursors. /// - private PropertyInfo[] GetProperties() { + private PropertyInfo[] GetProperties() + { return typeof(Cursors).GetProperties(BindingFlags.Static | BindingFlags.Public); } @@ -151,20 +176,23 @@ private PropertyInfo[] GetProperties() { /// will return null if the data type does not support a /// standard set of values. /// - public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { - if (values == null) { + public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) + { + if (values == null) + { ArrayList list = new ArrayList(); PropertyInfo[] props = GetProperties(); - for (int i = 0; i < props.Length; i++) { + for (int i = 0; i < props.Length; i++) + { PropertyInfo prop = props[i]; object[] tempIndex = null; Debug.Assert(prop.GetValue(null, tempIndex) != null, "Property " + prop.Name + " returned NULL"); list.Add(prop.GetValue(null, tempIndex)); } - + values = new StandardValuesCollection(list.ToArray()); } - + return values; } @@ -172,7 +200,8 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex /// Determines if this object supports a standard set of values /// that can be picked from a list. /// - public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { + public override bool GetStandardValuesSupported(ITypeDescriptorContext context) + { return true; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Cursors.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Cursors.cs index 3292a0eb312..0f2fc4c97b8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Cursors.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Cursors.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; @@ -14,47 +15,52 @@ namespace System.Windows.Forms { /// /// Standard cursors /// - public sealed class Cursors { - private static Cursor appStarting = null; - private static Cursor arrow = null; - private static Cursor cross = null; - private static Cursor defaultCursor = null; - private static Cursor iBeam = null; - private static Cursor no = null; - private static Cursor sizeAll = null; - private static Cursor sizeNESW = null; - private static Cursor sizeNS = null; - private static Cursor sizeNWSE = null; - private static Cursor sizeWE = null; - private static Cursor upArrow = null; - private static Cursor wait = null; - private static Cursor help = null; - private static Cursor hSplit = null; - private static Cursor vSplit = null; - private static Cursor noMove2D = null; - private static Cursor noMoveHoriz = null; - private static Cursor noMoveVert = null; - private static Cursor panEast = null; - private static Cursor panNE = null; - private static Cursor panNorth = null; - private static Cursor panNW = null; - private static Cursor panSE = null; - private static Cursor panSouth = null; - private static Cursor panSW = null; - private static Cursor panWest = null; - private static Cursor hand = null; - - private Cursors() { + public sealed class Cursors + { + private static Cursor appStarting = null; + private static Cursor arrow = null; + private static Cursor cross = null; + private static Cursor defaultCursor = null; + private static Cursor iBeam = null; + private static Cursor no = null; + private static Cursor sizeAll = null; + private static Cursor sizeNESW = null; + private static Cursor sizeNS = null; + private static Cursor sizeNWSE = null; + private static Cursor sizeWE = null; + private static Cursor upArrow = null; + private static Cursor wait = null; + private static Cursor help = null; + private static Cursor hSplit = null; + private static Cursor vSplit = null; + private static Cursor noMove2D = null; + private static Cursor noMoveHoriz = null; + private static Cursor noMoveVert = null; + private static Cursor panEast = null; + private static Cursor panNE = null; + private static Cursor panNorth = null; + private static Cursor panNW = null; + private static Cursor panSE = null; + private static Cursor panSouth = null; + private static Cursor panSW = null; + private static Cursor panWest = null; + private static Cursor hand = null; + + private Cursors() + { } - internal static Cursor KnownCursorFromHCursor( IntPtr handle ) { - if (handle == IntPtr.Zero) { + internal static Cursor KnownCursorFromHCursor(IntPtr handle) + { + if (handle == IntPtr.Zero) + { return null; } - else { + else + { return new Cursor(handle); } - + // if (handle == Cursors.AppStarting.Handle) return Cursors.AppStarting; // if (handle == Cursors.Arrow.Handle) return Cursors.Arrow; // if (handle == Cursors.IBeam.Handle) return Cursors.IBeam; @@ -71,7 +77,7 @@ internal static Cursor KnownCursorFromHCursor( IntPtr handle ) { // if (handle == Cursors.WaitCursor.Handle) return Cursors.WaitCursor; // if (handle == Cursors.Help.Handle) return Cursors.Help; // if (handle == IntPtr.Zero) return null; - + // appStarting = new Cursor(NativeMethods.IDC_APPSTARTING,0); // arrow = new Cursor(NativeMethods.IDC_ARROW,0); // cross = new Cursor(NativeMethods.IDC_CROSS,0); @@ -87,227 +93,283 @@ internal static Cursor KnownCursorFromHCursor( IntPtr handle ) { // wait = new Cursor(NativeMethods.IDC_WAIT,0); // help = new Cursor(NativeMethods.IDC_HELP,0); } - - public static Cursor AppStarting { - get { + + public static Cursor AppStarting + { + get + { if (appStarting == null) - appStarting = new Cursor(NativeMethods.IDC_APPSTARTING,0); + appStarting = new Cursor(NativeMethods.IDC_APPSTARTING, 0); return appStarting; } } - public static Cursor Arrow { - get { + public static Cursor Arrow + { + get + { if (arrow == null) - arrow = new Cursor(NativeMethods.IDC_ARROW,0); + arrow = new Cursor(NativeMethods.IDC_ARROW, 0); return arrow; } } - public static Cursor Cross { - get { + public static Cursor Cross + { + get + { if (cross == null) - cross = new Cursor(NativeMethods.IDC_CROSS,0); + cross = new Cursor(NativeMethods.IDC_CROSS, 0); return cross; } } - public static Cursor Default { - get { + public static Cursor Default + { + get + { if (defaultCursor == null) - defaultCursor = new Cursor(NativeMethods.IDC_ARROW,0); + defaultCursor = new Cursor(NativeMethods.IDC_ARROW, 0); return defaultCursor; } } - public static Cursor IBeam { - get { + public static Cursor IBeam + { + get + { if (iBeam == null) - iBeam = new Cursor(NativeMethods.IDC_IBEAM,0); + iBeam = new Cursor(NativeMethods.IDC_IBEAM, 0); return iBeam; } } - public static Cursor No { - get { + public static Cursor No + { + get + { if (no == null) - no = new Cursor(NativeMethods.IDC_NO,0); + no = new Cursor(NativeMethods.IDC_NO, 0); return no; } } - public static Cursor SizeAll { - get { + public static Cursor SizeAll + { + get + { if (sizeAll == null) - sizeAll = new Cursor(NativeMethods.IDC_SIZEALL,0); + sizeAll = new Cursor(NativeMethods.IDC_SIZEALL, 0); return sizeAll; } } - public static Cursor SizeNESW { - get { + public static Cursor SizeNESW + { + get + { if (sizeNESW == null) - sizeNESW = new Cursor(NativeMethods.IDC_SIZENESW,0); + sizeNESW = new Cursor(NativeMethods.IDC_SIZENESW, 0); return sizeNESW; } } - public static Cursor SizeNS { - get { + public static Cursor SizeNS + { + get + { if (sizeNS == null) - sizeNS = new Cursor(NativeMethods.IDC_SIZENS,0); + sizeNS = new Cursor(NativeMethods.IDC_SIZENS, 0); return sizeNS; } } - public static Cursor SizeNWSE { - get { + public static Cursor SizeNWSE + { + get + { if (sizeNWSE == null) - sizeNWSE = new Cursor(NativeMethods.IDC_SIZENWSE,0); + sizeNWSE = new Cursor(NativeMethods.IDC_SIZENWSE, 0); return sizeNWSE; } } - public static Cursor SizeWE { - get { + public static Cursor SizeWE + { + get + { if (sizeWE == null) - sizeWE = new Cursor(NativeMethods.IDC_SIZEWE,0); + sizeWE = new Cursor(NativeMethods.IDC_SIZEWE, 0); return sizeWE; } } - public static Cursor UpArrow { - get { + public static Cursor UpArrow + { + get + { if (upArrow == null) - upArrow = new Cursor(NativeMethods.IDC_UPARROW,0); + upArrow = new Cursor(NativeMethods.IDC_UPARROW, 0); return upArrow; } } - public static Cursor WaitCursor { - get { + public static Cursor WaitCursor + { + get + { if (wait == null) - wait = new Cursor(NativeMethods.IDC_WAIT,0); + wait = new Cursor(NativeMethods.IDC_WAIT, 0); return wait; } } - public static Cursor Help { - get { + public static Cursor Help + { + get + { if (help == null) - help = new Cursor(NativeMethods.IDC_HELP,0); + help = new Cursor(NativeMethods.IDC_HELP, 0); return help; } } - public static Cursor HSplit { - get { + public static Cursor HSplit + { + get + { if (hSplit == null) - hSplit = new Cursor("hsplit.cur", 0); + hSplit = new Cursor("hsplit.cur", 0); return hSplit; } } - public static Cursor VSplit { - get { + public static Cursor VSplit + { + get + { if (vSplit == null) - vSplit = new Cursor("vsplit.cur", 0); + vSplit = new Cursor("vsplit.cur", 0); return vSplit; } } - public static Cursor NoMove2D { - get { + public static Cursor NoMove2D + { + get + { if (noMove2D == null) - noMove2D = new Cursor("nomove2d.cur", 0); + noMove2D = new Cursor("nomove2d.cur", 0); return noMove2D; } } - public static Cursor NoMoveHoriz { - get { + public static Cursor NoMoveHoriz + { + get + { if (noMoveHoriz == null) noMoveHoriz = new Cursor("nomoveh.cur", 0); return noMoveHoriz; } } - public static Cursor NoMoveVert { - get { + public static Cursor NoMoveVert + { + get + { if (noMoveVert == null) - noMoveVert = new Cursor("nomovev.cur", 0); + noMoveVert = new Cursor("nomovev.cur", 0); return noMoveVert; } } - public static Cursor PanEast { - get { + public static Cursor PanEast + { + get + { if (panEast == null) - panEast = new Cursor("east.cur", 0); + panEast = new Cursor("east.cur", 0); return panEast; } } - public static Cursor PanNE { - get { + public static Cursor PanNE + { + get + { if (panNE == null) - panNE = new Cursor("ne.cur", 0); + panNE = new Cursor("ne.cur", 0); return panNE; } } - public static Cursor PanNorth { - get { + public static Cursor PanNorth + { + get + { if (panNorth == null) - panNorth = new Cursor("north.cur", 0); + panNorth = new Cursor("north.cur", 0); return panNorth; } } - public static Cursor PanNW { - get { + public static Cursor PanNW + { + get + { if (panNW == null) - panNW = new Cursor("nw.cur", 0); + panNW = new Cursor("nw.cur", 0); return panNW; } } - public static Cursor PanSE { - get { + public static Cursor PanSE + { + get + { if (panSE == null) - panSE = new Cursor("se.cur", 0); + panSE = new Cursor("se.cur", 0); return panSE; } } - public static Cursor PanSouth { - get { + public static Cursor PanSouth + { + get + { if (panSouth == null) - panSouth = new Cursor("south.cur", 0); + panSouth = new Cursor("south.cur", 0); return panSouth; } } - public static Cursor PanSW { - get { + public static Cursor PanSW + { + get + { if (panSW == null) - panSW = new Cursor("sw.cur", 0); + panSW = new Cursor("sw.cur", 0); return panSW; } } - public static Cursor PanWest { - get { + public static Cursor PanWest + { + get + { if (panWest == null) - panWest = new Cursor("west.cur", 0); + panWest = new Cursor("west.cur", 0); return panWest; } } - public static Cursor Hand { - get { + public static Cursor Hand + { + get + { if (hand == null) - hand = new Cursor("hand.cur", 0); + hand = new Cursor("hand.cur", 0); return hand; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataFormats.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataFormats.cs index 04a89e077eb..d85de8d1505 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataFormats.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataFormats.cs @@ -301,7 +301,7 @@ public Format(string name, int id) Name = name; Id = id; } - + /// /// Specifies the name of this format. /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs index 23147ed5212..bdf37fca0b2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs @@ -2,5724 +2,6465 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { - using System.Text; - using System.Runtime.Serialization.Formatters; - using System.Runtime.InteropServices; - using System.ComponentModel; - using System; - using System.Collections; - using System.Windows.Forms; - using System.Windows.Forms.Design; - using System.ComponentModel.Design; - using System.Drawing; - - using Microsoft.Win32; - using System.Windows.Forms.ComponentModel; - using System.Diagnostics; - using System.Diagnostics.CodeAnalysis; - using System.Globalization; - +namespace System.Windows.Forms +{ + using System.Text; + using System.Runtime.Serialization.Formatters; + using System.Runtime.InteropServices; + using System.ComponentModel; + using System; + using System.Collections; + using System.Windows.Forms; + using System.Windows.Forms.Design; + using System.ComponentModel.Design; + using System.Drawing; + + using Microsoft.Win32; + using System.Windows.Forms.ComponentModel; + using System.Diagnostics; + using System.Diagnostics.CodeAnalysis; + using System.Globalization; + + /// + /// Displays ADO.NET data in a scrollable + /// grid. + /// + [ + ComVisible(true), + ClassInterface(ClassInterfaceType.AutoDispatch), + Designer("System.Windows.Forms.Design.DataGridDesigner, " + AssemblyRef.SystemDesign), + DefaultProperty(nameof(DataSource)), + DefaultEvent(nameof(Navigate)), + ComplexBindingProperties(nameof(DataSource), nameof(DataMember)), + ] + public class DataGrid : Control, ISupportInitialize, IDataGridEditingService + { +#if DEBUG + internal TraceSwitch DataGridAcc = new TraceSwitch("DataGridAcc", "Trace Windows Forms DataGrid Accessibility"); +#else + internal TraceSwitch DataGridAcc = null; +#endif + + private const int GRIDSTATE_allowSorting = 0x00000001; + private const int GRIDSTATE_columnHeadersVisible = 0x00000002; + private const int GRIDSTATE_rowHeadersVisible = 0x00000004; + private const int GRIDSTATE_trackColResize = 0x00000008; + private const int GRIDSTATE_trackRowResize = 0x00000010; + private const int GRIDSTATE_isLedgerStyle = 0x00000020; + private const int GRIDSTATE_isFlatMode = 0x00000040; + private const int GRIDSTATE_listHasErrors = 0x00000080; + private const int GRIDSTATE_dragging = 0x00000100; + private const int GRIDSTATE_inListAddNew = 0x00000200; + private const int GRIDSTATE_inDeleteRow = 0x00000400; + private const int GRIDSTATE_canFocus = 0x00000800; + private const int GRIDSTATE_readOnlyMode = 0x00001000; + private const int GRIDSTATE_allowNavigation = 0x00002000; + private const int GRIDSTATE_isNavigating = 0x00004000; + private const int GRIDSTATE_isEditing = 0x00008000; + private const int GRIDSTATE_editControlChanging = 0x00010000; + private const int GRIDSTATE_isScrolling = 0x00020000; + private const int GRIDSTATE_overCaption = 0x00040000; + private const int GRIDSTATE_childLinkFocused = 0x00080000; + private const int GRIDSTATE_inAddNewRow = 0x00100000; + private const int GRIDSTATE_inSetListManager = 0x00200000; + private const int GRIDSTATE_metaDataChanged = 0x00400000; + private const int GRIDSTATE_exceptionInPaint = 0x00800000; + private const int GRIDSTATE_layoutSuspended = 0x01000000; + + // PERF: take all the bools and put them into a state variable + private System.Collections.Specialized.BitVector32 gridState; // see GRIDSTATE_ consts above + + // for column widths + private const int NumRowsForAutoResize = 10; + + private const int errorRowBitmapWidth = 15; + + private const DataGridParentRowsLabelStyle defaultParentRowsLabelStyle = DataGridParentRowsLabelStyle.Both; + + private const BorderStyle defaultBorderStyle = BorderStyle.Fixed3D; + + private const bool defaultCaptionVisible = true; + + private const bool defaultParentRowsVisible = true; + + private DataGridTableStyle defaultTableStyle = new DataGridTableStyle(true); + + // private bool allowSorting = true; + + private SolidBrush alternatingBackBrush = DefaultAlternatingBackBrush; + + // private bool columnHeadersVisible = true; + + private SolidBrush gridLineBrush = DefaultGridLineBrush; + + private const DataGridLineStyle defaultGridLineStyle = DataGridLineStyle.Solid; + private DataGridLineStyle gridLineStyle = defaultGridLineStyle; + + private SolidBrush headerBackBrush = DefaultHeaderBackBrush; + + private Font headerFont = null; // this is ambient property to Font value + + private SolidBrush headerForeBrush = DefaultHeaderForeBrush; + private Pen headerForePen = DefaultHeaderForePen; + + private SolidBrush linkBrush = DefaultLinkBrush; + + private const int defaultPreferredColumnWidth = 75; + private int preferredColumnWidth = defaultPreferredColumnWidth; + + private static int defaultFontHeight = Control.DefaultFont.Height; + private int prefferedRowHeight = defaultFontHeight + 3; + + // private bool rowHeadersVisible = true; + private const int defaultRowHeaderWidth = 35; + private int rowHeaderWidth = defaultRowHeaderWidth; + private int minRowHeaderWidth; + + private SolidBrush selectionBackBrush = DefaultSelectionBackBrush; + private SolidBrush selectionForeBrush = DefaultSelectionForeBrush; + + // parent rows + // + private DataGridParentRows parentRows = null; + // Set_ListManager uses the originalState to determine + // if the grid should disconnect from all the MetaDataChangedEvents + // keep "originalState != null" when navigating back and forth in the grid + // and use Add/RemoveMetaDataChanged methods. + private DataGridState originalState = null; + + // ui state + // + // Don't use dataGridRows, use the accessor!!! + private DataGridRow[] dataGridRows = new DataGridRow[0]; + private int dataGridRowsLength = 0; + + // for toolTip + private int toolTipId = 0; + private DataGridToolTip toolTipProvider = null; + + private DataGridAddNewRow addNewRow = null; + private LayoutData layout = new LayoutData(); + private NativeMethods.RECT[] cachedScrollableRegion = null; + + // header namespace goo + // + + // these are actually get/set by ColumnBehavior + internal bool allowColumnResize = true; + + internal bool allowRowResize = true; + + internal DataGridParentRowsLabelStyle parentRowsLabels = defaultParentRowsLabelStyle; + + // information for col/row resizing + // private bool trackColResize = false; + private int trackColAnchor = 0; + private int trackColumn = 0; + // private bool trackRowResize = false; + private int trackRowAnchor = 0; + private int trackRow = 0; + private PropertyDescriptor trackColumnHeader = null; + private MouseEventArgs lastSplitBar = null; + + // private bool isLedgerStyle = true; + // private bool isFlatMode = false; + private Font linkFont = null; + + private SolidBrush backBrush = DefaultBackBrush; + private SolidBrush foreBrush = DefaultForeBrush; + private SolidBrush backgroundBrush = DefaultBackgroundBrush; + + // font cacheing info + private int fontHeight = -1; + private int linkFontHeight = -1; + private int captionFontHeight = -1; + private int headerFontHeight = -1; + + // the preffered height of the row. + + // if the list has items with errors + + // private bool listHasErrors = false; + + // caption + private DataGridCaption caption; + + // Border + // + private BorderStyle borderStyle; + + // data binding + // + private object dataSource = null; + private string dataMember = string.Empty; + private CurrencyManager listManager = null; + + // currently focused control + // we want to unparent it either when rebinding the grid or when the grid is disposed + Control toBeDisposedEditingControl = null; + + // persistent data state + // + internal GridTableStylesCollection dataGridTables = null; + // SET myGridTable in SetDataGridTable ONLY + internal DataGridTableStyle myGridTable = null; + internal bool checkHierarchy = true; + internal bool inInit = false; + + // Selection + internal int currentRow = 0; + internal int currentCol = 0; + private int numSelectedRows = 0; + private int lastRowSelected = -1; + + // dragging: + // private bool dragging = false; + + // addNewRow + // private bool inAddNewRow = false; + // delete Row + // private bool inDeleteRow = false; + + // when we leave, we call CommitEdit + // if we leave, then do not focus the dataGrid. + // so we can't focus the grid at the following moments: + // 1. while processing the OnLayout event + // 2. while processing the OnLeave event + // private bool canFocus = true; + + // for CurrentCell +#if DEBUG + private bool inDataSource_PositionChanged = false; +#endif // DEBUG + + // Policy + // private bool readOnlyMode = false; + private Policy policy = new Policy(); + // private bool allowNavigation = true; + + // editing + // private bool isNavigating = false; + // private bool isEditing = false; + // private bool editControlChanging = false; + private DataGridColumnStyle editColumn = null; + private DataGridRow editRow = null; + + // scrolling + // + private ScrollBar horizScrollBar = new HScrollBar(); + private ScrollBar vertScrollBar = new VScrollBar(); + + // the sum of the widths of the columns preceding the firstVisibleColumn + // + private int horizontalOffset = 0; + + // the number of pixels of the firstVisibleColumn which are not visible + // + private int negOffset = 0; + + private int wheelDelta = 0; + // private bool isScrolling = false; + + // Visibility + // + internal int firstVisibleRow = 0; + internal int firstVisibleCol = 0; + private int numVisibleRows = 0; + // the number of columns which are visible + private int numVisibleCols = 0; + private int numTotallyVisibleRows = 0; + // lastTotallyVisibleCol == -1 means that the data grid does not show any column in its entirety + private int lastTotallyVisibleCol = 0; + + // mouse move hot-tracking + // + private int oldRow = -1; + // private bool overCaption = true; + + // child relationships focused + // + // private bool childLinkFocused = false; + + // private static readonly object EVENT_COLUMNHEADERCLICK = new object(); + private static readonly object EVENT_CURRENTCELLCHANGED = new object(); + // private static readonly object EVENT_COLUMNRESIZE = new object(); + // private static readonly object EVENT_LINKCLICKED = new object(); + private static readonly object EVENT_NODECLICKED = new object(); + // private static readonly object EVENT_ROWRESIZE = new object(); + private static readonly object EVENT_SCROLL = new object(); + private static readonly object EVENT_BACKBUTTONCLICK = new object(); + private static readonly object EVENT_DOWNBUTTONCLICK = new object(); + + + // event handlers + // + private ItemChangedEventHandler itemChangedHandler; + private EventHandler positionChangedHandler; + private EventHandler currentChangedHandler; + private EventHandler metaDataChangedHandler; + + // we have to know when the collection of dataGridTableStyles changes + private CollectionChangeEventHandler dataGridTableStylesCollectionChanged; + + private EventHandler backButtonHandler; + private EventHandler downButtonHandler; + + private NavigateEventHandler onNavigate; + + private EventHandler onRowHeaderClick; + + // forDebug + // + // private int forDebug = 0; + + // =----------------------------------------------------------------- + + + /// + /// Initializes a new instance of the + /// class. + /// + public DataGrid() : base() + { + SetStyle(ControlStyles.UserPaint, true); + SetStyle(ControlStyles.Opaque, false); + SetStyle(ControlStyles.SupportsTransparentBackColor, false); + SetStyle(ControlStyles.UserMouse, true); + this.gridState = new System.Collections.Specialized.BitVector32(0x00042827); + + dataGridTables = new GridTableStylesCollection(this); + layout = CreateInitialLayoutState(); + parentRows = new DataGridParentRows(this); + + horizScrollBar.Top = ClientRectangle.Height - horizScrollBar.Height; + horizScrollBar.Left = 0; + horizScrollBar.Visible = false; + horizScrollBar.Scroll += new ScrollEventHandler(GridHScrolled); + Controls.Add(horizScrollBar); + + vertScrollBar.Top = 0; + vertScrollBar.Left = ClientRectangle.Width - vertScrollBar.Width; + vertScrollBar.Visible = false; + vertScrollBar.Scroll += new ScrollEventHandler(GridVScrolled); + Controls.Add(vertScrollBar); + + BackColor = DefaultBackBrush.Color; + ForeColor = DefaultForeBrush.Color; + borderStyle = defaultBorderStyle; + + // create the event handlers + // + currentChangedHandler = new EventHandler(DataSource_RowChanged); + positionChangedHandler = new EventHandler(DataSource_PositionChanged); + itemChangedHandler = new ItemChangedEventHandler(DataSource_ItemChanged); + metaDataChangedHandler = new EventHandler(DataSource_MetaDataChanged); + dataGridTableStylesCollectionChanged = new CollectionChangeEventHandler(TableStylesCollectionChanged); + this.dataGridTables.CollectionChanged += dataGridTableStylesCollectionChanged; + + SetDataGridTable(this.defaultTableStyle, true); + + backButtonHandler = new EventHandler(OnBackButtonClicked); + downButtonHandler = new EventHandler(OnShowParentDetailsButtonClicked); + + caption = new DataGridCaption(this); + caption.BackwardClicked += backButtonHandler; + caption.DownClicked += downButtonHandler; + + RecalculateFonts(); + Size = new Size(130, 80); + Invalidate(); + PerformLayout(); + } + + // =------------------------------------------------------------------ + // = Properties + // =------------------------------------------------------------------ + + /// + /// Gets or sets a value indicating whether the grid can be resorted by clicking on + /// a column header. + /// + [ + SRCategory(nameof(SR.CatBehavior)), + DefaultValue(true), + SRDescription(nameof(SR.DataGridAllowSortingDescr)) + ] + public bool AllowSorting + { + get + { + return gridState[GRIDSTATE_allowSorting]; + } + set + { + if (AllowSorting != value) + { + gridState[GRIDSTATE_allowSorting] = value; + if (!value && this.listManager != null) + { + IList list = this.listManager.List; + if (list is IBindingList) + ((IBindingList)list).RemoveSort(); + } + } + } + } + + [ + SRCategory(nameof(SR.CatColors)), + SRDescription(nameof(SR.DataGridAlternatingBackColorDescr)) + ] + public Color AlternatingBackColor + { + get + { + return alternatingBackBrush.Color; + } + set + { + if (value.IsEmpty) + { + throw new ArgumentException(string.Format(SR.DataGridEmptyColor, + "AlternatingBackColor")); + } + if (IsTransparentColor(value)) + throw new ArgumentException(SR.DataGridTransparentAlternatingBackColorNotAllowed); + if (!alternatingBackBrush.Color.Equals(value)) + { + alternatingBackBrush = new SolidBrush(value); + InvalidateInside(); + } + } + } + + public void ResetAlternatingBackColor() + { + if (ShouldSerializeAlternatingBackColor()) + { + AlternatingBackColor = DefaultAlternatingBackBrush.Color; + InvalidateInside(); + } + } + + protected virtual bool ShouldSerializeAlternatingBackColor() + { + return !AlternatingBackBrush.Equals(DefaultAlternatingBackBrush); + } + + internal Brush AlternatingBackBrush + { + get + { + return alternatingBackBrush; + } + } + + // overrode those properties just to move the BackColor and the ForeColor + // from the Appearance group onto the Color Group + /// + /// Gets or sets the background color of the grid. + /// + [ + SRCategory(nameof(SR.CatColors)), + SRDescription(nameof(SR.ControlBackColorDescr)) + ] + public override Color BackColor + { + // overrode those properties just to move the BackColor and the ForeColor + // from the Appearance group onto the Color Group + get + { + return base.BackColor; + } + set + { + if (IsTransparentColor(value)) + throw new ArgumentException(SR.DataGridTransparentBackColorNotAllowed); + base.BackColor = value; + } + } + + public override void ResetBackColor() + { + if (!this.BackColor.Equals(DefaultBackBrush.Color)) + { + this.BackColor = DefaultBackBrush.Color; + } + } + + [ + SRCategory(nameof(SR.CatColors)), + SRDescription(nameof(SR.ControlForeColorDescr)) + ] + public override Color ForeColor + { + get + { + return base.ForeColor; + } + set + { + base.ForeColor = value; + } + } + public override void ResetForeColor() + { + if (!this.ForeColor.Equals(DefaultForeBrush.Color)) + { + this.ForeColor = DefaultForeBrush.Color; + } + } + + /// + /// + /// Gets a value + /// indicating whether the property should be + /// persisted. + /// + /// + internal SolidBrush BackBrush + { + get + { + return backBrush; + } + } + + internal SolidBrush ForeBrush + { + get + { + return foreBrush; + } + } + + /// + /// + /// Gets or + /// sets the border style. + /// + /// + [ + SRCategory(nameof(SR.CatAppearance)), + DefaultValue(defaultBorderStyle), + DispId(NativeMethods.ActiveX.DISPID_BORDERSTYLE), + SRDescription(nameof(SR.DataGridBorderStyleDescr)) + ] + public BorderStyle BorderStyle + { + get + { + return borderStyle; + } + set + { + //valid values are 0x0 to 0x2. + if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)) + { + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(BorderStyle)); + } + if (borderStyle != value) + { + borderStyle = value; + PerformLayout(); + Invalidate(); + OnBorderStyleChanged(EventArgs.Empty); + } + } + } + + private static readonly object EVENT_BORDERSTYLECHANGED = new object(); + + [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnBorderStyleChangedDescr))] + public event EventHandler BorderStyleChanged + { + add => Events.AddHandler(EVENT_BORDERSTYLECHANGED, value); + remove => Events.RemoveHandler(EVENT_BORDERSTYLECHANGED, value); + } + + private int BorderWidth + { + get + { + if (BorderStyle == BorderStyle.Fixed3D) + { + return SystemInformation.Border3DSize.Width; + } + else if (BorderStyle == BorderStyle.FixedSingle) + { + return 2; + } + else + { + return 0; + } + } + } + + protected override Size DefaultSize + { + get + { + return new Size(130, 80); + } + } + + private static SolidBrush DefaultSelectionBackBrush + { + get + { + return (SolidBrush)SystemBrushes.ActiveCaption; + } + } + private static SolidBrush DefaultSelectionForeBrush + { + get + { + return (SolidBrush)SystemBrushes.ActiveCaptionText; + } + } + internal static SolidBrush DefaultBackBrush + { + get + { + return (SolidBrush)SystemBrushes.Window; + } + } + internal static SolidBrush DefaultForeBrush + { + get + { + return (SolidBrush)SystemBrushes.WindowText; + } + } + private static SolidBrush DefaultBackgroundBrush + { + get + { + return (SolidBrush)SystemBrushes.AppWorkspace; + } + } + internal static SolidBrush DefaultParentRowsForeBrush + { + get + { + return (SolidBrush)SystemBrushes.WindowText; + } + } + internal static SolidBrush DefaultParentRowsBackBrush + { + get + { + return (SolidBrush)SystemBrushes.Control; + } + } + internal static SolidBrush DefaultAlternatingBackBrush + { + get + { + return (SolidBrush)SystemBrushes.Window; + } + } + private static SolidBrush DefaultGridLineBrush + { + get + { + return (SolidBrush)SystemBrushes.Control; + } + } + private static SolidBrush DefaultHeaderBackBrush + { + get + { + return (SolidBrush)SystemBrushes.Control; + } + } + private static SolidBrush DefaultHeaderForeBrush + { + get + { + return (SolidBrush)SystemBrushes.ControlText; + } + } + private static Pen DefaultHeaderForePen + { + get + { + return new Pen(SystemColors.ControlText); + } + } + private static SolidBrush DefaultLinkBrush + { + get + { + return (SolidBrush)SystemBrushes.HotTrack; + } + } + + + private bool ListHasErrors + { + get + { + return gridState[GRIDSTATE_listHasErrors]; + } + set + { + if (ListHasErrors != value) + { + gridState[GRIDSTATE_listHasErrors] = value; + ComputeMinimumRowHeaderWidth(); + if (!layout.RowHeadersVisible) + return; + if (value) + { + if (myGridTable.IsDefault) + this.RowHeaderWidth += errorRowBitmapWidth; + else + this.myGridTable.RowHeaderWidth += errorRowBitmapWidth; + } + else + { + if (myGridTable.IsDefault) + this.RowHeaderWidth -= errorRowBitmapWidth; + else + this.myGridTable.RowHeaderWidth -= errorRowBitmapWidth; + } + } + } + } + + private bool Bound + { + get + { + return !(listManager == null || myGridTable == null); + } + } + + internal DataGridCaption Caption + { + get + { + return caption; + } + } + + + /// + /// + /// Gets or sets the background color of the caption area. + /// + /// + [ + SRCategory(nameof(SR.CatColors)), + SRDescription(nameof(SR.DataGridCaptionBackColorDescr)) + ] + public Color CaptionBackColor + { + get + { + return Caption.BackColor; + } + set + { + if (IsTransparentColor(value)) + throw new ArgumentException(SR.DataGridTransparentCaptionBackColorNotAllowed); + Caption.BackColor = value; + } + } + + private void ResetCaptionBackColor() + { + Caption.ResetBackColor(); + } + + /// + /// + /// Gets a value + /// indicating whether the property should be + /// persisted. + /// + /// + protected virtual bool ShouldSerializeCaptionBackColor() + { + return Caption.ShouldSerializeBackColor(); + } + + /// + /// + /// Gets + /// or sets the foreground color + /// of the caption area. + /// + /// + [ + SRCategory(nameof(SR.CatColors)), + SRDescription(nameof(SR.DataGridCaptionForeColorDescr)) + ] + public Color CaptionForeColor + { + get + { + return Caption.ForeColor; + } + set + { + Caption.ForeColor = value; + } + } + + private void ResetCaptionForeColor() + { + Caption.ResetForeColor(); + } + + /// + /// + /// Gets a value + /// indicating whether the property should be + /// persisted. + /// + /// + protected virtual bool ShouldSerializeCaptionForeColor() + { + return Caption.ShouldSerializeForeColor(); + } + + /// + /// + /// Gets or sets the font of the grid's caption. + /// + /// + [ + SRCategory(nameof(SR.CatAppearance)), + Localizable(true), + AmbientValue(null), + SRDescription(nameof(SR.DataGridCaptionFontDescr)) + ] + public Font CaptionFont + { + get + { + return Caption.Font; + } + set + { + Caption.Font = value; + } + } + + /// + /// + /// Gets a value indicating whether the + /// caption's font is persisted. + /// + /// + private bool ShouldSerializeCaptionFont() + { + return Caption.ShouldSerializeFont(); + } + + private void ResetCaptionFont() + { + Caption.ResetFont(); + } + /// - /// Displays ADO.NET data in a scrollable - /// grid. + /// + /// Gets or sets the text of the grid's caption. + /// /// [ - ComVisible(true), - ClassInterface(ClassInterfaceType.AutoDispatch), - Designer("System.Windows.Forms.Design.DataGridDesigner, " + AssemblyRef.SystemDesign), - DefaultProperty(nameof(DataSource)), - DefaultEvent(nameof(Navigate)), - ComplexBindingProperties(nameof(DataSource), nameof(DataMember)), + SRCategory(nameof(SR.CatAppearance)), + DefaultValue(""), + Localizable(true), + SRDescription(nameof(SR.DataGridCaptionTextDescr)) ] - public class DataGrid : Control, ISupportInitialize, IDataGridEditingService { - #if DEBUG - internal TraceSwitch DataGridAcc = new TraceSwitch("DataGridAcc", "Trace Windows Forms DataGrid Accessibility"); - #else - internal TraceSwitch DataGridAcc = null; - #endif - - private const int GRIDSTATE_allowSorting = 0x00000001; - private const int GRIDSTATE_columnHeadersVisible = 0x00000002; - private const int GRIDSTATE_rowHeadersVisible = 0x00000004; - private const int GRIDSTATE_trackColResize = 0x00000008; - private const int GRIDSTATE_trackRowResize = 0x00000010; - private const int GRIDSTATE_isLedgerStyle = 0x00000020; - private const int GRIDSTATE_isFlatMode = 0x00000040; - private const int GRIDSTATE_listHasErrors = 0x00000080; - private const int GRIDSTATE_dragging = 0x00000100; - private const int GRIDSTATE_inListAddNew = 0x00000200; - private const int GRIDSTATE_inDeleteRow = 0x00000400; - private const int GRIDSTATE_canFocus = 0x00000800; - private const int GRIDSTATE_readOnlyMode = 0x00001000; - private const int GRIDSTATE_allowNavigation = 0x00002000; - private const int GRIDSTATE_isNavigating = 0x00004000; - private const int GRIDSTATE_isEditing = 0x00008000; - private const int GRIDSTATE_editControlChanging = 0x00010000; - private const int GRIDSTATE_isScrolling = 0x00020000; - private const int GRIDSTATE_overCaption = 0x00040000; - private const int GRIDSTATE_childLinkFocused = 0x00080000; - private const int GRIDSTATE_inAddNewRow = 0x00100000; - private const int GRIDSTATE_inSetListManager = 0x00200000; - private const int GRIDSTATE_metaDataChanged = 0x00400000; - private const int GRIDSTATE_exceptionInPaint = 0x00800000; - private const int GRIDSTATE_layoutSuspended = 0x01000000; - - // PERF: take all the bools and put them into a state variable - private System.Collections.Specialized.BitVector32 gridState; // see GRIDSTATE_ consts above - - // for column widths - private const int NumRowsForAutoResize = 10; - - private const int errorRowBitmapWidth = 15; - - private const DataGridParentRowsLabelStyle defaultParentRowsLabelStyle = DataGridParentRowsLabelStyle.Both; - - private const BorderStyle defaultBorderStyle = BorderStyle.Fixed3D; - - private const bool defaultCaptionVisible = true; - - private const bool defaultParentRowsVisible = true; - - private DataGridTableStyle defaultTableStyle = new DataGridTableStyle(true); - - // private bool allowSorting = true; - - private SolidBrush alternatingBackBrush = DefaultAlternatingBackBrush; - - // private bool columnHeadersVisible = true; - - private SolidBrush gridLineBrush = DefaultGridLineBrush; - - private const DataGridLineStyle defaultGridLineStyle = DataGridLineStyle.Solid; - private DataGridLineStyle gridLineStyle = defaultGridLineStyle; - - private SolidBrush headerBackBrush = DefaultHeaderBackBrush; - - private Font headerFont = null; // this is ambient property to Font value - - private SolidBrush headerForeBrush = DefaultHeaderForeBrush; - private Pen headerForePen = DefaultHeaderForePen; - - private SolidBrush linkBrush = DefaultLinkBrush; - - private const int defaultPreferredColumnWidth = 75; - private int preferredColumnWidth = defaultPreferredColumnWidth; - - private static int defaultFontHeight = Control.DefaultFont.Height; - private int prefferedRowHeight = defaultFontHeight + 3; - - // private bool rowHeadersVisible = true; - private const int defaultRowHeaderWidth = 35; - private int rowHeaderWidth = defaultRowHeaderWidth; - private int minRowHeaderWidth; - - private SolidBrush selectionBackBrush = DefaultSelectionBackBrush; - private SolidBrush selectionForeBrush = DefaultSelectionForeBrush; - - // parent rows - // - private DataGridParentRows parentRows = null; - // Set_ListManager uses the originalState to determine - // if the grid should disconnect from all the MetaDataChangedEvents - // keep "originalState != null" when navigating back and forth in the grid - // and use Add/RemoveMetaDataChanged methods. - private DataGridState originalState = null; - - // ui state - // - // Don't use dataGridRows, use the accessor!!! - private DataGridRow[] dataGridRows = new DataGridRow[0]; - private int dataGridRowsLength = 0; - - // for toolTip - private int toolTipId = 0; - private DataGridToolTip toolTipProvider = null; - - private DataGridAddNewRow addNewRow = null; - private LayoutData layout = new LayoutData(); - private NativeMethods.RECT[] cachedScrollableRegion = null; - - // header namespace goo - // - - // these are actually get/set by ColumnBehavior - internal bool allowColumnResize = true; - - internal bool allowRowResize = true; - - internal DataGridParentRowsLabelStyle parentRowsLabels = defaultParentRowsLabelStyle; - - // information for col/row resizing - // private bool trackColResize = false; - private int trackColAnchor = 0; - private int trackColumn = 0; - // private bool trackRowResize = false; - private int trackRowAnchor = 0; - private int trackRow = 0; - private PropertyDescriptor trackColumnHeader = null; - private MouseEventArgs lastSplitBar = null; - - // private bool isLedgerStyle = true; - // private bool isFlatMode = false; - private Font linkFont = null; - - private SolidBrush backBrush = DefaultBackBrush; - private SolidBrush foreBrush = DefaultForeBrush; - private SolidBrush backgroundBrush = DefaultBackgroundBrush; - - // font cacheing info - private int fontHeight = -1; - private int linkFontHeight = -1; - private int captionFontHeight = -1; - private int headerFontHeight = -1; - - // the preffered height of the row. - - // if the list has items with errors - - // private bool listHasErrors = false; - - // caption - private DataGridCaption caption; - - // Border - // - private BorderStyle borderStyle; - - // data binding - // - private object dataSource = null; - private string dataMember = string.Empty; - private CurrencyManager listManager = null; + public string CaptionText + { + get + { + return Caption.Text; + } + set + { + Caption.Text = value; + } + } - // currently focused control - // we want to unparent it either when rebinding the grid or when the grid is disposed - Control toBeDisposedEditingControl = null; - - // persistent data state - // - internal GridTableStylesCollection dataGridTables = null; - // SET myGridTable in SetDataGridTable ONLY - internal DataGridTableStyle myGridTable = null; - internal bool checkHierarchy = true; - internal bool inInit = false; - - // Selection - internal int currentRow = 0; - internal int currentCol = 0; - private int numSelectedRows = 0; - private int lastRowSelected = -1; - - // dragging: - // private bool dragging = false; - - // addNewRow - // private bool inAddNewRow = false; - // delete Row - // private bool inDeleteRow = false; - - // when we leave, we call CommitEdit - // if we leave, then do not focus the dataGrid. - // so we can't focus the grid at the following moments: - // 1. while processing the OnLayout event - // 2. while processing the OnLeave event - // private bool canFocus = true; - - // for CurrentCell - #if DEBUG - private bool inDataSource_PositionChanged = false; - #endif // DEBUG - - // Policy - // private bool readOnlyMode = false; - private Policy policy = new Policy(); - // private bool allowNavigation = true; - - // editing - // private bool isNavigating = false; - // private bool isEditing = false; - // private bool editControlChanging = false; - private DataGridColumnStyle editColumn = null; - private DataGridRow editRow = null; - - // scrolling - // - private ScrollBar horizScrollBar = new HScrollBar(); - private ScrollBar vertScrollBar = new VScrollBar(); - - // the sum of the widths of the columns preceding the firstVisibleColumn - // - private int horizontalOffset = 0; - - // the number of pixels of the firstVisibleColumn which are not visible - // - private int negOffset = 0; - - private int wheelDelta = 0; - // private bool isScrolling = false; - - // Visibility - // - internal int firstVisibleRow = 0; - internal int firstVisibleCol = 0; - private int numVisibleRows = 0; - // the number of columns which are visible - private int numVisibleCols = 0; - private int numTotallyVisibleRows = 0; - // lastTotallyVisibleCol == -1 means that the data grid does not show any column in its entirety - private int lastTotallyVisibleCol = 0; - - // mouse move hot-tracking - // - private int oldRow = -1; - // private bool overCaption = true; - - // child relationships focused - // - // private bool childLinkFocused = false; - - // private static readonly object EVENT_COLUMNHEADERCLICK = new object(); - private static readonly object EVENT_CURRENTCELLCHANGED = new object(); - // private static readonly object EVENT_COLUMNRESIZE = new object(); - // private static readonly object EVENT_LINKCLICKED = new object(); - private static readonly object EVENT_NODECLICKED = new object(); - // private static readonly object EVENT_ROWRESIZE = new object(); - private static readonly object EVENT_SCROLL = new object(); - private static readonly object EVENT_BACKBUTTONCLICK = new object(); - private static readonly object EVENT_DOWNBUTTONCLICK = new object(); - - - // event handlers - // - private ItemChangedEventHandler itemChangedHandler; - private EventHandler positionChangedHandler; - private EventHandler currentChangedHandler; - private EventHandler metaDataChangedHandler; - - // we have to know when the collection of dataGridTableStyles changes - private CollectionChangeEventHandler dataGridTableStylesCollectionChanged; - - private EventHandler backButtonHandler; - private EventHandler downButtonHandler; - - private NavigateEventHandler onNavigate; - - private EventHandler onRowHeaderClick; - - // forDebug - // - // private int forDebug = 0; - - // =----------------------------------------------------------------- - - - /// - /// Initializes a new instance of the - /// class. - /// - public DataGrid() : base() { - SetStyle(ControlStyles.UserPaint, true); - SetStyle(ControlStyles.Opaque, false); - SetStyle(ControlStyles.SupportsTransparentBackColor, false); - SetStyle(ControlStyles.UserMouse, true); - this.gridState = new System.Collections.Specialized.BitVector32(0x00042827); - - dataGridTables = new GridTableStylesCollection(this); - layout = CreateInitialLayoutState(); - parentRows = new DataGridParentRows(this); - - horizScrollBar.Top = ClientRectangle.Height - horizScrollBar.Height; - horizScrollBar.Left = 0; - horizScrollBar.Visible = false; - horizScrollBar.Scroll += new ScrollEventHandler(GridHScrolled); - Controls.Add(horizScrollBar); - - vertScrollBar.Top = 0; - vertScrollBar.Left = ClientRectangle.Width - vertScrollBar.Width; - vertScrollBar.Visible = false; - vertScrollBar.Scroll += new ScrollEventHandler(GridVScrolled); - Controls.Add(vertScrollBar); - - BackColor = DefaultBackBrush.Color; - ForeColor = DefaultForeBrush.Color; - borderStyle = defaultBorderStyle; - - // create the event handlers - // - currentChangedHandler = new EventHandler(DataSource_RowChanged); - positionChangedHandler = new EventHandler(DataSource_PositionChanged); - itemChangedHandler = new ItemChangedEventHandler(DataSource_ItemChanged); - metaDataChangedHandler = new EventHandler(DataSource_MetaDataChanged); - dataGridTableStylesCollectionChanged = new CollectionChangeEventHandler(TableStylesCollectionChanged); - this.dataGridTables.CollectionChanged += dataGridTableStylesCollectionChanged; - - SetDataGridTable(this.defaultTableStyle, true); - - backButtonHandler = new EventHandler(OnBackButtonClicked); - downButtonHandler = new EventHandler(OnShowParentDetailsButtonClicked); - - caption = new DataGridCaption(this); - caption.BackwardClicked += backButtonHandler; - caption.DownClicked += downButtonHandler; - - RecalculateFonts(); - Size = new Size(130, 80); - Invalidate(); - PerformLayout(); + /// + /// + /// Gets or sets a value that indicates + /// whether the grid's caption is visible. + /// + /// + [ + DefaultValue(true), + SRCategory(nameof(SR.CatDisplay)), + SRDescription(nameof(SR.DataGridCaptionVisibleDescr)) + ] + public bool CaptionVisible + { + get + { + return layout.CaptionVisible; } - - // =------------------------------------------------------------------ - // = Properties - // =------------------------------------------------------------------ - - /// - /// Gets or sets a value indicating whether the grid can be resorted by clicking on - /// a column header. - /// - [ - SRCategory(nameof(SR.CatBehavior)), - DefaultValue(true), - SRDescription(nameof(SR.DataGridAllowSortingDescr)) - ] - public bool AllowSorting { - get { - return gridState[GRIDSTATE_allowSorting]; - } - set { - if (AllowSorting != value) { - gridState[GRIDSTATE_allowSorting] = value; - if (!value && this.listManager != null) { - IList list = this.listManager.List; - if (list is IBindingList) - ((IBindingList) list).RemoveSort(); + set + { + if (layout.CaptionVisible != value) + { + layout.CaptionVisible = value; + PerformLayout(); + Invalidate(); + OnCaptionVisibleChanged(EventArgs.Empty); + } + } + } + + private static readonly object EVENT_CAPTIONVISIBLECHANGED = new object(); + + [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnCaptionVisibleChangedDescr))] + public event EventHandler CaptionVisibleChanged + { + add => Events.AddHandler(EVENT_CAPTIONVISIBLECHANGED, value); + remove => Events.RemoveHandler(EVENT_CAPTIONVISIBLECHANGED, value); + } + + /// + /// + /// Gets or sets which cell has the focus. Not available at design time. + /// + /// + [ + Browsable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), + SRDescription(nameof(SR.DataGridCurrentCellDescr)) + ] + public DataGridCell CurrentCell + { + get + { + return new DataGridCell(currentRow, currentCol); + } + set + { + // if the OnLayout event was not set in the grid, then we can't + // reliably set the currentCell on the grid. + if (layout.dirty) + throw new ArgumentException(SR.DataGridSettingCurrentCellNotGood); + if (value.RowNumber == currentRow && value.ColumnNumber == currentCol) + return; + + // should we throw an exception, maybe? + if (DataGridRowsLength == 0 || this.myGridTable.GridColumnStyles == null || this.myGridTable.GridColumnStyles.Count == 0) + return; + EnsureBound(); + + int currentRowSaved = currentRow; + int currentColSaved = currentCol; + bool wasEditing = gridState[GRIDSTATE_isEditing]; + bool cellChanged = false; + + // if the position in the listManager changed under the DataGrid, + // then do not edit after setting the current cell + bool doNotEdit = false; + + int newCol = value.ColumnNumber; + int newRow = value.RowNumber; + + string errorMessage = null; + + try + { + int columnCount = myGridTable.GridColumnStyles.Count; + if (newCol < 0) + newCol = 0; + if (newCol >= columnCount) + newCol = columnCount - 1; + + int localGridRowsLength = DataGridRowsLength; + DataGridRow[] localGridRows = DataGridRows; + + if (newRow < 0) + { + newRow = 0; + } + if (newRow >= localGridRowsLength) + { + newRow = localGridRowsLength - 1; + } + + // Current Column changing + // + if (currentCol != newCol) + { + cellChanged = true; + int currentListManagerPosition = this.ListManager.Position; + int currentListManagerCount = this.ListManager.List.Count; + + EndEdit(); + + if (this.ListManager.Position != currentListManagerPosition || + currentListManagerCount != this.ListManager.List.Count) + { + // EndEdit changed the list. + // Reset the data grid rows and the current row inside the datagrid. + // And then exit the method. + RecreateDataGridRows(); + if (this.ListManager.List.Count > 0) + { + this.currentRow = this.ListManager.Position; + Edit(); + } + else + { + this.currentRow = -1; + } + + return; + } + + currentCol = newCol; + InvalidateRow(currentRow); + } + + // Current Row changing + // + if (currentRow != newRow) + { + cellChanged = true; + int currentListManagerPosition = this.ListManager.Position; + int currentListManagerCount = this.ListManager.List.Count; + + EndEdit(); + + if (this.ListManager.Position != currentListManagerPosition || + currentListManagerCount != this.ListManager.List.Count) + { + // EndEdit changed the list. + // Reset the data grid rows and the current row inside the datagrid. + // And then exit the method. + RecreateDataGridRows(); + if (this.ListManager.List.Count > 0) + { + this.currentRow = this.ListManager.Position; + Edit(); + } + else + { + this.currentRow = -1; + } + + return; + } + + if (currentRow < localGridRowsLength) + localGridRows[currentRow].OnRowLeave(); + localGridRows[newRow].OnRowEnter(); + currentRow = newRow; + if (currentRowSaved < localGridRowsLength) + InvalidateRow(currentRowSaved); + InvalidateRow(currentRow); + + if (currentRowSaved != listManager.Position) + { + // not in sync +#if DEBUG + Debug.Assert(inDataSource_PositionChanged, "currentRow and listManager.Position can be out of sync only when the listManager changes its position under the DataGrid or when navigating back"); + Debug.Assert(ListManager.Position == currentRow || listManager.Position == -1, "DataSource_PositionChanged changes the position in the grid to the position in the listManager"); +#endif //DEBUG + doNotEdit = true; + if (gridState[GRIDSTATE_isEditing]) + AbortEdit(); + } + else if (gridState[GRIDSTATE_inAddNewRow]) + { +#if DEBUG + int currentRowCount = this.DataGridRowsLength; +#endif // debug + // cancelCurrentEdit will change the position in the list + // to the last element in the list. and the grid will get an on position changed + // event, and will set the current cell to the last element in the dataSource. + // so unhook the PositionChanged event from the listManager; + this.ListManager.PositionChanged -= positionChangedHandler; + this.ListManager.CancelCurrentEdit(); + this.ListManager.Position = this.currentRow; + this.ListManager.PositionChanged += positionChangedHandler; +#if DEBUG + + Debug.Assert(currentRowSaved > currentRow, "we can only go up when we are inAddNewRow"); + Debug.Assert(currentRowCount == this.DataGridRowsLength, "the number of rows in the dataGrid should not change"); + Debug.Assert(currentRowCount == this.ListManager.Count + 1, "the listManager should have one less record"); +#endif // debug + localGridRows[DataGridRowsLength - 1] = new DataGridAddNewRow(this, this.myGridTable, DataGridRowsLength - 1); + SetDataGridRows(localGridRows, DataGridRowsLength); + gridState[GRIDSTATE_inAddNewRow] = false; + } + else + { + ListManager.EndCurrentEdit(); + // some special care must be given when setting the + // position in the listManager. + // if EndCurrentEdit() deleted the current row + // ( because of some filtering problem, say ) + // then we cannot go over the last row + // + if (localGridRowsLength != DataGridRowsLength) + { + Debug.Assert(localGridRowsLength == DataGridRowsLength + 1, "this is the only change that could have happened"); + currentRow = (currentRow == localGridRowsLength - 1) ? DataGridRowsLength - 1 : currentRow; + } + + if (currentRow == dataGridRowsLength - 1 && policy.AllowAdd) + { + // it may be case ( see previous comment ) + // that listManager.EndCurrentEdit changed the number of rows + // in the grid. in this case, we should not be using the old + // localGridRows in our assertion, cause they are outdated now + // + Debug.Assert(this.DataGridRows[currentRow] is DataGridAddNewRow, "the last row is the DataGridAddNewRow"); + this.AddNewRow(); + Debug.Assert(ListManager.Position == currentRow || listManager.Position == -1, "the listManager should be positioned at the last row"); + } + else + { + + ListManager.Position = currentRow; + } } + } + } - } - - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridAlternatingBackColorDescr)) - ] - public Color AlternatingBackColor { - get { - return alternatingBackBrush.Color; - } - set { - if (value.IsEmpty) { - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, - "AlternatingBackColor")); + catch (Exception e) + { + errorMessage = e.Message; + } + + if (errorMessage != null) + { + DialogResult result = RTLAwareMessageBox.Show(null, + string.Format(SR.DataGridPushedIncorrectValueIntoColumn, errorMessage), + SR.DataGridErrorMessageBoxCaption, MessageBoxButtons.YesNo, + MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); + + if (result == DialogResult.Yes) + { + currentRow = currentRowSaved; + currentCol = currentColSaved; + Debug.Assert(currentRow == ListManager.Position || listManager.Position == -1, "the position in the list manager (" + ListManager.Position + ") is out of sync with the currentRow (" + currentRow + ")" + " and the exception is '" + errorMessage + "'"); + // this will make sure the newRow will not paint the + // row selector. + InvalidateRowHeader(newRow); + // also, make sure that we get the row selector on the currentrow, too + InvalidateRowHeader(currentRow); + if (wasEditing) + Edit(); } - if (IsTransparentColor(value)) - throw new ArgumentException(SR.DataGridTransparentAlternatingBackColorNotAllowed); - if (!alternatingBackBrush.Color.Equals(value)) { - alternatingBackBrush = new SolidBrush(value); - InvalidateInside(); + else + { + // if the user committed a row that used to be addNewRow and the backEnd rejects it, + // and then it tries to navigate down then we should stay in the addNewRow + // in this particular scenario, CancelCurrentEdit will cause the last row to be deleted, + // and this will ultimately call InvalidateRow w/ a row number larger than the number of rows + // so set the currentRow here: + if (currentRow == this.DataGridRowsLength - 1 && currentRowSaved == this.DataGridRowsLength - 2 && DataGridRows[currentRow] is DataGridAddNewRow) + newRow = currentRowSaved; + currentRow = newRow; + Debug.Assert(result == DialogResult.No, "we only put cancel and ok on the error message box"); + this.listManager.PositionChanged -= positionChangedHandler; + this.listManager.CancelCurrentEdit(); + this.listManager.Position = newRow; + this.listManager.PositionChanged += positionChangedHandler; + currentRow = newRow; + currentCol = newCol; + if (wasEditing) + Edit(); + } + } + + if (cellChanged) + { + EnsureVisible(currentRow, currentCol); + OnCurrentCellChanged(EventArgs.Empty); + + // if the user changed the current cell using the UI, edit the new cell + // but if the user changed the current cell by changing the position in the + // listManager, then do not continue the edit + // + if (!doNotEdit) + { +#if DEBUG + Debug.Assert(!inDataSource_PositionChanged, "if the user changed the current cell using the UI, then do not edit"); +#endif // debug + Edit(); } + + + AccessibilityNotifyClients(AccessibleEvents.Focus, CurrentCellAccIndex); + AccessibilityNotifyClients(AccessibleEvents.Selection, CurrentCellAccIndex); } + + Debug.Assert(currentRow == ListManager.Position || listManager.Position == -1, "the position in the list manager is out of sync with the currentRow"); } - - public void ResetAlternatingBackColor() { - if (ShouldSerializeAlternatingBackColor()) { - AlternatingBackColor = DefaultAlternatingBackBrush.Color; + } + + internal int CurrentCellAccIndex + { + get + { + int currentCellAccIndex = 0; + currentCellAccIndex++; // ParentRowsAccessibleObject + currentCellAccIndex += this.myGridTable.GridColumnStyles.Count; // ColumnHeaderAccessibleObject + currentCellAccIndex += this.DataGridRows.Length; // DataGridRowAccessibleObject + if (this.horizScrollBar.Visible) // Horizontal Scroll Bar Accessible Object + currentCellAccIndex++; + if (this.vertScrollBar.Visible) // Vertical Scroll Bar Accessible Object + currentCellAccIndex++; + currentCellAccIndex += (this.currentRow * this.myGridTable.GridColumnStyles.Count) + this.currentCol; + return currentCellAccIndex; + } + } + + [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnCurrentCellChangedDescr))] + public event EventHandler CurrentCellChanged + { + add => Events.AddHandler(EVENT_CURRENTCELLCHANGED, value); + remove => Events.RemoveHandler(EVENT_CURRENTCELLCHANGED, value); + } + + private int CurrentColumn + { + get + { + return CurrentCell.ColumnNumber; + } + set + { + this.CurrentCell = new DataGridCell(currentRow, value); + } + } + + private int CurrentRow + { + get + { + return CurrentCell.RowNumber; + } + set + { + CurrentCell = new DataGridCell(value, currentCol); + } + } + + [ + SRCategory(nameof(SR.CatColors)), + SRDescription(nameof(SR.DataGridSelectionBackColorDescr)) + ] + public Color SelectionBackColor + { + get + { + return selectionBackBrush.Color; + } + set + { + if (value.IsEmpty) + throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "SelectionBackColor")); + if (IsTransparentColor(value)) + throw new ArgumentException(SR.DataGridTransparentSelectionBackColorNotAllowed); + if (!value.Equals(selectionBackBrush.Color)) + { + selectionBackBrush = new SolidBrush(value); + InvalidateInside(); } } - - protected virtual bool ShouldSerializeAlternatingBackColor() + } + + internal SolidBrush SelectionBackBrush + { + get { - return !AlternatingBackBrush.Equals(DefaultAlternatingBackBrush); + return this.selectionBackBrush; } - - internal Brush AlternatingBackBrush { - get { - return alternatingBackBrush; - } + } + + internal SolidBrush SelectionForeBrush + { + get + { + return this.selectionForeBrush; } - - // overrode those properties just to move the BackColor and the ForeColor - // from the Appearance group onto the Color Group - /// - /// Gets or sets the background color of the grid. - /// - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.ControlBackColorDescr)) - ] - public override Color BackColor { - // overrode those properties just to move the BackColor and the ForeColor - // from the Appearance group onto the Color Group - get { - return base.BackColor; - } - set { - if (IsTransparentColor(value)) - throw new ArgumentException(SR.DataGridTransparentBackColorNotAllowed); - base.BackColor = value; - } + } + + protected bool ShouldSerializeSelectionBackColor() + { + return !DefaultSelectionBackBrush.Equals(selectionBackBrush); + } + + public void ResetSelectionBackColor() + { + if (ShouldSerializeSelectionBackColor()) + SelectionBackColor = DefaultSelectionBackBrush.Color; + } + + [ + SRCategory(nameof(SR.CatColors)), + SRDescription(nameof(SR.DataGridSelectionForeColorDescr)) + ] + public Color SelectionForeColor + { + get + { + return selectionForeBrush.Color; } - - public override void ResetBackColor() { - if (!this.BackColor.Equals(DefaultBackBrush.Color)) { - this.BackColor = DefaultBackBrush.Color; + set + { + if (value.IsEmpty) + throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "SelectionForeColor")); + if (!value.Equals(selectionForeBrush.Color)) + { + selectionForeBrush = new SolidBrush(value); + + InvalidateInside(); } } - - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.ControlForeColorDescr)) - ] - public override Color ForeColor { - get { - return base.ForeColor; - } - set { - base.ForeColor = value; - } + } + + protected virtual bool ShouldSerializeSelectionForeColor() + { + return !SelectionForeBrush.Equals(DefaultSelectionForeBrush); + } + + public void ResetSelectionForeColor() + { + if (ShouldSerializeSelectionForeColor()) + SelectionForeColor = DefaultSelectionForeBrush.Color; + } + + internal override bool ShouldSerializeForeColor() + { + return !DefaultForeBrush.Color.Equals(this.ForeColor); + } + + /// + /// Indicates whether the property should be + /// persisted. + /// + internal override bool ShouldSerializeBackColor() + { + return !DefaultBackBrush.Color.Equals(this.BackColor); + } + + // Don't use dataGridRows, use the accessor!!! + internal DataGridRow[] DataGridRows + { + get + { + if (dataGridRows == null) + CreateDataGridRows(); + return dataGridRows; } - public override void ResetForeColor() { - if (!this.ForeColor.Equals(DefaultForeBrush.Color)) { - this.ForeColor = DefaultForeBrush.Color; - } + } + + // ToolTipping + internal DataGridToolTip ToolTipProvider + { + get + { + return toolTipProvider; } - - /// - /// - /// Gets a value - /// indicating whether the property should be - /// persisted. - /// - /// - internal SolidBrush BackBrush { - get { - return backBrush; - } + } + + internal int ToolTipId + { + get + { + return toolTipId; } - - internal SolidBrush ForeBrush { - get { - return foreBrush; - } + set + { + toolTipId = value; } - - /// - /// - /// Gets or - /// sets the border style. - /// - /// - [ - SRCategory(nameof(SR.CatAppearance)), - DefaultValue(defaultBorderStyle), - DispId(NativeMethods.ActiveX.DISPID_BORDERSTYLE), - SRDescription(nameof(SR.DataGridBorderStyleDescr)) - ] - public BorderStyle BorderStyle { - get { - return borderStyle; - } - set { - //valid values are 0x0 to 0x2. - if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)){ - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(BorderStyle)); - } - if (borderStyle != value) { - borderStyle = value; - PerformLayout(); - Invalidate(); - OnBorderStyleChanged(EventArgs.Empty); - } - } + } + + private void ResetToolTip() + { + // remove all the tool tips which are stored + for (int i = 0; i < ToolTipId; i++) + { + ToolTipProvider.RemoveToolTip(new IntPtr(i)); } - - private static readonly object EVENT_BORDERSTYLECHANGED = new object(); - - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnBorderStyleChangedDescr))] - public event EventHandler BorderStyleChanged { - add => Events.AddHandler(EVENT_BORDERSTYLECHANGED, value); - remove => Events.RemoveHandler(EVENT_BORDERSTYLECHANGED, value); + + // add toolTips for the backButton and + // details button on the caption. + if (!this.parentRows.IsEmpty()) + { + bool alignRight = this.isRightToLeft(); + int detailsButtonWidth = this.Caption.GetDetailsButtonWidth(); + Rectangle backButton = this.Caption.GetBackButtonRect(this.layout.Caption, alignRight, detailsButtonWidth); + Rectangle detailsButton = this.Caption.GetDetailsButtonRect(this.layout.Caption, alignRight); + + // mirror the buttons wrt RTL property + backButton.X = MirrorRectangle(backButton, layout.Inside, isRightToLeft()); + detailsButton.X = MirrorRectangle(detailsButton, layout.Inside, isRightToLeft()); + + ToolTipProvider.AddToolTip(SR.DataGridCaptionBackButtonToolTip, new IntPtr(0), backButton); + ToolTipProvider.AddToolTip(SR.DataGridCaptionDetailsButtonToolTip, new IntPtr(1), detailsButton); + ToolTipId = 2; } - - private int BorderWidth { - get { - if (BorderStyle == BorderStyle.Fixed3D) { - return SystemInformation.Border3DSize.Width; - } - else if (BorderStyle == BorderStyle.FixedSingle) { - return 2; - } - else { - return 0; - } - } + else + { + ToolTipId = 0; } - - protected override Size DefaultSize { - get { - return new Size(130, 80); - } + } + + + + /// + /// Given a cursor, this will Create the right DataGridRows + /// + private void CreateDataGridRows() + { + CurrencyManager listManager = ListManager; + DataGridTableStyle dgt = this.myGridTable; + InitializeColumnWidths(); + + if (listManager == null) + { + SetDataGridRows(new DataGridRow[0], 0); + return; } - - private static SolidBrush DefaultSelectionBackBrush { - get { - return (SolidBrush)SystemBrushes.ActiveCaption; - } + + int nDataGridRows = listManager.Count; + if (policy.AllowAdd) + nDataGridRows++; + + DataGridRow[] rows = new DataGridRow[nDataGridRows]; + for (int r = 0; r < listManager.Count; r++) + { + rows[r] = new DataGridRelationshipRow(this, dgt, r); } - private static SolidBrush DefaultSelectionForeBrush { - get { - return (SolidBrush)SystemBrushes.ActiveCaptionText; - } + + if (policy.AllowAdd) + { + this.addNewRow = new DataGridAddNewRow(this, dgt, nDataGridRows - 1); + rows[nDataGridRows - 1] = addNewRow; + } + else + { + addNewRow = null; } - internal static SolidBrush DefaultBackBrush { - get { - return (SolidBrush)SystemBrushes.Window; + // SetDataGridRows(rows, rows.Length); + SetDataGridRows(rows, nDataGridRows); + } + + private void RecreateDataGridRows() + { + int nDataGridRows = 0; + CurrencyManager listManager = ListManager; + + if (listManager != null) + { + nDataGridRows = listManager.Count; + if (policy.AllowAdd) + { + nDataGridRows++; } } - internal static SolidBrush DefaultForeBrush { - get { - return (SolidBrush)SystemBrushes.WindowText; + SetDataGridRows(null, nDataGridRows); + } + + /// + /// Sets the array of DataGridRow objects used for + /// all row-related logic in the DataGrid. + /// + internal void SetDataGridRows(DataGridRow[] newRows, int newRowsLength) + { + dataGridRows = newRows; + dataGridRowsLength = newRowsLength; + + // update the vertical scroll bar + vertScrollBar.Maximum = Math.Max(0, DataGridRowsLength - 1); + if (firstVisibleRow > newRowsLength) + { + vertScrollBar.Value = 0; + firstVisibleRow = 0; + } + + ResetUIState(); +#if DEBUG + // sanity check: all the rows should have the same + // dataGridTable + if (newRows != null && newRowsLength > 0) + { + DataGridTableStyle dgTable = newRows[0].DataGridTableStyle; + for (int i = 0; i < newRowsLength; i++) + { + Debug.Assert(dgTable == newRows[i].DataGridTableStyle, "how can two rows have different tableStyles?"); + } } - private static SolidBrush DefaultBackgroundBrush { - get { - return (SolidBrush)SystemBrushes.AppWorkspace; +#endif // DEBUG + Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: There are now " + DataGridRowsLength.ToString(CultureInfo.InvariantCulture) + " rows."); + } + + internal int DataGridRowsLength + { + get + { + return dataGridRowsLength; + } + } + + /// + /// Gets or sets the data source that the grid is displaying data for. + /// + [ + DefaultValue(null), + SRCategory(nameof(SR.CatData)), + RefreshProperties(RefreshProperties.Repaint), + AttributeProvider(typeof(IListSource)), + SRDescription(nameof(SR.DataGridDataSourceDescr)) + ] + public object DataSource + { + get + { + return dataSource; + } + + set + { + if (value != null && !(value is IList || value is IListSource)) + throw new ArgumentException(SR.BadDataSourceForComplexBinding); + if (dataSource != null && dataSource.Equals(value)) + { + return; + } + + // when the designer resets the dataSource to null, set the dataMember to null, too + if ((value == null || value == Convert.DBNull) && this.DataMember != null && this.DataMember.Length != 0) + { + this.dataSource = null; + this.DataMember = string.Empty; + return; } + + // if we are setting the dataSource and the dataMember is not a part + // of the properties in the dataSource, then set the dataMember to "" + // + if (value != null) + EnforceValidDataMember(value); + + Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: DataSource being set to " + ((value == null) ? "null" : value.ToString())); + + // when we change the dataSource, we need to clear the parent rows. + // the same goes for all the caption UI: reset it when the datasource changes. + // + ResetParentRows(); + Set_ListManager(value, this.DataMember, false); + } + } + + private static readonly object EVENT_DATASOURCECHANGED = new object(); + + [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnDataSourceChangedDescr))] + public event EventHandler DataSourceChanged + { + add => Events.AddHandler(EVENT_DATASOURCECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATASOURCECHANGED, value); + } + + /// + /// + /// Gets or sets the specific table in a DataSource for the control. + /// + /// + [ + DefaultValue(null), + SRCategory(nameof(SR.CatData)), + Editor("System.Windows.Forms.Design.DataMemberListEditor, " + AssemblyRef.SystemDesign, typeof(System.Drawing.Design.UITypeEditor)), + SRDescription(nameof(SR.DataGridDataMemberDescr)) + ] + public string DataMember + { + get + { + return dataMember; + } + set + { + if (dataMember != null && dataMember.Equals(value)) + return; + Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: DataSource being set to " + ((value == null) ? "null" : value.ToString())); + // when we change the dataMember, we need to clear the parent rows. + // the same goes for all the caption UI: reset it when the datamember changes. + // + ResetParentRows(); + Set_ListManager(this.DataSource, value, false); + } + } + + public void SetDataBinding(object dataSource, string dataMember) + { + parentRows.Clear(); + originalState = null; + caption.BackButtonActive = caption.DownButtonActive = caption.BackButtonVisible = false; + caption.SetDownButtonDirection(!layout.ParentRowsVisible); + + Set_ListManager(dataSource, dataMember, false); + } + + [ + Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), + SRDescription(nameof(SR.DataGridListManagerDescr)) + ] + internal protected CurrencyManager ListManager + { + get + { + //try to return something useful: + if (listManager == null && this.BindingContext != null && this.DataSource != null) + return (CurrencyManager)this.BindingContext[this.DataSource, this.DataMember]; + else + return listManager; + } + set + { + throw new NotSupportedException(SR.DataGridSetListManager); + } + } + + internal void Set_ListManager(object newDataSource, string newDataMember, bool force) + { + Set_ListManager(newDataSource, newDataMember, force, true); // true for forcing column creation + } + + // + // prerequisite: the dataMember and the dataSource should be set to the new values + // + // will do the following: + // call EndEdit on the current listManager, will unWire the listManager events, will set the listManager to the new + // reality, will wire the new listManager, will update the policy, will set the dataGridTable, will reset the ui state. + // + internal void Set_ListManager(object newDataSource, string newDataMember, bool force, bool forceColumnCreation) + { + bool dataSourceChanged = this.DataSource != newDataSource; + bool dataMemberChanged = this.DataMember != newDataMember; + + // if nothing happened, then why do any work? + if (!force && !dataSourceChanged && !dataMemberChanged && gridState[GRIDSTATE_inSetListManager]) + return; + + gridState[GRIDSTATE_inSetListManager] = true; + if (this.toBeDisposedEditingControl != null) + { + Debug.Assert(this.Controls.Contains(this.toBeDisposedEditingControl)); + this.Controls.Remove(this.toBeDisposedEditingControl); + this.toBeDisposedEditingControl = null; } - internal static SolidBrush DefaultParentRowsForeBrush { - get { - return (SolidBrush)SystemBrushes.WindowText; + bool beginUpdateInternal = true; + try + { + // will endEdit on the current listManager + UpdateListManager(); + + // unwire the events: + if (this.listManager != null) + UnWireDataSource(); + + CurrencyManager oldListManager = listManager; + bool listManagerChanged = false; + // set up the new listManager + // CAUTION: we need to set up the listManager in the grid before setting the dataSource/dataMember props + // in the grid. the reason is that if the BindingContext was not yet requested, and it is created in the BindingContext prop + // then the grid will call Set_ListManager again, and eventually that means that the dataGrid::listManager will + // be hooked up twice to all the events (PositionChanged, ItemChanged, CurrentChanged) + if (newDataSource != null && this.BindingContext != null && !(newDataSource == Convert.DBNull)) + this.listManager = (CurrencyManager)this.BindingContext[newDataSource, newDataMember]; + else + listManager = null; + + // update the dataSource and the dateMember + this.dataSource = newDataSource; + this.dataMember = newDataMember == null ? "" : newDataMember; + + listManagerChanged = (listManager != oldListManager); + + // wire the events + if (listManager != null) + { + WireDataSource(); + // update the policy + policy.UpdatePolicy(this.listManager, this.ReadOnly); + } + + if (!Initializing) + { + if (listManager == null) + { + if (this.ContainsFocus && this.ParentInternal == null) + { + Debug.Assert(this.toBeDisposedEditingControl == null, "we should have removed the toBeDisposedEditingControl already"); + // if we unparent the active control then the form won't close + for (int i = 0; i < this.Controls.Count; i++) + { + if (this.Controls[i].Focused) + { + this.toBeDisposedEditingControl = this.Controls[i]; + break; + } + } + + if (this.toBeDisposedEditingControl == this.horizScrollBar || this.toBeDisposedEditingControl == this.vertScrollBar) + { + this.toBeDisposedEditingControl = null; + } + +#if DEBUG + else + { + Debug.Assert(this.toBeDisposedEditingControl != null, "if the grid contains the focus, then the active control should be in the children of data grid control"); + Debug.Assert(this.editColumn != null, "if we have an editing control should be a control in the data grid column"); + if (this.editColumn is DataGridTextBoxColumn) + { + Debug.Assert(((DataGridTextBoxColumn)this.editColumn).TextBox == this.toBeDisposedEditingControl, "if we have an editing control should be a control in the data grid column"); + } + } +#endif // debug; + + } + + SetDataGridRows(null, 0); + this.defaultTableStyle.GridColumnStyles.Clear(); + SetDataGridTable(this.defaultTableStyle, forceColumnCreation); + + if (this.toBeDisposedEditingControl != null) + { + this.Controls.Add(this.toBeDisposedEditingControl); + } + } } - } - internal static SolidBrush DefaultParentRowsBackBrush { - get { - return (SolidBrush)SystemBrushes.Control; + + // PERF: if the listManager did not change, then do not: + // 1. create new rows + // 2. create new columns + // 3. compute the errors in the list + // + // when the metaDataChanges, we need to recreate + // the rows and the columns + // + if (listManagerChanged || gridState[GRIDSTATE_metaDataChanged]) + { + if (this.Visible) + BeginUpdateInternal(); + + if (listManager != null) + { + // get rid of the old gridColumns + // we need to clear the old column collection even when navigating to + // a list that has a table style associated w/ it. Why? because the + // old column collection will be used by the parent rows to paint + this.defaultTableStyle.GridColumnStyles.ResetDefaultColumnCollection(); + + DataGridTableStyle newGridTable = this.dataGridTables[listManager.GetListName()]; + if (newGridTable == null) + { + SetDataGridTable(this.defaultTableStyle, forceColumnCreation); + } + else + { + SetDataGridTable(newGridTable, forceColumnCreation); + } + + // set the currentRow in ssync w/ the position in the listManager + currentRow = listManager.Position == -1 ? 0 : listManager.Position; + } + + // when we create the rows we need to use the current dataGridTable + // + RecreateDataGridRows(); + if (this.Visible) + EndUpdateInternal(); + beginUpdateInternal = false; + + ComputeMinimumRowHeaderWidth(); + if (this.myGridTable.IsDefault) + this.RowHeaderWidth = Math.Max(this.minRowHeaderWidth, this.RowHeaderWidth); + else + this.myGridTable.RowHeaderWidth = Math.Max(this.minRowHeaderWidth, this.RowHeaderWidth); + + ListHasErrors = DataGridSourceHasErrors(); + + // build the list of columns and relationships + // wipe out the now invalid states + //ResetMouseState(); + + ResetUIState(); + + //layout.CaptionVisible = dataCursor == null ? false : true; + + OnDataSourceChanged(EventArgs.Empty); } + } - internal static SolidBrush DefaultAlternatingBackBrush { - get { - return (SolidBrush)SystemBrushes.Window; - } + finally + { + gridState[GRIDSTATE_inSetListManager] = false; + // start painting again + if (beginUpdateInternal && this.Visible) + EndUpdateInternal(); } - private static SolidBrush DefaultGridLineBrush { - get { - return (SolidBrush)SystemBrushes.Control; + } + + /// + /// Gets or sets index of the selected row. + /// + // will set the position in the ListManager + // + [ + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), + Browsable(false), + SRDescription(nameof(SR.DataGridSelectedIndexDescr)) + ] + public int CurrentRowIndex + { + get + { + if (originalState == null) + return this.listManager == null ? -1 : this.listManager.Position; + else + { + if (this.BindingContext == null) + return -1; + CurrencyManager originalListManager = (CurrencyManager)this.BindingContext[originalState.DataSource, originalState.DataMember]; + return originalListManager.Position; } } - private static SolidBrush DefaultHeaderBackBrush { - get { - return (SolidBrush)SystemBrushes.Control; + set + { + if (this.listManager == null) + throw new InvalidOperationException(SR.DataGridSetSelectIndex); + + if (originalState == null) + { + this.listManager.Position = value; + currentRow = value; + return; } + + // if we have a this.ListManager, then this.BindingManager cannot be null + // + CurrencyManager originalListManager = (CurrencyManager)this.BindingContext[originalState.DataSource, originalState.DataMember]; + originalListManager.Position = value; + + // this is for parent rows + originalState.LinkingRow = originalState.DataGridRows[value]; + + // Invalidate everything + Invalidate(); } - private static SolidBrush DefaultHeaderForeBrush { - get { - return (SolidBrush)SystemBrushes.ControlText; - } + } + + + /// + /// Gets the collection of tables for the grid. + /// + [ + SRCategory(nameof(SR.CatData)), + DesignerSerializationVisibility(DesignerSerializationVisibility.Content), + Localizable(true), + SRDescription(nameof(SR.DataGridGridTablesDescr)) + ] + public GridTableStylesCollection TableStyles + { + get + { + return dataGridTables; } - private static Pen DefaultHeaderForePen { - get { - return new Pen(SystemColors.ControlText); - } + } + + internal new int FontHeight + { + get + { + return fontHeight; } - private static SolidBrush DefaultLinkBrush { - get { - return (SolidBrush)SystemBrushes.HotTrack; - } + } + + internal AccessibleObject ParentRowsAccessibleObject + { + get + { + return parentRows.AccessibleObject; } - - - private bool ListHasErrors { - get { - return gridState[GRIDSTATE_listHasErrors]; - } - set { - if (ListHasErrors != value) - { - gridState[GRIDSTATE_listHasErrors] = value; - ComputeMinimumRowHeaderWidth(); - if (!layout.RowHeadersVisible) - return; - if (value) { - if (myGridTable.IsDefault) - this.RowHeaderWidth += errorRowBitmapWidth; - else - this.myGridTable.RowHeaderWidth += errorRowBitmapWidth; - } - else { - if (myGridTable.IsDefault) - this.RowHeaderWidth -= errorRowBitmapWidth; - else - this.myGridTable.RowHeaderWidth -= errorRowBitmapWidth; - } - } - } - } - - private bool Bound { - get { - return !(listManager == null || myGridTable == null); - } + } + + internal Rectangle ParentRowsBounds + { + get + { + return layout.ParentRows; } - - internal DataGridCaption Caption { - get { - return caption; - } + } + + /// + /// Gets or sets the color of the grid lines. + /// + [ + SRCategory(nameof(SR.CatColors)), + SRDescription(nameof(SR.DataGridGridLineColorDescr)) + ] + public Color GridLineColor + { + get + { + return gridLineBrush.Color; } - - - /// - /// - /// Gets or sets the background color of the caption area. - /// - /// - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridCaptionBackColorDescr)) - ] - public Color CaptionBackColor { - get { - return Caption.BackColor; - } - set { - if (IsTransparentColor(value)) - throw new ArgumentException(SR.DataGridTransparentCaptionBackColorNotAllowed); - Caption.BackColor = value; + set + { + if (gridLineBrush.Color != value) + { + if (value.IsEmpty) + throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "GridLineColor")); + gridLineBrush = new SolidBrush(value); + + Invalidate(layout.Data); } } - - private void ResetCaptionBackColor() { - Caption.ResetBackColor(); - } - - /// - /// - /// Gets a value - /// indicating whether the property should be - /// persisted. - /// - /// - protected virtual bool ShouldSerializeCaptionBackColor() + } + + protected virtual bool ShouldSerializeGridLineColor() + { + return !GridLineBrush.Equals(DefaultGridLineBrush); + } + + public void ResetGridLineColor() + { + if (ShouldSerializeGridLineColor()) { - return Caption.ShouldSerializeBackColor(); - } - - /// - /// - /// Gets - /// or sets the foreground color - /// of the caption area. - /// - /// - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridCaptionForeColorDescr)) - ] - public Color CaptionForeColor { - get { - return Caption.ForeColor; - } - set { - Caption.ForeColor = value; - } + GridLineColor = DefaultGridLineBrush.Color; } - - private void ResetCaptionForeColor() { - Caption.ResetForeColor(); + } + + internal SolidBrush GridLineBrush + { + get + { + return gridLineBrush; } - - /// - /// - /// Gets a value - /// indicating whether the property should be - /// persisted. - /// - /// - protected virtual bool ShouldSerializeCaptionForeColor() + } + + /// + /// + /// Gets or sets the line style of the grid. + /// + /// + [ + SRCategory(nameof(SR.CatAppearance)), + DefaultValue(defaultGridLineStyle), + SRDescription(nameof(SR.DataGridGridLineStyleDescr)) + ] + public DataGridLineStyle GridLineStyle + { + get { - return Caption.ShouldSerializeForeColor(); + return gridLineStyle; } - - /// - /// - /// Gets or sets the font of the grid's caption. - /// - /// - [ - SRCategory(nameof(SR.CatAppearance)), - Localizable(true), - AmbientValue(null), - SRDescription(nameof(SR.DataGridCaptionFontDescr)) - ] - public Font CaptionFont { - get { - return Caption.Font; + set + { + //valid values are 0x0 to 0x1. + if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridLineStyle.None, (int)DataGridLineStyle.Solid)) + { + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridLineStyle)); } - set { - Caption.Font = value; + if (gridLineStyle != value) + { + gridLineStyle = value; + this.myGridTable.ResetRelationsUI(); + Invalidate(layout.Data); } } - - /// - /// - /// Gets a value indicating whether the - /// caption's font is persisted. - /// - /// - private bool ShouldSerializeCaptionFont() { - return Caption.ShouldSerializeFont(); - } - - private void ResetCaptionFont() { - Caption.ResetFont(); + } + + internal int GridLineWidth + { + get + { + Debug.Assert(this.GridLineStyle == DataGridLineStyle.Solid || this.GridLineStyle == DataGridLineStyle.None, "are there any other styles?"); + return GridLineStyle == DataGridLineStyle.Solid ? 1 : 0; } - - /// - /// - /// Gets or sets the text of the grid's caption. - /// - /// - [ - SRCategory(nameof(SR.CatAppearance)), - DefaultValue(""), - Localizable(true), - SRDescription(nameof(SR.DataGridCaptionTextDescr)) - ] - public string CaptionText { - get { - return Caption.Text; - } - set { - Caption.Text = value; - } + } + + /// + /// + /// Gets or + /// sets the + /// way parent row labels are displayed. + /// + /// + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), + DefaultValue(defaultParentRowsLabelStyle), + SRCategory(nameof(SR.CatDisplay)), + SRDescription(nameof(SR.DataGridParentRowsLabelStyleDescr)) + ] + public DataGridParentRowsLabelStyle ParentRowsLabelStyle + { + get + { + return parentRowsLabels; } - - /// - /// - /// Gets or sets a value that indicates - /// whether the grid's caption is visible. - /// - /// - [ - DefaultValue(true), - SRCategory(nameof(SR.CatDisplay)), - SRDescription(nameof(SR.DataGridCaptionVisibleDescr)) - ] - public bool CaptionVisible { - get { - return layout.CaptionVisible; + + set + { + //valid values are 0x0 to 0x3 + if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridParentRowsLabelStyle.None, (int)DataGridParentRowsLabelStyle.Both)) + { + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridParentRowsLabelStyle)); } - set { - if (layout.CaptionVisible != value) { - layout.CaptionVisible = value; - PerformLayout(); - Invalidate(); - OnCaptionVisibleChanged(EventArgs.Empty); - } + + if (parentRowsLabels != value) + { + parentRowsLabels = value; + Invalidate(layout.ParentRows); + OnParentRowsLabelStyleChanged(EventArgs.Empty); } } - - private static readonly object EVENT_CAPTIONVISIBLECHANGED = new object(); - - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnCaptionVisibleChangedDescr))] - public event EventHandler CaptionVisibleChanged { - add => Events.AddHandler(EVENT_CAPTIONVISIBLECHANGED, value); - remove => Events.RemoveHandler(EVENT_CAPTIONVISIBLECHANGED, value); - } - - /// - /// - /// Gets or sets which cell has the focus. Not available at design time. - /// - /// - [ - Browsable(false), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - SRDescription(nameof(SR.DataGridCurrentCellDescr)) - ] - public DataGridCell CurrentCell { - get { - return new DataGridCell(currentRow, currentCol); - } - set { - // if the OnLayout event was not set in the grid, then we can't - // reliably set the currentCell on the grid. - if (layout.dirty) - throw new ArgumentException(SR.DataGridSettingCurrentCellNotGood); - if (value.RowNumber == currentRow && value.ColumnNumber == currentCol) - return; - - // should we throw an exception, maybe? - if (DataGridRowsLength == 0 || this.myGridTable.GridColumnStyles == null || this.myGridTable.GridColumnStyles.Count == 0) - return; - EnsureBound(); - - int currentRowSaved = currentRow; - int currentColSaved = currentCol; - bool wasEditing = gridState[GRIDSTATE_isEditing]; - bool cellChanged = false; - - // if the position in the listManager changed under the DataGrid, - // then do not edit after setting the current cell - bool doNotEdit = false; - - int newCol = value.ColumnNumber; - int newRow = value.RowNumber; - - string errorMessage = null; - - try { - int columnCount = myGridTable.GridColumnStyles.Count; - if (newCol < 0) - newCol = 0; - if (newCol >= columnCount) - newCol = columnCount - 1; - - int localGridRowsLength = DataGridRowsLength; - DataGridRow[] localGridRows = DataGridRows; - - if (newRow < 0) { - newRow = 0; - } - if (newRow >= localGridRowsLength) { - newRow = localGridRowsLength - 1; - } - - // Current Column changing - // - if (currentCol != newCol) { - cellChanged = true; - int currentListManagerPosition = this.ListManager.Position; - int currentListManagerCount = this.ListManager.List.Count; - - EndEdit(); + } - if (this.ListManager.Position != currentListManagerPosition || - currentListManagerCount != this.ListManager.List.Count) { - // EndEdit changed the list. - // Reset the data grid rows and the current row inside the datagrid. - // And then exit the method. - RecreateDataGridRows(); - if (this.ListManager.List.Count > 0) { - this.currentRow = this.ListManager.Position; - Edit(); - } else { - this.currentRow = -1; - } + private static readonly object EVENT_PARENTROWSLABELSTYLECHANGED = new object(); - return; - } - - currentCol = newCol; - InvalidateRow(currentRow); - } - - // Current Row changing - // - if (currentRow != newRow) { - cellChanged = true; - int currentListManagerPosition = this.ListManager.Position; - int currentListManagerCount = this.ListManager.List.Count; + [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnParentRowsLabelStyleChangedDescr))] + public event EventHandler ParentRowsLabelStyleChanged + { + add => Events.AddHandler(EVENT_PARENTROWSLABELSTYLECHANGED, value); + remove => Events.RemoveHandler(EVENT_PARENTROWSLABELSTYLECHANGED, value); + } - EndEdit(); + internal bool Initializing + { + get + { + return inInit; + } + } - if (this.ListManager.Position != currentListManagerPosition || - currentListManagerCount != this.ListManager.List.Count) { - // EndEdit changed the list. - // Reset the data grid rows and the current row inside the datagrid. - // And then exit the method. - RecreateDataGridRows(); - if (this.ListManager.List.Count > 0) { - this.currentRow = this.ListManager.Position; - Edit(); - } else { - this.currentRow = -1; - } + /// + /// + /// Gets the index of the first visible column in a grid. + /// + /// + [ + Browsable(false), + SRDescription(nameof(SR.DataGridFirstVisibleColumnDescr)) + ] + public int FirstVisibleColumn + { + get + { + return firstVisibleCol; + } + } - return; - } + /// + /// + /// Gets or sets a value indicating whether the grid displays in flat mode. + /// + /// + [ + DefaultValue(false), + SRCategory(nameof(SR.CatAppearance)), + SRDescription(nameof(SR.DataGridFlatModeDescr)) + ] + public bool FlatMode + { + get + { + return gridState[GRIDSTATE_isFlatMode]; + } + set + { + if (value != FlatMode) + { + gridState[GRIDSTATE_isFlatMode] = value; + Invalidate(layout.Inside); + OnFlatModeChanged(EventArgs.Empty); + } + } + } - if (currentRow < localGridRowsLength) - localGridRows[currentRow].OnRowLeave(); - localGridRows[newRow].OnRowEnter(); - currentRow = newRow; - if (currentRowSaved < localGridRowsLength) - InvalidateRow(currentRowSaved); - InvalidateRow(currentRow); - - if (currentRowSaved != listManager.Position) { - // not in sync - #if DEBUG - Debug.Assert(inDataSource_PositionChanged, "currentRow and listManager.Position can be out of sync only when the listManager changes its position under the DataGrid or when navigating back"); - Debug.Assert(ListManager.Position == currentRow || listManager.Position == -1, "DataSource_PositionChanged changes the position in the grid to the position in the listManager"); - #endif //DEBUG - doNotEdit = true; - if (gridState[GRIDSTATE_isEditing]) - AbortEdit(); - } else if (gridState[GRIDSTATE_inAddNewRow]) { - #if DEBUG - int currentRowCount = this.DataGridRowsLength; - #endif // debug - // cancelCurrentEdit will change the position in the list - // to the last element in the list. and the grid will get an on position changed - // event, and will set the current cell to the last element in the dataSource. - // so unhook the PositionChanged event from the listManager; - this.ListManager.PositionChanged -= positionChangedHandler; - this.ListManager.CancelCurrentEdit(); - this.ListManager.Position = this.currentRow; - this.ListManager.PositionChanged += positionChangedHandler; - #if DEBUG - - Debug.Assert(currentRowSaved > currentRow, "we can only go up when we are inAddNewRow"); - Debug.Assert(currentRowCount == this.DataGridRowsLength, "the number of rows in the dataGrid should not change"); - Debug.Assert(currentRowCount == this.ListManager.Count + 1, "the listManager should have one less record"); - #endif // debug - localGridRows[DataGridRowsLength - 1] = new DataGridAddNewRow(this, this.myGridTable, DataGridRowsLength-1); - SetDataGridRows(localGridRows, DataGridRowsLength); - gridState[GRIDSTATE_inAddNewRow] = false; - } else { - ListManager.EndCurrentEdit(); - // some special care must be given when setting the - // position in the listManager. - // if EndCurrentEdit() deleted the current row - // ( because of some filtering problem, say ) - // then we cannot go over the last row - // - if (localGridRowsLength != DataGridRowsLength) - { - Debug.Assert(localGridRowsLength == DataGridRowsLength + 1, "this is the only change that could have happened"); - currentRow = (currentRow == localGridRowsLength - 1) ? DataGridRowsLength - 1 : currentRow; - } - - if (currentRow == dataGridRowsLength - 1 && policy.AllowAdd) { - // it may be case ( see previous comment ) - // that listManager.EndCurrentEdit changed the number of rows - // in the grid. in this case, we should not be using the old - // localGridRows in our assertion, cause they are outdated now - // - Debug.Assert(this.DataGridRows[currentRow] is DataGridAddNewRow, "the last row is the DataGridAddNewRow"); - this.AddNewRow(); - Debug.Assert(ListManager.Position == currentRow || listManager.Position == -1, "the listManager should be positioned at the last row"); - } else { - - ListManager.Position = currentRow; - } - } - - } - - } - catch (Exception e) { - errorMessage = e.Message; - } - - if (errorMessage != null) { - DialogResult result = RTLAwareMessageBox.Show(null, - string.Format(SR.DataGridPushedIncorrectValueIntoColumn, errorMessage), - SR.DataGridErrorMessageBoxCaption, MessageBoxButtons.YesNo, - MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); - - if (result == DialogResult.Yes) { - currentRow = currentRowSaved; - currentCol = currentColSaved; - Debug.Assert(currentRow == ListManager.Position || listManager.Position == -1, "the position in the list manager (" + ListManager.Position + ") is out of sync with the currentRow (" + currentRow + ")" + " and the exception is '" + errorMessage + "'"); - // this will make sure the newRow will not paint the - // row selector. - InvalidateRowHeader(newRow); - // also, make sure that we get the row selector on the currentrow, too - InvalidateRowHeader(currentRow); - if (wasEditing) - Edit(); - } else { - // if the user committed a row that used to be addNewRow and the backEnd rejects it, - // and then it tries to navigate down then we should stay in the addNewRow - // in this particular scenario, CancelCurrentEdit will cause the last row to be deleted, - // and this will ultimately call InvalidateRow w/ a row number larger than the number of rows - // so set the currentRow here: - if (currentRow == this.DataGridRowsLength - 1 && currentRowSaved == this.DataGridRowsLength - 2 && DataGridRows[currentRow] is DataGridAddNewRow) - newRow = currentRowSaved; - currentRow = newRow; - Debug.Assert(result == DialogResult.No, "we only put cancel and ok on the error message box"); - this.listManager.PositionChanged -= positionChangedHandler; - this.listManager.CancelCurrentEdit(); - this.listManager.Position = newRow; - this.listManager.PositionChanged += positionChangedHandler; - currentRow = newRow; - currentCol = newCol; - if (wasEditing) - Edit(); - } - } + private static readonly object EVENT_FLATMODECHANGED = new object(); - if (cellChanged) { - EnsureVisible(currentRow, currentCol); - OnCurrentCellChanged(EventArgs.Empty); - - // if the user changed the current cell using the UI, edit the new cell - // but if the user changed the current cell by changing the position in the - // listManager, then do not continue the edit - // - if (!doNotEdit) - { - #if DEBUG - Debug.Assert(!inDataSource_PositionChanged, "if the user changed the current cell using the UI, then do not edit"); - #endif // debug - Edit(); - } + [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnFlatModeChangedDescr))] + public event EventHandler FlatModeChanged + { + add => Events.AddHandler(EVENT_FLATMODECHANGED, value); + remove => Events.RemoveHandler(EVENT_FLATMODECHANGED, value); + } + /// + /// + /// Gets or + /// sets the background color of all row and column headers. + /// + /// + [ + SRCategory(nameof(SR.CatColors)), + SRDescription(nameof(SR.DataGridHeaderBackColorDescr)) + ] + public Color HeaderBackColor + { + get + { + return headerBackBrush.Color; + } + set + { + if (value.IsEmpty) + throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "HeaderBackColor")); + if (IsTransparentColor(value)) + throw new ArgumentException(SR.DataGridTransparentHeaderBackColorNotAllowed); + if (!value.Equals(headerBackBrush.Color)) + { + headerBackBrush = new SolidBrush(value); - AccessibilityNotifyClients(AccessibleEvents.Focus, CurrentCellAccIndex); - AccessibilityNotifyClients(AccessibleEvents.Selection, CurrentCellAccIndex); - } - - Debug.Assert(currentRow == ListManager.Position || listManager.Position == -1, "the position in the list manager is out of sync with the currentRow"); + if (layout.RowHeadersVisible) + Invalidate(layout.RowHeaders); + if (layout.ColumnHeadersVisible) + Invalidate(layout.ColumnHeaders); + Invalidate(layout.TopLeftHeader); } } + } - internal int CurrentCellAccIndex { - get { - int currentCellAccIndex = 0; - currentCellAccIndex ++; // ParentRowsAccessibleObject - currentCellAccIndex += this.myGridTable.GridColumnStyles.Count; // ColumnHeaderAccessibleObject - currentCellAccIndex += this.DataGridRows.Length; // DataGridRowAccessibleObject - if (this.horizScrollBar.Visible) // Horizontal Scroll Bar Accessible Object - currentCellAccIndex ++; - if (this.vertScrollBar.Visible) // Vertical Scroll Bar Accessible Object - currentCellAccIndex ++; - currentCellAccIndex += (this.currentRow * this.myGridTable.GridColumnStyles.Count) + this.currentCol; - return currentCellAccIndex; - } + internal SolidBrush HeaderBackBrush + { + get + { + return headerBackBrush; } - - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnCurrentCellChangedDescr))] - public event EventHandler CurrentCellChanged { - add => Events.AddHandler(EVENT_CURRENTCELLCHANGED, value); - remove => Events.RemoveHandler(EVENT_CURRENTCELLCHANGED, value); + } + + protected virtual bool ShouldSerializeHeaderBackColor() + { + return !HeaderBackBrush.Equals(DefaultHeaderBackBrush); + } + + public void ResetHeaderBackColor() + { + if (ShouldSerializeHeaderBackColor()) + { + HeaderBackColor = DefaultHeaderBackBrush.Color; } - - private int CurrentColumn { - get { - return CurrentCell.ColumnNumber; - } - set { - this.CurrentCell = new DataGridCell(currentRow, value); - } + } + internal SolidBrush BackgroundBrush + { + get + { + return backgroundBrush; } - - private int CurrentRow { - get { - return CurrentCell.RowNumber; - } - set { - CurrentCell = new DataGridCell(value, currentCol); - } + } + + private void ResetBackgroundColor() + { + if (backgroundBrush != null && BackgroundBrush != DefaultBackgroundBrush) + { + backgroundBrush.Dispose(); + backgroundBrush = null; } - - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridSelectionBackColorDescr)) - ] - public Color SelectionBackColor { - get { - return selectionBackBrush.Color; - } - set { - if (value.IsEmpty) - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "SelectionBackColor")); - if (IsTransparentColor(value)) - throw new ArgumentException(SR.DataGridTransparentSelectionBackColorNotAllowed); - if (!value.Equals(selectionBackBrush.Color)) { - selectionBackBrush = new SolidBrush(value); - - InvalidateInside(); + backgroundBrush = DefaultBackgroundBrush; + } + + protected virtual bool ShouldSerializeBackgroundColor() + { + return !BackgroundBrush.Equals(DefaultBackgroundBrush); + } + + + // using this property, the user can set the backGround color + /// + /// Gets or sets the background color of the grid. + /// + [ + SRCategory(nameof(SR.CatColors)), + SRDescription(nameof(SR.DataGridBackgroundColorDescr)) + ] + public Color BackgroundColor + { + get + { + return backgroundBrush.Color; + } + set + { + if (value.IsEmpty) + throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "BackgroundColor")); + if (!value.Equals(backgroundBrush.Color)) + { + + if (backgroundBrush != null && BackgroundBrush != DefaultBackgroundBrush) + { + backgroundBrush.Dispose(); + backgroundBrush = null; } + backgroundBrush = new SolidBrush(value); + + Invalidate(layout.Inside); + OnBackgroundColorChanged(EventArgs.Empty); } } - - internal SolidBrush SelectionBackBrush { - get { - return this.selectionBackBrush; - } + } + + private static readonly object EVENT_BACKGROUNDCOLORCHANGED = new object(); + + [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnBackgroundColorChangedDescr))] + public event EventHandler BackgroundColorChanged + { + add => Events.AddHandler(EVENT_BACKGROUNDCOLORCHANGED, value); + remove => Events.RemoveHandler(EVENT_BACKGROUNDCOLORCHANGED, value); + } + + /// + /// + /// Indicates whether the property should be persisted. + /// + /// + [ + SRCategory(nameof(SR.CatAppearance)), + SRDescription(nameof(SR.DataGridHeaderFontDescr)) + ] + public Font HeaderFont + { + get + { + return (headerFont == null ? this.Font : headerFont); } - - internal SolidBrush SelectionForeBrush { - get { - return this.selectionForeBrush; + set + { + if (value == null) + throw new ArgumentNullException(nameof(HeaderFont)); + if (!value.Equals(headerFont)) + { + headerFont = value; + RecalculateFonts(); + PerformLayout(); + Invalidate(layout.Inside); } } - - protected bool ShouldSerializeSelectionBackColor() + } + + protected bool ShouldSerializeHeaderFont() + { + return (headerFont != null); + } + + public void ResetHeaderFont() + { + if (headerFont != null) { - return !DefaultSelectionBackBrush.Equals(selectionBackBrush); + headerFont = null; + RecalculateFonts(); + PerformLayout(); + Invalidate(layout.Inside); } - - public void ResetSelectionBackColor() { - if (ShouldSerializeSelectionBackColor()) - SelectionBackColor = DefaultSelectionBackBrush.Color; + } + + /// + /// + /// Resets the property to its default value. + /// + /// + /// + /// + /// Gets or sets the foreground color of the grid's headers. + /// + /// + [ + SRCategory(nameof(SR.CatColors)), + SRDescription(nameof(SR.DataGridHeaderForeColorDescr)) + ] + public Color HeaderForeColor + { + get + { + return headerForePen.Color; } - - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridSelectionForeColorDescr)) - ] - public Color SelectionForeColor { - get { - return selectionForeBrush.Color; - } - set { - if (value.IsEmpty) - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "SelectionForeColor")); - if (!value.Equals(selectionForeBrush.Color)) { - selectionForeBrush = new SolidBrush(value); - - InvalidateInside(); - } + set + { + if (value.IsEmpty) + throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "HeaderForeColor")); + if (!value.Equals(headerForePen.Color)) + { + headerForePen = new Pen(value); + headerForeBrush = new SolidBrush(value); + + if (layout.RowHeadersVisible) + Invalidate(layout.RowHeaders); + if (layout.ColumnHeadersVisible) + Invalidate(layout.ColumnHeaders); + Invalidate(layout.TopLeftHeader); } } - - protected virtual bool ShouldSerializeSelectionForeColor() + } + + protected virtual bool ShouldSerializeHeaderForeColor() + { + return !HeaderForePen.Equals(DefaultHeaderForePen); + } + + public void ResetHeaderForeColor() + { + if (ShouldSerializeHeaderForeColor()) { - return !SelectionForeBrush.Equals(DefaultSelectionForeBrush); + HeaderForeColor = DefaultHeaderForeBrush.Color; } - - public void ResetSelectionForeColor() { - if (ShouldSerializeSelectionForeColor()) - SelectionForeColor = DefaultSelectionForeBrush.Color; + } + + internal SolidBrush HeaderForeBrush + { + get + { + return this.headerForeBrush; } - - internal override bool ShouldSerializeForeColor() + } + + internal Pen HeaderForePen + { + get { - return !DefaultForeBrush.Color.Equals(this.ForeColor); + return headerForePen; } - - /// - /// Indicates whether the property should be - /// persisted. - /// - internal override bool ShouldSerializeBackColor() + } + private void ResetHorizontalOffset() + { + horizontalOffset = 0; + negOffset = 0; + firstVisibleCol = 0; + numVisibleCols = 0; + lastTotallyVisibleCol = -1; + } + + internal int HorizontalOffset + { + get { - return !DefaultBackBrush.Color.Equals(this.BackColor); + return horizontalOffset; } - - // Don't use dataGridRows, use the accessor!!! - internal DataGridRow[] DataGridRows { - get { - if (dataGridRows == null) - CreateDataGridRows(); - return dataGridRows; + set + { + //if (CompModSwitches.DataGridScrolling.TraceVerbose) Debug.WriteLine("DataGridScrolling: Set_HorizontalOffset, value = " + value.ToString()); + if (value < 0) + value = 0; + + // + // if the dataGrid is not bound ( listManager == null || gridTable == null) + // then use ResetHorizontalOffset(); + // + + int totalWidth = GetColumnWidthSum(); + int widthNotVisible = totalWidth - layout.Data.Width; + if (value > widthNotVisible && widthNotVisible > 0) + value = widthNotVisible; + + if (value == horizontalOffset) + return; + + int change = horizontalOffset - value; + horizScrollBar.Value = value; + Rectangle scroll = layout.Data; + if (layout.ColumnHeadersVisible) + scroll = Rectangle.Union(scroll, layout.ColumnHeaders); + horizontalOffset = value; + + this.firstVisibleCol = ComputeFirstVisibleColumn(); + // update the lastTotallyVisibleCol + ComputeVisibleColumns(); + + if (gridState[GRIDSTATE_isScrolling]) + { + // if the user did not click on the grid yet, then do not put the edit + // control when scrolling + if (currentCol >= firstVisibleCol && currentCol < firstVisibleCol + numVisibleCols - 1 && (gridState[GRIDSTATE_isEditing] || gridState[GRIDSTATE_isNavigating])) + Edit(); + else + EndEdit(); + + // isScrolling is set to TRUE when the user scrolls. + // once we move the edit box, we finished processing the scroll event, so set isScrolling to FALSE + // to set isScrolling to TRUE, we need another scroll event. + gridState[GRIDSTATE_isScrolling] = false; } - } - - // ToolTipping - internal DataGridToolTip ToolTipProvider { - get { - return toolTipProvider; + else + { + EndEdit(); } + + NativeMethods.RECT[] rects = CreateScrollableRegion(scroll); + ScrollRectangles(rects, change); + OnScroll(EventArgs.Empty); } - - internal int ToolTipId { - get { - return toolTipId; - } - set { - toolTipId = value; + } + + private void ScrollRectangles(NativeMethods.RECT[] rects, int change) + { + if (rects != null) + { + NativeMethods.RECT scroll; + if (isRightToLeft()) + change = -change; + for (int r = 0; r < rects.Length; r++) + { + scroll = rects[r]; + SafeNativeMethods.ScrollWindow(new HandleRef(this, Handle), + change, + 0, + ref scroll, + ref scroll); } } - - private void ResetToolTip() + } + + /// + /// + [ + SRDescription(nameof(SR.DataGridHorizScrollBarDescr)) + ] + protected ScrollBar HorizScrollBar + { + get { - // remove all the tool tips which are stored - for (int i = 0; i < ToolTipId; i ++) { - ToolTipProvider.RemoveToolTip(new IntPtr(i)); - } + return horizScrollBar; + } + } - // add toolTips for the backButton and - // details button on the caption. - if (!this.parentRows.IsEmpty()) { - bool alignRight = this.isRightToLeft(); - int detailsButtonWidth = this.Caption.GetDetailsButtonWidth(); - Rectangle backButton = this.Caption.GetBackButtonRect(this.layout.Caption, alignRight, detailsButtonWidth); - Rectangle detailsButton = this.Caption.GetDetailsButtonRect(this.layout.Caption, alignRight); - - // mirror the buttons wrt RTL property - backButton.X = MirrorRectangle(backButton, layout.Inside, isRightToLeft()); - detailsButton.X = MirrorRectangle(detailsButton, layout.Inside, isRightToLeft()); - - ToolTipProvider.AddToolTip(SR.DataGridCaptionBackButtonToolTip, new IntPtr(0), backButton); - ToolTipProvider.AddToolTip(SR.DataGridCaptionDetailsButtonToolTip, new IntPtr(1), detailsButton); - ToolTipId = 2; - } else { - ToolTipId = 0; - } + /// + /// + /// Retrieves a value indicating whether odd and even + /// rows are painted using a different background color. + /// + /// + // Cleanup eventually to be static. + internal bool LedgerStyle + { + get + { + return gridState[GRIDSTATE_isLedgerStyle]; } - - - - /// - /// Given a cursor, this will Create the right DataGridRows - /// - private void CreateDataGridRows() { - CurrencyManager listManager = ListManager; - DataGridTableStyle dgt = this.myGridTable; - InitializeColumnWidths(); - - if (listManager == null) { - SetDataGridRows(new DataGridRow[0], 0); - return; - } - - int nDataGridRows = listManager.Count; - if (policy.AllowAdd) - nDataGridRows++; - - DataGridRow[] rows = new DataGridRow[nDataGridRows]; - for (int r = 0; r < listManager.Count; r++) { - rows[r] = new DataGridRelationshipRow(this, dgt,r); - } - - if (policy.AllowAdd) { - this.addNewRow = new DataGridAddNewRow(this, dgt, nDataGridRows - 1); - rows[nDataGridRows - 1] = addNewRow; - } - else { - addNewRow = null; + /* + set { + if (isLedgerStyle != value) { + isLedgerStyle = value; + InvalidateInside(); } - // SetDataGridRows(rows, rows.Length); - SetDataGridRows(rows, nDataGridRows); } - - private void RecreateDataGridRows() { - int nDataGridRows = 0; - CurrencyManager listManager = ListManager; - - if (listManager != null) { - nDataGridRows = listManager.Count; - if (policy.AllowAdd) { - nDataGridRows++; - } - } - SetDataGridRows(null, nDataGridRows); + */ + } + + /// + /// + /// Indicates whether the property should be persisted. + /// + /// + [ + SRCategory(nameof(SR.CatColors)), + SRDescription(nameof(SR.DataGridLinkColorDescr)) + ] + public Color LinkColor + { + get + { + return linkBrush.Color; } - - /// - /// Sets the array of DataGridRow objects used for - /// all row-related logic in the DataGrid. - /// - internal void SetDataGridRows(DataGridRow[] newRows, int newRowsLength) { - dataGridRows = newRows; - dataGridRowsLength = newRowsLength; - - // update the vertical scroll bar - vertScrollBar.Maximum = Math.Max(0, DataGridRowsLength - 1); - if (firstVisibleRow > newRowsLength) { - vertScrollBar.Value = 0; - firstVisibleRow = 0; - } - - ResetUIState(); - #if DEBUG - // sanity check: all the rows should have the same - // dataGridTable - if (newRows != null && newRowsLength > 0) { - DataGridTableStyle dgTable = newRows[0].DataGridTableStyle; - for (int i = 0; i < newRowsLength; i ++) { - Debug.Assert(dgTable == newRows[i].DataGridTableStyle, "how can two rows have different tableStyles?"); - - } + set + { + if (value.IsEmpty) + throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "LinkColor")); + if (!linkBrush.Color.Equals(value)) + { + linkBrush = new SolidBrush(value); + Invalidate(layout.Data); } - #endif // DEBUG - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: There are now " + DataGridRowsLength.ToString(CultureInfo.InvariantCulture) + " rows."); } - - internal int DataGridRowsLength { - get { - return dataGridRowsLength; - } + } + + internal virtual bool ShouldSerializeLinkColor() + { + return !LinkBrush.Equals(DefaultLinkBrush); + } + + public void ResetLinkColor() + { + if (ShouldSerializeLinkColor()) + LinkColor = DefaultLinkBrush.Color; + } + + internal Brush LinkBrush + { + get + { + return linkBrush; } - - /// - /// Gets or sets the data source that the grid is displaying data for. - /// - [ - DefaultValue(null), - SRCategory(nameof(SR.CatData)), - RefreshProperties(RefreshProperties.Repaint), - AttributeProvider(typeof(IListSource)), - SRDescription(nameof(SR.DataGridDataSourceDescr)) - ] - public object DataSource { - get { - return dataSource; - } - - set { - if (value != null && !(value is IList || value is IListSource)) - throw new ArgumentException(SR.BadDataSourceForComplexBinding); - if (dataSource != null && dataSource.Equals(value)) - { - return; - } - - // when the designer resets the dataSource to null, set the dataMember to null, too - if ((value == null || value == Convert.DBNull) && this.DataMember != null && this.DataMember.Length != 0 ) { - this.dataSource = null; - this.DataMember = string.Empty; - return; - } - - // if we are setting the dataSource and the dataMember is not a part - // of the properties in the dataSource, then set the dataMember to "" - // - if (value != null) - EnforceValidDataMember(value); - - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: DataSource being set to " + ((value == null) ? "null" : value.ToString())); - - // when we change the dataSource, we need to clear the parent rows. - // the same goes for all the caption UI: reset it when the datasource changes. - // - ResetParentRows(); - Set_ListManager(value, this.DataMember, false); - } + } + + /// + /// + /// Gets + /// or sets the color a link changes to when + /// the mouse pointer moves over it. + /// + /// + [ + SRDescription(nameof(SR.DataGridLinkHoverColorDescr)), + SRCategory(nameof(SR.CatColors)), + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never) + + ] + public Color LinkHoverColor + { + get + { + return this.LinkColor; + } + set + { + } + } + + protected virtual bool ShouldSerializeLinkHoverColor() + { + return false; + // return !LinkHoverBrush.Equals(defaultLinkHoverBrush); + } + + public void ResetLinkHoverColor() + { + /* + if (ShouldSerializeLinkHoverColor()) + LinkHoverColor = defaultLinkHoverBrush.Color;*/ + } + + /// + /// + /// Indicates whether the property should be + /// persisted. + /// + /// + + internal Font LinkFont + { + get + { + return linkFont; + } + } + + internal int LinkFontHeight + { + get + { + return linkFontHeight; } + } - private static readonly object EVENT_DATASOURCECHANGED = new object(); - - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnDataSourceChangedDescr))] - public event EventHandler DataSourceChanged { - add => Events.AddHandler(EVENT_DATASOURCECHANGED, value); - remove => Events.RemoveHandler(EVENT_DATASOURCECHANGED, value); + /// + /// Gets or sets a value + /// that specifies which links are shown and in what context. + /// + [ + DefaultValue(true), + SRDescription(nameof(SR.DataGridNavigationModeDescr)), + SRCategory(nameof(SR.CatBehavior)) + ] + public bool AllowNavigation + { + get + { + return gridState[GRIDSTATE_allowNavigation]; } - - /// - /// - /// Gets or sets the specific table in a DataSource for the control. - /// - /// - [ - DefaultValue(null), - SRCategory(nameof(SR.CatData)), - Editor("System.Windows.Forms.Design.DataMemberListEditor, " + AssemblyRef.SystemDesign, typeof(System.Drawing.Design.UITypeEditor)), - SRDescription(nameof(SR.DataGridDataMemberDescr)) - ] - public string DataMember { - get { - return dataMember; - } - set { - if (dataMember != null && dataMember.Equals(value)) - return; - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: DataSource being set to " + ((value == null) ? "null" : value.ToString())); - // when we change the dataMember, we need to clear the parent rows. - // the same goes for all the caption UI: reset it when the datamember changes. - // - ResetParentRows(); - Set_ListManager(this.DataSource, value, false); + set + { + if (AllowNavigation != value) + { + gridState[GRIDSTATE_allowNavigation] = value; + // let the Caption know about this: + this.Caption.BackButtonActive = !parentRows.IsEmpty() && (value); + this.Caption.BackButtonVisible = this.Caption.BackButtonActive; + RecreateDataGridRows(); + + OnAllowNavigationChanged(EventArgs.Empty); } } - - public void SetDataBinding(object dataSource, string dataMember) { - parentRows.Clear(); - originalState = null; - caption.BackButtonActive = caption.DownButtonActive = caption.BackButtonVisible = false; - caption.SetDownButtonDirection(!layout.ParentRowsVisible); - - Set_ListManager(dataSource, dataMember, false); + } + + private static readonly object EVENT_ALLOWNAVIGATIONCHANGED = new object(); + + [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnNavigationModeChangedDescr))] + public event EventHandler AllowNavigationChanged + { + add => Events.AddHandler(EVENT_ALLOWNAVIGATIONCHANGED, value); + remove => Events.RemoveHandler(EVENT_ALLOWNAVIGATIONCHANGED, value); + } + + [ + Browsable(false), EditorBrowsable(EditorBrowsableState.Never) + ] + public override Cursor Cursor + { + // get the cursor out of the propertyGrid. + get + { + return base.Cursor; } - - [ - Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), - SRDescription(nameof(SR.DataGridListManagerDescr)) - ] - internal protected CurrencyManager ListManager { - get { - //try to return something useful: - if (listManager == null && this.BindingContext != null && this.DataSource != null) - return (CurrencyManager) this.BindingContext[this.DataSource, this.DataMember]; - else - return listManager; - } - set { - throw new NotSupportedException(SR.DataGridSetListManager); - } + + set + { + base.Cursor = value; } - - internal void Set_ListManager(object newDataSource, string newDataMember, bool force) { - Set_ListManager(newDataSource, newDataMember, force, true); // true for forcing column creation + } + + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + new public event EventHandler CursorChanged + { + add => base.CursorChanged += value; + remove => base.CursorChanged -= value; + } + + [ + Browsable(false), EditorBrowsable(EditorBrowsableState.Never) + ] + public override Image BackgroundImage + { + // get the BackgroundImage out of the propertyGrid. + get + { + return base.BackgroundImage; } - - // - // prerequisite: the dataMember and the dataSource should be set to the new values - // - // will do the following: - // call EndEdit on the current listManager, will unWire the listManager events, will set the listManager to the new - // reality, will wire the new listManager, will update the policy, will set the dataGridTable, will reset the ui state. - // - internal void Set_ListManager(object newDataSource, string newDataMember, bool force, bool forceColumnCreation) + + set { - bool dataSourceChanged = this.DataSource != newDataSource; - bool dataMemberChanged = this.DataMember != newDataMember; - - // if nothing happened, then why do any work? - if (!force && !dataSourceChanged && !dataMemberChanged && gridState[GRIDSTATE_inSetListManager]) - return; - - gridState[GRIDSTATE_inSetListManager] = true; - if (this.toBeDisposedEditingControl != null) { - Debug.Assert(this.Controls.Contains(this.toBeDisposedEditingControl)); - this.Controls.Remove(this.toBeDisposedEditingControl); - this.toBeDisposedEditingControl = null; - } - bool beginUpdateInternal = true; - try { - // will endEdit on the current listManager - UpdateListManager(); - - // unwire the events: - if (this.listManager != null) - UnWireDataSource(); - - CurrencyManager oldListManager = listManager; - bool listManagerChanged = false; - // set up the new listManager - // CAUTION: we need to set up the listManager in the grid before setting the dataSource/dataMember props - // in the grid. the reason is that if the BindingContext was not yet requested, and it is created in the BindingContext prop - // then the grid will call Set_ListManager again, and eventually that means that the dataGrid::listManager will - // be hooked up twice to all the events (PositionChanged, ItemChanged, CurrentChanged) - if (newDataSource != null && this.BindingContext != null && !(newDataSource == Convert.DBNull)) - this.listManager = (CurrencyManager) this.BindingContext[newDataSource, newDataMember]; - else - listManager = null; - - // update the dataSource and the dateMember - this.dataSource = newDataSource; - this.dataMember = newDataMember == null ? "" : newDataMember; - - listManagerChanged = (listManager != oldListManager); - - // wire the events - if (listManager != null) { - WireDataSource(); - // update the policy - policy.UpdatePolicy(this.listManager, this.ReadOnly); - } - - if (!Initializing) - { - if (listManager == null) - { - if (this.ContainsFocus && this.ParentInternal == null) { - Debug.Assert(this.toBeDisposedEditingControl == null, "we should have removed the toBeDisposedEditingControl already"); - // if we unparent the active control then the form won't close - for (int i = 0; i < this.Controls.Count; i++) { - if (this.Controls[i].Focused) { - this.toBeDisposedEditingControl = this.Controls[i]; - break; - } - } + base.BackgroundImage = value; + } + } - if (this.toBeDisposedEditingControl == this.horizScrollBar || this.toBeDisposedEditingControl == this.vertScrollBar) { - this.toBeDisposedEditingControl = null; - } + [ + Browsable(false), EditorBrowsable(EditorBrowsableState.Never) + ] + public override ImageLayout BackgroundImageLayout + { + // get the BackgroundImage out of the propertyGrid. + get + { + return base.BackgroundImageLayout; + } - #if DEBUG - else { - Debug.Assert(this.toBeDisposedEditingControl != null, "if the grid contains the focus, then the active control should be in the children of data grid control"); - Debug.Assert(this.editColumn != null, "if we have an editing control should be a control in the data grid column"); - if (this.editColumn is DataGridTextBoxColumn) { - Debug.Assert(((DataGridTextBoxColumn) this.editColumn).TextBox == this.toBeDisposedEditingControl, "if we have an editing control should be a control in the data grid column"); - } - } - #endif // debug; + set + { + base.BackgroundImageLayout = value; + } + } - } - SetDataGridRows(null, 0); - this.defaultTableStyle.GridColumnStyles.Clear(); - SetDataGridTable(this.defaultTableStyle, forceColumnCreation); - if (this.toBeDisposedEditingControl != null) { - this.Controls.Add(this.toBeDisposedEditingControl); - } - } - } - - // PERF: if the listManager did not change, then do not: - // 1. create new rows - // 2. create new columns - // 3. compute the errors in the list - // - // when the metaDataChanges, we need to recreate - // the rows and the columns - // - if (listManagerChanged || gridState[GRIDSTATE_metaDataChanged]) { - if (this.Visible) BeginUpdateInternal(); - - if (listManager != null) - { - // get rid of the old gridColumns - // we need to clear the old column collection even when navigating to - // a list that has a table style associated w/ it. Why? because the - // old column collection will be used by the parent rows to paint - this.defaultTableStyle.GridColumnStyles.ResetDefaultColumnCollection(); - - DataGridTableStyle newGridTable = this.dataGridTables[listManager.GetListName()]; - if (newGridTable == null) { - SetDataGridTable(this.defaultTableStyle, forceColumnCreation); - } else { - SetDataGridTable(newGridTable, forceColumnCreation); - } - - // set the currentRow in ssync w/ the position in the listManager - currentRow = listManager.Position == -1 ? 0 : listManager.Position; - } - - // when we create the rows we need to use the current dataGridTable - // - RecreateDataGridRows(); - if (this.Visible) EndUpdateInternal(); - beginUpdateInternal = false; - - ComputeMinimumRowHeaderWidth(); - if (this.myGridTable.IsDefault) - this.RowHeaderWidth = Math.Max(this.minRowHeaderWidth, this.RowHeaderWidth); - else - this.myGridTable.RowHeaderWidth = Math.Max(this.minRowHeaderWidth, this.RowHeaderWidth); - - ListHasErrors = DataGridSourceHasErrors(); - - // build the list of columns and relationships - // wipe out the now invalid states - //ResetMouseState(); - - ResetUIState(); - - //layout.CaptionVisible = dataCursor == null ? false : true; - - OnDataSourceChanged(EventArgs.Empty); - } - - } finally { - gridState[GRIDSTATE_inSetListManager] = false; - // start painting again - if (beginUpdateInternal && this.Visible) EndUpdateInternal(); - } - } - - /// - /// Gets or sets index of the selected row. - /// - // will set the position in the ListManager - // - [ - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false), - SRDescription(nameof(SR.DataGridSelectedIndexDescr)) - ] - public int CurrentRowIndex { - get { - if (originalState == null) - return this.listManager == null ? - 1 : this.listManager.Position; - else { - if (this.BindingContext == null) - return -1; - CurrencyManager originalListManager = (CurrencyManager) this.BindingContext[originalState.DataSource, originalState.DataMember]; - return originalListManager.Position; - } - } - set { - if (this.listManager == null) - throw new InvalidOperationException(SR.DataGridSetSelectIndex); - - if (originalState == null) { - this.listManager.Position = value; - currentRow = value; - return; - } - - // if we have a this.ListManager, then this.BindingManager cannot be null - // - CurrencyManager originalListManager = (CurrencyManager) this.BindingContext[originalState.DataSource, originalState.DataMember]; - originalListManager.Position = value; - - // this is for parent rows - originalState.LinkingRow = originalState.DataGridRows[value]; - - // Invalidate everything - Invalidate(); - } + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + new public event EventHandler BackgroundImageChanged + { + add => base.BackgroundImageChanged += value; + remove => base.BackgroundImageChanged -= value; + } + + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + new public event EventHandler BackgroundImageLayoutChanged + { + add => base.BackgroundImageLayoutChanged += value; + remove => base.BackgroundImageLayoutChanged -= value; + } + + /// + /// + /// Gets or sets the background color of parent rows. + /// + /// + [ + SRCategory(nameof(SR.CatColors)), + SRDescription(nameof(SR.DataGridParentRowsBackColorDescr)) + ] + public Color ParentRowsBackColor + { + get + { + return parentRows.BackColor; } - - - /// - /// Gets the collection of tables for the grid. - /// - [ - SRCategory(nameof(SR.CatData)), - DesignerSerializationVisibility(DesignerSerializationVisibility.Content), - Localizable(true), - SRDescription(nameof(SR.DataGridGridTablesDescr)) - ] - public GridTableStylesCollection TableStyles { - get { - return dataGridTables; - } + set + { + if (IsTransparentColor(value)) + throw new ArgumentException(SR.DataGridTransparentParentRowsBackColorNotAllowed); + this.parentRows.BackColor = value; } - - internal new int FontHeight { - get { - return fontHeight; - } + } + + internal SolidBrush ParentRowsBackBrush + { + get + { + return parentRows.BackBrush; } - - internal AccessibleObject ParentRowsAccessibleObject { - get { - return parentRows.AccessibleObject; - } + } + + /// + /// + /// Indicates whether the property should be + /// persisted. + /// + /// + protected virtual bool ShouldSerializeParentRowsBackColor() + { + return !ParentRowsBackBrush.Equals(DefaultParentRowsBackBrush); + } + + private void ResetParentRowsBackColor() + { + if (ShouldSerializeParentRowsBackColor()) + parentRows.BackBrush = DefaultParentRowsBackBrush; + } + + /// + /// + /// Gets or sets the foreground color of parent rows. + /// + /// + [ + SRCategory(nameof(SR.CatColors)), + SRDescription(nameof(SR.DataGridParentRowsForeColorDescr)) + ] + public Color ParentRowsForeColor + { + get + { + return parentRows.ForeColor; } - - internal Rectangle ParentRowsBounds { - get { - return layout.ParentRows; - } + set + { + this.parentRows.ForeColor = value; } - - /// - /// Gets or sets the color of the grid lines. - /// - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridGridLineColorDescr)) - ] - public Color GridLineColor { - get { - return gridLineBrush.Color; - } - set { - if (gridLineBrush.Color != value) { - if (value.IsEmpty) - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "GridLineColor")); - gridLineBrush = new SolidBrush(value); - - Invalidate(layout.Data); - } - } + } + + internal SolidBrush ParentRowsForeBrush + { + get + { + return parentRows.ForeBrush; } - - protected virtual bool ShouldSerializeGridLineColor() + } + + /// + /// + /// Indicates whether the property should be + /// persisted. + /// + /// + protected virtual bool ShouldSerializeParentRowsForeColor() + { + return !ParentRowsForeBrush.Equals(DefaultParentRowsForeBrush); + } + + private void ResetParentRowsForeColor() + { + if (ShouldSerializeParentRowsForeColor()) + parentRows.ForeBrush = DefaultParentRowsForeBrush; + } + + + /// + /// + /// Gets + /// or sets the default width of the grid columns in + /// pixels. + /// + /// + [ + DefaultValue(defaultPreferredColumnWidth), + SRCategory(nameof(SR.CatLayout)), + SRDescription(nameof(SR.DataGridPreferredColumnWidthDescr)), + TypeConverter(typeof(DataGridPreferredColumnWidthTypeConverter)) + ] + public int PreferredColumnWidth + { + get { - return !GridLineBrush.Equals(DefaultGridLineBrush); + return preferredColumnWidth; } - - public void ResetGridLineColor() { - if (ShouldSerializeGridLineColor()) { - GridLineColor = DefaultGridLineBrush.Color; + set + { + if (value < 0) + throw new ArgumentException(SR.DataGridColumnWidth, "PreferredColumnWidth"); + if (preferredColumnWidth != value) + { + preferredColumnWidth = value; } } - - internal SolidBrush GridLineBrush { - get { - return gridLineBrush; - } + } + + /// + /// + /// Gets or sets the preferred row height for the control. + /// + /// + [ + SRCategory(nameof(SR.CatLayout)), + SRDescription(nameof(SR.DataGridPreferredRowHeightDescr)) + ] + public int PreferredRowHeight + { + get + { + return prefferedRowHeight; } - - /// - /// - /// Gets or sets the line style of the grid. - /// - /// - [ - SRCategory(nameof(SR.CatAppearance)), - DefaultValue(defaultGridLineStyle), - SRDescription(nameof(SR.DataGridGridLineStyleDescr)) - ] - public DataGridLineStyle GridLineStyle { - get { - return gridLineStyle; - } - set { - //valid values are 0x0 to 0x1. - if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridLineStyle.None, (int)DataGridLineStyle.Solid)) - { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridLineStyle)); - } - if (gridLineStyle != value) { - gridLineStyle = value; - this.myGridTable.ResetRelationsUI(); - Invalidate(layout.Data); - } - } + set + { + if (value < 0) + throw new ArgumentException(SR.DataGridRowRowHeight); + prefferedRowHeight = value; } - - internal int GridLineWidth { - get { - Debug.Assert(this.GridLineStyle == DataGridLineStyle.Solid || this.GridLineStyle == DataGridLineStyle.None, "are there any other styles?"); - return GridLineStyle == DataGridLineStyle.Solid ? 1 : 0; - } + } + + private void ResetPreferredRowHeight() + { + prefferedRowHeight = defaultFontHeight + 3; + } + + protected bool ShouldSerializePreferredRowHeight() + { + return prefferedRowHeight != defaultFontHeight + 3; + } + + /// + /// Gets or sets a value indicating whether the grid + /// is in read-only mode. + /// + [ + DefaultValue(false), + SRCategory(nameof(SR.CatBehavior)), + SRDescription(nameof(SR.DataGridReadOnlyDescr)) + ] + public bool ReadOnly + { + get + { + return gridState[GRIDSTATE_readOnlyMode]; } - - /// - /// - /// Gets or - /// sets the - /// way parent row labels are displayed. - /// - /// - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - DefaultValue(defaultParentRowsLabelStyle), - SRCategory(nameof(SR.CatDisplay)), - SRDescription(nameof(SR.DataGridParentRowsLabelStyleDescr)) - ] - public DataGridParentRowsLabelStyle ParentRowsLabelStyle { - get { - return parentRowsLabels; - } - - set { - //valid values are 0x0 to 0x3 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridParentRowsLabelStyle.None, (int)DataGridParentRowsLabelStyle.Both)) + set + { + if (ReadOnly != value) + { + bool recreateRows = false; + if (value) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridParentRowsLabelStyle)); + // AllowAdd happens to have the same boolean value as whether we need to recreate rows. + recreateRows = policy.AllowAdd; + + policy.AllowRemove = false; + policy.AllowEdit = false; + policy.AllowAdd = false; } - - if (parentRowsLabels != value) + else { - parentRowsLabels = value; - Invalidate(layout.ParentRows); - OnParentRowsLabelStyleChanged(EventArgs.Empty); - } - } - } - - private static readonly object EVENT_PARENTROWSLABELSTYLECHANGED = new object(); - - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnParentRowsLabelStyleChangedDescr))] - public event EventHandler ParentRowsLabelStyleChanged { - add => Events.AddHandler(EVENT_PARENTROWSLABELSTYLECHANGED, value); - remove => Events.RemoveHandler(EVENT_PARENTROWSLABELSTYLECHANGED, value); - } - - internal bool Initializing { - get { - return inInit; - } - } - - /// - /// - /// Gets the index of the first visible column in a grid. - /// - /// - [ - Browsable(false), - SRDescription(nameof(SR.DataGridFirstVisibleColumnDescr)) - ] - public int FirstVisibleColumn { - get { - return firstVisibleCol; - } - } - - /// - /// - /// Gets or sets a value indicating whether the grid displays in flat mode. - /// - /// - [ - DefaultValue(false), - SRCategory(nameof(SR.CatAppearance)), - SRDescription(nameof(SR.DataGridFlatModeDescr)) - ] - public bool FlatMode { - get { - return gridState[GRIDSTATE_isFlatMode]; - } - set { - if (value != FlatMode) { - gridState[GRIDSTATE_isFlatMode] = value; - Invalidate(layout.Inside); - OnFlatModeChanged(EventArgs.Empty); + recreateRows |= policy.UpdatePolicy(this.listManager, value); } - } - } - - private static readonly object EVENT_FLATMODECHANGED = new object(); - - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnFlatModeChangedDescr))] - public event EventHandler FlatModeChanged { - add => Events.AddHandler(EVENT_FLATMODECHANGED, value); - remove => Events.RemoveHandler(EVENT_FLATMODECHANGED, value); - } - - /// - /// - /// Gets or - /// sets the background color of all row and column headers. - /// - /// - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridHeaderBackColorDescr)) - ] - public Color HeaderBackColor { - get { - return headerBackBrush.Color; - } - set { - if (value.IsEmpty) - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "HeaderBackColor")); - if (IsTransparentColor(value)) - throw new ArgumentException(SR.DataGridTransparentHeaderBackColorNotAllowed); - if (!value.Equals(headerBackBrush.Color)) { - headerBackBrush = new SolidBrush(value); - - if (layout.RowHeadersVisible) - Invalidate(layout.RowHeaders); - if (layout.ColumnHeadersVisible) - Invalidate(layout.ColumnHeaders); - Invalidate(layout.TopLeftHeader); + gridState[GRIDSTATE_readOnlyMode] = value; + DataGridRow[] dataGridRows = this.DataGridRows; + if (recreateRows) + { + RecreateDataGridRows(); + + // keep the selected rows + DataGridRow[] currentDataGridRows = this.DataGridRows; + int rowCount = Math.Min(currentDataGridRows.Length, dataGridRows.Length); + for (int i = 0; i < rowCount; i++) + { + if (dataGridRows[i].Selected) + currentDataGridRows[i].Selected = true; + } } + + // the addnew row needs to be updated. + PerformLayout(); + InvalidateInside(); + OnReadOnlyChanged(EventArgs.Empty); } } - - internal SolidBrush HeaderBackBrush { - get { - return headerBackBrush; - } - } - - protected virtual bool ShouldSerializeHeaderBackColor() + } + + private static readonly object EVENT_READONLYCHANGED = new object(); + + [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnReadOnlyChangedDescr))] + public event EventHandler ReadOnlyChanged + { + add => Events.AddHandler(EVENT_READONLYCHANGED, value); + remove => Events.RemoveHandler(EVENT_READONLYCHANGED, value); + } + + /// + /// + /// Gets + /// or sets a value indicating if the grid's column headers are visible. + /// + /// + [ + SRCategory(nameof(SR.CatDisplay)), + DefaultValue(true), + SRDescription(nameof(SR.DataGridColumnHeadersVisibleDescr)) + ] + public bool ColumnHeadersVisible + { + get { - return !HeaderBackBrush.Equals(DefaultHeaderBackBrush); + return gridState[GRIDSTATE_columnHeadersVisible]; } - - public void ResetHeaderBackColor() { - if(ShouldSerializeHeaderBackColor()) { - HeaderBackColor = DefaultHeaderBackBrush.Color; + set + { + if (ColumnHeadersVisible != value) + { + gridState[GRIDSTATE_columnHeadersVisible] = value; + layout.ColumnHeadersVisible = value; + PerformLayout(); + InvalidateInside(); } } - internal SolidBrush BackgroundBrush { - get { - return backgroundBrush; + } + + /// + /// + /// Gets or sets a value indicating whether the parent rows of a table are + /// visible. + /// + /// + [ + SRCategory(nameof(SR.CatDisplay)), + DefaultValue(true), + SRDescription(nameof(SR.DataGridParentRowsVisibleDescr)) + ] + public bool ParentRowsVisible + { + get + { + return layout.ParentRowsVisible; + } + set + { + if (layout.ParentRowsVisible != value) + { + SetParentRowsVisibility(value); + + // update the caption: parentDownVisible == false corresponds to DownButtonDown == true; + // + caption.SetDownButtonDirection(!value); + + OnParentRowsVisibleChanged(EventArgs.Empty); } } + } - private void ResetBackgroundColor() { - if (backgroundBrush != null && BackgroundBrush != DefaultBackgroundBrush) { - backgroundBrush.Dispose(); - backgroundBrush = null; - } - backgroundBrush = DefaultBackgroundBrush; - } - - protected virtual bool ShouldSerializeBackgroundColor() + private static readonly object EVENT_PARENTROWSVISIBLECHANGED = new object(); + + [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnParentRowsVisibleChangedDescr))] + public event EventHandler ParentRowsVisibleChanged + { + add => Events.AddHandler(EVENT_PARENTROWSVISIBLECHANGED, value); + remove => Events.RemoveHandler(EVENT_PARENTROWSVISIBLECHANGED, value); + } + + internal bool ParentRowsIsEmpty() + { + return parentRows.IsEmpty(); + } + + /// + /// + /// Gets or sets a value indicating whether the data grid's row headers are + /// visible. + /// + /// + [ + SRCategory(nameof(SR.CatDisplay)), + DefaultValue(true), + SRDescription(nameof(SR.DataGridRowHeadersVisibleDescr)) + ] + public bool RowHeadersVisible + { + get { - return !BackgroundBrush.Equals(DefaultBackgroundBrush); + return gridState[GRIDSTATE_rowHeadersVisible]; } - - - // using this property, the user can set the backGround color - /// - /// Gets or sets the background color of the grid. - /// - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridBackgroundColorDescr)) - ] - public Color BackgroundColor { - get { - return backgroundBrush.Color; - } - set { - if (value.IsEmpty) - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "BackgroundColor")); - if (!value.Equals(backgroundBrush.Color)) { - - if (backgroundBrush != null && BackgroundBrush != DefaultBackgroundBrush) { - backgroundBrush.Dispose(); - backgroundBrush = null; - } - backgroundBrush = new SolidBrush(value); - - Invalidate(layout.Inside); - OnBackgroundColorChanged(EventArgs.Empty); - } + set + { + if (RowHeadersVisible != value) + { + gridState[GRIDSTATE_rowHeadersVisible] = value; + PerformLayout(); + InvalidateInside(); } } - - private static readonly object EVENT_BACKGROUNDCOLORCHANGED = new object(); - - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnBackgroundColorChangedDescr))] - public event EventHandler BackgroundColorChanged { - add => Events.AddHandler(EVENT_BACKGROUNDCOLORCHANGED, value); - remove => Events.RemoveHandler(EVENT_BACKGROUNDCOLORCHANGED, value); + } + + [ + SRCategory(nameof(SR.CatLayout)), + DefaultValue(defaultRowHeaderWidth), + SRDescription(nameof(SR.DataGridRowHeaderWidthDescr)) + ] + public int RowHeaderWidth + { + get + { + return rowHeaderWidth; } - - /// - /// - /// Indicates whether the property should be persisted. - /// - /// - [ - SRCategory(nameof(SR.CatAppearance)), - SRDescription(nameof(SR.DataGridHeaderFontDescr)) - ] - public Font HeaderFont { - get { - return(headerFont == null ? this.Font : headerFont); - } - set { - if (value == null) - throw new ArgumentNullException(nameof(HeaderFont)); - if (!value.Equals(headerFont)) { - headerFont = value; - RecalculateFonts(); + set + { + value = Math.Max(this.minRowHeaderWidth, value); + if (rowHeaderWidth != value) + { + rowHeaderWidth = value; + if (layout.RowHeadersVisible) + { PerformLayout(); - Invalidate(layout.Inside); + InvalidateInside(); } } } - - protected bool ShouldSerializeHeaderFont() { - return(headerFont != null); + } + + /// + /// + /// Gets or sets the width of headers. + /// + /// + + [ + Browsable(false), EditorBrowsable(EditorBrowsableState.Never), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), + Bindable(false) + ] + public override string Text + { + get + { + return base.Text; } - - public void ResetHeaderFont() { - if (headerFont != null) { - headerFont = null; - RecalculateFonts(); - PerformLayout(); - Invalidate(layout.Inside); - } + set + { + base.Text = value; } - - /// - /// - /// Resets the property to its default value. - /// - /// - /// - /// - /// Gets or sets the foreground color of the grid's headers. - /// - /// - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridHeaderForeColorDescr)) - ] - public Color HeaderForeColor { - get { - return headerForePen.Color; - } - set { - if (value.IsEmpty) - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "HeaderForeColor")); - if (!value.Equals(headerForePen.Color)) { - headerForePen = new Pen(value); - headerForeBrush = new SolidBrush(value); - - if (layout.RowHeadersVisible) - Invalidate(layout.RowHeaders); - if (layout.ColumnHeadersVisible) - Invalidate(layout.ColumnHeaders); - Invalidate(layout.TopLeftHeader); - } - } + } + + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + new public event EventHandler TextChanged + { + add => base.TextChanged += value; + remove => base.TextChanged -= value; + } + + /// + /// + /// Gets the vertical scroll bar of the control. + /// + /// + [ + Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), + SRDescription(nameof(SR.DataGridVertScrollBarDescr)) + ] + protected ScrollBar VertScrollBar + { + get + { + return vertScrollBar; } - - protected virtual bool ShouldSerializeHeaderForeColor() + } + + /// + /// + /// Gets the number of visible columns. + /// + /// + [ + Browsable(false), + SRDescription(nameof(SR.DataGridVisibleColumnCountDescr)) + ] + public int VisibleColumnCount + { + get { - return !HeaderForePen.Equals(DefaultHeaderForePen); + return Math.Min(numVisibleCols, this.myGridTable == null ? 0 : this.myGridTable.GridColumnStyles.Count); } - - public void ResetHeaderForeColor() { - if(ShouldSerializeHeaderForeColor()) { - HeaderForeColor = DefaultHeaderForeBrush.Color; - } + } + + /// + /// + /// Gets the number of rows visible. + /// + /// + [ + Browsable(false), + SRDescription(nameof(SR.DataGridVisibleRowCountDescr)) + ] + public int VisibleRowCount + { + get + { + return numVisibleRows; } - - internal SolidBrush HeaderForeBrush { - get { - return this.headerForeBrush; - } + } + + + /// + /// Gets or sets the value of the cell at + /// the specified the row and column. + /// + public object this[int rowIndex, int columnIndex] + { + get + { + EnsureBound(); + if (rowIndex < 0 || rowIndex >= DataGridRowsLength) + throw new ArgumentOutOfRangeException(nameof(rowIndex)); + if (columnIndex < 0 || columnIndex >= myGridTable.GridColumnStyles.Count) + throw new ArgumentOutOfRangeException(nameof(columnIndex)); + CurrencyManager listManager = this.listManager; + DataGridColumnStyle column = myGridTable.GridColumnStyles[columnIndex]; + return column.GetColumnValueAtRow(listManager, rowIndex); } - - internal Pen HeaderForePen { - get { - return headerForePen; + set + { + EnsureBound(); + if (rowIndex < 0 || rowIndex >= DataGridRowsLength) + throw new ArgumentOutOfRangeException(nameof(rowIndex)); + if (columnIndex < 0 || columnIndex >= myGridTable.GridColumnStyles.Count) + throw new ArgumentOutOfRangeException(nameof(columnIndex)); + CurrencyManager listManager = this.listManager; + if (listManager.Position != rowIndex) + listManager.Position = rowIndex; + DataGridColumnStyle column = myGridTable.GridColumnStyles[columnIndex]; + column.SetColumnValueAtRow(listManager, rowIndex, value); + + // invalidate the bounds of the cell only if the cell is visible + if (columnIndex >= firstVisibleCol && columnIndex <= firstVisibleCol + numVisibleCols - 1 && + rowIndex >= firstVisibleRow && rowIndex <= firstVisibleRow + numVisibleRows) + { + Rectangle bounds = GetCellBounds(rowIndex, columnIndex); + this.Invalidate(bounds); } } - private void ResetHorizontalOffset() { - horizontalOffset = 0; - negOffset = 0; - firstVisibleCol = 0; - numVisibleCols = 0; - lastTotallyVisibleCol = -1; - } - - internal int HorizontalOffset { - get { - return horizontalOffset; - } - set { - //if (CompModSwitches.DataGridScrolling.TraceVerbose) Debug.WriteLine("DataGridScrolling: Set_HorizontalOffset, value = " + value.ToString()); - if (value < 0) - value = 0; - - // - // if the dataGrid is not bound ( listManager == null || gridTable == null) - // then use ResetHorizontalOffset(); - // - - int totalWidth = GetColumnWidthSum(); - int widthNotVisible = totalWidth - layout.Data.Width; - if (value > widthNotVisible && widthNotVisible > 0) - value = widthNotVisible; - - if (value == horizontalOffset) - return; - - int change = horizontalOffset - value; - horizScrollBar.Value = value; - Rectangle scroll = layout.Data; - if (layout.ColumnHeadersVisible) - scroll = Rectangle.Union(scroll, layout.ColumnHeaders); - horizontalOffset = value; - - this.firstVisibleCol = ComputeFirstVisibleColumn(); - // update the lastTotallyVisibleCol - ComputeVisibleColumns(); - - if (gridState[GRIDSTATE_isScrolling]) - { - // if the user did not click on the grid yet, then do not put the edit - // control when scrolling - if (currentCol >= firstVisibleCol && currentCol < firstVisibleCol + numVisibleCols - 1 && (gridState[GRIDSTATE_isEditing] || gridState[GRIDSTATE_isNavigating])) - Edit(); - else - EndEdit(); - - // isScrolling is set to TRUE when the user scrolls. - // once we move the edit box, we finished processing the scroll event, so set isScrolling to FALSE - // to set isScrolling to TRUE, we need another scroll event. - gridState[GRIDSTATE_isScrolling] = false; - } - else - { - EndEdit(); - } - - NativeMethods.RECT[] rects = CreateScrollableRegion(scroll); - ScrollRectangles(rects, change); - OnScroll(EventArgs.Empty); - } + } + + /// + /// Gets or sets the value of a specified . + /// + public object this[DataGridCell cell] + { + get + { + return this[cell.RowNumber, cell.ColumnNumber]; } - - private void ScrollRectangles(NativeMethods.RECT[] rects, int change) { - if (rects != null) { - NativeMethods.RECT scroll; - if (isRightToLeft()) change = -change; - for (int r = 0; r < rects.Length; r++) { - scroll = rects[r]; - SafeNativeMethods.ScrollWindow(new HandleRef(this, Handle), - change, - 0, - ref scroll, - ref scroll); - } - } + set + { + this[cell.RowNumber, cell.ColumnNumber] = value; } - - /// - /// - [ - SRDescription(nameof(SR.DataGridHorizScrollBarDescr)) - ] - protected ScrollBar HorizScrollBar { - get { - return horizScrollBar; - } + } + + private void WireTableStylePropChanged(DataGridTableStyle gridTable) + { + gridTable.GridLineColorChanged += new EventHandler(GridLineColorChanged); + gridTable.GridLineStyleChanged += new EventHandler(GridLineStyleChanged); + gridTable.HeaderBackColorChanged += new EventHandler(HeaderBackColorChanged); + gridTable.HeaderFontChanged += new EventHandler(HeaderFontChanged); + gridTable.HeaderForeColorChanged += new EventHandler(HeaderForeColorChanged); + gridTable.LinkColorChanged += new EventHandler(LinkColorChanged); + gridTable.LinkHoverColorChanged += new EventHandler(LinkHoverColorChanged); + gridTable.PreferredColumnWidthChanged += new EventHandler(PreferredColumnWidthChanged); + gridTable.RowHeadersVisibleChanged += new EventHandler(RowHeadersVisibleChanged); + gridTable.ColumnHeadersVisibleChanged += new EventHandler(ColumnHeadersVisibleChanged); + gridTable.RowHeaderWidthChanged += new EventHandler(RowHeaderWidthChanged); + gridTable.AllowSortingChanged += new EventHandler(AllowSortingChanged); + } + + private void UnWireTableStylePropChanged(DataGridTableStyle gridTable) + { + gridTable.GridLineColorChanged -= new EventHandler(GridLineColorChanged); + gridTable.GridLineStyleChanged -= new EventHandler(GridLineStyleChanged); + gridTable.HeaderBackColorChanged -= new EventHandler(HeaderBackColorChanged); + gridTable.HeaderFontChanged -= new EventHandler(HeaderFontChanged); + gridTable.HeaderForeColorChanged -= new EventHandler(HeaderForeColorChanged); + gridTable.LinkColorChanged -= new EventHandler(LinkColorChanged); + gridTable.LinkHoverColorChanged -= new EventHandler(LinkHoverColorChanged); + gridTable.PreferredColumnWidthChanged -= new EventHandler(PreferredColumnWidthChanged); + gridTable.RowHeadersVisibleChanged -= new EventHandler(RowHeadersVisibleChanged); + gridTable.ColumnHeadersVisibleChanged -= new EventHandler(ColumnHeadersVisibleChanged); + gridTable.RowHeaderWidthChanged -= new EventHandler(RowHeaderWidthChanged); + gridTable.AllowSortingChanged -= new EventHandler(AllowSortingChanged); + } + + /// + /// DataSource events are handled + /// + private void WireDataSource() + { + Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: WireDataSource"); + Debug.Assert(listManager != null, "Can't wire up to a null DataSource"); + listManager.CurrentChanged += currentChangedHandler; + listManager.PositionChanged += positionChangedHandler; + listManager.ItemChanged += itemChangedHandler; + listManager.MetaDataChanged += metaDataChangedHandler; + } + + private void UnWireDataSource() + { + Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: UnWireDataSource"); + Debug.Assert(listManager != null, "Can't un wire from a null DataSource"); + listManager.CurrentChanged -= currentChangedHandler; + listManager.PositionChanged -= positionChangedHandler; + listManager.ItemChanged -= itemChangedHandler; + listManager.MetaDataChanged -= metaDataChangedHandler; + } + + // This is called after a row has been added. And I think whenever + // a row gets deleted, etc. + // We recreate our datagrid rows at this point. + private void DataSource_Changed(object sender, EventArgs ea) + { + Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: DataSource_Changed"); + + // the grid will receive the dataSource_Changed event when + // allowAdd changes on the dataView. + policy.UpdatePolicy(this.ListManager, this.ReadOnly); + if (gridState[GRIDSTATE_inListAddNew]) + { + // we are adding a new row + // keep the old rows, w/ their height, expanded/collapsed information + // + Debug.Assert(policy.AllowAdd, "how can we add a new row if the policy does not allow this?"); + Debug.Assert(DataGridRowsLength == DataGridRows.Length, "how can this fail?"); + + DataGridRow[] gridRows = DataGridRows; + int currentRowCount = DataGridRowsLength; + // put the added row: + // + gridRows[currentRowCount - 1] = new DataGridRelationshipRow(this, this.myGridTable, currentRowCount - 1); + SetDataGridRows(gridRows, currentRowCount); } - - /// - /// - /// Retrieves a value indicating whether odd and even - /// rows are painted using a different background color. - /// - /// - // Cleanup eventually to be static. - internal bool LedgerStyle { - get { - return gridState[GRIDSTATE_isLedgerStyle]; - } - /* - set { - if (isLedgerStyle != value) { - isLedgerStyle = value; - InvalidateInside(); - } - } - */ + else if (gridState[GRIDSTATE_inAddNewRow] && !gridState[GRIDSTATE_inDeleteRow]) + { + // when the backEnd adds a row and we are still inAddNewRow + listManager.CancelCurrentEdit(); + gridState[GRIDSTATE_inAddNewRow] = false; + RecreateDataGridRows(); } - - /// - /// - /// Indicates whether the property should be persisted. - /// - /// - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridLinkColorDescr)) - ] - public Color LinkColor { - get { - return linkBrush.Color; - } - set { - if (value.IsEmpty) - throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "LinkColor")); - if (!linkBrush.Color.Equals(value)) { - linkBrush = new SolidBrush(value); - Invalidate(layout.Data); - } - } + else if (!gridState[GRIDSTATE_inDeleteRow]) + { + RecreateDataGridRows(); + currentRow = Math.Min(currentRow, this.listManager.Count); } - - internal virtual bool ShouldSerializeLinkColor() + + bool oldListHasErrors = ListHasErrors; + ListHasErrors = DataGridSourceHasErrors(); + // if we changed the ListHasErrors, then the grid is already invalidated + if (oldListHasErrors == ListHasErrors) + InvalidateInside(); + } + + private void GridLineColorChanged(object sender, EventArgs e) + { + Invalidate(layout.Data); + } + private void GridLineStyleChanged(object sender, EventArgs e) + { + this.myGridTable.ResetRelationsUI(); + Invalidate(layout.Data); + } + private void HeaderBackColorChanged(object sender, EventArgs e) + { + if (layout.RowHeadersVisible) + Invalidate(layout.RowHeaders); + if (layout.ColumnHeadersVisible) + Invalidate(layout.ColumnHeaders); + Invalidate(layout.TopLeftHeader); + } + private void HeaderFontChanged(object sender, EventArgs e) + { + RecalculateFonts(); + PerformLayout(); + Invalidate(layout.Inside); + } + private void HeaderForeColorChanged(object sender, EventArgs e) + { + if (layout.RowHeadersVisible) + Invalidate(layout.RowHeaders); + if (layout.ColumnHeadersVisible) + Invalidate(layout.ColumnHeaders); + Invalidate(layout.TopLeftHeader); + } + private void LinkColorChanged(object sender, EventArgs e) + { + Invalidate(layout.Data); + } + private void LinkHoverColorChanged(object sender, EventArgs e) + { + Invalidate(layout.Data); + } + private void PreferredColumnWidthChanged(object sender, EventArgs e) + { + // reset the dataGridRows + SetDataGridRows(null, this.DataGridRowsLength); + // layout the horizontal scroll bar + PerformLayout(); + // invalidate everything + Invalidate(); + } + private void RowHeadersVisibleChanged(object sender, EventArgs e) + { + layout.RowHeadersVisible = this.myGridTable == null ? false : this.myGridTable.RowHeadersVisible; + PerformLayout(); + InvalidateInside(); + } + private void ColumnHeadersVisibleChanged(object sender, EventArgs e) + { + layout.ColumnHeadersVisible = this.myGridTable == null ? false : this.myGridTable.ColumnHeadersVisible; + PerformLayout(); + InvalidateInside(); + } + private void RowHeaderWidthChanged(object sender, EventArgs e) + { + if (layout.RowHeadersVisible) { - return !LinkBrush.Equals(DefaultLinkBrush); - } - - public void ResetLinkColor() { - if (ShouldSerializeLinkColor()) - LinkColor = DefaultLinkBrush.Color; + PerformLayout(); + InvalidateInside(); } - - internal Brush LinkBrush { - get { - return linkBrush; - } + } + private void AllowSortingChanged(object sender, EventArgs e) + { + if (!this.myGridTable.AllowSorting && this.listManager != null) + { + IList list = this.listManager.List; + if (list is IBindingList) + ((IBindingList)list).RemoveSort(); } - - /// - /// - /// Gets - /// or sets the color a link changes to when - /// the mouse pointer moves over it. - /// - /// - [ - SRDescription(nameof(SR.DataGridLinkHoverColorDescr)), - SRCategory(nameof(SR.CatColors)), - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never) - - ] - public Color LinkHoverColor { - get { - return this.LinkColor; - } - set { - } + } + + private void DataSource_RowChanged(object sender, EventArgs ea) + { + Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: DataSource_RowChanged"); + // it may be the case that our cache was not updated + // to the latest changes in the list : CurrentChanged is fired before + // ListChanged. + // So invalidate the row if there is something to invalidate + DataGridRow[] rows = this.DataGridRows; + if (currentRow < this.DataGridRowsLength) + { + InvalidateRow(currentRow); } - - protected virtual bool ShouldSerializeLinkHoverColor() + } + + /// + /// + /// Fired by the DataSource when row position moves. + /// + /// + private void DataSource_PositionChanged(object sender, EventArgs ea) + { +#if DEBUG + inDataSource_PositionChanged = true; +#endif + Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: DataSource_PositionChanged to " + listManager.Position.ToString(CultureInfo.InvariantCulture)); + // the grid will get the PositionChanged event + // before the OnItemChanged event when a row will be deleted in the backEnd; + // we still want to keep the old rows when the user deletes the rows using the grid + // and we do not want to do the same work twice when the user adds a row via the grid + if (this.DataGridRowsLength > this.listManager.Count + (policy.AllowAdd ? 1 : 0) && !gridState[GRIDSTATE_inDeleteRow]) { - return false; - // return !LinkHoverBrush.Equals(defaultLinkHoverBrush); + Debug.Assert(!gridState[GRIDSTATE_inAddNewRow] && !gridState[GRIDSTATE_inListAddNew], "how can the list decrease when we are adding a row?"); + RecreateDataGridRows(); } - - public void ResetLinkHoverColor() { - /* - if (ShouldSerializeLinkHoverColor()) - LinkHoverColor = defaultLinkHoverBrush.Color;*/ + if (this.ListManager.Position != currentRow) + { + CurrentCell = new DataGridCell(listManager.Position, currentCol); + } - - /// - /// - /// Indicates whether the property should be - /// persisted. - /// - /// - - internal Font LinkFont { - get { - return linkFont; +#if DEBUG + inDataSource_PositionChanged = false; +#endif + } + + internal void DataSource_MetaDataChanged(object sender, EventArgs e) + { + MetaDataChanged(); + } + + private bool DataGridSourceHasErrors() + { + if (this.listManager == null) + return false; + for (int i = 0; i < this.listManager.Count; i++) + { + object errObj = this.listManager[i]; + if (errObj is IDataErrorInfo) + { + string errString = ((IDataErrorInfo)errObj).Error; + if (errString != null && errString.Length != 0) + return true; } } - - internal int LinkFontHeight { - get { - return linkFontHeight; + return false; + } + + private void TableStylesCollectionChanged(object sender, CollectionChangeEventArgs ccea) + { + // if the users changed the collection of tableStyles + if (sender != this.dataGridTables) + return; + if (this.listManager == null) + return; + + if (ccea.Action == CollectionChangeAction.Add) + { + DataGridTableStyle tableStyle = (DataGridTableStyle)ccea.Element; + if (this.listManager.GetListName().Equals(tableStyle.MappingName)) + { + Debug.Assert(this.myGridTable.IsDefault, "if the table is not default, then it had a name. how can one add another table to the collection w/ the same name and not throw an exception"); + SetDataGridTable(tableStyle, true); // true for forcing column creation + SetDataGridRows(null, 0); } } - - /// - /// Gets or sets a value - /// that specifies which links are shown and in what context. - /// - [ - DefaultValue(true), - SRDescription(nameof(SR.DataGridNavigationModeDescr)), - SRCategory(nameof(SR.CatBehavior)) - ] - public bool AllowNavigation { - get { - return gridState[GRIDSTATE_allowNavigation]; - } - set { - if (AllowNavigation != value) { - gridState[GRIDSTATE_allowNavigation] = value; - // let the Caption know about this: - this.Caption.BackButtonActive = !parentRows.IsEmpty() && (value); - this.Caption.BackButtonVisible = this.Caption.BackButtonActive; - RecreateDataGridRows(); - - OnAllowNavigationChanged(EventArgs.Empty); - } + else if (ccea.Action == CollectionChangeAction.Remove) + { + DataGridTableStyle tableStyle = (DataGridTableStyle)ccea.Element; + if (this.myGridTable.MappingName.Equals(tableStyle.MappingName)) + { + Debug.Assert(this.myGridTable.IsDefault, "if the table is not default, then it had a name. how can one add another table to the collection w/ the same name and not throw an exception"); + this.defaultTableStyle.GridColumnStyles.ResetDefaultColumnCollection(); + SetDataGridTable(this.defaultTableStyle, true); // true for forcing column creation + SetDataGridRows(null, 0); } } - - private static readonly object EVENT_ALLOWNAVIGATIONCHANGED = new object(); - - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnNavigationModeChangedDescr))] - public event EventHandler AllowNavigationChanged { - add => Events.AddHandler(EVENT_ALLOWNAVIGATIONCHANGED, value); - remove => Events.RemoveHandler(EVENT_ALLOWNAVIGATIONCHANGED, value); - } - - [ - Browsable(false), EditorBrowsable(EditorBrowsableState.Never) - ] - public override Cursor Cursor { - // get the cursor out of the propertyGrid. - get { - return base.Cursor; + else + { + Debug.Assert(ccea.Action == CollectionChangeAction.Refresh, "what else is possible?"); + // we have to search to see if the collection of table styles contains one + // w/ the same name as the list in the dataGrid + + DataGridTableStyle newGridTable = this.dataGridTables[listManager.GetListName()]; + if (newGridTable == null) + { + if (!this.myGridTable.IsDefault) + { + // get rid of the old gridColumns + this.defaultTableStyle.GridColumnStyles.ResetDefaultColumnCollection(); + SetDataGridTable(this.defaultTableStyle, true); // true for forcing column creation + SetDataGridRows(null, 0); + } } - - set { - base.Cursor = value; + else + { + SetDataGridTable(newGridTable, true); // true for forcing column creation + SetDataGridRows(null, 0); } } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler CursorChanged { - add => base.CursorChanged += value; - remove => base.CursorChanged -= value; - } - - [ - Browsable(false), EditorBrowsable(EditorBrowsableState.Never) - ] - public override Image BackgroundImage { - // get the BackgroundImage out of the propertyGrid. - get { - return base.BackgroundImage; - } - - set { - base.BackgroundImage = value; + } + + private void DataSource_ItemChanged(object sender, ItemChangedEventArgs ea) + { + Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: DataSource_ItemChanged at index " + ea.Index.ToString(CultureInfo.InvariantCulture)); + + // if ea.Index == -1, then we invalidate all rows. + if (ea.Index == -1) + { + DataSource_Changed(sender, EventArgs.Empty); + /* + // if there are rows which are invisible, it is more efficient to invalidata layout.Data + if (numVisibleRows <= dataGridRowsLength) + Invalidate(layout.Data); + else + { + Debug.Assert(firstVisibleRow == 0, "if all rows are visible, then how come that first row is not visible?"); + for (int i = 0; i < numVisibleRows; i++) + InvalidateRow(firstVisibleRow + numVisibleRows); } + */ } - - [ - Browsable(false), EditorBrowsable(EditorBrowsableState.Never) - ] - public override ImageLayout BackgroundImageLayout { - // get the BackgroundImage out of the propertyGrid. - get { - return base.BackgroundImageLayout; - } - - set { - base.BackgroundImageLayout = value; + else + { + // let's see how we are doing w/ the errors + object errObj = this.listManager[ea.Index]; + bool oldListHasErrors = ListHasErrors; + if (errObj is IDataErrorInfo) + { + if (((IDataErrorInfo)errObj).Error.Length != 0) + ListHasErrors = true; + else if (ListHasErrors) + { + // maybe there was an error that now is fixed + ListHasErrors = DataGridSourceHasErrors(); + } } + + // Invalidate the row only if we did not change the ListHasErrors + if (oldListHasErrors == ListHasErrors) + InvalidateRow(ea.Index); + + // we need to update the edit box: + // we update the text in the edit box only when the currentRow + // equals the ea.Index + if (editColumn != null && ea.Index == currentRow) + editColumn.UpdateUI(this.ListManager, ea.Index, null); } - - - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged { - add => base.BackgroundImageChanged += value; - remove => base.BackgroundImageChanged -= value; - } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { - add => base.BackgroundImageLayoutChanged += value; - remove => base.BackgroundImageLayoutChanged -= value; - } - - /// - /// - /// Gets or sets the background color of parent rows. - /// - /// - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridParentRowsBackColorDescr)) - ] - public Color ParentRowsBackColor { - get { - return parentRows.BackColor; - } - set { - if (IsTransparentColor(value)) - throw new ArgumentException(SR.DataGridTransparentParentRowsBackColorNotAllowed); - this.parentRows.BackColor = value; - } + } + + protected virtual void OnBorderStyleChanged(EventArgs e) + { + EventHandler eh = Events[EVENT_BORDERSTYLECHANGED] as EventHandler; + if (eh != null) + { + eh(this, e); } - - internal SolidBrush ParentRowsBackBrush { - get { - return parentRows.BackBrush; - } + } + + protected virtual void OnCaptionVisibleChanged(EventArgs e) + { + EventHandler eh = Events[EVENT_CAPTIONVISIBLECHANGED] as EventHandler; + if (eh != null) + { + eh(this, e); } - - /// - /// - /// Indicates whether the property should be - /// persisted. - /// - /// - protected virtual bool ShouldSerializeParentRowsBackColor() + } + + protected virtual void OnCurrentCellChanged(EventArgs e) + { + EventHandler eh = Events[EVENT_CURRENTCELLCHANGED] as EventHandler; + if (eh != null) { - return !ParentRowsBackBrush.Equals(DefaultParentRowsBackBrush); + eh(this, e); } - - private void ResetParentRowsBackColor() { - if (ShouldSerializeParentRowsBackColor()) - parentRows.BackBrush = DefaultParentRowsBackBrush; + } + + /* + /// + /// + /// Raises the event. + /// + /// + /// + /// An that contains the event data. + /// + /// + /// + /// Raising an event invokes the event-handling method through a delegate. For an + /// overview, see . + /// + /// When overriding in an + /// derived class, be sure to call the base class's method. + /// + protected void OnColumnHeaderClick(EventArgs e) { + RaiseEvent(EVENT_COLUMNHEADERCLICK, e); + } + */ + + protected virtual void OnFlatModeChanged(EventArgs e) + { + EventHandler eh = Events[EVENT_FLATMODECHANGED] as EventHandler; + if (eh != null) + { + eh(this, e); } - - /// - /// - /// Gets or sets the foreground color of parent rows. - /// - /// - [ - SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridParentRowsForeColorDescr)) - ] - public Color ParentRowsForeColor { - get { - return parentRows.ForeColor; - } - set { - this.parentRows.ForeColor = value; - } + } + + protected virtual void OnBackgroundColorChanged(EventArgs e) + { + EventHandler eh = Events[EVENT_BACKGROUNDCOLORCHANGED] as EventHandler; + if (eh != null) + { + eh(this, e); } - - internal SolidBrush ParentRowsForeBrush { - get { - return parentRows.ForeBrush; - } + } + + protected virtual void OnAllowNavigationChanged(EventArgs e) + { + EventHandler eh = Events[EVENT_ALLOWNAVIGATIONCHANGED] as EventHandler; + if (eh != null) + { + eh(this, e); } - - /// - /// - /// Indicates whether the property should be - /// persisted. - /// - /// - protected virtual bool ShouldSerializeParentRowsForeColor() + } + + protected virtual void OnParentRowsVisibleChanged(EventArgs e) + { + EventHandler eh = Events[EVENT_PARENTROWSVISIBLECHANGED] as EventHandler; + if (eh != null) { - return !ParentRowsForeBrush.Equals(DefaultParentRowsForeBrush); + eh(this, e); } - - private void ResetParentRowsForeColor() { - if (ShouldSerializeParentRowsForeColor()) - parentRows.ForeBrush = DefaultParentRowsForeBrush; + } + + protected virtual void OnParentRowsLabelStyleChanged(EventArgs e) + { + EventHandler eh = Events[EVENT_PARENTROWSLABELSTYLECHANGED] as EventHandler; + if (eh != null) + { + eh(this, e); } - - - /// - /// - /// Gets - /// or sets the default width of the grid columns in - /// pixels. - /// - /// - [ - DefaultValue(defaultPreferredColumnWidth), - SRCategory(nameof(SR.CatLayout)), - SRDescription(nameof(SR.DataGridPreferredColumnWidthDescr)), - TypeConverter(typeof(DataGridPreferredColumnWidthTypeConverter)) - ] - public int PreferredColumnWidth { - get { - return preferredColumnWidth; - } - set { - if (value < 0) - throw new ArgumentException(SR.DataGridColumnWidth, "PreferredColumnWidth"); - if (preferredColumnWidth != value) { - preferredColumnWidth = value; - } - } + } + + protected virtual void OnReadOnlyChanged(EventArgs e) + { + EventHandler eh = Events[EVENT_READONLYCHANGED] as EventHandler; + if (eh != null) + { + eh(this, e); } - - /// - /// - /// Gets or sets the preferred row height for the control. - /// - /// - [ - SRCategory(nameof(SR.CatLayout)), - SRDescription(nameof(SR.DataGridPreferredRowHeightDescr)) - ] - public int PreferredRowHeight { - get { - return prefferedRowHeight; - } - set { - if (value < 0) - throw new ArgumentException(SR.DataGridRowRowHeight); - prefferedRowHeight = value; - } + } + + /// + /// + /// Raises the + /// event. + /// + /// + protected void OnNavigate(NavigateEventArgs e) + { + if (onNavigate != null) + onNavigate(this, e); + } + + /* + /// + /// + /// Raises the event. + /// + /// + protected void OnColumnResize(EventArgs e) { + RaiseEvent(EVENT_COLUMNRESIZE, e); + } + + internal void OnLinkClick(EventArgs e) { + RaiseEvent(EVENT_LINKCLICKED, e); + } + */ + + internal void OnNodeClick(EventArgs e) + { + // if we expanded/collapsed the RelationshipRow + // then we need to layout the vertical scroll bar + // + PerformLayout(); + + + // also, we need to let the hosted edit control that its + // boundaries possibly changed. do this with a call to Edit() + // do this only if the firstVisibleColumn is the editColumn + // + GridColumnStylesCollection columns = this.myGridTable.GridColumnStyles; + if (firstVisibleCol > -1 && firstVisibleCol < columns.Count && columns[firstVisibleCol] == editColumn) + Edit(); + + // Raise the event for the event listeners + EventHandler handler = (EventHandler)Events[EVENT_NODECLICKED]; + if (handler != null) + { + handler(this, e); } + } - private void ResetPreferredRowHeight() { - prefferedRowHeight = defaultFontHeight + 3; - } - - protected bool ShouldSerializePreferredRowHeight() + /// + /// Raises the event. + /// + protected void OnRowHeaderClick(EventArgs e) + { + if (onRowHeaderClick != null) + onRowHeaderClick(this, e); + } + + /// + /// + /// Raises the event. + /// + /// + protected void OnScroll(EventArgs e) + { + // reset the toolTip information + if (ToolTipProvider != null) + ResetToolTip(); + + EventHandler handler = (EventHandler)Events[EVENT_SCROLL]; + if (handler != null) { - return prefferedRowHeight != defaultFontHeight + 3; + handler(this, e); } - - /// - /// Gets or sets a value indicating whether the grid - /// is in read-only mode. - /// - [ - DefaultValue(false), - SRCategory(nameof(SR.CatBehavior)), - SRDescription(nameof(SR.DataGridReadOnlyDescr)) - ] - public bool ReadOnly { - get { - return gridState[GRIDSTATE_readOnlyMode]; - } - set { - if (ReadOnly != value) { - bool recreateRows = false; - if (value) { - // AllowAdd happens to have the same boolean value as whether we need to recreate rows. - recreateRows = policy.AllowAdd; - - policy.AllowRemove = false; - policy.AllowEdit = false; - policy.AllowAdd = false; - } - else { - recreateRows |= policy.UpdatePolicy(this.listManager, value); - } - gridState[GRIDSTATE_readOnlyMode] = value; - DataGridRow[] dataGridRows = this.DataGridRows; - if (recreateRows) { - RecreateDataGridRows(); - - // keep the selected rows - DataGridRow[] currentDataGridRows = this.DataGridRows; - int rowCount = Math.Min(currentDataGridRows.Length, dataGridRows.Length); - for (int i = 0; i < rowCount; i++) { - if (dataGridRows[i].Selected) - currentDataGridRows[i].Selected = true; - } - } - - // the addnew row needs to be updated. - PerformLayout(); - InvalidateInside(); - OnReadOnlyChanged(EventArgs.Empty); - } - } + } + + /// + /// + /// Listens + /// for the horizontal scrollbar's scroll + /// event. + /// + /// + protected virtual void GridHScrolled(object sender, ScrollEventArgs se) + { + if (!Enabled) + return; + if (DataSource == null) + { + Debug.Fail("Horizontal Scrollbar should be disabled without a DataSource."); + return; } - - private static readonly object EVENT_READONLYCHANGED = new object(); - - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnReadOnlyChangedDescr))] - public event EventHandler ReadOnlyChanged { - add => Events.AddHandler(EVENT_READONLYCHANGED, value); - remove => Events.RemoveHandler(EVENT_READONLYCHANGED, value); + + gridState[GRIDSTATE_isScrolling] = true; + +#if DEBUG + + Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "DataGridScrolling: in GridHScrolled: the scroll event type:"); + switch (se.Type) + { + case ScrollEventType.SmallIncrement: + Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "small increment"); + break; + case ScrollEventType.SmallDecrement: + Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "small decrement"); + break; + case ScrollEventType.LargeIncrement: + Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "Large decrement"); + break; + case ScrollEventType.LargeDecrement: + Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "small decrement"); + break; + case ScrollEventType.ThumbPosition: + Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "Thumb Position"); + break; + case ScrollEventType.ThumbTrack: + Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "Thumb Track"); + break; + case ScrollEventType.First: + Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "First"); + break; + case ScrollEventType.Last: + Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "Last"); + break; + case ScrollEventType.EndScroll: + Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "EndScroll"); + break; } - - /// - /// - /// Gets - /// or sets a value indicating if the grid's column headers are visible. - /// - /// - [ - SRCategory(nameof(SR.CatDisplay)), - DefaultValue(true), - SRDescription(nameof(SR.DataGridColumnHeadersVisibleDescr)) - ] - public bool ColumnHeadersVisible { - get { - return gridState[GRIDSTATE_columnHeadersVisible]; - } - set { - if (ColumnHeadersVisible != value) { - gridState[GRIDSTATE_columnHeadersVisible] = value; - layout.ColumnHeadersVisible = value; - PerformLayout(); - InvalidateInside(); + +#endif // DEBUG + + if (se.Type == ScrollEventType.SmallIncrement || + se.Type == ScrollEventType.SmallDecrement) + { + int dCols = (se.Type == ScrollEventType.SmallIncrement) ? 1 : -1; + if (se.Type == ScrollEventType.SmallDecrement && this.negOffset == 0) + { + GridColumnStylesCollection cols = this.myGridTable.GridColumnStyles; + // if the column before the first visible column has width == 0 then skip it + for (int i = this.firstVisibleCol - 1; i >= 0 && cols[i].Width == 0; i--) + { + dCols--; } } - } - - /// - /// - /// Gets or sets a value indicating whether the parent rows of a table are - /// visible. - /// - /// - [ - SRCategory(nameof(SR.CatDisplay)), - DefaultValue(true), - SRDescription(nameof(SR.DataGridParentRowsVisibleDescr)) - ] - public bool ParentRowsVisible { - get { - return layout.ParentRowsVisible; - } - set { - if (layout.ParentRowsVisible != value) { - SetParentRowsVisibility(value); - - // update the caption: parentDownVisible == false corresponds to DownButtonDown == true; - // - caption.SetDownButtonDirection(!value); - - OnParentRowsVisibleChanged(EventArgs.Empty); + + if (se.Type == ScrollEventType.SmallIncrement && this.negOffset == 0) + { + GridColumnStylesCollection cols = this.myGridTable.GridColumnStyles; + for (int i = this.firstVisibleCol; i > -1 && i < cols.Count && cols[i].Width == 0; i++) + { + dCols++; } } + + ScrollRight(dCols); + se.NewValue = HorizontalOffset; } - - private static readonly object EVENT_PARENTROWSVISIBLECHANGED = new object(); - - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridOnParentRowsVisibleChangedDescr))] - public event EventHandler ParentRowsVisibleChanged { - add => Events.AddHandler(EVENT_PARENTROWSVISIBLECHANGED, value); - remove => Events.RemoveHandler(EVENT_PARENTROWSVISIBLECHANGED, value); + else if (se.Type != ScrollEventType.EndScroll) + { + HorizontalOffset = se.NewValue; } - - internal bool ParentRowsIsEmpty() { - return parentRows.IsEmpty(); + + this.gridState[GRIDSTATE_isScrolling] = false; + } + + /// + /// + /// Listens + /// for the vertical scrollbar's scroll event. + /// + /// + protected virtual void GridVScrolled(object sender, ScrollEventArgs se) + { + if (!Enabled) + return; + if (DataSource == null) + { + Debug.Fail("Vertical Scrollbar should be disabled without a DataSource."); + return; } - - /// - /// - /// Gets or sets a value indicating whether the data grid's row headers are - /// visible. - /// - /// - [ - SRCategory(nameof(SR.CatDisplay)), - DefaultValue(true), - SRDescription(nameof(SR.DataGridRowHeadersVisibleDescr)) - ] - public bool RowHeadersVisible { - get { - return gridState[GRIDSTATE_rowHeadersVisible]; - } - set { - if (RowHeadersVisible != value) { - gridState[GRIDSTATE_rowHeadersVisible] = value; - PerformLayout(); - InvalidateInside(); - } - } + + gridState[GRIDSTATE_isScrolling] = true; + + try + { + se.NewValue = Math.Min(se.NewValue, DataGridRowsLength - numTotallyVisibleRows); + int dRows = se.NewValue - firstVisibleRow; + ScrollDown(dRows); } - - [ - SRCategory(nameof(SR.CatLayout)), - DefaultValue(defaultRowHeaderWidth), - SRDescription(nameof(SR.DataGridRowHeaderWidthDescr)) - ] - public int RowHeaderWidth { - get { - return rowHeaderWidth; - } - set { - value = Math.Max(this.minRowHeaderWidth, value); - if (rowHeaderWidth != value) - { - rowHeaderWidth = value; - if (layout.RowHeadersVisible) - { - PerformLayout(); - InvalidateInside(); - } - } - } + finally + { + gridState[GRIDSTATE_isScrolling] = false; } - - /// - /// - /// Gets or sets the width of headers. - /// - /// - - [ - Browsable(false), EditorBrowsable(EditorBrowsableState.Never), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Bindable(false) - ] - public override string Text { - get { - return base.Text; - } - set { - base.Text = value; - } + } + + private void HandleEndCurrentEdit() + { + int currentRowSaved = currentRow; + int currentColSaved = currentCol; + + string errorMessage = null; + + try + { + listManager.EndCurrentEdit(); } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TextChanged { - add => base.TextChanged += value; - remove => base.TextChanged -= value; + catch (Exception e) + { + errorMessage = e.Message; } - - /// - /// - /// Gets the vertical scroll bar of the control. - /// - /// - [ - Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), - SRDescription(nameof(SR.DataGridVertScrollBarDescr)) - ] - protected ScrollBar VertScrollBar { - get { - return vertScrollBar; + + if (errorMessage != null) + { + DialogResult result = RTLAwareMessageBox.Show(null, string.Format(SR.DataGridPushedIncorrectValueIntoColumn, + errorMessage), SR.DataGridErrorMessageBoxCaption, MessageBoxButtons.YesNo, + MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); + + if (result == DialogResult.Yes) + { + currentRow = currentRowSaved; + currentCol = currentColSaved; + Debug.Assert(currentRow == ListManager.Position || listManager.Position == -1, "the position in the list manager (" + ListManager.Position + ") is out of sync with the currentRow (" + currentRow + ")" + " and the exception is '" + errorMessage + "'"); + // also, make sure that we get the row selector on the currentrow, too + InvalidateRowHeader(currentRow); + Edit(); } - } - - /// - /// - /// Gets the number of visible columns. - /// - /// - [ - Browsable(false), - SRDescription(nameof(SR.DataGridVisibleColumnCountDescr)) - ] - public int VisibleColumnCount { - get { - return Math.Min(numVisibleCols, this.myGridTable == null ? 0 : this.myGridTable.GridColumnStyles.Count); + else + { + // if the user committed a row that used to be addNewRow and the backEnd rejects it, + // and then it tries to navigate down then we should stay in the addNewRow + // in this particular scenario, CancelCurrentEdit will cause the last row to be deleted, + // and this will ultimately call InvalidateRow w/ a row number larger than the number of rows + // so set the currentRow here: + Debug.Assert(result == DialogResult.No, "we only put cancel and ok on the error message box"); + this.listManager.PositionChanged -= positionChangedHandler; + this.listManager.CancelCurrentEdit(); + this.listManager.Position = currentRow; + this.listManager.PositionChanged += positionChangedHandler; } } - - /// - /// - /// Gets the number of rows visible. - /// - /// - [ - Browsable(false), - SRDescription(nameof(SR.DataGridVisibleRowCountDescr)) - ] - public int VisibleRowCount { - get { - return numVisibleRows; + } + + /// + /// + /// Listens + /// for the caption's back button clicked event. + /// + /// + protected void OnBackButtonClicked(object sender, EventArgs e) + { + NavigateBack(); + + EventHandler handler = (EventHandler)Events[EVENT_BACKBUTTONCLICK]; + if (handler != null) + handler(this, e); + } + + protected override void OnBackColorChanged(EventArgs e) + { + backBrush = new SolidBrush(BackColor); + Invalidate(); + + base.OnBackColorChanged(e); + } + + protected override void OnBindingContextChanged(EventArgs e) + { + if (this.DataSource != null && !gridState[GRIDSTATE_inSetListManager]) + try + { + Set_ListManager(this.DataSource, this.DataMember, true, false); // we do not want to create columns + // if the columns are already created + // the grid should not rely on OnBindingContextChanged + // to create columns. } - } - - - /// - /// Gets or sets the value of the cell at - /// the specified the row and column. - /// - public object this[int rowIndex, int columnIndex] { - get { - EnsureBound(); - if (rowIndex < 0 || rowIndex >= DataGridRowsLength) - throw new ArgumentOutOfRangeException(nameof(rowIndex)); - if (columnIndex < 0 || columnIndex >= myGridTable.GridColumnStyles.Count) - throw new ArgumentOutOfRangeException(nameof(columnIndex)); - CurrencyManager listManager = this.listManager; - DataGridColumnStyle column = myGridTable.GridColumnStyles[columnIndex]; - return column.GetColumnValueAtRow(listManager, rowIndex); - } - set { - EnsureBound(); - if (rowIndex < 0 || rowIndex >= DataGridRowsLength) - throw new ArgumentOutOfRangeException(nameof(rowIndex)); - if (columnIndex < 0 || columnIndex >= myGridTable.GridColumnStyles.Count) - throw new ArgumentOutOfRangeException(nameof(columnIndex)); - CurrencyManager listManager = this.listManager; - if (listManager.Position != rowIndex) - listManager.Position = rowIndex; - DataGridColumnStyle column = myGridTable.GridColumnStyles[columnIndex]; - column.SetColumnValueAtRow(listManager, rowIndex, value); - - // invalidate the bounds of the cell only if the cell is visible - if (columnIndex >= firstVisibleCol && columnIndex <= firstVisibleCol+ numVisibleCols - 1 && - rowIndex >= firstVisibleRow && rowIndex <= firstVisibleRow + numVisibleRows) { - Rectangle bounds = GetCellBounds(rowIndex, columnIndex); - this.Invalidate(bounds); - } + catch + { + // at runtime we will rethrow the exception + if (this.Site == null || !this.Site.DesignMode) + throw; + + RTLAwareMessageBox.Show(null, SR.DataGridExceptionInPaint, null, + MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); + + if (this.Visible) + BeginUpdateInternal(); + + ResetParentRows(); + + Set_ListManager(null, string.Empty, true); + if (this.Visible) + EndUpdateInternal(); } + base.OnBindingContextChanged(e); + } + + protected virtual void OnDataSourceChanged(EventArgs e) + { + EventHandler eh = Events[EVENT_DATASOURCECHANGED] as EventHandler; + if (eh != null) + { + eh(this, e); } - - /// - /// Gets or sets the value of a specified . - /// - public object this[DataGridCell cell] { - get { - return this[cell.RowNumber, cell.ColumnNumber]; + } + + /// + /// + /// Listens for + /// the caption's down button clicked event. + /// + /// + protected void OnShowParentDetailsButtonClicked(object sender, EventArgs e) + { + // we need to fire the ParentRowsVisibleChanged event + // and the ParentRowsVisible property just calls SetParentRowsVisibility and + // then fires the event. + this.ParentRowsVisible = !caption.ToggleDownButtonDirection(); + + EventHandler handler = (EventHandler)Events[EVENT_DOWNBUTTONCLICK]; + if (handler != null) + handler(this, e); + } + + protected override void OnForeColorChanged(EventArgs e) + { + foreBrush = new SolidBrush(ForeColor); + Invalidate(); + + base.OnForeColorChanged(e); + } + + protected override void OnFontChanged(EventArgs e) + { + // let the caption know about the event changed + // + this.Caption.OnGridFontChanged(); + RecalculateFonts(); + RecreateDataGridRows(); + // get all the rows in the parentRows stack, and modify their height + if (originalState != null) + { + Debug.Assert(!parentRows.IsEmpty(), "if the originalState is not null, then parentRows contains at least one row"); + Stack parentStack = new Stack(); + // this is a huge performance hit: + // everytime we get/put something from/to + // the parentRows, the buttons in the dataGridCaption + // are invalidated + while (!parentRows.IsEmpty()) + { + DataGridState dgs = parentRows.PopTop(); + int rowCount = dgs.DataGridRowsLength; + + for (int i = 0; i < rowCount; i++) + { + // performance hit: this will cause to invalidate a bunch of + // stuff + + dgs.DataGridRows[i].Height = dgs.DataGridRows[i].MinimumRowHeight(dgs.GridColumnStyles); + } + parentStack.Push(dgs); } - set { - this[cell.RowNumber, cell.ColumnNumber] = value; + + while (parentStack.Count != 0) + { + parentRows.AddParent((DataGridState)parentStack.Pop()); } } - - private void WireTableStylePropChanged(DataGridTableStyle gridTable) { - gridTable.GridLineColorChanged += new EventHandler(GridLineColorChanged); - gridTable.GridLineStyleChanged += new EventHandler(GridLineStyleChanged); - gridTable.HeaderBackColorChanged += new EventHandler(HeaderBackColorChanged); - gridTable.HeaderFontChanged += new EventHandler(HeaderFontChanged); - gridTable.HeaderForeColorChanged += new EventHandler(HeaderForeColorChanged); - gridTable.LinkColorChanged += new EventHandler(LinkColorChanged); - gridTable.LinkHoverColorChanged += new EventHandler(LinkHoverColorChanged); - gridTable.PreferredColumnWidthChanged += new EventHandler(PreferredColumnWidthChanged); - gridTable.RowHeadersVisibleChanged += new EventHandler(RowHeadersVisibleChanged); - gridTable.ColumnHeadersVisibleChanged += new EventHandler(ColumnHeadersVisibleChanged); - gridTable.RowHeaderWidthChanged += new EventHandler(RowHeaderWidthChanged); - gridTable.AllowSortingChanged += new EventHandler(AllowSortingChanged); - } - - private void UnWireTableStylePropChanged(DataGridTableStyle gridTable) { - gridTable.GridLineColorChanged -= new EventHandler(GridLineColorChanged); - gridTable.GridLineStyleChanged -= new EventHandler(GridLineStyleChanged); - gridTable.HeaderBackColorChanged -= new EventHandler(HeaderBackColorChanged); - gridTable.HeaderFontChanged -= new EventHandler(HeaderFontChanged); - gridTable.HeaderForeColorChanged -= new EventHandler(HeaderForeColorChanged); - gridTable.LinkColorChanged -= new EventHandler(LinkColorChanged); - gridTable.LinkHoverColorChanged -= new EventHandler(LinkHoverColorChanged); - gridTable.PreferredColumnWidthChanged -= new EventHandler(PreferredColumnWidthChanged); - gridTable.RowHeadersVisibleChanged -= new EventHandler(RowHeadersVisibleChanged); - gridTable.ColumnHeadersVisibleChanged -= new EventHandler(ColumnHeadersVisibleChanged); - gridTable.RowHeaderWidthChanged -= new EventHandler(RowHeaderWidthChanged); - gridTable.AllowSortingChanged -= new EventHandler(AllowSortingChanged); - } - - /// - /// DataSource events are handled - /// - private void WireDataSource() { - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: WireDataSource"); - Debug.Assert(listManager!= null, "Can't wire up to a null DataSource"); - listManager.CurrentChanged += currentChangedHandler; - listManager.PositionChanged += positionChangedHandler; - listManager.ItemChanged += itemChangedHandler; - listManager.MetaDataChanged += metaDataChangedHandler; - } - - private void UnWireDataSource() { - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: UnWireDataSource"); - Debug.Assert(listManager != null, "Can't un wire from a null DataSource"); - listManager.CurrentChanged -= currentChangedHandler; - listManager.PositionChanged -= positionChangedHandler; - listManager.ItemChanged -= itemChangedHandler; - listManager.MetaDataChanged -= metaDataChangedHandler; - } - - // This is called after a row has been added. And I think whenever - // a row gets deleted, etc. - // We recreate our datagrid rows at this point. - private void DataSource_Changed(object sender, EventArgs ea) { - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: DataSource_Changed"); - - // the grid will receive the dataSource_Changed event when - // allowAdd changes on the dataView. - policy.UpdatePolicy(this.ListManager, this.ReadOnly); - if (gridState[GRIDSTATE_inListAddNew]) { - // we are adding a new row - // keep the old rows, w/ their height, expanded/collapsed information - // - Debug.Assert(policy.AllowAdd, "how can we add a new row if the policy does not allow this?"); - Debug.Assert(DataGridRowsLength == DataGridRows.Length, "how can this fail?"); - - DataGridRow[] gridRows = DataGridRows; - int currentRowCount = DataGridRowsLength; - // put the added row: - // - gridRows[currentRowCount - 1] = new DataGridRelationshipRow(this, this.myGridTable, currentRowCount - 1); - SetDataGridRows(gridRows, currentRowCount); - } else if (gridState[GRIDSTATE_inAddNewRow] && !gridState[GRIDSTATE_inDeleteRow]) { - // when the backEnd adds a row and we are still inAddNewRow - listManager.CancelCurrentEdit(); - gridState[GRIDSTATE_inAddNewRow] = false; - RecreateDataGridRows(); - } else if (!gridState[GRIDSTATE_inDeleteRow]) { - RecreateDataGridRows(); - currentRow = Math.Min(currentRow, this.listManager.Count); + + base.OnFontChanged(e); + } + + /// + /// + /// Raises the + /// event. + /// + /// + protected override void OnPaintBackground(PaintEventArgs ebe) + { + // null body + } + + /// + /// + /// Raises the event which + /// repositions controls + /// and updates scroll bars. + /// + /// + protected override void OnLayout(LayoutEventArgs levent) + { + // if we get a OnLayout event while the editControl changes, then just + // ignore it + // + if (gridState[GRIDSTATE_editControlChanging]) + return; + + Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: OnLayout"); + base.OnLayout(levent); + + if (gridState[GRIDSTATE_layoutSuspended]) + return; + + gridState[GRIDSTATE_canFocus] = false; + try + { + if (IsHandleCreated) + { + if (layout.ParentRowsVisible) + parentRows.OnLayout(); + + // reset the toolTip information + if (ToolTipProvider != null) + ResetToolTip(); + + ComputeLayout(); } - - bool oldListHasErrors = ListHasErrors; - ListHasErrors = DataGridSourceHasErrors(); - // if we changed the ListHasErrors, then the grid is already invalidated - if (oldListHasErrors == ListHasErrors) - InvalidateInside(); - } - - private void GridLineColorChanged(object sender, EventArgs e) { - Invalidate(layout.Data); - } - private void GridLineStyleChanged(object sender, EventArgs e) { - this.myGridTable.ResetRelationsUI(); - Invalidate(layout.Data); - } - private void HeaderBackColorChanged(object sender, EventArgs e) { - if (layout.RowHeadersVisible) - Invalidate(layout.RowHeaders); - if (layout.ColumnHeadersVisible) - Invalidate(layout.ColumnHeaders); - Invalidate(layout.TopLeftHeader); - } - private void HeaderFontChanged(object sender, EventArgs e) { - RecalculateFonts(); - PerformLayout(); - Invalidate(layout.Inside); } - private void HeaderForeColorChanged(object sender, EventArgs e) { - if (layout.RowHeadersVisible) - Invalidate(layout.RowHeaders); - if (layout.ColumnHeadersVisible) - Invalidate(layout.ColumnHeaders); - Invalidate(layout.TopLeftHeader); + finally + { + gridState[GRIDSTATE_canFocus] = true; } - private void LinkColorChanged(object sender, EventArgs e) { - Invalidate(layout.Data); + + } + + /// + /// + /// Raises the + /// event. + /// + /// + protected override void OnHandleCreated(EventArgs e) + { + base.OnHandleCreated(e); + + // toolTipping + toolTipProvider = new DataGridToolTip(this); + toolTipProvider.CreateToolTipHandle(); + toolTipId = 0; + + PerformLayout(); + } + + /// + /// + /// Raises the + /// event. + /// + /// + protected override void OnHandleDestroyed(EventArgs e) + { + base.OnHandleDestroyed(e); + + // toolTipping + if (toolTipProvider != null) + { + toolTipProvider.Destroy(); + toolTipProvider = null; } - private void LinkHoverColorChanged(object sender, EventArgs e) { - Invalidate(layout.Data); + toolTipId = 0; + } + + /// + /// Raises the + /// event. + /// + protected override void OnEnter(EventArgs e) + { + if (gridState[GRIDSTATE_canFocus] && !gridState[GRIDSTATE_editControlChanging]) + { + if (Bound) + { + Edit(); + } + base.OnEnter(e); } - private void PreferredColumnWidthChanged(object sender, EventArgs e) { - // reset the dataGridRows - SetDataGridRows(null, this.DataGridRowsLength); - // layout the horizontal scroll bar - PerformLayout(); - // invalidate everything - Invalidate(); + } + + /// + /// Raises the + /// event. + /// + protected override void OnLeave(EventArgs e) + { + OnLeave_Grid(); + base.OnLeave(e); + } + + private void OnLeave_Grid() + { + gridState[GRIDSTATE_canFocus] = false; + try + { + EndEdit(); + if (this.listManager != null && !this.gridState[GRIDSTATE_editControlChanging]) + { + if (gridState[GRIDSTATE_inAddNewRow]) + { + // if the user did not type anything + // in the addNewRow, then cancel the currentedit + this.listManager.CancelCurrentEdit(); + // set the addNewRow back + DataGridRow[] localGridRows = this.DataGridRows; + localGridRows[DataGridRowsLength - 1] = new DataGridAddNewRow(this, this.myGridTable, DataGridRowsLength - 1); + SetDataGridRows(localGridRows, DataGridRowsLength); + } + else + { + // this.listManager.EndCurrentEdit(); + HandleEndCurrentEdit(); + } + } } - private void RowHeadersVisibleChanged(object sender, EventArgs e) { - layout.RowHeadersVisible = this.myGridTable == null ? false : this.myGridTable.RowHeadersVisible; - PerformLayout(); - InvalidateInside(); + finally + { + gridState[GRIDSTATE_canFocus] = true; + // inAddNewRow should be set to false if the control was + // not changing + if (!this.gridState[GRIDSTATE_editControlChanging]) + gridState[GRIDSTATE_inAddNewRow] = false; } - private void ColumnHeadersVisibleChanged(object sender, EventArgs e) { - layout.ColumnHeadersVisible = this.myGridTable == null ? false : this.myGridTable.ColumnHeadersVisible; - PerformLayout(); - InvalidateInside(); + } + + /// + /// + /// Raises the + /// event. + /// + /// + protected override void OnKeyDown(KeyEventArgs ke) + { + Debug.WriteLineIf(CompModSwitches.DataGridKeys.TraceVerbose, "DataGridKeys: OnKeyDown "); + base.OnKeyDown(ke); + ProcessGridKey(ke); + } + + /// + /// Raises the event. + /// + protected override void OnKeyPress(KeyPressEventArgs kpe) + { + Debug.WriteLineIf(CompModSwitches.DataGridKeys.TraceVerbose, "DataGridKeys: OnKeyPress " + TypeDescriptor.GetConverter(typeof(Keys)).ConvertToString(kpe.KeyChar)); + + base.OnKeyPress(kpe); + GridColumnStylesCollection coll = this.myGridTable.GridColumnStyles; + if (coll != null && currentCol > 0 && currentCol < coll.Count) + { + if (!coll[currentCol].ReadOnly) + if (kpe.KeyChar > 32) + { + Edit(new string(new char[] { (char)kpe.KeyChar })); + } } - private void RowHeaderWidthChanged(object sender, EventArgs e) { - if (layout.RowHeadersVisible) + } + + /// + /// Raises the event. + /// + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + + gridState[GRIDSTATE_childLinkFocused] = false; + gridState[GRIDSTATE_dragging] = false; + if (listManager == null) + return; + + HitTestInfo location = HitTest(e.X, e.Y); + Keys nModifier = ModifierKeys; + bool isControlDown = (nModifier & Keys.Control) == Keys.Control && (nModifier & Keys.Alt) == 0; + bool isShiftDown = (nModifier & Keys.Shift) == Keys.Shift; + + // Only left clicks for now + if (e.Button != MouseButtons.Left) + return; + + // Check column resize + if (location.type == HitTestType.ColumnResize) + { + if (e.Clicks > 1) { - PerformLayout(); - InvalidateInside(); + ColAutoResize(location.col); } + else + ColResizeBegin(e, location.col); + return; } - private void AllowSortingChanged(object sender, EventArgs e) { - if (!this.myGridTable.AllowSorting && this.listManager != null) { - IList list = this.listManager.List; - if (list is IBindingList) - ((IBindingList) list).RemoveSort(); + + // Check row resize + if (location.type == HitTestType.RowResize) + { + if (e.Clicks > 1) + { + RowAutoResize(location.row); } - } - - private void DataSource_RowChanged(object sender, EventArgs ea) { - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: DataSource_RowChanged"); - // it may be the case that our cache was not updated - // to the latest changes in the list : CurrentChanged is fired before - // ListChanged. - // So invalidate the row if there is something to invalidate - DataGridRow[] rows = this.DataGridRows; - if (currentRow < this.DataGridRowsLength) { - InvalidateRow(currentRow); + else + { + RowResizeBegin(e, location.row); } + return; } - - /// - /// - /// Fired by the DataSource when row position moves. - /// - /// - private void DataSource_PositionChanged(object sender, EventArgs ea) { - #if DEBUG - inDataSource_PositionChanged = true; - #endif - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: DataSource_PositionChanged to " + listManager.Position.ToString(CultureInfo.InvariantCulture)); - // the grid will get the PositionChanged event - // before the OnItemChanged event when a row will be deleted in the backEnd; - // we still want to keep the old rows when the user deletes the rows using the grid - // and we do not want to do the same work twice when the user adds a row via the grid - if (this.DataGridRowsLength > this.listManager.Count + (policy.AllowAdd?1:0) && !gridState[GRIDSTATE_inDeleteRow]) { - Debug.Assert(!gridState[GRIDSTATE_inAddNewRow] && !gridState[GRIDSTATE_inListAddNew], "how can the list decrease when we are adding a row?"); - RecreateDataGridRows(); - } - if (this.ListManager.Position != currentRow) { - CurrentCell = new DataGridCell(listManager.Position, currentCol); - - } - #if DEBUG - inDataSource_PositionChanged = false; - #endif + + // Check column headers + if (location.type == HitTestType.ColumnHeader) + { + trackColumnHeader = this.myGridTable.GridColumnStyles[location.col].PropertyDescriptor; + return; } - - internal void DataSource_MetaDataChanged(object sender, EventArgs e) { - MetaDataChanged(); + + if (location.type == HitTestType.Caption) + { + Rectangle captionRect = layout.Caption; + caption.MouseDown(e.X - captionRect.X, e.Y - captionRect.Y); + return; } - - private bool DataGridSourceHasErrors() - { - if (this.listManager == null) - return false; - for (int i = 0; i < this.listManager.Count; i++) + + if (layout.Data.Contains(e.X, e.Y) || layout.RowHeaders.Contains(e.X, e.Y)) + { + // Check with the row underneath the mouse + int row = GetRowFromY(e.Y); + if (row > -1) { - object errObj = this.listManager[i]; - if (errObj is IDataErrorInfo) + Point p = NormalizeToRow(e.X, e.Y, row); + DataGridRow[] localGridRows = DataGridRows; + if (localGridRows[row].OnMouseDown(p.X, p.Y, + layout.RowHeaders, + isRightToLeft())) { - string errString = ((IDataErrorInfo)errObj).Error; - if (errString != null && errString.Length != 0) - return true; + CommitEdit(); + + // possibly this was the last row, so then the link may not + // be visible. make it visible, by making the row visible. + // how can we be sure that the user did not click + // on a relationship and navigated to the child rows? + // check if the row is expanded: if the row is expanded, then the user clicked + // on the node. when we navigate to child rows the rows are recreated + // and are initially collapsed + localGridRows = this.DataGridRows; + if (row < DataGridRowsLength && (localGridRows[row] is DataGridRelationshipRow) && ((DataGridRelationshipRow)localGridRows[row]).Expanded) + EnsureVisible(row, 0); + + // show the edit box + // + Edit(); + return; } } - return false; } - - private void TableStylesCollectionChanged(object sender, CollectionChangeEventArgs ccea) { - // if the users changed the collection of tableStyles - if (sender != this.dataGridTables) - return; - if (this.listManager == null) - return; - - if (ccea.Action == CollectionChangeAction.Add) { - DataGridTableStyle tableStyle = (DataGridTableStyle) ccea.Element; - if (this.listManager.GetListName().Equals(tableStyle.MappingName)) { - Debug.Assert(this.myGridTable.IsDefault, "if the table is not default, then it had a name. how can one add another table to the collection w/ the same name and not throw an exception"); - SetDataGridTable(tableStyle, true); // true for forcing column creation - SetDataGridRows(null, 0); - } - } else if (ccea.Action == CollectionChangeAction.Remove) { - DataGridTableStyle tableStyle = (DataGridTableStyle) ccea.Element; - if (this.myGridTable.MappingName.Equals(tableStyle.MappingName)) { - Debug.Assert(this.myGridTable.IsDefault, "if the table is not default, then it had a name. how can one add another table to the collection w/ the same name and not throw an exception"); - this.defaultTableStyle.GridColumnStyles.ResetDefaultColumnCollection(); - SetDataGridTable(this.defaultTableStyle, true); // true for forcing column creation - SetDataGridRows(null, 0); - } - } else { - Debug.Assert(ccea.Action == CollectionChangeAction.Refresh, "what else is possible?"); - // we have to search to see if the collection of table styles contains one - // w/ the same name as the list in the dataGrid - - DataGridTableStyle newGridTable = this.dataGridTables[listManager.GetListName()]; - if (newGridTable == null) { - if (!this.myGridTable.IsDefault) { - // get rid of the old gridColumns - this.defaultTableStyle.GridColumnStyles.ResetDefaultColumnCollection(); - SetDataGridTable(this.defaultTableStyle, true); // true for forcing column creation - SetDataGridRows(null, 0); - } - } else { - SetDataGridTable(newGridTable, true); // true for forcing column creation - SetDataGridRows(null, 0); + + // Check row headers + // + if (location.type == HitTestType.RowHeader) + { + EndEdit(); + if (!(DataGridRows[location.row] is DataGridAddNewRow)) + { + int savedCurrentRow = this.currentRow; + CurrentCell = new DataGridCell(location.row, currentCol); + if (location.row != savedCurrentRow && + this.currentRow != location.row && + this.currentRow == savedCurrentRow) + { + // The data grid was not able to move away from its previous current row. + // Be defensive and don't select the row. + return; } } - } - - private void DataSource_ItemChanged(object sender, ItemChangedEventArgs ea) { - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: DataSource_ItemChanged at index " + ea.Index.ToString(CultureInfo.InvariantCulture)); - - // if ea.Index == -1, then we invalidate all rows. - if (ea.Index == -1) + + if (isControlDown) { - DataSource_Changed(sender, EventArgs.Empty); - /* - // if there are rows which are invisible, it is more efficient to invalidata layout.Data - if (numVisibleRows <= dataGridRowsLength) - Invalidate(layout.Data); + if (IsSelected(location.row)) + UnSelect(location.row); else - { - Debug.Assert(firstVisibleRow == 0, "if all rows are visible, then how come that first row is not visible?"); - for (int i = 0; i < numVisibleRows; i++) - InvalidateRow(firstVisibleRow + numVisibleRows); - } - */ + Select(location.row); } - else + else { - // let's see how we are doing w/ the errors - object errObj = this.listManager[ea.Index]; - bool oldListHasErrors = ListHasErrors; - if (errObj is IDataErrorInfo) + if (lastRowSelected == -1 || !isShiftDown) + { + ResetSelection(); + Select(location.row); + } + else { - if (((IDataErrorInfo)errObj).Error.Length != 0) - ListHasErrors = true; - else if (ListHasErrors) + int lowerRow = Math.Min(lastRowSelected, location.row); + int upperRow = Math.Max(lastRowSelected, location.row); + + // we need to reset the old SelectedRows. + // ResetSelection() will also reset lastRowSelected, so we + // need to save it + int saveLastRowSelected = lastRowSelected; + ResetSelection(); + lastRowSelected = saveLastRowSelected; + + DataGridRow[] rows = DataGridRows; + for (int i = lowerRow; i <= upperRow; i++) { - // maybe there was an error that now is fixed - ListHasErrors = DataGridSourceHasErrors(); + rows[i].Selected = true; + numSelectedRows++; } + + // hide the edit box: + // + EndEdit(); + return; } - - // Invalidate the row only if we did not change the ListHasErrors - if (oldListHasErrors == ListHasErrors) - InvalidateRow(ea.Index); - - // we need to update the edit box: - // we update the text in the edit box only when the currentRow - // equals the ea.Index - if (editColumn != null && ea.Index == currentRow) - editColumn.UpdateUI(this.ListManager, ea.Index, null); } + + lastRowSelected = location.row; + // OnRowHeaderClick(EventArgs.Empty); + return; } - - protected virtual void OnBorderStyleChanged(EventArgs e) { - EventHandler eh = Events[EVENT_BORDERSTYLECHANGED] as EventHandler; - if (eh != null) { - eh(this, e); - } + + // Check parentRows + // + if (location.type == HitTestType.ParentRows) + { + EndEdit(); + parentRows.OnMouseDown(e.X, e.Y, isRightToLeft()); } - - protected virtual void OnCaptionVisibleChanged(EventArgs e) { - EventHandler eh = Events[EVENT_CAPTIONVISIBLECHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + + // Check cell clicks + // + if (location.type == HitTestType.Cell) + { + if (this.myGridTable.GridColumnStyles[location.col].MouseDown(location.row, e.X, e.Y)) + return; + DataGridCell target = new DataGridCell(location.row, location.col); + if (policy.AllowEdit && CurrentCell.Equals(target)) + { + ResetSelection(); + // + // what if only a part of the current cell is visible? + // + EnsureVisible(currentRow, currentCol); + Edit(); } - } - - protected virtual void OnCurrentCellChanged(EventArgs e) { - EventHandler eh = Events[EVENT_CURRENTCELLCHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + else + { + ResetSelection(); + CurrentCell = target; } } - - /* - /// - /// - /// Raises the event. - /// - /// - /// - /// An that contains the event data. - /// - /// - /// - /// Raising an event invokes the event-handling method through a delegate. For an - /// overview, see . - /// - /// When overriding in an - /// derived class, be sure to call the base class's method. - /// - protected void OnColumnHeaderClick(EventArgs e) { - RaiseEvent(EVENT_COLUMNHEADERCLICK, e); + } + + /// + /// Creates the + /// event. + /// + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + if (oldRow != -1) + { + DataGridRow[] localGridRows = DataGridRows; + localGridRows[oldRow].OnMouseLeft(layout.RowHeaders, isRightToLeft()); } - */ - - protected virtual void OnFlatModeChanged(EventArgs e) { - EventHandler eh = Events[EVENT_FLATMODECHANGED] as EventHandler; - if (eh != null) { - eh(this, e); - } + if (gridState[GRIDSTATE_overCaption]) + { + caption.MouseLeft(); } - - protected virtual void OnBackgroundColorChanged(EventArgs e) { - EventHandler eh = Events[EVENT_BACKGROUNDCOLORCHANGED] as EventHandler; - if (eh != null) { - eh(this, e); - } + // when the mouse leaves the grid control, reset the cursor to arrow + Cursor = null; + } + + internal void TextBoxOnMouseWheel(MouseEventArgs e) + { + this.OnMouseWheel(e); + } + + /// + /// Raises the + /// event. + /// + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + if (listManager == null) + return; + + HitTestInfo location = HitTest(e.X, e.Y); + + bool alignToRight = isRightToLeft(); + + // We need to give UI feedback when the user is resizing a column + if (gridState[GRIDSTATE_trackColResize]) + { + ColResizeMove(e); } - - protected virtual void OnAllowNavigationChanged(EventArgs e) { - EventHandler eh = Events[EVENT_ALLOWNAVIGATIONCHANGED] as EventHandler; - if (eh != null) { - eh(this, e); - } + + if (gridState[GRIDSTATE_trackRowResize]) + { + RowResizeMove(e); } - - protected virtual void OnParentRowsVisibleChanged(EventArgs e) { - EventHandler eh = Events[EVENT_PARENTROWSVISIBLECHANGED] as EventHandler; - if (eh != null) { - eh(this, e); - } + + if (gridState[GRIDSTATE_trackColResize] || location.type == HitTestType.ColumnResize) + { + Cursor = Cursors.SizeWE; + return; } - - protected virtual void OnParentRowsLabelStyleChanged(EventArgs e) { - EventHandler eh = Events[EVENT_PARENTROWSLABELSTYLECHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + else if (gridState[GRIDSTATE_trackRowResize] || location.type == HitTestType.RowResize) + { + Cursor = Cursors.SizeNS; + return; + } + else + { + Cursor = null; + } + + if ((layout.Data.Contains(e.X, e.Y) + || (layout.RowHeadersVisible && layout.RowHeaders.Contains(e.X, e.Y)))) + { + // && (isNavigating || isEditing)) { + DataGridRow[] localGridRows = DataGridRows; + // If we are over a row, let it know about the mouse move. + int rowOver = GetRowFromY(e.Y); + // set the dragging bit: + if (lastRowSelected != -1 && !gridState[GRIDSTATE_dragging]) + { + int topRow = GetRowTop(lastRowSelected); + int bottomRow = topRow + localGridRows[lastRowSelected].Height; + int dragHeight = SystemInformation.DragSize.Height; + gridState[GRIDSTATE_dragging] = ((e.Y - topRow < dragHeight && topRow - e.Y < dragHeight) || (e.Y - bottomRow < dragHeight && bottomRow - e.Y < dragHeight)); } + if (rowOver > -1) + { + Point p = NormalizeToRow(e.X, e.Y, rowOver); + if (!localGridRows[rowOver].OnMouseMove(p.X, p.Y, layout.RowHeaders, alignToRight) && gridState[GRIDSTATE_dragging]) + { + // if the row did not use this, see if selection can use it + MouseButtons mouse = MouseButtons; + if (lastRowSelected != -1 && (mouse & MouseButtons.Left) == MouseButtons.Left + && !(((Control.ModifierKeys & Keys.Control) == Keys.Control) && (Control.ModifierKeys & Keys.Alt) == 0)) + { + // ResetSelection() will reset the lastRowSelected too + // + int saveLastRowSelected = lastRowSelected; + ResetSelection(); + lastRowSelected = saveLastRowSelected; + + int lowerRow = Math.Min(lastRowSelected, rowOver); + int upperRow = Math.Max(lastRowSelected, rowOver); + + DataGridRow[] rows = DataGridRows; + for (int i = lowerRow; i <= upperRow; i++) + { + rows[i].Selected = true; + numSelectedRows++; + } + } + } + } + + if (oldRow != rowOver && oldRow != -1) + { + localGridRows[oldRow].OnMouseLeft(layout.RowHeaders, alignToRight); + } + oldRow = rowOver; } - - protected virtual void OnReadOnlyChanged(EventArgs e) { - EventHandler eh = Events[EVENT_READONLYCHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + + // check parentRows + // + if (location.type == HitTestType.ParentRows) + { + if (parentRows != null) + { + parentRows.OnMouseMove(e.X, e.Y); } } - - /// - /// - /// Raises the - /// event. - /// - /// - protected void OnNavigate(NavigateEventArgs e) { - if (onNavigate != null) - onNavigate(this, e); + + if (location.type == HitTestType.Caption) + { + gridState[GRIDSTATE_overCaption] = true; + Rectangle captionRect = layout.Caption; + caption.MouseOver(e.X - captionRect.X, e.Y - captionRect.Y); + return; } - - /* - /// - /// - /// Raises the event. - /// - /// - protected void OnColumnResize(EventArgs e) { - RaiseEvent(EVENT_COLUMNRESIZE, e); + else + { + if (gridState[GRIDSTATE_overCaption]) + { + gridState[GRIDSTATE_overCaption] = false; + caption.MouseLeft(); + } } - - internal void OnLinkClick(EventArgs e) { - RaiseEvent(EVENT_LINKCLICKED, e); + } + + /// + /// Raises the event. + /// + protected override void OnMouseUp(MouseEventArgs e) + { + base.OnMouseUp(e); + gridState[GRIDSTATE_dragging] = false; + if (listManager == null || myGridTable == null) + return; + if (gridState[GRIDSTATE_trackColResize]) + { + ColResizeEnd(e); } - */ - - internal void OnNodeClick(EventArgs e) { - // if we expanded/collapsed the RelationshipRow - // then we need to layout the vertical scroll bar - // - PerformLayout(); - - - // also, we need to let the hosted edit control that its - // boundaries possibly changed. do this with a call to Edit() - // do this only if the firstVisibleColumn is the editColumn - // - GridColumnStylesCollection columns = this.myGridTable.GridColumnStyles; - if (firstVisibleCol > -1 && firstVisibleCol < columns.Count && columns[firstVisibleCol] == editColumn) - Edit(); - - // Raise the event for the event listeners - EventHandler handler = (EventHandler)Events[EVENT_NODECLICKED]; - if (handler != null) { - handler(this, e); - } + + if (gridState[GRIDSTATE_trackRowResize]) + { + RowResizeEnd(e); } - - /// - /// Raises the event. - /// - protected void OnRowHeaderClick(EventArgs e) { - if (onRowHeaderClick != null) - onRowHeaderClick(this, e); + + gridState[GRIDSTATE_trackColResize] = false; + gridState[GRIDSTATE_trackRowResize] = false; + + HitTestInfo ci = HitTest(e.X, e.Y); + if ((ci.type & HitTestType.Caption) == HitTestType.Caption) + { + caption.MouseUp(e.X, e.Y); } - - /// - /// - /// Raises the event. - /// - /// - protected void OnScroll(EventArgs e) { - // reset the toolTip information - if (ToolTipProvider != null) - ResetToolTip(); - - EventHandler handler = (EventHandler)Events[EVENT_SCROLL]; - if (handler != null) { - handler(this, e); + + // Check column headers + if (ci.type == HitTestType.ColumnHeader) + { + PropertyDescriptor prop = this.myGridTable.GridColumnStyles[ci.col].PropertyDescriptor; + if (prop == trackColumnHeader) + { + ColumnHeaderClicked(trackColumnHeader); } } - - /// - /// - /// Listens - /// for the horizontal scrollbar's scroll - /// event. - /// - /// - protected virtual void GridHScrolled(object sender, ScrollEventArgs se) { - if (!Enabled) - return; - if (DataSource == null) { - Debug.Fail("Horizontal Scrollbar should be disabled without a DataSource."); + + trackColumnHeader = null; + } + + /// + /// Raises the event. + /// + protected override void OnMouseWheel(MouseEventArgs e) + { + base.OnMouseWheel(e); + + if (e is HandledMouseEventArgs) + { + if (((HandledMouseEventArgs)e).Handled) + { + // The application event handler handled the scrolling - don't do anything more. return; } - - gridState[GRIDSTATE_isScrolling] = true; - - #if DEBUG - - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "DataGridScrolling: in GridHScrolled: the scroll event type:"); - switch (se.Type) + ((HandledMouseEventArgs)e).Handled = true; + } + + bool wheelingDown = true; + if ((ModifierKeys & Keys.Control) != 0) + wheelingDown = false; + + if (listManager == null || myGridTable == null) + return; + ScrollBar sb = wheelingDown ? vertScrollBar : horizScrollBar; + if (!sb.Visible) + return; + + // so we scroll. we have to know this, cause otherwise we will call EndEdit + // and that would be wrong. + gridState[GRIDSTATE_isScrolling] = true; + wheelDelta += e.Delta; + float movePerc = (float)wheelDelta / (float)NativeMethods.WHEEL_DELTA; + int move = (int)((float)SystemInformation.MouseWheelScrollLines * movePerc); + if (move != 0) + { + wheelDelta = 0; + Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: OnMouseWheel move=" + move.ToString(CultureInfo.InvariantCulture)); + if (wheelingDown) { - case ScrollEventType.SmallIncrement: - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "small increment"); - break; - case ScrollEventType.SmallDecrement: - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "small decrement"); - break; - case ScrollEventType.LargeIncrement: - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "Large decrement"); - break; - case ScrollEventType.LargeDecrement: - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "small decrement"); - break; - case ScrollEventType.ThumbPosition: - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "Thumb Position"); - break; - case ScrollEventType.ThumbTrack: - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "Thumb Track"); - break; - case ScrollEventType.First: - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "First"); - break; - case ScrollEventType.Last: - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "Last"); - break; - case ScrollEventType.EndScroll: - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "EndScroll"); - break; + int newRow = firstVisibleRow - move; + newRow = Math.Max(0, Math.Min(newRow, DataGridRowsLength - numTotallyVisibleRows)); + ScrollDown(newRow - firstVisibleRow); } - - #endif // DEBUG - - if (se.Type == ScrollEventType.SmallIncrement || - se.Type == ScrollEventType.SmallDecrement) + else { - int dCols = (se.Type == ScrollEventType.SmallIncrement)? 1:-1; - if (se.Type == ScrollEventType.SmallDecrement && this.negOffset == 0) { - GridColumnStylesCollection cols = this.myGridTable.GridColumnStyles; - // if the column before the first visible column has width == 0 then skip it - for (int i = this.firstVisibleCol - 1; i >= 0 && cols[i].Width == 0; i --) { - dCols --; - } - } - - if (se.Type == ScrollEventType.SmallIncrement && this.negOffset == 0) { - GridColumnStylesCollection cols = this.myGridTable.GridColumnStyles; - for (int i = this.firstVisibleCol; i > -1 && i < cols.Count && cols[i].Width == 0; i ++) { - dCols ++; - } - } - - ScrollRight(dCols); - se.NewValue = HorizontalOffset; + int newValue = horizScrollBar.Value + (move < 0 ? 1 : -1) * horizScrollBar.LargeChange; + HorizontalOffset = newValue; } - else if (se.Type != ScrollEventType.EndScroll) + } + + gridState[GRIDSTATE_isScrolling] = false; + } + + /// + /// Raises the + /// event. + /// + protected override void OnPaint(PaintEventArgs pe) + { + try + { + CheckHierarchyState(); + + if (this.layout.dirty) + ComputeLayout(); + + Graphics g = pe.Graphics; + + Region clipRegion = g.Clip; + if (layout.CaptionVisible) + caption.Paint(g, layout.Caption, isRightToLeft()); + + if (layout.ParentRowsVisible) { - HorizontalOffset = se.NewValue; + Debug.WriteLineIf(CompModSwitches.DataGridParents.TraceVerbose, "DataGridParents: Painting ParentRows " + layout.ParentRows.ToString()); + g.FillRectangle(SystemBrushes.AppWorkspace, layout.ParentRows); + parentRows.Paint(g, layout.ParentRows, isRightToLeft()); } - this.gridState[GRIDSTATE_isScrolling] = false; + Rectangle gridRect = layout.Data; + if (layout.RowHeadersVisible) + gridRect = Rectangle.Union(gridRect, layout.RowHeaders); + if (layout.ColumnHeadersVisible) + gridRect = Rectangle.Union(gridRect, layout.ColumnHeaders); + + g.SetClip(gridRect); + PaintGrid(g, gridRect); + g.Clip = clipRegion; + clipRegion.Dispose(); + PaintBorder(g, layout.ClientRectangle); + + g.FillRectangle(DefaultHeaderBackBrush, layout.ResizeBoxRect); + + base.OnPaint(pe); // raise paint event } - - /// - /// - /// Listens - /// for the vertical scrollbar's scroll event. - /// - /// - protected virtual void GridVScrolled(object sender, ScrollEventArgs se) { - if (!Enabled) - return; - if (DataSource == null) { - Debug.Fail("Vertical Scrollbar should be disabled without a DataSource."); - return; + catch + { + // at runtime we will rethrow the exception + if (this.Site == null || !this.Site.DesignMode) + throw; + gridState[GRIDSTATE_exceptionInPaint] = true; + try + { + RTLAwareMessageBox.Show(null, SR.DataGridExceptionInPaint, null, MessageBoxButtons.OK, + MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); + + if (this.Visible) + BeginUpdateInternal(); + + ResetParentRows(); + + Set_ListManager(null, string.Empty, true); } - - gridState[GRIDSTATE_isScrolling] = true; - - try { - se.NewValue = Math.Min(se.NewValue, DataGridRowsLength - numTotallyVisibleRows); - int dRows = se.NewValue - firstVisibleRow; - ScrollDown(dRows); - } finally { - gridState[GRIDSTATE_isScrolling] = false; + finally + { + gridState[GRIDSTATE_exceptionInPaint] = false; + if (this.Visible) + EndUpdateInternal(); } } - - private void HandleEndCurrentEdit() { - int currentRowSaved = currentRow; - int currentColSaved = currentCol; + } - string errorMessage = null; + // Since Win32 only invalidates the area that gets uncovered, + // we have to manually invalidate the old border area + /// + /// Raises the event. + /// + protected override void OnResize(EventArgs e) + { + Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: OnResize"); - try { - listManager.EndCurrentEdit(); - } - catch (Exception e) { - errorMessage = e.Message; - } + if (layout.CaptionVisible) + Invalidate(layout.Caption); + if (layout.ParentRowsVisible) + parentRows.OnResize(layout.ParentRows); - if (errorMessage != null) { - DialogResult result = RTLAwareMessageBox.Show(null, string.Format(SR.DataGridPushedIncorrectValueIntoColumn, - errorMessage), SR.DataGridErrorMessageBoxCaption, MessageBoxButtons.YesNo, - MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); - - if (result == DialogResult.Yes) { - currentRow = currentRowSaved; - currentCol = currentColSaved; - Debug.Assert(currentRow == ListManager.Position || listManager.Position == -1, "the position in the list manager (" + ListManager.Position + ") is out of sync with the currentRow (" + currentRow + ")" + " and the exception is '" + errorMessage + "'"); - // also, make sure that we get the row selector on the currentrow, too - InvalidateRowHeader(currentRow); - Edit(); - } else { - // if the user committed a row that used to be addNewRow and the backEnd rejects it, - // and then it tries to navigate down then we should stay in the addNewRow - // in this particular scenario, CancelCurrentEdit will cause the last row to be deleted, - // and this will ultimately call InvalidateRow w/ a row number larger than the number of rows - // so set the currentRow here: - Debug.Assert(result == DialogResult.No, "we only put cancel and ok on the error message box"); - this.listManager.PositionChanged -= positionChangedHandler; - this.listManager.CancelCurrentEdit(); - this.listManager.Position = currentRow; - this.listManager.PositionChanged += positionChangedHandler; - } - } + int borderWidth = BorderWidth; + Rectangle right; + Rectangle bottom; + Rectangle oldClientRectangle = layout.ClientRectangle; + + right = new Rectangle(oldClientRectangle.X + oldClientRectangle.Width - borderWidth, + oldClientRectangle.Y, + borderWidth, + oldClientRectangle.Height); + bottom = new Rectangle(oldClientRectangle.X, + oldClientRectangle.Y + oldClientRectangle.Height - borderWidth, + oldClientRectangle.Width, + borderWidth); + + Rectangle newClientRectangle = this.ClientRectangle; + if (newClientRectangle.Width != oldClientRectangle.Width) + { + Invalidate(right); + right = new Rectangle(newClientRectangle.X + newClientRectangle.Width - borderWidth, + newClientRectangle.Y, + borderWidth, + newClientRectangle.Height); + Invalidate(right); } - - /// - /// - /// Listens - /// for the caption's back button clicked event. - /// - /// - protected void OnBackButtonClicked(object sender, EventArgs e) { - NavigateBack(); - - EventHandler handler = (EventHandler)Events[EVENT_BACKBUTTONCLICK]; - if (handler != null) handler(this,e); + if (newClientRectangle.Height != oldClientRectangle.Height) + { + Invalidate(bottom); + bottom = new Rectangle(newClientRectangle.X, + newClientRectangle.Y + newClientRectangle.Height - borderWidth, + newClientRectangle.Width, + borderWidth); + Invalidate(bottom); } - - protected override void OnBackColorChanged(EventArgs e) { - backBrush = new SolidBrush(BackColor); + + //also, invalidate the ResizeBoxRect + if (!this.layout.ResizeBoxRect.IsEmpty) + Invalidate(layout.ResizeBoxRect); + + layout.ClientRectangle = newClientRectangle; + + int oldFirstVisibleRow = firstVisibleRow; + base.OnResize(e); + if (isRightToLeft() || oldFirstVisibleRow != firstVisibleRow) Invalidate(); - - base.OnBackColorChanged(e); + } + + internal void OnRowHeightChanged(DataGridRow row) + { + ClearRegionCache(); + int cy = GetRowTop(row.RowNumber); + if (cy > 0) + { + Rectangle refresh = new Rectangle(); + refresh.Y = cy; + refresh.X = layout.Inside.X; + refresh.Width = layout.Inside.Width; + refresh.Height = layout.Inside.Bottom - cy; + Invalidate(refresh); } - - protected override void OnBindingContextChanged(EventArgs e) { - if (this.DataSource != null && !gridState[GRIDSTATE_inSetListManager]) - try { - Set_ListManager(this.DataSource, this.DataMember, true, false); // we do not want to create columns - // if the columns are already created - // the grid should not rely on OnBindingContextChanged - // to create columns. - } catch { - // at runtime we will rethrow the exception - if (this.Site == null || !this.Site.DesignMode) - throw; - - RTLAwareMessageBox.Show(null, SR.DataGridExceptionInPaint, null, - MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); - - if (this.Visible) BeginUpdateInternal(); - - ResetParentRows(); - - Set_ListManager(null, string.Empty, true); - if (this.Visible) EndUpdateInternal(); - } - base.OnBindingContextChanged(e); + } + + internal void ParentRowsDataChanged() + { + Debug.Assert(originalState != null, "how can we get a list changed event from another listmanager/list while not navigating"); + + // do the reset work that is done in SetDataBindings, set_DataSource, set_DataMember; + parentRows.Clear(); + caption.BackButtonActive = caption.DownButtonActive = caption.BackButtonVisible = false; + caption.SetDownButtonDirection(!layout.ParentRowsVisible); + object dSource = originalState.DataSource; + string dMember = originalState.DataMember; + // we don't need to set the GRIDSTATE_metaDataChanged bit, cause + // the listManager from the originalState should be different from the current listManager + // + // set the originalState to null so that Set_ListManager knows that + // it has to unhook the MetaDataChanged events + originalState = null; + Set_ListManager(dSource, dMember, true); + } + + + // =------------------------------------------------------------------ + // = Methods + // =------------------------------------------------------------------ + + private void AbortEdit() + { + Debug.WriteLineIf(CompModSwitches.DataGridEditing.TraceVerbose, "DataGridEditing: \t! AbortEdit"); + Debug.Assert(gridState[GRIDSTATE_isEditing], "Can't abort an edit that is not happening!"); + + // the same rules from editColumn.OnEdit + // while changing the editControl's visibility, do not + // PerformLayout on the entire DataGrid + gridState[GRIDSTATE_editControlChanging] = true; + + editColumn.Abort(editRow.RowNumber); + + // reset the editControl flag: + gridState[GRIDSTATE_editControlChanging] = false; + + gridState[GRIDSTATE_isEditing] = false; + editRow = null; + editColumn = null; + } + + /// + /// Occurs when the user navigates to a new table. + /// + [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.DataGridNavigateEventDescr))] + public event NavigateEventHandler Navigate + { + add => onNavigate += value; + remove => onNavigate -= value; + } + + /// + /// Occurs when a row header is clicked. + /// + protected event EventHandler RowHeaderClick + { + add => onRowHeaderClick += value; + remove => onRowHeaderClick -= value; + } + + /// + /// + /// Adds an event handler for the 'System.Windows.Forms.DataGrid.OnNodeClick' + /// event. + /// + /// + [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.DataGridNodeClickEventDescr))] + internal event EventHandler NodeClick + { + add => Events.AddHandler(EVENT_NODECLICKED, value); + remove => Events.RemoveHandler(EVENT_NODECLICKED, value); + } + + /// + /// + /// Occurs when the user scrolls the control. + /// + /// + [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.DataGridScrollEventDescr))] + public event EventHandler Scroll + { + add => Events.AddHandler(EVENT_SCROLL, value); + remove => Events.RemoveHandler(EVENT_SCROLL, value); + } + + public override ISite Site + { + get + { + return base.Site; } - - protected virtual void OnDataSourceChanged(EventArgs e) { - EventHandler eh = Events[EVENT_DATASOURCECHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + set + { + ISite temp = this.Site; + base.Site = value; + if (value != temp && !Disposing) + { + // we should site the tables and the columns + // only when our site changes + SubObjectsSiteChange(false); + SubObjectsSiteChange(true); } } - - /// - /// - /// Listens for - /// the caption's down button clicked event. - /// - /// - protected void OnShowParentDetailsButtonClicked(object sender, EventArgs e) { - // we need to fire the ParentRowsVisibleChanged event - // and the ParentRowsVisible property just calls SetParentRowsVisibility and - // then fires the event. - this.ParentRowsVisible = !caption.ToggleDownButtonDirection(); - - EventHandler handler = (EventHandler)Events[EVENT_DOWNBUTTONCLICK]; - if (handler != null) handler(this,e); - } - - protected override void OnForeColorChanged(EventArgs e) { - foreBrush = new SolidBrush(ForeColor); - Invalidate(); - - base.OnForeColorChanged(e); - } - - protected override void OnFontChanged(EventArgs e) { - // let the caption know about the event changed - // - this.Caption.OnGridFontChanged(); - RecalculateFonts(); - RecreateDataGridRows(); - // get all the rows in the parentRows stack, and modify their height - if (originalState != null) { - Debug.Assert(!parentRows.IsEmpty(), "if the originalState is not null, then parentRows contains at least one row"); - Stack parentStack = new Stack(); - // this is a huge performance hit: - // everytime we get/put something from/to - // the parentRows, the buttons in the dataGridCaption - // are invalidated - while (!parentRows.IsEmpty()) { - DataGridState dgs = parentRows.PopTop(); - int rowCount = dgs.DataGridRowsLength; - - for(int i = 0; i < rowCount; i++) { - // performance hit: this will cause to invalidate a bunch of - // stuff - - dgs.DataGridRows[i].Height = dgs.DataGridRows[i].MinimumRowHeight(dgs.GridColumnStyles); - } - parentStack.Push(dgs); - } - - while(parentStack.Count != 0) { - parentRows.AddParent((DataGridState)parentStack.Pop()); - } - } - - base.OnFontChanged(e); + } + + internal void AddNewRow() + { + EnsureBound(); + ResetSelection(); + // EndEdit(); + UpdateListManager(); + gridState[GRIDSTATE_inListAddNew] = true; + gridState[GRIDSTATE_inAddNewRow] = true; + try + { + this.ListManager.AddNew(); } - - /// - /// - /// Raises the - /// event. - /// - /// - protected override void OnPaintBackground(PaintEventArgs ebe) { - // null body + catch + { + gridState[GRIDSTATE_inListAddNew] = false; + gridState[GRIDSTATE_inAddNewRow] = false; + PerformLayout(); + InvalidateInside(); + throw; } - - /// - /// - /// Raises the event which - /// repositions controls - /// and updates scroll bars. - /// - /// - protected override void OnLayout(LayoutEventArgs levent) { - // if we get a OnLayout event while the editControl changes, then just - // ignore it - // - if (gridState[GRIDSTATE_editControlChanging]) return; - - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: OnLayout"); - base.OnLayout(levent); - - if (gridState[GRIDSTATE_layoutSuspended]) return; - - gridState[GRIDSTATE_canFocus] = false; - try { - if (IsHandleCreated) { - if (layout.ParentRowsVisible) - parentRows.OnLayout(); - - // reset the toolTip information - if (ToolTipProvider != null) - ResetToolTip(); - - ComputeLayout(); - } - } finally { - gridState[GRIDSTATE_canFocus] = true; - } - + gridState[GRIDSTATE_inListAddNew] = false; + } + + /// + /// Attempts to + /// put the grid into a state where editing is + /// allowed. + /// + public bool BeginEdit(DataGridColumnStyle gridColumn, int rowNumber) + { + if (this.DataSource == null || this.myGridTable == null) + return false; + + // We deny edit requests if we are already editing a cell. + if (gridState[GRIDSTATE_isEditing]) + return false; + else + { + int col = -1; + if ((col = this.myGridTable.GridColumnStyles.IndexOf(gridColumn)) < 0) + return false; + CurrentCell = new DataGridCell(rowNumber, col); + ResetSelection(); + Edit(); + return true; } - - /// - /// - /// Raises the - /// event. - /// - /// - protected override void OnHandleCreated(EventArgs e) { - base.OnHandleCreated(e); - - // toolTipping - toolTipProvider = new DataGridToolTip(this); - toolTipProvider.CreateToolTipHandle(); - toolTipId = 0; - - PerformLayout(); + } + + /// + /// Specifies the beginning of the initialization code. + /// + public void BeginInit() + { + if (inInit) + throw new InvalidOperationException(SR.DataGridBeginInit); + inInit = true; + } + + private Rectangle CalcRowResizeFeedbackRect(MouseEventArgs e) + { + Rectangle inside = layout.Data; + Rectangle r = new Rectangle(inside.X, e.Y, inside.Width, 3); + r.Y = Math.Min(inside.Bottom - 3, r.Y); + r.Y = Math.Max(r.Y, 0); + return r; + } + + private Rectangle CalcColResizeFeedbackRect(MouseEventArgs e) + { + Rectangle inside = layout.Data; + Rectangle r = new Rectangle(e.X, inside.Y, 3, inside.Height); + r.X = Math.Min(inside.Right - 3, r.X); + r.X = Math.Max(r.X, 0); + return r; + } + + private void CancelCursorUpdate() + { + Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: Requesting CancelEdit()"); + if (listManager != null) + { + EndEdit(); + listManager.CancelCurrentEdit(); } - - /// - /// - /// Raises the - /// event. - /// - /// - protected override void OnHandleDestroyed(EventArgs e) + } + + private void CheckHierarchyState() + { + if (checkHierarchy && this.listManager != null && this.myGridTable != null) { - base.OnHandleDestroyed(e); + if (myGridTable == null) + // there was nothing to check + return; - // toolTipping - if (toolTipProvider != null) { - toolTipProvider.Destroy(); - toolTipProvider = null; - } - toolTipId = 0; - } - - /// - /// Raises the - /// event. - /// - protected override void OnEnter(EventArgs e) { - if (gridState[GRIDSTATE_canFocus] && !gridState[GRIDSTATE_editControlChanging]) { - if (Bound) - { - Edit(); - } - base.OnEnter(e); - } - } - - /// - /// Raises the - /// event. - /// - protected override void OnLeave(EventArgs e) { - OnLeave_Grid(); - base.OnLeave(e); - } - - private void OnLeave_Grid() { - gridState[GRIDSTATE_canFocus] = false; - try { - EndEdit(); - if (this.listManager != null && !this.gridState[GRIDSTATE_editControlChanging]) { - if (gridState[GRIDSTATE_inAddNewRow]) { - // if the user did not type anything - // in the addNewRow, then cancel the currentedit - this.listManager.CancelCurrentEdit(); - // set the addNewRow back - DataGridRow[] localGridRows = this.DataGridRows; - localGridRows[DataGridRowsLength - 1] = new DataGridAddNewRow(this, this.myGridTable, DataGridRowsLength-1); - SetDataGridRows(localGridRows, DataGridRowsLength); - } else { - // this.listManager.EndCurrentEdit(); - HandleEndCurrentEdit(); - } - } - } finally { - gridState[GRIDSTATE_canFocus] = true; - // inAddNewRow should be set to false if the control was - // not changing - if (!this.gridState[GRIDSTATE_editControlChanging]) - gridState[GRIDSTATE_inAddNewRow] = false; - } - } - - /// - /// - /// Raises the - /// event. - /// - /// - protected override void OnKeyDown(KeyEventArgs ke) { - Debug.WriteLineIf(CompModSwitches.DataGridKeys.TraceVerbose, "DataGridKeys: OnKeyDown "); - base.OnKeyDown(ke); - ProcessGridKey(ke); - } - - /// - /// Raises the event. - /// - protected override void OnKeyPress(KeyPressEventArgs kpe) { - Debug.WriteLineIf(CompModSwitches.DataGridKeys.TraceVerbose, "DataGridKeys: OnKeyPress " + TypeDescriptor.GetConverter(typeof(Keys)).ConvertToString(kpe.KeyChar)); - - base.OnKeyPress(kpe); - GridColumnStylesCollection coll = this.myGridTable.GridColumnStyles; - if (coll != null && currentCol > 0 && currentCol < coll.Count) { - if (!coll[currentCol].ReadOnly) - if (kpe.KeyChar > 32) { - Edit(new string(new char [] { (char) kpe.KeyChar})); - } + for (int j = 0; j < myGridTable.GridColumnStyles.Count; j++) + { + DataGridColumnStyle gridColumn = myGridTable.GridColumnStyles[j]; } + + checkHierarchy = false; } - - /// - /// Raises the event. - /// - protected override void OnMouseDown(MouseEventArgs e) { - base.OnMouseDown(e); - - gridState[GRIDSTATE_childLinkFocused] = false; - gridState[GRIDSTATE_dragging] = false; - if (listManager == null) - return; - - HitTestInfo location = HitTest(e.X, e.Y); - Keys nModifier = ModifierKeys; - bool isControlDown = (nModifier & Keys.Control) == Keys.Control && (nModifier & Keys.Alt) == 0; - bool isShiftDown = (nModifier & Keys.Shift) == Keys.Shift; - - // Only left clicks for now - if (e.Button != MouseButtons.Left) - return; - - // Check column resize - if (location.type == HitTestType.ColumnResize) { - if (e.Clicks > 1) { - ColAutoResize(location.col); - } - else - ColResizeBegin(e, location.col); - return; + } + + /// + /// The DataGrid caches an array of rectangular areas + /// which represent the area which scrolls left to right. + /// This method is invoked whenever the DataGrid's + /// scrollable regions change in such a way as to require + /// a re-recalculation. + /// + private void ClearRegionCache() + { + cachedScrollableRegion = null; + } + + /// + /// Determines the best fit size for the given column. + /// + private void ColAutoResize(int col) + { + Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: ColAutoResize"); + EndEdit(); + CurrencyManager listManager = this.listManager; + if (listManager == null) + return; + + int size; + Graphics g = CreateGraphicsInternal(); + try + { + DataGridColumnStyle column = myGridTable.GridColumnStyles[col]; + string columnName = column.HeaderText; + + Font headerFont; + if (this.myGridTable.IsDefault) + headerFont = this.HeaderFont; + else + headerFont = this.myGridTable.HeaderFont; + size = (int)g.MeasureString(columnName, headerFont).Width + layout.ColumnHeaders.Height + 1; // The sort triangle's width is equal to it's height + int rowCount = listManager.Count; + for (int row = 0; row < rowCount; ++row) + { + object value = column.GetColumnValueAtRow(listManager, row); + int width = column.GetPreferredSize(g, value).Width; + if (width > size) + size = width; } - - // Check row resize - if (location.type == HitTestType.RowResize) + + if (column.Width != size) { - if (e.Clicks > 1) + column._width = size; + + ComputeVisibleColumns(); + + bool lastColumnIsLastTotallyVisibleCol = true; + if (this.lastTotallyVisibleCol != -1) { - RowAutoResize(location.row); + for (int i = this.lastTotallyVisibleCol + 1; i < this.myGridTable.GridColumnStyles.Count; i++) + { + if (this.myGridTable.GridColumnStyles[i].PropertyDescriptor != null) + { + lastColumnIsLastTotallyVisibleCol = false; + break; + } + } } else { - RowResizeBegin(e, location.row); - } - return; - } - - // Check column headers - if (location.type == HitTestType.ColumnHeader) { - trackColumnHeader = this.myGridTable.GridColumnStyles[location.col].PropertyDescriptor; - return; - } - - if (location.type == HitTestType.Caption) { - Rectangle captionRect = layout.Caption; - caption.MouseDown(e.X - captionRect.X, e.Y - captionRect.Y); - return; - } - - if (layout.Data.Contains(e.X, e.Y) || layout.RowHeaders.Contains(e.X, e.Y)) { - // Check with the row underneath the mouse - int row = GetRowFromY(e.Y); - if (row > -1) { - Point p = NormalizeToRow(e.X, e.Y, row); - DataGridRow[] localGridRows = DataGridRows; - if (localGridRows[row].OnMouseDown(p.X, p.Y, - layout.RowHeaders, - isRightToLeft())) { - CommitEdit(); - - // possibly this was the last row, so then the link may not - // be visible. make it visible, by making the row visible. - // how can we be sure that the user did not click - // on a relationship and navigated to the child rows? - // check if the row is expanded: if the row is expanded, then the user clicked - // on the node. when we navigate to child rows the rows are recreated - // and are initially collapsed - localGridRows = this.DataGridRows; - if (row < DataGridRowsLength && (localGridRows[row] is DataGridRelationshipRow) && ((DataGridRelationshipRow)localGridRows[row]).Expanded) - EnsureVisible(row, 0); - - // show the edit box - // - Edit(); - return; - } + lastColumnIsLastTotallyVisibleCol = false; } - } - - // Check row headers - // - if (location.type == HitTestType.RowHeader) { - EndEdit(); - if (!(DataGridRows[location.row] is DataGridAddNewRow)) { - int savedCurrentRow = this.currentRow; - CurrentCell = new DataGridCell(location.row, currentCol); - if (location.row != savedCurrentRow && - this.currentRow != location.row && - this.currentRow == savedCurrentRow) { - // The data grid was not able to move away from its previous current row. - // Be defensive and don't select the row. - return; + + // if the column shrank and the last totally visible column was the last column + // then we need to recompute the horizontalOffset, firstVisibleCol, negOffset. + // lastTotallyVisibleCol remains the last column + if (lastColumnIsLastTotallyVisibleCol && + (this.negOffset != 0 || this.horizontalOffset != 0)) + { + + // update the column width + column._width = size; + + int cx = 0; + int colCount = this.myGridTable.GridColumnStyles.Count; + int visibleWidth = layout.Data.Width; + GridColumnStylesCollection cols = this.myGridTable.GridColumnStyles; + + // assume everything fits + this.negOffset = 0; + this.horizontalOffset = 0; + this.firstVisibleCol = 0; + + for (int i = colCount - 1; i >= 0; i--) + { + if (cols[i].PropertyDescriptor == null) + { + continue; + } + + cx += cols[i].Width; + if (cx > visibleWidth) + { + if (this.negOffset == 0) + { + this.firstVisibleCol = i; + this.negOffset = cx - visibleWidth; + this.horizontalOffset = this.negOffset; + this.numVisibleCols++; + } + else + { + this.horizontalOffset += cols[i].Width; + } + } + else + { + this.numVisibleCols++; + } } - } - if (isControlDown) { - if (IsSelected(location.row)) - UnSelect(location.row); - else - Select(location.row); + // refresh the horizontal scrollbar + PerformLayout(); + + // we need to invalidate the layout.Data and layout.ColumnHeaders + Invalidate(Rectangle.Union(layout.Data, layout.ColumnHeaders)); } - else { - if (lastRowSelected == -1 || !isShiftDown) + else + { + // need to refresh the scroll bar + PerformLayout(); + + Rectangle rightArea = layout.Data; + if (layout.ColumnHeadersVisible) + rightArea = Rectangle.Union(rightArea, layout.ColumnHeaders); + + int left = GetColBeg(col); + + if (!isRightToLeft()) { - ResetSelection(); - Select(location.row); + rightArea.Width -= left - rightArea.X; + rightArea.X = left; } else { - int lowerRow = Math.Min(lastRowSelected, location.row); - int upperRow = Math.Max(lastRowSelected, location.row); - - // we need to reset the old SelectedRows. - // ResetSelection() will also reset lastRowSelected, so we - // need to save it - int saveLastRowSelected = lastRowSelected; - ResetSelection(); - lastRowSelected = saveLastRowSelected; - - DataGridRow[] rows = DataGridRows; - for (int i = lowerRow; i <= upperRow; i++) - { - rows[i].Selected = true; - numSelectedRows ++; - } - - // hide the edit box: - // - EndEdit(); - return; + rightArea.Width = rightArea.Width - left; } - } - - lastRowSelected = location.row; - // OnRowHeaderClick(EventArgs.Empty); - return; - } - - // Check parentRows - // - if (location.type == HitTestType.ParentRows) - { - EndEdit(); - parentRows.OnMouseDown(e.X, e.Y, isRightToLeft()); - } - - // Check cell clicks - // - if (location.type == HitTestType.Cell) { - if (this.myGridTable.GridColumnStyles[location.col].MouseDown(location.row, e.X, e.Y)) - return; - DataGridCell target = new DataGridCell(location.row, location.col); - if (policy.AllowEdit && CurrentCell.Equals(target)) { - ResetSelection(); - // - // what if only a part of the current cell is visible? - // - EnsureVisible(currentRow, currentCol); - Edit(); - } - else { - ResetSelection(); - CurrentCell = target; + + Invalidate(rightArea); } } } - - /// - /// Creates the - /// event. - /// - protected override void OnMouseLeave(EventArgs e) { - base.OnMouseLeave(e); - if (oldRow != -1) { - DataGridRow[] localGridRows = DataGridRows; - localGridRows[oldRow].OnMouseLeft(layout.RowHeaders, isRightToLeft()); - } - if (gridState[GRIDSTATE_overCaption]) { - caption.MouseLeft(); - } - // when the mouse leaves the grid control, reset the cursor to arrow - Cursor = null; + finally + { + g.Dispose(); } - - internal void TextBoxOnMouseWheel(MouseEventArgs e) { - this.OnMouseWheel(e); + + if (this.horizScrollBar.Visible) + { + this.horizScrollBar.Value = HorizontalOffset; } - - /// - /// Raises the - /// event. - /// - protected override void OnMouseMove(MouseEventArgs e) { - base.OnMouseMove(e); - if (listManager == null) - return; - - HitTestInfo location = HitTest(e.X, e.Y); - - bool alignToRight = isRightToLeft(); - - // We need to give UI feedback when the user is resizing a column - if (gridState[GRIDSTATE_trackColResize]) { - ColResizeMove(e); - } - - if (gridState[GRIDSTATE_trackRowResize]) - { - RowResizeMove(e); - } - - if (gridState[GRIDSTATE_trackColResize] || location.type == HitTestType.ColumnResize) - { - Cursor = Cursors.SizeWE; - return; - } - else if ( gridState[GRIDSTATE_trackRowResize] || location.type == HitTestType.RowResize) + // OnColumnResize(EventArgs.Empty); + } + + /// + /// + /// Collapses child relations, if any exist for all rows, or for a + /// specified row. + /// + /// + public void Collapse(int row) + { + SetRowExpansionState(row, false); + } + + private void ColResizeBegin(MouseEventArgs e, int col) + { + Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: ColResizeBegin"); + Debug.Assert(myGridTable != null, "Column resizing operations can't be called when myGridTable == null."); + + int x = e.X; + EndEdit(); + Rectangle clip = Rectangle.Union(layout.ColumnHeaders, layout.Data); + if (isRightToLeft()) + { + clip.Width = GetColBeg(col) - layout.Data.X - 2; + } + else + { + int leftEdge = GetColBeg(col); + clip.X = leftEdge + 3; + clip.Width = layout.Data.X + layout.Data.Width - leftEdge - 2; + } + + CaptureInternal = true; + Cursor.ClipInternal = RectangleToScreen(clip); + gridState[GRIDSTATE_trackColResize] = true; + trackColAnchor = x; + trackColumn = col; + + DrawColSplitBar(e); + lastSplitBar = e; + } + + private void ColResizeMove(MouseEventArgs e) + { + if (lastSplitBar != null) + { + DrawColSplitBar(lastSplitBar); + lastSplitBar = e; + } + DrawColSplitBar(e); + } + + private void ColResizeEnd(MouseEventArgs e) + { + Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: ColResizeEnd"); + Debug.Assert(myGridTable != null, "Column resizing operations can't be called when myGridTable == null."); + + this.gridState[GRIDSTATE_layoutSuspended] = true; + try + { + if (lastSplitBar != null) { - Cursor = Cursors.SizeNS; - return; + DrawColSplitBar(lastSplitBar); + lastSplitBar = null; } - else + + bool rightToLeft = isRightToLeft(); + + int x = rightToLeft ? Math.Max(e.X, layout.Data.X) : Math.Min(e.X, layout.Data.Right + 1); + int delta = x - GetColEnd(trackColumn); + if (rightToLeft) + delta = -delta; + + if (trackColAnchor != x && delta != 0) { - Cursor = null; - } - - if ((layout.Data.Contains(e.X, e.Y) - || (layout.RowHeadersVisible && layout.RowHeaders.Contains(e.X, e.Y)))) { - // && (isNavigating || isEditing)) { - DataGridRow[] localGridRows = DataGridRows; - // If we are over a row, let it know about the mouse move. - int rowOver = GetRowFromY(e.Y); - // set the dragging bit: - if (lastRowSelected != -1 && !gridState[GRIDSTATE_dragging]) { - int topRow = GetRowTop(lastRowSelected); - int bottomRow = topRow + localGridRows[lastRowSelected].Height; - int dragHeight = SystemInformation.DragSize.Height; - gridState[GRIDSTATE_dragging] = ((e.Y - topRow < dragHeight && topRow - e.Y < dragHeight) || (e.Y - bottomRow < dragHeight && bottomRow - e.Y < dragHeight)); + DataGridColumnStyle column = myGridTable.GridColumnStyles[trackColumn]; + int proposed = column.Width + delta; + proposed = Math.Max(proposed, 3); + column.Width = proposed; + + // refresh scrolling data: horizontalOffset, negOffset, firstVisibleCol, numVisibleCols, lastTotallyVisibleCol + ComputeVisibleColumns(); + + bool lastColumnIsLastTotallyVisibleCol = true; + for (int i = this.lastTotallyVisibleCol + 1; i < this.myGridTable.GridColumnStyles.Count; i++) + { + if (this.myGridTable.GridColumnStyles[i].PropertyDescriptor != null) + { + lastColumnIsLastTotallyVisibleCol = false; + break; + } } - if (rowOver > -1) { - Point p = NormalizeToRow(e.X, e.Y, rowOver); - if (!localGridRows[rowOver].OnMouseMove(p.X, p.Y, layout.RowHeaders, alignToRight) && gridState[GRIDSTATE_dragging]) { - // if the row did not use this, see if selection can use it - MouseButtons mouse = MouseButtons; - if (lastRowSelected != -1 && (mouse & MouseButtons.Left) == MouseButtons.Left - && !(((Control.ModifierKeys & Keys.Control) == Keys.Control) && (Control.ModifierKeys & Keys.Alt) == 0)){ - // ResetSelection() will reset the lastRowSelected too - // - int saveLastRowSelected = lastRowSelected; - ResetSelection(); - lastRowSelected = saveLastRowSelected; - - int lowerRow = Math.Min(lastRowSelected, rowOver); - int upperRow = Math.Max(lastRowSelected, rowOver); - - DataGridRow[] rows = DataGridRows; - for (int i = lowerRow; i <= upperRow; i++) + + if (lastColumnIsLastTotallyVisibleCol && + (this.negOffset != 0 || this.horizontalOffset != 0)) + { + + int cx = 0; + int colCount = this.myGridTable.GridColumnStyles.Count; + int visibleWidth = this.layout.Data.Width; + GridColumnStylesCollection cols = this.myGridTable.GridColumnStyles; + + // assume everything fits + this.negOffset = 0; + this.horizontalOffset = 0; + this.firstVisibleCol = 0; + + for (int i = colCount - 1; i > -1; i--) + { + if (cols[i].PropertyDescriptor == null) + { + continue; + } + + cx += cols[i].Width; + + if (cx > visibleWidth) + { + if (this.negOffset == 0) { - rows[i].Selected = true; - numSelectedRows ++; + this.negOffset = cx - visibleWidth; + this.firstVisibleCol = i; + this.horizontalOffset = negOffset; + this.numVisibleCols++; } + else + { + this.horizontalOffset += cols[i].Width; + } + } + else + { + this.numVisibleCols++; } } + + // and invalidate pretty much everything + Invalidate(Rectangle.Union(this.layout.Data, this.layout.ColumnHeaders)); } - - if (oldRow != rowOver && oldRow != -1) { - localGridRows[oldRow].OnMouseLeft(layout.RowHeaders, alignToRight); - } - oldRow = rowOver; - } - - // check parentRows - // - if (location.type == HitTestType.ParentRows) - { - if (parentRows != null) + else { - parentRows.OnMouseMove(e.X, e.Y); - } - } - - if (location.type == HitTestType.Caption) { - gridState[GRIDSTATE_overCaption] = true; - Rectangle captionRect = layout.Caption; - caption.MouseOver(e.X - captionRect.X, e.Y - captionRect.Y); - return; - } - else { - if (gridState[GRIDSTATE_overCaption]) { - gridState[GRIDSTATE_overCaption] = false; - caption.MouseLeft(); + + Rectangle rightArea = Rectangle.Union(layout.ColumnHeaders, layout.Data); + int left = GetColBeg(trackColumn); + rightArea.Width -= rightToLeft ? rightArea.Right - left : left - rightArea.X; + rightArea.X = rightToLeft ? layout.Data.X : left; + Invalidate(rightArea); } } } - - /// - /// Raises the event. - /// - protected override void OnMouseUp(MouseEventArgs e) { - base.OnMouseUp(e); - gridState[GRIDSTATE_dragging] = false; - if (listManager == null || myGridTable == null) - return; - if (gridState[GRIDSTATE_trackColResize]) { - ColResizeEnd(e); - } - - if (gridState[GRIDSTATE_trackRowResize]) - { - RowResizeEnd(e); - } - - gridState[GRIDSTATE_trackColResize] = false; - gridState[GRIDSTATE_trackRowResize] = false; - - HitTestInfo ci = HitTest(e.X, e.Y); - if ((ci.type & HitTestType.Caption) == HitTestType.Caption) { - caption.MouseUp(e.X, e.Y); - } - - // Check column headers - if (ci.type == HitTestType.ColumnHeader) { - PropertyDescriptor prop = this.myGridTable.GridColumnStyles[ci.col].PropertyDescriptor; - if (prop == trackColumnHeader) { - ColumnHeaderClicked(trackColumnHeader); - } - } - - trackColumnHeader = null; + finally + { + Cursor.ClipInternal = Rectangle.Empty; + CaptureInternal = false; + this.gridState[GRIDSTATE_layoutSuspended] = false; } - - /// - /// Raises the event. - /// - protected override void OnMouseWheel(MouseEventArgs e) { - base.OnMouseWheel(e); - - if (e is HandledMouseEventArgs) { - if (((HandledMouseEventArgs) e).Handled) { - // The application event handler handled the scrolling - don't do anything more. - return; - } - ((HandledMouseEventArgs) e).Handled = true; - } - bool wheelingDown = true; - if ((ModifierKeys & Keys.Control) != 0) - wheelingDown = false; - - if (listManager == null || myGridTable == null) - return; - ScrollBar sb = wheelingDown ? vertScrollBar : horizScrollBar; - if (!sb.Visible) - return; - - // so we scroll. we have to know this, cause otherwise we will call EndEdit - // and that would be wrong. - gridState[GRIDSTATE_isScrolling] = true; - wheelDelta += e.Delta; - float movePerc = (float)wheelDelta / (float)NativeMethods.WHEEL_DELTA; - int move = (int)((float)SystemInformation.MouseWheelScrollLines * movePerc); - if (move != 0) { - wheelDelta = 0; - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: OnMouseWheel move="+move.ToString(CultureInfo.InvariantCulture)); - if (wheelingDown) { - int newRow = firstVisibleRow - move; - newRow = Math.Max(0, Math.Min(newRow, DataGridRowsLength - numTotallyVisibleRows)); - ScrollDown(newRow - firstVisibleRow); - } - else { - int newValue = horizScrollBar.Value + (move < 0 ? 1 : -1) * horizScrollBar.LargeChange; - HorizontalOffset = newValue; - } - } + PerformLayout(); - gridState[GRIDSTATE_isScrolling] = false; - } - - /// - /// Raises the - /// event. - /// - protected override void OnPaint(PaintEventArgs pe) { - try { - CheckHierarchyState(); - - if (this.layout.dirty) - ComputeLayout(); - - Graphics g = pe.Graphics; - - Region clipRegion = g.Clip; - if (layout.CaptionVisible) - caption.Paint(g, layout.Caption, isRightToLeft()); - - if (layout.ParentRowsVisible) { - Debug.WriteLineIf(CompModSwitches.DataGridParents.TraceVerbose, "DataGridParents: Painting ParentRows " + layout.ParentRows.ToString()); - g.FillRectangle(SystemBrushes.AppWorkspace, layout.ParentRows); - parentRows.Paint(g, layout.ParentRows, isRightToLeft()); - } - - Rectangle gridRect = layout.Data; - if (layout.RowHeadersVisible) - gridRect = Rectangle.Union(gridRect, layout.RowHeaders); - if (layout.ColumnHeadersVisible) - gridRect = Rectangle.Union(gridRect, layout.ColumnHeaders); - - g.SetClip(gridRect); - PaintGrid(g, gridRect); - g.Clip = clipRegion; - clipRegion.Dispose(); - PaintBorder(g, layout.ClientRectangle); - - g.FillRectangle(DefaultHeaderBackBrush, layout.ResizeBoxRect); - - base.OnPaint(pe); // raise paint event - } - catch { - // at runtime we will rethrow the exception - if (this.Site == null || !this.Site.DesignMode) - throw; - gridState[GRIDSTATE_exceptionInPaint] = true; - try { - RTLAwareMessageBox.Show(null, SR.DataGridExceptionInPaint, null, MessageBoxButtons.OK, - MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); - - if (this.Visible) BeginUpdateInternal(); - - ResetParentRows(); - - Set_ListManager(null, string.Empty, true); - } finally { - gridState[GRIDSTATE_exceptionInPaint] = false; - if (this.Visible) EndUpdateInternal(); - } - } + if (this.horizScrollBar.Visible) + { + this.horizScrollBar.Value = HorizontalOffset; } - - // Since Win32 only invalidates the area that gets uncovered, - // we have to manually invalidate the old border area - /// - /// Raises the event. - /// - protected override void OnResize(EventArgs e) { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: OnResize"); - - if (layout.CaptionVisible) - Invalidate(layout.Caption); - if (layout.ParentRowsVisible) - parentRows.OnResize(layout.ParentRows); - - int borderWidth = BorderWidth; - Rectangle right; - Rectangle bottom; - Rectangle oldClientRectangle = layout.ClientRectangle; - - right = new Rectangle(oldClientRectangle.X + oldClientRectangle.Width - borderWidth, - oldClientRectangle.Y, - borderWidth, - oldClientRectangle.Height); - bottom = new Rectangle(oldClientRectangle.X, - oldClientRectangle.Y + oldClientRectangle.Height - borderWidth, - oldClientRectangle.Width, - borderWidth); - - Rectangle newClientRectangle = this.ClientRectangle; - if (newClientRectangle.Width != oldClientRectangle.Width) { - Invalidate(right); - right = new Rectangle(newClientRectangle.X + newClientRectangle.Width - borderWidth, - newClientRectangle.Y, - borderWidth, - newClientRectangle.Height); - Invalidate(right); - } - if (newClientRectangle.Height != oldClientRectangle.Height) { - Invalidate(bottom); - bottom = new Rectangle(newClientRectangle.X, - newClientRectangle.Y + newClientRectangle.Height - borderWidth, - newClientRectangle.Width, - borderWidth); - Invalidate(bottom); + // OnColumnResize(EventArgs.Empty); + } + + private void MetaDataChanged() + { + // when we reset the Binding in the grid, we need to clear the parent rows. + // the same goes for all the caption UI: reset it when the datasource changes. + // + parentRows.Clear(); + caption.BackButtonActive = caption.DownButtonActive = caption.BackButtonVisible = false; + caption.SetDownButtonDirection(!layout.ParentRowsVisible); + + gridState[GRIDSTATE_metaDataChanged] = true; + try + { + if (originalState != null) + { + // set the originalState to null so that Set_ListManager knows that + // it has to unhook the MetaDataChanged events + Set_ListManager(originalState.DataSource, originalState.DataMember, true); + originalState = null; } - - //also, invalidate the ResizeBoxRect - if (!this.layout.ResizeBoxRect.IsEmpty) - Invalidate(layout.ResizeBoxRect); - - layout.ClientRectangle = newClientRectangle; - - int oldFirstVisibleRow = firstVisibleRow; - base.OnResize(e); - if (isRightToLeft() || oldFirstVisibleRow != firstVisibleRow) - Invalidate(); - } - - internal void OnRowHeightChanged(DataGridRow row) { - ClearRegionCache(); - int cy = GetRowTop(row.RowNumber); - if (cy > 0) { - Rectangle refresh = new Rectangle(); - refresh.Y = cy; - refresh.X = layout.Inside.X; - refresh.Width = layout.Inside.Width; - refresh.Height = layout.Inside.Bottom - cy; - Invalidate(refresh); + else + { + Set_ListManager(this.DataSource, this.DataMember, true); } } - - internal void ParentRowsDataChanged() { - Debug.Assert(originalState != null, "how can we get a list changed event from another listmanager/list while not navigating"); - - // do the reset work that is done in SetDataBindings, set_DataSource, set_DataMember; - parentRows.Clear(); - caption.BackButtonActive = caption.DownButtonActive = caption.BackButtonVisible = false; - caption.SetDownButtonDirection(!layout.ParentRowsVisible); - object dSource = originalState.DataSource; - string dMember = originalState.DataMember; - // we don't need to set the GRIDSTATE_metaDataChanged bit, cause - // the listManager from the originalState should be different from the current listManager - // - // set the originalState to null so that Set_ListManager knows that - // it has to unhook the MetaDataChanged events - originalState = null; - Set_ListManager(dSource, dMember, true); - } - - - // =------------------------------------------------------------------ - // = Methods - // =------------------------------------------------------------------ - - private void AbortEdit() { - Debug.WriteLineIf(CompModSwitches.DataGridEditing.TraceVerbose, "DataGridEditing: \t! AbortEdit"); - Debug.Assert(gridState[GRIDSTATE_isEditing], "Can't abort an edit that is not happening!"); - - // the same rules from editColumn.OnEdit - // while changing the editControl's visibility, do not - // PerformLayout on the entire DataGrid - gridState[GRIDSTATE_editControlChanging] = true; - - editColumn.Abort(editRow.RowNumber); - - // reset the editControl flag: - gridState[GRIDSTATE_editControlChanging] = false; - - gridState[GRIDSTATE_isEditing] = false; - editRow = null; - editColumn = null; - } - - /// - /// Occurs when the user navigates to a new table. - /// - [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.DataGridNavigateEventDescr))] - public event NavigateEventHandler Navigate { - add => onNavigate += value; - remove => onNavigate -= value; - } - - /// - /// Occurs when a row header is clicked. - /// - protected event EventHandler RowHeaderClick { - add => onRowHeaderClick += value; - remove => onRowHeaderClick -= value; - } - - /// - /// - /// Adds an event handler for the 'System.Windows.Forms.DataGrid.OnNodeClick' - /// event. - /// - /// - [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.DataGridNodeClickEventDescr))] - internal event EventHandler NodeClick { - add => Events.AddHandler(EVENT_NODECLICKED, value); - remove => Events.RemoveHandler(EVENT_NODECLICKED, value); - } - - /// - /// - /// Occurs when the user scrolls the control. - /// - /// - [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.DataGridScrollEventDescr))] - public event EventHandler Scroll { - add => Events.AddHandler(EVENT_SCROLL, value); - remove => Events.RemoveHandler(EVENT_SCROLL, value); + finally + { + gridState[GRIDSTATE_metaDataChanged] = false; } - - public override ISite Site { - get { - return base.Site; - } - set { - ISite temp = this.Site; - base.Site = value; - if (value != temp && !Disposing) { - // we should site the tables and the columns - // only when our site changes - SubObjectsSiteChange(false); - SubObjectsSiteChange(true); - } + } + + + // =------------------------------------------------------------------ + // = Functions to resize rows + // =------------------------------------------------------------------ + + // will autoResize "row" + private void RowAutoResize(int row) + { + Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: RowAutoResize"); + + EndEdit(); + CurrencyManager listManager = this.ListManager; + if (listManager == null) + return; + + Graphics g = CreateGraphicsInternal(); + try + { + GridColumnStylesCollection columns = myGridTable.GridColumnStyles; + DataGridRow resizeRow = DataGridRows[row]; + int rowCount = listManager.Count; + int resizeHeight = 0; + + // compute the height that we should resize to: + int columnsCount = columns.Count; + for (int col = 0; col < columnsCount; col++) + { + object value = columns[col].GetColumnValueAtRow(listManager, row); + resizeHeight = Math.Max(resizeHeight, columns[col].GetPreferredHeight(g, value)); } - } - - internal void AddNewRow() { - EnsureBound(); - ResetSelection(); - // EndEdit(); - UpdateListManager(); - gridState[GRIDSTATE_inListAddNew] = true; - gridState[GRIDSTATE_inAddNewRow] = true; - try { - this.ListManager.AddNew(); - } catch { - gridState[GRIDSTATE_inListAddNew] = false; - gridState[GRIDSTATE_inAddNewRow] = false; + + if (resizeRow.Height != resizeHeight) + { + resizeRow.Height = resizeHeight; + + // needed to refresh scrollbar properties PerformLayout(); - InvalidateInside(); - throw; - } - gridState[GRIDSTATE_inListAddNew] = false; - } - - /// - /// Attempts to - /// put the grid into a state where editing is - /// allowed. - /// - public bool BeginEdit(DataGridColumnStyle gridColumn, int rowNumber) { - if (this.DataSource == null || this.myGridTable == null) - return false; - - // We deny edit requests if we are already editing a cell. - if (gridState[GRIDSTATE_isEditing]) - return false; - else { - int col = -1; - if ((col = this.myGridTable.GridColumnStyles.IndexOf(gridColumn)) < 0) - return false; - CurrentCell = new DataGridCell(rowNumber, col); - ResetSelection(); - Edit(); - return true; + + Rectangle rightArea = layout.Data; + if (layout.RowHeadersVisible) + rightArea = Rectangle.Union(rightArea, layout.RowHeaders); + int top = GetRowTop(row); + rightArea.Height -= rightArea.Y - top; + rightArea.Y = top; + Invalidate(rightArea); } } - - /// - /// Specifies the beginning of the initialization code. - /// - public void BeginInit() { - if (inInit) - throw new InvalidOperationException(SR.DataGridBeginInit); - inInit = true; - } - - private Rectangle CalcRowResizeFeedbackRect(MouseEventArgs e) { - Rectangle inside = layout.Data; - Rectangle r = new Rectangle(inside.X, e.Y, inside.Width, 3); - r.Y = Math.Min(inside.Bottom - 3, r.Y); - r.Y = Math.Max(r.Y , 0); - return r; + finally + { + g.Dispose(); } - - private Rectangle CalcColResizeFeedbackRect(MouseEventArgs e) { - Rectangle inside = layout.Data; - Rectangle r = new Rectangle(e.X, inside.Y, 3, inside.Height); - r.X = Math.Min(inside.Right - 3, r.X); - r.X = Math.Max(r.X , 0); - return r; + + // OnRowResize(EventArgs.Empty); + return; + } + + + + private void RowResizeBegin(MouseEventArgs e, int row) + { + Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: RowResizeBegin"); + Debug.Assert(myGridTable != null, "Row resizing operations can't be called when myGridTable == null."); + + int y = e.Y; + EndEdit(); + Rectangle clip = Rectangle.Union(layout.RowHeaders, layout.Data); + int topEdge = GetRowTop(row); + clip.Y = topEdge + 3; + clip.Height = layout.Data.Y + layout.Data.Height - topEdge - 2; + + CaptureInternal = true; + Cursor.ClipInternal = RectangleToScreen(clip); + gridState[GRIDSTATE_trackRowResize] = true; + trackRowAnchor = y; + trackRow = row; + + DrawRowSplitBar(e); + lastSplitBar = e; + } + + private void RowResizeMove(MouseEventArgs e) + { + if (lastSplitBar != null) + { + DrawRowSplitBar(lastSplitBar); + lastSplitBar = e; } - - private void CancelCursorUpdate() { - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: Requesting CancelEdit()"); - if (listManager != null) { - EndEdit(); - listManager.CancelCurrentEdit(); + DrawRowSplitBar(e); + } + + private void RowResizeEnd(MouseEventArgs e) + { + Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: RowResizeEnd"); + Debug.Assert(myGridTable != null, "Row resizing operations can't be called when myGridTable == null."); + + try + { + if (lastSplitBar != null) + { + DrawRowSplitBar(lastSplitBar); + lastSplitBar = null; } - } - - private void CheckHierarchyState() { - if (checkHierarchy && this.listManager != null && this.myGridTable != null) { - if (myGridTable == null) - // there was nothing to check - return; - - for (int j = 0; j < myGridTable.GridColumnStyles.Count; j++) { - DataGridColumnStyle gridColumn = myGridTable.GridColumnStyles[j]; - } - - checkHierarchy = false; + + int y = Math.Min(e.Y, layout.Data.Y + layout.Data.Height + 1); + int delta = y - GetRowBottom(trackRow); + if (trackRowAnchor != y && delta != 0) + { + DataGridRow row = DataGridRows[trackRow]; + int proposed = row.Height + delta; + proposed = Math.Max(proposed, 3); + row.Height = proposed; + + + // needed to refresh scrollbar properties + PerformLayout(); + + Rectangle rightArea = Rectangle.Union(layout.RowHeaders, layout.Data); + int top = GetRowTop(trackRow); + rightArea.Height -= rightArea.Y - top; + rightArea.Y = top; + Invalidate(rightArea); } } - - /// - /// The DataGrid caches an array of rectangular areas - /// which represent the area which scrolls left to right. - /// This method is invoked whenever the DataGrid's - /// scrollable regions change in such a way as to require - /// a re-recalculation. - /// - private void ClearRegionCache() { - cachedScrollableRegion = null; + finally + { + Cursor.ClipInternal = Rectangle.Empty; + CaptureInternal = false; } - - /// - /// Determines the best fit size for the given column. - /// - private void ColAutoResize(int col) { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: ColAutoResize"); - EndEdit(); - CurrencyManager listManager = this.listManager; - if (listManager == null) - return; - - int size; - Graphics g = CreateGraphicsInternal(); - try { - DataGridColumnStyle column = myGridTable.GridColumnStyles[col]; - string columnName = column.HeaderText; - - Font headerFont; - if (this.myGridTable.IsDefault) - headerFont = this.HeaderFont; - else - headerFont = this.myGridTable.HeaderFont; - size = (int) g.MeasureString(columnName, headerFont).Width + layout.ColumnHeaders.Height + 1; // The sort triangle's width is equal to it's height - int rowCount = listManager.Count; - for (int row = 0; row < rowCount; ++row) { - object value = column.GetColumnValueAtRow(listManager, row); - int width = column.GetPreferredSize(g, value).Width; - if (width > size) - size = width; - } + // OnRowResize(EventArgs.Empty); + } - if (column.Width != size) { - column._width = size; + /// + /// Fires the ColumnHeaderClicked event and handles column + /// sorting. + /// + private void ColumnHeaderClicked(PropertyDescriptor prop) + { + if (!CommitEdit()) + return; - ComputeVisibleColumns(); + // OnColumnHeaderClick(EventArgs.Empty); + bool allowSorting; + if (this.myGridTable.IsDefault) + allowSorting = this.AllowSorting; + else + allowSorting = myGridTable.AllowSorting; - bool lastColumnIsLastTotallyVisibleCol = true; - if (this.lastTotallyVisibleCol != -1) { - for (int i = this.lastTotallyVisibleCol + 1; i < this.myGridTable.GridColumnStyles.Count; i ++) { - if (this.myGridTable.GridColumnStyles[i].PropertyDescriptor != null) { - lastColumnIsLastTotallyVisibleCol = false; - break; - } - } - } else { - lastColumnIsLastTotallyVisibleCol = false; - } - - // if the column shrank and the last totally visible column was the last column - // then we need to recompute the horizontalOffset, firstVisibleCol, negOffset. - // lastTotallyVisibleCol remains the last column - if (lastColumnIsLastTotallyVisibleCol && - (this.negOffset != 0 || this.horizontalOffset != 0)) { - - // update the column width - column._width = size; - - int cx = 0; - int colCount = this.myGridTable.GridColumnStyles.Count; - int visibleWidth = layout.Data.Width; - GridColumnStylesCollection cols = this.myGridTable.GridColumnStyles; - - // assume everything fits - this.negOffset = 0; - this.horizontalOffset = 0; - this.firstVisibleCol= 0; - - for (int i = colCount - 1; i >= 0; i --) { - if (cols[i].PropertyDescriptor == null) { - continue; - } + if (!allowSorting) + return; + + // if (CompModSwitches.DataGridCursor.OutputVerbose) Debug.WriteLine("DataGridCursor: We are about to sort column " + col.ToString()); + ListSortDirection direction = this.ListManager.GetSortDirection(); + PropertyDescriptor sortColumn = this.ListManager.GetSortProperty(); + if (sortColumn != null && sortColumn.Equals(prop)) + direction = (direction == ListSortDirection.Ascending) ? ListSortDirection.Descending : ListSortDirection.Ascending; + else + // defaultSortDirection : ascending + direction = ListSortDirection.Ascending; + + if (listManager.Count == 0) + return; + + this.ListManager.SetSort(prop, direction); + ResetSelection(); + + InvalidateInside(); + } + + /// + /// Attempts to commit editing if a cell is being edited. + /// Return true if successfully commited editing. + /// Return false if editing can not be completed and the gird must + /// remain in our current Edit state. + /// + private bool CommitEdit() + { + + Debug.WriteLineIf(CompModSwitches.DataGridEditing.TraceVerbose, "DataGridEditing: \t CommitEdit " + (editRow == null ? "" : editRow.RowNumber.ToString(CultureInfo.InvariantCulture))); + + + // we want to commit the editing if + // 1. the user was editing or navigating around the data grid and + // 2. this is not the result of moving focus inside the data grid and + // 3. if the user was scrolling + if (!gridState[GRIDSTATE_isEditing] && !gridState[GRIDSTATE_isNavigating] || (gridState[GRIDSTATE_editControlChanging] && !gridState[GRIDSTATE_isScrolling])) + return true; + + // the same rules from editColumn.OnEdit + // flag that we are editing the Edit control, so if we get a OnLayout on the + // datagrid side of things while the edit control changes its visibility and bounds + // the datagrid does not perform a layout + gridState[GRIDSTATE_editControlChanging] = true; + + if (editColumn.ReadOnly || gridState[GRIDSTATE_inAddNewRow]) + { + bool focusTheGrid = false; + if (this.ContainsFocus) + { + focusTheGrid = true; + } - cx += cols[i].Width; - if (cx > visibleWidth) { - if (this.negOffset == 0) { - this.firstVisibleCol = i; - this.negOffset = cx - visibleWidth; - this.horizontalOffset = this.negOffset; - this.numVisibleCols ++; - } else { - this.horizontalOffset += cols[i].Width; - } - } else { - this.numVisibleCols ++; - } - } + if (focusTheGrid && gridState[GRIDSTATE_canFocus]) + this.Focus(); + editColumn.ConcedeFocus(); - // refresh the horizontal scrollbar - PerformLayout(); + // set the focus back to the grid + if (focusTheGrid && gridState[GRIDSTATE_canFocus] && CanFocus && !Focused) + this.Focus(); - // we need to invalidate the layout.Data and layout.ColumnHeaders - Invalidate(Rectangle.Union(layout.Data, layout.ColumnHeaders)); - } else { - // need to refresh the scroll bar - PerformLayout(); + // reset the editControl flag + gridState[GRIDSTATE_editControlChanging] = false; + return true; + } - Rectangle rightArea = layout.Data; - if (layout.ColumnHeadersVisible) - rightArea = Rectangle.Union(rightArea, layout.ColumnHeaders); + bool retVal = editColumn.Commit(ListManager, currentRow); - int left = GetColBeg(col); + // reset the editControl flag + gridState[GRIDSTATE_editControlChanging] = false; - if (!isRightToLeft()) { - rightArea.Width -= left - rightArea.X; - rightArea.X = left; - } else { - rightArea.Width = rightArea.Width - left; - } + if (retVal) + gridState[GRIDSTATE_isEditing] = false; - Invalidate(rightArea); - } - } - } - finally { - g.Dispose(); - } + return retVal; + } - if (this.horizScrollBar.Visible) { - this.horizScrollBar.Value = HorizontalOffset; - } - // OnColumnResize(EventArgs.Empty); + /// + /// Figure out how many rows we need to scroll down + /// to move targetRow into visibility. + /// + private int ComputeDeltaRows(int targetRow) + { + //Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "DataGridScrolling: ComputeDeltaRows, firstVisibleRow = " + // + firstVisibleRow.ToString() + ", " + // + "targetRow = " + targetRow.ToString()); + + if (firstVisibleRow == targetRow) + return 0; + + int dRows = 0; + int firstVisibleRowLogicalTop = -1; + int targetRowLogicalTop = -1; + int nRows = DataGridRowsLength; + int cy = 0; + DataGridRow[] localGridRows = DataGridRows; + + for (int row = 0; row < nRows; ++row) + { + if (row == firstVisibleRow) + firstVisibleRowLogicalTop = cy; + if (row == targetRow) + targetRowLogicalTop = cy; + if (targetRowLogicalTop != -1 && firstVisibleRowLogicalTop != -1) + break; + cy += localGridRows[row].Height; } - - /// - /// - /// Collapses child relations, if any exist for all rows, or for a - /// specified row. - /// - /// - public void Collapse(int row) { - SetRowExpansionState(row, false); + + int targetRowLogicalBottom = targetRowLogicalTop + localGridRows[targetRow].Height; + int dataLogicalBottom = layout.Data.Height + firstVisibleRowLogicalTop; + if (targetRowLogicalBottom > dataLogicalBottom) + { + // we need to move down. + int downDelta = targetRowLogicalBottom - dataLogicalBottom; + firstVisibleRowLogicalTop += downDelta; } - - private void ColResizeBegin(MouseEventArgs e, int col) { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: ColResizeBegin"); - Debug.Assert(myGridTable != null, "Column resizing operations can't be called when myGridTable == null."); - - int x = e.X; - EndEdit(); - Rectangle clip = Rectangle.Union(layout.ColumnHeaders, layout.Data); - if (isRightToLeft()) - { - clip.Width = GetColBeg(col) - layout.Data.X - 2; - } - else - { - int leftEdge = GetColBeg(col); - clip.X = leftEdge + 3; - clip.Width = layout.Data.X + layout.Data.Width - leftEdge - 2; - } - - CaptureInternal = true; - Cursor.ClipInternal = RectangleToScreen(clip); - gridState[GRIDSTATE_trackColResize] = true; - trackColAnchor = x; - trackColumn = col; - - DrawColSplitBar(e); - lastSplitBar = e; + else if (firstVisibleRowLogicalTop < targetRowLogicalTop) + { + // we don't need to move + return 0; } - - private void ColResizeMove(MouseEventArgs e) { - if (lastSplitBar != null) { - DrawColSplitBar(lastSplitBar); - lastSplitBar = e; - } - DrawColSplitBar(e); + else + { + // we need to move up. + int upDelta = firstVisibleRowLogicalTop - targetRowLogicalTop; + firstVisibleRowLogicalTop -= upDelta; + } + int newFirstRow = ComputeFirstVisibleRow(firstVisibleRowLogicalTop); + dRows = (newFirstRow - firstVisibleRow); + //Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "DataGridScrolling: ComputeDeltaRows returning " + dRows.ToString()); + return dRows; + } + + /// + /// Given the a logical vertical offset, figure out + /// which row number should be the first fully visible + /// row on or after the offset. + /// + private int ComputeFirstVisibleRow(int firstVisibleRowLogicalTop) + { + int first; + int nRows = DataGridRowsLength; + int cy = 0; + DataGridRow[] localGridRows = DataGridRows; + for (first = 0; first < nRows; ++first) + { + if (cy >= firstVisibleRowLogicalTop) + break; + cy += localGridRows[first].Height; } - - private void ColResizeEnd(MouseEventArgs e) { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: ColResizeEnd"); - Debug.Assert(myGridTable != null, "Column resizing operations can't be called when myGridTable == null."); - - this.gridState[GRIDSTATE_layoutSuspended] = true; - try { - if (lastSplitBar != null) { - DrawColSplitBar(lastSplitBar); - lastSplitBar = null; - } - - bool rightToLeft = isRightToLeft(); - - int x = rightToLeft ? Math.Max(e.X, layout.Data.X) : Math.Min(e.X, layout.Data.Right + 1); - int delta = x - GetColEnd(trackColumn); - if (rightToLeft) delta = -delta; - - if (trackColAnchor != x && delta != 0) { - DataGridColumnStyle column = myGridTable.GridColumnStyles[trackColumn]; - int proposed = column.Width + delta; - proposed = Math.Max(proposed, 3); - column.Width = proposed; - - // refresh scrolling data: horizontalOffset, negOffset, firstVisibleCol, numVisibleCols, lastTotallyVisibleCol - ComputeVisibleColumns(); - - bool lastColumnIsLastTotallyVisibleCol = true; - for (int i = this.lastTotallyVisibleCol + 1; i < this.myGridTable.GridColumnStyles.Count; i ++) { - if (this.myGridTable.GridColumnStyles[i].PropertyDescriptor != null) { - lastColumnIsLastTotallyVisibleCol = false; - break; - } - } + return first; + } - if (lastColumnIsLastTotallyVisibleCol && - (this.negOffset != 0 || this.horizontalOffset != 0)) { + /// + /// Constructs an updated Layout object. + /// + private void ComputeLayout() + { + Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: ComputeLayout"); - int cx = 0; - int colCount = this.myGridTable.GridColumnStyles.Count; - int visibleWidth = this.layout.Data.Width; - GridColumnStylesCollection cols = this.myGridTable.GridColumnStyles; + bool alignLeft = !isRightToLeft(); + Rectangle oldResizeRect = this.layout.ResizeBoxRect; - // assume everything fits - this.negOffset = 0; - this.horizontalOffset = 0; - this.firstVisibleCol = 0; + // hide the EditBox + EndEdit(); - for (int i = colCount - 1; i > -1; i --) { - if (cols[i].PropertyDescriptor == null) { - continue; - } + ClearRegionCache(); - cx += cols[i].Width; + // NOTE : Since Rectangles are structs, then assignment is a + // : copy. Therefore, after saying "Rectangle inside = newLayout.Inside", + // : we must always assign back to newLayout.Inside. + // - if (cx > visibleWidth) { - if (this.negOffset == 0) { - this.negOffset = cx - visibleWidth; - this.firstVisibleCol = i; - this.horizontalOffset = negOffset; - this.numVisibleCols ++; - } else { - this.horizontalOffset += cols[i].Width; - } - } else { - this.numVisibleCols ++; - } - } + // Important since all of the visibility flags will move + // to the new layout here. + LayoutData newLayout = new LayoutData(layout); - // and invalidate pretty much everything - Invalidate(Rectangle.Union(this.layout.Data, this.layout.ColumnHeaders)); - } else { - - Rectangle rightArea = Rectangle.Union(layout.ColumnHeaders, layout.Data); - int left = GetColBeg(trackColumn); - rightArea.Width -= rightToLeft ? rightArea.Right - left : left - rightArea.X; - rightArea.X = rightToLeft ? layout.Data.X : left; - Invalidate(rightArea); - } - } - } - finally { - Cursor.ClipInternal = Rectangle.Empty; - CaptureInternal = false; - this.gridState[GRIDSTATE_layoutSuspended] = false; - } + // Inside + newLayout.Inside = ClientRectangle; + Rectangle inside = newLayout.Inside; + int borderWidth = BorderWidth; + inside.Inflate(-borderWidth, -borderWidth); - PerformLayout(); + Rectangle insideLeft = inside; - if (this.horizScrollBar.Visible) { - this.horizScrollBar.Value = HorizontalOffset; - } - // OnColumnResize(EventArgs.Empty); - } - - private void MetaDataChanged() { - // when we reset the Binding in the grid, we need to clear the parent rows. - // the same goes for all the caption UI: reset it when the datasource changes. - // - parentRows.Clear(); - caption.BackButtonActive = caption.DownButtonActive = caption.BackButtonVisible = false; - caption.SetDownButtonDirection(!layout.ParentRowsVisible); - - gridState[GRIDSTATE_metaDataChanged] = true; - try { - if (originalState != null) { - // set the originalState to null so that Set_ListManager knows that - // it has to unhook the MetaDataChanged events - Set_ListManager(originalState.DataSource, originalState.DataMember, true); - originalState = null; - } else { - Set_ListManager(this.DataSource, this.DataMember, true); - } - } finally { - gridState[GRIDSTATE_metaDataChanged] = false; - } - } - - - // =------------------------------------------------------------------ - // = Functions to resize rows - // =------------------------------------------------------------------ - - // will autoResize "row" - private void RowAutoResize(int row) + // Caption + if (layout.CaptionVisible) { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: RowAutoResize"); - - EndEdit(); - CurrencyManager listManager = this.ListManager; - if (listManager == null) - return; - - Graphics g = CreateGraphicsInternal(); - try - { - GridColumnStylesCollection columns = myGridTable.GridColumnStyles; - DataGridRow resizeRow = DataGridRows[row]; - int rowCount = listManager.Count; - int resizeHeight = 0; - - // compute the height that we should resize to: - int columnsCount = columns.Count; - for (int col = 0; col < columnsCount; col++) { - object value = columns[col].GetColumnValueAtRow(listManager, row); - resizeHeight = Math.Max(resizeHeight, columns[col].GetPreferredHeight(g, value)); - } - - if (resizeRow.Height != resizeHeight) - { - resizeRow.Height = resizeHeight; - - // needed to refresh scrollbar properties - PerformLayout(); - - Rectangle rightArea = layout.Data; - if (layout.RowHeadersVisible) - rightArea = Rectangle.Union(rightArea, layout.RowHeaders); - int top = GetRowTop(row); - rightArea.Height -= rightArea.Y - top; - rightArea.Y = top; - Invalidate(rightArea); - } - } - finally - { - g.Dispose(); - } - - // OnRowResize(EventArgs.Empty); - return; + int captionHeight = captionFontHeight + 6; + Rectangle cap = newLayout.Caption; + cap = insideLeft; + cap.Height = captionHeight; + insideLeft.Y += captionHeight; + insideLeft.Height -= captionHeight; + + newLayout.Caption = cap; } - - - - private void RowResizeBegin(MouseEventArgs e, int row) + else { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: RowResizeBegin"); - Debug.Assert(myGridTable != null, "Row resizing operations can't be called when myGridTable == null."); - - int y = e.Y; - EndEdit(); - Rectangle clip = Rectangle.Union(layout.RowHeaders, layout.Data); - int topEdge = GetRowTop(row); - clip.Y = topEdge + 3; - clip.Height = layout.Data.Y + layout.Data.Height - topEdge - 2; - - CaptureInternal = true; - Cursor.ClipInternal = RectangleToScreen(clip); - gridState[GRIDSTATE_trackRowResize] = true; - trackRowAnchor = y; - trackRow = row; - - DrawRowSplitBar(e); - lastSplitBar = e; + newLayout.Caption = Rectangle.Empty; } - - private void RowResizeMove(MouseEventArgs e) + + // Parent Rows + if (layout.ParentRowsVisible) { - if (lastSplitBar != null) { - DrawRowSplitBar(lastSplitBar); - lastSplitBar = e; - } - DrawRowSplitBar(e); + Rectangle parents = newLayout.ParentRows; + int parentHeight = parentRows.Height; + parents = insideLeft; + parents.Height = parentHeight; + insideLeft.Y += parentHeight; + insideLeft.Height -= parentHeight; + + newLayout.ParentRows = parents; } - - private void RowResizeEnd(MouseEventArgs e) + else { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: RowResizeEnd"); - Debug.Assert(myGridTable != null, "Row resizing operations can't be called when myGridTable == null."); - - try { - if (lastSplitBar != null) { - DrawRowSplitBar(lastSplitBar); - lastSplitBar = null; - } - - int y = Math.Min(e.Y, layout.Data.Y + layout.Data.Height + 1); - int delta = y - GetRowBottom(trackRow); - if (trackRowAnchor != y && delta != 0) { - DataGridRow row = DataGridRows[trackRow]; - int proposed = row.Height + delta; - proposed = Math.Max(proposed, 3); - row.Height = proposed; - - - // needed to refresh scrollbar properties - PerformLayout(); - - Rectangle rightArea = Rectangle.Union(layout.RowHeaders, layout.Data); - int top = GetRowTop(trackRow); - rightArea.Height -= rightArea.Y - top; - rightArea.Y = top; - Invalidate(rightArea); - } - } - finally { - Cursor.ClipInternal = Rectangle.Empty; - CaptureInternal = false; - } - // OnRowResize(EventArgs.Empty); - } - - /// - /// Fires the ColumnHeaderClicked event and handles column - /// sorting. - /// - private void ColumnHeaderClicked(PropertyDescriptor prop) { - if (!CommitEdit()) - return; - - // OnColumnHeaderClick(EventArgs.Empty); - bool allowSorting; - if (this.myGridTable.IsDefault) - allowSorting = this.AllowSorting; - else - allowSorting = myGridTable.AllowSorting; - - if (!allowSorting) - return; - - // if (CompModSwitches.DataGridCursor.OutputVerbose) Debug.WriteLine("DataGridCursor: We are about to sort column " + col.ToString()); - ListSortDirection direction = this.ListManager.GetSortDirection(); - PropertyDescriptor sortColumn = this.ListManager.GetSortProperty(); - if (sortColumn != null && sortColumn.Equals(prop)) - direction = (direction == ListSortDirection.Ascending) ? ListSortDirection.Descending : ListSortDirection.Ascending; - else - // defaultSortDirection : ascending - direction = ListSortDirection.Ascending; - - if (listManager.Count == 0) - return; - - this.ListManager.SetSort(prop, direction); - ResetSelection(); - - InvalidateInside(); + newLayout.ParentRows = Rectangle.Empty; } - - /// - /// Attempts to commit editing if a cell is being edited. - /// Return true if successfully commited editing. - /// Return false if editing can not be completed and the gird must - /// remain in our current Edit state. - /// - private bool CommitEdit() { - - Debug.WriteLineIf(CompModSwitches.DataGridEditing.TraceVerbose, "DataGridEditing: \t CommitEdit " + (editRow == null ? "" : editRow.RowNumber.ToString(CultureInfo.InvariantCulture))); - - - // we want to commit the editing if - // 1. the user was editing or navigating around the data grid and - // 2. this is not the result of moving focus inside the data grid and - // 3. if the user was scrolling - if (!gridState[GRIDSTATE_isEditing] && !gridState[GRIDSTATE_isNavigating] || (gridState[GRIDSTATE_editControlChanging] && !gridState[GRIDSTATE_isScrolling])) - return true; - - // the same rules from editColumn.OnEdit - // flag that we are editing the Edit control, so if we get a OnLayout on the - // datagrid side of things while the edit control changes its visibility and bounds - // the datagrid does not perform a layout - gridState[GRIDSTATE_editControlChanging] = true; - - if (editColumn.ReadOnly || gridState[GRIDSTATE_inAddNewRow]) { - bool focusTheGrid = false; - if (this.ContainsFocus) { - focusTheGrid = true; - } - if (focusTheGrid && gridState[GRIDSTATE_canFocus]) - this.Focus(); - editColumn.ConcedeFocus(); - - // set the focus back to the grid - if (focusTheGrid && gridState[GRIDSTATE_canFocus] && CanFocus && !Focused) - this.Focus(); - - // reset the editControl flag - gridState[GRIDSTATE_editControlChanging] = false; - return true; - } - - bool retVal = editColumn.Commit(ListManager, currentRow); - - // reset the editControl flag - gridState[GRIDSTATE_editControlChanging] = false; - - if (retVal) - gridState[GRIDSTATE_isEditing] = false; - - return retVal; - } - - /// - /// Figure out how many rows we need to scroll down - /// to move targetRow into visibility. - /// - private int ComputeDeltaRows(int targetRow) { - //Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "DataGridScrolling: ComputeDeltaRows, firstVisibleRow = " - // + firstVisibleRow.ToString() + ", " - // + "targetRow = " + targetRow.ToString()); - - if (firstVisibleRow == targetRow) - return 0; - - int dRows = 0; - int firstVisibleRowLogicalTop = -1; - int targetRowLogicalTop = -1; - int nRows = DataGridRowsLength; - int cy = 0; - DataGridRow[] localGridRows = DataGridRows; - - for (int row = 0; row < nRows; ++row) { - if (row == firstVisibleRow) - firstVisibleRowLogicalTop = cy; - if (row == targetRow) - targetRowLogicalTop = cy; - if (targetRowLogicalTop != -1 && firstVisibleRowLogicalTop != -1) - break; - cy += localGridRows[row].Height; - } - - int targetRowLogicalBottom = targetRowLogicalTop + localGridRows[targetRow].Height; - int dataLogicalBottom = layout.Data.Height + firstVisibleRowLogicalTop; - if (targetRowLogicalBottom > dataLogicalBottom) { - // we need to move down. - int downDelta = targetRowLogicalBottom - dataLogicalBottom; - firstVisibleRowLogicalTop += downDelta; - } - else if (firstVisibleRowLogicalTop < targetRowLogicalTop) { - // we don't need to move - return 0; - } - else { - // we need to move up. - int upDelta = firstVisibleRowLogicalTop - targetRowLogicalTop; - firstVisibleRowLogicalTop -= upDelta; - } - int newFirstRow = ComputeFirstVisibleRow(firstVisibleRowLogicalTop); - dRows = (newFirstRow - firstVisibleRow); - //Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "DataGridScrolling: ComputeDeltaRows returning " + dRows.ToString()); - return dRows; + // Headers + // + int columnHeaderHeight = headerFontHeight + 6; + if (layout.ColumnHeadersVisible) + { + Rectangle colHeaders = newLayout.ColumnHeaders; + colHeaders = insideLeft; + colHeaders.Height = columnHeaderHeight; + insideLeft.Y += columnHeaderHeight; + insideLeft.Height -= columnHeaderHeight; + + newLayout.ColumnHeaders = colHeaders; } - - /// - /// Given the a logical vertical offset, figure out - /// which row number should be the first fully visible - /// row on or after the offset. - /// - private int ComputeFirstVisibleRow(int firstVisibleRowLogicalTop) { - int first; - int nRows = DataGridRowsLength; - int cy = 0; - DataGridRow[] localGridRows = DataGridRows; - for (first = 0; first < nRows; ++first) { - if (cy >= firstVisibleRowLogicalTop) - break; - cy += localGridRows[first].Height; - } - return first; + else + { + newLayout.ColumnHeaders = Rectangle.Empty; } - - /// - /// Constructs an updated Layout object. - /// - private void ComputeLayout() { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: ComputeLayout"); - - bool alignLeft = ! isRightToLeft(); - Rectangle oldResizeRect = this.layout.ResizeBoxRect; - - // hide the EditBox - EndEdit(); - - ClearRegionCache(); - - // NOTE : Since Rectangles are structs, then assignment is a - // : copy. Therefore, after saying "Rectangle inside = newLayout.Inside", - // : we must always assign back to newLayout.Inside. - // - - // Important since all of the visibility flags will move - // to the new layout here. - LayoutData newLayout = new LayoutData(layout); - - // Inside - newLayout.Inside = ClientRectangle; - Rectangle inside = newLayout.Inside; - int borderWidth = BorderWidth; - inside.Inflate(-borderWidth, -borderWidth); - - Rectangle insideLeft = inside; - - // Caption - if (layout.CaptionVisible) { - int captionHeight = captionFontHeight + 6; - Rectangle cap = newLayout.Caption; - cap = insideLeft; - cap.Height = captionHeight; - insideLeft.Y += captionHeight; - insideLeft.Height -= captionHeight; - - newLayout.Caption = cap; - } - else { - newLayout.Caption = Rectangle.Empty; - } - - // Parent Rows - if (layout.ParentRowsVisible) { - Rectangle parents = newLayout.ParentRows; - int parentHeight = parentRows.Height; - parents = insideLeft; - parents.Height = parentHeight; - insideLeft.Y += parentHeight; - insideLeft.Height -= parentHeight; - - newLayout.ParentRows = parents; + + bool newRowHeadersVisible = this.myGridTable.IsDefault ? this.RowHeadersVisible : this.myGridTable.RowHeadersVisible; + int newRowHeaderWidth = this.myGridTable.IsDefault ? this.RowHeaderWidth : this.myGridTable.RowHeaderWidth; + newLayout.RowHeadersVisible = newRowHeadersVisible; + if (this.myGridTable != null && newRowHeadersVisible) + { + Rectangle rowHeaders = newLayout.RowHeaders; + if (alignLeft) + { + rowHeaders = insideLeft; + rowHeaders.Width = newRowHeaderWidth; + insideLeft.X += newRowHeaderWidth; + insideLeft.Width -= newRowHeaderWidth; } - else { - newLayout.ParentRows = Rectangle.Empty; + else + { + rowHeaders = insideLeft; + rowHeaders.Width = newRowHeaderWidth; + rowHeaders.X = insideLeft.Right - newRowHeaderWidth; + insideLeft.Width -= newRowHeaderWidth; } - - // Headers - // - int columnHeaderHeight = headerFontHeight + 6; - if (layout.ColumnHeadersVisible) { + newLayout.RowHeaders = rowHeaders; + + if (layout.ColumnHeadersVisible) + { + Rectangle topLeft = newLayout.TopLeftHeader; Rectangle colHeaders = newLayout.ColumnHeaders; - colHeaders = insideLeft; - colHeaders.Height = columnHeaderHeight; - insideLeft.Y += columnHeaderHeight; - insideLeft.Height -= columnHeaderHeight; - - newLayout.ColumnHeaders = colHeaders; - } - else { - newLayout.ColumnHeaders = Rectangle.Empty; - } - - bool newRowHeadersVisible = this.myGridTable.IsDefault ? this.RowHeadersVisible : this.myGridTable.RowHeadersVisible; - int newRowHeaderWidth = this.myGridTable.IsDefault ? this.RowHeaderWidth : this.myGridTable.RowHeaderWidth; - newLayout.RowHeadersVisible = newRowHeadersVisible; - if (this.myGridTable != null && newRowHeadersVisible) { - Rectangle rowHeaders = newLayout.RowHeaders; if (alignLeft) { - rowHeaders = insideLeft; - rowHeaders.Width = newRowHeaderWidth; - insideLeft.X += newRowHeaderWidth; - insideLeft.Width -= newRowHeaderWidth; + topLeft = colHeaders; + topLeft.Width = newRowHeaderWidth; + colHeaders.Width -= newRowHeaderWidth; + colHeaders.X += newRowHeaderWidth; } else - { - rowHeaders = insideLeft; - rowHeaders.Width = newRowHeaderWidth; - rowHeaders.X = insideLeft.Right - newRowHeaderWidth; - insideLeft.Width -= newRowHeaderWidth; - } - newLayout.RowHeaders = rowHeaders; - - if (layout.ColumnHeadersVisible) { - Rectangle topLeft = newLayout.TopLeftHeader; - Rectangle colHeaders = newLayout.ColumnHeaders; - if (alignLeft) - { - topLeft = colHeaders; - topLeft.Width = newRowHeaderWidth; - colHeaders.Width -= newRowHeaderWidth; - colHeaders.X += newRowHeaderWidth; - } - else - { - topLeft = colHeaders; - topLeft.Width = newRowHeaderWidth; - topLeft.X = colHeaders.Right - newRowHeaderWidth; - colHeaders.Width -= newRowHeaderWidth; - } - - newLayout.TopLeftHeader = topLeft; - newLayout.ColumnHeaders = colHeaders; - } - else { - newLayout.TopLeftHeader = Rectangle.Empty; - } - } - else { - newLayout.RowHeaders = Rectangle.Empty; - newLayout.TopLeftHeader = Rectangle.Empty; - } - - // The Data region - newLayout.Data = insideLeft; - newLayout.Inside = inside; - - this.layout = newLayout; - - LayoutScrollBars(); - - // if the user shrank the grid client area, then OnResize invalidated the old - // resize area. however, we need to invalidate the left upper corner in the new ResizeArea - // note that we can't take the Invalidate call from the OnResize method, because if the - // user enlarges the form then the old area will not be invalidated. - // - if (!oldResizeRect.Equals(this.layout.ResizeBoxRect) && !this.layout.ResizeBoxRect.IsEmpty) - Invalidate(this.layout.ResizeBoxRect); - - this.layout.dirty = false; - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: " + layout.ToString()); - } - - /// - /// Computes the number of pixels to scroll to scroll from one - /// row to another. - /// - private int ComputeRowDelta(int from, int to) { - int first = from; - int last = to; - int sign = -1; - if (first > last) { - first = to; - last = from; - sign = 1; + { + topLeft = colHeaders; + topLeft.Width = newRowHeaderWidth; + topLeft.X = colHeaders.Right - newRowHeaderWidth; + colHeaders.Width -= newRowHeaderWidth; + } + + newLayout.TopLeftHeader = topLeft; + newLayout.ColumnHeaders = colHeaders; } - DataGridRow[] localGridRows = DataGridRows; - int delta = 0; - for (int row = first; row < last; ++row) { - delta += localGridRows[row].Height; + else + { + newLayout.TopLeftHeader = Rectangle.Empty; } - return sign * delta; } - - internal int MinimumRowHeaderWidth() { - return minRowHeaderWidth; + else + { + newLayout.RowHeaders = Rectangle.Empty; + newLayout.TopLeftHeader = Rectangle.Empty; } - - internal void ComputeMinimumRowHeaderWidth() { - minRowHeaderWidth = errorRowBitmapWidth; // the size of the pencil, star and row selector images are the same as the image for the error bitmap - if (this.ListHasErrors) - minRowHeaderWidth += errorRowBitmapWidth; - if (this.myGridTable != null && this.myGridTable.RelationsList.Count != 0) - minRowHeaderWidth += 15; // the size of the plus/minus glyph and spacing around it + + // The Data region + newLayout.Data = insideLeft; + newLayout.Inside = inside; + + this.layout = newLayout; + + LayoutScrollBars(); + + // if the user shrank the grid client area, then OnResize invalidated the old + // resize area. however, we need to invalidate the left upper corner in the new ResizeArea + // note that we can't take the Invalidate call from the OnResize method, because if the + // user enlarges the form then the old area will not be invalidated. + // + if (!oldResizeRect.Equals(this.layout.ResizeBoxRect) && !this.layout.ResizeBoxRect.IsEmpty) + Invalidate(this.layout.ResizeBoxRect); + + this.layout.dirty = false; + Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: " + layout.ToString()); + } + + /// + /// Computes the number of pixels to scroll to scroll from one + /// row to another. + /// + private int ComputeRowDelta(int from, int to) + { + int first = from; + int last = to; + int sign = -1; + if (first > last) + { + first = to; + last = from; + sign = 1; } - - /// - /// Updates the internal variables with the number of columns visible - /// inside the Grid's client rectangle. - /// - private void ComputeVisibleColumns() { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: ComputeVisibleColumns"); - EnsureBound(); - - GridColumnStylesCollection columns = myGridTable.GridColumnStyles; - - int nGridCols = columns.Count; - int cx = - negOffset; - int visibleColumns = 0; - int visibleWidth = layout.Data.Width; - int curCol = firstVisibleCol; - - // the same problem with negative numbers: - // if the width passed in is negative, then return 0 - // - // added the check for the columns.Count == 0 - // - if (visibleWidth < 0 || columns.Count == 0) + DataGridRow[] localGridRows = DataGridRows; + int delta = 0; + for (int row = first; row < last; ++row) + { + delta += localGridRows[row].Height; + } + return sign * delta; + } + + internal int MinimumRowHeaderWidth() + { + return minRowHeaderWidth; + } + + internal void ComputeMinimumRowHeaderWidth() + { + minRowHeaderWidth = errorRowBitmapWidth; // the size of the pencil, star and row selector images are the same as the image for the error bitmap + if (this.ListHasErrors) + minRowHeaderWidth += errorRowBitmapWidth; + if (this.myGridTable != null && this.myGridTable.RelationsList.Count != 0) + minRowHeaderWidth += 15; // the size of the plus/minus glyph and spacing around it + } + + /// + /// Updates the internal variables with the number of columns visible + /// inside the Grid's client rectangle. + /// + private void ComputeVisibleColumns() + { + Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: ComputeVisibleColumns"); + EnsureBound(); + + GridColumnStylesCollection columns = myGridTable.GridColumnStyles; + + int nGridCols = columns.Count; + int cx = -negOffset; + int visibleColumns = 0; + int visibleWidth = layout.Data.Width; + int curCol = firstVisibleCol; + + // the same problem with negative numbers: + // if the width passed in is negative, then return 0 + // + // added the check for the columns.Count == 0 + // + if (visibleWidth < 0 || columns.Count == 0) + { + numVisibleCols = firstVisibleCol = 0; + lastTotallyVisibleCol = -1; + return; + } + + while (cx < visibleWidth && curCol < nGridCols) + { + // if (columns.Visible && columns.PropertyDescriptor != null) + if (columns[curCol].PropertyDescriptor != null) + cx += columns[curCol].Width; + curCol++; + visibleColumns++; + } + + numVisibleCols = visibleColumns; + + // if we inflate the data area + // then we paint columns to the left of firstVisibleColumn + if (cx < visibleWidth) + { + for (int i = firstVisibleCol - 1; i > 0; i--) + { + if (cx + columns[i].Width > visibleWidth) + break; + // if (columns.Visible && columns.PropertyDescriptor != null) + if (columns[i].PropertyDescriptor != null) + cx += columns[i].Width; + visibleColumns++; + firstVisibleCol--; + } + + if (numVisibleCols != visibleColumns) { - numVisibleCols = firstVisibleCol = 0; + Debug.Assert(numVisibleCols < visibleColumns, "the number of visible columns can only grow"); + // is there space for more columns than were visible? + // if so, then we need to repaint Data and ColumnHeaders + Invalidate(layout.Data); + Invalidate(layout.ColumnHeaders); + + // update the number of visible columns to the new reality + numVisibleCols = visibleColumns; + } + } + + lastTotallyVisibleCol = firstVisibleCol + numVisibleCols - 1; + if (cx > visibleWidth) + { + if (numVisibleCols <= 1 || (numVisibleCols == 2 && this.negOffset != 0)) + { + // no column is entirely visible lastTotallyVisibleCol = -1; - return; } - - while (cx < visibleWidth && curCol < nGridCols) + else { - // if (columns.Visible && columns.PropertyDescriptor != null) - if (columns[curCol].PropertyDescriptor != null) - cx += columns[curCol].Width; - curCol++; - visibleColumns ++; + lastTotallyVisibleCol--; } - - numVisibleCols = visibleColumns; - - // if we inflate the data area - // then we paint columns to the left of firstVisibleColumn - if (cx < visibleWidth) + } + } + + /// + /// Determines which column is the first visible given + /// the object's horizontalOffset. + /// + private int ComputeFirstVisibleColumn() + { + int first = 0; + if (this.horizontalOffset == 0) + { + negOffset = 0; + return 0; + } + + // we will check to see if myGridTables.GridColumns.Count != 0 + // because when we reset the dataGridTable, we don't have any columns, and we still + // call HorizontalOffset = 0, and that will call ComputeFirstVisibleColumn with an empty collection of columns. + if (myGridTable != null && myGridTable.GridColumnStyles != null && myGridTable.GridColumnStyles.Count != 0) + { + GridColumnStylesCollection columns = myGridTable.GridColumnStyles; + int cx = 0; + int nGridCols = columns.Count; + + if (columns[0].Width == -1) { - for (int i = firstVisibleCol -1; i > 0; i--) - { - if (cx + columns[i].Width > visibleWidth) - break; - // if (columns.Visible && columns.PropertyDescriptor != null) - if (columns[i].PropertyDescriptor != null) - cx += columns[i].Width; - visibleColumns ++; - firstVisibleCol --; - } - - if (numVisibleCols != visibleColumns) + // the columns are not initialized yet + // +#if DEBUG + for (int i = 0; i < nGridCols; i++) { - Debug.Assert(numVisibleCols < visibleColumns, "the number of visible columns can only grow"); - // is there space for more columns than were visible? - // if so, then we need to repaint Data and ColumnHeaders - Invalidate(layout.Data); - Invalidate(layout.ColumnHeaders); - - // update the number of visible columns to the new reality - numVisibleCols = visibleColumns; + Debug.Assert(columns[i].Width == -1, "the columns' widths should not be initialized"); } +#endif // DEBUG + negOffset = 0; + return 0; } - - lastTotallyVisibleCol = firstVisibleCol + numVisibleCols - 1; - if (cx > visibleWidth) { - if (numVisibleCols <= 1 || (numVisibleCols == 2 && this.negOffset != 0)) { - // no column is entirely visible - lastTotallyVisibleCol = -1; - } else { - lastTotallyVisibleCol--; - } + + for (first = 0; first < nGridCols; first++) + { + // if (columns[first].Visible && columns[first].PropertyDescriptor != null); + if (columns[first].PropertyDescriptor != null) + cx += columns[first].Width; + if (cx > horizontalOffset) + break; } - } - - /// - /// Determines which column is the first visible given - /// the object's horizontalOffset. - /// - private int ComputeFirstVisibleColumn() { - int first = 0; - if (this.horizontalOffset == 0) { + // first may actually be the number of columns + // in that case all the columns fit in the layout data + if (first == nGridCols) + { + Debug.Assert(cx <= horizontalOffset, "look at the for loop before: we only exit that loop early if the cx is over the horizontal offset"); negOffset = 0; return 0; } - - // we will check to see if myGridTables.GridColumns.Count != 0 - // because when we reset the dataGridTable, we don't have any columns, and we still - // call HorizontalOffset = 0, and that will call ComputeFirstVisibleColumn with an empty collection of columns. - if (myGridTable != null && myGridTable.GridColumnStyles != null && myGridTable.GridColumnStyles.Count != 0) { - GridColumnStylesCollection columns = myGridTable.GridColumnStyles; - int cx = 0; - int nGridCols = columns.Count; - - if (columns[0].Width == -1) { - // the columns are not initialized yet - // - #if DEBUG - for (int i = 0; i < nGridCols; i++) { - Debug.Assert(columns[i].Width == -1, "the columns' widths should not be initialized"); - } - #endif // DEBUG - negOffset = 0; - return 0; - } - - for (first = 0; first < nGridCols; first++) { - // if (columns[first].Visible && columns[first].PropertyDescriptor != null); - if (columns[first].PropertyDescriptor != null) - cx += columns[first].Width; - if (cx > horizontalOffset) - break; - } - // first may actually be the number of columns - // in that case all the columns fit in the layout data - if (first == nGridCols) { - Debug.Assert(cx <= horizontalOffset, "look at the for loop before: we only exit that loop early if the cx is over the horizontal offset"); - negOffset = 0; - return 0; - } - negOffset = columns[first].Width - (cx - horizontalOffset); - //Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "DataGridScrolling: ComputeFirstVisibleColumn, ret = " + first.ToString() + ", negOffset = " + negOffset.ToString()); - } - return first; + negOffset = columns[first].Width - (cx - horizontalOffset); + //Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "DataGridScrolling: ComputeFirstVisibleColumn, ret = " + first.ToString() + ", negOffset = " + negOffset.ToString()); } - - /// - /// Updates the internal variables with the number of rows visible - /// in a given DataGrid Layout. - /// - private void ComputeVisibleRows() { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: ComputeVisibleRows"); - EnsureBound(); - - Rectangle data = layout.Data; - int visibleHeight = data.Height; - int cy = 0; - int visibleRows = 0; - DataGridRow[] localGridRows = DataGridRows; - int numRows = DataGridRowsLength; - - // when minimizing the dataGrid window, we will get negative values for the - // layout.Data.Width and layout.Data.Height ( is this a + return first; + } + + /// + /// Updates the internal variables with the number of rows visible + /// in a given DataGrid Layout. + /// + private void ComputeVisibleRows() + { + Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: ComputeVisibleRows"); + EnsureBound(); + + Rectangle data = layout.Data; + int visibleHeight = data.Height; + int cy = 0; + int visibleRows = 0; + DataGridRow[] localGridRows = DataGridRows; + int numRows = DataGridRowsLength; + + // when minimizing the dataGrid window, we will get negative values for the + // layout.Data.Width and layout.Data.Height ( is this a + + if (visibleHeight < 0) + { + numVisibleRows = numTotallyVisibleRows = 0; + return; + } + + for (int i = firstVisibleRow; i < numRows; ++i) + { + if (cy > visibleHeight) + break; + cy += localGridRows[i].Height; + visibleRows++; + } - if (visibleHeight < 0) + if (cy < visibleHeight) + { + for (int i = firstVisibleRow - 1; i >= 0; i--) { - numVisibleRows = numTotallyVisibleRows = 0; - return; - } - - for (int i = firstVisibleRow; i < numRows; ++i) { - if (cy > visibleHeight) + int height = localGridRows[i].Height; + if (cy + height > visibleHeight) break; - cy += localGridRows[i].Height; + cy += height; + firstVisibleRow--; visibleRows++; } - - if (cy < visibleHeight) { - for (int i = firstVisibleRow-1; i >= 0; i--) { - int height = localGridRows[i].Height; - if (cy + height > visibleHeight) - break; - cy += height; - firstVisibleRow--; - visibleRows++; - } - } - - numVisibleRows = numTotallyVisibleRows = visibleRows; - if (cy > visibleHeight) - numTotallyVisibleRows--; - - Debug.Assert(numVisibleRows >= 0, "the number of visible rows can't be negative"); - Debug.Assert(numTotallyVisibleRows >= 0, "the number of totally visible rows can't be negative"); } - - - /// - /// Constructs the new instance of the accessibility object for this control. Subclasses - /// should not call base.CreateAccessibilityObject. - /// - protected override AccessibleObject CreateAccessibilityInstance() { - return new DataGridAccessibleObject(this); + + numVisibleRows = numTotallyVisibleRows = visibleRows; + if (cy > visibleHeight) + numTotallyVisibleRows--; + + Debug.Assert(numVisibleRows >= 0, "the number of visible rows can't be negative"); + Debug.Assert(numTotallyVisibleRows >= 0, "the number of totally visible rows can't be negative"); + } + + + /// + /// Constructs the new instance of the accessibility object for this control. Subclasses + /// should not call base.CreateAccessibilityObject. + /// + protected override AccessibleObject CreateAccessibilityInstance() + { + return new DataGridAccessibleObject(this); + } + + + /// + /// Creates a DataGridState representing the child table retrieved + /// from the passed DataRelation. + /// + private DataGridState CreateChildState(string relationName, DataGridRow source) + { + DataGridState dgs = new DataGridState(); + + string newDataMember; + if (string.IsNullOrEmpty(this.DataMember)) + { + newDataMember = relationName; } - - - /// - /// Creates a DataGridState representing the child table retrieved - /// from the passed DataRelation. - /// - private DataGridState CreateChildState(string relationName, DataGridRow source) { - DataGridState dgs = new DataGridState(); - - string newDataMember; - if (string.IsNullOrEmpty(this.DataMember)) + else + { + newDataMember = this.DataMember + "." + relationName; + } + + CurrencyManager childLM = (CurrencyManager)this.BindingContext[this.DataSource, newDataMember]; + + dgs.DataSource = this.DataSource; + dgs.DataMember = newDataMember; + dgs.ListManager = childLM; + + dgs.DataGridRows = null; + dgs.DataGridRowsLength = childLM.Count + (policy.AllowAdd ? 1 : 0); + + return dgs; + } + + + /// + /// Constructs a Layout object containing the state + /// for a newly constructed DataGrid. + /// + private LayoutData CreateInitialLayoutState() + { + Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: CreateInitialLayoutState"); + LayoutData newLayout = new LayoutData(); + newLayout.Inside = new Rectangle(); + newLayout.TopLeftHeader = new Rectangle(); + newLayout.ColumnHeaders = new Rectangle(); + newLayout.RowHeaders = new Rectangle(); + newLayout.Data = new Rectangle(); + newLayout.Caption = new Rectangle(); + newLayout.ParentRows = new Rectangle(); + newLayout.ResizeBoxRect = new Rectangle(); + newLayout.ColumnHeadersVisible = true; + newLayout.RowHeadersVisible = true; + newLayout.CaptionVisible = defaultCaptionVisible; + newLayout.ParentRowsVisible = defaultParentRowsVisible; + newLayout.ClientRectangle = ClientRectangle; + return newLayout; + } + + /// + /// The DataGrid caches an array of rectangular areas + /// which represent the area which scrolls left to right. + /// This method is invoked whenever the DataGrid needs + /// this scrollable region. + /// + private NativeMethods.RECT[] CreateScrollableRegion(Rectangle scroll) + { + if (cachedScrollableRegion != null) + { + return cachedScrollableRegion; + } + + bool alignToRight = isRightToLeft(); + + using (Region region = new Region(scroll)) + { + int nRows = numVisibleRows; + int cy = layout.Data.Y; + int cx = layout.Data.X; + DataGridRow[] localGridRows = DataGridRows; + for (int r = firstVisibleRow; r < nRows; r++) { - newDataMember = relationName; + int rowHeight = localGridRows[r].Height; + Rectangle rowExclude = localGridRows[r].GetNonScrollableArea(); + rowExclude.X += cx; + rowExclude.X = MirrorRectangle(rowExclude, layout.Data, alignToRight); + if (!rowExclude.IsEmpty) + { + region.Exclude(new Rectangle(rowExclude.X, + rowExclude.Y + cy, + rowExclude.Width, + rowExclude.Height)); + } + cy += rowHeight; } - else + + using (Graphics graphics = CreateGraphicsInternal()) { - newDataMember = this.DataMember + "." + relationName; + IntPtr handle = region.GetHrgn(graphics); + if (handle != IntPtr.Zero) + { + cachedScrollableRegion = UnsafeNativeMethods.GetRectsFromRegion(handle); + + region.ReleaseHrgn(handle); + } } - - CurrencyManager childLM = (CurrencyManager) this.BindingContext[this.DataSource, newDataMember]; - - dgs.DataSource = this.DataSource; - dgs.DataMember = newDataMember; - dgs.ListManager = childLM; - - dgs.DataGridRows = null; - dgs.DataGridRowsLength = childLM.Count + (policy.AllowAdd ? 1 : 0); - - return dgs; - } - - - /// - /// Constructs a Layout object containing the state - /// for a newly constructed DataGrid. - /// - private LayoutData CreateInitialLayoutState() { - Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: CreateInitialLayoutState"); - LayoutData newLayout = new LayoutData(); - newLayout.Inside = new Rectangle(); - newLayout.TopLeftHeader = new Rectangle(); - newLayout.ColumnHeaders = new Rectangle(); - newLayout.RowHeaders = new Rectangle(); - newLayout.Data = new Rectangle(); - newLayout.Caption = new Rectangle(); - newLayout.ParentRows = new Rectangle(); - newLayout.ResizeBoxRect = new Rectangle(); - newLayout.ColumnHeadersVisible = true; - newLayout.RowHeadersVisible = true; - newLayout.CaptionVisible = defaultCaptionVisible; - newLayout.ParentRowsVisible = defaultParentRowsVisible; - newLayout.ClientRectangle = ClientRectangle; - return newLayout; } - - /// - /// The DataGrid caches an array of rectangular areas - /// which represent the area which scrolls left to right. - /// This method is invoked whenever the DataGrid needs - /// this scrollable region. - /// - private NativeMethods.RECT[] CreateScrollableRegion(Rectangle scroll) { - if (cachedScrollableRegion != null) { - return cachedScrollableRegion; + + return cachedScrollableRegion; + } + + /// + /// Disposes of the resources (other than memory) used + /// by the . + /// + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (vertScrollBar != null) + vertScrollBar.Dispose(); + if (horizScrollBar != null) + horizScrollBar.Dispose(); + + if (this.toBeDisposedEditingControl != null) + { + this.toBeDisposedEditingControl.Dispose(); + this.toBeDisposedEditingControl = null; } - - bool alignToRight = isRightToLeft(); - - using(Region region = new Region(scroll)) { - int nRows = numVisibleRows; - int cy = layout.Data.Y; - int cx = layout.Data.X; - DataGridRow[] localGridRows = DataGridRows; - for (int r = firstVisibleRow; r < nRows; r++) { - int rowHeight = localGridRows[r].Height; - Rectangle rowExclude = localGridRows[r].GetNonScrollableArea(); - rowExclude.X += cx; - rowExclude.X = MirrorRectangle(rowExclude, layout.Data, alignToRight); - if (!rowExclude.IsEmpty) { - region.Exclude(new Rectangle(rowExclude.X, - rowExclude.Y + cy, - rowExclude.Width, - rowExclude.Height)); - } - cy += rowHeight; - } - - using (Graphics graphics = CreateGraphicsInternal()) { - IntPtr handle = region.GetHrgn(graphics); - if (handle != IntPtr.Zero) { - cachedScrollableRegion = UnsafeNativeMethods.GetRectsFromRegion(handle); - region.ReleaseHrgn(handle); - } - } - } - - return cachedScrollableRegion; - } - - /// - /// Disposes of the resources (other than memory) used - /// by the . - /// - protected override void Dispose(bool disposing) { - if (disposing) { - if (vertScrollBar != null) - vertScrollBar.Dispose(); - if (horizScrollBar != null) - horizScrollBar.Dispose(); - - if (this.toBeDisposedEditingControl != null) { - this.toBeDisposedEditingControl.Dispose(); - this.toBeDisposedEditingControl = null; - } + GridTableStylesCollection tables = this.TableStyles; + if (tables != null) + { +#if DEBUG + Debug.Assert(this.myGridTable == null || this.myGridTable.IsDefault || tables.Contains(this.myGridTable), "how come that the currentTable is not in the list of tables?"); +#endif // DEBUG + for (int i = 0; i < tables.Count; i++) + tables[i].Dispose(); + } + } + base.Dispose(disposing); + } + + /// + /// Draws an XOR region to give UI feedback for Column Resizing. + /// This looks just like the Splitter control's UI when resizing. + /// + private void DrawColSplitBar(MouseEventArgs e) + { + Rectangle r = CalcColResizeFeedbackRect(e); + DrawSplitBar(r); + } + + /// + /// Draws an XOR region to give UI feedback for Row Resizing. + /// This looks just like the Splitter control's UI when resizing. + /// + private void DrawRowSplitBar(MouseEventArgs e) + { + Rectangle r = CalcRowResizeFeedbackRect(e); + DrawSplitBar(r); + } + + /// + /// Draws an XOR region to give UI feedback for Column/Row Resizing. + /// This looks just like the Splitter control's UI when resizing. + /// + private void DrawSplitBar(Rectangle r) + { + IntPtr parentHandle = Handle; + IntPtr dc = UnsafeNativeMethods.GetDCEx(new HandleRef(this, parentHandle), NativeMethods.NullHandleRef, NativeMethods.DCX_CACHE | NativeMethods.DCX_LOCKWINDOWUPDATE); + IntPtr halftone = ControlPaint.CreateHalftoneHBRUSH(); + IntPtr saveBrush = SafeNativeMethods.SelectObject(new HandleRef(this, dc), new HandleRef(null, halftone)); + SafeNativeMethods.PatBlt(new HandleRef(this, dc), r.X, r.Y, r.Width, r.Height, NativeMethods.PATINVERT); + SafeNativeMethods.SelectObject(new HandleRef(this, dc), new HandleRef(null, saveBrush)); + SafeNativeMethods.DeleteObject(new HandleRef(null, halftone)); + UnsafeNativeMethods.ReleaseDC(new HandleRef(this, parentHandle), new HandleRef(this, dc)); + } + + /// + /// Begin in-place editing of a cell. Any editing is commited + /// before the new edit takes place. + /// + /// This will always edit the currentCell + /// If you want to edit another cell than the current one, just reset CurrentCell + /// + private void Edit() + { + Edit(null); + } + + private void Edit(string displayText) + { + EnsureBound(); + + // we want to be able to edit a cell which is not visible, as in the case with editing and scrolling + // at the same time. So do not call Ensure Visible + // + // EnsureVisible(currentRow, currentCol); + + bool cellIsVisible = true; - GridTableStylesCollection tables = this.TableStyles; - if (tables != null) { - #if DEBUG - Debug.Assert(this.myGridTable == null || this.myGridTable.IsDefault || tables.Contains(this.myGridTable), "how come that the currentTable is not in the list of tables?"); - #endif // DEBUG - for (int i = 0; i < tables.Count; i++) - tables[i].Dispose(); - } - } - base.Dispose(disposing); - } - - /// - /// Draws an XOR region to give UI feedback for Column Resizing. - /// This looks just like the Splitter control's UI when resizing. - /// - private void DrawColSplitBar(MouseEventArgs e) + // whoever needs to call ResetSelection should not rely on + // Edit() to call it; + // + // ResetSelection(); + + EndEdit(); + + Debug.WriteLineIf(CompModSwitches.DataGridEditing.TraceVerbose, "DataGridEditing: Edit, currentRow = " + currentRow.ToString(CultureInfo.InvariantCulture) + + ", currentCol = " + currentCol.ToString(CultureInfo.InvariantCulture) + (displayText != null ? ", displayText= " + displayText : "")); + + /* allow navigation even if the policy does not allow editing + if (!policy.AllowEdit) + return; + */ + + DataGridRow[] localGridRows = DataGridRows; + + // what do you want to edit when there are no rows? + if (DataGridRowsLength == 0) + return; + + localGridRows[currentRow].OnEdit(); + editRow = localGridRows[currentRow]; + + // if the list has no columns, then what good is an edit? + if (this.myGridTable.GridColumnStyles.Count == 0) + return; + + // what if the currentCol does not have a propDesc? + editColumn = myGridTable.GridColumnStyles[currentCol]; + if (editColumn.PropertyDescriptor == null) + return; + + + Rectangle cellBounds = Rectangle.Empty; + if (currentRow < firstVisibleRow || currentRow > firstVisibleRow + numVisibleRows || + currentCol < firstVisibleCol || currentCol > firstVisibleCol + numVisibleCols - 1 || + (currentCol == firstVisibleCol && negOffset != 0)) { - Rectangle r = CalcColResizeFeedbackRect(e); - DrawSplitBar(r); + cellIsVisible = false; } - - /// - /// Draws an XOR region to give UI feedback for Row Resizing. - /// This looks just like the Splitter control's UI when resizing. - /// - private void DrawRowSplitBar(MouseEventArgs e) + else { - Rectangle r = CalcRowResizeFeedbackRect(e); - DrawSplitBar(r); + cellBounds = GetCellBounds(currentRow, currentCol); } - - /// - /// Draws an XOR region to give UI feedback for Column/Row Resizing. - /// This looks just like the Splitter control's UI when resizing. - /// - private void DrawSplitBar(Rectangle r) + + gridState[GRIDSTATE_isNavigating] = true; + gridState[GRIDSTATE_isEditing] = false; + + // once we call editColumn.Edit on a DataGridTextBoxColumn + // the edit control will become visible, and its bounds will get set. + // both actions cause Edit.Parent.OnLayout + // so we flag this change, cause we don't want to PerformLayout on the entire DataGrid + // everytime the edit column gets edited + gridState[GRIDSTATE_editControlChanging] = true; + + editColumn.Edit(this.ListManager, + currentRow, + cellBounds, + myGridTable.ReadOnly || this.ReadOnly || !policy.AllowEdit, + displayText, + cellIsVisible); + + // reset the editControlChanging to false + gridState[GRIDSTATE_editControlChanging] = false; + } + + /// + /// Requests an end to an edit operation taking place on the + /// + /// control. + /// + public bool EndEdit(DataGridColumnStyle gridColumn, int rowNumber, bool shouldAbort) + { + bool ret = false; + if (gridState[GRIDSTATE_isEditing]) { - IntPtr parentHandle = Handle; - IntPtr dc = UnsafeNativeMethods.GetDCEx(new HandleRef(this, parentHandle), NativeMethods.NullHandleRef, NativeMethods.DCX_CACHE | NativeMethods.DCX_LOCKWINDOWUPDATE); - IntPtr halftone = ControlPaint.CreateHalftoneHBRUSH(); - IntPtr saveBrush = SafeNativeMethods.SelectObject(new HandleRef(this, dc), new HandleRef(null, halftone)); - SafeNativeMethods.PatBlt(new HandleRef(this, dc), r.X, r.Y, r.Width, r.Height, NativeMethods.PATINVERT); - SafeNativeMethods.SelectObject(new HandleRef(this, dc), new HandleRef(null, saveBrush)); - SafeNativeMethods.DeleteObject(new HandleRef(null, halftone)); - UnsafeNativeMethods.ReleaseDC(new HandleRef(this, parentHandle), new HandleRef(this, dc)); - } - - /// - /// Begin in-place editing of a cell. Any editing is commited - /// before the new edit takes place. - /// - /// This will always edit the currentCell - /// If you want to edit another cell than the current one, just reset CurrentCell - /// - private void Edit() { - Edit(null); - } - - private void Edit(string displayText) { - EnsureBound(); - - // we want to be able to edit a cell which is not visible, as in the case with editing and scrolling - // at the same time. So do not call Ensure Visible - // - // EnsureVisible(currentRow, currentCol); - - bool cellIsVisible = true; - - // whoever needs to call ResetSelection should not rely on - // Edit() to call it; - // - // ResetSelection(); - - EndEdit(); - - Debug.WriteLineIf(CompModSwitches.DataGridEditing.TraceVerbose, "DataGridEditing: Edit, currentRow = " + currentRow.ToString(CultureInfo.InvariantCulture) + - ", currentCol = " + currentCol.ToString(CultureInfo.InvariantCulture) + (displayText != null ? ", displayText= " + displayText : "")); - - /* allow navigation even if the policy does not allow editing - if (!policy.AllowEdit) - return; - */ - - DataGridRow[] localGridRows = DataGridRows; - - // what do you want to edit when there are no rows? - if (DataGridRowsLength == 0) - return; - - localGridRows[currentRow].OnEdit(); - editRow = localGridRows[currentRow]; - - // if the list has no columns, then what good is an edit? - if (this.myGridTable.GridColumnStyles.Count == 0) - return; - - // what if the currentCol does not have a propDesc? - editColumn = myGridTable.GridColumnStyles[currentCol]; - if(editColumn.PropertyDescriptor == null) - return; - - - Rectangle cellBounds = Rectangle.Empty; - if (currentRow < firstVisibleRow || currentRow > firstVisibleRow + numVisibleRows || - currentCol < firstVisibleCol || currentCol > firstVisibleCol + numVisibleCols - 1 || - (currentCol == firstVisibleCol && negOffset != 0)) + if (gridColumn != editColumn) { - cellIsVisible = false; + Debug.WriteLineIf(CompModSwitches.DataGridEditing.TraceVerbose, "DataGridEditing: EndEdit requested on a column we are not editing."); } - else + if (rowNumber != editRow.RowNumber) { - cellBounds = GetCellBounds(currentRow, currentCol); - } - - gridState[GRIDSTATE_isNavigating] = true; - gridState[GRIDSTATE_isEditing] = false; - - // once we call editColumn.Edit on a DataGridTextBoxColumn - // the edit control will become visible, and its bounds will get set. - // both actions cause Edit.Parent.OnLayout - // so we flag this change, cause we don't want to PerformLayout on the entire DataGrid - // everytime the edit column gets edited - gridState[GRIDSTATE_editControlChanging] = true; - - editColumn.Edit(this.ListManager, - currentRow, - cellBounds, - myGridTable.ReadOnly || this.ReadOnly || !policy.AllowEdit, - displayText, - cellIsVisible); - - // reset the editControlChanging to false - gridState[GRIDSTATE_editControlChanging] = false; - } - - /// - /// Requests an end to an edit operation taking place on the - /// - /// control. - /// - public bool EndEdit(DataGridColumnStyle gridColumn, int rowNumber, bool shouldAbort) { - bool ret = false; - if (gridState[GRIDSTATE_isEditing]) { - if (gridColumn != editColumn) { - Debug.WriteLineIf(CompModSwitches.DataGridEditing.TraceVerbose, "DataGridEditing: EndEdit requested on a column we are not editing."); - } - if (rowNumber != editRow.RowNumber) { - Debug.WriteLineIf(CompModSwitches.DataGridEditing.TraceVerbose, "DataGridEditing: EndEdit requested on a row we are not editing."); - } - if (shouldAbort) { - AbortEdit(); - ret = true; - } - else - ret = CommitEdit(); - + Debug.WriteLineIf(CompModSwitches.DataGridEditing.TraceVerbose, "DataGridEditing: EndEdit requested on a row we are not editing."); } - return ret; - } - - /// - /// Ends any editing in progress by attempting to commit and then - /// aborting if not possible. - /// - private void EndEdit() { - Debug.WriteLineIf(CompModSwitches.DataGridEditing.TraceVerbose, "DataGridEditing: EndEdit"); - - if (!gridState[GRIDSTATE_isEditing] && !gridState[GRIDSTATE_isNavigating]) - return; - - if (!CommitEdit()) { + if (shouldAbort) + { AbortEdit(); + ret = true; } + else + ret = CommitEdit(); + } - - // PERF: we attempt to create a ListManager for the DataSource/DateMember combination - // we do this in order to check for a valid DataMember - // if the check succeeds, then it means that we actully put the listManager in the BindingContext's - // list of BindingManagers. this is fine, cause if the check succeds, then Set_ListManager - // will be called, and this will get the listManager from the bindingManagerBase hashTable kept in the BindingContext - // - // this will work if the dataMember does not contain any dots ('.') - // if the dataMember contains dots, then it will be more complicated: maybe part of the binding path - // is valid w/ the new dataSource - // but we can leave w/ this, cause in the designer the dataMember will be only a column name. and the DataSource/DataMember - // properties are for use w/ the designer. - // - private void EnforceValidDataMember(object value) { - Debug.Assert(value != null, "we should not have a null dataSource when we want to check for a valid dataMember"); - if (this.DataMember == null || this.DataMember.Length == 0) - return; - if (this.BindingContext == null) - return; - // - try { - BindingManagerBase bm = this.BindingContext[value, this.dataMember]; - } - catch { - this.dataMember = string.Empty; - } + return ret; + } + + /// + /// Ends any editing in progress by attempting to commit and then + /// aborting if not possible. + /// + private void EndEdit() + { + Debug.WriteLineIf(CompModSwitches.DataGridEditing.TraceVerbose, "DataGridEditing: EndEdit"); + + if (!gridState[GRIDSTATE_isEditing] && !gridState[GRIDSTATE_isNavigating]) + return; + + if (!CommitEdit()) + { + AbortEdit(); } - - // will be used by the columns to tell the grid that - // editing is taken place (ie, the grid is no longer in the - // editOrNavigateMode) - // - // also, tell the current row to lose child focus + } + + // PERF: we attempt to create a ListManager for the DataSource/DateMember combination + // we do this in order to check for a valid DataMember + // if the check succeeds, then it means that we actully put the listManager in the BindingContext's + // list of BindingManagers. this is fine, cause if the check succeds, then Set_ListManager + // will be called, and this will get the listManager from the bindingManagerBase hashTable kept in the BindingContext + // + // this will work if the dataMember does not contain any dots ('.') + // if the dataMember contains dots, then it will be more complicated: maybe part of the binding path + // is valid w/ the new dataSource + // but we can leave w/ this, cause in the designer the dataMember will be only a column name. and the DataSource/DataMember + // properties are for use w/ the designer. + // + private void EnforceValidDataMember(object value) + { + Debug.Assert(value != null, "we should not have a null dataSource when we want to check for a valid dataMember"); + if (this.DataMember == null || this.DataMember.Length == 0) + return; + if (this.BindingContext == null) + return; // - internal protected virtual void ColumnStartedEditing(Rectangle bounds) { - Debug.Assert( currentRow >= firstVisibleRow && currentRow <= firstVisibleRow + numVisibleRows, "how can one edit a row which is invisible?"); - DataGridRow[] localGridRows = DataGridRows; + try + { + BindingManagerBase bm = this.BindingContext[value, this.dataMember]; + } + catch + { + this.dataMember = string.Empty; + } + } - if (bounds.IsEmpty && this.editColumn is DataGridTextBoxColumn && this.currentRow != -1 && this.currentCol != -1) { - // set the bounds on the control - // this will only work w/ our DataGridTexBox control - DataGridTextBoxColumn col = this.editColumn as DataGridTextBoxColumn; - Rectangle editBounds = this.GetCellBounds(this.currentRow, this.currentCol); - - gridState[GRIDSTATE_editControlChanging] = true; - try { - col.TextBox.Bounds = editBounds; - } finally { - gridState[GRIDSTATE_editControlChanging] = false; - } - } + // will be used by the columns to tell the grid that + // editing is taken place (ie, the grid is no longer in the + // editOrNavigateMode) + // + // also, tell the current row to lose child focus + // + internal protected virtual void ColumnStartedEditing(Rectangle bounds) + { + Debug.Assert(currentRow >= firstVisibleRow && currentRow <= firstVisibleRow + numVisibleRows, "how can one edit a row which is invisible?"); + DataGridRow[] localGridRows = DataGridRows; - if (gridState[GRIDSTATE_inAddNewRow]) { - int currentRowCount = this.DataGridRowsLength; - DataGridRow[] newDataGridRows = new DataGridRow[currentRowCount + 1]; - for (int i = 0; i < currentRowCount; i++) { - newDataGridRows[i] = localGridRows[i]; - } - - - // put the AddNewRow - newDataGridRows[currentRowCount] = new DataGridAddNewRow(this, this.myGridTable, currentRowCount); - SetDataGridRows(newDataGridRows, currentRowCount + 1); - - Edit(); - // put this after the call to edit so that - // CommitEdit knows that the inAddNewRow is true; - gridState[GRIDSTATE_inAddNewRow] = false; - gridState[GRIDSTATE_isEditing] = true; - gridState[GRIDSTATE_isNavigating] = false; - return; + if (bounds.IsEmpty && this.editColumn is DataGridTextBoxColumn && this.currentRow != -1 && this.currentCol != -1) + { + // set the bounds on the control + // this will only work w/ our DataGridTexBox control + DataGridTextBoxColumn col = this.editColumn as DataGridTextBoxColumn; + Rectangle editBounds = this.GetCellBounds(this.currentRow, this.currentCol); + + gridState[GRIDSTATE_editControlChanging] = true; + try + { + col.TextBox.Bounds = editBounds; } - - gridState[GRIDSTATE_isEditing] = true; - gridState[GRIDSTATE_isNavigating] = false; - InvalidateRowHeader(this.currentRow); - - // tell the current row to lose the childFocuse - if (currentRow < localGridRows.Length) + finally { - localGridRows[currentRow].LoseChildFocus(layout.RowHeaders, isRightToLeft()); + gridState[GRIDSTATE_editControlChanging] = false; } } - - internal protected virtual void ColumnStartedEditing(Control editingControl) + + if (gridState[GRIDSTATE_inAddNewRow]) { - if (editingControl == null) + int currentRowCount = this.DataGridRowsLength; + DataGridRow[] newDataGridRows = new DataGridRow[currentRowCount + 1]; + for (int i = 0; i < currentRowCount; i++) { - return; + newDataGridRows[i] = localGridRows[i]; } - ColumnStartedEditing(editingControl.Bounds); - } - - /// - /// - /// Displays child relations, if any exist, for all rows or a - /// specific row. - /// - /// - public void Expand(int row) { - SetRowExpansionState(row, true); + + // put the AddNewRow + newDataGridRows[currentRowCount] = new DataGridAddNewRow(this, this.myGridTable, currentRowCount); + SetDataGridRows(newDataGridRows, currentRowCount + 1); + + Edit(); + // put this after the call to edit so that + // CommitEdit knows that the inAddNewRow is true; + gridState[GRIDSTATE_inAddNewRow] = false; + gridState[GRIDSTATE_isEditing] = true; + gridState[GRIDSTATE_isNavigating] = false; + return; } - - /// - /// - /// Creates a using the specified . - /// - /// - // protected and virtual because the SimpleDropdownDataGrid will override this - protected virtual DataGridColumnStyle CreateGridColumn(PropertyDescriptor prop, bool isDefault) { - return myGridTable == null ? null : myGridTable.CreateGridColumn(prop, isDefault); + + gridState[GRIDSTATE_isEditing] = true; + gridState[GRIDSTATE_isNavigating] = false; + InvalidateRowHeader(this.currentRow); + + // tell the current row to lose the childFocuse + if (currentRow < localGridRows.Length) + { + localGridRows[currentRow].LoseChildFocus(layout.RowHeaders, isRightToLeft()); } - - protected virtual DataGridColumnStyle CreateGridColumn(PropertyDescriptor prop) + } + + internal protected virtual void ColumnStartedEditing(Control editingControl) + { + if (editingControl == null) { - return myGridTable == null ? null : myGridTable.CreateGridColumn(prop); + return; } - - - #if PARENT_LINKS + + ColumnStartedEditing(editingControl.Bounds); + } + + /// + /// + /// Displays child relations, if any exist, for all rows or a + /// specific row. + /// + /// + public void Expand(int row) + { + SetRowExpansionState(row, true); + } + + /// + /// + /// Creates a using the specified . + /// + /// + // protected and virtual because the SimpleDropdownDataGrid will override this + protected virtual DataGridColumnStyle CreateGridColumn(PropertyDescriptor prop, bool isDefault) + { + return myGridTable == null ? null : myGridTable.CreateGridColumn(prop, isDefault); + } + + protected virtual DataGridColumnStyle CreateGridColumn(PropertyDescriptor prop) + { + return myGridTable == null ? null : myGridTable.CreateGridColumn(prop); + } + + +#if PARENT_LINKS private ListManager ListManagerForChildColumn(ListManager childListManager, PropertyDescriptor prop) { @@ -5779,1235 +6520,1374 @@ private ListManager ListManagerForChildColumn(ListManager childListManager, Prop return null; } - #endif - - /// - /// Specifies the end of the initialization code. - /// - public void EndInit() { - inInit = false; - if (myGridTable == null && this.ListManager != null) { - SetDataGridTable(this.TableStyles[this.ListManager.GetListName()], true); // true for forcing column creation - } - if (myGridTable != null) - myGridTable.DataGrid = this; +#endif + + /// + /// Specifies the end of the initialization code. + /// + public void EndInit() + { + inInit = false; + if (myGridTable == null && this.ListManager != null) + { + SetDataGridTable(this.TableStyles[this.ListManager.GetListName()], true); // true for forcing column creation } - - /// - /// Given a x coordinate, returns the column it is over. - /// - private int GetColFromX(int x) { - if (myGridTable == null) - return -1; - - Rectangle inside = layout.Data; - Debug.Assert(x >= inside.X && x < inside.Right, "x must be inside the horizontal bounds of layout.Data"); - - x = MirrorPoint(x, inside, isRightToLeft()); - - GridColumnStylesCollection columns = myGridTable.GridColumnStyles; - int columnCount = columns.Count; - - int cx = inside.X - negOffset; - int col = firstVisibleCol; - while (cx < inside.Width + inside.X && col < columnCount) { - // if (columns[col].Visible && columns[col].PropertyDescriptor != null) - if (columns[col].PropertyDescriptor != null) - cx += columns[col].Width; - if (cx > x) - return col; - ++col; - } + if (myGridTable != null) + myGridTable.DataGrid = this; + } + + /// + /// Given a x coordinate, returns the column it is over. + /// + private int GetColFromX(int x) + { + if (myGridTable == null) return -1; + + Rectangle inside = layout.Data; + Debug.Assert(x >= inside.X && x < inside.Right, "x must be inside the horizontal bounds of layout.Data"); + + x = MirrorPoint(x, inside, isRightToLeft()); + + GridColumnStylesCollection columns = myGridTable.GridColumnStyles; + int columnCount = columns.Count; + + int cx = inside.X - negOffset; + int col = firstVisibleCol; + while (cx < inside.Width + inside.X && col < columnCount) + { + // if (columns[col].Visible && columns[col].PropertyDescriptor != null) + if (columns[col].PropertyDescriptor != null) + cx += columns[col].Width; + if (cx > x) + return col; + ++col; + } + return -1; + } + + /// + /// Returns the coordinate of the left edge of the given column + /// Bi-Di: if the grid has the RightToLeft property set to RightToLeft.Yes, this will + /// return what appears as the right edge of the column + /// + internal int GetColBeg(int col) + { + Debug.Assert(myGridTable != null, "GetColBeg can't be called when myGridTable == null."); + + int offset = layout.Data.X - negOffset; + GridColumnStylesCollection columns = myGridTable.GridColumnStyles; + + int lastCol = Math.Min(col, columns.Count); + for (int i = firstVisibleCol; i < lastCol; ++i) + { + // if (columns[i].Visible && columns[i].PropertyDescriptor != null) + if (columns[i].PropertyDescriptor != null) + offset += columns[i].Width; } - - /// - /// Returns the coordinate of the left edge of the given column - /// Bi-Di: if the grid has the RightToLeft property set to RightToLeft.Yes, this will - /// return what appears as the right edge of the column - /// - internal int GetColBeg(int col) { - Debug.Assert(myGridTable != null, "GetColBeg can't be called when myGridTable == null."); - - int offset = layout.Data.X - negOffset; + return MirrorPoint(offset, layout.Data, isRightToLeft()); + } + + /// + /// Returns the coordinate of the right edge of the given column + /// Bi-Di: if the grid has the RightToLeft property set to RightToLeft.Yes, this will + /// return what appears as the left edge of the column + /// + internal int GetColEnd(int col) + { + // return MirrorPoint(GetColBeg(col) + myGridTable.GridColumnStyles[col].Width, layout.Data, isRightToLeft()); + int colBeg = GetColBeg(col); + Debug.Assert(myGridTable.GridColumnStyles[col].PropertyDescriptor != null, "why would we need the coordinate of a column that is not visible?"); + int width = myGridTable.GridColumnStyles[col].Width; + return isRightToLeft() ? colBeg - width : colBeg + width; + } + + private int GetColumnWidthSum() + { + int sum = 0; + if (myGridTable != null && myGridTable.GridColumnStyles != null) + { GridColumnStylesCollection columns = myGridTable.GridColumnStyles; - - int lastCol = Math.Min(col, columns.Count); - for (int i = firstVisibleCol; i < lastCol; ++i) { + + int columnsCount = columns.Count; + for (int i = 0; i < columnsCount; i++) // if (columns[i].Visible && columns[i].PropertyDescriptor != null) if (columns[i].PropertyDescriptor != null) - offset += columns[i].Width; - } - return MirrorPoint(offset, layout.Data, isRightToLeft()); - } - - /// - /// Returns the coordinate of the right edge of the given column - /// Bi-Di: if the grid has the RightToLeft property set to RightToLeft.Yes, this will - /// return what appears as the left edge of the column - /// - internal int GetColEnd(int col) { - // return MirrorPoint(GetColBeg(col) + myGridTable.GridColumnStyles[col].Width, layout.Data, isRightToLeft()); - int colBeg = GetColBeg(col); - Debug.Assert(myGridTable.GridColumnStyles[col].PropertyDescriptor != null, "why would we need the coordinate of a column that is not visible?"); - int width = myGridTable.GridColumnStyles[col].Width; - return isRightToLeft() ? colBeg - width : colBeg + width; + sum += columns[i].Width; } - - private int GetColumnWidthSum() { - int sum = 0; - if (myGridTable != null && myGridTable.GridColumnStyles != null) { - GridColumnStylesCollection columns = myGridTable.GridColumnStyles; - - int columnsCount = columns.Count; - for (int i = 0; i < columnsCount; i++) - // if (columns[i].Visible && columns[i].PropertyDescriptor != null) - if (columns[i].PropertyDescriptor != null) - sum += columns[i].Width; + return sum; + } + + /// + /// Not all rows in the DataGrid are expandable, + /// this computes which ones are and returns an array + /// of references to them. + /// + private DataGridRelationshipRow[] GetExpandableRows() + { + int nExpandableRows = DataGridRowsLength; + DataGridRow[] localGridRows = DataGridRows; + if (policy.AllowAdd) + nExpandableRows = Math.Max(nExpandableRows - 1, 0); + DataGridRelationshipRow[] expandableRows = new DataGridRelationshipRow[nExpandableRows]; + for (int i = 0; i < nExpandableRows; i++) + expandableRows[i] = (DataGridRelationshipRow)localGridRows[i]; + return expandableRows; + } + + /// + /// Returns the row number underneath the given y coordinate. + /// + private int GetRowFromY(int y) + { + Rectangle inside = layout.Data; + Debug.Assert(y >= inside.Y && y < inside.Bottom, "y must be inside the vertical bounds of the data"); + + int cy = inside.Y; + int row = firstVisibleRow; + int rowCount = DataGridRowsLength; + DataGridRow[] localGridRows = DataGridRows; + int bottom = inside.Bottom; + while (cy < bottom && row < rowCount) + { + cy += localGridRows[row].Height; + if (cy > y) + { + return row; } - return sum; + ++row; } - - /// - /// Not all rows in the DataGrid are expandable, - /// this computes which ones are and returns an array - /// of references to them. - /// - private DataGridRelationshipRow[] GetExpandableRows() { - int nExpandableRows = DataGridRowsLength; - DataGridRow[] localGridRows = DataGridRows; - if (policy.AllowAdd) - nExpandableRows = Math.Max(nExpandableRows-1,0); - DataGridRelationshipRow[] expandableRows = new DataGridRelationshipRow[nExpandableRows]; - for (int i = 0; i < nExpandableRows; i++) - expandableRows[i] = (DataGridRelationshipRow)localGridRows[i]; - return expandableRows; - } - - /// - /// Returns the row number underneath the given y coordinate. - /// - private int GetRowFromY(int y) { - Rectangle inside = layout.Data; - Debug.Assert(y >= inside.Y && y < inside.Bottom, "y must be inside the vertical bounds of the data"); - - int cy = inside.Y; - int row = firstVisibleRow; - int rowCount = DataGridRowsLength; - DataGridRow[] localGridRows = DataGridRows; - int bottom = inside.Bottom; - while (cy < bottom && row < rowCount) { - cy += localGridRows[row].Height; - if (cy > y) { - return row; + return -1; + } + + internal Rectangle GetRowHeaderRect() + { + return layout.RowHeaders; + } + + internal Rectangle GetColumnHeadersRect() + { + return layout.ColumnHeaders; + } + + /// + /// Determines where on the control's ClientRectangle a given row is + /// painting to. + /// + private Rectangle GetRowRect(int rowNumber) + { + Rectangle inside = layout.Data; + int cy = inside.Y; + DataGridRow[] localGridRows = DataGridRows; + for (int row = firstVisibleRow; row <= rowNumber; ++row) + { + if (cy > inside.Bottom) + { + break; + } + if (row == rowNumber) + { + Rectangle rowRect = new Rectangle(inside.X, + cy, + inside.Width, + localGridRows[row].Height); + if (layout.RowHeadersVisible) + { + rowRect.Width += layout.RowHeaders.Width; + rowRect.X -= isRightToLeft() ? 0 : layout.RowHeaders.Width; } - ++row; + return rowRect; } - return -1; + cy += localGridRows[row].Height; } - - internal Rectangle GetRowHeaderRect() { - return layout.RowHeaders; + return Rectangle.Empty; + } + + /// + /// Returns the coordinate of the top edge of the given row + /// + private int GetRowTop(int row) + { + DataGridRow[] localGridRows = DataGridRows; + int offset = layout.Data.Y; + int lastRow = Math.Min(row, DataGridRowsLength); + for (int i = firstVisibleRow; i < lastRow; ++i) + { + offset += localGridRows[i].Height; } - - internal Rectangle GetColumnHeadersRect() { - return layout.ColumnHeaders; + for (int i = firstVisibleRow; i > lastRow; i--) + { + offset -= localGridRows[i].Height; } - - /// - /// Determines where on the control's ClientRectangle a given row is - /// painting to. - /// - private Rectangle GetRowRect(int rowNumber) { - Rectangle inside = layout.Data; - int cy = inside.Y; - DataGridRow[] localGridRows = DataGridRows; - for (int row = firstVisibleRow; row <= rowNumber; ++row) { - if (cy > inside.Bottom) { - break; - } - if (row == rowNumber) { - Rectangle rowRect = new Rectangle(inside.X, - cy, - inside.Width, - localGridRows[row].Height); - if (layout.RowHeadersVisible) { - rowRect.Width += layout.RowHeaders.Width; - rowRect.X -= isRightToLeft() ? 0 : layout.RowHeaders.Width; - } - return rowRect; - } - cy += localGridRows[row].Height; - } - return Rectangle.Empty; + return offset; + } + + /// + /// Returns the coordinate of the bottom edge of the given row + /// + private int GetRowBottom(int row) + { + DataGridRow[] localGridRows = DataGridRows; + + return GetRowTop(row) + localGridRows[row].Height; + } + + /// + /// This method is called on methods that need the grid + /// to be bound to a DataTable to work. + /// + private void EnsureBound() + { + if (!Bound) + { + throw new InvalidOperationException(SR.DataGridUnbound); } - - /// - /// Returns the coordinate of the top edge of the given row - /// - private int GetRowTop(int row) { - DataGridRow[] localGridRows = DataGridRows; - int offset = layout.Data.Y; - int lastRow = Math.Min(row, DataGridRowsLength); - for (int i = firstVisibleRow; i < lastRow; ++i) { - offset += localGridRows[i].Height; - } - for (int i=firstVisibleRow; i > lastRow; i--) { - offset -= localGridRows[i].Height; - } - return offset; + } + + private void EnsureVisible(int row, int col) + { + if (row < firstVisibleRow + || row >= firstVisibleRow + numTotallyVisibleRows) + { + int dRows = ComputeDeltaRows(row); + ScrollDown(dRows); } - - /// - /// Returns the coordinate of the bottom edge of the given row - /// - private int GetRowBottom(int row) { - DataGridRow[] localGridRows = DataGridRows; - - return GetRowTop(row) + localGridRows[row].Height; + + if (this.firstVisibleCol == 0 && this.numVisibleCols == 0 && this.lastTotallyVisibleCol == -1) + { + // no columns are displayed whatsoever + // some sanity checks + Debug.Assert(this.negOffset == 0, " no columns are displayed so the negative offset should be 0"); + return; } - - /// - /// This method is called on methods that need the grid - /// to be bound to a DataTable to work. - /// - private void EnsureBound() { - if (!Bound) { - throw new InvalidOperationException(SR.DataGridUnbound); + + int previousFirstVisibleCol = this.firstVisibleCol; + int previousNegOffset = this.negOffset; + int previousLastTotallyVisibleCol = this.lastTotallyVisibleCol; + + while (col < firstVisibleCol + || col == firstVisibleCol && negOffset != 0 + || lastTotallyVisibleCol == -1 && col > firstVisibleCol + || lastTotallyVisibleCol > -1 && col > lastTotallyVisibleCol) + { + + ScrollToColumn(col); + + if (previousFirstVisibleCol == this.firstVisibleCol && + previousNegOffset == this.negOffset && + previousLastTotallyVisibleCol == this.lastTotallyVisibleCol) + { + // nothing changed since the last iteration + // don't get into an infinite loop + break; } + previousFirstVisibleCol = firstVisibleCol; + previousNegOffset = this.negOffset; + previousLastTotallyVisibleCol = this.lastTotallyVisibleCol; + + // continue to scroll to the right until the scrollTo column is the totally last visible column or it is the first visible column } - - private void EnsureVisible(int row, int col) { - if (row < firstVisibleRow - || row >= firstVisibleRow + numTotallyVisibleRows) { - int dRows = ComputeDeltaRows(row); - ScrollDown(dRows); - } - - if (this.firstVisibleCol == 0 && this.numVisibleCols == 0 && this.lastTotallyVisibleCol == -1) { - // no columns are displayed whatsoever - // some sanity checks - Debug.Assert(this.negOffset == 0, " no columns are displayed so the negative offset should be 0"); - return; - } + } - int previousFirstVisibleCol = this.firstVisibleCol; - int previousNegOffset = this.negOffset; - int previousLastTotallyVisibleCol = this.lastTotallyVisibleCol; + /// + /// Gets a + /// that specifies the four corners of the selected cell. + /// + public Rectangle GetCurrentCellBounds() + { + DataGridCell current = this.CurrentCell; + return GetCellBounds(current.RowNumber, current.ColumnNumber); + } + + /// + /// Gets the of the cell specified by row and column number. + /// + public Rectangle GetCellBounds(int row, int col) + { + DataGridRow[] localGridRows = DataGridRows; + Rectangle cellBounds = localGridRows[row].GetCellBounds(col); + cellBounds.Y += GetRowTop(row); + cellBounds.X += layout.Data.X - negOffset; + cellBounds.X = MirrorRectangle(cellBounds, layout.Data, isRightToLeft()); + return cellBounds; + } - while (col < firstVisibleCol - || col == firstVisibleCol && negOffset != 0 - || lastTotallyVisibleCol == -1 && col > firstVisibleCol - || lastTotallyVisibleCol > -1 && col > lastTotallyVisibleCol) { + /// + /// Gets the of the cell specified by . + /// + public Rectangle GetCellBounds(DataGridCell dgc) + { + return GetCellBounds(dgc.RowNumber, dgc.ColumnNumber); + } - ScrollToColumn(col); + // - if (previousFirstVisibleCol == this.firstVisibleCol && - previousNegOffset == this.negOffset && - previousLastTotallyVisibleCol == this.lastTotallyVisibleCol) { - // nothing changed since the last iteration - // don't get into an infinite loop - break; - } - previousFirstVisibleCol = firstVisibleCol; - previousNegOffset = this.negOffset; - previousLastTotallyVisibleCol = this.lastTotallyVisibleCol; - // continue to scroll to the right until the scrollTo column is the totally last visible column or it is the first visible column - } - } - - /// - /// Gets a - /// that specifies the four corners of the selected cell. - /// - public Rectangle GetCurrentCellBounds() { - DataGridCell current = this.CurrentCell; - return GetCellBounds(current.RowNumber, current.ColumnNumber); - } - - /// - /// Gets the of the cell specified by row and column number. - /// - public Rectangle GetCellBounds(int row, int col) { - DataGridRow[] localGridRows = DataGridRows; - Rectangle cellBounds = localGridRows[row].GetCellBounds(col); - cellBounds.Y += GetRowTop(row); - cellBounds.X += layout.Data.X - negOffset; - cellBounds.X = MirrorRectangle(cellBounds, layout.Data, isRightToLeft()); - return cellBounds; - } - - /// - /// Gets the of the cell specified by . - /// - public Rectangle GetCellBounds(DataGridCell dgc) { - return GetCellBounds(dgc.RowNumber, dgc.ColumnNumber); - } - - // + internal Rectangle GetRowBounds(DataGridRow row) + { + Rectangle rowBounds = new Rectangle(); + rowBounds.Y = GetRowTop(row.RowNumber); + rowBounds.X = layout.Data.X; + rowBounds.Height = row.Height; + rowBounds.Width = layout.Data.Width; + return rowBounds; + } + /// + /// Gets information, such as row and column number of a + /// clicked point on + /// the grid, + /// using the x + /// and y coordinate passed to the method. + /// + public HitTestInfo HitTest(int x, int y) + { + int topOfData = layout.Data.Y; + HitTestInfo ci = new HitTestInfo(); - internal Rectangle GetRowBounds(DataGridRow row) { - Rectangle rowBounds = new Rectangle(); - rowBounds.Y = GetRowTop(row.RowNumber); - rowBounds.X = layout.Data.X; - rowBounds.Height = row.Height; - rowBounds.Width = layout.Data.Width; - return rowBounds; + if (layout.CaptionVisible && layout.Caption.Contains(x, y)) + { + ci.type = HitTestType.Caption; + return ci; } - - /// - /// Gets information, such as row and column number of a - /// clicked point on - /// the grid, - /// using the x - /// and y coordinate passed to the method. - /// - public HitTestInfo HitTest(int x, int y) { - int topOfData = layout.Data.Y; - HitTestInfo ci = new HitTestInfo(); - - if (layout.CaptionVisible && layout.Caption.Contains(x,y)) { - ci.type = HitTestType.Caption; - return ci; - } - if (layout.ParentRowsVisible && layout.ParentRows.Contains(x,y)) { - ci.type = HitTestType.ParentRows; - return ci; - } - - if (!layout.Inside.Contains(x,y)) - return ci; - - if (layout.TopLeftHeader.Contains(x,y)) - return ci; - - // check for column resize - if (layout.ColumnHeaders.Contains(x,y)) { - ci.type = HitTestType.ColumnHeader; - ci.col = GetColFromX(x); - if (ci.col < 0) - return HitTestInfo.Nowhere; - int right = GetColBeg(ci.col + 1); - bool rightToLeft = isRightToLeft(); - if ((rightToLeft && x - right < 8) || (!rightToLeft && right - x < 8)) { - ci.type = HitTestType.ColumnResize; - } - return(allowColumnResize ? ci : HitTestInfo.Nowhere); - } - - //check for RowResize: - if (layout.RowHeaders.Contains(x,y)) { - ci.type = HitTestType.RowHeader; - ci.row = GetRowFromY(y); - if (ci.row < 0) - return HitTestInfo.Nowhere; - - // find out if the click was a RowResize click - DataGridRow[] localGridRows = DataGridRows; - int bottomBorder = GetRowTop(ci.row) + localGridRows[ci.row].Height; - if (bottomBorder - y - BorderWidth < 2 && !(localGridRows[ci.row] is DataGridAddNewRow)) { - ci.type = HitTestType.RowResize; - } - - return (allowRowResize ? ci : HitTestInfo.Nowhere); - } - - if (layout.Data.Contains(x,y)) { - ci.type = HitTestType.Cell; - ci.col = GetColFromX(x); - ci.row = GetRowFromY(y); - if (ci.col < 0 || ci.row < 0) return HitTestInfo.Nowhere; - return ci; - } + if (layout.ParentRowsVisible && layout.ParentRows.Contains(x, y)) + { + ci.type = HitTestType.ParentRows; return ci; } - - /// - /// Gets information, such as row and column number of a - /// clicked point on the grid, about the - /// grid using a specific - /// . - /// - public HitTestInfo HitTest(Point position) { - return HitTest(position.X, position.Y); + + if (!layout.Inside.Contains(x, y)) + return ci; + + if (layout.TopLeftHeader.Contains(x, y)) + return ci; + + // check for column resize + if (layout.ColumnHeaders.Contains(x, y)) + { + ci.type = HitTestType.ColumnHeader; + ci.col = GetColFromX(x); + if (ci.col < 0) + return HitTestInfo.Nowhere; + int right = GetColBeg(ci.col + 1); + bool rightToLeft = isRightToLeft(); + if ((rightToLeft && x - right < 8) || (!rightToLeft && right - x < 8)) + { + ci.type = HitTestType.ColumnResize; + } + return (allowColumnResize ? ci : HitTestInfo.Nowhere); } - - /// - /// Initializes the values for column widths in the table. - /// - private void InitializeColumnWidths() { - if (myGridTable == null) - return; - - GridColumnStylesCollection columns = myGridTable.GridColumnStyles; - int numCols = columns.Count; - - // Resize the columns to a approximation of a best fit. - // We find the best fit width of NumRowsForAutoResize rows - // and use it for each column. - int preferredColumnWidth = this.myGridTable.IsDefault ? this.PreferredColumnWidth : this.myGridTable.PreferredColumnWidth; - // if we set the PreferredColumnWidth to something else than AutoColumnSize - // then use that value - // - for (int col = 0; col < numCols; col++) { - // if the column width is not -1, then this column was initialized already - if (columns[col]._width != -1) continue; - - columns[col]._width = preferredColumnWidth; + + //check for RowResize: + if (layout.RowHeaders.Contains(x, y)) + { + ci.type = HitTestType.RowHeader; + ci.row = GetRowFromY(y); + if (ci.row < 0) + return HitTestInfo.Nowhere; + + // find out if the click was a RowResize click + DataGridRow[] localGridRows = DataGridRows; + int bottomBorder = GetRowTop(ci.row) + localGridRows[ci.row].Height; + if (bottomBorder - y - BorderWidth < 2 && !(localGridRows[ci.row] is DataGridAddNewRow)) + { + ci.type = HitTestType.RowResize; } + + return (allowRowResize ? ci : HitTestInfo.Nowhere); } - - /// - /// Invalidates the scrollable area of the DataGrid. - /// - internal void InvalidateInside() { - Invalidate(layout.Inside); + + if (layout.Data.Contains(x, y)) + { + ci.type = HitTestType.Cell; + ci.col = GetColFromX(x); + ci.row = GetRowFromY(y); + if (ci.col < 0 || ci.row < 0) + return HitTestInfo.Nowhere; + return ci; } - - /// - /// Invalidates the caption area of the DataGrid. - /// - internal void InvalidateCaption() { - if (layout.CaptionVisible) - Invalidate(layout.Caption); + return ci; + } + + /// + /// Gets information, such as row and column number of a + /// clicked point on the grid, about the + /// grid using a specific + /// . + /// + public HitTestInfo HitTest(Point position) + { + return HitTest(position.X, position.Y); + } + + /// + /// Initializes the values for column widths in the table. + /// + private void InitializeColumnWidths() + { + if (myGridTable == null) + return; + + GridColumnStylesCollection columns = myGridTable.GridColumnStyles; + int numCols = columns.Count; + + // Resize the columns to a approximation of a best fit. + // We find the best fit width of NumRowsForAutoResize rows + // and use it for each column. + int preferredColumnWidth = this.myGridTable.IsDefault ? this.PreferredColumnWidth : this.myGridTable.PreferredColumnWidth; + // if we set the PreferredColumnWidth to something else than AutoColumnSize + // then use that value + // + for (int col = 0; col < numCols; col++) + { + // if the column width is not -1, then this column was initialized already + if (columns[col]._width != -1) + continue; + + columns[col]._width = preferredColumnWidth; } - - /// - /// Invalidates a rectangle normalized to the caption's - /// visual bounds. - /// - internal void InvalidateCaptionRect(Rectangle r) { - if (layout.CaptionVisible) { - Invalidate(r); - } + } + + /// + /// Invalidates the scrollable area of the DataGrid. + /// + internal void InvalidateInside() + { + Invalidate(layout.Inside); + } + + /// + /// Invalidates the caption area of the DataGrid. + /// + internal void InvalidateCaption() + { + if (layout.CaptionVisible) + Invalidate(layout.Caption); + } + + /// + /// Invalidates a rectangle normalized to the caption's + /// visual bounds. + /// + internal void InvalidateCaptionRect(Rectangle r) + { + if (layout.CaptionVisible) + { + Invalidate(r); } - - /// - /// Invalidates the display region of a given DataGridColumn. - /// - internal void InvalidateColumn(int column) { - GridColumnStylesCollection gridColumns = this.myGridTable.GridColumnStyles; - if (column < 0 || gridColumns == null || gridColumns.Count <= column) - return; - - Debug.Assert(gridColumns[column].PropertyDescriptor != null, "how can we invalidate a column that is invisible?"); - // bail if the column is not visible. - if (column < firstVisibleCol || column > firstVisibleCol + numVisibleCols - 1) - return; - - Rectangle columnArea = new Rectangle(); - columnArea.Height = layout.Data.Height; - columnArea.Width = gridColumns[column].Width; - columnArea.Y = layout.Data.Y; - - int x = layout.Data.X - negOffset; - int gridColumnsCount = gridColumns.Count; - for (int i = firstVisibleCol; i < gridColumnsCount; ++i) { - if (i == column) - break; - x += gridColumns[i].Width; - } - columnArea.X = x; - columnArea.X = MirrorRectangle(columnArea, layout.Data, isRightToLeft()); - Invalidate(columnArea); + } + + /// + /// Invalidates the display region of a given DataGridColumn. + /// + internal void InvalidateColumn(int column) + { + GridColumnStylesCollection gridColumns = this.myGridTable.GridColumnStyles; + if (column < 0 || gridColumns == null || gridColumns.Count <= column) + return; + + Debug.Assert(gridColumns[column].PropertyDescriptor != null, "how can we invalidate a column that is invisible?"); + // bail if the column is not visible. + if (column < firstVisibleCol || column > firstVisibleCol + numVisibleCols - 1) + return; + + Rectangle columnArea = new Rectangle(); + columnArea.Height = layout.Data.Height; + columnArea.Width = gridColumns[column].Width; + columnArea.Y = layout.Data.Y; + + int x = layout.Data.X - negOffset; + int gridColumnsCount = gridColumns.Count; + for (int i = firstVisibleCol; i < gridColumnsCount; ++i) + { + if (i == column) + break; + x += gridColumns[i].Width; } - - /// - /// Invalidates the parent rows area of the DataGrid - /// - internal void InvalidateParentRows() { - if (layout.ParentRowsVisible) - Invalidate(layout.ParentRows); + columnArea.X = x; + columnArea.X = MirrorRectangle(columnArea, layout.Data, isRightToLeft()); + Invalidate(columnArea); + } + + /// + /// Invalidates the parent rows area of the DataGrid + /// + internal void InvalidateParentRows() + { + if (layout.ParentRowsVisible) + Invalidate(layout.ParentRows); + } + + /// + /// Invalidates a rectangle normalized to the parent + /// rows area's visual bounds. + /// + internal void InvalidateParentRowsRect(Rectangle r) + { + Rectangle parentRowsRect = layout.ParentRows; + Invalidate(r); + if (!parentRowsRect.IsEmpty) + { + //Invalidate(new Rectangle(parentRowsRect.X + r.X, parentRowsRect.Y + r.Y, + // r.Width, r.Height)); } - - /// - /// Invalidates a rectangle normalized to the parent - /// rows area's visual bounds. - /// - internal void InvalidateParentRowsRect(Rectangle r) { - Rectangle parentRowsRect = layout.ParentRows; - Invalidate(r); - if (!parentRowsRect.IsEmpty) { - //Invalidate(new Rectangle(parentRowsRect.X + r.X, parentRowsRect.Y + r.Y, - // r.Width, r.Height)); - } + } + + /// + /// Invalidate the painting region for the row specified. + /// + internal void InvalidateRow(int rowNumber) + { + Rectangle rowRect = GetRowRect(rowNumber); + if (!rowRect.IsEmpty) + { + Debug.WriteLineIf(CompModSwitches.DataGridPainting.TraceVerbose, "DataGridPainting: Invalidating row " + rowNumber.ToString(CultureInfo.InvariantCulture)); + Invalidate(rowRect); } - - /// - /// Invalidate the painting region for the row specified. - /// - internal void InvalidateRow(int rowNumber) { - Rectangle rowRect = GetRowRect(rowNumber); - if (!rowRect.IsEmpty) { - Debug.WriteLineIf(CompModSwitches.DataGridPainting.TraceVerbose, "DataGridPainting: Invalidating row " + rowNumber.ToString(CultureInfo.InvariantCulture)); - Invalidate(rowRect); - } + } + + private void InvalidateRowHeader(int rowNumber) + { + if (rowNumber >= firstVisibleRow && rowNumber < firstVisibleRow + numVisibleRows) + { + if (!layout.RowHeadersVisible) + return; + + Rectangle invalid = new Rectangle(); + invalid.Y = GetRowTop(rowNumber); + invalid.X = layout.RowHeaders.X; + invalid.Width = layout.RowHeaders.Width; + invalid.Height = this.DataGridRows[rowNumber].Height; + Invalidate(invalid); } - - private void InvalidateRowHeader(int rowNumber) { - if (rowNumber >= firstVisibleRow && rowNumber < firstVisibleRow + numVisibleRows) { - if (!layout.RowHeadersVisible) - return; - - Rectangle invalid = new Rectangle(); - invalid.Y = GetRowTop(rowNumber); - invalid.X = layout.RowHeaders.X; - invalid.Width = layout.RowHeaders.Width; - invalid.Height = this.DataGridRows[rowNumber].Height; - Invalidate(invalid); - } + } + + // NOTE: + // because of Rtl, we assume that the only place that calls InvalidateRowRect is + // the DataGridRelationshipRow + internal void InvalidateRowRect(int rowNumber, Rectangle r) + { + Rectangle rowRect = GetRowRect(rowNumber); + if (!rowRect.IsEmpty) + { + Debug.WriteLineIf(CompModSwitches.DataGridPainting.TraceVerbose, "DataGridPainting: Invalidating a rect in row " + rowNumber.ToString(CultureInfo.InvariantCulture)); + Rectangle inner = new Rectangle(rowRect.X + r.X, rowRect.Y + r.Y, r.Width, r.Height); + if (vertScrollBar.Visible && isRightToLeft()) + inner.X -= vertScrollBar.Width; + Invalidate(inner); } - - // NOTE: - // because of Rtl, we assume that the only place that calls InvalidateRowRect is - // the DataGridRelationshipRow - internal void InvalidateRowRect(int rowNumber, Rectangle r) { - Rectangle rowRect = GetRowRect(rowNumber); - if (!rowRect.IsEmpty) { - Debug.WriteLineIf(CompModSwitches.DataGridPainting.TraceVerbose, "DataGridPainting: Invalidating a rect in row " + rowNumber.ToString(CultureInfo.InvariantCulture)); - Rectangle inner = new Rectangle(rowRect.X + r.X, rowRect.Y + r.Y, r.Width, r.Height); - if (vertScrollBar.Visible && isRightToLeft()) - inner.X -= vertScrollBar.Width; - Invalidate(inner); - } - } - - /// - /// Gets a value that indicates whether a specified row's node is expanded or collapsed. - /// - public bool IsExpanded(int rowNumber) { - if (rowNumber < 0 || rowNumber > DataGridRowsLength) - throw new ArgumentOutOfRangeException(nameof(rowNumber)); - DataGridRow[] localGridRows = DataGridRows; - - // + } + /// + /// Gets a value that indicates whether a specified row's node is expanded or collapsed. + /// + public bool IsExpanded(int rowNumber) + { + if (rowNumber < 0 || rowNumber > DataGridRowsLength) + throw new ArgumentOutOfRangeException(nameof(rowNumber)); + DataGridRow[] localGridRows = DataGridRows; - DataGridRow row = localGridRows[rowNumber]; - if (row is DataGridRelationshipRow) { - DataGridRelationshipRow relRow = (DataGridRelationshipRow)row; - return relRow.Expanded; - } - else - return false; + // + + + DataGridRow row = localGridRows[rowNumber]; + if (row is DataGridRelationshipRow) + { + DataGridRelationshipRow relRow = (DataGridRelationshipRow)row; + return relRow.Expanded; } - - /// - /// - /// Gets a value indicating whether a - /// specified row is selected. - /// - /// - public bool IsSelected(int row) { - // - DataGridRow[] localGridRows = DataGridRows; - return localGridRows[row].Selected; + else + return false; + } + + /// + /// + /// Gets a value indicating whether a + /// specified row is selected. + /// + /// + public bool IsSelected(int row) + { + // + DataGridRow[] localGridRows = DataGridRows; + return localGridRows[row].Selected; + } + + internal static bool IsTransparentColor(Color color) + { + return color.A < 255; + } + + /// + /// Determines if Scrollbars should be visible, + /// updates their bounds and the bounds of all + /// other regions in the DataGrid's Layout. + /// + private void LayoutScrollBars() + { + // if we set the dataSource to null, then take away the scrollbars. + if (listManager == null || myGridTable == null) + { + horizScrollBar.Visible = false; + vertScrollBar.Visible = false; + return; } - - internal static bool IsTransparentColor(Color color) { - return color.A < 255; + + // Scrollbars are a tricky issue. + // We need to see if we can cram our columns and rows + // in without scrollbars and if they don't fit, we make + // scrollbars visible and then fixup our regions for the + // data and headers. + bool needHorizScrollbar = false; + bool needVertScrollbar = false; + bool recountRows = false; + bool alignToRight = isRightToLeft(); + + int nGridCols = myGridTable.GridColumnStyles.Count; + + // if we call LayoutScrollBars before CreateDataGridRows + // then the columns will have their default width ( 100 ) + // CreateDataGridRows will possibly change the columns' width + // + // and anyway, ComputeVisibleRows will call the DataGridRows accessor + // + DataGridRow[] gridRows = this.DataGridRows; + + // at this stage, the data grid columns may have their width set to -1 ( ie, their width is uninitialized ) + // make sure that the totalWidth is at least 0 + int totalWidth = Math.Max(0, GetColumnWidthSum()); + + if (totalWidth > layout.Data.Width && !needHorizScrollbar) + { + int horizHeight = horizScrollBar.Height; + layout.Data.Height -= horizHeight; + if (layout.RowHeadersVisible) + layout.RowHeaders.Height -= horizHeight; + needHorizScrollbar = true; } - - /// - /// Determines if Scrollbars should be visible, - /// updates their bounds and the bounds of all - /// other regions in the DataGrid's Layout. - /// - private void LayoutScrollBars() { - // if we set the dataSource to null, then take away the scrollbars. - if (listManager == null || myGridTable == null) { - horizScrollBar.Visible = false; - vertScrollBar.Visible = false; - return; - } - // Scrollbars are a tricky issue. - // We need to see if we can cram our columns and rows - // in without scrollbars and if they don't fit, we make - // scrollbars visible and then fixup our regions for the - // data and headers. - bool needHorizScrollbar = false; - bool needVertScrollbar = false; - bool recountRows = false; - bool alignToRight = isRightToLeft(); - - int nGridCols = myGridTable.GridColumnStyles.Count; - - // if we call LayoutScrollBars before CreateDataGridRows - // then the columns will have their default width ( 100 ) - // CreateDataGridRows will possibly change the columns' width - // - // and anyway, ComputeVisibleRows will call the DataGridRows accessor - // - DataGridRow[] gridRows = this.DataGridRows; + int oldFirstVisibleRow = firstVisibleRow; - // at this stage, the data grid columns may have their width set to -1 ( ie, their width is uninitialized ) - // make sure that the totalWidth is at least 0 - int totalWidth = Math.Max(0, GetColumnWidthSum()); - - if (totalWidth > layout.Data.Width && !needHorizScrollbar) { - int horizHeight = horizScrollBar.Height; - layout.Data.Height -= horizHeight; - if (layout.RowHeadersVisible) - layout.RowHeaders.Height -= horizHeight; - needHorizScrollbar = true; + ComputeVisibleRows(); + if (numTotallyVisibleRows != DataGridRowsLength && !needVertScrollbar) + { + int vertWidth = vertScrollBar.Width; + layout.Data.Width -= vertWidth; + if (layout.ColumnHeadersVisible) + { + if (alignToRight) + layout.ColumnHeaders.X += vertWidth; + + layout.ColumnHeaders.Width -= vertWidth; } - - int oldFirstVisibleRow = firstVisibleRow; - + needVertScrollbar = true; + } + + this.firstVisibleCol = ComputeFirstVisibleColumn(); + // we compute the number of visible columns only after we set up the vertical scroll bar. + ComputeVisibleColumns(); + + if (needVertScrollbar && totalWidth > layout.Data.Width && !needHorizScrollbar) + { + firstVisibleRow = oldFirstVisibleRow; + int horizHeight = horizScrollBar.Height; + layout.Data.Height -= horizHeight; + if (layout.RowHeadersVisible) + layout.RowHeaders.Height -= horizHeight; + needHorizScrollbar = true; + recountRows = true; + } + + if (recountRows) + { ComputeVisibleRows(); - if (numTotallyVisibleRows != DataGridRowsLength && !needVertScrollbar) { + if (numTotallyVisibleRows != DataGridRowsLength && !needVertScrollbar) + { int vertWidth = vertScrollBar.Width; layout.Data.Width -= vertWidth; if (layout.ColumnHeadersVisible) { if (alignToRight) layout.ColumnHeaders.X += vertWidth; - + layout.ColumnHeaders.Width -= vertWidth; } needVertScrollbar = true; } - - this.firstVisibleCol = ComputeFirstVisibleColumn(); - // we compute the number of visible columns only after we set up the vertical scroll bar. - ComputeVisibleColumns(); - - if (needVertScrollbar && totalWidth > layout.Data.Width && !needHorizScrollbar) { - firstVisibleRow = oldFirstVisibleRow; - int horizHeight = horizScrollBar.Height; - layout.Data.Height -= horizHeight; - if (layout.RowHeadersVisible) - layout.RowHeaders.Height -= horizHeight; - needHorizScrollbar = true; - recountRows = true; - } - - if (recountRows) { - ComputeVisibleRows(); - if (numTotallyVisibleRows != DataGridRowsLength && !needVertScrollbar) { - int vertWidth = vertScrollBar.Width; - layout.Data.Width -= vertWidth; - if (layout.ColumnHeadersVisible) - { - if (alignToRight) - layout.ColumnHeaders.X += vertWidth; - - layout.ColumnHeaders.Width -= vertWidth; - } - needVertScrollbar = true; - } - } - - layout.ResizeBoxRect = new Rectangle(); - if (needVertScrollbar && needHorizScrollbar) { - Rectangle data = layout.Data; - layout.ResizeBoxRect = new Rectangle(alignToRight ? data.X : data.Right, - data.Bottom, - vertScrollBar.Width, - horizScrollBar.Height); + } + + layout.ResizeBoxRect = new Rectangle(); + if (needVertScrollbar && needHorizScrollbar) + { + Rectangle data = layout.Data; + layout.ResizeBoxRect = new Rectangle(alignToRight ? data.X : data.Right, + data.Bottom, + vertScrollBar.Width, + horizScrollBar.Height); + } + + + if (needHorizScrollbar && nGridCols > 0) + { + //Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "DataGridScrolling: foo"); + + int widthNotVisible = totalWidth - layout.Data.Width; + + horizScrollBar.Minimum = 0; + horizScrollBar.Maximum = totalWidth; + horizScrollBar.SmallChange = 1; + horizScrollBar.LargeChange = Math.Max(totalWidth - widthNotVisible, 0); + horizScrollBar.Enabled = this.Enabled; + horizScrollBar.RightToLeft = RightToLeft; + horizScrollBar.Bounds = new Rectangle(alignToRight ? layout.Inside.X + layout.ResizeBoxRect.Width : layout.Inside.X, + layout.Data.Bottom, + layout.Inside.Width - layout.ResizeBoxRect.Width, + horizScrollBar.Height); + horizScrollBar.Visible = true; + } + else + { + HorizontalOffset = 0; + horizScrollBar.Visible = false; + } + + if (needVertScrollbar) + { + int vertScrollBarTop = layout.Data.Y; + if (layout.ColumnHeadersVisible) + vertScrollBarTop = layout.ColumnHeaders.Y; + // if numTotallyVisibleRows == 0 ( the height of the row is bigger than the height of + // the grid ) then scroll in increments of 1. + vertScrollBar.LargeChange = numTotallyVisibleRows != 0 ? numTotallyVisibleRows : 1; + vertScrollBar.Bounds = new Rectangle(alignToRight ? layout.Data.X : layout.Data.Right, + vertScrollBarTop, + vertScrollBar.Width, + layout.Data.Height + layout.ColumnHeaders.Height); + vertScrollBar.Enabled = this.Enabled; + vertScrollBar.Visible = true; + if (alignToRight) + layout.Data.X += vertScrollBar.Width; + } + else + { + vertScrollBar.Visible = false; + } + } + + /// + /// Navigates back to the table previously displayed in the grid. + /// + public void NavigateBack() + { + if (!CommitEdit() || parentRows.IsEmpty()) + return; + // when navigating back, if the grid is inAddNewRow state, cancel the currentEdit. + // we do not need to recreate the rows cause we are navigating back. + // the grid will catch any exception that happens. + if (gridState[GRIDSTATE_inAddNewRow]) + { + gridState[GRIDSTATE_inAddNewRow] = false; + try + { + listManager.CancelCurrentEdit(); } - - - if (needHorizScrollbar && nGridCols > 0) { - //Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "DataGridScrolling: foo"); - - int widthNotVisible = totalWidth - layout.Data.Width; - - horizScrollBar.Minimum = 0; - horizScrollBar.Maximum = totalWidth; - horizScrollBar.SmallChange = 1; - horizScrollBar.LargeChange = Math.Max(totalWidth - widthNotVisible, 0); - horizScrollBar.Enabled = this.Enabled; - horizScrollBar.RightToLeft = RightToLeft; - horizScrollBar.Bounds = new Rectangle(alignToRight ? layout.Inside.X + layout.ResizeBoxRect.Width : layout.Inside.X, - layout.Data.Bottom, - layout.Inside.Width - layout.ResizeBoxRect.Width, - horizScrollBar.Height); - horizScrollBar.Visible = true; - } - else { - HorizontalOffset = 0; - horizScrollBar.Visible = false; + catch + { } - - if (needVertScrollbar) { - int vertScrollBarTop = layout.Data.Y; - if (layout.ColumnHeadersVisible) - vertScrollBarTop = layout.ColumnHeaders.Y; - // if numTotallyVisibleRows == 0 ( the height of the row is bigger than the height of - // the grid ) then scroll in increments of 1. - vertScrollBar.LargeChange = numTotallyVisibleRows != 0 ? numTotallyVisibleRows : 1; - vertScrollBar.Bounds = new Rectangle(alignToRight ? layout.Data.X : layout.Data.Right, - vertScrollBarTop, - vertScrollBar.Width, - layout.Data.Height + layout.ColumnHeaders.Height); - vertScrollBar.Enabled = this.Enabled; - vertScrollBar.Visible = true; - if (alignToRight) - layout.Data.X += vertScrollBar.Width; + } + else + { + UpdateListManager(); + } + + + DataGridState newState = parentRows.PopTop(); + + ResetMouseState(); + + newState.PullState(this, false); // we do not want to create columns when navigating back + + // we need to have originalState != null when we process + // Set_ListManager in the NavigateBack/NavigateTo methods. + // otherwise the DataSource_MetaDataChanged event will not get registered + // properly + if (parentRows.GetTopParent() == null) + originalState = null; + + DataGridRow[] localGridRows = this.DataGridRows; + // what if the user changed the ReadOnly property + // on the grid while the user was navigating to the child rows? + // + // what if the policy does not allow for allowAdd? + // + if ((this.ReadOnly || !policy.AllowAdd) == (localGridRows[DataGridRowsLength - 1] is DataGridAddNewRow)) + { + int newDataGridRowsLength = (ReadOnly || !policy.AllowAdd) ? DataGridRowsLength - 1 : DataGridRowsLength + 1; + DataGridRow[] newDataGridRows = new DataGridRow[newDataGridRowsLength]; + for (int i = 0; i < Math.Min(newDataGridRowsLength, DataGridRowsLength); i++) + { + newDataGridRows[i] = DataGridRows[i]; } - else { - vertScrollBar.Visible = false; + if (!this.ReadOnly && policy.AllowAdd) + newDataGridRows[newDataGridRowsLength - 1] = new DataGridAddNewRow(this, this.myGridTable, newDataGridRowsLength - 1); + SetDataGridRows(newDataGridRows, newDataGridRowsLength); + } + + // when we navigate back from a child table, + // it may be the case that in between the user added a tableStyle that is different + // from the one that is currently in the grid + // in that case, we need to reset the dataGridTableStyle in the rows + localGridRows = this.DataGridRows; + if (localGridRows != null && localGridRows.Length != 0) + { + DataGridTableStyle dgTable = localGridRows[0].DataGridTableStyle; + if (dgTable != this.myGridTable) + { + for (int i = 0; i < localGridRows.Length; i++) + localGridRows[i].DataGridTableStyle = this.myGridTable; } } - - /// - /// Navigates back to the table previously displayed in the grid. - /// - public void NavigateBack() { - if (!CommitEdit() || parentRows.IsEmpty()) - return; - // when navigating back, if the grid is inAddNewRow state, cancel the currentEdit. - // we do not need to recreate the rows cause we are navigating back. - // the grid will catch any exception that happens. - if (gridState[GRIDSTATE_inAddNewRow]) { - gridState[GRIDSTATE_inAddNewRow] = false; - try { - listManager.CancelCurrentEdit(); - } catch { - } - } else { - UpdateListManager(); + + // if we have the default table, when we navigate back + // we also have the default gridColumns, w/ width = -1 + // we need to set the width on the new gridColumns + // + if (this.myGridTable.GridColumnStyles.Count > 0 && this.myGridTable.GridColumnStyles[0].Width == -1) + { +#if DEBUG + GridColumnStylesCollection cols = this.myGridTable.GridColumnStyles; + for (int i = 0; i < cols.Count; i++) + { + Debug.Assert(cols[i].Width == -1, "Sanity check"); } - - - DataGridState newState = parentRows.PopTop(); - - ResetMouseState(); - - newState.PullState(this, false); // we do not want to create columns when navigating back - - // we need to have originalState != null when we process - // Set_ListManager in the NavigateBack/NavigateTo methods. - // otherwise the DataSource_MetaDataChanged event will not get registered - // properly - if (parentRows.GetTopParent() == null) - originalState = null; - - DataGridRow[] localGridRows = this.DataGridRows; - // what if the user changed the ReadOnly property - // on the grid while the user was navigating to the child rows? - // - // what if the policy does not allow for allowAdd? + Debug.Assert(this.myGridTable.IsDefault, "when we navigate to the parent rows and the columns have widths -1 we are using the default table"); +#endif // DEBUG + InitializeColumnWidths(); + } + + // reset the currentRow to the old position in the listmanager: + currentRow = this.ListManager.Position == -1 ? 0 : this.ListManager.Position; + + // if the AllowNavigation changed while the user was navigating the + // child tables, so that the new navigation mode does not allow childNavigation anymore + // then reset the rows + if (!AllowNavigation) + { + RecreateDataGridRows(); + } + + caption.BackButtonActive = (parentRows.GetTopParent() != null) && AllowNavigation; + caption.BackButtonVisible = caption.BackButtonActive; + caption.DownButtonActive = (parentRows.GetTopParent() != null); + + PerformLayout(); + Invalidate(); + // reposition the scroll bar + if (vertScrollBar.Visible) + vertScrollBar.Value = firstVisibleRow; + if (horizScrollBar.Visible) + horizScrollBar.Value = HorizontalOffset + negOffset; + Edit(); + OnNavigate(new NavigateEventArgs(false)); + } + + /// + /// + /// Navigates to the table specified by row and relation + /// name. + /// + /// + public void NavigateTo(int rowNumber, string relationName) + { + // do not navigate if AllowNavigation is set to false + if (!AllowNavigation) + return; + DataGridRow[] localGridRows = DataGridRows; + if (rowNumber < 0 || rowNumber > DataGridRowsLength - (policy.AllowAdd ? 2 : 1)) + { + throw new ArgumentOutOfRangeException(nameof(rowNumber)); + } + EnsureBound(); + + DataGridRow source = localGridRows[rowNumber]; + + NavigateTo(relationName, source, false); + } + + internal void NavigateTo(string relationName, DataGridRow source, bool fromRow) + { + // do not navigate if AllowNavigation is set to false + if (!AllowNavigation) + return; + // Commit the edit if possible + if (!CommitEdit()) + return; + + DataGridState childState; + try + { + childState = CreateChildState(relationName, source); + } + catch + { + // if we get an error when creating the RelatedCurrencyManager + // then navigateBack and ignore the exception. // - if ((this.ReadOnly || !policy.AllowAdd) == (localGridRows[DataGridRowsLength -1] is DataGridAddNewRow)) { - int newDataGridRowsLength = (ReadOnly || !policy.AllowAdd) ? DataGridRowsLength - 1 : DataGridRowsLength + 1; - DataGridRow[] newDataGridRows = new DataGridRow[newDataGridRowsLength]; - for (int i = 0; i < Math.Min(newDataGridRowsLength, DataGridRowsLength); i++) { - newDataGridRows[i] = DataGridRows[i]; - } - if(!this.ReadOnly && policy.AllowAdd) - newDataGridRows[newDataGridRowsLength - 1] = new DataGridAddNewRow(this, this.myGridTable, newDataGridRowsLength-1); - SetDataGridRows(newDataGridRows, newDataGridRowsLength); - } - - // when we navigate back from a child table, - // it may be the case that in between the user added a tableStyle that is different - // from the one that is currently in the grid - // in that case, we need to reset the dataGridTableStyle in the rows - localGridRows = this.DataGridRows; - if (localGridRows != null && localGridRows.Length != 0) { - DataGridTableStyle dgTable = localGridRows[0].DataGridTableStyle; - if (dgTable != this.myGridTable) { - for (int i = 0; i < localGridRows.Length; i ++) - localGridRows[i].DataGridTableStyle = this.myGridTable; - } - } - - // if we have the default table, when we navigate back - // we also have the default gridColumns, w/ width = -1 - // we need to set the width on the new gridColumns + NavigateBack(); + return; + } + + // call EndCurrentEdit before navigating. + // if we get an exception, we do not navigate. + // + try + { + this.listManager.EndCurrentEdit(); + } + catch + { + return; + } + + // Preserve our current state + // we need to do this after the EndCurrentEdit, otherwise the + // DataGridState will get the listChanged event from the EndCurrentEdit + DataGridState dgs = new DataGridState(this); + dgs.LinkingRow = source; + + // we need to update the Position in the ListManager + // ( the RelatedListManager uses only the position in the parentManager + // to create the childRows + // + // before the code was calling CurrentCell = this and such + // we should only call EndCurrentEdit ( which the code was doing anyway ) + // and then set the position in the listManager to the new row. + // + if (source.RowNumber != CurrentRow) + this.listManager.Position = source.RowNumber; + + // We save our state if the parent rows stack is empty. + if (parentRows.GetTopParent() == null) + { + originalState = dgs; + } + + parentRows.AddParent(dgs); + + NavigateTo(childState); + + OnNavigate(new NavigateEventArgs(true)); + if (fromRow) + { + // OnLinkClick(EventArgs.Empty); + } + } + + private void NavigateTo(DataGridState childState) + { + // we are navigating... better stop editing. + EndEdit(); + + // also, we are no longer in editOrNavigate mode either + gridState[GRIDSTATE_isNavigating] = false; + + // reset hot tracking + ResetMouseState(); + + // Retrieve the child state + childState.PullState(this, true); // true for creating columns when we navigate to child rows + + if (this.listManager.Position != this.currentRow) + { + this.currentRow = listManager.Position == -1 ? 0 : listManager.Position; + } + + if (parentRows.GetTopParent() != null) + { + caption.BackButtonActive = AllowNavigation; + caption.BackButtonVisible = caption.BackButtonActive; + caption.DownButtonActive = true; + } + + HorizontalOffset = 0; + PerformLayout(); + Invalidate(); + } + + + /// + /// Given a coordinate in the control this method returns + /// the equivalent point for a row. + /// + private Point NormalizeToRow(int x, int y, int row) + { + Debug.Assert(row >= firstVisibleRow && row < firstVisibleRow + numVisibleRows, + "Row " + row.ToString(CultureInfo.InvariantCulture) + "is not visible! firstVisibleRow = " + + firstVisibleRow.ToString(CultureInfo.InvariantCulture) + ", numVisibleRows = " + + numVisibleRows.ToString(CultureInfo.InvariantCulture)); + Point origin = new Point(0, layout.Data.Y); + + DataGridRow[] localGridRows = DataGridRows; + for (int r = firstVisibleRow; r < row; ++r) + { + origin.Y += localGridRows[r].Height; + } + // when hittesting for the PlusMinus, the code in the DataGridRelationshipRow + // will use real X coordinate ( the one from layout.RowHeaders ) to paint the glyph + // + return new Point(x, y - origin.Y); + } + + internal void OnColumnCollectionChanged(object sender, CollectionChangeEventArgs e) + { + DataGridTableStyle table = (DataGridTableStyle)sender; + if (table.Equals(this.myGridTable)) + { + // if we changed the column collection, then we need to set the property + // descriptors in the column collection. + // unless the user set the propertyDescriptor in the columnCollection // - if (this.myGridTable.GridColumnStyles.Count > 0 && this.myGridTable.GridColumnStyles[0].Width == -1) { - #if DEBUG - GridColumnStylesCollection cols = this.myGridTable.GridColumnStyles; - for (int i = 0; i < cols.Count; i++) { - Debug.Assert(cols[i].Width == -1, "Sanity check"); - } - Debug.Assert(this.myGridTable.IsDefault, "when we navigate to the parent rows and the columns have widths -1 we are using the default table"); - #endif // DEBUG - InitializeColumnWidths(); - } - - // reset the currentRow to the old position in the listmanager: - currentRow = this.ListManager.Position == -1 ? 0 : this.ListManager.Position; - - // if the AllowNavigation changed while the user was navigating the - // child tables, so that the new navigation mode does not allow childNavigation anymore - // then reset the rows - if (!AllowNavigation) { - RecreateDataGridRows(); + if (!this.myGridTable.IsDefault) + { + // if the element in the collectionChangeEventArgs is not null + // and the action is refresh, then it means that the user + // set the propDesc. we do not want to override this. + if (e.Action != CollectionChangeAction.Refresh || e.Element == null) + PairTableStylesAndGridColumns(this.listManager, this.myGridTable, false); } - - caption.BackButtonActive = (parentRows.GetTopParent() != null) && AllowNavigation; - caption.BackButtonVisible = caption.BackButtonActive; - caption.DownButtonActive = (parentRows.GetTopParent() != null); - - PerformLayout(); Invalidate(); - // reposition the scroll bar - if (vertScrollBar.Visible) - vertScrollBar.Value = firstVisibleRow; - if (horizScrollBar.Visible) - horizScrollBar.Value = HorizontalOffset + negOffset; - Edit(); - OnNavigate(new NavigateEventArgs(false)); + PerformLayout(); } - - /// - /// - /// Navigates to the table specified by row and relation - /// name. - /// - /// - public void NavigateTo(int rowNumber, string relationName) { - // do not navigate if AllowNavigation is set to false - if (!AllowNavigation) - return; - DataGridRow[] localGridRows = DataGridRows; - if (rowNumber < 0 || rowNumber > DataGridRowsLength - (policy.AllowAdd ? 2:1)) { - throw new ArgumentOutOfRangeException(nameof(rowNumber)); - } - EnsureBound(); - - DataGridRow source = localGridRows[rowNumber]; - - NavigateTo(relationName, source, false); + } + + /// + /// Paints column headers. + /// + private void PaintColumnHeaders(Graphics g) + { + + bool alignToLeft = isRightToLeft(); + Rectangle boundingRect = layout.ColumnHeaders; + if (!alignToLeft) + boundingRect.X -= negOffset; + boundingRect.Width += negOffset; + + int columnHeaderWidth = PaintColumnHeaderText(g, boundingRect); + + if (alignToLeft) + boundingRect.X = boundingRect.Right - columnHeaderWidth; + + boundingRect.Width = columnHeaderWidth; + if (!FlatMode) + { + ControlPaint.DrawBorder3D(g, boundingRect, Border3DStyle.RaisedInner); + boundingRect.Inflate(-1, -1); + // g.SetPen(OldSystemPens.Control); + // g.OldBrush = (OldSystemBrushes.Hollow); + boundingRect.Width--; + boundingRect.Height--; + g.DrawRectangle(SystemPens.Control, boundingRect); } - - internal void NavigateTo(string relationName, DataGridRow source, bool fromRow) { - // do not navigate if AllowNavigation is set to false - if (!AllowNavigation) - return; - // Commit the edit if possible - if (!CommitEdit()) - return; - - DataGridState childState; - try { - childState = CreateChildState(relationName, source); + } + + private int PaintColumnHeaderText(Graphics g, Rectangle boundingRect) + { + int cx = 0; + Rectangle textBounds = boundingRect; + GridColumnStylesCollection gridColumns = this.myGridTable.GridColumnStyles; + bool alignRight = isRightToLeft(); + + + int nGridCols = gridColumns.Count; + // for sorting + PropertyDescriptor sortProperty = null; + sortProperty = this.ListManager.GetSortProperty(); + + // Now paint the column header text! + for (int col = firstVisibleCol; col < nGridCols; ++col) + { + if (gridColumns[col].PropertyDescriptor == null) + continue; + + if (cx > boundingRect.Width) + break; + + bool columnSorted = sortProperty != null && sortProperty.Equals(gridColumns[col].PropertyDescriptor); + TriangleDirection whichWay = TriangleDirection.Up; + if (columnSorted) + { + ListSortDirection direction = this.ListManager.GetSortDirection(); + if (direction == ListSortDirection.Descending) + whichWay = TriangleDirection.Down; } - catch { - // if we get an error when creating the RelatedCurrencyManager - // then navigateBack and ignore the exception. - // - NavigateBack(); - return; + + if (alignRight) + { + textBounds.Width = gridColumns[col].Width - + (columnSorted ? textBounds.Height : 0); + textBounds.X = boundingRect.Right - cx - textBounds.Width; } - - // call EndCurrentEdit before navigating. - // if we get an exception, we do not navigate. - // - try { - this.listManager.EndCurrentEdit(); + else + { + textBounds.X = boundingRect.X + cx; + textBounds.Width = gridColumns[col].Width - + (columnSorted ? textBounds.Height : 0); } - catch { - return; + + // at the moment we paint some pixels twice. + // we should not call FilLRectangle, once the real GDI+ is there, we will have no need to do that + + // if the user set the HeaderBackBrush property on the + // dataGrid, then use that property + Brush headerBrush; + if (this.myGridTable.IsDefault) + headerBrush = HeaderBackBrush; + else + headerBrush = this.myGridTable.HeaderBackBrush; + + g.FillRectangle(headerBrush, textBounds); + // granted, the code would be a lot cleaner if we were using a "new Rectangle" + // but like this will be faster + if (alignRight) + { + textBounds.X -= 2; + textBounds.Y += 2; } - - // Preserve our current state - // we need to do this after the EndCurrentEdit, otherwise the - // DataGridState will get the listChanged event from the EndCurrentEdit - DataGridState dgs = new DataGridState(this); - dgs.LinkingRow = source; - - // we need to update the Position in the ListManager - // ( the RelatedListManager uses only the position in the parentManager - // to create the childRows - // - // before the code was calling CurrentCell = this and such - // we should only call EndCurrentEdit ( which the code was doing anyway ) - // and then set the position in the listManager to the new row. - // - if (source.RowNumber != CurrentRow) - this.listManager.Position = source.RowNumber; - - // We save our state if the parent rows stack is empty. - if (parentRows.GetTopParent() == null) { - originalState = dgs; + else + { + textBounds.X += 2; + textBounds.Y += 2; } - - parentRows.AddParent(dgs); - - NavigateTo(childState); - - OnNavigate(new NavigateEventArgs(true)); - if (fromRow) { - // OnLinkClick(EventArgs.Empty); + + StringFormat format = new StringFormat(); + + // the columnHeaderText alignment should be the same as + // the alignment in the column + // + HorizontalAlignment colAlignment = gridColumns[col].Alignment; + format.Alignment = colAlignment == HorizontalAlignment.Right ? StringAlignment.Far : + colAlignment == HorizontalAlignment.Center ? StringAlignment.Center : + StringAlignment.Near; + + // part 1, section 1: the column headers should not wrap + format.FormatFlags |= StringFormatFlags.NoWrap; + + if (alignRight) + { + format.FormatFlags |= StringFormatFlags.DirectionRightToLeft; + format.Alignment = StringAlignment.Near; + } + g.DrawString(gridColumns[col].HeaderText, + this.myGridTable.IsDefault ? this.HeaderFont : this.myGridTable.HeaderFont, + this.myGridTable.IsDefault ? this.HeaderForeBrush : this.myGridTable.HeaderForeBrush, + textBounds, + format); + format.Dispose(); + + if (alignRight) + { + textBounds.X += 2; + textBounds.Y -= 2; } - } - - private void NavigateTo(DataGridState childState) { - // we are navigating... better stop editing. - EndEdit(); - - // also, we are no longer in editOrNavigate mode either - gridState[GRIDSTATE_isNavigating] = false; - - // reset hot tracking - ResetMouseState(); - - // Retrieve the child state - childState.PullState(this, true); // true for creating columns when we navigate to child rows - - if (this.listManager.Position != this.currentRow) { - this.currentRow = listManager.Position == -1 ? 0 : listManager.Position; + else + { + textBounds.X -= 2; + textBounds.Y -= 2; } - - if (parentRows.GetTopParent() != null) { - caption.BackButtonActive = AllowNavigation; - caption.BackButtonVisible = caption.BackButtonActive; - caption.DownButtonActive = true; + + if (columnSorted) + { + // + + Rectangle triBounds = new Rectangle(alignRight ? textBounds.X - textBounds.Height : textBounds.Right, + textBounds.Y, + textBounds.Height, + textBounds.Height); + + g.FillRectangle(headerBrush, triBounds); + int deflateValue = Math.Max(0, (textBounds.Height - 5) / 2); + triBounds.Inflate(-deflateValue, -deflateValue); + + Pen pen1 = new Pen(this.BackgroundBrush); + Pen pen2 = new Pen(this.myGridTable.BackBrush); + Triangle.Paint(g, triBounds, whichWay, headerBrush, pen1, pen2, pen1, true); + pen1.Dispose(); + pen2.Dispose(); } - - HorizontalOffset = 0; - PerformLayout(); - Invalidate(); - } - - - /// - /// Given a coordinate in the control this method returns - /// the equivalent point for a row. - /// - private Point NormalizeToRow(int x, int y, int row) { - Debug.Assert(row >= firstVisibleRow && row < firstVisibleRow + numVisibleRows, - "Row " + row.ToString(CultureInfo.InvariantCulture) + "is not visible! firstVisibleRow = " + - firstVisibleRow.ToString(CultureInfo.InvariantCulture) + ", numVisibleRows = " + - numVisibleRows.ToString(CultureInfo.InvariantCulture)); - Point origin = new Point(0, layout.Data.Y); - - DataGridRow[] localGridRows = DataGridRows; - for (int r = firstVisibleRow; r < row; ++r) { - origin.Y += localGridRows[r].Height; + int paintedWidth = textBounds.Width + (columnSorted ? textBounds.Height : 0); + + if (!FlatMode) + { + if (alignRight && columnSorted) + textBounds.X -= textBounds.Height; + textBounds.Width = paintedWidth; + + ControlPaint.DrawBorder3D(g, textBounds, Border3DStyle.RaisedInner); } - // when hittesting for the PlusMinus, the code in the DataGridRelationshipRow - // will use real X coordinate ( the one from layout.RowHeaders ) to paint the glyph - // - return new Point(x, y - origin.Y); + cx += paintedWidth; } - - internal void OnColumnCollectionChanged(object sender, CollectionChangeEventArgs e) { - DataGridTableStyle table = (DataGridTableStyle)sender; - if (table.Equals(this.myGridTable)) { - // if we changed the column collection, then we need to set the property - // descriptors in the column collection. - // unless the user set the propertyDescriptor in the columnCollection - // - if (!this.myGridTable.IsDefault) { - // if the element in the collectionChangeEventArgs is not null - // and the action is refresh, then it means that the user - // set the propDesc. we do not want to override this. - if (e.Action != CollectionChangeAction.Refresh || e.Element == null) - PairTableStylesAndGridColumns(this.listManager, this.myGridTable, false); - } - Invalidate(); - PerformLayout(); - } + + // paint the possible exposed portion to the right ( or left, as the case may be) + if (cx < boundingRect.Width) + { + textBounds = boundingRect; + + if (!alignRight) + textBounds.X += cx; + + textBounds.Width -= cx; + g.FillRectangle(backgroundBrush, textBounds); } - - /// - /// Paints column headers. - /// - private void PaintColumnHeaders(Graphics g) { - - bool alignToLeft = isRightToLeft(); - Rectangle boundingRect = layout.ColumnHeaders; - if (!alignToLeft) - boundingRect.X -= negOffset; - boundingRect.Width += negOffset; - - int columnHeaderWidth = PaintColumnHeaderText(g, boundingRect); - - if (alignToLeft) - boundingRect.X = boundingRect.Right - columnHeaderWidth; - - boundingRect.Width = columnHeaderWidth; - if (!FlatMode) { - ControlPaint.DrawBorder3D(g, boundingRect, Border3DStyle.RaisedInner); - boundingRect.Inflate(-1, -1); - // g.SetPen(OldSystemPens.Control); - // g.OldBrush = (OldSystemBrushes.Hollow); - boundingRect.Width --; - boundingRect.Height--; - g.DrawRectangle(SystemPens.Control, boundingRect); - } + return cx; + } + + + /// + /// Paints a border around the bouding rectangle given + /// + private void PaintBorder(Graphics g, Rectangle bounds) + { + if (BorderStyle == BorderStyle.None) + return; + if (BorderStyle == BorderStyle.Fixed3D) + { + Border3DStyle style = Border3DStyle.Sunken; + ControlPaint.DrawBorder3D(g, bounds, style); } - - private int PaintColumnHeaderText(Graphics g, Rectangle boundingRect) { - int cx = 0; - Rectangle textBounds = boundingRect; - GridColumnStylesCollection gridColumns = this.myGridTable.GridColumnStyles; - bool alignRight = isRightToLeft(); - - - int nGridCols = gridColumns.Count; - // for sorting - PropertyDescriptor sortProperty = null; - sortProperty = this.ListManager.GetSortProperty(); - - // Now paint the column header text! - for (int col = firstVisibleCol; col < nGridCols; ++col) { - if (gridColumns[col].PropertyDescriptor == null) - continue; - - if (cx > boundingRect.Width) - break; - - bool columnSorted = sortProperty != null && sortProperty.Equals(gridColumns[col].PropertyDescriptor); - TriangleDirection whichWay = TriangleDirection.Up; - if (columnSorted) - { - ListSortDirection direction = this.ListManager.GetSortDirection(); - if (direction == ListSortDirection.Descending) - whichWay = TriangleDirection.Down; - } - - if (alignRight) - { - textBounds.Width = gridColumns[col].Width - - (columnSorted ? textBounds.Height : 0); - textBounds.X = boundingRect.Right - cx - textBounds.Width; - } - else - { - textBounds.X = boundingRect.X + cx; - textBounds.Width = gridColumns[col].Width - - (columnSorted ? textBounds.Height : 0); - } - - // at the moment we paint some pixels twice. - // we should not call FilLRectangle, once the real GDI+ is there, we will have no need to do that - - // if the user set the HeaderBackBrush property on the - // dataGrid, then use that property - Brush headerBrush; - if (this.myGridTable.IsDefault) - headerBrush = HeaderBackBrush; - else - headerBrush = this.myGridTable.HeaderBackBrush; - - g.FillRectangle(headerBrush, textBounds); - // granted, the code would be a lot cleaner if we were using a "new Rectangle" - // but like this will be faster - if (alignRight) - { - textBounds.X -= 2; textBounds.Y += 2; - } - else - { - textBounds.X += 2; textBounds.Y += 2; - } - - StringFormat format = new StringFormat(); - - // the columnHeaderText alignment should be the same as - // the alignment in the column - // - HorizontalAlignment colAlignment = gridColumns[col].Alignment; - format.Alignment = colAlignment == HorizontalAlignment.Right ? StringAlignment.Far : - colAlignment == HorizontalAlignment.Center ? StringAlignment.Center : - StringAlignment.Near; - - // part 1, section 1: the column headers should not wrap - format.FormatFlags |= StringFormatFlags.NoWrap; - - if (alignRight) { - format.FormatFlags |= StringFormatFlags.DirectionRightToLeft; - format.Alignment = StringAlignment.Near; - } - g.DrawString(gridColumns[col].HeaderText, - this.myGridTable.IsDefault ? this.HeaderFont : this.myGridTable.HeaderFont, - this.myGridTable.IsDefault ? this.HeaderForeBrush : this.myGridTable.HeaderForeBrush, - textBounds, - format); - format.Dispose(); - - if (alignRight) - { - textBounds.X += 2; textBounds.Y -= 2; - } - else - { - textBounds.X -= 2; textBounds.Y -= 2; - } - - if (columnSorted) { - // + else if (BorderStyle == BorderStyle.FixedSingle) + { + Brush br; - Rectangle triBounds = new Rectangle(alignRight ? textBounds.X - textBounds.Height : textBounds.Right, - textBounds.Y, - textBounds.Height, - textBounds.Height); - - g.FillRectangle(headerBrush, triBounds); - int deflateValue = Math.Max(0,(textBounds.Height - 5) / 2); - triBounds.Inflate(-deflateValue, -deflateValue); - - Pen pen1 = new Pen(this.BackgroundBrush); - Pen pen2 = new Pen(this.myGridTable.BackBrush); - Triangle.Paint(g, triBounds, whichWay, headerBrush, pen1, pen2, pen1, true); - pen1.Dispose(); - pen2.Dispose(); - } - int paintedWidth = textBounds.Width + (columnSorted ? textBounds.Height : 0); - - if (!FlatMode) { - if (alignRight && columnSorted) - textBounds.X -= textBounds.Height; - textBounds.Width = paintedWidth; - - ControlPaint.DrawBorder3D(g, textBounds, Border3DStyle.RaisedInner); - } - cx += paintedWidth; - } - - // paint the possible exposed portion to the right ( or left, as the case may be) - if (cx < boundingRect.Width) { - textBounds = boundingRect; - - if (!alignRight) - textBounds.X += cx; - - textBounds.Width -= cx; - g.FillRectangle(backgroundBrush, textBounds); - } - return cx; + if (this.myGridTable.IsDefault) + br = this.HeaderForeBrush; + else + br = this.myGridTable.HeaderForeBrush; + g.FillRectangle(br, bounds.X, bounds.Y, bounds.Width + 2, 2); + g.FillRectangle(br, bounds.Right - 2, bounds.Y, 2, bounds.Height + 2); + g.FillRectangle(br, bounds.X, bounds.Bottom - 2, bounds.Width + 2, 2); + g.FillRectangle(br, bounds.X, bounds.Y, 2, bounds.Height + 2); } - - - /// - /// Paints a border around the bouding rectangle given - /// - private void PaintBorder(Graphics g, Rectangle bounds) + else { - if (BorderStyle == BorderStyle.None) - return; - if (BorderStyle == BorderStyle.Fixed3D) { - Border3DStyle style = Border3DStyle.Sunken; - ControlPaint.DrawBorder3D(g, bounds, style ); + Pen pen = SystemPens.WindowFrame; + bounds.Width--; + bounds.Height--; + g.DrawRectangle(pen, bounds); + } + } + + /// + /// Paints the grid in the bounding rectangle given. + /// This includes the column headers and each visible row. + /// + private void PaintGrid(Graphics g, Rectangle gridBounds) + { + Debug.WriteLineIf(CompModSwitches.DataGridPainting.TraceVerbose, "DataGridPainting: PaintGrid on " + gridBounds.ToString()); + + Rectangle rc = gridBounds; + + if (this.listManager != null) + { + if (layout.ColumnHeadersVisible) + { + Region r = g.Clip; + g.SetClip(layout.ColumnHeaders); + PaintColumnHeaders(g); + g.Clip = r; + r.Dispose(); + int columnHeaderHeight = layout.ColumnHeaders.Height; + rc.Y += columnHeaderHeight; + rc.Height -= columnHeaderHeight; } - else if (BorderStyle == BorderStyle.FixedSingle) { - Brush br; - + + if (layout.TopLeftHeader.Width > 0) + { if (this.myGridTable.IsDefault) - br = this.HeaderForeBrush; + g.FillRectangle(this.HeaderBackBrush, layout.TopLeftHeader); else - br = this.myGridTable.HeaderForeBrush; - g.FillRectangle(br, bounds.X, bounds.Y, bounds.Width + 2, 2); - g.FillRectangle(br, bounds.Right - 2, bounds.Y, 2, bounds.Height + 2); - g.FillRectangle(br, bounds.X, bounds.Bottom - 2, bounds.Width + 2, 2); - g.FillRectangle(br, bounds.X, bounds.Y, 2, bounds.Height + 2); - } - else { - Pen pen = SystemPens.WindowFrame; - bounds.Width --; - bounds.Height--; - g.DrawRectangle(pen, bounds); - } - } - - /// - /// Paints the grid in the bounding rectangle given. - /// This includes the column headers and each visible row. - /// - private void PaintGrid(Graphics g, Rectangle gridBounds) { - Debug.WriteLineIf(CompModSwitches.DataGridPainting.TraceVerbose, "DataGridPainting: PaintGrid on " + gridBounds.ToString()); - - Rectangle rc = gridBounds; - - if (this.listManager != null) { - if (layout.ColumnHeadersVisible) { - Region r = g.Clip; - g.SetClip(layout.ColumnHeaders); - PaintColumnHeaders(g); - g.Clip = r; - r.Dispose(); - int columnHeaderHeight = layout.ColumnHeaders.Height; - rc.Y += columnHeaderHeight; - rc.Height -= columnHeaderHeight; - } - - if (layout.TopLeftHeader.Width > 0) { - if (this.myGridTable.IsDefault) - g.FillRectangle(this.HeaderBackBrush, layout.TopLeftHeader); - else - g.FillRectangle(this.myGridTable.HeaderBackBrush, layout.TopLeftHeader); - - if (!FlatMode) { - ControlPaint.DrawBorder3D(g, layout.TopLeftHeader, Border3DStyle.RaisedInner); - } + g.FillRectangle(this.myGridTable.HeaderBackBrush, layout.TopLeftHeader); + + if (!FlatMode) + { + ControlPaint.DrawBorder3D(g, layout.TopLeftHeader, Border3DStyle.RaisedInner); } - - PaintRows(g, ref rc) ; - } - - // paint the possible exposed portion below - if (rc.Height > 0) { - g.FillRectangle(backgroundBrush, rc); } + + PaintRows(g, ref rc); } - - private void DeleteDataGridRows(int deletedRows) { - if (deletedRows == 0) - return; - - int currentRowCount = DataGridRowsLength; - int newDataGridRowsLength = currentRowCount - deletedRows + (gridState[GRIDSTATE_inAddNewRow] ? 1:0); - DataGridRow[] newDataGridRows = new DataGridRow[newDataGridRowsLength]; - DataGridRow[] gridRows = DataGridRows; - - // the number of selected entries so far in the array - int selectedEntries = 0; - - for (int i = 0; i < currentRowCount; i++) { - if (gridRows[i].Selected) { - selectedEntries ++; - } else { - newDataGridRows[i - selectedEntries] = gridRows[i]; - newDataGridRows[i - selectedEntries].number = i - selectedEntries; - } + + // paint the possible exposed portion below + if (rc.Height > 0) + { + g.FillRectangle(backgroundBrush, rc); + } + } + + private void DeleteDataGridRows(int deletedRows) + { + if (deletedRows == 0) + return; + + int currentRowCount = DataGridRowsLength; + int newDataGridRowsLength = currentRowCount - deletedRows + (gridState[GRIDSTATE_inAddNewRow] ? 1 : 0); + DataGridRow[] newDataGridRows = new DataGridRow[newDataGridRowsLength]; + DataGridRow[] gridRows = DataGridRows; + + // the number of selected entries so far in the array + int selectedEntries = 0; + + for (int i = 0; i < currentRowCount; i++) + { + if (gridRows[i].Selected) + { + selectedEntries++; } - - if (gridState[GRIDSTATE_inAddNewRow]) { - newDataGridRows[currentRowCount - selectedEntries] = new DataGridAddNewRow(this, this.myGridTable, currentRowCount - selectedEntries); - gridState[GRIDSTATE_inAddNewRow] = false; + else + { + newDataGridRows[i - selectedEntries] = gridRows[i]; + newDataGridRows[i - selectedEntries].number = i - selectedEntries; } - - Debug.Assert(selectedEntries == deletedRows, "all the rows that would have been deleted should have been selected: selectedGridEntries " + selectedEntries.ToString(CultureInfo.InvariantCulture) + " deletedRows " + deletedRows.ToString(CultureInfo.InvariantCulture)); - - SetDataGridRows(newDataGridRows, newDataGridRowsLength); } - - /// - /// Paints the visible rows on the grid. - /// - private void PaintRows(Graphics g, ref Rectangle boundingRect) { - int cy = 0; - bool alignRight = isRightToLeft(); - Rectangle rowBounds = boundingRect; - Rectangle dataBounds = Rectangle.Empty; - bool paintRowHeaders = layout.RowHeadersVisible; - Rectangle headerBounds = Rectangle.Empty; - - - int numRows = DataGridRowsLength; - DataGridRow[] localGridRows = DataGridRows; - int numCols = myGridTable.GridColumnStyles.Count - firstVisibleCol; - - for (int row = firstVisibleRow; row < numRows; row++) { - if (cy > boundingRect.Height) - break; - - rowBounds = boundingRect; - rowBounds.Height = localGridRows[row].Height; - rowBounds.Y = boundingRect.Y + cy; - - // will add some errors - #if false + + if (gridState[GRIDSTATE_inAddNewRow]) + { + newDataGridRows[currentRowCount - selectedEntries] = new DataGridAddNewRow(this, this.myGridTable, currentRowCount - selectedEntries); + gridState[GRIDSTATE_inAddNewRow] = false; + } + + Debug.Assert(selectedEntries == deletedRows, "all the rows that would have been deleted should have been selected: selectedGridEntries " + selectedEntries.ToString(CultureInfo.InvariantCulture) + " deletedRows " + deletedRows.ToString(CultureInfo.InvariantCulture)); + + SetDataGridRows(newDataGridRows, newDataGridRowsLength); + } + + /// + /// Paints the visible rows on the grid. + /// + private void PaintRows(Graphics g, ref Rectangle boundingRect) + { + int cy = 0; + bool alignRight = isRightToLeft(); + Rectangle rowBounds = boundingRect; + Rectangle dataBounds = Rectangle.Empty; + bool paintRowHeaders = layout.RowHeadersVisible; + Rectangle headerBounds = Rectangle.Empty; + + + int numRows = DataGridRowsLength; + DataGridRow[] localGridRows = DataGridRows; + int numCols = myGridTable.GridColumnStyles.Count - firstVisibleCol; + + for (int row = firstVisibleRow; row < numRows; row++) + { + if (cy > boundingRect.Height) + break; + + rowBounds = boundingRect; + rowBounds.Height = localGridRows[row].Height; + rowBounds.Y = boundingRect.Y + cy; + + // will add some errors +#if false if (forDebug == 0 || forDebug == 1) { object dRowView = listManager[row]; @@ -7024,888 +7904,1017 @@ private void PaintRows(Graphics g, ref Rectangle boundingRect) { */ forDebug ++; } - #endif // false - if (paintRowHeaders) { - headerBounds = rowBounds; - headerBounds.Width = layout.RowHeaders.Width; - - if (alignRight) - { - headerBounds.X = rowBounds.Right - headerBounds.Width; - } - - if (g.IsVisible(headerBounds)) { - localGridRows[row].PaintHeader(g, headerBounds, alignRight, gridState[GRIDSTATE_isEditing]); - g.ExcludeClip(headerBounds); - } - - if (!alignRight) - rowBounds.X += headerBounds.Width; - rowBounds.Width -= headerBounds.Width; +#endif // false + if (paintRowHeaders) + { + headerBounds = rowBounds; + headerBounds.Width = layout.RowHeaders.Width; + + if (alignRight) + { + headerBounds.X = rowBounds.Right - headerBounds.Width; } - if (g.IsVisible(rowBounds)) { - dataBounds = rowBounds; - if (!alignRight) - dataBounds.X -= negOffset; - dataBounds.Width += negOffset; - - localGridRows[row].Paint(g, dataBounds, rowBounds, firstVisibleCol, numCols, alignRight); + + if (g.IsVisible(headerBounds)) + { + localGridRows[row].PaintHeader(g, headerBounds, alignRight, gridState[GRIDSTATE_isEditing]); + g.ExcludeClip(headerBounds); } - cy += rowBounds.Height; + + if (!alignRight) + rowBounds.X += headerBounds.Width; + rowBounds.Width -= headerBounds.Width; } - boundingRect.Y += cy; - boundingRect.Height -= cy; - } - - - /// - /// - /// Gets or sets a value that indicates whether a key should be processed - /// further. - /// - /// - protected override bool ProcessDialogKey(Keys keyData) { - Debug.WriteLineIf(CompModSwitches.DataGridKeys.TraceVerbose, "DataGridKeys: ProcessDialogKey " + TypeDescriptor.GetConverter(typeof(Keys)).ConvertToString(keyData)); - DataGridRow[] localGridRows = DataGridRows; - if (listManager != null && DataGridRowsLength > 0 && localGridRows[currentRow].OnKeyPress(keyData)) { - Debug.WriteLineIf(CompModSwitches.DataGridKeys.TraceVerbose, "DataGridKeys: Current Row ate the keystroke"); - return true; + if (g.IsVisible(rowBounds)) + { + dataBounds = rowBounds; + if (!alignRight) + dataBounds.X -= negOffset; + dataBounds.Width += negOffset; + + localGridRows[row].Paint(g, dataBounds, rowBounds, firstVisibleCol, numCols, alignRight); } - - switch (keyData & Keys.KeyCode) { - case Keys.Tab: - case Keys.Up: - case Keys.Down: - case Keys.Left: - case Keys.Right: - case Keys.Next: - case Keys.Prior: - case Keys.Enter: - case Keys.Escape: - case Keys.Oemplus: - case Keys.Add: - case Keys.OemMinus: - case Keys.Subtract: - case Keys.Space: - case Keys.Delete: - case Keys.A: - KeyEventArgs ke = new KeyEventArgs(keyData); - if (ProcessGridKey(ke)) - return true; - break; - - case Keys.C: - if ((keyData & Keys.Control) != 0 && (keyData & Keys.Alt) == 0) + cy += rowBounds.Height; + } + boundingRect.Y += cy; + boundingRect.Height -= cy; + } + + + /// + /// + /// Gets or sets a value that indicates whether a key should be processed + /// further. + /// + /// + protected override bool ProcessDialogKey(Keys keyData) + { + Debug.WriteLineIf(CompModSwitches.DataGridKeys.TraceVerbose, "DataGridKeys: ProcessDialogKey " + TypeDescriptor.GetConverter(typeof(Keys)).ConvertToString(keyData)); + DataGridRow[] localGridRows = DataGridRows; + if (listManager != null && DataGridRowsLength > 0 && localGridRows[currentRow].OnKeyPress(keyData)) + { + Debug.WriteLineIf(CompModSwitches.DataGridKeys.TraceVerbose, "DataGridKeys: Current Row ate the keystroke"); + return true; + } + + switch (keyData & Keys.KeyCode) + { + case Keys.Tab: + case Keys.Up: + case Keys.Down: + case Keys.Left: + case Keys.Right: + case Keys.Next: + case Keys.Prior: + case Keys.Enter: + case Keys.Escape: + case Keys.Oemplus: + case Keys.Add: + case Keys.OemMinus: + case Keys.Subtract: + case Keys.Space: + case Keys.Delete: + case Keys.A: + KeyEventArgs ke = new KeyEventArgs(keyData); + if (ProcessGridKey(ke)) + return true; + break; + + case Keys.C: + if ((keyData & Keys.Control) != 0 && (keyData & Keys.Alt) == 0) + { + // the user pressed Ctrl-C + if (!Bound) + break; + + // need to distinguish between selecting a set of rows, and + // selecting just one column. + if (numSelectedRows == 0) { - // the user pressed Ctrl-C - if (!Bound) - break; - - // need to distinguish between selecting a set of rows, and - // selecting just one column. - if (numSelectedRows == 0) + // copy the data from one column only + if (currentRow < ListManager.Count) { - // copy the data from one column only - if (currentRow < ListManager.Count) + GridColumnStylesCollection columns = myGridTable.GridColumnStyles; + if (currentCol >= 0 && currentCol < columns.Count) { - GridColumnStylesCollection columns = myGridTable.GridColumnStyles; - if (currentCol >= 0 && currentCol < columns.Count) - { - DataGridColumnStyle column = columns[currentCol]; - string text = column.GetDisplayText(column.GetColumnValueAtRow(ListManager, currentRow)); + DataGridColumnStyle column = columns[currentCol]; + string text = column.GetDisplayText(column.GetColumnValueAtRow(ListManager, currentRow)); - // copy the data to the clipboard - Clipboard.SetDataObject(text); - return true; - } - } + // copy the data to the clipboard + Clipboard.SetDataObject(text); + return true; + } } - else + } + else + { + // the user selected a set of rows to copy the data from + + int numRowsOutputted = 0; // the number of rows written to "text" + string text = string.Empty; + + for (int i = 0; i < DataGridRowsLength; ++i) { - // the user selected a set of rows to copy the data from - - int numRowsOutputted = 0; // the number of rows written to "text" - string text = string.Empty; - - for (int i = 0; i < DataGridRowsLength; ++i) + if (localGridRows[i].Selected) { - if (localGridRows[i].Selected) + GridColumnStylesCollection columns = myGridTable.GridColumnStyles; + int numCols = columns.Count; + for (int j = 0; j < numCols; j++) { - GridColumnStylesCollection columns = myGridTable.GridColumnStyles; - int numCols = columns.Count; - for (int j = 0; j < numCols; j++) - { - DataGridColumnStyle column = columns[j]; - text += column.GetDisplayText(column.GetColumnValueAtRow(ListManager, i)); - - // do not put the delimiter at the end of the last column - if ( j < numCols - 1) - { - text += GetOutputTextDelimiter(); - } - } - - // put the hard enter "\r\n" only if this is not the last selected row - if (numRowsOutputted < numSelectedRows - 1) + DataGridColumnStyle column = columns[j]; + text += column.GetDisplayText(column.GetColumnValueAtRow(ListManager, i)); + + // do not put the delimiter at the end of the last column + if (j < numCols - 1) { - text += "\r\n"; + text += GetOutputTextDelimiter(); } - - numRowsOutputted ++; } + + // put the hard enter "\r\n" only if this is not the last selected row + if (numRowsOutputted < numSelectedRows - 1) + { + text += "\r\n"; + } + + numRowsOutputted++; } - - // copy the data to the clipboard - Clipboard.SetDataObject(text); - return true; } - + + // copy the data to the clipboard + Clipboard.SetDataObject(text); + return true; } - break; - } - return base.ProcessDialogKey(keyData); + + } + break; } - - private void DeleteRows(DataGridRow[] localGridRows) { - int rowsDeleted = 0; - - int currentRowsCount = this.listManager == null ? 0 : this.listManager.Count; - - if (this.Visible) BeginUpdateInternal(); - try { - if (this.ListManager != null) { - for (int i = 0; i < this.DataGridRowsLength; i++) { - if (localGridRows[i].Selected) { - if (localGridRows[i] is DataGridAddNewRow) { - Debug.Assert(i == DataGridRowsLength - 1, "the location of addNewRow is " + i.ToString(CultureInfo.InvariantCulture) + " and there are " + DataGridRowsLength.ToString(CultureInfo.InvariantCulture) + " rows "); - localGridRows[i].Selected = false; - } - else { - this.ListManager.RemoveAt(i - rowsDeleted); - rowsDeleted ++; - } + return base.ProcessDialogKey(keyData); + } + + private void DeleteRows(DataGridRow[] localGridRows) + { + int rowsDeleted = 0; + + int currentRowsCount = this.listManager == null ? 0 : this.listManager.Count; + + if (this.Visible) + BeginUpdateInternal(); + try + { + if (this.ListManager != null) + { + for (int i = 0; i < this.DataGridRowsLength; i++) + { + if (localGridRows[i].Selected) + { + if (localGridRows[i] is DataGridAddNewRow) + { + Debug.Assert(i == DataGridRowsLength - 1, "the location of addNewRow is " + i.ToString(CultureInfo.InvariantCulture) + " and there are " + DataGridRowsLength.ToString(CultureInfo.InvariantCulture) + " rows "); + localGridRows[i].Selected = false; + } + else + { + this.ListManager.RemoveAt(i - rowsDeleted); + rowsDeleted++; } } } } - catch { - // if we got an exception from the back end - // when deleting the rows then we should reset - // our rows and re-throw the exception - // - RecreateDataGridRows(); - gridState[GRIDSTATE_inDeleteRow] = false; - if (this.Visible) EndUpdateInternal(); - throw; - } - // keep the copy of the old rows in place - // it may be the case that deleting one row could cause multiple rows to be deleted in the same list + } + catch + { + // if we got an exception from the back end + // when deleting the rows then we should reset + // our rows and re-throw the exception // - if (this.listManager != null && currentRowsCount == this.listManager.Count + rowsDeleted) { - DeleteDataGridRows(rowsDeleted); - } else { - RecreateDataGridRows(); - } - + RecreateDataGridRows(); gridState[GRIDSTATE_inDeleteRow] = false; - if (this.Visible) EndUpdateInternal(); + if (this.Visible) + EndUpdateInternal(); + throw; + } + // keep the copy of the old rows in place + // it may be the case that deleting one row could cause multiple rows to be deleted in the same list + // + if (this.listManager != null && currentRowsCount == this.listManager.Count + rowsDeleted) + { + DeleteDataGridRows(rowsDeleted); + } + else + { + RecreateDataGridRows(); + } - if (this.listManager != null && currentRowsCount != this.listManager.Count + rowsDeleted) { - Invalidate(); - } + gridState[GRIDSTATE_inDeleteRow] = false; + if (this.Visible) + EndUpdateInternal(); + + if (this.listManager != null && currentRowsCount != this.listManager.Count + rowsDeleted) + { + Invalidate(); } - - - // convention: - // if we return -1 it means that the user was going left and there were no visible columns to the left of the current one - // if we return cols.Count + 1 it means that the user was going right and there were no visible columns to the right of the currrent - private int MoveLeftRight(GridColumnStylesCollection cols, int startCol, bool goRight) { - int i; - if (goRight) { - for (i = startCol + 1; i < cols.Count; i++) { - // if (cols[i].Visible && cols[i].PropertyDescriptor != null) - if (cols[i].PropertyDescriptor != null) - return i; - } - return i; - } else { - for (i = startCol - 1; i>=0; i--) { - // if (cols[i].Visible && cols[i].PropertyDescriptor != null) - if (cols[i].PropertyDescriptor != null) - return i; - } - return i; + } + + + // convention: + // if we return -1 it means that the user was going left and there were no visible columns to the left of the current one + // if we return cols.Count + 1 it means that the user was going right and there were no visible columns to the right of the currrent + private int MoveLeftRight(GridColumnStylesCollection cols, int startCol, bool goRight) + { + int i; + if (goRight) + { + for (i = startCol + 1; i < cols.Count; i++) + { + // if (cols[i].Visible && cols[i].PropertyDescriptor != null) + if (cols[i].PropertyDescriptor != null) + return i; } + return i; } - - /// - /// - /// Processes keys for grid navigation. - /// - /// - [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] - // - protected bool ProcessGridKey(KeyEventArgs ke) { - Debug.WriteLineIf(CompModSwitches.DataGridKeys.TraceVerbose, "DataGridKeys: ProcessGridKey "+ TypeDescriptor.GetConverter(typeof(Keys)).ConvertToString(ke.KeyCode)); - if (listManager == null || myGridTable == null) - return false; - - DataGridRow[] localGridRows = DataGridRows; - KeyEventArgs biDiKe = ke; - // check for Bi-Di - // - if (isRightToLeft()) + else + { + for (i = startCol - 1; i >= 0; i--) { - switch(ke.KeyCode) { - case Keys.Left: - biDiKe = new KeyEventArgs((Keys.Right | ke.Modifiers)); - break; - case Keys.Right: - biDiKe = new KeyEventArgs((Keys.Left | ke.Modifiers)); - break; - default: - break; - } + // if (cols[i].Visible && cols[i].PropertyDescriptor != null) + if (cols[i].PropertyDescriptor != null) + return i; } - - GridColumnStylesCollection cols = this.myGridTable.GridColumnStyles; - int firstColumnMarkedVisible = 0; - int lastColumnMarkedVisible = cols.Count; - for (int i = 0; i < cols.Count; i++) { - if (cols[i].PropertyDescriptor != null) { - firstColumnMarkedVisible = i; + return i; + } + } + + /// + /// + /// Processes keys for grid navigation. + /// + /// + [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] + // + protected bool ProcessGridKey(KeyEventArgs ke) + { + Debug.WriteLineIf(CompModSwitches.DataGridKeys.TraceVerbose, "DataGridKeys: ProcessGridKey " + TypeDescriptor.GetConverter(typeof(Keys)).ConvertToString(ke.KeyCode)); + if (listManager == null || myGridTable == null) + return false; + + DataGridRow[] localGridRows = DataGridRows; + KeyEventArgs biDiKe = ke; + // check for Bi-Di + // + if (isRightToLeft()) + { + switch (ke.KeyCode) + { + case Keys.Left: + biDiKe = new KeyEventArgs((Keys.Right | ke.Modifiers)); break; - } - } - - for (int i = cols.Count - 1 ; i >= 0; i--) { - if (cols[i].PropertyDescriptor != null) { - lastColumnMarkedVisible = i; + case Keys.Right: + biDiKe = new KeyEventArgs((Keys.Left | ke.Modifiers)); + break; + default: break; - } } - - switch (biDiKe.KeyCode) { - case Keys.Tab: - return ProcessTabKey(biDiKe.KeyData); - case Keys.Up: - gridState[GRIDSTATE_childLinkFocused] = false; - if (this.dataGridRowsLength == 0) { - return true; - } + } - if (biDiKe.Control && !biDiKe.Alt) - { - if (biDiKe.Shift) - { - DataGridRow [] gridRows = DataGridRows; - - int savedCurrentRow = currentRow; - CurrentRow = 0; - - ResetSelection(); - - for (int i = 0; i <= savedCurrentRow; i ++) - gridRows[i].Selected = true; - numSelectedRows = savedCurrentRow + 1; - // hide the edit box - // - EndEdit(); - return true; - } - // do not make the parentRowsVisible = false; - // ParentRowsVisible = false; - ResetSelection(); - CurrentRow = 0; - Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); - return true; - } - else if (biDiKe.Shift) - { - DataGridRow [] gridRows = DataGridRows; - // keep a continous selected region - if (gridRows[currentRow].Selected) { - if (currentRow >= 1) { - if (gridRows[currentRow - 1].Selected) { - if (currentRow >= DataGridRowsLength - 1 || !gridRows[currentRow+1].Selected) { - numSelectedRows --; - gridRows[currentRow].Selected = false; - } - } else { - numSelectedRows += gridRows[currentRow -1].Selected ? 0:1; - gridRows[currentRow - 1].Selected = true; - } - CurrentRow --; - } - } else { - numSelectedRows ++; - gridRows[currentRow].Selected = true; - if (currentRow >= 1) { - numSelectedRows += gridRows[currentRow-1].Selected ? 0:1; - gridRows[currentRow-1].Selected = true; - CurrentRow --; - } - } - - // hide the edit box: - // - EndEdit(); - Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); - return true; - } - else if (biDiKe.Alt) + GridColumnStylesCollection cols = this.myGridTable.GridColumnStyles; + int firstColumnMarkedVisible = 0; + int lastColumnMarkedVisible = cols.Count; + for (int i = 0; i < cols.Count; i++) + { + if (cols[i].PropertyDescriptor != null) + { + firstColumnMarkedVisible = i; + break; + } + } + + for (int i = cols.Count - 1; i >= 0; i--) + { + if (cols[i].PropertyDescriptor != null) + { + lastColumnMarkedVisible = i; + break; + } + } + + switch (biDiKe.KeyCode) + { + case Keys.Tab: + return ProcessTabKey(biDiKe.KeyData); + case Keys.Up: + gridState[GRIDSTATE_childLinkFocused] = false; + if (this.dataGridRowsLength == 0) + { + return true; + } + + if (biDiKe.Control && !biDiKe.Alt) + { + if (biDiKe.Shift) { - // will need to collapse all child table links - // -1 is for all rows, and false is for collapsing the rows - SetRowExpansionState(-1, false); - Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); + DataGridRow[] gridRows = DataGridRows; + + int savedCurrentRow = currentRow; + CurrentRow = 0; + + ResetSelection(); + + for (int i = 0; i <= savedCurrentRow; i++) + gridRows[i].Selected = true; + numSelectedRows = savedCurrentRow + 1; + // hide the edit box + // + EndEdit(); return true; } + // do not make the parentRowsVisible = false; + // ParentRowsVisible = false; ResetSelection(); - CurrentRow = CurrentRow - 1; - Edit(); + CurrentRow = 0; Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); - break; - case Keys.Down: - gridState[GRIDSTATE_childLinkFocused] = false; - if (this.dataGridRowsLength == 0) { - return true; - } - - if (biDiKe.Control && !biDiKe.Alt) + return true; + } + else if (biDiKe.Shift) + { + DataGridRow[] gridRows = DataGridRows; + // keep a continous selected region + if (gridRows[currentRow].Selected) { - if (biDiKe.Shift) + if (currentRow >= 1) { - int savedCurrentRow = currentRow; - CurrentRow = Math.Max(0, DataGridRowsLength - (policy.AllowAdd ? 2:1)); - DataGridRow [] gridRows = DataGridRows; - - ResetSelection(); - - for (int i = savedCurrentRow; i <= currentRow; i++) - gridRows[i].Selected = true; - - numSelectedRows = currentRow - savedCurrentRow + 1; - // hide the edit box - // - EndEdit(); - return true; - } - // do not make the parentRowsVisible = true; - // ParentRowsVisible = true; - ResetSelection(); - CurrentRow = Math.Max(0, DataGridRowsLength - (policy.AllowAdd ? 2 : 1)); - Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); - return true; - } - else if (biDiKe.Shift) - { - DataGridRow [] gridRows = DataGridRows; - - // keep a continous selected region - if (gridRows[currentRow].Selected) { - - // -1 because we index from 0 - if (currentRow < DataGridRowsLength - (policy.AllowAdd ? 1:0) - 1) { - if (gridRows[currentRow + 1].Selected) { - if (currentRow == 0 || !gridRows[currentRow - 1].Selected) { - numSelectedRows --; - gridRows[currentRow].Selected = false; - } - } else { - numSelectedRows += gridRows[currentRow + 1].Selected ? 0:1; - gridRows[currentRow + 1].Selected = true; + if (gridRows[currentRow - 1].Selected) + { + if (currentRow >= DataGridRowsLength - 1 || !gridRows[currentRow + 1].Selected) + { + numSelectedRows--; + gridRows[currentRow].Selected = false; } - - CurrentRow ++; } - } else { - numSelectedRows ++; - gridRows[currentRow].Selected = true; - // -1 because we index from 0, and -1 so this is not the last row - // so it adds to -2 - if (currentRow < DataGridRowsLength - (policy.AllowAdd ? 1:0) - 1) { - CurrentRow ++; - numSelectedRows += gridRows[currentRow].Selected ? 0:1; - gridRows[currentRow].Selected = true; + else + { + numSelectedRows += gridRows[currentRow - 1].Selected ? 0 : 1; + gridRows[currentRow - 1].Selected = true; } + CurrentRow--; } - - // hide the edit box: - // - EndEdit(); - Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); - return true; } - else if (biDiKe.Alt) + else { - // will need to expande all child table links - // -1 is for all rows, and true is for expanding the rows - SetRowExpansionState(-1, true); - return true; + numSelectedRows++; + gridRows[currentRow].Selected = true; + if (currentRow >= 1) + { + numSelectedRows += gridRows[currentRow - 1].Selected ? 0 : 1; + gridRows[currentRow - 1].Selected = true; + CurrentRow--; + } } - ResetSelection(); - Edit(); - CurrentRow = CurrentRow + 1; + + // hide the edit box: + // + EndEdit(); Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); - break; - case Keys.OemMinus: - case Keys.Subtract: - gridState[GRIDSTATE_childLinkFocused] = false; - if (biDiKe.Control && !biDiKe.Alt) - { - SetRowExpansionState(-1, false); - return true; - } - return false; - case Keys.Oemplus: - case Keys.Add: - gridState[GRIDSTATE_childLinkFocused] = false; - if (biDiKe.Control) - { - SetRowExpansionState(-1, true); - // hide the edit box - // - EndEdit(); - return true; - } - return false; - case Keys.Space: - gridState[GRIDSTATE_childLinkFocused] = false; - if (this.dataGridRowsLength == 0) { - return true; - } + return true; + } + else if (biDiKe.Alt) + { + // will need to collapse all child table links + // -1 is for all rows, and false is for collapsing the rows + SetRowExpansionState(-1, false); + Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); + return true; + } + ResetSelection(); + CurrentRow = CurrentRow - 1; + Edit(); + Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); + break; + case Keys.Down: + gridState[GRIDSTATE_childLinkFocused] = false; + if (this.dataGridRowsLength == 0) + { + return true; + } + if (biDiKe.Control && !biDiKe.Alt) + { if (biDiKe.Shift) { + int savedCurrentRow = currentRow; + CurrentRow = Math.Max(0, DataGridRowsLength - (policy.AllowAdd ? 2 : 1)); + DataGridRow[] gridRows = DataGridRows; + ResetSelection(); - EndEdit(); - DataGridRow [] gridRows = DataGridRows; - gridRows[currentRow].Selected = true; - numSelectedRows = 1; - - return true; - } - return false; - case Keys.Next: - gridState[GRIDSTATE_childLinkFocused] = false; - if (this.dataGridRowsLength == 0) { - return true; - } - if (biDiKe.Shift) - { - int savedCurrentRow = currentRow; - CurrentRow = Math.Min(DataGridRowsLength - (policy.AllowAdd ? 2:1), currentRow + numTotallyVisibleRows); - - DataGridRow [] gridRows = DataGridRows; for (int i = savedCurrentRow; i <= currentRow; i++) - { - if (!gridRows[i].Selected) - { - gridRows[i].Selected = true; - numSelectedRows ++; - } - } - // hide edit box + gridRows[i].Selected = true; + + numSelectedRows = currentRow - savedCurrentRow + 1; + // hide the edit box // EndEdit(); - } else if (biDiKe.Control && !biDiKe.Alt) { - // map ctrl-pageDown to show the parentRows - ParentRowsVisible = true; - } - else - { - ResetSelection(); - CurrentRow = Math.Min(DataGridRowsLength - (policy.AllowAdd ? 2:1), - CurrentRow + numTotallyVisibleRows); - } - break; - case Keys.Prior: - if (this.dataGridRowsLength == 0) { return true; } + // do not make the parentRowsVisible = true; + // ParentRowsVisible = true; + ResetSelection(); + CurrentRow = Math.Max(0, DataGridRowsLength - (policy.AllowAdd ? 2 : 1)); + Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); + return true; + } + else if (biDiKe.Shift) + { + DataGridRow[] gridRows = DataGridRows; - gridState[GRIDSTATE_childLinkFocused] = false; - if (biDiKe.Shift) + // keep a continous selected region + if (gridRows[currentRow].Selected) { - int savedCurrentRow = currentRow; - CurrentRow = Math.Max(0, CurrentRow - numTotallyVisibleRows); - - DataGridRow [] gridRows = DataGridRows; - for (int i = savedCurrentRow; i >= currentRow; i--) + + // -1 because we index from 0 + if (currentRow < DataGridRowsLength - (policy.AllowAdd ? 1 : 0) - 1) { - if ( !gridRows[i].Selected) + if (gridRows[currentRow + 1].Selected) + { + if (currentRow == 0 || !gridRows[currentRow - 1].Selected) + { + numSelectedRows--; + gridRows[currentRow].Selected = false; + } + } + else { - gridRows[i].Selected = true; - numSelectedRows ++; + numSelectedRows += gridRows[currentRow + 1].Selected ? 0 : 1; + gridRows[currentRow + 1].Selected = true; } + + CurrentRow++; } - - // hide the edit box - // - EndEdit(); - } else if (biDiKe.Control && !biDiKe.Alt) { - // map ctrl-pageUp to hide the parentRows - ParentRowsVisible = false; } else { - ResetSelection(); - CurrentRow = Math.Max(0, - CurrentRow - numTotallyVisibleRows); + numSelectedRows++; + gridRows[currentRow].Selected = true; + // -1 because we index from 0, and -1 so this is not the last row + // so it adds to -2 + if (currentRow < DataGridRowsLength - (policy.AllowAdd ? 1 : 0) - 1) + { + CurrentRow++; + numSelectedRows += gridRows[currentRow].Selected ? 0 : 1; + gridRows[currentRow].Selected = true; + } } - break; - case Keys.Left: - gridState[GRIDSTATE_childLinkFocused] = false; + + // hide the edit box: + // + EndEdit(); + Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); + return true; + } + else if (biDiKe.Alt) + { + // will need to expande all child table links + // -1 is for all rows, and true is for expanding the rows + SetRowExpansionState(-1, true); + return true; + } + ResetSelection(); + Edit(); + CurrentRow = CurrentRow + 1; + Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); + break; + case Keys.OemMinus: + case Keys.Subtract: + gridState[GRIDSTATE_childLinkFocused] = false; + if (biDiKe.Control && !biDiKe.Alt) + { + SetRowExpansionState(-1, false); + return true; + } + return false; + case Keys.Oemplus: + case Keys.Add: + gridState[GRIDSTATE_childLinkFocused] = false; + if (biDiKe.Control) + { + SetRowExpansionState(-1, true); + // hide the edit box + // + EndEdit(); + return true; + } + return false; + case Keys.Space: + gridState[GRIDSTATE_childLinkFocused] = false; + if (this.dataGridRowsLength == 0) + { + return true; + } + + if (biDiKe.Shift) + { ResetSelection(); - if ((biDiKe.Modifiers & Keys.Modifiers) == Keys.Alt) - { - if (Caption.BackButtonVisible) - NavigateBack(); - return true; - } - - if ((biDiKe.Modifiers & Keys.Control) == Keys.Control) - { - // we should navigate to the first visible column - CurrentColumn = firstColumnMarkedVisible; - break; - } - - if (currentCol == firstColumnMarkedVisible && currentRow != 0) + EndEdit(); + DataGridRow[] gridRows = DataGridRows; + gridRows[currentRow].Selected = true; + numSelectedRows = 1; + + return true; + } + return false; + case Keys.Next: + gridState[GRIDSTATE_childLinkFocused] = false; + if (this.dataGridRowsLength == 0) + { + return true; + } + + if (biDiKe.Shift) + { + int savedCurrentRow = currentRow; + CurrentRow = Math.Min(DataGridRowsLength - (policy.AllowAdd ? 2 : 1), currentRow + numTotallyVisibleRows); + + DataGridRow[] gridRows = DataGridRows; + for (int i = savedCurrentRow; i <= currentRow; i++) { - CurrentRow = CurrentRow - 1; - int newCol = MoveLeftRight(this.myGridTable.GridColumnStyles, this.myGridTable.GridColumnStyles.Count, false); - Debug.Assert(newCol != -1, "there should be at least a visible column, right?"); - CurrentColumn = newCol; - } - else { - int newCol = MoveLeftRight(this.myGridTable.GridColumnStyles, currentCol, false); - if (newCol == -1) { - if (currentRow == 0) - return true; - else { - // go to the previous row: - CurrentRow = CurrentRow - 1; - CurrentColumn = lastColumnMarkedVisible; - } - } else { - CurrentColumn = newCol; + if (!gridRows[i].Selected) + { + gridRows[i].Selected = true; + numSelectedRows++; } } - break; - case Keys.Right: - gridState[GRIDSTATE_childLinkFocused] = false; + // hide edit box + // + EndEdit(); + } + else if (biDiKe.Control && !biDiKe.Alt) + { + // map ctrl-pageDown to show the parentRows + ParentRowsVisible = true; + } + else + { ResetSelection(); - if ((biDiKe.Modifiers & Keys.Control) == Keys.Control && !biDiKe.Alt) - { - // we should navigate to the last column that is marked as Visible - CurrentColumn = lastColumnMarkedVisible; - break; - } - - if (currentCol == lastColumnMarkedVisible && currentRow != DataGridRowsLength - 1) + CurrentRow = Math.Min(DataGridRowsLength - (policy.AllowAdd ? 2 : 1), + CurrentRow + numTotallyVisibleRows); + } + break; + case Keys.Prior: + if (this.dataGridRowsLength == 0) + { + return true; + } + + gridState[GRIDSTATE_childLinkFocused] = false; + if (biDiKe.Shift) + { + int savedCurrentRow = currentRow; + CurrentRow = Math.Max(0, CurrentRow - numTotallyVisibleRows); + + DataGridRow[] gridRows = DataGridRows; + for (int i = savedCurrentRow; i >= currentRow; i--) { - CurrentRow = CurrentRow + 1; - // navigate to the first visible column - CurrentColumn = firstColumnMarkedVisible; - } - else { - int newCol = MoveLeftRight(this.myGridTable.GridColumnStyles, this.currentCol, true); - if (newCol == cols.Count + 1) { - // navigate to the first visible column - // and the next row - // - CurrentColumn = firstColumnMarkedVisible; - CurrentRow ++; + if (!gridRows[i].Selected) + { + gridRows[i].Selected = true; + numSelectedRows++; } - else - CurrentColumn = newCol; } - break; - case Keys.F2: - gridState[GRIDSTATE_childLinkFocused] = false; + + // hide the edit box + // + EndEdit(); + } + else if (biDiKe.Control && !biDiKe.Alt) + { + // map ctrl-pageUp to hide the parentRows + ParentRowsVisible = false; + } + else + { ResetSelection(); - Edit(); - break; - #if DEBUG - case Keys.F12: - gridState[GRIDSTATE_childLinkFocused] = false; - AddNewRow(); + CurrentRow = Math.Max(0, + CurrentRow - numTotallyVisibleRows); + } + break; + case Keys.Left: + gridState[GRIDSTATE_childLinkFocused] = false; + ResetSelection(); + if ((biDiKe.Modifiers & Keys.Modifiers) == Keys.Alt) + { + if (Caption.BackButtonVisible) + NavigateBack(); + return true; + } + + if ((biDiKe.Modifiers & Keys.Control) == Keys.Control) + { + // we should navigate to the first visible column + CurrentColumn = firstColumnMarkedVisible; break; - #endif - case Keys.Home: - gridState[GRIDSTATE_childLinkFocused] = false; - if (this.dataGridRowsLength == 0) { - return true; - } + } - ResetSelection(); - CurrentColumn = 0; - if (biDiKe.Control && !biDiKe.Alt) { - int currentRowSaved = currentRow; - CurrentRow = 0; - - if (biDiKe.Shift) + if (currentCol == firstColumnMarkedVisible && currentRow != 0) + { + CurrentRow = CurrentRow - 1; + int newCol = MoveLeftRight(this.myGridTable.GridColumnStyles, this.myGridTable.GridColumnStyles.Count, false); + Debug.Assert(newCol != -1, "there should be at least a visible column, right?"); + CurrentColumn = newCol; + } + else + { + int newCol = MoveLeftRight(this.myGridTable.GridColumnStyles, currentCol, false); + if (newCol == -1) + { + if (currentRow == 0) + return true; + else { - // Ctrl-Shift-Home will select all the rows up to the first one - DataGridRow[] gridRows = DataGridRows; - for (int i = 0; i <= currentRowSaved; i++) - { - gridRows[i].Selected = true; - numSelectedRows ++; - } - // hide the edit box: - EndEdit(); + // go to the previous row: + CurrentRow = CurrentRow - 1; + CurrentColumn = lastColumnMarkedVisible; } - Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); - return true; } - Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); - break; - case Keys.Delete: - gridState[GRIDSTATE_childLinkFocused] = false; - if (policy.AllowRemove && numSelectedRows > 0) { - #if DEBUG - // when the list is empty, then the position - // in the listManager is -1, and the currentPosition in the grid is 0 - if (ListManager != null && ListManager.Count > 0) { - Debug.Assert(ListManager.Position == this.currentRow, - "Current row out of sync with DataSource", - "The DataSource's Position property should be mirrored by the CurrentCell.RowNumber of the DataGrid."); - } - #endif // DEBUG - - gridState[GRIDSTATE_inDeleteRow] = true; - DeleteRows(localGridRows); - // set the currentRow to the position in the list - this.currentRow = this.listManager.Count == 0 ? 0 : this.listManager.Position; - numSelectedRows = 0; - } else { - // if we did not use the the Delete key, let the dataGridTextBox use it - return false; + else + { + CurrentColumn = newCol; } + } + break; + case Keys.Right: + gridState[GRIDSTATE_childLinkFocused] = false; + ResetSelection(); + if ((biDiKe.Modifiers & Keys.Control) == Keys.Control && !biDiKe.Alt) + { + // we should navigate to the last column that is marked as Visible + CurrentColumn = lastColumnMarkedVisible; break; - case Keys.End: - gridState[GRIDSTATE_childLinkFocused] = false; - if (this.dataGridRowsLength == 0) { - return true; + } + + if (currentCol == lastColumnMarkedVisible && currentRow != DataGridRowsLength - 1) + { + CurrentRow = CurrentRow + 1; + // navigate to the first visible column + CurrentColumn = firstColumnMarkedVisible; + } + else + { + int newCol = MoveLeftRight(this.myGridTable.GridColumnStyles, this.currentCol, true); + if (newCol == cols.Count + 1) + { + // navigate to the first visible column + // and the next row + // + CurrentColumn = firstColumnMarkedVisible; + CurrentRow++; } + else + CurrentColumn = newCol; + } + break; + case Keys.F2: + gridState[GRIDSTATE_childLinkFocused] = false; + ResetSelection(); + Edit(); + break; +#if DEBUG + case Keys.F12: + gridState[GRIDSTATE_childLinkFocused] = false; + AddNewRow(); + break; +#endif + case Keys.Home: + gridState[GRIDSTATE_childLinkFocused] = false; + if (this.dataGridRowsLength == 0) + { + return true; + } - ResetSelection(); - // go the the last visible column - CurrentColumn = lastColumnMarkedVisible; - - if (biDiKe.Control && !biDiKe.Alt) { - int savedCurrentRow = currentRow; - CurrentRow = Math.Max(0, DataGridRowsLength - (policy.AllowAdd ? 2:1)); - - if (biDiKe.Shift) + ResetSelection(); + CurrentColumn = 0; + if (biDiKe.Control && !biDiKe.Alt) + { + int currentRowSaved = currentRow; + CurrentRow = 0; + + if (biDiKe.Shift) + { + // Ctrl-Shift-Home will select all the rows up to the first one + DataGridRow[] gridRows = DataGridRows; + for (int i = 0; i <= currentRowSaved; i++) { - // Ctrl-Shift-Home will select all the rows up to the first one - DataGridRow[] gridRows = DataGridRows; - for (int i = savedCurrentRow; i <= currentRow; i++) - { - gridRows[i].Selected = true; - } - numSelectedRows = currentRow - savedCurrentRow + 1; - // hide the edit box - // - EndEdit(); + gridRows[i].Selected = true; + numSelectedRows++; } - Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); - return true; - } - Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); - break; - case Keys.Enter: - gridState[GRIDSTATE_childLinkFocused] = false; - ResetSelection(); - - // yield the return key if there is no editing - if (!gridState[GRIDSTATE_isEditing]) - return false; - - // Ctrl-Enter will call EndCurrentEdit - if ((biDiKe.Modifiers & Keys.Control) != 0 && !biDiKe.Alt) - { + // hide the edit box: EndEdit(); - HandleEndCurrentEdit(); - Edit(); // put the edit box on the screen } - else + Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); + return true; + } + Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); + break; + case Keys.Delete: + gridState[GRIDSTATE_childLinkFocused] = false; + if (policy.AllowRemove && numSelectedRows > 0) + { +#if DEBUG + // when the list is empty, then the position + // in the listManager is -1, and the currentPosition in the grid is 0 + if (ListManager != null && ListManager.Count > 0) { - // Do not commit the edit, cause reseting the - // current cell will do that - // - // CommitEdit(); - - CurrentRow = currentRow + 1; + Debug.Assert(ListManager.Position == this.currentRow, + "Current row out of sync with DataSource", + "The DataSource's Position property should be mirrored by the CurrentCell.RowNumber of the DataGrid."); } - - break; - case Keys.A: - gridState[GRIDSTATE_childLinkFocused] = false; - if (biDiKe.Control && !biDiKe.Alt) +#endif // DEBUG + + gridState[GRIDSTATE_inDeleteRow] = true; + DeleteRows(localGridRows); + // set the currentRow to the position in the list + this.currentRow = this.listManager.Count == 0 ? 0 : this.listManager.Position; + numSelectedRows = 0; + } + else + { + // if we did not use the the Delete key, let the dataGridTextBox use it + return false; + } + break; + case Keys.End: + gridState[GRIDSTATE_childLinkFocused] = false; + if (this.dataGridRowsLength == 0) + { + return true; + } + + ResetSelection(); + // go the the last visible column + CurrentColumn = lastColumnMarkedVisible; + + if (biDiKe.Control && !biDiKe.Alt) + { + int savedCurrentRow = currentRow; + CurrentRow = Math.Max(0, DataGridRowsLength - (policy.AllowAdd ? 2 : 1)); + + if (biDiKe.Shift) { - DataGridRow [] gridRows = DataGridRows; - for (int i = 0; i < DataGridRowsLength; i++) - if (gridRows[i] is DataGridRelationshipRow) gridRows[i].Selected = true; - - numSelectedRows = DataGridRowsLength - (policy.AllowAdd ? 1 : 0); + // Ctrl-Shift-Home will select all the rows up to the first one + DataGridRow[] gridRows = DataGridRows; + for (int i = savedCurrentRow; i <= currentRow; i++) + { + gridRows[i].Selected = true; + } + numSelectedRows = currentRow - savedCurrentRow + 1; // hide the edit box // EndEdit(); - return true; } + Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); + return true; + } + Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); + break; + case Keys.Enter: + gridState[GRIDSTATE_childLinkFocused] = false; + ResetSelection(); + + // yield the return key if there is no editing + if (!gridState[GRIDSTATE_isEditing]) return false; - case Keys.Escape: - gridState[GRIDSTATE_childLinkFocused] = false; - ResetSelection(); - if (gridState[GRIDSTATE_isEditing]) + + // Ctrl-Enter will call EndCurrentEdit + if ((biDiKe.Modifiers & Keys.Control) != 0 && !biDiKe.Alt) + { + EndEdit(); + HandleEndCurrentEdit(); + Edit(); // put the edit box on the screen + } + else + { + // Do not commit the edit, cause reseting the + // current cell will do that + // + // CommitEdit(); + + CurrentRow = currentRow + 1; + } + + break; + case Keys.A: + gridState[GRIDSTATE_childLinkFocused] = false; + if (biDiKe.Control && !biDiKe.Alt) + { + DataGridRow[] gridRows = DataGridRows; + for (int i = 0; i < DataGridRowsLength; i++) + if (gridRows[i] is DataGridRelationshipRow) + gridRows[i].Selected = true; + + numSelectedRows = DataGridRowsLength - (policy.AllowAdd ? 1 : 0); + // hide the edit box + // + EndEdit(); + return true; + } + return false; + case Keys.Escape: + gridState[GRIDSTATE_childLinkFocused] = false; + ResetSelection(); + if (gridState[GRIDSTATE_isEditing]) + { + // rollback + AbortEdit(); + + // we have to invalidate the row header ( make it display the row selector instead of the pencil ) + if (layout.RowHeadersVisible && this.currentRow > -1) { - // rollback - AbortEdit(); - - // we have to invalidate the row header ( make it display the row selector instead of the pencil ) - if (layout.RowHeadersVisible && this.currentRow > -1) { - Rectangle rowHdrRect = GetRowRect(this.currentRow); - rowHdrRect.Width = layout.RowHeaders.Width; - Invalidate(rowHdrRect); - } - - // now put the edit column back on the screen - Edit(); - } - else { - // add this protected virtual method for the XML designer team - CancelEditing(); - Edit(); - return false; + Rectangle rowHdrRect = GetRowRect(this.currentRow); + rowHdrRect.Width = layout.RowHeaders.Width; + Invalidate(rowHdrRect); } - break; - } - return true; - } - - /// - /// Previews a keyboard message and returns a value indicating if the key was - /// consumed. - /// - protected override bool ProcessKeyPreview(ref Message m) { - if (m.Msg == Interop.WindowMessages.WM_KEYDOWN) { - KeyEventArgs ke = new KeyEventArgs((Keys)(unchecked((int)(long)m.WParam)) | ModifierKeys); - switch (ke.KeyCode) { - case Keys.Up: - case Keys.Down: - case Keys.Prior: - case Keys.Next: - case Keys.Right: - case Keys.Left: - case Keys.Tab: - case Keys.Escape: - case Keys.Enter: - case Keys.OemMinus: - case Keys.Subtract: - case Keys.Oemplus: - case Keys.Add: - case Keys.Space: - case Keys.Home: - case Keys.End: - case Keys.F2: - case Keys.Delete: - case Keys.A: - return ProcessGridKey(ke); + + // now put the edit column back on the screen + Edit(); + } + else + { + // add this protected virtual method for the XML designer team + CancelEditing(); + Edit(); + return false; } + break; + } + return true; + } + + /// + /// Previews a keyboard message and returns a value indicating if the key was + /// consumed. + /// + protected override bool ProcessKeyPreview(ref Message m) + { + if (m.Msg == Interop.WindowMessages.WM_KEYDOWN) + { + KeyEventArgs ke = new KeyEventArgs((Keys)(unchecked((int)(long)m.WParam)) | ModifierKeys); + switch (ke.KeyCode) + { + case Keys.Up: + case Keys.Down: + case Keys.Prior: + case Keys.Next: + case Keys.Right: + case Keys.Left: + case Keys.Tab: + case Keys.Escape: + case Keys.Enter: + case Keys.OemMinus: + case Keys.Subtract: + case Keys.Oemplus: + case Keys.Add: + case Keys.Space: + case Keys.Home: + case Keys.End: + case Keys.F2: + case Keys.Delete: + case Keys.A: + return ProcessGridKey(ke); + } // Ctrl-Tab will be sent as a tab paired w/ a control on the KeyUp message // - } else if (m.Msg == Interop.WindowMessages.WM_KEYUP) { - KeyEventArgs ke = new KeyEventArgs((Keys)(unchecked((int)(long)m.WParam)) | ModifierKeys); - if (ke.KeyCode == Keys.Tab) - return ProcessGridKey(ke); + } + else if (m.Msg == Interop.WindowMessages.WM_KEYUP) + { + KeyEventArgs ke = new KeyEventArgs((Keys)(unchecked((int)(long)m.WParam)) | ModifierKeys); + if (ke.KeyCode == Keys.Tab) + return ProcessGridKey(ke); + } + + return base.ProcessKeyPreview(ref m); + } + + /// + /// + /// Gets a value indicating whether the Tab key should be processed. + /// + /// + protected bool ProcessTabKey(Keys keyData) + { + if (this.listManager == null || myGridTable == null) + return false; + bool wasEditing = false; + int columnCount = myGridTable.GridColumnStyles.Count; + bool biDi = isRightToLeft(); + ResetSelection(); + + // Try to commit changes to cell if we were editing + if (gridState[GRIDSTATE_isEditing]) + { + wasEditing = true; + if (!CommitEdit()) + { + //MessageBox.Show("Could not commit changes! Press Escape to abort edit"); + Edit(); // if we can't commit the value put the edit box so that the user sees where the focus is + return true; } - - return base.ProcessKeyPreview(ref m); } - - /// - /// - /// Gets a value indicating whether the Tab key should be processed. - /// - /// - protected bool ProcessTabKey(Keys keyData) { - if (this.listManager == null || myGridTable == null) - return false; - bool wasEditing = false; - int columnCount = myGridTable.GridColumnStyles.Count; - bool biDi = isRightToLeft(); - ResetSelection(); - - // Try to commit changes to cell if we were editing - if (gridState[GRIDSTATE_isEditing]) { - wasEditing = true; - if (!CommitEdit()) { - //MessageBox.Show("Could not commit changes! Press Escape to abort edit"); - Edit(); // if we can't commit the value put the edit box so that the user sees where the focus is - return true; - } + + if ((keyData & Keys.Control) == Keys.Control) + { + // when the user hits ctrl-alt-tab just ignore it. + if ((keyData & Keys.Alt) == Keys.Alt) + return true; + + // navigate to the next control in the form + Keys ke = keyData & ~(Keys.Control); + EndEdit(); + + gridState[GRIDSTATE_editControlChanging] = true; + try + { + Focus(); } - - if ((keyData & Keys.Control) == Keys.Control) + finally + { + gridState[GRIDSTATE_editControlChanging] = false; + } + + return base.ProcessDialogKey(ke); + } + + // see if the child relationships can use this TAB key + DataGridRow[] localRows = DataGridRows; + GridColumnStylesCollection cols = this.myGridTable.GridColumnStyles; + + int lastColumnMarkedVisible = 0; + int firstColumnMarkedVisible = cols.Count - 1; + // + + if (localRows.Length == 0) + { + EndEdit(); + + return base.ProcessDialogKey(keyData); + } + + for (int i = 0; i < cols.Count; i++) + { + // if (cols[i].Visible && cols[i].PropertyDescriptor != null) { + if (cols[i].PropertyDescriptor != null) + { + firstColumnMarkedVisible = i; + break; + } + } + for (int i = cols.Count - 1; i >= 0; i--) + { + // if (cols[i].Visible && cols[i].PropertyDescriptor != null) { + if (cols[i].PropertyDescriptor != null) + { + lastColumnMarkedVisible = i; + break; + } + } + + if (CurrentColumn == lastColumnMarkedVisible) + { + if (gridState[GRIDSTATE_childLinkFocused] || (!gridState[GRIDSTATE_childLinkFocused] && (keyData & Keys.Shift) != Keys.Shift)) { - // when the user hits ctrl-alt-tab just ignore it. - if ((keyData & Keys.Alt) == Keys.Alt) + if (localRows[CurrentRow].ProcessTabKey(keyData, layout.RowHeaders, isRightToLeft())) + { + if (cols.Count > 0) + cols[CurrentColumn].ConcedeFocus(); + gridState[GRIDSTATE_childLinkFocused] = true; + // let the grid regain focus + // introduced because of that BeginInvoke thing in the OnLeave method.... + if (gridState[GRIDSTATE_canFocus] && CanFocus && !Focused) + this.Focus(); return true; - - // navigate to the next control in the form - Keys ke = keyData & ~(Keys.Control); - EndEdit(); - - gridState[GRIDSTATE_editControlChanging] = true; - try { - Focus(); - } finally { - gridState[GRIDSTATE_editControlChanging] = false; } - - return base.ProcessDialogKey(ke); } - - // see if the child relationships can use this TAB key - DataGridRow[] localRows = DataGridRows; - GridColumnStylesCollection cols = this.myGridTable.GridColumnStyles; - - int lastColumnMarkedVisible = 0; - int firstColumnMarkedVisible = cols.Count-1; - // - if (localRows.Length == 0) { + // actually, it turns out that we should leave the + // control if we are in the last row + if ((this.currentRow == this.DataGridRowsLength - 1) && ((keyData & Keys.Shift) == 0)) + { + EndEdit(); - return base.ProcessDialogKey(keyData); } - - for (int i = 0; i < cols.Count; i ++) { - // if (cols[i].Visible && cols[i].PropertyDescriptor != null) { - if (cols[i].PropertyDescriptor != null) { - firstColumnMarkedVisible = i; - break; - } - } - for (int i = cols.Count - 1; i >= 0; i --) { - // if (cols[i].Visible && cols[i].PropertyDescriptor != null) { - if (cols[i].PropertyDescriptor != null) { - lastColumnMarkedVisible = i; - break; - } - } - - if (CurrentColumn == lastColumnMarkedVisible) + } + + + if (CurrentColumn == firstColumnMarkedVisible) + { + // if the childLink is focused, then navigate within the relations + // in the row, otherwise expand the relations list for the row above + if (!gridState[GRIDSTATE_childLinkFocused]) { - if (gridState[GRIDSTATE_childLinkFocused] || (!gridState[GRIDSTATE_childLinkFocused] && (keyData & Keys.Shift) != Keys.Shift)) { - if (localRows[CurrentRow].ProcessTabKey(keyData, layout.RowHeaders, isRightToLeft())) + if (CurrentRow != 0 && (keyData & Keys.Shift) == Keys.Shift) + { + if (localRows[CurrentRow - 1].ProcessTabKey(keyData, layout.RowHeaders, isRightToLeft())) { + CurrentRow--; if (cols.Count > 0) cols[CurrentColumn].ConcedeFocus(); gridState[GRIDSTATE_childLinkFocused] = true; @@ -7916,674 +8925,735 @@ protected bool ProcessTabKey(Keys keyData) { return true; } } - - // actually, it turns out that we should leave the - // control if we are in the last row - if ((this.currentRow == this.DataGridRowsLength -1) && ((keyData & Keys.Shift) == 0)) { - - EndEdit(); - return base.ProcessDialogKey(keyData); - } } - - - if (CurrentColumn == firstColumnMarkedVisible) + else { - // if the childLink is focused, then navigate within the relations - // in the row, otherwise expand the relations list for the row above - if (!gridState[GRIDSTATE_childLinkFocused]) { - if (CurrentRow != 0 && (keyData & Keys.Shift) == Keys.Shift) - { - if (localRows[CurrentRow - 1].ProcessTabKey(keyData, layout.RowHeaders, isRightToLeft())) - { - CurrentRow --; - if (cols.Count > 0) - cols[CurrentColumn].ConcedeFocus(); - gridState[GRIDSTATE_childLinkFocused] = true; - // let the grid regain focus - // introduced because of that BeginInvoke thing in the OnLeave method.... - if (gridState[GRIDSTATE_canFocus] && CanFocus && !Focused) - this.Focus(); - return true; - } - } - } else { - if (localRows[CurrentRow].ProcessTabKey(keyData, layout.RowHeaders, isRightToLeft())) { - return true; - } else { - // we were on the firstColumn, previously the link was focused - // we have to navigate to the last column - gridState[GRIDSTATE_childLinkFocused] = false; - CurrentColumn = lastColumnMarkedVisible; - return true; - } - } - - // if we are on the first cell ( not on the addNewRow ) - // then shift - tab should move to the next control on the form - if (this.currentRow == 0 && ((keyData & Keys.Shift) == Keys.Shift)) { - EndEdit(); - return base.ProcessDialogKey(keyData); - } - } - - // move - if ((keyData & Keys.Shift) != Keys.Shift) { - // forward - if (CurrentColumn == lastColumnMarkedVisible) { - if (CurrentRow != DataGridRowsLength - 1) - CurrentColumn = firstColumnMarkedVisible; - CurrentRow = CurrentRow + 1; - } - else { - int nextCol = MoveLeftRight(cols, currentCol, true); // true for going right; - Debug.Assert(nextCol < cols.Count, "we already checked that we are not at the lastColumnMarkedVisible"); - CurrentColumn = nextCol; + if (localRows[CurrentRow].ProcessTabKey(keyData, layout.RowHeaders, isRightToLeft())) + { + return true; } - } - else { - // backward - if (CurrentColumn == firstColumnMarkedVisible) { - if (CurrentRow != 0) - { - CurrentColumn = lastColumnMarkedVisible; - } - if (!gridState[GRIDSTATE_childLinkFocused]) // - CurrentRow --; - } else if (gridState[GRIDSTATE_childLinkFocused] && CurrentColumn == lastColumnMarkedVisible) { - // part deux: when we hilite the childLink and then press shift-tab, we - // don't want to navigate at the second to last column - InvalidateRow(this.currentRow); - Edit(); - } else { - int prevCol = MoveLeftRight(cols, currentCol, false); // false for going left - Debug.Assert(prevCol != -1, "we already checked that we are not at the first columnMarked visible"); - CurrentColumn = prevCol; + else + { + // we were on the firstColumn, previously the link was focused + // we have to navigate to the last column + gridState[GRIDSTATE_childLinkFocused] = false; + CurrentColumn = lastColumnMarkedVisible; + return true; } } - - // if we got here, then invalidate childLinkFocused - // - gridState[GRIDSTATE_childLinkFocused] = false; - - // Begin another edit if we were editing before - if (wasEditing) { - ResetSelection(); - Edit(); + + // if we are on the first cell ( not on the addNewRow ) + // then shift - tab should move to the next control on the form + if (this.currentRow == 0 && ((keyData & Keys.Shift) == Keys.Shift)) + { + EndEdit(); + return base.ProcessDialogKey(keyData); } - return true; } - - virtual protected void CancelEditing() { - CancelCursorUpdate(); - // yield the escape key if there is no editing - // make the last row a DataGridAddNewRow - if (gridState[GRIDSTATE_inAddNewRow]) { - gridState[GRIDSTATE_inAddNewRow] = false; - DataGridRow[] localGridRows = this.DataGridRows; - - localGridRows[DataGridRowsLength-1] = new DataGridAddNewRow(this, this.myGridTable, DataGridRowsLength -1); - SetDataGridRows(localGridRows, DataGridRowsLength); + + // move + if ((keyData & Keys.Shift) != Keys.Shift) + { + // forward + if (CurrentColumn == lastColumnMarkedVisible) + { + if (CurrentRow != DataGridRowsLength - 1) + CurrentColumn = firstColumnMarkedVisible; + CurrentRow = CurrentRow + 1; + } + else + { + int nextCol = MoveLeftRight(cols, currentCol, true); // true for going right; + Debug.Assert(nextCol < cols.Count, "we already checked that we are not at the lastColumnMarkedVisible"); + CurrentColumn = nextCol; } } - - internal void RecalculateFonts() { - try { - linkFont = new Font(Font, FontStyle.Underline); + else + { + // backward + if (CurrentColumn == firstColumnMarkedVisible) + { + if (CurrentRow != 0) + { + CurrentColumn = lastColumnMarkedVisible; + } + if (!gridState[GRIDSTATE_childLinkFocused]) // + CurrentRow--; } - catch { + else if (gridState[GRIDSTATE_childLinkFocused] && CurrentColumn == lastColumnMarkedVisible) + { + // part deux: when we hilite the childLink and then press shift-tab, we + // don't want to navigate at the second to last column + InvalidateRow(this.currentRow); + Edit(); } - fontHeight = Font.Height; - linkFontHeight = LinkFont.Height; - captionFontHeight = CaptionFont.Height; - - if (this.myGridTable == null || this.myGridTable.IsDefault) - headerFontHeight = this.HeaderFont.Height; else - headerFontHeight = myGridTable.HeaderFont.Height; - } - - // the BackButtonClicked event: - // - /// - /// Occurs when the BackButton is clicked. - /// - [ - SRCategory(nameof(SR.CatAction)), - SRDescription(nameof(SR.DataGridBackButtonClickDescr)) - ] - public event EventHandler BackButtonClick { - add => Events.AddHandler(EVENT_BACKBUTTONCLICK, value); - remove => Events.RemoveHandler(EVENT_BACKBUTTONCLICK, value); + { + int prevCol = MoveLeftRight(cols, currentCol, false); // false for going left + Debug.Assert(prevCol != -1, "we already checked that we are not at the first columnMarked visible"); + CurrentColumn = prevCol; + } } - - // the DownButtonClick event + + // if we got here, then invalidate childLinkFocused // - /// - /// Occurs when the Down button is clicked. - /// - [ - SRCategory(nameof(SR.CatAction)), - SRDescription(nameof(SR.DataGridDownButtonClickDescr)) - ] - public event EventHandler ShowParentDetailsButtonClick { - add => Events.AddHandler(EVENT_DOWNBUTTONCLICK, value); - remove => Events.RemoveHandler(EVENT_DOWNBUTTONCLICK, value); + gridState[GRIDSTATE_childLinkFocused] = false; + + // Begin another edit if we were editing before + if (wasEditing) + { + ResetSelection(); + Edit(); } - - private void ResetMouseState() { - oldRow = -1; - gridState[GRIDSTATE_overCaption] = true; + return true; + } + + virtual protected void CancelEditing() + { + CancelCursorUpdate(); + // yield the escape key if there is no editing + // make the last row a DataGridAddNewRow + if (gridState[GRIDSTATE_inAddNewRow]) + { + gridState[GRIDSTATE_inAddNewRow] = false; + DataGridRow[] localGridRows = this.DataGridRows; + + localGridRows[DataGridRowsLength - 1] = new DataGridAddNewRow(this, this.myGridTable, DataGridRowsLength - 1); + SetDataGridRows(localGridRows, DataGridRowsLength); } - - /// - /// Turns off selection for all rows that are selected. - /// - protected void ResetSelection() { - if (numSelectedRows > 0) { - DataGridRow[] localGridRows = DataGridRows; - for (int i = 0; i < DataGridRowsLength; ++i) - if (localGridRows[i].Selected) - localGridRows[i].Selected = false; - } - numSelectedRows = 0; - lastRowSelected = -1; + } + + internal void RecalculateFonts() + { + try + { + linkFont = new Font(Font, FontStyle.Underline); } - - private void ResetParentRows() { - parentRows.Clear(); - originalState = null; - caption.BackButtonActive = caption.DownButtonActive = caption.BackButtonVisible = false; - caption.SetDownButtonDirection(!layout.ParentRowsVisible); + catch + { } - - /// - /// Re-initializes all UI related state. - /// - private void ResetUIState() { - gridState[GRIDSTATE_childLinkFocused] = false; - ResetSelection(); - ResetMouseState(); - PerformLayout(); - Invalidate(); // we want to invalidate after we set up the scrollbars - - // invalidate the horizontalscrollbar and the vertical scrollbar - // - if (horizScrollBar.Visible) - horizScrollBar.Invalidate(); - if (vertScrollBar.Visible) - vertScrollBar.Invalidate(); + fontHeight = Font.Height; + linkFontHeight = LinkFont.Height; + captionFontHeight = CaptionFont.Height; + + if (this.myGridTable == null || this.myGridTable.IsDefault) + headerFontHeight = this.HeaderFont.Height; + else + headerFontHeight = myGridTable.HeaderFont.Height; + } + + // the BackButtonClicked event: + // + /// + /// Occurs when the BackButton is clicked. + /// + [ + SRCategory(nameof(SR.CatAction)), + SRDescription(nameof(SR.DataGridBackButtonClickDescr)) + ] + public event EventHandler BackButtonClick + { + add => Events.AddHandler(EVENT_BACKBUTTONCLICK, value); + remove => Events.RemoveHandler(EVENT_BACKBUTTONCLICK, value); + } + + // the DownButtonClick event + // + /// + /// Occurs when the Down button is clicked. + /// + [ + SRCategory(nameof(SR.CatAction)), + SRDescription(nameof(SR.DataGridDownButtonClickDescr)) + ] + public event EventHandler ShowParentDetailsButtonClick + { + add => Events.AddHandler(EVENT_DOWNBUTTONCLICK, value); + remove => Events.RemoveHandler(EVENT_DOWNBUTTONCLICK, value); + } + + private void ResetMouseState() + { + oldRow = -1; + gridState[GRIDSTATE_overCaption] = true; + } + + /// + /// Turns off selection for all rows that are selected. + /// + protected void ResetSelection() + { + if (numSelectedRows > 0) + { + DataGridRow[] localGridRows = DataGridRows; + for (int i = 0; i < DataGridRowsLength; ++i) + if (localGridRows[i].Selected) + localGridRows[i].Selected = false; } - - /// - /// Scrolls the datagrid down an arbritrary number of rows. - /// - private void ScrollDown(int rows) { - //Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "DataGridScrolling: ScrollDown, rows = " + rows.ToString()); - if (rows != 0) { - ClearRegionCache(); - - // we should put "dataGridRowsLength -1" - int newFirstRow = Math.Max(0, Math.Min(firstVisibleRow + rows, this.DataGridRowsLength -1)); - int oldFirstRow = firstVisibleRow; - firstVisibleRow = newFirstRow; - vertScrollBar.Value = newFirstRow; - bool wasEditing = this.gridState[GRIDSTATE_isEditing]; - ComputeVisibleRows(); - - if (gridState[GRIDSTATE_isScrolling]) { - Edit(); - // isScrolling is set to TRUE when the user scrolls. - // once we move the edit box, we finished processing the scroll event, so set isScrolling to FALSE - // to set isScrolling to TRUE, we need another scroll event. - gridState[GRIDSTATE_isScrolling] = false; - } else { - EndEdit(); - } - - int deltaY = ComputeRowDelta(oldFirstRow, newFirstRow); - Rectangle rowsRect = layout.Data; - if (layout.RowHeadersVisible) - rowsRect = Rectangle.Union(rowsRect, layout.RowHeaders); - NativeMethods.RECT scrollArea = NativeMethods.RECT.FromXYWH(rowsRect.X, rowsRect.Y, rowsRect.Width, rowsRect.Height); - SafeNativeMethods.ScrollWindow(new HandleRef(this, Handle), 0, deltaY, ref scrollArea, ref scrollArea); - OnScroll(EventArgs.Empty); - - if (wasEditing) { - // invalidate the rowHeader for the - InvalidateRowHeader(currentRow); - } + numSelectedRows = 0; + lastRowSelected = -1; + } + + private void ResetParentRows() + { + parentRows.Clear(); + originalState = null; + caption.BackButtonActive = caption.DownButtonActive = caption.BackButtonVisible = false; + caption.SetDownButtonDirection(!layout.ParentRowsVisible); + } + + /// + /// Re-initializes all UI related state. + /// + private void ResetUIState() + { + gridState[GRIDSTATE_childLinkFocused] = false; + ResetSelection(); + ResetMouseState(); + PerformLayout(); + Invalidate(); // we want to invalidate after we set up the scrollbars + + // invalidate the horizontalscrollbar and the vertical scrollbar + // + if (horizScrollBar.Visible) + horizScrollBar.Invalidate(); + if (vertScrollBar.Visible) + vertScrollBar.Invalidate(); + } + + /// + /// Scrolls the datagrid down an arbritrary number of rows. + /// + private void ScrollDown(int rows) + { + //Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "DataGridScrolling: ScrollDown, rows = " + rows.ToString()); + if (rows != 0) + { + ClearRegionCache(); + + // we should put "dataGridRowsLength -1" + int newFirstRow = Math.Max(0, Math.Min(firstVisibleRow + rows, this.DataGridRowsLength - 1)); + int oldFirstRow = firstVisibleRow; + firstVisibleRow = newFirstRow; + vertScrollBar.Value = newFirstRow; + bool wasEditing = this.gridState[GRIDSTATE_isEditing]; + ComputeVisibleRows(); + + if (gridState[GRIDSTATE_isScrolling]) + { + Edit(); + // isScrolling is set to TRUE when the user scrolls. + // once we move the edit box, we finished processing the scroll event, so set isScrolling to FALSE + // to set isScrolling to TRUE, we need another scroll event. + gridState[GRIDSTATE_isScrolling] = false; } - } - - /// - /// Scrolls the datagrid right an arbritrary number of columns. - /// - private void ScrollRight(int columns) { - Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "DataGridScrolling: ScrollRight, columns = " + columns.ToString(CultureInfo.InvariantCulture)); - int newCol = firstVisibleCol + columns; - - GridColumnStylesCollection gridColumns = myGridTable.GridColumnStyles; - int newColOffset = 0; - int nGridCols = gridColumns.Count; - int nVisibleCols = 0; - - // if we try to scroll past the last totally visible column, - // then the toolTips will dissapear - if (this.myGridTable.IsDefault) - nVisibleCols = nGridCols; else - for (int i = 0; i < nGridCols; i++) - if (gridColumns[i].PropertyDescriptor != null) - nVisibleCols ++; - - if (this.lastTotallyVisibleCol == nVisibleCols - 1 && columns > 0 || - this.firstVisibleCol == 0 && columns < 0 && negOffset == 0) - return; - - newCol = Math.Min(newCol, nGridCols - 1); - - for (int i = 0; i < newCol; i++) - // if (gridColumns[i].Visible && gridColumns[i].PropertyDescriptor != null) - if (gridColumns[i].PropertyDescriptor != null) - newColOffset += gridColumns[i].Width; - - HorizontalOffset = newColOffset; - } - - /// - /// Scrolls a given column into visibility. - /// - private void ScrollToColumn(int targetCol) { - // do not flush the columns to the left - // so, scroll only as many columns as is necessary. - // + { + EndEdit(); + } - int dCols = targetCol - firstVisibleCol; - - if (targetCol > lastTotallyVisibleCol && lastTotallyVisibleCol != -1) - dCols = targetCol - lastTotallyVisibleCol; - - // if only part of the currentCol is visible - // then we should still scroll - if (dCols != 0 || negOffset != 0) - ScrollRight(dCols); - } - - /// - /// Selects a given row - /// - public void Select(int row) { - // - Debug.WriteLineIf(CompModSwitches.DataGridSelection.TraceVerbose, "Selecting row " + row.ToString(CultureInfo.InvariantCulture)); - DataGridRow[] localGridRows = DataGridRows; - if (!localGridRows[row].Selected) { - localGridRows[row].Selected = true; - numSelectedRows++; + int deltaY = ComputeRowDelta(oldFirstRow, newFirstRow); + Rectangle rowsRect = layout.Data; + if (layout.RowHeadersVisible) + rowsRect = Rectangle.Union(rowsRect, layout.RowHeaders); + NativeMethods.RECT scrollArea = NativeMethods.RECT.FromXYWH(rowsRect.X, rowsRect.Y, rowsRect.Width, rowsRect.Height); + SafeNativeMethods.ScrollWindow(new HandleRef(this, Handle), 0, deltaY, ref scrollArea, ref scrollArea); + OnScroll(EventArgs.Empty); + + if (wasEditing) + { + // invalidate the rowHeader for the + InvalidateRowHeader(currentRow); } - - // when selecting a row, hide the edit box - // - EndEdit(); } - - // this function will pair the listManager w/ a table from the TableStylesCollection. - // and for each column in the TableStylesCollection will pair them w/ a propertyDescriptor - // from the listManager - // - // prerequisite: the current table is either the default table, or has the same name as the - // list in the listManager. + } + + /// + /// Scrolls the datagrid right an arbritrary number of columns. + /// + private void ScrollRight(int columns) + { + Debug.WriteLineIf(CompModSwitches.DataGridScrolling.TraceVerbose, "DataGridScrolling: ScrollRight, columns = " + columns.ToString(CultureInfo.InvariantCulture)); + int newCol = firstVisibleCol + columns; + + GridColumnStylesCollection gridColumns = myGridTable.GridColumnStyles; + int newColOffset = 0; + int nGridCols = gridColumns.Count; + int nVisibleCols = 0; + + // if we try to scroll past the last totally visible column, + // then the toolTips will dissapear + if (this.myGridTable.IsDefault) + nVisibleCols = nGridCols; + else + for (int i = 0; i < nGridCols; i++) + if (gridColumns[i].PropertyDescriptor != null) + nVisibleCols++; + + if (this.lastTotallyVisibleCol == nVisibleCols - 1 && columns > 0 || + this.firstVisibleCol == 0 && columns < 0 && negOffset == 0) + return; + + newCol = Math.Min(newCol, nGridCols - 1); + + for (int i = 0; i < newCol; i++) + // if (gridColumns[i].Visible && gridColumns[i].PropertyDescriptor != null) + if (gridColumns[i].PropertyDescriptor != null) + newColOffset += gridColumns[i].Width; + + HorizontalOffset = newColOffset; + } + + /// + /// Scrolls a given column into visibility. + /// + private void ScrollToColumn(int targetCol) + { + // do not flush the columns to the left + // so, scroll only as many columns as is necessary. + // + + int dCols = targetCol - firstVisibleCol; + + if (targetCol > lastTotallyVisibleCol && lastTotallyVisibleCol != -1) + dCols = targetCol - lastTotallyVisibleCol; + + // if only part of the currentCol is visible + // then we should still scroll + if (dCols != 0 || negOffset != 0) + ScrollRight(dCols); + } + + /// + /// Selects a given row + /// + public void Select(int row) + { + // + Debug.WriteLineIf(CompModSwitches.DataGridSelection.TraceVerbose, "Selecting row " + row.ToString(CultureInfo.InvariantCulture)); + DataGridRow[] localGridRows = DataGridRows; + if (!localGridRows[row].Selected) + { + localGridRows[row].Selected = true; + numSelectedRows++; + } + + // when selecting a row, hide the edit box // - private void PairTableStylesAndGridColumns(CurrencyManager lm, DataGridTableStyle gridTable, bool forceColumnCreation) { - PropertyDescriptorCollection props = lm.GetItemProperties(); - GridColumnStylesCollection gridCols = gridTable.GridColumnStyles; - - // ]it is possible to have a dataTable w/ an empty string for a name. - if (!gridTable.IsDefault && string.Compare(lm.GetListName(), gridTable.MappingName, true, CultureInfo.InvariantCulture) == 0) { - // we will force column creation only at runtime - if (gridTable.GridColumnStyles.Count == 0 && !DesignMode) { - // we have to create some default columns for each of the propertyDescriptors - // - if (forceColumnCreation) - gridTable.SetGridColumnStylesCollection(lm); - else - gridTable.SetRelationsList(lm); - } else { - // it may the case that the user will have two lists w/ the same name. - // When switching binding between those different lists, we need to invalidate - // the propertyDescriptors from the current gridColumns - // - for (int i = 0; i < gridCols.Count; i ++) - gridCols[i].PropertyDescriptor = null; - - // pair the propertyDescriptor from each column to the actual property descriptor - // from the listManager - // - for (int i = 0; i < props.Count; i ++) { - DataGridColumnStyle col = gridCols.MapColumnStyleToPropertyName(props[i].Name); - if (col != null) { - col.PropertyDescriptor = props[i]; - } - } - // TableStyle::SetGridColumnStylesCollection will also set the - // relations list in the tableStyle. + EndEdit(); + } + + // this function will pair the listManager w/ a table from the TableStylesCollection. + // and for each column in the TableStylesCollection will pair them w/ a propertyDescriptor + // from the listManager + // + // prerequisite: the current table is either the default table, or has the same name as the + // list in the listManager. + // + private void PairTableStylesAndGridColumns(CurrencyManager lm, DataGridTableStyle gridTable, bool forceColumnCreation) + { + PropertyDescriptorCollection props = lm.GetItemProperties(); + GridColumnStylesCollection gridCols = gridTable.GridColumnStyles; + + // ]it is possible to have a dataTable w/ an empty string for a name. + if (!gridTable.IsDefault && string.Compare(lm.GetListName(), gridTable.MappingName, true, CultureInfo.InvariantCulture) == 0) + { + // we will force column creation only at runtime + if (gridTable.GridColumnStyles.Count == 0 && !DesignMode) + { + // we have to create some default columns for each of the propertyDescriptors + // + if (forceColumnCreation) + gridTable.SetGridColumnStylesCollection(lm); + else gridTable.SetRelationsList(lm); - } - } else { - // we should put an assert, that this is the default Table Style - #if DEBUG - Debug.Assert(gridTable.IsDefault, "if we don't have a match, then the dataGRid should have the default table"); - #endif // DEBUG - gridTable.SetGridColumnStylesCollection(lm); - if (gridTable.GridColumnStyles.Count > 0 && gridTable.GridColumnStyles[0].Width == -1) { - #if DEBUG - GridColumnStylesCollection cols = gridTable.GridColumnStyles; - for (int i = 0; i < cols.Count; i++) { - Debug.Assert(cols[i].Width == -1, "if one column's width is not initialized, the same should be happening for the rest of the columns"); + } + else + { + // it may the case that the user will have two lists w/ the same name. + // When switching binding between those different lists, we need to invalidate + // the propertyDescriptors from the current gridColumns + // + for (int i = 0; i < gridCols.Count; i++) + gridCols[i].PropertyDescriptor = null; + + // pair the propertyDescriptor from each column to the actual property descriptor + // from the listManager + // + for (int i = 0; i < props.Count; i++) + { + DataGridColumnStyle col = gridCols.MapColumnStyleToPropertyName(props[i].Name); + if (col != null) + { + col.PropertyDescriptor = props[i]; } - #endif // DEBUG - InitializeColumnWidths(); } + // TableStyle::SetGridColumnStylesCollection will also set the + // relations list in the tableStyle. + gridTable.SetRelationsList(lm); } } - - /// - /// Sets the current GridTable for the DataGrid. - /// This GridTable is the table which is currently - /// being displayed on the grid. - /// - internal void SetDataGridTable(DataGridTableStyle newTable, bool forceColumnCreation) + else { - // we have to listen to the dataGridTable for the propertyChangedEvent - if(this.myGridTable != null) { - // unwire the propertyChanged event - UnWireTableStylePropChanged(myGridTable); - - if (myGridTable.IsDefault) { - // reset the propertyDescriptors on the default table. - myGridTable.GridColumnStyles.ResetPropertyDescriptors(); - - // reset the relationship list from the default table - myGridTable.ResetRelationsList(); + // we should put an assert, that this is the default Table Style +#if DEBUG + Debug.Assert(gridTable.IsDefault, "if we don't have a match, then the dataGRid should have the default table"); +#endif // DEBUG + gridTable.SetGridColumnStylesCollection(lm); + if (gridTable.GridColumnStyles.Count > 0 && gridTable.GridColumnStyles[0].Width == -1) + { +#if DEBUG + GridColumnStylesCollection cols = gridTable.GridColumnStyles; + for (int i = 0; i < cols.Count; i++) + { + Debug.Assert(cols[i].Width == -1, "if one column's width is not initialized, the same should be happening for the rest of the columns"); } +#endif // DEBUG + InitializeColumnWidths(); } - - myGridTable = newTable; - - WireTableStylePropChanged(myGridTable); - - this.layout.RowHeadersVisible = newTable.IsDefault ? this.RowHeadersVisible : newTable.RowHeadersVisible; - - // we need to force the grid into the dataGridTableStyle - // this way the controls in the columns will be parented - // consider this scenario: when the user finished InitializeComponent, it added - // a bunch of tables. all of those tables will have the DataGrid property set to this - // grid. however, in InitializeComponent the tables will not have parented the - // edit controls w/ the grid. - // - // the code in DataGridTextBoxColumn already checks to see if the edits are parented - // before parenting them. - // - if (newTable != null) - newTable.DataGrid = this; - - // pair the tableStyles and GridColumns - // - if (this.listManager != null) - PairTableStylesAndGridColumns(this.listManager, this.myGridTable, forceColumnCreation); - - // reset the relations UI on the newTable - if (newTable != null) - newTable.ResetRelationsUI(); - - // set the isNavigating to false - gridState[GRIDSTATE_isNavigating] = false; - - horizScrollBar.Value = 0; - firstVisibleRow = 0; - currentCol = 0; - // if we add a tableStyle that mapps to the - // current listName, then we should set the currentRow to the - // position in the listManager - if (this.listManager == null) - currentRow = 0; - else - currentRow = this.listManager.Position == -1 ? 0 : listManager.Position; - ResetHorizontalOffset(); - negOffset = 0; - ResetUIState(); - - // check the hierarchy - checkHierarchy = true; } - - /// - /// Scrolls the data area down to make room for the parent rows - /// and lays out the different regions of the DataGrid. - /// - internal void SetParentRowsVisibility(bool visible) { - Rectangle parentRowsRect = layout.ParentRows; - Rectangle underParentRows = layout.Data; - - if (layout.RowHeadersVisible) { - underParentRows.X -= isRightToLeft() ? 0 : layout.RowHeaders.Width; - underParentRows.Width += layout.RowHeaders.Width; - } - if (layout.ColumnHeadersVisible) { - underParentRows.Y -= layout.ColumnHeaders.Height; - underParentRows.Height += layout.ColumnHeaders.Height; - } - - // hide the Edit Box - EndEdit(); - - if (visible) { - /* - RECT scrollArea = RECT.FromXYWH(underParentRows.X, underParentRows.Y, underParentRows.Width, underParentRows.Height); - - Debug.WriteLineIf(CompModSwitches.DataGridParents.TraceVerbose, "DataGridParents: Making parent rows visible."); - SafeNativeMethods.ScrollWindow(this.Handle, 0, parentRowsRect.Height, - ref scrollArea, ref scrollArea); - */ - - layout.ParentRowsVisible = true; - - PerformLayout(); - - Invalidate(); - - } - else { - // Rectangle scrollArea = Rectangle.Union(layout.ParentRows, underParentRows); - // RECT scrollRECT = RECT.FromXYWH(scrollArea.X, scrollArea.Y, scrollArea.Width, scrollArea.Height); - - NativeMethods.RECT scrollRECT = NativeMethods.RECT.FromXYWH(underParentRows.X, underParentRows.Y - layout.ParentRows.Height, underParentRows.Width, underParentRows.Height + layout.ParentRows.Height); - - SafeNativeMethods.ScrollWindow(new HandleRef(this, Handle), 0, -parentRowsRect.Height, ref scrollRECT, ref scrollRECT); - - // If the vertical scrollbar was visible before and not after - // the ScrollWindow call, then we will not get invalidated - // completely. We need to translate the visual bounds of - // the scrollbar's old location up and invalidate. - // - if (vertScrollBar.Visible) { - Rectangle fixupRect = vertScrollBar.Bounds; - fixupRect.Y -= parentRowsRect.Height; - fixupRect.Height += parentRowsRect.Height; - Invalidate(fixupRect); - } - - Debug.WriteLineIf(CompModSwitches.DataGridParents.TraceVerbose, "DataGridParents: Making parent rows invisible."); - layout.ParentRowsVisible = false; - PerformLayout(); + } + + /// + /// Sets the current GridTable for the DataGrid. + /// This GridTable is the table which is currently + /// being displayed on the grid. + /// + internal void SetDataGridTable(DataGridTableStyle newTable, bool forceColumnCreation) + { + // we have to listen to the dataGridTable for the propertyChangedEvent + if (this.myGridTable != null) + { + // unwire the propertyChanged event + UnWireTableStylePropChanged(myGridTable); + + if (myGridTable.IsDefault) + { + // reset the propertyDescriptors on the default table. + myGridTable.GridColumnStyles.ResetPropertyDescriptors(); + + // reset the relationship list from the default table + myGridTable.ResetRelationsList(); } } - - /// - /// Sets whether a row is expanded or not. - /// - private void SetRowExpansionState(int row, bool expanded) { - if (row < -1 || row > DataGridRowsLength - (policy.AllowAdd ? 2:1)) { - throw new ArgumentOutOfRangeException(nameof(row)); + + myGridTable = newTable; + + WireTableStylePropChanged(myGridTable); + + this.layout.RowHeadersVisible = newTable.IsDefault ? this.RowHeadersVisible : newTable.RowHeadersVisible; + + // we need to force the grid into the dataGridTableStyle + // this way the controls in the columns will be parented + // consider this scenario: when the user finished InitializeComponent, it added + // a bunch of tables. all of those tables will have the DataGrid property set to this + // grid. however, in InitializeComponent the tables will not have parented the + // edit controls w/ the grid. + // + // the code in DataGridTextBoxColumn already checks to see if the edits are parented + // before parenting them. + // + if (newTable != null) + newTable.DataGrid = this; + + // pair the tableStyles and GridColumns + // + if (this.listManager != null) + PairTableStylesAndGridColumns(this.listManager, this.myGridTable, forceColumnCreation); + + // reset the relations UI on the newTable + if (newTable != null) + newTable.ResetRelationsUI(); + + // set the isNavigating to false + gridState[GRIDSTATE_isNavigating] = false; + + horizScrollBar.Value = 0; + firstVisibleRow = 0; + currentCol = 0; + // if we add a tableStyle that mapps to the + // current listName, then we should set the currentRow to the + // position in the listManager + if (this.listManager == null) + currentRow = 0; + else + currentRow = this.listManager.Position == -1 ? 0 : listManager.Position; + ResetHorizontalOffset(); + negOffset = 0; + ResetUIState(); + + // check the hierarchy + checkHierarchy = true; + } + + /// + /// Scrolls the data area down to make room for the parent rows + /// and lays out the different regions of the DataGrid. + /// + internal void SetParentRowsVisibility(bool visible) + { + Rectangle parentRowsRect = layout.ParentRows; + Rectangle underParentRows = layout.Data; + + if (layout.RowHeadersVisible) + { + underParentRows.X -= isRightToLeft() ? 0 : layout.RowHeaders.Width; + underParentRows.Width += layout.RowHeaders.Width; + } + if (layout.ColumnHeadersVisible) + { + underParentRows.Y -= layout.ColumnHeaders.Height; + underParentRows.Height += layout.ColumnHeaders.Height; + } + + // hide the Edit Box + EndEdit(); + + if (visible) + { + /* + RECT scrollArea = RECT.FromXYWH(underParentRows.X, underParentRows.Y, underParentRows.Width, underParentRows.Height); + + Debug.WriteLineIf(CompModSwitches.DataGridParents.TraceVerbose, "DataGridParents: Making parent rows visible."); + SafeNativeMethods.ScrollWindow(this.Handle, 0, parentRowsRect.Height, + ref scrollArea, ref scrollArea); + */ + + layout.ParentRowsVisible = true; + + PerformLayout(); + + Invalidate(); + + } + else + { + // Rectangle scrollArea = Rectangle.Union(layout.ParentRows, underParentRows); + // RECT scrollRECT = RECT.FromXYWH(scrollArea.X, scrollArea.Y, scrollArea.Width, scrollArea.Height); + + NativeMethods.RECT scrollRECT = NativeMethods.RECT.FromXYWH(underParentRows.X, underParentRows.Y - layout.ParentRows.Height, underParentRows.Width, underParentRows.Height + layout.ParentRows.Height); + + SafeNativeMethods.ScrollWindow(new HandleRef(this, Handle), 0, -parentRowsRect.Height, ref scrollRECT, ref scrollRECT); + + // If the vertical scrollbar was visible before and not after + // the ScrollWindow call, then we will not get invalidated + // completely. We need to translate the visual bounds of + // the scrollbar's old location up and invalidate. + // + if (vertScrollBar.Visible) + { + Rectangle fixupRect = vertScrollBar.Bounds; + fixupRect.Y -= parentRowsRect.Height; + fixupRect.Height += parentRowsRect.Height; + Invalidate(fixupRect); } - - DataGridRow[] localGridRows = DataGridRows; - if (row == -1) { - DataGridRelationshipRow[] expandableRows = GetExpandableRows(); - bool repositionEditControl = false; - - for (int r = 0; r < expandableRows.Length; ++r) { - if (expandableRows[r].Expanded != expanded) - { - expandableRows[r].Expanded = expanded; - repositionEditControl = true; - } - } - if (repositionEditControl) + + Debug.WriteLineIf(CompModSwitches.DataGridParents.TraceVerbose, "DataGridParents: Making parent rows invisible."); + layout.ParentRowsVisible = false; + PerformLayout(); + } + } + + /// + /// Sets whether a row is expanded or not. + /// + private void SetRowExpansionState(int row, bool expanded) + { + if (row < -1 || row > DataGridRowsLength - (policy.AllowAdd ? 2 : 1)) + { + throw new ArgumentOutOfRangeException(nameof(row)); + } + + DataGridRow[] localGridRows = DataGridRows; + if (row == -1) + { + DataGridRelationshipRow[] expandableRows = GetExpandableRows(); + bool repositionEditControl = false; + + for (int r = 0; r < expandableRows.Length; ++r) + { + if (expandableRows[r].Expanded != expanded) { - // we need to reposition the edit control - if (gridState[GRIDSTATE_isNavigating] || gridState[GRIDSTATE_isEditing]) - { - ResetSelection(); - Edit(); - } + expandableRows[r].Expanded = expanded; + repositionEditControl = true; } } - else if (localGridRows[row] is DataGridRelationshipRow) { - DataGridRelationshipRow expandableRow = (DataGridRelationshipRow)localGridRows[row]; - if (expandableRow.Expanded != expanded) + if (repositionEditControl) + { + // we need to reposition the edit control + if (gridState[GRIDSTATE_isNavigating] || gridState[GRIDSTATE_isEditing]) { - // we need to reposition the edit control - if (gridState[GRIDSTATE_isNavigating] || gridState[GRIDSTATE_isEditing]) - { - ResetSelection(); - Edit(); - } - - expandableRow.Expanded = expanded; + ResetSelection(); + Edit(); } } } - - private void ObjectSiteChange(IContainer container, IComponent component, bool site) { - if (site) { - if (component.Site == null) { - container.Add(component); + else if (localGridRows[row] is DataGridRelationshipRow) + { + DataGridRelationshipRow expandableRow = (DataGridRelationshipRow)localGridRows[row]; + if (expandableRow.Expanded != expanded) + { + // we need to reposition the edit control + if (gridState[GRIDSTATE_isNavigating] || gridState[GRIDSTATE_isEditing]) + { + ResetSelection(); + Edit(); } + + expandableRow.Expanded = expanded; } - else { - if (component.Site != null && component.Site.Container == container) { - container.Remove(component); - } + } + } + + private void ObjectSiteChange(IContainer container, IComponent component, bool site) + { + if (site) + { + if (component.Site == null) + { + container.Add(component); } } - - public void SubObjectsSiteChange(bool site) { - DataGrid dgrid = this; - if (dgrid.DesignMode && dgrid.Site != null) { - IDesignerHost host = (IDesignerHost)dgrid.Site.GetService(typeof(IDesignerHost)); - if (host != null) { - DesignerTransaction trans = host.CreateTransaction(); - try { - IContainer container = dgrid.Site.Container; - - DataGridTableStyle[] tables = new DataGridTableStyle[dgrid.TableStyles.Count]; - dgrid.TableStyles.CopyTo(tables, 0); - - for (int i = 0; i < tables.Length; i++) { - DataGridTableStyle table = tables[i]; - ObjectSiteChange(container, table, site); - - DataGridColumnStyle[] columns = new DataGridColumnStyle[table.GridColumnStyles.Count]; - table.GridColumnStyles.CopyTo(columns, 0); - - for (int j = 0; j < columns.Length; j++) { - DataGridColumnStyle column = columns[j]; - ObjectSiteChange(container, column, site); - } + else + { + if (component.Site != null && component.Site.Container == container) + { + container.Remove(component); + } + } + } + + public void SubObjectsSiteChange(bool site) + { + DataGrid dgrid = this; + if (dgrid.DesignMode && dgrid.Site != null) + { + IDesignerHost host = (IDesignerHost)dgrid.Site.GetService(typeof(IDesignerHost)); + if (host != null) + { + DesignerTransaction trans = host.CreateTransaction(); + try + { + IContainer container = dgrid.Site.Container; + + DataGridTableStyle[] tables = new DataGridTableStyle[dgrid.TableStyles.Count]; + dgrid.TableStyles.CopyTo(tables, 0); + + for (int i = 0; i < tables.Length; i++) + { + DataGridTableStyle table = tables[i]; + ObjectSiteChange(container, table, site); + + DataGridColumnStyle[] columns = new DataGridColumnStyle[table.GridColumnStyles.Count]; + table.GridColumnStyles.CopyTo(columns, 0); + + for (int j = 0; j < columns.Length; j++) + { + DataGridColumnStyle column = columns[j]; + ObjectSiteChange(container, column, site); } } - finally { - trans.Commit(); - } + } + finally + { + trans.Commit(); } } } - - /// - /// Unselects a given row - /// - public void UnSelect(int row) { - // - Debug.WriteLineIf(CompModSwitches.DataGridSelection.TraceVerbose, "DataGridSelection: Unselecting row " + row.ToString(CultureInfo.InvariantCulture)); - DataGridRow[] localGridRows = DataGridRows; - if (localGridRows[row].Selected) { - localGridRows[row].Selected = false; - numSelectedRows--; - } + } + + /// + /// Unselects a given row + /// + public void UnSelect(int row) + { + // + Debug.WriteLineIf(CompModSwitches.DataGridSelection.TraceVerbose, "DataGridSelection: Unselecting row " + row.ToString(CultureInfo.InvariantCulture)); + DataGridRow[] localGridRows = DataGridRows; + if (localGridRows[row].Selected) + { + localGridRows[row].Selected = false; + numSelectedRows--; } - - /// - /// Asks the cursor to update. - /// - private void UpdateListManager() { - Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: Requesting EndEdit()"); - try { - if (this.listManager != null) { - EndEdit(); - this.listManager.EndCurrentEdit(); - } - } - catch { + } + + /// + /// Asks the cursor to update. + /// + private void UpdateListManager() + { + Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: Requesting EndEdit()"); + try + { + if (this.listManager != null) + { + EndEdit(); + this.listManager.EndCurrentEdit(); } } - - /// - /// Will return the string that will be used as a delimiter between columns - /// when copying rows contents to the Clipboard. - /// At the moment, return "\t" - /// - protected virtual string GetOutputTextDelimiter() { - return "\t"; + catch + { } - + } + + /// + /// Will return the string that will be used as a delimiter between columns + /// when copying rows contents to the Clipboard. + /// At the moment, return "\t" + /// + protected virtual string GetOutputTextDelimiter() + { + return "\t"; + } + + /// + /// The accessible object class for a DataGrid. The child accessible objects + /// are accessible objects corresponding to the propertygrid entries. + /// + [System.Runtime.InteropServices.ComVisible(true)] + internal class DataGridAccessibleObject : ControlAccessibleObject + { /// - /// The accessible object class for a DataGrid. The child accessible objects - /// are accessible objects corresponding to the propertygrid entries. + /// Construct a PropertyGridViewAccessibleObject /// - [System.Runtime.InteropServices.ComVisible(true)] - internal class DataGridAccessibleObject : ControlAccessibleObject { - /// - /// Construct a PropertyGridViewAccessibleObject - /// - public DataGridAccessibleObject(DataGrid owner) : base(owner) { - } - - internal DataGrid DataGrid { - get { - return (DataGrid)Owner; - } + public DataGridAccessibleObject(DataGrid owner) : base(owner) + { + } + + internal DataGrid DataGrid + { + get + { + return (DataGrid)Owner; } + } - private int ColumnCountPrivate { - get { - return ((DataGrid)Owner).myGridTable.GridColumnStyles.Count; - } + private int ColumnCountPrivate + { + get + { + return ((DataGrid)Owner).myGridTable.GridColumnStyles.Count; } + } - private int RowCountPrivate { - get { - return ((DataGrid)Owner).dataGridRows.Length; - } + private int RowCountPrivate + { + get + { + return ((DataGrid)Owner).dataGridRows.Length; } + } - public override string Name { - get { + public override string Name + { + get + { // Special case: If an explicit name has been set in the AccessibleName property, use that. // Note: Any non-null value in AccessibleName overrides the default accessible name logic, // even an empty string (this is the only way to *force* the accessible name to be blank). string name = Owner.AccessibleName; - if (name != null) { + if (name != null) + { return name; } @@ -8591,451 +9661,514 @@ public override string Name { return "DataGrid"; } - set { - // If anyone tries to set the accessible name, just cache the value in the control's - // AccessibleName property. This value will then end up overriding the normal accessible - // name logic, until such time as AccessibleName is set back to null. - Owner.AccessibleName = value; + set + { + // If anyone tries to set the accessible name, just cache the value in the control's + // AccessibleName property. This value will then end up overriding the normal accessible + // name logic, until such time as AccessibleName is set back to null. + Owner.AccessibleName = value; + } + } + + public override AccessibleRole Role + { + get + { + AccessibleRole role = Owner.AccessibleRole; + if (role != AccessibleRole.Default) + { + return role; + } + return AccessibleRole.Table; + } + } + public override AccessibleObject GetChild(int index) + { + DataGrid dataGrid = (DataGrid)Owner; + + int cols = ColumnCountPrivate; + int rows = RowCountPrivate; + + if (dataGrid.dataGridRows == null) + { + dataGrid.CreateDataGridRows(); } - } - public override AccessibleRole Role { - get { - AccessibleRole role = Owner.AccessibleRole; - if (role != AccessibleRole.Default) { - return role; - } - return AccessibleRole.Table; - } + if (index < 1) + { + return dataGrid.ParentRowsAccessibleObject; } - public override AccessibleObject GetChild(int index) { - DataGrid dataGrid = (DataGrid)Owner; - - int cols = ColumnCountPrivate; - int rows = RowCountPrivate; - - if (dataGrid.dataGridRows == null) { - dataGrid.CreateDataGridRows(); - } - - if (index < 1) { - return dataGrid.ParentRowsAccessibleObject; + else + { + index -= 1; + if (index < cols) + { + return dataGrid.myGridTable.GridColumnStyles[index].HeaderAccessibleObject; } - else { - index -= 1; - if (index < cols) { - return dataGrid.myGridTable.GridColumnStyles[index].HeaderAccessibleObject; + else + { + index -= cols; + + if (index < rows) + { + Debug.Assert(dataGrid.dataGridRows[index].RowNumber == index, "Row number is wrong!"); + return dataGrid.dataGridRows[index].AccessibleObject; } - else { - index -= cols; - - if (index < rows) { - Debug.Assert(dataGrid.dataGridRows[index].RowNumber == index, "Row number is wrong!"); - return dataGrid.dataGridRows[index].AccessibleObject; - } - else { - index -= rows; + else + { + index -= rows; - if (dataGrid.horizScrollBar.Visible) { - if (index == 0) { - return dataGrid.horizScrollBar.AccessibilityObject; - } - index --; + if (dataGrid.horizScrollBar.Visible) + { + if (index == 0) + { + return dataGrid.horizScrollBar.AccessibilityObject; } + index--; + } - if (dataGrid.vertScrollBar.Visible) { - if (index == 0) { - return dataGrid.vertScrollBar.AccessibilityObject; - } - index --; + if (dataGrid.vertScrollBar.Visible) + { + if (index == 0) + { + return dataGrid.vertScrollBar.AccessibilityObject; } + index--; + } - int colCount = dataGrid.myGridTable.GridColumnStyles.Count; - int rowCount = dataGrid.dataGridRows.Length; - int currentRow = index / colCount; - int currentCol = index % colCount; + int colCount = dataGrid.myGridTable.GridColumnStyles.Count; + int rowCount = dataGrid.dataGridRows.Length; + int currentRow = index / colCount; + int currentCol = index % colCount; - if (currentRow < dataGrid.dataGridRows.Length && currentCol < dataGrid.myGridTable.GridColumnStyles.Count) { - return dataGrid.dataGridRows[currentRow].AccessibleObject.GetChild(currentCol); - } + if (currentRow < dataGrid.dataGridRows.Length && currentCol < dataGrid.myGridTable.GridColumnStyles.Count) + { + return dataGrid.dataGridRows[currentRow].AccessibleObject.GetChild(currentCol); } } } - - return null; } - - public override int GetChildCount() { - int n = 1 + ColumnCountPrivate + ((DataGrid)Owner).DataGridRowsLength; - if (DataGrid.horizScrollBar.Visible) { - n++; - } - if (DataGrid.vertScrollBar.Visible) { - n++; - } - n += this.DataGrid.DataGridRows.Length * this.DataGrid.myGridTable.GridColumnStyles.Count; - return n; + + return null; + } + + public override int GetChildCount() + { + int n = 1 + ColumnCountPrivate + ((DataGrid)Owner).DataGridRowsLength; + if (DataGrid.horizScrollBar.Visible) + { + n++; } - - public override AccessibleObject GetFocused() { - if (DataGrid.Focused) { - return GetSelected(); - } - - return null; + if (DataGrid.vertScrollBar.Visible) + { + n++; } - - public override AccessibleObject GetSelected() { - if (this.DataGrid.DataGridRows.Length == 0 || this.DataGrid.myGridTable.GridColumnStyles.Count == 0) { - return null; - } + n += this.DataGrid.DataGridRows.Length * this.DataGrid.myGridTable.GridColumnStyles.Count; + return n; + } - DataGridCell cell = DataGrid.CurrentCell; - return GetChild(1 + ColumnCountPrivate + cell.RowNumber).GetChild(cell.ColumnNumber); + public override AccessibleObject GetFocused() + { + if (DataGrid.Focused) + { + return GetSelected(); } - - public override AccessibleObject HitTest(int x, int y) { - Point client = DataGrid.PointToClient(new Point(x, y)); - HitTestInfo hti = DataGrid.HitTest(client.X, client.Y); - - switch (hti.Type) { - case HitTestType.RowHeader: - return GetChild(1 + ColumnCountPrivate + hti.Row); - case HitTestType.Cell: - return GetChild(1 + ColumnCountPrivate + hti.Row).GetChild(hti.Column); - case HitTestType.ColumnHeader: - return GetChild(1 + hti.Column); - case HitTestType.ParentRows: - return DataGrid.ParentRowsAccessibleObject; - case HitTestType.None: - case HitTestType.ColumnResize: - case HitTestType.RowResize: - case HitTestType.Caption: - break; - } - + + return null; + } + + public override AccessibleObject GetSelected() + { + if (this.DataGrid.DataGridRows.Length == 0 || this.DataGrid.myGridTable.GridColumnStyles.Count == 0) + { return null; } - public override AccessibleObject Navigate(AccessibleNavigation navdir) { - // We're only handling FirstChild and LastChild here - if (GetChildCount() > 0) { - switch(navdir) { - case AccessibleNavigation.FirstChild: - return GetChild(0); - case AccessibleNavigation.LastChild: - return GetChild(GetChildCount() - 1); - } - } - - return null; // Perform default behavior - } + DataGridCell cell = DataGrid.CurrentCell; + return GetChild(1 + ColumnCountPrivate + cell.RowNumber).GetChild(cell.ColumnNumber); } - - - - // - // This simple data structure holds all of the layout information - // for the DataGrid. - // - internal class LayoutData { - internal bool dirty = true; - // region inside the Control's borders. - public Rectangle Inside = Rectangle.Empty; - - public Rectangle RowHeaders = Rectangle.Empty; - - public Rectangle TopLeftHeader = Rectangle.Empty; - public Rectangle ColumnHeaders = Rectangle.Empty; - public Rectangle Data = Rectangle.Empty; - - public Rectangle Caption = Rectangle.Empty; - public Rectangle ParentRows = Rectangle.Empty; - - public Rectangle ResizeBoxRect = Rectangle.Empty; - - public bool ColumnHeadersVisible; - public bool RowHeadersVisible; - public bool CaptionVisible; - public bool ParentRowsVisible; - - // used for resizing. - public Rectangle ClientRectangle = Rectangle.Empty; - - public LayoutData() { - } - - public LayoutData(LayoutData src) { - GrabLayout(src); - } - - private void GrabLayout(LayoutData src) { - this.Inside = src.Inside; - this.TopLeftHeader = src.TopLeftHeader; - this.ColumnHeaders = src.ColumnHeaders; - this.RowHeaders = src.RowHeaders; - this.Data = src.Data; - this.Caption = src.Caption; - this.ParentRows = src.ParentRows; - this.ResizeBoxRect = src.ResizeBoxRect; - this.ColumnHeadersVisible = src.ColumnHeadersVisible; - this.RowHeadersVisible = src.RowHeadersVisible; - this.CaptionVisible = src.CaptionVisible; - this.ParentRowsVisible = src.ParentRowsVisible; - this.ClientRectangle = src.ClientRectangle; + + public override AccessibleObject HitTest(int x, int y) + { + Point client = DataGrid.PointToClient(new Point(x, y)); + HitTestInfo hti = DataGrid.HitTest(client.X, client.Y); + + switch (hti.Type) + { + case HitTestType.RowHeader: + return GetChild(1 + ColumnCountPrivate + hti.Row); + case HitTestType.Cell: + return GetChild(1 + ColumnCountPrivate + hti.Row).GetChild(hti.Column); + case HitTestType.ColumnHeader: + return GetChild(1 + hti.Column); + case HitTestType.ParentRows: + return DataGrid.ParentRowsAccessibleObject; + case HitTestType.None: + case HitTestType.ColumnResize: + case HitTestType.RowResize: + case HitTestType.Caption: + break; } - - public override string ToString() { - StringBuilder sb = new StringBuilder(200); - sb.Append(base.ToString()); - sb.Append(" { \n"); - sb.Append("Inside = "); - sb.Append(Inside.ToString()); - sb.Append('\n'); - sb.Append("TopLeftHeader = "); - sb.Append(TopLeftHeader.ToString()); - sb.Append('\n'); - sb.Append("ColumnHeaders = "); - sb.Append(ColumnHeaders.ToString()); - sb.Append('\n'); - sb.Append("RowHeaders = "); - sb.Append(RowHeaders.ToString()); - sb.Append('\n'); - sb.Append("Data = "); - sb.Append(Data.ToString()); - sb.Append('\n'); - sb.Append("Caption = "); - sb.Append(Caption.ToString()); - sb.Append('\n'); - sb.Append("ParentRows = "); - sb.Append(ParentRows.ToString()); - sb.Append('\n'); - sb.Append("ResizeBoxRect = "); - sb.Append(ResizeBoxRect.ToString()); - sb.Append('\n'); - sb.Append("ColumnHeadersVisible = "); - sb.Append(ColumnHeadersVisible.ToString()); - sb.Append('\n'); - sb.Append("RowHeadersVisible = "); - sb.Append(RowHeadersVisible.ToString()); - sb.Append('\n'); - sb.Append("CaptionVisible = "); - sb.Append(CaptionVisible.ToString()); - sb.Append('\n'); - sb.Append("ParentRowsVisible = "); - sb.Append(ParentRowsVisible.ToString()); - sb.Append('\n'); - sb.Append("ClientRectangle = "); - sb.Append(ClientRectangle.ToString()); - sb.Append(" } "); - return sb.ToString(); + + return null; + } + + public override AccessibleObject Navigate(AccessibleNavigation navdir) + { + // We're only handling FirstChild and LastChild here + if (GetChildCount() > 0) + { + switch (navdir) + { + case AccessibleNavigation.FirstChild: + return GetChild(0); + case AccessibleNavigation.LastChild: + return GetChild(GetChildCount() - 1); + } } + + return null; // Perform default behavior } - + } + + + + // + // This simple data structure holds all of the layout information + // for the DataGrid. + // + internal class LayoutData + { + internal bool dirty = true; + // region inside the Control's borders. + public Rectangle Inside = Rectangle.Empty; + + public Rectangle RowHeaders = Rectangle.Empty; + + public Rectangle TopLeftHeader = Rectangle.Empty; + public Rectangle ColumnHeaders = Rectangle.Empty; + public Rectangle Data = Rectangle.Empty; + + public Rectangle Caption = Rectangle.Empty; + public Rectangle ParentRows = Rectangle.Empty; + + public Rectangle ResizeBoxRect = Rectangle.Empty; + + public bool ColumnHeadersVisible; + public bool RowHeadersVisible; + public bool CaptionVisible; + public bool ParentRowsVisible; + + // used for resizing. + public Rectangle ClientRectangle = Rectangle.Empty; + + public LayoutData() + { + } + + public LayoutData(LayoutData src) + { + GrabLayout(src); + } + + private void GrabLayout(LayoutData src) + { + this.Inside = src.Inside; + this.TopLeftHeader = src.TopLeftHeader; + this.ColumnHeaders = src.ColumnHeaders; + this.RowHeaders = src.RowHeaders; + this.Data = src.Data; + this.Caption = src.Caption; + this.ParentRows = src.ParentRows; + this.ResizeBoxRect = src.ResizeBoxRect; + this.ColumnHeadersVisible = src.ColumnHeadersVisible; + this.RowHeadersVisible = src.RowHeadersVisible; + this.CaptionVisible = src.CaptionVisible; + this.ParentRowsVisible = src.ParentRowsVisible; + this.ClientRectangle = src.ClientRectangle; + } + + public override string ToString() + { + StringBuilder sb = new StringBuilder(200); + sb.Append(base.ToString()); + sb.Append(" { \n"); + sb.Append("Inside = "); + sb.Append(Inside.ToString()); + sb.Append('\n'); + sb.Append("TopLeftHeader = "); + sb.Append(TopLeftHeader.ToString()); + sb.Append('\n'); + sb.Append("ColumnHeaders = "); + sb.Append(ColumnHeaders.ToString()); + sb.Append('\n'); + sb.Append("RowHeaders = "); + sb.Append(RowHeaders.ToString()); + sb.Append('\n'); + sb.Append("Data = "); + sb.Append(Data.ToString()); + sb.Append('\n'); + sb.Append("Caption = "); + sb.Append(Caption.ToString()); + sb.Append('\n'); + sb.Append("ParentRows = "); + sb.Append(ParentRows.ToString()); + sb.Append('\n'); + sb.Append("ResizeBoxRect = "); + sb.Append(ResizeBoxRect.ToString()); + sb.Append('\n'); + sb.Append("ColumnHeadersVisible = "); + sb.Append(ColumnHeadersVisible.ToString()); + sb.Append('\n'); + sb.Append("RowHeadersVisible = "); + sb.Append(RowHeadersVisible.ToString()); + sb.Append('\n'); + sb.Append("CaptionVisible = "); + sb.Append(CaptionVisible.ToString()); + sb.Append('\n'); + sb.Append("ParentRowsVisible = "); + sb.Append(ParentRowsVisible.ToString()); + sb.Append('\n'); + sb.Append("ClientRectangle = "); + sb.Append(ClientRectangle.ToString()); + sb.Append(" } "); + return sb.ToString(); + } + } + + /// + /// Contains information + /// about the part of the control the user + /// has clicked. This class cannot be inherited. + /// + public sealed class HitTestInfo + { + internal HitTestType type = HitTestType.None; + + internal int row; + internal int col; + /// - /// Contains information - /// about the part of the control the user - /// has clicked. This class cannot be inherited. + /// Allows the object to inform you the + /// extent of the grid. /// - public sealed class HitTestInfo { - internal HitTestType type = HitTestType.None; - - internal int row; - internal int col; - - /// - /// Allows the object to inform you the - /// extent of the grid. - /// - [ - SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes") // DataGrid.HitTestInfo type is - // actually immutable. - ] - public static readonly HitTestInfo Nowhere = new HitTestInfo(); - - internal HitTestInfo() { - type = (HitTestType)0; - row = col = -1; - } - - internal HitTestInfo(HitTestType type) { - this.type = type; - row = col = -1; - } - - /// - /// Gets the number of the clicked column. - /// - public int Column { - get { - return col; - } - } - - /// - /// Gets the - /// number of the clicked row. - /// - public int Row { - get { - return row; - } - } - - /// - /// Gets the part of the control, other than the row or column, that was - /// clicked. - /// - public HitTestType Type { - get { - return type; - } + [ + SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes") // DataGrid.HitTestInfo type is + // actually immutable. + ] + public static readonly HitTestInfo Nowhere = new HitTestInfo(); + + internal HitTestInfo() + { + type = (HitTestType)0; + row = col = -1; + } + + internal HitTestInfo(HitTestType type) + { + this.type = type; + row = col = -1; + } + + /// + /// Gets the number of the clicked column. + /// + public int Column + { + get + { + return col; } - - /// - /// Indicates whether two objects are identical. - /// - public override bool Equals(object value) { - if (value is HitTestInfo) { - HitTestInfo ci =(HitTestInfo) value; - return(type == ci.type && - row == ci.row && - col == ci.col); - } - return false; + } + + /// + /// Gets the + /// number of the clicked row. + /// + public int Row + { + get + { + return row; } - - /// - /// Gets the hash code for the instance. - /// - public override int GetHashCode() { - return(int)type +(row << 8) +(col << 16); + } + + /// + /// Gets the part of the control, other than the row or column, that was + /// clicked. + /// + public HitTestType Type + { + get + { + return type; } - - /// - /// Gets the type, row number, and column number. - /// - public override string ToString() { - return "{ " + ((type).ToString()) + "," + row.ToString(CultureInfo.InvariantCulture) + "," + col.ToString(CultureInfo.InvariantCulture) + "}"; + } + + /// + /// Indicates whether two objects are identical. + /// + public override bool Equals(object value) + { + if (value is HitTestInfo) + { + HitTestInfo ci = (HitTestInfo)value; + return (type == ci.type && + row == ci.row && + col == ci.col); } + return false; } - + /// - /// Specifies the part of the - /// control the user has clicked.< + /// Gets the hash code for the instance. /// - [Flags] - public enum HitTestType - { - None = 0x00000000, - Cell = 0x00000001, - ColumnHeader = 0x00000002, - RowHeader = 0x00000004, - ColumnResize = 0x00000008, - RowResize = 0x00000010, - Caption = 0x00000020, - ParentRows = 0x00000040 + public override int GetHashCode() + { + return (int)type + (row << 8) + (col << 16); } - + /// - /// Holds policy information for what the grid can and cannot do. + /// Gets the type, row number, and column number. /// - private class Policy { - - private bool allowAdd = true; - private bool allowEdit = true; - private bool allowRemove = true; - - public Policy() { - } - - public bool AllowAdd { - get { - return allowAdd; - } - set { - if (allowAdd != value) { - allowAdd = value; - } - } + public override string ToString() + { + return "{ " + ((type).ToString()) + "," + row.ToString(CultureInfo.InvariantCulture) + "," + col.ToString(CultureInfo.InvariantCulture) + "}"; + } + } + + /// + /// Specifies the part of the + /// control the user has clicked.< + /// + [Flags] + public enum HitTestType + { + None = 0x00000000, + Cell = 0x00000001, + ColumnHeader = 0x00000002, + RowHeader = 0x00000004, + ColumnResize = 0x00000008, + RowResize = 0x00000010, + Caption = 0x00000020, + ParentRows = 0x00000040 + } + + /// + /// Holds policy information for what the grid can and cannot do. + /// + private class Policy + { + + private bool allowAdd = true; + private bool allowEdit = true; + private bool allowRemove = true; + + public Policy() + { + } + + public bool AllowAdd + { + get + { + return allowAdd; } - - public bool AllowEdit { - get { - return allowEdit; - } - set { - if (allowEdit != value) { - allowEdit = value; - } + set + { + if (allowAdd != value) + { + allowAdd = value; } } - - public bool AllowRemove { - get { - return allowRemove; - } - set { - if (allowRemove != value) { - allowRemove = value; - } - } + } + + public bool AllowEdit + { + get + { + return allowEdit; } - - // returns true if the UI needs to be updated (here because addnew has changed) - public bool UpdatePolicy(CurrencyManager listManager, bool gridReadOnly) - { - bool change = false; - // only IBindingList can have an AddNewRow - IBindingList bl = listManager == null ? null : listManager.List as IBindingList; - if (listManager == null) { - if (!allowAdd) - change = true; - allowAdd = allowEdit = allowRemove = true; - } - else { - if (AllowAdd != listManager.AllowAdd && !gridReadOnly) - change = true; - AllowAdd= listManager.AllowAdd && !gridReadOnly && bl != null && bl.SupportsChangeNotification; - AllowEdit= listManager.AllowEdit && !gridReadOnly; - AllowRemove = listManager.AllowRemove && !gridReadOnly && bl != null && bl.SupportsChangeNotification; // + set + { + if (allowEdit != value) + { + allowEdit = value; } - return change; } } - - // - // Given the x coordinate and the Width of rectangle R1 inside rectangle rect, - // this function returns the x coordinate of the rectangle that - // corresponds to the Bi-Di transformation - // - private int MirrorRectangle(Rectangle R1, Rectangle rect, bool rightToLeft) + + public bool AllowRemove { - if (rightToLeft) - return rect.Right + rect.X - R1.Right; - else - return R1.X; + get + { + return allowRemove; + } + set + { + if (allowRemove != value) + { + allowRemove = value; + } + } } - - // - // Given the x coordinate of a point inside rectangle rect, - // this function returns the x coordinate of the point that - // corresponds to the Bi-Di transformation - // - private int MirrorPoint(int x, Rectangle rect, bool rightToLeft) + + // returns true if the UI needs to be updated (here because addnew has changed) + public bool UpdatePolicy(CurrencyManager listManager, bool gridReadOnly) { - if (rightToLeft) - return rect.Right + rect.X - x; + bool change = false; + // only IBindingList can have an AddNewRow + IBindingList bl = listManager == null ? null : listManager.List as IBindingList; + if (listManager == null) + { + if (!allowAdd) + change = true; + allowAdd = allowEdit = allowRemove = true; + } else - return x; - } - - // This function will return true if the RightToLeft property of the dataGrid is - // set to YES - private bool isRightToLeft() - { - return ( RightToLeft == RightToLeft.Yes); + { + if (AllowAdd != listManager.AllowAdd && !gridReadOnly) + change = true; + AllowAdd = listManager.AllowAdd && !gridReadOnly && bl != null && bl.SupportsChangeNotification; + AllowEdit = listManager.AllowEdit && !gridReadOnly; + AllowRemove = listManager.AllowRemove && !gridReadOnly && bl != null && bl.SupportsChangeNotification; // + } + return change; } } + + // + // Given the x coordinate and the Width of rectangle R1 inside rectangle rect, + // this function returns the x coordinate of the rectangle that + // corresponds to the Bi-Di transformation + // + private int MirrorRectangle(Rectangle R1, Rectangle rect, bool rightToLeft) + { + if (rightToLeft) + return rect.Right + rect.X - R1.Right; + else + return R1.X; + } + + // + // Given the x coordinate of a point inside rectangle rect, + // this function returns the x coordinate of the point that + // corresponds to the Bi-Di transformation + // + private int MirrorPoint(int x, Rectangle rect, bool rightToLeft) + { + if (rightToLeft) + return rect.Right + rect.X - x; + else + return x; + } + + // This function will return true if the RightToLeft property of the dataGrid is + // set to YES + private bool isRightToLeft() + { + return (RightToLeft == RightToLeft.Yes); + } } +} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridAddNewRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridAddNewRow.cs index 39708939773..5216ec49cde 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridAddNewRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridAddNewRow.cs @@ -2,12 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; using System; - + using System.Windows.Forms; using System.ComponentModel; using System.Drawing; @@ -17,12 +18,14 @@ namespace System.Windows.Forms { /// This class fully encapsulates the painting logic for an addnew row /// appearing in a DataGrid. /// - internal class DataGridAddNewRow : DataGridRow { + internal class DataGridAddNewRow : DataGridRow + { private bool dataBound = false; public DataGridAddNewRow(DataGrid dGrid, DataGridTableStyle gridTable, int rowNum) - : base(dGrid, gridTable, rowNum) { + : base(dGrid, gridTable, rowNum) + { } // =------------------------------------------------------------------ @@ -36,22 +39,28 @@ public DataGridAddNewRow(DataGrid dGrid, DataGridTableStyle gridTable, int rowNu /// row contents and permit editing, etc because a DataRecord /// exists in the cursor that created this row. /// - public bool DataBound { - get { + public bool DataBound + { + get + { return dataBound; } - set { + set + { dataBound = value; } } - public override void OnEdit() { - if (!DataBound) { + public override void OnEdit() + { + if (!DataBound) + { DataGrid.AddNewRow(); } } - public override void OnRowLeave() { + public override void OnRowLeave() + { if (DataBound) DataBound = false; } @@ -82,7 +91,8 @@ public override int Paint(Graphics g, Rectangle trueRowBounds, int firstVisibleColumn, int columnCount, - bool alignToRight) { + bool alignToRight) + { Rectangle dataBounds = bounds; DataGridLineStyle gridStyle; if (this.dgTable.IsDefault) @@ -99,12 +109,15 @@ public override int Paint(Graphics g, } protected override void PaintCellContents(Graphics g, Rectangle cellBounds, DataGridColumnStyle column, - Brush backBr, Brush foreBrush, bool alignToRight) { - if (DataBound) { + Brush backBr, Brush foreBrush, bool alignToRight) + { + if (DataBound) + { CurrencyManager listManager = DataGrid.ListManager; column.Paint(g, cellBounds, listManager, this.RowNumber, alignToRight); } - else { + else + { base.PaintCellContents(g, cellBounds, column, backBr, foreBrush, alignToRight); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs index 9c6ec0bc48d..aa40a7de2f2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs @@ -2,12 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; using System; - + using System.Windows.Forms; using System.ComponentModel; using System.Drawing; @@ -18,36 +19,37 @@ namespace System.Windows.Forms { /// which each cell contains a check box for representing /// a boolean value. /// - public class DataGridBoolColumn : DataGridColumnStyle { + public class DataGridBoolColumn : DataGridColumnStyle + { private static readonly int idealCheckSize = 14; private bool isEditing = false; private bool isSelected = false; private bool allowNull = true; - private int editingRow = -1; + private int editingRow = -1; private object currentValue = Convert.DBNull; - + private object trueValue = true; private object falseValue = false; private object nullValue = Convert.DBNull; - private static readonly object EventTrueValue = new object(); - private static readonly object EventFalseValue = new object(); - private static readonly object EventAllowNull = new object(); - + private static readonly object EventTrueValue = new object(); + private static readonly object EventFalseValue = new object(); + private static readonly object EventAllowNull = new object(); + /// /// Initializes a new instance of the class. /// - public DataGridBoolColumn() : base() {} + public DataGridBoolColumn() : base() { } /// /// Initializes a new instance of a with the specified . /// public DataGridBoolColumn(PropertyDescriptor prop) - : base(prop) {} + : base(prop) { } public DataGridBoolColumn(PropertyDescriptor prop, bool isDefault) - : base(prop, isDefault){} + : base(prop, isDefault) { } /// /// Gets or sets the actual value used when setting the @@ -55,12 +57,16 @@ public DataGridBoolColumn(PropertyDescriptor prop, bool isDefault) /// [TypeConverterAttribute(typeof(StringConverter)), DefaultValue(true)] - public object TrueValue { - get { + public object TrueValue + { + get + { return trueValue; } - set { - if (!trueValue.Equals(value)) { + set + { + if (!trueValue.Equals(value)) + { this.trueValue = value; OnTrueValueChanged(EventArgs.Empty); Invalidate(); @@ -68,52 +74,62 @@ public object TrueValue { } } - public event EventHandler TrueValueChanged { + public event EventHandler TrueValueChanged + { add => Events.AddHandler(EventTrueValue, value); remove => Events.RemoveHandler(EventTrueValue, value); } - + /// /// Gets or sets the actual value used when setting the value of the column to /// . /// [TypeConverterAttribute(typeof(StringConverter)), DefaultValue(false)] - public object FalseValue { - get { + public object FalseValue + { + get + { return falseValue; } - set { - if (!falseValue.Equals(value)) { + set + { + if (!falseValue.Equals(value)) + { this.falseValue = value; OnFalseValueChanged(EventArgs.Empty); Invalidate(); } } } - - public event EventHandler FalseValueChanged { + + public event EventHandler FalseValueChanged + { add => Events.AddHandler(EventFalseValue, value); remove => Events.RemoveHandler(EventFalseValue, value); } - + /// /// Gets or sets the actual value used when setting the value of the column to /// . /// [TypeConverterAttribute(typeof(StringConverter))] - public object NullValue { - get { + public object NullValue + { + get + { return nullValue; } - set { - if (!nullValue.Equals(value)) { + set + { + if (!nullValue.Equals(value)) + { this.nullValue = value; OnFalseValueChanged(EventArgs.Empty); Invalidate(); } } } - + // =------------------------------------------------------------------ // = Methods // =------------------------------------------------------------------ @@ -122,21 +138,23 @@ public object NullValue { // so there is no data to be pushed back into the backEnd. // make isEditing false so that in the Commit call we do not do any work. // - protected internal override void ConcedeFocus() { + protected internal override void ConcedeFocus() + { base.ConcedeFocus(); this.isSelected = false; this.isEditing = false; } - private Rectangle GetCheckBoxBounds(Rectangle bounds, bool alignToRight) { + private Rectangle GetCheckBoxBounds(Rectangle bounds, bool alignToRight) + { if (alignToRight) - return new Rectangle(bounds.X +((bounds.Width - idealCheckSize) /2), - bounds.Y +((bounds.Height - idealCheckSize) / 2), + return new Rectangle(bounds.X + ((bounds.Width - idealCheckSize) / 2), + bounds.Y + ((bounds.Height - idealCheckSize) / 2), bounds.Width < idealCheckSize ? bounds.Width : idealCheckSize, idealCheckSize); else - return new Rectangle(Math.Max(0,bounds.X +((bounds.Width - idealCheckSize) /2)), - Math.Max(0,bounds.Y +((bounds.Height - idealCheckSize) / 2)), + return new Rectangle(Math.Max(0, bounds.X + ((bounds.Width - idealCheckSize) / 2)), + Math.Max(0, bounds.Y + ((bounds.Height - idealCheckSize) / 2)), bounds.Width < idealCheckSize ? bounds.Width : idealCheckSize, idealCheckSize); } @@ -144,21 +162,26 @@ private Rectangle GetCheckBoxBounds(Rectangle bounds, bool alignToRight) { /// /// Gets the value at the specified row. /// - protected internal override object GetColumnValueAtRow(CurrencyManager lm, int row) { + protected internal override object GetColumnValueAtRow(CurrencyManager lm, int row) + { object baseValue = base.GetColumnValueAtRow(lm, row); object value = Convert.DBNull; - if (baseValue.Equals(trueValue)) { + if (baseValue.Equals(trueValue)) + { value = true; } - else if (baseValue.Equals(falseValue)) { + else if (baseValue.Equals(falseValue)) + { value = false; } return value; } - private bool IsReadOnly() { + private bool IsReadOnly() + { bool ret = this.ReadOnly; - if (this.DataGridTableStyle != null) { + if (this.DataGridTableStyle != null) + { ret = ret || this.DataGridTableStyle.ReadOnly; if (this.DataGridTableStyle.DataGrid != null) ret = ret || this.DataGridTableStyle.DataGrid.ReadOnly; @@ -169,35 +192,41 @@ private bool IsReadOnly() { /// /// Sets the value a a specified row. /// - protected internal override void SetColumnValueAtRow(CurrencyManager lm, int row, object value) { + protected internal override void SetColumnValueAtRow(CurrencyManager lm, int row, object value) + { object baseValue = null; - if (true.Equals(value)) { + if (true.Equals(value)) + { baseValue = TrueValue; } - else if (false.Equals(value)) { + else if (false.Equals(value)) + { baseValue = FalseValue; } - else if (Convert.IsDBNull(value)) { + else if (Convert.IsDBNull(value)) + { baseValue = NullValue; } currentValue = baseValue; base.SetColumnValueAtRow(lm, row, baseValue); } - + /// /// Gets the optimum width and height of a cell given /// a specific value to contain. /// - protected internal override Size GetPreferredSize(Graphics g, object value) { - return new Size(idealCheckSize+2, idealCheckSize+2); + protected internal override Size GetPreferredSize(Graphics g, object value) + { + return new Size(idealCheckSize + 2, idealCheckSize + 2); } /// /// Gets /// the height of a cell in a column. /// - protected internal override int GetMinimumHeight() { - return idealCheckSize+2; + protected internal override int GetMinimumHeight() + { + return idealCheckSize + 2; } /// @@ -215,7 +244,8 @@ protected internal override int GetPreferredHeight(Graphics g, object value) /// Initiates a request to interrupt an edit procedure. /// /// - protected internal override void Abort(int rowNum) { + protected internal override void Abort(int rowNum) + { isSelected = false; isEditing = false; Invalidate(); @@ -227,7 +257,8 @@ protected internal override void Abort(int rowNum) { /// Initiates a request to complete an editing procedure. /// /// - protected internal override bool Commit(CurrencyManager dataSource, int rowNum) { + protected internal override bool Commit(CurrencyManager dataSource, int rowNum) + { isSelected = false; // always invalidate Invalidate(); @@ -260,7 +291,8 @@ protected internal override void Edit(CurrencyManager source, if (!grid.Focused) grid.Focus(); - if (!readOnly && !IsReadOnly()) { + if (!readOnly && !IsReadOnly()) + { editingRow = rowNum; currentValue = GetColumnValueAtRow(source, rowNum); } @@ -274,9 +306,12 @@ protected internal override void Edit(CurrencyManager source, /// process it. /// /// - internal override bool KeyPress(int rowNum, Keys keyData) { - if (isSelected && editingRow == rowNum && !IsReadOnly()) { - if ((keyData & Keys.KeyCode) == Keys.Space) { + internal override bool KeyPress(int rowNum, Keys keyData) + { + if (isSelected && editingRow == rowNum && !IsReadOnly()) + { + if ((keyData & Keys.KeyCode) == Keys.Space) + { ToggleValue(); Invalidate(); return true; @@ -291,9 +326,11 @@ internal override bool KeyPress(int rowNum, Keys keyData) { /// the specified x and y coordinates. /// /// - internal override bool MouseDown(int rowNum, int x, int y) { + internal override bool MouseDown(int rowNum, int x, int y) + { base.MouseDown(rowNum, x, y); - if (isSelected && editingRow == rowNum && !IsReadOnly()) { + if (isSelected && editingRow == rowNum && !IsReadOnly()) + { ToggleValue(); Invalidate(); return true; @@ -301,17 +338,20 @@ internal override bool MouseDown(int rowNum, int x, int y) { return false; } - private void OnTrueValueChanged(EventArgs e) { + private void OnTrueValueChanged(EventArgs e) + { EventHandler eh = this.Events[EventTrueValue] as EventHandler; if (eh != null) eh(this, e); } - private void OnFalseValueChanged(EventArgs e) { + private void OnFalseValueChanged(EventArgs e) + { EventHandler eh = this.Events[EventFalseValue] as EventHandler; if (eh != null) eh(this, e); } - private void OnAllowNullChanged(EventArgs e) { + private void OnAllowNullChanged(EventArgs e) + { EventHandler eh = this.Events[EventAllowNull] as EventHandler; if (eh != null) eh(this, e); @@ -324,7 +364,7 @@ private void OnAllowNullChanged(EventArgs e) { /// protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum) { - Paint(g,bounds,source, rowNum, false); + Paint(g, bounds, source, rowNum, false); } /// @@ -332,8 +372,9 @@ protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyMan /// with the given , , /// row number, and alignment settings. /// - protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, bool alignToRight) { - Paint(g,bounds,source, rowNum, this.DataGridTableStyle.BackBrush, this.DataGridTableStyle.ForeBrush, alignToRight); + protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, bool alignToRight) + { + Paint(g, bounds, source, rowNum, this.DataGridTableStyle.BackBrush, this.DataGridTableStyle.ForeBrush, alignToRight); } /// @@ -342,10 +383,12 @@ protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyMan /// protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, Brush backBrush, Brush foreBrush, - bool alignToRight) { + bool alignToRight) + { object value = (isEditing && editingRow == rowNum) ? currentValue : GetColumnValueAtRow(source, rowNum); ButtonState checkedState = ButtonState.Inactive; - if (!Convert.IsDBNull(value)) { + if (!Convert.IsDBNull(value)) + { checkedState = ((bool)value ? ButtonState.Checked : ButtonState.Normal); } @@ -355,28 +398,33 @@ protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyMan g.ExcludeClip(box); System.Drawing.Brush selectionBrush = this.DataGridTableStyle.IsDefault ? this.DataGridTableStyle.DataGrid.SelectionBackBrush : this.DataGridTableStyle.SelectionBackBrush; - if (isSelected && editingRow == rowNum && !IsReadOnly()) { + if (isSelected && editingRow == rowNum && !IsReadOnly()) + { g.FillRectangle(selectionBrush, bounds); } else g.FillRectangle(backBrush, bounds); g.Clip = r; - if (checkedState == ButtonState.Inactive) { + if (checkedState == ButtonState.Inactive) + { ControlPaint.DrawMixedCheckBox(g, box, ButtonState.Checked); - } else { + } + else + { ControlPaint.DrawCheckBox(g, box, checkedState); } // if the column is read only we should still show selection - if (IsReadOnly() && isSelected && source.Position == rowNum) { - bounds.Inflate(-1,-1); + if (IsReadOnly() && isSelected && source.Position == rowNum) + { + bounds.Inflate(-1, -1); System.Drawing.Pen pen = new System.Drawing.Pen(selectionBrush); pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash; g.DrawRectangle(pen, bounds); pen.Dispose(); // restore the bounds rectangle - bounds.Inflate(1,1); + bounds.Inflate(1, 1); } } @@ -388,11 +436,14 @@ protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyMan DefaultValue(true), SRDescription(nameof(SR.DataGridBoolColumnAllowNullValue)) ] - public bool AllowNull { - get { + public bool AllowNull + { + get + { return allowNull; } - set { + set + { if (allowNull != value) { allowNull = value; @@ -408,11 +459,12 @@ public bool AllowNull { } } - public event EventHandler AllowNullChanged { + public event EventHandler AllowNullChanged + { add => Events.AddHandler(EventAllowNull, value); remove => Events.RemoveHandler(EventAllowNull, value); } - + /// /// Enters a into the column. /// @@ -422,35 +474,45 @@ protected internal override void EnterNullValue() // does not allowNull if (!this.AllowNull || IsReadOnly()) return; - if (currentValue != Convert.DBNull) { + if (currentValue != Convert.DBNull) + { currentValue = Convert.DBNull; Invalidate(); } } - private void ResetNullValue() { + private void ResetNullValue() + { NullValue = Convert.DBNull; } - private bool ShouldSerializeNullValue() { + private bool ShouldSerializeNullValue() + { return nullValue != Convert.DBNull; } - private void ToggleValue() { - - if (currentValue is bool && ((bool)currentValue) == false) { + private void ToggleValue() + { + + if (currentValue is bool && ((bool)currentValue) == false) + { currentValue = true; } - else { - if (AllowNull) { - if (Convert.IsDBNull(currentValue)) { + else + { + if (AllowNull) + { + if (Convert.IsDBNull(currentValue)) + { currentValue = false; } - else { + else + { currentValue = Convert.DBNull; } } - else { + else + { currentValue = false; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs index 90c4deb7d5b..537c7ca3efc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs @@ -2,12 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; using System; - + using System.Windows.Forms; using System.ComponentModel; using System.Drawing; @@ -21,15 +22,16 @@ namespace System.Windows.Forms { /// Represents a caption in the DataGrid control. /// /// - internal class DataGridCaption { - + internal class DataGridCaption + { + internal EventHandlerList events; private const int xOffset = 3; private const int yOffset = 1; private const int textPadding = 2; private const int buttonToText = 4; - private static ColorMap[] colorMap = new ColorMap[] {new ColorMap()}; + private static ColorMap[] colorMap = new ColorMap[] { new ColorMap() }; private static readonly Point minimumBounds = new Point(50, 30); @@ -38,18 +40,18 @@ internal class DataGridCaption { private bool backButtonVisible = false; private bool downButtonVisible = false; - private SolidBrush backBrush = DefaultBackBrush; - private SolidBrush foreBrush = DefaultForeBrush; - private Pen textBorderPen = DefaultTextBorderPen; + private SolidBrush backBrush = DefaultBackBrush; + private SolidBrush foreBrush = DefaultForeBrush; + private Pen textBorderPen = DefaultTextBorderPen; private string text = string.Empty; - private bool textBorderVisible = false; - private Font textFont = null; + private bool textBorderVisible = false; + private Font textFont = null; // use the datagridFont when the textFont is not set // we cache this font ( cause we have to make it bold every time we paint the caption ) // - private Font dataGridFont = null; + private Font dataGridFont = null; private bool backActive = false; private bool downActive = false; @@ -65,7 +67,7 @@ internal class DataGridCaption { private Rectangle backButtonRect = new Rectangle(); private Rectangle downButtonRect = new Rectangle(); - private Rectangle textRect = new Rectangle(); + private Rectangle textRect = new Rectangle(); private CaptionLocation lastMouseLocation = CaptionLocation.Nowhere; @@ -74,7 +76,8 @@ internal class DataGridCaption { private static readonly object EVENT_DOWNCLICKED = new object(); private static readonly object EVENT_CAPTIONCLICKED = new object(); - internal DataGridCaption(DataGrid dataGrid) { + internal DataGridCaption(DataGrid dataGrid) + { this.dataGrid = dataGrid; this.downButtonVisible = dataGrid.ParentRowsVisible; colorMap[0].OldColor = Color.White; @@ -82,12 +85,16 @@ internal DataGridCaption(DataGrid dataGrid) { OnGridFontChanged(); } - internal void OnGridFontChanged() { - if (dataGridFont == null || !dataGridFont.Equals(dataGrid.Font)) { - try { + internal void OnGridFontChanged() + { + if (dataGridFont == null || !dataGridFont.Equals(dataGrid.Font)) + { + try + { this.dataGridFont = new Font(dataGrid.Font, FontStyle.Bold); } - catch { + catch + { } } } @@ -96,54 +103,72 @@ internal void OnGridFontChanged() { // = Properties // =------------------------------------------------------------------ - internal bool BackButtonActive { - get { + internal bool BackButtonActive + { + get + { return backActive; } - set { - if (backActive != value) { + set + { + if (backActive != value) + { backActive = value; InvalidateCaptionRect(backButtonRect); } } } - internal bool DownButtonActive { - get { + internal bool DownButtonActive + { + get + { return downActive; } - set { - if (downActive != value) { + set + { + if (downActive != value) + { downActive = value; InvalidateCaptionRect(downButtonRect); } } } - internal static SolidBrush DefaultBackBrush { - get { + internal static SolidBrush DefaultBackBrush + { + get + { return (SolidBrush)SystemBrushes.ActiveCaption; } } - - internal static Pen DefaultTextBorderPen { - get { + + internal static Pen DefaultTextBorderPen + { + get + { return new Pen(SystemColors.ActiveCaptionText); } } - - internal static SolidBrush DefaultForeBrush { - get { + + internal static SolidBrush DefaultForeBrush + { + get + { return (SolidBrush)SystemBrushes.ActiveCaptionText; } } - - internal Color BackColor { - get { + + internal Color BackColor + { + get + { return backBrush.Color; } - set { - if (!backBrush.Color.Equals(value)) { + set + { + if (!backBrush.Color.Equals(value)) + { if (value.IsEmpty) throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "Caption BackColor")); backBrush = new SolidBrush(value); @@ -151,18 +176,23 @@ internal Color BackColor { } } } - - internal EventHandlerList Events { - get { - if (events == null) { + + internal EventHandlerList Events + { + get + { + if (events == null) + { events = new EventHandlerList(); } return events; } } - internal Font Font { - get { + internal Font Font + { + get + { // use the dataGridFont only if the user // did not set the CaptionFont // @@ -171,12 +201,15 @@ internal Font Font { else return textFont; } - set { - if (textFont == null || !textFont.Equals(value)) { + set + { + if (textFont == null || !textFont.Equals(value)) + { textFont = value; // this property gets called in the constructor before dataGrid has a caption // and we don't need this special-handling then... - if (dataGrid.Caption != null) { + if (dataGrid.Caption != null) + { dataGrid.RecalculateFonts(); dataGrid.PerformLayout(); dataGrid.Invalidate(); // smaller invalidate rect? @@ -185,42 +218,53 @@ internal Font Font { } } - internal bool ShouldSerializeFont() { + internal bool ShouldSerializeFont() + { return textFont != null && !textFont.Equals(this.dataGridFont); } - internal bool ShouldSerializeBackColor() { + internal bool ShouldSerializeBackColor() + { return !backBrush.Equals(DefaultBackBrush); } - - internal void ResetBackColor() { - if (ShouldSerializeBackColor()) { + + internal void ResetBackColor() + { + if (ShouldSerializeBackColor()) + { backBrush = DefaultBackBrush; Invalidate(); } } - internal void ResetForeColor() { - if (ShouldSerializeForeColor()) { + internal void ResetForeColor() + { + if (ShouldSerializeForeColor()) + { foreBrush = DefaultForeBrush; Invalidate(); } } - internal bool ShouldSerializeForeColor() { + internal bool ShouldSerializeForeColor() + { return !foreBrush.Equals(DefaultForeBrush); } - internal void ResetFont() { + internal void ResetFont() + { textFont = null; Invalidate(); } - internal string Text { - get { + internal string Text + { + get + { return text; } - set { + set + { if (value == null) text = string.Empty; else @@ -229,21 +273,27 @@ internal string Text { } } - internal bool TextBorderVisible { - get { + internal bool TextBorderVisible + { + get + { return textBorderVisible; } - set { + set + { textBorderVisible = value; Invalidate(); } } - internal Color ForeColor { - get { + internal Color ForeColor + { + get + { return foreBrush.Color; } - set { + set + { if (value.IsEmpty) throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "Caption ForeColor")); foreBrush = new SolidBrush(value); @@ -252,30 +302,40 @@ internal Color ForeColor { } } - internal Point MinimumBounds { - get { + internal Point MinimumBounds + { + get + { return minimumBounds; } } - internal bool BackButtonVisible { - get { + internal bool BackButtonVisible + { + get + { return backButtonVisible; } - set { - if (backButtonVisible != value) { + set + { + if (backButtonVisible != value) + { backButtonVisible = value; Invalidate(); } } } - internal bool DownButtonVisible { - get { + internal bool DownButtonVisible + { + get + { return downButtonVisible; } - set { - if (downButtonVisible != value) { + set + { + if (downButtonVisible != value) + { downButtonVisible = value; Invalidate(); } @@ -286,12 +346,17 @@ internal bool DownButtonVisible { // = Methods // =------------------------------------------------------------------ - protected virtual void AddEventHandler(object key, Delegate handler) { + protected virtual void AddEventHandler(object key, Delegate handler) + { // Locking 'this' here is ok since this is an internal class. - lock(this) { - if (handler == null) return; - for (EventEntry e = eventList; e != null; e = e.next) { - if (e.key == key) { + lock (this) + { + if (handler == null) + return; + for (EventEntry e = eventList; e != null; e = e.next) + { + if (e.key == key) + { e.handler = Delegate.Combine(e.handler, handler); return; } @@ -303,7 +368,8 @@ protected virtual void AddEventHandler(object key, Delegate handler) { /// /// Adds a listener for the BackwardClicked event. /// - internal event EventHandler BackwardClicked { + internal event EventHandler BackwardClicked + { add => Events.AddHandler(EVENT_BACKWARDCLICKED, value); remove => Events.RemoveHandler(EVENT_BACKWARDCLICKED, value); } @@ -312,128 +378,160 @@ internal event EventHandler BackwardClicked { /// /// Adds a listener for the CaptionClicked event. /// - internal event EventHandler CaptionClicked { + internal event EventHandler CaptionClicked + { add => Events.AddHandler(EVENT_CAPTIONCLICKED, value); remove => Events.RemoveHandler(EVENT_CAPTIONCLICKED, value); } - internal event EventHandler DownClicked { + internal event EventHandler DownClicked + { add => Events.AddHandler(EVENT_DOWNCLICKED, value); remove => Events.RemoveHandler(EVENT_DOWNCLICKED, value); } - private void Invalidate() { + private void Invalidate() + { if (dataGrid != null) dataGrid.InvalidateCaption(); } - private void InvalidateCaptionRect(Rectangle r) { + private void InvalidateCaptionRect(Rectangle r) + { if (dataGrid != null) dataGrid.InvalidateCaptionRect(r); } - private void InvalidateLocation(CaptionLocation loc) { + private void InvalidateLocation(CaptionLocation loc) + { Rectangle r; - switch (loc) { + switch (loc) + { case CaptionLocation.BackButton: r = backButtonRect; - r.Inflate(1,1); + r.Inflate(1, 1); InvalidateCaptionRect(r); break; case CaptionLocation.DownButton: r = downButtonRect; - r.Inflate(1,1); + r.Inflate(1, 1); InvalidateCaptionRect(r); break; } } - protected void OnBackwardClicked(EventArgs e) { - if (backActive) { + protected void OnBackwardClicked(EventArgs e) + { + if (backActive) + { EventHandler handler = (EventHandler)Events[EVENT_BACKWARDCLICKED]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } } - protected void OnCaptionClicked(EventArgs e) { + protected void OnCaptionClicked(EventArgs e) + { EventHandler handler = (EventHandler)Events[EVENT_CAPTIONCLICKED]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } - protected void OnDownClicked(EventArgs e) { - if (downActive && downButtonVisible) { + protected void OnDownClicked(EventArgs e) + { + if (downActive && downButtonVisible) + { EventHandler handler = (EventHandler)Events[EVENT_DOWNCLICKED]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } } - private Bitmap GetBitmap(string bitmapName) { - try { + private Bitmap GetBitmap(string bitmapName) + { + try + { return DpiHelper.GetBitmapFromIcon(typeof(DataGridCaption), bitmapName); } - catch (Exception e) { + catch (Exception e) + { Debug.Fail("Failed to load bitmap: " + bitmapName, e.ToString()); return null; } } - private Bitmap GetBackButtonBmp(bool alignRight) { - if (alignRight) { + private Bitmap GetBackButtonBmp(bool alignRight) + { + if (alignRight) + { if (leftButtonBitmap_bidi == null) leftButtonBitmap_bidi = GetBitmap("DataGridCaption.backarrow_bidi"); return leftButtonBitmap_bidi; - } else { + } + else + { if (leftButtonBitmap == null) leftButtonBitmap = GetBitmap("DataGridCaption.backarrow"); return leftButtonBitmap; } } - private Bitmap GetDetailsBmp() { + private Bitmap GetDetailsBmp() + { if (magnifyingGlassBitmap == null) magnifyingGlassBitmap = GetBitmap("DataGridCaption.Details"); return magnifyingGlassBitmap; } - protected virtual Delegate GetEventHandler(object key) { + protected virtual Delegate GetEventHandler(object key) + { // Locking 'this' here is ok since this is an internal class. - lock(this) { - for (EventEntry e = eventList; e != null; e = e.next) { - if (e.key == key) return e.handler; + lock (this) + { + for (EventEntry e = eventList; e != null; e = e.next) + { + if (e.key == key) + return e.handler; } return null; } } - internal Rectangle GetBackButtonRect(Rectangle bounds, bool alignRight, int downButtonWidth) { + internal Rectangle GetBackButtonRect(Rectangle bounds, bool alignRight, int downButtonWidth) + { Bitmap backButtonBmp = GetBackButtonBmp(false); Size backButtonSize; - lock (backButtonBmp) { + lock (backButtonBmp) + { backButtonSize = backButtonBmp.Size; } - return new Rectangle( bounds.Right - xOffset * 4 - downButtonWidth - backButtonSize.Width, + return new Rectangle(bounds.Right - xOffset * 4 - downButtonWidth - backButtonSize.Width, bounds.Y + yOffset + textPadding, backButtonSize.Width, backButtonSize.Height); } - internal int GetDetailsButtonWidth() { + internal int GetDetailsButtonWidth() + { int width = 0; Bitmap detailsBmp = GetDetailsBmp(); - lock (detailsBmp) { + lock (detailsBmp) + { width = detailsBmp.Size.Width; } return width; } - internal Rectangle GetDetailsButtonRect(Rectangle bounds, bool alignRight) { + internal Rectangle GetDetailsButtonRect(Rectangle bounds, bool alignRight) + { Size downButtonSize; Bitmap detailsBmp = GetDetailsBmp(); - lock (detailsBmp) { + lock (detailsBmp) + { downButtonSize = detailsBmp.Size; } int downButtonWidth = downButtonSize.Width; - return new Rectangle( bounds.Right - xOffset * 2 - downButtonWidth, + return new Rectangle(bounds.Right - xOffset * 2 - downButtonWidth, bounds.Y + yOffset + textPadding, downButtonWidth, downButtonSize.Height); @@ -443,8 +541,9 @@ internal Rectangle GetDetailsButtonRect(Rectangle bounds, bool alignRight) { /// Called by the dataGrid when it needs the caption /// to repaint. /// - internal void Paint(Graphics g, Rectangle bounds, bool alignRight) { - Size textSize = new Size((int) g.MeasureString(text, this.Font).Width + 2, this.Font.Height + 2); + internal void Paint(Graphics g, Rectangle bounds, bool alignRight) + { + Size textSize = new Size((int)g.MeasureString(text, this.Font).Width + 2, this.Font.Height + 2); downButtonRect = GetDetailsButtonRect(bounds, alignRight); int downButtonWidth = GetDetailsButtonWidth(); @@ -464,7 +563,8 @@ internal void Paint(Graphics g, Rectangle bounds, bool alignRight) { // align the caption text box, downButton, and backButton // if the RigthToLeft property is set to true - if (alignRight) { + if (alignRight) + { textRect.X = bounds.Right - textRect.Width; backButtonRect.X = bounds.X + xOffset * 4 + downButtonWidth; downButtonRect.X = bounds.X + xOffset * 2; @@ -483,11 +583,14 @@ internal void Paint(Graphics g, Rectangle bounds, bool alignRight) { // g.FillRectangle(backBrush, bounds); - if (backButtonVisible) { + if (backButtonVisible) + { PaintBackButton(g, backButtonRect, alignRight); - if (backActive) { - if (lastMouseLocation == CaptionLocation.BackButton) { - backButtonRect.Inflate(1,1); + if (backActive) + { + if (lastMouseLocation == CaptionLocation.BackButton) + { + backButtonRect.Inflate(1, 1); ControlPaint.DrawBorder3D(g, backButtonRect, backPressed ? Border3DStyle.SunkenInner : Border3DStyle.RaisedInner); } @@ -495,7 +598,8 @@ internal void Paint(Graphics g, Rectangle bounds, bool alignRight) { } PaintText(g, textRect, alignRight); - if (downButtonVisible && !dataGrid.ParentRowsIsEmpty()) { + if (downButtonVisible && !dataGrid.ParentRowsIsEmpty()) + { PaintDownButton(g, downButtonRect); // the rules have changed, yet again. // now: if we show the parent rows and the mouse is @@ -505,46 +609,54 @@ internal void Paint(Graphics g, Rectangle bounds, bool alignRight) { // if (lastMouseLocation == CaptionLocation.DownButton) { - downButtonRect.Inflate(1,1); + downButtonRect.Inflate(1, 1); ControlPaint.DrawBorder3D(g, downButtonRect, downPressed ? Border3DStyle.SunkenInner : Border3DStyle.RaisedInner); } } } - private void PaintIcon(Graphics g, Rectangle bounds, Bitmap b) { + private void PaintIcon(Graphics g, Rectangle bounds, Bitmap b) + { ImageAttributes attr = new ImageAttributes(); attr.SetRemapTable(colorMap, ColorAdjustType.Bitmap); - g.DrawImage(b, bounds, 0, 0, bounds.Width, bounds.Height,GraphicsUnit.Pixel, attr); + g.DrawImage(b, bounds, 0, 0, bounds.Width, bounds.Height, GraphicsUnit.Pixel, attr); attr.Dispose(); } - private void PaintBackButton(Graphics g, Rectangle bounds, bool alignRight) { + private void PaintBackButton(Graphics g, Rectangle bounds, bool alignRight) + { Bitmap backButtonBmp = GetBackButtonBmp(alignRight); - lock (backButtonBmp) { + lock (backButtonBmp) + { PaintIcon(g, bounds, backButtonBmp); } } - private void PaintDownButton(Graphics g, Rectangle bounds) { + private void PaintDownButton(Graphics g, Rectangle bounds) + { Bitmap detailsBmp = GetDetailsBmp(); - lock (detailsBmp) { + lock (detailsBmp) + { PaintIcon(g, bounds, detailsBmp); } } - private void PaintText(Graphics g, Rectangle bounds, bool alignToRight) { + private void PaintText(Graphics g, Rectangle bounds, bool alignToRight) + { Rectangle textBounds = bounds; if (textBounds.Width <= 0 || textBounds.Height <= 0) return; - if (textBorderVisible) { + if (textBorderVisible) + { g.DrawRectangle(this.textBorderPen, textBounds.X, textBounds.Y, textBounds.Width - 1, textBounds.Height - 1); - textBounds.Inflate(-1,-1); + textBounds.Inflate(-1, -1); } - if (textPadding > 0) { + if (textPadding > 0) + { Rectangle border = textBounds; border.Height = textPadding; g.FillRectangle(this.backBrush, border); @@ -553,7 +665,7 @@ private void PaintText(Graphics g, Rectangle bounds, bool alignToRight) { g.FillRectangle(this.backBrush, border); border = new Rectangle(textBounds.X, textBounds.Y + textPadding, - textPadding, textBounds.Height - 2*textPadding); + textPadding, textBounds.Height - 2 * textPadding); g.FillRectangle(this.backBrush, border); border.X = textBounds.Right - textPadding; @@ -565,7 +677,8 @@ private void PaintText(Graphics g, Rectangle bounds, bool alignToRight) { // Brush foreBrush = new SolidBrush(dataGrid.CaptionForeColor); StringFormat format = new StringFormat(); - if (alignToRight) { + if (alignToRight) + { format.FormatFlags |= StringFormatFlags.DirectionRightToLeft; format.Alignment = StringAlignment.Far; } @@ -574,27 +687,34 @@ private void PaintText(Graphics g, Rectangle bounds, bool alignToRight) { // foreBrush.Dispose(); } - private CaptionLocation FindLocation(int x, int y) { - if (!backButtonRect.IsEmpty) { - if (backButtonRect.Contains(x,y)) + private CaptionLocation FindLocation(int x, int y) + { + if (!backButtonRect.IsEmpty) + { + if (backButtonRect.Contains(x, y)) return CaptionLocation.BackButton; } - if (!downButtonRect.IsEmpty) { - if (downButtonRect.Contains(x,y)) + if (!downButtonRect.IsEmpty) + { + if (downButtonRect.Contains(x, y)) return CaptionLocation.DownButton; } - if (!textRect.IsEmpty) { - if (textRect.Contains(x,y)) + if (!textRect.IsEmpty) + { + if (textRect.Contains(x, y)) return CaptionLocation.Text; } return CaptionLocation.Nowhere; } - private bool DownButtonDown { - get { + private bool DownButtonDown + { + get + { return downButtonDown; } - set { + set + { if (downButtonDown != value) { downButtonDown = value; @@ -603,7 +723,8 @@ private bool DownButtonDown { } } - internal bool GetDownButtonDirection() { + internal bool GetDownButtonDirection() + { return DownButtonDown; } @@ -611,9 +732,11 @@ internal bool GetDownButtonDirection() { /// Called by the dataGrid when the mouse is pressed /// inside the caption. /// - internal void MouseDown(int x, int y) { + internal void MouseDown(int x, int y) + { CaptionLocation loc = FindLocation(x, y); - switch (loc) { + switch (loc) + { case CaptionLocation.BackButton: backPressed = true; InvalidateLocation(loc); @@ -632,17 +755,21 @@ internal void MouseDown(int x, int y) { /// Called by the dataGrid when the mouse is released /// inside the caption. /// - internal void MouseUp(int x, int y) { + internal void MouseUp(int x, int y) + { CaptionLocation loc = FindLocation(x, y); - switch (loc) { + switch (loc) + { case CaptionLocation.DownButton: - if (downPressed == true) { + if (downPressed == true) + { downPressed = false; OnDownClicked(EventArgs.Empty); } break; case CaptionLocation.BackButton: - if (backPressed == true) { + if (backPressed == true) + { backPressed = false; OnBackwardClicked(EventArgs.Empty); } @@ -654,7 +781,8 @@ internal void MouseUp(int x, int y) { /// Called by the dataGrid when the mouse leaves /// the caption area. /// - internal void MouseLeft() { + internal void MouseLeft() + { CaptionLocation oldLoc = lastMouseLocation; lastMouseLocation = CaptionLocation.Nowhere; InvalidateLocation(oldLoc); @@ -664,7 +792,8 @@ internal void MouseLeft() { /// Called by the dataGrid when the mouse is /// inside the caption. /// - internal void MouseOver(int x, int y) { + internal void MouseOver(int x, int y) + { CaptionLocation newLoc = FindLocation(x, y); InvalidateLocation(lastMouseLocation); @@ -672,23 +801,33 @@ internal void MouseOver(int x, int y) { lastMouseLocation = newLoc; } - protected virtual void RaiseEvent(object key, EventArgs e) { + protected virtual void RaiseEvent(object key, EventArgs e) + { Delegate handler = GetEventHandler(key); - if (handler != null)((EventHandler)handler)(this, e); + if (handler != null) + ((EventHandler)handler)(this, e); } - protected virtual void RemoveEventHandler(object key, Delegate handler) { + protected virtual void RemoveEventHandler(object key, Delegate handler) + { // Locking 'this' here is ok since this is an internal class. - lock(this) { - if (handler == null) return; - for (EventEntry e = eventList, prev = null; e != null; prev = e, e = e.next) { - if (e.key == key) { + lock (this) + { + if (handler == null) + return; + for (EventEntry e = eventList, prev = null; e != null; prev = e, e = e.next) + { + if (e.key == key) + { e.handler = Delegate.Remove(e.handler, handler); - if (e.handler == null) { - if (prev == null) { + if (e.handler == null) + { + if (prev == null) + { eventList = e.next; } - else { + else + { prev.next = e.next; } } @@ -698,7 +837,8 @@ protected virtual void RemoveEventHandler(object key, Delegate handler) { } } - protected virtual void RemoveEventHandlers() { + protected virtual void RemoveEventHandlers() + { eventList = null; } @@ -710,23 +850,27 @@ internal void SetDownButtonDirection(bool pointDown) /// /// Toggles the direction the "Down Button" is pointing. /// - internal bool ToggleDownButtonDirection() { + internal bool ToggleDownButtonDirection() + { DownButtonDown = !DownButtonDown; return DownButtonDown; } - internal enum CaptionLocation { + internal enum CaptionLocation + { Nowhere, BackButton, DownButton, Text } - private sealed class EventEntry { + private sealed class EventEntry + { internal EventEntry next; internal object key; internal Delegate handler; - internal EventEntry(EventEntry next, object key, Delegate handler) { + internal EventEntry(EventEntry next, object key, Delegate handler) + { this.next = next; this.key = key; this.handler = handler; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs index 7c084eaf712..72c9c10d3d1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -22,92 +23,112 @@ namespace System.Windows.Forms { Editor("System.Windows.Forms.Design.DataGridColumnCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), ListBindable(false) ] - public class GridColumnStylesCollection : BaseCollection, IList { + public class GridColumnStylesCollection : BaseCollection, IList + { CollectionChangeEventHandler onCollectionChanged; - ArrayList items = new ArrayList(); - DataGridTableStyle owner = null; - private bool isDefault = false; + ArrayList items = new ArrayList(); + DataGridTableStyle owner = null; + private bool isDefault = false; // we have to implement IList for the Collection editor to work // - int IList.Add(object value) { - return this.Add((DataGridColumnStyle) value); + int IList.Add(object value) + { + return this.Add((DataGridColumnStyle)value); } - void IList.Clear() { + void IList.Clear() + { this.Clear(); } - bool IList.Contains(object value) { + bool IList.Contains(object value) + { return items.Contains(value); } - int IList.IndexOf(object value) { + int IList.IndexOf(object value) + { return items.IndexOf(value); } - void IList.Insert(int index, object value) { + void IList.Insert(int index, object value) + { throw new NotSupportedException(); } - void IList.Remove(object value) { + void IList.Remove(object value) + { this.Remove((DataGridColumnStyle)value); } - void IList.RemoveAt(int index) { + void IList.RemoveAt(int index) + { this.RemoveAt(index); } - bool IList.IsFixedSize { - get {return false;} + bool IList.IsFixedSize + { + get { return false; } } - bool IList.IsReadOnly { - get {return false;} + bool IList.IsReadOnly + { + get { return false; } } - object IList.this[int index] { + object IList.this[int index] + { get { return items[index]; } set { throw new NotSupportedException(); } } - void ICollection.CopyTo(Array array, int index) { + void ICollection.CopyTo(Array array, int index) + { this.items.CopyTo(array, index); } - int ICollection.Count { - get {return this.items.Count;} + int ICollection.Count + { + get { return this.items.Count; } } - bool ICollection.IsSynchronized { - get {return false;} + bool ICollection.IsSynchronized + { + get { return false; } } - object ICollection.SyncRoot { - get {return this;} + object ICollection.SyncRoot + { + get { return this; } } - IEnumerator IEnumerable.GetEnumerator() { + IEnumerator IEnumerable.GetEnumerator() + { return items.GetEnumerator(); } - internal GridColumnStylesCollection(DataGridTableStyle table) { + internal GridColumnStylesCollection(DataGridTableStyle table) + { owner = table; } - internal GridColumnStylesCollection(DataGridTableStyle table, bool isDefault) : this(table) { + internal GridColumnStylesCollection(DataGridTableStyle table, bool isDefault) : this(table) + { this.isDefault = isDefault; } /// /// Gets the list of items in the collection. /// - protected override ArrayList List { - get { + protected override ArrayList List + { + get + { return items; } } - + /* implemented in BaseCollection /// /// @@ -148,8 +169,10 @@ public override int Count { /// /// Gets the System.Windows.Forms.DataGridColumnStyle at a specified index. /// - public DataGridColumnStyle this[int index] { - get { + public DataGridColumnStyle this[int index] + { + get + { return (DataGridColumnStyle)items[index]; } } @@ -158,12 +181,15 @@ public DataGridColumnStyle this[int index] { /// Gets the System.Windows.Forms.DataGridColumnStyle /// with the specified name. /// - public DataGridColumnStyle this[string columnName] { + public DataGridColumnStyle this[string columnName] + { // PM team has reviewed and decided on naming changes already [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] - get { + get + { int itemCount = items.Count; - for (int i = 0; i < itemCount; ++i) { + for (int i = 0; i < itemCount; ++i) + { DataGridColumnStyle column = (DataGridColumnStyle)items[i]; // NOTE: case-insensitive if (string.Equals(column.MappingName, columnName, StringComparison.OrdinalIgnoreCase)) @@ -173,9 +199,11 @@ public DataGridColumnStyle this[string columnName] { } } - internal DataGridColumnStyle MapColumnStyleToPropertyName(string mappingName) { + internal DataGridColumnStyle MapColumnStyleToPropertyName(string mappingName) + { int itemCount = items.Count; - for (int i = 0; i < itemCount; ++i) { + for (int i = 0; i < itemCount; ++i) + { DataGridColumnStyle column = (DataGridColumnStyle)items[i]; // NOTE: case-insensitive if (string.Equals(column.MappingName, mappingName, StringComparison.OrdinalIgnoreCase)) @@ -189,13 +217,16 @@ internal DataGridColumnStyle MapColumnStyleToPropertyName(string mappingName) { /// specified . /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1043:UseIntegralOrStringArgumentForIndexers")] - public DataGridColumnStyle this[PropertyDescriptor propertyDesciptor] { + public DataGridColumnStyle this[PropertyDescriptor propertyDesciptor] + { [ System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly") // already shipped ] - get { + get + { int itemCount = items.Count; - for (int i = 0; i < itemCount; ++i) { + for (int i = 0; i < itemCount; ++i) + { DataGridColumnStyle column = (DataGridColumnStyle)items[i]; if (propertyDesciptor.Equals(column.PropertyDescriptor)) return column; @@ -204,8 +235,10 @@ public DataGridColumnStyle this[PropertyDescriptor propertyDesciptor] { } } - internal DataGridTableStyle DataGridTableStyle { - get { + internal DataGridTableStyle DataGridTableStyle + { + get + { return this.owner; } } @@ -214,24 +247,29 @@ internal DataGridTableStyle DataGridTableStyle { /// Adds a System.Windows.Forms.DataGridColumnStyle to the System.Windows.Forms.GridColumnStylesCollection /// - internal void CheckForMappingNameDuplicates(DataGridColumnStyle column) { + internal void CheckForMappingNameDuplicates(DataGridColumnStyle column) + { if (string.IsNullOrEmpty(column.MappingName)) return; for (int i = 0; i < items.Count; i++) - if ( ((DataGridColumnStyle)items[i]).MappingName.Equals(column.MappingName) && column != items[i]) + if (((DataGridColumnStyle)items[i]).MappingName.Equals(column.MappingName) && column != items[i]) throw new ArgumentException(SR.DataGridColumnStyleDuplicateMappingName, "column"); } - private void ColumnStyleMappingNameChanged(object sender, EventArgs pcea) { + private void ColumnStyleMappingNameChanged(object sender, EventArgs pcea) + { OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null)); } - private void ColumnStylePropDescChanged(object sender, EventArgs pcea) { - OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, (DataGridColumnStyle) sender)); + private void ColumnStylePropDescChanged(object sender, EventArgs pcea) + { + OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, (DataGridColumnStyle)sender)); } - public virtual int Add(DataGridColumnStyle column) { - if (this.isDefault) { + public virtual int Add(DataGridColumnStyle column) + { + if (this.isDefault) + { throw new ArgumentException(SR.DataGridDefaultColumnCollectionChanged); } @@ -252,19 +290,23 @@ public virtual int Add(DataGridColumnStyle column) { OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, column)); return index; } - - public void AddRange(DataGridColumnStyle[] columns) { - if (columns == null) { + + public void AddRange(DataGridColumnStyle[] columns) + { + if (columns == null) + { throw new ArgumentNullException(nameof(columns)); } - for (int i = 0; i < columns.Length; i++) { - Add(columns[i]); + for (int i = 0; i < columns.Length; i++) + { + Add(columns[i]); } } // the dataGrid will need to add default columns to a default // table when there is no match for the listName in the tableStyle - internal void AddDefaultColumn(DataGridColumnStyle column) { + internal void AddDefaultColumn(DataGridColumnStyle column) + { #if DEBUG Debug.Assert(this.isDefault, "we should be calling this function only for default tables"); Debug.Assert(column.IsDefault, "we should be a default column"); @@ -273,10 +315,12 @@ internal void AddDefaultColumn(DataGridColumnStyle column) { this.items.Add(column); } - internal void ResetDefaultColumnCollection() { + internal void ResetDefaultColumnCollection() + { Debug.Assert(this.isDefault, "we should be calling this function only for default tables"); // unparent the edit controls - for (int i = 0; i < Count; i++) { + for (int i = 0; i < Count; i++) + { this[i].ReleaseHostedControl(); } @@ -287,13 +331,16 @@ internal void ResetDefaultColumnCollection() { /// /// Occurs when a change is made to the System.Windows.Forms.GridColumnStylesCollection. /// - public event CollectionChangeEventHandler CollectionChanged { + public event CollectionChangeEventHandler CollectionChanged + { add => onCollectionChanged += value; remove => onCollectionChanged -= value; } - - public void Clear() { - for (int i = 0; i < Count; i ++) { + + public void Clear() + { + for (int i = 0; i < Count; i++) + { this[i].ReleaseHostedControl(); } items.Clear(); @@ -306,7 +353,8 @@ public void Clear() { /// specified . /// /// - public bool Contains(PropertyDescriptor propertyDescriptor) { + public bool Contains(PropertyDescriptor propertyDescriptor) + { return this[propertyDescriptor] != null; } @@ -315,7 +363,8 @@ public bool Contains(PropertyDescriptor propertyDescriptor) { /// Gets a value indicating whether the System.Windows.Forms.GridColumnsStyleCollection contains the specified System.Windows.Forms.DataGridColumnStyle. /// /// - public bool Contains(DataGridColumnStyle column) { + public bool Contains(DataGridColumnStyle column) + { int index = items.IndexOf(column); return index != -1; } @@ -325,9 +374,11 @@ public bool Contains(DataGridColumnStyle column) { /// Gets a value indicating whether the System.Windows.Forms.GridColumnsStyleCollection contains the System.Windows.Forms.DataGridColumnStyle with the specified name. /// /// - public bool Contains(string name) { + public bool Contains(string name) + { IEnumerator e = items.GetEnumerator(); - while (e.MoveNext()) { + while (e.MoveNext()) + { DataGridColumnStyle column = (DataGridColumnStyle)e.Current; // NOTE: case-insensitive if (string.Compare(column.MappingName, name, true, CultureInfo.InvariantCulture) == 0) @@ -439,9 +490,11 @@ public override IEnumerator GetEnumerator(bool allowRemove) { /// /// Gets the index of a specified System.Windows.Forms.DataGridColumnStyle. /// - public int IndexOf(DataGridColumnStyle element) { + public int IndexOf(DataGridColumnStyle element) + { int itemCount = items.Count; - for (int i = 0; i < itemCount; ++i) { + for (int i = 0; i < itemCount; ++i) + { DataGridColumnStyle column = (DataGridColumnStyle)items[i]; if (element == column) return i; @@ -452,12 +505,14 @@ public int IndexOf(DataGridColumnStyle element) { /// /// Raises the System.Windows.Forms.GridColumnsCollection.CollectionChanged event. /// - protected void OnCollectionChanged(CollectionChangeEventArgs e) { + protected void OnCollectionChanged(CollectionChangeEventArgs e) + { if (onCollectionChanged != null) onCollectionChanged(this, e); DataGrid grid = owner.DataGrid; - if (grid != null) { + if (grid != null) + { grid.checkHierarchy = true; } } @@ -465,15 +520,18 @@ protected void OnCollectionChanged(CollectionChangeEventArgs e) { /// /// Removes the specified System.Windows.Forms.DataGridColumnStyle from the System.Windows.Forms.GridColumnsStyleCollection. /// - public void Remove(DataGridColumnStyle column) { - if (this.isDefault) { + public void Remove(DataGridColumnStyle column) + { + if (this.isDefault) + { throw new ArgumentException(SR.DataGridDefaultColumnCollectionChanged); } int columnIndex = -1; int itemsCount = items.Count; for (int i = 0; i < itemsCount; ++i) - if (items[i] == column) { + if (items[i] == column) + { columnIndex = i; break; } @@ -486,8 +544,10 @@ public void Remove(DataGridColumnStyle column) { /// /// Removes the System.Windows.Forms.DataGridColumnStyle with the specified index from the System.Windows.Forms.GridColumnsStyleCollection. /// - public void RemoveAt(int index) { - if (this.isDefault) { + public void RemoveAt(int index) + { + if (this.isDefault) + { throw new ArgumentException(SR.DataGridDefaultColumnCollectionChanged); } @@ -502,8 +562,10 @@ public void RemoveAt(int index) { OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, toRemove)); } - public void ResetPropertyDescriptors() { - for (int i = 0; i < this.Count; i++) { + public void ResetPropertyDescriptors() + { + for (int i = 0; i < this.Count; i++) + { this[i].PropertyDescriptor = null; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnStyle.cs index 6ae49677488..020ccaa23b7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnStyle.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnStyle.cs @@ -475,7 +475,7 @@ protected internal virtual object GetColumnValueAtRow(CurrencyManager source, in { throw new InvalidOperationException(SR.DataGridColumnNoPropertyDescriptor); } - + return descriptor.GetValue(source[rowNum]); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridDefaultColumnWidthTypeConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridDefaultColumnWidthTypeConverter.cs index 0d44c69627d..15b1cb554b7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridDefaultColumnWidthTypeConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridDefaultColumnWidthTypeConverter.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System; @@ -11,7 +12,8 @@ namespace System.Windows.Forms { using Microsoft.Win32; using System.Globalization; - public class DataGridPreferredColumnWidthTypeConverter : TypeConverter { + public class DataGridPreferredColumnWidthTypeConverter : TypeConverter + { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string) || sourceType == typeof(int)) @@ -26,8 +28,8 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul { if (value.GetType() == typeof(int)) { - int pulica = (int) value; - if (pulica == - 1) + int pulica = (int)value; + if (pulica == -1) return "AutoColumnResize (-1)"; else return pulica.ToString(CultureInfo.CurrentCulture); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRows.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRows.cs index e850be913c0..b83b01a9319 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRows.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRows.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Text; using System; using System.Collections; @@ -15,7 +16,8 @@ namespace System.Windows.Forms { using System.Diagnostics; using System.Runtime.Versioning; - internal class DataGridParentRows { + internal class DataGridParentRows + { // siting // private DataGrid dataGrid; @@ -35,7 +37,7 @@ internal class DataGridParentRows { private static Bitmap rightArrow = null; private static Bitmap leftArrow = null; - private ColorMap[] colorMap = new ColorMap[] {new ColorMap()}; + private ColorMap[] colorMap = new ColorMap[] { new ColorMap() }; // private bool gridLineDots = false; // private Color gridLineColor = SystemColors.Control; @@ -71,7 +73,8 @@ internal class DataGridParentRows { private ArrayList rowHeights = new ArrayList(); AccessibleObject accessibleObject; - internal DataGridParentRows(DataGrid dataGrid) { + internal DataGridParentRows(DataGrid dataGrid) + { this.colorMap[0].OldColor = Color.Black; this.dataGrid = dataGrid; // UpdateGridLinePen(); @@ -81,35 +84,46 @@ internal DataGridParentRows(DataGrid dataGrid) { // = Properties // =------------------------------------------------------------------ - public AccessibleObject AccessibleObject { - get { - if (accessibleObject == null) { + public AccessibleObject AccessibleObject + { + get + { + if (accessibleObject == null) + { accessibleObject = new DataGridParentRowsAccessibleObject(this); } return accessibleObject; } } - internal Color BackColor { - get { + internal Color BackColor + { + get + { return backBrush.Color; } - set { + set + { if (value.IsEmpty) throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "Parent Rows BackColor")); - if (value != backBrush.Color) { + if (value != backBrush.Color) + { backBrush = new SolidBrush(value); Invalidate(); } } } - internal SolidBrush BackBrush { - get { + internal SolidBrush BackBrush + { + get + { return backBrush; } - set { - if (value != backBrush) { + set + { + if (value != backBrush) + { CheckNull(value, "BackBrush"); backBrush = value; Invalidate(); @@ -117,12 +131,16 @@ internal SolidBrush BackBrush { } } - internal SolidBrush ForeBrush { - get { + internal SolidBrush ForeBrush + { + get + { return foreBrush; } - set { - if (value != foreBrush) { + set + { + if (value != foreBrush) + { CheckNull(value, "BackBrush"); foreBrush = value; Invalidate(); @@ -132,12 +150,15 @@ internal SolidBrush ForeBrush { // since the layout of the parentRows is computed on every paint message, // we can actually return true ClientRectangle coordinates - internal Rectangle GetBoundsForDataGridStateAccesibility(DataGridState dgs) { + internal Rectangle GetBoundsForDataGridStateAccesibility(DataGridState dgs) + { Rectangle ret = Rectangle.Empty; int rectY = 0; - for (int i = 0; i < parentsCount; i++) { - int height = (int) rowHeights[i]; - if (parents[i] == dgs) { + for (int i = 0; i < parentsCount; i++) + { + int height = (int)rowHeights[i]; + if (parents[i] == dgs) + { ret.X = layout.leftArrow.IsEmpty ? layout.data.X : layout.leftArrow.Right; ret.Height = height; ret.Y = rectY; @@ -163,12 +184,16 @@ internal Color BorderColor { } */ - internal Brush BorderBrush { - get { + internal Brush BorderBrush + { + get + { return borderBrush; } - set { - if (value != borderBrush) { + set + { + if (value != borderBrush) + { borderBrush = value; Invalidate(); } @@ -203,31 +228,40 @@ internal bool GridLineDots { } */ - internal int Height { - get { + internal int Height + { + get + { return totalHeight; } } - internal Color ForeColor { - get { + internal Color ForeColor + { + get + { return foreBrush.Color; } - set { + set + { if (value.IsEmpty) throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "Parent Rows ForeColor")); - if (value != foreBrush.Color) { + if (value != foreBrush.Color) + { foreBrush = new SolidBrush(value); Invalidate(); } } } - internal bool Visible { - get { + internal bool Visible + { + get + { return dataGrid.ParentRowsVisible; } - set { + set + { dataGrid.ParentRowsVisible = value; } } @@ -239,15 +273,18 @@ internal bool Visible { /// /// Adds a DataGridState object to the top of the list of parents. /// - internal void AddParent(DataGridState dgs) { - CurrencyManager childDataSource = (CurrencyManager) dataGrid.BindingContext[dgs.DataSource, dgs.DataMember]; + internal void AddParent(DataGridState dgs) + { + CurrencyManager childDataSource = (CurrencyManager)dataGrid.BindingContext[dgs.DataSource, dgs.DataMember]; parents.Add(dgs); SetParentCount(parentsCount + 1); Debug.Assert(GetTopParent() != null, "we should have a parent at least"); } - internal void Clear() { - for (int i = 0; i < parents.Count; i++) { + internal void Clear() + { + for (int i = 0; i < parents.Count; i++) + { DataGridState dgs = parents[i] as DataGridState; dgs.RemoveChangeNotification(); } @@ -257,53 +294,62 @@ internal void Clear() { SetParentCount(0); } - internal void SetParentCount(int count) { + internal void SetParentCount(int count) + { parentsCount = count; dataGrid.Caption.BackButtonVisible = (parentsCount > 0) && (dataGrid.AllowNavigation); } - internal void CheckNull(object value, string propName) { + internal void CheckNull(object value, string propName) + { if (value == null) throw new ArgumentNullException(nameof(propName)); } - internal void Dispose() { + internal void Dispose() + { gridLinePen.Dispose(); } /// /// Retrieves the top most parent in the list of parents. /// - internal DataGridState GetTopParent() { - if (parentsCount < 1) { + internal DataGridState GetTopParent() + { + if (parentsCount < 1) + { return null; } - return(DataGridState)(((ICloneable)(parents[parentsCount-1])).Clone()); + return (DataGridState)(((ICloneable)(parents[parentsCount - 1])).Clone()); } /// /// Determines if there are any parent rows contained in this object. /// - internal bool IsEmpty() { + internal bool IsEmpty() + { return parentsCount == 0; } /// /// Similar to GetTopParent() but also removes it. /// - internal DataGridState PopTop() { - if (parentsCount < 1) { + internal DataGridState PopTop() + { + if (parentsCount < 1) + { return null; } SetParentCount(parentsCount - 1); - DataGridState ret = (DataGridState)parents[parentsCount]; + DataGridState ret = (DataGridState)parents[parentsCount]; ret.RemoveChangeNotification(); - parents.RemoveAt(parentsCount); + parents.RemoveAt(parentsCount); return ret; } - internal void Invalidate() { + internal void Invalidate() + { if (dataGrid != null) dataGrid.InvalidateParentRows(); } @@ -318,12 +364,14 @@ internal void InvalidateRect(Rectangle rect) } // called from DataGrid::OnLayout - internal void OnLayout() { + internal void OnLayout() + { if (parentsCount == rowHeights.Count) return; int height = 0; - if (totalHeight == 0) { + if (totalHeight == 0) + { totalHeight += 2 * borderWidth; } @@ -339,43 +387,50 @@ internal void OnLayout() { // ( ie, when the form does not process PerformLayout ) // the grid will receive an OnLayout message when there is more // than one parent in the grid - if (parentsCount > rowHeights.Count) { + if (parentsCount > rowHeights.Count) + { Debug.Assert(parentsCount == rowHeights.Count + 1 || rowHeights.Count == 0, "see comment above for more info"); int rowHeightsCount = this.rowHeights.Count; - for (int i = rowHeightsCount; i < parentsCount; i++) { - DataGridState dgs = (DataGridState) parents[i]; + for (int i = rowHeightsCount; i < parentsCount; i++) + { + DataGridState dgs = (DataGridState)parents[i]; GridColumnStylesCollection cols = dgs.GridColumnStyles; int colsHeight = 0; - for (int j=0; j 0) { + private void LeftArrowClick(int cellCount) + { + if (horizOffset > 0) + { ResetMouseInfo(); horizOffset -= 1; Invalidate(); @@ -402,8 +459,10 @@ private void LeftArrowClick(int cellCount) { } } - private void RightArrowClick(int cellCount) { - if (horizOffset < cellCount - 1) { + private void RightArrowClick(int cellCount) + { + if (horizOffset < cellCount - 1) + { ResetMouseInfo(); horizOffset += 1; Invalidate(); @@ -418,15 +477,18 @@ private void RightArrowClick(int cellCount) { // the only mouse clicks that are handled are // the mouse clicks on the LeftArrow and RightArrow // - internal void OnMouseDown(int x, int y, bool alignToRight) { - if (layout.rightArrow.IsEmpty) { + internal void OnMouseDown(int x, int y, bool alignToRight) + { + if (layout.rightArrow.IsEmpty) + { Debug.Assert(layout.leftArrow.IsEmpty, "we can't have the leftArrow w/o the rightArrow"); return; } int cellCount = CellCount(); - if (layout.rightArrow.Contains(x,y)) { + if (layout.rightArrow.Contains(x, y)) + { // draw a nice sunken border around the right arrow area // we want to keep a cell on the screen @@ -437,7 +499,8 @@ internal void OnMouseDown(int x, int y, bool alignToRight) { else RightArrowClick(cellCount); } - else if (layout.leftArrow.Contains(x,y)) { + else if (layout.leftArrow.Contains(x, y)) + { downLeftArrow = true; if (alignToRight) @@ -445,7 +508,7 @@ internal void OnMouseDown(int x, int y, bool alignToRight) { else LeftArrowClick(cellCount); } - else + else { if (downLeftArrow) { @@ -460,7 +523,8 @@ internal void OnMouseDown(int x, int y, bool alignToRight) { } } - internal void OnMouseLeave() { + internal void OnMouseLeave() + { if (downLeftArrow) { downLeftArrow = false; @@ -473,7 +537,8 @@ internal void OnMouseLeave() { } } - internal void OnMouseMove(int x, int y) { + internal void OnMouseMove(int x, int y) + { /* if (!layout.leftArrow.IsEmpty && layout.leftArrow.Contains(x,y)) { @@ -503,31 +568,35 @@ internal void OnMouseMove(int x, int y) { } } - internal void OnMouseUp(int x, int y) { + internal void OnMouseUp(int x, int y) + { ResetMouseInfo(); - if (!layout.rightArrow.IsEmpty && layout.rightArrow.Contains(x,y)) + if (!layout.rightArrow.IsEmpty && layout.rightArrow.Contains(x, y)) { InvalidateRect(layout.rightArrow); return; } - if (!layout.leftArrow.IsEmpty && layout.leftArrow.Contains(x,y)) + if (!layout.leftArrow.IsEmpty && layout.leftArrow.Contains(x, y)) { InvalidateRect(layout.leftArrow); return; } } - internal void OnResize(Rectangle oldBounds) { + internal void OnResize(Rectangle oldBounds) + { Invalidate(); } /// /// Paints the parent rows /// - internal void Paint(Graphics g, Rectangle visualbounds, bool alignRight) { + internal void Paint(Graphics g, Rectangle visualbounds, bool alignRight) + { Rectangle bounds = visualbounds; // Paint the border around our bounds - if (borderWidth > 0) { + if (borderWidth > 0) + { PaintBorder(g, bounds); bounds.Inflate(-borderWidth, -borderWidth); } @@ -535,7 +604,8 @@ internal void Paint(Graphics g, Rectangle visualbounds, bool alignRight) { PaintParentRows(g, bounds, alignRight); } - private void PaintBorder(Graphics g, Rectangle bounds) { + private void PaintBorder(Graphics g, Rectangle bounds) + { Rectangle border = bounds; // top @@ -548,7 +618,7 @@ private void PaintBorder(Graphics g, Rectangle bounds) { // left border = new Rectangle(bounds.X, bounds.Y + borderWidth, - borderWidth, bounds.Height - 2*borderWidth); + borderWidth, bounds.Height - 2 * borderWidth); g.FillRectangle(borderBrush, border); // right @@ -558,21 +628,25 @@ private void PaintBorder(Graphics g, Rectangle bounds) { // will return the width of the text box that will fit all the // tables names - private int GetTableBoxWidth(Graphics g, Font font) { + private int GetTableBoxWidth(Graphics g, Font font) + { // try to make the font BOLD Font textFont = font; - try { + try + { textFont = new Font(font, FontStyle.Bold); } - catch { + catch + { } int width = 0; - for (int row = 0; row < parentsCount; row ++) { - DataGridState dgs = (DataGridState) parents[row]; + for (int row = 0; row < parentsCount; row++) + { + DataGridState dgs = (DataGridState)parents[row]; // Graphics.MeasureString(...) returns different results for ": " than for " :" // string displayTableName = dgs.ListManager.GetListName() + " :"; - int size = (int) g.MeasureString(displayTableName, textFont).Width; + int size = (int)g.MeasureString(displayTableName, textFont).Width; width = Math.Max(size, width); } @@ -581,17 +655,20 @@ private int GetTableBoxWidth(Graphics g, Font font) { // will return the width of the text box that will // fit all the column names - private int GetColBoxWidth(Graphics g, Font font, int colNum) { + private int GetColBoxWidth(Graphics g, Font font, int colNum) + { int width = 0; - for (int row = 0; row < parentsCount; row ++) { - DataGridState dgs = (DataGridState) parents[row]; + for (int row = 0; row < parentsCount; row++) + { + DataGridState dgs = (DataGridState)parents[row]; GridColumnStylesCollection columns = dgs.GridColumnStyles; - if (colNum < columns.Count) { + if (colNum < columns.Count) + { // Graphics.MeasureString(...) returns different results for ": " than for " :" // string colName = columns[colNum].HeaderText + " :"; - int size = (int) g.MeasureString(colName, font).Width; + int size = (int)g.MeasureString(colName, font).Width; width = Math.Max(size, width); } } @@ -601,13 +678,16 @@ private int GetColBoxWidth(Graphics g, Font font, int colNum) { // will return the width of the best fit for the column // - private int GetColDataBoxWidth(Graphics g, int colNum) { + private int GetColDataBoxWidth(Graphics g, int colNum) + { int width = 0; - for (int row = 0; row < parentsCount; row ++) { - DataGridState dgs = (DataGridState) parents[row]; + for (int row = 0; row < parentsCount; row++) + { + DataGridState dgs = (DataGridState)parents[row]; GridColumnStylesCollection columns = dgs.GridColumnStyles; - if (colNum < columns.Count) { - object value = columns[colNum].GetColumnValueAtRow((CurrencyManager) dataGrid.BindingContext[dgs.DataSource, dgs.DataMember], + if (colNum < columns.Count) + { + object value = columns[colNum].GetColumnValueAtRow((CurrencyManager)dataGrid.BindingContext[dgs.DataSource, dgs.DataMember], dgs.LinkingRow.RowNumber); int size = columns[colNum].GetPreferredSize(g, value).Width; width = Math.Max(size, width); @@ -617,21 +697,25 @@ private int GetColDataBoxWidth(Graphics g, int colNum) { } // will return the count of the table with the largest number of columns - private int ColsCount() { + private int ColsCount() + { int colNum = 0; - for (int row = 0; row < parentsCount; row ++) { - DataGridState dgs = (DataGridState) parents[row]; + for (int row = 0; row < parentsCount; row++) + { + DataGridState dgs = (DataGridState)parents[row]; colNum = Math.Max(colNum, dgs.GridColumnStyles.Count); } return colNum; } // will return the total width required to paint the parentRows - private int TotalWidth(int tableNameBoxWidth, int[] colsNameWidths, int[] colsDataWidths) { + private int TotalWidth(int tableNameBoxWidth, int[] colsNameWidths, int[] colsDataWidths) + { int totalWidth = 0; totalWidth += tableNameBoxWidth; Debug.Assert(colsNameWidths.Length == colsDataWidths.Length, "both arrays are as long as the largest column count in dgs"); - for (int i = 0; i < colsNameWidths.Length; i ++) { + for (int i = 0; i < colsNameWidths.Length; i++) + { totalWidth += colsNameWidths[i]; totalWidth += colsDataWidths[i]; } @@ -644,21 +728,25 @@ private int TotalWidth(int tableNameBoxWidth, int[] colsNameWidths, int[] colsDa // computes the layout for the parent rows // - private void ComputeLayout(Rectangle bounds, int tableNameBoxWidth, int[] colsNameWidths, int[] colsDataWidths) { + private void ComputeLayout(Rectangle bounds, int tableNameBoxWidth, int[] colsNameWidths, int[] colsDataWidths) + { int totalWidth = TotalWidth(tableNameBoxWidth, colsNameWidths, colsDataWidths); - if (totalWidth > bounds.Width) { + if (totalWidth > bounds.Width) + { layout.leftArrow = new Rectangle(bounds.X, bounds.Y, 15, bounds.Height); layout.data = new Rectangle(layout.leftArrow.Right, bounds.Y, bounds.Width - 30, bounds.Height); layout.rightArrow = new Rectangle(layout.data.Right, bounds.Y, 15, bounds.Height); } - else { + else + { layout.data = bounds; layout.leftArrow = Rectangle.Empty; layout.rightArrow = Rectangle.Empty; } } - private void PaintParentRows(Graphics g, Rectangle bounds, bool alignToRight) { + private void PaintParentRows(Graphics g, Rectangle bounds, bool alignToRight) + { // variables needed for aligning the table and column names int tableNameBoxWidth = 0; int numCols = ColsCount(); @@ -668,18 +756,22 @@ private void PaintParentRows(Graphics g, Rectangle bounds, bool alignToRight) { // compute the size of the box that will contain the tableName // if (dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.TableName || - dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.Both) { + dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.Both) + { tableNameBoxWidth = GetTableBoxWidth(g, dataGrid.Font); } // initialiaze the arrays that contain the column names and the column size // - for (int i = 0; i < numCols; i++) { + for (int i = 0; i < numCols; i++) + { if (dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.ColumnName || - dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.Both) { + dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.Both) + { colsNameWidths[i] = GetColBoxWidth(g, dataGrid.Font, i); } - else { + else + { colsNameWidths[i] = 0; } colsDataWidths[i] = GetColDataBoxWidth(g, i); @@ -700,12 +792,13 @@ private void PaintParentRows(Graphics g, Rectangle bounds, bool alignToRight) { // paint the parent rows: // Rectangle rowBounds = layout.data; - for (int row = 0; row < parentsCount; ++row) { - rowBounds.Height = (int) rowHeights[row]; + for (int row = 0; row < parentsCount; ++row) + { + rowBounds.Height = (int)rowHeights[row]; if (rowBounds.Y > bounds.Bottom) break; int paintedWidth = PaintRow(g, rowBounds, row, dataGrid.Font, alignToRight, tableNameBoxWidth, colsNameWidths, colsDataWidths); - if (row == parentsCount-1) + if (row == parentsCount - 1) break; // draw the grid line below @@ -722,11 +815,14 @@ private void PaintParentRows(Graphics g, Rectangle bounds, bool alignToRight) { } } - private Bitmap GetBitmap(string bitmapName) { - try { + private Bitmap GetBitmap(string bitmapName) + { + try + { return DpiHelper.GetBitmapFromIcon(typeof(DataGridParentRows), bitmapName); } - catch (Exception e) { + catch (Exception e) + { Debug.Fail("Failed to load bitmap: " + bitmapName, e.ToString()); return null; } @@ -759,7 +855,7 @@ private void PaintBitmap(Graphics g, Bitmap b, Rectangle bounds) ImageAttributes attr = new ImageAttributes(); this.colorMap[0].NewColor = this.ForeColor; attr.SetRemapTable(colorMap, ColorAdjustType.Bitmap); - g.DrawImage(b, bmpRect, 0, 0, bmpRect.Width, bmpRect.Height,GraphicsUnit.Pixel, attr); + g.DrawImage(b, bmpRect, 0, 0, bmpRect.Width, bmpRect.Height, GraphicsUnit.Pixel, attr); attr.Dispose(); } @@ -793,14 +889,17 @@ private void PaintLeftArrow(Graphics g, Rectangle bounds, bool alignToRight) if (downLeftArrow) { PaintDownButton(g, bounds); - layout.leftArrow.Inflate(-1,-1); - lock (bmp) { + layout.leftArrow.Inflate(-1, -1); + lock (bmp) + { PaintBitmap(g, bmp, bounds); } - layout.leftArrow.Inflate(1,1); + layout.leftArrow.Inflate(1, 1); } - else { - lock (bmp) { + else + { + lock (bmp) + { PaintBitmap(g, bmp, bounds); } } @@ -822,39 +921,46 @@ private void PaintRightArrow(Graphics g, Rectangle bounds, bool alignToRight) if (downRightArrow) { PaintDownButton(g, bounds); - layout.rightArrow.Inflate(-1,-1); - lock (bmp) { + layout.rightArrow.Inflate(-1, -1); + lock (bmp) + { PaintBitmap(g, bmp, bounds); } - layout.rightArrow.Inflate(1,1); + layout.rightArrow.Inflate(1, 1); } - else { - lock (bmp) { + else + { + lock (bmp) + { PaintBitmap(g, bmp, bounds); } } } private int PaintRow(Graphics g, Rectangle bounds, int row, Font font, bool alignToRight, - int tableNameBoxWidth, int[] colsNameWidths, int[] colsDataWidths) { - DataGridState dgs = (DataGridState) parents[row]; + int tableNameBoxWidth, int[] colsNameWidths, int[] colsDataWidths) + { + DataGridState dgs = (DataGridState)parents[row]; Rectangle paintBounds = bounds; Rectangle rowBounds = bounds; - paintBounds.Height = (int) rowHeights[row]; - rowBounds.Height = (int) rowHeights[row]; + paintBounds.Height = (int)rowHeights[row]; + rowBounds.Height = (int)rowHeights[row]; int paintedWidth = 0; // used for scrolling: when paiting, we will skip horizOffset cells in the dataGrid ParentRows int skippedCells = 0; // paint the table name - if ( dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.TableName || - dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.Both) { - if (skippedCells < horizOffset) { + if (dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.TableName || + dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.Both) + { + if (skippedCells < horizOffset) + { // skip this - skippedCells ++; + skippedCells++; } - else { + else + { paintBounds.Width = Math.Min(paintBounds.Width, tableNameBoxWidth); paintBounds.X = MirrorRect(bounds, paintBounds, alignToRight); string displayTableName = dgs.ListManager.GetListName() + ": "; @@ -871,7 +977,8 @@ private int PaintRow(Graphics g, Rectangle bounds, int row, Font font, bool alig paintedWidth += PaintColumns(g, rowBounds, dgs, font, alignToRight, colsNameWidths, colsDataWidths, skippedCells); // paint the possible space left after columns - if (paintedWidth < bounds.Width) { + if (paintedWidth < bounds.Width) + { paintBounds.X = bounds.X + paintedWidth; paintBounds.Width = bounds.Width - paintedWidth; paintBounds.X = MirrorRect(bounds, paintBounds, alignToRight); @@ -881,23 +988,28 @@ private int PaintRow(Graphics g, Rectangle bounds, int row, Font font, bool alig } private int PaintColumns(Graphics g, Rectangle bounds, DataGridState dgs, Font font, bool alignToRight, - int[] colsNameWidths, int[] colsDataWidths, int skippedCells) { + int[] colsNameWidths, int[] colsDataWidths, int skippedCells) + { Rectangle paintBounds = bounds; Rectangle rowBounds = bounds; GridColumnStylesCollection cols = dgs.GridColumnStyles; int cx = 0; - for (int i = 0; i < cols.Count; i ++) { + for (int i = 0; i < cols.Count; i++) + { if (cx >= bounds.Width) break; // paint the column name, if we have to if (dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.ColumnName || - dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.Both) { - if (skippedCells < horizOffset) { + dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.Both) + { + if (skippedCells < horizOffset) + { // skip this column } - else { + else + { paintBounds.X = bounds.X + cx; paintBounds.Width = Math.Min(bounds.Width - cx, colsNameWidths[i]); paintBounds.X = MirrorRect(bounds, paintBounds, alignToRight); @@ -912,10 +1024,13 @@ private int PaintColumns(Graphics g, Rectangle bounds, DataGridState dgs, Font f if (cx >= bounds.Width) break; - if (skippedCells < horizOffset) { + if (skippedCells < horizOffset) + { // skip this cell - skippedCells ++; - } else { + skippedCells++; + } + else + { // paint the cell contents paintBounds.X = bounds.X + cx; paintBounds.Width = Math.Min(bounds.Width - cx, colsDataWidths[i]); @@ -923,7 +1038,7 @@ private int PaintColumns(Graphics g, Rectangle bounds, DataGridState dgs, Font f // when we paint the data grid parent rows, we want to paint the data at the position // stored in the currency manager. - cols[i].Paint(g, paintBounds, (CurrencyManager) dataGrid.BindingContext[dgs.DataSource, dgs.DataMember], + cols[i].Paint(g, paintBounds, (CurrencyManager)dataGrid.BindingContext[dgs.DataSource, dgs.DataMember], dataGrid.BindingContext[dgs.DataSource, dgs.DataMember].Position, BackBrush, ForeBrush, alignToRight); cx += paintBounds.Width; @@ -942,7 +1057,7 @@ private int PaintColumns(Graphics g, Rectangle bounds, DataGridState dgs, Font f // put 3 pixels in between columns // see DonnaWa // - if ( i < cols.Count - 1) + if (i < cols.Count - 1) { paintBounds.X = bounds.X + cx; paintBounds.Width = Math.Min(bounds.Width - cx, 3); @@ -961,19 +1076,23 @@ private int PaintColumns(Graphics g, Rectangle bounds, DataGridState dgs, Font f /// Draws on the screen the text. It is used only to paint the Table Name and the column Names /// Returns the width of bounding rectangle that was passed in /// - private int PaintText(Graphics g, Rectangle textBounds, string text, Font font, bool bold, bool alignToRight) { + private int PaintText(Graphics g, Rectangle textBounds, string text, Font font, bool bold, bool alignToRight) + { Font textFont = font; if (bold) - try { + try + { textFont = new Font(font, FontStyle.Bold); - } catch {} + } + catch { } else textFont = font; // right now, we paint the entire box, cause it will be used anyway g.FillRectangle(BackBrush, textBounds); StringFormat format = new StringFormat(); - if (alignToRight) { + if (alignToRight) + { format.FormatFlags |= StringFormatFlags.DirectionRightToLeft; format.Alignment = StringAlignment.Far; } @@ -991,7 +1110,8 @@ private int PaintText(Graphics g, Rectangle textBounds, string text, Font font, // will return the X coordinate of the containedRect mirrored within the surroundingRect // according to the value of alignToRight - private int MirrorRect(Rectangle surroundingRect, Rectangle containedRect, bool alignToRight) { + private int MirrorRect(Rectangle surroundingRect, Rectangle containedRect, bool alignToRight) + { Debug.Assert(containedRect.X >= surroundingRect.X && containedRect.Right <= surroundingRect.Right, "containedRect is not contained in surroundingRect"); if (alignToRight) return surroundingRect.Right - containedRect.Right + surroundingRect.X; @@ -999,18 +1119,21 @@ private int MirrorRect(Rectangle surroundingRect, Rectangle containedRect, bool return containedRect.X; } - private class Layout { + private class Layout + { public Rectangle data; public Rectangle leftArrow; public Rectangle rightArrow; - public Layout() { + public Layout() + { data = Rectangle.Empty; leftArrow = Rectangle.Empty; rightArrow = Rectangle.Empty; } - public override string ToString() { + public override string ToString() + { StringBuilder sb = new StringBuilder(200); sb.Append("ParentRows Layout: \n"); sb.Append("data = "); @@ -1026,61 +1149,80 @@ public override string ToString() { } [ComVisible(true)] - protected internal class DataGridParentRowsAccessibleObject : AccessibleObject { + protected internal class DataGridParentRowsAccessibleObject : AccessibleObject + { DataGridParentRows owner = null; - public DataGridParentRowsAccessibleObject(DataGridParentRows owner) : base() { + public DataGridParentRowsAccessibleObject(DataGridParentRows owner) : base() + { Debug.Assert(owner != null, "DataGridParentRowsAccessibleObject must have a valid owner"); this.owner = owner; } - internal DataGridParentRows Owner { - get { + internal DataGridParentRows Owner + { + get + { return owner; } } - public override Rectangle Bounds { - get { + public override Rectangle Bounds + { + get + { return owner.dataGrid.RectangleToScreen(owner.dataGrid.ParentRowsBounds); } } - public override string DefaultAction { - get { + public override string DefaultAction + { + get + { return SR.AccDGNavigateBack; } } - public override string Name { - get { + public override string Name + { + get + { return SR.AccDGParentRows; } } - public override AccessibleObject Parent { - get { + public override AccessibleObject Parent + { + get + { return owner.dataGrid.AccessibilityObject; } } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { return AccessibleRole.List; } } - public override AccessibleStates State { - get { + public override AccessibleStates State + { + get + { AccessibleStates state = AccessibleStates.ReadOnly; - if (owner.parentsCount == 0) { + if (owner.parentsCount == 0) + { state |= AccessibleStates.Invisible; } - if (owner.dataGrid.ParentRowsVisible) { + if (owner.dataGrid.ParentRowsVisible) + { state |= AccessibleStates.Expanded; } - else { + else + { state |= AccessibleStates.Collapsed; } @@ -1088,21 +1230,26 @@ public override AccessibleStates State { } } - public override string Value { - get { + public override string Value + { + get + { return null; } } - - public override void DoDefaultAction() { + + public override void DoDefaultAction() + { owner.dataGrid.NavigateBack(); } - public override AccessibleObject GetChild(int index) { + public override AccessibleObject GetChild(int index) + { return ((DataGridState)owner.parents[index]).ParentRowAccessibleObject; } - public override int GetChildCount() { + public override int GetChildCount() + { return owner.parentsCount; } @@ -1110,19 +1257,24 @@ public override int GetChildCount() { /// Returns the currently focused child, if any. /// Returns this if the object itself is focused. /// - public override AccessibleObject GetFocused() { + public override AccessibleObject GetFocused() + { return null; } - internal AccessibleObject GetNext(AccessibleObject child) { + internal AccessibleObject GetNext(AccessibleObject child) + { int children = GetChildCount(); bool hit = false; - for (int i=0; i=0; i--) { - if (hit) { + for (int i = children - 1; i >= 0; i--) + { + if (hit) + { return GetChild(i); } - if (GetChild(i) == child) { + if (GetChild(i) == child) + { hit = true; } } @@ -1149,8 +1305,10 @@ internal AccessibleObject GetPrev(AccessibleObject child) { /// /// Navigate to the next or previous grid entry. /// - public override AccessibleObject Navigate(AccessibleNavigation navdir) { - switch (navdir) { + public override AccessibleObject Navigate(AccessibleNavigation navdir) + { + switch (navdir) + { case AccessibleNavigation.Right: case AccessibleNavigation.Next: case AccessibleNavigation.Down: @@ -1160,12 +1318,14 @@ public override AccessibleObject Navigate(AccessibleNavigation navdir) { case AccessibleNavigation.Previous: return Parent.GetChild(GetChildCount() - 1); case AccessibleNavigation.FirstChild: - if (GetChildCount() > 0) { + if (GetChildCount() > 0) + { return GetChild(0); } break; case AccessibleNavigation.LastChild: - if (GetChildCount() > 0) { + if (GetChildCount() > 0) + { return GetChild(GetChildCount() - 1); } break; @@ -1176,7 +1336,8 @@ public override AccessibleObject Navigate(AccessibleNavigation navdir) { } - public override void Select(AccessibleSelection flags) { + public override void Select(AccessibleSelection flags) + { } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRelationshipRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRelationshipRow.cs index 5ec5f8d8681..7a0cb8844fa 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRelationshipRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRelationshipRow.cs @@ -2,15 +2,16 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Runtime.InteropServices; - + using System.Windows.Forms; using System.ComponentModel; using System.Drawing; - + using Microsoft.Win32; using System.Diagnostics; using System.Collections; @@ -20,14 +21,15 @@ namespace System.Windows.Forms { /// This class fully encapsulates the painting logic for a row /// appearing in a DataGrid. /// - internal class DataGridRelationshipRow : DataGridRow { - private const bool defaultOpen = false; - private const int expandoBoxWidth = 14; - private const int indentWidth = 20; + internal class DataGridRelationshipRow : DataGridRow + { + private const bool defaultOpen = false; + private const int expandoBoxWidth = 14; + private const int indentWidth = 20; // private const int relationshipSpacing = 1; - private const int triangleSize = 5; + private const int triangleSize = 5; - private bool expanded = defaultOpen; + private bool expanded = defaultOpen; // private bool hasRelationships = false; // private Font linkFont = null; // private new DataGrid dataGrid; // Currently used only to obtain a Graphics object for measuring text @@ -42,7 +44,8 @@ internal class DataGridRelationshipRow : DataGridRow { // private int focusedTextWidth; public DataGridRelationshipRow(DataGrid dataGrid, DataGridTableStyle dgTable, int rowNumber) - : base(dataGrid, dgTable, rowNumber) { + : base(dataGrid, dgTable, rowNumber) + { // this.dataGrid = dataGrid; // linkFont = dataGrid.LinkFont; // relationshipHeight = dataGrid.LinkFontHeight + this.dgTable.relationshipSpacing; @@ -52,7 +55,8 @@ public DataGridRelationshipRow(DataGrid dataGrid, DataGridTableStyle dgTable, in // } } - internal protected override int MinimumRowHeight(GridColumnStylesCollection cols) { + internal protected override int MinimumRowHeight(GridColumnStylesCollection cols) + { /* if (DataGrid != null && DataGrid.LinkFontHeight + this.dgTable.relationshipSpacing != relationshipHeight) { relationshipRect = Rectangle.Empty; @@ -63,7 +67,8 @@ internal protected override int MinimumRowHeight(GridColumnStylesCollection cols return base.MinimumRowHeight(cols) + (this.expanded ? GetRelationshipRect().Height : 0); } - internal protected override int MinimumRowHeight(DataGridTableStyle dgTable) { + internal protected override int MinimumRowHeight(DataGridTableStyle dgTable) + { /* if (DataGrid != null && DataGrid.LinkFontHeight + this.dgTable.relationshipSpacing != relationshipHeight) { relationshipRect = Rectangle.Empty; @@ -78,11 +83,14 @@ internal protected override int MinimumRowHeight(DataGridTableStyle dgTable) { // = Properties // =------------------------------------------------------------------ - public virtual bool Expanded { - get { + public virtual bool Expanded + { + get + { return expanded; } - set { + set + { if (expanded == value) return; if (expanded) @@ -128,11 +136,14 @@ private int BorderWidth { } #endif //FALSE - private int FocusedRelation { - get { + private int FocusedRelation + { + get + { return this.dgTable.FocusedRelation; } - set { + set + { dgTable.FocusedRelation = value; } } @@ -141,27 +152,32 @@ private int FocusedRelation { // = Methods // =------------------------------------------------------------------ - private void Collapse() { + private void Collapse() + { Debug.Assert(this.dgTable.DataGrid.AllowNavigation, "how can the user collapse the relations if the grid does not allow navigation?"); - if (expanded) { + if (expanded) + { expanded = false; // relationshipRect = Rectangle.Empty; FocusedRelation = -1; DataGrid.OnRowHeightChanged(this); } } - - protected override AccessibleObject CreateAccessibleObject() { + + protected override AccessibleObject CreateAccessibleObject() + { return new DataGridRelationshipRowAccessibleObject(this); } - private void Expand() { + private void Expand() + { Debug.Assert(this.dgTable.DataGrid.AllowNavigation, "how can the user expand the relations if the grid does not allow navigation?"); if (expanded == false && DataGrid != null && this.dgTable != null - && this.dgTable.RelationsList.Count > 0) { + && this.dgTable.RelationsList.Count > 0) + { expanded = true; FocusedRelation = -1; @@ -170,15 +186,18 @@ private void Expand() { } } - public override int Height { - get { + public override int Height + { + get + { int height = base.Height; if (expanded) return height + GetRelationshipRect().Height; else return height; } - set { + set + { // we should use the RelationshipRect only when the row is expanded if (expanded) base.Height = value - GetRelationshipRect().Height; @@ -189,7 +208,8 @@ public override int Height { // so the edit box will not paint under the // grid line of the row - public override Rectangle GetCellBounds(int col) { + public override Rectangle GetCellBounds(int col) + { Rectangle cellBounds = base.GetCellBounds(col); // decrement base.Height by 1, so the edit box will not // paint over the bottom line. @@ -201,7 +221,8 @@ public override Rectangle GetCellBounds(int col) { /// Given an origin, this procedure returns /// a rectangle that describes the location of an outline box. /// - private Rectangle GetOutlineRect(int xOrigin, int yOrigin) { + private Rectangle GetOutlineRect(int xOrigin, int yOrigin) + { Rectangle outline = new Rectangle(xOrigin + 2, yOrigin + 2, 9, @@ -209,15 +230,18 @@ private Rectangle GetOutlineRect(int xOrigin, int yOrigin) { return outline; } - public override Rectangle GetNonScrollableArea() { - if (expanded) { + public override Rectangle GetNonScrollableArea() + { + if (expanded) + { return GetRelationshipRect(); } else return Rectangle.Empty; } - private Rectangle GetRelationshipRect() { + private Rectangle GetRelationshipRect() + { Debug.Assert(this.expanded, "we should need this rectangle only when the row is expanded"); Rectangle ret = this.dgTable.RelationshipRect; ret.Y = base.Height - this.dgTable.BorderWidth; @@ -258,10 +282,12 @@ private Rectangle GetRelationshipRect() { #endif// FALSE - private Rectangle GetRelationshipRectWithMirroring() { + private Rectangle GetRelationshipRectWithMirroring() + { Rectangle relRect = GetRelationshipRect(); bool rowHeadersVisible = this.dgTable.IsDefault ? this.DataGrid.RowHeadersVisible : this.dgTable.RowHeadersVisible; - if (rowHeadersVisible) { + if (rowHeadersVisible) + { int rowHeaderWidth = this.dgTable.IsDefault ? this.DataGrid.RowHeaderWidth : this.dgTable.RowHeaderWidth; relRect.X += DataGrid.GetRowHeaderRect().X + rowHeaderWidth; } @@ -274,32 +300,40 @@ private Rectangle GetRelationshipRectWithMirroring() { /// area. The coordinates are normalized to the rectangle's top /// left point. /// - private bool PointOverPlusMinusGlyph(int x, int y, Rectangle rowHeaders, bool alignToRight) { + private bool PointOverPlusMinusGlyph(int x, int y, Rectangle rowHeaders, bool alignToRight) + { if (dgTable == null || dgTable.DataGrid == null || !dgTable.DataGrid.AllowNavigation) return false; Rectangle insideRowHeaders = rowHeaders; - if (!this.DataGrid.FlatMode) { - insideRowHeaders.Inflate(-1,-1); + if (!this.DataGrid.FlatMode) + { + insideRowHeaders.Inflate(-1, -1); } Rectangle outline = GetOutlineRect(insideRowHeaders.Right - expandoBoxWidth, 0); outline.X = MirrorRectangle(outline.X, outline.Width, insideRowHeaders, alignToRight); - return outline.Contains(x,y); + return outline.Contains(x, y); } - public override bool OnMouseDown(int x, int y, Rectangle rowHeaders, bool alignToRight) { + public override bool OnMouseDown(int x, int y, Rectangle rowHeaders, bool alignToRight) + { bool rowHeadersVisible = this.dgTable.IsDefault ? this.DataGrid.RowHeadersVisible : this.dgTable.RowHeadersVisible; - if (rowHeadersVisible) { - if (PointOverPlusMinusGlyph(x,y,rowHeaders, alignToRight)) { - if (this.dgTable.RelationsList.Count == 0) { + if (rowHeadersVisible) + { + if (PointOverPlusMinusGlyph(x, y, rowHeaders, alignToRight)) + { + if (this.dgTable.RelationsList.Count == 0) + { return false; } - else if (expanded) { + else if (expanded) + { Collapse(); } - else { + else + { Expand(); } DataGrid.OnNodeClick(EventArgs.Empty); @@ -313,9 +347,11 @@ public override bool OnMouseDown(int x, int y, Rectangle rowHeaders, bool alignT // hit test for relationships Rectangle relRect = GetRelationshipRectWithMirroring(); - if (relRect.Contains(x, y)) { + if (relRect.Contains(x, y)) + { int r = RelationFromY(y); - if (r != -1) { + if (r != -1) + { // first, reset the FocusedRelation FocusedRelation = -1; DataGrid.NavigateTo(((string)this.dgTable.RelationsList[r]), this, true); @@ -327,13 +363,15 @@ public override bool OnMouseDown(int x, int y, Rectangle rowHeaders, bool alignT return base.OnMouseDown(x, y, rowHeaders, alignToRight); } - public override bool OnMouseMove(int x, int y, Rectangle rowHeaders, bool alignToRight) { + public override bool OnMouseMove(int x, int y, Rectangle rowHeaders, bool alignToRight) + { if (!expanded) return false; Rectangle relRect = GetRelationshipRectWithMirroring(); - if (relRect.Contains(x, y)) { + if (relRect.Contains(x, y)) + { this.DataGrid.Cursor = Cursors.Hand; return true; } @@ -344,7 +382,8 @@ public override bool OnMouseMove(int x, int y, Rectangle rowHeaders, bool alignT // this function will not invalidate all of the // row - public override void OnMouseLeft(Rectangle rowHeaders, bool alignToRight) { + public override void OnMouseLeft(Rectangle rowHeaders, bool alignToRight) + { if (!expanded) return; @@ -352,17 +391,20 @@ public override void OnMouseLeft(Rectangle rowHeaders, bool alignToRight) { relRect.X += rowHeaders.X + this.dgTable.RowHeaderWidth; relRect.X = MirrorRelationshipRectangle(relRect, rowHeaders, alignToRight); - if (FocusedRelation != -1) { + if (FocusedRelation != -1) + { InvalidateRowRect(relRect); FocusedRelation = -1; } } - public override void OnMouseLeft() { + public override void OnMouseLeft() + { if (!expanded) return; - if (FocusedRelation != -1) { + if (FocusedRelation != -1) + { InvalidateRow(); FocusedRelation = -1; } @@ -372,12 +414,14 @@ public override void OnMouseLeft() { /// /// Called by the DataGrid when a keypress occurs on a row with "focus." /// - public override bool OnKeyPress(Keys keyData) { + public override bool OnKeyPress(Keys keyData) + { // ignore the shift key if it is not paired w/ the TAB key if ((keyData & Keys.Modifiers) == Keys.Shift && (keyData & Keys.KeyCode) != Keys.Tab) return false; - switch (keyData & Keys.KeyCode) { + switch (keyData & Keys.KeyCode) + { case Keys.F5: if (dgTable == null || dgTable.DataGrid == null || !dgTable.DataGrid.AllowNavigation) return false; @@ -396,7 +440,8 @@ public override bool OnKeyPress(Keys keyData) { else return base.OnKeyPress(keyData); case Keys.Enter: - if (FocusedRelation != -1) { + if (FocusedRelation != -1) + { // somebody set the relation number up already // navigate to the relation DataGrid.NavigateTo(((string)this.dgTable.RelationsList[FocusedRelation]), this, true); @@ -419,7 +464,8 @@ public override bool OnKeyPress(Keys keyData) { // will reset the FocusedRelation and will invalidate the // rectangle so that the linkFont is no longer shown - internal override void LoseChildFocus(Rectangle rowHeaders, bool alignToRight) { + internal override void LoseChildFocus(Rectangle rowHeaders, bool alignToRight) + { // we only invalidate stuff if the row is expanded. if (FocusedRelation == -1 || !expanded) return; @@ -441,7 +487,8 @@ internal override void LoseChildFocus(Rectangle rowHeaders, bool alignToRight) { // it passes it to the row. If the dataRelationshipRow can become focused, // then it eats the TAB key, otherwise it will give it back to the dataGrid. // - internal override bool ProcessTabKey(Keys keyData, Rectangle rowHeaders, bool alignToRight) { + internal override bool ProcessTabKey(Keys keyData, Rectangle rowHeaders, bool alignToRight) + { Debug.Assert((keyData & Keys.Control) != Keys.Control, "the DataGridRelationshipRow only handles TAB and TAB-SHIFT"); Debug.Assert((keyData & Keys.Alt) != Keys.Alt, "the DataGridRelationshipRow only handles TAB and TAB-SHIFT"); @@ -454,8 +501,10 @@ internal override bool ProcessTabKey(Keys keyData, Rectangle rowHeaders, bool al if (!expanded) Expand(); - if ((keyData & Keys.Shift) == Keys.Shift) { - if (FocusedRelation == 0) { + if ((keyData & Keys.Shift) == Keys.Shift) + { + if (FocusedRelation == 0) + { // if user hits TAB-SHIFT and the focus was on the first relationship then // reset FocusedRelation and let the dataGrid use the key // @@ -476,11 +525,13 @@ internal override bool ProcessTabKey(Keys keyData, Rectangle rowHeaders, bool al // set of relationships FocusedRelation = this.dgTable.RelationsList.Count - 1; else - FocusedRelation --; + FocusedRelation--; return true; } - else { - if (FocusedRelation == this.dgTable.RelationsList.Count - 1) { + else + { + if (FocusedRelation == this.dgTable.RelationsList.Count - 1) + { // if the user hits TAB and the focus was on the last relationship then // reset FocusedRelation and let the dataGrid use the key // @@ -496,7 +547,7 @@ internal override bool ProcessTabKey(Keys keyData, Rectangle rowHeaders, bool al relRect.X = MirrorRelationshipRectangle(relRect, rowHeaders, alignToRight); InvalidateRowRect(relRect); - FocusedRelation ++; + FocusedRelation++; return true; } } @@ -504,7 +555,8 @@ internal override bool ProcessTabKey(Keys keyData, Rectangle rowHeaders, bool al /// /// Paints the row. /// - public override int Paint(Graphics g, Rectangle bounds, Rectangle trueRowBounds, int firstVisibleColumn, int numVisibleColumns) { + public override int Paint(Graphics g, Rectangle bounds, Rectangle trueRowBounds, int firstVisibleColumn, int numVisibleColumns) + { return Paint(g, bounds, trueRowBounds, firstVisibleColumn, numVisibleColumns, false); } @@ -513,8 +565,10 @@ public override int Paint(Graphics g, Rectangle trueRowBounds, // real row bounds. int firstVisibleColumn, int numVisibleColumns, - bool alignToRight) { - if (CompModSwitches.DGRelationShpRowPaint.TraceVerbose) Debug.WriteLine("Painting row " + RowNumber.ToString(CultureInfo.InvariantCulture) + " with bounds " + bounds.ToString()); + bool alignToRight) + { + if (CompModSwitches.DGRelationShpRowPaint.TraceVerbose) + Debug.WriteLine("Painting row " + RowNumber.ToString(CultureInfo.InvariantCulture) + " with bounds " + bounds.ToString()); int bWidth = this.dgTable.BorderWidth; // paint the data cells @@ -527,7 +581,8 @@ public override int Paint(Graphics g, if (bWidth > 0) PaintBottomBorder(g, dataBounds, dataWidth, bWidth, alignToRight); - if (expanded && this.dgTable.RelationsList.Count > 0) { + if (expanded && this.dgTable.RelationsList.Count > 0) + { // paint the relationships Rectangle relationBounds = new Rectangle(trueRowBounds.X, dataBounds.Bottom, @@ -544,7 +599,8 @@ public override int Paint(Graphics g, } protected override void PaintCellContents(Graphics g, Rectangle cellBounds, DataGridColumnStyle column, - Brush backBr, Brush foreBrush, bool alignToRight) { + Brush backBr, Brush foreBrush, bool alignToRight) + { CurrencyManager listManager = DataGrid.ListManager; // painting the error.. @@ -553,12 +609,14 @@ protected override void PaintCellContents(Graphics g, Rectangle cellBounds, Data Rectangle bounds = cellBounds; object errInfo = DataGrid.ListManager[this.number]; if (errInfo is IDataErrorInfo) - errString = ((IDataErrorInfo) errInfo)[column.PropertyDescriptor.Name]; + errString = ((IDataErrorInfo)errInfo)[column.PropertyDescriptor.Name]; - if (!string.IsNullOrEmpty(errString)) { + if (!string.IsNullOrEmpty(errString)) + { Bitmap bmp = GetErrorBitmap(); Rectangle errRect; - lock (bmp) { + lock (bmp) + { errRect = PaintIcon(g, bounds, true, alignToRight, bmp, backBr); } // paint the errors correctly when RTL = true @@ -566,21 +624,23 @@ protected override void PaintCellContents(Graphics g, Rectangle cellBounds, Data bounds.Width -= errRect.Width + xOffset; else bounds.X += errRect.Width + xOffset; - DataGrid.ToolTipProvider.AddToolTip(errString, (IntPtr)(DataGrid.ToolTipId ++), errRect); + DataGrid.ToolTipProvider.AddToolTip(errString, (IntPtr)(DataGrid.ToolTipId++), errRect); } column.Paint(g, bounds, listManager, this.RowNumber, backBr, foreBrush, alignToRight); } - public override void PaintHeader(Graphics g, Rectangle bounds, bool alignToRight, bool isDirty) { + public override void PaintHeader(Graphics g, Rectangle bounds, bool alignToRight, bool isDirty) + { DataGrid grid = this.DataGrid; Rectangle insideBounds = bounds; - if (!grid.FlatMode) { + if (!grid.FlatMode) + { ControlPaint.DrawBorder3D(g, insideBounds, Border3DStyle.RaisedInner); - insideBounds.Inflate(-1,-1); + insideBounds.Inflate(-1, -1); } if (this.dgTable.IsDefault) @@ -589,14 +649,16 @@ public override void PaintHeader(Graphics g, Rectangle bounds, bool alignToRight PaintHeaderInside(g, insideBounds, this.dgTable.HeaderBackBrush, alignToRight, isDirty); } - public void PaintHeaderInside(Graphics g, Rectangle bounds, Brush backBr, bool alignToRight, bool isDirty) { + public void PaintHeaderInside(Graphics g, Rectangle bounds, Brush backBr, bool alignToRight, bool isDirty) + { // paint the row header bool paintPlusMinus = dgTable.RelationsList.Count > 0 && dgTable.DataGrid.AllowNavigation; int rowHeaderBoundsX = MirrorRectangle(bounds.X, bounds.Width - (paintPlusMinus ? expandoBoxWidth : 0), bounds, alignToRight); - if (!alignToRight) Debug.Assert(bounds.X == rowHeaderBoundsX, "what's up doc?"); + if (!alignToRight) + Debug.Assert(bounds.X == rowHeaderBoundsX, "what's up doc?"); Rectangle rowHeaderBounds = new Rectangle(rowHeaderBoundsX, bounds.Y, @@ -608,13 +670,15 @@ public void PaintHeaderInside(Graphics g, Rectangle bounds, Brush backBr, bool a // Paint the expando on the right int expandoBoxX = MirrorRectangle(bounds.X + rowHeaderBounds.Width, expandoBoxWidth, bounds, alignToRight); - if (!alignToRight) Debug.Assert(rowHeaderBounds.Right == expandoBoxX, "what's up doc?"); + if (!alignToRight) + Debug.Assert(rowHeaderBounds.Right == expandoBoxX, "what's up doc?"); Rectangle expandoBox = new Rectangle(expandoBoxX, bounds.Y, expandoBoxWidth, bounds.Height); - if (paintPlusMinus) { + if (paintPlusMinus) + { PaintPlusMinusGlyph(g, expandoBox, backBr, alignToRight); } @@ -624,7 +688,8 @@ public void PaintHeaderInside(Graphics g, Rectangle bounds, Brush backBr, bool a /// Paints the relationships below the data area. /// private void PaintRelations(Graphics g, Rectangle bounds, Rectangle trueRowBounds, - int dataWidth, int firstCol, int nCols, bool alignToRight) { + int dataWidth, int firstCol, int nCols, bool alignToRight) + { // Calculate the relationship rect. // relationshipRect = Rectangle.Empty; @@ -653,14 +718,16 @@ private void PaintRelations(Graphics g, Rectangle bounds, Rectangle trueRowBound int cy = PaintRelationText(g, relRect, alignToRight); - if (cy < relRect.Height) { + if (cy < relRect.Height) + { g.FillRectangle(GetBackBrush(), relRect.X, relRect.Y + cy, relRect.Width, relRect.Height - cy); } g.Clip = r; // paint any exposed area to the right or to the left (BI-DI) - if (paintedWidth < bounds.Width) { + if (paintedWidth < bounds.Width) + { int bWidth; if (this.dgTable.IsDefault) bWidth = this.DataGrid.GridLineWidth; @@ -673,7 +740,8 @@ private void PaintRelations(Graphics g, Rectangle bounds, Rectangle trueRowBound bounds.Height); // Paint the border to the right of each cell - if (bWidth > 0) { + if (bWidth > 0) + { Brush br; // if the user changed the gridLineColor on the dataGrid // from the defaultValue, then use that value; @@ -691,7 +759,8 @@ private void PaintRelations(Graphics g, Rectangle bounds, Rectangle trueRowBound } - private int PaintRelationText(Graphics g, Rectangle bounds, bool alignToRight) { + private int PaintRelationText(Graphics g, Rectangle bounds, bool alignToRight) + { g.FillRectangle(GetBackBrush(), bounds.X, bounds.Y, bounds.Width, System.Windows.Forms.DataGridTableStyle.relationshipSpacing); int relationshipHeight = this.dgTable.RelationshipHeight; @@ -699,7 +768,8 @@ private int PaintRelationText(Graphics g, Rectangle bounds, bool alignToRight) { bounds.Width, relationshipHeight); int cy = System.Windows.Forms.DataGridTableStyle.relationshipSpacing; - for (int r = 0; r < this.dgTable.RelationsList.Count; ++r) { + for (int r = 0; r < this.dgTable.RelationsList.Count; ++r) + { if (cy > bounds.Height) break; @@ -708,17 +778,19 @@ private int PaintRelationText(Graphics g, Rectangle bounds, bool alignToRight) { Font textFont = this.DataGrid.Font; textBrush = this.dgTable.IsDefault ? this.DataGrid.LinkBrush : this.dgTable.LinkBrush; textFont = this.DataGrid.LinkFont; - + g.FillRectangle(GetBackBrush(), textBounds); StringFormat format = new StringFormat(); - if (alignToRight) { + if (alignToRight) + { format.FormatFlags |= StringFormatFlags.DirectionRightToLeft; format.Alignment = StringAlignment.Far; } g.DrawString(((string)this.dgTable.RelationsList[r]), textFont, textBrush, textBounds, format); - if (r == FocusedRelation && this.number == this.DataGrid.CurrentCell.RowNumber) { + if (r == FocusedRelation && this.number == this.DataGrid.CurrentCell.RowNumber) + { textBounds.Width = this.dgTable.FocusedTextWidth; ControlPaint.DrawFocusRectangle(g, textBounds, ((SolidBrush)textBrush).Color, ((SolidBrush)GetBackBrush()).Color); textBounds.Width = bounds.Width; @@ -731,8 +803,10 @@ private int PaintRelationText(Graphics g, Rectangle bounds, bool alignToRight) { return cy; } - private void PaintPlusMinusGlyph(Graphics g, Rectangle bounds, Brush backBr, bool alignToRight) { - if (CompModSwitches.DGRelationShpRowPaint.TraceVerbose) Debug.WriteLine("PlusMinusGlyph painting in bounds -> " + bounds.ToString()); + private void PaintPlusMinusGlyph(Graphics g, Rectangle bounds, Brush backBr, bool alignToRight) + { + if (CompModSwitches.DGRelationShpRowPaint.TraceVerbose) + Debug.WriteLine("PlusMinusGlyph painting in bounds -> " + bounds.ToString()); Rectangle outline = GetOutlineRect(bounds.X, bounds.Y); outline = Rectangle.Intersect(bounds, outline); @@ -741,7 +815,8 @@ private void PaintPlusMinusGlyph(Graphics g, Rectangle bounds, Brush backBr, boo g.FillRectangle(backBr, bounds); - if (CompModSwitches.DGRelationShpRowPaint.TraceVerbose) Debug.WriteLine("Painting PlusMinusGlyph with outline -> " + outline.ToString()); + if (CompModSwitches.DGRelationShpRowPaint.TraceVerbose) + Debug.WriteLine("Painting PlusMinusGlyph with outline -> " + outline.ToString()); // draw the +/- box Pen drawPen = this.dgTable.IsDefault ? this.DataGrid.HeaderForePen : this.dgTable.HeaderForePen; g.DrawRectangle(drawPen, outline.X, outline.Y, outline.Width - 1, outline.Height - 1); @@ -750,19 +825,21 @@ private void PaintPlusMinusGlyph(Graphics g, Rectangle bounds, Brush backBr, boo // draw the - g.DrawLine(drawPen, outline.X + indent, outline.Y + outline.Width / 2, - outline.Right - indent - 1, outline.Y + outline.Width/2); // -1 on the y coordinate + outline.Right - indent - 1, outline.Y + outline.Width / 2); // -1 on the y coordinate - if (!expanded) { + if (!expanded) + { // draw the vertical line to make + g.DrawLine(drawPen, - outline.X + outline.Height/2, outline.Y + indent, - outline.X + outline.Height/2, outline.Bottom - indent - 1); // -1... hinting + outline.X + outline.Height / 2, outline.Y + indent, + outline.X + outline.Height / 2, outline.Bottom - indent - 1); // -1... hinting } - else { + else + { Point[] points = new Point[3]; - points[0] = new Point(outline.X + outline.Height/2, outline.Bottom); + points[0] = new Point(outline.X + outline.Height / 2, outline.Bottom); - points[1] = new Point(points[0].X, bounds.Y + 2*indent + base.Height); + points[1] = new Point(points[0].X, bounds.Y + 2 * indent + base.Height); points[2] = new Point(alignToRight ? bounds.X : bounds.Right, points[1].Y); @@ -770,12 +847,14 @@ private void PaintPlusMinusGlyph(Graphics g, Rectangle bounds, Brush backBr, boo } } - private int RelationFromY(int y) { + private int RelationFromY(int y) + { int relation = -1; int relationshipHeight = this.dgTable.RelationshipHeight; Rectangle relRect = GetRelationshipRect(); int cy = base.Height - this.dgTable.BorderWidth + System.Windows.Forms.DataGridTableStyle.relationshipSpacing; - while (cy < relRect.Bottom) { + while (cy < relRect.Bottom) + { if (cy > y) break; cy += relationshipHeight; @@ -788,52 +867,66 @@ private int RelationFromY(int y) { // given the relRect and the rowHeader, this function will return the // X coordinate of the relationship rectangle as it should appear on the screen - private int MirrorRelationshipRectangle(Rectangle relRect, Rectangle rowHeader, bool alignToRight) { + private int MirrorRelationshipRectangle(Rectangle relRect, Rectangle rowHeader, bool alignToRight) + { if (alignToRight) return rowHeader.X - relRect.Width; else return relRect.X; - + } // given the X and Width of a rectangle R1 contained in rect, // this will return the X coordinate of the rectangle that corresponds to R1 in Bi-Di transformation - private int MirrorRectangle(int x, int width, Rectangle rect, bool alignToRight) { + private int MirrorRectangle(int x, int width, Rectangle rect, bool alignToRight) + { if (alignToRight) return rect.Right + rect.X - width - x; else return x; } - [ComVisible(true)] - protected class DataGridRelationshipRowAccessibleObject : DataGridRowAccessibleObject { - public DataGridRelationshipRowAccessibleObject(DataGridRow owner) : base(owner) { + [ComVisible(true)] + protected class DataGridRelationshipRowAccessibleObject : DataGridRowAccessibleObject + { + public DataGridRelationshipRowAccessibleObject(DataGridRow owner) : base(owner) + { } - protected override void AddChildAccessibleObjects(IList children) { + protected override void AddChildAccessibleObjects(IList children) + { base.AddChildAccessibleObjects(children); DataGridRelationshipRow row = (DataGridRelationshipRow)Owner; - if (row.dgTable.RelationsList!= null) { - for (int i=0; i 0) { - if (RelationshipRow.Expanded) { + public override string DefaultAction + { + get + { + if (RelationshipRow.dgTable.RelationsList.Count > 0) + { + if (RelationshipRow.Expanded) + { return SR.AccDGCollapse; } - else { + else + { return SR.AccDGExpand; } } @@ -841,14 +934,19 @@ public override string DefaultAction { } } - public override AccessibleStates State { - get { + public override AccessibleStates State + { + get + { AccessibleStates state = base.State; - if (RelationshipRow.dgTable.RelationsList.Count > 0) { - if (((DataGridRelationshipRow)Owner).Expanded) { + if (RelationshipRow.dgTable.RelationsList.Count > 0) + { + if (((DataGridRelationshipRow)Owner).Expanded) + { state |= AccessibleStates.Expanded; } - else { + else + { state |= AccessibleStates.Collapsed; } } @@ -856,37 +954,46 @@ public override AccessibleStates State { } } - public override void DoDefaultAction() { - if (RelationshipRow.dgTable.RelationsList.Count > 0) { + public override void DoDefaultAction() + { + if (RelationshipRow.dgTable.RelationsList.Count > 0) + { ((DataGridRelationshipRow)Owner).Expanded = !((DataGridRelationshipRow)Owner).Expanded; } } - public override AccessibleObject GetFocused() { + public override AccessibleObject GetFocused() + { DataGridRelationshipRow row = (DataGridRelationshipRow)Owner; int focusRel = row.dgTable.FocusedRelation; - if (focusRel == -1) { + if (focusRel == -1) + { return base.GetFocused(); } - else { + else + { return GetChild(GetChildCount() - row.dgTable.RelationsList.Count + focusRel); } } } [ComVisible(true)] - protected class DataGridRelationshipAccessibleObject : AccessibleObject { + protected class DataGridRelationshipAccessibleObject : AccessibleObject + { DataGridRelationshipRow owner = null; int relationship; - public DataGridRelationshipAccessibleObject(DataGridRelationshipRow owner, int relationship) : base() { + public DataGridRelationshipAccessibleObject(DataGridRelationshipRow owner, int relationship) : base() + { Debug.Assert(owner != null, "DataGridRelationshipAccessibleObject must have a valid owner DataGridRow"); this.owner = owner; this.relationship = relationship; } - public override Rectangle Bounds { - get { + public override Rectangle Bounds + { + get + { Rectangle rowBounds = DataGrid.GetRowBounds(owner); Rectangle bounds = owner.Expanded ? owner.GetRelationshipRectWithMirroring() : Rectangle.Empty; @@ -901,53 +1008,68 @@ public override Rectangle Bounds { } } - public override string Name { - get { + public override string Name + { + get + { return (string)owner.dgTable.RelationsList[relationship]; } } - protected DataGridRelationshipRow Owner { - get { + protected DataGridRelationshipRow Owner + { + get + { return owner; } } - public override AccessibleObject Parent { - get { + public override AccessibleObject Parent + { + get + { return owner.AccessibleObject; } } - protected DataGrid DataGrid { - get { + protected DataGrid DataGrid + { + get + { return owner.DataGrid; } } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { return AccessibleRole.Link; } } - public override AccessibleStates State { - get { + public override AccessibleStates State + { + get + { DataGridRow[] dgRows = this.DataGrid.DataGridRows; - if (Array.IndexOf(dgRows, this.owner) == -1) { + if (Array.IndexOf(dgRows, this.owner) == -1) + { return AccessibleStates.Unavailable; } - AccessibleStates state = AccessibleStates.Selectable - | AccessibleStates.Focusable + AccessibleStates state = AccessibleStates.Selectable + | AccessibleStates.Focusable | AccessibleStates.Linked; - if (!owner.Expanded) { + if (!owner.Expanded) + { state |= AccessibleStates.Invisible; } - if (DataGrid.Focused && Owner.dgTable.FocusedRelation == relationship) { + if (DataGrid.Focused && Owner.dgTable.FocusedRelation == relationship) + { state |= AccessibleStates.Focused; } @@ -955,55 +1077,69 @@ public override AccessibleStates State { } } - public override string Value { - get { + public override string Value + { + get + { DataGridRow[] dgRows = this.DataGrid.DataGridRows; - if (Array.IndexOf(dgRows, this.owner) == -1) { + if (Array.IndexOf(dgRows, this.owner) == -1) + { return null; - } else { + } + else + { return (string)owner.dgTable.RelationsList[relationship]; } } - set { + set + { // not supported } } - public override string DefaultAction { - get { + public override string DefaultAction + { + get + { return SR.AccDGNavigate; } } - public override void DoDefaultAction() { + public override void DoDefaultAction() + { ((DataGridRelationshipRow)Owner).Expanded = true; owner.FocusedRelation = -1; DataGrid.NavigateTo((string)owner.dgTable.RelationsList[relationship], owner, true); DataGrid.BeginInvoke(new MethodInvoker(this.ResetAccessibilityLayer)); } - private void ResetAccessibilityLayer() { - ((DataGrid.DataGridAccessibleObject) DataGrid.AccessibilityObject).NotifyClients(AccessibleEvents.Reorder, 0); - ((DataGrid.DataGridAccessibleObject) DataGrid.AccessibilityObject).NotifyClients(AccessibleEvents.Focus, DataGrid.CurrentCellAccIndex); - ((DataGrid.DataGridAccessibleObject) DataGrid.AccessibilityObject).NotifyClients(AccessibleEvents.Selection, DataGrid.CurrentCellAccIndex); + private void ResetAccessibilityLayer() + { + ((DataGrid.DataGridAccessibleObject)DataGrid.AccessibilityObject).NotifyClients(AccessibleEvents.Reorder, 0); + ((DataGrid.DataGridAccessibleObject)DataGrid.AccessibilityObject).NotifyClients(AccessibleEvents.Focus, DataGrid.CurrentCellAccIndex); + ((DataGrid.DataGridAccessibleObject)DataGrid.AccessibilityObject).NotifyClients(AccessibleEvents.Selection, DataGrid.CurrentCellAccIndex); } /// /// Navigate to the next or previous grid entry. /// - public override AccessibleObject Navigate(AccessibleNavigation navdir) { - switch (navdir) { + public override AccessibleObject Navigate(AccessibleNavigation navdir) + { + switch (navdir) + { case AccessibleNavigation.Right: case AccessibleNavigation.Next: case AccessibleNavigation.Down: - if (relationship + 1 < owner.dgTable.RelationsList.Count) { + if (relationship + 1 < owner.dgTable.RelationsList.Count) + { return Parent.GetChild(Parent.GetChildCount() - owner.dgTable.RelationsList.Count + relationship + 1); } break; case AccessibleNavigation.Up: case AccessibleNavigation.Left: case AccessibleNavigation.Previous: - if (relationship > 0) { + if (relationship > 0) + { return Parent.GetChild(Parent.GetChildCount() - owner.dgTable.RelationsList.Count + relationship - 1); } break; @@ -1013,14 +1149,17 @@ public override AccessibleObject Navigate(AccessibleNavigation navdir) { } - public override void Select(AccessibleSelection flags) { + public override void Select(AccessibleSelection flags) + { // Focus the PropertyGridView window // - if ( (flags & AccessibleSelection.TakeFocus) == AccessibleSelection.TakeFocus) { + if ((flags & AccessibleSelection.TakeFocus) == AccessibleSelection.TakeFocus) + { DataGrid.Focus(); } - if ( (flags & AccessibleSelection.TakeSelection) == AccessibleSelection.TakeSelection) { + if ((flags & AccessibleSelection.TakeSelection) == AccessibleSelection.TakeSelection) + { Owner.FocusedRelation = relationship; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRow.cs index c0f2f72e46c..0426747c665 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRow.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Versioning; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -20,14 +21,15 @@ namespace System.Windows.Forms { /// /// control. /// - internal abstract class DataGridRow : MarshalByRefObject { - internal protected int number; // row number - private bool selected; - private int height; + internal abstract class DataGridRow : MarshalByRefObject + { + internal protected int number; // row number + private bool selected; + private int height; // protected DataRow dataRow; - private IntPtr tooltipID = new IntPtr(-1); - private string tooltip = string.Empty; - AccessibleObject accessibleObject; + private IntPtr tooltipID = new IntPtr(-1); + private string tooltip = string.Empty; + AccessibleObject accessibleObject; // for accessibility... // @@ -40,7 +42,7 @@ internal abstract class DataGridRow : MarshalByRefObject { // we will be mapping only the black color to // the HeaderForeColor // - private static ColorMap[] colorMap = new ColorMap[] {new ColorMap()}; + private static ColorMap[] colorMap = new ColorMap[] { new ColorMap() }; // bitmaps // @@ -59,7 +61,8 @@ internal abstract class DataGridRow : MarshalByRefObject { SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // This class and its derived classes are internal. // So this is not a security back door. ] - public DataGridRow(DataGrid dataGrid, DataGridTableStyle dgTable, int rowNumber) { + public DataGridRow(DataGrid dataGrid, DataGridTableStyle dgTable, int rowNumber) + { if (dataGrid == null || dgTable.DataGrid == null) throw new ArgumentNullException(nameof(dataGrid)); if (rowNumber < 0) @@ -76,37 +79,47 @@ public DataGridRow(DataGrid dataGrid, DataGridTableStyle dgTable, int rowNumber) height = MinimumRowHeight(dgTable); } - public AccessibleObject AccessibleObject { - get { - if (accessibleObject == null) { + public AccessibleObject AccessibleObject + { + get + { + if (accessibleObject == null) + { accessibleObject = CreateAccessibleObject(); } return accessibleObject; } } - protected virtual AccessibleObject CreateAccessibleObject() { + protected virtual AccessibleObject CreateAccessibleObject() + { return new DataGridRowAccessibleObject(this); } - internal protected virtual int MinimumRowHeight(DataGridTableStyle dgTable) { + internal protected virtual int MinimumRowHeight(DataGridTableStyle dgTable) + { return MinimumRowHeight(dgTable.GridColumnStyles); } - internal protected virtual int MinimumRowHeight(GridColumnStylesCollection columns) { + internal protected virtual int MinimumRowHeight(GridColumnStylesCollection columns) + { int h = dgTable.IsDefault ? this.DataGrid.PreferredRowHeight : dgTable.PreferredRowHeight; - try { - if (this.dgTable.DataGrid.DataSource != null) { + try + { + if (this.dgTable.DataGrid.DataSource != null) + { int nCols = columns.Count; - for (int i = 0; i < nCols; ++i) { + for (int i = 0; i < nCols; ++i) + { // if (columns[i].Visible && columns[i].PropertyDescriptor != null) if (columns[i].PropertyDescriptor != null) h = Math.Max(h, columns[i].GetMinimumHeight()); } } } - catch { + catch + { } return h; } @@ -118,17 +131,22 @@ internal protected virtual int MinimumRowHeight(GridColumnStylesCollection colum /// /// Gets the control the row belongs to. /// - public DataGrid DataGrid { - get { + public DataGrid DataGrid + { + get + { return this.dgTable.DataGrid; } } - internal DataGridTableStyle DataGridTableStyle { - get { + internal DataGridTableStyle DataGridTableStyle + { + get + { return this.dgTable; } - set { + set + { dgTable = value; } } @@ -152,11 +170,14 @@ public DataRow DataRow { /// /// Gets or sets the height of the row. /// - public virtual int Height { - get { + public virtual int Height + { + get + { return height; } - set { + set + { // the height of the row should be at least 0. // this way, if the row has a relationship list and the user resizes the row such that // the new height does not accomodate the height of the relationship list @@ -172,8 +193,10 @@ public virtual int Height { /// /// Gets the row's number. /// - public int RowNumber { - get { + public int RowNumber + { + get + { return this.number; } } @@ -181,11 +204,14 @@ public int RowNumber { /// /// Gets or sets a value indicating whether the row is selected. /// - public virtual bool Selected { - get { + public virtual bool Selected + { + get + { return selected; } - set { + set + { selected = value; InvalidateRow(); } @@ -198,11 +224,14 @@ public virtual bool Selected { /// /// Gets the bitmap associated with the row. /// - protected Bitmap GetBitmap(string bitmapName) { - try { + protected Bitmap GetBitmap(string bitmapName) + { + try + { return DpiHelper.GetBitmapFromIcon(typeof(DataGridCaption), bitmapName); } - catch (Exception e) { + catch (Exception e) + { Debug.Fail("Failed to load bitmap: " + bitmapName, e.ToString()); throw e; } @@ -212,12 +241,14 @@ protected Bitmap GetBitmap(string bitmapName) { /// When overridden in a derived class, gets the /// where a cell's contents gets painted. /// - public virtual Rectangle GetCellBounds(int col) { + public virtual Rectangle GetCellBounds(int col) + { int firstVisibleCol = this.dgTable.DataGrid.FirstVisibleColumn; int cx = 0; Rectangle cellBounds = new Rectangle(); GridColumnStylesCollection columns = this.dgTable.GridColumnStyles; - if (columns != null) { + if (columns != null) + { for (int i = firstVisibleCol; i < col; i++) if (columns[i].PropertyDescriptor != null) cx += columns[i].Width; @@ -235,14 +266,16 @@ public virtual Rectangle GetCellBounds(int col) { /// When overridden in a derived class, gets the of the non-scrollable area of /// the row. /// - public virtual Rectangle GetNonScrollableArea() { + public virtual Rectangle GetNonScrollableArea() + { return Rectangle.Empty; } /// /// Gets or sets the bitmap displayed in the row header of a new row. /// - protected Bitmap GetStarBitmap() { + protected Bitmap GetStarBitmap() + { if (starBmp == null) starBmp = GetBitmap("DataGridRow.star"); return starBmp; @@ -252,7 +285,8 @@ protected Bitmap GetStarBitmap() { /// Gets or sets the bitmap displayed in the row header that indicates a row can /// be edited. /// - protected Bitmap GetPencilBitmap() { + protected Bitmap GetPencilBitmap() + { if (pencilBmp == null) pencilBmp = GetBitmap("DataGridRow.pencil"); return pencilBmp; @@ -261,29 +295,34 @@ protected Bitmap GetPencilBitmap() { /// /// Gets or sets the bitmap displayed on a row with an error. /// - protected Bitmap GetErrorBitmap() { + protected Bitmap GetErrorBitmap() + { if (errorBmp == null) errorBmp = GetBitmap("DataGridRow.error"); return errorBmp; } - protected Bitmap GetLeftArrowBitmap() { + protected Bitmap GetLeftArrowBitmap() + { if (leftArrow == null) leftArrow = GetBitmap("DataGridRow.left"); return leftArrow; } - protected Bitmap GetRightArrowBitmap() { + protected Bitmap GetRightArrowBitmap() + { if (rightArrow == null) rightArrow = GetBitmap("DataGridRow.right"); return rightArrow; } - public virtual void InvalidateRow() { + public virtual void InvalidateRow() + { this.dgTable.DataGrid.InvalidateRow(number); } - public virtual void InvalidateRowRect(Rectangle r) { + public virtual void InvalidateRowRect(Rectangle r) + { this.dgTable.DataGrid.InvalidateRowRect(number, r); } @@ -291,18 +330,22 @@ public virtual void InvalidateRowRect(Rectangle r) { /// When overridden in a derived class, notifies the grid that an edit will /// occur. /// - public virtual void OnEdit() { + public virtual void OnEdit() + { } /// /// When overridden in a derived class, called by the control when a key press occurs on a row with focus. /// - public virtual bool OnKeyPress(Keys keyData) { + public virtual bool OnKeyPress(Keys keyData) + { int currentColIndex = this.dgTable.DataGrid.CurrentCell.ColumnNumber; GridColumnStylesCollection columns = this.dgTable.GridColumnStyles; - if (columns != null && currentColIndex >= 0 && currentColIndex < columns.Count) { + if (columns != null && currentColIndex >= 0 && currentColIndex < columns.Count) + { DataGridColumnStyle currentColumn = columns[currentColIndex]; - if (currentColumn.KeyPress(this.RowNumber, keyData)) { + if (currentColumn.KeyPress(this.RowNumber, keyData)) + { return true; } } @@ -316,7 +359,7 @@ public virtual bool OnKeyPress(Keys keyData) { /// public virtual bool OnMouseDown(int x, int y, Rectangle rowHeaders) { - return OnMouseDown(x,y,rowHeaders, false); + return OnMouseDown(x, y, rowHeaders, false); } /// @@ -324,7 +367,8 @@ public virtual bool OnMouseDown(int x, int y, Rectangle rowHeaders) /// in the row's /// client area, specified by x and y coordinates. /// - public virtual bool OnMouseDown(int x, int y, Rectangle rowHeaders, bool alignToRight) { + public virtual bool OnMouseDown(int x, int y, Rectangle rowHeaders, bool alignToRight) + { // if we call base.OnMouseDown, then the row could not use this // mouse click at all. in that case LoseChildFocus, so the edit control // will become visible @@ -336,31 +380,35 @@ public virtual bool OnMouseDown(int x, int y, Rectangle rowHeaders, bool alignTo /// /// - public virtual bool OnMouseMove(int x, int y, Rectangle rowHeaders) { + public virtual bool OnMouseMove(int x, int y, Rectangle rowHeaders) + { return false; } - + /// /// When overridden in a derived class, is called by the when /// the mouse moves within the row's client area. /// - public virtual bool OnMouseMove(int x, int y, Rectangle rowHeaders, bool alignToRight) { + public virtual bool OnMouseMove(int x, int y, Rectangle rowHeaders, bool alignToRight) + { return false; } /// /// - public virtual void OnMouseLeft(Rectangle rowHeaders, bool alignToRight) { + public virtual void OnMouseLeft(Rectangle rowHeaders, bool alignToRight) + { } - public virtual void OnMouseLeft() { + public virtual void OnMouseLeft() + { } /// /// When overridden in a derived class, causes the RowEnter event to occur. /// - public virtual void OnRowEnter() {} - public virtual void OnRowLeave() {} + public virtual void OnRowEnter() { } + public virtual void OnRowLeave() { } // processes the Tab Key // returns TRUE if the TAB key is processed @@ -394,7 +442,8 @@ protected virtual void PaintBottomBorder(Graphics g, Rectangle bounds, int dataW PaintBottomBorder(g, bounds, dataWidth, this.dgTable.GridLineWidth, false); } - protected virtual void PaintBottomBorder(Graphics g, Rectangle bounds, int dataWidth, int borderWidth, bool alignToRight) { + protected virtual void PaintBottomBorder(Graphics g, Rectangle bounds, int dataWidth, int borderWidth, bool alignToRight) + { // paint bottom border Rectangle bottomBorder = new Rectangle(alignToRight ? bounds.Right - dataWidth : bounds.X, bounds.Bottom - borderWidth, @@ -404,9 +453,10 @@ protected virtual void PaintBottomBorder(Graphics g, Rectangle bounds, int dataW g.FillRectangle(this.dgTable.IsDefault ? this.DataGrid.GridLineBrush : this.dgTable.GridLineBrush, bottomBorder); // paint any exposed region to the right - if (dataWidth < bounds.Width) { + if (dataWidth < bounds.Width) + { g.FillRectangle(this.dgTable.DataGrid.BackgroundBrush, - alignToRight ? bounds.X: bottomBorder.Right, + alignToRight ? bounds.X : bottomBorder.Right, bottomBorder.Y, bounds.Width - bottomBorder.Width, borderWidth); @@ -428,18 +478,20 @@ public virtual int PaintData(Graphics g, Rectangle bounds, int firstVisibleColumn, int columnCount, - bool alignToRight) { + bool alignToRight) + { Debug.WriteLineIf(CompModSwitches.DGRowPaint.TraceVerbose, "Painting DataGridAddNewRow: bounds = " + bounds.ToString()); - Rectangle cellBounds = bounds; - int bWidth = this.dgTable.IsDefault ? this.DataGrid.GridLineWidth : this.dgTable.GridLineWidth; - int cx = 0; + Rectangle cellBounds = bounds; + int bWidth = this.dgTable.IsDefault ? this.DataGrid.GridLineWidth : this.dgTable.GridLineWidth; + int cx = 0; DataGridCell current = this.dgTable.DataGrid.CurrentCell; GridColumnStylesCollection columns = dgTable.GridColumnStyles; int nCols = columns.Count; - for (int col = firstVisibleColumn; col < nCols; ++col) { + for (int col = firstVisibleColumn; col < nCols; ++col) + { if (cx > bounds.Width) break; @@ -466,7 +518,8 @@ public virtual int PaintData(Graphics g, alignToRight); // Paint the border to the right of each cell - if (bWidth > 0) { + if (bWidth > 0) + { g.FillRectangle(this.dgTable.IsDefault ? this.DataGrid.GridLineBrush : this.dgTable.GridLineBrush, alignToRight ? cellBounds.X - bWidth : cellBounds.Right, cellBounds.Y, @@ -477,7 +530,8 @@ public virtual int PaintData(Graphics g, } // Paint any exposed area to the right ( or left ) of the data cell area - if (cx < bounds.Width) { + if (cx < bounds.Width) + { g.FillRectangle(this.dgTable.DataGrid.BackgroundBrush, alignToRight ? bounds.X : bounds.X + cx, bounds.Y, @@ -494,7 +548,8 @@ protected virtual void PaintCellContents(Graphics g, Rectangle cellBounds, DataG } protected virtual void PaintCellContents(Graphics g, Rectangle cellBounds, DataGridColumnStyle column, - Brush backBr, Brush foreBrush, bool alignToRight) { + Brush backBr, Brush foreBrush, bool alignToRight) + { g.FillRectangle(backBr, cellBounds); } @@ -506,11 +561,13 @@ protected virtual void PaintCellContents(Graphics g, Rectangle cellBounds, DataG // // will return the rectangle that includes the Icon // - protected Rectangle PaintIcon(Graphics g, Rectangle visualBounds, bool paintIcon, bool alignToRight, Bitmap bmp) { - return PaintIcon(g, visualBounds, paintIcon, alignToRight, bmp, + protected Rectangle PaintIcon(Graphics g, Rectangle visualBounds, bool paintIcon, bool alignToRight, Bitmap bmp) + { + return PaintIcon(g, visualBounds, paintIcon, alignToRight, bmp, this.dgTable.IsDefault ? this.DataGrid.HeaderBackBrush : this.dgTable.HeaderBackBrush); } - protected Rectangle PaintIcon(Graphics g, Rectangle visualBounds, bool paintIcon, bool alignToRight, Bitmap bmp, Brush backBrush) { + protected Rectangle PaintIcon(Graphics g, Rectangle visualBounds, bool paintIcon, bool alignToRight, Bitmap bmp, Brush backBrush) + { Size bmpSize = bmp.Size; Rectangle bmpRect = new Rectangle(alignToRight ? visualBounds.Right - xOffset - bmpSize.Width : visualBounds.X + xOffset, visualBounds.Y + yOffset, @@ -523,7 +580,7 @@ protected Rectangle PaintIcon(Graphics g, Rectangle visualBounds, bool paintIcon colorMap[0].OldColor = Color.Black; ImageAttributes attr = new ImageAttributes(); attr.SetRemapTable(colorMap, ColorAdjustType.Bitmap); - g.DrawImage(bmp, bmpRect, 0, 0, bmpRect.Width, bmpRect.Height,GraphicsUnit.Pixel, attr); + g.DrawImage(bmp, bmpRect, 0, 0, bmpRect.Width, bmpRect.Height, GraphicsUnit.Pixel, attr); // g.DrawImage(bmp, bmpRect); attr.Dispose(); } @@ -532,16 +589,19 @@ protected Rectangle PaintIcon(Graphics g, Rectangle visualBounds, bool paintIcon } // assume that the row is not aligned to right, and that the row is not dirty - public virtual void PaintHeader(Graphics g, Rectangle visualBounds) { + public virtual void PaintHeader(Graphics g, Rectangle visualBounds) + { PaintHeader(g, visualBounds, false); } // assume that the row is not dirty - public virtual void PaintHeader(Graphics g, Rectangle visualBounds, bool alignToRight) { - PaintHeader(g,visualBounds, alignToRight, false); + public virtual void PaintHeader(Graphics g, Rectangle visualBounds, bool alignToRight) + { + PaintHeader(g, visualBounds, alignToRight, false); } - public virtual void PaintHeader(Graphics g, Rectangle visualBounds, bool alignToRight, bool rowIsDirty) { + public virtual void PaintHeader(Graphics g, Rectangle visualBounds, bool alignToRight, bool rowIsDirty) + { Rectangle bounds = visualBounds; // paint the first part of the row header: the Arror or Pencil/Star @@ -549,7 +609,8 @@ public virtual void PaintHeader(Graphics g, Rectangle visualBounds, bool alignTo if (this is DataGridAddNewRow) { bmp = GetStarBitmap(); - lock (bmp) { + lock (bmp) + { bounds.X += PaintIcon(g, bounds, true, alignToRight, bmp).Width + xOffset; } return; @@ -557,14 +618,16 @@ public virtual void PaintHeader(Graphics g, Rectangle visualBounds, bool alignTo else if (rowIsDirty) { bmp = GetPencilBitmap(); - lock (bmp) { + lock (bmp) + { bounds.X += PaintIcon(g, bounds, RowNumber == this.DataGrid.CurrentCell.RowNumber, alignToRight, bmp).Width + xOffset; } } else { bmp = alignToRight ? GetLeftArrowBitmap() : GetRightArrowBitmap(); - lock (bmp) { + lock (bmp) + { bounds.X += PaintIcon(g, bounds, RowNumber == this.DataGrid.CurrentCell.RowNumber, alignToRight, bmp).Width + xOffset; } } @@ -575,12 +638,14 @@ public virtual void PaintHeader(Graphics g, Rectangle visualBounds, bool alignTo if (!(errorInfo is IDataErrorInfo)) return; - string errString = ((IDataErrorInfo) errorInfo).Error; + string errString = ((IDataErrorInfo)errorInfo).Error; if (errString == null) errString = string.Empty; - if (tooltip != errString) { - if (!string.IsNullOrEmpty(tooltip)) { + if (tooltip != errString) + { + if (!string.IsNullOrEmpty(tooltip)) + { DataGrid.ToolTipProvider.RemoveToolTip(tooltipID); tooltip = string.Empty; tooltipID = new IntPtr(-1); @@ -593,7 +658,8 @@ public virtual void PaintHeader(Graphics g, Rectangle visualBounds, bool alignTo // we now have an error string: paint the errorIcon and add the tooltip Rectangle errRect; bmp = GetErrorBitmap(); - lock (bmp) { + lock (bmp) + { errRect = PaintIcon(g, bounds, true, alignToRight, bmp); } bounds.X += errRect.Width + xOffset; @@ -603,9 +669,11 @@ public virtual void PaintHeader(Graphics g, Rectangle visualBounds, bool alignTo DataGrid.ToolTipProvider.AddToolTip(tooltip, tooltipID, errRect); } - protected Brush GetBackBrush() { + protected Brush GetBackBrush() + { Brush br = this.dgTable.IsDefault ? DataGrid.BackBrush : this.dgTable.BackBrush; - if (DataGrid.LedgerStyle && (RowNumber % 2 == 1)) { + if (DataGrid.LedgerStyle && (RowNumber % 2 == 1)) + { br = this.dgTable.IsDefault ? this.DataGrid.AlternatingBackBrush : this.dgTable.AlternatingBackBrush; } return br; @@ -616,12 +684,14 @@ protected Brush GetBackBrush() { /// for the appropriate values for a given row and column when painting the data. /// /// - protected Brush BackBrushForDataPaint(ref DataGridCell current, DataGridColumnStyle gridColumn, int column) { + protected Brush BackBrushForDataPaint(ref DataGridCell current, DataGridColumnStyle gridColumn, int column) + { Brush backBr = this.GetBackBrush(); - if (Selected) { + if (Selected) + { backBr = this.dgTable.IsDefault ? this.DataGrid.SelectionBackBrush : this.dgTable.SelectionBackBrush; - } + } /* if (RowNumber == current.RowNumber && column == current.ColumnNumber) { backBr = grid.CurrentCellBackBrush; @@ -630,11 +700,13 @@ protected Brush BackBrushForDataPaint(ref DataGridCell current, DataGridColumnSt return backBr; } - protected Brush ForeBrushForDataPaint(ref DataGridCell current, DataGridColumnStyle gridColumn, int column) { + protected Brush ForeBrushForDataPaint(ref DataGridCell current, DataGridColumnStyle gridColumn, int column) + { // Brush foreBrush = gridColumn.ForeBrush; Brush foreBrush = this.dgTable.IsDefault ? this.DataGrid.ForeBrush : this.dgTable.ForeBrush; - if (Selected) { + if (Selected) + { foreBrush = this.dgTable.IsDefault ? this.DataGrid.SelectionForeBrush : this.dgTable.SelectionForeBrush; } /* @@ -646,22 +718,28 @@ protected Brush ForeBrushForDataPaint(ref DataGridCell current, DataGridColumnSt } [ComVisible(true)] - protected class DataGridRowAccessibleObject : AccessibleObject { + protected class DataGridRowAccessibleObject : AccessibleObject + { ArrayList cells; DataGridRow owner = null; - internal static string CellToDisplayString(DataGrid grid, int row, int column) { - if (column < grid.myGridTable.GridColumnStyles.Count) { + internal static string CellToDisplayString(DataGrid grid, int row, int column) + { + if (column < grid.myGridTable.GridColumnStyles.Count) + { return grid.myGridTable.GridColumnStyles[column].PropertyDescriptor.Converter.ConvertToString(grid[row, column]); } - else { + else + { return ""; } } - internal static object DisplayStringToCell(DataGrid grid, int row, int column, string value) { - if (column < grid.myGridTable.GridColumnStyles.Count) { + internal static object DisplayStringToCell(DataGrid grid, int row, int column, string value) + { + if (column < grid.myGridTable.GridColumnStyles.Count) + { return grid.myGridTable.GridColumnStyles[column].PropertyDescriptor.Converter.ConvertFromString(value); } // ignore... @@ -673,7 +751,8 @@ internal static object DisplayStringToCell(DataGrid grid, int row, int column, s SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // This class and its derived classes are internal. // So this is not a security back door. ] - public DataGridRowAccessibleObject(DataGridRow owner) : base() { + public DataGridRowAccessibleObject(DataGridRow owner) : base() + { Debug.Assert(owner != null, "DataGridRowAccessibleObject must have a valid owner DataGridRow"); this.owner = owner; DataGrid grid = DataGrid; @@ -682,8 +761,10 @@ public DataGridRowAccessibleObject(DataGridRow owner) : base() { EnsureChildren(); } - private void EnsureChildren() { - if (cells == null) { + private void EnsureChildren() + { + if (cells == null) + { // default size... little extra for relationships... // cells = new ArrayList(DataGrid.myGridTable.GridColumnStyles.Count + 2); @@ -691,76 +772,97 @@ private void EnsureChildren() { } } - protected virtual void AddChildAccessibleObjects(IList children) { + protected virtual void AddChildAccessibleObjects(IList children) + { Debug.WriteLineIf(DataGrid.DataGridAcc.TraceVerbose, "Create row's accessible children"); Debug.Indent(); GridColumnStylesCollection cols = DataGrid.myGridTable.GridColumnStyles; int len = cols.Count; Debug.WriteLineIf(DataGrid.DataGridAcc.TraceVerbose, len + " columns present"); - for (int i=0; i - public override AccessibleObject GetFocused() { - if (DataGrid.Focused) { + public override AccessibleObject GetFocused() + { + if (DataGrid.Focused) + { DataGridCell cell = DataGrid.CurrentCell; - if (cell.RowNumber == owner.RowNumber) { + if (cell.RowNumber == owner.RowNumber) + { return (AccessibleObject)cells[cell.ColumnNumber]; } } @@ -804,8 +914,10 @@ public override AccessibleObject GetFocused() { /// /// Navigate to the next or previous grid entry.entry. /// - public override AccessibleObject Navigate(AccessibleNavigation navdir) { - switch (navdir) { + public override AccessibleObject Navigate(AccessibleNavigation navdir) + { + switch (navdir) + { case AccessibleNavigation.Down: case AccessibleNavigation.Right: case AccessibleNavigation.Next: @@ -817,12 +929,14 @@ public override AccessibleObject Navigate(AccessibleNavigation navdir) { return DataGrid.AccessibilityObject.GetChild(1 + owner.dgTable.GridColumnStyles.Count + owner.RowNumber - 1); case AccessibleNavigation.FirstChild: - if (GetChildCount() > 0) { + if (GetChildCount() > 0) + { return GetChild(0); } break; case AccessibleNavigation.LastChild: - if (GetChildCount() > 0) { + if (GetChildCount() > 0) + { return GetChild(GetChildCount() - 1); } break; @@ -832,16 +946,19 @@ public override AccessibleObject Navigate(AccessibleNavigation navdir) { } - public override void Select(AccessibleSelection flags) { + public override void Select(AccessibleSelection flags) + { // Focus the PropertyGridView window // - if ( (flags & AccessibleSelection.TakeFocus) == AccessibleSelection.TakeFocus) { + if ((flags & AccessibleSelection.TakeFocus) == AccessibleSelection.TakeFocus) + { DataGrid.Focus(); } // Select the grid entry // - if ( (flags & AccessibleSelection.TakeSelection) == AccessibleSelection.TakeSelection) { + if ((flags & AccessibleSelection.TakeSelection) == AccessibleSelection.TakeSelection) + { DataGrid.CurrentRowIndex = owner.RowNumber; } } @@ -849,62 +966,80 @@ public override void Select(AccessibleSelection flags) { } [ComVisible(true)] - protected class DataGridCellAccessibleObject : AccessibleObject { + protected class DataGridCellAccessibleObject : AccessibleObject + { DataGridRow owner = null; int column; - public DataGridCellAccessibleObject(DataGridRow owner, int column) : base() { + public DataGridCellAccessibleObject(DataGridRow owner, int column) : base() + { Debug.Assert(owner != null, "DataGridColumnAccessibleObject must have a valid owner DataGridRow"); this.owner = owner; this.column = column; Debug.WriteLineIf(DataGrid.DataGridAcc.TraceVerbose, "Create cell accessible object"); } - public override Rectangle Bounds { - get { + public override Rectangle Bounds + { + get + { return DataGrid.RectangleToScreen(DataGrid.GetCellBounds(new DataGridCell(owner.RowNumber, column))); } } - public override string Name { - get { + public override string Name + { + get + { return DataGrid.myGridTable.GridColumnStyles[column].HeaderText; } } - public override AccessibleObject Parent { - get { + public override AccessibleObject Parent + { + get + { return owner.AccessibleObject; } } - protected DataGrid DataGrid { - get { + protected DataGrid DataGrid + { + get + { return owner.DataGrid; } } - public override string DefaultAction { - get { + public override string DefaultAction + { + get + { return SR.AccDGEdit; } } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { return AccessibleRole.Cell; } } - public override AccessibleStates State { - get { + public override AccessibleStates State + { + get + { AccessibleStates state = AccessibleStates.Selectable | AccessibleStates.Focusable; // Determine focus // if (DataGrid.CurrentCell.RowNumber == owner.RowNumber - && DataGrid.CurrentCell.ColumnNumber == column) { - if (DataGrid.Focused) { + && DataGrid.CurrentCell.ColumnNumber == column) + { + if (DataGrid.Focused) + { state |= AccessibleStates.Focused; } state |= AccessibleStates.Selected; @@ -914,25 +1049,32 @@ public override AccessibleStates State { } } - public override string Value { - get { - if (owner is DataGridAddNewRow) { + public override string Value + { + get + { + if (owner is DataGridAddNewRow) + { return null; } - else { + else + { return DataGridRowAccessibleObject.CellToDisplayString(DataGrid, owner.RowNumber, column); } } - set { - if (!(owner is DataGridAddNewRow)) { - object realValue = DataGridRowAccessibleObject.DisplayStringToCell(DataGrid, owner.RowNumber, column, value); + set + { + if (!(owner is DataGridAddNewRow)) + { + object realValue = DataGridRowAccessibleObject.DisplayStringToCell(DataGrid, owner.RowNumber, column, value); DataGrid[owner.RowNumber, column] = realValue; } } } - public override void DoDefaultAction() { + public override void DoDefaultAction() + { Select(AccessibleSelection.TakeFocus | AccessibleSelection.TakeSelection); } @@ -940,7 +1082,8 @@ public override void DoDefaultAction() { /// Returns the currently focused child, if any. /// Returns this if the object itself is focused. /// - public override AccessibleObject GetFocused() { + public override AccessibleObject GetFocused() + { // Datagrid always returns the cell as the focused thing... so do we! // return DataGrid.AccessibilityObject.GetFocused(); @@ -950,16 +1093,21 @@ public override AccessibleObject GetFocused() { /// /// Navigate to the next or previous grid entry. /// - public override AccessibleObject Navigate(AccessibleNavigation navdir) { - switch (navdir) { + public override AccessibleObject Navigate(AccessibleNavigation navdir) + { + switch (navdir) + { case AccessibleNavigation.Right: case AccessibleNavigation.Next: - if (column < owner.AccessibleObject.GetChildCount() - 1) { + if (column < owner.AccessibleObject.GetChildCount() - 1) + { return owner.AccessibleObject.GetChild(column + 1); } - else { + else + { AccessibleObject o = DataGrid.AccessibilityObject.GetChild(1 + owner.dgTable.GridColumnStyles.Count + owner.RowNumber + 1); - if (o != null) { + if (o != null) + { return o.Navigate(AccessibleNavigation.FirstChild); } } @@ -970,12 +1118,15 @@ public override AccessibleObject Navigate(AccessibleNavigation navdir) { return DataGrid.AccessibilityObject.GetChild(1 + owner.dgTable.GridColumnStyles.Count + owner.RowNumber - 1).Navigate(AccessibleNavigation.FirstChild); case AccessibleNavigation.Left: case AccessibleNavigation.Previous: - if (column > 0) { + if (column > 0) + { return owner.AccessibleObject.GetChild(column - 1); } - else { + else + { AccessibleObject o = DataGrid.AccessibilityObject.GetChild(1 + owner.dgTable.GridColumnStyles.Count + owner.RowNumber - 1); - if (o != null) { + if (o != null) + { return o.Navigate(AccessibleNavigation.LastChild); } } @@ -991,16 +1142,19 @@ public override AccessibleObject Navigate(AccessibleNavigation navdir) { } - public override void Select(AccessibleSelection flags) { + public override void Select(AccessibleSelection flags) + { // Focus the PropertyGridView window // - if ( (flags & AccessibleSelection.TakeFocus) == AccessibleSelection.TakeFocus) { + if ((flags & AccessibleSelection.TakeFocus) == AccessibleSelection.TakeFocus) + { DataGrid.Focus(); } // Select the grid entry // - if ( (flags & AccessibleSelection.TakeSelection) == AccessibleSelection.TakeSelection) { + if ((flags & AccessibleSelection.TakeSelection) == AccessibleSelection.TakeSelection) + { DataGrid.CurrentCell = new DataGridCell(owner.RowNumber, column); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs index ef34102dc6f..46a3b86f770 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; @@ -18,36 +19,42 @@ namespace System.Windows.Forms { /// Encapsulates the state of a DataGrid that changes when the /// user navigates back and forth through ADO.NET data relations. /// - internal sealed class DataGridState : ICloneable { + internal sealed class DataGridState : ICloneable + { // fields // public object DataSource = null; public string DataMember = null; public CurrencyManager ListManager = null; - public DataGridRow[] DataGridRows = new DataGridRow[0]; + public DataGridRow[] DataGridRows = new DataGridRow[0]; public DataGrid DataGrid; public int DataGridRowsLength = 0; public GridColumnStylesCollection GridColumnStyles = null; - public int FirstVisibleRow = 0; - public int FirstVisibleCol = 0; + public int FirstVisibleRow = 0; + public int FirstVisibleCol = 0; - public int CurrentRow = 0; - public int CurrentCol = 0; + public int CurrentRow = 0; + public int CurrentCol = 0; - public DataGridRow LinkingRow = null; - AccessibleObject parentRowAccessibleObject; + public DataGridRow LinkingRow = null; + AccessibleObject parentRowAccessibleObject; - public DataGridState() { + public DataGridState() + { } - public DataGridState(DataGrid dataGrid) { + public DataGridState(DataGrid dataGrid) + { PushState(dataGrid); } - - internal AccessibleObject ParentRowAccessibleObject { - get { - if (parentRowAccessibleObject == null) { + + internal AccessibleObject ParentRowAccessibleObject + { + get + { + if (parentRowAccessibleObject == null) + { parentRowAccessibleObject = new DataGridStateParentRowAccessibleObject(this); } return parentRowAccessibleObject; @@ -57,7 +64,8 @@ internal AccessibleObject ParentRowAccessibleObject { // methods // - public object Clone() { + public object Clone() + { DataGridState dgs = new DataGridState(); dgs.DataGridRows = DataGridRows; dgs.DataSource = DataSource; @@ -76,7 +84,8 @@ public object Clone() { /// Called by a DataGrid when it wishes to preserve its /// transient state in the current DataGridState object. /// - public void PushState(DataGrid dataGrid) { + public void PushState(DataGrid dataGrid) + { this.DataSource = dataGrid.DataSource; this.DataMember = dataGrid.DataMember; this.DataGrid = dataGrid; @@ -86,12 +95,13 @@ public void PushState(DataGrid dataGrid) { this.FirstVisibleCol = dataGrid.firstVisibleCol; this.CurrentRow = dataGrid.currentRow; this.GridColumnStyles = new GridColumnStylesCollection(dataGrid.myGridTable); - + this.GridColumnStyles.Clear(); - foreach(DataGridColumnStyle style in dataGrid.myGridTable.GridColumnStyles) { + foreach (DataGridColumnStyle style in dataGrid.myGridTable.GridColumnStyles) + { this.GridColumnStyles.Add(style); } - + this.ListManager = dataGrid.ListManager; this.ListManager.ItemChanged += new ItemChangedEventHandler(DataSource_Changed); this.ListManager.MetaDataChanged += new EventHandler(DataSource_MetaDataChanged); @@ -100,7 +110,8 @@ public void PushState(DataGrid dataGrid) { // this is needed so that the parent rows will remove notification from the list // when the datagridstate is no longer needed; - public void RemoveChangeNotification() { + public void RemoveChangeNotification() + { this.ListManager.ItemChanged -= new ItemChangedEventHandler(DataSource_Changed); this.ListManager.MetaDataChanged -= new EventHandler(DataSource_MetaDataChanged); } @@ -109,7 +120,8 @@ public void RemoveChangeNotification() { /// Called by a grid when it wishes to match its transient /// state with the current DataGridState object. /// - public void PullState(DataGrid dataGrid, bool createColumn) { + public void PullState(DataGrid dataGrid, bool createColumn) + { // dataGrid.DataSource = DataSource; // dataGrid.DataMember = DataMember; dataGrid.Set_ListManager(DataSource, DataMember, true, createColumn); // true for forcing new listManager, @@ -126,8 +138,10 @@ public void PullState(DataGrid dataGrid, bool createColumn) { dataGrid.SetDataGridRows(DataGridRows, DataGridRowsLength); } - private void DataSource_Changed(object sender, ItemChangedEventArgs e) { - if (this.DataGrid != null && this.ListManager.Position == e.Index) { + private void DataSource_Changed(object sender, ItemChangedEventArgs e) + { + if (this.DataGrid != null && this.ListManager.Position == e.Index) + { DataGrid.InvalidateParentRows(); return; } @@ -136,23 +150,28 @@ private void DataSource_Changed(object sender, ItemChangedEventArgs e) { DataGrid.ParentRowsDataChanged(); } - private void DataSource_MetaDataChanged(object sender, EventArgs e) { + private void DataSource_MetaDataChanged(object sender, EventArgs e) + { if (this.DataGrid != null) DataGrid.ParentRowsDataChanged(); } [ComVisible(true)] - internal class DataGridStateParentRowAccessibleObject : AccessibleObject { + internal class DataGridStateParentRowAccessibleObject : AccessibleObject + { DataGridState owner = null; - public DataGridStateParentRowAccessibleObject(DataGridState owner) : base() { + public DataGridStateParentRowAccessibleObject(DataGridState owner) : base() + { Debug.Assert(owner != null, "DataGridRowAccessibleObject must have a valid owner DataGridRow"); this.owner = owner; } - public override Rectangle Bounds { - get { + public override Rectangle Bounds + { + get + { DataGridParentRows dataGridParentRows = ((DataGridParentRows.DataGridParentRowsAccessibleObject)this.Parent).Owner; DataGrid g = owner.LinkingRow.DataGrid; Rectangle r = dataGridParentRows.GetBoundsForDataGridStateAccesibility(owner); @@ -161,26 +180,34 @@ public override Rectangle Bounds { } } - public override string Name { - get { + public override string Name + { + get + { return SR.AccDGParentRow; } } - public override AccessibleObject Parent { - get { + public override AccessibleObject Parent + { + get + { return owner.LinkingRow.DataGrid.ParentRowsAccessibleObject; } } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { return AccessibleRole.ListItem; } } - public override string Value { - get { + public override string Value + { + get + { StringBuilder sb = new StringBuilder(); CurrencyManager source = (CurrencyManager)owner.LinkingRow.DataGrid.BindingContext[owner.DataSource, owner.DataMember]; @@ -189,8 +216,10 @@ public override string Value { sb.Append(": "); bool needComma = false; - foreach (DataGridColumnStyle col in owner.GridColumnStyles) { - if (needComma) { + foreach (DataGridColumnStyle col in owner.GridColumnStyles) + { + if (needComma) + { sb.Append(", "); } @@ -209,10 +238,12 @@ public override string Value { /// /// Navigate to the next or previous grid entry. /// - public override AccessibleObject Navigate(AccessibleNavigation navdir) { + public override AccessibleObject Navigate(AccessibleNavigation navdir) + { DataGridParentRows.DataGridParentRowsAccessibleObject parentAcc = (DataGridParentRows.DataGridParentRowsAccessibleObject)Parent; - switch (navdir) { + switch (navdir) + { case AccessibleNavigation.Down: case AccessibleNavigation.Right: case AccessibleNavigation.Next: diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs index 73f74b95849..c4a96d9c285 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; @@ -25,48 +26,49 @@ namespace System.Windows.Forms { DesignTimeVisible(false), //DefaultProperty("GridTableName") ] - public class DataGridTableStyle : Component, IDataGridEditingService { + public class DataGridTableStyle : Component, IDataGridEditingService + { // internal for DataGridColumn accessibility... // - internal DataGrid dataGrid = null; + internal DataGrid dataGrid = null; // relationship UI - private int relationshipHeight = 0; - internal const int relationshipSpacing = 1; - private Rectangle relationshipRect = Rectangle.Empty; - private int focusedRelation = -1; - private int focusedTextWidth; + private int relationshipHeight = 0; + internal const int relationshipSpacing = 1; + private Rectangle relationshipRect = Rectangle.Empty; + private int focusedRelation = -1; + private int focusedTextWidth; // will contain a list of relationships that this table has private ArrayList relationsList = new ArrayList(2); // the name of the table private string mappingName = string.Empty; - private GridColumnStylesCollection gridColumns = null; - private bool readOnly = false; - private bool isDefaultTableStyle = false; - - private static readonly object EventAllowSorting = new object(); - private static readonly object EventGridLineColor = new object(); - private static readonly object EventGridLineStyle = new object(); - private static readonly object EventHeaderBackColor = new object(); - private static readonly object EventHeaderForeColor = new object(); - private static readonly object EventHeaderFont = new object(); - private static readonly object EventLinkColor = new object(); - private static readonly object EventLinkHoverColor = new object(); - private static readonly object EventPreferredColumnWidth = new object(); - private static readonly object EventPreferredRowHeight = new object(); - private static readonly object EventColumnHeadersVisible = new object(); - private static readonly object EventRowHeaderWidth = new object(); - private static readonly object EventSelectionBackColor = new object(); - private static readonly object EventSelectionForeColor = new object(); - private static readonly object EventMappingName = new object(); - private static readonly object EventAlternatingBackColor = new object(); - private static readonly object EventBackColor = new object(); - private static readonly object EventForeColor = new object(); - private static readonly object EventReadOnly = new object(); - private static readonly object EventRowHeadersVisible = new object(); + private GridColumnStylesCollection gridColumns = null; + private bool readOnly = false; + private bool isDefaultTableStyle = false; + + private static readonly object EventAllowSorting = new object(); + private static readonly object EventGridLineColor = new object(); + private static readonly object EventGridLineStyle = new object(); + private static readonly object EventHeaderBackColor = new object(); + private static readonly object EventHeaderForeColor = new object(); + private static readonly object EventHeaderFont = new object(); + private static readonly object EventLinkColor = new object(); + private static readonly object EventLinkHoverColor = new object(); + private static readonly object EventPreferredColumnWidth = new object(); + private static readonly object EventPreferredRowHeight = new object(); + private static readonly object EventColumnHeadersVisible = new object(); + private static readonly object EventRowHeaderWidth = new object(); + private static readonly object EventSelectionBackColor = new object(); + private static readonly object EventSelectionForeColor = new object(); + private static readonly object EventMappingName = new object(); + private static readonly object EventAlternatingBackColor = new object(); + private static readonly object EventBackColor = new object(); + private static readonly object EventForeColor = new object(); + private static readonly object EventReadOnly = new object(); + private static readonly object EventRowHeadersVisible = new object(); // add a bunch of properties, taken from the dataGrid // @@ -74,33 +76,33 @@ public class DataGridTableStyle : Component, IDataGridEditingService { // default values // private const bool defaultAllowSorting = true; - private const DataGridLineStyle defaultGridLineStyle = DataGridLineStyle.Solid; - private const int defaultPreferredColumnWidth = 75; - private const int defaultRowHeaderWidth = 35; - internal static readonly Font defaultFont = Control.DefaultFont; - internal static readonly int defaultFontHeight = defaultFont.Height; + private const DataGridLineStyle defaultGridLineStyle = DataGridLineStyle.Solid; + private const int defaultPreferredColumnWidth = 75; + private const int defaultRowHeaderWidth = 35; + internal static readonly Font defaultFont = Control.DefaultFont; + internal static readonly int defaultFontHeight = defaultFont.Height; // the actual place holders for properties // - private bool allowSorting = defaultAllowSorting; - private SolidBrush alternatingBackBrush = DefaultAlternatingBackBrush; - private SolidBrush backBrush = DefaultBackBrush; - private SolidBrush foreBrush = DefaultForeBrush; - private SolidBrush gridLineBrush = DefaultGridLineBrush; - private DataGridLineStyle gridLineStyle = defaultGridLineStyle; - internal SolidBrush headerBackBrush = DefaultHeaderBackBrush; - internal Font headerFont = null; // this is ambient property to Font value. - internal SolidBrush headerForeBrush = DefaultHeaderForeBrush; - internal Pen headerForePen = DefaultHeaderForePen; - private SolidBrush linkBrush = DefaultLinkBrush; - internal int preferredColumnWidth = defaultPreferredColumnWidth; - private int prefferedRowHeight = defaultFontHeight + 3; - private SolidBrush selectionBackBrush = DefaultSelectionBackBrush; - private SolidBrush selectionForeBrush = DefaultSelectionForeBrush; - private int rowHeaderWidth = defaultRowHeaderWidth; - private bool rowHeadersVisible = true; - private bool columnHeadersVisible = true; + private bool allowSorting = defaultAllowSorting; + private SolidBrush alternatingBackBrush = DefaultAlternatingBackBrush; + private SolidBrush backBrush = DefaultBackBrush; + private SolidBrush foreBrush = DefaultForeBrush; + private SolidBrush gridLineBrush = DefaultGridLineBrush; + private DataGridLineStyle gridLineStyle = defaultGridLineStyle; + internal SolidBrush headerBackBrush = DefaultHeaderBackBrush; + internal Font headerFont = null; // this is ambient property to Font value. + internal SolidBrush headerForeBrush = DefaultHeaderForeBrush; + internal Pen headerForePen = DefaultHeaderForePen; + private SolidBrush linkBrush = DefaultLinkBrush; + internal int preferredColumnWidth = defaultPreferredColumnWidth; + private int prefferedRowHeight = defaultFontHeight + 3; + private SolidBrush selectionBackBrush = DefaultSelectionBackBrush; + private SolidBrush selectionForeBrush = DefaultSelectionForeBrush; + private int rowHeaderWidth = defaultRowHeaderWidth; + private bool rowHeadersVisible = true; + private bool columnHeadersVisible = true; // the dataGrid would need to know when the ColumnHeaderVisible, RowHeadersVisible, RowHeaderWidth // and preferredColumnWidth, preferredRowHeight properties are changed in the current dataGridTableStyle @@ -113,16 +115,21 @@ public class DataGridTableStyle : Component, IDataGridEditingService { DefaultValue(defaultAllowSorting), SRDescription(nameof(SR.DataGridAllowSortingDescr)) ] - public bool AllowSorting { - get { + public bool AllowSorting + { + get + { return allowSorting; } - set { - if (this.isDefaultTableStyle) { + set + { + if (this.isDefaultTableStyle) + { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "AllowSorting")); } - if (allowSorting != value) { + if (allowSorting != value) + { allowSorting = value; OnAllowSortingChanged(EventArgs.Empty); } @@ -132,7 +139,8 @@ public bool AllowSorting { /// /// [To be supplied] /// - public event EventHandler AllowSortingChanged { + public event EventHandler AllowSortingChanged + { add => Events.AddHandler(EventAllowSorting, value); remove => Events.RemoveHandler(EventAllowSorting, value); } @@ -141,22 +149,28 @@ public event EventHandler AllowSortingChanged { SRCategory(nameof(SR.CatColors)), SRDescription(nameof(SR.DataGridAlternatingBackColorDescr)) ] - public Color AlternatingBackColor { - get { + public Color AlternatingBackColor + { + get + { return alternatingBackBrush.Color; } - set { - if (this.isDefaultTableStyle) { + set + { + if (this.isDefaultTableStyle) + { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "AlternatingBackColor")); } if (System.Windows.Forms.DataGrid.IsTransparentColor(value)) throw new ArgumentException(SR.DataGridTableStyleTransparentAlternatingBackColorNotAllowed); - if (value.IsEmpty) { + if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "AlternatingBackColor")); } - if (!alternatingBackBrush.Color.Equals(value)) { + if (!alternatingBackBrush.Color.Equals(value)) + { alternatingBackBrush = new SolidBrush(value); InvalidateInside(); OnAlternatingBackColorChanged(EventArgs.Empty); @@ -164,12 +178,15 @@ public Color AlternatingBackColor { } } - public event EventHandler AlternatingBackColorChanged { + public event EventHandler AlternatingBackColorChanged + { add => Events.AddHandler(EventAlternatingBackColor, value); remove => Events.RemoveHandler(EventAlternatingBackColor, value); } - public void ResetAlternatingBackColor() { - if (ShouldSerializeAlternatingBackColor()) { + public void ResetAlternatingBackColor() + { + if (ShouldSerializeAlternatingBackColor()) + { AlternatingBackColor = DefaultAlternatingBackBrush.Color; InvalidateInside(); } @@ -180,22 +197,28 @@ protected virtual bool ShouldSerializeAlternatingBackColor() return !AlternatingBackBrush.Equals(DefaultAlternatingBackBrush); } - internal SolidBrush AlternatingBackBrush { - get { + internal SolidBrush AlternatingBackBrush + { + get + { return alternatingBackBrush; } } - protected bool ShouldSerializeBackColor() { + protected bool ShouldSerializeBackColor() + { return !System.Windows.Forms.DataGridTableStyle.DefaultBackBrush.Equals(this.backBrush); } - protected bool ShouldSerializeForeColor() { + protected bool ShouldSerializeForeColor() + { return !System.Windows.Forms.DataGridTableStyle.DefaultForeBrush.Equals(this.foreBrush); } - internal SolidBrush BackBrush { - get { + internal SolidBrush BackBrush + { + get + { return this.backBrush; } } @@ -204,22 +227,28 @@ internal SolidBrush BackBrush { SRCategory(nameof(SR.CatColors)), SRDescription(nameof(SR.ControlBackColorDescr)) ] - public Color BackColor { - get { + public Color BackColor + { + get + { return this.backBrush.Color; } - set { - if (this.isDefaultTableStyle) { + set + { + if (this.isDefaultTableStyle) + { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "BackColor")); } if (System.Windows.Forms.DataGrid.IsTransparentColor(value)) throw new ArgumentException(SR.DataGridTableStyleTransparentBackColorNotAllowed); - if (value.IsEmpty) { + if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "BackColor")); } - if (!backBrush.Color.Equals(value)) { + if (!backBrush.Color.Equals(value)) + { this.backBrush = new SolidBrush(value); InvalidateInside(); OnBackColorChanged(EventArgs.Empty); @@ -227,19 +256,24 @@ public Color BackColor { } } - public event EventHandler BackColorChanged { + public event EventHandler BackColorChanged + { add => Events.AddHandler(EventBackColor, value); remove => Events.RemoveHandler(EventBackColor, value); } - public void ResetBackColor() { - if (!this.backBrush.Equals(DefaultBackBrush)) { + public void ResetBackColor() + { + if (!this.backBrush.Equals(DefaultBackBrush)) + { this.BackColor = DefaultBackBrush.Color; } } - internal int BorderWidth { - get { + internal int BorderWidth + { + get + { DataGrid dataGrid = this.DataGrid; if (dataGrid == null) return 0; @@ -247,10 +281,13 @@ internal int BorderWidth { // then use the value of that property DataGridLineStyle gridStyle; int gridLineWidth; - if (this.IsDefault) { + if (this.IsDefault) + { gridStyle = this.DataGrid.GridLineStyle; gridLineWidth = this.DataGrid.GridLineWidth; - } else { + } + else + { gridStyle = this.GridLineStyle; gridLineWidth = this.GridLineWidth; } @@ -262,77 +299,106 @@ internal int BorderWidth { } } - internal static SolidBrush DefaultAlternatingBackBrush { - get { + internal static SolidBrush DefaultAlternatingBackBrush + { + get + { return (SolidBrush)SystemBrushes.Window; } } - internal static SolidBrush DefaultBackBrush { - get { + internal static SolidBrush DefaultBackBrush + { + get + { return (SolidBrush)SystemBrushes.Window; } } - internal static SolidBrush DefaultForeBrush { - get { + internal static SolidBrush DefaultForeBrush + { + get + { return (SolidBrush)SystemBrushes.WindowText; } } - private static SolidBrush DefaultGridLineBrush { - get { + private static SolidBrush DefaultGridLineBrush + { + get + { return (SolidBrush)SystemBrushes.Control; } } - private static SolidBrush DefaultHeaderBackBrush { - get { + private static SolidBrush DefaultHeaderBackBrush + { + get + { return (SolidBrush)SystemBrushes.Control; } } - private static SolidBrush DefaultHeaderForeBrush { - get { + private static SolidBrush DefaultHeaderForeBrush + { + get + { return (SolidBrush)SystemBrushes.ControlText; } } - private static Pen DefaultHeaderForePen { - get { + private static Pen DefaultHeaderForePen + { + get + { return new Pen(SystemColors.ControlText); } } - private static SolidBrush DefaultLinkBrush { - get { + private static SolidBrush DefaultLinkBrush + { + get + { return (SolidBrush)SystemBrushes.HotTrack; } } - private static SolidBrush DefaultSelectionBackBrush { - get { + private static SolidBrush DefaultSelectionBackBrush + { + get + { return (SolidBrush)SystemBrushes.ActiveCaption; } } - private static SolidBrush DefaultSelectionForeBrush { - get { + private static SolidBrush DefaultSelectionForeBrush + { + get + { return (SolidBrush)SystemBrushes.ActiveCaptionText; } } - internal int FocusedRelation { - get { + internal int FocusedRelation + { + get + { return focusedRelation; } - set { - if (focusedRelation != value) { + set + { + if (focusedRelation != value) + { focusedRelation = value; - if (focusedRelation == -1) { + if (focusedRelation == -1) + { focusedTextWidth = 0; - } else { + } + else + { Graphics g = DataGrid.CreateGraphicsInternal(); - focusedTextWidth = (int) Math.Ceiling(g.MeasureString(((string) RelationsList[focusedRelation]), DataGrid.LinkFont).Width); + focusedTextWidth = (int)Math.Ceiling(g.MeasureString(((string)RelationsList[focusedRelation]), DataGrid.LinkFont).Width); g.Dispose(); } } } } - internal int FocusedTextWidth { - get { + internal int FocusedTextWidth + { + get + { return this.focusedTextWidth; } } @@ -341,20 +407,26 @@ internal int FocusedTextWidth { SRCategory(nameof(SR.CatColors)), SRDescription(nameof(SR.ControlForeColorDescr)) ] - public Color ForeColor { - get { + public Color ForeColor + { + get + { return this.foreBrush.Color; } - set { - if (this.isDefaultTableStyle) { + set + { + if (this.isDefaultTableStyle) + { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "ForeColor")); } - if (value.IsEmpty) { + if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "BackColor")); } - if (!foreBrush.Color.Equals(value)) { + if (!foreBrush.Color.Equals(value)) + { this.foreBrush = new SolidBrush(value); InvalidateInside(); OnForeColorChanged(EventArgs.Empty); @@ -362,19 +434,24 @@ public Color ForeColor { } } - public event EventHandler ForeColorChanged { + public event EventHandler ForeColorChanged + { add => Events.AddHandler(EventForeColor, value); remove => Events.RemoveHandler(EventForeColor, value); } - internal SolidBrush ForeBrush { - get { + internal SolidBrush ForeBrush + { + get + { return this.foreBrush; } } - public void ResetForeColor() { - if (!this.foreBrush.Equals(DefaultForeBrush)) { + public void ResetForeColor() + { + if (!this.foreBrush.Equals(DefaultForeBrush)) + { this.ForeColor = DefaultForeBrush.Color; } } @@ -383,16 +460,21 @@ public void ResetForeColor() { SRCategory(nameof(SR.CatColors)), SRDescription(nameof(SR.DataGridGridLineColorDescr)) ] - public Color GridLineColor { - get { + public Color GridLineColor + { + get + { return gridLineBrush.Color; } - set { - if (this.isDefaultTableStyle) { + set + { + if (this.isDefaultTableStyle) + { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "GridLineColor")); } - if (gridLineBrush.Color != value) { + if (gridLineBrush.Color != value) + { if (value.IsEmpty) throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "GridLineColor")); gridLineBrush = new SolidBrush(value); @@ -403,7 +485,8 @@ public Color GridLineColor { } } - public event EventHandler GridLineColorChanged { + public event EventHandler GridLineColorChanged + { add => Events.AddHandler(EventGridLineColor, value); remove => Events.RemoveHandler(EventGridLineColor, value); } @@ -413,20 +496,26 @@ protected virtual bool ShouldSerializeGridLineColor() return !GridLineBrush.Equals(DefaultGridLineBrush); } - public void ResetGridLineColor() { - if (ShouldSerializeGridLineColor()) { + public void ResetGridLineColor() + { + if (ShouldSerializeGridLineColor()) + { GridLineColor = DefaultGridLineBrush.Color; } } - internal SolidBrush GridLineBrush { - get { + internal SolidBrush GridLineBrush + { + get + { return gridLineBrush; } } - internal int GridLineWidth { - get { + internal int GridLineWidth + { + get + { Debug.Assert(this.GridLineStyle == DataGridLineStyle.Solid || this.GridLineStyle == DataGridLineStyle.None, "are there any other styles?"); return GridLineStyle == DataGridLineStyle.Solid ? 1 : 0; } @@ -437,20 +526,26 @@ internal int GridLineWidth { DefaultValue(defaultGridLineStyle), SRDescription(nameof(SR.DataGridGridLineStyleDescr)) ] - public DataGridLineStyle GridLineStyle { - get { + public DataGridLineStyle GridLineStyle + { + get + { return gridLineStyle; } - set { - if (this.isDefaultTableStyle) { + set + { + if (this.isDefaultTableStyle) + { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "GridLineStyle")); } - + //valid values are 0x0 to 0x1. - if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridLineStyle.None, (int)DataGridLineStyle.Solid)) { + if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridLineStyle.None, (int)DataGridLineStyle.Solid)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridLineStyle)); } - if (gridLineStyle != value) { + if (gridLineStyle != value) + { gridLineStyle = value; // Invalidate(layout.Data); OnGridLineStyleChanged(EventArgs.Empty); @@ -458,21 +553,26 @@ public DataGridLineStyle GridLineStyle { } } - public event EventHandler GridLineStyleChanged { + public event EventHandler GridLineStyleChanged + { add => Events.AddHandler(EventGridLineStyle, value); remove => Events.RemoveHandler(EventGridLineStyle, value); } [ SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridHeaderBackColorDescr)) + SRDescription(nameof(SR.DataGridHeaderBackColorDescr)) ] - public Color HeaderBackColor { - get { + public Color HeaderBackColor + { + get + { return headerBackBrush.Color; } - set { - if (this.isDefaultTableStyle) { + set + { + if (this.isDefaultTableStyle) + { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "HeaderBackColor")); } @@ -480,7 +580,8 @@ public Color HeaderBackColor { throw new ArgumentException(SR.DataGridTableStyleTransparentHeaderBackColorNotAllowed); if (value.IsEmpty) throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "HeaderBackColor")); - if (!value.Equals(headerBackBrush.Color)) { + if (!value.Equals(headerBackBrush.Color)) + { headerBackBrush = new SolidBrush(value); /* @@ -495,13 +596,16 @@ public Color HeaderBackColor { } } - public event EventHandler HeaderBackColorChanged { + public event EventHandler HeaderBackColorChanged + { add => Events.AddHandler(EventHeaderBackColor, value); remove => Events.RemoveHandler(EventHeaderBackColor, value); } - internal SolidBrush HeaderBackBrush { - get { + internal SolidBrush HeaderBackBrush + { + get + { return headerBackBrush; } } @@ -511,8 +615,10 @@ protected virtual bool ShouldSerializeHeaderBackColor() return !HeaderBackBrush.Equals(DefaultHeaderBackBrush); } - public void ResetHeaderBackColor() { - if(ShouldSerializeHeaderBackColor()) { + public void ResetHeaderBackColor() + { + if (ShouldSerializeHeaderBackColor()) + { HeaderBackColor = DefaultHeaderBackBrush.Color; } } @@ -523,16 +629,21 @@ public void ResetHeaderBackColor() { AmbientValue(null), SRDescription(nameof(SR.DataGridHeaderFontDescr)) ] - public Font HeaderFont { - get { - return(headerFont == null ? (this.DataGrid == null ? Control.DefaultFont : this.DataGrid.Font) : headerFont); + public Font HeaderFont + { + get + { + return (headerFont == null ? (this.DataGrid == null ? Control.DefaultFont : this.DataGrid.Font) : headerFont); } - set { - if (this.isDefaultTableStyle) { + set + { + if (this.isDefaultTableStyle) + { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "HeaderFont")); } - if (value == null && headerFont != null || (value != null && !value.Equals(headerFont))) { + if (value == null && headerFont != null || (value != null && !value.Equals(headerFont))) + { headerFont = value; /* RecalculateFonts(); @@ -544,17 +655,21 @@ public Font HeaderFont { } } - public event EventHandler HeaderFontChanged { + public event EventHandler HeaderFontChanged + { add => Events.AddHandler(EventHeaderFont, value); remove => Events.RemoveHandler(EventHeaderFont, value); } - private bool ShouldSerializeHeaderFont() { - return(headerFont != null); + private bool ShouldSerializeHeaderFont() + { + return (headerFont != null); } - public void ResetHeaderFont() { - if (headerFont != null) { + public void ResetHeaderFont() + { + if (headerFont != null) + { headerFont = null; /* RecalculateFonts(); @@ -567,20 +682,25 @@ public void ResetHeaderFont() { [ SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridHeaderForeColorDescr)) + SRDescription(nameof(SR.DataGridHeaderForeColorDescr)) ] - public Color HeaderForeColor { - get { + public Color HeaderForeColor + { + get + { return headerForePen.Color; } - set { - if (this.isDefaultTableStyle) { + set + { + if (this.isDefaultTableStyle) + { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "HeaderForeColor")); } if (value.IsEmpty) throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "HeaderForeColor")); - if (!value.Equals(headerForePen.Color)) { + if (!value.Equals(headerForePen.Color)) + { headerForePen = new Pen(value); headerForeBrush = new SolidBrush(value); @@ -596,7 +716,8 @@ public Color HeaderForeColor { } } - public event EventHandler HeaderForeColorChanged { + public event EventHandler HeaderForeColorChanged + { add => Events.AddHandler(EventHeaderForeColor, value); remove => Events.RemoveHandler(EventHeaderForeColor, value); } @@ -606,20 +727,26 @@ protected virtual bool ShouldSerializeHeaderForeColor() return !HeaderForePen.Equals(DefaultHeaderForePen); } - public void ResetHeaderForeColor() { - if(ShouldSerializeHeaderForeColor()) { + public void ResetHeaderForeColor() + { + if (ShouldSerializeHeaderForeColor()) + { HeaderForeColor = DefaultHeaderForeBrush.Color; } } - internal SolidBrush HeaderForeBrush { - get { + internal SolidBrush HeaderForeBrush + { + get + { return this.headerForeBrush; } } - internal Pen HeaderForePen { - get { + internal Pen HeaderForePen + { + get + { return headerForePen; } } @@ -628,18 +755,23 @@ internal Pen HeaderForePen { SRCategory(nameof(SR.CatColors)), SRDescription(nameof(SR.DataGridLinkColorDescr)) ] - public Color LinkColor { - get { + public Color LinkColor + { + get + { return linkBrush.Color; } - set { - if (this.isDefaultTableStyle) { + set + { + if (this.isDefaultTableStyle) + { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "LinkColor")); } if (value.IsEmpty) throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "LinkColor")); - if (!linkBrush.Color.Equals(value)) { + if (!linkBrush.Color.Equals(value)) + { linkBrush = new SolidBrush(value); // Invalidate(layout.Data); OnLinkColorChanged(EventArgs.Empty); @@ -647,7 +779,8 @@ public Color LinkColor { } } - public event EventHandler LinkColorChanged { + public event EventHandler LinkColorChanged + { add => Events.AddHandler(EventLinkColor, value); remove => Events.RemoveHandler(EventLinkColor, value); } @@ -657,13 +790,16 @@ protected virtual bool ShouldSerializeLinkColor() return !LinkBrush.Equals(DefaultLinkBrush); } - public void ResetLinkColor() { + public void ResetLinkColor() + { if (ShouldSerializeLinkColor()) LinkColor = DefaultLinkBrush.Color; } - internal Brush LinkBrush { - get { + internal Brush LinkBrush + { + get + { return linkBrush; } } @@ -674,16 +810,20 @@ internal Brush LinkBrush { Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public Color LinkHoverColor { - get { + public Color LinkHoverColor + { + get + { return this.LinkColor; } [SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters")] - set { + set + { } } - public event EventHandler LinkHoverColorChanged { + public event EventHandler LinkHoverColorChanged + { add => Events.AddHandler(EventLinkHoverColor, value); remove => Events.RemoveHandler(EventLinkHoverColor, value); } @@ -694,17 +834,22 @@ protected virtual bool ShouldSerializeLinkHoverColor() // return !LinkHoverBrush.Equals(defaultLinkHoverBrush); } - internal Rectangle RelationshipRect { - get { - if (this.relationshipRect.IsEmpty) { + internal Rectangle RelationshipRect + { + get + { + if (this.relationshipRect.IsEmpty) + { ComputeRelationshipRect(); } return this.relationshipRect; } } - private Rectangle ComputeRelationshipRect() { - if (relationshipRect.IsEmpty && DataGrid.AllowNavigation) { + private Rectangle ComputeRelationshipRect() + { + if (relationshipRect.IsEmpty && DataGrid.AllowNavigation) + { Debug.WriteLineIf(CompModSwitches.DGRelationShpRowLayout.TraceVerbose, "GetRelationshipRect grinding away"); Graphics g = DataGrid.CreateGraphicsInternal(); relationshipRect = new Rectangle(); @@ -713,8 +858,9 @@ private Rectangle ComputeRelationshipRect() { // Determine the width of the widest relationship name int longestRelationship = 0; - for (int r = 0; r < this.RelationsList.Count; ++r) { - int rwidth = (int) Math.Ceiling(g.MeasureString(((string) this.RelationsList[r]), this.DataGrid.LinkFont).Width) + for (int r = 0; r < this.RelationsList.Count; ++r) + { + int rwidth = (int)Math.Ceiling(g.MeasureString(((string)this.RelationsList[r]), this.DataGrid.LinkFont).Width) ; if (rwidth > longestRelationship) longestRelationship = rwidth; @@ -732,19 +878,23 @@ private Rectangle ComputeRelationshipRect() { return relationshipRect; } - internal void ResetRelationsUI() { + internal void ResetRelationsUI() + { this.relationshipRect = Rectangle.Empty; this.focusedRelation = -1; this.relationshipHeight = this.dataGrid.LinkFontHeight + relationshipSpacing; } - internal int RelationshipHeight { - get { + internal int RelationshipHeight + { + get + { return this.relationshipHeight; } } - public void ResetLinkHoverColor() { + public void ResetLinkHoverColor() + { /*if (ShouldSerializeLinkHoverColor()) LinkHoverColor = defaultLinkHoverBrush.Color;*/ } @@ -756,18 +906,23 @@ public void ResetLinkHoverColor() { SRDescription(nameof(SR.DataGridPreferredColumnWidthDescr)), TypeConverter(typeof(DataGridPreferredColumnWidthTypeConverter)) ] - public int PreferredColumnWidth { - get { + public int PreferredColumnWidth + { + get + { return preferredColumnWidth; } - set { - if (this.isDefaultTableStyle) { + set + { + if (this.isDefaultTableStyle) + { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "PreferredColumnWidth")); } if (value < 0) throw new ArgumentException(SR.DataGridColumnWidth, "PreferredColumnWidth"); - if (preferredColumnWidth != value) { + if (preferredColumnWidth != value) + { preferredColumnWidth = value; /* @@ -784,22 +939,27 @@ public int PreferredColumnWidth { } } - public event EventHandler PreferredColumnWidthChanged { + public event EventHandler PreferredColumnWidthChanged + { add => Events.AddHandler(EventPreferredColumnWidth, value); remove => Events.RemoveHandler(EventPreferredColumnWidth, value); } - + [ SRCategory(nameof(SR.CatLayout)), Localizable(true), SRDescription(nameof(SR.DataGridPreferredRowHeightDescr)) ] - public int PreferredRowHeight { - get { + public int PreferredRowHeight + { + get + { return prefferedRowHeight; } - set { - if (this.isDefaultTableStyle) { + set + { + if (this.isDefaultTableStyle) + { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "PrefferedRowHeight")); } @@ -833,14 +993,16 @@ public int PreferredRowHeight { } } - public event EventHandler PreferredRowHeightChanged { + public event EventHandler PreferredRowHeightChanged + { add => Events.AddHandler(EventPreferredRowHeight, value); remove => Events.RemoveHandler(EventPreferredRowHeight, value); } - private void ResetPreferredRowHeight() { - PreferredRowHeight = defaultFontHeight + 3; - } + private void ResetPreferredRowHeight() + { + PreferredRowHeight = defaultFontHeight + 3; + } protected bool ShouldSerializePreferredRowHeight() { @@ -852,12 +1014,16 @@ protected bool ShouldSerializePreferredRowHeight() DefaultValue(true), SRDescription(nameof(SR.DataGridColumnHeadersVisibleDescr)) ] - public bool ColumnHeadersVisible { - get { + public bool ColumnHeadersVisible + { + get + { return columnHeadersVisible; } - set { - if (columnHeadersVisible != value) { + set + { + if (columnHeadersVisible != value) + { columnHeadersVisible = value; /* PerformLayout(); @@ -868,7 +1034,8 @@ public bool ColumnHeadersVisible { } } - public event EventHandler ColumnHeadersVisibleChanged { + public event EventHandler ColumnHeadersVisibleChanged + { add => Events.AddHandler(EventColumnHeadersVisible, value); remove => Events.RemoveHandler(EventColumnHeadersVisible, value); } @@ -878,12 +1045,16 @@ public event EventHandler ColumnHeadersVisibleChanged { DefaultValue(true), SRDescription(nameof(SR.DataGridRowHeadersVisibleDescr)) ] - public bool RowHeadersVisible { - get { + public bool RowHeadersVisible + { + get + { return rowHeadersVisible; } - set { - if (rowHeadersVisible != value) { + set + { + if (rowHeadersVisible != value) + { rowHeadersVisible = value; /* PerformLayout(); @@ -894,7 +1065,8 @@ public bool RowHeadersVisible { } } - public event EventHandler RowHeadersVisibleChanged { + public event EventHandler RowHeadersVisibleChanged + { add => Events.AddHandler(EventRowHeadersVisible, value); remove => Events.RemoveHandler(EventRowHeadersVisible, value); } @@ -905,11 +1077,14 @@ public event EventHandler RowHeadersVisibleChanged { Localizable(true), SRDescription(nameof(SR.DataGridRowHeaderWidthDescr)) ] - public int RowHeaderWidth { - get { + public int RowHeaderWidth + { + get + { return rowHeaderWidth; } - set { + set + { if (this.DataGrid != null) value = Math.Max(this.DataGrid.MinimumRowHeaderWidth(), value); if (rowHeaderWidth != value) @@ -927,7 +1102,8 @@ public int RowHeaderWidth { } } - public event EventHandler RowHeaderWidthChanged { + public event EventHandler RowHeaderWidthChanged + { add => Events.AddHandler(EventRowHeaderWidth, value); remove => Events.RemoveHandler(EventRowHeaderWidth, value); } @@ -936,12 +1112,16 @@ public event EventHandler RowHeaderWidthChanged { SRCategory(nameof(SR.CatColors)), SRDescription(nameof(SR.DataGridSelectionBackColorDescr)) ] - public Color SelectionBackColor { - get { + public Color SelectionBackColor + { + get + { return selectionBackBrush.Color; } - set { - if (this.isDefaultTableStyle) { + set + { + if (this.isDefaultTableStyle) + { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "SelectionBackColor")); } @@ -949,7 +1129,8 @@ public Color SelectionBackColor { throw new ArgumentException(SR.DataGridTableStyleTransparentSelectionBackColorNotAllowed); if (value.IsEmpty) throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "SelectionBackColor")); - if (!value.Equals(selectionBackBrush.Color)) { + if (!value.Equals(selectionBackBrush.Color)) + { selectionBackBrush = new SolidBrush(value); InvalidateInside(); @@ -959,19 +1140,24 @@ public Color SelectionBackColor { } } - public event EventHandler SelectionBackColorChanged { + public event EventHandler SelectionBackColorChanged + { add => Events.AddHandler(EventSelectionBackColor, value); remove => Events.RemoveHandler(EventSelectionBackColor, value); } - internal SolidBrush SelectionBackBrush { - get { + internal SolidBrush SelectionBackBrush + { + get + { return this.selectionBackBrush; } } - internal SolidBrush SelectionForeBrush { - get { + internal SolidBrush SelectionForeBrush + { + get + { return this.selectionForeBrush; } } @@ -980,8 +1166,9 @@ protected bool ShouldSerializeSelectionBackColor() { return !DefaultSelectionBackBrush.Equals(selectionBackBrush); } - - public void ResetSelectionBackColor() { + + public void ResetSelectionBackColor() + { if (ShouldSerializeSelectionBackColor()) SelectionBackColor = DefaultSelectionBackBrush.Color; } @@ -989,20 +1176,25 @@ public void ResetSelectionBackColor() { [ Description("The foreground color for the current data grid row"), SRCategory(nameof(SR.CatColors)), - SRDescription(nameof(SR.DataGridSelectionForeColorDescr)) + SRDescription(nameof(SR.DataGridSelectionForeColorDescr)) ] - public Color SelectionForeColor { - get { + public Color SelectionForeColor + { + get + { return selectionForeBrush.Color; } - set { - if (this.isDefaultTableStyle) { + set + { + if (this.isDefaultTableStyle) + { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "SelectionForeColor")); } if (value.IsEmpty) throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "SelectionForeColor")); - if (!value.Equals(selectionForeBrush.Color)) { + if (!value.Equals(selectionForeBrush.Color)) + { selectionForeBrush = new SolidBrush(value); InvalidateInside(); @@ -1012,7 +1204,8 @@ public Color SelectionForeColor { } } - public event EventHandler SelectionForeColorChanged { + public event EventHandler SelectionForeColorChanged + { add => Events.AddHandler(EventSelectionForeColor, value); remove => Events.RemoveHandler(EventSelectionForeColor, value); } @@ -1022,14 +1215,16 @@ protected virtual bool ShouldSerializeSelectionForeColor() return !SelectionForeBrush.Equals(DefaultSelectionForeBrush); } - public void ResetSelectionForeColor() { + public void ResetSelectionForeColor() + { if (ShouldSerializeSelectionForeColor()) SelectionForeColor = DefaultSelectionForeBrush.Color; } // will need this function from the dataGrid // - private void InvalidateInside() { + private void InvalidateInside() + { if (this.DataGrid != null) this.DataGrid.InvalidateInside(); } @@ -1043,13 +1238,15 @@ private void InvalidateInside() { /// /// Initializes a new instance of the class. /// - public DataGridTableStyle(bool isDefaultTableStyle) { + public DataGridTableStyle(bool isDefaultTableStyle) + { gridColumns = new GridColumnStylesCollection(this, isDefaultTableStyle); gridColumns.CollectionChanged += new CollectionChangeEventHandler(this.OnColumnCollectionChanged); this.isDefaultTableStyle = isDefaultTableStyle; } - public DataGridTableStyle() : this(false) { + public DataGridTableStyle() : this(false) + { } /// @@ -1060,30 +1257,35 @@ public DataGridTableStyle() : this(false) { SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // If the constructor does not set the GridColumnStyles // it would be a breaking change. ] - public DataGridTableStyle(CurrencyManager listManager) : this() { + public DataGridTableStyle(CurrencyManager listManager) : this() + { Debug.Assert(listManager != null, "the DataGridTabel cannot use a null listManager"); this.mappingName = listManager.GetListName(); // set up the Relations and the columns SetGridColumnStylesCollection(listManager); } - internal void SetRelationsList(CurrencyManager listManager) { + internal void SetRelationsList(CurrencyManager listManager) + { PropertyDescriptorCollection propCollection = listManager.GetItemProperties(); Debug.Assert(!this.IsDefault, "the grid can set the relations only on a table that was manually added by the user"); int propCount = propCollection.Count; if (relationsList.Count > 0) relationsList.Clear(); - for (int i = 0; i < propCount; i++) { + for (int i = 0; i < propCount; i++) + { PropertyDescriptor prop = propCollection[i]; Debug.Assert(prop != null, "prop is null: how that happened?"); - if (PropertyDescriptorIsARelation(prop)) { + if (PropertyDescriptorIsARelation(prop)) + { // relation relationsList.Add(prop.Name); } } } - internal void SetGridColumnStylesCollection(CurrencyManager listManager) { + internal void SetGridColumnStylesCollection(CurrencyManager listManager) + { // when we are setting the gridColumnStyles, do not handle any gridColumnCollectionChanged events gridColumns.CollectionChanged -= new CollectionChangeEventHandler(this.OnColumnCollectionChanged); @@ -1095,13 +1297,15 @@ internal void SetGridColumnStylesCollection(CurrencyManager listManager) { Debug.Assert(propCollection != null, "propCollection is null: how that happened?"); int propCount = propCollection.Count; - for (int i = 0; i < propCount; i++) { + for (int i = 0; i < propCount; i++) + { PropertyDescriptor prop = propCollection[i]; Debug.Assert(prop != null, "prop is null: how that happened?"); // do not take into account the properties that are browsable. if (!prop.IsBrowsable) continue; - if (PropertyDescriptorIsARelation(prop)) { + if (PropertyDescriptorIsARelation(prop)) + { // relation relationsList.Add(prop.Name); } @@ -1111,7 +1315,8 @@ internal void SetGridColumnStylesCollection(CurrencyManager listManager) { DataGridColumnStyle col = this.CreateGridColumn(prop, this.isDefaultTableStyle); if (this.isDefaultTableStyle) gridColumns.AddDefaultColumn(col); - else { + else + { col.MappingName = prop.Name; col.HeaderText = prop.Name; gridColumns.Add(col); @@ -1123,15 +1328,18 @@ internal void SetGridColumnStylesCollection(CurrencyManager listManager) { gridColumns.CollectionChanged += new CollectionChangeEventHandler(this.OnColumnCollectionChanged); } - private static bool PropertyDescriptorIsARelation(PropertyDescriptor prop) { + private static bool PropertyDescriptorIsARelation(PropertyDescriptor prop) + { return typeof(IList).IsAssignableFrom(prop.PropertyType) && !typeof(Array).IsAssignableFrom(prop.PropertyType); } - internal protected virtual DataGridColumnStyle CreateGridColumn(PropertyDescriptor prop) { + internal protected virtual DataGridColumnStyle CreateGridColumn(PropertyDescriptor prop) + { return this.CreateGridColumn(prop, false); } - internal protected virtual DataGridColumnStyle CreateGridColumn(PropertyDescriptor prop, bool isDefault) { + internal protected virtual DataGridColumnStyle CreateGridColumn(PropertyDescriptor prop, bool isDefault) + { DataGridColumnStyle ret = null; Type dataType = prop.PropertyType; @@ -1152,7 +1360,8 @@ internal protected virtual DataGridColumnStyle CreateGridColumn(PropertyDescript dataType.Equals(typeof(double)) || dataType.Equals(typeof(float)) || dataType.Equals(typeof(byte)) || - dataType.Equals(typeof(sbyte))) { + dataType.Equals(typeof(sbyte))) + { ret = new DataGridTextBoxColumn(prop, "G", isDefault); } else @@ -1162,8 +1371,10 @@ internal protected virtual DataGridColumnStyle CreateGridColumn(PropertyDescript return ret; } - internal void ResetRelationsList() { - if (this.isDefaultTableStyle) { + internal void ResetRelationsList() + { + if (this.isDefaultTableStyle) + { relationsList.Clear(); } } @@ -1176,11 +1387,14 @@ internal void ResetRelationsList() { /// Gets the name of this grid table. /// [Editor("System.Windows.Forms.Design.DataGridTableStyleMappingNameEditor, " + AssemblyRef.SystemDesign, typeof(System.Drawing.Design.UITypeEditor)), DefaultValue("")] - public string MappingName { - get { + public string MappingName + { + get + { return mappingName; } - set { + set + { if (value == null) value = string.Empty; if (value.Equals(mappingName)) @@ -1189,10 +1403,13 @@ public string MappingName { mappingName = value; // this could throw - try { + try + { if (this.DataGrid != null) this.DataGrid.TableStyles.CheckForMappingNameDuplicates(this); - } catch { + } + catch + { this.mappingName = originalMappingName; throw; } @@ -1200,7 +1417,8 @@ public string MappingName { } } - public event EventHandler MappingNameChanged { + public event EventHandler MappingNameChanged + { add => Events.AddHandler(EventMappingName, value); remove => Events.RemoveHandler(EventMappingName, value); } @@ -1209,8 +1427,10 @@ public event EventHandler MappingNameChanged { /// Gets the /// list of relation objects for the grid table. /// - internal ArrayList RelationsList { - get { + internal ArrayList RelationsList + { + get + { return relationsList; } } @@ -1222,8 +1442,10 @@ internal ArrayList RelationsList { Localizable(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Content) ] - public virtual GridColumnStylesCollection GridColumnStyles { - get { + public virtual GridColumnStylesCollection GridColumnStyles + { + get + { return gridColumns; } } @@ -1239,7 +1461,8 @@ internal void SetInternalDataGrid(DataGrid dG, bool force) { if (dataGrid != null && dataGrid.Equals(dG) && !force) return; - else { + else + { dataGrid = dG; if (dG != null && dG.Initializing) return; @@ -1253,11 +1476,14 @@ internal void SetInternalDataGrid(DataGrid dG, bool force) /// Gets or sets the control for the drawn table. /// [Browsable(false)] - public virtual DataGrid DataGrid { - get { + public virtual DataGrid DataGrid + { + get + { return dataGrid; } - set { + set + { SetInternalDataGrid(value, true); } } @@ -1267,19 +1493,24 @@ public virtual DataGrid DataGrid { /// edited. /// [DefaultValue(false)] - public virtual bool ReadOnly { - get { + public virtual bool ReadOnly + { + get + { return readOnly; } - set { - if (readOnly != value) { + set + { + if (readOnly != value) + { readOnly = value; OnReadOnlyChanged(EventArgs.Empty); } } } - public event EventHandler ReadOnlyChanged { + public event EventHandler ReadOnlyChanged + { add => Events.AddHandler(EventReadOnly, value); remove => Events.RemoveHandler(EventReadOnly, value); } @@ -1291,7 +1522,8 @@ public event EventHandler ReadOnlyChanged { /// /// Requests an edit operation. /// - public bool BeginEdit(DataGridColumnStyle gridColumn, int rowNumber) { + public bool BeginEdit(DataGridColumnStyle gridColumn, int rowNumber) + { DataGrid grid = this.DataGrid; if (grid == null) return false; @@ -1303,7 +1535,8 @@ public bool BeginEdit(DataGridColumnStyle gridColumn, int rowNumber) { /// Requests an end to an edit /// operation. /// - public bool EndEdit(DataGridColumnStyle gridColumn, int rowNumber, bool shouldAbort) { + public bool EndEdit(DataGridColumnStyle gridColumn, int rowNumber, bool shouldAbort) + { DataGrid grid = this.DataGrid; if (grid == null) return false; @@ -1311,38 +1544,48 @@ public bool EndEdit(DataGridColumnStyle gridColumn, int rowNumber, bool shouldAb return grid.EndEdit(gridColumn, rowNumber, shouldAbort); } - internal void InvalidateColumn(DataGridColumnStyle column) { + internal void InvalidateColumn(DataGridColumnStyle column) + { int index = GridColumnStyles.IndexOf(column); if (index >= 0 && DataGrid != null) DataGrid.InvalidateColumn(index); } - private void OnColumnCollectionChanged(object sender, CollectionChangeEventArgs e) { + private void OnColumnCollectionChanged(object sender, CollectionChangeEventArgs e) + { gridColumns.CollectionChanged -= new CollectionChangeEventHandler(this.OnColumnCollectionChanged); - try { + try + { DataGrid grid = this.DataGrid; DataGridColumnStyle col = e.Element as DataGridColumnStyle; - if (e.Action == CollectionChangeAction.Add) { + if (e.Action == CollectionChangeAction.Add) + { if (col != null) col.SetDataGridInternalInColumn(grid); - } else if (e.Action == CollectionChangeAction.Remove) { + } + else if (e.Action == CollectionChangeAction.Remove) + { if (col != null) col.SetDataGridInternalInColumn(null); - } else { + } + else + { // refresh Debug.Assert(e.Action == CollectionChangeAction.Refresh, "there are only Add, Remove and Refresh in the CollectionChangeAction"); // if we get a column in this collectionChangeEventArgs it means // that the propertyDescriptor in that column changed. if (e.Element != null) - for (int i = 0; i < gridColumns.Count; i++ ) + for (int i = 0; i < gridColumns.Count; i++) gridColumns[i].SetDataGridInternalInColumn(null); } if (grid != null) grid.OnColumnCollectionChanged(this, e); - } finally { + } + finally + { gridColumns.CollectionChanged += new CollectionChangeEventHandler(this.OnColumnCollectionChanged); } } @@ -1358,116 +1601,139 @@ internal void OnColumnChanged(object sender, PropertyChangedEvent event) { GenerateVisibleColumnsCache(); } #endif - protected virtual void OnReadOnlyChanged(EventArgs e) { + protected virtual void OnReadOnlyChanged(EventArgs e) + { EventHandler eh = Events[EventReadOnly] as EventHandler; if (eh != null) eh(this, e); } - protected virtual void OnMappingNameChanged(EventArgs e) { + protected virtual void OnMappingNameChanged(EventArgs e) + { EventHandler eh = Events[EventMappingName] as EventHandler; if (eh != null) eh(this, e); } - protected virtual void OnAlternatingBackColorChanged(EventArgs e) { + protected virtual void OnAlternatingBackColorChanged(EventArgs e) + { EventHandler eh = Events[EventAlternatingBackColor] as EventHandler; if (eh != null) eh(this, e); } - protected virtual void OnForeColorChanged(EventArgs e) { + protected virtual void OnForeColorChanged(EventArgs e) + { EventHandler eh = Events[EventBackColor] as EventHandler; if (eh != null) eh(this, e); } - protected virtual void OnBackColorChanged(EventArgs e) { + protected virtual void OnBackColorChanged(EventArgs e) + { EventHandler eh = Events[EventForeColor] as EventHandler; if (eh != null) eh(this, e); } - protected virtual void OnAllowSortingChanged(EventArgs e) { + protected virtual void OnAllowSortingChanged(EventArgs e) + { EventHandler eh = Events[EventAllowSorting] as EventHandler; if (eh != null) eh(this, e); } - protected virtual void OnGridLineColorChanged(EventArgs e) { + protected virtual void OnGridLineColorChanged(EventArgs e) + { EventHandler eh = Events[EventGridLineColor] as EventHandler; if (eh != null) eh(this, e); } - protected virtual void OnGridLineStyleChanged(EventArgs e) { + protected virtual void OnGridLineStyleChanged(EventArgs e) + { EventHandler eh = Events[EventGridLineStyle] as EventHandler; if (eh != null) eh(this, e); } - protected virtual void OnHeaderBackColorChanged(EventArgs e) { + protected virtual void OnHeaderBackColorChanged(EventArgs e) + { EventHandler eh = Events[EventHeaderBackColor] as EventHandler; if (eh != null) eh(this, e); } - protected virtual void OnHeaderFontChanged(EventArgs e) { + protected virtual void OnHeaderFontChanged(EventArgs e) + { EventHandler eh = Events[EventHeaderFont] as EventHandler; if (eh != null) eh(this, e); } - protected virtual void OnHeaderForeColorChanged(EventArgs e) { + protected virtual void OnHeaderForeColorChanged(EventArgs e) + { EventHandler eh = Events[EventHeaderForeColor] as EventHandler; if (eh != null) eh(this, e); } - protected virtual void OnLinkColorChanged(EventArgs e) { + protected virtual void OnLinkColorChanged(EventArgs e) + { EventHandler eh = Events[EventLinkColor] as EventHandler; if (eh != null) eh(this, e); } - protected virtual void OnLinkHoverColorChanged(EventArgs e) { + protected virtual void OnLinkHoverColorChanged(EventArgs e) + { EventHandler eh = Events[EventLinkHoverColor] as EventHandler; if (eh != null) eh(this, e); } - protected virtual void OnPreferredRowHeightChanged(EventArgs e) { + protected virtual void OnPreferredRowHeightChanged(EventArgs e) + { EventHandler eh = Events[EventPreferredRowHeight] as EventHandler; if (eh != null) eh(this, e); } - protected virtual void OnPreferredColumnWidthChanged(EventArgs e) { + protected virtual void OnPreferredColumnWidthChanged(EventArgs e) + { EventHandler eh = Events[EventPreferredColumnWidth] as EventHandler; if (eh != null) eh(this, e); } - protected virtual void OnColumnHeadersVisibleChanged(EventArgs e) { + protected virtual void OnColumnHeadersVisibleChanged(EventArgs e) + { EventHandler eh = Events[EventColumnHeadersVisible] as EventHandler; if (eh != null) eh(this, e); } - protected virtual void OnRowHeadersVisibleChanged(EventArgs e) { + protected virtual void OnRowHeadersVisibleChanged(EventArgs e) + { EventHandler eh = Events[EventRowHeadersVisible] as EventHandler; if (eh != null) eh(this, e); } - protected virtual void OnRowHeaderWidthChanged(EventArgs e) { + protected virtual void OnRowHeaderWidthChanged(EventArgs e) + { EventHandler eh = Events[EventRowHeaderWidth] as EventHandler; if (eh != null) eh(this, e); } - protected virtual void OnSelectionForeColorChanged(EventArgs e) { + protected virtual void OnSelectionForeColorChanged(EventArgs e) + { EventHandler eh = Events[EventSelectionForeColor] as EventHandler; if (eh != null) eh(this, e); } - protected virtual void OnSelectionBackColorChanged(EventArgs e) { + protected virtual void OnSelectionBackColorChanged(EventArgs e) + { EventHandler eh = Events[EventSelectionBackColor] as EventHandler; if (eh != null) eh(this, e); } - protected override void Dispose(bool disposing) { - if (disposing) { + protected override void Dispose(bool disposing) + { + if (disposing) + { GridColumnStylesCollection cols = this.GridColumnStyles; - if (cols != null) { + if (cols != null) + { for (int i = 0; i < cols.Count; i++) cols[i].Dispose(); } @@ -1475,8 +1741,10 @@ protected override void Dispose(bool disposing) { base.Dispose(disposing); } - internal bool IsDefault { - get { + internal bool IsDefault + { + get + { return this.isDefaultTableStyle; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs index 0861e5a1dad..da2dfae43fc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; @@ -11,88 +12,107 @@ namespace System.Windows.Forms { using System.Windows.Forms; using System.ComponentModel; using System.Globalization; - + /// /// Represents a collection of objects in the /// control. /// [ListBindable(false)] - public class GridTableStylesCollection : BaseCollection ,IList { + public class GridTableStylesCollection : BaseCollection, IList + { CollectionChangeEventHandler onCollectionChanged; - ArrayList items = new ArrayList(); - DataGrid owner = null; + ArrayList items = new ArrayList(); + DataGrid owner = null; - int IList.Add(object value) { - return this.Add((DataGridTableStyle) value); + int IList.Add(object value) + { + return this.Add((DataGridTableStyle)value); } - void IList.Clear() { + void IList.Clear() + { this.Clear(); } - bool IList.Contains(object value) { + bool IList.Contains(object value) + { return items.Contains(value); } - int IList.IndexOf(object value) { + int IList.IndexOf(object value) + { return items.IndexOf(value); } - void IList.Insert(int index, object value) { + void IList.Insert(int index, object value) + { throw new NotSupportedException(); } - void IList.Remove(object value) { + void IList.Remove(object value) + { this.Remove((DataGridTableStyle)value); } - void IList.RemoveAt(int index) { + void IList.RemoveAt(int index) + { this.RemoveAt(index); } - bool IList.IsFixedSize { - get {return false;} + bool IList.IsFixedSize + { + get { return false; } } - bool IList.IsReadOnly { - get {return false;} + bool IList.IsReadOnly + { + get { return false; } } - object IList.this[int index] { + object IList.this[int index] + { get { return items[index]; } set { throw new NotSupportedException(); } } - void ICollection.CopyTo(Array array, int index) { + void ICollection.CopyTo(Array array, int index) + { this.items.CopyTo(array, index); } - int ICollection.Count { - get {return this.items.Count;} + int ICollection.Count + { + get { return this.items.Count; } } - bool ICollection.IsSynchronized { - get {return false;} + bool ICollection.IsSynchronized + { + get { return false; } } - object ICollection.SyncRoot { - get {return this;} + object ICollection.SyncRoot + { + get { return this; } } - IEnumerator IEnumerable.GetEnumerator() { + IEnumerator IEnumerable.GetEnumerator() + { return items.GetEnumerator(); } - internal GridTableStylesCollection(DataGrid grid) { + internal GridTableStylesCollection(DataGrid grid) + { owner = grid; } - protected override ArrayList List { - get { + protected override ArrayList List + { + get + { return items; } } - + /* implemented in BaseCollection /// /// Retrieves the number of GridTables in the collection. @@ -110,8 +130,10 @@ public override int Count { /// /// Retrieves the DataGridTable with the specified index. /// - public DataGridTableStyle this[int index] { - get { + public DataGridTableStyle this[int index] + { + get + { return (DataGridTableStyle)items[index]; } } @@ -119,12 +141,15 @@ public DataGridTableStyle this[int index] { /// /// Retrieves the DataGridTable with the name provided. /// - public DataGridTableStyle this[string tableName] { - get { + public DataGridTableStyle this[string tableName] + { + get + { if (tableName == null) throw new ArgumentNullException(nameof(tableName)); int itemCount = items.Count; - for (int i = 0; i < itemCount; ++i) { + for (int i = 0; i < itemCount; ++i) + { DataGridTableStyle table = (DataGridTableStyle)items[i]; // NOTE: case-insensitive if (string.Equals(table.MappingName, tableName, StringComparison.OrdinalIgnoreCase)) @@ -134,18 +159,20 @@ public DataGridTableStyle this[string tableName] { } } - internal void CheckForMappingNameDuplicates(DataGridTableStyle table) { + internal void CheckForMappingNameDuplicates(DataGridTableStyle table) + { if (string.IsNullOrEmpty(table.MappingName)) return; for (int i = 0; i < items.Count; i++) - if ( ((DataGridTableStyle)items[i]).MappingName.Equals(table.MappingName) && table != items[i]) + if (((DataGridTableStyle)items[i]).MappingName.Equals(table.MappingName) && table != items[i]) throw new ArgumentException(SR.DataGridTableStyleDuplicateMappingName, "table"); } /// /// Adds a to this collection. /// - public virtual int Add(DataGridTableStyle table) { + public virtual int Add(DataGridTableStyle table) + { // set the rowHeaderWidth on the newly added table to at least the minimum value // on its owner if (this.owner != null && this.owner.MinimumRowHeaderWidth() > table.RowHeaderWidth) @@ -158,19 +185,23 @@ public virtual int Add(DataGridTableStyle table) { table.MappingNameChanged += new EventHandler(TableStyleMappingNameChanged); int index = items.Add(table); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, table)); - + return index; } - - private void TableStyleMappingNameChanged(object sender, EventArgs pcea) { + + private void TableStyleMappingNameChanged(object sender, EventArgs pcea) + { OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null)); } - - public virtual void AddRange(DataGridTableStyle[] tables) { - if (tables == null) { + + public virtual void AddRange(DataGridTableStyle[] tables) + { + if (tables == null) + { throw new ArgumentNullException(nameof(tables)); } - foreach(DataGridTableStyle table in tables) { + foreach (DataGridTableStyle table in tables) + { table.DataGrid = owner; table.MappingNameChanged += new EventHandler(TableStyleMappingNameChanged); items.Add(table); @@ -178,13 +209,16 @@ public virtual void AddRange(DataGridTableStyle[] tables) { OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null)); } - public event CollectionChangeEventHandler CollectionChanged { + public event CollectionChangeEventHandler CollectionChanged + { add => onCollectionChanged += value; remove => onCollectionChanged -= value; } - - public void Clear() { - for (int i = 0; i < items.Count; i++) { + + public void Clear() + { + for (int i = 0; i < items.Count; i++) + { DataGridTableStyle element = (DataGridTableStyle)items[i]; element.MappingNameChanged -= new EventHandler(TableStyleMappingNameChanged); } @@ -196,7 +230,8 @@ public void Clear() { /// /// Checks to see if a DataGridTableStyle is contained in this collection. /// - public bool Contains(DataGridTableStyle table) { + public bool Contains(DataGridTableStyle table) + { int index = items.IndexOf(table); return index != -1; } @@ -205,9 +240,11 @@ public bool Contains(DataGridTableStyle table) { /// Checks to see if a with the given name /// is contained in this collection. /// - public bool Contains(string name) { + public bool Contains(string name) + { int itemCount = items.Count; - for (int i = 0; i < itemCount; ++i) { + for (int i = 0; i < itemCount; ++i) + { DataGridTableStyle table = (DataGridTableStyle)items[i]; // NOTE: case-insensitive if (string.Compare(table.MappingName, name, true, CultureInfo.InvariantCulture) == 0) @@ -229,12 +266,14 @@ public override IEnumerator GetEnumerator(bool allowRemove) { } */ - protected void OnCollectionChanged(CollectionChangeEventArgs e) { + protected void OnCollectionChanged(CollectionChangeEventArgs e) + { if (onCollectionChanged != null) onCollectionChanged(this, e); DataGrid grid = owner; - if (grid != null) { + if (grid != null) + { /* FOR DEMO: Microsoft: TableStylesCollection::OnCollectionChanged: set the datagridtble DataView dataView = ((DataView) grid.DataSource); if (dataView != null) { @@ -250,11 +289,13 @@ protected void OnCollectionChanged(CollectionChangeEventArgs e) { } } - public void Remove(DataGridTableStyle table) { + public void Remove(DataGridTableStyle table) + { int tableIndex = -1; int itemsCount = items.Count; for (int i = 0; i < itemsCount; ++i) - if (items[i] == table) { + if (items[i] == table) + { tableIndex = i; break; } @@ -264,7 +305,8 @@ public void Remove(DataGridTableStyle table) { RemoveAt(tableIndex); } - public void RemoveAt(int index) { + public void RemoveAt(int index) + { DataGridTableStyle element = (DataGridTableStyle)items[index]; element.MappingNameChanged -= new EventHandler(TableStyleMappingNameChanged); items.RemoveAt(index); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBox.cs index 3f6f613e785..04f9406dbfa 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBox.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms{ +namespace System.Windows.Forms +{ using System; using System.Windows.Forms; using System.ComponentModel; @@ -20,7 +21,8 @@ namespace System.Windows.Forms{ ToolboxItem(false), DesignTimeVisible(false) ] - public class DataGridTextBox : TextBox { + public class DataGridTextBox : TextBox + { private bool isInEditOrNavigateMode = true; @@ -28,7 +30,8 @@ public class DataGridTextBox : TextBox { // takes place private DataGrid dataGrid; - public DataGridTextBox() : base () { + public DataGridTextBox() : base() + { TabStop = false; } /// @@ -39,10 +42,12 @@ public void SetDataGrid(DataGrid parentGrid) dataGrid = parentGrid; } - protected override void WndProc(ref Message m) { + protected override void WndProc(ref Message m) + { // but what if we get a CtrlV? // what about deleting from the menu? - if (m.Msg == Interop.WindowMessages.WM_PASTE || m.Msg == Interop.WindowMessages.WM_CUT || m.Msg == Interop.WindowMessages.WM_CLEAR) { + if (m.Msg == Interop.WindowMessages.WM_PASTE || m.Msg == Interop.WindowMessages.WM_CUT || m.Msg == Interop.WindowMessages.WM_CLEAR) + { IsInEditOrNavigateMode = false; dataGrid.ColumnStartedEditing(Bounds); } @@ -51,7 +56,8 @@ protected override void WndProc(ref Message m) { } - protected override void OnMouseWheel(MouseEventArgs e) { + protected override void OnMouseWheel(MouseEventArgs e) + { dataGrid.TextBoxOnMouseWheel(e); } @@ -94,7 +100,8 @@ protected internal override bool ProcessKeyMessage(ref Message m) return ProcessKeyPreview(ref m); } - if (m.Msg == Interop.WindowMessages.WM_CHAR) { + if (m.Msg == Interop.WindowMessages.WM_CHAR) + { if (key == Keys.LineFeed) // eat the LineFeed we get when the user presses Ctrl-Enter in a gridTextBox return true; return ProcessKeyEventArgs(ref m); @@ -143,7 +150,7 @@ protected internal override bool ProcessKeyMessage(ref Message m) // send this character to the dataGrid // else, process the KeyEvent // - if ( Text.IndexOf("\r\n") < 0 || SelectionStart + SelectionLength < Text.IndexOf("\r\n")) + if (Text.IndexOf("\r\n") < 0 || SelectionStart + SelectionLength < Text.IndexOf("\r\n")) return ProcessKeyPreview(ref m); return ProcessKeyEventArgs(ref m); case Keys.Home: @@ -171,23 +178,25 @@ protected internal override bool ProcessKeyMessage(ref Message m) case Keys.Space: if (IsInEditOrNavigateMode && (Control.ModifierKeys & Keys.Shift) == Keys.Shift) { - // when we get a SHIFT-SPACEBAR message, disregard the WM_CHAR part of the message - if (m.Msg == Interop.WindowMessages.WM_CHAR) return true; + // when we get a SHIFT-SPACEBAR message, disregard the WM_CHAR part of the message + if (m.Msg == Interop.WindowMessages.WM_CHAR) + return true; - // if the user pressed the SHIFT key at the same time with - // the space key, send the key message to the DataGrid - return ProcessKeyPreview(ref m); + // if the user pressed the SHIFT key at the same time with + // the space key, send the key message to the DataGrid + return ProcessKeyPreview(ref m); } return ProcessKeyEventArgs(ref m); case Keys.A: if (IsInEditOrNavigateMode && (Control.ModifierKeys & Keys.Control) == Keys.Control) { - // when we get a Control-A message, disregard the WM_CHAR part of the message - if (m.Msg == Interop.WindowMessages.WM_CHAR) return true; + // when we get a Control-A message, disregard the WM_CHAR part of the message + if (m.Msg == Interop.WindowMessages.WM_CHAR) + return true; - // if the user pressed the Control key at the same time with - // the space key, send the key message to the DataGrid - return ProcessKeyPreview(ref m); + // if the user pressed the Control key at the same time with + // the space key, send the key message to the DataGrid + return ProcessKeyPreview(ref m); } return ProcessKeyEventArgs(ref m); case Keys.F2: @@ -197,13 +206,15 @@ protected internal override bool ProcessKeyMessage(ref Message m) SelectionStart = Text.Length; return true; case Keys.Delete: - if (IsInEditOrNavigateMode) { + if (IsInEditOrNavigateMode) + { // pass the delete to the parent, in our case, the DataGrid // if the dataGrid used the key, then we aren't gonne // use it anymore, else we are if (ProcessKeyPreview(ref m)) return true; - else { + else + { // the edit control will use the // delete key: we are in Edit mode now: IsInEditOrNavigateMode = false; @@ -226,11 +237,14 @@ protected internal override bool ProcessKeyMessage(ref Message m) } } - public bool IsInEditOrNavigateMode { - get { + public bool IsInEditOrNavigateMode + { + get + { return isInEditOrNavigateMode; } - set { + set + { isInEditOrNavigateMode = value; if (value) SelectAll(); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs index c59f7407819..376dbeb428a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs @@ -2,16 +2,17 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; - + using System.Windows.Forms; using System.ComponentModel; using System.ComponentModel.Design; using System.Windows.Forms.ComponentModel; using System.Drawing; - + using Microsoft.Win32; using System.Diagnostics; using System.Globalization; @@ -20,11 +21,12 @@ namespace System.Windows.Forms { /// /// Hosts a System.Windows.Forms.TextBox control in a cell of a System.Windows.Forms.DataGridColumnStyle for editing strings. /// - public class DataGridTextBoxColumn : DataGridColumnStyle { + public class DataGridTextBoxColumn : DataGridColumnStyle + { // ui State - private int xMargin = 2; - private int yMargin = 1; + private int xMargin = 2; + private int yMargin = 1; // private int fontHandle = 0; private string format = null; private TypeConverter typeConverter; @@ -46,7 +48,8 @@ public class DataGridTextBoxColumn : DataGridColumnStyle { SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // If the constructor does not set format // it would be a breaking change. ] - public DataGridTextBoxColumn() : this(null, null) { + public DataGridTextBoxColumn() : this(null, null) + { } /// @@ -58,7 +61,8 @@ public DataGridTextBoxColumn() : this(null, null) { // it would be a breaking change. ] public DataGridTextBoxColumn(PropertyDescriptor prop) - : this(prop, null, false) { + : this(prop, null, false) + { } /// @@ -69,13 +73,14 @@ public DataGridTextBoxColumn(PropertyDescriptor prop) SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // If the constructor does not set format // it would be a breaking change. ] - public DataGridTextBoxColumn(PropertyDescriptor prop, string format) : this(prop, format, false){} + public DataGridTextBoxColumn(PropertyDescriptor prop, string format) : this(prop, format, false) { } [ SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // If the constructor does not set format // it would be a breaking change. ] - public DataGridTextBoxColumn(PropertyDescriptor prop, string format, bool isDefault) : base(prop, isDefault) { + public DataGridTextBoxColumn(PropertyDescriptor prop, string format, bool isDefault) : base(prop, isDefault) + { edit = new DataGridTextBox(); edit.BorderStyle = BorderStyle.None; edit.Multiline = true; @@ -88,7 +93,7 @@ public DataGridTextBoxColumn(PropertyDescriptor prop, string format, bool isDefa SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // If the constructor does not set format // it would be a breaking change. ] - public DataGridTextBoxColumn(PropertyDescriptor prop, bool isDefault) : this(prop, null, isDefault) {} + public DataGridTextBoxColumn(PropertyDescriptor prop, bool isDefault) : this(prop, null, isDefault) { } // =------------------------------------------------------------------ @@ -99,13 +104,16 @@ public DataGridTextBoxColumn(PropertyDescriptor prop, bool isDefault) : this(pro /// Gets the hosted System.Windows.Forms.TextBox control. /// [Browsable(false)] - public virtual TextBox TextBox { - get { + public virtual TextBox TextBox + { + get + { return edit; } } - internal override bool KeyPress(int rowNum, Keys keyData) { + internal override bool KeyPress(int rowNum, Keys keyData) + { if (edit.IsInEditOrNavigateMode) return base.KeyPress(rowNum, keyData); @@ -121,12 +129,15 @@ internal override bool KeyPress(int rowNum, Keys keyData) { /// . /// /// - protected override void SetDataGridInColumn(DataGrid value) { + protected override void SetDataGridInColumn(DataGrid value) + { base.SetDataGridInColumn(value); - if (edit.ParentInternal != null) { + if (edit.ParentInternal != null) + { edit.ParentInternal.Controls.Remove(edit); } - if (value != null) { + if (value != null) + { value.Controls.Add(edit); } @@ -155,13 +166,17 @@ public override Font Font { SRDescription(nameof(SR.FormatControlFormatDescr)), DefaultValue(null) ] - public override PropertyDescriptor PropertyDescriptor { - set { + public override PropertyDescriptor PropertyDescriptor + { + set + { base.PropertyDescriptor = value; - if (this.PropertyDescriptor != null) { - if (this.PropertyDescriptor.PropertyType != typeof(object)) { + if (this.PropertyDescriptor != null) + { + if (this.PropertyDescriptor.PropertyType != typeof(object)) + { this.typeConverter = TypeDescriptor.GetConverter(this.PropertyDescriptor.PropertyType); - this.parseMethod = this.PropertyDescriptor.PropertyType.GetMethod("Parse", new Type[]{typeof(string), typeof(IFormatProvider)}); + this.parseMethod = this.PropertyDescriptor.PropertyType.GetMethod("Parse", new Type[] { typeof(string), typeof(IFormatProvider) }); } } } @@ -170,20 +185,25 @@ public override PropertyDescriptor PropertyDescriptor { // add the corresponding value Editor: rip one from the valueEditor for the DisplayMember in the // format object [DefaultValue(null), Editor("System.Windows.Forms.Design.DataGridColumnStyleFormatEditor, " + AssemblyRef.SystemDesign, typeof(System.Drawing.Design.UITypeEditor))] - public string Format { - get { + public string Format + { + get + { return format; } - set { + set + { if (value == null) value = string.Empty; - if (format == null || !format.Equals(value)) { + if (format == null || !format.Equals(value)) + { this.format = value; // if the associated typeConverter cannot convert from string, // then we can't modify the column value. hence, make it readOnly // - if (format.Length == 0) { + if (format.Length == 0) + { if (this.typeConverter != null && !typeConverter.CanConvertFrom(typeof(string))) this.ReadOnly = true; } @@ -194,24 +214,31 @@ public string Format { } [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public IFormatProvider FormatInfo { - get { + public IFormatProvider FormatInfo + { + get + { return this.formatInfo; } - set { + set + { if (this.formatInfo == null || !this.formatInfo.Equals(value)) this.formatInfo = value; } } - public override bool ReadOnly { - get { + public override bool ReadOnly + { + get + { return base.ReadOnly; } - set { + set + { // if the gridColumn is can't convert the string to // the backGround propertyDescriptor, then make the column ReadOnly - if (!value && (format == null || format.Length == 0)) { + if (!value && (format == null || format.Length == 0)) + { if (this.typeConverter != null && !this.typeConverter.CanConvertFrom(typeof(string))) return; } @@ -223,7 +250,8 @@ public override bool ReadOnly { // = Methods // =------------------------------------------------------------------ - private void DebugOut(string s) { + private void DebugOut(string s) + { Debug.WriteLineIf(CompModSwitches.DGEditColumnEditing.TraceVerbose, "DGEditColumnEditing: " + s); } @@ -231,7 +259,8 @@ private void DebugOut(string s) { /// /// Informs the column the focus is being conceded. /// - protected internal override void ConcedeFocus() { + protected internal override void ConcedeFocus() + { edit.Bounds = Rectangle.Empty; // edit.Visible = false; // HideEditBox(); @@ -244,7 +273,8 @@ protected internal override void ConcedeFocus() { /// control. /// /// - protected void HideEditBox() { + protected void HideEditBox() + { bool wasFocused = edit.Focused; edit.Visible = false; @@ -262,7 +292,8 @@ protected void HideEditBox() { // before deleting the column will go to the backEnd) // however, in that situation, we are left w/ the editColumn which is not parented. // the grid will call Edit to reset the EditColumn - if (wasFocused && this.DataGridTableStyle != null && this.DataGridTableStyle.DataGrid != null && this.DataGridTableStyle.DataGrid.CanFocus) { + if (wasFocused && this.DataGridTableStyle != null && this.DataGridTableStyle.DataGrid != null && this.DataGridTableStyle.DataGrid.CanFocus) + { this.DataGridTableStyle.DataGrid.Focus(); Debug.Assert(!edit.Focused, "the edit control just conceeded focus to the dataGrid"); } @@ -280,7 +311,8 @@ protected internal override void UpdateUI(CurrencyManager source, int rowNum, st /// Ends an edit operation on the System.Windows.Forms.DataGridColumnStyle /// . /// - protected void EndEdit() { + protected void EndEdit() + { edit.IsInEditOrNavigateMode = true; DebugOut("Ending Edit"); Invalidate(); @@ -291,9 +323,10 @@ protected void EndEdit() { /// height of the cell in a specified row relative /// to the specified value. /// - protected internal override Size GetPreferredSize(Graphics g, object value) { + protected internal override Size GetPreferredSize(Graphics g, object value) + { Size extents = Size.Ceiling(g.MeasureString(GetText(value), DataGridTableStyle.DataGrid.Font)); - extents.Width += xMargin*2 + this.DataGridTableStyle.GridLineWidth; + extents.Width += xMargin * 2 + this.DataGridTableStyle.GridLineWidth; extents.Height += yMargin; return extents; } @@ -304,7 +337,8 @@ protected internal override Size GetPreferredSize(Graphics g, object value) { /// . /// /// - protected internal override int GetMinimumHeight() { + protected internal override int GetMinimumHeight() + { // why + 3? cause we have to give some way to the edit box. return FontHeight + yMargin + 3; } @@ -312,14 +346,15 @@ protected internal override int GetMinimumHeight() { /// /// Gets the height to be used in for automatically resizing columns. /// - protected internal override int GetPreferredHeight(Graphics g, object value) { + protected internal override int GetPreferredHeight(Graphics g, object value) + { int newLineIndex = 0; int newLines = 0; string valueString = GetText(value); while (newLineIndex != -1 && newLineIndex < valueString.Length) { newLineIndex = valueString.IndexOf("\r\n", newLineIndex + 1); - newLines ++; + newLines++; } return FontHeight * newLines + yMargin; @@ -330,7 +365,8 @@ protected internal override int GetPreferredHeight(Graphics g, object value) { /// Initiates a request to interrupt an edit procedure. /// /// - protected internal override void Abort(int rowNum) { + protected internal override void Abort(int rowNum) + { RollBack(); HideEditBox(); EndEdit(); @@ -342,7 +378,8 @@ protected internal override void Abort(int rowNum) { /// Enters a in the column. /// /// - protected internal override void EnterNullValue() { + protected internal override void EnterNullValue() + { if (this.ReadOnly) return; @@ -369,7 +406,8 @@ protected internal override void EnterNullValue() { /// Inititates a request to complete an editing procedure. /// /// - protected internal override bool Commit(CurrencyManager dataSource, int rowNum) { + protected internal override bool Commit(CurrencyManager dataSource, int rowNum) + { // always hide the edit box // HideEditBox(); edit.Bounds = Rectangle.Empty; @@ -377,33 +415,42 @@ protected internal override bool Commit(CurrencyManager dataSource, int rowNum) if (edit.IsInEditOrNavigateMode) return true; - try { + try + { object value = edit.Text; - if (NullText.Equals(value)) { + if (NullText.Equals(value)) + { value = Convert.DBNull; edit.Text = NullText; - } else if (format != null && format.Length != 0 && this.parseMethod != null && this.FormatInfo != null) { + } + else if (format != null && format.Length != 0 && this.parseMethod != null && this.FormatInfo != null) + { // use reflection to get the Parse method on the // type of the propertyDescriptor. - value = (object) parseMethod.Invoke(null, new object[] {edit.Text, this.FormatInfo}); - if (value is IFormattable) { + value = (object)parseMethod.Invoke(null, new object[] { edit.Text, this.FormatInfo }); + if (value is IFormattable) + { edit.Text = ((IFormattable)value).ToString(format, formatInfo); - }else + } + else edit.Text = value.ToString(); - } else if (typeConverter != null && typeConverter.CanConvertFrom(typeof(string))) { + } + else if (typeConverter != null && typeConverter.CanConvertFrom(typeof(string))) + { value = typeConverter.ConvertFromString(edit.Text); edit.Text = typeConverter.ConvertToString(value); } SetColumnValueAtRow(dataSource, rowNum, value); } - catch { - // MessageBox.Show("There was an error caught setting field \"" - // + this.PropertyDescriptor.Name + "\" to the value \"" + edit.Text + "\"\n" - // + "The value is being rolled back to the original.\n" - // + "The error was a '" + e.Message + "' " + e.StackTrace - // , "Error commiting changes...", MessageBox.IconError); - // Debug.WriteLine(e.GetType().Name); + catch + { + // MessageBox.Show("There was an error caught setting field \"" + // + this.PropertyDescriptor.Name + "\" to the value \"" + edit.Text + "\"\n" + // + "The value is being rolled back to the original.\n" + // + "The error was a '" + e.Message + "' " + e.StackTrace + // , "Error commiting changes...", MessageBox.IconError); + // Debug.WriteLine(e.GetType().Name); RollBack(); return false; } @@ -420,7 +467,8 @@ protected internal override void Edit(CurrencyManager source, Rectangle bounds, bool readOnly, string displayText, - bool cellIsVisible) { + bool cellIsVisible) + { DebugOut("Begining Edit, rowNum :" + rowNum.ToString(CultureInfo.InvariantCulture)); Rectangle originalBounds = bounds; @@ -428,7 +476,8 @@ protected internal override void Edit(CurrencyManager source, edit.ReadOnly = readOnly || ReadOnly || this.DataGridTableStyle.ReadOnly; edit.Text = GetText(GetColumnValueAtRow(source, rowNum)); - if (!edit.ReadOnly && displayText != null) { + if (!edit.ReadOnly && displayText != null) + { // tell the grid that we are changing stuff this.DataGridTableStyle.DataGrid.ColumnStartedEditing(bounds); // tell the edit control that the user changed it @@ -436,9 +485,10 @@ protected internal override void Edit(CurrencyManager source, edit.Text = displayText; } - if (cellIsVisible) { + if (cellIsVisible) + { bounds.Offset(xMargin, 2 * yMargin); - bounds.Width -= xMargin; + bounds.Width -= xMargin; bounds.Height -= 2 * yMargin; DebugOut("edit bounds: " + bounds.ToString()); edit.Bounds = bounds; @@ -447,7 +497,8 @@ protected internal override void Edit(CurrencyManager source, edit.TextAlign = this.Alignment; } - else { + else + { edit.Bounds = Rectangle.Empty; // edit.Bounds = originalBounds; // edit.Visible = false; @@ -459,7 +510,8 @@ protected internal override void Edit(CurrencyManager source, editRow = rowNum; - if (!edit.ReadOnly) { + if (!edit.ReadOnly) + { oldValue = edit.Text; } @@ -468,7 +520,8 @@ protected internal override void Edit(CurrencyManager source, // uses the SelectedText property if (displayText == null) edit.SelectAll(); - else { + else + { int end = edit.Text.Length; edit.Select(end, 0); } @@ -477,33 +530,41 @@ protected internal override void Edit(CurrencyManager source, DataGridTableStyle.DataGrid.Invalidate(originalBounds); } - internal override string GetDisplayText(object value) { + internal override string GetDisplayText(object value) + { return GetText(value); } - private string GetText(object value) { + private string GetText(object value) + { if (value is System.DBNull) return NullText; - else if (format != null && format.Length != 0 && (value is IFormattable)) { - try { + else if (format != null && format.Length != 0 && (value is IFormattable)) + { + try + { return ((IFormattable)value).ToString(format, this.formatInfo); } - catch { + catch + { // } - } else { + } + else + { // use the typeConverter: if (this.typeConverter != null && this.typeConverter.CanConvertTo(typeof(string))) return (string)this.typeConverter.ConvertTo(value, typeof(string)); } - return(value != null ? value.ToString() : ""); + return (value != null ? value.ToString() : ""); } /// /// Paints the a System.Windows.Forms.DataGridColumnStyle with the specified System.Drawing.Graphics, /// System.Drawing.Rectangle, DataView.Rectangle, and row number. /// - protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum) { + protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum) + { Paint(g, bounds, source, rowNum, false); } @@ -512,7 +573,8 @@ protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyMan /// Paints a System.Windows.Forms.DataGridColumnStyle with the specified System.Drawing.Graphics, System.Drawing.Rectangle, DataView, row number, and alignment. /// /// - protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, bool alignToRight) { + protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, bool alignToRight) + { string text = GetText(GetColumnValueAtRow(source, rowNum)); PaintText(g, bounds, text, alignToRight); } @@ -523,7 +585,8 @@ protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyMan /// and foreground color.. /// protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, - Brush backBrush, Brush foreBrush, bool alignToRight) { + Brush backBrush, Brush foreBrush, bool alignToRight) + { string text = GetText(GetColumnValueAtRow(source, rowNum)); PaintText(g, bounds, text, backBrush, foreBrush, alignToRight); } @@ -532,7 +595,8 @@ protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyMan /// Draws the text and /// rectangle at the given location with the specified alignment. /// - protected void PaintText(Graphics g, Rectangle bounds, string text, bool alignToRight) { + protected void PaintText(Graphics g, Rectangle bounds, string text, bool alignToRight) + { PaintText(g, bounds, text, this.DataGridTableStyle.BackBrush, this.DataGridTableStyle.ForeBrush, alignToRight); } @@ -540,7 +604,8 @@ protected void PaintText(Graphics g, Rectangle bounds, string text, bool alignTo /// Draws the text and rectangle at the specified location with the /// specified colors and alignment. /// - protected void PaintText(Graphics g, Rectangle textBounds, string text, Brush backBrush, Brush foreBrush, bool alignToRight) { + protected void PaintText(Graphics g, Rectangle textBounds, string text, Brush backBrush, Brush foreBrush, bool alignToRight) + { /* if (edit.Visible) g.BackColor = BackColor; @@ -549,7 +614,8 @@ protected void PaintText(Graphics g, Rectangle textBounds, string text, Brush ba Rectangle rect = textBounds; StringFormat format = new StringFormat(); - if (alignToRight) { + if (alignToRight) + { format.FormatFlags |= StringFormatFlags.DirectionRightToLeft; } @@ -562,19 +628,22 @@ protected void PaintText(Graphics g, Rectangle textBounds, string text, Brush ba g.FillRectangle(backBrush, rect); // by design, painting leaves a little padding around the rectangle. // so do not deflate the rectangle. - rect.Offset(0,2 * yMargin); + rect.Offset(0, 2 * yMargin); rect.Height -= 2 * yMargin; g.DrawString(text, this.DataGridTableStyle.DataGrid.Font, foreBrush, rect, format); format.Dispose(); } - private void RollBack() { + private void RollBack() + { Debug.Assert(!edit.IsInEditOrNavigateMode, "Must be editing to rollback changes..."); edit.Text = oldValue; } - protected internal override void ReleaseHostedControl() { - if (edit.ParentInternal != null) { + protected internal override void ReleaseHostedControl() + { + if (edit.ParentInternal != null) + { edit.ParentInternal.Controls.Remove(edit); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs index 60682ffb2a6..6f99e2ad308 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs @@ -2,10 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.InteropServices; using System.Drawing; - + using System.Windows.Forms; using Microsoft.Win32; using System.Diagnostics; @@ -13,7 +14,8 @@ namespace System.Windows.Forms { // this class is basically a NativeWindow that does toolTipping // should be one for the entire grid - internal class DataGridToolTip : MarshalByRefObject { + internal class DataGridToolTip : MarshalByRefObject + { // the toolTip control private NativeWindow tipWindow = null; @@ -23,7 +25,7 @@ internal class DataGridToolTip : MarshalByRefObject { // CONSTRUCTOR public DataGridToolTip(DataGrid dataGrid) { - Debug.Assert(dataGrid!= null, "can't attach a tool tip to a null grid"); + Debug.Assert(dataGrid != null, "can't attach a tool tip to a null grid"); this.dataGrid = dataGrid; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridView.cs index f762fa170c0..d729ca05025 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridView.cs @@ -154,96 +154,96 @@ public partial class DataGridView : Control, ISupportInitialize private static readonly object EVENT_DATAGRIDVIEWUSERDELETEDROW = new object(); private static readonly object EVENT_DATAGRIDVIEWUSERDELETINGROW = new object(); - private const int DATAGRIDVIEWSTATE1_allowUserToAddRows = 0x00000001; - private const int DATAGRIDVIEWSTATE1_allowUserToDeleteRows = 0x00000002; - private const int DATAGRIDVIEWSTATE1_allowUserToOrderColumns = 0x00000004; - private const int DATAGRIDVIEWSTATE1_columnHeadersVisible = 0x00000008; - private const int DATAGRIDVIEWSTATE1_rowHeadersVisible = 0x00000010; - private const int DATAGRIDVIEWSTATE1_forwardCharMessage = 0x00000020; - private const int DATAGRIDVIEWSTATE1_leavingWithTabKey = 0x00000040; - private const int DATAGRIDVIEWSTATE1_multiSelect = 0x00000080; - private const int DATAGRIDVIEWSTATE1_ignoringEditingChanges = 0x00000200; - private const int DATAGRIDVIEWSTATE1_ambientForeColor = 0x00000400; - private const int DATAGRIDVIEWSTATE1_scrolledSinceMouseDown = 0x00000800; - private const int DATAGRIDVIEWSTATE1_editingControlHidden = 0x00001000; - private const int DATAGRIDVIEWSTATE1_standardTab = 0x00002000; - private const int DATAGRIDVIEWSTATE1_editingControlChanging = 0x00004000; - private const int DATAGRIDVIEWSTATE1_currentCellInEditMode = 0x00008000; - private const int DATAGRIDVIEWSTATE1_virtualMode = 0x00010000; - private const int DATAGRIDVIEWSTATE1_editedCellChanged = 0x00020000; - private const int DATAGRIDVIEWSTATE1_editedRowChanged = 0x00040000; - private const int DATAGRIDVIEWSTATE1_newRowEdited = 0x00080000; - private const int DATAGRIDVIEWSTATE1_readOnly = 0x00100000; - private const int DATAGRIDVIEWSTATE1_newRowCreatedByEditing = 0x00200000; - private const int DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell = 0x00400000; - private const int DATAGRIDVIEWSTATE1_autoGenerateColumns = 0x00800000; - private const int DATAGRIDVIEWSTATE1_customCursorSet = 0x01000000; - private const int DATAGRIDVIEWSTATE1_ambientFont = 0x02000000; - private const int DATAGRIDVIEWSTATE1_ambientColumnHeadersFont = 0x04000000; - private const int DATAGRIDVIEWSTATE1_ambientRowHeadersFont = 0x08000000; - private const int DATAGRIDVIEWSTATE1_isAutoSized = 0x40000000; + private const int DATAGRIDVIEWSTATE1_allowUserToAddRows = 0x00000001; + private const int DATAGRIDVIEWSTATE1_allowUserToDeleteRows = 0x00000002; + private const int DATAGRIDVIEWSTATE1_allowUserToOrderColumns = 0x00000004; + private const int DATAGRIDVIEWSTATE1_columnHeadersVisible = 0x00000008; + private const int DATAGRIDVIEWSTATE1_rowHeadersVisible = 0x00000010; + private const int DATAGRIDVIEWSTATE1_forwardCharMessage = 0x00000020; + private const int DATAGRIDVIEWSTATE1_leavingWithTabKey = 0x00000040; + private const int DATAGRIDVIEWSTATE1_multiSelect = 0x00000080; + private const int DATAGRIDVIEWSTATE1_ignoringEditingChanges = 0x00000200; + private const int DATAGRIDVIEWSTATE1_ambientForeColor = 0x00000400; + private const int DATAGRIDVIEWSTATE1_scrolledSinceMouseDown = 0x00000800; + private const int DATAGRIDVIEWSTATE1_editingControlHidden = 0x00001000; + private const int DATAGRIDVIEWSTATE1_standardTab = 0x00002000; + private const int DATAGRIDVIEWSTATE1_editingControlChanging = 0x00004000; + private const int DATAGRIDVIEWSTATE1_currentCellInEditMode = 0x00008000; + private const int DATAGRIDVIEWSTATE1_virtualMode = 0x00010000; + private const int DATAGRIDVIEWSTATE1_editedCellChanged = 0x00020000; + private const int DATAGRIDVIEWSTATE1_editedRowChanged = 0x00040000; + private const int DATAGRIDVIEWSTATE1_newRowEdited = 0x00080000; + private const int DATAGRIDVIEWSTATE1_readOnly = 0x00100000; + private const int DATAGRIDVIEWSTATE1_newRowCreatedByEditing = 0x00200000; + private const int DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell = 0x00400000; + private const int DATAGRIDVIEWSTATE1_autoGenerateColumns = 0x00800000; + private const int DATAGRIDVIEWSTATE1_customCursorSet = 0x01000000; + private const int DATAGRIDVIEWSTATE1_ambientFont = 0x02000000; + private const int DATAGRIDVIEWSTATE1_ambientColumnHeadersFont = 0x04000000; + private const int DATAGRIDVIEWSTATE1_ambientRowHeadersFont = 0x08000000; + private const int DATAGRIDVIEWSTATE1_isAutoSized = 0x40000000; // DATAGRIDVIEWSTATE2_ - private const int DATAGRIDVIEWSTATE2_showEditingIcon = 0x00000001; - private const int DATAGRIDVIEWSTATE2_allowUserToResizeColumns = 0x00000002; - private const int DATAGRIDVIEWSTATE2_allowUserToResizeRows = 0x00000004; - private const int DATAGRIDVIEWSTATE2_mouseOverRemovedEditingCtrl = 0x00000008; - private const int DATAGRIDVIEWSTATE2_mouseOverRemovedEditingPanel = 0x00000010; - private const int DATAGRIDVIEWSTATE2_mouseEnterExpected = 0x00000020; - private const int DATAGRIDVIEWSTATE2_enableHeadersVisualStyles = 0x00000040; - private const int DATAGRIDVIEWSTATE2_showCellErrors = 0x00000080; - private const int DATAGRIDVIEWSTATE2_showCellToolTips = 0x00000100; - private const int DATAGRIDVIEWSTATE2_showRowErrors = 0x00000200; + private const int DATAGRIDVIEWSTATE2_showEditingIcon = 0x00000001; + private const int DATAGRIDVIEWSTATE2_allowUserToResizeColumns = 0x00000002; + private const int DATAGRIDVIEWSTATE2_allowUserToResizeRows = 0x00000004; + private const int DATAGRIDVIEWSTATE2_mouseOverRemovedEditingCtrl = 0x00000008; + private const int DATAGRIDVIEWSTATE2_mouseOverRemovedEditingPanel = 0x00000010; + private const int DATAGRIDVIEWSTATE2_mouseEnterExpected = 0x00000020; + private const int DATAGRIDVIEWSTATE2_enableHeadersVisualStyles = 0x00000040; + private const int DATAGRIDVIEWSTATE2_showCellErrors = 0x00000080; + private const int DATAGRIDVIEWSTATE2_showCellToolTips = 0x00000100; + private const int DATAGRIDVIEWSTATE2_showRowErrors = 0x00000200; private const int DATAGRIDVIEWSTATE2_showColumnRelocationInsertion = 0x00000400; - private const int DATAGRIDVIEWSTATE2_rightToLeftMode = 0x00000800; - private const int DATAGRIDVIEWSTATE2_rightToLeftValid = 0x00001000; - private const int DATAGRIDVIEWSTATE2_currentCellWantsInputKey = 0x00002000; - private const int DATAGRIDVIEWSTATE2_stopRaisingVerticalScroll = 0x00004000; - private const int DATAGRIDVIEWSTATE2_stopRaisingHorizontalScroll = 0x00008000; - private const int DATAGRIDVIEWSTATE2_replacedCellSelected = 0x00010000; - private const int DATAGRIDVIEWSTATE2_replacedCellReadOnly = 0x00020000; - private const int DATAGRIDVIEWSTATE2_raiseSelectionChanged = 0x00040000; - private const int DATAGRIDVIEWSTATE2_initializing = 0x00080000; - private const int DATAGRIDVIEWSTATE2_autoSizedWithoutHandle = 0x00100000; - private const int DATAGRIDVIEWSTATE2_ignoreCursorChange = 0x00200000; - private const int DATAGRIDVIEWSTATE2_rowsCollectionClearedInSetCell= 0x00400000; - private const int DATAGRIDVIEWSTATE2_nextMouseUpIsDouble = 0x00800000; - private const int DATAGRIDVIEWSTATE2_inBindingContextChanged = 0x01000000; - private const int DATAGRIDVIEWSTATE2_allowHorizontalScrollbar = 0x02000000; - private const int DATAGRIDVIEWSTATE2_usedFillWeightsDirty = 0x04000000; - private const int DATAGRIDVIEWSTATE2_messageFromEditingCtrls = 0x08000000; - private const int DATAGRIDVIEWSTATE2_cellMouseDownInContentBounds = 0x10000000; - private const int DATAGRIDVIEWSTATE2_discardEditingControl = 0x20000000; + private const int DATAGRIDVIEWSTATE2_rightToLeftMode = 0x00000800; + private const int DATAGRIDVIEWSTATE2_rightToLeftValid = 0x00001000; + private const int DATAGRIDVIEWSTATE2_currentCellWantsInputKey = 0x00002000; + private const int DATAGRIDVIEWSTATE2_stopRaisingVerticalScroll = 0x00004000; + private const int DATAGRIDVIEWSTATE2_stopRaisingHorizontalScroll = 0x00008000; + private const int DATAGRIDVIEWSTATE2_replacedCellSelected = 0x00010000; + private const int DATAGRIDVIEWSTATE2_replacedCellReadOnly = 0x00020000; + private const int DATAGRIDVIEWSTATE2_raiseSelectionChanged = 0x00040000; + private const int DATAGRIDVIEWSTATE2_initializing = 0x00080000; + private const int DATAGRIDVIEWSTATE2_autoSizedWithoutHandle = 0x00100000; + private const int DATAGRIDVIEWSTATE2_ignoreCursorChange = 0x00200000; + private const int DATAGRIDVIEWSTATE2_rowsCollectionClearedInSetCell = 0x00400000; + private const int DATAGRIDVIEWSTATE2_nextMouseUpIsDouble = 0x00800000; + private const int DATAGRIDVIEWSTATE2_inBindingContextChanged = 0x01000000; + private const int DATAGRIDVIEWSTATE2_allowHorizontalScrollbar = 0x02000000; + private const int DATAGRIDVIEWSTATE2_usedFillWeightsDirty = 0x04000000; + private const int DATAGRIDVIEWSTATE2_messageFromEditingCtrls = 0x08000000; + private const int DATAGRIDVIEWSTATE2_cellMouseDownInContentBounds = 0x10000000; + private const int DATAGRIDVIEWSTATE2_discardEditingControl = 0x20000000; // DATAGRIDVIEWOPER_ - private const int DATAGRIDVIEWOPER_trackColResize = 0x00000001; - private const int DATAGRIDVIEWOPER_trackRowResize = 0x00000002; - private const int DATAGRIDVIEWOPER_trackColSelect = 0x00000004; - private const int DATAGRIDVIEWOPER_trackRowSelect = 0x00000008; - private const int DATAGRIDVIEWOPER_trackCellSelect = 0x00000010; - private const int DATAGRIDVIEWOPER_trackColRelocation = 0x00000020; - private const int DATAGRIDVIEWOPER_inSort = 0x00000040; - private const int DATAGRIDVIEWOPER_trackColHeadersResize = 0x00000080; - private const int DATAGRIDVIEWOPER_trackRowHeadersResize = 0x00000100; - private const int DATAGRIDVIEWOPER_trackMouseMoves = 0x00000200; - private const int DATAGRIDVIEWOPER_inRefreshColumns = 0x00000400; - private const int DATAGRIDVIEWOPER_inDisplayIndexAdjustments = 0x00000800; - private const int DATAGRIDVIEWOPER_lastEditCtrlClickDoubled = 0x00001000; - private const int DATAGRIDVIEWOPER_inMouseDown = 0x00002000; - private const int DATAGRIDVIEWOPER_inReadOnlyChange = 0x00004000; - private const int DATAGRIDVIEWOPER_inCellValidating = 0x00008000; - private const int DATAGRIDVIEWOPER_inBorderStyleChange = 0x00010000; - private const int DATAGRIDVIEWOPER_inCurrentCellChange = 0x00020000; - private const int DATAGRIDVIEWOPER_inAdjustFillingColumns = 0x00040000; - private const int DATAGRIDVIEWOPER_inAdjustFillingColumn = 0x00080000; - private const int DATAGRIDVIEWOPER_inDispose = 0x00100000; - private const int DATAGRIDVIEWOPER_inBeginEdit = 0x00200000; - private const int DATAGRIDVIEWOPER_inEndEdit = 0x00400000; + private const int DATAGRIDVIEWOPER_trackColResize = 0x00000001; + private const int DATAGRIDVIEWOPER_trackRowResize = 0x00000002; + private const int DATAGRIDVIEWOPER_trackColSelect = 0x00000004; + private const int DATAGRIDVIEWOPER_trackRowSelect = 0x00000008; + private const int DATAGRIDVIEWOPER_trackCellSelect = 0x00000010; + private const int DATAGRIDVIEWOPER_trackColRelocation = 0x00000020; + private const int DATAGRIDVIEWOPER_inSort = 0x00000040; + private const int DATAGRIDVIEWOPER_trackColHeadersResize = 0x00000080; + private const int DATAGRIDVIEWOPER_trackRowHeadersResize = 0x00000100; + private const int DATAGRIDVIEWOPER_trackMouseMoves = 0x00000200; + private const int DATAGRIDVIEWOPER_inRefreshColumns = 0x00000400; + private const int DATAGRIDVIEWOPER_inDisplayIndexAdjustments = 0x00000800; + private const int DATAGRIDVIEWOPER_lastEditCtrlClickDoubled = 0x00001000; + private const int DATAGRIDVIEWOPER_inMouseDown = 0x00002000; + private const int DATAGRIDVIEWOPER_inReadOnlyChange = 0x00004000; + private const int DATAGRIDVIEWOPER_inCellValidating = 0x00008000; + private const int DATAGRIDVIEWOPER_inBorderStyleChange = 0x00010000; + private const int DATAGRIDVIEWOPER_inCurrentCellChange = 0x00020000; + private const int DATAGRIDVIEWOPER_inAdjustFillingColumns = 0x00040000; + private const int DATAGRIDVIEWOPER_inAdjustFillingColumn = 0x00080000; + private const int DATAGRIDVIEWOPER_inDispose = 0x00100000; + private const int DATAGRIDVIEWOPER_inBeginEdit = 0x00200000; + private const int DATAGRIDVIEWOPER_inEndEdit = 0x00400000; private const int DATAGRIDVIEWOPER_resizingOperationAboutToStart = 0x00800000; - private const int DATAGRIDVIEWOPER_trackKeyboardColResize = 0x01000000; - private const int DATAGRIDVIEWOPER_mouseOperationMask = DATAGRIDVIEWOPER_trackColResize | DATAGRIDVIEWOPER_trackRowResize | + private const int DATAGRIDVIEWOPER_trackKeyboardColResize = 0x01000000; + private const int DATAGRIDVIEWOPER_mouseOperationMask = DATAGRIDVIEWOPER_trackColResize | DATAGRIDVIEWOPER_trackRowResize | DATAGRIDVIEWOPER_trackColRelocation | DATAGRIDVIEWOPER_trackColHeadersResize | DATAGRIDVIEWOPER_trackRowHeadersResize; - private const int DATAGRIDVIEWOPER_keyboardOperationMask = DATAGRIDVIEWOPER_trackKeyboardColResize; + private const int DATAGRIDVIEWOPER_keyboardOperationMask = DATAGRIDVIEWOPER_trackKeyboardColResize; private static Size DragSize = SystemInformation.DragSize; @@ -396,7 +396,7 @@ public partial class DataGridView : Control, ISupportInitialize private DataGridViewToolTip toolTipControl; // the tool tip string we get from cells private string toolTipCaption = string.Empty; - + private const int maxTTDISPINFOBufferLength = 80; // Last Mouse Click Info @@ -415,28 +415,28 @@ public partial class DataGridView : Control, ISupportInitialize /// public DataGridView() { - SetStyle(ControlStyles.UserPaint | - ControlStyles.Opaque | + SetStyle(ControlStyles.UserPaint | + ControlStyles.Opaque | ControlStyles.UserMouse, true); - + SetStyle(ControlStyles.SupportsTransparentBackColor, false); // this class overrides GetPreferredSizeCore, let Control automatically cache the result - SetState2(STATE2_USEPREFERREDSIZECACHE, true); + SetState2(STATE2_USEPREFERREDSIZECACHE, true); this.dataGridViewState1 = new System.Collections.Specialized.BitVector32(0x00000000); this.dataGridViewState2 = new System.Collections.Specialized.BitVector32(0x00000000); - this.dataGridViewOper = new System.Collections.Specialized.BitVector32(0x00000000); + this.dataGridViewOper = new System.Collections.Specialized.BitVector32(0x00000000); - this.dataGridViewState1[ DATAGRIDVIEWSTATE1_columnHeadersVisible - | DATAGRIDVIEWSTATE1_rowHeadersVisible + this.dataGridViewState1[DATAGRIDVIEWSTATE1_columnHeadersVisible + | DATAGRIDVIEWSTATE1_rowHeadersVisible | DATAGRIDVIEWSTATE1_autoGenerateColumns | DATAGRIDVIEWSTATE1_allowUserToAddRows - | DATAGRIDVIEWSTATE1_allowUserToDeleteRows ] = true; + | DATAGRIDVIEWSTATE1_allowUserToDeleteRows] = true; - this.dataGridViewState2[ DATAGRIDVIEWSTATE2_showEditingIcon + this.dataGridViewState2[DATAGRIDVIEWSTATE2_showEditingIcon | DATAGRIDVIEWSTATE2_enableHeadersVisualStyles | DATAGRIDVIEWSTATE2_mouseEnterExpected | DATAGRIDVIEWSTATE2_allowUserToResizeColumns @@ -445,7 +445,7 @@ this.dataGridViewState2[ DATAGRIDVIEWSTATE2_showEditingIcon | DATAGRIDVIEWSTATE2_showCellErrors | DATAGRIDVIEWSTATE2_showRowErrors | DATAGRIDVIEWSTATE2_allowHorizontalScrollbar - | DATAGRIDVIEWSTATE2_usedFillWeightsDirty ] = true; + | DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = true; this.displayedBandsInfo = new DisplayedBandsData(); @@ -460,9 +460,9 @@ this.dataGridViewState2[ DATAGRIDVIEWSTATE2_showEditingIcon this.individualSelectedCells = new DataGridViewCellLinkedList(); this.individualReadOnlyCells = new DataGridViewCellLinkedList(); - this.advancedCellBorderStyle = new DataGridViewAdvancedBorderStyle(this, - DataGridViewAdvancedCellBorderStyle.OutsetDouble, - DataGridViewAdvancedCellBorderStyle.OutsetPartial, + this.advancedCellBorderStyle = new DataGridViewAdvancedBorderStyle(this, + DataGridViewAdvancedCellBorderStyle.OutsetDouble, + DataGridViewAdvancedCellBorderStyle.OutsetPartial, DataGridViewAdvancedCellBorderStyle.InsetDouble); this.advancedRowHeadersBorderStyle = new DataGridViewAdvancedBorderStyle(this); this.advancedColumnHeadersBorderStyle = new DataGridViewAdvancedBorderStyle(this); @@ -481,12 +481,12 @@ this.dataGridViewState2[ DATAGRIDVIEWSTATE2_showEditingIcon this.clipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithAutoHeaderText; this.layout = new LayoutData(); - this.layout.TopLeftHeader = Rectangle.Empty; - this.layout.ColumnHeaders = Rectangle.Empty; - this.layout.RowHeaders = Rectangle.Empty; + this.layout.TopLeftHeader = Rectangle.Empty; + this.layout.ColumnHeaders = Rectangle.Empty; + this.layout.RowHeaders = Rectangle.Empty; this.layout.ColumnHeadersVisible = true; - this.layout.RowHeadersVisible = true; - this.layout.ClientRectangle = this.ClientRectangle; + this.layout.RowHeadersVisible = true; + this.layout.ClientRectangle = this.ClientRectangle; this.scrollBars = ScrollBars.Both; @@ -672,7 +672,7 @@ public virtual DataGridViewAdvancedBorderStyle AdjustedTopLeftHeaderBorderStyle ] public DataGridViewAdvancedBorderStyle AdvancedCellBorderStyle { - get + get { return this.advancedCellBorderStyle; } @@ -743,7 +743,7 @@ internal bool AllowUserToAddRowsInternal } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewOnAllowUserToAddRowsChangedDescr)) ] public event EventHandler AllowUserToAddRowsChanged @@ -789,7 +789,7 @@ internal bool AllowUserToDeleteRowsInternal } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewOnAllowUserToDeleteRowsChangedDescr)) ] public event EventHandler AllowUserToDeleteRowsChanged @@ -820,7 +820,7 @@ public bool AllowUserToOrderColumns } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewOnAllowUserToOrderColumnsChangedDescr)) ] public event EventHandler AllowUserToOrderColumnsChanged @@ -857,7 +857,7 @@ public bool AllowUserToResizeColumns } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewOnAllowUserToResizeColumnsChangedDescr)) ] public event EventHandler AllowUserToResizeColumnsChanged @@ -894,7 +894,7 @@ public bool AllowUserToResizeRows } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewOnAllowUserToResizeRowsChangedDescr)) ] public event EventHandler AllowUserToResizeRowsChanged @@ -937,7 +937,7 @@ public DataGridViewCellStyle AlternatingRowsDefaultCellStyle } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewAlternatingRowsDefaultCellStyleChangedDescr)) ] public event EventHandler AlternatingRowsDefaultCellStyleChanged @@ -977,7 +977,8 @@ public bool AutoGenerateColumns { return this.dataGridViewState1[DATAGRIDVIEWSTATE1_autoGenerateColumns]; } - set{ + set + { if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_autoGenerateColumns] != value) { this.dataGridViewState1[DATAGRIDVIEWSTATE1_autoGenerateColumns] = value; @@ -1028,11 +1029,11 @@ public DataGridViewAutoSizeColumnsMode AutoSizeColumnsMode { return this.autoSizeColumnsMode; } - + set { - switch (value) - { + switch (value) + { case DataGridViewAutoSizeColumnsMode.None: case DataGridViewAutoSizeColumnsMode.ColumnHeader: case DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader: @@ -1041,9 +1042,9 @@ public DataGridViewAutoSizeColumnsMode AutoSizeColumnsMode case DataGridViewAutoSizeColumnsMode.DisplayedCells: case DataGridViewAutoSizeColumnsMode.Fill: break; - default: - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewAutoSizeColumnsMode)); - } + default: + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewAutoSizeColumnsMode)); + } if (this.autoSizeColumnsMode != value) @@ -1081,7 +1082,7 @@ public DataGridViewAutoSizeColumnsMode AutoSizeColumnsMode } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewAutoSizeColumnsModeChangedDescr)) ] public event DataGridViewAutoSizeColumnsModeEventHandler AutoSizeColumnsModeChanged @@ -1106,20 +1107,20 @@ public DataGridViewAutoSizeRowsMode AutoSizeRowsMode } set { - switch (value) - { - case DataGridViewAutoSizeRowsMode.None: - case DataGridViewAutoSizeRowsMode.AllHeaders: - case DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders: - case DataGridViewAutoSizeRowsMode.AllCells: - case DataGridViewAutoSizeRowsMode.DisplayedHeaders: - case DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders: - case DataGridViewAutoSizeRowsMode.DisplayedCells: - break; - default: - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewAutoSizeRowsMode)); - } - if ((value == DataGridViewAutoSizeRowsMode.AllHeaders || value == DataGridViewAutoSizeRowsMode.DisplayedHeaders) && + switch (value) + { + case DataGridViewAutoSizeRowsMode.None: + case DataGridViewAutoSizeRowsMode.AllHeaders: + case DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders: + case DataGridViewAutoSizeRowsMode.AllCells: + case DataGridViewAutoSizeRowsMode.DisplayedHeaders: + case DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders: + case DataGridViewAutoSizeRowsMode.DisplayedCells: + break; + default: + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewAutoSizeRowsMode)); + } + if ((value == DataGridViewAutoSizeRowsMode.AllHeaders || value == DataGridViewAutoSizeRowsMode.DisplayedHeaders) && !this.RowHeadersVisible) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAutoSizeRowsInvisibleRowHeader)); @@ -1134,7 +1135,7 @@ public DataGridViewAutoSizeRowsMode AutoSizeRowsMode } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewAutoSizeRowsModeChangedDescr)) ] public event DataGridViewAutoSizeModeEventHandler AutoSizeRowsModeChanged @@ -1142,19 +1143,19 @@ public event DataGridViewAutoSizeModeEventHandler AutoSizeRowsModeChanged add => this.Events.AddHandler(EVENT_DATAGRIDVIEWAUTOSIZEROWSMODECHANGED, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWAUTOSIZEROWSMODECHANGED, value); } - + [ - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public override Color BackColor { - get + get { return base.BackColor; } - set + set { base.BackColor = value; } @@ -1170,9 +1171,9 @@ public override Color BackColor remove => base.BackColorChanged -= value; } - internal SolidBrush BackgroundBrush + internal SolidBrush BackgroundBrush { - get + get { return this.backgroundBrush; } @@ -1201,7 +1202,7 @@ public Color BackgroundColor { throw new ArgumentException(string.Format(SR.DataGridView_TransparentColor, "BackgroundColor")); } - if (!value.Equals(this.backgroundBrush.Color)) + if (!value.Equals(this.backgroundBrush.Color)) { this.backgroundBrush = new SolidBrush(value); OnBackgroundColorChanged(EventArgs.Empty); @@ -1210,10 +1211,10 @@ public Color BackgroundColor } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewBackgroundColorChangedDescr)) ] - public event EventHandler BackgroundColorChanged + public event EventHandler BackgroundColorChanged { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWBACKGROUNDCOLORCHANGED, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWBACKGROUNDCOLORCHANGED, value); @@ -1283,17 +1284,18 @@ private bool ShouldSerializeBackgroundColor() ] public BorderStyle BorderStyle { - get + get { return this.borderStyle; } - set + set { // Sequential enum. Valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)){ - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(BorderStyle)); + if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)) + { + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(BorderStyle)); } - if (this.borderStyle != value) + if (this.borderStyle != value) { using (LayoutTransaction.CreateTransactionIf(this.AutoSize, this.ParentInternal, this, PropertyNames.BorderStyle)) { @@ -1310,7 +1312,7 @@ public BorderStyle BorderStyle } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewBorderStyleChangedDescr)) ] public event EventHandler BorderStyleChanged @@ -1319,19 +1321,19 @@ public event EventHandler BorderStyleChanged remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWBORDERSTYLECHANGED, value); } - internal int BorderWidth + internal int BorderWidth { - get + get { - if (this.BorderStyle == BorderStyle.Fixed3D) + if (this.BorderStyle == BorderStyle.Fixed3D) { return Application.RenderWithVisualStyles ? 1 : SystemInformation.Border3DSize.Width; } - else if (this.BorderStyle == BorderStyle.FixedSingle) + else if (this.BorderStyle == BorderStyle.FixedSingle) { return 1; } - else + else { return 0; } @@ -1345,7 +1347,7 @@ protected override bool CanEnableIme { bool canEnable = false; - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_CanEnableIme(), this = " + this ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_CanEnableIme(), this = " + this); Debug.Indent(); if (this.ptCurrentCell.X != -1 /*&& !this.IsCurrentCellInEditMode*/ && ColumnEditable(this.ptCurrentCell.X)) @@ -1359,7 +1361,7 @@ protected override bool CanEnableIme } } - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Value = " + canEnable ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Value = " + canEnable); Debug.Unindent(); return canEnable; @@ -1374,7 +1376,7 @@ protected override bool CanEnableIme ] public DataGridViewCellBorderStyle CellBorderStyle { - get + get { switch (this.advancedCellBorderStyle.All) { @@ -1398,12 +1400,12 @@ public DataGridViewCellBorderStyle CellBorderStyle return DataGridViewCellBorderStyle.SingleVertical; } } - if (this.advancedCellBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.Outset && + if (this.advancedCellBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.Outset && this.advancedCellBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.Outset) { return DataGridViewCellBorderStyle.RaisedVertical; } - if (this.advancedCellBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.Inset && + if (this.advancedCellBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.Inset && this.advancedCellBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.Inset) { return DataGridViewCellBorderStyle.SunkenVertical; @@ -1417,12 +1419,12 @@ public DataGridViewCellBorderStyle CellBorderStyle { return DataGridViewCellBorderStyle.SingleHorizontal; } - if (this.advancedCellBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.Outset && + if (this.advancedCellBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.Outset && this.advancedCellBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.Outset) { return DataGridViewCellBorderStyle.RaisedHorizontal; } - if (this.advancedCellBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.Inset && + if (this.advancedCellBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.Inset && this.advancedCellBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.Inset) { return DataGridViewCellBorderStyle.SunkenHorizontal; @@ -1452,7 +1454,7 @@ public DataGridViewCellBorderStyle CellBorderStyle // Sequential enum. Valid values are 0x0 to 0xa if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridViewCellBorderStyle.Custom, (int)DataGridViewCellBorderStyle.SunkenHorizontal)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewCellBorderStyle)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewCellBorderStyle)); } if (value != this.CellBorderStyle) @@ -1534,7 +1536,7 @@ public DataGridViewCellBorderStyle CellBorderStyle } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridView_CellBorderStyleChangedDescr)) ] public event EventHandler CellBorderStyleChanged @@ -1577,7 +1579,7 @@ private DataGridViewCellStyleChangedEventArgs CellStyleChangedEventArgs } return this.dgvcsce; } - } + } internal DataGridViewCellValueEventArgs CellValueEventArgs { @@ -1608,7 +1610,7 @@ public DataGridViewClipboardCopyMode ClipboardCopyMode // Sequential enum. Valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridViewClipboardCopyMode.Disable, (int)DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewClipboardCopyMode)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewClipboardCopyMode)); } this.clipboardCopyMode = value; } @@ -1683,7 +1685,7 @@ public int ColumnCount ] public DataGridViewHeaderBorderStyle ColumnHeadersBorderStyle { - get + get { switch (this.advancedColumnHeadersBorderStyle.All) { @@ -1711,7 +1713,7 @@ public DataGridViewHeaderBorderStyle ColumnHeadersBorderStyle // Sequential enum. Valid values are 0x0 to 0x4 if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridViewHeaderBorderStyle.Custom, (int)DataGridViewHeaderBorderStyle.None)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewHeaderBorderStyle)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewHeaderBorderStyle)); } if (value != this.ColumnHeadersBorderStyle) { @@ -1751,7 +1753,7 @@ public DataGridViewHeaderBorderStyle ColumnHeadersBorderStyle } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridView_ColumnHeadersBorderStyleChangedDescr)) ] public event EventHandler ColumnHeadersBorderStyleChanged @@ -1767,7 +1769,7 @@ public event EventHandler ColumnHeadersBorderStyleChanged ] public DataGridViewCellStyle ColumnHeadersDefaultCellStyle { - get + get { if (this.columnHeadersDefaultCellStyle == null) { @@ -1775,7 +1777,7 @@ public DataGridViewCellStyle ColumnHeadersDefaultCellStyle } return this.columnHeadersDefaultCellStyle; } - set + set { DataGridViewCellStyle cs = this.ColumnHeadersDefaultCellStyle; cs.RemoveScope(DataGridViewCellStyleScopes.ColumnHeaders); @@ -1793,7 +1795,8 @@ public DataGridViewCellStyle ColumnHeadersDefaultCellStyle } } - private DataGridViewCellStyle DefaultColumnHeadersDefaultCellStyle { + private DataGridViewCellStyle DefaultColumnHeadersDefaultCellStyle + { get { DataGridViewCellStyle defaultStyle = new DataGridViewCellStyle(); @@ -1813,7 +1816,7 @@ private DataGridViewCellStyle DefaultColumnHeadersDefaultCellStyle { } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewColumnHeadersDefaultCellStyleChangedDescr)) ] public event EventHandler ColumnHeadersDefaultCellStyleChanged @@ -1824,16 +1827,16 @@ public event EventHandler ColumnHeadersDefaultCellStyleChanged [ SRCategory(nameof(SR.CatAppearance)), - Localizable(true), + Localizable(true), SRDescription(nameof(SR.DataGridView_ColumnHeadersHeightDescr)) ] public int ColumnHeadersHeight { - get + get { return this.columnHeadersHeight; } - set + set { if (value < minimumColumnHeadersHeight) { @@ -1855,7 +1858,7 @@ public int ColumnHeadersHeight } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewColumnHeadersHeightChangedDescr)) ] public event EventHandler ColumnHeadersHeightChanged @@ -1888,10 +1891,10 @@ public DataGridViewColumnHeadersHeightSizeMode ColumnHeadersHeightSizeMode } set { - // Sequential enum. Valid values are 0x0 to 0x2 + // Sequential enum. Valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridViewColumnHeadersHeightSizeMode.EnableResizing, (int)DataGridViewColumnHeadersHeightSizeMode.AutoSize)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewColumnHeadersHeightSizeMode)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewColumnHeadersHeightSizeMode)); } if (this.columnHeadersHeightSizeMode != value) { @@ -1907,7 +1910,7 @@ public DataGridViewColumnHeadersHeightSizeMode ColumnHeadersHeightSizeMode } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridView_ColumnHeadersHeightSizeModeChangedDescr)) ] public event DataGridViewAutoSizeModeEventHandler ColumnHeadersHeightSizeModeChanged @@ -1937,13 +1940,13 @@ public event DataGridViewAutoSizeModeEventHandler ColumnHeadersHeightSizeModeCha DefaultValue(true), SRDescription(nameof(SR.DataGridViewColumnHeadersVisibleDescr)) ] - public bool ColumnHeadersVisible + public bool ColumnHeadersVisible { - get + get { return this.dataGridViewState1[DATAGRIDVIEWSTATE1_columnHeadersVisible]; } - set + set { if (this.ColumnHeadersVisible != value) { @@ -2010,7 +2013,7 @@ public DataGridViewCell CurrentCell Debug.Assert(this.ptCurrentCell.X >= 0 && ptCurrentCell.Y >= 0); Debug.Assert(this.ptCurrentCell.X < this.Columns.Count); Debug.Assert(this.ptCurrentCell.Y < this.Rows.Count); - DataGridViewRow dataGridViewRow = (DataGridViewRow) this.Rows[this.ptCurrentCell.Y]; // unsharing row + DataGridViewRow dataGridViewRow = (DataGridViewRow)this.Rows[this.ptCurrentCell.Y]; // unsharing row return dataGridViewRow.Cells[this.ptCurrentCell.X]; } set @@ -2136,7 +2139,7 @@ private bool CurrentCellIsEditedAndOnlySelectedCell [ Browsable(false) ] - public DataGridViewRow CurrentRow + public DataGridViewRow CurrentRow { get { @@ -2211,7 +2214,7 @@ public string DataMember } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewDataMemberChangedDescr)) ] public event EventHandler DataMemberChanged @@ -2269,7 +2272,7 @@ public object DataSource } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewDataSourceChangedDescr)) ] public event EventHandler DataSourceChanged @@ -2278,19 +2281,19 @@ public event EventHandler DataSourceChanged remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWDATASOURCECHANGED, value); } - private static SolidBrush DefaultBackBrush + private static SolidBrush DefaultBackBrush { - get + get { - return (SolidBrush) SystemBrushes.Window; + return (SolidBrush)SystemBrushes.Window; } } - private static SolidBrush DefaultBackgroundBrush + private static SolidBrush DefaultBackgroundBrush { - get + get { - return (SolidBrush) SystemBrushes.AppWorkspace; + return (SolidBrush)SystemBrushes.AppWorkspace; } } @@ -2299,21 +2302,21 @@ private static SolidBrush DefaultBackgroundBrush SRDescription(nameof(SR.DataGridView_DefaultCellStyleDescr)), AmbientValue(null) ] - public DataGridViewCellStyle DefaultCellStyle + public DataGridViewCellStyle DefaultCellStyle { - get + get { if (this.defaultCellStyle == null) { - this.defaultCellStyle = this.DefaultDefaultCellStyle; + this.defaultCellStyle = this.DefaultDefaultCellStyle; return this.defaultCellStyle; } - else if (this.defaultCellStyle.BackColor == Color.Empty || - this.defaultCellStyle.ForeColor == Color.Empty || - this.defaultCellStyle.SelectionBackColor == Color.Empty || - this.defaultCellStyle.SelectionForeColor == Color.Empty || - this.defaultCellStyle.Font == null || - this.defaultCellStyle.Alignment == DataGridViewContentAlignment.NotSet || + else if (this.defaultCellStyle.BackColor == Color.Empty || + this.defaultCellStyle.ForeColor == Color.Empty || + this.defaultCellStyle.SelectionBackColor == Color.Empty || + this.defaultCellStyle.SelectionForeColor == Color.Empty || + this.defaultCellStyle.Font == null || + this.defaultCellStyle.Alignment == DataGridViewContentAlignment.NotSet || this.defaultCellStyle.WrapMode == DataGridViewTriState.NotSet) { DataGridViewCellStyle defaultCellStyleTmp = new DataGridViewCellStyle(this.defaultCellStyle); @@ -2356,7 +2359,7 @@ public DataGridViewCellStyle DefaultCellStyle return this.defaultCellStyle; } } - set + set { DataGridViewCellStyle cs = this.DefaultCellStyle; cs.RemoveScope(DataGridViewCellStyleScopes.DataGridView); @@ -2374,9 +2377,9 @@ public DataGridViewCellStyle DefaultCellStyle } } - private DataGridViewCellStyle DefaultDefaultCellStyle + private DataGridViewCellStyle DefaultDefaultCellStyle { - get + get { DataGridViewCellStyle defaultCellStyle = new DataGridViewCellStyle(); defaultCellStyle.BackColor = DefaultBackBrush.Color; @@ -2390,13 +2393,13 @@ private DataGridViewCellStyle DefaultDefaultCellStyle this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientFont] = true; this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientForeColor] = true; - + return defaultCellStyle; } } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewDefaultCellStyleChangedDescr)) ] public event EventHandler DefaultCellStyleChanged @@ -2405,17 +2408,17 @@ public event EventHandler DefaultCellStyleChanged remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWDEFAULTCELLSTYLECHANGED, value); } - private static SolidBrush DefaultForeBrush + private static SolidBrush DefaultForeBrush { - get + get { - return (SolidBrush) SystemBrushes.WindowText; + return (SolidBrush)SystemBrushes.WindowText; } } private static Color DefaultGridColor { - get + get { return SystemColors.ControlDark; } @@ -2423,15 +2426,15 @@ private static Color DefaultGridColor private static SolidBrush DefaultHeadersBackBrush { - get + get { - return (SolidBrush) SystemBrushes.Control; + return (SolidBrush)SystemBrushes.Control; } } private DataGridViewCellStyle DefaultRowHeadersDefaultCellStyle { - get + get { DataGridViewCellStyle defaultStyle = new DataGridViewCellStyle(); defaultStyle.BackColor = DefaultHeadersBackBrush.Color; @@ -2449,19 +2452,19 @@ private DataGridViewCellStyle DefaultRowHeadersDefaultCellStyle } } - private static SolidBrush DefaultSelectionBackBrush + private static SolidBrush DefaultSelectionBackBrush { - get + get { - return (SolidBrush) SystemBrushes.Highlight; + return (SolidBrush)SystemBrushes.Highlight; } } - - private static SolidBrush DefaultSelectionForeBrush + + private static SolidBrush DefaultSelectionForeBrush { - get + get { - return (SolidBrush) SystemBrushes.HighlightText; + return (SolidBrush)SystemBrushes.HighlightText; } } @@ -2485,8 +2488,10 @@ internal DisplayedBandsData DisplayedBandsInfo /// Returns the client rect of the display area of the control. /// The DataGridView control return its client rectangle minus the potential scrollbars. /// - public override Rectangle DisplayRectangle { - get { + public override Rectangle DisplayRectangle + { + get + { Rectangle rectDisplay = this.ClientRectangle; if (this.horizScrollBar != null && this.horizScrollBar.Visible) { @@ -2520,8 +2525,8 @@ public DataGridViewEditMode EditMode // Sequential enum. Valid values are 0x0 to 0x4 if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridViewEditMode.EditOnEnter, (int)DataGridViewEditMode.EditProgrammatically)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewEditMode)); - } + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewEditMode)); + } if (this.editMode != value) { this.editMode = value; @@ -2531,7 +2536,7 @@ public DataGridViewEditMode EditMode } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridView_EditModeChangedDescr)) ] public event EventHandler EditModeChanged @@ -2766,7 +2771,7 @@ internal int FirstDisplayedColumnIndex { return -1; } - + int firstDisplayedColumnIndex = -1; DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); if (dataGridViewColumn != null) @@ -2903,8 +2908,8 @@ public int FirstDisplayedScrollingColumnIndex return; } - if (this.ptCurrentCell.X >= 0 && - !CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, + if (this.ptCurrentCell.X >= 0 && + !CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, false /*forCurrentCellChange*/, false /*forCurrentRowChange*/)) { // Could not commit edited cell value - return silently @@ -2979,7 +2984,7 @@ public int FirstDisplayedScrollingRowIndex } if (this.ptCurrentCell.X >= 0 && - !CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, + !CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, false /*forCurrentCellChange*/, false /*forCurrentRowChange*/)) { // Could not commit edited cell value - return silently @@ -3014,11 +3019,11 @@ public int FirstDisplayedScrollingRowIndex ] public override Color ForeColor { - get + get { return base.ForeColor; } - set + set { base.ForeColor = value; } @@ -3035,16 +3040,16 @@ public override Color ForeColor } [ - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced) ] public override Font Font { - get + get { return base.Font; } - set + set { base.Font = value; } @@ -3083,7 +3088,7 @@ public Color GridColor { throw new ArgumentException(string.Format(SR.DataGridView_TransparentColor, "GridColor")); } - if (!value.Equals(this.gridPen.Color)) + if (!value.Equals(this.gridPen.Color)) { if (this.gridPen != null) { @@ -3097,10 +3102,10 @@ public Color GridColor } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewOnGridColorChangedDescr)) ] - public event EventHandler GridColorChanged + public event EventHandler GridColorChanged { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWGRIDCOLORCHANGED, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWGRIDCOLORCHANGED, value); @@ -3119,13 +3124,13 @@ internal Pen GridPen } } - internal int HorizontalOffset + internal int HorizontalOffset { - get + get { return this.horizontalOffset; } - set + set { if (value < 0) { @@ -3187,7 +3192,7 @@ internal int HorizontalOffset // update the lastTotallyDisplayedScrollingCol ComputeVisibleColumns(); - if (this.editingControl != null && + if (this.editingControl != null && !this.Columns[this.ptCurrentCell.X].Frozen && this.displayedBandsInfo.FirstDisplayedScrollingCol > -1) { @@ -3458,7 +3463,7 @@ private bool IsSharedCellReadOnly(DataGridViewCell dataGridViewCell, int rowInde { Debug.Assert(dataGridViewCell != null); Debug.Assert(rowIndex >= 0); - DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); + DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); return this.ReadOnly || (rowState & DataGridViewElementStates.ReadOnly) != 0 || (dataGridViewCell.OwningColumn != null && dataGridViewCell.OwningColumn.ReadOnly) || @@ -3527,7 +3532,7 @@ public bool MultiSelect } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewOnMultiSelectChangedDescr)) ] public event EventHandler MultiSelectChanged @@ -3578,16 +3583,16 @@ private int NoSelectionChangeCount EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Padding Padding + public new Padding Padding { - get - { - return base.Padding; + get + { + return base.Padding; } - set - { + set + { base.Padding = value; - } + } } [ @@ -3635,12 +3640,12 @@ public bool ReadOnly { // Current cell becomes read-only. Exit editing mode. if (!EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit, - DataGridViewValidateCellInternal.Always /*validateCell*/, + DataGridViewValidateCellInternal.Always /*validateCell*/, false /*fireCellLeave*/, false /*fireCellEnter*/, false /*fireRowLeave*/, false /*fireRowEnter*/, - false /*fireLeave*/, + false /*fireLeave*/, true /*keepFocus*/, false /*resetCurrentCell*/, false /*resetAnchorCell*/)) @@ -3692,7 +3697,7 @@ public bool ReadOnly } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewOnReadOnlyChangedDescr)) ] public event EventHandler ReadOnlyChanged @@ -3778,7 +3783,7 @@ public int RowCount while (value < this.Rows.Count) { int currentRowCount = this.Rows.Count; - this.Rows.RemoveAt(currentRowCount - (this.AllowUserToAddRowsInternal ? 2 : 1)); + this.Rows.RemoveAt(currentRowCount - (this.AllowUserToAddRowsInternal ? 2 : 1)); if (this.Rows.Count >= currentRowCount) { // Row removal failed. We stop the loop. @@ -3841,7 +3846,7 @@ public DataGridViewHeaderBorderStyle RowHeadersBorderStyle // Sequential enum. Valid values are 0x0 to 0x4 if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridViewHeaderBorderStyle.Custom, (int)DataGridViewHeaderBorderStyle.None)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewHeaderBorderStyle)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewHeaderBorderStyle)); } if (value != this.RowHeadersBorderStyle) @@ -3882,7 +3887,7 @@ public DataGridViewHeaderBorderStyle RowHeadersBorderStyle } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridView_RowHeadersBorderStyleChangedDescr)) ] public event EventHandler RowHeadersBorderStyleChanged @@ -3898,7 +3903,7 @@ public event EventHandler RowHeadersBorderStyleChanged ] public DataGridViewCellStyle RowHeadersDefaultCellStyle { - get + get { if (this.rowHeadersDefaultCellStyle == null) { @@ -3906,7 +3911,7 @@ public DataGridViewCellStyle RowHeadersDefaultCellStyle } return this.rowHeadersDefaultCellStyle; } - set + set { DataGridViewCellStyle cs = this.RowHeadersDefaultCellStyle; cs.RemoveScope(DataGridViewCellStyleScopes.RowHeaders); @@ -3925,7 +3930,7 @@ public DataGridViewCellStyle RowHeadersDefaultCellStyle } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewRowHeadersDefaultCellStyleChangedDescr)) ] public event EventHandler RowHeadersDefaultCellStyleChanged @@ -3933,7 +3938,7 @@ public event EventHandler RowHeadersDefaultCellStyleChanged add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWHEADERSDEFAULTCELLSTYLECHANGED, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEADERSDEFAULTCELLSTYLECHANGED, value); } - + /// /// /// Gets or sets a value indicating whether the dataGridView's row headers are @@ -3947,11 +3952,11 @@ public event EventHandler RowHeadersDefaultCellStyleChanged ] public bool RowHeadersVisible { - get + get { return this.dataGridViewState1[DATAGRIDVIEWSTATE1_rowHeadersVisible]; } - set + set { if (this.RowHeadersVisible != value) { @@ -3978,16 +3983,16 @@ public bool RowHeadersVisible [ SRCategory(nameof(SR.CatLayout)), - Localizable(true), + Localizable(true), SRDescription(nameof(SR.DataGridView_RowHeadersWidthDescr)) ] public int RowHeadersWidth { - get + get { return this.rowHeadersWidth; } - set + set { if (value < minimumRowHeadersWidth) { @@ -4037,7 +4042,7 @@ private int RowHeadersWidthInternal } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewRowHeadersWidthChangedDescr)) ] public event EventHandler RowHeadersWidthChanged @@ -4048,7 +4053,7 @@ public event EventHandler RowHeadersWidthChanged private bool ShouldSerializeRowHeadersWidth() { - return (this.rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing || this.rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.DisableResizing) && + return (this.rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing || this.rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.DisableResizing) && defaultRowHeadersWidth != this.RowHeadersWidth; } @@ -4074,7 +4079,7 @@ public DataGridViewRowHeadersWidthSizeMode RowHeadersWidthSizeMode // Sequential enum. Valid values are 0x0 to 0x4 if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridViewRowHeadersWidthSizeMode.EnableResizing, (int)DataGridViewRowHeadersWidthSizeMode.AutoSizeToFirstHeader)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewRowHeadersWidthSizeMode)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewRowHeadersWidthSizeMode)); } if (this.rowHeadersWidthSizeMode != value) { @@ -4093,7 +4098,7 @@ public DataGridViewRowHeadersWidthSizeMode RowHeadersWidthSizeMode } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridView_RowHeadersWidthSizeModeChangedDescr)) ] public event DataGridViewAutoSizeModeEventHandler RowHeadersWidthSizeModeChanged @@ -4151,7 +4156,7 @@ public DataGridViewCellStyle RowsDefaultCellStyle } [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewRowsDefaultCellStyleChangedDescr)) ] public event EventHandler RowsDefaultCellStyleChanged @@ -4203,7 +4208,7 @@ internal DataGridViewRow RowTemplateClone { get { - DataGridViewRow rowTemplateClone = (DataGridViewRow) this.RowTemplate.Clone(); + DataGridViewRow rowTemplateClone = (DataGridViewRow)this.RowTemplate.Clone(); CompleteCellsCollection(rowTemplateClone); return rowTemplateClone; } @@ -4213,9 +4218,9 @@ internal DataGridViewRow RowTemplateClone /// Possible return values are given by the ScrollBars enumeration. /// [ - DefaultValue(ScrollBars.Both), - Localizable(true), - SRCategory(nameof(SR.CatLayout)), + DefaultValue(ScrollBars.Both), + Localizable(true), + SRCategory(nameof(SR.CatLayout)), SRDescription(nameof(SR.DataGridView_ScrollBarsDescr)) ] public ScrollBars ScrollBars @@ -4229,7 +4234,7 @@ public ScrollBars ScrollBars // Sequential enum. Valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(value, (int)value, (int)ScrollBars.None, (int)ScrollBars.Both)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ScrollBars)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ScrollBars)); } if (this.scrollBars != value) @@ -4278,45 +4283,45 @@ public DataGridViewSelectedCellCollection SelectedCells switch (this.SelectionMode) { case DataGridViewSelectionMode.CellSelect: - { - // Note: If we change the design and decide that SelectAll() should use band selection, - // we need to add those to the selected cells. - stcc.AddCellLinkedList(this.individualSelectedCells); - break; - } + { + // Note: If we change the design and decide that SelectAll() should use band selection, + // we need to add those to the selected cells. + stcc.AddCellLinkedList(this.individualSelectedCells); + break; + } case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: - { - foreach (int columnIndex in this.selectedBandIndexes) { - foreach (DataGridViewRow dataGridViewRow in this.Rows) // unshares all rows! + foreach (int columnIndex in this.selectedBandIndexes) { - stcc.Add(dataGridViewRow.Cells[columnIndex]); + foreach (DataGridViewRow dataGridViewRow in this.Rows) // unshares all rows! + { + stcc.Add(dataGridViewRow.Cells[columnIndex]); + } } + if (this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) + { + stcc.AddCellLinkedList(this.individualSelectedCells); + } + break; } - if (this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) - { - stcc.AddCellLinkedList(this.individualSelectedCells); - } - break; - } case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: - { - foreach (int rowIndex in this.selectedBandIndexes) { - DataGridViewRow dataGridViewRow = (DataGridViewRow) this.Rows[rowIndex]; // unshares the selected row - foreach (DataGridViewCell dataGridViewCell in dataGridViewRow.Cells) + foreach (int rowIndex in this.selectedBandIndexes) { - stcc.Add(dataGridViewCell); + DataGridViewRow dataGridViewRow = (DataGridViewRow)this.Rows[rowIndex]; // unshares the selected row + foreach (DataGridViewCell dataGridViewCell in dataGridViewRow.Cells) + { + stcc.Add(dataGridViewCell); + } } + if (this.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) + { + stcc.AddCellLinkedList(this.individualSelectedCells); + } + break; } - if (this.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) - { - stcc.AddCellLinkedList(this.individualSelectedCells); - } - break; - } } return stcc; } @@ -4350,7 +4355,7 @@ public DataGridViewSelectedColumnCollection SelectedColumns return strc; } } - + [ Browsable(false), ] @@ -4373,7 +4378,7 @@ public DataGridViewSelectedRowCollection SelectedRows case DataGridViewSelectionMode.RowHeaderSelect: foreach (int rowIndex in this.selectedBandIndexes) { - strc.Add((DataGridViewRow) this.Rows[rowIndex]); // unshares the selected row + strc.Add((DataGridViewRow)this.Rows[rowIndex]); // unshares the selected row } break; } @@ -4398,7 +4403,7 @@ public DataGridViewSelectionMode SelectionMode // Sequential enum. Valid values are 0x0 to 0x4 if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridViewSelectionMode.CellSelect, (int)DataGridViewSelectionMode.ColumnHeaderSelect)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewSelectionMode)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewSelectionMode)); } if (this.SelectionMode != value) @@ -4557,7 +4562,8 @@ public bool ShowEditingIcon } else { - if (this.IsCurrentCellDirty) { + if (this.IsCurrentCellDirty) + { Debug.Assert(this.ptCurrentCell.Y >= 0); InvalidateCellPrivate(-1, this.ptCurrentCell.Y); } @@ -4578,7 +4584,7 @@ public bool ShowRowErrors { return this.dataGridViewState2[DATAGRIDVIEWSTATE2_showRowErrors]; } - set + set { if (this.ShowRowErrors != value) { @@ -4620,7 +4626,7 @@ internal bool SingleHorizontalBorderAdded { get { - return !this.layout.ColumnHeadersVisible && + return !this.layout.ColumnHeadersVisible && (this.AdvancedCellBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Single || this.CellBorderStyle == DataGridViewCellBorderStyle.SingleHorizontal); } @@ -4630,7 +4636,7 @@ internal bool SingleVerticalBorderAdded { get { - return !this.layout.RowHeadersVisible && + return !this.layout.RowHeadersVisible && (this.AdvancedCellBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Single || this.CellBorderStyle == DataGridViewCellBorderStyle.SingleVertical); } @@ -4663,8 +4669,8 @@ public SortOrder SortOrder /// /// [ - SRCategory(nameof(SR.CatBehavior)), - DefaultValue(false), + SRCategory(nameof(SR.CatBehavior)), + DefaultValue(false), EditorBrowsable(EditorBrowsableState.Advanced), SRDescription(nameof(SR.DataGridView_StandardTabDescr)) ] @@ -4687,7 +4693,7 @@ public bool StandardTab internal override bool SupportsUiaProviders => true; [ - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Bindable(false) ] @@ -4824,7 +4830,7 @@ internal int VerticalOffset { return this.verticalOffset; } - set + set { if (value < 0) { @@ -4925,7 +4931,7 @@ private bool VisibleCellExists // Events start here [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridViewAutoSizeColumnModeChangedDescr)) ] public event DataGridViewAutoSizeColumnModeEventHandler AutoSizeColumnModeChanged @@ -4948,7 +4954,7 @@ public event QuestionEventHandler CancelRowEdit SRCategory(nameof(SR.CatData)), SRDescription(nameof(SR.DataGridView_CellBeginEditDescr)) ] - public event DataGridViewCellCancelEventHandler CellBeginEdit + public event DataGridViewCellCancelEventHandler CellBeginEdit { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLBEGINEDIT, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLBEGINEDIT, value); @@ -5020,7 +5026,7 @@ public event DataGridViewCellEventHandler CellDoubleClick SRCategory(nameof(SR.CatData)), SRDescription(nameof(SR.DataGridView_CellEndEditDescr)) ] - public event DataGridViewCellEventHandler CellEndEdit + public event DataGridViewCellEventHandler CellEndEdit { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLENDEDIT, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLENDEDIT, value); @@ -5061,7 +5067,7 @@ public event DataGridViewCellErrorTextNeededEventHandler CellErrorTextNeeded SRCategory(nameof(SR.CatDisplay)), SRDescription(nameof(SR.DataGridView_CellFormattingDescr)) ] - public event DataGridViewCellFormattingEventHandler CellFormatting + public event DataGridViewCellFormattingEventHandler CellFormatting { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLFORMATTING, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLFORMATTING, value); @@ -5141,7 +5147,7 @@ public event DataGridViewCellMouseEventHandler CellMouseMove SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.DataGridView_CellMouseUpDescr)) ] - public event DataGridViewCellMouseEventHandler CellMouseUp + public event DataGridViewCellMouseEventHandler CellMouseUp { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLMOUSEUP, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLMOUSEUP, value); @@ -5151,7 +5157,7 @@ public event DataGridViewCellMouseEventHandler CellMouseUp SRCategory(nameof(SR.CatDisplay)), SRDescription(nameof(SR.DataGridView_CellPaintingDescr)) ] - public event DataGridViewCellPaintingEventHandler CellPainting + public event DataGridViewCellPaintingEventHandler CellPainting { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLPAINTING, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLPAINTING, value); @@ -5171,7 +5177,7 @@ public event DataGridViewCellParsingEventHandler CellParsing SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.DataGridView_CellStateChangedDescr)) ] - public event DataGridViewCellStateChangedEventHandler CellStateChanged + public event DataGridViewCellStateChangedEventHandler CellStateChanged { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLSTATECHANGED, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLSTATECHANGED, value); @@ -5181,7 +5187,7 @@ public event DataGridViewCellStateChangedEventHandler CellStateChanged SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridView_CellStyleChangedDescr)) ] - public event DataGridViewCellEventHandler CellStyleChanged + public event DataGridViewCellEventHandler CellStyleChanged { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLSTYLECHANGED, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLSTYLECHANGED, value); @@ -5224,7 +5230,7 @@ public event DataGridViewCellToolTipTextNeededEventHandler CellToolTipTextNeeded ] public event DataGridViewCellEventHandler CellValidated { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLVALIDATED, value); + add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLVALIDATED, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLVALIDATED, value); } @@ -5242,7 +5248,7 @@ public event DataGridViewCellValidatingEventHandler CellValidating SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.DataGridView_CellValueChangedDescr)) ] - public event DataGridViewCellEventHandler CellValueChanged + public event DataGridViewCellEventHandler CellValueChanged { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLVALUECHANGED, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLVALUECHANGED, value); @@ -5253,7 +5259,7 @@ public event DataGridViewCellEventHandler CellValueChanged EditorBrowsable(EditorBrowsableState.Advanced), SRDescription(nameof(SR.DataGridView_CellValueNeededDescr)) ] - public event DataGridViewCellValueEventHandler CellValueNeeded + public event DataGridViewCellValueEventHandler CellValueNeeded { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLVALUENEEDED, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLVALUENEEDED, value); @@ -5264,7 +5270,7 @@ public event DataGridViewCellValueEventHandler CellValueNeeded EditorBrowsable(EditorBrowsableState.Advanced), SRDescription(nameof(SR.DataGridView_CellValuePushedDescr)) ] - public event DataGridViewCellValueEventHandler CellValuePushed + public event DataGridViewCellValueEventHandler CellValuePushed { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLVALUEPUSHED, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLVALUEPUSHED, value); @@ -5314,7 +5320,7 @@ public event DataGridViewColumnEventHandler ColumnDefaultCellStyleChanged SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridView_ColumnDisplayIndexChangedDescr)) ] - public event DataGridViewColumnEventHandler ColumnDisplayIndexChanged + public event DataGridViewColumnEventHandler ColumnDisplayIndexChanged { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNDISPLAYINDEXCHANGED, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNDISPLAYINDEXCHANGED, value); @@ -5344,14 +5350,14 @@ public event DataGridViewColumnEventHandler ColumnDividerWidthChanged SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.DataGridView_ColumnHeaderMouseClickDescr)) ] - public event DataGridViewCellMouseEventHandler ColumnHeaderMouseClick + public event DataGridViewCellMouseEventHandler ColumnHeaderMouseClick { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERMOUSECLICK, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERMOUSECLICK, value); } [ - SRCategory(nameof(SR.CatMouse)), + SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.DataGridView_ColumnHeaderMouseDoubleClickDescr)) ] public event DataGridViewCellMouseEventHandler ColumnHeaderMouseDoubleClick @@ -5364,7 +5370,7 @@ public event DataGridViewCellMouseEventHandler ColumnHeaderMouseDoubleClick SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridView_ColumnHeaderCellChangedDescr)) ] - public event DataGridViewColumnEventHandler ColumnHeaderCellChanged + public event DataGridViewColumnEventHandler ColumnHeaderCellChanged { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERCELLCHANGED, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERCELLCHANGED, value); @@ -5374,7 +5380,7 @@ public event DataGridViewColumnEventHandler ColumnHeaderCellChanged SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridView_ColumnMinimumWidthChangedDescr)) ] - public event DataGridViewColumnEventHandler ColumnMinimumWidthChanged + public event DataGridViewColumnEventHandler ColumnMinimumWidthChanged { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNMINIMUMWIDTHCHANGED, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNMINIMUMWIDTHCHANGED, value); @@ -5421,7 +5427,7 @@ public event DataGridViewColumnEventHandler ColumnSortModeChanged SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.DataGridView_ColumnStateChangedDescr)) ] - public event DataGridViewColumnStateChangedEventHandler ColumnStateChanged + public event DataGridViewColumnStateChangedEventHandler ColumnStateChanged { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNSTATECHANGED, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNSTATECHANGED, value); @@ -5441,14 +5447,14 @@ public event DataGridViewColumnEventHandler ColumnToolTipTextChanged SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.DataGridView_ColumnWidthChangedDescr)) ] - public event DataGridViewColumnEventHandler ColumnWidthChanged + public event DataGridViewColumnEventHandler ColumnWidthChanged { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNWIDTHCHANGED, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNWIDTHCHANGED, value); } [ - SRCategory(nameof(SR.CatAction)), + SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.DataGridView_CurrentCellChangedDescr)) ] public event EventHandler CurrentCellChanged @@ -5458,7 +5464,7 @@ public event EventHandler CurrentCellChanged } [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), EditorBrowsable(EditorBrowsableState.Advanced), SRDescription(nameof(SR.DataGridView_CurrentCellDirtyStateChangedDescr)) ] @@ -5469,7 +5475,7 @@ public event EventHandler CurrentCellDirtyStateChanged } [ - SRCategory(nameof(SR.CatData)), + SRCategory(nameof(SR.CatData)), SRDescription(nameof(SR.DataGridView_DataBindingCompleteDescr)) ] public event DataGridViewBindingCompleteEventHandler DataBindingComplete @@ -5489,7 +5495,7 @@ public event DataGridViewDataErrorEventHandler DataError } [ - SRCategory(nameof(SR.CatData)), + SRCategory(nameof(SR.CatData)), EditorBrowsable(EditorBrowsableState.Advanced), SRDescription(nameof(SR.DataGridView_DefaultValuesNeededDescr)) ] @@ -5558,7 +5564,7 @@ public event DataGridViewRowContextMenuStripNeededEventHandler RowContextMenuStr SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridView_RowDefaultCellStyleChangedDescr)) ] - public event DataGridViewRowEventHandler RowDefaultCellStyleChanged + public event DataGridViewRowEventHandler RowDefaultCellStyleChanged { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWDEFAULTCELLSTYLECHANGED, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWDEFAULTCELLSTYLECHANGED, value); @@ -5630,7 +5636,7 @@ public event DataGridViewRowErrorTextNeededEventHandler RowErrorTextNeeded SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.DataGridView_RowHeaderMouseClickDescr)) ] - public event DataGridViewCellMouseEventHandler RowHeaderMouseClick + public event DataGridViewCellMouseEventHandler RowHeaderMouseClick { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWHEADERMOUSECLICK, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEADERMOUSECLICK, value); @@ -5640,7 +5646,7 @@ public event DataGridViewCellMouseEventHandler RowHeaderMouseClick SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.DataGridView_RowHeaderMouseDoubleClickDescr)) ] - public event DataGridViewCellMouseEventHandler RowHeaderMouseDoubleClick + public event DataGridViewCellMouseEventHandler RowHeaderMouseDoubleClick { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWHEADERMOUSEDOUBLECLICK, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEADERMOUSEDOUBLECLICK, value); @@ -5650,7 +5656,7 @@ public event DataGridViewCellMouseEventHandler RowHeaderMouseDoubleClick SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridView_RowHeaderCellChangedDescr)) ] - public event DataGridViewRowEventHandler RowHeaderCellChanged + public event DataGridViewRowEventHandler RowHeaderCellChanged { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWHEADERCELLCHANGED, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEADERCELLCHANGED, value); @@ -5660,7 +5666,7 @@ public event DataGridViewRowEventHandler RowHeaderCellChanged SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridView_RowHeightChangedDescr)) ] - public event DataGridViewRowEventHandler RowHeightChanged + public event DataGridViewRowEventHandler RowHeightChanged { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWHEIGHTCHANGED, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEIGHTCHANGED, value); @@ -5714,14 +5720,14 @@ public event DataGridViewCellEventHandler RowLeave SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DataGridView_RowMinimumHeightChangedDescr)) ] - public event DataGridViewRowEventHandler RowMinimumHeightChanged + public event DataGridViewRowEventHandler RowMinimumHeightChanged { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWMINIMUMHEIGHTCHANGED, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWMINIMUMHEIGHTCHANGED, value); } [ - SRCategory(nameof(SR.CatDisplay)), + SRCategory(nameof(SR.CatDisplay)), SRDescription(nameof(SR.DataGridView_RowPostPaintDescr)) ] public event DataGridViewRowPostPaintEventHandler RowPostPaint @@ -5743,7 +5749,7 @@ internal DataGridViewRowPostPaintEventArgs RowPostPaintEventArgs } [ - SRCategory(nameof(SR.CatDisplay)), + SRCategory(nameof(SR.CatDisplay)), SRDescription(nameof(SR.DataGridView_RowPrePaintDescr)) ] public event DataGridViewRowPrePaintEventHandler RowPrePaint @@ -5765,7 +5771,7 @@ internal DataGridViewRowPrePaintEventArgs RowPrePaintEventArgs } [ - SRCategory(nameof(SR.CatAction)), + SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.DataGridView_RowsAddedDescr)) ] public event DataGridViewRowsAddedEventHandler RowsAdded @@ -5788,7 +5794,7 @@ public event DataGridViewRowsRemovedEventHandler RowsRemoved SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.DataGridView_RowStateChangedDescr)) ] - public event DataGridViewRowStateChangedEventHandler RowStateChanged + public event DataGridViewRowStateChangedEventHandler RowStateChanged { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWSTATECHANGED, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWSTATECHANGED, value); @@ -5798,8 +5804,8 @@ public event DataGridViewRowStateChangedEventHandler RowStateChanged SRCategory(nameof(SR.CatBehavior)), EditorBrowsable(EditorBrowsableState.Advanced), SRDescription(nameof(SR.DataGridView_RowUnsharedDescr)) - ] - public event DataGridViewRowEventHandler RowUnshared + ] + public event DataGridViewRowEventHandler RowUnshared { add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWUNSHARED, value); remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWUNSHARED, value); @@ -5826,7 +5832,7 @@ public event DataGridViewCellCancelEventHandler RowValidating } [ - SRCategory(nameof(SR.CatAction)), + SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.DataGridView_ScrollDescr)) ] public event ScrollEventHandler Scroll @@ -5867,7 +5873,7 @@ public event EventHandler Sorted } [ - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] new public event EventHandler StyleChanged @@ -5957,8 +5963,8 @@ void ISupportInitialize.EndInit() { // Resetting SelectionMode to its acceptable default value. We don't want the control to ever end up in an invalid state. this.SelectionMode = defaultSelectionMode; // DataGridViewSelectionMode.RowHeaderSelect - throw new InvalidOperationException(string.Format(SR.DataGridView_SelectionModeReset, - string.Format(SR.DataGridView_SelectionModeAndSortModeClash, (selectionMode).ToString()), + throw new InvalidOperationException(string.Format(SR.DataGridView_SelectionModeReset, + string.Format(SR.DataGridView_SelectionModeAndSortModeClash, (selectionMode).ToString()), (defaultSelectionMode).ToString())); } } @@ -5967,7 +5973,7 @@ void ISupportInitialize.EndInit() /* INTERNAL ENUMERATIONS */ - internal enum DataGridViewHitTestTypeInternal + internal enum DataGridViewHitTestTypeInternal { None, Cell, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAccessibleObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAccessibleObject.cs index 46d5ef709f2..6b967f3b6f9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAccessibleObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAccessibleObject.cs @@ -300,14 +300,14 @@ internal override object GetPropertyValue(int propertyID) break; } - + return base.GetPropertyValue(propertyID); } internal override bool IsPatternSupported(int patternId) { - if (patternId == NativeMethods.UIA_TablePatternId || + if (patternId == NativeMethods.UIA_TablePatternId || patternId == NativeMethods.UIA_GridPatternId) { return true; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAdvancedBorderStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAdvancedBorderStyle.cs index 05cad831b1a..340692ed24c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAdvancedBorderStyle.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAdvancedBorderStyle.cs @@ -19,15 +19,15 @@ public sealed class DataGridViewAdvancedBorderStyle : ICloneable private DataGridViewAdvancedCellBorderStyle bottom = DataGridViewAdvancedCellBorderStyle.None; public DataGridViewAdvancedBorderStyle() : this(null, - DataGridViewAdvancedCellBorderStyle.NotSet, - DataGridViewAdvancedCellBorderStyle.NotSet, + DataGridViewAdvancedCellBorderStyle.NotSet, + DataGridViewAdvancedCellBorderStyle.NotSet, DataGridViewAdvancedCellBorderStyle.NotSet) { } - internal DataGridViewAdvancedBorderStyle(DataGridView owner) : this(owner, - DataGridViewAdvancedCellBorderStyle.NotSet, - DataGridViewAdvancedCellBorderStyle.NotSet, + internal DataGridViewAdvancedBorderStyle(DataGridView owner) : this(owner, + DataGridViewAdvancedCellBorderStyle.NotSet, + DataGridViewAdvancedCellBorderStyle.NotSet, DataGridViewAdvancedCellBorderStyle.NotSet) { } @@ -36,8 +36,8 @@ internal DataGridViewAdvancedBorderStyle(DataGridView owner) : this(owner, /// Creates a new DataGridViewAdvancedBorderStyle. The specified owner will /// be notified when the values are changed. /// - internal DataGridViewAdvancedBorderStyle(DataGridView owner, - DataGridViewAdvancedCellBorderStyle banned1, + internal DataGridViewAdvancedBorderStyle(DataGridView owner, + DataGridViewAdvancedCellBorderStyle banned1, DataGridViewAdvancedCellBorderStyle banned2, DataGridViewAdvancedCellBorderStyle banned3) { @@ -49,17 +49,17 @@ internal DataGridViewAdvancedBorderStyle(DataGridView owner, public DataGridViewAdvancedCellBorderStyle All { - get + get { return this.all ? this.top : DataGridViewAdvancedCellBorderStyle.NotSet; } - set + set { // Sequential enum. Valid values are 0x0 to 0x7 if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridViewAdvancedCellBorderStyle.NotSet, (int)DataGridViewAdvancedCellBorderStyle.OutsetPartial)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewAdvancedCellBorderStyle)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewAdvancedCellBorderStyle)); } if (value == DataGridViewAdvancedCellBorderStyle.NotSet || value == this.banned1 || @@ -82,20 +82,20 @@ public DataGridViewAdvancedCellBorderStyle All public DataGridViewAdvancedCellBorderStyle Bottom { - get + get { - if (this.all) + if (this.all) { return this.top; } return this.bottom; } - set + set { // Sequential enum. Valid values are 0x0 to 0x7 if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridViewAdvancedCellBorderStyle.NotSet, (int)DataGridViewAdvancedCellBorderStyle.OutsetPartial)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewAdvancedCellBorderStyle)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewAdvancedCellBorderStyle)); } if (value == DataGridViewAdvancedCellBorderStyle.NotSet) { @@ -132,20 +132,20 @@ internal DataGridViewAdvancedCellBorderStyle BottomInternal public DataGridViewAdvancedCellBorderStyle Left { - get + get { - if (this.all) + if (this.all) { return this.top; } return this.left; } - set + set { // Sequential enum. Valid values are 0x0 to 0x7 if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridViewAdvancedCellBorderStyle.NotSet, (int)DataGridViewAdvancedCellBorderStyle.OutsetPartial)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewAdvancedCellBorderStyle)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewAdvancedCellBorderStyle)); } if (value == DataGridViewAdvancedCellBorderStyle.NotSet) { @@ -191,21 +191,21 @@ internal DataGridViewAdvancedCellBorderStyle LeftInternal public DataGridViewAdvancedCellBorderStyle Right { - get + get { - if (this.all) + if (this.all) { return this.top; } return this.right; } - set + set { // Sequential enum. Valid values are 0x0 to 0x7 if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridViewAdvancedCellBorderStyle.NotSet, (int)DataGridViewAdvancedCellBorderStyle.OutsetPartial)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewAdvancedCellBorderStyle)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewAdvancedCellBorderStyle)); } if (value == DataGridViewAdvancedCellBorderStyle.NotSet) { @@ -247,16 +247,16 @@ internal DataGridViewAdvancedCellBorderStyle RightInternal public DataGridViewAdvancedCellBorderStyle Top { - get + get { return this.top; } - set + set { - // Sequential enum. Valid values are 0x0 to 0x7 + // Sequential enum. Valid values are 0x0 to 0x7 if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridViewAdvancedCellBorderStyle.NotSet, (int)DataGridViewAdvancedCellBorderStyle.OutsetPartial)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewAdvancedCellBorderStyle)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewAdvancedCellBorderStyle)); } if (value == DataGridViewAdvancedCellBorderStyle.NotSet) { @@ -295,7 +295,7 @@ internal DataGridViewAdvancedCellBorderStyle TopInternal } } - public override bool Equals(object other) + public override bool Equals(object other) { DataGridViewAdvancedBorderStyle dgvabsOther = other as DataGridViewAdvancedBorderStyle; @@ -304,21 +304,21 @@ public override bool Equals(object other) return false; } - return dgvabsOther.all == this.all && - dgvabsOther.top == this.top && - dgvabsOther.left == this.left && - dgvabsOther.bottom == this.bottom && + return dgvabsOther.all == this.all && + dgvabsOther.top == this.top && + dgvabsOther.left == this.left && + dgvabsOther.bottom == this.bottom && dgvabsOther.right == this.right; } public override int GetHashCode() => HashCode.Combine(top, left, bottom, right); - public override string ToString() + public override string ToString() { return "DataGridViewAdvancedBorderStyle { All=" + this.All.ToString() + ", Left=" + this.Left.ToString() + ", Right=" + this.Right.ToString() + ", Top=" + this.Top.ToString() + ", Bottom=" + this.Bottom.ToString() + " }"; } - object ICloneable.Clone() + object ICloneable.Clone() { DataGridViewAdvancedBorderStyle dgvabs = new DataGridViewAdvancedBorderStyle(this.owner, this.banned1, this.banned2, this.banned3); dgvabs.all = this.all; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewBand.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewBand.cs index 6ba10614054..55ac9adb28b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewBand.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewBand.cs @@ -411,7 +411,7 @@ internal int MinimumThickness throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.DataGridViewBand_MinimumWidthSmallerThanOne, DataGridViewBand.MinBandThickness)); } } - + if (Thickness < value) { // Force the new minimum width on potential auto fill column. @@ -422,7 +422,7 @@ internal int MinimumThickness Thickness = value; } - + _minimumThickness = value; DataGridView?.OnBandMinimumThicknessChanged(this); } @@ -459,7 +459,7 @@ public virtual bool ReadOnly { throw new InvalidOperationException(string.Format(SR.DataGridView_InvalidPropertySetOnSharedRow, nameof(ReadOnly))); } - + OnStateChanging(DataGridViewElementStates.ReadOnly); DataGridView.SetReadOnlyRowCore(_bandIndex, value); } @@ -750,7 +750,7 @@ public virtual bool Visible // the 'new' row cannot be made invisble. throw new InvalidOperationException(SR.DataGridViewBand_NewRowCannotBeInvisible); } - + OnStateChanging(DataGridViewElementStates.Visible); if (value) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonCell.cs index bff029350cd..3b93ec7d5dd 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonCell.cs @@ -91,10 +91,10 @@ public FlatStyle FlatStyle } set { - // Sequential enum. Valid values are 0x0 to 0x3 + // Sequential enum. Valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(value, (int)value, (int)FlatStyle.Flat, (int)FlatStyle.System)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(FlatStyle)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(FlatStyle)); } if (value != this.FlatStyle) { @@ -118,7 +118,7 @@ internal FlatStyle FlatStyleInternal public override Type FormattedValueType { - get + get { // we return string for the formatted type return defaultFormattedValueType; @@ -347,58 +347,58 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl switch (freeDimension) { case DataGridViewFreeDimension.Width: - { - if (cellStyle.WrapMode == DataGridViewTriState.True && formattedString.Length > 1 && - constraintSize.Height - borderAndPaddingHeights - marginHeights - 2 * DATAGRIDVIEWBUTTONCELL_verticalTextMargin > 0) - { - preferredSize = new Size(DataGridViewCell.MeasureTextWidth(graphics, - formattedString, - cellStyle.Font, - constraintSize.Height - borderAndPaddingHeights - marginHeights - 2 * DATAGRIDVIEWBUTTONCELL_verticalTextMargin, - flags), - 0); - } - else { - preferredSize = new Size(DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags).Width, - 0); + if (cellStyle.WrapMode == DataGridViewTriState.True && formattedString.Length > 1 && + constraintSize.Height - borderAndPaddingHeights - marginHeights - 2 * DATAGRIDVIEWBUTTONCELL_verticalTextMargin > 0) + { + preferredSize = new Size(DataGridViewCell.MeasureTextWidth(graphics, + formattedString, + cellStyle.Font, + constraintSize.Height - borderAndPaddingHeights - marginHeights - 2 * DATAGRIDVIEWBUTTONCELL_verticalTextMargin, + flags), + 0); + } + else + { + preferredSize = new Size(DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags).Width, + 0); + } + break; } - break; - } case DataGridViewFreeDimension.Height: - { - if (cellStyle.WrapMode == DataGridViewTriState.True && formattedString.Length > 1 && - constraintSize.Width - borderAndPaddingWidths - marginWidths - 2 * DATAGRIDVIEWBUTTONCELL_horizontalTextMargin > 0) { - preferredSize = new Size(0, - DataGridViewCell.MeasureTextHeight(graphics, - formattedString, - cellStyle.Font, - constraintSize.Width - borderAndPaddingWidths - marginWidths - 2 * DATAGRIDVIEWBUTTONCELL_horizontalTextMargin, - flags)); - } - else - { - preferredSize = new Size(0, - DataGridViewCell.MeasureTextSize(graphics, - formattedString, - cellStyle.Font, - flags).Height); + if (cellStyle.WrapMode == DataGridViewTriState.True && formattedString.Length > 1 && + constraintSize.Width - borderAndPaddingWidths - marginWidths - 2 * DATAGRIDVIEWBUTTONCELL_horizontalTextMargin > 0) + { + preferredSize = new Size(0, + DataGridViewCell.MeasureTextHeight(graphics, + formattedString, + cellStyle.Font, + constraintSize.Width - borderAndPaddingWidths - marginWidths - 2 * DATAGRIDVIEWBUTTONCELL_horizontalTextMargin, + flags)); + } + else + { + preferredSize = new Size(0, + DataGridViewCell.MeasureTextSize(graphics, + formattedString, + cellStyle.Font, + flags).Height); + } + break; } - break; - } default: - { - if (cellStyle.WrapMode == DataGridViewTriState.True && formattedString.Length > 1) { - preferredSize = DataGridViewCell.MeasureTextPreferredSize(graphics, formattedString, cellStyle.Font, 5.0F, flags); - } - else - { - preferredSize = DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags); + if (cellStyle.WrapMode == DataGridViewTriState.True && formattedString.Length > 1) + { + preferredSize = DataGridViewCell.MeasureTextPreferredSize(graphics, formattedString, cellStyle.Font, 5.0F, flags); + } + else + { + preferredSize = DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags); + } + break; } - break; - } } if (freeDimension != DataGridViewFreeDimension.Height) @@ -439,12 +439,12 @@ private static Rectangle GetThemeMargins(Graphics g) protected override object GetValue(int rowIndex) { if (this.UseColumnTextForButtonValue && - this.DataGridView != null && - this.DataGridView.NewRowIndex != rowIndex && - this.OwningColumn != null && + this.DataGridView != null && + this.DataGridView.NewRowIndex != rowIndex && + this.OwningColumn != null && this.OwningColumn is DataGridViewButtonColumn) { - return ((DataGridViewButtonColumn) this.OwningColumn).Text; + return ((DataGridViewButtonColumn)this.OwningColumn).Text; } return base.GetValue(rowIndex); } @@ -573,7 +573,7 @@ protected override void OnMouseMove(DataGridViewCellMouseEventArgs e) { return; } - + bool oldMouseInContentBounds = mouseInContentBounds; mouseInContentBounds = GetContentBounds(e.RowIndex).Contains(e.X, e.Y); if (oldMouseInContentBounds != mouseInContentBounds) @@ -587,7 +587,7 @@ protected override void OnMouseMove(DataGridViewCellMouseEventArgs e) e.RowIndex == this.DataGridView.MouseDownCellAddress.Y && Control.MouseButtons == MouseButtons.Left) { - if ((this.ButtonState & ButtonState.Pushed) == 0 && + if ((this.ButtonState & ButtonState.Pushed) == 0 && mouseInContentBounds && this.DataGridView.CellMouseDownInContentBounds) { @@ -615,11 +615,11 @@ protected override void OnMouseUp(DataGridViewCellMouseEventArgs e) } } - protected override void Paint(Graphics graphics, + protected override void Paint(Graphics graphics, Rectangle clipBounds, - Rectangle cellBounds, - int rowIndex, - DataGridViewElementStates elementState, + Rectangle cellBounds, + int rowIndex, + DataGridViewElementStates elementState, object value, object formattedValue, string errorText, @@ -632,11 +632,11 @@ protected override void Paint(Graphics graphics, throw new ArgumentNullException(nameof(cellStyle)); } - PaintPrivate(graphics, + PaintPrivate(graphics, clipBounds, - cellBounds, - rowIndex, - elementState, + cellBounds, + rowIndex, + elementState, formattedValue, errorText, cellStyle, @@ -655,10 +655,10 @@ protected override void Paint(Graphics graphics, // if computeContentBounds is true then PaintPrivate returns the contentBounds // else if computeErrorIconBounds is true then PaintPrivate returns the errorIconBounds // else it returns Rectangle.Empty; - private Rectangle PaintPrivate(Graphics g, + private Rectangle PaintPrivate(Graphics g, Rectangle clipBounds, - Rectangle cellBounds, - int rowIndex, + Rectangle cellBounds, + int rowIndex, DataGridViewElementStates elementState, object formattedValue, string errorText, @@ -735,15 +735,15 @@ private Rectangle PaintPrivate(Graphics g, { pbState = VisualStyles.PushButtonState.Pressed; } - else if (this.DataGridView.MouseEnteredCellAddress.Y == rowIndex && + else if (this.DataGridView.MouseEnteredCellAddress.Y == rowIndex && this.DataGridView.MouseEnteredCellAddress.X == this.ColumnIndex && mouseInContentBounds) { pbState = VisualStyles.PushButtonState.Hot; } - if (DataGridViewCell.PaintFocus(paintParts) && - cellCurrent && - this.DataGridView.ShowFocusCues && + if (DataGridViewCell.PaintFocus(paintParts) && + cellCurrent && + this.DataGridView.ShowFocusCues && this.DataGridView.Focused) { pbState |= VisualStyles.PushButtonState.Default; @@ -757,7 +757,7 @@ private Rectangle PaintPrivate(Graphics g, { if (paint && DataGridViewCell.PaintContentBackground(paintParts)) { - ControlPaint.DrawBorder(g, valBounds, SystemColors.Control, + ControlPaint.DrawBorder(g, valBounds, SystemColors.Control, (this.ButtonState == ButtonState.Normal) ? ButtonBorderStyle.Outset : ButtonBorderStyle.Inset); } resultBounds = valBounds; @@ -782,9 +782,11 @@ private Rectangle PaintPrivate(Graphics g, this.DataGridView.Enabled).Calculate(); IntPtr hdc = g.GetHdc(); - try { - using( WindowsGraphics wg = WindowsGraphics.FromHdc(hdc)) { - + try + { + using (WindowsGraphics wg = WindowsGraphics.FromHdc(hdc)) + { + System.Windows.Forms.Internal.WindowsBrush windowsBrush; if (colors.options.highContrast) { @@ -802,9 +804,10 @@ private Rectangle PaintPrivate(Graphics g, { windowsBrush.Dispose(); } - } + } } - finally { + finally + { g.ReleaseHdc(); } } @@ -813,8 +816,10 @@ private Rectangle PaintPrivate(Graphics g, mouseInContentBounds) { IntPtr hdc = g.GetHdc(); - try { - using( WindowsGraphics wg = WindowsGraphics.FromHdc(hdc)) { + try + { + using (WindowsGraphics wg = WindowsGraphics.FromHdc(hdc)) + { Color mouseOverBackColor = SystemColors.ControlDark; using (System.Windows.Forms.Internal.WindowsBrush windowBrush = new System.Windows.Forms.Internal.WindowsSolidBrush(wg.DeviceContext, mouseOverBackColor)) { @@ -822,7 +827,8 @@ private Rectangle PaintPrivate(Graphics g, } } } - finally { + finally + { g.ReleaseHdc(); } } @@ -897,11 +903,11 @@ private Rectangle PaintPrivate(Graphics g, Debug.Assert(valBounds.Height <= 0 || valBounds.Width <= 0); resultBounds = Rectangle.Empty; } - + if (paint && DataGridViewCell.PaintFocus(paintParts) && cellCurrent && - this.DataGridView.ShowFocusCues && + this.DataGridView.ShowFocusCues && this.DataGridView.Focused && valBounds.Width > 2 * SystemInformation.Border3DSize.Width + 1 && valBounds.Height > 2 * SystemInformation.Border3DSize.Height + 1) @@ -945,7 +951,7 @@ private Rectangle PaintPrivate(Graphics g, else { Debug.Assert(this.FlatStyle == FlatStyle.Popup, "FlatStyle.Popup is the last flat style"); - if ((this.ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0 || + if ((this.ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0 || (this.DataGridView.CurrentCellAddress.Y == rowIndex && this.DataGridView.CurrentCellAddress.X == this.ColumnIndex)) { // If we are painting the current cell, then paint the text up. @@ -965,7 +971,7 @@ private Rectangle PaintPrivate(Graphics g, this.DataGridView.RightToLeft); options.everettButtonCompat = false; ButtonBaseAdapter.LayoutData layout = options.Layout(); - + ControlPaint.DrawFocusRectangle(g, layout.focus, @@ -1068,7 +1074,7 @@ public static void DrawButton(Graphics g, Rectangle bounds, int buttonState) protected class DataGridViewButtonCellAccessibleObject : DataGridViewCellAccessibleObject { - public DataGridViewButtonCellAccessibleObject(DataGridViewCell owner) : base (owner) + public DataGridViewButtonCellAccessibleObject(DataGridViewCell owner) : base(owner) { } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonColumn.cs index bbdbc9bb0a9..30dd75cecbe 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonColumn.cs @@ -80,7 +80,7 @@ public FlatStyle FlatStyle { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return ((DataGridViewButtonCell) this.CellTemplate).FlatStyle; + return ((DataGridViewButtonCell)this.CellTemplate).FlatStyle; } set { @@ -199,7 +199,7 @@ public override object Clone() } else { - dataGridViewColumn = (DataGridViewButtonColumn) System.Activator.CreateInstance(thisType); + dataGridViewColumn = (DataGridViewButtonColumn)System.Activator.CreateInstance(thisType); } if (dataGridViewColumn != null) { @@ -218,9 +218,9 @@ private bool ShouldSerializeDefaultCellStyle() DataGridViewCellStyle defaultCellStyle = this.DefaultCellStyle; - return (!defaultCellStyle.BackColor.IsEmpty || + return (!defaultCellStyle.BackColor.IsEmpty || !defaultCellStyle.ForeColor.IsEmpty || - !defaultCellStyle.SelectionBackColor.IsEmpty || + !defaultCellStyle.SelectionBackColor.IsEmpty || !defaultCellStyle.SelectionForeColor.IsEmpty || defaultCellStyle.Font != null || !defaultCellStyle.IsNullValueDefault || @@ -229,11 +229,11 @@ private bool ShouldSerializeDefaultCellStyle() !defaultCellStyle.FormatProvider.Equals(System.Globalization.CultureInfo.CurrentCulture) || defaultCellStyle.Alignment != DataGridViewContentAlignment.MiddleCenter || defaultCellStyle.WrapMode != DataGridViewTriState.NotSet || - defaultCellStyle.Tag != null || + defaultCellStyle.Tag != null || !defaultCellStyle.Padding.Equals(Padding.Empty)); } - public override string ToString() + public override string ToString() { StringBuilder sb = new StringBuilder(64); sb.Append("DataGridViewButtonColumn { Name="); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs index 1b6ce9cb0c3..45458eedad9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs @@ -4964,12 +4964,12 @@ internal Rectangle GetAccessibleObjectBounds(AccessibleObject parentAccObject) { cellRight = rowRect.Right - rightToLeftRowHeadersWidth; } - + if ((cellRight - cellLeft) >= 0) cellRect.Width = cellRight - cellLeft; else cellRect.Width = 0; - + return cellRect; } @@ -5325,33 +5325,33 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga internal override object GetPropertyValue(int propertyID) { - switch (propertyID) - { - case NativeMethods.UIA_NamePropertyId: - return this.Name; - case NativeMethods.UIA_HasKeyboardFocusPropertyId: - return (State & AccessibleStates.Focused) == AccessibleStates.Focused; // Announce the cell when focusing. - case NativeMethods.UIA_IsEnabledPropertyId: - return owner.DataGridView.Enabled; - case NativeMethods.UIA_AutomationIdPropertyId: - return AutomationId; - case NativeMethods.UIA_HelpTextPropertyId: - return Help ?? string.Empty; - case NativeMethods.UIA_IsKeyboardFocusablePropertyId: - return (State & AccessibleStates.Focusable) == AccessibleStates.Focusable; - case NativeMethods.UIA_IsPasswordPropertyId: - return false; - case NativeMethods.UIA_IsOffscreenPropertyId: - return (State & AccessibleStates.Offscreen) == AccessibleStates.Offscreen; - case NativeMethods.UIA_AccessKeyPropertyId: - return string.Empty; - case NativeMethods.UIA_GridItemContainingGridPropertyId: - return Owner.DataGridView.AccessibilityObject; - case NativeMethods.UIA_IsTableItemPatternAvailablePropertyId: - return IsPatternSupported(NativeMethods.UIA_TableItemPatternId); - case NativeMethods.UIA_IsGridItemPatternAvailablePropertyId: - return IsPatternSupported(NativeMethods.UIA_GridItemPatternId); - } + switch (propertyID) + { + case NativeMethods.UIA_NamePropertyId: + return this.Name; + case NativeMethods.UIA_HasKeyboardFocusPropertyId: + return (State & AccessibleStates.Focused) == AccessibleStates.Focused; // Announce the cell when focusing. + case NativeMethods.UIA_IsEnabledPropertyId: + return owner.DataGridView.Enabled; + case NativeMethods.UIA_AutomationIdPropertyId: + return AutomationId; + case NativeMethods.UIA_HelpTextPropertyId: + return Help ?? string.Empty; + case NativeMethods.UIA_IsKeyboardFocusablePropertyId: + return (State & AccessibleStates.Focusable) == AccessibleStates.Focusable; + case NativeMethods.UIA_IsPasswordPropertyId: + return false; + case NativeMethods.UIA_IsOffscreenPropertyId: + return (State & AccessibleStates.Offscreen) == AccessibleStates.Offscreen; + case NativeMethods.UIA_AccessKeyPropertyId: + return string.Empty; + case NativeMethods.UIA_GridItemContainingGridPropertyId: + return Owner.DataGridView.AccessibilityObject; + case NativeMethods.UIA_IsTableItemPatternAvailablePropertyId: + return IsPatternSupported(NativeMethods.UIA_TableItemPatternId); + case NativeMethods.UIA_IsGridItemPatternAvailablePropertyId: + return IsPatternSupported(NativeMethods.UIA_GridItemPatternId); + } return base.GetPropertyValue(propertyID); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellCollection.cs index 3dc72c694d8..2cef78a8bec 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellCollection.cs @@ -28,7 +28,7 @@ public class DataGridViewCellCollection : BaseCollection, IList int IList.Add(object value) { - return this.Add((DataGridViewCell) value); + return this.Add((DataGridViewCell)value); } void IList.Clear() @@ -48,12 +48,12 @@ int IList.IndexOf(object value) void IList.Insert(int index, object value) { - this.Insert(index, (DataGridViewCell) value); + this.Insert(index, (DataGridViewCell)value); } void IList.Remove(object value) { - this.Remove((DataGridViewCell) value); + this.Remove((DataGridViewCell)value); } void IList.RemoveAt(int index) @@ -63,18 +63,18 @@ void IList.RemoveAt(int index) bool IList.IsFixedSize { - get {return false;} + get { return false; } } bool IList.IsReadOnly { - get {return false;} + get { return false; } } object IList.this[int index] { get { return this[index]; } - set { this[index] = (DataGridViewCell) value; } + set { this[index] = (DataGridViewCell)value; } } void ICollection.CopyTo(Array array, int index) @@ -84,17 +84,17 @@ void ICollection.CopyTo(Array array, int index) int ICollection.Count { - get {return this.items.Count;} + get { return this.items.Count; } } bool ICollection.IsSynchronized { - get {return false;} + get { return false; } } object ICollection.SyncRoot { - get {return this;} + get { return this; } } IEnumerator IEnumerable.GetEnumerator() @@ -123,7 +123,7 @@ public DataGridViewCell this[int index] { get { - return (DataGridViewCell) this.items[index]; + return (DataGridViewCell)this.items[index]; } set { @@ -145,7 +145,7 @@ public DataGridViewCell this[int index] this.owner.DataGridView.OnReplacingCell(this.owner, index); } - DataGridViewCell oldDataGridViewCell = (DataGridViewCell) this.items[index]; + DataGridViewCell oldDataGridViewCell = (DataGridViewCell)this.items[index]; this.items[index] = dataGridViewCell; dataGridViewCell.OwningRowInternal = this.owner; dataGridViewCell.StateInternal = oldDataGridViewCell.State; @@ -186,7 +186,7 @@ public DataGridViewCell this[string columnName] { throw new ArgumentException(string.Format(SR.DataGridViewColumnCollection_ColumnNotFound, columnName), "columnName"); } - return (DataGridViewCell) this.items[dataGridViewColumn.Index]; + return (DataGridViewCell)this.items[dataGridViewColumn.Index]; } set { @@ -239,7 +239,7 @@ internal int AddInternal(DataGridViewCell dataGridViewCell) OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, dataGridViewCell)); return index; } - + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual void AddRange(params DataGridViewCell[] dataGridViewCells) { @@ -285,7 +285,7 @@ public virtual void AddRange(params DataGridViewCell[] dataGridViewCells) } OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null)); } - + public virtual void Clear() { if (this.owner.DataGridView != null) @@ -367,7 +367,7 @@ public virtual void Remove(DataGridViewCell cell) int itemsCount = this.items.Count; for (int i = 0; i < itemsCount; ++i) { - if (this.items[i] == cell) + if (this.items[i] == cell) { cellIndex = i; break; @@ -394,7 +394,7 @@ public virtual void RemoveAt(int index) internal void RemoveAtInternal(int index) { - DataGridViewCell dataGridViewCell = (DataGridViewCell) this.items[index]; + DataGridViewCell dataGridViewCell = (DataGridViewCell)this.items[index]; this.items.RemoveAt(index); dataGridViewCell.DataGridViewInternal = null; dataGridViewCell.OwningRowInternal = null; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellConverter.cs index 357bd534043..9f5f045f2b9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellConverter.cs @@ -13,24 +13,31 @@ namespace System.Windows.Forms using System.ComponentModel.Design.Serialization; // used by the designer to serialize the DataGridViewCell class - internal class DataGridViewCellConverter : ExpandableObjectConverter { - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { - if (destinationType == typeof(InstanceDescriptor)) { + internal class DataGridViewCellConverter : ExpandableObjectConverter + { + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) + { + if (destinationType == typeof(InstanceDescriptor)) + { return true; } return base.CanConvertTo(context, destinationType); } - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) { + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == null) + { throw new ArgumentNullException(nameof(destinationType)); } DataGridViewCell cell = value as DataGridViewCell; - if (destinationType == typeof(InstanceDescriptor) && cell != null) { + if (destinationType == typeof(InstanceDescriptor) && cell != null) + { ConstructorInfo ctor = cell.GetType().GetConstructor(new Type[0]); - if (ctor != null) { + if (ctor != null) + { return new InstanceDescriptor(ctor, new object[0], false); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellErrorTextNeededEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellErrorTextNeededEventArgs.cs index 3778112fe3d..cb06a449f22 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellErrorTextNeededEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellErrorTextNeededEventArgs.cs @@ -7,7 +7,7 @@ namespace System.Windows.Forms public class DataGridViewCellErrorTextNeededEventArgs : DataGridViewCellEventArgs { - internal DataGridViewCellErrorTextNeededEventArgs( int columnIndex, int rowIndex, string errorText) : base(columnIndex, rowIndex) + internal DataGridViewCellErrorTextNeededEventArgs(int columnIndex, int rowIndex, string errorText) : base(columnIndex, rowIndex) { ErrorText = errorText; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellFormattingEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellFormattingEventArgs.cs index 9b20e743eb2..289f98ab330 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellFormattingEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellFormattingEventArgs.cs @@ -29,9 +29,9 @@ public DataGridViewCellFormattingEventArgs(int columnIndex, public DataGridViewCellStyle CellStyle { get; set; } public int ColumnIndex { get; } - + public bool FormattingApplied { get; set; } - + public int RowIndex { get; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellMouseEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellMouseEventArgs.cs index 6f542a09ac4..439bc1f6fcc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellMouseEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellMouseEventArgs.cs @@ -6,10 +6,10 @@ namespace System.Windows.Forms { public class DataGridViewCellMouseEventArgs : MouseEventArgs { - public DataGridViewCellMouseEventArgs(int columnIndex, - int rowIndex, - int localX, - int localY, + public DataGridViewCellMouseEventArgs(int columnIndex, + int rowIndex, + int localX, + int localY, MouseEventArgs e) : base(e.Button, e.Clicks, localX, localY, e.Delta) { if (columnIndex < -1) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellPaintingEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellPaintingEventArgs.cs index 9da601e6ced..25a844c024d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellPaintingEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellPaintingEventArgs.cs @@ -13,11 +13,11 @@ public class DataGridViewCellPaintingEventArgs : HandledEventArgs private DataGridView _dataGridView; public DataGridViewCellPaintingEventArgs(DataGridView dataGridView, - Graphics graphics, + Graphics graphics, Rectangle clipBounds, - Rectangle cellBounds, - int rowIndex, - int columnIndex, + Rectangle cellBounds, + int rowIndex, + int columnIndex, DataGridViewElementStates cellState, object value, object formattedValue, @@ -167,9 +167,9 @@ public void PaintContent(Rectangle clipBounds) internal void SetProperties(Graphics graphics, Rectangle clipBounds, - Rectangle cellBounds, - int rowIndex, - int columnIndex, + Rectangle cellBounds, + int rowIndex, + int columnIndex, DataGridViewElementStates cellState, object value, object formattedValue, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyle.cs index 88482e1d0d6..cdb07ea5798 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyle.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyle.cs @@ -88,14 +88,14 @@ public DataGridViewContentAlignment Alignment int alignment = this.Properties.GetInteger(PropAlignment, out found); if (found) { - return (DataGridViewContentAlignment) alignment; + return (DataGridViewContentAlignment)alignment; } return DataGridViewContentAlignment.NotSet; } set { - switch (value) - { + switch (value) + { case DataGridViewContentAlignment.NotSet: case DataGridViewContentAlignment.TopLeft: case DataGridViewContentAlignment.TopCenter: @@ -107,8 +107,8 @@ public DataGridViewContentAlignment Alignment case DataGridViewContentAlignment.BottomCenter: case DataGridViewContentAlignment.BottomRight: break; - default: - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewContentAlignment)); + default: + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewContentAlignment)); } this.AlignmentInternal = value; } @@ -124,7 +124,7 @@ internal DataGridViewContentAlignment AlignmentInternal Debug.Assert(Enum.IsDefined(typeof(DataGridViewContentAlignment), value)); if (this.Alignment != value) { - this.Properties.SetInteger(PropAlignment, (int) value); + this.Properties.SetInteger(PropAlignment, (int)value); OnPropertyChanged(DataGridViewCellStylePropertyInternal.Other); } } @@ -137,7 +137,7 @@ public Color BackColor { get { - return this.Properties.GetColor(PropBackColor); + return this.Properties.GetColor(PropBackColor); } set { @@ -154,7 +154,7 @@ public Color BackColor } [ - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] @@ -178,7 +178,7 @@ public object DataSourceNullValue return; } - if (value == System.DBNull.Value && + if (value == System.DBNull.Value && this.Properties.ContainsObject(PropDataSourceNullValue)) { this.Properties.RemoveObject(PropDataSourceNullValue); @@ -203,7 +203,7 @@ public Font Font { get { - return (Font) this.Properties.GetObject(PropFont); + return (Font)this.Properties.GetObject(PropFont); } set { @@ -220,7 +220,7 @@ public Font Font } } } - + [ SRCategory(nameof(SR.CatAppearance)) ] @@ -237,7 +237,7 @@ public Color ForeColor { this.Properties.SetColor(PropForeColor, value); } - if (!c.Equals(this.ForeColor)) + if (!c.Equals(this.ForeColor)) { OnPropertyChanged(DataGridViewCellStylePropertyInternal.ForeColor); } @@ -261,7 +261,7 @@ public string Format } else { - return (string) format; + return (string)format; } } set @@ -293,7 +293,7 @@ public IFormatProvider FormatProvider } else { - return (IFormatProvider) formatProvider; + return (IFormatProvider)formatProvider; } } set @@ -463,7 +463,7 @@ public Color SelectionBackColor { get { - return this.Properties.GetColor(PropSelectionBackColor); + return this.Properties.GetColor(PropSelectionBackColor); } set { @@ -478,7 +478,7 @@ public Color SelectionBackColor } } } - + [ SRCategory(nameof(SR.CatAppearance)) ] @@ -486,7 +486,7 @@ public Color SelectionForeColor { get { - return this.Properties.GetColor(PropSelectionForeColor); + return this.Properties.GetColor(PropSelectionForeColor); } set { @@ -495,7 +495,7 @@ public Color SelectionForeColor { this.Properties.SetColor(PropSelectionForeColor, value); } - if (!c.Equals(this.SelectionForeColor)) + if (!c.Equals(this.SelectionForeColor)) { OnPropertyChanged(DataGridViewCellStylePropertyInternal.Color); } @@ -534,15 +534,16 @@ public DataGridViewTriState WrapMode int wrap = this.Properties.GetInteger(PropWrapMode, out found); if (found) { - return (DataGridViewTriState) wrap; + return (DataGridViewTriState)wrap; } return DataGridViewTriState.NotSet; } set { // Sequential enum. Valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridViewTriState.NotSet, (int)DataGridViewTriState.False)){ - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewTriState)); + if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridViewTriState.NotSet, (int)DataGridViewTriState.False)) + { + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewTriState)); } this.WrapModeInternal = value; } @@ -555,7 +556,7 @@ internal DataGridViewTriState WrapModeInternal Debug.Assert(value >= DataGridViewTriState.NotSet && value <= DataGridViewTriState.False); if (this.WrapMode != value) { - this.Properties.SetInteger(PropWrapMode, (int) value); + this.Properties.SetInteger(PropWrapMode, (int)value); OnPropertyChanged(DataGridViewCellStylePropertyInternal.Other); } } @@ -627,11 +628,12 @@ public virtual void ApplyStyle(DataGridViewCellStyle dataGridViewCellStyle) } } - public virtual DataGridViewCellStyle Clone() { + public virtual DataGridViewCellStyle Clone() + { return new DataGridViewCellStyle(this); } - public override bool Equals(object o) + public override bool Equals(object o) { DataGridViewCellStyle dgvcs = o as DataGridViewCellStyle; if (dgvcs != null) @@ -657,13 +659,13 @@ internal DataGridViewCellStyleDifferences GetDifferencesFrom(DataGridViewCellSty dgvcs.NullValue != this.NullValue || dgvcs.Padding != this.Padding || dgvcs.Tag != this.Tag || - dgvcs.WrapMode != this.WrapMode ); + dgvcs.WrapMode != this.WrapMode); bool preferredSizeNonAffectingPropDifferent = ( dgvcs.BackColor != this.BackColor || dgvcs.ForeColor != this.ForeColor || dgvcs.SelectionBackColor != this.SelectionBackColor || - dgvcs.SelectionForeColor != this.SelectionForeColor ); + dgvcs.SelectionForeColor != this.SelectionForeColor); if (preferredSizeAffectingPropDifferent) { @@ -745,42 +747,49 @@ internal void RemoveScope(DataGridViewCellStyleScopes scope) } } - private bool ShouldSerializeBackColor() { + private bool ShouldSerializeBackColor() + { bool found; this.Properties.GetColor(PropBackColor, out found); return found; } - private bool ShouldSerializeFont() { + private bool ShouldSerializeFont() + { return this.Properties.GetObject(PropFont) != null; } - private bool ShouldSerializeForeColor() { + private bool ShouldSerializeForeColor() + { bool found; this.Properties.GetColor(PropForeColor, out found); return found; } - private bool ShouldSerializeFormatProvider() { + private bool ShouldSerializeFormatProvider() + { return this.Properties.GetObject(PropFormatProvider) != null; } - private bool ShouldSerializePadding() { + private bool ShouldSerializePadding() + { return this.Padding != Padding.Empty; } - private bool ShouldSerializeSelectionBackColor() { + private bool ShouldSerializeSelectionBackColor() + { bool found; this.Properties.GetObject(PropSelectionBackColor, out found); return found; } - private bool ShouldSerializeSelectionForeColor() { + private bool ShouldSerializeSelectionForeColor() + { bool found; this.Properties.GetColor(PropSelectionForeColor, out found); return found; } - + public override string ToString() { StringBuilder sb = new StringBuilder(128); @@ -894,7 +903,8 @@ public override string ToString() return sb.ToString(); } - object ICloneable.Clone() { + object ICloneable.Clone() + { return Clone(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyleConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyleConverter.cs index 1336a9de45b..e5ac3ac0a06 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyleConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyleConverter.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; @@ -17,19 +18,22 @@ namespace System.Windows.Forms { /// /// - public class DataGridViewCellStyleConverter : TypeConverter { - + public class DataGridViewCellStyleConverter : TypeConverter + { + /// /// Gets a value indicating whether this converter can /// convert an object to the given destination type using the context. /// - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { - if (destinationType == typeof(InstanceDescriptor)) { + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) + { + if (destinationType == typeof(InstanceDescriptor)) + { return true; } return base.CanConvertTo(context, destinationType); } - + /// /// Converts the given object to another type. The most common types to convert /// are to and from a string object. The default implementation will make a call @@ -37,16 +41,19 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) { + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == null) + { throw new ArgumentNullException(nameof(destinationType)); } - if (destinationType == typeof(InstanceDescriptor) && value is DataGridViewCellStyle) { + if (destinationType == typeof(InstanceDescriptor) && value is DataGridViewCellStyle) + { ConstructorInfo ctor = value.GetType().GetConstructor(new Type[0]); return new InstanceDescriptor(ctor, new object[0], false); } - + return base.ConvertTo(context, culture, value, destinationType); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellToolTipTextNeededEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellToolTipTextNeededEventArgs.cs index df370548bed..825f8c8e1c8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellToolTipTextNeededEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellToolTipTextNeededEventArgs.cs @@ -6,7 +6,7 @@ namespace System.Windows.Forms { public class DataGridViewCellToolTipTextNeededEventArgs : DataGridViewCellEventArgs { - internal DataGridViewCellToolTipTextNeededEventArgs(int columnIndex, int rowIndex, string toolTipText) : base(columnIndex, rowIndex) + internal DataGridViewCellToolTipTextNeededEventArgs(int columnIndex, int rowIndex, string toolTipText) : base(columnIndex, rowIndex) { ToolTipText = toolTipText; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs index bdcb67d1946..d7e507d3bdd 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs @@ -23,7 +23,7 @@ public class DataGridViewCheckBoxCell : DataGridViewCell, IDataGridViewEditingCe private static readonly DataGridViewContentAlignment anyLeft = DataGridViewContentAlignment.TopLeft | DataGridViewContentAlignment.MiddleLeft | DataGridViewContentAlignment.BottomLeft; private static readonly DataGridViewContentAlignment anyRight = DataGridViewContentAlignment.TopRight | DataGridViewContentAlignment.MiddleRight | DataGridViewContentAlignment.BottomRight; private static readonly DataGridViewContentAlignment anyCenter = DataGridViewContentAlignment.TopCenter | DataGridViewContentAlignment.MiddleCenter | DataGridViewContentAlignment.BottomCenter; - private static readonly DataGridViewContentAlignment anyBottom = DataGridViewContentAlignment.BottomRight | DataGridViewContentAlignment.BottomCenter | DataGridViewContentAlignment.BottomLeft; + private static readonly DataGridViewContentAlignment anyBottom = DataGridViewContentAlignment.BottomRight | DataGridViewContentAlignment.BottomCenter | DataGridViewContentAlignment.BottomLeft; private static readonly DataGridViewContentAlignment anyMiddle = DataGridViewContentAlignment.MiddleRight | DataGridViewContentAlignment.MiddleCenter | DataGridViewContentAlignment.MiddleLeft; private static readonly VisualStyleElement CheckBoxElement = VisualStyleElement.Button.CheckBox.UncheckedNormal; @@ -276,7 +276,7 @@ public FlatStyle FlatStyle // Sequential enum. Valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(value, (int)value, (int)FlatStyle.Flat, (int)FlatStyle.System)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(FlatStyle)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(FlatStyle)); } if (value != this.FlatStyle) { @@ -466,7 +466,7 @@ public override object Clone() Type thisType = this.GetType(); if (thisType == cellType) //performance improvement { - dataGridViewCell = new DataGridViewCheckBoxCell(); + dataGridViewCell = new DataGridViewCheckBoxCell(); } else { @@ -574,7 +574,7 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC { return Rectangle.Empty; } - + Point ptCurrentCell = this.DataGridView.CurrentCellAddress; if (ptCurrentCell.X == this.ColumnIndex && ptCurrentCell.Y == rowIndex && this.DataGridView.IsCurrentCellInEditMode) @@ -655,7 +655,7 @@ protected override object GetFormattedValue(object value, { if (ret is bool) { - bool retBool = (bool) ret; + bool retBool = (bool)ret; if (retBool) { return string.Format(this.ThreeState ? SR.DataGridViewCheckBoxCell_ClipboardChecked : SR.DataGridViewCheckBoxCell_ClipboardTrue); @@ -667,7 +667,7 @@ protected override object GetFormattedValue(object value, } else if (ret is CheckState) { - CheckState retCheckState = (CheckState) ret; + CheckState retCheckState = (CheckState)ret; if (retCheckState == CheckState.Checked) { return string.Format(this.ThreeState ? SR.DataGridViewCheckBoxCell_ClipboardChecked : SR.DataGridViewCheckBoxCell_ClipboardTrue); @@ -724,21 +724,21 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl switch (freeDimension) { case DataGridViewFreeDimension.Width: - { - preferredSize = new Size(checkBoxSize.Width + borderAndPaddingWidths + 2 * DATAGRIDVIEWCHECKBOXCELL_margin, 0); - break; - } + { + preferredSize = new Size(checkBoxSize.Width + borderAndPaddingWidths + 2 * DATAGRIDVIEWCHECKBOXCELL_margin, 0); + break; + } case DataGridViewFreeDimension.Height: - { - preferredSize = new Size(0, checkBoxSize.Height + borderAndPaddingHeights + 2 * DATAGRIDVIEWCHECKBOXCELL_margin); - break; - } + { + preferredSize = new Size(0, checkBoxSize.Height + borderAndPaddingHeights + 2 * DATAGRIDVIEWCHECKBOXCELL_margin); + break; + } default: - { - preferredSize = new Size(checkBoxSize.Width + borderAndPaddingWidths + 2 * DATAGRIDVIEWCHECKBOXCELL_margin, - checkBoxSize.Height + borderAndPaddingHeights + 2 * DATAGRIDVIEWCHECKBOXCELL_margin); - break; - } + { + preferredSize = new Size(checkBoxSize.Width + borderAndPaddingWidths + 2 * DATAGRIDVIEWCHECKBOXCELL_margin, + checkBoxSize.Height + borderAndPaddingHeights + 2 * DATAGRIDVIEWCHECKBOXCELL_margin); + break; + } } } else @@ -759,20 +759,20 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl switch (freeDimension) { case DataGridViewFreeDimension.Width: - { - preferredSize = new Size(checkBoxSize + borderAndPaddingWidths, 0); - break; - } + { + preferredSize = new Size(checkBoxSize + borderAndPaddingWidths, 0); + break; + } case DataGridViewFreeDimension.Height: - { - preferredSize = new Size(0, checkBoxSize + borderAndPaddingHeights); - break; - } + { + preferredSize = new Size(0, checkBoxSize + borderAndPaddingHeights); + break; + } default: - { - preferredSize = new Size(checkBoxSize + borderAndPaddingWidths, checkBoxSize + borderAndPaddingHeights); - break; - } + { + preferredSize = new Size(checkBoxSize + borderAndPaddingWidths, checkBoxSize + borderAndPaddingHeights); + break; + } } } @@ -949,7 +949,7 @@ protected override void OnMouseLeave(int rowIndex) } if ((this.ButtonState & ButtonState.Pushed) != 0 && - this.ColumnIndex == this.DataGridView.MouseDownCellAddress.X && + this.ColumnIndex == this.DataGridView.MouseDownCellAddress.X && rowIndex == this.DataGridView.MouseDownCellAddress.Y) { UpdateButtonState(this.ButtonState & ~ButtonState.Pushed, rowIndex); @@ -962,7 +962,7 @@ protected override void OnMouseMove(DataGridViewCellMouseEventArgs e) { return; } - + bool oldMouseInContentBounds = mouseInContentBounds; mouseInContentBounds = GetContentBounds(e.RowIndex).Contains(e.X, e.Y); if (oldMouseInContentBounds != mouseInContentBounds) @@ -976,7 +976,7 @@ protected override void OnMouseMove(DataGridViewCellMouseEventArgs e) e.RowIndex == this.DataGridView.MouseDownCellAddress.Y && Control.MouseButtons == MouseButtons.Left) { - if ((this.ButtonState & ButtonState.Pushed) == 0 && + if ((this.ButtonState & ButtonState.Pushed) == 0 && mouseInContentBounds && this.DataGridView.CellMouseDownInContentBounds) { @@ -1025,10 +1025,10 @@ private void NotifyMASSClient(Point position) (this.DataGridView.AccessibilityObject as Control.ControlAccessibleObject).NotifyClients(AccessibleEvents.StateChange, objectID, childID); } - protected override void Paint(Graphics graphics, + protected override void Paint(Graphics graphics, Rectangle clipBounds, - Rectangle cellBounds, - int rowIndex, + Rectangle cellBounds, + int rowIndex, DataGridViewElementStates elementState, object value, object formattedValue, @@ -1042,10 +1042,10 @@ protected override void Paint(Graphics graphics, throw new ArgumentNullException(nameof(cellStyle)); } - PaintPrivate(graphics, + PaintPrivate(graphics, clipBounds, - cellBounds, - rowIndex, + cellBounds, + rowIndex, elementState, formattedValue, errorText, @@ -1065,10 +1065,10 @@ protected override void Paint(Graphics graphics, // if computeContentBounds is true then PaintPrivate returns the contentBounds // else if computeErrorIconBounds is true then PaintPrivate returns the errorIconBounds // else it returns Rectangle.Empty; - private Rectangle PaintPrivate(Graphics g, + private Rectangle PaintPrivate(Graphics g, Rectangle clipBounds, - Rectangle cellBounds, - int rowIndex, + Rectangle cellBounds, + int rowIndex, DataGridViewElementStates elementState, object formattedValue, string errorText, @@ -1104,7 +1104,7 @@ private Rectangle PaintPrivate(Graphics g, CheckState checkState; ButtonState bs; Point ptCurrentCell = this.DataGridView.CurrentCellAddress; - if (ptCurrentCell.X == this.ColumnIndex && + if (ptCurrentCell.X == this.ColumnIndex && ptCurrentCell.Y == rowIndex && this.DataGridView.IsCurrentCellInEditMode) { drawErrorText = false; @@ -1160,11 +1160,11 @@ private Rectangle PaintPrivate(Graphics g, valBounds.Height -= cellStyle.Padding.Vertical; } - if (paint && + if (paint && DataGridViewCell.PaintFocus(paintParts) && - this.DataGridView.ShowFocusCues && - this.DataGridView.Focused && - ptCurrentCell.X == this.ColumnIndex && + this.DataGridView.ShowFocusCues && + this.DataGridView.Focused && + ptCurrentCell.X == this.ColumnIndex && ptCurrentCell.Y == rowIndex) { // Draw focus rectangle @@ -1174,16 +1174,16 @@ private Rectangle PaintPrivate(Graphics g, Rectangle errorBounds = valBounds; valBounds.Inflate(-DATAGRIDVIEWCHECKBOXCELL_margin, -DATAGRIDVIEWCHECKBOXCELL_margin); - + Size checkBoxSize; CheckBoxState themeCheckBoxState = CheckBoxState.UncheckedNormal; if (this.DataGridView.ApplyVisualStylesToInnerCells) { - themeCheckBoxState = CheckBoxRenderer.ConvertFromButtonState(bs, drawAsMixedCheckBox, - this.DataGridView.MouseEnteredCellAddress.Y == rowIndex && - this.DataGridView.MouseEnteredCellAddress.X == this.ColumnIndex && + themeCheckBoxState = CheckBoxRenderer.ConvertFromButtonState(bs, drawAsMixedCheckBox, + this.DataGridView.MouseEnteredCellAddress.Y == rowIndex && + this.DataGridView.MouseEnteredCellAddress.X == this.ColumnIndex && mouseInContentBounds); checkBoxSize = CheckBoxRenderer.GetGlyphSize(g, themeCheckBoxState); switch (this.FlatStyle) @@ -1255,9 +1255,9 @@ private Rectangle PaintPrivate(Graphics g, { if (paint && DataGridViewCell.PaintContentForeground(paintParts)) { - DataGridViewCheckBoxCellRenderer.DrawCheckBox(g, - new Rectangle(checkBoxX, checkBoxY, checkBoxSize.Width, checkBoxSize.Height), - (int) themeCheckBoxState); + DataGridViewCheckBoxCellRenderer.DrawCheckBox(g, + new Rectangle(checkBoxX, checkBoxY, checkBoxSize.Width, checkBoxSize.Height), + (int)themeCheckBoxState); } resultBounds = new Rectangle(checkBoxX, checkBoxY, checkBoxSize.Width, checkBoxSize.Height); @@ -1315,8 +1315,8 @@ private Rectangle PaintPrivate(Graphics g, using (Pen pen = new Pen(foreBrush.Color)) { - g.DrawLine(pen, checkBounds.Left, checkBounds.Top, checkBounds.Right-1, checkBounds.Top); - g.DrawLine(pen, checkBounds.Left, checkBounds.Top, checkBounds.Left, checkBounds.Bottom-1); + g.DrawLine(pen, checkBounds.Left, checkBounds.Top, checkBounds.Right - 1, checkBounds.Top); + g.DrawLine(pen, checkBounds.Left, checkBounds.Top, checkBounds.Left, checkBounds.Bottom - 1); } } @@ -1341,7 +1341,7 @@ private Rectangle PaintPrivate(Graphics g, // draw the check box if (checkState != CheckState.Unchecked) { - Rectangle fullSize = new Rectangle(checkBoxX-1, checkBoxY-1, checkBoxSize.Width+3, checkBoxSize.Height+3); + Rectangle fullSize = new Rectangle(checkBoxX - 1, checkBoxY - 1, checkBoxSize.Width + 3, checkBoxSize.Height + 3); fullSize.Width++; fullSize.Height++; @@ -1406,8 +1406,8 @@ private Rectangle PaintPrivate(Graphics g, this.DataGridView.RightToLeft); options.everettButtonCompat = false; ButtonBaseAdapter.LayoutData layout = options.Layout(); - - + + if (paint && DataGridViewCell.PaintContentForeground(paintParts)) { ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintPopupRender(g, @@ -1423,7 +1423,7 @@ private Rectangle PaintPrivate(Graphics g, true /*disabledColors*/, colors); CheckBoxBaseAdapter.DrawPopupBorder(g, layout.checkBounds, colors); - CheckBoxBaseAdapter.DrawCheckOnly(checkBoxSize.Width, + CheckBoxBaseAdapter.DrawCheckOnly(checkBoxSize.Width, checkState == CheckState.Checked || checkState == CheckState.Indeterminate, this.DataGridView.Enabled, checkState, @@ -1440,7 +1440,7 @@ private Rectangle PaintPrivate(Graphics g, mouseInContentBounds) { // paint over - + ButtonBaseAdapter.LayoutOptions options = ButtonInternal.CheckBoxPopupAdapter.PaintPopupLayout(g, true /*show3D*/, checkBoxSize.Width, @@ -1499,7 +1499,7 @@ private Rectangle PaintPrivate(Graphics g, options.everettButtonCompat = false; ButtonBaseAdapter.LayoutData layout = options.Layout(); - + if (paint && DataGridViewCell.PaintContentForeground(paintParts)) { ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintPopupRender(g, @@ -1566,7 +1566,7 @@ public override object ParseFormattedValue(object formattedValue, { if (formattedValue is bool) { - if ((bool) formattedValue) + if ((bool)formattedValue) { if (this.TrueValue != null) { @@ -1599,7 +1599,7 @@ public override object ParseFormattedValue(object formattedValue, } else if (formattedValue is CheckState) { - switch ((CheckState) formattedValue) + switch ((CheckState)formattedValue) { case CheckState.Checked: if (this.TrueValue != null) @@ -1683,7 +1683,8 @@ private bool SwitchFormattedValue() /// Gets the row Index and column Index of the cell. /// /// - public override string ToString() { + public override string ToString() + { return "DataGridViewCheckBoxCell { ColumnIndex=" + this.ColumnIndex.ToString(CultureInfo.CurrentCulture) + ", RowIndex=" + this.RowIndex.ToString(CultureInfo.CurrentCulture) + " }"; } @@ -1715,7 +1716,7 @@ public static VisualStyleRenderer CheckBoxRenderer public static void DrawCheckBox(Graphics g, Rectangle bounds, int state) { - CheckBoxRenderer.SetParameters(CheckBoxElement.ClassName, CheckBoxElement.Part, (int) state); + CheckBoxRenderer.SetParameters(CheckBoxElement.ClassName, CheckBoxElement.Part, (int)state); CheckBoxRenderer.DrawBackground(g, bounds, Rectangle.Truncate(g.ClipBounds)); } } @@ -1724,7 +1725,7 @@ protected class DataGridViewCheckBoxCellAccessibleObject : DataGridViewCellAcces { private int[] runtimeId = null; // Used by UIAutomation - public DataGridViewCheckBoxCellAccessibleObject(DataGridViewCell owner) : base (owner) + public DataGridViewCheckBoxCellAccessibleObject(DataGridViewCell owner) : base(owner) { } @@ -1768,11 +1769,11 @@ public override string DefaultAction if (formattedValue is System.Windows.Forms.CheckState) { - switchToCheckedState = ((CheckState) formattedValue) == CheckState.Unchecked; + switchToCheckedState = ((CheckState)formattedValue) == CheckState.Unchecked; } else if (formattedValue is bool) { - switchToCheckedState = !((bool) formattedValue); + switchToCheckedState = !((bool)formattedValue); } if (switchToCheckedState) @@ -1793,7 +1794,7 @@ public override string DefaultAction public override void DoDefaultAction() { - DataGridViewCheckBoxCell dataGridViewCell = (DataGridViewCheckBoxCell) this.Owner; + DataGridViewCheckBoxCell dataGridViewCell = (DataGridViewCheckBoxCell)this.Owner; DataGridView dataGridView = dataGridViewCell.DataGridView; if (dataGridView != null && dataGridViewCell.RowIndex == -1) @@ -1839,9 +1840,12 @@ public override int GetChildCount() internal override bool IsIAccessibleExSupported() => true; - internal override int[] RuntimeId { - get { - if (runtimeId == null) { + internal override int[] RuntimeId + { + get + { + if (runtimeId == null) + { runtimeId = new int[2]; runtimeId[0] = RuntimeIDFirstItem; // first item is static - 0x2a runtimeId[1] = this.GetHashCode(); @@ -1851,41 +1855,52 @@ internal override int[] RuntimeId { } } - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_IsTogglePatternAvailablePropertyId) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_IsTogglePatternAvailablePropertyId) + { return (object)IsPatternSupported(NativeMethods.UIA_TogglePatternId); } - else if (propertyID == NativeMethods.UIA_ControlTypePropertyId) { + else if (propertyID == NativeMethods.UIA_ControlTypePropertyId) + { return NativeMethods.UIA_CheckBoxControlTypeId; } return base.GetPropertyValue(propertyID); } - internal override bool IsPatternSupported(int patternId) { - if (patternId == NativeMethods.UIA_TogglePatternId) { + internal override bool IsPatternSupported(int patternId) + { + if (patternId == NativeMethods.UIA_TogglePatternId) + { return true; } return base.IsPatternSupported(patternId); } - internal override void Toggle() { + internal override void Toggle() + { DoDefaultAction(); } - internal override UnsafeNativeMethods.ToggleState ToggleState { - get { + internal override UnsafeNativeMethods.ToggleState ToggleState + { + get + { bool toggledState = true; object formattedValue = this.Owner.FormattedValue; - if (formattedValue is System.Windows.Forms.CheckState) { + if (formattedValue is System.Windows.Forms.CheckState) + { toggledState = ((CheckState)formattedValue) == CheckState.Checked; } - else if (formattedValue is bool) { + else if (formattedValue is bool) + { toggledState = ((bool)formattedValue); } - else { + else + { return UnsafeNativeMethods.ToggleState.ToggleState_Indeterminate; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxColumn.cs index f4e1c369702..5f99cea703d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxColumn.cs @@ -11,7 +11,7 @@ namespace System.Windows.Forms using System.Drawing; using System.Diagnostics.CodeAnalysis; using System.Globalization; - + [ToolboxBitmapAttribute(typeof(DataGridViewCheckBoxColumn), "DataGridViewCheckBoxColumn")] public class DataGridViewCheckBoxColumn : DataGridViewColumn { @@ -62,7 +62,7 @@ private DataGridViewCheckBoxCell CheckBoxCellTemplate { get { - return (DataGridViewCheckBoxCell) this.CellTemplate; + return (DataGridViewCheckBoxCell)this.CellTemplate; } } @@ -89,7 +89,7 @@ public override DataGridViewCellStyle DefaultCellStyle SRDescription(nameof(SR.DataGridView_CheckBoxColumnFalseValueDescr)), TypeConverter(typeof(StringConverter)) ] - public object FalseValue + public object FalseValue { get { @@ -128,7 +128,7 @@ public object FalseValue SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.DataGridView_CheckBoxColumnFlatStyleDescr)) ] - public FlatStyle FlatStyle + public FlatStyle FlatStyle { get { @@ -168,7 +168,7 @@ public FlatStyle FlatStyle SRDescription(nameof(SR.DataGridView_CheckBoxColumnIndeterminateValueDescr)), TypeConverter(typeof(StringConverter)) ] - public object IndeterminateValue + public object IndeterminateValue { get { @@ -240,16 +240,16 @@ public bool ThreeState } this.DataGridView.InvalidateColumn(this.Index); } - - if (value && - this.DefaultCellStyle.NullValue is bool && - (bool) this.DefaultCellStyle.NullValue == false) + + if (value && + this.DefaultCellStyle.NullValue is bool && + (bool)this.DefaultCellStyle.NullValue == false) { this.DefaultCellStyle.NullValue = CheckState.Indeterminate; } - else if (!value && - this.DefaultCellStyle.NullValue is CheckState && - (CheckState) this.DefaultCellStyle.NullValue == CheckState.Indeterminate) + else if (!value && + this.DefaultCellStyle.NullValue is CheckState && + (CheckState)this.DefaultCellStyle.NullValue == CheckState.Indeterminate) { this.DefaultCellStyle.NullValue = false; } @@ -323,9 +323,9 @@ private bool ShouldSerializeDefaultCellStyle() DataGridViewCellStyle defaultCellStyle = this.DefaultCellStyle; - return (!defaultCellStyle.BackColor.IsEmpty || + return (!defaultCellStyle.BackColor.IsEmpty || !defaultCellStyle.ForeColor.IsEmpty || - !defaultCellStyle.SelectionBackColor.IsEmpty || + !defaultCellStyle.SelectionBackColor.IsEmpty || !defaultCellStyle.SelectionForeColor.IsEmpty || defaultCellStyle.Font != null || !defaultCellStyle.NullValue.Equals(defaultNullValue) || @@ -334,7 +334,7 @@ private bool ShouldSerializeDefaultCellStyle() !defaultCellStyle.FormatProvider.Equals(System.Globalization.CultureInfo.CurrentCulture) || defaultCellStyle.Alignment != DataGridViewContentAlignment.MiddleCenter || defaultCellStyle.WrapMode != DataGridViewTriState.NotSet || - defaultCellStyle.Tag != null || + defaultCellStyle.Tag != null || !defaultCellStyle.Padding.Equals(Padding.Empty)); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumn.cs index 70f3c97115e..eaa36f091c7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumn.cs @@ -24,14 +24,14 @@ namespace System.Windows.Forms public class DataGridViewColumn : DataGridViewBand, IComponent { private const float DATAGRIDVIEWCOLUMN_defaultFillWeight = 100F; - private const int DATAGRIDVIEWCOLUMN_defaultWidth = 100; - private const int DATAGRIDVIEWCOLUMN_defaultMinColumnThickness = 5; + private const int DATAGRIDVIEWCOLUMN_defaultWidth = 100; + private const int DATAGRIDVIEWCOLUMN_defaultMinColumnThickness = 5; - private const byte DATAGRIDVIEWCOLUMN_automaticSort = 0x01; - private const byte DATAGRIDVIEWCOLUMN_programmaticSort = 0x02; - private const byte DATAGRIDVIEWCOLUMN_isDataBound = 0x04; - private const byte DATAGRIDVIEWCOLUMN_isBrowsableInternal = 0x08; - private const byte DATAGRIDVIEWCOLUMN_displayIndexHasChangedInternal = 0x10; + private const byte DATAGRIDVIEWCOLUMN_automaticSort = 0x01; + private const byte DATAGRIDVIEWCOLUMN_programmaticSort = 0x02; + private const byte DATAGRIDVIEWCOLUMN_isDataBound = 0x04; + private const byte DATAGRIDVIEWCOLUMN_isBrowsableInternal = 0x08; + private const byte DATAGRIDVIEWCOLUMN_displayIndexHasChangedInternal = 0x10; private byte flags; // see DATAGRIDVIEWCOLUMN_ consts above private DataGridViewCell cellTemplate; @@ -56,7 +56,7 @@ public class DataGridViewColumn : DataGridViewBand, IComponent /// Initializes a new instance of the class. /// /// - public DataGridViewColumn() : this((DataGridViewCell) null) + public DataGridViewColumn() : this((DataGridViewCell)null) { } @@ -97,19 +97,19 @@ public DataGridViewAutoSizeColumnMode AutoSizeMode } set { - switch (value) - { - case DataGridViewAutoSizeColumnMode.NotSet: - case DataGridViewAutoSizeColumnMode.None: - case DataGridViewAutoSizeColumnMode.ColumnHeader: - case DataGridViewAutoSizeColumnMode.AllCellsExceptHeader: - case DataGridViewAutoSizeColumnMode.AllCells: - case DataGridViewAutoSizeColumnMode.DisplayedCellsExceptHeader: - case DataGridViewAutoSizeColumnMode.DisplayedCells: - case DataGridViewAutoSizeColumnMode.Fill: - break; - default: - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewAutoSizeColumnMode)); + switch (value) + { + case DataGridViewAutoSizeColumnMode.NotSet: + case DataGridViewAutoSizeColumnMode.None: + case DataGridViewAutoSizeColumnMode.ColumnHeader: + case DataGridViewAutoSizeColumnMode.AllCellsExceptHeader: + case DataGridViewAutoSizeColumnMode.AllCells: + case DataGridViewAutoSizeColumnMode.DisplayedCellsExceptHeader: + case DataGridViewAutoSizeColumnMode.DisplayedCells: + case DataGridViewAutoSizeColumnMode.Fill: + break; + default: + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewAutoSizeColumnMode)); } if (this.autoSizeMode != value) { @@ -136,7 +136,7 @@ public DataGridViewAutoSizeColumnMode AutoSizeMode this.autoSizeMode = value; if (this.DataGridView == null) { - if (this.InheritedAutoSizeMode != DataGridViewAutoSizeColumnMode.Fill && + if (this.InheritedAutoSizeMode != DataGridViewAutoSizeColumnMode.Fill && this.InheritedAutoSizeMode != DataGridViewAutoSizeColumnMode.None && this.InheritedAutoSizeMode != DataGridViewAutoSizeColumnMode.NotSet) { @@ -300,9 +300,9 @@ private bool ShouldSerializeDefaultCellStyle() DataGridViewCellStyle defaultCellStyle = this.DefaultCellStyle; - return (!defaultCellStyle.BackColor.IsEmpty || + return (!defaultCellStyle.BackColor.IsEmpty || !defaultCellStyle.ForeColor.IsEmpty || - !defaultCellStyle.SelectionBackColor.IsEmpty || + !defaultCellStyle.SelectionBackColor.IsEmpty || !defaultCellStyle.SelectionForeColor.IsEmpty || defaultCellStyle.Font != null || !defaultCellStyle.IsNullValueDefault || @@ -311,7 +311,7 @@ private bool ShouldSerializeDefaultCellStyle() !defaultCellStyle.FormatProvider.Equals(System.Globalization.CultureInfo.CurrentCulture) || defaultCellStyle.Alignment != DataGridViewContentAlignment.NotSet || defaultCellStyle.WrapMode != DataGridViewTriState.NotSet || - defaultCellStyle.Tag != null || + defaultCellStyle.Tag != null || !defaultCellStyle.Padding.Equals(Padding.Empty)); } @@ -345,11 +345,11 @@ internal int DesiredMinimumWidth ] public int DisplayIndex { - get + get { return this.displayIndex; } - set + set { if (this.displayIndex != value) { @@ -405,7 +405,7 @@ internal bool DisplayIndexHasChanged { if (value) { - this.flags |= (byte) DATAGRIDVIEWCOLUMN_displayIndexHasChangedInternal; + this.flags |= (byte)DATAGRIDVIEWCOLUMN_displayIndexHasChangedInternal; } else { @@ -442,11 +442,11 @@ public event EventHandler Disposed ] public int DividerWidth { - get + get { return this.DividerThickness; } - set + set { this.DividerThickness = value; } @@ -521,7 +521,7 @@ public DataGridViewColumnHeaderCell HeaderCell { get { - return (DataGridViewColumnHeaderCell) base.HeaderCellCore; + return (DataGridViewColumnHeaderCell)base.HeaderCellCore; } set { @@ -568,7 +568,7 @@ public string HeaderText private bool ShouldSerializeHeaderText() { - return this.HasHeaderCell && ((DataGridViewColumnHeaderCell) this.HeaderCell).ContainsLocalValue; + return this.HasHeaderCell && ((DataGridViewColumnHeaderCell)this.HeaderCell).ContainsLocalValue; } [ @@ -741,7 +741,7 @@ internal bool IsBrowsableInternal { if (value) { - this.flags |= (byte) DATAGRIDVIEWCOLUMN_isBrowsableInternal; + this.flags |= (byte)DATAGRIDVIEWCOLUMN_isBrowsableInternal; } else { @@ -783,7 +783,7 @@ internal bool IsDataBoundInternal [ DefaultValue(DATAGRIDVIEWCOLUMN_defaultMinColumnThickness), - Localizable(true), + Localizable(true), SRCategory(nameof(SR.CatLayout)), SRDescription(nameof(SR.DataGridView_ColumnMinimumWidthDescr)), RefreshProperties(RefreshProperties.Repaint) @@ -833,7 +833,7 @@ public string Name return name; } set - { + { string oldName = this.name; if (string.IsNullOrEmpty(value)) { @@ -843,8 +843,8 @@ public string Name { this.name = value; } - - if (this.DataGridView != null && !string.Equals(this.name, oldName,StringComparison.Ordinal)) + + if (this.DataGridView != null && !string.Equals(this.name, oldName, StringComparison.Ordinal)) { this.DataGridView.OnColumnNameChanged(this); } @@ -866,7 +866,7 @@ public override bool ReadOnly if (this.IsDataBound && this.DataGridView != null && this.DataGridView.DataConnection != null && - this.boundColumnIndex != -1 && + this.boundColumnIndex != -1 && this.DataGridView.DataConnection.DataFieldIsReadOnly(this.boundColumnIndex) && !value) { @@ -970,7 +970,7 @@ public DataGridViewColumnSortMode SortMode [ DefaultValue(""), - Localizable(true), + Localizable(true), SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.DataGridView_ColumnToolTipTextDescr)) ] @@ -1016,7 +1016,7 @@ public Type ValueType { get { - return (Type) this.Properties.GetObject(PropDataGridViewColumnValueType); + return (Type)this.Properties.GetObject(PropDataGridViewColumnValueType); } set { @@ -1027,7 +1027,7 @@ public Type ValueType [ DefaultValue(true), - Localizable(true), + Localizable(true), SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.DataGridView_ColumnVisibleDescr)) ] @@ -1045,7 +1045,7 @@ public override bool Visible [ SRCategory(nameof(SR.CatLayout)), - Localizable(true), + Localizable(true), SRDescription(nameof(SR.DataGridView_ColumnWidthDescr)), RefreshProperties(RefreshProperties.Repaint) ] @@ -1065,7 +1065,7 @@ public override object Clone() { // - DataGridViewColumn dataGridViewColumn = (DataGridViewColumn) System.Activator.CreateInstance(this.GetType()); + DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)System.Activator.CreateInstance(this.GetType()); if (dataGridViewColumn != null) { CloneInternal(dataGridViewColumn); @@ -1094,7 +1094,7 @@ internal void CloneInternal(DataGridViewColumn dataGridViewColumn) if (this.HasHeaderCell) { - dataGridViewColumn.HeaderCell = (DataGridViewColumnHeaderCell) this.HeaderCell.Clone(); + dataGridViewColumn.HeaderCell = (DataGridViewColumnHeaderCell)this.HeaderCell.Clone(); } dataGridViewColumn.AutoSizeMode = this.AutoSizeMode; @@ -1102,13 +1102,14 @@ internal void CloneInternal(DataGridViewColumn dataGridViewColumn) dataGridViewColumn.FillWeightInternal = this.FillWeight; } - protected override void Dispose(bool disposing) { - try + protected override void Dispose(bool disposing) + { + try { if (disposing) { // - lock(this) + lock (this) { if (this.site != null && this.site.Container != null) { @@ -1122,7 +1123,7 @@ protected override void Dispose(bool disposing) { } } } - finally + finally { base.Dispose(disposing); } @@ -1167,7 +1168,8 @@ public virtual int GetPreferredWidth(DataGridViewAutoSizeColumnMode autoSizeColu { throw new ArgumentException(string.Format(SR.DataGridView_NeedColumnAutoSizingCriteria, "autoSizeColumnMode")); } - switch (autoSizeColumnMode) { + switch (autoSizeColumnMode) + { case DataGridViewAutoSizeColumnMode.NotSet: case DataGridViewAutoSizeColumnMode.None: case DataGridViewAutoSizeColumnMode.ColumnHeader: @@ -1177,9 +1179,9 @@ public virtual int GetPreferredWidth(DataGridViewAutoSizeColumnMode autoSizeColu case DataGridViewAutoSizeColumnMode.DisplayedCells: case DataGridViewAutoSizeColumnMode.Fill: break; - default: - throw new InvalidEnumArgumentException(nameof(autoSizeColumnMode), (int) autoSizeColumnMode, typeof(DataGridViewAutoSizeColumnMode)); - } + default: + throw new InvalidEnumArgumentException(nameof(autoSizeColumnMode), (int)autoSizeColumnMode, typeof(DataGridViewAutoSizeColumnMode)); + } DataGridView dataGridView = this.DataGridView; @@ -1190,7 +1192,7 @@ public virtual int GetPreferredWidth(DataGridViewAutoSizeColumnMode autoSizeColu return -1; } - DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaInternal = (DataGridViewAutoSizeColumnCriteriaInternal) autoSizeColumnMode; + DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaInternal = (DataGridViewAutoSizeColumnCriteriaInternal)autoSizeColumnMode; Debug.Assert(autoSizeColumnCriteriaInternal == DataGridViewAutoSizeColumnCriteriaInternal.Header || autoSizeColumnCriteriaInternal == DataGridViewAutoSizeColumnCriteriaInternal.AllRows || autoSizeColumnCriteriaInternal == DataGridViewAutoSizeColumnCriteriaInternal.DisplayedRows || diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs index 6ecc145bdee..2c9010aff3a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs @@ -13,7 +13,7 @@ namespace System.Windows.Forms using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Globalization; - + /// /// Represents a collection of objects in the /// control. @@ -38,12 +38,12 @@ public class DataGridViewColumnCollection : BaseCollection, IList bool IList.IsFixedSize { - get {return false;} + get { return false; } } bool IList.IsReadOnly { - get {return false;} + get { return false; } } object IList.this[int index] @@ -54,7 +54,7 @@ object IList.this[int index] int IList.Add(object value) { - return this.Add((DataGridViewColumn) value); + return this.Add((DataGridViewColumn)value); } void IList.Clear() @@ -74,12 +74,12 @@ int IList.IndexOf(object value) void IList.Insert(int index, object value) { - this.Insert(index, (DataGridViewColumn) value); + this.Insert(index, (DataGridViewColumn)value); } void IList.Remove(object value) { - this.Remove((DataGridViewColumn) value); + this.Remove((DataGridViewColumn)value); } void IList.RemoveAt(int index) @@ -92,7 +92,7 @@ void IList.RemoveAt(int index) int ICollection.Count { - get + get { return this.items.Count; } @@ -100,7 +100,7 @@ int ICollection.Count bool ICollection.IsSynchronized { - get + get { return false; } @@ -108,7 +108,7 @@ bool ICollection.IsSynchronized object ICollection.SyncRoot { - get + get { return this; } @@ -166,7 +166,7 @@ public DataGridViewColumn this[int index] { get { - return (DataGridViewColumn) this.items[index]; + return (DataGridViewColumn)this.items[index]; } } @@ -184,7 +184,7 @@ public DataGridViewColumn this[string columnName] int itemCount = this.items.Count; for (int i = 0; i < itemCount; ++i) { - DataGridViewColumn dataGridViewColumn = (DataGridViewColumn) this.items[i]; + DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.items[i]; // NOTE: case-insensitive if (string.Equals(dataGridViewColumn.Name, columnName, StringComparison.OrdinalIgnoreCase)) { @@ -205,7 +205,7 @@ internal int ActualDisplayIndexToColumnIndex(int actualDisplayIndex, DataGridVie { // Microsoft: is there a faster way to get the column index? DataGridViewColumn dataGridViewColumn = GetFirstColumn(includeFilter); - for (int i = 0; i < actualDisplayIndex; i ++) + for (int i = 0; i < actualDisplayIndex; i++) { dataGridViewColumn = GetNextColumn(dataGridViewColumn, includeFilter, DataGridViewElementStates.None); } @@ -255,7 +255,7 @@ public virtual int Add(DataGridViewColumn dataGridViewColumn) #endif return index; } - + public virtual void AddRange(params DataGridViewColumn[] dataGridViewColumns) { if (dataGridViewColumns == null) @@ -280,7 +280,7 @@ public virtual void AddRange(params DataGridViewColumn[] dataGridViewColumns) ArrayList sortedColumns = new ArrayList(dataGridViewColumns.Length); // All columns with DisplayIndex != -1 are put into the initialColumns array - foreach (DataGridViewColumn dataGridViewColumn in dataGridViewColumns) + foreach (DataGridViewColumn dataGridViewColumn in dataGridViewColumns) { if (dataGridViewColumn.DisplayIndex != -1) { @@ -296,9 +296,9 @@ public virtual void AddRange(params DataGridViewColumn[] dataGridViewColumns) { smallestDisplayIndex = int.MaxValue; smallestIndex = -1; - for (index = 0; index < initialColumns.Count; index++) + for (index = 0; index < initialColumns.Count; index++) { - DataGridViewColumn dataGridViewColumn = (DataGridViewColumn) initialColumns[index]; + DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)initialColumns[index]; if (dataGridViewColumn.DisplayIndex < smallestDisplayIndex) { smallestDisplayIndex = dataGridViewColumn.DisplayIndex; @@ -312,7 +312,7 @@ public virtual void AddRange(params DataGridViewColumn[] dataGridViewColumns) // The columns with DisplayIndex == -1 are append at the end of sortedColumns // without disrupting their relative order. - foreach (DataGridViewColumn dataGridViewColumn in dataGridViewColumns) + foreach (DataGridViewColumn dataGridViewColumn in dataGridViewColumns) { if (dataGridViewColumn.DisplayIndex == -1) { @@ -322,7 +322,7 @@ public virtual void AddRange(params DataGridViewColumn[] dataGridViewColumns) // Finally the dataGridViewColumns is reconstructed using the sortedColumns. index = 0; - foreach (DataGridViewColumn dataGridViewColumn in sortedColumns) + foreach (DataGridViewColumn dataGridViewColumn in sortedColumns) { dataGridViewColumns[index] = dataGridViewColumn; index++; @@ -330,7 +330,7 @@ public virtual void AddRange(params DataGridViewColumn[] dataGridViewColumns) this.DataGridView.OnAddingColumns(dataGridViewColumns); // will throw an exception if the addition is illegal - foreach (DataGridViewColumn dataGridViewColumn in dataGridViewColumns) + foreach (DataGridViewColumn dataGridViewColumn in dataGridViewColumns) { InvalidateCachedColumnsOrder(); index = this.items.Add(dataGridViewColumn); @@ -400,7 +400,7 @@ internal int ColumnIndexToActualDisplayIndex(int columnIndex, DataGridViewElemen while (dataGridViewColumn != null && dataGridViewColumn.Index != columnIndex) { dataGridViewColumn = GetNextColumn(dataGridViewColumn, includeFilter, DataGridViewElementStates.None); - actualDisplayIndex ++; + actualDisplayIndex++; } return actualDisplayIndex; } @@ -422,7 +422,7 @@ public virtual bool Contains(string columnName) int itemCount = this.items.Count; for (int i = 0; i < itemCount; ++i) { - DataGridViewColumn dataGridViewColumn = (DataGridViewColumn) this.items[i]; + DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.items[i]; // NOTE: case-insensitive if (0 == string.Compare(dataGridViewColumn.Name, columnName, true, CultureInfo.InvariantCulture)) { @@ -439,8 +439,8 @@ public void CopyTo(DataGridViewColumn[] array, int index) internal bool DisplayInOrder(int columnIndex1, int columnIndex2) { - int displayIndex1 = ((DataGridViewColumn) this.items[columnIndex1]).DisplayIndex; - int displayIndex2 = ((DataGridViewColumn) this.items[columnIndex2]).DisplayIndex; + int displayIndex1 = ((DataGridViewColumn)this.items[columnIndex1]).DisplayIndex; + int displayIndex2 = ((DataGridViewColumn)this.items[columnIndex2]).DisplayIndex; return displayIndex1 < displayIndex2; } @@ -450,7 +450,7 @@ internal DataGridViewColumn GetColumnAtDisplayIndex(int displayIndex) { return null; } - DataGridViewColumn dataGridViewColumn = ((DataGridViewColumn) this.items[displayIndex]); + DataGridViewColumn dataGridViewColumn = ((DataGridViewColumn)this.items[displayIndex]); if (dataGridViewColumn.DisplayIndex == displayIndex) { // Performance gain if display indexes coincide with indexes. @@ -458,7 +458,7 @@ internal DataGridViewColumn GetColumnAtDisplayIndex(int displayIndex) } for (int columnIndex = 0; columnIndex < this.items.Count; columnIndex++) { - dataGridViewColumn = ((DataGridViewColumn) this.items[columnIndex]); + dataGridViewColumn = ((DataGridViewColumn)this.items[columnIndex]); if (dataGridViewColumn.DisplayIndex == displayIndex) { return dataGridViewColumn; @@ -531,16 +531,16 @@ public int GetColumnCount(DataGridViewElementStates includeFilter) internal int GetColumnCount(DataGridViewElementStates includeFilter, int fromColumnIndex, int toColumnIndex) { - Debug.Assert((includeFilter & ~(DataGridViewElementStates.Displayed | DataGridViewElementStates.Frozen | DataGridViewElementStates.Resizable | + Debug.Assert((includeFilter & ~(DataGridViewElementStates.Displayed | DataGridViewElementStates.Frozen | DataGridViewElementStates.Resizable | DataGridViewElementStates.ReadOnly | DataGridViewElementStates.Selected | DataGridViewElementStates.Visible)) == 0); Debug.Assert((includeFilter & DataGridViewElementStates.Resizable) == 0); Debug.Assert(DisplayInOrder(fromColumnIndex, toColumnIndex)); - Debug.Assert(((DataGridViewColumn) this.items[toColumnIndex]).StateIncludes(includeFilter)); + Debug.Assert(((DataGridViewColumn)this.items[toColumnIndex]).StateIncludes(includeFilter)); int jumpColumns = 0; - DataGridViewColumn dataGridViewColumn = (DataGridViewColumn) this.items[fromColumnIndex]; - - while (dataGridViewColumn != (DataGridViewColumn) this.items[toColumnIndex]) + DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.items[fromColumnIndex]; + + while (dataGridViewColumn != (DataGridViewColumn)this.items[toColumnIndex]) { dataGridViewColumn = GetNextColumn(dataGridViewColumn, includeFilter, DataGridViewElementStates.None); @@ -563,7 +563,7 @@ private int GetColumnSortedIndex(DataGridViewColumn dataGridViewColumn) #if DEBUG Debug.Assert(VerifyColumnOrderCache()); #endif - if (this.lastAccessedSortedIndex != -1 && + if (this.lastAccessedSortedIndex != -1 && this.itemsSorted[this.lastAccessedSortedIndex] == dataGridViewColumn) { return this.lastAccessedSortedIndex; @@ -572,7 +572,7 @@ private int GetColumnSortedIndex(DataGridViewColumn dataGridViewColumn) int index = 0; while (index < this.itemsSorted.Count) { - if (dataGridViewColumn.Index == ((DataGridViewColumn) this.itemsSorted[index]).Index) + if (dataGridViewColumn.Index == ((DataGridViewColumn)this.itemsSorted[index]).Index) { this.lastAccessedSortedIndex = index; return index; @@ -625,11 +625,11 @@ public int GetColumnsWidth(DataGridViewElementStates includeFilter) } int columnsWidth = 0; - for(int columnIndex = 0; columnIndex < this.items.Count; columnIndex++) + for (int columnIndex = 0; columnIndex < this.items.Count; columnIndex++) { - if (((DataGridViewColumn) this.items[columnIndex]).StateIncludes(includeFilter)) + if (((DataGridViewColumn)this.items[columnIndex]).StateIncludes(includeFilter)) { - columnsWidth += ((DataGridViewColumn) this.items[columnIndex]).Thickness; + columnsWidth += ((DataGridViewColumn)this.items[columnIndex]).Thickness; } } @@ -738,8 +738,8 @@ public DataGridViewColumn GetLastColumn(DataGridViewElementStates includeFilter, int index = this.itemsSorted.Count - 1; while (index >= 0) { - DataGridViewColumn dataGridViewColumn = (DataGridViewColumn) this.itemsSorted[index]; - if (dataGridViewColumn.StateIncludes(includeFilter) && + DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.itemsSorted[index]; + if (dataGridViewColumn.StateIncludes(includeFilter) && dataGridViewColumn.StateExcludes(excludeFilter)) { this.lastAccessedSortedIndex = index; @@ -783,15 +783,15 @@ public DataGridViewColumn GetNextColumn(DataGridViewColumn dataGridViewColumnSta int indexMin = int.MaxValue, displayIndexMin = int.MaxValue; for (index = 0; index < this.items.Count; index++) { - DataGridViewColumn dataGridViewColumn = (DataGridViewColumn) this.items[index]; - if (dataGridViewColumn.StateIncludes(includeFilter) && - dataGridViewColumn.StateExcludes(excludeFilter) && - (dataGridViewColumn.DisplayIndex > dataGridViewColumnStart.DisplayIndex || - (dataGridViewColumn.DisplayIndex == dataGridViewColumnStart.DisplayIndex && + DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.items[index]; + if (dataGridViewColumn.StateIncludes(includeFilter) && + dataGridViewColumn.StateExcludes(excludeFilter) && + (dataGridViewColumn.DisplayIndex > dataGridViewColumnStart.DisplayIndex || + (dataGridViewColumn.DisplayIndex == dataGridViewColumnStart.DisplayIndex && dataGridViewColumn.Index > dataGridViewColumnStart.Index))) { - if (dataGridViewColumn.DisplayIndex < displayIndexMin || - (dataGridViewColumn.DisplayIndex == displayIndexMin && + if (dataGridViewColumn.DisplayIndex < displayIndexMin || + (dataGridViewColumn.DisplayIndex == displayIndexMin && dataGridViewColumn.Index < indexMin)) { indexMin = index; @@ -800,7 +800,7 @@ public DataGridViewColumn GetNextColumn(DataGridViewColumn dataGridViewColumnSta } } } - return columnFound ? ((DataGridViewColumn) this.items[indexMin]) : null; + return columnFound ? ((DataGridViewColumn)this.items[indexMin]) : null; } else { @@ -809,7 +809,7 @@ public DataGridViewColumn GetNextColumn(DataGridViewColumn dataGridViewColumnSta { DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.itemsSorted[index]; - if (dataGridViewColumn.StateIncludes (includeFilter) && dataGridViewColumn.StateExcludes (excludeFilter)) + if (dataGridViewColumn.StateIncludes(includeFilter) && dataGridViewColumn.StateExcludes(excludeFilter)) { this.lastAccessedSortedIndex = index; return dataGridViewColumn; @@ -821,7 +821,7 @@ public DataGridViewColumn GetNextColumn(DataGridViewColumn dataGridViewColumnSta return null; } - public DataGridViewColumn GetPreviousColumn(DataGridViewColumn dataGridViewColumnStart, + public DataGridViewColumn GetPreviousColumn(DataGridViewColumn dataGridViewColumnStart, DataGridViewElementStates includeFilter, DataGridViewElementStates excludeFilter) { @@ -855,14 +855,14 @@ public DataGridViewColumn GetPreviousColumn(DataGridViewColumn dataGridViewColum for (index = 0; index < this.items.Count; index++) { DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.items[index]; - if (dataGridViewColumn.StateIncludes(includeFilter) && - dataGridViewColumn.StateExcludes(excludeFilter) && - (dataGridViewColumn.DisplayIndex < dataGridViewColumnStart.DisplayIndex || - (dataGridViewColumn.DisplayIndex == dataGridViewColumnStart.DisplayIndex && + if (dataGridViewColumn.StateIncludes(includeFilter) && + dataGridViewColumn.StateExcludes(excludeFilter) && + (dataGridViewColumn.DisplayIndex < dataGridViewColumnStart.DisplayIndex || + (dataGridViewColumn.DisplayIndex == dataGridViewColumnStart.DisplayIndex && dataGridViewColumn.Index < dataGridViewColumnStart.Index))) { - if (dataGridViewColumn.DisplayIndex > displayIndexMax || - (dataGridViewColumn.DisplayIndex == displayIndexMax && + if (dataGridViewColumn.DisplayIndex > displayIndexMax || + (dataGridViewColumn.DisplayIndex == displayIndexMax && dataGridViewColumn.Index > indexMax)) { indexMax = index; @@ -871,7 +871,7 @@ public DataGridViewColumn GetPreviousColumn(DataGridViewColumn dataGridViewColum } } } - return columnFound ? ((DataGridViewColumn) this.items[indexMax]) : null; + return columnFound ? ((DataGridViewColumn)this.items[indexMax]) : null; } else { @@ -879,7 +879,7 @@ public DataGridViewColumn GetPreviousColumn(DataGridViewColumn dataGridViewColum while (index >= 0) { DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.itemsSorted[index]; - if (dataGridViewColumn.StateIncludes(includeFilter) && + if (dataGridViewColumn.StateIncludes(includeFilter) && dataGridViewColumn.StateExcludes(excludeFilter)) { this.lastAccessedSortedIndex = index; @@ -1075,7 +1075,7 @@ public virtual void Remove(string columnName) int itemsCount = this.items.Count; for (int i = 0; i < itemsCount; ++i) { - DataGridViewColumn dataGridViewColumn = (DataGridViewColumn) this.items[i]; + DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.items[i]; // NOTE: case-insensitive if (0 == string.Compare(dataGridViewColumn.Name, columnName, true, CultureInfo.InvariantCulture)) { @@ -1121,7 +1121,7 @@ internal void RemoveAtInternal(int index, bool force) Debug.Assert(!this.DataGridView.InDisplayIndexAdjustments); DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.items[index]; - Point newCurrentCell; + Point newCurrentCell; this.DataGridView.OnRemovingColumn(dataGridViewColumn, out newCurrentCell, force); InvalidateCachedColumnsOrder(); this.items.RemoveAt(index); @@ -1180,7 +1180,7 @@ private void UpdateColumnCaches(DataGridViewColumn dataGridViewColumn, bool addi private void UpdateColumnOrderCache() { - this.itemsSorted = (ArrayList) this.items.Clone(); + this.itemsSorted = (ArrayList)this.items.Clone(); this.itemsSorted.Sort(columnOrderComparer); this.lastAccessedSortedIndex = -1; } @@ -1200,14 +1200,17 @@ internal bool VerifyColumnDisplayIndexes() private bool VerifyColumnOrderCache() { - if (this.itemsSorted == null) return false; - if (this.itemsSorted.Count != this.items.Count) return false; + if (this.itemsSorted == null) + return false; + if (this.itemsSorted.Count != this.items.Count) + return false; int index = 0; - while (index < this.itemsSorted.Count-1) + while (index < this.itemsSorted.Count - 1) { - if (((DataGridViewColumn) this.itemsSorted[index+1]).DisplayIndex != - ((DataGridViewColumn) this.itemsSorted[index]).DisplayIndex+1) return false; + if (((DataGridViewColumn)this.itemsSorted[index + 1]).DisplayIndex != + ((DataGridViewColumn)this.itemsSorted[index]).DisplayIndex + 1) + return false; index++; } return true; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnConverter.cs index e75bb655da2..8060d2fd384 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnConverter.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; @@ -15,16 +16,19 @@ namespace System.Windows.Forms { using System.Diagnostics; using System.Globalization; using System.Reflection; - - internal class DataGridViewColumnConverter : ExpandableObjectConverter { - - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { - if (destinationType == typeof(InstanceDescriptor)) { + + internal class DataGridViewColumnConverter : ExpandableObjectConverter + { + + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) + { + if (destinationType == typeof(InstanceDescriptor)) + { return true; } return base.CanConvertTo(context, destinationType); } - + /// /// Converts the given object to another type. The most common types to convert /// are to and from a string object. The default implementation will make a call @@ -32,34 +36,40 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) { + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == null) + { throw new ArgumentNullException(nameof(destinationType)); } DataGridViewColumn dataGridViewColumn = value as DataGridViewColumn; - if (destinationType == typeof(InstanceDescriptor) && dataGridViewColumn != null) { + if (destinationType == typeof(InstanceDescriptor) && dataGridViewColumn != null) + { ConstructorInfo ctor; - + // public DataGridViewColumn(Type cellType) // - if (dataGridViewColumn.CellType != null) { + if (dataGridViewColumn.CellType != null) + { ctor = dataGridViewColumn.GetType().GetConstructor(new Type[] { typeof(Type) }); - if (ctor != null) { + if (ctor != null) + { return new InstanceDescriptor(ctor, new object[] { dataGridViewColumn.CellType }, false); - } + } } // public DataGridViewColumn() // ctor = dataGridViewColumn.GetType().GetConstructor(new Type[0]); - if (ctor != null) { + if (ctor != null) + { return new InstanceDescriptor(ctor, new object[0], false); } } - + return base.ConvertTo(context, culture, value, destinationType); - } - } + } + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnDesignTimeVisibleAttribute.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnDesignTimeVisibleAttribute.cs index bd7f2e1bce0..3664eed4bd0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnDesignTimeVisibleAttribute.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnDesignTimeVisibleAttribute.cs @@ -2,22 +2,28 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { -using System.Diagnostics.CodeAnalysis; +namespace System.Windows.Forms +{ + using System.Diagnostics.CodeAnalysis; [AttributeUsage(AttributeTargets.Class)] - public sealed class DataGridViewColumnDesignTimeVisibleAttribute: Attribute { + public sealed class DataGridViewColumnDesignTimeVisibleAttribute : Attribute + { private bool visible; - public DataGridViewColumnDesignTimeVisibleAttribute (bool visible) { + public DataGridViewColumnDesignTimeVisibleAttribute(bool visible) + { this.visible = visible; } - - public DataGridViewColumnDesignTimeVisibleAttribute () { + + public DataGridViewColumnDesignTimeVisibleAttribute() + { } - public bool Visible { - get { + public bool Visible + { + get + { return visible; } } @@ -39,9 +45,11 @@ public bool Visible { // actually immutable. ] public static readonly DataGridViewColumnDesignTimeVisibleAttribute Default = Yes; - - public override bool Equals(object obj) { - if (obj == this) { + + public override bool Equals(object obj) + { + if (obj == this) + { return true; } @@ -49,11 +57,13 @@ public override bool Equals(object obj) { return other != null && other.Visible == visible; } - public override int GetHashCode() { + public override int GetHashCode() + { return typeof(DataGridViewColumnDesignTimeVisibleAttribute).GetHashCode() ^ (visible ? -1 : 0); } - - public override bool IsDefaultAttribute() { + + public override bool IsDefaultAttribute() + { return (this.Visible == Default.Visible); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnHeaderCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnHeaderCell.cs index 87f685158e6..0eff3c11e3b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnHeaderCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnHeaderCell.cs @@ -30,7 +30,7 @@ public class DataGridViewColumnHeaderCell : DataGridViewHeaderCell private static byte sortGlyphSeparatorWidth = DATAGRIDVIEWCOLUMNHEADERCELL_sortGlyphSeparatorWidth; private static byte sortGlyphHorizontalMargin = DATAGRIDVIEWCOLUMNHEADERCELL_sortGlyphHorizontalMargin; private static byte sortGlyphWidth = DATAGRIDVIEWCOLUMNHEADERCELL_sortGlyphWidth; - private static byte sortGlyphHeight = DATAGRIDVIEWCOLUMNHEADERCELL_sortGlyphHeight; + private static byte sortGlyphHeight = DATAGRIDVIEWCOLUMNHEADERCELL_sortGlyphHeight; private static Type cellType = typeof(DataGridViewColumnHeaderCell); @@ -38,13 +38,16 @@ public class DataGridViewColumnHeaderCell : DataGridViewHeaderCell public DataGridViewColumnHeaderCell() { - if (!isScalingInitialized) { - if (DpiHelper.IsScalingRequired) { + if (!isScalingInitialized) + { + if (DpiHelper.IsScalingRequired) + { sortGlyphSeparatorWidth = (byte)DpiHelper.LogicalToDeviceUnitsX(DATAGRIDVIEWCOLUMNHEADERCELL_sortGlyphSeparatorWidth); sortGlyphHorizontalMargin = (byte)DpiHelper.LogicalToDeviceUnitsX(DATAGRIDVIEWCOLUMNHEADERCELL_sortGlyphHorizontalMargin); sortGlyphWidth = (byte)DpiHelper.LogicalToDeviceUnitsX(DATAGRIDVIEWCOLUMNHEADERCELL_sortGlyphWidth); // make sure that the width of the base of the arrow is odd, otherwise the tip of the arrow is one pixel off to the side - if ((sortGlyphWidth % 2) == 0) { + if ((sortGlyphWidth % 2) == 0) + { sortGlyphWidth++; } sortGlyphHeight = (byte)DpiHelper.LogicalToDeviceUnitsY(DATAGRIDVIEWCOLUMNHEADERCELL_sortGlyphHeight); @@ -75,7 +78,7 @@ public SortOrder SortGlyphDirection // Sequential enum. Valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)SortOrder.None, (int)SortOrder.Descending)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(SortOrder)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(SortOrder)); } if (this.OwningColumn == null || this.DataGridView == null) { @@ -115,7 +118,7 @@ public override object Clone() { // - dataGridViewCell = (DataGridViewColumnHeaderCell) System.Activator.CreateInstance(thisType); + dataGridViewCell = (DataGridViewColumnHeaderCell)System.Activator.CreateInstance(thisType); } base.CloneInternal(dataGridViewCell); dataGridViewCell.Value = this.Value; @@ -199,13 +202,13 @@ protected override object GetClipboardContent(int rowIndex, { if (!inLastRow) { - sb.Append((char) Keys.Return); - sb.Append((char) Keys.LineFeed); + sb.Append((char)Keys.Return); + sb.Append((char)Keys.LineFeed); } } else { - sb.Append(csv ? ',' : (char) Keys.Tab); + sb.Append(csv ? ',' : (char)Keys.Tab); } return sb.ToString(); } @@ -227,14 +230,14 @@ protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCel { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - + if (this.DataGridView == null || this.OwningColumn == null) { return Rectangle.Empty; } object value = GetValue(rowIndex); - + // Intentionally not using GetFormattedValue because header cells don't typically perform formatting. // the content bounds are computed on demand // we mimic a lot of the painting code @@ -328,7 +331,7 @@ public override DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle in if (cellStyle != null && !cellStyle.BackColor.IsEmpty) { inheritedCellStyleTmp.BackColor = cellStyle.BackColor; - } + } else if (!columnHeadersStyle.BackColor.IsEmpty) { inheritedCellStyleTmp.BackColor = columnHeadersStyle.BackColor; @@ -341,7 +344,7 @@ public override DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle in if (cellStyle != null && !cellStyle.ForeColor.IsEmpty) { inheritedCellStyleTmp.ForeColor = cellStyle.ForeColor; - } + } else if (!columnHeadersStyle.ForeColor.IsEmpty) { inheritedCellStyleTmp.ForeColor = columnHeadersStyle.ForeColor; @@ -354,7 +357,7 @@ public override DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle in if (cellStyle != null && !cellStyle.SelectionBackColor.IsEmpty) { inheritedCellStyleTmp.SelectionBackColor = cellStyle.SelectionBackColor; - } + } else if (!columnHeadersStyle.SelectionBackColor.IsEmpty) { inheritedCellStyleTmp.SelectionBackColor = columnHeadersStyle.SelectionBackColor; @@ -367,7 +370,7 @@ public override DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle in if (cellStyle != null && !cellStyle.SelectionForeColor.IsEmpty) { inheritedCellStyleTmp.SelectionForeColor = cellStyle.SelectionForeColor; - } + } else if (!columnHeadersStyle.SelectionForeColor.IsEmpty) { inheritedCellStyleTmp.SelectionForeColor = columnHeadersStyle.SelectionForeColor; @@ -381,7 +384,7 @@ public override DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle in if (cellStyle != null && cellStyle.Font != null) { inheritedCellStyleTmp.Font = cellStyle.Font; - } + } else if (columnHeadersStyle.Font != null) { inheritedCellStyleTmp.Font = columnHeadersStyle.Font; @@ -420,7 +423,7 @@ public override DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle in if (cellStyle != null && cellStyle.Format.Length != 0) { inheritedCellStyleTmp.Format = cellStyle.Format; - } + } else if (columnHeadersStyle.Format.Length != 0) { inheritedCellStyleTmp.Format = columnHeadersStyle.Format; @@ -446,7 +449,7 @@ public override DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle in if (cellStyle != null && cellStyle.Alignment != DataGridViewContentAlignment.NotSet) { inheritedCellStyleTmp.AlignmentInternal = cellStyle.Alignment; - } + } else if (columnHeadersStyle.Alignment != DataGridViewContentAlignment.NotSet) { inheritedCellStyleTmp.AlignmentInternal = columnHeadersStyle.Alignment; @@ -460,7 +463,7 @@ public override DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle in if (cellStyle != null && cellStyle.WrapMode != DataGridViewTriState.NotSet) { inheritedCellStyleTmp.WrapModeInternal = cellStyle.WrapMode; - } + } else if (columnHeadersStyle.WrapMode != DataGridViewTriState.NotSet) { inheritedCellStyleTmp.WrapModeInternal = columnHeadersStyle.WrapMode; @@ -536,140 +539,140 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl switch (freeDimension) { case DataGridViewFreeDimension.Width: - { - preferredSize = new Size(0, 0); - if (!string.IsNullOrEmpty(valStr)) { - if (cellStyle.WrapMode == DataGridViewTriState.True) + preferredSize = new Size(0, 0); + if (!string.IsNullOrEmpty(valStr)) { - preferredSize = new Size(DataGridViewCell.MeasureTextWidth(graphics, - valStr, - cellStyle.Font, - Math.Max(1, constraintSize.Height - borderAndPaddingHeights - 2 * DATAGRIDVIEWCOLUMNHEADERCELL_verticalMargin), - flags), - 0); + if (cellStyle.WrapMode == DataGridViewTriState.True) + { + preferredSize = new Size(DataGridViewCell.MeasureTextWidth(graphics, + valStr, + cellStyle.Font, + Math.Max(1, constraintSize.Height - borderAndPaddingHeights - 2 * DATAGRIDVIEWCOLUMNHEADERCELL_verticalMargin), + flags), + 0); + } + else + { + preferredSize = new Size(DataGridViewCell.MeasureTextSize(graphics, + valStr, + cellStyle.Font, + flags).Width, + 0); + } } - else + if (constraintSize.Height - borderAndPaddingHeights - 2 * DATAGRIDVIEWCOLUMNHEADERCELL_verticalMargin > sortGlyphHeight && + this.OwningColumn != null && + this.OwningColumn.SortMode != DataGridViewColumnSortMode.NotSortable) { - preferredSize = new Size(DataGridViewCell.MeasureTextSize(graphics, - valStr, - cellStyle.Font, - flags).Width, - 0); + preferredSize.Width += sortGlyphWidth + + 2 * sortGlyphHorizontalMargin; + if (!string.IsNullOrEmpty(valStr)) + { + preferredSize.Width += sortGlyphSeparatorWidth; + } } + preferredSize.Width = Math.Max(preferredSize.Width, 1); + break; } - if (constraintSize.Height - borderAndPaddingHeights - 2 * DATAGRIDVIEWCOLUMNHEADERCELL_verticalMargin > sortGlyphHeight && - this.OwningColumn != null && - this.OwningColumn.SortMode != DataGridViewColumnSortMode.NotSortable) + case DataGridViewFreeDimension.Height: { - preferredSize.Width += sortGlyphWidth + - 2 * sortGlyphHorizontalMargin; - if (!string.IsNullOrEmpty(valStr)) + int allowedWidth = constraintSize.Width - borderAndPaddingWidths; + Size glyphSize; + preferredSize = new Size(0, 0); + + if (allowedWidth >= sortGlyphWidth + 2 * sortGlyphHorizontalMargin && + this.OwningColumn != null && + this.OwningColumn.SortMode != DataGridViewColumnSortMode.NotSortable) { - preferredSize.Width += sortGlyphSeparatorWidth; + glyphSize = new Size(sortGlyphWidth + 2 * sortGlyphHorizontalMargin, + sortGlyphHeight); + } + else + { + glyphSize = Size.Empty; } - } - preferredSize.Width = Math.Max(preferredSize.Width, 1); - break; - } - case DataGridViewFreeDimension.Height: - { - int allowedWidth = constraintSize.Width - borderAndPaddingWidths; - Size glyphSize; - preferredSize = new Size(0, 0); - - if (allowedWidth >= sortGlyphWidth + 2 * sortGlyphHorizontalMargin && - this.OwningColumn != null && - this.OwningColumn.SortMode != DataGridViewColumnSortMode.NotSortable) - { - glyphSize = new Size(sortGlyphWidth + 2 * sortGlyphHorizontalMargin, - sortGlyphHeight); - } - else - { - glyphSize = Size.Empty; - } - if (allowedWidth - DATAGRIDVIEWCOLUMNHEADERCELL_horizontalTextMarginLeft - DATAGRIDVIEWCOLUMNHEADERCELL_horizontalTextMarginRight > 0 && - !string.IsNullOrEmpty(valStr)) - { - if (cellStyle.WrapMode == DataGridViewTriState.True) + if (allowedWidth - DATAGRIDVIEWCOLUMNHEADERCELL_horizontalTextMarginLeft - DATAGRIDVIEWCOLUMNHEADERCELL_horizontalTextMarginRight > 0 && + !string.IsNullOrEmpty(valStr)) { - if (glyphSize.Width > 0 && - allowedWidth - - DATAGRIDVIEWCOLUMNHEADERCELL_horizontalTextMarginLeft - - DATAGRIDVIEWCOLUMNHEADERCELL_horizontalTextMarginRight - - sortGlyphSeparatorWidth - - glyphSize.Width > 0) + if (cellStyle.WrapMode == DataGridViewTriState.True) { - preferredSize = new Size(0, - DataGridViewCell.MeasureTextHeight(graphics, - valStr, - cellStyle.Font, - allowedWidth - - DATAGRIDVIEWCOLUMNHEADERCELL_horizontalTextMarginLeft - - DATAGRIDVIEWCOLUMNHEADERCELL_horizontalTextMarginRight - - sortGlyphSeparatorWidth - - glyphSize.Width, - flags)); + if (glyphSize.Width > 0 && + allowedWidth - + DATAGRIDVIEWCOLUMNHEADERCELL_horizontalTextMarginLeft - + DATAGRIDVIEWCOLUMNHEADERCELL_horizontalTextMarginRight - + sortGlyphSeparatorWidth - + glyphSize.Width > 0) + { + preferredSize = new Size(0, + DataGridViewCell.MeasureTextHeight(graphics, + valStr, + cellStyle.Font, + allowedWidth - + DATAGRIDVIEWCOLUMNHEADERCELL_horizontalTextMarginLeft - + DATAGRIDVIEWCOLUMNHEADERCELL_horizontalTextMarginRight - + sortGlyphSeparatorWidth - + glyphSize.Width, + flags)); + } + else + { + preferredSize = new Size(0, + DataGridViewCell.MeasureTextHeight(graphics, + valStr, + cellStyle.Font, + allowedWidth - + DATAGRIDVIEWCOLUMNHEADERCELL_horizontalTextMarginLeft - + DATAGRIDVIEWCOLUMNHEADERCELL_horizontalTextMarginRight, + flags)); + } } else { preferredSize = new Size(0, - DataGridViewCell.MeasureTextHeight(graphics, - valStr, - cellStyle.Font, - allowedWidth - - DATAGRIDVIEWCOLUMNHEADERCELL_horizontalTextMarginLeft - - DATAGRIDVIEWCOLUMNHEADERCELL_horizontalTextMarginRight, - flags)); + DataGridViewCell.MeasureTextSize(graphics, + valStr, + cellStyle.Font, + flags).Height); } } - else - { - preferredSize = new Size(0, - DataGridViewCell.MeasureTextSize(graphics, - valStr, - cellStyle.Font, - flags).Height); - } + preferredSize.Height = Math.Max(preferredSize.Height, glyphSize.Height); + preferredSize.Height = Math.Max(preferredSize.Height, 1); + break; } - preferredSize.Height = Math.Max(preferredSize.Height, glyphSize.Height); - preferredSize.Height = Math.Max(preferredSize.Height, 1); - break; - } default: - { - if (!string.IsNullOrEmpty(valStr)) { - if (cellStyle.WrapMode == DataGridViewTriState.True) + if (!string.IsNullOrEmpty(valStr)) { - preferredSize = DataGridViewCell.MeasureTextPreferredSize(graphics, valStr, cellStyle.Font, 5.0F, flags); + if (cellStyle.WrapMode == DataGridViewTriState.True) + { + preferredSize = DataGridViewCell.MeasureTextPreferredSize(graphics, valStr, cellStyle.Font, 5.0F, flags); + } + else + { + preferredSize = DataGridViewCell.MeasureTextSize(graphics, valStr, cellStyle.Font, flags); + } } else { - preferredSize = DataGridViewCell.MeasureTextSize(graphics, valStr, cellStyle.Font, flags); + preferredSize = new Size(0, 0); } - } - else - { - preferredSize = new Size(0, 0); - } - if (this.OwningColumn != null && - this.OwningColumn.SortMode != DataGridViewColumnSortMode.NotSortable) - { - preferredSize.Width += sortGlyphWidth + - 2 * sortGlyphHorizontalMargin; - if (!string.IsNullOrEmpty(valStr)) + if (this.OwningColumn != null && + this.OwningColumn.SortMode != DataGridViewColumnSortMode.NotSortable) { - preferredSize.Width += sortGlyphSeparatorWidth; + preferredSize.Width += sortGlyphWidth + + 2 * sortGlyphHorizontalMargin; + if (!string.IsNullOrEmpty(valStr)) + { + preferredSize.Width += sortGlyphSeparatorWidth; + } + preferredSize.Height = Math.Max(preferredSize.Height, sortGlyphHeight); } - preferredSize.Height = Math.Max(preferredSize.Height, sortGlyphHeight); + preferredSize.Width = Math.Max(preferredSize.Width, 1); + preferredSize.Height = Math.Max(preferredSize.Height, 1); + break; } - preferredSize.Width = Math.Max(preferredSize.Width, 1); - preferredSize.Height = Math.Max(preferredSize.Height, 1); - break; - } } if (freeDimension != DataGridViewFreeDimension.Height) @@ -722,11 +725,11 @@ protected override object GetValue(int rowIndex) } } - protected override void Paint(Graphics graphics, + protected override void Paint(Graphics graphics, Rectangle clipBounds, - Rectangle cellBounds, - int rowIndex, - DataGridViewElementStates dataGridViewElementState, + Rectangle cellBounds, + int rowIndex, + DataGridViewElementStates dataGridViewElementState, object value, object formattedValue, string errorText, @@ -739,13 +742,13 @@ protected override void Paint(Graphics graphics, throw new ArgumentNullException(nameof(cellStyle)); } - PaintPrivate(graphics, + PaintPrivate(graphics, clipBounds, - cellBounds, - rowIndex, - dataGridViewElementState, + cellBounds, + rowIndex, + dataGridViewElementState, formattedValue, - cellStyle, + cellStyle, advancedBorderStyle, paintParts, true /*paint*/); @@ -758,8 +761,8 @@ protected override void Paint(Graphics graphics, // PaintPrivate returns the content bounds; private Rectangle PaintPrivate(Graphics g, Rectangle clipBounds, - Rectangle cellBounds, - int rowIndex, + Rectangle cellBounds, + int rowIndex, DataGridViewElementStates dataGridViewElementState, object formattedValue, DataGridViewCellStyle cellStyle, @@ -807,7 +810,7 @@ private Rectangle PaintPrivate(Graphics g, // Theming if (paint && DataGridViewCell.PaintBackground(paintParts) && backgroundBounds.Width > 0 && backgroundBounds.Height > 0) { - int state = (int) HeaderItemState.Normal; + int state = (int)HeaderItemState.Normal; // Set the state to Pressed/Hot only if the column can be sorted or selected if (this.OwningColumn != null && this.OwningColumn.SortMode != DataGridViewColumnSortMode.NotSortable || @@ -817,12 +820,12 @@ private Rectangle PaintPrivate(Graphics g, if (this.ButtonState != ButtonState.Normal) { Debug.Assert(this.ButtonState == ButtonState.Pushed); - state = (int) HeaderItemState.Pressed; + state = (int)HeaderItemState.Pressed; } - else if (this.DataGridView.MouseEnteredCellAddress.Y == rowIndex && + else if (this.DataGridView.MouseEnteredCellAddress.Y == rowIndex && this.DataGridView.MouseEnteredCellAddress.X == this.ColumnIndex) { - state = (int) HeaderItemState.Hot; + state = (int)HeaderItemState.Hot; } else if (cellSelected) { @@ -841,7 +844,7 @@ private Rectangle PaintPrivate(Graphics g, { // Flip the column header background Bitmap bmFlipXPThemes = this.FlipXPThemesBitmap; - if (bmFlipXPThemes == null || + if (bmFlipXPThemes == null || bmFlipXPThemes.Width < backgroundBounds.Width || bmFlipXPThemes.Width > 2 * backgroundBounds.Width || bmFlipXPThemes.Height < backgroundBounds.Height || bmFlipXPThemes.Height > 2 * backgroundBounds.Height) { @@ -850,7 +853,7 @@ private Rectangle PaintPrivate(Graphics g, Graphics gFlip = Graphics.FromImage(bmFlipXPThemes); DataGridViewColumnHeaderCellRenderer.DrawHeader(gFlip, new Rectangle(0, 0, backgroundBounds.Width, backgroundBounds.Height), state); bmFlipXPThemes.RotateFlip(RotateFlipType.RotateNoneFlipX); - g.DrawImage(bmFlipXPThemes, backgroundBounds, new Rectangle(bmFlipXPThemes.Width - backgroundBounds.Width, 0, backgroundBounds.Width, backgroundBounds.Height), GraphicsUnit.Pixel); + g.DrawImage(bmFlipXPThemes, backgroundBounds, new Rectangle(bmFlipXPThemes.Width - backgroundBounds.Width, 0, backgroundBounds.Width, backgroundBounds.Height), GraphicsUnit.Pixel); } else { @@ -876,7 +879,7 @@ private Rectangle PaintPrivate(Graphics g, { if (paint && DataGridViewCell.PaintBackground(paintParts) && backgroundBounds.Width > 0 && backgroundBounds.Height > 0) { - br = this.DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) || IsHighlighted() ? + br = this.DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) || IsHighlighted() ? cellStyle.SelectionBackColor : cellStyle.BackColor); if (br.Color.A == 255) { @@ -950,17 +953,17 @@ private Rectangle PaintPrivate(Graphics g, sortGlyphSeparatorWidth - sortGlyphHorizontalMargin - sortGlyphWidth, - valBounds.Top + - (valBounds.Height-sortGlyphHeight)/2); + valBounds.Top + + (valBounds.Height - sortGlyphHeight) / 2); } else { sortGlyphLocation = new Point(valBounds.Right + DATAGRIDVIEWCOLUMNHEADERCELL_horizontalTextMarginRight + - sortGlyphSeparatorWidth + + sortGlyphSeparatorWidth + sortGlyphHorizontalMargin, - valBounds.Top + - (valBounds.Height-sortGlyphHeight)/2); + valBounds.Top + + (valBounds.Height - sortGlyphHeight) / 2); } } } @@ -994,8 +997,8 @@ private Rectangle PaintPrivate(Graphics g, valBounds.Height >= sortGlyphHeight) { displaySortGlyph = true; - sortGlyphLocation = new Point(valBounds.Left + (valBounds.Width-sortGlyphWidth)/2, - valBounds.Top + (valBounds.Height-sortGlyphHeight)/2); + sortGlyphLocation = new Point(valBounds.Left + (valBounds.Width - sortGlyphWidth) / 2, + valBounds.Top + (valBounds.Height - sortGlyphHeight) / 2); } } @@ -1012,44 +1015,44 @@ private Rectangle PaintPrivate(Graphics g, case DataGridViewAdvancedCellBorderStyle.OutsetDouble: case DataGridViewAdvancedCellBorderStyle.Outset: // Sunken look - g.DrawLine(penControlDark, - sortGlyphLocation.X, - sortGlyphLocation.Y + sortGlyphHeight-2, - sortGlyphLocation.X + sortGlyphWidth/2-1, + g.DrawLine(penControlDark, + sortGlyphLocation.X, + sortGlyphLocation.Y + sortGlyphHeight - 2, + sortGlyphLocation.X + sortGlyphWidth / 2 - 1, sortGlyphLocation.Y); - g.DrawLine(penControlDark, - sortGlyphLocation.X+1, - sortGlyphLocation.Y + sortGlyphHeight-2, - sortGlyphLocation.X + sortGlyphWidth/2-1, + g.DrawLine(penControlDark, + sortGlyphLocation.X + 1, + sortGlyphLocation.Y + sortGlyphHeight - 2, + sortGlyphLocation.X + sortGlyphWidth / 2 - 1, sortGlyphLocation.Y); g.DrawLine(penControlLightLight, - sortGlyphLocation.X + sortGlyphWidth/2, + sortGlyphLocation.X + sortGlyphWidth / 2, sortGlyphLocation.Y, - sortGlyphLocation.X + sortGlyphWidth-2, - sortGlyphLocation.Y + sortGlyphHeight-2); + sortGlyphLocation.X + sortGlyphWidth - 2, + sortGlyphLocation.Y + sortGlyphHeight - 2); g.DrawLine(penControlLightLight, - sortGlyphLocation.X + sortGlyphWidth/2, + sortGlyphLocation.X + sortGlyphWidth / 2, sortGlyphLocation.Y, - sortGlyphLocation.X + sortGlyphWidth-3, - sortGlyphLocation.Y + sortGlyphHeight-2); + sortGlyphLocation.X + sortGlyphWidth - 3, + sortGlyphLocation.Y + sortGlyphHeight - 2); g.DrawLine(penControlLightLight, sortGlyphLocation.X, - sortGlyphLocation.Y + sortGlyphHeight-1, - sortGlyphLocation.X + sortGlyphWidth-2, - sortGlyphLocation.Y + sortGlyphHeight-1); + sortGlyphLocation.Y + sortGlyphHeight - 1, + sortGlyphLocation.X + sortGlyphWidth - 2, + sortGlyphLocation.Y + sortGlyphHeight - 1); break; case DataGridViewAdvancedCellBorderStyle.Inset: // Raised look - g.DrawLine(penControlLightLight, - sortGlyphLocation.X, - sortGlyphLocation.Y + sortGlyphHeight - 2, - sortGlyphLocation.X + sortGlyphWidth / 2 - 1, + g.DrawLine(penControlLightLight, + sortGlyphLocation.X, + sortGlyphLocation.Y + sortGlyphHeight - 2, + sortGlyphLocation.X + sortGlyphWidth / 2 - 1, sortGlyphLocation.Y); - g.DrawLine(penControlLightLight, - sortGlyphLocation.X+1, - sortGlyphLocation.Y + sortGlyphHeight - 2, - sortGlyphLocation.X + sortGlyphWidth / 2 - 1, + g.DrawLine(penControlLightLight, + sortGlyphLocation.X + 1, + sortGlyphLocation.Y + sortGlyphHeight - 2, + sortGlyphLocation.X + sortGlyphWidth / 2 - 1, sortGlyphLocation.Y); g.DrawLine(penControlDark, sortGlyphLocation.X + sortGlyphWidth / 2, @@ -1095,59 +1098,59 @@ private Rectangle PaintPrivate(Graphics g, case DataGridViewAdvancedCellBorderStyle.OutsetDouble: case DataGridViewAdvancedCellBorderStyle.Outset: // Sunken look - g.DrawLine(penControlDark, - sortGlyphLocation.X, - sortGlyphLocation.Y+1, - sortGlyphLocation.X+sortGlyphWidth/2-1, - sortGlyphLocation.Y+sortGlyphHeight-1); - g.DrawLine(penControlDark, - sortGlyphLocation.X+1, - sortGlyphLocation.Y+1, - sortGlyphLocation.X+sortGlyphWidth/2-1, - sortGlyphLocation.Y+sortGlyphHeight-1); + g.DrawLine(penControlDark, + sortGlyphLocation.X, + sortGlyphLocation.Y + 1, + sortGlyphLocation.X + sortGlyphWidth / 2 - 1, + sortGlyphLocation.Y + sortGlyphHeight - 1); + g.DrawLine(penControlDark, + sortGlyphLocation.X + 1, + sortGlyphLocation.Y + 1, + sortGlyphLocation.X + sortGlyphWidth / 2 - 1, + sortGlyphLocation.Y + sortGlyphHeight - 1); g.DrawLine(penControlLightLight, - sortGlyphLocation.X+sortGlyphWidth/2, - sortGlyphLocation.Y+sortGlyphHeight-1, - sortGlyphLocation.X+sortGlyphWidth-2, - sortGlyphLocation.Y+1); + sortGlyphLocation.X + sortGlyphWidth / 2, + sortGlyphLocation.Y + sortGlyphHeight - 1, + sortGlyphLocation.X + sortGlyphWidth - 2, + sortGlyphLocation.Y + 1); g.DrawLine(penControlLightLight, - sortGlyphLocation.X+sortGlyphWidth/2, - sortGlyphLocation.Y+sortGlyphHeight-1, - sortGlyphLocation.X+sortGlyphWidth-3, - sortGlyphLocation.Y+1); + sortGlyphLocation.X + sortGlyphWidth / 2, + sortGlyphLocation.Y + sortGlyphHeight - 1, + sortGlyphLocation.X + sortGlyphWidth - 3, + sortGlyphLocation.Y + 1); g.DrawLine(penControlLightLight, sortGlyphLocation.X, sortGlyphLocation.Y, - sortGlyphLocation.X+sortGlyphWidth-2, + sortGlyphLocation.X + sortGlyphWidth - 2, sortGlyphLocation.Y); break; case DataGridViewAdvancedCellBorderStyle.Inset: // Raised look - g.DrawLine(penControlLightLight, - sortGlyphLocation.X, - sortGlyphLocation.Y+1, - sortGlyphLocation.X+sortGlyphWidth/2-1, - sortGlyphLocation.Y+sortGlyphHeight-1); - g.DrawLine(penControlLightLight, - sortGlyphLocation.X+1, - sortGlyphLocation.Y+1, - sortGlyphLocation.X+sortGlyphWidth/2-1, - sortGlyphLocation.Y+sortGlyphHeight-1); + g.DrawLine(penControlLightLight, + sortGlyphLocation.X, + sortGlyphLocation.Y + 1, + sortGlyphLocation.X + sortGlyphWidth / 2 - 1, + sortGlyphLocation.Y + sortGlyphHeight - 1); + g.DrawLine(penControlLightLight, + sortGlyphLocation.X + 1, + sortGlyphLocation.Y + 1, + sortGlyphLocation.X + sortGlyphWidth / 2 - 1, + sortGlyphLocation.Y + sortGlyphHeight - 1); g.DrawLine(penControlDark, - sortGlyphLocation.X+sortGlyphWidth/2, - sortGlyphLocation.Y+sortGlyphHeight-1, - sortGlyphLocation.X+sortGlyphWidth-2, - sortGlyphLocation.Y+1); + sortGlyphLocation.X + sortGlyphWidth / 2, + sortGlyphLocation.Y + sortGlyphHeight - 1, + sortGlyphLocation.X + sortGlyphWidth - 2, + sortGlyphLocation.Y + 1); g.DrawLine(penControlDark, - sortGlyphLocation.X+sortGlyphWidth/2, - sortGlyphLocation.Y+sortGlyphHeight-1, - sortGlyphLocation.X+sortGlyphWidth-3, - sortGlyphLocation.Y+1); + sortGlyphLocation.X + sortGlyphWidth / 2, + sortGlyphLocation.Y + sortGlyphHeight - 1, + sortGlyphLocation.X + sortGlyphWidth - 3, + sortGlyphLocation.Y + 1); g.DrawLine(penControlDark, sortGlyphLocation.X, sortGlyphLocation.Y, - sortGlyphLocation.X+sortGlyphWidth-2, + sortGlyphLocation.X + sortGlyphWidth - 2, sortGlyphLocation.Y); break; @@ -1176,7 +1179,7 @@ private Rectangle PaintPrivate(Graphics g, private bool IsHighlighted() { - return this.DataGridView.SelectionMode == DataGridViewSelectionMode.FullRowSelect && + return this.DataGridView.SelectionMode == DataGridViewSelectionMode.FullRowSelect && this.DataGridView.CurrentCell != null && this.DataGridView.CurrentCell.Selected && this.DataGridView.CurrentCell.OwningColumn == this.OwningColumn; } @@ -1228,14 +1231,14 @@ public static VisualStyleRenderer VisualStyleRenderer public static void DrawHeader(Graphics g, Rectangle bounds, int headerState) { Rectangle rectClip = Rectangle.Truncate(g.ClipBounds); - if ((int) HeaderItemState.Hot == headerState) + if ((int)HeaderItemState.Hot == headerState) { // Workaround for a VisualStyleRenderer.SetParameters(HeaderElement); - Rectangle cornerClip = new Rectangle(bounds.Left, bounds.Bottom-2, 2, 2); + Rectangle cornerClip = new Rectangle(bounds.Left, bounds.Bottom - 2, 2, 2); cornerClip.Intersect(rectClip); VisualStyleRenderer.DrawBackground(g, bounds, cornerClip); - cornerClip = new Rectangle(bounds.Right-2, bounds.Bottom-2, 2, 2); + cornerClip = new Rectangle(bounds.Right - 2, bounds.Bottom - 2, 2, 2); cornerClip.Intersect(rectClip); VisualStyleRenderer.DrawBackground(g, bounds, cornerClip); } @@ -1246,7 +1249,7 @@ public static void DrawHeader(Graphics g, Rectangle bounds, int headerState) protected class DataGridViewColumnHeaderCellAccessibleObject : DataGridViewCellAccessibleObject { - public DataGridViewColumnHeaderCellAccessibleObject(DataGridViewColumnHeaderCell owner) : base (owner) + public DataGridViewColumnHeaderCellAccessibleObject(DataGridViewColumnHeaderCell owner) : base(owner) { } @@ -1268,7 +1271,7 @@ public override string DefaultAction { return string.Format(SR.DataGridView_AccColumnHeaderCellDefaultAction); } - else if (this.Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.FullColumnSelect|| + else if (this.Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.FullColumnSelect || this.Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) { return string.Format(SR.DataGridView_AccColumnHeaderCellSelectDefaultAction); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs index 3ed2920729f..ab4c4035841 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs @@ -21,19 +21,19 @@ namespace System.Windows.Forms /// public class DataGridViewComboBoxCell : DataGridViewCell { - private static readonly int PropComboBoxCellDataSource = PropertyStore.CreateKey(); - private static readonly int PropComboBoxCellDisplayMember = PropertyStore.CreateKey(); - private static readonly int PropComboBoxCellValueMember = PropertyStore.CreateKey(); - private static readonly int PropComboBoxCellItems = PropertyStore.CreateKey(); - private static readonly int PropComboBoxCellDropDownWidth = PropertyStore.CreateKey(); - private static readonly int PropComboBoxCellMaxDropDownItems = PropertyStore.CreateKey(); - private static readonly int PropComboBoxCellEditingComboBox = PropertyStore.CreateKey(); - private static readonly int PropComboBoxCellValueMemberProp = PropertyStore.CreateKey(); - private static readonly int PropComboBoxCellDisplayMemberProp = PropertyStore.CreateKey(); - private static readonly int PropComboBoxCellDataManager = PropertyStore.CreateKey(); - private static readonly int PropComboBoxCellColumnTemplate = PropertyStore.CreateKey(); - private static readonly int PropComboBoxCellFlatStyle = PropertyStore.CreateKey(); - private static readonly int PropComboBoxCellDisplayStyle = PropertyStore.CreateKey(); + private static readonly int PropComboBoxCellDataSource = PropertyStore.CreateKey(); + private static readonly int PropComboBoxCellDisplayMember = PropertyStore.CreateKey(); + private static readonly int PropComboBoxCellValueMember = PropertyStore.CreateKey(); + private static readonly int PropComboBoxCellItems = PropertyStore.CreateKey(); + private static readonly int PropComboBoxCellDropDownWidth = PropertyStore.CreateKey(); + private static readonly int PropComboBoxCellMaxDropDownItems = PropertyStore.CreateKey(); + private static readonly int PropComboBoxCellEditingComboBox = PropertyStore.CreateKey(); + private static readonly int PropComboBoxCellValueMemberProp = PropertyStore.CreateKey(); + private static readonly int PropComboBoxCellDisplayMemberProp = PropertyStore.CreateKey(); + private static readonly int PropComboBoxCellDataManager = PropertyStore.CreateKey(); + private static readonly int PropComboBoxCellColumnTemplate = PropertyStore.CreateKey(); + private static readonly int PropComboBoxCellFlatStyle = PropertyStore.CreateKey(); + private static readonly int PropComboBoxCellDisplayStyle = PropertyStore.CreateKey(); private static readonly int PropComboBoxCellDisplayStyleForCurrentCellOnly = PropertyStore.CreateKey(); private const byte DATAGRIDVIEWCOMBOBOXCELL_margin = 3; @@ -77,9 +77,9 @@ public class DataGridViewComboBoxCell : DataGridViewCell public DataGridViewComboBoxCell() { this.flags = DATAGRIDVIEWCOMBOBOXCELL_autoComplete; - if (!isScalingInitialized) + if (!isScalingInitialized) { - if (DpiHelper.IsScalingRequired) + if (DpiHelper.IsScalingRequired) { offset2X = DpiHelper.LogicalToDeviceUnitsX(OFFSET_2PIXELS); offset2Y = DpiHelper.LogicalToDeviceUnitsY(OFFSET_2PIXELS); @@ -308,7 +308,7 @@ public DataGridViewComboBoxDisplayStyle DisplayStyle // Sequential enum. Valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridViewComboBoxDisplayStyle.ComboBox, (int)DataGridViewComboBoxDisplayStyle.Nothing)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewComboBoxDisplayStyle)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewComboBoxDisplayStyle)); } if (value != this.DisplayStyle) { @@ -483,7 +483,7 @@ public FlatStyle FlatStyle // Sequential enum. Valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(value, (int)value, (int)FlatStyle.Flat, (int)FlatStyle.System)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(FlatStyle)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(FlatStyle)); } if (value != this.FlatStyle) { @@ -566,7 +566,7 @@ private bool PaintXPThemes return !paintFlat && this.DataGridView.ApplyVisualStylesToInnerCells; } } - + private static bool PostXPThemesExist { get @@ -615,7 +615,7 @@ internal DataGridViewComboBoxColumn TemplateComboBoxColumn { get { - return (DataGridViewComboBoxColumn) this.Properties.GetObject(PropComboBoxCellColumnTemplate); + return (DataGridViewComboBoxColumn)this.Properties.GetObject(PropComboBoxCellColumnTemplate); } set { @@ -680,8 +680,8 @@ private PropertyDescriptor ValueMemberProperty } } } - - + + public override Type ValueType { get @@ -737,16 +737,16 @@ private void CheckDropDownList(int x, int y, int rowIndex) { dropHeight = Math.Min(GetDropDownButtonHeight(g, cellStyle), adjustedSize.Height - 2); } - + int dropWidth = Math.Min(SystemInformation.HorizontalScrollBarThumbWidth, adjustedSize.Width - 2 * DATAGRIDVIEWCOMBOBOXCELL_margin - 1); - if (dropHeight > 0 && dropWidth > 0 && - y >= borderAndPaddingWidths.Y + 1 && + if (dropHeight > 0 && dropWidth > 0 && + y >= borderAndPaddingWidths.Y + 1 && y <= borderAndPaddingWidths.Y + 1 + dropHeight) { if (this.DataGridView.RightToLeftInternal) { - if (x >= borderAndPaddingWidths.X + 1 && + if (x >= borderAndPaddingWidths.X + 1 && x <= borderAndPaddingWidths.X + dropWidth + 1) { this.EditingComboBox.DroppedDown = true; @@ -754,7 +754,7 @@ private void CheckDropDownList(int x, int y, int rowIndex) } else { - if (x >= size.Width - borderAndPaddingWidths.Width - dropWidth - 1 && + if (x >= size.Width - borderAndPaddingWidths.Width - dropWidth - 1 && x <= size.Width - borderAndPaddingWidths.Width - 1) { this.EditingComboBox.DroppedDown = true; @@ -778,12 +778,12 @@ private void CheckNoDataSource() // throw new InvalidOperationException(string.Format(SR.DataGridView_InvalidOperationOnSharedCell)); // } //} - + private void ComboBox_DropDown(object sender, EventArgs e) { Debug.Assert(this.DataGridView != null); Debug.Assert(this.EditingComboBox != null); - + ComboBox comboBox = this.EditingComboBox; DataGridViewComboBoxColumn owningComboBoxColumn = this.OwningColumn as DataGridViewComboBoxColumn; if (owningComboBoxColumn != null) @@ -821,7 +821,7 @@ private void ComboBox_DropDown(object sender, EventArgs e) { // The dropdown width may have been previously adjusted to the items because of the owning column autosized. // The dropdown width needs to be realigned to the DropDownWidth property value. - int dropDownWidth = unchecked( (int) (long)UnsafeNativeMethods.SendMessage(new HandleRef(comboBox, comboBox.Handle), NativeMethods.CB_GETDROPPEDWIDTH, 0, 0)); + int dropDownWidth = unchecked((int)(long)UnsafeNativeMethods.SendMessage(new HandleRef(comboBox, comboBox.Handle), NativeMethods.CB_GETDROPPEDWIDTH, 0, 0)); if (dropDownWidth != this.DropDownWidth) { UnsafeNativeMethods.SendMessage(new HandleRef(comboBox, comboBox.Handle), NativeMethods.CB_SETDROPPEDWIDTH, this.DropDownWidth, 0); @@ -1120,7 +1120,7 @@ protected override object GetFormattedValue(object value, if (value == null || ((this.ValueType != null && !this.ValueType.IsAssignableFrom(value.GetType())) && value != System.DBNull.Value)) { // Do not raise the DataError event if the value is null and the row is the 'new row'. - + if (value == null /* && ((this.DataGridView != null && rowIndex == this.DataGridView.NewRowIndex) || this.Items.Count == 0)*/) { // Debug.Assert(rowIndex != -1 || this.Items.Count == 0); @@ -1177,7 +1177,7 @@ protected override object GetFormattedValue(object value, } else { - if (!this.Items.Contains(value) && + if (!this.Items.Contains(value) && value != System.DBNull.Value && (!(value is string) || !string.IsNullOrEmpty(strValue))) { @@ -1263,7 +1263,7 @@ internal ObjectCollection GetItems(DataGridView dataGridView) if (this.CreateItemsFromDataSource) { items.ClearInternal(); - CurrencyManager dataManager = GetDataManager(dataGridView); + CurrencyManager dataManager = GetDataManager(dataGridView); if (dataManager != null && dataManager.Count != -1) { object[] newItems = new object[dataManager.Count]; @@ -1467,13 +1467,13 @@ private void InitializeComboBoxText() int rowIndex = ((IDataGridViewEditingControl)this.EditingComboBox).EditingControlRowIndex; Debug.Assert(rowIndex > -1); DataGridViewCellStyle dataGridViewCellStyle = GetInheritedStyle(null, rowIndex, false); - this.EditingComboBox.Text = (string) GetFormattedValue(GetValue(rowIndex), rowIndex, ref dataGridViewCellStyle, null, null, DataGridViewDataErrorContexts.Formatting); + this.EditingComboBox.Text = (string)GetFormattedValue(GetValue(rowIndex), rowIndex, ref dataGridViewCellStyle, null, null, DataGridViewDataErrorContexts.Formatting); } public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle) { - Debug.Assert(this.DataGridView != null && - this.DataGridView.EditingPanel != null && + Debug.Assert(this.DataGridView != null && + this.DataGridView.EditingPanel != null && this.DataGridView.EditingControl != null); Debug.Assert(!this.ReadOnly); base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle); @@ -1564,7 +1564,7 @@ private void InitializeDisplayMemberPropertyDescriptor(string displayMember) if (string.IsNullOrEmpty(displayMember)) { this.DisplayMemberProperty = null; - } + } else { BindingMemberInfo displayBindingMember = new BindingMemberInfo(displayMember); @@ -1581,7 +1581,7 @@ private void InitializeDisplayMemberPropertyDescriptor(string displayMember) { this.DisplayMemberProperty = displayMemberProperty; } - } + } } } @@ -1592,7 +1592,7 @@ private void InitializeValueMemberPropertyDescriptor(string valueMember) if (string.IsNullOrEmpty(valueMember)) { this.ValueMemberProperty = null; - } + } else { BindingMemberInfo valueBindingMember = new BindingMemberInfo(valueMember); @@ -1624,7 +1624,7 @@ private object ItemFromComboBoxDataSource(PropertyDescriptor property, object ke { throw new ArgumentNullException(nameof(key)); } - + //if (key == this.keyUsedDuringAutoSize) //{ // return this.valueUsedDuringAutoSize; @@ -1916,13 +1916,13 @@ protected override void OnMouseLeave(int rowIndex) mouseInDropDownButtonBounds = false; if (this.ColumnIndex >= 0 && rowIndex >= 0 && - (this.FlatStyle == FlatStyle.Standard || this.FlatStyle == FlatStyle.System) && + (this.FlatStyle == FlatStyle.Standard || this.FlatStyle == FlatStyle.System) && this.DataGridView.ApplyVisualStylesToInnerCells) { this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex); } } - + if (this.DisplayStyle == DataGridViewComboBoxDisplayStyle.ComboBox && this.FlatStyle == FlatStyle.Popup) { this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex); @@ -1950,7 +1950,7 @@ protected override void OnMouseMove(DataGridViewCellMouseEventArgs e) bool isFirstDisplayedScrollingColumn = this.OwningColumn.Index == this.DataGridView.FirstDisplayedScrollingColumnIndex; DataGridViewAdvancedBorderStyle dgvabsEffective, dgvabsPlaceholder; dgvabsPlaceholder = new DataGridViewAdvancedBorderStyle(); - dgvabsEffective = AdjustCellBorderStyle(this.DataGridView.AdvancedCellBorderStyle, dgvabsPlaceholder, + dgvabsEffective = AdjustCellBorderStyle(this.DataGridView.AdvancedCellBorderStyle, dgvabsPlaceholder, singleVerticalBorderAdded, singleHorizontalBorderAdded, isFirstDisplayedRow, @@ -2003,10 +2003,10 @@ private bool OwnsEditingComboBox(int rowIndex) return rowIndex != -1 && this.EditingComboBox != null && rowIndex == ((IDataGridViewEditingControl)this.EditingComboBox).EditingControlRowIndex; } - protected override void Paint(Graphics graphics, + protected override void Paint(Graphics graphics, Rectangle clipBounds, - Rectangle cellBounds, - int rowIndex, + Rectangle cellBounds, + int rowIndex, DataGridViewElementStates elementState, object value, object formattedValue, @@ -2021,10 +2021,10 @@ protected override void Paint(Graphics graphics, } Rectangle dropDownButtonRect; - PaintPrivate(graphics, + PaintPrivate(graphics, clipBounds, - cellBounds, - rowIndex, + cellBounds, + rowIndex, elementState, formattedValue, errorText, @@ -2049,10 +2049,10 @@ protected override void Paint(Graphics graphics, // else it returns Rectangle.Empty; // // PaintPrivate uses the computeDropDownButtonRect to determine if it should compute the dropDownButtonRect - private Rectangle PaintPrivate(Graphics g, + private Rectangle PaintPrivate(Graphics g, Rectangle clipBounds, - Rectangle cellBounds, - int rowIndex, + Rectangle cellBounds, + int rowIndex, DataGridViewElementStates elementState, object formattedValue, string errorText, @@ -2162,7 +2162,7 @@ private Rectangle PaintPrivate(Graphics g, DataGridViewComboBoxCellRenderer.DrawTextBox(g, valBounds, comboBoxState); } } - if (!paintPostXPThemes && + if (!paintPostXPThemes && DataGridViewCell.PaintBackground(paintParts) && br.Color.A == 255 && valBounds.Width > 2 && valBounds.Height > 2) { g.FillRectangle(br, valBounds.Left + 1, valBounds.Top + 1, valBounds.Width - 2, valBounds.Height - 2); @@ -2172,7 +2172,7 @@ private Rectangle PaintPrivate(Graphics g, { if (paintPostXPThemes && drawDropDownButton && !drawComboBox) { - g.DrawRectangle(SystemPens.ControlLightLight, new Rectangle(valBounds.X, valBounds.Y, valBounds.Width-1, valBounds.Height-1)); + g.DrawRectangle(SystemPens.ControlLightLight, new Rectangle(valBounds.X, valBounds.Y, valBounds.Width - 1, valBounds.Height - 1)); } else { @@ -2275,7 +2275,7 @@ private Rectangle PaintPrivate(Graphics g, if (!paintFlat && !paintXPThemes && (drawComboBox || drawDropDownButton)) { // border painting is ripped from button renderer - Color color= SystemColors.Control; + Color color = SystemColors.Control; Color buttonShadow; Color buttonShadowDark; Color buttonFace = color; @@ -2308,16 +2308,20 @@ private Rectangle PaintPrivate(Graphics g, highlight = g.GetNearestColor(highlight); // top + left Pen pen; - if (stockColor) { - if (SystemInformation.HighContrast) { + if (stockColor) + { + if (SystemInformation.HighContrast) + { pen = SystemPens.ControlLight; } - else { + else + { pen = SystemPens.Control; } } - else { - pen= new Pen(highlight); + else + { + pen = new Pen(highlight); } if (drawDropDownButton) @@ -2336,10 +2340,12 @@ private Rectangle PaintPrivate(Graphics g, valBounds.X + valBounds.Width - 1, valBounds.Y + valBounds.Height - 1); } // bottom + right - if (stockColor) { + if (stockColor) + { pen = SystemPens.ControlDarkDark; } - else { + else + { pen.Color = buttonShadowDark; } if (drawDropDownButton) @@ -2374,10 +2380,12 @@ private Rectangle PaintPrivate(Graphics g, dropRect.X + 1, dropRect.Y + dropRect.Height - 2); } // Bottom + Right inset - if (stockColor) { + if (stockColor) + { pen = SystemPens.ControlDark; } - else { + else + { pen.Color = buttonShadow; } if (drawDropDownButton) @@ -2387,7 +2395,8 @@ private Rectangle PaintPrivate(Graphics g, g.DrawLine(pen, dropRect.X + dropRect.Width - 2, dropRect.Y + 1, dropRect.X + dropRect.Width - 2, dropRect.Y + dropRect.Height - 2); } - if (!stockColor) { + if (!stockColor) + { pen.Dispose(); } } @@ -2402,11 +2411,11 @@ private Rectangle PaintPrivate(Graphics g, // if the height is odd - favor pushing it over one pixel down. middle.Y += (dropRect.Height % 2); - g.FillPolygon(SystemBrushes.ControlText, new Point[] + g.FillPolygon(SystemBrushes.ControlText, new Point[] { new Point(middle.X - offset2X, middle.Y - 1), new Point(middle.X + offset2X + 1, middle.Y - 1), - new Point(middle.X, middle.Y + offset2Y) + new Point(middle.X, middle.Y + offset2Y) }); } else if (!paintXPThemes) @@ -2485,11 +2494,11 @@ private Rectangle PaintPrivate(Graphics g, if (textBounds.Width > 1 && textBounds.Height > 1) { - if (cellCurrent && + if (cellCurrent && !cellEdited && DataGridViewCell.PaintFocus(paintParts) && - this.DataGridView.ShowFocusCues && - this.DataGridView.Focused && + this.DataGridView.ShowFocusCues && + this.DataGridView.Focused && paint) { // Draw focus rectangle @@ -2570,7 +2579,7 @@ private Rectangle PaintPrivate(Graphics g, else { textColor = cellSelected ? cellStyle.SelectionForeColor : cellStyle.ForeColor; - } + } TextRenderer.DrawText(g, formattedString, cellStyle.Font, @@ -2590,7 +2599,7 @@ private Rectangle PaintPrivate(Graphics g, { PaintErrorIcon(g, cellStyle, rowIndex, cellBounds, errorBounds, errorText); if (cellEdited) - { + { return Rectangle.Empty; } } @@ -2629,7 +2638,7 @@ public override object ParseFormattedValue(object formattedValue, } // Find the item given its display value - if ((this.DataManager != null && + if ((this.DataManager != null && (this.DisplayMemberProperty != null || this.ValueMemberProperty != null)) || !string.IsNullOrEmpty(this.DisplayMember) || !string.IsNullOrEmpty(this.ValueMember)) { @@ -2661,7 +2670,7 @@ public override object ParseFormattedValue(object formattedValue, /// Gets the row Index and column Index of the cell. /// /// - public override string ToString() + public override string ToString() { return "DataGridViewComboBoxCell { ColumnIndex=" + this.ColumnIndex.ToString(CultureInfo.CurrentCulture) + ", RowIndex=" + this.RowIndex.ToString(CultureInfo.CurrentCulture) + " }"; } @@ -2669,7 +2678,7 @@ public override string ToString() private void UnwireDataSource() { IComponent component = this.DataSource as IComponent; - if (component != null) + if (component != null) { component.Disposed -= new EventHandler(DataSource_Disposed); } @@ -2702,45 +2711,45 @@ private void WireDataSource(object dataSource) /// /// [ListBindable(false)] - public class ObjectCollection : IList + public class ObjectCollection : IList { private DataGridViewComboBoxCell owner; private ArrayList items; private IComparer comparer; - public ObjectCollection(DataGridViewComboBoxCell owner) + public ObjectCollection(DataGridViewComboBoxCell owner) { Debug.Assert(owner != null); this.owner = owner; } - private IComparer Comparer + private IComparer Comparer { - get + get { - if (this.comparer == null) + if (this.comparer == null) { this.comparer = new ItemComparer(this.owner); } return this.comparer; } } - + /// /// Retrieves the number of items. /// public int Count { - get + get { return this.InnerArray.Count; } } - + /// /// Internal access to the actual data store. /// - internal ArrayList InnerArray + internal ArrayList InnerArray { get { @@ -2760,7 +2769,7 @@ object ICollection.SyncRoot } } - bool ICollection.IsSynchronized + bool ICollection.IsSynchronized { get { @@ -2768,22 +2777,22 @@ bool ICollection.IsSynchronized } } - bool IList.IsFixedSize + bool IList.IsFixedSize { get { return false; } } - - public bool IsReadOnly + + public bool IsReadOnly { - get + get { return false; } } - + /// /// Adds an item to the collection. For an unsorted combo box, the item is /// added to the end of the existing list of items. For a sorted combo box, @@ -2791,30 +2800,30 @@ public bool IsReadOnly /// The item's ToString() method is called to obtain the string that is /// displayed in the combo box. /// - public int Add(object item) + public int Add(object item) { //this.owner.CheckNoSharedCell(); this.owner.CheckNoDataSource(); - if (item == null) + if (item == null) { throw new ArgumentNullException(nameof(item)); } - + int index = this.InnerArray.Add(item); - + bool success = false; - if (this.owner.Sorted) + if (this.owner.Sorted) { - try + try { this.InnerArray.Sort(this.Comparer); index = this.InnerArray.IndexOf(item); success = true; } - finally + finally { - if (!success) + if (!success) { this.InnerArray.Remove(item); } @@ -2824,12 +2833,12 @@ public int Add(object item) this.owner.OnItemsCollectionChanged(); return index; } - - int IList.Add(object item) + + int IList.Add(object item) { return Add(item); } - + public void AddRange(params object[] items) { //this.owner.CheckNoSharedCell(); @@ -2837,26 +2846,26 @@ public void AddRange(params object[] items) AddRangeInternal((ICollection)items); this.owner.OnItemsCollectionChanged(); } - - public void AddRange(ObjectCollection value) + + public void AddRange(ObjectCollection value) { //this.owner.CheckNoSharedCell(); this.owner.CheckNoDataSource(); - AddRangeInternal((ICollection) value); + AddRangeInternal((ICollection)value); this.owner.OnItemsCollectionChanged(); } - + /// /// Add range that bypasses the data source check. /// - internal void AddRangeInternal(ICollection items) + internal void AddRangeInternal(ICollection items) { if (items == null) { throw new ArgumentNullException(nameof(items)); } - - foreach(object item in items) + + foreach (object item in items) { if (item == null) { @@ -2880,17 +2889,17 @@ internal void SortInternal() /// /// Retrieves the item with the specified index. /// - public virtual object this[int index] + public virtual object this[int index] { - get + get { - if (index < 0 || index >= this.InnerArray.Count) + if (index < 0 || index >= this.InnerArray.Count) { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } return this.InnerArray[index]; } - set + set { //this.owner.CheckNoSharedCell(); this.owner.CheckNoDataSource(); @@ -2909,7 +2918,7 @@ public virtual object this[int index] this.owner.OnItemsCollectionChanged(); } } - + /// /// Removes all items from the collection. /// @@ -2929,7 +2938,7 @@ internal void ClearInternal() this.InnerArray.Clear(); } - public bool Contains(object value) + public bool Contains(object value) { return IndexOf(value) != -1; } @@ -2937,10 +2946,10 @@ public bool Contains(object value) /// /// Copies the DataGridViewComboBoxCell Items collection to a destination array. /// - public void CopyTo(object[] destination, int arrayIndex) + public void CopyTo(object[] destination, int arrayIndex) { int count = this.InnerArray.Count; - for(int i = 0; i < count; i++) + for (int i = 0; i < count; i++) { destination[i + arrayIndex] = this.InnerArray[i]; } @@ -2949,7 +2958,7 @@ public void CopyTo(object[] destination, int arrayIndex) void ICollection.CopyTo(Array destination, int index) { int count = this.InnerArray.Count; - for(int i = 0; i < count; i++) + for (int i = 0; i < count; i++) { destination.SetValue(this.InnerArray[i], i + index); } @@ -2958,14 +2967,14 @@ void ICollection.CopyTo(Array destination, int index) /// /// Returns an enumerator for the DataGridViewComboBoxCell Items collection. /// - public IEnumerator GetEnumerator() + public IEnumerator GetEnumerator() { return this.InnerArray.GetEnumerator(); } - - public int IndexOf(object value) + + public int IndexOf(object value) { - if (value == null) + if (value == null) { throw new ArgumentNullException(nameof(value)); } @@ -2979,57 +2988,57 @@ public int IndexOf(object value) /// The item's toString() method is called to obtain the string that is /// displayed in the combo box. /// - public void Insert(int index, object item) + public void Insert(int index, object item) { //this.owner.CheckNoSharedCell(); this.owner.CheckNoDataSource(); - - if (item == null) + + if (item == null) { throw new ArgumentNullException(nameof(item)); } - - if (index < 0 || index > this.InnerArray.Count) + + if (index < 0 || index > this.InnerArray.Count) { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), nameof(index))); } - + // If the combo box is sorted, then just treat this like an add // because we are going to twiddle the index anyway. if (this.owner.Sorted) { Add(item); } - else + else { this.InnerArray.Insert(index, item); this.owner.OnItemsCollectionChanged(); } } - + /// /// Removes the given item from the collection, provided that it is /// actually in the list. /// - public void Remove(object value) + public void Remove(object value) { int index = this.InnerArray.IndexOf(value); - - if (index != -1) + + if (index != -1) { RemoveAt(index); } } - + /// /// Removes an item from the collection at the given index. /// - public void RemoveAt(int index) + public void RemoveAt(int index) { //this.owner.CheckNoSharedCell(); this.owner.CheckNoDataSource(); - - if (index < 0 || index >= this.InnerArray.Count) + + if (index < 0 || index >= this.InnerArray.Count) { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } @@ -3038,18 +3047,18 @@ public void RemoveAt(int index) } } // end ObjectCollection - private sealed class ItemComparer : System.Collections.IComparer + private sealed class ItemComparer : System.Collections.IComparer { private DataGridViewComboBoxCell dataGridViewComboBoxCell; - public ItemComparer(DataGridViewComboBoxCell dataGridViewComboBoxCell) + public ItemComparer(DataGridViewComboBoxCell dataGridViewComboBoxCell) { this.dataGridViewComboBoxCell = dataGridViewComboBoxCell; } - public int Compare(object item1, object item2) + public int Compare(object item1, object item2) { - if (item1 == null) + if (item1 == null) { if (item2 == null) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxColumn.cs index e4a8a2940c1..0a2cd860c07 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxColumn.cs @@ -11,7 +11,7 @@ namespace System.Windows.Forms using System.Drawing; using System.Drawing.Design; using System.Globalization; - + [ Designer("System.Windows.Forms.Design.DataGridViewComboBoxColumnDesigner, " + AssemblyRef.SystemDesign), ToolboxBitmapAttribute(typeof(DataGridViewComboBoxColumn), "DataGridViewComboBoxColumn") @@ -93,7 +93,7 @@ private DataGridViewComboBoxCell ComboBoxCellTemplate { get { - return (DataGridViewComboBoxCell) this.CellTemplate; + return (DataGridViewComboBoxCell)this.CellTemplate; } } @@ -148,7 +148,7 @@ public object DataSource ] public string DisplayMember { - get + get { if (this.ComboBoxCellTemplate == null) { @@ -156,7 +156,7 @@ public string DisplayMember } return this.ComboBoxCellTemplate.DisplayMember; } - set + set { if (this.ComboBoxCellTemplate == null) { @@ -314,7 +314,7 @@ public FlatStyle FlatStyle { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return ((DataGridViewComboBoxCell) this.CellTemplate).FlatStyle; + return ((DataGridViewComboBoxCell)this.CellTemplate).FlatStyle; } set { @@ -367,7 +367,7 @@ public DataGridViewComboBoxCell.ObjectCollection Items ] public string ValueMember { - get + get { if (this.ComboBoxCellTemplate == null) { @@ -375,7 +375,7 @@ public string ValueMember } return this.ComboBoxCellTemplate.ValueMember; } - set + set { if (this.ComboBoxCellTemplate == null) { @@ -415,7 +415,7 @@ public int MaxDropDownItems } return this.ComboBoxCellTemplate.MaxDropDownItems; } - set + set { if (this.MaxDropDownItems != value) { @@ -445,7 +445,7 @@ public int MaxDropDownItems ] public bool Sorted { - get + get { if (this.ComboBoxCellTemplate == null) { @@ -453,7 +453,7 @@ public bool Sorted } return this.ComboBoxCellTemplate.Sorted; } - set + set { if (this.Sorted != value) { @@ -494,7 +494,7 @@ public override object Clone() if (dataGridViewColumn != null) { base.CloneInternal(dataGridViewColumn); - ((DataGridViewComboBoxCell) dataGridViewColumn.CellTemplate).TemplateComboBoxColumn = dataGridViewColumn; + ((DataGridViewComboBoxCell)dataGridViewColumn.CellTemplate).TemplateComboBoxColumn = dataGridViewColumn; } return dataGridViewColumn; } @@ -525,7 +525,7 @@ internal void OnItemsCollectionChanged() /// /// /// - public override string ToString() + public override string ToString() { StringBuilder sb = new StringBuilder(64); sb.Append("DataGridViewComboBoxColumn { Name="); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxEditingControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxEditingControl.cs index 01975abb882..3a938c638b4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxEditingControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxEditingControl.cs @@ -151,7 +151,7 @@ private void NotifyDataGridViewOfValueChange() this.dataGridView.NotifyCurrentCellDirty(true); } - protected override void OnSelectedIndexChanged(EventArgs e) + protected override void OnSelectedIndexChanged(EventArgs e) { base.OnSelectedIndexChanged(e); if (this.SelectedIndex != -1) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewContentAlignment.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewContentAlignment.cs index f9f76a50ff7..b8f0abaf1a3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewContentAlignment.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewContentAlignment.cs @@ -13,43 +13,43 @@ public enum DataGridViewContentAlignment /// on the left. /// TopLeft = 0x001, - + /// /// Content is vertically aligned at the top, and horizontally aligned /// at the center. /// TopCenter = 0x002, - + /// /// Content is vertically aligned at the top, and horizontally aligned /// on the right. /// TopRight = 0x004, - + /// /// Content is vertically aligned in the middle, and horizontally aligned /// on the left. /// MiddleLeft = 0x010, - + /// /// Content is vertically aligned in the middle, and horizontally aligned /// at the center. /// MiddleCenter = 0x020, - + /// /// Content is vertically aligned in the middle, and horizontally aligned /// on the right. /// MiddleRight = 0x040, - + /// /// Content is vertically aligned at the bottom, and horizontally aligned /// on the left. /// BottomLeft = 0x100, - + /// /// Content is vertically aligned at the bottom, and horizontally aligned /// at the center. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewDataConnection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewDataConnection.cs index c3152ad8421..85392257541 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewDataConnection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewDataConnection.cs @@ -686,9 +686,9 @@ private void ProcessListChanged(ListChangedEventArgs e) } else { - #if DEBUG +#if DEBUG Debug.Fail("fail in debug builds so we can catch this situation in the check in suites"); - #endif // DEBUG +#endif // DEBUG throw new InvalidOperationException(); } break; @@ -805,7 +805,7 @@ private void currencyManager_PositionChanged(object sender, EventArgs e) return; } - + this.dataConnectionState[DATACONNECTIONSTATE_positionChangingInCurrencyManager] = true; try @@ -1077,7 +1077,7 @@ private void GetSortingInformationFromBackend(out PropertyDescriptor sortPropert // Go thru the IBindingListView which offers the entire list of sorted columns // and pick the first one as the SortedColumn. ListSortDescriptionCollection sorts = iblv.SortDescriptions; - if (sorts != null && + if (sorts != null && sorts.Count > 0 && sorts[0].PropertyDescriptor != null) { @@ -1208,7 +1208,7 @@ public void SetDataConnection(object dataSource, string dataMember) public string GetError(int rowIndex) { IDataErrorInfo errInfo = null; - try + try { errInfo = this.currencyManager[rowIndex] as IDataErrorInfo; } @@ -1218,7 +1218,7 @@ public string GetError(int rowIndex) { throw; } - DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs(exception, -1 /*columnIndex*/, rowIndex, + DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs(exception, -1 /*columnIndex*/, rowIndex, DataGridViewDataErrorContexts.Display); this.owner.OnDataErrorInternal(dgvdee); if (dgvdee.ThrowException) @@ -1304,7 +1304,7 @@ public void MatchCurrencyManagerPosition(bool scrollIntoView, bool clearSelectio // all the properties in the currency manager should be either Browsable(false) or point to sub lists if (this.props != null) { - for (int i = 0; i < this.props.Count; i ++) + for (int i = 0; i < this.props.Count; i++) { Debug.Assert(!props[i].IsBrowsable || typeof(IList).IsAssignableFrom(props[i].PropertyType), "if the DGV does not have any columns then the properties in the currency manager should be Browsable(false) or point to sub lists"); } @@ -1365,7 +1365,7 @@ public void MatchCurrencyManagerPosition(bool scrollIntoView, bool clearSelectio // Scroll target cell into view first. if ((scrollIntoView && !this.owner.ScrollIntoView(columnIndex, rowIndex, true)) || - (columnIndex < this.owner.Columns.Count && rowIndex < this.owner.Rows.Count && + (columnIndex < this.owner.Columns.Count && rowIndex < this.owner.Rows.Count && !this.owner.SetAndSelectCurrentCellAddress(columnIndex, rowIndex, true, /*setAnchorCellAddress*/ false, /*validateCurrentCell*/ @@ -1385,7 +1385,7 @@ public void CancelRowEdit(bool restoreRow, bool addNewFinished) try { object currentItem = null; - if (this.currencyManager.Position >= 0 && this.currencyManager.Position < this.currencyManager.List.Count ) + if (this.currencyManager.Position >= 0 && this.currencyManager.Position < this.currencyManager.List.Count) { currentItem = this.currencyManager.Current; } @@ -1397,7 +1397,7 @@ public void CancelRowEdit(bool restoreRow, bool addNewFinished) // So, if the current item inside the currency manager did not change, we have to start a new transaction. // (If the current item inside the currency manager changed, then the currency manager would have already started a new transaction). IEditableObject editableObject = null; - if (this.currencyManager.Position >= 0 && this.currencyManager.Position < this.currencyManager.List.Count ) + if (this.currencyManager.Position >= 0 && this.currencyManager.Position < this.currencyManager.List.Count) { editableObject = this.currencyManager.Current as IEditableObject; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewEditingCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewEditingCell.cs index f4016ceca8d..ba5a7224d58 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewEditingCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewEditingCell.cs @@ -6,7 +6,7 @@ namespace System.Windows.Forms { using System; using System.Diagnostics.CodeAnalysis; - + public interface IDataGridViewEditingCell { [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewElement.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewElement.cs index 8e63b5905d1..c7148a99618 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewElement.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewElement.cs @@ -10,7 +10,7 @@ namespace System.Windows.Forms /// /// Identifies an element in the dataGridView (base class for TCell, TBand, TRow, TColumn. /// - public class DataGridViewElement + public class DataGridViewElement { private DataGridViewElementStates _state; // enabled frozen readOnly resizable selected visible private DataGridView _dataGridView; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewEventHandlers.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewEventHandlers.cs index 2e45020efcc..1848a788579 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewEventHandlers.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewEventHandlers.cs @@ -35,7 +35,7 @@ namespace System.Windows.Forms [SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances")] public delegate void DataGridViewCellMouseEventHandler(object sender, DataGridViewCellMouseEventArgs e); - + [SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances")] public delegate void DataGridViewCellPaintingEventHandler(object sender, DataGridViewCellPaintingEventArgs e); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHeaderCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHeaderCell.cs index 6c6db6b70ef..310a8465765 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHeaderCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHeaderCell.cs @@ -41,7 +41,7 @@ protected ButtonState ButtonState int buttonState = this.Properties.GetInteger(PropButtonState, out found); if (found) { - return (ButtonState) buttonState; + return (ButtonState)buttonState; } return ButtonState.Normal; } @@ -57,17 +57,19 @@ private ButtonState ButtonStatePrivate Debug.Assert(Enum.IsDefined(typeof(ButtonState), value)); if (this.ButtonState != value) { - this.Properties.SetInteger(PropButtonState, (int) value); + this.Properties.SetInteger(PropButtonState, (int)value); } } } - protected override void Dispose(bool disposing) { - if (FlipXPThemesBitmap != null && disposing) { - FlipXPThemesBitmap.Dispose(); - } - base.Dispose(disposing); - + protected override void Dispose(bool disposing) + { + if (FlipXPThemesBitmap != null && disposing) + { + FlipXPThemesBitmap.Dispose(); + } + base.Dispose(disposing); + } [ @@ -223,7 +225,7 @@ public override Type ValueType { get { - Type valueType = (Type) this.Properties.GetObject(PropValueType); + Type valueType = (Type)this.Properties.GetObject(PropValueType); if (valueType != null) { return valueType; @@ -256,7 +258,7 @@ public override bool Visible if (this.OwningColumn != null) { // column header cell - return this.OwningColumn.Visible && + return this.OwningColumn.Visible && (this.DataGridView == null || this.DataGridView.ColumnHeadersVisible); } @@ -314,7 +316,7 @@ public override DataGridViewElementStates GetInheritedState(int rowIndex) if (this.OwningRow != null) { // row header cell - if ((this.DataGridView == null && rowIndex != -1) || + if ((this.DataGridView == null && rowIndex != -1) || (this.DataGridView != null && (rowIndex < 0 || rowIndex >= this.DataGridView.Rows.Count))) { throw new ArgumentException(string.Format(SR.InvalidArgument, nameof(rowIndex), rowIndex)); @@ -536,7 +538,7 @@ protected override void OnMouseDown(DataGridViewCellMouseEventArgs e) { return; } - if (e.Button == MouseButtons.Left && + if (e.Button == MouseButtons.Left && this.DataGridView.ApplyVisualStylesToHeaderCells && !this.DataGridView.ResizingOperationAboutToStart) { @@ -595,11 +597,11 @@ protected override void OnMouseUp(DataGridViewCellMouseEventArgs e) } } - protected override void Paint(Graphics graphics, + protected override void Paint(Graphics graphics, Rectangle clipBounds, - Rectangle cellBounds, - int rowIndex, - DataGridViewElementStates dataGridViewElementState, + Rectangle cellBounds, + int rowIndex, + DataGridViewElementStates dataGridViewElementState, object value, object formattedValue, string errorText, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHitTestCloseEdge.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHitTestCloseEdge.cs index 6412aee8f5c..49167c5e1ff 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHitTestCloseEdge.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHitTestCloseEdge.cs @@ -4,12 +4,12 @@ namespace System.Windows.Forms { - internal enum DataGridViewHitTestTypeCloseEdge + internal enum DataGridViewHitTestTypeCloseEdge { - None = 0, - Left = 1, - Right = 2, - Top = 3, + None = 0, + Left = 1, + Right = 2, + Top = 3, Bottom = 4 } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHitTestInfo.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHitTestInfo.cs index 0687ffe8ccc..fcc0a94bf48 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHitTestInfo.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHitTestInfo.cs @@ -8,7 +8,7 @@ namespace System.Windows.Forms { public partial class DataGridView { - public sealed class HitTestInfo + public sealed class HitTestInfo { internal DataGridViewHitTestType type = DataGridViewHitTestType.None; //internal DataGridViewHitTestTypeCloseEdge edge = DataGridViewHitTestTypeCloseEdge.None; @@ -42,7 +42,7 @@ internal HitTestInfo() /// public int ColumnIndex { - get + get { return this.col; } @@ -54,7 +54,7 @@ public int ColumnIndex /// public int RowIndex { - get + get { return this.row; } @@ -65,7 +65,7 @@ public int RowIndex /// public int ColumnX { - get + get { return this.colStart; } @@ -76,7 +76,7 @@ public int ColumnX /// public int RowY { - get + get { return this.rowStart; } @@ -88,7 +88,7 @@ public int RowY /// public DataGridViewHitTestType Type { - get + get { return this.type; } @@ -97,14 +97,14 @@ public DataGridViewHitTestType Type /// /// Indicates whether two objects are identical. /// - public override bool Equals(object value) + public override bool Equals(object value) { HitTestInfo hti = value as HitTestInfo; - if (hti != null) + if (hti != null) { return (this.type == hti.type && - this.row == hti.row && - this.col == hti.col); + this.row == hti.row && + this.col == hti.col); } return false; } @@ -117,7 +117,7 @@ public override bool Equals(object value) /// /// Gets the type, column number and row number. /// - public override string ToString() + public override string ToString() { return "{ Type:" + type.ToString() + ", Column:" + col.ToString(CultureInfo.CurrentCulture) + ", Row:" + row.ToString(CultureInfo.CurrentCulture) + " }"; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageCell.cs index 1e77aa4aa78..fc294850071 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageCell.cs @@ -64,13 +64,13 @@ public override object DefaultNewRowValue DefaultValue("") ] public string Description - { + { get { object description = this.Properties.GetObject(PropImageCellDescription); if (description != null) { - return (string) description; + return (string)description; } return string.Empty; } @@ -152,7 +152,7 @@ public DataGridViewImageCellLayout ImageLayout // Sequential enum. Valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridViewImageCellLayout.NotSet, (int)DataGridViewImageCellLayout.Zoom)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewImageCellLayout)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewImageCellLayout)); } if (this.ImageLayout != value) { @@ -211,15 +211,15 @@ internal bool ValueIsIconInternal { if (value) { - this.flags |= (byte) DATAGRIDVIEWIMAGECELL_valueIsIcon; + this.flags |= (byte)DATAGRIDVIEWIMAGECELL_valueIsIcon; } else { - this.flags = (byte) (this.flags & ~DATAGRIDVIEWIMAGECELL_valueIsIcon); + this.flags = (byte)(this.flags & ~DATAGRIDVIEWIMAGECELL_valueIsIcon); } - if (this.DataGridView != null && - this.RowIndex != -1 && - this.DataGridView.NewRowIndex == this.RowIndex && + if (this.DataGridView != null && + this.RowIndex != -1 && + this.DataGridView.NewRowIndex == this.RowIndex && !this.DataGridView.VirtualMode) { Debug.Assert(this.DataGridView.AllowUserToAddRowsInternal); @@ -401,8 +401,8 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC return errBounds; } - - + + protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, @@ -535,7 +535,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl preferredSize = new Size(1, 0); } } - else + else { if (img != null) { @@ -725,15 +725,15 @@ private Rectangle ImgBounds(Rectangle bounds, int imgWidth, int imgHeight, DataG return imgBounds; } - protected override void Paint(Graphics graphics, + protected override void Paint(Graphics graphics, Rectangle clipBounds, - Rectangle cellBounds, - int rowIndex, + Rectangle cellBounds, + int rowIndex, DataGridViewElementStates elementState, object value, object formattedValue, - string errorText, - DataGridViewCellStyle cellStyle, + string errorText, + DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { @@ -742,14 +742,14 @@ protected override void Paint(Graphics graphics, throw new ArgumentNullException(nameof(cellStyle)); } - PaintPrivate(graphics, + PaintPrivate(graphics, clipBounds, - cellBounds, - rowIndex, + cellBounds, + rowIndex, elementState, formattedValue, - errorText, - cellStyle, + errorText, + cellStyle, advancedBorderStyle, paintParts, false /*computeContentBounds*/, @@ -765,14 +765,14 @@ protected override void Paint(Graphics graphics, // if computeContentBounds is true then PaintPrivate returns the contentBounds // else if computeErrorIconBounds is true then PaintPrivate returns the errorIconBounds // else it returns Rectangle.Empty; - private Rectangle PaintPrivate(Graphics g, + private Rectangle PaintPrivate(Graphics g, Rectangle clipBounds, - Rectangle cellBounds, - int rowIndex, + Rectangle cellBounds, + int rowIndex, DataGridViewElementStates elementState, object formattedValue, - string errorText, - DataGridViewCellStyle cellStyle, + string errorText, + DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts, bool computeContentBounds, @@ -834,7 +834,7 @@ private Rectangle PaintPrivate(Graphics g, { if (this.OwningColumn is DataGridViewImageColumn) { - imageLayout = ((DataGridViewImageColumn) this.OwningColumn).ImageLayout; + imageLayout = ((DataGridViewImageColumn)this.OwningColumn).ImageLayout; Debug.Assert(imageLayout != DataGridViewImageCellLayout.NotSet); } else @@ -920,11 +920,11 @@ private Rectangle PaintPrivate(Graphics g, } Point ptCurrentCell = this.DataGridView.CurrentCellAddress; - if (paint && - DataGridViewCell.PaintFocus(paintParts) && - ptCurrentCell.X == this.ColumnIndex && + if (paint && + DataGridViewCell.PaintFocus(paintParts) && + ptCurrentCell.X == this.ColumnIndex && ptCurrentCell.Y == rowIndex && - this.DataGridView.ShowFocusCues && + this.DataGridView.ShowFocusCues && this.DataGridView.Focused) { // Draw focus rectangle @@ -964,7 +964,7 @@ public override string ToString() protected class DataGridViewImageCellAccessibleObject : DataGridViewCellAccessibleObject { - public DataGridViewImageCellAccessibleObject(DataGridViewCell owner) : base (owner) + public DataGridViewImageCellAccessibleObject(DataGridViewCell owner) : base(owner) { } @@ -994,7 +994,7 @@ public override string Description public override string Value { - get + get { return base.Value; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageColumn.cs index 68e133d2cb1..95709117f14 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageColumn.cs @@ -83,7 +83,7 @@ public override DataGridViewCellStyle DefaultCellStyle [ Browsable(true), DefaultValue(""), - SRCategory(nameof(SR.CatAppearance)), + SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.DataGridViewImageColumn_DescriptionDescr)) ] public string Description @@ -165,7 +165,7 @@ private DataGridViewImageCell ImageCellTemplate { get { - return (DataGridViewImageCell) this.CellTemplate; + return (DataGridViewImageCell)this.CellTemplate; } } @@ -247,16 +247,16 @@ public bool ValuesAreIcons } this.DataGridView.OnColumnCommonChange(this.Index); } - - if (value && - this.DefaultCellStyle.NullValue is Bitmap && - (Bitmap) this.DefaultCellStyle.NullValue == DataGridViewImageCell.ErrorBitmap) + + if (value && + this.DefaultCellStyle.NullValue is Bitmap && + (Bitmap)this.DefaultCellStyle.NullValue == DataGridViewImageCell.ErrorBitmap) { this.DefaultCellStyle.NullValue = DataGridViewImageCell.ErrorIcon; } - else if (!value && - this.DefaultCellStyle.NullValue is Icon && - (Icon) this.DefaultCellStyle.NullValue == DataGridViewImageCell.ErrorIcon) + else if (!value && + this.DefaultCellStyle.NullValue is Icon && + (Icon)this.DefaultCellStyle.NullValue == DataGridViewImageCell.ErrorIcon) { this.DefaultCellStyle.NullValue = DataGridViewImageCell.ErrorBitmap; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkCell.cs index 54bafa2234c..a758e7f718e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkCell.cs @@ -137,14 +137,14 @@ public LinkBehavior LinkBehavior { return (LinkBehavior)linkBehavior; } - return LinkBehavior.SystemDefault; + return LinkBehavior.SystemDefault; } set { // Sequential enum. Valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(value, (int)value, (int)LinkBehavior.SystemDefault, (int)LinkBehavior.NeverUnderline)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(LinkBehavior)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(LinkBehavior)); } if (value != this.LinkBehavior) { @@ -246,7 +246,7 @@ private LinkState LinkState int linkState = this.Properties.GetInteger(PropLinkCellLinkState, out found); if (found) { - return (LinkState) linkState; + return (LinkState)linkState; } return LinkState.Normal; } @@ -254,7 +254,7 @@ private LinkState LinkState { if (this.LinkState != value) { - this.Properties.SetInteger(PropLinkCellLinkState, (int) value); + this.Properties.SetInteger(PropLinkCellLinkState, (int)value); } } } @@ -465,7 +465,7 @@ public override Type ValueType public override object Clone() { DataGridViewLinkCell dataGridViewCell; - Type thisType = this.GetType (); + Type thisType = this.GetType(); if (thisType == cellType) //performance improvement { @@ -655,39 +655,39 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl switch (freeDimension) { case DataGridViewFreeDimension.Width: - { - int maxHeight = constraintSize.Height - borderAndPaddingHeights - DATAGRIDVIEWLINKCELL_verticalTextMarginTop - DATAGRIDVIEWLINKCELL_verticalTextMarginBottom; - if ((cellStyle.Alignment & anyBottom) != 0) { - maxHeight--; + int maxHeight = constraintSize.Height - borderAndPaddingHeights - DATAGRIDVIEWLINKCELL_verticalTextMarginTop - DATAGRIDVIEWLINKCELL_verticalTextMarginBottom; + if ((cellStyle.Alignment & anyBottom) != 0) + { + maxHeight--; + } + preferredSize = new Size(DataGridViewCell.MeasureTextWidth(graphics, + formattedString, + cellStyle.Font, + Math.Max(1, maxHeight), + flags), + 0); + break; } - preferredSize = new Size(DataGridViewCell.MeasureTextWidth(graphics, - formattedString, - cellStyle.Font, - Math.Max(1, maxHeight), - flags), - 0); - break; - } case DataGridViewFreeDimension.Height: - { - preferredSize = new Size(0, - DataGridViewCell.MeasureTextHeight(graphics, - formattedString, - cellStyle.Font, - Math.Max(1, constraintSize.Width - borderAndPaddingWidths - DATAGRIDVIEWLINKCELL_horizontalTextMarginLeft - DATAGRIDVIEWLINKCELL_horizontalTextMarginRight), - flags)); - break; - } + { + preferredSize = new Size(0, + DataGridViewCell.MeasureTextHeight(graphics, + formattedString, + cellStyle.Font, + Math.Max(1, constraintSize.Width - borderAndPaddingWidths - DATAGRIDVIEWLINKCELL_horizontalTextMarginLeft - DATAGRIDVIEWLINKCELL_horizontalTextMarginRight), + flags)); + break; + } default: - { - preferredSize = DataGridViewCell.MeasureTextPreferredSize(graphics, - formattedString, - cellStyle.Font, - 5.0F, - flags); - break; - } + { + preferredSize = DataGridViewCell.MeasureTextPreferredSize(graphics, + formattedString, + cellStyle.Font, + 5.0F, + flags); + break; + } } } else @@ -695,22 +695,22 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl switch (freeDimension) { case DataGridViewFreeDimension.Width: - { - preferredSize = new Size(DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags).Width, - 0); - break; - } + { + preferredSize = new Size(DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags).Width, + 0); + break; + } case DataGridViewFreeDimension.Height: - { - preferredSize = new Size(0, - DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags).Height); - break; - } + { + preferredSize = new Size(0, + DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags).Height); + break; + } default: - { - preferredSize = DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags); - break; - } + { + preferredSize = DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags); + break; + } } } @@ -742,12 +742,12 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl protected override object GetValue(int rowIndex) { if (this.UseColumnTextForLinkValue && - this.DataGridView != null && - this.DataGridView.NewRowIndex != rowIndex && - this.OwningColumn != null && + this.DataGridView != null && + this.DataGridView.NewRowIndex != rowIndex && + this.OwningColumn != null && this.OwningColumn is DataGridViewLinkColumn) { - return ((DataGridViewLinkColumn) this.OwningColumn).Text; + return ((DataGridViewLinkColumn)this.OwningColumn).Text; } return base.GetValue(rowIndex); } @@ -905,10 +905,10 @@ protected override void OnMouseUp(DataGridViewCellMouseEventArgs e) } } - protected override void Paint(Graphics graphics, + protected override void Paint(Graphics graphics, Rectangle clipBounds, - Rectangle cellBounds, - int rowIndex, + Rectangle cellBounds, + int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, @@ -922,14 +922,14 @@ protected override void Paint(Graphics graphics, throw new ArgumentNullException(nameof(cellStyle)); } - PaintPrivate(graphics, + PaintPrivate(graphics, clipBounds, - cellBounds, + cellBounds, rowIndex, cellState, formattedValue, - errorText, - cellStyle, + errorText, + cellStyle, advancedBorderStyle, paintParts, false /*computeContentBounds*/, @@ -948,7 +948,7 @@ protected override void Paint(Graphics graphics, // else it returns Rectangle.Empty; private Rectangle PaintPrivate(Graphics g, Rectangle clipBounds, - Rectangle cellBounds, + Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object formattedValue, @@ -1104,11 +1104,11 @@ private Rectangle PaintPrivate(Graphics g, else if (paint || computeContentBounds) { if (cellCurrent && - this.DataGridView.ShowFocusCues && - this.DataGridView.Focused && - DataGridViewCell.PaintFocus(paintParts) && - paint && - valBounds.Width > 0 && + this.DataGridView.ShowFocusCues && + this.DataGridView.Focused && + DataGridViewCell.PaintFocus(paintParts) && + paint && + valBounds.Width > 0 && valBounds.Height > 0) { // Draw focus rectangle @@ -1139,7 +1139,7 @@ public override string ToString() protected class DataGridViewLinkCellAccessibleObject : DataGridViewCellAccessibleObject { - public DataGridViewLinkCellAccessibleObject(DataGridViewCell owner) : base (owner) + public DataGridViewLinkCellAccessibleObject(DataGridViewCell owner) : base(owner) { } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkColumn.cs index ebec78a0816..c22c4df69f7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkColumn.cs @@ -69,7 +69,7 @@ private bool ShouldSerializeActiveLinkColor() return !this.ActiveLinkColor.Equals(LinkUtilities.IEActiveLinkColor); } - + [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs index e19a1d3e585..89dc531dcd2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs @@ -10,7 +10,7 @@ namespace System.Windows.Forms using System; using System.Diagnostics.CodeAnalysis; using System.Collections; - using System.Windows.Forms.Design; + using System.Windows.Forms.Design; using System.ComponentModel.Design; using System.Drawing; using System.Windows.Forms.ComponentModel; @@ -87,7 +87,7 @@ internal void AddNewRow(bool createdByEditing) ] public virtual DataGridViewAdvancedBorderStyle AdjustColumnHeaderBorderStyle(DataGridViewAdvancedBorderStyle dataGridViewAdvancedBorderStyleInput, DataGridViewAdvancedBorderStyle dataGridViewAdvancedBorderStylePlaceholder, - bool isFirstDisplayedColumn, + bool isFirstDisplayedColumn, bool isLastVisibleColumn) { if (this.ApplyVisualStylesToHeaderCells) @@ -334,7 +334,7 @@ private bool AdjustExpandingColumn(DataGridViewColumn dataGridViewColumn, int ro Debug.Assert(this.noAutoSizeCount > 0); this.noAutoSizeCount--; } - + return ret; } @@ -372,7 +372,7 @@ private int AdjustExpandingRow(int rowIndex, int columnIndex, bool fixedWidth) // IntPtr handle = this.Handle; // Force creation of control's handle because for databound grids, handle creation wipes out and recreates the columns/rows. int width = 0; DataGridViewCell dataGridViewCell; - if (columnIndex > -1 && (((DataGridViewAutoSizeRowsModeInternal) autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0) + if (columnIndex > -1 && (((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0) { dataGridViewCell = this.Rows.SharedRow(rowIndex).Cells[columnIndex]; if (fixedWidth) @@ -383,7 +383,7 @@ private int AdjustExpandingRow(int rowIndex, int columnIndex, bool fixedWidth) else { Debug.Assert(columnIndex == -1); - Debug.Assert((((DataGridViewAutoSizeRowsModeInternal) autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) != 0); + Debug.Assert((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) != 0); dataGridViewCell = this.Rows.SharedRow(rowIndex).HeaderCell; if (fixedWidth) { @@ -423,8 +423,8 @@ private int AdjustExpandingRow(int rowIndex, int columnIndex, bool fixedWidth) [SuppressMessage("Microsoft.Performance", "CA1817:DoNotCallPropertiesThatCloneValuesInLoops")] // Can't cache DataGridViewRow object because rowIndex is changing in loop. private void AdjustExpandingRows(int columnIndex, bool fixedWidth) { - if ((((DataGridViewAutoSizeRowsModeInternal) this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0 || - ((((DataGridViewAutoSizeRowsModeInternal) this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) != 0 && this.RowHeadersVisible)) + if ((((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0 || + ((((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) != 0 && this.RowHeadersVisible)) { if (!this.IsHandleCreated) { @@ -439,7 +439,7 @@ private void AdjustExpandingRows(int columnIndex, bool fixedWidth) this.inBulkPaintCount++; try { - if ((((DataGridViewAutoSizeRowsModeInternal) this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllRows) != 0) + if ((((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllRows) != 0) { this.inBulkLayoutCount++; try @@ -450,7 +450,7 @@ private void AdjustExpandingRows(int columnIndex, bool fixedWidth) { int width = 0; DataGridViewCell dataGridViewCell; - if (columnIndex > -1 && (((DataGridViewAutoSizeRowsModeInternal) this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0) + if (columnIndex > -1 && (((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0) { dataGridViewCell = this.Rows.SharedRow(rowIndex).Cells[columnIndex]; if (fixedWidth) @@ -461,7 +461,7 @@ private void AdjustExpandingRows(int columnIndex, bool fixedWidth) else { //Debug.Assert(columnIndex == -1); - Debug.Assert((((DataGridViewAutoSizeRowsModeInternal) this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) != 0); + Debug.Assert((((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) != 0); dataGridViewCell = this.Rows.SharedRow(rowIndex).HeaderCell; if (fixedWidth) { @@ -492,7 +492,7 @@ private void AdjustExpandingRows(int columnIndex, bool fixedWidth) } else { - Debug.Assert((((DataGridViewAutoSizeRowsModeInternal) this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.DisplayedRows) != 0); + Debug.Assert((((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.DisplayedRows) != 0); int displayHeight = this.layout.Data.Height; int cy = 0; @@ -657,7 +657,7 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid { if (dataGridViewColumnTmp.Index != dataGridViewColumn.Index && dataGridViewColumnTmp.Visible && - dataGridViewColumnTmp.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill && + dataGridViewColumnTmp.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill && dataGridViewColumnTmp.DesiredFillWidth != -1) { dataGridViewColumnTmp.UsedFillWeight = Math.Max(dataGridViewColumnTmp.FillWeight * usedWeightSumNoneMinimal / weightSumNoneMinimal, @@ -680,7 +680,7 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid } } } - #if DEBUG +#if DEBUG float weightSumDbg = 0F; foreach (DataGridViewColumn dataGridViewColumnTmp in this.Columns) { @@ -691,7 +691,7 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid } } Debug.Assert(Math.Abs(weightSum - weightSumDbg) < 1.0F); - #endif +#endif } else { @@ -846,7 +846,7 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid } } } - #if DEBUG +#if DEBUG float weightSumDbg = 0F; foreach (DataGridViewColumn dataGridViewColumnTmp in this.Columns) { @@ -857,7 +857,7 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid } } Debug.Assert(Math.Abs(weightSum - weightSumDbg) < 1.0F); - #endif +#endif } // UsedFillWeight properties are up-to-date @@ -939,9 +939,9 @@ private bool AdjustFillingColumns() availableWidth -= SystemInformation.VerticalScrollBarWidth; } } - + int columnEntry; - + if (availableWidth <= requiredWidthSum) { // All auto filled columns need to take their minimum width. If (availableWidth < requiredWidthSum) a horizontal scrollbar appears. @@ -1265,14 +1265,14 @@ private bool AdjustFillingColumns() private void AdjustShrinkingRows(DataGridViewAutoSizeRowsMode autoSizeRowsMode, bool fixedWidth, bool internalAutosizing) { - if ((((DataGridViewAutoSizeRowsModeInternal) autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0 || - ((((DataGridViewAutoSizeRowsModeInternal) autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) != 0 && this.RowHeadersVisible)) + if ((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0 || + ((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) != 0 && this.RowHeadersVisible)) { // Switch to batch operation this.inBulkPaintCount++; try { - if ((((DataGridViewAutoSizeRowsModeInternal) autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllRows) != 0) + if ((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllRows) != 0) { // Very expensive processing - the developer should avoid this scenario. this.inBulkLayoutCount++; @@ -1292,7 +1292,7 @@ private void AdjustShrinkingRows(DataGridViewAutoSizeRowsMode autoSizeRowsMode, } else { - Debug.Assert((((DataGridViewAutoSizeRowsModeInternal) autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.DisplayedRows) != 0); + Debug.Assert((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.DisplayedRows) != 0); int displayHeight = this.layout.Data.Height; int cy = 0; @@ -1310,7 +1310,7 @@ private void AdjustShrinkingRows(DataGridViewAutoSizeRowsMode autoSizeRowsMode, int cyFrozen = cy; int oldFirstVisibleScrollingRow = this.displayedBandsInfo.FirstDisplayedScrollingRow; rowIndex = oldFirstVisibleScrollingRow; - while (rowIndex != -1 && + while (rowIndex != -1 && cy < displayHeight && oldFirstVisibleScrollingRow == this.displayedBandsInfo.FirstDisplayedScrollingRow) { @@ -1351,7 +1351,7 @@ private void AdjustShrinkingRows(DataGridViewAutoSizeRowsMode autoSizeRowsMode, } // Does not seem to be a valid fxcop violation report. Contacting fxcop team to double-check. - [SuppressMessage("Microsoft.Performance", "CA1817:DoNotCallPropertiesThatCloneValuesInLoops")] + [SuppressMessage("Microsoft.Performance", "CA1817:DoNotCallPropertiesThatCloneValuesInLoops")] public bool AreAllCellsSelected(bool includeInvisibleCells) { if (this.Columns.Count == 0 && this.Rows.Count == 0) @@ -1370,103 +1370,103 @@ public bool AreAllCellsSelected(bool includeInvisibleCells) switch (this.SelectionMode) { case DataGridViewSelectionMode.CellSelect: - { - allCellsSelected = this.individualSelectedCells.Count == this.Columns.Count * this.Rows.Count; - if (allCellsSelected || includeInvisibleCells) - { - return allCellsSelected; - } - else { - for (int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); - rowIndex != -1; - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) + allCellsSelected = this.individualSelectedCells.Count == this.Columns.Count * this.Rows.Count; + if (allCellsSelected || includeInvisibleCells) { - dataGridViewRow = this.Rows[rowIndex]; // unshares this row - - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); - while (dataGridViewColumn != null) + return allCellsSelected; + } + else + { + for (int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + rowIndex != -1; + rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) { - if (!dataGridViewRow.Cells[dataGridViewColumn.Index].Selected) + dataGridViewRow = this.Rows[rowIndex]; // unshares this row + + DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + while (dataGridViewColumn != null) { - return false; + if (!dataGridViewRow.Cells[dataGridViewColumn.Index].Selected) + { + return false; + } + dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + DataGridViewElementStates.Visible, + DataGridViewElementStates.None); } - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, - DataGridViewElementStates.Visible, - DataGridViewElementStates.None); } + return true; } - return true; } - } case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: - { - allCellsSelected = this.selectedBandIndexes.Count * this.Rows.Count + this.individualSelectedCells.Count == this.Columns.Count * this.Rows.Count; - if (allCellsSelected || includeInvisibleCells) - { - return allCellsSelected; - } - else { - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); - while (dataGridViewColumn != null) + allCellsSelected = this.selectedBandIndexes.Count * this.Rows.Count + this.individualSelectedCells.Count == this.Columns.Count * this.Rows.Count; + if (allCellsSelected || includeInvisibleCells) + { + return allCellsSelected; + } + else { - if (!this.selectedBandIndexes.Contains(dataGridViewColumn.Index)) + DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + while (dataGridViewColumn != null) { - for (int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); - rowIndex != -1; - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) + if (!this.selectedBandIndexes.Contains(dataGridViewColumn.Index)) { - dataGridViewRow = this.Rows[rowIndex]; // unshares this row - if (!dataGridViewRow.Cells[dataGridViewColumn.Index].Selected) + for (int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + rowIndex != -1; + rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) { - return false; + dataGridViewRow = this.Rows[rowIndex]; // unshares this row + if (!dataGridViewRow.Cells[dataGridViewColumn.Index].Selected) + { + return false; + } } } + dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + DataGridViewElementStates.Visible, + DataGridViewElementStates.None); } - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, - DataGridViewElementStates.Visible, - DataGridViewElementStates.None); + return true; } - return true; } - } case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: - { - allCellsSelected = this.selectedBandIndexes.Count * this.Columns.Count + this.individualSelectedCells.Count == this.Columns.Count * this.Rows.Count; - if (allCellsSelected || includeInvisibleCells) - { - return allCellsSelected; - } - else { - for (int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); - rowIndex != -1; - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) + allCellsSelected = this.selectedBandIndexes.Count * this.Columns.Count + this.individualSelectedCells.Count == this.Columns.Count * this.Rows.Count; + if (allCellsSelected || includeInvisibleCells) { - Debug.Assert(this.selectedBandIndexes.Contains(rowIndex) == - ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) != 0)); - if ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) == 0) + return allCellsSelected; + } + else + { + for (int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + rowIndex != -1; + rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) { - dataGridViewRow = this.Rows[rowIndex]; // unshares this row - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); - while (dataGridViewColumn != null) + Debug.Assert(this.selectedBandIndexes.Contains(rowIndex) == + ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) != 0)); + if ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) == 0) { - if (!dataGridViewRow.Cells[dataGridViewColumn.Index].Selected) + dataGridViewRow = this.Rows[rowIndex]; // unshares this row + DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + while (dataGridViewColumn != null) { - return false; + if (!dataGridViewRow.Cells[dataGridViewColumn.Index].Selected) + { + return false; + } + dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + DataGridViewElementStates.Visible, + DataGridViewElementStates.None); } - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, - DataGridViewElementStates.Visible, - DataGridViewElementStates.None); } } + return true; } - return true; } - } } Debug.Fail("DataGridView.AreAllCellsSelected - Shouldn't reach this code"); return false; @@ -1518,9 +1518,9 @@ private void AutoGenerateDataBoundColumns(DataGridViewColumn[] boundColumns) // We only clone columns which are data bound w/ the new DataSource/DataMember combination. if (this.dataConnection != null && this.dataConnection.BoundColumnIndex(dataGridViewCols[i].DataPropertyName) != -1) { - clonedColumns[clonedColumnsCount] = (DataGridViewColumn) dataGridViewCols[i].Clone(); + clonedColumns[clonedColumnsCount] = (DataGridViewColumn)dataGridViewCols[i].Clone(); clonedColumns[clonedColumnsCount].DisplayIndex = dataGridViewCols[i].DisplayIndex; - clonedColumnsCount ++; + clonedColumnsCount++; } } } @@ -1535,7 +1535,7 @@ private void AutoGenerateDataBoundColumns(DataGridViewColumn[] boundColumns) } else { - i++; + i++; } } @@ -1560,14 +1560,14 @@ private void AutoGenerateDataBoundColumns(DataGridViewColumn[] boundColumns) // 4. Add new columns for the Fields which were not data bound previously ( ie, for fields which do not have a clone ). if (boundColumns != null) { - for (int j = 0; j < boundColumns.Length; j ++) + for (int j = 0; j < boundColumns.Length; j++) { if (boundColumns[j] != null && boundColumns[j].IsBrowsableInternal) { bool addNewColumn = true; // Go thru the list of cloned columns and see if there is another column w/ the same data property name. int clonedColIndex = 0; - for (; clonedColIndex < clonedColumnsCount; clonedColIndex ++) + for (; clonedColIndex < clonedColumnsCount; clonedColIndex++) { if (finalClonedColumns[clonedColIndex] != null && string.Compare(finalClonedColumns[clonedColIndex].DataPropertyName, @@ -1595,14 +1595,14 @@ private void AutoGenerateDataBoundColumns(DataGridViewColumn[] boundColumns) } } } - #if DEBUG +#if DEBUG else { // If there are no data bound columns then there are no cloned columns either. Debug.Assert(finalClonedColumns.Length == 0); Debug.Assert(clonedColumnsCount == 0); } - #endif // DEBUG +#endif // DEBUG // 5. Add remaining cloned columns. if (clonedColumnsCount > 0) @@ -1628,7 +1628,7 @@ private bool AutoResizeAllVisibleColumnsInternal(DataGridViewAutoSizeColumnCrite DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); while (dataGridViewColumn != null) { - DataGridViewAutoSizeColumnCriteriaInternal inheritedAutoSizeColumnCriteria = (DataGridViewAutoSizeColumnCriteriaInternal) dataGridViewColumn.InheritedAutoSizeMode; + DataGridViewAutoSizeColumnCriteriaInternal inheritedAutoSizeColumnCriteria = (DataGridViewAutoSizeColumnCriteriaInternal)dataGridViewColumn.InheritedAutoSizeMode; DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaFiltered = (inheritedAutoSizeColumnCriteria & autoSizeColumnCriteriaFilter); if (autoSizeColumnCriteriaFiltered != 0) { @@ -1659,7 +1659,7 @@ protected void AutoResizeColumn(int columnIndex, DataGridViewAutoSizeColumnMode { throw new ArgumentException(string.Format(SR.DataGridView_NeedColumnAutoSizingCriteria, "autoSizeColumnMode")); } - + switch (autoSizeColumnMode) { case DataGridViewAutoSizeColumnMode.NotSet: @@ -1685,7 +1685,7 @@ protected void AutoResizeColumn(int columnIndex, DataGridViewAutoSizeColumnMode throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAutoSizeInvisibleColumnHeader)); } - AutoResizeColumnInternal(columnIndex, (DataGridViewAutoSizeColumnCriteriaInternal) autoSizeColumnMode, fixedHeight); + AutoResizeColumnInternal(columnIndex, (DataGridViewAutoSizeColumnCriteriaInternal)autoSizeColumnMode, fixedHeight); } public void AutoResizeColumnHeadersHeight() @@ -1863,7 +1863,7 @@ private bool AutoResizeColumnInternal(int columnIndex, DataGridViewAutoSizeColum // IntPtr handle = this.Handle; // Force creation of control's handle because for databound grids, handle creation wipes out and recreates the columns. // Note: Even none-resizable column can programmatically be resized. DataGridViewColumn dataGridViewColumn = this.Columns[columnIndex]; - int preferredColumnWidth = dataGridViewColumn.GetPreferredWidth((DataGridViewAutoSizeColumnMode) autoSizeColumnCriteriaInternal, fixedHeight); + int preferredColumnWidth = dataGridViewColumn.GetPreferredWidth((DataGridViewAutoSizeColumnMode)autoSizeColumnCriteriaInternal, fixedHeight); if (preferredColumnWidth < dataGridViewColumn.MinimumThickness) { preferredColumnWidth = dataGridViewColumn.MinimumThickness; @@ -1928,9 +1928,9 @@ protected void AutoResizeRow(int rowIndex, DataGridViewAutoSizeRowMode autoSizeR throw new ArgumentOutOfRangeException(nameof(rowIndex)); } // not using ClientUtils here because it's a flags enum, masking instead. - if (((DataGridViewAutoSizeRowCriteriaInternal) autoSizeRowMode & invalidDataGridViewAutoSizeRowCriteriaInternalMask) != 0) + if (((DataGridViewAutoSizeRowCriteriaInternal)autoSizeRowMode & invalidDataGridViewAutoSizeRowCriteriaInternalMask) != 0) { - throw new InvalidEnumArgumentException(nameof(autoSizeRowMode), (int) autoSizeRowMode, typeof(DataGridViewAutoSizeRowMode)); + throw new InvalidEnumArgumentException(nameof(autoSizeRowMode), (int)autoSizeRowMode, typeof(DataGridViewAutoSizeRowMode)); } if (autoSizeRowMode == DataGridViewAutoSizeRowMode.RowHeader && !this.RowHeadersVisible) { @@ -1949,7 +1949,7 @@ public void AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode rowHea // User can override this if there is a quicker way to determine preferred row headers width protected void AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode rowHeadersWidthSizeMode, - bool fixedColumnHeadersHeight, + bool fixedColumnHeadersHeight, bool fixedRowsHeight) { if (rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing || @@ -1959,11 +1959,11 @@ protected void AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode row } // custom range checking, not using ClientUtils. if (rowHeadersWidthSizeMode < DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders || rowHeadersWidthSizeMode > DataGridViewRowHeadersWidthSizeMode.AutoSizeToFirstHeader) - { - throw new InvalidEnumArgumentException(nameof(rowHeadersWidthSizeMode), (int)rowHeadersWidthSizeMode, typeof(DataGridViewRowHeadersWidthSizeMode)); + { + throw new InvalidEnumArgumentException(nameof(rowHeadersWidthSizeMode), (int)rowHeadersWidthSizeMode, typeof(DataGridViewRowHeadersWidthSizeMode)); } - + if (!this.RowHeadersVisible) { return; @@ -1997,44 +1997,25 @@ protected void AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode row switch (rowHeadersWidthSizeMode) { case DataGridViewRowHeadersWidthSizeMode.AutoSizeToFirstHeader: - { - rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); - if (rowIndex != -1) { - if (fixedRowsHeight) - { - preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndex).HeaderCell.GetPreferredWidth(rowIndex, this.Rows.SharedRow(rowIndex).GetHeight(rowIndex))); - } - else + rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + if (rowIndex != -1) { - preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndex).HeaderCell.GetPreferredSize(rowIndex).Width); + if (fixedRowsHeight) + { + preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndex).HeaderCell.GetPreferredWidth(rowIndex, this.Rows.SharedRow(rowIndex).GetHeight(rowIndex))); + } + else + { + preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndex).HeaderCell.GetPreferredSize(rowIndex).Width); + } } + break; } - break; - } case DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders: - { - int displayHeight = this.layout.Data.Height, cy = 0; - rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); - while (rowIndex != -1 && cy < displayHeight) - { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); - int dataGridViewRowHeight = dataGridViewRow.GetHeight(rowIndex); - cy += dataGridViewRowHeight; - if (fixedRowsHeight) - { - preferredWidth = Math.Max(preferredWidth, dataGridViewRow.HeaderCell.GetPreferredWidth(rowIndex, dataGridViewRowHeight)); - } - else - { - preferredWidth = Math.Max(preferredWidth, dataGridViewRow.HeaderCell.GetPreferredSize(rowIndex).Width); - } - rowIndex = this.Rows.GetNextRow(rowIndex, - DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); - } - if (cy < displayHeight) { - rowIndex = this.displayedBandsInfo.FirstDisplayedScrollingRow; + int displayHeight = this.layout.Data.Height, cy = 0; + rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); while (rowIndex != -1 && cy < displayHeight) { DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); @@ -2048,33 +2029,52 @@ protected void AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode row { preferredWidth = Math.Max(preferredWidth, dataGridViewRow.HeaderCell.GetPreferredSize(rowIndex).Width); } - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); + rowIndex = this.Rows.GetNextRow(rowIndex, + DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + } + if (cy < displayHeight) + { + rowIndex = this.displayedBandsInfo.FirstDisplayedScrollingRow; + while (rowIndex != -1 && cy < displayHeight) + { + DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); + int dataGridViewRowHeight = dataGridViewRow.GetHeight(rowIndex); + cy += dataGridViewRowHeight; + if (fixedRowsHeight) + { + preferredWidth = Math.Max(preferredWidth, dataGridViewRow.HeaderCell.GetPreferredWidth(rowIndex, dataGridViewRowHeight)); + } + else + { + preferredWidth = Math.Max(preferredWidth, dataGridViewRow.HeaderCell.GetPreferredSize(rowIndex).Width); + } + rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); + } } + break; } - break; - } case DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders: - { - for (rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); - rowIndex != -1; - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) { - if (fixedRowsHeight) - { - preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndex).HeaderCell.GetPreferredWidth(rowIndex, this.Rows.SharedRow(rowIndex).GetHeight(rowIndex))); - } - else + for (rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + rowIndex != -1; + rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) { - preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndex).HeaderCell.GetPreferredSize(rowIndex).Width); + if (fixedRowsHeight) + { + preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndex).HeaderCell.GetPreferredWidth(rowIndex, this.Rows.SharedRow(rowIndex).GetHeight(rowIndex))); + } + else + { + preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndex).HeaderCell.GetPreferredSize(rowIndex).Width); + } } + break; } - break; - } default: - { - Debug.Fail("Unexpected rowHeadersWidthSizeMode value in AutoResizeRowHeadersWidth"); - break; - } + { + Debug.Fail("Unexpected rowHeadersWidthSizeMode value in AutoResizeRowHeadersWidth"); + break; + } } if (preferredWidth < minimumRowHeadersWidth) { @@ -2096,13 +2096,13 @@ public void AutoResizeRowHeadersWidth(int rowIndex, DataGridViewRowHeadersWidthS { AutoResizeRowHeadersWidth(rowIndex, rowHeadersWidthSizeMode, - true /*fixedColumnHeadersHeight*/, + true /*fixedColumnHeadersHeight*/, true /*fixedRowHeight*/); } protected void AutoResizeRowHeadersWidth(int rowIndex, DataGridViewRowHeadersWidthSizeMode rowHeadersWidthSizeMode, - bool fixedColumnHeadersHeight, + bool fixedColumnHeadersHeight, bool fixedRowHeight) { if (rowIndex < -1 || rowIndex >= this.Rows.Count) @@ -2114,11 +2114,11 @@ protected void AutoResizeRowHeadersWidth(int rowIndex, { throw new ArgumentException(string.Format(SR.DataGridView_NeedAutoSizingCriteria, "rowHeadersWidthSizeMode")); } - if (rowHeadersWidthSizeMode < DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders || rowHeadersWidthSizeMode > DataGridViewRowHeadersWidthSizeMode.AutoSizeToFirstHeader) + if (rowHeadersWidthSizeMode < DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders || rowHeadersWidthSizeMode > DataGridViewRowHeadersWidthSizeMode.AutoSizeToFirstHeader) { - throw new InvalidEnumArgumentException(nameof(rowHeadersWidthSizeMode), (int)rowHeadersWidthSizeMode, typeof(DataGridViewRowHeadersWidthSizeMode)); + throw new InvalidEnumArgumentException(nameof(rowHeadersWidthSizeMode), (int)rowHeadersWidthSizeMode, typeof(DataGridViewRowHeadersWidthSizeMode)); } - + if (!this.RowHeadersVisible) { return; @@ -2168,44 +2168,25 @@ protected void AutoResizeRowHeadersWidth(int rowIndex, switch (rowHeadersWidthSizeMode) { case DataGridViewRowHeadersWidthSizeMode.AutoSizeToFirstHeader: - { - rowIndexTmp = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); - if (rowIndexTmp != -1) { - if (rowIndex != rowIndexTmp || fixedRowHeight) - { - preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndexTmp).HeaderCell.GetPreferredWidth(rowIndexTmp, this.Rows.SharedRow(rowIndexTmp).GetHeight(rowIndexTmp))); - } - else + rowIndexTmp = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + if (rowIndexTmp != -1) { - preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndexTmp).HeaderCell.GetPreferredSize(rowIndexTmp).Width); + if (rowIndex != rowIndexTmp || fixedRowHeight) + { + preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndexTmp).HeaderCell.GetPreferredWidth(rowIndexTmp, this.Rows.SharedRow(rowIndexTmp).GetHeight(rowIndexTmp))); + } + else + { + preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndexTmp).HeaderCell.GetPreferredSize(rowIndexTmp).Width); + } } + break; } - break; - } case DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders: - { - int displayHeight = this.layout.Data.Height, cy = 0; - rowIndexTmp = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); - while (rowIndexTmp != -1 && cy < displayHeight) - { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndexTmp); - int dataGridViewRowHeight = dataGridViewRow.GetHeight(rowIndexTmp); - cy += dataGridViewRowHeight; - if (rowIndex != rowIndexTmp || fixedRowHeight) - { - preferredWidth = Math.Max(preferredWidth, dataGridViewRow.HeaderCell.GetPreferredWidth(rowIndexTmp, dataGridViewRowHeight)); - } - else - { - preferredWidth = Math.Max(preferredWidth, dataGridViewRow.HeaderCell.GetPreferredSize(rowIndexTmp).Width); - } - rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, - DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); - } - if (cy < displayHeight) { - rowIndexTmp = this.displayedBandsInfo.FirstDisplayedScrollingRow; + int displayHeight = this.layout.Data.Height, cy = 0; + rowIndexTmp = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); while (rowIndexTmp != -1 && cy < displayHeight) { DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndexTmp); @@ -2219,33 +2200,52 @@ protected void AutoResizeRowHeadersWidth(int rowIndex, { preferredWidth = Math.Max(preferredWidth, dataGridViewRow.HeaderCell.GetPreferredSize(rowIndexTmp).Width); } - rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible); + rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, + DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + } + if (cy < displayHeight) + { + rowIndexTmp = this.displayedBandsInfo.FirstDisplayedScrollingRow; + while (rowIndexTmp != -1 && cy < displayHeight) + { + DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndexTmp); + int dataGridViewRowHeight = dataGridViewRow.GetHeight(rowIndexTmp); + cy += dataGridViewRowHeight; + if (rowIndex != rowIndexTmp || fixedRowHeight) + { + preferredWidth = Math.Max(preferredWidth, dataGridViewRow.HeaderCell.GetPreferredWidth(rowIndexTmp, dataGridViewRowHeight)); + } + else + { + preferredWidth = Math.Max(preferredWidth, dataGridViewRow.HeaderCell.GetPreferredSize(rowIndexTmp).Width); + } + rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible); + } } + break; } - break; - } case DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders: - { - for (rowIndexTmp = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); - rowIndexTmp != -1; - rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible)) { - if (rowIndex != rowIndexTmp || fixedRowHeight) - { - preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndexTmp).HeaderCell.GetPreferredWidth(rowIndexTmp, this.Rows.SharedRow(rowIndexTmp).GetHeight(rowIndexTmp))); - } - else + for (rowIndexTmp = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + rowIndexTmp != -1; + rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible)) { - preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndexTmp).HeaderCell.GetPreferredSize(rowIndexTmp).Width); + if (rowIndex != rowIndexTmp || fixedRowHeight) + { + preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndexTmp).HeaderCell.GetPreferredWidth(rowIndexTmp, this.Rows.SharedRow(rowIndexTmp).GetHeight(rowIndexTmp))); + } + else + { + preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndexTmp).HeaderCell.GetPreferredSize(rowIndexTmp).Width); + } } + break; } - break; - } default: - { - Debug.Fail("Unexpected rowHeadersWidthSizeMode value in AutoResizeRowHeadersWidth"); - break; - } + { + Debug.Fail("Unexpected rowHeadersWidthSizeMode value in AutoResizeRowHeadersWidth"); + break; + } } if (preferredWidth < minimumRowHeadersWidth) { @@ -2266,7 +2266,7 @@ protected void AutoResizeRowHeadersWidth(int rowIndex, private void AutoResizeRowInternal(int rowIndex, DataGridViewAutoSizeRowMode autoSizeRowMode, bool fixedWidth, bool internalAutosizing) { Debug.Assert(rowIndex >= 0 && rowIndex < this.Rows.Count); - Debug.Assert(((DataGridViewAutoSizeRowCriteriaInternal) autoSizeRowMode & invalidDataGridViewAutoSizeRowCriteriaInternalMask) == 0); + Debug.Assert(((DataGridViewAutoSizeRowCriteriaInternal)autoSizeRowMode & invalidDataGridViewAutoSizeRowCriteriaInternalMask) == 0); if (!this.IsHandleCreated) { @@ -2335,8 +2335,8 @@ public void AutoResizeRows(DataGridViewAutoSizeRowsMode autoSizeRowsMode) protected void AutoResizeRows(DataGridViewAutoSizeRowsMode autoSizeRowsMode, bool fixedWidth) { - switch (autoSizeRowsMode) - { + switch (autoSizeRowsMode) + { case DataGridViewAutoSizeRowsMode.None: case DataGridViewAutoSizeRowsMode.AllHeaders: case DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders: @@ -2345,8 +2345,8 @@ protected void AutoResizeRows(DataGridViewAutoSizeRowsMode autoSizeRowsMode, boo case DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders: case DataGridViewAutoSizeRowsMode.DisplayedCells: break; - default: - throw new InvalidEnumArgumentException(nameof(autoSizeRowsMode), (int)autoSizeRowsMode, typeof(DataGridViewAutoSizeRowsMode)); + default: + throw new InvalidEnumArgumentException(nameof(autoSizeRowsMode), (int)autoSizeRowsMode, typeof(DataGridViewAutoSizeRowsMode)); } if (autoSizeRowsMode == DataGridViewAutoSizeRowsMode.None) @@ -2366,9 +2366,9 @@ protected void AutoResizeRows(DataGridViewAutoSizeRowsMode autoSizeRowsMode, boo protected void AutoResizeRows(int rowIndexStart, int rowsCount, DataGridViewAutoSizeRowMode autoSizeRowMode, bool fixedWidth) { // not using ClientUtils.IsEnumValid here because DataGridViewAutoSizeRowCriteriaInternal is a flags enum. - if (((DataGridViewAutoSizeRowCriteriaInternal) autoSizeRowMode & invalidDataGridViewAutoSizeRowCriteriaInternalMask) != 0) + if (((DataGridViewAutoSizeRowCriteriaInternal)autoSizeRowMode & invalidDataGridViewAutoSizeRowCriteriaInternalMask) != 0) { - throw new InvalidEnumArgumentException(nameof(autoSizeRowMode), (int) autoSizeRowMode, typeof(DataGridViewAutoSizeRowMode)); + throw new InvalidEnumArgumentException(nameof(autoSizeRowMode), (int)autoSizeRowMode, typeof(DataGridViewAutoSizeRowMode)); } if (autoSizeRowMode == DataGridViewAutoSizeRowMode.RowHeader && !this.RowHeadersVisible) @@ -2440,7 +2440,7 @@ private void BeginColumnHeadersResize(int mouseY, int mouseBarOffset) Invalidate(CalcRowResizeFeedbackRect(this.currentRowSplitBar)); } - private void BeginColumnRelocation(int mouseX, int index) + private void BeginColumnRelocation(int mouseX, int index) { if (this.IsKeyboardOperationActive()) { @@ -2492,7 +2492,7 @@ private void BeginColumnResize(int x, int columnIndex) Invalidate(CalcColResizeFeedbackRect(this.currentColSplitBar)); } - private void BeginMouseColumnResize(int mouseX, int mouseBarOffset, int index) + private void BeginMouseColumnResize(int mouseX, int mouseBarOffset, int index) { if (this.IsKeyboardOperationActive()) { @@ -2789,7 +2789,7 @@ private void BeginRowResize(int mouseY, int mouseBarOffset, int index) private void BuildInheritedColumnHeaderCellStyle(DataGridViewCellStyle inheritedCellStyle, DataGridViewCell cell) { Debug.Assert(inheritedCellStyle != null); - + DataGridViewCellStyle cellStyle = null; if (cell.HasStyle) { @@ -2806,7 +2806,7 @@ private void BuildInheritedColumnHeaderCellStyle(DataGridViewCellStyle inherited if (cellStyle != null && !cellStyle.BackColor.IsEmpty) { inheritedCellStyle.BackColor = cellStyle.BackColor; - } + } else if (!columnHeadersStyle.BackColor.IsEmpty) { inheritedCellStyle.BackColor = columnHeadersStyle.BackColor; @@ -2819,7 +2819,7 @@ private void BuildInheritedColumnHeaderCellStyle(DataGridViewCellStyle inherited if (cellStyle != null && !cellStyle.ForeColor.IsEmpty) { inheritedCellStyle.ForeColor = cellStyle.ForeColor; - } + } else if (!columnHeadersStyle.ForeColor.IsEmpty) { inheritedCellStyle.ForeColor = columnHeadersStyle.ForeColor; @@ -2832,7 +2832,7 @@ private void BuildInheritedColumnHeaderCellStyle(DataGridViewCellStyle inherited if (cellStyle != null && !cellStyle.SelectionBackColor.IsEmpty) { inheritedCellStyle.SelectionBackColor = cellStyle.SelectionBackColor; - } + } else if (!columnHeadersStyle.SelectionBackColor.IsEmpty) { inheritedCellStyle.SelectionBackColor = columnHeadersStyle.SelectionBackColor; @@ -2845,7 +2845,7 @@ private void BuildInheritedColumnHeaderCellStyle(DataGridViewCellStyle inherited if (cellStyle != null && !cellStyle.SelectionForeColor.IsEmpty) { inheritedCellStyle.SelectionForeColor = cellStyle.SelectionForeColor; - } + } else if (!columnHeadersStyle.SelectionForeColor.IsEmpty) { inheritedCellStyle.SelectionForeColor = columnHeadersStyle.SelectionForeColor; @@ -2858,7 +2858,7 @@ private void BuildInheritedColumnHeaderCellStyle(DataGridViewCellStyle inherited if (cellStyle != null && cellStyle.Font != null) { inheritedCellStyle.Font = cellStyle.Font; - } + } else if (columnHeadersStyle.Font != null) { inheritedCellStyle.Font = columnHeadersStyle.Font; @@ -2897,7 +2897,7 @@ private void BuildInheritedColumnHeaderCellStyle(DataGridViewCellStyle inherited if (cellStyle != null && cellStyle.Format.Length != 0) { inheritedCellStyle.Format = cellStyle.Format; - } + } else if (columnHeadersStyle.Format.Length != 0) { inheritedCellStyle.Format = columnHeadersStyle.Format; @@ -2923,7 +2923,7 @@ private void BuildInheritedColumnHeaderCellStyle(DataGridViewCellStyle inherited if (cellStyle != null && cellStyle.Alignment != DataGridViewContentAlignment.NotSet) { inheritedCellStyle.AlignmentInternal = cellStyle.Alignment; - } + } else if (columnHeadersStyle != null && columnHeadersStyle.Alignment != DataGridViewContentAlignment.NotSet) { inheritedCellStyle.AlignmentInternal = columnHeadersStyle.Alignment; @@ -2937,7 +2937,7 @@ private void BuildInheritedColumnHeaderCellStyle(DataGridViewCellStyle inherited if (cellStyle != null && cellStyle.WrapMode != DataGridViewTriState.NotSet) { inheritedCellStyle.WrapModeInternal = cellStyle.WrapMode; - } + } else if (columnHeadersStyle != null && columnHeadersStyle.WrapMode != DataGridViewTriState.NotSet) { inheritedCellStyle.WrapModeInternal = columnHeadersStyle.WrapMode; @@ -2975,7 +2975,7 @@ private void BuildInheritedColumnHeaderCellStyle(DataGridViewCellStyle inherited } } - private Rectangle CalcColRelocationFeedbackRect(int mouseX) + private Rectangle CalcColRelocationFeedbackRect(int mouseX) { Rectangle r, inside = this.layout.ColumnHeaders; if (this.layout.TopLeftHeader.Width > 0) @@ -2984,9 +2984,9 @@ private Rectangle CalcColRelocationFeedbackRect(int mouseX) } if (this.RightToLeftInternal) { - r = new Rectangle(mouseX + this.mouseBarOffset - this.Columns[this.trackColumn].Thickness + 1, + r = new Rectangle(mouseX + this.mouseBarOffset - this.Columns[this.trackColumn].Thickness + 1, inside.Y, - this.Columns[this.trackColumn].Thickness, + this.Columns[this.trackColumn].Thickness, inside.Height); r.X = Math.Max(inside.Left, r.X); r.X = Math.Min(r.X, inside.Right - r.Width); @@ -3000,7 +3000,7 @@ private Rectangle CalcColRelocationFeedbackRect(int mouseX) return r; } - private Rectangle CalcColResizeFeedbackRect(int mouseX) + private Rectangle CalcColResizeFeedbackRect(int mouseX) { Rectangle inside = this.layout.Data; Rectangle r = new Rectangle(mouseX + this.mouseBarOffset - 1, inside.Y, 3, inside.Height); @@ -3016,7 +3016,7 @@ private Rectangle CalcColResizeFeedbackRect(int mouseX) return r; } - private Rectangle CalcRowResizeFeedbackRect(int mouseY) + private Rectangle CalcRowResizeFeedbackRect(int mouseY) { Rectangle inside = this.layout.Data; Rectangle r = new Rectangle(inside.X, mouseY + this.mouseBarOffset - 1, inside.Width, 3); @@ -3056,14 +3056,14 @@ private bool CancelEdit(bool endEdit /*, DataGridViewDataErrorContexts context*/ { if (endEdit && this.EditMode != DataGridViewEditMode.EditOnEnter && this.editingControl != null) { - bool success = EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.InitialValueRestoration, - DataGridViewValidateCellInternal.Never /*validateCell*/, - false /*fireCellLeave*/, - false /*fireCellEnter*/, - false /*fireRowLeave*/, - false /*fireRowEnter*/, - false /*fireLeave*/, - true /*keepFocus*/, + bool success = EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.InitialValueRestoration, + DataGridViewValidateCellInternal.Never /*validateCell*/, + false /*fireCellLeave*/, + false /*fireCellEnter*/, + false /*fireRowLeave*/, + false /*fireRowEnter*/, + false /*fireLeave*/, + true /*keepFocus*/, true /*resetCurrentCell unused here*/, true /*resetAnchorCell unused here*/); Debug.Assert(success); @@ -3114,7 +3114,7 @@ private bool CancelEdit(bool endEdit /*, DataGridViewDataErrorContexts context*/ if (this.editingControl != null) { - ((IDataGridViewEditingControl) this.editingControl).PrepareEditingControlForEdit(true /*selectAll*/); + ((IDataGridViewEditingControl)this.editingControl).PrepareEditingControlForEdit(true /*selectAll*/); } else { @@ -3192,8 +3192,8 @@ private DataGridViewDataErrorEventArgs CancelEditPrivate(/*ref DataGridViewCell if (this.DataSource != null || this.VirtualMode) { - if ((currentRowDirty && !currentCellDirty) || - (this.dataGridViewState1[DATAGRIDVIEWSTATE1_newRowEdited] && + if ((currentRowDirty && !currentCellDirty) || + (this.dataGridViewState1[DATAGRIDVIEWSTATE1_newRowEdited] && !this.dataGridViewState1[DATAGRIDVIEWSTATE1_editedRowChanged])) { bool discardNewRow = this.dataGridViewState1[DATAGRIDVIEWSTATE1_newRowEdited]; @@ -3247,7 +3247,7 @@ private DataGridViewDataErrorEventArgs CancelEditPrivate(/*ref DataGridViewCell if (this.editingControl != null) { InitializeEditingControlValue(ref dataGridViewCellStyle, dataGridViewCell); - if (((IDataGridViewEditingControl) this.editingControl).RepositionEditingControlOnValueChange) + if (((IDataGridViewEditingControl)this.editingControl).RepositionEditingControlOnValueChange) { PositionEditingControl(true /*setLocation*/, true /*setSize*/, false /*setFocus*/); } @@ -3267,7 +3267,7 @@ private DataGridViewDataErrorEventArgs CancelEditPrivate(/*ref DataGridViewCell } else { - if (!this.IsCurrentRowDirty && + if (!this.IsCurrentRowDirty && this.ptCurrentCell.Y == this.newRowIndex - 1 && this.dataGridViewState1[DATAGRIDVIEWSTATE1_newRowCreatedByEditing]) { @@ -3382,7 +3382,7 @@ private void CaptureMouse(Rectangle cursorClip) Cursor.ClipInternal = RectangleToScreen(cursorClip); } - private void ClearRegionCache() + private void ClearRegionCache() { this.cachedScrollableRegion = null; } @@ -3406,38 +3406,38 @@ public void ClearSelection() switch (this.SelectionMode) { case DataGridViewSelectionMode.CellSelect: - { - // If we change the design and start using this.selectedBandIndexes in this SelectionMode, - // we'll have to clear those selections too. - break; - } + { + // If we change the design and start using this.selectedBandIndexes in this SelectionMode, + // we'll have to clear those selections too. + break; + } - case DataGridViewSelectionMode.FullRowSelect: + case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: - { - while(this.selectedBandIndexes.Count > 0) { - SetSelectedRowCore(this.selectedBandIndexes.HeadInt, false); - } - - // Force repainting of the current collumn's header cell to remove highlighting - if (this.ptCurrentCell.X != -1 && - this.SelectionMode == DataGridViewSelectionMode.FullRowSelect) - { - InvalidateCellPrivate(this.ptCurrentCell.X, -1); + while (this.selectedBandIndexes.Count > 0) + { + SetSelectedRowCore(this.selectedBandIndexes.HeadInt, false); + } + + // Force repainting of the current collumn's header cell to remove highlighting + if (this.ptCurrentCell.X != -1 && + this.SelectionMode == DataGridViewSelectionMode.FullRowSelect) + { + InvalidateCellPrivate(this.ptCurrentCell.X, -1); + } + break; } - break; - } case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: - { - while(this.selectedBandIndexes.Count > 0) { - SetSelectedColumnCore(this.selectedBandIndexes.HeadInt, false); + while (this.selectedBandIndexes.Count > 0) + { + SetSelectedColumnCore(this.selectedBandIndexes.HeadInt, false); + } + break; } - break; - } } } finally @@ -3459,47 +3459,47 @@ protected void ClearSelection(int columnIndexException, int rowIndexException, b case DataGridViewSelectionMode.CellSelect: case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: - { - if (columnIndexException < 0 || columnIndexException >= this.Columns.Count) { - throw new ArgumentOutOfRangeException(nameof(columnIndexException)); - } - break; - } + if (columnIndexException < 0 || columnIndexException >= this.Columns.Count) + { + throw new ArgumentOutOfRangeException(nameof(columnIndexException)); + } + break; + } case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: - { - if (columnIndexException < -1 || columnIndexException >= this.Columns.Count) { - throw new ArgumentOutOfRangeException(nameof(columnIndexException)); + if (columnIndexException < -1 || columnIndexException >= this.Columns.Count) + { + throw new ArgumentOutOfRangeException(nameof(columnIndexException)); + } + break; } - break; - } } - + switch (this.SelectionMode) { case DataGridViewSelectionMode.CellSelect: case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: - { - if (rowIndexException < 0 || rowIndexException >= this.Rows.Count) { - throw new ArgumentOutOfRangeException(nameof(rowIndexException)); + if (rowIndexException < 0 || rowIndexException >= this.Rows.Count) + { + throw new ArgumentOutOfRangeException(nameof(rowIndexException)); + } + break; } - break; - } case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: - { - if (rowIndexException < -1 || rowIndexException >= this.Rows.Count) { - throw new ArgumentOutOfRangeException(nameof(rowIndexException)); + if (rowIndexException < -1 || rowIndexException >= this.Rows.Count) + { + throw new ArgumentOutOfRangeException(nameof(rowIndexException)); + } + break; } - break; - } } // Clears all selection except the row/column/cell specified as parameter @@ -3519,58 +3519,58 @@ protected void ClearSelection(int columnIndexException, int rowIndexException, b switch (this.SelectionMode) { case DataGridViewSelectionMode.CellSelect: - { - // If we change the design and start using this.selectedBandIndexes in this SelectionMode, - // we'll have to clear those selections too. - RemoveIndividuallySelectedCells(columnIndexException, rowIndexException); - break; - } + { + // If we change the design and start using this.selectedBandIndexes in this SelectionMode, + // we'll have to clear those selections too. + RemoveIndividuallySelectedCells(columnIndexException, rowIndexException); + break; + } case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: - { - int bandIndex = 0; - while (bandIndex < this.selectedBandIndexes.Count) { - if (this.selectedBandIndexes[bandIndex] != rowIndexException) + int bandIndex = 0; + while (bandIndex < this.selectedBandIndexes.Count) { - // deselect currently selected row - SetSelectedRowCore(this.selectedBandIndexes[bandIndex], false); + if (this.selectedBandIndexes[bandIndex] != rowIndexException) + { + // deselect currently selected row + SetSelectedRowCore(this.selectedBandIndexes[bandIndex], false); + } + else + { + bandIndex++; + } } - else + if (this.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) { - bandIndex++; + RemoveIndividuallySelectedCells(columnIndexException, rowIndexException); } + break; } - if (this.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) - { - RemoveIndividuallySelectedCells(columnIndexException, rowIndexException); - } - break; - } case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: - { - int bandIndex = 0; - while (bandIndex < this.selectedBandIndexes.Count) { - if (this.selectedBandIndexes[bandIndex] != columnIndexException) + int bandIndex = 0; + while (bandIndex < this.selectedBandIndexes.Count) { - // deselect currently selected column - SetSelectedColumnCore(this.selectedBandIndexes[bandIndex], false); + if (this.selectedBandIndexes[bandIndex] != columnIndexException) + { + // deselect currently selected column + SetSelectedColumnCore(this.selectedBandIndexes[bandIndex], false); + } + else + { + bandIndex++; + } } - else + if (this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) { - bandIndex++; + RemoveIndividuallySelectedCells(columnIndexException, rowIndexException); } + break; } - if (this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) - { - RemoveIndividuallySelectedCells(columnIndexException, rowIndexException); - } - break; - } } if (selectExceptionElement) { @@ -3591,7 +3591,7 @@ protected void ClearSelection(int columnIndexException, int rowIndexException, b private bool ColumnEditable(int columnIndex) { - Debug.Assert(columnIndex >= 0 && columnIndex < this.Columns.Count, "Invalid columnIndex: " + columnIndex ); + Debug.Assert(columnIndex >= 0 && columnIndex < this.Columns.Count, "Invalid columnIndex: " + columnIndex); if (this.Columns[columnIndex].IsDataBound && this.dataConnection != null && !this.dataConnection.AllowEdit) @@ -3655,7 +3655,7 @@ private bool ColumnRelocationTarget(MouseEventArgs e, HitTestInfo hti, out int p { int xColumnLeftEdge = GetColumnXFromIndex(hti.col); int wColumn = this.Columns[hti.col].Width; - if ((this.RightToLeftInternal && e.X < xColumnLeftEdge - wColumn / 2) || + if ((this.RightToLeftInternal && e.X < xColumnLeftEdge - wColumn / 2) || (!this.RightToLeftInternal && e.X > xColumnLeftEdge + wColumn / 2)) { // Insert column on the right of hti.col @@ -3675,7 +3675,7 @@ private bool ColumnRelocationTarget(MouseEventArgs e, HitTestInfo hti, out int p } else { - previousColumnIndex = (hti.typeInternal == DataGridViewHitTestTypeInternal.ColumnResizeRight || hti.typeInternal == DataGridViewHitTestTypeInternal.ColumnHeaderRight) ? + previousColumnIndex = (hti.typeInternal == DataGridViewHitTestTypeInternal.ColumnResizeRight || hti.typeInternal == DataGridViewHitTestTypeInternal.ColumnHeaderRight) ? hti.col : hti.adjacentCol; } DataGridViewColumn dataGridViewColumnNext = null; @@ -3689,7 +3689,7 @@ private bool ColumnRelocationTarget(MouseEventArgs e, HitTestInfo hti, out int p !(previousColumnIndex == -1 && hti.col == this.trackColumn) && (dataGridViewColumnNext == null || this.trackColumn != dataGridViewColumnNext.Index)) { - return true; + return true; } } else if (hti.typeInternal == DataGridViewHitTestTypeInternal.FirstColumnHeaderLeft || @@ -3698,14 +3698,14 @@ private bool ColumnRelocationTarget(MouseEventArgs e, HitTestInfo hti, out int p Debug.Assert(hti.col != -1); if (hti.col != this.trackColumn) { - return true; + return true; } } return false; } - private static bool ColumnsDisplayInOrder(int columnIndex1, - int columnDisplayIndex1, + private static bool ColumnsDisplayInOrder(int columnIndex1, + int columnDisplayIndex1, int columnIndex2, int columnDisplayIndex2) { @@ -3718,13 +3718,13 @@ public bool CommitEdit(DataGridViewDataErrorContexts context) if (this.IsCurrentCellInEditMode) { DataGridViewCell dataGridViewCurrentCell = this.CurrentCellInternal; - DataGridViewDataErrorEventArgs dgvdee = CommitEdit(ref dataGridViewCurrentCell, - context, + DataGridViewDataErrorEventArgs dgvdee = CommitEdit(ref dataGridViewCurrentCell, + context, DataGridViewValidateCellInternal.Never, false /*fireCellLeave*/, false /*fireCellEnter*/, false /*fireRowLeave*/, - false /*fireRowEnter*/, + false /*fireRowEnter*/, false /*fireLeave*/); if (null != dgvdee) { @@ -3741,8 +3741,8 @@ public bool CommitEdit(DataGridViewDataErrorContexts context) return true; } - private DataGridViewDataErrorEventArgs CommitEdit(ref DataGridViewCell dataGridViewCurrentCell, - DataGridViewDataErrorContexts context, + private DataGridViewDataErrorEventArgs CommitEdit(ref DataGridViewCell dataGridViewCurrentCell, + DataGridViewDataErrorContexts context, DataGridViewValidateCellInternal validateCell, bool fireCellLeave, bool fireCellEnter, @@ -3812,9 +3812,9 @@ private DataGridViewDataErrorEventArgs CommitEdit(ref DataGridViewCell dataGridV { return null; } - DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs(null, - this.ptCurrentCell.X, - this.ptCurrentCell.Y, + DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs(null, + this.ptCurrentCell.X, + this.ptCurrentCell.Y, // null, // null, context); @@ -3863,9 +3863,9 @@ private DataGridViewDataErrorEventArgs CommitEdit(ref DataGridViewCell dataGridV { return null; } - DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs(null, - this.ptCurrentCell.X, - this.ptCurrentCell.Y, + DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs(null, + this.ptCurrentCell.X, + this.ptCurrentCell.Y, context); dgvdee.Cancel = true; return dgvdee; @@ -3891,9 +3891,9 @@ private DataGridViewDataErrorEventArgs CommitEdit(ref DataGridViewCell dataGridV { return null; } - DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs(exception, - this.ptCurrentCell.X, - this.ptCurrentCell.Y, + DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs(exception, + this.ptCurrentCell.X, + this.ptCurrentCell.Y, // dataGridViewCurrentCell.Value, // formattedValue, context); @@ -3910,19 +3910,19 @@ private DataGridViewDataErrorEventArgs CommitEdit(ref DataGridViewCell dataGridV if (this.editingControl != null) { - ((IDataGridViewEditingControl) this.editingControl).EditingControlValueChanged = false; + ((IDataGridViewEditingControl)this.editingControl).EditingControlValueChanged = false; } else { Debug.Assert(this.dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode]); - ((IDataGridViewEditingCell) this.CurrentCellInternal).EditingCellValueChanged = false; + ((IDataGridViewEditingCell)this.CurrentCellInternal).EditingCellValueChanged = false; } this.IsCurrentCellDirtyInternal = false; this.IsCurrentRowDirtyInternal = true; if (validateAndPushFormattedValue) { - if (validateCell == DataGridViewValidateCellInternal.Always || + if (validateCell == DataGridViewValidateCellInternal.Always || validateCell == DataGridViewValidateCellInternal.WhenChanged) { if (this.ptCurrentCell.X == -1) @@ -3936,8 +3936,8 @@ private DataGridViewDataErrorEventArgs CommitEdit(ref DataGridViewCell dataGridV return null; } - private bool CommitEdit(DataGridViewDataErrorContexts context, - bool forCurrentCellChange, + private bool CommitEdit(DataGridViewDataErrorContexts context, + bool forCurrentCellChange, bool forCurrentRowChange) { // If we're already within a CellValidating event handler, don't try to commit the cell again. @@ -3947,8 +3947,8 @@ private bool CommitEdit(DataGridViewDataErrorContexts context, } DataGridViewCell dataGridViewCurrentCell = this.CurrentCellInternal; - DataGridViewDataErrorEventArgs dgvdee = CommitEdit(ref dataGridViewCurrentCell, - context, + DataGridViewDataErrorEventArgs dgvdee = CommitEdit(ref dataGridViewCurrentCell, + context, forCurrentCellChange ? DataGridViewValidateCellInternal.Always : DataGridViewValidateCellInternal.WhenChanged /*validateCell*/, forCurrentCellChange /*fireCellLeave*/, forCurrentCellChange /*fireCellEnter*/, @@ -4019,13 +4019,13 @@ private bool CommitEditForOperation(int columnIndex, int rowIndex, bool forCurre if (forCurrentCellChange) { if (!EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.CurrentCellChange, - DataGridViewValidateCellInternal.Always /*validateCell*/, - true /*fireCellLeave*/, - true /*fireCellEnter*/, - this.ptCurrentCell.Y != rowIndex /*fireRowLeave*/, - this.ptCurrentCell.Y != rowIndex /*fireRowEnter*/, - false /*fireLeave*/, - this.EditMode != DataGridViewEditMode.EditOnEnter /*keepFocus*/, + DataGridViewValidateCellInternal.Always /*validateCell*/, + true /*fireCellLeave*/, + true /*fireCellEnter*/, + this.ptCurrentCell.Y != rowIndex /*fireRowLeave*/, + this.ptCurrentCell.Y != rowIndex /*fireRowEnter*/, + false /*fireLeave*/, + this.EditMode != DataGridViewEditMode.EditOnEnter /*keepFocus*/, false /*resetCurrentCell*/, false /*resetAnchorCell unused here*/)) { @@ -4061,7 +4061,7 @@ private bool CommitEditForOperation(int columnIndex, int rowIndex, bool forCurre { BeginEditInternal(true /*selectAll*/); } - + return false; } if (IsInnerCellOutOfBounds(columnIndexTmp, rowIndexTmp)) @@ -4073,8 +4073,8 @@ private bool CommitEditForOperation(int columnIndex, int rowIndex, bool forCurre } else { - if (!CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, - false /*forCurrentCellChange*/, + if (!CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, + false /*forCurrentCellChange*/, this.ptCurrentCell.Y != rowIndex /*forCurrentRowChange*/)) { return false; @@ -4095,7 +4095,7 @@ private bool CommitEditForOperation(int columnIndex, int rowIndex, bool forCurre // row in the grid which may be the 'new row'. int lastVisibleRowIndex = this.Rows.GetLastRow(DataGridViewElementStates.Visible); if (forCurrentCellChange && - this.ptCurrentCell.X == -1 && + this.ptCurrentCell.X == -1 && lastVisibleRowIndex != -1) { bool success = SetAndSelectCurrentCellAddress(columnIndex, lastVisibleRowIndex, true, false, false, false /*clearSelection*/, false /*forceCurrentCellSelection*/); @@ -4126,9 +4126,9 @@ internal void CompleteCellsCollection(DataGridViewRow dataGridViewRow) { throw new InvalidOperationException(string.Format(SR.DataGridView_AColumnHasNoCellTemplate)); } - DataGridViewCell dgvcNew = (DataGridViewCell) this.Columns[columnIndex].CellTemplate.Clone(); + DataGridViewCell dgvcNew = (DataGridViewCell)this.Columns[columnIndex].CellTemplate.Clone(); cells[cellCount] = dgvcNew; - cellCount ++; + cellCount++; } dataGridViewRow.Cells.AddRange(cells); } @@ -4138,7 +4138,7 @@ internal void CompleteCellsCollection(DataGridViewRow dataGridViewRow) /// Determines which column is the first visible scrolling /// column given the object's horizontalOffset. /// - private int ComputeFirstVisibleScrollingColumn() + private int ComputeFirstVisibleScrollingColumn() { if (this.Columns.GetColumnsWidth(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen) >= this.layout.Data.Width) { @@ -4199,7 +4199,7 @@ private int ComputeHeightOfFittingTrailingScrollingRows(int totalVisibleFrozenHe int displayHeight = this.layout.Data.Height - totalVisibleFrozenHeight; int rowHeight = 0, rowHeights = 0; int indexTmp = this.Rows.Count; - + if (indexTmp == 0 || displayHeight <= 0) { return 0; @@ -4233,7 +4233,7 @@ private int ComputeHeightOfFittingTrailingScrollingRows(int totalVisibleFrozenHe while (indexTmp != -1 && rowHeights + rowHeight <= displayHeight) { rowHeights += rowHeight; - indexTmp = this.Rows.GetPreviousRow(indexTmp, + indexTmp = this.Rows.GetPreviousRow(indexTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); if (indexTmp != -1) @@ -4276,7 +4276,7 @@ private int ComputeHeightOfTrailingScrollingRows() return 0; } - private bool ComputeLayout() + private bool ComputeLayout() { ClearRegionCache(); @@ -4307,7 +4307,7 @@ private bool ComputeLayout() Rectangle insideLeft = inside; // Headers - if (this.layout.ColumnHeadersVisible) + if (this.layout.ColumnHeadersVisible) { Rectangle colHeaders = insideLeft; colHeaders.Height = Math.Min(this.columnHeadersHeight, colHeaders.Height); @@ -4316,12 +4316,12 @@ private bool ComputeLayout() Debug.Assert(insideLeft.Height >= 0); newLayout.ColumnHeaders = colHeaders; } - else + else { newLayout.ColumnHeaders = Rectangle.Empty; } - if (this.layout.RowHeadersVisible) + if (this.layout.RowHeadersVisible) { Rectangle rowHeaders = insideLeft; rowHeaders.Width = Math.Min(this.rowHeadersWidth, rowHeaders.Width); @@ -4337,7 +4337,7 @@ private bool ComputeLayout() Debug.Assert(insideLeft.Width >= 0); newLayout.RowHeaders = rowHeaders; - if (this.layout.ColumnHeadersVisible) + if (this.layout.ColumnHeadersVisible) { Rectangle topLeft; Rectangle colHeaders = newLayout.ColumnHeaders; @@ -4361,7 +4361,7 @@ private bool ComputeLayout() newLayout.TopLeftHeader = Rectangle.Empty; } } - else + else { newLayout.RowHeaders = Rectangle.Empty; newLayout.TopLeftHeader = Rectangle.Empty; @@ -4387,7 +4387,7 @@ private bool ComputeLayout() insideLeft.Height--; } } - + // Data region newLayout.Data = insideLeft; newLayout.Inside = inside; @@ -4429,7 +4429,7 @@ private void ComputeLayoutShortcut(bool computeVisibleRows) { ComputeVisibleRows(); } - #if DEBUG +#if DEBUG else { int oldNumTotallyVisibleFrozenRows = this.displayedBandsInfo.NumTotallyDisplayedFrozenRows; @@ -4442,25 +4442,25 @@ private void ComputeLayoutShortcut(bool computeVisibleRows) Debug.Assert(oldNumTotallyVisibleScrollingRows == this.displayedBandsInfo.NumTotallyDisplayedScrollingRows); Debug.Assert(oldFirstVisibleScrollingRow == this.displayedBandsInfo.FirstDisplayedScrollingRow); } - #endif - - #if DEBUG - int newFirstVisibleScrollingCol = ComputeFirstVisibleScrollingColumn(); - Debug.Assert(newFirstVisibleScrollingCol == this.displayedBandsInfo.FirstDisplayedScrollingCol); +#endif - int oldLastTotallyVisibleScrollingCol = this.displayedBandsInfo.LastTotallyDisplayedScrollingCol; - int oldFirstVisibleScrollingCol = this.displayedBandsInfo.FirstDisplayedScrollingCol; - ComputeVisibleColumns(); - Debug.Assert(oldLastTotallyVisibleScrollingCol == this.displayedBandsInfo.LastTotallyDisplayedScrollingCol); - Debug.Assert(oldFirstVisibleScrollingCol == this.displayedBandsInfo.FirstDisplayedScrollingCol); - #endif +#if DEBUG + int newFirstVisibleScrollingCol = ComputeFirstVisibleScrollingColumn(); + Debug.Assert(newFirstVisibleScrollingCol == this.displayedBandsInfo.FirstDisplayedScrollingCol); + + int oldLastTotallyVisibleScrollingCol = this.displayedBandsInfo.LastTotallyDisplayedScrollingCol; + int oldFirstVisibleScrollingCol = this.displayedBandsInfo.FirstDisplayedScrollingCol; + ComputeVisibleColumns(); + Debug.Assert(oldLastTotallyVisibleScrollingCol == this.displayedBandsInfo.LastTotallyDisplayedScrollingCol); + Debug.Assert(oldFirstVisibleScrollingCol == this.displayedBandsInfo.FirstDisplayedScrollingCol); +#endif if (this.vertScrollBar.Enabled) { int totalVisibleHeight = this.Rows.GetRowsHeight(DataGridViewElementStates.Visible); int totalVisibleFrozenHeight = this.Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); int oldVertScrollBarValue = this.vertScrollBar.Value; - int oldThumbHeight = Math.Max(((this.vertScrollBar.Height - 2*SystemInformation.VerticalScrollBarArrowHeight) * this.vertScrollBar.LargeChange) / this.vertScrollBar.Maximum, 8); + int oldThumbHeight = Math.Max(((this.vertScrollBar.Height - 2 * SystemInformation.VerticalScrollBarArrowHeight) * this.vertScrollBar.LargeChange) / this.vertScrollBar.Maximum, 8); this.vertScrollBar.Maximum = totalVisibleHeight - totalVisibleFrozenHeight; Debug.Assert(this.vertScrollBar.Maximum > 0); @@ -4470,7 +4470,7 @@ private void ComputeLayoutShortcut(bool computeVisibleRows) if (this.vertScrollBar.Visible && (oldVertScrollBarValue != this.verticalOffset || - oldThumbHeight != Math.Max(((this.vertScrollBar.Height - 2*SystemInformation.VerticalScrollBarArrowHeight) * this.vertScrollBar.LargeChange) / this.vertScrollBar.Maximum, 8))) + oldThumbHeight != Math.Max(((this.vertScrollBar.Height - 2 * SystemInformation.VerticalScrollBarArrowHeight) * this.vertScrollBar.LargeChange) / this.vertScrollBar.Maximum, 8))) { // Only update the vertical scroll bar is the thumb moved or resized. this.vertScrollBar.Invalidate(); @@ -4506,7 +4506,7 @@ private int ComputeScrolledOffRowCount(int scrolledOffRowsHeight) } */ - private void ComputeVisibleColumns() + private void ComputeVisibleColumns() { DataGridViewColumn dataGridViewColumn = null; int numVisibleScrollingCols = 0, visibleScrollingColumnsTmp = 0; @@ -4692,11 +4692,11 @@ private void ComputeVisibleColumns() this.displayedBandsInfo.NumDisplayedFrozenCols = numDisplayedFrozenCols; this.displayedBandsInfo.FirstDisplayedScrollingCol = firstDisplayedScrollingCol; this.displayedBandsInfo.NumDisplayedScrollingCols = numVisibleScrollingCols; - Debug.Assert((this.displayedBandsInfo.NumDisplayedScrollingCols > 0 && this.displayedBandsInfo.FirstDisplayedScrollingCol != -1) || + Debug.Assert((this.displayedBandsInfo.NumDisplayedScrollingCols > 0 && this.displayedBandsInfo.FirstDisplayedScrollingCol != -1) || (this.displayedBandsInfo.NumDisplayedScrollingCols == 0 && this.displayedBandsInfo.FirstDisplayedScrollingCol == -1)); } - - private void ComputeVisibleRows() + + private void ComputeVisibleRows() { int firstDisplayedFrozenRow = -1; int firstDisplayedScrollingRow = this.displayedBandsInfo.FirstDisplayedScrollingRow; @@ -4796,7 +4796,7 @@ private void ComputeVisibleRows() } } - if (cy < displayHeight) + if (cy < displayHeight) { for (int i = firstDisplayedScrollingRow - 1; i >= numTotallyDisplayedFrozenRows; i--) { @@ -4845,7 +4845,7 @@ private void ComputeVisibleRows() this.displayedBandsInfo.NumTotallyDisplayedFrozenRows = numTotallyDisplayedFrozenRows; this.displayedBandsInfo.LastDisplayedFrozenRow = lastDisplayedFrozenRow; this.displayedBandsInfo.LastDisplayedScrollingRow = lastDisplayedScrollingRow; - + Debug.Assert(this.displayedBandsInfo.NumTotallyDisplayedFrozenRows >= 0, "the number of visible frozen rows can't be negative"); Debug.Assert(this.displayedBandsInfo.NumDisplayedScrollingRows >= 0, "the number of visible scrolling rows can't be negative"); Debug.Assert(this.displayedBandsInfo.NumTotallyDisplayedScrollingRows >= 0, "the number of totally visible scrolling rows can't be negative"); @@ -4874,7 +4874,7 @@ private Point ConvertCellToGridCoord(int columnIndex, int rowIndex, int x, int y columnX = this.layout.RowHeaders.Left; } } - + if (rowIndex > -1) { rowY = GetRowYFromIndex(rowIndex); @@ -4883,7 +4883,7 @@ private Point ConvertCellToGridCoord(int columnIndex, int rowIndex, int x, int y { rowY = this.layout.ColumnHeaders.Top; } - + return new Point(columnX + x, rowY + y); } @@ -4926,7 +4926,7 @@ private void CorrectColumnDisplayIndexesAfterDeletion(DataGridViewColumn dataGri private void CorrectColumnDisplayIndexesAfterInsertion(DataGridViewColumn dataGridViewColumn) { - Debug.Assert(dataGridViewColumn != null); + Debug.Assert(dataGridViewColumn != null); Debug.Assert(dataGridViewColumn.DataGridView == this); // dataGridViewColumn.DisplayIndex has been set already. Debug.Assert(dataGridViewColumn.DisplayIndex >= 0); @@ -4976,7 +4976,7 @@ private void CorrectColumnFrozenState(DataGridViewColumn dataGridViewColumn, int } DataGridViewColumn dataGridViewColumnPrev; - int displayIndex = anticipatedColumnDisplayIndex-1; + int displayIndex = anticipatedColumnDisplayIndex - 1; do { dataGridViewColumnPrev = this.Columns.GetColumnAtDisplayIndex(displayIndex); @@ -5010,14 +5010,14 @@ private void CorrectColumnFrozenStates(DataGridViewColumn[] dataGridViewColumns) DataGridViewColumn dataGridViewColumnClone; foreach (DataGridViewColumn dataGridViewColumn in this.Columns) { - dataGridViewColumnClone = (DataGridViewColumn) dataGridViewColumn.Clone(); + dataGridViewColumnClone = (DataGridViewColumn)dataGridViewColumn.Clone(); // DataGridViewColumn.Clone does not replicate the DisplayIndex value. dataGridViewColumnClone.DisplayIndex = dataGridViewColumn.DisplayIndex; dataGridViewTmp.Columns.Add(dataGridViewColumnClone); } foreach (DataGridViewColumn dataGridViewColumn in dataGridViewColumns) { - dataGridViewColumnClone = (DataGridViewColumn) dataGridViewColumn.Clone(); + dataGridViewColumnClone = (DataGridViewColumn)dataGridViewColumn.Clone(); dataGridViewColumnClone.DisplayIndex = dataGridViewColumn.DisplayIndex; dataGridViewTmp.Columns.Add(dataGridViewColumnClone); } @@ -5084,7 +5084,7 @@ private void CorrectColumnFrozenStates(DataGridViewColumn dataGridViewColumn, bo } } } - + private void CorrectColumnFrozenStatesForMove(DataGridViewColumn dataGridViewColumn, int newDisplayIndex) { Debug.Assert(dataGridViewColumn != null); @@ -5112,7 +5112,7 @@ private void CorrectColumnFrozenStatesForMove(DataGridViewColumn dataGridViewCol // Get the closest visible column placed after the displaced column DataGridViewColumn dataGridViewColumnNext; displayIndex = newDisplayIndex; - do + do { dataGridViewColumnNext = this.Columns.GetColumnAtDisplayIndex(displayIndex); displayIndex++; @@ -5183,7 +5183,7 @@ private void CorrectRowFrozenState(DataGridViewRow dataGridViewRow, DataGridView int previousRowIndex = this.Rows.GetPreviousRow(anticipatedRowIndex, DataGridViewElementStates.Visible, DataGridViewElementStates.None); - if (previousRowIndex != -1 && + if (previousRowIndex != -1 && (this.Rows.GetRowState(previousRowIndex) & DataGridViewElementStates.Frozen) == 0 && (rowState & DataGridViewElementStates.Frozen) != 0) { @@ -5194,7 +5194,7 @@ private void CorrectRowFrozenState(DataGridViewRow dataGridViewRow, DataGridView int nextRowIndex = this.Rows.GetNextRow((previousRowIndex == -1) ? anticipatedRowIndex - 1 : previousRowIndex, DataGridViewElementStates.Visible, DataGridViewElementStates.None); - if (nextRowIndex != -1 && + if (nextRowIndex != -1 && (this.Rows.GetRowState(nextRowIndex) & DataGridViewElementStates.Frozen) != 0 && (rowState & DataGridViewElementStates.Frozen) == 0) { @@ -5376,9 +5376,9 @@ protected virtual DataGridViewRowCollection CreateRowsInstance() return new DataGridViewRowCollection(this); } - private NativeMethods.RECT[] CreateScrollableRegion(Rectangle scroll) + private NativeMethods.RECT[] CreateScrollableRegion(Rectangle scroll) { - if (this.cachedScrollableRegion != null) + if (this.cachedScrollableRegion != null) { return this.cachedScrollableRegion; } @@ -5433,11 +5433,11 @@ private void DiscardNewRow() } } - private void DiscardZonesInScrollingArea(ref Rectangle rectScrollingArea, - int emptyBackgroundWidth, - int emptyBackgroundHeight, + private void DiscardZonesInScrollingArea(ref Rectangle rectScrollingArea, + int emptyBackgroundWidth, + int emptyBackgroundHeight, int frozenVisibleRowsHeight, - bool discardFrozenColumns, + bool discardFrozenColumns, bool discardFrozenRows) { // Discard empty background @@ -5517,7 +5517,7 @@ public int DisplayedRowCount(bool includePartialRow) (this.displayedBandsInfo.NumTotallyDisplayedFrozenRows + this.displayedBandsInfo.NumTotallyDisplayedScrollingRows); } - protected override void Dispose(bool disposing) + protected override void Dispose(bool disposing) { if (disposing) { @@ -5525,7 +5525,7 @@ protected override void Dispose(bool disposing) try { // Remove any Columns contained in this control - for (int i = 0; i < this.Columns.Count; i ++) + for (int i = 0; i < this.Columns.Count; i++) { this.Columns[i].Dispose(); } @@ -5656,7 +5656,7 @@ private void DrawColHeaderShadow(Graphics g, int mouseX) } if (this.RightToLeftInternal) { - rectInsertionBar.X = Math.Max(this.layout.ColumnHeaders.X, + rectInsertionBar.X = Math.Max(this.layout.ColumnHeaders.X, GetColumnXFromIndex(this.trackColumnEdge) - this.Columns[this.trackColumnEdge].Width - offsetFromCenter); } else @@ -5734,7 +5734,7 @@ private void DrawSplitBar(Rectangle r) private void EditingControls_CommonMouseEventHandler(object sender, MouseEventArgs e, DataGridViewMouseEvent dgvme) { Debug.Assert(this.ptCurrentCell.X != -1); - int adjustedX = this.editingPanel.Location.X + e.X; + int adjustedX = this.editingPanel.Location.X + e.X; int adjustedY = this.editingPanel.Location.Y + e.Y; if (sender == this.editingControl) { @@ -5748,10 +5748,10 @@ private void EditingControls_CommonMouseEventHandler(object sender, MouseEventAr this.dataGridViewOper[DATAGRIDVIEWOPER_lastEditCtrlClickDoubled] = false; } - MouseEventArgs me = new MouseEventArgs(e.Button, - e.Clicks, - adjustedX, - adjustedY, + MouseEventArgs me = new MouseEventArgs(e.Button, + e.Clicks, + adjustedX, + adjustedY, e.Delta); HitTestInfo hti = HitTest(me.X, me.Y); @@ -5766,8 +5766,8 @@ private void EditingControls_CommonMouseEventHandler(object sender, MouseEventAr { this.dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls] = true; // Check to see if this is a CellMouseDoubleClick situation - if ((dgvme == DataGridViewMouseEvent.MouseDown || - dgvme == DataGridViewMouseEvent.Click || + if ((dgvme == DataGridViewMouseEvent.MouseDown || + dgvme == DataGridViewMouseEvent.Click || dgvme == DataGridViewMouseEvent.MouseClick) && (DateTime.Now.Ticks - this.lastMouseClickInfo.timeStamp) / 10000 <= SystemInformation.DoubleClickTime && e.Button == this.lastMouseClickInfo.button && @@ -5788,38 +5788,38 @@ private void EditingControls_CommonMouseEventHandler(object sender, MouseEventAr switch (dgvme) { case DataGridViewMouseEvent.MouseDown: - { - OnMouseDown(me); - if (dgvcme.ColumnIndex < this.Columns.Count && - dgvcme.RowIndex < this.Rows.Count) { - OnCellMouseDown(dgvcme); + OnMouseDown(me); + if (dgvcme.ColumnIndex < this.Columns.Count && + dgvcme.RowIndex < this.Rows.Count) + { + OnCellMouseDown(dgvcme); + } + break; } - break; - } case DataGridViewMouseEvent.Click: - { - OnDoubleClick(me); - if (e.Button == MouseButtons.Left && - dgvcme.ColumnIndex < this.Columns.Count && - dgvcme.RowIndex < this.Rows.Count) { - OnCellDoubleClick(new DataGridViewCellEventArgs(dgvcme.ColumnIndex, dgvcme.RowIndex)); + OnDoubleClick(me); + if (e.Button == MouseButtons.Left && + dgvcme.ColumnIndex < this.Columns.Count && + dgvcme.RowIndex < this.Rows.Count) + { + OnCellDoubleClick(new DataGridViewCellEventArgs(dgvcme.ColumnIndex, dgvcme.RowIndex)); + } + break; } - break; - } case DataGridViewMouseEvent.MouseClick: - { - // Set the flag that prevents the triple-click to be exposed as a double-click - this.dataGridViewOper[DATAGRIDVIEWOPER_lastEditCtrlClickDoubled] = true; - - OnMouseDoubleClick(me); - if (dgvcme.ColumnIndex < this.Columns.Count && dgvcme.RowIndex < this.Rows.Count) { - OnCellMouseDoubleClick(dgvcme); + // Set the flag that prevents the triple-click to be exposed as a double-click + this.dataGridViewOper[DATAGRIDVIEWOPER_lastEditCtrlClickDoubled] = true; + + OnMouseDoubleClick(me); + if (dgvcme.ColumnIndex < this.Columns.Count && dgvcme.RowIndex < this.Rows.Count) + { + OnCellMouseDoubleClick(dgvcme); + } + break; } - break; - } } return; } @@ -6009,9 +6009,9 @@ private void EditingControls_MouseUp(object sender, System.Windows.Forms.MouseEv EditingControls_CommonMouseEventHandler(sender, e, DataGridViewMouseEvent.MouseUp); } - private void EndColumnHeadersResize(MouseEventArgs e) + private void EndColumnHeadersResize(MouseEventArgs e) { - try + try { if (this.currentRowSplitBar != -1) { @@ -6026,17 +6026,17 @@ private void EndColumnHeadersResize(MouseEventArgs e) this.ColumnHeadersHeight += delta; } } - finally + finally { RealeaseMouse(); } } - private void EndColumnRelocation(MouseEventArgs e, HitTestInfo hti) + private void EndColumnRelocation(MouseEventArgs e, HitTestInfo hti) { - try + try { - if (this.lastHeaderShadow != -1) + if (this.lastHeaderShadow != -1) { this.dataGridViewState2[DATAGRIDVIEWSTATE2_showColumnRelocationInsertion] = false; this.trackColumnEdge = -1; @@ -6061,7 +6061,7 @@ private void EndColumnRelocation(MouseEventArgs e, HitTestInfo hti) } } } - finally + finally { RealeaseMouse(); } @@ -6115,20 +6115,20 @@ public bool EndEdit(DataGridViewDataErrorContexts context) } else { - return EndEdit(context, - DataGridViewValidateCellInternal.Never /*validateCell*/, + return EndEdit(context, + DataGridViewValidateCellInternal.Never /*validateCell*/, false /*fireCellLeave*/, false /*fireCellEnter*/, false /*fireRowLeave*/, false /*fireRowEnter*/, - false /*fireLeave*/, + false /*fireLeave*/, true /*keepFocus*/, true /*resetCurrentCell*/, true /*resetAnchorCell*/); } } - private bool EndEdit(DataGridViewDataErrorContexts context, + private bool EndEdit(DataGridViewDataErrorContexts context, DataGridViewValidateCellInternal validateCell, bool fireCellLeave, bool fireCellEnter, @@ -6243,9 +6243,9 @@ private bool EndEdit(DataGridViewDataErrorContexts context, } } - private void EndRowHeadersResize(MouseEventArgs e) + private void EndRowHeadersResize(MouseEventArgs e) { - try + try { if (this.currentColSplitBar != -1) { @@ -6269,7 +6269,7 @@ private void EndRowHeadersResize(MouseEventArgs e) this.RowHeadersWidth += delta; } } - finally + finally { RealeaseMouse(); } @@ -6277,7 +6277,7 @@ private void EndRowHeadersResize(MouseEventArgs e) private void EndRowResize(MouseEventArgs e) { - try + try { if (this.currentRowSplitBar != -1) { @@ -6290,7 +6290,7 @@ private void EndRowResize(MouseEventArgs e) dataGridViewRow.GetHeightInfo(this.trackRow, out height, out minimumHeight); int y = Math.Min(e.Y + this.mouseBarOffset, this.layout.Data.Bottom - 1); int delta = y - (GetRowYFromIndex(this.trackRow) + height) + 1; - if (this.trackRowAnchor != y && delta != 0) + if (this.trackRowAnchor != y && delta != 0) { int proposedHeight = height + delta; proposedHeight = Math.Max(proposedHeight, minimumHeight); @@ -6304,8 +6304,8 @@ private void EndRowResize(MouseEventArgs e) dataGridViewRow.ThicknessInternal = proposedHeight; } } - } - finally + } + finally { RealeaseMouse(); } @@ -6380,7 +6380,7 @@ private void FlushDisplayedChanged() else { Rectangle rectScreen = Screen.FromControl(this).WorkingArea; - int maxDisplayedRows = (int) (rectScreen.Height / DataGridViewBand.MinBandThickness); + int maxDisplayedRows = (int)(rectScreen.Height / DataGridViewBand.MinBandThickness); // Make sure all displayed scrolling rows have the Displayed state. int rowIndexTmp = this.displayedBandsInfo.FirstDisplayedScrollingRow; @@ -6425,7 +6425,7 @@ private void FlushDisplayedChanged() } // Make sure all displayed frozen rows have their Displayed state set to true - int numDisplayedFrozenRows = this.displayedBandsInfo.NumDisplayedFrozenRows; + int numDisplayedFrozenRows = this.displayedBandsInfo.NumDisplayedFrozenRows; rowIndexTmp = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); while (numDisplayedFrozenRows > 0) { @@ -6449,13 +6449,13 @@ private void FlushDisplayedChanged() int lastDisplayedFrozenRowIndex = -1; int lastDisplayedScrollingRowIndex = -1; - if (this.displayedBandsInfo.NumDisplayedFrozenRows > 0) + if (this.displayedBandsInfo.NumDisplayedFrozenRows > 0) { int firstDisplayedFrozenRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); Debug.Assert(firstDisplayedFrozenRowIndex != -1); if (this.displayedBandsInfo.NumDisplayedFrozenRows > 1) { - lastDisplayedFrozenRowIndex = this.Rows.GetNextRow(firstDisplayedFrozenRowIndex, DataGridViewElementStates.Visible, this.displayedBandsInfo.NumDisplayedFrozenRows-2 /*skipRows*/); + lastDisplayedFrozenRowIndex = this.Rows.GetNextRow(firstDisplayedFrozenRowIndex, DataGridViewElementStates.Visible, this.displayedBandsInfo.NumDisplayedFrozenRows - 2 /*skipRows*/); } else { @@ -6751,11 +6751,11 @@ protected override AccessibleObject GetAccessibilityObjectById(int objectId) return this.AccessibilityObject.GetChild(objectId - 1); } - - + + internal SolidBrush GetCachedBrush(Color color) { - SolidBrush brush = (SolidBrush) this.brushes[color]; + SolidBrush brush = (SolidBrush)this.brushes[color]; if (brush == null) { brush = new SolidBrush(color); @@ -6777,11 +6777,11 @@ internal WindowsSolidBrush GetCachedWindowsBrush(Color color) } #endif // DGV_GDI - - + + internal Pen GetCachedPen(Color color) { - Pen pen = (Pen) this.pens[color]; + Pen pen = (Pen)this.pens[color]; if (pen == null) { pen = new Pen(color); @@ -6859,21 +6859,21 @@ public int GetCellCount(DataGridViewElementStates includeFilter) switch (this.SelectionMode) { case DataGridViewSelectionMode.CellSelect: - { - // If we change the design and decide that SelectAll() should use band selection, - // we need to take the bands into account. - return cellCount; - } + { + // If we change the design and decide that SelectAll() should use band selection, + // we need to take the bands into account. + return cellCount; + } case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: - { - return cellCount + this.selectedBandIndexes.Count * this.Rows.Count; - } + { + return cellCount + this.selectedBandIndexes.Count * this.Rows.Count; + } case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: - { - return cellCount + this.selectedBandIndexes.Count * this.Columns.Count; - } + { + return cellCount + this.selectedBandIndexes.Count * this.Columns.Count; + } } } @@ -6882,7 +6882,7 @@ public int GetCellCount(DataGridViewElementStates includeFilter) resizableRequired = (includeFilter & DataGridViewElementStates.Resizable) == DataGridViewElementStates.Resizable; readOnlyRequired = (includeFilter & DataGridViewElementStates.ReadOnly) == DataGridViewElementStates.ReadOnly; visibleRequired = (includeFilter & DataGridViewElementStates.Visible) == DataGridViewElementStates.Visible; - + foreach (DataGridViewCell dataGridViewCell in this.individualSelectedCells) { if (GetCellCount_CellIncluded(dataGridViewCell, dataGridViewCell.RowIndex, displayedRequired, frozenRequired, resizableRequired, readOnlyRequired, visibleRequired)) @@ -6893,44 +6893,44 @@ public int GetCellCount(DataGridViewElementStates includeFilter) switch (this.SelectionMode) { case DataGridViewSelectionMode.CellSelect: - { - // If we change the design and decide that SelectAll() should use band selection, - // we need to take the bands into account. - return cellCount; - } + { + // If we change the design and decide that SelectAll() should use band selection, + // we need to take the bands into account. + return cellCount; + } case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: - { - for (int rowIndex = 0; rowIndex < this.Rows.Count; rowIndex++) { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); - foreach (int columnIndex in this.selectedBandIndexes) + for (int rowIndex = 0; rowIndex < this.Rows.Count; rowIndex++) { - DataGridViewCell dataGridViewCell = dataGridViewRow.Cells[columnIndex]; - if (GetCellCount_CellIncluded(dataGridViewCell, rowIndex, displayedRequired, frozenRequired, resizableRequired, readOnlyRequired, visibleRequired)) + DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); + foreach (int columnIndex in this.selectedBandIndexes) { - cellCount++; + DataGridViewCell dataGridViewCell = dataGridViewRow.Cells[columnIndex]; + if (GetCellCount_CellIncluded(dataGridViewCell, rowIndex, displayedRequired, frozenRequired, resizableRequired, readOnlyRequired, visibleRequired)) + { + cellCount++; + } } } + return cellCount; } - return cellCount; - } case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: - { - foreach (int rowIndex in this.selectedBandIndexes) { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); - foreach (DataGridViewCell dataGridViewCell in dataGridViewRow.Cells) + foreach (int rowIndex in this.selectedBandIndexes) { - if (GetCellCount_CellIncluded(dataGridViewCell, rowIndex, displayedRequired, frozenRequired, resizableRequired, readOnlyRequired, visibleRequired)) + DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); + foreach (DataGridViewCell dataGridViewCell in dataGridViewRow.Cells) { - cellCount++; + if (GetCellCount_CellIncluded(dataGridViewCell, rowIndex, displayedRequired, frozenRequired, resizableRequired, readOnlyRequired, visibleRequired)) + { + cellCount++; + } } } + return cellCount; } - return cellCount; - } } } @@ -6963,12 +6963,12 @@ public int GetCellCount(DataGridViewElementStates includeFilter) return cellCount; } - private bool GetCellCount_CellIncluded(DataGridViewCell dataGridViewCell, + private bool GetCellCount_CellIncluded(DataGridViewCell dataGridViewCell, int rowIndex, bool displayedRequired, - bool frozenRequired, - bool resizableRequired, - bool readOnlyRequired, + bool frozenRequired, + bool resizableRequired, + bool readOnlyRequired, bool visibleRequired) { Debug.Assert(dataGridViewCell != null); @@ -7568,7 +7568,7 @@ public virtual DataObject GetClipboardContent() // Cycle through the visible rows. bool firstRowIndex = true; int rowIndex = firstVisibleRowIndex; - int nextRowIndex = -1; + int nextRowIndex = -1; if (rowIndex != -1) { nextRowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); @@ -8160,12 +8160,12 @@ private static void GetClipboardContentForHtml(StringBuilder sbContent, out Syst utf8Stream.Write(destinationBytes, 0, bytecountEndOfHtml); utf8Stream.WriteByte((byte)0); - #if DEBUG +#if DEBUG Debug.Assert(destinationBytes[97] == '<'); - Debug.Assert(destinationBytes[bytecountEndOfHtml-1] == '>'); + Debug.Assert(destinationBytes[bytecountEndOfHtml - 1] == '>'); Debug.Assert(destinationBytes[133] == '<'); Debug.Assert(destinationBytes[bytecountEndOfFragment] == '<'); - #endif +#endif } // Rectangle returned includes the potential column header @@ -8222,7 +8222,7 @@ private Rectangle GetColumnDisplayRectanglePrivate(int columnIndex, bool cutOver { cx += dataGridViewColumn.Thickness; } - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen, DataGridViewElementStates.None); } @@ -8264,13 +8264,13 @@ private Rectangle GetColumnDisplayRectanglePrivate(int columnIndex, bool cutOver cx -= this.negOffset; } } - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); } } } - + if (columnFound) { Debug.Assert(dataGridViewColumn != null); @@ -8279,8 +8279,8 @@ private Rectangle GetColumnDisplayRectanglePrivate(int columnIndex, bool cutOver { viewedColumnWidth -= this.negOffset; } - if (cutOverflow && - ((!this.RightToLeftInternal && cx + viewedColumnWidth > data.Right) || + if (cutOverflow && + ((!this.RightToLeftInternal && cx + viewedColumnWidth > data.Right) || (this.RightToLeftInternal && cx - viewedColumnWidth < data.X))) { if (this.RightToLeftInternal) @@ -8306,10 +8306,10 @@ private Rectangle GetColumnDisplayRectanglePrivate(int columnIndex, bool cutOver { columnRect = new Rectangle(cx, data.Y, displayWidth, data.Height); } - if (this.layout.ColumnHeadersVisible) + if (this.layout.ColumnHeadersVisible) { columnRect.Height += this.layout.ColumnHeaders.Height; - columnRect.Y -= this.layout.ColumnHeaders.Height; + columnRect.Y -= this.layout.ColumnHeaders.Height; } return columnRect; } @@ -8337,7 +8337,7 @@ private int GetColumnIndexFromX(int x, out int xColumnLeftEdge) int cx; if (this.RightToLeftInternal) { - cx = data.Right-1; + cx = data.Right - 1; } else { @@ -8346,7 +8346,7 @@ private int GetColumnIndexFromX(int x, out int xColumnLeftEdge) // first try to match x against a frozen column DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); - while (dataGridViewColumn != null && + while (dataGridViewColumn != null && ((!this.RightToLeftInternal && cx < data.Right) || (this.RightToLeftInternal && cx >= data.X))) { if (this.RightToLeftInternal) @@ -8385,7 +8385,7 @@ private int GetColumnIndexFromX(int x, out int xColumnLeftEdge) if (this.displayedBandsInfo.FirstDisplayedScrollingCol >= 0) { dataGridViewColumn = this.Columns[this.displayedBandsInfo.FirstDisplayedScrollingCol]; - while (dataGridViewColumn != null && + while (dataGridViewColumn != null && ((!this.RightToLeftInternal && cx < data.Right) || (this.RightToLeftInternal && cx >= data.X))) { Debug.Assert(dataGridViewColumn.Visible && !dataGridViewColumn.Frozen); @@ -8456,7 +8456,7 @@ internal int GetColumnXFromIndex(int index) int x; if (this.RightToLeftInternal) { - x = this.layout.Data.Right-1; + x = this.layout.Data.Right - 1; } else { @@ -8596,7 +8596,7 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous if (mouseY >= rectScrollingArea.Top && mouseY <= rectScrollingArea.Bottom) { // Mouse's Y is in-bound -- correct X value - hti = HitTest(this.RightToLeftInternal ? rectScrollingArea.Right-1 : rectScrollingArea.Left, mouseY); + hti = HitTest(this.RightToLeftInternal ? rectScrollingArea.Right - 1 : rectScrollingArea.Left, mouseY); if (this.ptAnchorCell.Y != -1 && (this.Rows.GetRowState(this.ptAnchorCell.Y) & DataGridViewElementStates.Frozen) != 0 && this.trackRowEdge != -1 && @@ -8642,11 +8642,11 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous yOffset = mouseY - rectScrollingArea.Top; // yOffset strictly negative if (this.RightToLeftInternal) { - mouseX = rectScrollingArea.Right-1; + mouseX = rectScrollingArea.Right - 1; } else { - mouseX = rectScrollingArea.Left+1; + mouseX = rectScrollingArea.Left + 1; } } else @@ -8666,11 +8666,11 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous yOffset = mouseY - rectScrollingArea.Bottom; // yOffset strictly positive if (this.RightToLeftInternal) { - mouseX = rectScrollingArea.Right-1; + mouseX = rectScrollingArea.Right - 1; } else { - mouseX = rectScrollingArea.Left+1; + mouseX = rectScrollingArea.Left + 1; } } } @@ -8729,7 +8729,7 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous if ((!this.RightToLeftInternal && mouseX < rectScrollingArea.Left) || (this.RightToLeftInternal && mouseX > rectScrollingArea.Right)) { - if (this.ptAnchorCell.X != -1 && + if (this.ptAnchorCell.X != -1 && (!this.Columns[this.ptAnchorCell.X].Frozen || (this.trackColumnEdge != -1 && !this.Columns[this.trackColumnEdge].Frozen)) && this.displayedBandsInfo.FirstDisplayedScrollingCol >= 0 && @@ -8747,7 +8747,7 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous // Left scrolling is required xOffset = mouseX - rectScrollingArea.Left; } - mouseY = rectScrollingArea.Top+1; + mouseY = rectScrollingArea.Top + 1; } else { @@ -8767,14 +8767,14 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous } DataGridViewColumn newFirstVisibleScrollingCol = this.Columns.GetNextColumn(this.Columns[this.displayedBandsInfo.FirstDisplayedScrollingCol], - DataGridViewElementStates.Visible, + DataGridViewElementStates.Visible, DataGridViewElementStates.None); int newColOffset = 0; for (DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); dataGridViewColumn != newFirstVisibleScrollingCol; dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, - DataGridViewElementStates.Visible, + DataGridViewElementStates.Visible, DataGridViewElementStates.None)) { newColOffset += dataGridViewColumn.Thickness; @@ -8793,7 +8793,7 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous // Right scrolling is required xOffset = mouseX - rectScrollingArea.Right; } - mouseY = rectScrollingArea.Top+1; + mouseY = rectScrollingArea.Top + 1; } } } @@ -8816,7 +8816,7 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous (this.ptAnchorCell.Y != -1 && (this.Rows.GetRowState(this.ptAnchorCell.Y) & DataGridViewElementStates.Frozen) == 0) || (this.ptCurrentCell.Y != -1 && (this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Frozen) == 0) - ) + ) && this.verticalOffset != 0 ) @@ -8830,7 +8830,7 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous // Correct mouse's Y - no scrolling can be performed if (mouseY < this.layout.Data.Top) { - mouseY = this.layout.Data.Top+1; + mouseY = this.layout.Data.Top + 1; recomputeHitTestInfo = true; } } @@ -8849,14 +8849,14 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous else { // Correct mouse's Y - no scrolling can be performed - mouseY = rectScrollingArea.Bottom-1; + mouseY = rectScrollingArea.Bottom - 1; recomputeHitTestInfo = true; } } else { // Correct mouse's Y - no scrolling can be performed - mouseY = rectScrollingArea.Bottom-1; + mouseY = rectScrollingArea.Bottom - 1; recomputeHitTestInfo = true; } } @@ -8867,7 +8867,7 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous Debug.Assert(mouseY >= rectScrollingArea.Top && mouseY <= rectScrollingArea.Bottom); } #endif - if ((!this.RightToLeftInternal && mouseX < rectScrollingArea.Left) || + if ((!this.RightToLeftInternal && mouseX < rectScrollingArea.Left) || (this.RightToLeftInternal && mouseX > rectScrollingArea.Right)) { // Mouse's X is on the left of scrolling bands (LTR) @@ -8876,7 +8876,7 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous (this.ptAnchorCell.X != -1 && !this.Columns[this.ptAnchorCell.X].Frozen) || (this.ptCurrentCell.X != -1 && !this.Columns[this.ptCurrentCell.X].Frozen) - ) + ) && this.displayedBandsInfo.FirstDisplayedScrollingCol >= 0 && (this.negOffset > 0 || @@ -8900,12 +8900,12 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous // Correct mouse's X - no scrolling can be performed if (!this.RightToLeftInternal && mouseX < this.layout.Data.Left) { - mouseX = this.layout.Data.Left+1; + mouseX = this.layout.Data.Left + 1; recomputeHitTestInfo = true; } else if (this.RightToLeftInternal && mouseX > this.layout.Data.Right) { - mouseX = this.layout.Data.Right-1; + mouseX = this.layout.Data.Right - 1; recomputeHitTestInfo = true; } } @@ -8919,14 +8919,14 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous this.Columns.GetNextColumn(this.Columns[this.displayedBandsInfo.LastTotallyDisplayedScrollingCol], DataGridViewElementStates.Visible, DataGridViewElementStates.None) != null)) { DataGridViewColumn newFirstVisibleScrollingCol = this.Columns.GetNextColumn(this.Columns[this.displayedBandsInfo.FirstDisplayedScrollingCol], - DataGridViewElementStates.Visible, + DataGridViewElementStates.Visible, DataGridViewElementStates.None); int newColOffset = 0; for (DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); dataGridViewColumn != newFirstVisibleScrollingCol; dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, - DataGridViewElementStates.Visible, + DataGridViewElementStates.Visible, DataGridViewElementStates.None)) { newColOffset += dataGridViewColumn.Thickness; @@ -8950,11 +8950,11 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous // Correct mouse's X - no scrolling can be performed if (this.RightToLeftInternal) { - mouseX = rectScrollingArea.Left+1; + mouseX = rectScrollingArea.Left + 1; } else { - mouseX = rectScrollingArea.Right-1; + mouseX = rectScrollingArea.Right - 1; } recomputeHitTestInfo = true; } @@ -8964,11 +8964,11 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous // Correct mouse's X - no scrolling can be performed if (this.RightToLeftInternal) { - mouseX = rectScrollingArea.Left+1; + mouseX = rectScrollingArea.Left + 1; } else { - mouseX = rectScrollingArea.Right-1; + mouseX = rectScrollingArea.Right - 1; } recomputeHitTestInfo = true; } @@ -8990,12 +8990,12 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous internal override Size GetPreferredSizeCore(Size proposedConstraints) { - int bordersAndPaddingWidth = 2*(this.BorderWidth + this.Padding.Size.Width); - int bordersAndPaddingHeight = 2*(this.BorderWidth + this.Padding.Size.Height); + int bordersAndPaddingWidth = 2 * (this.BorderWidth + this.Padding.Size.Width); + int bordersAndPaddingHeight = 2 * (this.BorderWidth + this.Padding.Size.Height); bool allowHorizScrollbar = (this.scrollBars == ScrollBars.Both) || (this.scrollBars == ScrollBars.Horizontal); bool allowVertScrollbar = (this.scrollBars == ScrollBars.Both) || (this.scrollBars == ScrollBars.Vertical); - + int minimumWidth = 16 + bordersAndPaddingWidth; if (allowVertScrollbar) { @@ -9056,7 +9056,7 @@ private Rectangle GetRowDisplayRectanglePrivate(int rowIndex, bool cutOverflow) indexTmp != -1 && !rowFound; ) { - if (cy > data.Bottom) + if (cy > data.Bottom) { break; } @@ -9077,7 +9077,7 @@ private Rectangle GetRowDisplayRectanglePrivate(int rowIndex, bool cutOverflow) indexTmp != -1 && !rowFound; ) { - if (cy > data.Bottom) + if (cy > data.Bottom) { break; } @@ -9092,7 +9092,7 @@ private Rectangle GetRowDisplayRectanglePrivate(int rowIndex, bool cutOverflow) } } } - + if (rowFound) { int displayHeight; @@ -9109,7 +9109,7 @@ private Rectangle GetRowDisplayRectanglePrivate(int rowIndex, bool cutOverflow) cy, data.Width, displayHeight); - if (this.layout.RowHeadersVisible) + if (this.layout.RowHeadersVisible) { rowRect.Width += this.layout.RowHeaders.Width; if (!this.RightToLeftInternal) @@ -9123,12 +9123,12 @@ private Rectangle GetRowDisplayRectanglePrivate(int rowIndex, bool cutOverflow) return Rectangle.Empty; } - private int GetRowIndexFromY(int y, out int yRowTopEdge) + private int GetRowIndexFromY(int y, out int yRowTopEdge) { Rectangle data = this.layout.Data; - Debug.Assert(y >= data.Y-1 && y < data.Bottom, "y must be inside the vertical bounds of the data area."); + Debug.Assert(y >= data.Y - 1 && y < data.Bottom, "y must be inside the vertical bounds of the data area."); - if (y == data.Y-1) + if (y == data.Y - 1) { y++; } @@ -9275,7 +9275,7 @@ internal int GetRowYFromIndex(int index) { return y; } - indexTmp = this.Rows.GetPreviousRow(indexTmp, + indexTmp = this.Rows.GetPreviousRow(indexTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); } @@ -9300,7 +9300,7 @@ private bool GetTabKeyEffective(bool shift, bool ctrl) } } - public HitTestInfo HitTest(int x, int y) + public HitTestInfo HitTest(int x, int y) { HitTestInfo hti = new HitTestInfo(); @@ -9327,7 +9327,7 @@ public HitTestInfo HitTest(int x, int y) hti.typeInternal = DataGridViewHitTestTypeInternal.TopLeftHeader; if (this.RightToLeftInternal) { - hti.colStart = this.layout.TopLeftHeader.Right-1; + hti.colStart = this.layout.TopLeftHeader.Right - 1; } else { @@ -9364,7 +9364,7 @@ public HitTestInfo HitTest(int x, int y) } // check for column resize / insertion - if (this.layout.ColumnHeaders.Contains(x, y)) + if (this.layout.ColumnHeaders.Contains(x, y)) { int xColumnLeftEdge; // this is actually the right edge in RTL mode hti.col = GetColumnIndexFromX(x, out xColumnLeftEdge); @@ -9391,7 +9391,7 @@ public HitTestInfo HitTest(int x, int y) hti.mouseBarOffset = xColumnLeftEdge + columnWidth - x - 1; } DataGridViewColumn dataGridViewColumn = this.Columns[hti.col]; - if (dataGridViewColumn.Resizable == DataGridViewTriState.True && + if (dataGridViewColumn.Resizable == DataGridViewTriState.True && (dataGridViewColumn.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.None || dataGridViewColumn.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill)) { hti.typeInternal = DataGridViewHitTestTypeInternal.ColumnResizeRight; @@ -9423,7 +9423,7 @@ public HitTestInfo HitTest(int x, int y) { hti.mouseBarOffset = xColumnLeftEdge - x - 1; } - if (dataGridViewColumn.Resizable == DataGridViewTriState.True && + if (dataGridViewColumn.Resizable == DataGridViewTriState.True && (dataGridViewColumn.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.None || dataGridViewColumn.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill)) { hti.typeInternal = DataGridViewHitTestTypeInternal.ColumnResizeLeft; @@ -9465,7 +9465,7 @@ public HitTestInfo HitTest(int x, int y) } // check for row resize - if (this.layout.RowHeaders.Contains(x, y)) + if (this.layout.RowHeaders.Contains(x, y)) { int yRowTopEdge; hti.row = GetRowIndexFromY(y, out yRowTopEdge); @@ -9479,7 +9479,7 @@ public HitTestInfo HitTest(int x, int y) hti.rowStart = yRowTopEdge; if (this.RightToLeftInternal) { - hti.colStart = this.layout.RowHeaders.Right-1; + hti.colStart = this.layout.RowHeaders.Right - 1; } else { @@ -9541,7 +9541,7 @@ public HitTestInfo HitTest(int x, int y) } } - if (this.layout.Data.Contains(x, y)) + if (this.layout.Data.Contains(x, y)) { int xColumnLeftEdge, yRowTopEdge; hti.col = GetColumnIndexFromX(x, out xColumnLeftEdge); @@ -9571,7 +9571,7 @@ public HitTestInfo HitTest(int x, int y) hti.mouseBarOffset = xColumnLeftEdge + columnWidth - x - 1; } DataGridViewColumn dataGridViewColumn = this.Columns[hti.col]; - if (dataGridViewColumn.Resizable == DataGridViewTriState.True && + if (dataGridViewColumn.Resizable == DataGridViewTriState.True && (dataGridViewColumn.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.None || dataGridViewColumn.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill)) { hti.typeInternal = DataGridViewHitTestTypeInternal.ColumnResizeRight; @@ -9599,7 +9599,7 @@ public HitTestInfo HitTest(int x, int y) { hti.mouseBarOffset = xColumnLeftEdge - x - 1; } - if (dataGridViewColumn.Resizable == DataGridViewTriState.True && + if (dataGridViewColumn.Resizable == DataGridViewTriState.True && (dataGridViewColumn.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.None || dataGridViewColumn.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill)) { hti.typeInternal = DataGridViewHitTestTypeInternal.ColumnResizeLeft; @@ -9630,7 +9630,7 @@ public HitTestInfo HitTest(int x, int y) DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); Debug.Assert(dataGridViewColumn != null); if (hti.col == dataGridViewColumn.Index && - this.RowHeadersVisible && + this.RowHeadersVisible && this.RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing) { hti.typeInternal = DataGridViewHitTestTypeInternal.RowHeadersResizeLeft; @@ -9689,7 +9689,7 @@ public HitTestInfo HitTest(int x, int y) int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); Debug.Assert(rowIndex >= 0); if (hti.row == rowIndex && - this.ColumnHeadersVisible && + this.ColumnHeadersVisible && this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing) { hti.typeInternal = DataGridViewHitTestTypeInternal.ColumnHeadersResizeTop; @@ -9722,7 +9722,7 @@ private void HorizScrollTimerHandler() this.horizScrollTimer.Interval = GetColumnScrollRate(absXOffset); if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect]) { - hti = HitTest(ptMouse.X+(this.RightToLeftInternal?1:-1)*(xOffset+normOffset), mouseY); + hti = HitTest(ptMouse.X + (this.RightToLeftInternal ? 1 : -1) * (xOffset + normOffset), mouseY); if (hti.col >= 0) { OnColumnSelectMouseMove(hti); @@ -9732,11 +9732,11 @@ private void HorizScrollTimerHandler() { if (yOffset != 0) { - hti = HitTest(ptMouse.X+(this.RightToLeftInternal?1:-1)*(xOffset+normOffset), ptMouse.Y-yOffset-(yOffset/Math.Abs(yOffset))); + hti = HitTest(ptMouse.X + (this.RightToLeftInternal ? 1 : -1) * (xOffset + normOffset), ptMouse.Y - yOffset - (yOffset / Math.Abs(yOffset))); } else { - hti = HitTest(ptMouse.X+(this.RightToLeftInternal?1:-1)*(xOffset+normOffset), mouseY); + hti = HitTest(ptMouse.X + (this.RightToLeftInternal ? 1 : -1) * (xOffset + normOffset), mouseY); } if (hti.col >= 0 && hti.row >= 0) { @@ -9815,7 +9815,7 @@ private bool InitializeEditingControlValue(ref DataGridViewCellStyle dataGridVie Debug.Assert(this.editingControl != null); DataGridViewDataErrorEventArgs dgvdee = null; - object initialFormattedValue = dataGridViewCell.GetFormattedValue(this.ptCurrentCell.Y, ref dataGridViewCellStyle, DataGridViewDataErrorContexts.Formatting); + object initialFormattedValue = dataGridViewCell.GetFormattedValue(this.ptCurrentCell.Y, ref dataGridViewCellStyle, DataGridViewDataErrorContexts.Formatting); this.dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlChanging] = true; this.dataGridViewState1[DATAGRIDVIEWSTATE1_ignoringEditingChanges] = true; try @@ -9830,7 +9830,7 @@ private bool InitializeEditingControlValue(ref DataGridViewCellStyle dataGridVie throw; } dgvdee = new DataGridViewDataErrorEventArgs(exception, this.ptCurrentCell.X, - this.ptCurrentCell.Y, + this.ptCurrentCell.Y, DataGridViewDataErrorContexts.InitialValueRestoration); OnDataErrorInternal(dgvdee); } @@ -9935,7 +9935,7 @@ private void InvalidateData() /// /// Invalidates the scrollable area of the DataGridView. /// - private void InvalidateInside() + private void InvalidateInside() { if (this.IsHandleCreated) { @@ -10095,7 +10095,7 @@ private void InvalidateRows(int lo, int hi) break; } - i ++; + i++; } if (bottom <= top) @@ -10167,45 +10167,45 @@ protected override bool IsInputKey(Keys keyData) switch (keyData & Keys.KeyCode) { case Keys.Escape: - { - return this.IsEscapeKeyEffective; - } + { + return this.IsEscapeKeyEffective; + } case Keys.Tab: - { - return GetTabKeyEffective((keyData & Keys.Shift) == Keys.Shift, (keyData & Keys.Control) == Keys.Control); - } + { + return GetTabKeyEffective((keyData & Keys.Shift) == Keys.Shift, (keyData & Keys.Control) == Keys.Control); + } case Keys.A: - { - if ((keyData & (Keys.Control | Keys.Shift | Keys.Alt)) == Keys.Control) { - return true; + if ((keyData & (Keys.Control | Keys.Shift | Keys.Alt)) == Keys.Control) + { + return true; + } + break; } - break; - } case Keys.C: case Keys.Insert: - { - if ((keyData & (Keys.Control | Keys.Shift | Keys.Alt)) == Keys.Control) { - return true; + if ((keyData & (Keys.Control | Keys.Shift | Keys.Alt)) == Keys.Control) + { + return true; + } + break; } - break; - } case Keys.Space: - { - if ((keyData & (Keys.Control | Keys.Shift | Keys.Alt)) == Keys.Shift && - (this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect || - this.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) && - this.ptCurrentCell.X != -1) { - return true; + if ((keyData & (Keys.Control | Keys.Shift | Keys.Alt)) == Keys.Shift && + (this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect || + this.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) && + this.ptCurrentCell.X != -1) + { + return true; + } + break; } - break; - } case Keys.Up: case Keys.Down: @@ -10221,9 +10221,9 @@ protected override bool IsInputKey(Keys keyData) case Keys.NumPad0: case Keys.F2: case Keys.F3: - { - return true; - } + { + return true; + } } return base.IsInputKey(keyData); } @@ -10233,7 +10233,7 @@ protected override bool IsInputKey(Keys keyData) /// updates their bounds and the bounds of all /// other regions in the dataGridView's Layout. /// - private void LayoutScrollBars() + private void LayoutScrollBars() { SuspendLayout(); try @@ -10465,7 +10465,7 @@ private void LayoutScrollBars() } else { - this.vertScrollBar.Visible = false; + this.vertScrollBar.Visible = false; this.verticalOffset = ComputeHeightOfScrolledOffRows(); this.vertScrollBar.Enabled = false; @@ -10485,9 +10485,9 @@ private void MakeFirstDisplayedCellCurrentCell(bool includeNewRow) { // No current cell - try to set the first displayed cell to be the current one. Point firstDisplayedCellAddress = this.FirstDisplayedCellAddress; - if (firstDisplayedCellAddress.X != -1 && + if (firstDisplayedCellAddress.X != -1 && (includeNewRow || - !this.AllowUserToAddRowsInternal || + !this.AllowUserToAddRowsInternal || firstDisplayedCellAddress.Y != this.Rows.Count - 1)) { bool success = SetAndSelectCurrentCellAddress(firstDisplayedCellAddress.X, @@ -10523,12 +10523,12 @@ private static DataGridViewAutoSizeRowMode MapAutoSizeRowsModeToRowMode(DataGrid } } - private void MoveColumnHeadersOrRowResize(MouseEventArgs e) + private void MoveColumnHeadersOrRowResize(MouseEventArgs e) { this.lastRowSplitBar = this.currentRowSplitBar; this.currentRowSplitBar = e.Y; Rectangle lastSplitBarRect = CalcRowResizeFeedbackRect(this.lastRowSplitBar); - if (this.editingControl != null && + if (this.editingControl != null && !this.dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlHidden] && this.editingPanel.Bounds.IntersectsWith(lastSplitBarRect)) { @@ -10581,7 +10581,7 @@ private void MapDataGridViewColumnToDataBoundField(DataGridViewColumn dataGridVi } } - private void MoveColumnRelocation(MouseEventArgs e, HitTestInfo hti) + private void MoveColumnRelocation(MouseEventArgs e, HitTestInfo hti) { this.lastHeaderShadow = e.X; this.dataGridViewState2[DATAGRIDVIEWSTATE2_showColumnRelocationInsertion] = ColumnRelocationTarget(e, hti, out this.trackColumnEdge); @@ -10617,7 +10617,7 @@ public virtual void NotifyCurrentCellDirty(bool dirty) // and autosizing code only looks at committed values. this.IsCurrentCellDirtyInternal = dirty; - if (dirty && this.editingControl != null && ((IDataGridViewEditingControl) this.editingControl).RepositionEditingControlOnValueChange) + if (dirty && this.editingControl != null && ((IDataGridViewEditingControl)this.editingControl).RepositionEditingControlOnValueChange) { PositionEditingControl(true /*setLocation*/, true /*setSize*/, false /*setFocus*/); } @@ -10790,7 +10790,7 @@ internal void OnAddedRows_PreNotification(DataGridViewRow[] dataGridViewRows) { // Note: no row can be added that breaks the frozen row packing on the top - foreach(DataGridViewRow dataGridViewRow in dataGridViewRows) + foreach (DataGridViewRow dataGridViewRow in dataGridViewRows) { OnAddedRow_PreNotification(dataGridViewRow.Index); } @@ -10816,7 +10816,7 @@ internal void OnAddingColumn(DataGridViewColumn dataGridViewColumn) throw new InvalidOperationException(string.Format(SR.DataGridView_ColumnAlreadyBelongsToDataGridView)); } - if (!this.InInitialization && + if (!this.InInitialization && dataGridViewColumn.SortMode == DataGridViewColumnSortMode.Automatic && (this.SelectionMode == DataGridViewSelectionMode.FullColumnSelect || this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect)) @@ -11285,8 +11285,8 @@ protected virtual void OnAutoSizeColumnModeChanged(DataGridViewAutoSizeColumnMod // Save current column width for later reuse dataGridViewColumn.CachedThickness = dataGridViewColumn.Thickness; } - AutoResizeColumnInternal(dataGridViewColumn.Index, - (DataGridViewAutoSizeColumnCriteriaInternal) autoSizeColumnMode, + AutoResizeColumnInternal(dataGridViewColumn.Index, + (DataGridViewAutoSizeColumnCriteriaInternal)autoSizeColumnMode, fixedHeight); } } @@ -11442,12 +11442,12 @@ protected virtual void OnAutoSizeRowsModeChanged(DataGridViewAutoSizeModeEventAr } } - protected virtual void OnBackgroundColorChanged(EventArgs e) + protected virtual void OnBackgroundColorChanged(EventArgs e) { InvalidateInside(); EventHandler eh = this.Events[EVENT_DATAGRIDVIEWBACKGROUNDCOLORCHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) { eh(this, e); } @@ -11463,7 +11463,7 @@ internal void OnBandContextMenuStripChanged(DataGridViewBand dataGridViewBand) } else { - DataGridViewRowEventArgs dgvre = new DataGridViewRowEventArgs((DataGridViewRow) dataGridViewBand); + DataGridViewRowEventArgs dgvre = new DataGridViewRowEventArgs((DataGridViewRow)dataGridViewBand); OnRowContextMenuStripChanged(dgvre); } } @@ -11478,7 +11478,7 @@ internal void OnBandDefaultCellStyleChanged(DataGridViewBand dataGridViewBand) } else { - DataGridViewRowEventArgs dgvre = new DataGridViewRowEventArgs((DataGridViewRow) dataGridViewBand); + DataGridViewRowEventArgs dgvre = new DataGridViewRowEventArgs((DataGridViewRow)dataGridViewBand); OnRowDefaultCellStyleChanged(dgvre); } } @@ -11493,7 +11493,7 @@ internal void OnBandDividerThicknessChanged(DataGridViewBand dataGridViewBand) } else { - DataGridViewRowEventArgs dgvre = new DataGridViewRowEventArgs((DataGridViewRow) dataGridViewBand); + DataGridViewRowEventArgs dgvre = new DataGridViewRowEventArgs((DataGridViewRow)dataGridViewBand); OnRowDividerHeightChanged(dgvre); } } @@ -11508,7 +11508,7 @@ internal void OnBandHeaderCellChanged(DataGridViewBand dataGridViewBand) } else { - DataGridViewRowEventArgs dgvre = new DataGridViewRowEventArgs((DataGridViewRow) dataGridViewBand); + DataGridViewRowEventArgs dgvre = new DataGridViewRowEventArgs((DataGridViewRow)dataGridViewBand); OnRowHeaderCellChanged(dgvre); } } @@ -11523,7 +11523,7 @@ internal void OnBandMinimumThicknessChanged(DataGridViewBand dataGridViewBand) } else { - DataGridViewRowEventArgs dgvre = new DataGridViewRowEventArgs((DataGridViewRow) dataGridViewBand); + DataGridViewRowEventArgs dgvre = new DataGridViewRowEventArgs((DataGridViewRow)dataGridViewBand); OnRowMinimumHeightChanged(dgvre); } } @@ -11538,7 +11538,7 @@ internal void OnBandThicknessChanged(DataGridViewBand dataGridViewBand) } else { - DataGridViewRowEventArgs dgvre = new DataGridViewRowEventArgs((DataGridViewRow) dataGridViewBand); + DataGridViewRowEventArgs dgvre = new DataGridViewRowEventArgs((DataGridViewRow)dataGridViewBand); OnRowHeightChanged(dgvre); } } @@ -11642,7 +11642,7 @@ protected virtual void OnCellBorderStyleChanged(EventArgs e) { PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); Invalidate(); - + EventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLBORDERSTYLECHANGED] as EventHandler; if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) { @@ -11717,7 +11717,7 @@ internal void OnCellCommonChange(int columnIndex, int rowIndex) autoSizeColumn |= (autoSizeColumnCriteriaInternal & DataGridViewAutoSizeColumnCriteriaInternal.DisplayedRows) != 0; } - bool autoSizeRow = (((DataGridViewAutoSizeRowsModeInternal) this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0; + bool autoSizeRow = (((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0; if (autoSizeRow) { AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(this.autoSizeRowsMode), !autoSizeColumn /*fixedWidth*/, true /*internalAutosizing*/); @@ -12186,10 +12186,10 @@ protected virtual void OnCellMouseDown(DataGridViewCellMouseEventArgs e) case DataGridViewHitTestTypeInternal.TopLeftHeaderResizeBottom: case DataGridViewHitTestTypeInternal.ColumnHeadersResizeTop: case DataGridViewHitTestTypeInternal.ColumnHeadersResizeBottom: - { - this.dataGridViewOper[DATAGRIDVIEWOPER_resizingOperationAboutToStart] = (e.Clicks == 1); - break; - } + { + this.dataGridViewOper[DATAGRIDVIEWOPER_resizingOperationAboutToStart] = (e.Clicks == 1); + break; + } } } @@ -12218,93 +12218,93 @@ protected virtual void OnCellMouseDown(DataGridViewCellMouseEventArgs e) // Check column resize case DataGridViewHitTestTypeInternal.ColumnResizeLeft: case DataGridViewHitTestTypeInternal.ColumnResizeRight: - { - int columnIndex = (hti.typeInternal == DataGridViewHitTestTypeInternal.ColumnResizeRight) ? hti.col : hti.adjacentCol; - Debug.Assert(this.Columns[columnIndex].Resizable == DataGridViewTriState.True); - if (e.Clicks == 1) { - BeginMouseColumnResize(ptGridCoord.X, hti.mouseBarOffset, columnIndex); + int columnIndex = (hti.typeInternal == DataGridViewHitTestTypeInternal.ColumnResizeRight) ? hti.col : hti.adjacentCol; + Debug.Assert(this.Columns[columnIndex].Resizable == DataGridViewTriState.True); + if (e.Clicks == 1) + { + BeginMouseColumnResize(ptGridCoord.X, hti.mouseBarOffset, columnIndex); + } + break; } - break; - } // Check row resize case DataGridViewHitTestTypeInternal.RowResizeBottom: case DataGridViewHitTestTypeInternal.RowResizeTop: - { - int rowIndex = (hti.typeInternal == DataGridViewHitTestTypeInternal.RowResizeBottom) ? hti.row : hti.adjacentRow; - if (e.Clicks == 1) { - BeginRowResize(ptGridCoord.Y, hti.mouseBarOffset, rowIndex); + int rowIndex = (hti.typeInternal == DataGridViewHitTestTypeInternal.RowResizeBottom) ? hti.row : hti.adjacentRow; + if (e.Clicks == 1) + { + BeginRowResize(ptGridCoord.Y, hti.mouseBarOffset, rowIndex); + } + break; } - break; - } // Check for column header mouse down case DataGridViewHitTestTypeInternal.ColumnHeader: case DataGridViewHitTestTypeInternal.ColumnHeaderLeft: case DataGridViewHitTestTypeInternal.ColumnHeaderRight: case DataGridViewHitTestTypeInternal.FirstColumnHeaderLeft: - { - if (isAltDown && this.AllowUserToOrderColumns && - (this.SelectionMode == DataGridViewSelectionMode.FullColumnSelect || - this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect)) { - BeginColumnRelocation(ptGridCoord.X, hti.col); + if (isAltDown && this.AllowUserToOrderColumns && + (this.SelectionMode == DataGridViewSelectionMode.FullColumnSelect || + this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect)) + { + BeginColumnRelocation(ptGridCoord.X, hti.col); + } + else + { + OnColumnHeaderMouseDown(hti, isShiftDown, isControlDown); + } + break; } - else - { - OnColumnHeaderMouseDown(hti, isShiftDown, isControlDown); - } - break; - } // Check for row header mouse down case DataGridViewHitTestTypeInternal.RowHeader: - { - OnRowHeaderMouseDown(hti, isShiftDown, isControlDown); - break; - } + { + OnRowHeaderMouseDown(hti, isShiftDown, isControlDown); + break; + } // Check for cell mouse down case DataGridViewHitTestTypeInternal.Cell: - { - OnCellMouseDown(hti, isShiftDown, isControlDown); - break; - } + { + OnCellMouseDown(hti, isShiftDown, isControlDown); + break; + } // Check for top/left header mouse down case DataGridViewHitTestTypeInternal.TopLeftHeader: - { - OnTopLeftHeaderMouseDown(); - break; - } + { + OnTopLeftHeaderMouseDown(); + break; + } // Check for row headers resize case DataGridViewHitTestTypeInternal.TopLeftHeaderResizeLeft: case DataGridViewHitTestTypeInternal.TopLeftHeaderResizeRight: case DataGridViewHitTestTypeInternal.RowHeadersResizeLeft: case DataGridViewHitTestTypeInternal.RowHeadersResizeRight: - { - if (e.Clicks == 1) { - BeginRowHeadersResize(ptGridCoord.X, hti.mouseBarOffset); + if (e.Clicks == 1) + { + BeginRowHeadersResize(ptGridCoord.X, hti.mouseBarOffset); + } + break; } - break; - } // Check for column headers resize case DataGridViewHitTestTypeInternal.TopLeftHeaderResizeTop: case DataGridViewHitTestTypeInternal.TopLeftHeaderResizeBottom: case DataGridViewHitTestTypeInternal.ColumnHeadersResizeTop: case DataGridViewHitTestTypeInternal.ColumnHeadersResizeBottom: - { - if (e.Clicks == 1) { - BeginColumnHeadersResize(ptGridCoord.Y, hti.mouseBarOffset); + if (e.Clicks == 1) + { + BeginColumnHeadersResize(ptGridCoord.Y, hti.mouseBarOffset); + } + break; } - break; - } } // Make sure that there is a current cell after this mouse down event. if (this.ptCurrentCell.X == -1) @@ -12382,165 +12382,78 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo switch (this.SelectionMode) { case DataGridViewSelectionMode.CellSelect: - { - if (isControlDown && - IsSharedCellSelected(this.Rows.SharedRow(hti.row).Cells[hti.col], hti.row) && - (!isShiftDown || !this.MultiSelect)) { - select = false; - } - if (select) - { - if ((!this.MultiSelect || !isControlDown) && !(this.MultiSelect && isShiftDown)) + if (isControlDown && + IsSharedCellSelected(this.Rows.SharedRow(hti.row).Cells[hti.col], hti.row) && + (!isShiftDown || !this.MultiSelect)) { - Debug.Assert(this.MultiSelect || this.individualSelectedCells.Count <= 1); - RemoveIndividuallySelectedCells(hti.col, hti.row); + select = false; } - if (this.MultiSelect) + if (select) { - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) + if ((!this.MultiSelect || !isControlDown) && !(this.MultiSelect && isShiftDown)) { - this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect] = true; + Debug.Assert(this.MultiSelect || this.individualSelectedCells.Count <= 1); + RemoveIndividuallySelectedCells(hti.col, hti.row); } - if (isShiftDown) + if (this.MultiSelect) { - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - if (this.ptAnchorCell.X == -1) + if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) { - return; + this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect] = true; } - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, hti.col, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, hti.row); - } - else - { - SetSelectedCellCore(hti.col, hti.row, true); - } - } - else - { - SetSelectedCellCore(hti.col, hti.row, true); - } - } - else - { - SetSelectedCellCore(hti.col, hti.row, false); - } - bool success = SetCurrentCellAddressCore(hti.col, hti.row, !isShiftDown, false, true); - Debug.Assert(success); - break; - } - - case DataGridViewSelectionMode.FullColumnSelect: - { - if (isControlDown && this.Columns[hti.col].Selected) - { - select = false; - } - if (select) - { - bool selectColumnRange = false; - this.trackColumn = hti.col; - this.trackColumnEdge = -1; - if (this.MultiSelect && - isShiftDown && - this.ptAnchorCell.X > -1 && - this.Columns[this.ptAnchorCell.X].Selected) - { - selectColumnRange = true; - } - if (!this.MultiSelect || !isControlDown || isShiftDown) - { - Debug.Assert(this.MultiSelect || this.selectedBandIndexes.Count <= 1); - int bandIndex = 0; - bool switchedToBulkPaint = false; - if (this.selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) - { - this.inBulkPaintCount++; - switchedToBulkPaint = true; - } - try - { - while (bandIndex < this.selectedBandIndexes.Count) + if (isShiftDown) { - if (this.selectedBandIndexes[bandIndex] != hti.col) - { - // deselect currently selected column - SetSelectedColumnCore(this.selectedBandIndexes[bandIndex], false); - } - else + int oldEdgeColumnIndex = this.ptCurrentCell.X; + int oldEdgeRowIndex = this.ptCurrentCell.Y; + if (this.ptAnchorCell.X == -1) { - bandIndex++; + return; } + UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, hti.col, + this.ptAnchorCell.Y, ref oldEdgeRowIndex, hti.row); } - } - finally - { - if (switchedToBulkPaint) + else { - ExitBulkPaint(-1, -1); + SetSelectedCellCore(hti.col, hti.row, true); } } - } - if (this.MultiSelect && this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) - { - this.dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] = true; - } - if (selectColumnRange) - { - if (this.Columns.DisplayInOrder(this.ptAnchorCell.X, hti.col)) - { - SelectColumnRange(this.ptAnchorCell.X, hti.col, true); - } else { - SelectColumnRange(hti.col, this.ptAnchorCell.X, true); + SetSelectedCellCore(hti.col, hti.row, true); } } - else if (!this.selectedBandIndexes.Contains(hti.col)) + else { - SetSelectedColumnCore(hti.col, true); + SetSelectedCellCore(hti.col, hti.row, false); } + bool success = SetCurrentCellAddressCore(hti.col, hti.row, !isShiftDown, false, true); + Debug.Assert(success); + break; } - else - { - Debug.Assert(this.selectedBandIndexes.Contains(hti.col)); - SetSelectedColumnCore(hti.col, false); - } - bool success = SetCurrentCellAddressCore(hti.col, hti.row, !isShiftDown, false, true); - Debug.Assert(success); - break; - } - case DataGridViewSelectionMode.ColumnHeaderSelect: - { - if (isControlDown && - (this.Columns[hti.col].Selected || IsSharedCellSelected(this.Rows.SharedRow(hti.row).Cells[hti.col], hti.row)) && - (!isShiftDown || !this.MultiSelect)) - { - select = false; - } - if (select) + case DataGridViewSelectionMode.FullColumnSelect: { - if (!this.MultiSelect) + if (isControlDown && this.Columns[hti.col].Selected) { - Debug.Assert(this.selectedBandIndexes.Count <= 1); - if (this.selectedBandIndexes.Count > 0) - { - SetSelectedColumnCore(this.selectedBandIndexes.HeadInt, false); - } - else - { - RemoveIndividuallySelectedCells(); - } - SetSelectedCellCore(hti.col, hti.row, true); + select = false; } - else + if (select) { - // this.MultiSelect == true - if (!isControlDown && !isShiftDown) + bool selectColumnRange = false; + this.trackColumn = hti.col; + this.trackColumnEdge = -1; + if (this.MultiSelect && + isShiftDown && + this.ptAnchorCell.X > -1 && + this.Columns[this.ptAnchorCell.X].Selected) { + selectColumnRange = true; + } + if (!this.MultiSelect || !isControlDown || isShiftDown) + { + Debug.Assert(this.MultiSelect || this.selectedBandIndexes.Count <= 1); + int bandIndex = 0; bool switchedToBulkPaint = false; if (this.selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) { @@ -12549,11 +12462,18 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo } try { - while (this.selectedBandIndexes.Count > 0) + while (bandIndex < this.selectedBandIndexes.Count) { - SetSelectedColumnCore(this.selectedBandIndexes.HeadInt, false); + if (this.selectedBandIndexes[bandIndex] != hti.col) + { + // deselect currently selected column + SetSelectedColumnCore(this.selectedBandIndexes[bandIndex], false); + } + else + { + bandIndex++; + } } - RemoveIndividuallySelectedCells(hti.col, hti.row); } finally { @@ -12563,164 +12483,154 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo } } } - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) + if (this.MultiSelect && this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) { - this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect] = true; + this.dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] = true; } - if (isShiftDown) + if (selectColumnRange) { - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - if (this.ptAnchorCell.X == -1) + if (this.Columns.DisplayInOrder(this.ptAnchorCell.X, hti.col)) { - return; + SelectColumnRange(this.ptAnchorCell.X, hti.col, true); + } + else + { + SelectColumnRange(hti.col, this.ptAnchorCell.X, true); } - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, hti.col, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, hti.row); - } - else - { - SetSelectedCellCore(hti.col, hti.row, true); - } - } - } - else - { - if (!this.MultiSelect) - { - Debug.Assert(this.selectedBandIndexes.Count <= 1); - if (this.selectedBandIndexes.Count > 0) - { - SetSelectedColumnCore(this.selectedBandIndexes.HeadInt, false); } - else + else if (!this.selectedBandIndexes.Contains(hti.col)) { - SetSelectedCellCore(hti.col, hti.row, false); + SetSelectedColumnCore(hti.col, true); } } else { - SetSelectedCellCore(hti.col, hti.row, false); + Debug.Assert(this.selectedBandIndexes.Contains(hti.col)); + SetSelectedColumnCore(hti.col, false); } + bool success = SetCurrentCellAddressCore(hti.col, hti.row, !isShiftDown, false, true); + Debug.Assert(success); + break; } - bool success = SetCurrentCellAddressCore(hti.col, hti.row, !isShiftDown, false, true); - Debug.Assert(success); - break; - } - case DataGridViewSelectionMode.FullRowSelect: - { - if (isControlDown && - ((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) != 0)) - { - select = false; - } - if (select) + case DataGridViewSelectionMode.ColumnHeaderSelect: { - bool selectRowRange = false; - this.trackRow = hti.row; - this.trackRowEdge = -1; - if (this.MultiSelect && - isShiftDown && - this.ptAnchorCell.Y > -1 && (this.Rows.GetRowState(this.ptAnchorCell.Y) & DataGridViewElementStates.Selected) != 0) + if (isControlDown && + (this.Columns[hti.col].Selected || IsSharedCellSelected(this.Rows.SharedRow(hti.row).Cells[hti.col], hti.row)) && + (!isShiftDown || !this.MultiSelect)) { - selectRowRange = true; + select = false; } - - if (!this.MultiSelect || !isControlDown || isShiftDown) + if (select) { - Debug.Assert(this.MultiSelect || this.selectedBandIndexes.Count <= 1); - int bandIndex = 0; - bool switchedToBulkPaint = false; - if (this.selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) + if (!this.MultiSelect) { - this.inBulkPaintCount++; - switchedToBulkPaint = true; + Debug.Assert(this.selectedBandIndexes.Count <= 1); + if (this.selectedBandIndexes.Count > 0) + { + SetSelectedColumnCore(this.selectedBandIndexes.HeadInt, false); + } + else + { + RemoveIndividuallySelectedCells(); + } + SetSelectedCellCore(hti.col, hti.row, true); } - try + else { - while (bandIndex < this.selectedBandIndexes.Count) + // this.MultiSelect == true + if (!isControlDown && !isShiftDown) { - if (this.selectedBandIndexes[bandIndex] != hti.row) + bool switchedToBulkPaint = false; + if (this.selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) { - // deselect currently selected row - SetSelectedRowCore(this.selectedBandIndexes[bandIndex], false); + this.inBulkPaintCount++; + switchedToBulkPaint = true; } - else + try { - bandIndex++; + while (this.selectedBandIndexes.Count > 0) + { + SetSelectedColumnCore(this.selectedBandIndexes.HeadInt, false); + } + RemoveIndividuallySelectedCells(hti.col, hti.row); + } + finally + { + if (switchedToBulkPaint) + { + ExitBulkPaint(-1, -1); + } } } - } - finally - { - if (switchedToBulkPaint) + if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) + { + this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect] = true; + } + if (isShiftDown) + { + int oldEdgeColumnIndex = this.ptCurrentCell.X; + int oldEdgeRowIndex = this.ptCurrentCell.Y; + if (this.ptAnchorCell.X == -1) + { + return; + } + UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, hti.col, + this.ptAnchorCell.Y, ref oldEdgeRowIndex, hti.row); + } + else { - ExitBulkPaint(-1, -1); + SetSelectedCellCore(hti.col, hti.row, true); } } } - if (this.MultiSelect && this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) - { - this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] = true; - } - if (selectRowRange) + else { - if (hti.row >= this.ptAnchorCell.Y) + if (!this.MultiSelect) { - SelectRowRange(this.ptAnchorCell.Y, hti.row, true); + Debug.Assert(this.selectedBandIndexes.Count <= 1); + if (this.selectedBandIndexes.Count > 0) + { + SetSelectedColumnCore(this.selectedBandIndexes.HeadInt, false); + } + else + { + SetSelectedCellCore(hti.col, hti.row, false); + } } else { - SelectRowRange(hti.row, this.ptAnchorCell.Y, true); + SetSelectedCellCore(hti.col, hti.row, false); } } - else if ((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) == 0) - { - Debug.Assert(this.selectedBandIndexes.Contains(hti.row) == - ((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) != 0)); - SetSelectedRowCore(hti.row, true); - } - } - else - { - Debug.Assert(this.selectedBandIndexes.Contains(hti.row)); - SetSelectedRowCore(hti.row, false); + bool success = SetCurrentCellAddressCore(hti.col, hti.row, !isShiftDown, false, true); + Debug.Assert(success); + break; } - bool success = SetCurrentCellAddressCore(hti.col, hti.row, !isShiftDown, false, true); - Debug.Assert(success); - break; - } - case DataGridViewSelectionMode.RowHeaderSelect: - { - if (isControlDown && - (((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) != 0) || - IsSharedCellSelected(this.Rows.SharedRow(hti.row).Cells[hti.col], hti.row)) && - (!isShiftDown || !this.MultiSelect)) - { - select = false; - } - if (select) + case DataGridViewSelectionMode.FullRowSelect: { - if (!this.MultiSelect) + if (isControlDown && + ((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) != 0)) { - Debug.Assert(this.selectedBandIndexes.Count <= 1); - if (this.selectedBandIndexes.Count > 0) - { - SetSelectedRowCore(this.selectedBandIndexes.HeadInt, false); - } - else - { - RemoveIndividuallySelectedCells(); - } - SetSelectedCellCore(hti.col, hti.row, true); + select = false; } - else + if (select) { - // this.MultiSelect == true - if (!isControlDown && !isShiftDown) + bool selectRowRange = false; + this.trackRow = hti.row; + this.trackRowEdge = -1; + if (this.MultiSelect && + isShiftDown && + this.ptAnchorCell.Y > -1 && (this.Rows.GetRowState(this.ptAnchorCell.Y) & DataGridViewElementStates.Selected) != 0) { + selectRowRange = true; + } + + if (!this.MultiSelect || !isControlDown || isShiftDown) + { + Debug.Assert(this.MultiSelect || this.selectedBandIndexes.Count <= 1); + int bandIndex = 0; bool switchedToBulkPaint = false; if (this.selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) { @@ -12729,11 +12639,18 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo } try { - while (this.selectedBandIndexes.Count > 0) + while (bandIndex < this.selectedBandIndexes.Count) { - SetSelectedRowCore(this.selectedBandIndexes.HeadInt, false); + if (this.selectedBandIndexes[bandIndex] != hti.row) + { + // deselect currently selected row + SetSelectedRowCore(this.selectedBandIndexes[bandIndex], false); + } + else + { + bandIndex++; + } } - RemoveIndividuallySelectedCells(hti.col, hti.row); } finally { @@ -12743,53 +12660,136 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo } } } - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) + if (this.MultiSelect && this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) { - this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect] = true; + this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] = true; } - if (isShiftDown) + if (selectRowRange) { - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - if (this.ptAnchorCell.X == -1) + if (hti.row >= this.ptAnchorCell.Y) { - return; + SelectRowRange(this.ptAnchorCell.Y, hti.row, true); + } + else + { + SelectRowRange(hti.row, this.ptAnchorCell.Y, true); } - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, hti.col, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, hti.row); } - else + else if ((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) == 0) { - SetSelectedCellCore(hti.col, hti.row, true); + Debug.Assert(this.selectedBandIndexes.Contains(hti.row) == + ((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) != 0)); + SetSelectedRowCore(hti.row, true); } } + else + { + Debug.Assert(this.selectedBandIndexes.Contains(hti.row)); + SetSelectedRowCore(hti.row, false); + } + bool success = SetCurrentCellAddressCore(hti.col, hti.row, !isShiftDown, false, true); + Debug.Assert(success); + break; } - else + + case DataGridViewSelectionMode.RowHeaderSelect: { - if (!this.MultiSelect) + if (isControlDown && + (((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) != 0) || + IsSharedCellSelected(this.Rows.SharedRow(hti.row).Cells[hti.col], hti.row)) && + (!isShiftDown || !this.MultiSelect)) + { + select = false; + } + if (select) { - Debug.Assert(this.selectedBandIndexes.Count <= 1); - if (this.selectedBandIndexes.Count > 0) + if (!this.MultiSelect) { - SetSelectedRowCore(this.selectedBandIndexes.HeadInt, false); + Debug.Assert(this.selectedBandIndexes.Count <= 1); + if (this.selectedBandIndexes.Count > 0) + { + SetSelectedRowCore(this.selectedBandIndexes.HeadInt, false); + } + else + { + RemoveIndividuallySelectedCells(); + } + SetSelectedCellCore(hti.col, hti.row, true); } else { - SetSelectedCellCore(hti.col, hti.row, false); + // this.MultiSelect == true + if (!isControlDown && !isShiftDown) + { + bool switchedToBulkPaint = false; + if (this.selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) + { + this.inBulkPaintCount++; + switchedToBulkPaint = true; + } + try + { + while (this.selectedBandIndexes.Count > 0) + { + SetSelectedRowCore(this.selectedBandIndexes.HeadInt, false); + } + RemoveIndividuallySelectedCells(hti.col, hti.row); + } + finally + { + if (switchedToBulkPaint) + { + ExitBulkPaint(-1, -1); + } + } + } + if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) + { + this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect] = true; + } + if (isShiftDown) + { + int oldEdgeColumnIndex = this.ptCurrentCell.X; + int oldEdgeRowIndex = this.ptCurrentCell.Y; + if (this.ptAnchorCell.X == -1) + { + return; + } + UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, hti.col, + this.ptAnchorCell.Y, ref oldEdgeRowIndex, hti.row); + } + else + { + SetSelectedCellCore(hti.col, hti.row, true); + } } } else { - SetSelectedCellCore(hti.col, hti.row, false); + if (!this.MultiSelect) + { + Debug.Assert(this.selectedBandIndexes.Count <= 1); + if (this.selectedBandIndexes.Count > 0) + { + SetSelectedRowCore(this.selectedBandIndexes.HeadInt, false); + } + else + { + SetSelectedCellCore(hti.col, hti.row, false); + } + } + else + { + SetSelectedCellCore(hti.col, hti.row, false); + } } - } - bool success = SetCurrentCellAddressCore(hti.col, hti.row, !isShiftDown, false, true); + bool success = SetCurrentCellAddressCore(hti.col, hti.row, !isShiftDown, false, true); - // Microsoft: SetCurrentCellAddressCore can fail if by navigating to a cell the list under the - // DataGridView changes. - // Debug.Assert(success); - break; - } + // Microsoft: SetCurrentCellAddressCore can fail if by navigating to a cell the list under the + // DataGridView changes. + // Debug.Assert(success); + break; + } } } finally @@ -12918,15 +12918,15 @@ protected virtual void OnCellMouseMove(DataGridViewCellMouseEventArgs e) case DataGridViewHitTestTypeInternal.ColumnHeaderLeft: case DataGridViewHitTestTypeInternal.ColumnHeaderRight: case DataGridViewHitTestTypeInternal.FirstColumnHeaderLeft: - { - Debug.Assert(!this.dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls]); - if (Math.Abs(this.ptMouseDownGridCoord.X - ptGridCoord.X) >= DataGridView.DragSize.Width || - Math.Abs(this.ptMouseDownGridCoord.Y - ptGridCoord.Y) >= DataGridView.DragSize.Height) { - BeginColumnRelocation(this.ptMouseDownGridCoord.X, this.ptMouseDownCell.X); + Debug.Assert(!this.dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls]); + if (Math.Abs(this.ptMouseDownGridCoord.X - ptGridCoord.X) >= DataGridView.DragSize.Width || + Math.Abs(this.ptMouseDownGridCoord.Y - ptGridCoord.Y) >= DataGridView.DragSize.Height) + { + BeginColumnRelocation(this.ptMouseDownGridCoord.X, this.ptMouseDownCell.X); + } + break; } - break; - } } } } @@ -12981,7 +12981,7 @@ protected internal virtual void OnCellPainting(DataGridViewCellPaintingEventArgs internal DataGridViewCellParsingEventArgs OnCellParsing(int rowIndex, int columnIndex, object formattedValue, Type valueType, DataGridViewCellStyle cellStyle) { - DataGridViewCellParsingEventArgs dgvcpe = new DataGridViewCellParsingEventArgs(rowIndex, columnIndex, + DataGridViewCellParsingEventArgs dgvcpe = new DataGridViewCellParsingEventArgs(rowIndex, columnIndex, formattedValue, valueType, cellStyle); @@ -13457,11 +13457,11 @@ protected virtual void OnCellValueNeeded(DataGridViewCellValueEventArgs e) { throw new ArgumentOutOfRangeException("e.RowIndex"); } -//#if DEBUG + //#if DEBUG // Some customer scenarios may result in accessing cell values while this.dataStoreAccessAllowed is false. This is bad practice, // but since we're late in Whidbey, throwing an exception would be destabilizing our internal customers. // Debug.Assert(this.dataStoreAccessAllowed); -//#endif + //#endif DataGridViewCellValueEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLVALUENEEDED] as DataGridViewCellValueEventHandler; if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) { @@ -13601,7 +13601,7 @@ internal void OnColumnCollectionChanged_PreNotification(CollectionChangeEventArg ResetUIState(false /*useRowShortcut*/, false /*computeVisibleRows*/); } - internal void OnColumnCollectionChanged_PostNotification(DataGridViewColumn dataGridViewColumn) + internal void OnColumnCollectionChanged_PostNotification(DataGridViewColumn dataGridViewColumn) { if (this.Columns.Count != 0 && this.Rows.Count == 0) { @@ -13667,7 +13667,7 @@ protected virtual void OnColumnDataPropertyNameChanged(DataGridViewColumnEventAr } DataGridViewColumnEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNDATAPROPERTYNAMECHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) { eh(this, e); } @@ -13894,7 +13894,7 @@ private void OnColumnGlobalAutoSize(int columnIndex) { AutoResizeColumnHeadersHeight(columnIndex, true /*fixedRowHeadersWidth*/, true /*fixedColumnWidth*/); } - if (!fixedHeight && + if (!fixedHeight && autoSizeColumnCriteriaInternal != DataGridViewAutoSizeColumnCriteriaInternal.None && autoSizeColumnCriteriaInternal != DataGridViewAutoSizeColumnCriteriaInternal.Fill) { @@ -13965,7 +13965,7 @@ private void OnColumnHeaderGlobalAutoSize(int columnIndex) protected virtual void OnColumnHeaderMouseClick(DataGridViewCellMouseEventArgs e) { if (e.Button == MouseButtons.Left && - this.SelectionMode != DataGridViewSelectionMode.FullColumnSelect && + this.SelectionMode != DataGridViewSelectionMode.FullColumnSelect && this.SelectionMode != DataGridViewSelectionMode.ColumnHeaderSelect) { DataGridViewColumn dataGridViewColumn = this.Columns[e.ColumnIndex]; @@ -13984,12 +13984,12 @@ protected virtual void OnColumnHeaderMouseClick(DataGridViewCellMouseEventArgs e } if ((this.DataSource == null) || - (this.DataSource != null && - (this.dataConnection.List is IBindingList) && - ((IBindingList) this.dataConnection.List).SupportsSorting && + (this.DataSource != null && + (this.dataConnection.List is IBindingList) && + ((IBindingList)this.dataConnection.List).SupportsSorting && dataGridViewColumn.IsDataBound)) { - Sort(dataGridViewColumn, direction); + Sort(dataGridViewColumn, direction); } } } @@ -14025,175 +14025,175 @@ private void OnColumnHeaderMouseDown(HitTestInfo hti, bool isShiftDown, bool isC case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: - { - bool select = true; - if (isControlDown && this.Columns[hti.col].Selected) { - select = false; - } - if (select) - { - int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); - if (rowIndex > -1 && hti.col != this.ptCurrentCell.X) - { - // Make sure we will be able to scroll into view - int oldCurrentCellX = this.ptCurrentCell.X; - int oldCurrentCellY = this.ptCurrentCell.Y; - if (!EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.CurrentCellChange, - DataGridViewValidateCellInternal.Always /*validateCell*/, - true /*fireCellLeave*/, - true /*fireCellEnter*/, - rowIndex != this.ptCurrentCell.Y /*fireRowLeave*/, - rowIndex != this.ptCurrentCell.Y /*fireRowEnter*/, - false /*fireLeave*/, - this.EditMode != DataGridViewEditMode.EditOnEnter /*keepFocus*/, - true /*resetCurrentCell*/, - false /*resetAnchorCell*/)) - { - // Just cancel operation silently instead of throwing InvalidOperationException - return; - } - if (rowIndex != oldCurrentCellY && oldCurrentCellY != -1) + bool select = true; + if (isControlDown && this.Columns[hti.col].Selected) + { + select = false; + } + if (select) + { + int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + if (rowIndex > -1 && hti.col != this.ptCurrentCell.X) { - DataGridViewCell dataGridViewCellTmp = null; - if (IsInnerCellOutOfBounds(oldCurrentCellX, oldCurrentCellY)) + // Make sure we will be able to scroll into view + int oldCurrentCellX = this.ptCurrentCell.X; + int oldCurrentCellY = this.ptCurrentCell.Y; + if (!EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.CurrentCellChange, + DataGridViewValidateCellInternal.Always /*validateCell*/, + true /*fireCellLeave*/, + true /*fireCellEnter*/, + rowIndex != this.ptCurrentCell.Y /*fireRowLeave*/, + rowIndex != this.ptCurrentCell.Y /*fireRowEnter*/, + false /*fireLeave*/, + this.EditMode != DataGridViewEditMode.EditOnEnter /*keepFocus*/, + true /*resetCurrentCell*/, + false /*resetAnchorCell*/)) { + // Just cancel operation silently instead of throwing InvalidOperationException return; } - if (OnRowValidating(ref dataGridViewCellTmp, oldCurrentCellX, oldCurrentCellY)) + if (rowIndex != oldCurrentCellY && oldCurrentCellY != -1) { - // Row validation was cancelled + DataGridViewCell dataGridViewCellTmp = null; if (IsInnerCellOutOfBounds(oldCurrentCellX, oldCurrentCellY)) { return; } - OnRowEnter(ref dataGridViewCellTmp, oldCurrentCellX, oldCurrentCellY, true /*canCreateNewRow*/, true /*validationFailureOccurred*/); + if (OnRowValidating(ref dataGridViewCellTmp, oldCurrentCellX, oldCurrentCellY)) + { + // Row validation was cancelled + if (IsInnerCellOutOfBounds(oldCurrentCellX, oldCurrentCellY)) + { + return; + } + OnRowEnter(ref dataGridViewCellTmp, oldCurrentCellX, oldCurrentCellY, true /*canCreateNewRow*/, true /*validationFailureOccurred*/); + if (IsInnerCellOutOfBounds(oldCurrentCellX, oldCurrentCellY)) + { + return; + } + OnCellEnter(ref dataGridViewCellTmp, oldCurrentCellX, oldCurrentCellY); + return; + } if (IsInnerCellOutOfBounds(oldCurrentCellX, oldCurrentCellY)) { return; } - OnCellEnter(ref dataGridViewCellTmp, oldCurrentCellX, oldCurrentCellY); - return; - } - if (IsInnerCellOutOfBounds(oldCurrentCellX, oldCurrentCellY)) - { - return; + OnRowValidated(ref dataGridViewCellTmp, oldCurrentCellX, oldCurrentCellY); } - OnRowValidated(ref dataGridViewCellTmp, oldCurrentCellX, oldCurrentCellY); } - } - if (IsColumnOutOfBounds(hti.col)) - { - return; - } + if (IsColumnOutOfBounds(hti.col)) + { + return; + } - bool selectColumnRange = false; - this.trackColumn = hti.col; - this.trackColumnEdge = -1; - if (this.MultiSelect && - isShiftDown && - this.ptAnchorCell.X > -1 && - this.Columns[this.ptAnchorCell.X].Selected) - { - selectColumnRange = true; - } - if (!this.MultiSelect || !isControlDown || isShiftDown) - { - Debug.Assert(this.MultiSelect || this.selectedBandIndexes.Count <= 1); - int bandIndex = 0; - bool switchedToBulkPaint = false; - if (this.selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) + bool selectColumnRange = false; + this.trackColumn = hti.col; + this.trackColumnEdge = -1; + if (this.MultiSelect && + isShiftDown && + this.ptAnchorCell.X > -1 && + this.Columns[this.ptAnchorCell.X].Selected) { - this.inBulkPaintCount++; - switchedToBulkPaint = true; + selectColumnRange = true; } - try + if (!this.MultiSelect || !isControlDown || isShiftDown) { - while (bandIndex < this.selectedBandIndexes.Count) + Debug.Assert(this.MultiSelect || this.selectedBandIndexes.Count <= 1); + int bandIndex = 0; + bool switchedToBulkPaint = false; + if (this.selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) + { + this.inBulkPaintCount++; + switchedToBulkPaint = true; + } + try { - if (this.selectedBandIndexes[bandIndex] != hti.col) + while (bandIndex < this.selectedBandIndexes.Count) { - // deselect currently selected column - SetSelectedColumnCore(this.selectedBandIndexes[bandIndex], false); + if (this.selectedBandIndexes[bandIndex] != hti.col) + { + // deselect currently selected column + SetSelectedColumnCore(this.selectedBandIndexes[bandIndex], false); + } + else + { + bandIndex++; + } + } + if (this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) + { + RemoveIndividuallySelectedCells(); } else { - bandIndex++; + Debug.Assert(this.individualSelectedCells.Count == 0); } } - if (this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) - { - RemoveIndividuallySelectedCells(); - } - else + finally { - Debug.Assert(this.individualSelectedCells.Count == 0); + if (switchedToBulkPaint) + { + ExitBulkPaint(-1, -1); + } } } - finally + if (this.MultiSelect && this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) { - if (switchedToBulkPaint) - { - ExitBulkPaint(-1, -1); - } + this.dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] = true; } - } - if (this.MultiSelect && this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) - { - this.dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] = true; - } - if (selectColumnRange) - { - if (this.Columns.DisplayInOrder(this.ptAnchorCell.X, hti.col)) + if (selectColumnRange) { - SelectColumnRange(this.ptAnchorCell.X, hti.col, true); + if (this.Columns.DisplayInOrder(this.ptAnchorCell.X, hti.col)) + { + SelectColumnRange(this.ptAnchorCell.X, hti.col, true); + } + else + { + SelectColumnRange(hti.col, this.ptAnchorCell.X, true); + } } - else + else if (!this.selectedBandIndexes.Contains(hti.col)) { - SelectColumnRange(hti.col, this.ptAnchorCell.X, true); + SetSelectedColumnCore(hti.col, true); } - } - else if (!this.selectedBandIndexes.Contains(hti.col)) - { - SetSelectedColumnCore(hti.col, true); - } - // set current cell to the top most visible cell in the column - if (rowIndex != -1) - { - if (hti.col != this.ptCurrentCell.X) + // set current cell to the top most visible cell in the column + if (rowIndex != -1) { - if (IsInnerCellOutOfBounds(hti.col, rowIndex)) + if (hti.col != this.ptCurrentCell.X) { - return; + if (IsInnerCellOutOfBounds(hti.col, rowIndex)) + { + return; + } + bool success = ScrollIntoView(hti.col, rowIndex, false); + Debug.Assert(success); + if (IsInnerCellOutOfBounds(hti.col, rowIndex)) + { + return; + } + success = SetCurrentCellAddressCore(hti.col, rowIndex, !isShiftDown, false, true); + Debug.Assert(success); } - bool success = ScrollIntoView(hti.col, rowIndex, false); - Debug.Assert(success); - if (IsInnerCellOutOfBounds(hti.col, rowIndex)) + else if (-1 != this.ptCurrentCell.X) { - return; + // Potentially have to give focus back to the current edited cell. + bool success = SetCurrentCellAddressCore(this.ptCurrentCell.X, this.ptCurrentCell.Y, false /*setAnchorCellAddress*/, false /*validateCurrentCell*/, false /*throughMouseClick*/); + Debug.Assert(success); } - success = SetCurrentCellAddressCore(hti.col, rowIndex, !isShiftDown, false, true); - Debug.Assert(success); } - else if (-1 != this.ptCurrentCell.X) + else { - // Potentially have to give focus back to the current edited cell. - bool success = SetCurrentCellAddressCore(this.ptCurrentCell.X, this.ptCurrentCell.Y, false /*setAnchorCellAddress*/, false /*validateCurrentCell*/, false /*throughMouseClick*/); - Debug.Assert(success); + Debug.Assert(this.CurrentCellAddress == new Point(-1, -1)); } } else { - Debug.Assert(this.CurrentCellAddress == new Point(-1, -1)); + Debug.Assert(this.selectedBandIndexes.Contains(hti.col)); + SetSelectedColumnCore(hti.col, false); } + break; } - else - { - Debug.Assert(this.selectedBandIndexes.Contains(hti.col)); - SetSelectedColumnCore(hti.col, false); - } - break; - } } } finally @@ -14206,7 +14206,7 @@ protected virtual void OnColumnHeadersBorderStyleChanged(EventArgs e) { PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); Invalidate(); - + EventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNHEADERSBORDERSTYLECHANGED] as EventHandler; if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) { @@ -14395,7 +14395,7 @@ protected virtual void OnColumnNameChanged(DataGridViewColumnEventArgs e) { InvalidateCellPrivate(dataGridViewColumn.Index, -1); - DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaInternal = (DataGridViewAutoSizeColumnCriteriaInternal) dataGridViewColumn.InheritedAutoSizeMode; + DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaInternal = (DataGridViewAutoSizeColumnCriteriaInternal)dataGridViewColumn.InheritedAutoSizeMode; DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaFiltered = autoSizeColumnCriteriaInternal & DataGridViewAutoSizeColumnCriteriaInternal.Header; bool fixedColumnWidth = autoSizeColumnCriteriaFiltered == 0 || !this.ColumnHeadersVisible; if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) @@ -14448,8 +14448,8 @@ private void OnColumnSelectMouseMove(HitTestInfo hti) Debug.Assert(hti.col >= 0); Debug.Assert(this.MultiSelect); - if (this.ptCurrentCell.X != -1 && - hti.col != this.ptCurrentCell.X && + if (this.ptCurrentCell.X != -1 && + hti.col != this.ptCurrentCell.X && !CommitEditForOperation(hti.col, this.ptCurrentCell.Y, true)) { // Return silently if validating/commit/abort failed @@ -14537,10 +14537,10 @@ private void OnColumnSelectMouseMove(HitTestInfo hti) { return; } - bool success = SetCurrentCellAddressCore(hti.col, - this.ptCurrentCell.Y, - false /*setAnchorCellAddress*/, - false /*validateCurrentCell*/, + bool success = SetCurrentCellAddressCore(hti.col, + this.ptCurrentCell.Y, + false /*setAnchorCellAddress*/, + false /*validateCurrentCell*/, false /*throughMouseClick*/); Debug.Assert(success); } @@ -14595,7 +14595,7 @@ protected virtual void OnColumnSortModeChanged(DataGridViewColumnEventArgs e) // this.sortedColumn = null; and InvalidateCellPrivate(e.Column.Index, -1); } // Potential resizing of the column headers and/or affected column. - DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaInternal = (DataGridViewAutoSizeColumnCriteriaInternal) dataGridViewColumn.InheritedAutoSizeMode; + DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaInternal = (DataGridViewAutoSizeColumnCriteriaInternal)dataGridViewColumn.InheritedAutoSizeMode; DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaFiltered = autoSizeColumnCriteriaInternal & DataGridViewAutoSizeColumnCriteriaInternal.Header; bool fixedColumnWidth = autoSizeColumnCriteriaFiltered == 0 || !this.ColumnHeadersVisible; if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) @@ -14691,8 +14691,8 @@ protected virtual void OnColumnStateChanged(DataGridViewColumnStateChangedEventA PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, true /*repositionEditingControl*/); - bool autoSizeRows = (((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0 || - ((((DataGridViewAutoSizeRowsModeInternal) this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) != 0 && + bool autoSizeRows = (((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0 || + ((((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) != 0 && this.RowHeadersVisible); bool autoSizeColumn = false; DataGridViewAutoSizeColumnMode autoSizeColumnMode = dataGridViewColumn.InheritedAutoSizeMode; @@ -14776,7 +14776,7 @@ protected virtual void OnColumnToolTipTextChanged(DataGridViewColumnEventArgs e) throw new ArgumentException(string.Format(SR.DataGridView_ColumnDoesNotBelongToDataGridView)); } DataGridViewColumnEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNTOOLTIPTEXTCHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) { eh(this, e); } @@ -14878,7 +14878,7 @@ protected virtual void OnCurrentCellChanged(EventArgs e) eh(this, e); } } - + protected virtual void OnCurrentCellDirtyStateChanged(EventArgs e) { if (this.RowHeadersVisible && this.ShowEditingIcon) @@ -15301,7 +15301,7 @@ protected virtual void OnEditingControlShowing(DataGridViewEditingControlShowing protected virtual void OnEditModeChanged(EventArgs e) { if (this.Focused && - this.EditMode == DataGridViewEditMode.EditOnEnter && + this.EditMode == DataGridViewEditMode.EditOnEnter && this.ptCurrentCell.X > -1 && !this.IsCurrentCellInEditMode) { @@ -15341,7 +15341,7 @@ protected override void OnEnabledChanged(EventArgs e) } } - protected override void OnEnter(EventArgs e) + protected override void OnEnter(EventArgs e) { if (this.editingControl != null && this.editingControl.ContainsFocus) { @@ -15358,7 +15358,7 @@ protected override void OnEnter(EventArgs e) } this.dataGridViewState1[DATAGRIDVIEWSTATE1_leavingWithTabKey] = false; - + if (this.ptCurrentCell.X > -1) { DataGridViewCell dataGridViewCell = null; @@ -15386,7 +15386,7 @@ protected override void OnEnter(EventArgs e) if (this.ptCurrentCell.X > -1 && !this.IsCurrentCellInEditMode) { - if (this.EditMode == DataGridViewEditMode.EditOnEnter || + if (this.EditMode == DataGridViewEditMode.EditOnEnter || (this.EditMode != DataGridViewEditMode.EditProgrammatically && this.CurrentCellInternal.EditType == null)) { BeginEditInternal(true /*selectAll*/); @@ -15407,7 +15407,7 @@ protected override void OnEnter(EventArgs e) InvalidateCellPrivate(this.ptCurrentCell.X /*columnIndex*/, this.ptCurrentCell.Y /*rowIndex*/); } } - + // Draw focus rectangle around the grid if (this.IsGridFocusRectangleEnabled()) { @@ -15419,13 +15419,13 @@ protected override void OnFontChanged(EventArgs e) { base.OnFontChanged(e); - if (GetAnyDisposingInHierarchy ()) + if (GetAnyDisposingInHierarchy()) { return; } // Change may be due to an ambient font change. - if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientColumnHeadersFont] && + if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientColumnHeadersFont] && this.ColumnHeadersDefaultCellStyle.Font != base.Font) { this.ColumnHeadersDefaultCellStyle.Font = base.Font; @@ -15537,12 +15537,12 @@ protected override void OnGotFocus(EventArgs e) } } - protected virtual void OnGridColorChanged(EventArgs e) + protected virtual void OnGridColorChanged(EventArgs e) { InvalidateInside(); EventHandler eh = this.Events[EVENT_DATAGRIDVIEWGRIDCOLORCHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) { eh(this, e); } @@ -15598,12 +15598,12 @@ internal void OnInsertedColumn_PostNotification(Point newCurrentCell) if (newCurrentCell.X != -1) { Debug.Assert(this.ptCurrentCell.X == -1); - bool success = SetAndSelectCurrentCellAddress(newCurrentCell.X, - newCurrentCell.Y, - true, - false, - false, - false /*clearSelection*/, + bool success = SetAndSelectCurrentCellAddress(newCurrentCell.X, + newCurrentCell.Y, + true, + false, + false, + false /*clearSelection*/, this.Columns.GetColumnCount(DataGridViewElementStates.Visible) == 1 /*forceCurrentCellSelection*/); Debug.Assert(success); } @@ -15635,12 +15635,12 @@ internal void OnInsertedRow_PostNotification(int rowIndex, Point newCurrentCell, if (lastInsertion && newCurrentCell.Y != -1) { Debug.Assert(this.ptCurrentCell.X == -1); - bool success = SetAndSelectCurrentCellAddress(newCurrentCell.X, - newCurrentCell.Y, - true, - false, - false, - false /*clearSelection*/, + bool success = SetAndSelectCurrentCellAddress(newCurrentCell.X, + newCurrentCell.Y, + true, + false, + false, + false /*clearSelection*/, this.Rows.GetRowCount(DataGridViewElementStates.Visible) == 1 /*forceCurrentCellSelection*/); Debug.Assert(success); } @@ -15820,11 +15820,11 @@ internal void OnInsertingColumn(int columnIndexInserted, DataGridViewColumn data } } - internal void OnInsertingRow(int rowIndexInserted, - DataGridViewRow dataGridViewRow, + internal void OnInsertingRow(int rowIndexInserted, + DataGridViewRow dataGridViewRow, DataGridViewElementStates rowState, - ref Point newCurrentCell, - bool firstInsertion, + ref Point newCurrentCell, + bool firstInsertion, int insertionCount, bool force) { @@ -15957,7 +15957,7 @@ internal void OnInsertingRows(int rowIndexInserted, DataGridViewRow[] dataGridVi } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnKeyDown(KeyEventArgs e) + protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (e.Handled) @@ -16005,16 +16005,16 @@ protected override void OnKeyDown(KeyEventArgs e) case Keys.Space: case Keys.Tab: case Keys.Up: - { - e.Handled = ProcessDataGridViewKey(e); - break; - } + { + e.Handled = ProcessDataGridViewKey(e); + break; + } } } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnKeyPress(KeyPressEventArgs e) + protected override void OnKeyPress(KeyPressEventArgs e) { base.OnKeyPress(e); if (e.Handled) @@ -16040,7 +16040,7 @@ protected override void OnKeyPress(KeyPressEventArgs e) } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnKeyUp(KeyEventArgs e) + protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); if (e.Handled) @@ -16072,7 +16072,7 @@ protected override void OnKeyUp(KeyEventArgs e) } } - protected override void OnLayout(LayoutEventArgs e) + protected override void OnLayout(LayoutEventArgs e) { if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlChanging]) { @@ -16091,7 +16091,7 @@ protected override void OnLayout(LayoutEventArgs e) } } - protected override void OnLeave(EventArgs e) + protected override void OnLeave(EventArgs e) { if (this.ptCurrentCell.X > -1 && !this.dataGridViewState1[DATAGRIDVIEWSTATE1_leavingWithTabKey]) { @@ -16136,15 +16136,15 @@ protected override void OnMouseClick(MouseEventArgs e) bool mouseClickRaised = false; if (!this.dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackColResize] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowResize] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize] && + !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed && + !this.dataGridViewOper[DATAGRIDVIEWOPER_trackColResize] && + !this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowResize] && + !this.dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize] && !this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize]) { HitTestInfo hti = HitTest(e.X, e.Y); - if (this.ptMouseDownCell.X == hti.col && + if (this.ptMouseDownCell.X == hti.col && this.ptMouseDownCell.Y == hti.row && (e.Button != MouseButtons.Left || this.ptMouseDownCell.X == -1 || @@ -16189,24 +16189,24 @@ protected override void OnMouseClick(MouseEventArgs e) case DataGridViewHitTestTypeInternal.ColumnHeaderLeft: case DataGridViewHitTestTypeInternal.ColumnHeaderRight: case DataGridViewHitTestTypeInternal.FirstColumnHeaderLeft: - { - Debug.Assert(dgvcme != null); - if (dgvcme.ColumnIndex < this.Columns.Count && dgvcme.RowIndex < this.Rows.Count) { - OnColumnHeaderMouseClick(dgvcme); + Debug.Assert(dgvcme != null); + if (dgvcme.ColumnIndex < this.Columns.Count && dgvcme.RowIndex < this.Rows.Count) + { + OnColumnHeaderMouseClick(dgvcme); + } + break; } - break; - } case DataGridViewHitTestTypeInternal.RowHeader: - { - Debug.Assert(dgvcme != null); - if (dgvcme.ColumnIndex < this.Columns.Count && dgvcme.RowIndex < this.Rows.Count) { - OnRowHeaderMouseClick(dgvcme); + Debug.Assert(dgvcme != null); + if (dgvcme.ColumnIndex < this.Columns.Count && dgvcme.RowIndex < this.Rows.Count) + { + OnRowHeaderMouseClick(dgvcme); + } + break; } - break; - } } } } @@ -16222,9 +16222,9 @@ protected override void OnMouseDoubleClick(MouseEventArgs e) base.OnMouseDoubleClick(e); if (!this.dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackColResize] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowResize] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize] && + !this.dataGridViewOper[DATAGRIDVIEWOPER_trackColResize] && + !this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowResize] && + !this.dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize] && !this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize]) { HitTestInfo hti = HitTest(e.X, e.Y); @@ -16232,8 +16232,8 @@ protected override void OnMouseDoubleClick(MouseEventArgs e) if (this.ptMouseDownCell.X == hti.col && this.ptMouseDownCell.Y == hti.row) { DataGridViewCellMouseEventArgs dgvcme = null; - if (hti.Type != DataGridViewHitTestType.None && - hti.Type != DataGridViewHitTestType.HorizontalScrollBar && + if (hti.Type != DataGridViewHitTestType.None && + hti.Type != DataGridViewHitTestType.HorizontalScrollBar && hti.Type != DataGridViewHitTestType.VerticalScrollBar) { int mouseX = e.X - hti.ColumnX; @@ -16253,76 +16253,76 @@ protected override void OnMouseDoubleClick(MouseEventArgs e) case DataGridViewHitTestTypeInternal.ColumnHeaderLeft: case DataGridViewHitTestTypeInternal.ColumnHeaderRight: case DataGridViewHitTestTypeInternal.FirstColumnHeaderLeft: - { - Debug.Assert(dgvcme != null); - if (dgvcme.ColumnIndex < this.Columns.Count && dgvcme.RowIndex < this.Rows.Count) { - OnColumnHeaderMouseDoubleClick(dgvcme); + Debug.Assert(dgvcme != null); + if (dgvcme.ColumnIndex < this.Columns.Count && dgvcme.RowIndex < this.Rows.Count) + { + OnColumnHeaderMouseDoubleClick(dgvcme); + } + break; } - break; - } case DataGridViewHitTestTypeInternal.ColumnResizeLeft: case DataGridViewHitTestTypeInternal.ColumnResizeRight: - { - int columnIndex = (hti.typeInternal == DataGridViewHitTestTypeInternal.ColumnResizeRight) ? hti.col : hti.adjacentCol; - if (columnIndex < this.Columns.Count) { - HandledMouseEventArgs hme = new HandledMouseEventArgs(e.Button, e.Clicks, e.X, e.Y, e.Delta, false /*defaultHandledValue*/); - DataGridViewColumnDividerDoubleClickEventArgs dgvcddce = new DataGridViewColumnDividerDoubleClickEventArgs(columnIndex, hme); - Debug.Assert(this.Columns[columnIndex].Resizable == DataGridViewTriState.True); - OnColumnDividerDoubleClick(dgvcddce); + int columnIndex = (hti.typeInternal == DataGridViewHitTestTypeInternal.ColumnResizeRight) ? hti.col : hti.adjacentCol; + if (columnIndex < this.Columns.Count) + { + HandledMouseEventArgs hme = new HandledMouseEventArgs(e.Button, e.Clicks, e.X, e.Y, e.Delta, false /*defaultHandledValue*/); + DataGridViewColumnDividerDoubleClickEventArgs dgvcddce = new DataGridViewColumnDividerDoubleClickEventArgs(columnIndex, hme); + Debug.Assert(this.Columns[columnIndex].Resizable == DataGridViewTriState.True); + OnColumnDividerDoubleClick(dgvcddce); + } + break; } - break; - } - + case DataGridViewHitTestTypeInternal.TopLeftHeaderResizeTop: case DataGridViewHitTestTypeInternal.TopLeftHeaderResizeBottom: case DataGridViewHitTestTypeInternal.ColumnHeadersResizeTop: case DataGridViewHitTestTypeInternal.ColumnHeadersResizeBottom: - { - HandledMouseEventArgs hme = new HandledMouseEventArgs(e.Button, e.Clicks, e.X, e.Y, e.Delta, false /*defaultHandledValue*/); - DataGridViewRowDividerDoubleClickEventArgs dgvrddce = new DataGridViewRowDividerDoubleClickEventArgs(-1, hme); - Debug.Assert(this.columnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing); - OnRowDividerDoubleClick(dgvrddce); - break; - } + { + HandledMouseEventArgs hme = new HandledMouseEventArgs(e.Button, e.Clicks, e.X, e.Y, e.Delta, false /*defaultHandledValue*/); + DataGridViewRowDividerDoubleClickEventArgs dgvrddce = new DataGridViewRowDividerDoubleClickEventArgs(-1, hme); + Debug.Assert(this.columnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing); + OnRowDividerDoubleClick(dgvrddce); + break; + } case DataGridViewHitTestTypeInternal.RowHeader: - { - Debug.Assert(dgvcme != null); - if (dgvcme.ColumnIndex < this.Columns.Count && dgvcme.RowIndex < this.Rows.Count) { - OnRowHeaderMouseDoubleClick(dgvcme); + Debug.Assert(dgvcme != null); + if (dgvcme.ColumnIndex < this.Columns.Count && dgvcme.RowIndex < this.Rows.Count) + { + OnRowHeaderMouseDoubleClick(dgvcme); + } + break; } - break; - } case DataGridViewHitTestTypeInternal.RowResizeBottom: case DataGridViewHitTestTypeInternal.RowResizeTop: - { - int rowIndex = (hti.typeInternal == DataGridViewHitTestTypeInternal.RowResizeBottom) ? hti.row : hti.adjacentRow; - if (rowIndex < this.Rows.Count) { - HandledMouseEventArgs hme = new HandledMouseEventArgs(e.Button, e.Clicks, e.X, e.Y, e.Delta, false /*defaultHandledValue*/); - DataGridViewRowDividerDoubleClickEventArgs dgvrddce = new DataGridViewRowDividerDoubleClickEventArgs(rowIndex, hme); - Debug.Assert(this.Rows[rowIndex].Resizable == DataGridViewTriState.True); - OnRowDividerDoubleClick(dgvrddce); + int rowIndex = (hti.typeInternal == DataGridViewHitTestTypeInternal.RowResizeBottom) ? hti.row : hti.adjacentRow; + if (rowIndex < this.Rows.Count) + { + HandledMouseEventArgs hme = new HandledMouseEventArgs(e.Button, e.Clicks, e.X, e.Y, e.Delta, false /*defaultHandledValue*/); + DataGridViewRowDividerDoubleClickEventArgs dgvrddce = new DataGridViewRowDividerDoubleClickEventArgs(rowIndex, hme); + Debug.Assert(this.Rows[rowIndex].Resizable == DataGridViewTriState.True); + OnRowDividerDoubleClick(dgvrddce); + } + break; } - break; - } case DataGridViewHitTestTypeInternal.TopLeftHeaderResizeLeft: case DataGridViewHitTestTypeInternal.TopLeftHeaderResizeRight: case DataGridViewHitTestTypeInternal.RowHeadersResizeLeft: case DataGridViewHitTestTypeInternal.RowHeadersResizeRight: - { - HandledMouseEventArgs hme = new HandledMouseEventArgs(e.Button, e.Clicks, e.X, e.Y, e.Delta, false /*defaultHandledValue*/); - DataGridViewColumnDividerDoubleClickEventArgs dgvcddce = new DataGridViewColumnDividerDoubleClickEventArgs(-1, hme); - Debug.Assert(this.rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing); - OnColumnDividerDoubleClick(dgvcddce); - break; - } + { + HandledMouseEventArgs hme = new HandledMouseEventArgs(e.Button, e.Clicks, e.X, e.Y, e.Delta, false /*defaultHandledValue*/); + DataGridViewColumnDividerDoubleClickEventArgs dgvcddce = new DataGridViewColumnDividerDoubleClickEventArgs(-1, hme); + Debug.Assert(this.rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing); + OnColumnDividerDoubleClick(dgvcddce); + break; + } } } } @@ -16352,8 +16352,8 @@ protected override void OnMouseDown(MouseEventArgs e) HitTestInfo hti = HitTest(e.X, e.Y); - if (hti.Type != DataGridViewHitTestType.None && - hti.Type != DataGridViewHitTestType.HorizontalScrollBar && + if (hti.Type != DataGridViewHitTestType.None && + hti.Type != DataGridViewHitTestType.HorizontalScrollBar && hti.Type != DataGridViewHitTestType.VerticalScrollBar) { this.ptMouseDownCell.X = hti.col; @@ -16371,8 +16371,8 @@ protected override void OnMouseDown(MouseEventArgs e) protected override void OnMouseEnter(EventArgs e) { - if (!this.dataGridViewState2[DATAGRIDVIEWSTATE2_mouseOverRemovedEditingCtrl] && - !this.dataGridViewState2[DATAGRIDVIEWSTATE2_mouseOverRemovedEditingPanel] && + if (!this.dataGridViewState2[DATAGRIDVIEWSTATE2_mouseOverRemovedEditingCtrl] && + !this.dataGridViewState2[DATAGRIDVIEWSTATE2_mouseOverRemovedEditingPanel] && this.dataGridViewState2[DATAGRIDVIEWSTATE2_mouseEnterExpected] && !this.toolTipControl.Activated) { @@ -16384,7 +16384,7 @@ protected override void OnMouseEnter(EventArgs e) this.dataGridViewState2[DATAGRIDVIEWSTATE2_mouseEnterExpected] = false; } - protected override void OnMouseLeave(EventArgs e) + protected override void OnMouseLeave(EventArgs e) { // when the mouse leaves the dataGridView control, reset the cursor to the previously cached one if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet]) @@ -16422,7 +16422,7 @@ protected override void OnMouseLeave(EventArgs e) } } - protected override void OnMouseMove(MouseEventArgs e) + protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); @@ -16431,7 +16431,7 @@ protected override void OnMouseMove(MouseEventArgs e) UpdateMouseEnteredCell(hti, e); // We need to give UI feedback when the user is resizing a column - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackColResize]) + if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackColResize]) { MoveRowHeadersOrColumnResize(e.X); } @@ -16443,11 +16443,11 @@ protected override void OnMouseMove(MouseEventArgs e) { MoveColumnRelocation(e, hti); } - else if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize]) + else if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize]) { MoveColumnHeadersOrRowResize(e); } - else if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize]) + else if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize]) { MoveRowHeadersOrColumnResize(e.X); } @@ -16459,7 +16459,7 @@ protected override void OnMouseMove(MouseEventArgs e) hti.typeInternal == DataGridViewHitTestTypeInternal.TopLeftHeaderResizeRight || hti.typeInternal == DataGridViewHitTestTypeInternal.ColumnResizeRight || hti.typeInternal == DataGridViewHitTestTypeInternal.RowHeadersResizeLeft || - hti.typeInternal == DataGridViewHitTestTypeInternal.RowHeadersResizeRight) && + hti.typeInternal == DataGridViewHitTestTypeInternal.RowHeadersResizeRight) && !this.dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize] && !this.dataGridViewOper[DATAGRIDVIEWOPER_trackColRelocation] && !this.dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] && @@ -16519,8 +16519,8 @@ protected override void OnMouseMove(MouseEventArgs e) this.CursorInternal = this.oldCursor; } - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] || - this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] || + if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] || + this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] || this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect]) { int xOffset, yOffset, mouseX = e.X, mouseY = e.Y; @@ -16562,8 +16562,8 @@ protected override void OnMouseMove(MouseEventArgs e) } if (/*!this.dataGridViewState1[DATAGRIDVIEWSTATE1_scrolledSinceMouseDown] && */ - hti.Type != DataGridViewHitTestType.None && - hti.Type != DataGridViewHitTestType.HorizontalScrollBar && + hti.Type != DataGridViewHitTestType.None && + hti.Type != DataGridViewHitTestType.HorizontalScrollBar && hti.Type != DataGridViewHitTestType.VerticalScrollBar) { if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] && hti.col >= 0) @@ -16597,7 +16597,7 @@ protected override void OnMouseMove(MouseEventArgs e) } } - protected override void OnMouseUp(MouseEventArgs e) + protected override void OnMouseUp(MouseEventArgs e) { if (!this.dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls]) { @@ -16717,7 +16717,7 @@ protected override void OnMouseWheel(MouseEventArgs e) bool verticalScroll = ((ModifierKeys & Keys.Control) == 0); - ScrollBar sb = (verticalScroll ? (ScrollBar) this.vertScrollBar : (ScrollBar) this.horizScrollBar); + ScrollBar sb = (verticalScroll ? (ScrollBar)this.vertScrollBar : (ScrollBar)this.horizScrollBar); if (!sb.Visible || !sb.Enabled) { @@ -16745,15 +16745,15 @@ protected override void OnMouseWheel(MouseEventArgs e) if (verticalScroll) { this.cumulativeVerticalWheelDelta += e.Delta; - partialNotches = (float) this.cumulativeVerticalWheelDelta / (float) NativeMethods.WHEEL_DELTA; + partialNotches = (float)this.cumulativeVerticalWheelDelta / (float)NativeMethods.WHEEL_DELTA; } else { this.cumulativeHorizontalWheelDelta += e.Delta; - partialNotches = (float) this.cumulativeHorizontalWheelDelta / (float) NativeMethods.WHEEL_DELTA; + partialNotches = (float)this.cumulativeHorizontalWheelDelta / (float)NativeMethods.WHEEL_DELTA; } - int fullNotches = (int) partialNotches; + int fullNotches = (int)partialNotches; if (wheelScrollLines == -1) { @@ -16761,7 +16761,7 @@ protected override void OnMouseWheel(MouseEventArgs e) if (fullNotches != 0) { if (this.ptCurrentCell.X >= 0 && - !CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, + !CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, false /*forCurrentCellChange*/, false /*forCurrentRowChange*/)) { // Could not commit edited cell value @@ -16798,11 +16798,11 @@ protected override void OnMouseWheel(MouseEventArgs e) else { // Evaluate number of bands to scroll - int scrollBands = (int) ((float) wheelScrollLines * partialNotches); + int scrollBands = (int)((float)wheelScrollLines * partialNotches); if (scrollBands != 0) { if (this.ptCurrentCell.X >= 0 && - !CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, + !CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, false /*forCurrentCellChange*/, false /*forCurrentRowChange*/)) { // Could not commit edited cell value @@ -16825,7 +16825,7 @@ protected override void OnMouseWheel(MouseEventArgs e) } else { - this.cumulativeVerticalWheelDelta -= (int) ((float) scrollBands * ((float) NativeMethods.WHEEL_DELTA / (float) wheelScrollLines)); + this.cumulativeVerticalWheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); } } else @@ -16850,7 +16850,7 @@ protected override void OnMouseWheel(MouseEventArgs e) } else { - this.cumulativeVerticalWheelDelta -= (int) ((float) scrollBands * ((float) NativeMethods.WHEEL_DELTA / (float) wheelScrollLines)); + this.cumulativeVerticalWheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); } } } @@ -16879,7 +16879,7 @@ protected override void OnMouseWheel(MouseEventArgs e) } else { - this.cumulativeHorizontalWheelDelta -= (int) ((float) scrollBands * ((float) NativeMethods.WHEEL_DELTA / (float) wheelScrollLines)); + this.cumulativeHorizontalWheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); } } } @@ -16914,12 +16914,12 @@ protected virtual void OnNewRowNeeded(DataGridViewRowEventArgs e) } } - protected override void OnPaint(PaintEventArgs e) + protected override void OnPaint(PaintEventArgs e) { - try + try { // We can't paint if we are disposed. - if (this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] || this.IsDisposed) + if (this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] || this.IsDisposed) { return; } @@ -16976,9 +16976,9 @@ protected override void OnPaint(PaintEventArgs e) } catch (Exception ex) { - #if DEBUG - Debug.Fail("DataGridView.OnPaint exception: " + ex.Message + " stack trace " + ex.StackTrace); - #endif +#if DEBUG + Debug.Fail("DataGridView.OnPaint exception: " + ex.Message + " stack trace " + ex.StackTrace); +#endif if (ClientUtils.IsCriticalException(ex)) { throw; @@ -17106,7 +17106,7 @@ internal override void OnParentBecameInvisible() OnVisibleChangedPrivate(); } } - + protected virtual void OnReadOnlyChanged(EventArgs e) { EventHandler eh = this.Events[EVENT_DATAGRIDVIEWREADONLYCHANGED] as EventHandler; @@ -17120,8 +17120,8 @@ protected virtual void OnReadOnlyChanged(EventArgs e) if (!this.ReadOnly && this.ptCurrentCell.X != -1 && ColumnEditable(this.ptCurrentCell.X) && - !this.IsCurrentCellInEditMode && - (this.EditMode == DataGridViewEditMode.EditOnEnter || + !this.IsCurrentCellInEditMode && + (this.EditMode == DataGridViewEditMode.EditOnEnter || (this.EditMode != DataGridViewEditMode.EditProgrammatically && this.CurrentCellInternal.EditType == null)) && !this.Rows[this.ptCurrentCell.Y].Cells[this.ptCurrentCell.X].ReadOnly) // Unshares the row { @@ -17158,12 +17158,12 @@ internal void OnRemovedColumn_PostNotification(DataGridViewColumn dataGridViewCo if (newCurrentCell.X != -1) { Debug.Assert(this.ptCurrentCell.X == -1); - bool success = SetAndSelectCurrentCellAddress(newCurrentCell.X, - newCurrentCell.Y, - true, - false, - false, - false /*clearSelection*/, + bool success = SetAndSelectCurrentCellAddress(newCurrentCell.X, + newCurrentCell.Y, + true, + false, + false, + false /*clearSelection*/, false /*forceCurrentCellSelection*/); Debug.Assert(success); } @@ -17183,7 +17183,7 @@ internal void OnRemovedColumn_PostNotification(DataGridViewColumn dataGridViewCo DataGridViewAutoSizeColumnMode autoSizeColumnMode = dataGridViewColumn.GetInheritedAutoSizeMode(this); Debug.Assert(autoSizeColumnMode != DataGridViewAutoSizeColumnMode.NotSet); if (autoSizeColumnMode != DataGridViewAutoSizeColumnMode.None && - autoSizeColumnMode != DataGridViewAutoSizeColumnMode.Fill && + autoSizeColumnMode != DataGridViewAutoSizeColumnMode.Fill && dataGridViewColumn.ThicknessInternal != dataGridViewColumn.CachedThickness) { dataGridViewColumn.ThicknessInternal = Math.Max(dataGridViewColumn.MinimumWidth, dataGridViewColumn.CachedThickness); @@ -17208,10 +17208,10 @@ internal void OnRemovedRow_PostNotification(DataGridViewRow dataGridViewRow, Poi if (newCurrentCell.Y != -1) { Debug.Assert(this.ptCurrentCell.X == -1); - bool success = SetAndSelectCurrentCellAddress(newCurrentCell.X, - newCurrentCell.Y, - true /*setAnchorCellAddress*/, - false /*validateCurrentCell*/, + bool success = SetAndSelectCurrentCellAddress(newCurrentCell.X, + newCurrentCell.Y, + true /*setAnchorCellAddress*/, + false /*validateCurrentCell*/, false /*throughMouseClick*/, false /*clearSelection*/, false /*forceCurrentCellSelection*/); @@ -17293,8 +17293,8 @@ internal void OnRemovingColumn(DataGridViewColumn dataGridViewColumn, out Point if (columnIndex == this.ptCurrentCell.X) { DataGridViewColumn dataGridViewColumnNext = this.Columns.GetNextColumn( - this.Columns[columnIndex], - DataGridViewElementStates.Visible, + this.Columns[columnIndex], + DataGridViewElementStates.Visible, DataGridViewElementStates.None); if (dataGridViewColumnNext != null) { @@ -17310,8 +17310,8 @@ internal void OnRemovingColumn(DataGridViewColumn dataGridViewColumn, out Point else { DataGridViewColumn dataGridViewColumnPrevious = this.Columns.GetPreviousColumn( - this.Columns[columnIndex], - DataGridViewElementStates.Visible, + this.Columns[columnIndex], + DataGridViewElementStates.Visible, DataGridViewElementStates.None); if (dataGridViewColumnPrevious != null) { @@ -17396,7 +17396,7 @@ internal void OnRemovingColumn(DataGridViewColumn dataGridViewColumn, out Point // If the column being removed is the sorted column and it is also the dataBound column // then see if there is another dataBound column which has the same property name as the sorted column. // If so, then make that dataGridViewColumn the sorted column in the data grid view. - for (int i = 0; i < this.Columns.Count; i ++) + for (int i = 0; i < this.Columns.Count; i++) { if (dataGridViewColumn != this.Columns[i] && this.Columns[i].SortMode != DataGridViewColumnSortMode.NotSortable && @@ -17475,7 +17475,7 @@ internal void OnRemovingColumn(DataGridViewColumn dataGridViewColumn, out Point columnEntries--; raiseSelectionChanged = true; } - else + else { if (columnIndex < columnIndexSelected) { @@ -17497,7 +17497,7 @@ internal void OnRemovingRow(int rowIndexDeleted, out Point newCurrentCell, bool // if force is true, the row needs to be deleted no matter what. The underlying data row was already deleted. Debug.Assert(rowIndexDeleted >= 0 && rowIndexDeleted < this.Rows.Count); - + this.dataGridViewState1[DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell] = false; newCurrentCell = new Point(-1, -1); @@ -17512,7 +17512,7 @@ internal void OnRemovingRow(int rowIndexDeleted, out Point newCurrentCell, bool if (rowIndexPrevious > -1 && this.AllowUserToAddRowsInternal) { Debug.Assert(this.newRowIndex != -1); - Debug.Assert(this.newRowIndex == this.Rows.Count-1); + Debug.Assert(this.newRowIndex == this.Rows.Count - 1); if (rowIndexNext > -1 && rowIndexNext < this.Rows.Count - 1) { newY = rowIndexNext - 1; @@ -17537,7 +17537,7 @@ internal void OnRemovingRow(int rowIndexDeleted, out Point newCurrentCell, bool this.IsCurrentCellDirtyInternal = false; this.IsCurrentRowDirtyInternal = false; } - else + else { Debug.Assert(rowIndexDeleted < this.ptCurrentCell.Y); newY = this.ptCurrentCell.Y - 1; @@ -17582,7 +17582,7 @@ internal void OnRemovingRow(int rowIndexDeleted, out Point newCurrentCell, bool this.selectedBandIndexes.RemoveAt(rowEntry); rowEntries--; } - else + else { if (rowIndexDeleted < rowIndex) { @@ -17677,7 +17677,7 @@ internal void OnReplacingCell(DataGridViewRow dataGridViewRow, int columnIndex) } } - protected override void OnResize(EventArgs e) + protected override void OnResize(EventArgs e) { int borderWidth = this.BorderWidth; Rectangle right; @@ -17704,7 +17704,7 @@ protected override void OnResize(EventArgs e) Rectangle newGridFocusRectangle = this.DisplayRectangle; newGridFocusRectangle.Inflate(1 - borderWidth - FOCUS_RECT_OFFSET, 1 - borderWidth - FOCUS_RECT_OFFSET); - if (newClientRectangle.Width != oldClientRectangle.Width) + if (newClientRectangle.Width != oldClientRectangle.Width) { Invalidate(right); right = new Rectangle(newClientRectangle.X + newClientRectangle.Width - borderWidth, @@ -17713,7 +17713,7 @@ protected override void OnResize(EventArgs e) newClientRectangle.Height); Invalidate(right); } - if (newClientRectangle.Height != oldClientRectangle.Height) + if (newClientRectangle.Height != oldClientRectangle.Height) { Invalidate(bottom); bottom = new Rectangle(newClientRectangle.X, @@ -17764,10 +17764,10 @@ protected override void OnRightToLeftChanged(EventArgs e) PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); } - internal void OnRowCollectionChanged_PostNotification(bool recreateNewRow, - bool allowSettingCurrentCell, - CollectionChangeAction cca, - DataGridViewRow dataGridViewRow, + internal void OnRowCollectionChanged_PostNotification(bool recreateNewRow, + bool allowSettingCurrentCell, + CollectionChangeAction cca, + DataGridViewRow dataGridViewRow, int rowIndex) { if (recreateNewRow && @@ -17803,7 +17803,7 @@ internal void OnRowCollectionChanged_PostNotification(bool recreateNewRow, case CollectionChangeAction.Remove: invalidatePreferredSizeCache = dataGridViewRow.DataGridView == null && dataGridViewRow.Visible; break; - // case CollectionChangeAction.Refresh: invalidatePreferredSizeCache stays true + // case CollectionChangeAction.Refresh: invalidatePreferredSizeCache stays true } if (invalidatePreferredSizeCache) { @@ -17950,12 +17950,12 @@ private void OnRowEnter(ref DataGridViewCell dataGridViewCell, int columnIndex, OnDefaultValuesNeeded(dgvre); InvalidateRowPrivate(this.newRowIndex); } - #if DEBUG +#if DEBUG else { Debug.Assert(this.newRowIndex == -1, "newRowIndex and AllowUserToAddRowsInternal became out of sync"); } - #endif // +#endif // } } @@ -18215,207 +18215,207 @@ private void OnRowHeaderMouseDown(HitTestInfo hti, bool isShiftDown, bool isCont case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: - { - bool select = true; - if (isControlDown && - ((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) != 0)) { - select = false; - } - if (select) - { - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); - if (dataGridViewColumn != null && hti.row != this.ptCurrentCell.Y) - { - int oldCurrentCellX = this.ptCurrentCell.X; - int oldCurrentCellY = this.ptCurrentCell.Y; - // Make sure we will be able to scroll into view - if (!EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.CurrentCellChange, - DataGridViewValidateCellInternal.Always /*validateCell*/, - true /*fireCellLeave*/, - true /*fireCellEnter*/, - hti.row != this.ptCurrentCell.Y /*fireRowLeave*/, - hti.row != this.ptCurrentCell.Y /*fireRowEnter*/, - false /*fireLeave*/, - this.EditMode != DataGridViewEditMode.EditOnEnter /*keepFocus*/, - true /*resetCurrentCell*/, - false /*resetAnchorCell*/)) - { - // Just cancel operation silently instead of throwing InvalidOperationException - return; - } - if (oldCurrentCellY != -1) + bool select = true; + if (isControlDown && + ((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) != 0)) + { + select = false; + } + if (select) + { + DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + if (dataGridViewColumn != null && hti.row != this.ptCurrentCell.Y) { - DataGridViewCell dataGridViewCellTmp = null; - if (IsInnerCellOutOfBounds(oldCurrentCellX, oldCurrentCellY)) + int oldCurrentCellX = this.ptCurrentCell.X; + int oldCurrentCellY = this.ptCurrentCell.Y; + // Make sure we will be able to scroll into view + if (!EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.CurrentCellChange, + DataGridViewValidateCellInternal.Always /*validateCell*/, + true /*fireCellLeave*/, + true /*fireCellEnter*/, + hti.row != this.ptCurrentCell.Y /*fireRowLeave*/, + hti.row != this.ptCurrentCell.Y /*fireRowEnter*/, + false /*fireLeave*/, + this.EditMode != DataGridViewEditMode.EditOnEnter /*keepFocus*/, + true /*resetCurrentCell*/, + false /*resetAnchorCell*/)) { + // Just cancel operation silently instead of throwing InvalidOperationException return; } - if (OnRowValidating(ref dataGridViewCellTmp, oldCurrentCellX, oldCurrentCellY)) + if (oldCurrentCellY != -1) { - // Row validation was cancelled + DataGridViewCell dataGridViewCellTmp = null; if (IsInnerCellOutOfBounds(oldCurrentCellX, oldCurrentCellY)) { return; } - OnRowEnter(ref dataGridViewCellTmp, oldCurrentCellX, oldCurrentCellY, true /*canCreateNewRow*/, true /*validationFailureOccurred*/); + if (OnRowValidating(ref dataGridViewCellTmp, oldCurrentCellX, oldCurrentCellY)) + { + // Row validation was cancelled + if (IsInnerCellOutOfBounds(oldCurrentCellX, oldCurrentCellY)) + { + return; + } + OnRowEnter(ref dataGridViewCellTmp, oldCurrentCellX, oldCurrentCellY, true /*canCreateNewRow*/, true /*validationFailureOccurred*/); + if (IsInnerCellOutOfBounds(oldCurrentCellX, oldCurrentCellY)) + { + return; + } + OnCellEnter(ref dataGridViewCellTmp, oldCurrentCellX, oldCurrentCellY); + return; + } if (IsInnerCellOutOfBounds(oldCurrentCellX, oldCurrentCellY)) { return; } - OnCellEnter(ref dataGridViewCellTmp, oldCurrentCellX, oldCurrentCellY); - return; - } - if (IsInnerCellOutOfBounds(oldCurrentCellX, oldCurrentCellY)) - { - return; - } - OnRowValidated(ref dataGridViewCellTmp, oldCurrentCellX, oldCurrentCellY); + OnRowValidated(ref dataGridViewCellTmp, oldCurrentCellX, oldCurrentCellY); - // Row validation was not cancelled, but operation needs to be re-evaluated. - if (hti.row >= this.Rows.Count) - { - int lastVisibleRowIndex = this.Rows.GetLastRow(DataGridViewElementStates.Visible); - if (this.ptCurrentCell.X == -1 && lastVisibleRowIndex != -1) + // Row validation was not cancelled, but operation needs to be re-evaluated. + if (hti.row >= this.Rows.Count) { - // CurrentCell was reset because commit deleted row(s). - // Since the user wants to select a row, we don't want to - // end up with no CurrentCell. We pick the last visible - // row in the grid which may be the 'new row'. - if (IsColumnOutOfBounds(oldCurrentCellX)) + int lastVisibleRowIndex = this.Rows.GetLastRow(DataGridViewElementStates.Visible); + if (this.ptCurrentCell.X == -1 && lastVisibleRowIndex != -1) { - return; + // CurrentCell was reset because commit deleted row(s). + // Since the user wants to select a row, we don't want to + // end up with no CurrentCell. We pick the last visible + // row in the grid which may be the 'new row'. + if (IsColumnOutOfBounds(oldCurrentCellX)) + { + return; + } + bool success = SetAndSelectCurrentCellAddress(oldCurrentCellX, + lastVisibleRowIndex, + true, + false, + false, + false /*clearSelection*/, + false /*forceCurrentCellSelection*/); + Debug.Assert(success); } - bool success = SetAndSelectCurrentCellAddress(oldCurrentCellX, - lastVisibleRowIndex, - true, - false, - false, - false /*clearSelection*/, - false /*forceCurrentCellSelection*/); - Debug.Assert(success); + return; + } + else if ((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Visible) == 0) + { + return; } - return; - } - else if ((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Visible) == 0) - { - return; } } - } - bool selectRowRange = false; - this.trackRow = hti.row; - this.trackRowEdge = -1; - if (this.MultiSelect && - isShiftDown && - this.ptAnchorCell.Y > -1 && - (this.Rows.GetRowState(this.ptAnchorCell.Y) & DataGridViewElementStates.Selected) != 0) - { - selectRowRange = true; - } - if (!this.MultiSelect || !isControlDown || isShiftDown) - { - Debug.Assert(this.MultiSelect || this.selectedBandIndexes.Count <= 1); - int bandIndex = 0; - bool switchedToBulkPaint = false; - if (this.selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) + bool selectRowRange = false; + this.trackRow = hti.row; + this.trackRowEdge = -1; + if (this.MultiSelect && + isShiftDown && + this.ptAnchorCell.Y > -1 && + (this.Rows.GetRowState(this.ptAnchorCell.Y) & DataGridViewElementStates.Selected) != 0) { - this.inBulkPaintCount++; - switchedToBulkPaint = true; + selectRowRange = true; } - try + if (!this.MultiSelect || !isControlDown || isShiftDown) { - while (bandIndex < this.selectedBandIndexes.Count) + Debug.Assert(this.MultiSelect || this.selectedBandIndexes.Count <= 1); + int bandIndex = 0; + bool switchedToBulkPaint = false; + if (this.selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) + { + this.inBulkPaintCount++; + switchedToBulkPaint = true; + } + try { - if (this.selectedBandIndexes[bandIndex] != hti.row) + while (bandIndex < this.selectedBandIndexes.Count) { - // deselect currently selected row - SetSelectedRowCore(this.selectedBandIndexes[bandIndex], false); + if (this.selectedBandIndexes[bandIndex] != hti.row) + { + // deselect currently selected row + SetSelectedRowCore(this.selectedBandIndexes[bandIndex], false); + } + else + { + bandIndex++; + } + } + + if (this.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) + { + RemoveIndividuallySelectedCells(); } else { - bandIndex++; + Debug.Assert(this.individualSelectedCells.Count == 0); } } - - if (this.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) - { - RemoveIndividuallySelectedCells(); - } - else + finally { - Debug.Assert(this.individualSelectedCells.Count == 0); + if (switchedToBulkPaint) + { + ExitBulkPaint(-1, -1); + } } } - finally + if (this.MultiSelect && this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) { - if (switchedToBulkPaint) - { - ExitBulkPaint(-1, -1); - } + this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] = true; } - } - if (this.MultiSelect && this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) - { - this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] = true; - } - if (selectRowRange) - { - if (hti.row >= this.ptAnchorCell.Y) + if (selectRowRange) { - SelectRowRange(this.ptAnchorCell.Y, hti.row, true); + if (hti.row >= this.ptAnchorCell.Y) + { + SelectRowRange(this.ptAnchorCell.Y, hti.row, true); + } + else + { + SelectRowRange(hti.row, this.ptAnchorCell.Y, true); + } } - else + else if ((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) == 0) { - SelectRowRange(hti.row, this.ptAnchorCell.Y, true); + Debug.Assert(this.selectedBandIndexes.Contains(hti.row) == + ((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) != 0)); + SetSelectedRowCore(hti.row, true); } - } - else if ((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) == 0) - { - Debug.Assert(this.selectedBandIndexes.Contains(hti.row) == - ((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) != 0)); - SetSelectedRowCore(hti.row, true); - } - if (dataGridViewColumn != null) - { - if (hti.row != this.ptCurrentCell.Y) + if (dataGridViewColumn != null) { - if (IsInnerCellOutOfBounds(dataGridViewColumn.Index, hti.row)) + if (hti.row != this.ptCurrentCell.Y) { - return; + if (IsInnerCellOutOfBounds(dataGridViewColumn.Index, hti.row)) + { + return; + } + // set current cell to the left most visible cell in the row + bool success = ScrollIntoView(dataGridViewColumn.Index, hti.row, false); + Debug.Assert(success); + if (IsInnerCellOutOfBounds(dataGridViewColumn.Index, hti.row)) + { + return; + } + success = SetCurrentCellAddressCore(dataGridViewColumn.Index, hti.row, !selectRowRange, false, true); + Debug.Assert(success); } - // set current cell to the left most visible cell in the row - bool success = ScrollIntoView(dataGridViewColumn.Index, hti.row, false); - Debug.Assert(success); - if (IsInnerCellOutOfBounds(dataGridViewColumn.Index, hti.row)) + else if (-1 != this.ptCurrentCell.Y) { - return; + // Potentially have to give focus back to the current edited cell. + bool success = SetCurrentCellAddressCore(this.ptCurrentCell.X, this.ptCurrentCell.Y, + false /*setAnchorCellAddress*/, + false /*validateCurrentCell*/, + false /*throughMouseClick*/); + Debug.Assert(success); } - success = SetCurrentCellAddressCore(dataGridViewColumn.Index, hti.row, !selectRowRange, false, true); - Debug.Assert(success); } - else if (-1 != this.ptCurrentCell.Y) + else { - // Potentially have to give focus back to the current edited cell. - bool success = SetCurrentCellAddressCore(this.ptCurrentCell.X, this.ptCurrentCell.Y, - false /*setAnchorCellAddress*/, - false /*validateCurrentCell*/, - false /*throughMouseClick*/); - Debug.Assert(success); + Debug.Assert(this.CurrentCellAddress == new Point(-1, -1)); } } else { - Debug.Assert(this.CurrentCellAddress == new Point(-1, -1)); + Debug.Assert(this.selectedBandIndexes.Contains(hti.row)); + SetSelectedRowCore(hti.row, false); } + break; } - else - { - Debug.Assert(this.selectedBandIndexes.Contains(hti.row)); - SetSelectedRowCore(hti.row, false); - } - break; - } } } finally @@ -18428,7 +18428,7 @@ protected virtual void OnRowHeadersBorderStyleChanged(EventArgs e) { PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); Invalidate(); - + EventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWHEADERSBORDERSTYLECHANGED] as EventHandler; if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) { @@ -18720,8 +18720,8 @@ private void OnRowSelectMouseMove(HitTestInfo hti) Debug.Assert(hti.row >= 0); Debug.Assert(this.MultiSelect); - if (this.ptCurrentCell.Y != -1 && - hti.row != this.ptCurrentCell.Y && + if (this.ptCurrentCell.Y != -1 && + hti.row != this.ptCurrentCell.Y && !CommitEditForOperation(this.ptCurrentCell.X, hti.row, true)) { // Return silently if validating/commit/abort failed @@ -18804,10 +18804,10 @@ private void OnRowSelectMouseMove(HitTestInfo hti) { return; } - bool success = SetCurrentCellAddressCore(this.ptCurrentCell.X, - hti.row, - false /*setAnchorCellAddress*/, - false /*validateCurrentCell*/, + bool success = SetCurrentCellAddressCore(this.ptCurrentCell.X, + hti.row, + false /*setAnchorCellAddress*/, + false /*validateCurrentCell*/, false /*throughMouseClick*/); Debug.Assert(success); } @@ -18916,71 +18916,71 @@ protected virtual void OnRowStateChanged(int rowIndex, DataGridViewRowStateChang break; case DataGridViewElementStates.Visible: - { - if (!rowVisible && (newState & DataGridViewElementStates.Displayed) != 0) { - // Displayed row becomes invisible. Turns off the Displayed state. - this.Rows.SetRowState(rowIndex, DataGridViewElementStates.Displayed, false); - } + if (!rowVisible && (newState & DataGridViewElementStates.Displayed) != 0) + { + // Displayed row becomes invisible. Turns off the Displayed state. + this.Rows.SetRowState(rowIndex, DataGridViewElementStates.Displayed, false); + } - PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, true /*repositionEditingControl*/); - Invalidate(); + PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, true /*repositionEditingControl*/); + Invalidate(); - bool rowDisplayed = (this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Displayed) != 0; - DataGridViewAutoSizeRowsModeInternal autoSizeRowsModeInternal = (DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode; + bool rowDisplayed = (this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Displayed) != 0; + DataGridViewAutoSizeRowsModeInternal autoSizeRowsModeInternal = (DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode; - bool autoSizeRow = false; + bool autoSizeRow = false; - if (autoSizeRowsModeInternal != DataGridViewAutoSizeRowsModeInternal.None) - { - int height = dataGridViewRow.ThicknessInternal; - if (rowVisible) + if (autoSizeRowsModeInternal != DataGridViewAutoSizeRowsModeInternal.None) { - // Cache row's height before potential autosizing occurs - // Valid operation even for shared rows - dataGridViewRow.CachedThickness = height; - if (!((autoSizeRowsModeInternal & DataGridViewAutoSizeRowsModeInternal.DisplayedRows) != 0 && !rowDisplayed)) + int height = dataGridViewRow.ThicknessInternal; + if (rowVisible) { - AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(this.autoSizeRowsMode), false /*fixedWidth*/, true /*internalAutosizing*/); - autoSizeRow = true; + // Cache row's height before potential autosizing occurs + // Valid operation even for shared rows + dataGridViewRow.CachedThickness = height; + if (!((autoSizeRowsModeInternal & DataGridViewAutoSizeRowsModeInternal.DisplayedRows) != 0 && !rowDisplayed)) + { + AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(this.autoSizeRowsMode), false /*fixedWidth*/, true /*internalAutosizing*/); + autoSizeRow = true; + } } - } - else if (height != dataGridViewRow.CachedThickness) - { - // Rows that are made invisible in the collection take their non-autosized height - // Not calling OnRowHeightInfoPushed(...) because rows are autosized - // Make sure the affected row is unshared - if (dataGridViewRow.Index == -1) + else if (height != dataGridViewRow.CachedThickness) { - dataGridViewRow = this.Rows[rowIndex]; + // Rows that are made invisible in the collection take their non-autosized height + // Not calling OnRowHeightInfoPushed(...) because rows are autosized + // Make sure the affected row is unshared + if (dataGridViewRow.Index == -1) + { + dataGridViewRow = this.Rows[rowIndex]; + } + dataGridViewRow.ThicknessInternal = Math.Max(dataGridViewRow.MinimumHeight, dataGridViewRow.CachedThickness); } - dataGridViewRow.ThicknessInternal = Math.Max(dataGridViewRow.MinimumHeight, dataGridViewRow.CachedThickness); } - } - // Auto size columms also if needed - DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaFilter = DataGridViewAutoSizeColumnCriteriaInternal.AllRows; - if (rowDisplayed) - { - autoSizeColumnCriteriaFilter |= DataGridViewAutoSizeColumnCriteriaInternal.DisplayedRows; - } - if (rowVisible && this.Rows.GetRowCount(DataGridViewElementStates.Visible) > 1) - { - // Columns can only expand, and not collapse. - AdjustExpandingColumns(autoSizeColumnCriteriaFilter, rowIndex); - } - else - { - AutoResizeAllVisibleColumnsInternal(autoSizeColumnCriteriaFilter, true /*fixedHeight*/); - } + // Auto size columms also if needed + DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaFilter = DataGridViewAutoSizeColumnCriteriaInternal.AllRows; + if (rowDisplayed) + { + autoSizeColumnCriteriaFilter |= DataGridViewAutoSizeColumnCriteriaInternal.DisplayedRows; + } + if (rowVisible && this.Rows.GetRowCount(DataGridViewElementStates.Visible) > 1) + { + // Columns can only expand, and not collapse. + AdjustExpandingColumns(autoSizeColumnCriteriaFilter, rowIndex); + } + else + { + AutoResizeAllVisibleColumnsInternal(autoSizeColumnCriteriaFilter, true /*fixedHeight*/); + } - if (autoSizeRow) - { - // Second round of row autosizing - AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(this.autoSizeRowsMode), true /*fixedWidth*/, true /*internalAutosizing*/); + if (autoSizeRow) + { + // Second round of row autosizing + AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(this.autoSizeRowsMode), true /*fixedWidth*/, true /*internalAutosizing*/); + } + break; } - break; - } } DataGridViewRowStateChangedEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWSTATECHANGED] as DataGridViewRowStateChangedEventHandler; @@ -19276,7 +19276,7 @@ internal void OnSortGlyphDirectionChanged(DataGridViewColumnHeaderCell dataGridV // If the column whose SortGlyphChanges is the sorted column and it is also the dataBound column // then see if there is another dataBound column which has the same property name as the sorted column. // If so, then make that dataGridViewColumn the sorted column in the data grid view. - for (int i = 0; i < this.Columns.Count; i ++) + for (int i = 0; i < this.Columns.Count; i++) { if (dataGridViewColumn != this.Columns[i] && this.Columns[i].SortMode != DataGridViewColumnSortMode.NotSortable && @@ -19371,7 +19371,7 @@ private void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventAr } } - protected override void OnValidating(CancelEventArgs e) + protected override void OnValidating(CancelEventArgs e) { // Avoid Cell/Row Validation events when the grid or its editing control gets the focus if (!this.BecomingActiveControl && (this.editingControl == null || !this.editingControl.BecomingActiveControl)) @@ -19701,12 +19701,12 @@ private void PaintColumnHeaders(Graphics g, Rectangle clipBounds, bool singleBor isFirstDisplayedColumn, isLastVisibleColumn); // Microsoft: should paintSelectionBackground be dev-settable? - cell.PaintWork(g, - clipBounds, - cellBounds, - -1, - dataGridViewColumn.State, - inheritedCellStyle, + cell.PaintWork(g, + clipBounds, + cellBounds, + -1, + dataGridViewColumn.State, + inheritedCellStyle, dgvabsEffective, DataGridViewPaintParts.Background | DataGridViewPaintParts.Border | DataGridViewPaintParts.ContentBackground | DataGridViewPaintParts.ContentForeground | DataGridViewPaintParts.ErrorIcon | DataGridViewPaintParts.SelectionBackground); @@ -19774,12 +19774,12 @@ private void PaintColumnHeaders(Graphics g, Rectangle clipBounds, bool singleBor dgvabsEffective = AdjustColumnHeaderBorderStyle(this.AdvancedColumnHeadersBorderStyle, dataGridViewAdvancedBorderStylePlaceholder, isFirstDisplayedColumn, isLastVisibleColumn); - cell.PaintWork(g, - clipBounds, - cellBounds, - -1, - dataGridViewColumn.State, - inheritedCellStyle, + cell.PaintWork(g, + clipBounds, + cellBounds, + -1, + dataGridViewColumn.State, + inheritedCellStyle, dgvabsEffective, DataGridViewPaintParts.Background | DataGridViewPaintParts.Border | DataGridViewPaintParts.ContentBackground | DataGridViewPaintParts.ContentForeground | DataGridViewPaintParts.ErrorIcon | DataGridViewPaintParts.SelectionBackground); @@ -19803,16 +19803,16 @@ private void PaintColumnHeaders(Graphics g, Rectangle clipBounds, bool singleBor } } - private void PaintGrid(Graphics g, + private void PaintGrid(Graphics g, Rectangle gridBounds, Rectangle clipRect, - bool singleVerticalBorderAdded, - bool singleHorizontalBorderAdded) + bool singleVerticalBorderAdded, + bool singleHorizontalBorderAdded) { Rectangle rc = gridBounds; - if (this.layout.TopLeftHeader.Width > 0 && - (clipRect.IntersectsWith(this.layout.TopLeftHeader) || this.lastHeaderShadow != -1)) + if (this.layout.TopLeftHeader.Width > 0 && + (clipRect.IntersectsWith(this.layout.TopLeftHeader) || this.lastHeaderShadow != -1)) { if (this.Columns.Count > 0 || this.Rows.Count > 0) { @@ -19864,8 +19864,8 @@ private void PaintGrid(Graphics g, } else if (this.currentColSplitBar != -1) { - Debug.Assert(this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize] || - this.dataGridViewOper[DATAGRIDVIEWOPER_trackColResize] || + Debug.Assert(this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize] || + this.dataGridViewOper[DATAGRIDVIEWOPER_trackColResize] || this.dataGridViewOper[DATAGRIDVIEWOPER_trackKeyboardColResize]); DrawColSplitBar(this.currentColSplitBar); } @@ -19912,12 +19912,12 @@ private void PaintRows(Graphics g, indexTmpNext = this.Rows.GetNextRow(indexTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); - if (clipRect.IntersectsWith(rowBounds)) + if (clipRect.IntersectsWith(rowBounds)) { dataGridViewRow = this.Rows.SharedRow(indexTmp); dataGridViewRow.Paint(g, clipRect, - rowBounds, + rowBounds, indexTmp, this.Rows.GetRowState(indexTmp), isFirstDisplayedRow, @@ -19965,12 +19965,12 @@ private void PaintRows(Graphics g, indexTmpNext = this.Rows.GetNextRow(indexTmp, DataGridViewElementStates.Visible); - if (clipRect.IntersectsWith(rowBounds)) + if (clipRect.IntersectsWith(rowBounds)) { dataGridViewRow = this.Rows.SharedRow(indexTmp); dataGridViewRow.Paint(g, clipRect, - rowBounds, + rowBounds, indexTmp, this.Rows.GetRowState(indexTmp), isFirstDisplayedRow, @@ -19998,20 +19998,20 @@ private void PaintTopLeftHeaderCell(Graphics g) cellBounds.Width = this.rowHeadersWidth; cellBounds.Height = this.columnHeadersHeight; // Microsoft: Should paintSelectionBackground be dev-settable? - cell.PaintWork(g, - this.layout.TopLeftHeader, - cellBounds, - -1, - cell.State, - inheritedCellStyle, + cell.PaintWork(g, + this.layout.TopLeftHeader, + cellBounds, + -1, + cell.State, + inheritedCellStyle, this.AdjustedTopLeftHeaderBorderStyle, DataGridViewPaintParts.Background | DataGridViewPaintParts.Border | DataGridViewPaintParts.ContentBackground | DataGridViewPaintParts.ContentForeground | DataGridViewPaintParts.ErrorIcon | DataGridViewPaintParts.SelectionBackground); } } - private void PerformLayoutPrivate(bool useRowShortcut, - bool computeVisibleRows, - bool invalidInAdjustFillingColumns, + private void PerformLayoutPrivate(bool useRowShortcut, + bool computeVisibleRows, + bool invalidInAdjustFillingColumns, bool repositionEditingControl) { this.inPerformLayoutCount++; @@ -20106,18 +20106,18 @@ private void PopulateNewRowWithDefaultValues() private void PositionEditingControl(bool setLocation, bool setSize, bool setFocus) { Debug.Assert(this.editingControl != null); - + if (!this.IsHandleCreated) { return; } - #if DEBUG - DataGridViewCell dataGridViewCell = this.CurrentCellInternal; - Debug.Assert(dataGridViewCell != null); - Debug.Assert(dataGridViewCell.ColumnIndex == this.ptCurrentCell.X); - Debug.Assert(dataGridViewCell.RowIndex == this.ptCurrentCell.Y || dataGridViewCell.RowIndex == -1); - #endif +#if DEBUG + DataGridViewCell dataGridViewCell = this.CurrentCellInternal; + Debug.Assert(dataGridViewCell != null); + Debug.Assert(dataGridViewCell.ColumnIndex == this.ptCurrentCell.X); + Debug.Assert(dataGridViewCell.RowIndex == this.ptCurrentCell.Y || dataGridViewCell.RowIndex == -1); +#endif Rectangle editingZone = this.layout.Data; if (editingZone.Width == 0 || editingZone.Height == 0) @@ -20132,7 +20132,7 @@ private void PositionEditingControl(bool setLocation, bool setSize, bool setFocu int leftEdge = GetColumnXFromIndex(this.ptCurrentCell.X); if (this.RightToLeftInternal) { - leftEdge -= this.Columns[this.ptCurrentCell.X].Width-1; + leftEdge -= this.Columns[this.ptCurrentCell.X].Width - 1; } Rectangle cellBounds = new Rectangle(leftEdge, GetRowYFromIndex(this.ptCurrentCell.Y), this.Columns[this.ptCurrentCell.X].Width, this.Rows.SharedRow(this.ptCurrentCell.Y).GetHeight(this.ptCurrentCell.Y)); @@ -20152,7 +20152,7 @@ private void PositionEditingControl(bool setLocation, bool setSize, bool setFocu int totalVisibleFrozenHeight = this.Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); editingZone.Y += totalVisibleFrozenHeight; } - cellClip.Intersect(editingZone); + cellClip.Intersect(editingZone); if (cellClip.Width == 0 || cellClip.Height == 0) { @@ -20189,10 +20189,10 @@ private void PositionEditingControl(bool setLocation, bool setSize, bool setFocu } this.CurrentCellInternal.PositionEditingControl( - setLocation || this.dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlHidden], - setSize || this.dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlHidden], + setLocation || this.dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlHidden], + setSize || this.dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlHidden], cellBounds, cellClip, this.InheritedEditingCellStyle, - singleVerticalBorderAdded, singleHorizontalBorderAdded, + singleVerticalBorderAdded, singleHorizontalBorderAdded, isFirstDisplayedColumn, isFirstDisplayedRow); this.dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlHidden] = false; } @@ -20258,22 +20258,22 @@ protected bool ProcessDeleteKey(Keys keyData) { int dataGridRowsCount = this.Rows.Count; #if DEBUG - int dataGridViewRowsCount = this.Rows.Count; // the number of rows in the dataGridView row collection not counting the AddNewRow - int rowCount = this.dataConnection.CurrencyManager.List.Count; - if (this.AllowUserToAddRowsInternal ) - { - if (this.newRowIndex < rowCount) - { - // the user did not type inside the 'add new row' - Debug.Assert(rowCount == dataGridViewRowsCount, "out of sync in AddNewTransaction when the user did not type in the 'add new row'"); - } - else + int dataGridViewRowsCount = this.Rows.Count; // the number of rows in the dataGridView row collection not counting the AddNewRow + int rowCount = this.dataConnection.CurrencyManager.List.Count; + if (this.AllowUserToAddRowsInternal) { - dataGridViewRowsCount --; + if (this.newRowIndex < rowCount) + { + // the user did not type inside the 'add new row' + Debug.Assert(rowCount == dataGridViewRowsCount, "out of sync in AddNewTransaction when the user did not type in the 'add new row'"); + } + else + { + dataGridViewRowsCount--; + } } - } - Debug.Assert(rowCount == dataGridViewRowsCount, "out of sync"); + Debug.Assert(rowCount == dataGridViewRowsCount, "out of sync"); #endif DataGridViewDataErrorEventArgs dgvdee = null; try @@ -20372,8 +20372,8 @@ protected override bool ProcessDialogKey(Keys keyData) { // Make sure the current cell is in editing mode if needed. if (this.ptCurrentCell.X > -1 && - !this.IsCurrentCellInEditMode && - (this.EditMode == DataGridViewEditMode.EditOnEnter || + !this.IsCurrentCellInEditMode && + (this.EditMode == DataGridViewEditMode.EditOnEnter || (this.EditMode != DataGridViewEditMode.EditProgrammatically && this.CurrentCellInternal.EditType == null))) { BeginEditInternal(true /*selectAll*/); @@ -20407,14 +20407,14 @@ protected override bool ProcessDialogKey(Keys keyData) if (this.editingControl != null) { this.dataGridViewState1[DATAGRIDVIEWSTATE1_leavingWithTabKey] = true; - if (!EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.LeaveControl, - DataGridViewValidateCellInternal.Always, - true /*fireCellLeave*/, - true /*fireCellEnter*/, - true /*fireRowLeave*/, - true /*fireRowEnter*/, - true /*fireLeave*/, - false /*keepFocus*/, + if (!EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.LeaveControl, + DataGridViewValidateCellInternal.Always, + true /*fireCellLeave*/, + true /*fireCellEnter*/, + true /*fireRowLeave*/, + true /*fireRowEnter*/, + true /*fireLeave*/, + false /*keepFocus*/, false /*resetCurrentCell*/, false /*resetAnchorCell unused here*/)) { @@ -20509,7 +20509,7 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) //SelectCellRange(this.ptCurrentCell.X, this.ptAnchorCell.Y, this.ptCurrentCell.X, lastVisibleRowIndex, true); int oldEdgeColumnIndex = this.ptCurrentCell.X; int oldEdgeRowIndex = this.ptCurrentCell.Y; - if (this.ptCurrentCell.X == -1 || this.ptAnchorCell.X == -1 || + if (this.ptCurrentCell.X == -1 || this.ptAnchorCell.X == -1 || IsRowOutOfBounds(lastVisibleRowIndex)) { moved = false; @@ -20684,10 +20684,10 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) } ClearSelection(); SetSelectedCellCore(this.ptCurrentCell.X, nextVisibleRowIndex, true); - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, - nextVisibleRowIndex, - true /*setAnchorCellAddress*/, - false /*validateCurrentCell*/, + success = SetCurrentCellAddressCore(this.ptCurrentCell.X, + nextVisibleRowIndex, + true /*setAnchorCellAddress*/, + false /*validateCurrentCell*/, false /*throughMouseClick*/); if (!success) { @@ -21396,7 +21396,7 @@ protected bool ProcessEndKey(Keys keyData) } else { - if (this.ptCurrentCell.Y > -1 && + if (this.ptCurrentCell.Y > -1 && (this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { ClearSelection(); @@ -21621,13 +21621,13 @@ protected bool ProcessEnterKey(Keys keyData) } else { - EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit, - DataGridViewValidateCellInternal.WhenChanged /*validateCell*/, + EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit, + DataGridViewValidateCellInternal.WhenChanged /*validateCell*/, false /*fireCellLeave*/, false /*fireCellEnter*/, false /*fireRowLeave*/, false /*fireRowEnter*/, - false /*fireLeave*/, + false /*fireLeave*/, true /*keepFocus*/, true /*resetCurrentCell unused here*/, true /*resetAnchorCell unused here*/); @@ -21679,13 +21679,13 @@ protected bool ProcessEscapeKey(Keys keyData) ] protected bool ProcessF2Key(Keys keyData) { - if (this.ptCurrentCell.X != -1 && - !this.IsCurrentCellInEditMode && + if (this.ptCurrentCell.X != -1 && + !this.IsCurrentCellInEditMode && ModifierKeys == 0) { Debug.Assert(this.ptCurrentCell.Y != -1); Debug.Assert(this.CurrentCellInternal != null); - Debug.Assert(this.EditMode != DataGridViewEditMode.EditOnEnter || + Debug.Assert(this.EditMode != DataGridViewEditMode.EditOnEnter || (IsSharedCellReadOnly(this.CurrentCellInternal, this.ptCurrentCell.Y) || !ColumnEditable(this.ptCurrentCell.X))); if (ColumnEditable(this.ptCurrentCell.X) && !IsSharedCellReadOnly(this.CurrentCellInternal, this.ptCurrentCell.Y) && @@ -21796,12 +21796,12 @@ protected bool ProcessHomeKey(Keys keyData) if (IsInnerCellOutOfBounds(firstVisibleColumnIndex, firstVisibleRowIndex)) { return true; - } + } if ((keyData & Keys.Shift) == Keys.Shift) { if (this.MultiSelect && this.ptAnchorCell.X >= 0) { - if (this.ptCurrentCell.Y > -1 && + if (this.ptCurrentCell.Y > -1 && (this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { ClearSelection(); @@ -22030,7 +22030,7 @@ protected override bool ProcessKeyEventArgs(ref Message m) (this.EditMode == DataGridViewEditMode.EditOnKeystroke || this.EditMode == DataGridViewEditMode.EditOnKeystrokeOrF2)) { KeyEventArgs ke = new KeyEventArgs((Keys)(unchecked((int)(long)m.WParam)) | ModifierKeys); - if (ke.KeyCode != Keys.ProcessKey || (int) m.LParam != 0x01) // Changing IME context does not trigger editing mode + if (ke.KeyCode != Keys.ProcessKey || (int)m.LParam != 0x01) // Changing IME context does not trigger editing mode { Type editControlType = dataGridViewCell.EditType; Type editingCellInterface = null; @@ -22062,7 +22062,7 @@ protected override bool ProcessKeyEventArgs(ref Message m) } } else if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_forwardCharMessage] && - (m.Msg == Interop.WindowMessages.WM_SYSCHAR || m.Msg == Interop.WindowMessages.WM_CHAR || m.Msg == Interop.WindowMessages.WM_IME_CHAR)) + (m.Msg == Interop.WindowMessages.WM_SYSCHAR || m.Msg == Interop.WindowMessages.WM_CHAR || m.Msg == Interop.WindowMessages.WM_IME_CHAR)) { this.dataGridViewState1[DATAGRIDVIEWSTATE1_forwardCharMessage] = false; if (this.editingControl != null) @@ -22074,7 +22074,7 @@ protected override bool ProcessKeyEventArgs(ref Message m) return base.ProcessKeyEventArgs(ref m); } - protected override bool ProcessKeyPreview(ref Message m) + protected override bool ProcessKeyPreview(ref Message m) { bool dataGridViewWantsInputKey; KeyEventArgs ke = new KeyEventArgs((Keys)((int)m.WParam) | ModifierKeys); @@ -22463,7 +22463,7 @@ private bool ProcessLeftKeyPrivate(Keys keyData) if (this.ptCurrentCell.X == -1 || IsColumnOutOfBounds(previousVisibleColumnIndex)) { return true; - } + } if (this.Columns[this.ptCurrentCell.X].Selected) { ClearSelection(); @@ -22647,7 +22647,7 @@ private bool ProcessLeftMost(bool shift, int firstVisibleColumnIndex, int firstV IsColumnOutOfBounds(firstVisibleColumnIndex)) { return true; - } + } UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, firstVisibleColumnIndex, this.ptAnchorCell.Y, ref oldEdgeRowIndex, oldEdgeRowIndex); success = SetCurrentCellAddressCore(firstVisibleColumnIndex, this.ptCurrentCell.Y, false, false, false); @@ -22692,7 +22692,7 @@ private bool ProcessLeftMost(bool shift, int firstVisibleColumnIndex, int firstV { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(firstVisibleColumnIndex)) + if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(firstVisibleColumnIndex)) { return true; } @@ -22969,14 +22969,14 @@ protected bool ProcessNextKey(Keys keyData) { int firstDisplayedScrollingRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); Debug.Assert(firstDisplayedScrollingRowIndex != -1); - if (!ScrollIntoView(this.ptCurrentCell.X == -1 ? firstVisibleColumnIndex : this.ptCurrentCell.X, + if (!ScrollIntoView(this.ptCurrentCell.X == -1 ? firstVisibleColumnIndex : this.ptCurrentCell.X, firstDisplayedScrollingRowIndex, true)) { return true; } - jumpRows = this.Rows.GetRowCount(DataGridViewElementStates.Visible, - this.ptCurrentCell.Y, - firstDisplayedScrollingRowIndex)-1; + jumpRows = this.Rows.GetRowCount(DataGridViewElementStates.Visible, + this.ptCurrentCell.Y, + firstDisplayedScrollingRowIndex) - 1; } else { @@ -23228,7 +23228,7 @@ protected bool ProcessPriorKey(Keys keyData) // Make sure the first scrolling row is visible if any int firstDisplayedScrollingRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); if (firstDisplayedScrollingRowIndex != -1 && - !ScrollIntoView(this.ptCurrentCell.X == -1 ? firstVisibleColumnIndex : this.ptCurrentCell.X, + !ScrollIntoView(this.ptCurrentCell.X == -1 ? firstVisibleColumnIndex : this.ptCurrentCell.X, firstDisplayedScrollingRowIndex, true)) { return true; @@ -24331,84 +24331,84 @@ protected bool ProcessTabKey(Keys keyData) /// Processes keys for dataGridView navigation. /// /// - protected virtual bool ProcessDataGridViewKey(KeyEventArgs e) + protected virtual bool ProcessDataGridViewKey(KeyEventArgs e) { switch (e.KeyCode) { case Keys.Tab: - { - return ProcessTabKey(e.KeyData); - } + { + return ProcessTabKey(e.KeyData); + } case Keys.Up: - { - return ProcessUpKey(e.KeyData); - } + { + return ProcessUpKey(e.KeyData); + } case Keys.Down: - { - return ProcessDownKey(e.KeyData); - } + { + return ProcessDownKey(e.KeyData); + } case Keys.Next: - { - return ProcessNextKey(e.KeyData); - } + { + return ProcessNextKey(e.KeyData); + } case Keys.Prior: - { - return ProcessPriorKey(e.KeyData); - } + { + return ProcessPriorKey(e.KeyData); + } case Keys.Left: - { - return ProcessLeftKey(e.KeyData); - } + { + return ProcessLeftKey(e.KeyData); + } case Keys.Right: - { - return ProcessRightKey(e.KeyData); - } + { + return ProcessRightKey(e.KeyData); + } case Keys.F2: - { - return ProcessF2Key(e.KeyData); - } + { + return ProcessF2Key(e.KeyData); + } case Keys.F3: - { - return ProcessF3Key(e.KeyData); - } + { + return ProcessF3Key(e.KeyData); + } case Keys.Home: - { - return ProcessHomeKey(e.KeyData); - } + { + return ProcessHomeKey(e.KeyData); + } case Keys.D0: case Keys.NumPad0: - { - return ProcessZeroKey(e.KeyData); - } + { + return ProcessZeroKey(e.KeyData); + } case Keys.Delete: - { - return ProcessDeleteKey(e.KeyData); - } + { + return ProcessDeleteKey(e.KeyData); + } case Keys.End: - { - return ProcessEndKey(e.KeyData); - } + { + return ProcessEndKey(e.KeyData); + } case Keys.Enter: - { - return ProcessEnterKey(e.KeyData); - } + { + return ProcessEnterKey(e.KeyData); + } case Keys.Escape: - { - return ProcessEscapeKey(e.KeyData); - } + { + return ProcessEscapeKey(e.KeyData); + } case Keys.A: - { - return ProcessAKey(e.KeyData); - } + { + return ProcessAKey(e.KeyData); + } case Keys.C: case Keys.Insert: - { - return ProcessInsertKey(e.KeyData); - } + { + return ProcessInsertKey(e.KeyData); + } case Keys.Space: - { - return ProcessSpaceKey(e.KeyData); - } + { + return ProcessSpaceKey(e.KeyData); + } } return false; } @@ -24463,7 +24463,7 @@ protected bool ProcessUpKey(Keys keyData) { return true; } - if (this.ptAnchorCell.X == -1 || this.ptCurrentCell.X == -1 || + if (this.ptAnchorCell.X == -1 || this.ptCurrentCell.X == -1 || IsRowOutOfBounds(firstVisibleRowIndex)) { return true; @@ -24645,7 +24645,7 @@ protected bool ProcessUpKey(Keys keyData) { return true; } - if (this.ptAnchorCell.X == -1 || this.ptCurrentCell.X == -1 || + if (this.ptAnchorCell.X == -1 || this.ptCurrentCell.X == -1 || IsRowOutOfBounds(firstVisibleRowIndex)) { return true; @@ -24824,7 +24824,7 @@ protected bool ProcessUpKey(Keys keyData) { return true; } - if (this.ptAnchorCell.X == -1 || this.ptCurrentCell.X == -1 || + if (this.ptAnchorCell.X == -1 || this.ptCurrentCell.X == -1 || IsRowOutOfBounds(firstVisibleRowIndex)) { return true; @@ -25137,9 +25137,9 @@ protected bool ProcessZeroKey(Keys keyData) { if (this.editingControl != null) { - ((IDataGridViewEditingControl) this.editingControl).EditingControlFormattedValue = nullValue; - ((IDataGridViewEditingControl) this.editingControl).EditingControlValueChanged = true; - ((IDataGridViewEditingControl) this.editingControl).PrepareEditingControlForEdit(true /*selectAll*/); + ((IDataGridViewEditingControl)this.editingControl).EditingControlFormattedValue = nullValue; + ((IDataGridViewEditingControl)this.editingControl).EditingControlValueChanged = true; + ((IDataGridViewEditingControl)this.editingControl).PrepareEditingControlForEdit(true /*selectAll*/); } else { @@ -25184,10 +25184,10 @@ private bool PushFormattedValue(ref DataGridViewCell dataGridViewCurrentCell, ob DataGridViewCellStyle cellStyle = this.InheritedEditingCellStyle; - DataGridViewCellParsingEventArgs dgvcpe = OnCellParsing(this.ptCurrentCell.Y, - this.ptCurrentCell.X, - formattedValue, - dataGridViewCurrentCell.ValueType, + DataGridViewCellParsingEventArgs dgvcpe = OnCellParsing(this.ptCurrentCell.Y, + this.ptCurrentCell.X, + formattedValue, + dataGridViewCurrentCell.ValueType, cellStyle); if (dgvcpe.ParsingApplied && dgvcpe.Value != null && @@ -25270,7 +25270,7 @@ private void RefreshColumns() } else { - for (int j = 0; j < dataGridViewCols.Count; j ++) + for (int j = 0; j < dataGridViewCols.Count; j++) { // when we refresh the columns, always clear whatever binding information we had on the columns dataGridViewCols[j].IsDataBoundInternal = false; @@ -25313,12 +25313,12 @@ public bool RefreshEdit() { if (InitializeEditingControlValue(ref dataGridViewCellStyle, dataGridViewCurrentCell)) { - if (((IDataGridViewEditingControl) this.editingControl).RepositionEditingControlOnValueChange) + if (((IDataGridViewEditingControl)this.editingControl).RepositionEditingControlOnValueChange) { PositionEditingControl(true /*setLocation*/, true /*setSize*/, false /*setFocus*/); } - ((IDataGridViewEditingControl) this.editingControl).PrepareEditingControlForEdit(true /*selectAll*/); - ((IDataGridViewEditingControl) this.editingControl).EditingControlValueChanged = false; + ((IDataGridViewEditingControl)this.editingControl).PrepareEditingControlForEdit(true /*selectAll*/); + ((IDataGridViewEditingControl)this.editingControl).EditingControlValueChanged = false; this.IsCurrentCellDirtyInternal = false; return true; } @@ -25385,10 +25385,10 @@ private void RefreshRows(bool scrollIntoView) Debug.Assert(list.Count == rowsCount); if (rowsCount > 1) { - this.Rows.AddCopiesInternal(0, rowsCount-1); + this.Rows.AddCopiesInternal(0, rowsCount - 1); } // Add selected Columns back in selectedBandIndexes - foreach(DataGridViewColumn column in Columns) + foreach (DataGridViewColumn column in Columns) { if (column.Selected && (!this.selectedBandIndexes.Contains(column.Index))) { @@ -25443,7 +25443,7 @@ private void RemoveIndividualReadOnlyCellsInColumn(int columnIndex) private void RemoveIndividualReadOnlyCellsInRow(int rowIndex) { - int cellIndex = 0; + int cellIndex = 0; while (cellIndex < this.individualReadOnlyCells.Count) { DataGridViewCell dataGridViewCell = this.individualReadOnlyCells[cellIndex]; @@ -25580,7 +25580,7 @@ private void RemoveIndividuallySelectedCellsInRow(int rowIndex) Debug.Assert(this.noSelectionChangeCount > 0); // Since there are typically not many columns in a row, we don't try to switch into a bulk operation // as we do in RemoveIndividuallySelectedCellsInColumn. - int cellIndex = 0; + int cellIndex = 0; while (cellIndex < this.individualSelectedCells.Count) { DataGridViewCell dataGridViewCell = this.individualSelectedCells[cellIndex]; @@ -25748,7 +25748,7 @@ private bool RowNeedsDisplayedState(int rowIndex, int lastDisplayedFrozenRowInde { Debug.Assert(rowIndex >= 0); Debug.Assert(rowIndex < this.Rows.Count); - + DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); if ((rowState & DataGridViewElementStates.Visible) == 0) @@ -25799,9 +25799,9 @@ private bool ScrollColumnIntoView(int columnIndex, int rowIndex, bool committed, int columnsToScroll; if (this.Columns.DisplayInOrder(columnIndex, this.displayedBandsInfo.FirstDisplayedScrollingCol)) { - if (!committed && this.ptCurrentCell.X >= 0 && + if (!committed && this.ptCurrentCell.X >= 0 && !CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, - forCurrentCellChange && (this.ptCurrentCell.X != columnIndex || this.ptCurrentCell.Y != rowIndex), + forCurrentCellChange && (this.ptCurrentCell.X != columnIndex || this.ptCurrentCell.Y != rowIndex), this.ptCurrentCell.Y != rowIndex /*forCurrentRowChange*/)) { return false; @@ -25816,9 +25816,9 @@ private bool ScrollColumnIntoView(int columnIndex, int rowIndex, bool committed, } else if (columnIndex == this.displayedBandsInfo.FirstDisplayedScrollingCol && this.negOffset > 0) { - if (!committed && this.ptCurrentCell.X >= 0 && + if (!committed && this.ptCurrentCell.X >= 0 && !CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, - forCurrentCellChange && (this.ptCurrentCell.X != columnIndex || this.ptCurrentCell.Y != rowIndex), + forCurrentCellChange && (this.ptCurrentCell.X != columnIndex || this.ptCurrentCell.Y != rowIndex), this.ptCurrentCell.Y != rowIndex /*forCurrentRowChange*/)) { return false; @@ -25829,9 +25829,9 @@ private bool ScrollColumnIntoView(int columnIndex, int rowIndex, bool committed, (this.displayedBandsInfo.LastTotallyDisplayedScrollingCol != columnIndex && this.Columns.DisplayInOrder(this.displayedBandsInfo.LastTotallyDisplayedScrollingCol, columnIndex))) { - if (!committed && this.ptCurrentCell.X >= 0 && + if (!committed && this.ptCurrentCell.X >= 0 && !CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, - forCurrentCellChange && (this.ptCurrentCell.X != columnIndex || this.ptCurrentCell.Y != rowIndex), + forCurrentCellChange && (this.ptCurrentCell.X != columnIndex || this.ptCurrentCell.Y != rowIndex), this.ptCurrentCell.Y != rowIndex /*forCurrentRowChange*/)) { return false; @@ -25888,7 +25888,7 @@ private bool ScrollColumnIntoView(int columnIndex, int rowIndex, bool committed, return true; } - private void ScrollColumns(int columns) + private void ScrollColumns(int columns) { DataGridViewColumn newFirstVisibleScrollingCol = null; DataGridViewColumn dataGridViewColumnTmp; @@ -25964,7 +25964,7 @@ private void ScrollColumns(int columns) DataGridViewElementStates.Frozen); dataGridViewColumn != newFirstVisibleScrollingCol; dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, - DataGridViewElementStates.Visible, + DataGridViewElementStates.Visible, DataGridViewElementStates.None)) { newColOffset += dataGridViewColumn.Thickness; @@ -26013,7 +26013,7 @@ private bool ScrollIntoView(int columnIndex, int rowIndex, bool forCurrentCellCh return ScrollRowIntoView(columnIndex, rowIndex, committed, forCurrentCellChange); } - private void ScrollRectangles(NativeMethods.RECT[] rects, int change) + private void ScrollRectangles(NativeMethods.RECT[] rects, int change) { if (rects != null) { @@ -26044,7 +26044,7 @@ private bool ScrollRowIntoView(int columnIndex, int rowIndex, bool committed, bo int rowsToScroll; if (rowIndex < this.displayedBandsInfo.FirstDisplayedScrollingRow) { - if (!committed && this.ptCurrentCell.X >= 0 && + if (!committed && this.ptCurrentCell.X >= 0 && !CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, forCurrentCellChange && (this.ptCurrentCell.X != columnIndex || this.ptCurrentCell.Y != rowIndex), this.ptCurrentCell.Y != rowIndex /*forCurrentRowChange*/)) @@ -26121,7 +26121,7 @@ private void ScrollRows(int rowCount, int deltaY, ScrollEventType scrollEventTyp rowsRect.Height -= frozenRowsThickness; Debug.Assert(rowsRect.Height >= 0); - if (this.editingControl != null && + if (this.editingControl != null && (this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Frozen) == 0) { Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow > -1); @@ -26157,7 +26157,7 @@ private void ScrollRows(int rowCount, int deltaY, ScrollEventType scrollEventTyp } } - private void ScrollRowsByCount(int rows, ScrollEventType scrollEventType) + private void ScrollRowsByCount(int rows, ScrollEventType scrollEventType) { Debug.Assert(rows != 0); Debug.Assert((rows > 0 && (scrollEventType == ScrollEventType.SmallIncrement || scrollEventType == ScrollEventType.LargeIncrement)) || @@ -26301,7 +26301,7 @@ private void ScrollRowsByHeight(int height) } // Does not seem to be a valid fxcop violation report. Contacting fxcop team to double-check. - [SuppressMessage("Microsoft.Performance", "CA1817:DoNotCallPropertiesThatCloneValuesInLoops")] + [SuppressMessage("Microsoft.Performance", "CA1817:DoNotCallPropertiesThatCloneValuesInLoops")] public void SelectAll() { if (!this.MultiSelect) @@ -26317,54 +26317,54 @@ public void SelectAll() switch (this.SelectionMode) { case DataGridViewSelectionMode.CellSelect: - { - // Bonjour the scalability issues! We select each cell, one at the time. - int maxColumnIndex = this.Columns.Count; - int rowIndex = 0, maxRowIndex = this.Rows.Count; - while (rowIndex < maxRowIndex) { - dataGridViewRow = this.Rows[rowIndex]; //unsharing each row! - int columnIndex = 0; - while (columnIndex < maxColumnIndex) + // Bonjour the scalability issues! We select each cell, one at the time. + int maxColumnIndex = this.Columns.Count; + int rowIndex = 0, maxRowIndex = this.Rows.Count; + while (rowIndex < maxRowIndex) { - SetSelectedCellCore(columnIndex, rowIndex, true); - columnIndex++; + dataGridViewRow = this.Rows[rowIndex]; //unsharing each row! + int columnIndex = 0; + while (columnIndex < maxColumnIndex) + { + SetSelectedCellCore(columnIndex, rowIndex, true); + columnIndex++; + } + rowIndex++; } - rowIndex++; + break; } - break; - } case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: - { - int rowIndex = 0, maxRowIndex = this.Rows.Count; - while (rowIndex < maxRowIndex) { - DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); - if ((rowState & DataGridViewElementStates.Selected) == 0) + int rowIndex = 0, maxRowIndex = this.Rows.Count; + while (rowIndex < maxRowIndex) { - SetSelectedRowCore(rowIndex, true); + DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); + if ((rowState & DataGridViewElementStates.Selected) == 0) + { + SetSelectedRowCore(rowIndex, true); + } + rowIndex++; } - rowIndex++; + break; } - break; - } case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: - { - int columnIndex = 0, maxColumnIndex = this.Columns.Count; - while (columnIndex < maxColumnIndex) { - if (!this.Columns[columnIndex].Selected) + int columnIndex = 0, maxColumnIndex = this.Columns.Count; + while (columnIndex < maxColumnIndex) { - SetSelectedColumnCore(columnIndex, true); + if (!this.Columns[columnIndex].Selected) + { + SetSelectedColumnCore(columnIndex, true); + } + columnIndex++; } - columnIndex++; + break; } - break; - } } } finally @@ -26403,63 +26403,63 @@ private DataGridViewCell SelectedCell(int index) switch (this.SelectionMode) { case DataGridViewSelectionMode.CellSelect: - { - if (index < this.individualSelectedCells.Count) { - return this.individualSelectedCells[index]; + if (index < this.individualSelectedCells.Count) + { + return this.individualSelectedCells[index]; + } + break; } - break; - } case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: - { - int selectedBand = 0, selectedBands = this.selectedBandIndexes.Count; - while (selectedBand < selectedBands && index >= 0) { - if (index >= this.Rows.Count) + int selectedBand = 0, selectedBands = this.selectedBandIndexes.Count; + while (selectedBand < selectedBands && index >= 0) { - index -= this.Rows.Count; - selectedBand++; + if (index >= this.Rows.Count) + { + index -= this.Rows.Count; + selectedBand++; + } + else + { + int columnIndex = this.selectedBandIndexes[selectedBand]; + return this.Rows.SharedRow(index).Cells[columnIndex]; + } } - else + + if (this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect && + index < this.individualSelectedCells.Count) { - int columnIndex = this.selectedBandIndexes[selectedBand]; - return this.Rows.SharedRow(index).Cells[columnIndex]; + return this.individualSelectedCells[index]; } + break; } - - if (this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect && - index < this.individualSelectedCells.Count) - { - return this.individualSelectedCells[index]; - } - break; - } case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: - { - int selectedBand = 0, selectedBands = this.selectedBandIndexes.Count; - while (selectedBand < selectedBands && index >= 0) { - if (index >= this.Columns.Count) + int selectedBand = 0, selectedBands = this.selectedBandIndexes.Count; + while (selectedBand < selectedBands && index >= 0) { - index -= this.Columns.Count; - selectedBand++; + if (index >= this.Columns.Count) + { + index -= this.Columns.Count; + selectedBand++; + } + else + { + int rowIndex = this.selectedBandIndexes[selectedBand]; + return this.Rows.SharedRow(rowIndex).Cells[index]; + } } - else + + if (this.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect && + index < this.individualSelectedCells.Count) { - int rowIndex = this.selectedBandIndexes[selectedBand]; - return this.Rows.SharedRow(rowIndex).Cells[index]; + return this.individualSelectedCells[index]; } + break; } - - if (this.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect && - index < this.individualSelectedCells.Count) - { - return this.individualSelectedCells[index]; - } - break; - } } return null; } @@ -26488,8 +26488,8 @@ private void SetColumnHeadersHeightInternal(int columnHeadersHeight, bool invali } } - protected virtual bool SetCurrentCellAddressCore(int columnIndex, - int rowIndex, + protected virtual bool SetCurrentCellAddressCore(int columnIndex, + int rowIndex, bool setAnchorCellAddress, bool validateCurrentCell, bool throughMouseClick) @@ -26555,13 +26555,13 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, if (oldCurrentCellX >= 0) { currentCell = this.CurrentCellInternal; - if (!EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.CurrentCellChange, + if (!EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.CurrentCellChange, validateCurrentCell ? DataGridViewValidateCellInternal.Always : DataGridViewValidateCellInternal.Never /*validateCell*/, validateCurrentCell /*fireCellLeave*/, false /*fireCellEnter*/, validateCurrentCell && oldCurrentCellY != rowIndex /*fireRowLeave*/, false /*fireRowEnter*/, - false /*fireLeave*/, + false /*fireLeave*/, this.EditMode != DataGridViewEditMode.EditOnEnter /*keepFocus*/, false /*resetCurrentCell*/, false /*resetAnchorCell unused here*/)) @@ -26644,7 +26644,7 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, } // rowIndex = Math.Min(rowIndex, this.Rows.GetRowCount(DataGridViewElementStates.Visible) - 1); } - + if (IsInnerCellOutOfBounds(columnIndex, rowIndex)) { return false; @@ -26663,14 +26663,14 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, this.ptAnchorCell.Y = rowIndex; } - #if FALSE +#if FALSE if (this.dataGridViewState2[DATAGRIDVIEWSTATE2_rowsCollectionClearedInSetCell]) { // DATAGRIDVIEWSTATE2_rowsCollectionClearedInSetCell bit will be cleared while executing the // "finally" block. return true; } - #endif +#endif currentCell = this.CurrentCellInternal; if (currentCell.EnterUnsharesRowInternal(rowIndex, throughMouseClick)) @@ -26701,7 +26701,7 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, !this.IsCurrentCellInEditMode && !this.dataGridViewState1[DATAGRIDVIEWSTATE1_leavingWithTabKey] && // don't edit if we're in the process of leaving the grid !this.dataGridViewState2[DATAGRIDVIEWSTATE2_rowsCollectionClearedInSetCell] && // don't edit if the rows collection changed - (this.EditMode == DataGridViewEditMode.EditOnEnter || + (this.EditMode == DataGridViewEditMode.EditOnEnter || (this.EditMode != DataGridViewEditMode.EditProgrammatically && currentCell.EditType == null))) { BeginEditInternal(true /*selectAll*/); @@ -26728,12 +26728,12 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, this.ptAnchorCell.Y = rowIndex; } if (this.Focused && - (!this.IsCurrentCellInEditMode && (this.EditMode == DataGridViewEditMode.EditOnEnter || + (!this.IsCurrentCellInEditMode && (this.EditMode == DataGridViewEditMode.EditOnEnter || (this.EditMode != DataGridViewEditMode.EditProgrammatically && this.CurrentCellInternal.EditType == null)))) { BeginEditInternal(true /*selectAll*/); } - else + else { CorrectFocus(false /*onlyIfGridHasFocus*/); } @@ -26743,7 +26743,7 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, { int oldCurrentCellX = this.ptCurrentCell.X; int oldCurrentCellY = this.ptCurrentCell.Y; - if (oldCurrentCellX >= 0 && + if (oldCurrentCellX >= 0 && !this.dataGridViewState1[DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell] && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose]) { @@ -26754,7 +26754,7 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, false /*fireCellEnter*/, validateCurrentCell /*fireRowLeave*/, false /*fireRowEnter*/, - false /*fireLeave*/, + false /*fireLeave*/, this.EditMode != DataGridViewEditMode.EditOnEnter /*keepFocus*/, false /*resetCurrentCell*/, false /*resetAnchorCell unused here*/)) @@ -26841,8 +26841,8 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, return true; } - internal void SetCurrentCellAddressCoreInternal(int columnIndex, - int rowIndex, + internal void SetCurrentCellAddressCoreInternal(int columnIndex, + int rowIndex, bool setAnchorCellAddress, bool validateCurrentCell, bool throughMouseClick) @@ -26970,7 +26970,7 @@ private void SelectColumnRange(int columnIndexFrom, int columnIndexTo, bool sele Debug.Assert((this.Columns[columnIndexFrom]).DisplayIndex <= (this.Columns[columnIndexTo]).DisplayIndex); Debug.Assert(this.noSelectionChangeCount > 0); - int columnIndex = columnIndexFrom; + int columnIndex = columnIndexFrom; do { if (select) @@ -26988,7 +26988,7 @@ private void SelectColumnRange(int columnIndexFrom, int columnIndexTo, bool sele if (columnIndex != columnIndexTo) { DataGridViewColumn dataGridViewColumn = this.Columns.GetNextColumn(this.Columns[columnIndex], - DataGridViewElementStates.Visible, + DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); columnIndex = dataGridViewColumn.Index; @@ -27058,8 +27058,8 @@ private void SelectRowRange(int rowIndexFrom, int rowIndexTo, bool select) } } - private bool SetAndSelectCurrentCellAddress(int columnIndex, - int rowIndex, + private bool SetAndSelectCurrentCellAddress(int columnIndex, + int rowIndex, bool setAnchorCellAddress, bool validateCurrentCell, bool throughMouseClick, @@ -27104,22 +27104,22 @@ private bool SetAndSelectCurrentCellAddress(int columnIndex, { case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: - { - if (this.selectedBandIndexes.HeadInt != columnIndex) { - return true; // Do not change a single selection that does not match the new current cell + if (this.selectedBandIndexes.HeadInt != columnIndex) + { + return true; // Do not change a single selection that does not match the new current cell + } + break; } - break; - } case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: - { - if (this.selectedBandIndexes.HeadInt != rowIndex) { - return true; // Do not change a single selection that does not match the new current cell + if (this.selectedBandIndexes.HeadInt != rowIndex) + { + return true; // Do not change a single selection that does not match the new current cell + } + break; } - break; - } } } SetSelectedElementCore(columnIndex, rowIndex, true); @@ -27130,10 +27130,12 @@ private bool SetAndSelectCurrentCellAddress(int columnIndex, protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { - if ((specified & BoundsSpecified.Width) == BoundsSpecified.Width && width > upperSize) { + if ((specified & BoundsSpecified.Width) == BoundsSpecified.Width && width > upperSize) + { throw new ArgumentOutOfRangeException(nameof(width), width, string.Format(SR.DataGridView_SizeTooLarge, (upperSize).ToString(CultureInfo.CurrentCulture))); } - if ((specified & BoundsSpecified.Height) == BoundsSpecified.Height && height > upperSize) { + if ((specified & BoundsSpecified.Height) == BoundsSpecified.Height && height > upperSize) + { throw new ArgumentOutOfRangeException(nameof(height), height, string.Format(SR.DataGridView_SizeTooLarge, (upperSize).ToString(CultureInfo.CurrentCulture))); } base.SetBoundsCore(x, y, width, height, specified); @@ -27182,7 +27184,7 @@ internal void SetReadOnlyCellCore(int columnIndex, int rowIndex, bool readOnly) dataGridViewCellTmp.ReadOnlyInternal = true; this.individualReadOnlyCells.Add(dataGridViewCellTmp); } - for (int row = rowIndex+1; row < this.Rows.Count; row++) + for (int row = rowIndex + 1; row < this.Rows.Count; row++) { dataGridViewCellTmp = this.Rows[row].Cells[columnIndex]; dataGridViewCellTmp.ReadOnlyInternal = true; @@ -27198,7 +27200,7 @@ internal void SetReadOnlyCellCore(int columnIndex, int rowIndex, bool readOnly) dataGridViewCellTmp.ReadOnlyInternal = true; this.individualReadOnlyCells.Add(dataGridViewCellTmp); } - for (int column = columnIndex+1; column < this.Columns.Count; column++) + for (int column = columnIndex + 1; column < this.Columns.Count; column++) { dataGridViewCellTmp = this.Rows[rowIndex].Cells[column]; dataGridViewCellTmp.ReadOnlyInternal = true; @@ -27345,7 +27347,7 @@ protected virtual void SetSelectedCellCore(int columnIndex, int rowIndex, bool s dataGridViewCellTmp.SelectedInternal = true; this.individualSelectedCells.Add(dataGridViewCellTmp); } - for (int row = rowIndex+1; row < this.Rows.Count; row++) + for (int row = rowIndex + 1; row < this.Rows.Count; row++) { dataGridViewCellTmp = this.Rows[row].Cells[columnIndex]; dataGridViewCellTmp.SelectedInternal = true; @@ -27378,7 +27380,7 @@ protected virtual void SetSelectedCellCore(int columnIndex, int rowIndex, bool s dataGridViewCellTmp.SelectedInternal = true; this.individualSelectedCells.Add(dataGridViewCellTmp); } - for (int column = columnIndex+1; column < this.Columns.Count; column++) + for (int column = columnIndex + 1; column < this.Columns.Count; column++) { dataGridViewCellTmp = this.Rows[rowIndex].Cells[column]; dataGridViewCellTmp.SelectedInternal = true; @@ -27428,171 +27430,171 @@ internal void SetSelectedCellCoreInternal(int columnIndex, int rowIndex, bool se switch (this.SelectionMode) { case DataGridViewSelectionMode.CellSelect: - { - if (selected && !this.MultiSelect) { - Debug.Assert(this.individualSelectedCells.Count <= 1); - RemoveIndividuallySelectedCells(); + if (selected && !this.MultiSelect) + { + Debug.Assert(this.individualSelectedCells.Count <= 1); + RemoveIndividuallySelectedCells(); + } + SetSelectedCellCore(columnIndex, rowIndex, selected); + break; } - SetSelectedCellCore(columnIndex, rowIndex, selected); - break; - } case DataGridViewSelectionMode.FullColumnSelect: - { - if (selected) { - if (!this.MultiSelect) + if (selected) { - Debug.Assert(this.selectedBandIndexes.Count <= 1); - int bandIndex = 0; - while (bandIndex < this.selectedBandIndexes.Count) + if (!this.MultiSelect) { - if (this.selectedBandIndexes[bandIndex] != columnIndex) - { - // deselect currently selected column - SetSelectedColumnCore(this.selectedBandIndexes[bandIndex], false); - } - else + Debug.Assert(this.selectedBandIndexes.Count <= 1); + int bandIndex = 0; + while (bandIndex < this.selectedBandIndexes.Count) { - bandIndex++; + if (this.selectedBandIndexes[bandIndex] != columnIndex) + { + // deselect currently selected column + SetSelectedColumnCore(this.selectedBandIndexes[bandIndex], false); + } + else + { + bandIndex++; + } } } + if (!this.selectedBandIndexes.Contains(columnIndex)) + { + SetSelectedColumnCore(columnIndex, true); + } } - if (!this.selectedBandIndexes.Contains(columnIndex)) - { - SetSelectedColumnCore(columnIndex, true); - } - } - else - { - if (this.selectedBandIndexes.Contains(columnIndex)) + else { - SetSelectedColumnCore(columnIndex, false); + if (this.selectedBandIndexes.Contains(columnIndex)) + { + SetSelectedColumnCore(columnIndex, false); + } } + break; } - break; - } case DataGridViewSelectionMode.ColumnHeaderSelect: - { - if (selected) { - if (!this.MultiSelect) + if (selected) { - Debug.Assert(this.selectedBandIndexes.Count <= 1); - if (this.selectedBandIndexes.Count > 0) - { - SetSelectedColumnCore(this.selectedBandIndexes.HeadInt, false); - } - else + if (!this.MultiSelect) { - RemoveIndividuallySelectedCells(); + Debug.Assert(this.selectedBandIndexes.Count <= 1); + if (this.selectedBandIndexes.Count > 0) + { + SetSelectedColumnCore(this.selectedBandIndexes.HeadInt, false); + } + else + { + RemoveIndividuallySelectedCells(); + } } + SetSelectedCellCore(columnIndex, rowIndex, true); } - SetSelectedCellCore(columnIndex, rowIndex, true); - } - else - { - if (!this.MultiSelect) + else { - Debug.Assert(this.selectedBandIndexes.Count <= 1); - if (this.selectedBandIndexes.Count > 0) + if (!this.MultiSelect) { - SetSelectedColumnCore(this.selectedBandIndexes.HeadInt, false); + Debug.Assert(this.selectedBandIndexes.Count <= 1); + if (this.selectedBandIndexes.Count > 0) + { + SetSelectedColumnCore(this.selectedBandIndexes.HeadInt, false); + } + else + { + SetSelectedCellCore(columnIndex, rowIndex, false); + } } else { SetSelectedCellCore(columnIndex, rowIndex, false); } } - else - { - SetSelectedCellCore(columnIndex, rowIndex, false); - } + break; } - break; - } case DataGridViewSelectionMode.FullRowSelect: - { - if (selected) { - if (!this.MultiSelect) + if (selected) { - Debug.Assert(this.selectedBandIndexes.Count <= 1); - int bandIndex = 0; - while (bandIndex < this.selectedBandIndexes.Count) + if (!this.MultiSelect) { - if (this.selectedBandIndexes[bandIndex] != rowIndex) - { - // deselect currently selected row - SetSelectedRowCore(this.selectedBandIndexes[bandIndex], false); - } - else + Debug.Assert(this.selectedBandIndexes.Count <= 1); + int bandIndex = 0; + while (bandIndex < this.selectedBandIndexes.Count) { - bandIndex++; + if (this.selectedBandIndexes[bandIndex] != rowIndex) + { + // deselect currently selected row + SetSelectedRowCore(this.selectedBandIndexes[bandIndex], false); + } + else + { + bandIndex++; + } } } + if ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) == 0) + { + Debug.Assert(this.selectedBandIndexes.Contains(rowIndex) == + ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) != 0)); + SetSelectedRowCore(rowIndex, true); + } } - if ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) == 0) - { - Debug.Assert(this.selectedBandIndexes.Contains(rowIndex) == - ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) != 0)); - SetSelectedRowCore(rowIndex, true); - } - } - else - { - if ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) != 0) + else { - Debug.Assert(this.selectedBandIndexes.Contains(rowIndex) == - ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) != 0)); - SetSelectedRowCore(rowIndex, false); + if ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) != 0) + { + Debug.Assert(this.selectedBandIndexes.Contains(rowIndex) == + ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) != 0)); + SetSelectedRowCore(rowIndex, false); + } } + break; } - break; - } case DataGridViewSelectionMode.RowHeaderSelect: - { - if (selected) { - if (!this.MultiSelect) + if (selected) { - Debug.Assert(this.selectedBandIndexes.Count <= 1); - if (this.selectedBandIndexes.Count > 0) - { - SetSelectedRowCore(this.selectedBandIndexes.HeadInt, false); - } - else + if (!this.MultiSelect) { - RemoveIndividuallySelectedCells(); + Debug.Assert(this.selectedBandIndexes.Count <= 1); + if (this.selectedBandIndexes.Count > 0) + { + SetSelectedRowCore(this.selectedBandIndexes.HeadInt, false); + } + else + { + RemoveIndividuallySelectedCells(); + } } + SetSelectedCellCore(columnIndex, rowIndex, true); } - SetSelectedCellCore(columnIndex, rowIndex, true); - } - else - { - if (!this.MultiSelect) + else { - Debug.Assert(this.selectedBandIndexes.Count <= 1); - if (this.selectedBandIndexes.Count > 0) + if (!this.MultiSelect) { - SetSelectedRowCore(this.selectedBandIndexes.HeadInt, false); + Debug.Assert(this.selectedBandIndexes.Count <= 1); + if (this.selectedBandIndexes.Count > 0) + { + SetSelectedRowCore(this.selectedBandIndexes.HeadInt, false); + } + else + { + SetSelectedCellCore(columnIndex, rowIndex, false); + } } else { SetSelectedCellCore(columnIndex, rowIndex, false); } } - else - { - SetSelectedCellCore(columnIndex, rowIndex, false); - } + break; } - break; - } } } finally @@ -27680,44 +27682,44 @@ private void SetSelectedElementCore(int columnIndex, int rowIndex, bool selected switch (this.SelectionMode) { case DataGridViewSelectionMode.CellSelect: - { - SetSelectedCellCore(columnIndex, rowIndex, selected); - break; - } - case DataGridViewSelectionMode.RowHeaderSelect: - { - if (columnIndex == -1) { - SetSelectedRowCore(rowIndex, selected); + SetSelectedCellCore(columnIndex, rowIndex, selected); + break; } - else + case DataGridViewSelectionMode.RowHeaderSelect: { - SetSelectedCellCore(columnIndex, rowIndex, selected); + if (columnIndex == -1) + { + SetSelectedRowCore(rowIndex, selected); + } + else + { + SetSelectedCellCore(columnIndex, rowIndex, selected); + } + break; } - break; - } case DataGridViewSelectionMode.ColumnHeaderSelect: - { - if (rowIndex == -1) { - SetSelectedColumnCore(columnIndex, selected); + if (rowIndex == -1) + { + SetSelectedColumnCore(columnIndex, selected); + } + else + { + SetSelectedCellCore(columnIndex, rowIndex, selected); + } + break; } - else + case DataGridViewSelectionMode.FullRowSelect: { - SetSelectedCellCore(columnIndex, rowIndex, selected); + SetSelectedRowCore(rowIndex, selected); + break; } - break; - } - case DataGridViewSelectionMode.FullRowSelect: - { - SetSelectedRowCore(rowIndex, selected); - break; - } case DataGridViewSelectionMode.FullColumnSelect: - { - SetSelectedColumnCore(columnIndex, selected); - break; - } + { + SetSelectedColumnCore(columnIndex, selected); + break; + } } } @@ -27839,7 +27841,7 @@ public virtual void Sort(DataGridViewColumn dataGridViewColumn, ListSortDirectio throw new InvalidOperationException(string.Format(SR.DataGridView_OperationDisabledInVirtualMode)); } - SortInternal(null, dataGridViewColumn, direction); + SortInternal(null, dataGridViewColumn, direction); } public virtual void Sort(IComparer comparer) @@ -27910,8 +27912,8 @@ private void SortInternal(IComparer comparer, DataGridViewColumn dataGridViewCol Debug.Assert(0 == this.Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)); } - if (this.sortedColumn != null && - this.sortedColumn.SortMode == DataGridViewColumnSortMode.Automatic && + if (this.sortedColumn != null && + this.sortedColumn.SortMode == DataGridViewColumnSortMode.Automatic && this.sortedColumn.HasHeaderCell) { this.sortedColumn.HeaderCell.SortGlyphDirection = SortOrder.None; @@ -27932,7 +27934,7 @@ private void SortInternal(IComparer comparer, DataGridViewColumn dataGridViewCol this.sortedColumn = null; this.sortOrder = SortOrder.None; } - + if (this.DataSource == null) { // Displayed rows may end up all spread out in the final layout. @@ -27951,10 +27953,10 @@ private void SortInternal(IComparer comparer, DataGridViewColumn dataGridViewCol { if (!IsInnerCellOutOfBounds(this.ptCurrentCellCache.X, this.ptCurrentCellCache.Y)) { - SetAndSelectCurrentCellAddress(this.ptCurrentCellCache.X, - this.ptCurrentCellCache.Y, - true, - false, + SetAndSelectCurrentCellAddress(this.ptCurrentCellCache.X, + this.ptCurrentCellCache.Y, + true, + false, false, false /*clearSelection*/, false /*forceCurrentCellSelection*/); @@ -28043,7 +28045,7 @@ internal void SwapSortedRows(int rowIndex1, int rowIndex2) } } - private void DataGridViewHScrolled(object sender, ScrollEventArgs se) + private void DataGridViewHScrolled(object sender, ScrollEventArgs se) { if (!this.Enabled) { @@ -28096,7 +28098,7 @@ private void DataGridViewHScrolled(object sender, ScrollEventArgs se) } } - private void DataGridViewVScrolled(object sender, ScrollEventArgs se) + private void DataGridViewVScrolled(object sender, ScrollEventArgs se) { if (!this.Enabled) { @@ -28140,55 +28142,55 @@ private void DataGridViewVScrolled(object sender, ScrollEventArgs se) switch (se.Type) { case ScrollEventType.SmallIncrement: - { - // Making sure that when the last visible scrolling row is taller than the data area, it does not get scrolled off screen - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0); - if (this.vertScrollBar.Value + this.Rows.SharedRow(this.displayedBandsInfo.FirstDisplayedScrollingRow).GetHeight(this.displayedBandsInfo.FirstDisplayedScrollingRow) <= - this.vertScrollBar.Maximum - ComputeHeightOfFittingTrailingScrollingRows(totalVisibleFrozenHeight)) { - ScrollRowsByCount(1, ScrollEventType.SmallIncrement); + // Making sure that when the last visible scrolling row is taller than the data area, it does not get scrolled off screen + Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0); + if (this.vertScrollBar.Value + this.Rows.SharedRow(this.displayedBandsInfo.FirstDisplayedScrollingRow).GetHeight(this.displayedBandsInfo.FirstDisplayedScrollingRow) <= + this.vertScrollBar.Maximum - ComputeHeightOfFittingTrailingScrollingRows(totalVisibleFrozenHeight)) + { + ScrollRowsByCount(1, ScrollEventType.SmallIncrement); + } + se.NewValue = this.VerticalOffset; + break; } - se.NewValue = this.VerticalOffset; - break; - } case ScrollEventType.SmallDecrement: - { - if (this.vertScrollBar.Value != this.vertScrollBar.Minimum) { - ScrollRowsByCount(-1, ScrollEventType.SmallDecrement); + if (this.vertScrollBar.Value != this.vertScrollBar.Minimum) + { + ScrollRowsByCount(-1, ScrollEventType.SmallDecrement); + } + se.NewValue = this.VerticalOffset; + break; } - se.NewValue = this.VerticalOffset; - break; - } case ScrollEventType.LargeIncrement: - { - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0); - int firstDisplayedScrollingRowHeight = this.Rows.SharedRow(this.displayedBandsInfo.FirstDisplayedScrollingRow).GetHeight(this.displayedBandsInfo.FirstDisplayedScrollingRow); - this.VerticalOffset += Math.Max(firstDisplayedScrollingRowHeight, this.vertScrollBar.LargeChange); - se.NewValue = this.VerticalOffset; - break; - } + { + Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0); + int firstDisplayedScrollingRowHeight = this.Rows.SharedRow(this.displayedBandsInfo.FirstDisplayedScrollingRow).GetHeight(this.displayedBandsInfo.FirstDisplayedScrollingRow); + this.VerticalOffset += Math.Max(firstDisplayedScrollingRowHeight, this.vertScrollBar.LargeChange); + se.NewValue = this.VerticalOffset; + break; + } case ScrollEventType.LargeDecrement: - { - this.VerticalOffset -= this.vertScrollBar.LargeChange; - se.NewValue = this.VerticalOffset; - break; - } + { + this.VerticalOffset -= this.vertScrollBar.LargeChange; + se.NewValue = this.VerticalOffset; + break; + } case ScrollEventType.ThumbTrack: case ScrollEventType.First: case ScrollEventType.Last: - { - if (se.NewValue >= this.vertScrollBar.Maximum - this.vertScrollBar.LargeChange) - { - // Need to display the last scrolling row - this.VerticalOffset = this.vertScrollBar.Maximum - ComputeHeightOfFittingTrailingScrollingRows(totalVisibleFrozenHeight); - } - else { - this.VerticalOffset = se.NewValue; + if (se.NewValue >= this.vertScrollBar.Maximum - this.vertScrollBar.LargeChange) + { + // Need to display the last scrolling row + this.VerticalOffset = this.vertScrollBar.Maximum - ComputeHeightOfFittingTrailingScrollingRows(totalVisibleFrozenHeight); + } + else + { + this.VerticalOffset = se.NewValue; + } + break; } - break; - } } } @@ -28348,7 +28350,7 @@ private bool TabToNextCell() private bool TabToPreviousCell() { bool success; - + DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); int firstVisibleColumnIndex = (dataGridViewColumn == null) ? -1 : dataGridViewColumn.Index; int firstVisibleRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); @@ -28844,16 +28846,16 @@ private void UpdateMouseEnteredCell(HitTestInfo hti, MouseEventArgs e) htiToUse = HitTest(ptMouse.X, ptMouse.Y); } - if (htiToUse.Type != DataGridViewHitTestType.None && - htiToUse.Type != DataGridViewHitTestType.HorizontalScrollBar && + if (htiToUse.Type != DataGridViewHitTestType.None && + htiToUse.Type != DataGridViewHitTestType.HorizontalScrollBar && htiToUse.Type != DataGridViewHitTestType.VerticalScrollBar) { if (this.ptMouseEnteredCell.X != htiToUse.col || this.ptMouseEnteredCell.Y != htiToUse.row) { DataGridViewCellEventArgs dgvce; - if (this.ptMouseEnteredCell.X >= -1 && - this.ptMouseEnteredCell.X < this.Columns.Count && - this.ptMouseEnteredCell.Y >= -1 && + if (this.ptMouseEnteredCell.X >= -1 && + this.ptMouseEnteredCell.X < this.Columns.Count && + this.ptMouseEnteredCell.Y >= -1 && this.ptMouseEnteredCell.Y < this.Rows.Count) { dgvce = new DataGridViewCellEventArgs(this.ptMouseEnteredCell.X, this.ptMouseEnteredCell.Y); @@ -28875,9 +28877,9 @@ private void UpdateMouseEnteredCell(HitTestInfo hti, MouseEventArgs e) } else if (this.ptMouseEnteredCell.X != -2) { - if (this.ptMouseEnteredCell.X >= -1 && - this.ptMouseEnteredCell.X < this.Columns.Count && - this.ptMouseEnteredCell.Y >= -1 && + if (this.ptMouseEnteredCell.X >= -1 && + this.ptMouseEnteredCell.X < this.Columns.Count && + this.ptMouseEnteredCell.Y >= -1 && this.ptMouseEnteredCell.Y < this.Rows.Count) { DataGridViewCellEventArgs dgvce = new DataGridViewCellEventArgs(this.ptMouseEnteredCell.X, this.ptMouseEnteredCell.Y); @@ -28948,26 +28950,26 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu SelectCellRange(newEdgeColumnIndex, newEdgeRowIndex, dataGridViewColumn.Index, anchorRowIndex, true); } } - else if (newEdgeRowIndex > oldEdgeRowIndex && + else if (newEdgeRowIndex > oldEdgeRowIndex && anchorRowIndex <= oldEdgeRowIndex && newEdgeColumnIndex == oldEdgeColumnIndex) { // h3 if (this.Columns.DisplayInOrder(anchorColumnIndex, newEdgeColumnIndex) || anchorColumnIndex == newEdgeColumnIndex) { - SelectCellRange(anchorColumnIndex, - this.Rows.GetNextRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), - newEdgeColumnIndex, - newEdgeRowIndex, + SelectCellRange(anchorColumnIndex, + this.Rows.GetNextRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), + newEdgeColumnIndex, + newEdgeRowIndex, true); } else { // newEdgeColumnIndex before anchorColumnIndex - SelectCellRange(newEdgeColumnIndex, - this.Rows.GetNextRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), - anchorColumnIndex, - newEdgeRowIndex, + SelectCellRange(newEdgeColumnIndex, + this.Rows.GetNextRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), + anchorColumnIndex, + newEdgeRowIndex, true); } } @@ -28978,19 +28980,19 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu // h4 if (this.Columns.DisplayInOrder(anchorColumnIndex, newEdgeColumnIndex) || anchorColumnIndex == newEdgeColumnIndex) { - SelectCellRange(anchorColumnIndex, - newEdgeRowIndex, - newEdgeColumnIndex, - this.Rows.GetPreviousRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), + SelectCellRange(anchorColumnIndex, + newEdgeRowIndex, + newEdgeColumnIndex, + this.Rows.GetPreviousRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), true); } else { // newEdgeColumnIndex before anchorColumnIndex - SelectCellRange(newEdgeColumnIndex, - newEdgeRowIndex, - anchorColumnIndex, - this.Rows.GetPreviousRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), + SelectCellRange(newEdgeColumnIndex, + newEdgeRowIndex, + anchorColumnIndex, + this.Rows.GetPreviousRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), true); } } @@ -29002,10 +29004,10 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu DataGridViewColumn dataGridViewColumn = this.Columns.GetNextColumn(this.Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); SelectCellRange(dataGridViewColumn.Index, anchorRowIndex, newEdgeColumnIndex, oldEdgeRowIndex, true); - SelectCellRange(anchorColumnIndex, - this.Rows.GetNextRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), + SelectCellRange(anchorColumnIndex, + this.Rows.GetNextRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), newEdgeColumnIndex, - newEdgeRowIndex, + newEdgeRowIndex, true); } else if (this.Columns.DisplayInOrder(oldEdgeColumnIndex, newEdgeColumnIndex) && @@ -29018,9 +29020,9 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu Debug.Assert(dataGridViewColumn != null); SelectCellRange(dataGridViewColumn.Index, oldEdgeRowIndex, newEdgeColumnIndex, anchorRowIndex, true); SelectCellRange(anchorColumnIndex, - newEdgeRowIndex, + newEdgeRowIndex, newEdgeColumnIndex, - this.Rows.GetPreviousRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), + this.Rows.GetPreviousRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), true); } else @@ -29059,9 +29061,9 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu Debug.Assert(dataGridViewColumn != null); SelectCellRange(newEdgeColumnIndex, oldEdgeRowIndex, dataGridViewColumn.Index, anchorRowIndex, true); SelectCellRange(newEdgeColumnIndex, - newEdgeRowIndex, + newEdgeRowIndex, anchorColumnIndex, - this.Rows.GetPreviousRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), + this.Rows.GetPreviousRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), true); } else @@ -29096,9 +29098,9 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu Debug.Assert(dataGridViewColumn != null); SelectCellRange(newEdgeColumnIndex, anchorRowIndex, dataGridViewColumn.Index, oldEdgeRowIndex, true); SelectCellRange(newEdgeColumnIndex, - this.Rows.GetNextRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), + this.Rows.GetNextRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), anchorColumnIndex, - newEdgeRowIndex, + newEdgeRowIndex, true); } else if (this.Columns.DisplayInOrder(newEdgeColumnIndex, oldEdgeColumnIndex)) @@ -29147,9 +29149,9 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu // d3 dataGridViewColumn = this.Columns.GetPreviousColumn(this.Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); - SelectCellRange(oldEdgeColumnIndex, - this.Rows.GetNextRow(newEdgeRowIndex, DataGridViewElementStates.Visible), - anchorColumnIndex, + SelectCellRange(oldEdgeColumnIndex, + this.Rows.GetNextRow(newEdgeRowIndex, DataGridViewElementStates.Visible), + anchorColumnIndex, oldEdgeRowIndex, false); SelectCellRange(newEdgeColumnIndex, @@ -29187,9 +29189,9 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu // c3 dataGridViewColumn = this.Columns.GetPreviousColumn(this.Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); - SelectCellRange(oldEdgeColumnIndex, - oldEdgeRowIndex, - anchorColumnIndex, + SelectCellRange(oldEdgeColumnIndex, + oldEdgeRowIndex, + anchorColumnIndex, this.Rows.GetPreviousRow(newEdgeRowIndex, DataGridViewElementStates.Visible), false); SelectCellRange(newEdgeColumnIndex, @@ -29261,8 +29263,8 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu // d2 dataGridViewColumn = this.Columns.GetNextColumn(this.Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); - SelectCellRange(anchorColumnIndex, - this.Rows.GetNextRow(newEdgeRowIndex, DataGridViewElementStates.Visible), + SelectCellRange(anchorColumnIndex, + this.Rows.GetNextRow(newEdgeRowIndex, DataGridViewElementStates.Visible), oldEdgeColumnIndex, oldEdgeRowIndex, false); @@ -29300,9 +29302,9 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu // c2 dataGridViewColumn = this.Columns.GetNextColumn(this.Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); - SelectCellRange(anchorColumnIndex, - oldEdgeRowIndex, - oldEdgeColumnIndex, + SelectCellRange(anchorColumnIndex, + oldEdgeRowIndex, + oldEdgeColumnIndex, this.Rows.GetPreviousRow(newEdgeRowIndex, DataGridViewElementStates.Visible), false); SelectCellRange(dataGridViewColumn.Index, @@ -29339,10 +29341,10 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu // c1 if (this.Columns.DisplayInOrder(anchorColumnIndex, oldEdgeColumnIndex)) { - SelectCellRange(anchorColumnIndex, - oldEdgeRowIndex, - oldEdgeColumnIndex, - this.Rows.GetPreviousRow(newEdgeRowIndex, DataGridViewElementStates.Visible), + SelectCellRange(anchorColumnIndex, + oldEdgeRowIndex, + oldEdgeColumnIndex, + this.Rows.GetPreviousRow(newEdgeRowIndex, DataGridViewElementStates.Visible), false); } else @@ -29399,7 +29401,7 @@ private void VertScrollTimerHandler() Point ptMouse = PointToClient(Control.MousePosition); HitTestInfo hti = HitTest(ptMouse.X, ptMouse.Y); int xOffset, yOffset, mouseX = ptMouse.X, mouseY = ptMouse.Y; - + if (GetOutOfBoundCorrectedHitTestInfo(ref hti, ref mouseX, ref mouseY, out xOffset, out yOffset)) { if (yOffset != 0) @@ -29488,23 +29490,23 @@ private void WireScrollBarsEvents() /// /// Handles the WM_CONTEXTMENU message /// - internal override void WmContextMenu(ref Message m) + internal override void WmContextMenu(ref Message m) { ContextMenuStrip contextMenuStrip; - int x = unchecked( (int)(short)(long)m.LParam); - int y = unchecked( (int) (long)m.LParam) >> 16; + int x = unchecked((int)(short)(long)m.LParam); + int y = unchecked((int)(long)m.LParam) >> 16; Point client; bool keyboardActivated = false; // lparam will be exactly -1 when the user invokes the context menu // with the keyboard. // - if (unchecked( (int) (long)m.LParam) == -1) + if (unchecked((int)(long)m.LParam) == -1) { keyboardActivated = true; - client = new Point(this.Width/2, this.Height/2); - contextMenuStrip = (ContextMenuStrip) this.ContextMenuStrip; + client = new Point(this.Width / 2, this.Height / 2); + contextMenuStrip = (ContextMenuStrip)this.ContextMenuStrip; } - else + else { client = PointToClient(new Point(x, y)); HitTestInfo hti = HitTest(client.X, client.Y); @@ -29534,7 +29536,7 @@ internal override void WmContextMenu(ref Message m) } else { - contextMenuStrip = (ContextMenuStrip) this.ContextMenuStrip; + contextMenuStrip = (ContextMenuStrip)this.ContextMenuStrip; } } @@ -29559,7 +29561,7 @@ private void WmGetDlgCode(ref Message m) Keys modifierKeys = ModifierKeys; if (GetTabKeyEffective((modifierKeys & Keys.Shift) == Keys.Shift, (modifierKeys & Keys.Control) == Keys.Control)) { - m.Result = (IntPtr) ((long) m.Result | NativeMethods.DLGC_WANTTAB); + m.Result = (IntPtr)((long)m.Result | NativeMethods.DLGC_WANTTAB); } } @@ -29570,7 +29572,7 @@ private unsafe bool WmNotify(ref Message m) return false; } - NativeMethods.NMHDR* nmhdr = (NativeMethods.NMHDR *)m.LParam; + NativeMethods.NMHDR* nmhdr = (NativeMethods.NMHDR*)m.LParam; if (nmhdr->code == NativeMethods.TTN_GETDISPINFO && !DesignMode) { string toolTip = this.ToolTipPrivate; @@ -29579,7 +29581,7 @@ private unsafe bool WmNotify(ref Message m) { // MSDN: Setting the max width has the added benefit of enabling multiline tool tips! UnsafeNativeMethods.SendMessage(new HandleRef(this, nmhdr->hwndFrom), NativeMethods.TTM_SETMAXTIPWIDTH, 0, SystemInformation.MaxWindowTrackSize.Width); - NativeMethods.TOOLTIPTEXT ttt = (NativeMethods.TOOLTIPTEXT) m.GetLParam(typeof(NativeMethods.TOOLTIPTEXT)); + NativeMethods.TOOLTIPTEXT ttt = (NativeMethods.TOOLTIPTEXT)m.GetLParam(typeof(NativeMethods.TOOLTIPTEXT)); ttt.lpszText = toolTip; @@ -29595,7 +29597,7 @@ private unsafe bool WmNotify(ref Message m) return false; } - protected override void WndProc(ref Message m) + protected override void WndProc(ref Message m) { switch (m.Msg) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRow.cs index 105a2096913..56d912c8cfe 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRow.cs @@ -1802,7 +1802,7 @@ public override Rectangle Bounds } Rectangle rowRect = owner.DataGridView.RectangleToScreen(owner.DataGridView.GetRowDisplayRectangle(owner.Index, false /*cutOverflow*/)); - + int horizontalScrollBarHeight = 0; if (this.owner.DataGridView.HorizontalScrollBarVisible) { @@ -1823,7 +1823,7 @@ public override Rectangle Bounds rowRectBottom = dataGridViewRect.Bottom - owner.DataGridView.BorderWidth - horizontalScrollBarHeight; } - + if ((dataGridViewRect.Top + columnHeadersHeight) > rowRect.Top) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowCollection.cs index 713299a6799..096e530ef51 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowCollection.cs @@ -15,7 +15,7 @@ namespace System.Windows.Forms using System.ComponentModel.Design.Serialization; using System.Globalization; using System.Diagnostics.CodeAnalysis; - + /// /// Represents a collection of objects in the /// control. @@ -26,7 +26,7 @@ namespace System.Windows.Forms "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + AssemblyRef.SystemDesign), SuppressMessage("Microsoft.Design", "CA1010:CollectionsShouldImplementGenericInterface") // Consider adding an IList implementation ] - public class DataGridViewRowCollection : ICollection ,IList + public class DataGridViewRowCollection : ICollection, IList { #if DEBUG // set to false when the cached row heights are dirty and should not be accessed. @@ -47,7 +47,7 @@ public class DataGridViewRowCollection : ICollection ,IList int IList.Add(object value) { - return this.Add((DataGridViewRow) value); + return this.Add((DataGridViewRow)value); } void IList.Clear() @@ -67,12 +67,12 @@ int IList.IndexOf(object value) void IList.Insert(int index, object value) { - this.Insert(index, (DataGridViewRow) value); + this.Insert(index, (DataGridViewRow)value); } void IList.Remove(object value) { - this.Remove((DataGridViewRow) value); + this.Remove((DataGridViewRow)value); } void IList.RemoveAt(int index) @@ -100,9 +100,9 @@ object IList.this[int index] { get { - return this[index]; + return this[index]; } - set + set { throw new NotSupportedException(); } @@ -115,9 +115,9 @@ void ICollection.CopyTo(Array array, int index) this.items.CopyTo(array, index); } - int ICollection.Count + int ICollection.Count { - get + get { return this.Count; } @@ -200,7 +200,7 @@ internal ArrayList SharedList public DataGridViewRow SharedRow(int rowIndex) { - return (DataGridViewRow) this.SharedList[rowIndex]; + return (DataGridViewRow)this.SharedList[rowIndex]; } protected DataGridView DataGridView @@ -214,9 +214,9 @@ protected DataGridView DataGridView /// /// Retrieves the DataGridViewRow with the specified index. /// - public DataGridViewRow this[int index] + public DataGridViewRow this[int index] { - get + get { DataGridViewRow dataGridViewRow = SharedRow(index); if (dataGridViewRow.Index == -1) @@ -235,7 +235,7 @@ public DataGridViewRow this[int index] } // unshare row - DataGridViewRow newDataGridViewRow = (DataGridViewRow) dataGridViewRow.Clone(); + DataGridViewRow newDataGridViewRow = (DataGridViewRow)dataGridViewRow.Clone(); newDataGridViewRow.IndexInternal = index; newDataGridViewRow.DataGridViewInternal = dataGridViewRow.DataGridView; newDataGridViewRow.StateInternal = SharedRowState(index); @@ -765,7 +765,7 @@ private int AddDuplicateRow(DataGridViewRow rowTemplate, bool newRow) { Debug.Assert(this.DataGridView != null); - DataGridViewRow dataGridViewRow = (DataGridViewRow) rowTemplate.Clone(); + DataGridViewRow dataGridViewRow = (DataGridViewRow)rowTemplate.Clone(); dataGridViewRow.StateInternal = DataGridViewElementStates.None; dataGridViewRow.DataGridViewInternal = this.dataGridView; DataGridViewCellCollection dgvcc = dataGridViewRow.Cells; @@ -798,7 +798,7 @@ private int AddDuplicateRow(DataGridViewRow rowTemplate, bool newRow) this.rowStates.Add(rowState); return this.SharedList.Add(dataGridViewRow); } - + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual void AddRange(params DataGridViewRow[] dataGridViewRows) { @@ -837,7 +837,7 @@ public virtual void AddRange(params DataGridViewRow[] dataGridViewRows) // OnAddingRows checks for Selected flag of each row and their dimension. this.DataGridView.OnAddingRows(dataGridViewRows, true /*checkFrozenStates*/); // will throw an exception if the addition is illegal - foreach(DataGridViewRow dataGridViewRow in dataGridViewRows) + foreach (DataGridViewRow dataGridViewRow in dataGridViewRows) { Debug.Assert(dataGridViewRow.Cells.Count == this.DataGridView.Columns.Count); int columnIndex = 0; @@ -904,7 +904,7 @@ internal void ClearInternal(bool recreateNewRow) if (rowCount > 0) { this.DataGridView.OnClearingRows(); - + for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { SharedRow(rowIndex).DetachFromDataGridView(); @@ -919,7 +919,7 @@ internal void ClearInternal(bool recreateNewRow) #endif OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null), 0, rowCount, true, false, recreateNewRow, new Point(-1, -1)); } - else if (recreateNewRow && + else if (recreateNewRow && this.DataGridView.Columns.Count != 0 && this.DataGridView.AllowUserToAddRowsInternal && this.items.Count == 0) // accessing AllowUserToAddRowsInternal can trigger a nested call to ClearInternal. Rows count needs to be checked again. @@ -1130,7 +1130,7 @@ public int GetNextRow(int indexStart, DataGridViewElementStates includeFilter) return (index < this.items.Count) ? index : -1; } - public int GetNextRow(int indexStart, + public int GetNextRow(int indexStart, DataGridViewElementStates includeFilter, DataGridViewElementStates excludeFilter) { @@ -1181,7 +1181,7 @@ public int GetPreviousRow(int indexStart, DataGridViewElementStates includeFilte return (index >= 0) ? index : -1; } - public int GetPreviousRow(int indexStart, + public int GetPreviousRow(int indexStart, DataGridViewElementStates includeFilter, DataGridViewElementStates excludeFilter) { @@ -1314,7 +1314,7 @@ public int GetRowsHeight(DataGridViewElementStates includeFilter) } break; } - + int rowsHeight = 0; for (int rowIndex = 0; rowIndex < this.items.Count; rowIndex++) { @@ -1400,7 +1400,7 @@ public int IndexOf(DataGridViewRow dataGridViewRow) public virtual void Insert(int rowIndex, params object[] values) { Debug.Assert(this.DataGridView != null); - + if (values == null) { throw new ArgumentNullException(nameof(values)); @@ -1442,7 +1442,7 @@ public virtual void Insert(int rowIndex, DataGridViewRow dataGridViewRow) { throw new InvalidOperationException(string.Format(SR.DataGridView_ForbiddenOperationInEventHandler)); } - + InsertInternal(rowIndex, dataGridViewRow); } @@ -1711,12 +1711,12 @@ private void InsertCopiesPrivate(DataGridViewRow rowTemplate, DataGridViewElemen Debug.Assert(this.rowStates.Count == this.SharedList.Count); if (count > 1) { - this.DataGridView.OnInsertedRow_PreNotification(indexDestination, 1); + this.DataGridView.OnInsertedRow_PreNotification(indexDestination, 1); if (RowIsSharable(indexDestination)) { DataGridViewRow rowTemplate2 = SharedRow(indexDestination); // Done once only, continue to check if this is OK - will throw an exception if the insertion is illegal. - this.DataGridView.OnInsertingRow(indexDestination + 1, rowTemplate2, rowTemplateState, ref newCurrentCell, false, count-1, false /*force*/); + this.DataGridView.OnInsertingRow(indexDestination + 1, rowTemplate2, rowTemplateState, ref newCurrentCell, false, count - 1, false /*force*/); for (int i = 1; i < count; i++) { this.SharedList.Insert(indexDestination + i, rowTemplate2); @@ -1728,7 +1728,7 @@ private void InsertCopiesPrivate(DataGridViewRow rowTemplate, DataGridViewElemen this.cachedRowCountsAccessAllowed = false; #endif // Only calling this once instead of 'count-1' times. Continue to check if this is OK. - this.DataGridView.OnInsertedRow_PreNotification(indexDestination+1, count-1); + this.DataGridView.OnInsertedRow_PreNotification(indexDestination + 1, count - 1); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null), indexDestination, count, false, true, false, newCurrentCell); } else @@ -1763,7 +1763,7 @@ private void InsertDuplicateRow(int indexDestination, DataGridViewRow rowTemplat { Debug.Assert(this.DataGridView != null); - DataGridViewRow dataGridViewRow = (DataGridViewRow) rowTemplate.Clone(); + DataGridViewRow dataGridViewRow = (DataGridViewRow)rowTemplate.Clone(); dataGridViewRow.StateInternal = DataGridViewElementStates.None; dataGridViewRow.DataGridViewInternal = this.dataGridView; DataGridViewCellCollection dgvcc = dataGridViewRow.Cells; @@ -1889,11 +1889,11 @@ public virtual void InsertRange(int rowIndex, params DataGridViewRow[] dataGridV internal void InvalidateCachedRowCount(DataGridViewElementStates includeFilter) { - Debug.Assert(includeFilter == DataGridViewElementStates.Displayed || - includeFilter == DataGridViewElementStates.Selected || - includeFilter == DataGridViewElementStates.ReadOnly || - includeFilter == DataGridViewElementStates.Resizable || - includeFilter == DataGridViewElementStates.Frozen || + Debug.Assert(includeFilter == DataGridViewElementStates.Displayed || + includeFilter == DataGridViewElementStates.Selected || + includeFilter == DataGridViewElementStates.ReadOnly || + includeFilter == DataGridViewElementStates.Resizable || + includeFilter == DataGridViewElementStates.Frozen || includeFilter == DataGridViewElementStates.Visible); if (includeFilter == DataGridViewElementStates.Visible) @@ -1916,7 +1916,7 @@ internal void InvalidateCachedRowCount(DataGridViewElementStates includeFilter) internal void InvalidateCachedRowCounts() { - this.rowCountsVisible = this.rowCountsVisibleFrozen = this.rowCountsVisibleSelected = -1; + this.rowCountsVisible = this.rowCountsVisibleFrozen = this.rowCountsVisibleSelected = -1; #if DEBUG this.cachedRowCountsAccessAllowed = true; #endif @@ -1961,13 +1961,13 @@ protected virtual void OnCollectionChanged(CollectionChangeEventArgs e) } } - private void OnCollectionChanged(CollectionChangeEventArgs e, - int rowIndex, + private void OnCollectionChanged(CollectionChangeEventArgs e, + int rowIndex, int rowCount) { Debug.Assert(e.Action != CollectionChangeAction.Remove); Point newCurrentCell = new Point(-1, -1); - DataGridViewRow dataGridViewRow = (DataGridViewRow) e.Element; + DataGridViewRow dataGridViewRow = (DataGridViewRow)e.Element; int originalIndex = 0; if (dataGridViewRow != null && e.Action == CollectionChangeAction.Add) { @@ -1983,11 +1983,11 @@ private void OnCollectionChanged(CollectionChangeEventArgs e, OnCollectionChanged_PostNotification(e.Action, rowIndex, rowCount, dataGridViewRow, false, false, false, newCurrentCell); } - private void OnCollectionChanged(CollectionChangeEventArgs e, - int rowIndex, - int rowCount, - bool changeIsDeletion, - bool changeIsInsertion, + private void OnCollectionChanged(CollectionChangeEventArgs e, + int rowIndex, + int rowCount, + bool changeIsDeletion, + bool changeIsInsertion, bool recreateNewRow, Point newCurrentCell) { @@ -2007,10 +2007,10 @@ private void OnCollectionChanged(CollectionChangeEventArgs e, OnCollectionChanged_PostNotification(e.Action, rowIndex, rowCount, dataGridViewRow, changeIsDeletion, changeIsInsertion, recreateNewRow, newCurrentCell); } - private void OnCollectionChanged_PreNotification(CollectionChangeAction cca, + private void OnCollectionChanged_PreNotification(CollectionChangeAction cca, int rowIndex, int rowCount, - ref DataGridViewRow dataGridViewRow, + ref DataGridViewRow dataGridViewRow, bool changeIsInsertion) { Debug.Assert(this.DataGridView != null); @@ -2019,117 +2019,117 @@ private void OnCollectionChanged_PreNotification(CollectionChangeAction cca, switch (cca) { case CollectionChangeAction.Add: - { - int firstDisplayedRowHeight = 0; - UpdateRowCaches(rowIndex, ref dataGridViewRow, true); - if ((GetRowState(rowIndex) & DataGridViewElementStates.Visible) == 0) { - // Adding an invisible row - no need for repaint - useRowShortcut = true; - computeVisibleRows = changeIsInsertion; - } - else - { - int firstDisplayedRowIndex = this.DataGridView.FirstDisplayedRowIndex; - if (firstDisplayedRowIndex != -1) + int firstDisplayedRowHeight = 0; + UpdateRowCaches(rowIndex, ref dataGridViewRow, true); + if ((GetRowState(rowIndex) & DataGridViewElementStates.Visible) == 0) { - firstDisplayedRowHeight = SharedRow(firstDisplayedRowIndex).GetHeight(firstDisplayedRowIndex); + // Adding an invisible row - no need for repaint + useRowShortcut = true; + computeVisibleRows = changeIsInsertion; } - } - if (changeIsInsertion) - { - this.DataGridView.OnInsertedRow_PreNotification(rowIndex, 1); - if (!useRowShortcut) + else { - if ((GetRowState(rowIndex) & DataGridViewElementStates.Frozen) != 0) + int firstDisplayedRowIndex = this.DataGridView.FirstDisplayedRowIndex; + if (firstDisplayedRowIndex != -1) { - // Inserted row is frozen - useRowShortcut = this.DataGridView.FirstDisplayedScrollingRowIndex == -1 && - GetRowsHeightExceedLimit(DataGridViewElementStates.Visible, 0, rowIndex, this.DataGridView.LayoutInfo.Data.Height); + firstDisplayedRowHeight = SharedRow(firstDisplayedRowIndex).GetHeight(firstDisplayedRowIndex); } - else if (this.DataGridView.FirstDisplayedScrollingRowIndex != -1 && - rowIndex > this.DataGridView.FirstDisplayedScrollingRowIndex) + } + if (changeIsInsertion) + { + this.DataGridView.OnInsertedRow_PreNotification(rowIndex, 1); + if (!useRowShortcut) { - useRowShortcut = GetRowsHeightExceedLimit(DataGridViewElementStates.Visible, 0, rowIndex, this.DataGridView.LayoutInfo.Data.Height + this.DataGridView.VerticalScrollingOffset) && - firstDisplayedRowHeight <= this.DataGridView.LayoutInfo.Data.Height; + if ((GetRowState(rowIndex) & DataGridViewElementStates.Frozen) != 0) + { + // Inserted row is frozen + useRowShortcut = this.DataGridView.FirstDisplayedScrollingRowIndex == -1 && + GetRowsHeightExceedLimit(DataGridViewElementStates.Visible, 0, rowIndex, this.DataGridView.LayoutInfo.Data.Height); + } + else if (this.DataGridView.FirstDisplayedScrollingRowIndex != -1 && + rowIndex > this.DataGridView.FirstDisplayedScrollingRowIndex) + { + useRowShortcut = GetRowsHeightExceedLimit(DataGridViewElementStates.Visible, 0, rowIndex, this.DataGridView.LayoutInfo.Data.Height + this.DataGridView.VerticalScrollingOffset) && + firstDisplayedRowHeight <= this.DataGridView.LayoutInfo.Data.Height; + } } } - } - else - { - this.DataGridView.OnAddedRow_PreNotification(rowIndex); - if (!useRowShortcut) + else { - int displayedRowsHeightBeforeAddition = GetRowsHeight(DataGridViewElementStates.Visible) - this.DataGridView.VerticalScrollingOffset - dataGridViewRow.GetHeight(rowIndex); - dataGridViewRow = SharedRow(rowIndex); - useRowShortcut = this.DataGridView.LayoutInfo.Data.Height < displayedRowsHeightBeforeAddition && - firstDisplayedRowHeight <= this.DataGridView.LayoutInfo.Data.Height; + this.DataGridView.OnAddedRow_PreNotification(rowIndex); + if (!useRowShortcut) + { + int displayedRowsHeightBeforeAddition = GetRowsHeight(DataGridViewElementStates.Visible) - this.DataGridView.VerticalScrollingOffset - dataGridViewRow.GetHeight(rowIndex); + dataGridViewRow = SharedRow(rowIndex); + useRowShortcut = this.DataGridView.LayoutInfo.Data.Height < displayedRowsHeightBeforeAddition && + firstDisplayedRowHeight <= this.DataGridView.LayoutInfo.Data.Height; + } } + break; } - break; - } case CollectionChangeAction.Remove: - { - Debug.Assert(rowCount == 1); - DataGridViewElementStates rowStates = GetRowState(rowIndex); - bool deletedRowVisible = (rowStates & DataGridViewElementStates.Visible) != 0; - bool deletedRowFrozen = (rowStates & DataGridViewElementStates.Frozen) != 0; - - // Can't do this earlier since it would break UpdateRowCaches - this.rowStates.RemoveAt(rowIndex); - this.SharedList.RemoveAt(rowIndex); + { + Debug.Assert(rowCount == 1); + DataGridViewElementStates rowStates = GetRowState(rowIndex); + bool deletedRowVisible = (rowStates & DataGridViewElementStates.Visible) != 0; + bool deletedRowFrozen = (rowStates & DataGridViewElementStates.Frozen) != 0; + + // Can't do this earlier since it would break UpdateRowCaches + this.rowStates.RemoveAt(rowIndex); + this.SharedList.RemoveAt(rowIndex); #if DEBUG - this.DataGridView.dataStoreAccessAllowed = false; + this.DataGridView.dataStoreAccessAllowed = false; #endif - this.DataGridView.OnRemovedRow_PreNotification(rowIndex); - if (deletedRowVisible) - { - if (deletedRowFrozen) - { - // Delete row is frozen - useRowShortcut = this.DataGridView.FirstDisplayedScrollingRowIndex == -1 && - GetRowsHeightExceedLimit(DataGridViewElementStates.Visible, 0, rowIndex, this.DataGridView.LayoutInfo.Data.Height + SystemInformation.HorizontalScrollBarHeight); - } - else if (this.DataGridView.FirstDisplayedScrollingRowIndex != -1 && - rowIndex > this.DataGridView.FirstDisplayedScrollingRowIndex) + this.DataGridView.OnRemovedRow_PreNotification(rowIndex); + if (deletedRowVisible) { - int firstDisplayedRowHeight = 0; - int firstDisplayedRowIndex = this.DataGridView.FirstDisplayedRowIndex; - if (firstDisplayedRowIndex != -1) + if (deletedRowFrozen) { - firstDisplayedRowHeight = SharedRow(firstDisplayedRowIndex).GetHeight(firstDisplayedRowIndex); + // Delete row is frozen + useRowShortcut = this.DataGridView.FirstDisplayedScrollingRowIndex == -1 && + GetRowsHeightExceedLimit(DataGridViewElementStates.Visible, 0, rowIndex, this.DataGridView.LayoutInfo.Data.Height + SystemInformation.HorizontalScrollBarHeight); + } + else if (this.DataGridView.FirstDisplayedScrollingRowIndex != -1 && + rowIndex > this.DataGridView.FirstDisplayedScrollingRowIndex) + { + int firstDisplayedRowHeight = 0; + int firstDisplayedRowIndex = this.DataGridView.FirstDisplayedRowIndex; + if (firstDisplayedRowIndex != -1) + { + firstDisplayedRowHeight = SharedRow(firstDisplayedRowIndex).GetHeight(firstDisplayedRowIndex); + } + useRowShortcut = GetRowsHeightExceedLimit(DataGridViewElementStates.Visible, 0, rowIndex, this.DataGridView.LayoutInfo.Data.Height + this.DataGridView.VerticalScrollingOffset + SystemInformation.HorizontalScrollBarHeight) && + firstDisplayedRowHeight <= this.DataGridView.LayoutInfo.Data.Height; } - useRowShortcut = GetRowsHeightExceedLimit(DataGridViewElementStates.Visible, 0, rowIndex, this.DataGridView.LayoutInfo.Data.Height + this.DataGridView.VerticalScrollingOffset + SystemInformation.HorizontalScrollBarHeight) && - firstDisplayedRowHeight <= this.DataGridView.LayoutInfo.Data.Height; } + else + { + // Deleting an invisible row - no need for repaint + useRowShortcut = true; + } + break; } - else - { - // Deleting an invisible row - no need for repaint - useRowShortcut = true; - } - break; - } case CollectionChangeAction.Refresh: - { - InvalidateCachedRowCounts(); - InvalidateCachedRowsHeights(); - break; - } + { + InvalidateCachedRowCounts(); + InvalidateCachedRowsHeights(); + break; + } default: - { - Debug.Fail("Unexpected cca value in DataGridViewRowCollecttion.OnCollectionChanged"); - break; - } + { + Debug.Fail("Unexpected cca value in DataGridViewRowCollecttion.OnCollectionChanged"); + break; + } } this.DataGridView.ResetUIState(useRowShortcut, computeVisibleRows); } - private void OnCollectionChanged_PostNotification(CollectionChangeAction cca, - int rowIndex, + private void OnCollectionChanged_PostNotification(CollectionChangeAction cca, + int rowIndex, int rowCount, DataGridViewRow dataGridViewRow, bool changeIsDeletion, @@ -2153,32 +2153,32 @@ private void OnCollectionChanged_PostNotification(CollectionChangeAction cca, switch (cca) { case CollectionChangeAction.Add: - { - if (changeIsInsertion) - { - this.DataGridView.OnInsertedRow_PostNotification(rowIndex, newCurrentCell, true); - } - else { - this.DataGridView.OnAddedRow_PostNotification(rowIndex); + if (changeIsInsertion) + { + this.DataGridView.OnInsertedRow_PostNotification(rowIndex, newCurrentCell, true); + } + else + { + this.DataGridView.OnAddedRow_PostNotification(rowIndex); + } + break; } - break; - } case CollectionChangeAction.Remove: - { - this.DataGridView.OnRemovedRow_PostNotification(dataGridViewRow, newCurrentCell); - break; - } + { + this.DataGridView.OnRemovedRow_PostNotification(dataGridViewRow, newCurrentCell); + break; + } case CollectionChangeAction.Refresh: - { - if (changeIsDeletion) { - this.DataGridView.OnClearedRows(); + if (changeIsDeletion) + { + this.DataGridView.OnClearedRows(); + } + break; } - break; - } } this.DataGridView.OnRowCollectionChanged_PostNotification(recreateNewRow, newCurrentCell.X == -1, cca, dataGridViewRow, rowIndex); @@ -2219,7 +2219,7 @@ public virtual void RemoveAt(int index) if (this.DataGridView.NewRowIndex == index) { Debug.Assert(this.DataGridView.AllowUserToAddRowsInternal); - throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_CannotDeleteNewRow)); + throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_CannotDeleteNewRow)); } if (this.DataGridView.NoDimensionChangeAllowed) @@ -2264,7 +2264,7 @@ internal void RemoveAtInternal(int index, bool force) dataGridViewRow = SharedRow(index); Debug.Assert(this.DataGridView != null); this.DataGridView.OnRemovingRow(index, out newCurrentCell, force); - UpdateRowCaches(index, ref dataGridViewRow, false /*adding*/); + UpdateRowCaches(index, ref dataGridViewRow, false /*adding*/); if (dataGridViewRow.Index != -1) { this.rowStates[index] = dataGridViewRow.State; @@ -2275,7 +2275,7 @@ internal void RemoveAtInternal(int index, bool force) // Note that OnCollectionChanged takes care of calling this.items.RemoveAt(index) & // this.rowStates.RemoveAt(index). Can't do it here since OnCollectionChanged uses the arrays. OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, dataGridViewRow), index, 1, true, false, false, newCurrentCell); - } + } private static bool RowHasValueOrToolTipText(DataGridViewRow dataGridViewRow) { @@ -2327,7 +2327,7 @@ internal void SetRowState(int rowIndex, DataGridViewElementStates state, bool va // row is shared if (((this.rowStates[rowIndex] & state) != 0) != value) { - if (state == DataGridViewElementStates.Frozen || + if (state == DataGridViewElementStates.Frozen || state == DataGridViewElementStates.Visible || state == DataGridViewElementStates.ReadOnly) { @@ -2350,40 +2350,40 @@ internal void SetRowState(int rowIndex, DataGridViewElementStates state, bool va switch (state) { case DataGridViewElementStates.Displayed: - { - dataGridViewRow.DisplayedInternal = value; - break; - } + { + dataGridViewRow.DisplayedInternal = value; + break; + } case DataGridViewElementStates.Selected: - { - dataGridViewRow.SelectedInternal = value; - break; - } + { + dataGridViewRow.SelectedInternal = value; + break; + } case DataGridViewElementStates.Visible: - { - dataGridViewRow.Visible = value; - break; - } + { + dataGridViewRow.Visible = value; + break; + } case DataGridViewElementStates.Frozen: - { - dataGridViewRow.Frozen = value; - break; - } + { + dataGridViewRow.Frozen = value; + break; + } case DataGridViewElementStates.ReadOnly: - { - dataGridViewRow.ReadOnlyInternal = value; - break; - } + { + dataGridViewRow.ReadOnlyInternal = value; + break; + } case DataGridViewElementStates.Resizable: - { - dataGridViewRow.Resizable = value ? DataGridViewTriState.True : DataGridViewTriState.False; - break; - } + { + dataGridViewRow.Resizable = value ? DataGridViewTriState.True : DataGridViewTriState.False; + break; + } default: - { - Debug.Fail("Unexpected DataGridViewElementStates parameter in DataGridViewRowCollection.SetRowState."); - break; - } + { + Debug.Fail("Unexpected DataGridViewElementStates parameter in DataGridViewRowCollection.SetRowState."); + break; + } } } } @@ -2463,15 +2463,15 @@ private void UpdateRowCaches(int rowIndex, ref DataGridViewRow dataGridViewRow, { int rowCountIncrement = adding ? 1 : -1; int rowHeightIncrement = 0; - if (this.rowsHeightVisible != -1 || - (this.rowsHeightVisibleFrozen != -1 && + if (this.rowsHeightVisible != -1 || + (this.rowsHeightVisibleFrozen != -1 && ((rowStates & (DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)) == (DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)))) { // dataGridViewRow may become unshared in GetHeight call rowHeightIncrement = adding ? dataGridViewRow.GetHeight(rowIndex) : -dataGridViewRow.GetHeight(rowIndex); dataGridViewRow = SharedRow(rowIndex); } - + if (this.rowCountsVisible != -1) { this.rowCountsVisible += rowCountIncrement; @@ -2481,7 +2481,7 @@ private void UpdateRowCaches(int rowIndex, ref DataGridViewRow dataGridViewRow, Debug.Assert(rowHeightIncrement != 0); this.rowsHeightVisible += rowHeightIncrement; } - + if ((rowStates & (DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)) == (DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)) { if (this.rowCountsVisibleFrozen != -1) @@ -2511,37 +2511,37 @@ private void UpdateRowCaches(int rowIndex, ref DataGridViewRow dataGridViewRow, #endif } -/*#if DEBUG - private bool inVerifyRowFrozenStates = false; - public void VerifyRowFrozenStates() - { - if (inVerifyRowFrozenStates) return; - - inVerifyRowFrozenStates = true; - try - { - bool previousVisibleRowFrozen = true; - for (int rowIndex = 0; rowIndex < this.items.Count; rowIndex++) + /*#if DEBUG + private bool inVerifyRowFrozenStates = false; + public void VerifyRowFrozenStates() { - DataGridViewElementStates rowStates = GetRowState(rowIndex); - if (!previousVisibleRowFrozen && - (rowStates & DataGridViewElementStates.Visible) != 0 && - (rowStates & DataGridViewElementStates.Frozen) != 0) + if (inVerifyRowFrozenStates) return; + + inVerifyRowFrozenStates = true; + try { - Debug.Fail("VerifyRowFrozenStates - wrong frozen state"); + bool previousVisibleRowFrozen = true; + for (int rowIndex = 0; rowIndex < this.items.Count; rowIndex++) + { + DataGridViewElementStates rowStates = GetRowState(rowIndex); + if (!previousVisibleRowFrozen && + (rowStates & DataGridViewElementStates.Visible) != 0 && + (rowStates & DataGridViewElementStates.Frozen) != 0) + { + Debug.Fail("VerifyRowFrozenStates - wrong frozen state"); + } + if ((rowStates & DataGridViewElementStates.Visible) != 0) + { + previousVisibleRowFrozen = (rowStates & DataGridViewElementStates.Frozen) != 0; + } + } } - if ((rowStates & DataGridViewElementStates.Visible) != 0) + finally { - previousVisibleRowFrozen = (rowStates & DataGridViewElementStates.Frozen) != 0; + inVerifyRowFrozenStates = false; } } - } - finally - { - inVerifyRowFrozenStates = false; - } - } -#endif*/ + #endif*/ /* Private classes */ @@ -2619,9 +2619,9 @@ private void CustomQuickSort(int left, int right) } int k = (left + right) >> 1; - object x = Pivot(left, k, right); - int i = left+1; - int j = right-1; + object x = Pivot(left, k, right); + int i = left + 1; + int j = right - 1; do { while (k != i && this.rowComparer.CompareObjects(this.rowComparer.GetComparedObject(i), x, i, k) < 0) @@ -2794,7 +2794,7 @@ internal int CompareObjects(object value1, object value2, int rowIndex1, int row else { result = rowIndex2 - rowIndex1; - } + } } } } @@ -2826,54 +2826,54 @@ public ComparedObjectMax() { } } } - private class UnsharingRowEnumerator : IEnumerator + private class UnsharingRowEnumerator : IEnumerator { private DataGridViewRowCollection owner; private int current; - + /// /// Creates a new enumerator that will enumerate over the rows and unshare the accessed rows if needed. /// - public UnsharingRowEnumerator(DataGridViewRowCollection owner) + public UnsharingRowEnumerator(DataGridViewRowCollection owner) { this.owner = owner; this.current = -1; } - + /// /// Moves to the next element, or returns false if at the end. /// - bool IEnumerator.MoveNext() + bool IEnumerator.MoveNext() { - if (this.current < this.owner.Count - 1) + if (this.current < this.owner.Count - 1) { this.current++; return true; } - else + else { this.current = this.owner.Count; return false; } } - + /// /// Resets the enumeration back to the beginning. /// - void IEnumerator.Reset() + void IEnumerator.Reset() { this.current = -1; } - + /// /// Retrieves the current value in the enumerator. /// - object IEnumerator.Current + object IEnumerator.Current { - get + get { - if (this.current == -1) + if (this.current == -1) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_EnumNotStarted)); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowHeaderCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowHeaderCell.cs index 0833b70ffcb..8399782de74 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowHeaderCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowHeaderCell.cs @@ -1189,7 +1189,7 @@ public override Rectangle Bounds { cellRect.X = rowRect.Right - cellRect.Width; } - + return cellRect; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowPrePaintEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowPrePaintEventArgs.cs index d18931cc1d2..97fd666e904 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowPrePaintEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowPrePaintEventArgs.cs @@ -14,8 +14,8 @@ public class DataGridViewRowPrePaintEventArgs : HandledEventArgs private DataGridViewPaintParts _paintParts; public DataGridViewRowPrePaintEventArgs(DataGridView dataGridView, - Graphics graphics, - Rectangle clipBounds, + Graphics graphics, + Rectangle clipBounds, Rectangle rowBounds, int rowIndex, DataGridViewElementStates rowState, @@ -95,10 +95,10 @@ public void DrawFocus(Rectangle bounds, bool cellsPaintSelectionBackground) throw new InvalidOperationException(string.Format(SR.DataGridViewElementPaintingEventArgs_RowIndexOutOfRange)); } - _dataGridView.Rows.SharedRow(RowIndex).DrawFocus(Graphics, - ClipBounds, - bounds, - RowIndex, + _dataGridView.Rows.SharedRow(RowIndex).DrawFocus(Graphics, + ClipBounds, + bounds, + RowIndex, State, InheritedRowStyle, cellsPaintSelectionBackground); @@ -134,10 +134,10 @@ public void PaintCellsBackground(Rectangle clipBounds, bool cellsPaintSelectionB paintParts |= DataGridViewPaintParts.SelectionBackground; } _dataGridView.Rows.SharedRow(RowIndex).PaintCells(Graphics, - clipBounds, - RowBounds, - RowIndex, - State, + clipBounds, + RowBounds, + RowIndex, + State, IsFirstDisplayedRow, IsLastVisibleRow, paintParts); @@ -178,23 +178,23 @@ public void PaintHeader(DataGridViewPaintParts paintParts) } _dataGridView.Rows.SharedRow(RowIndex).PaintHeader(Graphics, - ClipBounds, - RowBounds, - RowIndex, - State, - IsFirstDisplayedRow, + ClipBounds, + RowBounds, + RowIndex, + State, + IsFirstDisplayedRow, IsLastVisibleRow, paintParts); } - internal void SetProperties(Graphics graphics, - Rectangle clipBounds, - Rectangle rowBounds, - int rowIndex, - DataGridViewElementStates rowState, - string errorText, - DataGridViewCellStyle inheritedRowStyle, - bool isFirstDisplayedRow, + internal void SetProperties(Graphics graphics, + Rectangle clipBounds, + Rectangle rowBounds, + int rowIndex, + DataGridViewElementStates rowState, + string errorText, + DataGridViewCellStyle inheritedRowStyle, + bool isFirstDisplayedRow, bool isLastVisibleRow) { Debug.Assert(graphics != null); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowStateChangedEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowStateChangedEventArgs.cs index f8679934e40..85256d0584b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowStateChangedEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowStateChangedEventArgs.cs @@ -12,7 +12,7 @@ public DataGridViewRowStateChangedEventArgs(DataGridViewRow dataGridViewRow, Dat StateChanged = stateChanged; } - public DataGridViewRow Row { get;} + public DataGridViewRow Row { get; } public DataGridViewElementStates StateChanged { get; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedCellCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedCellCollection.cs index 5c721b29340..3f0f51f5647 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedCellCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedCellCollection.cs @@ -111,12 +111,12 @@ protected override ArrayList List return this.items; } } - + public DataGridViewCell this[int index] { get { - return (DataGridViewCell) this.items[index]; + return (DataGridViewCell)this.items[index]; } } @@ -128,7 +128,7 @@ internal int Add(DataGridViewCell dataGridViewCell) Debug.Assert(!Contains(dataGridViewCell)); return this.items.Add(dataGridViewCell); } - + /* Not used for now internal void AddRange(DataGridViewCell[] dataGridViewCells) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedColumnCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedColumnCollection.cs index 2bd3651c624..19533b6f37f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedColumnCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedColumnCollection.cs @@ -108,12 +108,12 @@ protected override ArrayList List return this.items; } } - + public DataGridViewColumn this[int index] { get { - return (DataGridViewColumn) this.items[index]; + return (DataGridViewColumn)this.items[index]; } } @@ -124,7 +124,7 @@ internal int Add(DataGridViewColumn dataGridViewColumn) { return this.items.Add(dataGridViewColumn); } - + /* Unused at this point internal void AddRange(DataGridViewColumn[] dataGridViewColumns) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedRowCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedRowCollection.cs index 463cabe4a7e..23326b9d1b5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedRowCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedRowCollection.cs @@ -111,12 +111,12 @@ protected override ArrayList List return this.items; } } - + public DataGridViewRow this[int index] { get { - return (DataGridViewRow) this.items[index]; + return (DataGridViewRow)this.items[index]; } } @@ -127,7 +127,7 @@ internal int Add(DataGridViewRow dataGridViewRow) { return this.items.Add(dataGridViewRow); } - + /* Unused at this point internal void AddRange(DataGridViewRow[] dataGridViewRows) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectionMode.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectionMode.cs index deeb3a1ad52..a6560ed1fe6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectionMode.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectionMode.cs @@ -4,7 +4,7 @@ namespace System.Windows.Forms { - public enum DataGridViewSelectionMode + public enum DataGridViewSelectionMode { CellSelect = 0, FullRowSelect = 1, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSortCompareEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSortCompareEventArgs.cs index eaa279a65c6..6ff01567e4a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSortCompareEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSortCompareEventArgs.cs @@ -13,9 +13,9 @@ public class DataGridViewSortCompareEventArgs : HandledEventArgs private DataGridViewColumn dataGridViewColumn; private object cellValue1, cellValue2; private int sortResult, rowIndex1, rowIndex2; - + public DataGridViewSortCompareEventArgs(DataGridViewColumn dataGridViewColumn, - object cellValue1, + object cellValue1, object cellValue2, int rowIndex1, int rowIndex2) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxCell.cs index 743a2fea29d..c797c2d7782 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxCell.cs @@ -61,7 +61,7 @@ private DataGridViewTextBoxEditingControl EditingTextBox { get { - return (DataGridViewTextBoxEditingControl) this.Properties.GetObject(PropTextBoxCellEditingTextBox); + return (DataGridViewTextBoxEditingControl)this.Properties.GetObject(PropTextBoxCellEditingTextBox); } set { @@ -132,11 +132,11 @@ public override object Clone() { DataGridViewTextBoxCell dataGridViewCell; Type thisType = this.GetType(); - if(thisType == cellType) //performance improvement + if (thisType == cellType) //performance improvement { dataGridViewCell = new DataGridViewTextBoxCell(); } - else + else { // @@ -249,7 +249,7 @@ private Rectangle GetAdjustedEditingControlBounds(Rectangle editingControlBounds } else { - string editedFormattedValue = (string) ((IDataGridViewEditingControl) txtEditingControl).GetEditingControlFormattedValue(DataGridViewDataErrorContexts.Formatting); + string editedFormattedValue = (string)((IDataGridViewEditingControl)txtEditingControl).GetEditingControlFormattedValue(DataGridViewDataErrorContexts.Formatting); if (string.IsNullOrEmpty(editedFormattedValue)) { editedFormattedValue = " "; @@ -429,34 +429,34 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl switch (freeDimension) { case DataGridViewFreeDimension.Width: - { - preferredSize = new Size(DataGridViewCell.MeasureTextWidth(graphics, - formattedString, - cellStyle.Font, - Math.Max(1, constraintSize.Height - borderAndPaddingHeights - DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithWrapping - DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginBottom), - flags), - 0); - break; - } + { + preferredSize = new Size(DataGridViewCell.MeasureTextWidth(graphics, + formattedString, + cellStyle.Font, + Math.Max(1, constraintSize.Height - borderAndPaddingHeights - DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithWrapping - DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginBottom), + flags), + 0); + break; + } case DataGridViewFreeDimension.Height: - { - preferredSize = new Size(0, - DataGridViewCell.MeasureTextHeight(graphics, - formattedString, - cellStyle.Font, - Math.Max(1, constraintSize.Width - borderAndPaddingWidths - DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginLeft - DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginRight), - flags)); - break; - } + { + preferredSize = new Size(0, + DataGridViewCell.MeasureTextHeight(graphics, + formattedString, + cellStyle.Font, + Math.Max(1, constraintSize.Width - borderAndPaddingWidths - DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginLeft - DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginRight), + flags)); + break; + } default: - { - preferredSize = DataGridViewCell.MeasureTextPreferredSize(graphics, - formattedString, - cellStyle.Font, - 5.0F, - flags); - break; - } + { + preferredSize = DataGridViewCell.MeasureTextPreferredSize(graphics, + formattedString, + cellStyle.Font, + 5.0F, + flags); + break; + } } } else @@ -464,22 +464,22 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl switch (freeDimension) { case DataGridViewFreeDimension.Width: - { - preferredSize = new Size(DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags).Width, - 0); - break; - } + { + preferredSize = new Size(DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags).Width, + 0); + break; + } case DataGridViewFreeDimension.Height: - { - preferredSize = new Size(0, - DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags).Height); - break; - } + { + preferredSize = new Size(0, + DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags).Height); + break; + } default: - { - preferredSize = DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags); - break; - } + { + preferredSize = DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags); + break; + } } } @@ -593,9 +593,9 @@ private bool OwnsEditingTextBox(int rowIndex) return rowIndex != -1 && this.EditingTextBox != null && rowIndex == ((IDataGridViewEditingControl)this.EditingTextBox).EditingControlRowIndex; } - protected override void Paint(Graphics graphics, + protected override void Paint(Graphics graphics, Rectangle clipBounds, - Rectangle cellBounds, + Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, @@ -610,9 +610,9 @@ protected override void Paint(Graphics graphics, throw new ArgumentNullException(nameof(cellStyle)); } - PaintPrivate(graphics, + PaintPrivate(graphics, clipBounds, - cellBounds, + cellBounds, rowIndex, cellState, formattedValue, @@ -633,9 +633,9 @@ protected override void Paint(Graphics graphics, // if computeContentBounds is true then PaintPrivate returns the contentBounds // else if computeErrorIconBounds is true then PaintPrivate returns the errorIconBounds // else it returns Rectangle.Empty; - private Rectangle PaintPrivate(Graphics graphics, + private Rectangle PaintPrivate(Graphics graphics, Rectangle clipBounds, - Rectangle cellBounds, + Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object formattedValue, @@ -672,7 +672,7 @@ private Rectangle PaintPrivate(Graphics graphics, valBounds.Height -= borderWidths.Bottom; SolidBrush br; - + Point ptCurrentCell = this.DataGridView.CurrentCellAddress; bool cellCurrent = ptCurrentCell.X == this.ColumnIndex && ptCurrentCell.Y == rowIndex; bool cellEdited = cellCurrent && this.DataGridView.EditingControl != null; @@ -709,10 +709,10 @@ private Rectangle PaintPrivate(Graphics graphics, if (paint && cellCurrent && !cellEdited) { // Draw focus rectangle - if (DataGridViewCell.PaintFocus(paintParts) && - this.DataGridView.ShowFocusCues && - this.DataGridView.Focused && - valBounds.Width > 0 && + if (DataGridViewCell.PaintFocus(paintParts) && + this.DataGridView.ShowFocusCues && + this.DataGridView.Focused && + valBounds.Width > 0 && valBounds.Height > 0) { ControlPaint.DrawFocusRectangle(graphics, valBounds, Color.Empty, br.Color); @@ -775,20 +775,20 @@ private Rectangle PaintPrivate(Graphics graphics, return resultBounds; } - public override void PositionEditingControl(bool setLocation, - bool setSize, - Rectangle cellBounds, - Rectangle cellClip, - DataGridViewCellStyle cellStyle, - bool singleVerticalBorderAdded, - bool singleHorizontalBorderAdded, - bool isFirstDisplayedColumn, + public override void PositionEditingControl(bool setLocation, + bool setSize, + Rectangle cellBounds, + Rectangle cellClip, + DataGridViewCellStyle cellStyle, + bool singleVerticalBorderAdded, + bool singleHorizontalBorderAdded, + bool isFirstDisplayedColumn, bool isFirstDisplayedRow) { - Rectangle editingControlBounds = PositionEditingPanel(cellBounds, - cellClip, - cellStyle, - singleVerticalBorderAdded, + Rectangle editingControlBounds = PositionEditingPanel(cellBounds, + cellClip, + cellStyle, + singleVerticalBorderAdded, singleHorizontalBorderAdded, isFirstDisplayedColumn, isFirstDisplayedRow); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxColumn.cs index 85fd33b8a61..59eaccbf364 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxColumn.cs @@ -10,7 +10,7 @@ namespace System.Windows.Forms using System.Diagnostics; using System.Drawing; using System.Globalization; - + [ToolboxBitmapAttribute(typeof(DataGridViewTextBoxColumn), "DataGridViewTextBoxColumn")] public class DataGridViewTextBoxColumn : DataGridViewColumn { @@ -98,11 +98,11 @@ private DataGridViewTextBoxCell TextBoxCellTemplate { get { - return (DataGridViewTextBoxCell) this.CellTemplate; + return (DataGridViewTextBoxCell)this.CellTemplate; } } - public override string ToString() + public override string ToString() { StringBuilder sb = new StringBuilder(64); sb.Append("DataGridViewTextBoxColumn { Name="); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxEditingControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxEditingControl.cs index 098ad906593..58e47cc63b9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxEditingControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxEditingControl.cs @@ -54,7 +54,7 @@ public virtual object EditingControlFormattedValue } set { - this.Text = (string) value; + this.Text = (string)value; } } @@ -248,7 +248,7 @@ protected override void OnTextChanged(EventArgs e) protected override bool ProcessKeyEventArgs(ref Message m) { - switch ((Keys)(int) m.WParam) + switch ((Keys)(int)m.WParam) { case Keys.Enter: if (m.Msg == Interop.WindowMessages.WM_CHAR && @@ -282,7 +282,7 @@ protected override bool ProcessKeyEventArgs(ref Message m) return base.ProcessKeyEventArgs(ref m); } - private static HorizontalAlignment TranslateAlignment(DataGridViewContentAlignment align) + private static HorizontalAlignment TranslateAlignment(DataGridViewContentAlignment align) { if ((align & anyRight) != 0) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopLeftHeaderCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopLeftHeaderCell.cs index bd4b17c5312..de326324644 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopLeftHeaderCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopLeftHeaderCell.cs @@ -182,14 +182,14 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl { val = null; } - return DataGridViewUtilities.GetPreferredRowHeaderSize(graphics, - (string) val, - cellStyle, - borderAndPaddingWidths, + return DataGridViewUtilities.GetPreferredRowHeaderSize(graphics, + (string)val, + cellStyle, + borderAndPaddingWidths, borderAndPaddingHeights, this.DataGridView.ShowCellErrors, false /*showGlyph*/, - constraintSize, + constraintSize, flags); } @@ -326,9 +326,9 @@ private Rectangle PaintPrivate(Graphics graphics, valBounds.Offset(DATAGRIDVIEWTOPLEFTHEADERCELL_horizontalTextMarginLeft, DATAGRIDVIEWTOPLEFTHEADERCELL_verticalTextMargin); valBounds.Width -= DATAGRIDVIEWTOPLEFTHEADERCELL_horizontalTextMarginLeft + DATAGRIDVIEWTOPLEFTHEADERCELL_horizontalTextMarginRight; valBounds.Height -= 2 * DATAGRIDVIEWTOPLEFTHEADERCELL_verticalTextMargin; - if (valBounds.Width > 0 && - valBounds.Height > 0 && - !string.IsNullOrEmpty(formattedValueStr) && + if (valBounds.Width > 0 && + valBounds.Height > 0 && + !string.IsNullOrEmpty(formattedValueStr) && (paint || computeContentBounds)) { Color textColor; @@ -419,7 +419,7 @@ protected override void PaintBorder(Graphics graphics, /// /// /// - public override string ToString() + public override string ToString() { return "DataGridViewTopLeftHeaderCell"; } @@ -454,7 +454,7 @@ public static void DrawHeader(Graphics g, Rectangle bounds, int headerState) protected class DataGridViewTopLeftHeaderCellAccessibleObject : DataGridViewColumnHeaderCellAccessibleObject { - public DataGridViewTopLeftHeaderCellAccessibleObject(DataGridViewTopLeftHeaderCell owner) : base (owner) + public DataGridViewTopLeftHeaderCellAccessibleObject(DataGridViewTopLeftHeaderCell owner) : base(owner) { } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopRowAccessibleObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopRowAccessibleObject.cs index 7f0c7ef53c0..121f2995700 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopRowAccessibleObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopRowAccessibleObject.cs @@ -121,7 +121,7 @@ public override AccessibleObject GetChild(int index) { throw new InvalidOperationException(string.Format(SR.DataGridViewTopRowAccessibleObject_OwnerNotSet)); } - + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); @@ -135,7 +135,7 @@ public override AccessibleObject GetChild(int index) if (this.owner.RowHeadersVisible) { // decrement the index because the first child is the top left header cell - index --; + index--; } Debug.Assert(index >= 0); @@ -161,7 +161,7 @@ public override int GetChildCount() if (this.owner.RowHeadersVisible) { // + 1 is the top left header cell accessibility object - result ++; + result++; } return result; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewUtilities.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewUtilities.cs index 68c2f62dfe2..417f6a75af5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewUtilities.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewUtilities.cs @@ -10,7 +10,7 @@ namespace System.Windows.Forms using System.Windows.Forms.Internal; using System.Drawing.Imaging; using System.Windows.Forms.VisualStyles; - + /// /// /// @@ -55,8 +55,8 @@ internal static System.Drawing.ContentAlignment ComputeDrawingContentAlignmentFo } } - internal static TextFormatFlags ComputeTextFormatFlagsForCellStyleAlignment(bool rightToLeft, - DataGridViewContentAlignment alignment, + internal static TextFormatFlags ComputeTextFormatFlagsForCellStyleAlignment(bool rightToLeft, + DataGridViewContentAlignment alignment, DataGridViewTriState wrapMode) { TextFormatFlags tff; @@ -160,9 +160,9 @@ internal static TextFormatFlags ComputeTextFormatFlagsForCellStyleAlignment(bool } - internal static Size GetPreferredRowHeaderSize(Graphics graphics, - string val, - DataGridViewCellStyle cellStyle, + internal static Size GetPreferredRowHeaderSize(Graphics graphics, + string val, + DataGridViewCellStyle cellStyle, int borderAndPaddingWidths, int borderAndPaddingHeights, bool showRowErrors, @@ -176,125 +176,125 @@ internal static Size GetPreferredRowHeaderSize(Graphics graphics, switch (freeDimension) { case DataGridViewFreeDimension.Width: - { - int preferredWidth = 0, allowedHeight = constraintSize.Height - borderAndPaddingHeights; - if (!string.IsNullOrEmpty(val)) { - int maxHeight = allowedHeight - 2 * DATAGRIDVIEWROWHEADERCELL_verticalTextMargin; - if (maxHeight > 0) + int preferredWidth = 0, allowedHeight = constraintSize.Height - borderAndPaddingHeights; + if (!string.IsNullOrEmpty(val)) { - if (cellStyle.WrapMode == DataGridViewTriState.True) + int maxHeight = allowedHeight - 2 * DATAGRIDVIEWROWHEADERCELL_verticalTextMargin; + if (maxHeight > 0) { - preferredWidth = DataGridViewCell.MeasureTextWidth(graphics, val, cellStyle.Font, maxHeight, flags); + if (cellStyle.WrapMode == DataGridViewTriState.True) + { + preferredWidth = DataGridViewCell.MeasureTextWidth(graphics, val, cellStyle.Font, maxHeight, flags); + } + else + { + preferredWidth = DataGridViewCell.MeasureTextSize(graphics, val, cellStyle.Font, flags).Width; + } + preferredWidth += 2 * DATAGRIDVIEWROWHEADERCELL_contentMarginWidth + DATAGRIDVIEWROWHEADERCELL_horizontalTextMarginLeft + DATAGRIDVIEWROWHEADERCELL_horizontalTextMarginRight; } - else + } + if (allowedHeight >= DATAGRIDVIEWROWHEADERCELL_iconsHeight + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginHeight) + { + if (showGlyph) { - preferredWidth = DataGridViewCell.MeasureTextSize(graphics, val, cellStyle.Font, flags).Width; + preferredWidth += DATAGRIDVIEWROWHEADERCELL_iconsWidth + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth; + } + if (showRowErrors) + { + preferredWidth += DATAGRIDVIEWROWHEADERCELL_iconsWidth + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth; } - preferredWidth += 2 * DATAGRIDVIEWROWHEADERCELL_contentMarginWidth + DATAGRIDVIEWROWHEADERCELL_horizontalTextMarginLeft + DATAGRIDVIEWROWHEADERCELL_horizontalTextMarginRight; } + preferredWidth = Math.Max(preferredWidth, 1); + preferredWidth += borderAndPaddingWidths; + return new Size(preferredWidth, 0); } - if (allowedHeight >= DATAGRIDVIEWROWHEADERCELL_iconsHeight + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginHeight) + case DataGridViewFreeDimension.Height: { - if (showGlyph) + int minHeightIcon = 1, minHeightContent = 1; + int allowedWidth = constraintSize.Width - borderAndPaddingWidths; + if (!string.IsNullOrEmpty(val)) { - preferredWidth += DATAGRIDVIEWROWHEADERCELL_iconsWidth + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth; + if (showGlyph && allowedWidth >= 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth + DATAGRIDVIEWROWHEADERCELL_iconsWidth) + { + // There is enough room for the status icon + minHeightIcon = DATAGRIDVIEWROWHEADERCELL_iconsHeight + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginHeight; + // Status icon takes priority + allowedWidth -= 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth + DATAGRIDVIEWROWHEADERCELL_iconsWidth; + } + if (showRowErrors && allowedWidth >= 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth + DATAGRIDVIEWROWHEADERCELL_iconsWidth) + { + // There is enough room for the error icon + minHeightIcon = DATAGRIDVIEWROWHEADERCELL_iconsHeight + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginHeight; + // There is enough room for both the status and error icons + allowedWidth -= 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth + DATAGRIDVIEWROWHEADERCELL_iconsWidth; + } + if (allowedWidth > 2 * DATAGRIDVIEWROWHEADERCELL_contentMarginWidth + + DATAGRIDVIEWROWHEADERCELL_horizontalTextMarginLeft + + DATAGRIDVIEWROWHEADERCELL_horizontalTextMarginRight) + { + // There is enough room for text + allowedWidth -= 2 * DATAGRIDVIEWROWHEADERCELL_contentMarginWidth + + DATAGRIDVIEWROWHEADERCELL_horizontalTextMarginLeft + + DATAGRIDVIEWROWHEADERCELL_horizontalTextMarginRight; + if (cellStyle.WrapMode == DataGridViewTriState.True) + { + minHeightContent = DataGridViewCell.MeasureTextHeight(graphics, val, cellStyle.Font, allowedWidth, flags); + } + else + { + minHeightContent = DataGridViewCell.MeasureTextSize(graphics, val, cellStyle.Font, flags).Height; + } + minHeightContent += 2 * DATAGRIDVIEWROWHEADERCELL_verticalTextMargin; + } } - if (showRowErrors) + else { - preferredWidth += DATAGRIDVIEWROWHEADERCELL_iconsWidth + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth; + if ((showGlyph || showRowErrors) && allowedWidth >= 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth + DATAGRIDVIEWROWHEADERCELL_iconsWidth) + { + minHeightIcon = DATAGRIDVIEWROWHEADERCELL_iconsHeight + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginHeight; + } } + return new Size(0, Math.Max(minHeightIcon, minHeightContent) + borderAndPaddingHeights); } - preferredWidth = Math.Max(preferredWidth, 1); - preferredWidth += borderAndPaddingWidths; - return new Size(preferredWidth, 0); - } - case DataGridViewFreeDimension.Height: - { - int minHeightIcon = 1, minHeightContent = 1; - int allowedWidth = constraintSize.Width - borderAndPaddingWidths; - if (!string.IsNullOrEmpty(val)) + default: { - if (showGlyph && allowedWidth >= 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth + DATAGRIDVIEWROWHEADERCELL_iconsWidth) - { - // There is enough room for the status icon - minHeightIcon = DATAGRIDVIEWROWHEADERCELL_iconsHeight + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginHeight; - // Status icon takes priority - allowedWidth -= 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth + DATAGRIDVIEWROWHEADERCELL_iconsWidth; - } - if (showRowErrors && allowedWidth >= 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth + DATAGRIDVIEWROWHEADERCELL_iconsWidth) + if (!string.IsNullOrEmpty(val)) { - // There is enough room for the error icon - minHeightIcon = DATAGRIDVIEWROWHEADERCELL_iconsHeight + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginHeight; - // There is enough room for both the status and error icons - allowedWidth -= 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth + DATAGRIDVIEWROWHEADERCELL_iconsWidth; - } - if (allowedWidth > 2 * DATAGRIDVIEWROWHEADERCELL_contentMarginWidth + - DATAGRIDVIEWROWHEADERCELL_horizontalTextMarginLeft + - DATAGRIDVIEWROWHEADERCELL_horizontalTextMarginRight) - { - // There is enough room for text - allowedWidth -= 2 * DATAGRIDVIEWROWHEADERCELL_contentMarginWidth + - DATAGRIDVIEWROWHEADERCELL_horizontalTextMarginLeft + - DATAGRIDVIEWROWHEADERCELL_horizontalTextMarginRight; if (cellStyle.WrapMode == DataGridViewTriState.True) { - minHeightContent = DataGridViewCell.MeasureTextHeight(graphics, val, cellStyle.Font, allowedWidth, flags); + preferredSize = DataGridViewCell.MeasureTextPreferredSize(graphics, val, cellStyle.Font, 5.0F, flags); } else { - minHeightContent = DataGridViewCell.MeasureTextSize(graphics, val, cellStyle.Font, flags).Height; + preferredSize = DataGridViewCell.MeasureTextSize(graphics, val, cellStyle.Font, flags); } - minHeightContent += 2 * DATAGRIDVIEWROWHEADERCELL_verticalTextMargin; + preferredSize.Width += 2 * DATAGRIDVIEWROWHEADERCELL_contentMarginWidth + + DATAGRIDVIEWROWHEADERCELL_horizontalTextMarginLeft + + DATAGRIDVIEWROWHEADERCELL_horizontalTextMarginRight; + preferredSize.Height += 2 * DATAGRIDVIEWROWHEADERCELL_verticalTextMargin; } - } - else - { - if ((showGlyph || showRowErrors) && allowedWidth >= 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth + DATAGRIDVIEWROWHEADERCELL_iconsWidth) + else { - minHeightIcon = DATAGRIDVIEWROWHEADERCELL_iconsHeight + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginHeight; + preferredSize = new Size(0, 1); } - } - return new Size(0, Math.Max(minHeightIcon, minHeightContent) + borderAndPaddingHeights); - } - default: - { - if (!string.IsNullOrEmpty(val)) - { - if (cellStyle.WrapMode == DataGridViewTriState.True) + if (showGlyph) { - preferredSize = DataGridViewCell.MeasureTextPreferredSize(graphics, val, cellStyle.Font, 5.0F, flags); + preferredSize.Width += DATAGRIDVIEWROWHEADERCELL_iconsWidth + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth; } - else + if (showRowErrors) { - preferredSize = DataGridViewCell.MeasureTextSize(graphics, val, cellStyle.Font, flags); + preferredSize.Width += DATAGRIDVIEWROWHEADERCELL_iconsWidth + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth; } - preferredSize.Width += 2 * DATAGRIDVIEWROWHEADERCELL_contentMarginWidth + - DATAGRIDVIEWROWHEADERCELL_horizontalTextMarginLeft + - DATAGRIDVIEWROWHEADERCELL_horizontalTextMarginRight; - preferredSize.Height += 2*DATAGRIDVIEWROWHEADERCELL_verticalTextMargin; - } - else - { - preferredSize = new Size(0, 1); - } - if (showGlyph) - { - preferredSize.Width += DATAGRIDVIEWROWHEADERCELL_iconsWidth + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth; - } - if (showRowErrors) - { - preferredSize.Width += DATAGRIDVIEWROWHEADERCELL_iconsWidth + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth; - } - if (showGlyph || showRowErrors) - { - preferredSize.Height = Math.Max(preferredSize.Height, - DATAGRIDVIEWROWHEADERCELL_iconsHeight + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginHeight); + if (showGlyph || showRowErrors) + { + preferredSize.Height = Math.Max(preferredSize.Height, + DATAGRIDVIEWROWHEADERCELL_iconsHeight + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginHeight); + } + preferredSize.Width += borderAndPaddingWidths; + preferredSize.Height += borderAndPaddingHeights; + return preferredSize; } - preferredSize.Width += borderAndPaddingWidths; - preferredSize.Height += borderAndPaddingHeights; - return preferredSize; - } } } @@ -433,30 +433,30 @@ internal static Point GetTextLocation(Rectangle cellBounds, internal static bool ValidTextFormatFlags(TextFormatFlags flags) { - return (flags & ~(TextFormatFlags.Bottom | - TextFormatFlags.Default | - TextFormatFlags.EndEllipsis | - TextFormatFlags.ExpandTabs | - TextFormatFlags.ExternalLeading | - TextFormatFlags.HidePrefix | - TextFormatFlags.HorizontalCenter | - TextFormatFlags.Internal | - TextFormatFlags.Left | - TextFormatFlags.ModifyString | - TextFormatFlags.NoClipping | - TextFormatFlags.NoFullWidthCharacterBreak | - TextFormatFlags.NoPrefix | - TextFormatFlags.PathEllipsis | - TextFormatFlags.PrefixOnly | - TextFormatFlags.PreserveGraphicsClipping | - TextFormatFlags.PreserveGraphicsTranslateTransform | - TextFormatFlags.Right | - TextFormatFlags.RightToLeft | - TextFormatFlags.SingleLine | - TextFormatFlags.TextBoxControl | - TextFormatFlags.Top | - TextFormatFlags.VerticalCenter | - TextFormatFlags.WordBreak | + return (flags & ~(TextFormatFlags.Bottom | + TextFormatFlags.Default | + TextFormatFlags.EndEllipsis | + TextFormatFlags.ExpandTabs | + TextFormatFlags.ExternalLeading | + TextFormatFlags.HidePrefix | + TextFormatFlags.HorizontalCenter | + TextFormatFlags.Internal | + TextFormatFlags.Left | + TextFormatFlags.ModifyString | + TextFormatFlags.NoClipping | + TextFormatFlags.NoFullWidthCharacterBreak | + TextFormatFlags.NoPrefix | + TextFormatFlags.PathEllipsis | + TextFormatFlags.PrefixOnly | + TextFormatFlags.PreserveGraphicsClipping | + TextFormatFlags.PreserveGraphicsTranslateTransform | + TextFormatFlags.Right | + TextFormatFlags.RightToLeft | + TextFormatFlags.SingleLine | + TextFormatFlags.TextBoxControl | + TextFormatFlags.Top | + TextFormatFlags.VerticalCenter | + TextFormatFlags.WordBreak | TextFormatFlags.WordEllipsis)) == 0; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DateBoldEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DateBoldEventArgs.cs index 5423a609fc7..dd9a4242b4a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DateBoldEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DateBoldEventArgs.cs @@ -17,7 +17,7 @@ internal DateBoldEventArgs(DateTime start, int size) } public DateTime StartDate { get; } - + public int Size { get; } public int[] DaysToBold { get; set; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs index 1dfc96ac18e..545dfffc805 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.InteropServices; using System.Diagnostics; @@ -31,7 +32,8 @@ namespace System.Windows.Forms { Designer("System.Windows.Forms.Design.DateTimePickerDesigner, " + AssemblyRef.SystemDesign), SRDescription(nameof(SR.DescriptionDateTimePicker)) ] - public class DateTimePicker : Control { + public class DateTimePicker : Control + { /// /// Specifies the default title back color. This field is read-only. /// @@ -54,10 +56,10 @@ public class DateTimePicker : Control { private static readonly string DateTimePickerLocalizedControlTypeString = SR.DateTimePickerLocalizedControlType; private const int TIMEFORMAT_NOUPDOWN = NativeMethods.DTS_TIMEFORMAT & (~NativeMethods.DTS_UPDOWN); - private EventHandler onCloseUp; - private EventHandler onDropDown; - private EventHandler onValueChanged; - private EventHandler onRightToLeftLayoutChanged; + private EventHandler onCloseUp; + private EventHandler onDropDown; + private EventHandler onValueChanged; + private EventHandler onRightToLeftLayoutChanged; // We need to restrict the available dates because of limitations in the comctl // DateTime and MonthCalendar controls @@ -74,50 +76,51 @@ public class DateTimePicker : Control { [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public static readonly DateTime MaxDateTime = new DateTime(9998, 12, 31); - private int style; - private short prefHeightCache = -1; + private int style; + private short prefHeightCache = -1; /// /// validTime determines whether the CheckBox in the DTP is checked. The CheckBox is only /// displayed when ShowCheckBox is true. /// - private bool validTime = true; + private bool validTime = true; // DateTime changeover: DateTime is a value class, not an object, so we need to keep track // of whether or not its values have been initialised in a separate boolean. - private bool userHasSetValue = false; - private DateTime value = DateTime.Now; - private DateTime creationTime = DateTime.Now; + private bool userHasSetValue = false; + private DateTime value = DateTime.Now; + private DateTime creationTime = DateTime.Now; // Reconcile out-of-range min/max values in the property getters. - private DateTime max = DateTime.MaxValue; - private DateTime min = DateTime.MinValue; - private Color calendarForeColor = DefaultForeColor; - private Color calendarTitleBackColor = DefaultTitleBackColor; - private Color calendarTitleForeColor = DefaultTitleForeColor; - private Color calendarMonthBackground = DefaultMonthBackColor; - private Color calendarTrailingText = DefaultTrailingForeColor; - private Font calendarFont = null; - private FontHandleWrapper calendarFontHandleWrapper = null; + private DateTime max = DateTime.MaxValue; + private DateTime min = DateTime.MinValue; + private Color calendarForeColor = DefaultForeColor; + private Color calendarTitleBackColor = DefaultTitleBackColor; + private Color calendarTitleForeColor = DefaultTitleForeColor; + private Color calendarMonthBackground = DefaultMonthBackColor; + private Color calendarTrailingText = DefaultTrailingForeColor; + private Font calendarFont = null; + private FontHandleWrapper calendarFontHandleWrapper = null; // Since there is no way to get the customFormat from the DTP, we need to // cache it. Also we have to track if the user wanted customFormat or // shortDate format (shortDate is the lack of being in Long or DateTime format // without a customFormat). What fun! // - private string customFormat; + private string customFormat; - private DateTimePickerFormat format; + private DateTimePickerFormat format; - private bool rightToLeftLayout = false; + private bool rightToLeftLayout = false; /// /// Initializes a new instance of the class. /// public DateTimePicker() - : base() { + : base() + { // this class overrides GetPreferredSizeCore, let Control automatically cache the result - SetState2(STATE2_USEPREFERREDSIZECACHE, true); - + SetState2(STATE2_USEPREFERREDSIZECACHE, true); + SetStyle(ControlStyles.FixedHeight, true); // Since DateTimePicker does its own mouse capturing, we do not want @@ -135,54 +138,68 @@ public DateTimePicker() } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Color BackColor { - get { - if (ShouldSerializeBackColor()) { + public override Color BackColor + { + get + { + if (ShouldSerializeBackColor()) + { return base.BackColor; } - else { + else + { return SystemColors.Window; } } - set { + set + { base.BackColor = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackColorChanged { + new public event EventHandler BackColorChanged + { add => base.BackColorChanged += value; remove => base.BackColorChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged { + new public event EventHandler BackgroundImageChanged + { add => base.BackgroundImageChanged += value; remove => base.BackgroundImageChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { + new public event EventHandler BackgroundImageLayoutChanged + { add => base.BackgroundImageLayoutChanged += value; remove => base.BackgroundImageLayoutChanged -= value; } @@ -194,17 +211,22 @@ public override ImageLayout BackgroundImageLayout { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.DateTimePickerCalendarForeColorDescr)) ] - public Color CalendarForeColor { - get { + public Color CalendarForeColor + { + get + { return calendarForeColor; } - set { - if (value.IsEmpty) { + set + { + if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.InvalidNullArgument, "value")); } - if (!value.Equals(calendarForeColor)) { + if (!value.Equals(calendarForeColor)) + { calendarForeColor = value; SetControlColor(NativeMethods.MCSC_TEXT, value); } @@ -220,16 +242,21 @@ public Color CalendarForeColor { AmbientValue(null), SRDescription(nameof(SR.DateTimePickerCalendarFontDescr)) ] - public Font CalendarFont { - get { - if (calendarFont == null) { + public Font CalendarFont + { + get + { + if (calendarFont == null) + { return Font; } return calendarFont; } - set { - if ((value == null && calendarFont != null) || (value != null && !value.Equals(calendarFont))) { + set + { + if ((value == null && calendarFont != null) || (value != null && !value.Equals(calendarFont))) + { calendarFont = value; calendarFontHandleWrapper = null; SetControlCalendarFont(); @@ -237,14 +264,18 @@ public Font CalendarFont { } } - private IntPtr CalendarFontHandle { - get { - if (calendarFont == null) { + private IntPtr CalendarFontHandle + { + get + { + if (calendarFont == null) + { Debug.Assert(calendarFontHandleWrapper == null, "font handle out of sync with Font"); return FontHandle; } - if (calendarFontHandleWrapper == null) { + if (calendarFontHandleWrapper == null) + { calendarFontHandleWrapper = new FontHandleWrapper(CalendarFont); } @@ -259,17 +290,22 @@ private IntPtr CalendarFontHandle { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.DateTimePickerCalendarTitleBackColorDescr)) ] - public Color CalendarTitleBackColor { - get { + public Color CalendarTitleBackColor + { + get + { return calendarTitleBackColor; } - set { - if (value.IsEmpty) { + set + { + if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.InvalidNullArgument, "value")); } - if (!value.Equals(calendarTitleBackColor)) { + if (!value.Equals(calendarTitleBackColor)) + { calendarTitleBackColor = value; SetControlColor(NativeMethods.MCSC_TITLEBK, value); } @@ -283,17 +319,22 @@ public Color CalendarTitleBackColor { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.DateTimePickerCalendarTitleForeColorDescr)) ] - public Color CalendarTitleForeColor { - get { + public Color CalendarTitleForeColor + { + get + { return calendarTitleForeColor; } - set { - if (value.IsEmpty) { + set + { + if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.InvalidNullArgument, "value")); } - if (!value.Equals(calendarTitleForeColor)) { + if (!value.Equals(calendarTitleForeColor)) + { calendarTitleForeColor = value; SetControlColor(NativeMethods.MCSC_TITLETEXT, value); } @@ -307,17 +348,22 @@ public Color CalendarTitleForeColor { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.DateTimePickerCalendarTrailingForeColorDescr)) ] - public Color CalendarTrailingForeColor { - get { + public Color CalendarTrailingForeColor + { + get + { return calendarTrailingText; } - set { - if (value.IsEmpty) { + set + { + if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.InvalidNullArgument, "value")); } - if (!value.Equals(calendarTrailingText)) { + if (!value.Equals(calendarTrailingText)) + { calendarTrailingText = value; SetControlColor(NativeMethods.MCSC_TRAILINGTEXT, value); } @@ -331,17 +377,22 @@ public Color CalendarTrailingForeColor { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.DateTimePickerCalendarMonthBackgroundDescr)) ] - public Color CalendarMonthBackground { - get { + public Color CalendarMonthBackground + { + get + { return calendarMonthBackground; } - set { - if (value.IsEmpty) { + set + { + if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.InvalidNullArgument, "value")); } - if (!value.Equals(calendarMonthBackground)) { + if (!value.Equals(calendarMonthBackground)) + { calendarMonthBackground = value; SetControlColor(NativeMethods.MCSC_MONTHBK, value); } @@ -357,27 +408,37 @@ public Color CalendarMonthBackground { Bindable(true), SRDescription(nameof(SR.DateTimePickerCheckedDescr)) ] - public bool Checked { - get { + public bool Checked + { + get + { // the information from win32 DateTimePicker is reliable only when ShowCheckBoxes is True - if (this.ShowCheckBox && IsHandleCreated) { + if (this.ShowCheckBox && IsHandleCreated) + { NativeMethods.SYSTEMTIME sys = new NativeMethods.SYSTEMTIME(); int gdt = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.DTM_GETSYSTEMTIME, 0, sys); return gdt == NativeMethods.GDT_VALID; - } else { + } + else + { return validTime; } } - set { - if (this.Checked != value) { + set + { + if (this.Checked != value) + { // set the information into the win32 DateTimePicker only if ShowCheckBoxes is True - if (this.ShowCheckBox && IsHandleCreated) { - if (value) { + if (this.ShowCheckBox && IsHandleCreated) + { + if (value) + { int gdt = NativeMethods.GDT_VALID; NativeMethods.SYSTEMTIME sys = DateTimePicker.DateTimeToSysTime(Value); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.DTM_SETSYSTEMTIME, gdt, sys); } - else { + else + { int gdt = NativeMethods.GDT_NONE; NativeMethods.SYSTEMTIME sys = null; UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.DTM_SETSYSTEMTIME, gdt, sys); @@ -395,21 +456,26 @@ public bool Checked { Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - new public event EventHandler Click { - add => base.Click += value; - remove => base.Click -= value; } + new public event EventHandler Click + { + add => base.Click += value; + remove => base.Click -= value; + } /// /// Returns the CreateParams used to create this window. /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ClassName = NativeMethods.WC_DATETIMEPICK; cp.Style |= style; - switch (format) { + switch (format) + { case DateTimePickerFormat.Long: cp.Style |= NativeMethods.DTS_LONGDATEFORMAT; break; @@ -424,7 +490,8 @@ protected override CreateParams CreateParams { cp.ExStyle |= NativeMethods.WS_EX_CLIENTEDGE; - if (RightToLeft == RightToLeft.Yes && RightToLeftLayout == true) { + if (RightToLeft == RightToLeft.Yes && RightToLeftLayout == true) + { //We want to turn on mirroring for DateTimePicker explicitly. cp.ExStyle |= NativeMethods.WS_EX_LAYOUTRTL; //Don't need these styles when mirroring is turned on. @@ -445,18 +512,23 @@ protected override CreateParams CreateParams { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.DateTimePickerCustomFormatDescr)) ] - public string CustomFormat { - get { + public string CustomFormat + { + get + { return customFormat; } - set { + set + { if ((value != null && !value.Equals(customFormat)) || - (value == null && customFormat != null)) { + (value == null && customFormat != null)) + { customFormat = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { if (format == DateTimePickerFormat.Custom) SendMessage(NativeMethods.DTM_SETFORMAT, 0, customFormat); } @@ -468,8 +540,10 @@ public string CustomFormat { /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(200, PreferredHeight); } } @@ -479,11 +553,14 @@ protected override Size DefaultSize { /// on controls that are based on Win32 Native Controls. /// [EditorBrowsable(EditorBrowsableState.Never)] - protected override bool DoubleBuffered { - get { + protected override bool DoubleBuffered + { + get + { return base.DoubleBuffered; } - set { + set + { base.DoubleBuffered = value; } } @@ -492,9 +569,11 @@ protected override bool DoubleBuffered { Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - new public event EventHandler DoubleClick { - add => base.DoubleClick += value; - remove => base.DoubleClick -= value; } + new public event EventHandler DoubleClick + { + add => base.DoubleClick += value; + remove => base.DoubleClick -= value; + } /// /// The current value of the dropDownAlign property. The calendar @@ -506,16 +585,20 @@ protected override bool DoubleBuffered { Localizable(true), SRDescription(nameof(SR.DateTimePickerDropDownAlignDescr)) ] - public LeftRightAlignment DropDownAlign { - get { - return((style & NativeMethods.DTS_RIGHTALIGN) != 0) + public LeftRightAlignment DropDownAlign + { + get + { + return ((style & NativeMethods.DTS_RIGHTALIGN) != 0) ? LeftRightAlignment.Right : LeftRightAlignment.Left; } - set { + set + { //valid values are 0x0 to 0x1 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)LeftRightAlignment.Left, (int)LeftRightAlignment.Right)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)LeftRightAlignment.Left, (int)LeftRightAlignment.Right)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(LeftRightAlignment)); } @@ -524,22 +607,28 @@ public LeftRightAlignment DropDownAlign { } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Color ForeColor { - get { - if (ShouldSerializeForeColor()) { + public override Color ForeColor + { + get + { + if (ShouldSerializeForeColor()) + { return base.ForeColor; } - else { + else + { return SystemColors.WindowText; } } - set { + set + { base.ForeColor = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler ForeColorChanged { + new public event EventHandler ForeColorChanged + { add => base.ForeColorChanged += value; remove => base.ForeColorChanged -= value; } @@ -553,19 +642,23 @@ public override Color ForeColor { RefreshProperties(RefreshProperties.Repaint), SRDescription(nameof(SR.DateTimePickerFormatDescr)) ] - public DateTimePickerFormat Format { - get { + public DateTimePickerFormat Format + { + get + { return format; } - set { + set + { //valid values are 0x1, 0x2,0x4,0x8. max number of bits on at a time is 1 if (!ClientUtils.IsEnumValid(value, (int)value, (int)DateTimePickerFormat.Long, (int)DateTimePickerFormat.Custom, /*maxNumberOfBitsOn*/1)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DateTimePickerFormat)); } - if (format != value) { + if (format != value) + { format = value; RecreateHandle(); @@ -576,7 +669,8 @@ public DateTimePickerFormat Format { } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.DateTimePickerOnFormatChangedDescr))] - public event EventHandler FormatChanged { + public event EventHandler FormatChanged + { add => Events.AddHandler(EVENT_FORMATCHANGED, value); remove => Events.RemoveHandler(EVENT_FORMATCHANGED, value); } @@ -586,7 +680,8 @@ public event EventHandler FormatChanged { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event PaintEventHandler Paint { + public new event PaintEventHandler Paint + { add => base.Paint += value; remove => base.Paint -= value; } @@ -629,12 +724,16 @@ static internal DateTime EffectiveMaxDate(DateTime maxDate) SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.DateTimePickerMaxDateDescr)) ] - public DateTime MaxDate { - get { + public DateTime MaxDate + { + get + { return EffectiveMaxDate(max); } - set { - if (value != max) { + set + { + if (value != max) + { if (value < EffectiveMinDate(min)) { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(MaxDate), FormatDateTime(value), nameof(MinDate))); @@ -649,7 +748,8 @@ public DateTime MaxDate { //If Value (which was once valid) is suddenly greater than the max (since we just set it) //then adjust this... - if (Value > max) { + if (Value > max) + { Value = max; } } @@ -659,15 +759,17 @@ public DateTime MaxDate { /// /// Specifies the maximum date value. This property is read-only. /// - public static DateTime MaximumDateTime { - get { - DateTime maxSupportedDateTime = CultureInfo.CurrentCulture.Calendar.MaxSupportedDateTime; - if (maxSupportedDateTime.Year > MaxDateTime.Year) - { - return MaxDateTime; - } - return maxSupportedDateTime; - } + public static DateTime MaximumDateTime + { + get + { + DateTime maxSupportedDateTime = CultureInfo.CurrentCulture.Calendar.MaxSupportedDateTime; + if (maxSupportedDateTime.Year > MaxDateTime.Year) + { + return MaxDateTime; + } + return maxSupportedDateTime; + } } /// @@ -678,8 +780,10 @@ public static DateTime MaximumDateTime { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.DateTimePickerMinDateDescr)) ] - public DateTime MinDate { - get { + public DateTime MinDate + { + get + { return EffectiveMinDate(min); } set @@ -715,50 +819,59 @@ public DateTime MinDate { /// /// Specifies the minimum date value. This property is read-only. /// - public static DateTime MinimumDateTime { - get { - DateTime minSupportedDateTime = CultureInfo.CurrentCulture.Calendar.MinSupportedDateTime; - if (minSupportedDateTime.Year < 1753) - { - return new DateTime(1753, 1, 1); - } - return minSupportedDateTime; - } + public static DateTime MinimumDateTime + { + get + { + DateTime minSupportedDateTime = CultureInfo.CurrentCulture.Calendar.MinSupportedDateTime; + if (minSupportedDateTime.Year < 1753) + { + return new DateTime(1753, 1, 1); + } + return minSupportedDateTime; + } } [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - new public event MouseEventHandler MouseClick { - add => base.MouseClick += value; - remove => base.MouseClick -= value; } + new public event MouseEventHandler MouseClick + { + add => base.MouseClick += value; + remove => base.MouseClick -= value; + } [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - new public event MouseEventHandler MouseDoubleClick { - add => base.MouseDoubleClick += value; - remove => base.MouseDoubleClick -= value; } + new public event MouseEventHandler MouseDoubleClick + { + add => base.MouseDoubleClick += value; + remove => base.MouseDoubleClick -= value; + } [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Padding Padding { + public new Padding Padding + { get { return base.Padding; } - set { base.Padding = value;} + set { base.Padding = value; } } [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public new event EventHandler PaddingChanged { - add => base.PaddingChanged += value; - remove => base.PaddingChanged -= value; } + public new event EventHandler PaddingChanged + { + add => base.PaddingChanged += value; + remove => base.PaddingChanged -= value; + } /// /// Indicates the preferred height of the DateTimePicker control. This property is read-only. @@ -767,10 +880,12 @@ public static DateTime MinimumDateTime { Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public int PreferredHeight { - get { + public int PreferredHeight + { + get + { if (prefHeightCache > -1) - return(int)prefHeightCache; + return (int)prefHeightCache; // Base the preferred height on the current font int height = FontHeight; @@ -795,16 +910,21 @@ public int PreferredHeight { DefaultValue(false), SRDescription(nameof(SR.ControlRightToLeftLayoutDescr)) ] - public virtual bool RightToLeftLayout { - get { + public virtual bool RightToLeftLayout + { + get + { return rightToLeftLayout; } - set { - if (value != rightToLeftLayout) { + set + { + if (value != rightToLeftLayout) + { rightToLeftLayout = value; - using(new LayoutTransaction(this, this, PropertyNames.RightToLeftLayout)) { + using (new LayoutTransaction(this, this, PropertyNames.RightToLeftLayout)) + { OnRightToLeftLayoutChanged(EventArgs.Empty); } } @@ -823,11 +943,14 @@ public virtual bool RightToLeftLayout { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.DateTimePickerShowNoneDescr)) ] - public bool ShowCheckBox { - get { - return(style & NativeMethods.DTS_SHOWNONE) != 0; + public bool ShowCheckBox + { + get + { + return (style & NativeMethods.DTS_SHOWNONE) != 0; } - set { + set + { SetStyleBit(value, NativeMethods.DTS_SHOWNONE); } } @@ -841,12 +964,16 @@ public bool ShowCheckBox { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.DateTimePickerShowUpDownDescr)) ] - public bool ShowUpDown { - get { - return(style & NativeMethods.DTS_UPDOWN) != 0; + public bool ShowUpDown + { + get + { + return (style & NativeMethods.DTS_UPDOWN) != 0; } - set { - if (ShowUpDown != value) { + set + { + if (ShowUpDown != value) + { SetStyleBit(value, NativeMethods.DTS_UPDOWN); } } @@ -858,24 +985,30 @@ public bool ShowUpDown { /// an exception if the string (value) being passed in is invalid. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { + set + { // Clause to check length // - if (value == null || value.Length == 0) { + if (value == null || value.Length == 0) + { ResetValue(); } - else { + else + { Value = DateTime.Parse(value, CultureInfo.CurrentCulture); } } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - new public event EventHandler TextChanged { + new public event EventHandler TextChanged + { add => base.TextChanged += value; remove => base.TextChanged -= value; } @@ -889,22 +1022,27 @@ public override string Text { RefreshProperties(RefreshProperties.All), SRDescription(nameof(SR.DateTimePickerValueDescr)) ] - public DateTime Value { - get { + public DateTime Value + { + get + { //checkbox clicked, no value set - no value set state should never occur, but just in case if (!userHasSetValue && validTime) return creationTime; else return value; } - set { + set + { bool valueChanged = !DateTime.Equals(this.Value, value); // Check for value set here; if we've not set the value yet, it'll be Now, so the second // part of the test will fail. // So, if userHasSetValue isn't set, we don't care if the value is still the same - and we'll // update anyway. - if (!userHasSetValue || valueChanged) { - if ((value < MinDate) || (value > MaxDate)) { + if (!userHasSetValue || valueChanged) + { + if ((value < MinDate) || (value > MaxDate)) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidBoundArgument, nameof(Value), FormatDateTime(value), $"'{nameof(MinDate)}'", $"'{nameof(MaxDate)}'")); } @@ -913,7 +1051,8 @@ public DateTime Value { this.value = value; userHasSetValue = true; - if (IsHandleCreated) { + if (IsHandleCreated) + { /* * Make sure any changes to this code * get propagated to createHandle @@ -923,11 +1062,13 @@ public DateTime Value { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.DTM_SETSYSTEMTIME, gdt, sys); } - if (valueChanged) { + if (valueChanged) + { OnValueChanged(EventArgs.Empty); } - if (!oldText.Equals(this.Text)) { + if (!oldText.Equals(this.Text)) + { OnTextChanged(EventArgs.Empty); } } @@ -938,14 +1079,16 @@ public DateTime Value { /// Occurs when the dropdown calendar is dismissed and disappears. /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.DateTimePickerOnCloseUpDescr))] - public event EventHandler CloseUp { + public event EventHandler CloseUp + { add => onCloseUp += value; remove => onCloseUp -= value; } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnRightToLeftLayoutChangedDescr))] - public event EventHandler RightToLeftLayoutChanged { + public event EventHandler RightToLeftLayoutChanged + { add => onRightToLeftLayoutChanged += value; remove => onRightToLeftLayoutChanged -= value; } @@ -954,7 +1097,8 @@ public event EventHandler RightToLeftLayoutChanged { /// Occurs when the value for the control changes. /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.valueChangedEventDescr))] - public event EventHandler ValueChanged { + public event EventHandler ValueChanged + { add => onValueChanged += value; remove => onValueChanged -= value; } @@ -964,34 +1108,40 @@ public event EventHandler ValueChanged { /// Occurs when the drop down calendar is shown. /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.DateTimePickerOnDropDownDescr))] - public event EventHandler DropDown { + public event EventHandler DropDown + { add => onDropDown += value; remove => onDropDown -= value; } - + /// /// /// Constructs the new instance of the accessibility object for this control. Subclasses /// should not call base.CreateAccessibilityObject. /// /// - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new DateTimePickerAccessibleObject(this); } /// /// Creates the physical window handle. /// - protected override void CreateHandle() { - if (!RecreatingHandle) { + protected override void CreateHandle() + { + if (!RecreatingHandle) + { IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); - - try { + + try + { NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); icc.dwICC = NativeMethods.ICC_DATE_CLASSES; SafeNativeMethods.InitCommonControlsEx(icc); } - finally { + finally + { UnsafeNativeMethods.ThemingScope.Deactivate(userCookie); } } @@ -1000,7 +1150,8 @@ protected override void CreateHandle() { base.CreateHandle(); - if (userHasSetValue && validTime) { + if (userHasSetValue && validTime) + { /* * Make sure any changes to this code * get propagated to setValue @@ -1009,13 +1160,15 @@ protected override void CreateHandle() { NativeMethods.SYSTEMTIME sys = DateTimePicker.DateTimeToSysTime(Value); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.DTM_SETSYSTEMTIME, gdt, sys); } - else if (!validTime) { + else if (!validTime) + { int gdt = NativeMethods.GDT_NONE; NativeMethods.SYSTEMTIME sys = null; UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.DTM_SETSYSTEMTIME, gdt, sys); } - if (format == DateTimePickerFormat.Custom) { + if (format == DateTimePickerFormat.Custom) + { SendMessage(NativeMethods.DTM_SETFORMAT, 0, customFormat); } @@ -1028,7 +1181,8 @@ protected override void CreateHandle() { /// /// Destroys the physical window handle. /// - protected override void DestroyHandle() { + protected override void DestroyHandle() + { value = Value; base.DestroyHandle(); } @@ -1036,18 +1190,21 @@ protected override void DestroyHandle() { // Return a localized string representation of the given DateTime value. // Used for throwing exceptions, etc. // - private static string FormatDateTime(DateTime value) { + private static string FormatDateTime(DateTime value) + { return value.ToString("G", CultureInfo.CurrentCulture); } // GetPreferredSize and SetBoundsCore call this method to allow controls to self impose // constraints on their size. - internal override Rectangle ApplyBoundsConstraints(int suggestedX, int suggestedY, int proposedWidth, int proposedHeight) { - // Lock DateTimePicker to its preferred height. - return base.ApplyBoundsConstraints(suggestedX,suggestedY, proposedWidth, PreferredHeight); + internal override Rectangle ApplyBoundsConstraints(int suggestedX, int suggestedY, int proposedWidth, int proposedHeight) + { + // Lock DateTimePicker to its preferred height. + return base.ApplyBoundsConstraints(suggestedX, suggestedY, proposedWidth, PreferredHeight); } - internal override Size GetPreferredSizeCore(Size proposedConstraints) { + internal override Size GetPreferredSizeCore(Size proposedConstraints) + { int height = PreferredHeight; int width = CommonProperties.GetSpecifiedBounds(this).Width; return new Size(width, height); @@ -1057,9 +1214,12 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) { /// /// Handling special input keys, such as pgup, pgdown, home, end, etc... /// - protected override bool IsInputKey(Keys keyData) { - if ((keyData & Keys.Alt) == Keys.Alt) return false; - switch (keyData & Keys.KeyCode) { + protected override bool IsInputKey(Keys keyData) + { + if ((keyData & Keys.Alt) == Keys.Alt) + return false; + switch (keyData & Keys.KeyCode) + { case Keys.PageUp: case Keys.PageDown: case Keys.Home: @@ -1073,23 +1233,29 @@ protected override bool IsInputKey(Keys keyData) { /// Raises the /// event. /// - protected virtual void OnCloseUp(EventArgs eventargs) { - if (onCloseUp != null) onCloseUp(this, eventargs); + protected virtual void OnCloseUp(EventArgs eventargs) + { + if (onCloseUp != null) + onCloseUp(this, eventargs); } /// /// Raises the event. /// - protected virtual void OnDropDown(EventArgs eventargs) { - if (onDropDown != null) { + protected virtual void OnDropDown(EventArgs eventargs) + { + if (onDropDown != null) + { onDropDown(this, eventargs); } } - protected virtual void OnFormatChanged(EventArgs e) { + protected virtual void OnFormatChanged(EventArgs e) + { EventHandler eh = Events[EVENT_FORMATCHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } @@ -1115,24 +1281,30 @@ protected override void OnHandleDestroyed(EventArgs e) /// /// Raises the event. /// - protected virtual void OnValueChanged(EventArgs eventargs) { - if (onValueChanged != null) { + protected virtual void OnValueChanged(EventArgs eventargs) + { + if (onValueChanged != null) + { onValueChanged(this, eventargs); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnRightToLeftLayoutChanged(EventArgs e) { - if (GetAnyDisposingInHierarchy()) { + protected virtual void OnRightToLeftLayoutChanged(EventArgs e) + { + if (GetAnyDisposingInHierarchy()) + { return; } - if (RightToLeft == RightToLeft.Yes) { + if (RightToLeft == RightToLeft.Yes) + { RecreateHandle(); } - if (onRightToLeftLayoutChanged != null) { - onRightToLeftLayoutChanged(this, e); + if (onRightToLeftLayoutChanged != null) + { + onRightToLeftLayoutChanged(this, e); } } @@ -1140,7 +1312,8 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) { /// /// Occurs when a property for the control changes. /// - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { base.OnFontChanged(e); //clear the pref height cache @@ -1148,33 +1321,40 @@ protected override void OnFontChanged(EventArgs e) { Height = PreferredHeight; - if (calendarFont == null) { + if (calendarFont == null) + { calendarFontHandleWrapper = null; SetControlCalendarFont(); } } - private void ResetCalendarForeColor() { + private void ResetCalendarForeColor() + { CalendarForeColor = DefaultForeColor; } - private void ResetCalendarFont() { + private void ResetCalendarFont() + { CalendarFont = null; } - private void ResetCalendarMonthBackground() { - CalendarMonthBackground = DefaultMonthBackColor; + private void ResetCalendarMonthBackground() + { + CalendarMonthBackground = DefaultMonthBackColor; } - private void ResetCalendarTitleBackColor() { + private void ResetCalendarTitleBackColor() + { CalendarTitleBackColor = DefaultTitleBackColor; } - private void ResetCalendarTitleForeColor() { + private void ResetCalendarTitleForeColor() + { CalendarTitleBackColor = DefaultForeColor; } - private void ResetCalendarTrailingForeColor() { + private void ResetCalendarTrailingForeColor() + { CalendarTrailingForeColor = DefaultTrailingForeColor; } @@ -1182,28 +1362,32 @@ private void ResetCalendarTrailingForeColor() { /// Resets the property to its default /// value. /// - private void ResetFormat() { + private void ResetFormat() + { Format = DateTimePickerFormat.Long; } /// /// Resets the property to its default value. /// - private void ResetMaxDate() { + private void ResetMaxDate() + { MaxDate = MaximumDateTime; } /// /// Resets the property to its default value. /// - private void ResetMinDate() { + private void ResetMinDate() + { MinDate = MinimumDateTime; } /// /// Resets the property to its default value. /// - private void ResetValue() { + private void ResetValue() + { // always update on reset with ShowNone = false -- as it'll take the current time. this.value = DateTime.Now; @@ -1217,7 +1401,8 @@ private void ResetValue() { userHasSetValue = false; // Update the text displayed in the DateTimePicker - if (IsHandleCreated) { + if (IsHandleCreated) + { int gdt = NativeMethods.GDT_VALID; NativeMethods.SYSTEMTIME sys = DateTimePicker.DateTimeToSysTime(value); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.DTM_SETSYSTEMTIME, gdt, sys); @@ -1234,8 +1419,10 @@ private void ResetValue() { /// /// If the handle has been created, this applies the color to the control /// - private void SetControlColor(int colorIndex, Color value) { - if (IsHandleCreated) { + private void SetControlColor(int colorIndex, Color value) + { + if (IsHandleCreated) + { SendMessage(NativeMethods.DTM_SETMCCOLOR, colorIndex, ColorTranslator.ToWin32(value)); } } @@ -1243,8 +1430,10 @@ private void SetControlColor(int colorIndex, Color value) { /// /// If the handle has been created, this applies the font to the control. /// - private void SetControlCalendarFont() { - if (IsHandleCreated) { + private void SetControlCalendarFont() + { + if (IsHandleCreated) + { SendMessage(NativeMethods.DTM_SETMCFONT, CalendarFontHandle, NativeMethods.InvalidIntPtr); } } @@ -1252,7 +1441,8 @@ private void SetControlCalendarFont() { /// /// Applies all the colors to the control. /// - private void SetAllControlColors() { + private void SetAllControlColors() + { SetControlColor(NativeMethods.MCSC_MONTHBK, calendarMonthBackground); SetControlColor(NativeMethods.MCSC_TEXT, calendarForeColor); SetControlColor(NativeMethods.MCSC_TITLEBK, calendarTitleBackColor); @@ -1264,12 +1454,15 @@ private void SetAllControlColors() { /// Updates the window handle with the min/max ranges if it has been /// created. /// - private void SetRange() { + private void SetRange() + { SetRange(EffectiveMinDate(min), EffectiveMaxDate(max)); } - private void SetRange(DateTime min, DateTime max) { - if (IsHandleCreated) { + private void SetRange(DateTime min, DateTime max) + { + if (IsHandleCreated) + { int flags = 0; NativeMethods.SYSTEMTIMEARRAY sa = new NativeMethods.SYSTEMTIMEARRAY(); @@ -1300,17 +1493,22 @@ private void SetRange(DateTime min, DateTime max) { /// /// Turns on or off a given style bit /// - private void SetStyleBit(bool flag, int bit) { - if (((style & bit) != 0) == flag) return; + private void SetStyleBit(bool flag, int bit) + { + if (((style & bit) != 0) == flag) + return; - if (flag) { + if (flag) + { style |= bit; } - else { + else + { style &= ~bit; } - if (IsHandleCreated) { + if (IsHandleCreated) + { RecreateHandle(); Invalidate(); Update(); @@ -1321,77 +1519,88 @@ private void SetStyleBit(bool flag, int bit) { /// Determines if the property needs to be /// persisted. /// - private bool ShouldSerializeCalendarForeColor() { + private bool ShouldSerializeCalendarForeColor() + { return !CalendarForeColor.Equals(DefaultForeColor); } /// /// Determines if the property needs to be persisted. /// - private bool ShouldSerializeCalendarFont() { + private bool ShouldSerializeCalendarFont() + { return calendarFont != null; } /// /// Determines if the property needs to be persisted. /// - private bool ShouldSerializeCalendarTitleBackColor() { + private bool ShouldSerializeCalendarTitleBackColor() + { return !calendarTitleBackColor.Equals(DefaultTitleBackColor); } /// /// Determines if the property needs to be persisted. /// - private bool ShouldSerializeCalendarTitleForeColor() { + private bool ShouldSerializeCalendarTitleForeColor() + { return !calendarTitleForeColor.Equals(DefaultTitleForeColor); } /// /// Determines if the property needs to be persisted. /// - private bool ShouldSerializeCalendarTrailingForeColor() { + private bool ShouldSerializeCalendarTrailingForeColor() + { return !calendarTrailingText.Equals(DefaultTrailingForeColor); } /// /// Determines if the property needs to be persisted. /// - private bool ShouldSerializeCalendarMonthBackground() { + private bool ShouldSerializeCalendarMonthBackground() + { return !calendarMonthBackground.Equals(DefaultMonthBackColor); } /// /// Determines if the property needs to be persisted. /// - private bool ShouldSerializeMaxDate() { + private bool ShouldSerializeMaxDate() + { return max != MaximumDateTime && max != DateTime.MaxValue; } /// /// Determines if the property needs to be persisted. /// - private bool ShouldSerializeMinDate() { + private bool ShouldSerializeMinDate() + { return min != MinimumDateTime && min != DateTime.MinValue; } /// /// Determines if the property needs to be persisted. /// - private bool ShouldSerializeValue() { + private bool ShouldSerializeValue() + { return userHasSetValue; } /// /// Determines if the property needs to be persisted. /// - private bool ShouldSerializeFormat() { - return(Format != DateTimePickerFormat.Long); + private bool ShouldSerializeFormat() + { + return (Format != DateTimePickerFormat.Long); } /// /// Returns the control as a string /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); return s + ", Value: " + FormatDateTime(Value); @@ -1400,31 +1609,38 @@ public override string ToString() { /// /// Forces a repaint of the updown control if it is displayed. /// - private void UpdateUpDown() { + private void UpdateUpDown() + { // The upDown control doesn't repaint correctly. // - if (ShowUpDown) { + if (ShowUpDown) + { EnumChildren c = new EnumChildren(); NativeMethods.EnumChildrenCallback cb = new NativeMethods.EnumChildrenCallback(c.enumChildren); UnsafeNativeMethods.EnumChildWindows(new HandleRef(this, Handle), cb, NativeMethods.NullHandleRef); - if (c.hwndFound != IntPtr.Zero) { + if (c.hwndFound != IntPtr.Zero) + { SafeNativeMethods.InvalidateRect(new HandleRef(c, c.hwndFound), null, true); SafeNativeMethods.UpdateWindow(new HandleRef(c, c.hwndFound)); } } } - private void MarshaledUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs pref) { - try { + private void MarshaledUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs pref) + { + try + { //use begininvoke instead of invoke in case the destination thread is not processing messages. BeginInvoke(new UserPreferenceChangedEventHandler(this.UserPreferenceChanged), new object[] { sender, pref }); } catch (InvalidOperationException) { } //if the destination thread does not exist, don't send. } - private void UserPreferenceChanged(object sender, UserPreferenceChangedEventArgs pref) { - if (pref.Category == UserPreferenceCategory.Locale) { - // We need to recreate the monthcalendar handle when the locale changes, because + private void UserPreferenceChanged(object sender, UserPreferenceChangedEventArgs pref) + { + if (pref.Category == UserPreferenceCategory.Locale) + { + // We need to recreate the monthcalendar handle when the locale changes, because // the day names etc. are only updated on a handle recreate (comctl32 limitation). // RecreateHandle(); @@ -1434,26 +1650,31 @@ private void UserPreferenceChanged(object sender, UserPreferenceChangedEventArgs /// /// Handles the DTN_CLOSEUP notification /// - private void WmCloseUp(ref Message m) { + private void WmCloseUp(ref Message m) + { OnCloseUp(EventArgs.Empty); } /// /// Handles the DTN_DATETIMECHANGE notification /// - private void WmDateTimeChange(ref Message m) { + private void WmDateTimeChange(ref Message m) + { NativeMethods.NMDATETIMECHANGE nmdtc = (NativeMethods.NMDATETIMECHANGE)m.GetLParam(typeof(NativeMethods.NMDATETIMECHANGE)); DateTime temp = value; bool oldvalid = validTime; - if (nmdtc.dwFlags != NativeMethods.GDT_NONE) { + if (nmdtc.dwFlags != NativeMethods.GDT_NONE) + { validTime = true; value = DateTimePicker.SysTimeToDateTime(nmdtc.st); userHasSetValue = true; } - else { + else + { validTime = false; } - if (value!=temp || oldvalid != validTime) { + if (value != temp || oldvalid != validTime) + { OnValueChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } @@ -1462,11 +1683,14 @@ private void WmDateTimeChange(ref Message m) { /// /// Handles the DTN_DROPDOWN notification /// - private void WmDropDown(ref Message m) { + private void WmDropDown(ref Message m) + { - if (this.RightToLeftLayout == true && this.RightToLeft == RightToLeft.Yes) { - IntPtr handle = SendMessage(NativeMethods.DTM_GETMONTHCAL, 0,0); - if (handle != IntPtr.Zero) { + if (this.RightToLeftLayout == true && this.RightToLeft == RightToLeft.Yes) + { + IntPtr handle = SendMessage(NativeMethods.DTM_GETMONTHCAL, 0, 0); + if (handle != IntPtr.Zero) + { int style = unchecked((int)((long)UnsafeNativeMethods.GetWindowLong(new HandleRef(this, handle), NativeMethods.GWL_EXSTYLE))); style |= NativeMethods.WS_EX_LAYOUTRTL | NativeMethods.WS_EX_NOINHERITLAYOUT; style &= ~(NativeMethods.WS_EX_RIGHT | NativeMethods.WS_EX_RTLREADING); @@ -1479,7 +1703,8 @@ private void WmDropDown(ref Message m) { /// /// Handles system color changes /// - protected override void OnSystemColorsChanged(EventArgs e) { + protected override void OnSystemColorsChanged(EventArgs e) + { SetAllControlColors(); base.OnSystemColorsChanged(e); } @@ -1487,11 +1712,14 @@ protected override void OnSystemColorsChanged(EventArgs e) { /// /// Handles the WM_COMMAND messages reflected from the parent control. /// - private void WmReflectCommand(ref Message m) { - if (m.HWnd == Handle) { + private void WmReflectCommand(ref Message m) + { + if (m.HWnd == Handle) + { NativeMethods.NMHDR nmhdr = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR)); - switch (nmhdr.code) { + switch (nmhdr.code) + { case NativeMethods.DTN_CLOSEUP: WmCloseUp(ref m); break; @@ -1508,11 +1736,14 @@ private void WmReflectCommand(ref Message m) { /// /// Overrided wndProc /// - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { case Interop.WindowMessages.WM_LBUTTONDOWN: Focus(); - if (!ValidationCancelled) { + if (!ValidationCancelled) + { base.WndProc(ref m); } break; @@ -1534,7 +1765,8 @@ protected override void WndProc(ref Message m) { /// Takes a DateTime value and returns a SYSTEMTIME struct /// Note: 1 second granularity /// - internal static NativeMethods.SYSTEMTIME DateTimeToSysTime(DateTime time) { + internal static NativeMethods.SYSTEMTIME DateTimeToSysTime(DateTime time) + { NativeMethods.SYSTEMTIME sys = new NativeMethods.SYSTEMTIME(); sys.wYear = (short)time.Year; sys.wMonth = (short)time.Month; @@ -1551,16 +1783,19 @@ internal static NativeMethods.SYSTEMTIME DateTimeToSysTime(DateTime time) { /// Takes a SYSTEMTIME struct and returns a DateTime value /// Note: 1 second granularity. /// - internal static DateTime SysTimeToDateTime(NativeMethods.SYSTEMTIME s) { + internal static DateTime SysTimeToDateTime(NativeMethods.SYSTEMTIME s) + { return new DateTime(s.wYear, s.wMonth, s.wDay, s.wHour, s.wMinute, s.wSecond); } /// /// - private sealed class EnumChildren { + private sealed class EnumChildren + { public IntPtr hwndFound = IntPtr.Zero; - public bool enumChildren(IntPtr hwnd, IntPtr lparam) { + public bool enumChildren(IntPtr hwnd, IntPtr lparam) + { hwndFound = hwnd; return true; } @@ -1569,65 +1804,82 @@ public bool enumChildren(IntPtr hwnd, IntPtr lparam) { /// /// [ComVisible(true)] - public class DateTimePickerAccessibleObject : ControlAccessibleObject { + public class DateTimePickerAccessibleObject : ControlAccessibleObject + { - public DateTimePickerAccessibleObject(DateTimePicker owner) : base(owner) { + public DateTimePickerAccessibleObject(DateTimePicker owner) : base(owner) + { } - public override string KeyboardShortcut { - get { + public override string KeyboardShortcut + { + get + { // APP COMPAT. When computing DateTimePickerAccessibleObject::get_KeyboardShorcut the previous label // takes precedence over DTP::Text. // This code was copied from the Everett sources. Label previousLabel = this.PreviousLabel; - if (previousLabel != null) { + if (previousLabel != null) + { char previousLabelMnemonic = WindowsFormsUtils.GetMnemonic(previousLabel.Text, false /*convertToUpperCase*/); - if (previousLabelMnemonic != (char) 0) { + if (previousLabelMnemonic != (char)0) + { return "Alt+" + previousLabelMnemonic; } } string baseShortcut = base.KeyboardShortcut; - - if ((baseShortcut == null || baseShortcut.Length == 0)) { + + if ((baseShortcut == null || baseShortcut.Length == 0)) + { char ownerTextMnemonic = WindowsFormsUtils.GetMnemonic(this.Owner.Text, false /*convertToUpperCase*/); - if (ownerTextMnemonic != (char) 0) { + if (ownerTextMnemonic != (char)0) + { return "Alt+" + ownerTextMnemonic; } } - + return baseShortcut; } } - public override string Value { - get { + public override string Value + { + get + { string baseValue = base.Value; - if (baseValue == null || baseValue.Length == 0) { + if (baseValue == null || baseValue.Length == 0) + { return Owner.Text; } return baseValue; } } - public override AccessibleStates State { - get { + public override AccessibleStates State + { + get + { AccessibleStates state = base.State; - if(((DateTimePicker)Owner).ShowCheckBox && - ((DateTimePicker)Owner).Checked) { - state |= AccessibleStates.Checked; + if (((DateTimePicker)Owner).ShowCheckBox && + ((DateTimePicker)Owner).Checked) + { + state |= AccessibleStates.Checked; } return state; } } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { AccessibleRole role = Owner.AccessibleRole; - if (role != AccessibleRole.Default) { + if (role != AccessibleRole.Default) + { return role; } @@ -1637,8 +1889,10 @@ public override AccessibleRole Role { internal override bool IsIAccessibleExSupported() => true; - internal override object GetPropertyValue(int propertyID) { - switch (propertyID) { + internal override object GetPropertyValue(int propertyID) + { + switch (propertyID) + { case NativeMethods.UIA_IsTogglePatternAvailablePropertyId: return IsPatternSupported(NativeMethods.UIA_TogglePatternId); case NativeMethods.UIA_LocalizedControlTypePropertyId: @@ -1648,8 +1902,10 @@ internal override object GetPropertyValue(int propertyID) { } } - internal override bool IsPatternSupported(int patternId) { - if (patternId == NativeMethods.UIA_TogglePatternId && ((DateTimePicker)Owner).ShowCheckBox) { + internal override bool IsPatternSupported(int patternId) + { + if (patternId == NativeMethods.UIA_TogglePatternId && ((DateTimePicker)Owner).ShowCheckBox) + { return true; } @@ -1658,15 +1914,18 @@ internal override bool IsPatternSupported(int patternId) { #region Toggle Pattern - internal override UnsafeNativeMethods.ToggleState ToggleState { - get { - return ((DateTimePicker)Owner).Checked ? - UnsafeNativeMethods.ToggleState.ToggleState_On : + internal override UnsafeNativeMethods.ToggleState ToggleState + { + get + { + return ((DateTimePicker)Owner).Checked ? + UnsafeNativeMethods.ToggleState.ToggleState_On : UnsafeNativeMethods.ToggleState.ToggleState_Off; } } - internal override void Toggle() { + internal override void Toggle() + { ((DateTimePicker)Owner).Checked = !((DateTimePicker)Owner).Checked; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Day.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Day.cs index 6d9f6d6db79..88922070a05 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Day.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Day.cs @@ -37,7 +37,7 @@ public enum Day /// /// The day Saturday. /// - Saturday = 5, + Saturday = 5, /// /// The day Sunday. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs index a5b3d00c387..b548749f2b1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.Design { +namespace System.Windows.Forms.Design +{ using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; @@ -24,7 +25,8 @@ namespace System.Windows.Forms.Design { ClassInterface(ClassInterfaceType.AutoDispatch) ] [ToolboxItem(false)] - public class ComponentEditorForm : Form { + public class ComponentEditorForm : Form + { private IComponent component; private Type[] pageTypes; private ComponentEditorPageSite[] pageSites; @@ -56,10 +58,12 @@ public class ComponentEditorForm : Form { /// Initializes a new instance of the class. /// /// - public ComponentEditorForm(object component, Type[] pageTypes) : base() { - - if (!(component is IComponent)) { - throw new ArgumentException(SR.ComponentEditorFormBadComponent,"component"); + public ComponentEditorForm(object component, Type[] pageTypes) : base() + { + + if (!(component is IComponent)) + { + throw new ArgumentException(SR.ComponentEditorFormBadComponent, "component"); } this.component = (IComponent)component; this.pageTypes = pageTypes; @@ -82,18 +86,25 @@ public ComponentEditorForm(object component, Type[] pageTypes) : base() { /// /// Applies any changes in the set of ComponentPageControl to the actual component. /// - internal virtual void ApplyChanges(bool lastApply) { - if (dirty) { + internal virtual void ApplyChanges(bool lastApply) + { + if (dirty) + { IComponentChangeService changeService = null; - if (component.Site != null) { + if (component.Site != null) + { changeService = (IComponentChangeService)component.Site.GetService(typeof(IComponentChangeService)); - if (changeService != null) { - try { + if (changeService != null) + { + try + { changeService.OnComponentChanging(component, null); } - catch (CheckoutException e) { - if (e == CheckoutException.Canceled) { + catch (CheckoutException e) + { + if (e == CheckoutException.Canceled) + { return; } throw e; @@ -101,14 +112,17 @@ internal virtual void ApplyChanges(bool lastApply) { } } - for (int n = 0; n < pageSites.Length; n++) { - if (pageSites[n].Dirty) { + for (int n = 0; n < pageSites.Length; n++) + { + if (pageSites[n].Dirty) + { pageSites[n].GetPageControl().ApplyChanges(); pageSites[n].Dirty = false; } } - if (changeService != null) { + if (changeService != null) + { changeService.OnComponentChanged(component, null, null, null); } @@ -116,8 +130,10 @@ internal virtual void ApplyChanges(bool lastApply) { cancelButton.Text = SR.CloseCaption; dirty = false; - if (lastApply == false) { - for (int n = 0; n < pageSites.Length; n++) { + if (lastApply == false) + { + for (int n = 0; n < pageSites.Length; n++) + { pageSites[n].GetPageControl().OnApplyComplete(); } } @@ -154,7 +170,7 @@ public override bool AutoSize { add => base.AutoSizeChanged += value; remove => base.AutoSizeChanged -= value; - } + } /* @@ -167,18 +183,23 @@ private void CreateNewTransaction() { /// /// Handles ok/cancel/apply/help button click events /// - private void OnButtonClick(object sender, EventArgs e) { - if (sender == okButton) { + private void OnButtonClick(object sender, EventArgs e) + { + if (sender == okButton) + { ApplyChanges(true); DialogResult = DialogResult.OK; } - else if (sender == cancelButton) { + else if (sender == cancelButton) + { DialogResult = DialogResult.Cancel; } - else if (sender == applyButton) { + else if (sender == applyButton) + { ApplyChanges(false); } - else if (sender == helpButton) { + else if (sender == helpButton) + { ShowPageHelp(); } } @@ -186,11 +207,14 @@ private void OnButtonClick(object sender, EventArgs e) { /// /// Lays out the UI of the form. /// - private void OnConfigureUI() { + private void OnConfigureUI() + { Font uiFont = Control.DefaultFont; - if (component.Site != null) { + if (component.Site != null) + { IUIService uiService = (IUIService)component.Site.GetService(typeof(IUIService)); - if (uiService != null) { + if (uiService != null) + { uiFont = (Font)uiService.Styles["DialogFont"]; } } @@ -214,14 +238,16 @@ private void OnConfigureUI() { int selectorWidth = MIN_SELECTOR_WIDTH; - if (pageSites != null) { + if (pageSites != null) + { // Add the nodes corresponding to the pages - for (int n = 0; n < pageSites.Length; n++) { + for (int n = 0; n < pageSites.Length; n++) + { ComponentEditorPage page = pageSites[n].GetPageControl(); string title = page.Title; Graphics graphics = CreateGraphicsInternal(); - int titleWidth = (int) graphics.MeasureString(title, Font).Width; + int titleWidth = (int)graphics.MeasureString(title, Font).Width; graphics.Dispose(); selectorImageList.Images.Add(page.Icon.ToBitmap()); @@ -234,10 +260,12 @@ private void OnConfigureUI() { string caption = string.Empty; ISite site = component.Site; - if (site != null) { + if (site != null) + { caption = string.Format(SR.ComponentEditorFormProperties, site.Name); } - else { + else + { caption = SR.ComponentEditorFormPropertiesNoName; } this.Text = caption; @@ -249,9 +277,11 @@ private void OnConfigureUI() { grayStrip.Bounds = new Rectangle(pageHostBounds.X, BUTTON_PAD, pageHostBounds.Width, STRIP_HEIGHT); - if (pageSites != null) { + if (pageSites != null) + { Rectangle pageBounds = new Rectangle(0, 0, pageHostBounds.Width, pageHostBounds.Height); - for (int n = 0; n < pageSites.Length; n++) { + for (int n = 0; n < pageSites.Length; n++) + { ComponentEditorPage page = pageSites[n].GetPageControl(); page.GetControl().Bounds = pageBounds; } @@ -299,7 +329,7 @@ private void OnConfigureUI() { okButton.FlatStyle = FlatStyle.System; this.AcceptButton = okButton; - this.Controls.Clear(); + this.Controls.Clear(); this.Controls.AddRange(new Control[] { selector, grayStrip, @@ -310,12 +340,12 @@ private void OnConfigureUI() { helpButton }); - #pragma warning disable 618 +#pragma warning disable 618 // continuing with the old autoscale base size stuff, it works, // and is currently set to a non-standard height AutoScaleBaseSize = new Size(5, 14); ApplyAutoScaling(); - #pragma warning restore 618 +#pragma warning restore 618 } @@ -324,12 +354,14 @@ private void OnConfigureUI() { /// [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] // - protected override void OnActivated(EventArgs e) { + protected override void OnActivated(EventArgs e) + { base.OnActivated(e); - if (firstActivate) { + if (firstActivate) + { firstActivate = false; - + selector.SelectedNode = selector.Nodes[initialActivePage]; pageSites[initialActivePage].Active = true; activePage = initialActivePage; @@ -342,7 +374,8 @@ protected override void OnActivated(EventArgs e) { /// [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] // - protected override void OnHelpRequested(HelpEventArgs e) { + protected override void OnHelpRequested(HelpEventArgs e) + { base.OnHelpRequested(e); ShowPageHelp(); } @@ -350,7 +383,8 @@ protected override void OnHelpRequested(HelpEventArgs e) { /// /// Called to initialize this form with the new component. /// - private void OnNewObjects() { + private void OnNewObjects() + { pageSites = null; maxSize = new Size(3 * (BUTTON_WIDTH + BUTTON_PAD), 24 * pageTypes.Length); @@ -358,7 +392,8 @@ private void OnNewObjects() { // create sites for them // - for (int n = 0; n < pageTypes.Length; n++) { + for (int n = 0; n < pageTypes.Length; n++) + { pageSites[n] = new ComponentEditorPageSite(pageHost, pageTypes[n], component, this); ComponentEditorPage page = pageSites[n].GetPageControl(); @@ -371,7 +406,8 @@ private void OnNewObjects() { // and set them all to an ideal size // - for (int n = 0; n < pageSites.Length; n++) { + for (int n = 0; n < pageSites.Length; n++) + { pageSites[n].GetPageControl().Size = maxSize; } } @@ -379,13 +415,15 @@ private void OnNewObjects() { /// /// Handles switching between pages. /// - protected virtual void OnSelChangeSelector(object source, TreeViewEventArgs e) { - if (firstActivate == true) { + protected virtual void OnSelChangeSelector(object source, TreeViewEventArgs e) + { + if (firstActivate == true) + { // treeview seems to fire a change event when it is first setup before // the form is activated return; } - + int newPage = selector.SelectedNode.Index; Debug.Assert((newPage >= 0) && (newPage < pageSites.Length), "Invalid page selected"); @@ -393,7 +431,8 @@ protected virtual void OnSelChangeSelector(object source, TreeViewEventArgs e) { if (newPage == activePage) return; - if (activePage != -1) { + if (activePage != -1) + { if (pageSites[activePage].AutoCommit) ApplyChanges(false); pageSites[activePage].Active = false; @@ -408,7 +447,8 @@ protected virtual void OnSelChangeSelector(object source, TreeViewEventArgs e) { /// Provides a method to override in order to pre-process input messages before /// they are dispatched. /// - public override bool PreProcessMessage(ref Message msg) { + public override bool PreProcessMessage(ref Message msg) + { if (null != pageSites && pageSites[activePage].GetPageControl().IsPageMessage(ref msg)) return true; @@ -419,7 +459,8 @@ public override bool PreProcessMessage(ref Message msg) { /// Sets the controls of the form to dirty. This enables the "apply" /// button. /// - internal virtual void SetDirty() { + internal virtual void SetDirty() + { dirty = true; applyButton.Enabled = true; cancelButton.Text = SR.CancelCaption; @@ -428,35 +469,41 @@ internal virtual void SetDirty() { /// /// Shows the form. The form will have no owner window. /// - public virtual DialogResult ShowForm() { + public virtual DialogResult ShowForm() + { return ShowForm(null, 0); } /// /// Shows the form and the specified page. The form will have no owner window. /// - public virtual DialogResult ShowForm(int page) { + public virtual DialogResult ShowForm(int page) + { return ShowForm(null, page); } /// /// Shows the form with the specified owner. /// - public virtual DialogResult ShowForm(IWin32Window owner) { + public virtual DialogResult ShowForm(IWin32Window owner) + { return ShowForm(owner, 0); } /// /// Shows the form and the specified page with the specified owner. /// - public virtual DialogResult ShowForm(IWin32Window owner, int page) { + public virtual DialogResult ShowForm(IWin32Window owner, int page) + { initialActivePage = page; // CreateNewTransaction(); - try { + try + { ShowDialog(owner); } - finally { + finally + { /* if (DialogResult == DialogResult.OK) { transaction.Commit(); @@ -474,10 +521,12 @@ public virtual DialogResult ShowForm(IWin32Window owner, int page) { /// /// Shows help for the active page. /// - private void ShowPageHelp() { + private void ShowPageHelp() + { Debug.Assert(activePage != -1); - if (pageSites[activePage].GetPageControl().SupportsHelp()) { + if (pageSites[activePage].GetPageControl().SupportsHelp()) + { pageSites[activePage].GetPageControl().ShowHelp(); } } @@ -486,7 +535,8 @@ private void ShowPageHelp() { /// Implements a standard version of ComponentEditorPageSite for use within a /// ComponentEditorForm. /// - private sealed class ComponentEditorPageSite : IComponentEditorPageSite { + private sealed class ComponentEditorPageSite : IComponentEditorPageSite + { internal IComponent component; internal ComponentEditorPage pageControl; internal Control parent; @@ -497,7 +547,8 @@ private sealed class ComponentEditorPageSite : IComponentEditorPageSite { /// /// Creates the page site. /// - internal ComponentEditorPageSite(Control parent, Type pageClass, IComponent component, ComponentEditorForm form) { + internal ComponentEditorPageSite(Control parent, Type pageClass, IComponent component, ComponentEditorForm form) + { this.component = component; this.parent = parent; this.isActive = false; @@ -508,10 +559,12 @@ internal ComponentEditorPageSite(Control parent, Type pageClass, IComponent comp this.form = form; - try { + try + { pageControl = (ComponentEditorPage)Activator.CreateInstance(pageClass); } - catch (TargetInvocationException e) { + catch (TargetInvocationException e) + { Debug.Fail(e.ToString()); throw new TargetInvocationException(string.Format(SR.ExceptionCreatingCompEditorControl, e.ToString()), e.InnerException); } @@ -523,33 +576,42 @@ internal ComponentEditorPageSite(Control parent, Type pageClass, IComponent comp /// /// Called by the ComponentEditorForm to activate / deactivate the page. /// - internal bool Active { - set { - if (value) { + internal bool Active + { + set + { + if (value) + { // make sure the page has been created pageControl.CreateControl(); // activate it and give it focus pageControl.Activate(); } - else { + else + { pageControl.Deactivate(); } isActive = value; } } - internal bool AutoCommit { - get { + internal bool AutoCommit + { + get + { return pageControl.CommitOnDeactivate; } } - internal bool Dirty { - get { + internal bool Dirty + { + get + { return isDirty; } - set { + set + { isDirty = value; } } @@ -557,24 +619,27 @@ internal bool Dirty { /// /// Called by a page to return a parenting control for itself. /// - public Control GetControl() { + public Control GetControl() + { return parent; } /// /// Called by the ComponentEditorForm to get the actual page. /// - internal ComponentEditorPage GetPageControl() { + internal ComponentEditorPage GetPageControl() + { return pageControl; } /// /// Called by a page to mark it's contents as dirty. /// - public void SetDirty() { + public void SetDirty() + { if (isActive) Dirty = true; - form.SetDirty(); + form.SetDirty(); } } @@ -582,7 +647,8 @@ public void SetDirty() { /// // This should be moved into a shared location // Its a duplication of what exists in the StyleBuilder. - internal sealed class PageSelector : TreeView { + internal sealed class PageSelector : TreeView + { private const int PADDING_VERT = 3; private const int PADDING_HORZ = 4; @@ -596,7 +662,8 @@ internal sealed class PageSelector : TreeView { private IntPtr hbrushDither; - public PageSelector() { + public PageSelector() + { this.HotTracking = true; this.HideSelection = false; this.BackColor = SystemColors.Control; @@ -613,8 +680,10 @@ public PageSelector() { - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ExStyle |= NativeMethods.WS_EX_STATICEDGE; @@ -622,7 +691,8 @@ protected override CreateParams CreateParams { } } - private void CreateDitherBrush() { + private void CreateDitherBrush() + { Debug.Assert(hbrushDither == IntPtr.Zero, "Brush should not be recreated."); short[] patternBits = new short[] { @@ -634,7 +704,8 @@ private void CreateDitherBrush() { Debug.Assert(hbitmapTemp != IntPtr.Zero, "could not create dither bitmap. Page selector UI will not be correct"); - if (hbitmapTemp != IntPtr.Zero) { + if (hbitmapTemp != IntPtr.Zero) + { hbrushDither = SafeNativeMethods.CreatePatternBrush(new HandleRef(null, hbitmapTemp)); Debug.Assert(hbrushDither != IntPtr.Zero, @@ -645,7 +716,8 @@ private void CreateDitherBrush() { } private void DrawTreeItem(string itemText, int imageIndex, IntPtr dc, NativeMethods.RECT rcIn, - int state, int backColor, int textColor) { + int state, int backColor, int textColor) + { IntNativeMethods.SIZE size = new IntNativeMethods.SIZE(); IntNativeMethods.RECT rc2 = new IntNativeMethods.RECT(); IntNativeMethods.RECT rc = new IntNativeMethods.RECT(rcIn.left, rcIn.top, rcIn.right, rcIn.bottom); @@ -658,11 +730,13 @@ private void DrawTreeItem(string itemText, int imageIndex, IntPtr dc, NativeMeth hfontOld = SafeNativeMethods.SelectObject(new HandleRef(null, dc), new HandleRef(Parent, ((Control)Parent).FontHandle)); // Fill the background - if (((state & STATE_SELECTED) != 0) && (hbrushDither != IntPtr.Zero)) { + if (((state & STATE_SELECTED) != 0) && (hbrushDither != IntPtr.Zero)) + { FillRectDither(dc, rcIn); SafeNativeMethods.SetBkMode(new HandleRef(null, dc), NativeMethods.TRANSPARENT); } - else { + else + { SafeNativeMethods.SetBkColor(new HandleRef(null, dc), backColor); IntUnsafeNativeMethods.ExtTextOut(new HandleRef(null, dc), 0, 0, NativeMethods.ETO_CLIPPED | NativeMethods.ETO_OPAQUE, ref rc, null, 0, null); } @@ -684,7 +758,8 @@ private void DrawTreeItem(string itemText, int imageIndex, IntPtr dc, NativeMeth NativeMethods.ILD_TRANSPARENT); // Draw the hot-tracking border if needed - if ((state & STATE_HOT) != 0) { + if ((state & STATE_HOT) != 0) + { int savedColor; // top left @@ -716,7 +791,8 @@ private void DrawTreeItem(string itemText, int imageIndex, IntPtr dc, NativeMeth SafeNativeMethods.SelectObject(new HandleRef(null, dc), new HandleRef(null, hfontOld)); } - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { base.OnHandleCreated(e); int itemHeight; @@ -725,37 +801,41 @@ protected override void OnHandleCreated(EventArgs e) { itemHeight += 2 * PADDING_VERT; UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TVM_SETITEMHEIGHT, itemHeight, 0); - if (hbrushDither == IntPtr.Zero) { + if (hbrushDither == IntPtr.Zero) + { CreateDitherBrush(); } } - private void OnCustomDraw(ref Message m) { + private void OnCustomDraw(ref Message m) + { NativeMethods.NMTVCUSTOMDRAW nmtvcd = (NativeMethods.NMTVCUSTOMDRAW)m.GetLParam(typeof(NativeMethods.NMTVCUSTOMDRAW)); - switch (nmtvcd.nmcd.dwDrawStage) { + switch (nmtvcd.nmcd.dwDrawStage) + { case NativeMethods.CDDS_PREPAINT: m.Result = (IntPtr)(NativeMethods.CDRF_NOTIFYITEMDRAW | NativeMethods.CDRF_NOTIFYPOSTPAINT); break; case NativeMethods.CDDS_ITEMPREPAINT: { TreeNode itemNode = TreeNode.FromHandle(this, (IntPtr)nmtvcd.nmcd.dwItemSpec); - if (itemNode != null) { + if (itemNode != null) + { int state = STATE_NORMAL; int itemState = nmtvcd.nmcd.uItemState; if (((itemState & NativeMethods.CDIS_HOT) != 0) || ((itemState & NativeMethods.CDIS_FOCUS) != 0)) - state |= STATE_HOT; + state |= STATE_HOT; if ((itemState & NativeMethods.CDIS_SELECTED) != 0) - state |= STATE_SELECTED; + state |= STATE_SELECTED; DrawTreeItem(itemNode.Text, itemNode.ImageIndex, nmtvcd.nmcd.hdc, nmtvcd.nmcd.rc, state, ColorTranslator.ToWin32(SystemColors.Control), ColorTranslator.ToWin32(SystemColors.ControlText)); - } + } m.Result = (IntPtr)NativeMethods.CDRF_SKIPDEFAULT; - + } break; case NativeMethods.CDDS_POSTPAINT: @@ -767,19 +847,23 @@ private void OnCustomDraw(ref Message m) { } } - protected override void OnHandleDestroyed(EventArgs e) { + protected override void OnHandleDestroyed(EventArgs e) + { base.OnHandleDestroyed(e); - if (!RecreatingHandle && (hbrushDither != IntPtr.Zero)) { + if (!RecreatingHandle && (hbrushDither != IntPtr.Zero)) + { SafeNativeMethods.DeleteObject(new HandleRef(this, hbrushDither)); hbrushDither = IntPtr.Zero; } } - private void FillRectDither(IntPtr dc, NativeMethods.RECT rc) { + private void FillRectDither(IntPtr dc, NativeMethods.RECT rc) + { IntPtr hbrushOld = SafeNativeMethods.SelectObject(new HandleRef(null, dc), new HandleRef(this, hbrushDither)); - if (hbrushOld != IntPtr.Zero) { + if (hbrushOld != IntPtr.Zero) + { int oldTextColor, oldBackColor; oldTextColor = SafeNativeMethods.SetTextColor(new HandleRef(null, dc), ColorTranslator.ToWin32(SystemColors.ControlLightLight)); @@ -791,10 +875,13 @@ private void FillRectDither(IntPtr dc, NativeMethods.RECT rc) { } } - protected override void WndProc(ref Message m) { - if (m.Msg == Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_NOTIFY) { + protected override void WndProc(ref Message m) + { + if (m.Msg == Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_NOTIFY) + { NativeMethods.NMHDR nmh = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR)); - if (nmh.code == NativeMethods.NM_CUSTOMDRAW) { + if (nmh.code == NativeMethods.NM_CUSTOMDRAW) + { OnCustomDraw(ref m); return; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorPage.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorPage.cs index 71454a585b8..f365fa97186 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorPage.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorPage.cs @@ -4,7 +4,8 @@ -namespace System.Windows.Forms.Design { +namespace System.Windows.Forms.Design +{ using System.ComponentModel; using System.Diagnostics; @@ -25,7 +26,8 @@ namespace System.Windows.Forms.Design { ClassInterface(ClassInterfaceType.AutoDispatch), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1012:AbstractTypesShouldNotHaveConstructors") // Shipped in Everett ] - public abstract class ComponentEditorPage : Panel { + public abstract class ComponentEditorPage : Panel + { IComponentEditorPageSite pageSite; IComponent component; @@ -40,7 +42,8 @@ public abstract class ComponentEditorPage : Panel { /// Initializes a new instance of the class. /// /// - public ComponentEditorPage() : base() { + public ComponentEditorPage() : base() + { commitOnDeactivate = false; firstActivate = true; loadRequired = false; @@ -78,35 +81,40 @@ public override bool AutoSize /// /// Gets or sets the page site. /// - protected IComponentEditorPageSite PageSite { + protected IComponentEditorPageSite PageSite + { get { return pageSite; } set { pageSite = value; } } /// /// Gets or sets the component to edit. /// - protected IComponent Component { + protected IComponent Component + { get { return component; } set { component = value; } } /// /// Indicates whether the page is being activated for the first time. /// - protected bool FirstActivate { + protected bool FirstActivate + { get { return firstActivate; } set { firstActivate = value; } } /// /// Indicates whether a load is required previous to editing. /// - protected bool LoadRequired { + protected bool LoadRequired + { get { return loadRequired; } set { loadRequired = value; } } /// /// Indicates if loading is taking place. /// - protected int Loading { + protected int Loading + { get { return loading; } set { loading = value; } } @@ -115,11 +123,14 @@ protected int Loading { /// Indicates whether an editor should apply its /// changes before it is deactivated. /// - public bool CommitOnDeactivate { - get { + public bool CommitOnDeactivate + { + get + { return commitOnDeactivate; } - set { + set + { commitOnDeactivate = value; } } @@ -127,8 +138,10 @@ public bool CommitOnDeactivate { /// /// Gets or sets the creation parameters for this control. /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.Style &= ~(NativeMethods.WS_BORDER | NativeMethods.WS_OVERLAPPED | NativeMethods.WS_DLGFRAME); return cp; @@ -138,16 +151,20 @@ protected override CreateParams CreateParams { /// /// Gets or sets the icon for this page. /// - public Icon Icon { - - - get { - if (icon == null) { + public Icon Icon + { + + + get + { + if (icon == null) + { icon = new Icon(typeof(ComponentEditorPage), "ComponentEditorPage"); } return icon; } - set { + set + { icon = value; } } @@ -156,8 +173,10 @@ public Icon Icon { /// /// Gets or sets the title of the page. /// - public virtual string Title { - get { + public virtual string Title + { + get + { return base.Text; } } @@ -165,8 +184,10 @@ public virtual string Title { /// /// Activates and displays the page. /// - public virtual void Activate() { - if (loadRequired) { + public virtual void Activate() + { + if (loadRequired) + { EnterLoadingMode(); LoadComponent(); ExitLoadingMode(); @@ -180,14 +201,16 @@ public virtual void Activate() { /// /// Applies changes to all the components being edited. /// - public virtual void ApplyChanges() { + public virtual void ApplyChanges() + { SaveComponent(); } /// /// Deactivates and hides the page. /// - public virtual void Deactivate() { + public virtual void Deactivate() + { Visible = false; } @@ -195,7 +218,8 @@ public virtual void Deactivate() { /// Increments the loading counter, which determines whether a page /// is in loading mode. /// - protected void EnterLoadingMode() { + protected void EnterLoadingMode() + { loading++; } @@ -203,7 +227,8 @@ protected void EnterLoadingMode() { /// Decrements the loading counter, which determines whether a page /// is in loading mode. /// - protected void ExitLoadingMode() { + protected void ExitLoadingMode() + { Debug.Assert(loading > 0, "Unbalanced Enter/ExitLoadingMode calls"); loading--; } @@ -211,35 +236,40 @@ protected void ExitLoadingMode() { /// /// Gets the control that represents the window for this page. /// - public virtual Control GetControl() { + public virtual Control GetControl() + { return this; } /// /// Gets the component that is to be edited. /// - protected IComponent GetSelectedComponent() { + protected IComponent GetSelectedComponent() + { return component; } /// /// Processes messages that could be handled by the page. /// - public virtual bool IsPageMessage(ref Message msg) { + public virtual bool IsPageMessage(ref Message msg) + { return PreProcessMessage(ref msg); } /// /// Gets a value indicating whether the page is being activated for the first time. /// - protected bool IsFirstActivate() { + protected bool IsFirstActivate() + { return firstActivate; } /// /// Gets a value indicating whether the page is being loaded. /// - protected bool IsLoading() { + protected bool IsLoading() + { return loading != 0; } @@ -253,7 +283,8 @@ protected bool IsLoading() { /// Called when the page along with its sibling /// pages have applied their changes. /// - public virtual void OnApplyComplete() { + public virtual void OnApplyComplete() + { ReloadComponent(); } @@ -261,8 +292,10 @@ public virtual void OnApplyComplete() { /// Called when the current component may have changed elsewhere /// and needs to be reloded into the UI. /// - protected virtual void ReloadComponent() { - if (Visible == false) { + protected virtual void ReloadComponent() + { + if (Visible == false) + { loadRequired = true; } } @@ -275,8 +308,10 @@ protected virtual void ReloadComponent() { /// /// Sets the page to be in dirty state. /// - protected virtual void SetDirty() { - if (IsLoading() == false) { + protected virtual void SetDirty() + { + if (IsLoading() == false) + { pageSite.SetDirty(); } } @@ -284,7 +319,8 @@ protected virtual void SetDirty() { /// /// Sets the component to be edited. /// - public virtual void SetComponent(IComponent component) { + public virtual void SetComponent(IComponent component) + { this.component = component; loadRequired = true; } @@ -292,7 +328,8 @@ public virtual void SetComponent(IComponent component) { /// /// Sets the site for this page. /// - public virtual void SetSite(IComponentEditorPageSite site) { + public virtual void SetSite(IComponentEditorPageSite site) + { this.pageSite = site; pageSite.GetControl().Controls.Add(this); @@ -302,13 +339,15 @@ public virtual void SetSite(IComponentEditorPageSite site) { /// /// Provides help information to the help system. /// - public virtual void ShowHelp() { + public virtual void ShowHelp() + { } /// /// Gets a value indicating whether the editor supports Help. /// - public virtual bool SupportsHelp() { + public virtual bool SupportsHelp() + { return false; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DisplayInformation.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DisplayInformation.cs index 6c4e762b256..c2185ebad27 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DisplayInformation.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DisplayInformation.cs @@ -19,35 +19,42 @@ internal class DisplayInformation private static bool dropShadowEnabled; private static bool menuAccessKeysUnderlinedValid; private static bool menuAccessKeysUnderlined; - - - static DisplayInformation() { + + + static DisplayInformation() + { SystemEvents.UserPreferenceChanging += new UserPreferenceChangingEventHandler(UserPreferenceChanging); - SystemEvents.DisplaySettingsChanging += new EventHandler(DisplaySettingsChanging); + SystemEvents.DisplaySettingsChanging += new EventHandler(DisplaySettingsChanging); } - public static short BitsPerPixel { - get { - if (bitsPerPixel == 0) { + public static short BitsPerPixel + { + get + { + if (bitsPerPixel == 0) + { // we used to iterate through all screens, but // for some reason unused screens can temparily appear // in the AllScreens collection - we would honor the display // setting of an unused screen. // According to EnumDisplayMonitors, a primary screen check should be sufficient bitsPerPixel = (short)Screen.PrimaryScreen.BitsPerPixel; - - } - return bitsPerPixel; - } - } + + } + return bitsPerPixel; + } + } /// ///tests to see if the monitor is in low resolution mode (8-bit color depth or less). /// - public static bool LowResolution { - get { - - if (lowResSettingValid && !lowRes) { + public static bool LowResolution + { + get + { + + if (lowResSettingValid && !lowRes) + { return lowRes; } // dont cache if we're in low resolution. @@ -60,9 +67,12 @@ public static bool LowResolution { /// ///tests to see if we are under high contrast mode /// - public static bool HighContrast { - get { - if (highContrastSettingValid) { + public static bool HighContrast + { + get + { + if (highContrastSettingValid) + { return highContrast; } highContrast = SystemInformation.HighContrast; @@ -70,9 +80,12 @@ public static bool HighContrast { return highContrast; } } - public static bool IsDropShadowEnabled { - get { - if (dropShadowSettingValid) { + public static bool IsDropShadowEnabled + { + get + { + if (dropShadowSettingValid) + { return dropShadowEnabled; } dropShadowEnabled = SystemInformation.IsDropShadowEnabled; @@ -84,9 +97,12 @@ public static bool IsDropShadowEnabled { /// ///test to see if we are under terminal server mode /// - public static bool TerminalServer { - get { - if (terminalSettingValid) { + public static bool TerminalServer + { + get + { + if (terminalSettingValid) + { return isTerminalServerSession; } @@ -97,14 +113,17 @@ public static bool TerminalServer { } // return if mnemonic underlines should always be there regardless of ALT - public static bool MenuAccessKeysUnderlined { - get { - if (menuAccessKeysUnderlinedValid) { - return menuAccessKeysUnderlined; - } - menuAccessKeysUnderlined = SystemInformation.MenuAccessKeysUnderlined; - menuAccessKeysUnderlinedValid = true; - return menuAccessKeysUnderlined; + public static bool MenuAccessKeysUnderlined + { + get + { + if (menuAccessKeysUnderlinedValid) + { + return menuAccessKeysUnderlined; + } + menuAccessKeysUnderlined = SystemInformation.MenuAccessKeysUnderlined; + menuAccessKeysUnderlinedValid = true; + return menuAccessKeysUnderlined; } } @@ -112,7 +131,7 @@ public static bool MenuAccessKeysUnderlined { ///event handler for change in display setting /// private static void DisplaySettingsChanging(object obj, EventArgs ea) - { + { highContrastSettingValid = false; lowResSettingValid = false; terminalSettingValid = false; @@ -124,16 +143,18 @@ private static void DisplaySettingsChanging(object obj, EventArgs ea) /// ///event handler for change in user preference /// - private static void UserPreferenceChanging(object obj, UserPreferenceChangingEventArgs e) { + private static void UserPreferenceChanging(object obj, UserPreferenceChangingEventArgs e) + { highContrastSettingValid = false; lowResSettingValid = false; terminalSettingValid = false; dropShadowSettingValid = false; bitsPerPixel = 0; - - if (e.Category == UserPreferenceCategory.General) { - menuAccessKeysUnderlinedValid =false; + + if (e.Category == UserPreferenceCategory.General) + { + menuAccessKeysUnderlinedValid = false; } } } - } +} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DockingAttribute.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DockingAttribute.cs index 096f119943e..6ad98f2e3b3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DockingAttribute.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DockingAttribute.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ /// /// @@ -10,7 +11,8 @@ namespace System.Windows.Forms { /// /// [AttributeUsage(AttributeTargets.Class)] - public sealed class DockingAttribute : Attribute { + public sealed class DockingAttribute : Attribute + { private DockingBehavior dockingBehavior; /// @@ -18,16 +20,18 @@ public sealed class DockingAttribute : Attribute { /// Default constructor. /// /// - public DockingAttribute() { + public DockingAttribute() + { this.dockingBehavior = DockingBehavior.Never; } - + /// /// /// Constructor. /// /// - public DockingAttribute(DockingBehavior dockingBehavior) { + public DockingAttribute(DockingBehavior dockingBehavior) + { this.dockingBehavior = dockingBehavior; } @@ -44,16 +48,20 @@ public DockingAttribute(DockingBehavior dockingBehavior) { /// DockingBehavior property. /// /// - public DockingBehavior DockingBehavior { - get { + public DockingBehavior DockingBehavior + { + get + { return dockingBehavior; } } /// /// - public override bool Equals(object obj) { - if (obj == this) { + public override bool Equals(object obj) + { + if (obj == this) + { return true; } @@ -62,13 +70,15 @@ public override bool Equals(object obj) { return (other != null) && other.DockingBehavior == this.dockingBehavior; } - public override int GetHashCode() { + public override int GetHashCode() + { return dockingBehavior.GetHashCode(); } /// /// - public override bool IsDefaultAttribute() { + public override bool IsDefaultAttribute() + { return (this.Equals(Default)); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DomainUpDown.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DomainUpDown.cs index d049b9ea14e..94ae4a9c607 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DomainUpDown.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DomainUpDown.cs @@ -2,12 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; using System; - + using System.Runtime.InteropServices; using System.ComponentModel; using System.Drawing; @@ -28,10 +29,11 @@ namespace System.Windows.Forms { DefaultBindingProperty(nameof(SelectedItem)), SRDescription(nameof(SR.DescriptionDomainUpDown)) ] - public class DomainUpDown : UpDownBase { + public class DomainUpDown : UpDownBase + { - private readonly static string DefaultValue = string.Empty; - private readonly static bool DefaultWrap = false; + private readonly static string DefaultValue = string.Empty; + private readonly static bool DefaultWrap = false; ////////////////////////////////////////////////////////////// // Member variables @@ -59,12 +61,13 @@ public class DomainUpDown : UpDownBase { /// Initializes a new instance of the class. /// /// - public DomainUpDown() : base() { + public DomainUpDown() : base() + { // this class overrides GetPreferredSizeCore, let Control automatically cache the result - SetState2(STATE2_USEPREFERREDSIZECACHE, true); + SetState2(STATE2_USEPREFERREDSIZECACHE, true); Text = string.Empty; - } - + } + // Properties /// @@ -80,10 +83,13 @@ public DomainUpDown() : base() { Localizable(true), Editor("System.Windows.Forms.Design.StringCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)) ] - public DomainUpDownItemCollection Items { + public DomainUpDownItemCollection Items + { - get { - if (domainItems == null) { + get + { + if (domainItems == null) + { domainItems = new DomainUpDownItemCollection(this); } return domainItems; @@ -95,18 +101,21 @@ public DomainUpDownItemCollection Items { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Padding Padding { + public new Padding Padding + { get { return base.Padding; } - set { base.Padding = value;} + set { base.Padding = value; } } [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public new event EventHandler PaddingChanged { - add => base.PaddingChanged += value; - remove => base.PaddingChanged -= value; } + public new event EventHandler PaddingChanged + { + add => base.PaddingChanged += value; + remove => base.PaddingChanged -= value; + } /// /// @@ -119,23 +128,30 @@ public DomainUpDownItemCollection Items { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.DomainUpDownSelectedIndexDescr)) ] - public int SelectedIndex { + public int SelectedIndex + { - get { - if (UserEdit) { + get + { + if (UserEdit) + { return -1; } - else { + else + { return domainIndex; } } - set { - if (value < -1 || value >= Items.Count) { + set + { + if (value < -1 || value >= Items.Count) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(SelectedIndex), value)); } - - if (value != SelectedIndex) { + + if (value != SelectedIndex) + { SelectIndex(value); } } @@ -153,23 +169,30 @@ public int SelectedIndex { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.DomainUpDownSelectedItemDescr)) ] - public object SelectedItem { - get { + public object SelectedItem + { + get + { int index = SelectedIndex; - return(index == -1) ? null : Items[index]; + return (index == -1) ? null : Items[index]; } - set { + set + { // Treat null as selecting no item // - if (value == null) { + if (value == null) + { SelectedIndex = -1; } - else { + else + { // Attempt to find the given item in the list of items // - for (int i = 0; i < Items.Count; i++) { - if (value != null && value.Equals(Items[i])) { + for (int i = 0; i < Items.Count; i++) + { + if (value != null && value.Equals(Items[i])) + { SelectedIndex = i; break; } @@ -188,15 +211,19 @@ public object SelectedItem { DefaultValue(false), SRDescription(nameof(SR.DomainUpDownSortedDescr)) ] - public bool Sorted { + public bool Sorted + { - get { + get + { return sorted; } - set { + set + { sorted = value; - if (sorted) { + if (sorted) + { SortDomainItems(); } } @@ -214,13 +241,16 @@ public bool Sorted { DefaultValue(false), SRDescription(nameof(SR.DomainUpDownWrapDescr)) ] - public bool Wrap { + public bool Wrap + { - get { + get + { return wrap; } - set { + set + { wrap = value; } } @@ -237,56 +267,69 @@ public bool Wrap { /// /// [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.DomainUpDownOnSelectedItemChangedDescr))] - public event EventHandler SelectedItemChanged { + public event EventHandler SelectedItemChanged + { add => onSelectedItemChanged += value; remove => onSelectedItemChanged -= value; } - + /// /// Constructs the new instance of the accessibility object for this control. Subclasses /// should not call base.CreateAccessibilityObject. /// - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new DomainUpDownAccessibleObject(this); } - + /// /// /// Displays the next item in the object collection. /// /// - public override void DownButton() { + public override void DownButton() + { // Make sure domain values exist, and there are >0 items // - if (domainItems == null) { + if (domainItems == null) + { return; } - if (domainItems.Count <= 0) { + if (domainItems.Count <= 0) + { return; } // If the user has entered text, attempt to match it to the domain list // int matchIndex = -1; - if (UserEdit) { + if (UserEdit) + { matchIndex = MatchIndex(Text, false, domainIndex); } - if (matchIndex != -1) { + if (matchIndex != -1) + { // Found a match, so select this value - if (!LocalAppContextSwitches.UseLegacyDomainUpDownControlScrolling) { + if (!LocalAppContextSwitches.UseLegacyDomainUpDownControlScrolling) + { domainIndex = matchIndex; } SelectIndex(matchIndex); - } else { + } + else + { // Otherwise, get the next string in the domain list - if (domainIndex < domainItems.Count - 1) { + if (domainIndex < domainItems.Count - 1) + { SelectIndex(domainIndex + 1); - } else if (Wrap) { + } + else if (Wrap) + { SelectIndex(0); } } - + } /// @@ -297,28 +340,35 @@ public override void DownButton() { /// returns -1 otherwise. /// - internal int MatchIndex(string text, bool complete) { + internal int MatchIndex(string text, bool complete) + { return MatchIndex(text, complete, domainIndex); } - internal int MatchIndex(string text, bool complete, int startPosition) { + internal int MatchIndex(string text, bool complete, int startPosition) + { // Make sure domain values exist - if (domainItems == null) { + if (domainItems == null) + { return -1; } // Sanity check of parameters - if (text.Length < 1) { + if (text.Length < 1) + { return -1; } - if (domainItems.Count <= 0) { + if (domainItems.Count <= 0) + { return -1; } - if (startPosition < 0) { + if (startPosition < 0) + { startPosition = domainItems.Count - 1; } - if (startPosition >= domainItems.Count) { + if (startPosition >= domainItems.Count) + { startPosition = 0; } @@ -329,24 +379,28 @@ internal int MatchIndex(string text, bool complete, int startPosition) { int matchIndex = -1; bool found = false; - if (!complete) { + if (!complete) + { text = text.ToUpper(CultureInfo.InvariantCulture); } // Attempt to match the string with Items[index] - do { + do + { if (complete) found = Items[index].ToString().Equals(text); else found = Items[index].ToString().ToUpper(CultureInfo.InvariantCulture).StartsWith(text); - if (found) { + if (found) + { matchIndex = index; } // Calculate the next index to attempt to match index++; - if (index >= domainItems.Count) { + if (index >= domainItems.Count) + { index = 0; } @@ -362,7 +416,8 @@ internal int MatchIndex(string text, bool complete, int startPosition) { /// function. /// /// - protected override void OnChanged(object source, EventArgs e) { + protected override void OnChanged(object source, EventArgs e) + { OnSelectedItemChanged(source, e); } @@ -371,8 +426,10 @@ protected override void OnChanged(object source, EventArgs e) { /// event, using the input character to find the next matching item in our /// item collection. /// - protected override void OnTextBoxKeyPress(object source, KeyPressEventArgs e) { - if (ReadOnly) { + protected override void OnTextBoxKeyPress(object source, KeyPressEventArgs e) + { + if (ReadOnly) + { char[] character = new char[] { e.KeyChar }; UnicodeCategory uc = char.GetUnicodeCategory(character[0]); @@ -382,11 +439,13 @@ protected override void OnTextBoxKeyPress(object source, KeyPressEventArgs e) { || uc == UnicodeCategory.MathSymbol || uc == UnicodeCategory.OtherLetter || uc == UnicodeCategory.OtherNumber - || uc == UnicodeCategory.UppercaseLetter) { + || uc == UnicodeCategory.UppercaseLetter) + { // Attempt to match the character to a domain item int matchIndex = MatchIndex(new string(character), false, domainIndex + 1); - if (matchIndex != -1) { + if (matchIndex != -1) + { // Select the matching domain item SelectIndex(matchIndex); @@ -403,10 +462,12 @@ protected override void OnTextBoxKeyPress(object source, KeyPressEventArgs e) { /// Raises the event. /// /// - protected void OnSelectedItemChanged(object source, EventArgs e) { + protected void OnSelectedItemChanged(object source, EventArgs e) + { // Call the event handler - if (onSelectedItemChanged != null) { + if (onSelectedItemChanged != null) + { onSelectedItemChanged(this, e); } } @@ -414,63 +475,74 @@ protected void OnSelectedItemChanged(object source, EventArgs e) { /// /// Selects the item in the domain list at the given index /// - private void SelectIndex(int index) { + private void SelectIndex(int index) + { // Sanity check index Debug.Assert(domainItems != null, "Domain values array is null"); Debug.Assert(index < domainItems.Count && index >= -1, "SelectValue: index out of range"); - if (domainItems == null || index < -1 || index >= domainItems.Count) { + if (domainItems == null || index < -1 || index >= domainItems.Count) + { // Defensive programming index = -1; return; } - + // If the selected index has changed, update the text // domainIndex = index; - if (domainIndex >= 0) { + if (domainIndex >= 0) + { stringValue = domainItems[domainIndex].ToString(); UserEdit = false; UpdateEditText(); } - else { + else + { UserEdit = true; } - - Debug.Assert(domainIndex >=0 || UserEdit == true, "UserEdit should be true when domainIndex < 0 " + UserEdit); + + Debug.Assert(domainIndex >= 0 || UserEdit == true, "UserEdit should be true when domainIndex < 0 " + UserEdit); } /// /// Sorts the domain values /// - private void SortDomainItems() { + private void SortDomainItems() + { if (inSort) return; - + inSort = true; - try { + try + { // Sanity check Debug.Assert(sorted == true, "Sorted == false"); - if (!sorted) { + if (!sorted) + { return; } - if (domainItems != null) { + if (domainItems != null) + { // Sort the domain values ArrayList.Adapter(domainItems).Sort(new DomainUpDownItemCompare()); // Update the domain index - if (!UserEdit) { + if (!UserEdit) + { int newIndex = MatchIndex(stringValue, true); - if (newIndex != -1) { + if (newIndex != -1) + { SelectIndex(newIndex); } } } } - finally { + finally + { inSort = false; } } @@ -478,11 +550,13 @@ private void SortDomainItems() { /// /// Provides some interesting info about this control in String form. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); - if (Items != null) { + if (Items != null) + { s += ", Items.Count: " + Items.Count.ToString(CultureInfo.CurrentCulture); s += ", SelectedIndex: " + SelectedIndex.ToString(CultureInfo.CurrentCulture); } @@ -494,50 +568,63 @@ public override string ToString() { /// Displays the previous item in the collection. /// /// - public override void UpButton() { + public override void UpButton() + { // Make sure domain values exist, and there are >0 items - if (domainItems == null) { + if (domainItems == null) + { return; } - if (domainItems.Count <= 0) { + if (domainItems.Count <= 0) + { return; } // legacy behaviour. we do not want to void operation if domainIndex was -1 in latest runtime. - if (domainIndex == -1 && LocalAppContextSwitches.UseLegacyDomainUpDownControlScrolling) { + if (domainIndex == -1 && LocalAppContextSwitches.UseLegacyDomainUpDownControlScrolling) + { return; } // If the user has entered text, attempt to match it to the domain list int matchIndex = -1; - if (UserEdit) { + if (UserEdit) + { matchIndex = MatchIndex(Text, false, domainIndex); } - if (matchIndex != -1) { + if (matchIndex != -1) + { // Found a match, so set the domain index accordingly //In legacy (.NET framework 4.7.1 and below), we were just updating selected index but no actualy change in the spinner. //with new runtime, we update the selected index and perform spinner action. - if (!LocalAppContextSwitches.UseLegacyDomainUpDownControlScrolling) { + if (!LocalAppContextSwitches.UseLegacyDomainUpDownControlScrolling) + { domainIndex = matchIndex; } SelectIndex(matchIndex); - } else { + } + else + { // Otherwise, get the previous string in the domain list - if (domainIndex > 0) { + if (domainIndex > 0) + { SelectIndex(domainIndex - 1); - } else if (Wrap) { + } + else if (Wrap) + { SelectIndex(domainItems.Count - 1); } } } - + /// /// /// Updates the text in the up-down control to display the selected item. /// /// - protected override void UpdateEditText() { + protected override void UpdateEditText() + { Debug.Assert(!UserEdit, "UserEdit should be false"); // Defensive programming @@ -549,10 +636,11 @@ protected override void UpdateEditText() { // This is not a breaking change -- Even though this control previously autosized to hieght, // it didn't actually have an AutoSize property. The new AutoSize property enables the // smarter behavior. - internal override Size GetPreferredSizeCore(Size proposedConstraints) { + internal override Size GetPreferredSizeCore(Size proposedConstraints) + { int height = PreferredHeight; int width = LayoutUtils.OldGetLargestStringSizeInCollection(Font, Items).Width; - + // AdjuctWindowRect with our border, since textbox is borderless. width = SizeFromClientSize(width, height).Width + upDownButtons.Width; return new Size(width, height) + Padding.Size; @@ -564,30 +652,37 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) { /// Encapsulates a collection of objects for use by the /// class. /// - public class DomainUpDownItemCollection : ArrayList { + public class DomainUpDownItemCollection : ArrayList + { DomainUpDown owner; internal DomainUpDownItemCollection(DomainUpDown owner) - : base() { + : base() + { this.owner = owner; } /// /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public override object this[int index] { - get { + public override object this[int index] + { + get + { return base[index]; } - set { + set + { base[index] = value; - if (owner.SelectedIndex == index) { + if (owner.SelectedIndex == index) + { owner.SelectIndex(index); } - if (owner.Sorted) { + if (owner.Sorted) + { owner.SortDomainItems(); } } @@ -595,11 +690,13 @@ public override object this[int index] { /// /// - public override int Add(object item) { + public override int Add(object item) + { // Overridden to perform sorting after adding an item int ret = base.Add(item); - if (owner.Sorted) { + if (owner.Sorted) + { owner.SortDomainItems(); } return ret; @@ -607,28 +704,34 @@ public override int Add(object item) { /// /// - public override void Remove(object item) { + public override void Remove(object item) + { int index = IndexOf(item); - - if (index == -1) { + + if (index == -1) + { throw new ArgumentOutOfRangeException(nameof(item), item, string.Format(SR.InvalidArgument, nameof(item), item)); } - else { - RemoveAt(index); + else + { + RemoveAt(index); } } - + /// /// - public override void RemoveAt(int item) { + public override void RemoveAt(int item) + { // Overridden to update the domain index if neccessary base.RemoveAt(item); - if (item < owner.domainIndex) { + if (item < owner.domainIndex) + { // The item removed was before the currently selected item owner.SelectIndex(owner.domainIndex - 1); } - else if (item == owner.domainIndex) { + else if (item == owner.domainIndex) + { // The currently selected item was removed // owner.SelectIndex(-1); @@ -637,9 +740,11 @@ public override void RemoveAt(int item) { /// /// - public override void Insert(int index, object item) { + public override void Insert(int index, object item) + { base.Insert(index, item); - if (owner.Sorted) { + if (owner.Sorted) + { owner.SortDomainItems(); } } @@ -647,11 +752,15 @@ public override void Insert(int index, object item) { /// /// - private sealed class DomainUpDownItemCompare : IComparer { + private sealed class DomainUpDownItemCompare : IComparer + { - public int Compare(object p, object q) { - if (p == q) return 0; - if (p == null || q == null) { + public int Compare(object p, object q) + { + if (p == q) + return 0; + if (p == null || q == null) + { return 0; } @@ -661,45 +770,57 @@ public int Compare(object p, object q) { /// /// - [System.Runtime.InteropServices.ComVisible(true)] - public class DomainUpDownAccessibleObject : ControlAccessibleObject { + [System.Runtime.InteropServices.ComVisible(true)] + public class DomainUpDownAccessibleObject : ControlAccessibleObject + { private DomainItemListAccessibleObject itemList; - + /// /// - public DomainUpDownAccessibleObject(Control owner) : base(owner) { + public DomainUpDownAccessibleObject(Control owner) : base(owner) + { } /// /// Gets or sets the accessible name. /// - public override string Name { - get { + public override string Name + { + get + { string baseName = base.Name; return ((DomainUpDown)Owner).GetAccessibleName(baseName); } - set { + set + { base.Name = value; } } - - private DomainItemListAccessibleObject ItemList { - get { - if (itemList == null) { + + private DomainItemListAccessibleObject ItemList + { + get + { + if (itemList == null) + { itemList = new DomainItemListAccessibleObject(this); } return itemList; } } - - public override AccessibleRole Role { - get { + + public override AccessibleRole Role + { + get + { AccessibleRole role = Owner.AccessibleRole; - if (role != AccessibleRole.Default) { + if (role != AccessibleRole.Default) + { return role; } - else { + else + { return AccessibleRole.SpinButton; } } @@ -707,81 +828,99 @@ public override AccessibleRole Role { /// /// - public override AccessibleObject GetChild(int index) { - switch(index) { + public override AccessibleObject GetChild(int index) + { + switch (index) + { // TextBox child // case 0: return ((UpDownBase)Owner).TextBox.AccessibilityObject.Parent; - + // Up/down buttons // case 1: return ((UpDownBase)Owner).UpDownButtonsInternal.AccessibilityObject.Parent; - - case 2: + + case 2: return ItemList; } - + return null; } /// /// - public override int GetChildCount() { + public override int GetChildCount() + { return 3; } } - - internal class DomainItemListAccessibleObject : AccessibleObject { - + + internal class DomainItemListAccessibleObject : AccessibleObject + { + private DomainUpDownAccessibleObject parent; - - public DomainItemListAccessibleObject(DomainUpDownAccessibleObject parent) : base() { + + public DomainItemListAccessibleObject(DomainUpDownAccessibleObject parent) : base() + { this.parent = parent; } - - public override string Name { - get { + + public override string Name + { + get + { string baseName = base.Name; - if (baseName == null || baseName.Length == 0) { + if (baseName == null || baseName.Length == 0) + { return "Items"; } return baseName; } - set { + set + { base.Name = value; } } - - public override AccessibleObject Parent { - get { + + public override AccessibleObject Parent + { + get + { return parent; } } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { return AccessibleRole.List; } } - public override AccessibleStates State { - get { + public override AccessibleStates State + { + get + { return AccessibleStates.Invisible | AccessibleStates.Offscreen; } } - - public override AccessibleObject GetChild(int index) { - - if (index >=0 && index < GetChildCount()) { + + public override AccessibleObject GetChild(int index) + { + + if (index >= 0 && index < GetChildCount()) + { return new DomainItemAccessibleObject(((DomainUpDown)parent.Owner).Items[index].ToString(), this); } - + return null; } - public override int GetChildCount() { + public override int GetChildCount() + { return ((DomainUpDown)parent.Owner).Items.Count; } @@ -789,46 +928,59 @@ public override int GetChildCount() { /// /// - [System.Runtime.InteropServices.ComVisible(true)] - public class DomainItemAccessibleObject : AccessibleObject { + [System.Runtime.InteropServices.ComVisible(true)] + public class DomainItemAccessibleObject : AccessibleObject + { private string name; private DomainItemListAccessibleObject parent; - public DomainItemAccessibleObject(string name, AccessibleObject parent) : base() { + public DomainItemAccessibleObject(string name, AccessibleObject parent) : base() + { this.name = name; this.parent = (DomainItemListAccessibleObject)parent; } - public override string Name { - get { + public override string Name + { + get + { return name; } - set { + set + { name = value; } } - public override AccessibleObject Parent { - get { + public override AccessibleObject Parent + { + get + { return parent; } } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { return AccessibleRole.ListItem; } } - public override AccessibleStates State { - get { + public override AccessibleStates State + { + get + { return AccessibleStates.Selectable; } } - public override string Value { - get { + public override string Value + { + get + { return name; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DragEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DragEventArgs.cs index 7fdb0b19ea7..b8705c012e1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DragEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DragEventArgs.cs @@ -16,7 +16,8 @@ public class DragEventArgs : EventArgs /// /// Initializes a new instance of the class. /// - public DragEventArgs(IDataObject data, int keyState, int x, int y, DragDropEffects allowedEffect, DragDropEffects effect) { + public DragEventArgs(IDataObject data, int keyState, int x, int y, DragDropEffects allowedEffect, DragDropEffects effect) + { Data = data; KeyState = keyState; X = x; @@ -51,7 +52,7 @@ public DragEventArgs(IDataObject data, int keyState, int x, int y, DragDropEffec /// of the drag event. /// public DragDropEffects AllowedEffect { get; } - + /// /// Gets or sets which drag-and-drop operations are allowed by the target of the drag event. /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DrawItemState.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DrawItemState.cs index 87af23de3b1..7d0d8bee5f8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DrawItemState.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DrawItemState.cs @@ -34,7 +34,7 @@ public enum DrawItemState /// The item has focus. /// Focus = NativeMethods.ODS_FOCUS, - + /// /// The item is grayed. Only menu controls use this value. /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DrawListViewColumnHeaderEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DrawListViewColumnHeaderEventArgs.cs index 5e8da249fd8..3a4664ba47a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DrawListViewColumnHeaderEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DrawListViewColumnHeaderEventArgs.cs @@ -6,25 +6,25 @@ using System.Drawing; using System.Windows.Forms.VisualStyles; -namespace System.Windows.Forms +namespace System.Windows.Forms { /// /// This class contains the information a user needs to paint ListView /// column header (Details view only). /// - public class DrawListViewColumnHeaderEventArgs : EventArgs + public class DrawListViewColumnHeaderEventArgs : EventArgs { /// /// Creates a new DrawListViewColumnHeaderEventArgs with the given parameters. /// - public DrawListViewColumnHeaderEventArgs(Graphics graphics, Rectangle bounds, int columnIndex, + public DrawListViewColumnHeaderEventArgs(Graphics graphics, Rectangle bounds, int columnIndex, ColumnHeader header, ListViewItemStates state, Color foreColor, Color backColor, Font font) { Graphics = graphics; Bounds = bounds; ColumnIndex = columnIndex; - Header = header; + Header = header; State = state; ForeColor = foreColor; BackColor = backColor; @@ -70,7 +70,7 @@ public DrawListViewColumnHeaderEventArgs(Graphics graphics, Rectangle bounds, in /// Font used to render the header's text. /// public Font Font { get; } - + /// /// Causes the item do be drawn by the system instead of owner drawn. /// @@ -92,23 +92,23 @@ public void DrawBackground() { Graphics.FillRectangle(backBrush, Bounds); } - + // Draw the 3d header Rectangle r = Bounds; - + r.Width -= 1; r.Height -= 1; - + // Draw the dark border around the whole thing Graphics.DrawRectangle(SystemPens.ControlDarkDark, r); - + r.Width -= 1; r.Height -= 1; - + // Draw the light 3D border Graphics.DrawLine(SystemPens.ControlLightLight, r.X, r.Y, r.Right, r.Y); Graphics.DrawLine(SystemPens.ControlLightLight, r.X, r.Y, r.X, r.Bottom); - + // Draw the dark 3D Border Graphics.DrawLine(SystemPens.ControlDark, r.X + 1, r.Bottom, r.Right, r.Bottom); Graphics.DrawLine(SystemPens.ControlDark, r.Right, r.Y + 1, r.Right, r.Bottom); @@ -121,8 +121,8 @@ public void DrawBackground() public void DrawText() { HorizontalAlignment hAlign = Header.TextAlign; - TextFormatFlags flags = (hAlign == HorizontalAlignment.Left) ? TextFormatFlags.Left : - ((hAlign == HorizontalAlignment.Center) ? TextFormatFlags.HorizontalCenter : + TextFormatFlags flags = (hAlign == HorizontalAlignment.Left) ? TextFormatFlags.Left : + ((hAlign == HorizontalAlignment.Center) ? TextFormatFlags.HorizontalCenter : TextFormatFlags.Right); flags |= TextFormatFlags.WordEllipsis; @@ -135,7 +135,7 @@ public void DrawText() [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] // We want to measure the size of blank space so we don't have to localize it. public void DrawText(TextFormatFlags flags) { - string text = Header.Text; + string text = Header.Text; int padding = TextRenderer.MeasureText(" ", Font).Width; Rectangle newBounds = Rectangle.Inflate(Bounds, -padding, 0); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DrawListViewSubItemEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DrawListViewSubItemEventArgs.cs index 2e744a0ba8d..8462910a38d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DrawListViewSubItemEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DrawListViewSubItemEventArgs.cs @@ -118,9 +118,9 @@ public void DrawText() [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] // We want to measure the size of blank spaces o we don't have to localize it. public void DrawText(TextFormatFlags flags) { - string text = (ItemIndex == -1) ? Item.Text : SubItem.Text; - Font font = (ItemIndex == -1) ? Item.Font : SubItem.Font; - Color color = (ItemIndex == -1) ? Item.ForeColor : SubItem.ForeColor; + string text = (ItemIndex == -1) ? Item.Text : SubItem.Text; + Font font = (ItemIndex == -1) ? Item.Font : SubItem.Font; + Color color = (ItemIndex == -1) ? Item.ForeColor : SubItem.ForeColor; int padding = TextRenderer.MeasureText(" ", font).Width; Rectangle newBounds = Rectangle.Inflate(Bounds, -padding, 0); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DrawListViewSubItemEventHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DrawListViewSubItemEventHandler.cs index 7974078718e..15f46c25a11 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DrawListViewSubItemEventHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DrawListViewSubItemEventHandler.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms +namespace System.Windows.Forms { /// /// Handler for the ListView's DrawSubItem event. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DrawTreeNodeEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DrawTreeNodeEventArgs.cs index d297a45b014..a472d9f8423 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DrawTreeNodeEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DrawTreeNodeEventArgs.cs @@ -41,7 +41,7 @@ public DrawTreeNodeEventArgs(Graphics graphics, TreeNode node, Rectangle bounds, /// Miscellaneous state information. /// public TreeNodeStates State { get; } - + /// /// Causes the item do be drawn by the system instead of owner drawn. /// NOTE: In OwnerDrawText mode, setting this to true is same as calling DrawText. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DropSource.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DropSource.cs index d9bd1aac77d..9f5a9534f3a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DropSource.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DropSource.cs @@ -4,60 +4,68 @@ namespace System.Windows.Forms { - using System; + using System; - /// - internal class DropSource : UnsafeNativeMethods.IOleDropSource { + /// + internal class DropSource : UnsafeNativeMethods.IOleDropSource + { - private const int DragDropSDrop = 0x00040100; - private const int DragDropSCancel = 0x00040101; - private const int DragDropSUseDefaultCursors = 0x00040102; - - private ISupportOleDropSource peer; + private const int DragDropSDrop = 0x00040100; + private const int DragDropSCancel = 0x00040101; + private const int DragDropSUseDefaultCursors = 0x00040102; - public DropSource(ISupportOleDropSource peer ) { - if (peer == null) - throw new ArgumentNullException(nameof(peer)); - this.peer = peer; + private ISupportOleDropSource peer; + + public DropSource(ISupportOleDropSource peer) + { + if (peer == null) + throw new ArgumentNullException(nameof(peer)); + this.peer = peer; + } + + public int OleQueryContinueDrag(int fEscapePressed, int grfKeyState) + { + QueryContinueDragEventArgs qcdevent = null; + bool escapePressed = (fEscapePressed != 0); + DragAction action = DragAction.Continue; + if (escapePressed) + { + action = DragAction.Cancel; + } + else if ((grfKeyState & NativeMethods.MK_LBUTTON) == 0 + && (grfKeyState & NativeMethods.MK_RBUTTON) == 0 + && (grfKeyState & NativeMethods.MK_MBUTTON) == 0) + { + action = DragAction.Drop; } - public int OleQueryContinueDrag(int fEscapePressed, int grfKeyState) { - QueryContinueDragEventArgs qcdevent = null; - bool escapePressed = (fEscapePressed != 0); - DragAction action = DragAction.Continue; - if (escapePressed) { - action = DragAction.Cancel; - } - else if ((grfKeyState & NativeMethods.MK_LBUTTON) == 0 - && (grfKeyState & NativeMethods.MK_RBUTTON) == 0 - && (grfKeyState & NativeMethods.MK_MBUTTON) == 0) { - action = DragAction.Drop; - } - - qcdevent = new QueryContinueDragEventArgs(grfKeyState,escapePressed, action); - peer.OnQueryContinueDrag(qcdevent); - - int hr = 0; - - switch (qcdevent.Action) { - case DragAction.Drop: - hr = DragDropSDrop; - break; - case DragAction.Cancel: - hr = DragDropSCancel; - break; - } - - return hr; + qcdevent = new QueryContinueDragEventArgs(grfKeyState, escapePressed, action); + peer.OnQueryContinueDrag(qcdevent); + + int hr = 0; + + switch (qcdevent.Action) + { + case DragAction.Drop: + hr = DragDropSDrop; + break; + case DragAction.Cancel: + hr = DragDropSCancel; + break; } - public int OleGiveFeedback(int dwEffect) { - GiveFeedbackEventArgs gfbevent = new GiveFeedbackEventArgs((DragDropEffects) dwEffect, true); - peer.OnGiveFeedback(gfbevent); - if (gfbevent.UseDefaultCursors) { - return DragDropSUseDefaultCursors; - } - return 0; + return hr; + } + + public int OleGiveFeedback(int dwEffect) + { + GiveFeedbackEventArgs gfbevent = new GiveFeedbackEventArgs((DragDropEffects)dwEffect, true); + peer.OnGiveFeedback(gfbevent); + if (gfbevent.UseDefaultCursors) + { + return DragDropSUseDefaultCursors; } + return 0; } + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DropTarget.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DropTarget.cs index bf2df94a134..23cc478d95b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DropTarget.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DropTarget.cs @@ -10,104 +10,120 @@ namespace System.Windows.Forms { internal class DropTarget : UnsafeNativeMethods.IOleDropTarget { - private IDataObject lastDataObject = null; - private DragDropEffects lastEffect = DragDropEffects.None; - private IDropTarget owner; + private IDataObject lastDataObject = null; + private DragDropEffects lastEffect = DragDropEffects.None; + private IDropTarget owner; - public DropTarget(IDropTarget owner) { - Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "DropTarget created"); - this.owner = owner; - } + public DropTarget(IDropTarget owner) + { + Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "DropTarget created"); + this.owner = owner; + } #if DEBUG - ~DropTarget() { - Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "DropTarget destroyed"); - } + ~DropTarget() + { + Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "DropTarget destroyed"); + } #endif - private DragEventArgs CreateDragEventArgs(object pDataObj, int grfKeyState, NativeMethods.POINTL pt, int pdwEffect) { - - IDataObject data = null; + private DragEventArgs CreateDragEventArgs(object pDataObj, int grfKeyState, NativeMethods.POINTL pt, int pdwEffect) + { - if (pDataObj == null) { - data = lastDataObject; - } - else { - if (pDataObj is IDataObject) { - data = (IDataObject)pDataObj; - } - else if (pDataObj is IComDataObject) { - data = new DataObject(pDataObj); - } - else { - return null; // Unknown data object interface; we can't work with this so return null - } - } + IDataObject data = null; - DragEventArgs drgevent = new DragEventArgs(data, grfKeyState, pt.x, pt.y, (DragDropEffects)pdwEffect, lastEffect); - lastDataObject = data; - return drgevent; + if (pDataObj == null) + { + data = lastDataObject; } - - int UnsafeNativeMethods.IOleDropTarget.OleDragEnter(object pDataObj, int grfKeyState, - UnsafeNativeMethods.POINTSTRUCT pt, - ref int pdwEffect) { - Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "OleDragEnter recieved"); - NativeMethods.POINTL ptl = new NativeMethods.POINTL(); - ptl.x = pt.x; - ptl.y = pt.y; - Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "\t" + (ptl.x) + "," + (ptl.y)); - Debug.Assert(pDataObj != null, "OleDragEnter didn't give us a valid data object."); - DragEventArgs drgevent = CreateDragEventArgs(pDataObj, grfKeyState, ptl, pdwEffect); - - if (drgevent != null) { - owner.OnDragEnter(drgevent); - pdwEffect = (int)drgevent.Effect; - lastEffect = drgevent.Effect; + else + { + if (pDataObj is IDataObject) + { + data = (IDataObject)pDataObj; + } + else if (pDataObj is IComDataObject) + { + data = new DataObject(pDataObj); } - else { - pdwEffect = (int)DragDropEffects.None; + else + { + return null; // Unknown data object interface; we can't work with this so return null } - return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleDropTarget.OleDragOver(int grfKeyState, UnsafeNativeMethods.POINTSTRUCT pt, ref int pdwEffect) { - Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "OleDragOver recieved"); - NativeMethods.POINTL ptl = new NativeMethods.POINTL(); - ptl.x = pt.x; - ptl.y = pt.y; - Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "\t" + (ptl.x) + "," + (ptl.y)); - DragEventArgs drgevent = CreateDragEventArgs(null, grfKeyState, ptl, pdwEffect); - owner.OnDragOver(drgevent); + + DragEventArgs drgevent = new DragEventArgs(data, grfKeyState, pt.x, pt.y, (DragDropEffects)pdwEffect, lastEffect); + lastDataObject = data; + return drgevent; + } + + int UnsafeNativeMethods.IOleDropTarget.OleDragEnter(object pDataObj, int grfKeyState, + UnsafeNativeMethods.POINTSTRUCT pt, + ref int pdwEffect) + { + Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "OleDragEnter recieved"); + NativeMethods.POINTL ptl = new NativeMethods.POINTL(); + ptl.x = pt.x; + ptl.y = pt.y; + Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "\t" + (ptl.x) + "," + (ptl.y)); + Debug.Assert(pDataObj != null, "OleDragEnter didn't give us a valid data object."); + DragEventArgs drgevent = CreateDragEventArgs(pDataObj, grfKeyState, ptl, pdwEffect); + + if (drgevent != null) + { + owner.OnDragEnter(drgevent); pdwEffect = (int)drgevent.Effect; lastEffect = drgevent.Effect; - return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleDropTarget.OleDragLeave() { - Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "OleDragLeave recieved"); - owner.OnDragLeave(EventArgs.Empty); - return NativeMethods.S_OK; + else + { + pdwEffect = (int)DragDropEffects.None; } - int UnsafeNativeMethods.IOleDropTarget.OleDrop(object pDataObj, int grfKeyState, UnsafeNativeMethods.POINTSTRUCT pt, ref int pdwEffect) { - Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "OleDrop recieved"); - NativeMethods.POINTL ptl = new NativeMethods.POINTL(); - ptl.x = pt.x; - ptl.y = pt.y; - Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "\t" + (ptl.x) + "," + (ptl.y)); - DragEventArgs drgevent = CreateDragEventArgs(pDataObj, grfKeyState, ptl, pdwEffect); - - if (drgevent != null) { - owner.OnDragDrop(drgevent); - pdwEffect = (int)drgevent.Effect; - } - else { - pdwEffect = (int)DragDropEffects.None; - } - - lastEffect = DragDropEffects.None; - lastDataObject = null; - return NativeMethods.S_OK; + return NativeMethods.S_OK; + } + int UnsafeNativeMethods.IOleDropTarget.OleDragOver(int grfKeyState, UnsafeNativeMethods.POINTSTRUCT pt, ref int pdwEffect) + { + Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "OleDragOver recieved"); + NativeMethods.POINTL ptl = new NativeMethods.POINTL(); + ptl.x = pt.x; + ptl.y = pt.y; + Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "\t" + (ptl.x) + "," + (ptl.y)); + DragEventArgs drgevent = CreateDragEventArgs(null, grfKeyState, ptl, pdwEffect); + owner.OnDragOver(drgevent); + pdwEffect = (int)drgevent.Effect; + lastEffect = drgevent.Effect; + return NativeMethods.S_OK; + } + int UnsafeNativeMethods.IOleDropTarget.OleDragLeave() + { + Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "OleDragLeave recieved"); + owner.OnDragLeave(EventArgs.Empty); + return NativeMethods.S_OK; + } + int UnsafeNativeMethods.IOleDropTarget.OleDrop(object pDataObj, int grfKeyState, UnsafeNativeMethods.POINTSTRUCT pt, ref int pdwEffect) + { + Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "OleDrop recieved"); + NativeMethods.POINTL ptl = new NativeMethods.POINTL(); + ptl.x = pt.x; + ptl.y = pt.y; + Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "\t" + (ptl.x) + "," + (ptl.y)); + DragEventArgs drgevent = CreateDragEventArgs(pDataObj, grfKeyState, ptl, pdwEffect); + + if (drgevent != null) + { + owner.OnDragDrop(drgevent); + pdwEffect = (int)drgevent.Effect; } + else + { + pdwEffect = (int)DragDropEffects.None; + } + + lastEffect = DragDropEffects.None; + lastDataObject = null; + return NativeMethods.S_OK; } + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorBlinkStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorBlinkStyle.cs index 8c78ff612c8..f01014e3029 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorBlinkStyle.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorBlinkStyle.cs @@ -16,14 +16,14 @@ public enum ErrorBlinkStyle /// in this case, the user might not know that there is a new error. /// BlinkIfDifferentError, - + /// /// Blink the error icon when the error is first displayed, or when /// a new error description string is set for the control and the /// error icon is already displayed. /// AlwaysBlink, - + /// /// Never blink the error icon. /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs index c0b94533ee8..33f0f71dbc8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Threading; using System.Runtime.InteropServices; using System.ComponentModel; @@ -14,7 +15,7 @@ namespace System.Windows.Forms { using System.Drawing; using System.Windows.Forms; using System.Windows.Forms.Design; - using System.Windows.Forms.Internal; + using System.Windows.Forms.Internal; using System.Runtime.Versioning; /// @@ -32,7 +33,8 @@ namespace System.Windows.Forms { ComplexBindingProperties(nameof(DataSource), nameof(DataMember)), SRDescription(nameof(SR.DescriptionErrorProvider)) ] - public class ErrorProvider : Component, IExtenderProvider, ISupportInitialize { + public class ErrorProvider : Component, IExtenderProvider, ISupportInitialize + { // // FIELDS @@ -67,7 +69,7 @@ public class ErrorProvider : Component, IExtenderProvider, ISupportInitialize { private EventHandler onRightToLeftChanged; private bool rightToLeft = false; - + private object userData; // @@ -77,21 +79,25 @@ public class ErrorProvider : Component, IExtenderProvider, ISupportInitialize { /// /// Default constructor. /// - public ErrorProvider() { + public ErrorProvider() + { icon = DefaultIcon; blinkRate = defaultBlinkRate; blinkStyle = defaultBlinkStyle; currentChanged = new EventHandler(ErrorManager_CurrentChanged); } - public ErrorProvider(ContainerControl parentControl) : this() { + public ErrorProvider(ContainerControl parentControl) : this() + { this.parentControl = parentControl; propChangedEvent = new EventHandler(ParentControl_BindingContextChanged); parentControl.BindingContextChanged += propChangedEvent; } - public ErrorProvider(IContainer container) : this() { - if (container == null) { + public ErrorProvider(IContainer container) : this() + { + if (container == null) + { throw new ArgumentNullException(nameof(container)); } @@ -102,18 +108,22 @@ public ErrorProvider(IContainer container) : this() { // PROPERTIES // - public override ISite Site { - set { + public override ISite Site + { + set + { base.Site = value; if (value == null) return; IDesignerHost host = value.GetService(typeof(IDesignerHost)) as IDesignerHost; - if (host != null) { + if (host != null) + { IComponent baseComp = host.RootComponent; - if (baseComp is ContainerControl) { - this.ContainerControl = (ContainerControl) baseComp; + if (baseComp is ContainerControl) + { + this.ContainerControl = (ContainerControl)baseComp; } } } @@ -127,30 +137,38 @@ public override ISite Site { DefaultValue(defaultBlinkStyle), SRDescription(nameof(SR.ErrorProviderBlinkStyleDescr)) ] - public ErrorBlinkStyle BlinkStyle { - get { - if (blinkRate == 0) { + public ErrorBlinkStyle BlinkStyle + { + get + { + if (blinkRate == 0) + { return ErrorBlinkStyle.NeverBlink; } return blinkStyle; } - set { + set + { //valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)ErrorBlinkStyle.BlinkIfDifferentError, (int)ErrorBlinkStyle.NeverBlink)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)ErrorBlinkStyle.BlinkIfDifferentError, (int)ErrorBlinkStyle.NeverBlink)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ErrorBlinkStyle)); } // If the blinkRate == 0, then set blinkStyle = neverBlink // - if (this.blinkRate == 0) { + if (this.blinkRate == 0) + { value = ErrorBlinkStyle.NeverBlink; } - if (this.blinkStyle == value) { + if (this.blinkStyle == value) + { return; } - if (value == ErrorBlinkStyle.AlwaysBlink) { + if (value == ErrorBlinkStyle.AlwaysBlink) + { // we need to startBlinking on all the controlItems // in our items hashTable. this.showIcon = true; @@ -160,14 +178,17 @@ public ErrorBlinkStyle BlinkStyle { w.StartBlinking(); } } - else if (blinkStyle == ErrorBlinkStyle.AlwaysBlink) { + else if (blinkStyle == ErrorBlinkStyle.AlwaysBlink) + { // we need to stop blinking... this.blinkStyle = value; - foreach (ErrorWindow w in windows.Values) { + foreach (ErrorWindow w in windows.Values) + { w.StopBlinking(); } } - else { + else + { this.blinkStyle = value; } } @@ -183,12 +204,16 @@ public ErrorBlinkStyle BlinkStyle { SRCategory(nameof(SR.CatData)), SRDescription(nameof(SR.ErrorProviderContainerControlDescr)) ] - public ContainerControl ContainerControl { - get { + public ContainerControl ContainerControl + { + get + { return parentControl; } - set { - if (parentControl != value) { + set + { + if (parentControl != value) + { if (parentControl != null) parentControl.BindingContextChanged -= propChangedEvent; @@ -213,14 +238,18 @@ public ContainerControl ContainerControl { DefaultValue(false), SRDescription(nameof(SR.ControlRightToLeftDescr)) ] - public virtual bool RightToLeft { - get { + public virtual bool RightToLeft + { + get + { return rightToLeft; } - set { - if (value != rightToLeft) { + set + { + if (value != rightToLeft) + { rightToLeft = value; OnRightToLeftChanged(EventArgs.Empty); } @@ -228,10 +257,11 @@ public virtual bool RightToLeft { } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnRightToLeftChangedDescr))] - public event EventHandler RightToLeftChanged { + public event EventHandler RightToLeftChanged + { add => onRightToLeftChanged += value; remove => onRightToLeftChanged -= value; - } + } /// /// User defined data associated with the control. @@ -244,16 +274,20 @@ public event EventHandler RightToLeftChanged { DefaultValue(null), TypeConverter(typeof(StringConverter)), ] - public object Tag { - get { + public object Tag + { + get + { return userData; } - set { + set + { userData = value; } } - private void Set_ErrorManager(object newDataSource, string newDataMember, bool force) { + private void Set_ErrorManager(object newDataSource, string newDataMember, bool force) + { if (inSetErrorManager) return; inSetErrorManager = true; @@ -274,20 +308,24 @@ private void Set_ErrorManager(object newDataSource, string newDataMember, bool f this.dataSource = newDataSource; this.dataMember = newDataMember; - if (initializing) { + if (initializing) + { setErrorManagerOnEndInit = true; } - else { + else + { // unwire the errorManager: // UnwireEvents(errorManager); // get the new errorManager // - if (parentControl != null && this.dataSource != null && parentControl.BindingContext != null) { + if (parentControl != null && this.dataSource != null && parentControl.BindingContext != null) + { errorManager = parentControl.BindingContext[this.dataSource, this.dataMember]; } - else { + else + { errorManager = null; } @@ -300,7 +338,9 @@ private void Set_ErrorManager(object newDataSource, string newDataMember, bool f if (errorManager != null) UpdateBinding(); } - } finally { + } + finally + { inSetErrorManager = false; } } @@ -314,17 +354,23 @@ private void Set_ErrorManager(object newDataSource, string newDataMember, bool f AttributeProvider(typeof(IListSource)), SRDescription(nameof(SR.ErrorProviderDataSourceDescr)) ] - public object DataSource { - get { + public object DataSource + { + get + { return dataSource; } - set { - if (parentControl != null && value != null && !string.IsNullOrEmpty(this.dataMember)) { + set + { + if (parentControl != null && value != null && !string.IsNullOrEmpty(this.dataMember)) + { // Let's check if the datamember exists in the new data source - try { + try + { errorManager = parentControl.BindingContext[value, this.dataMember]; } - catch (ArgumentException) { + catch (ArgumentException) + { // The data member doesn't exist in the data source, so set it to null this.dataMember = string.Empty; } @@ -334,7 +380,8 @@ public object DataSource { } } - private bool ShouldSerializeDataSource() { + private bool ShouldSerializeDataSource() + { return (dataSource != null); } @@ -347,104 +394,129 @@ private bool ShouldSerializeDataSource() { Editor("System.Windows.Forms.Design.DataMemberListEditor, " + AssemblyRef.SystemDesign, typeof(System.Drawing.Design.UITypeEditor)), SRDescription(nameof(SR.ErrorProviderDataMemberDescr)) ] - public string DataMember { - get { + public string DataMember + { + get + { return dataMember; } - set { - if (value == null) value = string.Empty; + set + { + if (value == null) + value = string.Empty; Set_ErrorManager(this.DataSource, value, false); } } - private bool ShouldSerializeDataMember() { + private bool ShouldSerializeDataMember() + { return (dataMember != null && dataMember.Length != 0); } - public void BindToDataAndErrors(object newDataSource, string newDataMember) { + public void BindToDataAndErrors(object newDataSource, string newDataMember) + { Set_ErrorManager(newDataSource, newDataMember, false); } - private void WireEvents(BindingManagerBase listManager) { - if (listManager != null) { + private void WireEvents(BindingManagerBase listManager) + { + if (listManager != null) + { listManager.CurrentChanged += currentChanged; listManager.BindingComplete += new BindingCompleteEventHandler(this.ErrorManager_BindingComplete); CurrencyManager currManager = listManager as CurrencyManager; - if (currManager != null) { + if (currManager != null) + { currManager.ItemChanged += new ItemChangedEventHandler(this.ErrorManager_ItemChanged); currManager.Bindings.CollectionChanged += new CollectionChangeEventHandler(this.ErrorManager_BindingsChanged); } } } - private void UnwireEvents(BindingManagerBase listManager) { - if (listManager != null) { + private void UnwireEvents(BindingManagerBase listManager) + { + if (listManager != null) + { listManager.CurrentChanged -= currentChanged; listManager.BindingComplete -= new BindingCompleteEventHandler(this.ErrorManager_BindingComplete); CurrencyManager currManager = listManager as CurrencyManager; - if (currManager != null) { + if (currManager != null) + { currManager.ItemChanged -= new ItemChangedEventHandler(this.ErrorManager_ItemChanged); currManager.Bindings.CollectionChanged -= new CollectionChangeEventHandler(this.ErrorManager_BindingsChanged); } } } - private void ErrorManager_BindingComplete(object sender, BindingCompleteEventArgs e) { + private void ErrorManager_BindingComplete(object sender, BindingCompleteEventArgs e) + { Binding binding = e.Binding; - if (binding != null && binding.Control != null) { + if (binding != null && binding.Control != null) + { SetError(binding.Control, (e.ErrorText == null ? string.Empty : e.ErrorText)); } } - private void ErrorManager_BindingsChanged(object sender, CollectionChangeEventArgs e) { + private void ErrorManager_BindingsChanged(object sender, CollectionChangeEventArgs e) + { ErrorManager_CurrentChanged(errorManager, e); } - private void ParentControl_BindingContextChanged(object sender, EventArgs e) { + private void ParentControl_BindingContextChanged(object sender, EventArgs e) + { Set_ErrorManager(this.DataSource, this.DataMember, true); } // Work around... we should figure out if errors changed automatically. - public void UpdateBinding() { + public void UpdateBinding() + { ErrorManager_CurrentChanged(errorManager, EventArgs.Empty); } - private void ErrorManager_ItemChanged(object sender, ItemChangedEventArgs e) { + private void ErrorManager_ItemChanged(object sender, ItemChangedEventArgs e) + { BindingsCollection errBindings = errorManager.Bindings; int bindingsCount = errBindings.Count; // If the list became empty then reset the errors - if (e.Index == -1 && errorManager.Count == 0) { - for (int j = 0; j < bindingsCount; j++) { - if (errBindings[j].Control != null) { + if (e.Index == -1 && errorManager.Count == 0) + { + for (int j = 0; j < bindingsCount; j++) + { + if (errBindings[j].Control != null) + { // ...ignore everything but bindings to Controls SetError(errBindings[j].Control, ""); } } } - else { + else + { ErrorManager_CurrentChanged(sender, e); } } - private void ErrorManager_CurrentChanged(object sender, EventArgs e) { + private void ErrorManager_CurrentChanged(object sender, EventArgs e) + { Debug.Assert(sender == errorManager, "who else can send us messages?"); // flush the old list // // items.Clear(); - if (errorManager.Count == 0) { + if (errorManager.Count == 0) + { return; } object value = errorManager.Current; - if ( !(value is IDataErrorInfo)) { + if (!(value is IDataErrorInfo)) + { return; } @@ -455,7 +527,8 @@ private void ErrorManager_CurrentChanged(object sender, EventArgs e) { // that the error that we get is the same error. then we want to // show the error and not blink ) // - foreach (ControlItem ctl in items.Values) { + foreach (ControlItem ctl in items.Values) + { ctl.BlinkPhase = 0; } @@ -463,29 +536,35 @@ private void ErrorManager_CurrentChanged(object sender, EventArgs e) { // Hashtable controlError = new Hashtable(bindingsCount); - for (int j = 0; j < bindingsCount; j++) { + for (int j = 0; j < bindingsCount; j++) + { // Ignore everything but bindings to Controls - if (errBindings[j].Control == null) { + if (errBindings[j].Control == null) + { continue; } Binding dataBinding = errBindings[j]; - string error = ((IDataErrorInfo) value)[dataBinding.BindingMemberInfo.BindingField]; + string error = ((IDataErrorInfo)value)[dataBinding.BindingMemberInfo.BindingField]; - if (error == null) { + if (error == null) + { error = string.Empty; } string outputError = string.Empty; if (controlError.Contains(dataBinding.Control)) - outputError = (string) controlError[dataBinding.Control]; + outputError = (string)controlError[dataBinding.Control]; // Utilize the error string without including the field name. - if (string.IsNullOrEmpty(outputError)) { + if (string.IsNullOrEmpty(outputError)) + { outputError = error; - } else { + } + else + { outputError = string.Concat(outputError, "\r\n", error); } @@ -493,9 +572,10 @@ private void ErrorManager_CurrentChanged(object sender, EventArgs e) { } IEnumerator enumerator = controlError.GetEnumerator(); - while (enumerator.MoveNext()) { - DictionaryEntry entry = (DictionaryEntry) enumerator.Current; - SetError((Control) entry.Key, (string) entry.Value); + while (enumerator.MoveNext()) + { + DictionaryEntry entry = (DictionaryEntry)enumerator.Current; + SetError((Control)entry.Key, (string)entry.Value); } } @@ -508,12 +588,16 @@ private void ErrorManager_CurrentChanged(object sender, EventArgs e) { SRDescription(nameof(SR.ErrorProviderBlinkRateDescr)), RefreshProperties(RefreshProperties.Repaint) ] - public int BlinkRate { - get { + public int BlinkRate + { + get + { return blinkRate; } - set { - if (value < 0) { + set + { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(BlinkRate), value, SR.BlinkRateMustBeZeroOrMore); } blinkRate = value; @@ -526,11 +610,16 @@ public int BlinkRate { /// /// Demand load and cache the default icon. /// - static Icon DefaultIcon { - get { - if (defaultIcon == null) { - lock (typeof(ErrorProvider)) { - if (defaultIcon == null) { + static Icon DefaultIcon + { + get + { + if (defaultIcon == null) + { + lock (typeof(ErrorProvider)) + { + if (defaultIcon == null) + { defaultIcon = new Icon(typeof(ErrorProvider), "Error"); } } @@ -549,11 +638,14 @@ static Icon DefaultIcon { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ErrorProviderIconDescr)) ] - public Icon Icon { - get { + public Icon Icon + { + get + { return icon; } - set { + set + { if (value == null) throw new ArgumentNullException(nameof(value)); icon = value; @@ -568,10 +660,12 @@ public Icon Icon { /// /// Create the icon region on demand. /// - internal IconRegion Region { - - - get { + internal IconRegion Region + { + + + get + { if (region == null) region = new IconRegion(Icon); return region; @@ -583,15 +677,18 @@ internal IconRegion Region { // // Begin bulk member initialization - deferring binding to data source until EndInit is reached - void ISupportInitialize.BeginInit() { + void ISupportInitialize.BeginInit() + { initializing = true; } // End bulk member initialization by binding to data source - private void EndInitCore() { + private void EndInitCore() + { initializing = false; - if (setErrorManagerOnEndInit) { + if (setErrorManagerOnEndInit) + { setErrorManagerOnEndInit = false; Set_ErrorManager(this.DataSource, this.DataMember, true); } @@ -601,13 +698,16 @@ private void EndInitCore() { // If DataSource is still initializing, hook its Initialized event and wait for it to signal completion. // If DataSource is already initialized, just go ahead and complete our initialization now. // - void ISupportInitialize.EndInit() { + void ISupportInitialize.EndInit() + { ISupportInitializeNotification dsInit = (this.DataSource as ISupportInitializeNotification); - if (dsInit != null && !dsInit.IsInitialized) { + if (dsInit != null && !dsInit.IsInitialized) + { dsInit.Initialized += new EventHandler(DataSource_Initialized); } - else { + else + { EndInitCore(); } } @@ -616,13 +716,15 @@ void ISupportInitialize.EndInit() { // This situation can arise if the call to the DataSource's EndInit() method comes after the call to the // BindingSource's EndInit() method (since code-generated ordering of these calls is non-deterministic). // - private void DataSource_Initialized(object sender, EventArgs e) { + private void DataSource_Initialized(object sender, EventArgs e) + { ISupportInitializeNotification dsInit = (this.DataSource as ISupportInitializeNotification); Debug.Assert(dsInit != null, "ErrorProvider: ISupportInitializeNotification.Initialized event received, but current DataSource does not support ISupportInitializeNotification!"); Debug.Assert(dsInit.IsInitialized, "ErrorProvider: DataSource sent ISupportInitializeNotification.Initialized event but before it had finished initializing."); - if (dsInit != null) { + if (dsInit != null) + { dsInit.Initialized -= new EventHandler(DataSource_Initialized); } @@ -632,15 +734,19 @@ private void DataSource_Initialized(object sender, EventArgs e) { /// /// Clears all errors being tracked by this error provider, ie. undoes all previous calls to SetError. /// - public void Clear() { + public void Clear() + { ErrorWindow[] w = new ErrorWindow[windows.Values.Count]; windows.Values.CopyTo(w, 0); - for (int i = 0; i < w.Length; i++) { + for (int i = 0; i < w.Length; i++) + { w[i].Dispose(); } windows.Clear(); - foreach (ControlItem item in items.Values) { - if (item != null) { + foreach (ControlItem item in items.Values) + { + if (item != null) + { item.Dispose(); } } @@ -650,7 +756,8 @@ public void Clear() { /// /// Returns whether a control can be extended. /// - public bool CanExtend(object extendee) { + public bool CanExtend(object extendee) + { return extendee is Control && !(extendee is Form) && !(extendee is ToolBar); } @@ -658,8 +765,10 @@ public bool CanExtend(object extendee) { /// Release any resources that this component is using. After calling Dispose, /// the component should no longer be used. /// - protected override void Dispose(bool disposing) { - if (disposing) { + protected override void Dispose(bool disposing) + { + if (disposing) + { Clear(); DisposeRegion(); UnwireEvents(errorManager); @@ -670,8 +779,10 @@ protected override void Dispose(bool disposing) { /// /// Helper to dispose the cached icon region. /// - void DisposeRegion() { - if (region != null) { + void DisposeRegion() + { + if (region != null) + { region.Dispose(); region = null; } @@ -680,11 +791,13 @@ void DisposeRegion() { /// /// Helper to make sure we have allocated a control item for this control. /// - private ControlItem EnsureControlItem(Control control) { + private ControlItem EnsureControlItem(Control control) + { if (control == null) throw new ArgumentNullException(nameof(control)); ControlItem item = (ControlItem)items[control]; - if (item == null) { + if (item == null) + { item = new ControlItem(this, control, (IntPtr)(++itemIdCounter)); items[control] = item; } @@ -694,9 +807,11 @@ private ControlItem EnsureControlItem(Control control) { /// /// Helper to make sure we have allocated an error window for this control. /// - internal ErrorWindow EnsureErrorWindow(Control parent) { + internal ErrorWindow EnsureErrorWindow(Control parent) + { ErrorWindow window = (ErrorWindow)windows[parent]; - if (window == null) { + if (window == null) + { window = new ErrorWindow(this, parent); windows[parent] = window; } @@ -712,7 +827,8 @@ internal ErrorWindow EnsureErrorWindow(Control parent) { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ErrorProviderErrorDescr)) ] - public string GetError(Control control) { + public string GetError(Control control) + { return EnsureControlItem(control).Error; } @@ -725,7 +841,8 @@ public string GetError(Control control) { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ErrorProviderIconAlignmentDescr)) ] - public ErrorIconAlignment GetIconAlignment(Control control) { + public ErrorIconAlignment GetIconAlignment(Control control) + { return EnsureControlItem(control).IconAlignment; } @@ -738,49 +855,57 @@ public ErrorIconAlignment GetIconAlignment(Control control) { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ErrorProviderIconPaddingDescr)) ] - public int GetIconPadding(Control control) { + public int GetIconPadding(Control control) + { return EnsureControlItem(control).IconPadding; } - private void ResetIcon() { + private void ResetIcon() + { Icon = DefaultIcon; } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnRightToLeftChanged(EventArgs e) { + protected virtual void OnRightToLeftChanged(EventArgs e) + { foreach (ErrorWindow w in windows.Values) { w.Update(false); } - - if (onRightToLeftChanged != null) { - onRightToLeftChanged(this, e); + + if (onRightToLeftChanged != null) + { + onRightToLeftChanged(this, e); } } /// /// Sets the error description string for the specified control. /// - public void SetError(Control control, string value) { + public void SetError(Control control, string value) + { EnsureControlItem(control).Error = value; } /// /// Sets where the error icon should be placed relative to the control. /// - public void SetIconAlignment(Control control, ErrorIconAlignment value) { + public void SetIconAlignment(Control control, ErrorIconAlignment value) + { EnsureControlItem(control).IconAlignment = value; } /// /// Sets the amount of extra space to leave next to the error icon. /// - public void SetIconPadding(Control control, int padding) { + public void SetIconPadding(Control control, int padding) + { EnsureControlItem(control).IconPadding = padding; } - private bool ShouldSerializeIcon() { + private bool ShouldSerializeIcon() + { return Icon != DefaultIcon; } @@ -792,7 +917,8 @@ private bool ShouldSerializeIcon() { /// rectangle associated with each error icon being displayed is added as a /// tool to the tooltip window. /// - internal class ErrorWindow : NativeWindow { + internal class ErrorWindow : NativeWindow + { // // FIELDS @@ -804,8 +930,8 @@ internal class ErrorWindow : NativeWindow { Rectangle windowBounds = Rectangle.Empty; System.Windows.Forms.Timer timer; NativeWindow tipWindow; - - DeviceContext mirrordc= null; + + DeviceContext mirrordc = null; Size mirrordcExtent = Size.Empty; Point mirrordcOrigin = Point.Empty; DeviceContextMapMode mirrordcMode = DeviceContextMapMode.Text; @@ -817,7 +943,8 @@ internal class ErrorWindow : NativeWindow { /// /// Construct an error window for this provider and control parent. /// - public ErrorWindow(ErrorProvider provider, Control parent) { + public ErrorWindow(ErrorProvider provider, Control parent) + { this.provider = provider; this.parent = parent; } @@ -829,7 +956,8 @@ public ErrorWindow(ErrorProvider provider, Control parent) { /// /// This is called when a control would like to show an error icon. /// - public void Add(ControlItem item) { + public void Add(ControlItem item) + { items.Add(item); if (!EnsureCreated()) { @@ -850,15 +978,18 @@ public void Add(ControlItem item) { /// /// Called to get rid of any resources the Object may have. /// - public void Dispose() { + public void Dispose() + { EnsureDestroyed(); } /// /// Make sure the error window is created, and the tooltip window is created. /// - bool EnsureCreated() { - if (Handle == IntPtr.Zero) { + bool EnsureCreated() + { + if (Handle == IntPtr.Zero) + { if (!parent.IsHandleCreated) { return false; @@ -896,12 +1027,15 @@ bool EnsureCreated() { /// /// Destroy the timer, toolwindow, and the error window itself. /// - void EnsureDestroyed() { - if (timer != null) { + void EnsureDestroyed() + { + if (timer != null) + { timer.Dispose(); timer = null; } - if (tipWindow != null) { + if (tipWindow != null) + { tipWindow.DestroyHandle(); tipWindow = null; } @@ -919,13 +1053,15 @@ void EnsureDestroyed() { NativeMethods.SWP_HIDEWINDOW | NativeMethods.SWP_NOSIZE | NativeMethods.SWP_NOMOVE); - if (parent != null) { + if (parent != null) + { parent.Invalidate(true); } DestroyHandle(); Debug.Assert(mirrordc == null, "Why is mirrordc non-null?"); - if (mirrordc != null) { + if (mirrordc != null) + { mirrordc.Dispose(); } } @@ -941,12 +1077,14 @@ void EnsureDestroyed() { /// To work around that we create our own mirrored dc when we need to. /// /// - void CreateMirrorDC(IntPtr hdc, int originOffset) { + void CreateMirrorDC(IntPtr hdc, int originOffset) + { Debug.Assert(mirrordc == null, "Why is mirrordc non-null? Did you not call RestoreMirrorDC?"); mirrordc = DeviceContext.FromHdc(hdc); - if (parent.IsMirrored && mirrordc != null) { + if (parent.IsMirrored && mirrordc != null) + { mirrordc.SaveHdc(); mirrordcExtent = mirrordc.ViewportExtent; mirrordcOrigin = mirrordc.ViewportOrigin; @@ -957,9 +1095,11 @@ void CreateMirrorDC(IntPtr hdc, int originOffset) { } } - void RestoreMirrorDC() { - - if (parent.IsMirrored && mirrordc != null) { + void RestoreMirrorDC() + { + + if (parent.IsMirrored && mirrordc != null) + { mirrordc.ViewportExtent = mirrordcExtent; mirrordc.ViewportOrigin = mirrordcOrigin; mirrordc.SetMapMode(mirrordcMode); @@ -967,7 +1107,7 @@ void RestoreMirrorDC() { mirrordc.Dispose(); } - mirrordc= null; + mirrordc = null; mirrordcExtent = Size.Empty; mirrordcOrigin = Point.Empty; mirrordcMode = DeviceContextMapMode.Text; @@ -977,57 +1117,72 @@ void RestoreMirrorDC() { /// This is called when the error window needs to paint. We paint each icon at its /// correct location. /// - void OnPaint(ref Message m) { + void OnPaint(ref Message m) + { NativeMethods.PAINTSTRUCT ps = new NativeMethods.PAINTSTRUCT(); IntPtr hdc = UnsafeNativeMethods.BeginPaint(new HandleRef(this, Handle), ref ps); - try { + try + { CreateMirrorDC(hdc, windowBounds.Width - 1); - try { - for (int i = 0; i < items.Count; i++) { + try + { + for (int i = 0; i < items.Count; i++) + { ControlItem item = (ControlItem)items[i]; Rectangle bounds = item.GetIconBounds(provider.Region.Size); SafeNativeMethods.DrawIconEx(new HandleRef(this, mirrordc.Hdc), bounds.X - windowBounds.X, bounds.Y - windowBounds.Y, new HandleRef(provider.Region, provider.Region.IconHandle), bounds.Width, bounds.Height, 0, NativeMethods.NullHandleRef, NativeMethods.DI_NORMAL); } } - finally { + finally + { RestoreMirrorDC(); } - } - finally { + } + finally + { UnsafeNativeMethods.EndPaint(new HandleRef(this, Handle), ref ps); } } - protected override void OnThreadException(Exception e) { + protected override void OnThreadException(Exception e) + { Application.OnThreadException(e); } /// /// This is called when an error icon is flashing, and the view needs to be updatd. /// - void OnTimer(object sender, EventArgs e) { + void OnTimer(object sender, EventArgs e) + { int blinkPhase = 0; - for (int i = 0; i < items.Count; i++) { + for (int i = 0; i < items.Count; i++) + { blinkPhase += ((ControlItem)items[i]).BlinkPhase; } - if (blinkPhase == 0 && provider.BlinkStyle != ErrorBlinkStyle.AlwaysBlink) { + if (blinkPhase == 0 && provider.BlinkStyle != ErrorBlinkStyle.AlwaysBlink) + { Debug.Assert(timer != null); timer.Stop(); } Update(true /*timerCaused*/); } - private void OnToolTipVisibilityChanging(System.IntPtr id, bool toolTipShown) { - for (int i = 0; i < items.Count; i++) { - if (((ControlItem)items[i]).Id == id) { + private void OnToolTipVisibilityChanging(System.IntPtr id, bool toolTipShown) + { + for (int i = 0; i < items.Count; i++) + { + if (((ControlItem)items[i]).Id == id) + { ((ControlItem)items[i]).ToolTipShown = toolTipShown; } } #if DEBUG int shownTooltips = 0; - for (int j = 0; j < items.Count; j++) { - if (((ControlItem)items[j]).ToolTipShown) { + for (int j = 0; j < items.Count; j++) + { + if (((ControlItem)items[j]).ToolTipShown) + { shownTooltips++; } } @@ -1038,10 +1193,12 @@ private void OnToolTipVisibilityChanging(System.IntPtr id, bool toolTipShown) { /// /// This is called when a control no longer needs to display an error icon. /// - public void Remove(ControlItem item) { + public void Remove(ControlItem item) + { items.Remove(item); - if (tipWindow != null) { + if (tipWindow != null) + { NativeMethods.TOOLINFO_T toolInfo = new NativeMethods.TOOLINFO_T(); toolInfo.cbSize = Marshal.SizeOf(toolInfo); toolInfo.hwnd = Handle; @@ -1049,10 +1206,12 @@ public void Remove(ControlItem item) { UnsafeNativeMethods.SendMessage(new HandleRef(tipWindow, tipWindow.Handle), NativeMethods.TTM_DELTOOL, 0, toolInfo); } - if (items.Count == 0) { + if (items.Count == 0) + { EnsureDestroyed(); } - else { + else + { Update(false /*timerCaused*/); } } @@ -1061,8 +1220,10 @@ public void Remove(ControlItem item) { /// Start the blinking process. The timer will fire until there are no more /// icons that need to blink. /// - internal void StartBlinking() { - if (timer == null) { + internal void StartBlinking() + { + if (timer == null) + { timer = new System.Windows.Forms.Timer(); timer.Tick += new EventHandler(OnTimer); } @@ -1071,8 +1232,10 @@ internal void StartBlinking() { Update(false /*timerCaused*/); } - internal void StopBlinking() { - if (timer != null) { + internal void StopBlinking() + { + if (timer != null) + { timer.Stop(); } Update(false /*timerCaused*/); @@ -1083,11 +1246,13 @@ internal void StopBlinking() { /// set the tooltip rectangles and descriptions. This basically brings /// the error window up to date with the internal data structures. /// - public void Update(bool timerCaused) { + public void Update(bool timerCaused) + { IconRegion iconRegion = provider.Region; Size size = iconRegion.Size; windowBounds = Rectangle.Empty; - for (int i = 0; i < items.Count; i++) { + for (int i = 0; i < items.Count; i++) + { ControlItem item = (ControlItem)items[i]; Rectangle iconBounds = item.GetIconBounds(size); if (windowBounds.IsEmpty) @@ -1096,18 +1261,22 @@ public void Update(bool timerCaused) { windowBounds = Rectangle.Union(windowBounds, iconBounds); } - Region windowRegion = new Region(new Rectangle(0, 0, 0, 0)); + Region windowRegion = new Region(new Rectangle(0, 0, 0, 0)); IntPtr windowRegionHandle = IntPtr.Zero; - try { - for (int i = 0; i < items.Count; i++) { + try + { + for (int i = 0; i < items.Count; i++) + { ControlItem item = (ControlItem)items[i]; Rectangle iconBounds = item.GetIconBounds(size); iconBounds.X -= windowBounds.X; iconBounds.Y -= windowBounds.Y; bool showIcon = true; - if (!item.ToolTipShown) { - switch (provider.BlinkStyle) { + if (!item.ToolTipShown) + { + switch (provider.BlinkStyle) + { case ErrorBlinkStyle.NeverBlink: // always show icon break; @@ -1129,7 +1298,8 @@ public void Update(bool timerCaused) { iconRegion.Region.Translate(-iconBounds.X, -iconBounds.Y); } - if (tipWindow != null) { + if (tipWindow != null) + { NativeMethods.TOOLINFO_T toolInfo = new NativeMethods.TOOLINFO_T(); toolInfo.cbSize = Marshal.SizeOf(toolInfo); toolInfo.hwnd = Handle; @@ -1137,52 +1307,63 @@ public void Update(bool timerCaused) { toolInfo.lpszText = item.Error; toolInfo.rect = NativeMethods.RECT.FromXYWH(iconBounds.X, iconBounds.Y, iconBounds.Width, iconBounds.Height); toolInfo.uFlags = NativeMethods.TTF_SUBCLASS; - if (provider.RightToLeft) { + if (provider.RightToLeft) + { toolInfo.uFlags |= NativeMethods.TTF_RTLREADING; } UnsafeNativeMethods.SendMessage(new HandleRef(tipWindow, tipWindow.Handle), NativeMethods.TTM_SETTOOLINFO, 0, toolInfo); } - if (timerCaused && item.BlinkPhase > 0) { + if (timerCaused && item.BlinkPhase > 0) + { item.BlinkPhase--; } } - if (timerCaused) { + if (timerCaused) + { provider.showIcon = !provider.showIcon; } DeviceContext dc = null; dc = DeviceContext.FromHwnd(this.Handle); - try { + try + { CreateMirrorDC(dc.Hdc, windowBounds.Width); - + Graphics graphics = Graphics.FromHdcInternal(mirrordc.Hdc); - try { + try + { windowRegionHandle = windowRegion.GetHrgn(graphics); Interop.HandleCollector.Add(windowRegionHandle, Interop.CommonHandles.GDI); } - finally { + finally + { graphics.Dispose(); RestoreMirrorDC(); } - - if (UnsafeNativeMethods.SetWindowRgn(new HandleRef(this, Handle), new HandleRef(windowRegion, windowRegionHandle), true) != 0) { + + if (UnsafeNativeMethods.SetWindowRgn(new HandleRef(this, Handle), new HandleRef(windowRegion, windowRegionHandle), true) != 0) + { //The HWnd owns the region. windowRegionHandle = IntPtr.Zero; } } - - finally { - if (dc != null) { + + finally + { + if (dc != null) + { dc.Dispose(); } } } - finally { + finally + { windowRegion.Dispose(); - if (windowRegionHandle != IntPtr.Zero) { + if (windowRegionHandle != IntPtr.Zero) + { SafeNativeMethods.DeleteObject(new HandleRef(null, windowRegionHandle)); } } @@ -1195,8 +1376,10 @@ public void Update(bool timerCaused) { /// /// Called when the error window gets a windows message. /// - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { case Interop.WindowMessages.WM_NOTIFY: NativeMethods.NMHDR nmhdr = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR)); if (nmhdr.code == NativeMethods.TTN_SHOW || nmhdr.code == NativeMethods.TTN_POP) @@ -1221,7 +1404,8 @@ protected override void WndProc(ref Message m) { /// is tracking state for. It contains the values of all the extender /// properties. /// - internal class ControlItem { + internal class ControlItem + { // // FIELDS @@ -1246,7 +1430,8 @@ internal class ControlItem { /// Construct the item with its associated control, provider, and /// a unique ID. The ID is used for the tooltip ID. /// - public ControlItem(ErrorProvider provider, Control control, IntPtr id) { + public ControlItem(ErrorProvider provider, Control control, IntPtr id) + { this.toolTipShown = false; this.iconAlignment = defaultIconAlignment; this.error = string.Empty; @@ -1261,8 +1446,10 @@ public ControlItem(ErrorProvider provider, Control control, IntPtr id) { this.control.ParentChanged += new EventHandler(OnParentVisibleChanged); } - public void Dispose() { - if (control != null) { + public void Dispose() + { + if (control != null) + { control.HandleCreated -= new EventHandler(OnCreateHandle); control.HandleDestroyed -= new EventHandler(OnDestroyHandle); control.LocationChanged -= new EventHandler(OnBoundsChanged); @@ -1280,8 +1467,10 @@ public void Dispose() { /// /// Returns the unique ID for this control. The ID used as the tooltip ID. /// - public IntPtr Id { - get { + public IntPtr Id + { + get + { return id; } } @@ -1294,11 +1483,14 @@ public IntPtr Id { /// reduced by one (until zero), thus causing the error icon to appear /// or disappear. /// - public int BlinkPhase { - get { + public int BlinkPhase + { + get + { return blinkPhase; } - set { + set + { blinkPhase = value; } } @@ -1306,12 +1498,16 @@ public int BlinkPhase { /// /// Returns or sets the icon padding for the control. /// - public int IconPadding { - get { + public int IconPadding + { + get + { return iconPadding; } - set { - if (iconPadding != value) { + set + { + if (iconPadding != value) + { iconPadding = value; UpdateWindow(); } @@ -1321,35 +1517,46 @@ public int IconPadding { /// /// Returns or sets the error description string for the control. /// - public string Error { - get { + public string Error + { + get + { return error; } - set { - if (value == null) { + set + { + if (value == null) + { value = string.Empty; } // if the error is the same and the blinkStyle is not AlwaysBlink, then // we should not add the error and not start blinking. - if (error.Equals(value) && provider.BlinkStyle != ErrorBlinkStyle.AlwaysBlink) { + if (error.Equals(value) && provider.BlinkStyle != ErrorBlinkStyle.AlwaysBlink) + { return; } bool adding = error.Length == 0; error = value; - if (value.Length == 0) { + if (value.Length == 0) + { RemoveFromWindow(); } - else { - if (adding) { + else + { + if (adding) + { AddToWindow(); } - else { - if (provider.BlinkStyle != ErrorBlinkStyle.NeverBlink) { + else + { + if (provider.BlinkStyle != ErrorBlinkStyle.NeverBlink) + { StartBlinking(); } - else { + else + { UpdateWindow(); } } @@ -1360,12 +1567,16 @@ public string Error { /// /// Returns or sets the location of the error icon for the control. /// - public ErrorIconAlignment IconAlignment { - get { + public ErrorIconAlignment IconAlignment + { + get + { return iconAlignment; } - set { - if (iconAlignment != value) { + set + { + if (iconAlignment != value) + { //valid values are 0x0 to 0x5 if (!ClientUtils.IsEnumValid(value, (int)value, (int)ErrorIconAlignment.TopLeft, (int)ErrorIconAlignment.BottomRight)) { @@ -1382,17 +1593,22 @@ public ErrorIconAlignment IconAlignment { /// public bool ToolTipShown { - get { + get + { return this.toolTipShown; } - set { + set + { this.toolTipShown = value; } } - internal ErrorIconAlignment RTLTranslateIconAlignment(ErrorIconAlignment align) { - if (provider.RightToLeft) { - switch (align) { + internal ErrorIconAlignment RTLTranslateIconAlignment(ErrorIconAlignment align) + { + if (provider.RightToLeft) + { + switch (align) + { case ErrorIconAlignment.TopLeft: return ErrorIconAlignment.TopRight; case ErrorIconAlignment.MiddleLeft: @@ -1410,7 +1626,8 @@ internal ErrorIconAlignment RTLTranslateIconAlignment(ErrorIconAlignment align) return align; } } - else { + else + { return align; } } @@ -1420,11 +1637,13 @@ internal ErrorIconAlignment RTLTranslateIconAlignment(ErrorIconAlignment align) /// the control being extended. The size passed in is the size of /// the icon. /// - internal Rectangle GetIconBounds(Size size) { + internal Rectangle GetIconBounds(Size size) + { int x = 0; int y = 0; - switch (RTLTranslateIconAlignment(IconAlignment)) { + switch (RTLTranslateIconAlignment(IconAlignment)) + { case ErrorIconAlignment.TopLeft: case ErrorIconAlignment.MiddleLeft: case ErrorIconAlignment.BottomLeft: @@ -1437,7 +1656,8 @@ internal Rectangle GetIconBounds(Size size) { break; } - switch (IconAlignment) { + switch (IconAlignment) + { case ErrorIconAlignment.TopLeft: case ErrorIconAlignment.TopRight: y = control.Top; @@ -1460,8 +1680,10 @@ internal Rectangle GetIconBounds(Size size) { /// window, then update the window state because some property /// has changed. /// - void UpdateWindow() { - if (window != null) { + void UpdateWindow() + { + if (window != null) + { window.Update(false /*timerCaused*/); } } @@ -1471,8 +1693,10 @@ void UpdateWindow() { /// window, then start blinking the error window. The blink /// count /// - void StartBlinking() { - if (window != null) { + void StartBlinking() + { + if (window != null) + { BlinkPhase = startingBlinkPhase; window.StartBlinking(); } @@ -1481,12 +1705,14 @@ void StartBlinking() { /// /// Add this control's error icon to the error window. /// - void AddToWindow() { + void AddToWindow() + { // if we are recreating the control, then add the control. if (window == null && (control.Created || control.RecreatingHandle) && control.Visible && control.ParentInternal != null && - error.Length > 0) { + error.Length > 0) + { window = provider.EnsureErrorWindow(control.ParentInternal); window.Add(this); // Make sure that we blink if the style is set to AlwaysBlink or BlinkIfDifferrentError @@ -1500,8 +1726,10 @@ void AddToWindow() { /// /// Remove this control's error icon from the error window. /// - void RemoveFromWindow() { - if (window != null) { + void RemoveFromWindow() + { + if (window != null) + { window.Remove(this); window = null; } @@ -1510,11 +1738,13 @@ void RemoveFromWindow() { /// /// This is called when a property on the control is changed. /// - void OnBoundsChanged(object sender, EventArgs e) { + void OnBoundsChanged(object sender, EventArgs e) + { UpdateWindow(); } - void OnParentVisibleChanged(object sender, EventArgs e) { + void OnParentVisibleChanged(object sender, EventArgs e) + { this.BlinkPhase = 0; RemoveFromWindow(); AddToWindow(); @@ -1523,14 +1753,16 @@ void OnParentVisibleChanged(object sender, EventArgs e) { /// /// This is called when the control's handle is created. /// - void OnCreateHandle(object sender, EventArgs e) { + void OnCreateHandle(object sender, EventArgs e) + { AddToWindow(); } /// /// This is called when the control's handle is destroyed. /// - void OnDestroyHandle(object sender, EventArgs e) { + void OnDestroyHandle(object sender, EventArgs e) + { RemoveFromWindow(); } } @@ -1538,7 +1770,8 @@ void OnDestroyHandle(object sender, EventArgs e) { /// /// This represents the HRGN of icon. The region is calculate from the icon's mask. /// - internal class IconRegion { + internal class IconRegion + { // // FIELDS @@ -1554,9 +1787,10 @@ internal class IconRegion { /// /// Constructor that takes an Icon and extracts its 16x16 version. /// - - - public IconRegion(Icon icon) { + + + public IconRegion(Icon icon) + { this.icon = new Icon(icon, 16, 16); } @@ -1567,8 +1801,10 @@ public IconRegion(Icon icon) { /// /// Returns the handle of the icon. /// - public IntPtr IconHandle { - get { + public IntPtr IconHandle + { + get + { return icon.Handle; } } @@ -1576,14 +1812,18 @@ public IntPtr IconHandle { /// /// Returns the handle of the region. /// - public Region Region { - - get { - if (region == null) { - region = new Region(new Rectangle(0,0,0,0)); + public Region Region + { + + get + { + if (region == null) + { + region = new Region(new Rectangle(0, 0, 0, 0)); IntPtr mask = IntPtr.Zero; - try { + try + { Size size = icon.Size; Bitmap bitmap = icon.ToBitmap(); mask = ControlPaint.CreateHBitmapTransparencyMask(bitmap); @@ -1594,22 +1834,26 @@ public Region Region { int bitmapBitsAllocationSize = 16; //if width is not multiple of 16, we need to allocate BitmapBitsAllocationSize for remaining bits. - int widthInBytes = 2 * ((size.Width +15) / bitmapBitsAllocationSize); // its in bytes. + int widthInBytes = 2 * ((size.Width + 15) / bitmapBitsAllocationSize); // its in bytes. byte[] bits = new byte[widthInBytes * size.Height]; SafeNativeMethods.GetBitmapBits(new HandleRef(null, mask), bits.Length, bits); - for (int y = 0; y < size.Height; y++) { - for (int x = 0; x < size.Width; x++) { + for (int y = 0; y < size.Height; y++) + { + for (int x = 0; x < size.Width; x++) + { // see if bit is set in mask. bits in byte are reversed. 0 is black (set). - if ((bits[y * widthInBytes + x / 8] & (1 << (7 - (x % 8)))) == 0) { + if ((bits[y * widthInBytes + x / 8] & (1 << (7 - (x % 8)))) == 0) + { region.Union(new Rectangle(x, y, 1, 1)); - } + } } } region.Intersect(new Rectangle(0, 0, size.Width, size.Height)); } - finally { + finally + { if (mask != IntPtr.Zero) SafeNativeMethods.DeleteObject(new HandleRef(null, mask)); } @@ -1622,8 +1866,10 @@ public Region Region { /// /// Return the size of the icon. /// - public Size Size { - get { + public Size Size + { + get + { return icon.Size; } } @@ -1635,8 +1881,10 @@ public Size Size { /// /// Release any resources held by this Object. /// - public void Dispose() { - if (region != null) { + public void Dispose() + { + if (region != null) + { region.Dispose(); region = null; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FileDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FileDialog.cs index b767556d2bc..e12cf94cfc7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FileDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FileDialog.cs @@ -144,7 +144,7 @@ public string FileName { return string.Empty; } - + return _fileNames[0]; } set => _fileNames = value != null ? new string[] { value } : null; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FileDialogCustomPlace.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FileDialogCustomPlace.cs index b128afa652a..74b561efdcd 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FileDialogCustomPlace.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FileDialogCustomPlace.cs @@ -23,7 +23,7 @@ public FileDialogCustomPlace(string path) public FileDialogCustomPlace(Guid knownFolderGuid) { - KnownFolderGuid = knownFolderGuid; + KnownFolderGuid = knownFolderGuid; } public string Path diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FileDialogCustomPlacesCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FileDialogCustomPlacesCollection.cs index f29a0d25d59..9ee2816c1aa 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FileDialogCustomPlacesCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FileDialogCustomPlacesCollection.cs @@ -8,7 +8,7 @@ namespace System.Windows.Forms { public class FileDialogCustomPlacesCollection : Collection - { + { internal void Apply(FileDialogNative.IFileDialog dialog) { // Walk backwards @@ -32,7 +32,7 @@ internal void Apply(FileDialogNative.IFileDialog dialog) } } - public void Add(string path) => Add(new FileDialogCustomPlace(path)); + public void Add(string path) => Add(new FileDialogCustomPlace(path)); public void Add(Guid knownFolderGuid) => Add(new FileDialogCustomPlace(knownFolderGuid)); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FileDialog_Vista.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FileDialog_Vista.cs index e1bfcc80242..f41e7cd3b50 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FileDialog_Vista.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FileDialog_Vista.cs @@ -172,7 +172,7 @@ private bool HandleVistaFileOk(FileDialogNative.IFileDialog dialog) // When the dialog is dismissed OK, the Readonly bit can't // be left on if ShowReadOnly was false // Downlevel this happens automatically, on Vista mode, we need to watch out for it. - _options &= ~ NativeMethods.OFN_READONLY; + _options &= ~NativeMethods.OFN_READONLY; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FlatButtonAppearance.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FlatButtonAppearance.cs index fe8b2e3487f..ea7579c9614 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FlatButtonAppearance.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FlatButtonAppearance.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Drawing; using System.Globalization; @@ -12,17 +13,19 @@ namespace System.Windows.Forms { /// /// [TypeConverter(typeof(FlatButtonAppearanceConverter))] - public class FlatButtonAppearance { + public class FlatButtonAppearance + { private ButtonBase owner; - private int borderSize = 1; - private Color borderColor = Color.Empty; - private Color checkedBackColor = Color.Empty; + private int borderSize = 1; + private Color borderColor = Color.Empty; + private Color checkedBackColor = Color.Empty; private Color mouseDownBackColor = Color.Empty; private Color mouseOverBackColor = Color.Empty; - internal FlatButtonAppearance(ButtonBase owner) { + internal FlatButtonAppearance(ButtonBase owner) + { this.owner = owner; } @@ -38,17 +41,22 @@ internal FlatButtonAppearance(ButtonBase owner) { EditorBrowsable(EditorBrowsableState.Always), DefaultValue(1), ] - public int BorderSize { - get { + public int BorderSize + { + get + { return borderSize; } - set { + set + { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(BorderSize), value, 0)); - if (borderSize != value) { + if (borderSize != value) + { borderSize = value; - if (owner != null && owner.ParentInternal != null) { + if (owner != null && owner.ParentInternal != null) + { LayoutTransaction.DoLayoutIf(owner.AutoSize, owner.ParentInternal, owner, PropertyNames.FlatAppearanceBorderSize); } owner.Invalidate(); @@ -68,16 +76,21 @@ public int BorderSize { EditorBrowsable(EditorBrowsableState.Always), DefaultValue(typeof(Color), ""), ] - public Color BorderColor { - get { + public Color BorderColor + { + get + { return borderColor; } - set { - if (value.Equals(Color.Transparent)) { + set + { + if (value.Equals(Color.Transparent)) + { throw new NotSupportedException(SR.ButtonFlatAppearanceInvalidBorderColor); } - - if (borderColor != value) { + + if (borderColor != value) + { borderColor = value; owner.Invalidate(); } @@ -96,12 +109,16 @@ public Color BorderColor { EditorBrowsable(EditorBrowsableState.Always), DefaultValue(typeof(Color), ""), ] - public Color CheckedBackColor { - get { + public Color CheckedBackColor + { + get + { return checkedBackColor; } - set { - if (checkedBackColor != value) { + set + { + if (checkedBackColor != value) + { checkedBackColor = value; owner.Invalidate(); } @@ -121,12 +138,16 @@ public Color CheckedBackColor { EditorBrowsable(EditorBrowsableState.Always), DefaultValue(typeof(Color), ""), ] - public Color MouseDownBackColor { - get { + public Color MouseDownBackColor + { + get + { return mouseDownBackColor; } - set { - if (mouseDownBackColor != value) { + set + { + if (mouseDownBackColor != value) + { mouseDownBackColor = value; owner.Invalidate(); } @@ -146,12 +167,16 @@ public Color MouseDownBackColor { EditorBrowsable(EditorBrowsableState.Always), DefaultValue(typeof(Color), ""), ] - public Color MouseOverBackColor { - get { + public Color MouseOverBackColor + { + get + { return mouseOverBackColor; } - set { - if (mouseOverBackColor != value) { + set + { + if (mouseOverBackColor != value) + { mouseOverBackColor = value; owner.Invalidate(); } @@ -160,16 +185,21 @@ public Color MouseOverBackColor { } - internal sealed class ApplicableToButtonAttribute : Attribute { - public ApplicableToButtonAttribute() { + internal sealed class ApplicableToButtonAttribute : Attribute + { + public ApplicableToButtonAttribute() + { } } - internal class FlatButtonAppearanceConverter : ExpandableObjectConverter { + internal class FlatButtonAppearanceConverter : ExpandableObjectConverter + { // Don't let the property grid display the full type name in the value cell - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == typeof(string)) { + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == typeof(string)) + { return ""; } @@ -177,8 +207,10 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul } // Don't let the property grid display the CheckedBackColor property for Button controls - public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { - if (context != null && context.Instance is Button) { + public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) + { + if (context != null && context.Instance is Button) + { Attribute[] attributes2 = new Attribute[attributes.Length + 1]; attributes.CopyTo(attributes2, 0); attributes2[attributes.Length] = new ApplicableToButtonAttribute(); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FlowLayoutPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FlowLayoutPanel.cs index 6048537b058..25bebd36d66 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FlowLayoutPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FlowLayoutPanel.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.ComponentModel; using System.Diagnostics; @@ -17,14 +18,17 @@ namespace System.Windows.Forms { [Designer("System.Windows.Forms.Design.FlowLayoutPanelDesigner, " + AssemblyRef.SystemDesign)] [Docking(DockingBehavior.Ask)] [SRDescription(nameof(SR.DescriptionFlowLayoutPanel))] - public class FlowLayoutPanel : Panel, IExtenderProvider { + public class FlowLayoutPanel : Panel, IExtenderProvider + { private FlowLayoutSettings _flowLayoutSettings; - public FlowLayoutPanel() { + public FlowLayoutPanel() + { _flowLayoutSettings = FlowLayout.CreateSettings(this); } - - public override LayoutEngine LayoutEngine { + + public override LayoutEngine LayoutEngine + { get { return FlowLayout.Instance; } } @@ -32,10 +36,12 @@ public override LayoutEngine LayoutEngine { [DefaultValue(FlowDirection.LeftToRight)] [SRCategory(nameof(SR.CatLayout))] [Localizable(true)] - public FlowDirection FlowDirection { + public FlowDirection FlowDirection + { get { return _flowLayoutSettings.FlowDirection; } - set { - _flowLayoutSettings.FlowDirection = value; + set + { + _flowLayoutSettings.FlowDirection = value; Debug.Assert(FlowDirection == value, "FlowDirection should be the same as we set it"); } } @@ -44,31 +50,36 @@ public FlowDirection FlowDirection { [DefaultValue(true)] [SRCategory(nameof(SR.CatLayout))] [Localizable(true)] - public bool WrapContents { + public bool WrapContents + { get { return _flowLayoutSettings.WrapContents; } - set { + set + { _flowLayoutSettings.WrapContents = value; Debug.Assert(WrapContents == value, "WrapContents should be the same as we set it"); } } #region Provided properties - bool IExtenderProvider.CanExtend(object obj) { + bool IExtenderProvider.CanExtend(object obj) + { Control control = obj as Control; return control != null && control.Parent == this; } [DefaultValue(false)] [DisplayName("FlowBreak")] - public bool GetFlowBreak(Control control) { + public bool GetFlowBreak(Control control) + { return _flowLayoutSettings.GetFlowBreak(control); } [DisplayName("FlowBreak")] - public void SetFlowBreak(Control control, bool value) { + public void SetFlowBreak(Control control, bool value) + { _flowLayoutSettings.SetFlowBreak(control, value); } - + #endregion } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FlowLayoutSettings.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FlowLayoutSettings.cs index 36a157ae21d..e38943ab75c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FlowLayoutSettings.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FlowLayoutSettings.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.ComponentModel; using System.Diagnostics; @@ -10,49 +11,58 @@ namespace System.Windows.Forms { using System.Windows.Forms.Layout; [DefaultProperty(nameof(FlowDirection))] - public class FlowLayoutSettings : LayoutSettings { + public class FlowLayoutSettings : LayoutSettings + { - internal FlowLayoutSettings(IArrangedElement owner) : base(owner) {} - - public override LayoutEngine LayoutEngine { + internal FlowLayoutSettings(IArrangedElement owner) : base(owner) { } + + public override LayoutEngine LayoutEngine + { get { return FlowLayout.Instance; } } [SRDescription(nameof(SR.FlowPanelFlowDirectionDescr))] [DefaultValue(FlowDirection.LeftToRight)] [SRCategory(nameof(SR.CatLayout))] - public FlowDirection FlowDirection { + public FlowDirection FlowDirection + { get { return FlowLayout.GetFlowDirection(Owner); } - set { + set + { FlowLayout.SetFlowDirection(Owner, value); Debug.Assert(FlowDirection == value, "FlowDirection should be the same as we set it"); } } - + [SRDescription(nameof(SR.FlowPanelWrapContentsDescr))] [DefaultValue(true)] [SRCategory(nameof(SR.CatLayout))] - public bool WrapContents { + public bool WrapContents + { get { return FlowLayout.GetWrapContents(Owner); } - set { + set + { FlowLayout.SetWrapContents(Owner, value); Debug.Assert(WrapContents == value, "WrapContents should be the same as we set it"); } } - public void SetFlowBreak(object child, bool value) { + public void SetFlowBreak(object child, bool value) + { IArrangedElement element = FlowLayout.Instance.CastToArrangedElement(child); - if (GetFlowBreak(child) != value) { + if (GetFlowBreak(child) != value) + { CommonProperties.SetFlowBreak(element, value); } } - public bool GetFlowBreak(object child) { + public bool GetFlowBreak(object child) + { IArrangedElement element = FlowLayout.Instance.CastToArrangedElement(child); return CommonProperties.GetFlowBreak(element); } - + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FontDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FontDialog.cs index 85c9086d85f..8688e9965b3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FontDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FontDialog.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -28,7 +29,8 @@ namespace System.Windows.Forms { DefaultProperty(nameof(Font)), SRDescription(nameof(SR.DescriptionFontDialog)) ] - public class FontDialog : CommonDialog { + public class FontDialog : CommonDialog + { protected static readonly object EventApply = new object(); private const int defaultMinSize = 0; @@ -52,7 +54,8 @@ public class FontDialog : CommonDialog { SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // If the constructor does not call Reset // it would be a breaking change. ] - public FontDialog() { + public FontDialog() + { Reset(); } @@ -63,16 +66,19 @@ public FontDialog() { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(true), SRDescription(nameof(SR.FnDallowSimulationsDescr)) ] - public bool AllowSimulations { - get { + public bool AllowSimulations + { + get + { return !GetOption(NativeMethods.CF_NOSIMULATIONS); } - set { + set + { SetOption(NativeMethods.CF_NOSIMULATIONS, !value); } } @@ -83,16 +89,19 @@ public bool AllowSimulations { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(true), SRDescription(nameof(SR.FnDallowVectorFontsDescr)) ] - public bool AllowVectorFonts { - get { + public bool AllowVectorFonts + { + get + { return !GetOption(NativeMethods.CF_NOVECTORFONTS); } - set { + set + { SetOption(NativeMethods.CF_NOVECTORFONTS, !value); } } @@ -105,16 +114,19 @@ public bool AllowVectorFonts { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(true), SRDescription(nameof(SR.FnDallowVerticalFontsDescr)) ] - public bool AllowVerticalFonts { - get { + public bool AllowVerticalFonts + { + get + { return !GetOption(NativeMethods.CF_NOVERTFONTS); } - set { + set + { SetOption(NativeMethods.CF_NOVERTFONTS, !value); } } @@ -128,16 +140,19 @@ public bool AllowVerticalFonts { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(true), SRDescription(nameof(SR.FnDallowScriptChangeDescr)) ] - public bool AllowScriptChange { - get { + public bool AllowScriptChange + { + get + { return !GetOption(NativeMethods.CF_SELECTSCRIPT); } - set { + set + { SetOption(NativeMethods.CF_SELECTSCRIPT, !value); } } @@ -148,25 +163,31 @@ public bool AllowScriptChange { /// /// [ - SRCategory(nameof(SR.CatData)), + SRCategory(nameof(SR.CatData)), SRDescription(nameof(SR.FnDcolorDescr)), DefaultValue(typeof(Color), "Black") ] - public Color Color { - get { + public Color Color + { + get + { // Convert to RGB and back to resolve indirect colors like SystemColors.ControlText // to real color values like Color.Lime - if (usingDefaultIndirectColor) { + if (usingDefaultIndirectColor) + { return ColorTranslator.FromWin32(ColorTranslator.ToWin32(color)); } return color; } - set { - if (!value.IsEmpty) { + set + { + if (!value.IsEmpty) + { color = value; usingDefaultIndirectColor = false; } - else { + else + { color = SystemColors.ControlText; usingDefaultIndirectColor = true; } @@ -180,16 +201,19 @@ public Color Color { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(false), SRDescription(nameof(SR.FnDfixedPitchOnlyDescr)) ] - public bool FixedPitchOnly { - get { + public bool FixedPitchOnly + { + get + { return GetOption(NativeMethods.CF_FIXEDPITCHONLY); } - set { + set + { SetOption(NativeMethods.CF_FIXEDPITCHONLY, value); } } @@ -200,18 +224,20 @@ public bool FixedPitchOnly { /// /// [ - SRCategory(nameof(SR.CatData)), + SRCategory(nameof(SR.CatData)), SRDescription(nameof(SR.FnDfontDescr)) ] - public Font Font { - - - get { + public Font Font + { + + + get + { Font result = font; if (result == null) result = Control.DefaultFont; - float actualSize = result.SizeInPoints; + float actualSize = result.SizeInPoints; if (minSize != defaultMinSize && actualSize < MinSize) result = new Font(result.FontFamily, MinSize, result.Style, GraphicsUnit.Point); if (maxSize != defaultMaxSize && actualSize > MaxSize) @@ -219,7 +245,8 @@ public Font Font { return result; } - set { + set + { font = value; } } @@ -231,16 +258,19 @@ public Font Font { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(false), SRDescription(nameof(SR.FnDfontMustExistDescr)) ] - public bool FontMustExist { - get { + public bool FontMustExist + { + get + { return GetOption(NativeMethods.CF_FORCEFONTEXIST); } - set { + set + { SetOption(NativeMethods.CF_FORCEFONTEXIST, value); } } @@ -252,21 +282,26 @@ public bool FontMustExist { /// /// [ - SRCategory(nameof(SR.CatData)), + SRCategory(nameof(SR.CatData)), DefaultValue(defaultMaxSize), SRDescription(nameof(SR.FnDmaxSizeDescr)) ] - public int MaxSize { - get { + public int MaxSize + { + get + { return maxSize; } - set { - if (value < 0) { + set + { + if (value < 0) + { value = 0; } maxSize = value; - if (maxSize > 0 && maxSize < minSize) { + if (maxSize > 0 && maxSize < minSize) + { minSize = maxSize; } } @@ -278,21 +313,26 @@ public int MaxSize { /// /// [ - SRCategory(nameof(SR.CatData)), + SRCategory(nameof(SR.CatData)), DefaultValue(defaultMinSize), SRDescription(nameof(SR.FnDminSizeDescr)) ] - public int MinSize { - get { + public int MinSize + { + get + { return minSize; } - set { - if (value < 0) { + set + { + if (value < 0) + { value = 0; } minSize = value; - if (maxSize > 0 && maxSize < minSize) { + if (maxSize > 0 && maxSize < minSize) + { maxSize = minSize; } } @@ -303,8 +343,10 @@ public int MinSize { /// Gets the value passed to CHOOSEFONT.Flags. /// /// - protected int Options { - get { + protected int Options + { + get + { return options; } } @@ -317,15 +359,18 @@ protected int Options { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(false), SRDescription(nameof(SR.FnDscriptsOnlyDescr)) ] - public bool ScriptsOnly { - get { + public bool ScriptsOnly + { + get + { return GetOption(NativeMethods.CF_SCRIPTSONLY); } - set { + set + { SetOption(NativeMethods.CF_SCRIPTSONLY, value); } } @@ -336,15 +381,18 @@ public bool ScriptsOnly { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(false), SRDescription(nameof(SR.FnDshowApplyDescr)) ] - public bool ShowApply { - get { + public bool ShowApply + { + get + { return GetOption(NativeMethods.CF_APPLY); } - set { + set + { SetOption(NativeMethods.CF_APPLY, value); } } @@ -355,15 +403,18 @@ public bool ShowApply { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(false), SRDescription(nameof(SR.FnDshowColorDescr)) ] - public bool ShowColor { - get { + public bool ShowColor + { + get + { return showColor; } - set { + set + { this.showColor = value; } } @@ -375,15 +426,18 @@ public bool ShowColor { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(true), SRDescription(nameof(SR.FnDshowEffectsDescr)) ] - public bool ShowEffects { - get { + public bool ShowEffects + { + get + { return GetOption(NativeMethods.CF_EFFECTS); } - set { + set + { SetOption(NativeMethods.CF_EFFECTS, value); } } @@ -394,15 +448,18 @@ public bool ShowEffects { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(false), SRDescription(nameof(SR.FnDshowHelpDescr)) ] - public bool ShowHelp { - get { + public bool ShowHelp + { + get + { return GetOption(NativeMethods.CF_SHOWHELP); } - set { + set + { SetOption(NativeMethods.CF_SHOWHELP, value); } } @@ -414,7 +471,8 @@ public bool ShowHelp { /// /// [SRDescription(nameof(SR.FnDapplyDescr))] - public event EventHandler Apply { + public event EventHandler Apply + { add => Events.AddHandler(EventApply, value); remove => Events.RemoveHandler(EventApply, value); } @@ -422,8 +480,9 @@ public event EventHandler Apply { /// /// Returns the state of the given option flag. /// - internal bool GetOption(int option) { - return(options & option) != 0; + internal bool GetOption(int option) + { + return (options & option) != 0; } /// @@ -432,23 +491,29 @@ internal bool GetOption(int option) { /// specific functionality to a common dialog box. /// /// - protected override IntPtr HookProc(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam) { - - switch (msg) { + protected override IntPtr HookProc(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam) + { + + switch (msg) + { case Interop.WindowMessages.WM_COMMAND: - if ((int)wparam == 0x402) { + if ((int)wparam == 0x402) + { NativeMethods.LOGFONT lf = new NativeMethods.LOGFONT(); UnsafeNativeMethods.SendMessage(new HandleRef(null, hWnd), Interop.WindowMessages.WM_CHOOSEFONT_GETLOGFONT, 0, lf); UpdateFont(lf); int index = (int)UnsafeNativeMethods.SendDlgItemMessage(new HandleRef(null, hWnd), 0x473, NativeMethods.CB_GETCURSEL, IntPtr.Zero, IntPtr.Zero); - if (index != NativeMethods.CB_ERR) { + if (index != NativeMethods.CB_ERR) + { UpdateColor((int)UnsafeNativeMethods.SendDlgItemMessage(new HandleRef(null, hWnd), 0x473, - NativeMethods.CB_GETITEMDATA, (IntPtr) index, IntPtr.Zero)); + NativeMethods.CB_GETITEMDATA, (IntPtr)index, IntPtr.Zero)); } - if (NativeWindow.WndProcShouldBeDebuggable) { + if (NativeWindow.WndProcShouldBeDebuggable) + { OnApply(EventArgs.Empty); } - else { + else + { try { OnApply(EventArgs.Empty); @@ -461,7 +526,8 @@ protected override IntPtr HookProc(IntPtr hWnd, int msg, IntPtr wparam, IntPtr l } break; case Interop.WindowMessages.WM_INITDIALOG: - if (!showColor) { + if (!showColor) + { IntPtr hWndCtl = UnsafeNativeMethods.GetDlgItem(new HandleRef(null, hWnd), NativeMethods.cmb4); SafeNativeMethods.ShowWindow(new HandleRef(null, hWndCtl), NativeMethods.SW_HIDE); hWndCtl = UnsafeNativeMethods.GetDlgItem(new HandleRef(null, hWnd), NativeMethods.stc4); @@ -469,7 +535,7 @@ protected override IntPtr HookProc(IntPtr hWnd, int msg, IntPtr wparam, IntPtr l } break; } - + return base.HookProc(hWnd, msg, wparam, lparam); } @@ -478,9 +544,11 @@ protected override IntPtr HookProc(IntPtr hWnd, int msg, IntPtr wparam, IntPtr l /// Raises the event. /// /// - protected virtual void OnApply(EventArgs e) { + protected virtual void OnApply(EventArgs e) + { EventHandler handler = (EventHandler)Events[EventApply]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// @@ -488,18 +556,20 @@ protected virtual void OnApply(EventArgs e) { /// Resets all dialog box options to their default values. /// /// - public override void Reset() { + public override void Reset() + { options = NativeMethods.CF_SCREENFONTS | NativeMethods.CF_EFFECTS; font = null; color = SystemColors.ControlText; - usingDefaultIndirectColor = true; + usingDefaultIndirectColor = true; showColor = false; minSize = defaultMinSize; maxSize = defaultMaxSize; SetOption(NativeMethods.CF_TTONLY, true); } - private void ResetFont() { + private void ResetFont() + { font = null; } @@ -511,7 +581,8 @@ private void ResetFont() { /// /// /// - protected override bool RunDialog(IntPtr hWndOwner) { + protected override bool RunDialog(IntPtr hWndOwner) + { NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(this.HookProc); NativeMethods.CHOOSEFONT cf = new NativeMethods.CHOOSEFONT(); IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef); @@ -519,16 +590,19 @@ protected override bool RunDialog(IntPtr hWndOwner) { Graphics graphics = Graphics.FromHdcInternal(screenDC); - try { + try + { Font.ToLogFont(lf, graphics); } - finally { + finally + { graphics.Dispose(); } UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC)); IntPtr logFontPtr = IntPtr.Zero; - try { + try + { logFontPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf()); Marshal.StructureToPtr(lf, logFontPtr, false); @@ -537,7 +611,8 @@ protected override bool RunDialog(IntPtr hWndOwner) { cf.hDC = IntPtr.Zero; cf.lpLogFont = logFontPtr; cf.Flags = Options | NativeMethods.CF_INITTOLOGFONTSTRUCT | NativeMethods.CF_ENABLEHOOK; - if (minSize > 0 || maxSize > 0) { + if (minSize > 0 || maxSize > 0) + { cf.Flags |= NativeMethods.CF_LIMITSIZE; } @@ -545,29 +620,35 @@ protected override bool RunDialog(IntPtr hWndOwner) { //if ShowEffects=false then we will draw the sample text in standard control text color regardless. //(limitation of windows control) // - if (ShowColor || ShowEffects) { + if (ShowColor || ShowEffects) + { cf.rgbColors = ColorTranslator.ToWin32(color); } - else { + else + { cf.rgbColors = ColorTranslator.ToWin32(SystemColors.ControlText); } cf.lpfnHook = hookProcPtr; cf.hInstance = UnsafeNativeMethods.GetModuleHandle(null); cf.nSizeMin = minSize; - if (maxSize == 0) { + if (maxSize == 0) + { cf.nSizeMax = int.MaxValue; } - else { + else + { cf.nSizeMax = maxSize; } Debug.Assert(cf.nSizeMin <= cf.nSizeMax, "min and max font sizes are the wrong way around"); - if (!SafeNativeMethods.ChooseFont(cf)) return false; + if (!SafeNativeMethods.ChooseFont(cf)) + return false; NativeMethods.LOGFONT lfReturned = Marshal.PtrToStructure(logFontPtr); - if (lfReturned.lfFaceName != null && lfReturned.lfFaceName.Length > 0) { + if (lfReturned.lfFaceName != null && lfReturned.lfFaceName.Length > 0) + { lf = lfReturned; UpdateFont(lf); UpdateColor(cf.rgbColors); @@ -575,7 +656,8 @@ protected override bool RunDialog(IntPtr hWndOwner) { return true; } - finally { + finally + { if (logFontPtr != IntPtr.Zero) Marshal.FreeCoTaskMem(logFontPtr); } @@ -584,11 +666,14 @@ protected override bool RunDialog(IntPtr hWndOwner) { /// /// Sets the given option to the given boolean value. /// - internal void SetOption(int option, bool value) { - if (value) { + internal void SetOption(int option, bool value) + { + if (value) + { options |= option; } - else { + else + { options &= ~option; } } @@ -599,7 +684,8 @@ internal void SetOption(int option, bool value) { /// persisted. /// /// - private bool ShouldSerializeFont() { + private bool ShouldSerializeFont() + { return !Font.Equals(Control.DefaultFont); } @@ -610,40 +696,49 @@ private bool ShouldSerializeFont() { /// /// /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); return s + ", Font: " + Font.ToString(); } /// /// - private void UpdateColor(int rgb) { - if (ColorTranslator.ToWin32(color) != rgb) { + private void UpdateColor(int rgb) + { + if (ColorTranslator.ToWin32(color) != rgb) + { color = ColorTranslator.FromOle(rgb); - usingDefaultIndirectColor = false; + usingDefaultIndirectColor = false; } } /// /// - private void UpdateFont(NativeMethods.LOGFONT lf) { + private void UpdateFont(NativeMethods.LOGFONT lf) + { IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef); - try { + try + { Font fontInWorldUnits = null; - try { + try + { fontInWorldUnits = Font.FromLogFont(lf, screenDC); // The dialog claims its working in points (a device-independent unit), // but actually gives us something in world units (device-dependent). font = ControlPaint.FontInPoints(fontInWorldUnits); } - finally { - if (fontInWorldUnits != null) { + finally + { + if (fontInWorldUnits != null) + { fontInWorldUnits.Dispose(); } } } - finally { + finally + { UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC)); } } 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 afbd0d3ebce..fa792406a54 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System; using System.Collections; @@ -39,7 +40,8 @@ namespace System.Windows.Forms { DefaultEvent(nameof(Load)), InitializationEvent(nameof(Load)), ] - public class Form : ContainerControl { + public class Form : ContainerControl + { #if DEBUG static readonly BooleanSwitch AlwaysRestrictWindows = new BooleanSwitch("AlwaysRestrictWindows", "Always make Form classes behave as though they are restricted"); #endif @@ -68,48 +70,48 @@ public class Form : ContainerControl { // The following flags should be used with formState[..] not formStateEx[..] // Don't add any more sections to this vector, it is already full. // - private static readonly BitVector32.Section FormStateAllowTransparency = BitVector32.CreateSection(1); - private static readonly BitVector32.Section FormStateBorderStyle = BitVector32.CreateSection(6, FormStateAllowTransparency); - private static readonly BitVector32.Section FormStateTaskBar = BitVector32.CreateSection(1, FormStateBorderStyle); - private static readonly BitVector32.Section FormStateControlBox = BitVector32.CreateSection(1, FormStateTaskBar); - private static readonly BitVector32.Section FormStateKeyPreview = BitVector32.CreateSection(1, FormStateControlBox); - private static readonly BitVector32.Section FormStateLayered = BitVector32.CreateSection(1, FormStateKeyPreview); - private static readonly BitVector32.Section FormStateMaximizeBox = BitVector32.CreateSection(1, FormStateLayered); - private static readonly BitVector32.Section FormStateMinimizeBox = BitVector32.CreateSection(1, FormStateMaximizeBox); - private static readonly BitVector32.Section FormStateHelpButton = BitVector32.CreateSection(1, FormStateMinimizeBox); - private static readonly BitVector32.Section FormStateStartPos = BitVector32.CreateSection(4, FormStateHelpButton); - private static readonly BitVector32.Section FormStateWindowState = BitVector32.CreateSection(2, FormStateStartPos); - private static readonly BitVector32.Section FormStateShowWindowOnCreate = BitVector32.CreateSection(1, FormStateWindowState); - private static readonly BitVector32.Section FormStateAutoScaling = BitVector32.CreateSection(1, FormStateShowWindowOnCreate); - private static readonly BitVector32.Section FormStateSetClientSize = BitVector32.CreateSection(1, FormStateAutoScaling); - private static readonly BitVector32.Section FormStateTopMost = BitVector32.CreateSection(1, FormStateSetClientSize); - private static readonly BitVector32.Section FormStateSWCalled = BitVector32.CreateSection(1, FormStateTopMost); - private static readonly BitVector32.Section FormStateMdiChildMax = BitVector32.CreateSection(1, FormStateSWCalled); - private static readonly BitVector32.Section FormStateRenderSizeGrip = BitVector32.CreateSection(1, FormStateMdiChildMax); - private static readonly BitVector32.Section FormStateSizeGripStyle = BitVector32.CreateSection(2, FormStateRenderSizeGrip); - private static readonly BitVector32.Section FormStateIsWindowActivated = BitVector32.CreateSection(1, FormStateSizeGripStyle); - private static readonly BitVector32.Section FormStateIsTextEmpty = BitVector32.CreateSection(1, FormStateIsWindowActivated); - private static readonly BitVector32.Section FormStateIsActive = BitVector32.CreateSection(1, FormStateIsTextEmpty); - private static readonly BitVector32.Section FormStateIconSet = BitVector32.CreateSection(1, FormStateIsActive); + private static readonly BitVector32.Section FormStateAllowTransparency = BitVector32.CreateSection(1); + private static readonly BitVector32.Section FormStateBorderStyle = BitVector32.CreateSection(6, FormStateAllowTransparency); + private static readonly BitVector32.Section FormStateTaskBar = BitVector32.CreateSection(1, FormStateBorderStyle); + private static readonly BitVector32.Section FormStateControlBox = BitVector32.CreateSection(1, FormStateTaskBar); + private static readonly BitVector32.Section FormStateKeyPreview = BitVector32.CreateSection(1, FormStateControlBox); + private static readonly BitVector32.Section FormStateLayered = BitVector32.CreateSection(1, FormStateKeyPreview); + private static readonly BitVector32.Section FormStateMaximizeBox = BitVector32.CreateSection(1, FormStateLayered); + private static readonly BitVector32.Section FormStateMinimizeBox = BitVector32.CreateSection(1, FormStateMaximizeBox); + private static readonly BitVector32.Section FormStateHelpButton = BitVector32.CreateSection(1, FormStateMinimizeBox); + private static readonly BitVector32.Section FormStateStartPos = BitVector32.CreateSection(4, FormStateHelpButton); + private static readonly BitVector32.Section FormStateWindowState = BitVector32.CreateSection(2, FormStateStartPos); + private static readonly BitVector32.Section FormStateShowWindowOnCreate = BitVector32.CreateSection(1, FormStateWindowState); + private static readonly BitVector32.Section FormStateAutoScaling = BitVector32.CreateSection(1, FormStateShowWindowOnCreate); + private static readonly BitVector32.Section FormStateSetClientSize = BitVector32.CreateSection(1, FormStateAutoScaling); + private static readonly BitVector32.Section FormStateTopMost = BitVector32.CreateSection(1, FormStateSetClientSize); + private static readonly BitVector32.Section FormStateSWCalled = BitVector32.CreateSection(1, FormStateTopMost); + private static readonly BitVector32.Section FormStateMdiChildMax = BitVector32.CreateSection(1, FormStateSWCalled); + private static readonly BitVector32.Section FormStateRenderSizeGrip = BitVector32.CreateSection(1, FormStateMdiChildMax); + private static readonly BitVector32.Section FormStateSizeGripStyle = BitVector32.CreateSection(2, FormStateRenderSizeGrip); + private static readonly BitVector32.Section FormStateIsWindowActivated = BitVector32.CreateSection(1, FormStateSizeGripStyle); + private static readonly BitVector32.Section FormStateIsTextEmpty = BitVector32.CreateSection(1, FormStateIsWindowActivated); + private static readonly BitVector32.Section FormStateIsActive = BitVector32.CreateSection(1, FormStateIsTextEmpty); + private static readonly BitVector32.Section FormStateIconSet = BitVector32.CreateSection(1, FormStateIsActive); // The following flags should be used with formStateEx[...] not formState[..] - private static readonly BitVector32.Section FormStateExCalledClosing = BitVector32.CreateSection(1); - private static readonly BitVector32.Section FormStateExUpdateMenuHandlesSuspendCount = BitVector32.CreateSection(8, FormStateExCalledClosing); - private static readonly BitVector32.Section FormStateExUpdateMenuHandlesDeferred = BitVector32.CreateSection(1, FormStateExUpdateMenuHandlesSuspendCount); - private static readonly BitVector32.Section FormStateExUseMdiChildProc = BitVector32.CreateSection(1, FormStateExUpdateMenuHandlesDeferred); - private static readonly BitVector32.Section FormStateExCalledOnLoad = BitVector32.CreateSection(1, FormStateExUseMdiChildProc); - private static readonly BitVector32.Section FormStateExCalledMakeVisible = BitVector32.CreateSection(1, FormStateExCalledOnLoad); - private static readonly BitVector32.Section FormStateExCalledCreateControl = BitVector32.CreateSection(1, FormStateExCalledMakeVisible); - private static readonly BitVector32.Section FormStateExAutoSize = BitVector32.CreateSection(1, FormStateExCalledCreateControl); - private static readonly BitVector32.Section FormStateExInUpdateMdiControlStrip = BitVector32.CreateSection(1, FormStateExAutoSize); - private static readonly BitVector32.Section FormStateExShowIcon = BitVector32.CreateSection(1, FormStateExInUpdateMdiControlStrip); - private static readonly BitVector32.Section FormStateExMnemonicProcessed = BitVector32.CreateSection(1, FormStateExShowIcon); - private static readonly BitVector32.Section FormStateExInScale = BitVector32.CreateSection(1, FormStateExMnemonicProcessed); - private static readonly BitVector32.Section FormStateExInModalSizingLoop = BitVector32.CreateSection(1, FormStateExInScale); - private static readonly BitVector32.Section FormStateExSettingAutoScale = BitVector32.CreateSection(1, FormStateExInModalSizingLoop); - private static readonly BitVector32.Section FormStateExWindowBoundsWidthIsClientSize = BitVector32.CreateSection(1, FormStateExSettingAutoScale); - private static readonly BitVector32.Section FormStateExWindowBoundsHeightIsClientSize = BitVector32.CreateSection(1, FormStateExWindowBoundsWidthIsClientSize); - private static readonly BitVector32.Section FormStateExWindowClosing = BitVector32.CreateSection(1, FormStateExWindowBoundsHeightIsClientSize); + private static readonly BitVector32.Section FormStateExCalledClosing = BitVector32.CreateSection(1); + private static readonly BitVector32.Section FormStateExUpdateMenuHandlesSuspendCount = BitVector32.CreateSection(8, FormStateExCalledClosing); + private static readonly BitVector32.Section FormStateExUpdateMenuHandlesDeferred = BitVector32.CreateSection(1, FormStateExUpdateMenuHandlesSuspendCount); + private static readonly BitVector32.Section FormStateExUseMdiChildProc = BitVector32.CreateSection(1, FormStateExUpdateMenuHandlesDeferred); + private static readonly BitVector32.Section FormStateExCalledOnLoad = BitVector32.CreateSection(1, FormStateExUseMdiChildProc); + private static readonly BitVector32.Section FormStateExCalledMakeVisible = BitVector32.CreateSection(1, FormStateExCalledOnLoad); + private static readonly BitVector32.Section FormStateExCalledCreateControl = BitVector32.CreateSection(1, FormStateExCalledMakeVisible); + private static readonly BitVector32.Section FormStateExAutoSize = BitVector32.CreateSection(1, FormStateExCalledCreateControl); + private static readonly BitVector32.Section FormStateExInUpdateMdiControlStrip = BitVector32.CreateSection(1, FormStateExAutoSize); + private static readonly BitVector32.Section FormStateExShowIcon = BitVector32.CreateSection(1, FormStateExInUpdateMdiControlStrip); + private static readonly BitVector32.Section FormStateExMnemonicProcessed = BitVector32.CreateSection(1, FormStateExShowIcon); + private static readonly BitVector32.Section FormStateExInScale = BitVector32.CreateSection(1, FormStateExMnemonicProcessed); + private static readonly BitVector32.Section FormStateExInModalSizingLoop = BitVector32.CreateSection(1, FormStateExInScale); + private static readonly BitVector32.Section FormStateExSettingAutoScale = BitVector32.CreateSection(1, FormStateExInModalSizingLoop); + private static readonly BitVector32.Section FormStateExWindowBoundsWidthIsClientSize = BitVector32.CreateSection(1, FormStateExSettingAutoScale); + private static readonly BitVector32.Section FormStateExWindowBoundsHeightIsClientSize = BitVector32.CreateSection(1, FormStateExWindowBoundsWidthIsClientSize); + private static readonly BitVector32.Section FormStateExWindowClosing = BitVector32.CreateSection(1, FormStateExWindowBoundsHeightIsClientSize); private const int SizeGripSize = 16; @@ -123,58 +125,58 @@ public class Form : ContainerControl { // 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 PropAcceptButton = PropertyStore.CreateKey(); - private static readonly int PropCancelButton = PropertyStore.CreateKey(); - private static readonly int PropDefaultButton = PropertyStore.CreateKey(); - private static readonly int PropDialogOwner = PropertyStore.CreateKey(); - - private static readonly int PropMainMenu = PropertyStore.CreateKey(); - private static readonly int PropDummyMenu = PropertyStore.CreateKey(); - private static readonly int PropCurMenu = PropertyStore.CreateKey(); - private static readonly int PropMergedMenu = PropertyStore.CreateKey(); - - private static readonly int PropOwner = PropertyStore.CreateKey(); - private static readonly int PropOwnedForms = PropertyStore.CreateKey(); - private static readonly int PropMaximizedBounds = PropertyStore.CreateKey(); - private static readonly int PropOwnedFormsCount = PropertyStore.CreateKey(); - - private static readonly int PropMinTrackSizeWidth = PropertyStore.CreateKey(); - private static readonly int PropMinTrackSizeHeight = PropertyStore.CreateKey(); - private static readonly int PropMaxTrackSizeWidth = PropertyStore.CreateKey(); - private static readonly int PropMaxTrackSizeHeight = PropertyStore.CreateKey(); - - private static readonly int PropFormMdiParent = PropertyStore.CreateKey(); - private static readonly int PropActiveMdiChild = PropertyStore.CreateKey(); + private static readonly int PropAcceptButton = PropertyStore.CreateKey(); + private static readonly int PropCancelButton = PropertyStore.CreateKey(); + private static readonly int PropDefaultButton = PropertyStore.CreateKey(); + private static readonly int PropDialogOwner = PropertyStore.CreateKey(); + + private static readonly int PropMainMenu = PropertyStore.CreateKey(); + private static readonly int PropDummyMenu = PropertyStore.CreateKey(); + private static readonly int PropCurMenu = PropertyStore.CreateKey(); + private static readonly int PropMergedMenu = PropertyStore.CreateKey(); + + private static readonly int PropOwner = PropertyStore.CreateKey(); + private static readonly int PropOwnedForms = PropertyStore.CreateKey(); + private static readonly int PropMaximizedBounds = PropertyStore.CreateKey(); + private static readonly int PropOwnedFormsCount = PropertyStore.CreateKey(); + + private static readonly int PropMinTrackSizeWidth = PropertyStore.CreateKey(); + private static readonly int PropMinTrackSizeHeight = PropertyStore.CreateKey(); + private static readonly int PropMaxTrackSizeWidth = PropertyStore.CreateKey(); + private static readonly int PropMaxTrackSizeHeight = PropertyStore.CreateKey(); + + private static readonly int PropFormMdiParent = PropertyStore.CreateKey(); + private static readonly int PropActiveMdiChild = PropertyStore.CreateKey(); private static readonly int PropFormerlyActiveMdiChild = PropertyStore.CreateKey(); - private static readonly int PropMdiChildFocusable = PropertyStore.CreateKey(); + private static readonly int PropMdiChildFocusable = PropertyStore.CreateKey(); - private static readonly int PropMainMenuStrip = PropertyStore.CreateKey(); - private static readonly int PropMdiWindowListStrip = PropertyStore.CreateKey(); - private static readonly int PropMdiControlStrip = PropertyStore.CreateKey(); + private static readonly int PropMainMenuStrip = PropertyStore.CreateKey(); + private static readonly int PropMdiWindowListStrip = PropertyStore.CreateKey(); + private static readonly int PropMdiControlStrip = PropertyStore.CreateKey(); - private static readonly int PropOpacity = PropertyStore.CreateKey(); + private static readonly int PropOpacity = PropertyStore.CreateKey(); private static readonly int PropTransparencyKey = PropertyStore.CreateKey(); // Form per instance members // Note: Do not add anything to this list unless absolutely neccessary. - private BitVector32 formState = new BitVector32(0x21338); // magic value... all the defaults... see the ctor for details... - private BitVector32 formStateEx = new BitVector32(); + private BitVector32 formState = new BitVector32(0x21338); // magic value... all the defaults... see the ctor for details... + private BitVector32 formStateEx = new BitVector32(); - private Icon icon; - private Icon smallIcon; - private Size autoScaleBaseSize = System.Drawing.Size.Empty; - private Size minAutoSize = Size.Empty; - private Rectangle restoredWindowBounds = new Rectangle(-1, -1, -1, -1); - private BoundsSpecified restoredWindowBoundsSpecified; - private DialogResult dialogResult; - private MdiClient ctlClient; - private NativeWindow ownerWindow; - private bool rightToLeftLayout = false; + private Icon icon; + private Icon smallIcon; + private Size autoScaleBaseSize = System.Drawing.Size.Empty; + private Size minAutoSize = Size.Empty; + private Rectangle restoredWindowBounds = new Rectangle(-1, -1, -1, -1); + private BoundsSpecified restoredWindowBoundsSpecified; + private DialogResult dialogResult; + private MdiClient ctlClient; + private NativeWindow ownerWindow; + private bool rightToLeftLayout = false; - private Rectangle restoreBounds = new Rectangle(-1, -1, -1, -1); - private CloseReason closeReason = CloseReason.None; + private Rectangle restoreBounds = new Rectangle(-1, -1, -1, -1); + private CloseReason closeReason = CloseReason.None; private VisualStyleRenderer sizeGripRenderer; @@ -215,31 +217,31 @@ public Form() : base() #endif // Assert section. - Debug.Assert(formState[FormStateAllowTransparency] == 0, "Failed to set formState[FormStateAllowTransparency]"); - Debug.Assert(formState[FormStateBorderStyle] == (int)FormBorderStyle.Sizable, "Failed to set formState[FormStateBorderStyle]"); - Debug.Assert(formState[FormStateTaskBar] == 1, "Failed to set formState[FormStateTaskBar]"); - Debug.Assert(formState[FormStateControlBox] == 1, "Failed to set formState[FormStateControlBox]"); - Debug.Assert(formState[FormStateKeyPreview] == 0, "Failed to set formState[FormStateKeyPreview]"); - Debug.Assert(formState[FormStateLayered] == 0, "Failed to set formState[FormStateLayered]"); - Debug.Assert(formState[FormStateMaximizeBox] == 1, "Failed to set formState[FormStateMaximizeBox]"); - Debug.Assert(formState[FormStateMinimizeBox] == 1, "Failed to set formState[FormStateMinimizeBox]"); - Debug.Assert(formState[FormStateHelpButton] == 0, "Failed to set formState[FormStateHelpButton]"); - Debug.Assert(formState[FormStateStartPos] == (int)FormStartPosition.WindowsDefaultLocation, "Failed to set formState[FormStateStartPos]"); - Debug.Assert(formState[FormStateWindowState] == (int)FormWindowState.Normal, "Failed to set formState[FormStateWindowState]"); - Debug.Assert(formState[FormStateShowWindowOnCreate] == 0, "Failed to set formState[FormStateShowWindowOnCreate]"); - Debug.Assert(formState[FormStateAutoScaling] == 1, "Failed to set formState[FormStateAutoScaling]"); - Debug.Assert(formState[FormStateSetClientSize] == 0, "Failed to set formState[FormStateSetClientSize]"); - Debug.Assert(formState[FormStateTopMost] == 0, "Failed to set formState[FormStateTopMost]"); - Debug.Assert(formState[FormStateSWCalled] == 0, "Failed to set formState[FormStateSWCalled]"); - Debug.Assert(formState[FormStateMdiChildMax] == 0, "Failed to set formState[FormStateMdiChildMax]"); - Debug.Assert(formState[FormStateRenderSizeGrip] == 0, "Failed to set formState[FormStateRenderSizeGrip]"); - Debug.Assert(formState[FormStateSizeGripStyle] == 0, "Failed to set formState[FormStateSizeGripStyle]"); - Debug.Assert(formState[FormStateIsWindowActivated] == 0, "Failed to set formState[FormStateIsWindowActivated]"); - Debug.Assert(formState[FormStateIsTextEmpty] == 0, "Failed to set formState[FormStateIsTextEmpty]"); - Debug.Assert(formState[FormStateIsActive] == 0, "Failed to set formState[FormStateIsActive]"); - Debug.Assert(formState[FormStateIconSet] == 0, "Failed to set formState[FormStateIconSet]"); - - formStateEx[FormStateExShowIcon] = 1; + Debug.Assert(formState[FormStateAllowTransparency] == 0, "Failed to set formState[FormStateAllowTransparency]"); + Debug.Assert(formState[FormStateBorderStyle] == (int)FormBorderStyle.Sizable, "Failed to set formState[FormStateBorderStyle]"); + Debug.Assert(formState[FormStateTaskBar] == 1, "Failed to set formState[FormStateTaskBar]"); + Debug.Assert(formState[FormStateControlBox] == 1, "Failed to set formState[FormStateControlBox]"); + Debug.Assert(formState[FormStateKeyPreview] == 0, "Failed to set formState[FormStateKeyPreview]"); + Debug.Assert(formState[FormStateLayered] == 0, "Failed to set formState[FormStateLayered]"); + Debug.Assert(formState[FormStateMaximizeBox] == 1, "Failed to set formState[FormStateMaximizeBox]"); + Debug.Assert(formState[FormStateMinimizeBox] == 1, "Failed to set formState[FormStateMinimizeBox]"); + Debug.Assert(formState[FormStateHelpButton] == 0, "Failed to set formState[FormStateHelpButton]"); + Debug.Assert(formState[FormStateStartPos] == (int)FormStartPosition.WindowsDefaultLocation, "Failed to set formState[FormStateStartPos]"); + Debug.Assert(formState[FormStateWindowState] == (int)FormWindowState.Normal, "Failed to set formState[FormStateWindowState]"); + Debug.Assert(formState[FormStateShowWindowOnCreate] == 0, "Failed to set formState[FormStateShowWindowOnCreate]"); + Debug.Assert(formState[FormStateAutoScaling] == 1, "Failed to set formState[FormStateAutoScaling]"); + Debug.Assert(formState[FormStateSetClientSize] == 0, "Failed to set formState[FormStateSetClientSize]"); + Debug.Assert(formState[FormStateTopMost] == 0, "Failed to set formState[FormStateTopMost]"); + Debug.Assert(formState[FormStateSWCalled] == 0, "Failed to set formState[FormStateSWCalled]"); + Debug.Assert(formState[FormStateMdiChildMax] == 0, "Failed to set formState[FormStateMdiChildMax]"); + Debug.Assert(formState[FormStateRenderSizeGrip] == 0, "Failed to set formState[FormStateRenderSizeGrip]"); + Debug.Assert(formState[FormStateSizeGripStyle] == 0, "Failed to set formState[FormStateSizeGripStyle]"); + Debug.Assert(formState[FormStateIsWindowActivated] == 0, "Failed to set formState[FormStateIsWindowActivated]"); + Debug.Assert(formState[FormStateIsTextEmpty] == 0, "Failed to set formState[FormStateIsTextEmpty]"); + Debug.Assert(formState[FormStateIsActive] == 0, "Failed to set formState[FormStateIsActive]"); + Debug.Assert(formState[FormStateIconSet] == 0, "Failed to set formState[FormStateIconSet]"); + + formStateEx[FormStateExShowIcon] = 1; SetState(STATE_VISIBLE, false); SetState(STATE_TOPLEVEL, true); @@ -267,12 +269,16 @@ public Form() : base() DefaultValue(null), SRDescription(nameof(SR.FormAcceptButtonDescr)) ] - public IButtonControl AcceptButton { - get { + public IButtonControl AcceptButton + { + get + { return (IButtonControl)Properties.GetObject(PropAcceptButton); } - set { - if (AcceptButton != value) { + set + { + if (AcceptButton != value) + { Properties.SetObject(PropAcceptButton, value); UpdateDefaultButton(); @@ -284,7 +290,7 @@ public IButtonControl AcceptButton { } */ } - } + } } /// @@ -332,7 +338,7 @@ internal bool Active InnerMostActiveContainerControl.FocusActiveControlInternal(); } - + OnActivated(EventArgs.Empty); } else @@ -347,12 +353,15 @@ internal bool Active /// /// Gets the currently active form for this application. /// - public static Form ActiveForm { - get { + public static Form ActiveForm + { + get + { IntPtr hwnd = UnsafeNativeMethods.GetForegroundWindow(); Control c = Control.FromHandle(hwnd); - if (c != null && c is Form) { - return(Form)c; + if (c != null && c is Form) + { + return (Form)c; } return null; } @@ -369,8 +378,10 @@ public static Form ActiveForm { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.FormActiveMDIChildDescr)) ] - public Form ActiveMdiChild { - get { + public Form ActiveMdiChild + { + get + { Form mdiChild = ActiveMdiChildInternal; // We keep the active mdi child in the cached in the property store; when changing its value @@ -379,15 +390,18 @@ public Form ActiveMdiChild { // (to properly handle menu merging among other things) rendering the cache out-of-date; the problem // arises when the user has an event handler that is raised during this process; in that case we ask // Windows for it (see ActiveMdiChildFromWindows). - - if( mdiChild == null ){ + + if (mdiChild == null) + { // If this.MdiClient != null it means this.IsMdiContainer == true. - if( this.ctlClient != null && this.ctlClient.IsHandleCreated){ + if (this.ctlClient != null && this.ctlClient.IsHandleCreated) + { IntPtr hwnd = this.ctlClient.SendMessage(Interop.WindowMessages.WM_MDIGETACTIVE, 0, 0); mdiChild = Control.FromHandle(hwnd) as Form; } } - if( mdiChild != null && mdiChild.Visible && mdiChild.Enabled ){ + if (mdiChild != null && mdiChild.Visible && mdiChild.Enabled) + { return mdiChild; } return null; @@ -397,12 +411,15 @@ public Form ActiveMdiChild { /// /// Property to be used internally. See comments a on ActiveMdiChild property. /// - internal Form ActiveMdiChildInternal{ - get{ + internal Form ActiveMdiChildInternal + { + get + { return (Form)Properties.GetObject(PropActiveMdiChild); } - set{ + set + { Properties.SetObject(PropActiveMdiChild, value); } } @@ -433,24 +450,31 @@ private Form FormerlyActiveMdiChild DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlAllowTransparencyDescr)) ] - public bool AllowTransparency { - get { + public bool AllowTransparency + { + get + { return formState[FormStateAllowTransparency] != 0; } - set { + set + { if (value != (formState[FormStateAllowTransparency] != 0) && - OSFeature.Feature.IsPresent(OSFeature.LayeredWindows)) { + OSFeature.Feature.IsPresent(OSFeature.LayeredWindows)) + { formState[FormStateAllowTransparency] = (value ? 1 : 0); formState[FormStateLayered] = formState[FormStateAllowTransparency]; UpdateStyles(); - if (!value) { - if (Properties.ContainsObject(PropOpacity)) { + if (!value) + { + if (Properties.ContainsObject(PropOpacity)) + { Properties.SetObject(PropOpacity, (object)1.0f); } - if (Properties.ContainsObject(PropTransparencyKey)) { + if (Properties.ContainsObject(PropTransparencyKey)) + { Properties.SetObject(PropTransparencyKey, Color.Empty); } UpdateLayered(); @@ -474,37 +498,44 @@ public bool AllowTransparency { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public bool AutoScale { - get { + public bool AutoScale + { + get + { return formState[FormStateAutoScaling] != 0; } - set { + set + { formStateEx[FormStateExSettingAutoScale] = 1; - try { - if (value) { + try + { + if (value) + { formState[FormStateAutoScaling] = 1; // if someone insists on auto scaling, // force the new property back to none so they // don't compete. AutoScaleMode = AutoScaleMode.None; - + } - else { + else + { formState[FormStateAutoScaling] = 0; } } - finally { + finally + { formStateEx[FormStateExSettingAutoScale] = 0; } } } -// Our STRONG recommendation to customers is to upgrade to AutoScaleDimensions -// however, since this is generated by default in Everett, and there's not a 1:1 mapping of -// the old to the new, we are un-obsoleting the setter for AutoScaleBaseSize only. + // Our STRONG recommendation to customers is to upgrade to AutoScaleDimensions + // however, since this is generated by default in Everett, and there's not a 1:1 mapping of + // the old to the new, we are un-obsoleting the setter for AutoScaleBaseSize only. #pragma warning disable 618 /// /// The base size used for autoscaling. The AutoScaleBaseSize is used @@ -518,16 +549,20 @@ public bool AutoScale { Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public virtual Size AutoScaleBaseSize { - get { - if (autoScaleBaseSize.IsEmpty) { + public virtual Size AutoScaleBaseSize + { + get + { + if (autoScaleBaseSize.IsEmpty) + { SizeF real = GetAutoScaleSize(Font); return new Size((int)Math.Round(real.Width), (int)Math.Round(real.Height)); } return autoScaleBaseSize; } - set { + set + { // Only allow the set when not in designmode, this prevents us from // preserving an old value. The form design should prevent this for // us by shadowing this property, so we just assert that the designer @@ -549,11 +584,14 @@ public virtual Size AutoScaleBaseSize { [ Localizable(true) ] - public override bool AutoScroll { - get { return base.AutoScroll;} + public override bool AutoScroll + { + get { return base.AutoScroll; } - set { - if (value) { + set + { + if (value) + { IsMdiContainer = false; } base.AutoScroll = value; @@ -564,12 +602,16 @@ public override bool AutoScroll { // just in case someone parents a Form to a container control. [Browsable(true), EditorBrowsable(EditorBrowsableState.Always), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] - public override bool AutoSize { + public override bool AutoSize + { get { return formStateEx[FormStateExAutoSize] != 0; } - set { - if (value != AutoSize) { + set + { + if (value != AutoSize) + { formStateEx[FormStateExAutoSize] = value ? 1 : 0; - if (!AutoSize) { + if (!AutoSize) + { minAutoSize = Size.Empty; // If we just disabled AutoSize, restore the original size. this.Size = CommonProperties.GetSpecifiedBounds(this).Size; @@ -601,25 +643,32 @@ public override bool AutoSize { DefaultValue(AutoSizeMode.GrowOnly), Localizable(true) ] - public AutoSizeMode AutoSizeMode { - get { + public AutoSizeMode AutoSizeMode + { + get + { return GetAutoSizeMode(); } - set { + set + { - if (!ClientUtils.IsEnumValid(value, (int)value, (int)AutoSizeMode.GrowAndShrink, (int)AutoSizeMode.GrowOnly)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)AutoSizeMode.GrowAndShrink, (int)AutoSizeMode.GrowOnly)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AutoSizeMode)); } - - if (GetAutoSizeMode() != value) { + + if (GetAutoSizeMode() != value) + { SetAutoSizeMode(value); Control toLayout = DesignMode || ParentInternal == null ? this : ParentInternal; - if(toLayout != null) { + if (toLayout != 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(toLayout.LayoutEngine == DefaultLayout.Instance) { + if (toLayout.LayoutEngine == DefaultLayout.Instance) + { toLayout.LayoutEngine.InitLayout(this, BoundsSpecified.Size); } LayoutTransaction.DoLayout(toLayout, this, PropertyNames.AutoSize); @@ -635,11 +684,14 @@ public AutoSizeMode AutoSizeMode { Browsable(true), EditorBrowsable(EditorBrowsableState.Always), ] - public override AutoValidate AutoValidate { - get { + public override AutoValidate AutoValidate + { + get + { return base.AutoValidate; } - set { + set + { base.AutoValidate = value; } } @@ -648,7 +700,8 @@ public override AutoValidate AutoValidate { Browsable(true), EditorBrowsable(EditorBrowsableState.Always), ] - public new event EventHandler AutoValidateChanged { + public new event EventHandler AutoValidateChanged + { add => base.AutoValidateChanged += value; remove => base.AutoValidateChanged -= value; } @@ -657,8 +710,10 @@ public override AutoValidate AutoValidate { /// The background color of this control. This is an ambient property and /// will always return a non-null value. /// - public override Color BackColor { - get { + public override Color BackColor + { + get + { // Forms should not inherit BackColor from their parent, // particularly if the parent is an MDIClient. Color c = RawBackColor; // inheritedProperties.BackColor @@ -668,43 +723,56 @@ public override Color BackColor { return DefaultBackColor; } - set { + set + { base.BackColor = value; } } - private bool CalledClosing { - get{ + private bool CalledClosing + { + get + { return formStateEx[FormStateExCalledClosing] != 0; } - set{ + set + { formStateEx[FormStateExCalledClosing] = (value ? 1 : 0); } } - private bool CalledCreateControl { - get{ + private bool CalledCreateControl + { + get + { return formStateEx[FormStateExCalledCreateControl] != 0; } - set{ + set + { formStateEx[FormStateExCalledCreateControl] = (value ? 1 : 0); } } - private bool CalledMakeVisible { - get{ + private bool CalledMakeVisible + { + get + { return formStateEx[FormStateExCalledMakeVisible] != 0; } - set{ + set + { formStateEx[FormStateExCalledMakeVisible] = (value ? 1 : 0); } } - private bool CalledOnLoad { - get{ + private bool CalledOnLoad + { + get + { return formStateEx[FormStateExCalledOnLoad] != 0; } - set{ + set + { formStateEx[FormStateExCalledOnLoad] = (value ? 1 : 0); } } @@ -776,14 +844,18 @@ public FormBorderStyle FormBorderStyle DefaultValue(null), SRDescription(nameof(SR.FormCancelButtonDescr)) ] - public IButtonControl CancelButton { - get { + public IButtonControl CancelButton + { + get + { return (IButtonControl)Properties.GetObject(PropCancelButton); } - set { + set + { Properties.SetObject(PropCancelButton, value); - if (value != null && value.DialogResult == DialogResult.None) { + if (value != null && value.DialogResult == DialogResult.None) + { value.DialogResult = DialogResult.Cancel; } } @@ -795,14 +867,17 @@ public IButtonControl CancelButton { /// /// [ - Localizable(true), + Localizable(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible) ] - new public Size ClientSize { - get { + new public Size ClientSize + { + get + { return base.ClientSize; } - set { + set + { base.ClientSize = value; } } @@ -828,8 +903,10 @@ public bool ControlBox /// Retrieves the CreateParams used to create the window. /// If a subclass overrides this function, it must call the base implementation. /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; if (this.IsHandleCreated && (this.WindowStyle & NativeMethods.WS_DISABLED) != 0) @@ -844,12 +921,14 @@ protected override CreateParams CreateParams { cp.Style &= (~NativeMethods.WS_DISABLED); } - if (TopLevel && (formState[FormStateLayered] != 0)) { + if (TopLevel && (formState[FormStateLayered] != 0)) + { cp.ExStyle |= NativeMethods.WS_EX_LAYERED; } IWin32Window dialogOwner = (IWin32Window)Properties.GetObject(PropDialogOwner); - if (dialogOwner != null) { + if (dialogOwner != null) + { cp.Parent = Control.GetSafeHandle(dialogOwner); } @@ -857,7 +936,8 @@ protected override CreateParams CreateParams { FillInCreateParamsWindowState(cp); FillInCreateParamsBorderIcons(cp); - if (formState[FormStateTaskBar] != 0) { + if (formState[FormStateTaskBar] != 0) + { cp.ExStyle |= NativeMethods.WS_EX_APPWINDOW; } @@ -870,43 +950,51 @@ protected override CreateParams CreateParams { cp.ExStyle |= NativeMethods.WS_EX_DLGMODALFRAME; } - if (IsMdiChild) { + if (IsMdiChild) + { if (Visible && (WindowState == FormWindowState.Maximized - || WindowState == FormWindowState.Normal)) { + || WindowState == FormWindowState.Normal)) + { Form formMdiParent = (Form)Properties.GetObject(PropFormMdiParent); Form form = formMdiParent.ActiveMdiChildInternal; if (form != null - && form.WindowState == FormWindowState.Maximized) { + && form.WindowState == FormWindowState.Maximized) + { cp.Style |= NativeMethods.WS_MAXIMIZE; formState[FormStateWindowState] = (int)FormWindowState.Maximized; SetState(STATE_SIZELOCKEDBYOS, true); } } - if (formState[FormStateMdiChildMax] != 0) { + if (formState[FormStateMdiChildMax] != 0) + { cp.Style |= NativeMethods.WS_MAXIMIZE; } cp.ExStyle |= NativeMethods.WS_EX_MDICHILD; } - if (TopLevel || IsMdiChild) { + if (TopLevel || IsMdiChild) + { FillInCreateParamsStartPosition(cp); // Delay setting to visible until after the handle gets created // to allow applyClientSize to adjust the size before displaying // the form. // - if ((cp.Style & NativeMethods.WS_VISIBLE) != 0) { + if ((cp.Style & NativeMethods.WS_VISIBLE) != 0) + { formState[FormStateShowWindowOnCreate] = 1; cp.Style &= (~NativeMethods.WS_VISIBLE); } - else { + else + { formState[FormStateShowWindowOnCreate] = 0; } } - if (RightToLeft == RightToLeft.Yes && RightToLeftLayout == true) { + if (RightToLeft == RightToLeft.Yes && RightToLeftLayout == true) + { //We want to turn on mirroring for Form explicitly. cp.ExStyle |= NativeMethods.WS_EX_LAYOUTRTL | NativeMethods.WS_EX_NOINHERITLAYOUT; //Don't need these styles when mirroring is turned on. @@ -916,23 +1004,29 @@ protected override CreateParams CreateParams { } } - internal CloseReason CloseReason { + internal CloseReason CloseReason + { get { return closeReason; } set { closeReason = value; } } /// /// The default icon used by the Form. This is the standard "windows forms" icon. /// - internal static Icon DefaultIcon { - get { + internal static Icon DefaultIcon + { + get + { // Avoid locking if the value is filled in... // - if (defaultIcon == null) { - lock(internalSyncObject) { + if (defaultIcon == null) + { + lock (internalSyncObject) + { // Once we grab the lock, we re-check the value to avoid a // race condition. // - if (defaultIcon == null) { + if (defaultIcon == null) + { defaultIcon = new Icon(typeof(Form), "wfc"); } } @@ -941,8 +1035,10 @@ internal static Icon DefaultIcon { } } - protected override ImeMode DefaultImeMode { - get { + protected override ImeMode DefaultImeMode + { + get + { return ImeMode.NoControl; } } @@ -951,8 +1047,10 @@ protected override ImeMode DefaultImeMode { /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(300, 300); } } @@ -966,8 +1064,10 @@ protected override Size DefaultSize { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.FormDesktopBoundsDescr)) ] - public Rectangle DesktopBounds { - get { + public Rectangle DesktopBounds + { + get + { Rectangle screen = SystemInformation.WorkingArea; Rectangle bounds = Bounds; bounds.X -= screen.X; @@ -975,7 +1075,8 @@ public Rectangle DesktopBounds { return bounds; } - set { + set + { SetDesktopBounds(value.X, value.Y, value.Width, value.Height); } } @@ -989,8 +1090,10 @@ public Rectangle DesktopBounds { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.FormDesktopLocationDescr)) ] - public Point DesktopLocation { - get { + public Point DesktopLocation + { + get + { Rectangle screen = SystemInformation.WorkingArea; Point loc = Location; loc.X -= screen.X; @@ -998,7 +1101,8 @@ public Point DesktopLocation { return loc; } - set { + set + { SetDesktopLocation(value.X, value.Y); } } @@ -1012,12 +1116,15 @@ public Point DesktopLocation { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.FormDialogResultDescr)) ] - public DialogResult DialogResult { - get { + public DialogResult DialogResult + { + get + { return dialogResult; } - set { + set + { //valid values are 0x0 to 0x7 if (!ClientUtils.IsEnumValid(value, (int)value, (int)DialogResult.None, (int)DialogResult.No)) { @@ -1028,8 +1135,10 @@ public DialogResult DialogResult { } } - internal override bool HasMenu { - get { + internal override bool HasMenu + { + get + { bool hasMenu = false; // Verify that the menu actually contains items so that any @@ -1037,7 +1146,8 @@ internal override bool HasMenu { // Note that Windows will not draw a menu bar for a menu that does not contain // any items. Menu menu = Menu; - if (TopLevel && menu != null && menu.ItemCount > 0) { + if (TopLevel && menu != null && menu.ItemCount > 0) + { hasMenu = true; } return hasMenu; @@ -1055,16 +1165,21 @@ internal override bool HasMenu { DefaultValue(false), SRDescription(nameof(SR.FormHelpButtonDescr)) ] - public bool HelpButton { - get { + public bool HelpButton + { + get + { return formState[FormStateHelpButton] != 0; } - set { - if (value) { + set + { + if (value) + { formState[FormStateHelpButton] = 1; } - else { + else + { formState[FormStateHelpButton] = 0; } UpdateFormStyles(); @@ -1077,7 +1192,8 @@ public bool HelpButton { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.FormHelpButtonClickedDescr)) ] - public event CancelEventHandler HelpButtonClicked { + public event CancelEventHandler HelpButtonClicked + { add => Events.AddHandler(EVENT_HELPBUTTONCLICKED, value); remove => Events.RemoveHandler(EVENT_HELPBUTTONCLICKED, value); } @@ -1129,20 +1245,25 @@ public Icon Icon /// /// Determines whether the window is closing. /// - private bool IsClosing { - get { + private bool IsClosing + { + get + { return formStateEx[FormStateExWindowClosing] == 1; } - set { + set + { formStateEx[FormStateExWindowClosing] = value ? 1 : 0; } } // Returns a more accurate statement of whether or not the form is maximized. // during handle creation, an MDIChild is created as not maximized. - private bool IsMaximized { - get { - return (WindowState == FormWindowState.Maximized || (IsMdiChild && (formState[FormStateMdiChildMax] ==1))); + private bool IsMaximized + { + get + { + return (WindowState == FormWindowState.Maximized || (IsMdiChild && (formState[FormStateMdiChildMax] == 1))); } } @@ -1158,23 +1279,30 @@ private bool IsMaximized { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.FormIsMDIChildDescr)) ] - public bool IsMdiChild { - get { + public bool IsMdiChild + { + get + { return (Properties.GetObject(PropFormMdiParent) != null); } } // 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 { - if (this.Properties.ContainsObject(PropMdiChildFocusable)) { - return (bool) this.Properties.GetObject(PropMdiChildFocusable); + internal bool IsMdiChildFocusable + { + get + { + if (this.Properties.ContainsObject(PropMdiChildFocusable)) + { + return (bool)this.Properties.GetObject(PropMdiChildFocusable); } return false; } - set { - if (value != this.IsMdiChildFocusable) { + set + { + if (value != this.IsMdiChildFocusable) + { this.Properties.SetObject(PropMdiChildFocusable, value); } } @@ -1192,21 +1320,26 @@ internal bool IsMdiChildFocusable { DefaultValue(false), SRDescription(nameof(SR.FormIsMDIContainerDescr)) ] - public bool IsMdiContainer { - get { + public bool IsMdiContainer + { + get + { return ctlClient != null; } - set { + set + { if (value == IsMdiContainer) return; - if (value) { + if (value) + { Debug.Assert(ctlClient == null, "why isn't ctlClient null"); AllowTransparency = false; Controls.Add(new MdiClient()); } - else { + else + { Debug.Assert(ctlClient != null, "why is ctlClient null"); ActiveMdiChildInternal = null; ctlClient.Dispose(); @@ -1237,15 +1370,20 @@ public bool IsMdiContainer { DefaultValue(false), SRDescription(nameof(SR.FormKeyPreviewDescr)) ] - public bool KeyPreview { - get { + public bool KeyPreview + { + get + { return formState[FormStateKeyPreview] != 0; } - set { - if (value) { + set + { + if (value) + { formState[FormStateKeyPreview] = 1; } - else { + else + { formState[FormStateKeyPreview] = 0; } } @@ -1257,11 +1395,14 @@ public bool KeyPreview { /// /// [SettingsBindable(true)] - public new Point Location { - get { + public new Point Location + { + get + { return base.Location; } - set { + set + { base.Location = value; } } @@ -1272,12 +1413,16 @@ public bool KeyPreview { /// maximized. /// /// - protected Rectangle MaximizedBounds { - get { - return Properties.GetRectangle(PropMaximizedBounds, out _); + protected Rectangle MaximizedBounds + { + get + { + return Properties.GetRectangle(PropMaximizedBounds, out _); } - set { - if (!value.Equals( MaximizedBounds )) { + set + { + if (!value.Equals(MaximizedBounds)) + { Properties.SetRectangle(PropMaximizedBounds, value); OnMaximizedBoundsChanged(EventArgs.Empty); } @@ -1287,7 +1432,8 @@ protected Rectangle MaximizedBounds { private static readonly object EVENT_MAXIMIZEDBOUNDSCHANGED = new object(); [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.FormOnMaximizedBoundsChangedDescr))] - public event EventHandler MaximizedBoundsChanged { + public event EventHandler MaximizedBoundsChanged + { add => Events.AddHandler(EVENT_MAXIMIZEDBOUNDSCHANGED, value); remove => Events.RemoveHandler(EVENT_MAXIMIZEDBOUNDSCHANGED, value); @@ -1305,17 +1451,23 @@ public event EventHandler MaximizedBoundsChanged { RefreshProperties(RefreshProperties.Repaint), DefaultValue(typeof(Size), "0, 0") ] - public override Size MaximumSize { - get { - if (Properties.ContainsInteger(PropMaxTrackSizeWidth)) { + public override Size MaximumSize + { + get + { + if (Properties.ContainsInteger(PropMaxTrackSizeWidth)) + { return new Size(Properties.GetInteger(PropMaxTrackSizeWidth), Properties.GetInteger(PropMaxTrackSizeHeight)); } return Size.Empty; } - set { - if (!value.Equals( MaximumSize )) { + set + { + if (!value.Equals(MaximumSize)) + { - if (value.Width < 0 || value.Height < 0 ) { + if (value.Width < 0 || value.Height < 0) + { throw new ArgumentOutOfRangeException(nameof(MaximumSize)); } @@ -1324,13 +1476,16 @@ public override Size MaximumSize { // Bump minimum size if necessary // - if (!MinimumSize.IsEmpty && !value.IsEmpty) { + if (!MinimumSize.IsEmpty && !value.IsEmpty) + { - if (Properties.GetInteger(PropMinTrackSizeWidth) > value.Width) { + if (Properties.GetInteger(PropMinTrackSizeWidth) > value.Width) + { Properties.SetInteger(PropMinTrackSizeWidth, value.Width); } - if (Properties.GetInteger(PropMinTrackSizeHeight) > value.Height) { + if (Properties.GetInteger(PropMinTrackSizeHeight) > value.Height) + { Properties.SetInteger(PropMinTrackSizeHeight, value.Height); } } @@ -1338,7 +1493,8 @@ public override Size MaximumSize { // Keep form size within new limits // Size size = Size; - if (!value.IsEmpty && (size.Width > value.Width || size.Height > value.Height)) { + if (!value.IsEmpty && (size.Width > value.Width || size.Height > value.Height)) + { Size = new Size(Math.Min(size.Width, value.Width), Math.Min(size.Height, value.Height)); } @@ -1348,7 +1504,8 @@ public override Size MaximumSize { } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.FormOnMaximumSizeChangedDescr))] - public event EventHandler MaximumSizeChanged { + public event EventHandler MaximumSizeChanged + { add => Events.AddHandler(EVENT_MAXIMUMSIZECHANGED, value); remove => Events.RemoveHandler(EVENT_MAXIMUMSIZECHANGED, value); @@ -1359,13 +1516,17 @@ public event EventHandler MaximumSizeChanged { SRDescription(nameof(SR.FormMenuStripDescr)), TypeConverter(typeof(ReferenceConverter)) ] - public MenuStrip MainMenuStrip { - get { + public MenuStrip MainMenuStrip + { + get + { return (MenuStrip)Properties.GetObject(PropMainMenuStrip); } - set { + set + { Properties.SetObject(PropMainMenuStrip, value); - if (IsHandleCreated && Menu == null) { + if (IsHandleCreated && Menu == null) + { UpdateMenuHandles(); } } @@ -1375,10 +1536,12 @@ public MenuStrip MainMenuStrip { /// Hide Margin/MarginChanged /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new Padding Margin { + public new Padding Margin + { get { return base.Margin; } - set { - base.Margin = value; + set + { + base.Margin = value; } } @@ -1387,7 +1550,8 @@ public MenuStrip MainMenuStrip { /// Hide Margin/MarginChanged /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler MarginChanged { + public new event EventHandler MarginChanged + { add => base.MarginChanged += value; remove => base.MarginChanged -= value; } @@ -1405,28 +1569,36 @@ public MenuStrip MainMenuStrip { TypeConverter(typeof(ReferenceConverter)), Browsable(false), ] - public MainMenu Menu { - get { + public MainMenu Menu + { + get + { return (MainMenu)Properties.GetObject(PropMainMenu); } - set { + set + { MainMenu mainMenu = Menu; - if (mainMenu != value) { - if (mainMenu != null) { + if (mainMenu != value) + { + if (mainMenu != null) + { mainMenu.form = null; } Properties.SetObject(PropMainMenu, value); - if (value != null) { - if (value.form != null) { + if (value != null) + { + if (value.form != null) + { value.form.Menu = null; } value.form = this; } - if (formState[FormStateSetClientSize] == 1 && !IsHandleCreated) { + if (formState[FormStateSetClientSize] == 1 && !IsHandleCreated) + { ClientSize = ClientSize; } @@ -1509,7 +1681,8 @@ public override Size MinimumSize } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.FormOnMinimumSizeChangedDescr))] - public event EventHandler MinimumSizeChanged { + public event EventHandler MinimumSizeChanged + { add => Events.AddHandler(EVENT_MINIMUMSIZECHANGED, value); remove => Events.RemoveHandler(EVENT_MINIMUMSIZECHANGED, value); @@ -1524,15 +1697,20 @@ public event EventHandler MinimumSizeChanged { DefaultValue(true), SRDescription(nameof(SR.FormMaximizeBoxDescr)) ] - public bool MaximizeBox { - get { + public bool MaximizeBox + { + get + { return formState[FormStateMaximizeBox] != 0; } - set { - if (value) { + set + { + if (value) + { formState[FormStateMaximizeBox] = 1; } - else { + else + { formState[FormStateMaximizeBox] = 0; } UpdateFormStyles(); @@ -1552,12 +1730,16 @@ public bool MaximizeBox { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.FormMDIChildrenDescr)) ] - public Form[] MdiChildren { - get { - if (ctlClient != null) { + public Form[] MdiChildren + { + get + { + if (ctlClient != null) + { return ctlClient.MdiChildren; } - else { + else + { return new Form[0]; } } @@ -1570,8 +1752,10 @@ public Form[] MdiChildren { /// Represents the client area of a Multiple Document Interface (MDI) Form window, also known as the MDI child window. /// /// - internal MdiClient MdiClient { - get { + internal MdiClient MdiClient + { + get + { return this.ctlClient; } } @@ -1586,11 +1770,14 @@ internal MdiClient MdiClient { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.FormMDIParentDescr)) ] - public Form MdiParent { - get { + public Form MdiParent + { + get + { return MdiParentInternal; } - set { + set + { MdiParentInternal = value; } } @@ -1666,12 +1853,14 @@ private Form MdiParentInternal } } - private MdiWindowListStrip MdiWindowListStrip { + private MdiWindowListStrip MdiWindowListStrip + { get { return Properties.GetObject(PropMdiWindowListStrip) as MdiWindowListStrip; } set { Properties.SetObject(PropMdiWindowListStrip, value); } } - private MdiControlStrip MdiControlStrip { + private MdiControlStrip MdiControlStrip + { get { return Properties.GetObject(PropMdiControlStrip) as MdiControlStrip; } set { Properties.SetObject(PropMdiControlStrip, value); } } @@ -1688,25 +1877,33 @@ private MdiControlStrip MdiControlStrip { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.FormMergedMenuDescr)), ] - public MainMenu MergedMenu { - get { + public MainMenu MergedMenu + { + get + { return this.MergedMenuPrivate; } } - private MainMenu MergedMenuPrivate { - get { + private MainMenu MergedMenuPrivate + { + get + { Form formMdiParent = (Form)Properties.GetObject(PropFormMdiParent); - if (formMdiParent == null) return null; + if (formMdiParent == null) + return null; MainMenu mergedMenu = (MainMenu)Properties.GetObject(PropMergedMenu); - if (mergedMenu != null) return mergedMenu; + if (mergedMenu != null) + return mergedMenu; MainMenu parentMenu = formMdiParent.Menu; MainMenu mainMenu = Menu; - if (mainMenu == null) return parentMenu; - if (parentMenu == null) return mainMenu; + if (mainMenu == null) + return parentMenu; + if (parentMenu == null) + return mainMenu; // Create a menu that merges the two and save it for next time. mergedMenu = new MainMenu(); @@ -1726,15 +1923,20 @@ private MainMenu MergedMenuPrivate { DefaultValue(true), SRDescription(nameof(SR.FormMinimizeBoxDescr)) ] - public bool MinimizeBox { - get { + public bool MinimizeBox + { + get + { return formState[FormStateMinimizeBox] != 0; } - set { - if (value) { + set + { + if (value) + { formState[FormStateMinimizeBox] = 1; } - else { + else + { formState[FormStateMinimizeBox] = 0; } UpdateFormStyles(); @@ -1753,8 +1955,10 @@ public bool MinimizeBox { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.FormModalDescr)) ] - public bool Modal { - get { + public bool Modal + { + get + { return GetState(STATE_MODAL); } } @@ -1776,7 +1980,7 @@ public double Opacity { return Convert.ToDouble(opacity, CultureInfo.InvariantCulture); } - + return 1.0f; } set @@ -1824,8 +2028,10 @@ public double Opacity } } - private byte OpacityAsByte { - get { + private byte OpacityAsByte + { + get + { return (byte)(Opacity * 255.0f); } } @@ -1839,13 +2045,16 @@ private byte OpacityAsByte { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.FormOwnedFormsDescr)) ] - public Form[] OwnedForms { - get { + public Form[] OwnedForms + { + get + { Form[] ownedForms = (Form[])Properties.GetObject(PropOwnedForms); int ownedFormsCount = Properties.GetInteger(PropOwnedFormsCount); Form[] result = new Form[ownedFormsCount]; - if (ownedFormsCount > 0) { + if (ownedFormsCount > 0) + { Array.Copy(ownedForms, 0, result, 0, ownedFormsCount); } @@ -1862,16 +2071,20 @@ public Form[] OwnedForms { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.FormOwnerDescr)) ] - public Form Owner { - get { + public Form Owner + { + get + { return OwnerInternal; } - set { + set + { Form ownerOld = OwnerInternal; if (ownerOld == value) return; - if (value != null && !TopLevel) { + if (value != null && !TopLevel) + { throw new ArgumentException(SR.NonTopLevelCantHaveOwner, "value"); } @@ -1880,13 +2093,15 @@ public Form Owner { Properties.SetObject(PropOwner, null); - if (ownerOld != null) { + if (ownerOld != null) + { ownerOld.RemoveOwnedForm(this); } Properties.SetObject(PropOwner, value); - if (value != null) { + if (value != null) + { value.AddOwnedForm(this); } @@ -1894,8 +2109,10 @@ public Form Owner { } } - internal Form OwnerInternal { - get { + internal Form OwnerInternal + { + get + { return (Form)Properties.GetObject(PropOwner); } } @@ -1907,12 +2124,15 @@ internal Form OwnerInternal { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false) ] - public Rectangle RestoreBounds { - get { - if (restoreBounds.Width == -1 - && restoreBounds.Height == -1 + public Rectangle RestoreBounds + { + get + { + if (restoreBounds.Width == -1 + && restoreBounds.Height == -1 && restoreBounds.X == -1 - && restoreBounds.Y == -1) { + && restoreBounds.Y == -1) + { // Form scaling depends on this property being // set correctly. In some cases (where the size has not yet been set or // has only been set to the default, restoreBounds will remain uninitialized until the @@ -1934,28 +2154,37 @@ public Rectangle RestoreBounds { DefaultValue(false), SRDescription(nameof(SR.ControlRightToLeftLayoutDescr)) ] - public virtual bool RightToLeftLayout { - get { + public virtual bool RightToLeftLayout + { + get + { return rightToLeftLayout; } - set { - if (value != rightToLeftLayout) { + set + { + if (value != rightToLeftLayout) + { rightToLeftLayout = value; - using(new LayoutTransaction(this, this, PropertyNames.RightToLeftLayout)) { + using (new LayoutTransaction(this, this, PropertyNames.RightToLeftLayout)) + { OnRightToLeftLayoutChanged(EventArgs.Empty); } } } } - internal override Control ParentInternal { - get { + internal override Control ParentInternal + { + get + { return base.ParentInternal; } - set { - if (value != null) { + set + { + if (value != null) + { Owner = null; } base.ParentInternal = value; @@ -2008,8 +2237,10 @@ public bool ShowIcon } } - internal override int ShowParams { - get { + internal override int ShowParams + { + get + { // From MSDN: // The first time an application calls ShowWindow, it should use the WinMain function's nCmdShow parameter as its nCmdShow parameter. Subsequent calls to ShowWindow must use one of the values in the given list, instead of the one specified by the WinMain function's nCmdShow parameter. @@ -2019,7 +2250,8 @@ internal override int ShowParams { // Applications create their main window by calling CreateWindow with the WS_VISIBLE flag cleared, and later call ShowWindow with the SW_SHOW flag set to make it visible. // - switch(WindowState) { + switch (WindowState) + { case FormWindowState.Maximized: return NativeMethods.SW_SHOWMAXIMIZED; case FormWindowState.Minimized: @@ -2056,11 +2288,14 @@ protected virtual bool ShowWithoutActivation DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Localizable(false) ] - new public Size Size { - get { + new public Size Size + { + get + { return base.Size; } - set { + set + { base.Size = value; } } @@ -2075,12 +2310,16 @@ protected virtual bool ShowWithoutActivation DefaultValue(SizeGripStyle.Auto), SRDescription(nameof(SR.FormSizeGripStyleDescr)) ] - public SizeGripStyle SizeGripStyle { - get { - return(SizeGripStyle)formState[FormStateSizeGripStyle]; + public SizeGripStyle SizeGripStyle + { + get + { + return (SizeGripStyle)formState[FormStateSizeGripStyle]; } - set { - if (SizeGripStyle != value) { + set + { + if (SizeGripStyle != value) + { //do some bounds checking here // //valid values are 0x0 to 0x2 @@ -2107,11 +2346,14 @@ public SizeGripStyle SizeGripStyle { DefaultValue(FormStartPosition.WindowsDefaultLocation), SRDescription(nameof(SR.FormStartPositionDescr)) ] - public FormStartPosition StartPosition { - get { - return(FormStartPosition)formState[FormStateStartPos]; + public FormStartPosition StartPosition + { + get + { + return (FormStartPosition)formState[FormStateStartPos]; } - set { + set + { //valid values are 0x0 to 0x4 if (!ClientUtils.IsEnumValid(value, (int)value, (int)FormStartPosition.Manual, (int)FormStartPosition.CenterParent)) { @@ -2128,17 +2370,21 @@ public FormStartPosition StartPosition { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - new public int TabIndex { - get { + new public int TabIndex + { + get + { return base.TabIndex; } - set { + set + { base.TabIndex = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TabIndexChanged { + new public event EventHandler TabIndexChanged + { add => base.TabIndexChanged += value; remove => base.TabIndexChanged -= value; } @@ -2154,17 +2400,21 @@ public FormStartPosition StartPosition { DispId(NativeMethods.ActiveX.DISPID_TABSTOP), SRDescription(nameof(SR.ControlTabStopDescr)) ] - public new bool TabStop { - get { + public new bool TabStop + { + get + { return base.TabStop; } - set { + set + { base.TabStop = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler TabStopChanged { + public new event EventHandler TabStopChanged + { add => base.TabStopChanged += value; remove => base.TabStopChanged -= value; } @@ -2173,13 +2423,17 @@ public FormStartPosition StartPosition { /// For forms that are show in task bar false, this returns a HWND /// they must be parented to in order for it to work. /// - private HandleRef TaskbarOwner { - get { - if (ownerWindow == null) { + private HandleRef TaskbarOwner + { + get + { + if (ownerWindow == null) + { ownerWindow = new NativeWindow(); } - if (ownerWindow.Handle == IntPtr.Zero) { + if (ownerWindow.Handle == IntPtr.Zero) + { CreateParams cp = new CreateParams(); cp.ExStyle = NativeMethods.WS_EX_TOOLWINDOW; ownerWindow.CreateHandle(cp); @@ -2190,11 +2444,14 @@ private HandleRef TaskbarOwner { } [SettingsBindable(true)] - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; } } @@ -2206,12 +2463,16 @@ public override string Text { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool TopLevel { - get { + public bool TopLevel + { + get + { return GetTopLevel(); } - set { - if (!value && ((Form)this).IsMdiContainer && !DesignMode) { + set + { + if (!value && ((Form)this).IsMdiContainer && !DesignMode) + { throw new ArgumentException(SR.MDIContainerMustBeTopLevel, "value"); } SetTopLevel(value); @@ -2248,17 +2509,22 @@ public bool TopMost SRCategory(nameof(SR.CatWindowStyle)), SRDescription(nameof(SR.FormTransparencyKeyDescr)) ] - public Color TransparencyKey { - get { + public Color TransparencyKey + { + get + { object key = Properties.GetObject(PropTransparencyKey); - if (key != null) { + if (key != null) + { return (Color)key; } return Color.Empty; } - set { + set + { Properties.SetObject(PropTransparencyKey, value); - if (!IsMdiContainer) { + if (!IsMdiContainer) + { bool oldLayered = (formState[FormStateLayered] == 1); if (value != Color.Empty) { @@ -2280,7 +2546,8 @@ public Color TransparencyKey { // [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void SetVisibleCore(bool value) { + protected override void SetVisibleCore(bool value) + { Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Form::SetVisibleCore(" + value.ToString() + ") - " + this.Name); // If DialogResult.OK and the value == GetVisibleCore() then this code has been called either through @@ -2293,24 +2560,31 @@ protected override void SetVisibleCore(bool value) { // (!value || calledMakeVisible) is to make sure that we fall // through and execute the code below atleast once. - if (GetVisibleCore() == value && (!value || CalledMakeVisible)) { + if (GetVisibleCore() == value && (!value || CalledMakeVisible)) + { base.SetVisibleCore(value); return; } - if (value) { + if (value) + { CalledMakeVisible = true; - if (CalledCreateControl) { - if (CalledOnLoad) { + if (CalledCreateControl) + { + if (CalledOnLoad) + { // Make sure the form is in the Application.OpenForms collection - if (!Application.OpenForms.Contains(this)) { + if (!Application.OpenForms.Contains(this)) + { Application.OpenForms.Add(this); } } - else { + else + { CalledOnLoad = true; OnLoad(EventArgs.Empty); - if (dialogResult != DialogResult.None) { + if (dialogResult != DialogResult.None) + { // Don't show the dialog if the dialog result was set // in the OnLoad event. // @@ -2320,7 +2594,8 @@ protected override void SetVisibleCore(bool value) { } } - if (!IsMdiChild) { + if (!IsMdiChild) + { base.SetVisibleCore(value); // We need to force this call if we were created @@ -2328,22 +2603,27 @@ protected override void SetVisibleCore(bool value) { // it won't send a WM_SHOWWINDOW the first time it's called. // when WM_SHOWWINDOW gets called, we'll flip this bit to true // - if (0==formState[FormStateSWCalled]) { + if (0 == formState[FormStateSWCalled]) + { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.WindowMessages.WM_SHOWWINDOW, value ? 1 : 0, 0); } } - else { + else + { // Throw away any existing handle. - if (IsHandleCreated) { + if (IsHandleCreated) + { // Everett/RTM used to wrap this in an assert for AWP. DestroyHandle(); } - if (!value) { + if (!value) + { InvalidateMergedMenu(); SetState(STATE_VISIBLE, false); } - else { + else + { // The ordering is important here... Force handle creation // (getHandle) then show the window (ShowWindow) then finish @@ -2354,21 +2634,25 @@ protected override void SetVisibleCore(bool value) { // Ask the mdiClient to re-layout the controls so that any docking or // anchor settings for this mdi child window will be honored. MdiParentInternal.MdiClient.PerformLayout(); - - if (ParentInternal != null && ParentInternal.Visible) { + + if (ParentInternal != null && ParentInternal.Visible) + { SuspendLayout(); - try{ + try + { SafeNativeMethods.ShowWindow(new HandleRef(this, Handle), NativeMethods.SW_SHOW); CreateControl(); // If this form is mdichild and maximized, we need to redraw the MdiParent non-client area to // update the menu bar because we always create the window as if it were not maximized. // See comment on CreateHandle about this. - if (WindowState == FormWindowState.Maximized) { + if (WindowState == FormWindowState.Maximized) + { MdiParentInternal.UpdateWindowIcon(true); } } - finally{ + finally + { ResumeLayout(); } } @@ -2378,9 +2662,11 @@ protected override void SetVisibleCore(bool value) { //( - - if (value && !IsMdiChild && (WindowState == FormWindowState.Maximized || TopMost)) { - if (ActiveControl == null){ + + if (value && !IsMdiChild && (WindowState == FormWindowState.Maximized || TopMost)) + { + if (ActiveControl == null) + { SelectNextControl(null, true, true, true, false); } FocusActiveControlInternal(); @@ -2467,7 +2753,8 @@ internal override string WindowText /// Occurs when the form is activated in code or by the user. /// [SRCategory(nameof(SR.CatFocus)), SRDescription(nameof(SR.FormOnActivateDescr))] - public event EventHandler Activated { + public event EventHandler Activated + { add => Events.AddHandler(EVENT_ACTIVATED, value); remove => Events.RemoveHandler(EVENT_ACTIVATED, value); } @@ -2482,7 +2769,8 @@ public event EventHandler Activated { Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public event CancelEventHandler Closing { + public event CancelEventHandler Closing + { add => Events.AddHandler(EVENT_CLOSING, value); remove => Events.RemoveHandler(EVENT_CLOSING, value); } @@ -2497,7 +2785,8 @@ public event CancelEventHandler Closing { Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public event EventHandler Closed { + public event EventHandler Closed + { add => Events.AddHandler(EVENT_CLOSED, value); remove => Events.RemoveHandler(EVENT_CLOSED, value); } @@ -2507,7 +2796,8 @@ public event EventHandler Closed { /// Occurs when the form loses focus and is not the active form. /// [SRCategory(nameof(SR.CatFocus)), SRDescription(nameof(SR.FormOnDeactivateDescr))] - public event EventHandler Deactivate { + public event EventHandler Deactivate + { add => Events.AddHandler(EVENT_DEACTIVATE, value); remove => Events.RemoveHandler(EVENT_DEACTIVATE, value); } @@ -2517,7 +2807,8 @@ public event EventHandler Deactivate { /// Occurs when the form is closing. /// [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.FormOnFormClosingDescr))] - public event FormClosingEventHandler FormClosing { + public event FormClosingEventHandler FormClosing + { add => Events.AddHandler(EVENT_FORMCLOSING, value); remove => Events.RemoveHandler(EVENT_FORMCLOSING, value); } @@ -2527,7 +2818,8 @@ public event FormClosingEventHandler FormClosing { /// Occurs when the form is closed. /// [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.FormOnFormClosedDescr))] - public event FormClosedEventHandler FormClosed { + public event FormClosedEventHandler FormClosed + { add => Events.AddHandler(EVENT_FORMCLOSED, value); remove => Events.RemoveHandler(EVENT_FORMCLOSED, value); } @@ -2537,7 +2829,8 @@ public event FormClosedEventHandler FormClosed { /// Occurs before the form becomes visible. /// [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.FormOnLoadDescr))] - public event EventHandler Load { + public event EventHandler Load + { add => Events.AddHandler(EVENT_LOAD, value); remove => Events.RemoveHandler(EVENT_LOAD, value); } @@ -2547,7 +2840,8 @@ public event EventHandler Load { /// within an MDI application. /// [SRCategory(nameof(SR.CatLayout)), SRDescription(nameof(SR.FormOnMDIChildActivateDescr))] - public event EventHandler MdiChildActivate { + public event EventHandler MdiChildActivate + { add => Events.AddHandler(EVENT_MDI_CHILD_ACTIVATE, value); remove => Events.RemoveHandler(EVENT_MDI_CHILD_ACTIVATE, value); } @@ -2556,12 +2850,13 @@ public event EventHandler MdiChildActivate { /// Occurs when the menu of a form loses focus. /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.FormOnMenuCompleteDescr)), Browsable(false) ] - public event EventHandler MenuComplete { - add => Events.AddHandler(EVENT_MENUCOMPLETE, value); + public event EventHandler MenuComplete + { + add => Events.AddHandler(EVENT_MENUCOMPLETE, value); remove => Events.RemoveHandler(EVENT_MENUCOMPLETE, value); } @@ -2569,11 +2864,12 @@ public event EventHandler MenuComplete { /// Occurs when the menu of a form receives focus. /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.FormOnMenuStartDescr)), Browsable(false) ] - public event EventHandler MenuStart { + public event EventHandler MenuStart + { add => Events.AddHandler(EVENT_MENUSTART, value); remove => Events.RemoveHandler(EVENT_MENUSTART, value); } @@ -2583,7 +2879,8 @@ public event EventHandler MenuStart { /// Occurs after the input language of the form has changed. /// [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.FormOnInputLangChangeDescr))] - public event InputLanguageChangedEventHandler InputLanguageChanged { + public event InputLanguageChangedEventHandler InputLanguageChanged + { add => Events.AddHandler(EVENT_INPUTLANGCHANGE, value); remove => Events.RemoveHandler(EVENT_INPUTLANGCHANGE, value); } @@ -2594,13 +2891,15 @@ public event InputLanguageChangedEventHandler InputLanguageChanged { /// form. /// [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.FormOnInputLangChangeRequestDescr))] - public event InputLanguageChangingEventHandler InputLanguageChanging { + public event InputLanguageChangingEventHandler InputLanguageChanging + { add => Events.AddHandler(EVENT_INPUTLANGCHANGEREQUEST, value); remove => Events.RemoveHandler(EVENT_INPUTLANGCHANGEREQUEST, value); } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnRightToLeftLayoutChangedDescr))] - public event EventHandler RightToLeftLayoutChanged { + public event EventHandler RightToLeftLayoutChanged + { add => Events.AddHandler(EVENT_RIGHTTOLEFTLAYOUTCHANGED, value); remove => Events.RemoveHandler(EVENT_RIGHTTOLEFTLAYOUTCHANGED, value); } @@ -2609,7 +2908,8 @@ public event EventHandler RightToLeftLayoutChanged { /// Occurs whenever the form is first shown. /// [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.FormOnShownDescr))] - public event EventHandler Shown { + public event EventHandler Shown + { add => Events.AddHandler(EVENT_SHOWN, value); remove => Events.RemoveHandler(EVENT_SHOWN, value); } @@ -2617,12 +2917,16 @@ public event EventHandler Shown { /// /// Activates the form and gives it focus. /// - public void Activate() { - if (Visible && IsHandleCreated) { - if (IsMdiChild) { + public void Activate() + { + if (Visible && IsHandleCreated) + { + if (IsMdiChild) + { MdiParentInternal.MdiClient.SendMessage(Interop.WindowMessages.WM_MDIACTIVATE, Handle, 0); } - else { + else + { UnsafeNativeMethods.SetForegroundWindow(new HandleRef(this, Handle)); } } @@ -2672,11 +2976,13 @@ protected void ActivateMdiChild(Form form) /// Adds /// an owned form to this form. /// - public void AddOwnedForm(Form ownedForm) { + public void AddOwnedForm(Form ownedForm) + { if (ownedForm == null) return; - if (ownedForm.OwnerInternal != this) { + if (ownedForm.OwnerInternal != this) + { ownedForm.Owner = this; // NOTE: this calls AddOwnedForm again with correct owner set. return; } @@ -2685,18 +2991,22 @@ public void AddOwnedForm(Form ownedForm) { int ownedFormsCount = Properties.GetInteger(PropOwnedFormsCount); // Make sure this isn't already in the list: - for (int i=0;i < ownedFormsCount;i++) { - if (ownedForms[i]==ownedForm) { + for (int i = 0; i < ownedFormsCount; i++) + { + if (ownedForms[i] == ownedForm) + { return; } } - if (ownedForms == null) { + if (ownedForms == null) + { ownedForms = new Form[4]; Properties.SetObject(PropOwnedForms, ownedForms); } - else if (ownedForms.Length == ownedFormsCount) { - Form[] newOwnedForms = new Form[ownedFormsCount*2]; + else if (ownedForms.Length == ownedFormsCount) + { + Form[] newOwnedForms = new Form[ownedFormsCount * 2]; Array.Copy(ownedForms, 0, newOwnedForms, 0, ownedFormsCount); ownedForms = newOwnedForms; Properties.SetObject(PropOwnedForms, ownedForms); @@ -2711,7 +3021,8 @@ public void AddOwnedForm(Form ownedForm) { // Fonts) we end up making everything too small due to roundoff, // etc... solution - just don't shrink as much. // - private float AdjustScale(float scale) { + private float AdjustScale(float scale) + { // NOTE : This function is cloned in FormDocumentDesigner... remember to keep // : them in sync // @@ -2719,25 +3030,29 @@ private float AdjustScale(float scale) { // Map 0.0 - .92... increment by 0.08 // - if (scale < .92f) { + if (scale < .92f) + { return scale + 0.08f; } // Map .92 - .99 to 1.0 // - else if (scale < 1.0f) { + else if (scale < 1.0f) + { return 1.0f; } // Map 1.02... increment by 0.08 // - else if (scale > 1.01f) { + else if (scale > 1.01f) + { return scale + 0.08f; } // Map 1.0 - 1.01... no change // - else { + else + { return scale; } } @@ -2745,13 +3060,16 @@ private float AdjustScale(float scale) { /// /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void AdjustFormScrollbars(bool displayScrollbars) { - if (WindowState != FormWindowState.Minimized) { + protected override void AdjustFormScrollbars(bool displayScrollbars) + { + if (WindowState != FormWindowState.Minimized) + { base.AdjustFormScrollbars(displayScrollbars); } } - private void AdjustSystemMenu(IntPtr hmenu) { + private void AdjustSystemMenu(IntPtr hmenu) + { UpdateWindowState(); FormWindowState winState = WindowState; FormBorderStyle borderStyle = FormBorderStyle; @@ -2766,43 +3084,53 @@ private void AdjustSystemMenu(IntPtr hmenu) { bool showSize = sizableBorder && winState != FormWindowState.Minimized && winState != FormWindowState.Maximized; - if (!showMin) { + if (!showMin) + { UnsafeNativeMethods.EnableMenuItem(new HandleRef(this, hmenu), NativeMethods.SC_MINIMIZE, NativeMethods.MF_BYCOMMAND | NativeMethods.MF_GRAYED); } - else { + else + { UnsafeNativeMethods.EnableMenuItem(new HandleRef(this, hmenu), NativeMethods.SC_MINIMIZE, NativeMethods.MF_BYCOMMAND | NativeMethods.MF_ENABLED); } - if (!showMax) { + if (!showMax) + { UnsafeNativeMethods.EnableMenuItem(new HandleRef(this, hmenu), NativeMethods.SC_MAXIMIZE, NativeMethods.MF_BYCOMMAND | NativeMethods.MF_GRAYED); } - else { + else + { UnsafeNativeMethods.EnableMenuItem(new HandleRef(this, hmenu), NativeMethods.SC_MAXIMIZE, NativeMethods.MF_BYCOMMAND | NativeMethods.MF_ENABLED); } - if (!showClose) { + if (!showClose) + { UnsafeNativeMethods.EnableMenuItem(new HandleRef(this, hmenu), NativeMethods.SC_CLOSE, NativeMethods.MF_BYCOMMAND | NativeMethods.MF_GRAYED); } - else { + else + { UnsafeNativeMethods.EnableMenuItem(new HandleRef(this, hmenu), NativeMethods.SC_CLOSE, NativeMethods.MF_BYCOMMAND | NativeMethods.MF_ENABLED); } - if (!showRestore) { + if (!showRestore) + { UnsafeNativeMethods.EnableMenuItem(new HandleRef(this, hmenu), NativeMethods.SC_RESTORE, NativeMethods.MF_BYCOMMAND | NativeMethods.MF_GRAYED); } - else { + else + { UnsafeNativeMethods.EnableMenuItem(new HandleRef(this, hmenu), NativeMethods.SC_RESTORE, NativeMethods.MF_BYCOMMAND | NativeMethods.MF_ENABLED); } - if (!showSize) { + if (!showSize) + { UnsafeNativeMethods.EnableMenuItem(new HandleRef(this, hmenu), NativeMethods.SC_SIZE, NativeMethods.MF_BYCOMMAND | NativeMethods.MF_GRAYED); } - else { + else + { UnsafeNativeMethods.EnableMenuItem(new HandleRef(this, hmenu), NativeMethods.SC_SIZE, NativeMethods.MF_BYCOMMAND | NativeMethods.MF_ENABLED); } @@ -2811,8 +3139,10 @@ private void AdjustSystemMenu(IntPtr hmenu) { /// /// This forces the SystemMenu to look like we want. /// - private void AdjustSystemMenu() { - if (IsHandleCreated) { + private void AdjustSystemMenu() + { + if (IsHandleCreated) + { IntPtr hmenu = UnsafeNativeMethods.GetSystemMenu(new HandleRef(this, Handle), false); AdjustSystemMenu(hmenu); hmenu = IntPtr.Zero; @@ -2824,7 +3154,8 @@ private void AdjustSystemMenu() { /// [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This method has been deprecated. Use the ApplyAutoScaling method instead. http://go.microsoft.com/fwlink/?linkid=14202")] - protected void ApplyAutoScaling() { + protected void ApplyAutoScaling() + { Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "ApplyAutoScaling... "); Debug.Indent(); // NOTE : This function is cloned in FormDocumentDesigner... remember to keep @@ -2836,7 +3167,8 @@ protected void ApplyAutoScaling() { // two GetAutoScaleBaseSize calls only to find that they returned the same // value. // - if (!autoScaleBaseSize.IsEmpty) { + if (!autoScaleBaseSize.IsEmpty) + { Size baseVar = AutoScaleBaseSize; Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "base =" + baseVar); SizeF newVarF = GetAutoScaleSize(Font); @@ -2866,9 +3198,11 @@ protected void ApplyAutoScaling() { /// This adjusts the size of the windowRect so that the client rect is the /// correct size. /// - private void ApplyClientSize() { + private void ApplyClientSize() + { if ((FormWindowState)formState[FormStateWindowState] != FormWindowState.Normal - || !IsHandleCreated) { + || !IsHandleCreated) + { return; } @@ -2886,15 +3220,19 @@ private void ApplyClientSize() { // don't get set to the correct size. // bool adjustScroll = false; - if (formState[FormStateSetClientSize] != 0) { + if (formState[FormStateSetClientSize] != 0) + { adjustScroll = true; formState[FormStateSetClientSize] = 0; } - if (adjustScroll) { - if (hscr) { + if (adjustScroll) + { + if (hscr) + { correctClientSize.Height += SystemInformation.HorizontalScrollBarHeight; } - if (vscr) { + if (vscr) + { correctClientSize.Width += SystemInformation.VerticalScrollBarWidth; } } @@ -2910,16 +3248,19 @@ private void ApplyClientSize() { // computeWindowSize. We only do this logic if the width needs to // be adjusted to avoid double adjusting the window. // - if (correctClientSize.Width != currentClient.Width) { + if (correctClientSize.Width != currentClient.Width) + { Size correct = ComputeWindowSize(correctClientSize); // Since computeWindowSize ignores scrollbars, we must tack these on to // assure the correct size. // - if (vscr) { + if (vscr) + { correct.Width += SystemInformation.VerticalScrollBarWidth; } - if (hscr) { + if (hscr) + { correct.Height += SystemInformation.HorizontalScrollBarHeight; } bounds.Width = correct.Width; @@ -2934,7 +3275,8 @@ private void ApplyClientSize() { // account), so we just need to adjust the height by the correct // amount. // - if (correctClientSize.Height != currentClient.Height) { + if (correctClientSize.Height != currentClient.Height) + { int delta = correctClientSize.Height - currentClient.Height; bounds.Height += delta; @@ -2948,13 +3290,15 @@ private void ApplyClientSize() { /// Assigns a new parent control. Sends out the appropriate property change /// notifications for properties that are affected by the change of parent. /// - internal override void AssignParent(Control value) { + 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(PropFormMdiParent); - if (formMdiParent != null && formMdiParent.MdiClient != value) { + if (formMdiParent != null && formMdiParent.MdiClient != value) + { Properties.SetObject(PropFormMdiParent, null); } @@ -2976,8 +3320,10 @@ internal override void AssignParent(Control value) { /// Note we set a flag to determine if we've already called close or not. /// /// - internal bool CheckCloseDialog(bool closingOnly) { - if (dialogResult == DialogResult.None && Visible) { + internal bool CheckCloseDialog(bool closingOnly) + { + if (dialogResult == DialogResult.None && Visible) + { return false; } try @@ -3029,16 +3375,19 @@ internal bool CheckCloseDialog(bool closingOnly) { /// /// Closes the form. /// - public void Close() { + public void Close() + { if (GetState(STATE_CREATINGHANDLE)) throw new InvalidOperationException(string.Format(SR.ClosingWhileCreatingHandle, "Close")); - if (IsHandleCreated) { + if (IsHandleCreated) + { closeReason = CloseReason.UserClosing; SendMessage(Interop.WindowMessages.WM_CLOSE, 0, 0); } - else{ + else + { // MSDN: When a form is closed, all resources created within the object are closed and the form is disposed. // For MDI child: MdiChildren collection gets updated Dispose(); @@ -3049,7 +3398,8 @@ public void Close() { /// Computes the window size from the clientSize based on the styles /// returned from CreateParams. /// - private Size ComputeWindowSize(Size clientSize) { + private Size ComputeWindowSize(Size clientSize) + { CreateParams cp = CreateParams; return ComputeWindowSize(clientSize, cp.Style, cp.ExStyle); } @@ -3058,7 +3408,8 @@ private Size ComputeWindowSize(Size clientSize) { /// Computes the window size from the clientSize base on the specified /// window styles. This will not return the correct size if menus wrap. /// - private Size ComputeWindowSize(Size clientSize, int style, int exStyle) { + private Size ComputeWindowSize(Size clientSize, int style, int exStyle) + { NativeMethods.RECT result = new NativeMethods.RECT(0, 0, clientSize.Width, clientSize.Height); AdjustWindowRectEx(ref result, style, HasMenu, exStyle); return new Size(result.right - result.left, result.bottom - result.top); @@ -3067,7 +3418,8 @@ private Size ComputeWindowSize(Size clientSize, int style, int exStyle) { /// /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override Control.ControlCollection CreateControlsInstance() { + protected override Control.ControlCollection CreateControlsInstance() + { return new ControlCollection(this); } @@ -3075,16 +3427,20 @@ protected override Control.ControlCollection CreateControlsInstance() { /// Cleans up form state after a control has been removed. /// Package scope for Control /// - internal override void AfterControlRemoved(Control control, Control oldParent) { + internal override void AfterControlRemoved(Control control, Control oldParent) + { base.AfterControlRemoved(control, oldParent); - if (control == AcceptButton) { + if (control == AcceptButton) + { this.AcceptButton = null; } - if (control == CancelButton) { + if (control == CancelButton) + { this.CancelButton = null; } - if (control == ctlClient) { + if (control == ctlClient) + { ctlClient = null; UpdateMenuHandles(); } @@ -3096,22 +3452,27 @@ internal override void AfterControlRemoved(Control control, Control oldParent) { /// it must call the base implementation. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void CreateHandle() { + protected override void CreateHandle() + { // In the windows MDI code we have to suspend menu // 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(PropFormMdiParent); - if (form != null){ + if (form != null) + { form.SuspendUpdateMenuHandles(); } - try { + try + { // If the child is created before the MDI parent we can // get Win32 exceptions as the MDI child is parked to the parking window. - if (IsMdiChild && MdiParentInternal.IsHandleCreated) { + if (IsMdiChild && MdiParentInternal.IsHandleCreated) + { MdiClient mdiClient = MdiParentInternal.MdiClient; - if (mdiClient != null && !mdiClient.IsHandleCreated) { + if (mdiClient != null && !mdiClient.IsHandleCreated) + { mdiClient.CreateControl(); } } @@ -3123,7 +3484,8 @@ protected override void CreateHandle() { // We really should find out what causes this... but I can't find it... // if (IsMdiChild - && (FormWindowState)formState[FormStateWindowState] == FormWindowState.Maximized) { + && (FormWindowState)formState[FormStateWindowState] == FormWindowState.Maximized) + { // This is the reason why we see the blue borders // when creating a maximized mdi child, unfortunately we cannot fix this now... @@ -3133,7 +3495,8 @@ protected override void CreateHandle() { formState[FormStateWindowState] = (int)FormWindowState.Maximized; formState[FormStateMdiChildMax] = 0; } - else { + else + { base.CreateHandle(); } @@ -3142,10 +3505,12 @@ protected override void CreateHandle() { AdjustSystemMenu(); - if ((FormStartPosition)formState[FormStateStartPos] != FormStartPosition.WindowsDefaultBounds) { + if ((FormStartPosition)formState[FormStateStartPos] != FormStartPosition.WindowsDefaultBounds) + { ApplyClientSize(); } - if (formState[FormStateShowWindowOnCreate] == 1) { + if (formState[FormStateShowWindowOnCreate] == 1) + { Visible = true; } @@ -3157,24 +3522,28 @@ protected override void CreateHandle() { // In order for a window not to have a taskbar entry, it must // be owned. // - if (!ShowInTaskbar && OwnerInternal == null && TopLevel) { + if (!ShowInTaskbar && OwnerInternal == null && TopLevel) + { UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_HWNDPARENT, TaskbarOwner); // Make sure the large icon is set so the ALT+TAB icon // reflects the real icon of the application Icon icon = Icon; - if (icon != null && TaskbarOwner.Handle != IntPtr.Zero) { - UnsafeNativeMethods.SendMessage(TaskbarOwner, Interop.WindowMessages.WM_SETICON, NativeMethods.ICON_BIG, icon.Handle); + if (icon != null && TaskbarOwner.Handle != IntPtr.Zero) + { + UnsafeNativeMethods.SendMessage(TaskbarOwner, Interop.WindowMessages.WM_SETICON, NativeMethods.ICON_BIG, icon.Handle); } } - if (formState[FormStateTopMost] != 0) { + if (formState[FormStateTopMost] != 0) + { TopMost = true; } } - finally { - if (form != null) + finally + { + if (form != null) form.ResumeUpdateMenuHandles(); // We need to reset the styles in case Windows tries to set us up @@ -3186,14 +3555,17 @@ protected override void CreateHandle() { // Deactivates active MDI child and temporarily marks it as unfocusable, // so that WM_SETFOCUS sent to MDIClient does not activate that child. - private void DeactivateMdiChild() { + private void DeactivateMdiChild() + { Form activeMdiChild = ActiveMdiChildInternal; - if (null != activeMdiChild) { + if (null != activeMdiChild) + { Form mdiParent = activeMdiChild.MdiParentInternal; activeMdiChild.Active = false; activeMdiChild.IsMdiChildFocusable = false; - if (!activeMdiChild.IsClosing) { + if (!activeMdiChild.IsClosing) + { FormerlyActiveMdiChild = activeMdiChild; } // Enter/Leave events on child controls are raised from the ActivateMdiChild method, usually when another @@ -3202,14 +3574,17 @@ private void DeactivateMdiChild() { // in the MSDN doc that the MdiChildActivate event is raised when an mdi child is activated or closed - // we actually meant the last mdi child is closed). bool fakeActivation = true; - foreach(Form mdiChild in mdiParent.MdiChildren ){ - if( mdiChild != this && mdiChild.Visible ){ + foreach (Form mdiChild in mdiParent.MdiChildren) + { + if (mdiChild != this && mdiChild.Visible) + { fakeActivation = false; // more than one mdi child visible. break; } } - if( fakeActivation ){ + if (fakeActivation) + { mdiParent.ActivateMdiChild(null); } @@ -3235,14 +3610,18 @@ private void DeactivateMdiChild() { [ EditorBrowsable(EditorBrowsableState.Advanced) ] - protected override void DefWndProc(ref Message m) { - if (ctlClient != null && ctlClient.IsHandleCreated && ctlClient.ParentInternal == this){ + protected override void DefWndProc(ref Message m) + { + if (ctlClient != null && ctlClient.IsHandleCreated && ctlClient.ParentInternal == this) + { m.Result = UnsafeNativeMethods.DefFrameProc(m.HWnd, ctlClient.Handle, m.Msg, m.WParam, m.LParam); } - else if (0 != formStateEx[FormStateExUseMdiChildProc]){ + else if (0 != formStateEx[FormStateExUseMdiChildProc]) + { m.Result = UnsafeNativeMethods.DefMDIChildProc(m.HWnd, m.Msg, m.WParam, m.LParam); } - else { + else + { base.DefWndProc(ref m); } } @@ -3251,34 +3630,44 @@ protected override void DefWndProc(ref Message m) { /// Releases all the system resources associated with the Form. If a subclass /// overrides this function, it must call the base implementation. /// - protected override void Dispose(bool disposing) { - if (disposing) { + protected override void Dispose(bool disposing) + { + if (disposing) + { CalledOnLoad = false; CalledMakeVisible = false; CalledCreateControl = false; - if (Properties.ContainsObject(PropAcceptButton)) Properties.SetObject(PropAcceptButton, null); - if (Properties.ContainsObject(PropCancelButton)) Properties.SetObject(PropCancelButton, null); - if (Properties.ContainsObject(PropDefaultButton)) Properties.SetObject(PropDefaultButton, null); - if (Properties.ContainsObject(PropActiveMdiChild)) Properties.SetObject(PropActiveMdiChild, null); + if (Properties.ContainsObject(PropAcceptButton)) + Properties.SetObject(PropAcceptButton, null); + if (Properties.ContainsObject(PropCancelButton)) + Properties.SetObject(PropCancelButton, null); + if (Properties.ContainsObject(PropDefaultButton)) + Properties.SetObject(PropDefaultButton, null); + if (Properties.ContainsObject(PropActiveMdiChild)) + Properties.SetObject(PropActiveMdiChild, null); - if (MdiWindowListStrip != null){ + if (MdiWindowListStrip != null) + { MdiWindowListStrip.Dispose(); MdiWindowListStrip = null; } - if (MdiControlStrip != null){ + if (MdiControlStrip != null) + { MdiControlStrip.Dispose(); MdiControlStrip = null; } - if (MainMenuStrip != null) { + if (MainMenuStrip != null) + { // should NOT call dispose on MainMenuStrip - it's likely NOT to be in the form's control collection. MainMenuStrip = null; } - + Form owner = (Form)Properties.GetObject(PropOwner); - if (owner != null) { + if (owner != null) + { owner.RemoveOwnedForm(this); Properties.SetObject(PropOwner, null); } @@ -3286,14 +3675,17 @@ protected override void Dispose(bool disposing) { Form[] ownedForms = (Form[])Properties.GetObject(PropOwnedForms); int ownedFormsCount = Properties.GetInteger(PropOwnedFormsCount); - for (int i = ownedFormsCount-1 ; i >= 0; i--) { - if (ownedForms[i] != null) { + for (int i = ownedFormsCount - 1; i >= 0; i--) + { + if (ownedForms[i] != null) + { // it calls remove and removes itself. ownedForms[i].Dispose(); } } - if (smallIcon != null) { + if (smallIcon != null) + { smallIcon.Dispose(); smallIcon = null; } @@ -3304,12 +3696,14 @@ protected override void Dispose(bool disposing) { MainMenu mainMenu = Menu; // We should only dispose this form's menus! - if (mainMenu != null && mainMenu.ownerForm == this) { + if (mainMenu != null && mainMenu.ownerForm == this) + { mainMenu.Dispose(); Properties.SetObject(PropMainMenu, null); } - if (Properties.GetObject(PropCurMenu) != null) { + if (Properties.GetObject(PropCurMenu) != null) + { Properties.SetObject(PropCurMenu, null); } @@ -3317,21 +3711,25 @@ protected override void Dispose(bool disposing) { MainMenu dummyMenu = (MainMenu)Properties.GetObject(PropDummyMenu); - if (dummyMenu != null) { + if (dummyMenu != null) + { dummyMenu.Dispose(); Properties.SetObject(PropDummyMenu, null); } MainMenu mergedMenu = (MainMenu)Properties.GetObject(PropMergedMenu); - if (mergedMenu != null) { - if (mergedMenu.ownerForm == this || mergedMenu.form == null) { + if (mergedMenu != null) + { + if (mergedMenu.ownerForm == this || mergedMenu.form == null) + { mergedMenu.Dispose(); } Properties.SetObject(PropMergedMenu, null); } } - else { + else + { base.Dispose(disposing); } } @@ -3483,7 +3881,7 @@ private void FillInCreateParamsStartPosition(CreateParams cp) { desktop = Screen.FromPoint(Control.MousePosition); } - + Rectangle screenRect = desktop.WorkingArea; // if, we're maximized, then don't set the x & y coordinates (they're @ (0,0) ) if (WindowState != FormWindowState.Maximized) @@ -3518,7 +3916,7 @@ private void FillInCreateParamsWindowState(CreateParams cp) /// private protected override bool FocusInternal() { - Debug.Assert( IsHandleCreated, "Attempt to set focus to a form that has not yet created its handle." ); + Debug.Assert(IsHandleCreated, "Attempt to set focus to a form that has not yet created its handle."); // If this form is a MdiChild, then we need to set the focus differently. if (IsMdiChild) @@ -3537,28 +3935,33 @@ private protected override bool FocusInternal() // used to measure font height. // So we don't have to localize it. ] - public static SizeF GetAutoScaleSize(Font font) { + public static SizeF GetAutoScaleSize(Font font) + { float height = font.Height; float width = 9.0f; - try { - using( Graphics graphics = Graphics.FromHwndInternal(IntPtr.Zero /*screen*/) ) { + try + { + using (Graphics graphics = Graphics.FromHwndInternal(IntPtr.Zero /*screen*/)) + { string magicString = "The quick brown fox jumped over the lazy dog."; double magicNumber = 44.549996948242189; // chosen for compatibility with older versions of windows forms, but approximately magicString.Length float stringWidth = graphics.MeasureString(magicString, font).Width; - width = (float) (stringWidth / magicNumber); + width = (float)(stringWidth / magicNumber); } } - catch { // We may get an bogus OutOfMemoryException - // (which is a critical exception - according to ClientUtils.IsCriticalException()) - // from GDI+. So we can't use ClientUtils.IsCriticalException here and rethrow. + catch + { // We may get an bogus OutOfMemoryException + // (which is a critical exception - according to ClientUtils.IsCriticalException()) + // from GDI+. So we can't use ClientUtils.IsCriticalException here and rethrow. } return new SizeF(width, height); } - internal override Size GetPreferredSizeCore(Size proposedSize) { + internal override Size GetPreferredSizeCore(Size proposedSize) + { // @@ -3622,8 +4025,10 @@ private void CallShownEvent() /// /// Override since CanProcessMnemonic is overriden too (base.CanSelectCore calls CanProcessMnemonic). /// - internal override bool CanSelectCore() { - if( !GetStyle(ControlStyles.Selectable) || !this.Enabled || !this.Visible) { + internal override bool CanSelectCore() + { + if (!GetStyle(ControlStyles.Selectable) || !this.Enabled || !this.Visible) + { return false; } return true; @@ -3633,8 +4038,10 @@ internal override bool CanSelectCore() { /// When an MDI form is hidden it means its handle has not yet been created or has been destroyed (see /// SetVisibleCore). If the handle is recreated, the form will be made visible which should be avoided. /// - internal bool CanRecreateHandle() { - if( IsMdiChild ){ + internal bool CanRecreateHandle() + { + if (IsMdiChild) + { // During changing visibility, it is possible that the style returns true for visible but the handle has // not yet been created, add a check for both. return GetState(STATE_VISIBLE) && IsHandleCreated; @@ -3645,12 +4052,14 @@ internal bool CanRecreateHandle() { /// /// Overriden to handle MDI mnemonic processing properly. /// - internal override bool CanProcessMnemonic() { + internal override bool CanProcessMnemonic() + { #if DEBUG TraceCanProcessMnemonic(); #endif // If this is a Mdi child form, child controls should process mnemonics only if this is the active mdi child. - if (this.IsMdiChild && (formStateEx[FormStateExMnemonicProcessed] == 1 || this != this.MdiParentInternal.ActiveMdiChildInternal || this.WindowState == FormWindowState.Minimized)){ + if (this.IsMdiChild && (formStateEx[FormStateExMnemonicProcessed] == 1 || this != this.MdiParentInternal.ActiveMdiChildInternal || this.WindowState == FormWindowState.Minimized)) + { return false; } @@ -3660,25 +4069,32 @@ internal override bool CanProcessMnemonic() { /// /// Overriden to handle MDI mnemonic processing properly. /// - protected internal override bool ProcessMnemonic(char charCode) { + protected internal override bool ProcessMnemonic(char charCode) + { // MDI container form has at least one control, the MDI client which contains the MDI children. We need // to allow the MDI children process the mnemonic before any other control in the MDI container (like // menu items or any other control). - if( base.ProcessMnemonic( charCode ) ){ + if (base.ProcessMnemonic(charCode)) + { return true; } - if( this.IsMdiContainer ){ + if (this.IsMdiContainer) + { // ContainerControl have already processed the active MDI child for us (if any) in the call above, // now process remaining controls (non-mdi children). - if( this.Controls.Count > 1 ){ // Ignore the MdiClient control - for( int index = 0; index < this.Controls.Count; index++ ){ + if (this.Controls.Count > 1) + { // Ignore the MdiClient control + for (int index = 0; index < this.Controls.Count; index++) + { Control ctl = this.Controls[index]; - if( ctl is MdiClient ){ + if (ctl is MdiClient) + { continue; } - if( ctl.ProcessMnemonic( charCode ) ){ + if (ctl.ProcessMnemonic(charCode)) + { return true; } } @@ -3693,14 +4109,17 @@ protected internal override bool ProcessMnemonic(char charCode) { /// /// Centers the dialog to its parent. /// - protected void CenterToParent() { - if (TopLevel) { + protected void CenterToParent() + { + if (TopLevel) + { Point p = new Point(); Size s = Size; IntPtr ownerHandle = IntPtr.Zero; ownerHandle = UnsafeNativeMethods.GetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_HWNDPARENT); - if (ownerHandle != IntPtr.Zero) { + if (ownerHandle != IntPtr.Zero) + { Screen desktop = Screen.FromHandle(ownerHandle); Rectangle screenRect = desktop.WorkingArea; NativeMethods.RECT ownerRect = new NativeMethods.RECT(); @@ -3721,7 +4140,8 @@ protected void CenterToParent() { Location = p; } - else { + else + { CenterToScreen(); } } @@ -3733,27 +4153,33 @@ protected void CenterToParent() { /// it will try the HWND owner of the form, and finally this will /// center the form on the same monitor as the mouse cursor. /// - protected void CenterToScreen() { + protected void CenterToScreen() + { Point p = new Point(); Screen desktop = null; - if (OwnerInternal != null) { + if (OwnerInternal != null) + { desktop = Screen.FromControl(OwnerInternal); } - else { + else + { IntPtr hWndOwner = IntPtr.Zero; - if (TopLevel) { + if (TopLevel) + { hWndOwner = UnsafeNativeMethods.GetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_HWNDPARENT); } - if (hWndOwner != IntPtr.Zero) { + if (hWndOwner != IntPtr.Zero) + { desktop = Screen.FromHandle(hWndOwner); } - else { + else + { desktop = Screen.FromPoint(Control.MousePosition); } } Rectangle screenRect = desktop.WorkingArea; - p.X = Math.Max(screenRect.X,screenRect.X + (screenRect.Width - Width)/2); - p.Y = Math.Max(screenRect.Y,screenRect.Y + (screenRect.Height - Height)/2); + p.X = Math.Max(screenRect.X, screenRect.X + (screenRect.Width - Width) / 2); + p.Y = Math.Max(screenRect.Y, screenRect.Y + (screenRect.Height - Height) / 2); Location = p; } @@ -3761,19 +4187,23 @@ protected void CenterToScreen() { /// Invalidates the merged menu, forcing the menu to be recreated if /// needed again. /// - private void InvalidateMergedMenu() { + private void InvalidateMergedMenu() + { // here, we just set the merged menu to null (indicating that the menu structure // needs to be rebuilt). Then, we signal the parent to updated its menus. - if (Properties.ContainsObject(PropMergedMenu)) { + if (Properties.ContainsObject(PropMergedMenu)) + { MainMenu menu = Properties.GetObject(PropMergedMenu) as MainMenu; - if (menu != null && menu.ownerForm == this) { + if (menu != null && menu.ownerForm == this) + { menu.Dispose(); } Properties.SetObject(PropMergedMenu, null); } Form parForm = ParentFormInternal; - if (parForm != null) { + if (parForm != null) + { parForm.MenuChanged(0, parForm.Menu); } } @@ -3782,41 +4212,51 @@ private void InvalidateMergedMenu() { /// Arranges the Multiple Document Interface /// (MDI) child forms according to value. /// - public void LayoutMdi(MdiLayout value) { - if (ctlClient == null){ + public void LayoutMdi(MdiLayout value) + { + if (ctlClient == null) + { return; } ctlClient.LayoutMdi(value); } // Package scope for menu interop - internal void MenuChanged(int change, Menu menu) { + internal void MenuChanged(int change, Menu menu) + { Form parForm = ParentFormInternal; - if (parForm != null && this == parForm.ActiveMdiChildInternal) { + if (parForm != null && this == parForm.ActiveMdiChildInternal) + { parForm.MenuChanged(change, menu); return; } - switch (change) { + switch (change) + { case Windows.Forms.Menu.CHANGE_ITEMS: case Windows.Forms.Menu.CHANGE_MERGE: - if (ctlClient == null || !ctlClient.IsHandleCreated) { + if (ctlClient == null || !ctlClient.IsHandleCreated) + { if (menu == Menu && change == Windows.Forms.Menu.CHANGE_ITEMS) UpdateMenuHandles(); break; } // Tell the children to toss their mergedMenu. - if (IsHandleCreated) { + if (IsHandleCreated) + { UpdateMenuHandles(null, false); } Control.ControlCollection children = ctlClient.Controls; - for (int i = children.Count; i-- > 0;) { + for (int i = children.Count; i-- > 0;) + { Control ctl = children[i]; - if (ctl is Form && ctl.Properties.ContainsObject(PropMergedMenu)) { + if (ctl is Form && ctl.Properties.ContainsObject(PropMergedMenu)) + { MainMenu mainMenu = ctl.Properties.GetObject(PropMergedMenu) as MainMenu; - if (mainMenu != null && mainMenu.ownerForm == ctl) { + if (mainMenu != null && mainMenu.ownerForm == ctl) + { mainMenu.Dispose(); } ctl.Properties.SetObject(PropMergedMenu, null); @@ -3826,12 +4266,14 @@ internal void MenuChanged(int change, Menu menu) { UpdateMenuHandles(); break; case Windows.Forms.Menu.CHANGE_VISIBLE: - if (menu == Menu || (this.ActiveMdiChildInternal != null && menu == this.ActiveMdiChildInternal.Menu)) { + if (menu == Menu || (this.ActiveMdiChildInternal != null && menu == this.ActiveMdiChildInternal.Menu)) + { UpdateMenuHandles(); } break; case Windows.Forms.Menu.CHANGE_MDI: - if (ctlClient != null && ctlClient.IsHandleCreated) { + if (ctlClient != null && ctlClient.IsHandleCreated) + { UpdateMenuHandles(); } break; @@ -3842,27 +4284,32 @@ internal void MenuChanged(int change, Menu menu) { /// The activate event is fired when the form is activated. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnActivated(EventArgs e) { + protected virtual void OnActivated(EventArgs e) + { EventHandler handler = (EventHandler)Events[EVENT_ACTIVATED]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// /// Override of AutoScaleModeChange method from ContainerControl. We use /// this to keep our own AutoScale property in sync. /// - internal override void OnAutoScaleModeChanged() { + internal override void OnAutoScaleModeChanged() + { base.OnAutoScaleModeChanged(); // Obsolete code required here for backwards compat #pragma warning disable 618 - if (formStateEx[FormStateExSettingAutoScale] != 1) { + if (formStateEx[FormStateExSettingAutoScale] != 1) + { AutoScale = false; } #pragma warning restore 618 } - protected override void OnBackgroundImageChanged(EventArgs e) { + protected override void OnBackgroundImageChanged(EventArgs e) + { base.OnBackgroundImageChanged(e); if (IsMdiContainer) { @@ -3872,7 +4319,8 @@ protected override void OnBackgroundImageChanged(EventArgs e) { } } - protected override void OnBackgroundImageLayoutChanged(EventArgs e) { + protected override void OnBackgroundImageLayoutChanged(EventArgs e) + { base.OnBackgroundImageLayoutChanged(e); if (IsMdiContainer) { @@ -3886,18 +4334,22 @@ protected override void OnBackgroundImageLayoutChanged(EventArgs e) { /// The Closing event is fired when the form is closed. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnClosing(CancelEventArgs e) { + protected virtual void OnClosing(CancelEventArgs e) + { CancelEventHandler handler = (CancelEventHandler)Events[EVENT_CLOSING]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// /// The Closed event is fired when the form is closed. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnClosed(EventArgs e) { + protected virtual void OnClosed(EventArgs e) + { EventHandler handler = (EventHandler)Events[EVENT_CLOSED]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } @@ -3905,32 +4357,38 @@ protected virtual void OnClosed(EventArgs e) { /// The Closing event is fired before the form is closed. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnFormClosing(FormClosingEventArgs e) { + protected virtual void OnFormClosing(FormClosingEventArgs e) + { FormClosingEventHandler handler = (FormClosingEventHandler)Events[EVENT_FORMCLOSING]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// /// The Closed event is fired when the form is closed. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnFormClosed(FormClosedEventArgs e) { + protected virtual void OnFormClosed(FormClosedEventArgs e) + { //Remove the form from Application.OpenForms (nothing happens if isn't present) Application.OpenForms.Remove(this); FormClosedEventHandler handler = (FormClosedEventHandler)Events[EVENT_FORMCLOSED]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// /// Raises the CreateControl event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnCreateControl() { + protected override void OnCreateControl() + { CalledCreateControl = true; base.OnCreateControl(); - if (CalledMakeVisible && !CalledOnLoad) { + if (CalledMakeVisible && !CalledOnLoad) + { CalledOnLoad = true; OnLoad(EventArgs.Empty); } @@ -3940,43 +4398,53 @@ protected override void OnCreateControl() { /// Raises the Deactivate event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnDeactivate(EventArgs e) { + protected virtual void OnDeactivate(EventArgs e) + { EventHandler handler = (EventHandler)Events[EVENT_DEACTIVATE]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// /// Raises the EnabledChanged event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnEnabledChanged(EventArgs e) { + protected override void OnEnabledChanged(EventArgs e) + { base.OnEnabledChanged(e); - if (!DesignMode && Enabled && Active) { + if (!DesignMode && Enabled && Active) + { // Make sure we activate the active control. Control activeControl = ActiveControl; - if( activeControl == null ){ + if (activeControl == null) + { SelectNextControl(this, true, true, true, true); } - else{ + else + { FocusActiveControlInternal(); } } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnEnter(EventArgs e) { + protected override void OnEnter(EventArgs e) + { base.OnEnter(e); // Enter events are not raised on mdi child form controls on form Enabled. - if( IsMdiChild ){ + if (IsMdiChild) + { UpdateFocusedControl(); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnFontChanged(EventArgs e) { - if (DesignMode) { + protected override void OnFontChanged(EventArgs e) + { + if (DesignMode) + { UpdateAutoScaleBaseSize(); } base.OnFontChanged(e); @@ -3988,7 +4456,8 @@ protected override void OnFontChanged(EventArgs e) { /// Call base.OnHandleCreated first. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { formStateEx[FormStateExUseMdiChildProc] = (IsMdiChild && Visible) ? 1 : 0; base.OnHandleCreated(e); UpdateLayered(); @@ -4013,18 +4482,22 @@ protected override void OnHandleDestroyed(EventArgs e) /// Handles the event that a helpButton is clicked /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnHelpButtonClicked(CancelEventArgs e) { + protected virtual void OnHelpButtonClicked(CancelEventArgs e) + { CancelEventHandler handler = (CancelEventHandler)Events[EVENT_HELPBUTTONCLICKED]; - if (handler != null) { - handler(this,e); + if (handler != null) + { + handler(this, e); } } - protected override void OnLayout(LayoutEventArgs levent) { + protected override void OnLayout(LayoutEventArgs levent) + { // Typically forms are either top level or parented to an MDIClient area. // In either case, forms a responsible for managing their own size. - if(AutoSize /*&& DesignMode*/) { + if (AutoSize /*&& DesignMode*/) + { // If AutoSized, set the Form to the maximum of its preferredSize or the user // specified size. Size prefSize = this.PreferredSize; @@ -4035,7 +4508,8 @@ protected override void OnLayout(LayoutEventArgs levent) { Size adjustedSize = AutoSizeMode == AutoSizeMode.GrowAndShrink ? prefSize : LayoutUtils.UnionSizes(prefSize, Size); IArrangedElement form = this as IArrangedElement; - if (form != null) { + if (form != null) + { form.SetBounds(new Rectangle(this.Left, this.Top, adjustedSize.Width, adjustedSize.Height), BoundsSpecified.None); } } @@ -4046,17 +4520,20 @@ protected override void OnLayout(LayoutEventArgs levent) { /// The Load event is fired before the form becomes visible for the first time. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnLoad(EventArgs e) { + protected virtual void OnLoad(EventArgs e) + { //First - add the form to Application.OpenForms Application.OpenForms.Add(this); - if (Application.UseWaitCursor) { + if (Application.UseWaitCursor) + { this.UseWaitCursor = true; } // subhag: This will apply AutoScaling to the form just // before the form becomes visible. // - if (formState[FormStateAutoScaling] == 1 && !DesignMode) { + if (formState[FormStateAutoScaling] == 1 && !DesignMode) + { // Turn off autoscaling so we don't do this on every handle // creation. // @@ -4065,11 +4542,11 @@ protected virtual void OnLoad(EventArgs e) { #pragma warning disable 618 ApplyAutoScaling(); #pragma warning restore 618 - + } -/* - /// + /* + /// @@ -4082,18 +4559,21 @@ protected virtual void OnLoad(EventArgs e) { -*/ + */ // Also, at this time we can now locate the form the the correct // area of the screen. We must do this after applying any // autoscaling. // - if (GetState(STATE_MODAL)) { + if (GetState(STATE_MODAL)) + { FormStartPosition startPos = (FormStartPosition)formState[FormStateStartPos]; - if (startPos == FormStartPosition.CenterParent) { + if (startPos == FormStartPosition.CenterParent) + { CenterToParent(); } - else if (startPos == FormStartPosition.CenterScreen) { + else if (startPos == FormStartPosition.CenterScreen) + { CenterToScreen(); } } @@ -4101,10 +4581,11 @@ protected virtual void OnLoad(EventArgs e) { // There is no good way to explain this event except to say // that it's just another name for OnControlCreated. EventHandler handler = (EventHandler)Events[EVENT_LOAD]; - if (handler != null) { + if (handler != null) + { string text = Text; - handler(this,e); + handler(this, e); // It seems that if you set a window style during the onload @@ -4115,7 +4596,8 @@ protected virtual void OnLoad(EventArgs e) { // This seems to manifiest itself in changes to the window caption, // and changes to the control box and help. - foreach (Control c in Controls) { + foreach (Control c in Controls) + { c.Invalidate(); } } @@ -4128,26 +4610,32 @@ protected virtual void OnLoad(EventArgs e) { } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnMaximizedBoundsChanged(EventArgs e) { + protected virtual void OnMaximizedBoundsChanged(EventArgs e) + { EventHandler eh = Events[EVENT_MAXIMIZEDBOUNDSCHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnMaximumSizeChanged(EventArgs e) { + protected virtual void OnMaximumSizeChanged(EventArgs e) + { EventHandler eh = Events[EVENT_MAXIMUMSIZECHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnMinimumSizeChanged(EventArgs e) { + protected virtual void OnMinimumSizeChanged(EventArgs e) + { EventHandler eh = Events[EVENT_MINIMUMSIZECHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } @@ -4157,9 +4645,11 @@ protected virtual void OnMinimumSizeChanged(EventArgs e) { /// event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnInputLanguageChanged(InputLanguageChangedEventArgs e) { + protected virtual void OnInputLanguageChanged(InputLanguageChangedEventArgs e) + { InputLanguageChangedEventHandler handler = (InputLanguageChangedEventHandler)Events[EVENT_INPUTLANGCHANGE]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// @@ -4167,16 +4657,20 @@ protected virtual void OnInputLanguageChanged(InputLanguageChangedEventArgs e) { /// event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnInputLanguageChanging(InputLanguageChangingEventArgs e) { + protected virtual void OnInputLanguageChanging(InputLanguageChangingEventArgs e) + { InputLanguageChangingEventHandler handler = (InputLanguageChangingEventHandler)Events[EVENT_INPUTLANGCHANGEREQUEST]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnVisibleChanged(EventArgs e) { + protected override void OnVisibleChanged(EventArgs e) + { UpdateRenderSizeGrip(); Form mdiParent = MdiParentInternal; - if (mdiParent != null) { + if (mdiParent != null) + { mdiParent.UpdateMdiWindowListStrip(); } base.OnVisibleChanged(e); @@ -4190,7 +4684,8 @@ protected override void OnVisibleChanged(EventArgs e) { && Visible && (AcceptButton != null) && UnsafeNativeMethods.SystemParametersInfo(NativeMethods.SPI_GETSNAPTODEFBUTTON, 0, ref data, 0) - && data) { + && data) + { Control button = AcceptButton as Control; NativeMethods.POINT ptToSnap = new NativeMethods.POINT( @@ -4198,7 +4693,8 @@ protected override void OnVisibleChanged(EventArgs e) { button.Top + button.Height / 2); UnsafeNativeMethods.ClientToScreen(new HandleRef(this, Handle), ptToSnap); - if (!button.IsWindowObscured) { + if (!button.IsWindowObscured) + { Cursor.Position = new Point(ptToSnap.x, ptToSnap.y); } } @@ -4208,11 +4704,13 @@ protected override void OnVisibleChanged(EventArgs e) { /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnMdiChildActivate(EventArgs e) { + protected virtual void OnMdiChildActivate(EventArgs e) + { UpdateMenuHandles(); UpdateToolStrip(); EventHandler handler = (EventHandler)Events[EVENT_MDI_CHILD_ACTIVATE]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// @@ -4222,39 +4720,47 @@ protected virtual void OnMdiChildActivate(EventArgs e) { protected virtual void OnMenuStart(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_MENUSTART]; - handler?.Invoke(this,e); + handler?.Invoke(this, e); } /// /// Raises the MenuComplete event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnMenuComplete(EventArgs e) { + protected virtual void OnMenuComplete(EventArgs e) + { EventHandler handler = (EventHandler)Events[EVENT_MENUCOMPLETE]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// /// Raises the Paint event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnPaint(PaintEventArgs e) { + protected override void OnPaint(PaintEventArgs e) + { base.OnPaint(e); - if (formState[FormStateRenderSizeGrip] != 0) { + if (formState[FormStateRenderSizeGrip] != 0) + { Size sz = ClientSize; - if (Application.RenderWithVisualStyles) { - if (sizeGripRenderer == null) { + if (Application.RenderWithVisualStyles) + { + if (sizeGripRenderer == null) + { sizeGripRenderer = new VisualStyleRenderer(VisualStyleElement.Status.Gripper.Normal); } sizeGripRenderer.DrawBackground(e.Graphics, new Rectangle(sz.Width - SizeGripSize, sz.Height - SizeGripSize, SizeGripSize, SizeGripSize)); } - else { + else + { ControlPaint.DrawSizeGrip(e.Graphics, BackColor, sz.Width - SizeGripSize, sz.Height - SizeGripSize, SizeGripSize, SizeGripSize); } } - - if (IsMdiContainer) { + + if (IsMdiContainer) + { e.Graphics.FillRectangle(SystemBrushes.AppWorkspace, ClientRectangle); } } @@ -4263,9 +4769,11 @@ protected override void OnPaint(PaintEventArgs e) { /// Raises the Resize event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnResize(EventArgs e) { + protected override void OnResize(EventArgs e) + { base.OnResize(e); - if (formState[FormStateRenderSizeGrip] != 0) { + if (formState[FormStateRenderSizeGrip] != 0) + { Invalidate(); } } @@ -4275,28 +4783,35 @@ protected override void OnResize(EventArgs e) { /// [Browsable(true), EditorBrowsable(EditorBrowsableState.Always), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] - protected virtual void OnDpiChanged(DpiChangedEventArgs e) { - if (e.DeviceDpiNew != e.DeviceDpiOld) { + protected virtual void OnDpiChanged(DpiChangedEventArgs e) + { + if (e.DeviceDpiNew != e.DeviceDpiOld) + { CommonProperties.xClearAllPreferredSizeCaches(this); // call any additional handlers ((DpiChangedEventHandler)Events[EVENT_DPI_CHANGED])?.Invoke(this, e); - if (!e.Cancel) { + if (!e.Cancel) + { float factor = (float)e.DeviceDpiNew / (float)e.DeviceDpiOld; SuspendAllLayout(this); - try { + try + { SafeNativeMethods.SetWindowPos(new HandleRef(this, HandleInternal), NativeMethods.NullHandleRef, e.SuggestedRectangle.X, e.SuggestedRectangle.Y, e.SuggestedRectangle.Width, e.SuggestedRectangle.Height, NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE); - if (AutoScaleMode != AutoScaleMode.Font) { + if (AutoScaleMode != AutoScaleMode.Font) + { Font = new Font(this.Font.FontFamily, this.Font.Size * factor, this.Font.Style); FormDpiChanged(factor); } - else { + else + { ScaleFont(factor); FormDpiChanged(factor); } } - finally { + finally + { // We want to perform layout for dpi-changed HDpi improvements - setting the second parameter to 'true' ResumeAllLayout(this, true); } @@ -4310,7 +4825,8 @@ protected virtual void OnDpiChanged(DpiChangedEventArgs e) { /// /// [SRCategory(nameof(SR.CatLayout)), SRDescription(nameof(SR.FormOnDpiChangedDescr))] - public event DpiChangedEventHandler DpiChanged { + public event DpiChangedEventHandler DpiChanged + { add => Events.AddHandler(EVENT_DPI_CHANGED, value); remove => Events.RemoveHandler(EVENT_DPI_CHANGED, value); } @@ -4318,12 +4834,13 @@ public event DpiChangedEventHandler DpiChanged { /// /// Handles the WM_DPICHANGED message /// - private void WmDpiChanged(ref Message m) { + private void WmDpiChanged(ref Message m) + { DefWndProc(ref m); DpiChangedEventArgs e = new DpiChangedEventArgs(deviceDpi, m); deviceDpi = e.DeviceDpiNew; - + OnDpiChanged(e); } @@ -4331,7 +4848,8 @@ private void WmDpiChanged(ref Message m) { /// Allows derived form to handle WM_GETDPISCALEDSIZE message. /// [Browsable(true), EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual bool OnGetDpiScaledSize(int deviceDpiOld, int deviceDpiNew, ref Size desiredSize) { + protected virtual bool OnGetDpiScaledSize(int deviceDpiOld, int deviceDpiNew, ref Size desiredSize) + { return false; // scale linearly } @@ -4346,52 +4864,65 @@ protected virtual bool OnGetDpiScaledSize(int deviceDpiOld, int deviceDpiNew, re /// is the desired height of the window. A return value of zero indicates that the app does not /// want any special behavior and the candidate rectangle will be computed linearly. /// - private void WmGetDpiScaledSize(ref Message m) { + private void WmGetDpiScaledSize(ref Message m) + { DefWndProc(ref m); - + Size desiredSize = new Size(); - if (OnGetDpiScaledSize(deviceDpi, NativeMethods.Util.SignedLOWORD(m.WParam), ref desiredSize)) { - m.Result = (IntPtr)(unchecked((Size.Height & 0xFFFF) << 16) | (Size.Width & 0xFFFF)); - } else { + if (OnGetDpiScaledSize(deviceDpi, NativeMethods.Util.SignedLOWORD(m.WParam), ref desiredSize)) + { + m.Result = (IntPtr)(unchecked((Size.Height & 0xFFFF) << 16) | (Size.Width & 0xFFFF)); + } + else + { m.Result = IntPtr.Zero; } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnRightToLeftLayoutChanged(EventArgs e) { - if (GetAnyDisposingInHierarchy()) { + protected virtual void OnRightToLeftLayoutChanged(EventArgs e) + { + if (GetAnyDisposingInHierarchy()) + { return; } - if (RightToLeft == RightToLeft.Yes) { + if (RightToLeft == RightToLeft.Yes) + { RecreateHandle(); } EventHandler eh = Events[EVENT_RIGHTTOLEFTLAYOUTCHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } // Want to do this after we fire the event. - if (RightToLeft == RightToLeft.Yes) { - foreach(Control c in this.Controls) { + if (RightToLeft == RightToLeft.Yes) + { + foreach (Control c in this.Controls) + { c.RecreateHandleCore(); } } - + } /// /// Thi event fires whenever the form is first shown. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnShown(EventArgs e) { + protected virtual void OnShown(EventArgs e) + { EventHandler handler = (EventHandler)Events[EVENT_SHOWN]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnTextChanged(EventArgs e) { + protected override void OnTextChanged(EventArgs e) + { base.OnTextChanged(e); // If there is no control box, there should only be a title bar if text != "". @@ -4406,7 +4937,8 @@ protected override void OnTextChanged(EventArgs e) { /// Simulates a InputLanguageChanged event. Used by Control to forward events /// to the parent form. /// - internal void PerformOnInputLanguageChanged(InputLanguageChangedEventArgs iplevent) { + internal void PerformOnInputLanguageChanged(InputLanguageChangedEventArgs iplevent) + { OnInputLanguageChanged(iplevent); } @@ -4414,7 +4946,8 @@ internal void PerformOnInputLanguageChanged(InputLanguageChangedEventArgs ipleve /// Simulates a InputLanguageChanging event. Used by Control to forward /// events to the parent form. /// - internal void PerformOnInputLanguageChanging(InputLanguageChangingEventArgs iplcevent) { + internal void PerformOnInputLanguageChanging(InputLanguageChangingEventArgs iplcevent) + { OnInputLanguageChanging(iplcevent); } @@ -4422,11 +4955,14 @@ internal void PerformOnInputLanguageChanging(InputLanguageChangingEventArgs iplc /// Processes a command key. Overrides Control.processCmdKey() to provide /// additional handling of main menu command keys and Mdi accelerators. /// - protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { - if (base.ProcessCmdKey(ref msg, keyData)) return true; + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) + { + if (base.ProcessCmdKey(ref msg, keyData)) + return true; MainMenu curMenu = (MainMenu)Properties.GetObject(PropCurMenu); - if (curMenu != null && curMenu.ProcessCmdKey(ref msg, keyData)) return true; + if (curMenu != null && curMenu.ProcessCmdKey(ref msg, keyData)) + return true; // Process MDI accelerator keys. @@ -4439,7 +4975,8 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { win32Message.hwnd = msg.HWnd; if (ctlClient != null && ctlClient.Handle != IntPtr.Zero && - UnsafeNativeMethods.TranslateMDISysAccel(ctlClient.Handle, ref win32Message)) { + UnsafeNativeMethods.TranslateMDISysAccel(ctlClient.Handle, ref win32Message)) + { retValue = true; } @@ -4458,17 +4995,22 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { /// The method performs no processing on keys that include the ALT or /// CONTROL modifiers. /// - protected override bool ProcessDialogKey(Keys keyData) { - if ((keyData & (Keys.Alt | Keys.Control)) == Keys.None) { + protected override bool ProcessDialogKey(Keys keyData) + { + if ((keyData & (Keys.Alt | Keys.Control)) == Keys.None) + { Keys keyCode = (Keys)keyData & Keys.KeyCode; IButtonControl button; - switch (keyCode) { + switch (keyCode) + { case Keys.Return: button = (IButtonControl)Properties.GetObject(PropDefaultButton); - if (button != null) { + if (button != null) + { //PerformClick now checks for validationcancelled... - if (button is Control) { + if (button is Control) + { button.PerformClick(); } return true; @@ -4476,7 +5018,8 @@ protected override bool ProcessDialogKey(Keys keyData) { break; case Keys.Escape: button = (IButtonControl)Properties.GetObject(PropCancelButton); - if (button != null) { + if (button != null) + { // In order to keep the behavior in sync with native // and MFC dialogs, we want to not give the cancel button // the focus on Escape. If we do, we end up with giving it @@ -4498,24 +5041,29 @@ protected override bool ProcessDialogKey(Keys keyData) { /// Processes a dialog character For a MdiChild. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override bool ProcessDialogChar(char charCode) { + protected override bool ProcessDialogChar(char charCode) + { #if DEBUG Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "Form.ProcessDialogChar [" + charCode.ToString() + "]"); #endif // If we're the top-level form or control, we need to do the mnemonic handling // - if (this.IsMdiChild && charCode != ' ') { - if (ProcessMnemonic(charCode)) { + if (this.IsMdiChild && charCode != ' ') + { + if (ProcessMnemonic(charCode)) + { return true; } // ContainerControl calls ProcessMnemonic starting from the active MdiChild form (this) // so let's flag it as processed. formStateEx[FormStateExMnemonicProcessed] = 1; - try{ + try + { return base.ProcessDialogChar(charCode); } - finally{ + finally + { formStateEx[FormStateExMnemonicProcessed] = 0; } } @@ -4525,22 +5073,26 @@ protected override bool ProcessDialogChar(char charCode) { } - protected override bool ProcessKeyPreview(ref Message m) { + protected override bool ProcessKeyPreview(ref Message m) + { if (formState[FormStateKeyPreview] != 0 && ProcessKeyEventArgs(ref m)) return true; return base.ProcessKeyPreview(ref m); } - protected override bool ProcessTabKey(bool forward) { + protected override bool ProcessTabKey(bool forward) + { if (SelectNextControl(ActiveControl, forward, true, true, true)) return true; // I've added a special case for UserControls because they shouldn't cycle back to the // beginning if they don't have a parent form, such as when they're on an ActiveXBridge. - if (IsMdiChild || ParentFormInternal == null) { + if (IsMdiChild || ParentFormInternal == null) + { bool selected = SelectNextControl(null, forward, true, true, false); - if (selected) { + if (selected) + { return true; } } @@ -4552,8 +5104,10 @@ protected override bool ProcessTabKey(bool forward) { /// /// Raises the FormClosed event for this form when Application.Exit is called. /// - internal void RaiseFormClosedOnAppExit() { - if (!Modal) { + internal void RaiseFormClosedOnAppExit() + { + if (!Modal) + { /* This is not required because Application.ExitPrivate() loops through all forms in the Application.OpenForms collection // Fire FormClosed event on all MDI children if (IsMdiContainer) { @@ -4569,11 +5123,14 @@ 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.GetInteger(PropOwnedFormsCount); - if (ownedFormsCount > 0) { + if (ownedFormsCount > 0) + { Form[] ownedForms = this.OwnedForms; FormClosedEventArgs fce = new FormClosedEventArgs(CloseReason.FormOwnerClosing); - for (int i = ownedFormsCount-1 ; i >= 0; i--) { - if (ownedForms[i] != null && !Application.OpenForms.Contains(ownedForms[i])) { + for (int i = ownedFormsCount - 1; i >= 0; i--) + { + if (ownedForms[i] != null && !Application.OpenForms.Contains(ownedForms[i])) + { ownedForms[i].OnFormClosed(fce); } } @@ -4586,10 +5143,12 @@ internal void RaiseFormClosedOnAppExit() { /// Raises the FormClosing event for this form when Application.Exit is called. /// Returns e.Cancel returned by the event handler. /// - internal bool RaiseFormClosingOnAppExit() { + internal bool RaiseFormClosingOnAppExit() + { FormClosingEventArgs e = new FormClosingEventArgs(CloseReason.ApplicationExitCall, false); // e.Cancel = !Validate(true); This would cause a breaking change between v2.0 and v1.0/v1.1 in case validation fails. - if (!Modal) { + if (!Modal) + { /* This is not required because Application.ExitPrivate() loops through all forms in the Application.OpenForms collection // Fire FormClosing event on all MDI children if (IsMdiContainer) { @@ -4609,13 +5168,17 @@ 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.GetInteger(PropOwnedFormsCount); - if (ownedFormsCount > 0) { + if (ownedFormsCount > 0) + { Form[] ownedForms = this.OwnedForms; FormClosingEventArgs fce = new FormClosingEventArgs(CloseReason.FormOwnerClosing, false); - for (int i = ownedFormsCount - 1; i >= 0; i--) { - if (ownedForms[i] != null && !Application.OpenForms.Contains(ownedForms[i])) { + for (int i = ownedFormsCount - 1; i >= 0; i--) + { + if (ownedForms[i] != null && !Application.OpenForms.Contains(ownedForms[i])) + { ownedForms[i].OnFormClosing(fce); - if (fce.Cancel) { + if (fce.Cancel) + { e.Cancel = true; break; } @@ -4632,17 +5195,20 @@ internal bool RaiseFormClosingOnAppExit() { [ SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive") ] - internal override void RecreateHandleCore() { + internal override void RecreateHandleCore() + { //Debug.Assert( CanRecreateHandle(), "Recreating handle when form is not ready yet." ); NativeMethods.WINDOWPLACEMENT wp = new NativeMethods.WINDOWPLACEMENT(); FormStartPosition oldStartPosition = FormStartPosition.Manual; - if (!IsMdiChild && (WindowState == FormWindowState.Minimized || WindowState == FormWindowState.Maximized)) { + if (!IsMdiChild && (WindowState == FormWindowState.Minimized || WindowState == FormWindowState.Maximized)) + { wp.length = Marshal.SizeOf(); UnsafeNativeMethods.GetWindowPlacement(new HandleRef(this, Handle), ref wp); } - if (StartPosition != FormStartPosition.Manual) { + if (StartPosition != FormStartPosition.Manual) + { oldStartPosition = StartPosition; // Set the startup postion to manual, to stop the form from // changing position each time RecreateHandle() is called. @@ -4651,10 +5217,12 @@ internal override void RecreateHandleCore() { EnumThreadWindowsCallback etwcb = null; SafeNativeMethods.EnumThreadWindowsCallback callback = null; - if (IsHandleCreated) { + if (IsHandleCreated) + { // First put all the owned windows into a list etwcb = new EnumThreadWindowsCallback(); - if (etwcb != null) { + if (etwcb != null) + { callback = new SafeNativeMethods.EnumThreadWindowsCallback(etwcb.Callback); UnsafeNativeMethods.EnumThreadWindows(SafeNativeMethods.GetCurrentThreadId(), new NativeMethods.EnumThreadWindowsCallback(callback), @@ -4667,20 +5235,24 @@ internal override void RecreateHandleCore() { base.RecreateHandleCore(); - if (etwcb != null) { + if (etwcb != null) + { // Set the owner of the windows in the list back to the new Form's handle etwcb.SetOwners(new HandleRef(this, this.Handle)); } - - if (oldStartPosition != FormStartPosition.Manual) { + + if (oldStartPosition != FormStartPosition.Manual) + { StartPosition = oldStartPosition; } - if (wp.length > 0) { + if (wp.length > 0) + { UnsafeNativeMethods.SetWindowPlacement(new HandleRef(this, Handle), ref wp); } - if (callback != null) { + if (callback != null) + { GC.KeepAlive(callback); } } @@ -4691,11 +5263,13 @@ internal override void RecreateHandleCore() { /// removed form to null. /// /// - public void RemoveOwnedForm(Form ownedForm) { + public void RemoveOwnedForm(Form ownedForm) + { if (ownedForm == null) return; - if (ownedForm.OwnerInternal != null) { + if (ownedForm.OwnerInternal != null) + { ownedForm.Owner = null; // NOTE: this will call RemoveOwnedForm again, bypassing if. return; } @@ -4703,9 +5277,12 @@ public void RemoveOwnedForm(Form ownedForm) { Form[] ownedForms = (Form[])Properties.GetObject(PropOwnedForms); int ownedFormsCount = Properties.GetInteger(PropOwnedFormsCount); - if (ownedForms != null) { - for (int i = 0; i < ownedFormsCount; i++) { - if (ownedForm.Equals(ownedForms[i])) { + if (ownedForms != null) + { + for (int i = 0; i < ownedFormsCount; i++) + { + if (ownedForm.Equals(ownedForms[i])) + { // clear out the reference. // @@ -4713,7 +5290,8 @@ public void RemoveOwnedForm(Form ownedForm) { // compact the array. // - if (i + 1 < ownedFormsCount) { + if (i + 1 < ownedFormsCount) + { Array.Copy(ownedForms, i + 1, ownedForms, i, ownedFormsCount - i - 1); ownedForms[ownedFormsCount - 1] = null; } @@ -4728,9 +5306,11 @@ public void RemoveOwnedForm(Form ownedForm) { /// /// Resets the form's icon the the default value. /// - private void ResetIcon() { + private void ResetIcon() + { icon = null; - if (smallIcon != null) { + if (smallIcon != null) + { smallIcon.Dispose(); smallIcon = null; } @@ -4741,7 +5321,8 @@ private void ResetIcon() { /// /// Resets the TransparencyKey to Color.Empty. /// - private void ResetTransparencyKey() { + private void ResetTransparencyKey() + { TransparencyKey = Color.Empty; } @@ -4749,7 +5330,8 @@ private void ResetTransparencyKey() { /// Occurs when the form enters the sizing modal loop /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.FormOnResizeBeginDescr))] - public event EventHandler ResizeBegin { + public event EventHandler ResizeBegin + { add => Events.AddHandler(EVENT_RESIZEBEGIN, value); remove => Events.RemoveHandler(EVENT_RESIZEBEGIN, value); } @@ -4758,7 +5340,8 @@ public event EventHandler ResizeBegin { /// Occurs when the control exits the sizing modal loop. /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.FormOnResizeEndDescr))] - public event EventHandler ResizeEnd { + public event EventHandler ResizeEnd + { add => Events.AddHandler(EVENT_RESIZEEND, value); remove => Events.RemoveHandler(EVENT_RESIZEEND, value); } @@ -4767,10 +5350,12 @@ public event EventHandler ResizeEnd { /// This is called when we have just been restored after being /// minimized. At this point we resume our layout. /// - private void ResumeLayoutFromMinimize() { + private void ResumeLayoutFromMinimize() + { // If we're currently minimized, resume our layout because we are // about to snap out of it. - if (formState[FormStateWindowState] == (int)FormWindowState.Minimized) { + if (formState[FormStateWindowState] == (int)FormWindowState.Minimized) + { ResumeLayout(); } } @@ -4781,15 +5366,18 @@ private void ResumeLayoutFromMinimize() { // In the normal case where no one sets Location or Size programmatically, // Windows does the restoring for us. // - private void RestoreWindowBoundsIfNecessary() { - if (WindowState == FormWindowState.Normal) { + private void RestoreWindowBoundsIfNecessary() + { + if (WindowState == FormWindowState.Normal) + { Size restoredSize = restoredWindowBounds.Size; - if ((restoredWindowBoundsSpecified & BoundsSpecified.Size) != 0) { + if ((restoredWindowBoundsSpecified & BoundsSpecified.Size) != 0) + { restoredSize = SizeFromClientSize(restoredSize.Width, restoredSize.Height); } SetBounds(restoredWindowBounds.X, restoredWindowBounds.Y, - formStateEx[FormStateExWindowBoundsWidthIsClientSize]==1 ? restoredSize.Width : restoredWindowBounds.Width, - formStateEx[FormStateExWindowBoundsHeightIsClientSize]==1 ? restoredSize.Height : restoredWindowBounds.Height, + formStateEx[FormStateExWindowBoundsWidthIsClientSize] == 1 ? restoredSize.Width : restoredWindowBounds.Width, + formStateEx[FormStateExWindowBoundsHeightIsClientSize] == 1 ? restoredSize.Height : restoredWindowBounds.Height, restoredWindowBoundsSpecified); restoredWindowBoundsSpecified = 0; restoredWindowBounds = new Rectangle(-1, -1, -1, -1); @@ -4803,14 +5391,17 @@ private void RestoreWindowBoundsIfNecessary() { /// becomes zero and updateMenuHandlesDeferred is true, updateMenuHandles /// is called. /// - private void ResumeUpdateMenuHandles() { + private void ResumeUpdateMenuHandles() + { int suspendCount = formStateEx[FormStateExUpdateMenuHandlesSuspendCount]; - if (suspendCount <= 0) { + if (suspendCount <= 0) + { throw new InvalidOperationException(SR.TooManyResumeUpdateMenuHandles); } formStateEx[FormStateExUpdateMenuHandlesSuspendCount] = --suspendCount; - if (suspendCount == 0 && formStateEx[FormStateExUpdateMenuHandlesDeferred] != 0) { + if (suspendCount == 0 && formStateEx[FormStateExUpdateMenuHandlesDeferred] != 0) + { UpdateMenuHandles(); } } @@ -4848,19 +5439,24 @@ protected override void Select(bool directed, bool forward) /// Base function that performs scaling of the form. /// [EditorBrowsable(EditorBrowsableState.Never)] - protected override void ScaleCore(float x, float y) { + protected override void ScaleCore(float x, float y) + { Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, GetType().Name + "::ScaleCore(" + x + ", " + y + ")"); SuspendLayout(); - try { - if (WindowState == FormWindowState.Normal) { + try + { + if (WindowState == FormWindowState.Normal) + { //Get size values in advance to prevent one change from affecting another. Size clientSize = ClientSize; Size minSize = MinimumSize; Size maxSize = MaximumSize; - if (!MinimumSize.IsEmpty) { + if (!MinimumSize.IsEmpty) + { MinimumSize = ScaleSize(minSize, x, y); } - if (!MaximumSize.IsEmpty) { + if (!MaximumSize.IsEmpty) + { MaximumSize = ScaleSize(maxSize, x, y); } ClientSize = ScaleSize(clientSize, x, y); @@ -4868,15 +5464,18 @@ protected override void ScaleCore(float x, float y) { ScaleDockPadding(x, y); - foreach(Control control in Controls) { - if (control != null) { + foreach (Control control in Controls) + { + if (control != null) + { #pragma warning disable 618 control.Scale(x, y); #pragma warning restore 618 } } } - finally { + finally + { ResumeLayout(); } } @@ -4886,32 +5485,38 @@ protected override void ScaleCore(float x, float y) { /// if it is maximized or minimized. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override Rectangle GetScaledBounds(Rectangle bounds, SizeF factor, BoundsSpecified specified) { + protected override Rectangle GetScaledBounds(Rectangle bounds, SizeF factor, BoundsSpecified specified) + { // If we're maximized or minimized, scale using the restored bounds, not // the real bounds. - if (WindowState != FormWindowState.Normal) { + if (WindowState != FormWindowState.Normal) + { bounds = RestoreBounds; } return base.GetScaledBounds(bounds, factor, specified); } - + /// /// Scale this form. Form overrides this to enforce a maximum / minimum size. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { + protected override void ScaleControl(SizeF factor, BoundsSpecified specified) + { formStateEx[FormStateExInScale] = 1; - try { - + try + { + // don't scale the location of MDI child forms - if (MdiParentInternal != null) { + if (MdiParentInternal != null) + { specified &= ~BoundsSpecified.Location; } base.ScaleControl(factor, specified); } - finally { + finally + { formStateEx[FormStateExInScale] = 0; } } @@ -5008,13 +5613,17 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound /// Sets the defaultButton for the form. The defaultButton is "clicked" when /// the user presses Enter. /// - private void SetDefaultButton(IButtonControl button) { + private void SetDefaultButton(IButtonControl button) + { IButtonControl defaultButton = (IButtonControl)Properties.GetObject(PropDefaultButton); - if (defaultButton != button) { - if (defaultButton != null) defaultButton.NotifyDefault(false); + if (defaultButton != button) + { + if (defaultButton != null) + defaultButton.NotifyDefault(false); Properties.SetObject(PropDefaultButton, button); - if (button != null) button.NotifyDefault(true); + if (button != null) + button.NotifyDefault(true); } } @@ -5024,20 +5633,27 @@ private void SetDefaultButton(IButtonControl button) { /// to make the clientSize the requested size. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void SetClientSizeCore(int x, int y) { + protected override void SetClientSizeCore(int x, int y) + { bool hadHScroll = HScroll, hadVScroll = VScroll; base.SetClientSizeCore(x, y); - if (IsHandleCreated) { + if (IsHandleCreated) + { // Adjust for the scrollbars, if they were introduced by // the call to base.SetClientSizeCore - if (VScroll != hadVScroll) { - if (VScroll) x += SystemInformation.VerticalScrollBarWidth; + if (VScroll != hadVScroll) + { + if (VScroll) + x += SystemInformation.VerticalScrollBarWidth; } - if (HScroll != hadHScroll) { - if (HScroll) y += SystemInformation.HorizontalScrollBarHeight; + if (HScroll != hadHScroll) + { + if (HScroll) + y += SystemInformation.HorizontalScrollBarHeight; } - if (x != ClientSize.Width || y != ClientSize.Height) { + if (x != ClientSize.Width || y != ClientSize.Height) + { base.SetClientSizeCore(x, y); } } @@ -5048,7 +5664,8 @@ protected override void SetClientSizeCore(int x, int y) { /// /// Sets the bounds of the form in desktop coordinates. /// - public void SetDesktopBounds(int x, int y, int width, int height) { + public void SetDesktopBounds(int x, int y, int width, int height) + { Rectangle workingArea = SystemInformation.WorkingArea; SetBounds(x + workingArea.X, y + workingArea.Y, width, height, BoundsSpecified.All); } @@ -5056,7 +5673,8 @@ public void SetDesktopBounds(int x, int y, int width, int height) { /// /// Sets the location of the form in desktop coordinates. /// - public void SetDesktopLocation(int x, int y) { + public void SetDesktopLocation(int x, int y) + { Rectangle workingArea = SystemInformation.WorkingArea; Location = new Point(workingArea.X + x, workingArea.Y + y); } @@ -5065,29 +5683,37 @@ public void SetDesktopLocation(int x, int y) { /// /// Makes the control display by setting the visible property to true /// - public void Show(IWin32Window owner) { - if (owner == this) { + public void Show(IWin32Window owner) + { + if (owner == this) + { throw new InvalidOperationException(string.Format(SR.OwnsSelfOrOwner, "Show")); } - else if (Visible) { + else if (Visible) + { throw new InvalidOperationException(string.Format(SR.ShowDialogOnVisible, "Show")); } - else if (!Enabled) { + else if (!Enabled) + { throw new InvalidOperationException(string.Format(SR.ShowDialogOnDisabled, "Show")); } - else if (!TopLevel) { + else if (!TopLevel) + { throw new InvalidOperationException(string.Format(SR.ShowDialogOnNonTopLevel, "Show")); } - else if (!SystemInformation.UserInteractive) { + else if (!SystemInformation.UserInteractive) + { throw new InvalidOperationException(SR.CantShowModalOnNonInteractive); } - else if ( (owner != null) && ((int)UnsafeNativeMethods.GetWindowLong(new HandleRef(owner, Control.GetSafeHandle(owner)), NativeMethods.GWL_EXSTYLE) - & NativeMethods.WS_EX_TOPMOST) == 0 ) { // It's not the top-most window - if (owner is Control) { + else if ((owner != null) && ((int)UnsafeNativeMethods.GetWindowLong(new HandleRef(owner, Control.GetSafeHandle(owner)), NativeMethods.GWL_EXSTYLE) + & NativeMethods.WS_EX_TOPMOST) == 0) + { // It's not the top-most window + if (owner is Control) + { owner = ((Control)owner).TopLevelControlInternal; } } @@ -5096,12 +5722,15 @@ public void Show(IWin32Window owner) { IntPtr hWndOldOwner = IntPtr.Zero; Properties.SetObject(PropDialogOwner, owner); Form oldOwner = OwnerInternal; - if (owner is Form && owner != oldOwner) { + if (owner is Form && owner != oldOwner) + { Owner = (Form)owner; } - if (hWndOwner != IntPtr.Zero && hWndOwner != Handle) { + if (hWndOwner != IntPtr.Zero && hWndOwner != Handle) + { // Catch the case of a window trying to own its owner - if (UnsafeNativeMethods.GetWindowLong(new HandleRef(owner, hWndOwner), NativeMethods.GWL_HWNDPARENT) == Handle) { + if (UnsafeNativeMethods.GetWindowLong(new HandleRef(owner, hWndOwner), NativeMethods.GWL_HWNDPARENT) == Handle) + { throw new ArgumentException(string.Format(SR.OwnsSelfOrOwner, "show"), "owner"); } @@ -5117,40 +5746,50 @@ public void Show(IWin32Window owner) { /// /// Displays this form as a modal dialog box with no owner window. /// - public DialogResult ShowDialog() { + public DialogResult ShowDialog() + { return ShowDialog(null); } /// /// Shows this form as a modal dialog with the specified owner. /// - public DialogResult ShowDialog(IWin32Window owner) { - if (owner == this) { + public DialogResult ShowDialog(IWin32Window owner) + { + if (owner == this) + { throw new ArgumentException(string.Format(SR.OwnsSelfOrOwner, "showDialog"), "owner"); } - else if (Visible) { + else if (Visible) + { throw new InvalidOperationException(string.Format(SR.ShowDialogOnVisible, "showDialog")); } - else if (!Enabled) { + else if (!Enabled) + { throw new InvalidOperationException(string.Format(SR.ShowDialogOnDisabled, "showDialog")); } - else if (!TopLevel) { + else if (!TopLevel) + { throw new InvalidOperationException(string.Format(SR.ShowDialogOnNonTopLevel, "showDialog")); } - else if (Modal) { + else if (Modal) + { throw new InvalidOperationException(string.Format(SR.ShowDialogOnModal, "showDialog")); } - else if (!SystemInformation.UserInteractive) { + else if (!SystemInformation.UserInteractive) + { throw new InvalidOperationException(SR.CantShowModalOnNonInteractive); } - else if ( (owner != null) && ((int)UnsafeNativeMethods.GetWindowLong(new HandleRef(owner, Control.GetSafeHandle(owner)), NativeMethods.GWL_EXSTYLE) - & NativeMethods.WS_EX_TOPMOST) == 0 ) { // It's not the top-most window - if (owner is Control) { + else if ((owner != null) && ((int)UnsafeNativeMethods.GetWindowLong(new HandleRef(owner, Control.GetSafeHandle(owner)), NativeMethods.GWL_EXSTYLE) + & NativeMethods.WS_EX_TOPMOST) == 0) + { // It's not the top-most window + if (owner is Control) + { owner = ((Control)owner).TopLevelControlInternal; } } @@ -5162,7 +5801,8 @@ public DialogResult ShowDialog(IWin32Window owner) { this.CloseReason = CloseReason.None; IntPtr hWndCapture = UnsafeNativeMethods.GetCapture(); - if (hWndCapture != IntPtr.Zero) { + if (hWndCapture != IntPtr.Zero) + { UnsafeNativeMethods.SendMessage(new HandleRef(null, hWndCapture), Interop.WindowMessages.WM_CANCELMODE, IntPtr.Zero, IntPtr.Zero); SafeNativeMethods.ReleaseCapture(); } @@ -5173,11 +5813,13 @@ public DialogResult ShowDialog(IWin32Window owner) { Form oldOwner = OwnerInternal; - if (owner is Form && owner != oldOwner) { + if (owner is Form && owner != oldOwner) + { Owner = (Form)owner; } - try { + try + { SetState(STATE_MODAL, true); // It's possible that while in the process of creating the control, @@ -5197,9 +5839,11 @@ public DialogResult ShowDialog(IWin32Window owner) { // CreateControl(); - if (hWndOwner != IntPtr.Zero && hWndOwner != Handle) { + if (hWndOwner != IntPtr.Zero && hWndOwner != Handle) + { // Catch the case of a window trying to own its owner - if (UnsafeNativeMethods.GetWindowLong(new HandleRef(owner, hWndOwner), NativeMethods.GWL_HWNDPARENT) == Handle) { + if (UnsafeNativeMethods.GetWindowLong(new HandleRef(owner, hWndOwner), NativeMethods.GWL_HWNDPARENT) == Handle) + { throw new ArgumentException(string.Format(SR.OwnsSelfOrOwner, "showDialog"), "owner"); } @@ -5209,7 +5853,8 @@ public DialogResult ShowDialog(IWin32Window owner) { UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_HWNDPARENT, new HandleRef(owner, hWndOwner)); } - try { + try + { // If the DialogResult was already set, then there's // no need to actually display the dialog. // @@ -5219,25 +5864,31 @@ public DialogResult ShowDialog(IWin32Window owner) { Application.RunDialog(this); } } - finally { + finally + { // Call SetActiveWindow before setting Visible = false. // - if (!UnsafeNativeMethods.IsWindow(new HandleRef(null, hWndActive))) hWndActive = hWndOwner; - if (UnsafeNativeMethods.IsWindow(new HandleRef(null, hWndActive)) && SafeNativeMethods.IsWindowVisible(new HandleRef(null, hWndActive))) { + if (!UnsafeNativeMethods.IsWindow(new HandleRef(null, hWndActive))) + hWndActive = hWndOwner; + if (UnsafeNativeMethods.IsWindow(new HandleRef(null, hWndActive)) && SafeNativeMethods.IsWindowVisible(new HandleRef(null, hWndActive))) + { UnsafeNativeMethods.SetActiveWindow(new HandleRef(null, hWndActive)); } - else if (UnsafeNativeMethods.IsWindow(new HandleRef(null, hWndOwner)) && SafeNativeMethods.IsWindowVisible(new HandleRef(null, hWndOwner))){ + else if (UnsafeNativeMethods.IsWindow(new HandleRef(null, hWndOwner)) && SafeNativeMethods.IsWindowVisible(new HandleRef(null, hWndOwner))) + { UnsafeNativeMethods.SetActiveWindow(new HandleRef(null, hWndOwner)); } SetVisibleCore(false); - if (IsHandleCreated) { + if (IsHandleCreated) + { // If this is a dialog opened from an MDI Container, then invalidate // so that child windows will be properly updated. if (this.OwnerInternal != null && - this.OwnerInternal.IsMdiContainer) { + this.OwnerInternal.IsMdiContainer) + { this.OwnerInternal.Invalidate(true); this.OwnerInternal.Update(); } @@ -5248,7 +5899,8 @@ public DialogResult ShowDialog(IWin32Window owner) { SetState(STATE_MODAL, false); } } - finally { + finally + { Owner = oldOwner; Properties.SetObject(PropDialogOwner, null); } @@ -5260,18 +5912,21 @@ public DialogResult ShowDialog(IWin32Window owner) { /// persisted. /// [EditorBrowsable(EditorBrowsableState.Never)] - internal virtual bool ShouldSerializeAutoScaleBaseSize() { + internal virtual bool ShouldSerializeAutoScaleBaseSize() + { return formState[FormStateAutoScaling] != 0; } - private bool ShouldSerializeClientSize() { + private bool ShouldSerializeClientSize() + { return true; } /// /// Indicates whether the property should be persisted. /// - private bool ShouldSerializeIcon() { + private bool ShouldSerializeIcon() + { return formState[FormStateIconSet] == 1; } @@ -5279,7 +5934,8 @@ private bool ShouldSerializeIcon() { /// Determines if the Location property needs to be persisted. /// [EditorBrowsable(EditorBrowsableState.Never)] - private bool ShouldSerializeLocation() { + private bool ShouldSerializeLocation() + { return Left != 0 || Top != 0; } @@ -5287,7 +5943,8 @@ private bool ShouldSerializeLocation() { /// Indicates whether the property should be persisted. /// [EditorBrowsable(EditorBrowsableState.Never)] - internal override bool ShouldSerializeSize() { + internal override bool ShouldSerializeSize() + { return false; } @@ -5296,7 +5953,8 @@ internal override bool ShouldSerializeSize() { /// persisted. /// [EditorBrowsable(EditorBrowsableState.Never)] - internal bool ShouldSerializeTransparencyKey() { + internal bool ShouldSerializeTransparencyKey() + { return !TransparencyKey.Equals(Color.Empty); } @@ -5305,10 +5963,12 @@ internal bool ShouldSerializeTransparencyKey() { /// while minimized can be a problem because the physical dimensions /// of the window are very small. So, we simply suspend. /// - private void SuspendLayoutForMinimize() { + private void SuspendLayoutForMinimize() + { // If we're not currently minimized, suspend our layout because we are // about to become minimized - if (formState[FormStateWindowState] != (int)FormWindowState.Minimized) { + if (formState[FormStateWindowState] != (int)FormWindowState.Minimized) + { SuspendLayout(); } } @@ -5316,7 +5976,8 @@ private void SuspendLayoutForMinimize() { /// /// Increments updateMenuHandleSuspendCount. /// - private void SuspendUpdateMenuHandles() { + private void SuspendUpdateMenuHandles() + { int suspendCount = formStateEx[FormStateExUpdateMenuHandlesSuspendCount]; formStateEx[FormStateExUpdateMenuHandlesSuspendCount] = ++suspendCount; } @@ -5324,7 +5985,8 @@ private void SuspendUpdateMenuHandles() { /// /// Returns a string representation for this control. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); return s + ", Text: " + Text; @@ -5333,13 +5995,16 @@ public override string ToString() { /// /// Updates the autoscalebasesize based on the current font. /// - private void UpdateAutoScaleBaseSize() { + private void UpdateAutoScaleBaseSize() + { autoScaleBaseSize = Size.Empty; } - private void UpdateRenderSizeGrip() { + private void UpdateRenderSizeGrip() + { int current = formState[FormStateRenderSizeGrip]; - switch (FormBorderStyle) { + switch (FormBorderStyle) + { case FormBorderStyle.None: case FormBorderStyle.FixedSingle: case FormBorderStyle.Fixed3D: @@ -5349,7 +6014,8 @@ private void UpdateRenderSizeGrip() { break; case FormBorderStyle.Sizable: case FormBorderStyle.SizableToolWindow: - switch (SizeGripStyle) { + switch (SizeGripStyle) + { case SizeGripStyle.Show: formState[FormStateRenderSizeGrip] = 1; break; @@ -5357,10 +6023,12 @@ private void UpdateRenderSizeGrip() { formState[FormStateRenderSizeGrip] = 0; break; case SizeGripStyle.Auto: - if (GetState(STATE_MODAL)) { + if (GetState(STATE_MODAL)) + { formState[FormStateRenderSizeGrip] = 1; } - else { + else + { formState[FormStateRenderSizeGrip] = 0; } break; @@ -5368,7 +6036,8 @@ private void UpdateRenderSizeGrip() { break; } - if (formState[FormStateRenderSizeGrip] != current) { + if (formState[FormStateRenderSizeGrip] != current) + { Invalidate(); } } @@ -5377,7 +6046,8 @@ private void UpdateRenderSizeGrip() { /// Updates the default button based on current selection, and the /// acceptButton property. /// - protected override void UpdateDefaultButton() { + protected override void UpdateDefaultButton() + { ContainerControl cc = this; while (cc.ActiveControl is ContainerControl) @@ -5397,7 +6067,7 @@ protected override void UpdateDefaultButton() { if (cc.ActiveControl is IButtonControl) { - SetDefaultButton((IButtonControl) cc.ActiveControl); + SetDefaultButton((IButtonControl)cc.ActiveControl); } else { @@ -5408,17 +6078,22 @@ protected override void UpdateDefaultButton() { /// /// Updates the underlying hWnd with the correct parent/owner of the form. /// - private void UpdateHandleWithOwner() { - if (IsHandleCreated && TopLevel) { + private void UpdateHandleWithOwner() + { + if (IsHandleCreated && TopLevel) + { HandleRef ownerHwnd = NativeMethods.NullHandleRef; Form owner = (Form)Properties.GetObject(PropOwner); - if (owner != null) { + if (owner != null) + { ownerHwnd = new HandleRef(owner, owner.Handle); } - else { - if (!ShowInTaskbar) { + else + { + if (!ShowInTaskbar) + { ownerHwnd = TaskbarOwner; } } @@ -5431,116 +6106,142 @@ private void UpdateHandleWithOwner() { /// Updates the layered window attributes if the control /// is in layered mode. /// - private void UpdateLayered() { - if ((formState[FormStateLayered] != 0) && IsHandleCreated && TopLevel && OSFeature.Feature.IsPresent(OSFeature.LayeredWindows)) { + private void UpdateLayered() + { + if ((formState[FormStateLayered] != 0) && IsHandleCreated && TopLevel && OSFeature.Feature.IsPresent(OSFeature.LayeredWindows)) + { bool result; Color transparencyKey = TransparencyKey; - if (transparencyKey.IsEmpty) { + if (transparencyKey.IsEmpty) + { result = UnsafeNativeMethods.SetLayeredWindowAttributes(new HandleRef(this, Handle), 0, OpacityAsByte, NativeMethods.LWA_ALPHA); } - else if (OpacityAsByte == 255) { + else if (OpacityAsByte == 255) + { // Windows doesn't do so well setting colorkey and alpha, so avoid it if we can result = UnsafeNativeMethods.SetLayeredWindowAttributes(new HandleRef(this, Handle), ColorTranslator.ToWin32(transparencyKey), 0, NativeMethods.LWA_COLORKEY); } - else { + else + { result = UnsafeNativeMethods.SetLayeredWindowAttributes(new HandleRef(this, Handle), ColorTranslator.ToWin32(transparencyKey), OpacityAsByte, NativeMethods.LWA_ALPHA | NativeMethods.LWA_COLORKEY); } - if (!result) { + if (!result) + { throw new Win32Exception(); } } } - private void UpdateMenuHandles() { + private void UpdateMenuHandles() + { Form form; // Forget the current menu. - if (Properties.GetObject(PropCurMenu) != null) { + if (Properties.GetObject(PropCurMenu) != null) + { Properties.SetObject(PropCurMenu, null); } - if (IsHandleCreated) { - if (!TopLevel) { + if (IsHandleCreated) + { + if (!TopLevel) + { UpdateMenuHandles(null, true); } - else { + else + { form = ActiveMdiChildInternal; - if (form != null) { + if (form != null) + { UpdateMenuHandles(form.MergedMenuPrivate, true); } - else { + else + { UpdateMenuHandles(Menu, true); } } } } - private void UpdateMenuHandles(MainMenu menu, bool forceRedraw) { + private void UpdateMenuHandles(MainMenu menu, bool forceRedraw) + { Debug.Assert(IsHandleCreated, "shouldn't call when handle == 0"); int suspendCount = formStateEx[FormStateExUpdateMenuHandlesSuspendCount]; - if (suspendCount > 0 && menu != null) { + if (suspendCount > 0 && menu != null) + { formStateEx[FormStateExUpdateMenuHandlesDeferred] = 1; return; } MainMenu curMenu = menu; - if (curMenu != null) { + if (curMenu != null) + { curMenu.form = this; } - if (curMenu != null || Properties.ContainsObject(PropCurMenu)) { + if (curMenu != null || Properties.ContainsObject(PropCurMenu)) + { Properties.SetObject(PropCurMenu, curMenu); } - if (ctlClient == null || !ctlClient.IsHandleCreated) { - if (menu != null) { + if (ctlClient == null || !ctlClient.IsHandleCreated) + { + if (menu != null) + { UnsafeNativeMethods.SetMenu(new HandleRef(this, Handle), new HandleRef(menu, menu.Handle)); } - else { + else + { UnsafeNativeMethods.SetMenu(new HandleRef(this, Handle), NativeMethods.NullHandleRef); } } - else { - Debug.Assert( IsMdiContainer, "Not an MDI container!" ); + else + { + Debug.Assert(IsMdiContainer, "Not an MDI container!"); // when both MainMenuStrip and Menu are set, we honor the win32 menu over // the MainMenuStrip as the place to store the system menu controls for the maximized MDI child. MenuStrip mainMenuStrip = MainMenuStrip; - if( mainMenuStrip == null || menu!=null){ // We are dealing with a Win32 Menu; MenuStrip doesn't have control buttons. + if (mainMenuStrip == null || menu != null) + { // We are dealing with a Win32 Menu; MenuStrip doesn't have control buttons. // We have a MainMenu and we're going to use it - + // We need to set the "dummy" menu even when a menu is being removed // (set to null) so that duplicate control buttons are not placed on the menu bar when // an ole menu is being removed. // Make MDI forget the mdi item position. MainMenu dummyMenu = (MainMenu)Properties.GetObject(PropDummyMenu); - if (dummyMenu == null) { + if (dummyMenu == null) + { dummyMenu = new MainMenu(); dummyMenu.ownerForm = this; Properties.SetObject(PropDummyMenu, dummyMenu); } UnsafeNativeMethods.SendMessage(new HandleRef(ctlClient, ctlClient.Handle), Interop.WindowMessages.WM_MDISETMENU, dummyMenu.Handle, IntPtr.Zero); - if (menu != null) { + if (menu != null) + { // Microsoft, 5/2/1998 - don't use Win32 native Mdi lists... // UnsafeNativeMethods.SendMessage(new HandleRef(ctlClient, ctlClient.Handle), Interop.WindowMessages.WM_MDISETMENU, menu.Handle, IntPtr.Zero); } } - + // (New fix: Only destroy Win32 Menu if using a MenuStrip) - if( menu == null && mainMenuStrip != null ){ // If MainMenuStrip, we need to remove any Win32 Menu to make room for it. - IntPtr hMenu = UnsafeNativeMethods.GetMenu(new HandleRef(this, this.Handle)); - if (hMenu != IntPtr.Zero) { + if (menu == null && mainMenuStrip != null) + { // If MainMenuStrip, we need to remove any Win32 Menu to make room for it. + IntPtr hMenu = UnsafeNativeMethods.GetMenu(new HandleRef(this, this.Handle)); + if (hMenu != IntPtr.Zero) + { // We had a MainMenu and now we're switching over to MainMenuStrip @@ -5551,17 +6252,19 @@ private void UpdateMenuHandles(MainMenu menu, bool forceRedraw) { // once we clear the main menu we're in trouble - this eats the close, minimize, maximize gadgets // of the child form. (See WM_MDISETMENU in MSDN) Form activeMdiChild = this.ActiveMdiChildInternal; - if (activeMdiChild != null && activeMdiChild.WindowState == FormWindowState.Maximized) { + if (activeMdiChild != null && activeMdiChild.WindowState == FormWindowState.Maximized) + { activeMdiChild.RecreateHandle(); } - + // Since we're removing a menu but we possibly had a menu previously, // we need to clear the cached size so that new size calculations will be performed correctly. CommonProperties.xClearPreferredSizeCache(this); } } } - if (forceRedraw) { + if (forceRedraw) + { SafeNativeMethods.DrawMenuBar(new HandleRef(this, Handle)); } formStateEx[FormStateExUpdateMenuHandlesDeferred] = 0; @@ -5570,19 +6273,24 @@ private void UpdateMenuHandles(MainMenu menu, bool forceRedraw) { // Call this function instead of UpdateStyles() when the form's client-size must // be preserved e.g. when changing the border style. // - internal void UpdateFormStyles() { + internal void UpdateFormStyles() + { Size previousClientSize = ClientSize; base.UpdateStyles(); - if (!ClientSize.Equals(previousClientSize)) { + if (!ClientSize.Equals(previousClientSize)) + { ClientSize = previousClientSize; } } - private static Type FindClosestStockType(Type type) { - Type[] stockTypes = new Type[] { typeof (MenuStrip) }; // as opposed to what we had before... + private static Type FindClosestStockType(Type type) + { + Type[] stockTypes = new Type[] { typeof(MenuStrip) }; // as opposed to what we had before... // simply add other types here from most specific to most generic if we want to merge other types of toolstrips... - foreach(Type t in stockTypes) { - if(t.IsAssignableFrom(type)) { + foreach (Type t in stockTypes) + { + if (t.IsAssignableFrom(type)) + { return t; } } @@ -5590,7 +6298,8 @@ private static Type FindClosestStockType(Type type) { } /// ToolStrip MDI Merging support - private void UpdateToolStrip() { + private void UpdateToolStrip() + { //MERGEDEBUG Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "\r\n============"); //MERGEDEBUG Debug.WriteLineIf(ToolStrip.MergeDebug.TraceVerbose, "ToolStripMerging: starting merge operation"); @@ -5603,25 +6312,30 @@ private void UpdateToolStrip() { //MERGEDEBUG Debug.WriteLineIf(ToolStrip.MergeDebug.TraceVerbose, "ToolStripMerging: found "+childrenToolStrips.Count+" mergeable toolstrip in children"); // revert any previous merge - if(thisToolstrip != null) { + if (thisToolstrip != null) + { //MERGEDEBUG Debug.WriteLineIf(ToolStrip.MergeDebug.TraceVerbose, "ToolStripMerging: reverting merge in " + destinationToolStrip.Name); ToolStripManager.RevertMerge(thisToolstrip); } // if someone has a MdiWindowListItem specified we should merge in the // names of all the MDI child forms. - UpdateMdiWindowListStrip(); + UpdateMdiWindowListStrip(); - if(ActiveMdiChildInternal != null) { + if (ActiveMdiChildInternal != null) + { // do the new merging - foreach(ToolStrip sourceToolStrip in childrenToolStrips) { + foreach (ToolStrip sourceToolStrip in childrenToolStrips) + { Type closestMatchingSourceType = FindClosestStockType(sourceToolStrip.GetType()); - if(thisToolstrip != null) { + if (thisToolstrip != null) + { Type closestMatchingTargetType = FindClosestStockType(thisToolstrip.GetType()); if (closestMatchingTargetType != null && closestMatchingSourceType != null && closestMatchingSourceType == closestMatchingTargetType && - thisToolstrip.GetType().IsAssignableFrom(sourceToolStrip.GetType())) { + thisToolstrip.GetType().IsAssignableFrom(sourceToolStrip.GetType())) + { ToolStripManager.Merge(sourceToolStrip, thisToolstrip); break; } @@ -5635,9 +6349,11 @@ private void UpdateToolStrip() { UpdateMdiControlStrip(activeMdiForm != null && activeMdiForm.IsMaximized); } - private void UpdateMdiControlStrip(bool maximized) { + private void UpdateMdiControlStrip(bool maximized) + { - if (formStateEx[FormStateExInUpdateMdiControlStrip] != 0) { + if (formStateEx[FormStateExInUpdateMdiControlStrip] != 0) + { //MERGEDEBUG Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: Detected re-entrant call to UpdateMdiControlStrip, returning."); return; } @@ -5645,24 +6361,29 @@ private void UpdateMdiControlStrip(bool maximized) { // we dont want to be redundantly called as we could merge in two control menus. formStateEx[FormStateExInUpdateMdiControlStrip] = 1; - try { + try + { MdiControlStrip mdiControlStrip = this.MdiControlStrip; - if (MdiControlStrip != null) { - if (mdiControlStrip.MergedMenu != null) { + if (MdiControlStrip != null) + { + if (mdiControlStrip.MergedMenu != null) + { #if DEBUG //MERGEDEBUG Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: Calling RevertMerge on MDIControl strip."); int numWindowListItems = 0; - if (MdiWindowListStrip != null && MdiWindowListStrip.MergedMenu != null && MdiWindowListStrip.MergedMenu.MdiWindowListItem != null) { + if (MdiWindowListStrip != null && MdiWindowListStrip.MergedMenu != null && MdiWindowListStrip.MergedMenu.MdiWindowListItem != null) + { numWindowListItems = MdiWindowListStrip.MergedMenu.MdiWindowListItem.DropDownItems.Count; } #endif - ToolStripManager.RevertMergeInternal(mdiControlStrip.MergedMenu,mdiControlStrip,/*revertMDIStuff*/true); + ToolStripManager.RevertMergeInternal(mdiControlStrip.MergedMenu, mdiControlStrip,/*revertMDIStuff*/true); #if DEBUG // double check that RevertMerge doesnt accidentally revert more than it should. - if (MdiWindowListStrip != null && MdiWindowListStrip.MergedMenu != null && MdiWindowListStrip.MergedMenu.MdiWindowListItem != null) { + if (MdiWindowListStrip != null && MdiWindowListStrip.MergedMenu != null && MdiWindowListStrip.MergedMenu.MdiWindowListItem != null) + { Debug.Assert(numWindowListItems == MdiWindowListStrip.MergedMenu.MdiWindowListItem.DropDownItems.Count, "Calling RevertMerge modified the mdiwindowlistitem"); } #endif @@ -5672,18 +6393,23 @@ private void UpdateMdiControlStrip(bool maximized) { MdiControlStrip = null; } - if (ActiveMdiChildInternal != null && maximized) { - if (ActiveMdiChildInternal.ControlBox) { + if (ActiveMdiChildInternal != null && maximized) + { + if (ActiveMdiChildInternal.ControlBox) + { Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: Detected ControlBox on ActiveMDI child, adding in MDIControlStrip."); Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose && this.Menu != null, "UpdateMdiControlStrip: Bailing as we detect there's already an HMenu to do this for us."); // determine if we need to add control gadgets into the MenuStrip - if (this.Menu == null) { + if (this.Menu == null) + { // double check GetMenu incase someone is using interop - IntPtr hMenu = UnsafeNativeMethods.GetMenu(new HandleRef(this, this.Handle)); - if (hMenu == IntPtr.Zero) { + IntPtr hMenu = UnsafeNativeMethods.GetMenu(new HandleRef(this, this.Handle)); + if (hMenu == IntPtr.Zero) + { MenuStrip sourceMenuStrip = ToolStripManager.GetMainMenuStrip(this); - if (sourceMenuStrip != null) { + if (sourceMenuStrip != null) + { this.MdiControlStrip = new MdiControlStrip(ActiveMdiChildInternal); Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: built up an MDI control strip for " + ActiveMdiChildInternal.Text + " with " + MdiControlStrip.Items.Count.ToString(CultureInfo.InvariantCulture) + " items."); Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: merging MDI control strip into source menustrip - items before: " + sourceMenuStrip.Items.Count.ToString(CultureInfo.InvariantCulture)); @@ -5696,28 +6422,34 @@ private void UpdateMdiControlStrip(bool maximized) { } } } - finally { + finally + { formStateEx[FormStateExInUpdateMdiControlStrip] = 0; } } - internal void UpdateMdiWindowListStrip() { - if (IsMdiContainer) { - if (MdiWindowListStrip != null && MdiWindowListStrip.MergedMenu != null) { + internal void UpdateMdiWindowListStrip() + { + if (IsMdiContainer) + { + if (MdiWindowListStrip != null && MdiWindowListStrip.MergedMenu != null) + { //MERGEDEBUG Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiWindowListStrip: Calling RevertMerge on MDIWindowList strip."); //MERGEDEBUG Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose && MdiWindowListStrip.MergedMenu.MdiWindowListItem != null, "UpdateMdiWindowListStrip: MdiWindowListItem dropdown item count before: " + MdiWindowListStrip.MergedMenu.MdiWindowListItem.DropDownItems.Count.ToString()); - ToolStripManager.RevertMergeInternal(MdiWindowListStrip.MergedMenu,MdiWindowListStrip,/*revertMdiStuff*/true); + ToolStripManager.RevertMergeInternal(MdiWindowListStrip.MergedMenu, MdiWindowListStrip,/*revertMdiStuff*/true); //MERGEDEBUG Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose && MdiWindowListStrip.MergedMenu.MdiWindowListItem != null, "UpdateMdiWindowListStrip: MdiWindowListItem dropdown item count after: " + MdiWindowListStrip.MergedMenu.MdiWindowListItem.DropDownItems.Count.ToString()); } - + MenuStrip sourceMenuStrip = ToolStripManager.GetMainMenuStrip(this); - if (sourceMenuStrip != null && sourceMenuStrip.MdiWindowListItem != null) { - if (MdiWindowListStrip == null) { - MdiWindowListStrip = new MdiWindowListStrip(); + if (sourceMenuStrip != null && sourceMenuStrip.MdiWindowListItem != null) + { + if (MdiWindowListStrip == null) + { + MdiWindowListStrip = new MdiWindowListStrip(); } int nSubItems = sourceMenuStrip.MdiWindowListItem.DropDownItems.Count; - bool shouldIncludeSeparator = (nSubItems > 0 && - !(sourceMenuStrip.MdiWindowListItem.DropDownItems[nSubItems-1] is ToolStripSeparator)); + bool shouldIncludeSeparator = (nSubItems > 0 && + !(sourceMenuStrip.MdiWindowListItem.DropDownItems[nSubItems - 1] is ToolStripSeparator)); //MERGEDEBUG Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiWindowListStrip: Calling populate items."); MdiWindowListStrip.PopulateItems(this, sourceMenuStrip.MdiWindowListItem, shouldIncludeSeparator); //MERGEDEBUG Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiWindowListStrip: mdiwindowlist dd item count before: " + sourceMenuStrip.MdiWindowListItem.DropDownItems.Count.ToString()); @@ -5740,7 +6472,8 @@ protected virtual void OnResizeBegin(EventArgs e) if (CanRaiseEvents) { EventHandler handler = (EventHandler)Events[EVENT_RESIZEBEGIN]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } } @@ -5754,13 +6487,15 @@ protected virtual void OnResizeEnd(EventArgs e) if (CanRaiseEvents) { EventHandler handler = (EventHandler)Events[EVENT_RESIZEEND]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnStyleChanged(EventArgs e) { + protected override void OnStyleChanged(EventArgs e) + { base.OnStyleChanged(e); AdjustSystemMenu(); } @@ -5780,7 +6515,8 @@ private void UpdateWindowIcon(bool redrawFrame) { icon = null; } - else { + else + { icon = Icon; } @@ -5799,15 +6535,15 @@ private void UpdateWindowIcon(bool redrawFrame) if (smallIcon != null) { - SendMessage(Interop.WindowMessages.WM_SETICON,NativeMethods.ICON_SMALL,smallIcon.Handle); + SendMessage(Interop.WindowMessages.WM_SETICON, NativeMethods.ICON_SMALL, smallIcon.Handle); } - SendMessage(Interop.WindowMessages.WM_SETICON,NativeMethods.ICON_BIG,icon.Handle); + SendMessage(Interop.WindowMessages.WM_SETICON, NativeMethods.ICON_BIG, icon.Handle); } else { - SendMessage(Interop.WindowMessages.WM_SETICON,NativeMethods.ICON_SMALL,0); - SendMessage(Interop.WindowMessages.WM_SETICON,NativeMethods.ICON_BIG,0); + SendMessage(Interop.WindowMessages.WM_SETICON, NativeMethods.ICON_SMALL, 0); + SendMessage(Interop.WindowMessages.WM_SETICON, NativeMethods.ICON_BIG, 0); } if (redrawFrame) @@ -5824,32 +6560,38 @@ private void UpdateWindowIcon(bool redrawFrame) // This function is called from all over the place, including my personal favorite, // WM_ERASEBKGRND. Seems that's one of the first messages we get when a user clicks the min/max // button, even before WM_WINDOWPOSCHANGED. - private void UpdateWindowState() { - if (IsHandleCreated) { + private void UpdateWindowState() + { + if (IsHandleCreated) + { FormWindowState oldState = WindowState; NativeMethods.WINDOWPLACEMENT wp = new NativeMethods.WINDOWPLACEMENT(); wp.length = Marshal.SizeOf(); UnsafeNativeMethods.GetWindowPlacement(new HandleRef(this, Handle), ref wp); - switch (wp.showCmd) { + switch (wp.showCmd) + { case NativeMethods.SW_NORMAL: case NativeMethods.SW_RESTORE: case NativeMethods.SW_SHOW: case NativeMethods.SW_SHOWNA: case NativeMethods.SW_SHOWNOACTIVATE: - if (formState[FormStateWindowState] != (int)FormWindowState.Normal) { + if (formState[FormStateWindowState] != (int)FormWindowState.Normal) + { formState[FormStateWindowState] = (int)FormWindowState.Normal; } break; case NativeMethods.SW_SHOWMAXIMIZED: - if (formState[FormStateMdiChildMax] == 0) { + if (formState[FormStateMdiChildMax] == 0) + { formState[FormStateWindowState] = (int)FormWindowState.Maximized; } break; case NativeMethods.SW_SHOWMINIMIZED: case NativeMethods.SW_MINIMIZE: case NativeMethods.SW_SHOWMINNOACTIVE: - if (formState[FormStateMdiChildMax] == 0) { + if (formState[FormStateMdiChildMax] == 0) + { formState[FormStateWindowState] = (int)FormWindowState.Minimized; } break; @@ -5861,9 +6603,11 @@ private void UpdateWindowState() { // If we used to be normal and we just became minimized or maximized, // stash off our current bounds so we can properly restore. // - if (oldState == FormWindowState.Normal && WindowState != FormWindowState.Normal) { + if (oldState == FormWindowState.Normal && WindowState != FormWindowState.Normal) + { - if (WindowState == FormWindowState.Minimized) { + if (WindowState == FormWindowState.Minimized) + { SuspendLayoutForMinimize(); } @@ -5880,11 +6624,13 @@ private void UpdateWindowState() { } // If we just became normal or maximized resume - if (oldState == FormWindowState.Minimized && WindowState != FormWindowState.Minimized) { + if (oldState == FormWindowState.Minimized && WindowState != FormWindowState.Minimized) + { ResumeLayoutFromMinimize(); } - switch (WindowState) { + switch (WindowState) + { case FormWindowState.Normal: SetState(STATE_SIZELOCKEDBYOS, false); break; @@ -5894,7 +6640,8 @@ private void UpdateWindowState() { break; } - if (oldState != WindowState) { + if (oldState != WindowState) + { AdjustSystemMenu(); } } @@ -5906,7 +6653,8 @@ private void UpdateWindowState() { /// for details of exactly which child controls will be validated. /// [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] - public override bool ValidateChildren() { + public override bool ValidateChildren() + { return base.ValidateChildren(); } @@ -5915,14 +6663,16 @@ public override bool ValidateChildren() { /// validated and which controls are skipped is determined by . /// [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] - public override bool ValidateChildren(ValidationConstraints validationConstraints) { + public override bool ValidateChildren(ValidationConstraints validationConstraints) + { return base.ValidateChildren(validationConstraints); } /// /// WM_ACTIVATE handler /// - private void WmActivate(ref Message m) { + private void WmActivate(ref Message m) + { Application.FormActivated(this.Modal, true); // inform MsoComponentManager we're active Active = NativeMethods.Util.LOWORD(m.WParam) != NativeMethods.WA_INACTIVE; Application.FormActivated(this.Modal, Active); // inform MsoComponentManager we're active @@ -5931,7 +6681,8 @@ private void WmActivate(ref Message m) { /// /// WM_ENTERSIZEMOVE handler, so that user can hook up OnResizeBegin event. /// - private void WmEnterSizeMove(ref Message m) { + private void WmEnterSizeMove(ref Message m) + { formStateEx[FormStateExInModalSizingLoop] = 1; OnResizeBegin(EventArgs.Empty); } @@ -5939,7 +6690,8 @@ private void WmEnterSizeMove(ref Message m) { /// /// WM_EXITSIZEMOVE handler, so that user can hook up OnResizeEnd event. /// - private void WmExitSizeMove(ref Message m) { + private void WmExitSizeMove(ref Message m) + { formStateEx[FormStateExInModalSizingLoop] = 0; OnResizeEnd(EventArgs.Empty); } @@ -5947,7 +6699,8 @@ private void WmExitSizeMove(ref Message m) { /// /// WM_CREATE handler /// - private void WmCreate(ref Message m) { + private void WmCreate(ref Message m) + { base.WndProc(ref m); NativeMethods.STARTUPINFO_I si = new NativeMethods.STARTUPINFO_I(); UnsafeNativeMethods.GetStartupInfo(si); @@ -5955,8 +6708,10 @@ private void WmCreate(ref Message m) { // If we've been created from explorer, it may // force us to show up normal. Force our current window state to // the specified state, unless it's _specified_ max or min - if (TopLevel && (si.dwFlags & NativeMethods.STARTF_USESHOWWINDOW) != 0) { - switch (si.wShowWindow) { + if (TopLevel && (si.dwFlags & NativeMethods.STARTF_USESHOWWINDOW) != 0) + { + switch (si.wShowWindow) + { case NativeMethods.SW_MAXIMIZE: WindowState = FormWindowState.Maximized; break; @@ -5970,14 +6725,18 @@ private void WmCreate(ref Message m) { /// /// WM_CLOSE, WM_QUERYENDSESSION, and WM_ENDSESSION handler /// - private void WmClose(ref Message m) { + private void WmClose(ref Message m) + { FormClosingEventArgs e = new FormClosingEventArgs(CloseReason, false); // Pass 1 (WM_CLOSE & WM_QUERYENDSESSION)... Closing // - if (m.Msg != Interop.WindowMessages.WM_ENDSESSION) { - if (Modal) { - if (dialogResult == DialogResult.None) { + if (m.Msg != Interop.WindowMessages.WM_ENDSESSION) + { + if (Modal) + { + if (dialogResult == DialogResult.None) + { dialogResult = DialogResult.Cancel; } CalledClosing = false; @@ -5994,17 +6753,22 @@ private void WmClose(ref Message m) { e.Cancel = !CheckCloseDialog(true); } - else { + else + { e.Cancel = !Validate(true); // Call OnClosing/OnFormClosing on all MDI children - if (IsMdiContainer) { + if (IsMdiContainer) + { FormClosingEventArgs fe = new FormClosingEventArgs(CloseReason.MdiFormClosing, e.Cancel); - foreach(Form mdiChild in MdiChildren) { - if (mdiChild.IsHandleCreated) { + foreach (Form mdiChild in MdiChildren) + { + if (mdiChild.IsHandleCreated) + { mdiChild.OnClosing(fe); mdiChild.OnFormClosing(fe); - if (fe.Cancel) { + if (fe.Cancel) + { // Set the Cancel property for the MDI Container's // FormClosingEventArgs, as well, so that closing the MDI container // will be cancelled. @@ -6021,12 +6785,15 @@ private void WmClose(ref Message m) { // Call OnClosing/OnFormClosing on all the forms that current form owns. Form[] ownedForms = this.OwnedForms; int ownedFormsCount = Properties.GetInteger(PropOwnedFormsCount); - for (int i = ownedFormsCount-1 ; i >= 0; i--) { + for (int i = ownedFormsCount - 1; i >= 0; i--) + { FormClosingEventArgs cfe = new FormClosingEventArgs(CloseReason.FormOwnerClosing, e.Cancel); - if (ownedForms[i] != null) { + if (ownedForms[i] != null) + { //Call OnFormClosing on the child forms. ownedForms[i].OnFormClosing(cfe); - if (cfe.Cancel) { + if (cfe.Cancel) + { // Set the cancel flag for the Owner form e.Cancel = true; break; @@ -6038,34 +6805,43 @@ private void WmClose(ref Message m) { OnFormClosing(e); } - if (m.Msg == Interop.WindowMessages.WM_QUERYENDSESSION) { + if (m.Msg == Interop.WindowMessages.WM_QUERYENDSESSION) + { m.Result = (IntPtr)(e.Cancel ? 0 : 1); } - else if (e.Cancel && (MdiParent != null)) { + else if (e.Cancel && (MdiParent != null)) + { // This is the case of an MDI child close event being canceled by the user. CloseReason = CloseReason.None; } - if (Modal) { + if (Modal) + { return; } } - else { + else + { e.Cancel = m.WParam == IntPtr.Zero; } // Pass 2 (WM_CLOSE & WM_ENDSESSION)... Fire closed // event on all mdi children and ourselves // - if (m.Msg != Interop.WindowMessages.WM_QUERYENDSESSION) { + if (m.Msg != Interop.WindowMessages.WM_QUERYENDSESSION) + { FormClosedEventArgs fc; - if (!e.Cancel) { + if (!e.Cancel) + { IsClosing = true; - if (IsMdiContainer) { + if (IsMdiContainer) + { fc = new FormClosedEventArgs(CloseReason.MdiFormClosing); - foreach(Form mdiChild in MdiChildren) { - if (mdiChild.IsHandleCreated) { + foreach (Form mdiChild in MdiChildren) + { + if (mdiChild.IsHandleCreated) + { mdiChild.IsTopMdiWindowClosing = IsClosing; mdiChild.OnClosed(fc); mdiChild.OnFormClosed(fc); @@ -6076,15 +6852,17 @@ private void WmClose(ref Message m) { // Call OnClosed/OnFormClosed on all the forms that current form owns. Form[] ownedForms = this.OwnedForms; int ownedFormsCount = Properties.GetInteger(PropOwnedFormsCount); - for (int i = ownedFormsCount-1 ; i >= 0; i--) { + for (int i = ownedFormsCount - 1; i >= 0; i--) + { fc = new FormClosedEventArgs(CloseReason.FormOwnerClosing); - if (ownedForms[i] != null) { + if (ownedForms[i] != null) + { //Call OnClosed and OnFormClosed on the child forms. ownedForms[i].OnClosed(fc); ownedForms[i].OnFormClosed(fc); } } - + fc = new FormClosedEventArgs(CloseReason); OnClosed(fc); OnFormClosed(fc); @@ -6097,7 +6875,8 @@ private void WmClose(ref Message m) { /// /// WM_ENTERMENULOOP handler /// - private void WmEnterMenuLoop(ref Message m) { + private void WmEnterMenuLoop(ref Message m) + { OnMenuStart(EventArgs.Empty); base.WndProc(ref m); } @@ -6105,7 +6884,8 @@ private void WmEnterMenuLoop(ref Message m) { /// /// Handles the WM_ERASEBKGND message /// - private void WmEraseBkgnd(ref Message m) { + private void WmEraseBkgnd(ref Message m) + { UpdateWindowState(); base.WndProc(ref m); } @@ -6113,7 +6893,8 @@ private void WmEraseBkgnd(ref Message m) { /// /// WM_EXITMENULOOP handler /// - private void WmExitMenuLoop(ref Message m) { + private void WmExitMenuLoop(ref Message m) + { OnMenuComplete(EventArgs.Empty); base.WndProc(ref m); } @@ -6199,10 +6980,12 @@ private void WmGetMinMaxInfoHelper(ref Message m, Size minTrack, Size maxTrack, /// /// WM_INITMENUPOPUP handler /// - private void WmInitMenuPopup(ref Message m) { + private void WmInitMenuPopup(ref Message m) + { MainMenu curMenu = (MainMenu)Properties.GetObject(PropCurMenu); - if (curMenu != null) { + if (curMenu != null) + { //curMenu.UpdateRtl((RightToLeft == RightToLeft.Yes)); @@ -6215,20 +6998,25 @@ private void WmInitMenuPopup(ref Message m) { /// /// Handles the WM_MENUCHAR message /// - private void WmMenuChar(ref Message m) { + private void WmMenuChar(ref Message m) + { MainMenu curMenu = (MainMenu)Properties.GetObject(PropCurMenu); - if (curMenu == null) { - + if (curMenu == null) + { + Form formMdiParent = (Form)Properties.GetObject(PropFormMdiParent); - if (formMdiParent != null && formMdiParent.Menu != null) { + if (formMdiParent != null && formMdiParent.Menu != null) + { UnsafeNativeMethods.PostMessage(new HandleRef(formMdiParent, formMdiParent.Handle), Interop.WindowMessages.WM_SYSCOMMAND, new IntPtr(NativeMethods.SC_KEYMENU), m.WParam); m.Result = (IntPtr)NativeMethods.Util.MAKELONG(0, 1); return; } } - if (curMenu != null) { + if (curMenu != null) + { curMenu.WmMenuChar(ref m); - if (m.Result != IntPtr.Zero) { + if (m.Result != IntPtr.Zero) + { // This char is a mnemonic on our menu. return; } @@ -6240,30 +7028,38 @@ private void WmMenuChar(ref Message m) { /// /// WM_MDIACTIVATE handler /// - private void WmMdiActivate(ref Message m) { + private void WmMdiActivate(ref Message m) + { base.WndProc(ref m); Debug.Assert(Properties.GetObject(PropFormMdiParent) != null, "how is formMdiParent null?"); Debug.Assert(IsHandleCreated, "how is handle 0?"); Form formMdiParent = (Form)Properties.GetObject(PropFormMdiParent); - if (formMdiParent != null) { + if (formMdiParent != null) + { // This message is propagated twice by the MDIClient window. Once to the // window being deactivated and once to the window being activated. - if (Handle == m.WParam) { + if (Handle == m.WParam) + { formMdiParent.DeactivateMdiChild(); } - else if (Handle == m.LParam) { + else if (Handle == m.LParam) + { formMdiParent.ActivateMdiChild(this); } } } - private void WmNcButtonDown(ref Message m) { - if (IsMdiChild) { + private void WmNcButtonDown(ref Message m) + { + if (IsMdiChild) + { Form formMdiParent = (Form)Properties.GetObject(PropFormMdiParent); - if (formMdiParent.ActiveMdiChildInternal == this) { - if (ActiveControl != null && !ActiveControl.ContainsFocus) { + if (formMdiParent.ActiveMdiChildInternal == this) + { + if (ActiveControl != null && !ActiveControl.ContainsFocus) + { InnerMostActiveContainerControl.FocusActiveControlInternal(); } } @@ -6274,22 +7070,27 @@ private void WmNcButtonDown(ref Message m) { /// /// WM_NCDESTROY handler /// - private void WmNCDestroy(ref Message m) { - MainMenu mainMenu = Menu; - MainMenu dummyMenu = (MainMenu)Properties.GetObject(PropDummyMenu); - MainMenu curMenu = (MainMenu)Properties.GetObject(PropCurMenu); + private void WmNCDestroy(ref Message m) + { + MainMenu mainMenu = Menu; + MainMenu dummyMenu = (MainMenu)Properties.GetObject(PropDummyMenu); + MainMenu curMenu = (MainMenu)Properties.GetObject(PropCurMenu); MainMenu mergedMenu = (MainMenu)Properties.GetObject(PropMergedMenu); - if (mainMenu != null) { + if (mainMenu != null) + { mainMenu.ClearHandles(); } - if (curMenu != null) { + if (curMenu != null) + { curMenu.ClearHandles(); } - if (mergedMenu != null) { + if (mergedMenu != null) + { mergedMenu.ClearHandles(); } - if (dummyMenu != null) { + if (dummyMenu != null) + { dummyMenu.ClearHandles(); } @@ -6300,12 +7101,14 @@ private void WmNCDestroy(ref Message m) { // that point our handle is not actually destroyed so // destroying our parent actually causes a recursive // WM_DESTROY. - if (ownerWindow != null) { + if (ownerWindow != null) + { ownerWindow.DestroyHandle(); ownerWindow = null; } - if (Modal && dialogResult == DialogResult.None) { + if (Modal && dialogResult == DialogResult.None) + { DialogResult = DialogResult.Cancel; } } @@ -6313,15 +7116,17 @@ private void WmNCDestroy(ref Message m) { /// /// WM_NCHITTEST handler /// - private void WmNCHitTest(ref Message m) { - if (formState[FormStateRenderSizeGrip] != 0 ) { + private void WmNCHitTest(ref Message m) + { + if (formState[FormStateRenderSizeGrip] != 0) + { int x = NativeMethods.Util.LOWORD(m.LParam); int y = NativeMethods.Util.HIWORD(m.LParam); // Convert to client coordinates // NativeMethods.POINT pt = new NativeMethods.POINT(x, y); - UnsafeNativeMethods.ScreenToClient(new HandleRef(this, this.Handle), pt ); + UnsafeNativeMethods.ScreenToClient(new HandleRef(this, this.Handle), pt); Size clientSize = ClientSize; @@ -6329,11 +7134,12 @@ private void WmNCHitTest(ref Message m) { // the grip area in this case not to get in the way of the control box. We only need to check for the client's // height since the window width will be at least the size of the control box which is always bigger than the // grip width. - if( pt.x >= (clientSize.Width - SizeGripSize) && - pt.y >= (clientSize.Height - SizeGripSize) && - clientSize.Height >= SizeGripSize){ - m.Result = IsMirrored ? (IntPtr)NativeMethods.HTBOTTOMLEFT : (IntPtr)NativeMethods.HTBOTTOMRIGHT; - return; + if (pt.x >= (clientSize.Width - SizeGripSize) && + pt.y >= (clientSize.Height - SizeGripSize) && + clientSize.Height >= SizeGripSize) + { + m.Result = IsMirrored ? (IntPtr)NativeMethods.HTBOTTOMLEFT : (IntPtr)NativeMethods.HTBOTTOMRIGHT; + return; } } @@ -6344,9 +7150,10 @@ private void WmNCHitTest(ref Message m) { // The edge values are the 8 values from HTLEFT (10) to HTBOTTOMRIGHT (17). if (AutoSizeMode == AutoSizeMode.GrowAndShrink) { - int result = unchecked( (int) (long)m.Result); - if (result >= NativeMethods.HTLEFT && - result <= NativeMethods.HTBOTTOMRIGHT) { + int result = unchecked((int)(long)m.Result); + if (result >= NativeMethods.HTLEFT && + result <= NativeMethods.HTBOTTOMRIGHT) + { m.Result = (IntPtr)NativeMethods.HTBORDER; } } @@ -6356,7 +7163,8 @@ private void WmNCHitTest(ref Message m) { /// /// WM_SHOWWINDOW handler /// - private void WmShowWindow(ref Message m) { + private void WmShowWindow(ref Message m) + { formState[FormStateSWCalled] = 1; base.WndProc(ref m); } @@ -6365,20 +7173,24 @@ private void WmShowWindow(ref Message m) { /// /// WM_SYSCOMMAND handler /// - private void WmSysCommand(ref Message m) { + private void WmSysCommand(ref Message m) + { bool callDefault = true; int sc = (NativeMethods.Util.LOWORD(m.WParam) & 0xFFF0); - switch (sc) { + switch (sc) + { case NativeMethods.SC_CLOSE: CloseReason = CloseReason.UserClosing; - if (IsMdiChild && !ControlBox) { + if (IsMdiChild && !ControlBox) + { callDefault = false; } break; case NativeMethods.SC_KEYMENU: - if (IsMdiChild && !ControlBox) { + if (IsMdiChild && !ControlBox) + { callDefault = false; } break; @@ -6390,17 +7202,20 @@ private void WmSysCommand(ref Message m) { case NativeMethods.SC_CONTEXTHELP: CancelEventArgs e = new CancelEventArgs(false); OnHelpButtonClicked(e); - if (e.Cancel == true) { + if (e.Cancel == true) + { callDefault = false; } break; } - if (Command.DispatchID(NativeMethods.Util.LOWORD(m.WParam))) { + if (Command.DispatchID(NativeMethods.Util.LOWORD(m.WParam))) + { callDefault = false; } - if (callDefault) { + if (callDefault) + { base.WndProc(ref m); } @@ -6409,15 +7224,18 @@ private void WmSysCommand(ref Message m) { /// /// WM_SIZE handler /// - private void WmSize(ref Message m) { + private void WmSize(ref Message m) + { // If this is an MDI parent, don't pass WM_SIZE to the default // window proc. We handle resizing the MDIClient window ourselves // (using ControlDock.FILL). // - if (ctlClient == null) { + if (ctlClient == null) + { base.WndProc(ref m); - if (MdiControlStrip == null && MdiParentInternal != null && MdiParentInternal.ActiveMdiChildInternal == this) { + if (MdiControlStrip == null && MdiParentInternal != null && MdiParentInternal.ActiveMdiChildInternal == this) + { int wParam = m.WParam.ToInt32(); MdiParentInternal.UpdateMdiControlStrip(wParam == NativeMethods.SIZE_MAXIMIZED); } @@ -6427,8 +7245,10 @@ private void WmSize(ref Message m) { /// /// WM_UNINITMENUPOPUP handler /// - private void WmUnInitMenuPopup(ref Message m) { - if (Menu != null) { + private void WmUnInitMenuPopup(ref Message m) + { + if (Menu != null) + { //Whidbey addition - also raise the MainMenu.Collapse event for the current menu Menu.OnCollapse(EventArgs.Empty); } @@ -6437,7 +7257,8 @@ private void WmUnInitMenuPopup(ref Message m) { /// /// WM_WINDOWPOSCHANGED handler /// - private void WmWindowPosChanged(ref Message m) { + private void WmWindowPosChanged(ref Message m) + { // We must update the windowState, because resize is fired // from here... (in Control) @@ -6445,14 +7266,16 @@ private void WmWindowPosChanged(ref Message m) { base.WndProc(ref m); RestoreWindowBoundsIfNecessary(); - } + } /// /// Base wndProc encapsulation. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { case Interop.WindowMessages.WM_NCACTIVATE: base.WndProc(ref m); break; @@ -6469,7 +7292,8 @@ protected override void WndProc(ref Message m) { WmMdiActivate(ref m); break; case Interop.WindowMessages.WM_CLOSE: - if (CloseReason == CloseReason.None) { + if (CloseReason == CloseReason.None) + { CloseReason = CloseReason.TaskManagerClosing; } WmClose(ref m); @@ -6540,7 +7364,8 @@ protected override void WndProc(ref Message m) { // doesn't release it's capture in response to a CAPTURECHANGED // message, so we force capture away if no button is down. // - if (CaptureInternal && MouseButtons == (MouseButtons)0) { + if (CaptureInternal && MouseButtons == (MouseButtons)0) + { CaptureInternal = false; } break; @@ -6561,7 +7386,8 @@ protected override void WndProc(ref Message m) { /// Represents a collection of controls on the form. /// [ComVisible(false)] - public new class ControlCollection : Control.ControlCollection { + public new class ControlCollection : Control.ControlCollection + { private Form owner; @@ -6571,7 +7397,8 @@ protected override void WndProc(ref Message m) { /// Initializes a new instance of the ControlCollection class. /// public ControlCollection(Form owner) - : base(owner) { + : base(owner) + { this.owner = owner; } @@ -6579,13 +7406,17 @@ public ControlCollection(Form owner) /// Adds a control /// to the form. /// - public override void Add(Control value) { - if (value is MdiClient && owner.ctlClient == null) { - if (!owner.TopLevel && !owner.DesignMode) { + public override void Add(Control value) + { + if (value is MdiClient && owner.ctlClient == null) + { + if (!owner.TopLevel && !owner.DesignMode) + { throw new ArgumentException(SR.MDIContainerMustBeTopLevel, "value"); } owner.AutoScroll = false; - if (owner.IsMdiChild) { + if (owner.IsMdiChild) + { throw new ArgumentException(SR.FormMDIParentAndChild, "value"); } owner.ctlClient = (MdiClient)value; @@ -6593,13 +7424,15 @@ public override void Add(Control value) { // make sure we don't add a form that has a valid mdi parent // - if (value is Form && ((Form)value).MdiParentInternal != null) { + if (value is Form && ((Form)value).MdiParentInternal != null) + { throw new ArgumentException(SR.FormMDIParentCannotAdd, "value"); } base.Add(value); - if (owner.ctlClient != null) { + if (owner.ctlClient != null) + { owner.ctlClient.SendToBack(); } } @@ -6608,8 +7441,10 @@ public override void Add(Control value) { /// /// Removes a control from the form. /// - public override void Remove(Control value) { - if (value == owner.ctlClient) { + public override void Remove(Control value) + { + if (value == owner.ctlClient) + { owner.ctlClient = null; } base.Remove(value); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FormClosedEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FormClosedEventArgs.cs index 3ebf00d92dd..0df61bb186f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FormClosedEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FormClosedEventArgs.cs @@ -11,7 +11,7 @@ public class FormClosedEventArgs : EventArgs { public FormClosedEventArgs(CloseReason closeReason) { - CloseReason = closeReason; + CloseReason = closeReason; } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FormClosingEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FormClosingEventArgs.cs index 020b01075ea..47415be0181 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FormClosingEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FormClosingEventArgs.cs @@ -13,7 +13,7 @@ public class FormClosingEventArgs : CancelEventArgs { public FormClosingEventArgs(CloseReason closeReason, bool cancel) : base(cancel) { - CloseReason = closeReason; + CloseReason = closeReason; } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FormCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FormCollection.cs index 69df8ff5160..9231fd63511 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FormCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FormCollection.cs @@ -2,34 +2,42 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Collections; using System.ComponentModel; using System.Globalization; - + /// /// /// This is a read only collection of Forms exposed as a static property of the /// Application class. This is used to store all the currently loaded forms in an app. /// /// - public class FormCollection : ReadOnlyCollectionBase { + public class FormCollection : ReadOnlyCollectionBase + { internal static object CollectionSyncRoot = new object(); - + /// /// /// Gets a form specified by name, if present, else returns null. If there are multiple /// forms with matching names, the first form found is returned. /// /// - public virtual Form this[string name] { - get { - if (name != null) { - lock (CollectionSyncRoot) { - foreach(Form form in InnerList) { - if (string.Equals(form.Name, name, StringComparison.OrdinalIgnoreCase)) { + public virtual Form this[string name] + { + get + { + if (name != null) + { + lock (CollectionSyncRoot) + { + foreach (Form form in InnerList) + { + if (string.Equals(form.Name, name, StringComparison.OrdinalIgnoreCase)) + { return form; } } @@ -38,28 +46,33 @@ public virtual Form this[string name] { return null; } } - + /// /// /// Gets a form specified by index. /// /// - public virtual Form this[int index] { - get { + public virtual Form this[int index] + { + get + { Form f = null; - lock (CollectionSyncRoot) { - f = (Form) InnerList[index]; + lock (CollectionSyncRoot) + { + f = (Form)InnerList[index]; } return f; } } - + /// /// Used internally to add a Form to the FormCollection /// - internal void Add(Form form) { - lock (CollectionSyncRoot) { + internal void Add(Form form) + { + lock (CollectionSyncRoot) + { InnerList.Add(form); } } @@ -80,8 +93,10 @@ internal bool Contains(Form form) /// /// Used internally to add a Form to the FormCollection /// - internal void Remove(Form form) { - lock (CollectionSyncRoot) { + internal void Remove(Form form) + { + lock (CollectionSyncRoot) + { InnerList.Remove(form); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FxCopSuppression.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FxCopSuppression.cs index e984db6bcc2..05aa882dfb9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FxCopSuppression.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FxCopSuppression.cs @@ -3,476 +3,476 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.BindingCompleteEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.BindingManagerDataErrorEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.CacheVirtualItemsEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ColumnClickEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ColumnReorderedEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ColumnWidthChangedEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ColumnWidthChangingEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ComponentModel.Com2Interop.Com2EventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ComponentModel.Com2Interop.GetAttributesEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ComponentModel.Com2Interop.GetBoolValueEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ComponentModel.Com2Interop.GetNameItemEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ComponentModel.Com2Interop.GetRefreshStateEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ComponentModel.Com2Interop.GetTypeConverterAndTypeEditorEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ContentsResizedEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.Control+IPropertyNotifySinkEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ControlEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ConvertEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.DateBoldEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.DateRangeEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.DragEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.DrawItemEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.DrawListViewColumnHeaderEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.DrawListViewItemEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.DrawListViewSubItemEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.DrawToolTipEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.DrawTreeNodeEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.FormClosedEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.FormClosingEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.GiveFeedbackEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.HelpEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.HtmlElementErrorEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.HtmlElementEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.InputLanguageChangedEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.InputLanguageChangingEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.InvalidateEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ItemChangedEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ItemCheckedEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ItemCheckEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ItemDragEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.KeyEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.KeyPressEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.LabelEditEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.LayoutEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.LinkClickedEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.LinkLabelLinkClickedEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ListControlConvertEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ListViewItemMouseHoverEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ListViewItemSelectionChangedEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ListViewVirtualItemsSelectionRangeChangedEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.MaskInputRejectedEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.MeasureItemEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.MouseEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.NavigateEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.NodeLabelEditEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.PaintEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.PopupEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.PreviewKeyDownEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.PropertyGridInternal.GridEntryRecreateChildrenEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.PropertyTabChangedEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.PropertyValueChangedEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.QueryAccessibilityHelpEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.QueryContinueDragEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.QuestionEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.RaftingContainerRenderEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.RetrieveVirtualItemEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ScrollEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.SearchForVirtualItemEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.SelectedGridItemChangedEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.SplitterCancelEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.SplitterEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.StatusBarDrawItemEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.StatusBarPanelClickEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.TabControlCancelEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.TabControlEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.TableLayoutCellPaintEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ToolBarButtonClickEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ToolStripArrowRenderEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ToolStripContentPanelRenderEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ToolStripDropDownClosedEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ToolStripDropDownClosingEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ToolStripGripRenderEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ToolStripItemClickedEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ToolStripItemEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ToolStripItemImageRenderEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ToolStripItemRenderEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ToolStripItemTextRenderEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ToolStripPanelRenderEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ToolStripRenderEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.ToolStripSeparatorRenderEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.TreeNodeMouseClickEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.TreeNodeMouseHoverEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.TreeViewCancelEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.TreeViewEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.TypeValidationEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.UICuesEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.UpDownEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.WebBrowserDocumentCompletedEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.WebBrowserNavigatedEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.WebBrowserNavigatingEventHandler")] -[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope="type", Target="System.Windows.Forms.WebBrowserProgressChangedEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.BindingCompleteEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.BindingManagerDataErrorEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.CacheVirtualItemsEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ColumnClickEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ColumnReorderedEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ColumnWidthChangedEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ColumnWidthChangingEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ComponentModel.Com2Interop.Com2EventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ComponentModel.Com2Interop.GetAttributesEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ComponentModel.Com2Interop.GetBoolValueEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ComponentModel.Com2Interop.GetNameItemEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ComponentModel.Com2Interop.GetRefreshStateEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ComponentModel.Com2Interop.GetTypeConverterAndTypeEditorEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ContentsResizedEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.Control+IPropertyNotifySinkEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ControlEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ConvertEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.DateBoldEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.DateRangeEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.DragEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.DrawItemEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.DrawListViewColumnHeaderEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.DrawListViewItemEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.DrawListViewSubItemEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.DrawToolTipEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.DrawTreeNodeEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.FormClosedEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.FormClosingEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.GiveFeedbackEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.HelpEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.HtmlElementErrorEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.HtmlElementEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.InputLanguageChangedEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.InputLanguageChangingEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.InvalidateEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ItemChangedEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ItemCheckedEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ItemCheckEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ItemDragEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.KeyEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.KeyPressEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.LabelEditEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.LayoutEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.LinkClickedEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.LinkLabelLinkClickedEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ListControlConvertEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ListViewItemMouseHoverEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ListViewItemSelectionChangedEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ListViewVirtualItemsSelectionRangeChangedEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.MaskInputRejectedEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.MeasureItemEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.MouseEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.NavigateEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.NodeLabelEditEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.PaintEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.PopupEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.PreviewKeyDownEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.PropertyGridInternal.GridEntryRecreateChildrenEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.PropertyTabChangedEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.PropertyValueChangedEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.QueryAccessibilityHelpEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.QueryContinueDragEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.QuestionEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.RaftingContainerRenderEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.RetrieveVirtualItemEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ScrollEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.SearchForVirtualItemEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.SelectedGridItemChangedEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.SplitterCancelEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.SplitterEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.StatusBarDrawItemEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.StatusBarPanelClickEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.TabControlCancelEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.TabControlEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.TableLayoutCellPaintEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ToolBarButtonClickEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ToolStripArrowRenderEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ToolStripContentPanelRenderEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ToolStripDropDownClosedEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ToolStripDropDownClosingEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ToolStripGripRenderEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ToolStripItemClickedEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ToolStripItemEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ToolStripItemImageRenderEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ToolStripItemRenderEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ToolStripItemTextRenderEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ToolStripPanelRenderEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ToolStripRenderEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.ToolStripSeparatorRenderEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.TreeNodeMouseClickEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.TreeNodeMouseHoverEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.TreeViewCancelEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.TreeViewEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.TypeValidationEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.UICuesEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.UpDownEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.WebBrowserDocumentCompletedEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.WebBrowserNavigatedEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.WebBrowserNavigatingEventHandler")] +[assembly: SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances", Scope = "type", Target = "System.Windows.Forms.WebBrowserProgressChangedEventHandler")] -[assembly: SuppressMessage("Microsoft.Naming", "CA1701:ResourceStringCompoundWordsShouldBeCasedCorrectly", Scope="resource", Target="System.Windows.Forms.resources", MessageId="checkbox")] -[assembly: SuppressMessage("Microsoft.Naming", "CA1701:ResourceStringCompoundWordsShouldBeCasedCorrectly", Scope="resource", Target="System.Windows.Forms.resources", MessageId="toolbars")] -[assembly: SuppressMessage("Microsoft.Naming", "CA1701:ResourceStringCompoundWordsShouldBeCasedCorrectly", Scope="resource", Target="System.Windows.Forms.resources", MessageId="scrollbars")] -[assembly: SuppressMessage("Microsoft.Naming", "CA1701:ResourceStringCompoundWordsShouldBeCasedCorrectly", Scope="resource", Target="System.Windows.Forms.resources", MessageId="scrollbar")] -[assembly: SuppressMessage("Microsoft.Naming", "CA1701:ResourceStringCompoundWordsShouldBeCasedCorrectly", Scope="resource", Target="System.Windows.Forms.resources", MessageId="AutoSuggest")] -[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope="resource", Target="System.Windows.Forms.resources", MessageId="shorcut")] -[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope="resource", Target="System.Windows.Forms.resources", MessageId="Sortable")] -[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope="resource", Target="System.Windows.Forms.resources", MessageId="Sel")] -[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope="resource", Target="System.Windows.Forms.resources", MessageId="multiline")] -[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope="resource", Target="System.Windows.Forms.resources", MessageId="Multiline")] -[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope="resource", Target="System.Windows.Forms.resources", MessageId="resheader")] -[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope="resource", Target="System.Windows.Forms.resources", MessageId="objs")] -[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope="resource", Target="System.Windows.Forms.resources", MessageId="Renderer")] -[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope="resource", Target="System.Windows.Forms.resources", MessageId="Lresult")] -[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope="resource", Target="System.Windows.Forms.resources", MessageId="Dn")] +[assembly: SuppressMessage("Microsoft.Naming", "CA1701:ResourceStringCompoundWordsShouldBeCasedCorrectly", Scope = "resource", Target = "System.Windows.Forms.resources", MessageId = "checkbox")] +[assembly: SuppressMessage("Microsoft.Naming", "CA1701:ResourceStringCompoundWordsShouldBeCasedCorrectly", Scope = "resource", Target = "System.Windows.Forms.resources", MessageId = "toolbars")] +[assembly: SuppressMessage("Microsoft.Naming", "CA1701:ResourceStringCompoundWordsShouldBeCasedCorrectly", Scope = "resource", Target = "System.Windows.Forms.resources", MessageId = "scrollbars")] +[assembly: SuppressMessage("Microsoft.Naming", "CA1701:ResourceStringCompoundWordsShouldBeCasedCorrectly", Scope = "resource", Target = "System.Windows.Forms.resources", MessageId = "scrollbar")] +[assembly: SuppressMessage("Microsoft.Naming", "CA1701:ResourceStringCompoundWordsShouldBeCasedCorrectly", Scope = "resource", Target = "System.Windows.Forms.resources", MessageId = "AutoSuggest")] +[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "System.Windows.Forms.resources", MessageId = "shorcut")] +[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "System.Windows.Forms.resources", MessageId = "Sortable")] +[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "System.Windows.Forms.resources", MessageId = "Sel")] +[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "System.Windows.Forms.resources", MessageId = "multiline")] +[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "System.Windows.Forms.resources", MessageId = "Multiline")] +[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "System.Windows.Forms.resources", MessageId = "resheader")] +[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "System.Windows.Forms.resources", MessageId = "objs")] +[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "System.Windows.Forms.resources", MessageId = "Renderer")] +[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "System.Windows.Forms.resources", MessageId = "Lresult")] +[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "System.Windows.Forms.resources", MessageId = "Dn")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.Internal.IntSafeNativeMethods.ExtTextOut(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32,System.Windows.Forms.Internal.IntNativeMethods+RECT&,System.String,System.Int32,System.Int32[]):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.Internal.IntSafeNativeMethods.FormatMessage(System.Int32,System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Text.StringBuilder,System.Int32,System.Runtime.InteropServices.HandleRef):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.Internal.IntSafeNativeMethods.GetObject(System.Runtime.InteropServices.HandleRef,System.Int32,System.Windows.Forms.Internal.IntNativeMethods+LOGFONT):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.Internal.IntUnsafeNativeMethods.IntCreateDC(System.String,System.String,System.String,System.Runtime.InteropServices.HandleRef):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.Internal.IntUnsafeNativeMethods.IntCreateIC(System.String,System.String,System.String,System.Runtime.InteropServices.HandleRef):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.NativeMethods+Util.lstrlen(System.String):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.NativeMethods+Util.RegisterWindowMessage(System.String):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.SafeNativeMethods.ChooseColor(System.Windows.Forms.NativeMethods+CHOOSECOLOR):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.SafeNativeMethods.ChooseFont(System.Windows.Forms.NativeMethods+CHOOSEFONT):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.SafeNativeMethods.EnumDisplaySettings(System.String,System.Int32,System.Windows.Forms.NativeMethods+DEVMODE&):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.SafeNativeMethods.FormatMessage(System.Int32,System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Text.StringBuilder,System.Int32,System.Runtime.InteropServices.HandleRef):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.SafeNativeMethods.GetClipboardFormatName(System.Int32,System.Text.StringBuilder,System.Int32):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.SafeNativeMethods.GetCurrentThemeName(System.Text.StringBuilder,System.Int32,System.Text.StringBuilder,System.Int32,System.Text.StringBuilder,System.Int32):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.SafeNativeMethods.GetThemeDocumentationProperty(System.String,System.String,System.Text.StringBuilder,System.Int32):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.SafeNativeMethods.GetThemeFilename(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32,System.Text.StringBuilder,System.Int32):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.SafeNativeMethods.GetThemeFont(System.Runtime.InteropServices.HandleRef,System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LOGFONT):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.SafeNativeMethods.GetThemeString(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32,System.Text.StringBuilder,System.Int32):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.SafeNativeMethods.HtmlHelp(System.Runtime.InteropServices.HandleRef,System.String,System.Int32,System.Int32):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.SafeNativeMethods.HtmlHelp(System.Runtime.InteropServices.HandleRef,System.String,System.Int32,System.String):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.SafeNativeMethods.HtmlHelp(System.Runtime.InteropServices.HandleRef,System.String,System.Int32,System.Windows.Forms.NativeMethods+HH_AKLINK):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.SafeNativeMethods.HtmlHelp(System.Runtime.InteropServices.HandleRef,System.String,System.Int32,System.Windows.Forms.NativeMethods+HH_FTS_QUERY):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.SafeNativeMethods.HtmlHelp(System.Runtime.InteropServices.HandleRef,System.String,System.Int32,System.Windows.Forms.NativeMethods+HH_POPUP):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.SafeNativeMethods.MessageBox(System.Runtime.InteropServices.HandleRef,System.String,System.String,System.Int32):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.OleCreateFontIndirect(System.Windows.Forms.NativeMethods+tagFONTDESC,System.Guid&):System.Windows.Forms.SafeNativeMethods+IFont")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.SafeNativeMethods.OleCreateIFontDispIndirect(System.Windows.Forms.NativeMethods+FONTDESC,System.Guid&):System.Windows.Forms.SafeNativeMethods+IFontDisp")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.OleCreateIFontIndirect(System.Windows.Forms.NativeMethods+FONTDESC,System.Guid&):System.Windows.Forms.SafeNativeMethods+IFont")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.SafeNativeMethods.RegisterClipboardFormat(System.String):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.SafeNativeMethods.RegisterWindowMessage(System.String):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.CopyMemoryA(System.IntPtr,System.String,System.Int32):System.Void")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.DragQueryFile(System.Runtime.InteropServices.HandleRef,System.Int32,System.Text.StringBuilder,System.Int32):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.FindWindow(System.String,System.String):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.GetClassInfo(System.Runtime.InteropServices.HandleRef,System.String,System.IntPtr):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.GetClassInfo(System.Runtime.InteropServices.HandleRef,System.String,System.Windows.Forms.NativeMethods+WNDCLASS_I):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.GetClassName(System.Runtime.InteropServices.HandleRef,System.Text.StringBuilder,System.Int32):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.GetComputerName(System.Text.StringBuilder,System.Int32[]):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.GetLocaleInfo(System.Int32,System.Int32,System.Text.StringBuilder,System.Int32):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.GetMenuItemInfo(System.Runtime.InteropServices.HandleRef,System.Int32,System.Boolean,System.Windows.Forms.NativeMethods+MENUITEMINFO_T):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.GetModuleFileName(System.Runtime.InteropServices.HandleRef,System.Text.StringBuilder,System.Int32):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.GetModuleHandle(System.String):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.GetObject(System.Runtime.InteropServices.HandleRef,System.Int32,System.Windows.Forms.NativeMethods+LOGFONT):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.GetOpenFileName(System.Windows.Forms.NativeMethods+OPENFILENAME_I):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.GetProcAddress(System.Runtime.InteropServices.HandleRef,System.String):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.GetSaveFileName(System.Windows.Forms.NativeMethods+OPENFILENAME_I):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.GetShortPathName(System.String,System.String,System.UInt32):System.UInt32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.GetTempFileName(System.String,System.String,System.Int32,System.Text.StringBuilder):System.Void")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.GetUserName(System.Text.StringBuilder,System.Int32[]):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.GlobalAddAtom(System.String):System.Int16")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.InsertMenuItem(System.Runtime.InteropServices.HandleRef,System.Int32,System.Boolean,System.Windows.Forms.NativeMethods+MENUITEMINFO_T):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.IntCreateDC(System.String,System.String,System.String,System.Runtime.InteropServices.HandleRef):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.IntCreateIC(System.String,System.String,System.String,System.Runtime.InteropServices.HandleRef):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.IntCreateWindowEx(System.Int32,System.String,System.String,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Runtime.InteropServices.HandleRef,System.Runtime.InteropServices.HandleRef,System.Runtime.InteropServices.HandleRef,System.Object):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.LoadLibrary(System.String):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.LookupAccountName(System.String,System.String,System.Byte[],System.Int32&,System.Text.StringBuilder,System.Int32&,System.Int32&):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.OleCreatePropertyFrameIndirect(System.Windows.Forms.NativeMethods+OCPFIPARAMS):System.Void")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.PageSetupDlg(System.Windows.Forms.NativeMethods+PAGESETUPDLG):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.PrintDlg(System.Windows.Forms.NativeMethods+PRINTDLG):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.PrintDlgEx(System.Windows.Forms.NativeMethods+PRINTDLGEX):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.RegisterClass(System.Windows.Forms.NativeMethods+WNDCLASS_D):System.Int16")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.String):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Text.StringBuilder):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+FINDTEXT):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LOGFONT):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVBKIMAGE):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVCOLUMN_T):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TCITEM_T):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TOOLINFO_T):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.IntPtr,System.String):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SetMenuItemInfo(System.Runtime.InteropServices.HandleRef,System.Int32,System.Boolean,System.Windows.Forms.NativeMethods+MENUITEMINFO_T):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.Shell_NotifyIcon(System.Int32,System.Windows.Forms.NativeMethods+NOTIFYICONDATA):System.Int32")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.ShellExecute(System.Runtime.InteropServices.HandleRef,System.String,System.String,System.String,System.String,System.Int32):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SystemParametersInfo(System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LOGFONT,System.Int32):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.SystemParametersInfo(System.Int32,System.Int32,System.Windows.Forms.NativeMethods+NONCLIENTMETRICS,System.Int32):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.UnregisterClass(System.String,System.Runtime.InteropServices.HandleRef):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.OleCreateFontIndirect(System.Windows.Forms.NativeMethods+tagFONTDESC,System.Guid&):System.Windows.Forms.UnsafeNativeMethods+IFont")] -[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods.OleCreateIFontIndirect(System.Windows.Forms.NativeMethods+FONTDESC,System.Guid&):System.Windows.Forms.UnsafeNativeMethods+IFont")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.Internal.IntSafeNativeMethods.ExtTextOut(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32,System.Windows.Forms.Internal.IntNativeMethods+RECT&,System.String,System.Int32,System.Int32[]):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.Internal.IntSafeNativeMethods.FormatMessage(System.Int32,System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Text.StringBuilder,System.Int32,System.Runtime.InteropServices.HandleRef):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.Internal.IntSafeNativeMethods.GetObject(System.Runtime.InteropServices.HandleRef,System.Int32,System.Windows.Forms.Internal.IntNativeMethods+LOGFONT):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.Internal.IntUnsafeNativeMethods.IntCreateDC(System.String,System.String,System.String,System.Runtime.InteropServices.HandleRef):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.Internal.IntUnsafeNativeMethods.IntCreateIC(System.String,System.String,System.String,System.Runtime.InteropServices.HandleRef):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.NativeMethods+Util.lstrlen(System.String):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.NativeMethods+Util.RegisterWindowMessage(System.String):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.SafeNativeMethods.ChooseColor(System.Windows.Forms.NativeMethods+CHOOSECOLOR):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.SafeNativeMethods.ChooseFont(System.Windows.Forms.NativeMethods+CHOOSEFONT):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.SafeNativeMethods.EnumDisplaySettings(System.String,System.Int32,System.Windows.Forms.NativeMethods+DEVMODE&):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.SafeNativeMethods.FormatMessage(System.Int32,System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Text.StringBuilder,System.Int32,System.Runtime.InteropServices.HandleRef):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.SafeNativeMethods.GetClipboardFormatName(System.Int32,System.Text.StringBuilder,System.Int32):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.SafeNativeMethods.GetCurrentThemeName(System.Text.StringBuilder,System.Int32,System.Text.StringBuilder,System.Int32,System.Text.StringBuilder,System.Int32):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.SafeNativeMethods.GetThemeDocumentationProperty(System.String,System.String,System.Text.StringBuilder,System.Int32):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.SafeNativeMethods.GetThemeFilename(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32,System.Text.StringBuilder,System.Int32):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.SafeNativeMethods.GetThemeFont(System.Runtime.InteropServices.HandleRef,System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LOGFONT):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.SafeNativeMethods.GetThemeString(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32,System.Text.StringBuilder,System.Int32):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.SafeNativeMethods.HtmlHelp(System.Runtime.InteropServices.HandleRef,System.String,System.Int32,System.Int32):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.SafeNativeMethods.HtmlHelp(System.Runtime.InteropServices.HandleRef,System.String,System.Int32,System.String):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.SafeNativeMethods.HtmlHelp(System.Runtime.InteropServices.HandleRef,System.String,System.Int32,System.Windows.Forms.NativeMethods+HH_AKLINK):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.SafeNativeMethods.HtmlHelp(System.Runtime.InteropServices.HandleRef,System.String,System.Int32,System.Windows.Forms.NativeMethods+HH_FTS_QUERY):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.SafeNativeMethods.HtmlHelp(System.Runtime.InteropServices.HandleRef,System.String,System.Int32,System.Windows.Forms.NativeMethods+HH_POPUP):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.SafeNativeMethods.MessageBox(System.Runtime.InteropServices.HandleRef,System.String,System.String,System.Int32):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.OleCreateFontIndirect(System.Windows.Forms.NativeMethods+tagFONTDESC,System.Guid&):System.Windows.Forms.SafeNativeMethods+IFont")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.SafeNativeMethods.OleCreateIFontDispIndirect(System.Windows.Forms.NativeMethods+FONTDESC,System.Guid&):System.Windows.Forms.SafeNativeMethods+IFontDisp")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.OleCreateIFontIndirect(System.Windows.Forms.NativeMethods+FONTDESC,System.Guid&):System.Windows.Forms.SafeNativeMethods+IFont")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.SafeNativeMethods.RegisterClipboardFormat(System.String):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.SafeNativeMethods.RegisterWindowMessage(System.String):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.CopyMemoryA(System.IntPtr,System.String,System.Int32):System.Void")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.DragQueryFile(System.Runtime.InteropServices.HandleRef,System.Int32,System.Text.StringBuilder,System.Int32):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.FindWindow(System.String,System.String):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.GetClassInfo(System.Runtime.InteropServices.HandleRef,System.String,System.IntPtr):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.GetClassInfo(System.Runtime.InteropServices.HandleRef,System.String,System.Windows.Forms.NativeMethods+WNDCLASS_I):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.GetClassName(System.Runtime.InteropServices.HandleRef,System.Text.StringBuilder,System.Int32):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.GetComputerName(System.Text.StringBuilder,System.Int32[]):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.GetLocaleInfo(System.Int32,System.Int32,System.Text.StringBuilder,System.Int32):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.GetMenuItemInfo(System.Runtime.InteropServices.HandleRef,System.Int32,System.Boolean,System.Windows.Forms.NativeMethods+MENUITEMINFO_T):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.GetModuleFileName(System.Runtime.InteropServices.HandleRef,System.Text.StringBuilder,System.Int32):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.GetModuleHandle(System.String):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.GetObject(System.Runtime.InteropServices.HandleRef,System.Int32,System.Windows.Forms.NativeMethods+LOGFONT):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.GetOpenFileName(System.Windows.Forms.NativeMethods+OPENFILENAME_I):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.GetProcAddress(System.Runtime.InteropServices.HandleRef,System.String):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.GetSaveFileName(System.Windows.Forms.NativeMethods+OPENFILENAME_I):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.GetShortPathName(System.String,System.String,System.UInt32):System.UInt32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.GetTempFileName(System.String,System.String,System.Int32,System.Text.StringBuilder):System.Void")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.GetUserName(System.Text.StringBuilder,System.Int32[]):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.GlobalAddAtom(System.String):System.Int16")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.InsertMenuItem(System.Runtime.InteropServices.HandleRef,System.Int32,System.Boolean,System.Windows.Forms.NativeMethods+MENUITEMINFO_T):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.IntCreateDC(System.String,System.String,System.String,System.Runtime.InteropServices.HandleRef):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.IntCreateIC(System.String,System.String,System.String,System.Runtime.InteropServices.HandleRef):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.IntCreateWindowEx(System.Int32,System.String,System.String,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Runtime.InteropServices.HandleRef,System.Runtime.InteropServices.HandleRef,System.Runtime.InteropServices.HandleRef,System.Object):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.LoadLibrary(System.String):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.LookupAccountName(System.String,System.String,System.Byte[],System.Int32&,System.Text.StringBuilder,System.Int32&,System.Int32&):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.OleCreatePropertyFrameIndirect(System.Windows.Forms.NativeMethods+OCPFIPARAMS):System.Void")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.PageSetupDlg(System.Windows.Forms.NativeMethods+PAGESETUPDLG):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.PrintDlg(System.Windows.Forms.NativeMethods+PRINTDLG):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.PrintDlgEx(System.Windows.Forms.NativeMethods+PRINTDLGEX):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.RegisterClass(System.Windows.Forms.NativeMethods+WNDCLASS_D):System.Int16")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.String):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Text.StringBuilder):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+FINDTEXT):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LOGFONT):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVBKIMAGE):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LVCOLUMN_T):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TCITEM_T):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Windows.Forms.NativeMethods+TOOLINFO_T):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef,System.Int32,System.IntPtr,System.String):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SetMenuItemInfo(System.Runtime.InteropServices.HandleRef,System.Int32,System.Boolean,System.Windows.Forms.NativeMethods+MENUITEMINFO_T):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.Shell_NotifyIcon(System.Int32,System.Windows.Forms.NativeMethods+NOTIFYICONDATA):System.Int32")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.ShellExecute(System.Runtime.InteropServices.HandleRef,System.String,System.String,System.String,System.String,System.Int32):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SystemParametersInfo(System.Int32,System.Int32,System.Windows.Forms.NativeMethods+LOGFONT,System.Int32):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.SystemParametersInfo(System.Int32,System.Int32,System.Windows.Forms.NativeMethods+NONCLIENTMETRICS,System.Int32):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.UnregisterClass(System.String,System.Runtime.InteropServices.HandleRef):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.OleCreateFontIndirect(System.Windows.Forms.NativeMethods+tagFONTDESC,System.Guid&):System.Windows.Forms.UnsafeNativeMethods+IFont")] +[assembly: SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods.OleCreateIFontIndirect(System.Windows.Forms.NativeMethods+FONTDESC,System.Guid&):System.Windows.Forms.UnsafeNativeMethods+IFont")] // -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.ColumnHeader.Clone():System.Object")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.DataGridViewComboBoxColumn.Clone():System.Object")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.DataGridViewColumn.Clone():System.Object")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.DataGridViewHeaderCell.Clone():System.Object")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.DataGridViewImageCell.Clone():System.Object")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.DataGridViewCheckBoxCell.Clone():System.Object")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.DataGridViewButtonColumn.Clone():System.Object")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.DataGridViewLinkCell.Clone():System.Object")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.DataGridViewColumnHeaderCell.Clone():System.Object")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.TreeNode.Clone():System.Object")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.DataGridViewImageColumn.Clone():System.Object")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.DataGridViewRow.Clone():System.Object")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.ListViewItem.Clone():System.Object")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.DataGridViewTextBoxCell.Clone():System.Object")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.DataGridViewRowHeaderCell.Clone():System.Object")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.DataGridViewBand.get_HeaderCellCore():System.Windows.Forms.DataGridViewHeaderCell")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.DataGridViewBand.Clone():System.Object")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.DataGridViewBand.set_DefaultHeaderCellType(System.Type):System.Void")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.DataGridViewLinkColumn.Clone():System.Object")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.DataGridViewCell.Clone():System.Object")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.MenuItem.MergeMenu():System.Windows.Forms.MenuItem")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.DataGridViewComboBoxCell.Clone():System.Object")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.DataGridViewButtonCell.Clone():System.Object")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.FeatureSupport.IsPresent(System.String,System.String,System.Version):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope="member", Target="System.Windows.Forms.FeatureSupport.GetVersionPresent(System.String,System.String):System.Version")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.ColumnHeader.Clone():System.Object")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.DataGridViewComboBoxColumn.Clone():System.Object")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.DataGridViewColumn.Clone():System.Object")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.DataGridViewHeaderCell.Clone():System.Object")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.DataGridViewImageCell.Clone():System.Object")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.DataGridViewCheckBoxCell.Clone():System.Object")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.DataGridViewButtonColumn.Clone():System.Object")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.DataGridViewLinkCell.Clone():System.Object")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.DataGridViewColumnHeaderCell.Clone():System.Object")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.TreeNode.Clone():System.Object")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.DataGridViewImageColumn.Clone():System.Object")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.DataGridViewRow.Clone():System.Object")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.ListViewItem.Clone():System.Object")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.DataGridViewTextBoxCell.Clone():System.Object")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.DataGridViewRowHeaderCell.Clone():System.Object")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.DataGridViewBand.get_HeaderCellCore():System.Windows.Forms.DataGridViewHeaderCell")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.DataGridViewBand.Clone():System.Object")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.DataGridViewBand.set_DefaultHeaderCellType(System.Type):System.Void")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.DataGridViewLinkColumn.Clone():System.Object")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.DataGridViewCell.Clone():System.Object")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.MenuItem.MergeMenu():System.Windows.Forms.MenuItem")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.DataGridViewComboBoxCell.Clone():System.Object")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.DataGridViewButtonCell.Clone():System.Object")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.FeatureSupport.IsPresent(System.String,System.String,System.Version):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods", Scope = "member", Target = "System.Windows.Forms.FeatureSupport.GetVersionPresent(System.String,System.String):System.Version")] // Following message suppressions are for MaskedTextBox unsupported base methods/properties. -[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope="member", Target="System.Windows.Forms.MaskedTextBox.add_AcceptsTabChanged(System.EventHandler):System.Void")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope="member", Target="System.Windows.Forms.MaskedTextBox.add_AcceptsTabChanged(System.EventHandler):System.Void")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope="member", Target="System.Windows.Forms.MaskedTextBox.add_MultilineChanged(System.EventHandler):System.Void")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope="member", Target="System.Windows.Forms.MaskedTextBox.add_MultilineChanged(System.EventHandler):System.Void")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope="member", Target="System.Windows.Forms.MaskedTextBox.GetFirstCharIndexFromLine(System.Int32):System.Int32")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope="member", Target="System.Windows.Forms.MaskedTextBox.GetFirstCharIndexFromLine(System.Int32):System.Int32")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope="member", Target="System.Windows.Forms.MaskedTextBox.remove_AcceptsTabChanged(System.EventHandler):System.Void")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope="member", Target="System.Windows.Forms.MaskedTextBox.remove_AcceptsTabChanged(System.EventHandler):System.Void")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope="member", Target="System.Windows.Forms.MaskedTextBox.remove_MultilineChanged(System.EventHandler):System.Void")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope="member", Target="System.Windows.Forms.MaskedTextBox.remove_MultilineChanged(System.EventHandler):System.Void")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope="member", Target="System.Windows.Forms.MaskedTextBox.set_AcceptsTab(System.Boolean):System.Void")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope="member", Target="System.Windows.Forms.MaskedTextBox.set_AcceptsTab(System.Boolean):System.Void")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope="member", Target="System.Windows.Forms.MaskedTextBox.set_Lines(System.String[]):System.Void")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope="member", Target="System.Windows.Forms.MaskedTextBox.set_Lines(System.String[]):System.Void")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope="member", Target="System.Windows.Forms.MaskedTextBox.set_Padding(System.Windows.Forms.Padding):System.Void")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope="member", Target="System.Windows.Forms.MaskedTextBox.set_Padding(System.Windows.Forms.Padding):System.Void")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope="member", Target="System.Windows.Forms.MaskedTextBox.set_WordWrap(System.Boolean):System.Void")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope="member", Target="System.Windows.Forms.MaskedTextBox.set_WordWrap(System.Boolean):System.Void")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Scope="member", Target="System.Windows.Forms.MaskedTextBox.Lines")] -[assembly: SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Scope="member", Target="System.Windows.Forms.MaskedTextBox.Lines")] -[assembly: SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Scope="member", Target="System.Windows.Forms.MaskedTextBox.GetFirstCharIndexOfCurrentLine():System.Int32")] -[assembly: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope="member", Target="System.Windows.Forms.MaskedTextBox.MultilineChanged")] -[assembly: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope="member", Target="System.Windows.Forms.MaskedTextBox.PerformTypeValidation(System.ComponentModel.CancelEventArgs):System.Object")] -[assembly: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope="member", Target="System.Windows.Forms.MaskedTextBox.WmCopy():System.Boolean")] -[assembly: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope="member", Target="System.Windows.Forms.MaskedTextBox.WmPaste():System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.add_AcceptsTabChanged(System.EventHandler):System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.add_AcceptsTabChanged(System.EventHandler):System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.add_MultilineChanged(System.EventHandler):System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.add_MultilineChanged(System.EventHandler):System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.GetFirstCharIndexFromLine(System.Int32):System.Int32")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.GetFirstCharIndexFromLine(System.Int32):System.Int32")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.remove_AcceptsTabChanged(System.EventHandler):System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.remove_AcceptsTabChanged(System.EventHandler):System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.remove_MultilineChanged(System.EventHandler):System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.remove_MultilineChanged(System.EventHandler):System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.set_AcceptsTab(System.Boolean):System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.set_AcceptsTab(System.Boolean):System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.set_Lines(System.String[]):System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.set_Lines(System.String[]):System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.set_Padding(System.Windows.Forms.Padding):System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.set_Padding(System.Windows.Forms.Padding):System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.set_WordWrap(System.Boolean):System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.set_WordWrap(System.Boolean):System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.Lines")] +[assembly: SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.Lines")] +[assembly: SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.GetFirstCharIndexOfCurrentLine():System.Int32")] +[assembly: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.MultilineChanged")] +[assembly: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.PerformTypeValidation(System.ComponentModel.CancelEventArgs):System.Object")] +[assembly: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.WmCopy():System.Boolean")] +[assembly: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "System.Windows.Forms.MaskedTextBox.WmPaste():System.Void")] //SafeHandle Suppressions. -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Design.ComponentEditorForm+PageSelector.hbrushDither")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.VisualStyles.VisualStyleRenderer+ThemeHandle._hTheme")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.ToolStripMenuItem.nativeMenuHandle")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.ToolStripMenuItem.targetWindowHandle")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.ComponentModel.Com2Interop.Com2FontConverter.lastHandle")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.ComponentModel.Com2Interop.BaseCAMarshaler.caArrayAddress")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.ComponentModel.Com2Interop.Com2PictureConverter.lastNativeHandle")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.PropertyGridInternal.PropertyGridView.baseHfont")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.PropertyGridInternal.PropertyGridView.boldHfont")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.PropertyGridInternal.PropertyGridView+MouseHook.mouseHookHandle")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Internal.WindowsBrush.nativeHandle")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Internal.WindowsFont.hFont")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Internal.WindowsPen.nativeHandle")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Internal.WindowsBitmap.nativeHandle")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.WindowsFormsUtils+ScreenGraphics.hDC")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+MEASUREITEMSTRUCT.itemData")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.ToolBarButton.stringIndex")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target=",System.Windows.Forms.NativeMethods+LOGBRUSH.lbHatch")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.AxHost.hwndFocus")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.AxHost.wndprocAddr")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.RichTextBox.moduleHandle")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+EDITSTREAM.dwCookie")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+CLIENTCREATESTRUCT.hWindowMenu")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+COPYDATASTRUCT.lpData")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+LVITEM.puColumns")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+LVITEM.lParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.ImageList+NativeImageList.himl")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+WINDOWPOS.hwndInsertAfter")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+WINDOWPOS.hwnd")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+PAINTSTRUCT.hdc")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TEXTRANGE.lpstrText")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods+tagQACONTAINER.hpal")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+VARIANT.data2")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+VARIANT.data1")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+OCPFIPARAMS.hwndOwner")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+OCPFIPARAMS.ppUnk")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+OCPFIPARAMS.uuid")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Control+ActiveXImpl.accelTable")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Control+ActiveXImpl.clipRegion")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Control+ActiveXImpl.hwndParent")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+LVITEM_NOTEXT.pszText")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+LVITEM_NOTEXT.lParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.CreateParams.parent")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.InputLanguage.handle")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+tagFUNCDESC.lprgelemdescParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+HDITEM.hbm")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+HDITEM.pvFilter")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+HDITEM.lParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+NMHEADER.pItem")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+PICTDESCicon.hicon")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+ENDROPFILES.hDrop")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+MENUITEMINFO_T.hbmpChecked")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+MENUITEMINFO_T.dwItemData")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+MENUITEMINFO_T.hSubMenu")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+MENUITEMINFO_T.hbmpUnchecked")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+PICTDESC.union1")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+MENUITEMINFO_T_RW.hbmpChecked")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+MENUITEMINFO_T_RW.hbmpItem")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+MENUITEMINFO_T_RW.dwItemData")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+MENUITEMINFO_T_RW.dwTypeData")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+MENUITEMINFO_T_RW.hSubMenu")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+MENUITEMINFO_T_RW.hbmpUnchecked")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TV_ITEM.pszText")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TV_ITEM.hItem")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TV_ITEM.lParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+tagPARAMDESC.pparamdescex")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Message.result")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Message.wparam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Message.hWnd")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Message.lparam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+NMLISTVIEW.lParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.ToolStrip.hwndThatLostFocus")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TCITEM_T.lParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TOOLINFO_T.uId")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TOOLINFO_T.hinst")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TOOLINFO_T.hwnd")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TOOLINFO_T.lParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+NMTOOLBAR.pszText")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+EVENTMSG.hwnd")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+NMLVDISPINFO_UNSAFE.idFrom")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+NMLVDISPINFO_UNSAFE.pszText")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+NMLVDISPINFO_UNSAFE.hwndFrom")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+NMLVDISPINFO_UNSAFE.puColumns")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+NMLVDISPINFO_UNSAFE.lParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+NMTVGETINFOTIP.lParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+NMTVGETINFOTIP.item")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Control.originalImeContext")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.CommonDialog.defaultControlHwnd")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+MSG.lParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+MSG.wParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+MSG.hwnd")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.ToolStripManager+ModalMenuFilter._lastActiveWindow")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.ToolStripManager+ModalMenuFilter._activeHwnd")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+WNDCLASS_D.hbrBackground")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+WNDCLASS_D.hIcon")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+WNDCLASS_D.hInstance")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+WNDCLASS_D.hCursor")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Control+FontHandleWrapper.handle")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Screen.hmonitor")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+tagVARDESC.lpstrSchema")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+tagVARDESC.unionMember")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.DataGridRow.tooltipID")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+tagCONTROLINFO.hAccel")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+PICTDESCemf.hemf")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+ICONINFO.hbmMask")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+ICONINFO.hbmColor")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.DateTimePicker+EnumChildren.hwndFound")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+HDLAYOUT.prc")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+HDLAYOUT.pwpos")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+tagTYPEATTR.lpstrSchema")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+STARTUPINFO_I.lpReserved2")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+STARTUPINFO_I.lpReserved")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+STARTUPINFO_I.lpDesktop")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+STARTUPINFO_I.lpTitle")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+STARTUPINFO_I.hStdError")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+STARTUPINFO_I.hStdOutput")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+STARTUPINFO_I.hStdInput")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+NMDAYSTATE.prgDayState")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+PICTDESCbmp.hbitmap")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+PICTDESCbmp.hpalette")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+NOTIFYICONDATA.hWnd")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+NOTIFYICONDATA.hIcon")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+CA_STRUCT.pElems")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+LVFINDINFO.lParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+WNDCLASS_I.hbrBackground")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+WNDCLASS_I.lpszMenuName")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+WNDCLASS_I.hIcon")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+WNDCLASS_I.hInstance")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+WNDCLASS_I.lpszClassName")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+WNDCLASS_I.lpfnWndProc")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+WNDCLASS_I.hCursor")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TOOLTIPTEXTA.hinst")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+NMHDR.hwndFrom")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+NMHDR.idFrom")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+ENLINK.lParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+ENLINK.wParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+tagCAUUID.pElems")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+tagOIFI.hAccel")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+tagOIFI.hwndFrame")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods.InvalidIntPtr")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods.LPSTR_TEXTCALLBACK")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods.NullHandleRef")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.SendKeys+SKEvent.hwnd")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+HELPINFO.hItemHandle")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+ENPROTECTED.lParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+ENPROTECTED.wParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+LVCOLUMN.pszText")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+IMAGELISTDRAWPARAMS.hdcDst")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+IMAGELISTDRAWPARAMS.himl")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.CachedItemHdcInfo.cachedItemBitmap")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.CachedItemHdcInfo.cachedItemHDC")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+NMCUSTOMDRAW.hdc")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+NMCUSTOMDRAW.lItemlParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+NMCUSTOMDRAW.dwItemSpec")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TVSORTCB.lParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TVSORTCB.hParent")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+DRAWITEMSTRUCT.hDC")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+DRAWITEMSTRUCT.hwndItem")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+DRAWITEMSTRUCT.itemData")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+HDITEM2.pvFilter")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+HDITEM2.hbm")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+HDITEM2.pszText_notUsed")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+HDITEM2.lParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.StatusBar+ControlToolTip+Tool.id")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TBBUTTON.iString")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TBBUTTON.dwData")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Application+ThreadContext.handle")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods+OFNOTIFY.lpOFN")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods+OFNOTIFY.pszFile")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods+OFNOTIFY.hdr_hwndFrom")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.UnsafeNativeMethods+OFNOTIFY.hdr_idFrom")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TOOLINFO_TOOLTIP.uId")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TOOLINFO_TOOLTIP.lpszText")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TOOLINFO_TOOLTIP.hinst")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TOOLINFO_TOOLTIP.hwnd")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TOOLINFO_TOOLTIP.lParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.ErrorProvider+ControlItem.id")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeWindow+WindowClass.defWindowProc")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+MOUSEHOOKSTRUCT.hWnd")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+tagDISPPARAMS.rgdispidNamedArgs")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+tagDISPPARAMS.rgvarg")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TV_HITTESTINFO.hItem")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TV_INSERTSTRUCT.item_pszText")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TV_INSERTSTRUCT.item_hItem")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TV_INSERTSTRUCT.hInsertAfter")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TV_INSERTSTRUCT.item_lParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TV_INSERTSTRUCT.hParent")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+LVGROUP.pszHeader")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+LVGROUP.pszFooter")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+IMAGEINFO.hbmImage")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+IMAGEINFO.hbmMask")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Control+MetafileDCWrapper.hMetafileDC")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Control+MetafileDCWrapper.hBitmap")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Control+MetafileDCWrapper.hBitmapDC")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Control+MetafileDCWrapper.hOriginalBmp")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TRACKMOUSEEVENT.hwndTrack")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+tagTYPEDESC.unionMember")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+LVBKIMAGE.hBmp")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.WebBrowserBase.hwndFocus")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+NMLVGETINFOTIP.lpszText")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+NMLVGETINFOTIP.lParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TBBUTTONINFO.pszText")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TBBUTTONINFO.lParam")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Application+ThreadWindows.focusedHwnd")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Application+ThreadWindows.activeHwnd")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+TOOLTIPTEXT.hinst")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+tagEXCEPINFO.pvReserved")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+tagEXCEPINFO.pfnDeferredFillIn")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.SystemInformation.processWinStation")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+HIGHCONTRAST_I.lpszDefaultScheme")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.NativeMethods+LOGBRUSH.lbHatch")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.ComponentModel.Com2Interop.Com2PictureConverter.lastPalette")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Design.ComponentEditorForm+PageSelector.hbrushDither")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.VisualStyles.VisualStyleRenderer+ThemeHandle._hTheme")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.ToolStripMenuItem.nativeMenuHandle")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.ToolStripMenuItem.targetWindowHandle")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.ComponentModel.Com2Interop.Com2FontConverter.lastHandle")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.ComponentModel.Com2Interop.BaseCAMarshaler.caArrayAddress")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.ComponentModel.Com2Interop.Com2PictureConverter.lastNativeHandle")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.PropertyGridInternal.PropertyGridView.baseHfont")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.PropertyGridInternal.PropertyGridView.boldHfont")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.PropertyGridInternal.PropertyGridView+MouseHook.mouseHookHandle")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsBrush.nativeHandle")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsFont.hFont")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsPen.nativeHandle")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsBitmap.nativeHandle")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.WindowsFormsUtils+ScreenGraphics.hDC")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+MEASUREITEMSTRUCT.itemData")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.ToolBarButton.stringIndex")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = ",System.Windows.Forms.NativeMethods+LOGBRUSH.lbHatch")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.AxHost.hwndFocus")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.AxHost.wndprocAddr")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.RichTextBox.moduleHandle")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+EDITSTREAM.dwCookie")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+CLIENTCREATESTRUCT.hWindowMenu")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+COPYDATASTRUCT.lpData")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+LVITEM.puColumns")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+LVITEM.lParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.ImageList+NativeImageList.himl")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+WINDOWPOS.hwndInsertAfter")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+WINDOWPOS.hwnd")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+PAINTSTRUCT.hdc")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TEXTRANGE.lpstrText")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods+tagQACONTAINER.hpal")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+VARIANT.data2")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+VARIANT.data1")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+OCPFIPARAMS.hwndOwner")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+OCPFIPARAMS.ppUnk")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+OCPFIPARAMS.uuid")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Control+ActiveXImpl.accelTable")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Control+ActiveXImpl.clipRegion")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Control+ActiveXImpl.hwndParent")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+LVITEM_NOTEXT.pszText")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+LVITEM_NOTEXT.lParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.CreateParams.parent")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.InputLanguage.handle")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+tagFUNCDESC.lprgelemdescParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+HDITEM.hbm")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+HDITEM.pvFilter")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+HDITEM.lParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+NMHEADER.pItem")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+PICTDESCicon.hicon")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+ENDROPFILES.hDrop")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+MENUITEMINFO_T.hbmpChecked")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+MENUITEMINFO_T.dwItemData")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+MENUITEMINFO_T.hSubMenu")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+MENUITEMINFO_T.hbmpUnchecked")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+PICTDESC.union1")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+MENUITEMINFO_T_RW.hbmpChecked")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+MENUITEMINFO_T_RW.hbmpItem")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+MENUITEMINFO_T_RW.dwItemData")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+MENUITEMINFO_T_RW.dwTypeData")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+MENUITEMINFO_T_RW.hSubMenu")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+MENUITEMINFO_T_RW.hbmpUnchecked")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TV_ITEM.pszText")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TV_ITEM.hItem")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TV_ITEM.lParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+tagPARAMDESC.pparamdescex")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Message.result")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Message.wparam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Message.hWnd")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Message.lparam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+NMLISTVIEW.lParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.ToolStrip.hwndThatLostFocus")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TCITEM_T.lParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TOOLINFO_T.uId")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TOOLINFO_T.hinst")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TOOLINFO_T.hwnd")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TOOLINFO_T.lParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+NMTOOLBAR.pszText")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+EVENTMSG.hwnd")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+NMLVDISPINFO_UNSAFE.idFrom")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+NMLVDISPINFO_UNSAFE.pszText")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+NMLVDISPINFO_UNSAFE.hwndFrom")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+NMLVDISPINFO_UNSAFE.puColumns")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+NMLVDISPINFO_UNSAFE.lParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+NMTVGETINFOTIP.lParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+NMTVGETINFOTIP.item")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Control.originalImeContext")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.CommonDialog.defaultControlHwnd")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+MSG.lParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+MSG.wParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+MSG.hwnd")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.ToolStripManager+ModalMenuFilter._lastActiveWindow")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.ToolStripManager+ModalMenuFilter._activeHwnd")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+WNDCLASS_D.hbrBackground")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+WNDCLASS_D.hIcon")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+WNDCLASS_D.hInstance")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+WNDCLASS_D.hCursor")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Control+FontHandleWrapper.handle")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Screen.hmonitor")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+tagVARDESC.lpstrSchema")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+tagVARDESC.unionMember")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.DataGridRow.tooltipID")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+tagCONTROLINFO.hAccel")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+PICTDESCemf.hemf")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+ICONINFO.hbmMask")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+ICONINFO.hbmColor")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.DateTimePicker+EnumChildren.hwndFound")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+HDLAYOUT.prc")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+HDLAYOUT.pwpos")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+tagTYPEATTR.lpstrSchema")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+STARTUPINFO_I.lpReserved2")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+STARTUPINFO_I.lpReserved")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+STARTUPINFO_I.lpDesktop")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+STARTUPINFO_I.lpTitle")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+STARTUPINFO_I.hStdError")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+STARTUPINFO_I.hStdOutput")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+STARTUPINFO_I.hStdInput")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+NMDAYSTATE.prgDayState")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+PICTDESCbmp.hbitmap")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+PICTDESCbmp.hpalette")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+NOTIFYICONDATA.hWnd")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+NOTIFYICONDATA.hIcon")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+CA_STRUCT.pElems")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+LVFINDINFO.lParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+WNDCLASS_I.hbrBackground")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+WNDCLASS_I.lpszMenuName")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+WNDCLASS_I.hIcon")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+WNDCLASS_I.hInstance")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+WNDCLASS_I.lpszClassName")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+WNDCLASS_I.lpfnWndProc")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+WNDCLASS_I.hCursor")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TOOLTIPTEXTA.hinst")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+NMHDR.hwndFrom")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+NMHDR.idFrom")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+ENLINK.lParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+ENLINK.wParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+tagCAUUID.pElems")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+tagOIFI.hAccel")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+tagOIFI.hwndFrame")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods.InvalidIntPtr")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods.LPSTR_TEXTCALLBACK")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods.NullHandleRef")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.SendKeys+SKEvent.hwnd")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+HELPINFO.hItemHandle")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+ENPROTECTED.lParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+ENPROTECTED.wParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+LVCOLUMN.pszText")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+IMAGELISTDRAWPARAMS.hdcDst")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+IMAGELISTDRAWPARAMS.himl")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.CachedItemHdcInfo.cachedItemBitmap")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.CachedItemHdcInfo.cachedItemHDC")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+NMCUSTOMDRAW.hdc")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+NMCUSTOMDRAW.lItemlParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+NMCUSTOMDRAW.dwItemSpec")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TVSORTCB.lParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TVSORTCB.hParent")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+DRAWITEMSTRUCT.hDC")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+DRAWITEMSTRUCT.hwndItem")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+DRAWITEMSTRUCT.itemData")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+HDITEM2.pvFilter")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+HDITEM2.hbm")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+HDITEM2.pszText_notUsed")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+HDITEM2.lParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.StatusBar+ControlToolTip+Tool.id")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TBBUTTON.iString")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TBBUTTON.dwData")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Application+ThreadContext.handle")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods+OFNOTIFY.lpOFN")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods+OFNOTIFY.pszFile")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods+OFNOTIFY.hdr_hwndFrom")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.UnsafeNativeMethods+OFNOTIFY.hdr_idFrom")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TOOLINFO_TOOLTIP.uId")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TOOLINFO_TOOLTIP.lpszText")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TOOLINFO_TOOLTIP.hinst")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TOOLINFO_TOOLTIP.hwnd")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TOOLINFO_TOOLTIP.lParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.ErrorProvider+ControlItem.id")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeWindow+WindowClass.defWindowProc")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+MOUSEHOOKSTRUCT.hWnd")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+tagDISPPARAMS.rgdispidNamedArgs")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+tagDISPPARAMS.rgvarg")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TV_HITTESTINFO.hItem")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TV_INSERTSTRUCT.item_pszText")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TV_INSERTSTRUCT.item_hItem")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TV_INSERTSTRUCT.hInsertAfter")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TV_INSERTSTRUCT.item_lParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TV_INSERTSTRUCT.hParent")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+LVGROUP.pszHeader")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+LVGROUP.pszFooter")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+IMAGEINFO.hbmImage")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+IMAGEINFO.hbmMask")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Control+MetafileDCWrapper.hMetafileDC")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Control+MetafileDCWrapper.hBitmap")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Control+MetafileDCWrapper.hBitmapDC")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Control+MetafileDCWrapper.hOriginalBmp")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TRACKMOUSEEVENT.hwndTrack")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+tagTYPEDESC.unionMember")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+LVBKIMAGE.hBmp")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.WebBrowserBase.hwndFocus")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+NMLVGETINFOTIP.lpszText")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+NMLVGETINFOTIP.lParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TBBUTTONINFO.pszText")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TBBUTTONINFO.lParam")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Application+ThreadWindows.focusedHwnd")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Application+ThreadWindows.activeHwnd")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+TOOLTIPTEXT.hinst")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+tagEXCEPINFO.pvReserved")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+tagEXCEPINFO.pfnDeferredFillIn")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.SystemInformation.processWinStation")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+HIGHCONTRAST_I.lpszDefaultScheme")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.NativeMethods+LOGBRUSH.lbHatch")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.ComponentModel.Com2Interop.Com2PictureConverter.lastPalette")] //LinkDemands reviewed as part of security push [assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.ToolStripDropDownMenu..ctor(System.Windows.Forms.ToolStripItem)")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.ToolStripDropDownMenu.ShortcutToText(System.Windows.Forms.Keys,System.String):System.String")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.ToolStripDropDownMenu.ShortcutToText(System.Windows.Forms.Keys,System.String):System.String")] -[module: SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatRequireUnboxing", Scope="member", Target="System.Windows.Forms.ComponentModel.Com2Interop.ComNativeDescriptor.OnPropsInfoDisposed(System.Object,System.EventArgs):System.Void", MessageId="System.Collections.IEnumerator.get_Current")] -[module: SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatRequireUnboxing", Scope="member", Target="System.Windows.Forms.ComponentModel.Com2Interop.ComNativeDescriptor.CheckClear(System.Object):System.Void", MessageId="System.Collections.IEnumerator.get_Current")] +[module: SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatRequireUnboxing", Scope = "member", Target = "System.Windows.Forms.ComponentModel.Com2Interop.ComNativeDescriptor.OnPropsInfoDisposed(System.Object,System.EventArgs):System.Void", MessageId = "System.Collections.IEnumerator.get_Current")] +[module: SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatRequireUnboxing", Scope = "member", Target = "System.Windows.Forms.ComponentModel.Com2Interop.ComNativeDescriptor.CheckClear(System.Object):System.Void", MessageId = "System.Collections.IEnumerator.get_Current")] //End SafeHandle Suppressions. // InProc SxS Supperssions: Methods wich consume but not expose resources @@ -1321,5 +1321,6 @@ [module: SuppressMessage("Microsoft.SideBySide", "CA710:ExposedResourcesMustBeConsumed", Scope = "member", Target = "System.Windows.Forms.Internal.DeviceContext.#SelectObject(System.IntPtr,System.Windows.Forms.Internal.GdiObjectType)")] [module: SuppressMessage("Microsoft.SideBySide", "CA710:ExposedResourcesMustBeConsumed", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsPen.#get_HPen()")] -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/GDI/TextFormatFlags.cs b/src/System.Windows.Forms/src/System/Windows/Forms/GDI/TextFormatFlags.cs index ec4fbdd8f18..c821e6e0205 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/GDI/TextFormatFlags.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/GDI/TextFormatFlags.cs @@ -19,37 +19,37 @@ namespace System.Windows.Forms [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "Maps to native enum.")] public enum TextFormatFlags { - Bottom = IntTextFormatFlags.Bottom, + Bottom = IntTextFormatFlags.Bottom, // NOTE: This flag is used for measuring text and TextRenderer has methods for doing that // so we don't expose it to avoid confusion. // CalculateRectangle = IntTextFormatFlags.CalculateRectangle, - EndEllipsis = IntTextFormatFlags.EndEllipsis, - ExpandTabs = IntTextFormatFlags.ExpandTabs, - ExternalLeading = IntTextFormatFlags.ExternalLeading, - Default = IntTextFormatFlags.Default, - HidePrefix = IntTextFormatFlags.HidePrefix, - HorizontalCenter = IntTextFormatFlags.HorizontalCenter, - Internal = IntTextFormatFlags.Internal, - Left = IntTextFormatFlags.Left, // default - ModifyString = IntTextFormatFlags.ModifyString, - NoClipping = IntTextFormatFlags.NoClipping, - NoPrefix = IntTextFormatFlags.NoPrefix, - NoFullWidthCharacterBreak = IntTextFormatFlags.NoFullWidthCharacterBreak, - PathEllipsis = IntTextFormatFlags.PathEllipsis, - PrefixOnly = IntTextFormatFlags.PrefixOnly, - Right = IntTextFormatFlags.Right, - RightToLeft = IntTextFormatFlags.RightToLeft, - SingleLine = IntTextFormatFlags.SingleLine, + EndEllipsis = IntTextFormatFlags.EndEllipsis, + ExpandTabs = IntTextFormatFlags.ExpandTabs, + ExternalLeading = IntTextFormatFlags.ExternalLeading, + Default = IntTextFormatFlags.Default, + HidePrefix = IntTextFormatFlags.HidePrefix, + HorizontalCenter = IntTextFormatFlags.HorizontalCenter, + Internal = IntTextFormatFlags.Internal, + Left = IntTextFormatFlags.Left, // default + ModifyString = IntTextFormatFlags.ModifyString, + NoClipping = IntTextFormatFlags.NoClipping, + NoPrefix = IntTextFormatFlags.NoPrefix, + NoFullWidthCharacterBreak = IntTextFormatFlags.NoFullWidthCharacterBreak, + PathEllipsis = IntTextFormatFlags.PathEllipsis, + PrefixOnly = IntTextFormatFlags.PrefixOnly, + Right = IntTextFormatFlags.Right, + RightToLeft = IntTextFormatFlags.RightToLeft, + SingleLine = IntTextFormatFlags.SingleLine, // NOTE: TextRenderer does not expose a way to set the tab stops. Observe that ExapandTabs is available. // TabStop = IntTextFormatFlags.TabStop, - TextBoxControl = IntTextFormatFlags.TextBoxControl, - Top = IntTextFormatFlags.Top, // default - VerticalCenter = IntTextFormatFlags.VerticalCenter, + TextBoxControl = IntTextFormatFlags.TextBoxControl, + Top = IntTextFormatFlags.Top, // default + VerticalCenter = IntTextFormatFlags.VerticalCenter, [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Not a compound word")] - WordBreak = IntTextFormatFlags.WordBreak, - WordEllipsis = IntTextFormatFlags.WordEllipsis, + WordBreak = IntTextFormatFlags.WordBreak, + WordEllipsis = IntTextFormatFlags.WordEllipsis, /// /// The following flags are exclusive of TextRenderer (no Windows native flags) @@ -57,7 +57,7 @@ public enum TextFormatFlags /// specify whether to reapply clipping and coordintate transformations to the hdc /// obtained from the Graphics object, which returns a clean hdc. /// - PreserveGraphicsClipping = 0x01000000, + PreserveGraphicsClipping = 0x01000000, PreserveGraphicsTranslateTransform = 0x02000000, /// @@ -65,7 +65,7 @@ public enum TextFormatFlags /// Match the System.Internal.GDI.TextPaddingOptions. /// GlyphOverhangPadding = 0x00000000, // default. - NoPadding = 0x10000000, - LeftAndRightPadding = 0x20000000 + NoPadding = 0x10000000, + LeftAndRightPadding = 0x20000000 } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/GDI/TextRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/GDI/TextRenderer.cs index dfc70684431..a38f8bca7ec 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/GDI/TextRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/GDI/TextRenderer.cs @@ -9,7 +9,7 @@ namespace System.Windows.Forms using System.Windows.Forms.Internal; using System.Diagnostics; - + /// /// /// This class provides API for drawing GDI text. @@ -35,9 +35,10 @@ public static void DrawText(IDeviceContext dc, string text, Font font, Point pt, try { - using( WindowsGraphics wg = WindowsGraphics.FromHdc( hdc )) + using (WindowsGraphics wg = WindowsGraphics.FromHdc(hdc)) { - using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) { + using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) + { wg.DrawText(text, wf, pt, foreColor); } } @@ -61,9 +62,10 @@ public static void DrawText(IDeviceContext dc, string text, Font font, Point pt, try { - using( WindowsGraphics wg = WindowsGraphics.FromHdc( hdc )) + using (WindowsGraphics wg = WindowsGraphics.FromHdc(hdc)) { - using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) { + using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) + { wg.DrawText(text, wf, pt, foreColor, backColor); } } @@ -83,9 +85,10 @@ public static void DrawText(IDeviceContext dc, string text, Font font, Point pt, WindowsFontQuality fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics); - using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, flags )) + using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, flags)) { - using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) { + using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) + { wgr.WindowsGraphics.DrawText(text, wf, pt, foreColor, GetIntTextFormatFlags(flags)); } } @@ -100,9 +103,10 @@ public static void DrawText(IDeviceContext dc, string text, Font font, Point pt, WindowsFontQuality fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics); - using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, flags )) + using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, flags)) { - using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) { + using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) + { wgr.WindowsGraphics.DrawText(text, wf, pt, foreColor, backColor, GetIntTextFormatFlags(flags)); } } @@ -121,9 +125,10 @@ public static void DrawText(IDeviceContext dc, string text, Font font, Rectangle try { - using( WindowsGraphics wg = WindowsGraphics.FromHdc( hdc )) + using (WindowsGraphics wg = WindowsGraphics.FromHdc(hdc)) { - using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) { + using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) + { wg.DrawText(text, wf, bounds, foreColor); } } @@ -147,9 +152,10 @@ public static void DrawText(IDeviceContext dc, string text, Font font, Rectangle try { - using( WindowsGraphics wg = WindowsGraphics.FromHdc( hdc )) + using (WindowsGraphics wg = WindowsGraphics.FromHdc(hdc)) { - using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) { + using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) + { wg.DrawText(text, wf, bounds, foreColor, backColor); } } @@ -169,10 +175,11 @@ public static void DrawText(IDeviceContext dc, string text, Font font, Rectangle WindowsFontQuality fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics); - using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, flags )) + using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, flags)) { - using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont( font, fontQuality )) { - wgr.WindowsGraphics.DrawText( text, wf, bounds, foreColor, GetIntTextFormatFlags( flags ) ); + using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) + { + wgr.WindowsGraphics.DrawText(text, wf, bounds, foreColor, GetIntTextFormatFlags(flags)); } } } @@ -186,9 +193,10 @@ public static void DrawText(IDeviceContext dc, string text, Font font, Rectangle WindowsFontQuality fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics); - using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, flags )) + using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, flags)) { - using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont( font, fontQuality )) { + using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) + { wgr.WindowsGraphics.DrawText(text, wf, bounds, foreColor, backColor, GetIntTextFormatFlags(flags)); } } @@ -196,50 +204,53 @@ public static void DrawText(IDeviceContext dc, string text, Font font, Rectangle private static IntTextFormatFlags GetIntTextFormatFlags(TextFormatFlags flags) { - if( ((uint)flags & WindowsGraphics.GdiUnsupportedFlagMask) == 0 ) + if (((uint)flags & WindowsGraphics.GdiUnsupportedFlagMask) == 0) { - return (IntTextFormatFlags) flags; + return (IntTextFormatFlags)flags; } // Clear TextRenderer custom flags. - IntTextFormatFlags windowsGraphicsSupportedFlags = (IntTextFormatFlags) ( ((uint)flags) & ~WindowsGraphics.GdiUnsupportedFlagMask ); + IntTextFormatFlags windowsGraphicsSupportedFlags = (IntTextFormatFlags)(((uint)flags) & ~WindowsGraphics.GdiUnsupportedFlagMask); return windowsGraphicsSupportedFlags; } /// MeasureText wrappers. - - public static Size MeasureText(string text, Font font ) + + public static Size MeasureText(string text, Font font) { - if (string.IsNullOrEmpty(text)) + if (string.IsNullOrEmpty(text)) { return Size.Empty; } - - using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font)) { + + using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font)) + { return WindowsGraphicsCacheManager.MeasurementGraphics.MeasureText(text, wf); - } + } } - public static Size MeasureText(string text, Font font, Size proposedSize ) + public static Size MeasureText(string text, Font font, Size proposedSize) { - if (string.IsNullOrEmpty(text)) + if (string.IsNullOrEmpty(text)) { return Size.Empty; } - - using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font)) { + + using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font)) + { return WindowsGraphicsCacheManager.MeasurementGraphics.MeasureText(text, WindowsGraphicsCacheManager.GetWindowsFont(font), proposedSize); } } - public static Size MeasureText(string text, Font font, Size proposedSize, TextFormatFlags flags ) + public static Size MeasureText(string text, Font font, Size proposedSize, TextFormatFlags flags) { - if (string.IsNullOrEmpty(text)) + if (string.IsNullOrEmpty(text)) { return Size.Empty; } - using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font)) { + using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font)) + { return WindowsGraphicsCacheManager.MeasurementGraphics.MeasureText(text, wf, proposedSize, GetIntTextFormatFlags(flags)); } } @@ -250,7 +261,7 @@ public static Size MeasureText(IDeviceContext dc, string text, Font font) { throw new ArgumentNullException(nameof(dc)); } - if (string.IsNullOrEmpty(text)) + if (string.IsNullOrEmpty(text)) { return Size.Empty; } @@ -260,9 +271,10 @@ public static Size MeasureText(IDeviceContext dc, string text, Font font) try { - using( WindowsGraphics wg = WindowsGraphics.FromHdc( hdc )) + using (WindowsGraphics wg = WindowsGraphics.FromHdc(hdc)) { - using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) { + using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) + { return wg.MeasureText(text, wf); } } @@ -273,13 +285,13 @@ public static Size MeasureText(IDeviceContext dc, string text, Font font) } } - public static Size MeasureText(IDeviceContext dc, string text, Font font, Size proposedSize ) + public static Size MeasureText(IDeviceContext dc, string text, Font font, Size proposedSize) { if (dc == null) { throw new ArgumentNullException(nameof(dc)); } - if (string.IsNullOrEmpty(text)) + if (string.IsNullOrEmpty(text)) { return Size.Empty; } @@ -290,9 +302,10 @@ public static Size MeasureText(IDeviceContext dc, string text, Font font, Size p try { - using( WindowsGraphics wg = WindowsGraphics.FromHdc( hdc )) + using (WindowsGraphics wg = WindowsGraphics.FromHdc(hdc)) { - using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) { + using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) + { return wg.MeasureText(text, wf, proposedSize); } } @@ -303,13 +316,13 @@ public static Size MeasureText(IDeviceContext dc, string text, Font font, Size p } } - public static Size MeasureText(IDeviceContext dc, string text, Font font, Size proposedSize, TextFormatFlags flags ) - { + public static Size MeasureText(IDeviceContext dc, string text, Font font, Size proposedSize, TextFormatFlags flags) + { if (dc == null) { throw new ArgumentNullException(nameof(dc)); } - if (string.IsNullOrEmpty(text)) + if (string.IsNullOrEmpty(text)) { return Size.Empty; } @@ -317,22 +330,26 @@ public static Size MeasureText(IDeviceContext dc, string text, Font font, Size p using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, flags)) { - using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) { + using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) + { return wgr.WindowsGraphics.MeasureText(text, wf, proposedSize, GetIntTextFormatFlags(flags)); } } } - internal static Color DisabledTextColor(Color backColor) { - if (SystemInformation.HighContrast) { + internal static Color DisabledTextColor(Color backColor) + { + if (SystemInformation.HighContrast) + { return SystemColors.GrayText; } //Theme specs -- if the backcolor is darker than Control, we use // ControlPaint.Dark(backcolor). Otherwise we use ControlDark. Color disabledTextForeColor = SystemColors.ControlDark; - if (ControlPaint.IsDarker(backColor, SystemColors.Control)) { + if (ControlPaint.IsDarker(backColor, SystemColors.Control)) + { disabledTextForeColor = ControlPaint.Dark(backColor); } return disabledTextForeColor; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/GDI/WindowsGraphicsWrapper.cs b/src/System.Windows.Forms/src/System/Windows/Forms/GDI/WindowsGraphicsWrapper.cs index 38266d072c6..b86b3559251 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/GDI/WindowsGraphicsWrapper.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/GDI/WindowsGraphicsWrapper.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms +namespace System.Windows.Forms { using System; using System.Drawing; @@ -35,29 +35,29 @@ internal sealed class WindowsGraphicsWrapper : IDisposable /// In this case we create the WindowsGraphics from the native DC by calling IDeviceContext.GetHdc, /// on dispose we need to call IDeviceContext.ReleaseHdc. /// - - - public WindowsGraphicsWrapper( IDeviceContext idc, TextFormatFlags flags) + + + public WindowsGraphicsWrapper(IDeviceContext idc, TextFormatFlags flags) { - if( idc is Graphics ) + if (idc is Graphics) { ApplyGraphicsProperties properties = ApplyGraphicsProperties.None; - if( (flags & TextFormatFlags.PreserveGraphicsClipping) != 0) + if ((flags & TextFormatFlags.PreserveGraphicsClipping) != 0) { properties |= ApplyGraphicsProperties.Clipping; } - if( (flags & TextFormatFlags.PreserveGraphicsTranslateTransform) != 0) + if ((flags & TextFormatFlags.PreserveGraphicsTranslateTransform) != 0) { properties |= ApplyGraphicsProperties.TranslateTransform; } // Create the WindowsGraphics from the Grahpics object only if Graphics properties need // to be reapplied to the DC wrapped by the WindowsGraphics. - if( properties != ApplyGraphicsProperties.None ) + if (properties != ApplyGraphicsProperties.None) { - this.wg = WindowsGraphics.FromGraphics( idc as Graphics, properties); + this.wg = WindowsGraphics.FromGraphics(idc as Graphics, properties); } } else @@ -65,7 +65,7 @@ public WindowsGraphicsWrapper( IDeviceContext idc, TextFormatFlags flags) // If passed-in IDeviceContext object is a WindowsGraphics we can use it directly. this.wg = idc as WindowsGraphics; - if( this.wg != null ) + if (this.wg != null) { // In this case we cache the idc to compare it against the wg in the Dispose method to avoid // disposing of the wg. @@ -73,22 +73,22 @@ public WindowsGraphicsWrapper( IDeviceContext idc, TextFormatFlags flags) } } - if( this.wg == null ) + if (this.wg == null) { // The IDeviceContext object is not a WindowsGraphics, or it is a custom IDeviceContext, or // it is a Graphics object but we did not need to re-apply Graphics propertiesto the hdc. // So create the WindowsGraphics from the hdc directly. // Cache the IDC so the hdc can be released on dispose. this.idc = idc; - this.wg = WindowsGraphics.FromHdc( idc.GetHdc() ); + this.wg = WindowsGraphics.FromHdc(idc.GetHdc()); } // Set text padding on the WindowsGraphics (if any). - if( (flags & TextFormatFlags.LeftAndRightPadding) != 0 ) + if ((flags & TextFormatFlags.LeftAndRightPadding) != 0) { wg.TextPadding = TextPaddingOptions.LeftAndRightPadding; } - else if ((flags & TextFormatFlags.NoPadding) != 0 ) + else if ((flags & TextFormatFlags.NoPadding) != 0) { wg.TextPadding = TextPaddingOptions.NoPadding; } @@ -99,7 +99,7 @@ public WindowsGraphics WindowsGraphics { get { - Debug.Assert( this.wg != null, "WindowsGraphics is null." ); + Debug.Assert(this.wg != null, "WindowsGraphics is null."); return this.wg; } } @@ -115,20 +115,20 @@ public void Dispose() GC.SuppressFinalize(this); } - public void Dispose( bool disposing ) + public void Dispose(bool disposing) { - Debug.Assert( disposing, "We should always dispose of this guy and not let GC do it for us!" ); - - if( this.wg != null ) + Debug.Assert(disposing, "We should always dispose of this guy and not let GC do it for us!"); + + if (this.wg != null) { // We need to dispose of the WindowsGraphics if it is created by this class only, if the IDeviceContext is // a WindowsGraphics object we must not dispose of it since it is owned by the caller. - if( this.wg != this.idc ) + if (this.wg != this.idc) { // resets the hdc and disposes of the internal Graphics (if inititialized from one) which releases the hdc. this.wg.Dispose(); - if( this.idc != null ) // not initialized from a Graphics idc. + if (this.idc != null) // not initialized from a Graphics idc. { this.idc.ReleaseHdc(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/GetChildAtPointSkip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/GetChildAtPointSkip.cs index 53cd31ba8d6..46c0070a9cc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/GetChildAtPointSkip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/GetChildAtPointSkip.cs @@ -11,8 +11,8 @@ namespace System.Windows.Forms public enum GetChildAtPointSkip { None = 0x0000, - Invisible = 0x0001, - Disabled = 0x0002, + Invisible = 0x0001, + Disabled = 0x0002, Transparent = 0x0004 } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/GridItemType.cs b/src/System.Windows.Forms/src/System/Windows/Forms/GridItemType.cs index fa13e2e4109..621cd9b38f7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/GridItemType.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/GridItemType.cs @@ -8,7 +8,7 @@ public enum GridItemType { Property, Category, - ArrayValue, + ArrayValue, Root } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/GroupBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/GroupBox.cs index ba161002b1b..d5ce96eb607 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/GroupBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/GroupBox.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System; @@ -32,7 +33,8 @@ namespace System.Windows.Forms { Designer("System.Windows.Forms.Design.GroupBoxDesigner, " + AssemblyRef.SystemDesign), SRDescription(nameof(SR.DescriptionGroupBox)) ] - public class GroupBox : Control { + public class GroupBox : Control + { int fontHeight = -1; Font cachedFont; FlatStyle flatStyle = FlatStyle.Standard; @@ -42,9 +44,10 @@ public class GroupBox : Control { /// Initializes a new instance of the class. /// /// - public GroupBox() : base() { + public GroupBox() : base() + { // this class overrides GetPreferredSizeCore, let Control automatically cache the result - SetState2(STATE2_USEPREFERREDSIZECACHE, true); + SetState2(STATE2_USEPREFERREDSIZECACHE, true); SetStyle(ControlStyles.ContainerControl, true); SetStyle(ControlStyles.SupportsTransparentBackColor | @@ -62,11 +65,14 @@ public GroupBox() : base() { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public override bool AllowDrop { - get { + public override bool AllowDrop + { + get + { return base.AllowDrop; } - set { + set + { base.AllowDrop = value; } } @@ -101,27 +107,34 @@ public override bool AutoSize /// [ SRDescription(nameof(SR.ControlAutoSizeModeDescr)), - SRCategory(nameof(SR.CatLayout)), + SRCategory(nameof(SR.CatLayout)), Browsable(true), DefaultValue(AutoSizeMode.GrowOnly), Localizable(true) ] - public AutoSizeMode AutoSizeMode { - get { + public AutoSizeMode AutoSizeMode + { + get + { return GetAutoSizeMode(); } - set { - if (!ClientUtils.IsEnumValid(value, (int)value, (int)AutoSizeMode.GrowAndShrink, (int)AutoSizeMode.GrowOnly)){ + set + { + if (!ClientUtils.IsEnumValid(value, (int)value, (int)AutoSizeMode.GrowAndShrink, (int)AutoSizeMode.GrowOnly)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AutoSizeMode)); } - - if (GetAutoSizeMode() != value) { + + if (GetAutoSizeMode() != value) + { SetAutoSizeMode(value); - if(ParentInternal != null) { + 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(ParentInternal.LayoutEngine == DefaultLayout.Instance) { + if (ParentInternal.LayoutEngine == DefaultLayout.Instance) + { ParentInternal.LayoutEngine.InitLayout(this, BoundsSpecified.Size); } LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.AutoSize); @@ -130,14 +143,18 @@ public AutoSizeMode AutoSizeMode { } } - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; - if (!OwnerDraw) { + if (!OwnerDraw) + { cp.ClassName = "BUTTON"; cp.Style |= NativeMethods.BS_GROUPBOX; } - else { + else + { // if we swap back to a different flat style // we need to reset these guys. cp.ClassName = null; @@ -152,8 +169,10 @@ protected override CreateParams CreateParams { /// /// Set the default Padding to 3 so that it is consistent with Everett /// - protected override Padding DefaultPadding { - get { + protected override Padding DefaultPadding + { + get + { return new Padding(3); } } @@ -162,8 +181,10 @@ protected override Padding DefaultPadding { /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(200, 100); } } @@ -175,15 +196,19 @@ protected override Size DefaultSize { /// . /// /// - public override Rectangle DisplayRectangle { - get { + public override Rectangle DisplayRectangle + { + get + { Size size = ClientSize; - if (fontHeight == -1) { + if (fontHeight == -1) + { fontHeight = (int)Font.Height; - cachedFont = Font; + cachedFont = Font; } - else if (!object.ReferenceEquals(cachedFont, Font)) { + else if (!object.ReferenceEquals(cachedFont, Font)) + { // Must also cache font identity here because // we need to provide an accurate DisplayRectangle // picture even before the OnFontChanged event bubbles @@ -192,7 +217,7 @@ public override Rectangle DisplayRectangle { cachedFont = Font; } - + //for efficiency, so that we don't need to read property store four times Padding padding = Padding; return new Rectangle(padding.Left, fontHeight + padding.Top, Math.Max(size.Width - padding.Horizontal, 0), Math.Max(size.Height - fontHeight - padding.Vertical, 0)); @@ -204,18 +229,22 @@ public override Rectangle DisplayRectangle { DefaultValue(FlatStyle.Standard), SRDescription(nameof(SR.ButtonFlatStyleDescr)) ] - public FlatStyle FlatStyle { - get { + public FlatStyle FlatStyle + { + get + { return flatStyle; } - set { + set + { //valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(value, (int)value, (int)FlatStyle.Flat, (int)FlatStyle.System)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(FlatStyle)); } - if (flatStyle != value) { + if (flatStyle != value) + { bool originalOwnerDraw = OwnerDraw; flatStyle = value; @@ -231,10 +260,12 @@ public FlatStyle FlatStyle { ControlStyles.ResizeRedraw | ControlStyles.UserMouse, OwnerDraw); - if (needRecreate) { + if (needRecreate) + { RecreateHandle(); } - else { + else + { Refresh(); } @@ -243,8 +274,10 @@ public FlatStyle FlatStyle { } } - private bool OwnerDraw { - get { + private bool OwnerDraw + { + get + { return FlatStyle != FlatStyle.System; } } @@ -258,17 +291,21 @@ private bool OwnerDraw { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - new public bool TabStop { - get { + new public bool TabStop + { + get + { return base.TabStop; } - set { + set + { base.TabStop = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - new public event EventHandler TabStopChanged { + new public event EventHandler TabStopChanged + { add => base.TabStopChanged += value; remove => base.TabStopChanged -= value; } @@ -276,27 +313,34 @@ private bool OwnerDraw { [ Localizable(true) ] - public override string Text { - get{ + public override string Text + { + get + { return base.Text; } - set { - // the GroupBox controls immediately draws when teh WM_SETTEXT comes through, but - // does so in the wrong font, so we suspend that behavior, and then - // invalidate. - bool suspendRedraw = this.Visible; - try { - if (suspendRedraw && IsHandleCreated) { + set + { + // the GroupBox controls immediately draws when teh WM_SETTEXT comes through, but + // does so in the wrong font, so we suspend that behavior, and then + // invalidate. + bool suspendRedraw = this.Visible; + try + { + if (suspendRedraw && IsHandleCreated) + { SendMessage(Interop.WindowMessages.WM_SETREDRAW, 0, 0); } base.Text = value; - } - finally { - if (suspendRedraw && IsHandleCreated) { + } + finally + { + if (suspendRedraw && IsHandleCreated) + { SendMessage(Interop.WindowMessages.WM_SETREDRAW, 1, 0); } - } - Invalidate(true); + } + Invalidate(true); } } @@ -308,11 +352,14 @@ public override string Text { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.UseCompatibleTextRenderingDescr)) ] - public bool UseCompatibleTextRendering { - get{ + public bool UseCompatibleTextRendering + { + get + { return base.UseCompatibleTextRenderingInt; } - set{ + set + { base.UseCompatibleTextRenderingInt = value; } } @@ -322,29 +369,34 @@ public bool UseCompatibleTextRendering { /// This is provided for container controls to iterate through its children to set UseCompatibleTextRendering to the same /// value if the child control supports it. /// - internal override bool SupportsUseCompatibleTextRendering { - get { + internal override bool SupportsUseCompatibleTextRendering + { + get + { return true; } } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event EventHandler Click { + public new event EventHandler Click + { add => base.Click += value; remove => base.Click -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event MouseEventHandler MouseClick { + public new event MouseEventHandler MouseClick + { add => base.MouseClick += value; remove => base.MouseClick -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event EventHandler DoubleClick { + public new event EventHandler DoubleClick + { add => base.DoubleClick += value; remove => base.DoubleClick -= value; } @@ -352,105 +404,122 @@ internal override bool SupportsUseCompatibleTextRendering { /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event MouseEventHandler MouseDoubleClick { + public new event MouseEventHandler MouseDoubleClick + { add => base.MouseDoubleClick += value; remove => base.MouseDoubleClick -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event KeyEventHandler KeyUp { + public new event KeyEventHandler KeyUp + { add => base.KeyUp += value; remove => base.KeyUp -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event KeyEventHandler KeyDown { + public new event KeyEventHandler KeyDown + { add => base.KeyDown += value; remove => base.KeyDown -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event KeyPressEventHandler KeyPress { + public new event KeyPressEventHandler KeyPress + { add => base.KeyPress += value; remove => base.KeyPress -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event MouseEventHandler MouseDown { + public new event MouseEventHandler MouseDown + { add => base.MouseDown += value; remove => base.MouseDown -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event MouseEventHandler MouseUp { + public new event MouseEventHandler MouseUp + { add => base.MouseUp += value; remove => base.MouseUp -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event MouseEventHandler MouseMove { + public new event MouseEventHandler MouseMove + { add => base.MouseMove += value; remove => base.MouseMove -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event EventHandler MouseEnter { + public new event EventHandler MouseEnter + { add => base.MouseEnter += value; remove => base.MouseEnter -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event EventHandler MouseLeave { + public new event EventHandler MouseLeave + { add => base.MouseLeave += value; remove => base.MouseLeave -= value; } - protected override void OnPaint(PaintEventArgs e) { - - + protected override void OnPaint(PaintEventArgs e) + { + + // BACKCOMPAT requirement: // Why the Height/Width >= 10 check? This is because uxtheme doesn't seem to handle those cases // similar to what we do for the non-themed case, so if someone is using the groupbox as a // separator, their app will look weird in Whidbey. We render the old way in these cases. - - if (Application.RenderWithVisualStyles && Width >= 10 && Height >= 10) { + + if (Application.RenderWithVisualStyles && Width >= 10 && Height >= 10) + { GroupBoxState gbState = Enabled ? GroupBoxState.Normal : GroupBoxState.Disabled; TextFormatFlags textFlags = TextFormatFlags.Default | TextFormatFlags.TextBoxControl | TextFormatFlags.WordBreak | TextFormatFlags.PreserveGraphicsTranslateTransform | TextFormatFlags.PreserveGraphicsClipping; - if (!ShowKeyboardCues) { + if (!ShowKeyboardCues) + { textFlags |= TextFormatFlags.HidePrefix; } - if (RightToLeft == RightToLeft.Yes) { + if (RightToLeft == RightToLeft.Yes) + { textFlags |= (TextFormatFlags.Right | TextFormatFlags.RightToLeft); } // We only pass in the text color if it is explicitly set, else we let the renderer use the // color specified by the theme. This is a temporary workaround till we find a good // solution for the "default theme color" issue. - if (ShouldSerializeForeColor() || this.Enabled == false) { + if (ShouldSerializeForeColor() || this.Enabled == false) + { Color textcolor = this.Enabled ? ForeColor : TextRenderer.DisabledTextColor(this.BackColor); GroupBoxRenderer.DrawGroupBox(e.Graphics, new Rectangle(0, 0, Width, Height), Text, Font, textcolor, textFlags, gbState); } - else { + else + { GroupBoxRenderer.DrawGroupBox(e.Graphics, new Rectangle(0, 0, Width, Height), Text, Font, textFlags, gbState); } } - else { + else + { DrawGroupBox(e); } base.OnPaint(e); // raise paint event } - private void DrawGroupBox(PaintEventArgs e) { + private void DrawGroupBox(PaintEventArgs e) + { Graphics graphics = e.Graphics; Rectangle textRectangle = ClientRectangle; // Max text bounding box passed to drawing methods to support RTL. @@ -465,51 +534,65 @@ private void DrawGroupBox(PaintEventArgs e) { textRectangle.X += textOffset; textRectangle.Width -= 2 * textOffset; - try { - if( UseCompatibleTextRendering ){ - using( Brush textBrush = new SolidBrush(ForeColor)){ - using( StringFormat format = new StringFormat() ){ + try + { + if (UseCompatibleTextRendering) + { + using (Brush textBrush = new SolidBrush(ForeColor)) + { + using (StringFormat format = new StringFormat()) + { format.HotkeyPrefix = ShowKeyboardCues ? System.Drawing.Text.HotkeyPrefix.Show : System.Drawing.Text.HotkeyPrefix.Hide; // Adjust string format for Rtl controls - if (RightToLeft == RightToLeft.Yes) { + if (RightToLeft == RightToLeft.Yes) + { format.FormatFlags |= StringFormatFlags.DirectionRightToLeft; } textSize = Size.Ceiling(graphics.MeasureString(Text, Font, textRectangle.Width, format)); - if (Enabled) { + if (Enabled) + { graphics.DrawString(Text, Font, textBrush, textRectangle, format); } - else { + else + { ControlPaint.DrawStringDisabled(graphics, Text, Font, backColor, textRectangle, format); } } } } - else { - using( WindowsGraphics wg = WindowsGraphics.FromGraphics(graphics) ){ + else + { + using (WindowsGraphics wg = WindowsGraphics.FromGraphics(graphics)) + { IntTextFormatFlags flags = IntTextFormatFlags.WordBreak | IntTextFormatFlags.TextBoxControl; - if(!ShowKeyboardCues){ + if (!ShowKeyboardCues) + { flags |= IntTextFormatFlags.HidePrefix; } - if( RightToLeft == RightToLeft.Yes ){ + if (RightToLeft == RightToLeft.Yes) + { flags |= IntTextFormatFlags.RightToLeft; flags |= IntTextFormatFlags.Right; } - - using (WindowsFont wfont = WindowsGraphicsCacheManager.GetWindowsFont(this.Font)) { - textSize = wg.MeasureText(Text, wfont, new Size(textRectangle.Width , int.MaxValue), flags ); - - if( Enabled ) { + + using (WindowsFont wfont = WindowsGraphicsCacheManager.GetWindowsFont(this.Font)) + { + textSize = wg.MeasureText(Text, wfont, new Size(textRectangle.Width, int.MaxValue), flags); + + if (Enabled) + { wg.DrawText(Text, wfont, textRectangle, ForeColor, flags); } - else{ - ControlPaint.DrawStringDisabled(wg, Text, Font, backColor, textRectangle, ((TextFormatFlags) flags)); + else + { + ControlPaint.DrawStringDisabled(wg, Text, Font, backColor, textRectangle, ((TextFormatFlags)flags)); } } } @@ -523,46 +606,55 @@ private void DrawGroupBox(PaintEventArgs e) { } // Math.Min to assure we paint at least a small line. - int textRight = Math.Min( textLeft + textSize.Width, Width - 6); + int textRight = Math.Min(textLeft + textSize.Width, Width - 6); int boxTop = FontHeight / 2; - if (SystemInformation.HighContrast) { + if (SystemInformation.HighContrast) + { Color boxColor; - if (Enabled) { + if (Enabled) + { boxColor = ForeColor; } - else { + else + { boxColor = SystemColors.GrayText; } bool needToDispose = !boxColor.IsSystemColor; Pen boxPen = null; - try { - if (needToDispose) { + try + { + if (needToDispose) + { boxPen = new Pen(boxColor); } - else { + else + { boxPen = SystemPens.FromSystemColor(boxColor); } // left graphics.DrawLine(boxPen, 0, boxTop, 0, Height); //bottom - graphics.DrawLine(boxPen, 0, Height-1, Width, Height-1); + graphics.DrawLine(boxPen, 0, Height - 1, Width, Height - 1); //top-left graphics.DrawLine(boxPen, 0, boxTop, textLeft, boxTop); //top-right - graphics.DrawLine(boxPen, textRight, boxTop, Width-1, boxTop); + graphics.DrawLine(boxPen, textRight, boxTop, Width - 1, boxTop); //right - graphics.DrawLine(boxPen, Width-1, boxTop, Width-1, Height-1); + graphics.DrawLine(boxPen, Width - 1, boxTop, Width - 1, Height - 1); } - finally { - if (needToDispose && boxPen != null) { + finally + { + if (needToDispose && boxPen != null) + { boxPen.Dispose(); } } } - else { + else + { // left graphics.DrawLine(light, 1, boxTop, 1, Height - 1); graphics.DrawLine(dark, 0, boxTop, 0, Height - 2); @@ -585,17 +677,19 @@ private void DrawGroupBox(PaintEventArgs e) { graphics.DrawLine(dark, Width - 2, boxTop, Width - 2, Height - 2); } } - finally { + finally + { light.Dispose(); dark.Dispose(); } } - internal override Size GetPreferredSizeCore(Size proposedSize) { + internal override Size GetPreferredSizeCore(Size proposedSize) + { // Translating 0,0 from ClientSize to actual Size tells us how much space // is required for the borders. Size borderSize = SizeFromClientSize(Size.Empty); - Size totalPadding = borderSize + new Size(0,fontHeight) + Padding.Size; + Size totalPadding = borderSize + new Size(0, fontHeight) + Padding.Size; Size prefSize = LayoutEngine.GetPreferredSize(this, proposedSize - totalPadding); return prefSize + totalPadding; @@ -603,7 +697,8 @@ internal override Size GetPreferredSizeCore(Size proposedSize) { /// /// - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { fontHeight = -1; cachedFont = null; Invalidate(); @@ -614,17 +709,21 @@ protected override void OnFontChanged(EventArgs e) { /// We use this to process mnemonics and send them on to the first child /// control. /// - protected internal override bool ProcessMnemonic(char charCode) { - if (IsMnemonic(charCode, Text) && CanProcessMnemonic()) { + protected internal override bool ProcessMnemonic(char charCode) + { + if (IsMnemonic(charCode, Text) && CanProcessMnemonic()) + { SelectNextControl(null, true, true, true, false); return true; } return false; } [SuppressMessage("Microsoft.Portability", "CA1902:AvoidTestingForFloatingPointEquality")] - protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { - - if (factor.Width != 1F && factor.Height != 1F) { + protected override void ScaleControl(SizeF factor, BoundsSpecified specified) + { + + if (factor.Width != 1F && factor.Height != 1F) + { // Make sure when we're scaling by non-unity to clear the font cache // as the font has likely changed, but we dont know it yet as OnFontChanged has yet to // be called on us by our parent. @@ -639,7 +738,8 @@ protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { /// /// Returns a string representation for this control. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); return s + ", Text: " + Text; @@ -649,11 +749,14 @@ public override string ToString() { /// The Windows group box doesn't erase the background so we do it /// ourselves here. /// - private void WmEraseBkgnd(ref Message m) { + private void WmEraseBkgnd(ref Message m) + { NativeMethods.RECT rect = new NativeMethods.RECT(); SafeNativeMethods.GetClientRect(new HandleRef(this, Handle), ref rect); - using (Graphics graphics = Graphics.FromHdcInternal(m.WParam)) { - using (Brush b = new SolidBrush(BackColor)) { + using (Graphics graphics = Graphics.FromHdcInternal(m.WParam)) + { + using (Brush b = new SolidBrush(BackColor)) + { graphics.FillRectangle(b, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top); } @@ -661,14 +764,17 @@ private void WmEraseBkgnd(ref Message m) { m.Result = (IntPtr)1; } - protected override void WndProc(ref Message m) { - - if (OwnerDraw) { + protected override void WndProc(ref Message m) + { + + if (OwnerDraw) + { base.WndProc(ref m); return; } - switch (m.Msg) { + switch (m.Msg) + { case Interop.WindowMessages.WM_ERASEBKGND: case Interop.WindowMessages.WM_PRINTCLIENT: WmEraseBkgnd(ref m); @@ -680,7 +786,8 @@ protected override void WndProc(ref Message m) { // will always be exposed through MSAA. Reason: When FlatStyle=System, we map down to the Win32 // "Button" window class to get OS group box rendering; but the OS does not expose the children // of buttons to MSAA (beacuse it assumes buttons won't have children). - if (unchecked((int)(long)m.LParam) == NativeMethods.OBJID_QUERYCLASSNAMEIDX) { + if (unchecked((int)(long)m.LParam) == NativeMethods.OBJID_QUERYCLASSNAMEIDX) + { m.Result = IntPtr.Zero; } break; @@ -690,20 +797,25 @@ protected override void WndProc(ref Message m) { } } - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new GroupBoxAccessibleObject(this); } [System.Runtime.InteropServices.ComVisible(true)] internal class GroupBoxAccessibleObject : ControlAccessibleObject { - internal GroupBoxAccessibleObject(GroupBox owner) : base(owner) { + internal GroupBoxAccessibleObject(GroupBox owner) : base(owner) + { } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { AccessibleRole role = Owner.AccessibleRole; - if (role != AccessibleRole.Default) { + if (role != AccessibleRole.Default) + { return role; } return AccessibleRole.Grouping; @@ -712,8 +824,10 @@ public override AccessibleRole Role { internal override bool IsIAccessibleExSupported() => true; - internal override object GetPropertyValue(int propertyID) { - switch (propertyID) { + internal override object GetPropertyValue(int propertyID) + { + switch (propertyID) + { case NativeMethods.UIA_ControlTypePropertyId: return NativeMethods.UIA_GroupControlTypeId; case NativeMethods.UIA_IsKeyboardFocusablePropertyId: diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/GroupBoxRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/GroupBoxRenderer.cs index 406455dfb0b..f6533aed71c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/GroupBoxRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/GroupBoxRenderer.cs @@ -2,15 +2,16 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ -using System; -using System.Drawing; -using System.Windows.Forms.Internal; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Windows.Forms.VisualStyles; -using Microsoft.Win32; + using System; + using System.Drawing; + using System.Windows.Forms.Internal; + using System.Diagnostics; + using System.Diagnostics.CodeAnalysis; + using System.Windows.Forms.VisualStyles; + using Microsoft.Win32; /// @@ -18,7 +19,8 @@ namespace System.Windows.Forms { /// This is a rendering class for the GroupBox control. /// /// - public sealed class GroupBoxRenderer { + public sealed class GroupBoxRenderer + { //Make this per-thread, so that different threads can safely use these methods. [ThreadStatic] @@ -28,7 +30,8 @@ public sealed class GroupBoxRenderer { private const int boxHeaderWidth = 7; // The groupbox frame shows 7 pixels before the caption. private static bool renderMatchingApplicationState = true; //cannot instantiate - private GroupBoxRenderer() { + private GroupBoxRenderer() + { } /// @@ -38,17 +41,22 @@ private GroupBoxRenderer() { /// If this property is false, the renderer will always render with visualstyles. /// /// - public static bool RenderMatchingApplicationState { - get { + public static bool RenderMatchingApplicationState + { + get + { return renderMatchingApplicationState; } - set { + set + { renderMatchingApplicationState = value; } } - private static bool RenderWithVisualStyles { - get { + private static bool RenderWithVisualStyles + { + get + { return (!renderMatchingApplicationState || Application.RenderWithVisualStyles); } } @@ -58,16 +66,19 @@ private static bool RenderWithVisualStyles { /// Returns true if the background corresponding to the given state is partially transparent, else false. /// /// - public static bool IsBackgroundPartiallyTransparent(GroupBoxState state) { - if (RenderWithVisualStyles) { - InitializeRenderer((int)state); - return visualStyleRenderer.IsBackgroundPartiallyTransparent(); - } - else { - return false; //for downlevel, this is false - } + public static bool IsBackgroundPartiallyTransparent(GroupBoxState state) + { + if (RenderWithVisualStyles) + { + InitializeRenderer((int)state); + return visualStyleRenderer.IsBackgroundPartiallyTransparent(); + } + else + { + return false; //for downlevel, this is false + } } - + /// /// /// This is just a convenience wrapper for VisualStyleRenderer.DrawThemeParentBackground. For downlevel, @@ -77,11 +88,13 @@ public static bool IsBackgroundPartiallyTransparent(GroupBoxState state) { [ SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally ] - public static void DrawParentBackground(Graphics g, Rectangle bounds, Control childControl) { - if (RenderWithVisualStyles) { - InitializeRenderer(0); - visualStyleRenderer.DrawParentBackground(g, bounds, childControl); - } + public static void DrawParentBackground(Graphics g, Rectangle bounds, Control childControl) + { + if (RenderWithVisualStyles) + { + InitializeRenderer(0); + visualStyleRenderer.DrawParentBackground(g, bounds, childControl); + } } /// @@ -89,7 +102,8 @@ public static void DrawParentBackground(Graphics g, Rectangle bounds, Control ch /// Renders a GroupBox control. /// /// - public static void DrawGroupBox(Graphics g, Rectangle bounds, GroupBoxState state) { + public static void DrawGroupBox(Graphics g, Rectangle bounds, GroupBoxState state) + { if (RenderWithVisualStyles) DrawThemedGroupBoxNoText(g, bounds, state); else @@ -101,7 +115,8 @@ public static void DrawGroupBox(Graphics g, Rectangle bounds, GroupBoxState stat /// Renders a GroupBox control. Uses the text color specified by the theme. /// /// - public static void DrawGroupBox(Graphics g, Rectangle bounds, string groupBoxText, Font font, GroupBoxState state) { + public static void DrawGroupBox(Graphics g, Rectangle bounds, string groupBoxText, Font font, GroupBoxState state) + { DrawGroupBox(g, bounds, groupBoxText, font, TextFormatFlags.Top | TextFormatFlags.Left, state); } @@ -110,7 +125,8 @@ public static void DrawGroupBox(Graphics g, Rectangle bounds, string groupBoxTex /// Renders a GroupBox control. /// /// - public static void DrawGroupBox(Graphics g, Rectangle bounds, string groupBoxText, Font font, Color textColor, GroupBoxState state) { + public static void DrawGroupBox(Graphics g, Rectangle bounds, string groupBoxText, Font font, Color textColor, GroupBoxState state) + { DrawGroupBox(g, bounds, groupBoxText, font, textColor, TextFormatFlags.Top | TextFormatFlags.Left, state); } @@ -119,7 +135,8 @@ public static void DrawGroupBox(Graphics g, Rectangle bounds, string groupBoxTex /// Renders a GroupBox control. Uses the text color specified by the theme. /// /// - public static void DrawGroupBox(Graphics g, Rectangle bounds, string groupBoxText, Font font, TextFormatFlags flags, GroupBoxState state) { + public static void DrawGroupBox(Graphics g, Rectangle bounds, string groupBoxText, Font font, TextFormatFlags flags, GroupBoxState state) + { if (RenderWithVisualStyles) DrawThemedGroupBoxWithText(g, bounds, groupBoxText, font, DefaultTextColor(state), flags, state); else @@ -131,7 +148,8 @@ public static void DrawGroupBox(Graphics g, Rectangle bounds, string groupBoxTex /// Renders a GroupBox control. /// /// - public static void DrawGroupBox(Graphics g, Rectangle bounds, string groupBoxText, Font font, Color textColor, TextFormatFlags flags, GroupBoxState state) { + public static void DrawGroupBox(Graphics g, Rectangle bounds, string groupBoxText, Font font, Color textColor, TextFormatFlags flags, GroupBoxState state) + { if (RenderWithVisualStyles) DrawThemedGroupBoxWithText(g, bounds, groupBoxText, font, textColor, flags, state); else @@ -141,7 +159,8 @@ public static void DrawGroupBox(Graphics g, Rectangle bounds, string groupBoxTex /// /// Draws a themed GroupBox with no text label. /// - private static void DrawThemedGroupBoxNoText(Graphics g, Rectangle bounds, GroupBoxState state) { + private static void DrawThemedGroupBoxNoText(Graphics g, Rectangle bounds, GroupBoxState state) + { InitializeRenderer((int)state); visualStyleRenderer.DrawBackground(g, bounds); } @@ -149,7 +168,8 @@ private static void DrawThemedGroupBoxNoText(Graphics g, Rectangle bounds, Group /// /// Draws a themed GroupBox with a text label. /// - private static void DrawThemedGroupBoxWithText(Graphics g, Rectangle bounds, string groupBoxText, Font font, Color textColor, TextFormatFlags flags, GroupBoxState state) { + private static void DrawThemedGroupBoxWithText(Graphics g, Rectangle bounds, string groupBoxText, Font font, Color textColor, TextFormatFlags flags, GroupBoxState state) + { InitializeRenderer((int)state); // Calculate text area, and render text inside it @@ -160,10 +180,12 @@ private static void DrawThemedGroupBoxWithText(Graphics g, Rectangle bounds, str textBounds.Width = measuredBounds.Width; textBounds.Height = measuredBounds.Height; - if ((flags & TextFormatFlags.Right) == TextFormatFlags.Right) { + if ((flags & TextFormatFlags.Right) == TextFormatFlags.Right) + { textBounds.X = bounds.Right - textBounds.Width - boxHeaderWidth + 1; // +1 to account for the margin built in the MeasureText result } - else { + else + { textBounds.X += boxHeaderWidth - 1; // -1 to account for the margin built in the MeasureText result } @@ -175,9 +197,9 @@ private static void DrawThemedGroupBoxWithText(Graphics g, Rectangle bounds, str boxBounds.Height -= font.Height / 2; // Break box into three segments, that don't overlap the text area - Rectangle clipLeft = boxBounds; + Rectangle clipLeft = boxBounds; Rectangle clipMiddle = boxBounds; - Rectangle clipRight = boxBounds; + Rectangle clipRight = boxBounds; clipLeft.Width = boxHeaderWidth; clipMiddle.Width = Math.Max(0, textBounds.Width - 3); // -3 to account for the margin built in the MeasureText result @@ -195,7 +217,7 @@ private static void DrawThemedGroupBoxWithText(Graphics g, Rectangle bounds, str } clipMiddle.Y = textBounds.Bottom; clipMiddle.Height -= (textBounds.Bottom - boxBounds.Top); - + Debug.Assert(textBounds.Y <= boxBounds.Y, "if text below box, need to render area of box above text"); // Render clipped portion of background in each segment @@ -207,11 +229,13 @@ private static void DrawThemedGroupBoxWithText(Graphics g, Rectangle bounds, str /// /// Draws an un-themed GroupBox with no text label. /// - private static void DrawUnthemedGroupBoxNoText(Graphics g, Rectangle bounds, GroupBoxState state) { - Color backColor = SystemColors.Control; + private static void DrawUnthemedGroupBoxNoText(Graphics g, Rectangle bounds, GroupBoxState state) + { + Color backColor = SystemColors.Control; Pen light = new Pen(ControlPaint.Light(backColor, 1.0f)); Pen dark = new Pen(ControlPaint.Dark(backColor, 0f)); - try { + try + { // left g.DrawLine(light, bounds.Left + 1, bounds.Top + 1, bounds.Left + 1, bounds.Height - 1); g.DrawLine(dark, bounds.Left, bounds.Top + 1, bounds.Left, bounds.Height - 2); @@ -223,16 +247,19 @@ private static void DrawUnthemedGroupBoxNoText(Graphics g, Rectangle bounds, Gro // top g.DrawLine(light, bounds.Left + 1, bounds.Top + 1, bounds.Width - 1, bounds.Top + 1); g.DrawLine(dark, bounds.Left, bounds.Top, bounds.Width - 2, bounds.Top); - + // right g.DrawLine(light, bounds.Width - 1, bounds.Top, bounds.Width - 1, bounds.Height - 1); g.DrawLine(dark, bounds.Width - 2, bounds.Top, bounds.Width - 2, bounds.Height - 2); } - finally { - if (light != null) { + finally + { + if (light != null) + { light.Dispose(); } - if (dark != null) { + if (dark != null) + { dark.Dispose(); } } @@ -242,7 +269,8 @@ private static void DrawUnthemedGroupBoxNoText(Graphics g, Rectangle bounds, Gro /// Draws an un-themed GroupBox with a text label. /// Variation of the logic in GroupBox.DrawGroupBox(). /// - private static void DrawUnthemedGroupBoxWithText(Graphics g, Rectangle bounds, string groupBoxText, Font font, Color textColor, TextFormatFlags flags, GroupBoxState state) { + private static void DrawUnthemedGroupBoxWithText(Graphics g, Rectangle bounds, string groupBoxText, Font font, Color textColor, TextFormatFlags flags, GroupBoxState state) + { // Calculate text area, and render text inside it Rectangle textBounds = bounds; @@ -251,10 +279,12 @@ private static void DrawUnthemedGroupBoxWithText(Graphics g, Rectangle bounds, s textBounds.Width = measuredBounds.Width; textBounds.Height = measuredBounds.Height; - if ((flags & TextFormatFlags.Right) == TextFormatFlags.Right) { + if ((flags & TextFormatFlags.Right) == TextFormatFlags.Right) + { textBounds.X = bounds.Right - textBounds.Width - textOffset; } - else { + else + { textBounds.X += textOffset; } @@ -268,7 +298,7 @@ private static void DrawUnthemedGroupBoxWithText(Graphics g, Rectangle bounds, s Pen dark = new Pen(SystemColors.ControlDark); int boxTop = bounds.Top + font.Height / 2; - + // left g.DrawLine(light, bounds.Left + 1, boxTop, bounds.Left + 1, bounds.Height - 1); g.DrawLine(dark, bounds.Left, boxTop - 1, bounds.Left, bounds.Height - 2); @@ -280,11 +310,11 @@ private static void DrawUnthemedGroupBoxWithText(Graphics g, Rectangle bounds, s // top-left g.DrawLine(light, bounds.Left + 1, boxTop, textBounds.X - 2, boxTop); g.DrawLine(dark, bounds.Left, boxTop - 1, textBounds.X - 3, boxTop - 1); - + // top-right g.DrawLine(light, textBounds.X + textBounds.Width + 1, boxTop, bounds.Width - 1, boxTop); g.DrawLine(dark, textBounds.X + textBounds.Width + 2, boxTop - 1, bounds.Width - 2, boxTop - 1); - + // right g.DrawLine(light, bounds.Width - 1, boxTop, bounds.Width - 1, bounds.Height - 1); g.DrawLine(dark, bounds.Width - 2, boxTop - 1, bounds.Width - 2, bounds.Height - 2); @@ -293,28 +323,35 @@ private static void DrawUnthemedGroupBoxWithText(Graphics g, Rectangle bounds, s dark.Dispose(); } - private static Color DefaultTextColor(GroupBoxState state) { - if (RenderWithVisualStyles) { + private static Color DefaultTextColor(GroupBoxState state) + { + if (RenderWithVisualStyles) + { InitializeRenderer((int)state); return visualStyleRenderer.GetColor(ColorProperty.TextColor); } - else { + else + { return SystemColors.ControlText; } } - private static void InitializeRenderer(int state) { + private static void InitializeRenderer(int state) + { int part = GroupBoxElement.Part; if (SystemInformation.HighContrast && ((GroupBoxState)state == GroupBoxState.Disabled) - && VisualStyleRenderer.IsCombinationDefined(GroupBoxElement.ClassName, VisualStyleElement.Button.GroupBox.HighContrastDisabledPart)) { - part = VisualStyleElement.Button.GroupBox.HighContrastDisabledPart; + && VisualStyleRenderer.IsCombinationDefined(GroupBoxElement.ClassName, VisualStyleElement.Button.GroupBox.HighContrastDisabledPart)) + { + part = VisualStyleElement.Button.GroupBox.HighContrastDisabledPart; } - if (visualStyleRenderer == null) { + if (visualStyleRenderer == null) + { visualStyleRenderer = new VisualStyleRenderer(GroupBoxElement.ClassName, part, state); } - else { + else + { visualStyleRenderer.SetParameters(GroupBoxElement.ClassName, part, state); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Help.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Help.cs index a2228d28488..8f15a6f18dc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Help.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Help.cs @@ -2,10 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.InteropServices; using System.Diagnostics; - using System.Diagnostics.CodeAnalysis; + using System.Diagnostics.CodeAnalysis; using System; using System.Net; using System.Drawing; @@ -14,55 +15,57 @@ namespace System.Windows.Forms { using System.Text; using Microsoft.Win32; using System.Globalization; - + /// /// /// Represents the HTML 1.0 Help engine. /// /// - public class Help { + public class Help + { #if DEBUG internal static readonly TraceSwitch WindowsFormsHelpTrace = new TraceSwitch("WindowsFormsHelpTrace", "Debug help system"); #else internal static readonly TraceSwitch WindowsFormsHelpTrace; #endif - private const int HH_DISPLAY_TOPIC =0x0000; - private const int HH_HELP_FINDER =0x0000; // WinHelp equivalent - private const int HH_DISPLAY_TOC =0x0001; // not currently implemented - private const int HH_DISPLAY_INDEX =0x0002; // not currently implemented - private const int HH_DISPLAY_SEARCH =0x0003; // not currently implemented - private const int HH_SET_WIN_TYPE =0x0004; - private const int HH_GET_WIN_TYPE =0x0005; - private const int HH_GET_WIN_HANDLE =0x0006; - private const int HH_ENUM_INFO_TYPE =0x0007; // Get Info type name, call repeatedly to enumerate, -1 at end - private const int HH_SET_INFO_TYPE =0x0008; // Add Info type to filter. - private const int HH_SYNC =0x0009; - private const int HH_ADD_NAV_UI =0x000A; // not currently implemented - private const int HH_ADD_BUTTON =0x000B; // not currently implemented - private const int HH_GETBROWSER_APP =0x000C; // not currently implemented - private const int HH_KEYWORD_LOOKUP =0x000D; - private const int HH_DISPLAY_TEXT_POPUP =0x000E; // display string resource id or text in a popup window - private const int HH_HELP_CONTEXT =0x000F; // display mapped numeric value in dwData - private const int HH_TP_HELP_CONTEXTMENU =0x0010; // text popup help, same as WinHelp HELP_CONTEXTMENU - private const int HH_TP_HELP_WM_HELP =0x0011; // text popup help, same as WinHelp HELP_WM_HELP - private const int HH_CLOSE_ALL =0x0012; // close all windows opened directly or indirectly by the caller - private const int HH_ALINK_LOOKUP =0x0013; // ALink version of HH_KEYWORD_LOOKUP - private const int HH_GET_LAST_ERROR =0x0014; // not currently implemented // See HHERROR.h - private const int HH_ENUM_CATEGORY =0x0015; // Get category name, call repeatedly to enumerate, -1 at end - private const int HH_ENUM_CATEGORY_IT =0x0016; // Get category info type members, call repeatedly to enumerate, -1 at end - private const int HH_RESET_IT_FILTER =0x0017; // Clear the info type filter of all info types. - private const int HH_SET_INCLUSIVE_FILTER =0x0018; // set inclusive filtering method for untyped topics to be included in display - private const int HH_SET_EXCLUSIVE_FILTER =0x0019; // set exclusive filtering method for untyped topics to be excluded from display - private const int HH_SET_GUID =0x001A; // For Microsoft Installer -- dwData is a pointer to the GUID string + private const int HH_DISPLAY_TOPIC = 0x0000; + private const int HH_HELP_FINDER = 0x0000; // WinHelp equivalent + private const int HH_DISPLAY_TOC = 0x0001; // not currently implemented + private const int HH_DISPLAY_INDEX = 0x0002; // not currently implemented + private const int HH_DISPLAY_SEARCH = 0x0003; // not currently implemented + private const int HH_SET_WIN_TYPE = 0x0004; + private const int HH_GET_WIN_TYPE = 0x0005; + private const int HH_GET_WIN_HANDLE = 0x0006; + private const int HH_ENUM_INFO_TYPE = 0x0007; // Get Info type name, call repeatedly to enumerate, -1 at end + private const int HH_SET_INFO_TYPE = 0x0008; // Add Info type to filter. + private const int HH_SYNC = 0x0009; + private const int HH_ADD_NAV_UI = 0x000A; // not currently implemented + private const int HH_ADD_BUTTON = 0x000B; // not currently implemented + private const int HH_GETBROWSER_APP = 0x000C; // not currently implemented + private const int HH_KEYWORD_LOOKUP = 0x000D; + private const int HH_DISPLAY_TEXT_POPUP = 0x000E; // display string resource id or text in a popup window + private const int HH_HELP_CONTEXT = 0x000F; // display mapped numeric value in dwData + private const int HH_TP_HELP_CONTEXTMENU = 0x0010; // text popup help, same as WinHelp HELP_CONTEXTMENU + private const int HH_TP_HELP_WM_HELP = 0x0011; // text popup help, same as WinHelp HELP_WM_HELP + private const int HH_CLOSE_ALL = 0x0012; // close all windows opened directly or indirectly by the caller + private const int HH_ALINK_LOOKUP = 0x0013; // ALink version of HH_KEYWORD_LOOKUP + private const int HH_GET_LAST_ERROR = 0x0014; // not currently implemented // See HHERROR.h + private const int HH_ENUM_CATEGORY = 0x0015; // Get category name, call repeatedly to enumerate, -1 at end + private const int HH_ENUM_CATEGORY_IT = 0x0016; // Get category info type members, call repeatedly to enumerate, -1 at end + private const int HH_RESET_IT_FILTER = 0x0017; // Clear the info type filter of all info types. + private const int HH_SET_INCLUSIVE_FILTER = 0x0018; // set inclusive filtering method for untyped topics to be included in display + private const int HH_SET_EXCLUSIVE_FILTER = 0x0019; // set exclusive filtering method for untyped topics to be excluded from display + private const int HH_SET_GUID = 0x001A; // For Microsoft Installer -- dwData is a pointer to the GUID string private const int HTML10HELP = 2; - private const int HTMLFILE = 3; + private const int HTMLFILE = 3; // not creatable // - private Help() { - } + private Help() + { + } /// /// @@ -70,7 +73,8 @@ private Help() { /// the contents of the Help file at located at a specified Url. /// /// - public static void ShowHelp(Control parent, string url) { + public static void ShowHelp(Control parent, string url) + { ShowHelp(parent, url, HelpNavigator.TableOfContents, null); } @@ -81,7 +85,8 @@ public static void ShowHelp(Control parent, string url) { /// file for a specific topic found at the specified Url. /// /// - public static void ShowHelp(Control parent, string url, HelpNavigator navigator) { + public static void ShowHelp(Control parent, string url, HelpNavigator navigator) + { ShowHelp(parent, url, navigator, null); } @@ -92,11 +97,14 @@ public static void ShowHelp(Control parent, string url, HelpNavigator navigator) /// file for a specific topic found at the specified Url. /// /// - public static void ShowHelp(Control parent, string url, string keyword) { - if (keyword != null && keyword.Length != 0) { + public static void ShowHelp(Control parent, string url, string keyword) + { + if (keyword != null && keyword.Length != 0) + { ShowHelp(parent, url, HelpNavigator.Topic, keyword); } - else { + else + { ShowHelp(parent, url, HelpNavigator.TableOfContents, null); } } @@ -109,10 +117,12 @@ public static void ShowHelp(Control parent, string url, string keyword) { /// user. /// /// - public static void ShowHelp(Control parent, string url, HelpNavigator command, object parameter) { + public static void ShowHelp(Control parent, string url, HelpNavigator command, object parameter) + { Debug.WriteLineIf(Help.WindowsFormsHelpTrace.TraceVerbose, "Help:: ShowHelp"); - switch (GetHelpFileType(url)) { + switch (GetHelpFileType(url)) + { case HTML10HELP: ShowHTML10Help(parent, url, command, parameter); break; @@ -127,7 +137,8 @@ public static void ShowHelp(Control parent, string url, HelpNavigator command, o /// Displays the index of the specified file. /// /// - public static void ShowHelpIndex(Control parent, string url) { + public static void ShowHelpIndex(Control parent, string url) + { Debug.WriteLineIf(Help.WindowsFormsHelpTrace.TraceVerbose, "Help:: ShowHelpIndex"); ShowHelp(parent, url, HelpNavigator.Index, null); @@ -138,15 +149,17 @@ public static void ShowHelpIndex(Control parent, string url) { /// Displays a Help pop-up window. /// /// - public static void ShowPopup(Control parent, string caption, Point location) { + public static void ShowPopup(Control parent, string caption, Point location) + { Debug.WriteLineIf(Help.WindowsFormsHelpTrace.TraceVerbose, "Help:: ShowPopup"); NativeMethods.HH_POPUP pop = new NativeMethods.HH_POPUP(); // We have to marshal the string ourselves to prevent access violations. IntPtr pszText = Marshal.StringToCoTaskMemAuto(caption); - - try { + + try + { pop.pszText = pszText; pop.idString = 0; pop.pt = new NativeMethods.POINT(location.X, location.Y); @@ -158,7 +171,8 @@ public static void ShowPopup(Control parent, string caption, Point location) { ShowHTML10Help(parent, null, HelpNavigator.Topic, pop); } - finally { + finally + { Marshal.FreeCoTaskMem(pszText); } @@ -167,27 +181,31 @@ public static void ShowPopup(Control parent, string caption, Point location) { /// /// Displays HTML 1.0 Help with the specified parameters /// - private static void ShowHTML10Help(Control parent, string url, HelpNavigator command, object param) { + private static void ShowHTML10Help(Control parent, string url, HelpNavigator command, object param) + { Debug.WriteLineIf(Help.WindowsFormsHelpTrace.TraceVerbose, "Help:: ShowHTML10Help:: " + url + ", " + command.ToString("G") + ", " + param); - + // See if we can get a full path and file name and if that will // resolve the out of memory condition with file names that include spaces. // If we can't, though, we can't assume that the path's no good: it might be in // the Windows help directory. Uri file = null; string pathAndFileName = url; //This is our best guess at the path yet. - + file = Resolve(url); - if (file != null) { // Can't assume we have a good url + if (file != null) + { // Can't assume we have a good url pathAndFileName = file.AbsoluteUri; } - if (file == null || file.IsFile) { + if (file == null || file.IsFile) + { StringBuilder newPath = new StringBuilder(); string localPath = (file != null && file.IsFile) ? file.LocalPath : url; // If this is a local path, convert it to a short path name. Pass 0 as the length the first time uint requiredStringSize = UnsafeNativeMethods.GetShortPathName(localPath, newPath, 0); - if (requiredStringSize > 0) { + if (requiredStringSize > 0) + { //It's able to make it a short path. Happy day. newPath.Capacity = (int)requiredStringSize; requiredStringSize = UnsafeNativeMethods.GetShortPathName(localPath, newPath, requiredStringSize); @@ -197,47 +215,58 @@ private static void ShowHTML10Help(Control parent, string url, HelpNavigator com } HandleRef handle; - if (parent != null) { + if (parent != null) + { handle = new HandleRef(parent, parent.Handle); } - else { + else + { handle = new HandleRef(null, UnsafeNativeMethods.GetActiveWindow()); } object htmlParam; string stringParam = param as string; - if (stringParam != null) { + if (stringParam != null) + { int htmlCommand = MapCommandToHTMLCommand(command, stringParam, out htmlParam); - + string stringHtmlParam = htmlParam as string; - if (stringHtmlParam != null) { + if (stringHtmlParam != null) + { SafeNativeMethods.HtmlHelp(handle, pathAndFileName, htmlCommand, stringHtmlParam); } - else if (htmlParam is int) { + else if (htmlParam is int) + { SafeNativeMethods.HtmlHelp(handle, pathAndFileName, htmlCommand, (int)htmlParam); } - else if (htmlParam is NativeMethods.HH_FTS_QUERY) { + else if (htmlParam is NativeMethods.HH_FTS_QUERY) + { SafeNativeMethods.HtmlHelp(handle, pathAndFileName, htmlCommand, (NativeMethods.HH_FTS_QUERY)htmlParam); } - else if (htmlParam is NativeMethods.HH_AKLINK) { + else if (htmlParam is NativeMethods.HH_AKLINK) + { // According to MSDN documentation, we have to ensure that the help window is up // before we call ALINK lookup. // SafeNativeMethods.HtmlHelp(NativeMethods.NullHandleRef, pathAndFileName, HH_DISPLAY_TOPIC, (string)null); SafeNativeMethods.HtmlHelp(handle, pathAndFileName, htmlCommand, (NativeMethods.HH_AKLINK)htmlParam); } - else { + else + { Debug.Fail("Cannot handle HTML parameter of type: " + htmlParam.GetType()); SafeNativeMethods.HtmlHelp(handle, pathAndFileName, htmlCommand, (string)param); } } - else if (param == null ) { + else if (param == null) + { SafeNativeMethods.HtmlHelp(handle, pathAndFileName, MapCommandToHTMLCommand(command, null, out htmlParam), 0); } - else if (param is NativeMethods.HH_POPUP) { + else if (param is NativeMethods.HH_POPUP) + { SafeNativeMethods.HtmlHelp(handle, pathAndFileName, HH_DISPLAY_TEXT_POPUP, (NativeMethods.HH_POPUP)param); } - else if (param.GetType() == typeof(int)) { + else if (param.GetType() == typeof(int)) + { throw new ArgumentException(string.Format(SR.InvalidArgument, nameof(param), "Integer"), nameof(param)); } } @@ -250,16 +279,19 @@ private static void ShowHTML10Help(Control parent, string url, HelpNavigator com [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - private static void ShowHTMLFile(Control parent, string url, HelpNavigator command, object param) { + private static void ShowHTMLFile(Control parent, string url, HelpNavigator command, object param) + { Debug.WriteLineIf(Help.WindowsFormsHelpTrace.TraceVerbose, "Help:: ShowHTMLHelp:: " + url + ", " + command.ToString("G") + ", " + param); Uri file = Resolve(url); - if (file == null) { + if (file == null) + { throw new ArgumentException(string.Format(SR.HelpInvalidURL, url), "url"); } - switch (command) { + switch (command) + { case HelpNavigator.TableOfContents: case HelpNavigator.Find: case HelpNavigator.Index: @@ -267,17 +299,20 @@ private static void ShowHTMLFile(Control parent, string url, HelpNavigator comma // break; case HelpNavigator.Topic: - if (param != null && param is string) { + if (param != null && param is string) + { file = new Uri(file.ToString() + "#" + (string)param); } break; } HandleRef handle; - if (parent != null) { + if (parent != null) + { handle = new HandleRef(parent, parent.Handle); } - else { + else + { handle = new HandleRef(null, UnsafeNativeMethods.GetActiveWindow()); } @@ -286,48 +321,59 @@ private static void ShowHTMLFile(Control parent, string url, HelpNavigator comma UnsafeNativeMethods.ShellExecute_NoBFM(handle, null, file.ToString(), null, null, NativeMethods.SW_NORMAL); } - private static Uri Resolve(string partialUri) { + private static Uri Resolve(string partialUri) + { Debug.WriteLineIf(Help.WindowsFormsHelpTrace.TraceVerbose, "Help:: Resolve " + partialUri); Debug.Indent(); Uri file = null; - if (!string.IsNullOrEmpty(partialUri)) { - try { + if (!string.IsNullOrEmpty(partialUri)) + { + try + { file = new Uri(partialUri); } - catch (UriFormatException) { + catch (UriFormatException) + { // Ignore invalid uris. } } - if (file != null && file.Scheme == "file") { + if (file != null && file.Scheme == "file") + { string localPath = NativeMethods.GetLocalPath(partialUri); Debug.WriteLineIf(Help.WindowsFormsHelpTrace.TraceVerbose, "file, check for existence"); - if (!File.Exists(localPath)) { + if (!File.Exists(localPath)) + { // clear, and try relative to AppBase... // file = null; } } - if (file == null) { + if (file == null) + { Debug.WriteLineIf(Help.WindowsFormsHelpTrace.TraceVerbose, "try appbase relative"); - try { + try + { // try relative to AppBase... // - file = new Uri(new Uri(AppContext.BaseDirectory), + file = new Uri(new Uri(AppContext.BaseDirectory), partialUri); } - catch (UriFormatException) { + catch (UriFormatException) + { // Ignore invalid uris. } - if (file != null && file.Scheme == "file") { + if (file != null && file.Scheme == "file") + { string localPath = file.LocalPath + file.Fragment; Debug.WriteLineIf(Help.WindowsFormsHelpTrace.TraceVerbose, "file, check for existence"); - if (!File.Exists(localPath)) { + if (!File.Exists(localPath)) + { // clear - file isn't there... // file = null; @@ -339,21 +385,25 @@ private static Uri Resolve(string partialUri) { return file; } - private static int GetHelpFileType(string url) { + private static int GetHelpFileType(string url) + { Debug.WriteLineIf(Help.WindowsFormsHelpTrace.TraceVerbose, "Help:: GetHelpFileType " + url); - if (url == null) { + if (url == null) + { Debug.WriteLineIf(Help.WindowsFormsHelpTrace.TraceVerbose, "\tnull, must be Html File"); return HTMLFILE; } Uri file = Resolve(url); - if (file == null || file.Scheme == "file") { + if (file == null || file.Scheme == "file") + { Debug.WriteLineIf(Help.WindowsFormsHelpTrace.TraceVerbose, "\tfile"); string ext = Path.GetExtension(file == null ? url : file.LocalPath + file.Fragment).ToLower(CultureInfo.InvariantCulture); - if (ext == ".chm" || ext == ".col") { + if (ext == ".chm" || ext == ".col") + { Debug.WriteLineIf(Help.WindowsFormsHelpTrace.TraceVerbose, "\tchm or col, HtmlHelp 1.0 file"); return HTML10HELP; } @@ -366,50 +416,58 @@ private static int GetHelpFileType(string url) { /// /// Maps one of the COMMAND_* constants to the HTML 1.0 Help equivalent. /// - private static int MapCommandToHTMLCommand(HelpNavigator command, string param, out object htmlParam) { + private static int MapCommandToHTMLCommand(HelpNavigator command, string param, out object htmlParam) + { htmlParam = param; if ((string.IsNullOrEmpty(param)) && - (command == HelpNavigator.AssociateIndex || command == HelpNavigator.KeywordIndex)) { + (command == HelpNavigator.AssociateIndex || command == HelpNavigator.KeywordIndex)) + { return HH_DISPLAY_INDEX; } - switch (command) { + switch (command) + { case HelpNavigator.Topic: return HH_DISPLAY_TOPIC; - + case HelpNavigator.TableOfContents: return HH_DISPLAY_TOC; - + case HelpNavigator.Index: return HH_DISPLAY_INDEX; - - case HelpNavigator.Find: { - NativeMethods.HH_FTS_QUERY ftsQuery = new NativeMethods.HH_FTS_QUERY(); - ftsQuery.pszSearchQuery = param; - htmlParam = ftsQuery; - return HH_DISPLAY_SEARCH; - } - case HelpNavigator.TopicId: { - try { - htmlParam = int.Parse(param, CultureInfo.InvariantCulture); - return HH_HELP_CONTEXT; + + case HelpNavigator.Find: + { + NativeMethods.HH_FTS_QUERY ftsQuery = new NativeMethods.HH_FTS_QUERY(); + ftsQuery.pszSearchQuery = param; + htmlParam = ftsQuery; + return HH_DISPLAY_SEARCH; } - catch { - // default to just showing the index - return HH_DISPLAY_INDEX; + case HelpNavigator.TopicId: + { + try + { + htmlParam = int.Parse(param, CultureInfo.InvariantCulture); + return HH_HELP_CONTEXT; + } + catch + { + // default to just showing the index + return HH_DISPLAY_INDEX; + } } - } case HelpNavigator.KeywordIndex: - case HelpNavigator.AssociateIndex: { - NativeMethods.HH_AKLINK alink = new NativeMethods.HH_AKLINK(); - alink.pszKeywords = param; - alink.fIndexOnFail = true; - alink.fReserved = false; - htmlParam = alink; - return (command == HelpNavigator.KeywordIndex) ? HH_KEYWORD_LOOKUP : HH_ALINK_LOOKUP; - } - + case HelpNavigator.AssociateIndex: + { + NativeMethods.HH_AKLINK alink = new NativeMethods.HH_AKLINK(); + alink.pszKeywords = param; + alink.fIndexOnFail = true; + alink.fReserved = false; + htmlParam = alink; + return (command == HelpNavigator.KeywordIndex) ? HH_KEYWORD_LOOKUP : HH_ALINK_LOOKUP; + } + default: return (int)command; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs index 095e7c77883..0abeace9381 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs @@ -717,7 +717,7 @@ public override void ConnectToEvents() new HTMLDocumentEvents2(htmlDocument), typeof(UnsafeNativeMethods.DHTMLDocumentEvents2), /*throwException*/ false); - if (!cookie.Connected) + if (!cookie.Connected) { cookie = null; } @@ -855,91 +855,91 @@ public bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj) } public void onkeydown(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onkeyup(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public bool onkeypress(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public void onreadystatechange(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public bool onselectstart(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public void onrowsdelete(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onrowsinserted(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void oncellchange(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onpropertychange(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void ondataavailable(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void ondatasetcomplete(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onbeforeeditfocus(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onselectionchange(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public bool oncontrolselect(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public bool onmousewheel(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public void onactivate(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void ondeactivate(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public bool onbeforeactivate(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public bool onbeforedeactivate(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); @@ -947,7 +947,7 @@ public bool onbeforedeactivate(UnsafeNativeMethods.IHTMLEventObj evtObj) } } - #region operators + #region operators [SuppressMessage("Microsoft.Design", "CA1046:DoNotOverrideOperatorEqualsOnReferenceTypes")] public static bool operator ==(HtmlDocument left, HtmlDocument right) @@ -1000,7 +1000,7 @@ public override bool Equals(object obj) { return (this == (HtmlDocument)obj); } - #endregion + #endregion } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs index 8b3dd9b8117..77870230cd4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs @@ -126,9 +126,9 @@ public HtmlElement FirstChild UnsafeNativeMethods.IHTMLElement iHtmlElement = null; UnsafeNativeMethods.IHTMLDOMNode iHtmlDomNode = this.NativeHtmlElement as UnsafeNativeMethods.IHTMLDOMNode; - if( iHtmlDomNode != null ) + if (iHtmlDomNode != null) { - iHtmlElement = iHtmlDomNode.FirstChild() as UnsafeNativeMethods.IHTMLElement; + iHtmlElement = iHtmlDomNode.FirstChild() as UnsafeNativeMethods.IHTMLElement; } return iHtmlElement != null ? new HtmlElement(shimManager, iHtmlElement) : null; } @@ -222,7 +222,7 @@ public HtmlElement NextSibling UnsafeNativeMethods.IHTMLElement iHtmlElement = null; UnsafeNativeMethods.IHTMLDOMNode iHtmlDomNode = this.NativeHtmlElement as UnsafeNativeMethods.IHTMLDOMNode; - if( iHtmlDomNode != null ) + if (iHtmlDomNode != null) { iHtmlElement = iHtmlDomNode.NextSibling() as UnsafeNativeMethods.IHTMLElement; } @@ -846,9 +846,9 @@ public bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj) HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public void onmouseout(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public bool onselectstart(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); @@ -856,7 +856,7 @@ public bool onselectstart(UnsafeNativeMethods.IHTMLEventObj evtObj) } public void onfilterchange(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); @@ -868,129 +868,129 @@ public bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj) HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void ondataavailable(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void ondatasetcomplete(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onlosecapture(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onpropertychange(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onscroll(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onresize(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public bool oncut(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public bool onbeforecopy(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public bool oncopy(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public bool onbeforepaste(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public bool onpaste(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public bool oncontextmenu(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public void onrowsdelete(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onrowsinserted(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void oncellchange(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onreadystatechange(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onlayoutcomplete(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onpage(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onactivate(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void ondeactivate(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public bool onbeforedeactivate(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public bool onbeforeactivate(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public void onmove(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public bool oncontrolselect(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public bool onmovestart(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public void onmoveend(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public bool onmousewheel(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); @@ -1002,33 +1002,33 @@ public bool onchange(UnsafeNativeMethods.IHTMLEventObj evtObj) HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public void onselect(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onload(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onerror(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onabort(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public bool onsubmit(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public bool onreset(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } - + public void onchange_void(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onbounce(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onfinish(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onstart(UnsafeNativeMethods.IHTMLEventObj evtObj) { } } @@ -1127,7 +1127,7 @@ public override void ConnectToEvents() new HTMLElementEvents2(htmlElement), dispInterfaceTypes[i], /*throwException*/ false); - if (!cookie.Connected) + if (!cookie.Connected) { cookie = null; } @@ -1172,7 +1172,7 @@ protected override object GetEventSender() } - #region operators + #region operators [SuppressMessage("Microsoft.Design", "CA1046:DoNotOverrideOperatorEqualsOnReferenceTypes")] public static bool operator ==(HtmlElement left, HtmlElement right) { @@ -1226,7 +1226,7 @@ public override bool Equals(object obj) //never be null, so now it will return false as expected (not throw). return this == (obj as HtmlElement); } - #endregion + #endregion diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementCollection.cs index 1efdf36d538..be05258fb19 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementCollection.cs @@ -12,96 +12,120 @@ public sealed class HtmlElementCollection : ICollection private UnsafeNativeMethods.IHTMLElementCollection htmlElementCollection; private HtmlElement[] elementsArray; private HtmlShimManager shimManager; - - internal HtmlElementCollection(HtmlShimManager shimManager) { + + internal HtmlElementCollection(HtmlShimManager shimManager) + { this.htmlElementCollection = null; this.elementsArray = null; this.shimManager = shimManager; } - - internal HtmlElementCollection(HtmlShimManager shimManager, UnsafeNativeMethods.IHTMLElementCollection elements) { + + internal HtmlElementCollection(HtmlShimManager shimManager, UnsafeNativeMethods.IHTMLElementCollection elements) + { this.htmlElementCollection = elements; this.elementsArray = null; this.shimManager = shimManager; Debug.Assert(this.NativeHtmlElementCollection != null, "The element collection object should implement IHTMLElementCollection"); } - internal HtmlElementCollection(HtmlShimManager shimManager, HtmlElement[] array) { + internal HtmlElementCollection(HtmlShimManager shimManager, HtmlElement[] array) + { this.htmlElementCollection = null; this.elementsArray = array; this.shimManager = shimManager; } - private UnsafeNativeMethods.IHTMLElementCollection NativeHtmlElementCollection { - get { + private UnsafeNativeMethods.IHTMLElementCollection NativeHtmlElementCollection + { + get + { return this.htmlElementCollection; } } - public HtmlElement this[int index] { - get { + public HtmlElement this[int index] + { + get + { //do some bounds checking here... - if (index < 0 || index >= Count) { + if (index < 0 || index >= Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidBoundArgument, nameof(index), index, 0, Count - 1)); } - if (this.NativeHtmlElementCollection != null) { + if (this.NativeHtmlElementCollection != null) + { UnsafeNativeMethods.IHTMLElement htmlElement = this.NativeHtmlElementCollection.Item((object)index, (object)0) as UnsafeNativeMethods.IHTMLElement; return (htmlElement != null) ? new HtmlElement(shimManager, htmlElement) : null; } - else if (elementsArray != null) { + else if (elementsArray != null) + { return this.elementsArray[index]; } - else { + else + { return null; } } } - public HtmlElement this[string elementId] { - get { - if (this.NativeHtmlElementCollection != null) { + public HtmlElement this[string elementId] + { + get + { + if (this.NativeHtmlElementCollection != null) + { UnsafeNativeMethods.IHTMLElement htmlElement = this.NativeHtmlElementCollection.Item((object)elementId, (object)0) as UnsafeNativeMethods.IHTMLElement; return (htmlElement != null) ? new HtmlElement(shimManager, htmlElement) : null; } - else if (elementsArray != null) { + else if (elementsArray != null) + { int count = this.elementsArray.Length; - for (int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) + { HtmlElement element = this.elementsArray[i]; - if (element.Id == elementId) { + if (element.Id == elementId) + { return element; } } return null; // not found } - else { + else + { return null; } } } - public HtmlElementCollection GetElementsByName(string name) { + public HtmlElementCollection GetElementsByName(string name) + { int count = this.Count; HtmlElement[] temp = new HtmlElement[count]; // count is the maximum # of matches int tempIndex = 0; - - for (int i = 0; i < count; i++) { + + for (int i = 0; i < count; i++) + { HtmlElement element = this[i]; - if (element.GetAttribute("name") == name) { + if (element.GetAttribute("name") == name) + { temp[tempIndex] = element; tempIndex++; } } - - if (tempIndex == 0) { + + if (tempIndex == 0) + { return new HtmlElementCollection(shimManager); } - else { + else + { HtmlElement[] elements = new HtmlElement[tempIndex]; - for (int i = 0; i < tempIndex; i++) { + for (int i = 0; i < tempIndex; i++) + { elements[i] = temp[i]; } return new HtmlElementCollection(shimManager, elements); @@ -111,43 +135,55 @@ public HtmlElementCollection GetElementsByName(string name) { /// /// Returns the total number of elements in the collection. /// - public int Count { - get { - if (this.NativeHtmlElementCollection != null) { + public int Count + { + get + { + if (this.NativeHtmlElementCollection != null) + { return this.NativeHtmlElementCollection.GetLength(); } - else if (elementsArray != null) { + else if (elementsArray != null) + { return this.elementsArray.Length; } - else { + else + { return 0; } } } - - bool ICollection.IsSynchronized { - get { + + bool ICollection.IsSynchronized + { + get + { return false; } } - - object ICollection.SyncRoot { - get { + + object ICollection.SyncRoot + { + get + { return this; } } - void ICollection.CopyTo(Array dest, int index) { + void ICollection.CopyTo(Array dest, int index) + { int count = this.Count; - for (int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) + { dest.SetValue(this[i], index++); } } - public IEnumerator GetEnumerator() { + public IEnumerator GetEnumerator() + { HtmlElement[] htmlElements = new HtmlElement[this.Count]; ((ICollection)this).CopyTo(htmlElements, 0); - + return htmlElements.GetEnumerator(); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementEventArgs.cs index aea5f8d5596..acfb34f7fe5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementEventArgs.cs @@ -12,15 +12,15 @@ namespace System.Windows.Forms public sealed class HtmlElementEventArgs : EventArgs { private HtmlShimManager _shimManager; - + internal HtmlElementEventArgs(HtmlShimManager shimManager, UnsafeNativeMethods.IHTMLEventObj eventObj) { NativeHTMLEventObj = eventObj; Debug.Assert(NativeHTMLEventObj != null, "The event object should implement IHTMLEventObj"); - + _shimManager = shimManager; } - + private UnsafeNativeMethods.IHTMLEventObj NativeHTMLEventObj { get; } public MouseButtons MouseButtonsPressed @@ -29,13 +29,16 @@ public MouseButtons MouseButtonsPressed { MouseButtons buttons = MouseButtons.None; int nButtons = NativeHTMLEventObj.GetButton(); - if ((nButtons & 1) != 0) { + if ((nButtons & 1) != 0) + { buttons |= MouseButtons.Left; } - if ((nButtons & 2) != 0) { + if ((nButtons & 2) != 0) + { buttons |= MouseButtons.Right; } - if ((nButtons & 4) != 0) { + if ((nButtons & 4) != 0) + { buttons |= MouseButtons.Middle; } return buttons; @@ -57,7 +60,8 @@ public Point MousePosition get => new Point(NativeHTMLEventObj.GetX(), NativeHTMLEventObj.GetY()); } - public bool BubbleEvent { + public bool BubbleEvent + { get => !NativeHTMLEventObj.GetCancelBubble(); set => NativeHTMLEventObj.SetCancelBubble(!value); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlHistory.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlHistory.cs index 180781adfd8..3601a99144d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlHistory.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlHistory.cs @@ -14,7 +14,8 @@ using System.Net; using System.Globalization; -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ public sealed class HtmlHistory : IDisposable { private UnsafeNativeMethods.IOmHistory htmlHistory; @@ -26,42 +27,54 @@ internal HtmlHistory(UnsafeNativeMethods.IOmHistory history) Debug.Assert(this.NativeOmHistory != null, "The history object should implement IOmHistory"); } - private UnsafeNativeMethods.IOmHistory NativeOmHistory { - get { - if (this.disposed) { + private UnsafeNativeMethods.IOmHistory NativeOmHistory + { + get + { + if (this.disposed) + { throw new System.ObjectDisposedException(GetType().Name); } return this.htmlHistory; } } - public void Dispose() { + public void Dispose() + { this.htmlHistory = null; this.disposed = true; GC.SuppressFinalize(this); } - public int Length { - get { + public int Length + { + get + { return (int)this.NativeOmHistory.GetLength(); } } - public void Back(int numberBack) { - if (numberBack < 0) { + public void Back(int numberBack) + { + if (numberBack < 0) + { throw new ArgumentOutOfRangeException(nameof(numberBack), numberBack, string.Format(SR.InvalidLowBoundArgumentEx, nameof(numberBack), numberBack, 0)); } - else if (numberBack > 0) { + else if (numberBack > 0) + { object oNumForward = (object)(-numberBack); this.NativeOmHistory.Go(ref oNumForward); } } - public void Forward(int numberForward) { - if (numberForward < 0) { + public void Forward(int numberForward) + { + if (numberForward < 0) + { throw new ArgumentOutOfRangeException(nameof(numberForward), numberForward, string.Format(SR.InvalidLowBoundArgumentEx, nameof(numberForward), numberForward, 0)); } - else if (numberForward > 0) { + else if (numberForward > 0) + { object oNumForward = (object)numberForward; this.NativeOmHistory.Go(ref oNumForward); } @@ -93,13 +106,16 @@ public void Go(string urlString) /// /// Go to the specified position in the history list /// - public void Go(int relativePosition) { + public void Go(int relativePosition) + { object loc = (object)relativePosition; this.NativeOmHistory.Go(ref loc); } - public object DomHistory { - get { + public object DomHistory + { + get + { return this.NativeOmHistory; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlShim.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlShim.cs index 847c57c80c2..190e5faa6f6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlShim.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlShim.cs @@ -2,12 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; - + /// This is essentially a proxy object between the native /// html objects and our managed ones. We want the managed /// HtmlDocument, HtmlWindow and HtmlElement to be super-lightweight, @@ -16,22 +17,28 @@ namespace System.Windows.Forms { /// manages events coming out of the HtmlDocument, HtmlElement and HtmlWindow /// and serves them back up to the user. - internal abstract class HtmlShim : IDisposable { + internal abstract class HtmlShim : IDisposable + { private EventHandlerList events; private int eventCount = 0; private Dictionary attachedEventList; - - - protected HtmlShim() { + + + protected HtmlShim() + { } - ~HtmlShim() { + ~HtmlShim() + { Dispose(false); } - private EventHandlerList Events { - get { - if (events == null) { + private EventHandlerList Events + { + get + { + if (events == null) + { events = new EventHandlerList(); } return events; @@ -41,44 +48,51 @@ private EventHandlerList Events { /// Support IHtml*3.AttachHandler public abstract void AttachEventHandler(string eventName, EventHandler eventHandler); - - public void AddHandler(object key, Delegate value) { + + public void AddHandler(object key, Delegate value) + { eventCount++; Events.AddHandler(key, value); OnEventHandlerAdded(); } - protected HtmlToClrEventProxy AddEventProxy(string eventName, EventHandler eventHandler) { - if (attachedEventList == null) { + protected HtmlToClrEventProxy AddEventProxy(string eventName, EventHandler eventHandler) + { + if (attachedEventList == null) + { attachedEventList = new Dictionary(); - } + } HtmlToClrEventProxy proxy = new HtmlToClrEventProxy(this, eventName, eventHandler); attachedEventList[eventHandler] = proxy; return proxy; } - public abstract UnsafeNativeMethods.IHTMLWindow2 AssociatedWindow { + public abstract UnsafeNativeMethods.IHTMLWindow2 AssociatedWindow + { get; } - + /// create connectionpoint cookie public abstract void ConnectToEvents(); /// Support IHtml*3.DetachEventHandler - public abstract void DetachEventHandler(string eventName, EventHandler eventHandler); - + public abstract void DetachEventHandler(string eventName, EventHandler eventHandler); + /// disconnect from connectionpoint cookie /// inheriting classes should override to disconnect from ConnectionPoint and call base. - public virtual void DisconnectFromEvents() { + public virtual void DisconnectFromEvents() + { - if (attachedEventList != null) { + if (attachedEventList != null) + { EventHandler[] events = new EventHandler[attachedEventList.Count]; - attachedEventList.Keys.CopyTo(events,0); - - foreach (EventHandler eh in events) { + attachedEventList.Keys.CopyTo(events, 0); + + foreach (EventHandler eh in events) + { HtmlToClrEventProxy proxy = attachedEventList[eh]; DetachEventHandler(proxy.EventName, eh); } @@ -89,17 +103,21 @@ public virtual void DisconnectFromEvents() { /// return the sender for events, usually the HtmlWindow, HtmlElement, HtmlDocument protected abstract object GetEventSender(); - - - public void Dispose() { + + + public void Dispose() + { Dispose(true); GC.SuppressFinalize(this); } - protected virtual void Dispose(bool disposing) { - if (disposing) { + protected virtual void Dispose(bool disposing) + { + if (disposing) + { DisconnectFromEvents(); - if (this.events != null) { + if (this.events != null) + { this.events.Dispose(); this.events = null; } @@ -108,52 +126,63 @@ protected virtual void Dispose(bool disposing) { public void FireEvent(object key, EventArgs e) { - + System.Delegate delegateToInvoke = (System.Delegate)Events[key]; - - if (delegateToInvoke != null) { - try { - delegateToInvoke.DynamicInvoke(GetEventSender(), e); + + if (delegateToInvoke != null) + { + try + { + delegateToInvoke.DynamicInvoke(GetEventSender(), e); } - catch (Exception ex) { + catch (Exception ex) + { // Note: this check is for the debugger, so we can catch exceptions in the debugger instead of // throwing a thread exception. if (NativeWindow.WndProcShouldBeDebuggable) { throw; } - else { + else + { Application.OnThreadException(ex); } } } } - protected virtual void OnEventHandlerAdded() { - ConnectToEvents(); + protected virtual void OnEventHandlerAdded() + { + ConnectToEvents(); } - protected virtual void OnEventHandlerRemoved() { - if (eventCount <=0) { + protected virtual void OnEventHandlerRemoved() + { + if (eventCount <= 0) + { DisconnectFromEvents(); eventCount = 0; } } - public void RemoveHandler(object key, Delegate value) { + public void RemoveHandler(object key, Delegate value) + { eventCount--; Events.RemoveHandler(key, value); OnEventHandlerRemoved(); } - protected HtmlToClrEventProxy RemoveEventProxy(EventHandler eventHandler) { - if (attachedEventList == null) { - return null; + protected HtmlToClrEventProxy RemoveEventProxy(EventHandler eventHandler) + { + if (attachedEventList == null) + { + return null; } - if (attachedEventList.ContainsKey(eventHandler)) { - HtmlToClrEventProxy proxy = attachedEventList[eventHandler] as HtmlToClrEventProxy; - attachedEventList.Remove(eventHandler); - return proxy; + if (attachedEventList.ContainsKey(eventHandler)) + { + HtmlToClrEventProxy proxy = attachedEventList[eventHandler] as HtmlToClrEventProxy; + attachedEventList.Remove(eventHandler); + return proxy; } return null; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlShimManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlShimManager.cs index 0a669fd998b..1925398bc50 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlShimManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlShimManager.cs @@ -2,13 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Collections.Generic; using System.Collections; using System.Diagnostics; - + /// /// HtmlShimManager - this class manages the shims for HtmlWindows, HtmlDocuments, and HtmlElements. /// essentially we need a long-lasting object to call back on events from the web browser, and the @@ -17,204 +18,250 @@ namespace System.Windows.Forms { /// When a HtmlWindow unloads we prune our list of corresponding document, window, and element shims. /// /// - internal sealed class HtmlShimManager :IDisposable { - - private Dictionary htmlWindowShims; - private Dictionary htmlElementShims; - private Dictionary htmlDocumentShims; - - internal HtmlShimManager() { - } - - /// AddDocumentShim - adds a HtmlDocumentShim to list of shims to manage - /// Can create a WindowShim as a side effect so it knows when to self prune from the list. - /// - public void AddDocumentShim(HtmlDocument doc) { - HtmlDocument.HtmlDocumentShim shim = null; - - if (htmlDocumentShims == null) { - htmlDocumentShims = new Dictionary(); - shim = new HtmlDocument.HtmlDocumentShim(doc); - htmlDocumentShims[doc] = shim; - } - else if (!htmlDocumentShims.ContainsKey(doc)) { - shim = new HtmlDocument.HtmlDocumentShim(doc); - htmlDocumentShims[doc] = shim; - } - if (shim != null) { - OnShimAdded(shim); - } - - } - - /// AddWindowShim - adds a HtmlWindowShim to list of shims to manage - /// - - public void AddWindowShim(HtmlWindow window) { - HtmlWindow.HtmlWindowShim shim = null; - if (htmlWindowShims == null) { - htmlWindowShims = new Dictionary(); - shim = new HtmlWindow.HtmlWindowShim(window); - htmlWindowShims[window] = shim; - } - else if (!htmlWindowShims.ContainsKey(window)) { - shim = new HtmlWindow.HtmlWindowShim(window); - htmlWindowShims[window] = shim; - } - if (shim != null) { - // strictly not necessary, but here for future use. - OnShimAdded(shim); - } + internal sealed class HtmlShimManager : IDisposable + { + + private Dictionary htmlWindowShims; + private Dictionary htmlElementShims; + private Dictionary htmlDocumentShims; + + internal HtmlShimManager() + { + } + + /// AddDocumentShim - adds a HtmlDocumentShim to list of shims to manage + /// Can create a WindowShim as a side effect so it knows when to self prune from the list. + /// + public void AddDocumentShim(HtmlDocument doc) + { + HtmlDocument.HtmlDocumentShim shim = null; + + if (htmlDocumentShims == null) + { + htmlDocumentShims = new Dictionary(); + shim = new HtmlDocument.HtmlDocumentShim(doc); + htmlDocumentShims[doc] = shim; + } + else if (!htmlDocumentShims.ContainsKey(doc)) + { + shim = new HtmlDocument.HtmlDocumentShim(doc); + htmlDocumentShims[doc] = shim; + } + if (shim != null) + { + OnShimAdded(shim); } - /// AddElementShim - adds a HtmlDocumentShim to list of shims to manage - /// Can create a WindowShim as a side effect so it knows when to self prune from the list. - /// - public void AddElementShim(HtmlElement element) { - HtmlElement.HtmlElementShim shim = null; + } - if (htmlElementShims == null) { - htmlElementShims = new Dictionary(); - shim = new HtmlElement.HtmlElementShim(element); - htmlElementShims[element] = shim; - } - else if (!htmlElementShims.ContainsKey(element)) { - shim = new HtmlElement.HtmlElementShim(element); - htmlElementShims[element] = shim; - } - if (shim != null) { - OnShimAdded(shim); - } - + /// AddWindowShim - adds a HtmlWindowShim to list of shims to manage + /// + + public void AddWindowShim(HtmlWindow window) + { + HtmlWindow.HtmlWindowShim shim = null; + if (htmlWindowShims == null) + { + htmlWindowShims = new Dictionary(); + shim = new HtmlWindow.HtmlWindowShim(window); + htmlWindowShims[window] = shim; } - - internal HtmlDocument.HtmlDocumentShim GetDocumentShim(HtmlDocument document) { - if (htmlDocumentShims == null) { - return null; - } - if (htmlDocumentShims.ContainsKey(document)) { - return htmlDocumentShims[document]; - } + else if (!htmlWindowShims.ContainsKey(window)) + { + shim = new HtmlWindow.HtmlWindowShim(window); + htmlWindowShims[window] = shim; + } + if (shim != null) + { + // strictly not necessary, but here for future use. + OnShimAdded(shim); + } + } + + /// AddElementShim - adds a HtmlDocumentShim to list of shims to manage + /// Can create a WindowShim as a side effect so it knows when to self prune from the list. + /// + public void AddElementShim(HtmlElement element) + { + HtmlElement.HtmlElementShim shim = null; + + if (htmlElementShims == null) + { + htmlElementShims = new Dictionary(); + shim = new HtmlElement.HtmlElementShim(element); + htmlElementShims[element] = shim; + } + else if (!htmlElementShims.ContainsKey(element)) + { + shim = new HtmlElement.HtmlElementShim(element); + htmlElementShims[element] = shim; + } + if (shim != null) + { + OnShimAdded(shim); + } + + } + + internal HtmlDocument.HtmlDocumentShim GetDocumentShim(HtmlDocument document) + { + if (htmlDocumentShims == null) + { return null; } - - internal HtmlElement.HtmlElementShim GetElementShim(HtmlElement element) { - if (htmlElementShims == null) { - return null; - } - if (htmlElementShims.ContainsKey(element)) { - return htmlElementShims[element]; - } + if (htmlDocumentShims.ContainsKey(document)) + { + return htmlDocumentShims[document]; + } + return null; + } + + internal HtmlElement.HtmlElementShim GetElementShim(HtmlElement element) + { + if (htmlElementShims == null) + { return null; } + if (htmlElementShims.ContainsKey(element)) + { + return htmlElementShims[element]; + } + return null; + } - internal HtmlWindow.HtmlWindowShim GetWindowShim(HtmlWindow window) { - if (htmlWindowShims == null) { - return null; - } - if (htmlWindowShims.ContainsKey(window)) { - return htmlWindowShims[window]; - } + internal HtmlWindow.HtmlWindowShim GetWindowShim(HtmlWindow window) + { + if (htmlWindowShims == null) + { return null; } + if (htmlWindowShims.ContainsKey(window)) + { + return htmlWindowShims[window]; + } + return null; + } - private void OnShimAdded(HtmlShim addedShim) { - - Debug.Assert(addedShim != null, "Why are we calling this with a null shim?"); - if (addedShim != null) { - if (!(addedShim is HtmlWindow.HtmlWindowShim)) { - // we need to add a window shim here for documents and elements - // so we can sync Window.Unload. The window shim itself will trap - // the unload event and call back on us on OnWindowUnloaded. When - // that happens we know we can free all our ptrs to COM. - AddWindowShim(new HtmlWindow(this, addedShim.AssociatedWindow)); - } + private void OnShimAdded(HtmlShim addedShim) + { + + Debug.Assert(addedShim != null, "Why are we calling this with a null shim?"); + if (addedShim != null) + { + if (!(addedShim is HtmlWindow.HtmlWindowShim)) + { + // we need to add a window shim here for documents and elements + // so we can sync Window.Unload. The window shim itself will trap + // the unload event and call back on us on OnWindowUnloaded. When + // that happens we know we can free all our ptrs to COM. + AddWindowShim(new HtmlWindow(this, addedShim.AssociatedWindow)); } } - /// - /// HtmlWindowShim calls back on us when it has unloaded the page. At this point we need to - /// walk through our lists and make sure we've cleaned up - /// - internal void OnWindowUnloaded(HtmlWindow unloadedWindow) { - Debug.Assert(unloadedWindow != null, "Why are we calling this with a null window?"); - if (unloadedWindow != null) { - // - // prune documents - // - if (htmlDocumentShims != null) { - HtmlDocument.HtmlDocumentShim[] shims = new HtmlDocument.HtmlDocumentShim[htmlDocumentShims.Count]; - htmlDocumentShims.Values.CopyTo(shims,0); - - foreach (HtmlDocument.HtmlDocumentShim shim in shims) { - if (shim.AssociatedWindow == unloadedWindow.NativeHtmlWindow) { - htmlDocumentShims.Remove(shim.Document); - shim.Dispose(); - } + } + /// + /// HtmlWindowShim calls back on us when it has unloaded the page. At this point we need to + /// walk through our lists and make sure we've cleaned up + /// + internal void OnWindowUnloaded(HtmlWindow unloadedWindow) + { + Debug.Assert(unloadedWindow != null, "Why are we calling this with a null window?"); + if (unloadedWindow != null) + { + // + // prune documents + // + if (htmlDocumentShims != null) + { + HtmlDocument.HtmlDocumentShim[] shims = new HtmlDocument.HtmlDocumentShim[htmlDocumentShims.Count]; + htmlDocumentShims.Values.CopyTo(shims, 0); + + foreach (HtmlDocument.HtmlDocumentShim shim in shims) + { + if (shim.AssociatedWindow == unloadedWindow.NativeHtmlWindow) + { + htmlDocumentShims.Remove(shim.Document); + shim.Dispose(); } } - // - // prune elements - // - if (htmlElementShims != null) { - HtmlElement.HtmlElementShim[] shims = new HtmlElement.HtmlElementShim[htmlElementShims.Count]; - htmlElementShims.Values.CopyTo(shims,0); - - foreach (HtmlElement.HtmlElementShim shim in shims) { - if (shim.AssociatedWindow == unloadedWindow.NativeHtmlWindow) { - htmlElementShims.Remove(shim.Element); - shim.Dispose(); - } + } + // + // prune elements + // + if (htmlElementShims != null) + { + HtmlElement.HtmlElementShim[] shims = new HtmlElement.HtmlElementShim[htmlElementShims.Count]; + htmlElementShims.Values.CopyTo(shims, 0); + + foreach (HtmlElement.HtmlElementShim shim in shims) + { + if (shim.AssociatedWindow == unloadedWindow.NativeHtmlWindow) + { + htmlElementShims.Remove(shim.Element); + shim.Dispose(); } } + } - // - // prune the particular window from the list. - // - if (htmlWindowShims != null) { - if (htmlWindowShims.ContainsKey(unloadedWindow)) { - HtmlWindow.HtmlWindowShim shim = htmlWindowShims[unloadedWindow]; - htmlWindowShims.Remove(unloadedWindow); - shim.Dispose(); - } + // + // prune the particular window from the list. + // + if (htmlWindowShims != null) + { + if (htmlWindowShims.ContainsKey(unloadedWindow)) + { + HtmlWindow.HtmlWindowShim shim = htmlWindowShims[unloadedWindow]; + htmlWindowShims.Remove(unloadedWindow); + shim.Dispose(); } } } + } - public void Dispose() { - Dispose(true); - } + public void Dispose() + { + Dispose(true); + } - private void Dispose(bool disposing) { - if (disposing) { + private void Dispose(bool disposing) + { + if (disposing) + { - if (htmlElementShims != null){ - foreach (HtmlElement.HtmlElementShim shim in htmlElementShims.Values) { - shim.Dispose(); - } + if (htmlElementShims != null) + { + foreach (HtmlElement.HtmlElementShim shim in htmlElementShims.Values) + { + shim.Dispose(); } - if (htmlDocumentShims != null) { - foreach (HtmlDocument.HtmlDocumentShim shim in htmlDocumentShims.Values) { - shim.Dispose(); - } + } + if (htmlDocumentShims != null) + { + foreach (HtmlDocument.HtmlDocumentShim shim in htmlDocumentShims.Values) + { + shim.Dispose(); } + } - if (htmlWindowShims != null) { - foreach (HtmlWindow.HtmlWindowShim shim in htmlWindowShims.Values) { - shim.Dispose(); - } + if (htmlWindowShims != null) + { + foreach (HtmlWindow.HtmlWindowShim shim in htmlWindowShims.Values) + { + shim.Dispose(); } - htmlWindowShims = null; - htmlDocumentShims = null; - htmlWindowShims = null; - - } + htmlWindowShims = null; + htmlDocumentShims = null; + htmlWindowShims = null; + + } - ~HtmlShimManager() { - Dispose(false); - } - + } + ~HtmlShimManager() + { + Dispose(false); + } + + - - } - } + } +} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlToClrEventProxy.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlToClrEventProxy.cs index 6aa8a04b69b..914e7d0fedb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlToClrEventProxy.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlToClrEventProxy.cs @@ -19,8 +19,9 @@ internal class HtmlToClrEventProxy : IReflect private IReflect typeIReflectImplementation; private object sender = null; private string eventName; - - public HtmlToClrEventProxy(object sender, string eventName, EventHandler eventHandler) { + + public HtmlToClrEventProxy(object sender, string eventName, EventHandler eventHandler) + { this.eventHandler = eventHandler; this.eventName = eventName; @@ -28,75 +29,94 @@ public HtmlToClrEventProxy(object sender, string eventName, EventHandler eventHa typeIReflectImplementation = htmlToClrEventProxyType as IReflect; } - public string EventName { + public string EventName + { get { return eventName; } } - + [DispId(0)] - public void OnHtmlEvent() { + public void OnHtmlEvent() + { InvokeClrEvent(); } - private void InvokeClrEvent() { - if (eventHandler != null) { + private void InvokeClrEvent() + { + if (eventHandler != null) + { eventHandler(sender, EventArgs.Empty); } } -#region IReflect - - Type IReflect.UnderlyingSystemType { - get { + #region IReflect + + Type IReflect.UnderlyingSystemType + { + get + { return typeIReflectImplementation.UnderlyingSystemType; } } // Methods - System.Reflection.FieldInfo IReflect.GetField(string name, System.Reflection.BindingFlags bindingAttr) { + System.Reflection.FieldInfo IReflect.GetField(string name, System.Reflection.BindingFlags bindingAttr) + { return typeIReflectImplementation.GetField(name, bindingAttr); } - System.Reflection.FieldInfo[] IReflect.GetFields(System.Reflection.BindingFlags bindingAttr) { + System.Reflection.FieldInfo[] IReflect.GetFields(System.Reflection.BindingFlags bindingAttr) + { return typeIReflectImplementation.GetFields(bindingAttr); } - System.Reflection.MemberInfo[] IReflect.GetMember(string name, System.Reflection.BindingFlags bindingAttr) { + System.Reflection.MemberInfo[] IReflect.GetMember(string name, System.Reflection.BindingFlags bindingAttr) + { return typeIReflectImplementation.GetMember(name, bindingAttr); } - System.Reflection.MemberInfo[] IReflect.GetMembers(System.Reflection.BindingFlags bindingAttr){ + System.Reflection.MemberInfo[] IReflect.GetMembers(System.Reflection.BindingFlags bindingAttr) + { return typeIReflectImplementation.GetMembers(bindingAttr); } - System.Reflection.MethodInfo IReflect.GetMethod(string name, System.Reflection.BindingFlags bindingAttr) { + System.Reflection.MethodInfo IReflect.GetMethod(string name, System.Reflection.BindingFlags bindingAttr) + { return typeIReflectImplementation.GetMethod(name, bindingAttr); } - System.Reflection.MethodInfo IReflect.GetMethod(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type[] types, System.Reflection.ParameterModifier[] modifiers) { + System.Reflection.MethodInfo IReflect.GetMethod(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type[] types, System.Reflection.ParameterModifier[] modifiers) + { return typeIReflectImplementation.GetMethod(name, bindingAttr, binder, types, modifiers); } - System.Reflection.MethodInfo[] IReflect.GetMethods(System.Reflection.BindingFlags bindingAttr) { + System.Reflection.MethodInfo[] IReflect.GetMethods(System.Reflection.BindingFlags bindingAttr) + { return typeIReflectImplementation.GetMethods(bindingAttr); } - System.Reflection.PropertyInfo[] IReflect.GetProperties(System.Reflection.BindingFlags bindingAttr) { + System.Reflection.PropertyInfo[] IReflect.GetProperties(System.Reflection.BindingFlags bindingAttr) + { return typeIReflectImplementation.GetProperties(bindingAttr); } - System.Reflection.PropertyInfo IReflect.GetProperty(string name, System.Reflection.BindingFlags bindingAttr) { + System.Reflection.PropertyInfo IReflect.GetProperty(string name, System.Reflection.BindingFlags bindingAttr) + { return typeIReflectImplementation.GetProperty(name, bindingAttr); } - System.Reflection.PropertyInfo IReflect.GetProperty(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type returnType, Type[] types, System.Reflection.ParameterModifier[] modifiers) { + System.Reflection.PropertyInfo IReflect.GetProperty(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type returnType, Type[] types, System.Reflection.ParameterModifier[] modifiers) + { return typeIReflectImplementation.GetProperty(name, bindingAttr, binder, returnType, types, modifiers); } // InvokeMember: // If we get a call for DISPID=0, fire the CLR event. // - object IReflect.InvokeMember(string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters) { + object IReflect.InvokeMember(string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters) + { // - if (name == "[DISPID=0]") { + if (name == "[DISPID=0]") + { // we know we're getting called back to fire the event - translate this now into a CLR event. OnHtmlEvent(); // since there's no return value for void, return null. return null; } - else { + else + { return typeIReflectImplementation.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindow.cs index 724a957cc86..6249f88c778 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindow.cs @@ -181,7 +181,7 @@ public string StatusBarText public Uri Url { - get + get { UnsafeNativeMethods.IHTMLLocation iHtmlLocation = this.NativeHtmlWindow.GetLocation(); string stringLocation = (iHtmlLocation == null) ? "" : iHtmlLocation.GetHref(); @@ -447,7 +447,7 @@ public void onscroll(UnsafeNativeMethods.IHTMLEventObj evtObj) FireEvent(HtmlWindow.EventScroll, e); } - public void onresize(UnsafeNativeMethods.IHTMLEventObj evtObj) + public void onresize(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); FireEvent(HtmlWindow.EventResize, e); @@ -460,9 +460,9 @@ public bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj) } public void onbeforeunload(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onbeforeprint(UnsafeNativeMethods.IHTMLEventObj evtObj) { } - + public void onafterprint(UnsafeNativeMethods.IHTMLEventObj evtObj) { } } @@ -523,7 +523,7 @@ public override void ConnectToEvents() new HTMLWindowEvents2(htmlWindow), typeof(UnsafeNativeMethods.DHTMLWindowEvents2), /*throwException*/ false); - if (!cookie.Connected) + if (!cookie.Connected) { cookie = null; } @@ -576,7 +576,7 @@ public void OnWindowUnload() } } - #region operators + #region operators [SuppressMessage("Microsoft.Design", "CA1046:DoNotOverrideOperatorEqualsOnReferenceTypes")] public static bool operator ==(HtmlWindow left, HtmlWindow right) @@ -629,7 +629,7 @@ public override bool Equals(object obj) { return (this == (HtmlWindow)obj); } - #endregion + #endregion } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindowCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindowCollection.cs index 14cda4e1293..594b3b07595 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindowCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindowCollection.cs @@ -12,24 +12,30 @@ public class HtmlWindowCollection : ICollection { private UnsafeNativeMethods.IHTMLFramesCollection2 htmlFramesCollection2; private HtmlShimManager shimManager; - - internal HtmlWindowCollection(HtmlShimManager shimManager, UnsafeNativeMethods.IHTMLFramesCollection2 collection) { + + internal HtmlWindowCollection(HtmlShimManager shimManager, UnsafeNativeMethods.IHTMLFramesCollection2 collection) + { this.htmlFramesCollection2 = collection; this.shimManager = shimManager; - + Debug.Assert(this.NativeHTMLFramesCollection2 != null, "The window collection object should implement IHTMLFramesCollection2"); } - private UnsafeNativeMethods.IHTMLFramesCollection2 NativeHTMLFramesCollection2 { - get { + private UnsafeNativeMethods.IHTMLFramesCollection2 NativeHTMLFramesCollection2 + { + get + { return this.htmlFramesCollection2; } } - public HtmlWindow this[int index] { - get { - if (index < 0 || index >= Count) { + public HtmlWindow this[int index] + { + get + { + if (index < 0 || index >= Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidBoundArgument, nameof(index), index, 0, Count - 1)); } @@ -40,15 +46,19 @@ public HtmlWindow this[int index] { } } - public HtmlWindow this[string windowId] { - get { + public HtmlWindow this[string windowId] + { + get + { object oWindowId = (object)windowId; UnsafeNativeMethods.IHTMLWindow2 htmlWindow2 = null; - try { + try + { htmlWindow2 = this.htmlFramesCollection2.Item(ref oWindowId) as UnsafeNativeMethods.IHTMLWindow2; } - catch (COMException) { + catch (COMException) + { throw new ArgumentException(string.Format(SR.InvalidArgument, nameof(windowId), windowId), nameof(windowId)); } return (htmlWindow2 != null) ? new HtmlWindow(shimManager, htmlWindow2) : null; @@ -58,35 +68,44 @@ public HtmlWindow this[string windowId] { /// /// Returns the total number of elements in the collection. /// - public int Count { - get { + public int Count + { + get + { return this.NativeHTMLFramesCollection2.GetLength(); } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return false; } } - - object ICollection.SyncRoot { - get { + + object ICollection.SyncRoot + { + get + { return this; } } - void ICollection.CopyTo(Array dest, int index) { + void ICollection.CopyTo(Array dest, int index) + { int count = this.Count; - for (int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) + { dest.SetValue(this[i], index++); } } - public IEnumerator GetEnumerator() { + public IEnumerator GetEnumerator() + { HtmlWindow[] htmlWindows = new HtmlWindow[this.Count]; ((ICollection)this).CopyTo(htmlWindows, 0); - + return htmlWindows.GetEnumerator(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/IMessageModifyAndFilter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/IMessageModifyAndFilter.cs index 081cb42d699..c129dcaeb49 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/IMessageModifyAndFilter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/IMessageModifyAndFilter.cs @@ -10,4 +10,3 @@ internal interface IMessageModifyAndFilter : IMessageFilter { } } - \ No newline at end of file diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ImageIndexConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ImageIndexConverter.cs index e0993df7574..13a8d89528d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ImageIndexConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ImageIndexConverter.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System.Collections; @@ -17,15 +18,18 @@ namespace System.Windows.Forms { /// ImageIndexConverter is a class that can be used to convert /// image index values one data type to another. /// - public class ImageIndexConverter : Int32Converter { + public class ImageIndexConverter : Int32Converter + { - private string parentImageListProperty = "Parent"; - - protected virtual bool IncludeNoneAsStandardValue { - get { + private string parentImageListProperty = "Parent"; + + protected virtual bool IncludeNoneAsStandardValue + { + get + { return true; } - } + } /// /// this is the property to look at when there is no ImageList property @@ -33,23 +37,28 @@ protected virtual bool IncludeNoneAsStandardValue { /// on the ToolBarButton.Parent property. In ToolStripItem, the ImageList is on /// the ToolStripItem.Owner property. /// - internal string ParentImageListProperty { - get { + internal string ParentImageListProperty + { + get + { return parentImageListProperty; } - set { + set + { parentImageListProperty = value; } } - + /// /// /// Converts the given value object to a 32-bit signed integer object. /// /// - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + { string stringValue = value as string; - if (stringValue != null && string.Compare(stringValue, SR.toStringNone, true, culture) == 0) { + if (stringValue != null && string.Compare(stringValue, SR.toStringNone, true, culture) == 0) + { return -1; } @@ -64,12 +73,15 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) { + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == null) + { throw new ArgumentNullException(nameof(destinationType)); } - if (destinationType == typeof(string) && value is int && ((int)value) == -1) { + if (destinationType == typeof(string) && value is int && ((int)value) == -1) + { return SR.toStringNone; } @@ -82,32 +94,40 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul /// will return null if the data type does not support a /// standard set of values. /// - public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { - if (context != null && context.Instance != null) { + public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) + { + if (context != null && context.Instance != null) + { object instance = context.Instance; - + PropertyDescriptor imageListProp = ImageListUtils.GetImageListProperty(context.PropertyDescriptor, ref instance); - while (instance != null && imageListProp == null) { + while (instance != null && imageListProp == null) + { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(instance); - foreach (PropertyDescriptor prop in props) { - if (typeof(ImageList).IsAssignableFrom(prop.PropertyType)) { + foreach (PropertyDescriptor prop in props) + { + if (typeof(ImageList).IsAssignableFrom(prop.PropertyType)) + { imageListProp = prop; break; } } - if (imageListProp == null) { + if (imageListProp == null) + { // We didn't find the image list in this component. See if the // component has a "parent" property. If so, walk the tree... // PropertyDescriptor parentProp = props[ParentImageListProperty]; - if (parentProp != null) { + if (parentProp != null) + { instance = parentProp.GetValue(instance); } - else { + else + { // Stick a fork in us, we're done. // instance = null; @@ -115,39 +135,46 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex } } - if (imageListProp != null) { + if (imageListProp != null) + { ImageList imageList = (ImageList)imageListProp.GetValue(instance); - if (imageList != null) { - + if (imageList != null) + { + // Create array to contain standard values // object[] values; int nImages = imageList.Images.Count; - if (IncludeNoneAsStandardValue) { + if (IncludeNoneAsStandardValue) + { values = new object[nImages + 1]; values[nImages] = -1; } - else { + else + { values = new object[nImages]; } - - + + // Fill in the array // - for (int i = 0; i < nImages; i++) { + for (int i = 0; i < nImages; i++) + { values[i] = i; } - + return new StandardValuesCollection(values); } } } - if (IncludeNoneAsStandardValue) { - return new StandardValuesCollection(new object[] {-1}); + if (IncludeNoneAsStandardValue) + { + return new StandardValuesCollection(new object[] { -1 }); } - else { + else + { return new StandardValuesCollection(new object[0]); } } @@ -160,7 +187,8 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex /// then there are other valid values besides the list of /// standard values GetStandardValues provides. /// - public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { + public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) + { return false; } @@ -168,7 +196,8 @@ public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) /// Determines if this object supports a standard set of values /// that can be picked from a list. /// - public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { + public override bool GetStandardValuesSupported(ITypeDescriptorContext context) + { return true; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ImageKeyConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ImageKeyConverter.cs index 5b033679f2c..dfdf2f1fa26 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ImageKeyConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ImageKeyConverter.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System.Collections; @@ -18,15 +19,18 @@ namespace System.Windows.Forms { /// ImageIndexConverter is a class that can be used to convert /// image index values one data type to another. /// - public class ImageKeyConverter : StringConverter { + public class ImageKeyConverter : StringConverter + { - private string parentImageListProperty = "Parent"; - - protected virtual bool IncludeNoneAsStandardValue { - get { + private string parentImageListProperty = "Parent"; + + protected virtual bool IncludeNoneAsStandardValue + { + get + { return true; } - } + } /// /// this is the property to look at when there is no ImageList property @@ -34,11 +38,14 @@ protected virtual bool IncludeNoneAsStandardValue { /// on the ToolBarButton.Parent property. In ToolStripItem, the ImageList is on /// the ToolStripItem.Owner property. /// - internal string ParentImageListProperty { - get { + internal string ParentImageListProperty + { + get + { return parentImageListProperty; } - set { + set + { parentImageListProperty = value; } } @@ -46,8 +53,10 @@ internal string ParentImageListProperty { /// Gets a value indicating whether this converter can convert an object in the /// given source type to a string using the specified context. /// - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { - if (sourceType == typeof(string)) { + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + { + if (sourceType == typeof(string)) + { return true; } return base.CanConvertFrom(context, sourceType); @@ -56,18 +65,21 @@ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceT /// /// Converts the specified value object to a string object. /// - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - if (value is string) { + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + { + if (value is string) + { return (string)value; } - if (value == null) { + if (value == null) + { return ""; } return base.ConvertFrom(context, culture, value); } - + /// /// Converts the given object to another type. The most common types to convert /// are to and from a string object. The default implementation will make a call @@ -75,53 +87,65 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) { + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == null) + { throw new ArgumentNullException(nameof(destinationType)); } - if (destinationType == typeof(string) && value != null && value is string && ((string)value).Length == 0) { + if (destinationType == typeof(string) && value != null && value is string && ((string)value).Length == 0) + { return SR.toStringNone; } - else if (destinationType == typeof(string) && (value == null)) { + else if (destinationType == typeof(string) && (value == null)) + { return SR.toStringNone; } return base.ConvertTo(context, culture, value, destinationType); } - + /// /// Retrieves a collection containing a set of standard values /// for the data type this validator is designed for. This /// will return null if the data type does not support a /// standard set of values. /// - public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { - if (context != null && context.Instance != null) { - object instance = context.Instance; + public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) + { + if (context != null && context.Instance != null) + { + object instance = context.Instance; PropertyDescriptor imageListProp = ImageListUtils.GetImageListProperty(context.PropertyDescriptor, ref instance); - while (instance != null && imageListProp == null) { + while (instance != null && imageListProp == null) + { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(instance); - foreach (PropertyDescriptor prop in props) { - if (typeof(ImageList).IsAssignableFrom(prop.PropertyType)) { + foreach (PropertyDescriptor prop in props) + { + if (typeof(ImageList).IsAssignableFrom(prop.PropertyType)) + { imageListProp = prop; break; } } - if (imageListProp == null) { + if (imageListProp == null) + { // We didn't find the image list in this component. See if the // component has a "parent" property. If so, walk the tree... // PropertyDescriptor parentProp = props[ParentImageListProperty]; - if (parentProp != null) { + if (parentProp != null) + { instance = parentProp.GetValue(instance); } - else { + else + { // Stick a fork in us, we're done. // instance = null; @@ -129,45 +153,52 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex } } - if (imageListProp != null) { + if (imageListProp != null) + { ImageList imageList = (ImageList)imageListProp.GetValue(instance); - if (imageList != null) { - + if (imageList != null) + { + // Create array to contain standard values // object[] values; int nImages = imageList.Images.Count; - if (IncludeNoneAsStandardValue) { + if (IncludeNoneAsStandardValue) + { values = new object[nImages + 1]; values[nImages] = string.Empty; } - else { + else + { values = new object[nImages]; } - - + + // Fill in the array // StringCollection imageKeys = imageList.Images.Keys; - for (int i = 0; i < imageKeys.Count; i++) { + for (int i = 0; i < imageKeys.Count; i++) + { if ((imageKeys[i] != null) && (imageKeys[i].Length != 0)) values[i] = imageKeys[i]; } - + return new StandardValuesCollection(values); } } } - if (IncludeNoneAsStandardValue) { - return new StandardValuesCollection(new object[] {""}); + if (IncludeNoneAsStandardValue) + { + return new StandardValuesCollection(new object[] { "" }); } - else { + else + { return new StandardValuesCollection(new object[0]); } } - + /// /// Determines if the list of standard values returned from /// GetStandardValues is an exclusive list. If the list @@ -176,7 +207,8 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex /// then there are other valid values besides the list of /// standard values GetStandardValues provides. /// - public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { + public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) + { return true; } @@ -184,8 +216,9 @@ public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) /// Determines if this object supports a standard set of values /// that can be picked from a list. /// - public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { - return true; + public override bool GetStandardValuesSupported(ITypeDescriptorContext context) + { + return true; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ImageLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ImageLayout.cs index 69d243525db..cc1517fb949 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ImageLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ImageLayout.cs @@ -34,4 +34,4 @@ public enum ImageLayout /// Zoom, } -} +} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs index 0286d525919..e948ee4ab4b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.InteropServices; using System.ComponentModel; using System.ComponentModel.Design; @@ -10,8 +11,8 @@ namespace System.Windows.Forms { using System; using System.Collections.Specialized; using System.Collections; - using System.Drawing; - using System.Drawing.Imaging; + using System.Drawing; + using System.Drawing.Imaging; using System.Drawing.Design; using System.Windows.Forms; using System.Windows.Forms.Design; @@ -36,11 +37,12 @@ namespace System.Windows.Forms { DesignerSerializer("System.Windows.Forms.Design.ImageListCodeDomSerializer, " + AssemblyRef.SystemDesign, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + AssemblyRef.SystemDesign), SRDescription(nameof(SR.DescriptionImageList)) ] - public sealed class ImageList : Component { + public sealed class ImageList : Component + { // gpr: Copied from Icon private static Color fakeTransparencyColor = Color.FromArgb(0x0d, 0x0b, 0x0c); - private static Size DefaultImageSize = new Size(16, 16); + private static Size DefaultImageSize = new Size(16, 16); private const int INITIAL_CAPACITY = 4; private const int GROWBY = 4; @@ -77,9 +79,12 @@ public sealed class ImageList : Component { /// Creates a new ImageList Control with a default image size of 16x16 /// pixels /// - public ImageList() { // DO NOT DELETE -- AUTOMATION BP 1 - if (!isScalingInitialized) { - if (DpiHelper.IsScalingRequired) { + public ImageList() + { // DO NOT DELETE -- AUTOMATION BP 1 + if (!isScalingInitialized) + { + if (DpiHelper.IsScalingRequired) + { maxImageWidth = DpiHelper.LogicalToDeviceUnitsX(MAX_DIMENSION); maxImageHeight = DpiHelper.LogicalToDeviceUnitsY(MAX_DIMENSION); } @@ -91,8 +96,10 @@ public ImageList() { // DO NOT DELETE -- AUTOMATION BP 1 /// Creates a new ImageList Control with a default image size of 16x16 /// pixels and adds the ImageList to the passed in container. /// - public ImageList(IContainer container) : this() { - if (container == null) { + public ImageList(IContainer container) : this() + { + if (container == null) + { throw new ArgumentNullException(nameof(container)); } @@ -102,29 +109,35 @@ public ImageList(IContainer container) : this() { // This class is for classes that want to support both an ImageIndex // and ImageKey. We want to toggle between using keys or indexes. // Default is to use the integer index. - internal class Indexer { + internal class Indexer + { private string key = string.Empty; private int index = -1; private bool useIntegerIndex = true; private ImageList imageList = null; - public virtual ImageList ImageList { + public virtual ImageList ImageList + { get { return imageList; } set { imageList = value; } } - public virtual string Key { + public virtual string Key + { get { return key; } - set { + set + { index = -1; key = (value == null ? string.Empty : value); useIntegerIndex = false; } } - public virtual int Index { + public virtual int Index + { get { return index; } - set { + set + { key = string.Empty; index = value; useIntegerIndex = true; @@ -132,12 +145,16 @@ public virtual int Index { } - public virtual int ActualIndex { - get { - if (useIntegerIndex) { + public virtual int ActualIndex + { + get + { + if (useIntegerIndex) + { return Index; } - else if (ImageList != null) { + else if (ImageList != null) + { return ImageList.Images.IndexOfKey(Key); } @@ -153,33 +170,40 @@ public virtual int ActualIndex { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ImageListColorDepthDescr)) ] - public ColorDepth ColorDepth { - get { + public ColorDepth ColorDepth + { + get + { return colorDepth; } - set { + set + { // ColorDepth is not conitguous - list the members instead. - if (!ClientUtils.IsEnumValid_NotSequential(value, + if (!ClientUtils.IsEnumValid_NotSequential(value, (int)value, (int)ColorDepth.Depth4Bit, (int)ColorDepth.Depth8Bit, (int)ColorDepth.Depth16Bit, (int)ColorDepth.Depth24Bit, - (int)ColorDepth.Depth32Bit)) { + (int)ColorDepth.Depth32Bit)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ColorDepth)); } - if (colorDepth != value) { + if (colorDepth != value) + { colorDepth = value; PerformRecreateHandle(nameof(ColorDepth)); } } } - private bool ShouldSerializeColorDepth() { - return (Images.Count==0); + private bool ShouldSerializeColorDepth() + { + return (Images.Count == 0); } - private void ResetColorDepth() { + private void ResetColorDepth() + { ColorDepth = ColorDepth.Depth8Bit; } @@ -192,9 +216,12 @@ private void ResetColorDepth() { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ImageListHandleDescr)) ] - public IntPtr Handle { - get { - if (nativeImageList == null) { + public IntPtr Handle + { + get + { + if (nativeImageList == null) + { CreateHandle(); } return nativeImageList.Handle; @@ -209,7 +236,8 @@ public IntPtr Handle { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ImageListHandleCreatedDescr)) ] - public bool HandleCreated { + public bool HandleCreated + { get { return nativeImageList != null; } } @@ -220,8 +248,10 @@ public bool HandleCreated { SRDescription(nameof(SR.ImageListImagesDescr)), MergableProperty(false) ] - public ImageCollection Images { - get { + public ImageCollection Images + { + get + { if (imageCollection == null) imageCollection = new ImageCollection(this); return imageCollection; @@ -236,12 +266,16 @@ public ImageCollection Images { Localizable(true), SRDescription(nameof(SR.ImageListSizeDescr)) ] - public Size ImageSize { - get { + public Size ImageSize + { + get + { return imageSize; } - set { - if (value.IsEmpty) { + set + { + if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.InvalidArgument, nameof(ImageSize), "Size.Empty"), nameof(value)); } @@ -249,23 +283,27 @@ public Size ImageSize { // based on image size x bpp. Restrict this to a reasonable maximum // to keep people's systems from crashing. // - if (value.Width <= 0 || value.Width > maxImageWidth) { + if (value.Width <= 0 || value.Width > maxImageWidth) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidBoundArgument, "ImageSize.Width", value.Width, 1, maxImageWidth)); } - if (value.Height <= 0 || value.Height > maxImageHeight) { + if (value.Height <= 0 || value.Height > maxImageHeight) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidBoundArgument, "ImageSize.Height", value.Height, 1, maxImageHeight)); } - if (imageSize.Width != value.Width || imageSize.Height != value.Height) { + if (imageSize.Width != value.Width || imageSize.Height != value.Height) + { imageSize = new Size(value.Width, value.Height); PerformRecreateHandle(nameof(ImageSize)); } } } - private bool ShouldSerializeImageSize() { - return (Images.Count==0); + private bool ShouldSerializeImageSize() + { + return (Images.Count == 0); } /// @@ -276,8 +314,10 @@ private bool ShouldSerializeImageSize() { DefaultValue(null), SRDescription(nameof(SR.ImageListImageStreamDescr)) ] - public ImageListStreamer ImageStream { - get { + public ImageListStreamer ImageStream + { + get + { if (Images.Empty) return null; @@ -285,39 +325,45 @@ public ImageListStreamer ImageStream { // ImageListStreamer will do it for us. return new ImageListStreamer(this); } - set { - if (value != null) { + set + { + if (value != null) + { NativeImageList himl = value.GetNativeImageList(); - if (himl != null && himl != this.nativeImageList) { + if (himl != null && himl != this.nativeImageList) + { bool recreatingHandle = this.HandleCreated;//We only need to fire RecreateHandle if there was a previous handle DestroyHandle(); originals = null; this.nativeImageList = new NativeImageList(SafeNativeMethods.ImageList_Duplicate(new HandleRef(himl, himl.Handle))); int x, y; - if(SafeNativeMethods.ImageList_GetIconSize(new HandleRef(this, this.nativeImageList.Handle), out x, out y)) { - imageSize = new Size(x,y); + if (SafeNativeMethods.ImageList_GetIconSize(new HandleRef(this, this.nativeImageList.Handle), out x, out y)) + { + imageSize = new Size(x, y); } // need to get the image bpp NativeMethods.IMAGEINFO imageInfo = new NativeMethods.IMAGEINFO(); // review? do I need to delete the mask and image? - if(SafeNativeMethods.ImageList_GetImageInfo(new HandleRef(this, this.nativeImageList.Handle), 0, imageInfo)) { + if (SafeNativeMethods.ImageList_GetImageInfo(new HandleRef(this, this.nativeImageList.Handle), 0, imageInfo)) + { NativeMethods.BITMAP bmp = new NativeMethods.BITMAP(); UnsafeNativeMethods.GetObject(new HandleRef(null, imageInfo.hbmImage), Marshal.SizeOf(bmp), bmp); - switch(bmp.bmBitsPixel) { + switch (bmp.bmBitsPixel) + { case 4: - colorDepth = ColorDepth.Depth4Bit; + colorDepth = ColorDepth.Depth4Bit; break; case 8: - colorDepth = ColorDepth.Depth8Bit; + colorDepth = ColorDepth.Depth8Bit; break; case 16: - colorDepth = ColorDepth.Depth16Bit; + colorDepth = ColorDepth.Depth16Bit; break; case 24: - colorDepth = ColorDepth.Depth24Bit; + colorDepth = ColorDepth.Depth24Bit; break; case 32: - colorDepth = ColorDepth.Depth32Bit; + colorDepth = ColorDepth.Depth32Bit; break; default: Debug.Fail("Unknown color depth"); @@ -326,7 +372,8 @@ public ImageListStreamer ImageStream { } Images.ResetKeys(); - if (recreatingHandle) { + if (recreatingHandle) + { OnRecreateHandle(EventArgs.Empty); } } @@ -348,11 +395,14 @@ public ImageListStreamer ImageStream { DefaultValue(null), TypeConverter(typeof(StringConverter)), ] - public object Tag { - get { + public object Tag + { + get + { return userData; } - set { + set + { userData = value; } } @@ -364,18 +414,22 @@ public object Tag { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ImageListTransparentColorDescr)) ] - public Color TransparentColor { - get { + public Color TransparentColor + { + get + { return transparentColor; } - set { + set + { transparentColor = value; } } // Whether to use the transparent color, or rely on alpha instead - private bool UseTransparentColor { - get { return TransparentColor.A > 0;} + private bool UseTransparentColor + { + get { return TransparentColor.A > 0; } } @@ -383,12 +437,14 @@ private bool UseTransparentColor { Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), SRDescription(nameof(SR.ImageListOnRecreateHandleDescr)) ] - public event EventHandler RecreateHandle { + public event EventHandler RecreateHandle + { add => recreateHandler += value; remove => recreateHandler -= value; } - internal event EventHandler ChangeHandle { + internal event EventHandler ChangeHandle + { add => changeHandler += value; remove => changeHandler -= value; } @@ -396,50 +452,57 @@ internal event EventHandler ChangeHandle { //Creates a bitmap from the original image source.. // - - - private Bitmap CreateBitmap(Original original, out bool ownsBitmap) { + + + private Bitmap CreateBitmap(Original original, out bool ownsBitmap) + { Color transparent = transparentColor; ownsBitmap = false; if ((original.options & OriginalOptions.CustomTransparentColor) != 0) transparent = original.customTransparentColor; Bitmap bitmap; - if (original.image is Bitmap) { - bitmap = (Bitmap) original.image; + if (original.image is Bitmap) + { + bitmap = (Bitmap)original.image; } - else if (original.image is Icon) { + else if (original.image is Icon) + { bitmap = ((Icon)original.image).ToBitmap(); ownsBitmap = true; } - else { + else + { bitmap = new Bitmap((Image)original.image); ownsBitmap = true; } - if (transparent.A > 0) { + if (transparent.A > 0) + { // ImageList_AddMasked doesn't work on high color bitmaps, // so we always create the mask ourselves Bitmap source = bitmap; - bitmap = (Bitmap) bitmap.Clone(); + bitmap = (Bitmap)bitmap.Clone(); bitmap.MakeTransparent(transparent); - if(ownsBitmap) + if (ownsBitmap) source.Dispose(); ownsBitmap = true; } Size size = bitmap.Size; - if ((original.options & OriginalOptions.ImageStrip) != 0) { + if ((original.options & OriginalOptions.ImageStrip) != 0) + { // strip width must be a positive multiple of image list width if (size.Width == 0 || (size.Width % imageSize.Width) != 0) throw new ArgumentException(SR.ImageListStripBadWidth, "original"); if (size.Height != imageSize.Height) throw new ArgumentException(SR.ImageListImageTooShort, "original"); } - else if (!size.Equals(ImageSize)) { + else if (!size.Equals(ImageSize)) + { Bitmap source = bitmap; bitmap = new Bitmap(source, ImageSize); - if(ownsBitmap) + if (ownsBitmap) source.Dispose(); ownsBitmap = true; } @@ -447,21 +510,28 @@ private Bitmap CreateBitmap(Original original, out bool ownsBitmap) { } - private int AddIconToHandle(Original original, Icon icon) { - try { + private int AddIconToHandle(Original original, Icon icon) + { + try + { Debug.Assert(HandleCreated, "Calling AddIconToHandle when there is no handle"); int index = SafeNativeMethods.ImageList_ReplaceIcon(new HandleRef(this, Handle), -1, new HandleRef(icon, icon.Handle)); - if (index == -1) throw new InvalidOperationException(SR.ImageListAddFailed); + if (index == -1) + throw new InvalidOperationException(SR.ImageListAddFailed); return index; - } finally { - if((original.options & OriginalOptions.OwnsImage) != 0) { /// this is to handle the case were we clone the icon (see WHY WHY WHY below) + } + finally + { + if ((original.options & OriginalOptions.OwnsImage) != 0) + { /// this is to handle the case were we clone the icon (see WHY WHY WHY below) icon.Dispose(); } } } // Adds bitmap to the Imagelist handle... // - private int AddToHandle(Original original, Bitmap bitmap) { + private int AddToHandle(Original original, Bitmap bitmap) + { Debug.Assert(HandleCreated, "Calling AddToHandle when there is no handle"); IntPtr hMask = ControlPaint.CreateHBitmapTransparencyMask(bitmap); // Calls GDI to create Bitmap. @@ -470,7 +540,8 @@ private int AddToHandle(Original original, Bitmap bitmap) { SafeNativeMethods.DeleteObject(new HandleRef(null, hBitmap)); SafeNativeMethods.DeleteObject(new HandleRef(null, hMask)); - if (index == -1) throw new InvalidOperationException(SR.ImageListAddFailed); + if (index == -1) + throw new InvalidOperationException(SR.ImageListAddFailed); return index; } @@ -479,11 +550,13 @@ private int AddToHandle(Original original, Bitmap bitmap) { /// appropriate values with it. Inheriting classes overriding this method /// should not forget to call base.createHandle(); /// - private void CreateHandle() { + private void CreateHandle() + { Debug.Assert(nativeImageList == null, "Handle already created, this may be a source of temporary GDI leaks"); int flags = NativeMethods.ILC_MASK; - switch (colorDepth) { + switch (colorDepth) + { case ColorDepth.Depth4Bit: flags |= NativeMethods.ILC_COLOR4; break; @@ -507,30 +580,36 @@ private void CreateHandle() { // We enclose the imagelist handle create in a theming scope. IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); - try { + try + { SafeNativeMethods.InitCommonControls(); nativeImageList = new NativeImageList(SafeNativeMethods.ImageList_Create(imageSize.Width, imageSize.Height, flags, INITIAL_CAPACITY, GROWBY)); } - finally { + finally + { UnsafeNativeMethods.ThemingScope.Deactivate(userCookie); } - if (Handle == IntPtr.Zero) throw new InvalidOperationException(SR.ImageListCreateFailed); + if (Handle == IntPtr.Zero) + throw new InvalidOperationException(SR.ImageListCreateFailed); SafeNativeMethods.ImageList_SetBkColor(new HandleRef(this, Handle), NativeMethods.CLR_NONE); Debug.Assert(originals != null, "Handle not yet created, yet original images are gone"); - for (int i = 0; i < originals.Count; i++) { - Original original = (Original) originals[i]; - if (original.image is Icon) { + for (int i = 0; i < originals.Count; i++) + { + Original original = (Original)originals[i]; + if (original.image is Icon) + { AddIconToHandle(original, (Icon)original.image); // NOTE: if we own the icon (it's been created by us) this WILL dispose the icon to avoid a GDI leak // **** original.image is NOT LONGER VALID AFTER THIS POINT *** } - else { + else + { bool ownsBitmap = false; Bitmap bitmapValue = CreateBitmap(original, out ownsBitmap); AddToHandle(original, bitmapValue); - if(ownsBitmap) + if (ownsBitmap) bitmapValue.Dispose(); } } @@ -538,8 +617,10 @@ private void CreateHandle() { } // Don't merge this function into Dispose() -- that base.Dispose() will damage the design time experience - private void DestroyHandle() { - if (HandleCreated) { + private void DestroyHandle() + { + if (HandleCreated) + { nativeImageList.Dispose(); nativeImageList = null; originals = new ArrayList(); @@ -549,11 +630,16 @@ private void DestroyHandle() { /// /// Frees all resources assocaited with this component. /// - protected override void Dispose(bool disposing) { - if (disposing) { - if(originals != null) { // we might own some of the stuff that's not been created yet - foreach(Original original in originals) { - if((original.options & OriginalOptions.OwnsImage) != 0) { + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (originals != null) + { // we might own some of the stuff that's not been created yet + foreach (Original original in originals) + { + if ((original.options & OriginalOptions.OwnsImage) != 0) + { ((IDisposable)original.image).Dispose(); } } @@ -567,7 +653,8 @@ protected override void Dispose(bool disposing) { /// Draw the image indicated by the given index on the given Graphics /// at the given location. /// - public void Draw(Graphics g, Point pt, int index) { + public void Draw(Graphics g, Point pt, int index) + { Draw(g, pt.X, pt.Y, index); } @@ -575,7 +662,8 @@ public void Draw(Graphics g, Point pt, int index) { /// Draw the image indicated by the given index on the given Graphics /// at the given location. /// - public void Draw(Graphics g, int x, int y, int index) { + public void Draw(Graphics g, int x, int y, int index) + { Draw(g, x, y, imageSize.Width, imageSize.Height, index); } @@ -584,62 +672,77 @@ public void Draw(Graphics g, int x, int y, int index) { /// and raster op code specified. The image is stretched or compressed as /// necessary to fit the bounds provided. /// - public void Draw(Graphics g, int x, int y, int width, int height, int index) { + public void Draw(Graphics g, int x, int y, int width, int height, int index) + { if (index < 0 || index >= Images.Count) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); IntPtr dc = g.GetHdc(); - try { + try + { SafeNativeMethods.ImageList_DrawEx(new HandleRef(this, Handle), index, new HandleRef(g, dc), x, y, width, height, NativeMethods.CLR_NONE, NativeMethods.CLR_NONE, NativeMethods.ILD_TRANSPARENT); } - finally { + finally + { g.ReleaseHdcInternal(dc); } } - private void CopyBitmapData(BitmapData sourceData, BitmapData targetData) { + private void CopyBitmapData(BitmapData sourceData, BitmapData targetData) + { // do the actual copy int offsetSrc = 0; int offsetDest = 0; - unsafe { + unsafe + { for (int i = 0; i < targetData.Height; i++) { IntPtr srcPtr, destPtr; - if (IntPtr.Size == 4) { + if (IntPtr.Size == 4) + { srcPtr = new IntPtr(sourceData.Scan0.ToInt32() + offsetSrc); destPtr = new IntPtr(targetData.Scan0.ToInt32() + offsetDest); - } else { + } + else + { srcPtr = new IntPtr(sourceData.Scan0.ToInt64() + offsetSrc); destPtr = new IntPtr(targetData.Scan0.ToInt64() + offsetDest); } - UnsafeNativeMethods.CopyMemory(new HandleRef(this, destPtr), new HandleRef(this, srcPtr), Math.Abs(targetData.Stride)); + UnsafeNativeMethods.CopyMemory(new HandleRef(this, destPtr), new HandleRef(this, srcPtr), Math.Abs(targetData.Stride)); offsetSrc += sourceData.Stride; offsetDest += targetData.Stride; } } } - - private static bool BitmapHasAlpha(BitmapData bmpData) { - if(bmpData.PixelFormat != PixelFormat.Format32bppArgb && bmpData.PixelFormat != PixelFormat.Format32bppRgb) { + + private static bool BitmapHasAlpha(BitmapData bmpData) + { + if (bmpData.PixelFormat != PixelFormat.Format32bppArgb && bmpData.PixelFormat != PixelFormat.Format32bppRgb) + { return false; } - bool hasAlpha = false; - unsafe { - for (int i = 0; i < bmpData.Height; i++) { + bool hasAlpha = false; + unsafe + { + for (int i = 0; i < bmpData.Height; i++) + { int offsetRow = i * bmpData.Stride; - for (int j = 3; j < bmpData.Width*4; j += 4) { // *4 is safe since we know PixelFormat is ARGB - unsafe { + for (int j = 3; j < bmpData.Width * 4; j += 4) + { // *4 is safe since we know PixelFormat is ARGB + unsafe + { byte* candidate = ((byte*)bmpData.Scan0.ToPointer()) + offsetRow + j; - if (*candidate != 0) { + if (*candidate != 0) + { hasAlpha = true; goto Found; // gotos are not the best, but it's the best thing here... } } } } - Found: - return hasAlpha; + Found: + return hasAlpha; } } @@ -648,12 +751,13 @@ private static bool BitmapHasAlpha(BitmapData bmpData) { /// copy of the original image. /// // NOTE: forces handle creation, so doesn't return things from the original list - - private Bitmap GetBitmap(int index) { + + private Bitmap GetBitmap(int index) + { if (index < 0 || index >= Images.Count) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); - Bitmap result=null; + Bitmap result = null; // if the imagelist is 32bpp, if the image slot at index // has valid alpha information (not all zero... which is cause by windows just painting RGB values @@ -661,66 +765,81 @@ private Bitmap GetBitmap(int index) { // we're not using the mask. That means that // we can just get the whole image strip, cut out the piece that we want // and return that, that way we don't flatten the alpha by painting the value with the alpha... (ie using the alpha) - - if(ColorDepth == ColorDepth.Depth32Bit) { + + if (ColorDepth == ColorDepth.Depth32Bit) + { NativeMethods.IMAGEINFO imageInfo = new NativeMethods.IMAGEINFO(); // review? do I need to delete the mask and image inside of imageinfo? - if(SafeNativeMethods.ImageList_GetImageInfo(new HandleRef(this, this.Handle), index, imageInfo)) { + if (SafeNativeMethods.ImageList_GetImageInfo(new HandleRef(this, this.Handle), index, imageInfo)) + { Bitmap tmpBitmap = null; BitmapData bmpData = null; BitmapData targetData = null; - try { + try + { tmpBitmap = Bitmap.FromHbitmap(imageInfo.hbmImage); // - bmpData = tmpBitmap.LockBits(new Rectangle(imageInfo.rcImage_left,imageInfo.rcImage_top, imageInfo.rcImage_right-imageInfo.rcImage_left, imageInfo.rcImage_bottom-imageInfo.rcImage_top), ImageLockMode.ReadOnly, tmpBitmap.PixelFormat); + bmpData = tmpBitmap.LockBits(new Rectangle(imageInfo.rcImage_left, imageInfo.rcImage_top, imageInfo.rcImage_right - imageInfo.rcImage_left, imageInfo.rcImage_bottom - imageInfo.rcImage_top), ImageLockMode.ReadOnly, tmpBitmap.PixelFormat); - int offset = bmpData.Stride * imageSize.Height * index; + int offset = bmpData.Stride * imageSize.Height * index; // we need do the following if the image has alpha because otherwise the image is fully transparent even though it has data - if(BitmapHasAlpha(bmpData)) { + if (BitmapHasAlpha(bmpData)) + { result = new Bitmap(imageSize.Width, imageSize.Height, PixelFormat.Format32bppArgb); targetData = result.LockBits(new Rectangle(0, 0, imageSize.Width, imageSize.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); CopyBitmapData(bmpData, targetData); - } - } finally { - if(tmpBitmap != null) { - if(bmpData != null) { + } + } + finally + { + if (tmpBitmap != null) + { + if (bmpData != null) + { tmpBitmap.UnlockBits(bmpData); } tmpBitmap.Dispose(); } - if(result != null && targetData != null) { + if (result != null && targetData != null) + { result.UnlockBits(targetData); } } - } - } + } + } - if(result == null) { // paint with the mask but no alpha... + if (result == null) + { // paint with the mask but no alpha... result = new Bitmap(imageSize.Width, imageSize.Height); Graphics graphics = Graphics.FromImage(result); - try { + try + { IntPtr dc = graphics.GetHdc(); - try { + try + { SafeNativeMethods.ImageList_DrawEx(new HandleRef(this, Handle), index, new HandleRef(graphics, dc), 0, 0, imageSize.Width, imageSize.Height, NativeMethods.CLR_NONE, NativeMethods.CLR_NONE, NativeMethods.ILD_TRANSPARENT); } - finally { + finally + { graphics.ReleaseHdcInternal(dc); } } - finally { + finally + { graphics.Dispose(); - } + } } // gpr: See Icon for description of fakeTransparencyColor - if (result.RawFormat.Guid != ImageFormat.Icon.Guid) { + if (result.RawFormat.Guid != ImageFormat.Icon.Guid) + { result.MakeTransparent(fakeTransparencyColor); } return result; @@ -747,14 +866,18 @@ public Bitmap DebugOnly_GetMasterMask() { /// /// Called when the Handle property changes. /// - private void OnRecreateHandle(EventArgs eventargs) { - if (recreateHandler != null) { + private void OnRecreateHandle(EventArgs eventargs) + { + if (recreateHandler != null) + { recreateHandler(this, eventargs); } } - private void OnChangeHandle(EventArgs eventargs) { - if (changeHandler != null) { + private void OnChangeHandle(EventArgs eventargs) + { + if (changeHandler != null) + { changeHandler(this, eventargs); } } @@ -820,8 +943,10 @@ private void PutImageInTempBitmap(int index, bool useSnapshot) { // Thus, if you add a new Property to ImageList which ends up calling // PerformRecreateHandle, you must shadow the property in ImageListDesigner. - private void PerformRecreateHandle(string reason) { - if (!HandleCreated) return; + private void PerformRecreateHandle(string reason) + { + if (!HandleCreated) + return; if (originals == null || Images.Empty) originals = new ArrayList(); // spoof it into thinking this is the first CreateHandle @@ -834,15 +959,18 @@ private void PerformRecreateHandle(string reason) { OnRecreateHandle(EventArgs.Empty); } - private void ResetImageSize() { + private void ResetImageSize() + { ImageSize = DefaultImageSize; } - private void ResetTransparentColor() { + private void ResetTransparentColor() + { TransparentColor = Color.LightGray; } - private bool ShouldSerializeTransparentColor() { + private bool ShouldSerializeTransparentColor() + { return !TransparentColor.Equals(Color.LightGray); } @@ -850,23 +978,28 @@ private bool ShouldSerializeTransparentColor() { /// /// Returns a string representation for this control. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); - if (Images != null) { + if (Images != null) + { return s + " Images.Count: " + Images.Count.ToString(CultureInfo.CurrentCulture) + ", ImageSize: " + ImageSize.ToString(); } - else { + else + { return s; } } - internal class NativeImageList : IDisposable { + internal class NativeImageList : IDisposable + { private IntPtr himl; #if DEBUG private string callStack; #endif - internal NativeImageList(IntPtr himl) { + internal NativeImageList(IntPtr himl) + { this.himl = himl; #if DEBUG callStack = Environment.StackTrace; @@ -881,26 +1014,31 @@ internal IntPtr Handle } } - public void Dispose() { + public void Dispose() + { Dispose(true); GC.SuppressFinalize(this); } - public void Dispose(bool disposing) { - if (himl != IntPtr.Zero) { + public void Dispose(bool disposing) + { + if (himl != IntPtr.Zero) + { SafeNativeMethods.ImageList_Destroy(new HandleRef(null, himl)); himl = IntPtr.Zero; } } - ~NativeImageList() { + ~NativeImageList() + { Dispose(false); } } // An image before we add it to the image list, along with a few details about how to add it. - private class Original { + private class Original + { internal object image; internal OriginalOptions options; internal Color customTransparentColor = Color.Transparent; @@ -908,23 +1046,28 @@ private class Original { internal int nImages = 1; internal Original(object image, OriginalOptions options) - : this(image, options, Color.Transparent) { + : this(image, options, Color.Transparent) + { } internal Original(object image, OriginalOptions options, int nImages) - : this(image, options, Color.Transparent) { + : this(image, options, Color.Transparent) + { this.nImages = nImages; } - internal Original(object image, OriginalOptions options, Color customTransparentColor) { + internal Original(object image, OriginalOptions options, Color customTransparentColor) + { Debug.Assert(image != null, "image is null"); - if (!(image is Icon) && !(image is Image)) { + if (!(image is Icon) && !(image is Image)) + { throw new InvalidOperationException(SR.ImageListEntryType); } this.image = image; this.options = options; this.customTransparentColor = customTransparentColor; - if ((options & OriginalOptions.CustomTransparentColor) == 0) { + if ((options & OriginalOptions.CustomTransparentColor) == 0) + { Debug.Assert(customTransparentColor.Equals(Color.Transparent), "Specified a custom transparent color then told us to ignore it"); } @@ -932,12 +1075,13 @@ internal Original(object image, OriginalOptions options, Color customTransparent } [Flags] - private enum OriginalOptions { - Default = 0x00, + private enum OriginalOptions + { + Default = 0x00, - ImageStrip = 0x01, + ImageStrip = 0x01, CustomTransparentColor = 0x02, - OwnsImage = 0x04 + OwnsImage = 0x04 } @@ -948,7 +1092,8 @@ private enum OriginalOptions { [ Editor("System.Windows.Forms.Design.ImageCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)) ] - public sealed class ImageCollection : IList { + public sealed class ImageCollection : IList + { private ImageList owner; private ArrayList imageInfoCollection = new ArrayList(); @@ -961,54 +1106,70 @@ public sealed class ImageCollection : IList { /// Returns the keys in the image list - images without keys return String.Empty. /// /// - public StringCollection Keys { - get { + public StringCollection Keys + { + get + { // pass back a copy of the current state. StringCollection keysCollection = new StringCollection(); - for (int i = 0; i < imageInfoCollection.Count; i++) { + for (int i = 0; i < imageInfoCollection.Count; i++) + { ImageInfo image = imageInfoCollection[i] as ImageInfo; - if ((image != null) && (image.Name != null) && (image.Name.Length != 0)) { - keysCollection.Add(image.Name); - } else { + if ((image != null) && (image.Name != null) && (image.Name.Length != 0)) + { + keysCollection.Add(image.Name); + } + else + { keysCollection.Add(string.Empty); } } return keysCollection; - } + } } - internal ImageCollection(ImageList owner) { + internal ImageCollection(ImageList owner) + { this.owner = owner; } - internal void ResetKeys() { - if (imageInfoCollection!= null) + internal void ResetKeys() + { + if (imageInfoCollection != null) imageInfoCollection.Clear(); - for (int i = 0; i < this.Count; i++) { - imageInfoCollection.Add(new ImageCollection.ImageInfo()); + for (int i = 0; i < this.Count; i++) + { + imageInfoCollection.Add(new ImageCollection.ImageInfo()); } } - [Conditional("DEBUG")] - private void AssertInvariant() { + [Conditional("DEBUG")] + private void AssertInvariant() + { Debug.Assert(owner != null, "ImageCollection has no owner (ImageList)"); - Debug.Assert( (owner.originals == null) == (owner.HandleCreated), " Either we should have the original images, or the handle should be created"); + Debug.Assert((owner.originals == null) == (owner.HandleCreated), " Either we should have the original images, or the handle should be created"); } [Browsable(false)] - public int Count { - - get { + public int Count + { + + get + { Debug.Assert(owner != null, "ImageCollection has no owner (ImageList)"); - if (owner.HandleCreated) { + if (owner.HandleCreated) + { return SafeNativeMethods.ImageList_GetImageCount(new HandleRef(owner, owner.Handle)); } - else { + else + { int count = 0; - foreach(Original original in owner.originals) { - if (original != null) { + foreach (Original original in owner.originals) + { + if (original != null) + { count += original.nImages; } } @@ -1017,26 +1178,34 @@ public int Count { } } - object ICollection.SyncRoot { - get { + object ICollection.SyncRoot + { + get + { return this; } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return false; } } - bool IList.IsFixedSize { - get { + bool IList.IsFixedSize + { + get + { return false; } } - public bool IsReadOnly { - get { + public bool IsReadOnly + { + get + { return false; } } @@ -1044,46 +1213,54 @@ public bool IsReadOnly { /// /// Determines if the ImageList has any images, without forcing a handle creation. /// - public bool Empty { - get { + public bool Empty + { + get + { return Count == 0; } } [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public Image this[int index] { - - - get { + public Image this[int index] + { + + + get + { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); return owner.GetBitmap(index); } - set { + set + { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); - if (value == null) { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } - if (!(value is Bitmap)) + if (!(value is Bitmap)) throw new ArgumentException(SR.ImageListBitmap); AssertInvariant(); Bitmap bitmap = (Bitmap)value; bool ownsImage = false; - if (owner.UseTransparentColor && bitmap.RawFormat.Guid != ImageFormat.Icon.Guid) { + if (owner.UseTransparentColor && bitmap.RawFormat.Guid != ImageFormat.Icon.Guid) + { // Since there's no ImageList_ReplaceMasked, we need to generate // a transparent bitmap Bitmap source = bitmap; - bitmap = (Bitmap) bitmap.Clone(); + bitmap = (Bitmap)bitmap.Clone(); bitmap.MakeTransparent(owner.transparentColor); ownsImage = true; } - try { + try + { IntPtr hMask = ControlPaint.CreateHBitmapTransparencyMask(bitmap); IntPtr hBitmap = ControlPaint.CreateHBitmapColorMask(bitmap, hMask); bool ok = SafeNativeMethods.ImageList_Replace(new HandleRef(owner, owner.Handle), index, new HandleRef(null, hBitmap), new HandleRef(null, hMask)); @@ -1092,26 +1269,34 @@ public Image this[int index] { if (!ok) throw new InvalidOperationException(SR.ImageListReplaceFailed); - - } finally { - if(ownsImage) { + + } + finally + { + if (ownsImage) + { bitmap.Dispose(); } } } } - object IList.this[int index] { - - - get { + object IList.this[int index] + { + + + get + { return this[index]; } - set { - if (value is Image) { + set + { + if (value is Image) + { this[index] = (Image)value; } - else { + else + { throw new ArgumentException(SR.ImageListBadImage, "value"); } } @@ -1120,21 +1305,26 @@ object IList.this[int index] { /// /// Retrieves the child control with the specified key. /// - public Image this[string key] { - - - get { + public Image this[string key] + { + + + get + { // We do not support null and empty string as valid keys. - if ((key == null) || (key.Length == 0)){ + if ((key == null) || (key.Length == 0)) + { return null; } // Search for the key in our collection int index = IndexOfKey(key); - if (IsValidIndex(index)) { + if (IsValidIndex(index)) + { return this[index]; } - else { + else + { return null; } @@ -1145,7 +1335,8 @@ public Image this[string key] { /// /// Adds an image to the end of the image list with a key accessor. /// - public void Add(string key, Image image) { + public void Add(string key, Image image) + { Debug.Assert((this.Count == imageInfoCollection.Count), "The count of these two collections should be equal."); // Store off the name. @@ -1161,7 +1352,8 @@ public void Add(string key, Image image) { /// /// Adds an icon to the end of the image list with a key accessor. /// - public void Add(string key, Icon icon) { + public void Add(string key, Icon icon) + { Debug.Assert((this.Count == imageInfoCollection.Count), "The count of these two collections should be equal."); // Store off the name. @@ -1176,18 +1368,23 @@ public void Add(string key, Icon icon) { } - int IList.Add(object value) { - if (value is Image) { + int IList.Add(object value) + { + if (value is Image) + { Add((Image)value); return Count - 1; } - else { + else + { throw new ArgumentException(SR.ImageListBadImage, "value"); } } - public void Add(Icon value) { - if (value == null) { + public void Add(Icon value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } Add(new Original(value.Clone(), OriginalOptions.OwnsImage), null); // WHY WHY WHY do we clone here... @@ -1197,8 +1394,10 @@ public void Add(Icon value) { /// /// Add the given image to the ImageList. /// - public void Add(Image value) { - if (value == null) { + public void Add(Image value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } Original original = new Original(value, OriginalOptions.Default); @@ -1210,8 +1409,10 @@ public void Add(Image value) { /// to generate the mask. The number of images to add is inferred from /// the width of the given image. /// - public int Add(Image value, Color transparentColor) { - if (value == null) { + public int Add(Image value, Color transparentColor) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } Original original = new Original(value, OriginalOptions.CustomTransparentColor, @@ -1219,8 +1420,10 @@ public int Add(Image value, Color transparentColor) { return Add(original, null); } - private int Add(Original original, ImageInfo imageInfo) { - if (original == null || original.image == null) { + private int Add(Original original, ImageInfo imageInfo) + { + if (original == null || original.image == null) + { throw new ArgumentNullException(nameof(original)); } @@ -1228,40 +1431,51 @@ private int Add(Original original, ImageInfo imageInfo) { AssertInvariant(); - if (original.image is Bitmap) { - if (owner.originals != null) { + if (original.image is Bitmap) + { + if (owner.originals != null) + { index = owner.originals.Add(original); } - if (owner.HandleCreated) { + if (owner.HandleCreated) + { bool ownsBitmap = false; Bitmap bitmapValue = owner.CreateBitmap(original, out ownsBitmap); index = owner.AddToHandle(original, bitmapValue); - if(ownsBitmap) + if (ownsBitmap) bitmapValue.Dispose(); } } - else if (original.image is Icon) { - if (owner.originals != null) { + else if (original.image is Icon) + { + if (owner.originals != null) + { index = owner.originals.Add(original); } - if (owner.HandleCreated) { + if (owner.HandleCreated) + { index = owner.AddIconToHandle(original, (Icon)original.image); // NOTE: if we own the icon (it's been created by us) this WILL dispose the icon to avoid a GDI leak // **** original.image is NOT LONGER VALID AFTER THIS POINT *** } } - else { + else + { throw new ArgumentException(SR.ImageListBitmap); } // update the imageInfoCollection // support AddStrip - if ((original.options & OriginalOptions.ImageStrip) != 0) { - for (int i = 0; i < original.nImages; i++) { + if ((original.options & OriginalOptions.ImageStrip) != 0) + { + for (int i = 0; i < original.nImages; i++) + { imageInfoCollection.Add(new ImageInfo()); } - } else { + } + else + { if (imageInfo == null) imageInfo = new ImageInfo(); imageInfoCollection.Add(imageInfo); @@ -1273,25 +1487,30 @@ private int Add(Original original, ImageInfo imageInfo) { return index; } - public void AddRange(Image[] images) { - if (images == null) { + public void AddRange(Image[] images) + { + if (images == null) + { throw new ArgumentNullException(nameof(images)); } owner.inAddRange = true; - foreach(Image image in images) { + foreach (Image image in images) + { Add(image); } owner.inAddRange = false; owner.OnChangeHandle(EventArgs.Empty); - } + } /// /// Add an image strip the given image to the ImageList. A strip is a single Image /// which is treated as multiple images arranged side-by-side. /// - public int AddStrip(Image value) { + public int AddStrip(Image value) + { - if (value == null) { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } @@ -1312,7 +1531,8 @@ public int AddStrip(Image value) { /// /// Remove all images and masks from the ImageList. /// - public void Clear() { + public void Clear() + { AssertInvariant(); if (owner.originals != null) owner.originals.Clear(); @@ -1326,15 +1546,19 @@ public void Clear() { } [EditorBrowsable(EditorBrowsableState.Never)] - public bool Contains(Image image) { + public bool Contains(Image image) + { throw new NotSupportedException(); } - bool IList.Contains(object image) { - if (image is Image) { + bool IList.Contains(object image) + { + if (image is Image) + { return Contains((Image)image); } - else { + else + { return false; } } @@ -1342,31 +1566,38 @@ bool IList.Contains(object image) { /// /// Returns true if the collection contains an item with the specified key, false otherwise. /// - public bool ContainsKey(string key) { - return IsValidIndex(IndexOfKey(key)); + public bool ContainsKey(string key) + { + return IsValidIndex(IndexOfKey(key)); } [EditorBrowsable(EditorBrowsableState.Never)] - public int IndexOf(Image image) { + public int IndexOf(Image image) + { throw new NotSupportedException(); } - int IList.IndexOf(object image) { - if (image is Image) { + int IList.IndexOf(object image) + { + if (image is Image) + { return IndexOf((Image)image); } - else { + else + { return -1; } } - /// - /// The zero-based index of the first occurrence of value within the entire CollectionBase, - /// if found; otherwise, -1. - /// - public int IndexOfKey(string key) { + /// + /// The zero-based index of the first occurrence of value within the entire CollectionBase, + /// if found; otherwise, -1. + /// + public int IndexOfKey(string key) + { // Step 0 - Arg validation - if ((key == null) || (key.Length == 0)){ + if ((key == null) || (key.Length == 0)) + { return -1; // we dont support empty or null keys. } @@ -1375,15 +1606,18 @@ public int IndexOfKey(string key) { if (IsValidIndex(lastAccessedIndex)) { if ((imageInfoCollection[lastAccessedIndex] != null) && - (WindowsFormsUtils.SafeCompareStrings(((ImageInfo)imageInfoCollection[lastAccessedIndex]).Name, key, /* ignoreCase = */ true))) { - return lastAccessedIndex; - } + (WindowsFormsUtils.SafeCompareStrings(((ImageInfo)imageInfoCollection[lastAccessedIndex]).Name, key, /* ignoreCase = */ true))) + { + return lastAccessedIndex; + } } // step 2 - search for the item - for (int i = 0; i < this.Count; i ++) { + for (int i = 0; i < this.Count; i++) + { if ((imageInfoCollection[i] != null) && - (WindowsFormsUtils.SafeCompareStrings(((ImageInfo)imageInfoCollection[i]).Name, key, /* ignoreCase = */ true))) { + (WindowsFormsUtils.SafeCompareStrings(((ImageInfo)imageInfoCollection[i]).Name, key, /* ignoreCase = */ true))) + { lastAccessedIndex = i; return i; } @@ -1396,25 +1630,30 @@ public int IndexOfKey(string key) { - void IList.Insert(int index, object value) { + void IList.Insert(int index, object value) + { throw new NotSupportedException(); } /// /// Determines if the index is valid for the collection. /// - private bool IsValidIndex(int index) { + private bool IsValidIndex(int index) + { return ((index >= 0) && (index < this.Count)); } - void ICollection.CopyTo(Array dest, int index) { + void ICollection.CopyTo(Array dest, int index) + { AssertInvariant(); - for (int i = 0; i < Count; ++i) { + for (int i = 0; i < Count; ++i) + { dest.SetValue(owner.GetBitmap(i), index++); } } - public IEnumerator GetEnumerator() { + public IEnumerator GetEnumerator() + { // Forces handle creation AssertInvariant(); @@ -1426,65 +1665,81 @@ public IEnumerator GetEnumerator() { } [EditorBrowsable(EditorBrowsableState.Never)] - public void Remove(Image image) { + public void Remove(Image image) + { throw new NotSupportedException(); } - void IList.Remove(object image) { - if (image is Image) { + void IList.Remove(object image) + { + if (image is Image) + { Remove((Image)image); owner.OnChangeHandle(EventArgs.Empty); } } - public void RemoveAt(int index) { + public void RemoveAt(int index) + { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); AssertInvariant(); bool ok = SafeNativeMethods.ImageList_Remove(new HandleRef(owner, owner.Handle), index); - if (!ok) { + if (!ok) + { throw new InvalidOperationException(SR.ImageListRemoveFailed); - } else { - if ((imageInfoCollection != null) && (index >= 0 && index < imageInfoCollection.Count)) { - imageInfoCollection.RemoveAt(index); - owner.OnChangeHandle(EventArgs.Empty); + } + else + { + if ((imageInfoCollection != null) && (index >= 0 && index < imageInfoCollection.Count)) + { + imageInfoCollection.RemoveAt(index); + owner.OnChangeHandle(EventArgs.Empty); } } - } + } - /// - /// Removes the child control with the specified key. - /// - public void RemoveByKey(string key) { + /// + /// Removes the child control with the specified key. + /// + public void RemoveByKey(string key) + { int index = IndexOfKey(key); - if (IsValidIndex(index)) { + if (IsValidIndex(index)) + { RemoveAt(index); } - } + } /// /// Sets/Resets the key accessor for an image already in the image list. /// - public void SetKeyName(int index, string name) { - if (!IsValidIndex(index)) { + public void SetKeyName(int index, string name) + { + if (!IsValidIndex(index)) + { throw new IndexOutOfRangeException(); // } - if (imageInfoCollection[index] == null) { + if (imageInfoCollection[index] == null) + { imageInfoCollection[index] = new ImageInfo(); } ((ImageInfo)imageInfoCollection[index]).Name = name; } - internal class ImageInfo { + internal class ImageInfo + { private string name; - public ImageInfo() { + public ImageInfo() + { } - public string Name { + public string Name + { get { return name; } set { name = value; } } @@ -1493,9 +1748,11 @@ public string Name { } // end class ImageCollection } - internal class ImageListConverter : ComponentConverter { + internal class ImageListConverter : ComponentConverter + { - public ImageListConverter() : base(typeof(ImageList)) { + public ImageListConverter() : base(typeof(ImageList)) + { } /// @@ -1503,7 +1760,8 @@ public ImageListConverter() : base(typeof(ImageList)) { /// whether this object supports properties using the /// specified context. /// - public override bool GetPropertiesSupported(ITypeDescriptorContext context) { + public override bool GetPropertiesSupported(ITypeDescriptorContext context) + { return true; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ImageListStreamer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ImageListStreamer.cs index 6078c45cb08..e07ef6aa2f4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ImageListStreamer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ImageListStreamer.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Diagnostics; @@ -18,18 +19,20 @@ namespace System.Windows.Forms { /// /// [Serializable] - public sealed class ImageListStreamer : ISerializable, IDisposable { - + public sealed class ImageListStreamer : ISerializable, IDisposable + { + // compressed magic header. If we see this, the image stream is compressed. // (unicode for MSFT). // - private static readonly byte[] HEADER_MAGIC = new byte[] {0x4D, 0x53, 0x46, 0X74}; + private static readonly byte[] HEADER_MAGIC = new byte[] { 0x4D, 0x53, 0x46, 0X74 }; private static object internalSyncObject = new object(); - + private ImageList imageList; private ImageList.NativeImageList nativeImageList; - internal ImageListStreamer(ImageList il) { + internal ImageListStreamer(ImageList il) + { imageList = il; } @@ -48,36 +51,39 @@ private ImageListStreamer(SerializationInfo info, StreamingContext context) if (string.Equals(sie.Name, "Data", StringComparison.OrdinalIgnoreCase)) { #if DEBUG - try { -#endif - byte[] dat = (byte[])sie.Value; - if (dat != null) + try { - // We enclose this imagelist handle create in a theming scope. - IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); - - try +#endif + byte[] dat = (byte[])sie.Value; + if (dat != null) { - MemoryStream ms = new MemoryStream(Decompress(dat)); + // We enclose this imagelist handle create in a theming scope. + IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); + + try + { + MemoryStream ms = new MemoryStream(Decompress(dat)); - lock (internalSyncObject) { - SafeNativeMethods.InitCommonControls(); - nativeImageList = new ImageList.NativeImageList( - SafeNativeMethods.ImageList_Read(new UnsafeNativeMethods.ComStreamFromDataStream(ms))); + lock (internalSyncObject) + { + SafeNativeMethods.InitCommonControls(); + nativeImageList = new ImageList.NativeImageList( + SafeNativeMethods.ImageList_Read(new UnsafeNativeMethods.ComStreamFromDataStream(ms))); + } + } + finally + { + UnsafeNativeMethods.ThemingScope.Deactivate(userCookie); + } + if (nativeImageList.Handle == IntPtr.Zero) + { + throw new InvalidOperationException(SR.ImageListStreamerLoadFailed); } } - finally - { - UnsafeNativeMethods.ThemingScope.Deactivate(userCookie); - } - if (nativeImageList.Handle == IntPtr.Zero) - { - throw new InvalidOperationException(SR.ImageListStreamerLoadFailed); - } - } #if DEBUG } - catch (Exception e) { + catch (Exception e) + { Debug.Fail("ImageList serialization failure: " + e.ToString()); throw; } @@ -85,127 +91,144 @@ private ImageListStreamer(SerializationInfo info, StreamingContext context) } } } - + /// /// Compresses the given input, returning a new array that represents /// the compressed data. /// - private byte[] Compress(byte[] input) { - + private byte[] Compress(byte[] input) + { + int finalLength = 0; int idx = 0; int compressedIdx = 0; - - while(idx < input.Length) { - + + while (idx < input.Length) + { + byte current = input[idx++]; byte runLength = 1; - - while(idx < input.Length && input[idx] == current && runLength < 0xFF) { + + while (idx < input.Length && input[idx] == current && runLength < 0xFF) + { runLength++; idx++; } - + finalLength += 2; } - + byte[] output = new byte[finalLength + HEADER_MAGIC.Length]; - + Buffer.BlockCopy(HEADER_MAGIC, 0, output, 0, HEADER_MAGIC.Length); int idxOffset = HEADER_MAGIC.Length; idx = 0; - - while(idx < input.Length) { - + + while (idx < input.Length) + { + byte current = input[idx++]; byte runLength = 1; - - while(idx < input.Length && input[idx] == current && runLength < 0xFF) { + + while (idx < input.Length && input[idx] == current && runLength < 0xFF) + { runLength++; idx++; } - + output[idxOffset + compressedIdx++] = runLength; output[idxOffset + compressedIdx++] = current; } - + Debug.Assert(idxOffset + compressedIdx == output.Length, "RLE Compression failure in ImageListStreamer -- didn't fill array"); - + // Validate that our compression routine works - #if DEBUG +#if DEBUG byte[] debugCompare = Decompress(output); Debug.Assert(debugCompare.Length == input.Length, "RLE Compression in ImageListStreamer is broken."); int debugMaxCompare = input.Length; - for(int debugIdx = 0; debugIdx < debugMaxCompare; debugIdx++) { - if (debugCompare[debugIdx] != input[debugIdx]) { + for (int debugIdx = 0; debugIdx < debugMaxCompare; debugIdx++) + { + if (debugCompare[debugIdx] != input[debugIdx]) + { Debug.Fail("RLE Compression failure in ImageListStreamer at byte offset " + debugIdx); break; } } - #endif // DEBUG - +#endif // DEBUG + return output; } - + /// /// Decompresses the given input, returning a new array that represents /// the uncompressed data. /// - private byte[] Decompress(byte[] input) { - + private byte[] Decompress(byte[] input) + { + int finalLength = 0; int idx = 0; int outputIdx = 0; - + // Check for our header. If we don't have one, // we're not actually decompressed, so just return // the original. // - if (input.Length < HEADER_MAGIC.Length) { + if (input.Length < HEADER_MAGIC.Length) + { return input; } - - for(idx = 0; idx < HEADER_MAGIC.Length; idx++) { - if (input[idx] != HEADER_MAGIC[idx]) { + + for (idx = 0; idx < HEADER_MAGIC.Length; idx++) + { + if (input[idx] != HEADER_MAGIC[idx]) + { return input; } } - + // Ok, we passed the magic header test. - - for (idx = HEADER_MAGIC.Length; idx < input.Length; idx += 2) { + + for (idx = HEADER_MAGIC.Length; idx < input.Length; idx += 2) + { finalLength += input[idx]; } - + byte[] output = new byte[finalLength]; - + idx = HEADER_MAGIC.Length; - - while(idx < input.Length) { + + while (idx < input.Length) + { byte runLength = input[idx++]; byte current = input[idx++]; - + int startIdx = outputIdx; int endIdx = outputIdx + runLength; - - while(startIdx < endIdx) { + + while (startIdx < endIdx) + { output[startIdx++] = current; } - + outputIdx += runLength; } - + return output; } - public void /*cpr: ISerializable*/GetObjectData(SerializationInfo si, StreamingContext context) { + public void /*cpr: ISerializable*/GetObjectData(SerializationInfo si, StreamingContext context) + { MemoryStream stream = new MemoryStream(); IntPtr handle = IntPtr.Zero; - if (imageList != null) { + if (imageList != null) + { handle = imageList.Handle; } - else if (nativeImageList != null) { + else if (nativeImageList != null) + { handle = nativeImageList.Handle; } @@ -215,20 +238,24 @@ private byte[] Decompress(byte[] input) { si.AddValue("Data", Compress(stream.ToArray())); } - internal ImageList.NativeImageList GetNativeImageList() { + internal ImageList.NativeImageList GetNativeImageList() + { return nativeImageList; } - private bool WriteImageList(IntPtr imagelistHandle, Stream stream) { + private bool WriteImageList(IntPtr imagelistHandle, Stream stream) + { // What we need to do here is use WriteEx if comctl 6 or above, and Write otherwise. However, till we can fix // There isn't a reliable way to tell which version of comctl fusion is binding to. // So for now, we try to bind to WriteEx, and if that entry point isn't found, we use Write. - try { + try + { int hResult = SafeNativeMethods.ImageList_WriteEx(new HandleRef(this, imagelistHandle), NativeMethods.ILP_DOWNLEVEL, new UnsafeNativeMethods.ComStreamFromDataStream(stream)); return (hResult == NativeMethods.S_OK); } - catch (EntryPointNotFoundException) { + catch (EntryPointNotFoundException) + { // WriteEx wasn't found - that's fine - we will use Write. } @@ -238,14 +265,18 @@ private bool WriteImageList(IntPtr imagelistHandle, Stream stream) { /// /// Disposes the native image list handle. /// - public void Dispose() { + public void Dispose() + { Dispose(true); GC.SuppressFinalize(this); } - private void Dispose(bool disposing) { - if (disposing) { - if (nativeImageList != null) { + private void Dispose(bool disposing) + { + if (disposing) + { + if (nativeImageList != null) + { nativeImageList.Dispose(); nativeImageList = null; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/InputLanguage.cs b/src/System.Windows.Forms/src/System/Windows/Forms/InputLanguage.cs index cab35678312..24fc5e9f473 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/InputLanguage.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/InputLanguage.cs @@ -165,7 +165,7 @@ Look in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\000 // directly through the registry value if (layoutName == null) { - layoutName = (string) key.GetValue("Layout Text"); + layoutName = (string)key.GetValue("Layout Text"); } key.Close(); @@ -217,7 +217,7 @@ Look in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\000 // directly through the registry value if (layoutName == null) { - layoutName = (string) key.GetValue("Layout Text"); + layoutName = (string)key.GetValue("Layout Text"); } key.Close(); @@ -232,7 +232,7 @@ Look in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\000 foreach (string encoding in encodings) { Debug.Assert(encoding.Length == 8, "unexpected key in registry: hklm\\SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts\\" + encoding); - if (language == (0xffff & Convert.ToInt32(encoding.Substring(4,4), 16))) + if (language == (0xffff & Convert.ToInt32(encoding.Substring(4, 4), 16))) { RegistryKey key = layouts.OpenSubKey(encoding); string codeValue = (string)key.GetValue("Layout Id"); @@ -332,7 +332,7 @@ public static InputLanguage FromCulture(CultureInfo culture) // is the CU-preferred keyboard language for custom cultures. int lcid = culture.KeyboardLayoutId; - foreach(InputLanguage lang in InstalledInputLanguages) + foreach (InputLanguage lang in InstalledInputLanguages) { if ((unchecked((int)(long)lang.handle) & 0xFFFF) == lcid) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/InputLanguageCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/InputLanguageCollection.cs index 7071457d809..8d71ff75c04 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/InputLanguageCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/InputLanguageCollection.cs @@ -2,57 +2,65 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Collections; - - + + /// /// /// A collection that stores objects. /// /// - public class InputLanguageCollection : ReadOnlyCollectionBase { - + public class InputLanguageCollection : ReadOnlyCollectionBase + { + /// /// /// Initializes a new instance of containing any array of objects. /// /// - internal InputLanguageCollection(InputLanguage[] value) { + internal InputLanguageCollection(InputLanguage[] value) + { InnerList.AddRange(value); } - + /// /// Represents the entry at the specified index of the . /// - public InputLanguage this[int index] { - get { + public InputLanguage this[int index] + { + get + { return ((InputLanguage)(InnerList[index])); } } - + /// /// Gets a value indicating whether the /// contains the specified . /// - public bool Contains(InputLanguage value) { + public bool Contains(InputLanguage value) + { return InnerList.Contains(value); } - + /// /// Copies the values to a one-dimensional instance at the /// specified index. /// - public void CopyTo(InputLanguage[] array, int index) { + public void CopyTo(InputLanguage[] array, int index) + { InnerList.CopyTo(array, index); } - + /// /// Returns the index of a in /// the . /// - public int IndexOf(InputLanguage value) { + public int IndexOf(InputLanguage value) + { return InnerList.IndexOf(value); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/InsertKeyMode.cs b/src/System.Windows.Forms/src/System/Windows/Forms/InsertKeyMode.cs index 7451807bc96..60695971643 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/InsertKeyMode.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/InsertKeyMode.cs @@ -22,6 +22,6 @@ public enum InsertKeyMode /// /// Forces insertion mode to be 'off' regardless of the Insert key mode. /// - Overwrite + Overwrite } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ItemCheckedEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ItemCheckedEventArgs.cs index 90446b254e0..e637e68382f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ItemCheckedEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ItemCheckedEventArgs.cs @@ -13,7 +13,7 @@ public ItemCheckedEventArgs(ListViewItem item) { Item = item; } - + /// /// The index of the item that is about to change. /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ItemDragEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ItemDragEventArgs.cs index b5b9ebb555a..8235a0488b3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ItemDragEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ItemDragEventArgs.cs @@ -15,13 +15,13 @@ public class ItemDragEventArgs : EventArgs public ItemDragEventArgs(MouseButtons button) : this(button, null) { } - + public ItemDragEventArgs(MouseButtons button, object item) { Button = button; Item = item; } - + public MouseButtons Button { get; } public object Item { get; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/KeyEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/KeyEventArgs.cs index b53acdd63f3..0c3659191a0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/KeyEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/KeyEventArgs.cs @@ -48,10 +48,10 @@ public Keys KeyCode [SuppressMessage("Microsoft.Performance", "CA1803:AvoidCostlyCallsWherePossible")] get { - Keys keyGenerated = KeyData & Keys.KeyCode; + Keys keyGenerated = KeyData & Keys.KeyCode; // since Keys can be discontiguous, keeping Enum.IsDefined. - if (!Enum.IsDefined(typeof(Keys),(int)keyGenerated)) + if (!Enum.IsDefined(typeof(Keys), (int)keyGenerated)) { return Keys.None; } @@ -64,7 +64,7 @@ public Keys KeyCode /// event. /// public int KeyValue => (int)(KeyData & Keys.KeyCode); - + /// /// Gets the key data for a or /// event. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/KeyboardToolTipStateMachine.cs b/src/System.Windows.Forms/src/System/Windows/Forms/KeyboardToolTipStateMachine.cs index 2e077e43a25..b243bde6cf7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/KeyboardToolTipStateMachine.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/KeyboardToolTipStateMachine.cs @@ -25,17 +25,22 @@ * Please note that disabling Switch.UseLegacyAccessibilityFeatures, Switch.UseLegacyAccessibilityFeatures.2 and Switch.UseLegacyAccessibilityFeatures.3 is required to disable Switch.System.Windows.Forms.UseLegacyToolTipDisplay */ -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Runtime.CompilerServices; using System.Collections.Generic; using System.Diagnostics; using System.Threading; - internal sealed class KeyboardToolTipStateMachine { + internal sealed class KeyboardToolTipStateMachine + { - public static KeyboardToolTipStateMachine Instance { - get { - if (KeyboardToolTipStateMachine.instance == null) { + public static KeyboardToolTipStateMachine Instance + { + get + { + if (KeyboardToolTipStateMachine.instance == null) + { KeyboardToolTipStateMachine.instance = new KeyboardToolTipStateMachine(); } return KeyboardToolTipStateMachine.instance; @@ -55,8 +60,10 @@ public static KeyboardToolTipStateMachine Instance { private readonly WeakReference lastFocusedTool = new WeakReference(null); - private KeyboardToolTipStateMachine() { - this.transitions = new Dictionary> { + private KeyboardToolTipStateMachine() + { + this.transitions = new Dictionary> + { [new SmTransition(SmState.Hidden, SmEvent.FocusedTool)] = this.SetupInitShowTimer, [new SmTransition(SmState.Hidden, SmEvent.LeftTool)] = this.DoNothing, // OK @@ -78,61 +85,79 @@ [new SmTransition(SmState.ReadyForReshow, SmEvent.ReshowDelayTimerExpired)] = th }; } - public void ResetStateMachine(ToolTip toolTip) { + public void ResetStateMachine(ToolTip toolTip) + { this.Reset(toolTip); } - public void Hook(IKeyboardToolTip tool, ToolTip toolTip) { - if (tool.AllowsToolTip()) { + public void Hook(IKeyboardToolTip tool, ToolTip toolTip) + { + if (tool.AllowsToolTip()) + { this.StartTracking(tool, toolTip); tool.OnHooked(toolTip); } } - public void NotifyAboutMouseEnter(IKeyboardToolTip sender) { - if (this.IsToolTracked(sender) && sender.ShowsOwnToolTip()) { + public void NotifyAboutMouseEnter(IKeyboardToolTip sender) + { + if (this.IsToolTracked(sender) && sender.ShowsOwnToolTip()) + { this.Reset(null); } } - private bool IsToolTracked(IKeyboardToolTip sender) { + private bool IsToolTracked(IKeyboardToolTip sender) + { return this.toolToTip[sender] != null; } - public void NotifyAboutLostFocus(IKeyboardToolTip sender) { - if (this.IsToolTracked(sender) && sender.ShowsOwnToolTip()) { + public void NotifyAboutLostFocus(IKeyboardToolTip sender) + { + if (this.IsToolTracked(sender) && sender.ShowsOwnToolTip()) + { this.Transit(SmEvent.LeftTool, sender); - if (this.currentTool == null) { + if (this.currentTool == null) + { this.lastFocusedTool.SetTarget(null); } } } - public void NotifyAboutGotFocus(IKeyboardToolTip sender) { - if (this.IsToolTracked(sender) && sender.ShowsOwnToolTip() && sender.IsBeingTabbedTo()) { + public void NotifyAboutGotFocus(IKeyboardToolTip sender) + { + if (this.IsToolTracked(sender) && sender.ShowsOwnToolTip() && sender.IsBeingTabbedTo()) + { this.Transit(SmEvent.FocusedTool, sender); - if (this.currentTool == sender) { + if (this.currentTool == sender) + { this.lastFocusedTool.SetTarget(sender); } } } - public void Unhook(IKeyboardToolTip tool, ToolTip toolTip) { - if (tool.AllowsToolTip()) { + public void Unhook(IKeyboardToolTip tool, ToolTip toolTip) + { + if (tool.AllowsToolTip()) + { this.StopTracking(tool, toolTip); tool.OnUnhooked(toolTip); } } - public void NotifyAboutFormDeactivation(ToolTip sender) { + public void NotifyAboutFormDeactivation(ToolTip sender) + { this.OnFormDeactivation(sender); } - internal IKeyboardToolTip LastFocusedTool { - get { + internal IKeyboardToolTip LastFocusedTool + { + get + { IKeyboardToolTip tool; - if(this.lastFocusedTool.TryGetTarget(out tool)) { + if (this.lastFocusedTool.TryGetTarget(out tool)) + { return tool; } @@ -140,17 +165,21 @@ internal IKeyboardToolTip LastFocusedTool { } } - private SmState HideAndStartWaitingForRefocus(IKeyboardToolTip tool, ToolTip toolTip) { + private SmState HideAndStartWaitingForRefocus(IKeyboardToolTip tool, ToolTip toolTip) + { toolTip.HideToolTip(this.currentTool); return StartWaitingForRefocus(tool, toolTip); } - private SmState StartWaitingForRefocus(IKeyboardToolTip tool, ToolTip toolTip) { + private SmState StartWaitingForRefocus(IKeyboardToolTip tool, ToolTip toolTip) + { this.ResetTimer(); this.currentTool = null; SendOrPostCallback expirationCallback = null; - this.refocusDelayExpirationCallback = expirationCallback = (object toolObject) => { - if (this.currentState == SmState.WaitForRefocus && this.refocusDelayExpirationCallback == expirationCallback) { + this.refocusDelayExpirationCallback = expirationCallback = (object toolObject) => + { + if (this.currentState == SmState.WaitForRefocus && this.refocusDelayExpirationCallback == expirationCallback) + { this.Transit(SmEvent.RefocusWaitDelayExpired, (IKeyboardToolTip)toolObject); } }; @@ -158,32 +187,38 @@ private SmState StartWaitingForRefocus(IKeyboardToolTip tool, ToolTip toolTip) { return SmState.WaitForRefocus; } - private SmState SetupReshowTimer(IKeyboardToolTip tool, ToolTip toolTip) { + private SmState SetupReshowTimer(IKeyboardToolTip tool, ToolTip toolTip) + { this.currentTool = tool; this.ResetTimer(); this.StartTimer(toolTip.GetDelayTime(NativeMethods.TTDT_RESHOW), this.GetOneRunTickHandler((Timer sender) => this.Transit(SmEvent.ReshowDelayTimerExpired, tool))); return SmState.ReadyForReshow; } - private SmState ShowToolTip(IKeyboardToolTip tool, ToolTip toolTip) { + private SmState ShowToolTip(IKeyboardToolTip tool, ToolTip toolTip) + { string toolTipText = tool.GetCaptionForTool(toolTip); int autoPopDelay = toolTip.GetDelayTime(NativeMethods.TTDT_AUTOPOP); - if (!this.currentTool.IsHoveredWithMouse()) { + if (!this.currentTool.IsHoveredWithMouse()) + { toolTip.ShowKeyboardToolTip(toolTipText, this.currentTool, autoPopDelay); } this.StartTimer(autoPopDelay, this.GetOneRunTickHandler((Timer sender) => this.Transit(SmEvent.AutoPopupDelayTimerExpired, this.currentTool))); return SmState.Shown; } - private SmState ResetFsmToHidden(IKeyboardToolTip tool, ToolTip toolTip) { + private SmState ResetFsmToHidden(IKeyboardToolTip tool, ToolTip toolTip) + { return this.FullFsmReset(); } - private SmState DoNothing(IKeyboardToolTip tool, ToolTip toolTip) { + private SmState DoNothing(IKeyboardToolTip tool, ToolTip toolTip) + { return this.currentState; } - private SmState SetupInitShowTimer(IKeyboardToolTip tool, ToolTip toolTip) { + private SmState SetupInitShowTimer(IKeyboardToolTip tool, ToolTip toolTip) + { this.currentTool = tool; this.ResetTimer(); this.StartTimer(toolTip.GetDelayTime(NativeMethods.TTDT_INITIAL), this.GetOneRunTickHandler((Timer sender) => this.Transit(SmEvent.InitialDelayTimerExpired, this.currentTool))); @@ -191,15 +226,18 @@ private SmState SetupInitShowTimer(IKeyboardToolTip tool, ToolTip toolTip) { return SmState.ReadyForInitShow; } - private void StartTimer(int interval, EventHandler eventHandler) { + private void StartTimer(int interval, EventHandler eventHandler) + { this.timer.Interval = interval; this.timer.Tick += eventHandler; this.timer.Start(); } - private EventHandler GetOneRunTickHandler(Action handler) { + private EventHandler GetOneRunTickHandler(Action handler) + { EventHandler wrapper = null; - wrapper = (object sender, EventArgs eventArgs) => { + wrapper = (object sender, EventArgs eventArgs) => + { this.timer.Stop(); this.timer.Tick -= wrapper; handler(this.timer); @@ -207,34 +245,44 @@ private EventHandler GetOneRunTickHandler(Action handler) { return wrapper; } - private void Transit(SmEvent @event, IKeyboardToolTip source) { + private void Transit(SmEvent @event, IKeyboardToolTip source) + { Debug.Assert(transitions.ContainsKey(new SmTransition(this.currentState, @event)), "Unsupported KeyboardToolTipFsmTransition!"); bool fullFsmResetRequired = false; - try { + try + { ToolTip toolTip = this.toolToTip[source]; - if ((this.currentTool == null || this.currentTool.CanShowToolTipsNow()) && toolTip != null) { + if ((this.currentTool == null || this.currentTool.CanShowToolTipsNow()) && toolTip != null) + { Func transitionFunction = transitions[new SmTransition(this.currentState, @event)]; this.currentState = transitionFunction(source, toolTip); } - else { + else + { fullFsmResetRequired = true; } } - catch { + catch + { fullFsmResetRequired = true; throw; } - finally { - if (fullFsmResetRequired) { + finally + { + if (fullFsmResetRequired) + { this.FullFsmReset(); } } } - private SmState FullFsmReset() { - if (this.currentState == SmState.Shown && this.currentTool != null) { + private SmState FullFsmReset() + { + if (this.currentState == SmState.Shown && this.currentTool != null) + { ToolTip currentToolTip = this.toolToTip[this.currentTool]; - if (currentToolTip != null) { + if (currentToolTip != null) + { currentToolTip.HideToolTip(this.currentTool); } } @@ -243,32 +291,40 @@ private SmState FullFsmReset() { return this.currentState = SmState.Hidden; } - private void ResetTimer() { + private void ResetTimer() + { this.timer.ClearTimerTickHandlers(); this.timer.Stop(); } - private void Reset(ToolTip toolTipToReset) { - if (toolTipToReset == null || (this.currentTool != null && this.toolToTip[this.currentTool] == toolTipToReset)) { + private void Reset(ToolTip toolTipToReset) + { + if (toolTipToReset == null || (this.currentTool != null && this.toolToTip[this.currentTool] == toolTipToReset)) + { this.FullFsmReset(); } } - private void StartTracking(IKeyboardToolTip tool, ToolTip toolTip) { + private void StartTracking(IKeyboardToolTip tool, ToolTip toolTip) + { this.toolToTip[tool] = toolTip; } - private void StopTracking(IKeyboardToolTip tool, ToolTip toolTip) { + private void StopTracking(IKeyboardToolTip tool, ToolTip toolTip) + { this.toolToTip.Remove(tool, toolTip); } - private void OnFormDeactivation(ToolTip sender) { - if (this.currentTool != null && this.toolToTip[this.currentTool] == sender) { + private void OnFormDeactivation(ToolTip sender) + { + if (this.currentTool != null && this.toolToTip[this.currentTool] == sender) + { this.FullFsmReset(); } } - private enum SmEvent : byte { + private enum SmEvent : byte + { FocusedTool, LeftTool, InitialDelayTimerExpired, // internal @@ -277,7 +333,8 @@ private enum SmEvent : byte { RefocusWaitDelayExpired // internal } - private enum SmState : byte { + private enum SmState : byte + { Hidden, ReadyForInitShow, Shown, @@ -285,24 +342,29 @@ private enum SmState : byte { WaitForRefocus } - private struct SmTransition : IEquatable { + private struct SmTransition : IEquatable + { private readonly SmState currentState; private readonly SmEvent @event; - public SmTransition(SmState currentState, SmEvent @event) { + public SmTransition(SmState currentState, SmEvent @event) + { this.currentState = currentState; this.@event = @event; } - public bool Equals(SmTransition other) { + public bool Equals(SmTransition other) + { return this.currentState == other.currentState && this.@event == other.@event; } - public override bool Equals(object obj) { + public override bool Equals(object obj) + { return obj is SmTransition && this.Equals((SmTransition)obj); } - public override int GetHashCode() { + public override int GetHashCode() + { return (byte)this.currentState << 16 | (byte)this.@event; } } @@ -312,15 +374,20 @@ private sealed class InternalStateMachineTimer : Timer public void ClearTimerTickHandlers() => _onTimer = null; } - private sealed class ToolToTipDictionary { + private sealed class ToolToTipDictionary + { private ConditionalWeakTable> table = new ConditionalWeakTable>(); - public ToolTip this[IKeyboardToolTip tool] { - get { + public ToolTip this[IKeyboardToolTip tool] + { + get + { WeakReference toolTipReference; ToolTip toolTip = null; - if (this.table.TryGetValue(tool, out toolTipReference)) { - if (!toolTipReference.TryGetTarget(out toolTip)) { + if (this.table.TryGetValue(tool, out toolTipReference)) + { + if (!toolTipReference.TryGetTarget(out toolTip)) + { // removing dead reference this.table.Remove(tool); } @@ -328,27 +395,35 @@ public ToolTip this[IKeyboardToolTip tool] { return toolTip; } - set { + set + { WeakReference toolTipReference; - if (this.table.TryGetValue(tool, out toolTipReference)) { + if (this.table.TryGetValue(tool, out toolTipReference)) + { toolTipReference.SetTarget(value); } - else { + else + { this.table.Add(tool, new WeakReference(value)); } } } - public void Remove(IKeyboardToolTip tool, ToolTip toolTip) { + public void Remove(IKeyboardToolTip tool, ToolTip toolTip) + { WeakReference toolTipReference; ToolTip existingToolTip; - if (this.table.TryGetValue(tool, out toolTipReference)) { - if (toolTipReference.TryGetTarget(out existingToolTip)) { - if (existingToolTip == toolTip) { + if (this.table.TryGetValue(tool, out toolTipReference)) + { + if (toolTipReference.TryGetTarget(out existingToolTip)) + { + if (existingToolTip == toolTip) + { this.table.Remove(tool); } } - else { + else + { // removing dead reference this.table.Remove(tool); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Keys.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Keys.cs index d3284f033b2..4e0345b20a4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Keys.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Keys.cs @@ -174,821 +174,821 @@ public enum Keys /// The IME NonConvert key. /// IMENonconvert = 0x1D, - + /// /// The IME Accept key. /// IMEAccept = 0x1E, - + /// /// The IME Accept key. /// IMEAceept = IMEAccept, - + /// /// The IME Mode change request. /// IMEModeChange = 0x1F, - + /// /// The SPACEBAR key. /// Space = 0x20, - + /// /// The PAGE UP key. /// Prior = 0x21, - + /// /// The PAGE UP key. /// PageUp = Prior, - + /// /// The PAGE DOWN key. /// Next = 0x22, - + /// /// The PAGE DOWN key. /// PageDown = Next, - + /// /// The END key. /// End = 0x23, - + /// /// The HOME key. /// Home = 0x24, - + /// /// The LEFT ARROW key. /// Left = 0x25, - + /// /// The UP ARROW key. /// Up = 0x26, - + /// /// The RIGHT ARROW key. /// Right = 0x27, - + /// /// The DOWN ARROW key. /// Down = 0x28, - + /// /// The SELECT key. /// Select = 0x29, - + /// /// The PRINT key. /// Print = 0x2A, - + /// /// The EXECUTE key. /// Execute = 0x2B, - + /// /// The PRINT SCREEN key. /// Snapshot = 0x2C, - + /// /// The PRINT SCREEN key. /// PrintScreen = Snapshot, - + /// /// The INS key. /// Insert = 0x2D, - + /// /// The DEL key. /// Delete = 0x2E, - + /// /// The HELP key. /// Help = 0x2F, - + /// /// The 0 key. /// D0 = 0x30, // 0 - + /// /// The 1 key. /// D1 = 0x31, // 1 - + /// /// The 2 key. /// D2 = 0x32, // 2 - + /// /// The 3 key. /// D3 = 0x33, // 3 - + /// /// The 4 key. /// D4 = 0x34, // 4 - + /// /// The 5 key. /// D5 = 0x35, // 5 - + /// /// The 6 key. /// D6 = 0x36, // 6 - + /// /// The 7 key. /// D7 = 0x37, // 7 - + /// /// The 8 key. /// D8 = 0x38, // 8 - + /// /// The 9 key. /// D9 = 0x39, // 9 - + /// /// The A key. /// A = 0x41, - + /// /// The B key. /// B = 0x42, - + /// /// The C key. /// C = 0x43, - + /// /// The D key. /// D = 0x44, - + /// /// The E key. /// E = 0x45, - + /// /// The F key. /// F = 0x46, - + /// /// The G key. /// G = 0x47, - + /// /// The H key. /// H = 0x48, - + /// /// The I key. /// I = 0x49, - + /// /// The J key. /// J = 0x4A, - + /// /// The K key. /// K = 0x4B, - + /// /// The L key. /// L = 0x4C, - + /// /// The M key. /// M = 0x4D, - + /// /// The N key. /// N = 0x4E, - + /// /// The O key. /// O = 0x4F, - + /// /// The P key. /// P = 0x50, - + /// /// The Q key. /// Q = 0x51, - + /// /// The R key. /// R = 0x52, - + /// /// The S key. /// S = 0x53, - + /// /// The T key. /// T = 0x54, - + /// /// The U key. /// U = 0x55, - + /// /// The V key. /// V = 0x56, - + /// /// The W key. /// W = 0x57, - + /// /// The X key. /// X = 0x58, - + /// /// The Y key. /// Y = 0x59, - + /// /// The Z key. /// Z = 0x5A, - + /// /// The left Windows logo key (Microsoft Natural Keyboard). /// LWin = 0x5B, - + /// /// The right Windows logo key (Microsoft Natural Keyboard). /// RWin = 0x5C, - + /// /// The Application key (Microsoft Natural Keyboard). /// - + Apps = 0x5D, - + /// /// The Computer Sleep key. /// Sleep = 0x5F, - + /// /// The 0 key on the numeric keypad. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] // PM team has reviewed and decided on naming changes already NumPad0 = 0x60, - + /// /// The 1 key on the numeric keypad. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] // PM team has reviewed and decided on naming changes already NumPad1 = 0x61, - + /// /// The 2 key on the numeric keypad. /// NumPad2 = 0x62, - + /// /// The 3 key on the numeric keypad. /// NumPad3 = 0x63, - + /// /// The 4 key on the numeric keypad. /// NumPad4 = 0x64, - + /// /// The 5 key on the numeric keypad. /// NumPad5 = 0x65, - + /// /// The 6 key on the numeric keypad. /// NumPad6 = 0x66, - + /// /// The 7 key on the numeric keypad. /// NumPad7 = 0x67, - + /// /// The 8 key on the numeric keypad. /// NumPad8 = 0x68, - + /// /// The 9 key on the numeric keypad. /// NumPad9 = 0x69, - + /// /// The Multiply key. /// Multiply = 0x6A, - + /// /// The Add key. /// Add = 0x6B, - + /// /// The Separator key. /// Separator = 0x6C, - + /// /// The Subtract key. /// Subtract = 0x6D, - + /// /// The Decimal key. /// Decimal = 0x6E, - + /// /// The Divide key. /// Divide = 0x6F, - + /// /// The F1 key. /// F1 = 0x70, - + /// /// The F2 key. /// F2 = 0x71, - + /// /// The F3 key. /// F3 = 0x72, - + /// /// The F4 key. /// F4 = 0x73, - + /// /// The F5 key. /// F5 = 0x74, - + /// /// The F6 key. /// F6 = 0x75, - + /// /// The F7 key. /// F7 = 0x76, - + /// /// The F8 key. /// F8 = 0x77, - + /// /// The F9 key. /// F9 = 0x78, - + /// /// The F10 key. /// F10 = 0x79, - + /// /// The F11 key. /// F11 = 0x7A, - + /// /// The F12 key. /// F12 = 0x7B, - + /// /// The F13 key. /// F13 = 0x7C, - + /// /// The F14 key. /// F14 = 0x7D, - + /// /// The F15 key. /// F15 = 0x7E, - + /// /// The F16 key. /// F16 = 0x7F, - + /// /// The F17 key. /// F17 = 0x80, - + /// /// The F18 key. /// F18 = 0x81, - + /// /// The F19 key. /// F19 = 0x82, - + /// /// The F20 key. /// F20 = 0x83, - + /// /// The F21 key. /// F21 = 0x84, - + /// /// The F22 key. /// F22 = 0x85, - + /// /// The F23 key. /// F23 = 0x86, - + /// /// The F24 key. /// F24 = 0x87, - + /// /// The NUM LOCK key. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] // PM team has reviewed and decided on naming changes already NumLock = 0x90, - + /// /// The SCROLL LOCK key. /// Scroll = 0x91, - + /// /// The left SHIFT key. /// LShiftKey = 0xA0, - + /// /// The right SHIFT key. /// RShiftKey = 0xA1, - + /// /// The left CTRL key. /// LControlKey = 0xA2, - + /// /// The right CTRL key. /// RControlKey = 0xA3, - + /// /// The left ALT key. /// LMenu = 0xA4, - + /// /// The right ALT key. /// RMenu = 0xA5, - + /// /// The Browser Back key. /// BrowserBack = 0xA6, - + /// /// The Browser Forward key. /// - BrowserForward= 0xA7, - + BrowserForward = 0xA7, + /// /// The Browser Refresh key. /// - BrowserRefresh= 0xA8, - + BrowserRefresh = 0xA8, + /// /// The Browser Stop key. /// BrowserStop = 0xA9, - + /// /// The Browser Search key. /// BrowserSearch = 0xAA, - + /// /// The Browser Favorites key. /// BrowserFavorites = 0xAB, - + /// /// The Browser Home key. /// BrowserHome = 0xAC, - + /// /// The Volume Mute key. /// VolumeMute = 0xAD, - + /// /// The Volume Down key. /// VolumeDown = 0xAE, - + /// /// The Volume Up key. /// VolumeUp = 0xAF, - + /// /// The Media Next Track key. /// MediaNextTrack = 0xB0, - + /// /// The Media Previous Track key. /// MediaPreviousTrack = 0xB1, - + /// /// The Media Stop key. /// MediaStop = 0xB2, - + /// /// The Media Play Pause key. /// MediaPlayPause = 0xB3, - + /// /// The Launch Mail key. /// LaunchMail = 0xB4, - + /// /// The Select Media key. /// SelectMedia = 0xB5, - + /// /// The Launch Application1 key. /// LaunchApplication1 = 0xB6, - + /// /// The Launch Application2 key. /// LaunchApplication2 = 0xB7, - + /// /// The Oem Semicolon key. /// OemSemicolon = 0xBA, - + /// /// The Oem 1 key. /// Oem1 = OemSemicolon, - + /// /// The Oem plus key. /// Oemplus = 0xBB, - + /// /// The Oem comma key. /// Oemcomma = 0xBC, - + /// /// The Oem Minus key. /// OemMinus = 0xBD, - + /// /// The Oem Period key. /// OemPeriod = 0xBE, - + /// /// The Oem Question key. /// OemQuestion = 0xBF, - + /// /// The Oem 2 key. /// Oem2 = OemQuestion, - + /// /// The Oem tilde key. /// Oemtilde = 0xC0, - + /// /// The Oem 3 key. /// Oem3 = Oemtilde, - + /// /// The Oem Open Brackets key. /// OemOpenBrackets = 0xDB, - + /// /// The Oem 4 key. /// Oem4 = OemOpenBrackets, - + /// /// The Oem Pipe key. /// OemPipe = 0xDC, - + /// /// The Oem 5 key. /// Oem5 = OemPipe, - + /// /// The Oem Close Brackets key. /// OemCloseBrackets = 0xDD, - + /// /// The Oem 6 key. /// Oem6 = OemCloseBrackets, - + /// /// The Oem Quotes key. /// OemQuotes = 0xDE, - + /// /// The Oem 7 key. /// Oem7 = OemQuotes, - + /// /// The Oem8 key. /// Oem8 = 0xDF, - + /// /// The Oem Backslash key. /// OemBackslash = 0xE2, - + /// /// The Oem 102 key. /// Oem102 = OemBackslash, - + /// /// The PROCESS KEY key. /// ProcessKey = 0xE5, - + /// /// The Packet KEY key. /// Packet = 0xE7, - + /// /// The ATTN key. /// Attn = 0xF6, - + /// /// The CRSEL key. /// Crsel = 0xF7, - + /// /// The EXSEL key. /// Exsel = 0xF8, - + /// /// The ERASE EOF key. /// EraseEof = 0xF9, - + /// /// The PLAY key. /// Play = 0xFA, - + /// /// The ZOOM key. /// Zoom = 0xFB, - + /// /// A constant reserved for future use. /// NoName = 0xFC, - + /// /// The PA1 key. /// Pa1 = 0xFD, - + /// /// The CLEAR key. /// OemClear = 0xFE, - + /// /// The SHIFT modifier key. /// Shift = 0x00010000, - + /// /// The CTRL modifier key. /// Control = 0x00020000, - + /// /// The ALT modifier key. /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/KeysConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/KeysConverter.cs index 5ba5dd8458b..a5e2042de63 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/KeysConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/KeysConverter.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Text; using Microsoft.Win32; using System.Collections; @@ -20,11 +21,12 @@ namespace System.Windows.Forms { /// Provides a type converter to convert objects to and from various /// other representations. /// - public class KeysConverter : TypeConverter, IComparer { + public class KeysConverter : TypeConverter, IComparer + { private IDictionary keyNames; private List displayOrder; private StandardValuesCollection values; - + private const Keys FirstDigit = System.Windows.Forms.Keys.D0; private const Keys LastDigit = System.Windows.Forms.Keys.D9; private const Keys FirstAscii = System.Windows.Forms.Keys.A; @@ -32,12 +34,14 @@ public class KeysConverter : TypeConverter, IComparer { private const Keys FirstNumpadDigit = System.Windows.Forms.Keys.NumPad0; private const Keys LastNumpadDigit = System.Windows.Forms.Keys.NumPad9; - private void AddKey(string key, Keys value ) { + private void AddKey(string key, Keys value) + { keyNames[key] = value; displayOrder.Add(key); } - private void Initialize() { + private void Initialize() + { keyNames = new Hashtable(34); displayOrder = new List(34); @@ -84,9 +88,12 @@ private void Initialize() { /// Access to a lookup table of name/value pairs for keys. These are localized /// names. /// - private IDictionary KeyNames { - get { - if (keyNames == null) { + private IDictionary KeyNames + { + get + { + if (keyNames == null) + { Debug.Assert(displayOrder == null); Initialize(); } @@ -94,33 +101,40 @@ private IDictionary KeyNames { } } - private List DisplayOrder { - get { - if (displayOrder == null) { + private List DisplayOrder + { + get + { + if (displayOrder == null) + { Debug.Assert(keyNames == null); Initialize(); } return displayOrder; } } - + /// /// Determines if this converter can convert an object in the given source /// type to the native type of the converter. /// - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { - if (sourceType == typeof(string) || sourceType == typeof(Enum[])) { + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + { + if (sourceType == typeof(string) || sourceType == typeof(Enum[])) + { return true; } return base.CanConvertFrom(context, sourceType); } - + /// /// Gets a value indicating whether this converter can /// convert an object to the given destination type using the context. /// - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { - if (destinationType == typeof(Enum[])) { + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) + { + if (destinationType == typeof(Enum[])) + { return true; } return base.CanConvertTo(context, destinationType); @@ -129,87 +143,101 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati /// /// Compares two key values for equivalence. /// - public int Compare(object a, object b) { + public int Compare(object a, object b) + { return string.Compare(ConvertToString(a), ConvertToString(b), false, CultureInfo.InvariantCulture); } /// /// Converts the given object to the converter's native type. /// - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - - if (value is string) { - + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + { + + if (value is string) + { + string text = ((string)value).Trim(); - - if (text.Length == 0) { + + if (text.Length == 0) + { return null; } - else { - + else + { + // Parse an array of key tokens. // - string[] tokens = text.Split(new char[] {'+'}); - for (int i = 0; i < tokens.Length; i++) { + string[] tokens = text.Split(new char[] { '+' }); + for (int i = 0; i < tokens.Length; i++) + { tokens[i] = tokens[i].Trim(); } - + // Now lookup each key token in our key hashtable. // Keys key = (Keys)0; bool foundKeyCode = false; - - for (int i = 0; i < tokens.Length; i++) { + + for (int i = 0; i < tokens.Length; i++) + { object obj = KeyNames[tokens[i]]; - - if (obj == null) { - + + if (obj == null) + { + // Key was not found in our table. See if it is a valid value in // the Keys enum. // obj = Enum.Parse(typeof(Keys), tokens[i]); } - - if (obj != null) { + + if (obj != null) + { Keys currentKey = (Keys)obj; - - if ((currentKey & Keys.KeyCode) != 0) { - + + if ((currentKey & Keys.KeyCode) != 0) + { + // We found a match. If we have previously found a // key code, then check to see that this guy // isn't a key code (it is illegal to have, say, // "A + B" // - if (foundKeyCode) { + if (foundKeyCode) + { throw new FormatException(SR.KeysConverterInvalidKeyCombination); } foundKeyCode = true; } - + // Now OR the key into our current key // key |= currentKey; } - else { - + else + { + // We did not match this key. Report this as an error too. // throw new FormatException(string.Format(SR.KeysConverterInvalidKeyName, tokens[i])); - + } } - + return (object)key; } } - else if (value is Enum[]) { + else if (value is Enum[]) + { long finalValue = 0; - foreach(Enum e in (Enum[])value) { + foreach (Enum e in (Enum[])value) + { finalValue |= Convert.ToInt64(e, CultureInfo.InvariantCulture); } return Enum.ToObject(typeof(Keys), finalValue); } - + return base.ConvertFrom(context, culture, value); } @@ -220,17 +248,22 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// - [SuppressMessage("Microsoft.Performance", "CA1803:AvoidCostlyCallsWherePossible")] - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) { + [SuppressMessage("Microsoft.Performance", "CA1803:AvoidCostlyCallsWherePossible")] + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == null) + { throw new ArgumentNullException(nameof(destinationType)); } - if (value is Keys || value is int) { + if (value is Keys || value is int) + { bool asString = destinationType == typeof(string); bool asEnum = false; - if (!asString) asEnum = destinationType == typeof(Enum[]); - if (asString || asEnum) { + if (!asString) + asEnum = destinationType == typeof(Enum[]); + if (asString || asEnum) + { Keys key = (Keys)value; bool added = false; ArrayList terms = new ArrayList(); @@ -239,45 +272,55 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul // First, iterate through and do the modifiers. These are // additive, so we support things like Ctrl + Alt // - for (int i = 0; i < DisplayOrder.Count; i++) { + for (int i = 0; i < DisplayOrder.Count; i++) + { string keyString = (string)DisplayOrder[i]; Keys keyValue = (Keys)keyNames[keyString]; - if (((int)(keyValue) & (int)modifiers) != 0) { + if (((int)(keyValue) & (int)modifiers) != 0) + { - if (asString) { - if (added) { + if (asString) + { + if (added) + { terms.Add("+"); } terms.Add((string)keyString); } - else { + else + { terms.Add(keyValue); } - + added = true; } } - + // Now reset and do the key values. Here, we quit if // we find a match. // Keys keyOnly = (key & Keys.KeyCode); bool foundKey = false; - - if (added && asString) { + + if (added && asString) + { terms.Add("+"); } - for (int i = 0; i < DisplayOrder.Count; i++) { + for (int i = 0; i < DisplayOrder.Count; i++) + { string keyString = (string)DisplayOrder[i]; Keys keyValue = (Keys)keyNames[keyString]; - if (keyValue.Equals(keyOnly)) { + if (keyValue.Equals(keyOnly)) + { - if (asString) { + if (asString) + { terms.Add((string)keyString); } - else { + else + { terms.Add(keyValue); } added = true; @@ -285,59 +328,68 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul break; } } - + // Finally, if the key wasn't in our list, add it to // the end anyway. Here we just pull the key value out // of the enum. // - if (!foundKey && Enum.IsDefined(typeof(Keys), (int)keyOnly)) { - if (asString) { + if (!foundKey && Enum.IsDefined(typeof(Keys), (int)keyOnly)) + { + if (asString) + { terms.Add(((Enum)keyOnly).ToString()); } - else { + else + { terms.Add((Enum)keyOnly); } } - if (asString) { + if (asString) + { StringBuilder b = new StringBuilder(32); - foreach(string t in terms) { + foreach (string t in terms) + { b.Append(t); } return b.ToString(); } - else { + else + { return (Enum[])terms.ToArray(typeof(Enum)); } } } - + return base.ConvertTo(context, culture, value, destinationType); } - + /// /// Retrieves a collection containing a set of standard values /// for the data type this validator is designed for. This /// will return null if the data type does not support a /// standard set of values. /// - public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { - if (values == null) { + public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) + { + if (values == null) + { ArrayList list = new ArrayList(); - + ICollection keys = KeyNames.Values; - - foreach (object o in keys) { + + foreach (object o in keys) + { list.Add(o); } - + list.Sort(this); - + values = new StandardValuesCollection(list.ToArray()); } return values; } - + /// /// Determines if the list of standard values returned from /// GetStandardValues is an exclusive list. If the list @@ -346,15 +398,17 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex /// then there are other valid values besides the list of /// standard values GetStandardValues provides. /// - public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { + public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) + { return false; } - + /// /// Determines if this object supports a standard set of values /// that can be picked from a list. /// - public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { + public override bool GetStandardValuesSupported(ITypeDescriptorContext context) + { return true; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs index 5cb57efeccb..8b2b54541b7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Collections.Specialized; @@ -38,21 +39,22 @@ namespace System.Windows.Forms { SRDescription(nameof(SR.DescriptionLabel)) ] // If not for FormatControl, we could inherit from ButtonBase and get foreground images for free. - public class Label : Control, IAutomationLiveRegion { + public class Label : Control, IAutomationLiveRegion + { private static readonly object EVENT_TEXTALIGNCHANGED = new object(); private static readonly BitVector32.Section StateUseMnemonic = BitVector32.CreateSection(1); - private static readonly BitVector32.Section StateAutoSize = BitVector32.CreateSection(1, StateUseMnemonic); - private static readonly BitVector32.Section StateAnimating = BitVector32.CreateSection(1, StateAutoSize); - private static readonly BitVector32.Section StateFlatStyle = BitVector32.CreateSection((int)FlatStyle.System, StateAnimating); + private static readonly BitVector32.Section StateAutoSize = BitVector32.CreateSection(1, StateUseMnemonic); + private static readonly BitVector32.Section StateAnimating = BitVector32.CreateSection(1, StateAutoSize); + private static readonly BitVector32.Section StateFlatStyle = BitVector32.CreateSection((int)FlatStyle.System, StateAnimating); private static readonly BitVector32.Section StateBorderStyle = BitVector32.CreateSection((int)BorderStyle.Fixed3D, StateFlatStyle); private static readonly BitVector32.Section StateAutoEllipsis = BitVector32.CreateSection(1, StateBorderStyle); - private static readonly int PropImageList = PropertyStore.CreateKey(); - private static readonly int PropImage = PropertyStore.CreateKey(); + private static readonly int PropImageList = PropertyStore.CreateKey(); + private static readonly int PropImage = PropertyStore.CreateKey(); - private static readonly int PropTextAlign = PropertyStore.CreateKey(); + private static readonly int PropTextAlign = PropertyStore.CreateKey(); private static readonly int PropImageAlign = PropertyStore.CreateKey(); private static readonly int PropImageIndex = PropertyStore.CreateKey(); @@ -68,16 +70,16 @@ public class Label : Control, IAutomationLiveRegion { // BitVector32 labelState = new BitVector32(); - int requestedHeight; - int requestedWidth; - LayoutUtils.MeasureTextCache textMeasurementCache; + int requestedHeight; + int requestedWidth; + LayoutUtils.MeasureTextCache textMeasurementCache; //Tooltip is shown only if the Text in the Label is cut. internal bool showToolTip = false; - ToolTip textToolTip; + ToolTip textToolTip; // This bool suggests that the User has added a toolTip to this label // In such a case we should not show the AutoEllipsis tooltip. - bool controlToolTip = false; + bool controlToolTip = false; AutomationLiveSetting liveSetting; // } End Members @@ -89,10 +91,11 @@ public class Label : Control, IAutomationLiveRegion { /// /// public Label() - : base() { + : base() + { // this class overrides GetPreferredSizeCore, let Control automatically cache the result - SetState2(STATE2_USEPREFERREDSIZECACHE, true); - + SetState2(STATE2_USEPREFERREDSIZECACHE, true); + SetStyle(ControlStyles.UserPaint | ControlStyles.SupportsTransparentBackColor | ControlStyles.OptimizedDoubleBuffer, IsOwnerDraw()); @@ -102,9 +105,9 @@ public Label() SetStyle(ControlStyles.ResizeRedraw, true); - CommonProperties.SetSelfAutoSizeInDefaultLayout(this,true); + CommonProperties.SetSelfAutoSizeInDefaultLayout(this, true); - labelState[StateFlatStyle] = (int)FlatStyle.Standard; + labelState[StateFlatStyle] = (int)FlatStyle.Standard; labelState[StateUseMnemonic] = 1; labelState[StateBorderStyle] = (int)BorderStyle.None; @@ -128,12 +131,16 @@ public Label() EditorBrowsable(EditorBrowsableState.Always), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible) ] - public override bool AutoSize { - get { + public override bool AutoSize + { + get + { return base.AutoSize; } - set { - if (AutoSize != value) { + set + { + if (AutoSize != value) + { base.AutoSize = value; AdjustSize(); } @@ -159,27 +166,34 @@ public override bool AutoSize { EditorBrowsable(EditorBrowsableState.Always), SRDescription(nameof(SR.LabelAutoEllipsisDescr)) ] - public bool AutoEllipsis { - get { + public bool AutoEllipsis + { + get + { return labelState[StateAutoEllipsis] != 0; } - set { - if (AutoEllipsis != value) { + set + { + if (AutoEllipsis != value) + { labelState[StateAutoEllipsis] = value ? 1 : 0; MeasureTextCache.InvalidateCache(); OnAutoEllipsisChanged(/*EventArgs.Empty*/); - - if (value) { - if (textToolTip == null) { - textToolTip = new ToolTip(); + + if (value) + { + if (textToolTip == null) + { + textToolTip = new ToolTip(); } } - - - if (ParentInternal != null) { - LayoutTransaction.DoLayoutIf(AutoSize,ParentInternal, this, PropertyNames.AutoEllipsis); + + + if (ParentInternal != null) + { + LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.AutoEllipsis); } Invalidate(); } @@ -197,17 +211,21 @@ public bool AutoEllipsis { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.LabelBackgroundImageDescr)) ] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged { + new public event EventHandler BackgroundImageChanged + { add => base.BackgroundImageChanged += value; remove => base.BackgroundImageChanged -= value; } @@ -220,17 +238,21 @@ public override Image BackgroundImage { [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { + new public event EventHandler BackgroundImageLayoutChanged + { add => base.BackgroundImageLayoutChanged += value; remove => base.BackgroundImageLayoutChanged -= value; } @@ -246,22 +268,29 @@ public override ImageLayout BackgroundImageLayout { DispId(NativeMethods.ActiveX.DISPID_BORDERSTYLE), SRDescription(nameof(SR.LabelBorderDescr)) ] - public virtual BorderStyle BorderStyle { - get { + public virtual BorderStyle BorderStyle + { + get + { return (BorderStyle)labelState[StateBorderStyle]; } - set { + set + { //valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(BorderStyle)); } - if (BorderStyle != value) { + if (BorderStyle != value) + { labelState[StateBorderStyle] = (int)value; - if (ParentInternal != null) { + if (ParentInternal != null) + { LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.BorderStyle); } - if (AutoSize) { + if (AutoSize) + { AdjustSize(); } RecreateHandle(); @@ -273,8 +302,10 @@ public virtual BorderStyle BorderStyle { /// Determines whether the current state of the control allows for rendering text using TextRenderer (GDI). /// See LinkLabel implementation for details. /// - internal virtual bool CanUseTextRenderer { - get{ + internal virtual bool CanUseTextRenderer + { + get + { return true; } } @@ -282,12 +313,15 @@ internal virtual bool CanUseTextRenderer { /// /// Overrides Control. A Label is a Win32 STATIC control, which we setup here. /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ClassName = "STATIC"; - if (OwnerDraw) { + if (OwnerDraw) + { // An unfortunate side effect of this style is Windows sends us WM_DRAWITEM // messages instead of WM_PAINT, but since Windows insists on repainting // *without* a WM_PAINT after SetWindowText, I don't see much choice. @@ -300,8 +334,10 @@ protected override CreateParams CreateParams { } - if (!OwnerDraw) { - switch(TextAlign) { + if (!OwnerDraw) + { + switch (TextAlign) + { case ContentAlignment.TopLeft: case ContentAlignment.MiddleLeft: case ContentAlignment.BottomLeft: @@ -324,7 +360,8 @@ protected override CreateParams CreateParams { else cp.Style |= NativeMethods.SS_LEFT; - switch (BorderStyle) { + switch (BorderStyle) + { case BorderStyle.FixedSingle: cp.Style |= NativeMethods.WS_BORDER; break; @@ -340,14 +377,18 @@ protected override CreateParams CreateParams { } } - protected override ImeMode DefaultImeMode { - get { + protected override ImeMode DefaultImeMode + { + get + { return ImeMode.Disable; } } - protected override Padding DefaultMargin { - get { + protected override Padding DefaultMargin + { + get + { return new Padding(3, 0, 3, 0); } } @@ -356,8 +397,10 @@ protected override Padding DefaultMargin { /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(100, AutoSize ? PreferredHeight : 23); } } @@ -367,18 +410,22 @@ protected override Size DefaultSize { DefaultValue(FlatStyle.Standard), SRDescription(nameof(SR.ButtonFlatStyleDescr)) ] - public FlatStyle FlatStyle { - get { + public FlatStyle FlatStyle + { + get + { return (FlatStyle)labelState[StateFlatStyle]; } - set { + set + { //valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(value, (int)value, (int)FlatStyle.Flat, (int)FlatStyle.System)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(FlatStyle)); } - if (labelState[StateFlatStyle] != (int)value) { + if (labelState[StateFlatStyle] != (int)value) + { bool needRecreate = (labelState[StateFlatStyle] == (int)FlatStyle.System) || (value == FlatStyle.System); labelState[StateFlatStyle] = (int)value; @@ -387,15 +434,18 @@ public FlatStyle FlatStyle { | ControlStyles.SupportsTransparentBackColor | ControlStyles.OptimizedDoubleBuffer, OwnerDraw); - if (needRecreate) { + if (needRecreate) + { // this will clear the preferred size cache - it's OK if the parent is null - it would be a NOP. LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.BorderStyle); - if (AutoSize) { + if (AutoSize) + { AdjustSize(); } - RecreateHandle(); + RecreateHandle(); } - else { + else + { Refresh(); } } @@ -412,25 +462,32 @@ public FlatStyle FlatStyle { SRDescription(nameof(SR.ButtonImageDescr)), SRCategory(nameof(SR.CatAppearance)) ] - public Image Image { - - - get { + public Image Image + { + + + get + { Image image = (Image)Properties.GetObject(PropImage); - if (image == null && ImageList != null && ImageIndexer.ActualIndex >= 0) { + if (image == null && ImageList != null && ImageIndexer.ActualIndex >= 0) + { return ImageList.Images[ImageIndexer.ActualIndex]; } - else { + else + { return image; } } - set { - if (Image != value) { + set + { + if (Image != value) + { StopAnimate(); Properties.SetObject(PropImage, value); - if (value != null) { + if (value != null) + { ImageIndex = -1; ImageList = null; } @@ -458,13 +515,17 @@ public Image Image { SRDescription(nameof(SR.ButtonImageIndexDescr)), SRCategory(nameof(SR.CatAppearance)) ] - public int ImageIndex { - get { + public int ImageIndex + { + get + { - if (ImageIndexer != null) { + if (ImageIndexer != null) + { int index = ImageIndexer.Index; - if (ImageList != null && (index >= ImageList.Images.Count)) { + if (ImageList != null && (index >= ImageList.Images.Count)) + { return ImageList.Images.Count - 1; } return index; @@ -472,12 +533,16 @@ public int ImageIndex { } return -1; } - set { - if (value < -1) { + set + { + if (value < -1) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(ImageIndex), value, -1)); } - if (ImageIndex != value) { - if (value != -1) { + if (ImageIndex != value) + { + if (value != -1) + { // Image.set calls ImageIndex = -1 Properties.SetObject(PropImage, null); } @@ -504,16 +569,21 @@ public int ImageIndex { SRDescription(nameof(SR.ButtonImageIndexDescr)), SRCategory(nameof(SR.CatAppearance)) ] - public string ImageKey { - get { + public string ImageKey + { + get + { - if (ImageIndexer != null) { - return ImageIndexer.Key; - } - return null; + if (ImageIndexer != null) + { + return ImageIndexer.Key; + } + return null; } - set { - if (ImageKey != value) { + set + { + if (ImageKey != value) + { // Image.set calls ImageIndex = -1 Properties.SetObject(PropImage, null); @@ -524,20 +594,24 @@ public string ImageKey { } } - internal LabelImageIndexer ImageIndexer{ - get { - bool found; - LabelImageIndexer imageIndexer = Properties.GetObject(PropImageIndex, out found) as LabelImageIndexer; + internal LabelImageIndexer ImageIndexer + { + get + { + bool found; + LabelImageIndexer imageIndexer = Properties.GetObject(PropImageIndex, out found) as LabelImageIndexer; - // Demand create the ImageIndexer property - if ((imageIndexer == null) || (!found)) { + // Demand create the ImageIndexer property + if ((imageIndexer == null) || (!found)) + { imageIndexer = new LabelImageIndexer(this); ImageIndexer = imageIndexer; - } + } - return imageIndexer; + return imageIndexer; } - set { + set + { Properties.SetObject(PropImageIndex, value); } @@ -554,12 +628,16 @@ internal LabelImageIndexer ImageIndexer{ RefreshProperties(RefreshProperties.Repaint), SRCategory(nameof(SR.CatAppearance)) ] - public ImageList ImageList { - get { + public ImageList ImageList + { + get + { return (ImageList)Properties.GetObject(PropImageList); } - set { - if (ImageList != value) { + set + { + if (ImageList != value) + { EventHandler recreateHandler = new EventHandler(ImageListRecreateHandle); EventHandler disposedHandler = new EventHandler(DetachImageList); @@ -567,14 +645,16 @@ public ImageList ImageList { // Remove the previous imagelist handle recreate handler // ImageList imageList = ImageList; - if (imageList != null) { + if (imageList != null) + { imageList.RecreateHandle -= recreateHandler; imageList.Disposed -= disposedHandler; } // Make sure we don't have an Image as well as an ImageList // - if (value != null) { + if (value != null) + { Properties.SetObject(PropImage, null); // Image.set calls ImageList = null } @@ -582,7 +662,8 @@ public ImageList ImageList { // Add the new imagelist handle recreate handler // - if (value != null) { + if (value != null) + { value.RecreateHandle += recreateHandler; value.Disposed += disposedHandler; } @@ -603,20 +684,26 @@ public ImageList ImageList { SRDescription(nameof(SR.ButtonImageAlignDescr)), SRCategory(nameof(SR.CatAppearance)) ] - public ContentAlignment ImageAlign { - get { + public ContentAlignment ImageAlign + { + get + { bool found; int imageAlign = Properties.GetInteger(PropImageAlign, out found); - if (found) { + if (found) + { return (ContentAlignment)imageAlign; } return ContentAlignment.MiddleCenter; } - set { - if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ContentAlignment)); + set + { + if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) + { + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ContentAlignment)); } - if(value != ImageAlign) { + if (value != ImageAlign) + { Properties.SetInteger(PropImageAlign, (int)value); LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.ImageAlign); Invalidate(); @@ -643,12 +730,16 @@ private Rectangle ImageBounds { Browsable(true), EditorBrowsable(EditorBrowsableState.Always) ] - public AutomationLiveSetting LiveSetting { - get { + public AutomationLiveSetting LiveSetting + { + get + { return liveSetting; } - set { - if (!ClientUtils.IsEnumValid(value, (int)value, (int)AutomationLiveSetting.Off, (int)AutomationLiveSetting.Assertive)) { + set + { + if (!ClientUtils.IsEnumValid(value, (int)value, (int)AutomationLiveSetting.Off, (int)AutomationLiveSetting.Assertive)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AutomationLiveSetting)); } liveSetting = value; @@ -656,53 +747,65 @@ public AutomationLiveSetting LiveSetting { } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public ImeMode ImeMode { - get { + new public ImeMode ImeMode + { + get + { return base.ImeMode; } - set { + set + { base.ImeMode = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler ImeModeChanged { + public new event EventHandler ImeModeChanged + { add => base.ImeModeChanged += value; remove => base.ImeModeChanged -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event KeyEventHandler KeyUp { + public new event KeyEventHandler KeyUp + { add => base.KeyUp += value; remove => base.KeyUp -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event KeyEventHandler KeyDown { + public new event KeyEventHandler KeyDown + { add => base.KeyDown += value; remove => base.KeyDown -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event KeyPressEventHandler KeyPress { + public new event KeyPressEventHandler KeyPress + { add => base.KeyPress += value; remove => base.KeyPress -= value; } - internal LayoutUtils.MeasureTextCache MeasureTextCache { - get { - if (textMeasurementCache == null) { + internal LayoutUtils.MeasureTextCache MeasureTextCache + { + get + { + if (textMeasurementCache == null) + { textMeasurementCache = new LayoutUtils.MeasureTextCache(); } return textMeasurementCache; } } - internal virtual bool OwnerDraw { - get { + internal virtual bool OwnerDraw + { + get + { return IsOwnerDraw(); } } @@ -719,7 +822,8 @@ internal virtual bool OwnerDraw { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.LabelPreferredHeightDescr)) ] - public virtual int PreferredHeight { + public virtual int PreferredHeight + { get { return PreferredSize.Height; } } @@ -735,7 +839,8 @@ public virtual int PreferredHeight { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.LabelPreferredWidthDescr)) ] - public virtual int PreferredWidth { + public virtual int PreferredWidth + { get { return PreferredSize.Width; } } @@ -746,16 +851,20 @@ public virtual int PreferredWidth { [Obsolete("This property has been deprecated. Use BackColor instead. http://go.microsoft.com/fwlink/?linkid=14202")] virtual new protected bool RenderTransparent { - get { - return((Control) this).RenderTransparent; + get + { + return ((Control)this).RenderTransparent; } - set { + set + { } } - private bool SelfSizing { - get { + private bool SelfSizing + { + get + { return CommonProperties.ShouldSelfSize(this); } } @@ -767,17 +876,21 @@ private bool SelfSizing { /// /// [DefaultValue(false), Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public bool TabStop { - get { + new public bool TabStop + { + get + { return base.TabStop; } - set { + set + { base.TabStop = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TabStopChanged { + new public event EventHandler TabStopChanged + { add => base.TabStopChanged += value; remove => base.TabStopChanged -= value; } @@ -794,27 +907,34 @@ private bool SelfSizing { DefaultValue(ContentAlignment.TopLeft), SRCategory(nameof(SR.CatAppearance)) ] - public virtual ContentAlignment TextAlign { - get { + public virtual ContentAlignment TextAlign + { + get + { bool found; int textAlign = Properties.GetInteger(PropTextAlign, out found); - if (found) { + if (found) + { return (ContentAlignment)textAlign; } return ContentAlignment.TopLeft; } - set { + set + { - if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) { + if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ContentAlignment)); } - if (TextAlign != value) { + if (TextAlign != value) + { Properties.SetInteger(PropTextAlign, (int)value); Invalidate(); //Change the TextAlignment for SystemDrawn Labels .... - if (!OwnerDraw) { + if (!OwnerDraw) + { RecreateHandle(); } OnTextAlignChanged(EventArgs.Empty); @@ -833,18 +953,22 @@ public virtual ContentAlignment TextAlign { Editor("System.ComponentModel.Design.MultilineStringEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), SettingsBindable(true) ] - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; } } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.LabelOnTextAlignChangedDescr))] - public event EventHandler TextAlignChanged { + public event EventHandler TextAlignChanged + { add => Events.AddHandler(EVENT_TEXTALIGNCHANGED, value); remove => Events.RemoveHandler(EVENT_TEXTALIGNCHANGED, value); @@ -858,17 +982,22 @@ public event EventHandler TextAlignChanged { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.UseCompatibleTextRenderingDescr)) ] - public bool UseCompatibleTextRendering { - get{ - if( CanUseTextRenderer ){ + public bool UseCompatibleTextRendering + { + get + { + if (CanUseTextRenderer) + { return base.UseCompatibleTextRenderingInt; } // Use compat text rendering (GDI+). return true; } - set{ - if( base.UseCompatibleTextRenderingInt != value ) { + set + { + if (base.UseCompatibleTextRenderingInt != value) + { base.UseCompatibleTextRenderingInt = value; AdjustSize(); } @@ -880,8 +1009,10 @@ public bool UseCompatibleTextRendering { /// This is provided for container controls to iterate through its children to set UseCompatibleTextRendering to the same /// value if the child control supports it. /// - internal override bool SupportsUseCompatibleTextRendering { - get { + internal override bool SupportsUseCompatibleTextRendering + { + get + { return true; } } @@ -895,37 +1026,45 @@ internal override bool SupportsUseCompatibleTextRendering { DefaultValue(true), SRCategory(nameof(SR.CatAppearance)) ] - public bool UseMnemonic { - get { + public bool UseMnemonic + { + get + { return labelState[StateUseMnemonic] != 0; } - set { - - if (UseMnemonic != value) { - labelState[StateUseMnemonic] = value ? 1 : 0; - MeasureTextCache.InvalidateCache(); - - - // The size of the label need to be adjusted when the Mnemonic - // is set irrespective of auto-sizing - using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.Text)) { - AdjustSize(); - Invalidate(); - } - - //set windowStyle directly instead of recreating handle to increase efficiency - if (IsHandleCreated) { - int style = this.WindowStyle; - if (!UseMnemonic) { - - style |= NativeMethods.SS_NOPREFIX; - } - else { - style &= ~NativeMethods.SS_NOPREFIX; - } - this.WindowStyle = style; - } + set + { + + if (UseMnemonic != value) + { + labelState[StateUseMnemonic] = value ? 1 : 0; + MeasureTextCache.InvalidateCache(); + + + // The size of the label need to be adjusted when the Mnemonic + // is set irrespective of auto-sizing + using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.Text)) + { + AdjustSize(); + Invalidate(); + } + + //set windowStyle directly instead of recreating handle to increase efficiency + if (IsHandleCreated) + { + int style = this.WindowStyle; + if (!UseMnemonic) + { + + style |= NativeMethods.SS_NOPREFIX; + } + else + { + style &= ~NativeMethods.SS_NOPREFIX; + } + this.WindowStyle = style; + } } } } @@ -935,8 +1074,10 @@ public bool UseMnemonic { /// Updates the control in response to events that could affect either /// the size of the control, or the size of the text within it. /// - internal void AdjustSize() { - if (!SelfSizing) { + internal void AdjustSize() + { + if (!SelfSizing) + { return; } @@ -946,7 +1087,8 @@ internal void AdjustSize() { // to fit around text, since this will cause us to lose the original anchored size. if (!AutoSize && ((this.Anchor & (AnchorStyles.Left | AnchorStyles.Right)) == (AnchorStyles.Left | AnchorStyles.Right) || - (this.Anchor & (AnchorStyles.Top | AnchorStyles.Bottom)) == (AnchorStyles.Top | AnchorStyles.Bottom))) { + (this.Anchor & (AnchorStyles.Top | AnchorStyles.Bottom)) == (AnchorStyles.Top | AnchorStyles.Bottom))) + { return; } @@ -954,36 +1096,46 @@ internal void AdjustSize() { // int saveHeight = requestedHeight; int saveWidth = requestedWidth; - try { + try + { Size preferredSize = (AutoSize) ? PreferredSize : new Size(saveWidth, saveHeight); Size = preferredSize; } - finally { + finally + { requestedHeight = saveHeight; requestedWidth = saveWidth; } } - internal void Animate() { + internal void Animate() + { Animate(!DesignMode && Visible && Enabled && ParentInternal != null); } - internal void StopAnimate() { + internal void StopAnimate() + { Animate(false); } - private void Animate(bool animate) { + private void Animate(bool animate) + { bool currentlyAnimating = labelState[StateAnimating] != 0; - if (animate != currentlyAnimating) { + if (animate != currentlyAnimating) + { Image image = (Image)Properties.GetObject(PropImage); - if (animate) { - if (image != null) { + if (animate) + { + if (image != null) + { ImageAnimator.Animate(image, new EventHandler(this.OnFrameChanged)); labelState[StateAnimating] = animate ? 1 : 0; } } - else { - if (image != null) { + else + { + if (image != null) + { ImageAnimator.StopAnimate(image, new EventHandler(this.OnFrameChanged)); labelState[StateAnimating] = animate ? 1 : 0; } @@ -991,93 +1143,110 @@ private void Animate(bool animate) { } } - protected Rectangle CalcImageRenderBounds(Image image, Rectangle r, ContentAlignment align) { + protected Rectangle CalcImageRenderBounds(Image image, Rectangle r, ContentAlignment align) + { Size pointImageSize = image.Size; int xLoc = r.X + 2; int yLoc = r.Y + 2; - if ((align & WindowsFormsUtils.AnyRightAlign) !=0) { - xLoc = (r.X+r.Width - 4)-pointImageSize.Width; + if ((align & WindowsFormsUtils.AnyRightAlign) != 0) + { + xLoc = (r.X + r.Width - 4) - pointImageSize.Width; } - else if ((align & WindowsFormsUtils.AnyCenterAlign) != 0) { - xLoc = r.X + (r.Width - pointImageSize.Width)/2; + else if ((align & WindowsFormsUtils.AnyCenterAlign) != 0) + { + xLoc = r.X + (r.Width - pointImageSize.Width) / 2; } - if ((align & WindowsFormsUtils.AnyBottomAlign) != 0) { - yLoc = (r.Y+r.Height - 4)-pointImageSize.Height; + if ((align & WindowsFormsUtils.AnyBottomAlign) != 0) + { + yLoc = (r.Y + r.Height - 4) - pointImageSize.Height; } - else if ((align & WindowsFormsUtils.AnyTopAlign) != 0) { + else if ((align & WindowsFormsUtils.AnyTopAlign) != 0) + { yLoc = r.Y + 2; } - else { - yLoc = r.Y + (r.Height - pointImageSize.Height)/2; + else + { + yLoc = r.Y + (r.Height - pointImageSize.Height) / 2; } return new Rectangle(xLoc, yLoc, pointImageSize.Width, pointImageSize.Height); } - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new LabelAccessibleObject(this); } /// /// Get StringFormat object for rendering text using GDI+ (Graphics). /// - - - internal virtual StringFormat CreateStringFormat() { - return ControlPaint.CreateStringFormat( this, this.TextAlign, this.AutoEllipsis, this.UseMnemonic ); + + + internal virtual StringFormat CreateStringFormat() + { + return ControlPaint.CreateStringFormat(this, this.TextAlign, this.AutoEllipsis, this.UseMnemonic); } - private TextFormatFlags CreateTextFormatFlags() { + private TextFormatFlags CreateTextFormatFlags() + { return CreateTextFormatFlags(this.Size - GetBordersAndPadding()); } /// /// Get TextFormatFlags flags for rendering text using GDI (TextRenderer). /// - internal virtual TextFormatFlags CreateTextFormatFlags(Size constrainingSize){ + internal virtual TextFormatFlags CreateTextFormatFlags(Size constrainingSize) + { // PREFERRED SIZE CACHING: // Please read if you're adding a new TextFormatFlag. // whenever something can change the TextFormatFlags used // MeasureTextCache.InvalidateCache() should be called so we can approprately clear. - - TextFormatFlags flags = ControlPaint.CreateTextFormatFlags( this, this.TextAlign, this.AutoEllipsis, this.UseMnemonic ); + + TextFormatFlags flags = ControlPaint.CreateTextFormatFlags(this, this.TextAlign, this.AutoEllipsis, this.UseMnemonic); // Remove WordBreak if the size is large enough to display all the text. - if (!MeasureTextCache.TextRequiresWordBreak(Text, Font, constrainingSize, flags)) { + if (!MeasureTextCache.TextRequiresWordBreak(Text, Font, constrainingSize, flags)) + { // The effect of the TextBoxControl flag is that in-word line breaking will occur if needed, this happens when AutoSize // is false and a one-word line still doesn't fit the binding box (width). The other effect is that partially visible // lines are clipped; this is how GDI+ works by default. - flags &= ~(TextFormatFlags.WordBreak | TextFormatFlags.TextBoxControl); + flags &= ~(TextFormatFlags.WordBreak | TextFormatFlags.TextBoxControl); } return flags; } - private void DetachImageList(object sender, EventArgs e) { + private void DetachImageList(object sender, EventArgs e) + { ImageList = null; } - - protected override void Dispose(bool disposing) { - if (disposing) { + + protected override void Dispose(bool disposing) + { + if (disposing) + { StopAnimate(); // Holding on to images and image list is a memory leak. - if (ImageList != null) { - ImageList.Disposed -= new EventHandler(this.DetachImageList); + if (ImageList != null) + { + ImageList.Disposed -= new EventHandler(this.DetachImageList); ImageList.RecreateHandle -= new EventHandler(ImageListRecreateHandle); Properties.SetObject(PropImageList, null); } - if (Image != null) { + if (Image != null) + { Properties.SetObject(PropImage, null); } //Dipose the tooltip if one present.. - if (textToolTip != null) { + if (textToolTip != null) + { textToolTip.Dispose(); textToolTip = null; } @@ -1091,13 +1260,16 @@ protected override void Dispose(bool disposing) { /// Draws an within the specified bounds. /// /// - protected void DrawImage(System.Drawing.Graphics g, Image image, Rectangle r, ContentAlignment align) { + protected void DrawImage(System.Drawing.Graphics g, Image image, Rectangle r, ContentAlignment align) + { Rectangle loc = CalcImageRenderBounds(image, r, align); - if (!Enabled) { + if (!Enabled) + { ControlPaint.DrawImageDisabled(g, image, loc.X, loc.Y, BackColor); } - else { + else + { g.DrawImage(image, loc.X, loc.Y, image.Width, image.Height); } } @@ -1135,80 +1307,97 @@ private ArrayList GetLines() { return list; } */ - private Size GetBordersAndPadding() { - Size bordersAndPadding = Padding.Size; - - // COMPAT: Everett added random numbers to the height of the label - if (UseCompatibleTextRendering) { - //Always return the Fontheight + some buffer else the Text gets clipped for Autosize = true.. - //( - if (BorderStyle != BorderStyle.None) { - bordersAndPadding.Height += 6; // taken from Everett.PreferredHeight - bordersAndPadding.Width += 2; // taken from Everett.PreferredWidth - } - else { - bordersAndPadding.Height += 3; // taken from Everett.PreferredHeight - } - } - else { - // in Whidbey we'll actually ask the control the border size. - - bordersAndPadding += SizeFromClientSize(Size.Empty); - if (BorderStyle == BorderStyle.Fixed3D) { - bordersAndPadding += new Size(2, 2); - } - } - return bordersAndPadding; - - } - - - public override Size GetPreferredSize(Size proposedSize) { + private Size GetBordersAndPadding() + { + Size bordersAndPadding = Padding.Size; + + // COMPAT: Everett added random numbers to the height of the label + if (UseCompatibleTextRendering) + { + //Always return the Fontheight + some buffer else the Text gets clipped for Autosize = true.. + //( + if (BorderStyle != BorderStyle.None) + { + bordersAndPadding.Height += 6; // taken from Everett.PreferredHeight + bordersAndPadding.Width += 2; // taken from Everett.PreferredWidth + } + else + { + bordersAndPadding.Height += 3; // taken from Everett.PreferredHeight + } + } + else + { + // in Whidbey we'll actually ask the control the border size. + + bordersAndPadding += SizeFromClientSize(Size.Empty); + if (BorderStyle == BorderStyle.Fixed3D) + { + bordersAndPadding += new Size(2, 2); + } + } + return bordersAndPadding; + + } + + + public override Size GetPreferredSize(Size proposedSize) + { //make sure the behavior is consistent with GetPreferredSizeCore - if (proposedSize.Width == 1) { + if (proposedSize.Width == 1) + { proposedSize.Width = 0; } - if (proposedSize.Height == 1) { + if (proposedSize.Height == 1) + { proposedSize.Height = 0; } return base.GetPreferredSize(proposedSize); } - internal virtual bool UseGDIMeasuring() { + internal virtual bool UseGDIMeasuring() + { return (FlatStyle == FlatStyle.System || !UseCompatibleTextRendering); } - + [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] // See ComboBox.cs GetComboHeight - internal override Size GetPreferredSizeCore(Size proposedConstraints) { + internal override Size GetPreferredSizeCore(Size proposedConstraints) + { Size bordersAndPadding = GetBordersAndPadding(); // Subtract border area from constraints proposedConstraints -= bordersAndPadding; // keep positive - proposedConstraints = LayoutUtils.UnionSizes(proposedConstraints,Size.Empty); + proposedConstraints = LayoutUtils.UnionSizes(proposedConstraints, Size.Empty); Size requiredSize; // // TEXT Measurement // - - if (string.IsNullOrEmpty(Text)) { + + if (string.IsNullOrEmpty(Text)) + { // empty labels return the font height + borders - using (WindowsFont font = WindowsFont.FromFont(this.Font)) { + using (WindowsFont font = WindowsFont.FromFont(this.Font)) + { // this is the character that Windows uses to determine the extent requiredSize = WindowsGraphicsCacheManager.MeasurementGraphics.GetTextExtent("0", font); requiredSize.Width = 0; } } - else if (UseGDIMeasuring()) { + else if (UseGDIMeasuring()) + { TextFormatFlags format = FlatStyle == FlatStyle.System ? TextFormatFlags.Default : CreateTextFormatFlags(proposedConstraints); requiredSize = MeasureTextCache.GetTextSize(Text, Font, proposedConstraints, format); - } - else { + } + else + { // GDI+ rendering. - using (Graphics measurementGraphics = WindowsFormsUtils.CreateMeasurementGraphics()) { - using (StringFormat stringFormat = CreateStringFormat()) { + using (Graphics measurementGraphics = WindowsFormsUtils.CreateMeasurementGraphics()) + { + using (StringFormat stringFormat = CreateStringFormat()) + { SizeF bounds = (proposedConstraints.Width == 1) ? new SizeF(0, proposedConstraints.Height) : new SizeF(proposedConstraints.Width, proposedConstraints.Height); @@ -1216,9 +1405,9 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) { requiredSize = Size.Ceiling(measurementGraphics.MeasureString(Text, Font, bounds, stringFormat)); } } - + } - + requiredSize += bordersAndPadding; return requiredSize; @@ -1231,38 +1420,47 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) { // This method is called by LabelDesigner, using private reflection. System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode") ] - private int GetLeadingTextPaddingFromTextFormatFlags(){ - if( !IsHandleCreated ){ + private int GetLeadingTextPaddingFromTextFormatFlags() + { + if (!IsHandleCreated) + { return 0; } //If we are using GDI+ the code below will not work, except //if the style is FlatStyle.System since GDI will be used in that case. - if (UseCompatibleTextRendering && FlatStyle != FlatStyle.System) { + if (UseCompatibleTextRendering && FlatStyle != FlatStyle.System) + { return 0; } - - using( WindowsGraphics wg = WindowsGraphics.FromHwnd(this.Handle) ){ + + using (WindowsGraphics wg = WindowsGraphics.FromHwnd(this.Handle)) + { TextFormatFlags flags = CreateTextFormatFlags(); - if( (flags & TextFormatFlags.NoPadding ) == TextFormatFlags.NoPadding ){ + if ((flags & TextFormatFlags.NoPadding) == TextFormatFlags.NoPadding) + { wg.TextPadding = TextPaddingOptions.NoPadding; } - else if( (flags & TextFormatFlags.LeftAndRightPadding ) == TextFormatFlags.LeftAndRightPadding ){ + else if ((flags & TextFormatFlags.LeftAndRightPadding) == TextFormatFlags.LeftAndRightPadding) + { wg.TextPadding = TextPaddingOptions.LeftAndRightPadding; } - using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(this.Font)) { + using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(this.Font)) + { IntNativeMethods.DRAWTEXTPARAMS dtParams = wg.GetTextMargins(wf); // This is actually leading margin. - return dtParams.iLeftMargin; + return dtParams.iLeftMargin; } } } - private void ImageListRecreateHandle(object sender, EventArgs e) { - if (IsHandleCreated) { + private void ImageListRecreateHandle(object sender, EventArgs e) + { + if (IsHandleCreated) + { Invalidate(); } } @@ -1272,7 +1470,8 @@ private void ImageListRecreateHandle(object sender, EventArgs e) { /// internal override bool IsMnemonicsListenerAxSourced { - get{ + get + { return true; } } @@ -1283,7 +1482,8 @@ internal override bool IsMnemonicsListenerAxSourced /// Virtual methods defined on the class should not be called from constructors. If a derived class has overridden /// the method, the derived class version will be called (before the derived class constructor is called). /// - internal bool IsOwnerDraw(){ + internal bool IsOwnerDraw() + { return FlatStyle != FlatStyle.System; } @@ -1292,17 +1492,21 @@ internal bool IsOwnerDraw(){ /// Raises the event. /// /// - protected override void OnMouseEnter(EventArgs e) { - if (!controlToolTip && !DesignMode && AutoEllipsis && showToolTip && textToolTip != null) { + protected override void OnMouseEnter(EventArgs e) + { + if (!controlToolTip && !DesignMode && AutoEllipsis && showToolTip && textToolTip != null) + { - try { + try + { controlToolTip = true; textToolTip.Show(WindowsFormsUtils.TextWithoutMnemonics(Text), this); } - finally { + finally + { controlToolTip = false; } - + } base.OnMouseEnter(e); } @@ -1313,8 +1517,10 @@ protected override void OnMouseEnter(EventArgs e) { /// /// [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] - protected override void OnMouseLeave(EventArgs e) { - if (!controlToolTip && textToolTip != null && textToolTip.GetHandleCreated()) { + protected override void OnMouseLeave(EventArgs e) + { + if (!controlToolTip && textToolTip != null && textToolTip.GetHandleCreated()) + { textToolTip.RemoveAll(); textToolTip.Hide(this); @@ -1323,8 +1529,10 @@ protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); } - private void OnFrameChanged(object o, EventArgs e) { - if (Disposing || IsDisposed) { + private void OnFrameChanged(object o, EventArgs e) + { + if (Disposing || IsDisposed) + { return; } if (IsHandleCreated && InvokeRequired) @@ -1336,16 +1544,18 @@ private void OnFrameChanged(object o, EventArgs e) { Invalidate(); } - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { MeasureTextCache.InvalidateCache(); base.OnFontChanged(e); AdjustSize(); Invalidate(); } - + [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] - protected override void OnHandleDestroyed(EventArgs e) { + protected override void OnHandleDestroyed(EventArgs e) + { base.OnHandleDestroyed(e); if (textToolTip != null && textToolTip.GetHandleCreated()) { @@ -1353,90 +1563,113 @@ protected override void OnHandleDestroyed(EventArgs e) { } } - protected override void OnTextChanged(EventArgs e) { - - using(LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.Text)) { + protected override void OnTextChanged(EventArgs e) + { + + using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.Text)) + { MeasureTextCache.InvalidateCache(); base.OnTextChanged(e); AdjustSize(); Invalidate(); } - if (LiveSetting != AutomationLiveSetting.Off) { + if (LiveSetting != AutomationLiveSetting.Off) + { AccessibilityObject.RaiseLiveRegionChanged(); } } - protected virtual void OnTextAlignChanged(EventArgs e) { + protected virtual void OnTextAlignChanged(EventArgs e) + { EventHandler eh = Events[EVENT_TEXTALIGNCHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } - protected override void OnPaddingChanged(EventArgs e) { + protected override void OnPaddingChanged(EventArgs e) + { base.OnPaddingChanged(e); AdjustSize(); } /// /// - protected override void OnPaint(PaintEventArgs e) { + protected override void OnPaint(PaintEventArgs e) + { Animate(); ImageAnimator.UpdateFrames(this.Image); Rectangle face = LayoutUtils.DeflateRect(ClientRectangle, Padding); Image i = this.Image; - if (i != null) { + if (i != null) + { DrawImage(e.Graphics, i, face, RtlTranslateAlignment(ImageAlign)); } Color color; - if (Enabled && SystemInformation.HighContrast) { + if (Enabled && SystemInformation.HighContrast) + { color = SystemColors.WindowText; } - else { + else + { IntPtr hdc = e.Graphics.GetHdc(); - try { - using (WindowsGraphics wg = WindowsGraphics.FromHdc( hdc )) { + try + { + using (WindowsGraphics wg = WindowsGraphics.FromHdc(hdc)) + { color = wg.GetNearestColor((Enabled) ? ForeColor : DisabledColor); } } - finally { + finally + { e.Graphics.ReleaseHdc(); } } // Do actual drawing - if (AutoEllipsis) { + if (AutoEllipsis) + { Rectangle clientRect = this.ClientRectangle; Size preferredSize = GetPreferredSize(new Size(clientRect.Width, clientRect.Height)); showToolTip = (clientRect.Width < preferredSize.Width || clientRect.Height < preferredSize.Height); } - else { + else + { showToolTip = false; } - if (UseCompatibleTextRendering) { - using (StringFormat stringFormat = CreateStringFormat()) { - if (Enabled) { - using (Brush brush = new SolidBrush(color)) { + if (UseCompatibleTextRendering) + { + using (StringFormat stringFormat = CreateStringFormat()) + { + if (Enabled) + { + using (Brush brush = new SolidBrush(color)) + { e.Graphics.DrawString(Text, Font, brush, face, stringFormat); } } - else { + else + { ControlPaint.DrawStringDisabled(e.Graphics, Text, Font, color, face, stringFormat); } } } - else{ + else + { TextFormatFlags flags = CreateTextFormatFlags(); - if (Enabled) { + if (Enabled) + { TextRenderer.DrawText(e.Graphics, Text, Font, face, color, flags); } - else { + else + { //Theme specs -- if the backcolor is darker than Control, we use // ControlPaint.Dark(backcolor). Otherwise we use ControlDark. @@ -1451,18 +1684,22 @@ protected override void OnPaint(PaintEventArgs e) { /// /// Overriden by LinkLabel. /// - internal virtual void OnAutoEllipsisChanged(/*EventArgs e*/) { + internal virtual void OnAutoEllipsisChanged(/*EventArgs e*/) + { } - protected override void OnEnabledChanged(EventArgs e) { + protected override void OnEnabledChanged(EventArgs e) + { base.OnEnabledChanged(e); Animate(); } - protected override void OnParentChanged(EventArgs e) { + protected override void OnParentChanged(EventArgs e) + { base.OnParentChanged(e); - if (SelfSizing) { + if (SelfSizing) + { // In the case of SelfSizing // we dont know what size to be until we're parented AdjustSize(); @@ -1470,21 +1707,26 @@ protected override void OnParentChanged(EventArgs e) { Animate(); } - protected override void OnRightToLeftChanged(EventArgs e) { + protected override void OnRightToLeftChanged(EventArgs e) + { MeasureTextCache.InvalidateCache(); base.OnRightToLeftChanged(e); } - protected override void OnVisibleChanged(EventArgs e) { + protected override void OnVisibleChanged(EventArgs e) + { base.OnVisibleChanged(e); Animate(); } - internal override void PrintToMetaFileRecursive(HandleRef hDC, IntPtr lParam, Rectangle bounds) { + internal override void PrintToMetaFileRecursive(HandleRef hDC, IntPtr lParam, Rectangle bounds) + { base.PrintToMetaFileRecursive(hDC, lParam, bounds); - using (WindowsFormsUtils.DCMapping mapping = new WindowsFormsUtils.DCMapping(hDC, bounds)) { - using(Graphics g = Graphics.FromHdcInternal(hDC.Handle)) { + using (WindowsFormsUtils.DCMapping mapping = new WindowsFormsUtils.DCMapping(hDC, bounds)) + { + using (Graphics g = Graphics.FromHdcInternal(hDC.Handle)) + { ControlPaint.PrintBorder(g, new Rectangle(Point.Empty, Size), BorderStyle, Border3DStyle.SunkenOuter); } } @@ -1499,12 +1741,17 @@ internal override void PrintToMetaFileRecursive(HandleRef hDC, IntPtr lParam, Re /// mnemonic for this control. /// /// - protected internal override bool ProcessMnemonic(char charCode) { - if (UseMnemonic && IsMnemonic(charCode, Text) && CanProcessMnemonic()) { + protected internal override bool ProcessMnemonic(char charCode) + { + if (UseMnemonic && IsMnemonic(charCode, Text) && CanProcessMnemonic()) + { Control parent = ParentInternal; - if (parent != null) { - if (parent.SelectNextControl(this, true, false, true, false)) { - if (!parent.ContainsFocus) { + if (parent != null) + { + if (parent.SelectNextControl(this, true, false, true, false)) + { + if (!parent.ContainsFocus) + { parent.Focus(); } } @@ -1517,13 +1764,15 @@ protected internal override bool ProcessMnemonic(char charCode) { /// /// Overrides Control.setBoundsCore to enforce autoSize. /// - protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { + protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) + { if ((specified & BoundsSpecified.Height) != BoundsSpecified.None) requestedHeight = height; if ((specified & BoundsSpecified.Width) != BoundsSpecified.None) requestedWidth = width; - if (AutoSize && SelfSizing) { + if (AutoSize && SelfSizing) + { Size preferredSize = PreferredSize; width = preferredSize.Width; height = preferredSize.Height; @@ -1535,11 +1784,13 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound "It is SetBoundsCore's responsibility to ensure Size = PreferredSize when AutoSize is true."); } - private void ResetImage() { + private void ResetImage() + { Image = null; } - private bool ShouldSerializeImage() { + private bool ShouldSerializeImage() + { return Properties.GetObject(PropImage) != null; } @@ -1547,8 +1798,10 @@ private bool ShouldSerializeImage() { /// /// Called by ToolTip to poke in that Tooltip into this ComCtl so that the Native ChildToolTip is not exposed. /// - internal void SetToolTip(ToolTip toolTip) { - if (toolTip != null && !controlToolTip) { + internal void SetToolTip(ToolTip toolTip) + { + if (toolTip != null && !controlToolTip) + { controlToolTip = true; } } @@ -1558,7 +1811,8 @@ internal void SetToolTip(ToolTip toolTip) { /// /// Returns a string representation for this control. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); return s + ", Text: " + Text; } @@ -1569,8 +1823,10 @@ public override string ToString() { /// class would normally override. /// /// - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { case Interop.WindowMessages.WM_NCHITTEST: // label returns HT_TRANSPARENT for everything, so all messages get // routed to the parent. Change this so we can tell what's going on. @@ -1587,15 +1843,20 @@ protected override void WndProc(ref Message m) { } [System.Runtime.InteropServices.ComVisible(true)] - internal class LabelAccessibleObject : ControlAccessibleObject { + internal class LabelAccessibleObject : ControlAccessibleObject + { - public LabelAccessibleObject(Label owner) : base(owner) { + public LabelAccessibleObject(Label owner) : base(owner) + { } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { AccessibleRole role = Owner.AccessibleRole; - if (role != AccessibleRole.Default) { + if (role != AccessibleRole.Default) + { return role; } return AccessibleRole.StaticText; @@ -1604,8 +1865,10 @@ public override AccessibleRole Role { internal override bool IsIAccessibleExSupported() => true; - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_ControlTypePropertyId) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_ControlTypePropertyId) + { return NativeMethods.UIA_TextControlTypeId; } @@ -1621,55 +1884,66 @@ internal override object GetPropertyValue(int propertyID) { /// Override ImageList.Indexer to support Label's ImageList semantics. /// /// - internal class LabelImageIndexer : ImageList.Indexer { - private Label owner; - private bool useIntegerIndex = true; + internal class LabelImageIndexer : ImageList.Indexer + { + private Label owner; + private bool useIntegerIndex = true; - public LabelImageIndexer(Label owner) { - this.owner = owner; - } - - public override ImageList ImageList { - get { return (owner == null) ? null : owner.ImageList; } + public LabelImageIndexer(Label owner) + { + this.owner = owner; + } - set { Debug.Assert(false, "Setting the image list in this class is not supported");} - } + public override ImageList ImageList + { + get { return (owner == null) ? null : owner.ImageList; } + set { Debug.Assert(false, "Setting the image list in this class is not supported"); } + } - public override string Key { - get { return base.Key; } - set { - base.Key = value; - useIntegerIndex = false; - } - } - public override int Index { - get { return base.Index; } - set { - base.Index = value; - useIntegerIndex = true; - } + public override string Key + { + get { return base.Key; } + set + { + base.Key = value; + useIntegerIndex = false; + } + } - } + public override int Index + { + get { return base.Index; } + set + { + base.Index = value; + useIntegerIndex = true; + } + } - public override int ActualIndex { - get { - if (useIntegerIndex) { - // The behavior of label is to return the last item in the Images collection - // if the index is currently set higher than the count. - return (Index < ImageList.Images.Count) ? Index : ImageList.Images.Count - 1; - } - else if (ImageList != null) { - return ImageList.Images.IndexOfKey(Key); - } - return -1; + public override int ActualIndex + { + get + { + if (useIntegerIndex) + { + // The behavior of label is to return the last item in the Images collection + // if the index is currently set higher than the count. + return (Index < ImageList.Images.Count) ? Index : ImageList.Images.Count - 1; + } + else if (ImageList != null) + { + return ImageList.Images.IndexOfKey(Key); } + + return -1; } + } - } + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElementCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElementCollection.cs index 74a6631a7cb..1fd3517ed1d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElementCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElementCollection.cs @@ -2,49 +2,59 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.Layout { +namespace System.Windows.Forms.Layout +{ using System.Collections; public class ArrangedElementCollection : IList { internal static ArrangedElementCollection Empty = new ArrangedElementCollection(0); - + // We wrap an ArrayList rather than inherit from CollectionBase because we // do not want to break binary compatibility with ControlCollection. private ArrayList _innerList; // Internal constructor prevents externals from getting a hold of one of these. // We'll open this up in Orcas. - internal ArrangedElementCollection() { + internal ArrangedElementCollection() + { _innerList = new ArrayList(4); } - internal ArrangedElementCollection(ArrayList innerList) { + internal ArrangedElementCollection(ArrayList innerList) + { _innerList = innerList; } - private ArrangedElementCollection(int size) { + private ArrangedElementCollection(int size) + { _innerList = new ArrayList(size); } - - internal ArrayList InnerList { + + internal ArrayList InnerList + { get { return _innerList; } } - internal virtual IArrangedElement this[int index] { - get { return (IArrangedElement) InnerList[index]; } + internal virtual IArrangedElement this[int index] + { + get { return (IArrangedElement)InnerList[index]; } } - public override bool Equals(object obj) { + public override bool Equals(object obj) + { ArrangedElementCollection other = obj as ArrangedElementCollection; - if (other == null || Count != other.Count) { + if (other == null || Count != other.Count) + { return false; } - for (int i = 0; i < Count; i++) { - if (this.InnerList[i] != other.InnerList[i]) { + for (int i = 0; i < Count; i++) + { + if (this.InnerList[i] != other.InnerList[i]) + { return false; } } @@ -55,31 +65,35 @@ public override bool Equals(object obj) { public override int GetHashCode() { return base.GetHashCode(); } // Repositions a element in this list. - internal void MoveElement(IArrangedElement element, int fromIndex, int toIndex) { + internal void MoveElement(IArrangedElement element, int fromIndex, int toIndex) + { int delta = toIndex - fromIndex; - - switch (delta) { + + switch (delta) + { case -1: case 1: // simple swap this.InnerList[fromIndex] = this.InnerList[toIndex]; break; - + default: int start = 0; int dest = 0; - + // which direction are we moving? - if (delta > 0) { + if (delta > 0) + { // shift down by the delta to open the new spot start = fromIndex + 1; dest = fromIndex; } - else { + else + { // shift up by the delta to open the new spot start = toIndex; dest = toIndex + 1; - + // make it positive delta = -delta; } @@ -89,48 +103,56 @@ internal void MoveElement(IArrangedElement element, int fromIndex, int toIndex) this.InnerList[toIndex] = element; } - private static void Copy (ArrangedElementCollection sourceList, int sourceIndex, ArrangedElementCollection destinationList, int destinationIndex, int length) { - if(sourceIndex < destinationIndex) { + private static void Copy(ArrangedElementCollection sourceList, int sourceIndex, ArrangedElementCollection destinationList, int destinationIndex, int length) + { + if (sourceIndex < destinationIndex) + { // We need to copy from the back forward to prevent overwrite if source and // destination lists are the same, so we need to flip the source/dest indices // to point at the end of the spans to be copied. sourceIndex = sourceIndex + length; destinationIndex = destinationIndex + length; - - for(;length > 0; length--) { + + for (; length > 0; length--) + { destinationList.InnerList[--destinationIndex] = sourceList.InnerList[--sourceIndex]; } - } else { - for(;length > 0; length--) { + } + else + { + for (; length > 0; length--) + { destinationList.InnerList[destinationIndex++] = sourceList.InnerList[sourceIndex++]; } } } - + #region IList Members void IList.Clear() { InnerList.Clear(); } - bool IList.IsFixedSize { get { return InnerList.IsFixedSize; }} + bool IList.IsFixedSize { get { return InnerList.IsFixedSize; } } bool IList.Contains(object value) { return InnerList.Contains(value); } - public virtual bool IsReadOnly { get { return InnerList.IsReadOnly; }} + public virtual bool IsReadOnly { get { return InnerList.IsReadOnly; } } void IList.RemoveAt(int index) { InnerList.RemoveAt(index); } void IList.Remove(object value) { InnerList.Remove(value); } int IList.Add(object value) { return InnerList.Add(value); } int IList.IndexOf(object value) { return InnerList.IndexOf(value); } void IList.Insert(int index, object value) { throw new NotSupportedException(); /* InnerList.Insert(index, value); */ } - object IList.this[int index] { - get { return InnerList[index]; } + object IList.this[int index] + { + get { return InnerList[index]; } set { throw new NotSupportedException(); } } #endregion #region ICollection Members - public virtual int Count { + public virtual int Count + { get { return InnerList.Count; } } - object ICollection.SyncRoot { get { return InnerList.SyncRoot; }} + object ICollection.SyncRoot { get { return InnerList.SyncRoot; } } public void CopyTo(Array array, int index) { InnerList.CopyTo(array, index); } - bool ICollection.IsSynchronized { get { return InnerList.IsSynchronized; }} + bool ICollection.IsSynchronized { get { return InnerList.IsSynchronized; } } #endregion #region IEnumerable Members diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs index 091d3ed43b3..ed1534004db 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.Layout { +namespace System.Windows.Forms.Layout +{ using System; using System.Collections.Specialized; using System.Collections; @@ -11,16 +12,17 @@ namespace System.Windows.Forms.Layout { using System.Drawing; using System.Windows.Forms; using System.ComponentModel; - + // Some LayoutEngines extend the same properties to their children. We want // these extended properties to retain their value when moved from one container // to another. (For example, set BoxStretchInternal on a control in FlowPanel and then move // the control to GridPanel.) CommonProperties is a place to define keys and // accessors for such properties. - internal class CommonProperties { + internal class CommonProperties + { + - private static readonly int _layoutStateProperty = PropertyStore.CreateKey(); private static readonly int _specifiedBoundsProperty = PropertyStore.CreateKey(); private static readonly int _preferredSizeCacheProperty = PropertyStore.CreateKey(); @@ -28,18 +30,18 @@ internal class CommonProperties { private static readonly int _marginProperty = PropertyStore.CreateKey(); private static readonly int _minimumSizeProperty = PropertyStore.CreateKey(); - private static readonly int _maximumSizeProperty = PropertyStore.CreateKey(); + private static readonly int _maximumSizeProperty = PropertyStore.CreateKey(); private static readonly int _layoutBoundsProperty = PropertyStore.CreateKey(); - + #if DEBUG private static readonly int _lastKnownStateProperty = PropertyStore.CreateKey(); #endif - + internal const ContentAlignment DefaultAlignment = ContentAlignment.TopLeft; internal const AnchorStyles DefaultAnchor = AnchorStyles.Top | AnchorStyles.Left; internal const bool DefaultAutoSize = false; - + internal const DockStyle DefaultDock = DockStyle.None; internal static readonly Padding DefaultMargin = new Padding(3); internal static readonly Size DefaultMinimumSize = new Size(0, 0); @@ -59,25 +61,28 @@ internal class CommonProperties { private static readonly BitVector32.Section _anchorNeverShrinksSection = BitVector32.CreateSection(0x01, _BoxStretchInternalSection); private static readonly BitVector32.Section _flowBreakSection = BitVector32.CreateSection(0x01, _anchorNeverShrinksSection); private static readonly BitVector32.Section _selfAutoSizingSection = BitVector32.CreateSection(0x01, _flowBreakSection); - private static readonly BitVector32.Section _autoSizeModeSection = BitVector32.CreateSection(0x01, _selfAutoSizingSection); + private static readonly BitVector32.Section _autoSizeModeSection = BitVector32.CreateSection(0x01, _selfAutoSizingSection); + - - private enum DockAnchorMode{ + private enum DockAnchorMode + { Anchor = 0, Dock = 1 } -#region AppliesToAllLayouts + #region AppliesToAllLayouts /// ClearMaximumSize /// Removes the maximum size from the property store, making it "unset". /// - internal static void ClearMaximumSize(IArrangedElement element) { - if (element.Properties.ContainsObject(_maximumSizeProperty)) { - element.Properties.RemoveObject(_maximumSizeProperty); - } - } + internal static void ClearMaximumSize(IArrangedElement element) + { + if (element.Properties.ContainsObject(_maximumSizeProperty)) + { + element.Properties.RemoveObject(_maximumSizeProperty); + } + } /// GetAutoSize /// Determines whether or not the System.Windows.Forms.Layout LayoutEngines @@ -87,7 +92,8 @@ internal static void ClearMaximumSize(IArrangedElement element) { /// property and not calling base. If CommonProperties.GetAutoSize(element) is false, /// a layout engine will treat it as AutoSize = false and not size the element to its /// preferred size. - internal static bool GetAutoSize(IArrangedElement element) { + internal static bool GetAutoSize(IArrangedElement element) + { BitVector32 state = GetLayoutState(element); int value = state[_autoSizeSection]; return value != 0; @@ -99,34 +105,40 @@ internal static bool GetAutoSize(IArrangedElement element) { /// We can not use our pattern of passing the default value into Margin because the /// LayoutEngines read this property and do not know each element's DefaultMargin. /// Instead the Element sets the Margin in its ctor. - internal static Padding GetMargin(IArrangedElement element) { + internal static Padding GetMargin(IArrangedElement element) + { bool found; Padding padding = element.Properties.GetPadding(_marginProperty, out found); - if (found) { + if (found) + { return padding; } return DefaultMargin; } - /// GetMaximumSize - /// Returns the maximum size for an element - internal static Size GetMaximumSize(IArrangedElement element, Size defaultMaximumSize) { - bool found; - Size size = element.Properties.GetSize(_maximumSizeProperty, out found); - if (found) { - return size; - } - return defaultMaximumSize; + /// GetMaximumSize + /// Returns the maximum size for an element + internal static Size GetMaximumSize(IArrangedElement element, Size defaultMaximumSize) + { + bool found; + Size size = element.Properties.GetSize(_maximumSizeProperty, out found); + if (found) + { + return size; + } + return defaultMaximumSize; } - + /// GetMinimumSize /// Returns the minimum size for an element - internal static Size GetMinimumSize(IArrangedElement element, Size defaultMinimumSize) { + internal static Size GetMinimumSize(IArrangedElement element, Size defaultMinimumSize) + { bool found; Size size = element.Properties.GetSize(_minimumSizeProperty, out found); - if (found) { - return size; + if (found) + { + return size; } return defaultMinimumSize; } @@ -138,10 +150,12 @@ internal static Size GetMinimumSize(IArrangedElement element, Size defaultMinimu /// /// NOTE: LayoutEngines should never read this property. Padding gets incorperated into /// layout by modifying what the control reports for preferred size. - internal static Padding GetPadding(IArrangedElement element, Padding defaultPadding) { + internal static Padding GetPadding(IArrangedElement element, Padding defaultPadding) + { bool found; Padding padding = element.Properties.GetPadding(_paddingProperty, out found); - if (found) { + if (found) + { return padding; } return defaultPadding; @@ -149,63 +163,71 @@ internal static Padding GetPadding(IArrangedElement element, Padding defaultPadd /// GetSpecifiedBounds /// Returns the last size manually set into the element. See UpdateSpecifiedBounds. - internal static Rectangle GetSpecifiedBounds(IArrangedElement element) { + internal static Rectangle GetSpecifiedBounds(IArrangedElement element) + { bool found; Rectangle rectangle = element.Properties.GetRectangle(_specifiedBoundsProperty, out found); - if (found && rectangle != LayoutUtils.MaxRectangle) { - return rectangle; + if (found && rectangle != LayoutUtils.MaxRectangle) + { + return rectangle; } return element.Bounds; } /// ResetPadding /// clears out the padding from the property store - internal static void ResetPadding(IArrangedElement element) { + internal static void ResetPadding(IArrangedElement element) + { object value = element.Properties.GetObject(_paddingProperty); - if(value != null) { + if (value != null) + { element.Properties.RemoveObject(_paddingProperty); } } - + /// SetAutoSize /// Sets whether or not the layout engines should treat this control as auto sized. - internal static void SetAutoSize(IArrangedElement element, bool value) { + internal static void SetAutoSize(IArrangedElement element, bool value) + { Debug.Assert(value != GetAutoSize(element), "PERF: Caller should guard against setting AutoSize to original value."); BitVector32 state = GetLayoutState(element); state[_autoSizeSection] = value ? 1 : 0; SetLayoutState(element, state); - if(value == false) { + if (value == false) + { // If autoSize is being turned off, restore the control to its specified bounds. element.SetBounds(GetSpecifiedBounds(element), BoundsSpecified.None); } Debug.Assert(GetAutoSize(element) == value, "Error detected setting AutoSize."); - } - + } + /// SetMargin /// Sets the margin (exterior space) for an element. - internal static void SetMargin(IArrangedElement element, Padding value) { + internal static void SetMargin(IArrangedElement element, Padding value) + { Debug.Assert(value != GetMargin(element), "PERF: Caller should guard against setting Margin to original value."); element.Properties.SetPadding(_marginProperty, value); - + Debug.Assert(GetMargin(element) == value, "Error detected setting Margin."); LayoutTransaction.DoLayout(element.Container, element, PropertyNames.Margin); } - - + + /// SetMaximumSize /// Sets the maximum size for an element. - internal static void SetMaximumSize(IArrangedElement element, Size value) { + internal static void SetMaximumSize(IArrangedElement element, Size value) + { Debug.Assert(value != GetMaximumSize(element, new Size(-7109, -7107)), "PERF: Caller should guard against setting MaximumSize to original value."); element.Properties.SetSize(_maximumSizeProperty, value); - + // Element bounds may need to truncated to new maximum // Rectangle bounds = element.Bounds; @@ -221,13 +243,15 @@ internal static void SetMaximumSize(IArrangedElement element, Size value) { /// SetMinimumSize /// Sets the minimum size for an element. - internal static void SetMinimumSize(IArrangedElement element, Size value) { + internal static void SetMinimumSize(IArrangedElement element, Size value) + { Debug.Assert(value != GetMinimumSize(element, new Size(-7109, -7107)), "PERF: Caller should guard against setting MinimumSize to original value."); - + element.Properties.SetSize(_minimumSizeProperty, value); - using (new LayoutTransaction(element.Container as Control, element, PropertyNames.MinimumSize)) { + using (new LayoutTransaction(element.Container as Control, element, PropertyNames.MinimumSize)) + { // Element bounds may need to inflated to new minimum // Rectangle bounds = element.Bounds; @@ -235,7 +259,7 @@ internal static void SetMinimumSize(IArrangedElement element, Size value) { bounds.Height = Math.Max(bounds.Height, value.Height); element.SetBounds(bounds, BoundsSpecified.Size); } - + Debug.Assert(GetMinimumSize(element, new Size(-7109, -7107)) == value, "Error detected setting MinimumSize."); } @@ -243,13 +267,14 @@ internal static void SetMinimumSize(IArrangedElement element, Size value) { /// SetPadding /// Sets the padding (interior space) for an element. See GetPadding for more detiails. /// NOTE: It is the callers responsibility to do layout. See Control.Padding for details. - internal static void SetPadding(IArrangedElement element, Padding value) { + internal static void SetPadding(IArrangedElement element, Padding value) + { Debug.Assert(value != GetPadding(element, new Padding(-7105)), "PERF: Caller should guard against setting Padding to original value."); value = LayoutUtils.ClampNegativePaddingToZero(value); element.Properties.SetPadding(_paddingProperty, value); - + Debug.Assert(GetPadding(element, new Padding(-7105)) == value, "Error detected setting Padding."); } @@ -269,30 +294,39 @@ internal static void SetPadding(IArrangedElement element, Padding value) { /// /// Setting the control to Dock.None (via DefaultLayout.SetDock) /// element.SetBounds(CommonProperties.GetSpecifiedBounds(element), BoundsSpecified.None); - internal static void UpdateSpecifiedBounds(IArrangedElement element, int x, int y, int width, int height, BoundsSpecified specified) { + internal static void UpdateSpecifiedBounds(IArrangedElement element, int x, int y, int width, int height, BoundsSpecified specified) + { Rectangle originalBounds = CommonProperties.GetSpecifiedBounds(element); - + // PERF note: Bitwise operator usage intentional to optimize out branching. - + bool xChangedButNotSpecified = ((specified & BoundsSpecified.X) == BoundsSpecified.None) & x != originalBounds.X; bool yChangedButNotSpecified = ((specified & BoundsSpecified.Y) == BoundsSpecified.None) & y != originalBounds.Y; bool wChangedButNotSpecified = ((specified & BoundsSpecified.Width) == BoundsSpecified.None) & width != originalBounds.Width; bool hChangedButNotSpecified = ((specified & BoundsSpecified.Height) == BoundsSpecified.None) & height != originalBounds.Height; - - if(xChangedButNotSpecified | yChangedButNotSpecified | wChangedButNotSpecified | hChangedButNotSpecified) { + + if (xChangedButNotSpecified | yChangedButNotSpecified | wChangedButNotSpecified | hChangedButNotSpecified) + { // if any of them are changed and specified cache the new value. - - if (!xChangedButNotSpecified) originalBounds.X = x; - if (!yChangedButNotSpecified) originalBounds.Y = y; - if (!wChangedButNotSpecified) originalBounds.Width = width; - if (!hChangedButNotSpecified) originalBounds.Height = height; + + if (!xChangedButNotSpecified) + originalBounds.X = x; + if (!yChangedButNotSpecified) + originalBounds.Y = y; + if (!wChangedButNotSpecified) + originalBounds.Width = width; + if (!hChangedButNotSpecified) + originalBounds.Height = height; element.Properties.SetRectangle(_specifiedBoundsProperty, originalBounds); - - } else { + + } + else + { // SetBoundsCore is going to call this a lot with the same bounds. Avoid the set object // (which indirectly may causes an allocation) if we can. - if(element.Properties.ContainsObject(_specifiedBoundsProperty)) { + if (element.Properties.ContainsObject(_specifiedBoundsProperty)) + { // use MaxRectangle instead of null so we can reuse the SizeWrapper in the property store. element.Properties.SetRectangle(_specifiedBoundsProperty, LayoutUtils.MaxRectangle); } @@ -300,13 +334,14 @@ internal static void UpdateSpecifiedBounds(IArrangedElement element, int x, int } // Used by ToolStripControlHost.Size. - internal static void UpdateSpecifiedBounds(IArrangedElement element, int x, int y, int width, int height) { + internal static void UpdateSpecifiedBounds(IArrangedElement element, int x, int y, int width, int height) + { Rectangle bounds = new Rectangle(x, y, width, height); element.Properties.SetRectangle(_specifiedBoundsProperty, bounds); } - + /// xClearPreferredSizeCache /// clears the preferred size cached for any control that overrides /// the internal GetPreferredSizeCore method. DO NOT CALL DIRECTLY @@ -314,19 +349,21 @@ internal static void UpdateSpecifiedBounds(IArrangedElement element, int x, int /// - internal static void xClearPreferredSizeCache(IArrangedElement element) { + internal static void xClearPreferredSizeCache(IArrangedElement element) + { element.Properties.SetSize(_preferredSizeCacheProperty, LayoutUtils.InvalidSize); #if DEBUG Debug_ClearProperties(element); #endif - + Debug.Assert(xGetPreferredSizeCache(element) == Size.Empty, "Error detected in xClearPreferredSizeCache."); } /// xClearAllPreferredSizeCaches /// clears all the caching for an IArrangedElement hierarchy /// typically done in dispose. - internal static void xClearAllPreferredSizeCaches(IArrangedElement start) { + internal static void xClearAllPreferredSizeCaches(IArrangedElement start) + { CommonProperties.xClearPreferredSizeCache(start); ArrangedElementCollection controlsCollection = start.Children; @@ -334,7 +371,8 @@ internal static void xClearAllPreferredSizeCaches(IArrangedElement start) { // 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++) { + for (int i = 0; i < controlsCollection.Count; i++) + { xClearAllPreferredSizeCaches(controlsCollection[i]); } } @@ -343,18 +381,21 @@ internal static void xClearAllPreferredSizeCaches(IArrangedElement start) { /// This value is the cached result of the return value from /// a control's GetPreferredSizeCore implementation when asked /// for a constraining value of LayoutUtils.MaxValue (or Size.Empty too). - internal static Size xGetPreferredSizeCache(IArrangedElement element) { + internal static Size xGetPreferredSizeCache(IArrangedElement element) + { bool found; Size size = element.Properties.GetSize(_preferredSizeCacheProperty, out found); - if (found && (size != LayoutUtils.InvalidSize)) { - return size; + if (found && (size != LayoutUtils.InvalidSize)) + { + return size; } return Size.Empty; - } + } /// xSetPreferredSizeCache /// Sets a control's preferred size. See xGetPreferredSizeCache. - internal static void xSetPreferredSizeCache(IArrangedElement element, Size value) { + internal static void xSetPreferredSizeCache(IArrangedElement element, Size value) + { Debug.Assert(value == Size.Empty || value != xGetPreferredSizeCache(element), "PERF: Caller should guard against setting PreferredSizeCache to original value."); #if DEBUG Debug_SnapProperties(element); @@ -363,25 +404,27 @@ internal static void xSetPreferredSizeCache(IArrangedElement element, Size value Debug.Assert(xGetPreferredSizeCache(element) == value, "Error detected in xGetPreferredSizeCache."); } -#endregion + #endregion + + #region DockAndAnchorLayoutSpecific -#region DockAndAnchorLayoutSpecific - /// GetAutoSizeMode /// Returns whether or not a control should snap to its smallest size /// or retain its original size and only grow if the preferred size is larger. /// We tried not having GrowOnly as the default, but it becomes difficult /// to design panels or have Buttons maintain their default size of 100,23 - internal static AutoSizeMode GetAutoSizeMode(IArrangedElement element) { - BitVector32 state = GetLayoutState(element); - return state[_autoSizeModeSection] == 0 ? AutoSizeMode.GrowOnly : AutoSizeMode.GrowAndShrink; + internal static AutoSizeMode GetAutoSizeMode(IArrangedElement element) + { + BitVector32 state = GetLayoutState(element); + return state[_autoSizeModeSection] == 0 ? AutoSizeMode.GrowOnly : AutoSizeMode.GrowAndShrink; } /// GetNeedsDockAndAnchorLayout /// Do not use. Internal property for DockAndAnchor layout. /// Returns true if DefaultLayout needs to do any work for this element. /// (Returns false if the element is purely absolutely positioned) - internal static bool GetNeedsDockAndAnchorLayout(IArrangedElement element) { + internal static bool GetNeedsDockAndAnchorLayout(IArrangedElement element) + { BitVector32 state = GetLayoutState(element); bool result = state[_dockAndAnchorNeedsLayoutSection] != 0; @@ -390,16 +433,17 @@ internal static bool GetNeedsDockAndAnchorLayout(IArrangedElement element) { && xGetDock(element) == DefaultDock && GetAutoSize(element) == DefaultAutoSize) != result, "Individual values of Anchor/Dock/AutoRelocate/Autosize contradict GetNeedsDockAndAnchorLayout()."); - + return result; } /// GetNeedsAnchorLayout /// Do not use. Internal property for DockAndAnchor layout. /// Returns true if DefaultLayout needs to do anchoring for this element. - internal static bool GetNeedsAnchorLayout(IArrangedElement element) { + internal static bool GetNeedsAnchorLayout(IArrangedElement element) + { BitVector32 state = GetLayoutState(element); - bool result = (state[_dockAndAnchorNeedsLayoutSection] != 0) && (state[_dockModeSection] == (int) DockAnchorMode.Anchor); + bool result = (state[_dockAndAnchorNeedsLayoutSection] != 0) && (state[_dockModeSection] == (int)DockAnchorMode.Anchor); Debug.Assert( (xGetAnchor(element) != DefaultAnchor @@ -408,13 +452,14 @@ internal static bool GetNeedsAnchorLayout(IArrangedElement element) { return result; } - + /// GetNeedsDockLayout /// Do not use. Internal property for DockAndAnchor layout. /// Returns true if DefaultLayout needs to do docking for this element. - internal static bool GetNeedsDockLayout(IArrangedElement element) { + internal static bool GetNeedsDockLayout(IArrangedElement element) + { BitVector32 state = GetLayoutState(element); - bool result = state[_dockModeSection] == (int) DockAnchorMode.Dock && element.ParticipatesInLayout; + bool result = state[_dockModeSection] == (int)DockAnchorMode.Dock && element.ParticipatesInLayout; Debug.Assert(((xGetDock(element) != DockStyle.None) && element.ParticipatesInLayout) == result, "Error detected in GetNeedsDockLayout()."); @@ -428,7 +473,8 @@ internal static bool GetNeedsDockLayout(IArrangedElement element) { /// In V2, the LayoutEngine is the one responsible for sizing the child items when /// they're AutoSized. For new layout engines, the controls will let the layout engine /// size them, but for DefaultLayout, they're left to size themselves. - internal static bool GetSelfAutoSizeInDefaultLayout(IArrangedElement element) { + internal static bool GetSelfAutoSizeInDefaultLayout(IArrangedElement element) + { BitVector32 state = GetLayoutState(element); int value = state[_selfAutoSizingSection]; return (value == 1); @@ -440,20 +486,25 @@ internal static bool GetSelfAutoSizeInDefaultLayout(IArrangedElement element) { /// or retain its original size and only grow if the preferred size is larger. /// We tried not having GrowOnly as the default, but it becomes difficult /// to design panels or have Buttons maintain their default size of 100,23 - internal static void SetAutoSizeMode(IArrangedElement element, AutoSizeMode mode) { - BitVector32 state = GetLayoutState(element); - state[_autoSizeModeSection] = mode == AutoSizeMode.GrowAndShrink ? 1 : 0; - SetLayoutState(element, state); + internal static void SetAutoSizeMode(IArrangedElement element, AutoSizeMode mode) + { + BitVector32 state = GetLayoutState(element); + state[_autoSizeModeSection] = mode == AutoSizeMode.GrowAndShrink ? 1 : 0; + SetLayoutState(element, state); } /// ShouldSelfSize /// Compat flag for controls that previously sized themselves. /// See GetSelfAutoSize comments. - internal static bool ShouldSelfSize(IArrangedElement element) { - if (GetAutoSize(element)) { + internal static bool ShouldSelfSize(IArrangedElement element) + { + if (GetAutoSize(element)) + { // check for legacy layout engine - if (element.Container is Control) { - if (((Control)element.Container).LayoutEngine is DefaultLayout) { + if (element.Container is Control) + { + if (((Control)element.Container).LayoutEngine is DefaultLayout) + { return GetSelfAutoSizeInDefaultLayout(element); } } @@ -469,7 +520,8 @@ internal static bool ShouldSelfSize(IArrangedElement element) { /// SetSelfAutoSizeInDefaultLayout /// Compat flag for controls that previously sized themselves. /// See GetSelfAutoSize comments. - internal static void SetSelfAutoSizeInDefaultLayout(IArrangedElement element, bool value) { + internal static void SetSelfAutoSizeInDefaultLayout(IArrangedElement element, bool value) + { Debug.Assert(value != GetSelfAutoSizeInDefaultLayout(element), "PERF: Caller should guard against setting AutoSize to original value."); BitVector32 state = GetLayoutState(element); @@ -479,14 +531,15 @@ internal static void SetSelfAutoSizeInDefaultLayout(IArrangedElement element, bo Debug.Assert(GetSelfAutoSizeInDefaultLayout(element) == value, "Error detected setting AutoSize."); } - + /// xGetAnchor - /// Do not use this. Use DefaultLayout.GetAnchor. /// NOTE that Dock and Anchor are exclusive, so we store their enums in the same section. - internal static AnchorStyles xGetAnchor(IArrangedElement element) { + internal static AnchorStyles xGetAnchor(IArrangedElement element) + { BitVector32 state = GetLayoutState(element); - AnchorStyles value = (AnchorStyles) state[_dockAndAnchorSection]; - DockAnchorMode mode = (DockAnchorMode) state[_dockModeSection]; + AnchorStyles value = (AnchorStyles)state[_dockAndAnchorSection]; + DockAnchorMode mode = (DockAnchorMode)state[_dockModeSection]; // If we are docked, or if it the value is 0, we return DefaultAnchor value = mode == DockAnchorMode.Anchor ? xTranslateAnchorValue(value) : DefaultAnchor; @@ -498,13 +551,15 @@ internal static AnchorStyles xGetAnchor(IArrangedElement element) { /// xGetAutoSizedAndAnchored - /// Do not use. Internal property for DockAndAnchor layout. /// Returns true if the element is both AutoSized and Anchored. - internal static bool xGetAutoSizedAndAnchored(IArrangedElement element) { + internal static bool xGetAutoSizedAndAnchored(IArrangedElement element) + { BitVector32 state = GetLayoutState(element); - - if (state[_selfAutoSizingSection] != 0) { + + if (state[_selfAutoSizingSection] != 0) + { return false; } - bool result = (state[_autoSizeSection] != 0) && (state[_dockModeSection] == (int) DockAnchorMode.Anchor); + bool result = (state[_autoSizeSection] != 0) && (state[_dockModeSection] == (int)DockAnchorMode.Anchor); Debug.Assert(result == (GetAutoSize(element) && xGetDock(element) == DockStyle.None), "Error detected in xGetAutoSizeAndAnchored."); @@ -514,10 +569,11 @@ internal static bool xGetAutoSizedAndAnchored(IArrangedElement element) { /// xGetDock /// Do not use this. Use DefaultLayout.GetDock. /// Note that Dock and Anchor are exclusive, so we store their enums in the same section. - internal static DockStyle xGetDock(IArrangedElement element) { + internal static DockStyle xGetDock(IArrangedElement element) + { BitVector32 state = GetLayoutState(element); - DockStyle value = (DockStyle) state[_dockAndAnchorSection]; - DockAnchorMode mode = (DockAnchorMode) state[_dockModeSection]; + DockStyle value = (DockStyle)state[_dockAndAnchorSection]; + DockAnchorMode mode = (DockAnchorMode)state[_dockModeSection]; // If we are anchored we return DefaultDock value = mode == DockAnchorMode.Dock ? value : DefaultDock; @@ -529,42 +585,44 @@ internal static DockStyle xGetDock(IArrangedElement element) { return value; } - + /// xSetAnchor - /// Do not use this. Use DefaultLayout.SetAnchor. /// Note that Dock and Anchor are exclusive, so we store their enums in the same section. - internal static void xSetAnchor(IArrangedElement element, AnchorStyles value) { + internal static void xSetAnchor(IArrangedElement element, AnchorStyles value) + { Debug.Assert(value != xGetAnchor(element), "PERF: Caller should guard against setting Anchor to original value."); - + BitVector32 state = GetLayoutState(element); // We translate DefaultAnchor to zero - see the _dockAndAnchorNeedsLayoutSection section above. - state[_dockAndAnchorSection] = (int) xTranslateAnchorValue(value); - state[_dockModeSection] = (int) DockAnchorMode.Anchor; + state[_dockAndAnchorSection] = (int)xTranslateAnchorValue(value); + state[_dockModeSection] = (int)DockAnchorMode.Anchor; SetLayoutState(element, state); - Debug.Assert(GetLayoutState(element)[_dockModeSection] == (int) DockAnchorMode.Anchor, + Debug.Assert(GetLayoutState(element)[_dockModeSection] == (int)DockAnchorMode.Anchor, "xSetAnchor did not set mode to Anchor."); - } + } /// xSetDock /// Do not use this. Use DefaultLayout.SetDock. /// Note that Dock and Anchor are exclusive, so we store their enums in the same section. - internal static void xSetDock(IArrangedElement element, DockStyle value) { + internal static void xSetDock(IArrangedElement element, DockStyle value) + { Debug.Assert(value != xGetDock(element), "PERF: Caller should guard against setting Dock to original value."); Debug.Assert(ClientUtils.IsEnumValid(value, (int)value, (int)DockStyle.None, (int)DockStyle.Fill), "Illegal value passed to xSetDock."); BitVector32 state = GetLayoutState(element); - state[_dockAndAnchorSection] = (int) value; // See xTranslateAnchorValue for why this works with Dock.None. - state[_dockModeSection] = (int) (value == DockStyle.None ? DockAnchorMode.Anchor : DockAnchorMode.Dock); + state[_dockAndAnchorSection] = (int)value; // See xTranslateAnchorValue for why this works with Dock.None. + state[_dockModeSection] = (int)(value == DockStyle.None ? DockAnchorMode.Anchor : DockAnchorMode.Dock); SetLayoutState(element, state); Debug.Assert(xGetDock(element) == value, "Error detected setting Dock."); - Debug.Assert((GetLayoutState(element)[_dockModeSection] == (int) DockAnchorMode.Dock) + Debug.Assert((GetLayoutState(element)[_dockModeSection] == (int)DockAnchorMode.Dock) == (value != DockStyle.None), "xSetDock set DockMode incorrectly."); } @@ -574,8 +632,10 @@ internal static void xSetDock(IArrangedElement element, DockStyle value) { /// We either had to do this or map Dock.None to DefaultAnchor (Dock & Anchor share the same section /// in LayoutState.) Mapping DefaultAnchor to 0 is nicer because we do not need to allocate anything in /// the PropertyStore to get a 0 back from PropertyStore.GetInteger(). - private static AnchorStyles xTranslateAnchorValue(AnchorStyles anchor) { - switch(anchor) { + private static AnchorStyles xTranslateAnchorValue(AnchorStyles anchor) + { + switch (anchor) + { case AnchorStyles.None: return DefaultAnchor; case DefaultAnchor: @@ -584,48 +644,52 @@ private static AnchorStyles xTranslateAnchorValue(AnchorStyles anchor) { return anchor; } -#endregion + #endregion -#region FlowLayoutSpecific + #region FlowLayoutSpecific // - internal static bool GetFlowBreak(IArrangedElement element) { + internal static bool GetFlowBreak(IArrangedElement element) + { BitVector32 state = GetLayoutState(element); int value = state[_flowBreakSection]; return value == 1; } - - + + /// SetFlowBreak /// Use FlowLayoutSettings.SetFlowBreak instead. /// See GetFlowBreak. - internal static void SetFlowBreak(IArrangedElement element, bool value) { + internal static void SetFlowBreak(IArrangedElement element, bool value) + { Debug.Assert(value != GetFlowBreak(element), "PERF: Caller should guard against setting FlowBreak to original value."); - + BitVector32 state = GetLayoutState(element); state[_flowBreakSection] = value ? 1 : 0; SetLayoutState(element, state); - + LayoutTransaction.DoLayout(element.Container, element, PropertyNames.FlowBreak); - + Debug.Assert(GetFlowBreak(element) == value, "Error detected setitng SetFlowBreak."); } -#endregion -#region AutoScrollSpecific + #endregion + #region AutoScrollSpecific /// GetLayoutBounds - /// This is the size used to determine whether or not we need scrollbars. /// /// Used if the layoutengine always want to return the same layout bounds regardless /// of how it lays out. Example is TLP in RTL and LTR. - internal static Size GetLayoutBounds(IArrangedElement element) { + internal static Size GetLayoutBounds(IArrangedElement element) + { bool found; Size size = element.Properties.GetSize(_layoutBoundsProperty, out found); - if (found) { - return size; + if (found) + { + return size; } return Size.Empty; } @@ -642,93 +706,112 @@ internal static Size GetLayoutBounds(IArrangedElement element) { /// layout engine. If the bounds has been set, ScrollableControl will use /// those bounds to check if scrollbars should be added, rather than doing /// its own magic to figure it out. - internal static void SetLayoutBounds(IArrangedElement element, Size value) { + internal static void SetLayoutBounds(IArrangedElement element, Size value) + { element.Properties.SetSize(_layoutBoundsProperty, value); } /// HasLayoutBounds - /// Returns whether we have layout bounds stored for this element. - internal static bool HasLayoutBounds(IArrangedElement element) { - bool found; + internal static bool HasLayoutBounds(IArrangedElement element) + { + bool found; element.Properties.GetSize(_layoutBoundsProperty, out found); return found; } -#endregion -#region InternalCommonPropertiesHelpers + #endregion + #region InternalCommonPropertiesHelpers /// GetLayoutState - returns the layout state bit vector from the property store. /// CAREFUL: this is a copy of the state. You need to SetLayoutState() to save your changes. /// - internal static BitVector32 GetLayoutState(IArrangedElement element) { + internal static BitVector32 GetLayoutState(IArrangedElement element) + { return new BitVector32(element.Properties.GetInteger(_layoutStateProperty)); } - internal static void SetLayoutState(IArrangedElement element, BitVector32 state) { + internal static void SetLayoutState(IArrangedElement element, BitVector32 state) + { element.Properties.SetInteger(_layoutStateProperty, state.Data); } -#endregion + #endregion -#region DebugHelpers + #region DebugHelpers #if DEBUG - - + + internal static readonly TraceSwitch PreferredSize = new TraceSwitch("PreferredSize", "Debug preferred size assertion"); - internal static string Debug_GetChangedProperties(IArrangedElement element) { + internal static string Debug_GetChangedProperties(IArrangedElement element) + { string diff = string.Empty; - if (PreferredSize.TraceVerbose) { + if (PreferredSize.TraceVerbose) + { Hashtable propertyHash = element.Properties.GetObject(_lastKnownStateProperty) as Hashtable; - if(propertyHash != null) { - foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(element)) { - if (propertyHash.ContainsKey(pd.Name) && (propertyHash[pd.Name].ToString() != pd.Converter.ConvertToString(pd.GetValue(element)))) { - diff += "Prop [ " + pd.Name + "] OLD [" + propertyHash[pd.Name] + "] NEW [" + pd.Converter.ConvertToString(pd.GetValue(element)) + "]\r\n"; - } + if (propertyHash != null) + { + foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(element)) + { + if (propertyHash.ContainsKey(pd.Name) && (propertyHash[pd.Name].ToString() != pd.Converter.ConvertToString(pd.GetValue(element)))) + { + diff += "Prop [ " + pd.Name + "] OLD [" + propertyHash[pd.Name] + "] NEW [" + pd.Converter.ConvertToString(pd.GetValue(element)) + "]\r\n"; + } } } } - else { + else + { diff = "For more info, try enabling PreferredSize trace switch"; } return diff; } - internal static void Debug_SnapProperties(IArrangedElement element) { + internal static void Debug_SnapProperties(IArrangedElement element) + { // DEBUG - store off the old state so we can figure out what has changed in a GPS assert element.Properties.SetObject(_lastKnownStateProperty, Debug_GetCurrentPropertyState(element)); } - internal static void Debug_ClearProperties(IArrangedElement element) { + internal static void Debug_ClearProperties(IArrangedElement element) + { // DEBUG - clear off the old state so we can figure out what has changed in a GPS assert element.Properties.SetObject(_lastKnownStateProperty, null); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] - public static Hashtable Debug_GetCurrentPropertyState(object obj) { + public static Hashtable Debug_GetCurrentPropertyState(object obj) + { Hashtable propertyHash = new Hashtable(); - if (PreferredSize.TraceVerbose) { - - foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(obj)) { - if (pd.Name == "PreferredSize") { + if (PreferredSize.TraceVerbose) + { + + foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(obj)) + { + if (pd.Name == "PreferredSize") + { continue; // avoid accidentally forcing a call to GetPreferredSize } - try { - if (pd.IsBrowsable && !pd.IsReadOnly && pd.SerializationVisibility != DesignerSerializationVisibility.Hidden) { - propertyHash[pd.Name] = pd.Converter.ConvertToString(pd.GetValue(obj)); - } + try + { + if (pd.IsBrowsable && !pd.IsReadOnly && pd.SerializationVisibility != DesignerSerializationVisibility.Hidden) + { + propertyHash[pd.Name] = pd.Converter.ConvertToString(pd.GetValue(obj)); + } } - catch { + catch + { } } } return propertyHash; - + } - -#endif -#endregion + +#endif + #endregion } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DockAndAnchorLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DockAndAnchorLayout.cs index 29fe2ef6b27..23716a69b2e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DockAndAnchorLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DockAndAnchorLayout.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.Layout { +namespace System.Windows.Forms.Layout +{ using System; using System.Collections; using System.Collections.Generic; @@ -14,7 +15,8 @@ namespace System.Windows.Forms.Layout { using ControlCollection = System.Windows.Forms.Control.ControlCollection; using CompModSwitches = System.ComponentModel.CompModSwitches; - internal class DefaultLayout : LayoutEngine { + internal class DefaultLayout : LayoutEngine + { // Singleton instance shared by all controls. internal static readonly DefaultLayout Instance = new DefaultLayout(); @@ -25,50 +27,60 @@ internal class DefaultLayout : LayoutEngine { // Loop through the AutoSized controls and expand them if they are smaller than // their preferred size. If expanding the controls causes overlap, bump the overlapped // control if it is AutoRelocatable. - private static void LayoutAutoSizedControls(IArrangedElement container) { + private static void LayoutAutoSizedControls(IArrangedElement container) + { ArrangedElementCollection children = container.Children; - for (int i = children.Count - 1; i >= 0; i--) { + for (int i = children.Count - 1; i >= 0; i--) + { IArrangedElement element = children[i]; - - if(CommonProperties.xGetAutoSizedAndAnchored(element)) { - Rectangle bounds = GetCachedBounds(element); - + + if (CommonProperties.xGetAutoSizedAndAnchored(element)) + { + Rectangle bounds = GetCachedBounds(element); + AnchorStyles anchor = GetAnchor(element); Size proposedConstraints = LayoutUtils.MaxSize; - if ((anchor & (AnchorStyles.Left | AnchorStyles.Right)) == (AnchorStyles.Left | AnchorStyles.Right)) { + if ((anchor & (AnchorStyles.Left | AnchorStyles.Right)) == (AnchorStyles.Left | AnchorStyles.Right)) + { proposedConstraints.Width = bounds.Width; } - if ((anchor & (AnchorStyles.Top | AnchorStyles.Bottom)) == (AnchorStyles.Top | AnchorStyles.Bottom)) { + if ((anchor & (AnchorStyles.Top | AnchorStyles.Bottom)) == (AnchorStyles.Top | AnchorStyles.Bottom)) + { proposedConstraints.Height = bounds.Height; } Size prefSize = element.GetPreferredSize(proposedConstraints); - + Rectangle newBounds = bounds; - - if (CommonProperties.GetAutoSizeMode(element) == AutoSizeMode.GrowAndShrink) { + + if (CommonProperties.GetAutoSizeMode(element) == AutoSizeMode.GrowAndShrink) + { // this is the case for simple things like radio button, checkbox, etc. newBounds = GetGrowthBounds(element, prefSize); } - else { + else + { // we had whacked this check, but it turns out it causes undesirable // behavior in things like panel. a panel with no elements sizes to 0,0. - if(bounds.Width < prefSize.Width || bounds.Height < prefSize.Height) { + if (bounds.Width < prefSize.Width || bounds.Height < prefSize.Height) + { Size newSize = LayoutUtils.UnionSizes(bounds.Size, prefSize); newBounds = GetGrowthBounds(element, newSize); } } - if (newBounds != bounds) { - SetCachedBounds(element, newBounds); + if (newBounds != bounds) + { + SetCachedBounds(element, newBounds); } - } + } } } // Gets the bounds of the element after growing to newSize (note that depending on // anchoring the element may grow to the left/updwards rather than to the // right/downwards. i.e., it may be translated.) - private static Rectangle GetGrowthBounds(IArrangedElement element, Size newSize) { + private static Rectangle GetGrowthBounds(IArrangedElement element, Size newSize) + { GrowthDirection direction = GetGrowthDirection(element); Rectangle oldBounds = GetCachedBounds(element); Point location = oldBounds.Location; @@ -76,12 +88,14 @@ private static Rectangle GetGrowthBounds(IArrangedElement element, Size newSize) Debug.Assert((CommonProperties.GetAutoSizeMode(element) == AutoSizeMode.GrowAndShrink || newSize.Height >= oldBounds.Height && newSize.Width >= oldBounds.Width), "newSize expected to be >= current size."); - if((direction & GrowthDirection.Left) != GrowthDirection.None) { + if ((direction & GrowthDirection.Left) != GrowthDirection.None) + { // We are growing towards the left, translate X location.X -= newSize.Width - oldBounds.Width; } - - if((direction & GrowthDirection.Upward) != GrowthDirection.None) { + + if ((direction & GrowthDirection.Upward) != GrowthDirection.None) + { // We are growing towards the top, translate Y location.Y -= newSize.Height - oldBounds.Height; } @@ -93,24 +107,31 @@ private static Rectangle GetGrowthBounds(IArrangedElement element, Size newSize) return newBounds; } // Examines an elements anchoring to figure out which direction it should grow. - private static GrowthDirection GetGrowthDirection(IArrangedElement element) { + private static GrowthDirection GetGrowthDirection(IArrangedElement element) + { AnchorStyles anchor = GetAnchor(element); GrowthDirection growthDirection = GrowthDirection.None; - - if((anchor & AnchorStyles.Right) != AnchorStyles.None - && (anchor & AnchorStyles.Left) == AnchorStyles.None) { + + if ((anchor & AnchorStyles.Right) != AnchorStyles.None + && (anchor & AnchorStyles.Left) == AnchorStyles.None) + { // element is anchored to the right, but not the left. growthDirection |= GrowthDirection.Left; - } else { + } + else + { // otherwise we grow towards the right (common case) growthDirection |= GrowthDirection.Right; } - - if((anchor & AnchorStyles.Bottom) != AnchorStyles.None - && (anchor & AnchorStyles.Top) == AnchorStyles.None) { + + if ((anchor & AnchorStyles.Bottom) != AnchorStyles.None + && (anchor & AnchorStyles.Top) == AnchorStyles.None) + { // element is anchored to the bottom, but not the top. growthDirection |= GrowthDirection.Upward; - } else { + } + else + { // otherwise we grow towards the bottom. (common case) growthDirection |= GrowthDirection.Downward; } @@ -125,7 +146,8 @@ private static GrowthDirection GetGrowthDirection(IArrangedElement element) { } // Layout for a single anchored control. There's no order dependency when laying out anchored controls. - private static Rectangle GetAnchorDestination(IArrangedElement element, Rectangle displayRect, bool measureOnly) { + private static Rectangle GetAnchorDestination(IArrangedElement element, Rectangle displayRect, bool measureOnly) + { // Container can not be null since we AschorControls takes a non-null container. Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "\t\t'" + element + "' is anchored at " + GetCachedBounds(element).ToString()); @@ -145,42 +167,52 @@ private static Rectangle GetAnchorDestination(IArrangedElement element, Rectangl AnchorStyles anchor = GetAnchor(element); - if (IsAnchored(anchor, AnchorStyles.Right)) { + if (IsAnchored(anchor, AnchorStyles.Right)) + { Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "\t\t...adjusting right"); right += displayRect.Width; - if (!IsAnchored(anchor, AnchorStyles.Left)) { + if (!IsAnchored(anchor, AnchorStyles.Left)) + { Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "\t\t...adjusting left"); left += displayRect.Width; } } - else if (!IsAnchored(anchor, AnchorStyles.Left)) { + else if (!IsAnchored(anchor, AnchorStyles.Left)) + { Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "\t\t...adjusting left & right"); right += (displayRect.Width / 2); left += (displayRect.Width / 2); } - if (IsAnchored(anchor, AnchorStyles.Bottom)) { + if (IsAnchored(anchor, AnchorStyles.Bottom)) + { Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "\t\t...adjusting bottom"); bottom += displayRect.Height; - if (!IsAnchored(anchor, AnchorStyles.Top)) { + if (!IsAnchored(anchor, AnchorStyles.Top)) + { Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "\t\t...adjusting top"); top += displayRect.Height; } } - else if (!IsAnchored(anchor, AnchorStyles.Top)) { + else if (!IsAnchored(anchor, AnchorStyles.Top)) + { Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "\t\t...adjusting top & bottom"); - bottom += (displayRect.Height/2); - top += (displayRect.Height/2); + bottom += (displayRect.Height / 2); + top += (displayRect.Height / 2); } - if (!measureOnly) { + if (!measureOnly) + { // the size is actually zero, set the width and heights appropriately. - if (right < left) right = left; - if (bottom < top) bottom = top; + if (right < left) + right = left; + if (bottom < top) + bottom = top; } - else { + else + { Rectangle cachedBounds = GetCachedBounds(element); // in this scenario we've likely been passed a 0 sized display rectangle to determine our height. // we will need to translate the right and bottom edges as necessary to the positive plane. @@ -188,13 +220,16 @@ private static Rectangle GetAnchorDestination(IArrangedElement element, Rectangl // right < left means the control is anchored both left and right. // cachedBounds != element.Bounds means the element's size has changed // any, all, or none of these can be true. - if (right < left || cachedBounds.Width != element.Bounds.Width || cachedBounds.X != element.Bounds.X) { - if (cachedBounds != element.Bounds) { + if (right < left || cachedBounds.Width != element.Bounds.Width || cachedBounds.X != element.Bounds.X) + { + if (cachedBounds != element.Bounds) + { left = Math.Max(Math.Abs(left), Math.Abs(cachedBounds.Left)); } right = left + Math.Max(element.Bounds.Width, cachedBounds.Width) + Math.Abs(right); } - else { + else + { left = left > 0 ? left : element.Bounds.Left; right = right > 0 ? right : element.Bounds.Right + Math.Abs(right); } @@ -202,34 +237,39 @@ private static Rectangle GetAnchorDestination(IArrangedElement element, Rectangl // bottom < top means the control is anchored both top and bottom. // cachedBounds != element.Bounds means the element's size has changed // any, all, or none of these can be true. - if (bottom < top || cachedBounds.Height != element.Bounds.Height || cachedBounds.Y != element.Bounds.Y) { - if (cachedBounds != element.Bounds) { + if (bottom < top || cachedBounds.Height != element.Bounds.Height || cachedBounds.Y != element.Bounds.Y) + { + if (cachedBounds != element.Bounds) + { top = Math.Max(Math.Abs(top), Math.Abs(cachedBounds.Top)); } bottom = top + Math.Max(element.Bounds.Height, cachedBounds.Height) + Math.Abs(bottom); } - else { + else + { top = top > 0 ? top : element.Bounds.Top; bottom = bottom > 0 ? bottom : element.Bounds.Bottom + Math.Abs(bottom); } } - + Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "\t\t...new anchor dim (l,t,r,b) {" + (left) + ", " + (top) + ", " + (right) + ", " + (bottom) + "}"); - + return new Rectangle(left, top, right - left, bottom - top); } - - private static void LayoutAnchoredControls(IArrangedElement container) { + + private static void LayoutAnchoredControls(IArrangedElement container) + { Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "\tAnchor Processing"); Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "\t\tdisplayRect: " + container.DisplayRectangle.ToString()); Rectangle displayRectangle = container.DisplayRectangle; - if (CommonProperties.GetAutoSize(container) && ((displayRectangle.Width == 0) || (displayRectangle.Height == 0))) { + if (CommonProperties.GetAutoSize(container) && ((displayRectangle.Width == 0) || (displayRectangle.Height == 0))) + { // we havent set oursleves to the preferred size yet. proceeding will // just set all the control widths to zero. let's return here return; @@ -237,17 +277,20 @@ private static void LayoutAnchoredControls(IArrangedElement container) { ArrangedElementCollection children = container.Children; - for (int i = children.Count - 1; i >= 0; i--) { + for (int i = children.Count - 1; i >= 0; i--) + { IArrangedElement element = children[i]; - if (CommonProperties.GetNeedsAnchorLayout(element)) { + if (CommonProperties.GetNeedsAnchorLayout(element)) + { Debug.Assert(GetAnchorInfo(element) != null, "AnchorInfo should be initialized before LayoutAnchorControls()."); SetCachedBounds(element, GetAnchorDestination(element, displayRectangle, /*measureOnly=*/false)); } } } - private static Size LayoutDockedControls(IArrangedElement container, bool measureOnly) { + private static Size LayoutDockedControls(IArrangedElement container, bool measureOnly) + { Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "\tDock Processing"); Debug.Assert(!HasCachedBounds(container), "Do not call this method with an active cached bounds list."); @@ -256,70 +299,79 @@ private static Size LayoutDockedControls(IArrangedElement container, bool measur // If doing actual layout, we start with the container's rect and subtract as we layout. Rectangle remainingBounds = measureOnly ? Rectangle.Empty : container.DisplayRectangle; Size preferredSize = Size.Empty; - + IArrangedElement mdiClient = null; // Docking layout is order dependent. After much debate, we decided to use z-order as the // docking order. (Introducing a DockOrder property was a close second) ArrangedElementCollection children = container.Children; - for (int i = children.Count - 1; i >= 0; i--) { + for (int i = children.Count - 1; i >= 0; i--) + { IArrangedElement element = children[i]; Debug.Assert(element.Bounds == GetCachedBounds(element), "Why do we have cachedBounds for a docked element?"); - if (CommonProperties.GetNeedsDockLayout(element)) { - // Some controls modify their bounds when you call SetBoundsCore. We + if (CommonProperties.GetNeedsDockLayout(element)) + { + // Some controls modify their bounds when you call SetBoundsCore. We // therefore need to read the value of bounds back when adjusting our layout rectangle. - switch (GetDock(element)) { - case DockStyle.Top: { - Size elementSize = GetVerticalDockedSize(element, remainingBounds.Size, measureOnly); - Rectangle newElementBounds = new Rectangle(remainingBounds.X, remainingBounds.Y, elementSize.Width, elementSize.Height); + switch (GetDock(element)) + { + case DockStyle.Top: + { + Size elementSize = GetVerticalDockedSize(element, remainingBounds.Size, measureOnly); + Rectangle newElementBounds = new Rectangle(remainingBounds.X, remainingBounds.Y, elementSize.Width, elementSize.Height); + + xLayoutDockedControl(element, newElementBounds, measureOnly, ref preferredSize, ref remainingBounds); - xLayoutDockedControl(element, newElementBounds, measureOnly, ref preferredSize, ref remainingBounds); + // What we are really doing here: top += element.Bounds.Height; + remainingBounds.Y += element.Bounds.Height; + remainingBounds.Height -= element.Bounds.Height; + break; + } + case DockStyle.Bottom: + { + Size elementSize = GetVerticalDockedSize(element, remainingBounds.Size, measureOnly); + Rectangle newElementBounds = new Rectangle(remainingBounds.X, remainingBounds.Bottom - elementSize.Height, elementSize.Width, elementSize.Height); - // What we are really doing here: top += element.Bounds.Height; - remainingBounds.Y += element.Bounds.Height; - remainingBounds.Height -= element.Bounds.Height; - break; - } - case DockStyle.Bottom: { - Size elementSize = GetVerticalDockedSize(element, remainingBounds.Size, measureOnly); - Rectangle newElementBounds = new Rectangle(remainingBounds.X, remainingBounds.Bottom - elementSize.Height, elementSize.Width, elementSize.Height); + xLayoutDockedControl(element, newElementBounds, measureOnly, ref preferredSize, ref remainingBounds); - xLayoutDockedControl(element, newElementBounds, measureOnly, ref preferredSize, ref remainingBounds); + // What we are really doing here: bottom -= element.Bounds.Height; + remainingBounds.Height -= element.Bounds.Height; - // What we are really doing here: bottom -= element.Bounds.Height; - remainingBounds.Height -= element.Bounds.Height; - - break; - } - case DockStyle.Left: { - Size elementSize = GetHorizontalDockedSize(element, remainingBounds.Size, measureOnly); - Rectangle newElementBounds = new Rectangle(remainingBounds.X, remainingBounds.Y, elementSize.Width, elementSize.Height); + break; + } + case DockStyle.Left: + { + Size elementSize = GetHorizontalDockedSize(element, remainingBounds.Size, measureOnly); + Rectangle newElementBounds = new Rectangle(remainingBounds.X, remainingBounds.Y, elementSize.Width, elementSize.Height); - xLayoutDockedControl(element, newElementBounds, measureOnly, ref preferredSize, ref remainingBounds); + xLayoutDockedControl(element, newElementBounds, measureOnly, ref preferredSize, ref remainingBounds); - // What we are really doing here: left += element.Bounds.Width; - remainingBounds.X += element.Bounds.Width; - remainingBounds.Width -= element.Bounds.Width; - break; - } - case DockStyle.Right: { - Size elementSize = GetHorizontalDockedSize(element, remainingBounds.Size, measureOnly); - Rectangle newElementBounds = new Rectangle(remainingBounds.Right - elementSize.Width, remainingBounds.Y, elementSize.Width, elementSize.Height); + // What we are really doing here: left += element.Bounds.Width; + remainingBounds.X += element.Bounds.Width; + remainingBounds.Width -= element.Bounds.Width; + break; + } + case DockStyle.Right: + { + Size elementSize = GetHorizontalDockedSize(element, remainingBounds.Size, measureOnly); + Rectangle newElementBounds = new Rectangle(remainingBounds.Right - elementSize.Width, remainingBounds.Y, elementSize.Width, elementSize.Height); - xLayoutDockedControl(element, newElementBounds, measureOnly, ref preferredSize, ref remainingBounds); + xLayoutDockedControl(element, newElementBounds, measureOnly, ref preferredSize, ref remainingBounds); - // What we are really doing here: right -= element.Bounds.Width; - remainingBounds.Width -= element.Bounds.Width; - break; - } + // What we are really doing here: right -= element.Bounds.Width; + remainingBounds.Width -= element.Bounds.Width; + break; + } case DockStyle.Fill: - if (element is MdiClient) { + if (element is MdiClient) + { Debug.Assert(mdiClient == null, "How did we end up with multiple MdiClients?"); mdiClient = element; } - else { + else + { Size elementSize = remainingBounds.Size;//GetFillDockedSize(element, remainingBounds.Size, measureOnly); Rectangle newElementBounds = new Rectangle(remainingBounds.X, remainingBounds.Y, elementSize.Width, elementSize.Height); @@ -333,7 +385,8 @@ private static Size LayoutDockedControls(IArrangedElement container, bool measur } // Treat the MDI client specially, since it's supposed to blend in with the parent form - if (mdiClient != null) { + if (mdiClient != null) + { SetCachedBounds(mdiClient, remainingBounds); } } @@ -342,29 +395,37 @@ private static Size LayoutDockedControls(IArrangedElement container, bool measur // Helper method that either sets the element bounds or does the preferredSize computation based on // the value of measureOnly. - private static void xLayoutDockedControl(IArrangedElement element, Rectangle newElementBounds, bool measureOnly, ref Size preferredSize, ref Rectangle remainingBounds) { - if (measureOnly) { + private static void xLayoutDockedControl(IArrangedElement element, Rectangle newElementBounds, bool measureOnly, ref Size preferredSize, ref Rectangle remainingBounds) + { + if (measureOnly) + { Size neededSize = new Size( Math.Max(0, newElementBounds.Width - remainingBounds.Width), Math.Max(0, newElementBounds.Height - remainingBounds.Height)); DockStyle dockStyle = GetDock(element); - if ((dockStyle == DockStyle.Top) || (dockStyle == DockStyle.Bottom)) { + if ((dockStyle == DockStyle.Top) || (dockStyle == DockStyle.Bottom)) + { neededSize.Width = 0; } - if ((dockStyle == DockStyle.Left) || (dockStyle == DockStyle.Right)) { + if ((dockStyle == DockStyle.Left) || (dockStyle == DockStyle.Right)) + { neededSize.Height = 0; } - if (dockStyle != DockStyle.Fill) { + if (dockStyle != DockStyle.Fill) + { preferredSize += neededSize; remainingBounds.Size += neededSize; } - else if(dockStyle == DockStyle.Fill && CommonProperties.GetAutoSize(element)) { + else if (dockStyle == DockStyle.Fill && CommonProperties.GetAutoSize(element)) + { Size elementPrefSize = element.GetPreferredSize(neededSize); remainingBounds.Size += elementPrefSize; preferredSize += elementPrefSize; } - } else { + } + else + { element.SetBounds(newElementBounds, BoundsSpecified.None); #if DEBUG @@ -374,7 +435,8 @@ private static void xLayoutDockedControl(IArrangedElement element, Rectangle new // to enforce constraints like AutoSize. Generally you can just move this code to Control.GetAdjustedSize // and then PreferredSize will also pick up these constraints. See ComboBox as an example. // - if (CommonProperties.GetAutoSize(element) && !CommonProperties.GetSelfAutoSizeInDefaultLayout(element)) { + if (CommonProperties.GetAutoSize(element) && !CommonProperties.GetSelfAutoSizeInDefaultLayout(element)) + { Debug.Assert( (newElementBounds.Width < 0 || element.Bounds.Width == newElementBounds.Width) && (newElementBounds.Height < 0 || element.Bounds.Height == newElementBounds.Height), @@ -384,27 +446,35 @@ private static void xLayoutDockedControl(IArrangedElement element, Rectangle new } } - private static Size GetVerticalDockedSize(IArrangedElement element, Size remainingSize, bool measureOnly) { + private static Size GetVerticalDockedSize(IArrangedElement element, Size remainingSize, bool measureOnly) + { Size newSize = xGetDockedSize(element, remainingSize, /* constraints = */ new Size(remainingSize.Width, 1), measureOnly); - if (!measureOnly) { + if (!measureOnly) + { newSize.Width = remainingSize.Width; - } else { + } + else + { newSize.Width = Math.Max(newSize.Width, remainingSize.Width); } Debug.Assert((measureOnly && (newSize.Width >= remainingSize.Width)) || (newSize.Width == remainingSize.Width), "Error detected in GetVerticalDockedSize: Dock size computed incorrectly during layout."); - + return newSize; } - private static Size GetHorizontalDockedSize(IArrangedElement element, Size remainingSize, bool measureOnly) { + private static Size GetHorizontalDockedSize(IArrangedElement element, Size remainingSize, bool measureOnly) + { Size newSize = xGetDockedSize(element, remainingSize, /* constraints = */ new Size(1, remainingSize.Height), measureOnly); - if (!measureOnly) { + if (!measureOnly) + { newSize.Height = remainingSize.Height; - } else { + } + else + { newSize.Height = Math.Max(newSize.Height, remainingSize.Height); } @@ -431,15 +501,19 @@ private static Size GetHorizontalDockedSize(IArrangedElement element, Size remai // return newSize; //} - private static Size xGetDockedSize(IArrangedElement element, Size remainingSize, Size constraints, bool measureOnly) { + private static Size xGetDockedSize(IArrangedElement element, Size remainingSize, Size constraints, bool measureOnly) + { Size desiredSize; - - if (CommonProperties.GetAutoSize(element)) { + + if (CommonProperties.GetAutoSize(element)) + { // Ask control for its desired size using the provided constraints. // (e.g., a control docked to top will constrain width to remaining width // and minimize height.) desiredSize = element.GetPreferredSize(constraints); - } else { + } + else + { desiredSize = element.Bounds.Size; } @@ -447,25 +521,28 @@ private static Size xGetDockedSize(IArrangedElement element, Size remainingSize, return desiredSize; } - internal override bool LayoutCore(IArrangedElement container, LayoutEventArgs args) { + internal override bool LayoutCore(IArrangedElement container, LayoutEventArgs args) + { Size garbage; // PreferredSize is garbage if we are not measuring. return xLayout(container, /* measureOnly = */ false, out garbage); } // Note: PreferredSize is only computed if measureOnly = true. - private static bool xLayout(IArrangedElement container, bool measureOnly, out Size preferredSize) { - /* - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, - string.Format("{1}(hwnd=0x{0:X}).OnLayout", - (container.IsHandleCreated ? container.Handle : IntPtr.Zero), - container.GetType().FullName)); - */ - + private static bool xLayout(IArrangedElement container, bool measureOnly, out Size preferredSize) + { + /* + Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, + string.Format("{1}(hwnd=0x{0:X}).OnLayout", + (container.IsHandleCreated ? container.Handle : IntPtr.Zero), + container.GetType().FullName)); + */ + ArrangedElementCollection children = container.Children; preferredSize = new Size(-7103, -7105); // PreferredSize is garbage unless measureOnly is specified - + // short circuit for items with no children - if (!measureOnly && children.Count == 0) { + if (!measureOnly && children.Count == 0) + { return CommonProperties.GetAutoSize(container); } @@ -473,14 +550,19 @@ private static bool xLayout(IArrangedElement container, bool measureOnly, out Si bool anchor = false; bool autoSize = false; - - for (int i = children.Count - 1; i >= 0; i--) { + + for (int i = children.Count - 1; i >= 0; i--) + { IArrangedElement element = children[i]; - - if (CommonProperties.GetNeedsDockAndAnchorLayout(element)) { - if (!dock && CommonProperties.GetNeedsDockLayout(element)) dock = true; - if (!anchor && CommonProperties.GetNeedsAnchorLayout(element)) anchor = true; - if (!autoSize && CommonProperties.xGetAutoSizedAndAnchored(element)) autoSize = true; + + if (CommonProperties.GetNeedsDockAndAnchorLayout(element)) + { + if (!dock && CommonProperties.GetNeedsDockLayout(element)) + dock = true; + if (!anchor && CommonProperties.GetNeedsAnchorLayout(element)) + anchor = true; + if (!autoSize && CommonProperties.xGetAutoSizedAndAnchored(element)) + autoSize = true; } } @@ -490,39 +572,46 @@ private static bool xLayout(IArrangedElement container, bool measureOnly, out Si Size preferredSizeForDocking = Size.Empty; Size preferredSizeForAnchoring = Size.Empty; - if (dock) preferredSizeForDocking = LayoutDockedControls(container, measureOnly); - if (anchor && !measureOnly) { + if (dock) + preferredSizeForDocking = LayoutDockedControls(container, measureOnly); + if (anchor && !measureOnly) + { // in the case of anchor, where we currently are defines the preferred size, // so dont recalculate the positions of everything. LayoutAnchoredControls(container); } - - if (autoSize) LayoutAutoSizedControls(container); - if (!measureOnly) { + if (autoSize) + LayoutAutoSizedControls(container); + + if (!measureOnly) + { // Set the anchored controls to their computed positions. - ApplyCachedBounds(container); + ApplyCachedBounds(container); } - else { - + else + { + // Finish the preferredSize computation and clear cached anchored positions. preferredSizeForAnchoring = GetAnchorPreferredSize(container); Padding containerPadding = Padding.Empty; Control control = container as Control; - if (control != null) { - // calling this will respect Control.DefaultPadding. - containerPadding = control.Padding; + if (control != null) + { + // calling this will respect Control.DefaultPadding. + containerPadding = control.Padding; } - else { // not likely to happen but… - containerPadding = CommonProperties.GetPadding(container, Padding.Empty); + else + { // not likely to happen but… + containerPadding = CommonProperties.GetPadding(container, Padding.Empty); } preferredSizeForAnchoring.Width -= containerPadding.Left; preferredSizeForAnchoring.Height -= containerPadding.Top; ClearCachedBounds(container); - preferredSize = LayoutUtils.UnionSizes(preferredSizeForDocking, preferredSizeForAnchoring); + preferredSize = LayoutUtils.UnionSizes(preferredSizeForDocking, preferredSizeForAnchoring); } return CommonProperties.GetAutoSize(container); @@ -533,25 +622,28 @@ private static bool xLayout(IArrangedElement container, bool measureOnly, out Si /// This should only be called when the parent control changes or the /// anchor mode changes. /// - private static void UpdateAnchorInfo(IArrangedElement element) { + private static void UpdateAnchorInfo(IArrangedElement element) + { Debug.Assert(!HasCachedBounds(element.Container), "Do not call this method with an active cached bounds list."); AnchorInfo anchorInfo = GetAnchorInfo(element); - if(anchorInfo == null) { + if (anchorInfo == null) + { anchorInfo = new AnchorInfo(); SetAnchorInfo(element, anchorInfo); } - + Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "Update anchor info"); Debug.Indent(); Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, element.Container == null ? "No parent" : "Parent"); - if (CommonProperties.GetNeedsAnchorLayout(element) && element.Container != null) { + if (CommonProperties.GetNeedsAnchorLayout(element) && element.Container != null) + { Rectangle bounds = GetCachedBounds(element); - + AnchorInfo oldAnchorInfo = new AnchorInfo(); oldAnchorInfo.Left = anchorInfo.Left; oldAnchorInfo.Top = anchorInfo.Top; @@ -576,73 +668,91 @@ private static void UpdateAnchorInfo(IArrangedElement element) { anchorInfo.Bottom -= parentDisplayRect.Y; AnchorStyles anchor = GetAnchor(element); - if (IsAnchored(anchor, AnchorStyles.Right)) { - if (DpiHelper.IsScalingRequirementMet && (anchorInfo.Right - parentWidth > 0) && (oldAnchorInfo.Right < 0)) { + if (IsAnchored(anchor, AnchorStyles.Right)) + { + if (DpiHelper.IsScalingRequirementMet && (anchorInfo.Right - parentWidth > 0) && (oldAnchorInfo.Right < 0)) + { // parent was resized to fit its parent, or screen, we need to reuse old anchor info to prevent losing control beyond right edge anchorInfo.Right = oldAnchorInfo.Right; anchorInfo.Left = oldAnchorInfo.Right - bounds.Width; // control might have been resized, update Left anchor } - else { + else + { anchorInfo.Right -= parentWidth; - if (!IsAnchored(anchor, AnchorStyles.Left)) { + if (!IsAnchored(anchor, AnchorStyles.Left)) + { anchorInfo.Left -= parentWidth; } } } - else if (!IsAnchored(anchor, AnchorStyles.Left)) { - anchorInfo.Right -= (parentWidth/2); - anchorInfo.Left -= (parentWidth/2); + else if (!IsAnchored(anchor, AnchorStyles.Left)) + { + anchorInfo.Right -= (parentWidth / 2); + anchorInfo.Left -= (parentWidth / 2); } - if (IsAnchored(anchor, AnchorStyles.Bottom)) { - if (DpiHelper.IsScalingRequirementMet && (anchorInfo.Bottom - parentHeight > 0) && (oldAnchorInfo.Bottom < 0)) { + if (IsAnchored(anchor, AnchorStyles.Bottom)) + { + if (DpiHelper.IsScalingRequirementMet && (anchorInfo.Bottom - parentHeight > 0) && (oldAnchorInfo.Bottom < 0)) + { // parent was resized to fit its parent, or screen, we need to reuse old anchor info to prevent losing control beyond bottom edge anchorInfo.Bottom = oldAnchorInfo.Bottom; anchorInfo.Top = oldAnchorInfo.Bottom - bounds.Height; // control might have been resized, update Top anchor } - else { + else + { anchorInfo.Bottom -= parentHeight; - if (!IsAnchored(anchor, AnchorStyles.Top)) { + if (!IsAnchored(anchor, AnchorStyles.Top)) + { anchorInfo.Top -= parentHeight; } } } - else if (!IsAnchored(anchor, AnchorStyles.Top)) { - anchorInfo.Bottom -= (parentHeight/2); - anchorInfo.Top -= (parentHeight/2); + else if (!IsAnchored(anchor, AnchorStyles.Top)) + { + anchorInfo.Bottom -= (parentHeight / 2); + anchorInfo.Top -= (parentHeight / 2); } - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "anchor info (l,t,r,b): (" + anchorInfo.Left + ", " + anchorInfo.Top + ", " + anchorInfo.Right + ", " + anchorInfo.Bottom + ")"); + Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "anchor info (l,t,r,b): (" + anchorInfo.Left + ", " + anchorInfo.Top + ", " + anchorInfo.Right + ", " + anchorInfo.Bottom + ")"); } Debug.Unindent(); } - public static AnchorStyles GetAnchor(IArrangedElement element) { + public static AnchorStyles GetAnchor(IArrangedElement element) + { return CommonProperties.xGetAnchor(element); } - - public static void SetAnchor(IArrangedElement container, IArrangedElement element, AnchorStyles value) { + + public static void SetAnchor(IArrangedElement container, IArrangedElement element, AnchorStyles value) + { AnchorStyles oldValue = GetAnchor(element); - if (oldValue != value) { - if(CommonProperties.GetNeedsDockLayout(element)) { + if (oldValue != value) + { + if (CommonProperties.GetNeedsDockLayout(element)) + { // We set dock back to none to cause the element to size back to its original bounds. SetDock(element, DockStyle.None); } CommonProperties.xSetAnchor(element, value); - if (CommonProperties.GetNeedsAnchorLayout(element)) { + if (CommonProperties.GetNeedsAnchorLayout(element)) + { UpdateAnchorInfo(element); } - else { + else + { SetAnchorInfo(element, null); } - if (element.Container != null) { + if (element.Container != null) + { bool rightReleased = IsAnchored(oldValue, AnchorStyles.Right) && !IsAnchored(value, AnchorStyles.Right); bool bottomReleased = IsAnchored(oldValue, AnchorStyles.Bottom) && !IsAnchored(value, AnchorStyles.Bottom); - if(element.Container.Container != null && (rightReleased || bottomReleased)) { + if (element.Container.Container != null && (rightReleased || bottomReleased)) + { // If the right or bottom anchor is being released, we have a special case where the element's // margin may affect preferredSize where it didn't previously. Rather than do an expensive // check for this in OnLayout, we just detect the case her and force a relayout. @@ -654,51 +764,61 @@ public static void SetAnchor(IArrangedElement container, IArrangedElement elemen Debug.Assert(GetAnchor(element) == value, "Error setting Anchor value."); } - public static DockStyle GetDock(IArrangedElement element) { + public static DockStyle GetDock(IArrangedElement element) + { return CommonProperties.xGetDock(element); } - public static void SetDock(IArrangedElement element, DockStyle value) { + public static void SetDock(IArrangedElement element, DockStyle value) + { Debug.Assert(!HasCachedBounds(element.Container), "Do not call this method with an active cached bounds list."); - if (GetDock(element) != value) { + if (GetDock(element) != value) + { //valid values are 0x0 to 0x5 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)DockStyle.None, (int)DockStyle.Fill)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)DockStyle.None, (int)DockStyle.Fill)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DockStyle)); } bool dockNeedsLayout = CommonProperties.GetNeedsDockLayout(element); CommonProperties.xSetDock(element, value); - using (new LayoutTransaction(element.Container as Control, element, PropertyNames.Dock)) { + using (new LayoutTransaction(element.Container as Control, element, PropertyNames.Dock)) + { // if the item is autosized, calling setbounds performs a layout, which // if we havent set the anchor info properly yet makes dock/anchor layout cranky. - - if (value == DockStyle.None) { - if (dockNeedsLayout) { + + if (value == DockStyle.None) + { + if (dockNeedsLayout) + { // We are transitioning from docked to not docked, restore the original bounds. element.SetBounds(CommonProperties.GetSpecifiedBounds(element), BoundsSpecified.None); // Restore Anchor information as its now relevant again. UpdateAnchorInfo(element); } } - else { + else + { // Now setup the new bounds. // element.SetBounds(CommonProperties.GetSpecifiedBounds(element), BoundsSpecified.All); } } - + } Debug.Assert(GetDock(element) == value, "Error setting Dock value."); } - public static void ScaleAnchorInfo(IArrangedElement element, SizeF factor) { + public static void ScaleAnchorInfo(IArrangedElement element, SizeF factor) + { AnchorInfo anchorInfo = GetAnchorInfo(element); // some controls don't have AnchorInfo, i.e. Panels - if (anchorInfo != null) { + if (anchorInfo != null) + { anchorInfo.Left = (int)((float)anchorInfo.Left * factor.Width); anchorInfo.Top = (int)((float)anchorInfo.Top * factor.Height); anchorInfo.Right = (int)((float)anchorInfo.Right * factor.Width); @@ -708,28 +828,36 @@ public static void ScaleAnchorInfo(IArrangedElement element, SizeF factor) { } } - private static Rectangle GetCachedBounds(IArrangedElement element) { - if(element.Container != null) { - IDictionary dictionary = (IDictionary) element.Container.Properties.GetObject(_cachedBoundsProperty); - if(dictionary != null) { + private static Rectangle GetCachedBounds(IArrangedElement element) + { + if (element.Container != null) + { + IDictionary dictionary = (IDictionary)element.Container.Properties.GetObject(_cachedBoundsProperty); + if (dictionary != null) + { object bounds = dictionary[element]; - if(bounds != null) { - return (Rectangle) bounds; + if (bounds != null) + { + return (Rectangle)bounds; } } } return element.Bounds; } - private static bool HasCachedBounds(IArrangedElement container) { + private static bool HasCachedBounds(IArrangedElement container) + { return container != null && container.Properties.GetObject(_cachedBoundsProperty) != null; } - private static void ApplyCachedBounds(IArrangedElement container) { - if (CommonProperties.GetAutoSize(container)) { + private static void ApplyCachedBounds(IArrangedElement container) + { + if (CommonProperties.GetAutoSize(container)) + { //Avoiding calling DisplayRectangle before checking AutoSize for Everett compat Rectangle displayRectangle = container.DisplayRectangle; - if ((displayRectangle.Width == 0) || (displayRectangle.Height == 0)) { + if ((displayRectangle.Width == 0) || (displayRectangle.Height == 0)) + { ClearCachedBounds(container); return; } @@ -737,43 +865,50 @@ private static void ApplyCachedBounds(IArrangedElement container) { - IDictionary dictionary = (IDictionary) container.Properties.GetObject(_cachedBoundsProperty); - if(dictionary != null) { + IDictionary dictionary = (IDictionary)container.Properties.GetObject(_cachedBoundsProperty); + if (dictionary != null) + { #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) { + 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; - } + break; + } #endif } ClearCachedBounds(container); } } - private static void ClearCachedBounds(IArrangedElement container) { + private static void ClearCachedBounds(IArrangedElement container) + { container.Properties.SetObject(_cachedBoundsProperty, null); } - private static void SetCachedBounds(IArrangedElement element, Rectangle bounds) { - if(bounds != GetCachedBounds(element)) { - IDictionary dictionary = (IDictionary) element.Container.Properties.GetObject(_cachedBoundsProperty); - if (dictionary == null) { + private static void SetCachedBounds(IArrangedElement element, Rectangle bounds) + { + if (bounds != GetCachedBounds(element)) + { + IDictionary dictionary = (IDictionary)element.Container.Properties.GetObject(_cachedBoundsProperty); + if (dictionary == null) + { dictionary = new HybridDictionary(); element.Container.Properties.SetObject(_cachedBoundsProperty, dictionary); } @@ -781,106 +916,124 @@ private static void SetCachedBounds(IArrangedElement element, Rectangle bounds) } } - private static AnchorInfo GetAnchorInfo(IArrangedElement element) { - return (AnchorInfo) element.Properties.GetObject(_layoutInfoProperty); + private static AnchorInfo GetAnchorInfo(IArrangedElement element) + { + return (AnchorInfo)element.Properties.GetObject(_layoutInfoProperty); } - private static void SetAnchorInfo(IArrangedElement element, AnchorInfo value) { + private static void SetAnchorInfo(IArrangedElement element, AnchorInfo value) + { element.Properties.SetObject(_layoutInfoProperty, value); } - internal override void InitLayoutCore(IArrangedElement element, BoundsSpecified specified) { + internal override void InitLayoutCore(IArrangedElement element, BoundsSpecified specified) + { Debug.Assert(specified == BoundsSpecified.None || GetCachedBounds(element) == element.Bounds, "Attempt to InitLayout while element has active cached bounds."); - if(specified != BoundsSpecified.None && CommonProperties.GetNeedsAnchorLayout(element)) { + if (specified != BoundsSpecified.None && CommonProperties.GetNeedsAnchorLayout(element)) + { UpdateAnchorInfo(element); } } - internal override Size GetPreferredSize(IArrangedElement container, Size proposedBounds) { + internal override Size GetPreferredSize(IArrangedElement container, Size proposedBounds) + { Debug.Assert(!HasCachedBounds(container), "Do not call this method with an active cached bounds list."); - + Size prefSize; - + xLayout(container, /* measureOnly = */ true, out prefSize); -/* container.Bounds = prefSize; - xLayout(container, false, out prefSize); + /* container.Bounds = prefSize; + xLayout(container, false, out prefSize); + + // make sure controls are big enough to fit on form if not - increase container size + container.Bounds = newBounds; - // make sure controls are big enough to fit on form if not - increase container size - container.Bounds = newBounds; + xLayout(container, true, out prefSize);*/ - xLayout(container, true, out prefSize);*/ - return prefSize; } - private static Size GetAnchorPreferredSize(IArrangedElement container) { + private static Size GetAnchorPreferredSize(IArrangedElement container) + { Size prefSize = Size.Empty; - + ArrangedElementCollection children = container.Children; - for (int i = children.Count - 1; i >= 0; i--) { + for (int i = children.Count - 1; i >= 0; i--) + { IArrangedElement element = container.Children[i]; - if(!CommonProperties.GetNeedsDockLayout(element) && element.ParticipatesInLayout) { + if (!CommonProperties.GetNeedsDockLayout(element) && element.ParticipatesInLayout) + { AnchorStyles anchor = GetAnchor(element); Padding margin = CommonProperties.GetMargin(element); Rectangle elementSpace = LayoutUtils.InflateRect(GetCachedBounds(element), margin); - if (IsAnchored(anchor, AnchorStyles.Left) && !IsAnchored(anchor, AnchorStyles.Right)) { + if (IsAnchored(anchor, AnchorStyles.Left) && !IsAnchored(anchor, AnchorStyles.Right)) + { // If we are anchored to the left we make sure the container is large enough not to clip us // (unless we are right anchored, in which case growing the container will just resize us.) prefSize.Width = Math.Max(prefSize.Width, elementSpace.Right); } - - if (/*IsAnchored(anchor, AnchorStyles.Top) &&*/ !IsAnchored(anchor, AnchorStyles.Bottom)) { + + if (/*IsAnchored(anchor, AnchorStyles.Top) &&*/ !IsAnchored(anchor, AnchorStyles.Bottom)) + { // If we are anchored to the top we make sure the container is large enough not to clip us // (unless we are bottom anchored, in which case growing the container will just resize us.) prefSize.Height = Math.Max(prefSize.Height, elementSpace.Bottom); - + } - if (IsAnchored(anchor, AnchorStyles.Right)) { + if (IsAnchored(anchor, AnchorStyles.Right)) + { // If we are right anchored, see what the anchor distance between our right edge and // the container is, and make sure our container is large enough to accomodate us. Rectangle anchorDest = GetAnchorDestination(element, Rectangle.Empty, /*measureOnly=*/true); - if (anchorDest.Width < 0) { + if (anchorDest.Width < 0) + { prefSize.Width = Math.Max(prefSize.Width, elementSpace.Right + anchorDest.Width); } - else { + else + { prefSize.Width = Math.Max(prefSize.Width, anchorDest.Right); } } - - if (IsAnchored(anchor, AnchorStyles.Bottom)) { + + if (IsAnchored(anchor, AnchorStyles.Bottom)) + { // If we are right anchored, see what the anchor distance between our right edge and // the container is, and make sure our container is large enough to accomodate us. Rectangle anchorDest = GetAnchorDestination(element, Rectangle.Empty, /*measureOnly=*/true); - if (anchorDest.Height < 0) { + if (anchorDest.Height < 0) + { prefSize.Height = Math.Max(prefSize.Height, elementSpace.Bottom + anchorDest.Height); } - else { + else + { prefSize.Height = Math.Max(prefSize.Height, anchorDest.Bottom); } } } - } + } return prefSize; } - public static bool IsAnchored(AnchorStyles anchor, AnchorStyles desiredAnchor) { + public static bool IsAnchored(AnchorStyles anchor, AnchorStyles desiredAnchor) + { return (anchor & desiredAnchor) == desiredAnchor; } [Flags] - private enum GrowthDirection { - None = 0, - Upward = 0x01, - Downward = 0x02, - Left = 0x04, - Right = 0x08 + private enum GrowthDirection + { + None = 0, + Upward = 0x01, + Downward = 0x02, + Left = 0x04, + Right = 0x08 } @@ -996,15 +1149,16 @@ internal static string Debug_GetLayoutInfo(Control control, int indents) { } #endif -#endif - +#endif + #region AnchorInfo - private sealed class AnchorInfo { + private sealed class AnchorInfo + { public int Left; public int Top; public int Right; - public int Bottom; - } + public int Bottom; + } #endregion AnchorInfo } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs index efed439e88d..f724d42b928 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs @@ -2,14 +2,16 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.Layout { +namespace System.Windows.Forms.Layout +{ using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; - internal class FlowLayout : LayoutEngine { + internal class FlowLayout : LayoutEngine + { // Singleton instance shared by all FlowPanels. internal static readonly FlowLayout Instance = new FlowLayout(); @@ -17,14 +19,17 @@ internal class FlowLayout : LayoutEngine { private static readonly int _wrapContentsProperty = PropertyStore.CreateKey(); private static readonly int _flowDirectionProperty = PropertyStore.CreateKey(); - internal static FlowLayoutSettings CreateSettings(IArrangedElement owner) { + internal static FlowLayoutSettings CreateSettings(IArrangedElement owner) + { return new FlowLayoutSettings(owner); } - + // Entry point from LayoutEngine - internal override bool LayoutCore(IArrangedElement container, LayoutEventArgs args) { + internal override bool LayoutCore(IArrangedElement container, LayoutEventArgs args) + { #if DEBUG - if (CompModSwitches.FlowLayout.TraceInfo) { + if (CompModSwitches.FlowLayout.TraceInfo) + { Debug.WriteLine("FlowLayout::Layout(" + "container=" + container.ToString() + ", " + "displayRect=" + container.DisplayRectangle.ToString() + ", " @@ -42,9 +47,11 @@ internal override bool LayoutCore(IArrangedElement container, LayoutEventArgs ar return CommonProperties.GetAutoSize(container); } - internal override Size GetPreferredSize(IArrangedElement container, Size proposedConstraints) { + internal override Size GetPreferredSize(IArrangedElement container, Size proposedConstraints) + { #if DEBUG - if (CompModSwitches.FlowLayout.TraceInfo) { + if (CompModSwitches.FlowLayout.TraceInfo) + { Debug.WriteLine("FlowLayout::GetPreferredSize(" + "container=" + container.ToString() + ", " + "proposedConstraints=" + proposedConstraints.ToString() + ")"); @@ -54,7 +61,8 @@ internal override Size GetPreferredSize(IArrangedElement container, Size propose Rectangle measureBounds = new Rectangle(new Point(0, 0), proposedConstraints); Size prefSize = xLayout(container, measureBounds, /* measureOnly = */ true); - if(prefSize.Width > proposedConstraints.Width || prefSize.Height> proposedConstraints.Height) { + if (prefSize.Width > proposedConstraints.Width || prefSize.Height > proposedConstraints.Height) + { // Controls measured earlier than a control which couldn't be fit to constraints may // shift around with the new bounds. We need to make a 2nd pass through the // controls using these bounds which are gauranteed to fit. @@ -63,7 +71,8 @@ internal override Size GetPreferredSize(IArrangedElement container, Size propose } #if DEBUG - if (CompModSwitches.FlowLayout.TraceInfo) { + if (CompModSwitches.FlowLayout.TraceInfo) + { Debug.Unindent(); Debug.WriteLine("GetPreferredSize returned " + prefSize); } @@ -71,9 +80,11 @@ internal override Size GetPreferredSize(IArrangedElement container, Size propose return prefSize; } - private static ContainerProxy CreateContainerProxy(IArrangedElement container, FlowDirection flowDirection) { + private static ContainerProxy CreateContainerProxy(IArrangedElement container, FlowDirection flowDirection) + { - switch (flowDirection) { + switch (flowDirection) + { case FlowDirection.RightToLeft: return new RightToLeftProxy(container); case FlowDirection.TopDown: @@ -84,32 +95,35 @@ private static ContainerProxy CreateContainerProxy(IArrangedElement container, F default: return new ContainerProxy(container); } - + } // Both LayoutCore and GetPreferredSize forward to this method. The measureOnly flag determines which // behavior we get. - private Size xLayout(IArrangedElement container, Rectangle displayRect, bool measureOnly) { + private Size xLayout(IArrangedElement container, Rectangle displayRect, bool measureOnly) + { FlowDirection flowDirection = GetFlowDirection(container); bool wrapContents = GetWrapContents(container); ContainerProxy containerProxy = CreateContainerProxy(container, flowDirection); containerProxy.DisplayRect = displayRect; - + // refetch as it's now adjusted for Vertical. displayRect = containerProxy.DisplayRect; - + ElementProxy elementProxy = containerProxy.ElementProxy; Size layoutSize = Size.Empty; - if(!wrapContents) { + if (!wrapContents) + { // pretend that the container is infinitely wide to prevent wrapping. // DisplayRectangle.Right is Width + X - subtract X to prevent overflow. displayRect.Width = int.MaxValue - displayRect.X; } - for(int i = 0; i < container.Children.Count;) { + for (int i = 0; i < container.Children.Count;) + { int breakIndex; Size rowSize = Size.Empty; @@ -121,8 +135,9 @@ private Size xLayout(IArrangedElement container, Rectangle displayRect, bool mea // should be equal to the count of child items in the container. Debug.Assert(wrapContents == true || breakIndex == container.Children.Count, "We should not be trying to break the row if we are not wrapping contents."); - - if(!measureOnly) { + + if (!measureOnly) + { Rectangle rowBounds = new Rectangle(displayRect.X, layoutSize.Height + displayRect.Y, rowSize.Width, @@ -134,7 +149,8 @@ private Size xLayout(IArrangedElement container, Rectangle displayRect, bool mea i = breakIndex; } //verify that our alignment is correct - if (container.Children.Count != 0 && !measureOnly) { + if (container.Children.Count != 0 && !measureOnly) + { Debug_VerifyAlignment(container, flowDirection); } return LayoutUtils.FlipSizeIf(flowDirection == FlowDirection.TopDown || GetFlowDirection(container) == FlowDirection.BottomUp, layoutSize); @@ -143,7 +159,8 @@ private Size xLayout(IArrangedElement container, Rectangle displayRect, bool mea // Just forwards to xLayoutRow. This will layout elements from the start index to the end index. RowBounds // was computed by a call to measure row and is used for alignment/boxstretch. See the ElementProxy class // for an explaination of the elementProxy parameter. - private void LayoutRow(ContainerProxy containerProxy, ElementProxy elementProxy, int startIndex, int endIndex, Rectangle rowBounds) { + private void LayoutRow(ContainerProxy containerProxy, ElementProxy elementProxy, int startIndex, int endIndex, Rectangle rowBounds) + { int dummy; Size outSize = xLayoutRow(containerProxy, elementProxy, startIndex, endIndex, rowBounds, /* breakIndex = */ out dummy, /* measureOnly = */ false); Debug.Assert(dummy == endIndex, "EndIndex / BreakIndex mismatch."); @@ -152,12 +169,14 @@ private void LayoutRow(ContainerProxy containerProxy, ElementProxy elementProxy, // Just forwards to xLayoutRow. breakIndex is the index of the first control not to fit in the displayRectangle. The // returned Size is the size required to layout the controls from startIndex up to but not including breakIndex. See // the ElementProxy class for an explaination of the elementProxy parameter. - private Size MeasureRow(ContainerProxy containerProxy, ElementProxy elementProxy, int startIndex, Rectangle displayRectangle, out int breakIndex) { + private Size MeasureRow(ContainerProxy containerProxy, ElementProxy elementProxy, int startIndex, Rectangle displayRectangle, out int breakIndex) + { return xLayoutRow(containerProxy, elementProxy, startIndex, /* endIndex = */ containerProxy.Container.Children.Count, displayRectangle, out breakIndex, /* measureOnly = */ true); } // LayoutRow and MeasureRow both forward to this method. The measureOnly flag determines which behavior we get. - private Size xLayoutRow(ContainerProxy containerProxy, ElementProxy elementProxy, int startIndex, int endIndex, Rectangle rowBounds, out int breakIndex, bool measureOnly) { + private Size xLayoutRow(ContainerProxy containerProxy, ElementProxy elementProxy, int startIndex, int endIndex, Rectangle rowBounds, out int breakIndex, bool measureOnly) + { Debug.Assert(startIndex < endIndex, "Loop should be in forward Z-order."); Point location = rowBounds.Location; Size rowSize = Size.Empty; @@ -167,21 +186,25 @@ private Size xLayoutRow(ContainerProxy containerProxy, ElementProxy elementProxy bool wrapContents = GetWrapContents(containerProxy.Container); bool breakOnNextItem = false; - + ArrangedElementCollection collection = containerProxy.Container.Children; - for(int i = startIndex; i < endIndex; i++, breakIndex++) { + for (int i = startIndex; i < endIndex; i++, breakIndex++) + { elementProxy.Element = collection[i]; - if(!elementProxy.ParticipatesInLayout) { + if (!elementProxy.ParticipatesInLayout) + { continue; } // Figure out how much space this element is going to need (requiredSize) // Size prefSize; - if(elementProxy.AutoSize) { + if (elementProxy.AutoSize) + { Size elementConstraints = new Size(int.MaxValue, rowBounds.Height - elementProxy.Margin.Size.Height); - if(i == startIndex) { + if (i == startIndex) + { // If the element is the first in the row, attempt to pack it to the row width. (If its not 1st, it will wrap // to the first on the next row if its too long and then be packed if needed by the next call to xLayoutRow). elementConstraints.Width = rowBounds.Width - rowSize.Width - elementProxy.Margin.Size.Width; @@ -189,19 +212,23 @@ private Size xLayoutRow(ContainerProxy containerProxy, ElementProxy elementProxy // Make sure that subtracting the margins does not cause width/height to be <= 0, or we will // size as if we had infinite space when in fact we are trying to be as small as possible. - elementConstraints = LayoutUtils.UnionSizes(new Size(1, 1), elementConstraints); + elementConstraints = LayoutUtils.UnionSizes(new Size(1, 1), elementConstraints); prefSize = elementProxy.GetPreferredSize(elementConstraints); - } else { + } + else + { // If autosizing is turned off, we just use the element's current size as its preferred size. prefSize = elementProxy.SpecifiedSize; - + // except if it is stretching - then ignore the affect of the height dimension. - if (elementProxy.Stretches) { + if (elementProxy.Stretches) + { prefSize.Height = 0; - } + } // Enforce MinimumSize - if (prefSize.Height < elementProxy.MinimumSize.Height) { + if (prefSize.Height < elementProxy.MinimumSize.Height) + { prefSize.Height = elementProxy.MinimumSize.Height; } } @@ -209,32 +236,35 @@ private Size xLayoutRow(ContainerProxy containerProxy, ElementProxy elementProxy // Position the element (if applicable). // - if(!measureOnly) { + if (!measureOnly) + { // If measureOnly = false, rowBounds.Height = measured row hieght // (otherwise its the remaining displayRect of the container) - + Rectangle cellBounds = new Rectangle(location, new Size(requiredSize.Width, rowBounds.Height)); // We laid out the rows with the elementProxy's margins included. // We now deflate the rect to get the actual elementProxy bounds. cellBounds = LayoutUtils.DeflateRect(cellBounds, elementProxy.Margin); - + AnchorStyles anchorStyles = elementProxy.AnchorStyles; containerProxy.Bounds = LayoutUtils.AlignAndStretch(prefSize, cellBounds, anchorStyles); } - + // Keep track of how much space is being used in this row // - + location.X += requiredSize.Width; - - - if (laidOutItems > 0) { + + + if (laidOutItems > 0) + { // If control does not fit on this row, exclude it from row and stop now. // Exception: If row is empty, allow this control to fit on it. So controls // that exceed the maximum row width will end up occupying their own rows. - if(location.X > rowBounds.Right) { + if (location.X > rowBounds.Right) + { break; } @@ -242,25 +272,30 @@ private Size xLayoutRow(ContainerProxy containerProxy, ElementProxy elementProxy // Control fits on this row, so update the row size. // rowSize.Width != location.X because with a scrollable control // we could have started with a location like -100. - + rowSize.Width = location.X - rowBounds.X; - + rowSize.Height = Math.Max(rowSize.Height, requiredSize.Height); // check for line breaks. - if (wrapContents) { - if (breakOnNextItem) { + if (wrapContents) + { + if (breakOnNextItem) + { break; } - else if (i+1 < endIndex && CommonProperties.GetFlowBreak(elementProxy.Element)) { - if (laidOutItems == 0) { + else if (i + 1 < endIndex && CommonProperties.GetFlowBreak(elementProxy.Element)) + { + if (laidOutItems == 0) + { breakOnNextItem = true; } - else { + else + { breakIndex++; break; } - } + } } ++laidOutItems; } @@ -269,27 +304,32 @@ private Size xLayoutRow(ContainerProxy containerProxy, ElementProxy elementProxy } #region Provided properties - public static bool GetWrapContents(IArrangedElement container) { + public static bool GetWrapContents(IArrangedElement container) + { int wrapContents = container.Properties.GetInteger(_wrapContentsProperty); return (wrapContents == 0); // if not set return true. } - - public static void SetWrapContents(IArrangedElement container, bool value) { + + public static void SetWrapContents(IArrangedElement container, bool value) + { container.Properties.SetInteger(_wrapContentsProperty, value ? 0 : 1); // set to 0 if true, 1 if false LayoutTransaction.DoLayout(container, container, PropertyNames.WrapContents); Debug.Assert(GetWrapContents(container) == value, "GetWrapContents should return the same value as we set"); } - public static FlowDirection GetFlowDirection(IArrangedElement container) { - return (FlowDirection) container.Properties.GetInteger(_flowDirectionProperty); + public static FlowDirection GetFlowDirection(IArrangedElement container) + { + return (FlowDirection)container.Properties.GetInteger(_flowDirectionProperty); } - - public static void SetFlowDirection(IArrangedElement container, FlowDirection value) { + + public static void SetFlowDirection(IArrangedElement container, FlowDirection value) + { //valid values are 0x0 to 0x3 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)FlowDirection.LeftToRight, (int)FlowDirection.BottomUp)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)FlowDirection.LeftToRight, (int)FlowDirection.BottomUp)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(FlowDirection)); } - container.Properties.SetInteger(_flowDirectionProperty, (int) value); + container.Properties.SetInteger(_flowDirectionProperty, (int)value); LayoutTransaction.DoLayout(container, container, PropertyNames.FlowDirection); Debug.Assert(GetFlowDirection(container) == value, "GetFlowDirection should return the same value as we set"); } @@ -315,115 +355,141 @@ public static void SetFlowDirection(IArrangedElement container, FlowDirection va // A final note: This layout engine does all its RightToLeft translation itself. It does not support // WS_EX_LAYOUTRTL (OS mirroring). - private class ContainerProxy { + private class ContainerProxy + { private IArrangedElement _container; private ElementProxy _elementProxy; private Rectangle _displayRect; private bool _isContainerRTL; - public ContainerProxy(IArrangedElement container) { + public ContainerProxy(IArrangedElement container) + { this._container = container; this._isContainerRTL = false; - if (_container is Control) { - _isContainerRTL = ((Control)(_container)).RightToLeft == RightToLeft.Yes; + if (_container is Control) + { + _isContainerRTL = ((Control)(_container)).RightToLeft == RightToLeft.Yes; } } // method for setting the bounds of a child element. - public virtual Rectangle Bounds { - set { - if (IsContainerRTL) { + public virtual Rectangle Bounds + { + set + { + if (IsContainerRTL) + { // Offset the X coordinate... - if (IsVertical) { + if (IsVertical) + { //Offset the Y value here, since it is really the X value.... value.Y = DisplayRect.Bottom - value.Bottom; } - else { - value.X = DisplayRect.Right - value.Right; + else + { + value.X = DisplayRect.Right - value.Right; } FlowLayoutPanel flp = Container as FlowLayoutPanel; - if (flp != null) { + if (flp != null) + { Point ptScroll = flp.AutoScrollPosition; - if (ptScroll != Point.Empty) { + if (ptScroll != Point.Empty) + { Point pt = new Point(value.X, value.Y); - if (IsVertical) { + if (IsVertical) + { //Offset the Y value here, since it is really the X value.... pt.Offset(0, ptScroll.X); } - else { + else + { pt.Offset(ptScroll.X, 0); } value.Location = pt; } - } + } } - - ElementProxy.Bounds = value; + + ElementProxy.Bounds = value; } } // specifies the container laying out - public IArrangedElement Container { + public IArrangedElement Container + { get { return _container; } } // specifies if we're TopDown or BottomUp and should use the VerticalElementProxy to translate - protected virtual bool IsVertical { + protected virtual bool IsVertical + { get { return false; } } // returns true if container is RTL.Yes - protected bool IsContainerRTL { + protected bool IsContainerRTL + { get { return _isContainerRTL; } } // returns the display rectangle of the container - this WILL BE FLIPPED if the layout // is a vertical layout. - public Rectangle DisplayRect { - get { - return _displayRect; + public Rectangle DisplayRect + { + get + { + return _displayRect; } - set { - if (_displayRect != value) { - + set + { + if (_displayRect != value) + { + //flip the displayRect since when we do layout direction TopDown/BottomUp, we layout the controls //on the flipped rectangle as if our layout direction were LeftToRight/RightToLeft. In this case //we can save some code bloat _displayRect = LayoutUtils.FlipRectangleIf(IsVertical, value); - } - } + } + } } // returns the element proxy to use. A vertical element proxy will typically // flip all the sizes and rectangles so that it can fake being laid out in a horizontal manner. - public ElementProxy ElementProxy { - get { - if (_elementProxy == null) { + public ElementProxy ElementProxy + { + get + { + if (_elementProxy == null) + { _elementProxy = (IsVertical) ? new VerticalElementProxy() : new ElementProxy(); } return _elementProxy; } - - } + + } // used when you want to translate from right to left, but preserve Margin.Right & Margin.Left. - protected Rectangle RTLTranslateNoMarginSwap(Rectangle bounds) { + protected Rectangle RTLTranslateNoMarginSwap(Rectangle bounds) + { Rectangle newBounds = bounds; - + newBounds.X = DisplayRect.Right - bounds.X - bounds.Width + ElementProxy.Margin.Left - ElementProxy.Margin.Right; // Since DisplayRect.Right and bounds.X are both adjusted for the AutoScrollPosition, we need add it back here. FlowLayoutPanel flp = Container as FlowLayoutPanel; - if (flp != null) { + if (flp != null) + { Point ptScroll = flp.AutoScrollPosition; - if (ptScroll != Point.Empty) { + if (ptScroll != Point.Empty) + { Point pt = new Point(newBounds.X, newBounds.Y); - if (IsVertical) { - + if (IsVertical) + { + // We need to treat Vertical a litte differently. It really helps if you draw this out. // Remember that when we layout BottomUp, we first layout TopDown, then call this method. // When we layout TopDown we layout in flipped rectangles. I.e. x becomes y, y becomes x, @@ -434,7 +500,9 @@ protected Rectangle RTLTranslateNoMarginSwap(Rectangle bounds) { // we need to use its Y coordinate when offsetting. pt.Offset(ptScroll.Y, 0); - } else { + } + else + { pt.Offset(ptScroll.X, 0); } newBounds.Location = pt; @@ -446,62 +514,74 @@ protected Rectangle RTLTranslateNoMarginSwap(Rectangle bounds) { } - + // FlowDirection.RightToLeft proxy. - private class RightToLeftProxy : ContainerProxy { - public RightToLeftProxy(IArrangedElement container) : base(container) { + private class RightToLeftProxy : ContainerProxy + { + public RightToLeftProxy(IArrangedElement container) : base(container) + { } - - public override Rectangle Bounds { - set { - // if the container is RTL, align to the left, otherwise, align to the right. - // Do NOT use LayoutUtils.RTLTranslate as we want to preserve the padding.Right on the right... - base.Bounds = RTLTranslateNoMarginSwap(value); + + public override Rectangle Bounds + { + set + { + // if the container is RTL, align to the left, otherwise, align to the right. + // Do NOT use LayoutUtils.RTLTranslate as we want to preserve the padding.Right on the right... + base.Bounds = RTLTranslateNoMarginSwap(value); } - } + } } - - + + // FlowDirection.TopDown proxy. // For TopDown we're really still laying out horizontally. The element proxy is the one // which flips all the rectangles and rotates itself into the vertical orientation. // to achieve right to left, we actually have to do something non-intuitive - instead of // sending the control to the right, we have to send the control to the bottom. When the rotation // is complete - that's equivilant to pushing it to the right. - private class TopDownProxy : ContainerProxy { - public TopDownProxy(IArrangedElement container) : base(container) { + private class TopDownProxy : ContainerProxy + { + public TopDownProxy(IArrangedElement container) : base(container) + { } - protected override bool IsVertical { + protected override bool IsVertical + { get { return true; } } - } + } // FlowDirection.BottomUp proxy. - private class BottomUpProxy : ContainerProxy { - public BottomUpProxy(IArrangedElement container) : base(container) { + private class BottomUpProxy : ContainerProxy + { + public BottomUpProxy(IArrangedElement container) : base(container) + { } - protected override bool IsVertical { + protected override bool IsVertical + { get { return true; } } - // For BottomUp we're really still laying out horizontally. The element proxy is the one - // which flips all the rectangles and rotates itself into the vertical orientation. - // BottomUp is the analog of RightToLeft - meaning, in order to place a control at the bottom, - // the control has to be placed to the right. When the rotation is complete, that's the equivilant of - // pushing it to the right. This must be done all the time. - // - // To achieve right to left, we actually have to do something non-intuitive - instead of - // sending the control to the right, we have to send the control to the bottom. When the rotation - // is complete - that's equivilant to pushing it to the right. - - public override Rectangle Bounds { - set { - // push the control to the bottom. - // Do NOT use LayoutUtils.RTLTranslate as we want to preserve the padding.Right on the right... - base.Bounds = RTLTranslateNoMarginSwap(value); + // For BottomUp we're really still laying out horizontally. The element proxy is the one + // which flips all the rectangles and rotates itself into the vertical orientation. + // BottomUp is the analog of RightToLeft - meaning, in order to place a control at the bottom, + // the control has to be placed to the right. When the rotation is complete, that's the equivilant of + // pushing it to the right. This must be done all the time. + // + // To achieve right to left, we actually have to do something non-intuitive - instead of + // sending the control to the right, we have to send the control to the bottom. When the rotation + // is complete - that's equivilant to pushing it to the right. + + public override Rectangle Bounds + { + set + { + // push the control to the bottom. + // Do NOT use LayoutUtils.RTLTranslate as we want to preserve the padding.Right on the right... + base.Bounds = RTLTranslateNoMarginSwap(value); } - } + } } #endregion ContainerProxy @@ -509,25 +589,31 @@ public override Rectangle Bounds { // ElementProxy inserts a level of indirection between the LayoutEngine // and the IArrangedElement that allows us to use the same code path // for Vertical and Horizontal flow layout. (see VerticalElementProxy) - private class ElementProxy { - private IArrangedElement _element; - - public virtual AnchorStyles AnchorStyles { - get { + private class ElementProxy + { + private IArrangedElement _element; + + public virtual AnchorStyles AnchorStyles + { + get + { AnchorStyles anchorStyles = LayoutUtils.GetUnifiedAnchor(Element); bool isStretch = (anchorStyles & LayoutUtils.VerticalAnchorStyles) == LayoutUtils.VerticalAnchorStyles; //whether the control stretches to fill in the whole space bool isTop = (anchorStyles & AnchorStyles.Top) != 0; //whether the control anchors to top and does not stretch; bool isBottom = (anchorStyles & AnchorStyles.Bottom) != 0; //whether the control anchors to bottom and does not stretch; - if(isStretch) { + if (isStretch) + { //the element stretches to fill in the whole row. Equivalent to AnchorStyles.Top|AnchorStyles.Bottom return LayoutUtils.VerticalAnchorStyles; } - if(isTop) { + if (isTop) + { //the element anchors to top and doesn't stretch return AnchorStyles.Top; } - if(isBottom) { + if (isBottom) + { //the element anchors to bottom and doesn't stretch return AnchorStyles.Bottom; } @@ -535,95 +621,119 @@ public virtual AnchorStyles AnchorStyles { } } - public bool AutoSize { + public bool AutoSize + { get { return CommonProperties.GetAutoSize(_element); } } - - public virtual Rectangle Bounds { + + public virtual Rectangle Bounds + { set { _element.SetBounds(value, BoundsSpecified.None); } } - public IArrangedElement Element { + public IArrangedElement Element + { get { return _element; } - set { - _element = value; + set + { + _element = value; Debug.Assert(Element == value, "Element should be the same as we set it to"); } } - public bool Stretches { - get { + public bool Stretches + { + get + { AnchorStyles styles = AnchorStyles; - if ((LayoutUtils.VerticalAnchorStyles & styles) == LayoutUtils.VerticalAnchorStyles) { + if ((LayoutUtils.VerticalAnchorStyles & styles) == LayoutUtils.VerticalAnchorStyles) + { return true; } - else { + else + { return false; } } } - public virtual Padding Margin { + public virtual Padding Margin + { get { return CommonProperties.GetMargin(Element); } } - public virtual Size MinimumSize { + public virtual Size MinimumSize + { get { return CommonProperties.GetMinimumSize(Element, Size.Empty); } } - - public bool ParticipatesInLayout { + + public bool ParticipatesInLayout + { get { return _element.ParticipatesInLayout; } } - - public virtual Size SpecifiedSize { + + public virtual Size SpecifiedSize + { get { return CommonProperties.GetSpecifiedBounds(_element).Size; } } - public virtual Size GetPreferredSize(Size proposedSize) { + public virtual Size GetPreferredSize(Size proposedSize) + { return _element.GetPreferredSize(proposedSize); - } + } } // VerticalElementProxy swaps Top/Left, Bottom/Right, and other properties // so that the same code path used for horizantal flow can be applied to // vertical flow. - private class VerticalElementProxy : ElementProxy { - public override AnchorStyles AnchorStyles { - get { + private class VerticalElementProxy : ElementProxy + { + public override AnchorStyles AnchorStyles + { + get + { AnchorStyles anchorStyles = LayoutUtils.GetUnifiedAnchor(Element); bool isStretch = (anchorStyles & LayoutUtils.HorizontalAnchorStyles) == LayoutUtils.HorizontalAnchorStyles; //whether the control stretches to fill in the whole space bool isLeft = (anchorStyles & AnchorStyles.Left) != 0; //whether the control anchors to left and does not stretch; bool isRight = (anchorStyles & AnchorStyles.Right) != 0; //whether the control anchors to right and does not stretch; - if(isStretch) { + if (isStretch) + { return LayoutUtils.VerticalAnchorStyles; } - if(isLeft) { + if (isLeft) + { return AnchorStyles.Top; } - if(isRight) { + if (isRight) + { return AnchorStyles.Bottom; } return AnchorStyles.None; } } - public override Rectangle Bounds { + public override Rectangle Bounds + { set { base.Bounds = LayoutUtils.FlipRectangle(value); } } - public override Padding Margin { + public override Padding Margin + { get { return LayoutUtils.FlipPadding(base.Margin); } } - public override Size MinimumSize { + public override Size MinimumSize + { get { return LayoutUtils.FlipSize(base.MinimumSize); } } - public override Size SpecifiedSize { + public override Size SpecifiedSize + { get { return LayoutUtils.FlipSize(base.SpecifiedSize); } } - public override Size GetPreferredSize(Size proposedSize) { + public override Size GetPreferredSize(Size proposedSize) + { return LayoutUtils.FlipSize(base.GetPreferredSize(LayoutUtils.FlipSize(proposedSize))); } } @@ -631,19 +741,22 @@ public override Size GetPreferredSize(Size proposedSize) { #region DEBUG [Conditional("DEBUG_VERIFY_ALIGNMENT")] - private void Debug_VerifyAlignment(IArrangedElement container, FlowDirection flowDirection) { + private void Debug_VerifyAlignment(IArrangedElement container, FlowDirection flowDirection) + { #if DEBUG //We cannot apply any of these checks @ design-time since dragging new children into a FlowLayoutPanel //will attempt to set the children at the mouse position when the child was dropped - we rely on the controil //to reposition the children once added. Control flp = container as Control; - if (flp != null && flp.Site != null && flp.Site.DesignMode) { + if (flp != null && flp.Site != null && flp.Site.DesignMode) + { return; } //check to see if the first element is in its right place Padding margin = CommonProperties.GetMargin(container.Children[0]); - switch (flowDirection) { + switch (flowDirection) + { case FlowDirection.LeftToRight: case FlowDirection.TopDown: Debug.Assert(container.Children[0].Bounds.Y == margin.Top + container.DisplayRectangle.Y); @@ -657,11 +770,13 @@ private void Debug_VerifyAlignment(IArrangedElement container, FlowDirection flo Debug.Assert(container.Children[0].Bounds.Y == container.DisplayRectangle.Y + container.DisplayRectangle.Height - container.Children[0].Bounds.Height - margin.Bottom); Debug.Assert(container.Children[0].Bounds.X == margin.Left + container.DisplayRectangle.X); break; - } + } //next check to see if everything is in bound ArrangedElementCollection collection = container.Children; - for (int i = 1; i < collection.Count; i++) { - switch (flowDirection) { + for (int i = 1; i < collection.Count; i++) + { + switch (flowDirection) + { case FlowDirection.LeftToRight: case FlowDirection.TopDown: Debug.Assert(collection[i].Bounds.Y >= container.DisplayRectangle.Y); @@ -676,7 +791,7 @@ private void Debug_VerifyAlignment(IArrangedElement container, FlowDirection flo Debug.Assert(collection[i].Bounds.X >= container.DisplayRectangle.X); break; } - } + } #endif } #endregion DEBUG diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutEngine.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutEngine.cs index 98b6fc0a902..dec3f99d847 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutEngine.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutEngine.cs @@ -10,7 +10,7 @@ namespace System.Windows.Forms.Layout { public abstract class LayoutEngine - { + { internal IArrangedElement CastToArrangedElement(object obj) { if (!(obj is IArrangedElement element)) @@ -24,7 +24,7 @@ internal virtual Size GetPreferredSize(IArrangedElement container, Size proposed { return Size.Empty; } - + public virtual void InitLayout(object child, BoundsSpecified specified) { if (child == null) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutSettings.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutSettings.cs index 5e07a0f73e8..cfeb2417239 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutSettings.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutSettings.cs @@ -3,23 +3,29 @@ // See the LICENSE file in the project root for more information. using System.Windows.Forms.Layout; -namespace System.Windows.Forms { - - public abstract class LayoutSettings { +namespace System.Windows.Forms +{ + + public abstract class LayoutSettings + { private IArrangedElement _owner; - protected LayoutSettings() { + protected LayoutSettings() + { } - - internal LayoutSettings(IArrangedElement owner) { + + internal LayoutSettings(IArrangedElement owner) + { this._owner = owner; } - - public virtual LayoutEngine LayoutEngine { - get { return null;} + + public virtual LayoutEngine LayoutEngine + { + get { return null; } } - internal IArrangedElement Owner { + internal IArrangedElement Owner + { get { return _owner; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutUtils.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutUtils.cs index 8aa3dce3acd..43bd06d724f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutUtils.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutUtils.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.Layout { +namespace System.Windows.Forms.Layout +{ using System; using System.Collections; using System.Diagnostics; @@ -11,18 +12,19 @@ namespace System.Windows.Forms.Layout { using System.Drawing.Text; using System.Runtime.InteropServices; using System.Windows.Forms; - using System.Windows.Forms.ComponentModel; + using System.Windows.Forms.ComponentModel; using System.Collections.Generic; // Utilities used by layout code. If you use these outside of the layout // namespace, you should probably move them to WindowsFormsUtils. - internal class LayoutUtils { + internal class LayoutUtils + { public static readonly Size MaxSize = new Size(int.MaxValue, int.MaxValue); public static readonly Size InvalidSize = new Size(int.MinValue, int.MinValue); - + public static readonly Rectangle MaxRectangle = new Rectangle(0, 0, int.MaxValue, int.MaxValue); - + public const ContentAlignment AnyTop = ContentAlignment.TopLeft | ContentAlignment.TopCenter | ContentAlignment.TopRight; public const ContentAlignment AnyBottom = ContentAlignment.BottomLeft | ContentAlignment.BottomCenter | ContentAlignment.BottomRight; public const ContentAlignment AnyLeft = ContentAlignment.TopLeft | ContentAlignment.MiddleLeft | ContentAlignment.BottomLeft; @@ -31,7 +33,7 @@ internal class LayoutUtils { public const ContentAlignment AnyMiddle = ContentAlignment.MiddleLeft | ContentAlignment.MiddleCenter | ContentAlignment.MiddleRight; public const AnchorStyles HorizontalAnchorStyles = AnchorStyles.Left | AnchorStyles.Right; - public const AnchorStyles VerticalAnchorStyles = AnchorStyles.Top | AnchorStyles.Bottom; + public const AnchorStyles VerticalAnchorStyles = AnchorStyles.Top | AnchorStyles.Bottom; private static readonly AnchorStyles[] dockingToAnchor = new AnchorStyles[] { /* None */ AnchorStyles.Top | AnchorStyles.Left, @@ -41,17 +43,20 @@ internal class LayoutUtils { /* Right */ AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom, /* Fill */ AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left }; - + // A good, short test string for measuring control height. public readonly static string TestString = "j^"; // Returns the size of the largest string in the given collection. Non-string objects are converted // with ToString(). Uses OldMeasureString, not GDI+. Does not support multiline. - public static Size OldGetLargestStringSizeInCollection(Font font, ICollection objects) { + public static Size OldGetLargestStringSizeInCollection(Font font, ICollection objects) + { Size largestSize = Size.Empty; - if (objects != null) { - foreach(object obj in objects) { + if (objects != null) + { + foreach (object obj in objects) + { Size textSize = TextRenderer.MeasureText(obj.ToString(), font, new Size(short.MaxValue, short.MaxValue), TextFormatFlags.SingleLine); largestSize.Width = Math.Max(largestSize.Width, textSize.Width); largestSize.Height = Math.Max(largestSize.Height, textSize.Height); @@ -61,7 +66,7 @@ public static Size OldGetLargestStringSizeInCollection(Font font, ICollection ob } - + /* * We can cut ContentAlignment from a max index of 1024 (12b) down to 11 (4b) through * bit twiddling. The int result of this function maps to the ContentAlignment as indicated @@ -75,7 +80,8 @@ public static Size OldGetLargestStringSizeInCollection(Font font, ICollection ob * (The high 2 bits determine T/M/B. The low 2 bits determine L/C/R.) */ - public static int ContentAlignmentToIndex(ContentAlignment alignment) { + public static int ContentAlignmentToIndex(ContentAlignment alignment) + { /* * Here is what content alignment looks like coming in: * @@ -99,9 +105,9 @@ public static int ContentAlignmentToIndex(ContentAlignment alignment) { int result = (middleBits != 0 ? 0x04 : 0) | (bottomBits != 0 ? 0x08 : 0) | topBits | middleBits | bottomBits; // zero isn't used, so we can subtract 1 and start with index 0. - result --; + result--; - Debug.Assert(result >= 0x00 && result <=0x0A, "ContentAlignmentToIndex result out of range."); + Debug.Assert(result >= 0x00 && result <= 0x0A, "ContentAlignmentToIndex result out of range."); Debug.Assert(result != 0x00 || alignment == ContentAlignment.TopLeft, "Error detected in ContentAlignmentToIndex."); Debug.Assert(result != 0x01 || alignment == ContentAlignment.TopCenter, "Error detected in ContentAlignmentToIndex."); Debug.Assert(result != 0x02 || alignment == ContentAlignment.TopRight, "Error detected in ContentAlignmentToIndex."); @@ -118,23 +124,29 @@ public static int ContentAlignmentToIndex(ContentAlignment alignment) { } // Converts 0x00, 0x01, 0x02, 0x04 (3b flag) to 0, 1, 2, 3 (2b index) - private static byte xContentAlignmentToIndex(int threeBitFlag) { + private static byte xContentAlignmentToIndex(int threeBitFlag) + { Debug.Assert(threeBitFlag >= 0x00 && threeBitFlag <= 0x04 && threeBitFlag != 0x03, "threeBitFlag out of range."); - byte result = threeBitFlag == 0x04 ? (byte) 3 : (byte) threeBitFlag; + byte result = threeBitFlag == 0x04 ? (byte)3 : (byte)threeBitFlag; Debug.Assert((result & 0x03) == result, "Result out of range."); return result; } - public static Size ConvertZeroToUnbounded(Size size) { - if(size.Width == 0) size.Width = int.MaxValue; - if(size.Height == 0) size.Height = int.MaxValue; + public static Size ConvertZeroToUnbounded(Size size) + { + if (size.Width == 0) + size.Width = int.MaxValue; + if (size.Height == 0) + size.Height = int.MaxValue; return size; } // Clamps negative values in Padding struct to zero. - public static Padding ClampNegativePaddingToZero(Padding padding) { + public static Padding ClampNegativePaddingToZero(Padding padding) + { // Careful: Setting the LRTB properties causes Padding.All to be -1 even if LRTB all agree. - if(padding.All < 0) { + if (padding.All < 0) + { padding.Left = Math.Max(0, padding.Left); padding.Top = Math.Max(0, padding.Top); padding.Right = Math.Max(0, padding.Right); @@ -154,79 +166,94 @@ public static Padding ClampNegativePaddingToZero(Padding padding) { // Returns the positive opposite of the given anchor (e.g., L -> R, LT -> RB, LTR -> LBR, etc.). None return none. - private static AnchorStyles GetOppositeAnchor(AnchorStyles anchor) { + private static AnchorStyles GetOppositeAnchor(AnchorStyles anchor) + { AnchorStyles result = AnchorStyles.None; - if (anchor == AnchorStyles.None){ + if (anchor == AnchorStyles.None) + { return result; } - + // iterate through T,B,L,R // bitwise or B,T,R,L as appropriate - for (int i = 1; i <= (int)AnchorStyles.Right; i=i <<1) { - switch (anchor & (AnchorStyles)i) { - case AnchorStyles.None: + for (int i = 1; i <= (int)AnchorStyles.Right; i = i << 1) + { + switch (anchor & (AnchorStyles)i) + { + case AnchorStyles.None: break; - case AnchorStyles.Left: - result |= AnchorStyles.Right; - break; - case AnchorStyles.Top: - result |= AnchorStyles.Bottom; - break; - case AnchorStyles.Right: + case AnchorStyles.Left: + result |= AnchorStyles.Right; + break; + case AnchorStyles.Top: + result |= AnchorStyles.Bottom; + break; + case AnchorStyles.Right: result |= AnchorStyles.Left; break; - case AnchorStyles.Bottom: - result |= AnchorStyles.Top; - break; - default: + case AnchorStyles.Bottom: + result |= AnchorStyles.Top; break; - } + default: + break; + } } return result; } - public static TextImageRelation GetOppositeTextImageRelation(TextImageRelation relation) { - return (TextImageRelation) GetOppositeAnchor((AnchorStyles)relation); + public static TextImageRelation GetOppositeTextImageRelation(TextImageRelation relation) + { + return (TextImageRelation)GetOppositeAnchor((AnchorStyles)relation); } - public static Size UnionSizes(Size a, Size b) { + public static Size UnionSizes(Size a, Size b) + { return new Size( Math.Max(a.Width, b.Width), Math.Max(a.Height, b.Height)); } - public static Size IntersectSizes(Size a, Size b) { + public static Size IntersectSizes(Size a, Size b) + { return new Size( Math.Min(a.Width, b.Width), Math.Min(a.Height, b.Height)); } - public static bool IsIntersectHorizontally(Rectangle rect1, Rectangle rect2) { - if (!rect1.IntersectsWith(rect2)) { + public static bool IsIntersectHorizontally(Rectangle rect1, Rectangle rect2) + { + if (!rect1.IntersectsWith(rect2)) + { return false; } - if (rect1.X <= rect2.X && rect1.X + rect1.Width >= rect2.X + rect2.Width) { + if (rect1.X <= rect2.X && rect1.X + rect1.Width >= rect2.X + rect2.Width) + { //rect 1 contains rect 2 horizontally return true; - } - if (rect2.X <= rect1.X && rect2.X + rect2.Width >= rect1.X + rect1.Width) { + } + if (rect2.X <= rect1.X && rect2.X + rect2.Width >= rect1.X + rect1.Width) + { //rect 2 contains rect 1 horizontally return true; } return false; } - public static bool IsIntersectVertically(Rectangle rect1, Rectangle rect2) { - if (!rect1.IntersectsWith(rect2)) { + public static bool IsIntersectVertically(Rectangle rect1, Rectangle rect2) + { + if (!rect1.IntersectsWith(rect2)) + { return false; } - if (rect1.Y <= rect2.Y && rect1.Y + rect1.Width >= rect2.Y + rect2.Width) { + if (rect1.Y <= rect2.Y && rect1.Y + rect1.Width >= rect2.Y + rect2.Width) + { //rect 1 contains rect 2 vertically return true; - } - if (rect2.Y <= rect1.Y && rect2.Y + rect2.Width >= rect1.Y + rect1.Width) { + } + if (rect2.Y <= rect1.Y && rect2.Y + rect2.Width >= rect1.Y + rect1.Width) + { //rect 2 contains rect 1 vertically return true; } @@ -234,91 +261,112 @@ public static bool IsIntersectVertically(Rectangle rect1, Rectangle rect2) { } //returns anchorStyles, transforms from DockStyle if necessary - internal static AnchorStyles GetUnifiedAnchor(IArrangedElement element) { + internal static AnchorStyles GetUnifiedAnchor(IArrangedElement element) + { DockStyle dockStyle = DefaultLayout.GetDock(element); - if (dockStyle != DockStyle.None) { + if (dockStyle != DockStyle.None) + { return dockingToAnchor[(int)dockStyle]; } return DefaultLayout.GetAnchor(element); } - - public static Rectangle AlignAndStretch(Size fitThis, Rectangle withinThis, AnchorStyles anchorStyles) { + + public static Rectangle AlignAndStretch(Size fitThis, Rectangle withinThis, AnchorStyles anchorStyles) + { return Align(Stretch(fitThis, withinThis.Size, anchorStyles), withinThis, anchorStyles); } - public static Rectangle Align(Size alignThis, Rectangle withinThis, AnchorStyles anchorStyles) { + public static Rectangle Align(Size alignThis, Rectangle withinThis, AnchorStyles anchorStyles) + { return VAlign(alignThis, HAlign(alignThis, withinThis, anchorStyles), anchorStyles); } - public static Rectangle Align(Size alignThis, Rectangle withinThis, ContentAlignment align) { + public static Rectangle Align(Size alignThis, Rectangle withinThis, ContentAlignment align) + { return VAlign(alignThis, HAlign(alignThis, withinThis, align), align); } - public static Rectangle HAlign(Size alignThis, Rectangle withinThis, AnchorStyles anchorStyles) { - if ((anchorStyles & AnchorStyles.Right) != 0) { + public static Rectangle HAlign(Size alignThis, Rectangle withinThis, AnchorStyles anchorStyles) + { + if ((anchorStyles & AnchorStyles.Right) != 0) + { withinThis.X += withinThis.Width - alignThis.Width; } - else if (anchorStyles == AnchorStyles.None || (anchorStyles & HorizontalAnchorStyles) == 0) { + else if (anchorStyles == AnchorStyles.None || (anchorStyles & HorizontalAnchorStyles) == 0) + { withinThis.X += (withinThis.Width - alignThis.Width) / 2; } withinThis.Width = alignThis.Width; - + return withinThis; } - private static Rectangle HAlign(Size alignThis, Rectangle withinThis, ContentAlignment align) { - if ((align & AnyRight) != 0) { + private static Rectangle HAlign(Size alignThis, Rectangle withinThis, ContentAlignment align) + { + if ((align & AnyRight) != 0) + { withinThis.X += withinThis.Width - alignThis.Width; } - else if ((align & AnyCenter) != 0) { + else if ((align & AnyCenter) != 0) + { withinThis.X += (withinThis.Width - alignThis.Width) / 2; } withinThis.Width = alignThis.Width; - + return withinThis; } - public static Rectangle VAlign(Size alignThis, Rectangle withinThis, AnchorStyles anchorStyles) { - if ((anchorStyles & AnchorStyles.Bottom) != 0) { + public static Rectangle VAlign(Size alignThis, Rectangle withinThis, AnchorStyles anchorStyles) + { + if ((anchorStyles & AnchorStyles.Bottom) != 0) + { withinThis.Y += withinThis.Height - alignThis.Height; } - else if (anchorStyles == AnchorStyles.None || (anchorStyles & VerticalAnchorStyles) == 0) { + else if (anchorStyles == AnchorStyles.None || (anchorStyles & VerticalAnchorStyles) == 0) + { withinThis.Y += (withinThis.Height - alignThis.Height) / 2; } - + withinThis.Height = alignThis.Height; - + return withinThis; } - public static Rectangle VAlign(Size alignThis, Rectangle withinThis, ContentAlignment align) { - if ((align & AnyBottom) != 0) { + public static Rectangle VAlign(Size alignThis, Rectangle withinThis, ContentAlignment align) + { + if ((align & AnyBottom) != 0) + { withinThis.Y += withinThis.Height - alignThis.Height; } - else if ((align & AnyMiddle) != 0) { + else if ((align & AnyMiddle) != 0) + { withinThis.Y += (withinThis.Height - alignThis.Height) / 2; } - + withinThis.Height = alignThis.Height; - + return withinThis; } - public static Size Stretch(Size stretchThis, Size withinThis, AnchorStyles anchorStyles) { - Size stretchedSize = new Size( + public static Size Stretch(Size stretchThis, Size withinThis, AnchorStyles anchorStyles) + { + Size stretchedSize = new Size( (anchorStyles & HorizontalAnchorStyles) == HorizontalAnchorStyles ? withinThis.Width : stretchThis.Width, (anchorStyles & VerticalAnchorStyles) == VerticalAnchorStyles ? withinThis.Height : stretchThis.Height ); - if (stretchedSize.Width > withinThis.Width) { + if (stretchedSize.Width > withinThis.Width) + { stretchedSize.Width = withinThis.Width; } - if (stretchedSize.Height > withinThis.Height) { + if (stretchedSize.Height > withinThis.Height) + { stretchedSize.Height = withinThis.Height; } return stretchedSize; } - - public static Rectangle InflateRect(Rectangle rect, Padding padding) { + + public static Rectangle InflateRect(Rectangle rect, Padding padding) + { rect.X -= padding.Left; rect.Y -= padding.Top; rect.Width += padding.Horizontal; @@ -326,7 +374,8 @@ public static Rectangle InflateRect(Rectangle rect, Padding padding) { return rect; } - public static Rectangle DeflateRect(Rectangle rect, Padding padding) { + public static Rectangle DeflateRect(Rectangle rect, Padding padding) + { rect.X += padding.Left; rect.Y += padding.Top; rect.Width -= padding.Horizontal; @@ -334,30 +383,37 @@ public static Rectangle DeflateRect(Rectangle rect, Padding padding) { return rect; } - public static Size AddAlignedRegion(Size textSize, Size imageSize, TextImageRelation relation) { + public static Size AddAlignedRegion(Size textSize, Size imageSize, TextImageRelation relation) + { return AddAlignedRegionCore(textSize, imageSize, IsVerticalRelation(relation)); } - public static Size AddAlignedRegionCore(Size currentSize, Size contentSize, bool vertical) { - if(vertical) { + public static Size AddAlignedRegionCore(Size currentSize, Size contentSize, bool vertical) + { + if (vertical) + { currentSize.Width = Math.Max(currentSize.Width, contentSize.Width); currentSize.Height += contentSize.Height; - } else { + } + else + { currentSize.Width += contentSize.Width; currentSize.Height = Math.Max(currentSize.Height, contentSize.Height); } return currentSize; } - - public static Padding FlipPadding(Padding padding) { + + public static Padding FlipPadding(Padding padding) + { // If Padding.All != -1, then TLRB are all the same and there is no work to be done. - if(padding.All != -1) { + if (padding.All != -1) + { return padding; } // Padding is a stuct (passed by value, no need to make a copy) int temp; - + temp = padding.Top; padding.Top = padding.Left; padding.Left = temp; @@ -369,7 +425,8 @@ public static Padding FlipPadding(Padding padding) { return padding; } - public static Point FlipPoint(Point point) { + public static Point FlipPoint(Point point) + { // Point is a struct (passed by value, no need to make a copy) int temp = point.X; point.X = point.Y; @@ -377,18 +434,21 @@ public static Point FlipPoint(Point point) { return point; } - public static Rectangle FlipRectangle(Rectangle rect) { + public static Rectangle FlipRectangle(Rectangle rect) + { // Rectangle is a stuct (passed by value, no need to make a copy) rect.Location = FlipPoint(rect.Location); rect.Size = FlipSize(rect.Size); return rect; } - public static Rectangle FlipRectangleIf(bool condition, Rectangle rect) { + public static Rectangle FlipRectangleIf(bool condition, Rectangle rect) + { return condition ? FlipRectangle(rect) : rect; } - public static Size FlipSize(Size size) { + public static Size FlipSize(Size size) + { // Size is a struct (passed by value, no need to make a copy) int temp = size.Width; size.Width = size.Height; @@ -396,44 +456,54 @@ public static Size FlipSize(Size size) { return size; } - public static Size FlipSizeIf(bool condition, Size size) { + public static Size FlipSizeIf(bool condition, Size size) + { return condition ? FlipSize(size) : size; } - public static bool IsHorizontalAlignment(ContentAlignment align) { + public static bool IsHorizontalAlignment(ContentAlignment align) + { return !IsVerticalAlignment(align); } // True if text & image should be lined up horizontally. False if vertical or overlay. - public static bool IsHorizontalRelation(TextImageRelation relation) { + public static bool IsHorizontalRelation(TextImageRelation relation) + { return (relation & (TextImageRelation.TextBeforeImage | TextImageRelation.ImageBeforeText)) != 0; } - - public static bool IsVerticalAlignment(ContentAlignment align) { + + public static bool IsVerticalAlignment(ContentAlignment align) + { Debug.Assert(align != ContentAlignment.MiddleCenter, "Result is ambiguous with an alignment of MiddleCenter."); return (align & (ContentAlignment.TopCenter | ContentAlignment.BottomCenter)) != 0; } // True if text & image should be lined up vertically. False if horizontal or overlay. - public static bool IsVerticalRelation(TextImageRelation relation) { + public static bool IsVerticalRelation(TextImageRelation relation) + { return (relation & (TextImageRelation.TextAboveImage | TextImageRelation.ImageAboveText)) != 0; } - public static bool IsZeroWidthOrHeight(Rectangle rectangle) { + public static bool IsZeroWidthOrHeight(Rectangle rectangle) + { return (rectangle.Width == 0 || rectangle.Height == 0); } - public static bool IsZeroWidthOrHeight(Size size) { + public static bool IsZeroWidthOrHeight(Size size) + { return (size.Width == 0 || size.Height == 0); } - public static bool AreWidthAndHeightLarger(Size size1, Size size2){ + public static bool AreWidthAndHeightLarger(Size size1, Size size2) + { return ((size1.Width >= size2.Width) && (size1.Height >= size2.Height)); } - - public static void SplitRegion(Rectangle bounds, Size specifiedContent, AnchorStyles region1Align, out Rectangle region1, out Rectangle region2) { + + public static void SplitRegion(Rectangle bounds, Size specifiedContent, AnchorStyles region1Align, out Rectangle region1, out Rectangle region2) + { region1 = region2 = bounds; - switch(region1Align) { + switch (region1Align) + { case AnchorStyles.Left: region1.Width = specifiedContent.Width; region2.X += specifiedContent.Width; @@ -464,8 +534,10 @@ public static void SplitRegion(Rectangle bounds, Size specifiedContent, AnchorSt } // Expands adjacent regions to bounds. region1Align indicates which way the adjacency occurs. - public static void ExpandRegionsToFillBounds(Rectangle bounds, AnchorStyles region1Align, ref Rectangle region1, ref Rectangle region2) { - switch(region1Align) { + public static void ExpandRegionsToFillBounds(Rectangle bounds, AnchorStyles region1Align, ref Rectangle region1, ref Rectangle region2) + { + switch (region1Align) + { case AnchorStyles.Left: Debug.Assert(region1.Right == region2.Left, "Adjacency error."); region1 = SubstituteSpecifiedBounds(bounds, region1, AnchorStyles.Right); @@ -493,20 +565,26 @@ public static void ExpandRegionsToFillBounds(Rectangle bounds, AnchorStyles regi Debug.Assert(Rectangle.Union(region1, region2) == bounds, "region1 and region2 do not add up to bounds."); } - public static Size SubAlignedRegion(Size currentSize, Size contentSize, TextImageRelation relation) { + public static Size SubAlignedRegion(Size currentSize, Size contentSize, TextImageRelation relation) + { return SubAlignedRegionCore(currentSize, contentSize, IsVerticalRelation(relation)); } - - public static Size SubAlignedRegionCore(Size currentSize, Size contentSize, bool vertical) { - if(vertical) { + + public static Size SubAlignedRegionCore(Size currentSize, Size contentSize, bool vertical) + { + if (vertical) + { currentSize.Height -= contentSize.Height; - } else { + } + else + { currentSize.Width -= contentSize.Width; } return currentSize; - } + } - private static Rectangle SubstituteSpecifiedBounds(Rectangle originalBounds, Rectangle substitutionBounds, AnchorStyles specified) { + private static Rectangle SubstituteSpecifiedBounds(Rectangle originalBounds, Rectangle substitutionBounds, AnchorStyles specified) + { int left = (specified & AnchorStyles.Left) != 0 ? substitutionBounds.Left : originalBounds.Left; int top = (specified & AnchorStyles.Top) != 0 ? substitutionBounds.Top : originalBounds.Top; int right = (specified & AnchorStyles.Right) != 0 ? substitutionBounds.Right : originalBounds.Right; @@ -517,134 +595,149 @@ private static Rectangle SubstituteSpecifiedBounds(Rectangle originalBounds, Rec // given a rectangle, flip to the other side of (withinBounds) // // Never call this if you derive from ScrollableControl - public static Rectangle RTLTranslate(Rectangle bounds, Rectangle withinBounds) { + public static Rectangle RTLTranslate(Rectangle bounds, Rectangle withinBounds) + { bounds.X = withinBounds.Width - bounds.Right; return bounds; } /// MeasureTextCache /// 3000 character strings take 9 seconds to load the form - public sealed class MeasureTextCache { - private Size unconstrainedPreferredSize = LayoutUtils.InvalidSize; - private const int MaxCacheSize = 6; // the number of preferred sizes to store - private int nextCacheEntry = -1; // the next place in the ring buffer to store a preferred size - - private PreferredSizeCache[] sizeCacheList; // MRU of size MaxCacheSize - - - /// InvalidateCache - /// Clears out the cached values, should be called whenever Text, Font or a TextFormatFlag has changed - public void InvalidateCache() { - unconstrainedPreferredSize = LayoutUtils.InvalidSize; - sizeCacheList = null; - } - - - /// GetTextSize - /// Given constraints, format flags a font and text, determine the size of the string - /// employs an MRU of the last several constraints passed in via a ring-buffer of size MaxCacheSize. - /// Assumes Text and TextFormatFlags are the same, if either were to change, a call to - /// InvalidateCache should be made - public Size GetTextSize(string text, Font font, Size proposedConstraints, TextFormatFlags flags) { - - - if (!TextRequiresWordBreak(text, font, proposedConstraints, flags)) { - // Text fits within proposed width - - // IF we're here, this means we've got text that can fit into the proposedConstraints - // without wrapping. We've determined this because our - - // as a side effect of calling TextRequiresWordBreak, - // unconstrainedPreferredSize is set. - return unconstrainedPreferredSize; - } - else { - // Text does NOT fit within proposed width - requires WordBreak - - // IF we're here, this means that the wrapping width is smaller - // than our max width. For example: we measure the text with infinite - // bounding box and we determine the width to fit all the characters - // to be 200 px wide. We would come here only for proposed widths less - // than 200 px. - - - // Create our ring buffer if we dont have one - if (sizeCacheList == null) { - sizeCacheList = new PreferredSizeCache[MaxCacheSize]; - } - - // check the existing constraints from previous calls - foreach (PreferredSizeCache sizeCache in sizeCacheList) { - - if (sizeCache.ConstrainingSize == proposedConstraints) { - return sizeCache.PreferredSize; - } - else if ((sizeCache.ConstrainingSize.Width == proposedConstraints.Width) - && (sizeCache.PreferredSize.Height <= proposedConstraints.Height)) { - - // Caching a common case where the width matches perfectly, and the stored preferred height - // is smaller or equal to the constraining size. - // prefSize = GetPreferredSize(w,Int32.MaxValue); - // prefSize = GetPreferredSize(w,prefSize.Height); - - return sizeCache.PreferredSize; - } - // - } - - // if we've gotten here, it means we dont have a cache entry, therefore - // we should add a new one in the next available slot. - Size prefSize = TextRenderer.MeasureText(text, font, proposedConstraints, flags); - nextCacheEntry = (nextCacheEntry+1)%MaxCacheSize; - sizeCacheList[nextCacheEntry] = new PreferredSizeCache(proposedConstraints, prefSize); - - return prefSize; - - } - - } - - /// GetUnconstrainedSize - /// Gets the unconstrained (Int32.MaxValue, Int32.MaxValue) size for a piece of text - private Size GetUnconstrainedSize(string text, Font font, TextFormatFlags flags) { - - if (unconstrainedPreferredSize == LayoutUtils.InvalidSize) { - // we also investigated setting the SingleLine flag, however this did not yield as much benefit as the word break - // and had possibility of causing internationalization issues. - - flags = (flags & ~TextFormatFlags.WordBreak); // rip out the wordbreak flag - unconstrainedPreferredSize = TextRenderer.MeasureText(text, font, LayoutUtils.MaxSize, flags); - } - return unconstrainedPreferredSize; - } - - - /// TextRequiresWordBreak - /// If you give the text all the space in the world it wants, then there should be no reason - /// for it to break on a word. So we find out what the unconstrained size is (Int32.MaxValue, Int32.MaxValue) - /// for a string - eg. 35, 13. If the size passed in has a larger width than 35, then we know that - /// the WordBreak flag is not necessary. - public bool TextRequiresWordBreak(string text, Font font, Size size, TextFormatFlags flags) { - - // if the unconstrained size of the string is larger than the proposed width - // we need the word break flag, otherwise we dont, its a perf hit to use it. - return GetUnconstrainedSize(text, font, flags).Width > size.Width; - } - - private struct PreferredSizeCache { - public PreferredSizeCache(Size constrainingSize, Size preferredSize) { - this.ConstrainingSize = constrainingSize; - this.PreferredSize = preferredSize; - } - public Size ConstrainingSize; - public Size PreferredSize; - } - - } + public sealed class MeasureTextCache + { + private Size unconstrainedPreferredSize = LayoutUtils.InvalidSize; + private const int MaxCacheSize = 6; // the number of preferred sizes to store + private int nextCacheEntry = -1; // the next place in the ring buffer to store a preferred size + + private PreferredSizeCache[] sizeCacheList; // MRU of size MaxCacheSize + + + /// InvalidateCache + /// Clears out the cached values, should be called whenever Text, Font or a TextFormatFlag has changed + public void InvalidateCache() + { + unconstrainedPreferredSize = LayoutUtils.InvalidSize; + sizeCacheList = null; + } + + + /// GetTextSize + /// Given constraints, format flags a font and text, determine the size of the string + /// employs an MRU of the last several constraints passed in via a ring-buffer of size MaxCacheSize. + /// Assumes Text and TextFormatFlags are the same, if either were to change, a call to + /// InvalidateCache should be made + public Size GetTextSize(string text, Font font, Size proposedConstraints, TextFormatFlags flags) + { + + + if (!TextRequiresWordBreak(text, font, proposedConstraints, flags)) + { + // Text fits within proposed width + + // IF we're here, this means we've got text that can fit into the proposedConstraints + // without wrapping. We've determined this because our + + // as a side effect of calling TextRequiresWordBreak, + // unconstrainedPreferredSize is set. + return unconstrainedPreferredSize; + } + else + { + // Text does NOT fit within proposed width - requires WordBreak + + // IF we're here, this means that the wrapping width is smaller + // than our max width. For example: we measure the text with infinite + // bounding box and we determine the width to fit all the characters + // to be 200 px wide. We would come here only for proposed widths less + // than 200 px. + + + // Create our ring buffer if we dont have one + if (sizeCacheList == null) + { + sizeCacheList = new PreferredSizeCache[MaxCacheSize]; + } + + // check the existing constraints from previous calls + foreach (PreferredSizeCache sizeCache in sizeCacheList) + { + + if (sizeCache.ConstrainingSize == proposedConstraints) + { + return sizeCache.PreferredSize; + } + else if ((sizeCache.ConstrainingSize.Width == proposedConstraints.Width) + && (sizeCache.PreferredSize.Height <= proposedConstraints.Height)) + { + + // Caching a common case where the width matches perfectly, and the stored preferred height + // is smaller or equal to the constraining size. + // prefSize = GetPreferredSize(w,Int32.MaxValue); + // prefSize = GetPreferredSize(w,prefSize.Height); + + return sizeCache.PreferredSize; + } + // + } + + // if we've gotten here, it means we dont have a cache entry, therefore + // we should add a new one in the next available slot. + Size prefSize = TextRenderer.MeasureText(text, font, proposedConstraints, flags); + nextCacheEntry = (nextCacheEntry + 1) % MaxCacheSize; + sizeCacheList[nextCacheEntry] = new PreferredSizeCache(proposedConstraints, prefSize); + + return prefSize; + + } + + } + + /// GetUnconstrainedSize + /// Gets the unconstrained (Int32.MaxValue, Int32.MaxValue) size for a piece of text + private Size GetUnconstrainedSize(string text, Font font, TextFormatFlags flags) + { + + if (unconstrainedPreferredSize == LayoutUtils.InvalidSize) + { + // we also investigated setting the SingleLine flag, however this did not yield as much benefit as the word break + // and had possibility of causing internationalization issues. + + flags = (flags & ~TextFormatFlags.WordBreak); // rip out the wordbreak flag + unconstrainedPreferredSize = TextRenderer.MeasureText(text, font, LayoutUtils.MaxSize, flags); + } + return unconstrainedPreferredSize; + } + + + /// TextRequiresWordBreak + /// If you give the text all the space in the world it wants, then there should be no reason + /// for it to break on a word. So we find out what the unconstrained size is (Int32.MaxValue, Int32.MaxValue) + /// for a string - eg. 35, 13. If the size passed in has a larger width than 35, then we know that + /// the WordBreak flag is not necessary. + public bool TextRequiresWordBreak(string text, Font font, Size size, TextFormatFlags flags) + { + + // if the unconstrained size of the string is larger than the proposed width + // we need the word break flag, otherwise we dont, its a perf hit to use it. + return GetUnconstrainedSize(text, font, flags).Width > size.Width; + } + + private struct PreferredSizeCache + { + public PreferredSizeCache(Size constrainingSize, Size preferredSize) + { + this.ConstrainingSize = constrainingSize; + this.PreferredSize = preferredSize; + } + public Size ConstrainingSize; + public Size PreferredSize; + } + + } } - + // Frequently when you need to do a PreformLayout, you also need to invalidate the // PreferredSizeCache (you are laying out because you know that the action has changed // the PreferredSize of the control and/or its container). LayoutTransaction wraps both @@ -663,7 +756,8 @@ public PreferredSizeCache(Size constrainingSize, Size preferredSize) { // // The second usage spins off 12b for garbage collection, but I did some profiling and // it didn't seem significant (we were spinning off more from LayoutEventArgs.) - internal sealed class LayoutTransaction : IDisposable { + internal sealed class LayoutTransaction : IDisposable + { Control _controlToLayout; bool _resumeLayout; @@ -671,15 +765,18 @@ internal sealed class LayoutTransaction : IDisposable { int _layoutSuspendCount; #endif public LayoutTransaction(Control controlToLayout, IArrangedElement controlCausingLayout, string property) : - this(controlToLayout, controlCausingLayout, property, true) { + this(controlToLayout, controlCausingLayout, property, true) + { } - public LayoutTransaction(Control controlToLayout, IArrangedElement controlCausingLayout, string property, bool resumeLayout) { + public LayoutTransaction(Control controlToLayout, IArrangedElement controlCausingLayout, string property, bool resumeLayout) + { CommonProperties.xClearPreferredSizeCache(controlCausingLayout); _controlToLayout = controlToLayout; - + _resumeLayout = resumeLayout; - if(_controlToLayout != null) { + if (_controlToLayout != null) + { #if DEBUG _layoutSuspendCount = _controlToLayout.LayoutSuspendCount; #endif @@ -688,14 +785,17 @@ public LayoutTransaction(Control controlToLayout, IArrangedElement controlCausin // Same effect as calling performLayout on Dispose but then we would have to keep // controlCausingLayout and property around as state. - if (resumeLayout) { - _controlToLayout.PerformLayout(new LayoutEventArgs(controlCausingLayout, property)); + if (resumeLayout) + { + _controlToLayout.PerformLayout(new LayoutEventArgs(controlCausingLayout, property)); } } } - public void Dispose() { - if(_controlToLayout != null) { + public void Dispose() + { + if (_controlToLayout != null) + { _controlToLayout.ResumeLayout(_resumeLayout); #if DEBUG @@ -707,11 +807,14 @@ public void Dispose() { // This overload should be used when a property has changed that affects preferred size, // but you only want to layout if a certain condition exists (say you want to layout your // parent because your preferred size has changed). - public static IDisposable CreateTransactionIf(bool condition, Control controlToLayout, IArrangedElement elementCausingLayout, string property) { - if (condition) { - return new LayoutTransaction(controlToLayout, elementCausingLayout, property); + public static IDisposable CreateTransactionIf(bool condition, Control controlToLayout, IArrangedElement elementCausingLayout, string property) + { + if (condition) + { + return new LayoutTransaction(controlToLayout, elementCausingLayout, property); } - else { + else + { CommonProperties.xClearPreferredSizeCache(elementCausingLayout); return new NullLayoutTransaction(); @@ -719,37 +822,46 @@ public static IDisposable CreateTransactionIf(bool condition, Control controlToL } - public static void DoLayout(IArrangedElement elementToLayout, IArrangedElement elementCausingLayout, string property) { - if (elementCausingLayout != null) { + public static void DoLayout(IArrangedElement elementToLayout, IArrangedElement elementCausingLayout, string property) + { + if (elementCausingLayout != null) + { CommonProperties.xClearPreferredSizeCache(elementCausingLayout); - if(elementToLayout != null) { + if (elementToLayout != null) + { CommonProperties.xClearPreferredSizeCache(elementToLayout); elementToLayout.PerformLayout(elementCausingLayout, property); - + } } Debug.Assert(elementCausingLayout != null, "LayoutTransaction.DoLayout - elementCausingLayout is null, no layout performed - did you mix up your parameters?"); - + } // This overload should be used when a property has changed that affects preferred size, // but you only want to layout if a certain condition exists (say you want to layout your // parent because your preferred size has changed). - public static void DoLayoutIf(bool condition, IArrangedElement elementToLayout, IArrangedElement elementCausingLayout, string property) { - if (!condition) { - if (elementCausingLayout != null) { - CommonProperties.xClearPreferredSizeCache(elementCausingLayout); - } + public static void DoLayoutIf(bool condition, IArrangedElement elementToLayout, IArrangedElement elementCausingLayout, string property) + { + if (!condition) + { + if (elementCausingLayout != null) + { + CommonProperties.xClearPreferredSizeCache(elementCausingLayout); + } } - else { + else + { LayoutTransaction.DoLayout(elementToLayout, elementCausingLayout, property); } } - + } - internal struct NullLayoutTransaction : IDisposable { - public void Dispose() { - } + internal struct NullLayoutTransaction : IDisposable + { + public void Dispose() + { + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/PropertyNames.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/PropertyNames.cs index 6009fd039e3..4f483317a02 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/PropertyNames.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/PropertyNames.cs @@ -2,14 +2,16 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.Layout { +namespace System.Windows.Forms.Layout +{ using System.Diagnostics.CodeAnalysis; // LayoutEventArgs takes a string for AffectedProperty. This class contains const // strings to use as property names. Doing this allows us to use reference comparisons // which is advantageous because 1) pref and 2) we will not accidently collide with // names that extenders provide. - internal class PropertyNames { + internal class PropertyNames + { [SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate")] public static readonly string Alignment = "Alignment"; [SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate")] @@ -19,7 +21,7 @@ internal class PropertyNames { [SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate")] public static readonly string AutoSize = "AutoSize"; [SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate")] - public static readonly string Appearance = "Appearance"; + public static readonly string Appearance = "Appearance"; [SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate")] public static readonly string AutoEllipsis = "AutoEllipsis"; [SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate")] @@ -43,7 +45,7 @@ internal class PropertyNames { [SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate")] public static readonly string ColumnStyles = "ColumnStyles"; [SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate")] - public static readonly string Controls = "Controls"; + public static readonly string Controls = "Controls"; [SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate")] public static readonly string Dock = "Dock"; [SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate")] @@ -69,15 +71,15 @@ internal class PropertyNames { [SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate")] public static readonly string GrowStyle = "GrowStyle"; [SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate")] - public static readonly string Image= "Image"; + public static readonly string Image = "Image"; [SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate")] - public static readonly string ImageIndex= nameof(ImageIndex); + public static readonly string ImageIndex = nameof(ImageIndex); [SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate")] - public static readonly string ImageScaling= "ImageScaling"; + public static readonly string ImageScaling = "ImageScaling"; [SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate")] - public static readonly string ImageScalingSize= "ImageScalingSize"; + public static readonly string ImageScalingSize = "ImageScalingSize"; [SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate")] - public static readonly string ImageKey= "ImageKey"; + public static readonly string ImageKey = "ImageKey"; [SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate")] public static readonly string ImageAlign = "ImageAlign"; [SuppressMessage("Microsoft.Performance", "CA1802:UseLiteralsWhereAppropriate")] 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 7ce3de225d9..8686a2c6ef7 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 @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.Layout { +namespace System.Windows.Forms.Layout +{ using System; using System.Collections; @@ -14,8 +15,9 @@ namespace System.Windows.Forms.Layout { using System.Collections.Specialized; using System.Collections.Generic; using System.Globalization; - - internal class TableLayout : LayoutEngine { + + internal class TableLayout : LayoutEngine + { // This code was taken from ndp\clr\src\BCL\System\Array.cs // This changeset replaced the sorting algorithm when elements with the same @@ -24,7 +26,8 @@ internal class TableLayout : LayoutEngine { // some customers are putting more than one control in the same TableLayout cell // and we rely on this order to resovle the conflict - private static int GetMedian(int low, int hi) { + private static int GetMedian(int low, int hi) + { // Note both may be negative, if we are dealing with arrays w/ negative lower bounds. return low + ((hi - low) >> 1); } @@ -33,36 +36,46 @@ private static int GetMedian(int low, int hi) { private struct SorterObjectArray { private object[] keys; - private IComparer comparer; - - internal SorterObjectArray(object[] keys, IComparer comparer) { - if (comparer == null) comparer = Comparer.Default; + private IComparer comparer; + + internal SorterObjectArray(object[] keys, IComparer comparer) + { + if (comparer == null) + comparer = Comparer.Default; this.keys = keys; this.comparer = comparer; } - - internal void SwapIfGreaterWithItems(int a, int b) { - if (a != b) { - try { - if (comparer.Compare(keys[a], keys[b]) > 0) { + + internal void SwapIfGreaterWithItems(int a, int b) + { + if (a != b) + { + try + { + if (comparer.Compare(keys[a], keys[b]) > 0) + { object temp = keys[a]; keys[a] = keys[b]; keys[b] = temp; } } - catch (IndexOutOfRangeException) { + catch (IndexOutOfRangeException) + { throw new ArgumentException(); } - catch (Exception) { + catch (Exception) + { throw new InvalidOperationException(); } } } - internal void QuickSort(int left, int right) { + internal void QuickSort(int left, int right) + { // Can use the much faster jit helpers for array access. - do { + do + { int i = left; int j = right; @@ -75,21 +88,29 @@ internal void QuickSort(int left, int right) { SwapIfGreaterWithItems(middle, j); // swap the middle with the high object x = keys[middle]; - do { + do + { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. - try { - while (comparer.Compare(keys[i], x) < 0) i++; - while (comparer.Compare(x, keys[j]) < 0) j--; + try + { + while (comparer.Compare(keys[i], x) < 0) + i++; + while (comparer.Compare(x, keys[j]) < 0) + j--; } - catch (IndexOutOfRangeException) { + catch (IndexOutOfRangeException) + { throw new ArgumentException(); } - catch (Exception) { + catch (Exception) + { throw new InvalidOperationException(); } - if (i > j) break; - if (i < j) { + if (i > j) + break; + if (i < j) + { object key = keys[i]; keys[i] = keys[j]; keys[j] = key; @@ -97,23 +118,29 @@ internal void QuickSort(int left, int right) { i++; j--; } while (i <= j); - if (j - left <= right - i) { - if (left < j) QuickSort(left, j); + if (j - left <= right - i) + { + if (left < j) + QuickSort(left, j); left = i; } - else { - if (i < right) QuickSort(i, right); + else + { + if (i < right) + QuickSort(i, right); right = j; } } while (left < right); } } - - private static void Sort(object[] array, IComparer comparer) { + + private static void Sort(object[] array, IComparer comparer) + { if (array == null) throw new ArgumentNullException(nameof(array)); - if (array.Length > 1) { + if (array.Length > 1) + { SorterObjectArray sorter = new SorterObjectArray(array, comparer); sorter.QuickSort(0, array.Length - 1); } @@ -127,7 +154,7 @@ private static void Sort(object[] array, IComparer comparer) { private static readonly int _containerInfoProperty = PropertyStore.CreateKey(); private static readonly int _layoutInfoProperty = PropertyStore.CreateKey(); - + private static string[] _propertiesWhichInvalidateCache = new string[] { //suspend layout before changing one of the above property will cause the AffectedProperty of LayoutEventArgs to be set to null //for more information, see http://wiki/default.aspx/Microsoft.Projects.DotNetClient.LayoutEventArgs @@ -143,16 +170,20 @@ private static void Sort(object[] array, IComparer comparer) { PropertyNames.ColumnStyles, // RowSpan, ColumnSpan, TableIndex manually call ClearCachedAssignments. }; - - internal static TableLayoutSettings CreateSettings(IArrangedElement owner) { + + internal static TableLayoutSettings CreateSettings(IArrangedElement owner) + { return new TableLayoutSettings(owner); } - internal override void ProcessSuspendedLayoutEventArgs(IArrangedElement container, LayoutEventArgs args) { + internal override void ProcessSuspendedLayoutEventArgs(IArrangedElement container, LayoutEventArgs args) + { ContainerInfo containerInfo = GetContainerInfo(container); - - foreach(string propertyName in _propertiesWhichInvalidateCache) { - if(Object.ReferenceEquals(args.AffectedProperty, propertyName)) { + + foreach (string propertyName in _propertiesWhichInvalidateCache) + { + if (Object.ReferenceEquals(args.AffectedProperty, propertyName)) + { ClearCachedAssignments(containerInfo); break; } @@ -178,22 +209,23 @@ internal override void ProcessSuspendedLayoutEventArgs(IArrangedElement containe /// (a) Calculate bounds of item /// (b) Align and stretch item to fill column/row as according to Dock&Anchor properties. /// - internal override bool LayoutCore(IArrangedElement container, LayoutEventArgs args) { + internal override bool LayoutCore(IArrangedElement container, LayoutEventArgs args) + { ProcessSuspendedLayoutEventArgs(container, args); ContainerInfo containerInfo = GetContainerInfo(container); EnsureRowAndColumnAssignments(container, containerInfo, /* doNotCache = */false); - + int cellBorderWidth = containerInfo.CellBorderWidth; - + //shrink the size of the display rectangle so that we have space to draw the border Size containerSize = container.DisplayRectangle.Size - new Size(cellBorderWidth, cellBorderWidth); //make sure our sizes are non-negative containerSize.Width = Math.Max(containerSize.Width, 1); containerSize.Height = Math.Max(containerSize.Height, 1); - + Size usedSpace = ApplyStyles(containerInfo, containerSize, /*measureOnly=*/false); ExpandLastElement(containerInfo, usedSpace, containerSize); RectangleF displayRect = (RectangleF)container.DisplayRectangle; @@ -203,7 +235,7 @@ internal override bool LayoutCore(IArrangedElement container, LayoutEventArgs ar // ScrollableControl will first try to get the layoutbounds from the derived control when // trying to figure out if ScrollBars should be added. CommonProperties.SetLayoutBounds(containerInfo.Container, new Size(SumStrips(containerInfo.Columns, 0, containerInfo.Columns.Length), - SumStrips(containerInfo.Rows, 0, containerInfo.Rows.Length))); + SumStrips(containerInfo.Rows, 0, containerInfo.Rows.Length))); return CommonProperties.GetAutoSize(container); } @@ -219,8 +251,9 @@ internal override bool LayoutCore(IArrangedElement container, LayoutEventArgs ar /// Similar to LayoutCore. Row/Column assignments are NOT cached. TableLayout uses AGRESSIVE /// caching for performance reasons. /// - internal override Size GetPreferredSize(IArrangedElement container, Size proposedConstraints) { - + internal override Size GetPreferredSize(IArrangedElement container, Size proposedConstraints) + { + ContainerInfo containerInfo = GetContainerInfo(container); // PERF: Optimizing nested table layouts. @@ -231,8 +264,9 @@ internal override Size GetPreferredSize(IArrangedElement container, Size propose bool isCacheValid = false; float oldWidth = -1f; Size prefSize = containerInfo.GetCachedPreferredSize(proposedConstraints, out isCacheValid); - if(isCacheValid) { - return prefSize; + if (isCacheValid) + { + return prefSize; } //create a dummy containerInfo and we operate on the dummy containerInfo only @@ -241,9 +275,10 @@ internal override Size GetPreferredSize(IArrangedElement container, Size propose //size information may no longer be accurate. ContainerInfo tempInfo = new ContainerInfo(containerInfo); int cellBorderWidth = containerInfo.CellBorderWidth; - + //pretend the last column is the size of the container if it is absolutely sized - if (containerInfo.MaxColumns == 1 && containerInfo.ColumnStyles.Count > 0 && containerInfo.ColumnStyles[0].SizeType == SizeType.Absolute) { + if (containerInfo.MaxColumns == 1 && containerInfo.ColumnStyles.Count > 0 && containerInfo.ColumnStyles[0].SizeType == SizeType.Absolute) + { //shrink the size of the display rectangle so that we have space to draw the border Size containerSize = container.DisplayRectangle.Size - new Size(cellBorderWidth * 2, cellBorderWidth * 2); @@ -253,11 +288,11 @@ internal override Size GetPreferredSize(IArrangedElement container, Size propose oldWidth = containerInfo.ColumnStyles[0].Size; containerInfo.ColumnStyles[0].SetSize(Math.Max(oldWidth, Math.Min(proposedConstraints.Width, containerSize.Width))); } - + //notice we always assign rows and columns here since the user may change the properties of the table while the layout is //suspended, so we have no way to know whether the cache is invalid or not here. - EnsureRowAndColumnAssignments(container, tempInfo, /* doNotCache = */ true); - + EnsureRowAndColumnAssignments(container, tempInfo, /* doNotCache = */ true); + //deduct the padding for cell border before doing layout Size cellBorderSize = new Size(cellBorderWidth, cellBorderWidth); proposedConstraints -= cellBorderSize; @@ -276,7 +311,8 @@ internal override Size GetPreferredSize(IArrangedElement container, Size propose //prefSize = MeasureStyles(tempInfo); //restores the old strip size - if (oldWidth >= 0) { + if (oldWidth >= 0) + { containerInfo.ColumnStyles[0].SetSize(oldWidth); } @@ -289,35 +325,41 @@ internal override Size GetPreferredSize(IArrangedElement container, Size propose /// - Does nothing if Cache is valid /// - sets RowStart,RowSpan,ColumnStart,ColumnSpan into the LayoutInfo[] collection (containerInfo.ChildrenInfo) /// - private void EnsureRowAndColumnAssignments(IArrangedElement container, ContainerInfo containerInfo, bool doNotCache) { + private void EnsureRowAndColumnAssignments(IArrangedElement container, ContainerInfo containerInfo, bool doNotCache) + { // Assign new rows and columns if the cache is invalid or if we are in GetPreferredSize - if(!HasCachedAssignments(containerInfo) || doNotCache) { + if (!HasCachedAssignments(containerInfo) || doNotCache) + { AssignRowsAndColumns(containerInfo); } - + Debug_VerifyAssignmentsAreCurrent(container, containerInfo); } - + /// /// ExpandLastElement: expands the row/column to fill the rest of the space in the container. /// - private void ExpandLastElement(ContainerInfo containerInfo, Size usedSpace, Size totalSpace) { + private void ExpandLastElement(ContainerInfo containerInfo, Size usedSpace, Size totalSpace) + { Strip[] rows = containerInfo.Rows; Strip[] cols = containerInfo.Columns; - if (cols.Length != 0 && totalSpace.Width > usedSpace.Width) { - cols[cols.Length - 1].MinSize += totalSpace.Width - usedSpace.Width; + if (cols.Length != 0 && totalSpace.Width > usedSpace.Width) + { + cols[cols.Length - 1].MinSize += totalSpace.Width - usedSpace.Width; } - if (rows.Length != 0 && totalSpace.Height > usedSpace.Height) { + if (rows.Length != 0 && totalSpace.Height > usedSpace.Height) + { rows[rows.Length - 1].MinSize += totalSpace.Height - usedSpace.Height; } } - + /// /// AssignRowsAndColumns: part of EnsureRowAndColumnAssignments. /// determines the number of rows and columns we need to create /// - private void AssignRowsAndColumns(ContainerInfo containerInfo) { + private void AssignRowsAndColumns(ContainerInfo containerInfo) + { int numCols = containerInfo.MaxColumns; int numRows = containerInfo.MaxRows; @@ -328,57 +370,68 @@ private void AssignRowsAndColumns(ContainerInfo containerInfo) { int minSpace = containerInfo.MinRowsAndColumns; int minColumn = containerInfo.MinColumns; int minRow = containerInfo.MinRows; - + TableLayoutPanelGrowStyle growStyle = containerInfo.GrowStyle; - if (growStyle == TableLayoutPanelGrowStyle.FixedSize) { + if (growStyle == TableLayoutPanelGrowStyle.FixedSize) + { //if we're a fixed size - check to see if we have enough room - if (containerInfo.MinRowsAndColumns > numCols * numRows) { + if (containerInfo.MinRowsAndColumns > numCols * numRows) + { throw new ArgumentException(SR.TableLayoutPanelFullDesc); - } + } - if ((minColumn > numCols) || (minRow > numRows)) { + if ((minColumn > numCols) || (minRow > numRows)) + { throw new ArgumentException(SR.TableLayoutPanelSpanDesc); } - + numRows = Math.Max(1, numRows); numCols = Math.Max(1, numCols); // numRows = numRows - numRows indicates that columns are specified and rows should grow } - else if (growStyle == TableLayoutPanelGrowStyle.AddRows) { + else if (growStyle == TableLayoutPanelGrowStyle.AddRows) + { numRows = 0;//indicates that columns are specified and rows should grow } - else {//must be addcolumns + else + {//must be addcolumns numCols = 0;//indicates that rows are specified and columns should grow } - - if(numCols > 0) { + + if (numCols > 0) + { // The user specified the number of column (the simple/fast case) xAssignRowsAndColumns(containerInfo, childrenInfo, numCols, numRows == 0 ? int.MaxValue : numRows, growStyle); - } else if(numRows > 0) { + } + else if (numRows > 0) + { // The user specified rows only (we need to compute the number of columns) - + int estimatedCols = Math.Max((int)Math.Ceiling((float)minSpace / numRows), minColumn); - + //make sure that estimatedCols is positive estimatedCols = Math.Max(estimatedCols, 1); - - while(!xAssignRowsAndColumns(containerInfo, childrenInfo, estimatedCols, numRows, growStyle)) { + + while (!xAssignRowsAndColumns(containerInfo, childrenInfo, estimatedCols, numRows, growStyle)) + { // I am assuming that the division will put us pretty close to the right // number of columns. If this assumption is wrong, a binary search // between the number we get by dividing and childrenInfos.Count // could be more efficient. It would certainly degenerate better. estimatedCols++; } - } else { + } + else + { // No rows or columns specified, just do a vertical stack. - xAssignRowsAndColumns(containerInfo, childrenInfo, /* numCols = */ Math.Max(minColumn,1), /* numRows = */ int.MaxValue, growStyle); + xAssignRowsAndColumns(containerInfo, childrenInfo, /* numCols = */ Math.Max(minColumn, 1), /* numRows = */ int.MaxValue, growStyle); } } - - + + /// /// xAssignRowsAndColumns: part of AssignRowsAndColumns. /// def: fixed element: has a specific row/column assignment (assigned by SetRow,SetColumn, or Add(c,row,column) @@ -387,13 +440,14 @@ private void AssignRowsAndColumns(ContainerInfo containerInfo) { /// Determines the placement of fixed and flow elements. Walks through the rows/columns - if there's a /// spot for the fixed element, place it, else place the next flow element. /// - private bool xAssignRowsAndColumns(ContainerInfo containerInfo, LayoutInfo[] childrenInfo, int maxColumns, int maxRows, TableLayoutPanelGrowStyle growStyle) { + private bool xAssignRowsAndColumns(ContainerInfo containerInfo, LayoutInfo[] childrenInfo, int maxColumns, int maxRows, TableLayoutPanelGrowStyle growStyle) + { Debug.Assert(maxColumns > 0, "maxColumn must be positive"); - + int numColumns = 0; int numRows = 0; ReservationGrid reservationGrid = new ReservationGrid(); - + int currentRow = 0; int currentCol = 0; @@ -403,49 +457,56 @@ private bool xAssignRowsAndColumns(ContainerInfo containerInfo, LayoutInfo[] chi // make sure to snap these two collections as we're not in a "containerInfo.Valid" state // so we'll wind up building up the lists over and over again. LayoutInfo[] fixedChildrenInfo = containerInfo.FixedChildrenInfo; - - + + //the element at the head of the absolutely positioned element queue LayoutInfo fixedElement = GetNextLayoutInfo(fixedChildrenInfo, ref fixedElementIndex, /*absolutelyPositioned*/true); - + //the element at the head of the non-absolutely positioned element queue LayoutInfo flowElement = GetNextLayoutInfo(childrenInfo, ref flowElementIndex, /*absolutelyPositioned*/false); - - while (fixedElement != null || flowElement != null) { + + while (fixedElement != null || flowElement != null) + { int colStop = currentCol; int rowStop; - if (flowElement != null) { + if (flowElement != null) + { flowElement.RowStart = currentRow; flowElement.ColumnStart = currentCol; //try to layout the flowElement to see if it overlaps with the fixedElement AdvanceUntilFits(maxColumns, reservationGrid, flowElement, out colStop); //we have exceeded the row limit. just return - if (flowElement.RowStart >= maxRows) { + if (flowElement.RowStart >= maxRows) + { return false; } } //test to see if either the absolutely positioned element is null or it fits. - if (flowElement != null && (fixedElement == null || (!IsCursorPastInsertionPoint(fixedElement, flowElement.RowStart, colStop) && !IsOverlappingWithReservationGrid(fixedElement, reservationGrid, currentRow)))) { + if (flowElement != null && (fixedElement == null || (!IsCursorPastInsertionPoint(fixedElement, flowElement.RowStart, colStop) && !IsOverlappingWithReservationGrid(fixedElement, reservationGrid, currentRow)))) + { //Place the flow element. //advance the rows in reservation grid - for (int j = 0; j < flowElement.RowStart - currentRow; j++) { + for (int j = 0; j < flowElement.RowStart - currentRow; j++) + { reservationGrid.AdvanceRow(); } - + currentRow = flowElement.RowStart; rowStop = Math.Min(currentRow + flowElement.RowSpan, maxRows); - + //reserve spaces in the reservationGrid reservationGrid.ReserveAll(flowElement, rowStop, colStop); flowElement = GetNextLayoutInfo(childrenInfo, ref flowElementIndex, /*absolutelyPositioned*/false); } - else { + else + { // //otherwise we place the fixed element. // - if (currentCol >= maxColumns) { + if (currentCol >= maxColumns) + { //we have already passed the boundary. Go to next row currentCol = 0; currentRow++; @@ -454,22 +515,26 @@ private bool xAssignRowsAndColumns(ContainerInfo containerInfo, LayoutInfo[] chi //set the rowStart and columnStart to fixedElement's specifed position fixedElement.RowStart = Math.Min(fixedElement.RowPosition, maxRows - 1); fixedElement.ColumnStart = Math.Min(fixedElement.ColumnPosition, maxColumns - 1); - if (currentRow > fixedElement.RowStart) { + if (currentRow > fixedElement.RowStart) + { //we have already passed the specifed position. set the start column to the current column fixedElement.ColumnStart = currentCol; } - else if (currentRow == fixedElement.RowStart) { + else if (currentRow == fixedElement.RowStart) + { //set the start column to be the max of the specifed column and current column fixedElement.ColumnStart = Math.Max(fixedElement.ColumnStart, currentCol); } - else { + else + { //set the start column to the specified column, which we have already done } fixedElement.RowStart = Math.Max(fixedElement.RowStart, currentRow); //advance the reservation grid int j; - for (j = 0; j < fixedElement.RowStart - currentRow; j++) { + for (j = 0; j < fixedElement.RowStart - currentRow; j++) + { reservationGrid.AdvanceRow(); } @@ -478,55 +543,62 @@ private bool xAssignRowsAndColumns(ContainerInfo containerInfo, LayoutInfo[] chi AdvanceUntilFits(maxColumns, reservationGrid, fixedElement, out colStop); //we have exceeded the row limit. just return - if (fixedElement.RowStart >= maxRows) { + if (fixedElement.RowStart >= maxRows) + { return false; } - for (; j < fixedElement.RowStart - currentRow; j++) { + for (; j < fixedElement.RowStart - currentRow; j++) + { //advance the reservation grid if the fixedElement's row position has changed during layout reservationGrid.AdvanceRow(); } currentRow = fixedElement.RowStart; - + //make sure that we truncate the element's column span if it is too big - colStop = Math.Min(fixedElement.ColumnStart + fixedElement.ColumnSpan, maxColumns); - rowStop = Math.Min(fixedElement.RowStart + fixedElement.RowSpan, maxRows); + colStop = Math.Min(fixedElement.ColumnStart + fixedElement.ColumnSpan, maxColumns); + rowStop = Math.Min(fixedElement.RowStart + fixedElement.RowSpan, maxRows); //reserve space in the reservation grid - reservationGrid.ReserveAll(fixedElement, rowStop, colStop); + reservationGrid.ReserveAll(fixedElement, rowStop, colStop); fixedElement = GetNextLayoutInfo(fixedChildrenInfo, ref fixedElementIndex, /*absolutelyPositioned*/true); - } + } currentCol = colStop; - numRows = (numRows == int.MaxValue) ? rowStop : Math.Max(numRows, rowStop); - numColumns = (numColumns == int.MaxValue) ? colStop : Math.Max(numColumns, colStop); - } + numRows = (numRows == int.MaxValue) ? rowStop : Math.Max(numRows, rowStop); + numColumns = (numColumns == int.MaxValue) ? colStop : Math.Max(numColumns, colStop); + } Debug.Assert(numRows <= maxRows, "number of rows allocated shouldn't exceed max number of rows"); Debug.Assert(numColumns <= maxColumns, "number of columns allocated shouldn't exceed max number of columns"); // we should respect columncount and rowcount as according to GrowStyle. - if (growStyle == TableLayoutPanelGrowStyle.FixedSize) { + if (growStyle == TableLayoutPanelGrowStyle.FixedSize) + { // now that we've calculated the assignments - use the "max" as the actual number of rows. numColumns = maxColumns; numRows = maxRows; } - else if (growStyle == TableLayoutPanelGrowStyle.AddRows) { - numColumns = maxColumns; - numRows = Math.Max(containerInfo.MaxRows, numRows); + else if (growStyle == TableLayoutPanelGrowStyle.AddRows) + { + numColumns = maxColumns; + numRows = Math.Max(containerInfo.MaxRows, numRows); } - else { // add columns + else + { // add columns numRows = (maxRows == int.MaxValue) ? numRows : maxRows; numColumns = Math.Max(containerInfo.MaxColumns, numColumns); } // PERF: prevent overallocation of Strip[] arrays. We're going to null these guys out // anyways... so only allocate when the number of rows and columns is different. - if (containerInfo.Rows == null || containerInfo.Rows.Length != numRows) { + if (containerInfo.Rows == null || containerInfo.Rows.Length != numRows) + { containerInfo.Rows = new Strip[numRows]; } - if (containerInfo.Columns == null || containerInfo.Columns.Length != numColumns) { + if (containerInfo.Columns == null || containerInfo.Columns.Length != numColumns) + { containerInfo.Columns = new Strip[numColumns]; } @@ -534,37 +606,43 @@ private bool xAssignRowsAndColumns(ContainerInfo containerInfo, LayoutInfo[] chi return true; } - + /// /// GetNextLayoutInfo: part of xAssignRowsAndColumns. /// helper function that walks through the collection picking out the next flow element or fixed element. /// - private static LayoutInfo GetNextLayoutInfo(LayoutInfo[] layoutInfo, ref int index, bool absolutelyPositioned) { - - for (int i = ++index; i < layoutInfo.Length; i++) { - if (absolutelyPositioned == layoutInfo[i].IsAbsolutelyPositioned) { + private static LayoutInfo GetNextLayoutInfo(LayoutInfo[] layoutInfo, ref int index, bool absolutelyPositioned) + { + + for (int i = ++index; i < layoutInfo.Length; i++) + { + if (absolutelyPositioned == layoutInfo[i].IsAbsolutelyPositioned) + { index = i; return layoutInfo[i]; - } + } } index = layoutInfo.Length; return null; } - + /// /// IsCursorPastInsertionPoint: part of xAssignRowsAndColumns. /// check to see if the user specified location for fixedLayoutInfo has passed the insertion point specified by the cursor /// - private bool IsCursorPastInsertionPoint(LayoutInfo fixedLayoutInfo, int insertionRow, int insertionCol) { + private bool IsCursorPastInsertionPoint(LayoutInfo fixedLayoutInfo, int insertionRow, int insertionCol) + { Debug.Assert(fixedLayoutInfo.IsAbsolutelyPositioned, "should only check for those elements which are absolutely positioned"); - + //if the element is bumped to a row below its specified row position, it means that the element overlaps with previous controls - if (fixedLayoutInfo.RowPosition < insertionRow) { + if (fixedLayoutInfo.RowPosition < insertionRow) + { return true; } //if the element is bumped to a column after its specified column position, it also means that the element overlaps with previous controls - if (fixedLayoutInfo.RowPosition == insertionRow && fixedLayoutInfo.ColumnPosition < insertionCol) { + if (fixedLayoutInfo.RowPosition == insertionRow && fixedLayoutInfo.ColumnPosition < insertionCol) + { return true; } return false; @@ -574,14 +652,19 @@ private bool IsCursorPastInsertionPoint(LayoutInfo fixedLayoutInfo, int insertio /// IsOverlappingWithReservationGrid: part of xAssignRowsAndColumns. /// check to see if the absolutely positioned layoutInfo fits in the reservation grid /// - private bool IsOverlappingWithReservationGrid(LayoutInfo fixedLayoutInfo, ReservationGrid reservationGrid, int currentRow) { + private bool IsOverlappingWithReservationGrid(LayoutInfo fixedLayoutInfo, ReservationGrid reservationGrid, int currentRow) + { //since we shall not put anything above our current row, this means that the fixedLayoutInfo overlaps with something already placed on the table - if (fixedLayoutInfo.RowPosition < currentRow) { + if (fixedLayoutInfo.RowPosition < currentRow) + { return true; } - for (int rowOffset = fixedLayoutInfo.RowPosition - currentRow; rowOffset < fixedLayoutInfo.RowPosition - currentRow + fixedLayoutInfo.RowSpan; rowOffset++) { - for (int colOffset = fixedLayoutInfo.ColumnPosition; colOffset < fixedLayoutInfo.ColumnPosition + fixedLayoutInfo.ColumnSpan; colOffset++) { - if (reservationGrid.IsReserved(colOffset, rowOffset)) { + for (int rowOffset = fixedLayoutInfo.RowPosition - currentRow; rowOffset < fixedLayoutInfo.RowPosition - currentRow + fixedLayoutInfo.RowSpan; rowOffset++) + { + for (int colOffset = fixedLayoutInfo.ColumnPosition; colOffset < fixedLayoutInfo.ColumnPosition + fixedLayoutInfo.ColumnSpan; colOffset++) + { + if (reservationGrid.IsReserved(colOffset, rowOffset)) + { return true; } } @@ -595,22 +678,27 @@ private bool IsOverlappingWithReservationGrid(LayoutInfo fixedLayoutInfo, Reserv /// collide with a rowSpanned element. ColStop will be the column on which the /// element ends (exclusive). /// - private void AdvanceUntilFits(int maxColumns, ReservationGrid reservationGrid, LayoutInfo layoutInfo, out int colStop) { + private void AdvanceUntilFits(int maxColumns, ReservationGrid reservationGrid, LayoutInfo layoutInfo, out int colStop) + { int prevRow = layoutInfo.RowStart; - do { + do + { GetColStartAndStop(maxColumns, reservationGrid, layoutInfo, out colStop); - } while(ScanRowForOverlap(maxColumns, reservationGrid, layoutInfo, colStop, layoutInfo.RowStart - prevRow)); + } while (ScanRowForOverlap(maxColumns, reservationGrid, layoutInfo, colStop, layoutInfo.RowStart - prevRow)); } /// /// GetColStartAndStop: part of xAssignRowsAndColumns. /// /// - private void GetColStartAndStop(int maxColumns, ReservationGrid reservationGrid, LayoutInfo layoutInfo, out int colStop) { + private void GetColStartAndStop(int maxColumns, ReservationGrid reservationGrid, LayoutInfo layoutInfo, out int colStop) + { // Compute the column our element ends on colStop = layoutInfo.ColumnStart + layoutInfo.ColumnSpan; - if(colStop > maxColumns) { - if(layoutInfo.ColumnStart != 0) { + if (colStop > maxColumns) + { + if (layoutInfo.ColumnStart != 0) + { // If we are not already at the beginning or a row, move down // to the next row. layoutInfo.ColumnStart = 0; @@ -621,21 +709,26 @@ private void GetColStartAndStop(int maxColumns, ReservationGrid reservationGrid, } } - private bool ScanRowForOverlap(int maxColumns, ReservationGrid reservationGrid, LayoutInfo layoutInfo, int stopCol, int rowOffset) { - for(int i = layoutInfo.ColumnStart; i < stopCol; i++) { - if(reservationGrid.IsReserved(i, rowOffset)) { + private bool ScanRowForOverlap(int maxColumns, ReservationGrid reservationGrid, LayoutInfo layoutInfo, int stopCol, int rowOffset) + { + for (int i = layoutInfo.ColumnStart; i < stopCol; i++) + { + if (reservationGrid.IsReserved(i, rowOffset)) + { // If we hit reserved space, advance startCol past it. If we hit the end of the row, // just stop. AdvanceUntilFits will move to the next row and call us again. - for(layoutInfo.ColumnStart = i + 1; + for (layoutInfo.ColumnStart = i + 1; layoutInfo.ColumnStart < maxColumns && reservationGrid.IsReserved(layoutInfo.ColumnStart, rowOffset); - layoutInfo.ColumnStart++); + layoutInfo.ColumnStart++) + ; return true; } } return false; } - private Size ApplyStyles(ContainerInfo containerInfo, Size proposedConstraints, bool measureOnly) { + private Size ApplyStyles(ContainerInfo containerInfo, Size proposedConstraints, bool measureOnly) + { Size preferredSize = Size.Empty; //allocate space for all absolutely sized strips. Set the size of the rest of the strips to 0. @@ -644,36 +737,43 @@ private Size ApplyStyles(ContainerInfo containerInfo, Size proposedConstraints, // perf optimization - detect if we should worry about column spans containerInfo.ChildHasColumnSpan = false; - containerInfo.ChildHasRowSpan = false; - + containerInfo.ChildHasRowSpan = false; + //detect all rows/columns which have control starting from it - foreach(LayoutInfo layoutInfo in containerInfo.ChildrenInfo) { + foreach (LayoutInfo layoutInfo in containerInfo.ChildrenInfo) + { containerInfo.Columns[layoutInfo.ColumnStart].IsStart = true; containerInfo.Rows[layoutInfo.RowStart].IsStart = true; - if (layoutInfo.ColumnSpan > 1) { + if (layoutInfo.ColumnSpan > 1) + { containerInfo.ChildHasColumnSpan = true; } - if (layoutInfo.RowSpan > 1) { + if (layoutInfo.RowSpan > 1) + { containerInfo.ChildHasRowSpan = true; } - } + } preferredSize.Width = InflateColumns(containerInfo, proposedConstraints, measureOnly); - int expandLastElementWidth = Math.Max(0,proposedConstraints.Width - preferredSize.Width); + int expandLastElementWidth = Math.Max(0, proposedConstraints.Width - preferredSize.Width); preferredSize.Height = InflateRows(containerInfo, proposedConstraints, expandLastElementWidth, measureOnly); return preferredSize; } //allocate space for all absolutely sized strips. Set the size of the rest of the strips to 0. - private void InitializeStrips(Strip[] strips, IList styles) { + private void InitializeStrips(Strip[] strips, IList styles) + { Strip strip; - for (int i = 0; i < strips.Length; i++) { + for (int i = 0; i < strips.Length; i++) + { TableLayoutStyle style = i < styles.Count ? (TableLayoutStyle)styles[i] : null; strip = strips[i]; - if (style != null && style.SizeType == SizeType.Absolute) { - strip.MinSize = (int)Math.Round((double)((TableLayoutStyle)styles[i]).Size); + if (style != null && style.SizeType == SizeType.Absolute) + { + strip.MinSize = (int)Math.Round((double)((TableLayoutStyle)styles[i]).Size); strip.MaxSize = strip.MinSize; } - else { + else + { strip.MinSize = 0; strip.MaxSize = 0; } @@ -682,12 +782,14 @@ private void InitializeStrips(Strip[] strips, IList styles) { } } - private int InflateColumns(ContainerInfo containerInfo, Size proposedConstraints, bool measureOnly) { + private int InflateColumns(ContainerInfo containerInfo, Size proposedConstraints, bool measureOnly) + { bool dontHonorConstraint = measureOnly; - + LayoutInfo[] sortedChildren = containerInfo.ChildrenInfo; - if (containerInfo.ChildHasColumnSpan) { + if (containerInfo.ChildHasColumnSpan) + { Sort(sortedChildren, ColumnSpanComparer.GetInstance); } @@ -699,39 +801,47 @@ private int InflateColumns(ContainerInfo containerInfo, Size proposedConstraints // The Int16.MaxValue check will tell us whether we are actually constrained or not. This is not ideal. - if (dontHonorConstraint && (proposedConstraints.Width < short.MaxValue)) { + if (dontHonorConstraint && (proposedConstraints.Width < short.MaxValue)) + { TableLayoutPanel tlp = containerInfo.Container as TableLayoutPanel; - if (tlp != null && tlp.ParentInternal != null && tlp.ParentInternal.LayoutEngine == DefaultLayout.Instance) { - if (tlp.Dock == DockStyle.Top || tlp.Dock == DockStyle.Bottom || tlp.Dock == DockStyle.Fill) { + if (tlp != null && tlp.ParentInternal != null && tlp.ParentInternal.LayoutEngine == DefaultLayout.Instance) + { + if (tlp.Dock == DockStyle.Top || tlp.Dock == DockStyle.Bottom || tlp.Dock == DockStyle.Fill) + { dontHonorConstraint = false; // we want to honor constraints } - - if ((tlp.Anchor & (AnchorStyles.Left | AnchorStyles.Right)) == (AnchorStyles.Left | AnchorStyles.Right)) { + + if ((tlp.Anchor & (AnchorStyles.Left | AnchorStyles.Right)) == (AnchorStyles.Left | AnchorStyles.Right)) + { dontHonorConstraint = false; // we want to honor constraints - } + } } - } - - foreach(LayoutInfo layoutInfo in sortedChildren) { + } + + foreach (LayoutInfo layoutInfo in sortedChildren) + { IArrangedElement element = layoutInfo.Element; - + int columnSpan = layoutInfo.ColumnSpan; // since InitializeStrips already allocated absolutely sized columns, we can skip over them - if (columnSpan > 1 || !IsAbsolutelySized(layoutInfo.ColumnStart, containerInfo.ColumnStyles)) { - int minWidth =0, maxWidth = 0; + if (columnSpan > 1 || !IsAbsolutelySized(layoutInfo.ColumnStart, containerInfo.ColumnStyles)) + { + int minWidth = 0, maxWidth = 0; // optimize for the case where one of the parameters is known. if ((columnSpan == 1 && layoutInfo.RowSpan == 1) && - (IsAbsolutelySized(layoutInfo.RowStart, containerInfo.RowStyles))) { - int constrainingHeight = (int)containerInfo.RowStyles[layoutInfo.RowStart].Size; - minWidth = GetElementSize(element, new Size(0, constrainingHeight)).Width; - maxWidth = minWidth; + (IsAbsolutelySized(layoutInfo.RowStart, containerInfo.RowStyles))) + { + int constrainingHeight = (int)containerInfo.RowStyles[layoutInfo.RowStart].Size; + minWidth = GetElementSize(element, new Size(0, constrainingHeight)).Width; + maxWidth = minWidth; } - else { + else + { minWidth = GetElementSize(element, new Size(1, 0)).Width; maxWidth = GetElementSize(element, Size.Empty).Width; } - + // tack on margins Padding margin = CommonProperties.GetMargin(element); minWidth += margin.Horizontal; @@ -746,7 +856,8 @@ private int InflateColumns(ContainerInfo containerInfo, Size proposedConstraints int width = DistributeStyles(containerInfo.CellBorderWidth, containerInfo.ColumnStyles, containerInfo.Columns, proposedConstraints.Width, dontHonorConstraint); // TLP doesn't honor proposedConstraints - if (dontHonorConstraint && width > proposedConstraints.Width && proposedConstraints.Width > 1) { + if (dontHonorConstraint && width > proposedConstraints.Width && proposedConstraints.Width > 1) + { // Step 1: iterate through the rows or columns, // - calculate the amount of space allocated // - for percent size columns @@ -758,11 +869,14 @@ private int InflateColumns(ContainerInfo containerInfo, Size proposedConstraints int totalPercentAllocatedSpace = 0; TableLayoutStyleCollection styles = containerInfo.ColumnStyles; - for(int i = 0; i < strips.Length; i++) { + for (int i = 0; i < strips.Length; i++) + { Strip strip = strips[i]; - if(i < styles.Count) { - TableLayoutStyle style = (TableLayoutStyle) styles[i]; - if (style.SizeType == SizeType.Percent) { + if (i < styles.Count) + { + TableLayoutStyle style = (TableLayoutStyle)styles[i]; + if (style.SizeType == SizeType.Percent) + { totalPercent += style.Size; totalPercentAllocatedSpace += strip.MinSize; } @@ -775,27 +889,32 @@ private int InflateColumns(ContainerInfo containerInfo, Size proposedConstraints int stealAmount = Math.Min(currentOverflow, totalPercentAllocatedSpace); - for (int i = 0; i < strips.Length; i++) { - if(i < styles.Count) { - TableLayoutStyle style = (TableLayoutStyle) styles[i]; - if (style.SizeType == SizeType.Percent) { - float percentageOfTotal = style.Size / (float) totalPercent; - strips[i].MinSize -= (int) (percentageOfTotal * stealAmount); + for (int i = 0; i < strips.Length; i++) + { + if (i < styles.Count) + { + TableLayoutStyle style = (TableLayoutStyle)styles[i]; + if (style.SizeType == SizeType.Percent) + { + float percentageOfTotal = style.Size / (float)totalPercent; + strips[i].MinSize -= (int)(percentageOfTotal * stealAmount); } } } - + return width - stealAmount; } return width; } - private int InflateRows(ContainerInfo containerInfo, Size proposedConstraints, int expandLastElementWidth, bool measureOnly) { + private int InflateRows(ContainerInfo containerInfo, Size proposedConstraints, int expandLastElementWidth, bool measureOnly) + { bool dontHonorConstraint = measureOnly; - + LayoutInfo[] sortedChildren = containerInfo.ChildrenInfo; - if (containerInfo.ChildHasRowSpan) { + if (containerInfo.ChildHasRowSpan) + { Sort(sortedChildren, RowSpanComparer.GetInstance); } @@ -808,38 +927,45 @@ private int InflateRows(ContainerInfo containerInfo, Size proposedConstraints, i // then we should honor the constraint. // The Int16.MaxValue check will tell us whether we are actually constrained or not. This is not ideal. - - if (dontHonorConstraint && (proposedConstraints.Height < short.MaxValue)) { + + if (dontHonorConstraint && (proposedConstraints.Height < short.MaxValue)) + { TableLayoutPanel tlp = containerInfo.Container as TableLayoutPanel; - if (tlp != null && tlp.ParentInternal != null && tlp.ParentInternal.LayoutEngine == DefaultLayout.Instance) { - if (tlp.Dock == DockStyle.Left || tlp.Dock == DockStyle.Right || tlp.Dock == DockStyle.Fill) { + if (tlp != null && tlp.ParentInternal != null && tlp.ParentInternal.LayoutEngine == DefaultLayout.Instance) + { + if (tlp.Dock == DockStyle.Left || tlp.Dock == DockStyle.Right || tlp.Dock == DockStyle.Fill) + { dontHonorConstraint = false; // we want to honor constraints } - - if ((tlp.Anchor & (AnchorStyles.Top | AnchorStyles.Bottom)) == (AnchorStyles.Top | AnchorStyles.Bottom)) { + + if ((tlp.Anchor & (AnchorStyles.Top | AnchorStyles.Bottom)) == (AnchorStyles.Top | AnchorStyles.Bottom)) + { dontHonorConstraint = false; // we want to honor constraints - } + } } - } + } - foreach(LayoutInfo layoutInfo in sortedChildren) { + foreach (LayoutInfo layoutInfo in sortedChildren) + { IArrangedElement element = layoutInfo.Element; int rowSpan = layoutInfo.RowSpan; // we can skip over absolute row styles, as they've been preallocated - if (rowSpan > 1 || !IsAbsolutelySized(layoutInfo.RowStart, containerInfo.RowStyles)) { - + if (rowSpan > 1 || !IsAbsolutelySized(layoutInfo.RowStart, containerInfo.RowStyles)) + { + int currentWidth = SumStrips(containerInfo.Columns, layoutInfo.ColumnStart, layoutInfo.ColumnSpan); //make sure that the total width is the actual final width to avoid //inconsistency of width between the ApplyStyles and SetElementBounds // Only apply when there is one multiple percentage column - if (!dontHonorConstraint && layoutInfo.ColumnStart + layoutInfo.ColumnSpan >= containerInfo.MaxColumns && !multiplePercent) { - currentWidth += expandLastElementWidth; + if (!dontHonorConstraint && layoutInfo.ColumnStart + layoutInfo.ColumnSpan >= containerInfo.MaxColumns && !multiplePercent) + { + currentWidth += expandLastElementWidth; } - + // since we know the width at this point, use that as the constraining width. Padding margin = CommonProperties.GetMargin(element); - int minHeight = GetElementSize(element, new Size(currentWidth-margin.Horizontal, 0)).Height + margin.Vertical; + int minHeight = GetElementSize(element, new Size(currentWidth - margin.Horizontal, 0)).Height + margin.Vertical; int maxHeight = minHeight; int rowStop = Math.Min(layoutInfo.RowStart + layoutInfo.RowSpan, containerInfo.Rows.Length); DistributeSize(containerInfo.RowStyles, containerInfo.Rows, layoutInfo.RowStart, rowStop, minHeight, maxHeight, containerInfo.CellBorderWidth); @@ -849,18 +975,24 @@ private int InflateRows(ContainerInfo containerInfo, Size proposedConstraints, i } - - private Size GetElementSize(IArrangedElement element, Size proposedConstraints) { - if(CommonProperties.GetAutoSize(element)) { + + private Size GetElementSize(IArrangedElement element, Size proposedConstraints) + { + if (CommonProperties.GetAutoSize(element)) + { return element.GetPreferredSize(proposedConstraints); - } else { + } + else + { return CommonProperties.GetSpecifiedBounds(element).Size; } } - internal int SumStrips(Strip[] strips, int start, int span) { + internal int SumStrips(Strip[] strips, int start, int span) + { int size = 0; - for(int i = start; i < Math.Min(start + span, strips.Length); i++) { + for (int i = start; i < Math.Min(start + span, strips.Length); i++) + { Strip strip = strips[i]; size += strip.MinSize; } @@ -876,62 +1008,73 @@ private void DistributeSize(IList styles, Strip[] strips, int start, int stop, i xDistributeSize(styles, strips, start, stop, max, MaxSizeProxy.GetInstance, cellBorderWidth); } - private void xDistributeSize(IList styles, Strip[] strips, int start, int stop, int desiredLength, SizeProxy sizeProxy, int cellBorderWidth) { + private void xDistributeSize(IList styles, Strip[] strips, int start, int stop, int desiredLength, SizeProxy sizeProxy, int cellBorderWidth) + { int currentLength = 0; //total length allocated so far int numUninitializedStrips = 0; //number of strips whose Size is 0 and is not absolutely positioned - + //subtract the space for cell borders. Notice if a control spans two columns its //proposed size is 10 and the border width is 3, we actually only need to distribute //7 pixels among the two cells it spans desiredLength -= cellBorderWidth * (stop - start - 1); desiredLength = Math.Max(0, desiredLength); - - for(int i = start; i < stop; i++) { + + for (int i = start; i < stop; i++) + { sizeProxy.Strip = strips[i]; - if (!IsAbsolutelySized(i, styles) && sizeProxy.Size == 0) { + if (!IsAbsolutelySized(i, styles) && sizeProxy.Size == 0) + { //the strip is not absolutely sized and it hasn't been initialized numUninitializedStrips++; } - currentLength += sizeProxy.Size; + currentLength += sizeProxy.Size; } int missingLength = desiredLength - currentLength; - - if (missingLength <= 0) { + + if (missingLength <= 0) + { //no extra space left. Simply return. return; } - if (numUninitializedStrips == 0) { + if (numUninitializedStrips == 0) + { //look for any strip whose style is percent. If there is one, dump all space in it int lastPercent; - for (lastPercent = stop - 1; lastPercent >= start; lastPercent--) { - if (lastPercent < styles.Count && ((TableLayoutStyle) styles[lastPercent]).SizeType == SizeType.Percent) { + for (lastPercent = stop - 1; lastPercent >= start; lastPercent--) + { + if (lastPercent < styles.Count && ((TableLayoutStyle)styles[lastPercent]).SizeType == SizeType.Percent) + { break; } } //we have found one strip whose style is percent. //make sure that the for loop below only looks at this strip - if (lastPercent != start - 1) { - stop = lastPercent + 1; + if (lastPercent != start - 1) + { + stop = lastPercent + 1; } //every strip has absolute width or all of them have already been allocated space //walk backwards - for (int i = stop - 1; i >= start; i--) { - if (!IsAbsolutelySized(i, styles)) { + for (int i = stop - 1; i >= start; i--) + { + if (!IsAbsolutelySized(i, styles)) + { //dump the extra space to this strip - sizeProxy.Strip = strips[i]; - + sizeProxy.Strip = strips[i]; + if (!(i == strips.Length - 1) //this is not the last strip - && !strips[i+1].IsStart //and there is no control starting from the strip next to it - && !IsAbsolutelySized(i+1, styles)) { // and the strip next to it is not absolutely sized + && !strips[i + 1].IsStart //and there is no control starting from the strip next to it + && !IsAbsolutelySized(i + 1, styles)) + { // and the strip next to it is not absolutely sized //try to "borrow" space from the strip next to it - sizeProxy.Strip = strips[i+1]; + sizeProxy.Strip = strips[i + 1]; int offset = Math.Min(sizeProxy.Size, missingLength); sizeProxy.Size -= offset; - strips[i+1] = sizeProxy.Strip; + strips[i + 1] = sizeProxy.Strip; - sizeProxy.Strip = strips[i]; + sizeProxy.Strip = strips[i]; } //put whatever left into this strip sizeProxy.Size += missingLength; @@ -942,17 +1085,21 @@ private void xDistributeSize(IList styles, Strip[] strips, int start, int stop, //if we fall through here, everything is absolutely positioned. discard the extra space } //there are some uninitialized strips - else { + else + { //average space to be distributed int average = missingLength / numUninitializedStrips; //total number of uninitialized strips encountered so far int uninitializedStripIndex = 0; - for (int i = start; i < stop; i++) { + for (int i = start; i < stop; i++) + { sizeProxy.Strip = strips[i]; //this is an uninitialized strip - if (!IsAbsolutelySized(i, styles) && sizeProxy.Size == 0) { + if (!IsAbsolutelySized(i, styles) && sizeProxy.Size == 0) + { uninitializedStripIndex++; - if (uninitializedStripIndex == numUninitializedStrips) { + if (uninitializedStripIndex == numUninitializedStrips) + { //we are at the last strip. place round off error here average = missingLength - average * (numUninitializedStrips - 1); } @@ -960,11 +1107,12 @@ private void xDistributeSize(IList styles, Strip[] strips, int start, int stop, strips[i] = sizeProxy.Strip; } } - } + } } //determines whether strip[index]'s style is absolutely sized - private bool IsAbsolutelySized(int index, IList styles) { + private bool IsAbsolutelySized(int index, IList styles) + { return (index < styles.Count) && ((TableLayoutStyle)styles[index]).SizeType == SizeType.Absolute; } @@ -972,7 +1120,8 @@ private bool IsAbsolutelySized(int index, IList styles) { /// Now that we've allocated minimum and maximum sizes to everyone (the strips), distribute the extra space /// as according to the Row/Column styles. /// - private int DistributeStyles(int cellBorderWidth, IList styles, Strip[] strips, int maxSize, bool dontHonorConstraint) { + private int DistributeStyles(int cellBorderWidth, IList styles, Strip[] strips, int maxSize, bool dontHonorConstraint) + { int usedSpace = 0; //first, allocate the minimum space required for each element @@ -987,11 +1136,14 @@ private int DistributeStyles(int cellBorderWidth, IList styles, Strip[] strips, // - for percent size columns // - sum up the total "%"s being used // - eg totalPercent = 22 + 22 + 22 = 66%. each column should take up 1/3 of the remaining space. - for(int i = 0; i < strips.Length; i++) { + for (int i = 0; i < strips.Length; i++) + { Strip strip = strips[i]; - if(i < styles.Count) { - TableLayoutStyle style = (TableLayoutStyle) styles[i]; - switch(style.SizeType) { + if (i < styles.Count) + { + TableLayoutStyle style = (TableLayoutStyle)styles[i]; + switch (style.SizeType) + { case SizeType.Absolute: totalAbsoluteAndAutoSizeAllocatedSpace += strip.MinSize; // We gaurantee a strip will be exactly abs pixels @@ -1007,8 +1159,9 @@ private int DistributeStyles(int cellBorderWidth, IList styles, Strip[] strips, break; } } - else { - hasAutoSizeColumn = true; + else + { + hasAutoSizeColumn = true; } strip.MaxSize += cellBorderWidth; strip.MinSize += cellBorderWidth; //add the padding for the cell border @@ -1018,19 +1171,22 @@ private int DistributeStyles(int cellBorderWidth, IList styles, Strip[] strips, } int remainingSpace = maxSize - usedSpace; - - + + // Step 2: (ONLY if we have % style column) // - distribute unused space for absolute/autosize columns to percentage columns // - determine the extra space that is not being used for autosize and fixed columns // - divide space amongst % style columns using ratio of %/total % * total extra space - if (totalPercent > 0) { - - - if (!dontHonorConstraint) { - - if (totalPercentAllocatedSpace > maxSize - totalAbsoluteAndAutoSizeAllocatedSpace) { + if (totalPercent > 0) + { + + + if (!dontHonorConstraint) + { + + if (totalPercentAllocatedSpace > maxSize - totalAbsoluteAndAutoSizeAllocatedSpace) + { // fixup for the case where we've actually allocated more space than we have. // this can happen when the sum of the widths/heights of the controls are larger than the size of the // table (aka maxSize) @@ -1039,24 +1195,28 @@ private int DistributeStyles(int cellBorderWidth, IList styles, Strip[] strips, totalPercentAllocatedSpace = Math.Max(0, maxSize - totalAbsoluteAndAutoSizeAllocatedSpace); } - if (remainingSpace > 0) { + if (remainingSpace > 0) + { // If there's space left over, then give it to the percentage columns/rows totalPercentAllocatedSpace += remainingSpace; } - - else if (remainingSpace < 0) { + + else if (remainingSpace < 0) + { // If there's not enough space, then remove space from the percentage columns. // We do this by recalculating the space available. totalPercentAllocatedSpace = maxSize - totalAbsoluteAndAutoSizeAllocatedSpace - (strips.Length * cellBorderWidth); remainingSpace = 0; } - - + + // in this case the strips fill up the remaining space. - for (int i = 0; i < strips.Length; i++) { + for (int i = 0; i < strips.Length; i++) + { Strip strip = strips[i]; SizeType sizeType = i < styles.Count ? ((TableLayoutStyle)styles[i]).SizeType : SizeType.AutoSize; - if (sizeType == SizeType.Percent) { + if (sizeType == SizeType.Percent) + { TableLayoutStyle style = (TableLayoutStyle)styles[i]; // cast to int / (take the floor) so we know we dont accidentally go over our limit. @@ -1070,16 +1230,18 @@ private int DistributeStyles(int cellBorderWidth, IList styles, Strip[] strips, } } - else { + else + { // the size of the item defines the size allocated to the percentage style columns. // this supports [Ok][Cancel] in a 50% 50% column arrangement. When one grows it pushes the whole table // larger. int maxPercentWidth = 0; - for (int i = 0; i < strips.Length; i++) { - Strip strip = strips[i]; + for (int i = 0; i < strips.Length; i++) + { + Strip strip = strips[i]; SizeType sizeType = i < styles.Count ? ((TableLayoutStyle)styles[i]).SizeType : SizeType.AutoSize; - - + + // Performing the inverse calculation for GetPreferredSize: // // stylePercent * totalWidth colWidth * totalPercent @@ -1087,17 +1249,18 @@ private int DistributeStyles(int cellBorderWidth, IList styles, Strip[] strips, // totalPercent stylePercent // // we'll take the max of the total widths as the one for our preferred size. - if (sizeType == SizeType.Percent) { + if (sizeType == SizeType.Percent) + { TableLayoutStyle style = (TableLayoutStyle)styles[i]; - int totalWidth = (int)Math.Round(((strip.MinSize * totalPercent)/ style.Size)); + int totalWidth = (int)Math.Round(((strip.MinSize * totalPercent) / style.Size)); maxPercentWidth = Math.Max(maxPercentWidth, totalWidth); usedSpace -= strip.MinSize; } } usedSpace += maxPercentWidth; } - + } remainingSpace = maxSize - usedSpace; @@ -1107,14 +1270,18 @@ private int DistributeStyles(int cellBorderWidth, IList styles, Strip[] strips, // Step 3: add remaining space to autosize columns // - usually we only do this if we're not in preferred size (remaingSpace would be < 0) // - and there are no % style columns - - if(hasAutoSizeColumn && remainingSpace > 0) { - for(int i = 0; i < strips.Length; i++) { + + if (hasAutoSizeColumn && remainingSpace > 0) + { + for (int i = 0; i < strips.Length; i++) + { Strip strip = strips[i]; SizeType sizeType = i < styles.Count ? ((TableLayoutStyle)styles[i]).SizeType : SizeType.AutoSize; - if (sizeType == SizeType.AutoSize) { + if (sizeType == SizeType.AutoSize) + { int delta = Math.Min(strip.MaxSize - strip.MinSize, remainingSpace); - if(delta > 0) { + if (delta > 0) + { usedSpace += delta; remainingSpace -= delta; strip.MinSize += delta; @@ -1127,35 +1294,40 @@ private int DistributeStyles(int cellBorderWidth, IList styles, Strip[] strips, return usedSpace; } - private void SetElementBounds(ContainerInfo containerInfo, RectangleF displayRectF) { + private void SetElementBounds(ContainerInfo containerInfo, RectangleF displayRectF) + { int cellBorderWidth = containerInfo.CellBorderWidth; - + float top = displayRectF.Y; int currentCol = 0; int currentRow = 0; bool isContainerRTL = false; Rectangle displayRect = Rectangle.Truncate(displayRectF); - if (containerInfo.Container is Control) { - Control control = containerInfo.Container as Control; + if (containerInfo.Container is Control) + { + Control control = containerInfo.Container as Control; isContainerRTL = control.RightToLeft == RightToLeft.Yes; } LayoutInfo[] childrenInfo = containerInfo.ChildrenInfo; float startX = isContainerRTL ? displayRectF.Right : displayRectF.X; - + //sort everything according to row major, column minor order //so that we can ensure that as we walk through all elements //the cursor always goes from left to right and from top to bottom. - Sort(childrenInfo,PostAssignedPositionComparer.GetInstance); - for (int i = 0; i < childrenInfo.Length; i++) { + Sort(childrenInfo, PostAssignedPositionComparer.GetInstance); + for (int i = 0; i < childrenInfo.Length; i++) + { LayoutInfo layoutInfo = (LayoutInfo)childrenInfo[i]; IArrangedElement element = layoutInfo.Element; // Advance top to the beginning of this elements row. Debug.Assert(currentRow <= layoutInfo.RowStart, "RowStart should increase in forward Z-order."); - if(currentRow != layoutInfo.RowStart) { - for(; currentRow < layoutInfo.RowStart; currentRow++) { + if (currentRow != layoutInfo.RowStart) + { + for (; currentRow < layoutInfo.RowStart; currentRow++) + { top += containerInfo.Rows[currentRow].MinSize; } startX = isContainerRTL ? displayRectF.Right : displayRectF.X; @@ -1164,11 +1336,14 @@ private void SetElementBounds(ContainerInfo containerInfo, RectangleF displayRec // Advance left to the beginning of this elements column. Debug.Assert(currentCol <= layoutInfo.ColumnStart, "ColumnStart should increase in forward Z-order."); - for(; currentCol < layoutInfo.ColumnStart; currentCol++) { - if (isContainerRTL) { + for (; currentCol < layoutInfo.ColumnStart; currentCol++) + { + if (isContainerRTL) + { startX -= containerInfo.Columns[currentCol].MinSize; } - else { + else + { startX += containerInfo.Columns[currentCol].MinSize; } } @@ -1177,19 +1352,22 @@ private void SetElementBounds(ContainerInfo containerInfo, RectangleF displayRec // do this. int colStop = currentCol + layoutInfo.ColumnSpan; int width = 0; - for(;currentCol < colStop && currentCol < containerInfo.Columns.Length; currentCol++) { + for (; currentCol < colStop && currentCol < containerInfo.Columns.Length; currentCol++) + { width += containerInfo.Columns[currentCol].MinSize; } - if (isContainerRTL) { + if (isContainerRTL) + { startX -= width; } - + // Sum the total height of the span. We do not increment RowSpan // as we do this because there may be more elements on this row. int rowStop = currentRow + layoutInfo.RowSpan; int height = 0; - for(int rowIndex = currentRow; rowIndex < rowStop && rowIndex < containerInfo.Rows.Length; rowIndex++) { + for (int rowIndex = currentRow; rowIndex < rowStop && rowIndex < containerInfo.Rows.Length; rowIndex++) + { height += containerInfo.Rows[rowIndex].MinSize; } @@ -1198,33 +1376,36 @@ private void SetElementBounds(ContainerInfo containerInfo, RectangleF displayRec // We laid out the rows and columns with the element's margins included. // We now deflate the rect to get the actual element bounds. Padding elementMargin = CommonProperties.GetMargin(element); - if (isContainerRTL) { + if (isContainerRTL) + { int temp = elementMargin.Right; elementMargin.Right = elementMargin.Left; elementMargin.Left = temp; } - + cellBounds = LayoutUtils.DeflateRect(cellBounds, elementMargin); //make sure our sizes are non-negative cellBounds.Width = Math.Max(cellBounds.Width, 1); - cellBounds.Height = Math.Max(cellBounds.Height , 1); + cellBounds.Height = Math.Max(cellBounds.Height, 1); AnchorStyles anchorStyles = LayoutUtils.GetUnifiedAnchor(element); - + Rectangle elementBounds = LayoutUtils.AlignAndStretch(GetElementSize(element, cellBounds.Size), cellBounds, anchorStyles); // If the element was not BoxStretch.Both, AlignAndStretch does not gaurantee // that the element has been clipped to the cell bounds. elementBounds.Width = Math.Min(cellBounds.Width, elementBounds.Width); - elementBounds.Height = Math.Min(cellBounds.Height, elementBounds.Height); + elementBounds.Height = Math.Min(cellBounds.Height, elementBounds.Height); - if (isContainerRTL) { + if (isContainerRTL) + { elementBounds.X = cellBounds.X + (cellBounds.Right - elementBounds.Right); } element.SetBounds(elementBounds, BoundsSpecified.None); - if (!isContainerRTL) { + if (!isContainerRTL) + { startX += width; } } @@ -1232,71 +1413,85 @@ private void SetElementBounds(ContainerInfo containerInfo, RectangleF displayRec Debug_VerifyNoOverlapping(containerInfo.Container); } - internal IArrangedElement GetControlFromPosition (IArrangedElement container, int column, int row) { - if (row < 0) { + internal IArrangedElement GetControlFromPosition(IArrangedElement container, int column, int row) + { + if (row < 0) + { throw new ArgumentOutOfRangeException(nameof(row), row, string.Format(SR.InvalidArgument, "RowPosition", row)); } - if (column < 0) { + if (column < 0) + { throw new ArgumentOutOfRangeException(nameof(column), column, string.Format(SR.InvalidArgument, "ColumnPosition", column)); } ArrangedElementCollection children = container.Children; ContainerInfo containerInfo = GetContainerInfo(container); - - if (children == null || children.Count == 0) { + + if (children == null || children.Count == 0) + { //nothing in the container. returns null. return null; } - if (!containerInfo.Valid) { + if (!containerInfo.Valid) + { //hasn't performed layout yet. assign rows and columns first EnsureRowAndColumnAssignments(container, containerInfo, /* doNotCache = */ true); } - for (int i = 0; i < children.Count; i++) { + for (int i = 0; i < children.Count; i++) + { LayoutInfo layoutInfo = GetLayoutInfo(children[i]); //the row and column specified is within the region enclosed by the element. if (layoutInfo.ColumnStart <= column && (layoutInfo.ColumnStart + layoutInfo.ColumnSpan - 1) >= column && - layoutInfo.RowStart <= row && (layoutInfo.RowStart + layoutInfo.RowSpan - 1) >= row) { + layoutInfo.RowStart <= row && (layoutInfo.RowStart + layoutInfo.RowSpan - 1) >= row) + { return layoutInfo.Element; } } return null; } - internal TableLayoutPanelCellPosition GetPositionFromControl(IArrangedElement container, IArrangedElement child) { - if (container == null || child == null) { - return new TableLayoutPanelCellPosition(-1,-1); + internal TableLayoutPanelCellPosition GetPositionFromControl(IArrangedElement container, IArrangedElement child) + { + if (container == null || child == null) + { + return new TableLayoutPanelCellPosition(-1, -1); } ArrangedElementCollection children = container.Children; ContainerInfo containerInfo = GetContainerInfo(container); - if (children == null || children.Count == 0) { + if (children == null || children.Count == 0) + { //nothing in the container. returns null. - return new TableLayoutPanelCellPosition(-1,-1); + return new TableLayoutPanelCellPosition(-1, -1); } - if (!containerInfo.Valid) { + if (!containerInfo.Valid) + { //hasn't performed layout yet. assign rows and columns first EnsureRowAndColumnAssignments(container, containerInfo, /* doNotCache = */ true); } LayoutInfo layoutInfo = GetLayoutInfo(child); return new TableLayoutPanelCellPosition(layoutInfo.ColumnStart, layoutInfo.RowStart); - + } #region LayoutInfo - internal static LayoutInfo GetLayoutInfo(IArrangedElement element) { + internal static LayoutInfo GetLayoutInfo(IArrangedElement element) + { LayoutInfo layoutInfo = (LayoutInfo)element.Properties.GetObject(_layoutInfoProperty); - if(layoutInfo == null) { + if (layoutInfo == null) + { layoutInfo = new LayoutInfo(element); SetLayoutInfo(element, layoutInfo); } return layoutInfo; } - - internal static void SetLayoutInfo(IArrangedElement element, LayoutInfo value) { + + internal static void SetLayoutInfo(IArrangedElement element, LayoutInfo value) + { element.Properties.SetObject(_layoutInfoProperty, value); Debug.Assert(GetLayoutInfo(element) == value, "GetLayoutInfo should return the same value as we set it to"); - } + } /// @@ -1306,7 +1501,8 @@ internal static void SetLayoutInfo(IArrangedElement element, LayoutInfo value) { /// This class is used from ContainerInfo as a way of caching information /// about child controls. /// - internal sealed class LayoutInfo { + internal sealed class LayoutInfo + { //the actual row and column position of this control private int _rowStart = -1; //if change the default value, change the code in GetControlFromPosition also private int _columnStart = -1; @@ -1315,19 +1511,22 @@ internal sealed class LayoutInfo { //the row and column specified by the user. Only set when the element is absolutely positioned private int _rowPos = -1; private int _colPos = -1; - + //the element which owns this layoutInfo - private IArrangedElement _element; + private IArrangedElement _element; - public LayoutInfo(IArrangedElement element) { + public LayoutInfo(IArrangedElement element) + { _element = element; } - internal bool IsAbsolutelyPositioned { + internal bool IsAbsolutelyPositioned + { get { return _rowPos >= 0 && _colPos >= 0; } } - internal IArrangedElement Element { + internal IArrangedElement Element + { get { return _element; } } @@ -1335,11 +1534,13 @@ internal IArrangedElement Element { ///Can be -1 indicating that it is a "flow" element and ///will fit in as necessary. This occurs when a control ///is just added without specific position. - internal int RowPosition { + internal int RowPosition + { get { return _rowPos; } - set { + set + { // all validation should occur in TableLayoutSettings. - _rowPos = value; + _rowPos = value; } } @@ -1348,40 +1549,49 @@ internal int RowPosition { ///Can be -1 indicating that it is a "flow" element and ///will fit in as necessary. This occurs when a control ///is just added without specific position. - internal int ColumnPosition { - get { return _colPos;} - set { + internal int ColumnPosition + { + get { return _colPos; } + set + { // all validation should occur in TableLayoutSettings. - _colPos = value; - } + _colPos = value; + } } - - internal int RowStart { + + internal int RowStart + { get { return _rowStart; } set { _rowStart = value; } } - internal int ColumnStart { + internal int ColumnStart + { get { return _columnStart; } set { _columnStart = value; } } - internal int ColumnSpan { + internal int ColumnSpan + { get { return _columnSpan; } - set { + set + { _columnSpan = value; } } - internal int RowSpan { + internal int RowSpan + { get { return _rowSpan; } - set { + set + { _rowSpan = value; } } #if DEBUG - public LayoutInfo Clone() { + public LayoutInfo Clone() + { LayoutInfo clone = new LayoutInfo(_element); clone.RowStart = RowStart; clone.ColumnStart = ColumnStart; @@ -1392,9 +1602,11 @@ public LayoutInfo Clone() { return clone; } - public override bool Equals(object obj) { + public override bool Equals(object obj) + { LayoutInfo other = obj as LayoutInfo; - if(other == null) return false; + if (other == null) + return false; return other.RowStart == RowStart && other.ColumnStart == ColumnStart @@ -1411,20 +1623,24 @@ public override bool Equals(object obj) { #endregion #region ContainerInfo - internal static bool HasCachedAssignments(ContainerInfo containerInfo){ + internal static bool HasCachedAssignments(ContainerInfo containerInfo) + { return containerInfo.Valid; } - internal static void ClearCachedAssignments(ContainerInfo containerInfo) { + internal static void ClearCachedAssignments(ContainerInfo containerInfo) + { containerInfo.Valid = false; } //we make sure that our conatinerInfo never returns null. If there is no //existing containerInfo, instantiate a new one and store it in the property //store. - internal static ContainerInfo GetContainerInfo(IArrangedElement container) { - ContainerInfo containerInfo = (ContainerInfo) container.Properties.GetObject(_containerInfoProperty); - if (containerInfo == null) { + internal static ContainerInfo GetContainerInfo(IArrangedElement container) + { + ContainerInfo containerInfo = (ContainerInfo)container.Properties.GetObject(_containerInfoProperty); + if (containerInfo == null) + { containerInfo = new ContainerInfo(container); container.Properties.SetObject(_containerInfoProperty, containerInfo); } @@ -1439,14 +1655,15 @@ internal static ContainerInfo GetContainerInfo(IArrangedElement container) { /// as this class is responsible for caching information about the control and /// it's children being layed out. /// - internal sealed class ContainerInfo { + internal sealed class ContainerInfo + { private static Strip[] emptyStrip = new Strip[0]; - private static readonly int stateValid = BitVector32.CreateMask(); - private static readonly int stateChildInfoValid = BitVector32.CreateMask(stateValid); + private static readonly int stateValid = BitVector32.CreateMask(); + private static readonly int stateChildInfoValid = BitVector32.CreateMask(stateValid); private static readonly int stateChildHasColumnSpan = BitVector32.CreateMask(stateChildInfoValid); - private static readonly int stateChildHasRowSpan = BitVector32.CreateMask(stateChildHasColumnSpan); - + private static readonly int stateChildHasRowSpan = BitVector32.CreateMask(stateChildHasColumnSpan); + private int _cellBorderWidth; //the width for the cell border private Strip[] _cols = emptyStrip; private Strip[] _rows = emptyStrip; @@ -1457,20 +1674,22 @@ internal sealed class ContainerInfo { private TableLayoutPanelGrowStyle _growStyle; private IArrangedElement _container; private LayoutInfo[] _childInfo; - private int _countFixedChildren; + private int _countFixedChildren; private int _minRowsAndColumns; // The minimum space required to put all the controls without overlapping private int _minColumns; // The minimum number of columns required in order to put all absolutely positioned control on the table private int _minRows; // The minimum number of rows required in order to put all absolutely positioned control on the table - + private BitVector32 _state = new BitVector32(); - - - public ContainerInfo(IArrangedElement container) { + + + public ContainerInfo(IArrangedElement container) + { _container = container; _growStyle = TableLayoutPanelGrowStyle.AddRows; } - public ContainerInfo(ContainerInfo containerInfo) { + public ContainerInfo(ContainerInfo containerInfo) + { _cellBorderWidth = containerInfo.CellBorderWidth; _maxRows = containerInfo.MaxRows; _maxColumns = containerInfo.MaxColumns; @@ -1485,7 +1704,8 @@ public ContainerInfo(ContainerInfo containerInfo) { /// /// the container being laid out /// - public IArrangedElement Container { + public IArrangedElement Container + { get { return _container; } } @@ -1495,8 +1715,9 @@ public bool IsRowDefined { get { return (_maxRows != 0 && _maxColumns == 0); } } */ - - public int CellBorderWidth { + + public int CellBorderWidth + { get { return _cellBorderWidth; } set { _cellBorderWidth = value; } } @@ -1505,9 +1726,11 @@ public int CellBorderWidth { /// /// list of ints that represent the sizes of individual columns /// - public Strip[] Columns { + public Strip[] Columns + { get { return _cols; } - set { + set + { Debug.Assert(_cols.Length != value.Length, "PERF: should not allocate strips, we've already got an array"); _cols = value; } @@ -1516,12 +1739,14 @@ public Strip[] Columns { /// /// list of ints that represent the sizes of individual rows /// - public Strip[] Rows { + public Strip[] Rows + { get { return _rows; } - set { + set + { Debug.Assert(_rows.Length != value.Length, "PERF: should not allocate strips, we've already got an array"); - _rows = value; + _rows = value; } @@ -1530,29 +1755,35 @@ public Strip[] Rows { /// /// Same as TableLayoutSettings.RowCount /// - public int MaxRows { + public int MaxRows + { get { return _maxRows; } - set { - if (_maxRows != value) { + set + { + if (_maxRows != value) + { _maxRows = value; //invalidate the cache whenever we change the number of rows - Valid = false; + Valid = false; } - - } + + } } /// /// Same as TableLayoutSettings.ColumnCount /// - public int MaxColumns { - + public int MaxColumns + { + get { return _maxColumns; } - set { - if (_maxColumns != value) { + set + { + if (_maxColumns != value) + { _maxColumns = value; //invalidate the cache whenever we change the number of columns @@ -1563,28 +1794,34 @@ public int MaxColumns { /// Cached information - public int MinRowsAndColumns { - get { + public int MinRowsAndColumns + { + get + { Debug.Assert(ChildInfoValid, "Fetching invalid information"); - return _minRowsAndColumns; + return _minRowsAndColumns; } } /// Cached information - public int MinColumns { - get { + public int MinColumns + { + get + { Debug.Assert(ChildInfoValid, "Fetching invalid information"); - return _minColumns; + return _minColumns; } } /// Cached information - public int MinRows { - get { + public int MinRows + { + get + { Debug.Assert(ChildInfoValid, "Fetching invalid information"); - return _minRows; + return _minRows; } } @@ -1594,46 +1831,60 @@ public int MinRows { /// is used to determine if we will add rows/cols/or throw /// when the table gets full. /// - public TableLayoutPanelGrowStyle GrowStyle { - get { + public TableLayoutPanelGrowStyle GrowStyle + { + get + { return _growStyle; } - set { - if (_growStyle != value) { + set + { + if (_growStyle != value) + { _growStyle = value; Valid = false; // throw away cached row and column assignments } } } - public TableLayoutRowStyleCollection RowStyles { - get { - if (_rowStyles == null) { + public TableLayoutRowStyleCollection RowStyles + { + get + { + if (_rowStyles == null) + { _rowStyles = new TableLayoutRowStyleCollection(_container); } return _rowStyles; - - } - set { + + } + set + { _rowStyles = value; - if (_rowStyles != null) { - _rowStyles.EnsureOwnership(_container); + if (_rowStyles != null) + { + _rowStyles.EnsureOwnership(_container); } } } - public TableLayoutColumnStyleCollection ColumnStyles { - get { - if (_colStyles == null) { + public TableLayoutColumnStyleCollection ColumnStyles + { + get + { + if (_colStyles == null) + { _colStyles = new TableLayoutColumnStyleCollection(_container); } return _colStyles; - } - set { + } + set + { _colStyles = value; - if (_colStyles != null) { - _colStyles.EnsureOwnership(_container); + if (_colStyles != null) + { + _colStyles.EnsureOwnership(_container); } } } @@ -1642,49 +1893,58 @@ public TableLayoutColumnStyleCollection ColumnStyles { /// /// gets cached information about the children of the control being layed out. /// - public LayoutInfo[] ChildrenInfo { - get { - if (!_state[stateChildInfoValid]) { + public LayoutInfo[] ChildrenInfo + { + get + { + if (!_state[stateChildInfoValid]) + { _countFixedChildren = 0; - - _minRowsAndColumns = 0; - _minColumns = 0; + + _minRowsAndColumns = 0; + _minColumns = 0; _minRows = 0; ArrangedElementCollection children = Container.Children; LayoutInfo[] childInfo = new LayoutInfo[children.Count]; - int nonParticipatingElements = 0; + int nonParticipatingElements = 0; int index = 0; - for (int i = 0; i < children.Count; i++) { - IArrangedElement element = children[i]; - if (!element.ParticipatesInLayout) { - // If the element does not participate in layout (i.e., Visible = false), we - // exclude it from the childrenInfos list and it is ignored by the engine. - nonParticipatingElements++; - continue; - } - - LayoutInfo layoutInfo = GetLayoutInfo(element); - if (layoutInfo.IsAbsolutelyPositioned) { + for (int i = 0; i < children.Count; i++) + { + IArrangedElement element = children[i]; + if (!element.ParticipatesInLayout) + { + // If the element does not participate in layout (i.e., Visible = false), we + // exclude it from the childrenInfos list and it is ignored by the engine. + nonParticipatingElements++; + continue; + } + + LayoutInfo layoutInfo = GetLayoutInfo(element); + if (layoutInfo.IsAbsolutelyPositioned) + { _countFixedChildren++; - - } - childInfo[index++] = layoutInfo; - _minRowsAndColumns += layoutInfo.RowSpan * layoutInfo.ColumnSpan; - if (layoutInfo.IsAbsolutelyPositioned) { - _minColumns = Math.Max(_minColumns, layoutInfo.ColumnPosition + layoutInfo.ColumnSpan); - _minRows = Math.Max(_minRows, layoutInfo.RowPosition + layoutInfo.RowSpan); - } - + + } + childInfo[index++] = layoutInfo; + _minRowsAndColumns += layoutInfo.RowSpan * layoutInfo.ColumnSpan; + if (layoutInfo.IsAbsolutelyPositioned) + { + _minColumns = Math.Max(_minColumns, layoutInfo.ColumnPosition + layoutInfo.ColumnSpan); + _minRows = Math.Max(_minRows, layoutInfo.RowPosition + layoutInfo.RowSpan); + } + } - + // shorten the array if necessary. - if (nonParticipatingElements > 0) { - LayoutInfo[] trimmedChildInfo = new LayoutInfo[childInfo.Length - nonParticipatingElements]; - Array.Copy(childInfo, trimmedChildInfo, trimmedChildInfo.Length); - _childInfo = trimmedChildInfo; + if (nonParticipatingElements > 0) + { + LayoutInfo[] trimmedChildInfo = new LayoutInfo[childInfo.Length - nonParticipatingElements]; + Array.Copy(childInfo, trimmedChildInfo, trimmedChildInfo.Length); + _childInfo = trimmedChildInfo; } - else { - _childInfo = childInfo; + else + { + _childInfo = childInfo; } _state[stateChildInfoValid] = true; } @@ -1692,73 +1952,95 @@ public LayoutInfo[] ChildrenInfo { } } - public bool ChildInfoValid { + public bool ChildInfoValid + { get { return _state[stateChildInfoValid]; } } - public LayoutInfo[] FixedChildrenInfo { - get { - Debug.Assert(ChildInfoValid, "Fetched invalid information"); - // we only get this in a cached scenario - so we dont have to worry about caching it. - LayoutInfo[] fixedChildren = new LayoutInfo[_countFixedChildren]; - if (HasChildWithAbsolutePositioning) { - int index = 0; - for (int i = 0; i < _childInfo.Length; i++) { - if (_childInfo[i].IsAbsolutelyPositioned) { - fixedChildren[index++] = _childInfo[i]; - } - } - Sort(fixedChildren, PreAssignedPositionComparer.GetInstance); - } - return fixedChildren; - } - } - public bool Valid { + public LayoutInfo[] FixedChildrenInfo + { + get + { + Debug.Assert(ChildInfoValid, "Fetched invalid information"); + // we only get this in a cached scenario - so we dont have to worry about caching it. + LayoutInfo[] fixedChildren = new LayoutInfo[_countFixedChildren]; + if (HasChildWithAbsolutePositioning) + { + int index = 0; + for (int i = 0; i < _childInfo.Length; i++) + { + if (_childInfo[i].IsAbsolutelyPositioned) + { + fixedChildren[index++] = _childInfo[i]; + } + } + Sort(fixedChildren, PreAssignedPositionComparer.GetInstance); + } + return fixedChildren; + } + } + public bool Valid + { get { return _state[stateValid]; } - set { _state[stateValid] = value; - if (!_state[stateValid]) { + set + { + _state[stateValid] = value; + if (!_state[stateValid]) + { _state[stateChildInfoValid] = false; } } - } + } - public bool HasChildWithAbsolutePositioning { + public bool HasChildWithAbsolutePositioning + { get { return _countFixedChildren > 0; } } - public bool HasMultiplePercentColumns { - get { - if (_colStyles != null) { + public bool HasMultiplePercentColumns + { + get + { + if (_colStyles != null) + { bool foundAny = false; - foreach (ColumnStyle style in _colStyles) { - if (style.SizeType == SizeType.Percent) { - if (foundAny) { + foreach (ColumnStyle style in _colStyles) + { + if (style.SizeType == SizeType.Percent) + { + if (foundAny) + { return true; } foundAny = true; - } + } } } return false; } } - - public bool ChildHasColumnSpan { + + public bool ChildHasColumnSpan + { get { return _state[stateChildHasColumnSpan]; } set { _state[stateChildHasColumnSpan] = value; } } - public bool ChildHasRowSpan { + public bool ChildHasRowSpan + { get { return _state[stateChildHasRowSpan]; } set { _state[stateChildHasRowSpan] = value; } } - public Size GetCachedPreferredSize(Size proposedContstraints, out bool isValid) { + public Size GetCachedPreferredSize(Size proposedContstraints, out bool isValid) + { isValid = false; - if (proposedContstraints.Height == 0 || proposedContstraints.Width == 0) { + if (proposedContstraints.Height == 0 || proposedContstraints.Width == 0) + { Size cachedSize = CommonProperties.xGetPreferredSizeCache(Container); - - if(!cachedSize.IsEmpty) { + + if (!cachedSize.IsEmpty) + { isValid = true; return cachedSize; } @@ -1766,134 +2048,167 @@ public Size GetCachedPreferredSize(Size proposedContstraints, out bool isValid) return Size.Empty; } - + } #endregion #region SizeProxy implementations //sizeProxy. Takes a strip and return its minSize or maxSize accordingly - private abstract class SizeProxy { + private abstract class SizeProxy + { protected Strip strip; - public Strip Strip { + public Strip Strip + { get { return strip; } set { strip = value; } } - public abstract int Size { - get; set; + public abstract int Size + { + get; set; } } - private class MinSizeProxy : SizeProxy { + private class MinSizeProxy : SizeProxy + { private static readonly MinSizeProxy instance = new MinSizeProxy(); - public override int Size { + public override int Size + { get { return strip.MinSize; } set { strip.MinSize = value; } } - - public static MinSizeProxy GetInstance { - get { + + public static MinSizeProxy GetInstance + { + get + { return instance; } } } - private class MaxSizeProxy : SizeProxy { + private class MaxSizeProxy : SizeProxy + { private static readonly MaxSizeProxy instance = new MaxSizeProxy(); - public override int Size { + public override int Size + { get { return strip.MaxSize; } set { strip.MaxSize = value; } } - public static MaxSizeProxy GetInstance { - get { + public static MaxSizeProxy GetInstance + { + get + { return instance; } } } #endregion - + #region ICompare implementations - private abstract class SpanComparer : IComparer { - public abstract int GetSpan(LayoutInfo layoutInfo); + private abstract class SpanComparer : IComparer + { + public abstract int GetSpan(LayoutInfo layoutInfo); - public int Compare(object x, object y) { + public int Compare(object x, object y) + { LayoutInfo xInfo = (LayoutInfo)x; LayoutInfo yInfo = (LayoutInfo)y; return GetSpan(xInfo) - GetSpan(yInfo); } } - private class RowSpanComparer : SpanComparer { + private class RowSpanComparer : SpanComparer + { private static readonly RowSpanComparer instance = new RowSpanComparer(); - - public override int GetSpan(LayoutInfo layoutInfo) { + + public override int GetSpan(LayoutInfo layoutInfo) + { return layoutInfo.RowSpan; } - public static RowSpanComparer GetInstance { + public static RowSpanComparer GetInstance + { get { return instance; } } } - private class ColumnSpanComparer : SpanComparer { + private class ColumnSpanComparer : SpanComparer + { private static readonly ColumnSpanComparer instance = new ColumnSpanComparer(); - - public override int GetSpan(LayoutInfo layoutInfo) { + + public override int GetSpan(LayoutInfo layoutInfo) + { return layoutInfo.ColumnSpan; } - public static ColumnSpanComparer GetInstance { + public static ColumnSpanComparer GetInstance + { get { return instance; } } } - - private class PostAssignedPositionComparer : IComparer { + + private class PostAssignedPositionComparer : IComparer + { private static readonly PostAssignedPositionComparer instance = new PostAssignedPositionComparer(); - public static PostAssignedPositionComparer GetInstance { + public static PostAssignedPositionComparer GetInstance + { get { return instance; } } - - public int Compare (object x, object y) { + + public int Compare(object x, object y) + { LayoutInfo xInfo = (LayoutInfo)x; LayoutInfo yInfo = (LayoutInfo)y; - if (xInfo.RowStart < yInfo.RowStart) { + if (xInfo.RowStart < yInfo.RowStart) + { return -1; } - if (xInfo.RowStart > yInfo.RowStart) { + if (xInfo.RowStart > yInfo.RowStart) + { return 1; } - if (xInfo.ColumnStart < yInfo.ColumnStart) { + if (xInfo.ColumnStart < yInfo.ColumnStart) + { return -1; } - if (xInfo.ColumnStart > yInfo.ColumnStart) { + if (xInfo.ColumnStart > yInfo.ColumnStart) + { return 1; } return 0; } } - private class PreAssignedPositionComparer : IComparer { + private class PreAssignedPositionComparer : IComparer + { private static readonly PreAssignedPositionComparer instance = new PreAssignedPositionComparer(); - public static PreAssignedPositionComparer GetInstance { + public static PreAssignedPositionComparer GetInstance + { get { return instance; } } - - public int Compare (object x, object y) { + + public int Compare(object x, object y) + { LayoutInfo xInfo = (LayoutInfo)x; LayoutInfo yInfo = (LayoutInfo)y; - if (xInfo.RowPosition < yInfo.RowPosition) { + if (xInfo.RowPosition < yInfo.RowPosition) + { return -1; } - if (xInfo.RowPosition > yInfo.RowPosition) { + if (xInfo.RowPosition > yInfo.RowPosition) + { return 1; } - if (xInfo.ColumnPosition < yInfo.ColumnPosition) { + if (xInfo.ColumnPosition < yInfo.ColumnPosition) + { return -1; } - if (xInfo.ColumnPosition > yInfo.ColumnPosition) { + if (xInfo.ColumnPosition > yInfo.ColumnPosition) + { return 1; } return 0; @@ -1903,49 +2218,62 @@ public int Compare (object x, object y) { #region ReservationGrid // The ReservationGrid is used to track elements which span rows to prevent overlap. - private sealed class ReservationGrid { + private sealed class ReservationGrid + { int _numColumns = 1; ArrayList _rows = new ArrayList(); - - public bool IsReserved(int column, int rowOffset) { - if(rowOffset >= _rows.Count) { + + public bool IsReserved(int column, int rowOffset) + { + if (rowOffset >= _rows.Count) + { return false; } - if (column >= ((BitArray)_rows[rowOffset]).Length) { + if (column >= ((BitArray)_rows[rowOffset]).Length) + { return false; } return ((BitArray)_rows[rowOffset])[column]; } - - public void Reserve(int column, int rowOffset) { + + public void Reserve(int column, int rowOffset) + { Debug.Assert(!IsReserved(column, rowOffset), "we should not be reserving already reserved space."); - while(rowOffset >= _rows.Count) { + while (rowOffset >= _rows.Count) + { _rows.Add(new BitArray(_numColumns)); } //Debug.Assert(_numColumns == ((BitArray)_rows[rowOffset]).Length, "length doesn't match"); //increase the length of the _rows[rowOffset] if necessary - if (column >= ((BitArray)_rows[rowOffset]).Length) { + if (column >= ((BitArray)_rows[rowOffset]).Length) + { ((BitArray)_rows[rowOffset]).Length = column + 1; - if (column >= _numColumns) { + if (column >= _numColumns) + { _numColumns = column + 1; } } - + ((BitArray)_rows[rowOffset])[column] = true; Debug.Assert(IsReserved(column, rowOffset), "IsReserved/Reserved mismatch."); } //reserve all spaces taken by layoutInfo.Element, up till colStop - public void ReserveAll(LayoutInfo layoutInfo, int rowStop, int colStop) { - for (int rowOffset = 1; rowOffset < rowStop - layoutInfo.RowStart; rowOffset++) { - for (int reservedCol = layoutInfo.ColumnStart; reservedCol < colStop; reservedCol++) { + public void ReserveAll(LayoutInfo layoutInfo, int rowStop, int colStop) + { + for (int rowOffset = 1; rowOffset < rowStop - layoutInfo.RowStart; rowOffset++) + { + for (int reservedCol = layoutInfo.ColumnStart; reservedCol < colStop; reservedCol++) + { Reserve(reservedCol, rowOffset); } - } + } } - - public void AdvanceRow() { - if(_rows.Count > 0) { + + public void AdvanceRow() + { + if (_rows.Count > 0) + { _rows.RemoveAt(0); } } @@ -1953,22 +2281,26 @@ public void AdvanceRow() { } #endregion ReservationGrid - internal struct Strip { + internal struct Strip + { private int _maxSize; private int _minSize; private bool _isStart; //whether there is an element starting in this strip - - public int MinSize { + + public int MinSize + { get { return _minSize; } set { _minSize = value; } } - public int MaxSize { + public int MaxSize + { get { return _maxSize; } set { _maxSize = value; } } - public bool IsStart { + public bool IsStart + { get { return _isStart; } set { _isStart = value; } } @@ -1977,7 +2309,8 @@ public bool IsStart { #region DEBUG // Verify that the Row/Column assignments on the control are current. [Conditional("DEBUG_LAYOUT")] - private void Debug_VerifyAssignmentsAreCurrent(IArrangedElement container, ContainerInfo containerInfo) { + private void Debug_VerifyAssignmentsAreCurrent(IArrangedElement container, ContainerInfo containerInfo) + { #if DEBUG Hashtable oldLayoutInfo = new Hashtable(); ArrangedElementCollection children = container.Children; @@ -1985,9 +2318,11 @@ private void Debug_VerifyAssignmentsAreCurrent(IArrangedElement container, Conta int minSpace = 0; int minColumn = 0; - for (int i = 0; i < children.Count; i++) { + for (int i = 0; i < children.Count; i++) + { IArrangedElement element = children[i]; - if (!element.ParticipatesInLayout) { + if (!element.ParticipatesInLayout) + { // If the element does not participate in layout (i.e., Visible = false), we // exclude it from the childrenInfos list and it is ignored by the engine. continue; @@ -1996,19 +2331,21 @@ private void Debug_VerifyAssignmentsAreCurrent(IArrangedElement container, Conta LayoutInfo layoutInfo = GetLayoutInfo(element); childrenInfo.Add(layoutInfo); minSpace += layoutInfo.RowSpan * layoutInfo.ColumnSpan; - if (layoutInfo.IsAbsolutelyPositioned) { + if (layoutInfo.IsAbsolutelyPositioned) + { minColumn = Math.Max(minColumn, layoutInfo.ColumnPosition + layoutInfo.ColumnSpan); } } // Create a copy of the layoutInfos so we can restore to our original state - foreach(LayoutInfo layoutInfo in childrenInfo) { + foreach (LayoutInfo layoutInfo in childrenInfo) + { oldLayoutInfo[layoutInfo.Element] = layoutInfo.Clone(); } - + Strip[] rows = containerInfo.Rows; Strip[] cols = containerInfo.Columns; - + AssignRowsAndColumns(containerInfo); Debug.Assert((containerInfo.Columns == null && cols == null) || containerInfo.Columns.Length == cols.Length, @@ -2016,20 +2353,21 @@ private void Debug_VerifyAssignmentsAreCurrent(IArrangedElement container, Conta Debug.Assert((containerInfo.Rows == null && rows == null) || containerInfo.Rows.Length == rows.Length, "Cached assignment info is invalid: Number of required rows has changed."); - - foreach(LayoutInfo layoutInfo in childrenInfo) { + + foreach (LayoutInfo layoutInfo in childrenInfo) + { Debug.Assert(layoutInfo.Equals(oldLayoutInfo[layoutInfo.Element]), "Cached assignment info is invalid: LayoutInfo has changed." + " old layoutinfo: " + ((LayoutInfo)oldLayoutInfo[layoutInfo.Element]).RowStart + " " + ((LayoutInfo)oldLayoutInfo[layoutInfo.Element]).ColumnStart + " new layoutinfo: " + layoutInfo.RowStart + " " + layoutInfo.ColumnStart + " and the element is " + layoutInfo.Element.ToString()); - SetLayoutInfo(layoutInfo.Element, (LayoutInfo) oldLayoutInfo[layoutInfo.Element]); + SetLayoutInfo(layoutInfo.Element, (LayoutInfo)oldLayoutInfo[layoutInfo.Element]); } - + // Restore the information in row and column strips. Note that whenever we do a AssignRowAndColumns() // we instantiate new row and column strip collections, we have to restore the value back later. - + containerInfo.Rows = rows; containerInfo.Columns = cols; #endif // DEBUG @@ -2037,18 +2375,21 @@ private void Debug_VerifyAssignmentsAreCurrent(IArrangedElement container, Conta // Verifies that there is no overlapping of controls on the table (unless forced to do so via abs. positioning) [Conditional("DEBUG_LAYOUT")] - private void Debug_VerifyNoOverlapping(IArrangedElement container) { + private void Debug_VerifyNoOverlapping(IArrangedElement container) + { - // this code may be useful for debugging, but doesnt work well with - // row styles + // this code may be useful for debugging, but doesnt work well with + // row styles ArrayList layoutInfos = new ArrayList(container.Children.Count); ContainerInfo containerInfo = GetContainerInfo(container); Strip[] rows = containerInfo.Rows; Strip[] columns = containerInfo.Columns; - foreach(IArrangedElement element in container.Children) { - if (!element.ParticipatesInLayout) { + foreach (IArrangedElement element in container.Children) + { + if (!element.ParticipatesInLayout) + { // If the element does not participate in layout (i.e., Visible = false), we // exclude it from the layoutInfos list and it is ignored by the engine. continue; @@ -2057,43 +2398,51 @@ private void Debug_VerifyNoOverlapping(IArrangedElement container) { layoutInfos.Add(GetLayoutInfo(element)); } - for (int i = 0; i < layoutInfos.Count; i++) { + for (int i = 0; i < layoutInfos.Count; i++) + { LayoutInfo layoutInfo1 = (LayoutInfo)layoutInfos[i]; - + Rectangle elementBounds1 = layoutInfo1.Element.Bounds; Rectangle cellsOccupied1 = new Rectangle(layoutInfo1.ColumnStart, layoutInfo1.RowStart, layoutInfo1.ColumnSpan, layoutInfo1.RowSpan); - for (int j = i + 1; j < layoutInfos.Count; j++) { - LayoutInfo layoutInfo2 = (LayoutInfo)layoutInfos[j]; + for (int j = i + 1; j < layoutInfos.Count; j++) + { + LayoutInfo layoutInfo2 = (LayoutInfo)layoutInfos[j]; Rectangle elementBounds2 = layoutInfo2.Element.Bounds; Rectangle cellsOccupied2 = new Rectangle(layoutInfo2.ColumnStart, layoutInfo2.RowStart, layoutInfo2.ColumnSpan, layoutInfo2.RowSpan); Debug.Assert(!cellsOccupied1.IntersectsWith(cellsOccupied2), "controls overlap in the same cell"); // The actual control overlaps horizontally. this can only happen if all columns are absolutely sized - if (LayoutUtils.IsIntersectHorizontally(elementBounds1, elementBounds2)) { + if (LayoutUtils.IsIntersectHorizontally(elementBounds1, elementBounds2)) + { int k; Debug.Assert(containerInfo.ColumnStyles.Count >= layoutInfo1.ColumnStart + layoutInfo1.ColumnSpan, "length of column style too short"); Debug.Assert(containerInfo.ColumnStyles.Count >= layoutInfo1.ColumnStart + layoutInfo2.ColumnSpan, "length of column style too short"); - for (k = layoutInfo1.ColumnStart; k < layoutInfo1.ColumnStart + layoutInfo1.ColumnSpan; k++) { + for (k = layoutInfo1.ColumnStart; k < layoutInfo1.ColumnStart + layoutInfo1.ColumnSpan; k++) + { Debug.Assert(containerInfo.ColumnStyles[k].SizeType == SizeType.Absolute, "column " + k + " is not absolutely sized"); } - for (k = layoutInfo2.ColumnStart; k < layoutInfo2.ColumnStart + layoutInfo2.ColumnSpan; k++) { + for (k = layoutInfo2.ColumnStart; k < layoutInfo2.ColumnStart + layoutInfo2.ColumnSpan; k++) + { Debug.Assert(containerInfo.ColumnStyles[k].SizeType == SizeType.Absolute, "column " + k + " is not absolutely sized"); - } + } } // The actual control overlaps vertically. - if (LayoutUtils.IsIntersectVertically(elementBounds1, elementBounds2)) { + if (LayoutUtils.IsIntersectVertically(elementBounds1, elementBounds2)) + { int k; Debug.Assert(containerInfo.RowStyles.Count >= layoutInfo1.RowStart + layoutInfo1.RowSpan, "length of row style too short"); Debug.Assert(containerInfo.RowStyles.Count >= layoutInfo2.RowStart + layoutInfo2.RowSpan, "length of row style too short"); - for (k = layoutInfo1.RowStart; k < layoutInfo1.RowStart + layoutInfo1.RowSpan; k++) { + for (k = layoutInfo1.RowStart; k < layoutInfo1.RowStart + layoutInfo1.RowSpan; k++) + { Debug.Assert(containerInfo.RowStyles[k].SizeType == SizeType.Absolute, "column " + k + " is not absolutely sized"); } - for (k = layoutInfo2.RowStart; k < layoutInfo2.RowStart + layoutInfo2.RowSpan; k++) { + for (k = layoutInfo2.RowStart; k < layoutInfo2.RowStart + layoutInfo2.RowSpan; k++) + { Debug.Assert(containerInfo.RowStyles[k].SizeType == SizeType.Absolute, "column " + k + " is not absolutely sized"); - } + } } } - } + } } #endregion } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/LinkConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/LinkConverter.cs index 57706d155a3..6c57f93f43e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/LinkConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/LinkConverter.cs @@ -54,7 +54,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c { return null; } - + // Parse 2 integer values. if (culture == null) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs index dc4863e82e4..06958cd1e72 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System.Collections; using System.ComponentModel; @@ -21,7 +22,7 @@ namespace System.Windows.Forms { using System.Windows.Forms.Internal; using System; using System.Runtime.Versioning; - + /// /// /// Displays text that can contain a hyperlink. @@ -34,7 +35,8 @@ namespace System.Windows.Forms { ToolboxItem("System.Windows.Forms.Design.AutoSizeToolboxItem," + AssemblyRef.SystemDesign), SRDescription(nameof(SR.DescriptionLinkLabel)) ] - public class LinkLabel : Label, IButtonControl { + public class LinkLabel : Label, IButtonControl + { static readonly object EventLinkClicked = new object(); static Color iedisabledLinkColor = Color.Empty; @@ -57,7 +59,7 @@ public class LinkLabel : Label, IButtonControl { bool textLayoutValid = false; bool receivedDoubleClick = false; - + ArrayList links = new ArrayList(2); Link focusLink = null; @@ -66,15 +68,16 @@ public class LinkLabel : Label, IButtonControl { Cursor overrideCursor = null; bool processingOnGotFocus; // used to avoid raising the OnGotFocus event twice after selecting a focus link. - - LinkBehavior linkBehavior = System.Windows.Forms.LinkBehavior.SystemDefault; + + LinkBehavior linkBehavior = System.Windows.Forms.LinkBehavior.SystemDefault; /// /// /// Initializes a new default instance of the class. /// /// - public LinkLabel() : base() { + public LinkLabel() : base() + { SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.Opaque @@ -93,17 +96,23 @@ public LinkLabel() : base() { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.LinkLabelActiveLinkColorDescr)) ] - public Color ActiveLinkColor { - get { - if (activeLinkColor.IsEmpty) { + public Color ActiveLinkColor + { + get + { + if (activeLinkColor.IsEmpty) + { return IEActiveLinkColor; } - else { + else + { return activeLinkColor; } } - set { - if (activeLinkColor != value) { + set + { + if (activeLinkColor != value) + { activeLinkColor = value; InvalidateLink(null); } @@ -119,73 +128,96 @@ public Color ActiveLinkColor { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.LinkLabelDisabledLinkColorDescr)) ] - public Color DisabledLinkColor { - get { - if (disabledLinkColor.IsEmpty) { + public Color DisabledLinkColor + { + get + { + if (disabledLinkColor.IsEmpty) + { return IEDisabledLinkColor; } - else { + else + { return disabledLinkColor; } } - set { - if (disabledLinkColor != value) { + set + { + if (disabledLinkColor != value) + { disabledLinkColor = value; InvalidateLink(null); } } } - private Link FocusLink { - get { + private Link FocusLink + { + get + { return focusLink; } - set { - if (focusLink != value) { + set + { + if (focusLink != value) + { - if (focusLink != null) { + if (focusLink != null) + { InvalidateLink(focusLink); } focusLink = value; - - if (focusLink != null) { + + if (focusLink != null) + { InvalidateLink(focusLink); UpdateAccessibilityLink(focusLink); - + } } } } - - private Color IELinkColor { - get { + + private Color IELinkColor + { + get + { return LinkUtilities.IELinkColor; } } - private Color IEActiveLinkColor { - get { + private Color IEActiveLinkColor + { + get + { return LinkUtilities.IEActiveLinkColor; } } - private Color IEVisitedLinkColor { - get { + private Color IEVisitedLinkColor + { + get + { return LinkUtilities.IEVisitedLinkColor; } } - private Color IEDisabledLinkColor { - get { - if (iedisabledLinkColor.IsEmpty) { + private Color IEDisabledLinkColor + { + get + { + if (iedisabledLinkColor.IsEmpty) + { iedisabledLinkColor = ControlPaint.Dark(DisabledColor); } return iedisabledLinkColor; } } - private Rectangle ClientRectWithPadding { - get { + private Rectangle ClientRectWithPadding + { + get + { return LayoutUtils.DeflateRect(ClientRectangle, Padding); } } @@ -215,29 +247,37 @@ private Rectangle ClientRectWithPadding { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.LinkLabelLinkAreaDescr)) ] - public LinkArea LinkArea { - get { - if (links.Count == 0) { + public LinkArea LinkArea + { + get + { + if (links.Count == 0) + { return new LinkArea(0, 0); } return new LinkArea(((Link)links[0]).Start, ((Link)links[0]).Length); } - set { + set + { LinkArea pt = LinkArea; links.Clear(); - if (!value.IsEmpty) { - if (value.Start < 0) { + if (!value.IsEmpty) + { + if (value.Start < 0) + { throw new ArgumentOutOfRangeException(nameof(LinkArea), value, SR.LinkLabelAreaStart); } - if (value.Length < -1) { + if (value.Length < -1) + { throw new ArgumentOutOfRangeException(nameof(LinkArea), value, SR.LinkLabelAreaLength); } - if (value.Start != 0 || value.Length != 0) { + if (value.Start != 0 || value.Length != 0) + { Links.Add(new Link(this)); - + // Update the link area of the first link // ((Link)links[0]).Start = value.Start; @@ -247,7 +287,8 @@ public LinkArea LinkArea { UpdateSelectability(); - if (!pt.Equals(LinkArea)) { + if (!pt.Equals(LinkArea)) + { InvalidateTextLayout(); LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.LinkArea); base.AdjustSize(); @@ -266,16 +307,21 @@ public LinkArea LinkArea { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.LinkLabelLinkBehaviorDescr)) ] - public LinkBehavior LinkBehavior { - get { + public LinkBehavior LinkBehavior + { + get + { return linkBehavior; } - set { + set + { //valid values are 0x0 to 0x3 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)LinkBehavior.SystemDefault, (int)LinkBehavior.NeverUnderline)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)LinkBehavior.SystemDefault, (int)LinkBehavior.NeverUnderline)) + { throw new InvalidEnumArgumentException(nameof(LinkBehavior), (int)value, typeof(LinkBehavior)); } - if (value != linkBehavior) { + if (value != linkBehavior) + { linkBehavior = value; InvalidateLinkFonts(); InvalidateLink(null); @@ -292,20 +338,27 @@ public LinkBehavior LinkBehavior { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.LinkLabelLinkColorDescr)) ] - public Color LinkColor { - get { - if (linkColor.IsEmpty) { - if (SystemInformation.HighContrast) { + public Color LinkColor + { + get + { + if (linkColor.IsEmpty) + { + if (SystemInformation.HighContrast) + { return SystemColors.HotTrack; } return IELinkColor; } - else { + else + { return linkColor; } } - set { - if (linkColor != value) { + set + { + if (linkColor != value) + { linkColor = value; InvalidateLink(null); } @@ -321,9 +374,12 @@ public Color LinkColor { Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public LinkCollection Links { - get { - if (linkCollection == null) { + public LinkCollection Links + { + get + { + if (linkCollection == null) + { linkCollection = new LinkCollection(this); } return linkCollection; @@ -340,18 +396,25 @@ public LinkCollection Links { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.LinkLabelLinkVisitedDescr)) ] - public bool LinkVisited { - get { - if (links.Count == 0) { + public bool LinkVisited + { + get + { + if (links.Count == 0) + { return false; } - else { - return((Link)links[0]).Visited; + else + { + return ((Link)links[0]).Visited; } } - set { - if (value != LinkVisited) { - if (links.Count == 0) { + set + { + if (value != LinkVisited) + { + if (links.Count == 0) + { Links.Add(new Link(this)); } ((Link)links[0]).Visited = value; @@ -362,22 +425,29 @@ public bool LinkVisited { // link labels must always ownerdraw // - internal override bool OwnerDraw { - get { + internal override bool OwnerDraw + { + get + { return true; } } - protected Cursor OverrideCursor { - get { + protected Cursor OverrideCursor + { + get + { return overrideCursor; } - set { - if (overrideCursor != value) { + set + { + if (overrideCursor != value) + { overrideCursor = value; - if (IsHandleCreated) { + 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(); @@ -395,35 +465,43 @@ protected Cursor OverrideCursor { // Make this event visible through the property browser. [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] - new public event EventHandler TabStopChanged { + new public event EventHandler TabStopChanged + { add => base.TabStopChanged += value; remove => base.TabStopChanged -= value; } [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] - new public bool TabStop { - get { + new public bool TabStop + { + get + { return base.TabStop; } - set { + set + { base.TabStop = value; } } [RefreshProperties(RefreshProperties.Repaint)] - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; } } [RefreshProperties(RefreshProperties.Repaint)] - public new Padding Padding { - get {return base.Padding;} - set { base.Padding = value;} + public new Padding Padding + { + get { return base.Padding; } + set { base.Padding = value; } } /// @@ -435,20 +513,27 @@ public override string Text { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.LinkLabelVisitedLinkColorDescr)) ] - public Color VisitedLinkColor { - get { - if (visitedLinkColor.IsEmpty) { - if (SystemInformation.HighContrast) { + public Color VisitedLinkColor + { + get + { + if (visitedLinkColor.IsEmpty) + { + if (SystemInformation.HighContrast) + { return LinkUtilities.GetVisitedLinkColor(); } return IEVisitedLinkColor; } - else { + else + { return visitedLinkColor; } } - set { - if (visitedLinkColor != value) { + set + { + if (visitedLinkColor != value) + { visitedLinkColor = value; InvalidateLink(null); } @@ -461,42 +546,60 @@ public Color VisitedLinkColor { /// /// [WinCategory("Action"), SRDescription(nameof(SR.LinkLabelLinkClickedDescr))] - public event LinkLabelLinkClickedEventHandler LinkClicked { + public event LinkLabelLinkClickedEventHandler LinkClicked + { add => Events.AddHandler(EventLinkClicked, value); remove => Events.RemoveHandler(EventLinkClicked, value); } - internal static Rectangle CalcTextRenderBounds(Rectangle textRect, Rectangle clientRect, ContentAlignment align) { + internal static Rectangle CalcTextRenderBounds(Rectangle textRect, Rectangle clientRect, ContentAlignment align) + { int xLoc, yLoc, width, height; - if ((align & WindowsFormsUtils.AnyRightAlign) != 0) { + if ((align & WindowsFormsUtils.AnyRightAlign) != 0) + { xLoc = clientRect.Right - textRect.Width; - } else if ((align & WindowsFormsUtils.AnyCenterAlign) != 0) { + } + else if ((align & WindowsFormsUtils.AnyCenterAlign) != 0) + { xLoc = (clientRect.Width - textRect.Width) / 2; - } else { + } + else + { xLoc = clientRect.X; } - if ((align & WindowsFormsUtils.AnyBottomAlign) != 0) { + if ((align & WindowsFormsUtils.AnyBottomAlign) != 0) + { yLoc = clientRect.Bottom - textRect.Height; - } else if ((align & WindowsFormsUtils.AnyMiddleAlign) != 0) { + } + else if ((align & WindowsFormsUtils.AnyMiddleAlign) != 0) + { yLoc = (clientRect.Height - textRect.Height) / 2; - } else { + } + else + { yLoc = clientRect.Y; } // If the text rect does not fit in the client rect, make it fit. - if (textRect.Width > clientRect.Width) { + if (textRect.Width > clientRect.Width) + { xLoc = clientRect.X; width = clientRect.Width; - } else { + } + else + { width = textRect.Width; } - if (textRect.Height > clientRect.Height) { + if (textRect.Height > clientRect.Height) + { yLoc = clientRect.Y; height = clientRect.Height; - } else { + } + else + { height = textRect.Height; } @@ -507,7 +610,8 @@ internal static Rectangle CalcTextRenderBounds(Rectangle textRect, Rectangle cli /// Constructs the new instance of the accessibility object for this control. Subclasses /// should not call base.CreateAccessibilityObject. /// - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new LinkLabelAccessibleObject(this); } @@ -518,7 +622,8 @@ protected override AccessibleObject CreateAccessibilityInstance() { /// base.createHandle when overriding this method. /// /// - protected override void CreateHandle() { + protected override void CreateHandle() + { base.CreateHandle(); InvalidateTextLayout(); } @@ -531,19 +636,22 @@ protected override void CreateHandle() { /// entire text we are ok since it is just one area with the same size of the text binding /// area. /// - internal override bool CanUseTextRenderer { - get{ + internal override bool CanUseTextRenderer + { + get + { // If no link or the LinkArea is one and covers the entire text, we can support UseCompatibleTextRendering = false. // Observe that LinkArea refers to the first link always. - StringInfo stringInfo = new StringInfo( this.Text ); - return this.LinkArea.Start == 0 && ( this.LinkArea.Length == 0 || this.LinkArea.Length == stringInfo.LengthInTextElements ); + StringInfo stringInfo = new StringInfo(this.Text); + return this.LinkArea.Start == 0 && (this.LinkArea.Length == 0 || this.LinkArea.Length == stringInfo.LengthInTextElements); } } - internal override bool UseGDIMeasuring() { + internal override bool UseGDIMeasuring() + { return !UseCompatibleTextRendering; } - + /// /// Converts the character index into char index of the string /// This method is copied in LinkCollectionEditor.cs. Update the other @@ -553,12 +661,15 @@ internal override bool UseGDIMeasuring() { /// second character, then the index we need should be 2 instead of /// 1, and this method returns the correct index. /// - private static int ConvertToCharIndex(int index, string text) { - if (index <= 0) { + private static int ConvertToCharIndex(int index, string text) + { + if (index <= 0) + { return 0; } - if (string.IsNullOrEmpty(text)) { - Debug.Assert(text != null, "string should not be null"); + if (string.IsNullOrEmpty(text)) + { + Debug.Assert(text != null, "string should not be null"); //do no conversion, just return the original value passed in return index; } @@ -570,70 +681,83 @@ private static int ConvertToCharIndex(int index, string text) { int numTextElements = stringInfo.LengthInTextElements; //index is greater than the length of the string - if (index > numTextElements) { + if (index > numTextElements) + { return index - numTextElements + text.Length; //pretend all the characters after are ASCII characters } //return the length of the substring which has specified number of characters string sub = stringInfo.SubstringByTextElements(0, index); return sub.Length; } - - + + /// /// Ensures that we have analyzed the text run so that we can render each segment /// and link. /// - private void EnsureRun(Graphics g) { + private void EnsureRun(Graphics g) + { // bail early if everything is valid! // - if (textLayoutValid) { + if (textLayoutValid) + { return; } - if (this.textRegion != null) { + if (this.textRegion != null) + { this.textRegion.Dispose(); this.textRegion = null; } // bail early for no text // - if (Text.Length == 0) { + if (Text.Length == 0) + { Links.Clear(); - Links.Add (new Link (0, -1)); // default 'magic' link. + Links.Add(new Link(0, -1)); // default 'magic' link. textLayoutValid = true; return; } StringFormat textFormat = CreateStringFormat(); string text = Text; - try { + try + { Font alwaysUnderlined = new Font(Font, Font.Style | FontStyle.Underline); Graphics created = null; - try { - if (g == null) { + try + { + if (g == null) + { g = created = CreateGraphicsInternal(); } - if( UseCompatibleTextRendering ){ - Region[] textRegions = g.MeasureCharacterRanges (text, alwaysUnderlined, ClientRectWithPadding, textFormat); + if (UseCompatibleTextRendering) + { + Region[] textRegions = g.MeasureCharacterRanges(text, alwaysUnderlined, ClientRectWithPadding, textFormat); int regionIndex = 0; - - for (int i=0; i /// Calculate character ranges taking into account the locale. Provided for surrogate chars support. /// - private CharacterRange[] AdjustCharacterRangesForSurrogateChars(){ + private CharacterRange[] AdjustCharacterRangesForSurrogateChars() + { string text = Text; - if (string.IsNullOrEmpty(text)) { - return new CharacterRange[]{}; + if (string.IsNullOrEmpty(text)) + { + return new CharacterRange[] { }; } - StringInfo stringInfo = new StringInfo(text); + StringInfo stringInfo = new StringInfo(text); int textLen = stringInfo.LengthInTextElements; ArrayList ranges = new ArrayList(Links.Count); - foreach (Link link in Links) { + foreach (Link link in Links) + { int charStart = ConvertToCharIndex(link.Start, text); int charEnd = ConvertToCharIndex(link.Start + link.Length, text); - if (LinkInText(charStart, charEnd - charStart)) { - int length = (int) Math.Min(link.Length, textLen - link.Start); + if (LinkInText(charStart, charEnd - charStart)) + { + int length = (int)Math.Min(link.Length, textLen - link.Start); ranges.Add(new CharacterRange(charStart, ConvertToCharIndex(link.Start + length, text) - charStart)); } } @@ -739,34 +877,42 @@ private CharacterRange[] AdjustCharacterRangesForSurrogateChars(){ /// Determines whether the whole link label contains only one link, /// and the link runs from the beginning of the label to the end of it /// - private bool IsOneLink() { - if (links == null || links.Count != 1 || Text == null) { + private bool IsOneLink() + { + if (links == null || links.Count != 1 || Text == null) + { return false; } StringInfo stringInfo = new StringInfo(Text); - if (LinkArea.Start == 0 && LinkArea.Length == stringInfo.LengthInTextElements) { + if (LinkArea.Start == 0 && LinkArea.Length == stringInfo.LengthInTextElements) + { return true; } return false; } - + /// /// Determines if the given client coordinates is contained within a portion /// of a link area. /// - protected Link PointInLink(int x, int y) { + protected Link PointInLink(int x, int y) + { Graphics g = CreateGraphicsInternal(); Link hit = null; - try { + try + { EnsureRun(g); - foreach (Link link in links) { - if (link.VisualRegion != null && link.VisualRegion.IsVisible(x, y, g)) { + foreach (Link link in links) + { + if (link.VisualRegion != null && link.VisualRegion.IsVisible(x, y, g)) + { hit = link; break; } } } - finally { + finally + { g.Dispose(); g = null; } @@ -778,12 +924,16 @@ protected Link PointInLink(int x, int y) { /// the specified link. If link is null, then all linked text /// is invalidated. /// - private void InvalidateLink(Link link) { - if (IsHandleCreated) { - if (link == null || link.VisualRegion == null || IsOneLink()) { + private void InvalidateLink(Link link) + { + if (IsHandleCreated) + { + if (link == null || link.VisualRegion == null || IsOneLink()) + { Invalidate(); } - else{ + else + { Invalidate(link.VisualRegion); } } @@ -793,13 +943,16 @@ private void InvalidateLink(Link link) { /// Invalidates the current set of fonts we use when painting /// links. The fonts will be recreated when needed. /// - private void InvalidateLinkFonts() { + private void InvalidateLinkFonts() + { - if (linkFont != null) { + if (linkFont != null) + { linkFont.Dispose(); } - if (hoverLinkFont != null && hoverLinkFont != linkFont) { + if (hoverLinkFont != null && hoverLinkFont != linkFont) + { hoverLinkFont.Dispose(); } @@ -807,12 +960,14 @@ private void InvalidateLinkFonts() { hoverLinkFont = null; } - private void InvalidateTextLayout() { + private void InvalidateTextLayout() + { textLayoutValid = false; } - private bool LinkInText(int start, int length) { - return(0 <= start && start < Text.Length && 0 < length); + private bool LinkInText(int start, int length) + { + return (0 <= start && start < Text.Length && 0 < length); } /// @@ -822,12 +977,15 @@ private bool LinkInText(int start, int length) { /// is clicked. /// /// - DialogResult IButtonControl.DialogResult { - get { + DialogResult IButtonControl.DialogResult + { + get + { return dialogResult; } - set { + set + { //valid values are 0x0 to 0x7 if (!ClientUtils.IsEnumValid(value, (int)value, (int)DialogResult.None, (int)DialogResult.No)) { @@ -838,32 +996,40 @@ DialogResult IButtonControl.DialogResult { } } - void IButtonControl.NotifyDefault(bool value) { + void IButtonControl.NotifyDefault(bool value) + { } /// /// Raises the event. /// - protected override void OnGotFocus(EventArgs e) { - if (!this.processingOnGotFocus) { + protected override void OnGotFocus(EventArgs e) + { + if (!this.processingOnGotFocus) + { base.OnGotFocus(e); this.processingOnGotFocus = true; } - try { + try + { Link focusLink = FocusLink; - if (focusLink == null) { + if (focusLink == null) + { // Set focus on first link. // This will raise the OnGotFocus event again but it will not be processed because processingOnGotFocus is true. Select(true /*directed*/, true /*forward*/); } - else { + else + { InvalidateLink(focusLink); UpdateAccessibilityLink(focusLink); } } - finally { - if (this.processingOnGotFocus) { + finally + { + if (this.processingOnGotFocus) + { this.processingOnGotFocus = false; } } @@ -875,10 +1041,12 @@ protected override void OnGotFocus(EventArgs e) { /// event. /// /// - protected override void OnLostFocus(EventArgs e) { + protected override void OnLostFocus(EventArgs e) + { base.OnLostFocus(e); - if (FocusLink != null) { + if (FocusLink != null) + { InvalidateLink(FocusLink); } } @@ -889,11 +1057,14 @@ protected override void OnLostFocus(EventArgs e) { /// event. /// /// - protected override void OnKeyDown(KeyEventArgs e) { + protected override void OnKeyDown(KeyEventArgs e) + { base.OnKeyDown(e); - if (e.KeyCode == Keys.Enter) { - if (FocusLink != null && FocusLink.Enabled) { + if (e.KeyCode == Keys.Enter) + { + if (FocusLink != null && FocusLink.Enabled) + { OnLinkClicked(new LinkLabelLinkClickedEventArgs(FocusLink)); } } @@ -905,20 +1076,25 @@ protected override void OnKeyDown(KeyEventArgs e) { /// event. /// /// - protected override void OnMouseLeave(EventArgs e) { + protected override void OnMouseLeave(EventArgs e) + { base.OnMouseLeave(e); - if (!Enabled) { + if (!Enabled) + { return; } - foreach (Link link in links) { + foreach (Link link in links) + { if ((link.State & LinkState.Hover) == LinkState.Hover - || (link.State & LinkState.Active) == LinkState.Active) { + || (link.State & LinkState.Active) == LinkState.Active) + { bool activeChanged = (link.State & LinkState.Active) == LinkState.Active; link.State &= ~(LinkState.Hover | LinkState.Active); - if (activeChanged || hoverLinkFont != linkFont) { + if (activeChanged || hoverLinkFont != linkFont) + { InvalidateLink(link); } OverrideCursor = null; @@ -932,20 +1108,25 @@ protected override void OnMouseLeave(EventArgs e) { /// event. /// /// - protected override void OnMouseDown(MouseEventArgs e) { + protected override void OnMouseDown(MouseEventArgs e) + { base.OnMouseDown(e); - if (!Enabled || e.Clicks > 1) { + if (!Enabled || e.Clicks > 1) + { receivedDoubleClick = true; return; } - for (int i=0; i /// - protected override void OnMouseUp(MouseEventArgs e) { + protected override void OnMouseUp(MouseEventArgs e) + { base.OnMouseUp(e); // - if (Disposing || IsDisposed) { + if (Disposing || IsDisposed) + { return; } - if (!Enabled || e.Clicks > 1 || receivedDoubleClick) { + if (!Enabled || e.Clicks > 1 || receivedDoubleClick) + { receivedDoubleClick = false; return; } - for (int i=0; i /// /// Raises the /// event. /// /// - protected override void OnMouseMove(MouseEventArgs e) { + protected override void OnMouseMove(MouseEventArgs e) + { base.OnMouseMove(e); - if (!Enabled) { + if (!Enabled) + { return; } Link hoverLink = null; - foreach (Link link in links) { - if ((link.State & LinkState.Hover) == LinkState.Hover) { + foreach (Link link in links) + { + if ((link.State & LinkState.Hover) == LinkState.Hover) + { hoverLink = link; break; } @@ -1013,25 +1204,33 @@ protected override void OnMouseMove(MouseEventArgs e) { Link pointIn = PointInLink(e.X, e.Y); - if (pointIn != hoverLink) { - if (hoverLink != null) { + if (pointIn != hoverLink) + { + if (hoverLink != null) + { hoverLink.State &= ~LinkState.Hover; } - if (pointIn != null) { + if (pointIn != null) + { pointIn.State |= LinkState.Hover; - if (pointIn.Enabled) { + if (pointIn.Enabled) + { OverrideCursor = Cursors.Hand; } } - else { + else + { OverrideCursor = null; } - if (hoverLinkFont != linkFont) { - if (hoverLink != null) { + if (hoverLinkFont != linkFont) + { + if (hoverLink != null) + { InvalidateLink(hoverLink); } - if (pointIn != null) { + if (pointIn != null) + { InvalidateLink(pointIn); } } @@ -1043,14 +1242,17 @@ protected override void OnMouseMove(MouseEventArgs e) { /// Raises the event. /// /// - protected virtual void OnLinkClicked(LinkLabelLinkClickedEventArgs e) { + protected virtual void OnLinkClicked(LinkLabelLinkClickedEventArgs e) + { LinkLabelLinkClickedEventHandler handler = (LinkLabelLinkClickedEventHandler)Events[EventLinkClicked]; - if (handler != null) { + if (handler != null) + { handler(this, e); } } - protected override void OnPaddingChanged(EventArgs e) { + protected override void OnPaddingChanged(EventArgs e) + { base.OnPaddingChanged(e); InvalidateTextLayout(); } @@ -1061,7 +1263,8 @@ protected override void OnPaddingChanged(EventArgs e) { /// event. /// /// - protected override void OnPaint(PaintEventArgs e) { + protected override void OnPaint(PaintEventArgs e) + { RectangleF finalrect = RectangleF.Empty; //the focus rectangle if there is only one link Animate(); @@ -1070,28 +1273,35 @@ protected override void OnPaint(PaintEventArgs e) { // bail early for no text // - if (Text.Length == 0) { + if (Text.Length == 0) + { PaintLinkBackground(e.Graphics); } // Paint enabled link label // - else { - if (AutoEllipsis) { + else + { + if (AutoEllipsis) + { Rectangle clientRect = this.ClientRectWithPadding; Size preferredSize = GetPreferredSize(new Size(clientRect.Width, clientRect.Height)); showToolTip = (clientRect.Width < preferredSize.Width || clientRect.Height < preferredSize.Height); } - else { + else + { showToolTip = false; } - if (this.Enabled) { // Control.Enabled not to be confused with Link.Enabled + if (this.Enabled) + { // Control.Enabled not to be confused with Link.Enabled bool optimizeBackgroundRendering = !GetStyle(ControlStyles.OptimizedDoubleBuffer); SolidBrush foreBrush = new SolidBrush(ForeColor); SolidBrush linkBrush = new SolidBrush(LinkColor); - try { - if (!optimizeBackgroundRendering) { + try + { + if (!optimizeBackgroundRendering) + { PaintLinkBackground(e.Graphics); } @@ -1099,39 +1309,50 @@ protected override void OnPaint(PaintEventArgs e) { Region originalClip = e.Graphics.Clip; - try { - if (IsOneLink()) { + try + { + if (IsOneLink()) + { //exclude the area to draw the focus rectangle e.Graphics.Clip = originalClip; RectangleF[] rects = ((Link)links[0]).VisualRegion.GetRegionScans(e.Graphics.Transform); - if (rects != null && rects.Length > 0) { - if (UseCompatibleTextRendering) { + if (rects != null && rects.Length > 0) + { + if (UseCompatibleTextRendering) + { finalrect = new RectangleF(rects[0].Location, SizeF.Empty); - foreach (RectangleF rect in rects) { + foreach (RectangleF rect in rects) + { finalrect = RectangleF.Union(finalrect, rect); } } - else { + else + { finalrect = this.ClientRectWithPadding; Size finalRectSize = finalrect.Size.ToSize(); - + Size requiredSize = MeasureTextCache.GetTextSize(Text, Font, finalRectSize, CreateTextFormatFlags(finalRectSize)); finalrect.Width = requiredSize.Width; - if (requiredSize.Height < finalrect.Height) { + if (requiredSize.Height < finalrect.Height) + { finalrect.Height = requiredSize.Height; } finalrect = CalcTextRenderBounds(System.Drawing.Rectangle.Round(finalrect) /*textRect*/, this.ClientRectWithPadding /*clientRect*/, RtlTranslateContent(this.TextAlign)); } - using (Region region = new Region(finalrect)) { + using (Region region = new Region(finalrect)) + { e.Graphics.ExcludeClip(region); } } } - else { - foreach (Link link in links) { - if (link.VisualRegion != null) { + else + { + foreach (Link link in links) + { + if (link.VisualRegion != null) + { e.Graphics.ExcludeClip(link.VisualRegion); } } @@ -1141,35 +1362,42 @@ protected override void OnPaint(PaintEventArgs e) { // it's not necessary to paint with forebrush first // as it will be overlapped by linkbrush in the following steps - if (!IsOneLink()) { + if (!IsOneLink()) + { PaintLink(e.Graphics, null, foreBrush, linkBrush, optimizeBackgroundRendering, finalrect); } - foreach (Link link in links) { + foreach (Link link in links) + { PaintLink(e.Graphics, link, foreBrush, linkBrush, optimizeBackgroundRendering, finalrect); } - if (optimizeBackgroundRendering) { + if (optimizeBackgroundRendering) + { e.Graphics.Clip = originalClip; e.Graphics.ExcludeClip(this.textRegion); PaintLinkBackground(e.Graphics); } } - finally { + finally + { e.Graphics.Clip = originalClip; } } - finally { + finally + { foreBrush.Dispose(); linkBrush.Dispose(); } } // Paint disabled link label (disabled control, not to be confused with disabled link). // - else { + else + { Region originalClip = e.Graphics.Clip; - try { + try + { // We need to paint the background first before clipping to textRegion because it is calculated using // ClientRectWithPadding which in some cases is smaller that ClientRectangle. // @@ -1178,28 +1406,34 @@ protected override void OnPaint(PaintEventArgs e) { Color foreColor; - if (UseCompatibleTextRendering) { + if (UseCompatibleTextRendering) + { // APPCOMPAT: Use DisabledColor because Everett used DisabledColor. // (ie, dont use Graphics.GetNearestColor(DisabledColor.) StringFormat stringFormat = CreateStringFormat(); ControlPaint.DrawStringDisabled(e.Graphics, Text, Font, DisabledColor, ClientRectWithPadding, stringFormat); } - else { + else + { IntPtr hdc = e.Graphics.GetHdc(); - try { - using (WindowsGraphics wg = WindowsGraphics.FromHdc(hdc)) { + try + { + using (WindowsGraphics wg = WindowsGraphics.FromHdc(hdc)) + { foreColor = wg.GetNearestColor(DisabledColor); } } - finally { + finally + { e.Graphics.ReleaseHdc(); } Rectangle clientRectWidthPadding = ClientRectWithPadding; - + ControlPaint.DrawStringDisabled(e.Graphics, Text, Font, foreColor, clientRectWidthPadding, CreateTextFormatFlags(clientRectWidthPadding.Size)); } } - finally { + finally + { e.Graphics.Clip = originalClip; } } @@ -1211,36 +1445,44 @@ protected override void OnPaint(PaintEventArgs e) { RaisePaintEvent(this, e); } - protected override void OnPaintBackground(PaintEventArgs e) { + protected override void OnPaintBackground(PaintEventArgs e) + { Image i = this.Image; - if (i != null) { + if (i != null) + { Region oldClip = e.Graphics.Clip; Rectangle imageBounds = CalcImageRenderBounds(i, ClientRectangle, RtlTranslateAlignment(ImageAlign)); e.Graphics.ExcludeClip(imageBounds); - try { + try + { base.OnPaintBackground(e); } - finally { + finally + { e.Graphics.Clip = oldClip; } e.Graphics.IntersectClip(imageBounds); - try { + try + { base.OnPaintBackground(e); DrawImage(e.Graphics, i, ClientRectangle, RtlTranslateAlignment(ImageAlign)); } - finally { + finally + { e.Graphics.Clip = oldClip; } } - else { + else + { base.OnPaintBackground(e); } } - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { base.OnFontChanged(e); InvalidateTextLayout(); InvalidateLinkFonts(); @@ -1249,7 +1491,8 @@ protected override void OnFontChanged(EventArgs e) { /// /// - protected override void OnAutoSizeChanged(EventArgs e) { + protected override void OnAutoSizeChanged(EventArgs e) + { base.OnAutoSizeChanged(e); InvalidateTextLayout(); } @@ -1257,16 +1500,20 @@ protected override void OnAutoSizeChanged(EventArgs e) { /// /// Overriden by LinkLabel. /// - internal override void OnAutoEllipsisChanged(/*EventArgs e*/) { + internal override void OnAutoEllipsisChanged(/*EventArgs e*/) + { base.OnAutoEllipsisChanged(/*e*/); InvalidateTextLayout(); } - protected override void OnEnabledChanged(EventArgs e) { + protected override void OnEnabledChanged(EventArgs e) + { base.OnEnabledChanged(e); - - if (!Enabled) { - for (int i=0; i 0 ){ + if (rects != null && rects.Length > 0) + { Rectangle focusRect; - if (IsOneLink()) { + if (IsOneLink()) + { //draw one merged focus rectangle focusRect = Rectangle.Ceiling(finalrect); Debug.Assert(finalrect != RectangleF.Empty, "finalrect should be initialized"); ControlPaint.DrawFocusRectangle(g, focusRect, ForeColor, BackColor); } - else { - foreach (RectangleF rect in rects) { + else + { + foreach (RectangleF rect in rects) + { ControlPaint.DrawFocusRectangle(g, Rectangle.Ceiling(rect), ForeColor, BackColor); } } @@ -1387,27 +1660,34 @@ private void PaintLink(Graphics g, Link link, SolidBrush foreBrush, SolidBrush l // no else clause... we don't paint anything if we are given a link with no visual region. // } - else { // Painting with no link. + else + { // Painting with no link. g.IntersectClip(this.textRegion); - if (optimizeBackgroundRendering) { + if (optimizeBackgroundRendering) + { PaintLinkBackground(g); } - if( UseCompatibleTextRendering ){ + if (UseCompatibleTextRendering) + { StringFormat stringFormat = CreateStringFormat(); g.DrawString(Text, font, foreBrush, ClientRectWithPadding, stringFormat); } - else{ + else + { Color color; IntPtr hdc = g.GetHdc(); - try{ - using( WindowsGraphics wg = WindowsGraphics.FromHdc( hdc ) ) { + try + { + using (WindowsGraphics wg = WindowsGraphics.FromHdc(hdc)) + { color = wg.GetNearestColor(foreBrush.Color); } } - finally{ + finally + { g.ReleaseHdc(); } Rectangle clientRectWithPadding = ClientRectWithPadding; @@ -1416,22 +1696,28 @@ private void PaintLink(Graphics g, Link link, SolidBrush foreBrush, SolidBrush l } } - private void PaintLinkBackground(Graphics g) { - using (PaintEventArgs e = new PaintEventArgs(g, ClientRectangle)) { + private void PaintLinkBackground(Graphics g) + { + using (PaintEventArgs e = new PaintEventArgs(g, ClientRectangle)) + { InvokePaintBackground(this, e); } } - void IButtonControl.PerformClick() { + void IButtonControl.PerformClick() + { // If a link is not currently focused, focus on the first link // - if (FocusLink == null && Links.Count > 0) { + if (FocusLink == null && Links.Count > 0) + { string text = Text; - foreach (Link link in Links) { + foreach (Link link in Links) + { int charStart = ConvertToCharIndex(link.Start, text); int charEnd = ConvertToCharIndex(link.Start + link.Length, text); - if (link.Enabled && LinkInText(charStart, charEnd - charStart)) { + if (link.Enabled && LinkInText(charStart, charEnd - charStart)) + { FocusLink = link; break; } @@ -1440,7 +1726,8 @@ void IButtonControl.PerformClick() { // Act as if the focused link was clicked // - if (FocusLink != null) { + if (FocusLink != null) + { OnLinkClicked(new LinkLabelLinkClickedEventArgs(FocusLink)); } } @@ -1459,27 +1746,34 @@ void IButtonControl.PerformClick() { /// will seldom, if ever, need to override this method. /// /// - protected override bool ProcessDialogKey(Keys keyData) { - if ((keyData & (Keys.Alt | Keys.Control)) != Keys.Alt) { + protected override bool ProcessDialogKey(Keys keyData) + { + if ((keyData & (Keys.Alt | Keys.Control)) != Keys.Alt) + { Keys keyCode = keyData & Keys.KeyCode; - switch (keyCode) { + switch (keyCode) + { case Keys.Tab: - if (TabStop) { + if (TabStop) + { bool forward = (keyData & Keys.Shift) != Keys.Shift; - if (FocusNextLink(forward)) { + if (FocusNextLink(forward)) + { return true; } } break; case Keys.Up: case Keys.Left: - if (FocusNextLink(false)) { + if (FocusNextLink(false)) + { return true; } break; case Keys.Down: case Keys.Right: - if (FocusNextLink(true)) { + if (FocusNextLink(true)) + { return true; } break; @@ -1488,11 +1782,15 @@ protected override bool ProcessDialogKey(Keys keyData) { return base.ProcessDialogKey(keyData); } - private bool FocusNextLink(bool forward) { + private bool FocusNextLink(bool forward) + { int focusIndex = -1; - if (focusLink != null) { - for (int i=0; i= 0) { + if (focusIndex >= 0) + { test = Links[focusIndex]; charStart = ConvertToCharIndex(test.Start, text); charEnd = ConvertToCharIndex(test.Start + test.Length, text); } - else { + else + { test = null; } - + } while (test != null && !test.Enabled && LinkInText(charStart, charEnd - charStart)); } - if (focusIndex < 0 || focusIndex >= links.Count) { + if (focusIndex < 0 || focusIndex >= links.Count) + { return -1; } - else { + else + { return focusIndex; } } - private void ResetLinkArea() { + private void ResetLinkArea() + { LinkArea = new LinkArea(0, -1); } - internal void ResetActiveLinkColor() { + internal void ResetActiveLinkColor() + { activeLinkColor = Color.Empty; } - internal void ResetDisabledLinkColor() { + internal void ResetDisabledLinkColor() + { disabledLinkColor = Color.Empty; } - internal void ResetLinkColor() { + internal void ResetLinkColor() + { linkColor = Color.Empty; InvalidateLink(null); } - private void ResetVisitedLinkColor() { + private void ResetVisitedLinkColor() + { visitedLinkColor = Color.Empty; } @@ -1586,7 +1902,8 @@ private void ResetVisitedLinkColor() { /// base.setBoundsCore to actually cause the bounds of the control to change. /// /// - protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { + protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) + { // we cache too much state to try and optimize this (regions, etc)... it is best // to always relayout here... If we want to resurect this code in the future, @@ -1601,24 +1918,28 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound Invalidate(); } */ - + InvalidateTextLayout(); Invalidate(); base.SetBoundsCore(x, y, width, height, specified); } - protected override void Select(bool directed, bool forward) { + protected override void Select(bool directed, bool forward) + { - if (directed) { + if (directed) + { // In a multi-link label, if the tab came from another control, we want to keep the currently // focused link, otherwise, we set the focus to the next link. - if (links.Count > 0) { + if (links.Count > 0) + { // Find which link is currently focused // int focusIndex = -1; - if (FocusLink != null) { + if (FocusLink != null) + { focusIndex = links.IndexOf(FocusLink); } @@ -1628,16 +1949,20 @@ protected override void Select(bool directed, bool forward) { FocusLink = null; int newFocus = GetNextLinkIndex(focusIndex, forward); - if (newFocus == -1) { - if (forward) { + if (newFocus == -1) + { + if (forward) + { newFocus = GetNextLinkIndex(-1, forward); // -1, so "next" will be 0 } - else { + else + { newFocus = GetNextLinkIndex(links.Count, forward); // Count, so "next" will be Count-1 } } - if (newFocus != -1) { + if (newFocus != -1) + { FocusLink = (Link)links[newFocus]; } } @@ -1650,7 +1975,8 @@ protected override void Select(bool directed, bool forward) { /// Determines if the color for active links should remain the same. /// /// - internal bool ShouldSerializeActiveLinkColor() { + internal bool ShouldSerializeActiveLinkColor() + { return !activeLinkColor.IsEmpty; } @@ -1659,7 +1985,8 @@ internal bool ShouldSerializeActiveLinkColor() { /// Determines if the color for disabled links should remain the same. /// /// - internal bool ShouldSerializeDisabledLinkColor() { + internal bool ShouldSerializeDisabledLinkColor() + { return !disabledLinkColor.IsEmpty; } @@ -1669,8 +1996,10 @@ internal bool ShouldSerializeDisabledLinkColor() { /// link should remain the same. /// /// - private bool ShouldSerializeLinkArea() { - if (links.Count == 1) { + private bool ShouldSerializeLinkArea() + { + if (links.Count == 1) + { // use field access to find out if "length" is really -1 return Links[0].Start != 0 || Links[0]._length != -1; } @@ -1683,7 +2012,8 @@ private bool ShouldSerializeLinkArea() { /// Determines if the color of links in normal cases should remain the same. /// /// - internal bool ShouldSerializeLinkColor() { + internal bool ShouldSerializeLinkColor() + { return !linkColor.IsEmpty; } @@ -1691,9 +2021,10 @@ internal bool ShouldSerializeLinkColor() { /// Determines whether designer should generate code for setting the UseCompatibleTextRendering or not. /// DefaultValue(false) /// - private bool ShouldSerializeUseCompatibleTextRendering() { + private bool ShouldSerializeUseCompatibleTextRendering() + { // Serialize code if LinkLabel cannot support the feature or the property's value is not the default. - return !CanUseTextRenderer || UseCompatibleTextRendering != Control.UseCompatibleTextRenderingDefault; + return !CanUseTextRenderer || UseCompatibleTextRendering != Control.UseCompatibleTextRenderingDefault; } /// @@ -1701,7 +2032,8 @@ private bool ShouldSerializeUseCompatibleTextRendering() { /// Determines if the color of links that have been visited should remain the same. /// /// - private bool ShouldSerializeVisitedLinkColor() { + private bool ShouldSerializeVisitedLinkColor() + { return !visitedLinkColor.IsEmpty; } @@ -1712,40 +2044,50 @@ private bool ShouldSerializeVisitedLinkColor() { /// Update accessibility with the currently focused link. /// /// - private void UpdateAccessibilityLink(Link focusLink) { + private void UpdateAccessibilityLink(Link focusLink) + { - if (!IsHandleCreated) { + if (!IsHandleCreated) + { return; } - + int focusIndex = -1; - for (int i=0; i /// Validates that no links overlap. This will throw an exception if /// they do. /// - private void ValidateNoOverlappingLinks() { - for (int x=0; x - private void UpdateSelectability() { + private void UpdateSelectability() + { LinkArea pt = LinkArea; bool selectable = false; string text = Text; int charStart = ConvertToCharIndex(pt.Start, text); int charEnd = ConvertToCharIndex(pt.Start + pt.Length, text); - if (LinkInText(charStart, charEnd - charStart)) { + if (LinkInText(charStart, charEnd - charStart)) + { selectable = true; } - else { + else + { // If a link is currently focused, de-select it // - if (FocusLink != null) { + if (FocusLink != null) + { FocusLink = null; } } - + OverrideCursor = null; TabStop = selectable; SetStyle(ControlStyles.Selectable, selectable); @@ -1790,13 +2136,17 @@ private void UpdateSelectability() { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.UseCompatibleTextRenderingDescr)) ] - public new bool UseCompatibleTextRendering { - get { - Debug.Assert( CanUseTextRenderer || base.UseCompatibleTextRendering, "Using GDI text rendering when CanUseTextRenderer reported false." ); + public new bool UseCompatibleTextRendering + { + get + { + Debug.Assert(CanUseTextRenderer || base.UseCompatibleTextRendering, "Using GDI text rendering when CanUseTextRenderer reported false."); return base.UseCompatibleTextRendering; } - set { - if (base.UseCompatibleTextRendering != value) { + set + { + if (base.UseCompatibleTextRendering != value) + { // Cache the value so it is restored if CanUseTextRenderer becomes true and the designer can undo changes to this as side effect. base.UseCompatibleTextRendering = value; InvalidateTextLayout(); @@ -1809,20 +2159,25 @@ private void UpdateSelectability() { /// /// Handles the WM_SETCURSOR message /// - private void WmSetCursor(ref Message m) { + private void WmSetCursor(ref Message m) + { // Accessing through the Handle property has side effects that break this // logic. You must use InternalHandle. // - if (m.WParam == InternalHandle && NativeMethods.Util.LOWORD(m.LParam) == NativeMethods.HTCLIENT) { - if (OverrideCursor != null) { + if (m.WParam == InternalHandle && NativeMethods.Util.LOWORD(m.LParam) == NativeMethods.HTCLIENT) + { + if (OverrideCursor != null) + { Cursor.CurrentInternal = OverrideCursor; } - else { + else + { Cursor.CurrentInternal = Cursor; } } - else { + else + { DefWndProc(ref m); } @@ -1830,8 +2185,10 @@ private void WmSetCursor(ref Message m) { /// /// - protected override void WndProc(ref Message msg) { - switch (msg.Msg) { + protected override void WndProc(ref Message msg) + { + switch (msg.Msg) + { case Interop.WindowMessages.WM_SETCURSOR: WmSetCursor(ref msg); break; @@ -1841,7 +2198,8 @@ protected override void WndProc(ref Message msg) { } } - public class LinkCollection : IList { + public class LinkCollection : IList + { private LinkLabel owner; private bool linksAdded = false; //whether we should serialize the linkCollection @@ -1851,17 +2209,21 @@ public class LinkCollection : IList { /// Note this is not Thread Safe - but WinForms has to be run in a STA anyways. private int lastAccessedIndex = -1; - public LinkCollection(LinkLabel owner) { + public LinkCollection(LinkLabel owner) + { if (owner == null) throw new ArgumentNullException(nameof(owner)); this.owner = owner; } - public virtual Link this[int index] { - get { - return(Link)owner.links[index]; + public virtual Link this[int index] + { + get + { + return (Link)owner.links[index]; } - set { + set + { owner.links[index] = value; owner.links.Sort(LinkLabel.linkComparer); @@ -1870,47 +2232,59 @@ public virtual Link this[int index] { owner.Invalidate(); } } - - object IList.this[int index] { - get { + + object IList.this[int index] + { + get + { return this[index]; } - set { - if (value is Link) { + set + { + if (value is Link) + { this[index] = (Link)value; } - else { - throw new ArgumentException(SR.LinkLabelBadLink,"value"); + else + { + throw new ArgumentException(SR.LinkLabelBadLink, "value"); } } } - + /// /// Retrieves the child control with the specified key. /// - public virtual Link this[string key] { - get { + public virtual Link this[string key] + { + get + { // We do not support null and empty string as valid keys. - if (string.IsNullOrEmpty(key)){ + if (string.IsNullOrEmpty(key)) + { return null; } // Search for the key in our collection int index = IndexOfKey(key); - if (IsValidIndex(index)) { + if (IsValidIndex(index)) + { return this[index]; } - else { + else + { return null; } } } - + [Browsable(false)] - public int Count { - get { + public int Count + { + get + { return owner.links.Count; } } @@ -1918,55 +2292,70 @@ public int Count { /// /// whether we have added a non-trivial link to the collection /// - - public bool LinksAdded { - get { + + public bool LinksAdded + { + get + { return linksAdded; } } - - object ICollection.SyncRoot { - get { + + object ICollection.SyncRoot + { + get + { return this; } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return false; } } - - bool IList.IsFixedSize { - get { + + bool IList.IsFixedSize + { + get + { return false; } } - - public bool IsReadOnly { - get { + + public bool IsReadOnly + { + get + { return false; } } - - public Link Add(int start, int length) { - if (length != 0) { + + public Link Add(int start, int length) + { + if (length != 0) + { linksAdded = true; } return Add(start, length, null); } - public Link Add(int start, int length, object linkData) { - if (length != 0) { + public Link Add(int start, int length, object linkData) + { + if (length != 0) + { linksAdded = true; } // check for the special case where the list is in the "magic" // state of having only the default link in it. In that case // we want to clear the list before adding this link. // - if (owner.links.Count == 1 + if (owner.links.Count == 1 && this[0].Start == 0 - && this[0]._length == -1) { + && this[0]._length == -1) + { owner.links.Clear(); owner.FocusLink = null; @@ -1980,17 +2369,20 @@ public Link Add(int start, int length, object linkData) { return l; } - public int Add(Link value) { - if (value != null && value.Length != 0) { + public int Add(Link value) + { + if (value != null && value.Length != 0) + { linksAdded = true; } // check for the special case where the list is in the "magic" // state of having only the default link in it. In that case // we want to clear the list before adding this link. // - if (owner.links.Count == 1 + if (owner.links.Count == 1 && this[0].Start == 0 - && this[0]._length == -1) { + && this[0]._length == -1) + { owner.links.Clear(); owner.FocusLink = null; @@ -2001,13 +2393,15 @@ public int Add(Link value) { owner.links.Add(value); - if (this.owner.AutoSize) { + if (this.owner.AutoSize) + { LayoutTransaction.DoLayout(this.owner.ParentInternal, this.owner, PropertyNames.Links); this.owner.AdjustSize(); this.owner.Invalidate(); } - if (owner.Links.Count > 1) { + if (owner.Links.Count > 1) + { owner.links.Sort(LinkLabel.linkComparer); } @@ -2016,61 +2410,78 @@ public int Add(Link value) { owner.InvalidateTextLayout(); owner.Invalidate(); - if (owner.Links.Count > 1) { + if (owner.Links.Count > 1) + { return IndexOf(value); } - else { + else + { return 0; } } - - int IList.Add(object value) { - if (value is Link) { + + int IList.Add(object value) + { + if (value is Link) + { return Add((Link)value); } - else { - throw new ArgumentException(SR.LinkLabelBadLink,"value"); + else + { + throw new ArgumentException(SR.LinkLabelBadLink, "value"); } } - - void IList.Insert(int index, object value) { - if (value is Link) { + + void IList.Insert(int index, object value) + { + if (value is Link) + { Add((Link)value); } - else { + else + { throw new ArgumentException(SR.LinkLabelBadLink, "value"); } } - - public bool Contains(Link link) { + + public bool Contains(Link link) + { return owner.links.Contains(link); } /// /// Returns true if the collection contains an item with the specified key, false otherwise. /// - public virtual bool ContainsKey(string key) { - return IsValidIndex(IndexOfKey(key)); + public virtual bool ContainsKey(string key) + { + return IsValidIndex(IndexOfKey(key)); } - - bool IList.Contains(object link) { - if (link is Link) { + + bool IList.Contains(object link) + { + if (link is Link) + { return Contains((Link)link); } - else { + else + { return false; } } - - public int IndexOf(Link link) { + + public int IndexOf(Link link) + { return owner.links.IndexOf(link); } - - int IList.IndexOf(object link) { - if (link is Link) { + + int IList.IndexOf(object link) + { + if (link is Link) + { return IndexOf((Link)link); } - else { + else + { return -1; } } @@ -2078,23 +2489,28 @@ int IList.IndexOf(object link) { /// /// The zero-based index of the first occurrence of value within the entire CollectionBase, if found; otherwise, -1. /// - public virtual int IndexOfKey(string key) { + public virtual int IndexOfKey(string key) + { // Step 0 - Arg validation - if (string.IsNullOrEmpty(key)){ + if (string.IsNullOrEmpty(key)) + { return -1; // we dont support empty or null keys. } // step 1 - check the last cached item if (IsValidIndex(lastAccessedIndex)) { - if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) { + if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) + { return lastAccessedIndex; } } // step 2 - search for the item - for (int i = 0; i < this.Count; i ++) { - if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { + for (int i = 0; i < this.Count; i++) + { + if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) + { lastAccessedIndex = i; return i; } @@ -2108,19 +2524,22 @@ public virtual int IndexOfKey(string key) { /// /// Determines if the index is valid for the collection. /// - private bool IsValidIndex(int index) { + private bool IsValidIndex(int index) + { return ((index >= 0) && (index < this.Count)); } - + /// /// Remove all links from the linkLabel. /// - public virtual void Clear() { + public virtual void Clear() + { bool doLayout = this.owner.links.Count > 0 && this.owner.AutoSize; owner.links.Clear(); - if (doLayout) { + if (doLayout) + { LayoutTransaction.DoLayout(this.owner.ParentInternal, this.owner, PropertyNames.Links); this.owner.AdjustSize(); this.owner.Invalidate(); @@ -2131,28 +2550,35 @@ public virtual void Clear() { owner.Invalidate(); } - void ICollection.CopyTo(Array dest, int index) { + void ICollection.CopyTo(Array dest, int index) + { owner.links.CopyTo(dest, index); } - public IEnumerator GetEnumerator() { - if (owner.links != null) { + public IEnumerator GetEnumerator() + { + if (owner.links != null) + { return owner.links.GetEnumerator(); } - else { + else + { return new Link[0].GetEnumerator(); } } - - public void Remove(Link value) { - if (value.Owner != this.owner) { + public void Remove(Link value) + { + + if (value.Owner != this.owner) + { return; } owner.links.Remove(value); - if (this.owner.AutoSize) { + if (this.owner.AutoSize) + { LayoutTransaction.DoLayout(this.owner.ParentInternal, this.owner, PropertyNames.Links); this.owner.AdjustSize(); this.owner.Invalidate(); @@ -2165,29 +2591,35 @@ public void Remove(Link value) { owner.InvalidateTextLayout(); owner.Invalidate(); - if (owner.FocusLink == null && owner.links.Count > 0) { + if (owner.FocusLink == null && owner.links.Count > 0) + { owner.FocusLink = (Link)owner.links[0]; } } - - public void RemoveAt(int index) { + + public void RemoveAt(int index) + { Remove(this[index]); } - + /// /// Removes the child control with the specified key. /// - public virtual void RemoveByKey(string key) { - int index = IndexOfKey(key); - if (IsValidIndex(index)) { - RemoveAt(index); - } - } - - void IList.Remove(object value) { - if (value is Link) { + public virtual void RemoveByKey(string key) + { + int index = IndexOfKey(key); + if (IsValidIndex(index)) + { + RemoveAt(index); + } + } + + void IList.Remove(object value) + { + if (value is Link) + { Remove((Link)value); - } + } } } @@ -2371,42 +2803,53 @@ int IComparer.Compare(object link1, object link2) } [ComVisible(true)] - internal class LinkLabelAccessibleObject : LabelAccessibleObject { + internal class LinkLabelAccessibleObject : LabelAccessibleObject + { /// /// - public LinkLabelAccessibleObject(LinkLabel owner) : base(owner) { + public LinkLabelAccessibleObject(LinkLabel owner) : base(owner) + { } internal override bool IsIAccessibleExSupported() => true; /// /// - public override AccessibleObject GetChild(int index) { - if (index >= 0 && index < ((LinkLabel)Owner).Links.Count) { + public override AccessibleObject GetChild(int index) + { + if (index >= 0 && index < ((LinkLabel)Owner).Links.Count) + { return new LinkAccessibleObject(((LinkLabel)Owner).Links[index]); } - else { + else + { return null; } } - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_IsEnabledPropertyId) { - if (!Owner.Enabled) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_IsEnabledPropertyId) + { + if (!Owner.Enabled) + { return false; } } return base.GetPropertyValue(propertyID); } - - public override System.Windows.Forms.AccessibleObject HitTest(int x, int y) { + + public override System.Windows.Forms.AccessibleObject HitTest(int x, int y) + { Point p = Owner.PointToClient(new Point(x, y)); Link hit = ((LinkLabel)Owner).PointInLink(p.X, p.Y); - if (hit != null) { + if (hit != null) + { return new LinkAccessibleObject(hit); } - if (this.Bounds.Contains(x, y)) { + if (this.Bounds.Contains(x, y)) + { return this; } return null; @@ -2414,43 +2857,52 @@ public override System.Windows.Forms.AccessibleObject HitTest(int x, int y) { /// /// - public override int GetChildCount() { - return((LinkLabel)Owner).Links.Count; + public override int GetChildCount() + { + return ((LinkLabel)Owner).Links.Count; } } /// /// - [System.Runtime.InteropServices.ComVisible(true)] - internal class LinkAccessibleObject : AccessibleObject { + [System.Runtime.InteropServices.ComVisible(true)] + internal class LinkAccessibleObject : AccessibleObject + { private Link link; - public LinkAccessibleObject(Link link) : base() { + public LinkAccessibleObject(Link link) : base() + { this.link = link; } - public override Rectangle Bounds { - get { + public override Rectangle Bounds + { + get + { Region region = link.VisualRegion; Graphics g = Graphics.FromHwnd(link.Owner.Handle); // Make sure we have a region for this link // - if (region == null) { + if (region == null) + { link.Owner.EnsureRun(g); region = link.VisualRegion; - if (region == null) { + if (region == null) + { g.Dispose(); return Rectangle.Empty; } } Rectangle rect; - try { + try + { rect = Rectangle.Ceiling(region.GetBounds(g)); } - finally { + finally + { g.Dispose(); } @@ -2461,20 +2913,26 @@ public override Rectangle Bounds { } } - public override string DefaultAction { - get { + public override string DefaultAction + { + get + { return SR.AccessibleActionClick; } } - public override string Description { - get { + public override string Description + { + get + { return link.Description; } } - - public override string Name { - get { + + public override string Name + { + get + { string text = link.Owner.Text; string name; @@ -2482,36 +2940,45 @@ public override string Name { // as sometimes the link name in isolation // is unusable when using a screen reader name = text; - if (link.Owner.UseMnemonic) { + if (link.Owner.UseMnemonic) + { name = WindowsFormsUtils.TextWithoutMnemonics(name); } return name; } - set { + set + { base.Name = value; } } - public override AccessibleObject Parent { - get { - return link.Owner.AccessibilityObject; + public override AccessibleObject Parent + { + get + { + return link.Owner.AccessibilityObject; } } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { return AccessibleRole.Link; } } - public override AccessibleStates State { - get { + public override AccessibleStates State + { + get + { AccessibleStates state = AccessibleStates.Focusable; // Selected state // - if (link.Owner.FocusLink == link) { + if (link.Owner.FocusLink == link) + { state |= AccessibleStates.Focused; } @@ -2520,23 +2987,29 @@ public override AccessibleStates State { } } - public override string Value { - get { + public override string Value + { + get + { // Narrator announces Link's text twice, once as a Name property and once as a Value, thus removing value. // Value is optional for this role (Link). return string.Empty; } } - public override void DoDefaultAction() { + public override void DoDefaultAction() + { link.Owner.OnLinkClicked(new LinkLabelLinkClickedEventArgs(link)); } internal override bool IsIAccessibleExSupported() => true; - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_IsEnabledPropertyId) { - if (!link.Owner.Enabled) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_IsEnabledPropertyId) + { + if (!link.Owner.Enabled) + { return false; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabelLinkClickedEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabelLinkClickedEventArgs.cs index e03367884ee..ae97208ef25 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabelLinkClickedEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabelLinkClickedEventArgs.cs @@ -18,13 +18,13 @@ public class LinkLabelLinkClickedEventArgs : EventArgs public LinkLabelLinkClickedEventArgs(LinkLabel.Link link) : this(link, MouseButtons.Left) { } - + public LinkLabelLinkClickedEventArgs(LinkLabel.Link link, MouseButtons button) { Link = link; Button = button; } - + /// /// Gets the that was clicked. /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/LinkUtilities.cs b/src/System.Windows.Forms/src/System/Windows/Forms/LinkUtilities.cs index 8384adb57bf..907b2edb190 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/LinkUtilities.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/LinkUtilities.cs @@ -2,14 +2,16 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { -using System; -using System.Drawing; -using System.Windows.Forms; -using Microsoft.Win32; -using System.Globalization; +namespace System.Windows.Forms +{ + using System; + using System.Drawing; + using System.Windows.Forms; + using Microsoft.Win32; + using System.Globalization; - internal class LinkUtilities { + internal class LinkUtilities + { // IE fonts and colors static Color ielinkColor = Color.Empty; @@ -26,18 +28,21 @@ internal class LinkUtilities { /// Retrieves a named IE color from the registry. There are constants at the top /// of this file of the valid names to retrieve. /// - private static Color GetIEColor(string name) { + private static Color GetIEColor(string name) + { RegistryKey key = Registry.CurrentUser.OpenSubKey(IESettingsRegPath); - if (key != null) { + if (key != null) + { // Since this comes from the registry, be very careful about its contents. // string s = (string)key.GetValue(name); key.Close(); - if (s != null) { - string[] rgbs = s.Split(new char[] {','}); + if (s != null) + { + string[] rgbs = s.Split(new char[] { ',' }); int[] rgb = new int[3]; int nMax = Math.Min(rgb.Length, rgbs.Length); @@ -52,41 +57,54 @@ private static Color GetIEColor(string name) { } } - if (string.Equals(name, IEAnchorColor, StringComparison.OrdinalIgnoreCase)) { + if (string.Equals(name, IEAnchorColor, StringComparison.OrdinalIgnoreCase)) + { return Color.Blue; } - else if (string.Equals(name, IEAnchorColorVisited, StringComparison.OrdinalIgnoreCase)) { + else if (string.Equals(name, IEAnchorColorVisited, StringComparison.OrdinalIgnoreCase)) + { return Color.Purple; } - else if (string.Equals(name, IEAnchorColorHover, StringComparison.OrdinalIgnoreCase)) { + else if (string.Equals(name, IEAnchorColorHover, StringComparison.OrdinalIgnoreCase)) + { return Color.Red; } - else { + else + { return Color.Red; } } - public static Color IELinkColor { - get { - if (ielinkColor.IsEmpty) { + public static Color IELinkColor + { + get + { + if (ielinkColor.IsEmpty) + { ielinkColor = GetIEColor(IEAnchorColor); } return ielinkColor; } } - public static Color IEActiveLinkColor { - get { - if (ieactiveLinkColor.IsEmpty) { + public static Color IEActiveLinkColor + { + get + { + if (ieactiveLinkColor.IsEmpty) + { ieactiveLinkColor = GetIEColor(IEAnchorColorHover); } return ieactiveLinkColor; } } - public static Color IEVisitedLinkColor { - get { - if (ievisitedLinkColor.IsEmpty) { + public static Color IEVisitedLinkColor + { + get + { + if (ievisitedLinkColor.IsEmpty) + { ievisitedLinkColor = GetIEColor(IEAnchorColorVisited); } return ievisitedLinkColor; @@ -106,27 +124,34 @@ public static Color GetVisitedLinkColor() /// /// Retrieves the IE settings for link behavior from the registry. /// - public static LinkBehavior GetIELinkBehavior() { + public static LinkBehavior GetIELinkBehavior() + { RegistryKey key = null; - try { + try + { key = Registry.CurrentUser.OpenSubKey(IEMainRegPath); } - catch (System.Security.SecurityException) { + catch (System.Security.SecurityException) + { // User does not have right to access Registry path HKCU\\Software\\Microsoft\\Internet Explorer\\Main. // Catch SecurityException silently and let the return value fallback to AlwaysUnderline. } - if (key != null) { + if (key != null) + { string s = (string)key.GetValue("Anchor Underline"); key.Close(); - if (s != null && string.Compare(s, "no", true, CultureInfo.InvariantCulture) == 0) { + if (s != null && string.Compare(s, "no", true, CultureInfo.InvariantCulture) == 0) + { return LinkBehavior.NeverUnderline; } - if (s != null && string.Compare(s, "hover", true, CultureInfo.InvariantCulture) == 0) { + if (s != null && string.Compare(s, "hover", true, CultureInfo.InvariantCulture) == 0) + { return LinkBehavior.HoverUnderline; } - else { + else + { return LinkBehavior.AlwaysUnderline; } } @@ -134,19 +159,23 @@ public static LinkBehavior GetIELinkBehavior() { return LinkBehavior.AlwaysUnderline; } - public static void EnsureLinkFonts(Font baseFont, LinkBehavior link, ref Font linkFont, ref Font hoverLinkFont) { - if (linkFont != null && hoverLinkFont != null) { + public static void EnsureLinkFonts(Font baseFont, LinkBehavior link, ref Font linkFont, ref Font hoverLinkFont) + { + if (linkFont != null && hoverLinkFont != null) + { return; } bool underlineLink = true; bool underlineHover = true; - if (link == LinkBehavior.SystemDefault) { + if (link == LinkBehavior.SystemDefault) + { link = GetIELinkBehavior(); } - switch (link) { + switch (link) + { case LinkBehavior.AlwaysUnderline: underlineLink = true; underlineHover = true; @@ -166,33 +195,41 @@ public static void EnsureLinkFonts(Font baseFont, LinkBehavior link, ref Font li // We optimize for the "same" value (never & always) to avoid creating an // extra font object. // - if (underlineHover == underlineLink) { + if (underlineHover == underlineLink) + { FontStyle style = f.Style; - if (underlineHover) { + if (underlineHover) + { style |= FontStyle.Underline; } - else { + else + { style &= ~FontStyle.Underline; } hoverLinkFont = new Font(f, style); linkFont = hoverLinkFont; } - else { + else + { FontStyle hoverStyle = f.Style; - if (underlineHover) { + if (underlineHover) + { hoverStyle |= FontStyle.Underline; } - else { + else + { hoverStyle &= ~FontStyle.Underline; } hoverLinkFont = new Font(f, hoverStyle); FontStyle linkStyle = f.Style; - if (underlineLink) { + if (underlineLink) + { linkStyle |= FontStyle.Underline; } - else { + else + { linkStyle &= ~FontStyle.Underline; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingConverter.cs index 55d8e93857d..a68686409c8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingConverter.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Diagnostics; @@ -11,19 +12,23 @@ namespace System.Windows.Forms { using System.Collections; using System.Globalization; using System.Reflection; - - public class ListBindingConverter : TypeConverter { - + + public class ListBindingConverter : TypeConverter + { + private static Type[] ctorTypes = null; // the list of type of our ctor parameters. private static string[] ctorParamProps = null; // the name of each property to check to see if we need to init with a ctor. /// /// Creates our array of types on demand. /// - private static Type[] ConstructorParamaterTypes { - get { - if (ctorTypes == null) { - ctorTypes = new Type[]{typeof(string), typeof(object), typeof(string), typeof(bool), typeof(DataSourceUpdateMode), typeof(object), typeof(string), typeof(IFormatProvider)}; + private static Type[] ConstructorParamaterTypes + { + get + { + if (ctorTypes == null) + { + ctorTypes = new Type[] { typeof(string), typeof(object), typeof(string), typeof(bool), typeof(DataSourceUpdateMode), typeof(object), typeof(string), typeof(IFormatProvider) }; } return ctorTypes; } @@ -33,27 +38,32 @@ private static Type[] ConstructorParamaterTypes { /// Creates our array of param names on demand. /// - private static string[] ConstructorParameterProperties { - get { - if (ctorParamProps == null) { - ctorParamProps = new string[]{null, null, null, "FormattingEnabled", "DataSourceUpdateMode", "NullValue", "FormatString", "FormatInfo", }; + private static string[] ConstructorParameterProperties + { + get + { + if (ctorParamProps == null) + { + ctorParamProps = new string[] { null, null, null, "FormattingEnabled", "DataSourceUpdateMode", "NullValue", "FormatString", "FormatInfo", }; } return ctorParamProps; } } - - + + /// /// Gets a value indicating whether this converter can /// convert an object to the given destination type using the context. /// - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { - if (destinationType == typeof(InstanceDescriptor)) { + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) + { + if (destinationType == typeof(InstanceDescriptor)) + { return true; } return base.CanConvertTo(context, destinationType); } - + /// /// Converts the given object to another type. The most common types to convert /// are to and from a string object. The default implementation will make a call @@ -61,25 +71,29 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) { + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == null) + { throw new ArgumentNullException(nameof(destinationType)); } - if (destinationType == typeof(InstanceDescriptor) && value is Binding) { + if (destinationType == typeof(InstanceDescriptor) && value is Binding) + { Binding b = (Binding)value; - return GetInstanceDescriptorFromValues(b); + return GetInstanceDescriptorFromValues(b); } - + return base.ConvertTo(context, culture, value, destinationType); } - + /// /// Creates an instance of this type given a set of property values /// for the object. This is useful for objects that are immutable, but still /// want to provide changable properties. /// - public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) { + public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) + { try { return new Binding((string)propertyValues["PropertyName"], @@ -100,7 +114,8 @@ public override object CreateInstance(ITypeDescriptorContext context, IDictionar /// Determines if changing a value on this object should require a call to /// CreateInstance to create a new value. /// - public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) { + public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) + { return true; } @@ -108,7 +123,8 @@ public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) /// Gets the best matching ctor for a given binding and fills it out, based on the /// state of the Binding and the optimal ctor. /// - private InstanceDescriptor GetInstanceDescriptorFromValues(Binding b) { + private InstanceDescriptor GetInstanceDescriptorFromValues(Binding b) + { // The BindingFormattingDialog turns on Binding::FormattingEnabled property. // however, when the user data binds a property using the PropertyBrowser, Binding::FormattingEnabled is set to false @@ -118,19 +134,22 @@ private InstanceDescriptor GetInstanceDescriptorFromValues(Binding b) { bool isComplete = true; int lastItem = ConstructorParameterProperties.Length - 1; - - for (; lastItem >= 0; lastItem--) { - + + for (; lastItem >= 0; lastItem--) + { + // null means no prop is available, we quit here. // - if (ConstructorParameterProperties[lastItem] == null) { + if (ConstructorParameterProperties[lastItem] == null) + { break; } // get the property and see if it needs to be serialized. // PropertyDescriptor prop = TypeDescriptor.GetProperties(b)[ConstructorParameterProperties[lastItem]]; - if (prop != null && prop.ShouldSerializeValue(b)) { + if (prop != null && prop.ShouldSerializeValue(b)) + { break; } } @@ -144,7 +163,8 @@ private InstanceDescriptor GetInstanceDescriptorFromValues(Binding b) { // ConstructorInfo ctor = typeof(Binding).GetConstructor(ctorParams); Debug.Assert(ctor != null, "Failed to find Binding ctor for types!"); - if (ctor == null) { + if (ctor == null) + { isComplete = false; ctor = typeof(Binding).GetConstructor(new Type[] { typeof(string), @@ -156,9 +176,11 @@ private InstanceDescriptor GetInstanceDescriptorFromValues(Binding b) { // object[] values = new object[ctorParams.Length]; - for (int i = 0; i < values.Length; i++) { + for (int i = 0; i < values.Length; i++) + { object val = null; - switch (i) { + switch (i) + { case 0: val = b.PropertyName; break; @@ -178,4 +200,4 @@ private InstanceDescriptor GetInstanceDescriptorFromValues(Binding b) { } } } - + diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingHelper.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingHelper.cs index a3681c06c9b..18c674fc02f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingHelper.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingHelper.cs @@ -2,10 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; - using System.Diagnostics; + using System.Diagnostics; using System.ComponentModel; using System.Collections; using System.Collections.Generic; @@ -14,30 +15,38 @@ namespace System.Windows.Forms { /// /// - public static class ListBindingHelper { + public static class ListBindingHelper + { private static Attribute[] browsableAttribute; - private static Attribute[] BrowsableAttributeList { - get { - if (browsableAttribute == null) { - browsableAttribute = new Attribute[] {new BrowsableAttribute(true)}; + private static Attribute[] BrowsableAttributeList + { + get + { + if (browsableAttribute == null) + { + browsableAttribute = new Attribute[] { new BrowsableAttribute(true) }; } return browsableAttribute; } } - public static object GetList(object list) { - if (list is IListSource) { + public static object GetList(object list) + { + if (list is IListSource) + { return (list as IListSource).GetList(); } - else { + else + { return list; } } - public static object GetList(object dataSource, string dataMember) { + public static object GetList(object dataSource, string dataMember) + { // // The purpose of this method is to find a list, given a 'data source' object and a // decription of some 'data member' property of that object which returns the list. @@ -50,29 +59,34 @@ public static object GetList(object dataSource, string dataMember) { // dataSource = GetList(dataSource); - if (dataSource == null || dataSource is Type || string.IsNullOrEmpty(dataMember)) { + if (dataSource == null || dataSource is Type || string.IsNullOrEmpty(dataMember)) + { return dataSource; } PropertyDescriptorCollection dsProps = ListBindingHelper.GetListItemProperties(dataSource); PropertyDescriptor dmProp = dsProps.Find(dataMember, true); - if (dmProp == null) { + if (dmProp == null) + { throw new System.ArgumentException(string.Format(SR.DataSourceDataMemberPropNotFound, dataMember)); } object currentItem; - if (dataSource is ICurrencyManagerProvider) { + if (dataSource is ICurrencyManagerProvider) + { // Data source is another BindingSource so ask for its current item CurrencyManager cm = (dataSource as ICurrencyManagerProvider).CurrencyManager; bool currentKnown = (cm != null && cm.Position >= 0 && cm.Position <= cm.Count - 1); currentItem = currentKnown ? cm.Current : null; } - else if (dataSource is IEnumerable) { + else if (dataSource is IEnumerable) + { // Data source is an enumerable list, so walk to the first item currentItem = GetFirstItemByEnumerable(dataSource as IEnumerable); } - else { + else + { // Data source is not a list, so just use the data source itself currentItem = dataSource; } @@ -81,18 +95,22 @@ public static object GetList(object dataSource, string dataMember) { return (currentItem == null) ? null : dmProp.GetValue(currentItem); } - public static string GetListName(object list, PropertyDescriptor[] listAccessors) { + public static string GetListName(object list, PropertyDescriptor[] listAccessors) + { string name; - if (list == null) { + if (list == null) + { return string.Empty; } ITypedList typedList = list as ITypedList; - if (typedList != null) { + if (typedList != null) + { // Use typed list name = typedList.GetListName(listAccessors); } - else { + else + { Type type; // We always resolve via type in this case (not an instance) if (listAccessors == null || listAccessors.Length == 0 || listAccessors[0] == null) @@ -101,11 +119,13 @@ public static string GetListName(object list, PropertyDescriptor[] listAccessors { type = listAsType; } - else { + else + { type = list.GetType(); } } - else { + else + { // We don't walk down - always use type name type = listAccessors[0].PropertyType; } @@ -116,24 +136,32 @@ public static string GetListName(object list, PropertyDescriptor[] listAccessors return name; } - public static PropertyDescriptorCollection GetListItemProperties(object list) { + public static PropertyDescriptorCollection GetListItemProperties(object list) + { PropertyDescriptorCollection pdc; - if (list == null) { + if (list == null) + { return new PropertyDescriptorCollection(null); - } else if (list is Type) { + } + else if (list is Type) + { pdc = GetListItemPropertiesByType(list as Type); } - else { + else + { object target = GetList(list); - if (target is ITypedList) { + if (target is ITypedList) + { pdc = (target as ITypedList).GetItemProperties(null); } - else if (target is IEnumerable) { + else if (target is IEnumerable) + { pdc = GetListItemPropertiesByEnumerable(target as IEnumerable); } - else { + else + { pdc = TypeDescriptor.GetProperties(target); } } @@ -154,26 +182,31 @@ public static PropertyDescriptorCollection GetListItemProperties(object list, Pr object target = GetList(list); - if (target is ITypedList typedList) { + if (target is ITypedList typedList) + { return typedList.GetItemProperties(listAccessors); } - else if (target is IEnumerable enumerable) { + else if (target is IEnumerable enumerable) + { return GetListItemPropertiesByEnumerable(enumerable, listAccessors, 0); } - + return GetListItemPropertiesByInstance(target, listAccessors, 0); } - public static PropertyDescriptorCollection GetListItemProperties(object dataSource, string dataMember, PropertyDescriptor[] listAccessors) { + public static PropertyDescriptorCollection GetListItemProperties(object dataSource, string dataMember, PropertyDescriptor[] listAccessors) + { dataSource = GetList(dataSource); - if (!string.IsNullOrEmpty(dataMember)) { + if (!string.IsNullOrEmpty(dataMember)) + { // Find the property on the data source specified by the data member PropertyDescriptorCollection dsProps = ListBindingHelper.GetListItemProperties(dataSource); PropertyDescriptor dmProp = dsProps.Find(dataMember, true); // Error: Property not found - data member is invalid - if (dmProp == null) { + if (dmProp == null) + { throw new System.ArgumentException(string.Format(SR.DataSourceDataMemberPropNotFound, dataMember)); } @@ -181,7 +214,8 @@ public static PropertyDescriptorCollection GetListItemProperties(object dataSour int len = (listAccessors == null) ? 1 : (listAccessors.Length + 1); PropertyDescriptor[] listAccessors2 = new PropertyDescriptor[len]; listAccessors2[0] = dmProp; - for (int i = 1; i < len; ++i) { + for (int i = 1; i < len; ++i) + { listAccessors2[i] = listAccessors[i - 1]; } @@ -228,56 +262,67 @@ public static Type GetListItemType(object list) { return GetListItemTypeByEnumerable(enumerable); } - + return listType; } // Create an object of the given type. Throw an exception if this fails. [ExcludeFromCodeCoverage] - private static object CreateInstanceOfType(Type type) { + private static object CreateInstanceOfType(Type type) + { object instancedObject = null; Exception instanceException = null; - try { + try + { instancedObject = Activator.CreateInstance(type); } - catch (TargetInvocationException ex) { + catch (TargetInvocationException ex) + { instanceException = ex; // Default ctor threw an exception } - catch (MethodAccessException ex) { + catch (MethodAccessException ex) + { instanceException = ex; // Default ctor was not public } - catch (MissingMethodException ex) { + catch (MissingMethodException ex) + { instanceException = ex; // No default ctor defined } - if (instanceException != null) { + if (instanceException != null) + { throw new NotSupportedException(SR.BindingSourceInstanceError, instanceException); } return instancedObject; } - public static Type GetListItemType(object dataSource, string dataMember) { + public static Type GetListItemType(object dataSource, string dataMember) + { // No data source - if (dataSource == null) { + if (dataSource == null) + { return typeof(object); } // No data member - Determine item type directly from data source - if (string.IsNullOrEmpty(dataMember)) { + if (string.IsNullOrEmpty(dataMember)) + { return GetListItemType(dataSource); } // Get list item properties for this data source PropertyDescriptorCollection dsProps = GetListItemProperties(dataSource); - if (dsProps == null) { + if (dsProps == null) + { return typeof(object); } // Find the property specified by the data member PropertyDescriptor dmProp = dsProps.Find(dataMember, true); - if (dmProp == null || dmProp.PropertyType is ICustomTypeDescriptor) { + if (dmProp == null || dmProp.PropertyType is ICustomTypeDescriptor) + { return typeof(object); } @@ -285,10 +330,12 @@ public static Type GetListItemType(object dataSource, string dataMember) { return GetListItemType(dmProp.PropertyType); } - private static string GetListNameFromType(Type type) { + private static string GetListNameFromType(Type type) + { string name; - if (typeof(Array).IsAssignableFrom(type)) { + if (typeof(Array).IsAssignableFrom(type)) + { // If the type is Customers[], this will return "Customers" Type elementType = type.GetElementType(); if (elementType != null) @@ -301,7 +348,8 @@ private static string GetListNameFromType(Type type) { name = type.Name; } } - else if (typeof(IList).IsAssignableFrom(type)) { + else if (typeof(IList).IsAssignableFrom(type)) + { // If the type is BindingList, TCollection, TList (or equiv), this will return "T" PropertyInfo indexer = GetTypedIndexer(type); if (indexer != null) @@ -313,7 +361,8 @@ private static string GetListNameFromType(Type type) { name = type.Name; } } - else { + else + { // Fallback to type name name = type.Name; } @@ -321,7 +370,8 @@ private static string GetListNameFromType(Type type) { return name; } - private static PropertyDescriptorCollection GetListItemPropertiesByType(Type type, PropertyDescriptor[] listAccessors, int startIndex) { + private static PropertyDescriptorCollection GetListItemPropertiesByType(Type type, PropertyDescriptor[] listAccessors, int startIndex) + { PropertyDescriptorCollection pdc = null; if (listAccessors[startIndex] == null) { @@ -340,11 +390,13 @@ private static PropertyDescriptorCollection GetListItemPropertiesByType(Type typ // GetListItemProperties(PDForOrders.PropertyType, listAccessors, startIndex++) startIndex = startIndex + 1; - if (startIndex >= listAccessors.Length) { + if (startIndex >= listAccessors.Length) + { // Last item, return shape of item pdc = GetListItemProperties(subType); } - else { + else + { // Walk down the tree pdc = GetListItemPropertiesByType(subType, listAccessors, startIndex); } @@ -352,7 +404,8 @@ private static PropertyDescriptorCollection GetListItemPropertiesByType(Type typ return pdc; } - private static PropertyDescriptorCollection GetListItemPropertiesByEnumerable(IEnumerable iEnumerable, PropertyDescriptor[] listAccessors, int startIndex) { + private static PropertyDescriptorCollection GetListItemPropertiesByEnumerable(IEnumerable iEnumerable, PropertyDescriptor[] listAccessors, int startIndex) + { PropertyDescriptorCollection pdc = null; object subList = null; // Walk down the tree - first try and get the value @@ -369,32 +422,39 @@ private static PropertyDescriptorCollection GetListItemPropertiesByEnumerable(IE // object instance = GetFirstItemByEnumerable(iEnumerable); - if (instance != null) { + if (instance != null) + { // This calls GetValue(Customers[0], "Orders") - or Customers[0].Orders // If this list is non-null, it is an instance of Orders (Order[]) for the first customer subList = GetList(listAccessors[startIndex].GetValue(instance)); } - if (null == subList) { + if (null == subList) + { // Can't get shape by Instance, try by Type pdc = GetListItemPropertiesByType(listAccessors[startIndex].PropertyType, listAccessors, startIndex); } - else { + else + { // We have the Instance (e.g. Orders) ++startIndex; IEnumerable ienumerableSubList = subList as IEnumerable; - if (ienumerableSubList != null) { - if (startIndex == listAccessors.Length) { + if (ienumerableSubList != null) + { + if (startIndex == listAccessors.Length) + { // Last one, so get the shape pdc = GetListItemPropertiesByEnumerable(ienumerableSubList); } - else { + else + { // Looks like they want more (e.g. Customers.Orders.OrderDetails) pdc = GetListItemPropertiesByEnumerable(ienumerableSubList, listAccessors, startIndex); } } - else { + else + { // Not a list, so switch to a non-list based method of retrieving properties pdc = GetListItemPropertiesByInstance(subList, listAccessors, startIndex); } @@ -403,7 +463,8 @@ private static PropertyDescriptorCollection GetListItemPropertiesByEnumerable(IE return pdc; } - private static Type GetListItemTypeByEnumerable(IEnumerable iEnumerable) { + private static Type GetListItemTypeByEnumerable(IEnumerable iEnumerable) + { object instance = GetFirstItemByEnumerable(iEnumerable); return (instance != null) ? instance.GetType() : typeof(object); } @@ -448,7 +509,7 @@ private static PropertyDescriptorCollection GetListItemPropertiesByInstance(obje return GetListItemProperties(value, accessors); } } - + return TypeDescriptor.GetProperties(target, BrowsableAttributeList); } @@ -458,21 +519,27 @@ private static bool IsListBasedType(Type type) // check for IList, ITypedList, IListSource if (typeof(IList).IsAssignableFrom(type) || typeof(ITypedList).IsAssignableFrom(type) || - typeof(IListSource).IsAssignableFrom(type)) { + typeof(IListSource).IsAssignableFrom(type)) + { return true; } // check for IList<>: - if (type.IsGenericType && !type.IsGenericTypeDefinition) { - if (typeof(IList<>).IsAssignableFrom(type.GetGenericTypeDefinition())) { + if (type.IsGenericType && !type.IsGenericTypeDefinition) + { + if (typeof(IList<>).IsAssignableFrom(type.GetGenericTypeDefinition())) + { return true; } } // check for SomeObject : IList / SomeObject : IList<(SpecificListObjectType)> - foreach (Type curInterface in type.GetInterfaces()) { - if (curInterface.IsGenericType) { - if (typeof(IList<>).IsAssignableFrom(curInterface.GetGenericTypeDefinition())) { + foreach (Type curInterface in type.GetInterfaces()) + { + if (curInterface.IsGenericType) + { + if (typeof(IList<>).IsAssignableFrom(curInterface.GetGenericTypeDefinition())) + { return true; } } @@ -500,17 +567,21 @@ private static PropertyInfo GetTypedIndexer(Type type) { PropertyInfo indexer = null; - if (!IsListBasedType(type)) { + if (!IsListBasedType(type)) + { return null; } System.Reflection.PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); - for (int idx = 0; idx < props.Length; idx++) { - if (props[idx].GetIndexParameters().Length > 0 && props[idx].PropertyType != typeof(object)) { + for (int idx = 0; idx < props.Length; idx++) + { + if (props[idx].GetIndexParameters().Length > 0 && props[idx].PropertyType != typeof(object)) + { indexer = props[idx]; //Prefer the standard indexer, if there is one - if (indexer.Name == "Item") { + if (indexer.Name == "Item") + { break; } } @@ -519,26 +590,33 @@ private static PropertyInfo GetTypedIndexer(Type type) return indexer; } - private static PropertyDescriptorCollection GetListItemPropertiesByType(Type type) { + private static PropertyDescriptorCollection GetListItemPropertiesByType(Type type) + { return TypeDescriptor.GetProperties(GetListItemType(type), BrowsableAttributeList); } - private static PropertyDescriptorCollection GetListItemPropertiesByEnumerable(IEnumerable enumerable) { + private static PropertyDescriptorCollection GetListItemPropertiesByEnumerable(IEnumerable enumerable) + { PropertyDescriptorCollection pdc = null; Type targetType = enumerable.GetType(); - if (typeof(Array).IsAssignableFrom(targetType)) { + if (typeof(Array).IsAssignableFrom(targetType)) + { pdc = TypeDescriptor.GetProperties(targetType.GetElementType(), BrowsableAttributeList); } - else { + else + { ITypedList typedListEnumerable = enumerable as ITypedList; - if (typedListEnumerable != null) { + if (typedListEnumerable != null) + { pdc = typedListEnumerable.GetItemProperties(null); } - else { + else + { PropertyInfo indexer = GetTypedIndexer(targetType); - if (indexer != null && !typeof(ICustomTypeDescriptor).IsAssignableFrom(indexer.PropertyType)) { + if (indexer != null && !typeof(ICustomTypeDescriptor).IsAssignableFrom(indexer.PropertyType)) + { Type type = indexer.PropertyType; pdc = TypeDescriptor.GetProperties(type, BrowsableAttributeList); @@ -574,40 +652,49 @@ private static PropertyDescriptorCollection GetListItemPropertiesByEnumerable(IE // See if we were successful - if not, return the shape of the first // item in the list - if (null == pdc) { + if (null == pdc) + { object instance = GetFirstItemByEnumerable(enumerable); - if (enumerable is string) { + if (enumerable is string) + { pdc = TypeDescriptor.GetProperties(enumerable, BrowsableAttributeList); } - else if (instance == null) { + else if (instance == null) + { pdc = new PropertyDescriptorCollection(null); - } - else { + } + else + { pdc = TypeDescriptor.GetProperties(instance, BrowsableAttributeList); - if (!(enumerable is IList) && pdc.Count == 0) { + if (!(enumerable is IList) && pdc.Count == 0) + { pdc = TypeDescriptor.GetProperties(enumerable, BrowsableAttributeList); } } - + } // Return results return pdc; } - private static object GetFirstItemByEnumerable(IEnumerable enumerable) { + private static object GetFirstItemByEnumerable(IEnumerable enumerable) + { object instance = null; - if (enumerable is IList) { + if (enumerable is IList) + { // If the list supports IList (which is a superset of IEnumerable), then try to use its IList indexer // to get the first item, since some ILists don't support use of their plain IEnumerable interface. IList list = enumerable as IList; instance = (list.Count > 0) ? list[0] : null; } - else { + else + { // Otherwise use the enumerator to get the first item... - try { + try + { IEnumerator listEnumerator = enumerable.GetEnumerator(); if (listEnumerator == null) { @@ -622,7 +709,8 @@ private static object GetFirstItemByEnumerable(IEnumerable enumerable) { // after we are done w/ the enumerator, reset it listEnumerator.Reset(); } - catch (NotSupportedException) { + catch (NotSupportedException) + { // Some data sources do not offer a full implementation of IEnumerable. For example, SqlDataReader // only supports reading forwards through items, so it does not support calls to IEnumerable.Reset(). instance = null; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs index 44c1d553876..5733d3cf7a5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; @@ -54,7 +55,8 @@ namespace System.Windows.Forms { DefaultBindingProperty(nameof(SelectedValue)), SRDescription(nameof(SR.DescriptionListBox)) ] - public class ListBox : ListControl { + public class ListBox : ListControl + { /// /// while doing a search, if no matches are found, this is returned /// @@ -66,8 +68,8 @@ public class ListBox : ListControl { public const int DefaultItemHeight = 13; private static readonly object EVENT_SELECTEDINDEXCHANGED = new object(); - private static readonly object EVENT_DRAWITEM = new object(); - private static readonly object EVENT_MEASUREITEM = new object(); + private static readonly object EVENT_DRAWITEM = new object(); + private static readonly object EVENT_MEASUREITEM = new object(); SelectedObjectCollection selectedItems; SelectedIndexCollection selectedIndices; @@ -96,7 +98,7 @@ public class ListBox : ListControl { DrawMode drawMode = System.Windows.Forms.DrawMode.Normal; BorderStyle borderStyle = System.Windows.Forms.BorderStyle.Fixed3D; SelectionMode selectionMode = System.Windows.Forms.SelectionMode.One; - + SelectionMode cachedSelectionMode = System.Windows.Forms.SelectionMode.One; //We need to know that we are in middle of handleRecreate through Setter of SelectionMode. //In this case we set a bool denoting that we are changing SelectionMode and @@ -134,13 +136,14 @@ public class ListBox : ListControl { /// /// Creates a basic win32 list box with default values for everything. /// - public ListBox() : base() { - SetStyle(ControlStyles.UserPaint | - ControlStyles.StandardClick | + public ListBox() : base() + { + SetStyle(ControlStyles.UserPaint | + ControlStyles.StandardClick | ControlStyles.UseTextForAccessibility, false); // this class overrides GetPreferredSizeCore, let Control automatically cache the result - SetState2(STATE2_USEPREFERREDSIZECACHE, true); + SetState2(STATE2_USEPREFERREDSIZECACHE, true); SetBounds(0, 0, 120, 96); @@ -149,14 +152,17 @@ public ListBox() : base() { PrepareForDrawing(); } - protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) { + protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) + { base.RescaleConstantsForDpi(deviceDpiOld, deviceDpiNew); PrepareForDrawing(); } - private void PrepareForDrawing() { + private void PrepareForDrawing() + { // Scale paddings - if (DpiHelper.IsScalingRequirementMet) { + if (DpiHelper.IsScalingRequirementMet) + { scaledListItemStartPosition = LogicalToDeviceUnits(defaultListItemStartPos); // height inlude 2 borders ( top and bottom). we are using multiplication by 2 instead of scaling doubled value to get an even number @@ -166,48 +172,61 @@ private void PrepareForDrawing() { } } - public override Color BackColor { - get { - if (ShouldSerializeBackColor()) { + public override Color BackColor + { + get + { + if (ShouldSerializeBackColor()) + { return base.BackColor; } - else { + else + { return SystemColors.Window; } } - set { + set + { base.BackColor = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged { + new public event EventHandler BackgroundImageChanged + { add => base.BackgroundImageChanged += value; remove => base.BackgroundImageChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { + new public event EventHandler BackgroundImageLayoutChanged + { add => base.BackgroundImageLayoutChanged += value; remove => base.BackgroundImageLayoutChanged -= value; } @@ -222,27 +241,34 @@ public override ImageLayout BackgroundImageLayout { DispId(NativeMethods.ActiveX.DISPID_BORDERSTYLE), SRDescription(nameof(SR.ListBoxBorderDescr)) ] - public BorderStyle BorderStyle { - get { + public BorderStyle BorderStyle + { + get + { return borderStyle; } - set { + set + { //valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(BorderStyle)); } - if (value != borderStyle) { + if (value != borderStyle) + { borderStyle = value; RecreateHandle(); // Avoid the listbox and textbox behavior in Collection editors // integralHeightAdjust = true; - try { + try + { Height = requestedHeight; } - finally { + finally + { integralHeightAdjust = false; } } @@ -257,25 +283,31 @@ public BorderStyle BorderStyle { DefaultValue(0), SRDescription(nameof(SR.ListBoxColumnWidthDescr)) ] - public int ColumnWidth { - get { + public int ColumnWidth + { + get + { return columnWidth; } - set { + set + { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(value), value, 0)); } - if (columnWidth != value) { + if (columnWidth != value) + { columnWidth = value; // if it's zero, we need to reset, and only way to do // that is to recreate the handle. - if (columnWidth == 0) { + if (columnWidth == 0) + { RecreateHandle(); } - else if (IsHandleCreated) { + else if (IsHandleCreated) + { SendMessage(NativeMethods.LB_SETCOLUMNWIDTH, columnWidth, 0); } } @@ -288,17 +320,23 @@ public int ColumnWidth { /// however, forget to call base.getCreateParams() first to get the struct /// filled up with the basic info. /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ClassName = "LISTBOX"; cp.Style |= NativeMethods.WS_VSCROLL | NativeMethods.LBS_NOTIFY | NativeMethods.LBS_HASSTRINGS; - if (scrollAlwaysVisible) cp.Style |= NativeMethods.LBS_DISABLENOSCROLL; - if (!integralHeight) cp.Style |= NativeMethods.LBS_NOINTEGRALHEIGHT; - if (useTabStops) cp.Style |= NativeMethods.LBS_USETABSTOPS; - - switch (borderStyle) { + if (scrollAlwaysVisible) + cp.Style |= NativeMethods.LBS_DISABLENOSCROLL; + if (!integralHeight) + cp.Style |= NativeMethods.LBS_NOINTEGRALHEIGHT; + if (useTabStops) + cp.Style |= NativeMethods.LBS_USETABSTOPS; + + switch (borderStyle) + { case BorderStyle.Fixed3D: cp.ExStyle |= NativeMethods.WS_EX_CLIENTEDGE; break; @@ -307,14 +345,17 @@ protected override CreateParams CreateParams { break; } - if (multiColumn) { + if (multiColumn) + { cp.Style |= NativeMethods.LBS_MULTICOLUMN | NativeMethods.WS_HSCROLL; } - else if (horizontalScrollbar) { + else if (horizontalScrollbar) + { cp.Style |= NativeMethods.WS_HSCROLL; } - switch (selectionMode) { + switch (selectionMode) + { case SelectionMode.None: cp.Style |= NativeMethods.LBS_NOSEL; break; @@ -328,7 +369,8 @@ protected override CreateParams CreateParams { break; } - switch (drawMode) { + switch (drawMode) + { case DrawMode.Normal: break; case DrawMode.OwnerDrawFixed: @@ -353,20 +395,26 @@ protected override CreateParams CreateParams { DefaultValue(false), Browsable(false) ] - public bool UseCustomTabOffsets { - get { + public bool UseCustomTabOffsets + { + get + { return useCustomTabOffsets; } - set { - if (useCustomTabOffsets != value) { + set + { + if (useCustomTabOffsets != value) + { useCustomTabOffsets = value; RecreateHandle(); } } } - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(120, 96); } } @@ -382,24 +430,30 @@ protected override Size DefaultSize { SRDescription(nameof(SR.ListBoxDrawModeDescr)), RefreshProperties(RefreshProperties.Repaint) ] - public virtual DrawMode DrawMode { - get { + public virtual DrawMode DrawMode + { + get + { return drawMode; } - set { + set + { //valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)DrawMode.Normal, (int)DrawMode.OwnerDrawVariable)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DrawMode)); } - if (drawMode != value) { - if (MultiColumn && value == DrawMode.OwnerDrawVariable) { + if (drawMode != value) + { + if (MultiColumn && value == DrawMode.OwnerDrawVariable) + { throw new ArgumentException(SR.ListBoxVarHeightMultiCol, "value"); } drawMode = value; RecreateHandle(); - if (drawMode == DrawMode.OwnerDrawVariable) { + if (drawMode == DrawMode.OwnerDrawVariable) + { // Force a layout after RecreateHandle() completes because now // the LB is definitely fully populated and can report a preferred size accurately. LayoutTransaction.DoLayoutIf(AutoSize, this.ParentInternal, this, PropertyNames.DrawMode); @@ -410,10 +464,13 @@ public virtual DrawMode DrawMode { // Used internally to find the currently focused item // - internal int FocusedIndex { - get { - if (IsHandleCreated) { - return unchecked( (int) (long)SendMessage(NativeMethods.LB_GETCARETINDEX, 0, 0)); + internal int FocusedIndex + { + get + { + if (IsHandleCreated) + { + return unchecked((int)(long)SendMessage(NativeMethods.LB_GETCARETINDEX, 0, 0)); } return -1; @@ -425,14 +482,18 @@ internal int FocusedIndex { // the height of all the items to exceed the new height of the control. This is a bug in // the control, but can be easily worked around by removing and re-adding all the items. - public override Font Font { - get { + public override Font Font + { + get + { return base.Font; } - set { + set + { base.Font = value; - if (false == integralHeight) { + if (false == integralHeight) + { // Refresh the list to force the scroll bars to display // when the integral height is false. RefreshItems(); @@ -440,16 +501,21 @@ public override Font Font { } } - public override Color ForeColor { - get { - if (ShouldSerializeForeColor()) { + public override Color ForeColor + { + get + { + if (ShouldSerializeForeColor()) + { return base.ForeColor; } - else { + else + { return SystemColors.WindowText; } } - set { + set + { base.ForeColor = value; } } @@ -464,13 +530,17 @@ public override Color ForeColor { Localizable(true), SRDescription(nameof(SR.ListBoxHorizontalExtentDescr)) ] - public int HorizontalExtent { - get { + public int HorizontalExtent + { + get + { return horizontalExtent; } - set { - if (value != horizontalExtent) { + set + { + if (value != horizontalExtent) + { horizontalExtent = value; UpdateHorizontalExtent(); } @@ -490,13 +560,17 @@ public int HorizontalExtent { Localizable(true), SRDescription(nameof(SR.ListBoxHorizontalScrollbarDescr)) ] - public bool HorizontalScrollbar { - get { + public bool HorizontalScrollbar + { + get + { return horizontalScrollbar; } - set { - if (value != horizontalScrollbar) { + set + { + if (value != horizontalScrollbar) + { horizontalScrollbar = value; // There seems to be a bug in the native ListBox in that the addition @@ -508,7 +582,8 @@ public bool HorizontalScrollbar { // Only need to recreate the handle if not MultiColumn // (HorizontalScrollbar has no effect on a MultiColumn listbox) // - if (!MultiColumn) { + if (!MultiColumn) + { RecreateHandle(); } } @@ -528,23 +603,29 @@ public bool HorizontalScrollbar { SRDescription(nameof(SR.ListBoxIntegralHeightDescr)), RefreshProperties(RefreshProperties.Repaint) ] - public bool IntegralHeight { - get { + public bool IntegralHeight + { + get + { return integralHeight; } - set { - if (integralHeight != value) { + set + { + if (integralHeight != value) + { integralHeight = value; RecreateHandle(); // Avoid the listbox and textbox behaviour in Collection editors // integralHeightAdjust = true; - try { + try + { Height = requestedHeight; } - finally { + finally + { integralHeightAdjust = false; } } @@ -563,29 +644,37 @@ public bool IntegralHeight { SRDescription(nameof(SR.ListBoxItemHeightDescr)), RefreshProperties(RefreshProperties.Repaint) ] - public virtual int ItemHeight { - get { + public virtual int ItemHeight + { + get + { if (drawMode == DrawMode.OwnerDrawFixed || - drawMode == DrawMode.OwnerDrawVariable) { + drawMode == DrawMode.OwnerDrawVariable) + { return itemHeight; } return GetItemHeight(0); } - set { - if (value < 1 || value > 255) { + set + { + if (value < 1 || value > 255) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidExBoundArgument, nameof(ItemHeight), value, 0, 256)); } - if (itemHeight != value) { + if (itemHeight != value) + { itemHeight = value; - if (drawMode == DrawMode.OwnerDrawFixed && IsHandleCreated) { + if (drawMode == DrawMode.OwnerDrawFixed && IsHandleCreated) + { BeginUpdate(); SendMessage(NativeMethods.LB_SETITEMHEIGHT, 0, value); // Changing the item height might require a resize for IntegralHeight list boxes // - if (IntegralHeight) { + if (IntegralHeight) + { Size oldSize = Size; Size = new Size(oldSize.Width + 1, oldSize.Height); Size = oldSize; @@ -608,9 +697,12 @@ public virtual int ItemHeight { Editor("System.Windows.Forms.Design.ListControlStringCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), MergableProperty(false) ] - public ObjectCollection Items { - get { - if (itemsCollection == null) { + public ObjectCollection Items + { + get + { + if (itemsCollection == null) + { itemsCollection = CreateItemCollection(); } return itemsCollection; @@ -619,20 +711,25 @@ public ObjectCollection Items { // Computes the maximum width of all items in the ListBox // - internal virtual int MaxItemWidth { - get { + internal virtual int MaxItemWidth + { + get + { - if (horizontalExtent > 0) { + if (horizontalExtent > 0) + { return horizontalExtent; } - if (DrawMode != DrawMode.Normal) { + if (DrawMode != DrawMode.Normal) + { return -1; } // Return cached maxWidth if available // - if (maxWidth > -1) { + if (maxWidth > -1) + { return maxWidth; } @@ -654,13 +751,18 @@ internal virtual int MaxItemWidth { DefaultValue(false), SRDescription(nameof(SR.ListBoxMultiColumnDescr)) ] - public bool MultiColumn { - get { + public bool MultiColumn + { + get + { return multiColumn; } - set { - if (multiColumn != value) { - if (value && drawMode == DrawMode.OwnerDrawVariable) { + set + { + if (multiColumn != value) + { + if (value && drawMode == DrawMode.OwnerDrawVariable) + { throw new ArgumentException(SR.ListBoxVarHeightMultiCol, "value"); } multiColumn = value; @@ -677,32 +779,41 @@ public bool MultiColumn { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ListBoxPreferredHeightDescr)) ] - public int PreferredHeight { - get { + public int PreferredHeight + { + get + { int height = 0; - if (drawMode == DrawMode.OwnerDrawVariable) { + if (drawMode == DrawMode.OwnerDrawVariable) + { // don't try to get item heights from the LB when items haven't been // added to the LB yet. Just return current height. - if (RecreatingHandle || GetState(STATE_CREATINGHANDLE)) { + if (RecreatingHandle || GetState(STATE_CREATINGHANDLE)) + { height = this.Height; } - else { - if (itemsCollection != null) { + else + { + if (itemsCollection != null) + { int cnt = itemsCollection.Count; - for (int i = 0; i < cnt; i++) { + for (int i = 0; i < cnt; i++) + { height += GetItemHeight(i); } } } } - else { + else + { //When the list is empty, we don't want to multiply by 0 here. int cnt = (itemsCollection == null || itemsCollection.Count == 0) ? 1 : itemsCollection.Count; height = GetItemHeight(0) * cnt; } - if (borderStyle != BorderStyle.None) { + if (borderStyle != BorderStyle.None) + { height += SystemInformation.BorderSize.Height * 4 + 3; } @@ -741,12 +852,16 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) Localizable(true), SRDescription(nameof(SR.ListBoxScrollIsVisibleDescr)) ] - public bool ScrollAlwaysVisible { - get { + public bool ScrollAlwaysVisible + { + get + { return scrollAlwaysVisible; } - set { - if (scrollAlwaysVisible != value) { + set + { + if (scrollAlwaysVisible != value) + { scrollAlwaysVisible = value; RecreateHandle(); } @@ -757,8 +872,10 @@ public bool ScrollAlwaysVisible { /// Indicates whether list currently allows selection of list items. /// For ListBox, this returns true unless SelectionMode is SelectionMode.None. /// - protected override bool AllowSelection { - get { + protected override bool AllowSelection + { + get + { return selectionMode != SelectionMode.None; } } @@ -777,68 +894,85 @@ protected override bool AllowSelection { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ListBoxSelectedIndexDescr)) ] - public override int SelectedIndex { - get { + public override int SelectedIndex + { + get + { SelectionMode current = (selectionModeChanging) ? cachedSelectionMode : selectionMode; - - if (current == SelectionMode.None) { + + if (current == SelectionMode.None) + { return -1; } - if (current == SelectionMode.One && IsHandleCreated) { - return unchecked( (int) (long)SendMessage(NativeMethods.LB_GETCURSEL, 0, 0)); + if (current == SelectionMode.One && IsHandleCreated) + { + return unchecked((int)(long)SendMessage(NativeMethods.LB_GETCURSEL, 0, 0)); } - if (itemsCollection != null && SelectedItems.Count > 0) { + if (itemsCollection != null && SelectedItems.Count > 0) + { return Items.IndexOfIdentifier(SelectedItems.GetObjectAt(0)); } return -1; } - set { + set + { int itemCount = (itemsCollection == null) ? 0 : itemsCollection.Count; - if (value < -1 || value >= itemCount) { + if (value < -1 || value >= itemCount) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(SelectedIndex), value)); } - if (selectionMode == SelectionMode.None) { + if (selectionMode == SelectionMode.None) + { throw new ArgumentException(SR.ListBoxInvalidSelectionMode, nameof(value)); } - if (selectionMode == SelectionMode.One && value != -1) { + if (selectionMode == SelectionMode.One && value != -1) + { // Single select an individual value. int currentIndex = SelectedIndex; - if (currentIndex != value) { - if (currentIndex != -1) { + if (currentIndex != value) + { + if (currentIndex != -1) + { SelectedItems.SetSelected(currentIndex, false); } SelectedItems.SetSelected(value, true); - if (IsHandleCreated) { + if (IsHandleCreated) + { NativeSetSelected(value, true); } OnSelectedIndexChanged(EventArgs.Empty); } } - else if (value == -1) { - if (SelectedIndex != -1) { + else if (value == -1) + { + if (SelectedIndex != -1) + { ClearSelected(); // ClearSelected raises OnSelectedIndexChanged for us } } - else { - if (!SelectedItems.GetSelected(value)) { + else + { + if (!SelectedItems.GetSelected(value)) + { // Select this item while keeping any previously selected items selected. // SelectedItems.SetSelected(value, true); - if (IsHandleCreated) { + if (IsHandleCreated) + { NativeSetSelected(value, true); } OnSelectedIndexChanged(EventArgs.Empty); @@ -857,9 +991,12 @@ public override int SelectedIndex { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ListBoxSelectedIndicesDescr)) ] - public SelectedIndexCollection SelectedIndices { - get { - if (selectedIndices == null) { + public SelectedIndexCollection SelectedIndices + { + get + { + if (selectedIndices == null) + { selectedIndices = new SelectedIndexCollection(this); } return selectedIndices; @@ -880,23 +1017,31 @@ public SelectedIndexCollection SelectedIndices { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ListBoxSelectedItemDescr)) ] - public object SelectedItem { - get { - if (SelectedItems.Count > 0) { + public object SelectedItem + { + get + { + if (SelectedItems.Count > 0) + { return SelectedItems[0]; } return null; } - set { - if (itemsCollection != null) { - if (value != null) { + set + { + if (itemsCollection != null) + { + if (value != null) + { int index = itemsCollection.IndexOf(value); - if (index != -1) { + if (index != -1) + { SelectedIndex = index; } } - else { + else + { SelectedIndex = -1; } } @@ -911,9 +1056,12 @@ public object SelectedItem { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ListBoxSelectedItemsDescr)) ] - public SelectedObjectCollection SelectedItems { - get { - if (selectedItems == null) { + public SelectedObjectCollection SelectedItems + { + get + { + if (selectedItems == null) + { selectedItems = new SelectedObjectCollection(this); } return selectedItems; @@ -929,17 +1077,21 @@ public SelectedObjectCollection SelectedItems { DefaultValue(SelectionMode.One), SRDescription(nameof(SR.ListBoxSelectionModeDescr)) ] - public virtual SelectionMode SelectionMode { - get { + public virtual SelectionMode SelectionMode + { + get + { return selectionMode; } - set { + set + { if (!ClientUtils.IsEnumValid(value, (int)value, (int)SelectionMode.None, (int)SelectionMode.MultiExtended)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(SelectionMode)); } - if (selectionMode != value) { + if (selectionMode != value) + { SelectedItems.EnsureUpToDate(); selectionMode = value; try @@ -970,15 +1122,20 @@ public virtual SelectionMode SelectionMode { DefaultValue(false), SRDescription(nameof(SR.ListBoxSortedDescr)) ] - public bool Sorted { - get { + public bool Sorted + { + get + { return sorted; } - set { - if (sorted != value) { + set + { + if (sorted != value) + { sorted = value; - if (sorted && itemsCollection != null && itemsCollection.Count >= 1) { + if (sorted && itemsCollection != null && itemsCollection.Count >= 1) + { Sort(); } } @@ -990,30 +1147,41 @@ public bool Sorted { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Bindable(false) ] - public override string Text { - get { - if (SelectionMode != SelectionMode.None && SelectedItem != null) { - if (FormattingEnabled) { + public override string Text + { + get + { + if (SelectionMode != SelectionMode.None && SelectedItem != null) + { + if (FormattingEnabled) + { return GetItemText(SelectedItem); - } else { + } + else + { return FilterItemOnProperty(SelectedItem).ToString(); } } - else { + else + { return base.Text; } } - set { + set + { base.Text = value; // Scan through the list items looking for the supplied text string. If we find it, // select it. // - if (SelectionMode != SelectionMode.None && value != null && (SelectedItem == null || !value.Equals(GetItemText(SelectedItem)))) { + if (SelectionMode != SelectionMode.None && value != null && (SelectedItem == null || !value.Equals(GetItemText(SelectedItem)))) + { int cnt = Items.Count; - for (int index=0; index < cnt; ++index) { - if (string.Compare(value, GetItemText(Items[index]), true, CultureInfo.CurrentCulture) == 0) { + for (int index = 0; index < cnt; ++index) + { + if (string.Compare(value, GetItemText(Items[index]), true, CultureInfo.CurrentCulture) == 0) + { SelectedIndex = index; return; } @@ -1023,7 +1191,8 @@ public override string Text { } [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - new public event EventHandler TextChanged { + new public event EventHandler TextChanged + { add => base.TextChanged += value; remove => base.TextChanged -= value; } @@ -1038,20 +1207,27 @@ public override string Text { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ListBoxTopIndexDescr)) ] - public int TopIndex { - get { - if (IsHandleCreated) { - return unchecked( (int) (long)SendMessage(NativeMethods.LB_GETTOPINDEX, 0, 0)); + public int TopIndex + { + get + { + if (IsHandleCreated) + { + return unchecked((int)(long)SendMessage(NativeMethods.LB_GETTOPINDEX, 0, 0)); } - else { + else + { return topIndex; } } - set { - if (IsHandleCreated) { + set + { + if (IsHandleCreated) + { SendMessage(NativeMethods.LB_SETTOPINDEX, value, 0); } - else { + else + { topIndex = value; } } @@ -1066,12 +1242,16 @@ public int TopIndex { DefaultValue(true), SRDescription(nameof(SR.ListBoxUseTabStopsDescr)) ] - public bool UseTabStops { - get { + public bool UseTabStops + { + get + { return useTabStops; } - set { - if (useTabStops != value) { + set + { + if (useTabStops != value) + { useTabStops = value; RecreateHandle(); } @@ -1087,9 +1267,12 @@ public bool UseTabStops { DesignerSerializationVisibility(DesignerSerializationVisibility.Content), Browsable(false) ] - public IntegerCollection CustomTabOffsets { - get { - if (customTabOffsets == null) { + public IntegerCollection CustomTabOffsets + { + get + { + if (customTabOffsets == null) + { customTabOffsets = new IntegerCollection(this); } return customTabOffsets; @@ -1100,9 +1283,11 @@ public IntegerCollection CustomTabOffsets { /// Performs the work of adding the specified items to the Listbox /// [Obsolete("This method has been deprecated. There is no replacement. http://go.microsoft.com/fwlink/?linkid=14202")] - protected virtual void AddItemsCore(object[] value) { - int count = value == null? 0: value.Length; - if (count == 0) { + protected virtual void AddItemsCore(object[] value) + { + int count = value == null ? 0 : value.Length; + if (count == 0) + { return; } @@ -1110,13 +1295,15 @@ protected virtual void AddItemsCore(object[] value) { } [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] - public new event EventHandler Click { + public new event EventHandler Click + { add => base.Click += value; remove => base.Click -= value; } [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] - public new event MouseEventHandler MouseClick { + public new event MouseEventHandler MouseClick + { add => base.MouseClick += value; remove => base.MouseClick -= value; } @@ -1126,44 +1313,51 @@ protected virtual void AddItemsCore(object[] value) { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Padding Padding { + public new Padding Padding + { get { return base.Padding; } - set { base.Padding = value;} + set { base.Padding = value; } } [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public new event EventHandler PaddingChanged { - add => base.PaddingChanged += value; - remove => base.PaddingChanged -= value; } + public new event EventHandler PaddingChanged + { + add => base.PaddingChanged += value; + remove => base.PaddingChanged -= value; + } /// /// ListBox / CheckedListBox Onpaint. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event PaintEventHandler Paint { + public new event PaintEventHandler Paint + { add => base.Paint += value; remove => base.Paint -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.drawItemEventDescr))] - public event DrawItemEventHandler DrawItem { + public event DrawItemEventHandler DrawItem + { add => Events.AddHandler(EVENT_DRAWITEM, value); remove => Events.RemoveHandler(EVENT_DRAWITEM, value); } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.measureItemEventDescr))] - public event MeasureItemEventHandler MeasureItem { + public event MeasureItemEventHandler MeasureItem + { add => Events.AddHandler(EVENT_MEASUREITEM, value); remove => Events.RemoveHandler(EVENT_MEASUREITEM, value); } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.selectedIndexChangedEventDescr))] - public event EventHandler SelectedIndexChanged { + public event EventHandler SelectedIndexChanged + { add => Events.AddHandler(EVENT_SELECTEDINDEXCHANGED, value); remove => Events.RemoveHandler(EVENT_SELECTEDINDEXCHANGED, value); } @@ -1177,30 +1371,36 @@ public event EventHandler SelectedIndexChanged { /// way of doing this. Don't forget to call EndUpdate when you're done, /// or else the ListBox won't paint properly afterwards. /// - public void BeginUpdate() { + public void BeginUpdate() + { BeginUpdateInternal(); updateCount++; } - private void CheckIndex(int index) { + private void CheckIndex(int index) + { if (index < 0 || index >= Items.Count) throw new ArgumentOutOfRangeException(nameof(index), string.Format(SR.IndexOutOfRange, index.ToString(CultureInfo.CurrentCulture))); } - private void CheckNoDataSource() { + private void CheckNoDataSource() + { if (DataSource != null) throw new ArgumentException(SR.DataSourceLocksItems); } - protected virtual ObjectCollection CreateItemCollection() { + protected virtual ObjectCollection CreateItemCollection() + { return new ObjectCollection(this); } - internal virtual int ComputeMaxItemWidth(int oldMax) { + internal virtual int ComputeMaxItemWidth(int oldMax) + { // pass LayoutUtils the collection of strings string[] strings = new string[this.Items.Count]; - for (int i = 0; i < Items.Count; i ++) { + for (int i = 0; i < Items.Count; i++) + { strings[i] = GetItemText(Items[i]); } @@ -1211,22 +1411,27 @@ internal virtual int ComputeMaxItemWidth(int oldMax) { /// /// Unselects all currently selected items. /// - public void ClearSelected() { + public void ClearSelected() + { bool hadSelection = false; int itemCount = (itemsCollection == null) ? 0 : itemsCollection.Count; - for (int x = 0; x < itemCount;x++) { - if (SelectedItems.GetSelected(x)) { + for (int x = 0; x < itemCount; x++) + { + if (SelectedItems.GetSelected(x)) + { hadSelection = true; SelectedItems.SetSelected(x, false); - if (IsHandleCreated) { + if (IsHandleCreated) + { NativeSetSelected(x, false); } } } - if (hadSelection) { + if (hadSelection) + { OnSelectedIndexChanged(EventArgs.Empty); } } @@ -1240,7 +1445,8 @@ public void ClearSelected() { /// way of doing this. BeginUpdate should be called first, and this method /// should be called when you want the control to start painting again. /// - public void EndUpdate() { + public void EndUpdate() + { EndUpdateInternal(); --updateCount; } @@ -1279,7 +1485,8 @@ public int FindStringExact(string s, int startIndex) /// Returns the height of the given item in a list box. The index parameter /// is ignored if drawMode is not OwnerDrawVariable. /// - public int GetItemHeight(int index) { + public int GetItemHeight(int index) + { int itemCount = (itemsCollection == null) ? 0 : itemsCollection.Count; // Note: index == 0 is OK even if the ListBox currently has @@ -1288,10 +1495,12 @@ public int GetItemHeight(int index) { if (index < 0 || (index > 0 && index >= itemCount)) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); - if (drawMode != DrawMode.OwnerDrawVariable) index = 0; + if (drawMode != DrawMode.OwnerDrawVariable) + index = 0; - if (IsHandleCreated) { - int h = unchecked( (int) (long)SendMessage(NativeMethods.LB_GETITEMHEIGHT, index, 0)); + if (IsHandleCreated) + { + int h = unchecked((int)(long)SendMessage(NativeMethods.LB_GETITEMHEIGHT, index, 0)); if (h == -1) throw new Win32Exception(); return h; @@ -1305,7 +1514,8 @@ public int GetItemHeight(int index) { /// around an item in the list. If the item in question is not visible, /// the rectangle will be outside the visible portion of the control. /// - public Rectangle GetItemRectangle(int index) { + public Rectangle GetItemRectangle(int index) + { CheckIndex(index); NativeMethods.RECT rect = new NativeMethods.RECT(); SendMessage(NativeMethods.LB_GETITEMRECT, index, ref rect); @@ -1317,7 +1527,8 @@ public Rectangle GetItemRectangle(int index) { /// height, not the current height. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override Rectangle GetScaledBounds(Rectangle bounds, SizeF factor, BoundsSpecified specified) { + protected override Rectangle GetScaledBounds(Rectangle bounds, SizeF factor, BoundsSpecified specified) + { // update bounds' height to use the requested height, not the current height. These // can be different if integral height is turned on. bounds.Height = requestedHeight; @@ -1328,21 +1539,27 @@ protected override Rectangle GetScaledBounds(Rectangle bounds, SizeF factor, Bou /// Tells you whether or not the item at the supplied index is selected /// or not. /// - public bool GetSelected(int index) { + public bool GetSelected(int index) + { CheckIndex(index); return GetSelectedInternal(index); } - private bool GetSelectedInternal(int index) { - if (IsHandleCreated) { - int sel = unchecked( (int) (long)SendMessage(NativeMethods.LB_GETSEL, index, 0)); - if (sel == -1) { + private bool GetSelectedInternal(int index) + { + if (IsHandleCreated) + { + int sel = unchecked((int)(long)SendMessage(NativeMethods.LB_GETSEL, index, 0)); + if (sel == -1) + { throw new Win32Exception(); } return sel > 0; } - else { - if (itemsCollection != null && SelectedItems.GetSelected(index)) { + else + { + if (itemsCollection != null && SelectedItems.GetSelected(index)) + { return true; } return false; @@ -1352,22 +1569,26 @@ private bool GetSelectedInternal(int index) { /// /// Retrieves the index of the item at the given coordinates. /// - public int IndexFromPoint(Point p) { + public int IndexFromPoint(Point p) + { return IndexFromPoint(p.X, p.Y); } /// /// Retrieves the index of the item at the given coordinates. /// - public int IndexFromPoint(int x, int y) { + public int IndexFromPoint(int x, int y) + { //NT4 SP6A : SendMessage Fails. So First check whether the point is in Client Co-ordinates and then //call Sendmessage. // NativeMethods.RECT r = new NativeMethods.RECT(); UnsafeNativeMethods.GetClientRect(new HandleRef(this, Handle), ref r); - if (r.left <= x && x < r.right && r.top <= y && y < r.bottom) { - int index = unchecked( (int) (long)SendMessage(NativeMethods.LB_ITEMFROMPOINT, 0, unchecked( (int) (long)NativeMethods.Util.MAKELPARAM(x, y)))); - if (NativeMethods.Util.HIWORD(index) == 0) { + if (r.left <= x && x < r.right && r.top <= y && y < r.bottom) + { + int index = unchecked((int)(long)SendMessage(NativeMethods.LB_ITEMFROMPOINT, 0, unchecked((int)(long)NativeMethods.Util.MAKELPARAM(x, y)))); + if (NativeMethods.Util.HIWORD(index) == 0) + { // Inside ListBox client area return NativeMethods.Util.LOWORD(index); } @@ -1380,15 +1601,18 @@ public int IndexFromPoint(int x, int y) { /// Adds the given item to the native combo box. This asserts if the handle hasn't been /// created. /// - private int NativeAdd(object item) { + private int NativeAdd(object item) + { Debug.Assert(IsHandleCreated, "Shouldn't be calling Native methods before the handle is created."); - int insertIndex = unchecked( (int) (long)SendMessage(NativeMethods.LB_ADDSTRING, 0, GetItemText(item))); + int insertIndex = unchecked((int)(long)SendMessage(NativeMethods.LB_ADDSTRING, 0, GetItemText(item))); - if (insertIndex == NativeMethods.LB_ERRSPACE) { + if (insertIndex == NativeMethods.LB_ERRSPACE) + { throw new OutOfMemoryException(); } - if (insertIndex == NativeMethods.LB_ERR) { + if (insertIndex == NativeMethods.LB_ERR) + { // On older platforms the ListBox control returns LB_ERR if there are a // large number (>32000) of items. It doesn't appear to set error codes // appropriately, so we'll have to assume that LB_ERR corresponds to item @@ -1402,7 +1626,8 @@ private int NativeAdd(object item) { /// /// Clears the contents of the combo box. /// - private void NativeClear() { + private void NativeClear() + { Debug.Assert(IsHandleCreated, "Shouldn't be calling Native methods before the handle is created."); SendMessage(NativeMethods.LB_RESETCONTENT, 0, 0); } @@ -1410,8 +1635,9 @@ private void NativeClear() { /// /// Get the text stored by the native control for the specified list item. /// - internal string NativeGetItemText(int index) { - int len = unchecked( (int) (long)SendMessage(NativeMethods.LB_GETTEXTLEN, index, 0)); + internal string NativeGetItemText(int index) + { + int len = unchecked((int)(long)SendMessage(NativeMethods.LB_GETTEXTLEN, index, 0)); StringBuilder sb = new StringBuilder(len + 1); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LB_GETTEXT, index, sb); return sb.ToString(); @@ -1421,15 +1647,18 @@ internal string NativeGetItemText(int index) { /// Inserts the given item to the native combo box at the index. This asserts if the handle hasn't been /// created or if the resulting insert index doesn't match the passed in index. /// - private int NativeInsert(int index, object item) { + private int NativeInsert(int index, object item) + { Debug.Assert(IsHandleCreated, "Shouldn't be calling Native methods before the handle is created."); - int insertIndex = unchecked( (int) (long)SendMessage(NativeMethods.LB_INSERTSTRING, index, GetItemText(item))); + int insertIndex = unchecked((int)(long)SendMessage(NativeMethods.LB_INSERTSTRING, index, GetItemText(item))); - if (insertIndex == NativeMethods.LB_ERRSPACE) { + if (insertIndex == NativeMethods.LB_ERRSPACE) + { throw new OutOfMemoryException(); } - if (insertIndex == NativeMethods.LB_ERR) { + if (insertIndex == NativeMethods.LB_ERR) + { // On older platforms the ListBox control returns LB_ERR if there are a // large number (>32000) of items. It doesn't appear to set error codes // appropriately, so we'll have to assume that LB_ERR corresponds to item @@ -1444,16 +1673,18 @@ private int NativeInsert(int index, object item) { /// /// Removes the native item from the given index. /// - private void NativeRemoveAt(int index) { + private void NativeRemoveAt(int index) + { Debug.Assert(IsHandleCreated, "Shouldn't be calling Native methods before the handle is created."); - bool selected = (unchecked( (int) (long)SendMessage(NativeMethods.LB_GETSEL, (IntPtr)index, IntPtr.Zero)) > 0); + bool selected = (unchecked((int)(long)SendMessage(NativeMethods.LB_GETSEL, (IntPtr)index, IntPtr.Zero)) > 0); SendMessage(NativeMethods.LB_DELETESTRING, index, 0); //If the item currently selected is removed then we should fire a Selectionchanged event... //as the next time selected index returns -1... - if (selected) { + if (selected) + { OnSelectedIndexChanged(EventArgs.Empty); } } @@ -1462,15 +1693,18 @@ private void NativeRemoveAt(int index) { /// Sets the selection of the given index to the native window. This does not change /// the collection; you must update the collection yourself. /// - private void NativeSetSelected(int index, bool value) { + private void NativeSetSelected(int index, bool value) + { Debug.Assert(IsHandleCreated, "Should only call Native methods after the handle has been created"); Debug.Assert(selectionMode != SelectionMode.None, "Guard against setting selection for None selection mode outside this code."); - if (selectionMode == SelectionMode.One) { + if (selectionMode == SelectionMode.One) + { SendMessage(NativeMethods.LB_SETCURSEL, (value ? index : -1), 0); } - else { - SendMessage(NativeMethods.LB_SETSEL, value? -1: 0, index); + else + { + SendMessage(NativeMethods.LB_SETSEL, value ? -1 : 0, index); } } @@ -1479,29 +1713,34 @@ private void NativeSetSelected(int index, bool value) { /// query on that collection after we have called Dirty(). Dirty() is called /// when we receive a LBN_SELCHANGE message. /// - private void NativeUpdateSelection() { + private void NativeUpdateSelection() + { Debug.Assert(IsHandleCreated, "Should only call native methods if handle is created"); // Clear the selection state. // int cnt = Items.Count; - for (int i = 0; i < cnt; i++) { + for (int i = 0; i < cnt; i++) + { SelectedItems.SetSelected(i, false); } int[] result = null; - switch (selectionMode) { + switch (selectionMode) + { case SelectionMode.One: - int index = unchecked( (int) (long)SendMessage(NativeMethods.LB_GETCURSEL, 0, 0)); - if (index >= 0) result = new int[] {index}; + int index = unchecked((int)(long)SendMessage(NativeMethods.LB_GETCURSEL, 0, 0)); + if (index >= 0) + result = new int[] { index }; break; case SelectionMode.MultiSimple: case SelectionMode.MultiExtended: - int count = unchecked( (int) (long)SendMessage(NativeMethods.LB_GETSELCOUNT, 0, 0)); - if (count > 0) { + int count = unchecked((int)(long)SendMessage(NativeMethods.LB_GETSELCOUNT, 0, 0)); + if (count > 0) + { result = new int[count]; UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LB_GETSELITEMS, count, result); } @@ -1510,14 +1749,17 @@ private void NativeUpdateSelection() { // Now set the selected state on the appropriate items. // - if (result != null) { - foreach(int i in result) { - SelectedItems.SetSelected(i, true); + if (result != null) + { + foreach (int i in result) + { + SelectedItems.SetSelected(i, true); } } } - protected override void OnChangeUICues(UICuesEventArgs e) { + protected override void OnChangeUICues(UICuesEventArgs e) + { // ListBox seems to get a bit confused when the UI cues change for the first // time - it draws the focus rect when it shouldn't and vice-versa. So when @@ -1536,9 +1778,11 @@ protected override void OnChangeUICues(UICuesEventArgs e) { /// however, remember to call base.onDrawItem(e); to ensure the event is /// still fired to external listeners /// - protected virtual void OnDrawItem(DrawItemEventArgs e) { + protected virtual void OnDrawItem(DrawItemEventArgs e) + { DrawItemEventHandler handler = (DrawItemEventHandler)Events[EVENT_DRAWITEM]; - if (handler != null) { + if (handler != null) + { handler(this, e); } } @@ -1548,48 +1792,59 @@ protected virtual void OnDrawItem(DrawItemEventArgs e) { /// set up a few things, like column width, etc! Inheriting classes should /// not forget to call base.OnHandleCreated(). /// - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { base.OnHandleCreated(e); - + //for getting the current Locale to set the Scrollbars... // SendMessage(NativeMethods.LB_SETLOCALE, CultureInfo.CurrentCulture.LCID, 0); - if (columnWidth != 0) { + if (columnWidth != 0) + { SendMessage(NativeMethods.LB_SETCOLUMNWIDTH, columnWidth, 0); } - if (drawMode == DrawMode.OwnerDrawFixed) { + if (drawMode == DrawMode.OwnerDrawFixed) + { SendMessage(NativeMethods.LB_SETITEMHEIGHT, 0, ItemHeight); } - if (topIndex != 0) { + if (topIndex != 0) + { SendMessage(NativeMethods.LB_SETTOPINDEX, topIndex, 0); } - if (UseCustomTabOffsets && CustomTabOffsets != null) { + if (UseCustomTabOffsets && CustomTabOffsets != null) + { int wpar = CustomTabOffsets.Count; int[] offsets = new int[wpar]; CustomTabOffsets.CopyTo(offsets, 0); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LB_SETTABSTOPS, wpar, offsets); } - if (itemsCollection != null) { + if (itemsCollection != null) + { int count = itemsCollection.Count; - for(int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) + { NativeAdd(itemsCollection[i]); - if (selectionMode != SelectionMode.None) { - if (selectedItems != null) { + if (selectionMode != SelectionMode.None) + { + if (selectedItems != null) + { selectedItems.PushSelectionIntoNativeListBox(i); } } } } - if (selectedItems != null) { - if (selectedItems.Count > 0 && selectionMode == SelectionMode.One) { + if (selectedItems != null) + { + if (selectedItems.Count > 0 && selectionMode == SelectionMode.One) + { SelectedItems.Dirty(); SelectedItems.EnsureUpToDate(); } @@ -1602,22 +1857,27 @@ protected override void OnHandleCreated(EventArgs e) { /// correctly. Inheriting controls should not forget to call /// base.OnHandleDestroyed() /// - protected override void OnHandleDestroyed(EventArgs e) { + protected override void OnHandleDestroyed(EventArgs e) + { SelectedItems.EnsureUpToDate(); - if (Disposing) { + if (Disposing) + { itemsCollection = null; } base.OnHandleDestroyed(e); } - protected virtual void OnMeasureItem(MeasureItemEventArgs e) { + protected virtual void OnMeasureItem(MeasureItemEventArgs e) + { MeasureItemEventHandler handler = (MeasureItemEventHandler)Events[EVENT_MEASUREITEM]; - if (handler != null) { + if (handler != null) + { handler(this, e); } } - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { base.OnFontChanged(e); // Changing the font causes us to resize, always rounding down. @@ -1628,26 +1888,30 @@ protected override void OnFontChanged(EventArgs e) { UpdateFontCache(); } - + /// /// We override this so we can re-create the handle if the parent has changed. /// - protected override void OnParentChanged(EventArgs e) { + protected override void OnParentChanged(EventArgs e) + { base.OnParentChanged(e); //No need to RecreateHandle if we are removing the Listbox from controls collection... //so check the parent before recreating the handle... - if (this.ParentInternal != null) { + if (this.ParentInternal != null) + { RecreateHandle(); } } - protected override void OnResize(EventArgs e) { + protected override void OnResize(EventArgs e) + { base.OnResize(e); // There are some repainting issues for RightToLeft - so invalidate when we resize. // - if (RightToLeft == RightToLeft.Yes || this.HorizontalScrollbar) { + if (RightToLeft == RightToLeft.Yes || this.HorizontalScrollbar) + { Invalidate(); } @@ -1660,7 +1924,8 @@ protected override void OnResize(EventArgs e) { /// however, remember to call base.OnSelectedIndexChanged(e); to ensure the event is /// still fired to external listeners /// - protected override void OnSelectedIndexChanged(EventArgs e) { + protected override void OnSelectedIndexChanged(EventArgs e) + { base.OnSelectedIndexChanged(e); // set the position in the dataSource, if there is any @@ -1669,7 +1934,8 @@ protected override void OnSelectedIndexChanged(EventArgs e) { // calls CurrencyManager::EndCurrentEdit, and that will pull the dataFrom the controls // into the backEnd. We do not need to do that. // - if (this.DataManager != null && DataManager.Position != SelectedIndex) { + if (this.DataManager != null && DataManager.Position != SelectedIndex) + { //read this as "if everett or (whidbey and selindex is valid)" if (!FormattingEnabled || this.SelectedIndex != -1) { @@ -1682,17 +1948,20 @@ protected override void OnSelectedIndexChanged(EventArgs e) { // Call the handler after updating the DataManager's position so that // the DataManager's selected index will be correct in an event handler. EventHandler handler = (EventHandler)Events[EVENT_SELECTEDINDEXCHANGED]; - if (handler != null) { + if (handler != null) + { handler(this, e); } } - protected override void OnSelectedValueChanged(EventArgs e) { + protected override void OnSelectedValueChanged(EventArgs e) + { base.OnSelectedValueChanged(e); selectedValueChangedFired = true; } - protected override void OnDataSourceChanged(EventArgs e) { + protected override void OnDataSourceChanged(EventArgs e) + { if (DataSource == null) { BeginUpdate(); @@ -1704,7 +1973,8 @@ protected override void OnDataSourceChanged(EventArgs e) { RefreshItems(); } - protected override void OnDisplayMemberChanged(EventArgs e) { + protected override void OnDisplayMemberChanged(EventArgs e) + { base.OnDisplayMemberChanged(e); // we want to use the new DisplayMember even if there is no data source @@ -1718,20 +1988,24 @@ protected override void OnDisplayMemberChanged(EventArgs e) { /// Forces the ListBox to invalidate and immediately /// repaint itself and any children if OwnerDrawVariable. /// - public override void Refresh() { - if (drawMode == DrawMode.OwnerDrawVariable) { + public override void Refresh() + { + if (drawMode == DrawMode.OwnerDrawVariable) + { //Fire MeasureItem for Each Item in the Listbox... int cnt = Items.Count; Graphics graphics = CreateGraphicsInternal(); try { - for (int i = 0; i < cnt; i++) { + for (int i = 0; i < cnt; i++) + { MeasureItemEventArgs mie = new MeasureItemEventArgs(graphics, i, ItemHeight); OnMeasureItem(mie); } } - finally { + finally + { graphics.Dispose(); } @@ -1741,7 +2015,8 @@ public override void Refresh() { /// /// Reparses the objects, getting new text strings for them. /// - protected override void RefreshItems() { + protected override void RefreshItems() + { // Store the currently selected object collection. // @@ -1752,7 +2027,8 @@ protected override void RefreshItems() { itemsCollection = null; selectedIndices = null; - if (IsHandleCreated) { + if (IsHandleCreated) + { NativeClear(); } @@ -1761,35 +2037,45 @@ protected override void RefreshItems() { // if we have a dataSource and a DisplayMember, then use it // to populate the Items collection // - if (this.DataManager != null && this.DataManager.Count != -1) { + if (this.DataManager != null && this.DataManager.Count != -1) + { newItems = new object[this.DataManager.Count]; - for(int i = 0; i < newItems.Length; i++) { + for (int i = 0; i < newItems.Length; i++) + { newItems[i] = this.DataManager[i]; } } - else if (savedItems != null) { + else if (savedItems != null) + { newItems = new object[savedItems.Count]; savedItems.CopyTo(newItems, 0); } // Store the current list of items // - if (newItems != null) { + if (newItems != null) + { Items.AddRangeInternal(newItems); } // Restore the selected indices if SelectionMode allows it. // - if (SelectionMode != SelectionMode.None) { - if (this.DataManager != null) { + if (SelectionMode != SelectionMode.None) + { + if (this.DataManager != null) + { // put the selectedIndex in sync w/ the position in the dataManager this.SelectedIndex = this.DataManager.Position; } - else { - if (savedItems != null) { + else + { + if (savedItems != null) + { int cnt = savedItems.Count; - for(int index = 0; index < cnt; index++) { - if (savedItems.InnerArray.GetState(index, SelectedObjectCollection.SelectedObjectMask)) { + for (int index = 0; index < cnt; index++) + { + if (savedItems.InnerArray.GetState(index, SelectedObjectCollection.SelectedObjectMask)) + { SelectedItem = savedItems[index]; } } @@ -1802,37 +2088,44 @@ protected override void RefreshItems() { /// /// Reparses the object at the given index, getting new text string for it. /// - protected override void RefreshItem(int index) { + protected override void RefreshItem(int index) + { Items.SetItemInternal(index, Items[index]); } - public override void ResetBackColor() { + public override void ResetBackColor() + { base.ResetBackColor(); } - public override void ResetForeColor() { + public override void ResetForeColor() + { base.ResetForeColor(); } - private void ResetItemHeight() { + private void ResetItemHeight() + { itemHeight = DefaultItemHeight; } - - [SuppressMessage("Microsoft.Portability", "CA1902:AvoidTestingForFloatingPointEquality")] - protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { - - if (factor.Width != 1F && factor.Height != 1F) { - UpdateFontCache(); - } - base.ScaleControl(factor, specified); - } + + [SuppressMessage("Microsoft.Portability", "CA1902:AvoidTestingForFloatingPointEquality")] + protected override void ScaleControl(SizeF factor, BoundsSpecified specified) + { + + if (factor.Width != 1F && factor.Height != 1F) + { + UpdateFontCache(); + } + base.ScaleControl(factor, specified); + } /// /// Overrides Control.SetBoundsCore to remember the requestedHeight. /// - protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { + protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) + { // Avoid the listbox and textbox behaviour in Collection editors // @@ -1846,42 +2139,48 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound /// /// Performs the work of setting the specified items into the ListBox. /// - protected override void SetItemsCore(IList value) { - BeginUpdate(); - Items.ClearInternal(); - Items.AddRangeInternal(value); + protected override void SetItemsCore(IList value) + { + BeginUpdate(); + Items.ClearInternal(); + Items.AddRangeInternal(value); - this.SelectedItems.Dirty(); + this.SelectedItems.Dirty(); - // if the list changed, we want to keep the same selected index - // CurrencyManager will provide the PositionChanged event - // it will be provided before changing the list though... - if (this.DataManager != null) { - if (this.DataSource is ICurrencyManagerProvider) { - // Everett ListControl's had a + // if the list changed, we want to keep the same selected index + // CurrencyManager will provide the PositionChanged event + // it will be provided before changing the list though... + if (this.DataManager != null) + { + if (this.DataSource is ICurrencyManagerProvider) + { + // Everett ListControl's had a - this.selectedValueChangedFired = false; - } + this.selectedValueChangedFired = false; + } - if (IsHandleCreated) { - SendMessage(NativeMethods.LB_SETCURSEL, DataManager.Position, 0); - } + if (IsHandleCreated) + { + SendMessage(NativeMethods.LB_SETCURSEL, DataManager.Position, 0); + } - // if the list changed and we still did not fire the - // onselectedChanged event, then fire it now; - if (!selectedValueChangedFired) { - OnSelectedValueChanged(EventArgs.Empty); - selectedValueChangedFired = false; - } + // if the list changed and we still did not fire the + // onselectedChanged event, then fire it now; + if (!selectedValueChangedFired) + { + OnSelectedValueChanged(EventArgs.Empty); + selectedValueChangedFired = false; } - EndUpdate(); + } + EndUpdate(); } - protected override void SetItemCore(int index, object value) { + protected override void SetItemCore(int index, object value) + { Items.SetItemInternal(index, value); } @@ -1889,8 +2188,9 @@ protected override void SetItemCore(int index, object value) { /// Allows the user to set an item as being selected or not. This should /// only be used with ListBoxes that allow some sort of multi-selection. /// - public void SetSelected(int index, bool value) { - int itemCount = (itemsCollection == null) ? 0: itemsCollection.Count; + public void SetSelected(int index, bool value) + { + int itemCount = (itemsCollection == null) ? 0 : itemsCollection.Count; if (index < 0 || index >= itemCount) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); @@ -1898,7 +2198,8 @@ public void SetSelected(int index, bool value) { throw new InvalidOperationException(SR.ListBoxInvalidSelectionMode); SelectedItems.SetSelected(index, value); - if (IsHandleCreated) { + if (IsHandleCreated) + { NativeSetSelected(index, value); } SelectedItems.Dirty(); @@ -1908,7 +2209,8 @@ public void SetSelected(int index, bool value) { /// /// Sorts the items in the listbox. /// - protected virtual void Sort() { + protected virtual void Sort() + { // This will force the collection to add each item back to itself // if sorted is now true, then the add method will insert the item // into the correct position @@ -1918,17 +2220,21 @@ protected virtual void Sort() { SelectedObjectCollection currentSelections = SelectedItems; currentSelections.EnsureUpToDate(); - if (sorted && itemsCollection != null) { + if (sorted && itemsCollection != null) + { itemsCollection.InnerArray.Sort(); // Now that we've sorted, update our handle // if it has been created. - if (IsHandleCreated) { + if (IsHandleCreated) + { NativeClear(); int count = itemsCollection.Count; - for(int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) + { NativeAdd(itemsCollection[i]); - if (currentSelections.GetSelected(i)) { + if (currentSelections.GetSelected(i)) + { NativeSetSelected(i, true); } } @@ -1939,12 +2245,15 @@ protected virtual void Sort() { /// /// Returns a string representation for this control. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); - if (itemsCollection != null) { + if (itemsCollection != null) + { s += ", Items.Count: " + Items.Count.ToString(CultureInfo.CurrentCulture); - if (Items.Count > 0) { + if (Items.Count > 0) + { string z = GetItemText(Items[0]); string txt = (z.Length > 40) ? z.Substring(0, 40) : z; s += ", Items[0]: " + txt; @@ -1952,13 +2261,16 @@ public override string ToString() { } return s; } - private void UpdateFontCache() { + private void UpdateFontCache() + { fontIsChanged = true; integralHeightAdjust = true; - try { + try + { Height = requestedHeight; } - finally { + finally + { integralHeightAdjust = false; } maxWidth = -1; @@ -1968,10 +2280,13 @@ private void UpdateFontCache() { } - private void UpdateHorizontalExtent() { - if (!multiColumn && horizontalScrollbar && IsHandleCreated) { + private void UpdateHorizontalExtent() + { + if (!multiColumn && horizontalScrollbar && IsHandleCreated) + { int width = horizontalExtent; - if (width == 0) { + if (width == 0) + { width = MaxItemWidth; } SendMessage(NativeMethods.LB_SETHORIZONTALEXTENT, width, 0); @@ -1980,39 +2295,47 @@ private void UpdateHorizontalExtent() { // Updates the cached max item width // - private void UpdateMaxItemWidth(object item, bool removing) { + private void UpdateMaxItemWidth(object item, bool removing) + { // We shouldn't be caching maxWidth if we don't have horizontal scrollbars, // or horizontal extent has been set // - if (!horizontalScrollbar || horizontalExtent > 0) { + if (!horizontalScrollbar || horizontalExtent > 0) + { maxWidth = -1; return; } // Only update if we are currently caching maxWidth // - if (maxWidth > -1) { + if (maxWidth > -1) + { // Compute item width // int width; - using (Graphics graphics = CreateGraphicsInternal()) { + using (Graphics graphics = CreateGraphicsInternal()) + { width = (int)(Math.Ceiling(graphics.MeasureString(GetItemText(item), this.Font).Width)); } - if (removing) { + if (removing) + { // We're removing this item, so if it's the longest // in the list, reset the cache // - if (width >= maxWidth) { + if (width >= maxWidth) + { maxWidth = -1; } } - else { + else + { // We're adding or inserting this item - update the cache // - if (width > maxWidth) { + if (width > maxWidth) + { maxWidth = width; } } @@ -2022,8 +2345,10 @@ private void UpdateMaxItemWidth(object item, bool removing) { // Updates the Custom TabOffsets // - private void UpdateCustomTabOffsets() { - if (IsHandleCreated && UseCustomTabOffsets && CustomTabOffsets != null) { + private void UpdateCustomTabOffsets() + { + if (IsHandleCreated && UseCustomTabOffsets && CustomTabOffsets != null) + { int wpar = CustomTabOffsets.Count; int[] offsets = new int[wpar]; CustomTabOffsets.CopyTo(offsets, 0); @@ -2032,12 +2357,16 @@ private void UpdateCustomTabOffsets() { } } - private void WmPrint(ref Message m) { + private void WmPrint(ref Message m) + { base.WndProc(ref m); - if ((NativeMethods.PRF_NONCLIENT & (int)m.LParam) != 0 && Application.RenderWithVisualStyles && this.BorderStyle == BorderStyle.Fixed3D) { - using (Graphics g = Graphics.FromHdc(m.WParam)) { + if ((NativeMethods.PRF_NONCLIENT & (int)m.LParam) != 0 && Application.RenderWithVisualStyles && this.BorderStyle == BorderStyle.Fixed3D) + { + using (Graphics g = Graphics.FromHdc(m.WParam)) + { Rectangle rect = new Rectangle(0, 0, this.Size.Width - 1, this.Size.Height - 1); - using (Pen pen = new Pen(VisualStyleInformation.TextControlBorder)) { + using (Pen pen = new Pen(VisualStyleInformation.TextControlBorder)) + { g.DrawRectangle(pen, rect); } rect.Inflate(-1, -1); @@ -2048,10 +2377,13 @@ private void WmPrint(ref Message m) { /// /// - protected virtual void WmReflectCommand(ref Message m) { - switch (NativeMethods.Util.HIWORD(m.WParam)) { + protected virtual void WmReflectCommand(ref Message m) + { + switch (NativeMethods.Util.HIWORD(m.WParam)) + { case NativeMethods.LBN_SELCHANGE: - if (selectedItems != null) { + if (selectedItems != null) + { selectedItems.Dirty(); } OnSelectedIndexChanged(EventArgs.Empty); @@ -2065,34 +2397,43 @@ protected virtual void WmReflectCommand(ref Message m) { /// /// - private void WmReflectDrawItem(ref Message m) { + private void WmReflectDrawItem(ref Message m) + { NativeMethods.DRAWITEMSTRUCT dis = (NativeMethods.DRAWITEMSTRUCT)m.GetLParam(typeof(NativeMethods.DRAWITEMSTRUCT)); IntPtr dc = dis.hDC; IntPtr oldPal = SetUpPalette(dc, false /*force*/, false /*realize*/); - try { + try + { Graphics g = Graphics.FromHdcInternal(dc); - try { + try + { Rectangle bounds = Rectangle.FromLTRB(dis.rcItem.left, dis.rcItem.top, dis.rcItem.right, dis.rcItem.bottom); - - if (HorizontalScrollbar) { - if (MultiColumn) { + + if (HorizontalScrollbar) + { + if (MultiColumn) + { bounds.Width = Math.Max(ColumnWidth, bounds.Width); } - else { + else + { bounds.Width = Math.Max(MaxItemWidth, bounds.Width); } } - + OnDrawItem(new DrawItemEventArgs(g, Font, bounds, dis.itemID, (DrawItemState)dis.itemState, ForeColor, BackColor)); } - finally { + finally + { g.Dispose(); } } - finally { - if (oldPal != IntPtr.Zero) { + finally + { + if (oldPal != IntPtr.Zero) + { SafeNativeMethods.SelectPalette(new HandleRef(null, dc), new HandleRef(null, oldPal), 0); } } @@ -2102,22 +2443,27 @@ private void WmReflectDrawItem(ref Message m) { /// /// // This method is only called if in owner draw mode - private void WmReflectMeasureItem(ref Message m) { + private void WmReflectMeasureItem(ref Message m) + { NativeMethods.MEASUREITEMSTRUCT mis = (NativeMethods.MEASUREITEMSTRUCT)m.GetLParam(typeof(NativeMethods.MEASUREITEMSTRUCT)); - if (drawMode == DrawMode.OwnerDrawVariable && mis.itemID >= 0) { + if (drawMode == DrawMode.OwnerDrawVariable && mis.itemID >= 0) + { Graphics graphics = CreateGraphicsInternal(); MeasureItemEventArgs mie = new MeasureItemEventArgs(graphics, mis.itemID, ItemHeight); - try { + try + { OnMeasureItem(mie); mis.itemHeight = mie.ItemHeight; } - finally { + finally + { graphics.Dispose(); } } - else { + else + { mis.itemHeight = ItemHeight; } Marshal.StructureToPtr(mis, m.LParam, false); @@ -2129,8 +2475,10 @@ private void WmReflectMeasureItem(ref Message m) { /// to add extra functionality, but should not forget to call /// base.wndProc(m); to ensure the list continues to function properly. /// - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_COMMAND: WmReflectCommand(ref m); break; @@ -2144,7 +2492,8 @@ protected override void WndProc(ref Message m) { WmPrint(ref m); break; case Interop.WindowMessages.WM_LBUTTONDOWN: - if (selectedItems != null) { + if (selectedItems != null) + { selectedItems.Dirty(); } base.WndProc(ref m); @@ -2154,27 +2503,31 @@ protected override void WndProc(ref Message m) { // int x = NativeMethods.Util.SignedLOWORD(m.LParam); int y = NativeMethods.Util.SignedHIWORD(m.LParam); - Point pt = new Point(x,y); + Point pt = new Point(x, y); pt = PointToScreen(pt); bool captured = Capture; - if (captured && UnsafeNativeMethods.WindowFromPoint(pt.X, pt.Y) == Handle) { + if (captured && UnsafeNativeMethods.WindowFromPoint(pt.X, pt.Y) == Handle) + { - if (!doubleClickFired && !ValidationCancelled) { - OnClick(new MouseEventArgs(MouseButtons.Left, 1, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); - OnMouseClick(new MouseEventArgs(MouseButtons.Left, 1, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); + if (!doubleClickFired && !ValidationCancelled) + { + OnClick(new MouseEventArgs(MouseButtons.Left, 1, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); + OnMouseClick(new MouseEventArgs(MouseButtons.Left, 1, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); } - else { + else + { doubleClickFired = false; // WM_COMMAND is only fired if the user double clicks an item, // so we can't use that as a double-click substitute - if (!ValidationCancelled) { + if (!ValidationCancelled) + { OnDoubleClick(new MouseEventArgs(MouseButtons.Left, 2, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); OnMouseDoubleClick(new MouseEventArgs(MouseButtons.Left, 2, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); } - } + } } // @@ -2201,11 +2554,13 @@ protected override void WndProc(ref Message m) { // int rx = NativeMethods.Util.SignedLOWORD(m.LParam); int ry = NativeMethods.Util.SignedHIWORD(m.LParam); - Point rpt = new Point(rx,ry); + Point rpt = new Point(rx, ry); rpt = PointToScreen(rpt); bool rCaptured = Capture; - if (rCaptured && UnsafeNativeMethods.WindowFromPoint(rpt.X, rpt.Y) == Handle) { - if (selectedItems != null) { + if (rCaptured && UnsafeNativeMethods.WindowFromPoint(rpt.X, rpt.Y) == Handle) + { + if (selectedItems != null) + { selectedItems.Dirty(); } } @@ -2223,8 +2578,9 @@ protected override void WndProc(ref Message m) { case Interop.WindowMessages.WM_WINDOWPOSCHANGED: base.WndProc(ref m); - if (integralHeight && fontIsChanged) { - Height = Math.Max(Height,ItemHeight); + if (integralHeight && fontIsChanged) + { + Height = Math.Max(Height, ItemHeight); fontIsChanged = false; } break; @@ -2247,16 +2603,18 @@ protected override void WndProc(ref Message m) { /// collection and serveral read-only collections based /// on masks. ItemArray supports up to 31 masks. /// - internal class ItemArray : IComparer { + internal class ItemArray : IComparer + { private static int lastMask = 1; private ListControl listControl; - private Entry[] entries; - private int count; - private int version; + private Entry[] entries; + private int count; + private int version; - public ItemArray(ListControl listControl) { + public ItemArray(ListControl listControl) + { this.listControl = listControl; } @@ -2264,8 +2622,10 @@ public ItemArray(ListControl listControl) { /// The version of this array. This number changes with each /// change to the item list. /// - public int Version { - get { + public int Version + { + get + { return version; } } @@ -2274,7 +2634,8 @@ public int Version { /// Adds the given item to the array. The state is initially /// zero. /// - public object Add(object item) { + public object Add(object item) + { EnsureSpace(1); version++; entries[count] = new Entry(item); @@ -2284,13 +2645,16 @@ public object Add(object item) { /// /// Adds the given collection of items to the array. /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - public void AddRange(ICollection items) { - if (items == null) { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + public void AddRange(ICollection items) + { + if (items == null) + { throw new ArgumentNullException(nameof(items)); } EnsureSpace(items.Count); - foreach(object i in items) { + foreach (object i in items) + { entries[count++] = new Entry(i); } version++; @@ -2299,8 +2663,10 @@ public void AddRange(ICollection items) { /// /// Clears this array. /// - public void Clear() { - if (count > 0) { + public void Clear() + { + if (count > 0) + { Array.Clear(entries, 0, count); } @@ -2311,7 +2677,8 @@ public void Clear() { /// /// Allocates a new bitmask for use. /// - public static int CreateMask() { + public static int CreateMask() + { int mask = lastMask; lastMask = lastMask << 1; Debug.Assert(lastMask > mask, "We have overflowed our state mask."); @@ -2322,11 +2689,14 @@ public static int CreateMask() { /// Ensures that our internal array has space for /// the requested # of elements. /// - private void EnsureSpace(int elements) { - if (entries == null) { + private void EnsureSpace(int elements) + { + if (entries == null) + { entries = new Entry[Math.Max(elements, 4)]; } - else if (count + elements >= entries.Length) { + else if (count + elements >= entries.Length) + { int newLength = Math.Max(entries.Length * 2, entries.Length + elements); Entry[] newEntries = new Entry[newLength]; entries.CopyTo(newEntries, 0); @@ -2337,17 +2707,22 @@ private void EnsureSpace(int elements) { /// /// Turns a virtual index into an actual index. /// - public int GetActualIndex(int virtualIndex, int stateMask) { - if (stateMask == 0) { + public int GetActualIndex(int virtualIndex, int stateMask) + { + if (stateMask == 0) + { return virtualIndex; } // More complex; we must compute this index. int calcIndex = -1; - for(int i = 0; i < count; i++) { - if ((entries[i].state & stateMask) != 0) { + for (int i = 0; i < count; i++) + { + if ((entries[i].state & stateMask) != 0) + { calcIndex++; - if (calcIndex == virtualIndex) { + if (calcIndex == virtualIndex) + { return i; } } @@ -2359,9 +2734,11 @@ public int GetActualIndex(int virtualIndex, int stateMask) { /// /// Gets the count of items matching the given mask. /// - public int GetCount(int stateMask) { + public int GetCount(int stateMask) + { // If mask is zero, then just give the main count - if (stateMask == 0) { + if (stateMask == 0) + { return count; } @@ -2370,8 +2747,10 @@ public int GetCount(int stateMask) { int filteredCount = 0; - for(int i = 0; i < count; i++) { - if ((entries[i].state & stateMask) != 0) { + for (int i = 0; i < count; i++) + { + if ((entries[i].state & stateMask) != 0) + { filteredCount++; } } @@ -2383,7 +2762,8 @@ public int GetCount(int stateMask) { /// Retrieves an enumerator that will enumerate based on /// the given mask. /// - public IEnumerator GetEnumerator(int stateMask) { + public IEnumerator GetEnumerator(int stateMask) + { return GetEnumerator(stateMask, false); } @@ -2391,7 +2771,8 @@ public IEnumerator GetEnumerator(int stateMask) { /// Retrieves an enumerator that will enumerate based on /// the given mask. /// - public IEnumerator GetEnumerator(int stateMask, bool anyBit) { + public IEnumerator GetEnumerator(int stateMask, bool anyBit) + { return new EntryEnumerator(this, stateMask, anyBit); } @@ -2399,10 +2780,12 @@ public IEnumerator GetEnumerator(int stateMask, bool anyBit) { /// Gets the item at the given index. The index is /// virtualized against the given mask value. /// - public object GetItem(int virtualIndex, int stateMask) { + public object GetItem(int virtualIndex, int stateMask) + { int actualIndex = GetActualIndex(virtualIndex, stateMask); - if (actualIndex == -1) { + if (actualIndex == -1) + { throw new IndexOutOfRangeException(); } @@ -2412,10 +2795,12 @@ public object GetItem(int virtualIndex, int stateMask) { /// Gets the item at the given index. The index is /// virtualized against the given mask value. /// - internal object GetEntryObject(int virtualIndex, int stateMask) { + internal object GetEntryObject(int virtualIndex, int stateMask) + { int actualIndex = GetActualIndex(virtualIndex, stateMask); - if (actualIndex == -1) { + if (actualIndex == -1) + { throw new IndexOutOfRangeException(); } @@ -2425,7 +2810,8 @@ internal object GetEntryObject(int virtualIndex, int stateMask) { /// Returns true if the requested state mask is set. /// The index is the actual index to the array. /// - public bool GetState(int index, int stateMask) { + public bool GetState(int index, int stateMask) + { return ((entries[index].state & stateMask) == stateMask); } @@ -2433,14 +2819,18 @@ public bool GetState(int index, int stateMask) { /// Returns the virtual index of the item based on the /// state mask. /// - public int IndexOf(object item, int stateMask) { + public int IndexOf(object item, int stateMask) + { int virtualIndex = -1; - for(int i = 0; i < count; i++) { - if (stateMask == 0 || (entries[i].state & stateMask) != 0) { + for (int i = 0; i < count; i++) + { + if (stateMask == 0 || (entries[i].state & stateMask) != 0) + { virtualIndex++; - if (entries[i].item.Equals(item)) { + if (entries[i].item.Equals(item)) + { return virtualIndex; } } @@ -2454,13 +2844,17 @@ public int IndexOf(object item, int stateMask) { /// state mask. Uses reference equality to identify the /// given object in the list. /// - public int IndexOfIdentifier(object identifier, int stateMask) { + public int IndexOfIdentifier(object identifier, int stateMask) + { int virtualIndex = -1; - for(int i = 0; i < count; i++) { - if (stateMask == 0 || (entries[i].state & stateMask) != 0) { + for (int i = 0; i < count; i++) + { + if (stateMask == 0 || (entries[i].state & stateMask) != 0) + { virtualIndex++; - if (entries[i] == identifier) { + if (entries[i] == identifier) + { return virtualIndex; } } @@ -2473,10 +2867,12 @@ public int IndexOfIdentifier(object identifier, int stateMask) { /// Inserts item at the given index. The index /// is not virtualized. /// - public void Insert(int index, object item) { + public void Insert(int index, object item) + { EnsureSpace(1); - if (index < count) { + if (index < count) + { System.Array.Copy(entries, index, entries, index + 1, count - index); } @@ -2489,10 +2885,12 @@ public void Insert(int index, object item) { /// Removes the given item from the array. If /// the item is not in the array, this does nothing. /// - public void Remove(object item) { + public void Remove(object item) + { int index = IndexOf(item, 0); - if (index != -1) { + if (index != -1) + { RemoveAt(index); } } @@ -2500,10 +2898,12 @@ public void Remove(object item) { /// /// Removes the item at the given index. /// - public void RemoveAt(int index) { + public void RemoveAt(int index) + { count--; - for (int i = index; i < count; i++) { - entries[i] = entries[i+1]; + for (int i = index; i < count; i++) + { + entries[i] = entries[i + 1]; } entries[count] = null; version++; @@ -2512,18 +2912,22 @@ public void RemoveAt(int index) { /// /// Sets the item at the given index to a new value. /// - public void SetItem(int index, object item) { + public void SetItem(int index, object item) + { entries[index].item = item; } /// /// Sets the state data for the given index. /// - public void SetState(int index, int stateMask, bool value) { - if (value) { + public void SetState(int index, int stateMask, bool value) + { + if (value) + { entries[index].state |= stateMask; } - else { + else + { entries[index].state &= ~stateMask; } version++; @@ -2541,17 +2945,21 @@ public int BinarySearch(object element) /// /// Sorts our array. /// - public void Sort() { + public void Sort() + { Array.Sort(entries, 0, count, this); } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - public void Sort(Array externalArray) { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + public void Sort(Array externalArray) + { Array.Sort(externalArray, this); } - int IComparer.Compare(object item1, object item2) { - if (item1 == null) { + int IComparer.Compare(object item1, object item2) + { + if (item1 == null) + { if (item2 == null) return 0; //both null, then they are equal @@ -2560,11 +2968,13 @@ int IComparer.Compare(object item1, object item2) { if (item2 == null) return 1; //item2 is null, so item 1 is greater - if (item1 is Entry) { + if (item1 is Entry) + { item1 = ((Entry)item1).item; } - if (item2 is Entry) { + if (item2 is Entry) + { item2 = ((Entry)item2).item; } @@ -2578,11 +2988,13 @@ int IComparer.Compare(object item1, object item2) { /// /// This is a single entry in our item array. /// - private class Entry { + private class Entry + { public object item; public int state; - public Entry(object item) { + public Entry(object item) + { this.item = item; this.state = 0; } @@ -2592,7 +3004,8 @@ public Entry(object item) { /// EntryEnumerator is an enumerator that will enumerate over /// a given state mask. /// - private class EntryEnumerator : IEnumerator { + private class EntryEnumerator : IEnumerator + { private ItemArray items; private bool anyBit; private int state; @@ -2602,7 +3015,8 @@ private class EntryEnumerator : IEnumerator { /// /// Creates a new enumerator that will enumerate over the given state. /// - public EntryEnumerator(ItemArray items, int state, bool anyBit) { + public EntryEnumerator(ItemArray items, int state, bool anyBit) + { this.items = items; this.state = state; this.anyBit = anyBit; @@ -2613,24 +3027,33 @@ public EntryEnumerator(ItemArray items, int state, bool anyBit) { /// /// Moves to the next element, or returns false if at the end. /// - bool IEnumerator.MoveNext() { - if(version != items.version) throw new InvalidOperationException(SR.ListEnumVersionMismatch); - - while(true) { - if (current < items.count - 1) { - current++; - if (anyBit) { - if ((items.entries[current].state & state) != 0) { + bool IEnumerator.MoveNext() + { + if (version != items.version) + throw new InvalidOperationException(SR.ListEnumVersionMismatch); + + while (true) + { + if (current < items.count - 1) + { + current++; + if (anyBit) + { + if ((items.entries[current].state & state) != 0) + { return true; } } - else { - if ((items.entries[current].state & state) == state) { + else + { + if ((items.entries[current].state & state) == state) + { return true; } } } - else { + else + { current = items.count; return false; } @@ -2640,17 +3063,22 @@ bool IEnumerator.MoveNext() { /// /// Resets the enumeration back to the beginning. /// - void IEnumerator.Reset() { - if(version != items.version) throw new InvalidOperationException(SR.ListEnumVersionMismatch); + void IEnumerator.Reset() + { + if (version != items.version) + throw new InvalidOperationException(SR.ListEnumVersionMismatch); current = -1; } /// /// Retrieves the current value in the enumerator. /// - object IEnumerator.Current { - get { - if (current == -1 || current == items.count) { + object IEnumerator.Current + { + get + { + if (current == -1 || current == items.count) + { throw new InvalidOperationException(SR.ListEnumCurrentOutOfRange); } @@ -2667,12 +3095,14 @@ object IEnumerator.Current { /// /// [ListBindable(false)] - public class ObjectCollection : IList { + public class ObjectCollection : IList + { private ListBox owner; private ItemArray items; - public ObjectCollection(ListBox owner) { + public ObjectCollection(ListBox owner) + { this.owner = owner; } @@ -2681,7 +3111,8 @@ public ObjectCollection(ListBox owner) { /// Initializes a new instance of ListBox.ObjectCollection based on another ListBox.ObjectCollection. /// /// - public ObjectCollection(ListBox owner, ObjectCollection value) { + public ObjectCollection(ListBox owner, ObjectCollection value) + { this.owner = owner; this.AddRange(value); } @@ -2691,7 +3122,8 @@ public ObjectCollection(ListBox owner, ObjectCollection value) { /// Initializes a new instance of ListBox.ObjectCollection containing any array of objects. /// /// - public ObjectCollection(ListBox owner, object[] value) { + public ObjectCollection(ListBox owner, object[] value) + { this.owner = owner; this.AddRange(value); } @@ -2699,8 +3131,10 @@ public ObjectCollection(ListBox owner, object[] value) { /// /// Retrieves the number of items. /// - public int Count { - get { + public int Count + { + get + { return InnerArray.GetCount(0); } } @@ -2708,35 +3142,46 @@ public int Count { /// /// Internal access to the actual data store. /// - internal ItemArray InnerArray { - get { - if (items == null) { + internal ItemArray InnerArray + { + get + { + if (items == null) + { items = new ItemArray(owner); } return items; } } - object ICollection.SyncRoot { - get { + object ICollection.SyncRoot + { + get + { return this; } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return false; } } - bool IList.IsFixedSize { - get { + bool IList.IsFixedSize + { + get + { return false; } } - public bool IsReadOnly { - get { + public bool IsReadOnly + { + get + { return false; } } @@ -2823,26 +3268,30 @@ private int AddInternal(object item) InnerArray.Remove(item); } } - + return index; } - - int IList.Add(object item) { + + int IList.Add(object item) + { return Add(item); } - public void AddRange(ObjectCollection value) { + public void AddRange(ObjectCollection value) + { owner.CheckNoDataSource(); AddRangeInternal((ICollection)value); } - public void AddRange(object[] items) { + public void AddRange(object[] items) + { owner.CheckNoDataSource(); AddRangeInternal((ICollection)items); } - - internal void AddRangeInternal(ICollection items) { + + internal void AddRangeInternal(ICollection items) + { if (items == null) { @@ -2870,15 +3319,19 @@ internal void AddRangeInternal(ICollection items) { /// Retrieves the item with the specified index. /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public virtual object this[int index] { - get { - if (index < 0 || index >= InnerArray.GetCount(0)) { + public virtual object this[int index] + { + get + { + if (index < 0 || index >= InnerArray.GetCount(0)) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } return InnerArray.GetItem(index, 0); } - set { + set + { owner.CheckNoDataSource(); SetItemInternal(index, value); } @@ -2887,7 +3340,8 @@ public virtual object this[int index] { /// /// Removes all items from the ListBox. /// - public virtual void Clear() { + public virtual void Clear() + { owner.CheckNoDataSource(); ClearInternal(); } @@ -2895,18 +3349,21 @@ public virtual void Clear() { /// /// Removes all items from the ListBox. Bypasses the data source check. /// - internal void ClearInternal() { + internal void ClearInternal() + { //update the width.. to reset Scrollbars.. // Clear the selection state. // int cnt = owner.Items.Count; - for (int i = 0; i < cnt; i++) { + for (int i = 0; i < cnt; i++) + { owner.UpdateMaxItemWidth(InnerArray.GetItem(i, 0), true); } - if (owner.IsHandleCreated) { + if (owner.IsHandleCreated) + { owner.NativeClear(); } InnerArray.Clear(); @@ -2914,23 +3371,28 @@ internal void ClearInternal() { owner.UpdateHorizontalExtent(); } - public bool Contains(object value) { + public bool Contains(object value) + { return IndexOf(value) != -1; } /// /// Copies the ListBox Items collection to a destination array. /// - public void CopyTo(object[] destination, int arrayIndex) { + public void CopyTo(object[] destination, int arrayIndex) + { int count = InnerArray.GetCount(0); - for(int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) + { destination[i + arrayIndex] = InnerArray.GetItem(i, 0); } } - void ICollection.CopyTo(Array destination, int index) { + void ICollection.CopyTo(Array destination, int index) + { int count = InnerArray.GetCount(0); - for(int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) + { destination.SetValue(InnerArray.GetItem(i, 0), i + index); } } @@ -2938,24 +3400,29 @@ void ICollection.CopyTo(Array destination, int index) { /// /// Returns an enumerator for the ListBox Items collection. /// - public IEnumerator GetEnumerator() { + public IEnumerator GetEnumerator() + { return InnerArray.GetEnumerator(0); } - public int IndexOf(object value) { - if (value == null) { + public int IndexOf(object value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } - return InnerArray.IndexOf(value,0); + return InnerArray.IndexOf(value, 0); } - internal int IndexOfIdentifier(object value) { - if (value == null) { + internal int IndexOfIdentifier(object value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } - return InnerArray.IndexOfIdentifier(value,0); + return InnerArray.IndexOfIdentifier(value, 0); } /// @@ -2967,36 +3434,45 @@ internal int IndexOfIdentifier(object value) { /// A SystemException occurs if there is insufficient space available to /// store the new item. /// - public void Insert(int index, object item) { + public void Insert(int index, object item) + { owner.CheckNoDataSource(); - if (index < 0 || index > InnerArray.GetCount(0)) { + if (index < 0 || index > InnerArray.GetCount(0)) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - if (item == null) { + if (item == null) + { throw new ArgumentNullException(nameof(item)); } // If the combo box is sorted, then nust treat this like an add // because we are going to twiddle the index anyway. // - if (owner.sorted) { + if (owner.sorted) + { Add(item); } - else { + else + { InnerArray.Insert(index, item); - if (owner.IsHandleCreated) { + if (owner.IsHandleCreated) + { bool successful = false; - try { + try + { owner.NativeInsert(index, item); owner.UpdateMaxItemWidth(item, false); successful = true; } - finally { - if (!successful) { + finally + { + if (!successful) + { InnerArray.RemoveAt(index); } } @@ -3009,11 +3485,13 @@ public void Insert(int index, object item) { /// Removes the given item from the ListBox, provided that it is /// actually in the list. /// - public void Remove(object value) { + public void Remove(object value) + { int index = InnerArray.IndexOf(value, 0); - if (index != -1) { + if (index != -1) + { RemoveAt(index); } } @@ -3021,10 +3499,12 @@ public void Remove(object value) { /// /// Removes an item from the ListBox at the given index. /// - public void RemoveAt(int index) { + public void RemoveAt(int index) + { owner.CheckNoDataSource(); - if (index < 0 || index >= InnerArray.GetCount(0)) { + if (index < 0 || index >= InnerArray.GetCount(0)) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } @@ -3034,19 +3514,23 @@ public void RemoveAt(int index) { // SelectedIndexChanged is raised (by NativeRemoveAt), InnerArray's state matches wrapped LB state. InnerArray.RemoveAt(index); - if (owner.IsHandleCreated) { + if (owner.IsHandleCreated) + { owner.NativeRemoveAt(index); } owner.UpdateHorizontalExtent(); } - internal void SetItemInternal(int index, object value) { - if (value == null) { + internal void SetItemInternal(int index, object value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } - if (index < 0 || index >= InnerArray.GetCount(0)) { + if (index < 0 || index >= InnerArray.GetCount(0)) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } @@ -3055,20 +3539,25 @@ internal void SetItemInternal(int index, object value) { // If the native control has been created, and the display text of the new list item object // is different to the current text in the native list item, recreate the native list item... - if (owner.IsHandleCreated) { + if (owner.IsHandleCreated) + { bool selected = (owner.SelectedIndex == index); - if (string.Compare(this.owner.GetItemText(value), this.owner.NativeGetItemText(index), true, CultureInfo.CurrentCulture) != 0) { + if (string.Compare(this.owner.GetItemText(value), this.owner.NativeGetItemText(index), true, CultureInfo.CurrentCulture) != 0) + { owner.NativeRemoveAt(index); owner.SelectedItems.SetSelected(index, false); owner.NativeInsert(index, value); owner.UpdateMaxItemWidth(value, false); - if (selected) { + if (selected) + { owner.SelectedIndex = index; } } - else { + else + { // FOR COMPATIBILITY REASONS - if (selected) { + if (selected) + { owner.OnSelectedIndexChanged(EventArgs.Empty); //will fire selectedvaluechanged } } @@ -3079,12 +3568,14 @@ internal void SetItemInternal(int index, object value) { //****************************************************************************************** // IntegerCollection - public class IntegerCollection : IList { + public class IntegerCollection : IList + { private ListBox owner; private int[] innerArray; - private int count=0; + private int count = 0; - public IntegerCollection(ListBox owner) { + public IntegerCollection(ListBox owner) + { this.owner = owner; } @@ -3092,45 +3583,59 @@ public IntegerCollection(ListBox owner) { /// Number of current selected items. /// [Browsable(false)] - public int Count { - get { + public int Count + { + get + { return count; } } - object ICollection.SyncRoot { - get { + object ICollection.SyncRoot + { + get + { return this; } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return true; } } - bool IList.IsFixedSize { - get { + bool IList.IsFixedSize + { + get + { return false; } } - bool IList.IsReadOnly { - get { + bool IList.IsReadOnly + { + get + { return false; } } - public bool Contains(int item) { + public bool Contains(int item) + { return IndexOf(item) != -1; } - bool IList.Contains(object item) { - if (item is int) { + bool IList.Contains(object item) + { + if (item is int) + { return Contains((int)item); } - else { + else + { return false; } } @@ -3141,17 +3646,20 @@ public void Clear() innerArray = null; } - public int IndexOf(int item) { + public int IndexOf(int item) + { int index = -1; - if (innerArray != null) { + if (innerArray != null) + { index = Array.IndexOf(innerArray, item); // We initialize innerArray with more elements than needed in the method EnsureSpace, // and we don't actually remove element from innerArray in the method RemoveAt, // so there maybe some elements which are not actually in innerArray will be found // and we need to filter them out - if (index >= count) { + if (index >= count) + { index = -1; } } @@ -3159,11 +3667,14 @@ public int IndexOf(int item) { return index; } - int IList.IndexOf(object item) { - if (item is int) { + int IList.IndexOf(object item) + { + if (item is int) + { return IndexOf((int)item); } - else { + else + { return -1; } } @@ -3174,17 +3685,19 @@ int IList.IndexOf(object item) { /// A SystemException occurs if there is insufficient space available to /// store the new item. /// - private int AddInternal(int item) { + private int AddInternal(int item) + { EnsureSpace(1); int index = IndexOf(item); - if (index == -1) { + if (index == -1) + { innerArray[count++] = item; - Array.Sort(innerArray,0,count); + Array.Sort(innerArray, 0, count); index = IndexOf(item); } - return index; + return index; } /// @@ -3192,7 +3705,8 @@ private int AddInternal(int item) { /// A SystemException occurs if there is insufficient space available to /// store the new item. /// - public int Add(int item) { + public int Add(int item) + { int index = AddInternal(item); owner.UpdateCustomTabOffsets(); @@ -3204,18 +3718,22 @@ public int Add(int item) { SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // "item" is the name of the param passed in. // So we don't have to localize it. ] - int IList.Add(object item) { - if (!(item is int)) { + int IList.Add(object item) + { + if (!(item is int)) + { throw new ArgumentException(nameof(item)); } return Add((int)item); } - public void AddRange(int[] items) { + public void AddRange(int[] items) + { AddRangeInternal((ICollection)items); } - public void AddRange(IntegerCollection value) { + public void AddRange(IntegerCollection value) + { AddRangeInternal((ICollection)value); } @@ -3227,19 +3745,24 @@ public void AddRange(IntegerCollection value) { SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // "item" is the name of the param passed in. // So we don't have to localize it. ] - private void AddRangeInternal(ICollection items) { - if (items == null) { + private void AddRangeInternal(ICollection items) + { + if (items == null) + { throw new ArgumentNullException(nameof(items)); } owner.BeginUpdate(); try { EnsureSpace(items.Count); - foreach(object item in items) { - if (!(item is int)) { + foreach (object item in items) + { + if (!(item is int)) + { throw new ArgumentException(nameof(item)); } - else { + else + { AddInternal((int)item); } } @@ -3256,11 +3779,14 @@ private void AddRangeInternal(ICollection items) { /// Ensures that our internal array has space for /// the requested # of elements. /// - private void EnsureSpace(int elements) { - if (innerArray == null) { + private void EnsureSpace(int elements) + { + if (innerArray == null) + { innerArray = new int[Math.Max(elements, 4)]; } - else if (count + elements >= innerArray.Length) { + else if (count + elements >= innerArray.Length) + { int newLength = Math.Max(innerArray.Length * 2, innerArray.Length + elements); int[] newEntries = new int[newLength]; innerArray.CopyTo(newEntries, 0); @@ -3268,11 +3794,13 @@ private void EnsureSpace(int elements) { } } - void IList.Clear() { + void IList.Clear() + { Clear(); } - void IList.Insert(int index, object value) { + void IList.Insert(int index, object value) + { throw new NotSupportedException(SR.ListBoxCantInsertIntoIntegerCollection); } @@ -3281,14 +3809,17 @@ void IList.Insert(int index, object value) { SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // "value" is the name of the param passed in. // So we don't have to localize it. ] - void IList.Remove(object value) { - if (!(value is int)) { + void IList.Remove(object value) + { + if (!(value is int)) + { throw new ArgumentException(nameof(value)); } Remove((int)value); } - void IList.RemoveAt(int index) { + void IList.RemoveAt(int index) + { RemoveAt(index); } @@ -3296,11 +3827,13 @@ void IList.RemoveAt(int index) { /// Removes the given item from the array. If /// the item is not in the array, this does nothing. /// - public void Remove(int item) { + public void Remove(int item) + { int index = IndexOf(item); - if (index != -1) { + if (index != -1) + { RemoveAt(index); } } @@ -3308,14 +3841,17 @@ public void Remove(int item) { /// /// Removes the item at the given index. /// - public void RemoveAt(int index) { - if (index < 0 || index >= count) { + public void RemoveAt(int index) + { + if (index < 0 || index >= count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } count--; - for (int i = index; i < count; i++) { - innerArray[i] = innerArray[i+1]; + for (int i = index; i < count; i++) + { + innerArray[i] = innerArray[i + 1]; } } @@ -3326,17 +3862,21 @@ public void RemoveAt(int index) { SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // "index" is the name of the param passed in. // So we don't have to localize it. ] - public int this[int index] { - get { + public int this[int index] + { + get + { return innerArray[index]; } [ SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly") // This exception already shipped. // We can't change its text. ] - set { + set + { - if (index < 0 || index >= count) { + if (index < 0 || index >= count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } innerArray[index] = (int)value; @@ -3347,8 +3887,10 @@ public int this[int index] { } [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] - object IList.this[int index] { - get { + object IList.this[int index] + { + get + { return this[index]; } [ @@ -3357,25 +3899,31 @@ object IList.this[int index] { SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly") // This exception already shipped. // We can't change its text. ] - set { - if (!(value is int)) { + set + { + if (!(value is int)) + { throw new ArgumentException(nameof(value)); } - else { + else + { this[index] = (int)value; } } } - public void CopyTo(Array destination, int index) { + public void CopyTo(Array destination, int index) + { int cnt = Count; - for (int i = 0; i < cnt; i++) { + for (int i = 0; i < cnt; i++) + { destination.SetValue(this[i], i + index); } } - IEnumerator IEnumerable.GetEnumerator() { + IEnumerator IEnumerable.GetEnumerator() + { return new CustomTabOffsetsEnumerator(this); } @@ -3383,14 +3931,16 @@ IEnumerator IEnumerable.GetEnumerator() { /// EntryEnumerator is an enumerator that will enumerate over /// a given state mask. /// - private class CustomTabOffsetsEnumerator : IEnumerator { + private class CustomTabOffsetsEnumerator : IEnumerator + { private IntegerCollection items; private int current; /// /// Creates a new enumerator that will enumerate over the given state. /// - public CustomTabOffsetsEnumerator(IntegerCollection items) { + public CustomTabOffsetsEnumerator(IntegerCollection items) + { this.items = items; this.current = -1; } @@ -3398,13 +3948,16 @@ public CustomTabOffsetsEnumerator(IntegerCollection items) { /// /// Moves to the next element, or returns false if at the end. /// - bool IEnumerator.MoveNext() { + bool IEnumerator.MoveNext() + { - if (current < items.Count - 1) { + if (current < items.Count - 1) + { current++; return true; } - else { + else + { current = items.Count; return false; } @@ -3413,16 +3966,20 @@ bool IEnumerator.MoveNext() { /// /// Resets the enumeration back to the beginning. /// - void IEnumerator.Reset() { + void IEnumerator.Reset() + { current = -1; } /// /// Retrieves the current value in the enumerator. /// - object IEnumerator.Current { - get { - if (current == -1 || current == items.Count) { + object IEnumerator.Current + { + get + { + if (current == -1 || current == items.Count) + { throw new InvalidOperationException(SR.ListEnumCurrentOutOfRange); } @@ -3435,11 +3992,13 @@ object IEnumerator.Current { //****************************************************************************************** // SelectedIndices - public class SelectedIndexCollection : IList { + public class SelectedIndexCollection : IList + { private ListBox owner; /* C#r: protected */ - public SelectedIndexCollection(ListBox owner) { + public SelectedIndexCollection(ListBox owner) + { this.owner = owner; } @@ -3447,50 +4006,65 @@ public SelectedIndexCollection(ListBox owner) { /// Number of current selected items. /// [Browsable(false)] - public int Count { - get { + public int Count + { + get + { return owner.SelectedItems.Count; } } - object ICollection.SyncRoot { - get { + object ICollection.SyncRoot + { + get + { return this; } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return true; } } - bool IList.IsFixedSize { - get { + bool IList.IsFixedSize + { + get + { return true; } } - public bool IsReadOnly { - get { + public bool IsReadOnly + { + get + { return true; } } - public bool Contains(int selectedIndex) { + public bool Contains(int selectedIndex) + { return IndexOf(selectedIndex) != -1; } - bool IList.Contains(object selectedIndex) { - if (selectedIndex is int) { + bool IList.Contains(object selectedIndex) + { + if (selectedIndex is int) + { return Contains((int)selectedIndex); } - else { + else + { return false; } } - public int IndexOf(int selectedIndex) { + public int IndexOf(int selectedIndex) + { // Just what does this do? The selectedIndex parameter above is the index into the // main object collection. We look at the state of that item, and if the state indicates @@ -3498,7 +4072,8 @@ public int IndexOf(int selectedIndex) { // this collection match those on the SelectedObjectCollection. if (selectedIndex >= 0 && selectedIndex < InnerArray.GetCount(0) && - InnerArray.GetState(selectedIndex, SelectedObjectCollection.SelectedObjectMask)) { + InnerArray.GetState(selectedIndex, SelectedObjectCollection.SelectedObjectMask)) + { return InnerArray.IndexOf(InnerArray.GetItem(selectedIndex, 0), SelectedObjectCollection.SelectedObjectMask); } @@ -3506,50 +4081,63 @@ public int IndexOf(int selectedIndex) { return -1; } - int IList.IndexOf(object selectedIndex) { - if (selectedIndex is int) { + int IList.IndexOf(object selectedIndex) + { + if (selectedIndex is int) + { return IndexOf((int)selectedIndex); } - else { + else + { return -1; } } - int IList.Add(object value) { + int IList.Add(object value) + { throw new NotSupportedException(SR.ListBoxSelectedIndexCollectionIsReadOnly); } - void IList.Clear() { + void IList.Clear() + { throw new NotSupportedException(SR.ListBoxSelectedIndexCollectionIsReadOnly); } - void IList.Insert(int index, object value) { + void IList.Insert(int index, object value) + { throw new NotSupportedException(SR.ListBoxSelectedIndexCollectionIsReadOnly); } - void IList.Remove(object value) { + void IList.Remove(object value) + { throw new NotSupportedException(SR.ListBoxSelectedIndexCollectionIsReadOnly); } - void IList.RemoveAt(int index) { + void IList.RemoveAt(int index) + { throw new NotSupportedException(SR.ListBoxSelectedIndexCollectionIsReadOnly); } /// /// Retrieves the specified selected item. /// - public int this[int index] { - get { + public int this[int index] + { + get + { object identifier = InnerArray.GetEntryObject(index, SelectedObjectCollection.SelectedObjectMask); return InnerArray.IndexOfIdentifier(identifier, 0); } } - object IList.this[int index] { - get { + object IList.this[int index] + { + get + { return this[index]; } - set { + set + { throw new NotSupportedException(SR.ListBoxSelectedIndexCollectionIsReadOnly); } } @@ -3558,49 +4146,64 @@ object IList.this[int index] { /// This is the item array that stores our data. We share this backing store /// with the main object collection. /// - private ItemArray InnerArray { - get { + private ItemArray InnerArray + { + get + { owner.SelectedItems.EnsureUpToDate(); return ((ObjectCollection)owner.Items).InnerArray; } } - public void CopyTo(Array destination, int index) { + public void CopyTo(Array destination, int index) + { int cnt = Count; - for (int i = 0; i < cnt; i++) { + for (int i = 0; i < cnt; i++) + { destination.SetValue(this[i], i + index); } } - public void Clear() { - if (owner != null) { + public void Clear() + { + if (owner != null) + { owner.ClearSelected(); } } - public void Add(int index) { - if (owner != null) { + public void Add(int index) + { + if (owner != null) + { ObjectCollection items = owner.Items; - if (items != null) { - if (index != -1 && !Contains(index)) { + if (items != null) + { + if (index != -1 && !Contains(index)) + { owner.SetSelected(index, true); } } } } - public void Remove(int index) { - if (owner != null) { + public void Remove(int index) + { + if (owner != null) + { ObjectCollection items = owner.Items; - if (items != null) { - if (index != -1 && Contains(index)) { + if (items != null) + { + if (index != -1 && Contains(index)) + { owner.SetSelected(index, false); } } } } - public IEnumerator GetEnumerator() { + public IEnumerator GetEnumerator() + { return new SelectedIndexEnumerator(this); } @@ -3608,14 +4211,16 @@ public IEnumerator GetEnumerator() { /// EntryEnumerator is an enumerator that will enumerate over /// a given state mask. /// - private class SelectedIndexEnumerator : IEnumerator { + private class SelectedIndexEnumerator : IEnumerator + { private SelectedIndexCollection items; private int current; /// /// Creates a new enumerator that will enumerate over the given state. /// - public SelectedIndexEnumerator(SelectedIndexCollection items) { + public SelectedIndexEnumerator(SelectedIndexCollection items) + { this.items = items; this.current = -1; } @@ -3623,13 +4228,16 @@ public SelectedIndexEnumerator(SelectedIndexCollection items) { /// /// Moves to the next element, or returns false if at the end. /// - bool IEnumerator.MoveNext() { + bool IEnumerator.MoveNext() + { - if (current < items.Count - 1) { + if (current < items.Count - 1) + { current++; return true; } - else { + else + { current = items.Count; return false; } @@ -3638,16 +4246,20 @@ bool IEnumerator.MoveNext() { /// /// Resets the enumeration back to the beginning. /// - void IEnumerator.Reset() { + void IEnumerator.Reset() + { current = -1; } /// /// Retrieves the current value in the enumerator. /// - object IEnumerator.Current { - get { - if (current == -1 || current == items.Count) { + object IEnumerator.Current + { + get + { + if (current == -1 || current == items.Count) + { throw new InvalidOperationException(SR.ListEnumCurrentOutOfRange); } @@ -3658,18 +4270,20 @@ object IEnumerator.Current { } // Should be "ObjectCollection", except we already have one of those. - public class SelectedObjectCollection : IList { + public class SelectedObjectCollection : IList + { // This is the bitmask used within ItemArray to identify selected objects. internal static int SelectedObjectMask = ItemArray.CreateMask(); private ListBox owner; - private bool stateDirty; - private int lastVersion; - private int count; + private bool stateDirty; + private int lastVersion; + private int count; /* C#r: protected */ - public SelectedObjectCollection(ListBox owner) { + public SelectedObjectCollection(ListBox owner) + { this.owner = owner; this.stateDirty = true; this.lastVersion = -1; @@ -3678,25 +4292,30 @@ public SelectedObjectCollection(ListBox owner) { /// /// Number of current selected items. /// - public int Count { - get { - if (owner.IsHandleCreated) { + public int Count + { + get + { + if (owner.IsHandleCreated) + { SelectionMode current = (owner.selectionModeChanging) ? owner.cachedSelectionMode : owner.selectionMode; - switch (current) { + switch (current) + { case SelectionMode.None: return 0; case SelectionMode.One: int index = owner.SelectedIndex; - if (index >= 0) { + if (index >= 0) + { return 1; } return 0; case SelectionMode.MultiSimple: case SelectionMode.MultiExtended: - return unchecked( (int) (long)owner.SendMessage(NativeMethods.LB_GETSELCOUNT, 0, 0)); + return unchecked((int)(long)owner.SendMessage(NativeMethods.LB_GETSELCOUNT, 0, 0)); } return 0; @@ -3705,7 +4324,8 @@ public int Count { // If the handle hasn't been created, we must do this the hard way. // Getting the count when using a mask is expensive, so cache it. // - if (lastVersion != InnerArray.Version) { + if (lastVersion != InnerArray.Version) + { lastVersion = InnerArray.Version; count = InnerArray.GetCount(SelectedObjectMask); } @@ -3714,20 +4334,26 @@ public int Count { } } - object ICollection.SyncRoot { - get { + object ICollection.SyncRoot + { + get + { return this; } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return false; } } - bool IList.IsFixedSize { - get { + bool IList.IsFixedSize + { + get + { return true; } } @@ -3735,7 +4361,8 @@ bool IList.IsFixedSize { /// /// Called by the list box to dirty the selected item state. /// - internal void Dirty() { + internal void Dirty() + { stateDirty = true; } @@ -3743,8 +4370,10 @@ internal void Dirty() { /// This is the item array that stores our data. We share this backing store /// with the main object collection. /// - private ItemArray InnerArray { - get { + private ItemArray InnerArray + { + get + { EnsureUpToDate(); return ((ObjectCollection)owner.Items).InnerArray; } @@ -3755,47 +4384,59 @@ private ItemArray InnerArray { /// This is the function that Ensures that the selections are uptodate with /// current listbox handle selections. /// - internal void EnsureUpToDate() { - if (stateDirty) { - stateDirty = false; - if (owner.IsHandleCreated) { - owner.NativeUpdateSelection(); - } + internal void EnsureUpToDate() + { + if (stateDirty) + { + stateDirty = false; + if (owner.IsHandleCreated) + { + owner.NativeUpdateSelection(); + } } } - public bool IsReadOnly { - get { + public bool IsReadOnly + { + get + { return true; } } - public bool Contains(object selectedObject) { + public bool Contains(object selectedObject) + { return IndexOf(selectedObject) != -1; } - public int IndexOf(object selectedObject) { + public int IndexOf(object selectedObject) + { return InnerArray.IndexOf(selectedObject, SelectedObjectMask); } - int IList.Add(object value) { + int IList.Add(object value) + { throw new NotSupportedException(SR.ListBoxSelectedObjectCollectionIsReadOnly); } - void IList.Clear() { + void IList.Clear() + { throw new NotSupportedException(SR.ListBoxSelectedObjectCollectionIsReadOnly); } - void IList.Insert(int index, object value) { + void IList.Insert(int index, object value) + { throw new NotSupportedException(SR.ListBoxSelectedObjectCollectionIsReadOnly); } - void IList.Remove(object value) { + void IList.Remove(object value) + { throw new NotSupportedException(SR.ListBoxSelectedObjectCollectionIsReadOnly); } - void IList.RemoveAt(int index) { + void IList.RemoveAt(int index) + { throw new NotSupportedException(SR.ListBoxSelectedObjectCollectionIsReadOnly); } @@ -3805,31 +4446,38 @@ void IList.RemoveAt(int index) { // This method returns the "object" at the passed index rather than the "item" ... // this "object" is then compared in the IndexOf( ) method of the itemsCollection. // - internal object GetObjectAt(int index) { - return InnerArray.GetEntryObject(index, SelectedObjectCollection.SelectedObjectMask); + internal object GetObjectAt(int index) + { + return InnerArray.GetEntryObject(index, SelectedObjectCollection.SelectedObjectMask); } /// /// Retrieves the specified selected item. /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public object this[int index] { - get { + public object this[int index] + { + get + { return InnerArray.GetItem(index, SelectedObjectMask); } - set { + set + { throw new NotSupportedException(SR.ListBoxSelectedObjectCollectionIsReadOnly); } } - public void CopyTo(Array destination, int index) { + public void CopyTo(Array destination, int index) + { int cnt = InnerArray.GetCount(SelectedObjectMask); - for (int i = 0; i < cnt; i++) { + for (int i = 0; i < cnt; i++) + { destination.SetValue(InnerArray.GetItem(i, SelectedObjectMask), i + index); } } - public IEnumerator GetEnumerator() { + public IEnumerator GetEnumerator() + { return InnerArray.GetEnumerator(SelectedObjectMask); } @@ -3837,18 +4485,21 @@ public IEnumerator GetEnumerator() { /// This method returns if the actual item index is selected. The index is the index to the MAIN /// collection, not this one. /// - internal bool GetSelected(int index) { + internal bool GetSelected(int index) + { return InnerArray.GetState(index, SelectedObjectMask); } // when SelectedObjectsCollection::ItemArray is accessed we push the selection from Native ListBox into our .Net ListBox - see EnsureUpToDate() // when we create the handle we need to be able to do the opposite : push the selection from .Net ListBox into Native ListBox - internal void PushSelectionIntoNativeListBox(int index) { + internal void PushSelectionIntoNativeListBox(int index) + { // we can't use ItemArray accessor because this will wipe out our Selection collection bool selected = ((ObjectCollection)owner.Items).InnerArray.GetState(index, SelectedObjectMask); // push selection only if the item is actually selected // this also takes care of the case where owner.SelectionMode == SelectionMode.One - if (selected) { + if (selected) + { this.owner.NativeSetSelected(index, true /*we signal selection to the native listBox only if the item is actually selected*/); } } @@ -3856,34 +4507,45 @@ internal void PushSelectionIntoNativeListBox(int index) { /// /// Same thing for GetSelected. /// - internal void SetSelected(int index, bool value) { + internal void SetSelected(int index, bool value) + { InnerArray.SetState(index, SelectedObjectMask, value); } - public void Clear() { - if (owner != null) { + public void Clear() + { + if (owner != null) + { owner.ClearSelected(); } } - public void Add(object value) { - if (owner != null) { + public void Add(object value) + { + if (owner != null) + { ObjectCollection items = owner.Items; - if (items != null && value != null) { + if (items != null && value != null) + { int index = items.IndexOf(value); - if (index != -1 && !GetSelected(index)) { + if (index != -1 && !GetSelected(index)) + { owner.SelectedIndex = index; } } } } - public void Remove(object value) { - if (owner != null) { + public void Remove(object value) + { + if (owner != null) + { ObjectCollection items = owner.Items; - if (items != null & value != null) { + if (items != null & value != null) + { int index = items.IndexOf(value); - if (index != -1 && GetSelected(index)) { + if (index != -1 && GetSelected(index)) + { owner.SetSelected(index, false); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListControl.cs index 41becd780ec..6a56b34f3e7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListControl.cs @@ -309,7 +309,7 @@ public string ValueMember { SetDataConnection(DataSource, newValueMember, force: false); } - + // See if the valueMember is a member of // the properties in the dataManager if (DataManager != null && !string.IsNullOrEmpty(value)) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListItemConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListItemConverter.cs index 0b32dc14511..0a071c20e74 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListItemConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListItemConverter.cs @@ -51,13 +51,13 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul { ConstructorInfo ctor; // Should we use the subitem constructor? - for(int i = 1; i < item.SubItems.Count; ++i) + for (int i = 1; i < item.SubItems.Count; ++i) { if (item.SubItems[i].CustomStyle) { if (!string.IsNullOrEmpty(item.ImageKey)) { - ctor = typeof(ListViewItem).GetConstructor(new Type[] { typeof(ListViewItem.ListViewSubItem[]), typeof(string)}); + ctor = typeof(ListViewItem).GetConstructor(new Type[] { typeof(ListViewItem.ListViewSubItem[]), typeof(string) }); Debug.Assert(ctor != null, "Expected the constructor to exist."); ListViewItem.ListViewSubItem[] subItemArray = new ListViewItem.ListViewSubItem[item.SubItems.Count]; ((ICollection)item.SubItems).CopyTo(subItemArray, 0); @@ -65,7 +65,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul } else { - ctor = typeof(ListViewItem).GetConstructor(new Type[] { typeof(ListViewItem.ListViewSubItem[]), typeof(int)}); + ctor = typeof(ListViewItem).GetConstructor(new Type[] { typeof(ListViewItem.ListViewSubItem[]), typeof(int) }); Debug.Assert(ctor != null, "Expected the constructor to exist."); ListViewItem.ListViewSubItem[] subItemArray = new ListViewItem.ListViewSubItem[item.SubItems.Count]; ((ICollection)item.SubItems).CopyTo(subItemArray, 0); @@ -76,7 +76,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul // Convert SubItem array to string array string[] subItems = new string[item.SubItems.Count]; - for(int i=0; i < subItems.Length; ++i) + for (int i = 0; i < subItems.Length; ++i) { subItems[i] = item.SubItems[i].Text; } @@ -233,7 +233,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul // Otherwise, just use the text constructor ctor = typeof(ListViewItem.ListViewSubItem).GetConstructor(new Type[] { typeof(ListViewItem), typeof(string) }); Debug.Assert(ctor != null, "Expected the constructor to exist."); - return new InstanceDescriptor(ctor, new object[] {null, item.Text}, true); + return new InstanceDescriptor(ctor, new object[] { null, item.Text }, true); } return base.ConvertTo(context, culture, value, destinationType); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs index 2c125e9f17b..9a181e17b38 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System; using System.Collections; @@ -37,79 +38,80 @@ namespace System.Windows.Forms { DefaultEvent(nameof(SelectedIndexChanged)), SRDescription(nameof(SR.DescriptionListView)) ] - public class ListView : Control { + public class ListView : Control + { //members private const int MASK_HITTESTFLAG = 0x00F7; - private static readonly object EVENT_CACHEVIRTUALITEMS = new object(); - private static readonly object EVENT_COLUMNREORDERED = new object(); - private static readonly object EVENT_COLUMNWIDTHCHANGED = new object(); - private static readonly object EVENT_COLUMNWIDTHCHANGING = new object(); - private static readonly object EVENT_DRAWCOLUMNHEADER = new object(); - private static readonly object EVENT_DRAWITEM = new object(); - private static readonly object EVENT_DRAWSUBITEM = new object(); - private static readonly object EVENT_ITEMSELECTIONCHANGED = new object(); - private static readonly object EVENT_RETRIEVEVIRTUALITEM = new object(); - private static readonly object EVENT_SEARCHFORVIRTUALITEM = new object(); - private static readonly object EVENT_SELECTEDINDEXCHANGED = new object(); + private static readonly object EVENT_CACHEVIRTUALITEMS = new object(); + private static readonly object EVENT_COLUMNREORDERED = new object(); + private static readonly object EVENT_COLUMNWIDTHCHANGED = new object(); + private static readonly object EVENT_COLUMNWIDTHCHANGING = new object(); + private static readonly object EVENT_DRAWCOLUMNHEADER = new object(); + private static readonly object EVENT_DRAWITEM = new object(); + private static readonly object EVENT_DRAWSUBITEM = new object(); + private static readonly object EVENT_ITEMSELECTIONCHANGED = new object(); + private static readonly object EVENT_RETRIEVEVIRTUALITEM = new object(); + private static readonly object EVENT_SEARCHFORVIRTUALITEM = new object(); + private static readonly object EVENT_SELECTEDINDEXCHANGED = new object(); private static readonly object EVENT_VIRTUALITEMSSELECTIONRANGECHANGED = new object(); - private static readonly object EVENT_RIGHTTOLEFTLAYOUTCHANGED = new object(); + private static readonly object EVENT_RIGHTTOLEFTLAYOUTCHANGED = new object(); - private ItemActivation activation = ItemActivation.Standard; - private ListViewAlignment alignStyle = ListViewAlignment.Top; - private BorderStyle borderStyle = System.Windows.Forms.BorderStyle.Fixed3D; + private ItemActivation activation = ItemActivation.Standard; + private ListViewAlignment alignStyle = ListViewAlignment.Top; + private BorderStyle borderStyle = System.Windows.Forms.BorderStyle.Fixed3D; private ColumnHeaderStyle headerStyle = ColumnHeaderStyle.Clickable; - private SortOrder sorting = SortOrder.None; - private View viewStyle = System.Windows.Forms.View.LargeIcon; + private SortOrder sorting = SortOrder.None; + private View viewStyle = System.Windows.Forms.View.LargeIcon; private string toolTipCaption = string.Empty; - private const int LISTVIEWSTATE_ownerDraw = 0x00000001; - private const int LISTVIEWSTATE_allowColumnReorder = 0x00000002; - private const int LISTVIEWSTATE_autoArrange = 0x00000004; - private const int LISTVIEWSTATE_checkBoxes = 0x00000008; - private const int LISTVIEWSTATE_fullRowSelect = 0x00000010; - private const int LISTVIEWSTATE_gridLines = 0x00000020; - private const int LISTVIEWSTATE_hideSelection = 0x00000040; - private const int LISTVIEWSTATE_hotTracking = 0x00000080; - private const int LISTVIEWSTATE_labelEdit = 0x00000100; - private const int LISTVIEWSTATE_labelWrap = 0x00000200; - private const int LISTVIEWSTATE_multiSelect = 0x00000400; - private const int LISTVIEWSTATE_scrollable = 0x00000800; - private const int LISTVIEWSTATE_hoverSelection = 0x00001000; - private const int LISTVIEWSTATE_nonclickHdr = 0x00002000; - private const int LISTVIEWSTATE_inLabelEdit = 0x00004000; - private const int LISTVIEWSTATE_showItemToolTips = 0x00008000; - private const int LISTVIEWSTATE_backgroundImageTiled = 0x00010000; - private const int LISTVIEWSTATE_columnClicked = 0x00020000; - private const int LISTVIEWSTATE_doubleclickFired = 0x00040000; - private const int LISTVIEWSTATE_mouseUpFired = 0x00080000; - private const int LISTVIEWSTATE_expectingMouseUp = 0x00100000; - private const int LISTVIEWSTATE_comctlSupportsVisualStyles = 0x00200000; - private const int LISTVIEWSTATE_comctlSupportsVisualStylesTested = 0x00400000; - private const int LISTVIEWSTATE_showGroups = 0x00800000; - private const int LISTVIEWSTATE_handleDestroyed = 0x01000000; // while we are recreating the handle we want to know if we can still get data from the handle - private const int LISTVIEWSTATE_virtualMode = 0x02000000; - private const int LISTVIEWSTATE_headerControlTracking = 0x04000000; - private const int LISTVIEWSTATE_itemCollectionChangedInMouseDown = 0x08000000; - private const int LISTVIEWSTATE_flipViewToLargeIconAndSmallIcon = 0x10000000; - private const int LISTVIEWSTATE_headerDividerDblClick = 0x20000000; - private const int LISTVIEWSTATE_columnResizeCancelled = 0x40000000; - - private const int LISTVIEWSTATE1_insertingItemsNatively = 0x00000001; - private const int LISTVIEWSTATE1_cancelledColumnWidthChanging = 0x00000002; - private const int LISTVIEWSTATE1_disposingImageLists = 0x00000004; - private const int LISTVIEWSTATE1_useCompatibleStateImageBehavior = 0x00000008; - private const int LISTVIEWSTATE1_selectedIndexChangedSkipped = 0x00000010; - - private const int LVTOOLTIPTRACKING = 0x30; - private const int MAXTILECOLUMNS = 20; + private const int LISTVIEWSTATE_ownerDraw = 0x00000001; + private const int LISTVIEWSTATE_allowColumnReorder = 0x00000002; + private const int LISTVIEWSTATE_autoArrange = 0x00000004; + private const int LISTVIEWSTATE_checkBoxes = 0x00000008; + private const int LISTVIEWSTATE_fullRowSelect = 0x00000010; + private const int LISTVIEWSTATE_gridLines = 0x00000020; + private const int LISTVIEWSTATE_hideSelection = 0x00000040; + private const int LISTVIEWSTATE_hotTracking = 0x00000080; + private const int LISTVIEWSTATE_labelEdit = 0x00000100; + private const int LISTVIEWSTATE_labelWrap = 0x00000200; + private const int LISTVIEWSTATE_multiSelect = 0x00000400; + private const int LISTVIEWSTATE_scrollable = 0x00000800; + private const int LISTVIEWSTATE_hoverSelection = 0x00001000; + private const int LISTVIEWSTATE_nonclickHdr = 0x00002000; + private const int LISTVIEWSTATE_inLabelEdit = 0x00004000; + private const int LISTVIEWSTATE_showItemToolTips = 0x00008000; + private const int LISTVIEWSTATE_backgroundImageTiled = 0x00010000; + private const int LISTVIEWSTATE_columnClicked = 0x00020000; + private const int LISTVIEWSTATE_doubleclickFired = 0x00040000; + private const int LISTVIEWSTATE_mouseUpFired = 0x00080000; + private const int LISTVIEWSTATE_expectingMouseUp = 0x00100000; + private const int LISTVIEWSTATE_comctlSupportsVisualStyles = 0x00200000; + private const int LISTVIEWSTATE_comctlSupportsVisualStylesTested = 0x00400000; + private const int LISTVIEWSTATE_showGroups = 0x00800000; + private const int LISTVIEWSTATE_handleDestroyed = 0x01000000; // while we are recreating the handle we want to know if we can still get data from the handle + private const int LISTVIEWSTATE_virtualMode = 0x02000000; + private const int LISTVIEWSTATE_headerControlTracking = 0x04000000; + private const int LISTVIEWSTATE_itemCollectionChangedInMouseDown = 0x08000000; + private const int LISTVIEWSTATE_flipViewToLargeIconAndSmallIcon = 0x10000000; + private const int LISTVIEWSTATE_headerDividerDblClick = 0x20000000; + private const int LISTVIEWSTATE_columnResizeCancelled = 0x40000000; + + private const int LISTVIEWSTATE1_insertingItemsNatively = 0x00000001; + private const int LISTVIEWSTATE1_cancelledColumnWidthChanging = 0x00000002; + private const int LISTVIEWSTATE1_disposingImageLists = 0x00000004; + private const int LISTVIEWSTATE1_useCompatibleStateImageBehavior = 0x00000008; + private const int LISTVIEWSTATE1_selectedIndexChangedSkipped = 0x00000010; + + private const int LVTOOLTIPTRACKING = 0x30; + private const int MAXTILECOLUMNS = 20; // PERF: take all the bools and put them into a state variable - private System.Collections.Specialized.BitVector32 listViewState; // see LISTVIEWSTATE_ consts above - private System.Collections.Specialized.BitVector32 listViewState1;// see LISTVIEWSTATE1_ consts above + private System.Collections.Specialized.BitVector32 listViewState; // see LISTVIEWSTATE_ consts above + private System.Collections.Specialized.BitVector32 listViewState1;// see LISTVIEWSTATE1_ consts above @@ -129,10 +131,10 @@ public class ListView : Control { private MouseButtons downButton; private int itemCount; private int columnIndex = 0; - private int topIndex; - private bool hoveredAlready = false; + private int topIndex; + private bool hoveredAlready = false; - private bool rightToLeftLayout = false; + private bool rightToLeftLayout = false; // member variables which are used for VirtualMode @@ -154,9 +156,9 @@ public class ListView : Control { // add until EndUpdate is called. To do that, we push in an array list into our PropertyStore // under this key. When Endupdate is fired, we process the items all at once. // - private static readonly int PropDelayedUpdateItems = PropertyStore.CreateKey(); + private static readonly int PropDelayedUpdateItems = PropertyStore.CreateKey(); - private int updateCounter = 0; // the counter we use to track how many BeginUpdate/EndUpdate calls there have been. + private int updateCounter = 0; // the counter we use to track how many BeginUpdate/EndUpdate calls there have been. private ColumnHeader[] columnHeaders; private ListViewItemCollection listItemCollection; @@ -198,7 +200,7 @@ public class ListView : Control { // background image until it gets the first WM_PAINT message - I use words like *seems* because nothing is guaranteed // when it comes to win32 listView. // so our wrapper has to hang on to the previousBackgroundImageFileNames and destroy them after it gets the first WM_PAINT message - + int bkImgFileNamesCount = -1; string[] bkImgFileNames = null; private const int BKIMGARRAYSIZE = 8; @@ -218,7 +220,8 @@ public class ListView : Control { /// /// Creates an empty ListView with default styles. /// - public ListView() : base() { + public ListView() : base() + { int listViewStateFlags = LISTVIEWSTATE_scrollable | LISTVIEWSTATE_multiSelect | @@ -235,7 +238,7 @@ public ListView() : base() { odCacheFont = Font; odCacheFontHandle = FontHandle; - SetBounds(0,0,121,97); + SetBounds(0, 0, 121, 97); listItemCollection = new ListViewItemCollection(new ListViewNativeItemCollection(this)); columnHeaderCollection = new ColumnHeaderCollection(this); @@ -250,22 +253,28 @@ public ListView() : base() { DefaultValue(ItemActivation.Standard), SRDescription(nameof(SR.ListViewActivationDescr)) ] - public ItemActivation Activation { - get { + public ItemActivation Activation + { + get + { return activation; } - set { + set + { //valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)ItemActivation.Standard, (int)ItemActivation.TwoClick)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)ItemActivation.Standard, (int)ItemActivation.TwoClick)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ItemActivation)); } - if (this.HotTracking && value != ItemActivation.OneClick) { + if (this.HotTracking && value != ItemActivation.OneClick) + { throw new ArgumentException(SR.ListViewActivationMustBeOnWhenHotTrackingIsOn, "value"); } - if (activation != value) { + if (activation != value) + { activation = value; UpdateExtendedStyles(); } @@ -282,12 +291,15 @@ public ItemActivation Activation { Localizable(true), SRDescription(nameof(SR.ListViewAlignmentDescr)) ] - public ListViewAlignment Alignment { - get { + public ListViewAlignment Alignment + { + get + { return alignStyle; } - set { + set + { // using this as ListViewAlignment has discontiguous values. if (!ClientUtils.IsEnumValid_NotSequential(value, (int)value, @@ -298,7 +310,8 @@ public ListViewAlignment Alignment { { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ListViewAlignment)); } - if (alignStyle != value) { + if (alignStyle != value) + { alignStyle = value; RecreateHandleInternal(); } @@ -315,13 +328,17 @@ public ListViewAlignment Alignment { DefaultValue(false), SRDescription(nameof(SR.ListViewAllowColumnReorderDescr)) ] - public bool AllowColumnReorder { - get { + public bool AllowColumnReorder + { + get + { return listViewState[LISTVIEWSTATE_allowColumnReorder]; } - set { - if (AllowColumnReorder != value) { + set + { + if (AllowColumnReorder != value) + { listViewState[LISTVIEWSTATE_allowColumnReorder] = value; UpdateExtendedStyles(); } @@ -338,48 +355,62 @@ public bool AllowColumnReorder { DefaultValue(true), SRDescription(nameof(SR.ListViewAutoArrangeDescr)) ] - public bool AutoArrange { - get { + public bool AutoArrange + { + get + { return listViewState[LISTVIEWSTATE_autoArrange]; } - set { - if (AutoArrange != value) { + set + { + if (AutoArrange != value) + { listViewState[LISTVIEWSTATE_autoArrange] = value; UpdateStyles(); } } } - public override Color BackColor { - get { - if (ShouldSerializeBackColor()) { + public override Color BackColor + { + get + { + if (ShouldSerializeBackColor()) + { return base.BackColor; } - else { + else + { return SystemColors.Window; } } - set { + set + { base.BackColor = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(NativeMethods.LVM_SETBKCOLOR, 0, ColorTranslator.ToWin32(BackColor)); } } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { + new public event EventHandler BackgroundImageLayoutChanged + { add => base.BackgroundImageLayoutChanged += value; remove => base.BackgroundImageLayoutChanged -= value; } @@ -389,14 +420,19 @@ public override ImageLayout BackgroundImageLayout { DefaultValue(false), SRDescription(nameof(SR.ListViewBackgroundImageTiledDescr)) ] - public bool BackgroundImageTiled { - get { + public bool BackgroundImageTiled + { + get + { return listViewState[LISTVIEWSTATE_backgroundImageTiled]; } - set { - if (BackgroundImageTiled != value) { + set + { + if (BackgroundImageTiled != value) + { listViewState[LISTVIEWSTATE_backgroundImageTiled] = value; - if (IsHandleCreated && BackgroundImage != null) { + if (IsHandleCreated && BackgroundImage != null) + { // Don't call SetBackgroundImage because SetBackgroundImage deletes the existing image // We don't need to delete it and this causes BAD problems w/ the Win32 list view control. NativeMethods.LVBKIMAGE lvbkImage = new NativeMethods.LVBKIMAGE(); @@ -408,7 +444,7 @@ public bool BackgroundImageTiled { else lvbkImage.ulFlags = NativeMethods.LVBKIF_STYLE_NORMAL; - lvbkImage.ulFlags |= NativeMethods.LVBKIF_SOURCE_URL; + lvbkImage.ulFlags |= NativeMethods.LVBKIF_SOURCE_URL; lvbkImage.pszImage = this.backgroundImageFileName; lvbkImage.cchImageMax = this.backgroundImageFileName.Length + 1; @@ -427,19 +463,23 @@ public bool BackgroundImageTiled { DispId(NativeMethods.ActiveX.DISPID_BORDERSTYLE), SRDescription(nameof(SR.borderStyleDescr)) ] - public BorderStyle BorderStyle { - get { + public BorderStyle BorderStyle + { + get + { return borderStyle; } - set { + set + { //valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(BorderStyle)); } - if (borderStyle != value) { + if (borderStyle != value) + { borderStyle = value; UpdateStyles(); } @@ -455,62 +495,79 @@ public BorderStyle BorderStyle { DefaultValue(false), SRDescription(nameof(SR.ListViewCheckBoxesDescr)) ] - public bool CheckBoxes { - get { + public bool CheckBoxes + { + get + { return listViewState[LISTVIEWSTATE_checkBoxes]; } - set { - if (this.UseCompatibleStateImageBehavior) { - if (CheckBoxes != value) { - - if (value && this.View == View.Tile) { + set + { + if (this.UseCompatibleStateImageBehavior) + { + if (CheckBoxes != value) + { + + if (value && this.View == View.Tile) + { throw new NotSupportedException(SR.ListViewCheckBoxesNotSupportedInTileView); } - if (CheckBoxes) { + if (CheckBoxes) + { // Save away the checked items just in case we re-activate checkboxes // savedCheckedItems = new List(CheckedItems.Count); ListViewItem[] items = new ListViewItem[CheckedItems.Count]; CheckedItems.CopyTo(items, 0); - for (int i = 0; i < items.Length; i ++) { + for (int i = 0; i < items.Length; i++) + { savedCheckedItems.Add(items[i]); } } - + listViewState[LISTVIEWSTATE_checkBoxes] = value; UpdateExtendedStyles(); - - if (CheckBoxes && savedCheckedItems != null) { + + if (CheckBoxes && savedCheckedItems != null) + { // Check the saved checked items. // - if (savedCheckedItems.Count > 0) { - foreach(ListViewItem item in savedCheckedItems) { + if (savedCheckedItems.Count > 0) + { + foreach (ListViewItem item in savedCheckedItems) + { item.Checked = true; } } savedCheckedItems = null; - } - + } + // Comctl should handle auto-arrange for us, but doesn't if (AutoArrange) ArrangeIcons(Alignment); } - } else { - if (CheckBoxes != value) { + } + else + { + if (CheckBoxes != value) + { - if (value && this.View == View.Tile) { + if (value && this.View == View.Tile) + { throw new NotSupportedException(SR.ListViewCheckBoxesNotSupportedInTileView); } - if (CheckBoxes) { + if (CheckBoxes) + { // Save away the checked items just in case we re-activate checkboxes // savedCheckedItems = new List(CheckedItems.Count); ListViewItem[] items = new ListViewItem[CheckedItems.Count]; CheckedItems.CopyTo(items, 0); - for (int i = 0; i < items.Length; i ++) { + for (int i = 0; i < items.Length; i++) + { savedCheckedItems.Add(items[i]); } } @@ -520,7 +577,8 @@ public bool CheckBoxes { if ((!value && this.StateImageList != null && this.IsHandleCreated) || (!value && this.Alignment == ListViewAlignment.Left && this.IsHandleCreated) || (value && this.View == View.List && this.IsHandleCreated) || - (value && (this.View == View.SmallIcon || this.View == View.LargeIcon) && this.IsHandleCreated)) { + (value && (this.View == View.SmallIcon || this.View == View.LargeIcon) && this.IsHandleCreated)) + { // we have to recreate the handle when we are going from CheckBoxes == true to CheckBoxes == false // if we want to have the bitmaps from the StateImageList on the items. @@ -533,16 +591,21 @@ public bool CheckBoxes { *** we need to recreate the handle when we set CheckBoxes to TRUE **/ RecreateHandleInternal(); - } else { + } + else + { UpdateExtendedStyles(); } - if (CheckBoxes && savedCheckedItems != null) { + if (CheckBoxes && savedCheckedItems != null) + { // Check the saved checked items. // - if (savedCheckedItems.Count > 0) { - foreach(ListViewItem item in savedCheckedItems) { + if (savedCheckedItems.Count > 0) + { + foreach (ListViewItem item in savedCheckedItems) + { item.Checked = true; } } @@ -552,16 +615,21 @@ public bool CheckBoxes { // Setting the LVS_CHECKBOXES window style also causes the ListView to display the default checkbox // images rather than the user specified StateImageList. We send a LVM_SETIMAGELIST to restore the // user's images. - if (IsHandleCreated && imageListState != null) { - if (CheckBoxes) { // we want custom checkboxes + if (IsHandleCreated && imageListState != null) + { + if (CheckBoxes) + { // we want custom checkboxes SendMessage(NativeMethods.LVM_SETIMAGELIST, NativeMethods.LVSIL_STATE, imageListState.Handle); - } else { + } + else + { SendMessage(NativeMethods.LVM_SETIMAGELIST, NativeMethods.LVSIL_STATE, IntPtr.Zero); } } // Comctl should handle auto-arrange for us, but doesn't - if (AutoArrange) { + if (AutoArrange) + { ArrangeIcons(Alignment); } @@ -577,9 +645,12 @@ public bool CheckBoxes { Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public CheckedIndexCollection CheckedIndices { - get { - if (checkedIndexCollection == null) { + public CheckedIndexCollection CheckedIndices + { + get + { + if (checkedIndexCollection == null) + { checkedIndexCollection = new CheckedIndexCollection(this); } return checkedIndexCollection; @@ -593,9 +664,12 @@ public CheckedIndexCollection CheckedIndices { Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public CheckedListViewItemCollection CheckedItems { - get { - if (checkedListViewItemCollection == null) { + public CheckedListViewItemCollection CheckedItems + { + get + { + if (checkedListViewItemCollection == null) + { checkedListViewItemCollection = new CheckedListViewItemCollection(this); } return checkedListViewItemCollection; @@ -605,13 +679,15 @@ public CheckedListViewItemCollection CheckedItems { [ SRCategory(nameof(SR.CatBehavior)), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), - Editor("System.Windows.Forms.Design.ColumnHeaderCollectionEditor, " + AssemblyRef.SystemDesign,typeof(UITypeEditor)), + Editor("System.Windows.Forms.Design.ColumnHeaderCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), SRDescription(nameof(SR.ListViewColumnsDescr)), Localizable(true), MergableProperty(false) ] - public ColumnHeaderCollection Columns { - get { + public ColumnHeaderCollection Columns + { + get + { return columnHeaderCollection; } } @@ -621,35 +697,42 @@ public ColumnHeaderCollection Columns { /// the new listview features. This is true for ComCtl 6 and above, same as /// the versions that support visual styles. /// - private bool ComctlSupportsVisualStyles { - get { - if(!listViewState[LISTVIEWSTATE_comctlSupportsVisualStylesTested]) { - listViewState[LISTVIEWSTATE_comctlSupportsVisualStylesTested] = true; - listViewState[LISTVIEWSTATE_comctlSupportsVisualStyles] = Application.ComCtlSupportsVisualStyles; - } - return listViewState[LISTVIEWSTATE_comctlSupportsVisualStyles]; - } + private bool ComctlSupportsVisualStyles + { + get + { + if (!listViewState[LISTVIEWSTATE_comctlSupportsVisualStylesTested]) + { + listViewState[LISTVIEWSTATE_comctlSupportsVisualStylesTested] = true; + listViewState[LISTVIEWSTATE_comctlSupportsVisualStyles] = Application.ComCtlSupportsVisualStyles; + } + return listViewState[LISTVIEWSTATE_comctlSupportsVisualStyles]; + } } /// /// Computes the handle creation parameters for the ListView control. /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ClassName = NativeMethods.WC_LISTVIEW; // Keep the scrollbar if we are just updating styles... // - if (IsHandleCreated) { + if (IsHandleCreated) + { int currentStyle = unchecked((int)((long)UnsafeNativeMethods.GetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_STYLE))); cp.Style |= (currentStyle & (NativeMethods.WS_HSCROLL | NativeMethods.WS_VSCROLL)); } cp.Style |= NativeMethods.LVS_SHAREIMAGELISTS; - switch (alignStyle) { + switch (alignStyle) + { case ListViewAlignment.Top: cp.Style |= NativeMethods.LVS_ALIGNTOP; break; @@ -661,7 +744,8 @@ protected override CreateParams CreateParams { if (AutoArrange) cp.Style |= NativeMethods.LVS_AUTOARRANGE; - switch (borderStyle) { + switch (borderStyle) + { case BorderStyle.Fixed3D: cp.ExStyle |= NativeMethods.WS_EX_CLIENTEDGE; break; @@ -670,7 +754,8 @@ protected override CreateParams CreateParams { break; } - switch (headerStyle) { + switch (headerStyle) + { case ColumnHeaderStyle.None: cp.Style |= NativeMethods.LVS_NOCOLUMNHEADER; break; @@ -691,8 +776,10 @@ protected override CreateParams CreateParams { if (!MultiSelect) cp.Style |= NativeMethods.LVS_SINGLESEL; - if (listItemSorter == null) { - switch (sorting) { + if (listItemSorter == null) + { + switch (sorting) + { case SortOrder.Ascending: cp.Style |= NativeMethods.LVS_SORTASCENDING; break; @@ -708,11 +795,13 @@ protected override CreateParams CreateParams { // We can do this 'cuz the viewStyle enums are the same values as the actual LVS styles // this new check since the value for LV_VIEW_TILE == LVS_SINGLESEL; so dont OR that value since // LV_VIEW_TILE is not a STYLE but should be Send via a SENDMESSAGE. - if (viewStyle != View.Tile ) { + if (viewStyle != View.Tile) + { cp.Style |= (int)viewStyle; } - if (RightToLeft == RightToLeft.Yes && RightToLeftLayout == true) { + if (RightToLeft == RightToLeft.Yes && RightToLeftLayout == true) + { //We want to turn on mirroring for Form explicitly. cp.ExStyle |= NativeMethods.WS_EX_LAYOUTRTL; //Don't need these styles when mirroring is turned on. @@ -722,10 +811,12 @@ protected override CreateParams CreateParams { } } - internal ListViewGroup DefaultGroup { + internal ListViewGroup DefaultGroup + { get { - if (defaultGroup == null) { + if (defaultGroup == null) + { defaultGroup = new ListViewGroup(string.Format(SR.ListViewGroupDefaultGroup, "1")); } return defaultGroup; @@ -744,11 +835,14 @@ protected override Size DefaultSize } } - protected override bool DoubleBuffered { - get { + protected override bool DoubleBuffered + { + get + { return base.DoubleBuffered; } - set { + set + { if (this.DoubleBuffered != value) { base.DoubleBuffered = value; @@ -757,8 +851,10 @@ protected override bool DoubleBuffered { } } - internal bool ExpectingMouseUp { - get { + internal bool ExpectingMouseUp + { + get + { return this.listViewState[LISTVIEWSTATE_expectingMouseUp]; } } @@ -774,17 +870,22 @@ internal bool ExpectingMouseUp { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ListViewFocusedItemDescr)) ] - public ListViewItem FocusedItem { - get { - if (IsHandleCreated) { - int displayIndex = unchecked( (int) (long)SendMessage(NativeMethods.LVM_GETNEXTITEM, -1, NativeMethods.LVNI_FOCUSED)); + public ListViewItem FocusedItem + { + get + { + if (IsHandleCreated) + { + int displayIndex = unchecked((int)(long)SendMessage(NativeMethods.LVM_GETNEXTITEM, -1, NativeMethods.LVNI_FOCUSED)); if (displayIndex > -1) return Items[displayIndex]; } return null; } - set { - if (IsHandleCreated && value != null) { + set + { + if (IsHandleCreated && value != null) + { value.Focused = true; } } @@ -792,31 +893,39 @@ public ListViewItem FocusedItem { public override Color ForeColor { - get { - if (ShouldSerializeForeColor()) { + get + { + if (ShouldSerializeForeColor()) + { return base.ForeColor; } - else { + else + { return SystemColors.WindowText; } } - set { + set + { base.ForeColor = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(NativeMethods.LVM_SETTEXTCOLOR, 0, ColorTranslator.ToWin32(ForeColor)); } } } - private bool FlipViewToLargeIconAndSmallIcon { - get { + private bool FlipViewToLargeIconAndSmallIcon + { + get + { // it never hurts to check that our house is in order Debug.Assert(!this.listViewState[LISTVIEWSTATE_flipViewToLargeIconAndSmallIcon] || this.View == View.SmallIcon, "we need this bit only in SmallIcon view"); Debug.Assert(!this.listViewState[LISTVIEWSTATE_flipViewToLargeIconAndSmallIcon] || this.ComctlSupportsVisualStyles, "we need this bit only when loading ComCtl 6.0"); return this.listViewState[LISTVIEWSTATE_flipViewToLargeIconAndSmallIcon]; } - set { + set + { // it never hurts to check that our house is in order Debug.Assert(!value || this.View == View.SmallIcon, "we need this bit only in SmallIcon view"); Debug.Assert(!value || this.ComctlSupportsVisualStyles, "we need this bit only when loading ComCtl 6.0"); @@ -835,12 +944,16 @@ private bool FlipViewToLargeIconAndSmallIcon { DefaultValue(false), SRDescription(nameof(SR.ListViewFullRowSelectDescr)) ] - public bool FullRowSelect { - get { + public bool FullRowSelect + { + get + { return listViewState[LISTVIEWSTATE_fullRowSelect]; } - set { - if (FullRowSelect != value) { + set + { + if (FullRowSelect != value) + { listViewState[LISTVIEWSTATE_fullRowSelect] = value; UpdateExtendedStyles(); } @@ -856,13 +969,17 @@ public bool FullRowSelect { DefaultValue(false), SRDescription(nameof(SR.ListViewGridLinesDescr)) ] - public bool GridLines { - get { + public bool GridLines + { + get + { return listViewState[LISTVIEWSTATE_gridLines]; } - set { - if (GridLines != value) { + set + { + if (GridLines != value) + { listViewState[LISTVIEWSTATE_gridLines] = value; UpdateExtendedStyles(); } @@ -876,14 +993,16 @@ public bool GridLines { SRCategory(nameof(SR.CatBehavior)), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), Localizable(true), - Editor("System.Windows.Forms.Design.ListViewGroupCollectionEditor, " + AssemblyRef.SystemDesign,typeof(UITypeEditor)), + Editor("System.Windows.Forms.Design.ListViewGroupCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), SRDescription(nameof(SR.ListViewGroupsDescr)), MergableProperty(false) ] - public ListViewGroupCollection Groups { + public ListViewGroupCollection Groups + { get { - if (groups == null) { + if (groups == null) + { groups = new ListViewGroupCollection(this); } return groups; @@ -894,7 +1013,8 @@ public ListViewGroupCollection Groups { // and that the user wants to make use of list view groups internal bool GroupsEnabled { - get { + get + { return this.ShowGroups && groups != null && groups.Count > 0 && ComctlSupportsVisualStyles && !VirtualMode; } } @@ -908,22 +1028,26 @@ internal bool GroupsEnabled DefaultValue(ColumnHeaderStyle.Clickable), SRDescription(nameof(SR.ListViewHeaderStyleDescr)) ] - public ColumnHeaderStyle HeaderStyle { - get { return headerStyle;} - set { + public ColumnHeaderStyle HeaderStyle + { + get { return headerStyle; } + set + { //valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)ColumnHeaderStyle.None, (int)ColumnHeaderStyle.Clickable)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ColumnHeaderStyle)); } - if (headerStyle != value) { + if (headerStyle != value) + { // We can switch between NONE and either *one* of the other styles without // recreating the handle, but if we change from CLICKABLE to NONCLICKABLE // or vice versa, with or without an intervening setting of NONE, then // the handle needs to be recreated. headerStyle = value; if ((listViewState[LISTVIEWSTATE_nonclickHdr] && value == ColumnHeaderStyle.Clickable) || - (!listViewState[LISTVIEWSTATE_nonclickHdr] && value == ColumnHeaderStyle.Nonclickable)) { + (!listViewState[LISTVIEWSTATE_nonclickHdr] && value == ColumnHeaderStyle.Nonclickable)) + { listViewState[LISTVIEWSTATE_nonclickHdr] = !listViewState[LISTVIEWSTATE_nonclickHdr]; RecreateHandleInternal(); } @@ -942,13 +1066,17 @@ public ColumnHeaderStyle HeaderStyle { DefaultValue(true), SRDescription(nameof(SR.ListViewHideSelectionDescr)) ] - public bool HideSelection { - get { + public bool HideSelection + { + get + { return listViewState[LISTVIEWSTATE_hideSelection]; } - set { - if (HideSelection != value) { + set + { + if (HideSelection != value) + { listViewState[LISTVIEWSTATE_hideSelection] = value; UpdateStyles(); } @@ -962,15 +1090,20 @@ public bool HideSelection { DefaultValue(false), SRDescription(nameof(SR.ListViewHotTrackingDescr)) ] - public bool HotTracking { - get { + public bool HotTracking + { + get + { return listViewState[LISTVIEWSTATE_hotTracking]; } - set { - if (HotTracking != value) { + set + { + if (HotTracking != value) + { listViewState[LISTVIEWSTATE_hotTracking] = value; - if (value) { + if (value) + { this.HoverSelection = true; this.Activation = ItemActivation.OneClick; } @@ -987,14 +1120,19 @@ public bool HotTracking { DefaultValue(false), SRDescription(nameof(SR.ListViewHoverSelectDescr)) ] - public bool HoverSelection { - get { + public bool HoverSelection + { + get + { return listViewState[LISTVIEWSTATE_hoverSelection]; } - set { - if (HoverSelection != value) { - if (HotTracking && !value) { + set + { + if (HoverSelection != value) + { + if (HotTracking && !value) + { throw new ArgumentException(SR.ListViewHoverMustBeOnWhenHotTrackingIsOn, "value"); } @@ -1017,21 +1155,26 @@ internal bool InsertingItemsNatively DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ListViewInsertionMarkDescr)) ] - public ListViewInsertionMark InsertionMark { + public ListViewInsertionMark InsertionMark + { get { - if(insertionMark == null) { + if (insertionMark == null) + { insertionMark = new ListViewInsertionMark(this); } return insertionMark; } } - private bool ItemCollectionChangedInMouseDown { - get { + private bool ItemCollectionChangedInMouseDown + { + get + { return this.listViewState[LISTVIEWSTATE_itemCollectionChangedInMouseDown]; } - set { + set + { this.listViewState[LISTVIEWSTATE_itemCollectionChangedInMouseDown] = value; } } @@ -1040,12 +1183,14 @@ private bool ItemCollectionChangedInMouseDown { SRCategory(nameof(SR.CatBehavior)), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), Localizable(true), - Editor("System.Windows.Forms.Design.ListViewItemCollectionEditor, " + AssemblyRef.SystemDesign,typeof(UITypeEditor)), + Editor("System.Windows.Forms.Design.ListViewItemCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), SRDescription(nameof(SR.ListViewItemsDescr)), MergableProperty(false) ] - public ListViewItemCollection Items { - get { + public ListViewItemCollection Items + { + get + { return listItemCollection; } } @@ -1058,12 +1203,16 @@ public ListViewItemCollection Items { DefaultValue(false), SRDescription(nameof(SR.ListViewLabelEditDescr)) ] - public bool LabelEdit { - get { + public bool LabelEdit + { + get + { return listViewState[LISTVIEWSTATE_labelEdit]; } - set { - if (LabelEdit != value) { + set + { + if (LabelEdit != value) + { listViewState[LISTVIEWSTATE_labelEdit] = value; UpdateStyles(); } @@ -1079,12 +1228,16 @@ public bool LabelEdit { Localizable(true), SRDescription(nameof(SR.ListViewLabelWrapDescr)) ] - public bool LabelWrap { - get { + public bool LabelWrap + { + get + { return listViewState[LISTVIEWSTATE_labelWrap]; } - set { - if (LabelWrap != value) { + set + { + if (LabelWrap != value) + { listViewState[LISTVIEWSTATE_labelWrap] = value; UpdateStyles(); } @@ -1099,18 +1252,23 @@ public bool LabelWrap { DefaultValue(null), SRDescription(nameof(SR.ListViewLargeImageListDescr)) ] - public ImageList LargeImageList { - get { + public ImageList LargeImageList + { + get + { return imageListLarge; } - set { - if (value != imageListLarge) { + set + { + if (value != imageListLarge) + { EventHandler recreateHandler = new EventHandler(LargeImageListRecreateHandle); EventHandler disposedHandler = new EventHandler(DetachImageList); EventHandler changeHandler = new EventHandler(LargeImageListChangedHandle); - if (imageListLarge != null) { + if (imageListLarge != null) + { imageListLarge.RecreateHandle -= recreateHandler; imageListLarge.Disposed -= disposedHandler; imageListLarge.ChangeHandle -= changeHandler; @@ -1118,15 +1276,18 @@ public ImageList LargeImageList { imageListLarge = value; - if (value != null) { + if (value != null) + { value.RecreateHandle += recreateHandler; value.Disposed += disposedHandler; value.ChangeHandle += changeHandler; } - if (IsHandleCreated) { - SendMessage(NativeMethods.LVM_SETIMAGELIST, (IntPtr)NativeMethods.LVSIL_NORMAL, value == null ? IntPtr.Zero: value.Handle); - if (AutoArrange && !listViewState1[LISTVIEWSTATE1_disposingImageLists]) { + if (IsHandleCreated) + { + SendMessage(NativeMethods.LVM_SETIMAGELIST, (IntPtr)NativeMethods.LVSIL_NORMAL, value == null ? IntPtr.Zero : value.Handle); + if (AutoArrange && !listViewState1[LISTVIEWSTATE1_disposingImageLists]) + { UpdateListViewItemsLocations(); } } @@ -1138,11 +1299,14 @@ public ImageList LargeImageList { /// Returns the current LISTVIEWSTATE_handleDestroyed value so that this /// value can be accessed from child classes. /// - internal bool ListViewHandleDestroyed { - get { + internal bool ListViewHandleDestroyed + { + get + { return listViewState[LISTVIEWSTATE_handleDestroyed]; } - set { + set + { listViewState[LISTVIEWSTATE_handleDestroyed] = value; } } @@ -1156,15 +1320,20 @@ internal bool ListViewHandleDestroyed { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ListViewItemSorterDescr)) ] - public IComparer ListViewItemSorter { - get { + public IComparer ListViewItemSorter + { + get + { return listItemSorter; } - set { - if (listItemSorter != value) { + set + { + if (listItemSorter != value) + { listItemSorter = value; - if (!this.VirtualMode) { + if (!this.VirtualMode) + { Sort(); } } @@ -1179,12 +1348,16 @@ public IComparer ListViewItemSorter { DefaultValue(true), SRDescription(nameof(SR.ListViewMultiSelectDescr)) ] - public bool MultiSelect { - get { + public bool MultiSelect + { + get + { return listViewState[LISTVIEWSTATE_multiSelect]; } - set { - if (MultiSelect != value) { + set + { + if (MultiSelect != value) + { listViewState[LISTVIEWSTATE_multiSelect] = value; UpdateStyles(); } @@ -1200,16 +1373,19 @@ public bool MultiSelect { DefaultValue(false), SRDescription(nameof(SR.ListViewOwnerDrawDescr)) ] - public bool OwnerDraw { - get { + public bool OwnerDraw + { + get + { return listViewState[LISTVIEWSTATE_ownerDraw]; } - set { + set + { if (OwnerDraw != value) { - listViewState[LISTVIEWSTATE_ownerDraw] = value; - Invalidate(true); + listViewState[LISTVIEWSTATE_ownerDraw] = value; + Invalidate(true); } } } @@ -1226,16 +1402,21 @@ public bool OwnerDraw { DefaultValue(false), SRDescription(nameof(SR.ControlRightToLeftLayoutDescr)) ] - public virtual bool RightToLeftLayout { - get { + public virtual bool RightToLeftLayout + { + get + { return rightToLeftLayout; } - set { - if (value != rightToLeftLayout) { + set + { + if (value != rightToLeftLayout) + { rightToLeftLayout = value; - using(new LayoutTransaction(this, this, PropertyNames.RightToLeftLayout)) { + using (new LayoutTransaction(this, this, PropertyNames.RightToLeftLayout)) + { OnRightToLeftLayoutChanged(EventArgs.Empty); } } @@ -1243,7 +1424,8 @@ public virtual bool RightToLeftLayout { } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnRightToLeftLayoutChangedDescr))] - public event EventHandler RightToLeftLayoutChanged { + public event EventHandler RightToLeftLayoutChanged + { add => Events.AddHandler(EVENT_RIGHTTOLEFTLAYOUTCHANGED, value); remove => Events.RemoveHandler(EVENT_RIGHTTOLEFTLAYOUTCHANGED, value); } @@ -1257,12 +1439,16 @@ public event EventHandler RightToLeftLayoutChanged { DefaultValue(true), SRDescription(nameof(SR.ListViewScrollableDescr)) ] - public bool Scrollable { - get { + public bool Scrollable + { + get + { return listViewState[LISTVIEWSTATE_scrollable]; } - set { - if (Scrollable != value) { + set + { + if (Scrollable != value) + { listViewState[LISTVIEWSTATE_scrollable] = value; RecreateHandleInternal(); } @@ -1276,9 +1462,12 @@ public bool Scrollable { Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public SelectedIndexCollection SelectedIndices { - get { - if (selectedIndexCollection == null) { + public SelectedIndexCollection SelectedIndices + { + get + { + if (selectedIndexCollection == null) + { selectedIndexCollection = new SelectedIndexCollection(this); } return selectedIndexCollection; @@ -1294,9 +1483,12 @@ public SelectedIndexCollection SelectedIndices { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ListViewSelectedItemsDescr)) ] - public SelectedListViewItemCollection SelectedItems { - get { - if (selectedListViewItemCollection == null) { + public SelectedListViewItemCollection SelectedItems + { + get + { + if (selectedListViewItemCollection == null) + { selectedListViewItemCollection = new SelectedListViewItemCollection(this); } return selectedListViewItemCollection; @@ -1308,14 +1500,19 @@ public SelectedListViewItemCollection SelectedItems { DefaultValue(true), SRDescription(nameof(SR.ListViewShowGroupsDescr)) ] - public bool ShowGroups { - get { + public bool ShowGroups + { + get + { return this.listViewState[LISTVIEWSTATE_showGroups]; } - set { - if (value != this.ShowGroups) { + set + { + if (value != this.ShowGroups) + { this.listViewState[LISTVIEWSTATE_showGroups] = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { UpdateGroupView(); } } @@ -1330,38 +1527,49 @@ public bool ShowGroups { DefaultValue(null), SRDescription(nameof(SR.ListViewSmallImageListDescr)) ] - public ImageList SmallImageList { - get { + public ImageList SmallImageList + { + get + { return imageListSmall; } - set { - if (imageListSmall != value) { + set + { + if (imageListSmall != value) + { EventHandler recreateHandler = new EventHandler(SmallImageListRecreateHandle); EventHandler disposedHandler = new EventHandler(DetachImageList); - if (imageListSmall != null) { + if (imageListSmall != null) + { imageListSmall.RecreateHandle -= recreateHandler; imageListSmall.Disposed -= disposedHandler; } imageListSmall = value; - if (value != null) { + if (value != null) + { value.RecreateHandle += recreateHandler; value.Disposed += disposedHandler; } - if (IsHandleCreated) { + if (IsHandleCreated) + { - SendMessage(NativeMethods.LVM_SETIMAGELIST, (IntPtr)NativeMethods.LVSIL_SMALL, value == null ? IntPtr.Zero: value.Handle); + SendMessage(NativeMethods.LVM_SETIMAGELIST, (IntPtr)NativeMethods.LVSIL_SMALL, value == null ? IntPtr.Zero : value.Handle); - if (this.View == View.SmallIcon) { + if (this.View == View.SmallIcon) + { this.View = View.LargeIcon; this.View = View.SmallIcon; - } else if (!listViewState1[LISTVIEWSTATE1_disposingImageLists]) { + } + else if (!listViewState1[LISTVIEWSTATE1_disposingImageLists]) + { UpdateListViewItemsLocations(); } - if (this.View == View.Details) { + if (this.View == View.Details) + { this.Invalidate(true /*invalidateChildren*/); } } @@ -1374,12 +1582,16 @@ public ImageList SmallImageList { DefaultValue(false), SRDescription(nameof(SR.ListViewShowItemToolTipsDescr)) ] - public bool ShowItemToolTips { - get { + public bool ShowItemToolTips + { + get + { return listViewState[LISTVIEWSTATE_showItemToolTips]; } - set { - if (ShowItemToolTips != value) { + set + { + if (ShowItemToolTips != value) + { listViewState[LISTVIEWSTATE_showItemToolTips] = value; RecreateHandleInternal(); } @@ -1391,27 +1603,36 @@ public bool ShowItemToolTips { DefaultValue(SortOrder.None), SRDescription(nameof(SR.ListViewSortingDescr)) ] - public SortOrder Sorting { - get { + public SortOrder Sorting + { + get + { return sorting; } - set { + set + { //valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)SortOrder.None, (int)SortOrder.Descending)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(SortOrder)); } - if (sorting != value) { + if (sorting != value) + { sorting = value; - if (this.View == View.LargeIcon || this.View == View.SmallIcon) { - if (listItemSorter == null) { + if (this.View == View.LargeIcon || this.View == View.SmallIcon) + { + if (listItemSorter == null) + { listItemSorter = new IconComparer(sorting); } - else if (listItemSorter is IconComparer) { - ((IconComparer)listItemSorter).SortOrder = sorting; + else if (listItemSorter is IconComparer) + { + ((IconComparer)listItemSorter).SortOrder = sorting; } - } else if (value == SortOrder.None) { + } + else if (value == SortOrder.None) + { listItemSorter = null; } @@ -1430,42 +1651,54 @@ public SortOrder Sorting { DefaultValue(null), SRDescription(nameof(SR.ListViewStateImageListDescr)) ] - public ImageList StateImageList { - get { + public ImageList StateImageList + { + get + { return imageListState; } - set { - if (this.UseCompatibleStateImageBehavior) { - if (imageListState != value) { - + set + { + if (this.UseCompatibleStateImageBehavior) + { + if (imageListState != value) + { + EventHandler recreateHandler = new EventHandler(StateImageListRecreateHandle); EventHandler disposedHandler = new EventHandler(DetachImageList); - if (imageListState != null) { + if (imageListState != null) + { imageListState.RecreateHandle -= recreateHandler; imageListState.Disposed -= disposedHandler; } imageListState = value; - if (value != null) { + if (value != null) + { value.RecreateHandle += recreateHandler; value.Disposed += disposedHandler; } - + if (IsHandleCreated) - SendMessage(NativeMethods.LVM_SETIMAGELIST, NativeMethods.LVSIL_STATE, value == null ? IntPtr.Zero: value.Handle); + SendMessage(NativeMethods.LVM_SETIMAGELIST, NativeMethods.LVSIL_STATE, value == null ? IntPtr.Zero : value.Handle); } - } else { - if (imageListState != value) { + } + else + { + if (imageListState != value) + { EventHandler recreateHandler = new EventHandler(StateImageListRecreateHandle); EventHandler disposedHandler = new EventHandler(DetachImageList); - if (imageListState != null) { + if (imageListState != null) + { imageListState.RecreateHandle -= recreateHandler; imageListState.Disposed -= disposedHandler; } - if (this.IsHandleCreated && imageListState != null && this.CheckBoxes) { + if (this.IsHandleCreated && imageListState != null && this.CheckBoxes) + { // // If CheckBoxes are set to true, then we will have to recreate the handle. // For some reason, if CheckBoxes are set to true and the list view has a state imageList, then the native listView destroys @@ -1477,21 +1710,27 @@ public ImageList StateImageList { imageListState = value; - if (value != null) { + if (value != null) + { value.RecreateHandle += recreateHandler; value.Disposed += disposedHandler; } - if (IsHandleCreated) { - if (CheckBoxes) { + if (IsHandleCreated) + { + if (CheckBoxes) + { // need to recreate to get the new images pushed in. RecreateHandleInternal(); - } else { + } + else + { SendMessage(NativeMethods.LVM_SETIMAGELIST, NativeMethods.LVSIL_STATE, (imageListState == null || imageListState.Images.Count == 0) ? IntPtr.Zero : imageListState.Handle); } // Comctl should handle auto-arrange for us, but doesn't - if (!listViewState1[LISTVIEWSTATE1_disposingImageLists]) { + if (!listViewState1[LISTVIEWSTATE1_disposingImageLists]) + { UpdateListViewItemsLocations(); } } @@ -1501,17 +1740,21 @@ public ImageList StateImageList { } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Bindable(false)] - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TextChanged { + new public event EventHandler TextChanged + { add => base.TextChanged += value; remove => base.TextChanged -= value; } @@ -1521,38 +1764,51 @@ public override string Text { Browsable(true), SRDescription(nameof(SR.ListViewTileSizeDescr)), ] - public Size TileSize { - get { - if (tileSize.IsEmpty) { - if (this.IsHandleCreated) { + public Size TileSize + { + get + { + if (tileSize.IsEmpty) + { + if (this.IsHandleCreated) + { // Get the default value from the ListView // NativeMethods.LVTILEVIEWINFO tileViewInfo = new NativeMethods.LVTILEVIEWINFO(); tileViewInfo.dwMask = NativeMethods.LVTVIM_TILESIZE; UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_GETTILEVIEWINFO, 0, tileViewInfo); return new Size(tileViewInfo.sizeTile.cx, tileViewInfo.sizeTile.cy); - } else { + } + else + { return Size.Empty; } - } else { + } + else + { return tileSize; } } - set { - if (tileSize != value) { - if (value.IsEmpty || value.Height <= 0 || value.Width <= 0) { + set + { + if (tileSize != value) + { + if (value.IsEmpty || value.Height <= 0 || value.Width <= 0) + { throw new ArgumentOutOfRangeException(nameof(TileSize), SR.ListViewTileSizeMustBePositive); } tileSize = value; - if (this.IsHandleCreated) { + if (this.IsHandleCreated) + { NativeMethods.LVTILEVIEWINFO tileViewInfo = new NativeMethods.LVTILEVIEWINFO(); tileViewInfo.dwMask = NativeMethods.LVTVIM_TILESIZE; tileViewInfo.dwFlags = NativeMethods.LVTVIF_FIXEDSIZE; tileViewInfo.sizeTile = new NativeMethods.SIZE(tileSize.Width, tileSize.Height); bool retval = UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_SETTILEVIEWINFO, 0, tileViewInfo); Debug.Assert(retval, "LVM_SETTILEVIEWINFO failed"); - if (this.AutoArrange) { + if (this.AutoArrange) + { this.UpdateListViewItemsLocations(); } } @@ -1560,7 +1816,8 @@ public Size TileSize { } } - private bool ShouldSerializeTileSize() { + private bool ShouldSerializeTileSize() + { return !this.tileSize.Equals(Size.Empty); } @@ -1570,26 +1827,32 @@ private bool ShouldSerializeTileSize() { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ListViewTopItemDescr)) ] - public ListViewItem TopItem { - get { + public ListViewItem TopItem + { + get + { if (viewStyle == View.LargeIcon || viewStyle == View.SmallIcon || viewStyle == View.Tile) throw new InvalidOperationException(SR.ListViewGetTopItem); - if (!IsHandleCreated) { - if (Items.Count > 0) { + if (!IsHandleCreated) + { + if (Items.Count > 0) + { return Items[0]; } - else { + else + { return null; } } - topIndex = unchecked( (int) (long)SendMessage(NativeMethods.LVM_GETTOPINDEX, 0, 0)); + topIndex = unchecked((int)(long)SendMessage(NativeMethods.LVM_GETTOPINDEX, 0, 0)); if (topIndex >= 0 && topIndex < Items.Count) return Items[topIndex]; return null; } - set { + set + { if (viewStyle == View.LargeIcon || viewStyle == View.SmallIcon || viewStyle == View.Tile) throw new InvalidOperationException(SR.ListViewSetTopItem); @@ -1597,7 +1860,8 @@ public ListViewItem TopItem { return; if (value.ListView != this) return; - if (!IsHandleCreated) { + if (!IsHandleCreated) + { CreateHandle(); } if (value == TopItem) @@ -1628,8 +1892,10 @@ public ListViewItem TopItem { EditorBrowsable(EditorBrowsableState.Advanced), DefaultValue(true) ] - public bool UseCompatibleStateImageBehavior { - get { + public bool UseCompatibleStateImageBehavior + { + get + { return this.listViewState1[LISTVIEWSTATE1_useCompatibleStateImageBehavior]; } set @@ -1643,12 +1909,16 @@ public bool UseCompatibleStateImageBehavior { DefaultValue(View.LargeIcon), SRDescription(nameof(SR.ListViewViewDescr)) ] - public View View { - get { + public View View + { + get + { return viewStyle; } - set { - if (value == View.Tile && this.CheckBoxes) { + set + { + if (value == View.Tile && this.CheckBoxes) + { throw new NotSupportedException(SR.ListViewTileViewDoesNotSupportCheckBoxes); } @@ -1660,22 +1930,27 @@ public View View { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(View)); } - if (value == View.Tile && VirtualMode) { + if (value == View.Tile && VirtualMode) + { throw new NotSupportedException(SR.ListViewCantSetViewToTileViewInVirtualMode); } - if (viewStyle != value) { + if (viewStyle != value) + { viewStyle = value; - if (IsHandleCreated && ComctlSupportsVisualStyles) { - SendMessage(NativeMethods.LVM_SETVIEW,(int)viewStyle,0); + if (IsHandleCreated && ComctlSupportsVisualStyles) + { + SendMessage(NativeMethods.LVM_SETVIEW, (int)viewStyle, 0); UpdateGroupView(); // if we switched to Tile view we should update the win32 list view tile view info - if (viewStyle == View.Tile) { + if (viewStyle == View.Tile) + { UpdateTileView(); } } - else { + else + { UpdateStyles(); } @@ -1690,19 +1965,23 @@ public View View { RefreshProperties(RefreshProperties.Repaint), SRDescription(nameof(SR.ListViewVirtualListSizeDescr)) ] - public int VirtualListSize { - get { + public int VirtualListSize + { + get + { return this.virtualListSize; } - set { + set + { if (value < 0) throw new System.ArgumentException(string.Format(SR.ListViewVirtualListSizeInvalidArgument, "value", (value))); if (value == virtualListSize) return; bool keepTopItem = this.IsHandleCreated && VirtualMode && this.View == View.Details && !this.DesignMode; int topIndex = -1; - if (keepTopItem) { - topIndex = unchecked( (int) (long)SendMessage(NativeMethods.LVM_GETTOPINDEX, 0, 0)); + if (keepTopItem) + { + topIndex = unchecked((int)(long)SendMessage(NativeMethods.LVM_GETTOPINDEX, 0, 0)); } virtualListSize = value; @@ -1710,11 +1989,13 @@ public int VirtualListSize { if (IsHandleCreated && VirtualMode && !DesignMode) SendMessage(NativeMethods.LVM_SETITEMCOUNT, virtualListSize, 0); - if (keepTopItem) { + if (keepTopItem) + { topIndex = Math.Min(topIndex, this.VirtualListSize - 1); // After setting the virtual list size ComCtl makes the first item the top item. // So we set the top item only if it wasn't the first item to begin with. - if (topIndex > 0) { + if (topIndex > 0) + { ListViewItem lvItem = this.Items[topIndex]; this.TopItem = lvItem; } @@ -1728,27 +2009,33 @@ public int VirtualListSize { RefreshProperties(RefreshProperties.Repaint), SRDescription(nameof(SR.ListViewVirtualModeDescr)) ] - public bool VirtualMode { - get { + public bool VirtualMode + { + get + { return listViewState[LISTVIEWSTATE_virtualMode]; } - set { + set + { if (value == VirtualMode) return; if (value && Items.Count > 0) throw new InvalidOperationException(SR.ListViewVirtualListViewRequiresNoItems); - if (value && CheckedItems.Count > 0) { + if (value && CheckedItems.Count > 0) + { throw new InvalidOperationException(SR.ListViewVirtualListViewRequiresNoCheckedItems); } - if (value && SelectedItems.Count > 0) { + if (value && SelectedItems.Count > 0) + { throw new InvalidOperationException(SR.ListViewVirtualListViewRequiresNoSelectedItems); } // Tile view does not work w/ VirtualMode. - if (value && View == View.Tile) { + if (value && View == View.Tile) + { throw new NotSupportedException(SR.ListViewCantSetVirtualModeWhenInTileView); } @@ -1760,25 +2047,29 @@ public bool VirtualMode { [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ListViewAfterLabelEditDescr))] - public event LabelEditEventHandler AfterLabelEdit { + public event LabelEditEventHandler AfterLabelEdit + { add => onAfterLabelEdit += value; remove => onAfterLabelEdit -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ListViewBeforeLabelEditDescr))] - public event LabelEditEventHandler BeforeLabelEdit { + public event LabelEditEventHandler BeforeLabelEdit + { add => onBeforeLabelEdit += value; remove => onBeforeLabelEdit -= value; } [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ListViewCacheVirtualItemsEventDescr))] - public event CacheVirtualItemsEventHandler CacheVirtualItems { + public event CacheVirtualItemsEventHandler CacheVirtualItems + { add => Events.AddHandler(EVENT_CACHEVIRTUALITEMS, value); remove => Events.RemoveHandler(EVENT_CACHEVIRTUALITEMS, value); } [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ListViewColumnClickDescr))] - public event ColumnClickEventHandler ColumnClick { + public event ColumnClickEventHandler ColumnClick + { add => onColumnClick += value; remove => onColumnClick -= value; } @@ -1787,7 +2078,8 @@ public event ColumnClickEventHandler ColumnClick { /// Tell the user that the column headers are being rearranged /// [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ListViewColumnReorderedDscr))] - public event ColumnReorderedEventHandler ColumnReordered { + public event ColumnReorderedEventHandler ColumnReordered + { add => Events.AddHandler(EVENT_COLUMNREORDERED, value); remove => Events.RemoveHandler(EVENT_COLUMNREORDERED, value); } @@ -1796,7 +2088,8 @@ public event ColumnReorderedEventHandler ColumnReordered { /// Tell the user that the column width changed /// [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ListViewColumnWidthChangedDscr))] - public event ColumnWidthChangedEventHandler ColumnWidthChanged { + public event ColumnWidthChangedEventHandler ColumnWidthChanged + { add => Events.AddHandler(EVENT_COLUMNWIDTHCHANGED, value); remove => Events.RemoveHandler(EVENT_COLUMNWIDTHCHANGED, value); } @@ -1805,7 +2098,8 @@ public event ColumnWidthChangedEventHandler ColumnWidthChanged { /// Tell the user that the column width is being changed /// [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ListViewColumnWidthChangingDscr))] - public event ColumnWidthChangingEventHandler ColumnWidthChanging { + public event ColumnWidthChangingEventHandler ColumnWidthChanging + { add => Events.AddHandler(EVENT_COLUMNWIDTHCHANGING, value); remove => Events.RemoveHandler(EVENT_COLUMNWIDTHCHANGING, value); } @@ -1814,7 +2108,8 @@ public event ColumnWidthChangingEventHandler ColumnWidthChanging { /// Fires in owner draw + Details mode when a column header needs to be drawn. /// [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ListViewDrawColumnHeaderEventDescr))] - public event DrawListViewColumnHeaderEventHandler DrawColumnHeader { + public event DrawListViewColumnHeaderEventHandler DrawColumnHeader + { add => Events.AddHandler(EVENT_DRAWCOLUMNHEADER, value); remove => Events.RemoveHandler(EVENT_DRAWCOLUMNHEADER, value); } @@ -1823,7 +2118,8 @@ public event DrawListViewColumnHeaderEventHandler DrawColumnHeader { /// Fires in owner draw mode when a ListView item needs to be drawn. /// [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ListViewDrawItemEventDescr))] - public event DrawListViewItemEventHandler DrawItem { + public event DrawListViewItemEventHandler DrawItem + { add => Events.AddHandler(EVENT_DRAWITEM, value); remove => Events.RemoveHandler(EVENT_DRAWITEM, value); } @@ -1832,43 +2128,50 @@ public event DrawListViewItemEventHandler DrawItem { /// Fires in owner draw mode and Details view when a ListView sub-item needs to be drawn. /// [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ListViewDrawSubItemEventDescr))] - public event DrawListViewSubItemEventHandler DrawSubItem { + public event DrawListViewSubItemEventHandler DrawSubItem + { add => Events.AddHandler(EVENT_DRAWSUBITEM, value); remove => Events.RemoveHandler(EVENT_DRAWSUBITEM, value); } [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ListViewItemClickDescr))] - public event EventHandler ItemActivate { + public event EventHandler ItemActivate + { add => onItemActivate += value; remove => onItemActivate -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.CheckedListBoxItemCheckDescr))] - public event ItemCheckEventHandler ItemCheck { + public event ItemCheckEventHandler ItemCheck + { add => onItemCheck += value; remove => onItemCheck -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ListViewItemCheckedDescr))] - public event ItemCheckedEventHandler ItemChecked { + public event ItemCheckedEventHandler ItemChecked + { add => onItemChecked += value; remove => onItemChecked -= value; } [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ListViewItemDragDescr))] - public event ItemDragEventHandler ItemDrag { + public event ItemDragEventHandler ItemDrag + { add => onItemDrag += value; remove => onItemDrag -= value; } [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ListViewItemMouseHoverDescr))] - public event ListViewItemMouseHoverEventHandler ItemMouseHover { + public event ListViewItemMouseHoverEventHandler ItemMouseHover + { add => onItemMouseHover += value; remove => onItemMouseHover -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ListViewItemSelectionChangedDescr))] - public event ListViewItemSelectionChangedEventHandler ItemSelectionChanged { + public event ListViewItemSelectionChangedEventHandler ItemSelectionChanged + { add => Events.AddHandler(EVENT_ITEMSELECTIONCHANGED, value); remove => Events.RemoveHandler(EVENT_ITEMSELECTIONCHANGED, value); } @@ -1878,30 +2181,35 @@ public event ListViewItemSelectionChangedEventHandler ItemSelectionChanged { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Padding Padding { + public new Padding Padding + { get { return base.Padding; } - set { base.Padding = value;} + set { base.Padding = value; } } [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public new event EventHandler PaddingChanged { - add => base.PaddingChanged += value; - remove => base.PaddingChanged -= value; } + public new event EventHandler PaddingChanged + { + add => base.PaddingChanged += value; + remove => base.PaddingChanged -= value; + } /// /// ListView Onpaint. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event PaintEventHandler Paint { + public new event PaintEventHandler Paint + { add => base.Paint += value; remove => base.Paint -= value; } [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ListViewRetrieveVirtualItemEventDescr))] - public event RetrieveVirtualItemEventHandler RetrieveVirtualItem { + public event RetrieveVirtualItemEventHandler RetrieveVirtualItem + { add => Events.AddHandler(EVENT_RETRIEVEVIRTUALITEM, value); remove => Events.RemoveHandler(EVENT_RETRIEVEVIRTUALITEM, value); } @@ -1909,19 +2217,22 @@ public event RetrieveVirtualItemEventHandler RetrieveVirtualItem { /// /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ListViewSearchForVirtualItemDescr))] - public event SearchForVirtualItemEventHandler SearchForVirtualItem { + public event SearchForVirtualItemEventHandler SearchForVirtualItem + { add => Events.AddHandler(EVENT_SEARCHFORVIRTUALITEM, value); remove => Events.RemoveHandler(EVENT_SEARCHFORVIRTUALITEM, value); } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ListViewSelectedIndexChangedDescr))] - public event EventHandler SelectedIndexChanged { + public event EventHandler SelectedIndexChanged + { add => Events.AddHandler(EVENT_SELECTEDINDEXCHANGED, value); remove => Events.RemoveHandler(EVENT_SELECTEDINDEXCHANGED, value); } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ListViewVirtualItemsSelectionRangeChangedDescr))] - public event ListViewVirtualItemsSelectionRangeChangedEventHandler VirtualItemsSelectionRangeChanged { + public event ListViewVirtualItemsSelectionRangeChangedEventHandler VirtualItemsSelectionRangeChanged + { add => Events.AddHandler(EVENT_VIRTUALITEMSSELECTIONRANGECHANGED, value); remove => Events.RemoveHandler(EVENT_VIRTUALITEMSSELECTIONRANGECHANGED, value); } @@ -1934,16 +2245,19 @@ public event ListViewVirtualItemsSelectionRangeChangedEventHandler VirtualItemsS /// cached up items first, then do the requested operation. This keeps it simple so we don't have to /// try to maintain parellel state of the cache during a begin update end update. /// - private void ApplyUpdateCachedItems() { + private void ApplyUpdateCachedItems() + { // first check if there is a delayed update array // ArrayList newItems = (ArrayList)Properties.GetObject(PropDelayedUpdateItems); - if (newItems != null) { + if (newItems != null) + { // if there is, clear it and push the items in. // Properties.SetObject(PropDelayedUpdateItems, null); ListViewItem[] items = (ListViewItem[])newItems.ToArray(typeof(ListViewItem)); - if (items.Length > 0) { + if (items.Length > 0) + { InsertItems(itemCount, items, false /*checkHosting*/); } } @@ -1953,17 +2267,21 @@ private void ApplyUpdateCachedItems() { /// In Large Icon or Small Icon view, arranges the items according to one /// of the following behaviors: /// - public void ArrangeIcons(ListViewAlignment value) { + public void ArrangeIcons(ListViewAlignment value) + { // LVM_ARRANGE only work in SmallIcon view - if (viewStyle != View.SmallIcon) return; + if (viewStyle != View.SmallIcon) + return; - switch ((int)value) { + switch ((int)value) + { case NativeMethods.LVA_DEFAULT: case NativeMethods.LVA_ALIGNLEFT: case NativeMethods.LVA_ALIGNTOP: case NativeMethods.LVA_SNAPTOGRID: - if (IsHandleCreated) { - UnsafeNativeMethods.PostMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_ARRANGE, (int) value, 0); + if (IsHandleCreated) + { + UnsafeNativeMethods.PostMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_ARRANGE, (int)value, 0); } break; @@ -1971,7 +2289,8 @@ public void ArrangeIcons(ListViewAlignment value) { throw new ArgumentException(string.Format(SR.InvalidArgument, nameof(value), value), nameof(value)); } - if (!VirtualMode && sorting != SortOrder.None) { + if (!VirtualMode && sorting != SortOrder.None) + { Sort(); } @@ -1981,19 +2300,24 @@ public void ArrangeIcons(ListViewAlignment value) { /// In Large Icon or Small Icon view, arranges items according to the ListView's /// current alignment style. /// - public void ArrangeIcons() { + public void ArrangeIcons() + { ArrangeIcons((ListViewAlignment)NativeMethods.LVA_DEFAULT); } - public void AutoResizeColumns(ColumnHeaderAutoResizeStyle headerAutoResize) { - if (!this.IsHandleCreated) { + public void AutoResizeColumns(ColumnHeaderAutoResizeStyle headerAutoResize) + { + if (!this.IsHandleCreated) + { this.CreateHandle(); } UpdateColumnWidths(headerAutoResize); } - public void AutoResizeColumn(int columnIndex, ColumnHeaderAutoResizeStyle headerAutoResize) { - if (!this.IsHandleCreated) { + public void AutoResizeColumn(int columnIndex, ColumnHeaderAutoResizeStyle headerAutoResize) + { + if (!this.IsHandleCreated) + { this.CreateHandle(); } SetColumnWidth(columnIndex, headerAutoResize); @@ -2005,39 +2329,50 @@ public void AutoResizeColumn(int columnIndex, ColumnHeaderAutoResizeStyle header /// will improve performance and reduce flicker on the ListView as items are /// being updated. Always call EndUpdate immediately after the last item is updated. /// - public void BeginUpdate() { + public void BeginUpdate() + { BeginUpdateInternal(); // if this is the first BeginUpdate call, push an ArrayList into the PropertyStore so // we can cache up any items that have been added while this is active. // - if (updateCounter++ == 0 && null == Properties.GetObject(PropDelayedUpdateItems)) { + if (updateCounter++ == 0 && null == Properties.GetObject(PropDelayedUpdateItems)) + { Properties.SetObject(PropDelayedUpdateItems, new ArrayList()); } } - internal void CacheSelectedStateForItem(ListViewItem lvi, bool selected) { - if (selected) { - if (this.savedSelectedItems == null) { + internal void CacheSelectedStateForItem(ListViewItem lvi, bool selected) + { + if (selected) + { + if (this.savedSelectedItems == null) + { this.savedSelectedItems = new List(); } - if (!this.savedSelectedItems.Contains(lvi)) { + if (!this.savedSelectedItems.Contains(lvi)) + { this.savedSelectedItems.Add(lvi); } - } else { - if (this.savedSelectedItems != null && this.savedSelectedItems.Contains(lvi)) { + } + else + { + if (this.savedSelectedItems != null && this.savedSelectedItems.Contains(lvi)) + { this.savedSelectedItems.Remove(lvi); } } } #if DEBUG - private void CheckDisplayIndices() { + private void CheckDisplayIndices() + { // sanity check // all the column headers should have a displayIndex between 0 and this.Columns.Count - 1; // DisplayIndex should be different for different column headers int sumOfDisplayIndices = 0; - for (int i = 0; i < this.Columns.Count; i ++) { + for (int i = 0; i < this.Columns.Count; i++) + { sumOfDisplayIndices += this.Columns[i].DisplayIndex; Debug.Assert(this.Columns[i].DisplayIndex > -1 && this.Columns[i].DisplayIndex < this.Columns.Count, "display indices out of whack"); } @@ -2046,23 +2381,29 @@ private void CheckDisplayIndices() { } #endif - private void CleanPreviousBackgroundImageFiles() { - if (this.bkImgFileNames == null) { + private void CleanPreviousBackgroundImageFiles() + { + if (this.bkImgFileNames == null) + { return; } System.IO.FileInfo fi; - for (int i = 0; i <= this.bkImgFileNamesCount; i ++) { + for (int i = 0; i <= this.bkImgFileNamesCount; i++) + { fi = new System.IO.FileInfo(this.bkImgFileNames[i]); - if (fi.Exists) { + if (fi.Exists) + { // // ComCtl ListView uses COM objects to manipulate the bitmap we send it to them. // I could not find any resources which explain in detail when the IImgCtx objects // release the temporary file. So if we get a FileIO when we delete the temporary file // we don't do anything about it ( because we don't know what is a good time to try to delete the file again ). - try { + try + { fi.Delete(); - } catch (System.IO.IOException){} + } + catch (System.IO.IOException) { } } } @@ -2073,7 +2414,8 @@ private void CleanPreviousBackgroundImageFiles() { /// /// Removes all items and columns from the ListView. /// - public void Clear() { + public void Clear() + { Items.Clear(); Columns.Clear(); } @@ -2081,31 +2423,39 @@ public void Clear() { /// /// This is the sorting callback function called by the system ListView control. /// - private int CompareFunc(IntPtr lparam1, IntPtr lparam2, IntPtr lparamSort) { + private int CompareFunc(IntPtr lparam1, IntPtr lparam2, IntPtr lparamSort) + { Debug.Assert(listItemSorter != null, "null sorter!"); - if (listItemSorter != null) { + if (listItemSorter != null) + { return listItemSorter.Compare(listItemsTable[(int)lparam1], listItemsTable[(int)lparam2]); } - else { + else + { return 0; } } - private int CompensateColumnHeaderResize(Message m, bool columnResizeCancelled) { + private int CompensateColumnHeaderResize(Message m, bool columnResizeCancelled) + { if (this.ComctlSupportsVisualStyles && this.View == View.Details && !columnResizeCancelled && - this.Items.Count > 0) { - NativeMethods.NMHEADER header = (NativeMethods.NMHEADER) m.GetLParam(typeof(NativeMethods.NMHEADER)); + this.Items.Count > 0) + { + NativeMethods.NMHEADER header = (NativeMethods.NMHEADER)m.GetLParam(typeof(NativeMethods.NMHEADER)); return CompensateColumnHeaderResize(header.iItem, columnResizeCancelled); - } else { + } + else + { return 0; } } - private int CompensateColumnHeaderResize(int columnIndex, bool columnResizeCancelled) { + private int CompensateColumnHeaderResize(int columnIndex, bool columnResizeCancelled) + { // We need to compensate padding only when ComCtl60 is loaded. // We need to compensate padding only if the list view is in Details mode. // We need to compensate padding only if the user did not cancel ColumnWidthChanging event. @@ -2119,25 +2469,34 @@ private int CompensateColumnHeaderResize(int columnIndex, bool columnResizeCance if (this.ComctlSupportsVisualStyles && this.View == View.Details && !columnResizeCancelled && - this.Items.Count > 0) { + this.Items.Count > 0) + { // The user resized the first column. - if (columnIndex == 0) { + if (columnIndex == 0) + { ColumnHeader col = (this.columnHeaders != null && this.columnHeaders.Length > 0) ? this.columnHeaders[0] : null; - if (col != null) { - if (this.SmallImageList == null) { + if (col != null) + { + if (this.SmallImageList == null) + { return 2; - } else { + } + else + { // If the list view contains an item w/ a non-negative ImageIndex then we don't need to // add extra padding. bool addPadding = true; - for (int i = 0; i < this.Items.Count; i ++) { - if (this.Items[i].ImageIndexer.ActualIndex > -1) { + for (int i = 0; i < this.Items.Count; i++) + { + if (this.Items[i].ImageIndexer.ActualIndex > -1) + { addPadding = false; break; } } - if (addPadding) { + if (addPadding) + { // 18 = 16 + 2. // 16 = size of small image list. // 2 is the padding we add when there is no small image list. @@ -2153,16 +2512,20 @@ private int CompensateColumnHeaderResize(int columnIndex, bool columnResizeCance /// /// - protected override void CreateHandle() { - if (!RecreatingHandle) { + protected override void CreateHandle() + { + if (!RecreatingHandle) + { IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); - - try { + + try + { NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); icc.dwICC = NativeMethods.ICC_LISTVIEW_CLASSES; SafeNativeMethods.InitCommonControlsEx(icc); } - finally { + finally + { UnsafeNativeMethods.ThemingScope.Deactivate(userCookie); } } @@ -2183,7 +2546,8 @@ protected override void CreateHandle() { /// If OwnerDraw is true, we fire the OnDrawItem and OnDrawSubItem (in Details view) /// events and let the user do the drawing. /// - unsafe void CustomDraw(ref Message m) { + unsafe void CustomDraw(ref Message m) + { bool dontmess = false; bool itemDrawDefault = false; @@ -2577,25 +2941,32 @@ unsafe void CustomDraw(ref Message m) { } } - private void DeleteFileName(string fileName) { - if (!string.IsNullOrEmpty(fileName)) { - + private void DeleteFileName(string fileName) + { + if (!string.IsNullOrEmpty(fileName)) + { + System.IO.FileInfo fi = new System.IO.FileInfo(fileName); - if (fi.Exists) { + if (fi.Exists) + { // // ComCtl ListView uses COM objects to manipulate the bitmap we send it to them. // I could not find any resources which explain in detail when the IImgCtx objects // release the temporary file. So if we get a FileIO when we delete the temporary file // we don't do anything about it ( because we don't know what is a good time to try to delete the file again ). - try { + try + { fi.Delete(); - } catch (System.IO.IOException){} + } + catch (System.IO.IOException) { } } } } - private void DestroyLVGROUP(NativeMethods.LVGROUP lvgroup) { - if(lvgroup.pszHeader != IntPtr.Zero) { + private void DestroyLVGROUP(NativeMethods.LVGROUP lvgroup) + { + if (lvgroup.pszHeader != IntPtr.Zero) + { Marshal.FreeHGlobal(lvgroup.pszHeader); } } @@ -2604,15 +2975,17 @@ private void DestroyLVGROUP(NativeMethods.LVGROUP lvgroup) { /// Resets the imageList to null. We wire this method up to the imageList's /// Dispose event, so that we don't hang onto an imageList that's gone away. /// - private void DetachImageList(object sender, EventArgs e) { + private void DetachImageList(object sender, EventArgs e) + { listViewState1[LISTVIEWSTATE1_disposingImageLists] = true; - try { - #if DEBUG + try + { +#if DEBUG if (sender != imageListSmall && sender != imageListState && sender != imageListLarge) { Debug.Fail("ListView sunk dispose event from unknown component"); } - #endif // DEBUG +#endif // DEBUG if (sender == imageListSmall) SmallImageList = null; if (sender == imageListLarge) @@ -2620,13 +2993,14 @@ private void DetachImageList(object sender, EventArgs e) { if (sender == imageListState) StateImageList = null; } - finally { + finally + { listViewState1[LISTVIEWSTATE1_disposingImageLists] = false; } UpdateListViewItemsLocations(); - + } /// @@ -2634,25 +3008,32 @@ private void DetachImageList(object sender, EventArgs e) { /// This method removes the component from its container (if the component has a site) /// and triggers the dispose event. /// - protected override void Dispose(bool disposing) { - if (disposing) { + protected override void Dispose(bool disposing) + { + if (disposing) + { // Remove any event sinks we have hooked up to imageLists - if (imageListSmall != null) { + if (imageListSmall != null) + { imageListSmall.Disposed -= new EventHandler(this.DetachImageList); imageListSmall = null; } - if (imageListLarge != null) { + if (imageListLarge != null) + { imageListLarge.Disposed -= new EventHandler(this.DetachImageList); imageListLarge = null; } - if (imageListState != null) { + if (imageListState != null) + { imageListState.Disposed -= new EventHandler(this.DetachImageList); imageListState = null; } // Remove any ColumnHeaders contained in this control - if (columnHeaders != null) { - for (int colIdx = columnHeaders.Length-1; colIdx >= 0; colIdx--) { + if (columnHeaders != null) + { + for (int colIdx = columnHeaders.Length - 1; colIdx >= 0; colIdx--) + { columnHeaders[colIdx].OwnerListview = null; columnHeaders[colIdx].Dispose(); } @@ -2668,10 +3049,12 @@ protected override void Dispose(bool disposing) { odCacheFontHandleWrapper = null; } - if (!string.IsNullOrEmpty(this.backgroundImageFileName) || this.bkImgFileNames != null) { + if (!string.IsNullOrEmpty(this.backgroundImageFileName) || this.bkImgFileNames != null) + { System.IO.FileInfo fi; - if (!string.IsNullOrEmpty(this.backgroundImageFileName)) { + if (!string.IsNullOrEmpty(this.backgroundImageFileName)) + { fi = new System.IO.FileInfo(this.backgroundImageFileName); Debug.Assert(fi.Exists, "who deleted our temp file?"); // @@ -2679,12 +3062,15 @@ protected override void Dispose(bool disposing) { // I could not find any resources which explain in detail when the IImgCtx objects // release the temporary file. So if we get a FileIO when we delete the temporary file // we don't do anything about it ( because we don't know what is a good time to try to delete the file again ). - try { + try + { fi.Delete(); - } catch (System.IO.IOException){} + } + catch (System.IO.IOException) { } this.backgroundImageFileName = string.Empty; } - for (int i = 0; i <= this.bkImgFileNamesCount; i++) { + for (int i = 0; i <= this.bkImgFileNamesCount; i++) + { fi = new System.IO.FileInfo(this.bkImgFileNames[i]); Debug.Assert(fi.Exists, "who deleted our temp file?"); // @@ -2692,9 +3078,11 @@ protected override void Dispose(bool disposing) { // I could not find any resources which explain in detail when the IImgCtx objects // release the temporary file. So if we get a FileIO when we delete the temporary file // we don't do anything about it ( because we don't know what is a good time to try to delete the file again ). - try { + try + { fi.Delete(); - } catch (System.IO.IOException){} + } + catch (System.IO.IOException) { } } this.bkImgFileNames = null; @@ -2709,20 +3097,25 @@ protected override void Dispose(bool disposing) { /// /// Cancels the effect of BeginUpdate. /// - public void EndUpdate() { + public void EndUpdate() + { // On the final EndUpdate, check to see if we've got any cached items. // If we do, insert them as normal, then turn off the painting freeze. // - if (--updateCounter == 0 && null != Properties.GetObject(PropDelayedUpdateItems)) { + if (--updateCounter == 0 && null != Properties.GetObject(PropDelayedUpdateItems)) + { ApplyUpdateCachedItems(); } EndUpdateInternal(); } - private void EnsureDefaultGroup() { - if (IsHandleCreated && ComctlSupportsVisualStyles && GroupsEnabled) { - if (SendMessage(NativeMethods.LVM_HASGROUP, DefaultGroup.ID, 0) == IntPtr.Zero) { + private void EnsureDefaultGroup() + { + if (IsHandleCreated && ComctlSupportsVisualStyles && GroupsEnabled) + { + if (SendMessage(NativeMethods.LVM_HASGROUP, DefaultGroup.ID, 0) == IntPtr.Zero) + { UpdateGroupView(); InsertGroupNative(0, DefaultGroup); } @@ -2733,8 +3126,10 @@ private void EnsureDefaultGroup() { /// Ensure that the item is visible, scrolling the view as necessary. /// @index Index of item to scroll into view /// - public void EnsureVisible(int index) { - if (index < 0 || index >= Items.Count) { + public void EnsureVisible(int index) + { + if (index < 0 || index >= Items.Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } if (IsHandleCreated) @@ -2743,9 +3138,11 @@ public void EnsureVisible(int index) { /// /// - public ListViewItem FindItemWithText(string text) { + public ListViewItem FindItemWithText(string text) + { // if the user does not use the FindItemWithText overloads that specify a StartIndex and the listView is empty then return null - if (this.Items.Count == 0) { + if (this.Items.Count == 0) + { return null; } @@ -2754,23 +3151,26 @@ public ListViewItem FindItemWithText(string text) { /// /// - public ListViewItem FindItemWithText(string text, bool includeSubItemsInSearch, int startIndex) { + public ListViewItem FindItemWithText(string text, bool includeSubItemsInSearch, int startIndex) + { return FindItemWithText(text, includeSubItemsInSearch, startIndex, true); } /// /// - public ListViewItem FindItemWithText(string text, bool includeSubItemsInSearch, int startIndex, bool isPrefixSearch) { + public ListViewItem FindItemWithText(string text, bool includeSubItemsInSearch, int startIndex, bool isPrefixSearch) + { if (startIndex < 0 || startIndex >= this.Items.Count) { throw new ArgumentOutOfRangeException(nameof(startIndex), startIndex, string.Format(SR.InvalidArgument, nameof(startIndex), startIndex)); } - return FindItem(true, text, isPrefixSearch, new Point(0,0), SearchDirectionHint.Down, startIndex, includeSubItemsInSearch); + return FindItem(true, text, isPrefixSearch, new Point(0, 0), SearchDirectionHint.Down, startIndex, includeSubItemsInSearch); } /// /// - public ListViewItem FindNearestItem(SearchDirectionHint dir, Point point) { + public ListViewItem FindNearestItem(SearchDirectionHint dir, Point point) + { return FindNearestItem(dir, point.X, point.Y); } @@ -2778,11 +3178,13 @@ public ListViewItem FindNearestItem(SearchDirectionHint dir, Point point) { /// public ListViewItem FindNearestItem(SearchDirectionHint searchDirection, int x, int y) { - if (this.View != View.SmallIcon && this.View != View.LargeIcon) { + if (this.View != View.SmallIcon && this.View != View.LargeIcon) + { throw new InvalidOperationException(SR.ListViewFindNearestItemWorksOnlyInIconView); } - if ( searchDirection < SearchDirectionHint.Left || searchDirection > SearchDirectionHint.Down) { + if (searchDirection < SearchDirectionHint.Left || searchDirection > SearchDirectionHint.Down) + { throw new ArgumentOutOfRangeException(nameof(searchDirection), searchDirection, string.Format(SR.InvalidArgument, nameof(searchDirection), searchDirection)); } @@ -2790,9 +3192,10 @@ public ListViewItem FindNearestItem(SearchDirectionHint searchDirection, int x, // simply passing the (x,y) coordinates will cause problems when we call FindNearestItem for a point inside an item. // so we have to do some special processing when (x,y) falls inside an item; // - ListViewItem lvi = this.GetItemAt(x,y); + ListViewItem lvi = this.GetItemAt(x, y); - if (lvi != null) { + if (lvi != null) + { Rectangle itemBounds = lvi.Bounds; // LVM_FINDITEM is a nightmare // LVM_FINDITEM will use the top left corner of icon rectangle to determine the closest item @@ -2801,7 +3204,8 @@ public ListViewItem FindNearestItem(SearchDirectionHint searchDirection, int x, Rectangle iconBounds = this.GetItemRect(lvi.Index, ItemBoundsPortion.Icon); - switch (searchDirection) { + switch (searchDirection) + { case SearchDirectionHint.Up: y = Math.Max(itemBounds.Top, iconBounds.Top) - 1; break; @@ -2817,36 +3221,47 @@ public ListViewItem FindNearestItem(SearchDirectionHint searchDirection, int x, default: Debug.Assert(false, "these are all the search directions"); break; - } + } } return FindItem(false, string.Empty, false, new Point(x, y), searchDirection, -1, false); } - private ListViewItem FindItem(bool isTextSearch, string text, bool isPrefixSearch, Point pt, SearchDirectionHint dir, int startIndex, bool includeSubItemsInSearch) { - if (this.Items.Count == 0) { + private ListViewItem FindItem(bool isTextSearch, string text, bool isPrefixSearch, Point pt, SearchDirectionHint dir, int startIndex, bool includeSubItemsInSearch) + { + if (this.Items.Count == 0) + { return null; } if (!IsHandleCreated) CreateHandle(); - if (VirtualMode) { + if (VirtualMode) + { SearchForVirtualItemEventArgs sviEvent = new SearchForVirtualItemEventArgs(isTextSearch, isPrefixSearch, includeSubItemsInSearch, text, pt, dir, startIndex); OnSearchForVirtualItem(sviEvent); // NOTE: this will cause a RetrieveVirtualItem event w/o a corresponding cache hint event. - if (sviEvent.Index != -1) { + if (sviEvent.Index != -1) + { return this.Items[sviEvent.Index]; - } else { + } + else + { return null; } - } else { + } + else + { NativeMethods.LVFINDINFO lvFindInfo = new NativeMethods.LVFINDINFO(); - if (isTextSearch) { + if (isTextSearch) + { lvFindInfo.flags = NativeMethods.LVFI_STRING; lvFindInfo.flags |= (isPrefixSearch ? NativeMethods.LVFI_PARTIAL : 0); lvFindInfo.psz = text; - } else { + } + else + { lvFindInfo.flags = NativeMethods.LVFI_NEARESTXY; lvFindInfo.ptX = pt.X; lvFindInfo.ptY = pt.Y; @@ -2856,15 +3271,20 @@ private ListViewItem FindItem(bool isTextSearch, string text, bool isPrefixSearc lvFindInfo.lParam = IntPtr.Zero; int index = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_FINDITEM, - startIndex-1, // decrement startIndex so that the search is 0-based + startIndex - 1, // decrement startIndex so that the search is 0-based ref lvFindInfo); - if (index >= 0) { + if (index >= 0) + { return Items[index]; - } else if (isTextSearch && includeSubItemsInSearch) { + } + else if (isTextSearch && includeSubItemsInSearch) + { // win32 listView control can't search inside sub items - for (int i = startIndex; i < this.Items.Count; i ++) { + for (int i = startIndex; i < this.Items.Count; i++) + { ListViewItem lvi = this.Items[i]; - for (int j = 0; j < lvi.SubItems.Count; j ++) { + for (int j = 0; j < lvi.SubItems.Count; j++) + { ListViewItem.ListViewSubItem lvsi = lvi.SubItems[j]; // the win32 list view search for items w/ text is case insensitive // do the same for sub items @@ -2872,63 +3292,80 @@ private ListViewItem FindItem(bool isTextSearch, string text, bool isPrefixSearc // ie, use String.Compare(string, string, case sensitive, CultureInfo) // instead of new Whidbey String.Equals overload // String.Equals(string, string, StringComparison.OrdinalIgnoreCase - if (string.Equals(text,lvsi.Text, StringComparison.OrdinalIgnoreCase)) { + if (string.Equals(text, lvsi.Text, StringComparison.OrdinalIgnoreCase)) + { return lvi; - } else if (isPrefixSearch && CultureInfo.CurrentCulture.CompareInfo.IsPrefix(lvsi.Text, text, CompareOptions.IgnoreCase)) { + } + else if (isPrefixSearch && CultureInfo.CurrentCulture.CompareInfo.IsPrefix(lvsi.Text, text, CompareOptions.IgnoreCase)) + { return lvi; } } } return null; - } else { + } + else + { return null; } } } - private void ForceCheckBoxUpdate() { + private void ForceCheckBoxUpdate() + { // Force ListView to update its checkbox bitmaps. // - if (CheckBoxes && IsHandleCreated) { + if (CheckBoxes && IsHandleCreated) + { SendMessage(NativeMethods.LVM_SETEXTENDEDLISTVIEWSTYLE, NativeMethods.LVS_EX_CHECKBOXES, 0); SendMessage(NativeMethods.LVM_SETEXTENDEDLISTVIEWSTYLE, NativeMethods.LVS_EX_CHECKBOXES, NativeMethods.LVS_EX_CHECKBOXES); // Comctl should handle auto-arrange for us, but doesn't - if (AutoArrange) { + if (AutoArrange) + { ArrangeIcons(Alignment); } } } - private string GenerateRandomName() { + private string GenerateRandomName() + { Debug.Assert(this.BackgroundImage != null, "we need to generate random numbers only when saving the background image to disk"); Bitmap bm = new Bitmap(this.BackgroundImage); int handle = 0; - try { - handle = unchecked ((int) (long) bm.GetHicon()); - } catch { + try + { + handle = unchecked((int)(long)bm.GetHicon()); + } + catch + { bm.Dispose(); } Random rnd; - if (handle == 0) { + if (handle == 0) + { // there was a problem when we got the icon handle // use DateTime.Now to seed the randomizer rnd = new Random((int)System.DateTime.Now.Ticks); - } else { + } + else + { rnd = new Random(handle); } return rnd.Next().ToString(CultureInfo.InvariantCulture); } // IDs for identifying ListViewItem's - private int GenerateUniqueID() { + private int GenerateUniqueID() + { // Okay, if someone adds several billion items to the list and doesn't remove all of them, // we can reuse the same ID, but I'm willing to take that risk. We are even tracking IDs // on a per-list view basis to reduce the problem. int result = nextID++; - if (result == -1) {// leave -1 as a "no such value" ID + if (result == -1) + {// leave -1 as a "no such value" ID result = 0; nextID = 1; } @@ -2940,36 +3377,42 @@ private int GenerateUniqueID() { /// value from GetDisplayIndex, or -1 if you don't know. If provided, /// the search for the index can be greatly improved. /// - internal int GetDisplayIndex(ListViewItem item, int lastIndex) { + internal int GetDisplayIndex(ListViewItem item, int lastIndex) + { Debug.Assert(item.listView == this, "Can't GetDisplayIndex if the list item doesn't belong to us"); Debug.Assert(item.ID != -1, "ListViewItem has no ID yet"); ApplyUpdateCachedItems(); - if (IsHandleCreated && !ListViewHandleDestroyed) { + if (IsHandleCreated && !ListViewHandleDestroyed) + { NativeMethods.LVFINDINFO info = new NativeMethods.LVFINDINFO(); - info.lParam = (IntPtr) item.ID; + info.lParam = (IntPtr)item.ID; info.flags = NativeMethods.LVFI_PARAM; int displayIndex = -1; - if (lastIndex != -1) { + if (lastIndex != -1) + { displayIndex = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_FINDITEM, lastIndex - 1, ref info); } - if (displayIndex == -1) { + if (displayIndex == -1) + { displayIndex = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_FINDITEM, -1 /* beginning */, ref info); } Debug.Assert(displayIndex != -1, "This item is in the list view -- why can't we find a display index for it?"); return displayIndex; } - else { + else + { // PERF: The only reason we should ever call this before the handle is created // is if the user calls ListViewItem.Index. Debug.Assert(listItemsArray != null, "listItemsArray is null, but the handle isn't created"); int index = 0; - foreach (object o in listItemsArray) { + foreach (object o in listItemsArray) + { if (o == item) return index; index++; @@ -2982,11 +3425,13 @@ internal int GetDisplayIndex(ListViewItem item, int lastIndex) { /// Called by ColumnHeader objects to determine their position /// in the ListView /// - internal int GetColumnIndex(ColumnHeader ch) { + internal int GetColumnIndex(ColumnHeader ch) + { if (columnHeaders == null) return -1; - for (int i = 0; i < columnHeaders.Length; i++) { + for (int i = 0; i < columnHeaders.Length; i++) + { if (columnHeaders[i] == ch) return i; } @@ -2998,7 +3443,8 @@ internal int GetColumnIndex(ColumnHeader ch) { /// Returns the current ListViewItem corresponding to the specific /// x,y co-ordinate. /// - public ListViewItem GetItemAt(int x, int y) { + public ListViewItem GetItemAt(int x, int y) + { NativeMethods.LVHITTESTINFO lvhi = new NativeMethods.LVHITTESTINFO(); lvhi.pt_x = x; @@ -3013,19 +3459,23 @@ public ListViewItem GetItemAt(int x, int y) { return li; } - internal int GetNativeGroupId(ListViewItem item) { + internal int GetNativeGroupId(ListViewItem item) + { item.UpdateGroupFromName(); - if (item.Group != null && Groups.Contains(item.Group)) { + if (item.Group != null && Groups.Contains(item.Group)) + { return item.Group.ID; } - else { + else + { EnsureDefaultGroup(); return DefaultGroup.ID; } } - internal void GetSubItemAt(int x, int y, out int iItem, out int iSubItem) { + internal void GetSubItemAt(int x, int y, out int iItem, out int iSubItem) + { NativeMethods.LVHITTESTINFO lvhi = new NativeMethods.LVHITTESTINFO(); lvhi.pt_x = x; @@ -3033,64 +3483,76 @@ internal void GetSubItemAt(int x, int y, out int iItem, out int iSubItem) { int index = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SUBITEMHITTEST, 0, lvhi); - if (index > -1) { + if (index > -1) + { iItem = lvhi.iItem; iSubItem = lvhi.iSubItem; - } else { + } + else + { iItem = -1; iSubItem = -1; } } - internal Point GetItemPosition(int index) { + internal Point GetItemPosition(int index) + { NativeMethods.POINT pt = new NativeMethods.POINT(); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_GETITEMPOSITION, index, pt); return new Point(pt.x, pt.y); } - internal int GetItemState(int index) { + internal int GetItemState(int index) + { return GetItemState(index, NativeMethods.LVIS_FOCUSED | NativeMethods.LVIS_SELECTED | NativeMethods.LVIS_CUT | NativeMethods.LVIS_DROPHILITED | NativeMethods.LVIS_OVERLAYMASK | NativeMethods.LVIS_STATEIMAGEMASK); } - internal int GetItemState(int index, int mask) { - if (index < 0 || ((this.VirtualMode && index >= this.VirtualListSize) || (!this.VirtualMode && index >= itemCount))) { + internal int GetItemState(int index, int mask) + { + if (index < 0 || ((this.VirtualMode && index >= this.VirtualListSize) || (!this.VirtualMode && index >= itemCount))) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } Debug.Assert(IsHandleCreated, "How did we add items without a handle?"); - return unchecked( (int) (long)SendMessage(NativeMethods.LVM_GETITEMSTATE, index, mask)); + return unchecked((int)(long)SendMessage(NativeMethods.LVM_GETITEMSTATE, index, mask)); } /// /// Returns a list item's bounding rectangle, including subitems. /// - public Rectangle GetItemRect(int index) { + public Rectangle GetItemRect(int index) + { return GetItemRect(index, 0); } /// /// Returns a specific portion of a list item's bounding rectangle. /// - public Rectangle GetItemRect(int index, ItemBoundsPortion portion) { - if (index < 0 || index >= this.Items.Count) { + public Rectangle GetItemRect(int index, ItemBoundsPortion portion) + { + if (index < 0 || index >= this.Items.Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } //valid values are 0x0 to 0x3 - if (!ClientUtils.IsEnumValid(portion, (int)portion, (int)ItemBoundsPortion.Entire, (int)ItemBoundsPortion.ItemOnly)){ + if (!ClientUtils.IsEnumValid(portion, (int)portion, (int)ItemBoundsPortion.Entire, (int)ItemBoundsPortion.ItemOnly)) + { throw new InvalidEnumArgumentException(nameof(portion), (int)portion, typeof(ItemBoundsPortion)); } - if (this.View == View.Details && this.Columns.Count == 0) { + if (this.View == View.Details && this.Columns.Count == 0) + { return Rectangle.Empty; } NativeMethods.RECT itemrect = new NativeMethods.RECT(); itemrect.left = (int)portion; - if (unchecked( (int) (long)SendMessage(NativeMethods.LVM_GETITEMRECT, index, ref itemrect)) == 0) + if (unchecked((int)(long)SendMessage(NativeMethods.LVM_GETITEMRECT, index, ref itemrect)) == 0) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); return Rectangle.FromLTRB(itemrect.left, itemrect.top, itemrect.right, itemrect.bottom); @@ -3100,18 +3562,20 @@ public Rectangle GetItemRect(int index, ItemBoundsPortion portion) { /// Private version of GetItemRect that fails silently. We use this instead of catching /// exceptions thrown by GetItemRect, to avoid first chance exceptions confusing the user. /// - private Rectangle GetItemRectOrEmpty(int index) { + private Rectangle GetItemRectOrEmpty(int index) + { if (index < 0 || index >= this.Items.Count) return Rectangle.Empty; - if (this.View == View.Details && this.Columns.Count == 0) { + if (this.View == View.Details && this.Columns.Count == 0) + { return Rectangle.Empty; } NativeMethods.RECT itemrect = new NativeMethods.RECT(); itemrect.left = 0; - if (unchecked( (int) (long)SendMessage(NativeMethods.LVM_GETITEMRECT, index, ref itemrect)) == 0) + if (unchecked((int)(long)SendMessage(NativeMethods.LVM_GETITEMRECT, index, ref itemrect)) == 0) return Rectangle.Empty; return Rectangle.FromLTRB(itemrect.left, itemrect.top, itemrect.right, itemrect.bottom); @@ -3134,7 +3598,8 @@ private NativeMethods.LVGROUP GetLVGROUP(ListViewGroup group) // Alignment // - switch(group.HeaderAlignment) { + switch (group.HeaderAlignment) + { case HorizontalAlignment.Left: lvgroup.uAlign = NativeMethods.LVGA_HEADER_LEFT; break; @@ -3151,21 +3616,26 @@ private NativeMethods.LVGROUP GetLVGROUP(ListViewGroup group) /// /// Returns a listview sub-item's bounding rectangle. /// - internal Rectangle GetSubItemRect(int itemIndex, int subItemIndex) { + internal Rectangle GetSubItemRect(int itemIndex, int subItemIndex) + { return GetSubItemRect(itemIndex, subItemIndex, 0); } - internal Rectangle GetSubItemRect(int itemIndex, int subItemIndex, ItemBoundsPortion portion) { + internal Rectangle GetSubItemRect(int itemIndex, int subItemIndex, ItemBoundsPortion portion) + { // it seems that getting the rectangle for a sub item only works for list view which are in Details view - if (this.View != View.Details) { + if (this.View != View.Details) + { return Rectangle.Empty; } - if (itemIndex < 0 || itemIndex >= this.Items.Count) { + if (itemIndex < 0 || itemIndex >= this.Items.Count) + { throw new ArgumentOutOfRangeException(nameof(itemIndex), itemIndex, string.Format(SR.InvalidArgument, nameof(itemIndex), itemIndex)); } int subItemCount = Items[itemIndex].SubItems.Count; - if (subItemIndex < 0 || subItemIndex >= subItemCount) { + if (subItemIndex < 0 || subItemIndex >= subItemCount) + { throw new ArgumentOutOfRangeException(nameof(subItemIndex), subItemIndex, string.Format(SR.InvalidArgument, nameof(subItemIndex), subItemIndex)); } //valid values are 0x0 to 0x3 @@ -3174,14 +3644,15 @@ internal Rectangle GetSubItemRect(int itemIndex, int subItemIndex, ItemBoundsPor throw new InvalidEnumArgumentException(nameof(portion), (int)portion, typeof(ItemBoundsPortion)); } - if (this.Columns.Count == 0) { + if (this.Columns.Count == 0) + { return Rectangle.Empty; } NativeMethods.RECT itemrect = new NativeMethods.RECT(); itemrect.left = (int)portion; itemrect.top = subItemIndex; - if (unchecked( (int) (long)SendMessage(NativeMethods.LVM_GETSUBITEMRECT, itemIndex, ref itemrect)) == 0) + if (unchecked((int)(long)SendMessage(NativeMethods.LVM_GETSUBITEMRECT, itemIndex, ref itemrect)) == 0) throw new ArgumentOutOfRangeException(nameof(itemIndex), itemIndex, string.Format(SR.InvalidArgument, nameof(itemIndex), itemIndex)); Rectangle result = Rectangle.FromLTRB(itemrect.left, itemrect.top, itemrect.right, itemrect.bottom); @@ -3191,14 +3662,17 @@ internal Rectangle GetSubItemRect(int itemIndex, int subItemIndex, ItemBoundsPor /// /// - public ListViewHitTestInfo HitTest(Point point) { + public ListViewHitTestInfo HitTest(Point point) + { return HitTest(point.X, point.Y); } /// /// - public ListViewHitTestInfo HitTest(int x, int y) { - if (!this.ClientRectangle.Contains(x, y)) { + public ListViewHitTestInfo HitTest(int x, int y) + { + if (!this.ClientRectangle.Contains(x, y)) + { return new ListViewHitTestInfo(null /*hitItem*/, null /*hitSubItem*/, ListViewHitTestLocations.None /*hitLocation*/); } @@ -3208,38 +3682,52 @@ public ListViewHitTestInfo HitTest(int x, int y) { int iItem; - if (this.View == View.Details) { - iItem = unchecked( (int) (long)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_SUBITEMHITTEST, 0, lvhi)); - } else { - iItem = unchecked( (int) (long)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_HITTEST, 0, lvhi)); + if (this.View == View.Details) + { + iItem = unchecked((int)(long)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_SUBITEMHITTEST, 0, lvhi)); + } + else + { + iItem = unchecked((int)(long)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_HITTEST, 0, lvhi)); } ListViewItem item = (iItem == -1) ? null : Items[iItem]; ListViewHitTestLocations location = ListViewHitTestLocations.None; - if (item == null && (NativeMethods.LVHT_ABOVE & lvhi.flags) == NativeMethods.LVHT_ABOVE) { + if (item == null && (NativeMethods.LVHT_ABOVE & lvhi.flags) == NativeMethods.LVHT_ABOVE) + { location = (ListViewHitTestLocations)((MASK_HITTESTFLAG & lvhi.flags) | (int)ListViewHitTestLocations.AboveClientArea); } - else if (item != null && (NativeMethods.LVHT_ONITEMSTATEICON & lvhi.flags) == NativeMethods.LVHT_ONITEMSTATEICON) { + else if (item != null && (NativeMethods.LVHT_ONITEMSTATEICON & lvhi.flags) == NativeMethods.LVHT_ONITEMSTATEICON) + { location = (ListViewHitTestLocations)((MASK_HITTESTFLAG & lvhi.flags) | (int)ListViewHitTestLocations.StateImage); } - else { + else + { location = (ListViewHitTestLocations)lvhi.flags; } - if (this.View == View.Details && item != null) { - if (lvhi.iSubItem < item.SubItems.Count) { + if (this.View == View.Details && item != null) + { + if (lvhi.iSubItem < item.SubItems.Count) + { return new ListViewHitTestInfo(item, item.SubItems[lvhi.iSubItem], location); - } else { + } + else + { return new ListViewHitTestInfo(item, null, location); } - } else { + } + else + { return (new ListViewHitTestInfo(item, null, location)); } } - private void InvalidateColumnHeaders() { - if (viewStyle == View.Details && IsHandleCreated) { + private void InvalidateColumnHeaders() + { + if (viewStyle == View.Details && IsHandleCreated) + { // IntPtr hwndHdr = UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_GETHEADER, 0, 0); @@ -3251,13 +3739,15 @@ private void InvalidateColumnHeaders() { /// /// Inserts a new Column into the ListView /// - internal ColumnHeader InsertColumn(int index, ColumnHeader ch) { + internal ColumnHeader InsertColumn(int index, ColumnHeader ch) + { return InsertColumn(index, ch, true); } /// /// - internal ColumnHeader InsertColumn(int index, ColumnHeader ch, bool refreshSubItems) { + internal ColumnHeader InsertColumn(int index, ColumnHeader ch, bool refreshSubItems) + { if (ch == null) throw new ArgumentNullException(nameof(ch)); if (ch.OwnerListview != null) @@ -3267,10 +3757,12 @@ internal ColumnHeader InsertColumn(int index, ColumnHeader ch, bool refreshSubIt int idx; // in Tile view the ColumnHeaders collection is used for the Tile Information // recreate the handle in that case - if (IsHandleCreated && this.View != View.Tile) { + if (IsHandleCreated && this.View != View.Tile) + { idx = InsertColumnNative(index, ch); } - else { + else + { idx = index; } @@ -3281,7 +3773,8 @@ internal ColumnHeader InsertColumn(int index, ColumnHeader ch, bool refreshSubIt // Add the column to our internal array int columnCount = (columnHeaders == null ? 0 : columnHeaders.Length); - if (columnCount > 0) { + if (columnCount > 0) + { ColumnHeader[] newHeaders = new ColumnHeader[columnCount + 1]; if (columnCount > 0) System.Array.Copy(columnHeaders, 0, newHeaders, 0, columnCount); @@ -3290,7 +3783,8 @@ internal ColumnHeader InsertColumn(int index, ColumnHeader ch, bool refreshSubIt else columnHeaders = new ColumnHeader[1]; - if (idx < columnCount) { + if (idx < columnCount) + { System.Array.Copy(columnHeaders, idx, columnHeaders, idx + 1, columnCount - idx); } columnHeaders[idx] = ch; @@ -3298,7 +3792,8 @@ internal ColumnHeader InsertColumn(int index, ColumnHeader ch, bool refreshSubIt // in Tile view the ColumnHeaders collection is used for the Tile Information // recreate the handle in that case - if (ch.ActualImageIndex_Internal != -1 && this.IsHandleCreated && this.View != View.Tile) { + if (ch.ActualImageIndex_Internal != -1 && this.IsHandleCreated && this.View != View.Tile) + { SetColumnInfo(NativeMethods.LVCF_IMAGE, ch); } @@ -3306,51 +3801,60 @@ internal ColumnHeader InsertColumn(int index, ColumnHeader ch, bool refreshSubIt // update the DisplayIndex for each column // we are only setting an integer in the ColumnHeader, this is not expensive int[] indices = new int[this.Columns.Count]; - for (int i = 0; i < this.Columns.Count; i ++) { + for (int i = 0; i < this.Columns.Count; i++) + { ColumnHeader hdr = this.Columns[i]; - if (hdr == ch) { + if (hdr == ch) + { // the newly added column hdr.DisplayIndexInternal = index; - } else if (hdr.DisplayIndex >= index) { - hdr.DisplayIndexInternal ++; + } + else if (hdr.DisplayIndex >= index) + { + hdr.DisplayIndexInternal++; } indices[i] = hdr.DisplayIndexInternal; } - SetDisplayIndices( indices ); - + SetDisplayIndices(indices); + #if DEBUG CheckDisplayIndices(); #endif // in Tile view the ColumnHeaders collection is used for the Tile Information // recreate the handle in that case - if (this.IsHandleCreated && this.View == View.Tile) { + if (this.IsHandleCreated && this.View == View.Tile) + { this.RecreateHandleInternal(); - } else if (IsHandleCreated && refreshSubItems) + } + else if (IsHandleCreated && refreshSubItems) RealizeAllSubItems(); return ch; } - private int InsertColumnNative(int index, ColumnHeader ch) { + private int InsertColumnNative(int index, ColumnHeader ch) + { NativeMethods.LVCOLUMN_T lvColumn = new NativeMethods.LVCOLUMN_T(); lvColumn.mask = NativeMethods.LVCF_FMT | NativeMethods.LVCF_TEXT | NativeMethods.LVCF_WIDTH;// | NativeMethods.LVCF_ORDER | NativeMethods.LVCF_IMAGE; - if (ch.OwnerListview != null && ch.ActualImageIndex_Internal != -1) { + if (ch.OwnerListview != null && ch.ActualImageIndex_Internal != -1) + { lvColumn.mask |= NativeMethods.LVCF_IMAGE; lvColumn.iImage = ch.ActualImageIndex_Internal; } - lvColumn.fmt = (int)ch.TextAlign; - lvColumn.cx = ch.Width; - lvColumn.pszText = ch.Text; + lvColumn.fmt = (int)ch.TextAlign; + lvColumn.cx = ch.Width; + lvColumn.pszText = ch.Text; return (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_INSERTCOLUMN, index, lvColumn); } // when the user adds a group, this helper method makes sure that all the items // in the list view are parented by a group - be it the DefaultGroup or some other group - internal void InsertGroupInListView(int index, ListViewGroup group) { + internal void InsertGroupInListView(int index, ListViewGroup group) + { Debug.Assert(this.groups != null && this.groups.Count > 0, "this method should be used only when the user adds a group, not when we add our own DefaultGroup"); Debug.Assert(group != this.DefaultGroup, "this method should be used only when the user adds a group, not when we add our own DefaultGroup"); @@ -3363,10 +3867,13 @@ internal void InsertGroupInListView(int index, ListViewGroup group) { // take all the list view items which don't belong to any group and put them in the default group // - if (groupItems) { - for (int i = 0; i < this.Items.Count; i ++) { + if (groupItems) + { + for (int i = 0; i < this.Items.Count; i++) + { ListViewItem item = this.Items[i]; - if (item.Group == null) { + if (item.Group == null) + { item.UpdateStateToListView(item.Index); } } @@ -3374,8 +3881,10 @@ internal void InsertGroupInListView(int index, ListViewGroup group) { #if DEBUG // sanity check: all the items in the list view should have a group ID - if (this.GroupsEnabled) { - for (int i = 0; i < this.Items.Count; i ++) { + if (this.GroupsEnabled) + { + for (int i = 0; i < this.Items.Count; i++) + { ListViewItem item = this.Items[i]; NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM(); lvItem.iItem = item.Index; @@ -3388,20 +3897,21 @@ internal void InsertGroupInListView(int index, ListViewGroup group) { } // does the Win32 part of the job of inserting the group - private void InsertGroupNative(int index, ListViewGroup group) { - Debug.Assert(IsHandleCreated,"InsertGroupNative precondition: list-view handle must be created"); - Debug.Assert(group == DefaultGroup || this.Groups.Contains(group),"Make sure ListView.Groups contains this group before adding the native LVGROUP. Otherwise, custom-drawing may break."); + private void InsertGroupNative(int index, ListViewGroup group) + { + Debug.Assert(IsHandleCreated, "InsertGroupNative precondition: list-view handle must be created"); + Debug.Assert(group == DefaultGroup || this.Groups.Contains(group), "Make sure ListView.Groups contains this group before adding the native LVGROUP. Otherwise, custom-drawing may break."); NativeMethods.LVGROUP lvgroup = new NativeMethods.LVGROUP(); try { - lvgroup = GetLVGROUP(group); - int retval = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this,this.Handle),NativeMethods.LVM_INSERTGROUP,index,lvgroup); - Debug.Assert(retval != -1,"Failed to insert group"); + lvgroup = GetLVGROUP(group); + int retval = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_INSERTGROUP, index, lvgroup); + Debug.Assert(retval != -1, "Failed to insert group"); } finally { - DestroyLVGROUP(lvgroup); + DestroyLVGROUP(lvgroup); } } @@ -3410,9 +3920,11 @@ private void InsertGroupNative(int index, ListViewGroup group) { /// either in the correct sorted position, or, if no sorting is set, at the /// position indicated by the index parameter. /// - private void InsertItems(int displayIndex, ListViewItem[] items, bool checkHosting) { + private void InsertItems(int displayIndex, ListViewItem[] items, bool checkHosting) + { - if (items == null || items.Length == 0) { + if (items == null || items.Length == 0) + { return; } @@ -3424,11 +3936,15 @@ private void InsertItems(int displayIndex, ListViewItem[] items, bool checkHosti // if we're in the middle of a Begin/EndUpdate, just push the items into our array list // as they'll get processed on EndUpdate. // - if (updateCounter > 0 && Properties.GetObject(PropDelayedUpdateItems) != null) { + if (updateCounter > 0 && Properties.GetObject(PropDelayedUpdateItems) != null) + { // CheckHosting. - if (checkHosting) { - for (int i = 0; i < items.Length; i ++) { - if (items[i].listView != null) { + if (checkHosting) + { + for (int i = 0; i < items.Length; i++) + { + if (items[i].listView != null) + { throw new ArgumentException(string.Format(SR.OnlyOneControl, items[i].Text), "item"); } } @@ -3436,13 +3952,15 @@ private void InsertItems(int displayIndex, ListViewItem[] items, bool checkHosti ArrayList itemList = (ArrayList)Properties.GetObject(PropDelayedUpdateItems); Debug.Assert(itemList != null, "In Begin/EndUpdate with no delayed array!"); - if (itemList != null) { + if (itemList != null) + { itemList.AddRange(items); } // add the list view item to the list view // this way we can retrieve the item's index inside BeginUpdate/EndUpdate - for (int i = 0; i < items.Length; i ++) { + for (int i = 0; i < items.Length; i++) + { items[i].Host(this, GenerateUniqueID(), -1); } @@ -3453,10 +3971,12 @@ private void InsertItems(int displayIndex, ListViewItem[] items, bool checkHosti // loop through the items and give them id's so we can identify them later. // - for (int i = 0; i < items.Length; i++) { + for (int i = 0; i < items.Length; i++) + { ListViewItem item = items[i]; - if (checkHosting && item.listView != null) { + if (checkHosting && item.listView != null) + { throw new ArgumentException(string.Format(SR.OnlyOneControl, item.Text), "item"); } @@ -3467,11 +3987,12 @@ private void InsertItems(int displayIndex, ListViewItem[] items, bool checkHosti listItemsTable.Add(itemID, item); itemCount++; - item.Host(this,itemID, -1); + item.Host(this, itemID, -1); // if there's no handle created, just ad them to our list items array. // - if (!IsHandleCreated) { + if (!IsHandleCreated) + { Debug.Assert(listItemsArray != null, "listItemsArray is null, but the handle isn't created"); listItemsArray.Insert(displayIndex + i, item); } @@ -3479,7 +4000,8 @@ private void InsertItems(int displayIndex, ListViewItem[] items, bool checkHosti // finally if the handle is created, do the actual add into the real list view // - if (IsHandleCreated) { + if (IsHandleCreated) + { InsertItemsNative(displayIndex, items); } @@ -3491,7 +4013,8 @@ private void InsertItems(int displayIndex, ListViewItem[] items, bool checkHosti // Update sorted order - if (!VirtualMode) { + if (!VirtualMode) + { Sort(); } @@ -3504,8 +4027,10 @@ private void InsertItems(int displayIndex, ListViewItem[] items, bool checkHosti /// This only will be called when the Handle has been created for the list view. /// This method loops through the items, sets up their state then adds them. /// - private int InsertItemsNative(int index, ListViewItem[] items) { - if (items == null || items.Length == 0) { + private int InsertItemsNative(int index, ListViewItem[] items) + { + if (items == null || items.Length == 0) + { return 0; } Debug.Assert(IsHandleCreated, "InsertItemsNative precondition: list-view handle must be created"); @@ -3513,7 +4038,8 @@ private int InsertItemsNative(int index, ListViewItem[] items) { // Much more efficient to call the native insert with max + 1, than with max. The + 1 // for the display index accounts for itemCount++ above. // - if (index == itemCount - 1) { + if (index == itemCount - 1) + { index++; } @@ -3524,34 +4050,37 @@ private int InsertItemsNative(int index, ListViewItem[] items) { int maxColumns = 0; this.listViewState1[LISTVIEWSTATE1_insertingItemsNatively] = true; - try { + try + { // Set the count of items first. // SendMessage(NativeMethods.LVM_SETITEMCOUNT, itemCount, 0); // Now add the items. // - for (int i = 0; i < items.Length; i++) { + for (int i = 0; i < items.Length; i++) + { ListViewItem li = items[i]; Debug.Assert(this.Items.Contains(li), "Make sure ListView.Items contains this item before adding the native LVITEM. Otherwise, custom-drawing may break."); lvItem.Reset(); lvItem.mask = NativeMethods.LVIF_TEXT | NativeMethods.LVIF_IMAGE | NativeMethods.LVIF_PARAM | NativeMethods.LVIF_INDENT; - lvItem.iItem = index + i; - lvItem.pszText = li.Text; - lvItem.iImage = li.ImageIndexer.ActualIndex; - lvItem.iIndent = li.IndentCount; - lvItem.lParam = (IntPtr)li.ID; + lvItem.iItem = index + i; + lvItem.pszText = li.Text; + lvItem.iImage = li.ImageIndexer.ActualIndex; + lvItem.iIndent = li.IndentCount; + lvItem.lParam = (IntPtr)li.ID; - if (GroupsEnabled) { + if (GroupsEnabled) + { lvItem.mask |= NativeMethods.LVIF_GROUPID; lvItem.iGroupId = GetNativeGroupId(li); - #if DEBUG - Debug.Assert(SendMessage(NativeMethods.LVM_ISGROUPVIEWENABLED, 0, 0) != IntPtr.Zero, "Groups not enabled"); - Debug.Assert(SendMessage(NativeMethods.LVM_HASGROUP, lvItem.iGroupId, 0) != IntPtr.Zero, "Doesn't contain group id: " + lvItem.iGroupId.ToString(CultureInfo.InvariantCulture)); - #endif +#if DEBUG + Debug.Assert(SendMessage(NativeMethods.LVM_ISGROUPVIEWENABLED, 0, 0) != IntPtr.Zero, "Groups not enabled"); + Debug.Assert(SendMessage(NativeMethods.LVM_HASGROUP, lvItem.iGroupId, 0) != IntPtr.Zero, "Doesn't contain group id: " + lvItem.iGroupId.ToString(CultureInfo.InvariantCulture)); +#endif } lvItem.mask |= NativeMethods.LVIF_COLUMNS; @@ -3560,8 +4089,10 @@ private int InsertItemsNative(int index, ListViewItem[] items) { // make sure that our columns memory is big enough. // if not, then realloc it. // - if (lvItem.cColumns > maxColumns || hGlobalColumns == IntPtr.Zero) { - if (hGlobalColumns != IntPtr.Zero) { + if (lvItem.cColumns > maxColumns || hGlobalColumns == IntPtr.Zero) + { + if (hGlobalColumns != IntPtr.Zero) + { Marshal.FreeHGlobal(hGlobalColumns); } hGlobalColumns = Marshal.AllocHGlobal(lvItem.cColumns * sizeof(int)); @@ -3572,7 +4103,8 @@ private int InsertItemsNative(int index, ListViewItem[] items) { // lvItem.puColumns = hGlobalColumns; int[] columns = new int[lvItem.cColumns]; - for(int c = 0; c < lvItem.cColumns; c++) { + for (int c = 0; c < lvItem.cColumns; c++) + { columns[c] = c + 1; } Marshal.Copy(columns, 0, lvItem.puColumns, lvItem.cColumns); @@ -3586,44 +4118,53 @@ private int InsertItemsNative(int index, ListViewItem[] items) { int insertIndex; - try { + try + { li.UpdateStateToListView(lvItem.iItem, ref lvItem, false); insertIndex = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_INSERTITEM, 0, ref lvItem); - if (actualIndex == -1) { + if (actualIndex == -1) + { actualIndex = insertIndex; // and update our starting index. so we're going from the same point. // index = actualIndex; } - } finally { + } + finally + { // Restore the item check event handler. // onItemCheck = oldOnItemCheck; } - if (-1 == insertIndex) { + if (-1 == insertIndex) + { throw new InvalidOperationException(SR.ListViewAddItemFailed); } // add all sub items - for (int nItem = 1; nItem < li.SubItems.Count; ++nItem) { + for (int nItem = 1; nItem < li.SubItems.Count; ++nItem) + { SetItemText(insertIndex, nItem, li.SubItems[nItem].Text, ref lvItem); } // PERF. // Use StateSelected in order to avoid a call into the native list view. - if (li.StateImageSet || li.StateSelected) { + if (li.StateImageSet || li.StateSelected) + { // lvItem.state and lvItem.stateMask are set when the lvItem is updated in UpdateStateToListView call. SetItemState(insertIndex, lvItem.state, lvItem.stateMask); } } } - finally { - if (hGlobalColumns != IntPtr.Zero) { + finally + { + if (hGlobalColumns != IntPtr.Zero) + { Marshal.FreeHGlobal(hGlobalColumns); } this.listViewState1[LISTVIEWSTATE1_insertingItemsNatively] = false; @@ -3636,7 +4177,8 @@ private int InsertItemsNative(int index, ListViewItem[] items) { OnSelectedIndexChanged(EventArgs.Empty); } - if (this.FlipViewToLargeIconAndSmallIcon) { + if (this.FlipViewToLargeIconAndSmallIcon) + { this.FlipViewToLargeIconAndSmallIcon = false; this.View = View.LargeIcon; @@ -3649,9 +4191,12 @@ private int InsertItemsNative(int index, ListViewItem[] items) { /// /// Handling special input keys, such as pgup, pgdown, home, end, etc... /// - protected override bool IsInputKey(Keys keyData) { - if ((keyData & Keys.Alt) == Keys.Alt) return false; - switch (keyData & Keys.KeyCode) { + protected override bool IsInputKey(Keys keyData) + { + if ((keyData & Keys.Alt) == Keys.Alt) + return false; + switch (keyData & Keys.KeyCode) + { case Keys.PageUp: case Keys.PageDown: case Keys.Home: @@ -3663,8 +4208,10 @@ protected override bool IsInputKey(Keys keyData) { if (isInputKey) return true; - if (listViewState[LISTVIEWSTATE_inLabelEdit]) { - switch (keyData & Keys.KeyCode) { + if (listViewState[LISTVIEWSTATE_inLabelEdit]) + { + switch (keyData & Keys.KeyCode) + { case Keys.Return: case Keys.Escape: return true; @@ -3674,37 +4221,47 @@ protected override bool IsInputKey(Keys keyData) { return false; } - private void LargeImageListRecreateHandle(object sender, EventArgs e) { - if (IsHandleCreated) { + private void LargeImageListRecreateHandle(object sender, EventArgs e) + { + if (IsHandleCreated) + { IntPtr handle = (LargeImageList == null) ? IntPtr.Zero : LargeImageList.Handle; - SendMessage(NativeMethods.LVM_SETIMAGELIST, (IntPtr) NativeMethods.LVSIL_NORMAL, handle); + SendMessage(NativeMethods.LVM_SETIMAGELIST, (IntPtr)NativeMethods.LVSIL_NORMAL, handle); ForceCheckBoxUpdate(); } } - private void LargeImageListChangedHandle(object sender, EventArgs e) { - if (!this.VirtualMode && (null != sender) && (sender == imageListLarge) && IsHandleCreated) { - foreach (ListViewItem item in Items) { - if (item.ImageIndexer.ActualIndex != -1 && item.ImageIndexer.ActualIndex >= imageListLarge.Images.Count) { - SetItemImage(item.Index,imageListLarge.Images.Count - 1); + private void LargeImageListChangedHandle(object sender, EventArgs e) + { + if (!this.VirtualMode && (null != sender) && (sender == imageListLarge) && IsHandleCreated) + { + foreach (ListViewItem item in Items) + { + if (item.ImageIndexer.ActualIndex != -1 && item.ImageIndexer.ActualIndex >= imageListLarge.Images.Count) + { + SetItemImage(item.Index, imageListLarge.Images.Count - 1); } - else { - SetItemImage(item.Index,item.ImageIndexer.ActualIndex); + else + { + SetItemImage(item.Index, item.ImageIndexer.ActualIndex); } } } } - internal void ListViewItemToolTipChanged(ListViewItem item) { - if (this.IsHandleCreated) { + internal void ListViewItemToolTipChanged(ListViewItem item) + { + if (this.IsHandleCreated) + { // If we reset the item text then we also reset the tool tip text // SetItemText(item.Index, 0 /*subItemIndex*/, item.Text); } } - private void LvnBeginDrag(MouseButtons buttons, NativeMethods.NMLISTVIEW nmlv) { + private void LvnBeginDrag(MouseButtons buttons, NativeMethods.NMLISTVIEW nmlv) + { ListViewItem item = Items[nmlv.iItem]; OnItemDrag(new ItemDragEventArgs(buttons, item)); } @@ -3712,12 +4269,16 @@ private void LvnBeginDrag(MouseButtons buttons, NativeMethods.NMLISTVIEW nmlv) { /// /// Fires the afterLabelEdit event. /// - protected virtual void OnAfterLabelEdit(LabelEditEventArgs e) { - if (onAfterLabelEdit != null) onAfterLabelEdit(this, e); + protected virtual void OnAfterLabelEdit(LabelEditEventArgs e) + { + if (onAfterLabelEdit != null) + onAfterLabelEdit(this, e); } - protected override void OnBackgroundImageChanged(EventArgs e) { - if (IsHandleCreated) { + protected override void OnBackgroundImageChanged(EventArgs e) + { + if (IsHandleCreated) + { SetBackgroundImage(); } base.OnBackgroundImageChanged(e); @@ -3726,7 +4287,8 @@ protected override void OnBackgroundImageChanged(EventArgs e) { /// /// We keep track of if we've hovered already so we don't fire multiple hover events /// - protected override void OnMouseLeave(EventArgs e) { + protected override void OnMouseLeave(EventArgs e) + { hoveredAlready = false; base.OnMouseLeave(e); } @@ -3736,7 +4298,8 @@ protected override void OnMouseLeave(EventArgs e) { /// the item the mouse is hovering over is found. Each time a new item is hovered /// over a new event is raised. /// - protected override void OnMouseHover(EventArgs e) { + protected override void OnMouseHover(EventArgs e) + { /// Hover events need to be caught for each node /// within the TreeView so the appropriate @@ -3744,7 +4307,8 @@ protected override void OnMouseHover(EventArgs e) { ListViewItem item = null; - if (this.Items.Count > 0) { + if (this.Items.Count > 0) + { // APPCOMPAT // V1.* users implement virtualization by communicating directly to the native ListView and by passing our virtualization implementation. // In that case, the native list view may have an item under the mouse even if our wrapper thinks the item count is 0. @@ -3755,12 +4319,14 @@ protected override void OnMouseHover(EventArgs e) { item = GetItemAt(pos.X, pos.Y); } - if (item != prevHoveredItem && item != null) { + if (item != prevHoveredItem && item != null) + { OnItemMouseHover(new ListViewItemMouseHoverEventArgs(item)); prevHoveredItem = item; } - if (!hoveredAlready) { + if (!hoveredAlready) + { base.OnMouseHover(e); hoveredAlready = true; } @@ -3772,8 +4338,10 @@ protected override void OnMouseHover(EventArgs e) { /// /// Fires the beforeLabelEdit event. /// - protected virtual void OnBeforeLabelEdit(LabelEditEventArgs e) { - if (onBeforeLabelEdit != null) onBeforeLabelEdit(this, e); + protected virtual void OnBeforeLabelEdit(LabelEditEventArgs e) + { + if (onBeforeLabelEdit != null) + onBeforeLabelEdit(this, e); } /// @@ -3788,15 +4356,18 @@ protected virtual void OnCacheVirtualItems(CacheVirtualItemsEventArgs e) /// /// Fires the columnClick event. /// - protected virtual void OnColumnClick(ColumnClickEventArgs e) { - if (onColumnClick != null) onColumnClick(this, e); + protected virtual void OnColumnClick(ColumnClickEventArgs e) + { + if (onColumnClick != null) + onColumnClick(this, e); } /// /// Fires the column header rearranged event. /// - protected virtual void OnColumnReordered(ColumnReorderedEventArgs e) { - ColumnReorderedEventHandler handler = (ColumnReorderedEventHandler) Events[EVENT_COLUMNREORDERED]; + protected virtual void OnColumnReordered(ColumnReorderedEventArgs e) + { + ColumnReorderedEventHandler handler = (ColumnReorderedEventHandler)Events[EVENT_COLUMNREORDERED]; if (handler != null) handler(this, e); } @@ -3804,9 +4375,11 @@ protected virtual void OnColumnReordered(ColumnReorderedEventArgs e) { /// /// Fires the column width changing event. /// - protected virtual void OnColumnWidthChanged(ColumnWidthChangedEventArgs e) { + protected virtual void OnColumnWidthChanged(ColumnWidthChangedEventArgs e) + { ColumnWidthChangedEventHandler handler = (ColumnWidthChangedEventHandler)Events[EVENT_COLUMNWIDTHCHANGED]; - if (handler != null) { + if (handler != null) + { handler(this, e); } } @@ -3814,9 +4387,11 @@ protected virtual void OnColumnWidthChanged(ColumnWidthChangedEventArgs e) { /// /// Fires the column width changing event. /// - protected virtual void OnColumnWidthChanging(ColumnWidthChangingEventArgs e) { + protected virtual void OnColumnWidthChanging(ColumnWidthChangingEventArgs e) + { ColumnWidthChangingEventHandler handler = (ColumnWidthChangingEventHandler)Events[EVENT_COLUMNWIDTHCHANGING]; - if (handler != null) { + if (handler != null) + { handler(this, e); } } @@ -3824,9 +4399,11 @@ protected virtual void OnColumnWidthChanging(ColumnWidthChangingEventArgs e) { /// /// Fires the DrawColumnHeader event. /// - protected virtual void OnDrawColumnHeader(DrawListViewColumnHeaderEventArgs e) { + protected virtual void OnDrawColumnHeader(DrawListViewColumnHeaderEventArgs e) + { DrawListViewColumnHeaderEventHandler handler = (DrawListViewColumnHeaderEventHandler)Events[EVENT_DRAWCOLUMNHEADER]; - if (handler != null) { + if (handler != null) + { handler(this, e); } } @@ -3834,9 +4411,11 @@ protected virtual void OnDrawColumnHeader(DrawListViewColumnHeaderEventArgs e) { /// /// Fires the DrawItem event. /// - protected virtual void OnDrawItem(DrawListViewItemEventArgs e) { + protected virtual void OnDrawItem(DrawListViewItemEventArgs e) + { DrawListViewItemEventHandler handler = (DrawListViewItemEventHandler)Events[EVENT_DRAWITEM]; - if (handler != null) { + if (handler != null) + { handler(this, e); } } @@ -3844,25 +4423,32 @@ protected virtual void OnDrawItem(DrawListViewItemEventArgs e) { /// /// Fires the DrawSubItem event. /// - protected virtual void OnDrawSubItem(DrawListViewSubItemEventArgs e) { + protected virtual void OnDrawSubItem(DrawListViewSubItemEventArgs e) + { DrawListViewSubItemEventHandler handler = (DrawListViewSubItemEventHandler)Events[EVENT_DRAWSUBITEM]; - if (handler != null) { + if (handler != null) + { handler(this, e); } } - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { base.OnFontChanged(e); // When the user sets the font on the Form, the layout engine will compute the bounds for the native list view // and AFTER that will set the window font on the native list view. // That means that when the list view computed its item's position it did so w/ the previous font. // The solution is to send LVM_UPDATE to the native list view EVEN if the list view is not in SmallIcon or LargeIcon. - if (!VirtualMode && IsHandleCreated && AutoArrange) { + if (!VirtualMode && IsHandleCreated && AutoArrange) + { BeginUpdate(); - try { + try + { SendMessage(NativeMethods.LVM_UPDATE, -1, 0); - } finally { + } + finally + { EndUpdate(); } } @@ -3875,7 +4461,8 @@ protected override void OnFontChanged(EventArgs e) { /// /// - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { // uncache the "ComctlSupportsVisualStyles" property on a handle creation listViewState[LISTVIEWSTATE_comctlSupportsVisualStylesTested] = false; @@ -3883,57 +4470,64 @@ protected override void OnHandleCreated(EventArgs e) { this.FlipViewToLargeIconAndSmallIcon = false; base.OnHandleCreated(e); - + int version = unchecked((int)(long)SendMessage(NativeMethods.CCM_GETVERSION, 0, 0)); - if (version < 5) { + if (version < 5) + { SendMessage(NativeMethods.CCM_SETVERSION, 5, 0); } UpdateExtendedStyles(); RealizeProperties(); int color = ColorTranslator.ToWin32(BackColor); - SendMessage(NativeMethods.LVM_SETBKCOLOR,0,color); - SendMessage(NativeMethods.LVM_SETTEXTCOLOR,0,ColorTranslator.ToWin32(base.ForeColor)); + SendMessage(NativeMethods.LVM_SETBKCOLOR, 0, color); + SendMessage(NativeMethods.LVM_SETTEXTCOLOR, 0, ColorTranslator.ToWin32(base.ForeColor)); // The native list view will not invalidate the entire list view item area if the BkColor is not CLR_NONE. // This not noticeable if the customer paints the items w/ the same background color as the list view itself. // However, if the customer paints the items w/ a color different from the list view's back color // then when the user changes selection the native list view will not invalidate the entire list view item area. - SendMessage(NativeMethods.LVM_SETTEXTBKCOLOR, 0,NativeMethods.CLR_NONE); + SendMessage(NativeMethods.LVM_SETTEXTBKCOLOR, 0, NativeMethods.CLR_NONE); // LVS_NOSCROLL does not work well when the list view is in View.Details or in View.List modes. // we have to set this style after the list view was created and before we position the native list view items. // - if (!Scrollable) { + if (!Scrollable) + { int style = unchecked((int)((long)UnsafeNativeMethods.GetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_STYLE))); style |= NativeMethods.LVS_NOSCROLL; UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_STYLE, new HandleRef(null, (IntPtr)style)); } // in VirtualMode we have to tell the list view to ask for the list view item's state image index - if (VirtualMode) { - int callbackMask = unchecked( (int) (long)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_GETCALLBACKMASK, 0, 0)); + if (VirtualMode) + { + int callbackMask = unchecked((int)(long)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_GETCALLBACKMASK, 0, 0)); callbackMask |= NativeMethods.LVIS_STATEIMAGEMASK; UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_SETCALLBACKMASK, callbackMask, 0); } - if (ComctlSupportsVisualStyles) { - SendMessage(NativeMethods.LVM_SETVIEW,(int)viewStyle,0); + if (ComctlSupportsVisualStyles) + { + SendMessage(NativeMethods.LVM_SETVIEW, (int)viewStyle, 0); UpdateGroupView(); // Add groups // - if (groups != null) { - for(int index = 0;index < groups.Count;index++) { - InsertGroupNative(index,groups[index]); + if (groups != null) + { + for (int index = 0; index < groups.Count; index++) + { + InsertGroupNative(index, groups[index]); } } // Set tile view settings // - if (viewStyle == View.Tile) { + if (viewStyle == View.Tile) + { UpdateTileView(); } } @@ -3943,43 +4537,51 @@ protected override void OnHandleCreated(EventArgs e) { // Use a copy of the list items array so that we can maintain the (handle created || listItemsArray != null) invariant // ListViewItem[] listViewItemsToAdd = null; - if(listItemsArray != null) { + if (listItemsArray != null) + { listViewItemsToAdd = (ListViewItem[])listItemsArray.ToArray(typeof(ListViewItem)); listItemsArray = null; } int columnCount = (columnHeaders == null ? 0 : columnHeaders.Length); - if(columnCount > 0) { - int[] indices = new int [columnHeaders.Length]; + if (columnCount > 0) + { + int[] indices = new int[columnHeaders.Length]; int index = 0; - foreach(ColumnHeader column in columnHeaders) { + foreach (ColumnHeader column in columnHeaders) + { indices[index] = column.DisplayIndex; - InsertColumnNative(index++,column); + InsertColumnNative(index++, column); } - SetDisplayIndices( indices ); + SetDisplayIndices(indices); } // make sure that we're not in a begin/end update call. // - if (itemCount > 0 && listViewItemsToAdd != null) { + if (itemCount > 0 && listViewItemsToAdd != null) + { InsertItemsNative(0, listViewItemsToAdd); } - if (VirtualMode && VirtualListSize > -1 && !DesignMode) { + if (VirtualMode && VirtualListSize > -1 && !DesignMode) + { SendMessage(NativeMethods.LVM_SETITEMCOUNT, VirtualListSize, 0); } - if(columnCount > 0) { - UpdateColumnWidths(ColumnHeaderAutoResizeStyle.None); + if (columnCount > 0) + { + UpdateColumnWidths(ColumnHeaderAutoResizeStyle.None); } ArrangeIcons(alignStyle); UpdateListViewItemsLocations(); - if (!VirtualMode) { + if (!VirtualMode) + { Sort(); } - if (ComctlSupportsVisualStyles && (InsertionMark.Index > 0)) { + if (ComctlSupportsVisualStyles && (InsertionMark.Index > 0)) + { InsertionMark.UpdateListView(); } @@ -3988,9 +4590,12 @@ protected override void OnHandleCreated(EventArgs e) { // It is possible some checked items were added to the list view while its handle was null. // this.savedCheckedItems = null; - if (!this.CheckBoxes && !this.VirtualMode) { - for (int i = 0; i < this.Items.Count; i ++) { - if (this.Items[i].Checked) { + if (!this.CheckBoxes && !this.VirtualMode) + { + for (int i = 0; i < this.Items.Count; i++) + { + if (this.Items[i].Checked) + { this.UpdateSavedCheckedItems(this.Items[i], true /*addItem*/); } } @@ -3998,24 +4603,29 @@ protected override void OnHandleCreated(EventArgs e) { } - protected override void OnHandleDestroyed(EventArgs e) { + protected override void OnHandleDestroyed(EventArgs e) + { // don't save the list view items state when in virtual mode : it is the responsability of the // user to cache the list view items in virtual mode - if (!Disposing && !VirtualMode) { + if (!Disposing && !VirtualMode) + { int count = Items.Count; - for (int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) + { Items[i].UpdateStateFromListView(i, true); } // Save away the selected and checked items // - if (SelectedItems != null && !VirtualMode) { + if (SelectedItems != null && !VirtualMode) + { // Create an array because the SelectedItems collection is tuned for CopyTo() ListViewItem[] lviArr = new ListViewItem[SelectedItems.Count]; SelectedItems.CopyTo(lviArr, 0); savedSelectedItems = new List(lviArr.Length); - for (int i = 0; i < lviArr.Length; i ++) { + for (int i = 0; i < lviArr.Length; i++) + { savedSelectedItems.Add(lviArr[i]); } } @@ -4023,12 +4633,14 @@ protected override void OnHandleDestroyed(EventArgs e) { ListViewItem[] items = null; ListViewItemCollection tempItems = Items; - if (tempItems != null) { + if (tempItems != null) + { items = new ListViewItem[tempItems.Count]; tempItems.CopyTo(items, 0); } - if (items != null) { + if (items != null) + { listItemsArray = new ArrayList(items.Length); listItemsArray.AddRange(items); } @@ -4042,8 +4654,10 @@ protected override void OnHandleDestroyed(EventArgs e) { /// /// Fires the itemActivate event. /// - protected virtual void OnItemActivate(EventArgs e) { - if (onItemActivate != null) onItemActivate(this, e); + protected virtual void OnItemActivate(EventArgs e) + { + if (onItemActivate != null) + onItemActivate(this, e); } /// @@ -4051,53 +4665,66 @@ protected virtual void OnItemActivate(EventArgs e) { /// forget to call base.onItemCheck() to ensure that itemCheck vents /// are correctly fired for all other keys. /// - protected virtual void OnItemCheck(ItemCheckEventArgs ice) { - if (onItemCheck != null) { + protected virtual void OnItemCheck(ItemCheckEventArgs ice) + { + if (onItemCheck != null) + { onItemCheck(this, ice); } } - protected virtual void OnItemChecked(ItemCheckedEventArgs e) { - if (onItemChecked != null) { + protected virtual void OnItemChecked(ItemCheckedEventArgs e) + { + if (onItemChecked != null) + { onItemChecked(this, e); } } - protected virtual void OnItemDrag(ItemDragEventArgs e) { - if (onItemDrag != null) onItemDrag(this, e); + protected virtual void OnItemDrag(ItemDragEventArgs e) + { + if (onItemDrag != null) + onItemDrag(this, e); } /// /// Fires the ItemMouseHover event. /// - protected virtual void OnItemMouseHover(ListViewItemMouseHoverEventArgs e) { - if (onItemMouseHover != null) onItemMouseHover(this, e); + protected virtual void OnItemMouseHover(ListViewItemMouseHoverEventArgs e) + { + if (onItemMouseHover != null) + onItemMouseHover(this, e); } /// /// Fires the ItemSelectionChanged event. /// - protected virtual void OnItemSelectionChanged(ListViewItemSelectionChangedEventArgs e) { + protected virtual void OnItemSelectionChanged(ListViewItemSelectionChangedEventArgs e) + { ListViewItemSelectionChangedEventHandler eh = (ListViewItemSelectionChangedEventHandler)Events[EVENT_ITEMSELECTIONCHANGED]; if (eh != null) eh(this, e); } - protected override void OnParentChanged(EventArgs e) { + protected override void OnParentChanged(EventArgs e) + { base.OnParentChanged(e); // We must do this because the list view control caches the parent // handle and always sends notifications to the same handle. - if (IsHandleCreated) { + if (IsHandleCreated) + { RecreateHandleInternal(); } } /// /// - protected override void OnResize(EventArgs e) { + protected override void OnResize(EventArgs e) + { // If the list view is in Details mode and it is not Scrollable, we need to reposition the column header control. - if (this.View == View.Details && !this.Scrollable && this.IsHandleCreated) { + if (this.View == View.Details && !this.Scrollable && this.IsHandleCreated) + { PositionHeader(); } @@ -4106,26 +4733,31 @@ protected override void OnResize(EventArgs e) { /// /// - protected virtual void OnRetrieveVirtualItem(RetrieveVirtualItemEventArgs e) { - RetrieveVirtualItemEventHandler handler = (RetrieveVirtualItemEventHandler) Events[EVENT_RETRIEVEVIRTUALITEM]; + protected virtual void OnRetrieveVirtualItem(RetrieveVirtualItemEventArgs e) + { + RetrieveVirtualItemEventHandler handler = (RetrieveVirtualItemEventHandler)Events[EVENT_RETRIEVEVIRTUALITEM]; if (handler != null) handler(this, e); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnRightToLeftLayoutChanged(EventArgs e) { - if (GetAnyDisposingInHierarchy()) { + protected virtual void OnRightToLeftLayoutChanged(EventArgs e) + { + if (GetAnyDisposingInHierarchy()) + { return; } - if (RightToLeft == RightToLeft.Yes) { + if (RightToLeft == RightToLeft.Yes) + { RecreateHandleInternal(); } EventHandler eh = Events[EVENT_RIGHTTOLEFTLAYOUTCHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } @@ -4133,8 +4765,9 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) { /// /// Fires the search for virtual item event. /// - protected virtual void OnSearchForVirtualItem(SearchForVirtualItemEventArgs e) { - SearchForVirtualItemEventHandler handler = (SearchForVirtualItemEventHandler) Events[EVENT_SEARCHFORVIRTUALITEM]; + protected virtual void OnSearchForVirtualItem(SearchForVirtualItemEventArgs e) + { + SearchForVirtualItemEventHandler handler = (SearchForVirtualItemEventHandler)Events[EVENT_SEARCHFORVIRTUALITEM]; if (handler != null) handler(this, e); } @@ -4146,45 +4779,55 @@ protected virtual void OnSearchForVirtualItem(SearchForVirtualItemEventArgs e) { /// however, remember to call base.onSelectedIndexChanged(e); to ensure the event is /// still fired to external listeners /// - protected virtual void OnSelectedIndexChanged(EventArgs e) { + protected virtual void OnSelectedIndexChanged(EventArgs e) + { EventHandler handler = (EventHandler)Events[EVENT_SELECTEDINDEXCHANGED]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } - protected override void OnSystemColorsChanged(EventArgs e) { + protected override void OnSystemColorsChanged(EventArgs e) + { base.OnSystemColorsChanged(e); - if (IsHandleCreated) { + if (IsHandleCreated) + { int color = ColorTranslator.ToWin32(BackColor); - SendMessage(NativeMethods.LVM_SETBKCOLOR, 0,color); + SendMessage(NativeMethods.LVM_SETBKCOLOR, 0, color); // We should probably be OK if we don't set the TEXTBKCOLOR to CLR_NONE. // However, for the sake of being more robust, reset the TECTBKCOLOR to CLR_NONE when the system palette changes. - SendMessage(NativeMethods.LVM_SETTEXTBKCOLOR, 0,NativeMethods.CLR_NONE); + SendMessage(NativeMethods.LVM_SETTEXTBKCOLOR, 0, NativeMethods.CLR_NONE); } } - protected virtual void OnVirtualItemsSelectionRangeChanged(ListViewVirtualItemsSelectionRangeChangedEventArgs e) { - ListViewVirtualItemsSelectionRangeChangedEventHandler eh = (ListViewVirtualItemsSelectionRangeChangedEventHandler) Events[EVENT_VIRTUALITEMSSELECTIONRANGECHANGED]; + protected virtual void OnVirtualItemsSelectionRangeChanged(ListViewVirtualItemsSelectionRangeChangedEventArgs e) + { + ListViewVirtualItemsSelectionRangeChangedEventHandler eh = (ListViewVirtualItemsSelectionRangeChangedEventHandler)Events[EVENT_VIRTUALITEMSSELECTIONRANGECHANGED]; if (eh != null) eh(this, e); } - private unsafe void PositionHeader() { + private unsafe void PositionHeader() + { IntPtr hdrHWND = UnsafeNativeMethods.GetWindow(new HandleRef(this, this.Handle), NativeMethods.GW_CHILD); - if (hdrHWND != IntPtr.Zero) { + if (hdrHWND != IntPtr.Zero) + { - IntPtr prc = IntPtr.Zero; + IntPtr prc = IntPtr.Zero; IntPtr pwpos = IntPtr.Zero; prc = Marshal.AllocHGlobal(Marshal.SizeOf()); - if (prc == IntPtr.Zero) { + if (prc == IntPtr.Zero) + { return; } - try { + try + { pwpos = Marshal.AllocHGlobal(Marshal.SizeOf()); - if (prc == IntPtr.Zero) { + if (prc == IntPtr.Zero) + { // we could not allocate memory. // return return; @@ -4210,13 +4853,17 @@ private unsafe void PositionHeader() { wpos.cx, wpos.cy, wpos.flags | NativeMethods.SWP_SHOWWINDOW); - } finally { + } + finally + { // clean up our memory - if (prc != IntPtr.Zero) { + if (prc != IntPtr.Zero) + { Marshal.FreeHGlobal(prc); } - if (pwpos != IntPtr.Zero) { + if (pwpos != IntPtr.Zero) + { Marshal.FreeHGlobal(pwpos); } } @@ -4225,11 +4872,14 @@ private unsafe void PositionHeader() { /// /// - private void RealizeAllSubItems() { + private void RealizeAllSubItems() + { NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM(); - for (int i = 0; i < itemCount; i++) { + for (int i = 0; i < itemCount; i++) + { int subItemCount = Items[i].SubItems.Count; - for (int j = 0; j < subItemCount; j++) { + for (int j = 0; j < subItemCount; j++) + { SetItemText(i, j, Items[i].SubItems[j].Text, ref lvItem); } } @@ -4237,12 +4887,14 @@ private void RealizeAllSubItems() { /// /// - protected void RealizeProperties() { + protected void RealizeProperties() + { //Realize state information Color c; c = BackColor; - if (c != SystemColors.Window) { + if (c != SystemColors.Window) + { SendMessage(NativeMethods.LVM_SETBKCOLOR, 0, ColorTranslator.ToWin32(c)); } c = ForeColor; @@ -4256,7 +4908,8 @@ protected void RealizeProperties() { if (null != imageListSmall) SendMessage(NativeMethods.LVM_SETIMAGELIST, NativeMethods.LVSIL_SMALL, imageListSmall.Handle); - if (null != imageListState) { + if (null != imageListState) + { SendMessage(NativeMethods.LVM_SETIMAGELIST, NativeMethods.LVSIL_STATE, imageListState.Handle); } } @@ -4295,7 +4948,7 @@ public void RedrawItems(int startIndex, int endIndex, bool invalidateOnly) } if (this.IsHandleCreated) { - int retval = (int) UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), + int retval = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_REDRAWITEMS, startIndex, endIndex); Debug.Assert(retval != 0); @@ -4303,7 +4956,7 @@ public void RedrawItems(int startIndex, int endIndex, bool invalidateOnly) if (this.View == View.LargeIcon || this.View == View.SmallIcon) { Rectangle rectInvalid = this.Items[startIndex].Bounds; - for (int index = startIndex+1; index <= endIndex; index++) + for (int index = startIndex + 1; index <= endIndex; index++) { rectInvalid = Rectangle.Union(rectInvalid, this.Items[index].Bounds); } @@ -4341,36 +4994,42 @@ public void RedrawItems(int startIndex, int endIndex, bool invalidateOnly) // makes sure that the list view items which are w/o a listView group are parented to the DefaultGroup - if necessary // and then tell win32 to remove this group - internal void RemoveGroupFromListView(ListViewGroup group) { - EnsureDefaultGroup(); + internal void RemoveGroupFromListView(ListViewGroup group) + { + EnsureDefaultGroup(); - foreach(ListViewItem item in group.Items) { - if(item.ListView == this) { - item.UpdateStateToListView(item.Index); - } - } + foreach (ListViewItem item in group.Items) + { + if (item.ListView == this) + { + item.UpdateStateToListView(item.Index); + } + } - RemoveGroupNative(group); + RemoveGroupNative(group); - UpdateGroupView(); + UpdateGroupView(); } // does the job of telling win32 listView to remove this group - private void RemoveGroupNative(ListViewGroup group) { - Debug.Assert(IsHandleCreated,"RemoveGroupNative precondition: list-view handle must be created"); - int retval = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_REMOVEGROUP, group.ID, IntPtr.Zero); + private void RemoveGroupNative(ListViewGroup group) + { + Debug.Assert(IsHandleCreated, "RemoveGroupNative precondition: list-view handle must be created"); + int retval = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_REMOVEGROUP, group.ID, IntPtr.Zero); - // it is the job of whoever deletes this group to also turn off grouping if this was the last - // group deleted - return; - } + // it is the job of whoever deletes this group to also turn off grouping if this was the last + // group deleted + return; + } - private void Scroll(int fromLVItem, int toLVItem) { + private void Scroll(int fromLVItem, int toLVItem) + { int scrollY = GetItemPosition(toLVItem).Y - GetItemPosition(fromLVItem).Y; UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_SCROLL, 0, scrollY); } - private void SetBackgroundImage() { + private void SetBackgroundImage() + { // needed for OleInitialize Application.OleRequired(); @@ -4382,7 +5041,8 @@ private void SetBackgroundImage() { // so that we can delete it if the list control doesn't... string fileNameToDelete = this.backgroundImageFileName; - if (this.BackgroundImage != null) { + if (this.BackgroundImage != null) + { // save the image to a temporary file name string tempDirName = System.IO.Path.GetTempPath(); @@ -4401,14 +5061,17 @@ private void SetBackgroundImage() { else lvbkImage.ulFlags |= NativeMethods.LVBKIF_STYLE_NORMAL; - } else { + } + else + { lvbkImage.ulFlags = NativeMethods.LVBKIF_SOURCE_NONE; this.backgroundImageFileName = string.Empty; } UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_SETBKIMAGE, 0, lvbkImage); - if (string.IsNullOrEmpty(fileNameToDelete)) { + if (string.IsNullOrEmpty(fileNameToDelete)) + { return; } @@ -4417,12 +5080,14 @@ private void SetBackgroundImage() { // // 8 strings should be good enough for us - if (this.bkImgFileNames == null) { + if (this.bkImgFileNames == null) + { this.bkImgFileNames = new string[BKIMGARRAYSIZE]; this.bkImgFileNamesCount = -1; } - if (this.bkImgFileNamesCount == BKIMGARRAYSIZE - 1) { + if (this.bkImgFileNamesCount == BKIMGARRAYSIZE - 1) + { // it should be fine to delete the file name that was added first. // if it's not fine, then increase BKIMGARRAYSIZE this.DeleteFileName(this.bkImgFileNames[0]); @@ -4435,10 +5100,10 @@ private void SetBackgroundImage() { this.bkImgFileNames[6] = this.bkImgFileNames[7]; this.bkImgFileNames[7] = null; - this.bkImgFileNamesCount --; + this.bkImgFileNamesCount--; } - this.bkImgFileNamesCount ++; + this.bkImgFileNamesCount++; this.bkImgFileNames[this.bkImgFileNamesCount] = fileNameToDelete; // now force the paint @@ -4447,34 +5112,40 @@ private void SetBackgroundImage() { /// /// - internal void SetColumnInfo(int mask, ColumnHeader ch) { - if (IsHandleCreated) { + internal void SetColumnInfo(int mask, ColumnHeader ch) + { + if (IsHandleCreated) + { Debug.Assert((mask & ~(NativeMethods.LVCF_FMT | NativeMethods.LVCF_TEXT | NativeMethods.LVCF_IMAGE)) == 0, "Unsupported mask in setColumnInfo"); NativeMethods.LVCOLUMN lvColumn = new NativeMethods.LVCOLUMN(); - lvColumn.mask = mask; + lvColumn.mask = mask; - if ((mask & NativeMethods.LVCF_IMAGE) != 0 || (mask & NativeMethods.LVCF_FMT) != 0) { + if ((mask & NativeMethods.LVCF_IMAGE) != 0 || (mask & NativeMethods.LVCF_FMT) != 0) + { // When we set the ImageIndex we also have to alter the column format. // This means that we have to include the TextAlign into the column format. lvColumn.mask |= NativeMethods.LVCF_FMT; - if (ch.ActualImageIndex_Internal > -1) { + if (ch.ActualImageIndex_Internal > -1) + { // you would think that setting iImage would be enough. // actually we also have to set the format to include LVCFMT_IMAGE lvColumn.iImage = ch.ActualImageIndex_Internal; lvColumn.fmt |= NativeMethods.LVCFMT_IMAGE; } - lvColumn.fmt |= (int) ch.TextAlign; + lvColumn.fmt |= (int)ch.TextAlign; } - if ((mask & NativeMethods.LVCF_TEXT) != 0) { - lvColumn.pszText = Marshal.StringToHGlobalAuto(ch.Text); + if ((mask & NativeMethods.LVCF_TEXT) != 0) + { + lvColumn.pszText = Marshal.StringToHGlobalAuto(ch.Text); } int retval = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SETCOLUMN, ch.Index, lvColumn); - if ((mask & NativeMethods.LVCF_TEXT) != 0) { + if ((mask & NativeMethods.LVCF_TEXT) != 0) + { Marshal.FreeHGlobal(lvColumn.pszText); } @@ -4490,10 +5161,12 @@ internal void SetColumnInfo(int mask, ColumnHeader ch) { /// Setting width is a special case 'cuz LVM_SETCOLUMNWIDTH accepts more values /// for width than LVM_SETCOLUMN does. /// - internal void SetColumnWidth(int columnIndex, ColumnHeaderAutoResizeStyle headerAutoResize) { + internal void SetColumnWidth(int columnIndex, ColumnHeaderAutoResizeStyle headerAutoResize) + { if ((columnIndex < 0) || (columnIndex >= 0 && this.columnHeaders == null) || - (columnIndex >= this.columnHeaders.Length)) { + (columnIndex >= this.columnHeaders.Length)) + { throw new ArgumentOutOfRangeException(nameof(columnIndex), columnIndex, string.Format(SR.InvalidArgument, nameof(columnIndex), columnIndex)); } @@ -4507,58 +5180,73 @@ internal void SetColumnWidth(int columnIndex, ColumnHeaderAutoResizeStyle header int width = 0; int compensate = 0; - if (headerAutoResize == ColumnHeaderAutoResizeStyle.None) { + if (headerAutoResize == ColumnHeaderAutoResizeStyle.None) + { width = this.columnHeaders[columnIndex].WidthInternal; // If the width maps to a LVCSW_ const, then native control will autoresize. // We may need to compensate for that. - if (width == NativeMethods.LVSCW_AUTOSIZE_USEHEADER) { + if (width == NativeMethods.LVSCW_AUTOSIZE_USEHEADER) + { headerAutoResize = ColumnHeaderAutoResizeStyle.HeaderSize; - } else if (width == NativeMethods.LVSCW_AUTOSIZE) { + } + else if (width == NativeMethods.LVSCW_AUTOSIZE) + { headerAutoResize = ColumnHeaderAutoResizeStyle.ColumnContent; } } - if (headerAutoResize == ColumnHeaderAutoResizeStyle.HeaderSize) { + if (headerAutoResize == ColumnHeaderAutoResizeStyle.HeaderSize) + { compensate = this.CompensateColumnHeaderResize(columnIndex, false /*columnHeaderResizeCancelled*/); width = NativeMethods.LVSCW_AUTOSIZE_USEHEADER; - } else if (headerAutoResize == ColumnHeaderAutoResizeStyle.ColumnContent) { + } + else if (headerAutoResize == ColumnHeaderAutoResizeStyle.ColumnContent) + { compensate = this.CompensateColumnHeaderResize(columnIndex, false /*columnHeaderResizeCancelled*/); width = NativeMethods.LVSCW_AUTOSIZE; } - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(NativeMethods.LVM_SETCOLUMNWIDTH, columnIndex, NativeMethods.Util.MAKELPARAM(width, 0)); } if (this.IsHandleCreated && (headerAutoResize == ColumnHeaderAutoResizeStyle.ColumnContent || - headerAutoResize == ColumnHeaderAutoResizeStyle.HeaderSize)) { - if (compensate != 0) { + headerAutoResize == ColumnHeaderAutoResizeStyle.HeaderSize)) + { + if (compensate != 0) + { int newWidth = this.columnHeaders[columnIndex].Width + compensate; SendMessage(NativeMethods.LVM_SETCOLUMNWIDTH, columnIndex, NativeMethods.Util.MAKELPARAM(newWidth, 0)); } } } - private void SetColumnWidth(int index, int width) { - if (IsHandleCreated) { - SendMessage(NativeMethods.LVM_SETCOLUMNWIDTH, index, NativeMethods.Util.MAKELPARAM(width,0)); + private void SetColumnWidth(int index, int width) + { + if (IsHandleCreated) + { + SendMessage(NativeMethods.LVM_SETCOLUMNWIDTH, index, NativeMethods.Util.MAKELPARAM(width, 0)); } } // set the display indices of the listview columns - private void SetDisplayIndices(int[] indices) { + private void SetDisplayIndices(int[] indices) + { - int[] orderedColumns = new int[ indices.Length ]; - for (int i=0; i @@ -4568,17 +5256,21 @@ private void SetDisplayIndices(int[] indices) { /// internal void UpdateSavedCheckedItems(ListViewItem item, bool addItem) { - if (addItem && this.savedCheckedItems == null) { + if (addItem && this.savedCheckedItems == null) + { this.savedCheckedItems = new List(); } - if (addItem) { + if (addItem) + { this.savedCheckedItems.Add(item); - } else if (this.savedCheckedItems != null) { + } + else if (this.savedCheckedItems != null) + { Debug.Assert(this.savedCheckedItems.Contains(item), "somehow we lost track of one item"); this.savedCheckedItems.Remove(item); } - #if FALSE +#if FALSE if (savedCheckedItems != null && savedCheckedItems.Length > 0) { ListViewItem[] newSavedCheckedItems; int index = 0; @@ -4608,24 +5300,28 @@ internal void UpdateSavedCheckedItems(ListViewItem item, bool addItem) savedCheckedItems = new ListViewItem[1]; savedCheckedItems[0] = item; } - #endif // FALSE +#endif // FALSE } /// /// Called by ToolTip to poke in that Tooltip into this ComCtl so that the Native ChildToolTip is not exposed. /// - internal void SetToolTip(ToolTip toolTip, string toolTipCaption) { + internal void SetToolTip(ToolTip toolTip, string toolTipCaption) + { this.toolTipCaption = toolTipCaption; //native ListView expects tooltip HWND as a wParam and ignores lParam IntPtr oldHandle = UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_SETTOOLTIPS, new HandleRef(toolTip, toolTip.Handle), 0); UnsafeNativeMethods.DestroyWindow(new HandleRef(null, oldHandle)); } - internal void SetItemImage(int index, int image) { - if (index < 0 || ((this.VirtualMode && index >= this.VirtualListSize) || (!this.VirtualMode && index >= itemCount))) { + internal void SetItemImage(int index, int image) + { + if (index < 0 || ((this.VirtualMode && index >= this.VirtualListSize) || (!this.VirtualMode && index >= itemCount))) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - if (this.IsHandleCreated) { + if (this.IsHandleCreated) + { NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM(); lvItem.mask = NativeMethods.LVIF_IMAGE; lvItem.iItem = index; @@ -4634,11 +5330,14 @@ internal void SetItemImage(int index, int image) { } } - internal void SetItemIndentCount(int index, int indentCount) { - if (index < 0 || ((this.VirtualMode && index >= this.VirtualListSize) || (!this.VirtualMode && index >= itemCount))) { + internal void SetItemIndentCount(int index, int indentCount) + { + if (index < 0 || ((this.VirtualMode && index >= this.VirtualListSize) || (!this.VirtualMode && index >= itemCount))) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - if (this.IsHandleCreated) { + if (this.IsHandleCreated) + { NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM(); lvItem.mask = NativeMethods.LVIF_INDENT; lvItem.iItem = index; @@ -4647,7 +5346,8 @@ internal void SetItemIndentCount(int index, int indentCount) { } } - internal void SetItemPosition(int index, int x, int y) { + internal void SetItemPosition(int index, int x, int y) + { if (VirtualMode) return; if (index < 0 || index >= itemCount) @@ -4661,13 +5361,16 @@ internal void SetItemPosition(int index, int x, int y) { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SETITEMPOSITION32, index, pt); } - internal void SetItemState(int index, int state, int mask) { - if (index < -1 || ((this.VirtualMode && index >= this.VirtualListSize) || (!this.VirtualMode && index >= itemCount))) { + internal void SetItemState(int index, int state, int mask) + { + if (index < -1 || ((this.VirtualMode && index >= this.VirtualListSize) || (!this.VirtualMode && index >= itemCount))) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } Debug.Assert(index == -1 || this.IsHandleCreated, "How did we add items without a handle?"); - if (this.IsHandleCreated) { + if (this.IsHandleCreated) + { NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM(); lvItem.mask = NativeMethods.LVIF_STATE; lvItem.state = state; @@ -4676,43 +5379,49 @@ internal void SetItemState(int index, int state, int mask) { } } - internal void SetItemText(int itemIndex, int subItemIndex, string text) { + internal void SetItemText(int itemIndex, int subItemIndex, string text) + { - NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM(); + NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM(); SetItemText(itemIndex, subItemIndex, text, ref lvItem); } /// /// For perf, allow a LVITEM to be passed in so we can reuse in tight loops. /// - private void SetItemText(int itemIndex, int subItemIndex, string text, ref NativeMethods.LVITEM lvItem) { + private void SetItemText(int itemIndex, int subItemIndex, string text, ref NativeMethods.LVITEM lvItem) + { Debug.Assert(IsHandleCreated, "SetItemText with no handle"); // - if (this.View == View.List && subItemIndex == 0) { - int colWidth = unchecked( (int) (long)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_GETCOLUMNWIDTH, 0, 0)); + if (this.View == View.List && subItemIndex == 0) + { + int colWidth = unchecked((int)(long)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_GETCOLUMNWIDTH, 0, 0)); Graphics g = this.CreateGraphicsInternal(); int textWidth = 0; - try { + try + { textWidth = Size.Ceiling(g.MeasureString(text, this.Font)).Width; } - finally { + finally + { g.Dispose(); } - if (textWidth > colWidth) { + if (textWidth > colWidth) + { SetColumnWidth(0, textWidth); } } lvItem.mask = NativeMethods.LVIF_TEXT; - lvItem.iItem = itemIndex; + lvItem.iItem = itemIndex; lvItem.iSubItem = subItemIndex; - lvItem.pszText = text; + lvItem.pszText = text; UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SETITEMTEXT, itemIndex, ref lvItem); } @@ -4724,17 +5433,21 @@ private void SetItemText(int itemIndex, int subItemIndex, string text, ref Nativ // its selection mark. // So we explicitly set the selection mark. // - internal void SetSelectionMark(int itemIndex) { - if (itemIndex < 0 || itemIndex >= this.Items.Count) { + internal void SetSelectionMark(int itemIndex) + { + if (itemIndex < 0 || itemIndex >= this.Items.Count) + { return; } SendMessage(NativeMethods.LVM_SETSELECTIONMARK, 0, itemIndex); } - private void SmallImageListRecreateHandle(object sender, EventArgs e) { - if (IsHandleCreated) { + private void SmallImageListRecreateHandle(object sender, EventArgs e) + { + if (IsHandleCreated) + { IntPtr handle = (SmallImageList == null) ? IntPtr.Zero : SmallImageList.Handle; - SendMessage(NativeMethods.LVM_SETIMAGELIST, (IntPtr) NativeMethods.LVSIL_SMALL, handle); + SendMessage(NativeMethods.LVM_SETIMAGELIST, (IntPtr)NativeMethods.LVSIL_SMALL, handle); ForceCheckBoxUpdate(); } @@ -4743,48 +5456,59 @@ private void SmallImageListRecreateHandle(object sender, EventArgs e) { /// /// Updated the sorted order /// - public void Sort() { - if (VirtualMode) { + public void Sort() + { + if (VirtualMode) + { throw new InvalidOperationException(SR.ListViewSortNotAllowedInVirtualListView); } ApplyUpdateCachedItems(); - if (IsHandleCreated && listItemSorter != null) { + if (IsHandleCreated && listItemSorter != null) + { NativeMethods.ListViewCompareCallback callback = new NativeMethods.ListViewCompareCallback(this.CompareFunc); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SORTITEMS, IntPtr.Zero, callback); } } - private void StateImageListRecreateHandle(object sender, EventArgs e) { - if (IsHandleCreated) { + private void StateImageListRecreateHandle(object sender, EventArgs e) + { + if (IsHandleCreated) + { IntPtr handle = IntPtr.Zero; - if (StateImageList != null) { + if (StateImageList != null) + { handle = imageListState.Handle; } - SendMessage(NativeMethods.LVM_SETIMAGELIST, (IntPtr) NativeMethods.LVSIL_STATE, handle); + SendMessage(NativeMethods.LVM_SETIMAGELIST, (IntPtr)NativeMethods.LVSIL_STATE, handle); } } /// /// Returns a string representation for this control. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); - if (listItemsArray != null) { + if (listItemsArray != null) + { s += ", Items.Count: " + listItemsArray.Count.ToString(CultureInfo.CurrentCulture); - if (listItemsArray.Count > 0) { + if (listItemsArray.Count > 0) + { string z = listItemsArray[0].ToString(); string txt = (z.Length > 40) ? z.Substring(0, 40) : z; s += ", Items[0]: " + txt; } } - else if (Items != null) { + else if (Items != null) + { s += ", Items.Count: " + Items.Count.ToString(CultureInfo.CurrentCulture); - if (Items.Count > 0 && !VirtualMode) { + if (Items.Count > 0 && !VirtualMode) + { //Debug.Assert(Items[0] != null, "Why is there a null item in the list view item collection?"); - string z = (Items[0] == null) ? "null" : Items[0].ToString(); + string z = (Items[0] == null) ? "null" : Items[0].ToString(); string txt = (z.Length > 40) ? z.Substring(0, 40) : z; s += ", Items[0]: " + txt; } @@ -4793,12 +5517,15 @@ public override string ToString() { return s; } - internal void UpdateListViewItemsLocations() { - if (!VirtualMode && IsHandleCreated && AutoArrange && (View == View.LargeIcon || View == View.SmallIcon)) { + internal void UpdateListViewItemsLocations() + { + if (!VirtualMode && IsHandleCreated && AutoArrange && (View == View.LargeIcon || View == View.SmallIcon)) + { // this only has an affect for large icon and small icon views. // - try { + try + { BeginUpdate(); /* Not sure this does anything that just calling the function doesn't... @@ -4808,24 +5535,30 @@ Not sure this does anything that just calling the function doesn't... } */ SendMessage(NativeMethods.LVM_UPDATE, -1, 0); } - finally { + finally + { EndUpdate(); } } } - private void UpdateColumnWidths(ColumnHeaderAutoResizeStyle headerAutoResize) { - if (columnHeaders != null) { - for (int i = 0; i < this.columnHeaders.Length; i ++) { + private void UpdateColumnWidths(ColumnHeaderAutoResizeStyle headerAutoResize) + { + if (columnHeaders != null) + { + for (int i = 0; i < this.columnHeaders.Length; i++) + { SetColumnWidth(i, headerAutoResize); } } } - protected void UpdateExtendedStyles() { + protected void UpdateExtendedStyles() + { - if (IsHandleCreated) { + if (IsHandleCreated) + { int exStyle = 0; int exMask = NativeMethods.LVS_EX_ONECLICKACTIVATE | NativeMethods.LVS_EX_TWOCLICKACTIVATE | NativeMethods.LVS_EX_TRACKSELECT | NativeMethods.LVS_EX_UNDERLINEHOT | NativeMethods.LVS_EX_ONECLICKACTIVATE | @@ -4833,7 +5566,8 @@ protected void UpdateExtendedStyles() { NativeMethods.LVS_EX_FULLROWSELECT | NativeMethods.LVS_EX_GRIDLINES | NativeMethods.LVS_EX_INFOTIP | NativeMethods.LVS_EX_DOUBLEBUFFER; - switch (activation) { + switch (activation) + { case ItemActivation.OneClick: exStyle |= NativeMethods.LVS_EX_ONECLICKACTIVATE; break; @@ -4871,11 +5605,13 @@ protected void UpdateExtendedStyles() { } } - internal void UpdateGroupNative(ListViewGroup group) { - Debug.Assert(IsHandleCreated,"UpdateGroupNative precondition: list-view handle must be created"); + internal void UpdateGroupNative(ListViewGroup group) + { + Debug.Assert(IsHandleCreated, "UpdateGroupNative precondition: list-view handle must be created"); NativeMethods.LVGROUP lvgroup = new NativeMethods.LVGROUP(); - try { + try + { lvgroup = GetLVGROUP(group); int retval = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_SETGROUPINFO, @@ -4894,15 +5630,18 @@ internal void UpdateGroupNative(ListViewGroup group) { // ListViewGroupCollection::Clear needs to remove the items from the Default group // - internal void UpdateGroupView() { - if (IsHandleCreated && ComctlSupportsVisualStyles && !VirtualMode) { - int retval = unchecked( (int) (long)SendMessage(NativeMethods.LVM_ENABLEGROUPVIEW, GroupsEnabled ? 1 : 0, 0)); + internal void UpdateGroupView() + { + if (IsHandleCreated && ComctlSupportsVisualStyles && !VirtualMode) + { + int retval = unchecked((int)(long)SendMessage(NativeMethods.LVM_ENABLEGROUPVIEW, GroupsEnabled ? 1 : 0, 0)); Debug.Assert(retval != -1, "Error enabling group view"); } } // updates the win32 list view w/ our tile info - columns + tile size - private void UpdateTileView() { + private void UpdateTileView() + { Debug.Assert(ComctlSupportsVisualStyles, "this function works only when ComCtl 6.0 and higher is loaded"); Debug.Assert(this.viewStyle == View.Tile, "this function should be called only in Tile view"); NativeMethods.LVTILEVIEWINFO tileViewInfo = new NativeMethods.LVTILEVIEWINFO(); @@ -4915,16 +5654,18 @@ private void UpdateTileView() { tileViewInfo.dwFlags = NativeMethods.LVTVIF_FIXEDSIZE; tileViewInfo.sizeTile = new NativeMethods.SIZE(this.TileSize.Width, this.TileSize.Height); - bool retval = UnsafeNativeMethods.SendMessage(new HandleRef(this,Handle),NativeMethods.LVM_SETTILEVIEWINFO,0,tileViewInfo); - Debug.Assert(retval,"LVM_SETTILEVIEWINFO failed"); + bool retval = UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SETTILEVIEWINFO, 0, tileViewInfo); + Debug.Assert(retval, "LVM_SETTILEVIEWINFO failed"); } - private void WmNmClick(ref Message m) { + private void WmNmClick(ref Message m) + { // If we're checked, hittest to see if we're // on the check mark - if (CheckBoxes) { + if (CheckBoxes) + { Point pos = Cursor.Position; pos = PointToClient(pos); NativeMethods.LVHITTESTINFO lvhi = new NativeMethods.LVHITTESTINFO(); @@ -4933,13 +5674,18 @@ private void WmNmClick(ref Message m) { lvhi.pt_y = pos.Y; int displayIndex = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_HITTEST, 0, lvhi); - if (displayIndex != -1 && (lvhi.flags & NativeMethods.LVHT_ONITEMSTATEICON) != 0) { + if (displayIndex != -1 && (lvhi.flags & NativeMethods.LVHT_ONITEMSTATEICON) != 0) + { ListViewItem clickedItem = Items[displayIndex]; - if (clickedItem.Selected) { + if (clickedItem.Selected) + { bool check = !clickedItem.Checked; - if (!VirtualMode) { - foreach(ListViewItem item in SelectedItems) { - if (item != clickedItem) { + if (!VirtualMode) + { + foreach (ListViewItem item in SelectedItems) + { + if (item != clickedItem) + { item.Checked = check; } } @@ -4949,12 +5695,14 @@ private void WmNmClick(ref Message m) { } } - private void WmNmDblClick(ref Message m) { + private void WmNmDblClick(ref Message m) + { // If we're checked, hittest to see if we're // on the item - if (CheckBoxes) { + if (CheckBoxes) + { Point pos = Cursor.Position; pos = PointToClient(pos); NativeMethods.LVHITTESTINFO lvhi = new NativeMethods.LVHITTESTINFO(); @@ -4963,14 +5711,16 @@ private void WmNmDblClick(ref Message m) { lvhi.pt_y = pos.Y; int displayIndex = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_HITTEST, 0, lvhi); - if (displayIndex != -1 && (lvhi.flags & NativeMethods.LVHT_ONITEM) != 0) { + if (displayIndex != -1 && (lvhi.flags & NativeMethods.LVHT_ONITEM) != 0) + { ListViewItem clickedItem = Items[displayIndex]; clickedItem.Checked = !clickedItem.Checked; } } } - private void WmMouseDown(ref Message m, MouseButtons button, int clicks) { + private void WmMouseDown(ref Message m, MouseButtons button, int clicks) + { //Always Reset the MouseupFired.... listViewState[LISTVIEWSTATE_mouseUpFired] = false; @@ -4987,21 +5737,27 @@ private void WmMouseDown(ref Message m, MouseButtons button, int clicks) { OnMouseDown(new MouseEventArgs(button, clicks, x, y, 0)); //If Validation is cancelled dont fire any events through the Windows ListView's message loop... - if (!ValidationCancelled) { + if (!ValidationCancelled) + { - if (CheckBoxes) { + if (CheckBoxes) + { ListViewHitTestInfo lvhti = this.HitTest(x, y); - if (imageListState != null && imageListState.Images.Count < 2) { + if (imageListState != null && imageListState.Images.Count < 2) + { // When the user clicks on the check box and the listView's state image list // does not have 2 images, comctl will give us an AttemptToDivideByZero exception. // So don't send the message to DefWndProc in this situation. - if (lvhti.Location != ListViewHitTestLocations.StateImage) { + if (lvhti.Location != ListViewHitTestLocations.StateImage) + { DefWndProc(ref m); } } - else { + else + { // When a user clicks on the state image, focus the item. - if (lvhti.Item != null && lvhti.Location == ListViewHitTestLocations.StateImage) { + if (lvhti.Item != null && lvhti.Location == ListViewHitTestLocations.StateImage) + { lvhti.Item.Focused = true; } DefWndProc(ref m); @@ -5015,7 +5771,8 @@ private void WmMouseDown(ref Message m, MouseButtons button, int clicks) { } - private unsafe bool WmNotify(ref Message m) { + private unsafe bool WmNotify(ref Message m) + { NativeMethods.NMHDR* nmhdr = (NativeMethods.NMHDR*)m.LParam; // column header custom draw message handling @@ -5063,7 +5820,7 @@ private unsafe bool WmNotify(ref Message m) { } else { - + m.Result = (IntPtr)(NativeMethods.CDRF_SKIPDEFAULT); return true; // we are done - don't do default handling } @@ -5081,49 +5838,58 @@ private unsafe bool WmNotify(ref Message m) { } - if (nmhdr->code == NativeMethods.NM_RELEASEDCAPTURE && listViewState[LISTVIEWSTATE_columnClicked]) { + if (nmhdr->code == NativeMethods.NM_RELEASEDCAPTURE && listViewState[LISTVIEWSTATE_columnClicked]) + { listViewState[LISTVIEWSTATE_columnClicked] = false; OnColumnClick(new ColumnClickEventArgs(columnIndex)); } - if (nmhdr->code == NativeMethods.HDN_BEGINTRACK) { - this.listViewState[LISTVIEWSTATE_headerControlTracking] = true; + if (nmhdr->code == NativeMethods.HDN_BEGINTRACK) + { + this.listViewState[LISTVIEWSTATE_headerControlTracking] = true; - // Reset our tracking information for the new BEGINTRACK cycle. - this.listViewState1[LISTVIEWSTATE1_cancelledColumnWidthChanging] = false; - this.newWidthForColumnWidthChangingCancelled = -1; - this.listViewState1[LISTVIEWSTATE1_cancelledColumnWidthChanging] = false; + // Reset our tracking information for the new BEGINTRACK cycle. + this.listViewState1[LISTVIEWSTATE1_cancelledColumnWidthChanging] = false; + this.newWidthForColumnWidthChangingCancelled = -1; + this.listViewState1[LISTVIEWSTATE1_cancelledColumnWidthChanging] = false; - NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER) m.GetLParam(typeof(NativeMethods.NMHEADER)); - if (this.columnHeaders != null && this.columnHeaders.Length > nmheader.iItem) { - this.columnHeaderClicked = this.columnHeaders[nmheader.iItem]; - this.columnHeaderClickedWidth = this.columnHeaderClicked.Width; - } else { - this.columnHeaderClickedWidth = -1; - this.columnHeaderClicked = null; - } + NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER)m.GetLParam(typeof(NativeMethods.NMHEADER)); + if (this.columnHeaders != null && this.columnHeaders.Length > nmheader.iItem) + { + this.columnHeaderClicked = this.columnHeaders[nmheader.iItem]; + this.columnHeaderClickedWidth = this.columnHeaderClicked.Width; + } + else + { + this.columnHeaderClickedWidth = -1; + this.columnHeaderClicked = null; + } } - if (nmhdr->code == NativeMethods.HDN_ITEMCHANGING) { - NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER) m.GetLParam(typeof(NativeMethods.NMHEADER)); + if (nmhdr->code == NativeMethods.HDN_ITEMCHANGING) + { + NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER)m.GetLParam(typeof(NativeMethods.NMHEADER)); if (columnHeaders != null && nmheader.iItem < columnHeaders.Length && - (this.listViewState[LISTVIEWSTATE_headerControlTracking] || this.listViewState[LISTVIEWSTATE_headerDividerDblClick])) { + (this.listViewState[LISTVIEWSTATE_headerControlTracking] || this.listViewState[LISTVIEWSTATE_headerDividerDblClick])) + { // - NativeMethods.HDITEM2 hdItem = Marshal.PtrToStructure((IntPtr) nmheader.pItem); + NativeMethods.HDITEM2 hdItem = Marshal.PtrToStructure((IntPtr)nmheader.pItem); int newColumnWidth = ((hdItem.mask & NativeMethods.HDI_WIDTH) != 0) ? hdItem.cxy : -1; ColumnWidthChangingEventArgs colWidthChanging = new ColumnWidthChangingEventArgs(nmheader.iItem, newColumnWidth); OnColumnWidthChanging(colWidthChanging); - m.Result = (IntPtr) (colWidthChanging.Cancel ? 1 : 0); - if (colWidthChanging.Cancel) { + m.Result = (IntPtr)(colWidthChanging.Cancel ? 1 : 0); + if (colWidthChanging.Cancel) + { hdItem.cxy = colWidthChanging.NewWidth; // We are called inside HDN_DIVIDERDBLCLICK. // Turn off the compensation that our processing of HDN_DIVIDERDBLCLICK would otherwise add. - if (this.listViewState[LISTVIEWSTATE_headerDividerDblClick]) { + if (this.listViewState[LISTVIEWSTATE_headerDividerDblClick]) + { this.listViewState[LISTVIEWSTATE_columnResizeCancelled] = true; } @@ -5132,32 +5898,41 @@ private unsafe bool WmNotify(ref Message m) { // skip default processing return true; - } else { + } + else + { return false; } } } if ((nmhdr->code == NativeMethods.HDN_ITEMCHANGED) && - !this.listViewState[LISTVIEWSTATE_headerControlTracking]) { + !this.listViewState[LISTVIEWSTATE_headerControlTracking]) + { NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER)m.GetLParam(typeof(NativeMethods.NMHEADER)); - if (columnHeaders != null && nmheader.iItem < columnHeaders.Length) { + if (columnHeaders != null && nmheader.iItem < columnHeaders.Length) + { int w = columnHeaders[nmheader.iItem].Width; if (this.columnHeaderClicked == null || (this.columnHeaderClicked == this.columnHeaders[nmheader.iItem] && this.columnHeaderClickedWidth != -1 && - this.columnHeaderClickedWidth != w)) { + this.columnHeaderClickedWidth != w)) + { // // If the user double clicked on the column header and we still need to compensate for the column resize // then don't fire ColumnWidthChanged because at this point the column header does not have the final width. // - if (this.listViewState[LISTVIEWSTATE_headerDividerDblClick]) { - if (this.CompensateColumnHeaderResize(m, this.listViewState[LISTVIEWSTATE_columnResizeCancelled]) == 0) { + if (this.listViewState[LISTVIEWSTATE_headerDividerDblClick]) + { + if (this.CompensateColumnHeaderResize(m, this.listViewState[LISTVIEWSTATE_columnResizeCancelled]) == 0) + { OnColumnWidthChanged(new ColumnWidthChangedEventArgs(nmheader.iItem)); } - } else { + } + else + { OnColumnWidthChanged(new ColumnWidthChangedEventArgs(nmheader.iItem)); } @@ -5169,14 +5944,19 @@ private unsafe bool WmNotify(ref Message m) { ISite site = Site; - if (site != null) { + if (site != null) + { IComponentChangeService cs = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); - if (cs != null) { - try { + if (cs != null) + { + try + { cs.OnComponentChanging(this, null); } - catch (CheckoutException coEx) { - if (coEx == CheckoutException.Canceled) { + catch (CheckoutException coEx) + { + if (coEx == CheckoutException.Canceled) + { return false; } throw coEx; @@ -5185,14 +5965,18 @@ private unsafe bool WmNotify(ref Message m) { } } - if (nmhdr->code == NativeMethods.HDN_ENDTRACK) { + if (nmhdr->code == NativeMethods.HDN_ENDTRACK) + { Debug.Assert(this.listViewState[LISTVIEWSTATE_headerControlTracking], "HDN_ENDTRACK and HDN_BEGINTRACK are out of sync..."); this.listViewState[LISTVIEWSTATE_headerControlTracking] = false; - if (this.listViewState1[LISTVIEWSTATE1_cancelledColumnWidthChanging]) { - m.Result = (IntPtr) 1; - if (this.newWidthForColumnWidthChangingCancelled != -1) { + if (this.listViewState1[LISTVIEWSTATE1_cancelledColumnWidthChanging]) + { + m.Result = (IntPtr)1; + if (this.newWidthForColumnWidthChangingCancelled != -1) + { NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER)m.GetLParam(typeof(NativeMethods.NMHEADER)); - if (this.columnHeaders != null && this.columnHeaders.Length > nmheader.iItem) { + if (this.columnHeaders != null && this.columnHeaders.Length > nmheader.iItem) + { this.columnHeaders[nmheader.iItem].Width = this.newWidthForColumnWidthChangingCancelled; } } @@ -5202,37 +5986,47 @@ private unsafe bool WmNotify(ref Message m) { // skip default processing return true; - } else { + } + else + { return false; } } - if (nmhdr->code == NativeMethods.HDN_ENDDRAG) { - NativeMethods.NMHEADER header = (NativeMethods.NMHEADER) m.GetLParam(typeof(NativeMethods.NMHEADER)); - if (header.pItem != IntPtr.Zero) { + if (nmhdr->code == NativeMethods.HDN_ENDDRAG) + { + NativeMethods.NMHEADER header = (NativeMethods.NMHEADER)m.GetLParam(typeof(NativeMethods.NMHEADER)); + if (header.pItem != IntPtr.Zero) + { - NativeMethods.HDITEM2 hdItem = Marshal.PtrToStructure((IntPtr) header.pItem); - if ((hdItem.mask & NativeMethods.HDI_ORDER) == NativeMethods.HDI_ORDER) { + NativeMethods.HDITEM2 hdItem = Marshal.PtrToStructure((IntPtr)header.pItem); + if ((hdItem.mask & NativeMethods.HDI_ORDER) == NativeMethods.HDI_ORDER) + { int from = this.Columns[header.iItem].DisplayIndex; int to = hdItem.iOrder; // check this - if (from == to) { + if (from == to) + { return false; } // sometimes ComCtl gives us bogus values for HDIItem.iOrder. - if (to < 0) { + if (to < 0) + { return false; } ColumnReorderedEventArgs chrevent = new ColumnReorderedEventArgs(from, to, this.Columns[header.iItem]); OnColumnReordered(chrevent); - if (chrevent.Cancel) { + if (chrevent.Cancel) + { m.Result = new IntPtr(1); return true; - } else { + } + else + { // set the display indices. This is not an expensive operation because // we only set an integer in the column header class int lowDI = Math.Min(from, to); @@ -5240,12 +6034,16 @@ private unsafe bool WmNotify(ref Message m) { bool hdrMovedForward = to > from; ColumnHeader movedHdr = null; int[] indices = new int[this.Columns.Count]; - for (int i = 0; i < this.Columns.Count; i ++) { + for (int i = 0; i < this.Columns.Count; i++) + { ColumnHeader hdr = this.Columns[i]; - if (hdr.DisplayIndex == from) { + if (hdr.DisplayIndex == from) + { movedHdr = hdr; - } else if (hdr.DisplayIndex >= lowDI && hdr.DisplayIndex <= hiDI) { + } + else if (hdr.DisplayIndex >= lowDI && hdr.DisplayIndex <= hiDI) + { hdr.DisplayIndexInternal -= hdrMovedForward ? 1 : -1; } indices[i] = hdr.DisplayIndexInternal; @@ -5253,7 +6051,7 @@ private unsafe bool WmNotify(ref Message m) { movedHdr.DisplayIndexInternal = to; indices[movedHdr.Index] = movedHdr.DisplayIndexInternal; - SetDisplayIndices( indices ); + SetDisplayIndices(indices); #if DEBUG CheckDisplayIndices(); #endif @@ -5262,7 +6060,8 @@ private unsafe bool WmNotify(ref Message m) { } } - if (nmhdr->code == NativeMethods.HDN_DIVIDERDBLCLICK) { + if (nmhdr->code == NativeMethods.HDN_DIVIDERDBLCLICK) + { // We need to keep track that the user double clicked the column header divider // so we know that the column header width is changing. this.listViewState[LISTVIEWSTATE_headerDividerDblClick] = true; @@ -5293,26 +6092,32 @@ private unsafe bool WmNotify(ref Message m) { this.columnHeaderClicked = null; this.columnHeaderClickedWidth = -1; - if (columnResizeCancelled) { + if (columnResizeCancelled) + { // If the column resize was cancelled then apply the NewWidth supplied by the user. - if (this.newWidthForColumnWidthChangingCancelled != -1) { - NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER) m.GetLParam(typeof(NativeMethods.NMHEADER)); - if (this.columnHeaders != null && this.columnHeaders.Length > nmheader.iItem) { + if (this.newWidthForColumnWidthChangingCancelled != -1) + { + NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER)m.GetLParam(typeof(NativeMethods.NMHEADER)); + if (this.columnHeaders != null && this.columnHeaders.Length > nmheader.iItem) + { this.columnHeaders[nmheader.iItem].Width = this.newWidthForColumnWidthChangingCancelled; } } // Tell ComCtl that the HDN_DIVIDERDBLCLICK was cancelled. - m.Result = (IntPtr) 1; - } else { + m.Result = (IntPtr)1; + } + else + { // Compensate for the column resize. int compensateForColumnResize = this.CompensateColumnHeaderResize(m, columnResizeCancelled); - if (compensateForColumnResize != 0) { - #if DEBUG - NativeMethods.NMHEADER header = (NativeMethods.NMHEADER) m.GetLParam(typeof(NativeMethods.NMHEADER)); + if (compensateForColumnResize != 0) + { +#if DEBUG + NativeMethods.NMHEADER header = (NativeMethods.NMHEADER)m.GetLParam(typeof(NativeMethods.NMHEADER)); Debug.Assert(header.iItem == 0, "we only need to compensate for the first column resize"); Debug.Assert(this.columnHeaders.Length > 0, "there should be a column that we need to compensate for"); - #endif +#endif ColumnHeader col = this.columnHeaders[0]; col.Width += compensateForColumnResize; @@ -5326,7 +6131,8 @@ private unsafe bool WmNotify(ref Message m) { return false; // still need default handling } - private Font GetListHeaderFont(){ + private Font GetListHeaderFont() + { IntPtr hwndHdr = UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_GETHEADER, 0, 0); IntPtr hFont = UnsafeNativeMethods.SendMessage(new HandleRef(this, hwndHdr), Interop.WindowMessages.WM_GETFONT, 0, 0); return Font.FromHfont(hFont); @@ -5336,7 +6142,8 @@ private Font GetListHeaderFont(){ /// /// - private int GetIndexOfClickedItem(NativeMethods.LVHITTESTINFO lvhi) { + private int GetIndexOfClickedItem(NativeMethods.LVHITTESTINFO lvhi) + { Point pos = Cursor.Position; pos = PointToClient(pos); lvhi.pt_x = pos.X; @@ -5345,12 +6152,14 @@ private int GetIndexOfClickedItem(NativeMethods.LVHITTESTINFO lvhi) { } - internal void RecreateHandleInternal() { + internal void RecreateHandleInternal() + { // // For some reason, if CheckBoxes are set to true and the list view has a state imageList, then the native listView destroys // the state imageList. // (Yes, it does exactly that even though our wrapper sets LVS_SHAREIMAGELISTS on the native listView.) - if (this.IsHandleCreated && this.StateImageList != null) { + if (this.IsHandleCreated && this.StateImageList != null) + { SendMessage(NativeMethods.LVM_SETIMAGELIST, NativeMethods.LVSIL_STATE, IntPtr.Zero); } @@ -5360,16 +6169,19 @@ internal void RecreateHandleInternal() { /// /// [SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")] - private unsafe void WmReflectNotify(ref Message m) { + private unsafe void WmReflectNotify(ref Message m) + { NativeMethods.NMHDR* nmhdr = (NativeMethods.NMHDR*)m.LParam; - switch (nmhdr->code) { + switch (nmhdr->code) + { case NativeMethods.NM_CUSTOMDRAW: CustomDraw(ref m); break; - case NativeMethods.LVN_BEGINLABELEDIT: { + case NativeMethods.LVN_BEGINLABELEDIT: + { NativeMethods.NMLVDISPINFO_NOTEXT nmlvdp = (NativeMethods.NMLVDISPINFO_NOTEXT)m.GetLParam(typeof(NativeMethods.NMLVDISPINFO_NOTEXT)); LabelEditEventArgs e = new LabelEditEventArgs(nmlvdp.item.iItem); OnBeforeLabelEdit(e); @@ -5378,14 +6190,16 @@ private unsafe void WmReflectNotify(ref Message m) { break; } - case NativeMethods.LVN_COLUMNCLICK: { + case NativeMethods.LVN_COLUMNCLICK: + { NativeMethods.NMLISTVIEW nmlv = (NativeMethods.NMLISTVIEW)m.GetLParam(typeof(NativeMethods.NMLISTVIEW)); listViewState[LISTVIEWSTATE_columnClicked] = true; columnIndex = nmlv.iSubItem; break; } - case NativeMethods.LVN_ENDLABELEDIT: { + case NativeMethods.LVN_ENDLABELEDIT: + { listViewState[LISTVIEWSTATE_inLabelEdit] = false; NativeMethods.NMLVDISPINFO nmlvdp = (NativeMethods.NMLVDISPINFO)m.GetLParam(typeof(NativeMethods.NMLVDISPINFO)); LabelEditEventArgs e = new LabelEditEventArgs(nmlvdp.item.iItem, nmlvdp.item.pszText); @@ -5402,41 +6216,48 @@ private unsafe void WmReflectNotify(ref Message m) { OnItemActivate(EventArgs.Empty); break; - case NativeMethods.LVN_BEGINDRAG: { - // the items collection was modified while dragging - // that means that we can't reliably give the user the item on which the dragging started - // so don't tell the user about this operation... - // - if (!this.ItemCollectionChangedInMouseDown) { - NativeMethods.NMLISTVIEW nmlv = (NativeMethods.NMLISTVIEW)m.GetLParam(typeof(NativeMethods.NMLISTVIEW)); - LvnBeginDrag(MouseButtons.Left, nmlv); - } - - break; - } + case NativeMethods.LVN_BEGINDRAG: + { + // the items collection was modified while dragging + // that means that we can't reliably give the user the item on which the dragging started + // so don't tell the user about this operation... + // + if (!this.ItemCollectionChangedInMouseDown) + { + NativeMethods.NMLISTVIEW nmlv = (NativeMethods.NMLISTVIEW)m.GetLParam(typeof(NativeMethods.NMLISTVIEW)); + LvnBeginDrag(MouseButtons.Left, nmlv); + } - case NativeMethods.LVN_BEGINRDRAG: { - // the items collection was modified while dragging - // that means that we can't reliably give the user the item on which the dragging started - // so don't tell the user about this operation... - // - if (!this.ItemCollectionChangedInMouseDown) { - NativeMethods.NMLISTVIEW nmlv = (NativeMethods.NMLISTVIEW)m.GetLParam(typeof(NativeMethods.NMLISTVIEW)); - LvnBeginDrag(MouseButtons.Right, nmlv); + break; + } + + case NativeMethods.LVN_BEGINRDRAG: + { + // the items collection was modified while dragging + // that means that we can't reliably give the user the item on which the dragging started + // so don't tell the user about this operation... + // + if (!this.ItemCollectionChangedInMouseDown) + { + NativeMethods.NMLISTVIEW nmlv = (NativeMethods.NMLISTVIEW)m.GetLParam(typeof(NativeMethods.NMLISTVIEW)); + LvnBeginDrag(MouseButtons.Right, nmlv); + } + break; } - break; - } - case NativeMethods.LVN_ITEMCHANGING: { + case NativeMethods.LVN_ITEMCHANGING: + { NativeMethods.NMLISTVIEW* nmlv = (NativeMethods.NMLISTVIEW*)m.LParam; - if ((nmlv->uChanged & NativeMethods.LVIF_STATE) != 0) { + if ((nmlv->uChanged & NativeMethods.LVIF_STATE) != 0) + { // Because the state image mask is 1-based, a value of 1 means unchecked, // anything else means checked. We convert this to the more standard 0 or 1 CheckState oldState = (CheckState)(((nmlv->uOldState & NativeMethods.LVIS_STATEIMAGEMASK) >> 12) == 1 ? 0 : 1); CheckState newState = (CheckState)(((nmlv->uNewState & NativeMethods.LVIS_STATEIMAGEMASK) >> 12) == 1 ? 0 : 1); - if (oldState != newState) { + if (oldState != newState) + { ItemCheckEventArgs e = new ItemCheckEventArgs(nmlv->iItem, newState, oldState); OnItemCheck(e); m.Result = (IntPtr)(((int)e.NewValue == 0 ? 0 : 1) == (int)oldState ? 1 : 0); @@ -5445,19 +6266,22 @@ private unsafe void WmReflectNotify(ref Message m) { break; } - case NativeMethods.LVN_ITEMCHANGED: { + case NativeMethods.LVN_ITEMCHANGED: + { NativeMethods.NMLISTVIEW* nmlv = (NativeMethods.NMLISTVIEW*)m.LParam; // Check for state changes to the selected state... - if ((nmlv->uChanged & NativeMethods.LVIF_STATE) != 0) { + if ((nmlv->uChanged & NativeMethods.LVIF_STATE) != 0) + { // Because the state image mask is 1-based, a value of 1 means unchecked, // anything else means checked. We convert this to the more standard 0 or 1 CheckState oldValue = (CheckState)(((nmlv->uOldState & NativeMethods.LVIS_STATEIMAGEMASK) >> 12) == 1 ? 0 : 1); CheckState newValue = (CheckState)(((nmlv->uNewState & NativeMethods.LVIS_STATEIMAGEMASK) >> 12) == 1 ? 0 : 1); - if (newValue != oldValue) { + if (newValue != oldValue) + { ItemCheckedEventArgs e = new ItemCheckedEventArgs(Items[nmlv->iItem]); OnItemChecked(e); - + AccessibilityNotifyClients(AccessibleEvents.StateChange, nmlv->iItem); AccessibilityNotifyClients(AccessibleEvents.NameChange, nmlv->iItem); } @@ -5470,11 +6294,13 @@ private unsafe void WmReflectNotify(ref Message m) { // Changing this affects the behaviour as the control never // fires the event on a Deselct of an Items from multiple selections. // So leave it as it is... - if (newState != oldState) { + if (newState != oldState) + { if (this.VirtualMode && nmlv->iItem == -1) { - if (this.VirtualListSize > 0) { - ListViewVirtualItemsSelectionRangeChangedEventArgs lvvisrce = new ListViewVirtualItemsSelectionRangeChangedEventArgs(0, this.VirtualListSize-1, newState != 0); + if (this.VirtualListSize > 0) + { + ListViewVirtualItemsSelectionRangeChangedEventArgs lvvisrce = new ListViewVirtualItemsSelectionRangeChangedEventArgs(0, this.VirtualListSize - 1, newState != 0); OnVirtualItemsSelectionRangeChanged(lvvisrce); } } @@ -5486,7 +6312,8 @@ private unsafe void WmReflectNotify(ref Message m) { // In that case, the native list view may have an item under the mouse even if our wrapper thinks the item count is 0. // And that may cause GetItemAt to throw an out of bounds exception. - if (this.Items.Count > 0) { + if (this.Items.Count > 0) + { ListViewItemSelectionChangedEventArgs lvisce = new ListViewItemSelectionChangedEventArgs(this.Items[nmlv->iItem], nmlv->iItem, newState != 0); @@ -5521,7 +6348,8 @@ private unsafe void WmReflectNotify(ref Message m) { Point pos = Cursor.Position; pos = PointToClient(pos); - if (!ValidationCancelled && displayIndex != -1) { + if (!ValidationCancelled && displayIndex != -1) + { OnClick(EventArgs.Empty); OnMouseClick(new MouseEventArgs(button, 1, pos.X, pos.Y, 0)); } @@ -5541,7 +6369,8 @@ private unsafe void WmReflectNotify(ref Message m) { NativeMethods.LVHITTESTINFO lvhip = new NativeMethods.LVHITTESTINFO(); int index = GetIndexOfClickedItem(lvhip); - if (index != -1) { + if (index != -1) + { //just maintain state and fire double click.. in final mouseUp... listViewState[LISTVIEWSTATE_doubleclickFired] = true; } @@ -5553,15 +6382,21 @@ private unsafe void WmReflectNotify(ref Message m) { break; case NativeMethods.LVN_KEYDOWN: - if (CheckBoxes) { + if (CheckBoxes) + { NativeMethods.NMLVKEYDOWN lvkd = (NativeMethods.NMLVKEYDOWN)m.GetLParam(typeof(NativeMethods.NMLVKEYDOWN)); - if (lvkd.wVKey == (short)Keys.Space) { + if (lvkd.wVKey == (short)Keys.Space) + { ListViewItem focusedItem = FocusedItem; - if (focusedItem != null) { + if (focusedItem != null) + { bool check = !focusedItem.Checked; - if (!VirtualMode) { - foreach(ListViewItem item in SelectedItems) { - if (item != focusedItem) { + if (!VirtualMode) + { + foreach (ListViewItem item in SelectedItems) + { + if (item != focusedItem) + { item.Checked = check; } } @@ -5573,15 +6408,17 @@ private unsafe void WmReflectNotify(ref Message m) { case NativeMethods.LVN_ODCACHEHINT: // tell the user to prepare the cache: - NativeMethods.NMLVCACHEHINT cacheHint = (NativeMethods.NMLVCACHEHINT) m.GetLParam(typeof(NativeMethods.NMLVCACHEHINT)); + NativeMethods.NMLVCACHEHINT cacheHint = (NativeMethods.NMLVCACHEHINT)m.GetLParam(typeof(NativeMethods.NMLVCACHEHINT)); OnCacheVirtualItems(new CacheVirtualItemsEventArgs(cacheHint.iFrom, cacheHint.iTo)); break; default: - if (nmhdr->code == NativeMethods.LVN_GETDISPINFO) { + if (nmhdr->code == NativeMethods.LVN_GETDISPINFO) + { // we use the LVN_GETDISPINFO message only in virtual mode - if (this.VirtualMode && m.LParam != IntPtr.Zero) { - NativeMethods.NMLVDISPINFO_NOTEXT dispInfo= (NativeMethods.NMLVDISPINFO_NOTEXT) m.GetLParam(typeof(NativeMethods.NMLVDISPINFO_NOTEXT)); + if (this.VirtualMode && m.LParam != IntPtr.Zero) + { + NativeMethods.NMLVDISPINFO_NOTEXT dispInfo = (NativeMethods.NMLVDISPINFO_NOTEXT)m.GetLParam(typeof(NativeMethods.NMLVDISPINFO_NOTEXT)); RetrieveVirtualItemEventArgs rVI = new RetrieveVirtualItemEventArgs(dispInfo.item.iItem); OnRetrieveVirtualItem(rVI); @@ -5592,22 +6429,28 @@ private unsafe void WmReflectNotify(ref Message m) { } lvItem.SetItemIndex(this, dispInfo.item.iItem); - if ((dispInfo.item.mask & NativeMethods.LVIF_TEXT) != 0) { + if ((dispInfo.item.mask & NativeMethods.LVIF_TEXT) != 0) + { string text; - if (dispInfo.item.iSubItem == 0) { + if (dispInfo.item.iSubItem == 0) + { text = lvItem.Text; // we want the item } - else { - if (lvItem.SubItems.Count <= dispInfo.item.iSubItem) { + else + { + if (lvItem.SubItems.Count <= dispInfo.item.iSubItem) + { throw new InvalidOperationException(SR.ListViewVirtualModeCantAccessSubItem); } - else { + else + { text = lvItem.SubItems[dispInfo.item.iSubItem].Text; // we want the sub item } } // use the buffer provided by the ComCtrl list view. - if (dispInfo.item.cchTextMax <= text.Length) { + if (dispInfo.item.cchTextMax <= text.Length) + { text = text.Substring(0, dispInfo.item.cchTextMax - 1); } @@ -5615,26 +6458,32 @@ private unsafe void WmReflectNotify(ref Message m) { Marshal.Copy(buff, 0, dispInfo.item.pszText, text.Length + 1); } - if ((dispInfo.item.mask & NativeMethods.LVIF_IMAGE) != 0 && lvItem.ImageIndex != -1) { + if ((dispInfo.item.mask & NativeMethods.LVIF_IMAGE) != 0 && lvItem.ImageIndex != -1) + { dispInfo.item.iImage = lvItem.ImageIndex; } - if ((dispInfo.item.mask & NativeMethods.LVIF_INDENT) != 0) { + if ((dispInfo.item.mask & NativeMethods.LVIF_INDENT) != 0) + { dispInfo.item.iIndent = lvItem.IndentCount; } - if ((dispInfo.item.stateMask & NativeMethods.LVIS_STATEIMAGEMASK) != 0) { + if ((dispInfo.item.stateMask & NativeMethods.LVIS_STATEIMAGEMASK) != 0) + { dispInfo.item.state |= lvItem.RawStateImageIndex; } - Marshal.StructureToPtr(dispInfo, (IntPtr) m.LParam, false); + Marshal.StructureToPtr(dispInfo, (IntPtr)m.LParam, false); } } - else if (nmhdr->code == NativeMethods.LVN_ODSTATECHANGED) { - if (VirtualMode && m.LParam != IntPtr.Zero) { - NativeMethods.NMLVODSTATECHANGE odStateChange = (NativeMethods.NMLVODSTATECHANGE) m.GetLParam(typeof(NativeMethods.NMLVODSTATECHANGE)); + else if (nmhdr->code == NativeMethods.LVN_ODSTATECHANGED) + { + if (VirtualMode && m.LParam != IntPtr.Zero) + { + NativeMethods.NMLVODSTATECHANGE odStateChange = (NativeMethods.NMLVODSTATECHANGE)m.GetLParam(typeof(NativeMethods.NMLVODSTATECHANGE)); bool selectedChanged = (odStateChange.uNewState & NativeMethods.LVIS_SELECTED) != (odStateChange.uOldState & NativeMethods.LVIS_SELECTED); - if (selectedChanged) { + if (selectedChanged) + { // we have to substract 1 from iTo // // @@ -5644,17 +6493,20 @@ private unsafe void WmReflectNotify(ref Message m) { } } } - else if (nmhdr->code == NativeMethods.LVN_GETINFOTIP) { - if (ShowItemToolTips && m.LParam != IntPtr.Zero) { - NativeMethods.NMLVGETINFOTIP infoTip = (NativeMethods.NMLVGETINFOTIP) m.GetLParam(typeof(NativeMethods.NMLVGETINFOTIP)); + else if (nmhdr->code == NativeMethods.LVN_GETINFOTIP) + { + if (ShowItemToolTips && m.LParam != IntPtr.Zero) + { + NativeMethods.NMLVGETINFOTIP infoTip = (NativeMethods.NMLVGETINFOTIP)m.GetLParam(typeof(NativeMethods.NMLVGETINFOTIP)); ListViewItem lvi = Items[infoTip.item]; - if (lvi != null && !string.IsNullOrEmpty(lvi.ToolTipText)) { + if (lvi != null && !string.IsNullOrEmpty(lvi.ToolTipText)) + { // MSDN: // Setting the max width has the added benefit of enabling multiline // tool tips! // - + UnsafeNativeMethods.SendMessage(new HandleRef(this, nmhdr->hwndFrom), NativeMethods.TTM_SETMAXTIPWIDTH, 0, SystemInformation.MaxWindowTrackSize.Width); // UNICODE. Use char. @@ -5662,16 +6514,19 @@ private unsafe void WmReflectNotify(ref Message m) { char[] charBuf = (lvi.ToolTipText + "\0").ToCharArray(); Marshal.Copy(charBuf, 0, infoTip.lpszText, Math.Min(charBuf.Length, infoTip.cchTextMax)); - Marshal.StructureToPtr(infoTip, (IntPtr) m.LParam, false); + Marshal.StructureToPtr(infoTip, (IntPtr)m.LParam, false); } } } - else if (nmhdr->code == NativeMethods.LVN_ODFINDITEM) { - if (VirtualMode) { - NativeMethods.NMLVFINDITEM nmlvif = (NativeMethods.NMLVFINDITEM) m.GetLParam(typeof(NativeMethods.NMLVFINDITEM)); + else if (nmhdr->code == NativeMethods.LVN_ODFINDITEM) + { + if (VirtualMode) + { + NativeMethods.NMLVFINDITEM nmlvif = (NativeMethods.NMLVFINDITEM)m.GetLParam(typeof(NativeMethods.NMLVFINDITEM)); - if ((nmlvif.lvfi.flags & NativeMethods.LVFI_PARAM) != 0) { - m.Result = (IntPtr) (-1); + if ((nmlvif.lvfi.flags & NativeMethods.LVFI_PARAM) != 0) + { + m.Result = (IntPtr)(-1); return; } @@ -5681,23 +6536,27 @@ private unsafe void WmReflectNotify(ref Message m) { bool isPrefixSearch = (nmlvif.lvfi.flags & NativeMethods.LVFI_PARTIAL) != 0; string text = string.Empty; - if (isTextSearch) { + if (isTextSearch) + { text = nmlvif.lvfi.psz; } Point startingPoint = Point.Empty; - if ((nmlvif.lvfi.flags & NativeMethods.LVFI_NEARESTXY) != 0) { + if ((nmlvif.lvfi.flags & NativeMethods.LVFI_NEARESTXY) != 0) + { startingPoint = new Point(nmlvif.lvfi.ptX, nmlvif.lvfi.ptY); } SearchDirectionHint dir = SearchDirectionHint.Down; - if ((nmlvif.lvfi.flags & NativeMethods.LVFI_NEARESTXY) != 0) { + if ((nmlvif.lvfi.flags & NativeMethods.LVFI_NEARESTXY) != 0) + { // We can do this because SearchDirectionHint is set to the VK_* - dir = (SearchDirectionHint) nmlvif.lvfi.vkDirection; + dir = (SearchDirectionHint)nmlvif.lvfi.vkDirection; } int startIndex = nmlvif.iStart; - if (startIndex >= this.VirtualListSize) { + if (startIndex >= this.VirtualListSize) + { // we want to search starting from the last item. Wrap around the first item. startIndex = 0; } @@ -5713,21 +6572,27 @@ private unsafe void WmReflectNotify(ref Message m) { nmlvif.iStart); OnSearchForVirtualItem(sviEvent); - if (sviEvent.Index != -1) { - m.Result = (IntPtr) sviEvent.Index; - } else { - m.Result = (IntPtr) (-1); + if (sviEvent.Index != -1) + { + m.Result = (IntPtr)sviEvent.Index; + } + else + { + m.Result = (IntPtr)(-1); } } } - break; + break; } } - private void WmPrint(ref Message m) { + private void WmPrint(ref Message m) + { base.WndProc(ref m); - if ((NativeMethods.PRF_NONCLIENT & (int)m.LParam) != 0 && Application.RenderWithVisualStyles && this.BorderStyle == BorderStyle.Fixed3D) { - using (Graphics g = Graphics.FromHdc(m.WParam)) { + if ((NativeMethods.PRF_NONCLIENT & (int)m.LParam) != 0 && Application.RenderWithVisualStyles && this.BorderStyle == BorderStyle.Fixed3D) + { + using (Graphics g = Graphics.FromHdc(m.WParam)) + { Rectangle rect = new Rectangle(0, 0, this.Size.Width - 1, this.Size.Height - 1); g.DrawRectangle(new Pen(VisualStyleInformation.TextControlBorder), rect); rect.Inflate(-1, -1); @@ -5738,9 +6603,11 @@ private void WmPrint(ref Message m) { /// /// - protected override void WndProc(ref Message m) { + protected override void WndProc(ref Message m) + { - switch (m.Msg) { + switch (m.Msg) + { case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_NOTIFY: WmReflectNotify(ref m); break; @@ -5771,7 +6638,8 @@ protected override void WndProc(ref Message m) { NativeMethods.LVHITTESTINFO lvhip = new NativeMethods.LVHITTESTINFO(); int index = GetIndexOfClickedItem(lvhip); - if (!ValidationCancelled && listViewState[LISTVIEWSTATE_doubleclickFired] && index != -1) { + if (!ValidationCancelled && listViewState[LISTVIEWSTATE_doubleclickFired] && index != -1) + { listViewState[LISTVIEWSTATE_doubleclickFired] = false; OnDoubleClick(EventArgs.Empty); OnMouseDoubleClick(new MouseEventArgs(downButton, 2, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); @@ -5811,14 +6679,15 @@ protected override void WndProc(ref Message m) { base.WndProc(ref m); break; case Interop.WindowMessages.WM_MOUSEHOVER: - if (HoverSelection) { + if (HoverSelection) + { base.WndProc(ref m); } else OnMouseHover(EventArgs.Empty); break; case Interop.WindowMessages.WM_NOTIFY: - if(WmNotify(ref m)) + if (WmNotify(ref m)) { break; // we are done - skip default handling } @@ -5829,7 +6698,8 @@ protected override void WndProc(ref Message m) { case Interop.WindowMessages.WM_SETFOCUS: base.WndProc(ref m); - if (!this.RecreatingHandle && !this.ListViewHandleDestroyed) { + if (!this.RecreatingHandle && !this.ListViewHandleDestroyed) + { // This means that we get a WM_SETFOCUS on the hWnd that was destroyed. // Don't do anything because the information on the previous hWnd is most likely // out of sync w/ the information in our ListView wrapper. @@ -5859,7 +6729,8 @@ protected override void WndProc(ref Message m) { WmPrint(ref m); break; case Interop.WindowMessages.WM_TIMER: - if (unchecked( (int) (long)m.WParam) != LVTOOLTIPTRACKING || !ComctlSupportsVisualStyles) { + if (unchecked((int)(long)m.WParam) != LVTOOLTIPTRACKING || !ComctlSupportsVisualStyles) + { base.WndProc(ref m); } break; @@ -5871,39 +6742,48 @@ protected override void WndProc(ref Message m) { ///new class for comparing and sorting Icons .... //subhag - internal class IconComparer: IComparer { + internal class IconComparer : IComparer + { private SortOrder sortOrder; - public IconComparer(SortOrder currentSortOrder) { - this.sortOrder = currentSortOrder; + public IconComparer(SortOrder currentSortOrder) + { + this.sortOrder = currentSortOrder; } - public SortOrder SortOrder { - set { + public SortOrder SortOrder + { + set + { sortOrder = value; } } - public int Compare(object obj1, object obj2) { + public int Compare(object obj1, object obj2) + { //subhag - ListViewItem currentItem = (ListViewItem)obj1; - ListViewItem nextItem = (ListViewItem)obj2; - if (sortOrder == SortOrder.Ascending) { - return (string.Compare(currentItem.Text,nextItem.Text, false, CultureInfo.CurrentCulture)); + ListViewItem currentItem = (ListViewItem)obj1; + ListViewItem nextItem = (ListViewItem)obj2; + if (sortOrder == SortOrder.Ascending) + { + return (string.Compare(currentItem.Text, nextItem.Text, false, CultureInfo.CurrentCulture)); } - else { - return (string.Compare(nextItem.Text,currentItem.Text, false, CultureInfo.CurrentCulture)); + else + { + return (string.Compare(nextItem.Text, currentItem.Text, false, CultureInfo.CurrentCulture)); } } } //end subhag [ListBindable(false)] - public class CheckedIndexCollection : IList { + public class CheckedIndexCollection : IList + { private ListView owner; /* C#r: protected */ - public CheckedIndexCollection(ListView owner) { + public CheckedIndexCollection(ListView owner) + { this.owner = owner; } @@ -5911,17 +6791,22 @@ public CheckedIndexCollection(ListView owner) { /// Number of currently selected items. /// [Browsable(false)] - public int Count { - get { - if (!owner.CheckBoxes) { + public int Count + { + get + { + if (!owner.CheckBoxes) + { return 0; } // Count the number of checked items // int count = 0; - foreach(ListViewItem item in owner.Items) { - if (item != null && item.Checked) { + foreach (ListViewItem item in owner.Items) + { + if (item != null && item.Checked) + { count++; } } @@ -5929,12 +6814,16 @@ public int Count { } } - private int[] IndicesArray { - get { + private int[] IndicesArray + { + get + { int[] indices = new int[Count]; int index = 0; - for(int i=0; i < owner.Items.Count && index < indices.Length; ++i) { - if (owner.Items[i].Checked) { + for (int i = 0; i < owner.Items.Count && index < indices.Length; ++i) + { + if (owner.Items[i].Checked) + { indices[index++] = i; } } @@ -5945,10 +6834,13 @@ private int[] IndicesArray { /// /// Selected item in the list. /// - public int this[int index] { - get { + public int this[int index] + { + get + { - if (index < 0) { + if (index < 0) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } @@ -5956,11 +6848,14 @@ public int this[int index] { // int cnt = owner.Items.Count; int nChecked = 0; - for(int i = 0; i < cnt; i++) { + for (int i = 0; i < cnt; i++) + { ListViewItem item = owner.Items[i]; - if (item.Checked) { - if (nChecked == index) { + if (item.Checked) + { + if (nChecked == index) + { return i; } nChecked++; @@ -5972,124 +6867,159 @@ public int this[int index] { } } - object IList.this[int index] { - get { + object IList.this[int index] + { + get + { return this[index]; } - set { + set + { throw new NotSupportedException(); } } - object ICollection.SyncRoot { - get { + object ICollection.SyncRoot + { + get + { return this; } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return false; } } - bool IList.IsFixedSize { - get { + bool IList.IsFixedSize + { + get + { return true; } } - public bool IsReadOnly { - get { + public bool IsReadOnly + { + get + { return true; } } - public bool Contains(int checkedIndex) { - if (owner.Items[checkedIndex].Checked) { + public bool Contains(int checkedIndex) + { + if (owner.Items[checkedIndex].Checked) + { return true; } - else { + else + { return false; } } - bool IList.Contains(object checkedIndex) { - if (checkedIndex is int) { + bool IList.Contains(object checkedIndex) + { + if (checkedIndex is int) + { return Contains((int)checkedIndex); } - else { + else + { return false; } } - public int IndexOf(int checkedIndex) { + public int IndexOf(int checkedIndex) + { int[] indices = IndicesArray; - for(int index=0; index < indices.Length; ++index) { - if (indices[index] == checkedIndex) { + for (int index = 0; index < indices.Length; ++index) + { + if (indices[index] == checkedIndex) + { return index; } } return -1; } - int IList.IndexOf(object checkedIndex) { - if (checkedIndex is int) { + int IList.IndexOf(object checkedIndex) + { + if (checkedIndex is int) + { return IndexOf((int)checkedIndex); } - else { + else + { return -1; } } - int IList.Add(object value) { + int IList.Add(object value) + { throw new NotSupportedException(); } - void IList.Clear() { + void IList.Clear() + { throw new NotSupportedException(); } - void IList.Insert(int index, object value) { + void IList.Insert(int index, object value) + { throw new NotSupportedException(); } - void IList.Remove(object value) { + void IList.Remove(object value) + { throw new NotSupportedException(); } - void IList.RemoveAt(int index) { + void IList.RemoveAt(int index) + { throw new NotSupportedException(); } - void ICollection.CopyTo(Array dest, int index) { - if (Count > 0) { + void ICollection.CopyTo(Array dest, int index) + { + if (Count > 0) + { System.Array.Copy(IndicesArray, 0, dest, index, Count); } } - public IEnumerator GetEnumerator() { + public IEnumerator GetEnumerator() + { int[] indices = IndicesArray; - if (indices != null) { + if (indices != null) + { return indices.GetEnumerator(); } - else { + else + { return new int[0].GetEnumerator(); } } } [ListBindable(false)] - public class CheckedListViewItemCollection : IList { + public class CheckedListViewItemCollection : IList + { private ListView owner; - /// A caching mechanism for key accessor - /// We use an index here rather than control so that we don't have lifetime - /// issues by holding on to extra references. - private int lastAccessedIndex = -1; + /// A caching mechanism for key accessor + /// We use an index here rather than control so that we don't have lifetime + /// issues by holding on to extra references. + private int lastAccessedIndex = -1; /* C#r: protected */ - public CheckedListViewItemCollection(ListView owner) { + public CheckedListViewItemCollection(ListView owner) + { this.owner = owner; } @@ -6097,9 +7027,12 @@ public CheckedListViewItemCollection(ListView owner) { /// Number of currently selected items. /// [Browsable(false)] - public int Count { - get { - if (owner.VirtualMode) { + public int Count + { + get + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessCheckedItemsCollectionWhenInVirtualMode); } @@ -6107,12 +7040,16 @@ public int Count { } } - private ListViewItem[] ItemArray { - get { + private ListViewItem[] ItemArray + { + get + { ListViewItem[] items = new ListViewItem[Count]; int index = 0; - for(int i=0; i < owner.Items.Count && index < items.Length; ++i) { - if (owner.Items[i].Checked) { + for (int i = 0; i < owner.Items.Count && index < items.Length; ++i) + { + if (owner.Items[i].Checked) + { items[index++] = owner.Items[i]; } } @@ -6123,9 +7060,12 @@ private ListViewItem[] ItemArray { /// /// Selected item in the list. /// - public ListViewItem this[int index] { - get { - if (owner.VirtualMode) { + public ListViewItem this[int index] + { + get + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessCheckedItemsCollectionWhenInVirtualMode); } @@ -6134,92 +7074,118 @@ public ListViewItem this[int index] { } } - object IList.this[int index] { - get { - if (owner.VirtualMode) { + object IList.this[int index] + { + get + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessCheckedItemsCollectionWhenInVirtualMode); } return this[index]; } - set { + set + { throw new NotSupportedException(); } } - /// - /// Retrieves the child control with the specified key. - /// - public virtual ListViewItem this[string key] { - get { - if (owner.VirtualMode) { - throw new InvalidOperationException(SR.ListViewCantAccessCheckedItemsCollectionWhenInVirtualMode); - } - - // We do not support null and empty string as valid keys. - if(string.IsNullOrEmpty(key)) { - return null; - } + /// + /// Retrieves the child control with the specified key. + /// + public virtual ListViewItem this[string key] + { + get + { + if (owner.VirtualMode) + { + throw new InvalidOperationException(SR.ListViewCantAccessCheckedItemsCollectionWhenInVirtualMode); + } - // Search for the key in our collection - int index = IndexOfKey(key); - if(IsValidIndex(index)) { - return this[index]; - } - else { - return null; - } + // We do not support null and empty string as valid keys. + if (string.IsNullOrEmpty(key)) + { + return null; + } + // Search for the key in our collection + int index = IndexOfKey(key); + if (IsValidIndex(index)) + { + return this[index]; + } + else + { + return null; } - } - object ICollection.SyncRoot { - get { + } + } + + object ICollection.SyncRoot + { + get + { return this; } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return false; } } - bool IList.IsFixedSize { - get { + bool IList.IsFixedSize + { + get + { return true; } } - public bool IsReadOnly { - get { + public bool IsReadOnly + { + get + { return true; } } - public bool Contains(ListViewItem item) { - if (owner.VirtualMode) { + public bool Contains(ListViewItem item) + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessCheckedItemsCollectionWhenInVirtualMode); } - if (item != null && item.ListView == owner && item.Checked) { + if (item != null && item.ListView == owner && item.Checked) + { return true; } - else { + else + { return false; } } - bool IList.Contains(object item) { - if (owner.VirtualMode) { + bool IList.Contains(object item) + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessCheckedItemsCollectionWhenInVirtualMode); } - if (item is ListViewItem) { + if (item is ListViewItem) + { return Contains((ListViewItem)item); } - else { + else + { return false; } } @@ -6227,22 +7193,28 @@ bool IList.Contains(object item) { /// /// Returns true if the collection contains an item with the specified key, false otherwise. /// - public virtual bool ContainsKey(string key) { - if (owner.VirtualMode) { + public virtual bool ContainsKey(string key) + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessCheckedItemsCollectionWhenInVirtualMode); } - return IsValidIndex(IndexOfKey(key)); + return IsValidIndex(IndexOfKey(key)); } - public int IndexOf(ListViewItem item) { - if (owner.VirtualMode) { + public int IndexOf(ListViewItem item) + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessCheckedItemsCollectionWhenInVirtualMode); } ListViewItem[] items = ItemArray; - for(int index=0; index < items.Length; ++index) { - if (items[index] == item) { + for (int index = 0; index < items.Length; ++index) + { + if (items[index] == item) + { return index; } } @@ -6252,27 +7224,33 @@ public int IndexOf(ListViewItem item) { /// /// The zero-based index of the first occurrence of value within the entire CollectionBase, if found; otherwise, -1. /// - public virtual int IndexOfKey(string key) { - if (owner.VirtualMode) { + public virtual int IndexOfKey(string key) + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessCheckedItemsCollectionWhenInVirtualMode); } // Step 0 - Arg validation - if (string.IsNullOrEmpty(key)) { - return -1; // we dont support empty or null keys. + if (string.IsNullOrEmpty(key)) + { + return -1; // we dont support empty or null keys. } // step 1 - check the last cached item if (IsValidIndex(lastAccessedIndex)) { - if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) { + if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) + { return lastAccessedIndex; } } // step 2 - search for the item - for (int i = 0; i < this.Count; i ++) { - if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { + for (int i = 0; i < this.Count; i++) + { + if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) + { lastAccessedIndex = i; return i; } @@ -6287,63 +7265,80 @@ public virtual int IndexOfKey(string key) { /// /// Determines if the index is valid for the collection. /// - private bool IsValidIndex(int index) { + private bool IsValidIndex(int index) + { return ((index >= 0) && (index < this.Count)); } - int IList.IndexOf(object item) { - if (owner.VirtualMode) { + int IList.IndexOf(object item) + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessCheckedItemsCollectionWhenInVirtualMode); } - if (item is ListViewItem) { + if (item is ListViewItem) + { return IndexOf((ListViewItem)item); } - else { + else + { return -1; } } - int IList.Add(object value) { + int IList.Add(object value) + { throw new NotSupportedException(); } - void IList.Clear() { + void IList.Clear() + { throw new NotSupportedException(); } - void IList.Insert(int index, object value) { + void IList.Insert(int index, object value) + { throw new NotSupportedException(); } - void IList.Remove(object value) { + void IList.Remove(object value) + { throw new NotSupportedException(); } - void IList.RemoveAt(int index) { + void IList.RemoveAt(int index) + { throw new NotSupportedException(); } - public void CopyTo(Array dest, int index) { - if (owner.VirtualMode) { - throw new InvalidOperationException(SR.ListViewCantAccessCheckedItemsCollectionWhenInVirtualMode); + public void CopyTo(Array dest, int index) + { + if (owner.VirtualMode) + { + throw new InvalidOperationException(SR.ListViewCantAccessCheckedItemsCollectionWhenInVirtualMode); } - if (Count > 0) { + if (Count > 0) + { System.Array.Copy(ItemArray, 0, dest, index, Count); } } - public IEnumerator GetEnumerator() { - if (owner.VirtualMode) { + public IEnumerator GetEnumerator() + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessCheckedItemsCollectionWhenInVirtualMode); } ListViewItem[] items = ItemArray; - if (items != null) { + if (items != null) + { return items.GetEnumerator(); } - else { + else + { return new ListViewItem[0].GetEnumerator(); } } @@ -6351,11 +7346,13 @@ public IEnumerator GetEnumerator() { } [ListBindable(false)] - public class SelectedIndexCollection : IList { + public class SelectedIndexCollection : IList + { private ListView owner; /* C#r: protected */ - public SelectedIndexCollection(ListView owner) { + public SelectedIndexCollection(ListView owner) + { this.owner = owner; } @@ -6363,13 +7360,18 @@ public SelectedIndexCollection(ListView owner) { /// Number of currently selected items. /// [Browsable(false)] - public int Count { - get { - if (owner.IsHandleCreated) { - return unchecked( (int) (long)owner.SendMessage(NativeMethods.LVM_GETSELECTEDCOUNT, 0, 0)); + public int Count + { + get + { + if (owner.IsHandleCreated) + { + return unchecked((int)(long)owner.SendMessage(NativeMethods.LVM_GETSELECTEDCOUNT, 0, 0)); } - else { - if (owner.savedSelectedItems != null) { + else + { + if (owner.savedSelectedItems != null) + { return owner.savedSelectedItems.Count; } return 0; @@ -6377,17 +7379,22 @@ public int Count { } } - private int[] IndicesArray { - get { + private int[] IndicesArray + { + get + { int count = Count; int[] indices = new int[count]; - if (owner.IsHandleCreated) { + if (owner.IsHandleCreated) + { int displayIndex = -1; - for (int i = 0; i < count; i++) { - int fidx = unchecked( (int) (long)owner.SendMessage(NativeMethods.LVM_GETNEXTITEM, displayIndex, NativeMethods.LVNI_SELECTED)); + for (int i = 0; i < count; i++) + { + int fidx = unchecked((int)(long)owner.SendMessage(NativeMethods.LVM_GETNEXTITEM, displayIndex, NativeMethods.LVNI_SELECTED)); - if (fidx > -1) { + if (fidx > -1) + { indices[i] = fidx; displayIndex = fidx; } @@ -6395,9 +7402,11 @@ private int[] IndicesArray { throw new InvalidOperationException(SR.SelectedNotEqualActual); } } - else { + else + { Debug.Assert(owner.savedSelectedItems != null || count == 0, "if the count of selectedItems is greater than 0 then the selectedItems should have been saved by now"); - for (int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) + { indices[i] = owner.savedSelectedItems[i].Index; } } @@ -6409,94 +7418,121 @@ private int[] IndicesArray { /// /// Selected item in the list. /// - public int this[int index] { - get { + public int this[int index] + { + get + { - if (index < 0 || index >= Count) { + if (index < 0 || index >= Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - if (owner.IsHandleCreated) { + if (owner.IsHandleCreated) + { // Count through the selected items in the ListView, until // we reach the 'index'th selected item. // int fidx = -1; - for(int count = 0; count <= index; count++) { - fidx = unchecked( (int) (long)owner.SendMessage(NativeMethods.LVM_GETNEXTITEM, fidx, NativeMethods.LVNI_SELECTED)); + for (int count = 0; count <= index; count++) + { + fidx = unchecked((int)(long)owner.SendMessage(NativeMethods.LVM_GETNEXTITEM, fidx, NativeMethods.LVNI_SELECTED)); Debug.Assert(fidx != -1, "Invalid index returned from LVM_GETNEXTITEM"); } return fidx; } - else { + else + { Debug.Assert(owner.savedSelectedItems != null, "Null selected items collection"); return owner.savedSelectedItems[index].Index; } } } - object IList.this[int index] { - get { + object IList.this[int index] + { + get + { return this[index]; } - set { + set + { throw new NotSupportedException(); } } - object ICollection.SyncRoot { - get { + object ICollection.SyncRoot + { + get + { return this; } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return false; } } - bool IList.IsFixedSize { - get { + bool IList.IsFixedSize + { + get + { return false; } } - public bool IsReadOnly { - get { + public bool IsReadOnly + { + get + { return false; } } - public bool Contains(int selectedIndex) { + public bool Contains(int selectedIndex) + { return owner.Items[selectedIndex].Selected; } - bool IList.Contains(object selectedIndex) { - if (selectedIndex is int) { + bool IList.Contains(object selectedIndex) + { + if (selectedIndex is int) + { return Contains((int)selectedIndex); } - else { + else + { return false; } } - public int IndexOf(int selectedIndex) { + public int IndexOf(int selectedIndex) + { int[] indices = IndicesArray; - for(int index=0; index < indices.Length; ++index) { - if (indices[index] == selectedIndex) { + for (int index = 0; index < indices.Length; ++index) + { + if (indices[index] == selectedIndex) + { return index; } } return -1; } - int IList.IndexOf(object selectedIndex) { - if (selectedIndex is int) { + int IList.IndexOf(object selectedIndex) + { + if (selectedIndex is int) + { return IndexOf((int)selectedIndex); } - else { + else + { return -1; } } @@ -6505,7 +7541,7 @@ int IList.Add(object value) { if (value is int) { - return Add((int) value); + return Add((int)value); } else { @@ -6513,11 +7549,13 @@ int IList.Add(object value) } } - void IList.Clear() { + void IList.Clear() + { Clear(); } - void IList.Insert(int index, object value) { + void IList.Insert(int index, object value) + { throw new NotSupportedException(); } @@ -6525,7 +7563,7 @@ void IList.Remove(object value) { if (value is int) { - Remove((int) value); + Remove((int)value); } else { @@ -6533,7 +7571,8 @@ void IList.Remove(object value) } } - void IList.RemoveAt(int index) { + void IList.RemoveAt(int index) + { throw new NotSupportedException(); } @@ -6578,18 +7617,23 @@ public void Clear() } } - public void CopyTo(Array dest, int index) { - if (Count > 0) { + public void CopyTo(Array dest, int index) + { + if (Count > 0) + { System.Array.Copy(IndicesArray, 0, dest, index, Count); } } - public IEnumerator GetEnumerator() { + public IEnumerator GetEnumerator() + { int[] indices = IndicesArray; - if (indices != null) { + if (indices != null) + { return indices.GetEnumerator(); } - else { + else + { return new int[0].GetEnumerator(); } } @@ -6619,7 +7663,8 @@ public void Remove(int itemIndex) } [ListBindable(false)] - public class SelectedListViewItemCollection : IList { + public class SelectedListViewItemCollection : IList + { private ListView owner; /// A caching mechanism for key accessor @@ -6628,23 +7673,29 @@ public class SelectedListViewItemCollection : IList { private int lastAccessedIndex = -1; /* C#r: protected */ - public SelectedListViewItemCollection(ListView owner) { + public SelectedListViewItemCollection(ListView owner) + { this.owner = owner; } - private ListViewItem[] SelectedItemArray { - get { - if (owner.IsHandleCreated) { - int cnt = unchecked( (int) (long)owner.SendMessage(NativeMethods.LVM_GETSELECTEDCOUNT, 0, 0)); + private ListViewItem[] SelectedItemArray + { + get + { + if (owner.IsHandleCreated) + { + int cnt = unchecked((int)(long)owner.SendMessage(NativeMethods.LVM_GETSELECTEDCOUNT, 0, 0)); ListViewItem[] lvitems = new ListViewItem[cnt]; int displayIndex = -1; - for (int i = 0; i < cnt; i++) { - int fidx = unchecked( (int) (long)owner.SendMessage(NativeMethods.LVM_GETNEXTITEM, displayIndex, NativeMethods.LVNI_SELECTED)); + for (int i = 0; i < cnt; i++) + { + int fidx = unchecked((int)(long)owner.SendMessage(NativeMethods.LVM_GETNEXTITEM, displayIndex, NativeMethods.LVNI_SELECTED)); - if (fidx > -1) { + if (fidx > -1) + { lvitems[i] = owner.Items[fidx]; displayIndex = fidx; } @@ -6655,15 +7706,19 @@ private ListViewItem[] SelectedItemArray { return lvitems; } - else { - if (owner.savedSelectedItems != null) { + else + { + if (owner.savedSelectedItems != null) + { ListViewItem[] cloned = new ListViewItem[owner.savedSelectedItems.Count]; - for (int i = 0; i < owner.savedSelectedItems.Count; i ++) { + for (int i = 0; i < owner.savedSelectedItems.Count; i++) + { cloned[i] = owner.savedSelectedItems[i]; } return cloned; } - else { + else + { return new ListViewItem[0]; } } @@ -6674,17 +7729,23 @@ private ListViewItem[] SelectedItemArray { /// Number of currently selected items. /// [Browsable(false)] - public int Count { - get { - if (owner.VirtualMode) { + public int Count + { + get + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode); } - if (owner.IsHandleCreated) { - return unchecked( (int) (long)owner.SendMessage(NativeMethods.LVM_GETSELECTEDCOUNT, 0, 0)); + if (owner.IsHandleCreated) + { + return unchecked((int)(long)owner.SendMessage(NativeMethods.LVM_GETSELECTEDCOUNT, 0, 0)); } - else { - if (owner.savedSelectedItems != null) { + else + { + if (owner.savedSelectedItems != null) + { return owner.savedSelectedItems.Count; } return 0; @@ -6695,31 +7756,38 @@ public int Count { /// /// Selected item in the list. /// - public ListViewItem this[int index] { - get { + public ListViewItem this[int index] + { + get + { - if (owner.VirtualMode) { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode); } - if (index < 0 || index >= Count) { + if (index < 0 || index >= Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - if (owner.IsHandleCreated) { + if (owner.IsHandleCreated) + { // Count through the selected items in the ListView, until // we reach the 'index'th selected item. // int fidx = -1; - for(int count = 0; count <= index; count++) { - fidx = unchecked( (int) (long)owner.SendMessage(NativeMethods.LVM_GETNEXTITEM, fidx, NativeMethods.LVNI_SELECTED)); + for (int count = 0; count <= index; count++) + { + fidx = unchecked((int)(long)owner.SendMessage(NativeMethods.LVM_GETNEXTITEM, fidx, NativeMethods.LVNI_SELECTED)); Debug.Assert(fidx != -1, "Invalid index returned from LVM_GETNEXTITEM"); } return owner.Items[fidx]; } - else { + else + { Debug.Assert(owner.savedSelectedItems != null, "Null selected items collection"); return owner.savedSelectedItems[index]; } @@ -6729,73 +7797,93 @@ public ListViewItem this[int index] { /// /// Retrieves the child control with the specified key. /// - public virtual ListViewItem this[string key] { - get { - if (owner.VirtualMode) { + public virtual ListViewItem this[string key] + { + get + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode); } // We do not support null and empty string as valid keys. - if (string.IsNullOrEmpty(key)){ + if (string.IsNullOrEmpty(key)) + { return null; } // Search for the key in our collection int index = IndexOfKey(key); - if (IsValidIndex(index)) { + if (IsValidIndex(index)) + { return this[index]; } - else { + else + { return null; } } } - object IList.this[int index] { - get { - if (owner.VirtualMode) { + object IList.this[int index] + { + get + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode); } return this[index]; } - set { + set + { // SelectedListViewItemCollection is read-only throw new NotSupportedException(); } } - bool IList.IsFixedSize { - get { + bool IList.IsFixedSize + { + get + { return true; } } - public bool IsReadOnly { - get { + public bool IsReadOnly + { + get + { return true; } } - object ICollection.SyncRoot { - get { + object ICollection.SyncRoot + { + get + { return this; } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return false; } } - int IList.Add(object value) { + int IList.Add(object value) + { // SelectedListViewItemCollection is read-only throw new NotSupportedException(); } - void IList.Insert(int index, object value) { + void IList.Insert(int index, object value) + { // SelectedListViewItemCollection is read-only throw new NotSupportedException(); } @@ -6803,16 +7891,19 @@ void IList.Insert(int index, object value) { /// /// Determines if the index is valid for the collection. /// - private bool IsValidIndex(int index) { + private bool IsValidIndex(int index) + { return ((index >= 0) && (index < this.Count)); } - void IList.Remove(object value) { + void IList.Remove(object value) + { // SelectedListViewItemCollection is read-only throw new NotSupportedException(); } - void IList.RemoveAt(int index) { + void IList.RemoveAt(int index) + { // SelectedListViewItemCollection is read-only throw new NotSupportedException(); } @@ -6820,13 +7911,16 @@ void IList.RemoveAt(int index) { /// /// Unselects all items. /// - public void Clear() { - if (owner.VirtualMode) { + public void Clear() + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode); } ListViewItem[] items = SelectedItemArray; - for (int i=0; i < items.Length; i++) { + for (int i = 0; i < items.Length; i++) + { items[i].Selected = false; } } @@ -6834,82 +7928,105 @@ public void Clear() { /// /// Returns true if the collection contains an item with the specified key, false otherwise. /// - public virtual bool ContainsKey(string key) { - if (owner.VirtualMode) { + public virtual bool ContainsKey(string key) + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode); } return IsValidIndex(IndexOfKey(key)); } - public bool Contains(ListViewItem item) { - if (owner.VirtualMode) { + public bool Contains(ListViewItem item) + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode); } return (IndexOf(item) != -1); } - bool IList.Contains(object item) { - if (owner.VirtualMode) { + bool IList.Contains(object item) + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode); } - if (item is ListViewItem) { + if (item is ListViewItem) + { return Contains((ListViewItem)item); } - else { + else + { return false; } } - public void CopyTo(Array dest, int index) { - if (owner.VirtualMode) { + public void CopyTo(Array dest, int index) + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode); } - if (Count > 0) { + if (Count > 0) + { System.Array.Copy(SelectedItemArray, 0, dest, index, Count); } } - public IEnumerator GetEnumerator() { - if (owner.VirtualMode) { + public IEnumerator GetEnumerator() + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode); } ListViewItem[] items = SelectedItemArray; - if (items != null) { + if (items != null) + { return items.GetEnumerator(); } - else { + else + { return new ListViewItem[0].GetEnumerator(); } - } + } - public int IndexOf(ListViewItem item) { - if (owner.VirtualMode) { + public int IndexOf(ListViewItem item) + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode); } ListViewItem[] items = SelectedItemArray; - for(int index=0; index < items.Length; ++index) { - if (items[index] == item) { + for (int index = 0; index < items.Length; ++index) + { + if (items[index] == item) + { return index; } } return -1; } - int IList.IndexOf(object item) { - if (owner.VirtualMode) { + int IList.IndexOf(object item) + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode); } - if (item is ListViewItem) { + if (item is ListViewItem) + { return IndexOf((ListViewItem)item); } - else { + else + { return -1; } } @@ -6917,27 +8034,33 @@ int IList.IndexOf(object item) { /// /// The zero-based index of the first occurrence of value within the entire CollectionBase, if found; otherwise, -1. /// - public virtual int IndexOfKey(string key) { - if (owner.VirtualMode) { + public virtual int IndexOfKey(string key) + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode); } // Step 0 - Arg validation - if (string.IsNullOrEmpty(key)){ - return -1; // we dont support empty or null keys. + if (string.IsNullOrEmpty(key)) + { + return -1; // we dont support empty or null keys. } // step 1 - check the last cached item if (IsValidIndex(lastAccessedIndex)) { - if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) { + if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) + { return lastAccessedIndex; } } // step 2 - search for the item - for (int i = 0; i < this.Count; i ++) { - if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { + for (int i = 0; i < this.Count; i++) + { + if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) + { lastAccessedIndex = i; return i; } @@ -6951,10 +8074,12 @@ public virtual int IndexOfKey(string key) { } [ListBindable(false)] - public class ColumnHeaderCollection : IList { + public class ColumnHeaderCollection : IList + { private ListView owner; - public ColumnHeaderCollection(ListView owner) { + public ColumnHeaderCollection(ListView owner) + { this.owner = owner ?? throw new ArgumentNullException(nameof(owner)); } @@ -6962,19 +8087,24 @@ public ColumnHeaderCollection(ListView owner) { /// Given a Zero based index, returns the ColumnHeader object /// for the column at that index /// - public virtual ColumnHeader this[int index] { - get { + public virtual ColumnHeader this[int index] + { + get + { if (owner.columnHeaders == null || index < 0 || index >= owner.columnHeaders.Length) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); return owner.columnHeaders[index]; } } - object IList.this[int index] { - get { + object IList.this[int index] + { + get + { return this[index]; } - set { + set + { throw new NotSupportedException(); } } @@ -6982,19 +8112,24 @@ object IList.this[int index] { /// /// Retrieves the child control with the specified key. /// - public virtual ColumnHeader this[string key] { - get { + public virtual ColumnHeader this[string key] + { + get + { // We do not support null and empty string as valid keys. - if (string.IsNullOrEmpty(key)){ + if (string.IsNullOrEmpty(key)) + { return null; } // Search for the key in our collection int index = IndexOfKey(key); - if (IsValidIndex(index)) { + if (IsValidIndex(index)) + { return this[index]; } - else { + else + { return null; } @@ -7005,32 +8140,42 @@ public virtual ColumnHeader this[string key] { /// The number of columns the ListView currently has in Details view. /// [Browsable(false)] - public int Count { - get { + public int Count + { + get + { return owner.columnHeaders == null ? 0 : owner.columnHeaders.Length; } } - object ICollection.SyncRoot { - get { + object ICollection.SyncRoot + { + get + { return this; } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return true; } } - bool IList.IsFixedSize { - get { + bool IList.IsFixedSize + { + get + { return false; } } - public bool IsReadOnly { - get { + public bool IsReadOnly + { + get + { return false; } } @@ -7039,43 +8184,50 @@ public bool IsReadOnly { - /// - /// Removes the child control with the specified key. - /// - public virtual void RemoveByKey(string key) { + /// + /// Removes the child control with the specified key. + /// + public virtual void RemoveByKey(string key) + { int index = IndexOfKey(key); - if (IsValidIndex(index)) { + if (IsValidIndex(index)) + { RemoveAt(index); - } - } + } + } - /// A caching mechanism for key accessor - /// We use an index here rather than control so that we don't have lifetime - /// issues by holding on to extra references. - /// Note this is not Thread Safe - but WinForms has to be run in a STA anyways. - private int lastAccessedIndex = -1; + /// A caching mechanism for key accessor + /// We use an index here rather than control so that we don't have lifetime + /// issues by holding on to extra references. + /// Note this is not Thread Safe - but WinForms has to be run in a STA anyways. + private int lastAccessedIndex = -1; - /// - /// The zero-based index of the first occurrence of value within the entire CollectionBase, if found; otherwise, -1. - /// - public virtual int IndexOfKey(string key) { - // Step 0 - Arg validation - if (string.IsNullOrEmpty(key)){ - return -1; // we dont support empty or null keys. - } + /// + /// The zero-based index of the first occurrence of value within the entire CollectionBase, if found; otherwise, -1. + /// + public virtual int IndexOfKey(string key) + { + // Step 0 - Arg validation + if (string.IsNullOrEmpty(key)) + { + return -1; // we dont support empty or null keys. + } // step 1 - check the last cached item if (IsValidIndex(lastAccessedIndex)) { - if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) { + if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) + { return lastAccessedIndex; } } // step 2 - search for the item - for (int i = 0; i < this.Count; i ++) { - if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { + for (int i = 0; i < this.Count; i++) + { + if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) + { lastAccessedIndex = i; return i; } @@ -7084,21 +8236,23 @@ public virtual int IndexOfKey(string key) { // step 3 - we didn't find it. Invalidate the last accessed index and return -1. lastAccessedIndex = -1; return -1; - } + } - /// - /// Determines if the index is valid for the collection. - /// - private bool IsValidIndex(int index) { - return ((index >= 0) && (index < this.Count)); - } + /// + /// Determines if the index is valid for the collection. + /// + private bool IsValidIndex(int index) + { + return ((index >= 0) && (index < this.Count)); + } /// /// Adds a column to the end of the Column list /// - public virtual ColumnHeader Add(string text, int width, HorizontalAlignment textAlign) { + public virtual ColumnHeader Add(string text, int width, HorizontalAlignment textAlign) + { ColumnHeader columnHeader = new ColumnHeader(); columnHeader.Text = text; columnHeader.Width = width; @@ -7106,13 +8260,15 @@ public virtual ColumnHeader Add(string text, int width, HorizontalAlignment text return owner.InsertColumn(Count, columnHeader); } - public virtual int Add(ColumnHeader value) { + public virtual int Add(ColumnHeader value) + { int index = Count; owner.InsertColumn(index, value); return index; } - public virtual ColumnHeader Add(string text) { + public virtual ColumnHeader Add(string text) + { ColumnHeader columnHeader = new ColumnHeader(); columnHeader.Text = text; return owner.InsertColumn(Count, columnHeader); @@ -7120,21 +8276,24 @@ public virtual ColumnHeader Add(string text) { // <-- NEW ADD OVERLOADS IN WHIDBEY - public virtual ColumnHeader Add(string text, int width) { + public virtual ColumnHeader Add(string text, int width) + { ColumnHeader columnHeader = new ColumnHeader(); columnHeader.Text = text; columnHeader.Width = width; return owner.InsertColumn(Count, columnHeader); } - public virtual ColumnHeader Add(string key, string text) { + public virtual ColumnHeader Add(string key, string text) + { ColumnHeader columnHeader = new ColumnHeader(); columnHeader.Name = key; columnHeader.Text = text; return owner.InsertColumn(Count, columnHeader); } - public virtual ColumnHeader Add(string key, string text, int width) { + public virtual ColumnHeader Add(string key, string text, int width) + { ColumnHeader columnHeader = new ColumnHeader(); columnHeader.Name = key; columnHeader.Text = text; @@ -7142,7 +8301,8 @@ public virtual ColumnHeader Add(string key, string text, int width) { return owner.InsertColumn(Count, columnHeader); } - public virtual ColumnHeader Add(string key, string text, int width, HorizontalAlignment textAlign, string imageKey) { + public virtual ColumnHeader Add(string key, string text, int width, HorizontalAlignment textAlign, string imageKey) + { ColumnHeader columnHeader = new ColumnHeader(imageKey); columnHeader.Name = key; columnHeader.Text = text; @@ -7151,7 +8311,8 @@ public virtual ColumnHeader Add(string key, string text, int width, HorizontalAl return owner.InsertColumn(Count, columnHeader); } - public virtual ColumnHeader Add(string key, string text, int width, HorizontalAlignment textAlign, int imageIndex) { + public virtual ColumnHeader Add(string key, string text, int width, HorizontalAlignment textAlign, int imageIndex) + { ColumnHeader columnHeader = new ColumnHeader(imageIndex); columnHeader.Name = key; columnHeader.Text = text; @@ -7162,42 +8323,51 @@ public virtual ColumnHeader Add(string key, string text, int width, HorizontalAl // END - NEW ADD OVERLOADS IN WHIDBEY --> - public virtual void AddRange(ColumnHeader[] values) { - if (values == null) { + public virtual void AddRange(ColumnHeader[] values) + { + if (values == null) + { throw new ArgumentNullException(nameof(values)); } Hashtable usedIndices = new Hashtable(); - int [] indices = new int[values.Length]; + int[] indices = new int[values.Length]; - for (int i=0; i= 0 && values[i].DisplayIndex < values.Length) { - usedIndices.Add(values[i].DisplayIndex, i); + if (!usedIndices.ContainsKey(values[i].DisplayIndex) && values[i].DisplayIndex >= 0 && values[i].DisplayIndex < values.Length) + { + usedIndices.Add(values[i].DisplayIndex, i); } indices[i] = values[i].DisplayIndex; - Add( values[i] ); + Add(values[i]); } - if (usedIndices.Count == values.Length) { - owner.SetDisplayIndices( indices ); + if (usedIndices.Count == values.Length) + { + owner.SetDisplayIndices(indices); } } - int IList.Add(object value) { - if (value is ColumnHeader) { + int IList.Add(object value) + { + if (value is ColumnHeader) + { return Add((ColumnHeader)value); } - else { + else + { throw new ArgumentException(SR.ColumnHeaderCollectionInvalidArgument, nameof(value)); } } @@ -7205,23 +8375,32 @@ int IList.Add(object value) { /// /// Removes all columns from the list view. /// - public virtual void Clear() { + public virtual void Clear() + { // Delete the columns - if (owner.columnHeaders != null) { - if (owner.View == View.Tile) { + if (owner.columnHeaders != null) + { + if (owner.View == View.Tile) + { // in Tile view our ListView uses the column header collection to update the Tile Information - for (int colIdx = owner.columnHeaders.Length-1; colIdx >= 0; colIdx--) { + for (int colIdx = owner.columnHeaders.Length - 1; colIdx >= 0; colIdx--) + { int w = owner.columnHeaders[colIdx].Width; // Update width before detaching from ListView owner.columnHeaders[colIdx].OwnerListview = null; } owner.columnHeaders = null; - if (owner.IsHandleCreated) { + if (owner.IsHandleCreated) + { owner.RecreateHandleInternal(); } - } else { - for (int colIdx = owner.columnHeaders.Length-1; colIdx >= 0; colIdx--) { + } + else + { + for (int colIdx = owner.columnHeaders.Length - 1; colIdx >= 0; colIdx--) + { int w = owner.columnHeaders[colIdx].Width; // Update width before detaching from ListView - if (owner.IsHandleCreated) { + if (owner.IsHandleCreated) + { owner.SendMessage(NativeMethods.LVM_DELETECOLUMN, colIdx, 0); } owner.columnHeaders[colIdx].OwnerListview = null; @@ -7231,12 +8410,15 @@ public virtual void Clear() { } } - public bool Contains(ColumnHeader value) { + public bool Contains(ColumnHeader value) + { return IndexOf(value) != -1; } - bool IList.Contains(object value) { - if (value is ColumnHeader) { + bool IList.Contains(object value) + { + if (value is ColumnHeader) + { return Contains((ColumnHeader)value); } return false; @@ -7245,46 +8427,59 @@ bool IList.Contains(object value) { /// /// Returns true if the collection contains an item with the specified key, false otherwise. /// - public virtual bool ContainsKey(string key) { - return IsValidIndex(IndexOfKey(key)); + public virtual bool ContainsKey(string key) + { + return IsValidIndex(IndexOfKey(key)); } - void ICollection.CopyTo(Array dest, int index) { - if (Count > 0) { + void ICollection.CopyTo(Array dest, int index) + { + if (Count > 0) + { System.Array.Copy(owner.columnHeaders, 0, dest, index, Count); } } - public int IndexOf(ColumnHeader value) { - for(int index=0; index < Count; ++index) { - if (this[index] == value) { + public int IndexOf(ColumnHeader value) + { + for (int index = 0; index < Count; ++index) + { + if (this[index] == value) + { return index; } } return -1; } - int IList.IndexOf(object value) { - if (value is ColumnHeader) { + int IList.IndexOf(object value) + { + if (value is ColumnHeader) + { return IndexOf((ColumnHeader)value); } return -1; } - public void Insert(int index, ColumnHeader value) { - if (index < 0 || index > Count) { + public void Insert(int index, ColumnHeader value) + { + if (index < 0 || index > Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } owner.InsertColumn(index, value); } - void IList.Insert(int index, object value) { - if (value is ColumnHeader) { + void IList.Insert(int index, object value) + { + if (value is ColumnHeader) + { Insert(index, (ColumnHeader)value); } } - public void Insert(int index, string text, int width, HorizontalAlignment textAlign) { + public void Insert(int index, string text, int width, HorizontalAlignment textAlign) + { ColumnHeader columnHeader = new ColumnHeader(); columnHeader.Text = text; columnHeader.Width = width; @@ -7294,27 +8489,31 @@ public void Insert(int index, string text, int width, HorizontalAlignment textAl // <-- NEW INSERT OVERLOADS IN WHIDBEY - public void Insert(int index, string text) { + public void Insert(int index, string text) + { ColumnHeader columnHeader = new ColumnHeader(); columnHeader.Text = text; Insert(index, columnHeader); } - public void Insert(int index, string text, int width) { + public void Insert(int index, string text, int width) + { ColumnHeader columnHeader = new ColumnHeader(); columnHeader.Text = text; columnHeader.Width = width; Insert(index, columnHeader); } - public void Insert(int index, string key, string text) { + public void Insert(int index, string key, string text) + { ColumnHeader columnHeader = new ColumnHeader(); columnHeader.Name = key; columnHeader.Text = text; Insert(index, columnHeader); } - public void Insert(int index, string key, string text, int width) { + public void Insert(int index, string key, string text, int width) + { ColumnHeader columnHeader = new ColumnHeader(); columnHeader.Name = key; columnHeader.Text = text; @@ -7322,7 +8521,8 @@ public void Insert(int index, string key, string text, int width) { Insert(index, columnHeader); } - public void Insert(int index, string key, string text, int width, HorizontalAlignment textAlign, string imageKey) { + public void Insert(int index, string key, string text, int width, HorizontalAlignment textAlign, string imageKey) + { ColumnHeader columnHeader = new ColumnHeader(imageKey); columnHeader.Name = key; columnHeader.Text = text; @@ -7331,7 +8531,8 @@ public void Insert(int index, string key, string text, int width, HorizontalAlig Insert(index, columnHeader); } - public void Insert(int index, string key, string text, int width, HorizontalAlignment textAlign, int imageIndex) { + public void Insert(int index, string key, string text, int width, HorizontalAlignment textAlign, int imageIndex) + { ColumnHeader columnHeader = new ColumnHeader(imageIndex); columnHeader.Name = key; columnHeader.Text = text; @@ -7346,31 +8547,36 @@ public void Insert(int index, string key, string text, int width, HorizontalAlig /// /// removes a column from the ListView /// - public virtual void RemoveAt(int index) { + public virtual void RemoveAt(int index) + { if (owner.columnHeaders == null || index < 0 || index >= owner.columnHeaders.Length) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); int w = owner.columnHeaders[index].Width; // Update width before detaching from ListView // in Tile view our ListView uses the column header collection to update the Tile Information - if (owner.IsHandleCreated && this.owner.View != View.Tile) { - int retval = unchecked( (int) (long)owner.SendMessage(NativeMethods.LVM_DELETECOLUMN, index, 0)); + if (owner.IsHandleCreated && this.owner.View != View.Tile) + { + int retval = unchecked((int)(long)owner.SendMessage(NativeMethods.LVM_DELETECOLUMN, index, 0)); if (0 == retval) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } // we need to update the display indices - int[] indices = new int[this.Count-1]; + int[] indices = new int[this.Count - 1]; ColumnHeader removeHdr = this[index]; - for (int i = 0; i < this.Count; i ++) { + for (int i = 0; i < this.Count; i++) + { ColumnHeader hdr = this[i]; - if (i != index) { - if (hdr.DisplayIndex >= removeHdr.DisplayIndex) { - hdr.DisplayIndexInternal --; + if (i != index) + { + if (hdr.DisplayIndex >= removeHdr.DisplayIndex) + { + hdr.DisplayIndexInternal--; } - indices[ i>index ? i-1:i ] = hdr.DisplayIndexInternal; + indices[i > index ? i - 1 : i] = hdr.DisplayIndexInternal; } } @@ -7381,38 +8587,46 @@ public virtual void RemoveAt(int index) { Debug.Assert(columnCount >= 1, "Column mismatch"); if (columnCount == 1) owner.columnHeaders = null; - else { + else + { ColumnHeader[] newHeaders = new ColumnHeader[--columnCount]; if (index > 0) System.Array.Copy(owner.columnHeaders, 0, newHeaders, 0, index); if (index < columnCount) - System.Array.Copy(owner.columnHeaders, index+1, newHeaders, index, columnCount - index); + System.Array.Copy(owner.columnHeaders, index + 1, newHeaders, index, columnCount - index); owner.columnHeaders = newHeaders; } // in Tile view our ListView uses the column header collection to update the Tile Information - if (owner.IsHandleCreated && this.owner.View == View.Tile) { + if (owner.IsHandleCreated && this.owner.View == View.Tile) + { this.owner.RecreateHandleInternal(); } - owner.SetDisplayIndices( indices ); + owner.SetDisplayIndices(indices); } - public virtual void Remove(ColumnHeader column) { + public virtual void Remove(ColumnHeader column) + { int index = IndexOf(column); - if (index != -1) { + if (index != -1) + { RemoveAt(index); } } - void IList.Remove(object value) { - if (value is ColumnHeader) { + void IList.Remove(object value) + { + if (value is ColumnHeader) + { Remove((ColumnHeader)value); } } - public IEnumerator GetEnumerator() { - if (owner.columnHeaders != null) { + public IEnumerator GetEnumerator() + { + if (owner.columnHeaders != null) + { return owner.columnHeaders.GetEnumerator(); } else @@ -7426,7 +8640,8 @@ public IEnumerator GetEnumerator() { /// Represents the collection of items in a ListView or ListViewGroup /// [ListBindable(false)] - public class ListViewItemCollection : IList { + public class ListViewItemCollection : IList + { /// A caching mechanism for key accessor /// We use an index here rather than control so that we don't have lifetime @@ -7437,7 +8652,7 @@ internal interface IInnerList { int Count { get; } bool OwnerIsVirtualListView { get; } - bool OwnerIsDesignMode{ get; } + bool OwnerIsDesignMode { get; } ListViewItem this[int index] { get; set; } ListViewItem Add(ListViewItem item); void AddRange(ListViewItem[] items); @@ -7453,7 +8668,8 @@ internal interface IInnerList private IInnerList innerList; - public ListViewItemCollection(ListView owner) { + public ListViewItemCollection(ListView owner) + { // Kept for APPCOMPAT reasons. // In Whidbey this constructor is a no-op. @@ -7461,12 +8677,14 @@ public ListViewItemCollection(ListView owner) { this.innerList = new ListViewNativeItemCollection(owner); } - internal ListViewItemCollection(IInnerList innerList) { + internal ListViewItemCollection(IInnerList innerList) + { Debug.Assert(innerList != null, "Can't pass in null innerList"); this.innerList = innerList; } - private IInnerList InnerList { + private IInnerList InnerList + { get { return innerList; @@ -7477,32 +8695,42 @@ private IInnerList InnerList { /// Returns the total number of items within the list view. /// [Browsable(false)] - public int Count { - get { + public int Count + { + get + { return InnerList.Count; } } - object ICollection.SyncRoot { - get { + object ICollection.SyncRoot + { + get + { return this; } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return true; } } - bool IList.IsFixedSize { - get { + bool IList.IsFixedSize + { + get + { return false; } } - public bool IsReadOnly { - get { + public bool IsReadOnly + { + get + { return false; } } @@ -7510,16 +8738,21 @@ public bool IsReadOnly { /// /// Returns the ListViewItem at the given index. /// - public virtual ListViewItem this[int index] { - get { - if (index < 0 || index >= InnerList.Count) { + public virtual ListViewItem this[int index] + { + get + { + if (index < 0 || index >= InnerList.Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } return InnerList[index]; } - set { - if (index < 0 || index >= InnerList.Count) { + set + { + if (index < 0 || index >= InnerList.Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } @@ -7527,15 +8760,20 @@ public virtual ListViewItem this[int index] { } } - object IList.this[int index] { - get { + object IList.this[int index] + { + get + { return this[index]; } - set { - if (value is ListViewItem) { + set + { + if (value is ListViewItem) + { this[index] = (ListViewItem)value; } - else if (value != null) { + else if (value != null) + { this[index] = new ListViewItem(value.ToString(), -1); } } @@ -7544,19 +8782,24 @@ object IList.this[int index] { /// /// Retrieves the child control with the specified key. /// - public virtual ListViewItem this[string key] { - get { + public virtual ListViewItem this[string key] + { + get + { // We do not support null and empty string as valid keys. - if (string.IsNullOrEmpty(key)){ + if (string.IsNullOrEmpty(key)) + { return null; } // Search for the key in our collection int index = IndexOfKey(key); - if (IsValidIndex(index)) { + if (IsValidIndex(index)) + { return this[index]; } - else { + else + { return null; } @@ -7568,15 +8811,19 @@ public virtual ListViewItem this[string key] { /// the correct sorted position, or, if no sorting is set, at the end /// of the list. /// - public virtual ListViewItem Add(string text) { + public virtual ListViewItem Add(string text) + { return Add(text, -1); } - int IList.Add(object item) { - if (item is ListViewItem) { + int IList.Add(object item) + { + if (item is ListViewItem) + { return IndexOf(Add((ListViewItem)item)); } - else if (item != null) { + else if (item != null) + { return IndexOf(Add(item.ToString())); } return -1; @@ -7587,7 +8834,8 @@ int IList.Add(object item) { /// the correct sorted position, or, if no sorting is set, at the end /// of the list. /// - public virtual ListViewItem Add(string text, int imageIndex) { + public virtual ListViewItem Add(string text, int imageIndex) + { ListViewItem li = new ListViewItem(text, imageIndex); Add(li); return li; @@ -7598,7 +8846,8 @@ public virtual ListViewItem Add(string text, int imageIndex) { /// the correct sorted position, or, if no sorting is set, at the end /// of the list. /// - public virtual ListViewItem Add(ListViewItem value) { + public virtual ListViewItem Add(ListViewItem value) + { InnerList.Add(value); return value; } @@ -7610,7 +8859,8 @@ public virtual ListViewItem Add(ListViewItem value) { /// the correct sorted position, or, if no sorting is set, at the end /// of the list. /// - public virtual ListViewItem Add(string text, string imageKey) { + public virtual ListViewItem Add(string text, string imageKey) + { ListViewItem li = new ListViewItem(text, imageKey); Add(li); return li; @@ -7621,7 +8871,8 @@ public virtual ListViewItem Add(string text, string imageKey) { /// the correct sorted position, or, if no sorting is set, at the end /// of the list. /// - public virtual ListViewItem Add(string key, string text, string imageKey) { + public virtual ListViewItem Add(string key, string text, string imageKey) + { ListViewItem li = new ListViewItem(text, imageKey); li.Name = key; Add(li); @@ -7633,7 +8884,8 @@ public virtual ListViewItem Add(string key, string text, string imageKey) { /// the correct sorted position, or, if no sorting is set, at the end /// of the list. /// - public virtual ListViewItem Add(string key, string text, int imageIndex) { + public virtual ListViewItem Add(string key, string text, int imageIndex) + { ListViewItem li = new ListViewItem(text, imageIndex); li.Name = key; Add(li); @@ -7643,16 +8895,20 @@ public virtual ListViewItem Add(string key, string text, int imageIndex) { // END - NEW ADD OVERLOADS IN WHIDBEY --> - public void AddRange(ListViewItem[] items) { - if (items == null) { + public void AddRange(ListViewItem[] items) + { + if (items == null) + { throw new ArgumentNullException(nameof(items)); } InnerList.AddRange(items); } - public void AddRange(ListViewItemCollection items) { - if (items == null) { + public void AddRange(ListViewItemCollection items) + { + if (items == null) + { throw new ArgumentNullException(nameof(items)); } @@ -7664,31 +8920,38 @@ public void AddRange(ListViewItemCollection items) { /// /// Removes all items from the list view. /// - public virtual void Clear() { + public virtual void Clear() + { InnerList.Clear(); } - public bool Contains(ListViewItem item) { + public bool Contains(ListViewItem item) + { return InnerList.Contains(item); } - bool IList.Contains(object item) { - if (item is ListViewItem) { + bool IList.Contains(object item) + { + if (item is ListViewItem) + { return Contains((ListViewItem)item); } - else { + else + { return false; } } - /// - /// Returns true if the collection contains an item with the specified key, false otherwise. - /// - public virtual bool ContainsKey(string key) { - return IsValidIndex(IndexOfKey(key)); - } + /// + /// Returns true if the collection contains an item with the specified key, false otherwise. + /// + public virtual bool ContainsKey(string key) + { + return IsValidIndex(IndexOfKey(key)); + } - public void CopyTo(Array dest, int index) { + public void CopyTo(Array dest, int index) + { InnerList.CopyTo(dest, index); } @@ -7697,10 +8960,11 @@ public void CopyTo(Array dest, int index) { /// of all the controls that match. /// /// - public ListViewItem[] Find (string key, bool searchAllSubItems) { - ArrayList foundItems = FindInternal(key, searchAllSubItems, this, new ArrayList()); + public ListViewItem[] Find(string key, bool searchAllSubItems) + { + ArrayList foundItems = FindInternal(key, searchAllSubItems, this, new ArrayList()); - ListViewItem[] stronglyTypedFoundItems= new ListViewItem[foundItems.Count]; + ListViewItem[] stronglyTypedFoundItems = new ListViewItem[foundItems.Count]; foundItems.CopyTo(stronglyTypedFoundItems, 0); return stronglyTypedFoundItems; @@ -7711,77 +8975,98 @@ public ListViewItem[] Find (string key, bool searchAllSubItems) { /// of all the controls that match. /// /// - private ArrayList FindInternal(string key, bool searchAllSubItems, ListViewItemCollection listViewItems, ArrayList foundItems) { - if ((listViewItems == null) || (foundItems == null)) { - return null; // - } - - for (int i = 0; i < listViewItems.Count; i++) { - - if (WindowsFormsUtils.SafeCompareStrings(listViewItems[i].Name, key, /* ignoreCase = */ true)) { - foundItems.Add(listViewItems[i]); - } - else { - if (searchAllSubItems) { - // start from 1, as we've already compared subitems[0] - for(int j = 1; j < listViewItems[i].SubItems.Count; j++) { - if (WindowsFormsUtils.SafeCompareStrings(listViewItems[i].SubItems[j].Name, key, /* ignoreCase = */ true)) { - foundItems.Add(listViewItems[i]); - break; - } - } - } - } - } - - return foundItems; - } - - public IEnumerator GetEnumerator() { - if (this.InnerList.OwnerIsVirtualListView && !this.InnerList.OwnerIsDesignMode) { + private ArrayList FindInternal(string key, bool searchAllSubItems, ListViewItemCollection listViewItems, ArrayList foundItems) + { + if ((listViewItems == null) || (foundItems == null)) + { + return null; // + } + + for (int i = 0; i < listViewItems.Count; i++) + { + + if (WindowsFormsUtils.SafeCompareStrings(listViewItems[i].Name, key, /* ignoreCase = */ true)) + { + foundItems.Add(listViewItems[i]); + } + else + { + if (searchAllSubItems) + { + // start from 1, as we've already compared subitems[0] + for (int j = 1; j < listViewItems[i].SubItems.Count; j++) + { + if (WindowsFormsUtils.SafeCompareStrings(listViewItems[i].SubItems[j].Name, key, /* ignoreCase = */ true)) + { + foundItems.Add(listViewItems[i]); + break; + } + } + } + } + } + + return foundItems; + } + + public IEnumerator GetEnumerator() + { + if (this.InnerList.OwnerIsVirtualListView && !this.InnerList.OwnerIsDesignMode) + { // Throw the exception only at runtime. throw new InvalidOperationException(SR.ListViewCantGetEnumeratorInVirtualMode); } return InnerList.GetEnumerator(); } - public int IndexOf(ListViewItem item) { - for(int index=0; index < Count; ++index) { - if (this[index] == item) { + public int IndexOf(ListViewItem item) + { + for (int index = 0; index < Count; ++index) + { + if (this[index] == item) + { return index; } } return -1; } - int IList.IndexOf(object item) { - if (item is ListViewItem) { + int IList.IndexOf(object item) + { + if (item is ListViewItem) + { return IndexOf((ListViewItem)item); } - else { + else + { return -1; } } /// /// The zero-based index of the first occurrence of value within the entire CollectionBase, if found; otherwise, -1. /// - public virtual int IndexOfKey(string key) { - // Step 0 - Arg validation - if (string.IsNullOrEmpty(key)){ - return -1; // we dont support empty or null keys. - } + public virtual int IndexOfKey(string key) + { + // Step 0 - Arg validation + if (string.IsNullOrEmpty(key)) + { + return -1; // we dont support empty or null keys. + } // step 1 - check the last cached item if (IsValidIndex(lastAccessedIndex)) { - if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) { + if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) + { return lastAccessedIndex; } } // step 2 - search for the item - for (int i = 0; i < this.Count; i ++) { - if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { + for (int i = 0; i < this.Count; i++) + { + if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) + { lastAccessedIndex = i; return i; } @@ -7790,53 +9075,64 @@ public virtual int IndexOfKey(string key) { // step 3 - we didn't find it. Invalidate the last accessed index and return -1. lastAccessedIndex = -1; return -1; - } + } - /// - /// Determines if the index is valid for the collection. - /// - private bool IsValidIndex(int index) { - return ((index >= 0) && (index < this.Count)); - } + /// + /// Determines if the index is valid for the collection. + /// + private bool IsValidIndex(int index) + { + return ((index >= 0) && (index < this.Count)); + } - public ListViewItem Insert(int index, ListViewItem item) { - if (index < 0 || index > Count) { + public ListViewItem Insert(int index, ListViewItem item) + { + if (index < 0 || index > Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } InnerList.Insert(index, item); return item; } - public ListViewItem Insert(int index, string text) { + public ListViewItem Insert(int index, string text) + { return Insert(index, new ListViewItem(text)); } - public ListViewItem Insert(int index, string text, int imageIndex) { + public ListViewItem Insert(int index, string text, int imageIndex) + { return Insert(index, new ListViewItem(text, imageIndex)); } - void IList.Insert(int index, object item) { - if (item is ListViewItem) { + void IList.Insert(int index, object item) + { + if (item is ListViewItem) + { Insert(index, (ListViewItem)item); } - else if (item != null) { + else if (item != null) + { Insert(index, item.ToString()); } } // <-- NEW INSERT OVERLOADS IN WHIDBEY - public ListViewItem Insert(int index, string text, string imageKey) { + public ListViewItem Insert(int index, string text, string imageKey) + { return Insert(index, new ListViewItem(text, imageKey)); } - public virtual ListViewItem Insert(int index, string key, string text, string imageKey) { + public virtual ListViewItem Insert(int index, string key, string text, string imageKey) + { ListViewItem li = new ListViewItem(text, imageKey); li.Name = key; return Insert(index, li); } - public virtual ListViewItem Insert(int index, string key, string text, int imageIndex) { + public virtual ListViewItem Insert(int index, string key, string text, int imageIndex) + { ListViewItem li = new ListViewItem(text, imageIndex); li.Name = key; return Insert(index, li); @@ -7847,15 +9143,18 @@ public virtual ListViewItem Insert(int index, string key, string text, int image /// /// Removes an item from the ListView /// - public virtual void Remove(ListViewItem item) { + public virtual void Remove(ListViewItem item) + { InnerList.Remove(item); } /// /// Removes an item from the ListView /// - public virtual void RemoveAt(int index) { - if (index < 0 || index >= Count) { + public virtual void RemoveAt(int index) + { + if (index < 0 || index >= Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } @@ -7865,15 +9164,19 @@ public virtual void RemoveAt(int index) { /// /// Removes the child control with the specified key. /// - public virtual void RemoveByKey(string key) { + public virtual void RemoveByKey(string key) + { int index = IndexOfKey(key); - if (IsValidIndex(index)) { + if (IsValidIndex(index)) + { RemoveAt(index); - } + } } - void IList.Remove(object item) { - if (item == null || !(item is ListViewItem)) { + void IList.Remove(object item) + { + if (item == null || !(item is ListViewItem)) + { return; } @@ -7884,42 +9187,55 @@ void IList.Remove(object item) { // Overrides ListViewItemCollection methods and properties to automatically update // the native listview. // - internal class ListViewNativeItemCollection : ListViewItemCollection.IInnerList { + internal class ListViewNativeItemCollection : ListViewItemCollection.IInnerList + { private ListView owner; - public ListViewNativeItemCollection(ListView owner) { + public ListViewNativeItemCollection(ListView owner) + { this.owner = owner; } - public int Count { - get { + public int Count + { + get + { owner.ApplyUpdateCachedItems(); - if (owner.VirtualMode) { + if (owner.VirtualMode) + { return owner.VirtualListSize; } - else { + else + { return owner.itemCount; } } } - public bool OwnerIsVirtualListView { - get { + public bool OwnerIsVirtualListView + { + get + { return owner.VirtualMode; } } - public bool OwnerIsDesignMode { - get { + public bool OwnerIsDesignMode + { + get + { return owner.DesignMode; } } - public ListViewItem this[int displayIndex] { - get { + public ListViewItem this[int displayIndex] + { + get + { owner.ApplyUpdateCachedItems(); - if (owner.VirtualMode) { + if (owner.VirtualMode) + { // if we are showing virtual items, we need to get the item from the user RetrieveVirtualItemEventArgs rVI = new RetrieveVirtualItemEventArgs(displayIndex); @@ -7927,29 +9243,35 @@ public ListViewItem this[int displayIndex] { rVI.Item.SetItemIndex(this.owner, displayIndex); return rVI.Item; } - else { + else + { if (displayIndex < 0 || displayIndex >= owner.itemCount) throw new ArgumentOutOfRangeException(nameof(displayIndex), displayIndex, string.Format(SR.InvalidArgument, nameof(displayIndex), displayIndex)); - if (owner.IsHandleCreated && !owner.ListViewHandleDestroyed) { + if (owner.IsHandleCreated && !owner.ListViewHandleDestroyed) + { return (ListViewItem)owner.listItemsTable[DisplayIndexToID(displayIndex)]; } - else { + else + { Debug.Assert(owner.listItemsArray != null, "listItemsArray is null, but the handle isn't created"); return (ListViewItem)owner.listItemsArray[displayIndex]; } } } - set { + set + { owner.ApplyUpdateCachedItems(); - if (owner.VirtualMode) { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantModifyTheItemCollInAVirtualListView); } if (displayIndex < 0 || displayIndex >= owner.itemCount) throw new ArgumentOutOfRangeException(nameof(displayIndex), displayIndex, string.Format(SR.InvalidArgument, nameof(displayIndex), displayIndex)); - if (this.owner.ExpectingMouseUp) { + if (this.owner.ExpectingMouseUp) + { this.owner.ItemCollectionChangedInMouseDown = true; } @@ -7958,10 +9280,14 @@ public ListViewItem this[int displayIndex] { } } - public ListViewItem Add(ListViewItem value) { - if (owner.VirtualMode) { + public ListViewItem Add(ListViewItem value) + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAddItemsToAVirtualListView); - } else { + } + else + { Debug.Assert(!this.owner.FlipViewToLargeIconAndSmallIcon || this.Count == 0, "the FlipView... bit is turned off after adding 1 item."); // PERF. @@ -7969,13 +9295,15 @@ public ListViewItem Add(ListViewItem value) { // This saves a call into NativeListView to retrieve the real index. bool valueChecked = value.Checked; - owner.InsertItems(owner.itemCount, new ListViewItem[]{value}, true); + owner.InsertItems(owner.itemCount, new ListViewItem[] { value }, true); - if (owner.IsHandleCreated && !owner.CheckBoxes && valueChecked) { + if (owner.IsHandleCreated && !owner.CheckBoxes && valueChecked) + { owner.UpdateSavedCheckedItems(value, true /*addItem*/); } - if (this.owner.ExpectingMouseUp) { + if (this.owner.ExpectingMouseUp) + { this.owner.ItemCollectionChangedInMouseDown = true; } @@ -7983,12 +9311,15 @@ public ListViewItem Add(ListViewItem value) { } } - public void AddRange(ListViewItem[] values) { - if (values == null) { + public void AddRange(ListViewItem[] values) + { + if (values == null) + { throw new ArgumentNullException(nameof(values)); } - if (owner.VirtualMode) { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAddItemsToAVirtualListView); } @@ -7998,54 +9329,65 @@ public void AddRange(ListViewItem[] values) { Debug.Assert(!this.owner.FlipViewToLargeIconAndSmallIcon || this.Count == 0, "the FlipView... bit is turned off after adding 1 item."); bool[] checkedValues = null; - - if (owner.IsHandleCreated && !owner.CheckBoxes) { + + if (owner.IsHandleCreated && !owner.CheckBoxes) + { // PERF. // Cache the Checked bit before adding the item to the list view. // This saves a bunch of calls to native list view when we want to UpdateSavedCheckedItems. // checkedValues = new bool[values.Length]; - for (int i = 0; i < values.Length; i ++) { + for (int i = 0; i < values.Length; i++) + { checkedValues[i] = values[i].Checked; } } - try { + try + { owner.BeginUpdate(); owner.InsertItems(owner.itemCount, values, true); - if (owner.IsHandleCreated && !owner.CheckBoxes) { - for (int i = 0; i < values.Length; i ++) { - if (checkedValues[i]) { + if (owner.IsHandleCreated && !owner.CheckBoxes) + { + for (int i = 0; i < values.Length; i++) + { + if (checkedValues[i]) + { owner.UpdateSavedCheckedItems(values[i], true /*addItem*/); } } } - + } - finally { + finally + { owner.listItemSorter = comparer; owner.EndUpdate(); } - if (this.owner.ExpectingMouseUp) { + if (this.owner.ExpectingMouseUp) + { this.owner.ItemCollectionChangedInMouseDown = true; } - if (comparer != null || (owner.Sorting != SortOrder.None) && !owner.VirtualMode) { + if (comparer != null || (owner.Sorting != SortOrder.None) && !owner.VirtualMode) + { owner.Sort(); } } - private int DisplayIndexToID(int displayIndex) { + private int DisplayIndexToID(int displayIndex) + { Debug.Assert(!owner.VirtualMode, "in virtual mode, this method does not make any sense"); - if (owner.IsHandleCreated && !owner.ListViewHandleDestroyed) { + if (owner.IsHandleCreated && !owner.ListViewHandleDestroyed) + { // Obtain internal index of the item NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM(); lvItem.mask = NativeMethods.LVIF_PARAM; lvItem.iItem = displayIndex; UnsafeNativeMethods.SendMessage(new HandleRef(owner, owner.Handle), NativeMethods.LVM_GETITEM, 0, ref lvItem); - return (int) lvItem.lParam; + return (int)lvItem.lParam; } else { @@ -8053,29 +9395,36 @@ private int DisplayIndexToID(int displayIndex) { } } - public void Clear() { - if (owner.itemCount > 0) { + public void Clear() + { + if (owner.itemCount > 0) + { owner.ApplyUpdateCachedItems(); - if (owner.IsHandleCreated && !owner.ListViewHandleDestroyed) { + if (owner.IsHandleCreated && !owner.ListViewHandleDestroyed) + { // walk the items to see which ones are selected. // we use the LVM_GETNEXTITEM message to see what the next selected item is // so we can avoid checking selection for each one. // int count = owner.Items.Count; int nextSelected = (int)UnsafeNativeMethods.SendMessage(new HandleRef(owner, owner.Handle), NativeMethods.LVM_GETNEXTITEM, -1, NativeMethods.LVNI_SELECTED); - for (int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) + { ListViewItem item = owner.Items[i]; Debug.Assert(item != null, "Failed to get item at index " + i.ToString(CultureInfo.InvariantCulture)); - if (item != null) { + if (item != null) + { // if it's the one we're looking for, ask for the next one // - if (i == nextSelected) { + if (i == nextSelected) + { item.StateSelected = true; nextSelected = (int)UnsafeNativeMethods.SendMessage(new HandleRef(owner, owner.Handle), NativeMethods.LVM_GETNEXTITEM, nextSelected, NativeMethods.LVNI_SELECTED); } - else { + else + { // otherwise it's false // item.StateSelected = false; @@ -8090,119 +9439,147 @@ public void Clear() { // There's a problem in the list view that if it's in small icon, it won't pick upo the small icon // sizes until it changes from large icon, so we flip it twice here... // - if (owner.View == View.SmallIcon) { - if (this.owner.ComctlSupportsVisualStyles) { + if (owner.View == View.SmallIcon) + { + if (this.owner.ComctlSupportsVisualStyles) + { this.owner.FlipViewToLargeIconAndSmallIcon = true; - } else { + } + else + { Debug.Assert(!this.owner.FlipViewToLargeIconAndSmallIcon, "we only set this when comctl 6.0 is loaded"); owner.View = View.LargeIcon; owner.View = View.SmallIcon; } } } - else { + else + { - int count = owner.Items.Count; + int count = owner.Items.Count; - for (int i = 0; i < count; i++) { - ListViewItem item = owner.Items[i]; - if (item != null) { - item.UnHost(i, true); - } - } + for (int i = 0; i < count; i++) + { + ListViewItem item = owner.Items[i]; + if (item != null) + { + item.UnHost(i, true); + } + } - Debug.Assert(owner.listItemsArray != null, "listItemsArray is null, but the handle isn't created"); - owner.listItemsArray.Clear(); + Debug.Assert(owner.listItemsArray != null, "listItemsArray is null, but the handle isn't created"); + owner.listItemsArray.Clear(); } owner.listItemsTable.Clear(); - if (owner.IsHandleCreated && !owner.CheckBoxes) { + if (owner.IsHandleCreated && !owner.CheckBoxes) + { owner.savedCheckedItems = null; } owner.itemCount = 0; - if (this.owner.ExpectingMouseUp) { + if (this.owner.ExpectingMouseUp) + { this.owner.ItemCollectionChangedInMouseDown = true; } } } - public bool Contains(ListViewItem item) { + public bool Contains(ListViewItem item) + { owner.ApplyUpdateCachedItems(); - if (owner.IsHandleCreated && !owner.ListViewHandleDestroyed) { + if (owner.IsHandleCreated && !owner.ListViewHandleDestroyed) + { return owner.listItemsTable[item.ID] == item; } - else { + else + { Debug.Assert(owner.listItemsArray != null, "listItemsArray is null, but the handle isn't created"); return owner.listItemsArray.Contains(item); } } - public ListViewItem Insert(int index, ListViewItem item) { + public ListViewItem Insert(int index, ListViewItem item) + { int count = 0; - if (owner.VirtualMode) { + if (owner.VirtualMode) + { count = Count; } - else { + else + { count = owner.itemCount; } - if (index < 0 || index > count) { + if (index < 0 || index > count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - if (owner.VirtualMode) { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantAddItemsToAVirtualListView); } Debug.Assert(!this.owner.FlipViewToLargeIconAndSmallIcon || this.Count == 0, "the FlipView... bit is turned off after adding 1 item."); - if (index < count) { + if (index < count) + { // if we're not inserting at the end, force the add. // owner.ApplyUpdateCachedItems(); } - owner.InsertItems(index, new ListViewItem[]{item}, true); - if (owner.IsHandleCreated && !owner.CheckBoxes && item.Checked) { + owner.InsertItems(index, new ListViewItem[] { item }, true); + if (owner.IsHandleCreated && !owner.CheckBoxes && item.Checked) + { owner.UpdateSavedCheckedItems(item, true /*addItem*/); } - if (this.owner.ExpectingMouseUp) { + if (this.owner.ExpectingMouseUp) + { this.owner.ItemCollectionChangedInMouseDown = true; } return item; } - public int IndexOf(ListViewItem item) { + public int IndexOf(ListViewItem item) + { Debug.Assert(!owner.VirtualMode, "in virtual mode, this function does not make any sense"); - for(int i=0; i < Count; i++) { - if (item == this[i]) { + for (int i = 0; i < Count; i++) + { + if (item == this[i]) + { return i; } } return -1; } - public void Remove(ListViewItem item) { + public void Remove(ListViewItem item) + { int index = owner.VirtualMode ? Count - 1 : IndexOf(item); Debug.Assert(!this.owner.FlipViewToLargeIconAndSmallIcon || this.Count == 0, "the FlipView... bit is turned off after adding 1 item."); - if (owner.VirtualMode) { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantRemoveItemsFromAVirtualListView); } - - if (index != -1) { + + if (index != -1) + { RemoveAt(index); } } - public void RemoveAt(int index) { - if (owner.VirtualMode) { + public void RemoveAt(int index) + { + if (owner.VirtualMode) + { throw new InvalidOperationException(SR.ListViewCantRemoveItemsFromAVirtualListView); } @@ -8210,8 +9587,9 @@ public void RemoveAt(int index) { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); Debug.Assert(!this.owner.FlipViewToLargeIconAndSmallIcon || this.Count == 0, "the FlipView... bit is turned off after adding 1 item."); - - if (owner.IsHandleCreated && !owner.CheckBoxes && this[index].Checked) { + + if (owner.IsHandleCreated && !owner.CheckBoxes && this[index].Checked) + { owner.UpdateSavedCheckedItems(this[index], false /*addItem*/); } @@ -8219,15 +9597,17 @@ public void RemoveAt(int index) { int itemID = DisplayIndexToID(index); this[index].UnHost(true); - if (owner.IsHandleCreated) { + if (owner.IsHandleCreated) + { Debug.Assert(owner.listItemsArray == null, "listItemsArray not null, even though handle created"); - int retval = unchecked( (int) (long)owner.SendMessage(NativeMethods.LVM_DELETEITEM, index, 0)); + int retval = unchecked((int)(long)owner.SendMessage(NativeMethods.LVM_DELETEITEM, index, 0)); if (0 == retval) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - else { + else + { Debug.Assert(owner.listItemsArray != null, "listItemsArray is null, but the handle isn't created"); owner.listItemsArray.RemoveAt(index); } @@ -8235,21 +9615,26 @@ public void RemoveAt(int index) { owner.itemCount--; owner.listItemsTable.Remove(itemID); - if (this.owner.ExpectingMouseUp) { + if (this.owner.ExpectingMouseUp) + { this.owner.ItemCollectionChangedInMouseDown = true; } } - public void CopyTo(Array dest, int index) { - if (owner.itemCount > 0) { - for(int displayIndex=0; displayIndex < Count; ++displayIndex) { + public void CopyTo(Array dest, int index) + { + if (owner.itemCount > 0) + { + for (int displayIndex = 0; displayIndex < Count; ++displayIndex) + { dest.SetValue(this[displayIndex], index++); } } } - public IEnumerator GetEnumerator() { + public IEnumerator GetEnumerator() + { ListViewItem[] items = new ListViewItem[this.owner.itemCount]; this.CopyTo(items, 0); @@ -8266,30 +9651,37 @@ public IEnumerator GetEnumerator() { /// /// The AccessibleObject for this ListView instance. /// - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new ListViewAccessibleObject(this); } - internal class ListViewAccessibleObject : ControlAccessibleObject { + internal class ListViewAccessibleObject : ControlAccessibleObject + { private ListView owner; - internal ListViewAccessibleObject(ListView owner) : base(owner) { + internal ListViewAccessibleObject(ListView owner) : base(owner) + { this.owner = owner; } internal override bool IsIAccessibleExSupported() { - if (owner != null) { + if (owner != null) + { return true; } return base.IsIAccessibleExSupported(); } - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_ItemStatusPropertyId) { - switch (owner.Sorting) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_ItemStatusPropertyId) + { + switch (owner.Sorting) + { case SortOrder.None: return SR.NotSortedAccessibleStatus; case SortOrder.Ascending: diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupCollection.cs index f3a7129787a..bb19ba7b68c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupCollection.cs @@ -83,7 +83,7 @@ public ListViewGroup this[string key] if (_list == null) { - // nothing to do + // nothing to do return; } @@ -153,7 +153,7 @@ int IList.Add(object value) { throw new ArgumentException(SR.ListViewGroupCollectionBadListViewGroup, nameof(value)); } - + return Add(group); } @@ -210,7 +210,7 @@ public void Clear() { this[i].ListView = null; } - + List.Clear(); // we have to tell the listView that there are no more groups diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupConverter.cs index 41b8017ea78..3301d62beef 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupConverter.cs @@ -62,7 +62,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c ListViewItem item = context.Instance as ListViewItem; if (item != null && item.ListView != null) { - foreach(ListViewGroup group in item.ListView.Groups) + foreach (ListViewGroup group in item.ListView.Groups) { if (group.Header == text) { @@ -101,7 +101,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul ConstructorInfo ctor; // Header - ctor = typeof(ListViewGroup).GetConstructor(new Type[] {typeof(string), typeof(HorizontalAlignment)}); + ctor = typeof(ListViewGroup).GetConstructor(new Type[] { typeof(string), typeof(HorizontalAlignment) }); Debug.Assert(ctor != null, "Expected the constructor to exist."); return new InstanceDescriptor(ctor, new object[] { group.Header, group.HeaderAlignment }, false); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewHitTestInfo.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewHitTestInfo.cs index 22a23f821f2..e22bdb1f4fb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewHitTestInfo.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewHitTestInfo.cs @@ -2,18 +2,20 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; using System; - - + + /// /// /// Specifies the return value for HITTEST on ListView. /// /// - public class ListViewHitTestInfo { + public class ListViewHitTestInfo + { private ListViewHitTestLocations loc; private ListViewItem item; @@ -22,36 +24,43 @@ public class ListViewHitTestInfo { /// /// Creates a ListViewHitTestInfo instance. /// - public ListViewHitTestInfo(ListViewItem hitItem, ListViewItem.ListViewSubItem hitSubItem, ListViewHitTestLocations hitLocation) { + public ListViewHitTestInfo(ListViewItem hitItem, ListViewItem.ListViewSubItem hitSubItem, ListViewHitTestLocations hitLocation) + { this.item = hitItem; this.subItem = hitSubItem; this.loc = hitLocation; } - + /// /// This gives the exact location returned by hit test on listview. /// - public ListViewHitTestLocations Location { - get { + public ListViewHitTestLocations Location + { + get + { return loc; } } - + /// /// This gives the ListViewItem returned by hit test on listview. /// - public ListViewItem Item { - get { + public ListViewItem Item + { + get + { return item; } } - + /// /// This gives the ListViewSubItem returned by hit test on listview. /// - public ListViewItem.ListViewSubItem SubItem { - get { + public ListViewItem.ListViewSubItem SubItem + { + get + { return subItem; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewInsertionMark.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewInsertionMark.cs index 92f7afa6605..ce1a581b077 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewInsertionMark.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewInsertionMark.cs @@ -6,7 +6,8 @@ using System.Runtime.InteropServices; using System.Diagnostics; -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ /// /// @@ -14,14 +15,15 @@ namespace System.Windows.Forms { /// /// public sealed class ListViewInsertionMark - { + { private ListView listView; - + private int index = 0; private Color color = Color.Empty; private bool appearsAfterItem = false; - internal ListViewInsertionMark(ListView listView) { + internal ListViewInsertionMark(ListView listView) + { this.listView = listView; } @@ -31,28 +33,32 @@ internal ListViewInsertionMark(ListView listView) { /// before the item (the default). /// /// - public bool AppearsAfterItem { + public bool AppearsAfterItem + { get { return appearsAfterItem; } set { - if (appearsAfterItem != value) { + if (appearsAfterItem != value) + { appearsAfterItem = value; - if (listView.IsHandleCreated) { + if (listView.IsHandleCreated) + { UpdateListView(); } } } } - + /// /// Returns bounds of the insertion-mark. /// /// - public Rectangle Bounds { + public Rectangle Bounds + { get { NativeMethods.RECT rect = new NativeMethods.RECT(); @@ -60,56 +66,63 @@ public Rectangle Bounds { return Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom); } } - + /// /// The color of the insertion-mark. /// /// - public Color Color { - get + public Color Color + { + get { - if (color.IsEmpty) { + if (color.IsEmpty) + { color = SafeNativeMethods.ColorFromCOLORREF((int)listView.SendMessage(NativeMethods.LVM_GETINSERTMARKCOLOR, 0, 0)); } return color; - } + } set { - if (color != value) { + if (color != value) + { color = value; - if (listView.IsHandleCreated) { + if (listView.IsHandleCreated) + { listView.SendMessage(NativeMethods.LVM_SETINSERTMARKCOLOR, 0, SafeNativeMethods.ColorToCOLORREF(color)); } } } } - + /// /// Item next to which the insertion-mark appears. /// /// - public int Index { + public int Index + { get { return index; } set { - if (index != value) { + if (index != value) + { index = value; - if (listView.IsHandleCreated) { + if (listView.IsHandleCreated) + { UpdateListView(); } } } - } - + } + /// /// Performs a hit-test at the specified insertion point - /// and returns the closest item. + /// and returns the closest item. /// /// - public int NearestIndex(Point pt) + public int NearestIndex(Point pt) { NativeMethods.POINT point = new NativeMethods.POINT(); point.x = pt.X; @@ -119,18 +132,20 @@ public int NearestIndex(Point pt) UnsafeNativeMethods.SendMessage(new HandleRef(listView, listView.Handle), NativeMethods.LVM_INSERTMARKHITTEST, point, lvInsertMark); return lvInsertMark.iItem; - } + } - internal void UpdateListView() { + internal void UpdateListView() + { Debug.Assert(listView.IsHandleCreated, "ApplySavedState Precondition: List-view handle must be created"); - NativeMethods.LVINSERTMARK lvInsertMark = new NativeMethods.LVINSERTMARK(); + NativeMethods.LVINSERTMARK lvInsertMark = new NativeMethods.LVINSERTMARK(); lvInsertMark.dwFlags = appearsAfterItem ? NativeMethods.LVIM_AFTER : 0; lvInsertMark.iItem = index; UnsafeNativeMethods.SendMessage(new HandleRef(listView, listView.Handle), NativeMethods.LVM_SETINSERTMARK, 0, lvInsertMark); - if (!color.IsEmpty) { + if (!color.IsEmpty) + { listView.SendMessage(NativeMethods.LVM_SETINSERTMARKCOLOR, 0, SafeNativeMethods.ColorToCOLORREF(color)); - } + } } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItem.cs index ae6482e4c1a..14569bf9a30 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItem.cs @@ -1117,7 +1117,7 @@ internal void UpdateStateFromListView(int displayIndex, bool checkSelection) } } - internal void UnHost(bool checkSelection) => UnHost(Index, checkSelection); + internal void UnHost(bool checkSelection) => UnHost(Index, checkSelection); internal void UnHost(int displayIndex, bool checkSelection) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItemMouseHoverEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItemMouseHoverEventArgs.cs index 7f26f42758c..51036f8dbdd 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItemMouseHoverEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItemMouseHoverEventArgs.cs @@ -16,7 +16,7 @@ public ListViewItemMouseHoverEventArgs(ListViewItem item) { Item = item; } - + public ListViewItem Item { get; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItemState.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItemState.cs index 478826ae533..23bcb7f676a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItemState.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItemState.cs @@ -8,7 +8,7 @@ namespace System.Windows.Forms /// Gives state information about a ListView item/sub-item. Used with owner draw. /// [Flags] - public enum ListViewItemStates + public enum ListViewItemStates { Checked = NativeMethods.CDIS_CHECKED, Default = NativeMethods.CDIS_DEFAULT, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItemStateImageIndexConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItemStateImageIndexConverter.cs index 23114f0830d..86ee376a1f2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItemStateImageIndexConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItemStateImageIndexConverter.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System.Collections; @@ -16,13 +17,16 @@ namespace System.Windows.Forms { /// ListViewItemStateImageIndexConverter is a class that can be used to convert /// image index values one data type to another. /// - public class ListViewItemStateImageIndexConverter : ImageIndexConverter { + public class ListViewItemStateImageIndexConverter : ImageIndexConverter + { - protected override bool IncludeNoneAsStandardValue { - get { + protected override bool IncludeNoneAsStandardValue + { + get + { return false; } - } + } /// @@ -31,63 +35,74 @@ protected override bool IncludeNoneAsStandardValue { /// will return null if the data type does not support a /// standard set of values. /// - public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { - if (context != null && context.Instance != null) { + public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) + { + if (context != null && context.Instance != null) + { object instance = context.Instance; ImageList imageList = null; - PropertyDescriptorCollection listViewItemProps = TypeDescriptor.GetProperties(instance); + PropertyDescriptorCollection listViewItemProps = TypeDescriptor.GetProperties(instance); PropertyDescriptor listViewProp = listViewItemProps["ListView"]; - if (listViewProp != null) { - // Grab the ListView property off of the TreeNode. - object listViewInstance = listViewProp.GetValue(instance); - - if (listViewInstance != null) { - // Get the ImageList property from the ListView and set it to be the currentImageList. - PropertyDescriptorCollection listViewProps = TypeDescriptor.GetProperties(listViewInstance); - PropertyDescriptor listViewImageListProperty = listViewProps["StateImageList"]; - if (listViewImageListProperty != null) { - imageList = (ImageList)listViewImageListProperty.GetValue(listViewInstance); - } + if (listViewProp != null) + { + // Grab the ListView property off of the TreeNode. + object listViewInstance = listViewProp.GetValue(instance); + + if (listViewInstance != null) + { + // Get the ImageList property from the ListView and set it to be the currentImageList. + PropertyDescriptorCollection listViewProps = TypeDescriptor.GetProperties(listViewInstance); + PropertyDescriptor listViewImageListProperty = listViewProps["StateImageList"]; + if (listViewImageListProperty != null) + { + imageList = (ImageList)listViewImageListProperty.GetValue(listViewInstance); } - } - - if (imageList != null) { - + } + } + + if (imageList != null) + { + // Create array to contain standard values // object[] values; int nImages = imageList.Images.Count; - if (IncludeNoneAsStandardValue) { + if (IncludeNoneAsStandardValue) + { values = new object[nImages + 1]; values[nImages] = -1; } - else { + else + { values = new object[nImages]; } - - + + // Fill in the array // - for (int i = 0; i < nImages; i++) { + for (int i = 0; i < nImages; i++) + { values[i] = i; } - + return new StandardValuesCollection(values); } - + } - if (IncludeNoneAsStandardValue) { - return new StandardValuesCollection(new object[] {-1}); + if (IncludeNoneAsStandardValue) + { + return new StandardValuesCollection(new object[] { -1 }); } - else { + else + { return new StandardValuesCollection(new object[0]); } - + } - + } } \ No newline at end of file diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/LocalAppContextSwitches.cs b/src/System.Windows.Forms/src/System/Windows/Forms/LocalAppContextSwitches.cs index 9dfc0bc3a96..5ce0dcd15fa 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/LocalAppContextSwitches.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/LocalAppContextSwitches.cs @@ -2,10 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.CompilerServices; - internal static class LocalAppContextSwitches { + internal static class LocalAppContextSwitches + { internal const string DontSupportReentrantFilterMessageSwitchName = @"Switch.System.Windows.Forms.DontSupportReentrantFilterMessage"; internal const string DoNotSupportSelectAllShortcutInMultilineTextBoxSwitchName = @"Switch.System.Windows.Forms.DoNotSupportSelectAllShortcutInMultilineTextBox"; internal const string DoNotLoadLatestRichEditControlSwitchName = @"Switch.System.Windows.Forms.DoNotLoadLatestRichEditControl"; @@ -23,58 +25,74 @@ internal static class LocalAppContextSwitches { private static int _useLegacyImages; private static int _enableVisualStyleValidation; - public static bool DontSupportReentrantFilterMessage { + public static bool DontSupportReentrantFilterMessage + { [MethodImpl(MethodImplOptions.AggressiveInlining)] - get { + get + { return LocalAppContext.GetCachedSwitchValue(LocalAppContextSwitches.DontSupportReentrantFilterMessageSwitchName, ref _dontSupportReentrantFilterMessage); } } - public static bool DoNotSupportSelectAllShortcutInMultilineTextBox { + public static bool DoNotSupportSelectAllShortcutInMultilineTextBox + { [MethodImpl(MethodImplOptions.AggressiveInlining)] - get { + get + { return LocalAppContext.GetCachedSwitchValue(LocalAppContextSwitches.DoNotSupportSelectAllShortcutInMultilineTextBoxSwitchName, ref _doNotSupportSelectAllShortcutInMultilineTextBox); } } - public static bool DoNotLoadLatestRichEditControl { + public static bool DoNotLoadLatestRichEditControl + { [MethodImpl(MethodImplOptions.AggressiveInlining)] - get { + get + { return LocalAppContext.GetCachedSwitchValue(LocalAppContextSwitches.DoNotLoadLatestRichEditControlSwitchName, ref _doNotLoadLatestRichEditControl); } } - public static bool UseLegacyContextMenuStripSourceControlValue { + public static bool UseLegacyContextMenuStripSourceControlValue + { [MethodImpl(MethodImplOptions.AggressiveInlining)] - get { + get + { return LocalAppContext.GetCachedSwitchValue(LocalAppContextSwitches.UseLegacyContextMenuStripSourceControlValueSwitchName, ref _useLegacyContextMenuStripSourceControlValue); } } - public static bool UseLegacyDomainUpDownControlScrolling { + public static bool UseLegacyDomainUpDownControlScrolling + { [MethodImpl(MethodImplOptions.AggressiveInlining)] - get { + get + { return LocalAppContext.GetCachedSwitchValue(LocalAppContextSwitches.DomainUpDownUseLegacyScrollingSwitchName, ref _useLegacyDomainUpDownScrolling); } } - public static bool AllowUpdateChildControlIndexForTabControls { + public static bool AllowUpdateChildControlIndexForTabControls + { [MethodImpl(MethodImplOptions.AggressiveInlining)] - get { + get + { return LocalAppContext.GetCachedSwitchValue(LocalAppContextSwitches.AllowUpdateChildControlIndexForTabControlsSwitchName, ref _allowUpdateChildControlIndexForTabControls); } } - public static bool UseLegacyImages { + public static bool UseLegacyImages + { [MethodImpl(MethodImplOptions.AggressiveInlining)] - get { + get + { return LocalAppContext.GetCachedSwitchValue(LocalAppContextSwitches.UseLegacyImagesSwitchName, ref _useLegacyImages); } } - public static bool EnableVisualStyleValidation { + public static bool EnableVisualStyleValidation + { [MethodImpl(MethodImplOptions.AggressiveInlining)] - get { + get + { return LocalAppContext.GetCachedSwitchValue(LocalAppContextSwitches.EnableVisualStyleValidationSwitchName, ref _enableVisualStyleValidation); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs index 2158f19e9d8..4a3a6f916b2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System; @@ -16,7 +17,7 @@ namespace System.Windows.Forms { using System.Runtime.InteropServices; using System.Threading; using System.Windows.Forms; - + /// /// /// Summary to @@ -28,7 +29,8 @@ namespace System.Windows.Forms { ToolboxItem(false), DesignTimeVisible(false) ] - public sealed class MdiClient : Control { + public sealed class MdiClient : Control + { // kept in add order, not ZOrder. Need to return the correct // array of items... @@ -39,7 +41,8 @@ public sealed class MdiClient : Control { /// /// Creates a new MdiClient. /// - public MdiClient() : base() { + public MdiClient() : base() + { SetStyle(ControlStyles.Selectable, false); BackColor = SystemColors.AppWorkspace; Dock = DockStyle.Fill; @@ -51,22 +54,27 @@ public MdiClient() : base() { [ Localizable(true) ] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { Image result = base.BackgroundImage; if (result == null && ParentInternal != null) result = ParentInternal.BackgroundImage; return result; } - - set { + + set + { base.BackgroundImage = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { Image backgroundImage = BackgroundImage; if (backgroundImage != null && ParentInternal != null) { @@ -79,15 +87,18 @@ public override ImageLayout BackgroundImageLayout { } return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } /// /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ClassName = "MDICLIENT"; @@ -103,12 +114,14 @@ protected override CreateParams CreateParams { cp.ExStyle |= NativeMethods.WS_EX_CLIENTEDGE; cp.Param = new NativeMethods.CLIENTCREATESTRUCT(IntPtr.Zero, 1); ISite site = (ParentInternal == null) ? null : ParentInternal.Site; - if (site != null && site.DesignMode) { - cp.Style |= NativeMethods.WS_DISABLED; - SetState(STATE_ENABLED, false); + if (site != null && site.DesignMode) + { + cp.Style |= NativeMethods.WS_DISABLED; + SetState(STATE_ENABLED, false); } - - if (this.RightToLeft == RightToLeft.Yes && this.ParentInternal != null && this.ParentInternal.IsMirrored) { + + if (this.RightToLeft == RightToLeft.Yes && this.ParentInternal != null && this.ParentInternal.IsMirrored) + { //We want to turn on mirroring for MdiClient explicitly. cp.ExStyle |= NativeMethods.WS_EX_LAYOUTRTL | NativeMethods.WS_EX_NOINHERITLAYOUT; //Don't need these styles when mirroring is turned on. @@ -124,15 +137,18 @@ protected override CreateParams CreateParams { /// will be sorted by the order in which the children were /// added to the form, not the current ZOrder. /// - public Form[] MdiChildren { - get { + public Form[] MdiChildren + { + get + { Form[] temp = new Form[children.Count]; children.CopyTo(temp, 0); return temp; } } - protected override Control.ControlCollection CreateControlsInstance() { + protected override Control.ControlCollection CreateControlsInstance() + { return new ControlCollection(this); } @@ -140,11 +156,13 @@ protected override Control.ControlCollection CreateControlsInstance() { /// Arranges the MDI child forms according to value, which should be a /// member of the MdiLayout enum. /// - public void LayoutMdi(MdiLayout value) { + public void LayoutMdi(MdiLayout value) + { if (Handle == IntPtr.Zero) return; - switch (value) { + switch (value) + { case MdiLayout.Cascade: SendMessage(Interop.WindowMessages.WM_MDICASCADE, 0, 0); break; @@ -160,29 +178,33 @@ public void LayoutMdi(MdiLayout value) { } } - + /// /// - protected override void OnResize(EventArgs e) { + protected override void OnResize(EventArgs e) + { ISite site = (ParentInternal == null) ? null : ParentInternal.Site; - if (site != null && site.DesignMode && Handle != IntPtr.Zero) { + if (site != null && site.DesignMode && Handle != IntPtr.Zero) + { SetWindowRgn(); } base.OnResize(e); } - + /// /// Performs the work of scaling the entire control and any child controls. /// [EditorBrowsable(EditorBrowsableState.Never)] - protected override void ScaleCore(float dx, float dy) { + protected override void ScaleCore(float dx, float dy) + { // Don't scale child forms... // SuspendLayout(); - try { + try + { Rectangle bounds = Bounds; int sx = (int)Math.Round(bounds.X * dx); int sy = (int)Math.Round(bounds.Y * dy); @@ -190,7 +212,8 @@ protected override void ScaleCore(float dx, float dy) { int sh = (int)Math.Round((bounds.Y + bounds.Height) * dy - sy); SetBounds(sx, sy, sw, sh, BoundsSpecified.All); } - finally { + finally + { ResumeLayout(); } } @@ -198,21 +221,25 @@ protected override void ScaleCore(float dx, float dy) { /// /// Scale this form. Form overrides this to enforce a maximum / minimum size. /// - protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { + protected override void ScaleControl(SizeF factor, BoundsSpecified specified) + { // never scale X and Y of an MDI client form specified &= ~BoundsSpecified.Location; base.ScaleControl(factor, specified); } - protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { + protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) + { ISite site = (ParentInternal == null) ? null : ParentInternal.Site; - if (IsHandleCreated && (site == null || !site.DesignMode)) { + if (IsHandleCreated && (site == null || !site.DesignMode)) + { Rectangle oldBounds = Bounds; base.SetBoundsCore(x, y, width, height, specified); Rectangle newBounds = Bounds; int yDelta = oldBounds.Height - newBounds.Height; - if (yDelta != 0) { + if (yDelta != 0) + { // NOTE: This logic is to keep minimized MDI children anchored to // the bottom left of the client area, normally they are anchored // to the top right which just looks wierd! @@ -220,20 +247,26 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound NativeMethods.WINDOWPLACEMENT wp = new NativeMethods.WINDOWPLACEMENT(); wp.length = Marshal.SizeOf(); - for (int i=0; i < Controls.Count; i++) { + for (int i = 0; i < Controls.Count; i++) + { Control ctl = Controls[i]; - if (ctl != null && ctl is Form) { + if (ctl != null && ctl is Form) + { Form child = (Form)ctl; // Only adjust the window position for visible MDI Child windows to prevent // them from being re-displayed. - if (child.CanRecreateHandle() && child.WindowState == FormWindowState.Minimized) { + if (child.CanRecreateHandle() && child.WindowState == FormWindowState.Minimized) + { UnsafeNativeMethods.GetWindowPlacement(new HandleRef(child, child.Handle), ref wp); wp.ptMinPosition_y -= yDelta; - if (wp.ptMinPosition_y == -1) { - if (yDelta < 0) { + if (wp.ptMinPosition_y == -1) + { + if (yDelta < 0) + { wp.ptMinPosition_y = 0; } - else { + else + { wp.ptMinPosition_y = -2; } } @@ -245,7 +278,8 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound } } } - else { + else + { base.SetBoundsCore(x, y, width, height, specified); } } @@ -255,7 +289,8 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound /// There is case when the form contains a MainMenu and also has IsMdiContainer property set, in which, the MdiClient fails to /// resize and hence draw the correct backcolor. /// - private void SetWindowRgn() { + private void SetWindowRgn() + { IntPtr rgn1 = IntPtr.Zero; IntPtr rgn2 = IntPtr.Zero; NativeMethods.RECT rect = new NativeMethods.RECT(); @@ -265,58 +300,72 @@ private void SetWindowRgn() { Rectangle bounds = Bounds; rgn1 = SafeNativeMethods.CreateRectRgn(0, 0, bounds.Width, bounds.Height); - try { + try + { rgn2 = SafeNativeMethods.CreateRectRgn(-rect.left, -rect.top, bounds.Width - rect.right, bounds.Height - rect.bottom); - try { + try + { if (rgn1 == IntPtr.Zero || rgn2 == IntPtr.Zero) throw new InvalidOperationException(SR.ErrorSettingWindowRegion); if (SafeNativeMethods.CombineRgn(new HandleRef(null, rgn1), new HandleRef(null, rgn1), new HandleRef(null, rgn2), NativeMethods.RGN_DIFF) == 0) throw new InvalidOperationException(SR.ErrorSettingWindowRegion); - if (UnsafeNativeMethods.SetWindowRgn(new HandleRef(this, Handle), new HandleRef(null, rgn1), true) == 0) { + if (UnsafeNativeMethods.SetWindowRgn(new HandleRef(this, Handle), new HandleRef(null, rgn1), true) == 0) + { throw new InvalidOperationException(SR.ErrorSettingWindowRegion); } - else { + else + { // The hwnd now owns the region. rgn1 = IntPtr.Zero; } } - finally { - if (rgn2 != IntPtr.Zero) { + finally + { + if (rgn2 != IntPtr.Zero) + { SafeNativeMethods.DeleteObject(new HandleRef(null, rgn2)); } } } - finally { - if (rgn1 != IntPtr.Zero) { - SafeNativeMethods.DeleteObject(new HandleRef(null, rgn1)); + finally + { + if (rgn1 != IntPtr.Zero) + { + SafeNativeMethods.DeleteObject(new HandleRef(null, rgn1)); } } } - internal override bool ShouldSerializeBackColor() { + internal override bool ShouldSerializeBackColor() + { return BackColor != SystemColors.AppWorkspace; } - private bool ShouldSerializeLocation() { + private bool ShouldSerializeLocation() + { return false; } - internal override bool ShouldSerializeSize() { + internal override bool ShouldSerializeSize() + { return false; } - + /// /// - protected override void WndProc(ref Message m) { - switch (m.Msg) { - + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { + case Interop.WindowMessages.WM_CREATE: - if (ParentInternal != null && ParentInternal.Site != null && ParentInternal.Site.DesignMode && Handle != IntPtr.Zero) { + if (ParentInternal != null && ParentInternal.Site != null && ParentInternal.Site.DesignMode && Handle != IntPtr.Zero) + { SetWindowRgn(); } break; @@ -324,13 +373,16 @@ protected override void WndProc(ref Message m) { case Interop.WindowMessages.WM_SETFOCUS: InvokeGotFocus(ParentInternal, EventArgs.Empty); Form childForm = null; - if (ParentInternal is Form) { + if (ParentInternal is Form) + { childForm = ((Form)ParentInternal).ActiveMdiChildInternal; } - if (childForm == null && MdiChildren.Length > 0 && MdiChildren[0].IsMdiChildFocusable) { + if (childForm == null && MdiChildren.Length > 0 && MdiChildren[0].IsMdiChildFocusable) + { childForm = MdiChildren[0]; } - if (childForm != null && childForm.Visible) { + if (childForm != null && childForm.Visible) + { childForm.Active = true; } @@ -347,11 +399,13 @@ protected override void WndProc(ref Message m) { base.WndProc(ref m); } - internal override void OnInvokedSetScrollPosition(object sender, EventArgs e) { + internal override void OnInvokedSetScrollPosition(object sender, EventArgs e) + { Application.Idle += new EventHandler(this.OnIdle); //do this on idle (it must be mega-delayed). } - private void OnIdle(object sender, EventArgs e) { + private void OnIdle(object sender, EventArgs e) + { Application.Idle -= new EventHandler(this.OnIdle); base.OnInvokedSetScrollPosition(sender, e); } @@ -360,13 +414,15 @@ private void OnIdle(object sender, EventArgs e) { /// Collection of controls... /// [ComVisible(false)] - new public class ControlCollection : Control.ControlCollection { + new public class ControlCollection : Control.ControlCollection + { private MdiClient owner; /*C#r: protected*/ public ControlCollection(MdiClient owner) - : base(owner) { + : base(owner) + { this.owner = owner; } @@ -384,14 +440,18 @@ public ControlCollection(MdiClient owner) /// child.setMdiParent(this); /// /// - public override void Add(Control value) { - if (value == null) { + public override void Add(Control value) + { + if (value == null) + { return; } - if (!(value is Form) || !((Form)value).IsMdiChild) { + if (!(value is Form) || !((Form)value).IsMdiChild) + { throw new ArgumentException(SR.MDIChildAddToNonMDIParent, "value"); } - if (owner.CreateThreadId != value.CreateThreadId) { + if (owner.CreateThreadId != value.CreateThreadId) + { throw new ArgumentException(SR.AddDifferentThreads, "value"); } owner.children.Add((Form)value); @@ -401,7 +461,8 @@ public override void Add(Control value) { /// /// Removes a child control. /// - public override void Remove(Control value) { + public override void Remove(Control value) + { owner.children.Remove(value); base.Remove(value); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MDIControlStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MDIControlStrip.cs index f3f7b5eba0a..47512d23d54 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MDIControlStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MDIControlStrip.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.ComponentModel; using System.Drawing; @@ -14,225 +15,257 @@ namespace System.Windows.Forms { /// this is the toolstrip used for merging the [:)] [_][#][X] buttons onto an /// mdi parent when an MDI child is maximized. /// - internal class MdiControlStrip : MenuStrip { - - private ToolStripMenuItem system; - private ToolStripMenuItem close; - private ToolStripMenuItem minimize; - private ToolStripMenuItem restore; - private MenuStrip mergedMenu; - - private IWin32Window target; - - /// target is ideally the MDI Child to send the system commands to. - /// although there's nothing MDI child specific to it... you could have this - /// a toplevel window. - /// - public MdiControlStrip(IWin32Window target) { - IntPtr hMenu= UnsafeNativeMethods.GetSystemMenu(new HandleRef(this, Control.GetSafeHandle(target)), /*bRevert=*/false); - this.target = target; - - // The menu item itself takes care of enabledness and sending WM_SYSCOMMAND messages to the target. - minimize = new ControlBoxMenuItem(hMenu, NativeMethods.SC_MINIMIZE, target); - close = new ControlBoxMenuItem(hMenu, NativeMethods.SC_CLOSE, target); - restore = new ControlBoxMenuItem(hMenu, NativeMethods.SC_RESTORE, target); - - // The dropDown of the system menu is the one that talks to native. - system = new SystemMenuItem(); - - // However in the event that the target handle changes we have to push the new handle into everyone. - Control controlTarget = target as Control; - if (controlTarget != null) { - controlTarget.HandleCreated += new EventHandler(OnTargetWindowHandleRecreated); - controlTarget.Disposed += new EventHandler(OnTargetWindowDisposed); - } + internal class MdiControlStrip : MenuStrip + { - // add in opposite order to how you want it merged - this.Items.AddRange(new ToolStripItem[] { minimize, restore,close, system }); - this.SuspendLayout(); - foreach (ToolStripItem item in this.Items) { - item.DisplayStyle = ToolStripItemDisplayStyle.Image; - item.MergeIndex = 0; - item.MergeAction = MergeAction.Insert; - item.Overflow = ToolStripItemOverflow.Never; - item.Alignment = ToolStripItemAlignment.Right; - item.Padding = Padding.Empty; - // image is not scaled well on high dpi devices. Setting property to fit to size. - item.ImageScaling = ToolStripItemImageScaling.SizeToFit; - } + private ToolStripMenuItem system; + private ToolStripMenuItem close; + private ToolStripMenuItem minimize; + private ToolStripMenuItem restore; + private MenuStrip mergedMenu; - // set up the sytem menu - - - system.Image = GetTargetWindowIcon(); - system.Alignment = ToolStripItemAlignment.Left; - system.DropDownOpening += new EventHandler(OnSystemMenuDropDownOpening); - system.ImageScaling = ToolStripItemImageScaling.None; - system.DoubleClickEnabled = true; - system.DoubleClick += new EventHandler(OnSystemMenuDoubleClick); - system.Padding = Padding.Empty; - system.ShortcutKeys = Keys.Alt | Keys.OemMinus; - this.ResumeLayout(false); - } + private IWin32Window target; + /// target is ideally the MDI Child to send the system commands to. + /// although there's nothing MDI child specific to it... you could have this + /// a toplevel window. + /// + public MdiControlStrip(IWin32Window target) + { + IntPtr hMenu = UnsafeNativeMethods.GetSystemMenu(new HandleRef(this, Control.GetSafeHandle(target)), /*bRevert=*/false); + this.target = target; - #region Buttons - /* Unused - public ToolStripMenuItem System { - get { return system; } - } - */ + // The menu item itself takes care of enabledness and sending WM_SYSCOMMAND messages to the target. + minimize = new ControlBoxMenuItem(hMenu, NativeMethods.SC_MINIMIZE, target); + close = new ControlBoxMenuItem(hMenu, NativeMethods.SC_CLOSE, target); + restore = new ControlBoxMenuItem(hMenu, NativeMethods.SC_RESTORE, target); - public ToolStripMenuItem Close { - get { return close; } - } + // The dropDown of the system menu is the one that talks to native. + system = new SystemMenuItem(); - /* Unused - public ToolStripMenuItem Minimize { - get { return minimize; } + // However in the event that the target handle changes we have to push the new handle into everyone. + Control controlTarget = target as Control; + if (controlTarget != null) + { + controlTarget.HandleCreated += new EventHandler(OnTargetWindowHandleRecreated); + controlTarget.Disposed += new EventHandler(OnTargetWindowDisposed); } - - public ToolStripMenuItem Restore { - get { return restore; } + + // add in opposite order to how you want it merged + this.Items.AddRange(new ToolStripItem[] { minimize, restore, close, system }); + this.SuspendLayout(); + foreach (ToolStripItem item in this.Items) + { + item.DisplayStyle = ToolStripItemDisplayStyle.Image; + item.MergeIndex = 0; + item.MergeAction = MergeAction.Insert; + item.Overflow = ToolStripItemOverflow.Never; + item.Alignment = ToolStripItemAlignment.Right; + item.Padding = Padding.Empty; + // image is not scaled well on high dpi devices. Setting property to fit to size. + item.ImageScaling = ToolStripItemImageScaling.SizeToFit; } - */ - #endregion - internal MenuStrip MergedMenu { - get { - return mergedMenu; - } - set { - mergedMenu = value; - } + // set up the sytem menu + + + system.Image = GetTargetWindowIcon(); + system.Alignment = ToolStripItemAlignment.Left; + system.DropDownOpening += new EventHandler(OnSystemMenuDropDownOpening); + system.ImageScaling = ToolStripItemImageScaling.None; + system.DoubleClickEnabled = true; + system.DoubleClick += new EventHandler(OnSystemMenuDoubleClick); + system.Padding = Padding.Empty; + system.ShortcutKeys = Keys.Alt | Keys.OemMinus; + this.ResumeLayout(false); + } + + + #region Buttons + /* Unused + public ToolStripMenuItem System { + get { return system; } + } + */ + + public ToolStripMenuItem Close + { + get { return close; } + } + + /* Unused + public ToolStripMenuItem Minimize { + get { return minimize; } + } + + public ToolStripMenuItem Restore { + get { return restore; } + } + */ + #endregion + + internal MenuStrip MergedMenu + { + get + { + return mergedMenu; } - -/* PERF: consider shutting off layout -#region ShutOffLayout - protected override void OnLayout(LayoutEventArgs e) { - return; // if someone attempts + set + { + mergedMenu = value; } + } - protected override Size GetPreferredSize(Size proposedSize) { - return Size.Empty; - } -#endregion -*/ + /* PERF: consider shutting off layout + #region ShutOffLayout + protected override void OnLayout(LayoutEventArgs e) { + return; // if someone attempts + } + + protected override Size GetPreferredSize(Size proposedSize) { + return Size.Empty; + } + #endregion + */ + + private Image GetTargetWindowIcon() + { + Image systemIcon = null; + IntPtr hIcon = UnsafeNativeMethods.SendMessage(new HandleRef(this, Control.GetSafeHandle(target)), Interop.WindowMessages.WM_GETICON, NativeMethods.ICON_SMALL, 0); + Icon icon = (hIcon != IntPtr.Zero) ? Icon.FromHandle(hIcon) : Form.DefaultIcon; + Icon smallIcon = new Icon(icon, SystemInformation.SmallIconSize); + + systemIcon = smallIcon.ToBitmap(); + smallIcon.Dispose(); + + return systemIcon; + } - private Image GetTargetWindowIcon() { - Image systemIcon = null; - IntPtr hIcon = UnsafeNativeMethods.SendMessage(new HandleRef(this, Control.GetSafeHandle(target)), Interop.WindowMessages.WM_GETICON, NativeMethods.ICON_SMALL, 0); - Icon icon = (hIcon != IntPtr.Zero) ? Icon.FromHandle(hIcon) : Form.DefaultIcon; - Icon smallIcon = new Icon(icon, SystemInformation.SmallIconSize); + protected internal override void OnItemAdded(ToolStripItemEventArgs e) + { + base.OnItemAdded(e); + Debug.Assert(Items.Count <= 4, "Too many items in the MDIControlStrip. How did we get into this situation?"); + } + + private void OnTargetWindowDisposed(object sender, EventArgs e) + { + UnhookTarget(); + target = null; + } + + private void OnTargetWindowHandleRecreated(object sender, EventArgs e) + { + + // in the case that the handle for the form is recreated we need to set + // up the handles to point to the new window handle for the form. + + system.SetNativeTargetWindow(target); + minimize.SetNativeTargetWindow(target); + close.SetNativeTargetWindow(target); + restore.SetNativeTargetWindow(target); + + IntPtr hMenu = UnsafeNativeMethods.GetSystemMenu(new HandleRef(this, Control.GetSafeHandle(target)), /*bRevert=*/false); + system.SetNativeTargetMenu(hMenu); + minimize.SetNativeTargetMenu(hMenu); + close.SetNativeTargetMenu(hMenu); + restore.SetNativeTargetMenu(hMenu); + + // clear off the System DropDown. + if (system.HasDropDownItems) + { + // next time we need one we'll just fetch it fresh. + system.DropDown.Items.Clear(); + system.DropDown.Dispose(); + } - systemIcon = smallIcon.ToBitmap(); - smallIcon.Dispose(); + system.Image = GetTargetWindowIcon(); + } - return systemIcon; + private void OnSystemMenuDropDownOpening(object sender, EventArgs e) + { + if (!system.HasDropDownItems && (target != null)) + { + system.DropDown = ToolStripDropDownMenu.FromHMenu(UnsafeNativeMethods.GetSystemMenu(new HandleRef(this, Control.GetSafeHandle(target)), /*bRevert=*/false), target); } - - protected internal override void OnItemAdded(ToolStripItemEventArgs e) { - base.OnItemAdded(e); - Debug.Assert(Items.Count <= 4, "Too many items in the MDIControlStrip. How did we get into this situation?"); + else if (MergedMenu == null) + { + system.DropDown.Dispose(); } + } + + private void OnSystemMenuDoubleClick(object sender, EventArgs e) + { + Close.PerformClick(); + } - private void OnTargetWindowDisposed(object sender, EventArgs e) { + protected override void Dispose(bool disposing) + { + if (disposing) + { UnhookTarget(); target = null; } + base.Dispose(disposing); + } - private void OnTargetWindowHandleRecreated(object sender, EventArgs e) { - - // in the case that the handle for the form is recreated we need to set - // up the handles to point to the new window handle for the form. - - system.SetNativeTargetWindow(target); - minimize.SetNativeTargetWindow(target); - close.SetNativeTargetWindow(target); - restore.SetNativeTargetWindow(target); - - IntPtr hMenu= UnsafeNativeMethods.GetSystemMenu(new HandleRef(this, Control.GetSafeHandle(target)), /*bRevert=*/false); - system.SetNativeTargetMenu(hMenu); - minimize.SetNativeTargetMenu(hMenu); - close.SetNativeTargetMenu(hMenu); - restore.SetNativeTargetMenu(hMenu); - - // clear off the System DropDown. - if (system.HasDropDownItems) { - // next time we need one we'll just fetch it fresh. - system.DropDown.Items.Clear(); - system.DropDown.Dispose(); - } - - system.Image = GetTargetWindowIcon(); - } - - private void OnSystemMenuDropDownOpening(object sender, EventArgs e) { - if (!system.HasDropDownItems && (target != null)) { - system.DropDown = ToolStripDropDownMenu.FromHMenu(UnsafeNativeMethods.GetSystemMenu(new HandleRef(this, Control.GetSafeHandle(target)), /*bRevert=*/false), target); - } - else if (MergedMenu == null) { - system.DropDown.Dispose(); + private void UnhookTarget() + { + if (target != null) + { + Control controlTarget = target as Control; + if (controlTarget != null) + { + controlTarget.HandleCreated -= new EventHandler(OnTargetWindowHandleRecreated); + controlTarget.Disposed -= new EventHandler(OnTargetWindowDisposed); } + target = null; } - private void OnSystemMenuDoubleClick(object sender, EventArgs e) { - Close.PerformClick(); - } + } - protected override void Dispose(bool disposing) { - if (disposing) { - UnhookTarget(); - target = null; - } - base.Dispose(disposing); + // when the system menu item shortcut is evaluated - pop the dropdown + internal class ControlBoxMenuItem : ToolStripMenuItem + { + internal ControlBoxMenuItem(IntPtr hMenu, int nativeMenuCommandId, IWin32Window targetWindow) : + base(hMenu, nativeMenuCommandId, targetWindow) + { } - private void UnhookTarget() { - if (target != null) { - Control controlTarget = target as Control; - if (controlTarget != null) { - controlTarget.HandleCreated -= new EventHandler(OnTargetWindowHandleRecreated); - controlTarget.Disposed -= new EventHandler(OnTargetWindowDisposed); - } - target = null; + internal override bool CanKeyboardSelect + { + get + { + return false; } - } + } - // when the system menu item shortcut is evaluated - pop the dropdown - internal class ControlBoxMenuItem : ToolStripMenuItem { - internal ControlBoxMenuItem(IntPtr hMenu, int nativeMenuCommandId, IWin32Window targetWindow) : - base(hMenu, nativeMenuCommandId, targetWindow) { + // when the system menu item shortcut is evaluated - pop the dropdown + internal class SystemMenuItem : ToolStripMenuItem + { + public SystemMenuItem() + { + AccessibleName = SR.MDIChildSystemMenuItemAccessibleName; + } + protected internal override bool ProcessCmdKey(ref Message m, Keys keyData) + { + if (Visible && ShortcutKeys == keyData) + { + ShowDropDown(); + this.DropDown.SelectNextToolStripItem(null, true); + return true; } - - internal override bool CanKeyboardSelect { - get { - return false; - } + return base.ProcessCmdKey(ref m, keyData); + } + protected override void OnOwnerChanged(EventArgs e) + { + if (HasDropDownItems && DropDown.Visible) + { + HideDropDown(); } + base.OnOwnerChanged(e); } - // when the system menu item shortcut is evaluated - pop the dropdown - internal class SystemMenuItem : ToolStripMenuItem { - public SystemMenuItem(){ - AccessibleName = SR.MDIChildSystemMenuItemAccessibleName; - } - protected internal override bool ProcessCmdKey(ref Message m, Keys keyData) { - if (Visible && ShortcutKeys == keyData) { - ShowDropDown(); - this.DropDown.SelectNextToolStripItem(null, true); - return true; - } - return base.ProcessCmdKey(ref m, keyData); - } - protected override void OnOwnerChanged(EventArgs e) { - if (HasDropDownItems && DropDown.Visible) { - HideDropDown(); - } - base.OnOwnerChanged(e); - } - - } } + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MDIWindowDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MDIWindowDialog.cs index 37518c873d4..d916816648f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MDIWindowDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MDIWindowDialog.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.ComponentModel; using System.Diagnostics; using System; @@ -13,7 +14,8 @@ namespace System.Windows.Forms { /// /// - internal sealed class MdiWindowDialog : Form { + internal sealed class MdiWindowDialog : Form + { private System.Windows.Forms.ListBox itemList; private System.Windows.Forms.Button okButton; private System.Windows.Forms.Button cancelButton; @@ -21,13 +23,16 @@ internal sealed class MdiWindowDialog : Form { Form active; public MdiWindowDialog() - : base() { + : base() + { InitializeComponent(); } - public Form ActiveChildForm { - get { + public Form ActiveChildForm + { + get + { #if DEBUG ListItem item = (ListItem)itemList.SelectedItem; Debug.Assert(item != null, "No item selected!"); @@ -39,25 +44,32 @@ public Form ActiveChildForm { /// /// - private class ListItem { + private class ListItem + { public Form form; - public ListItem(Form f) { + public ListItem(Form f) + { form = f; } - public override string ToString() { + public override string ToString() + { return form.Text; } } - public void SetItems(Form active, Form[] all) { + public void SetItems(Form active, Form[] all) + { int selIndex = 0; - for (int i=0; i - private void InitializeComponent() { + private void InitializeComponent() + { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MdiWindowDialog)); this.itemList = new System.Windows.Forms.ListBox(); this.okButton = new System.Windows.Forms.Button(); @@ -93,29 +109,29 @@ private void InitializeComponent() { this.itemList.DoubleClick += new System.EventHandler(this.ItemList_doubleClick); this.itemList.SelectedIndexChanged += new EventHandler(this.ItemList_selectedIndexChanged); this.SuspendLayout(); -// -// itemList -// + // + // itemList + // resources.ApplyResources(this.itemList, "itemList"); this.itemList.FormattingEnabled = true; this.itemList.Name = "itemList"; -// -// okButton -// + // + // okButton + // resources.ApplyResources(this.okButton, "okButton"); this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.okButton.Margin = new System.Windows.Forms.Padding(0, 0, 3, 0); this.okButton.Name = "okButton"; -// -// cancelButton -// + // + // cancelButton + // resources.ApplyResources(this.cancelButton, "cancelButton"); this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Margin = new System.Windows.Forms.Padding(3, 0, 0, 0); this.cancelButton.Name = "cancelButton"; -// -// okCancelTableLayoutPanel -// + // + // okCancelTableLayoutPanel + // resources.ApplyResources(this.okCancelTableLayoutPanel, "okCancelTableLayoutPanel"); this.okCancelTableLayoutPanel.ColumnCount = 2; this.okCancelTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); @@ -125,9 +141,9 @@ private void InitializeComponent() { this.okCancelTableLayoutPanel.Name = "okCancelTableLayoutPanel"; this.okCancelTableLayoutPanel.RowCount = 1; this.okCancelTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle()); -// -// MdiWindowDialog -// + // + // MdiWindowDialog + // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.okCancelTableLayoutPanel); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MainMenu.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MainMenu.cs index 9f6a458b710..63b52f11e97 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MainMenu.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MainMenu.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; using System; using System.ComponentModel; @@ -22,20 +23,23 @@ public class MainMenu : Menu internal Form ownerForm; // this is the form that created this menu, and is the only form allowed to dispose it. private RightToLeft rightToLeft = System.Windows.Forms.RightToLeft.Inherit; private EventHandler onCollapse; - + /// /// Creates a new MainMenu control. /// public MainMenu() - : base(null) { + : base(null) + { } /// /// Initializes a new instance of the class with the specified container. /// - public MainMenu(IContainer container) : this() { - if (container == null) { + public MainMenu(IContainer container) : this() + { + if (container == null) + { throw new ArgumentNullException(nameof(container)); } @@ -47,17 +51,19 @@ public MainMenu(IContainer container) : this() { /// with. /// public MainMenu(MenuItem[] items) - : base(items) { + : base(items) + { } [SRDescription(nameof(SR.MainMenuCollapseDescr))] - public event EventHandler Collapse { + public event EventHandler Collapse + { add => onCollapse += value; remove => onCollapse -= value; } - + /// /// This is used for international applications where the language /// is written from RightToLeft. When this property is true, @@ -69,36 +75,47 @@ public event EventHandler Collapse { AmbientValue(RightToLeft.Inherit), SRDescription(nameof(SR.MenuRightToLeftDescr)) ] - public virtual RightToLeft RightToLeft { - get { - if (System.Windows.Forms.RightToLeft.Inherit == rightToLeft) { - if (form != null) { + public virtual RightToLeft RightToLeft + { + get + { + if (System.Windows.Forms.RightToLeft.Inherit == rightToLeft) + { + if (form != null) + { return form.RightToLeft; } - else { + else + { return RightToLeft.Inherit; } } - else { + else + { return rightToLeft; } } - set { - + set + { + //valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)RightToLeft.No, (int)RightToLeft.Inherit)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)RightToLeft.No, (int)RightToLeft.Inherit)) + { throw new InvalidEnumArgumentException(nameof(RightToLeft), (int)value, typeof(RightToLeft)); } - if (rightToLeft != value) { + if (rightToLeft != value) + { rightToLeft = value; UpdateRtl((value == System.Windows.Forms.RightToLeft.Yes)); } } } - - internal override bool RenderIsRightToLeft { - get { + + internal override bool RenderIsRightToLeft + { + get + { return (RightToLeft == System.Windows.Forms.RightToLeft.Yes && (form == null || !form.IsMirrored)); } } @@ -106,7 +123,8 @@ internal override bool RenderIsRightToLeft { /// /// Creates a new MainMenu object which is a dupliate of this one. /// - public virtual MainMenu CloneMenu() { + public virtual MainMenu CloneMenu() + { MainMenu newMenu = new MainMenu(); newMenu.CloneMenu(this); return newMenu; @@ -114,9 +132,10 @@ public virtual MainMenu CloneMenu() { /// /// - - - protected override IntPtr CreateMenuHandle() { + + + protected override IntPtr CreateMenuHandle() + { return UnsafeNativeMethods.CreateMenu(); } @@ -125,9 +144,12 @@ protected override IntPtr CreateMenuHandle() { /// If the menu is parented in a form, it is disconnected from that as /// well. /// - protected override void Dispose(bool disposing) { - if (disposing) { - if (form != null && (ownerForm == null || form == ownerForm)) { + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (form != null && (ownerForm == null || form == ownerForm)) + { form.Menu = null; } } @@ -137,17 +159,20 @@ protected override void Dispose(bool disposing) { /// /// Indicates which form in which we are currently residing [if any] /// - public Form GetForm() { + public Form GetForm() + { return form; } - internal Form GetFormUnsafe() { - return form; + internal Form GetFormUnsafe() + { + return form; } /// /// - internal override void ItemsChanged(int change) { + internal override void ItemsChanged(int change) + { base.ItemsChanged(change); if (form != null) form.MenuChanged(change, this); @@ -155,7 +180,8 @@ internal override void ItemsChanged(int change) { /// /// - internal virtual void ItemsChanged(int change, Menu menu) { + internal virtual void ItemsChanged(int change, Menu menu) + { if (form != null) form.MenuChanged(change, menu); } @@ -163,17 +189,21 @@ internal virtual void ItemsChanged(int change, Menu menu) { /// /// Fires the collapse event /// - protected internal virtual void OnCollapse(EventArgs e) { - if (onCollapse != null) { + protected internal virtual void OnCollapse(EventArgs e) + { + if (onCollapse != null) + { onCollapse(this, e); } } - + /// /// Returns true if the RightToLeft should be persisted in code gen. /// - internal virtual bool ShouldSerializeRightToLeft() { - if (System.Windows.Forms.RightToLeft.Inherit == RightToLeft) { + internal virtual bool ShouldSerializeRightToLeft() + { + if (System.Windows.Forms.RightToLeft.Inherit == RightToLeft) + { return false; } return true; @@ -182,7 +212,8 @@ internal virtual bool ShouldSerializeRightToLeft() { /// /// Returns a string representation for this control. /// - public override string ToString() { + public override string ToString() + { // Removing GetForm information return base.ToString(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs index 7f25f110bd8..4c5ecb58fa3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs @@ -41,23 +41,23 @@ public class MaskedTextBox : TextBoxBase // to implement our own. See http://msdn.microsoft.com/msdnmag/issues/1100/c/default.aspx for more info // about how to do this. See postponed - private const bool forward = true; - private const bool backward = false; - private const string nullMask = "<>"; // any char/str is OK here. + private const bool forward = true; + private const bool backward = false; + private const string nullMask = "<>"; // any char/str is OK here. - private static readonly object EVENT_MASKINPUTREJECTED = new object(); - private static readonly object EVENT_VALIDATIONCOMPLETED = new object(); - private static readonly object EVENT_TEXTALIGNCHANGED = new object(); + private static readonly object EVENT_MASKINPUTREJECTED = new object(); + private static readonly object EVENT_VALIDATIONCOMPLETED = new object(); + private static readonly object EVENT_TEXTALIGNCHANGED = new object(); private static readonly object EVENT_ISOVERWRITEMODECHANGED = new object(); - private static readonly object EVENT_MASKCHANGED = new object(); + private static readonly object EVENT_MASKCHANGED = new object(); // The native edit control's default password char (per thread). See corresponding property for more info. private static char systemPwdChar; // Values to track changes in IME composition string (if any). Having const variables is a bit more efficient // than having an enum (which creates a class). - private const byte imeConvertionNone = 0; // no convertion has been performed in the composition string. - private const byte imeConvertionUpdate = 1; // the char being composed has been updated but not coverted yet. + private const byte imeConvertionNone = 0; // no convertion has been performed in the composition string. + private const byte imeConvertionUpdate = 1; // the char being composed has been updated but not coverted yet. private const byte imeConvertionCompleted = 2; // the char being composed has been fully converted. ///////// Instance fields @@ -73,7 +73,7 @@ public class MaskedTextBox : TextBoxBase // Bit mask - Determines when the Korean IME is completing a composition, used when forcing convertion. private static int IME_COMPLETING = BitVector32.CreateMask(IME_ENDING_COMPOSITION); - + // Used for handling characters that have a modifier (Ctrl-A, Shift-Del...). private static int HANDLE_KEY_PRESS = BitVector32.CreateMask(IME_COMPLETING); @@ -92,24 +92,24 @@ public class MaskedTextBox : TextBoxBase // event is fired for the failing character. // If false, characters in the input string are processed one by one accepting the ones that comply // with the mask and raising the MaskInputRejected event for the rejected ones. - private static int REJECT_INPUT_ON_FIRST_FAILURE = BitVector32.CreateMask( QUERY_BASE_TEXT ); + private static int REJECT_INPUT_ON_FIRST_FAILURE = BitVector32.CreateMask(QUERY_BASE_TEXT); // Bit masks for boolean properties. - private static int HIDE_PROMPT_ON_LEAVE = BitVector32.CreateMask(REJECT_INPUT_ON_FIRST_FAILURE); - private static int BEEP_ON_ERROR = BitVector32.CreateMask(HIDE_PROMPT_ON_LEAVE); + private static int HIDE_PROMPT_ON_LEAVE = BitVector32.CreateMask(REJECT_INPUT_ON_FIRST_FAILURE); + private static int BEEP_ON_ERROR = BitVector32.CreateMask(HIDE_PROMPT_ON_LEAVE); private static int USE_SYSTEM_PASSWORD_CHAR = BitVector32.CreateMask(BEEP_ON_ERROR); - private static int INSERT_TOGGLED = BitVector32.CreateMask(USE_SYSTEM_PASSWORD_CHAR); - private static int CUTCOPYINCLUDEPROMPT = BitVector32.CreateMask(INSERT_TOGGLED); - private static int CUTCOPYINCLUDELITERALS = BitVector32.CreateMask(CUTCOPYINCLUDEPROMPT); + private static int INSERT_TOGGLED = BitVector32.CreateMask(USE_SYSTEM_PASSWORD_CHAR); + private static int CUTCOPYINCLUDEPROMPT = BitVector32.CreateMask(INSERT_TOGGLED); + private static int CUTCOPYINCLUDELITERALS = BitVector32.CreateMask(CUTCOPYINCLUDEPROMPT); ///////// Properties backend fields. See corresponding property comments for more info. - - private char passwordChar; // control's pwd char, it could be different from the one displayed if using system password. - private Type validatingType; - private IFormatProvider formatProvider; - private MaskedTextProvider maskedTextProvider; - private InsertKeyMode insertMode; - private HorizontalAlignment textAlign; + + private char passwordChar; // control's pwd char, it could be different from the one displayed if using system password. + private Type validatingType; + private IFormatProvider formatProvider; + private MaskedTextProvider maskedTextProvider; + private InsertKeyMode insertMode; + private HorizontalAlignment textAlign; // Bit vector to represent bool variables. private BitVector32 flagState; @@ -171,39 +171,39 @@ private void Initialize(MaskedTextProvider maskedTextProvider) // set default values. this.passwordChar = this.maskedTextProvider.PasswordChar; - this.insertMode = InsertKeyMode.Default; + this.insertMode = InsertKeyMode.Default; - this.flagState[HIDE_PROMPT_ON_LEAVE ] = false; - this.flagState[BEEP_ON_ERROR ] = false; - this.flagState[USE_SYSTEM_PASSWORD_CHAR ] = false; + this.flagState[HIDE_PROMPT_ON_LEAVE] = false; + this.flagState[BEEP_ON_ERROR] = false; + this.flagState[USE_SYSTEM_PASSWORD_CHAR] = false; this.flagState[REJECT_INPUT_ON_FIRST_FAILURE] = false; // CutCopyMaskFormat - set same defaults as TextMaskFormat (IncludePromptAndLiterals). // It is a lot easier to handle this flags individually since that's the way the MaskedTextProvider does it. - this.flagState[CUTCOPYINCLUDEPROMPT ] = this.maskedTextProvider.IncludePrompt; - this.flagState[CUTCOPYINCLUDELITERALS ] = this.maskedTextProvider.IncludeLiterals; + this.flagState[CUTCOPYINCLUDEPROMPT] = this.maskedTextProvider.IncludePrompt; + this.flagState[CUTCOPYINCLUDELITERALS] = this.maskedTextProvider.IncludeLiterals; // fields for internal use. this.flagState[HANDLE_KEY_PRESS] = true; - this.caretTestPos = 0; + this.caretTestPos = 0; } /////////////////// Properties /// - + /// /// Unsupported method/property. /// [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new bool AcceptsTab + public new bool AcceptsTab { get { return false; } - set {} + set { } } /// @@ -213,8 +213,8 @@ private void Initialize(MaskedTextProvider maskedTextProvider) /// This property has no particular effect if no mask has been set. /// [ - SRCategory(nameof(SR.CatBehavior)), - SRDescription(nameof(SR.MaskedTextBoxAllowPromptAsInputDescr)), + SRCategory(nameof(SR.CatBehavior)), + SRDescription(nameof(SR.MaskedTextBoxAllowPromptAsInputDescr)), DefaultValue(true) ] public bool AllowPromptAsInput @@ -225,31 +225,31 @@ public bool AllowPromptAsInput } set { - if( value != this.maskedTextProvider.AllowPromptAsInput ) + if (value != this.maskedTextProvider.AllowPromptAsInput) { // Recreate masked text provider since this property is read-only. - MaskedTextProvider newProvider = new MaskedTextProvider( - this.maskedTextProvider.Mask, - this.maskedTextProvider.Culture, - value, - this.maskedTextProvider.PromptChar, - this.maskedTextProvider.PasswordChar, - this.maskedTextProvider.AsciiOnly ); + MaskedTextProvider newProvider = new MaskedTextProvider( + this.maskedTextProvider.Mask, + this.maskedTextProvider.Culture, + value, + this.maskedTextProvider.PromptChar, + this.maskedTextProvider.PasswordChar, + this.maskedTextProvider.AsciiOnly); - SetMaskedTextProvider( newProvider ); + SetMaskedTextProvider(newProvider); } } } - + /// /// Unsupported method/property. /// [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new event EventHandler AcceptsTabChanged + public new event EventHandler AcceptsTabChanged { add { } remove { } @@ -260,8 +260,8 @@ public bool AllowPromptAsInput /// This property has no particular effect if no mask has been set. /// [ - SRCategory(nameof(SR.CatBehavior)), - SRDescription(nameof(SR.MaskedTextBoxAsciiOnlyDescr)), + SRCategory(nameof(SR.CatBehavior)), + SRDescription(nameof(SR.MaskedTextBoxAsciiOnlyDescr)), RefreshProperties(RefreshProperties.Repaint), DefaultValue(false) ] @@ -274,18 +274,18 @@ public bool AsciiOnly set { - if( value != this.maskedTextProvider.AsciiOnly ) + if (value != this.maskedTextProvider.AsciiOnly) { // Recreate masked text provider since this property is read-only. - MaskedTextProvider newProvider = new MaskedTextProvider( - this.maskedTextProvider.Mask, - this.maskedTextProvider.Culture, - this.maskedTextProvider.AllowPromptAsInput, - this.maskedTextProvider.PromptChar, - this.maskedTextProvider.PasswordChar, - value ); + MaskedTextProvider newProvider = new MaskedTextProvider( + this.maskedTextProvider.Mask, + this.maskedTextProvider.Culture, + this.maskedTextProvider.AllowPromptAsInput, + this.maskedTextProvider.PromptChar, + this.maskedTextProvider.PasswordChar, + value); - SetMaskedTextProvider( newProvider ); + SetMaskedTextProvider(newProvider); } } } @@ -294,17 +294,17 @@ public bool AsciiOnly /// Specifies whether to play a beep when the input is not valid according to the mask. /// [ - SRCategory(nameof(SR.CatBehavior)), - SRDescription(nameof(SR.MaskedTextBoxBeepOnErrorDescr)), + SRCategory(nameof(SR.CatBehavior)), + SRDescription(nameof(SR.MaskedTextBoxBeepOnErrorDescr)), DefaultValue(false) ] public bool BeepOnError { - get + get { return this.flagState[BEEP_ON_ERROR]; } - set + set { this.flagState[BEEP_ON_ERROR] = value; } @@ -316,7 +316,7 @@ public bool BeepOnError /// WndProc ignores EM_CANUNDO. /// [ - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] @@ -334,17 +334,17 @@ public bool BeepOnError /// however, forget to call base.getCreateParams() first to get the struct /// filled up with the basic info. /// - protected override CreateParams CreateParams + protected override CreateParams CreateParams { - get + get { CreateParams cp = base.CreateParams; - + // Translate for Rtl if necessary // HorizontalAlignment align = RtlTranslateHorizontal(textAlign); cp.ExStyle &= ~NativeMethods.WS_EX_RIGHT; // WS_EX_RIGHT overrides the ES_XXXX alignment styles - switch (align) + switch (align) { case HorizontalAlignment.Left: cp.Style |= NativeMethods.ES_LEFT; @@ -356,7 +356,7 @@ protected override CreateParams CreateParams cp.Style |= NativeMethods.ES_RIGHT; break; } - + return cp; } } @@ -378,23 +378,23 @@ public CultureInfo Culture set { - if( value == null ) + if (value == null) { throw new ArgumentNullException(); } - - if( !this.maskedTextProvider.Culture.Equals(value) ) + + if (!this.maskedTextProvider.Culture.Equals(value)) { // Recreate masked text provider since this property is read-only. - MaskedTextProvider newProvider = new MaskedTextProvider( - this.maskedTextProvider.Mask, - value, - this.maskedTextProvider.AllowPromptAsInput, - this.maskedTextProvider.PromptChar, - this.maskedTextProvider.PasswordChar, - this.maskedTextProvider.AsciiOnly ); + MaskedTextProvider newProvider = new MaskedTextProvider( + this.maskedTextProvider.Mask, + value, + this.maskedTextProvider.AllowPromptAsInput, + this.maskedTextProvider.PromptChar, + this.maskedTextProvider.PasswordChar, + this.maskedTextProvider.AsciiOnly); - SetMaskedTextProvider( newProvider ); + SetMaskedTextProvider(newProvider); } } } @@ -405,18 +405,18 @@ public CultureInfo Culture /// When prompt characters are excluded, theyare returned as spaces in the string returned. /// [ - SRCategory(nameof(SR.CatBehavior)), - SRDescription(nameof(SR.MaskedTextBoxCutCopyMaskFormat)), + SRCategory(nameof(SR.CatBehavior)), + SRDescription(nameof(SR.MaskedTextBoxCutCopyMaskFormat)), RefreshProperties(RefreshProperties.Repaint), DefaultValue(MaskFormat.IncludeLiterals) ] - public MaskFormat CutCopyMaskFormat - { + public MaskFormat CutCopyMaskFormat + { get { - if( this.flagState[CUTCOPYINCLUDEPROMPT] ) + if (this.flagState[CUTCOPYINCLUDEPROMPT]) { - if( this.flagState[CUTCOPYINCLUDELITERALS] ) + if (this.flagState[CUTCOPYINCLUDELITERALS]) { return MaskFormat.IncludePromptAndLiterals; } @@ -424,36 +424,36 @@ public MaskFormat CutCopyMaskFormat return MaskFormat.IncludePrompt; } - if( this.flagState[CUTCOPYINCLUDELITERALS] ) + if (this.flagState[CUTCOPYINCLUDELITERALS]) { return MaskFormat.IncludeLiterals; } return MaskFormat.ExcludePromptAndLiterals; } - + set { //valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(value, (int)value, (int)MaskFormat.ExcludePromptAndLiterals, (int)MaskFormat.IncludePromptAndLiterals)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(MaskFormat)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(MaskFormat)); } - if( value == MaskFormat.IncludePrompt ) + if (value == MaskFormat.IncludePrompt) { - this.flagState[CUTCOPYINCLUDEPROMPT] = true; + this.flagState[CUTCOPYINCLUDEPROMPT] = true; this.flagState[CUTCOPYINCLUDELITERALS] = false; - } - else if( value == MaskFormat.IncludeLiterals ) + } + else if (value == MaskFormat.IncludeLiterals) { - this.flagState[CUTCOPYINCLUDEPROMPT] = false; + this.flagState[CUTCOPYINCLUDEPROMPT] = false; this.flagState[CUTCOPYINCLUDELITERALS] = true; - } + } else // value == MaskFormat.IncludePromptAndLiterals || value == MaskFormat.ExcludePromptAndLiterals { bool include = value == MaskFormat.IncludePromptAndLiterals; - this.flagState[CUTCOPYINCLUDEPROMPT] = include; + this.flagState[CUTCOPYINCLUDEPROMPT] = include; this.flagState[CUTCOPYINCLUDELITERALS] = include; } } @@ -483,26 +483,26 @@ public IFormatProvider FormatProvider /// Specifies whether the PromptCharacter is displayed when the control loses focus. /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.MaskedTextBoxHidePromptOnLeaveDescr)), RefreshProperties(RefreshProperties.Repaint), DefaultValue(false) ] public bool HidePromptOnLeave { - get + get { return this.flagState[HIDE_PROMPT_ON_LEAVE]; } - set + set { - if( this.flagState[HIDE_PROMPT_ON_LEAVE] != value ) + if (this.flagState[HIDE_PROMPT_ON_LEAVE] != value) { this.flagState[HIDE_PROMPT_ON_LEAVE] = value; - + // If the control is not focused and there are available edit positions (mask not full) we need to // update the displayed text. - if( !this.flagState[IS_NULL_MASK]&& !this.Focused && !this.MaskFull && !this.DesignMode ) + if (!this.flagState[IS_NULL_MASK] && !this.Focused && !this.MaskFull && !this.DesignMode) { SetWindowText(); } @@ -547,8 +547,8 @@ private bool IncludePrompt /// This property has no particular effect if no mask has been set. /// [ - SRCategory(nameof(SR.CatBehavior)), - SRDescription(nameof(SR.MaskedTextBoxInsertKeyModeDescr)), + SRCategory(nameof(SR.CatBehavior)), + SRDescription(nameof(SR.MaskedTextBoxInsertKeyModeDescr)), DefaultValue(InsertKeyMode.Default) ] public InsertKeyMode InsertKeyMode @@ -568,7 +568,7 @@ public InsertKeyMode InsertKeyMode if (this.insertMode != value) { bool isOverwrite = this.IsOverwriteMode; - this.insertMode = value; + this.insertMode = value; if (isOverwrite != this.IsOverwriteMode) { @@ -581,7 +581,7 @@ public InsertKeyMode InsertKeyMode /// /// Overridden to handle unsupported RETURN key. /// - protected override bool IsInputKey(Keys keyData) + protected override bool IsInputKey(Keys keyData) { if ((keyData & Keys.KeyCode) == Keys.Return) { @@ -600,11 +600,11 @@ public bool IsOverwriteMode { get { - if( this.flagState[IS_NULL_MASK]) + if (this.flagState[IS_NULL_MASK]) { return false; // EditBox always inserts. } - + switch (this.insertMode) { case InsertKeyMode.Overwrite: @@ -628,7 +628,7 @@ public bool IsOverwriteMode } } - + /// /// Event to notify when the insert mode has changed. This is required for data binding. /// @@ -646,16 +646,16 @@ public event EventHandler IsOverwriteModeChanged /// Unsupported method/property. /// [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public new string[] Lines { - get - { + get + { string[] lines; - + this.flagState[QUERY_BASE_TEXT] = true; try { @@ -666,10 +666,10 @@ public event EventHandler IsOverwriteModeChanged this.flagState[QUERY_BASE_TEXT] = false; } - return lines; + return lines; } - set {} + set { } } /// @@ -677,8 +677,8 @@ public event EventHandler IsOverwriteModeChanged /// to add the existing input text (if any) using the new mask, failure is ignored. /// [ - SRCategory(nameof(SR.CatBehavior)), - SRDescription(nameof(SR.MaskedTextBoxMaskDescr)), + SRCategory(nameof(SR.CatBehavior)), + SRDescription(nameof(SR.MaskedTextBoxMaskDescr)), RefreshProperties(RefreshProperties.Repaint), DefaultValue(""), MergableProperty(false), @@ -687,9 +687,9 @@ public event EventHandler IsOverwriteModeChanged ] public string Mask { - get + get { - return this.flagState[IS_NULL_MASK]? string.Empty : this.maskedTextProvider.Mask; + return this.flagState[IS_NULL_MASK] ? string.Empty : this.maskedTextProvider.Mask; } set { @@ -698,40 +698,40 @@ public string Mask // 1. IsNullOrEmpty( value )->[Reset control] && this.flagState[IS_NULL_MASK]==>Already Reset. // 2. !IsNullOrEmpty( value )->[Set control] && !this.flagState[IS_NULL_MASK][control is set] && [value is the same]==>No need to update. // - if( this.flagState[IS_NULL_MASK] == string.IsNullOrEmpty( value ) && (this.flagState[IS_NULL_MASK] || value == this.maskedTextProvider.Mask) ) + if (this.flagState[IS_NULL_MASK] == string.IsNullOrEmpty(value) && (this.flagState[IS_NULL_MASK] || value == this.maskedTextProvider.Mask)) { return; } - string text = null; + string text = null; string newMask = value; - + // We need to update the this.flagState[IS_NULL_MASK]field before raising any events (when setting the maskedTextProvider) so // querying for properties from an event handler returns the right value (i.e: Text). - if( string.IsNullOrEmpty( value ) ) // Resetting the control, the native edit control will be in charge. + if (string.IsNullOrEmpty(value)) // Resetting the control, the native edit control will be in charge. { // Need to get the formatted & unformatted text before resetting the mask, they'll be used to determine whether we need to // raise the TextChanged event. - string formattedText = TextOutput; + string formattedText = TextOutput; string unformattedText = this.maskedTextProvider.ToString(false, false); this.flagState[IS_NULL_MASK] = true; - if( this.maskedTextProvider.IsPassword ) + if (this.maskedTextProvider.IsPassword) { SetEditControlPasswordChar(this.maskedTextProvider.PasswordChar); } // Set the window text to the unformatted text before raising events. Also, TextChanged needs to be raised after MaskChanged so // pass false to SetWindowText 'raiseTextChanged' param. - SetWindowText(unformattedText, false, false ); + SetWindowText(unformattedText, false, false); EventArgs e = EventArgs.Empty; OnMaskChanged(e); - if( unformattedText != formattedText ) + if (unformattedText != formattedText) { OnTextChanged(e); } @@ -740,16 +740,16 @@ public string Mask } else // Setting control to a new value. { - foreach( char c in value ) + foreach (char c in value) { - if( !MaskedTextProvider.IsValidMaskChar( c ) ) + if (!MaskedTextProvider.IsValidMaskChar(c)) { // Same message as in SR.MaskedTextProviderMaskInvalidChar in System.txt - throw new ArgumentException( string.Format( SR.MaskedTextBoxMaskInvalidChar) ); + throw new ArgumentException(string.Format(SR.MaskedTextBoxMaskInvalidChar)); } } - if( this.flagState[IS_NULL_MASK] ) + if (this.flagState[IS_NULL_MASK]) { // If this.IsNullMask, we are setting the mask to a new value; in this case we need to get the text because // the underlying MTP does not have it (used as a property backend only) and pass it to SetMaskedTextProvider @@ -760,17 +760,17 @@ public string Mask } // Recreate masked text provider since this property is read-only. - MaskedTextProvider newProvider = new MaskedTextProvider( - newMask, - this.maskedTextProvider.Culture, - this.maskedTextProvider.AllowPromptAsInput, - this.maskedTextProvider.PromptChar, - this.maskedTextProvider.PasswordChar, - this.maskedTextProvider.AsciiOnly ); + MaskedTextProvider newProvider = new MaskedTextProvider( + newMask, + this.maskedTextProvider.Culture, + this.maskedTextProvider.AllowPromptAsInput, + this.maskedTextProvider.PromptChar, + this.maskedTextProvider.PasswordChar, + this.maskedTextProvider.AsciiOnly); //text == null when setting to a different mask value or when resetting the mask to null. //text != null only when setting the mask from null to some value. - SetMaskedTextProvider( newProvider, text ); + SetMaskedTextProvider(newProvider, text); } } @@ -796,9 +796,9 @@ public event EventHandler MaskChanged ] public bool MaskCompleted { - get - { - return this.maskedTextProvider.MaskCompleted; + get + { + return this.maskedTextProvider.MaskCompleted; } } @@ -822,14 +822,14 @@ public bool MaskFull /// some of the properties require recreating the underlying provider when they are changed. /// [ - Browsable(false), + Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public MaskedTextProvider MaskedTextProvider { get { - return this.flagState[IS_NULL_MASK] ? null : (MaskedTextProvider) this.maskedTextProvider.Clone(); + return this.flagState[IS_NULL_MASK] ? null : (MaskedTextProvider)this.maskedTextProvider.Clone(); } } @@ -837,7 +837,7 @@ public MaskedTextProvider MaskedTextProvider /// Event to notify when an input has been rejected according to the mask. /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.MaskedTextBoxMaskInputRejectedDescr)) ] public event MaskInputRejectedEventHandler MaskInputRejected @@ -851,14 +851,14 @@ public event MaskInputRejectedEventHandler MaskInputRejected /// WndProc ignores EM_LIMITTEXT & this is a virtual method. /// [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public override int MaxLength { - get{ return base.MaxLength; } - set{} + get { return base.MaxLength; } + set { } } /// @@ -866,21 +866,21 @@ public override int MaxLength /// virtual method. /// [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public override bool Multiline { get { return false; } - set {} + set { } } /// /// Unsupported method/property. /// [ - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] @@ -896,8 +896,8 @@ public override bool Multiline /// character. /// [ - SRCategory(nameof(SR.CatBehavior)), - SRDescription(nameof(SR.MaskedTextBoxPasswordCharDescr)), + SRCategory(nameof(SR.CatBehavior)), + SRDescription(nameof(SR.MaskedTextBoxPasswordCharDescr)), RefreshProperties(RefreshProperties.Repaint), DefaultValue('\0') // This property is shadowed by MaskedTextBoxDesigner. ] @@ -911,18 +911,18 @@ public char PasswordChar } set { - if( !MaskedTextProvider.IsValidPasswordChar(value) ) // null character accepted (resets value) + if (!MaskedTextProvider.IsValidPasswordChar(value)) // null character accepted (resets value) { // Same message as in SR.MaskedTextProviderInvalidCharError. - throw new ArgumentException(SR.MaskedTextBoxInvalidCharError ); + throw new ArgumentException(SR.MaskedTextBoxInvalidCharError); } - if( this.passwordChar != value ) + if (this.passwordChar != value) { - if( value == this.maskedTextProvider.PromptChar ) + if (value == this.maskedTextProvider.PromptChar) { // Prompt and password chars must be different. - throw new InvalidOperationException( SR.MaskedTextBoxPasswordAndPromptCharError ); + throw new InvalidOperationException(SR.MaskedTextBoxPasswordAndPromptCharError); } this.passwordChar = value; @@ -932,7 +932,7 @@ public char PasswordChar { this.maskedTextProvider.PasswordChar = value; - if( this.flagState[IS_NULL_MASK]) + if (this.flagState[IS_NULL_MASK]) { SetEditControlPasswordChar(value); } @@ -950,13 +950,13 @@ public char PasswordChar /// /// Determines if the control is in password protect mode. /// - internal override bool PasswordProtect + internal override bool PasswordProtect { - get + get { - if( this.maskedTextProvider != null ) // could be queried during object construction. + if (this.maskedTextProvider != null) // could be queried during object construction. { - return this.maskedTextProvider.IsPassword; + return this.maskedTextProvider.IsPassword; } return base.PasswordProtect; } @@ -966,8 +966,8 @@ internal override bool PasswordProtect /// Specifies the prompt character to be used in the formatted string for unsupplied characters. /// [ - SRCategory(nameof(SR.CatAppearance)), - SRDescription(nameof(SR.MaskedTextBoxPromptCharDescr)), + SRCategory(nameof(SR.CatAppearance)), + SRDescription(nameof(SR.MaskedTextBoxPromptCharDescr)), RefreshProperties(RefreshProperties.Repaint), Localizable(true), DefaultValue('_') @@ -980,31 +980,31 @@ public char PromptChar } set { - if( !MaskedTextProvider.IsValidInputChar(value) ) + if (!MaskedTextProvider.IsValidInputChar(value)) { // This message is the same as the one in SR.MaskedTextProviderInvalidCharError. - throw new ArgumentException(SR.MaskedTextBoxInvalidCharError ); + throw new ArgumentException(SR.MaskedTextBoxInvalidCharError); } - if( this.maskedTextProvider.PromptChar != value ) + if (this.maskedTextProvider.PromptChar != value) { // We need to check maskedTextProvider password char in case it is using the system password. - if( value == this.passwordChar || value == this.maskedTextProvider.PasswordChar ) + if (value == this.passwordChar || value == this.maskedTextProvider.PasswordChar) { // Prompt and password chars must be different. - throw new InvalidOperationException( SR.MaskedTextBoxPasswordAndPromptCharError ); + throw new InvalidOperationException(SR.MaskedTextBoxPasswordAndPromptCharError); } - + // Recreate masked text provider to be consistent with AllowPromptAsInput - current text may have chars with same value as new prompt. - MaskedTextProvider newProvider = new MaskedTextProvider( - this.maskedTextProvider.Mask, - this.maskedTextProvider.Culture, - this.maskedTextProvider.AllowPromptAsInput, - value, - this.maskedTextProvider.PasswordChar, - this.maskedTextProvider.AsciiOnly ); + MaskedTextProvider newProvider = new MaskedTextProvider( + this.maskedTextProvider.Mask, + this.maskedTextProvider.Culture, + this.maskedTextProvider.AllowPromptAsInput, + value, + this.maskedTextProvider.PasswordChar, + this.maskedTextProvider.AsciiOnly); - SetMaskedTextProvider( newProvider ); + SetMaskedTextProvider(newProvider); } } } @@ -1012,14 +1012,14 @@ public char PromptChar /// /// Overwrite base class' property. /// - public new bool ReadOnly + public new bool ReadOnly { - get - { - return base.ReadOnly; + get + { + return base.ReadOnly; } - set + set { if (this.ReadOnly != value) { @@ -1040,8 +1040,8 @@ public char PromptChar /// where an edit char has not being assigned. /// [ - SRCategory(nameof(SR.CatBehavior)), - SRDescription(nameof(SR.MaskedTextBoxRejectInputOnFirstFailureDescr)), + SRCategory(nameof(SR.CatBehavior)), + SRDescription(nameof(SR.MaskedTextBoxRejectInputOnFirstFailureDescr)), DefaultValue(false) ] public bool RejectInputOnFirstFailure @@ -1066,23 +1066,23 @@ private void ResetCulture() this.Culture = CultureInfo.CurrentCulture; }*/ - + /// /// Specifies whether to reset and skip the current position if editable, when the input character /// has the same value as the prompt. This property takes precedence over AllowPromptAsInput. /// [ - SRCategory(nameof(SR.CatBehavior)), - SRDescription(nameof(SR.MaskedTextBoxResetOnPrompt)), + SRCategory(nameof(SR.CatBehavior)), + SRDescription(nameof(SR.MaskedTextBoxResetOnPrompt)), DefaultValue(true) ] public bool ResetOnPrompt { - get + get { return this.maskedTextProvider.ResetOnPrompt; } - set + set { this.maskedTextProvider.ResetOnPrompt = value; } @@ -1093,17 +1093,17 @@ public bool ResetOnPrompt /// is the space character. /// [ - SRCategory(nameof(SR.CatBehavior)), - SRDescription(nameof(SR.MaskedTextBoxResetOnSpace)), + SRCategory(nameof(SR.CatBehavior)), + SRDescription(nameof(SR.MaskedTextBoxResetOnSpace)), DefaultValue(true) ] public bool ResetOnSpace { - get + get { return this.maskedTextProvider.ResetOnSpace; } - set + set { this.maskedTextProvider.ResetOnSpace = value; } @@ -1114,17 +1114,17 @@ public bool ResetOnSpace /// the same value as the literal at that position. /// [ - SRCategory(nameof(SR.CatBehavior)), - SRDescription(nameof(SR.MaskedTextBoxSkipLiterals)), + SRCategory(nameof(SR.CatBehavior)), + SRDescription(nameof(SR.MaskedTextBoxSkipLiterals)), DefaultValue(true) ] public bool SkipLiterals { - get + get { return this.maskedTextProvider.SkipLiterals; } - set + set { this.maskedTextProvider.SkipLiterals = value; } @@ -1137,11 +1137,11 @@ public override string SelectedText { get { - if( this.flagState[IS_NULL_MASK]) + if (this.flagState[IS_NULL_MASK]) { return base.SelectedText; } - + return GetSelectedText(); } set @@ -1158,9 +1158,9 @@ internal override void SetSelectedTextInternal(string value, bool clearUndo) return; } - PasteInt( value ); + PasteInt(value); } - + /// /// Set the composition string as the result string. /// @@ -1169,13 +1169,13 @@ private void ImeComplete() this.flagState[IME_COMPLETING] = true; ImeNotify(NativeMethods.CPS_COMPLETE); } - + /// /// Notifies the IMM about changes to the status of the IME input context. /// private void ImeNotify(int action) { - HandleRef handle = new HandleRef(this, this.Handle); + HandleRef handle = new HandleRef(this, this.Handle); IntPtr inputContext = UnsafeNativeMethods.ImmGetContext(handle); if (inputContext != IntPtr.Zero) @@ -1199,9 +1199,9 @@ private void ImeNotify(int action) /// Sets the underlying edit control's password char to the one obtained from this.PasswordChar. /// This is used when the control is passworded and this.flagState[IS_NULL_MASK]. /// - private void SetEditControlPasswordChar( char pwdChar ) + private void SetEditControlPasswordChar(char pwdChar) { - if (this.IsHandleCreated) + if (this.IsHandleCreated) { // This message does not return a value. SendMessage(Interop.EditMessages.EM_SETPASSWORDCHAR, pwdChar, 0); @@ -1241,7 +1241,7 @@ private char SystemPasswordChar /// [ Editor("System.Windows.Forms.Design.MaskedTextBoxTextEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), - SRCategory(nameof(SR.CatAppearance)), + SRCategory(nameof(SR.CatAppearance)), RefreshProperties(RefreshProperties.Repaint), Bindable(true), DefaultValue(""), // This property is shadowed by MaskedTextBoxDesigner. @@ -1251,7 +1251,7 @@ public override string Text { get { - if( this.flagState[IS_NULL_MASK] || this.flagState[QUERY_BASE_TEXT]) + if (this.flagState[IS_NULL_MASK] || this.flagState[QUERY_BASE_TEXT]) { return base.Text; } @@ -1273,14 +1273,14 @@ public override string Text } else { - if( this.RejectInputOnFirstFailure ) + if (this.RejectInputOnFirstFailure) { MaskedTextResultHint hint; string oldText = TextOutput; if (this.maskedTextProvider.Set(value, out this.caretTestPos, out hint)) { //if( hint == MaskedTextResultHint.Success || hint == MaskedTextResultHint.SideEffect ) - if( TextOutput != oldText ) + if (TextOutput != oldText) { SetText(); } @@ -1302,12 +1302,12 @@ public override string Text /// /// Returns the length of the displayed text. /// - [Browsable( false )] + [Browsable(false)] public override int TextLength { get { - if( this.flagState[IS_NULL_MASK] ) + if (this.flagState[IS_NULL_MASK]) { return base.TextLength; } @@ -1330,7 +1330,7 @@ private string TextOutput { get { - Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." ); + Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); return this.maskedTextProvider.ToString(); } } @@ -1345,15 +1345,15 @@ private string TextOutput DefaultValue(HorizontalAlignment.Left), SRDescription(nameof(SR.TextBoxTextAlignDescr)) ] - public HorizontalAlignment TextAlign + public HorizontalAlignment TextAlign { - get + get { return textAlign; } - set + set { - if (textAlign != value) + if (textAlign != value) { //verify that 'value' is a valid enum type... //valid values are 0x0 to 0x2 @@ -1373,10 +1373,10 @@ public HorizontalAlignment TextAlign /// Event to notify the text alignment has changed. /// [ - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.RadioButtonOnTextAlignChangedDescr)) ] - public event EventHandler TextAlignChanged + public event EventHandler TextAlignChanged { add => Events.AddHandler(EVENT_TEXTALIGNCHANGED, value); @@ -1389,18 +1389,18 @@ public event EventHandler TextAlignChanged /// When prompt characters are excluded, theyare returned as spaces in the string returned. /// [ - SRCategory(nameof(SR.CatBehavior)), - SRDescription(nameof(SR.MaskedTextBoxTextMaskFormat)), + SRCategory(nameof(SR.CatBehavior)), + SRDescription(nameof(SR.MaskedTextBoxTextMaskFormat)), RefreshProperties(RefreshProperties.Repaint), DefaultValue(MaskFormat.IncludeLiterals) ] - public MaskFormat TextMaskFormat - { + public MaskFormat TextMaskFormat + { get { - if( this.IncludePrompt ) + if (this.IncludePrompt) { - if( this.IncludeLiterals ) + if (this.IncludeLiterals) { return MaskFormat.IncludePromptAndLiterals; } @@ -1408,17 +1408,17 @@ public MaskFormat TextMaskFormat return MaskFormat.IncludePrompt; } - if( this.IncludeLiterals ) + if (this.IncludeLiterals) { return MaskFormat.IncludeLiterals; } return MaskFormat.ExcludePromptAndLiterals; } - + set { - if( this.TextMaskFormat == value ) + if (this.TextMaskFormat == value) { return; } @@ -1433,24 +1433,24 @@ public MaskFormat TextMaskFormat // verify it against the new value and raise OnTextChange if needed. string oldText = this.flagState[IS_NULL_MASK] ? null : TextOutput; - if( value == MaskFormat.IncludePrompt ) + if (value == MaskFormat.IncludePrompt) { - this.IncludePrompt = true; + this.IncludePrompt = true; this.IncludeLiterals = false; - } - else if( value == MaskFormat.IncludeLiterals ) + } + else if (value == MaskFormat.IncludeLiterals) { - this.IncludePrompt = false; + this.IncludePrompt = false; this.IncludeLiterals = true; - } + } else // value == MaskFormat.IncludePromptAndLiterals || value == MaskFormat.ExcludePromptAndLiterals { bool include = value == MaskFormat.IncludePromptAndLiterals; - this.IncludePrompt = include; + this.IncludePrompt = include; this.IncludeLiterals = include; } - if( oldText != null && oldText != TextOutput ) + if (oldText != null && oldText != TextOutput) { OnTextChanged(EventArgs.Empty); } @@ -1461,16 +1461,16 @@ public MaskFormat TextMaskFormat /// Provides some interesting information for the TextBox control in String form. /// Returns the test string (no password, including literals and prompt). /// - public override string ToString() + public override string ToString() { - if( this.flagState[IS_NULL_MASK] ) + if (this.flagState[IS_NULL_MASK]) { return base.ToString(); } // base.ToString will call Text, we want to always display prompt and literals. bool includePrompt = this.IncludePrompt; - bool includeLits = this.IncludeLiterals; + bool includeLits = this.IncludeLiterals; string str; try { @@ -1490,7 +1490,7 @@ public override string ToString() /// Event to notify when the validating object completes parsing the formatted text. /// [ - SRCategory(nameof(SR.CatFocus)), + SRCategory(nameof(SR.CatFocus)), SRDescription(nameof(SR.MaskedTextBoxTypeValidationCompletedDescr)) ] public event TypeValidationEventHandler TypeValidationCompleted @@ -1504,7 +1504,7 @@ public event TypeValidationEventHandler TypeValidationCompleted /// This property has precedence over the PasswordChar property. /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.MaskedTextBoxUseSystemPasswordCharDescr)), RefreshProperties(RefreshProperties.Repaint), DefaultValue(false) @@ -1521,10 +1521,10 @@ public bool UseSystemPasswordChar { if (value) { - if( this.SystemPasswordChar == this.PromptChar ) + if (this.SystemPasswordChar == this.PromptChar) { // Prompt and password chars must be different. - throw new InvalidOperationException( SR.MaskedTextBoxPasswordAndPromptCharError ); + throw new InvalidOperationException(SR.MaskedTextBoxPasswordAndPromptCharError); } this.maskedTextProvider.PasswordChar = this.SystemPasswordChar; @@ -1532,12 +1532,12 @@ public bool UseSystemPasswordChar else { // this.passwordChar could be '\0', in which case we are resetting the display to show the input char. - this.maskedTextProvider.PasswordChar = this.passwordChar; + this.maskedTextProvider.PasswordChar = this.passwordChar; } this.flagState[USE_SYSTEM_PASSWORD_CHAR] = value; - if( this.flagState[IS_NULL_MASK]) + if (this.flagState[IS_NULL_MASK]) { SetEditControlPasswordChar(this.maskedTextProvider.PasswordChar); } @@ -1564,13 +1564,13 @@ public bool UseSystemPasswordChar ] public Type ValidatingType { - get + get { return this.validatingType; } - set + set { - if( this.validatingType != value ) + if (this.validatingType != value) { this.validatingType = value; } @@ -1581,14 +1581,14 @@ public Type ValidatingType /// Unsupported method/property. /// [ - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public new bool WordWrap { get { return false; } - set {} + set { } } @@ -1621,7 +1621,7 @@ protected override void CreateHandle() // update cached text value in Control. Don't preserve caret, cannot query for selection start at this time. SetWindowText(GetFormattedDisplayString(), false, false); } - + base.CreateHandle(); } @@ -1632,20 +1632,20 @@ protected override void CreateHandle() /// private void Delete(Keys keyCode, int startPosition, int selectionLen) { - Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." ); - Debug.Assert( keyCode == Keys.Delete || keyCode == Keys.Back, "Delete called with keyCode == " + keyCode.ToString() ); - Debug.Assert( startPosition >= 0 && ((startPosition + selectionLen) <= this.maskedTextProvider.Length), "Invalid position range." ); + Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); + Debug.Assert(keyCode == Keys.Delete || keyCode == Keys.Back, "Delete called with keyCode == " + keyCode.ToString()); + Debug.Assert(startPosition >= 0 && ((startPosition + selectionLen) <= this.maskedTextProvider.Length), "Invalid position range."); // On backspace, moving the start postion back by one has the same effect as delete. If text is selected, there is no // need for moving the position back. this.caretTestPos = startPosition; - if( selectionLen == 0 ) + if (selectionLen == 0) { - if( keyCode == Keys.Back ) + if (keyCode == Keys.Back) { - if( startPosition == 0 ) // At beginning of string, backspace does nothing. + if (startPosition == 0) // At beginning of string, backspace does nothing. { return; } @@ -1654,7 +1654,7 @@ private void Delete(Keys keyCode, int startPosition, int selectionLen) } else // (keyCode == Keys.Delete) { - if( (startPosition + selectionLen) == this.maskedTextProvider.Length ) // At end of string, delete does nothing. + if ((startPosition + selectionLen) == this.maskedTextProvider.Length) // At end of string, delete does nothing. { return; } @@ -1669,7 +1669,7 @@ private void Delete(Keys keyCode, int startPosition, int selectionLen) if (this.maskedTextProvider.RemoveAt(startPosition, endPos, out tempPos, out hint)) { //if( hint == MaskedTextResultHint.Success || hint == MaskedTextResultHint.SideEffect) // Text was changed. - if( TextOutput != oldText ) + if (TextOutput != oldText) { SetText(); this.caretTestPos = startPosition; @@ -1684,21 +1684,21 @@ private void Delete(Keys keyCode, int startPosition, int selectionLen) // (taken care by 'startPosition--' above). // 3. If hint == SideEffect, on Back move like arrow key, (startPosition is already moved, startPosition-- above). - if( selectionLen > 0 ) + if (selectionLen > 0) { this.caretTestPos = startPosition; } else { - if( hint == MaskedTextResultHint.NoEffect ) // Case 2. + if (hint == MaskedTextResultHint.NoEffect) // Case 2. { - if( keyCode == Keys.Delete ) + if (keyCode == Keys.Delete) { this.caretTestPos = this.maskedTextProvider.FindEditPositionFrom(startPosition, forward); } else { - if( this.maskedTextProvider.FindAssignedEditPositionFrom( startPosition, forward ) == MaskedTextProvider.InvalidIndex ) + if (this.maskedTextProvider.FindAssignedEditPositionFrom(startPosition, forward) == MaskedTextProvider.InvalidIndex) { // No assigned position at the right, nothing to shift then move to the next assigned position at the // left (if any). @@ -1711,20 +1711,20 @@ private void Delete(Keys keyCode, int startPosition, int selectionLen) this.caretTestPos = this.maskedTextProvider.FindEditPositionFrom(startPosition, backward); } - if( this.caretTestPos != MaskedTextProvider.InvalidIndex ) + if (this.caretTestPos != MaskedTextProvider.InvalidIndex) { this.caretTestPos++; // backspace gets ready to remove one position past the edit position. } } - if( this.caretTestPos == MaskedTextProvider.InvalidIndex ) + if (this.caretTestPos == MaskedTextProvider.InvalidIndex) { this.caretTestPos = startPosition; } } else // (hint == MaskedTextProvider.OperationHint.SideEffect) { - if( keyCode == Keys.Back ) // Case 3. + if (keyCode == Keys.Back) // Case 3. { this.caretTestPos = startPosition; } @@ -1740,7 +1740,7 @@ private void Delete(Keys keyCode, int startPosition, int selectionLen) // Reposition caret. Call base.SelectInternal for perf reasons. //this.SelectionLength = 0; //this.SelectionStart = this.caretTestPos; // new caret position. - base.SelectInternal( this.caretTestPos, 0, this.maskedTextProvider.Length ); + base.SelectInternal(this.caretTestPos, 0, this.maskedTextProvider.Length); return; } @@ -1748,7 +1748,7 @@ private void Delete(Keys keyCode, int startPosition, int selectionLen) /// /// Returns the character nearest to the given point. /// - public override char GetCharFromPosition(Point pt) + public override char GetCharFromPosition(Point pt) { char ch; @@ -1764,11 +1764,11 @@ public override char GetCharFromPosition(Point pt) return ch; } - + /// /// Returns the index of the character nearest to the given point. /// - public override int GetCharIndexFromPosition(Point pt) + public override int GetCharIndexFromPosition(Point pt) { int index; @@ -1790,21 +1790,21 @@ public override int GetCharIndexFromPosition(Point pt) /// internal override int GetEndPosition() { - if( this.flagState[IS_NULL_MASK]) + if (this.flagState[IS_NULL_MASK]) { return base.GetEndPosition(); } - int pos = this.maskedTextProvider.FindEditPositionFrom( this.maskedTextProvider.LastAssignedPosition + 1, forward ); + int pos = this.maskedTextProvider.FindEditPositionFrom(this.maskedTextProvider.LastAssignedPosition + 1, forward); - if( pos == MaskedTextProvider.InvalidIndex ) + if (pos == MaskedTextProvider.InvalidIndex) { pos = this.maskedTextProvider.LastAssignedPosition + 1; } return pos; } - + /// /// Unsupported method/property. /// @@ -1833,7 +1833,7 @@ internal override int GetEndPosition() /// private string GetFormattedDisplayString() { - Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." ); + Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); bool includePrompt; @@ -1868,7 +1868,7 @@ public override int GetLineFromCharIndex(int index) /// /// Returns the location of the character at the given index. /// - public override Point GetPositionFromCharIndex(int index) + public override Point GetPositionFromCharIndex(int index) { Point pos; @@ -1895,7 +1895,7 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) this.flagState[QUERY_BASE_TEXT] = true; try { - size = base.GetPreferredSizeCore( proposedConstraints ); + size = base.GetPreferredSizeCore(proposedConstraints); } finally { @@ -1911,20 +1911,20 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) /// private string GetSelectedText() { - Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." ); + Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); int selStart, selLength; - base.GetSelectionStartAndLength( out selStart, out selLength ); + base.GetSelectionStartAndLength(out selStart, out selLength); - if( selLength == 0 ) + if (selLength == 0) { return string.Empty; } - bool includePrompt = (CutCopyMaskFormat & MaskFormat.IncludePrompt ) != 0; - bool includeLiterals = (CutCopyMaskFormat & MaskFormat.IncludeLiterals) != 0; + bool includePrompt = (CutCopyMaskFormat & MaskFormat.IncludePrompt) != 0; + bool includeLiterals = (CutCopyMaskFormat & MaskFormat.IncludeLiterals) != 0; - return this.maskedTextProvider.ToString( /*ignorePasswordChar*/ true, includePrompt, includeLiterals, selStart, selLength ); + return this.maskedTextProvider.ToString( /*ignorePasswordChar*/ true, includePrompt, includeLiterals, selStart, selLength); } @@ -1942,12 +1942,12 @@ protected override void OnBackColorChanged(EventArgs e) /// Overridden to update the newly created handle with the settings of the PasswordChar properties /// if no mask has been set. /// - protected override void OnHandleCreated(EventArgs e) + protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); base.SetSelectionOnHandle(); - if( this.flagState[IS_NULL_MASK]&& this.maskedTextProvider.IsPassword ) + if (this.flagState[IS_NULL_MASK] && this.maskedTextProvider.IsPassword) { SetEditControlPasswordChar(this.maskedTextProvider.PasswordChar); } @@ -1976,7 +1976,7 @@ protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); - if( this.flagState[IS_NULL_MASK]) + if (this.flagState[IS_NULL_MASK]) { // Operates as a regular text box base. return; @@ -1985,7 +1985,7 @@ protected override void OnKeyDown(KeyEventArgs e) Keys keyCode = e.KeyCode; // Special-case Return & Esc since they generate invalid characters we should not process OnKeyPress. - if( keyCode == Keys.Return || keyCode == Keys.Escape ) + if (keyCode == Keys.Return || keyCode == Keys.Escape) { this.flagState[HANDLE_KEY_PRESS] = false; } @@ -2028,41 +2028,41 @@ protected override void OnKeyDown(KeyEventArgs e) } } - if ( keyCode == Keys.Delete || keyCode == Keys.Back ) // Deletion keys. + if (keyCode == Keys.Delete || keyCode == Keys.Back) // Deletion keys. { if (!this.ReadOnly) { int selectionLen; int startPosition; - base.GetSelectionStartAndLength( out startPosition, out selectionLen ); + base.GetSelectionStartAndLength(out startPosition, out selectionLen); switch (e.Modifiers) { case Keys.Shift: - if( keyCode == Keys.Delete ) + if (keyCode == Keys.Delete) { keyCode = Keys.Back; } goto default; case Keys.Control: - if( selectionLen == 0 ) // In other case, the selected text should be deleted. + if (selectionLen == 0) // In other case, the selected text should be deleted. { - if( keyCode == Keys.Delete ) // delete to the end of the string. + if (keyCode == Keys.Delete) // delete to the end of the string. { selectionLen = this.maskedTextProvider.Length - startPosition; } else // ( keyCode == Keys.Back ) // delete to the beginning of the string. { selectionLen = startPosition == this.maskedTextProvider.Length /*at end of text*/ ? startPosition : startPosition + 1; - startPosition = 0; + startPosition = 0; } } goto default; default: - if( !this.flagState[HANDLE_KEY_PRESS] ) + if (!this.flagState[HANDLE_KEY_PRESS]) { this.flagState[HANDLE_KEY_PRESS] = true; } @@ -2094,7 +2094,7 @@ protected override void OnKeyDown(KeyEventArgs e) */ - + Delete(keyCode, startPosition, selectionLen); e.SuppressKeyPress = true; } @@ -2108,18 +2108,18 @@ protected override void OnKeyDown(KeyEventArgs e) protected override void OnKeyPress(KeyPressEventArgs e) { base.OnKeyPress(e); - - if( this.flagState[IS_NULL_MASK]) + + if (this.flagState[IS_NULL_MASK]) { // Operates as a regular text box base. return; } // This key may be a combined key involving a letter, like Ctrl-A; let the native control handle it. - if( !this.flagState[HANDLE_KEY_PRESS] ) + if (!this.flagState[HANDLE_KEY_PRESS]) { this.flagState[HANDLE_KEY_PRESS] = true; - + // When the combined key involves a letter, the final character is not a letter. There are some // Ctrl combined keys that generate a letter and can be confusing; we do not mean to pass those // characters to the underlying Edit control. These combinations are: Ctrl-F<#> and Ctrl-Atl- @@ -2129,7 +2129,7 @@ protected override void OnKeyPress(KeyPressEventArgs e) } } - if( !this.ReadOnly) + if (!this.ReadOnly) { // At this point the character needs to be processed ... @@ -2138,17 +2138,17 @@ protected override void OnKeyPress(KeyPressEventArgs e) int selectionStart; int selectionLen; - base.GetSelectionStartAndLength( out selectionStart, out selectionLen ); + base.GetSelectionStartAndLength(out selectionStart, out selectionLen); string oldText = TextOutput; if (PlaceChar(e.KeyChar, selectionStart, selectionLen, this.IsOverwriteMode, out hint)) { //if( hint == MaskedTextResultHint.Success || hint == MaskedTextResultHint.SideEffect ) - if( TextOutput != oldText ) + if (TextOutput != oldText) { SetText(); // Now set the text in the display. } - + this.SelectionStart = ++this.caretTestPos; // caretTestPos is updated in PlaceChar. if (ImeModeConversion.InputLanguageTable == ImeModeConversion.KoreanTable) @@ -2168,7 +2168,7 @@ protected override void OnKeyPress(KeyPressEventArgs e) OnMaskInputRejected(new MaskInputRejectedEventArgs(this.caretTestPos, hint)); // caretTestPos is updated in PlaceChar. } - if( selectionLen > 0 ) + if (selectionLen > 0) { this.SelectionLength = 0; } @@ -2191,7 +2191,7 @@ protected override void OnKeyUp(KeyEventArgs e) this.flagState[IME_COMPLETING] = false; } - if( this.flagState[IME_ENDING_COMPOSITION] ) + if (this.flagState[IME_ENDING_COMPOSITION]) { this.flagState[IME_ENDING_COMPOSITION] = false; } @@ -2218,7 +2218,7 @@ protected virtual void OnMaskChanged(EventArgs e) /// private void OnMaskInputRejected(MaskInputRejectedEventArgs e) { - Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." ); + Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); if (this.BeepOnError) { @@ -2248,10 +2248,10 @@ protected override void OnMultilineChanged(EventArgs e) /// /// Raises the TextAlignChanged event. /// - protected virtual void OnTextAlignChanged(EventArgs e) + protected virtual void OnTextAlignChanged(EventArgs e) { EventHandler eh = Events[EVENT_TEXTALIGNCHANGED] as EventHandler; - if (eh != null) + if (eh != null) { eh(this, e); } @@ -2276,7 +2276,7 @@ private void OnTypeValidationCompleted(TypeValidationEventArgs e) /// raised [TypeValidationCompleted - Validating - Validated - Leave - KillFocus] /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnValidating(CancelEventArgs e) + protected override void OnValidating(CancelEventArgs e) { // Note: It seems impractical to perform type validation here if the control is read only but we need // to be consistent with other TextBoxBase controls which don't check for RO; and we don't want @@ -2289,7 +2289,7 @@ protected override void OnValidating(CancelEventArgs e) /// Raises the TextChanged event and related Input/Output text events when mask is null. /// Overriden here to be able to control order of text changed events. /// - protected override void OnTextChanged(EventArgs e) + protected override void OnTextChanged(EventArgs e) { // A text changed event handler will most likely query for the Text value, we need to return the // formatted one. @@ -2310,14 +2310,14 @@ protected override void OnTextChanged(EventArgs e) /// private void Replace(string text, int startPosition, int selectionLen) { - Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." ); + Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); Debug.Assert(text != null, "text is null."); // Clone the MaskedTextProvider so text properties are not modified until the paste operation is // completed. This is needed in case one of these properties is retreived in a MaskedInputRejected // event handler (clipboard text is attempted to be set into the input text char by char). - MaskedTextProvider clonedProvider = (MaskedTextProvider) this.maskedTextProvider.Clone(); + MaskedTextProvider clonedProvider = (MaskedTextProvider)this.maskedTextProvider.Clone(); // Cache the current caret position so we restore it in case the text does not change. int currentCaretPos = this.caretTestPos; @@ -2329,15 +2329,15 @@ private void Replace(string text, int startPosition, int selectionLen) MaskedTextResultHint hint = MaskedTextResultHint.NoEffect; int endPos = startPosition + selectionLen - 1; - if( this.RejectInputOnFirstFailure ) + if (this.RejectInputOnFirstFailure) { - bool succeeded; + bool succeeded; succeeded = (startPosition > endPos) ? - clonedProvider.InsertAt(text, startPosition, out this.caretTestPos, out hint ) : + clonedProvider.InsertAt(text, startPosition, out this.caretTestPos, out hint) : clonedProvider.Replace(text, startPosition, endPos, out this.caretTestPos, out hint); - if( !succeeded ) + if (!succeeded) { OnMaskInputRejected(new MaskInputRejectedEventArgs(this.caretTestPos, hint)); } @@ -2347,16 +2347,16 @@ private void Replace(string text, int startPosition, int selectionLen) // temp hint used to preserve the 'primary' operation hint (no side effects). MaskedTextResultHint tempHint = hint; int testPos; - + foreach (char ch in text) { - if( !this.maskedTextProvider.VerifyEscapeChar( ch, startPosition )) // char won't be escaped, find and edit position for it. + if (!this.maskedTextProvider.VerifyEscapeChar(ch, startPosition)) // char won't be escaped, find and edit position for it. { // Observe that we look for a position w/o respecting the selection length, because the input text could be larger than // the number of edit positions in the selection. testPos = clonedProvider.FindEditPositionFrom(startPosition, forward); - if( testPos == MaskedTextProvider.InvalidIndex ) + if (testPos == MaskedTextProvider.InvalidIndex) { // this will continue to execute (fail) until the end of the text so we fire the event for each remaining char. OnMaskInputRejected(new MaskInputRejectedEventArgs(startPosition, MaskedTextResultHint.UnavailableEditPosition)); @@ -2415,15 +2415,15 @@ private void Replace(string text, int startPosition, int selectionLen) // Always set the mtp, the formatted text could be the same but the assigned positions may be different. this.maskedTextProvider = clonedProvider; - + // Update text if needed. - if( updateText ) + if (updateText) { SetText(); // Update caret position. this.caretTestPos = startPosition; - base.SelectInternal( this.caretTestPos, 0, this.maskedTextProvider.Length ); + base.SelectInternal(this.caretTestPos, 0, this.maskedTextProvider.Length); } else { @@ -2438,16 +2438,16 @@ private void Replace(string text, int startPosition, int selectionLen) /// input is longer than selected text, and/or removing remaining characters from the selection if /// input contains less characters. /// - private void PasteInt( string text ) + private void PasteInt(string text) { - Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." ); - + Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); + int selStart, selLength; base.GetSelectionStartAndLength(out selStart, out selLength); - if( string.IsNullOrEmpty(text) ) + if (string.IsNullOrEmpty(text)) { - Delete( Keys.Delete, selStart, selLength ); + Delete(Keys.Delete, selStart, selLength); } else { @@ -2471,8 +2471,8 @@ private object PerformTypeValidation(CancelEventArgs e) if (this.validatingType != null) { string message = null; - - if (!this.flagState[IS_NULL_MASK]&& this.maskedTextProvider.MaskCompleted == false) + + if (!this.flagState[IS_NULL_MASK] && this.maskedTextProvider.MaskCompleted == false) { message = SR.MaskedTextBoxIncompleteMsg; } @@ -2480,7 +2480,7 @@ private object PerformTypeValidation(CancelEventArgs e) { string textValue; - if( !this.flagState[IS_NULL_MASK]) // replace prompt with space. + if (!this.flagState[IS_NULL_MASK]) // replace prompt with space. { textValue = this.maskedTextProvider.ToString(/*includePrompt*/ false, this.IncludeLiterals); } @@ -2523,11 +2523,11 @@ private object PerformTypeValidation(CancelEventArgs e) isValidInput = true; message = SR.MaskedTextBoxTypeValidationSucceeded; } - + TypeValidationEventArgs tve = new TypeValidationEventArgs(this.validatingType, isValidInput, parseRetVal, message); OnTypeValidationCompleted(tve); - if( e != null ) + if (e != null) { e.Cancel = tve.Cancel; } @@ -2543,16 +2543,16 @@ private object PerformTypeValidation(CancelEventArgs e) private bool PlaceChar(char ch, int startPosition, int length, bool overwrite, out MaskedTextResultHint hint) { - return PlaceChar(this.maskedTextProvider, ch, startPosition, length, overwrite, out hint ); + return PlaceChar(this.maskedTextProvider, ch, startPosition, length, overwrite, out hint); } /// /// Override version to be able to perform the operation on a cloned provider. /// - private bool PlaceChar(MaskedTextProvider provider, char ch, int startPosition, int length, bool overwrite, + private bool PlaceChar(MaskedTextProvider provider, char ch, int startPosition, int length, bool overwrite, out MaskedTextResultHint hint) { - Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." ); + Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); this.caretTestPos = startPosition; @@ -2635,7 +2635,7 @@ protected internal override bool ProcessKeyMessage(ref Message m) { // call base's method so the WM_CHAR and other messages are processed; this gives Control the // chance to flush all pending WM_CHAR processing after WM_IME_CHAR messages are generated. - + bool msgProcessed = base.ProcessKeyMessage(ref m); if (this.flagState[IS_NULL_MASK]) @@ -2646,14 +2646,15 @@ protected internal override bool ProcessKeyMessage(ref Message m) // If this WM_CHAR message is sent after WM_IME_CHAR, we ignore it since we already processed // the corresponding WM_IME_CHAR message. - if( m.Msg == Interop.WindowMessages.WM_CHAR && base.ImeWmCharsToIgnore > 0 ) { + if (m.Msg == Interop.WindowMessages.WM_CHAR && base.ImeWmCharsToIgnore > 0) + { return true; // meaning, we handled the message so it is not passed to the default WndProc. } return msgProcessed; } - + /// /// Designe time support for resetting Culture property.. /// @@ -2668,7 +2669,7 @@ private void ResetCulture() [ EditorBrowsable(EditorBrowsableState.Never) ] - public new void ScrollToCaret() + public new void ScrollToCaret() { } @@ -2677,29 +2678,29 @@ private void ResetCulture() /// and one of its properties, backed up by the MaskedTextProvider, changes; this requires /// recreating the provider because it is immutable. /// - private void SetMaskedTextProvider( MaskedTextProvider newProvider ) + private void SetMaskedTextProvider(MaskedTextProvider newProvider) { - SetMaskedTextProvider( newProvider, null); + SetMaskedTextProvider(newProvider, null); } /// /// Overload to allow for passing the text when the mask is being changed from null, /// in this case the maskedTextProvider holds backend info only (not the text). /// - private void SetMaskedTextProvider( MaskedTextProvider newProvider, string textOnInitializingMask ) + private void SetMaskedTextProvider(MaskedTextProvider newProvider, string textOnInitializingMask) { - Debug.Assert( newProvider != null, "Initializing from a null MaskProvider ref." ); - + Debug.Assert(newProvider != null, "Initializing from a null MaskProvider ref."); + // Set R/W properties. - newProvider.IncludePrompt = this.maskedTextProvider.IncludePrompt; - newProvider.IncludeLiterals = this.maskedTextProvider.IncludeLiterals; - newProvider.SkipLiterals = this.maskedTextProvider.SkipLiterals; - newProvider.ResetOnPrompt = this.maskedTextProvider.ResetOnPrompt; - newProvider.ResetOnSpace = this.maskedTextProvider.ResetOnSpace; + newProvider.IncludePrompt = this.maskedTextProvider.IncludePrompt; + newProvider.IncludeLiterals = this.maskedTextProvider.IncludeLiterals; + newProvider.SkipLiterals = this.maskedTextProvider.SkipLiterals; + newProvider.ResetOnPrompt = this.maskedTextProvider.ResetOnPrompt; + newProvider.ResetOnSpace = this.maskedTextProvider.ResetOnSpace; // If mask not initialized and not initializing it, the new provider is just a property backend. // Change won't have any effect in text. - if( this.flagState[IS_NULL_MASK] && textOnInitializingMask == null) + if (this.flagState[IS_NULL_MASK] && textOnInitializingMask == null) { this.maskedTextProvider = newProvider; return; @@ -2709,7 +2710,7 @@ private void SetMaskedTextProvider( MaskedTextProvider newProvider, string textO bool raiseOnMaskInputRejected = false; // Raise if new provider rejects old text. MaskedTextResultHint hint = MaskedTextResultHint.NoEffect; MaskedTextProvider oldProvider = this.maskedTextProvider; - + // Attempt to add previous text. // If the mask is the same, we need to preserve the caret and character positions if the text is added successfully. bool preserveCharPos = oldProvider.Mask == newProvider.Mask; @@ -2719,14 +2720,14 @@ private void SetMaskedTextProvider( MaskedTextProvider newProvider, string textO // NOTE: Whenever changing the MTP, the text is lost if any character in the old text violates the new provider's mask. - if( textOnInitializingMask != null ) // Changing Mask (from null), which is the only RO property that requires passing text. + if (textOnInitializingMask != null) // Changing Mask (from null), which is the only RO property that requires passing text. { - oldText = textOnInitializingMask; - raiseOnMaskInputRejected = !newProvider.Set( textOnInitializingMask, out testPos, out hint ); + oldText = textOnInitializingMask; + raiseOnMaskInputRejected = !newProvider.Set(textOnInitializingMask, out testPos, out hint); } else { - oldText = TextOutput; + oldText = TextOutput; // We need to attempt to set the input characters one by one in the edit positions so they are not // escaped. @@ -2734,10 +2735,10 @@ private void SetMaskedTextProvider( MaskedTextProvider newProvider, string textO int srcPos = 0; int dstPos = 0; - while( assignedCount > 0 ) + while (assignedCount > 0) { - srcPos = oldProvider.FindAssignedEditPositionFrom( srcPos, forward ); - Debug.Assert( srcPos != MaskedTextProvider.InvalidIndex, "InvalidIndex unexpected at this time." ); + srcPos = oldProvider.FindAssignedEditPositionFrom(srcPos, forward); + Debug.Assert(srcPos != MaskedTextProvider.InvalidIndex, "InvalidIndex unexpected at this time."); if (preserveCharPos) { @@ -2757,7 +2758,7 @@ private void SetMaskedTextProvider( MaskedTextProvider newProvider, string textO } } - if( !newProvider.Replace( oldProvider[srcPos], dstPos, out testPos, out hint )) + if (!newProvider.Replace(oldProvider[srcPos], dstPos, out testPos, out hint)) { preserveCharPos = false; newProvider.Clear(); @@ -2776,19 +2777,19 @@ private void SetMaskedTextProvider( MaskedTextProvider newProvider, string textO // Set provider. this.maskedTextProvider = newProvider; - if( this.flagState[IS_NULL_MASK] ) + if (this.flagState[IS_NULL_MASK]) { this.flagState[IS_NULL_MASK] = false; } // Raising events need to be done only after the new provider has been set so the MTB is in a state where properties // can be queried from event handlers safely. - if( raiseOnMaskInputRejected ) + if (raiseOnMaskInputRejected) { OnMaskInputRejected(new MaskInputRejectedEventArgs(testPos, hint)); } - if( newProvider.IsPassword ) + if (newProvider.IsPassword) { // Reset native edit control so the MaskedTextBox will take control over the characters that // need to be replaced with the password char (the input text characters). @@ -2839,19 +2840,19 @@ private void SetWindowText(string text, bool raiseTextChangedEvent, bool preserv try { - if( preserveCaret ) + if (preserveCaret) { this.caretTestPos = this.SelectionStart; } WindowText = text; // this calls Win32::SetWindowText directly, no OnTextChanged raised. - if( raiseTextChangedEvent ) + if (raiseTextChangedEvent) { OnTextChanged(EventArgs.Empty); } - if( preserveCaret ) + if (preserveCaret) { this.SelectionStart = this.caretTestPos; } @@ -2859,7 +2860,7 @@ private void SetWindowText(string text, bool raiseTextChangedEvent, bool preserv finally { this.flagState[QUERY_BASE_TEXT] = false; - } + } } /// @@ -2895,16 +2896,16 @@ public object ValidateText() /// private bool WmClear() { - Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." ); - - if( !this.ReadOnly ) + Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); + + if (!this.ReadOnly) { int selStart, selLength; - base.GetSelectionStartAndLength( out selStart, out selLength ); + base.GetSelectionStartAndLength(out selStart, out selLength); Delete(Keys.Delete, selStart, selLength); return true; } - + return false; } @@ -2915,7 +2916,7 @@ private bool WmClear() /// private bool WmCopy() { - Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." ); + Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); if (this.maskedTextProvider.IsPassword) // cannot copy password to clipboard. { @@ -2956,7 +2957,7 @@ private bool WmCopy() /// private bool WmImeComposition(ref Message m) { - Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." ); + Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); #if DEBUG if (this.ReadOnly || this.maskedTextProvider.IsPassword) @@ -3005,18 +3006,18 @@ private bool WmImeComposition(ref Message m) /// private bool WmImeStartComposition() { - Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." ); - + Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); + // Position the composition window in a valid place. - + int startPosition, selectionLen; - base.GetSelectionStartAndLength( out startPosition, out selectionLen ); + base.GetSelectionStartAndLength(out startPosition, out selectionLen); + + int startEditPos = this.maskedTextProvider.FindEditPositionFrom(startPosition, forward); - int startEditPos = this.maskedTextProvider.FindEditPositionFrom( startPosition, forward ); - - if( startEditPos != MaskedTextProvider.InvalidIndex ) + if (startEditPos != MaskedTextProvider.InvalidIndex) { - if (selectionLen > 0 && (ImeModeConversion.InputLanguageTable == ImeModeConversion.KoreanTable)) + if (selectionLen > 0 && (ImeModeConversion.InputLanguageTable == ImeModeConversion.KoreanTable)) { // Korean IME: We need to delete the selected text and reposition the caret so the IME processes one // character only, otherwise it would overwrite the selection with the caret (composition string), @@ -3038,9 +3039,9 @@ private bool WmImeStartComposition() } // update caret position. - if( startPosition != startEditPos ) + if (startPosition != startEditPos) { - this.caretTestPos = startEditPos; + this.caretTestPos = startEditPos; this.SelectionStart = this.caretTestPos; } @@ -3064,9 +3065,9 @@ private bool WmImeStartComposition() /// private void WmPaste() { - Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." ); + Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); - if( this.ReadOnly ) + if (this.ReadOnly) { return; } @@ -3089,15 +3090,19 @@ private void WmPaste() return; } - PasteInt( text ); + PasteInt(text); } - private void WmPrint(ref Message m) { + private void WmPrint(ref Message m) + { base.WndProc(ref m); - if ((NativeMethods.PRF_NONCLIENT & unchecked( (int) (long)m.LParam)) != 0 && Application.RenderWithVisualStyles && this.BorderStyle == BorderStyle.Fixed3D) { - using (Graphics g = Graphics.FromHdc(m.WParam)) { + if ((NativeMethods.PRF_NONCLIENT & unchecked((int)(long)m.LParam)) != 0 && Application.RenderWithVisualStyles && this.BorderStyle == BorderStyle.Fixed3D) + { + using (Graphics g = Graphics.FromHdc(m.WParam)) + { Rectangle rect = new Rectangle(0, 0, this.Size.Width - 1, this.Size.Height - 1); - using (Pen pen = new Pen(VisualStyleInformation.TextControlBorder)) { + using (Pen pen = new Pen(VisualStyleInformation.TextControlBorder)) + { g.DrawRectangle(pen, rect); } rect.Inflate(-1, -1); @@ -3134,7 +3139,7 @@ protected override void WndProc(ref Message m) break; // continue. } - if( this.flagState[IS_NULL_MASK]) + if (this.flagState[IS_NULL_MASK]) { base.WndProc(ref m); // Operates as a regular text box base. return; @@ -3143,7 +3148,7 @@ protected override void WndProc(ref Message m) switch (m.Msg) { case Interop.WindowMessages.WM_IME_STARTCOMPOSITION: - if( WmImeStartComposition() ) + if (WmImeStartComposition()) { break; } @@ -3154,7 +3159,7 @@ protected override void WndProc(ref Message m) goto default; case Interop.WindowMessages.WM_IME_COMPOSITION: - if( WmImeComposition( ref m ) ) + if (WmImeComposition(ref m)) { break; } @@ -3200,16 +3205,16 @@ protected override void WndProc(ref Message m) /// private void WmKillFocus() { - Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." ); + Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); - base.GetSelectionStartAndLength( out this.caretTestPos, out this.lastSelLength ); + base.GetSelectionStartAndLength(out this.caretTestPos, out this.lastSelLength); if (this.HidePromptOnLeave && !this.MaskFull) { SetWindowText(); // Update text w/ no prompt. // We need to update selection info in case the control is queried for it while it doesn't have the focus. - base.SelectInternal( this.caretTestPos, this.lastSelLength, this.maskedTextProvider.Length ); + base.SelectInternal(this.caretTestPos, this.lastSelLength, this.maskedTextProvider.Length); } } @@ -3219,16 +3224,16 @@ private void WmKillFocus() /// private void WmSetFocus() { - Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." ); - + Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); + if (this.HidePromptOnLeave && !this.MaskFull) // Prompt will show up. { SetWindowText(); } - + // Restore previous selection. Do this always (as opposed to within the condition above as in WmKillFocus) // because HidePromptOnLeave could have changed while the control did not have the focus. - base.SelectInternal( this.caretTestPos, this.lastSelLength, this.maskedTextProvider.Length ); + base.SelectInternal(this.caretTestPos, this.lastSelLength, this.maskedTextProvider.Length); } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListItemConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListItemConverter.cs index 1cad0873b8b..d41de9239b0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListItemConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListItemConverter.cs @@ -2,36 +2,40 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.ComponentModel; using System.Collections; - - internal class MdiWindowListItemConverter : ComponentConverter { - public MdiWindowListItemConverter(Type type) : base(type) { + + internal class MdiWindowListItemConverter : ComponentConverter + { + public MdiWindowListItemConverter(Type type) : base(type) + { } /// /// Gets a collection of standard values for the data type this validator is /// designed for. /// - public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { + public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) + { MenuStrip menu = context.Instance as MenuStrip; if (menu != null) { StandardValuesCollection values = base.GetStandardValues(context); ArrayList list = new ArrayList(); int count = values.Count; - for (int i=0; i this is the menu that merges into the MdiWindowListItem /// in an MDI parent when an MDI child is maximized. /// - internal class MdiWindowListStrip : MenuStrip { + internal class MdiWindowListStrip : MenuStrip + { private Form mdiParent = null; private ToolStripMenuItem mergeItem; private MenuStrip mergedMenu; - - public MdiWindowListStrip() { + + public MdiWindowListStrip() + { } - protected override void Dispose(bool disposing) { - if (disposing) { + protected override void Dispose(bool disposing) + { + if (disposing) + { mdiParent = null; - } - base.Dispose(disposing); + } + base.Dispose(disposing); } - internal ToolStripMenuItem MergeItem { - get { - if (mergeItem == null) { + internal ToolStripMenuItem MergeItem + { + get + { + if (mergeItem == null) + { mergeItem = new ToolStripMenuItem(); mergeItem.MergeAction = MergeAction.MatchOnly; } - if (mergeItem.Owner == null) { + if (mergeItem.Owner == null) + { this.Items.Add(mergeItem); } return mergeItem; } } - internal MenuStrip MergedMenu { - get { + internal MenuStrip MergedMenu + { + get + { return mergedMenu; } - set { + set + { mergedMenu = value; } } @@ -61,62 +73,71 @@ internal MenuStrip MergedMenu { /// enough in its working environment that we can't readily combine the two. /// But if you're fixing something here, chances are that the same issue will need scrutiny over there. /// - public void PopulateItems(Form mdiParent, ToolStripMenuItem mdiMergeItem, bool includeSeparator) { + public void PopulateItems(Form mdiParent, ToolStripMenuItem mdiMergeItem, bool includeSeparator) + { this.mdiParent = mdiParent; this.SuspendLayout(); MergeItem.DropDown.SuspendLayout(); - try { + try + { ToolStripMenuItem mergeItem = MergeItem; mergeItem.DropDownItems.Clear(); mergeItem.Text = mdiMergeItem.Text; Form[] forms = mdiParent.MdiChildren; - if(forms != null && forms.Length != 0){ + if (forms != null && forms.Length != 0) + { - if(includeSeparator) { + if (includeSeparator) + { ToolStripSeparator separator = new ToolStripSeparator(); separator.MergeAction = MergeAction.Append; separator.MergeIndex = -1; mergeItem.DropDownItems.Add(separator); } - + Form activeMdiChild = mdiParent.ActiveMdiChild; - + const int maxMenuForms = 9; // max number of Window menu items for forms int visibleChildren = 0; // number of visible child forms (so we know if we need to show More Windows... int accel = 1; // prefix the form name with this digit, underlined, as an accelerator int formsAddedToMenu = 0; bool activeFormAdded = false; - for (int i = 0; i < forms.Length; i++) { + for (int i = 0; i < forms.Length; i++) + { // we need to check close reason here because we could be getting called // here in the midst of a WM_CLOSE - WM_MDIDESTROY eventually fires a WM_MDIACTIVATE - if (forms[i].Visible && (forms[i].CloseReason == CloseReason.None)) { + if (forms[i].Visible && (forms[i].CloseReason == CloseReason.None)) + { visibleChildren++; - if ((activeFormAdded && (formsAddedToMenu < maxMenuForms)) || // don't exceed max - (!activeFormAdded && (formsAddedToMenu < (maxMenuForms-1)) || // save room for active if it's not in yet - (forms[i].Equals(activeMdiChild)))){ // there's always room for activeMdiChild - string text = WindowsFormsUtils.EscapeTextWithAmpersands(mdiParent.MdiChildren[i].Text); + if ((activeFormAdded && (formsAddedToMenu < maxMenuForms)) || // don't exceed max + (!activeFormAdded && (formsAddedToMenu < (maxMenuForms - 1)) || // save room for active if it's not in yet + (forms[i].Equals(activeMdiChild)))) + { // there's always room for activeMdiChild + string text = WindowsFormsUtils.EscapeTextWithAmpersands(mdiParent.MdiChildren[i].Text); text = (text == null) ? string.Empty : text; ToolStripMenuItem windowListItem = new ToolStripMenuItem(mdiParent.MdiChildren[i]); windowListItem.Text = string.Format(CultureInfo.CurrentCulture, "&{0} {1}", accel, text); windowListItem.MergeAction = MergeAction.Append; windowListItem.MergeIndex = accel; windowListItem.Click += new EventHandler(OnWindowListItemClick); - if (forms[i].Equals(activeMdiChild)) { // if this the active one, check it off. + if (forms[i].Equals(activeMdiChild)) + { // if this the active one, check it off. windowListItem.Checked = true; activeFormAdded = true; } accel++; formsAddedToMenu++; - Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose,"\tPopulateItems: Added " + windowListItem.Text); + Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "\tPopulateItems: Added " + windowListItem.Text); mergeItem.DropDownItems.Add(windowListItem); } } } // show the More Windows... item if necessary. - if (visibleChildren > maxMenuForms) { + if (visibleChildren > maxMenuForms) + { ToolStripMenuItem moreWindowsMenuItem = new ToolStripMenuItem(); moreWindowsMenuItem.Text = SR.MDIMenuMoreWindows; Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "\tPopulateItems: Added " + moreWindowsMenuItem.Text); @@ -126,7 +147,8 @@ public void PopulateItems(Form mdiParent, ToolStripMenuItem mdiMergeItem, bool i } } } - finally { + finally + { // this is an invisible toolstrip dont even bother doing layout. this.ResumeLayout(false); MergeItem.DropDown.ResumeLayout(false); @@ -134,20 +156,25 @@ public void PopulateItems(Form mdiParent, ToolStripMenuItem mdiMergeItem, bool i } /// handler for More Windows... This is similar to MenuItem.cs - private void OnMoreWindowsMenuItemClick(object sender, EventArgs e) { + private void OnMoreWindowsMenuItemClick(object sender, EventArgs e) + { + + Form[] forms = mdiParent.MdiChildren; - Form[] forms = mdiParent.MdiChildren; - - if (forms != null) { - using (MdiWindowDialog dialog = new MdiWindowDialog()) { + if (forms != null) + { + using (MdiWindowDialog dialog = new MdiWindowDialog()) + { dialog.SetItems(mdiParent.ActiveMdiChild, forms); DialogResult result = dialog.ShowDialog(); - if (result == DialogResult.OK) { + if (result == DialogResult.OK) + { // AllWindows Assert above allows this... // dialog.ActiveChildForm.Activate(); - if (dialog.ActiveChildForm.ActiveControl != null && !dialog.ActiveChildForm.ActiveControl.Focused) { + if (dialog.ActiveChildForm.ActiveControl != null && !dialog.ActiveChildForm.ActiveControl.Focused) + { dialog.ActiveChildForm.ActiveControl.Focus(); } } @@ -156,17 +183,21 @@ private void OnMoreWindowsMenuItemClick(object sender, EventArgs e) { } /// handler for 1 - 9. This is similar to MenuItem.cs - private void OnWindowListItemClick(object sender, EventArgs e) { + private void OnWindowListItemClick(object sender, EventArgs e) + { ToolStripMenuItem windowListItem = sender as ToolStripMenuItem; - if (windowListItem != null) { + if (windowListItem != null) + { Form boundForm = windowListItem.MdiForm; - - if (boundForm != null) { + + if (boundForm != null) + { boundForm.Activate(); - if (boundForm.ActiveControl != null && !boundForm.ActiveControl.Focused) { + if (boundForm.ActiveControl != null && !boundForm.ActiveControl.Focused) + { boundForm.ActiveControl.Focus(); - } + } } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MeasureItemEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MeasureItemEventArgs.cs index 1fe465991e9..d963c273837 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MeasureItemEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MeasureItemEventArgs.cs @@ -23,7 +23,7 @@ public MeasureItemEventArgs(Graphics graphics, int index, int itemHeight) ItemHeight = itemHeight; ItemWidth = 0; } - + /// /// A Graphics object to measure relative to. /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs index 8ca561a9574..8e6a19a6a4b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs @@ -18,10 +18,10 @@ namespace System.Windows.Forms [ListBindable(false)] public abstract class Menu : Component { - internal const int CHANGE_ITEMS = 0; // item(s) added or removed - internal const int CHANGE_VISIBLE = 1; // item(s) hidden or shown - internal const int CHANGE_MDI = 2; // mdi item changed - internal const int CHANGE_MERGE = 3; // mergeType or mergeOrder changed + internal const int CHANGE_ITEMS = 0; // item(s) added or removed + internal const int CHANGE_VISIBLE = 1; // item(s) hidden or shown + internal const int CHANGE_MDI = 2; // mdi item changed + internal const int CHANGE_MERGE = 3; // mergeType or mergeOrder changed internal const int CHANGE_ITEMADDED = 4; // mergeType or mergeOrder changed /// @@ -40,13 +40,15 @@ public abstract class Menu : Component internal bool created; private object userData; private string name; - + /// /// This is an abstract class. Instances cannot be created, so the constructor /// is only called from derived classes. /// - protected Menu(MenuItem[] items) { - if (items != null) { + protected Menu(MenuItem[] items) + { + if (items != null) + { MenuItems.AddRange(items); } } @@ -55,13 +57,16 @@ protected Menu(MenuItem[] items) { /// The HMENU handle corresponding to this menu. /// [ - Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), + Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlHandleDescr)) ] - public IntPtr Handle { - get { - if (handle == IntPtr.Zero) handle = CreateMenuHandle(); + public IntPtr Handle + { + get + { + if (handle == IntPtr.Zero) + handle = CreateMenuHandle(); CreateMenuItems(); return handle; } @@ -75,14 +80,18 @@ public IntPtr Handle { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.MenuIsParentDescr)) ] - public virtual bool IsParent { - get { + public virtual bool IsParent + { + get + { return null != items && ItemCount > 0; } } - internal int ItemCount { - get { + internal int ItemCount + { + get + { return _itemCount; } } @@ -95,15 +104,20 @@ internal int ItemCount { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.MenuMDIListItemDescr)) ] - public MenuItem MdiListItem { - get { - for (int i = 0; i < ItemCount; i++) { + public MenuItem MdiListItem + { + get + { + for (int i = 0; i < ItemCount; i++) + { MenuItem item = items[i]; if (item.MdiList) return item; - if (item.IsParent) { + if (item.IsParent) + { item = item.MdiListItem; - if (item != null) return item; + if (item != null) + return item; } } return null; @@ -119,23 +133,29 @@ public MenuItem MdiListItem { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false) ] - public string Name { - get { + public string Name + { + get + { return WindowsFormsUtils.GetComponentName(this, name); } - set { - if (value == null || value.Length == 0) { + set + { + if (value == null || value.Length == 0) + { name = null; } - else { - name = value; + else + { + name = value; } - if(Site!= null) { + if (Site != null) + { Site.Name = name; } } } - + [ Browsable(false), @@ -143,20 +163,25 @@ public string Name { SRDescription(nameof(SR.MenuMenuItemsDescr)), MergableProperty(false) ] - public MenuItemCollection MenuItems { - get { - if (itemsCollection == null) { + public MenuItemCollection MenuItems + { + get + { + if (itemsCollection == null) + { itemsCollection = new MenuItemCollection(this); } return itemsCollection; } } - internal virtual bool RenderIsRightToLeft { - get { + internal virtual bool RenderIsRightToLeft + { + get + { Debug.Assert(true, "Should never get called"); return false; - + } } @@ -169,25 +194,32 @@ internal virtual bool RenderIsRightToLeft { DefaultValue(null), TypeConverter(typeof(StringConverter)), ] - public object Tag { - get { + public object Tag + { + get + { return userData; } - set { + set + { userData = value; } } - + /// /// Notifies Menu that someone called Windows.DeleteMenu on its handle. /// - internal void ClearHandles() { - if (handle != IntPtr.Zero) { + internal void ClearHandles() + { + if (handle != IntPtr.Zero) + { UnsafeNativeMethods.DestroyMenu(new HandleRef(this, handle)); } handle = IntPtr.Zero; - if (created) { - for (int i = 0; i < ItemCount; i++) { + if (created) + { + for (int i = 0; i < ItemCount; i++) + { items[i].ClearHandles(); } created = false; @@ -200,52 +232,63 @@ internal void ClearHandles() { [ SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly") // Shipped as is in Everett ] - protected internal void CloneMenu(Menu menuSrc) { + protected internal void CloneMenu(Menu menuSrc) + { if (menuSrc == null) { throw new ArgumentNullException(nameof(menuSrc)); } MenuItem[] newItems = null; - if (menuSrc.items != null) { + if (menuSrc.items != null) + { int count = menuSrc.MenuItems.Count; newItems = new MenuItem[count]; for (int i = 0; i < count; i++) newItems[i] = menuSrc.MenuItems[i].CloneMenu(); } MenuItems.Clear(); - if (newItems != null) { + if (newItems != null) + { MenuItems.AddRange(newItems); } } /// /// - - - protected virtual IntPtr CreateMenuHandle() { + + + protected virtual IntPtr CreateMenuHandle() + { return UnsafeNativeMethods.CreatePopupMenu(); } /// /// - internal void CreateMenuItems() { - if (!created) { - for (int i = 0; i < ItemCount; i++) { + internal void CreateMenuItems() + { + if (!created) + { + for (int i = 0; i < ItemCount; i++) + { items[i].CreateMenuItem(); } created = true; } } - + /// /// - internal void DestroyMenuItems() { - if (created) { - for (int i = 0; i < ItemCount; i++) { + internal void DestroyMenuItems() + { + if (created) + { + for (int i = 0; i < ItemCount; i++) + { items[i].ClearHandles(); } - while (UnsafeNativeMethods.GetMenuItemCount(new HandleRef(this, handle)) > 0) { + while (UnsafeNativeMethods.GetMenuItemCount(new HandleRef(this, handle)) > 0) + { UnsafeNativeMethods.RemoveMenu(new HandleRef(this, handle), 0, NativeMethods.MF_BYPOSITION); } created = false; @@ -257,15 +300,19 @@ internal void DestroyMenuItems() { /// This method removes the component from its container (if the component has a site) /// and triggers the dispose event. /// - protected override void Dispose(bool disposing) { - if (disposing) { - while (ItemCount > 0) { + protected override void Dispose(bool disposing) + { + if (disposing) + { + while (ItemCount > 0) + { MenuItem item = items[--_itemCount]; // remove the item before we dispose it so it still has valid state // for undo/redo // - if (item.Site != null && item.Site.Container != null) { + if (item.Site != null && item.Site.Container != null) + { item.Site.Container.Remove(item); } @@ -274,39 +321,49 @@ protected override void Dispose(bool disposing) { } items = null; } - if (handle != IntPtr.Zero) { + if (handle != IntPtr.Zero) + { UnsafeNativeMethods.DestroyMenu(new HandleRef(this, handle)); this.handle = IntPtr.Zero; - if (disposing) { + if (disposing) + { ClearHandles(); } } base.Dispose(disposing); } - public MenuItem FindMenuItem(int type, IntPtr value) { - for (int i = 0; i < ItemCount; i++) { + public MenuItem FindMenuItem(int type, IntPtr value) + { + for (int i = 0; i < ItemCount; i++) + { MenuItem item = items[i]; - switch (type) { + switch (type) + { case FindHandle: - if (item.handle == value) return item; + if (item.handle == value) + return item; break; case FindShortcut: - if (item.Shortcut == (Shortcut)(int)value) return item; + if (item.Shortcut == (Shortcut)(int)value) + return item; break; } item = item.FindMenuItem(type, value); - if (item != null) return item; + if (item != null) + return item; } return null; } /// /// - protected int FindMergePosition(int mergeOrder) { + protected int FindMergePosition(int mergeOrder) + { int iMin, iLim, iT; - for (iMin = 0, iLim = ItemCount; iMin < iLim;) { + for (iMin = 0, iLim = ItemCount; iMin < iLim;) + { iT = (iMin + iLim) / 2; if (items[iT].MergeOrder <= mergeOrder) iMin = iT + 1; @@ -315,7 +372,7 @@ protected int FindMergePosition(int mergeOrder) { } return iMin; } - + /// /// // A new method for finding the approximate merge position. The original @@ -323,22 +380,27 @@ protected int FindMergePosition(int mergeOrder) { // as it's guaranteed to be in the MDI imlementation of merging container and child // menus. However, user code can call MergeMenu independently on a source and target // menu whose MergeOrder values are not necessarily pre-sorted. - internal int xFindMergePosition(int mergeOrder) { + internal int xFindMergePosition(int mergeOrder) + { int nPosition = 0; // Iterate from beginning to end since we can't assume any sequential ordering to MergeOrder - for (int nLoop = 0; nLoop < ItemCount; nLoop++) { + for (int nLoop = 0; nLoop < ItemCount; nLoop++) + { - if (items[nLoop].MergeOrder > mergeOrder) { + if (items[nLoop].MergeOrder > mergeOrder) + { // We didn't find what we're looking for, but we've found a stopping point. break; } - else if (items[nLoop].MergeOrder < mergeOrder) { + else if (items[nLoop].MergeOrder < mergeOrder) + { // We might have found what we're looking for, but we'll have to come around again // to know. nPosition = nLoop + 1; } - else if (mergeOrder == items[nLoop].MergeOrder) { + else if (mergeOrder == items[nLoop].MergeOrder) + { // We've found what we're looking for, so use this value for the merge order nPosition = nLoop; break; @@ -350,8 +412,10 @@ internal int xFindMergePosition(int mergeOrder) { //There's a win32 problem that doesn't allow menus to cascade right to left //unless we explicitely set the bit on the menu the first time it pops up - internal void UpdateRtl(bool setRightToLeftBit) { - foreach (MenuItem item in MenuItems) { + internal void UpdateRtl(bool setRightToLeftBit) + { + foreach (MenuItem item in MenuItems) + { item.UpdateItemRtl(setRightToLeftBit); item.UpdateRtl(setRightToLeftBit); } @@ -364,13 +428,16 @@ internal void UpdateRtl(bool setRightToLeftBit) { /// This can occur if it's contained in a MainMenu or if it isn't /// currently contained in any menu at all. /// - public ContextMenu GetContextMenu() { + public ContextMenu GetContextMenu() + { Menu menuT; - for (menuT = this; !(menuT is ContextMenu);) { - if (!(menuT is MenuItem)) return null; + for (menuT = this; !(menuT is ContextMenu);) + { + if (!(menuT is MenuItem)) + return null; menuT = ((MenuItem)menuT).Parent; } - return(ContextMenu)menuT; + return (ContextMenu)menuT; } @@ -381,19 +448,24 @@ public ContextMenu GetContextMenu() { /// This can occur if it's contained in a ContextMenu or if it isn't /// currently contained in any menu at all. /// - public MainMenu GetMainMenu() { + public MainMenu GetMainMenu() + { Menu menuT; - for (menuT = this; !(menuT is MainMenu);) { - if (!(menuT is MenuItem)) return null; + for (menuT = this; !(menuT is MainMenu);) + { + if (!(menuT is MenuItem)) + return null; menuT = ((MenuItem)menuT).Parent; } - return(MainMenu)menuT; + return (MainMenu)menuT; } /// /// - internal virtual void ItemsChanged(int change) { - switch (change) { + internal virtual void ItemsChanged(int change) + { + switch (change) + { case CHANGE_ITEMS: case CHANGE_VISIBLE: DestroyMenuItems(); @@ -410,19 +482,24 @@ internal virtual void ItemsChanged(int change) { /// index of matching item, and action for OS to take (execute or select). Zero is /// used to indicate that no match was found (OS should ignore key and beep). /// - private IntPtr MatchKeyToMenuItem(int startItem, char key, MenuItemKeyComparer comparer) { + private IntPtr MatchKeyToMenuItem(int startItem, char key, MenuItemKeyComparer comparer) + { int firstMatch = -1; bool multipleMatches = false; - for (int i = 0; i < items.Length && !multipleMatches; ++i) { + for (int i = 0; i < items.Length && !multipleMatches; ++i) + { int itemIndex = (startItem + i) % items.Length; MenuItem mi = items[itemIndex]; - if (mi != null && comparer(mi, key)) { - if (firstMatch < 0){ + if (mi != null && comparer(mi, key)) + { + if (firstMatch < 0) + { // Using Index doesnt respect hidden items. firstMatch = mi.MenuIndex; } - else { + else + { multipleMatches = true; } } @@ -432,7 +509,7 @@ private IntPtr MatchKeyToMenuItem(int startItem, char key, MenuItemKeyComparer c return IntPtr.Zero; int action = multipleMatches ? NativeMethods.MNC_SELECT : NativeMethods.MNC_EXECUTE; - return (IntPtr) NativeMethods.Util.MAKELONG(firstMatch, action); + return (IntPtr)NativeMethods.Util.MAKELONG(firstMatch, action); } /// Delegate type used by MatchKeyToMenuItem @@ -446,7 +523,8 @@ private IntPtr MatchKeyToMenuItem(int startItem, char key, MenuItemKeyComparer c [ SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly") // Shipped as is in Everett ] - public virtual void MergeMenu(Menu menuSrc) { + public virtual void MergeMenu(Menu menuSrc) + { if (menuSrc == null) { throw new ArgumentNullException(nameof(menuSrc)); @@ -460,14 +538,17 @@ public virtual void MergeMenu(Menu menuSrc) { MenuItem item; MenuItem itemDst; - if (menuSrc.items != null && items == null) { - MenuItems.Clear(); + if (menuSrc.items != null && items == null) + { + MenuItems.Clear(); } - for (i = 0; i < menuSrc.ItemCount; i++) { + for (i = 0; i < menuSrc.ItemCount; i++) + { item = menuSrc.items[i]; - switch (item.MergeType) { + switch (item.MergeType) + { default: continue; case MenuMerge.Add: @@ -485,26 +566,32 @@ public virtual void MergeMenu(Menu menuSrc) { // as it's guaranteed to be in the MDI imlementation of merging container and child // menus. However, user code can call MergeMenu independently on a source and target // menu whose MergeOrder values are not necessarily pre-sorted. - for (j = xFindMergePosition(mergeOrder); ; j++) { + for (j = xFindMergePosition(mergeOrder); ; j++) + { - if (j >= ItemCount) { + if (j >= ItemCount) + { // A matching merge position could not be found, // so simply append this menu item to the end. MenuItems.Add(j, item.MergeMenu()); break; } itemDst = items[j]; - if (itemDst.MergeOrder != mergeOrder) { + if (itemDst.MergeOrder != mergeOrder) + { MenuItems.Add(j, item.MergeMenu()); break; } - if (itemDst.MergeType != MenuMerge.Add) { + if (itemDst.MergeType != MenuMerge.Add) + { if (item.MergeType != MenuMerge.MergeItems - || itemDst.MergeType != MenuMerge.MergeItems) { + || itemDst.MergeType != MenuMerge.MergeItems) + { itemDst.Dispose(); MenuItems.Add(j, item.MergeMenu()); } - else { + else + { itemDst.MergeMenu(item); } break; @@ -515,9 +602,11 @@ public virtual void MergeMenu(Menu menuSrc) { /// /// - internal virtual bool ProcessInitMenuPopup(IntPtr handle) { + internal virtual bool ProcessInitMenuPopup(IntPtr handle) + { MenuItem item = FindMenuItem(FindHandle, handle); - if (item != null) { + if (item != null) + { item.OnInitMenuPopup(EventArgs.Empty); item.CreateMenuItems(); return true; @@ -527,18 +616,22 @@ internal virtual bool ProcessInitMenuPopup(IntPtr handle) { /// /// - protected internal virtual bool ProcessCmdKey(ref Message msg, Keys keyData) { + protected internal virtual bool ProcessCmdKey(ref Message msg, Keys keyData) + { MenuItem item = FindMenuItem(FindShortcut, (IntPtr)(int)keyData); - return item != null? item.ShortcutClick(): false; + return item != null ? item.ShortcutClick() : false; } /// /// Returns index of currently selected menu item in /// this menu, or -1 if no item is currently selected. /// - internal int SelectedMenuItemIndex { - get { - for (int i = 0; i < items.Length; ++i) { + internal int SelectedMenuItemIndex + { + get + { + for (int i = 0; i < items.Length; ++i) + { MenuItem mi = items[i]; if (mi != null && mi.Selected) return i; @@ -551,7 +644,8 @@ internal int SelectedMenuItemIndex { /// /// Returns a string representation for this control. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); return s + ", Items.Count: " + ItemCount.ToString(CultureInfo.CurrentCulture); @@ -561,13 +655,14 @@ public override string ToString() { /// Handles the WM_MENUCHAR message, forwarding it to the intended Menu /// object. All the real work is done inside WmMenuCharInternal(). /// - internal void WmMenuChar(ref Message m) { + internal void WmMenuChar(ref Message m) + { Menu menu = (m.LParam == handle) ? this : FindMenuItem(FindHandle, m.LParam); if (menu == null) return; - char menuKey = char.ToUpper((char) NativeMethods.Util.LOWORD(m.WParam), CultureInfo.CurrentCulture); + char menuKey = char.ToUpper((char)NativeMethods.Util.LOWORD(m.WParam), CultureInfo.CurrentCulture); m.Result = menu.WmMenuCharInternal(menuKey); } @@ -577,7 +672,8 @@ internal void WmMenuChar(ref Message m) { /// means *all* menu items on a menu when IsImageMarginPresent == true). Attempts to /// simulate the exact behavior that the OS provides for non owner-draw menu items. /// - internal IntPtr WmMenuCharInternal(char key) { + internal IntPtr WmMenuCharInternal(char key) + { // Start looking just beyond the current selected item (otherwise just start at the top) int startItem = (SelectedMenuItemIndex + 1) % items.Length; @@ -592,13 +688,15 @@ internal IntPtr WmMenuCharInternal(char key) { } /// MenuItemKeyComparer delegate used by WmMenuCharInternal - private bool CheckOwnerDrawItemWithMnemonic(MenuItem mi, char key) { + private bool CheckOwnerDrawItemWithMnemonic(MenuItem mi, char key) + { return mi.OwnerDraw && mi.Mnemonic == key; } /// MenuItemKeyComparer delegate used by WmMenuCharInternal - private bool CheckOwnerDrawItemNoMnemonic(MenuItem mi, char key) { + private bool CheckOwnerDrawItemNoMnemonic(MenuItem mi, char key) + { return mi.OwnerDraw && mi.Mnemonic == 0 && mi.Text.Length > 0 && @@ -606,7 +704,8 @@ private bool CheckOwnerDrawItemNoMnemonic(MenuItem mi, char key) { } [ListBindable(false)] - public class MenuItemCollection : IList { + public class MenuItemCollection : IList + { private Menu owner; /// A caching mechanism for key accessor @@ -614,24 +713,30 @@ public class MenuItemCollection : IList { /// issues by holding on to extra references. private int lastAccessedIndex = -1; - public MenuItemCollection(Menu owner) { + public MenuItemCollection(Menu owner) + { this.owner = owner; } - - public virtual MenuItem this[int index] { - get { + + public virtual MenuItem this[int index] + { + get + { if (index < 0 || index >= owner.ItemCount) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); return owner.items[index]; } // set not supported } - - object IList.this[int index] { - get { + + object IList.this[int index] + { + get + { return this[index]; } - set { + set + { throw new NotSupportedException(); } } @@ -639,51 +744,66 @@ object IList.this[int index] { /// /// Retrieves the child control with the specified key. /// - public virtual MenuItem this[string key] { - get { + public virtual MenuItem this[string key] + { + get + { // We do not support null and empty string as valid keys. - if (string.IsNullOrEmpty(key)){ + if (string.IsNullOrEmpty(key)) + { return null; } // Search for the key in our collection int index = IndexOfKey(key); - if (IsValidIndex(index)) { + if (IsValidIndex(index)) + { return this[index]; } - else { + else + { return null; } } } - - public int Count { - get { + + public int Count + { + get + { return owner.ItemCount; } } - object ICollection.SyncRoot { - get { + object ICollection.SyncRoot + { + get + { return this; } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return false; } } - - bool IList.IsFixedSize { - get { + + bool IList.IsFixedSize + { + get + { return false; } } - - public bool IsReadOnly { - get { + + public bool IsReadOnly + { + get + { return false; } } @@ -692,7 +812,8 @@ public bool IsReadOnly { /// /// Adds a new MenuItem to the end of this menu with the specified caption. /// - public virtual MenuItem Add(string caption) { + public virtual MenuItem Add(string caption) + { MenuItem item = new MenuItem(caption); Add(item); return item; @@ -702,7 +823,8 @@ public virtual MenuItem Add(string caption) { /// Adds a new MenuItem to the end of this menu with the specified caption, /// and click handler. /// - public virtual MenuItem Add(string caption, EventHandler onClick) { + public virtual MenuItem Add(string caption, EventHandler onClick) + { MenuItem item = new MenuItem(caption, onClick); Add(item); return item; @@ -712,7 +834,8 @@ public virtual MenuItem Add(string caption, EventHandler onClick) { /// Adds a new MenuItem to the end of this menu with the specified caption, /// click handler, and items. /// - public virtual MenuItem Add(string caption, MenuItem[] items) { + public virtual MenuItem Add(string caption, MenuItem[] items) + { MenuItem item = new MenuItem(caption, items); Add(item); return item; @@ -723,7 +846,8 @@ public virtual MenuItem Add(string caption, MenuItem[] items) { /// MenuItems can only be contained in one menu at a time, and may not be added /// more than once to the same menu. /// - public virtual int Add(MenuItem item) { + public virtual int Add(MenuItem item) + { return Add(owner.ItemCount, item); } @@ -733,26 +857,31 @@ public virtual int Add(MenuItem item) { /// MenuItems can only be contained in one menu at a time, and may not be added /// more than once to the same menu. /// - public virtual int Add(int index, MenuItem item) { + public virtual int Add(int index, MenuItem item) + { if (item == null) { throw new ArgumentNullException(nameof(item)); } - + // MenuItems can only belong to one menu at a time - if (item.Parent != null) { + if (item.Parent != null) + { // First check that we're not adding ourself, i.e. walk // the parent chain for equality - if (owner is MenuItem) { + if (owner is MenuItem) + { MenuItem parent = (MenuItem)owner; - while (parent != null) { - if (parent.Equals(item)) { + while (parent != null) + { + if (parent.Equals(item)) + { throw new ArgumentException(string.Format(SR.MenuItemAlreadyExists, item.Text), "item"); } if (parent.Parent is MenuItem) parent = (MenuItem)parent.Parent; - else + else break; } } @@ -760,7 +889,8 @@ public virtual int Add(int index, MenuItem item) { //if we're re-adding an item back to the same collection //the target index needs to be decremented since we're //removing an item from the collection - if (item.Parent.Equals(owner) && index > 0) { + if (item.Parent.Equals(owner) && index > 0) + { index--; } @@ -768,13 +898,16 @@ public virtual int Add(int index, MenuItem item) { } // Validate our index - if (index < 0 || index > owner.ItemCount) { + if (index < 0 || index > owner.ItemCount) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - - if (owner.items == null || owner.items.Length == owner.ItemCount) { - MenuItem[] newItems = new MenuItem[owner.ItemCount < 2? 4: owner.ItemCount * 2]; - if (owner.ItemCount > 0) System.Array.Copy(owner.items, 0, newItems, 0, owner.ItemCount); + + if (owner.items == null || owner.items.Length == owner.ItemCount) + { + MenuItem[] newItems = new MenuItem[owner.ItemCount < 2 ? 4 : owner.ItemCount * 2]; + if (owner.ItemCount > 0) + System.Array.Copy(owner.items, 0, newItems, 0, owner.ItemCount); owner.items = newItems; } System.Array.Copy(owner.items, index, owner.items, index + 1, owner.ItemCount - index); @@ -782,49 +915,61 @@ public virtual int Add(int index, MenuItem item) { owner._itemCount++; item.Parent = owner; owner.ItemsChanged(CHANGE_ITEMS); - if (owner is MenuItem) { - ((MenuItem) owner).ItemsChanged(CHANGE_ITEMADDED, item); + if (owner is MenuItem) + { + ((MenuItem)owner).ItemsChanged(CHANGE_ITEMADDED, item); } return index; } - - public virtual void AddRange(MenuItem[] items) { - if (items == null) { + + public virtual void AddRange(MenuItem[] items) + { + if (items == null) + { throw new ArgumentNullException(nameof(items)); } - foreach(MenuItem item in items) { + foreach (MenuItem item in items) + { Add(item); } } - int IList.Add(object value) { - if (value is MenuItem) { + int IList.Add(object value) + { + if (value is MenuItem) + { return Add((MenuItem)value); } - else { + else + { throw new ArgumentException(SR.MenuBadMenuItem, "value"); } } - - public bool Contains(MenuItem value) { + + public bool Contains(MenuItem value) + { return IndexOf(value) != -1; } - - bool IList.Contains(object value) { - if (value is MenuItem) { + + bool IList.Contains(object value) + { + if (value is MenuItem) + { return Contains((MenuItem)value); } - else { + else + { return false; } } - + /// /// Returns true if the collection contains an item with the specified key, false otherwise. /// - public virtual bool ContainsKey(string key) { - return IsValidIndex(IndexOfKey(key)); + public virtual bool ContainsKey(string key) + { + return IsValidIndex(IndexOfKey(key)); } /// @@ -832,17 +977,19 @@ public virtual bool ContainsKey(string key) { /// of all the controls that match. /// /// - public MenuItem [] Find(string key, bool searchAllChildren) { + public MenuItem[] Find(string key, bool searchAllChildren) + { - if ((key == null) || (key.Length == 0)) { + if ((key == null) || (key.Length == 0)) + { throw new System.ArgumentNullException(nameof(key), SR.FindKeyMayNotBeEmptyOrNull); } - - ArrayList foundMenuItems = FindInternal(key, searchAllChildren, this, new ArrayList()); + + ArrayList foundMenuItems = FindInternal(key, searchAllChildren, this, new ArrayList()); // Make this a stongly typed collection. - MenuItem[] stronglyTypedfoundMenuItems = new MenuItem[foundMenuItems.Count]; + MenuItem[] stronglyTypedfoundMenuItems = new MenuItem[foundMenuItems.Count]; foundMenuItems.CopyTo(stronglyTypedfoundMenuItems, 0); return stronglyTypedfoundMenuItems; @@ -853,78 +1000,98 @@ public MenuItem [] Find(string key, bool searchAllChildren) { /// of all the controls that match. /// /// - private ArrayList FindInternal(string key, bool searchAllChildren, MenuItemCollection menuItemsToLookIn, ArrayList foundMenuItems) { - if ((menuItemsToLookIn == null) || (foundMenuItems == null)) { + private ArrayList FindInternal(string key, bool searchAllChildren, MenuItemCollection menuItemsToLookIn, ArrayList foundMenuItems) + { + if ((menuItemsToLookIn == null) || (foundMenuItems == null)) + { return null; // } // Perform breadth first search - as it's likely people will want controls belonging // to the same parent close to each other. - - for (int i = 0; i < menuItemsToLookIn.Count; i++) { - if (menuItemsToLookIn[i] == null){ - continue; - } - - if (WindowsFormsUtils.SafeCompareStrings(menuItemsToLookIn[i].Name, key, /* ignoreCase = */ true)) { - foundMenuItems.Add(menuItemsToLookIn[i]); - } + + for (int i = 0; i < menuItemsToLookIn.Count; i++) + { + if (menuItemsToLookIn[i] == null) + { + continue; + } + + if (WindowsFormsUtils.SafeCompareStrings(menuItemsToLookIn[i].Name, key, /* ignoreCase = */ true)) + { + foundMenuItems.Add(menuItemsToLookIn[i]); + } } // Optional recurive search for controls in child collections. - - if (searchAllChildren){ - for (int i = 0; i < menuItemsToLookIn.Count; i++) { - if (menuItemsToLookIn[i] == null){ - continue; - } - if ((menuItemsToLookIn[i].MenuItems != null) && menuItemsToLookIn[i].MenuItems.Count > 0){ + + if (searchAllChildren) + { + for (int i = 0; i < menuItemsToLookIn.Count; i++) + { + if (menuItemsToLookIn[i] == null) + { + continue; + } + if ((menuItemsToLookIn[i].MenuItems != null) && menuItemsToLookIn[i].MenuItems.Count > 0) + { // if it has a valid child collecion, append those results to our collection foundMenuItems = FindInternal(key, searchAllChildren, menuItemsToLookIn[i].MenuItems, foundMenuItems); } - } + } } return foundMenuItems; } - public int IndexOf(MenuItem value) { - for(int index=0; index < Count; ++index) { - if (this[index] == value) { + public int IndexOf(MenuItem value) + { + for (int index = 0; index < Count; ++index) + { + if (this[index] == value) + { return index; - } + } } return -1; } - - int IList.IndexOf(object value) { - if (value is MenuItem) { + + int IList.IndexOf(object value) + { + if (value is MenuItem) + { return IndexOf((MenuItem)value); } - else { + else + { return -1; } } - + /// /// The zero-based index of the first occurrence of value within the entire CollectionBase, if found; otherwise, -1. /// - public virtual int IndexOfKey(string key) { - // Step 0 - Arg validation - if (string.IsNullOrEmpty(key)){ - return -1; // we dont support empty or null keys. - } + public virtual int IndexOfKey(string key) + { + // Step 0 - Arg validation + if (string.IsNullOrEmpty(key)) + { + return -1; // we dont support empty or null keys. + } // step 1 - check the last cached item if (IsValidIndex(lastAccessedIndex)) { - if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) { + if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) + { return lastAccessedIndex; } } // step 2 - search for the item - for (int i = 0; i < this.Count; i ++) { - if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { + for (int i = 0; i < this.Count; i++) + { + if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) + { lastAccessedIndex = i; return i; } @@ -933,33 +1100,40 @@ public virtual int IndexOfKey(string key) { // step 3 - we didn't find it. Invalidate the last accessed index and return -1. lastAccessedIndex = -1; return -1; - } + } - void IList.Insert(int index, object value) { - if (value is MenuItem) { - Add(index, (MenuItem)value); + void IList.Insert(int index, object value) + { + if (value is MenuItem) + { + Add(index, (MenuItem)value); } - else { - throw new ArgumentException(SR.MenuBadMenuItem,"value"); + else + { + throw new ArgumentException(SR.MenuBadMenuItem, "value"); } } - - /// - /// Determines if the index is valid for the collection. - /// - private bool IsValidIndex(int index) { + + /// + /// Determines if the index is valid for the collection. + /// + private bool IsValidIndex(int index) + { return ((index >= 0) && (index < this.Count)); - } + } /// /// Removes all existing MenuItems from this menu /// - public virtual void Clear() { - if (owner.ItemCount > 0) { - - for (int i = 0; i < owner.ItemCount; i++) { + public virtual void Clear() + { + if (owner.ItemCount > 0) + { + + for (int i = 0; i < owner.ItemCount; i++) + { owner.items[i].Parent = null; } @@ -968,19 +1142,23 @@ public virtual void Clear() { owner.ItemsChanged(CHANGE_ITEMS); - if (owner is MenuItem) { + if (owner is MenuItem) + { ((MenuItem)(owner)).UpdateMenuItem(true); } } } - public void CopyTo(Array dest, int index) { - if (owner.ItemCount > 0) { + public void CopyTo(Array dest, int index) + { + if (owner.ItemCount > 0) + { System.Array.Copy(owner.items, 0, dest, index, owner.ItemCount); } } - - public IEnumerator GetEnumerator() { + + public IEnumerator GetEnumerator() + { return new WindowsFormsUtils.ArraySubsetEnumerator(owner.items, owner.ItemCount); } @@ -988,8 +1166,10 @@ public IEnumerator GetEnumerator() { /// Removes the item at the specified index in this menu. All subsequent /// items are moved up one slot. /// - public virtual void RemoveAt(int index) { - if (index < 0 || index >= owner.ItemCount) { + public virtual void RemoveAt(int index) + { + if (index < 0 || index >= owner.ItemCount) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } @@ -1002,36 +1182,43 @@ public virtual void RemoveAt(int index) { //if the last item was removed, clear the collection // - if (owner.ItemCount == 0) { + if (owner.ItemCount == 0) + { Clear(); } - + } - /// - /// Removes the menu iteml with the specified key. - /// - public virtual void RemoveByKey(string key) { + /// + /// Removes the menu iteml with the specified key. + /// + public virtual void RemoveByKey(string key) + { int index = IndexOfKey(key); - if (IsValidIndex(index)) { - RemoveAt(index); - } + if (IsValidIndex(index)) + { + RemoveAt(index); + } } /// /// Removes the specified item from this menu. All subsequent /// items are moved down one slot. /// - public virtual void Remove(MenuItem item) { - if (item.Parent == owner) { + public virtual void Remove(MenuItem item) + { + if (item.Parent == owner) + { RemoveAt(item.Index); } } - void IList.Remove(object value) { - if (value is MenuItem) { + void IList.Remove(object value) + { + if (value is MenuItem) + { Remove((MenuItem)value); - } + } } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MenuItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MenuItem.cs index 5b35000c7e2..6c17e36ec6a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MenuItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MenuItem.cs @@ -1138,7 +1138,7 @@ private void PopulateMdiList() windowItem.Checked = true; activeFormAdded = true; } - + windowItem.Text = string.Format(CultureInfo.CurrentUICulture, "&{0} {1}", accel, forms[i].Text); accel++; formsAddedToMenu++; @@ -1348,7 +1348,8 @@ internal virtual bool ShortcutClick() public override string ToString() { string s = base.ToString(); - string menuItemText = _data?._caption ?? string.Empty;; + string menuItemText = _data?._caption ?? string.Empty; + ; return s + ", Text: " + menuItemText; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MenuStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MenuStrip.cs index 13e6324ed21..a98791c5d98 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MenuStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MenuStrip.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.ComponentModel; using System.Drawing; @@ -15,7 +16,8 @@ namespace System.Windows.Forms { ClassInterface(ClassInterfaceType.AutoDispatch), SRDescription(nameof(SR.DescriptionMenuStrip)) ] - public class MenuStrip : ToolStrip { + public class MenuStrip : ToolStrip + { private ToolStripMenuItem mdiWindowListItem = null; @@ -25,22 +27,28 @@ public class MenuStrip : ToolStrip { - public MenuStrip() { + public MenuStrip() + { this.CanOverflow = false; this.GripStyle = ToolStripGripStyle.Hidden; this.Stretch = true; } - internal override bool KeyboardActive { + internal override bool KeyboardActive + { get { return base.KeyboardActive; } - set { - if (base.KeyboardActive != value) { + set + { + if (base.KeyboardActive != value) + { base.KeyboardActive = value; - if (value) { + if (value) + { OnMenuActivate(EventArgs.Empty); } - else { + else + { OnMenuDeactivate(EventArgs.Empty); } } @@ -54,38 +62,50 @@ internal override bool KeyboardActive { SRCategory(nameof(SR.CatLayout)), Browsable(false) ] - public new bool CanOverflow { - get { + public new bool CanOverflow + { + get + { return base.CanOverflow; } - set { + set + { base.CanOverflow = value; } } - protected override bool DefaultShowItemToolTips { - get { + protected override bool DefaultShowItemToolTips + { + get + { return false; } } - protected override Padding DefaultGripMargin { - get { + protected override Padding DefaultGripMargin + { + get + { // MenuStrip control is scaled by Control::ScaleControl() // Ensure grip aligns properly when set visible. return new Padding(2, 2, 0, 2); } } - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(200, 24); } } - protected override Padding DefaultPadding { - get { + protected override Padding DefaultPadding + { + get + { // MenuStrip control is scaled by Control::ScaleControl() // Scoot the grip over when present - if (GripStyle == ToolStripGripStyle.Visible) { + if (GripStyle == ToolStripGripStyle.Visible) + { return new Padding(3, 2, 0, 2); } return new Padding(6, 2, 0, 2); @@ -93,23 +113,28 @@ protected override Padding DefaultPadding { } [DefaultValue(ToolStripGripStyle.Hidden)] - public new ToolStripGripStyle GripStyle { - get { + public new ToolStripGripStyle GripStyle + { + get + { return base.GripStyle; } - set { + set + { base.GripStyle = value; } } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.MenuStripMenuActivateDescr))] - public event EventHandler MenuActivate { + public event EventHandler MenuActivate + { add => Events.AddHandler(EventMenuActivate, value); remove => Events.RemoveHandler(EventMenuActivate, value); } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.MenuStripMenuDeactivateDescr))] - public event EventHandler MenuDeactivate { + public event EventHandler MenuDeactivate + { add => Events.AddHandler(EventMenuDeactivate, value); remove => Events.RemoveHandler(EventMenuDeactivate, value); } @@ -117,11 +142,14 @@ public event EventHandler MenuDeactivate { [DefaultValue(false)] [SRDescription(nameof(SR.ToolStripShowItemToolTipsDescr))] [SRCategory(nameof(SR.CatBehavior))] - public new bool ShowItemToolTips { - get { + public new bool ShowItemToolTips + { + get + { return base.ShowItemToolTips; } - set { + set + { base.ShowItemToolTips = value; } } @@ -129,11 +157,14 @@ public event EventHandler MenuDeactivate { [DefaultValue(true)] [SRCategory(nameof(SR.CatLayout))] [SRDescription(nameof(SR.ToolStripStretchDescr))] - public new bool Stretch { - get { + public new bool Stretch + { + get + { return base.Stretch; } - set { + set + { base.Stretch = value; } } @@ -143,64 +174,84 @@ public event EventHandler MenuDeactivate { [SRDescription(nameof(SR.MenuStripMdiWindowListItem))] [SRCategory(nameof(SR.CatBehavior))] [TypeConverterAttribute(typeof(MdiWindowListItemConverter))] - public ToolStripMenuItem MdiWindowListItem { - get { + public ToolStripMenuItem MdiWindowListItem + { + get + { return mdiWindowListItem; } - set { + set + { mdiWindowListItem = value; } } - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new MenuStripAccessibleObject(this); } - protected internal override ToolStripItem CreateDefaultItem(string text, Image image, EventHandler onClick) { - if (text == "-") { + protected internal override ToolStripItem CreateDefaultItem(string text, Image image, EventHandler onClick) + { + if (text == "-") + { return new ToolStripSeparator(); } - else { + else + { return new ToolStripMenuItem(text, image, onClick); } } - internal override ToolStripItem GetNextItem(ToolStripItem start, ArrowDirection direction, bool rtlAware) { + internal override ToolStripItem GetNextItem(ToolStripItem start, ArrowDirection direction, bool rtlAware) + { ToolStripItem nextItem = base.GetNextItem(start, direction, rtlAware); - if (nextItem is MdiControlStrip.SystemMenuItem) { + if (nextItem is MdiControlStrip.SystemMenuItem) + { nextItem = base.GetNextItem(nextItem, direction, rtlAware); } return nextItem; } - protected virtual void OnMenuActivate(EventArgs e) { - if (IsHandleCreated) { + protected virtual void OnMenuActivate(EventArgs e) + { + if (IsHandleCreated) + { AccessibilityNotifyClients(AccessibleEvents.SystemMenuStart, -1); } EventHandler handler = (EventHandler)Events[EventMenuActivate]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } - protected virtual void OnMenuDeactivate(EventArgs e) { - if (IsHandleCreated) { + protected virtual void OnMenuDeactivate(EventArgs e) + { + if (IsHandleCreated) + { AccessibilityNotifyClients(AccessibleEvents.SystemMenuEnd, -1); } EventHandler handler = (EventHandler)Events[EventMenuDeactivate]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// Called from ToolStripManager.ProcessMenuKey. Fires MenuActivate event and sets focus. /// - internal bool OnMenuKey() { - if (!(Focused || ContainsFocus)) { + internal bool OnMenuKey() + { + if (!(Focused || ContainsFocus)) + { Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[ProcessMenuKey] set focus to menustrip"); ToolStripManager.ModalMenuFilter.SetActiveToolStrip(this, /*menuKeyPressed=*/true); - if (DisplayedItems.Count > 0) { - if (DisplayedItems[0] is MdiControlStrip.SystemMenuItem) { + if (DisplayedItems.Count > 0) + { + if (DisplayedItems[0] is MdiControlStrip.SystemMenuItem) + { SelectNextToolStripItem(DisplayedItems[0], /*forward=*/true); } - else { + else + { // first alt should select "File". Future keydowns of alt should restore focus. SelectNextToolStripItem(null, /*forward=*/(RightToLeft == RightToLeft.No)); } @@ -211,15 +262,19 @@ internal bool OnMenuKey() { return false; } - protected override bool ProcessCmdKey(ref Message m, Keys keyData) { + protected override bool ProcessCmdKey(ref Message m, Keys keyData) + { - if (ToolStripManager.ModalMenuFilter.InMenuMode) { + if (ToolStripManager.ModalMenuFilter.InMenuMode) + { // ALT, then space should dismiss the menu and activate the system menu. - if (keyData == Keys.Space) { + if (keyData == Keys.Space) + { // if we're focused it's ok to activate system menu // if we're not focused - we should not activate if we contain focus - this means a text box or something // has focus. - if (Focused || !ContainsFocus) { + if (Focused || !ContainsFocus) + { NotifySelectionChange(null); Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[MenuStrip.ProcessCmdKey] Rolling up the menu and invoking the system menu"); ToolStripManager.ModalMenuFilter.ExitMenuMode(); @@ -237,13 +292,16 @@ protected override bool ProcessCmdKey(ref Message m, Keys keyData) { /// Summary of WndProc. /// /// - protected override void WndProc(ref Message m) { + protected override void WndProc(ref Message m) + { - if (m.Msg == Interop.WindowMessages.WM_MOUSEACTIVATE && (ActiveDropDowns.Count == 0)) { + if (m.Msg == Interop.WindowMessages.WM_MOUSEACTIVATE && (ActiveDropDowns.Count == 0)) + { // call menu activate before we actually take focus. Point pt = PointToClient(WindowsFormsUtils.LastCursorPoint); ToolStripItem item = GetItemAt(pt); - if (item != null && !(item is ToolStripControlHost)) { + if (item != null && !(item is ToolStripControlHost)) + { // verify the place where we've clicked is a place where we have to do "fake" focus // e.g. an item that isnt a control. KeyboardActive = true; @@ -254,24 +312,31 @@ protected override void WndProc(ref Message m) { } [System.Runtime.InteropServices.ComVisible(true)] - internal class MenuStripAccessibleObject : ToolStripAccessibleObject { + internal class MenuStripAccessibleObject : ToolStripAccessibleObject + { public MenuStripAccessibleObject(MenuStrip owner) - : base(owner) { + : base(owner) + { } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { AccessibleRole role = Owner.AccessibleRole; - if (role != AccessibleRole.Default) { + if (role != AccessibleRole.Default) + { return role; } return AccessibleRole.MenuBar; } } - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_ControlTypePropertyId) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_ControlTypePropertyId) + { return NativeMethods.UIA_MenuBarControlTypeId; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Message.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Message.cs index 85edc3cd903..79013ce5291 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Message.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Message.cs @@ -52,7 +52,7 @@ public static Message Create(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam) m.Result = IntPtr.Zero; #if DEBUG - if(s_allWinMessages.TraceVerbose) + if (s_allWinMessages.TraceVerbose) { Debug.WriteLine(m.ToString()); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MessageBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MessageBox.cs index 6747ba11106..5d33ab3e3a7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MessageBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MessageBox.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System; @@ -13,7 +14,7 @@ namespace System.Windows.Forms { using System.Runtime.InteropServices; using System.Windows.Forms; using System.Collections; - + /// /// /// Displays a @@ -22,33 +23,37 @@ namespace System.Windows.Forms { /// user. /// /// - public class MessageBox { - private const int IDOK = 1; - private const int IDCANCEL = 2; - private const int IDABORT = 3; - private const int IDRETRY = 4; - private const int IDIGNORE = 5; - private const int IDYES = 6; - private const int IDNO = 7; + public class MessageBox + { + private const int IDOK = 1; + private const int IDCANCEL = 2; + private const int IDABORT = 3; + private const int IDRETRY = 4; + private const int IDIGNORE = 5; + private const int IDYES = 6; + private const int IDNO = 7; - private const int HELP_BUTTON = 0x00004000; + private const int HELP_BUTTON = 0x00004000; - [ ThreadStatic ] + [ThreadStatic] private static HelpInfo[] helpInfoTable; - + /// /// This constructor is private so people aren't tempted to try and create /// instances of these -- they should just use the static show /// methods. /// - private MessageBox() { + private MessageBox() + { } - private static DialogResult Win32ToDialogResult(int value) { - switch (value) { + private static DialogResult Win32ToDialogResult(int value) + { + switch (value) + { case IDOK: return DialogResult.OK; case IDCANCEL: @@ -68,83 +73,95 @@ private static DialogResult Win32ToDialogResult(int value) { } } - - internal static HelpInfo HelpInfo { - get { + + internal static HelpInfo HelpInfo + { + get + { // unfortunately, there's no easy way to obtain handle of a message box. // we'll have to rely on the fact that modal message loops have to pop off in an orderly way. - if (helpInfoTable != null && helpInfoTable.Length > 0) { + if (helpInfoTable != null && helpInfoTable.Length > 0) + { // the top of the stack is actually at the end of the array. return helpInfoTable[helpInfoTable.Length - 1]; } - + return null; } } - private static void PopHelpInfo() { + private static void PopHelpInfo() + { - // we roll our own stack here because we want a pretty lightweight implementation. - // usually there's only going to be one message box shown at a time. But if - // someone shows two message boxes (say by launching them via a WM_TIMER message) - // we've got to gracefully handle the current help info. - if (helpInfoTable == null) { + // we roll our own stack here because we want a pretty lightweight implementation. + // usually there's only going to be one message box shown at a time. But if + // someone shows two message boxes (say by launching them via a WM_TIMER message) + // we've got to gracefully handle the current help info. + if (helpInfoTable == null) + { Debug.Fail("Why are we being called when there's nothing to pop?"); - - } - else { - if (helpInfoTable.Length == 1) { + + } + else + { + if (helpInfoTable.Length == 1) + { helpInfoTable = null; } - else { - int newCount = helpInfoTable.Length -1; - HelpInfo[] newTable = new HelpInfo[newCount]; - Array.Copy(helpInfoTable, newTable, newCount); - helpInfoTable = newTable; - + else + { + int newCount = helpInfoTable.Length - 1; + HelpInfo[] newTable = new HelpInfo[newCount]; + Array.Copy(helpInfoTable, newTable, newCount); + helpInfoTable = newTable; + } - } - + } + } - private static void PushHelpInfo(HelpInfo hpi) { - + private static void PushHelpInfo(HelpInfo hpi) + { + // we roll our own stack here because we want a pretty lightweight implementation. // usually there's only going to be one message box shown at a time. But if // someone shows two message boxes (say by launching them via a WM_TIMER message) // we've got to gracefully handle the current help info. int lastCount = 0; - HelpInfo[] newTable; - - if (helpInfoTable == null) { - newTable = new HelpInfo[lastCount+1]; + HelpInfo[] newTable; + + if (helpInfoTable == null) + { + newTable = new HelpInfo[lastCount + 1]; } - else { + else + { // if we already have a table - allocate a new slot lastCount = helpInfoTable.Length; - newTable = new HelpInfo[lastCount+1]; + newTable = new HelpInfo[lastCount + 1]; Array.Copy(helpInfoTable, newTable, lastCount); } newTable[lastCount] = hpi; helpInfoTable = newTable; - + } - + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// //START WHIDBEY ADDS // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// - + /// /// /// Displays a message box with specified text, caption, and style with Help Button. /// /// - public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, - MessageBoxDefaultButton defaultButton, MessageBoxOptions options,bool displayHelpButton) { - + public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, + MessageBoxDefaultButton defaultButton, MessageBoxOptions options, bool displayHelpButton) + { + return ShowCore(null, text, caption, buttons, icon, defaultButton, options, displayHelpButton); } @@ -154,8 +171,9 @@ public static DialogResult Show(string text, string caption, MessageBoxButtons b /// Displays a message box with specified text, caption, style and Help file Path . /// /// - public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, - MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath) { + public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, + MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath) + { HelpInfo hpi = new HelpInfo(helpFilePath); return ShowCore(null, text, caption, buttons, icon, defaultButton, options, hpi); @@ -167,22 +185,24 @@ public static DialogResult Show(string text, string caption, MessageBoxButtons b /// Displays a message box with specified text, caption, style and Help file Path for a IWin32Window. /// /// - public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, - MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath) { + public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, + MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath) + { HelpInfo hpi = new HelpInfo(helpFilePath); return ShowCore(owner, text, caption, buttons, icon, defaultButton, options, hpi); } - + /// /// /// Displays a message box with specified text, caption, style, Help file Path and keyword. /// /// - public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, - MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath, string keyword) { + public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, + MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath, string keyword) + { HelpInfo hpi = new HelpInfo(helpFilePath, keyword); return ShowCore(null, text, caption, buttons, icon, defaultButton, options, hpi); @@ -194,8 +214,9 @@ public static DialogResult Show(string text, string caption, MessageBoxButtons b /// Displays a message box with specified text, caption, style, Help file Path and keyword for a IWin32Window. /// /// - public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, - MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath, string keyword) { + public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, + MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath, string keyword) + { HelpInfo hpi = new HelpInfo(helpFilePath, keyword); return ShowCore(owner, text, caption, buttons, icon, defaultButton, options, hpi); @@ -207,8 +228,9 @@ public static DialogResult Show(IWin32Window owner, string text, string caption, /// Displays a message box with specified text, caption, style, Help file Path and HelpNavigator. /// /// - public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, - MessageBoxDefaultButton defaultButton, MessageBoxOptions options,string helpFilePath, HelpNavigator navigator) { + public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, + MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath, HelpNavigator navigator) + { HelpInfo hpi = new HelpInfo(helpFilePath, navigator); return ShowCore(null, text, caption, buttons, icon, defaultButton, options, hpi); @@ -219,8 +241,9 @@ public static DialogResult Show(string text, string caption, MessageBoxButtons b /// Displays a message box with specified text, caption, style, Help file Path and HelpNavigator for IWin32Window. /// /// - public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, - MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath, HelpNavigator navigator) { + public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, + MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath, HelpNavigator navigator) + { HelpInfo hpi = new HelpInfo(helpFilePath, navigator); return ShowCore(owner, text, caption, buttons, icon, defaultButton, options, hpi); @@ -231,8 +254,9 @@ public static DialogResult Show(IWin32Window owner, string text, string caption, /// Displays a message box with specified text, caption, style, Help file Path ,HelpNavigator and object. /// /// - public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, - MessageBoxDefaultButton defaultButton, MessageBoxOptions options,string helpFilePath, HelpNavigator navigator, object param) { + public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, + MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath, HelpNavigator navigator, object param) + { HelpInfo hpi = new HelpInfo(helpFilePath, navigator, param); @@ -245,11 +269,12 @@ public static DialogResult Show(string text, string caption, MessageBoxButtons b /// Displays a message box with specified text, caption, style, Help file Path ,HelpNavigator and object for a IWin32Window. /// /// - public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, - MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath, HelpNavigator navigator, object param) { + public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, + MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath, HelpNavigator navigator, object param) + { HelpInfo hpi = new HelpInfo(helpFilePath, navigator, param); - + return ShowCore(owner, text, caption, buttons, icon, defaultButton, options, hpi); } @@ -263,8 +288,9 @@ public static DialogResult Show(IWin32Window owner, string text, string caption, /// Displays a message box with specified text, caption, and style. /// /// - public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, - MessageBoxDefaultButton defaultButton, MessageBoxOptions options) { + public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, + MessageBoxDefaultButton defaultButton, MessageBoxOptions options) + { return ShowCore(null, text, caption, buttons, icon, defaultButton, options, false); } @@ -273,8 +299,9 @@ public static DialogResult Show(string text, string caption, MessageBoxButtons b /// Displays a message box with specified text, caption, and style. /// /// - public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, - MessageBoxDefaultButton defaultButton) { + public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, + MessageBoxDefaultButton defaultButton) + { return ShowCore(null, text, caption, buttons, icon, defaultButton, 0, false); } @@ -283,7 +310,8 @@ public static DialogResult Show(string text, string caption, MessageBoxButtons b /// Displays a message box with specified text, caption, and style. /// /// - public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon) { + public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon) + { return ShowCore(null, text, caption, buttons, icon, MessageBoxDefaultButton.Button1, 0, false); } @@ -292,7 +320,8 @@ public static DialogResult Show(string text, string caption, MessageBoxButtons b /// Displays a message box with specified text, caption, and style. /// /// - public static DialogResult Show(string text, string caption, MessageBoxButtons buttons) { + public static DialogResult Show(string text, string caption, MessageBoxButtons buttons) + { return ShowCore(null, text, caption, buttons, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, 0, false); } @@ -301,7 +330,8 @@ public static DialogResult Show(string text, string caption, MessageBoxButtons b /// Displays a message box with specified text and caption. /// /// - public static DialogResult Show(string text, string caption) { + public static DialogResult Show(string text, string caption) + { return ShowCore(null, text, caption, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, 0, false); } @@ -310,7 +340,8 @@ public static DialogResult Show(string text, string caption) { /// Displays a message box with specified text. /// /// - public static DialogResult Show(string text) { + public static DialogResult Show(string text) + { return ShowCore(null, text, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, 0, false); } @@ -319,8 +350,9 @@ public static DialogResult Show(string text) { /// Displays a message box with specified text, caption, and style. /// /// - public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, - MessageBoxDefaultButton defaultButton, MessageBoxOptions options) { + public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, + MessageBoxDefaultButton defaultButton, MessageBoxOptions options) + { return ShowCore(owner, text, caption, buttons, icon, defaultButton, options, false); } @@ -329,8 +361,9 @@ public static DialogResult Show(IWin32Window owner, string text, string caption, /// Displays a message box with specified text, caption, and style. /// /// - public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, - MessageBoxDefaultButton defaultButton) { + public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, + MessageBoxDefaultButton defaultButton) + { return ShowCore(owner, text, caption, buttons, icon, defaultButton, 0, false); } @@ -339,7 +372,8 @@ public static DialogResult Show(IWin32Window owner, string text, string caption, /// Displays a message box with specified text, caption, and style. /// /// - public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon) { + public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon) + { return ShowCore(owner, text, caption, buttons, icon, MessageBoxDefaultButton.Button1, 0, false); } @@ -348,7 +382,8 @@ public static DialogResult Show(IWin32Window owner, string text, string caption, /// Displays a message box with specified text, caption, and style. /// /// - public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons) { + public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons) + { return ShowCore(owner, text, caption, buttons, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, 0, false); } @@ -357,7 +392,8 @@ public static DialogResult Show(IWin32Window owner, string text, string caption, /// Displays a message box with specified text and caption. /// /// - public static DialogResult Show(IWin32Window owner, string text, string caption) { + public static DialogResult Show(IWin32Window owner, string text, string caption) + { return ShowCore(owner, text, caption, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, 0, false); } @@ -366,73 +402,90 @@ public static DialogResult Show(IWin32Window owner, string text, string caption) /// Displays a message box with specified text. /// /// - public static DialogResult Show(IWin32Window owner, string text) { + public static DialogResult Show(IWin32Window owner, string text) + { return ShowCore(owner, text, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, 0, false); } - private static DialogResult ShowCore(IWin32Window owner, string text, string caption, + private static DialogResult ShowCore(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, - MessageBoxOptions options, HelpInfo hpi) { + MessageBoxOptions options, HelpInfo hpi) + { DialogResult result = DialogResult.None; - try { + try + { PushHelpInfo(hpi); result = ShowCore(owner, text, caption, buttons, icon, defaultButton, options, true); } - finally { + finally + { PopHelpInfo(); } return result; - + } - private static DialogResult ShowCore(IWin32Window owner, string text, string caption, + private static DialogResult ShowCore(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, - MessageBoxOptions options, bool showHelp) { - - if (!ClientUtils.IsEnumValid(buttons, (int)buttons, (int)MessageBoxButtons.OK, (int)MessageBoxButtons.RetryCancel)){ - throw new InvalidEnumArgumentException(nameof(buttons), (int)buttons, typeof(MessageBoxButtons)); + MessageBoxOptions options, bool showHelp) + { + + if (!ClientUtils.IsEnumValid(buttons, (int)buttons, (int)MessageBoxButtons.OK, (int)MessageBoxButtons.RetryCancel)) + { + throw new InvalidEnumArgumentException(nameof(buttons), (int)buttons, typeof(MessageBoxButtons)); } // valid values are 0x0 0x10 0x20 0x30 0x40, chop off the last 4 bits and check that it's between 0 and 4. - if (!WindowsFormsUtils.EnumValidator.IsEnumWithinShiftedRange(icon, /*numBitsToShift*/4, /*min*/0x0,/*max*/0x4)) { + if (!WindowsFormsUtils.EnumValidator.IsEnumWithinShiftedRange(icon, /*numBitsToShift*/4, /*min*/0x0,/*max*/0x4)) + { throw new InvalidEnumArgumentException(nameof(icon), (int)icon, typeof(MessageBoxIcon)); } // valid values are 0x0 0x100, 0x200, chop off the last 8 bits and check that it's between 0 and 2. - if (!WindowsFormsUtils.EnumValidator.IsEnumWithinShiftedRange(defaultButton, /*numBitsToShift*/8, /*min*/0x0,/*max*/0x2)) { + if (!WindowsFormsUtils.EnumValidator.IsEnumWithinShiftedRange(defaultButton, /*numBitsToShift*/8, /*min*/0x0,/*max*/0x2)) + { throw new InvalidEnumArgumentException(nameof(defaultButton), (int)defaultButton, typeof(DialogResult)); } - + // options intentionally not verified because we don't expose all the options Win32 supports. - if (!SystemInformation.UserInteractive && (options & (MessageBoxOptions.ServiceNotification | MessageBoxOptions.DefaultDesktopOnly)) == 0) { + if (!SystemInformation.UserInteractive && (options & (MessageBoxOptions.ServiceNotification | MessageBoxOptions.DefaultDesktopOnly)) == 0) + { throw new InvalidOperationException(SR.CantShowModalOnNonInteractive); } - if (owner != null && (options & (MessageBoxOptions.ServiceNotification | MessageBoxOptions.DefaultDesktopOnly)) != 0) { + if (owner != null && (options & (MessageBoxOptions.ServiceNotification | MessageBoxOptions.DefaultDesktopOnly)) != 0) + { throw new ArgumentException(SR.CantShowMBServiceWithOwner, "options"); } - if (showHelp && (options & (MessageBoxOptions.ServiceNotification | MessageBoxOptions.DefaultDesktopOnly)) != 0) { + if (showHelp && (options & (MessageBoxOptions.ServiceNotification | MessageBoxOptions.DefaultDesktopOnly)) != 0) + { throw new ArgumentException(SR.CantShowMBServiceWithHelp, "options"); } - int style = (showHelp) ? HELP_BUTTON : 0; - style |= (int) buttons | (int) icon | (int) defaultButton | (int) options; + int style = (showHelp) ? HELP_BUTTON : 0; + style |= (int)buttons | (int)icon | (int)defaultButton | (int)options; IntPtr handle = IntPtr.Zero; - if (showHelp || ((options & (MessageBoxOptions.ServiceNotification | MessageBoxOptions.DefaultDesktopOnly)) == 0)) { - if (owner == null) { + if (showHelp || ((options & (MessageBoxOptions.ServiceNotification | MessageBoxOptions.DefaultDesktopOnly)) == 0)) + { + if (owner == null) + { handle = UnsafeNativeMethods.GetActiveWindow(); } - else { + else + { handle = Control.GetSafeHandle(owner); } } IntPtr userCookie = IntPtr.Zero; - if (Application.UseVisualStyles) { + if (Application.UseVisualStyles) + { // CLR4.0 or later, shell32.dll needs to be loaded explicitly. - if (UnsafeNativeMethods.GetModuleHandle(ExternDll.Shell32) == IntPtr.Zero) { - if (UnsafeNativeMethods.LoadLibraryFromSystemPathIfAvailable(ExternDll.Shell32) == IntPtr.Zero) { + if (UnsafeNativeMethods.GetModuleHandle(ExternDll.Shell32) == IntPtr.Zero) + { + if (UnsafeNativeMethods.LoadLibraryFromSystemPathIfAvailable(ExternDll.Shell32) == IntPtr.Zero) + { int lastWin32Error = Marshal.GetLastWin32Error(); throw new Win32Exception(lastWin32Error, string.Format(SR.LoadDLLError, ExternDll.Shell32)); } @@ -445,10 +498,12 @@ private static DialogResult ShowCore(IWin32Window owner, string text, string cap Application.BeginModalMessageLoop(); DialogResult result; - try { + try + { result = Win32ToDialogResult(SafeNativeMethods.MessageBox(new HandleRef(owner, handle), text, caption, style)); } - finally { + finally + { Application.EndModalMessageLoop(); UnsafeNativeMethods.ThemingScope.Deactivate(userCookie); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MessageBoxIcon.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MessageBoxIcon.cs index f799c07af1c..92b9f5fe91e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MessageBoxIcon.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MessageBoxIcon.cs @@ -27,7 +27,7 @@ public enum MessageBoxIcon /// /// Specifies that the message box contains an exclamation symbol. /// - Exclamation = 0x00000030, + Exclamation = 0x00000030, /// /// Specifies that the message box contains an asterisk symbol. @@ -53,6 +53,6 @@ public enum MessageBoxIcon /// /// Specifies that the message box contains an asterisk icon. /// - Information = Asterisk, + Information = Asterisk, } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MessageDecoder.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MessageDecoder.cs index 7ea19c3f8cc..1546195ea27 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MessageDecoder.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MessageDecoder.cs @@ -823,13 +823,14 @@ private static string MsgToString(int msg) break; default: - text = null; break; + text = null; + break; } if (text == null && ((msg & Interop.WindowMessages.WM_REFLECT) == Interop.WindowMessages.WM_REFLECT)) { string subtext = MsgToString(msg - Interop.WindowMessages.WM_REFLECT) ?? "???"; - + text = "WM_REFLECT + " + subtext; } @@ -842,7 +843,7 @@ private static string Parenthesize(string input) { return string.Empty; } - + return " (" + input + ")"; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MethodInvoker.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MethodInvoker.cs index 00c2499d6e8..81dbbc82a2c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MethodInvoker.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MethodInvoker.cs @@ -3,10 +3,11 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; - + /// /// Represents the method that will handle the /// event for a method. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs index d8c0ab6bc2c..2972a61c70c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs @@ -4,7 +4,8 @@ -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; @@ -69,7 +70,8 @@ namespace System.Windows.Forms { Designer("System.Windows.Forms.Design.MonthCalendarDesigner, " + AssemblyRef.SystemDesign), SRDescription(nameof(SR.DescriptionMonthCalendar)) ] - public class MonthCalendar : Control { + public class MonthCalendar : Control + { const long DAYS_TO_1601 = 548229; const long DAYS_TO_10000 = 3615900; static readonly Color DEFAULT_TITLE_BACK_COLOR = SystemColors.ActiveCaption; @@ -81,81 +83,82 @@ public class MonthCalendar : Control { /// This is the arbitrary number of pixels that the Win32 control /// inserts between calendars horizontally, regardless of font. /// - private const int INSERT_WIDTH_SIZE = 6; + private const int INSERT_WIDTH_SIZE = 6; /// /// This is the arbitrary number of pixels that the Win32 control /// inserts between calendars vertically, regardless of font. /// - private const int INSERT_HEIGHT_SIZE = 6; // From comctl32 MonthCalendar sources CALBORDER - private const Day DEFAULT_FIRST_DAY_OF_WEEK = Day.Default; - private const int DEFAULT_MAX_SELECTION_COUNT = 7; - private const int DEFAULT_SCROLL_CHANGE = 0; - private const int UNIQUE_DATE = 0; - private const int ANNUAL_DATE = 1; - private const int MONTHLY_DATE = 2; + private const int INSERT_HEIGHT_SIZE = 6; // From comctl32 MonthCalendar sources CALBORDER + private const Day DEFAULT_FIRST_DAY_OF_WEEK = Day.Default; + private const int DEFAULT_MAX_SELECTION_COUNT = 7; + private const int DEFAULT_SCROLL_CHANGE = 0; + private const int UNIQUE_DATE = 0; + private const int ANNUAL_DATE = 1; + private const int MONTHLY_DATE = 2; - private static readonly Size DefaultSingleMonthSize = new Size(176, 153); + private static readonly Size DefaultSingleMonthSize = new Size(176, 153); - private const int MaxScrollChange = 20000; + private const int MaxScrollChange = 20000; - private const int ExtraPadding = 2; - private int scaledExtraPadding = ExtraPadding; + private const int ExtraPadding = 2; + private int scaledExtraPadding = ExtraPadding; - private IntPtr mdsBuffer = IntPtr.Zero; - private int mdsBufferSize = 0; + private IntPtr mdsBuffer = IntPtr.Zero; + private int mdsBufferSize = 0; // styles - private Color titleBackColor = DEFAULT_TITLE_BACK_COLOR; - private Color titleForeColor = DEFAULT_TITLE_FORE_COLOR; - private Color trailingForeColor = DEFAULT_TRAILING_FORE_COLOR; - private bool showToday = true; - private bool showTodayCircle = true; - private bool showWeekNumbers = false; - private bool rightToLeftLayout = false; + private Color titleBackColor = DEFAULT_TITLE_BACK_COLOR; + private Color titleForeColor = DEFAULT_TITLE_FORE_COLOR; + private Color trailingForeColor = DEFAULT_TRAILING_FORE_COLOR; + private bool showToday = true; + private bool showTodayCircle = true; + private bool showWeekNumbers = false; + private bool rightToLeftLayout = false; // properties - private Size dimensions = new Size(1, 1); - private int maxSelectionCount = DEFAULT_MAX_SELECTION_COUNT; + private Size dimensions = new Size(1, 1); + private int maxSelectionCount = DEFAULT_MAX_SELECTION_COUNT; // Reconcile out-of-range min/max values in the property getters. - private DateTime maxDate = DateTime.MaxValue; - private DateTime minDate = DateTime.MinValue; - private int scrollChange = DEFAULT_SCROLL_CHANGE; - private bool todayDateSet = false; // Has TodayDate been explicitly set? - private DateTime todayDate = DateTime.Now.Date; - private DateTime selectionStart; - private DateTime selectionEnd; - private Day firstDayOfWeek = DEFAULT_FIRST_DAY_OF_WEEK; + private DateTime maxDate = DateTime.MaxValue; + private DateTime minDate = DateTime.MinValue; + private int scrollChange = DEFAULT_SCROLL_CHANGE; + private bool todayDateSet = false; // Has TodayDate been explicitly set? + private DateTime todayDate = DateTime.Now.Date; + private DateTime selectionStart; + private DateTime selectionEnd; + private Day firstDayOfWeek = DEFAULT_FIRST_DAY_OF_WEEK; private NativeMethods.MONTCALENDAR_VIEW_MODE mcCurView = NativeMethods.MONTCALENDAR_VIEW_MODE.MCMV_MONTH; private NativeMethods.MONTCALENDAR_VIEW_MODE mcOldView = NativeMethods.MONTCALENDAR_VIEW_MODE.MCMV_MONTH; /// /// Bitmask for the annually bolded dates. Months start on January. /// - private int[] monthsOfYear = new int[12]; + private int[] monthsOfYear = new int[12]; /// /// Bitmask for the dates bolded monthly. /// - private int datesToBoldMonthly = 0; + private int datesToBoldMonthly = 0; /// /// Lists are slow, so this section can be optimized. /// Implementation is such that inserts are fast, removals are slow. /// - private ArrayList arrayOfDates = new ArrayList(); - private ArrayList annualArrayOfDates = new ArrayList(); // we have to maintain these lists too. - private ArrayList monthlyArrayOfDates = new ArrayList(); + private ArrayList arrayOfDates = new ArrayList(); + private ArrayList annualArrayOfDates = new ArrayList(); // we have to maintain these lists too. + private ArrayList monthlyArrayOfDates = new ArrayList(); // notifications - private DateRangeEventHandler onDateChanged; - private DateRangeEventHandler onDateSelected; - private EventHandler onRightToLeftLayoutChanged; + private DateRangeEventHandler onDateChanged; + private DateRangeEventHandler onDateSelected; + private EventHandler onRightToLeftLayoutChanged; /// /// Creates a new MonthCalendar object. Styles are the default for a /// regular month calendar control. /// public MonthCalendar() - : base() { + : base() + { PrepareForDrawing(); @@ -163,7 +166,7 @@ public MonthCalendar() selectionEnd = todayDate; SetStyle(ControlStyles.UserPaint, false); SetStyle(ControlStyles.StandardClick, false); - + TabStop = true; } @@ -171,17 +174,21 @@ public MonthCalendar() /// MonthCalendar control accessbile object. /// /// - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new MonthCalendarAccessibleObject(this); } - protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) { + protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) + { base.RescaleConstantsForDpi(deviceDpiOld, deviceDpiNew); PrepareForDrawing(); } - private void PrepareForDrawing() { - if (DpiHelper.IsScalingRequirementMet) { + private void PrepareForDrawing() + { + if (DpiHelper.IsScalingRequirementMet) + { scaledExtraPadding = LogicalToDeviceUnits(ExtraPadding); } } @@ -194,33 +201,40 @@ private void PrepareForDrawing() { Localizable(true), SRDescription(nameof(SR.MonthCalendarAnnuallyBoldedDatesDescr)) ] - public DateTime[] AnnuallyBoldedDates { - get { + public DateTime[] AnnuallyBoldedDates + { + get + { DateTime[] dateTimes = new DateTime[annualArrayOfDates.Count]; - for (int i=0;i < annualArrayOfDates.Count; ++i) { + for (int i = 0; i < annualArrayOfDates.Count; ++i) + { dateTimes[i] = (DateTime)this.annualArrayOfDates[i]; } return dateTimes; } - set { + set + { // this.annualArrayOfDates.Clear(); - for (int i=0; i 0) { + if (value != null && value.Length > 0) + { //add each boldeddate to our ArrayList... - for (int i = 0; i < value.Length; i++) { + for (int i = 0; i < value.Length; i++) + { this.annualArrayOfDates.Add(value[i]); } - for (int i = 0; i < value.Length; ++i) { - monthsOfYear[value[i].Month-1] |= 0x00000001<<(value[i].Day-1); + for (int i = 0; i < value.Length; ++i) + { + monthsOfYear[value[i].Month - 1] |= 0x00000001 << (value[i].Day - 1); } } @@ -229,49 +243,62 @@ public DateTime[] AnnuallyBoldedDates { } [SRDescription(nameof(SR.MonthCalendarMonthBackColorDescr))] - public override Color BackColor { - get { - if (ShouldSerializeBackColor()) { + public override Color BackColor + { + get + { + if (ShouldSerializeBackColor()) + { return base.BackColor; } - else { + else + { return SystemColors.Window; } } - set { + set + { base.BackColor = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged { + new public event EventHandler BackgroundImageChanged + { add => base.BackgroundImageChanged += value; remove => base.BackgroundImageChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { + new public event EventHandler BackgroundImageLayoutChanged + { add => base.BackgroundImageLayoutChanged += value; remove => base.BackgroundImageLayoutChanged -= value; } @@ -283,25 +310,31 @@ public override ImageLayout BackgroundImageLayout { /// /*Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),*/ [Localizable(true)] - public DateTime[] BoldedDates { - get { + public DateTime[] BoldedDates + { + get + { DateTime[] dateTimes = new DateTime[arrayOfDates.Count]; - for (int i=0;i < arrayOfDates.Count; ++i) { + for (int i = 0; i < arrayOfDates.Count; ++i) + { dateTimes[i] = (DateTime)this.arrayOfDates[i]; } return dateTimes; } - set { + set + { // this.arrayOfDates.Clear(); - if (value != null && value.Length > 0) { + if (value != null && value.Length > 0) + { //add each boldeddate to our ArrayList... - for (int i = 0; i < value.Length; i++) { + for (int i = 0; i < value.Length; i++) + { this.arrayOfDates.Add(value[i]); } @@ -319,11 +352,14 @@ public DateTime[] BoldedDates { Localizable(true), SRDescription(nameof(SR.MonthCalendarDimensionsDescr)) ] - public Size CalendarDimensions { - get { + public Size CalendarDimensions + { + get + { return dimensions; } - set { + set + { if (!this.dimensions.Equals(value)) SetCalendarDimensions(value.Width, value.Height); } @@ -335,16 +371,22 @@ public Size CalendarDimensions { /// base.getCreateParams() to make sure the control continues to work /// correctly. /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ClassName = NativeMethods.WC_MONTHCAL; cp.Style |= NativeMethods.MCS_MULTISELECT | NativeMethods.MCS_DAYSTATE; - if (!showToday) cp.Style |= NativeMethods.MCS_NOTODAY; - if (!showTodayCircle) cp.Style |= NativeMethods.MCS_NOTODAYCIRCLE; - if (showWeekNumbers) cp.Style |= NativeMethods.MCS_WEEKNUMBERS; - - if (RightToLeft == RightToLeft.Yes && RightToLeftLayout == true) { + if (!showToday) + cp.Style |= NativeMethods.MCS_NOTODAY; + if (!showTodayCircle) + cp.Style |= NativeMethods.MCS_NOTODAYCIRCLE; + if (showWeekNumbers) + cp.Style |= NativeMethods.MCS_WEEKNUMBERS; + + if (RightToLeft == RightToLeft.Yes && RightToLeftLayout == true) + { //We want to turn on mirroring for Form explicitly. cp.ExStyle |= NativeMethods.WS_EX_LAYOUTRTL; //Don't need these styles when mirroring is turned on. @@ -355,18 +397,23 @@ protected override CreateParams CreateParams { } } - protected override ImeMode DefaultImeMode { - get { + protected override ImeMode DefaultImeMode + { + get + { return ImeMode.Disable; } } - protected override Padding DefaultMargin { + protected override Padding DefaultMargin + { get { return new Padding(9); } } - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return GetMinReqRect(); } } @@ -376,11 +423,14 @@ protected override Size DefaultSize { /// on controls that are based on Win32 Native Controls. /// [EditorBrowsable(EditorBrowsableState.Never)] - protected override bool DoubleBuffered { - get { + protected override bool DoubleBuffered + { + get + { return base.DoubleBuffered; } - set { + set + { base.DoubleBuffered = value; } } @@ -394,25 +444,33 @@ protected override bool DoubleBuffered { DefaultValue(DEFAULT_FIRST_DAY_OF_WEEK), SRDescription(nameof(SR.MonthCalendarFirstDayOfWeekDescr)) ] - public Day FirstDayOfWeek { - get { + public Day FirstDayOfWeek + { + get + { return firstDayOfWeek; } - set { + set + { //valid values are 0x0 to 0x7 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)Day.Monday, (int)Day.Default)){ - throw new InvalidEnumArgumentException(nameof(FirstDayOfWeek), (int)value, typeof(Day)); + if (!ClientUtils.IsEnumValid(value, (int)value, (int)Day.Monday, (int)Day.Default)) + { + throw new InvalidEnumArgumentException(nameof(FirstDayOfWeek), (int)value, typeof(Day)); } - if (value != firstDayOfWeek) { + if (value != firstDayOfWeek) + { firstDayOfWeek = value; - if (IsHandleCreated) { - if (value == Day.Default) { + if (IsHandleCreated) + { + if (value == Day.Default) + { RecreateHandle(); } - else { - SendMessage(NativeMethods.MCM_SETFIRSTDAYOFWEEK, 0, (int) value); + else + { + SendMessage(NativeMethods.MCM_SETFIRSTDAYOFWEEK, 0, (int)value); } } } @@ -420,32 +478,41 @@ public Day FirstDayOfWeek { } [SRDescription(nameof(SR.MonthCalendarForeColorDescr))] - public override Color ForeColor { - get { - if (ShouldSerializeForeColor()) { + public override Color ForeColor + { + get + { + if (ShouldSerializeForeColor()) + { return base.ForeColor; } - else { + else + { return SystemColors.WindowText; } } - set { + set + { base.ForeColor = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public ImeMode ImeMode { - get { + new public ImeMode ImeMode + { + get + { return base.ImeMode; } - set { + set + { base.ImeMode = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler ImeModeChanged { + public new event EventHandler ImeModeChanged + { add => base.ImeModeChanged += value; remove => base.ImeModeChanged -= value; } @@ -459,13 +526,18 @@ public override Color ForeColor { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.MonthCalendarMaxDateDescr)) ] - public DateTime MaxDate { - get { + public DateTime MaxDate + { + get + { return DateTimePicker.EffectiveMaxDate(maxDate); } - set { - if (value != maxDate) { - if (value < DateTimePicker.EffectiveMinDate(minDate)) { + set + { + if (value != maxDate) + { + if (value < DateTimePicker.EffectiveMinDate(minDate)) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(MaxDate), FormatDate(value), nameof(MinDate))); } maxDate = value; @@ -484,18 +556,24 @@ public DateTime MaxDate { DefaultValue(DEFAULT_MAX_SELECTION_COUNT), SRDescription(nameof(SR.MonthCalendarMaxSelectionCountDescr)) ] - public int MaxSelectionCount { - get { + public int MaxSelectionCount + { + get + { return maxSelectionCount; } - set { - if (value < 1) { + set + { + if (value < 1) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(MaxSelectionCount), value.ToString("D"), 1)); } - if (value != maxSelectionCount) { - if (IsHandleCreated) { - if (unchecked( (int) (long)SendMessage(NativeMethods.MCM_SETMAXSELCOUNT, value, 0)) == 0) + if (value != maxSelectionCount) + { + if (IsHandleCreated) + { + if (unchecked((int)(long)SendMessage(NativeMethods.MCM_SETMAXSELCOUNT, value, 0)) == 0) throw new ArgumentException(string.Format(SR.MonthCalendarMaxSelCount, value.ToString("D")), nameof(value)); } maxSelectionCount = value; @@ -512,19 +590,25 @@ public int MaxSelectionCount { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.MonthCalendarMinDateDescr)) ] - public DateTime MinDate { - get { + public DateTime MinDate + { + get + { return DateTimePicker.EffectiveMinDate(minDate); } - set { - if (value != minDate) { - if (value > DateTimePicker.EffectiveMaxDate(maxDate)) { + set + { + if (value != minDate) + { + if (value > DateTimePicker.EffectiveMaxDate(maxDate)) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidHighBoundArgument, nameof(MinDate), FormatDate(value), nameof(MaxDate))); } // If trying to set the minimum less than DateTimePicker.MinimumDateTime, throw // an exception. - if (value < DateTimePicker.MinimumDateTime) { + if (value < DateTimePicker.MinimumDateTime) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(MinDate), FormatDate(value), FormatDate(DateTimePicker.MinimumDateTime))); } @@ -541,16 +625,20 @@ public DateTime MinDate { Localizable(true), SRDescription(nameof(SR.MonthCalendarMonthlyBoldedDatesDescr)) ] - public DateTime[] MonthlyBoldedDates { - get { + public DateTime[] MonthlyBoldedDates + { + get + { DateTime[] dateTimes = new DateTime[monthlyArrayOfDates.Count]; - for (int i=0;i < monthlyArrayOfDates.Count; ++i) { + for (int i = 0; i < monthlyArrayOfDates.Count; ++i) + { dateTimes[i] = (DateTime)this.monthlyArrayOfDates[i]; } return dateTimes; } - set { + set + { // @@ -558,15 +646,18 @@ public DateTime[] MonthlyBoldedDates { this.monthlyArrayOfDates.Clear(); datesToBoldMonthly = 0; - if (value != null && value.Length > 0) { + if (value != null && value.Length > 0) + { //add each boldeddate to our ArrayList... - for (int i = 0; i < value.Length; i++) { + for (int i = 0; i < value.Length; i++) + { this.monthlyArrayOfDates.Add(value[i]); } - for (int i = 0; i < value.Length; ++i) { - datesToBoldMonthly |= 0x00000001<<(value[i].Day-1); + for (int i = 0; i < value.Length; ++i) + { + datesToBoldMonthly |= 0x00000001 << (value[i].Day - 1); } } @@ -576,8 +667,10 @@ public DateTime[] MonthlyBoldedDates { /// /// - private DateTime Now { - get { + private DateTime Now + { + get + { return DateTime.Now.Date; } } @@ -587,18 +680,21 @@ private DateTime Now { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Padding Padding { + public new Padding Padding + { get { return base.Padding; } - set { base.Padding = value;} + set { base.Padding = value; } } [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public new event EventHandler PaddingChanged { - add => base.PaddingChanged += value; - remove => base.PaddingChanged -= value; } + public new event EventHandler PaddingChanged + { + add => base.PaddingChanged += value; + remove => base.PaddingChanged -= value; + } /// /// This is used for international applications where the language @@ -612,16 +708,21 @@ private DateTime Now { DefaultValue(false), SRDescription(nameof(SR.ControlRightToLeftLayoutDescr)) ] - public virtual bool RightToLeftLayout { - get { + public virtual bool RightToLeftLayout + { + get + { return rightToLeftLayout; } - set { - if (value != rightToLeftLayout) { + set + { + if (value != rightToLeftLayout) + { rightToLeftLayout = value; - using(new LayoutTransaction(this, this, PropertyNames.RightToLeftLayout)) { + using (new LayoutTransaction(this, this, PropertyNames.RightToLeftLayout)) + { OnRightToLeftLayoutChanged(EventArgs.Empty); } } @@ -640,21 +741,28 @@ public virtual bool RightToLeftLayout { DefaultValue(DEFAULT_SCROLL_CHANGE), SRDescription(nameof(SR.MonthCalendarScrollChangeDescr)) ] - public int ScrollChange { - get { + public int ScrollChange + { + get + { return scrollChange; } - set { - if (scrollChange != value) { + set + { + if (scrollChange != value) + { - if (value < 0) { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(ScrollChange), value.ToString("D"), 0)); } - if (value > MaxScrollChange) { + if (value > MaxScrollChange) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidHighBoundArgumentEx, nameof(ScrollChange), value.ToString("D"), MaxScrollChange.ToString("D"))); } - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(NativeMethods.MCM_SETMONTHDELTA, value, 0); } scrollChange = value; @@ -672,28 +780,36 @@ public int ScrollChange { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.MonthCalendarSelectionEndDescr)) ] - public DateTime SelectionEnd { - get { + public DateTime SelectionEnd + { + get + { return selectionEnd; } - set { - if (selectionEnd != value) { + set + { + if (selectionEnd != value) + { // Keep SelectionEnd within min and max - if (value < MinDate) { + if (value < MinDate) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(SelectionEnd), FormatDate(value), nameof(MinDate))); } - if (value > MaxDate) { + if (value > MaxDate) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidHighBoundArgumentEx, nameof(SelectionEnd), FormatDate(value), nameof(MaxDate))); } // If we've moved SelectionEnd before SelectionStart, move SelectionStart back - if (selectionStart > value) { + if (selectionStart > value) + { selectionStart = value; } // If we've moved SelectionEnd too far beyond SelectionStart, move SelectionStart forward - if ((value - selectionStart).Days >= maxSelectionCount) { + if ((value - selectionStart).Days >= maxSelectionCount) + { selectionStart = value.AddDays(1 - maxSelectionCount); } @@ -714,29 +830,37 @@ public DateTime SelectionEnd { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.MonthCalendarSelectionStartDescr)) ] - public DateTime SelectionStart { - get { + public DateTime SelectionStart + { + get + { return selectionStart; } - set { - if (selectionStart != value) { + set + { + if (selectionStart != value) + { // Keep SelectionStart within min and max // - if (value < minDate) { + if (value < minDate) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(SelectionStart), FormatDate(value), nameof(MinDate))); } - if (value > maxDate) { + if (value > maxDate) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidHighBoundArgumentEx, nameof(SelectionStart), FormatDate(value), nameof(MaxDate))); } // If we've moved SelectionStart beyond SelectionEnd, move SelectionEnd forward - if (selectionEnd < value) { + if (selectionEnd < value) + { selectionEnd = value; } // If we've moved SelectionStart too far back from SelectionEnd, move SelectionEnd back - if ((selectionEnd - value).Days >= maxSelectionCount) { + if ((selectionEnd - value).Days >= maxSelectionCount) + { selectionEnd = value.AddDays(maxSelectionCount - 1); } @@ -754,11 +878,14 @@ public DateTime SelectionStart { SRDescription(nameof(SR.MonthCalendarSelectionRangeDescr)), Bindable(true) ] - public SelectionRange SelectionRange { - get { + public SelectionRange SelectionRange + { + get + { return new SelectionRange(SelectionStart, SelectionEnd); } - set { + set + { SetSelectionRange(value.Start, value.End); } } @@ -772,12 +899,16 @@ public SelectionRange SelectionRange { DefaultValue(true), SRDescription(nameof(SR.MonthCalendarShowTodayDescr)) ] - public bool ShowToday { - get { + public bool ShowToday + { + get + { return showToday; } - set { - if (showToday != value) { + set + { + if (showToday != value) + { showToday = value; UpdateStyles(); AdjustSize(); @@ -794,12 +925,16 @@ public bool ShowToday { DefaultValue(true), SRDescription(nameof(SR.MonthCalendarShowTodayCircleDescr)) ] - public bool ShowTodayCircle { - get { + public bool ShowTodayCircle + { + get + { return showTodayCircle; } - set { - if (showTodayCircle != value) { + set + { + if (showTodayCircle != value) + { showTodayCircle = value; UpdateStyles(); } @@ -816,12 +951,16 @@ public bool ShowTodayCircle { DefaultValue(false), SRDescription(nameof(SR.MonthCalendarShowWeekNumbersDescr)) ] - public bool ShowWeekNumbers { - get { + public bool ShowWeekNumbers + { + get + { return showWeekNumbers; } - set { - if (showWeekNumbers != value) { + set + { + if (showWeekNumbers != value) + { showWeekNumbers = value; UpdateStyles(); AdjustSize(); @@ -842,13 +981,16 @@ public bool ShowWeekNumbers { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.MonthCalendarSingleMonthSizeDescr)) ] - public Size SingleMonthSize { - get { + public Size SingleMonthSize + { + get + { NativeMethods.RECT rect = new NativeMethods.RECT(); - if (IsHandleCreated) { + if (IsHandleCreated) + { - if (unchecked( (int) (long)SendMessage(NativeMethods.MCM_GETMINREQRECT, 0, ref rect)) == 0) + if (unchecked((int)(long)SendMessage(NativeMethods.MCM_GETMINREQRECT, 0, ref rect)) == 0) throw new InvalidOperationException(SR.InvalidSingleMonthSize); return new Size(rect.right, rect.bottom); @@ -867,28 +1009,35 @@ public Size SingleMonthSize { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Localizable(false) ] - public new Size Size { - get { + public new Size Size + { + get + { return base.Size; } - set { + set + { base.Size = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Bindable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TextChanged { + new public event EventHandler TextChanged + { add => base.TextChanged += value; remove => base.TextChanged -= value; } @@ -902,27 +1051,36 @@ public override string Text { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.MonthCalendarTodayDateDescr)) ] - public DateTime TodayDate { - get { - if (todayDateSet) return todayDate; - if (IsHandleCreated) { + public DateTime TodayDate + { + get + { + if (todayDateSet) + return todayDate; + if (IsHandleCreated) + { NativeMethods.SYSTEMTIME st = new NativeMethods.SYSTEMTIME(); int res = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.MCM_GETTODAY, 0, st); Debug.Assert(res != 0, "MCM_GETTODAY failed"); return DateTimePicker.SysTimeToDateTime(st).Date; } - else return Now.Date; + else + return Now.Date; } - set { - if (!(todayDateSet) || (DateTime.Compare(value, todayDate) != 0)) { + set + { + if (!(todayDateSet) || (DateTime.Compare(value, todayDate) != 0)) + { // throw if trying to set the TodayDate to a value greater than MaxDate - if (DateTime.Compare(value, maxDate) > 0) { + if (DateTime.Compare(value, maxDate) > 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidHighBoundArgumentEx, nameof(TodayDate), FormatDate(value), FormatDate(maxDate))); } // throw if trying to set the TodayDate to a value less than MinDate - if (DateTime.Compare(value, minDate) < 0) { + if (DateTime.Compare(value, minDate) < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgument, nameof(TodayDate), FormatDate(value), FormatDate(minDate))); } @@ -945,8 +1103,10 @@ public DateTime TodayDate { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.MonthCalendarTodayDateSetDescr)) ] - public bool TodayDateSet { - get { + public bool TodayDateSet + { + get + { return todayDateSet; } } @@ -959,12 +1119,16 @@ public bool TodayDateSet { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.MonthCalendarTitleBackColorDescr)) ] - public Color TitleBackColor { - get { + public Color TitleBackColor + { + get + { return titleBackColor; } - set { - if (value.IsEmpty) { + set + { + if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.InvalidNullArgument, "value")); } @@ -981,12 +1145,16 @@ public Color TitleBackColor { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.MonthCalendarTitleForeColorDescr)) ] - public Color TitleForeColor { - get { + public Color TitleForeColor + { + get + { return titleForeColor; } - set { - if (value.IsEmpty) { + set + { + if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.InvalidNullArgument, "value")); } @@ -1003,12 +1171,16 @@ public Color TitleForeColor { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.MonthCalendarTrailingForeColorDescr)) ] - public Color TrailingForeColor { - get { + public Color TrailingForeColor + { + get + { return trailingForeColor; } - set { - if (value.IsEmpty) { + set + { + if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.InvalidNullArgument, "value")); } @@ -1021,17 +1193,20 @@ public Color TrailingForeColor { /// Adds a day that will be bolded annually on the month calendar. /// Be sure to call updateBoldedDates() afterwards. /// - public void AddAnnuallyBoldedDate(DateTime date) { + public void AddAnnuallyBoldedDate(DateTime date) + { annualArrayOfDates.Add(date); - monthsOfYear[date.Month-1] |= 0x00000001<<(date.Day-1); + monthsOfYear[date.Month - 1] |= 0x00000001 << (date.Day - 1); } /// /// Adds a day that will be bolded on the month calendar. /// Be sure to call updateBoldedDates() afterwards. /// - public void AddBoldedDate(DateTime date) { - if (!this.arrayOfDates.Contains(date)) { + public void AddBoldedDate(DateTime date) + { + if (!this.arrayOfDates.Contains(date)) + { this.arrayOfDates.Add(date); } } @@ -1040,49 +1215,56 @@ public void AddBoldedDate(DateTime date) { /// Adds a day that will be bolded monthly on the month calendar. /// Be sure to call updateBoldedDates() afterwards. /// - public void AddMonthlyBoldedDate(DateTime date) { + public void AddMonthlyBoldedDate(DateTime date) + { this.monthlyArrayOfDates.Add(date); - datesToBoldMonthly |= 0x00000001<<(date.Day-1); + datesToBoldMonthly |= 0x00000001 << (date.Day - 1); } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler Click { + public new event EventHandler Click + { add => base.Click += value; remove => base.Click -= value; } [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.MonthCalendarOnDateChangedDescr))] - public event DateRangeEventHandler DateChanged { + public event DateRangeEventHandler DateChanged + { add => onDateChanged += value; remove => onDateChanged -= value; } [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.MonthCalendarOnDateSelectedDescr))] - public event DateRangeEventHandler DateSelected { + public event DateRangeEventHandler DateSelected + { add => onDateSelected += value; remove => onDateSelected -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler DoubleClick { + public new event EventHandler DoubleClick + { add => base.DoubleClick += value; remove => base.DoubleClick -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event MouseEventHandler MouseClick { + public new event MouseEventHandler MouseClick + { add => base.MouseClick += value; remove => base.MouseClick -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event MouseEventHandler MouseDoubleClick { + public new event MouseEventHandler MouseDoubleClick + { add => base.MouseDoubleClick += value; remove => base.MouseDoubleClick -= value; } @@ -1092,13 +1274,15 @@ public event DateRangeEventHandler DateSelected { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event PaintEventHandler Paint { + public new event PaintEventHandler Paint + { add => base.Paint += value; remove => base.Paint -= value; } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnRightToLeftLayoutChangedDescr))] - public event EventHandler RightToLeftLayoutChanged { + public event EventHandler RightToLeftLayoutChanged + { add => onRightToLeftLayoutChanged += value; remove => onRightToLeftLayoutChanged -= value; } @@ -1109,7 +1293,8 @@ public event EventHandler RightToLeftLayoutChanged { /// restricted by the maximum size of the parent control, hence the requested number /// of rows and columns may not be what you get. /// - private void AdjustSize() { + private void AdjustSize() + { Size minSize = GetMinReqRect(); Size = minSize; } @@ -1117,46 +1302,54 @@ private void AdjustSize() { /// /// Event handler that bolds dates indicated by arrayOfDates /// - private void BoldDates(DateBoldEventArgs e) { + private void BoldDates(DateBoldEventArgs e) + { int months = e.Size; e.DaysToBold = new int[months]; SelectionRange range = GetDisplayRange(false); int startMonth = range.Start.Month; int startYear = range.Start.Year; int numDates = arrayOfDates.Count; - for (int i=0; i= 0 && DateTime.Compare(date, range.End) <= 0) { + for (int i = 0; i < numDates; ++i) + { + DateTime date = (DateTime)arrayOfDates[i]; + if (DateTime.Compare(date, range.Start) >= 0 && DateTime.Compare(date, range.End) <= 0) + { int month = date.Month; int year = date.Year; - int index = (year == startYear) ? month - startMonth : month + year*MONTHS_IN_YEAR - startYear*MONTHS_IN_YEAR - startMonth; - e.DaysToBold[index] |= (0x00000001<<(date.Day-1)); + int index = (year == startYear) ? month - startMonth : month + year * MONTHS_IN_YEAR - startYear * MONTHS_IN_YEAR - startMonth; + e.DaysToBold[index] |= (0x00000001 << (date.Day - 1)); } } //now we figure out which monthly and annual dates to bold --startMonth; - for (int i=0; i /// Compares only the day and month of each time. /// - private bool CompareDayAndMonth(DateTime t1, DateTime t2) { - return(t1.Day == t2.Day && t1.Month == t2.Month); + private bool CompareDayAndMonth(DateTime t1, DateTime t2) + { + return (t1.Day == t2.Day && t1.Month == t2.Month); } /// /// - protected override void CreateHandle() { - if (!RecreatingHandle) { - IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); - try { + protected override void CreateHandle() + { + if (!RecreatingHandle) + { + IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); + try + { NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); icc.dwICC = NativeMethods.ICC_DATE_CLASSES; SafeNativeMethods.InitCommonControlsEx(icc); } - finally { + finally + { UnsafeNativeMethods.ThemingScope.Deactivate(userCookie); } } @@ -1169,8 +1362,10 @@ protected override void CreateHandle() { /// for you. However, there may be times when you may want to expedite /// the garbage collectors cleanup. /// - protected override void Dispose(bool disposing) { - if (mdsBuffer != IntPtr.Zero) { + protected override void Dispose(bool disposing) + { + if (mdsBuffer != IntPtr.Zero) + { Marshal.FreeHGlobal(mdsBuffer); mdsBuffer = IntPtr.Zero; } @@ -1180,7 +1375,8 @@ protected override void Dispose(bool disposing) { // Return a localized string representation of the given DateTime value. // Used for throwing exceptions, etc. // - private static string FormatDate(DateTime value) { + private static string FormatDate(DateTime value) + { return value.ToString("d", CultureInfo.CurrentCulture); } @@ -1188,7 +1384,8 @@ private static string FormatDate(DateTime value) { /// Retrieves date information that represents the low and high limits of the /// control's display. /// - public SelectionRange GetDisplayRange(bool visible) { + public SelectionRange GetDisplayRange(bool visible) + { if (visible) return GetMonthRange(NativeMethods.GMR_VISIBLE); else @@ -1198,8 +1395,10 @@ public SelectionRange GetDisplayRange(bool visible) { /// /// Retrieves the enumeration value corresponding to the hit area. /// - private HitArea GetHitArea(int hit) { - switch (hit) { + private HitArea GetHitArea(int hit) + { + switch (hit) + { case NativeMethods.MCHT_TITLEBK: return HitArea.TitleBackground; case NativeMethods.MCHT_TITLEMONTH: @@ -1232,7 +1431,8 @@ private HitArea GetHitArea(int hit) { /// /// stub for getMinReqRect (int, boolean) /// - private Size GetMinReqRect() { + private Size GetMinReqRect() + { return GetMinReqRect(0, false, false); } @@ -1243,7 +1443,8 @@ private Size GetMinReqRect() { /// is set to false. If updateRows is true, then the /// number of rows will be updated according to height. /// - private Size GetMinReqRect(int newDimensionLength, bool updateRows, bool updateCols) { + private Size GetMinReqRect(int newDimensionLength, bool updateRows, bool updateCols) + { Size minSize = SingleMonthSize; // Calculate calendar height @@ -1256,22 +1457,25 @@ private Size GetMinReqRect(int newDimensionLength, bool updateRows, bool updateC } int todayHeight = textExtent.Height + 4; // The constant 4 is from the comctl32 MonthCalendar source code int calendarHeight = minSize.Height; - if (ShowToday) { + if (ShowToday) + { // If ShowToday is true, then minSize already includes the height of the today string. // So we remove it to get the actual calendar height. // calendarHeight -= todayHeight; } - if (updateRows) { + if (updateRows) + { Debug.Assert(calendarHeight > INSERT_HEIGHT_SIZE, "Divide by 0"); - int nRows = (newDimensionLength - todayHeight + INSERT_HEIGHT_SIZE)/(calendarHeight + INSERT_HEIGHT_SIZE); + int nRows = (newDimensionLength - todayHeight + INSERT_HEIGHT_SIZE) / (calendarHeight + INSERT_HEIGHT_SIZE); this.dimensions.Height = (nRows < 1) ? 1 : nRows; } - if (updateCols) { + if (updateCols) + { Debug.Assert(minSize.Width > INSERT_WIDTH_SIZE, "Divide by 0"); - int nCols = (newDimensionLength - scaledExtraPadding) /minSize.Width; + int nCols = (newDimensionLength - scaledExtraPadding) / minSize.Width; this.dimensions.Width = (nCols < 1) ? 1 : nCols; } @@ -1280,9 +1484,11 @@ private Size GetMinReqRect(int newDimensionLength, bool updateRows, bool updateC // If the width we've calculated is too small to fit the Today string, enlarge the width to fit // - if (IsHandleCreated) { - int maxTodayWidth = unchecked( (int) (long)SendMessage(NativeMethods.MCM_GETMAXTODAYWIDTH, 0, 0)); - if (maxTodayWidth > minSize.Width) { + if (IsHandleCreated) + { + int maxTodayWidth = unchecked((int)(long)SendMessage(NativeMethods.MCM_GETMAXTODAYWIDTH, 0, 0)); + if (maxTodayWidth > minSize.Width) + { minSize.Width = maxTodayWidth; } } @@ -1296,7 +1502,8 @@ private Size GetMinReqRect(int newDimensionLength, bool updateRows, bool updateC /// /// - private SelectionRange GetMonthRange(int flag) { + private SelectionRange GetMonthRange(int flag) + { NativeMethods.SYSTEMTIMEARRAY sa = new NativeMethods.SYSTEMTIMEARRAY(); SelectionRange range = new SelectionRange(); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.MCM_GETMONTHRANGE, flag, sa); @@ -1321,7 +1528,8 @@ private SelectionRange GetMonthRange(int flag) { /// Called by setBoundsCore. If updateRows is true, then the /// number of rows will be updated according to height. /// - private int GetPreferredHeight(int height, bool updateRows) { + private int GetPreferredHeight(int height, bool updateRows) + { Size preferredSize = GetMinReqRect(height, updateRows, false); return preferredSize.Height; } @@ -1330,7 +1538,8 @@ private int GetPreferredHeight(int height, bool updateRows) { /// Called by setBoundsCore. If updateCols is true, then the /// number of columns will be updated according to width. /// - private int GetPreferredWidth(int width, bool updateCols) { + private int GetPreferredWidth(int width, bool updateCols) + { Size preferredSize = GetMinReqRect(width, false, updateCols); return preferredSize.Width; } @@ -1339,7 +1548,8 @@ private int GetPreferredWidth(int width, bool updateCols) { /// Determines which portion of a month calendar control is at /// at a given point on the screen. /// - public HitTestInfo HitTest(int x, int y) { + public HitTestInfo HitTest(int x, int y) + { NativeMethods.MCHITTESTINFO mchi = new NativeMethods.MCHITTESTINFO(); mchi.pt_x = x; mchi.pt_y = y; @@ -1349,7 +1559,8 @@ public HitTestInfo HitTest(int x, int y) { // If the hit area has an associated valid date, get it // HitArea hitArea = GetHitArea(mchi.uHit); - if (HitTestInfo.HitAreaHasValidDateTime(hitArea)) { + if (HitTestInfo.HitAreaHasValidDateTime(hitArea)) + { NativeMethods.SYSTEMTIME sys = new NativeMethods.SYSTEMTIME(); sys.wYear = mchi.st_wYear; sys.wMonth = mchi.st_wMonth; @@ -1361,7 +1572,8 @@ public HitTestInfo HitTest(int x, int y) { sys.wMilliseconds = mchi.st_wMilliseconds; return new HitTestInfo(new Point(mchi.pt_x, mchi.pt_y), hitArea, DateTimePicker.SysTimeToDateTime(sys)); } - else { + else + { return new HitTestInfo(new Point(mchi.pt_x, mchi.pt_y), hitArea); } } @@ -1370,16 +1582,20 @@ public HitTestInfo HitTest(int x, int y) { /// Determines which portion of a month calendar control is at /// at a given point on the screen. /// - public HitTestInfo HitTest(Point point) { + public HitTestInfo HitTest(Point point) + { return HitTest(point.X, point.Y); } /// /// Handling special input keys, such as pgup, pgdown, home, end, etc... /// - protected override bool IsInputKey(Keys keyData) { - if ((keyData & Keys.Alt) == Keys.Alt) return false; - switch (keyData & Keys.KeyCode) { + protected override bool IsInputKey(Keys keyData) + { + if ((keyData & Keys.Alt) == Keys.Alt) + return false; + switch (keyData & Keys.KeyCode) + { case Keys.PageUp: case Keys.PageDown: case Keys.Home: @@ -1392,15 +1608,18 @@ protected override bool IsInputKey(Keys keyData) { /// /// Overrides Control.OnHandleCreated() /// - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { base.OnHandleCreated(e); SetSelRange(selectionStart, selectionEnd); - if (maxSelectionCount != DEFAULT_MAX_SELECTION_COUNT) { + if (maxSelectionCount != DEFAULT_MAX_SELECTION_COUNT) + { SendMessage(NativeMethods.MCM_SETMAXSELCOUNT, maxSelectionCount, 0); } AdjustSize(); - if (todayDateSet) { + if (todayDateSet) + { NativeMethods.SYSTEMTIME st = DateTimePicker.DateTimeToSysTime(todayDate); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.MCM_SETTODAY, 0, st); } @@ -1412,16 +1631,19 @@ protected override void OnHandleCreated(EventArgs e) { SetControlColor(NativeMethods.MCSC_TRAILINGTEXT, trailingForeColor); int firstDay; - if (firstDayOfWeek == Day.Default) { + if (firstDayOfWeek == Day.Default) + { firstDay = NativeMethods.LOCALE_IFIRSTDAYOFWEEK; } - else { + else + { firstDay = (int)firstDayOfWeek; } SendMessage(NativeMethods.MCM_SETFIRSTDAYOFWEEK, 0, firstDay); SetRange(); - if (scrollChange != DEFAULT_SCROLL_CHANGE) { + if (scrollChange != DEFAULT_SCROLL_CHANGE) + { SendMessage(NativeMethods.MCM_SETMONTHDELTA, scrollChange, 0); } @@ -1432,7 +1654,8 @@ protected override void OnHandleCreated(EventArgs e) { /// /// Overrides Control.OnHandleDestroyed() /// - protected override void OnHandleDestroyed(EventArgs e) { + protected override void OnHandleDestroyed(EventArgs e) + { SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(this.MarshaledUserPreferenceChanged); base.OnHandleDestroyed(e); } @@ -1442,8 +1665,10 @@ protected override void OnHandleDestroyed(EventArgs e) { /// Fires the event indicating that the currently selected date /// or range of dates has changed. /// - protected virtual void OnDateChanged(DateRangeEventArgs drevent) { - if (onDateChanged != null) { + protected virtual void OnDateChanged(DateRangeEventArgs drevent) + { + if (onDateChanged != null) + { onDateChanged(this, drevent); } } @@ -1451,39 +1676,48 @@ protected virtual void OnDateChanged(DateRangeEventArgs drevent) { /// /// Fires the event indicating that the user has changed his\her selection. /// - protected virtual void OnDateSelected(DateRangeEventArgs drevent) { - if (onDateSelected != null) { + protected virtual void OnDateSelected(DateRangeEventArgs drevent) + { + if (onDateSelected != null) + { onDateSelected(this, drevent); } } - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { base.OnFontChanged(e); AdjustSize(); } - protected override void OnForeColorChanged(EventArgs e) { + protected override void OnForeColorChanged(EventArgs e) + { base.OnForeColorChanged(e); SetControlColor(NativeMethods.MCSC_TEXT, ForeColor); } - protected override void OnBackColorChanged(EventArgs e) { + protected override void OnBackColorChanged(EventArgs e) + { base.OnBackColorChanged(e); SetControlColor(NativeMethods.MCSC_MONTHBK, BackColor); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnRightToLeftLayoutChanged(EventArgs e) { - if (GetAnyDisposingInHierarchy()) { + protected virtual void OnRightToLeftLayoutChanged(EventArgs e) + { + if (GetAnyDisposingInHierarchy()) + { return; } - if (RightToLeft == RightToLeft.Yes) { + if (RightToLeft == RightToLeft.Yes) + { RecreateHandle(); } - if (onRightToLeftLayoutChanged != null) { - onRightToLeftLayoutChanged(this, e); + if (onRightToLeftLayoutChanged != null) + { + onRightToLeftLayoutChanged(this, e); } } @@ -1492,9 +1726,10 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) { /// /// Removes all annually bolded days. Be sure to call updateBoldedDates() afterwards. /// - public void RemoveAllAnnuallyBoldedDates() { + public void RemoveAllAnnuallyBoldedDates() + { this.annualArrayOfDates.Clear(); - for (int i=0; i /// Removes all the bolded days. Be sure to call updateBoldedDates() afterwards. /// - public void RemoveAllBoldedDates() { + public void RemoveAllBoldedDates() + { this.arrayOfDates.Clear(); } /// /// Removes all monthly bolded days. Be sure to call updateBoldedDates() afterwards. /// - public void RemoveAllMonthlyBoldedDates() { + public void RemoveAllMonthlyBoldedDates() + { this.monthlyArrayOfDates.Clear(); datesToBoldMonthly = 0; } @@ -1521,22 +1758,27 @@ public void RemoveAllMonthlyBoldedDates() { /// comparing dates, only the day and month are used. Be sure to call /// updateBoldedDates afterwards. /// - public void RemoveAnnuallyBoldedDate(DateTime date) { + public void RemoveAnnuallyBoldedDate(DateTime date) + { int length = annualArrayOfDates.Count; - int i=0; - for (; i @@ -1545,10 +1787,13 @@ public void RemoveAnnuallyBoldedDate(DateTime date) { /// once in the bolded date list, then only the first date is removed. /// Be sure to call updateBoldedDates() afterwards. /// - public void RemoveBoldedDate(DateTime date) { + public void RemoveBoldedDate(DateTime date) + { int length = arrayOfDates.Count; - for (int i=0; i - public void RemoveMonthlyBoldedDate(DateTime date) { + public void RemoveMonthlyBoldedDate(DateTime date) + { int length = monthlyArrayOfDates.Count; - int i=0; - for (; i /// Resets the maximum selectable date. By default value, there is no /// upper limit. /// - private void ResetMaxDate() { + private void ResetMaxDate() + { MaxDate = DateTime.MaxValue; } @@ -1605,12 +1859,14 @@ private void ResetMaxDate() { /// Resets the minimum selectable date. By default value, there is no /// lower limit. /// - private void ResetMinDate() { + private void ResetMinDate() + { MinDate = DateTime.MinValue; } - private void ResetMonthlyBoldedDates() { + private void ResetMonthlyBoldedDates() + { monthlyArrayOfDates.Clear(); } @@ -1618,19 +1874,23 @@ private void ResetMonthlyBoldedDates() { /// Resets the limits of the selection range. By default value, the upper /// and lower limit is the current date. /// - private void ResetSelectionRange() { + private void ResetSelectionRange() + { SetSelectionRange(Now, Now); } - private void ResetTrailingForeColor() { + private void ResetTrailingForeColor() + { TrailingForeColor = DEFAULT_TRAILING_FORE_COLOR; } - private void ResetTitleForeColor() { + private void ResetTitleForeColor() + { TitleForeColor = DEFAULT_TITLE_FORE_COLOR; } - private void ResetTitleBackColor() { + private void ResetTitleBackColor() + { TitleBackColor = DEFAULT_TITLE_BACK_COLOR; } @@ -1642,7 +1902,8 @@ private void ResetTitleBackColor() { /// the control will no longer automatically update the current day /// for you. To re-enable this behavior, ResetTodayDate() is used. /// - private void ResetTodayDate() { + private void ResetTodayDate() + { todayDateSet = false; UpdateTodayDate(); } @@ -1656,20 +1917,23 @@ private void ResetTodayDate() { /// it is not necessary to decrease the size of an allocated /// block if the new requested size is smaller. /// - private IntPtr RequestBuffer(int reqSize) { + private IntPtr RequestBuffer(int reqSize) + { Debug.Assert(reqSize > 0, "Requesting a ridiculously small buffer"); int intSize = 4; // if the current buffer size is insufficient... - if (reqSize * intSize > mdsBufferSize) { + if (reqSize * intSize > mdsBufferSize) + { // free and expand the buffer, - if (mdsBuffer != IntPtr.Zero) { + if (mdsBuffer != IntPtr.Zero) + { Marshal.FreeHGlobal(mdsBuffer); mdsBuffer = IntPtr.Zero; } // Round up to the nearest multiple of MINIMUM_ALLOC_SIZE - float quotient = (float) (reqSize-1) / MINIMUM_ALLOC_SIZE; - int actualSize = ((int) (quotient+1)) * MINIMUM_ALLOC_SIZE; + float quotient = (float)(reqSize - 1) / MINIMUM_ALLOC_SIZE; + int actualSize = ((int)(quotient + 1)) * MINIMUM_ALLOC_SIZE; Debug.Assert(actualSize >= reqSize, "Tried to round up, but got it wrong"); mdsBufferSize = actualSize * intSize; @@ -1682,7 +1946,8 @@ private IntPtr RequestBuffer(int reqSize) { /// /// Overrides Control.SetBoundsCore to enforce auto-sizing. /// - protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { + protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) + { Rectangle oldBounds = Bounds; Size max = SystemInformation.MaxWindowTrackSize; @@ -1690,12 +1955,14 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound // We only want to update the number of rows/columns if we are not currently being scaled. bool updateRowsAndColumns = !DpiHelper.IsScalingRequirementMet || !IsCurrentlyBeingScaled; - if (width != oldBounds.Width) { + if (width != oldBounds.Width) + { if (width > max.Width) width = max.Width; width = GetPreferredWidth(width, updateRowsAndColumns); } - if (height != oldBounds.Height) { + if (height != oldBounds.Height) + { if (height > max.Height) height = max.Height; height = GetPreferredHeight(height, updateRowsAndColumns); @@ -1706,8 +1973,10 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound /// /// If the handle has been created, this applies the color to the control /// - private void SetControlColor(int colorIndex, Color value) { - if (IsHandleCreated) { + private void SetControlColor(int colorIndex, Color value) + { + if (IsHandleCreated) + { SendMessage(NativeMethods.MCM_SETCOLOR, colorIndex, ColorTranslator.ToWin32(value)); } } @@ -1716,29 +1985,36 @@ private void SetControlColor(int colorIndex, Color value) { /// Updates the window handle with the min/max ranges if it has been /// created. /// - private void SetRange() { + private void SetRange() + { SetRange(DateTimePicker.EffectiveMinDate(minDate), DateTimePicker.EffectiveMaxDate(maxDate)); } - private void SetRange(DateTime minDate, DateTime maxDate) { + private void SetRange(DateTime minDate, DateTime maxDate) + { // Keep selection range within passed in minDate and maxDate - if (selectionStart < minDate) { + if (selectionStart < minDate) + { selectionStart = minDate; } - if (selectionStart > maxDate) { + if (selectionStart > maxDate) + { selectionStart = maxDate; } - if (selectionEnd < minDate) { + if (selectionEnd < minDate) + { selectionEnd = minDate; } - if (selectionEnd > maxDate) { + if (selectionEnd > maxDate) + { selectionEnd = maxDate; } SetSelRange(selectionStart, selectionEnd); // Updated the calendar range // - if (IsHandleCreated) { + if (IsHandleCreated) + { int flag = 0; NativeMethods.SYSTEMTIMEARRAY sa = new NativeMethods.SYSTEMTIMEARRAY(); @@ -1762,11 +2038,14 @@ private void SetRange(DateTime minDate, DateTime maxDate) { /// /// Sets the number of columns and rows to display. /// - public void SetCalendarDimensions(int x, int y) { - if (x < 1) { + public void SetCalendarDimensions(int x, int y) + { + if (x < 1) + { throw new ArgumentOutOfRangeException(nameof(x), string.Format(SR.MonthCalendarInvalidDimensions, (x).ToString("D", CultureInfo.CurrentCulture), (y).ToString("D", CultureInfo.CurrentCulture))); } - if (y < 1) { + if (y < 1) + { throw new ArgumentOutOfRangeException(nameof(y), string.Format(SR.MonthCalendarInvalidDimensions, (x).ToString("D", CultureInfo.CurrentCulture), (y).ToString("D", CultureInfo.CurrentCulture))); } @@ -1775,16 +2054,20 @@ public void SetCalendarDimensions(int x, int y) { // The following code emulates what is done inside monthcalendar (in comctl32.dll): // The dimensions are gradually reduced until the inequality above holds. // - while (x * y > 12) { - if (x > y) { + while (x * y > 12) + { + if (x > y) + { x--; } - else { + else + { y--; } } - if (dimensions.Width != x || dimensions.Height != y) { + if (dimensions.Width != x || dimensions.Height != y) + { this.dimensions.Width = x; this.dimensions.Height = y; AdjustSize(); @@ -1795,12 +2078,15 @@ public void SetCalendarDimensions(int x, int y) { /// Sets date as the current selected date. The start and begin of /// the selection range will both be equal to date. /// - public void SetDate(DateTime date) { + public void SetDate(DateTime date) + { - if (date.Ticks < minDate.Ticks) { + if (date.Ticks < minDate.Ticks) + { throw new ArgumentOutOfRangeException(nameof(date), date, string.Format(SR.InvalidLowBoundArgumentEx, nameof(date), FormatDate(date), nameof(MinDate))); } - if (date.Ticks > maxDate.Ticks) { + if (date.Ticks > maxDate.Ticks) + { throw new ArgumentOutOfRangeException(nameof(date), date, string.Format(SR.InvalidHighBoundArgumentEx, nameof(date), FormatDate(date), nameof(MaxDate))); } @@ -1812,39 +2098,48 @@ public void SetDate(DateTime date) { /// The selection range will not be set if the selection range exceeds the /// maximum selection count. /// - public void SetSelectionRange(DateTime date1, DateTime date2) { + public void SetSelectionRange(DateTime date1, DateTime date2) + { // Keep the dates within the min and max dates - if (date1.Ticks < minDate.Ticks) { + if (date1.Ticks < minDate.Ticks) + { throw new ArgumentOutOfRangeException(nameof(date1), date1, string.Format(SR.InvalidLowBoundArgumentEx, nameof(SelectionStart), FormatDate(date1), nameof(MinDate))); } - if (date1.Ticks > maxDate.Ticks) { + if (date1.Ticks > maxDate.Ticks) + { throw new ArgumentOutOfRangeException(nameof(date1), date1, string.Format(SR.InvalidHighBoundArgumentEx, nameof(SelectionEnd), FormatDate(date1), nameof(MaxDate))); } - if (date2.Ticks < minDate.Ticks) { + if (date2.Ticks < minDate.Ticks) + { throw new ArgumentOutOfRangeException(nameof(date2), date2, string.Format(SR.InvalidLowBoundArgumentEx, nameof(SelectionStart), FormatDate(date2), nameof(MinDate))); } - if (date2.Ticks > maxDate.Ticks) { + if (date2.Ticks > maxDate.Ticks) + { throw new ArgumentOutOfRangeException(nameof(date2), date2, string.Format(SR.InvalidHighBoundArgumentEx, nameof(SelectionEnd), FormatDate(date2), nameof(MaxDate))); } // If date1 > date2, we just select date2 (compat) // - if (date1 > date2) { + if (date1 > date2) + { date2 = date1; } // If the range exceeds maxSelectionCount, compare with the previous range and adjust whichever // limit hasn't changed. // - if ((date2 - date1).Days >= maxSelectionCount) { + if ((date2 - date1).Days >= maxSelectionCount) + { - if (date1.Ticks == selectionStart.Ticks) { + if (date1.Ticks == selectionStart.Ticks) + { // Bring start date forward // date1 = date2.AddDays(1 - maxSelectionCount); } - else { + else + { // Bring end date back // date2 = date1.AddDays(maxSelectionCount - 1); @@ -1858,12 +2153,14 @@ public void SetSelectionRange(DateTime date1, DateTime date2) { /// /// Upper must be greater than Lower /// - private void SetSelRange(DateTime lower, DateTime upper) { + private void SetSelRange(DateTime lower, DateTime upper) + { Debug.Assert(lower.Ticks <= upper.Ticks, "lower must be less than upper"); bool changed = false; - if (selectionStart != lower || selectionEnd != upper) { + if (selectionStart != lower || selectionEnd != upper) + { changed = true; selectionStart = lower; selectionEnd = upper; @@ -1872,7 +2169,8 @@ private void SetSelRange(DateTime lower, DateTime upper) { // always set the value on the control, to ensure that // it is up to date. // - if (IsHandleCreated) { + if (IsHandleCreated) + { NativeMethods.SYSTEMTIMEARRAY sa = new NativeMethods.SYSTEMTIMEARRAY(); NativeMethods.SYSTEMTIME sys = DateTimePicker.DateTimeToSysTime(lower); @@ -1885,74 +2183,87 @@ private void SetSelRange(DateTime lower, DateTime upper) { sa.wMonth2 = sys.wMonth; sa.wDayOfWeek2 = sys.wDayOfWeek; sa.wDay2 = sys.wDay; - UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.MCM_SETSELRANGE , 0, sa); + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.MCM_SETSELRANGE, 0, sa); } - if (changed) { + if (changed) + { OnDateChanged(new DateRangeEventArgs(lower, upper)); } } - private bool ShouldSerializeAnnuallyBoldedDates() { + private bool ShouldSerializeAnnuallyBoldedDates() + { return annualArrayOfDates.Count > 0; } - private bool ShouldSerializeBoldedDates() { + private bool ShouldSerializeBoldedDates() + { return arrayOfDates.Count > 0; } - private bool ShouldSerializeCalendarDimensions() { + private bool ShouldSerializeCalendarDimensions() + { return !dimensions.Equals(new Size(1, 1)); } - private bool ShouldSerializeTrailingForeColor() { + private bool ShouldSerializeTrailingForeColor() + { return !TrailingForeColor.Equals(DEFAULT_TRAILING_FORE_COLOR); } - private bool ShouldSerializeTitleForeColor() { + private bool ShouldSerializeTitleForeColor() + { return !TitleForeColor.Equals(DEFAULT_TITLE_FORE_COLOR); } - private bool ShouldSerializeTitleBackColor() { + private bool ShouldSerializeTitleBackColor() + { return !TitleBackColor.Equals(DEFAULT_TITLE_BACK_COLOR); } - private bool ShouldSerializeMonthlyBoldedDates() { + private bool ShouldSerializeMonthlyBoldedDates() + { return monthlyArrayOfDates.Count > 0; } /// /// Retrieves true if the maxDate should be persisted in code gen. /// - private bool ShouldSerializeMaxDate() { + private bool ShouldSerializeMaxDate() + { return maxDate != DateTimePicker.MaximumDateTime && maxDate != DateTime.MaxValue; } /// /// Retrieves true if the minDate should be persisted in code gen. /// - private bool ShouldSerializeMinDate() { + private bool ShouldSerializeMinDate() + { return minDate != DateTimePicker.MinimumDateTime && minDate != DateTime.MinValue; } /// /// Retrieves true if the selectionRange should be persisted in code gen. /// - private bool ShouldSerializeSelectionRange() { + private bool ShouldSerializeSelectionRange() + { return !DateTime.Equals(selectionEnd, selectionStart); } /// /// Retrieves true if the todayDate should be persisted in code gen. /// - private bool ShouldSerializeTodayDate() { + private bool ShouldSerializeTodayDate() + { return todayDateSet; } /// /// Returns a string representation for this control. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); return s + ", " + SelectionRange.ToString(); @@ -1961,7 +2272,8 @@ public override string ToString() { /// /// Forces month calendar to display the current set of bolded dates. /// - public void UpdateBoldedDates() { + public void UpdateBoldedDates() + { RecreateHandle(); } @@ -1971,27 +2283,34 @@ public void UpdateBoldedDates() { /// it will be set to null (running clock mode - the today date will be /// automatically updated). /// - private void UpdateTodayDate() { - if (IsHandleCreated) { + private void UpdateTodayDate() + { + if (IsHandleCreated) + { NativeMethods.SYSTEMTIME st = null; - if (todayDateSet) { + if (todayDateSet) + { st = DateTimePicker.DateTimeToSysTime(todayDate); } UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.MCM_SETTODAY, 0, st); } } - private void MarshaledUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs pref) { - try { + private void MarshaledUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs pref) + { + try + { //use begininvoke instead of invoke in case the destination thread is not processing messages. BeginInvoke(new UserPreferenceChangedEventHandler(this.UserPreferenceChanged), new object[] { sender, pref }); } catch (InvalidOperationException) { } //if the destination thread does not exist, don't send. } - private void UserPreferenceChanged(object sender, UserPreferenceChangedEventArgs pref) { - if (pref.Category == UserPreferenceCategory.Locale) { - // We need to recreate the monthcalendar handle when the locale changes, because + private void UserPreferenceChanged(object sender, UserPreferenceChangedEventArgs pref) + { + if (pref.Category == UserPreferenceCategory.Locale) + { + // We need to recreate the monthcalendar handle when the locale changes, because // the day names etc. are only updated on a handle recreate (comctl32 limitation). // RecreateHandle(); @@ -2001,19 +2320,20 @@ private void UserPreferenceChanged(object sender, UserPreferenceChangedEventArgs /// /// Handles the MCN_SELCHANGE notification /// - private void WmDateChanged(ref Message m) { + private void WmDateChanged(ref Message m) + { NativeMethods.NMSELCHANGE nmmcsc = (NativeMethods.NMSELCHANGE)m.GetLParam(typeof(NativeMethods.NMSELCHANGE)); DateTime start = selectionStart = DateTimePicker.SysTimeToDateTime(nmmcsc.stSelStart); DateTime end = selectionEnd = DateTimePicker.SysTimeToDateTime(nmmcsc.stSelEnd); AccessibilityNotifyClients(AccessibleEvents.NameChange, -1); AccessibilityNotifyClients(AccessibleEvents.ValueChange, -1); - + //subhag if (start.Ticks < minDate.Ticks || end.Ticks < minDate.Ticks) - SetSelRange(minDate,minDate); + SetSelRange(minDate, minDate); else if (start.Ticks > maxDate.Ticks || end.Ticks > maxDate.Ticks) - SetSelRange(maxDate,maxDate); + SetSelRange(maxDate, maxDate); //end subhag OnDateChanged(new DateRangeEventArgs(start, end)); } @@ -2021,7 +2341,8 @@ private void WmDateChanged(ref Message m) { /// /// Handles the MCN_GETDAYSTATE notification /// - private void WmDateBold(ref Message m) { + private void WmDateBold(ref Message m) + { NativeMethods.NMDAYSTATE nmmcds = (NativeMethods.NMDAYSTATE)m.GetLParam(typeof(NativeMethods.NMDAYSTATE)); DateTime start = DateTimePicker.SysTimeToDateTime(nmmcds.stStart); DateBoldEventArgs boldEvent = new DateBoldEventArgs(start, nmmcds.cDayState); @@ -2038,10 +2359,12 @@ private void WmDateBold(ref Message m) { /// Handles the MCN_VIEWCHANGE notification /// - private void WmCalViewChanged (ref Message m) { + private void WmCalViewChanged(ref Message m) + { NativeMethods.NMVIEWCHANGE nmmcvm = (NativeMethods.NMVIEWCHANGE)m.GetLParam(typeof(NativeMethods.NMVIEWCHANGE)); Debug.Assert(mcCurView == (NativeMethods.MONTCALENDAR_VIEW_MODE)nmmcvm.uOldView, "Calendar view mode is out of sync with native control"); - if (mcCurView != (NativeMethods.MONTCALENDAR_VIEW_MODE)nmmcvm.uNewView) { + if (mcCurView != (NativeMethods.MONTCALENDAR_VIEW_MODE)nmmcvm.uNewView) + { mcOldView = mcCurView; mcCurView = (NativeMethods.MONTCALENDAR_VIEW_MODE)nmmcvm.uNewView; @@ -2052,7 +2375,8 @@ private void WmCalViewChanged (ref Message m) { /// /// Handles the MCN_SELECT notification /// - private void WmDateSelected(ref Message m) { + private void WmDateSelected(ref Message m) + { NativeMethods.NMSELCHANGE nmmcsc = (NativeMethods.NMSELCHANGE)m.GetLParam(typeof(NativeMethods.NMSELCHANGE)); DateTime start = selectionStart = DateTimePicker.SysTimeToDateTime(nmmcsc.stSelStart); DateTime end = selectionEnd = DateTimePicker.SysTimeToDateTime(nmmcsc.stSelEnd); @@ -2062,9 +2386,9 @@ private void WmDateSelected(ref Message m) { //subhag if (start.Ticks < minDate.Ticks || end.Ticks < minDate.Ticks) - SetSelRange(minDate,minDate); + SetSelRange(minDate, minDate); else if (start.Ticks > maxDate.Ticks || end.Ticks > maxDate.Ticks) - SetSelRange(maxDate,maxDate); + SetSelRange(maxDate, maxDate); //end subhag OnDateSelected(new DateRangeEventArgs(start, end)); @@ -2074,7 +2398,8 @@ private void WmDateSelected(ref Message m) { /// /// Handles the WM_GETDLGCODE message /// - private void WmGetDlgCode(ref Message m) { + private void WmGetDlgCode(ref Message m) + { // The MonthCalendar does its own handling of arrow keys m.Result = (IntPtr)NativeMethods.DLGC_WANTARROWS; } @@ -2082,10 +2407,13 @@ private void WmGetDlgCode(ref Message m) { /// /// Handles the WM_COMMAND messages reflected from the parent control. /// - private void WmReflectCommand(ref Message m) { - if (m.HWnd == Handle) { + private void WmReflectCommand(ref Message m) + { + if (m.HWnd == Handle) + { NativeMethods.NMHDR nmhdr = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR)); - switch (nmhdr.code) { + switch (nmhdr.code) + { case NativeMethods.MCN_SELECT: WmDateSelected(ref m); break; @@ -2105,11 +2433,14 @@ private void WmReflectCommand(ref Message m) { /// /// Overrided wndProc /// - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { case Interop.WindowMessages.WM_LBUTTONDOWN: Focus(); - if (!ValidationCancelled) { + if (!ValidationCancelled) + { base.WndProc(ref m); } break; @@ -2134,14 +2465,16 @@ protected override void WndProc(ref Message m) { /// HitTestInfo is for informational purposes only; the user should not construct these objects, and /// cannot modify any of the members. /// - public sealed class HitTestInfo { - readonly Point point; - readonly HitArea hitArea; - readonly DateTime time; + public sealed class HitTestInfo + { + readonly Point point; + readonly HitArea hitArea; + readonly DateTime time; /// /// - internal HitTestInfo(Point pt, HitArea area, DateTime time) { + internal HitTestInfo(Point pt, HitArea area, DateTime time) + { this.point = pt; this.hitArea = area; this.time = time; @@ -2150,7 +2483,8 @@ internal HitTestInfo(Point pt, HitArea area, DateTime time) { /// /// This constructor is used when the DateTime member is invalid. /// - internal HitTestInfo(Point pt, HitArea area) { + internal HitTestInfo(Point pt, HitArea area) + { this.point = pt; this.hitArea = area; } @@ -2158,7 +2492,8 @@ internal HitTestInfo(Point pt, HitArea area) { /// /// The point that was hit-tested /// - public Point Point { + public Point Point + { get { return point; } } @@ -2166,7 +2501,8 @@ public Point Point { /// Output member that receives an enumeration value from System.Windows.Forms.MonthCalendar.HitArea /// representing the result of the hit-test operation. /// - public HitArea HitArea { + public HitArea HitArea + { get { return hitArea; } } @@ -2174,17 +2510,20 @@ public HitArea HitArea { /// The time information specific to the location that was hit-tested. This value /// will only be valid at certain values of hitArea. /// - public DateTime Time { + public DateTime Time + { get { return time; } } /// /// Determines whether a given HitArea should have a corresponding valid DateTime /// - internal static bool HitAreaHasValidDateTime(HitArea hitArea) { - switch (hitArea) { + internal static bool HitAreaHasValidDateTime(HitArea hitArea) + { + switch (hitArea) + { case HitArea.Date: - //case HitArea.DayOfWeek: comCtl does not provide a valid date + //case HitArea.DayOfWeek: comCtl does not provide a valid date case HitArea.WeekNumbers: return true; } @@ -2288,20 +2627,26 @@ public enum HitArea /// /// [System.Runtime.InteropServices.ComVisible(true)] - internal class MonthCalendarAccessibleObject : ControlAccessibleObject { + internal class MonthCalendarAccessibleObject : ControlAccessibleObject + { private MonthCalendar calendar; public MonthCalendarAccessibleObject(Control owner) - : base(owner) { - calendar = owner as MonthCalendar; + : base(owner) + { + calendar = owner as MonthCalendar; } - public override AccessibleRole Role { - get { - if (calendar != null) { + public override AccessibleRole Role + { + get + { + if (calendar != null) + { AccessibleRole role = calendar.AccessibleRole; - if (role != AccessibleRole.Default) { + if (role != AccessibleRole.Default) + { return role; } } @@ -2309,14 +2654,19 @@ public override AccessibleRole Role { } } - public override string Help { - get { + public override string Help + { + get + { var help = base.Help; - if (help != null) { + if (help != null) + { return help; } - else { - if (calendar != null) { + else + { + if (calendar != null) + { return calendar.GetType().Name + "(" + calendar.GetType().BaseType.Name + ")"; } } @@ -2324,40 +2674,54 @@ public override string Help { } } - public override string Name { - get { + public override string Name + { + get + { string name = base.Name; - if (name != null) { + if (name != null) + { return name; } - if (calendar != null) { + if (calendar != null) + { - if (calendar.mcCurView == NativeMethods.MONTCALENDAR_VIEW_MODE.MCMV_MONTH) { - if (System.DateTime.Equals(calendar.SelectionStart.Date, calendar.SelectionEnd.Date)) { + if (calendar.mcCurView == NativeMethods.MONTCALENDAR_VIEW_MODE.MCMV_MONTH) + { + if (System.DateTime.Equals(calendar.SelectionStart.Date, calendar.SelectionEnd.Date)) + { name = string.Format(SR.MonthCalendarSingleDateSelected, calendar.SelectionStart.ToLongDateString()); } - else { + else + { name = string.Format(SR.MonthCalendarRangeSelected, calendar.SelectionStart.ToLongDateString(), calendar.SelectionEnd.ToLongDateString()); } } - else if (this.calendar.mcCurView == NativeMethods.MONTCALENDAR_VIEW_MODE.MCMV_YEAR) { - if (System.DateTime.Equals(this.calendar.SelectionStart.Month, this.calendar.SelectionEnd.Month)) { + else if (this.calendar.mcCurView == NativeMethods.MONTCALENDAR_VIEW_MODE.MCMV_YEAR) + { + if (System.DateTime.Equals(this.calendar.SelectionStart.Month, this.calendar.SelectionEnd.Month)) + { name = string.Format(SR.MonthCalendarSingleDateSelected, calendar.SelectionStart.ToString("y")); } - else { + else + { name = string.Format(SR.MonthCalendarRangeSelected, calendar.SelectionStart.ToString("y"), calendar.SelectionEnd.ToString("y")); } } - else if (calendar.mcCurView == NativeMethods.MONTCALENDAR_VIEW_MODE.MCMV_DECADE) { - if (System.DateTime.Equals(calendar.SelectionStart.Year, calendar.SelectionEnd.Year)) { + else if (calendar.mcCurView == NativeMethods.MONTCALENDAR_VIEW_MODE.MCMV_DECADE) + { + if (System.DateTime.Equals(calendar.SelectionStart.Year, calendar.SelectionEnd.Year)) + { name = string.Format(SR.MonthCalendarSingleYearSelected, calendar.SelectionStart.ToString("yyyy")); } - else { + else + { name = string.Format(SR.MonthCalendarYearRangeSelected, calendar.SelectionStart.ToString("yyyy"), calendar.SelectionEnd.ToString("yyyy")); } } - else if (calendar.mcCurView == NativeMethods.MONTCALENDAR_VIEW_MODE.MCMV_CENTURY) { + else if (calendar.mcCurView == NativeMethods.MONTCALENDAR_VIEW_MODE.MCMV_CENTURY) + { name = string.Format(SR.MonthCalendarSingleDecadeSelected, calendar.SelectionStart.ToString("yyyy")); } } @@ -2365,41 +2729,54 @@ public override string Name { } } - public override string Value { - get { + public override string Value + { + get + { var value = string.Empty; - try { - if (calendar != null) { - if (calendar.mcCurView == NativeMethods.MONTCALENDAR_VIEW_MODE.MCMV_MONTH) { - if (System.DateTime.Equals(calendar.SelectionStart.Date, calendar.SelectionEnd.Date)) { + try + { + if (calendar != null) + { + if (calendar.mcCurView == NativeMethods.MONTCALENDAR_VIEW_MODE.MCMV_MONTH) + { + if (System.DateTime.Equals(calendar.SelectionStart.Date, calendar.SelectionEnd.Date)) + { value = calendar.SelectionStart.ToLongDateString(); } - else { + else + { value = string.Format("{0} - {1}", calendar.SelectionStart.ToLongDateString(), calendar.SelectionEnd.ToLongDateString()); } } - else if (this.calendar.mcCurView == NativeMethods.MONTCALENDAR_VIEW_MODE.MCMV_YEAR) { - if (System.DateTime.Equals(this.calendar.SelectionStart.Month, this.calendar.SelectionEnd.Month)) { + else if (this.calendar.mcCurView == NativeMethods.MONTCALENDAR_VIEW_MODE.MCMV_YEAR) + { + if (System.DateTime.Equals(this.calendar.SelectionStart.Month, this.calendar.SelectionEnd.Month)) + { value = calendar.SelectionStart.ToString("y"); } - else { + else + { value = string.Format("{0} - {1}", calendar.SelectionStart.ToString("y"), calendar.SelectionEnd.ToString("y")); } } - else { + else + { value = string.Format("{0} - {1}", calendar.SelectionRange.Start.ToString(), calendar.SelectionRange.End.ToString()); } } } - catch { + catch + { value = base.Value; } return value; } - set { + set + { base.Value = value; } - } + } } } // end class MonthCalendar diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MouseButtons.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MouseButtons.cs index a3e4672e186..d7abc3ccb99 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MouseButtons.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MouseButtons.cs @@ -31,10 +31,10 @@ public enum MouseButtons /// /// The middle mouse button was pressed. /// - Middle = 0x00400000, - - XButton1 = 0x00800000, - + Middle = 0x00400000, + + XButton1 = 0x00800000, + XButton2 = 0x01000000, } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs index 34dbb1ff2c7..83b13dc5377 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs @@ -30,7 +30,8 @@ namespace System.Windows.Forms /// and a window procedure. The class automatically manages window class creation and registration. /// /// - public class NativeWindow : MarshalByRefObject, IWin32Window { + public class NativeWindow : MarshalByRefObject, IWin32Window + { #if DEBUG private static readonly BooleanSwitch AlwaysUseNormalWndProc = new BooleanSwitch("AlwaysUseNormalWndProc", "Skips checking for the debugger when choosing the debuggable WndProc handler"); #endif @@ -44,10 +45,10 @@ public class NativeWindow : MarshalByRefObject, IWin32Window { private readonly static int[] primes = { 11,17,23,29,37,47,59,71,89,107,131,163,197,239,293,353,431,521,631,761,919, 1103,1327,1597,1931,2333,2801,3371,4049,4861,5839,7013,8419,10103,12143,14591, - 17519,21023,25229,30293,36353,43627,52361,62851,75431,90523, 108631, 130363, + 17519,21023,25229,30293,36353,43627,52361,62851,75431,90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, - 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, - 4999559, 5999471, 7199369 + 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, + 4999559, 5999471, 7199369 }; const int InitializedFlags = 0x01; @@ -82,8 +83,8 @@ public class NativeWindow : MarshalByRefObject, IWin32Window { private static object createWindowSyncObject = new object(); #if DEBUG - AppDomain handleCreatedIn = null; - string subclassStatus = "None"; + AppDomain handleCreatedIn = null; + string subclassStatus = "None"; #endif IntPtr handle; NativeMethods.WndProc windowProc; @@ -98,7 +99,8 @@ public class NativeWindow : MarshalByRefObject, IWin32Window { CommonUnsafeNativeMethods.TryGetThreadDpiAwarenessContext() : DpiAwarenessContext.DPI_AWARENESS_CONTEXT_UNSPECIFIED; - static NativeWindow() { + static NativeWindow() + { EventHandler shutdownHandler = new EventHandler(OnShutdown); AppDomain.CurrentDomain.ProcessExit += shutdownHandler; AppDomain.CurrentDomain.DomainUnload += shutdownHandler; @@ -110,7 +112,8 @@ static NativeWindow() { hashBuckets = new HandleBucket[hashSize]; hashLoadSize = (int)(hashLoadFactor * hashSize); - if (hashLoadSize >= hashSize) { + if (hashLoadSize >= hashSize) + { hashLoadSize = hashSize - 1; } @@ -119,15 +122,18 @@ static NativeWindow() { hashForHandleId = new Dictionary(); } - public NativeWindow() { + public NativeWindow() + { weakThisPtr = new WeakReference(this); } /// /// Cache window DpiContext awareness information that helps to create handle with right context at the later time. /// - internal DpiAwarenessContext DpiAwarenessContext { - get { + internal DpiAwarenessContext DpiAwarenessContext + { + get + { return windowDpiAwarenessContext; } } @@ -135,7 +141,8 @@ internal DpiAwarenessContext DpiAwarenessContext { /// /// Override's the base object's finalize method. /// - ~NativeWindow() { + ~NativeWindow() + { ForceExitMessageLoop(); } @@ -144,48 +151,57 @@ internal DpiAwarenessContext DpiAwarenessContext { /// can perform the exact same code without further changes. If you make changes to the finalizer, /// change this method -- try not to change NativeWindow's finalizer. /// - internal void ForceExitMessageLoop() { + internal void ForceExitMessageLoop() + { IntPtr h; bool ownedHandle; // - lock (this) { + lock (this) + { h = handle; ownedHandle = ownHandle; } - if (handle != IntPtr.Zero) { + if (handle != IntPtr.Zero) + { //now, before we set handle to zero and finish the finalizer, let's send // a WM_NULL to the window. Why? Because if the main ui thread is INSIDE // the wndproc for this control during our unsubclass, then we could AV // when control finally reaches us. - if (UnsafeNativeMethods.IsWindow(new HandleRef(null, handle))) { + if (UnsafeNativeMethods.IsWindow(new HandleRef(null, handle))) + { int lpdwProcessId; //unused int id = SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(null, handle), out lpdwProcessId); Application.ThreadContext ctx = Application.ThreadContext.FromId(id); IntPtr threadHandle = (ctx == null ? IntPtr.Zero : ctx.GetHandle()); - if (threadHandle != IntPtr.Zero) { + if (threadHandle != IntPtr.Zero) + { int exitCode = 0; SafeNativeMethods.GetExitCodeThread(new HandleRef(null, threadHandle), out exitCode); - if (!AppDomain.CurrentDomain.IsFinalizingForUnload() && exitCode == NativeMethods.STATUS_PENDING) { + if (!AppDomain.CurrentDomain.IsFinalizingForUnload() && exitCode == NativeMethods.STATUS_PENDING) + { IntPtr result; if (UnsafeNativeMethods.SendMessageTimeout(new HandleRef(null, handle), NativeMethods.WM_UIUNSUBCLASS, IntPtr.Zero, IntPtr.Zero, - UnsafeNativeMethods.SMTO_ABORTIFHUNG, 100, out result) == IntPtr.Zero) { + UnsafeNativeMethods.SMTO_ABORTIFHUNG, 100, out result) == IntPtr.Zero) + { //Debug.Fail("unable to ping HWND:" + handle.ToString() + " during finalization"); } } } } - if (handle != IntPtr.Zero) { + if (handle != IntPtr.Zero) + { //if the dest thread is gone, it should be safe to unsubclass here. ReleaseHandle(true); } } - if (h != IntPtr.Zero && ownedHandle) { + if (h != IntPtr.Zero && ownedHandle) + { // If we owned the handle, post a // WM_CLOSE to get rid of it. // @@ -196,8 +212,10 @@ internal void ForceExitMessageLoop() { /// /// Indicates whether a window handle was created & is being tracked. /// - internal static bool AnyHandleCreated { - get { + internal static bool AnyHandleCreated + { + get + { return anyHandleCreated; } } @@ -207,8 +225,10 @@ internal static bool AnyHandleCreated { /// Gets the handle for this window. /// /// - public IntPtr Handle { - get { + public IntPtr Handle + { + get + { #if DEBUG Debug.Assert(handle == IntPtr.Zero || (handleCreatedIn != null && handleCreatedIn == AppDomain.CurrentDomain), "Attempt to access a handle created in a different domain"); @@ -233,9 +253,11 @@ public IntPtr Handle { /// /// This should be public, but it is way too late for that. /// - internal NativeWindow PreviousWindow { + internal NativeWindow PreviousWindow + { [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] - get { + get + { return previousWindow; } } @@ -244,14 +266,18 @@ internal NativeWindow PreviousWindow { /// Helper method that returns a static value for the /// unmanaged DefWindowProc call. /// - internal static IntPtr UserDefindowProc { - get { + internal static IntPtr UserDefindowProc + { + get + { return userDefWindowProc; } } - private static int WndProcFlags { - get { + private static int WndProcFlags + { + get + { // upcast for easy bit masking... // int intWndProcFlags = wndProcFlags; @@ -260,35 +286,45 @@ private static int WndProcFlags { // DebuggableCallback instead; this callback has no try/catch around it // so exceptions go to the debugger. // - if (intWndProcFlags == 0) { + if (intWndProcFlags == 0) + { Debug.WriteLineIf(WndProcChoice.TraceVerbose, "Init wndProcFlags"); Debug.Indent(); - if (userSetProcFlags != 0) { + if (userSetProcFlags != 0) + { intWndProcFlags = userSetProcFlags; } - else if (userSetProcFlagsForApp != 0) { + else if (userSetProcFlagsForApp != 0) + { intWndProcFlags = userSetProcFlagsForApp; } - else if (!Application.CustomThreadExceptionHandlerAttached) { - if (Debugger.IsAttached) { + else if (!Application.CustomThreadExceptionHandlerAttached) + { + if (Debugger.IsAttached) + { Debug.WriteLineIf(WndProcChoice.TraceVerbose, "Debugger is attached, using debuggable WndProc"); intWndProcFlags |= UseDebuggableWndProc; } - else { + else + { intWndProcFlags = AdjustWndProcFlagsFromRegistry(intWndProcFlags); Debug.WriteLineIf(WndProcChoice.TraceVerbose, "After reg check 0x" + intWndProcFlags.ToString("X", CultureInfo.InvariantCulture)); - if ((intWndProcFlags & DebuggerPresent) != 0) { + if ((intWndProcFlags & DebuggerPresent) != 0) + { Debug.WriteLineIf(WndProcChoice.TraceVerbose, "Debugger present"); intWndProcFlags = AdjustWndProcFlagsFromMetadata(intWndProcFlags); - if ((intWndProcFlags & AssemblyIsDebuggable) != 0) { - if ((intWndProcFlags & LoadConfigSettings) != 0) { + if ((intWndProcFlags & AssemblyIsDebuggable) != 0) + { + if ((intWndProcFlags & LoadConfigSettings) != 0) + { intWndProcFlags = AdjustWndProcFlagsFromConfig(intWndProcFlags); Debug.WriteLineIf(WndProcChoice.TraceVerbose, "After config check 0x" + intWndProcFlags.ToString("X", CultureInfo.InvariantCulture)); } - else { + else + { intWndProcFlags |= UseDebuggableWndProc; } } @@ -299,7 +335,8 @@ private static int WndProcFlags { } #if DEBUG - if (AlwaysUseNormalWndProc.Enabled) { + if (AlwaysUseNormalWndProc.Enabled) + { Debug.WriteLineIf(WndProcChoice.TraceVerbose, "Stripping debuggablewndproc due to AlwaysUseNormalWndProc switch"); intWndProcFlags &= ~UseDebuggableWndProc; } @@ -314,9 +351,11 @@ private static int WndProcFlags { } } - internal static bool WndProcShouldBeDebuggable { + internal static bool WndProcShouldBeDebuggable + { [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] - get { + get + { return (WndProcFlags & UseDebuggableWndProc) != 0; } } @@ -324,13 +363,16 @@ internal static bool WndProcShouldBeDebuggable { /// /// Inserts an entry into this hashtable. /// - private static void AddWindowToTable(IntPtr handle, NativeWindow window) { + private static void AddWindowToTable(IntPtr handle, NativeWindow window) + { Debug.Assert(handle != IntPtr.Zero, "Should never insert a zero handle into the hash"); - lock (internalSyncObject) { + lock (internalSyncObject) + { - if (handleCount >= hashLoadSize) { + if (handleCount >= hashLoadSize) + { ExpandTable(); } @@ -352,7 +394,8 @@ private static void AddWindowToTable(IntPtr handle, NativeWindow window) { GCHandle root = GCHandle.Alloc(window, GCHandleType.Weak); - do { + do + { int bucketNumber = (int)(seed % (uint)hashBuckets.Length); if (emptySlotNumber == -1 && (hashBuckets[bucketNumber].handle == new IntPtr(-1)) && (hashBuckets[bucketNumber].hash_coll < 0)) @@ -361,9 +404,11 @@ private static void AddWindowToTable(IntPtr handle, NativeWindow window) { //We need to check if the collision bit is set because we have the possibility where the first //item in the hash-chain has been deleted. if ((hashBuckets[bucketNumber].handle == IntPtr.Zero) || - (hashBuckets[bucketNumber].handle == new IntPtr(-1) && ((hashBuckets[bucketNumber].hash_coll & unchecked(0x80000000)) == 0))) { + (hashBuckets[bucketNumber].handle == new IntPtr(-1) && ((hashBuckets[bucketNumber].hash_coll & unchecked(0x80000000)) == 0))) + { - if (emptySlotNumber != -1) { // Reuse slot + if (emptySlotNumber != -1) + { // Reuse slot bucketNumber = emptySlotNumber; } @@ -382,10 +427,13 @@ private static void AddWindowToTable(IntPtr handle, NativeWindow window) { // If there is an existing window in this slot, reuse it. Be sure to hook up the previous and next // window pointers so we can get back to the right window. // - if (((hashBuckets[bucketNumber].hash_coll & 0x7FFFFFFF) == hashcode) && handle == hashBuckets[bucketNumber].handle) { + if (((hashBuckets[bucketNumber].hash_coll & 0x7FFFFFFF) == hashcode) && handle == hashBuckets[bucketNumber].handle) + { GCHandle prevWindow = hashBuckets[bucketNumber].window; - if (prevWindow.IsAllocated) { - if (prevWindow.Target != null) { + if (prevWindow.IsAllocated) + { + if (prevWindow.Target != null) + { window.previousWindow = ((NativeWindow)prevWindow.Target); Debug.Assert(window.previousWindow.nextWindow == null, "Last window in chain should have null next ptr"); window.previousWindow.nextWindow = window; @@ -396,7 +444,8 @@ private static void AddWindowToTable(IntPtr handle, NativeWindow window) { #if DEBUG string ownerString = string.Empty; NativeWindow w = window; - while(w != null) { + while (w != null) + { ownerString += ("->" + w.ToString()); w = w.previousWindow; } @@ -405,7 +454,8 @@ private static void AddWindowToTable(IntPtr handle, NativeWindow window) { return; } - if (emptySlotNumber == -1) {// We don't need to set the collision bit here since we already have an empty slot + if (emptySlotNumber == -1) + {// We don't need to set the collision bit here since we already have an empty slot hashBuckets[bucketNumber].hash_coll |= unchecked((int)0x80000000); } @@ -413,13 +463,14 @@ private static void AddWindowToTable(IntPtr handle, NativeWindow window) { } while (++ntry < hashBuckets.Length); - if (emptySlotNumber != -1) { + if (emptySlotNumber != -1) + { // Always set the hash_coll last because there may be readers // reading the table right now on other threads. hashBuckets[emptySlotNumber].window = root; hashBuckets[emptySlotNumber].handle = handle; #if DEBUG - hashBuckets[emptySlotNumber].owner = window.ToString(); + hashBuckets[emptySlotNumber].owner = window.ToString(); #endif hashBuckets[emptySlotNumber].hash_coll |= (int)hashcode; handleCount++; @@ -436,7 +487,8 @@ private static void AddWindowToTable(IntPtr handle, NativeWindow window) { /// /// Inserts an entry into this ID hashtable. /// - internal static void AddWindowToIDTable(object wrapper, IntPtr handle) { + internal static void AddWindowToIDTable(object wrapper, IntPtr handle) + { NativeWindow.hashForIdHandle[NativeWindow.globalID] = handle; NativeWindow.hashForHandleId[handle] = NativeWindow.globalID; UnsafeNativeMethods.SetWindowLong(new HandleRef(wrapper, handle), NativeMethods.GWL_ID, new HandleRef(wrapper, (IntPtr)globalID)); @@ -449,14 +501,17 @@ internal static void AddWindowToIDTable(object wrapper, IntPtr handle) { // due to its usage of the type WindowsFormsSection // [MethodImplAttribute(MethodImplOptions.NoInlining)] - private static int AdjustWndProcFlagsFromConfig(int wndProcFlags) { - if (WindowsFormsSection.GetSection().JitDebugging) { + private static int AdjustWndProcFlagsFromConfig(int wndProcFlags) + { + if (WindowsFormsSection.GetSection().JitDebugging) + { wndProcFlags |= UseDebuggableWndProc; } return wndProcFlags; } - private static int AdjustWndProcFlagsFromRegistry(int wndProcFlags) { + private static int AdjustWndProcFlagsFromRegistry(int wndProcFlags) + { // This is the enum used to define the meaning of the debug flag... // @@ -481,19 +536,24 @@ enum DebuggerLaunchSetting Debug.Assert(wndProcFlags == 0x00, "Re-entrancy into IsDebuggerInstalled()"); RegistryKey debugKey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\.NETFramework"); - if (debugKey == null) { + if (debugKey == null) + { Debug.WriteLineIf(WndProcChoice.TraceVerbose, ".NETFramework key not found"); return wndProcFlags; } - try { + try + { object value = debugKey.GetValue("DbgJITDebugLaunchSetting"); - if (value != null) { + if (value != null) + { Debug.WriteLineIf(WndProcChoice.TraceVerbose, "DbgJITDebugLaunchSetting value found, debugger is installed"); int dbgJit = 0; - try { + try + { dbgJit = (int)value; } - catch (InvalidCastException) { + catch (InvalidCastException) + { // If the value isn't a DWORD, then we will // continue to use the non-debuggable wndproc // @@ -504,19 +564,22 @@ enum DebuggerLaunchSetting // anything else, we should flag that the debugger // will catch unhandled exceptions // - if (dbgJit != 1) { + if (dbgJit != 1) + { wndProcFlags |= DebuggerPresent; wndProcFlags |= LoadConfigSettings; } } - else if (debugKey.GetValue("DbgManagedDebugger") != null) { + else if (debugKey.GetValue("DbgManagedDebugger") != null) + { //if there is a debugger installed, check the config files to decide //whether to allow JIT debugging. wndProcFlags |= DebuggerPresent; wndProcFlags |= LoadConfigSettings; } } - finally { + finally + { debugKey.Close(); } @@ -524,17 +587,23 @@ enum DebuggerLaunchSetting return wndProcFlags; } - static int AdjustWndProcFlagsFromMetadata(int wndProcFlags) { - if ((wndProcFlags & DebuggerPresent) != 0) { + static int AdjustWndProcFlagsFromMetadata(int wndProcFlags) + { + if ((wndProcFlags & DebuggerPresent) != 0) + { Debug.WriteLineIf(WndProcChoice.TraceVerbose, "Debugger present, checking for debuggable entry assembly"); Assembly entry = Assembly.GetEntryAssembly(); - if (entry != null) { - if (Attribute.IsDefined(entry, typeof(DebuggableAttribute))) { + if (entry != null) + { + if (Attribute.IsDefined(entry, typeof(DebuggableAttribute))) + { Debug.WriteLineIf(WndProcChoice.TraceVerbose, "Debuggable attribute on assembly"); Attribute[] attr = Attribute.GetCustomAttributes(entry, typeof(DebuggableAttribute)); - if (attr.Length > 0) { + if (attr.Length > 0) + { DebuggableAttribute dbg = (DebuggableAttribute)attr[0]; - if (dbg.IsJITTrackingEnabled) { + if (dbg.IsJITTrackingEnabled) + { // Only if the assembly is really setup for debugging // does it really make sense to enable the jitDebugging // @@ -554,13 +623,16 @@ static int AdjustWndProcFlagsFromMetadata(int wndProcFlags) { /// window. /// /// - public void AssignHandle(IntPtr handle) { + public void AssignHandle(IntPtr handle) + { AssignHandle(handle, true); } - internal void AssignHandle(IntPtr handle, bool assignUniqueID) { - lock (this) { + internal void AssignHandle(IntPtr handle, bool assignUniqueID) + { + lock (this) + { CheckReleased(); Debug.Assert(handle != IntPtr.Zero, "handle is 0"); #if DEBUG @@ -568,11 +640,13 @@ internal void AssignHandle(IntPtr handle, bool assignUniqueID) { #endif this.handle = handle; - if (userDefWindowProc == IntPtr.Zero) { + if (userDefWindowProc == IntPtr.Zero) + { string defproc = "DefWindowProcW"; userDefWindowProc = UnsafeNativeMethods.GetProcAddress(new HandleRef(null, UnsafeNativeMethods.GetModuleHandle("user32.dll")), defproc); - if (userDefWindowProc == IntPtr.Zero) { + if (userDefWindowProc == IntPtr.Zero) + { throw new Win32Exception(); } } @@ -581,11 +655,13 @@ internal void AssignHandle(IntPtr handle, bool assignUniqueID) { Debug.Assert(defWindowProc != IntPtr.Zero, "defWindowProc is 0"); - if (WndProcShouldBeDebuggable) { + if (WndProcShouldBeDebuggable) + { Debug.WriteLineIf(WndProcChoice.TraceVerbose, "Using debuggable wndproc"); windowProc = new NativeMethods.WndProc(this.DebuggableCallback); } - else { + else + { Debug.WriteLineIf(WndProcChoice.TraceVerbose, "Using normal wndproc"); windowProc = new NativeMethods.WndProc(this.Callback); } @@ -597,12 +673,14 @@ internal void AssignHandle(IntPtr handle, bool assignUniqueID) { Debug.Assert(defWindowProc != windowProcPtr, "Uh oh! Subclassed ourselves!!!"); if (assignUniqueID && (unchecked((int)((long)UnsafeNativeMethods.GetWindowLong(new HandleRef(this, handle), NativeMethods.GWL_STYLE))) & NativeMethods.WS_CHILD) != 0 && - unchecked((int)((long)UnsafeNativeMethods.GetWindowLong(new HandleRef(this, handle), NativeMethods.GWL_ID))) == 0) { + unchecked((int)((long)UnsafeNativeMethods.GetWindowLong(new HandleRef(this, handle), NativeMethods.GWL_ID))) == 0) + { UnsafeNativeMethods.SetWindowLong(new HandleRef(this, handle), NativeMethods.GWL_ID, new HandleRef(this, handle)); } - if (suppressedGC) { + if (suppressedGC) + { GC.ReRegisterForFinalize(this); suppressedGC = false; } @@ -617,27 +695,35 @@ internal void AssignHandle(IntPtr handle, bool assignUniqueID) { /// in a Message object and invokes the wndProc() method. A WM_NCDESTROY /// message automatically causes the releaseHandle() method to be called. /// - private IntPtr Callback(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam) { + private IntPtr Callback(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam) + { // Note: if you change this code be sure to change the // corresponding code in DebuggableCallback below! Message m = Message.Create(hWnd, msg, wparam, lparam); - try { - if (weakThisPtr.IsAlive && weakThisPtr.Target != null) { + try + { + if (weakThisPtr.IsAlive && weakThisPtr.Target != null) + { WndProc(ref m); } - else { + else + { DefWndProc(ref m); } } - catch (Exception e) { + catch (Exception e) + { OnThreadException(e); } - finally { - if (msg == Interop.WindowMessages.WM_NCDESTROY) ReleaseHandle(false); - if (msg == NativeMethods.WM_UIUNSUBCLASS) ReleaseHandle(true); + finally + { + if (msg == Interop.WindowMessages.WM_NCDESTROY) + ReleaseHandle(false); + if (msg == NativeMethods.WM_UIUNSUBCLASS) + ReleaseHandle(true); } return m.Result; @@ -646,8 +732,10 @@ private IntPtr Callback(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam) { /// /// Raises an exception if the window handle is not zero. /// - private void CheckReleased() { - if (handle != IntPtr.Zero) { + private void CheckReleased() + { + if (handle != IntPtr.Zero) + { throw new InvalidOperationException(SR.HandleAlreadyExists); } } @@ -662,17 +750,21 @@ private void CheckReleased() { // The call to UnsafeNativeMethods.CreateWindowEx is actually an interop call... System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Interoperability", "CA1404:CallGetLastErrorImmediatelyAfterPInvoke") ] - public virtual void CreateHandle(CreateParams cp) { + public virtual void CreateHandle(CreateParams cp) + { - lock (this) { + lock (this) + { CheckReleased(); WindowClass windowClass = WindowClass.Create(cp.ClassName, cp.ClassStyle); - lock (createWindowSyncObject) { + lock (createWindowSyncObject) + { // The CLR will sometimes pump messages while we're waiting on the lock. // If a message comes through (say a WM_ACTIVATE for the parent) which // causes the handle to be created, we can try to create the handle twice // for NativeWindow. Check the handle again t avoid this. - if (this.handle != IntPtr.Zero) { + if (this.handle != IntPtr.Zero) + { return; } windowClass.targetWindow = this; @@ -681,7 +773,8 @@ public virtual void CreateHandle(CreateParams cp) { // Parking window dpi awarness context need to match with dpi awarenss context of control being // parented to this parkign window. Otherwise, reparenting of control will fail. - using (DpiHelper.EnterDpiAwarenessScope(this.windowDpiAwarenessContext)) { + using (DpiHelper.EnterDpiAwarenessScope(this.windowDpiAwarenessContext)) + { IntPtr modHandle = UnsafeNativeMethods.GetModuleHandle(null); // Older versions of Windows AV rather than returning E_OUTOFMEMORY. @@ -702,7 +795,8 @@ public virtual void CreateHandle(CreateParams cp) { lastWin32Error = Marshal.GetLastWin32Error(); } - catch (NullReferenceException e) { + catch (NullReferenceException e) + { throw new OutOfMemoryException(SR.ErrorCreatingHandle, e); } } @@ -710,7 +804,8 @@ public virtual void CreateHandle(CreateParams cp) { Debug.WriteLineIf(CoreSwitches.PerfTrack.Enabled, "Handle created of type '" + cp.ClassName + "' with caption '" + cp.Caption + "' from NativeWindow of type '" + GetType().FullName + "'"); - if (createResult == IntPtr.Zero) { + if (createResult == IntPtr.Zero) + { throw new Win32Exception(lastWin32Error, SR.ErrorCreatingHandle); } ownHandle = true; @@ -725,24 +820,31 @@ public virtual void CreateHandle(CreateParams cp) { /// in a Message object and invokes the wndProc() method. A WM_NCDESTROY /// message automatically causes the releaseHandle() method to be called. /// - private IntPtr DebuggableCallback(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam) { + private IntPtr DebuggableCallback(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam) + { // Note: if you change this code be sure to change the // corresponding code in Callback above! Message m = Message.Create(hWnd, msg, wparam, lparam); - try { - if (weakThisPtr.IsAlive && weakThisPtr.Target != null) { + try + { + if (weakThisPtr.IsAlive && weakThisPtr.Target != null) + { WndProc(ref m); } - else { + else + { DefWndProc(ref m); } } - finally { - if (msg == Interop.WindowMessages.WM_NCDESTROY) ReleaseHandle(false); - if (msg == NativeMethods.WM_UIUNSUBCLASS) ReleaseHandle(true); + finally + { + if (msg == Interop.WindowMessages.WM_NCDESTROY) + ReleaseHandle(false); + if (msg == NativeMethods.WM_UIUNSUBCLASS) + ReleaseHandle(true); } return m.Result; @@ -752,9 +854,12 @@ private IntPtr DebuggableCallback(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lp /// Invokes the default window procedure associated with this Window. It is /// an error to call this method when the Handle property is zero. /// - public void DefWndProc(ref Message m) { - if (previousWindow == null) { - if (defWindowProc == IntPtr.Zero) { + public void DefWndProc(ref Message m) + { + if (previousWindow == null) + { + if (defWindowProc == IntPtr.Zero) + { #if DEBUG Debug.Fail("Can't find a default window procedure for message " + m.ToString() + " on class " + GetType().Name + " subclass status: " + subclassStatus); @@ -768,7 +873,8 @@ public void DefWndProc(ref Message m) { } m.Result = UnsafeNativeMethods.CallWindowProc(defWindowProc, m.HWnd, m.Msg, m.WParam, m.LParam); } - else { + else + { Debug.Assert(previousWindow != this, "Looping in our linked list"); m.Result = previousWindow.Callback(m.HWnd, m.Msg, m.WParam, m.LParam); } @@ -780,11 +886,15 @@ public void DefWndProc(ref Message m) { /// handle associated with this window. /// /// - public virtual void DestroyHandle() { + public virtual void DestroyHandle() + { // - lock (this) { - if (handle != IntPtr.Zero) { - if (!UnsafeNativeMethods.DestroyWindow(new HandleRef(this, handle))) { + lock (this) + { + if (handle != IntPtr.Zero) + { + if (!UnsafeNativeMethods.DestroyWindow(new HandleRef(this, handle))) + { UnSubclass(); //then post a close and let it do whatever it needs to do on its own. UnsafeNativeMethods.PostMessage(new HandleRef(this, handle), Interop.WindowMessages.WM_CLOSE, 0, 0); @@ -810,7 +920,8 @@ public virtual void DestroyHandle() { /// in the hashtable are redistributed into the new buckets using the cached /// hashcodes. /// - private static void ExpandTable() { + private static void ExpandTable() + { // Allocate new Array int oldhashsize = hashBuckets.Length; @@ -824,19 +935,23 @@ private static void ExpandTable() { // rehash table into new buckets int nb; - for (nb = 0; nb < oldhashsize; nb++) { + for (nb = 0; nb < oldhashsize; nb++) + { HandleBucket oldb = hashBuckets[nb]; - if ((oldb.handle != IntPtr.Zero) && (oldb.handle != new IntPtr(-1))) { + if ((oldb.handle != IntPtr.Zero) && (oldb.handle != new IntPtr(-1))) + { // Now re-fit this entry into the table // uint seed = (uint)oldb.hash_coll & 0x7FFFFFFF; uint incr = (uint)(1 + (((seed >> 5) + 1) % ((uint)newBuckets.Length - 1))); - do { + do + { int bucketNumber = (int)(seed % (uint)newBuckets.Length); - if ((newBuckets[bucketNumber].handle == IntPtr.Zero) || (newBuckets[bucketNumber].handle == new IntPtr(-1))) { + if ((newBuckets[bucketNumber].handle == IntPtr.Zero) || (newBuckets[bucketNumber].handle == new IntPtr(-1))) + { newBuckets[bucketNumber].window = oldb.window; newBuckets[bucketNumber].handle = oldb.handle; newBuckets[bucketNumber].hash_coll |= oldb.hash_coll & 0x7FFFFFFF; @@ -852,7 +967,8 @@ private static void ExpandTable() { hashBuckets = newBuckets; hashLoadSize = (int)(hashLoadFactor * hashsize); - if (hashLoadSize >= hashsize) { + if (hashLoadSize >= hashsize) + { hashLoadSize = hashsize - 1; } } @@ -864,8 +980,10 @@ private static void ExpandTable() { /// /// [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] - public static NativeWindow FromHandle(IntPtr handle) { - if (handle != IntPtr.Zero && handleCount > 0) { + public static NativeWindow FromHandle(IntPtr handle) + { + if (handle != IntPtr.Zero && handleCount > 0) + { return GetWindowFromTable(handle); } return null; @@ -875,32 +993,43 @@ public static NativeWindow FromHandle(IntPtr handle) { /// Calculates a prime number of at least minSize using a static table, and /// if we overflow it, we calculate directly. /// - private static int GetPrime(int minSize) { - if (minSize < 0) { + private static int GetPrime(int minSize) + { + if (minSize < 0) + { Debug.Fail("NativeWindow hashtable capacity overflow"); throw new OutOfMemoryException(); } - for (int i = 0; i < primes.Length; i++) { + for (int i = 0; i < primes.Length; i++) + { int size = primes[i]; - if (size >= minSize) return size; + if (size >= minSize) + return size; } //outside of our predefined table. //compute the hard way. - for (int j = ((minSize - 2) | 1); j < int.MaxValue; j += 2) { + for (int j = ((minSize - 2) | 1); j < int.MaxValue; j += 2) + { bool prime = true; - if ((j & 1) != 0) { + if ((j & 1) != 0) + { int target = (int)Math.Sqrt(j); - for (int divisor = 3; divisor < target; divisor += 2) { - if ((j % divisor) == 0) { + for (int divisor = 3; divisor < target; divisor += 2) + { + if ((j % divisor) == 0) + { prime = false; break; } } - if (prime) return j; + if (prime) + return j; } - else { - if (j == 2) { + else + { + if (j == 2) + { return j; } } @@ -912,7 +1041,8 @@ private static int GetPrime(int minSize) { /// Returns the native window for the given handle, or null if /// the handle is not in our hash table. /// - private static NativeWindow GetWindowFromTable(IntPtr handle) { + private static NativeWindow GetWindowFromTable(IntPtr handle) + { Debug.Assert(handle != IntPtr.Zero, "Zero handles cannot be stored in the table"); @@ -924,14 +1054,18 @@ private static NativeWindow GetWindowFromTable(IntPtr handle) { uint hashcode = InitHash(handle, buckets.Length, out seed, out incr); HandleBucket b; - do { + do + { int bucketNumber = (int)(seed % (uint)buckets.Length); b = buckets[bucketNumber]; - if (b.handle == IntPtr.Zero) { + if (b.handle == IntPtr.Zero) + { return null; } - if (((b.hash_coll & 0x7FFFFFFF) == hashcode) && handle == b.handle) { - if (b.window.IsAllocated) { + if (((b.hash_coll & 0x7FFFFFFF) == hashcode) && handle == b.handle) + { + if (b.window.IsAllocated) + { return (NativeWindow)b.window.Target; } } @@ -941,9 +1075,11 @@ private static NativeWindow GetWindowFromTable(IntPtr handle) { return null; } - internal IntPtr GetHandleFromID(short id) { + internal IntPtr GetHandleFromID(short id) + { IntPtr handle; - if (NativeWindow.hashForIdHandle == null || !NativeWindow.hashForIdHandle.TryGetValue(id, out handle)) { + if (NativeWindow.hashForIdHandle == null || !NativeWindow.hashForIdHandle.TryGetValue(id, out handle)) + { handle = IntPtr.Zero; } @@ -956,7 +1092,8 @@ internal IntPtr GetHandleFromID(short id) { /// 'incr' is h2(key, hashSize). Callers of this function should /// add 'incr' each time through a loop. /// - private static uint InitHash(IntPtr handle, int hashsize, out uint seed, out uint incr) { + private static uint InitHash(IntPtr handle, int hashsize, out uint seed, out uint incr) + { // Hashcode must be positive. Also, we must not use the sign bit, since // that is used for the collision bit. uint hashcode = ((uint)handle.GetHashCode()) & 0x7FFFFFFF; @@ -976,7 +1113,8 @@ private static uint InitHash(IntPtr handle, int hashsize, out uint seed, out uin /// window is changed. /// /// - protected virtual void OnHandleChange() { + protected virtual void OnHandleChange() + { } /// @@ -988,7 +1126,8 @@ protected virtual void OnHandleChange() { /// we move the class and window procs to DefWndProc /// [PrePrepareMethod] - private static void OnShutdown(object sender, EventArgs e) { + private static void OnShutdown(object sender, EventArgs e) + { // If we still have windows allocated, we must sling them to userDefWindowProc // or else they will AV if they get a message after the managed code has been @@ -997,14 +1136,18 @@ private static void OnShutdown(object sender, EventArgs e) { // we cannot call DestroyWindow because this API will fail if called from // an incorrect thread. // - if (handleCount > 0) { + if (handleCount > 0) + { Debug.Assert(userDefWindowProc != IntPtr.Zero, "We have active windows but no user window proc?"); - lock (internalSyncObject) { - for (int i = 0; i < hashBuckets.Length; i++) { + lock (internalSyncObject) + { + for (int i = 0; i < hashBuckets.Length; i++) + { HandleBucket b = hashBuckets[i]; - if (b.handle != IntPtr.Zero && b.handle != new IntPtr(-1)) { + if (b.handle != IntPtr.Zero && b.handle != new IntPtr(-1)) + { HandleRef href = new HandleRef(b, b.handle); UnsafeNativeMethods.SetWindowLong(href, NativeMethods.GWL_WNDPROC, new HandleRef(null, userDefWindowProc)); UnsafeNativeMethods.SetClassLong(href, NativeMethods.GCL_WNDPROC, userDefWindowProc); @@ -1012,9 +1155,11 @@ private static void OnShutdown(object sender, EventArgs e) { // Fish out the Window object, if it is valid, and NULL the handle pointer. This // way the rest of WinForms won't think the handle is still valid here. - if (b.window.IsAllocated) { + if (b.window.IsAllocated) + { NativeWindow w = (NativeWindow)b.window.Target; - if (w != null) { + if (w != null) + { w.handle = IntPtr.Zero; } } @@ -1043,7 +1188,8 @@ private static void OnShutdown(object sender, EventArgs e) { /// exception. /// /// - protected virtual void OnThreadException(Exception e) { + protected virtual void OnThreadException(Exception e) + { } /// @@ -1051,7 +1197,8 @@ protected virtual void OnThreadException(Exception e) { /// Releases the handle associated with this window. /// /// - public virtual void ReleaseHandle() { + public virtual void ReleaseHandle() + { ReleaseHandle(true); } @@ -1062,25 +1209,32 @@ public virtual void ReleaseHandle() { /// WM_DESTROY. Unsubclassing during this message can cause problems /// with XP's theme manager and it's not needed anyway. /// - private void ReleaseHandle(bool handleValid) { - if (handle != IntPtr.Zero) { + private void ReleaseHandle(bool handleValid) + { + if (handle != IntPtr.Zero) + { // - lock (this) { - if (handle != IntPtr.Zero) { - if (handleValid) { + lock (this) + { + if (handle != IntPtr.Zero) + { + if (handleValid) + { UnSubclass(); } RemoveWindowFromTable(handle, this); - if (ownHandle) { + if (ownHandle) + { Interop.HandleCollector.Remove(handle, Interop.CommonHandles.Window); ownHandle = false; } handle = IntPtr.Zero; //if not finalizing already. - if (weakThisPtr.IsAlive && weakThisPtr.Target != null) { + if (weakThisPtr.IsAlive && weakThisPtr.Target != null) + { OnHandleChange(); // Now that we have disposed, there is no need to finalize us any more. So @@ -1098,11 +1252,13 @@ private void ReleaseHandle(bool handleValid) { /// Removes an entry from this hashtable. If an entry with the specified /// key exists in the hashtable, it is removed. /// - private static void RemoveWindowFromTable(IntPtr handle, NativeWindow window) { + private static void RemoveWindowFromTable(IntPtr handle, NativeWindow window) + { Debug.Assert(handle != IntPtr.Zero, "Incorrect handle"); - lock (internalSyncObject) { + lock (internalSyncObject) + { uint seed; uint incr; @@ -1113,20 +1269,24 @@ private static void RemoveWindowFromTable(IntPtr handle, NativeWindow window) { HandleBucket b; int bn; // bucketNumber - do { + do + { bn = (int)(seed % (uint)hashBuckets.Length); // bucketNumber b = hashBuckets[bn]; - if (((b.hash_coll & 0x7FFFFFFF) == hashcode) && handle == b.handle) { + if (((b.hash_coll & 0x7FFFFFFF) == hashcode) && handle == b.handle) + { bool shouldRemoveBucket = (window.nextWindow == null); bool shouldReplaceBucket = IsRootWindowInListWithChildren(window); // We need to fixup the link pointers of window here. // - if (window.previousWindow != null) { + if (window.previousWindow != null) + { window.previousWindow.nextWindow = window.nextWindow; } - if (window.nextWindow != null) { + if (window.nextWindow != null) + { window.nextWindow.defWindowProc = window.defWindowProc; window.nextWindow.previousWindow = window.previousWindow; } @@ -1134,26 +1294,32 @@ private static void RemoveWindowFromTable(IntPtr handle, NativeWindow window) { window.nextWindow = null; window.previousWindow = null; - if (shouldReplaceBucket) { + if (shouldReplaceBucket) + { // Free the existing GC handle - if (hashBuckets[bn].window.IsAllocated) { + if (hashBuckets[bn].window.IsAllocated) + { hashBuckets[bn].window.Free(); } hashBuckets[bn].window = GCHandle.Alloc(prevWindow, GCHandleType.Weak); } - else if (shouldRemoveBucket) { + else if (shouldRemoveBucket) + { // Clear hash_coll field, then key, then value hashBuckets[bn].hash_coll &= unchecked((int)0x80000000); - if (hashBuckets[bn].hash_coll != 0) { + if (hashBuckets[bn].hash_coll != 0) + { hashBuckets[bn].handle = new IntPtr(-1); } - else { + else + { hashBuckets[bn].handle = IntPtr.Zero; } - if (hashBuckets[bn].window.IsAllocated) { + if (hashBuckets[bn].window.IsAllocated) + { hashBuckets[bn].window.Free(); } @@ -1171,7 +1337,8 @@ private static void RemoveWindowFromTable(IntPtr handle, NativeWindow window) { /// /// Determines if the given window is the first member of the linked list /// - private static bool IsRootWindowInListWithChildren(NativeWindow window) { + private static bool IsRootWindowInListWithChildren(NativeWindow window) + { // This seems backwards, but it isn't. When a new subclass comes in, // it's previousWindow field is set to the previous subclass. Therefore, // the top of the subclass chain has nextWindow == null and previousWindow @@ -1195,7 +1362,8 @@ private static bool IsRootWindowInListWithNoChildren(NativeWindow window) /// /// Inserts an entry into this ID hashtable. /// - internal static void RemoveWindowFromIDTable(IntPtr handle) { + internal static void RemoveWindowFromIDTable(IntPtr handle) + { short id = (short)NativeWindow.hashForHandleId[handle]; NativeWindow.hashForHandleId.Remove(handle); NativeWindow.hashForIdHandle.Remove(id); @@ -1222,37 +1390,47 @@ internal static void RemoveWindowFromIDTable(IntPtr handle) { /// When threadScope is true, the thread exception mode is set. The thread /// exception mode overrides the application exception mode if it's not Automatic. /// - internal static void SetUnhandledExceptionModeInternal(UnhandledExceptionMode mode, bool threadScope) { + internal static void SetUnhandledExceptionModeInternal(UnhandledExceptionMode mode, bool threadScope) + { - if (!threadScope && anyHandleCreatedInApp) { + if (!threadScope && anyHandleCreatedInApp) + { throw new InvalidOperationException(SR.ApplicationCannotChangeApplicationExceptionMode); } - if (threadScope && anyHandleCreated) { + if (threadScope && anyHandleCreated) + { throw new InvalidOperationException(SR.ApplicationCannotChangeThreadExceptionMode); } - switch (mode) { + switch (mode) + { case UnhandledExceptionMode.Automatic: - if (threadScope) { + if (threadScope) + { userSetProcFlags = 0; } - else { + else + { userSetProcFlagsForApp = 0; } break; case UnhandledExceptionMode.ThrowException: - if (threadScope) { + if (threadScope) + { userSetProcFlags = UseDebuggableWndProc | InitializedFlags; } - else { + else + { userSetProcFlagsForApp = UseDebuggableWndProc | InitializedFlags; } break; case UnhandledExceptionMode.CatchException: - if (threadScope) { + if (threadScope) + { userSetProcFlags = InitializedFlags; } - else { + else + { userSetProcFlagsForApp = InitializedFlags; } break; @@ -1271,18 +1449,21 @@ internal static void SetUnhandledExceptionModeInternal(UnhandledExceptionMode mo /// 3) User releasing this handle but this NativeWindow is not the current /// window proc. /// - private void UnSubclass() { + private void UnSubclass() + { bool finalizing = (!weakThisPtr.IsAlive || weakThisPtr.Target == null); HandleRef href = new HandleRef(this, handle); // Don't touch if the current window proc is not ours. // IntPtr currentWinPrc = UnsafeNativeMethods.GetWindowLong(new HandleRef(this, handle), NativeMethods.GWL_WNDPROC); - if (windowProcPtr == currentWinPrc) { - if (previousWindow == null) { + if (windowProcPtr == currentWinPrc) + { + if (previousWindow == null) + { #if DEBUG - subclassStatus = "Unsubclassing back to native defWindowProc"; + subclassStatus = "Unsubclassing back to native defWindowProc"; #endif // If the defWindowProc points to a native window proc, previousWindow will @@ -1291,8 +1472,10 @@ private void UnSubclass() { // UnsafeNativeMethods.SetWindowLong(href, NativeMethods.GWL_WNDPROC, new HandleRef(this, defWindowProc)); } - else { - if (finalizing) { + else + { + if (finalizing) + { #if DEBUG subclassStatus = "Setting back to userDefWindowProc -- next chain is managed"; @@ -1305,7 +1488,8 @@ private void UnSubclass() { // userDefWindowProc. UnsafeNativeMethods.SetWindowLong(href, NativeMethods.GWL_WNDPROC, new HandleRef(this, userDefWindowProc)); } - else { + else + { #if DEBUG subclassStatus = "Setting back to next managed subclass object"; @@ -1318,7 +1502,8 @@ private void UnSubclass() { } } } - else { + else + { // cutting the subclass chain anyway, even if we're not the last one in the chain // if the whole chain is all managed NativeWindow it doesnt matter, // if the chain is not, then someone has been dirty and didn't clean up properly, too bad for them... @@ -1327,7 +1512,8 @@ private void UnSubclass() { //If we find previouswindow pointing to us, then we can let RemoveWindowFromTable reassign the //defwndproc pointers properly when this guy gets removed (thereby unsubclassing ourselves) - if (nextWindow == null || nextWindow.defWindowProc != windowProcPtr) { + if (nextWindow == null || nextWindow.defWindowProc != windowProcPtr) + { // we didn't find it... let's unhook anyway and cut the chain... this prevents crashes UnsafeNativeMethods.SetWindowLong(href, NativeMethods.GWL_WNDPROC, new HandleRef(this, userDefWindowProc)); } @@ -1344,7 +1530,8 @@ private void UnSubclass() { /// /// - protected virtual void WndProc(ref Message m) { + protected virtual void WndProc(ref Message m) + { DefWndProc(ref m); } @@ -1362,7 +1549,8 @@ protected virtual void WndProc(ref Message m) { /// /// Reclaimed buckets store -1 in their handle, not the hash table reference. /// - private struct HandleBucket { + private struct HandleBucket + { public IntPtr handle; // Win32 window handle public GCHandle window; // a weak GC handle to the NativeWindow class public int hash_coll; // Store hash code; sign bit means there was a collision. @@ -1374,7 +1562,8 @@ private struct HandleBucket { /// /// WindowClass encapsulates a window class. /// - private class WindowClass { + private class WindowClass + { internal static WindowClass cache; internal WindowClass next; @@ -1390,13 +1579,15 @@ private class WindowClass { private static object wcInternalSyncObject = new object(); private static int domainQualifier = 0; - internal WindowClass(string className, int classStyle) { + internal WindowClass(string className, int classStyle) + { this.className = className; this.classStyle = classStyle; RegisterClass(); } - public IntPtr Callback(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam) { + public IntPtr Callback(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam) + { Debug.Assert(hWnd != IntPtr.Zero, "Windows called us with an HWND of 0"); UnsafeNativeMethods.SetWindowLong(new HandleRef(null, hWnd), NativeMethods.GWL_WNDPROC, new HandleRef(this, defWindowProc)); targetWindow.AssignHandle(hWnd); @@ -1408,26 +1599,35 @@ public IntPtr Callback(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam) { /// object if there is no such class/style available, or retrun a /// cached object if one exists. /// - internal static WindowClass Create(string className, int classStyle) { - lock (wcInternalSyncObject) { + internal static WindowClass Create(string className, int classStyle) + { + lock (wcInternalSyncObject) + { WindowClass wc = cache; - if (className == null) { + if (className == null) + { while (wc != null && (wc.className != null || - wc.classStyle != classStyle)) wc = wc.next; + wc.classStyle != classStyle)) + wc = wc.next; } - else { + else + { while (wc != null && - !className.Equals(wc.className)) { + !className.Equals(wc.className)) + { wc = wc.next; } } - if (wc == null) { + if (wc == null) + { wc = new WindowClass(className, classStyle); wc.next = cache; cache = wc; } - else { - if (!wc.registered) { + else + { + if (!wc.registered) + { wc.RegisterClass(); } } @@ -1441,11 +1641,14 @@ internal static WindowClass Create(string className, int classStyle) { /// the classes of everything in the cache. This allows the unused /// classes to be unrooted. They can later be re-rooted and reused. /// - internal static void DisposeCache() { - lock (wcInternalSyncObject) { + internal static void DisposeCache() + { + lock (wcInternalSyncObject) + { WindowClass wc = cache; - while (wc != null) { + while (wc != null) + { wc.UnregisterClass(); wc = wc.next; } @@ -1455,7 +1658,8 @@ internal static void DisposeCache() { /// /// Fabricates a full class name from a partial. /// - private string GetFullClassName(string className) { + private string GetFullClassName(string className) + { StringBuilder b = new StringBuilder(50); b.Append(Application.WindowsFormsVersion); b.Append('.'); @@ -1472,21 +1676,25 @@ private string GetFullClassName(string className) { /// Once the classname and style bits have been set, this can /// be called to register the class. /// - private void RegisterClass() { + private void RegisterClass() + { NativeMethods.WNDCLASS_D wndclass = new NativeMethods.WNDCLASS_D(); - if (userDefWindowProc == IntPtr.Zero) { + if (userDefWindowProc == IntPtr.Zero) + { string defproc = "DefWindowProcW"; userDefWindowProc = UnsafeNativeMethods.GetProcAddress(new HandleRef(null, UnsafeNativeMethods.GetModuleHandle("user32.dll")), defproc); - if (userDefWindowProc == IntPtr.Zero) { + if (userDefWindowProc == IntPtr.Zero) + { throw new Win32Exception(); } } string localClassName = className; - if (localClassName == null) { + if (localClassName == null) + { // If we don't use a hollow brush here, Windows will "pre paint" us with COLOR_WINDOW which // creates a little bit if flicker. This happens even though we are overriding wm_erasebackgnd. @@ -1499,11 +1707,13 @@ private void RegisterClass() { localClassName = "Window." + Convert.ToString(classStyle, 16); hashCode = 0; } - else { + else + { NativeMethods.WNDCLASS_I wcls = new NativeMethods.WNDCLASS_I(); bool ok = UnsafeNativeMethods.GetClassInfo(NativeMethods.NullHandleRef, className, wcls); int error = Marshal.GetLastWin32Error(); - if (!ok) { + if (!ok) + { throw new Win32Exception(error, SR.InvalidWndClsName); } wndclass.style = wcls.style; @@ -1528,10 +1738,12 @@ private void RegisterClass() { wndclass.lpszClassName = windowClassName; short atom = UnsafeNativeMethods.RegisterClass(wndclass); - if (atom == 0) { + if (atom == 0) + { int err = Marshal.GetLastWin32Error(); - if (err == NativeMethods.ERROR_CLASS_ALREADY_EXISTS) { + if (err == NativeMethods.ERROR_CLASS_ALREADY_EXISTS) + { // Check to see if the window class window // proc points to DefWndProc. If it does, then // this is a class from a rudely-terminated app domain @@ -1539,7 +1751,8 @@ private void RegisterClass() { // to throw. NativeMethods.WNDCLASS_I wcls = new NativeMethods.WNDCLASS_I(); bool ok = UnsafeNativeMethods.GetClassInfo(new HandleRef(null, UnsafeNativeMethods.GetModuleHandle(null)), windowClassName, wcls); - if (ok && wcls.lpfnWndProc == NativeWindow.UserDefindowProc) { + if (ok && wcls.lpfnWndProc == NativeWindow.UserDefindowProc) + { // We can just reuse this class because we have marked it // as being a nop in another domain. All we need to do is call SetClassLong. @@ -1548,16 +1761,19 @@ private void RegisterClass() { // if we can simply unregister and re-register the class. This might // work because the other domain shutdown would have posted WM_CLOSE to all // the windows of the class. - if (UnsafeNativeMethods.UnregisterClass(windowClassName, new HandleRef(null, UnsafeNativeMethods.GetModuleHandle(null)))) { + if (UnsafeNativeMethods.UnregisterClass(windowClassName, new HandleRef(null, UnsafeNativeMethods.GetModuleHandle(null)))) + { atom = UnsafeNativeMethods.RegisterClass(wndclass); // If this fails, we will always raise the first err above. No sense exposing our twiddling. } - else { + else + { // This is a little harder. We cannot reuse the class because it is // already in use. We must create a new class. We bump our domain qualifier // here to account for this, so we only do this expensive search once for the // domain. - do { + do + { domainQualifier++; windowClassName = GetFullClassName(localClassName); wndclass.lpszClassName = windowClassName; @@ -1567,7 +1783,8 @@ private void RegisterClass() { } } - if (atom == 0) { + if (atom == 0) + { windowProc = null; throw new Win32Exception(err); } @@ -1580,8 +1797,10 @@ private void RegisterClass() { /// last resort; the window class may be re-registered through /// a call to registerClass. /// - private void UnregisterClass() { - if (registered && UnsafeNativeMethods.UnregisterClass(windowClassName, new HandleRef(null, UnsafeNativeMethods.GetModuleHandle(null)))) { + private void UnregisterClass() + { + if (registered && UnsafeNativeMethods.UnregisterClass(windowClassName, new HandleRef(null, UnsafeNativeMethods.GetModuleHandle(null)))) + { windowProc = null; registered = false; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NoneExcludedImageIndexConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NoneExcludedImageIndexConverter.cs index e00d8baf835..5f7f3c4df18 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NoneExcludedImageIndexConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NoneExcludedImageIndexConverter.cs @@ -2,19 +2,23 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ /// /// Just returns false for IncludeNoneAsStandardValue /// - internal sealed class NoneExcludedImageIndexConverter : ImageIndexConverter { + internal sealed class NoneExcludedImageIndexConverter : ImageIndexConverter + { - protected override bool IncludeNoneAsStandardValue { - get { + protected override bool IncludeNoneAsStandardValue + { + get + { return false; } - } + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs index 420cfd3e315..3320d1c4f00 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs @@ -2,13 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System; using System.Runtime.InteropServices; - using System.Windows.Forms; + using System.Windows.Forms; using System.Windows.Forms.Design; using Microsoft.Win32; using System.Drawing; @@ -27,8 +28,9 @@ namespace System.Windows.Forms { ToolboxItemFilter("System.Windows.Forms"), SRDescription(nameof(SR.DescriptionNotifyIcon)) ] - public sealed class NotifyIcon : Component { - private static readonly object EVENT_MOUSEDOWN = new object(); + public sealed class NotifyIcon : Component + { + private static readonly object EVENT_MOUSEDOWN = new object(); private static readonly object EVENT_MOUSEMOVE = new object(); private static readonly object EVENT_MOUSEUP = new object(); private static readonly object EVENT_CLICK = new object(); @@ -68,7 +70,8 @@ public sealed class NotifyIcon : Component { /// Initializes a new instance of the class. /// /// - public NotifyIcon() { + public NotifyIcon() + { id = ++nextId; window = new NotifyIconNativeWindow(this); UpdateIcon(visible); @@ -79,8 +82,10 @@ public NotifyIcon() { /// Initializes a new instance of the class. /// /// - public NotifyIcon(IContainer container) : this() { - if (container == null) { + public NotifyIcon(IContainer container) : this() + { + if (container == null) + { throw new ArgumentNullException(nameof(container)); } @@ -100,12 +105,16 @@ public NotifyIcon(IContainer container) : this() { SRDescription(nameof(SR.NotifyIconBalloonTipTextDescr)), Editor("System.ComponentModel.Design.MultilineStringEditor, " + AssemblyRef.SystemDesign, typeof(System.Drawing.Design.UITypeEditor)) ] - public string BalloonTipText { - get { - return balloonTipText; + public string BalloonTipText + { + get + { + return balloonTipText; } - set { - if (value != balloonTipText) { + set + { + if (value != balloonTipText) + { balloonTipText = value; } } @@ -122,16 +131,21 @@ public string BalloonTipText { DefaultValue(ToolTipIcon.None), SRDescription(nameof(SR.NotifyIconBalloonTipIconDescr)) ] - public ToolTipIcon BalloonTipIcon { - get { - return balloonTipIcon; + public ToolTipIcon BalloonTipIcon + { + get + { + return balloonTipIcon; } - set { + set + { //valid values are 0x0 to 0x3 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolTipIcon.None, (int)ToolTipIcon.Error)){ - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolTipIcon)); + if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolTipIcon.None, (int)ToolTipIcon.Error)) + { + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolTipIcon)); } - if (value != balloonTipIcon) { + if (value != balloonTipIcon) + { balloonTipIcon = value; } } @@ -149,12 +163,16 @@ public ToolTipIcon BalloonTipIcon { DefaultValue(""), SRDescription(nameof(SR.NotifyIconBalloonTipTitleDescr)) ] - public string BalloonTipTitle { - get { - return balloonTipTitle; + public string BalloonTipTitle + { + get + { + return balloonTipTitle; } - set { - if (value != balloonTipTitle) { + set + { + if (value != balloonTipTitle) + { balloonTipTitle = value; } } @@ -164,7 +182,8 @@ public string BalloonTipTitle { /// [This event is raised on the NIN_BALLOONUSERCLICK message.] /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.NotifyIconOnBalloonTipClickedDescr))] - public event EventHandler BalloonTipClicked { + public event EventHandler BalloonTipClicked + { add => Events.AddHandler(EVENT_BALLOONTIPCLICKED, value); remove => Events.RemoveHandler(EVENT_BALLOONTIPCLICKED, value); @@ -174,7 +193,8 @@ public event EventHandler BalloonTipClicked { /// [This event is raised on the NIN_BALLOONTIMEOUT message.] /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.NotifyIconOnBalloonTipClosedDescr))] - public event EventHandler BalloonTipClosed { + public event EventHandler BalloonTipClosed + { add => Events.AddHandler(EVENT_BALLOONTIPCLOSED, value); remove => Events.RemoveHandler(EVENT_BALLOONTIPCLOSED, value); @@ -184,7 +204,8 @@ public event EventHandler BalloonTipClosed { /// [This event is raised on the NIN_BALLOONSHOW or NIN_BALLOONHIDE message.] /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.NotifyIconOnBalloonTipShownDescr))] - public event EventHandler BalloonTipShown { + public event EventHandler BalloonTipShown + { add => Events.AddHandler(EVENT_BALLOONTIPSHOWN, value); remove => Events.RemoveHandler(EVENT_BALLOONTIPSHOWN, value); } @@ -201,12 +222,15 @@ public event EventHandler BalloonTipShown { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.NotifyIconMenuDescr)) ] - public ContextMenu ContextMenu { - get { + public ContextMenu ContextMenu + { + get + { return contextMenu; } - set { + set + { this.contextMenu = value; } } @@ -216,12 +240,15 @@ public ContextMenu ContextMenu { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.NotifyIconMenuDescr)) ] - public ContextMenuStrip ContextMenuStrip { - get { + public ContextMenuStrip ContextMenuStrip + { + get + { return contextMenuStrip; } - - set { + + set + { this.contextMenuStrip = value; } } @@ -238,12 +265,16 @@ public ContextMenuStrip ContextMenuStrip { DefaultValue(null), SRDescription(nameof(SR.NotifyIconIconDescr)) ] - public Icon Icon { - get { + public Icon Icon + { + get + { return icon; } - set { - if (icon != value) { + set + { + if (icon != value) + { this.icon = value; UpdateIcon(visible); } @@ -263,18 +294,25 @@ public Icon Icon { SRDescription(nameof(SR.NotifyIconTextDescr)), Editor("System.ComponentModel.Design.MultilineStringEditor, " + AssemblyRef.SystemDesign, typeof(System.Drawing.Design.UITypeEditor)) ] - public string Text { - get { + public string Text + { + get + { return text; } - set { - if (value == null) value = string.Empty; - if (value != null && !value.Equals(this.text)) { - if (value != null && value.Length > 63) { + set + { + if (value == null) + value = string.Empty; + if (value != null && !value.Equals(this.text)) + { + if (value != null && value.Length > 63) + { throw new ArgumentOutOfRangeException(nameof(Text), value, string.Format(SR.TrayIcon_TextTooLong)); } this.text = value; - if (added) { + if (added) + { UpdateIcon(true); } } @@ -292,12 +330,16 @@ public string Text { DefaultValue(false), SRDescription(nameof(SR.NotifyIconVisDescr)) ] - public bool Visible { - get { + public bool Visible + { + get + { return visible; } - set { - if (visible != value) { + set + { + if (visible != value) + { UpdateIcon(value); visible = value; } @@ -312,11 +354,14 @@ public bool Visible { DefaultValue(null), TypeConverter(typeof(StringConverter)), ] - public object Tag { - get { + public object Tag + { + get + { return userData; } - set { + set + { userData = value; } } @@ -325,7 +370,8 @@ public object Tag { /// Occurs when the user clicks the icon in the system tray. /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ControlOnClickDescr))] - public event EventHandler Click { + public event EventHandler Click + { add => Events.AddHandler(EVENT_CLICK, value); remove => Events.RemoveHandler(EVENT_CLICK, value); } @@ -334,7 +380,8 @@ public event EventHandler Click { /// Occurs when the user double-clicks the icon in the system tray. /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ControlOnDoubleClickDescr))] - public event EventHandler DoubleClick { + public event EventHandler DoubleClick + { add => Events.AddHandler(EVENT_DOUBLECLICK, value); remove => Events.RemoveHandler(EVENT_DOUBLECLICK, value); } @@ -343,7 +390,8 @@ public event EventHandler DoubleClick { /// Occurs when the user clicks the icon in the system tray. /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.NotifyIconMouseClickDescr))] - public event MouseEventHandler MouseClick { + public event MouseEventHandler MouseClick + { add => Events.AddHandler(EVENT_MOUSECLICK, value); remove => Events.RemoveHandler(EVENT_MOUSECLICK, value); } @@ -352,7 +400,8 @@ public event MouseEventHandler MouseClick { /// Occurs when the user mouse double clicks the icon in the system tray. /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.NotifyIconMouseDoubleClickDescr))] - public event MouseEventHandler MouseDoubleClick { + public event MouseEventHandler MouseDoubleClick + { add => Events.AddHandler(EVENT_MOUSEDOUBLECLICK, value); remove => Events.RemoveHandler(EVENT_MOUSEDOUBLECLICK, value); } @@ -364,10 +413,11 @@ public event MouseEventHandler MouseDoubleClick { /// /// [SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.ControlOnMouseDownDescr))] - public event MouseEventHandler MouseDown { + public event MouseEventHandler MouseDown + { add => Events.AddHandler(EVENT_MOUSEDOWN, value); remove => Events.RemoveHandler(EVENT_MOUSEDOWN, value); - } + } /// /// @@ -376,10 +426,11 @@ public event MouseEventHandler MouseDown { /// /// [SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.ControlOnMouseMoveDescr))] - public event MouseEventHandler MouseMove { + public event MouseEventHandler MouseMove + { add => Events.AddHandler(EVENT_MOUSEMOVE, value); remove => Events.RemoveHandler(EVENT_MOUSEMOVE, value); - } + } /// /// @@ -389,10 +440,11 @@ public event MouseEventHandler MouseMove { /// /// [SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.ControlOnMouseUpDescr))] - public event MouseEventHandler MouseUp { + public event MouseEventHandler MouseUp + { add => Events.AddHandler(EVENT_MOUSEUP, value); remove => Events.RemoveHandler(EVENT_MOUSEUP, value); - } + } /// /// @@ -400,9 +452,12 @@ public event MouseEventHandler MouseUp { /// . /// /// - protected override void Dispose(bool disposing) { - if (disposing) { - if (window != null) { + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (window != null) + { this.icon = null; this.Text = string.Empty; UpdateIcon(false); @@ -412,11 +467,13 @@ protected override void Dispose(bool disposing) { contextMenuStrip = null; } } - else { + else + { // This same post is done in ControlNativeWindow's finalize method, so if you change // it, change it there too. // - if (window != null && window.Handle != IntPtr.Zero) { + if (window != null && window.Handle != IntPtr.Zero) + { UnsafeNativeMethods.PostMessage(new HandleRef(window, window.Handle), Interop.WindowMessages.WM_CLOSE, 0, 0); window.ReleaseHandle(); } @@ -429,9 +486,11 @@ protected override void Dispose(bool disposing) { /// This method raised the BalloonTipClicked event. /// /// - private void OnBalloonTipClicked() { + private void OnBalloonTipClicked() + { EventHandler handler = (EventHandler)Events[EVENT_BALLOONTIPCLICKED]; - if (handler != null) { + if (handler != null) + { handler(this, EventArgs.Empty); } } @@ -441,9 +500,11 @@ private void OnBalloonTipClicked() { /// This method raised the BalloonTipClosed event. /// /// - private void OnBalloonTipClosed() { + private void OnBalloonTipClosed() + { EventHandler handler = (EventHandler)Events[EVENT_BALLOONTIPCLOSED]; - if (handler != null) { + if (handler != null) + { handler(this, EventArgs.Empty); } } @@ -453,9 +514,11 @@ private void OnBalloonTipClosed() { /// This method raised the BalloonTipShown event. /// /// - private void OnBalloonTipShown() { + private void OnBalloonTipShown() + { EventHandler handler = (EventHandler)Events[EVENT_BALLOONTIPSHOWN]; - if (handler != null) { + if (handler != null) + { handler(this, EventArgs.Empty); } } @@ -469,20 +532,22 @@ private void OnBalloonTipShown() { /// other recipients do actually get the event. /// /// - private void OnClick(EventArgs e) { - EventHandler handler = (EventHandler) Events[ EVENT_CLICK ]; + private void OnClick(EventArgs e) + { + EventHandler handler = (EventHandler)Events[EVENT_CLICK]; if (handler != null) - handler( this, e ); + handler(this, e); } /// /// Inheriting classes should override this method to handle this event. /// Call base.onDoubleClick to send this event to any registered event listeners. /// - private void OnDoubleClick(EventArgs e) { - EventHandler handler = (EventHandler) Events[ EVENT_DOUBLECLICK ]; + private void OnDoubleClick(EventArgs e) + { + EventHandler handler = (EventHandler)Events[EVENT_DOUBLECLICK]; if (handler != null) - handler( this, e ); + handler(this, e); } @@ -490,20 +555,22 @@ private void OnDoubleClick(EventArgs e) { /// Inheriting classes should override this method to handle this event. /// Call base.OnMouseClick to send this event to any registered event listeners. /// - private void OnMouseClick(MouseEventArgs mea) { - MouseEventHandler handler = (MouseEventHandler) Events[ EVENT_MOUSECLICK ]; + private void OnMouseClick(MouseEventArgs mea) + { + MouseEventHandler handler = (MouseEventHandler)Events[EVENT_MOUSECLICK]; if (handler != null) - handler( this, mea ); + handler(this, mea); } - + /// /// Inheriting classes should override this method to handle this event. /// Call base.OnMouseDoubleClick to send this event to any registered event listeners. /// - private void OnMouseDoubleClick(MouseEventArgs mea) { - MouseEventHandler handler = (MouseEventHandler) Events[ EVENT_MOUSEDOUBLECLICK ]; + private void OnMouseDoubleClick(MouseEventArgs mea) + { + MouseEventHandler handler = (MouseEventHandler)Events[EVENT_MOUSEDOUBLECLICK]; if (handler != null) - handler( this, mea ); + handler(this, mea); } /// @@ -514,7 +581,8 @@ private void OnMouseDoubleClick(MouseEventArgs mea) { /// /// /// - private void OnMouseDown(MouseEventArgs e) { + private void OnMouseDown(MouseEventArgs e) + { MouseEventHandler handler = (MouseEventHandler)Events[EVENT_MOUSEDOWN]; if (handler != null) handler(this, e); @@ -527,7 +595,8 @@ private void OnMouseDown(MouseEventArgs e) { /// /// /// - private void OnMouseMove(MouseEventArgs e) { + private void OnMouseMove(MouseEventArgs e) + { MouseEventHandler handler = (MouseEventHandler)Events[EVENT_MOUSEMOVE]; if (handler != null) handler(this, e); @@ -539,7 +608,8 @@ private void OnMouseMove(MouseEventArgs e) { /// Call base.onMouseUp to send this event to any registered event listeners. /// /// - private void OnMouseUp(MouseEventArgs e) { + private void OnMouseUp(MouseEventArgs e) + { MouseEventHandler handler = (MouseEventHandler)Events[EVENT_MOUSEUP]; if (handler != null) handler(this, e); @@ -564,7 +634,8 @@ private void OnMouseUp(MouseEventArgs e) { /// ToolTip displays for an additional three seconds before being replaced by the second ToolTip. /// /// - public void ShowBalloonTip(int timeout) { + public void ShowBalloonTip(int timeout) + { ShowBalloonTip(timeout, this.balloonTipTitle, this.balloonTipText, this.balloonTipIcon); } @@ -589,10 +660,12 @@ public void ShowBalloonTip(int timeout) { /// ToolTip displays for an additional three seconds before being replaced by the second ToolTip. /// /// - public void ShowBalloonTip(int timeout, string tipTitle, string tipText, ToolTipIcon tipIcon) { + public void ShowBalloonTip(int timeout, string tipTitle, string tipText, ToolTipIcon tipIcon) + { - if (timeout < 0) { - throw new ArgumentOutOfRangeException(nameof(timeout), timeout, string.Format(SR.InvalidArgument, nameof(timeout), timeout)); + if (timeout < 0) + { + throw new ArgumentOutOfRangeException(nameof(timeout), timeout, string.Format(SR.InvalidArgument, nameof(timeout), timeout)); } if (string.IsNullOrEmpty(tipText)) @@ -601,20 +674,24 @@ public void ShowBalloonTip(int timeout, string tipTitle, string tipText, ToolTip } //valid values are 0x0 to 0x3 - if (!ClientUtils.IsEnumValid(tipIcon, (int)tipIcon, (int)ToolTipIcon.None, (int)ToolTipIcon.Error)){ + if (!ClientUtils.IsEnumValid(tipIcon, (int)tipIcon, (int)ToolTipIcon.None, (int)ToolTipIcon.Error)) + { throw new InvalidEnumArgumentException(nameof(tipIcon), (int)tipIcon, typeof(ToolTipIcon)); } - - - if (added ) { + + + if (added) + { // Bail if in design mode... - if (DesignMode) { - return; + if (DesignMode) + { + return; } NativeMethods.NOTIFYICONDATA data = new NativeMethods.NOTIFYICONDATA(); - if (window.Handle == IntPtr.Zero) { - window.CreateHandle(new CreateParams()); + if (window.Handle == IntPtr.Zero) + { + window.CreateHandle(new CreateParams()); } data.hWnd = window.Handle; data.uID = id; @@ -622,32 +699,44 @@ public void ShowBalloonTip(int timeout, string tipTitle, string tipText, ToolTip data.uTimeoutOrVersion = timeout; data.szInfoTitle = tipTitle; data.szInfo = tipText; - switch (tipIcon) { - case ToolTipIcon.Info: data.dwInfoFlags = NativeMethods.NIIF_INFO; break; - case ToolTipIcon.Warning: data.dwInfoFlags = NativeMethods.NIIF_WARNING; break; - case ToolTipIcon.Error: data.dwInfoFlags = NativeMethods.NIIF_ERROR; break; - case ToolTipIcon.None: data.dwInfoFlags = NativeMethods.NIIF_NONE; break; + switch (tipIcon) + { + case ToolTipIcon.Info: + data.dwInfoFlags = NativeMethods.NIIF_INFO; + break; + case ToolTipIcon.Warning: + data.dwInfoFlags = NativeMethods.NIIF_WARNING; + break; + case ToolTipIcon.Error: + data.dwInfoFlags = NativeMethods.NIIF_ERROR; + break; + case ToolTipIcon.None: + data.dwInfoFlags = NativeMethods.NIIF_NONE; + break; } UnsafeNativeMethods.Shell_NotifyIcon(NativeMethods.NIM_MODIFY, data); - } + } } /// /// Shows the context menu for the tray icon. /// - private void ShowContextMenu() { + private void ShowContextMenu() + { - if (contextMenu != null || contextMenuStrip != null) { + if (contextMenu != null || contextMenuStrip != null) + { NativeMethods.POINT pt = new NativeMethods.POINT(); UnsafeNativeMethods.GetCursorPos(pt); - + // Summary: the current window must be made the foreground window // before calling TrackPopupMenuEx, and a task switch must be // forced after the call. UnsafeNativeMethods.SetForegroundWindow(new HandleRef(window, window.Handle)); - if (contextMenu != null) { - contextMenu.OnPopup( EventArgs.Empty ); + if (contextMenu != null) + { + contextMenu.OnPopup(EventArgs.Empty); SafeNativeMethods.TrackPopupMenuEx(new HandleRef(contextMenu, contextMenu.Handle), NativeMethods.TPM_VERTICAL | NativeMethods.TPM_RIGHTALIGN, @@ -659,23 +748,27 @@ private void ShowContextMenu() { // Force task switch (see above) UnsafeNativeMethods.PostMessage(new HandleRef(window, window.Handle), Interop.WindowMessages.WM_NULL, IntPtr.Zero, IntPtr.Zero); } - else if (contextMenuStrip != null) { + else if (contextMenuStrip != null) + { // this will set the context menu strip to be toplevel // and will allow us to overlap the system tray contextMenuStrip.ShowInTaskbar(pt.x, pt.y); } } } - + /// /// Updates the icon in the system tray. /// - private void UpdateIcon(bool showIconInTray) { - lock(syncObj) { + private void UpdateIcon(bool showIconInTray) + { + lock (syncObj) + { // Bail if in design mode... // - if (DesignMode) { + if (DesignMode) + { return; } @@ -684,8 +777,10 @@ private void UpdateIcon(bool showIconInTray) { NativeMethods.NOTIFYICONDATA data = new NativeMethods.NOTIFYICONDATA(); data.uCallbackMessage = WM_TRAYMOUSEMESSAGE; data.uFlags = NativeMethods.NIF_MESSAGE; - if (showIconInTray) { - if (window.Handle == IntPtr.Zero) { + if (showIconInTray) + { + if (window.Handle == IntPtr.Zero) + { window.CreateHandle(new CreateParams()); } } @@ -693,23 +788,28 @@ private void UpdateIcon(bool showIconInTray) { data.uID = id; data.hIcon = IntPtr.Zero; data.szTip = null; - if (icon != null) { + if (icon != null) + { data.uFlags |= NativeMethods.NIF_ICON; data.hIcon = icon.Handle; } data.uFlags |= NativeMethods.NIF_TIP; data.szTip = text; - if (showIconInTray && icon != null) { - if (!added) { + if (showIconInTray && icon != null) + { + if (!added) + { UnsafeNativeMethods.Shell_NotifyIcon(NativeMethods.NIM_ADD, data); added = true; } - else { + else + { UnsafeNativeMethods.Shell_NotifyIcon(NativeMethods.NIM_MODIFY, data); } } - else if (added) { + else if (added) + { UnsafeNativeMethods.Shell_NotifyIcon(NativeMethods.NIM_DELETE, data); added = false; } @@ -719,8 +819,10 @@ private void UpdateIcon(bool showIconInTray) { /// /// Handles the mouse-down event /// - private void WmMouseDown(ref Message m, MouseButtons button, int clicks) { - if (clicks == 2) { + private void WmMouseDown(ref Message m, MouseButtons button, int clicks) + { + if (clicks == 2) + { OnDoubleClick(new MouseEventArgs(button, 2, 0, 0, 0)); OnMouseDoubleClick(new MouseEventArgs(button, 2, 0, 0, 0)); doubleClick = true; @@ -731,33 +833,40 @@ private void WmMouseDown(ref Message m, MouseButtons button, int clicks) { /// /// Handles the mouse-move event /// - private void WmMouseMove(ref Message m) { + private void WmMouseMove(ref Message m) + { OnMouseMove(new MouseEventArgs(Control.MouseButtons, 0, 0, 0, 0)); } /// /// Handles the mouse-up event /// - private void WmMouseUp(ref Message m, MouseButtons button) { + private void WmMouseUp(ref Message m, MouseButtons button) + { OnMouseUp(new MouseEventArgs(button, 0, 0, 0, 0)); //subhag - if(!doubleClick) { - OnClick(new MouseEventArgs(button, 0, 0, 0, 0)); - OnMouseClick(new MouseEventArgs(button, 0, 0, 0, 0)); + if (!doubleClick) + { + OnClick(new MouseEventArgs(button, 0, 0, 0, 0)); + OnMouseClick(new MouseEventArgs(button, 0, 0, 0, 0)); } doubleClick = false; } - private void WmTaskbarCreated(ref Message m) { + private void WmTaskbarCreated(ref Message m) + { added = false; UpdateIcon(visible); } - private void WndProc(ref Message msg) { + private void WndProc(ref Message msg) + { - switch (msg.Msg) { + switch (msg.Msg) + { case WM_TRAYMOUSEMESSAGE: - switch ((int)msg.LParam) { + switch ((int)msg.LParam) + { case Interop.WindowMessages.WM_LBUTTONDBLCLK: WmMouseDown(ref msg, MouseButtons.Left, 2); break; @@ -786,7 +895,8 @@ private void WndProc(ref Message msg) { WmMouseDown(ref msg, MouseButtons.Right, 1); break; case Interop.WindowMessages.WM_RBUTTONUP: - if (contextMenu != null || contextMenuStrip != null) { + if (contextMenu != null || contextMenuStrip != null) + { ShowContextMenu(); } WmMouseUp(ref msg, MouseButtons.Right); @@ -806,27 +916,32 @@ private void WndProc(ref Message msg) { } break; case Interop.WindowMessages.WM_COMMAND: - if (IntPtr.Zero == msg.LParam) { - if (Command.DispatchID((int)msg.WParam & 0xFFFF)) return; + if (IntPtr.Zero == msg.LParam) + { + if (Command.DispatchID((int)msg.WParam & 0xFFFF)) + return; } - else { + else + { window.DefWndProc(ref msg); } break; case Interop.WindowMessages.WM_DRAWITEM: // If the wparam is zero, then the message was sent by a menu. // See WM_DRAWITEM in MSDN. - if (msg.WParam == IntPtr.Zero) { + if (msg.WParam == IntPtr.Zero) + { WmDrawItemMenuItem(ref msg); } break; case Interop.WindowMessages.WM_MEASUREITEM: // If the wparam is zero, then the message was sent by a menu. - if (msg.WParam == IntPtr.Zero) { + if (msg.WParam == IntPtr.Zero) + { WmMeasureMenuItem(ref msg); } break; - + case Interop.WindowMessages.WM_INITMENUPOPUP: WmInitMenuPopup(ref msg); break; @@ -837,7 +952,8 @@ private void WndProc(ref Message msg) { break; default: - if (msg.Msg == WM_TASKBARCREATED) { + if (msg.Msg == WM_TASKBARCREATED) + { WmTaskbarCreated(ref msg); } window.DefWndProc(ref msg); @@ -845,9 +961,12 @@ private void WndProc(ref Message msg) { } } - private void WmInitMenuPopup(ref Message m) { - if (contextMenu != null) { - if (contextMenu.ProcessInitMenuPopup(m.WParam)) { + private void WmInitMenuPopup(ref Message m) + { + if (contextMenu != null) + { + if (contextMenu.ProcessInitMenuPopup(m.WParam)) + { return; } } @@ -855,7 +974,8 @@ private void WmInitMenuPopup(ref Message m) { window.DefWndProc(ref m); } - private void WmMeasureMenuItem(ref Message m) { + private void WmMeasureMenuItem(ref Message m) + { // Obtain the menu item object NativeMethods.MEASUREITEMSTRUCT mis = (NativeMethods.MEASUREITEMSTRUCT)m.GetLParam(typeof(NativeMethods.MEASUREITEMSTRUCT)); @@ -868,12 +988,14 @@ private void WmMeasureMenuItem(ref Message m) { Debug.Assert(menuItem != null, "UniqueID is not associated with a menu item"); // Delegate this message to the menu item - if (menuItem != null) { + if (menuItem != null) + { menuItem.WmMeasureItem(ref m); } } - private void WmDrawItemMenuItem(ref Message m) { + private void WmDrawItemMenuItem(ref Message m) + { // Obtain the menu item object NativeMethods.DRAWITEMSTRUCT dis = (NativeMethods.DRAWITEMSTRUCT)m.GetLParam(typeof(NativeMethods.DRAWITEMSTRUCT)); @@ -883,7 +1005,8 @@ private void WmDrawItemMenuItem(ref Message m) { MenuItem menuItem = MenuItem.GetMenuItemFromItemData(dis.itemData); // Delegate this message to the menu item - if (menuItem != null) { + if (menuItem != null) + { menuItem.WmDrawItem(ref m); } } @@ -891,50 +1014,61 @@ private void WmDrawItemMenuItem(ref Message m) { /// /// Defines a placeholder window that the NotifyIcon is attached to. /// - private class NotifyIconNativeWindow : NativeWindow { + private class NotifyIconNativeWindow : NativeWindow + { internal NotifyIcon reference; - private GCHandle rootRef; // We will root the control when we do not want to be elligible for garbage collection. + private GCHandle rootRef; // We will root the control when we do not want to be elligible for garbage collection. /// /// Create a new NotifyIcon, and bind the window to the NotifyIcon component. /// - internal NotifyIconNativeWindow(NotifyIcon component) { + internal NotifyIconNativeWindow(NotifyIcon component) + { reference = component; } - ~NotifyIconNativeWindow() { + ~NotifyIconNativeWindow() + { // This same post is done in Control's Dispose method, so if you change // it, change it there too. // - if (Handle != IntPtr.Zero) { + if (Handle != IntPtr.Zero) + { UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), Interop.WindowMessages.WM_CLOSE, 0, 0); } - + // This releases the handle from our window proc, re-routing it back to // the system. } - public void LockReference(bool locked) { - if (locked) { - if (!rootRef.IsAllocated) { + public void LockReference(bool locked) + { + if (locked) + { + if (!rootRef.IsAllocated) + { rootRef = GCHandle.Alloc(reference, GCHandleType.Normal); } } - else { - if (rootRef.IsAllocated) { + else + { + if (rootRef.IsAllocated) + { rootRef.Free(); } } } - protected override void OnThreadException(Exception e) { + protected override void OnThreadException(Exception e) + { Application.OnThreadException(e); } /// /// Pass messages on to the NotifyIcon object's wndproc handler. /// - protected override void WndProc(ref Message m) { + protected override void WndProc(ref Message m) + { Debug.Assert(reference != null, "NotifyIcon was garbage collected while it was still visible. How did we let that happen?"); reference.WndProc(ref m); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDown.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDown.cs index 94c0631a994..e5483e1fd18 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDown.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDown.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System; using System.ComponentModel; @@ -26,16 +27,17 @@ namespace System.Windows.Forms { DefaultBindingProperty(nameof(Value)), SRDescription(nameof(SR.DescriptionNumericUpDown)) ] - public class NumericUpDown : UpDownBase, ISupportInitialize { - - private static readonly decimal DefaultValue = decimal.Zero; - private static readonly decimal DefaultMinimum = decimal.Zero; - private static readonly decimal DefaultMaximum = (decimal)100.0; - private const int DefaultDecimalPlaces = 0; - private static readonly decimal DefaultIncrement = decimal.One; - private const bool DefaultThousandsSeparator = false; - private const bool DefaultHexadecimal = false; - private const int InvalidValue = -1; + public class NumericUpDown : UpDownBase, ISupportInitialize + { + + private static readonly decimal DefaultValue = decimal.Zero; + private static readonly decimal DefaultMinimum = decimal.Zero; + private static readonly decimal DefaultMaximum = (decimal)100.0; + private const int DefaultDecimalPlaces = 0; + private static readonly decimal DefaultIncrement = decimal.One; + private const bool DefaultThousandsSeparator = false; + private const bool DefaultHexadecimal = false; + private const int InvalidValue = -1; ////////////////////////////////////////////////////////////// // Member variables @@ -64,7 +66,7 @@ public class NumericUpDown : UpDownBase, ISupportInitialize { // Internal storage of the current value private decimal currentValue = DefaultValue; - private bool currentValueChanged; + private bool currentValueChanged; // Event handler for the onValueChanged event private EventHandler onValueChanged = null; @@ -86,9 +88,10 @@ public class NumericUpDown : UpDownBase, ISupportInitialize { SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // "0" is the default value for numeric up down. // So we don't have to localize it. ] - public NumericUpDown() : base() { + public NumericUpDown() : base() + { // this class overrides GetPreferredSizeCore, let Control automatically cache the result - SetState2(STATE2_USEPREFERREDSIZECACHE, true); + SetState2(STATE2_USEPREFERREDSIZECACHE, true); Text = "0"; StopAcceleration(); } @@ -98,7 +101,7 @@ public NumericUpDown() : base() { // ////////////////////////////////////////////////////////////// - + /// /// Specifies the acceleration information. /// @@ -106,9 +109,12 @@ public NumericUpDown() : base() { Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public NumericUpDownAccelerationCollection Accelerations { - get { - if( this.accelerations == null ){ + public NumericUpDownAccelerationCollection Accelerations + { + get + { + if (this.accelerations == null) + { this.accelerations = new NumericUpDownAccelerationCollection(); } return this.accelerations; @@ -123,14 +129,18 @@ public NumericUpDownAccelerationCollection Accelerations { DefaultValue(NumericUpDown.DefaultDecimalPlaces), SRDescription(nameof(SR.NumericUpDownDecimalPlacesDescr)) ] - public int DecimalPlaces { + public int DecimalPlaces + { - get { + get + { return decimalPlaces; } - set { - if (value < 0 || value > 99) { + set + { + if (value < 0 || value > 99) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidBoundArgument, nameof(DecimalPlaces), value, 0, 99)); } decimalPlaces = value; @@ -148,13 +158,16 @@ public int DecimalPlaces { DefaultValue(NumericUpDown.DefaultHexadecimal), SRDescription(nameof(SR.NumericUpDownHexadecimalDescr)) ] - public bool Hexadecimal { + public bool Hexadecimal + { - get { + get + { return hexadecimal; } - set { + set + { hexadecimal = value; UpdateEditText(); } @@ -169,21 +182,27 @@ public bool Hexadecimal { SRCategory(nameof(SR.CatData)), SRDescription(nameof(SR.NumericUpDownIncrementDescr)) ] - public decimal Increment { + public decimal Increment + { - get { - if (this.accelerationsCurrentIndex != InvalidValue) { + get + { + if (this.accelerationsCurrentIndex != InvalidValue) + { return this.Accelerations[this.accelerationsCurrentIndex].Increment; } return this.increment; } - set { - if (value < 0.0m) { + set + { + if (value < 0.0m) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(Increment), value)); } - else { + else + { this.increment = value; } } @@ -198,20 +217,24 @@ public decimal Increment { RefreshProperties(RefreshProperties.All), SRDescription(nameof(SR.NumericUpDownMaximumDescr)) ] - public decimal Maximum { + public decimal Maximum + { - get { + get + { return maximum; } - set { + set + { maximum = value; - if (minimum > maximum) { + if (minimum > maximum) + { minimum = maximum; } - + Value = Constrain(currentValue); - + Debug.Assert(maximum == value, "Maximum != what we just set it to!"); } } @@ -224,18 +247,22 @@ public decimal Maximum { RefreshProperties(RefreshProperties.All), SRDescription(nameof(SR.NumericUpDownMinimumDescr)) ] - public decimal Minimum { + public decimal Minimum + { - get { + get + { return minimum; } - set { + set + { minimum = value; - if (minimum > maximum) { + if (minimum > maximum) + { maximum = value; } - + Value = Constrain(currentValue); Debug.Assert(minimum.Equals(value), "Minimum != what we just set it to!"); @@ -247,24 +274,29 @@ public decimal Minimum { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Padding Padding { + public new Padding Padding + { get { return base.Padding; } - set { base.Padding = value;} + set { base.Padding = value; } } [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - new public event EventHandler PaddingChanged { - add => base.PaddingChanged += value; - remove => base.PaddingChanged -= value; } + new public event EventHandler PaddingChanged + { + add => base.PaddingChanged += value; + remove => base.PaddingChanged -= value; + } /// /// Determines whether the UpDownButtons have been pressed for enough time to activate acceleration. /// - private bool Spinning { - get{ + private bool Spinning + { + get + { return this.accelerations != null && this.buttonPressedStartTime != InvalidValue; } } @@ -276,25 +308,29 @@ private bool Spinning { /// [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never), - Bindable(false), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) + Bindable(false), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] // We're just overriding this to make it non-browsable. - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TextChanged { + new public event EventHandler TextChanged + { add => base.TextChanged += value; remove => base.TextChanged -= value; } - + /// /// Gets or sets a value indicating whether a thousands /// separator is displayed in the up-down control when appropriate. @@ -305,13 +341,16 @@ public override string Text { Localizable(true), SRDescription(nameof(SR.NumericUpDownThousandsSeparatorDescr)) ] - public bool ThousandsSeparator { + public bool ThousandsSeparator + { - get { + get + { return thousandsSeparator; } - set { + set + { thousandsSeparator = value; UpdateEditText(); } @@ -329,26 +368,33 @@ public bool ThousandsSeparator { Bindable(true), SRDescription(nameof(SR.NumericUpDownValueDescr)) ] - public decimal Value { + public decimal Value + { - get { - if (UserEdit) { + get + { + if (UserEdit) + { ValidateEditText(); } return currentValue; } - set { - if (value != currentValue) { - - if (!initializing && ((value < minimum) || (value > maximum))) { + set + { + if (value != currentValue) + { + + if (!initializing && ((value < minimum) || (value > maximum))) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidBoundArgument, nameof(Value), value, $"'{nameof(Minimum)}'", $"'{nameof(Maximum)}'")); } - else { - currentValue = value; - + else + { + currentValue = value; + OnValueChanged(EventArgs.Empty); - currentValueChanged = true; + currentValueChanged = true; UpdateEditText(); } } @@ -367,7 +413,8 @@ public decimal Value { /// /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.NumericUpDownOnValueChangedDescr))] - public event EventHandler ValueChanged { + public event EventHandler ValueChanged + { add => onValueChanged += value; remove => onValueChanged -= value; } @@ -375,30 +422,35 @@ public event EventHandler ValueChanged { /// /// Handles tasks required when the control is being initialized. /// - public void BeginInit() { + public void BeginInit() + { initializing = true; } // // Returns the provided value constrained to be within the min and max. // - private decimal Constrain(decimal value) { + private decimal Constrain(decimal value) + { Debug.Assert(minimum <= maximum, "minimum > maximum"); - if (value < minimum) { + if (value < minimum) + { value = minimum; } - if (value > maximum) { + if (value > maximum) + { value = maximum; } - + return value; } - - protected override AccessibleObject CreateAccessibilityInstance() { + + protected override AccessibleObject CreateAccessibilityInstance() + { return new NumericUpDownAccessibleObject(this); } @@ -407,10 +459,12 @@ protected override AccessibleObject CreateAccessibilityInstance() { /// Decrements the value of the up-down control. /// /// - public override void DownButton() { + public override void DownButton() + { SetNextAcceleration(); - if (UserEdit) { + if (UserEdit) + { ParseEditText(); } @@ -418,20 +472,24 @@ public override void DownButton() { // Operations on Decimals can throw OverflowException. // - try{ + try + { newValue -= this.Increment; - if (newValue < minimum){ + if (newValue < minimum) + { newValue = minimum; - if( this.Spinning){ + if (this.Spinning) + { StopAcceleration(); } } } - catch( OverflowException ){ + catch (OverflowException) + { newValue = minimum; } - + Value = newValue; } @@ -440,7 +498,8 @@ public override void DownButton() { /// Called when initialization of the control is complete. /// /// - public void EndInit() { + public void EndInit() + { initializing = false; Value = Constrain(currentValue); UpdateEditText(); @@ -449,22 +508,26 @@ public void EndInit() { /// /// Overridden to set/reset acceleration variables. /// - protected override void OnKeyDown(KeyEventArgs e) { - if (base.InterceptArrowKeys && (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down) && !this.Spinning) { - StartAcceleration(); + protected override void OnKeyDown(KeyEventArgs e) + { + if (base.InterceptArrowKeys && (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down) && !this.Spinning) + { + StartAcceleration(); } - + base.OnKeyDown(e); } - + /// /// Overridden to set/reset acceleration variables. /// - protected override void OnKeyUp(KeyEventArgs e) { - if (base.InterceptArrowKeys && (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)) { - StopAcceleration(); + protected override void OnKeyUp(KeyEventArgs e) + { + if (base.InterceptArrowKeys && (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)) + { + StopAcceleration(); } - + base.OnKeyUp(e); } @@ -474,55 +537,64 @@ protected override void OnKeyUp(KeyEventArgs e) { /// the decimal point, and editing keystrokes (backspace). /// /// - protected override void OnTextBoxKeyPress(object source, KeyPressEventArgs e) { + protected override void OnTextBoxKeyPress(object source, KeyPressEventArgs e) + { base.OnTextBoxKeyPress(source, e); - - NumberFormatInfo numberFormatInfo = System.Globalization.CultureInfo.CurrentCulture.NumberFormat; + + NumberFormatInfo numberFormatInfo = System.Globalization.CultureInfo.CurrentCulture.NumberFormat; string decimalSeparator = numberFormatInfo.NumberDecimalSeparator; string groupSeparator = numberFormatInfo.NumberGroupSeparator; string negativeSign = numberFormatInfo.NegativeSign; - + string keyInput = e.KeyChar.ToString(); - - if (char.IsDigit(e.KeyChar)) { + + if (char.IsDigit(e.KeyChar)) + { // Digits are OK } - else if (keyInput.Equals(decimalSeparator) || keyInput.Equals(groupSeparator) || - keyInput.Equals(negativeSign)) { + else if (keyInput.Equals(decimalSeparator) || keyInput.Equals(groupSeparator) || + keyInput.Equals(negativeSign)) + { // Decimal separator is OK } - else if (e.KeyChar == '\b') { + else if (e.KeyChar == '\b') + { // Backspace key is OK } - else if (Hexadecimal && ((e.KeyChar >= 'a' && e.KeyChar <= 'f') || e.KeyChar >= 'A' && e.KeyChar <= 'F')) { + else if (Hexadecimal && ((e.KeyChar >= 'a' && e.KeyChar <= 'f') || e.KeyChar >= 'A' && e.KeyChar <= 'F')) + { // Hexadecimal digits are OK } - else if ((ModifierKeys & (Keys.Control | Keys.Alt)) != 0) { + else if ((ModifierKeys & (Keys.Control | Keys.Alt)) != 0) + { // Let the edit control handle control and alt key combinations } - else { + else + { // Eat this invalid key and beep e.Handled = true; SafeNativeMethods.MessageBeep(0); } } - + /// /// Raises the event. /// - protected virtual void OnValueChanged(EventArgs e) { + protected virtual void OnValueChanged(EventArgs e) + { // Call the event handler - if (onValueChanged != null) { + if (onValueChanged != null) + { onValueChanged(this, e); } } - protected override void OnLostFocus(EventArgs e) + protected override void OnLostFocus(EventArgs e) { base.OnLostFocus(e); - if (UserEdit) + if (UserEdit) { UpdateEditText(); } @@ -531,14 +603,16 @@ protected override void OnLostFocus(EventArgs e) /// /// Overridden to start/end acceleration. /// - internal override void OnStartTimer() { + internal override void OnStartTimer() + { StartAcceleration(); } /// /// Overridden to start/end acceleration. /// - internal override void OnStopTimer() { + internal override void OnStopTimer() + { StopAcceleration(); } @@ -548,45 +622,54 @@ internal override void OnStopTimer() { /// numeric value and evaluates it. /// /// - protected void ParseEditText() { + protected void ParseEditText() + { Debug.Assert(UserEdit == true, "ParseEditText() - UserEdit == false"); - try { + try + { // Verify that the user is not starting the string with a "-" // before attempting to set the Value property since a "-" is a valid character with // which to start a string representing a negative number. if (!string.IsNullOrEmpty(Text) && - !(Text.Length == 1 && Text == "-")) { - if (Hexadecimal) { + !(Text.Length == 1 && Text == "-")) + { + if (Hexadecimal) + { Value = Constrain(Convert.ToDecimal(Convert.ToInt32(Text, 16))); } - else { - Value = Constrain(decimal.Parse(Text, CultureInfo.CurrentCulture)); + else + { + Value = Constrain(decimal.Parse(Text, CultureInfo.CurrentCulture)); } } } - catch { + catch + { // Leave value as it is } - finally { - UserEdit = false; + finally + { + UserEdit = false; } } /// /// Updates the index of the UpDownNumericAcceleration entry to use (if needed). /// - private void SetNextAcceleration() { + private void SetNextAcceleration() + { // Spinning will check if accelerations is null. - if(this.Spinning && this.accelerationsCurrentIndex < (this.accelerations.Count - 1)) { // if index not the last entry ... + if (this.Spinning && this.accelerationsCurrentIndex < (this.accelerations.Count - 1)) + { // if index not the last entry ... // Ticks are in 100-nanoseconds (1E-7 seconds). - long nowTicks = DateTime.Now.Ticks; + long nowTicks = DateTime.Now.Ticks; long buttonPressedElapsedTime = nowTicks - this.buttonPressedStartTime; - long accelerationInterval = 10000000L * this.accelerations[this.accelerationsCurrentIndex + 1].Seconds; // next entry. - + long accelerationInterval = 10000000L * this.accelerations[this.accelerationsCurrentIndex + 1].Seconds; // next entry. + // If Up/Down button pressed for more than the current acceleration entry interval, get next entry in the accel table. - if( buttonPressedElapsedTime > accelerationInterval ) + if (buttonPressedElapsedTime > accelerationInterval) { this.buttonPressedStartTime = nowTicks; this.accelerationsCurrentIndex++; @@ -594,86 +677,99 @@ private void SetNextAcceleration() { } } - private void ResetIncrement() { + private void ResetIncrement() + { Increment = DefaultIncrement; } - private void ResetMaximum() { - Maximum = DefaultMaximum; + private void ResetMaximum() + { + Maximum = DefaultMaximum; } - private void ResetMinimum() { + private void ResetMinimum() + { Minimum = DefaultMinimum; } - private void ResetValue() { + private void ResetValue() + { Value = DefaultValue; } - + /// /// Indicates whether the property should be /// persisted. /// - private bool ShouldSerializeIncrement() { + private bool ShouldSerializeIncrement() + { return !Increment.Equals(NumericUpDown.DefaultIncrement); } /// /// Indicates whether the property should be persisted. /// - private bool ShouldSerializeMaximum() { + private bool ShouldSerializeMaximum() + { return !Maximum.Equals(NumericUpDown.DefaultMaximum); } /// /// Indicates whether the property should be persisted. /// - private bool ShouldSerializeMinimum() { + private bool ShouldSerializeMinimum() + { return !Minimum.Equals(NumericUpDown.DefaultMinimum); } /// /// Indicates whether the property should be persisted. /// - private bool ShouldSerializeValue() { + private bool ShouldSerializeValue() + { return !Value.Equals(NumericUpDown.DefaultValue); } - + /// /// Records when UpDownButtons are pressed to enable acceleration. /// - private void StartAcceleration() { + private void StartAcceleration() + { this.buttonPressedStartTime = DateTime.Now.Ticks; } /// /// Reset when UpDownButtons are pressed. /// - private void StopAcceleration() { + private void StopAcceleration() + { this.accelerationsCurrentIndex = InvalidValue; - this.buttonPressedStartTime = InvalidValue; + this.buttonPressedStartTime = InvalidValue; } /// /// Provides some interesting info about this control in String form. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); s += ", Minimum = " + Minimum.ToString(CultureInfo.CurrentCulture) + ", Maximum = " + Maximum.ToString(CultureInfo.CurrentCulture); return s; } - + /// /// /// Increments the value of the up-down control. /// /// - public override void UpButton() { + public override void UpButton() + { SetNextAcceleration(); - if (UserEdit) { + if (UserEdit) + { ParseEditText(); } @@ -681,31 +777,38 @@ public override void UpButton() { // Operations on Decimals can throw OverflowException. // - try{ + try + { newValue += this.Increment; - if (newValue > maximum){ + if (newValue > maximum) + { newValue = maximum; - if( this.Spinning){ + if (this.Spinning) + { StopAcceleration(); } } } - catch( OverflowException ){ + catch (OverflowException) + { newValue = maximum; } - Value = newValue; + Value = newValue; } - private string GetNumberText(decimal num) { + private string GetNumberText(decimal num) + { string text; - - if (Hexadecimal) { + + if (Hexadecimal) + { text = ((long)num).ToString("X", CultureInfo.InvariantCulture); Debug.Assert(text == text.ToUpper(CultureInfo.InvariantCulture), "GetPreferredSize assumes hex digits to be uppercase."); } - else { + else + { text = num.ToString((ThousandsSeparator ? "N" : "F") + DecimalPlaces.ToString(CultureInfo.CurrentCulture), CultureInfo.CurrentCulture); } return text; @@ -716,15 +819,18 @@ private string GetNumberText(decimal num) { /// Displays the current value of the up-down control in the appropriate format. /// /// - protected override void UpdateEditText() { + protected override void UpdateEditText() + { // If we're initializing, we don't want to update the edit text yet, // just in case the value is invalid. - if (initializing) { + if (initializing) + { return; } // If the current value is user-edited, then parse this value before reformatting - if (UserEdit) { + if (UserEdit) + { ParseEditText(); } @@ -732,7 +838,8 @@ protected override void UpdateEditText() { // before attempting to set the Value property since a "-" is a valid character with // which to start a string representing a negative number. if (currentValueChanged || (!string.IsNullOrEmpty(Text) && - !(Text.Length == 1 && Text == "-"))) { + !(Text.Length == 1 && Text == "-"))) + { currentValueChanged = false; ChangingText = true; @@ -752,7 +859,8 @@ protected override void UpdateEditText() { /// the text displayed in the up-down control. /// /// - protected override void ValidateEditText() { + protected override void ValidateEditText() + { // See if the edit text parses to a valid decimal ParseEditText(); @@ -762,34 +870,41 @@ protected override void ValidateEditText() { // This is not a breaking change -- Even though this control previously autosized to hieght, // it didn't actually have an AutoSize property. The new AutoSize property enables the // smarter behavior. - internal override Size GetPreferredSizeCore(Size proposedConstraints) { + internal override Size GetPreferredSizeCore(Size proposedConstraints) + { int height = PreferredHeight; - + int baseSize = Hexadecimal ? 16 : 10; int digit = GetLargestDigit(0, baseSize); // The floor of log is intentionally 1 less than the number of digits. We initialize // testNumber to account for the missing digit. int numDigits = (int)Math.Floor(Math.Log(Math.Max(-(double)Minimum, (double)Maximum), baseSize)); int maxDigits; - if (this.Hexadecimal) { + if (this.Hexadecimal) + { maxDigits = (int)Math.Floor(Math.Log(long.MaxValue, baseSize)); } - else { + else + { maxDigits = (int)Math.Floor(Math.Log((double)decimal.MaxValue, baseSize)); } bool maxDigitsReached = numDigits >= maxDigits; decimal testNumber; - + // preinitialize testNumber with the leading digit - if(digit != 0 || numDigits == 1) { + if (digit != 0 || numDigits == 1) + { testNumber = digit; - } else { + } + else + { // zero can not be the leading digit if we need more than // one digit. (0*baseSize = 0 in the loop below) testNumber = GetLargestDigit(1, baseSize); } - if (maxDigitsReached) { + if (maxDigitsReached) + { // Prevent @@ -797,46 +912,56 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) { } // e.g., if the lagest digit is 7, and we can have 3 digits, the widest string would be "777" - for(int i = 0; i < numDigits; i++) { + for (int i = 0; i < numDigits; i++) + { testNumber = testNumber * baseSize + digit; } int textWidth = TextRenderer.MeasureText(GetNumberText(testNumber), this.Font).Width; - if (maxDigitsReached) { + if (maxDigitsReached) + { string shortText; - if (this.Hexadecimal) { - shortText = ((long) testNumber).ToString("X", CultureInfo.InvariantCulture); + if (this.Hexadecimal) + { + shortText = ((long)testNumber).ToString("X", CultureInfo.InvariantCulture); } - else { + else + { shortText = testNumber.ToString(CultureInfo.CurrentCulture); } int shortTextWidth = TextRenderer.MeasureText(shortText, this.Font).Width; // Adding the width of the one digit that was dropped earlier. // This assumes that no additional thousand separator is added by that digit which is correct. - textWidth += shortTextWidth / (numDigits+1); + textWidth += shortTextWidth / (numDigits + 1); } - + // Call AdjuctWindowRect to add space for the borders int width = SizeFromClientSize(textWidth, height).Width + upDownButtons.Width; return new Size(width, height) + Padding.Size; } - private int GetLargestDigit(int start, int end) { + private int GetLargestDigit(int start, int end) + { int largestDigit = -1; int digitWidth = -1; - for(int i = start; i < end; i++) { + for (int i = start; i < end; i++) + { char ch; - if(i < 10) { + if (i < 10) + { ch = i.ToString(CultureInfo.InvariantCulture)[0]; - } else { + } + else + { ch = (char)('A' + (i - 10)); } Size digitSize = TextRenderer.MeasureText(ch.ToString(), this.Font); - if(digitSize.Width >= digitWidth) { + if (digitSize.Width >= digitWidth) + { digitWidth = digitSize.Width; largestDigit = i; } @@ -844,60 +969,74 @@ private int GetLargestDigit(int start, int end) { Debug.Assert(largestDigit != -1 && digitWidth != -1, "Failed to find largest digit."); return largestDigit; } - - [System.Runtime.InteropServices.ComVisible(true)] - internal class NumericUpDownAccessibleObject : ControlAccessibleObject { - public NumericUpDownAccessibleObject(NumericUpDown owner) : base(owner) { + [System.Runtime.InteropServices.ComVisible(true)] + internal class NumericUpDownAccessibleObject : ControlAccessibleObject + { + + public NumericUpDownAccessibleObject(NumericUpDown owner) : base(owner) + { } /// /// Gets or sets the accessible name. /// - public override string Name { - get { + public override string Name + { + get + { string baseName = base.Name; return ((NumericUpDown)Owner).GetAccessibleName(baseName); } - set { + set + { base.Name = value; } } - - public override AccessibleRole Role { - get { + + public override AccessibleRole Role + { + get + { AccessibleRole role = Owner.AccessibleRole; - if (role != AccessibleRole.Default) { + if (role != AccessibleRole.Default) + { return role; } - else { + else + { return AccessibleRole.SpinButton; } } } - - public override AccessibleObject GetChild(int index) { - if (index >= 0 && index < GetChildCount()) { - + + public override AccessibleObject GetChild(int index) + { + if (index >= 0 && index < GetChildCount()) + { + // TextBox child // - if (index == 0) { + if (index == 0) + { return ((UpDownBase)Owner).TextBox.AccessibilityObject.Parent; } - + // Up/down buttons // - if (index == 1) { + if (index == 1) + { return ((UpDownBase)Owner).UpDownButtonsInternal.AccessibilityObject.Parent; } } - + return null; } - public override int GetChildCount() { + public override int GetChildCount() + { return 2; - } + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDownAcceleration.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDownAcceleration.cs index 4f9453b7e4d..24ec5216e40 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDownAcceleration.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDownAcceleration.cs @@ -2,9 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; - + /// /// Comprises the information specifying how acceleration should be performed /// on a Windows up-down control when the up/down button is pressed for certain @@ -27,7 +28,7 @@ public NumericUpDownAcceleration(int seconds, decimal increment) throw new ArgumentOutOfRangeException(nameof(increment), increment, SR.NumericUpDownLessThanZeroError); } - this.seconds = seconds; + this.seconds = seconds; this.increment = increment; } @@ -54,9 +55,10 @@ public int Seconds /// /// Determines the amount to increment by. /// - public decimal Increment { + public decimal Increment + { - get + get { return this.increment; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDownAccelerationCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDownAccelerationCollection.cs index 8521cc5f235..87b4228e7ef 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDownAccelerationCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDownAccelerationCollection.cs @@ -9,7 +9,7 @@ namespace System.Windows.Forms using System.Collections; using System.Collections.Generic; using System.ComponentModel; - + /// /// Represents a SORTED collection of NumericUpDownAcceleration objects in the NumericUpDown Control. /// The elements in the collection are sorted by the NumericUpDownAcceleration.Seconds property. @@ -21,14 +21,14 @@ public class NumericUpDownAccelerationCollection : MarshalByRefObject, ICollecti /// ICollection implementation. - + /// /// Adds an item (NumericUpDownAcceleration object) to the ICollection. /// The item is added preserving the collection sorted. /// public void Add(NumericUpDownAcceleration acceleration) { - if( acceleration == null ) + if (acceleration == null) { throw new ArgumentNullException(nameof(acceleration)); } @@ -36,9 +36,9 @@ public void Add(NumericUpDownAcceleration acceleration) // Keep the array sorted, insert in the right spot. int index = 0; - while( index < this.items.Count ) + while (index < this.items.Count) { - if( acceleration.Seconds < this.items[index].Seconds ) + if (acceleration.Seconds < this.items[index].Seconds) { break; } @@ -50,7 +50,7 @@ public void Add(NumericUpDownAcceleration acceleration) /// /// Removes all items from the ICollection. /// - public void Clear() + public void Clear() { this.items.Clear(); } @@ -58,7 +58,7 @@ public void Clear() /// /// Determines whether the IList contains a specific value. /// - public bool Contains(NumericUpDownAcceleration acceleration) + public bool Contains(NumericUpDownAcceleration acceleration) { return this.items.Contains(acceleration); } @@ -66,17 +66,17 @@ public bool Contains(NumericUpDownAcceleration acceleration) /// /// Copies the elements of the ICollection to an Array, starting at a particular Array index. /// - public void CopyTo(NumericUpDownAcceleration[] array, int index) + public void CopyTo(NumericUpDownAcceleration[] array, int index) { this.items.CopyTo(array, index); } - + /// /// Gets the number of elements contained in the ICollection. /// public int Count { - get {return this.items.Count;} + get { return this.items.Count; } } /// @@ -85,7 +85,7 @@ public int Count /// public bool IsReadOnly { - get {return false;} + get { return false; } } /// @@ -95,10 +95,10 @@ public bool Remove(NumericUpDownAcceleration acceleration) { return this.items.Remove(acceleration); } - + /// IEnumerable implementation. - - + + /// /// Returns an enumerator that can iterate through the collection. /// @@ -113,7 +113,7 @@ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() } /// NumericUpDownAccelerationCollection methods. - + /// /// Class constructor. /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/OpenFileDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/OpenFileDialog.cs index 410e04712a7..6053f1971b9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/OpenFileDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/OpenFileDialog.cs @@ -182,7 +182,7 @@ private protected override string[] ProcessVistaFiles(FileDialogNative.IFileDial results.GetCount(out count); string[] files = new string[count]; for (uint i = 0; i < count; ++i) - { + { FileDialogNative.IShellItem item; results.GetItemAt(i, out item); files[unchecked((int)i)] = GetFilePathFromShellItem(item); @@ -190,7 +190,7 @@ private protected override string[] ProcessVistaFiles(FileDialogNative.IFileDial return files; } else - { + { FileDialogNative.IShellItem item; openDialog.GetResult(out item); return new string[] { GetFilePathFromShellItem(item) }; @@ -244,7 +244,7 @@ public string[] SafeFileNames } private protected override bool SettingsSupportVistaDialog - { + { get => base.SettingsSupportVistaDialog && !ShowReadOnly; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Padding.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Padding.cs index 070434d9ef7..ee6ce5188c1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Padding.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Padding.cs @@ -137,7 +137,7 @@ public override bool Equals(object other) { return false; } - + return this == otherPadding; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PaintEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PaintEventArgs.cs index 0cc328fba64..cb7563ac08e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PaintEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PaintEventArgs.cs @@ -36,7 +36,7 @@ public class PaintEventArgs : EventArgs, IDisposable #if DEBUG private static readonly TraceSwitch s_paintEventFinalizationSwitch = new TraceSwitch("PaintEventFinalization", "Tracks the creation and finalization of PaintEvent objects"); - + internal static string GetAllocationStack() { if (s_paintEventFinalizationSwitch.TraceVerbose) @@ -101,7 +101,7 @@ public System.Drawing.Graphics Graphics _graphics.PageUnit = GraphicsUnit.Pixel; _savedGraphicsState = _graphics.Save(); // See ResetGraphics() below } - + return _graphics; } } @@ -118,8 +118,8 @@ public void Dispose() protected virtual void Dispose(bool disposing) { - if (disposing) - { + if (disposing) + { // Only dispose the graphics object if we created it via the dc. if (_graphics != null && _dc != IntPtr.Zero) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Panel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Panel.cs index cd5eafac11d..40e1653f11f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Panel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Panel.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; @@ -29,7 +30,8 @@ namespace System.Windows.Forms { Designer("System.Windows.Forms.Design.PanelDesigner, " + AssemblyRef.SystemDesign), SRDescription(nameof(SR.DescriptionPanel)) ] - public class Panel : ScrollableControl { + public class Panel : ScrollableControl + { private BorderStyle borderStyle = System.Windows.Forms.BorderStyle.None; @@ -37,9 +39,10 @@ public class Panel : ScrollableControl { /// Initializes a new instance of the class. /// public Panel() - : base() { + : base() + { // this class overrides GetPreferredSizeCore, let Control automatically cache the result - SetState2(STATE2_USEPREFERREDSIZECACHE, true); + SetState2(STATE2_USEPREFERREDSIZECACHE, true); TabStop = false; SetStyle(ControlStyles.Selectable | ControlStyles.AllPaintingInWmPaint, false); @@ -76,26 +79,33 @@ public override bool AutoSize /// [ SRDescription(nameof(SR.ControlAutoSizeModeDescr)), - SRCategory(nameof(SR.CatLayout)), + SRCategory(nameof(SR.CatLayout)), Browsable(true), DefaultValue(AutoSizeMode.GrowOnly), Localizable(true) ] - public virtual AutoSizeMode AutoSizeMode { - get { + public virtual AutoSizeMode AutoSizeMode + { + get + { return GetAutoSizeMode(); } - set { - if (!ClientUtils.IsEnumValid(value, (int)value, (int)AutoSizeMode.GrowAndShrink, (int)AutoSizeMode.GrowOnly)){ + set + { + if (!ClientUtils.IsEnumValid(value, (int)value, (int)AutoSizeMode.GrowAndShrink, (int)AutoSizeMode.GrowOnly)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AutoSizeMode)); } - if (GetAutoSizeMode() != value) { + if (GetAutoSizeMode() != value) + { SetAutoSizeMode(value); - if(ParentInternal != null) { + 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(ParentInternal.LayoutEngine == DefaultLayout.Instance) { + if (ParentInternal.LayoutEngine == DefaultLayout.Instance) + { ParentInternal.LayoutEngine.InitLayout(this, BoundsSpecified.Size); } LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.AutoSize); @@ -114,13 +124,17 @@ public virtual AutoSizeMode AutoSizeMode { DispId(NativeMethods.ActiveX.DISPID_BORDERSTYLE), SRDescription(nameof(SR.PanelBorderStyleDescr)) ] - public BorderStyle BorderStyle { - get { + public BorderStyle BorderStyle + { + get + { return borderStyle; } - set { - if (borderStyle != value) { + set + { + if (borderStyle != value) + { //valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)) { @@ -139,15 +153,18 @@ public BorderStyle BorderStyle { /// however, forget to call base.getCreateParams() first to get the struct /// filled up with the basic info. /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ExStyle |= NativeMethods.WS_EX_CONTROLPARENT; cp.ExStyle &= (~NativeMethods.WS_EX_CLIENTEDGE); cp.Style &= (~NativeMethods.WS_BORDER); - switch (borderStyle) { + switch (borderStyle) + { case BorderStyle.Fixed3D: cp.ExStyle |= NativeMethods.WS_EX_CLIENTEDGE; break; @@ -163,13 +180,16 @@ protected override CreateParams CreateParams { /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(200, 100); } } - internal override Size GetPreferredSizeCore(Size proposedSize) { + internal override Size GetPreferredSizeCore(Size proposedSize) + { // Translating 0,0 from ClientSize to actual Size tells us how much space // is required for the borders. Size borderSize = SizeFromClientSize(Size.Empty); @@ -180,21 +200,24 @@ internal override Size GetPreferredSizeCore(Size proposedSize) { /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event KeyEventHandler KeyUp { + public new event KeyEventHandler KeyUp + { add => base.KeyUp += value; remove => base.KeyUp -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event KeyEventHandler KeyDown { + public new event KeyEventHandler KeyDown + { add => base.KeyDown += value; remove => base.KeyDown -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event KeyPressEventHandler KeyPress { + public new event KeyPressEventHandler KeyPress + { add => base.KeyPress += value; remove => base.KeyPress -= value; } @@ -202,11 +225,14 @@ internal override Size GetPreferredSizeCore(Size proposedSize) { /// /// [DefaultValue(false)] - new public bool TabStop { - get { + new public bool TabStop + { + get + { return base.TabStop; } - set { + set + { base.TabStop = value; } } @@ -214,17 +240,21 @@ internal override Size GetPreferredSizeCore(Size proposedSize) { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Bindable(false)] - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TextChanged { + new public event EventHandler TextChanged + { add => base.TextChanged += value; remove => base.TextChanged -= value; } @@ -235,19 +265,24 @@ public override string Text { /// the event, but should not forget to call base.onResize() to /// ensure that the event is still fired for external listeners. /// - protected override void OnResize(EventArgs eventargs) { - if (DesignMode && borderStyle == BorderStyle.None) { + protected override void OnResize(EventArgs eventargs) + { + if (DesignMode && borderStyle == BorderStyle.None) + { Invalidate(); } base.OnResize(eventargs); } - - internal override void PrintToMetaFileRecursive(HandleRef hDC, IntPtr lParam, Rectangle bounds) { + + internal override void PrintToMetaFileRecursive(HandleRef hDC, IntPtr lParam, Rectangle bounds) + { base.PrintToMetaFileRecursive(hDC, lParam, bounds); - using (WindowsFormsUtils.DCMapping mapping = new WindowsFormsUtils.DCMapping(hDC, bounds)) { - using(Graphics g = Graphics.FromHdcInternal(hDC.Handle)) { + using (WindowsFormsUtils.DCMapping mapping = new WindowsFormsUtils.DCMapping(hDC, bounds)) + { + using (Graphics g = Graphics.FromHdcInternal(hDC.Handle)) + { ControlPaint.PrintBorder(g, new Rectangle(Point.Empty, Size), BorderStyle, Border3DStyle.Sunken); } } @@ -255,7 +290,8 @@ internal override void PrintToMetaFileRecursive(HandleRef hDC, IntPtr lParam, Re /// /// - private static string StringFromBorderStyle(BorderStyle value) { + private static string StringFromBorderStyle(BorderStyle value) + { Type borderStyleType = typeof(BorderStyle); return (ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)) ? (borderStyleType.ToString() + "." + value.ToString()) : "[Invalid BorderStyle]"; } @@ -263,7 +299,8 @@ private static string StringFromBorderStyle(BorderStyle value) { /// /// Returns a string representation for this control. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); return s + ", BorderStyle: " + StringFromBorderStyle(borderStyle); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs index f50de7dea8b..1c0e6d41107 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.Runtime.Versioning; @@ -33,7 +34,8 @@ namespace System.Windows.Forms { Designer("System.Windows.Forms.Design.PictureBoxDesigner, " + AssemblyRef.SystemDesign), SRDescription(nameof(SR.DescriptionPictureBox)) ] - public class PictureBox : Control, ISupportInitialize { + public class PictureBox : Control, ISupportInitialize + { /// /// The type of border this control will have. @@ -55,84 +57,88 @@ public class PictureBox : Control, ISupportInitialize { bool currentlyAnimating; // Instance members for asynchronous behavior - private AsyncOperation currentAsyncLoadOperation = null; - private string imageLocation; - private Image initialImage; - private Image errorImage; - private int contentLength; - private int totalBytesRead; - private MemoryStream tempDownloadStream; - private const int readBlockSize = 4096; - private byte[] readBuffer = null; + private AsyncOperation currentAsyncLoadOperation = null; + private string imageLocation; + private Image initialImage; + private Image errorImage; + private int contentLength; + private int totalBytesRead; + private MemoryStream tempDownloadStream; + private const int readBlockSize = 4096; + private byte[] readBuffer = null; private ImageInstallationType imageInstallationType; private SendOrPostCallback loadCompletedDelegate = null; private SendOrPostCallback loadProgressDelegate = null; - private bool handleValid = false; - private object internalSyncObject = new object(); + private bool handleValid = false; + private object internalSyncObject = new object(); // These default images will be demand loaded. - private Image defaultInitialImage = null; - private Image defaultErrorImage = null; + private Image defaultInitialImage = null; + private Image defaultErrorImage = null; - [ ThreadStatic ] - private static Image defaultInitialImageForThread = null; - - [ ThreadStatic ] - private static Image defaultErrorImageForThread = null; + [ThreadStatic] + private static Image defaultInitialImageForThread = null; + + [ThreadStatic] + private static Image defaultErrorImageForThread = null; private static readonly object defaultInitialImageKey = new object(); private static readonly object defaultErrorImageKey = new object(); private static readonly object loadCompletedKey = new object(); private static readonly object loadProgressChangedKey = new object(); - - private const int PICTUREBOXSTATE_asyncOperationInProgress = 0x00000001; - private const int PICTUREBOXSTATE_cancellationPending = 0x00000002; - private const int PICTUREBOXSTATE_useDefaultInitialImage = 0x00000004; - private const int PICTUREBOXSTATE_useDefaultErrorImage = 0x00000008; - private const int PICTUREBOXSTATE_waitOnLoad = 0x00000010; - private const int PICTUREBOXSTATE_needToLoadImageLocation = 0x00000020; - private const int PICTUREBOXSTATE_inInitialization = 0x00000040; + + private const int PICTUREBOXSTATE_asyncOperationInProgress = 0x00000001; + private const int PICTUREBOXSTATE_cancellationPending = 0x00000002; + private const int PICTUREBOXSTATE_useDefaultInitialImage = 0x00000004; + private const int PICTUREBOXSTATE_useDefaultErrorImage = 0x00000008; + private const int PICTUREBOXSTATE_waitOnLoad = 0x00000010; + private const int PICTUREBOXSTATE_needToLoadImageLocation = 0x00000020; + private const int PICTUREBOXSTATE_inInitialization = 0x00000040; // PERF: take all the bools and put them into a state variable - private System.Collections.Specialized.BitVector32 pictureBoxState; // see PICTUREBOXSTATE_ consts above + private System.Collections.Specialized.BitVector32 pictureBoxState; // see PICTUREBOXSTATE_ consts above // http://msdn.microsoft.com/en-us/library/93z9ee4x(v=VS.100).aspx // if we load an image from a stream, // we must keep the stream open for the lifetime of the Image StreamReader localImageStreamReader = null; Stream uriImageStream = null; - + /// /// Creates a new picture with all default properties and no /// Image. The default PictureBox.SizeMode will be PictureBoxSizeMode.NORMAL. /// /// - public PictureBox() { + public PictureBox() + { // this class overrides GetPreferredSizeCore, let Control automatically cache the result - SetState2(STATE2_USEPREFERREDSIZECACHE, true); + SetState2(STATE2_USEPREFERREDSIZECACHE, true); pictureBoxState = new System.Collections.Specialized.BitVector32(PICTUREBOXSTATE_useDefaultErrorImage | PICTUREBOXSTATE_useDefaultInitialImage); - SetStyle(ControlStyles.Opaque |ControlStyles.Selectable , false); - SetStyle(ControlStyles.OptimizedDoubleBuffer|ControlStyles.SupportsTransparentBackColor, true); + SetStyle(ControlStyles.Opaque | ControlStyles.Selectable, false); + SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.SupportsTransparentBackColor, true); TabStop = false; savedSize = Size; } - + /// /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override bool AllowDrop { - get { + public override bool AllowDrop + { + get + { return base.AllowDrop; } - set { + set + { base.AllowDrop = value; } } @@ -147,18 +153,23 @@ public override bool AllowDrop { DispId(NativeMethods.ActiveX.DISPID_BORDERSTYLE), SRDescription(nameof(SR.PictureBoxBorderStyleDescr)) ] - public BorderStyle BorderStyle { - get { + public BorderStyle BorderStyle + { + get + { return borderStyle; } - set { + set + { //valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(BorderStyle)); } - if (borderStyle != value) { + if (borderStyle != value) + { borderStyle = value; RecreateHandle(); AdjustSize(); @@ -196,17 +207,21 @@ public void CancelAsync() /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new bool CausesValidation { - get { + public new bool CausesValidation + { + get + { return base.CausesValidation; } - set { + set + { base.CausesValidation = value; } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler CausesValidationChanged { + new public event EventHandler CausesValidationChanged + { add => base.CausesValidationChanged += value; remove => base.CausesValidationChanged -= value; } @@ -217,11 +232,14 @@ public void CancelAsync() /// however, forget to call base.getCreateParams() first to get the struct /// filled up with the basic info. /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; - switch (borderStyle) { + switch (borderStyle) + { case BorderStyle.Fixed3D: cp.ExStyle |= NativeMethods.WS_EX_CLIENTEDGE; break; @@ -233,9 +251,11 @@ protected override CreateParams CreateParams { return cp; } } - - protected override ImeMode DefaultImeMode { - get { + + protected override ImeMode DefaultImeMode + { + get + { return ImeMode.Disable; } } @@ -244,8 +264,10 @@ protected override ImeMode DefaultImeMode { /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(100, 50); } } @@ -256,10 +278,12 @@ protected override Size DefaultSize { RefreshProperties(RefreshProperties.All), SRDescription(nameof(SR.PictureBoxErrorImageDescr)) ] - public Image ErrorImage { - - - get { + public Image ErrorImage + { + + + get + { // Strange pictureBoxState[PICTUREBOXSTATE_useDefaultErrorImage] approach used // here to avoid statically loading the default bitmaps from resources at // runtime when they're never used. @@ -279,7 +303,8 @@ public Image ErrorImage { } return errorImage; } - set { + set + { if (ErrorImage != value) { pictureBoxState[PICTUREBOXSTATE_useDefaultErrorImage] = false; @@ -293,17 +318,21 @@ public Image ErrorImage { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Color ForeColor { - get { + public override Color ForeColor + { + get + { return base.ForeColor; } - set { + set + { base.ForeColor = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler ForeColorChanged { + new public event EventHandler ForeColorChanged + { add => base.ForeColorChanged += value; remove => base.ForeColorChanged -= value; } @@ -312,17 +341,21 @@ public override Color ForeColor { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Font Font { - get { + public override Font Font + { + get + { return base.Font; } - set { + set + { base.Font = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler FontChanged { + new public event EventHandler FontChanged + { add => base.FontChanged += value; remove => base.FontChanged -= value; } @@ -336,12 +369,15 @@ public override Font Font { Bindable(true), SRDescription(nameof(SR.PictureBoxImageDescr)) ] - public Image Image { - - get { + public Image Image + { + + get + { return image; } - set { + set + { InstallNewImage(value, ImageInstallationType.DirectlySpecified); } } @@ -354,20 +390,20 @@ public Image Image { RefreshProperties(RefreshProperties.All), SRDescription(nameof(SR.PictureBoxImageLocationDescr)) ] - public string ImageLocation + public string ImageLocation { - get + get { return imageLocation; } - set + set { // Reload even if value hasn't changed, since Image itself may // have changed. imageLocation = value; pictureBoxState[PICTUREBOXSTATE_needToLoadImageLocation] = !string.IsNullOrEmpty(imageLocation); - + // Reset main image if it hasn't been directly specified. if (string.IsNullOrEmpty(imageLocation) && imageInstallationType != ImageInstallationType.DirectlySpecified) @@ -380,72 +416,78 @@ public string ImageLocation // Load immediately, so any error will occur synchronously Load(); } - + Invalidate(); } } - private Rectangle ImageRectangle { - get { + private Rectangle ImageRectangle + { + get + { return ImageRectangleFromSizeMode(sizeMode); } } - + private Rectangle ImageRectangleFromSizeMode(PictureBoxSizeMode mode) { Rectangle result = LayoutUtils.DeflateRect(ClientRectangle, Padding); - if (image != null) { - switch (mode) { - case PictureBoxSizeMode.Normal: - case PictureBoxSizeMode.AutoSize: - // Use image's size rather than client size. - result.Size = image.Size; - break; - - case PictureBoxSizeMode.StretchImage: - // Do nothing, was initialized to the available dimensions. - break; - - case PictureBoxSizeMode.CenterImage: - // Center within the available space. - result.X += (result.Width - image.Width) / 2; - result.Y += (result.Height - image.Height) / 2; - result.Size = image.Size; - break; - - case PictureBoxSizeMode.Zoom: - Size imageSize = image.Size; - float ratio = Math.Min((float)ClientRectangle.Width / (float)imageSize.Width, (float)ClientRectangle.Height / (float)imageSize.Height); - result.Width = (int)(imageSize.Width * ratio); - result.Height = (int) (imageSize.Height * ratio); - result.X = (ClientRectangle.Width - result.Width) /2; - result.Y = (ClientRectangle.Height - result.Height) /2; - break; - - default: - Debug.Fail("Unsupported PictureBoxSizeMode value: " + mode); - break; + if (image != null) + { + switch (mode) + { + case PictureBoxSizeMode.Normal: + case PictureBoxSizeMode.AutoSize: + // Use image's size rather than client size. + result.Size = image.Size; + break; + + case PictureBoxSizeMode.StretchImage: + // Do nothing, was initialized to the available dimensions. + break; + + case PictureBoxSizeMode.CenterImage: + // Center within the available space. + result.X += (result.Width - image.Width) / 2; + result.Y += (result.Height - image.Height) / 2; + result.Size = image.Size; + break; + + case PictureBoxSizeMode.Zoom: + Size imageSize = image.Size; + float ratio = Math.Min((float)ClientRectangle.Width / (float)imageSize.Width, (float)ClientRectangle.Height / (float)imageSize.Height); + result.Width = (int)(imageSize.Width * ratio); + result.Height = (int)(imageSize.Height * ratio); + result.X = (ClientRectangle.Width - result.Width) / 2; + result.Y = (ClientRectangle.Height - result.Height) / 2; + break; + + default: + Debug.Fail("Unsupported PictureBoxSizeMode value: " + mode); + break; } } return result; } - + [ SRCategory(nameof(SR.CatAsynchronous)), Localizable(true), RefreshProperties(RefreshProperties.All), SRDescription(nameof(SR.PictureBoxInitialImageDescr)) ] - public Image InitialImage { - - - get { + public Image InitialImage + { + + + get + { // Strange pictureBoxState[PICTUREBOXSTATE_useDefaultInitialImage] approach // used here to avoid statically loading the default bitmaps from resources at // runtime when they're never used. - + if (initialImage == null && pictureBoxState[PICTUREBOXSTATE_useDefaultInitialImage]) { if (defaultInitialImage == null) @@ -453,7 +495,7 @@ public Image InitialImage { // Can't share images across threads. if (defaultInitialImageForThread == null) { - defaultInitialImageForThread = DpiHelper.GetBitmapFromIcon(typeof(PictureBox), "PictureBox.Loading"); + defaultInitialImageForThread = DpiHelper.GetBitmapFromIcon(typeof(PictureBox), "PictureBox.Loading"); } defaultInitialImage = defaultInitialImageForThread; } @@ -461,7 +503,8 @@ public Image InitialImage { } return initialImage; } - set { + set + { if (InitialImage != value) { pictureBoxState[PICTUREBOXSTATE_useDefaultInitialImage] = false; @@ -469,38 +512,42 @@ public Image InitialImage { initialImage = value; } } - + private void InstallNewImage(Image value, ImageInstallationType installationType) { StopAnimate(); this.image = value; - - LayoutTransaction.DoLayoutIf(AutoSize, this, this, PropertyNames.Image); - + + LayoutTransaction.DoLayoutIf(AutoSize, this, this, PropertyNames.Image); + Animate(); if (installationType != ImageInstallationType.ErrorOrInitial) { AdjustSize(); } this.imageInstallationType = installationType; - + Invalidate(); CommonProperties.xClearPreferredSizeCache(this); } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public ImeMode ImeMode { - get { + new public ImeMode ImeMode + { + get + { return base.ImeMode; } - set { + set + { base.ImeMode = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler ImeModeChanged { + public new event EventHandler ImeModeChanged + { add => base.ImeModeChanged += value; remove => base.ImeModeChanged -= value; } @@ -590,7 +637,7 @@ public void LoadAsync() } pictureBoxState[PICTUREBOXSTATE_asyncOperationInProgress] = true; - + if ((Image == null || (imageInstallationType == ImageInstallationType.ErrorOrInitial)) && InitialImage != null) @@ -599,19 +646,19 @@ public void LoadAsync() } currentAsyncLoadOperation = AsyncOperationManager.CreateOperation(null); - + if (loadCompletedDelegate == null) { loadCompletedDelegate = new SendOrPostCallback(LoadCompletedDelegate); loadProgressDelegate = new SendOrPostCallback(LoadProgressDelegate); readBuffer = new byte[readBlockSize]; } - + pictureBoxState[PICTUREBOXSTATE_needToLoadImageLocation] = false; pictureBoxState[PICTUREBOXSTATE_cancellationPending] = false; contentLength = -1; tempDownloadStream = new MemoryStream(); - + WebRequest req = WebRequest.Create(CalculateUri(imageLocation)); // Invoke BeginGetResponse on a threadpool thread, as it has @@ -639,11 +686,11 @@ private void PostCompleted(Exception error, bool cancelled) } } - private void LoadCompletedDelegate(object arg) + private void LoadCompletedDelegate(object arg) { AsyncCompletedEventArgs e = (AsyncCompletedEventArgs)arg; - Image img = ErrorImage; + Image img = ErrorImage; ImageInstallationType installType = ImageInstallationType.ErrorOrInitial; if (!e.Cancelled && e.Error == null) @@ -665,7 +712,7 @@ private void LoadCompletedDelegate(object arg) { InstallNewImage(img, installType); } - + tempDownloadStream = null; pictureBoxState[PICTUREBOXSTATE_cancellationPending] = false; pictureBoxState[PICTUREBOXSTATE_asyncOperationInProgress] = false; @@ -676,8 +723,8 @@ private void LoadProgressDelegate(object arg) { OnLoadProgressChanged((ProgressChangedEventArgs)arg); } - - private void GetResponseCallback(IAsyncResult result) + + private void GetResponseCallback(IAsyncResult result) { if (pictureBoxState[PICTUREBOXSTATE_cancellationPending]) { @@ -713,7 +760,7 @@ private void GetResponseCallback(IAsyncResult result) } } - private void ReadCallBack(IAsyncResult result) + private void ReadCallBack(IAsyncResult result) { if (pictureBoxState[PICTUREBOXSTATE_cancellationPending]) { @@ -779,8 +826,8 @@ private void ReadCallBack(IAsyncResult result) } } } - - + + [ SRCategory(nameof(SR.CatAsynchronous)), SRDescription(nameof(SR.PictureBoxLoadAsync1Descr)), @@ -811,19 +858,19 @@ public event ProgressChangedEventHandler LoadProgressChanged add => this.Events.AddHandler(loadProgressChangedKey, value); remove => this.Events.RemoveHandler(loadProgressChangedKey, value); } - + private void ResetInitialImage() { pictureBoxState[PICTUREBOXSTATE_useDefaultInitialImage] = true; initialImage = defaultInitialImage; } - + private void ResetErrorImage() { pictureBoxState[PICTUREBOXSTATE_useDefaultErrorImage] = true; errorImage = defaultErrorImage; } - + private void ResetImage() { InstallNewImage(null, ImageInstallationType.DirectlySpecified); @@ -833,17 +880,21 @@ private void ResetImage() /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override RightToLeft RightToLeft { - get { + public override RightToLeft RightToLeft + { + get + { return base.RightToLeft; } - set { + set + { base.RightToLeft = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler RightToLeftChanged { + public new event EventHandler RightToLeftChanged + { add => base.RightToLeftChanged += value; remove => base.RightToLeftChanged -= value; } @@ -853,7 +904,7 @@ private bool ShouldSerializeInitialImage() { return !pictureBoxState[PICTUREBOXSTATE_useDefaultInitialImage]; } - + // Be sure not to re-serialized error image if it's the default. private bool ShouldSerializeErrorImage() { @@ -868,7 +919,7 @@ private bool ShouldSerializeImage() return (imageInstallationType == ImageInstallationType.DirectlySpecified) && (Image != null); } - + /// /// Indicates how the image is displayed. /// @@ -877,24 +928,30 @@ private bool ShouldSerializeImage() SRCategory(nameof(SR.CatBehavior)), Localizable(true), SRDescription(nameof(SR.PictureBoxSizeModeDescr)), - RefreshProperties(RefreshProperties.Repaint) + RefreshProperties(RefreshProperties.Repaint) ] - public PictureBoxSizeMode SizeMode { - get { + public PictureBoxSizeMode SizeMode + { + get + { return sizeMode; } - set { + set + { //valid values are 0x0 to 0x4 if (!ClientUtils.IsEnumValid(value, (int)value, (int)PictureBoxSizeMode.Normal, (int)PictureBoxSizeMode.Zoom)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(PictureBoxSizeMode)); } - if (this.sizeMode != value) { - if (value == PictureBoxSizeMode.AutoSize) { + if (this.sizeMode != value) + { + if (value == PictureBoxSizeMode.AutoSize) + { this.AutoSize = true; SetStyle(ControlStyles.FixedHeight | ControlStyles.FixedWidth, true); } - if (value != PictureBoxSizeMode.AutoSize) { + if (value != PictureBoxSizeMode.AutoSize) + { this.AutoSize = false; SetStyle(ControlStyles.FixedHeight | ControlStyles.FixedWidth, false); savedSize = Size; @@ -906,11 +963,12 @@ public PictureBoxSizeMode SizeMode { } } } - + private static readonly object EVENT_SIZEMODECHANGED = new object(); [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.PictureBoxOnSizeModeChangedDescr))] - public event EventHandler SizeModeChanged { + public event EventHandler SizeModeChanged + { add => Events.AddHandler(EVENT_SIZEMODECHANGED, value); remove => Events.RemoveHandler(EVENT_SIZEMODECHANGED, value); @@ -920,17 +978,21 @@ public event EventHandler SizeModeChanged { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public bool TabStop { - get { + new public bool TabStop + { + get + { return base.TabStop; } - set { + set + { base.TabStop = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TabStopChanged { + new public event EventHandler TabStopChanged + { add => base.TabStopChanged += value; remove => base.TabStopChanged -= value; } @@ -939,17 +1001,21 @@ public event EventHandler SizeModeChanged { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public int TabIndex { - get { + new public int TabIndex + { + get + { return base.TabIndex; } - set { + set + { base.TabIndex = value; } - } + } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TabIndexChanged { + new public event EventHandler TabIndexChanged + { add => base.TabIndexChanged += value; remove => base.TabIndexChanged -= value; } @@ -957,50 +1023,59 @@ public event EventHandler SizeModeChanged { /// /// /// - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Bindable(false)] - public override string Text { - get { + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Bindable(false)] + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TextChanged { + new public event EventHandler TextChanged + { add => base.TextChanged += value; remove => base.TextChanged -= value; } - + /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler Enter { + public new event EventHandler Enter + { add => base.Enter += value; remove => base.Enter -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event KeyEventHandler KeyUp { + public new event KeyEventHandler KeyUp + { add => base.KeyUp += value; remove => base.KeyUp -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event KeyEventHandler KeyDown { + public new event KeyEventHandler KeyDown + { add => base.KeyDown += value; remove => base.KeyDown -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event KeyPressEventHandler KeyPress { + public new event KeyPressEventHandler KeyPress + { add => base.KeyPress += value; remove => base.KeyPress -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler Leave { + public new event EventHandler Leave + { add => base.Leave += value; remove => base.Leave -= value; } @@ -1009,33 +1084,44 @@ public override string Text { /// If the PictureBox has the SizeMode property set to AutoSize, this makes /// sure that the picturebox is large enough to hold the image. /// - private void AdjustSize() { - if (sizeMode == PictureBoxSizeMode.AutoSize) { + private void AdjustSize() + { + if (sizeMode == PictureBoxSizeMode.AutoSize) + { Size = PreferredSize; - } - else { + } + else + { Size = savedSize; } } - private void Animate() { + private void Animate() + { Animate(!DesignMode && Visible && Enabled && ParentInternal != null); } - private void StopAnimate() { + private void StopAnimate() + { Animate(false); } - private void Animate(bool animate) { - if (animate != this.currentlyAnimating) { - if (animate) { - if (this.image != null) { + private void Animate(bool animate) + { + if (animate != this.currentlyAnimating) + { + if (animate) + { + if (this.image != null) + { ImageAnimator.Animate(this.image, new EventHandler(this.OnFrameChanged)); this.currentlyAnimating = animate; } } - else { - if (this.image != null) { + else + { + if (this.image != null) + { ImageAnimator.StopAnimate(this.image, new EventHandler(this.OnFrameChanged)); this.currentlyAnimating = animate; } @@ -1045,8 +1131,10 @@ private void Animate(bool animate) { /// /// - protected override void Dispose(bool disposing) { - if (disposing) { + protected override void Dispose(bool disposing) + { + if (disposing) + { StopAnimate(); } @@ -1055,12 +1143,15 @@ protected override void Dispose(bool disposing) { base.Dispose(disposing); } - private void DisposeImageStream() { - if (localImageStreamReader != null) { + private void DisposeImageStream() + { + if (localImageStreamReader != null) + { localImageStreamReader.Dispose(); localImageStreamReader = null; } - if (uriImageStream != null) { + if (uriImageStream != null) + { uriImageStream.Dispose(); localImageStreamReader = null; } @@ -1068,49 +1159,62 @@ private void DisposeImageStream() { // Overriding this method allows us to get the caching and clamping the proposedSize/output to // MinimumSize / MaximumSize from GetPreferredSize for free. - internal override Size GetPreferredSizeCore(Size proposedSize) { - if (image == null) { + internal override Size GetPreferredSizeCore(Size proposedSize) + { + if (image == null) + { return CommonProperties.GetSpecifiedBounds(this).Size; } - else { + else + { Size bordersAndPadding = SizeFromClientSize(Size.Empty) + Padding.Size; return image.Size + bordersAndPadding; } } - - protected override void OnEnabledChanged(EventArgs e) { + + protected override void OnEnabledChanged(EventArgs e) + { base.OnEnabledChanged(e); Animate(); } - - private void OnFrameChanged(object o, EventArgs e) { - if (Disposing || IsDisposed) { + + private void OnFrameChanged(object o, EventArgs e) + { + if (Disposing || IsDisposed) + { return; } // Handle should be created, before calling the BeginInvoke. - if (InvokeRequired && IsHandleCreated) { - lock (internalSyncObject) { - if (handleValid) { + if (InvokeRequired && IsHandleCreated) + { + lock (internalSyncObject) + { + if (handleValid) + { BeginInvoke(new EventHandler(this.OnFrameChanged), o, e); } return; } } - - Invalidate(); + + Invalidate(); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnHandleDestroyed(EventArgs e) { - lock (internalSyncObject) { + protected override void OnHandleDestroyed(EventArgs e) + { + lock (internalSyncObject) + { handleValid = false; } base.OnHandleDestroyed(e); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnHandleCreated(EventArgs e) { - lock (internalSyncObject) { + protected override void OnHandleCreated(EventArgs e) + { + lock (internalSyncObject) + { handleValid = true; } base.OnHandleCreated(e); @@ -1137,7 +1241,8 @@ protected virtual void OnLoadProgressChanged(ProgressChangedEventArgs e) /// /// Overridden onPaint to make sure that the image is painted correctly. /// - protected override void OnPaint(PaintEventArgs pe) { + protected override void OnPaint(PaintEventArgs pe) + { if (pictureBoxState[PICTUREBOXSTATE_needToLoadImageLocation]) { @@ -1162,19 +1267,20 @@ protected override void OnPaint(PaintEventArgs pe) { image = ErrorImage; } } - - if (image != null) { + + if (image != null) + { Animate(); ImageAnimator.UpdateFrames(this.Image); - + // Error and initial image are drawn centered, non-stretched. Rectangle drawingRect = (imageInstallationType == ImageInstallationType.ErrorOrInitial) ? ImageRectangleFromSizeMode(PictureBoxSizeMode.CenterImage) : ImageRectangle; - + pe.Graphics.DrawImage(image, drawingRect); - + } // Windows draws the border for us (see CreateParams) @@ -1182,12 +1288,14 @@ protected override void OnPaint(PaintEventArgs pe) { } - protected override void OnVisibleChanged(EventArgs e) { + protected override void OnVisibleChanged(EventArgs e) + { base.OnVisibleChanged(e); Animate(); } - protected override void OnParentChanged(EventArgs e) { + protected override void OnParentChanged(EventArgs e) + { base.OnParentChanged(e); Animate(); } @@ -1195,17 +1303,21 @@ protected override void OnParentChanged(EventArgs e) { /// /// OnResize override to invalidate entire control in Stetch mode /// - protected override void OnResize(EventArgs e) { + protected override void OnResize(EventArgs e) + { base.OnResize(e); - if (sizeMode == PictureBoxSizeMode.Zoom || sizeMode == PictureBoxSizeMode.StretchImage || sizeMode == PictureBoxSizeMode.CenterImage || BackgroundImage != null) { + if (sizeMode == PictureBoxSizeMode.Zoom || sizeMode == PictureBoxSizeMode.StretchImage || sizeMode == PictureBoxSizeMode.CenterImage || BackgroundImage != null) + { Invalidate(); } savedSize = Size; } - protected virtual void OnSizeModeChanged(EventArgs e) { + protected virtual void OnSizeModeChanged(EventArgs e) + { EventHandler eh = Events[EVENT_SIZEMODECHANGED] as EventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); } } @@ -1213,7 +1325,8 @@ protected virtual void OnSizeModeChanged(EventArgs e) { /// /// Returns a string representation for this control. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); return s + ", SizeMode: " + sizeMode.ToString("G"); @@ -1225,11 +1338,14 @@ public override string ToString() { DefaultValue(false), SRDescription(nameof(SR.PictureBoxWaitOnLoadDescr)) ] - public bool WaitOnLoad { - get { + public bool WaitOnLoad + { + get + { return pictureBoxState[PICTUREBOXSTATE_waitOnLoad]; } - set { + set + { pictureBoxState[PICTUREBOXSTATE_waitOnLoad] = value; } } @@ -1257,7 +1373,7 @@ void ISupportInitialize.EndInit() // Load when initialization completes, so any error will occur synchronously Load(); } - + pictureBoxState[PICTUREBOXSTATE_inInitialization] = false; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PopupEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PopupEventArgs.cs index cbc417ddaa5..ebc901b8aaa 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PopupEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PopupEventArgs.cs @@ -5,24 +5,24 @@ using System.ComponentModel; using System.Drawing; -namespace System.Windows.Forms +namespace System.Windows.Forms { /// /// This class contains the information a user needs to paint the ToolTip. /// - public class PopupEventArgs : CancelEventArgs + public class PopupEventArgs : CancelEventArgs { /// /// Creates a new PopupEventArgs with the given parameters. /// - public PopupEventArgs(IWin32Window associatedWindow, Control associatedControl, bool isBalloon, Size size) + public PopupEventArgs(IWin32Window associatedWindow, Control associatedControl, bool isBalloon, Size size) { AssociatedWindow = associatedWindow; AssociatedControl = associatedControl; ToolTipSize = size; IsBalloon = isBalloon; } - + /// /// The Associated Window for which the tooltip is being painted. /// @@ -32,7 +32,7 @@ public PopupEventArgs(IWin32Window associatedWindow, Control associatedControl, /// The control for which the tooltip is being painted. /// public Control AssociatedControl { get; } - + /// /// The rectangle outlining the area in which the painting should be done. /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PreviewKeyDownEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PreviewKeyDownEventArgs.cs index 520646b7a8b..9681c9ec87f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PreviewKeyDownEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PreviewKeyDownEventArgs.cs @@ -15,7 +15,7 @@ public PreviewKeyDownEventArgs(Keys keyData) { KeyData = keyData; } - + /// /// Gets the key data for a /// or event. @@ -38,12 +38,12 @@ public Keys KeyCode [SuppressMessage("Microsoft.Performance", "CA1803:AvoidCostlyCallsWherePossible")] // Keys is discontiguous so we have to use Enum.IsDefined. get { - Keys keyGenerated = KeyData & Keys.KeyCode; - if (!Enum.IsDefined(typeof(Keys),(int)keyGenerated)) + Keys keyGenerated = KeyData & Keys.KeyCode; + if (!Enum.IsDefined(typeof(Keys), (int)keyGenerated)) { return Keys.None; } - + return keyGenerated; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PageSetupDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PageSetupDialog.cs index da98c1f489c..86827f3c098 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PageSetupDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PageSetupDialog.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System; @@ -13,7 +14,7 @@ namespace System.Windows.Forms { using System.Runtime.InteropServices; using System.Text; using System.Globalization; - + /// /// Represents /// a dialog box that allows users to manipulate page settings, including margins and paper orientation. @@ -21,7 +22,8 @@ namespace System.Windows.Forms { [DefaultProperty(nameof(Document))] [SRDescription(nameof(SR.DescriptionPageSetupDialog))] // The only event this dialog has is HelpRequested, which isn't very useful - public sealed class PageSetupDialog : CommonDialog { + public sealed class PageSetupDialog : CommonDialog + { // If PrintDocument != null, pageSettings == printDocument.PageSettings private PrintDocument printDocument = null; private PageSettings pageSettings = null; @@ -35,11 +37,12 @@ public sealed class PageSetupDialog : CommonDialog { private bool showHelp; private bool showNetwork; private bool enableMetric; - + /// /// Initializes a new instance of the class. /// - public PageSetupDialog() { + public PageSetupDialog() + { Reset(); } @@ -50,15 +53,18 @@ public PageSetupDialog() { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(true), SRDescription(nameof(SR.PSDallowMarginsDescr)) ] - public bool AllowMargins { - get { + public bool AllowMargins + { + get + { return allowMargins; } - set { + set + { allowMargins = value; } } @@ -69,13 +75,14 @@ public bool AllowMargins { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(true), SRDescription(nameof(SR.PSDallowOrientationDescr)) ] - public bool AllowOrientation { - get { return allowOrientation;} - set { allowOrientation = value;} + public bool AllowOrientation + { + get { return allowOrientation; } + set { allowOrientation = value; } } /// @@ -86,13 +93,14 @@ public bool AllowOrientation { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(true), SRDescription(nameof(SR.PSDallowPaperDescr)) ] - public bool AllowPaper { - get { return allowPaper;} - set { allowPaper = value;} + public bool AllowPaper + { + get { return allowPaper; } + set { allowPaper = value; } } /// @@ -102,13 +110,14 @@ public bool AllowPaper { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(true), SRDescription(nameof(SR.PSDallowPrinterDescr)) ] - public bool AllowPrinter { - get { return allowPrinter;} - set { allowPrinter = value;} + public bool AllowPrinter + { + get { return allowPrinter; } + set { allowPrinter = value; } } /// @@ -117,15 +126,18 @@ public bool AllowPrinter { /// /// [ - SRCategory(nameof(SR.CatData)), + SRCategory(nameof(SR.CatData)), DefaultValue(null), SRDescription(nameof(SR.PDdocumentDescr)) ] - public PrintDocument Document { - get { return printDocument;} - set { + public PrintDocument Document + { + get { return printDocument; } + set + { printDocument = value; - if (printDocument != null) { + if (printDocument != null) + { pageSettings = printDocument.DefaultPageSettings; printerSettings = printDocument.PrinterSettings; } @@ -141,9 +153,10 @@ public PrintDocument Document { SRDescription(nameof(SR.PSDenableMetricDescr)), Browsable(true), EditorBrowsable(EditorBrowsableState.Always) ] - public bool EnableMetric { - get { return enableMetric;} - set { enableMetric = value;} + public bool EnableMetric + { + get { return enableMetric; } + set { enableMetric = value; } } /// @@ -154,12 +167,14 @@ public bool EnableMetric { /// /// [ - SRCategory(nameof(SR.CatData)), + SRCategory(nameof(SR.CatData)), SRDescription(nameof(SR.PSDminMarginsDescr)) ] - public Margins MinMargins { - get { return minMargins;} - set { + public Margins MinMargins + { + get { return minMargins; } + set + { if (value == null) value = new Margins(0, 0, 0, 0); minMargins = value; @@ -176,15 +191,17 @@ public Margins MinMargins { /// /// [ - SRCategory(nameof(SR.CatData)), + SRCategory(nameof(SR.CatData)), DefaultValue(null), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.PSDpageSettingsDescr)) ] - public PageSettings PageSettings { - get { return pageSettings;} - set { + public PageSettings PageSettings + { + get { return pageSettings; } + set + { pageSettings = value; printDocument = null; } @@ -198,15 +215,17 @@ public PageSettings PageSettings { /// /// [ - SRCategory(nameof(SR.CatData)), + SRCategory(nameof(SR.CatData)), DefaultValue(null), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.PSDprinterSettingsDescr)) ] - public PrinterSettings PrinterSettings { - get { return printerSettings;} - set { + public PrinterSettings PrinterSettings + { + get { return printerSettings; } + set + { printerSettings = value; printDocument = null; } @@ -218,13 +237,14 @@ public PrinterSettings PrinterSettings { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(false), SRDescription(nameof(SR.PSDshowHelpDescr)) ] - public bool ShowHelp { - get { return showHelp;} - set { showHelp = value;} + public bool ShowHelp + { + get { return showHelp; } + set { showHelp = value; } } /// @@ -233,28 +253,38 @@ public bool ShowHelp { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(true), SRDescription(nameof(SR.PSDshowNetworkDescr)) ] - public bool ShowNetwork { - get { return showNetwork;} - set { showNetwork = value;} + public bool ShowNetwork + { + get { return showNetwork; } + set { showNetwork = value; } } - private int GetFlags() { + private int GetFlags() + { int flags = 0; flags |= NativeMethods.PSD_ENABLEPAGESETUPHOOK; - if (!allowMargins) flags |= NativeMethods.PSD_DISABLEMARGINS; - if (!allowOrientation) flags |= NativeMethods.PSD_DISABLEORIENTATION; - if (!allowPaper) flags |= NativeMethods.PSD_DISABLEPAPER; - if (!allowPrinter || printerSettings == null) flags |= NativeMethods.PSD_DISABLEPRINTER; - - if (showHelp) flags |= NativeMethods.PSD_SHOWHELP; - if (!showNetwork) flags |= NativeMethods.PSD_NONETWORKBUTTON; - if (minMargins != null) flags |= NativeMethods.PSD_MINMARGINS; - if (pageSettings.Margins != null) flags |= NativeMethods.PSD_MARGINS; + if (!allowMargins) + flags |= NativeMethods.PSD_DISABLEMARGINS; + if (!allowOrientation) + flags |= NativeMethods.PSD_DISABLEORIENTATION; + if (!allowPaper) + flags |= NativeMethods.PSD_DISABLEPAPER; + if (!allowPrinter || printerSettings == null) + flags |= NativeMethods.PSD_DISABLEPRINTER; + + if (showHelp) + flags |= NativeMethods.PSD_SHOWHELP; + if (!showNetwork) + flags |= NativeMethods.PSD_NONETWORKBUTTON; + if (minMargins != null) + flags |= NativeMethods.PSD_MINMARGINS; + if (pageSettings.Margins != null) + flags |= NativeMethods.PSD_MARGINS; // return flags; @@ -265,7 +295,8 @@ private int GetFlags() { /// Resets all options to their default values. /// /// - public override void Reset() { + public override void Reset() + { allowMargins = true; allowOrientation = true; allowPaper = true; @@ -278,7 +309,8 @@ public override void Reset() { showNetwork = true; } - private void ResetMinMargins() { + private void ResetMinMargins() + { MinMargins = null; } @@ -289,7 +321,8 @@ private void ResetMinMargins() { /// persisted. /// /// - private bool ShouldSerializeMinMargins() { + private bool ShouldSerializeMinMargins() + { return minMargins.Left != 0 || minMargins.Right != 0 || minMargins.Top != 0 @@ -297,9 +330,11 @@ private bool ShouldSerializeMinMargins() { } private static void UpdateSettings(NativeMethods.PAGESETUPDLG data, PageSettings pageSettings, - PrinterSettings printerSettings) { + PrinterSettings printerSettings) + { pageSettings.SetHdevmode(data.hDevMode); - if (printerSettings != null) { + if (printerSettings != null) + { printerSettings.SetHdevmode(data.hDevMode); printerSettings.SetHdevnames(data.hDevNames); } @@ -313,14 +348,15 @@ private static void UpdateSettings(NativeMethods.PAGESETUPDLG data, PageSettings PrinterUnit fromUnit = ((data.Flags & NativeMethods.PSD_INHUNDREDTHSOFMILLIMETERS) != 0) ? PrinterUnit.HundredthsOfAMillimeter : PrinterUnit.ThousandthsOfAnInch; - + pageSettings.Margins = PrinterUnitConvert.Convert(newMargins, fromUnit, PrinterUnit.Display); } /// /// - protected override bool RunDialog(IntPtr hwndOwner) { + protected override bool RunDialog(IntPtr hwndOwner) + { NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(this.HookProc); if (pageSettings == null) @@ -331,7 +367,7 @@ protected override bool RunDialog(IntPtr hwndOwner) { data.Flags = GetFlags(); data.hwndOwner = hwndOwner; data.lpfnPageSetupHook = hookProcPtr; - + PrinterUnit toUnit = PrinterUnit.ThousandthsOfAnInch; // Below was a breaking change from RTM and EVERETT even though this was a correct FIX. @@ -341,14 +377,16 @@ protected override bool RunDialog(IntPtr hwndOwner) { //take the Units of Measurement while determining the PrinterUnits... // StringBuilder sb = new StringBuilder(2); - int result = UnsafeNativeMethods.GetLocaleInfo(NativeMethods.LOCALE_USER_DEFAULT,NativeMethods.LOCALE_IMEASURE, sb,sb.Capacity); - - if (result > 0 && int.Parse(sb.ToString(), CultureInfo.InvariantCulture) == 0) { + int result = UnsafeNativeMethods.GetLocaleInfo(NativeMethods.LOCALE_USER_DEFAULT, NativeMethods.LOCALE_IMEASURE, sb, sb.Capacity); + + if (result > 0 && int.Parse(sb.ToString(), CultureInfo.InvariantCulture) == 0) + { toUnit = PrinterUnit.HundredthsOfAMillimeter; } } - if (MinMargins != null) { + if (MinMargins != null) + { Margins margins = PrinterUnitConvert.Convert(MinMargins, PrinterUnit.Display, toUnit); data.minMarginLeft = margins.Left; data.minMarginTop = margins.Top; @@ -356,7 +394,8 @@ protected override bool RunDialog(IntPtr hwndOwner) { data.minMarginBottom = margins.Bottom; } - if (pageSettings.Margins != null) { + if (pageSettings.Margins != null) + { Margins margins = PrinterUnitConvert.Convert(pageSettings.Margins, PrinterUnit.Display, toUnit); data.marginLeft = margins.Left; data.marginTop = margins.Top; @@ -370,24 +409,27 @@ protected override bool RunDialog(IntPtr hwndOwner) { data.marginLeft = Math.Max(data.marginLeft, data.minMarginLeft); data.marginTop = Math.Max(data.marginTop, data.minMarginTop); data.marginRight = Math.Max(data.marginRight, data.minMarginRight); - data.marginBottom = Math.Max(data.marginBottom, data.minMarginBottom); + data.marginBottom = Math.Max(data.marginBottom, data.minMarginBottom); PrinterSettings printer = (printerSettings == null) ? pageSettings.PrinterSettings : printerSettings; data.hDevMode = printer.GetHdevmode(pageSettings); data.hDevNames = printer.GetHdevnames(); - try { + try + { bool status = UnsafeNativeMethods.PageSetupDlg(data); - if (!status) { + if (!status) + { // Debug.WriteLine(Windows.CommonDialogErrorToString(Windows.CommDlgExtendedError())); return false; } - + UpdateSettings(data, pageSettings, printerSettings); // yes, printerSettings, not printer return true; } - finally { + finally + { UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevMode)); UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevNames)); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintControllerWithStatusDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintControllerWithStatusDialog.cs index 605252e629f..c1b9591e950 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintControllerWithStatusDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintControllerWithStatusDialog.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; using System; using System.Threading; @@ -11,18 +12,21 @@ namespace System.Windows.Forms { using System.ComponentModel; using System.Drawing.Printing; - public class PrintControllerWithStatusDialog : PrintController { + public class PrintControllerWithStatusDialog : PrintController + { private PrintController underlyingController; private PrintDocument document; private BackgroundThread backgroundThread; private int pageNumber; private string dialogTitle; - public PrintControllerWithStatusDialog(PrintController underlyingController) - : this(underlyingController, string.Format(SR.PrintControllerWithStatusDialog_DialogTitlePrint)) { + public PrintControllerWithStatusDialog(PrintController underlyingController) + : this(underlyingController, string.Format(SR.PrintControllerWithStatusDialog_DialogTitlePrint)) + { } - public PrintControllerWithStatusDialog(PrintController underlyingController, string dialogTitle) { + public PrintControllerWithStatusDialog(PrintController underlyingController, string dialogTitle) + { this.underlyingController = underlyingController; this.dialogTitle = dialogTitle; } @@ -32,8 +36,10 @@ public PrintControllerWithStatusDialog(PrintController underlyingController, str /// and return its IsPreview Property. /// /// - public override bool IsPreview { - get { + public override bool IsPreview + { + get + { if (underlyingController != null) { return underlyingController.IsPreview; @@ -47,13 +53,15 @@ public override bool IsPreview { /// Implements StartPrint by delegating to the underlying controller. /// /// - public override void OnStartPrint(PrintDocument document, PrintEventArgs e) { + public override void OnStartPrint(PrintDocument document, PrintEventArgs e) + { base.OnStartPrint(document, e); this.document = document; pageNumber = 1; - if (SystemInformation.UserInteractive) { + if (SystemInformation.UserInteractive) + { backgroundThread = new BackgroundThread(this); // starts running & shows dialog automatically } @@ -61,17 +69,22 @@ public override void OnStartPrint(PrintDocument document, PrintEventArgs e) { // extra setup to make sure that we tear down // correctly... // - try { + try + { underlyingController.OnStartPrint(document, e); } - catch { - if (backgroundThread != null) { + catch + { + if (backgroundThread != null) + { backgroundThread.Stop(); } throw; } - finally { - if (backgroundThread != null && backgroundThread.canceled) { + finally + { + if (backgroundThread != null && backgroundThread.canceled) + { e.Cancel = true; } } @@ -82,14 +95,17 @@ public override void OnStartPrint(PrintDocument document, PrintEventArgs e) { /// Implements StartPage by delegating to the underlying controller. /// /// - public override Graphics OnStartPage(PrintDocument document, PrintPageEventArgs e) { + public override Graphics OnStartPage(PrintDocument document, PrintPageEventArgs e) + { base.OnStartPage(document, e); - if (backgroundThread != null) { + if (backgroundThread != null) + { backgroundThread.UpdateLabel(); } Graphics result = underlyingController.OnStartPage(document, e); - if (backgroundThread != null && backgroundThread.canceled){ + if (backgroundThread != null && backgroundThread.canceled) + { e.Cancel = true; } return result; @@ -100,9 +116,11 @@ public override Graphics OnStartPage(PrintDocument document, PrintPageEventArgs /// Implements EndPage by delegating to the underlying controller. /// /// - public override void OnEndPage(PrintDocument document, PrintPageEventArgs e) { + public override void OnEndPage(PrintDocument document, PrintPageEventArgs e) + { underlyingController.OnEndPage(document, e); - if (backgroundThread != null && backgroundThread.canceled) { + if (backgroundThread != null && backgroundThread.canceled) + { e.Cancel = true; } pageNumber++; @@ -115,20 +133,24 @@ public override void OnEndPage(PrintDocument document, PrintPageEventArgs e) { /// Implements EndPrint by delegating to the underlying controller. /// /// - public override void OnEndPrint(PrintDocument document, PrintEventArgs e) { + public override void OnEndPrint(PrintDocument document, PrintEventArgs e) + { underlyingController.OnEndPrint(document, e); - if (backgroundThread != null && backgroundThread.canceled) { + if (backgroundThread != null && backgroundThread.canceled) + { e.Cancel = true; } - if (backgroundThread != null) { + if (backgroundThread != null) + { backgroundThread.Stop(); } base.OnEndPrint(document, e); } - private class BackgroundThread { + private class BackgroundThread + { private PrintControllerWithStatusDialog parent; private StatusDialog dialog; private Thread thread; @@ -136,7 +158,8 @@ private class BackgroundThread { private bool alreadyStopped = false; // Called from any thread - internal BackgroundThread(PrintControllerWithStatusDialog parent) { + internal BackgroundThread(PrintControllerWithStatusDialog parent) + { this.parent = parent; // Calling Application.DoEvents() from within a paint event causes all sorts of problems, @@ -147,12 +170,16 @@ internal BackgroundThread(PrintControllerWithStatusDialog parent) { } // on correct thread - private void Run() { + private void Run() + { // - try { - lock (this) { - if (alreadyStopped) { + try + { + lock (this) + { + if (alreadyStopped) + { return; } @@ -161,13 +188,17 @@ private void Run() { dialog.Visible = true; } - if (!alreadyStopped) { + if (!alreadyStopped) + { Application.Run(dialog); } } - finally { - lock (this) { - if (dialog != null) { + finally + { + lock (this) + { + if (dialog != null) + { dialog.Dispose(); dialog = null; } @@ -176,9 +207,12 @@ private void Run() { } // Called from any thread - internal void Stop() { - lock (this) { - if (dialog != null && dialog.IsHandleCreated) { + internal void Stop() + { + lock (this) + { + if (dialog != null && dialog.IsHandleCreated) + { dialog.BeginInvoke(new MethodInvoker(dialog.Close)); return; } @@ -187,29 +221,34 @@ internal void Stop() { } // on correct thread - private void ThreadUnsafeUpdateLabel() { + private void ThreadUnsafeUpdateLabel() + { // "page {0} of {1}" - dialog.label1.Text = string.Format(SR.PrintControllerWithStatusDialog_NowPrinting, + dialog.label1.Text = string.Format(SR.PrintControllerWithStatusDialog_NowPrinting, parent.pageNumber, parent.document.DocumentName); } // Called from any thread - internal void UpdateLabel() { - if (dialog != null && dialog.IsHandleCreated) { + internal void UpdateLabel() + { + if (dialog != null && dialog.IsHandleCreated) + { dialog.BeginInvoke(new MethodInvoker(ThreadUnsafeUpdateLabel)); // Don't wait for a response } } } - private class StatusDialog : Form { + private class StatusDialog : Form + { internal Label label1; private Button button1; private TableLayoutPanel tableLayoutPanel1; private BackgroundThread backgroundThread; - internal StatusDialog(BackgroundThread backgroundThread, string dialogTitle) { - + internal StatusDialog(BackgroundThread backgroundThread, string dialogTitle) + { + InitializeComponent(); this.backgroundThread = backgroundThread; this.Text = dialogTitle; @@ -220,13 +259,16 @@ internal StatusDialog(BackgroundThread backgroundThread, string dialogTitle) { /// Tells whether the current resources for this dll have been /// localized for a RTL language. /// - private static bool IsRTLResources { - get { + private static bool IsRTLResources + { + get + { return SR.RTL != "RTL_False"; } } - private void InitializeComponent() { + private void InitializeComponent() + { if (IsRTLResources) { this.RightToLeft = RightToLeft.Yes; @@ -242,7 +284,7 @@ private void InitializeComponent() { label1.Size = new Size(240, 64); label1.TabIndex = 1; label1.Anchor = AnchorStyles.None; - + button1.AutoSize = true; button1.Size = new Size(75, 23); button1.TabIndex = 0; @@ -262,24 +304,27 @@ private void InitializeComponent() { tableLayoutPanel1.TabIndex = 0; tableLayoutPanel1.Controls.Add(label1, 0, 0); tableLayoutPanel1.Controls.Add(button1, 0, 1); - + this.AutoScaleDimensions = new Size(6, 13); this.AutoScaleMode = AutoScaleMode.Font; this.MaximizeBox = false; this.ControlBox = false; this.MinimizeBox = false; Size clientSize = new Size(256, 122); - if (DpiHelper.IsScalingRequired) { + if (DpiHelper.IsScalingRequired) + { this.ClientSize = DpiHelper.LogicalToDeviceUnits(clientSize); } - else { + else + { this.ClientSize = clientSize; } this.CancelButton = button1; - this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; + this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.Controls.Add(tableLayoutPanel1); } - private void button1_Click(object sender, System.EventArgs e) { + private void button1_Click(object sender, System.EventArgs e) + { button1.Enabled = false; label1.Text = string.Format(SR.PrintControllerWithStatusDialog_Canceling); backgroundThread.canceled = true; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintDialog.cs index d0ef734f5cb..c715ca8a624 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintDialog.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System; @@ -20,8 +21,9 @@ namespace System.Windows.Forms { [SRDescription(nameof(SR.DescriptionPrintDialog))] [Designer("System.Windows.Forms.Design.PrintDialogDesigner, " + AssemblyRef.SystemDesign)] // The only event this dialog has is HelpRequested, which isn't very useful - public sealed class PrintDialog : CommonDialog { - private const int printRangeMask = (int) (PrintRange.AllPages | PrintRange.SomePages + public sealed class PrintDialog : CommonDialog + { + private const int printRangeMask = (int)(PrintRange.AllPages | PrintRange.SomePages | PrintRange.Selection | PrintRange.CurrentPage); // If PrintDocument != null, settings == printDocument.PrinterSettings @@ -41,11 +43,12 @@ public sealed class PrintDialog : CommonDialog { /// /// Initializes a new instance of the class. /// - public PrintDialog() { + public PrintDialog() + { Reset(); } - + /// /// /// Gets or sets a value indicating whether the Current Page option button is enabled. @@ -55,11 +58,12 @@ public PrintDialog() { DefaultValue(false), SRDescription(nameof(SR.PDallowCurrentPageDescr)) ] - public bool AllowCurrentPage { - get { return allowCurrentPage;} - set { allowCurrentPage = value;} + public bool AllowCurrentPage + { + get { return allowCurrentPage; } + set { allowCurrentPage = value; } } - + /// /// @@ -67,26 +71,28 @@ public bool AllowCurrentPage { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(false), SRDescription(nameof(SR.PDallowPagesDescr)) ] - public bool AllowSomePages { - get { return allowPages;} - set { allowPages = value;} + public bool AllowSomePages + { + get { return allowPages; } + set { allowPages = value; } } /// /// Gets or sets a value indicating whether the Print to file check box is enabled. /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(true), SRDescription(nameof(SR.PDallowPrintToFileDescr)) ] - public bool AllowPrintToFile { - get { return allowPrintToFile;} - set { allowPrintToFile = value;} + public bool AllowPrintToFile + { + get { return allowPrintToFile; } + set { allowPrintToFile = value; } } /// @@ -95,13 +101,14 @@ public bool AllowPrintToFile { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(false), SRDescription(nameof(SR.PDallowSelectionDescr)) ] - public bool AllowSelection { - get { return allowSelection;} - set { allowSelection = value;} + public bool AllowSelection + { + get { return allowSelection; } + set { allowSelection = value; } } /// @@ -110,13 +117,15 @@ public bool AllowSelection { /// /// [ - SRCategory(nameof(SR.CatData)), + SRCategory(nameof(SR.CatData)), DefaultValue(null), SRDescription(nameof(SR.PDdocumentDescr)) ] - public PrintDocument Document { - get { return printDocument;} - set { + public PrintDocument Document + { + get { return printDocument; } + set + { printDocument = value; if (printDocument == null) settings = new PrinterSettings(); @@ -125,8 +134,10 @@ public PrintDocument Document { } } - private PageSettings PageSettings { - get { + private PageSettings PageSettings + { + get + { if (Document == null) return PrinterSettings.DefaultPageSettings; else @@ -141,22 +152,25 @@ private PageSettings PageSettings { /// /// [ - SRCategory(nameof(SR.CatData)), + SRCategory(nameof(SR.CatData)), DefaultValue(null), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.PDprinterSettingsDescr)) ] - public PrinterSettings PrinterSettings { - get { - + public PrinterSettings PrinterSettings + { + get + { + if (settings == null) { settings = new PrinterSettings(); } return settings; } - set { + set + { if (value != PrinterSettings) { settings = value; @@ -169,13 +183,14 @@ public PrinterSettings PrinterSettings { /// Gets or sets a value indicating whether the Print to file check box is checked. /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(false), SRDescription(nameof(SR.PDprintToFileDescr)) ] - public bool PrintToFile { - get { return printToFile;} - set { printToFile = value;} + public bool PrintToFile + { + get { return printToFile; } + set { printToFile = value; } } /// @@ -184,13 +199,14 @@ public bool PrintToFile { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(false), SRDescription(nameof(SR.PDshowHelpDescr)) ] - public bool ShowHelp { - get { return showHelp;} - set { showHelp = value;} + public bool ShowHelp + { + get { return showHelp; } + set { showHelp = value; } } /// @@ -199,13 +215,14 @@ public bool ShowHelp { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(true), SRDescription(nameof(SR.PDshowNetworkDescr)) ] - public bool ShowNetwork { - get { return showNetwork;} - set { showNetwork = value;} + public bool ShowNetwork + { + get { return showNetwork; } + set { showNetwork = value; } } @@ -275,7 +292,8 @@ private int GetFlags() /// settings to their default values. /// /// - public override void Reset() { + public override void Reset() + { allowCurrentPage = false; allowPages = false; allowPrintToFile = true; @@ -288,12 +306,15 @@ public override void Reset() { } // Create a PRINTDLG with a few useful defaults. - internal static NativeMethods.PRINTDLG CreatePRINTDLG() { + internal static NativeMethods.PRINTDLG CreatePRINTDLG() + { NativeMethods.PRINTDLG data = null; - if (IntPtr.Size == 4) { + if (IntPtr.Size == 4) + { data = new NativeMethods.PRINTDLG_32(); } - else { + else + { data = new NativeMethods.PRINTDLG_64(); } data.lStructSize = Marshal.SizeOf(data); @@ -318,7 +339,8 @@ internal static NativeMethods.PRINTDLG CreatePRINTDLG() { return data; } - internal static NativeMethods.PRINTDLGEX CreatePRINTDLGEX() { + internal static NativeMethods.PRINTDLGEX CreatePRINTDLGEX() + { NativeMethods.PRINTDLGEX data = new NativeMethods.PRINTDLGEX(); data.lStructSize = Marshal.SizeOf(data); data.hwndOwner = IntPtr.Zero; @@ -360,14 +382,16 @@ protected override bool RunDialog(IntPtr hwndOwner) } } - private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.WndProc hookProcPtr, NativeMethods.PRINTDLG data) { + private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.WndProc hookProcPtr, NativeMethods.PRINTDLG data) + { data.Flags = GetFlags(); - data.nCopies = (short) PrinterSettings.Copies; + data.nCopies = (short)PrinterSettings.Copies; data.hwndOwner = hwndOwner; data.lpfnPrintHook = hookProcPtr; - try { + try + { if (PageSettings == null) data.hDevMode = PrinterSettings.GetHdevmode(); else @@ -375,15 +399,18 @@ private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.WndProc hookProcPtr data.hDevNames = PrinterSettings.GetHdevnames(); } - catch (InvalidPrinterException) { + catch (InvalidPrinterException) + { data.hDevMode = IntPtr.Zero; data.hDevNames = IntPtr.Zero; // Leave those fields null; Windows will fill them in } - try { + try + { // Windows doesn't like it if page numbers are invalid - if (AllowSomePages) { + if (AllowSomePages) + { if (PrinterSettings.FromPage < PrinterSettings.MinimumPage || PrinterSettings.FromPage > PrinterSettings.MaximumPage) throw new ArgumentException(string.Format(SR.PDpageOutOfRange, "FromPage")); @@ -393,10 +420,10 @@ private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.WndProc hookProcPtr if (PrinterSettings.ToPage < PrinterSettings.FromPage) throw new ArgumentException(string.Format(SR.PDpageOutOfRange, "FromPage")); - data.nFromPage = (short) PrinterSettings.FromPage; - data.nToPage = (short) PrinterSettings.ToPage; - data.nMinPage = (short) PrinterSettings.MinimumPage; - data.nMaxPage = (short) PrinterSettings.MaximumPage; + data.nFromPage = (short)PrinterSettings.FromPage; + data.nToPage = (short)PrinterSettings.ToPage; + data.nMinPage = (short)PrinterSettings.MinimumPage; + data.nMaxPage = (short)PrinterSettings.MaximumPage; } if (!UnsafeNativeMethods.PrintDlg(data)) @@ -407,7 +434,8 @@ private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.WndProc hookProcPtr PrintToFile = ((data.Flags & NativeMethods.PD_PRINTTOFILE) != 0); PrinterSettings.PrintToFile = PrintToFile; - if (AllowSomePages) { + if (AllowSomePages) + { PrinterSettings.FromPage = data.nFromPage; PrinterSettings.ToPage = data.nToPage; } @@ -424,7 +452,8 @@ private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.WndProc hookProcPtr return true; } - finally { + finally + { UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevMode)); UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevNames)); } @@ -432,13 +461,15 @@ private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.WndProc hookProcPtr // Due to the nature of PRINTDLGEX vs PRINTDLG, separate but similar methods // are required for showing the print dialog on Win2k and newer OS'. - private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.PRINTDLGEX data) { + private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.PRINTDLGEX data) + { data.Flags = GetFlags(); data.nCopies = PrinterSettings.Copies; data.hwndOwner = hwndOwner; - try { + try + { if (PageSettings == null) data.hDevMode = PrinterSettings.GetHdevmode(); else @@ -446,15 +477,18 @@ private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.PRINTDLGEX data) { data.hDevNames = PrinterSettings.GetHdevnames(); } - catch (InvalidPrinterException) { + catch (InvalidPrinterException) + { data.hDevMode = IntPtr.Zero; data.hDevNames = IntPtr.Zero; // Leave those fields null; Windows will fill them in } - try { + try + { // Windows doesn't like it if page numbers are invalid - if (AllowSomePages) { + if (AllowSomePages) + { if (PrinterSettings.FromPage < PrinterSettings.MinimumPage || PrinterSettings.FromPage > PrinterSettings.MaximumPage) throw new ArgumentException(string.Format(SR.PDpageOutOfRange, "FromPage")); @@ -464,7 +498,8 @@ private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.PRINTDLGEX data) { if (PrinterSettings.ToPage < PrinterSettings.FromPage) throw new ArgumentException(string.Format(SR.PDpageOutOfRange, "FromPage")); - unsafe { + unsafe + { int* pageRangeField = (int*)data.pageRanges; *pageRangeField = PrinterSettings.FromPage; pageRangeField += 1; @@ -480,9 +515,10 @@ private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.PRINTDLGEX data) { // The flags NativeMethods.PD_SHOWHELP and NativeMethods.PD_NONETWORKBUTTON don't work with // PrintDlgEx. So we have to strip them out. data.Flags &= ~(NativeMethods.PD_SHOWHELP | NativeMethods.PD_NONETWORKBUTTON); - + int hr = UnsafeNativeMethods.PrintDlgEx(data); - if (NativeMethods.Failed(hr) || data.dwResultAction == NativeMethods.PD_RESULT_CANCEL) { + if (NativeMethods.Failed(hr) || data.dwResultAction == NativeMethods.PD_RESULT_CANCEL) + { return false; } @@ -490,8 +526,10 @@ private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.PRINTDLGEX data) { PrintToFile = ((data.Flags & NativeMethods.PD_PRINTTOFILE) != 0); PrinterSettings.PrintToFile = PrintToFile; - if (AllowSomePages) { - unsafe { + if (AllowSomePages) + { + unsafe + { int* pageRangeField = (int*)data.pageRanges; PrinterSettings.FromPage = *pageRangeField; pageRangeField += 1; @@ -512,7 +550,8 @@ private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.PRINTDLGEX data) { // We should return true only if the user pressed the "Print" button while dismissing the dialog. return (data.dwResultAction == NativeMethods.PD_RESULT_PRINT); } - finally { + finally + { if (data.hDevMode != IntPtr.Zero) UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevMode)); if (data.hDevNames != IntPtr.Zero) @@ -525,19 +564,20 @@ private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.PRINTDLGEX data) { // Due to the nature of PRINTDLGEX vs PRINTDLG, separate but similar methods // are required for updating the settings from the structure utilized by the dialog. // Take information from print dialog and put in PrinterSettings - private static void UpdatePrinterSettings(IntPtr hDevMode, IntPtr hDevNames, short copies, int flags, PrinterSettings settings, PageSettings pageSettings) { + private static void UpdatePrinterSettings(IntPtr hDevMode, IntPtr hDevNames, short copies, int flags, PrinterSettings settings, PageSettings pageSettings) + { // Mode settings.SetHdevmode(hDevMode); settings.SetHdevnames(hDevNames); - if (pageSettings!= null) + if (pageSettings != null) pageSettings.SetHdevmode(hDevMode); //Check for Copies == 1 since we might get the Right number of Copies from hdevMode.dmCopies... if (settings.Copies == 1) settings.Copies = copies; - settings.PrintRange = (PrintRange) (flags & printRangeMask); + settings.PrintRange = (PrintRange)(flags & printRangeMask); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewControl.cs index 958755b5203..0240c5ba265 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewControl.cs @@ -2,11 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.PrintPreviewControl.PhysicalToPixels(System.Drawing.Size,System.Drawing.Point):System.Drawing.Size")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.PrintPreviewControl.PixelsToPhysical(System.Drawing.Size,System.Drawing.Point):System.Drawing.Size")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.PrintPreviewControl.set_VirtualSize(System.Drawing.Size):System.Void")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.PrintPreviewControl.PhysicalToPixels(System.Drawing.Size,System.Drawing.Point):System.Drawing.Size")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.PrintPreviewControl.PixelsToPhysical(System.Drawing.Size,System.Drawing.Point):System.Drawing.Size")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.PrintPreviewControl.set_VirtualSize(System.Drawing.Size):System.Void")] -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.Diagnostics; @@ -28,9 +29,10 @@ namespace System.Windows.Forms { [ClassInterface(ClassInterfaceType.AutoDispatch)] [DefaultProperty(nameof(Document))] [SRDescription(nameof(SR.DescriptionPrintPreviewControl))] - public class PrintPreviewControl : Control { - Size virtualSize = new Size(1,1); - Point position = new Point(0,0); + public class PrintPreviewControl : Control + { + Size virtualSize = new Size(1, 1); + Point position = new Point(0, 0); Point lastOffset; bool antiAlias; @@ -60,25 +62,29 @@ public class PrintPreviewControl : Control { /// Initializes a new instance of the class. /// /// - public PrintPreviewControl() { + public PrintPreviewControl() + { ResetBackColor(); ResetForeColor(); Size = new Size(100, 100); SetStyle(ControlStyles.ResizeRedraw, false); SetStyle(ControlStyles.Opaque | ControlStyles.OptimizedDoubleBuffer, true); - + } [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(false), SRDescription(nameof(SR.PrintPreviewAntiAliasDescr)) ] - public bool UseAntiAlias { - get { + public bool UseAntiAlias + { + get + { return antiAlias; } - set { + set + { antiAlias = value; } } @@ -94,10 +100,13 @@ public bool UseAntiAlias { DefaultValue(true), SRDescription(nameof(SR.PrintPreviewAutoZoomDescr)) ] - public bool AutoZoom { - get { return autoZoom;} - set { - if (autoZoom != value) { + public bool AutoZoom + { + get { return autoZoom; } + set + { + if (autoZoom != value) + { autoZoom = value; InvalidateLayout(); } @@ -115,9 +124,11 @@ public bool AutoZoom { DefaultValue(null), SRDescription(nameof(SR.PrintPreviewDocumentDescr)) ] - public PrintDocument Document { - get { return document;} - set { + public PrintDocument Document + { + get { return document; } + set + { document = value; InvalidatePreview(); } @@ -134,10 +145,13 @@ public PrintDocument Document { SRCategory(nameof(SR.CatLayout)), SRDescription(nameof(SR.PrintPreviewColumnsDescr)) ] - public int Columns { - get { return columns;} - set { - if (value < 1 ) { + public int Columns + { + get { return columns; } + set + { + if (value < 1) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(Columns), value, 1)); } @@ -153,8 +167,10 @@ public int Columns { /// /// /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.Style |= NativeMethods.WS_HSCROLL; cp.Style |= NativeMethods.WS_VSCROLL; @@ -172,9 +188,11 @@ protected override CreateParams CreateParams { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlWithScrollbarsPositionDescr)) ] - private Point Position { - get { return position;} - set { + private Point Position + { + get { return position; } + set + { SetPositionNoInvalidate(value); } } @@ -190,11 +208,14 @@ private Point Position { SRDescription(nameof(SR.PrintPreviewRowsDescr)), SRCategory(nameof(SR.CatBehavior)) ] - public int Rows { - get { return rows;} - set { - - if (value < 1 ) { + public int Rows + { + get { return rows; } + set + { + + if (value < 1) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(Rows), value, 1)); } @@ -214,36 +235,43 @@ public int Rows { AmbientValue(RightToLeft.Inherit), SRDescription(nameof(SR.ControlRightToLeftDescr)) ] - public override RightToLeft RightToLeft { - get { + public override RightToLeft RightToLeft + { + get + { return base.RightToLeft; } - set { + set + { base.RightToLeft = value; InvalidatePreview(); } } [ - Browsable(false), EditorBrowsable(EditorBrowsableState.Never), - Bindable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never), + Bindable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public override string Text { - get { + ] + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TextChanged { + new public event EventHandler TextChanged + { add => base.TextChanged += value; remove => base.TextChanged -= value; } - + /// /// /// Gets or sets the page number of the upper left page. @@ -255,23 +283,29 @@ public override string Text { SRDescription(nameof(SR.PrintPreviewStartPageDescr)), SRCategory(nameof(SR.CatBehavior)) ] - public int StartPage { - get { + public int StartPage + { + get + { int value = startPage; - if (pageInfo != null) { + if (pageInfo != null) + { value = Math.Min(value, pageInfo.Length - (rows * columns)); } value = Math.Max(value, 0); return value; } - set { - if (value < 0 ) { + set + { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(StartPage), value, 0)); } int oldValue = StartPage; startPage = value; - if (oldValue != startPage) { + if (oldValue != startPage) + { InvalidateLayout(); OnStartPageChanged(EventArgs.Empty); } @@ -281,7 +315,8 @@ public int StartPage { private static readonly object EVENT_STARTPAGECHANGED = new object(); [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.RadioButtonOnStartPageChangedDescr))] - public event EventHandler StartPageChanged { + public event EventHandler StartPageChanged + { add => Events.AddHandler(EVENT_STARTPAGECHANGED, value); remove => Events.RemoveHandler(EVENT_STARTPAGECHANGED, value); } @@ -295,9 +330,11 @@ public event EventHandler StartPageChanged { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlWithScrollbarsVirtualSizeDescr)) ] - private Size VirtualSize { - get { return virtualSize;} - set { + private Size VirtualSize + { + get { return virtualSize; } + set + { SetVirtualSizeNoInvalidate(value); Invalidate(); } @@ -313,9 +350,11 @@ private Size VirtualSize { SRDescription(nameof(SR.PrintPreviewZoomDescr)), DefaultValue(DefaultZoom) ] - public double Zoom { - get { return zoom;} - set { + public double Zoom + { + get { return zoom; } + set + { if (value <= 0) throw new ArgumentException(SR.PrintPreviewControlZoomNegative); autoZoom = false; @@ -324,8 +363,10 @@ public double Zoom { } } - private int AdjustScroll(Message m, int pos, int maxPos, bool horizontal) { - switch (NativeMethods.Util.LOWORD(m.WParam)) { + private int AdjustScroll(Message m, int pos, int maxPos, bool horizontal) + { + switch (NativeMethods.Util.LOWORD(m.WParam)) + { case NativeMethods.SB_THUMBPOSITION: case NativeMethods.SB_THUMBTRACK: NativeMethods.SCROLLINFO si = new NativeMethods.SCROLLINFO(); @@ -342,34 +383,42 @@ private int AdjustScroll(Message m, int pos, int maxPos, bool horizontal) { } break; case NativeMethods.SB_LINEUP: - if (pos > SCROLL_LINE) { - pos-=SCROLL_LINE; + if (pos > SCROLL_LINE) + { + pos -= SCROLL_LINE; } - else { + else + { pos = 0; } break; case NativeMethods.SB_LINEDOWN: - if (pos < maxPos-SCROLL_LINE) { - pos+=SCROLL_LINE; + if (pos < maxPos - SCROLL_LINE) + { + pos += SCROLL_LINE; } - else { + else + { pos = maxPos; } break; case NativeMethods.SB_PAGEUP: - if (pos > SCROLL_PAGE) { - pos-=SCROLL_PAGE; + if (pos > SCROLL_PAGE) + { + pos -= SCROLL_PAGE; } - else { + else + { pos = 0; } break; case NativeMethods.SB_PAGEDOWN: - if (pos < maxPos-SCROLL_PAGE) { - pos+=SCROLL_PAGE; + if (pos < maxPos - SCROLL_PAGE) + { + pos += SCROLL_PAGE; } - else { + else + { pos = maxPos; } break; @@ -380,10 +429,12 @@ private int AdjustScroll(Message m, int pos, int maxPos, bool horizontal) { // This function computes everything in terms of physical size (millimeters), not pixels // - private void ComputeLayout() { + private void ComputeLayout() + { Debug.Assert(pageInfo != null, "Must call ComputePreview first"); layoutOk = true; - if (pageInfo.Length == 0) { + if (pageInfo.Length == 0) + { ClientSize = Size; return; } @@ -398,30 +449,33 @@ private void ComputeLayout() { Size pageSize = pageInfo[StartPage].PhysicalSize; Size controlPhysicalSize = new Size(PixelsToPhysical(new Point(Size), screendpi)); - if (autoZoom) { - double zoomX = ((double) controlPhysicalSize.Width - border*(columns + 1)) / (columns*pageSize.Width); - double zoomY = ((double) controlPhysicalSize.Height - border*(rows + 1)) / (rows*pageSize.Height); + if (autoZoom) + { + double zoomX = ((double)controlPhysicalSize.Width - border * (columns + 1)) / (columns * pageSize.Width); + double zoomY = ((double)controlPhysicalSize.Height - border * (rows + 1)) / (rows * pageSize.Height); zoom = Math.Min(zoomX, zoomY); } - imageSize = new Size((int) (zoom*pageSize.Width), (int) (zoom*pageSize.Height)); - int virtualX = (imageSize.Width * columns) + border * (columns +1); - int virtualY = (imageSize.Height * rows) + border * (rows +1); + imageSize = new Size((int)(zoom * pageSize.Width), (int)(zoom * pageSize.Height)); + int virtualX = (imageSize.Width * columns) + border * (columns + 1); + int virtualY = (imageSize.Height * rows) + border * (rows + 1); SetVirtualSizeNoInvalidate(new Size(PhysicalToPixels(new Point(virtualX, virtualY), screendpi))); } // "Prints" the document to memory - private void ComputePreview() { + private void ComputePreview() + { int oldStart = StartPage; if (document == null) pageInfo = new PreviewPageInfo[0]; - else { + else + { PrintController oldController = document.PrintController; PreviewPrintController previewController = new PreviewPrintController(); previewController.UseAntiAlias = UseAntiAlias; - document.PrintController = new PrintControllerWithStatusDialog(previewController, + document.PrintController = new PrintControllerWithStatusDialog(previewController, string.Format(SR.PrintControllerWithStatusDialog_DialogTitlePreview)); document.Print(); @@ -431,14 +485,16 @@ private void ComputePreview() { document.PrintController = oldController; } - if (oldStart != StartPage) { + if (oldStart != StartPage) + { OnStartPageChanged(EventArgs.Empty); } } // Recomputes the sizes and positions of pages without forcing a new "preview print" - private void InvalidateLayout() { - layoutOk = false; + private void InvalidateLayout() + { + layoutOk = false; Invalidate(); } @@ -447,7 +503,8 @@ private void InvalidateLayout() { /// Refreshes the preview of the document. /// /// - public void InvalidatePreview() { + public void InvalidatePreview() + { pageInfo = null; InvalidateLayout(); } @@ -457,50 +514,63 @@ public void InvalidatePreview() { /// Invalidate the layout, if necessary. /// /// - protected override void OnResize(EventArgs eventargs) { + protected override void OnResize(EventArgs eventargs) + { InvalidateLayout(); base.OnResize(eventargs); } - void CalculatePageInfo() { - if (pageInfoCalcPending) { + void CalculatePageInfo() + { + if (pageInfoCalcPending) + { return; } pageInfoCalcPending = true; - try { - if (pageInfo == null) { - try { + try + { + if (pageInfo == null) + { + try + { ComputePreview(); } - catch { + catch + { exceptionPrinting = true; throw; } - finally { + finally + { Invalidate(); } } } - finally { + finally + { pageInfoCalcPending = false; } } - + /// /// /// Paints the control. /// /// - protected override void OnPaint(PaintEventArgs pevent) { + protected override void OnPaint(PaintEventArgs pevent) + { Brush backBrush = new SolidBrush(BackColor); - try { - if (pageInfo == null || pageInfo.Length == 0) { + try + { + if (pageInfo == null || pageInfo.Length == 0) + { pevent.Graphics.FillRectangle(backBrush, ClientRectangle); - if (pageInfo != null || exceptionPrinting) { + if (pageInfo != null || exceptionPrinting) + { // Calculate formats StringFormat format = new StringFormat(); format.Alignment = ControlPaint.TranslateAlignment(ContentAlignment.MiddleCenter); @@ -508,24 +578,30 @@ protected override void OnPaint(PaintEventArgs pevent) { // Do actual drawing SolidBrush brush = new SolidBrush(ForeColor); - try { - if (exceptionPrinting) { + try + { + if (exceptionPrinting) + { pevent.Graphics.DrawString(SR.PrintPreviewExceptionPrinting, Font, brush, ClientRectangle, format); } - else { + else + { pevent.Graphics.DrawString(SR.PrintPreviewNoPages, Font, brush, ClientRectangle, format); } } - finally { + finally + { brush.Dispose(); format.Dispose(); } } - else { + else + { BeginInvoke(new MethodInvoker(CalculatePageInfo)); } - } - else { + } + else + { if (!layoutOk) ComputeLayout(); @@ -548,35 +624,40 @@ protected override void OnPaint(PaintEventArgs pevent) { Rectangle[] pageRenderArea = new Rectangle[rows * columns]; Point lastImageSize = Point.Empty; int maxImageHeight = 0; - - try { - for (int row = 0; row < rows; row++) { + + try + { + for (int row = 0; row < rows; row++) + { //Initialize our LastImageSize variable... lastImageSize.X = 0; lastImageSize.Y = maxImageHeight * row; - - for (int column = 0; column < columns; column++) { - int imageIndex = StartPage + column + row*columns; - if (imageIndex < pageInfo.Length) { + + for (int column = 0; column < columns; column++) + { + int imageIndex = StartPage + column + row * columns; + if (imageIndex < pageInfo.Length) + { Size pageSize = pageInfo[imageIndex].PhysicalSize; - if (autoZoom) { - double zoomX = ((double) controlPhysicalSize.Width - border*(columns + 1)) / (columns*pageSize.Width); - double zoomY = ((double) controlPhysicalSize.Height - border*(rows + 1)) / (rows*pageSize.Height); + if (autoZoom) + { + double zoomX = ((double)controlPhysicalSize.Width - border * (columns + 1)) / (columns * pageSize.Width); + double zoomY = ((double)controlPhysicalSize.Height - border * (rows + 1)) / (rows * pageSize.Height); zoom = Math.Min(zoomX, zoomY); } - imageSize = new Size((int) (zoom*pageSize.Width), (int) (zoom*pageSize.Height)); + imageSize = new Size((int)(zoom * pageSize.Width), (int)(zoom * pageSize.Height)); Point imagePixels = PhysicalToPixels(new Point(imageSize), screendpi); - - + + int x = offset.X + borderPixelsX * (column + 1) + lastImageSize.X; int y = offset.Y + borderPixelsY * (row + 1) + lastImageSize.Y; lastImageSize.X += imagePixels.X; //The Height is the Max of any PageHeight.. maxImageHeight = Math.Max(maxImageHeight, imagePixels.Y); - + pageRenderArea[imageIndex - StartPage] = new Rectangle(x, y, imagePixels.X, imagePixels.Y); pevent.Graphics.ExcludeClip(pageRenderArea[imageIndex - StartPage]); } @@ -585,66 +666,80 @@ protected override void OnPaint(PaintEventArgs pevent) { pevent.Graphics.FillRectangle(backBrush, ClientRectangle); } - finally { + finally + { pevent.Graphics.Clip = originalClip; } - for (int i=0; i [EditorBrowsable(EditorBrowsableState.Never)] - public override void ResetBackColor() { + public override void ResetBackColor() + { BackColor = SystemColors.AppWorkspace; } @@ -661,7 +757,8 @@ public override void ResetBackColor() { /// Resets the back color to the defaults for the PrintPreviewControl. /// [EditorBrowsable(EditorBrowsableState.Never)] - public override void ResetForeColor() { + public override void ResetForeColor() + { ForeColor = Color.White; } @@ -669,12 +766,14 @@ public override void ResetForeColor() { /// WM_HSCROLL handler /// - private void WmHScroll(ref Message m) { + private void WmHScroll(ref Message m) + { // The lparam is handle of the sending scrollbar, or NULL when // the scrollbar sending the message is the "form" scrollbar... // - if (m.LParam != IntPtr.Zero) { + if (m.LParam != IntPtr.Zero) + { base.WndProc(ref m); return; } @@ -687,14 +786,17 @@ private void WmHScroll(ref Message m) { Position = locPos; } - private void SetPositionNoInvalidate(Point value) { + private void SetPositionNoInvalidate(Point value) + { Point current = position; position = value; position.X = Math.Min(position.X, virtualSize.Width - Width); position.Y = Math.Min(position.Y, virtualSize.Height - Height); - if (position.X < 0) position.X = 0; - if (position.Y < 0) position.Y = 0; + if (position.X < 0) + position.X = 0; + if (position.Y < 0) + position.Y = 0; Rectangle rect = ClientRectangle; NativeMethods.RECT scroll = NativeMethods.RECT.FromXYWH(rect.X, rect.Y, rect.Width, rect.Height); @@ -708,10 +810,11 @@ private void SetPositionNoInvalidate(Point value) { UnsafeNativeMethods.SetScrollPos(new HandleRef(this, Handle), NativeMethods.SB_VERT, position.Y, true); } - internal void SetVirtualSizeNoInvalidate(Size value) { + internal void SetVirtualSizeNoInvalidate(Size value) + { virtualSize = value; SetPositionNoInvalidate(position); // Make sure it's within range - + NativeMethods.SCROLLINFO info = new NativeMethods.SCROLLINFO(); info.fMask = NativeMethods.SIF_RANGE | NativeMethods.SIF_PAGE; info.nMin = 0; @@ -730,12 +833,14 @@ internal void SetVirtualSizeNoInvalidate(Size value) { /// WM_VSCROLL handler /// - private void WmVScroll(ref Message m) { + private void WmVScroll(ref Message m) + { // The lparam is handle of the sending scrollbar, or NULL when // the scrollbar sending the message is the "form" scrollbar... // - if (m.LParam != IntPtr.Zero) { + if (m.LParam != IntPtr.Zero) + { base.WndProc(ref m); return; } @@ -753,22 +858,26 @@ private void WmVScroll(ref Message m) { /// //added to handle keyboard events // - private void WmKeyDown(ref Message msg) { + private void WmKeyDown(ref Message msg) + { Keys keyData = (Keys)((int)msg.WParam | (int)ModifierKeys); Point locPos = Position; int pos = 0; int maxPos = 0; - - switch (keyData & Keys.KeyCode) { + + switch (keyData & Keys.KeyCode) + { case Keys.PageUp: - if ((keyData & Keys.Modifiers) == Keys.Control) + if ((keyData & Keys.Modifiers) == Keys.Control) { pos = locPos.X; - if (pos > SCROLL_PAGE) { - pos-=SCROLL_PAGE; + if (pos > SCROLL_PAGE) + { + pos -= SCROLL_PAGE; } - else { + else + { pos = 0; } locPos.X = pos; @@ -780,14 +889,16 @@ private void WmKeyDown(ref Message msg) { } break; case Keys.PageDown: - if ((keyData & Keys.Modifiers) == Keys.Control) + if ((keyData & Keys.Modifiers) == Keys.Control) { pos = locPos.X; maxPos = Math.Max(Width, virtualSize.Width /*- Width*/); - if (pos < maxPos-SCROLL_PAGE) { - pos+=SCROLL_PAGE; + if (pos < maxPos - SCROLL_PAGE) + { + pos += SCROLL_PAGE; } - else { + else + { pos = maxPos; } locPos.X = pos; @@ -799,21 +910,22 @@ private void WmKeyDown(ref Message msg) { } break; case Keys.Home: - if ((keyData & Keys.Modifiers) == Keys.Control) - StartPage=0; + if ((keyData & Keys.Modifiers) == Keys.Control) + StartPage = 0; break; case Keys.End: if ((keyData & Keys.Modifiers) == Keys.Control) - StartPage=pageInfo.Length; + StartPage = pageInfo.Length; break; - + case Keys.Up: pos = locPos.Y; if (pos > SCROLL_LINE) { - pos-=SCROLL_LINE; + pos -= SCROLL_LINE; } - else { + else + { pos = 0; } locPos.Y = pos; @@ -823,23 +935,27 @@ private void WmKeyDown(ref Message msg) { pos = locPos.Y; maxPos = Math.Max(Height, virtualSize.Height/* - Height*/); - - if (pos < maxPos-SCROLL_LINE) { - pos+=SCROLL_LINE; + + if (pos < maxPos - SCROLL_LINE) + { + pos += SCROLL_LINE; } - else { + else + { pos = maxPos; } locPos.Y = pos; Position = locPos; break; case Keys.Left: - + pos = locPos.X; - if (pos > SCROLL_LINE) { - pos-=SCROLL_LINE; + if (pos > SCROLL_LINE) + { + pos -= SCROLL_LINE; } - else { + else + { pos = 0; } locPos.X = pos; @@ -848,10 +964,12 @@ private void WmKeyDown(ref Message msg) { case Keys.Right: pos = locPos.X; maxPos = Math.Max(Width, virtualSize.Width /*- Width*/); - if (pos < maxPos-SCROLL_LINE) { - pos+=SCROLL_LINE; + if (pos < maxPos - SCROLL_LINE) + { + pos += SCROLL_LINE; } - else { + else + { pos = maxPos; } locPos.X = pos; @@ -860,8 +978,10 @@ private void WmKeyDown(ref Message msg) { } } - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { case Interop.WindowMessages.WM_VSCROLL: WmVScroll(ref m); break; @@ -885,7 +1005,8 @@ protected override void WndProc(ref Message m) { /// persisted. /// /// - internal override bool ShouldSerializeBackColor() { + internal override bool ShouldSerializeBackColor() + { return !BackColor.Equals(SystemColors.AppWorkspace); } @@ -895,7 +1016,8 @@ internal override bool ShouldSerializeBackColor() { /// persisted. /// /// - internal override bool ShouldSerializeForeColor() { + internal override bool ShouldSerializeForeColor() + { return !ForeColor.Equals(Color.White); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs index fa0ff049065..bb9963c907b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System; using System.ComponentModel; @@ -30,7 +31,8 @@ namespace System.Windows.Forms { ToolboxItem(true), SRDescription(nameof(SR.DescriptionPrintPreviewDialog)) ] - public class PrintPreviewDialog : Form { + public class PrintPreviewDialog : Form + { PrintPreviewControl previewControl; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.NumericUpDown pageCounter; @@ -55,15 +57,16 @@ public class PrintPreviewDialog : Form { private System.Windows.Forms.ToolStripButton closeToolStripButton; private System.Windows.Forms.ToolStripLabel pageToolStripLabel; ImageList imageList; - + /// /// Initializes a new instance of the class. /// - public PrintPreviewDialog() { - - #pragma warning disable 618 + public PrintPreviewDialog() + { + +#pragma warning disable 618 base.AutoScaleBaseSize = new Size(5, 13); - #pragma warning restore 618 +#pragma warning restore 618 this.previewControl = new PrintPreviewControl(); this.imageList = new ImageList(); @@ -78,11 +81,14 @@ public PrintPreviewDialog() { /// the user presses the ENTER key. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public IButtonControl AcceptButton { - get { + new public IButtonControl AcceptButton + { + get + { return base.AcceptButton; } - set { + set + { base.AcceptButton = value; } } @@ -94,16 +100,19 @@ public PrintPreviewDialog() { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public bool AutoScale { - get { - #pragma warning disable 618 + new public bool AutoScale + { + get + { +#pragma warning disable 618 return base.AutoScale; - #pragma warning restore 618 +#pragma warning restore 618 } - set { - #pragma warning disable 618 + set + { +#pragma warning disable 618 base.AutoScale = value; - #pragma warning restore 618 +#pragma warning restore 618 } } @@ -114,12 +123,15 @@ public PrintPreviewDialog() { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override bool AutoScroll { - get { - + public override bool AutoScroll + { + get + { + return base.AutoScroll; } - set { + set + { base.AutoScroll = value; } } @@ -130,20 +142,24 @@ public override bool AutoScroll { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public override bool AutoSize { - get { + public override bool AutoSize + { + get + { return base.AutoSize; } - set { + set + { base.AutoSize = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler AutoSizeChanged { + new public event EventHandler AutoSizeChanged + { add => base.AutoSizeChanged += value; remove => base.AutoSizeChanged -= value; - } + } /// /// @@ -151,36 +167,44 @@ public override bool AutoSize { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override AutoValidate AutoValidate { - get { + public override AutoValidate AutoValidate + { + get + { return base.AutoValidate; } - set { + set + { base.AutoValidate = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler AutoValidateChanged { + public new event EventHandler AutoValidateChanged + { add => base.AutoValidateChanged += value; remove => base.AutoValidateChanged -= value; } - + /// /// The background color of this control. This is an ambient property and /// will always return a non-null value. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Color BackColor { - get { + public override Color BackColor + { + get + { return base.BackColor; } - set { + set + { base.BackColor = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackColorChanged { + new public event EventHandler BackColorChanged + { add => base.BackColorChanged += value; remove => base.BackColorChanged -= value; } @@ -191,11 +215,14 @@ public override Color BackColor { /// user presses the ESC key. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public IButtonControl CancelButton { - get { + new public IButtonControl CancelButton + { + get + { return base.CancelButton; } - set { + set + { base.CancelButton = value; } } @@ -204,11 +231,14 @@ public override Color BackColor { /// caption bar of the form. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public bool ControlBox { - get { + new public bool ControlBox + { + get + { return base.ControlBox; } - set { + set + { base.ControlBox = value; } } @@ -217,32 +247,39 @@ public override Color BackColor { /// Hide the property /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ContextMenuStrip ContextMenuStrip { - get { - return base.ContextMenuStrip; - } - set { - base.ContextMenuStrip = value; - } + public override ContextMenuStrip ContextMenuStrip + { + get + { + return base.ContextMenuStrip; + } + set + { + base.ContextMenuStrip = value; + } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler ContextMenuStripChanged { + public new event EventHandler ContextMenuStripChanged + { add => base.ContextMenuStripChanged += value; remove => base.ContextMenuStripChanged -= value; } - + /// /// /// Gets or sets the border style of the form. /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public FormBorderStyle FormBorderStyle { - get { + new public FormBorderStyle FormBorderStyle + { + get + { return base.FormBorderStyle; } - set { + set + { base.FormBorderStyle = value; } } @@ -253,11 +290,14 @@ public override ContextMenuStrip ContextMenuStrip { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public bool HelpButton { - get { + new public bool HelpButton + { + get + { return base.HelpButton; } - set { + set + { base.HelpButton = value; } } @@ -267,13 +307,16 @@ public override ContextMenuStrip ContextMenuStrip { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public Icon Icon { - - - get { + new public Icon Icon + { + + + get + { return base.Icon; } - set { + set + { base.Icon = value; } } @@ -284,11 +327,14 @@ public override ContextMenuStrip ContextMenuStrip { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public bool IsMdiContainer { - get { + new public bool IsMdiContainer + { + get + { return base.IsMdiContainer; } - set { + set + { base.IsMdiContainer = value; } } @@ -300,11 +346,14 @@ public override ContextMenuStrip ContextMenuStrip { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public bool KeyPreview { - get { + new public bool KeyPreview + { + get + { return base.KeyPreview; } - set { + set + { base.KeyPreview = value; } } @@ -314,16 +363,20 @@ public override ContextMenuStrip ContextMenuStrip { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public Size MaximumSize { - get { + new public Size MaximumSize + { + get + { return base.MaximumSize; } - set { + set + { base.MaximumSize = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler MaximumSizeChanged { + new public event EventHandler MaximumSizeChanged + { add => base.MaximumSizeChanged += value; remove => base.MaximumSizeChanged -= value; } @@ -332,11 +385,14 @@ public override ContextMenuStrip ContextMenuStrip { /// displayed in the caption bar of the form. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public bool MaximizeBox { - get { + new public bool MaximizeBox + { + get + { return base.MaximizeBox; } - set { + set + { base.MaximizeBox = value; } } @@ -345,21 +401,25 @@ public override ContextMenuStrip ContextMenuStrip { /// Hide the value /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public Padding Margin { - get { + new public Padding Margin + { + get + { return base.Margin; } - set { + set + { base.Margin = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler MarginChanged { + public new event EventHandler MarginChanged + { add => base.MarginChanged += value; remove => base.MarginChanged -= value; } - + /// /// /// Gets or sets the @@ -367,11 +427,14 @@ public override ContextMenuStrip ContextMenuStrip { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public MainMenu Menu { - get { + new public MainMenu Menu + { + get + { return base.Menu; } - set { + set + { base.Menu = value; } } @@ -382,16 +445,20 @@ public override ContextMenuStrip ContextMenuStrip { /// /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), EditorBrowsable(EditorBrowsableState.Never)] - new public Size MinimumSize { - get { + new public Size MinimumSize + { + get + { return base.MinimumSize; } - set { + set + { base.MinimumSize = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler MinimumSizeChanged { + new public event EventHandler MinimumSizeChanged + { add => base.MinimumSizeChanged += value; remove => base.MinimumSizeChanged -= value; } @@ -402,37 +469,45 @@ public override ContextMenuStrip ContextMenuStrip { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public Padding Padding { - get { + new public Padding Padding + { + get + { return base.Padding; } - set { + set + { base.Padding = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler PaddingChanged { + public new event EventHandler PaddingChanged + { add => base.PaddingChanged += value; remove => base.PaddingChanged -= value; } - + /// /// /// Gets or sets the size of the form. /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public Size Size { - get { + new public Size Size + { + get + { return base.Size; } - set { + set + { base.Size = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler SizeChanged { + new public event EventHandler SizeChanged + { add => base.SizeChanged += value; remove => base.SizeChanged -= value; } @@ -443,11 +518,14 @@ public override ContextMenuStrip ContextMenuStrip { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public FormStartPosition StartPosition { - get { + new public FormStartPosition StartPosition + { + get + { return base.StartPosition; } - set { + set + { base.StartPosition = value; } } @@ -456,11 +534,14 @@ public override ContextMenuStrip ContextMenuStrip { /// form of your application. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public bool TopMost { - get { + new public bool TopMost + { + get + { return base.TopMost; } - set { + set + { base.TopMost = value; } } @@ -469,11 +550,14 @@ public override ContextMenuStrip ContextMenuStrip { /// Gets or sets the color that will represent transparent areas of the form. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public Color TransparencyKey { - get { + new public Color TransparencyKey + { + get + { return base.TransparencyKey; } - set { + set + { base.TransparencyKey = value; } } @@ -482,25 +566,31 @@ public override ContextMenuStrip ContextMenuStrip { /// Hide the value /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public bool UseWaitCursor{ - get { + new public bool UseWaitCursor + { + get + { return base.UseWaitCursor; } - set { + set + { base.UseWaitCursor = value; } } - + /// /// Gets or sets the form's window state. /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public FormWindowState WindowState { - get { + new public FormWindowState WindowState + { + get + { return base.WindowState; } - set { + set + { base.WindowState = value; } } @@ -508,11 +598,14 @@ public override ContextMenuStrip ContextMenuStrip { /// The accessible role of the control /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public AccessibleRole AccessibleRole { - get { + new public AccessibleRole AccessibleRole + { + get + { return base.AccessibleRole; } - set { + set + { base.AccessibleRole = value; } } @@ -520,11 +613,14 @@ public override ContextMenuStrip ContextMenuStrip { /// The accessible description of the control /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public string AccessibleDescription { - get { + new public string AccessibleDescription + { + get + { return base.AccessibleDescription; } - set { + set + { base.AccessibleDescription = value; } } @@ -532,11 +628,14 @@ public override ContextMenuStrip ContextMenuStrip { /// The accessible name of the control /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public string AccessibleName { - get { + new public string AccessibleName + { + get + { return base.AccessibleName; } - set { + set + { base.AccessibleName = value; } } @@ -545,16 +644,20 @@ public override ContextMenuStrip ContextMenuStrip { /// Indicates whether entering the control causes validation on the controls requiring validation. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public bool CausesValidation { - get { + new public bool CausesValidation + { + get + { return base.CausesValidation; } - set { + set + { base.CausesValidation = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler CausesValidationChanged { + new public event EventHandler CausesValidationChanged + { add => base.CausesValidationChanged += value; remove => base.CausesValidationChanged -= value; } @@ -562,32 +665,39 @@ public override ContextMenuStrip ContextMenuStrip { /// Retrieves the bindings for this control. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public ControlBindingsCollection DataBindings { - get { + new public ControlBindingsCollection DataBindings + { + get + { return base.DataBindings; } } - - protected override Size DefaultMinimumSize { + + protected override Size DefaultMinimumSize + { get { return new Size(375, 250); } } - - + + /// /// Indicates whether the control is currently enabled. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public bool Enabled { - get { + new public bool Enabled + { + get + { return base.Enabled; } - set { + set + { base.Enabled = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler EnabledChanged { + new public event EventHandler EnabledChanged + { add => base.EnabledChanged += value; remove => base.EnabledChanged -= value; } @@ -597,25 +707,32 @@ protected override Size DefaultMinimumSize { [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - new public Point Location { - get { + new public Point Location + { + get + { return base.Location; } - set { + set + { base.Location = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler LocationChanged { + new public event EventHandler LocationChanged + { add => base.LocationChanged += value; remove => base.LocationChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public object Tag { - get { + new public object Tag + { + get + { return base.Tag; } - set { + set + { base.Tag = value; } } @@ -624,11 +741,14 @@ protected override Size DefaultMinimumSize { /// this control will allow drag and drop operations and events to be used. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override bool AllowDrop { - get { + public override bool AllowDrop + { + get + { return base.AllowDrop; } - set { + set + { base.AllowDrop = value; } } @@ -637,16 +757,20 @@ public override bool AllowDrop { /// control. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Cursor Cursor { - get { + public override Cursor Cursor + { + get + { return base.Cursor; } - set { + set + { base.Cursor = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler CursorChanged { + new public event EventHandler CursorChanged + { add => base.CursorChanged += value; remove => base.CursorChanged -= value; } @@ -655,16 +779,20 @@ public override Cursor Cursor { /// The background image of the control. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged { + new public event EventHandler BackgroundImageChanged + { add => base.BackgroundImageChanged += value; remove => base.BackgroundImageChanged -= value; } @@ -673,16 +801,20 @@ public override Image BackgroundImage { /// The background image layout of the control. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { + new public event EventHandler BackgroundImageLayoutChanged + { add => base.BackgroundImageLayoutChanged += value; remove => base.BackgroundImageLayoutChanged -= value; } @@ -691,16 +823,20 @@ public override ImageLayout BackgroundImageLayout { /// object when that object is selected. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public ImeMode ImeMode { - get { + new public ImeMode ImeMode + { + get + { return base.ImeMode; } - set { + set + { base.ImeMode = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler ImeModeChanged { + public new event EventHandler ImeModeChanged + { add => base.ImeModeChanged += value; remove => base.ImeModeChanged -= value; } @@ -713,11 +849,14 @@ public override ImageLayout BackgroundImageLayout { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public Size AutoScrollMargin { - get { + new public Size AutoScrollMargin + { + get + { return base.AutoScrollMargin; } - set { + set + { base.AutoScrollMargin = value; } } @@ -725,11 +864,14 @@ public override ImageLayout BackgroundImageLayout { /// Gets or sets the mimimum size of the auto-scroll. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public Size AutoScrollMinSize { - get { + new public Size AutoScrollMinSize + { + get + { return base.AutoScrollMinSize; } - set { + set + { base.AutoScrollMinSize = value; } } @@ -739,11 +881,14 @@ public override ImageLayout BackgroundImageLayout { /// edges. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override AnchorStyles Anchor { - get { + public override AnchorStyles Anchor + { + get + { return base.Anchor; } - set { + set + { base.Anchor = value; } } @@ -751,16 +896,20 @@ public override AnchorStyles Anchor { /// Indicates whether the control is visible. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public bool Visible { - get { + new public bool Visible + { + get + { return base.Visible; } - set { + set + { base.Visible = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler VisibleChanged { + new public event EventHandler VisibleChanged + { add => base.VisibleChanged += value; remove => base.VisibleChanged -= value; } @@ -768,16 +917,20 @@ public override AnchorStyles Anchor { /// The foreground color of the control. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Color ForeColor { - get { + public override Color ForeColor + { + get + { return base.ForeColor; } - set { + set + { base.ForeColor = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler ForeColorChanged { + new public event EventHandler ForeColorChanged + { add => base.ForeColorChanged += value; remove => base.ForeColorChanged -= value; } @@ -788,11 +941,14 @@ public override Color ForeColor { /// control placement and text will be from right to left. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override RightToLeft RightToLeft { - get { + public override RightToLeft RightToLeft + { + get + { return base.RightToLeft; } - set { + set + { base.RightToLeft = value; } } @@ -804,45 +960,54 @@ public override RightToLeft RightToLeft { /// control placement and text will be from right to left. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override bool RightToLeftLayout { - get { + public override bool RightToLeftLayout + { + get + { return base.RightToLeftLayout; } - set { + set + { base.RightToLeftLayout = value; } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler RightToLeftChanged { + public new event EventHandler RightToLeftChanged + { add => base.RightToLeftChanged += value; remove => base.RightToLeftChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler RightToLeftLayoutChanged { + public new event EventHandler RightToLeftLayoutChanged + { add => base.RightToLeftLayoutChanged += value; remove => base.RightToLeftLayoutChanged -= value; } - + /// /// Indicates whether the user can give the focus to this control using the TAB /// key. This property is read-only. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public bool TabStop { - get { + new public bool TabStop + { + get + { return base.TabStop; } - set { + set + { base.TabStop = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TabStopChanged { + new public event EventHandler TabStopChanged + { add => base.TabStopChanged += value; remove => base.TabStopChanged -= value; } @@ -851,21 +1016,25 @@ public override bool RightToLeftLayout { /// The current text associated with this control. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TextChanged { + new public event EventHandler TextChanged + { add => base.TextChanged += value; remove => base.TextChanged -= value; } - + /// /// The dock property. The dock property controls to which edge /// of the container this control is docked to. For example, when docked to @@ -873,16 +1042,20 @@ public override string Text { /// top of the container, extending the length of the container. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override DockStyle Dock { - get { + public override DockStyle Dock + { + get + { return base.Dock; } - set { + set + { base.Dock = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler DockChanged { + new public event EventHandler DockChanged + { add => base.DockChanged += value; remove => base.DockChanged -= value; } @@ -892,16 +1065,20 @@ public override DockStyle Dock { /// by default for painting and text in the control. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Font Font { - get { + public override Font Font + { + get + { return base.Font; } - set { + set + { base.Font = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler FontChanged { + new public event EventHandler FontChanged + { add => base.FontChanged += value; remove => base.FontChanged -= value; } @@ -911,16 +1088,20 @@ public override Font Font { /// will be shown when the user right clicks the mouse on the control. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ContextMenu ContextMenu { - get { + public override ContextMenu ContextMenu + { + get + { return base.ContextMenu; } - set { + set + { base.ContextMenu = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler ContextMenuChanged { + public new event EventHandler ContextMenuChanged + { add => base.ContextMenuChanged += value; remove => base.ContextMenuChanged -= value; } @@ -929,24 +1110,29 @@ public override ContextMenu ContextMenu { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public DockPaddingEdges DockPadding { - get { + new public DockPaddingEdges DockPadding + { + get + { return base.DockPadding; } } //------------------------------------------------------------------------------------------------------------- //end addition - + [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(false), SRDescription(nameof(SR.PrintPreviewAntiAliasDescr)) ] - public bool UseAntiAlias { - get { + public bool UseAntiAlias + { + get + { return PrintPreviewControl.UseAntiAlias; } - set { + set + { PrintPreviewControl.UseAntiAlias = value; } } @@ -957,22 +1143,25 @@ public bool UseAntiAlias { /// /// /// Keeping implementation of obsoleted AutoScaleBaseSize API - #pragma warning disable 618 +#pragma warning disable 618 // disable csharp compiler warning #0809: obsolete member overrides non-obsolete member - #pragma warning disable 0809 +#pragma warning disable 0809 [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This property has been deprecated. Use the AutoScaleDimensions property instead. http://go.microsoft.com/fwlink/?linkid=14202")] - public override Size AutoScaleBaseSize { - get { + public override Size AutoScaleBaseSize + { + get + { return base.AutoScaleBaseSize; } - set { + set + { // No-op } } - #pragma warning restore 0809 - #pragma warning restore 618 +#pragma warning restore 0809 +#pragma warning restore 618 /// /// @@ -984,21 +1173,27 @@ public override Size AutoScaleBaseSize { DefaultValue(null), SRDescription(nameof(SR.PrintPreviewDocumentDescr)) ] - public PrintDocument Document { - get { + public PrintDocument Document + { + get + { return previewControl.Document; } - set { + set + { previewControl.Document = value; } } - + [Browsable(false), DefaultValue(false), EditorBrowsable(EditorBrowsableState.Never)] - public new bool MinimizeBox { - get { + public new bool MinimizeBox + { + get + { return base.MinimizeBox; } - set { + set + { base.MinimizeBox = value; } } @@ -1012,8 +1207,9 @@ public PrintDocument Document { SRDescription(nameof(SR.PrintPreviewPrintPreviewControlDescr)), Browsable(false) ] - public PrintPreviewControl PrintPreviewControl { - get { return previewControl;} + public PrintPreviewControl PrintPreviewControl + { + get { return previewControl; } } /// @@ -1021,32 +1217,41 @@ public PrintPreviewControl PrintPreviewControl { /// Opacity does not apply to PrintPreviewDialogs. /// /// - [Browsable(false),EditorBrowsable(EditorBrowsableState.Advanced)] - public new double Opacity { - get { + [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] + public new double Opacity + { + get + { return base.Opacity; } - set { + set + { base.Opacity = value; } } - + [Browsable(false), DefaultValue(false), EditorBrowsable(EditorBrowsableState.Never)] - public new bool ShowInTaskbar { - get { + public new bool ShowInTaskbar + { + get + { return base.ShowInTaskbar; } - set { + set + { base.ShowInTaskbar = value; } } - + [Browsable(false), DefaultValue(SizeGripStyle.Hide), EditorBrowsable(EditorBrowsableState.Never)] - public new SizeGripStyle SizeGripStyle { - get { + public new SizeGripStyle SizeGripStyle + { + get + { return base.SizeGripStyle; } - set { + set + { base.SizeGripStyle = value; } } @@ -1055,8 +1260,9 @@ public PrintPreviewControl PrintPreviewControl { SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // The default page count is 1. // So we don't have to localize it. ] - void InitForm() { - + void InitForm() + { + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PrintPreviewDialog)); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); @@ -1322,7 +1528,7 @@ void InitForm() { menu.ShowCheckMargin = true; menu.ShowImageMargin = false; menu.RenderMode = System.Windows.Forms.ToolStripRenderMode.System; - + } //Create the ToolStripControlHost @@ -1351,14 +1557,15 @@ void InitForm() { } - + /// /// /// Forces the preview to be regenerated every time the dialog comes up /// /// - protected override void OnClosing(CancelEventArgs e) { + protected override void OnClosing(CancelEventArgs e) + { base.OnClosing(e); previewControl.InvalidatePreview(); } @@ -1368,20 +1575,24 @@ protected override void OnClosing(CancelEventArgs e) { /// subclass overrides this function, /// it must call the base implementation. /// - protected override void CreateHandle() { + protected override void CreateHandle() + { // We want to check printer settings before we push the modal message loop, // so the user has a chance to catch the exception instead of letting go to // the windows forms exception dialog. if (Document != null && !Document.PrinterSettings.IsValid) throw new InvalidPrinterException(Document.PrinterSettings); - + base.CreateHandle(); } - protected override bool ProcessDialogKey(Keys keyData) { - if ((keyData & (Keys.Alt | Keys.Control)) == Keys.None) { + protected override bool ProcessDialogKey(Keys keyData) + { + if ((keyData & (Keys.Alt | Keys.Control)) == Keys.None) + { Keys keyCode = (Keys)keyData & Keys.KeyCode; - switch (keyCode) { + switch (keyCode) + { case Keys.Left: case Keys.Right: case Keys.Up: @@ -1398,7 +1609,8 @@ protected override bool ProcessDialogKey(Keys keyData) { /// This is breaking from Everett. /// /// - protected override bool ProcessTabKey(bool forward) { + protected override bool ProcessTabKey(bool forward) + { if (this.ActiveControl == this.previewControl) { this.pageCounter.Focus(); @@ -1412,81 +1624,96 @@ protected override bool ProcessTabKey(bool forward) { /// AutoScaleBaseSize should never be persisted for PrintPreviewDialogs. /// /// - internal override bool ShouldSerializeAutoScaleBaseSize() { + internal override bool ShouldSerializeAutoScaleBaseSize() + { // This method is called when the dialog is "contained" on another form. // We should use our own base size, not the base size of our container. return false; } - - internal override bool ShouldSerializeText() { + + internal override bool ShouldSerializeText() + { return !Text.Equals(string.Format(SR.PrintPreviewDialog_PrintPreview)); } - void OncloseToolStripButtonClick(object sender, System.EventArgs e) { + void OncloseToolStripButtonClick(object sender, System.EventArgs e) + { this.Close(); } - void previewControl_StartPageChanged(object sender, EventArgs e) { + void previewControl_StartPageChanged(object sender, EventArgs e) + { pageCounter.Value = previewControl.StartPage + 1; } - - void CheckZoomMenu(ToolStripMenuItem toChecked) { - foreach (ToolStripMenuItem item in zoomToolStripSplitButton.DropDownItems) { + + void CheckZoomMenu(ToolStripMenuItem toChecked) + { + foreach (ToolStripMenuItem item in zoomToolStripSplitButton.DropDownItems) + { item.Checked = toChecked == item; } } - - void ZoomAuto(object sender, EventArgs eventargs) { + + void ZoomAuto(object sender, EventArgs eventargs) + { ToolStripMenuItem item = sender as ToolStripMenuItem; CheckZoomMenu(item); previewControl.AutoZoom = true; } - void Zoom500(object sender, EventArgs eventargs) { + void Zoom500(object sender, EventArgs eventargs) + { ToolStripMenuItem item = sender as ToolStripMenuItem; CheckZoomMenu(item); previewControl.Zoom = 5.00; } - void Zoom250(object sender, EventArgs eventargs) { + void Zoom250(object sender, EventArgs eventargs) + { ToolStripMenuItem item = sender as ToolStripMenuItem; CheckZoomMenu(item); previewControl.Zoom = 2.50; } - void Zoom150(object sender, EventArgs eventargs) { + void Zoom150(object sender, EventArgs eventargs) + { ToolStripMenuItem item = sender as ToolStripMenuItem; CheckZoomMenu(item); previewControl.Zoom = 1.50; } - void Zoom100(object sender, EventArgs eventargs) { + void Zoom100(object sender, EventArgs eventargs) + { ToolStripMenuItem item = sender as ToolStripMenuItem; CheckZoomMenu(item); previewControl.Zoom = 1.00; } - void Zoom75(object sender, EventArgs eventargs) { + void Zoom75(object sender, EventArgs eventargs) + { ToolStripMenuItem item = sender as ToolStripMenuItem; CheckZoomMenu(item); previewControl.Zoom = .75; } - void Zoom50(object sender, EventArgs eventargs) { + void Zoom50(object sender, EventArgs eventargs) + { ToolStripMenuItem item = sender as ToolStripMenuItem; CheckZoomMenu(item); previewControl.Zoom = .50; } - void Zoom25(object sender, EventArgs eventargs) { + void Zoom25(object sender, EventArgs eventargs) + { ToolStripMenuItem item = sender as ToolStripMenuItem; CheckZoomMenu(item); previewControl.Zoom = .25; } - void Zoom10(object sender, EventArgs eventargs) { + void Zoom10(object sender, EventArgs eventargs) + { ToolStripMenuItem item = sender as ToolStripMenuItem; CheckZoomMenu(item); previewControl.Zoom = .10; @@ -1497,64 +1724,74 @@ void OncloseToolStripButtonPaint(object sender, PaintEventArgs e) ToolStripItem item = sender as ToolStripItem; if (item != null && !item.Selected) { - Rectangle rect = new Rectangle (0, 0 , item.Bounds.Width - 1, item.Bounds.Height - 1); - using (Pen pen = new Pen(SystemColors.ControlDark)) + Rectangle rect = new Rectangle(0, 0, item.Bounds.Width - 1, item.Bounds.Height - 1); + using (Pen pen = new Pen(SystemColors.ControlDark)) { e.Graphics.DrawRectangle(pen, rect); } } } - - void OnprintToolStripButtonClick(object sender, System.EventArgs e) { - if (previewControl.Document != null) - { + + void OnprintToolStripButtonClick(object sender, System.EventArgs e) + { + if (previewControl.Document != null) + { previewControl.Document.Print(); - } + } } - - void OnzoomToolStripSplitButtonClick(object sender, System.EventArgs e) { + + void OnzoomToolStripSplitButtonClick(object sender, System.EventArgs e) + { ZoomAuto(null, EventArgs.Empty); } //-------- - void OnonepageToolStripButtonClick(object sender, System.EventArgs e) { - previewControl.Rows = 1; - previewControl.Columns = 1; + void OnonepageToolStripButtonClick(object sender, System.EventArgs e) + { + previewControl.Rows = 1; + previewControl.Columns = 1; } - void OntwopagesToolStripButtonClick(object sender, System.EventArgs e) { - previewControl.Rows = 1; - previewControl.Columns = 2; + void OntwopagesToolStripButtonClick(object sender, System.EventArgs e) + { + previewControl.Rows = 1; + previewControl.Columns = 2; } - void OnthreepagesToolStripButtonClick(object sender, System.EventArgs e) { + void OnthreepagesToolStripButtonClick(object sender, System.EventArgs e) + { previewControl.Rows = 1; previewControl.Columns = 3; } - void OnfourpagesToolStripButtonClick(object sender, System.EventArgs e) { - previewControl.Rows = 2; - previewControl.Columns = 2; + void OnfourpagesToolStripButtonClick(object sender, System.EventArgs e) + { + previewControl.Rows = 2; + previewControl.Columns = 2; } - void OnsixpagesToolStripButtonClick(object sender, System.EventArgs e) { + void OnsixpagesToolStripButtonClick(object sender, System.EventArgs e) + { previewControl.Rows = 2; previewControl.Columns = 3; } //---------------------- - void UpdownMove(object sender, EventArgs eventargs) { + void UpdownMove(object sender, EventArgs eventargs) + { int pageNum = ((int)pageCounter.Value) - 1; - if (pageNum >= 0) { + if (pageNum >= 0) + { // -1 because users like to count from one, and programmers from 0 previewControl.StartPage = pageNum; // And previewControl_PropertyChanged will change it again, // ensuring it stays within legal bounds. } - else { + else + { pageCounter.Value = previewControl.StartPage + 1; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ProfessionalColorTable.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ProfessionalColorTable.cs index 8d6c45aaa5c..72a42f21920 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ProfessionalColorTable.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ProfessionalColorTable.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; @@ -11,55 +12,68 @@ namespace System.Windows.Forms { using System.Collections; using System.Collections.Generic; using System.Diagnostics; - - public class ProfessionalColorTable { - private Dictionary professionalRGB = null; - private bool usingSystemColors = false; - private bool useSystemColors = false; + public class ProfessionalColorTable + { + + private Dictionary professionalRGB = null; + private bool usingSystemColors = false; + private bool useSystemColors = false; private string lastKnownColorScheme = string.Empty; - private const string oliveColorScheme = "HomeStead"; - private const string normalColorScheme = "NormalColor"; - private const string silverColorScheme = "Metallic"; - private const string royaleColorScheme = "Royale"; // sometimes returns NormalColor, sometimes returns Royale. + private const string oliveColorScheme = "HomeStead"; + private const string normalColorScheme = "NormalColor"; + private const string silverColorScheme = "Metallic"; + private const string royaleColorScheme = "Royale"; // sometimes returns NormalColor, sometimes returns Royale. - private const string lunaFileName = "luna.msstyles"; + private const string lunaFileName = "luna.msstyles"; private const string royaleFileName = "royale.msstyles"; private const string aeroFileName = "aero.msstyles"; - + private object colorFreshnessKey = null; - - public ProfessionalColorTable() { + + public ProfessionalColorTable() + { } - private Dictionary ColorTable { - get { - if (UseSystemColors) { + private Dictionary ColorTable + { + get + { + if (UseSystemColors) + { // someone has turned off theme support for the color table. - if (!usingSystemColors || professionalRGB == null) { - if (professionalRGB == null) { - professionalRGB= new Dictionary((int)KnownColors.lastKnownColor); + if (!usingSystemColors || professionalRGB == null) + { + if (professionalRGB == null) + { + professionalRGB = new Dictionary((int)KnownColors.lastKnownColor); } InitSystemColors(ref professionalRGB); } } - else if (ToolStripManager.VisualStylesEnabled) { + else if (ToolStripManager.VisualStylesEnabled) + { // themes are on and enabled in the manager - if (usingSystemColors || professionalRGB == null) { - if (professionalRGB == null) { - professionalRGB= new Dictionary((int)KnownColors.lastKnownColor); + if (usingSystemColors || professionalRGB == null) + { + if (professionalRGB == null) + { + professionalRGB = new Dictionary((int)KnownColors.lastKnownColor); } InitThemedColors(ref professionalRGB); } } - else { + else + { // themes are off. - if (!usingSystemColors || professionalRGB == null) { - if (professionalRGB == null) { - professionalRGB= new Dictionary((int)KnownColors.lastKnownColor); + if (!usingSystemColors || professionalRGB == null) + { + if (professionalRGB == null) + { + professionalRGB = new Dictionary((int)KnownColors.lastKnownColor); } InitSystemColors(ref professionalRGB); } @@ -72,21 +86,27 @@ private Dictionary ColorTable { /// when this is specified, professional colors picks from SystemColors rather than colors /// that match the current theme. If theming is not turned on, we'll fall back to SystemColors. /// - public bool UseSystemColors { - get { + public bool UseSystemColors + { + get + { return useSystemColors; } - set{ - if (useSystemColors != value) { + set + { + if (useSystemColors != value) + { useSystemColors = value; ResetRGBTable(); } } } - - internal Color FromKnownColor(ProfessionalColorTable.KnownColors color) { - if (ProfessionalColors.ColorFreshnessKey != colorFreshnessKey || ProfessionalColors.ColorScheme != lastKnownColorScheme) { - ResetRGBTable(); + + internal Color FromKnownColor(ProfessionalColorTable.KnownColors color) + { + if (ProfessionalColors.ColorFreshnessKey != colorFreshnessKey || ProfessionalColors.ColorScheme != lastKnownColorScheme) + { + ResetRGBTable(); } colorFreshnessKey = ProfessionalColors.ColorFreshnessKey; lastKnownColorScheme = ProfessionalColors.ColorScheme; @@ -96,346 +116,416 @@ internal Color FromKnownColor(ProfessionalColorTable.KnownColors color) { - private void ResetRGBTable() { - if (professionalRGB != null) { - professionalRGB.Clear(); + private void ResetRGBTable() + { + if (professionalRGB != null) + { + professionalRGB.Clear(); } - professionalRGB = null; + professionalRGB = null; } - -#region Colors + + #region Colors [SRDescription(nameof(SR.ProfessionalColorsButtonSelectedHighlightDescr))] - public virtual Color ButtonSelectedHighlight { + public virtual Color ButtonSelectedHighlight + { get { return FromKnownColor(KnownColors.ButtonSelectedHighlight); } } [SRDescription(nameof(SR.ProfessionalColorsButtonSelectedHighlightBorderDescr))] - public virtual Color ButtonSelectedHighlightBorder { + public virtual Color ButtonSelectedHighlightBorder + { get { return ButtonPressedBorder; } } [SRDescription(nameof(SR.ProfessionalColorsButtonPressedHighlightDescr))] - public virtual Color ButtonPressedHighlight { + public virtual Color ButtonPressedHighlight + { get { return FromKnownColor(KnownColors.ButtonPressedHighlight); } } [SRDescription(nameof(SR.ProfessionalColorsButtonPressedHighlightBorderDescr))] - public virtual Color ButtonPressedHighlightBorder { - get { return SystemColors.Highlight; } + public virtual Color ButtonPressedHighlightBorder + { + get { return SystemColors.Highlight; } } [SRDescription(nameof(SR.ProfessionalColorsButtonCheckedHighlightDescr))] - public virtual Color ButtonCheckedHighlight { + public virtual Color ButtonCheckedHighlight + { get { return FromKnownColor(KnownColors.ButtonCheckedHighlight); } } [SRDescription(nameof(SR.ProfessionalColorsButtonCheckedHighlightBorderDescr))] - public virtual Color ButtonCheckedHighlightBorder { + public virtual Color ButtonCheckedHighlightBorder + { get { return SystemColors.Highlight; } } - [SRDescription(nameof(SR.ProfessionalColorsButtonPressedBorderDescr))] - public virtual Color ButtonPressedBorder { + [SRDescription(nameof(SR.ProfessionalColorsButtonPressedBorderDescr))] + public virtual Color ButtonPressedBorder + { get { return FromKnownColor(KnownColors.msocbvcrCBCtlBdrMouseOver); } } [SRDescription(nameof(SR.ProfessionalColorsButtonSelectedBorderDescr))] - public virtual Color ButtonSelectedBorder { + public virtual Color ButtonSelectedBorder + { get { return FromKnownColor(KnownColors.msocbvcrCBCtlBdrMouseOver); } } [SRDescription(nameof(SR.ProfessionalColorsButtonCheckedGradientBeginDescr))] - public virtual Color ButtonCheckedGradientBegin { + public virtual Color ButtonCheckedGradientBegin + { get { return FromKnownColor(KnownColors.msocbvcrCBGradSelectedBegin); } - } - + } + [SRDescription(nameof(SR.ProfessionalColorsButtonCheckedGradientMiddleDescr))] - public virtual Color ButtonCheckedGradientMiddle { + public virtual Color ButtonCheckedGradientMiddle + { get { return FromKnownColor(KnownColors.msocbvcrCBGradSelectedMiddle); } } - + [SRDescription(nameof(SR.ProfessionalColorsButtonCheckedGradientEndDescr))] - public virtual Color ButtonCheckedGradientEnd { + public virtual Color ButtonCheckedGradientEnd + { get { return FromKnownColor(KnownColors.msocbvcrCBGradSelectedEnd); } } [SRDescription(nameof(SR.ProfessionalColorsButtonSelectedGradientBeginDescr))] - public virtual Color ButtonSelectedGradientBegin { + public virtual Color ButtonSelectedGradientBegin + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMouseOverBegin); } } [SRDescription(nameof(SR.ProfessionalColorsButtonSelectedGradientMiddleDescr))] - public virtual Color ButtonSelectedGradientMiddle { + public virtual Color ButtonSelectedGradientMiddle + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMouseOverMiddle); } } - + [SRDescription(nameof(SR.ProfessionalColorsButtonSelectedGradientEndDescr))] - public virtual Color ButtonSelectedGradientEnd { + public virtual Color ButtonSelectedGradientEnd + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMouseOverEnd); } } - + [SRDescription(nameof(SR.ProfessionalColorsButtonPressedGradientBeginDescr))] - public virtual Color ButtonPressedGradientBegin { + public virtual Color ButtonPressedGradientBegin + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMouseDownBegin); } } [SRDescription(nameof(SR.ProfessionalColorsButtonPressedGradientMiddleDescr))] - public virtual Color ButtonPressedGradientMiddle { + public virtual Color ButtonPressedGradientMiddle + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMouseDownMiddle); } } [SRDescription(nameof(SR.ProfessionalColorsButtonPressedGradientEndDescr))] - public virtual Color ButtonPressedGradientEnd { + public virtual Color ButtonPressedGradientEnd + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMouseDownEnd); } } [SRDescription(nameof(SR.ProfessionalColorsCheckBackgroundDescr))] - public virtual Color CheckBackground { + public virtual Color CheckBackground + { get { return FromKnownColor(KnownColors.msocbvcrCBCtlBkgdSelected); } } - - [SRDescription(nameof(SR.ProfessionalColorsCheckSelectedBackgroundDescr))] - public virtual Color CheckSelectedBackground { + + [SRDescription(nameof(SR.ProfessionalColorsCheckSelectedBackgroundDescr))] + public virtual Color CheckSelectedBackground + { get { return FromKnownColor(KnownColors.msocbvcrCBCtlBkgdSelectedMouseOver); } } [SRDescription(nameof(SR.ProfessionalColorsCheckPressedBackgroundDescr))] - public virtual Color CheckPressedBackground { + public virtual Color CheckPressedBackground + { get { return FromKnownColor(KnownColors.msocbvcrCBCtlBkgdSelectedMouseOver); } } [SRDescription(nameof(SR.ProfessionalColorsGripDarkDescr))] - public virtual Color GripDark { + public virtual Color GripDark + { get { return FromKnownColor(KnownColors.msocbvcrCBDragHandle); } } [SRDescription(nameof(SR.ProfessionalColorsGripLightDescr))] - public virtual Color GripLight { + public virtual Color GripLight + { get { return FromKnownColor(KnownColors.msocbvcrCBDragHandleShadow); } } [SRDescription(nameof(SR.ProfessionalColorsImageMarginGradientBeginDescr))] - public virtual Color ImageMarginGradientBegin { + public virtual Color ImageMarginGradientBegin + { get { return FromKnownColor(KnownColors.msocbvcrCBGradVertBegin); } } [SRDescription(nameof(SR.ProfessionalColorsImageMarginGradientMiddleDescr))] - public virtual Color ImageMarginGradientMiddle { + public virtual Color ImageMarginGradientMiddle + { get { return FromKnownColor(KnownColors.msocbvcrCBGradVertMiddle); } } [SRDescription(nameof(SR.ProfessionalColorsImageMarginGradientEndDescr))] - public virtual Color ImageMarginGradientEnd { + public virtual Color ImageMarginGradientEnd + { get { return (usingSystemColors) ? SystemColors.Control : FromKnownColor(KnownColors.msocbvcrCBGradVertEnd); } } - [SRDescription(nameof(SR.ProfessionalColorsImageMarginRevealedGradientBeginDescr))] - public virtual Color ImageMarginRevealedGradientBegin { + [SRDescription(nameof(SR.ProfessionalColorsImageMarginRevealedGradientBeginDescr))] + public virtual Color ImageMarginRevealedGradientBegin + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMenuIconBkgdDroppedBegin); } } [SRDescription(nameof(SR.ProfessionalColorsImageMarginRevealedGradientMiddleDescr))] - public virtual Color ImageMarginRevealedGradientMiddle { + public virtual Color ImageMarginRevealedGradientMiddle + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMenuIconBkgdDroppedMiddle); } } [SRDescription(nameof(SR.ProfessionalColorsImageMarginRevealedGradientEndDescr))] - public virtual Color ImageMarginRevealedGradientEnd { + public virtual Color ImageMarginRevealedGradientEnd + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMenuIconBkgdDroppedEnd); } } [SRDescription(nameof(SR.ProfessionalColorsMenuStripGradientBeginDescr))] - public virtual Color MenuStripGradientBegin { + public virtual Color MenuStripGradientBegin + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMainMenuHorzBegin); } } [SRDescription(nameof(SR.ProfessionalColorsMenuStripGradientEndDescr))] - public virtual Color MenuStripGradientEnd{ + public virtual Color MenuStripGradientEnd + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMainMenuHorzEnd); } } [SRDescription(nameof(SR.ProfessionalColorsMenuItemSelectedDescr))] - public virtual Color MenuItemSelected { - get { return FromKnownColor(KnownColors.msocbvcrCBCtlBkgdMouseOver); } + public virtual Color MenuItemSelected + { + get { return FromKnownColor(KnownColors.msocbvcrCBCtlBkgdMouseOver); } } [SRDescription(nameof(SR.ProfessionalColorsMenuItemBorderDescr))] - public virtual Color MenuItemBorder { + public virtual Color MenuItemBorder + { get { return FromKnownColor(KnownColors.msocbvcrCBCtlBdrSelected); } } [SRDescription(nameof(SR.ProfessionalColorsMenuBorderDescr))] - public virtual Color MenuBorder { + public virtual Color MenuBorder + { get { return FromKnownColor(KnownColors.msocbvcrCBMenuBdrOuter); } } [SRDescription(nameof(SR.ProfessionalColorsMenuItemSelectedGradientBeginDescr))] - public virtual Color MenuItemSelectedGradientBegin { + public virtual Color MenuItemSelectedGradientBegin + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMouseOverBegin); } } [SRDescription(nameof(SR.ProfessionalColorsMenuItemSelectedGradientEndDescr))] - public virtual Color MenuItemSelectedGradientEnd { + public virtual Color MenuItemSelectedGradientEnd + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMouseOverEnd); } } [SRDescription(nameof(SR.ProfessionalColorsMenuItemPressedGradientBeginDescr))] - public virtual Color MenuItemPressedGradientBegin { + public virtual Color MenuItemPressedGradientBegin + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMenuTitleBkgdBegin); } } [SRDescription(nameof(SR.ProfessionalColorsMenuItemPressedGradientMiddleDescr))] - public virtual Color MenuItemPressedGradientMiddle { + public virtual Color MenuItemPressedGradientMiddle + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMenuIconBkgdDroppedMiddle); } } [SRDescription(nameof(SR.ProfessionalColorsMenuItemPressedGradientEndDescr))] - public virtual Color MenuItemPressedGradientEnd { + public virtual Color MenuItemPressedGradientEnd + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMenuTitleBkgdEnd); } } [SRDescription(nameof(SR.ProfessionalColorsRaftingContainerGradientBeginDescr))] - public virtual Color RaftingContainerGradientBegin { + public virtual Color RaftingContainerGradientBegin + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMainMenuHorzBegin); } } [SRDescription(nameof(SR.ProfessionalColorsRaftingContainerGradientEndDescr))] - public virtual Color RaftingContainerGradientEnd { + public virtual Color RaftingContainerGradientEnd + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMainMenuHorzEnd); } } [SRDescription(nameof(SR.ProfessionalColorsSeparatorDarkDescr))] - public virtual Color SeparatorDark { + public virtual Color SeparatorDark + { get { return FromKnownColor(KnownColors.msocbvcrCBSplitterLine); } } [SRDescription(nameof(SR.ProfessionalColorsSeparatorLightDescr))] - public virtual Color SeparatorLight { + public virtual Color SeparatorLight + { get { return FromKnownColor(KnownColors.msocbvcrCBSplitterLineLight); } } - + [SRDescription(nameof(SR.ProfessionalColorsStatusStripGradientBeginDescr))] - public virtual Color StatusStripGradientBegin { + public virtual Color StatusStripGradientBegin + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMainMenuHorzBegin); } } - + [SRDescription(nameof(SR.ProfessionalColorsStatusStripGradientEndDescr))] - public virtual Color StatusStripGradientEnd { + public virtual Color StatusStripGradientEnd + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMainMenuHorzEnd); } } [SRDescription(nameof(SR.ProfessionalColorsToolStripBorderDescr))] - public virtual Color ToolStripBorder { + public virtual Color ToolStripBorder + { get { return FromKnownColor(KnownColors.msocbvcrCBShadow); } } [SRDescription(nameof(SR.ProfessionalColorsToolStripDropDownBackgroundDescr))] - public virtual Color ToolStripDropDownBackground { + public virtual Color ToolStripDropDownBackground + { get { return FromKnownColor(KnownColors.msocbvcrCBMenuBkgd); } } [SRDescription(nameof(SR.ProfessionalColorsToolStripGradientBeginDescr))] - public virtual Color ToolStripGradientBegin { + public virtual Color ToolStripGradientBegin + { get { return FromKnownColor(KnownColors.msocbvcrCBGradVertBegin); } } [SRDescription(nameof(SR.ProfessionalColorsToolStripGradientMiddleDescr))] - public virtual Color ToolStripGradientMiddle { + public virtual Color ToolStripGradientMiddle + { get { return FromKnownColor(KnownColors.msocbvcrCBGradVertMiddle); } } [SRDescription(nameof(SR.ProfessionalColorsToolStripGradientEndDescr))] - public virtual Color ToolStripGradientEnd { + public virtual Color ToolStripGradientEnd + { get { return FromKnownColor(KnownColors.msocbvcrCBGradVertEnd); } } - + [SRDescription(nameof(SR.ProfessionalColorsToolStripContentPanelGradientBeginDescr))] - public virtual Color ToolStripContentPanelGradientBegin { + public virtual Color ToolStripContentPanelGradientBegin + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMainMenuHorzBegin); } } [SRDescription(nameof(SR.ProfessionalColorsToolStripContentPanelGradientEndDescr))] - public virtual Color ToolStripContentPanelGradientEnd { + public virtual Color ToolStripContentPanelGradientEnd + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMainMenuHorzEnd); } } [SRDescription(nameof(SR.ProfessionalColorsToolStripPanelGradientBeginDescr))] - public virtual Color ToolStripPanelGradientBegin { + public virtual Color ToolStripPanelGradientBegin + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMainMenuHorzBegin); } } [SRDescription(nameof(SR.ProfessionalColorsToolStripPanelGradientEndDescr))] - public virtual Color ToolStripPanelGradientEnd { + public virtual Color ToolStripPanelGradientEnd + { get { return FromKnownColor(KnownColors.msocbvcrCBGradMainMenuHorzEnd); } } [SRDescription(nameof(SR.ProfessionalColorsOverflowButtonGradientBeginDescr))] - public virtual Color OverflowButtonGradientBegin { + public virtual Color OverflowButtonGradientBegin + { get { return FromKnownColor(KnownColors.msocbvcrCBGradOptionsBegin); } } - [SRDescription(nameof(SR.ProfessionalColorsOverflowButtonGradientMiddleDescr))] - public virtual Color OverflowButtonGradientMiddle { + [SRDescription(nameof(SR.ProfessionalColorsOverflowButtonGradientMiddleDescr))] + public virtual Color OverflowButtonGradientMiddle + { get { return FromKnownColor(KnownColors.msocbvcrCBGradOptionsMiddle); } } [SRDescription(nameof(SR.ProfessionalColorsOverflowButtonGradientEndDescr))] - public virtual Color OverflowButtonGradientEnd { + public virtual Color OverflowButtonGradientEnd + { get { return FromKnownColor(KnownColors.msocbvcrCBGradOptionsEnd); } } -#endregion Colors - - -#region NotDirectlyExposed - // - - - - internal Color ComboBoxButtonGradientBegin { - get { return MenuItemPressedGradientBegin; } - } - internal Color ComboBoxButtonGradientEnd { - get { return MenuItemPressedGradientEnd; } - } - internal Color ComboBoxButtonSelectedGradientBegin { - get { return MenuItemSelectedGradientBegin; } - } - internal Color ComboBoxButtonSelectedGradientEnd { - get { return MenuItemSelectedGradientEnd;} - } - internal Color ComboBoxButtonPressedGradientBegin { - get { return ButtonPressedGradientBegin; } - } - internal Color ComboBoxButtonPressedGradientEnd { - get { return ButtonPressedGradientEnd; } - } - internal Color ComboBoxButtonOnOverflow { - get { return ToolStripDropDownBackground; } - } - internal Color ComboBoxBorder { - get { return ButtonSelectedHighlightBorder; } - } - internal Color TextBoxBorder { - get { return ButtonSelectedHighlightBorder; } - } -#endregion - - - /* public virtual Color ControlLight { - get { return FromKnownColor(KnownColors.msocbvcrCBCtlBkgdLight); } - } */ - - private static Color GetAlphaBlendedColor(Graphics g, Color src, Color dest, int alpha) { + #endregion Colors + + + #region NotDirectlyExposed + // + + + + internal Color ComboBoxButtonGradientBegin + { + get { return MenuItemPressedGradientBegin; } + } + internal Color ComboBoxButtonGradientEnd + { + get { return MenuItemPressedGradientEnd; } + } + internal Color ComboBoxButtonSelectedGradientBegin + { + get { return MenuItemSelectedGradientBegin; } + } + internal Color ComboBoxButtonSelectedGradientEnd + { + get { return MenuItemSelectedGradientEnd; } + } + internal Color ComboBoxButtonPressedGradientBegin + { + get { return ButtonPressedGradientBegin; } + } + internal Color ComboBoxButtonPressedGradientEnd + { + get { return ButtonPressedGradientEnd; } + } + internal Color ComboBoxButtonOnOverflow + { + get { return ToolStripDropDownBackground; } + } + internal Color ComboBoxBorder + { + get { return ButtonSelectedHighlightBorder; } + } + internal Color TextBoxBorder + { + get { return ButtonSelectedHighlightBorder; } + } + #endregion + + + /* public virtual Color ControlLight { + get { return FromKnownColor(KnownColors.msocbvcrCBCtlBkgdLight); } + } */ + + private static Color GetAlphaBlendedColor(Graphics g, Color src, Color dest, int alpha) + { int red = (src.R * alpha + (255 - alpha) * dest.R) / 255; int green = (src.G * alpha + (255 - alpha) * dest.G) / 255; int blue = (src.B * alpha + (255 - alpha) * dest.B) / 255; int newAlpha = (src.A * alpha + (255 - alpha) * dest.A) / 255; - if (g == null) { + if (g == null) + { return Color.FromArgb(newAlpha, red, green, blue); } - else { + else + { return g.GetNearestColor(Color.FromArgb(newAlpha, red, green, blue)); } } @@ -443,7 +533,8 @@ private static Color GetAlphaBlendedColor(Graphics g, Color src, Color dest, in // this particular method gets us closer to office by increasing the resolution... - private static Color GetAlphaBlendedColorHighRes(Graphics graphics, Color src, Color dest, int alpha) { + private static Color GetAlphaBlendedColorHighRes(Graphics graphics, Color src, Color dest, int alpha) + { int sum; int nPart2; @@ -451,11 +542,13 @@ private static Color GetAlphaBlendedColorHighRes(Graphics graphics, Color src, C int nPart1 = alpha; - if (nPart1 < 100) { + if (nPart1 < 100) + { nPart2 = 100 - nPart1; sum = 100; } - else { + else + { nPart2 = 1000 - nPart1; sum = 1000; } @@ -467,35 +560,42 @@ private static Color GetAlphaBlendedColorHighRes(Graphics graphics, Color src, C g = (nPart1 * src.G + nPart2 * dest.G + sum / 2) / sum; b = (nPart1 * src.B + nPart2 * dest.B + sum / 2) / sum; - if (graphics == null) { + if (graphics == null) + { return Color.FromArgb(r, g, b); } - else { + else + { return graphics.GetNearestColor(Color.FromArgb(r, g, b)); } } - private void InitCommonColors(ref Dictionary rgbTable) { + private void InitCommonColors(ref Dictionary rgbTable) + { /// we need to calculate our own alpha blended color based on the Higlight and Window /// colors on the system. Since terminalserver + alphablending doesnt work we cant just do a /// FromARGB here. So we have a simple function which calculates the blending for us. - if (!DisplayInformation.LowResolution) { - using (Graphics g = WindowsFormsUtils.CreateMeasurementGraphics()) { + if (!DisplayInformation.LowResolution) + { + using (Graphics g = WindowsFormsUtils.CreateMeasurementGraphics()) + { rgbTable[ProfessionalColorTable.KnownColors.ButtonPressedHighlight] = GetAlphaBlendedColor(g, SystemColors.Window, GetAlphaBlendedColor(g, SystemColors.Highlight, SystemColors.Window, 160), 50); rgbTable[ProfessionalColorTable.KnownColors.ButtonCheckedHighlight] = GetAlphaBlendedColor(g, SystemColors.Window, GetAlphaBlendedColor(g, SystemColors.Highlight, SystemColors.Window, 80), 20); rgbTable[ProfessionalColorTable.KnownColors.ButtonSelectedHighlight] = rgbTable[ProfessionalColorTable.KnownColors.ButtonCheckedHighlight]; } } - else { + else + { rgbTable[ProfessionalColorTable.KnownColors.ButtonPressedHighlight] = SystemColors.Highlight; rgbTable[ProfessionalColorTable.KnownColors.ButtonCheckedHighlight] = SystemColors.ControlLight; rgbTable[ProfessionalColorTable.KnownColors.ButtonSelectedHighlight] = SystemColors.ControlLight; } } - internal void InitSystemColors(ref Dictionary rgbTable) { + internal void InitSystemColors(ref Dictionary rgbTable) + { usingSystemColors = true; InitCommonColors(ref rgbTable); @@ -505,186 +605,190 @@ internal void InitSystemColors(ref Dictionary rgbTable) { Color buttonFace = SystemColors.ButtonFace; Color buttonShadow = SystemColors.ButtonShadow; Color highlight = SystemColors.Highlight; - Color window = SystemColors.Window; + Color window = SystemColors.Window; Color empty = Color.Empty; Color controlText = SystemColors.ControlText; Color buttonHighlight = SystemColors.ButtonHighlight; - Color grayText = SystemColors.GrayText; - Color highlightText = SystemColors.HighlightText; + Color grayText = SystemColors.GrayText; + Color highlightText = SystemColors.HighlightText; Color windowText = SystemColors.WindowText; // initialize to high contrast - Color gradientBegin = buttonFace; + Color gradientBegin = buttonFace; Color gradientMiddle = buttonFace; - Color gradientEnd = buttonFace; + Color gradientEnd = buttonFace; Color msocbvcrCBCtlBkgdMouseOver = highlight; Color msocbvcrCBCtlBkgdMouseDown = highlight; bool lowResolution = DisplayInformation.LowResolution; bool highContrast = DisplayInformation.HighContrast; - - if (lowResolution) { + + if (lowResolution) + { msocbvcrCBCtlBkgdMouseOver = window; } - else if (!highContrast) { - gradientBegin = GetAlphaBlendedColorHighRes(null, buttonFace, window, 23); - gradientMiddle = GetAlphaBlendedColorHighRes(null, buttonFace, window, 50 ); - gradientEnd = SystemColors.ButtonFace; + else if (!highContrast) + { + gradientBegin = GetAlphaBlendedColorHighRes(null, buttonFace, window, 23); + gradientMiddle = GetAlphaBlendedColorHighRes(null, buttonFace, window, 50); + gradientEnd = SystemColors.ButtonFace; + - - msocbvcrCBCtlBkgdMouseOver = GetAlphaBlendedColorHighRes(null, highlight, window, 30); + msocbvcrCBCtlBkgdMouseOver = GetAlphaBlendedColorHighRes(null, highlight, window, 30); msocbvcrCBCtlBkgdMouseDown = GetAlphaBlendedColorHighRes(null, highlight, window, 50); - - + + } - - - - if (lowResolution || highContrast) { - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBkgd] = buttonFace; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdSelectedMouseOver] = SystemColors.ControlLight; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBDragHandle] = controlText; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMainMenuHorzEnd] = buttonFace; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsBegin] = buttonShadow; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsMiddle] = buttonShadow; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuIconBkgdDroppedBegin] = buttonShadow; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuIconBkgdDroppedMiddle] = buttonShadow; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuIconBkgdDroppedEnd] = buttonShadow; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuBdrOuter] = controlText; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuBkgd] = window; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBSplitterLine] = buttonShadow; + + + + if (lowResolution || highContrast) + { + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBkgd] = buttonFace; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdSelectedMouseOver] = SystemColors.ControlLight; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBDragHandle] = controlText; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMainMenuHorzEnd] = buttonFace; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsBegin] = buttonShadow; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsMiddle] = buttonShadow; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuIconBkgdDroppedBegin] = buttonShadow; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuIconBkgdDroppedMiddle] = buttonShadow; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuIconBkgdDroppedEnd] = buttonShadow; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuBdrOuter] = controlText; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuBkgd] = window; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBSplitterLine] = buttonShadow; } - else { - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBkgd] = GetAlphaBlendedColorHighRes(null, window, buttonFace, 165); - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdSelectedMouseOver] = GetAlphaBlendedColorHighRes(null, highlight, window, 50); - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBDragHandle] = GetAlphaBlendedColorHighRes(null, buttonShadow, window, 75); - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMainMenuHorzEnd] = GetAlphaBlendedColorHighRes(null, buttonFace, window, 205); - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsBegin] = GetAlphaBlendedColorHighRes(null, buttonFace, window, 70); - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsMiddle] = GetAlphaBlendedColorHighRes(null, buttonFace, window, 90); - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuIconBkgdDroppedBegin] = GetAlphaBlendedColorHighRes(null, buttonFace, window, 40); - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuIconBkgdDroppedMiddle] = GetAlphaBlendedColorHighRes(null, buttonFace, window, 70); - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuIconBkgdDroppedEnd] = GetAlphaBlendedColorHighRes(null, buttonFace, window, 90); - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuBdrOuter] = GetAlphaBlendedColorHighRes(null, controlText, buttonShadow, 20); - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuBkgd] = GetAlphaBlendedColorHighRes(null, buttonFace, window, 143); - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBSplitterLine] = GetAlphaBlendedColorHighRes(null, buttonShadow, window, 70); + else + { + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBkgd] = GetAlphaBlendedColorHighRes(null, window, buttonFace, 165); + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdSelectedMouseOver] = GetAlphaBlendedColorHighRes(null, highlight, window, 50); + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBDragHandle] = GetAlphaBlendedColorHighRes(null, buttonShadow, window, 75); + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMainMenuHorzEnd] = GetAlphaBlendedColorHighRes(null, buttonFace, window, 205); + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsBegin] = GetAlphaBlendedColorHighRes(null, buttonFace, window, 70); + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsMiddle] = GetAlphaBlendedColorHighRes(null, buttonFace, window, 90); + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuIconBkgdDroppedBegin] = GetAlphaBlendedColorHighRes(null, buttonFace, window, 40); + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuIconBkgdDroppedMiddle] = GetAlphaBlendedColorHighRes(null, buttonFace, window, 70); + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuIconBkgdDroppedEnd] = GetAlphaBlendedColorHighRes(null, buttonFace, window, 90); + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuBdrOuter] = GetAlphaBlendedColorHighRes(null, controlText, buttonShadow, 20); + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuBkgd] = GetAlphaBlendedColorHighRes(null, buttonFace, window, 143); + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBSplitterLine] = GetAlphaBlendedColorHighRes(null, buttonShadow, window, 70); } - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdSelected] = (lowResolution) ? SystemColors.ControlLight : highlight; - - - - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBdrOuterDocked] = buttonFace; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBdrOuterDocked] = buttonShadow; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBdrOuterFloating] = buttonShadow; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBdrMouseDown] = highlight; - - - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBdrMouseOver] = highlight; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBdrSelected] = highlight; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBdrSelectedMouseOver] = highlight; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgd] = empty; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdLight] = window; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdMouseDown] = highlight; -// rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdMouseOver] = (lowResolution) ? SystemColors.ControlLight : highlight; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdMouseOver] = window; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlText] = controlText; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlTextDisabled] = buttonShadow; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlTextLight] = grayText; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlTextMouseDown] = highlightText; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlTextMouseOver] = windowText; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBDockSeparatorLine] = empty; - - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBDragHandleShadow] = window; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBDropDownArrow] = empty; - - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMainMenuHorzBegin] = buttonFace; - - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseOverEnd] = msocbvcrCBCtlBkgdMouseOver; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseOverBegin] = msocbvcrCBCtlBkgdMouseOver; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseOverMiddle] = msocbvcrCBCtlBkgdMouseOver; - - - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsEnd] = buttonShadow; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsMouseOverBegin] = empty; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsMouseOverEnd] = empty; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsMouseOverMiddle] = empty; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsSelectedBegin] = empty; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsSelectedEnd] = empty; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsSelectedMiddle] = empty; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradSelectedBegin] = empty; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradSelectedEnd] = empty; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradSelectedMiddle] = empty; - - - - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradVertBegin] = gradientBegin; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradVertMiddle] = gradientMiddle; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradVertEnd] = gradientEnd; - - - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseDownBegin] = msocbvcrCBCtlBkgdMouseDown; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseDownMiddle] = msocbvcrCBCtlBkgdMouseDown; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseDownEnd] = msocbvcrCBCtlBkgdMouseDown; - - - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuTitleBkgdBegin] = gradientBegin; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuTitleBkgdEnd] = gradientMiddle; - - - - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBIconDisabledDark] = buttonShadow; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBIconDisabledLight] = buttonFace; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBLabelBkgnd] = buttonShadow; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBLowColorIconDisabled] = empty; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMainMenuBkgd] = buttonFace; - - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuCtlText] = windowText; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuCtlTextDisabled] = grayText; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuIconBkgd] = empty; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuIconBkgdDropped] = buttonShadow; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuShadow] = empty; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuSplitArrow] = buttonShadow; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBOptionsButtonShadow] = empty; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdSelected] = (lowResolution) ? SystemColors.ControlLight : highlight; + + + + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBdrOuterDocked] = buttonFace; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBdrOuterDocked] = buttonShadow; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBdrOuterFloating] = buttonShadow; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBdrMouseDown] = highlight; + + + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBdrMouseOver] = highlight; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBdrSelected] = highlight; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBdrSelectedMouseOver] = highlight; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgd] = empty; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdLight] = window; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdMouseDown] = highlight; + // rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdMouseOver] = (lowResolution) ? SystemColors.ControlLight : highlight; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdMouseOver] = window; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlText] = controlText; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlTextDisabled] = buttonShadow; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlTextLight] = grayText; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlTextMouseDown] = highlightText; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlTextMouseOver] = windowText; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBDockSeparatorLine] = empty; + + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBDragHandleShadow] = window; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBDropDownArrow] = empty; + + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMainMenuHorzBegin] = buttonFace; + + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseOverEnd] = msocbvcrCBCtlBkgdMouseOver; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseOverBegin] = msocbvcrCBCtlBkgdMouseOver; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseOverMiddle] = msocbvcrCBCtlBkgdMouseOver; + + + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsEnd] = buttonShadow; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsMouseOverBegin] = empty; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsMouseOverEnd] = empty; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsMouseOverMiddle] = empty; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsSelectedBegin] = empty; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsSelectedEnd] = empty; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsSelectedMiddle] = empty; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradSelectedBegin] = empty; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradSelectedEnd] = empty; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradSelectedMiddle] = empty; + + + + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradVertBegin] = gradientBegin; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradVertMiddle] = gradientMiddle; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradVertEnd] = gradientEnd; + + + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseDownBegin] = msocbvcrCBCtlBkgdMouseDown; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseDownMiddle] = msocbvcrCBCtlBkgdMouseDown; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseDownEnd] = msocbvcrCBCtlBkgdMouseDown; + + + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuTitleBkgdBegin] = gradientBegin; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuTitleBkgdEnd] = gradientMiddle; + + + + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBIconDisabledDark] = buttonShadow; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBIconDisabledLight] = buttonFace; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBLabelBkgnd] = buttonShadow; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBLowColorIconDisabled] = empty; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMainMenuBkgd] = buttonFace; + + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuCtlText] = windowText; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuCtlTextDisabled] = grayText; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuIconBkgd] = empty; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuIconBkgdDropped] = buttonShadow; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuShadow] = empty; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuSplitArrow] = buttonShadow; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBOptionsButtonShadow] = empty; rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBShadow] = rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBkgd]; - - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBSplitterLineLight] = buttonHighlight; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBTearOffHandle] = empty; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBTearOffHandleMouseOver] = empty; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBTitleBkgd] = buttonShadow; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBTitleText] = buttonHighlight; + + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBSplitterLineLight] = buttonHighlight; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBTearOffHandle] = empty; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBTearOffHandleMouseOver] = empty; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBTitleBkgd] = buttonShadow; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBTitleText] = buttonHighlight; rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDisabledFocuslessHighlightedText] = grayText; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDisabledHighlightedText] = grayText; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDlgGroupBoxText] = controlText; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdr] = buttonShadow; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrDark] = buttonFace; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrDarkMouseDown] = highlight; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrDarkMouseOver] = SystemColors.MenuText; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrLight] = buttonFace; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrLightMouseDown] = highlight; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrLightMouseOver] = SystemColors.MenuText; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrMouseDown] = highlight; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrMouseOver] = SystemColors.MenuText; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrSelected] = buttonShadow; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBkgd] = buttonFace; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDisabledHighlightedText] = grayText; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDlgGroupBoxText] = controlText; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdr] = buttonShadow; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrDark] = buttonFace; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrDarkMouseDown] = highlight; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrDarkMouseOver] = SystemColors.MenuText; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrLight] = buttonFace; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrLightMouseDown] = highlight; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrLightMouseOver] = SystemColors.MenuText; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrMouseDown] = highlight; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrMouseOver] = SystemColors.MenuText; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrSelected] = buttonShadow; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBkgd] = buttonFace; rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBkgdMouseDown] = highlight; rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBkgdMouseOver] = highlight; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBkgdSelected] = window; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabText] = controlText; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBkgdSelected] = window; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabText] = controlText; rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabTextMouseDown] = highlightText; rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabTextMouseOver] = highlight; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabTextSelected] = windowText; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWActiveTabBkgd] = buttonFace; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWActiveTabBkgd] = buttonShadow; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWActiveTabText] = buttonFace; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWActiveTabText] = controlText; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabTextSelected] = windowText; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWActiveTabBkgd] = buttonFace; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWActiveTabBkgd] = buttonShadow; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWActiveTabText] = buttonFace; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWActiveTabText] = controlText; rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWActiveTabTextDisabled] = buttonShadow; rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWActiveTabTextDisabled] = controlText; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWInactiveTabBkgd] = buttonFace; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWInactiveTabBkgd] = buttonShadow; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWInactiveTabText] = buttonHighlight; - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWInactiveTabText] = controlText; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWInactiveTabBkgd] = buttonFace; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWInactiveTabBkgd] = buttonShadow; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWInactiveTabText] = buttonHighlight; + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWInactiveTabText] = controlText; rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWTabBkgdMouseDown] = buttonFace; rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWTabBkgdMouseOver] = buttonFace; rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWTabTextMouseDown] = controlText; @@ -814,7 +918,8 @@ internal void InitSystemColors(ref Dictionary rgbTable) { } - internal void InitOliveLunaColors(ref Dictionary rgbTable) { + internal void InitOliveLunaColors(ref Dictionary rgbTable) + { rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBdrOuterDocked] = Color.FromArgb(81, 94, 51); rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBdrOuterDocked] = Color.FromArgb(81, 94, 51); rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBdrOuterFloating] = Color.FromArgb(116, 134, 94); @@ -1059,7 +1164,8 @@ internal void InitOliveLunaColors(ref Dictionary rgbTable) { rgbTable[ProfessionalColorTable.KnownColors.msocbvcrXLFormulaBarBkgd] = Color.FromArgb(217, 217, 167); } - internal void InitSilverLunaColors(ref Dictionary rgbTable) { + internal void InitSilverLunaColors(ref Dictionary rgbTable) + { rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBdrOuterDocked] = Color.FromArgb(173, 174, 193); rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBdrOuterFloating] = Color.FromArgb(122, 121, 153); rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBkgd] = Color.FromArgb(219, 218, 228); @@ -1300,259 +1406,266 @@ internal void InitSilverLunaColors(ref Dictionary rgbTable) { rgbTable[ProfessionalColorTable.KnownColors.msocbvcrXLFormulaBarBkgd] = Color.FromArgb(215, 215, 229); } - private void InitRoyaleColors(ref Dictionary rgbTable) { - - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBkgd] = Color.FromArgb(238,237,240); // msocbvcrCBBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBDragHandle ] = Color.FromArgb(189,188,191); // msocbvcrCBDragHandle -> Needs to equal VSCOLOR_COMMANDBAR_DRAGHANDLE in vscolors.cpp - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBSplitterLine] = Color.FromArgb(193,193,196); // msocbvcrCBSplitterLine - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBTitleBkgd] = Color.FromArgb(167,166,170); // msocbvcrCBTitleBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBTitleText] = Color.FromArgb(255,255,255); // msocbvcrCBTitleText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBdrOuterFloating] = Color.FromArgb(142,141,145); // msocbvcrCBBdrOuterFloating - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBdrOuterDocked] = Color.FromArgb(235,233,237); // msocbvcrCBBdrOuterDocked - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBTearOffHandle] = Color.FromArgb(238,237,240); // msocbvcrCBTearOffHandle - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBTearOffHandleMouseOver] = Color.FromArgb(194,207,229); // msocbvcrCBTearOffHandleMouseOver - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgd] = Color.FromArgb(238,237,240); // msocbvcrCBCtlBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlText] = Color.FromArgb(000,000,000); // msocbvcrCBCtlText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlTextDisabled] = Color.FromArgb(176,175,179); // msocbvcrCBCtlTextDisabled - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdMouseOver] = Color.FromArgb(194,207,229); // msocbvcrCBCtlBkgdMouseOver -> Needs to equal VSCOLOR_COMMANDBAR_HOVER in vscolors.cpp - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBdrMouseOver] = Color.FromArgb(51,94,168); // msocbvcrCBCtlBdrMouseOver -> Needs to equal VSCOLOR_COMMANDBAR_BORDER in vscolors.cpp - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlTextMouseOver] = Color.FromArgb(000,000,000); // msocbvcrCBCtlTextMouseOver - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdMouseDown] = Color.FromArgb(153,175,212); // msocbvcrCBCtlBkgdMouseDown -> Needs to equal VSCOLOR_COMMANDBAR_HOVEROVERSELECTED in vscolors.cpp - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBdrMouseDown] = Color.FromArgb(51,94,168); // msocbvcrCBCtlBdrMouseDown - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlTextMouseDown] = Color.FromArgb(255,255,255); // msocbvcrCBCtlTextMouseDown - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdSelected] = Color.FromArgb(226,229,238); // msocbvcrCBCtlBkgdSelected -> Needs to equal VSCOLOR_COMMANDBAR_SELECTED in vscolors.cpp - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBdrSelected] = Color.FromArgb(51,94,168); // msocbvcrCBCtlBdrSelected - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdSelectedMouseOver] = Color.FromArgb(51,94,168); // msocbvcrCBCtlBkgdSelectedMouseOver -> Needs to equal VSCOLOR_COMMANDBAR_HOVEROVERSELECTEDICON in vscolors.cpp - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBdrSelectedMouseOver] = Color.FromArgb(51,94,168); // msocbvcrCBCtlBdrSelectedMouseOver -> Needs to equal VSCOLOR_COMMANDBAR_HOVEROVERSELECTEDICON_BORDER in vscolors.cpp - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdLight] = Color.FromArgb(255,255,255); // msocbvcrCBCtlBkgdLight - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlTextLight] = Color.FromArgb(167,166,170); // msocbvcrCBCtlTextLight - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMainMenuBkgd] = Color.FromArgb(235,233,237); // msocbvcrCBMainMenuBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuBkgd] = Color.FromArgb(252,252,252); // msocbvcrCBMenuBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuCtlText] = Color.FromArgb(0,0,0); // msocbvcrCBMenuCtlText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuCtlTextDisabled] = Color.FromArgb(193,193,196); // msocbvcrCBMenuCtlTextDisabled - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuBdrOuter] = Color.FromArgb(134,133,136); // msocbvcrCBMenuBdrOuter - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuIconBkgd] = Color.FromArgb(238,237,240); // msocbvcrCBMenuIconBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuIconBkgdDropped] = Color.FromArgb(228,226,230); // msocbvcrCBMenuIconBkgdDropped - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuSplitArrow] = Color.FromArgb(167,166,170); // msocbvcrCBMenuSplitArrow - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPBkgd] = Color.FromArgb(245,244,246); // msocbvcrWPBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPText] = Color.FromArgb(255,51,153); // msocbvcrWPText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPTitleBkgdActive] = Color.FromArgb(255,51,153); // msocbvcrWPTitleBkgdActive - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPTitleBkgdInactive] = Color.FromArgb(255,51,153); // msocbvcrWPTitleBkgdInactive - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPTitleTextActive] = Color.FromArgb(255,51,153); // msocbvcrWPTitleTextActive - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPTitleTextInactive] = Color.FromArgb(255,51,153); // msocbvcrWPTitleTextInactive - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPBdrOuterFloating] = Color.FromArgb(255,51,153); // msocbvcrWPBdrOuterFloating - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPBdrOuterDocked] = Color.FromArgb(255,51,153); // msocbvcrWPBdrOuterDocked - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPCtlBdr] = Color.FromArgb(255,51,153); // msocbvcrWPCtlBdr - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPCtlText] = Color.FromArgb(255,51,153); // msocbvcrWPCtlText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPCtlBkgd] = Color.FromArgb(255,51,153); // msocbvcrWPCtlBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPCtlBdrDisabled] = Color.FromArgb(255,51,153); // msocbvcrWPCtlBdrDisabled - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPCtlTextDisabled] = Color.FromArgb(255,51,153); // msocbvcrWPCtlTextDisabled - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPCtlBkgdDisabled] = Color.FromArgb(255,51,153); // msocbvcrWPCtlBkgdDisabled - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPCtlBdrDefault] = Color.FromArgb(255,51,153); // msocbvcrWPCtlBdrDefault - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPGroupline] = Color.FromArgb(255,51,153); // msocbvcrWPGroupline - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrSBBdr] = Color.FromArgb(255,51,153); // msocbvcrSBBdr - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOBBkgdBdr] = Color.FromArgb(255,51,153); // msocbvcrOBBkgdBdr - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOBBkgdBdrContrast] = Color.FromArgb(255,51,153); // msocbvcrOBBkgdBdrContrast - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOABBkgd] = Color.FromArgb(255,51,153); // msocbvcrOABBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGDHeaderBkgd] = Color.FromArgb(255,51,153); // msocbvcrGDHeaderBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGDHeaderBdr] = Color.FromArgb(255,51,153); // msocbvcrGDHeaderBdr - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGDHeaderCellBdr] = Color.FromArgb(255,51,153); // msocbvcrGDHeaderCellBdr - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGDHeaderSeeThroughSelection] = Color.FromArgb(255,51,153); // msocbvcrGDHeaderSeeThroughSelection - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGDHeaderCellBkgd] = Color.FromArgb(255,51,153); // msocbvcrGDHeaderCellBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGDHeaderCellBkgdSelected] = Color.FromArgb(255,51,153); // msocbvcrGDHeaderCellBkgdSelected - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBSplitterLineLight] = Color.FromArgb(255,255,255); // msocbvcrCBSplitterLineLight - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBShadow] = Color.FromArgb(238,237,240); // msocbvcrCBShadow -> Needs to equal VSCOLOR_COMMANDBAR_SHADOW in vscolors.cpp - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBOptionsButtonShadow] = Color.FromArgb(245,244,246); // msocbvcrCBOptionsButtonShadow - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPNavBarBkgnd] = Color.FromArgb(193,193,196); // msocbvcrWPNavBarBkgnd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPBdrInnerDocked] = Color.FromArgb(245,244,246); // msocbvcrWPBdrInnerDocked - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBLabelBkgnd] = Color.FromArgb(235,233,237); // msocbvcrCBLabelBkgnd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBIconDisabledLight] = Color.FromArgb(235,233,237); // msocbvcrCBIconDisabledLight - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBIconDisabledDark] = Color.FromArgb(167,166,170); // msocbvcrCBIconDisabledDark - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBLowColorIconDisabled] = Color.FromArgb(176,175,179); // msocbvcrCBLowColorIconDisabled - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMainMenuHorzBegin] = Color.FromArgb(235,233,237); // msocbvcrCBGradMainMenuHorzBegin -> Needs to equal VSCOLOR_ENVIRONMENT_BACKGROUND and VSCOLOR_ENVIRONMENT_BACKGROUND_GRADIENTBEGIN in vscolors.cpp - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMainMenuHorzEnd] = Color.FromArgb(251,250,251); // msocbvcrCBGradMainMenuHorzEnd -> Needs to equal VSCOLOR_ENVIRONMENT_BACKGROUND_GRADIENTEND in vscolors.cpp - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradVertBegin] = Color.FromArgb(252,252,252); // msocbvcrCBGradVertBegin -> Needs to equal VSCOLOR_COMMANDBAR_GRADIENT_BEGIN in vscolors.cpp - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradVertMiddle] = Color.FromArgb(245,244,246); // msocbvcrCBGradVertMiddle -> Needs to equal VSCOLOR_COMMANDBAR_GRADIENT_MIDDLE in vscolors.cpp - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradVertEnd] = Color.FromArgb(235,233,237); // msocbvcrCBGradVertEnd -> Needs to equal VSCOLOR_COMMANDBAR_GRADIENT_END in vscolors.cpp - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsBegin] = Color.FromArgb(242,242,242); // msocbvcrCBGradOptionsBegin - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsMiddle] = Color.FromArgb(224,224,225); // msocbvcrCBGradOptionsMiddle - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsEnd] = Color.FromArgb(167,166,170); // msocbvcrCBGradOptionsEnd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuTitleBkgdBegin] = Color.FromArgb(252,252,252); // msocbvcrCBGradMenuTitleBkgdBegin - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuTitleBkgdEnd] = Color.FromArgb(245,244,246); // msocbvcrCBGradMenuTitleBkgdEnd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuIconBkgdDroppedBegin] = Color.FromArgb(247,246,248); // msocbvcrCBGradMenuIconBkgdDroppedBegin - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuIconBkgdDroppedMiddle] = Color.FromArgb(241,240,242); // msocbvcrCBGradMenuIconBkgdDroppedMiddle - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuIconBkgdDroppedEnd] = Color.FromArgb(228,226,230); // msocbvcrCBGradMenuIconBkgdDroppedEnd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsSelectedBegin] = Color.FromArgb(226,229,238); // msocbvcrCBGradOptionsSelectedBegin - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsSelectedMiddle] = Color.FromArgb(226,229,238); // msocbvcrCBGradOptionsSelectedMiddle - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsSelectedEnd] = Color.FromArgb(226,229,238); // msocbvcrCBGradOptionsSelectedEnd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsMouseOverBegin] = Color.FromArgb(194,207,229); // msocbvcrCBGradOptionsMouseOverBegin - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsMouseOverMiddle] = Color.FromArgb(194,207,229); // msocbvcrCBGradOptionsMouseOverMiddle - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsMouseOverEnd] = Color.FromArgb(194,207,229); // msocbvcrCBGradOptionsMouseOverEnd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradSelectedBegin] = Color.FromArgb(226,229,238); // msocbvcrCBGradSelectedBegin - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradSelectedMiddle] = Color.FromArgb(226,229,238); // msocbvcrCBGradSelectedMiddle - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradSelectedEnd] = Color.FromArgb(226,229,238); // msocbvcrCBGradSelectedEnd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseOverBegin] = Color.FromArgb(194,207,229); // msocbvcrCBGradMouseOverBegin - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseOverMiddle] = Color.FromArgb(194,207,229); // msocbvcrCBGradMouseOverMiddle - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseOverEnd] = Color.FromArgb(194,207,229); // msocbvcrCBGradMouseOverEnd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseDownBegin] = Color.FromArgb(153,175,212); // msocbvcrCBGradMouseDownBegin - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseDownMiddle] = Color.FromArgb(153,175,212); // msocbvcrCBGradMouseDownMiddle - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseDownEnd] = Color.FromArgb(153,175,212); // msocbvcrCBGradMouseDownEnd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrNetLookBkgnd] = Color.FromArgb(235,233,237); // msocbvcrNetLookBkgnd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuShadow] = Color.FromArgb(000,000,000); // msocbvcrCBMenuShadow - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBDockSeparatorLine] = Color.FromArgb(51,94,168); // msocbvcrCBDockSeparatorLine - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBDropDownArrow] = Color.FromArgb(235,233,237); // msocbvcrCBDropDownArrow - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKGridlines] = Color.FromArgb(255,51,153); // msocbvcrOLKGridlines - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKGroupText] = Color.FromArgb(255,51,153); // msocbvcrOLKGroupText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKGroupLine] = Color.FromArgb(255,51,153); // msocbvcrOLKGroupLine - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKGroupShaded] = Color.FromArgb(255,51,153); // msocbvcrOLKGroupShaded - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKGroupNested] = Color.FromArgb(255,51,153); // msocbvcrOLKGroupNested - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKIconBar] = Color.FromArgb(255,51,153); // msocbvcrOLKIconBar - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKFlagNone] = Color.FromArgb(255,51,153); // msocbvcrOLKFlagNone - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKFolderbarLight] = Color.FromArgb(255,51,153); // msocbvcrOLKFolderbarLight - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKFolderbarDark] = Color.FromArgb(255,51,153); // msocbvcrOLKFolderbarDark - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKFolderbarText] = Color.FromArgb(255,51,153); // msocbvcrOLKFolderbarText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBButtonLight] = Color.FromArgb(255,51,153); // msocbvcrOLKWBButtonLight - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBButtonDark] = Color.FromArgb(255,51,153); // msocbvcrOLKWBButtonDark - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBSelectedButtonLight] = Color.FromArgb(255,51,153); // msocbvcrOLKWBSelectedButtonLight - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBSelectedButtonDark] = Color.FromArgb(255,51,153); // msocbvcrOLKWBSelectedButtonDark - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBHoverButtonLight] = Color.FromArgb(255,51,153); // msocbvcrOLKWBHoverButtonLight - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBHoverButtonDark] = Color.FromArgb(255,51,153); // msocbvcrOLKWBHoverButtonDark - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBPressedButtonLight] = Color.FromArgb(255,51,153); // msocbvcrOLKWBPressedButtonLight - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBPressedButtonDark] = Color.FromArgb(255,51,153); // msocbvcrOLKWBPressedButtonDark - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBDarkOutline] = Color.FromArgb(255,51,153); // msocbvcrOLKWBDarkOutline - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBSplitterLight] = Color.FromArgb(255,51,153); // msocbvcrOLKWBSplitterLight - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBSplitterDark] = Color.FromArgb(255,51,153); // msocbvcrOLKWBSplitterDark - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBActionDividerLine] = Color.FromArgb(255,51,153); // msocbvcrOLKWBActionDividerLine - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBLabelText] = Color.FromArgb(255,51,153); // msocbvcrOLKWBLabelText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBFoldersBackground] = Color.FromArgb(255,51,153); // msocbvcrOLKWBFoldersBackground - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKTodayIndicatorLight] = Color.FromArgb(255,51,153); // msocbvcrOLKTodayIndicatorLight - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKTodayIndicatorDark] = Color.FromArgb(255,51,153); // msocbvcrOLKTodayIndicatorDark - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKInfoBarBkgd] = Color.FromArgb(255,51,153); // msocbvcrOLKInfoBarBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKInfoBarText] = Color.FromArgb(255,51,153); // msocbvcrOLKInfoBarText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKPreviewPaneLabelText] = Color.FromArgb(255,51,153); // msocbvcrOLKPreviewPaneLabelText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrHyperlink] = Color.FromArgb(0,61,178); // msocbvcrHyperlink - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrHyperlinkFollowed] = Color.FromArgb(170,0,170); // msocbvcrHyperlinkFollowed - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGWorkspaceBkgd] = Color.FromArgb(255,51,153); // msocbvcrOGWorkspaceBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGMDIParentWorkspaceBkgd] = Color.FromArgb(255,51,153); // msocbvcrOGMDIParentWorkspaceBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGRulerBkgd] = Color.FromArgb(255,51,153); // msocbvcrOGRulerBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGRulerActiveBkgd] = Color.FromArgb(255,51,153); // msocbvcrOGRulerActiveBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGRulerInactiveBkgd] = Color.FromArgb(255,51,153); // msocbvcrOGRulerInactiveBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGRulerText] = Color.FromArgb(255,51,153); // msocbvcrOGRulerText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGRulerTabStopTicks] = Color.FromArgb(255,51,153); // msocbvcrOGRulerTabStopTicks - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGRulerBdr] = Color.FromArgb(255,51,153); // msocbvcrOGRulerBdr - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGRulerTabBoxBdr] = Color.FromArgb(255,51,153); // msocbvcrOGRulerTabBoxBdr - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGRulerTabBoxBdrHighlight] = Color.FromArgb(255,51,153); // msocbvcrOGRulerTabBoxBdrHighlight - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrXLFormulaBarBkgd] = Color.FromArgb(255,51,153); // msocbvcrXLFormulaBarBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBDragHandleShadow] = Color.FromArgb(255,255,255); // msocbvcrCBDragHandleShadow -> Needs to equal VSCOLOR_COMMANDBAR_DRAGHANDLE_SHADOW in vscolors.cpp - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGTaskPaneGroupBoxHeaderBkgd] = Color.FromArgb(255,51,153); // msocbvcrOGTaskPaneGroupBoxHeaderBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPPOutlineThumbnailsPaneTabAreaBkgd] = Color.FromArgb(255,51,153); // msocbvcrPPOutlineThumbnailsPaneTabAreaBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPPOutlineThumbnailsPaneTabInactiveBkgd] = Color.FromArgb(255,51,153); // msocbvcrPPOutlineThumbnailsPaneTabInactiveBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPPOutlineThumbnailsPaneTabBdr] = Color.FromArgb(255,51,153); // msocbvcrPPOutlineThumbnailsPaneTabBdr - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPPOutlineThumbnailsPaneTabText] = Color.FromArgb(255,51,153); // msocbvcrPPOutlineThumbnailsPaneTabText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPPSlideBdrActiveSelected] = Color.FromArgb(255,51,153); // msocbvcrPPSlideBdrActiveSelected - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPPSlideBdrInactiveSelected] = Color.FromArgb(255,51,153); // msocbvcrPPSlideBdrInactiveSelected - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPPSlideBdrMouseOver] = Color.FromArgb(255,51,153); // msocbvcrPPSlideBdrMouseOver - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPPSlideBdrActiveSelectedMouseOver] = Color.FromArgb(255,51,153); // msocbvcrPPSlideBdrActiveSelectedMouseOver - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDlgGroupBoxText] = Color.FromArgb(0,0,0); // msocbvcrDlgGroupBoxText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrScrollbarBkgd] = Color.FromArgb(237,235,239); // msocbvcrScrollbarBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrListHeaderArrow] = Color.FromArgb(155,154,156); // msocbvcrListHeaderArrow - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDisabledHighlightedText] = Color.FromArgb(188,202,226); // msocbvcrDisabledHighlightedText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrFocuslessHighlightedBkgd] = Color.FromArgb(235,233,237); // msocbvcrFocuslessHighlightedBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrFocuslessHighlightedText] = Color.FromArgb(000,000,000); // msocbvcrFocuslessHighlightedText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDisabledFocuslessHighlightedText] = Color.FromArgb(167,166,170); // msocbvcrDisabledFocuslessHighlightedText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPCtlTextMouseDown] = Color.FromArgb(255,51,153); // msocbvcrWPCtlTextMouseDown - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPTextDisabled] = Color.FromArgb(255,51,153); // msocbvcrWPTextDisabled - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPInfoTipBkgd] = Color.FromArgb(255,51,153); // msocbvcrWPInfoTipBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPInfoTipText] = Color.FromArgb(255,51,153); // msocbvcrWPInfoTipText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWActiveTabBkgd] = Color.FromArgb(255,51,153); // msocbvcrDWActiveTabBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWActiveTabText] = Color.FromArgb(255,51,153); // msocbvcrDWActiveTabText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWActiveTabTextDisabled] = Color.FromArgb(255,51,153); // msocbvcrDWActiveTabTextDisabled - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWInactiveTabBkgd] = Color.FromArgb(255,51,153); // msocbvcrDWInactiveTabBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWInactiveTabText] = Color.FromArgb(255,51,153); // msocbvcrDWInactiveTabText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWTabBkgdMouseOver] = Color.FromArgb(255,51,153); // msocbvcrDWTabBkgdMouseOver - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWTabTextMouseOver] = Color.FromArgb(255,51,153); // msocbvcrDWTabTextMouseOver - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWTabBkgdMouseDown] = Color.FromArgb(255,51,153); // msocbvcrDWTabBkgdMouseDown - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWTabTextMouseDown] = Color.FromArgb(255,51,153); // msocbvcrDWTabTextMouseDown - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPLightBkgd] = Color.FromArgb(255,51,153); // msocbvcrGSPLightBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPDarkBkgd] = Color.FromArgb(255,51,153); // msocbvcrGSPDarkBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPGroupHeaderLightBkgd] = Color.FromArgb(255,51,153); // msocbvcrGSPGroupHeaderLightBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPGroupHeaderDarkBkgd] = Color.FromArgb(255,51,153); // msocbvcrGSPGroupHeaderDarkBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPGroupHeaderText] = Color.FromArgb(255,51,153); // msocbvcrGSPGroupHeaderText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPGroupContentLightBkgd] = Color.FromArgb(255,51,153); // msocbvcrGSPGroupContentLightBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPGroupContentDarkBkgd] = Color.FromArgb(255,51,153); // msocbvcrGSPGroupContentDarkBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPGroupContentText] = Color.FromArgb(255,51,153); // msocbvcrGSPGroupContentText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPGroupContentTextDisabled] = Color.FromArgb(255,51,153); // msocbvcrGSPGroupContentTextDisabled - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPGroupline] = Color.FromArgb(255,51,153); // msocbvcrGSPGroupline - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPHyperlink] = Color.FromArgb(255,51,153); // msocbvcrGSPHyperlink - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBkgd] = Color.FromArgb(212,212,226); // msocbvcrDocTabBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabText] = Color.FromArgb(000,000,000); // msocbvcrDocTabText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdr] = Color.FromArgb(118,116,146); // msocbvcrDocTabBdr - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrLight] = Color.FromArgb(255,255,255); // msocbvcrDocTabBdrLight - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrDark] = Color.FromArgb(186,185,206); // msocbvcrDocTabBdrDark - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBkgdSelected] = Color.FromArgb(255,255,255); // msocbvcrDocTabBkgdSelected - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabTextSelected] = Color.FromArgb(000,000,000); // msocbvcrDocTabTextSelected - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrSelected] = Color.FromArgb(124,124,148); // msocbvcrDocTabBdrSelected - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBkgdMouseOver] = Color.FromArgb(193,210,238); // msocbvcrDocTabBkgdMouseOver - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabTextMouseOver] = Color.FromArgb(49,106,197); // msocbvcrDocTabTextMouseOver - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrMouseOver] = Color.FromArgb(49,106,197); // msocbvcrDocTabBdrMouseOver - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrLightMouseOver] = Color.FromArgb(49,106,197); // msocbvcrDocTabBdrLightMouseOver - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrDarkMouseOver] = Color.FromArgb(49,106,197); // msocbvcrDocTabBdrDarkMouseOver - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBkgdMouseDown] = Color.FromArgb(154,183,228); // msocbvcrDocTabBkgdMouseDown - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabTextMouseDown] = Color.FromArgb(000,000,000); // msocbvcrDocTabTextMouseDown - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrMouseDown] = Color.FromArgb(75,75,111); // msocbvcrDocTabBdrMouseDown - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrLightMouseDown] = Color.FromArgb(75,75,111); // msocbvcrDocTabBdrLightMouseDown - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrDarkMouseDown] = Color.FromArgb(75,75,111); // msocbvcrDocTabBdrDarkMouseDown - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrToastGradBegin] = Color.FromArgb(246,244,236); // msocbvcrToastGradBegin - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrToastGradEnd] = Color.FromArgb(179,178,204); // msocbvcrToastGradEnd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrJotNavUIGradBegin] = Color.FromArgb(236,233,216); // msocbvcrJotNavUIGradBegin - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrJotNavUIGradMiddle] = Color.FromArgb(236,233,216); // msocbvcrJotNavUIGradMiddle - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrJotNavUIGradEnd] = Color.FromArgb(255,255,255); // msocbvcrJotNavUIGradEnd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrJotNavUIText] = Color.FromArgb(000,000,000); // msocbvcrJotNavUIText - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrJotNavUIBdr] = Color.FromArgb(172,168,153); // msocbvcrJotNavUIBdr - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPlacesBarBkgd] = Color.FromArgb(224,223,227); // msocbvcrPlacesBarBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPubPrintDocScratchPageBkgd] = Color.FromArgb(152,181,226); // msocbvcrPubPrintDocScratchPageBkgd - rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPubWebDocScratchPageBkgd] = Color.FromArgb(193,210,238); // msocbvcrPubWebDocScratchPageBkgd - - } - - - - - internal void InitThemedColors(ref Dictionary rgbTable) { + private void InitRoyaleColors(ref Dictionary rgbTable) + { + + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBkgd] = Color.FromArgb(238, 237, 240); // msocbvcrCBBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBDragHandle] = Color.FromArgb(189, 188, 191); // msocbvcrCBDragHandle -> Needs to equal VSCOLOR_COMMANDBAR_DRAGHANDLE in vscolors.cpp + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBSplitterLine] = Color.FromArgb(193, 193, 196); // msocbvcrCBSplitterLine + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBTitleBkgd] = Color.FromArgb(167, 166, 170); // msocbvcrCBTitleBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBTitleText] = Color.FromArgb(255, 255, 255); // msocbvcrCBTitleText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBdrOuterFloating] = Color.FromArgb(142, 141, 145); // msocbvcrCBBdrOuterFloating + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBdrOuterDocked] = Color.FromArgb(235, 233, 237); // msocbvcrCBBdrOuterDocked + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBTearOffHandle] = Color.FromArgb(238, 237, 240); // msocbvcrCBTearOffHandle + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBTearOffHandleMouseOver] = Color.FromArgb(194, 207, 229); // msocbvcrCBTearOffHandleMouseOver + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgd] = Color.FromArgb(238, 237, 240); // msocbvcrCBCtlBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlText] = Color.FromArgb(000, 000, 000); // msocbvcrCBCtlText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlTextDisabled] = Color.FromArgb(176, 175, 179); // msocbvcrCBCtlTextDisabled + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdMouseOver] = Color.FromArgb(194, 207, 229); // msocbvcrCBCtlBkgdMouseOver -> Needs to equal VSCOLOR_COMMANDBAR_HOVER in vscolors.cpp + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBdrMouseOver] = Color.FromArgb(51, 94, 168); // msocbvcrCBCtlBdrMouseOver -> Needs to equal VSCOLOR_COMMANDBAR_BORDER in vscolors.cpp + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlTextMouseOver] = Color.FromArgb(000, 000, 000); // msocbvcrCBCtlTextMouseOver + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdMouseDown] = Color.FromArgb(153, 175, 212); // msocbvcrCBCtlBkgdMouseDown -> Needs to equal VSCOLOR_COMMANDBAR_HOVEROVERSELECTED in vscolors.cpp + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBdrMouseDown] = Color.FromArgb(51, 94, 168); // msocbvcrCBCtlBdrMouseDown + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlTextMouseDown] = Color.FromArgb(255, 255, 255); // msocbvcrCBCtlTextMouseDown + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdSelected] = Color.FromArgb(226, 229, 238); // msocbvcrCBCtlBkgdSelected -> Needs to equal VSCOLOR_COMMANDBAR_SELECTED in vscolors.cpp + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBdrSelected] = Color.FromArgb(51, 94, 168); // msocbvcrCBCtlBdrSelected + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdSelectedMouseOver] = Color.FromArgb(51, 94, 168); // msocbvcrCBCtlBkgdSelectedMouseOver -> Needs to equal VSCOLOR_COMMANDBAR_HOVEROVERSELECTEDICON in vscolors.cpp + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBdrSelectedMouseOver] = Color.FromArgb(51, 94, 168); // msocbvcrCBCtlBdrSelectedMouseOver -> Needs to equal VSCOLOR_COMMANDBAR_HOVEROVERSELECTEDICON_BORDER in vscolors.cpp + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlBkgdLight] = Color.FromArgb(255, 255, 255); // msocbvcrCBCtlBkgdLight + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBCtlTextLight] = Color.FromArgb(167, 166, 170); // msocbvcrCBCtlTextLight + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMainMenuBkgd] = Color.FromArgb(235, 233, 237); // msocbvcrCBMainMenuBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuBkgd] = Color.FromArgb(252, 252, 252); // msocbvcrCBMenuBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuCtlText] = Color.FromArgb(0, 0, 0); // msocbvcrCBMenuCtlText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuCtlTextDisabled] = Color.FromArgb(193, 193, 196); // msocbvcrCBMenuCtlTextDisabled + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuBdrOuter] = Color.FromArgb(134, 133, 136); // msocbvcrCBMenuBdrOuter + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuIconBkgd] = Color.FromArgb(238, 237, 240); // msocbvcrCBMenuIconBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuIconBkgdDropped] = Color.FromArgb(228, 226, 230); // msocbvcrCBMenuIconBkgdDropped + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuSplitArrow] = Color.FromArgb(167, 166, 170); // msocbvcrCBMenuSplitArrow + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPBkgd] = Color.FromArgb(245, 244, 246); // msocbvcrWPBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPText] = Color.FromArgb(255, 51, 153); // msocbvcrWPText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPTitleBkgdActive] = Color.FromArgb(255, 51, 153); // msocbvcrWPTitleBkgdActive + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPTitleBkgdInactive] = Color.FromArgb(255, 51, 153); // msocbvcrWPTitleBkgdInactive + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPTitleTextActive] = Color.FromArgb(255, 51, 153); // msocbvcrWPTitleTextActive + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPTitleTextInactive] = Color.FromArgb(255, 51, 153); // msocbvcrWPTitleTextInactive + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPBdrOuterFloating] = Color.FromArgb(255, 51, 153); // msocbvcrWPBdrOuterFloating + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPBdrOuterDocked] = Color.FromArgb(255, 51, 153); // msocbvcrWPBdrOuterDocked + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPCtlBdr] = Color.FromArgb(255, 51, 153); // msocbvcrWPCtlBdr + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPCtlText] = Color.FromArgb(255, 51, 153); // msocbvcrWPCtlText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPCtlBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrWPCtlBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPCtlBdrDisabled] = Color.FromArgb(255, 51, 153); // msocbvcrWPCtlBdrDisabled + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPCtlTextDisabled] = Color.FromArgb(255, 51, 153); // msocbvcrWPCtlTextDisabled + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPCtlBkgdDisabled] = Color.FromArgb(255, 51, 153); // msocbvcrWPCtlBkgdDisabled + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPCtlBdrDefault] = Color.FromArgb(255, 51, 153); // msocbvcrWPCtlBdrDefault + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPGroupline] = Color.FromArgb(255, 51, 153); // msocbvcrWPGroupline + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrSBBdr] = Color.FromArgb(255, 51, 153); // msocbvcrSBBdr + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOBBkgdBdr] = Color.FromArgb(255, 51, 153); // msocbvcrOBBkgdBdr + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOBBkgdBdrContrast] = Color.FromArgb(255, 51, 153); // msocbvcrOBBkgdBdrContrast + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOABBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrOABBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGDHeaderBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrGDHeaderBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGDHeaderBdr] = Color.FromArgb(255, 51, 153); // msocbvcrGDHeaderBdr + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGDHeaderCellBdr] = Color.FromArgb(255, 51, 153); // msocbvcrGDHeaderCellBdr + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGDHeaderSeeThroughSelection] = Color.FromArgb(255, 51, 153); // msocbvcrGDHeaderSeeThroughSelection + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGDHeaderCellBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrGDHeaderCellBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGDHeaderCellBkgdSelected] = Color.FromArgb(255, 51, 153); // msocbvcrGDHeaderCellBkgdSelected + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBSplitterLineLight] = Color.FromArgb(255, 255, 255); // msocbvcrCBSplitterLineLight + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBShadow] = Color.FromArgb(238, 237, 240); // msocbvcrCBShadow -> Needs to equal VSCOLOR_COMMANDBAR_SHADOW in vscolors.cpp + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBOptionsButtonShadow] = Color.FromArgb(245, 244, 246); // msocbvcrCBOptionsButtonShadow + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPNavBarBkgnd] = Color.FromArgb(193, 193, 196); // msocbvcrWPNavBarBkgnd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPBdrInnerDocked] = Color.FromArgb(245, 244, 246); // msocbvcrWPBdrInnerDocked + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBLabelBkgnd] = Color.FromArgb(235, 233, 237); // msocbvcrCBLabelBkgnd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBIconDisabledLight] = Color.FromArgb(235, 233, 237); // msocbvcrCBIconDisabledLight + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBIconDisabledDark] = Color.FromArgb(167, 166, 170); // msocbvcrCBIconDisabledDark + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBLowColorIconDisabled] = Color.FromArgb(176, 175, 179); // msocbvcrCBLowColorIconDisabled + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMainMenuHorzBegin] = Color.FromArgb(235, 233, 237); // msocbvcrCBGradMainMenuHorzBegin -> Needs to equal VSCOLOR_ENVIRONMENT_BACKGROUND and VSCOLOR_ENVIRONMENT_BACKGROUND_GRADIENTBEGIN in vscolors.cpp + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMainMenuHorzEnd] = Color.FromArgb(251, 250, 251); // msocbvcrCBGradMainMenuHorzEnd -> Needs to equal VSCOLOR_ENVIRONMENT_BACKGROUND_GRADIENTEND in vscolors.cpp + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradVertBegin] = Color.FromArgb(252, 252, 252); // msocbvcrCBGradVertBegin -> Needs to equal VSCOLOR_COMMANDBAR_GRADIENT_BEGIN in vscolors.cpp + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradVertMiddle] = Color.FromArgb(245, 244, 246); // msocbvcrCBGradVertMiddle -> Needs to equal VSCOLOR_COMMANDBAR_GRADIENT_MIDDLE in vscolors.cpp + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradVertEnd] = Color.FromArgb(235, 233, 237); // msocbvcrCBGradVertEnd -> Needs to equal VSCOLOR_COMMANDBAR_GRADIENT_END in vscolors.cpp + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsBegin] = Color.FromArgb(242, 242, 242); // msocbvcrCBGradOptionsBegin + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsMiddle] = Color.FromArgb(224, 224, 225); // msocbvcrCBGradOptionsMiddle + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsEnd] = Color.FromArgb(167, 166, 170); // msocbvcrCBGradOptionsEnd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuTitleBkgdBegin] = Color.FromArgb(252, 252, 252); // msocbvcrCBGradMenuTitleBkgdBegin + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuTitleBkgdEnd] = Color.FromArgb(245, 244, 246); // msocbvcrCBGradMenuTitleBkgdEnd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuIconBkgdDroppedBegin] = Color.FromArgb(247, 246, 248); // msocbvcrCBGradMenuIconBkgdDroppedBegin + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuIconBkgdDroppedMiddle] = Color.FromArgb(241, 240, 242); // msocbvcrCBGradMenuIconBkgdDroppedMiddle + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMenuIconBkgdDroppedEnd] = Color.FromArgb(228, 226, 230); // msocbvcrCBGradMenuIconBkgdDroppedEnd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsSelectedBegin] = Color.FromArgb(226, 229, 238); // msocbvcrCBGradOptionsSelectedBegin + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsSelectedMiddle] = Color.FromArgb(226, 229, 238); // msocbvcrCBGradOptionsSelectedMiddle + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsSelectedEnd] = Color.FromArgb(226, 229, 238); // msocbvcrCBGradOptionsSelectedEnd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsMouseOverBegin] = Color.FromArgb(194, 207, 229); // msocbvcrCBGradOptionsMouseOverBegin + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsMouseOverMiddle] = Color.FromArgb(194, 207, 229); // msocbvcrCBGradOptionsMouseOverMiddle + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradOptionsMouseOverEnd] = Color.FromArgb(194, 207, 229); // msocbvcrCBGradOptionsMouseOverEnd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradSelectedBegin] = Color.FromArgb(226, 229, 238); // msocbvcrCBGradSelectedBegin + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradSelectedMiddle] = Color.FromArgb(226, 229, 238); // msocbvcrCBGradSelectedMiddle + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradSelectedEnd] = Color.FromArgb(226, 229, 238); // msocbvcrCBGradSelectedEnd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseOverBegin] = Color.FromArgb(194, 207, 229); // msocbvcrCBGradMouseOverBegin + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseOverMiddle] = Color.FromArgb(194, 207, 229); // msocbvcrCBGradMouseOverMiddle + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseOverEnd] = Color.FromArgb(194, 207, 229); // msocbvcrCBGradMouseOverEnd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseDownBegin] = Color.FromArgb(153, 175, 212); // msocbvcrCBGradMouseDownBegin + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseDownMiddle] = Color.FromArgb(153, 175, 212); // msocbvcrCBGradMouseDownMiddle + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBGradMouseDownEnd] = Color.FromArgb(153, 175, 212); // msocbvcrCBGradMouseDownEnd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrNetLookBkgnd] = Color.FromArgb(235, 233, 237); // msocbvcrNetLookBkgnd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBMenuShadow] = Color.FromArgb(000, 000, 000); // msocbvcrCBMenuShadow + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBDockSeparatorLine] = Color.FromArgb(51, 94, 168); // msocbvcrCBDockSeparatorLine + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBDropDownArrow] = Color.FromArgb(235, 233, 237); // msocbvcrCBDropDownArrow + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKGridlines] = Color.FromArgb(255, 51, 153); // msocbvcrOLKGridlines + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKGroupText] = Color.FromArgb(255, 51, 153); // msocbvcrOLKGroupText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKGroupLine] = Color.FromArgb(255, 51, 153); // msocbvcrOLKGroupLine + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKGroupShaded] = Color.FromArgb(255, 51, 153); // msocbvcrOLKGroupShaded + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKGroupNested] = Color.FromArgb(255, 51, 153); // msocbvcrOLKGroupNested + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKIconBar] = Color.FromArgb(255, 51, 153); // msocbvcrOLKIconBar + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKFlagNone] = Color.FromArgb(255, 51, 153); // msocbvcrOLKFlagNone + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKFolderbarLight] = Color.FromArgb(255, 51, 153); // msocbvcrOLKFolderbarLight + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKFolderbarDark] = Color.FromArgb(255, 51, 153); // msocbvcrOLKFolderbarDark + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKFolderbarText] = Color.FromArgb(255, 51, 153); // msocbvcrOLKFolderbarText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBButtonLight] = Color.FromArgb(255, 51, 153); // msocbvcrOLKWBButtonLight + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBButtonDark] = Color.FromArgb(255, 51, 153); // msocbvcrOLKWBButtonDark + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBSelectedButtonLight] = Color.FromArgb(255, 51, 153); // msocbvcrOLKWBSelectedButtonLight + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBSelectedButtonDark] = Color.FromArgb(255, 51, 153); // msocbvcrOLKWBSelectedButtonDark + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBHoverButtonLight] = Color.FromArgb(255, 51, 153); // msocbvcrOLKWBHoverButtonLight + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBHoverButtonDark] = Color.FromArgb(255, 51, 153); // msocbvcrOLKWBHoverButtonDark + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBPressedButtonLight] = Color.FromArgb(255, 51, 153); // msocbvcrOLKWBPressedButtonLight + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBPressedButtonDark] = Color.FromArgb(255, 51, 153); // msocbvcrOLKWBPressedButtonDark + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBDarkOutline] = Color.FromArgb(255, 51, 153); // msocbvcrOLKWBDarkOutline + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBSplitterLight] = Color.FromArgb(255, 51, 153); // msocbvcrOLKWBSplitterLight + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBSplitterDark] = Color.FromArgb(255, 51, 153); // msocbvcrOLKWBSplitterDark + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBActionDividerLine] = Color.FromArgb(255, 51, 153); // msocbvcrOLKWBActionDividerLine + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBLabelText] = Color.FromArgb(255, 51, 153); // msocbvcrOLKWBLabelText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKWBFoldersBackground] = Color.FromArgb(255, 51, 153); // msocbvcrOLKWBFoldersBackground + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKTodayIndicatorLight] = Color.FromArgb(255, 51, 153); // msocbvcrOLKTodayIndicatorLight + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKTodayIndicatorDark] = Color.FromArgb(255, 51, 153); // msocbvcrOLKTodayIndicatorDark + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKInfoBarBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrOLKInfoBarBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKInfoBarText] = Color.FromArgb(255, 51, 153); // msocbvcrOLKInfoBarText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOLKPreviewPaneLabelText] = Color.FromArgb(255, 51, 153); // msocbvcrOLKPreviewPaneLabelText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrHyperlink] = Color.FromArgb(0, 61, 178); // msocbvcrHyperlink + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrHyperlinkFollowed] = Color.FromArgb(170, 0, 170); // msocbvcrHyperlinkFollowed + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGWorkspaceBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrOGWorkspaceBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGMDIParentWorkspaceBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrOGMDIParentWorkspaceBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGRulerBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrOGRulerBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGRulerActiveBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrOGRulerActiveBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGRulerInactiveBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrOGRulerInactiveBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGRulerText] = Color.FromArgb(255, 51, 153); // msocbvcrOGRulerText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGRulerTabStopTicks] = Color.FromArgb(255, 51, 153); // msocbvcrOGRulerTabStopTicks + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGRulerBdr] = Color.FromArgb(255, 51, 153); // msocbvcrOGRulerBdr + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGRulerTabBoxBdr] = Color.FromArgb(255, 51, 153); // msocbvcrOGRulerTabBoxBdr + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGRulerTabBoxBdrHighlight] = Color.FromArgb(255, 51, 153); // msocbvcrOGRulerTabBoxBdrHighlight + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrXLFormulaBarBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrXLFormulaBarBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBDragHandleShadow] = Color.FromArgb(255, 255, 255); // msocbvcrCBDragHandleShadow -> Needs to equal VSCOLOR_COMMANDBAR_DRAGHANDLE_SHADOW in vscolors.cpp + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrOGTaskPaneGroupBoxHeaderBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrOGTaskPaneGroupBoxHeaderBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPPOutlineThumbnailsPaneTabAreaBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrPPOutlineThumbnailsPaneTabAreaBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPPOutlineThumbnailsPaneTabInactiveBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrPPOutlineThumbnailsPaneTabInactiveBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPPOutlineThumbnailsPaneTabBdr] = Color.FromArgb(255, 51, 153); // msocbvcrPPOutlineThumbnailsPaneTabBdr + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPPOutlineThumbnailsPaneTabText] = Color.FromArgb(255, 51, 153); // msocbvcrPPOutlineThumbnailsPaneTabText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPPSlideBdrActiveSelected] = Color.FromArgb(255, 51, 153); // msocbvcrPPSlideBdrActiveSelected + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPPSlideBdrInactiveSelected] = Color.FromArgb(255, 51, 153); // msocbvcrPPSlideBdrInactiveSelected + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPPSlideBdrMouseOver] = Color.FromArgb(255, 51, 153); // msocbvcrPPSlideBdrMouseOver + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPPSlideBdrActiveSelectedMouseOver] = Color.FromArgb(255, 51, 153); // msocbvcrPPSlideBdrActiveSelectedMouseOver + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDlgGroupBoxText] = Color.FromArgb(0, 0, 0); // msocbvcrDlgGroupBoxText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrScrollbarBkgd] = Color.FromArgb(237, 235, 239); // msocbvcrScrollbarBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrListHeaderArrow] = Color.FromArgb(155, 154, 156); // msocbvcrListHeaderArrow + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDisabledHighlightedText] = Color.FromArgb(188, 202, 226); // msocbvcrDisabledHighlightedText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrFocuslessHighlightedBkgd] = Color.FromArgb(235, 233, 237); // msocbvcrFocuslessHighlightedBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrFocuslessHighlightedText] = Color.FromArgb(000, 000, 000); // msocbvcrFocuslessHighlightedText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDisabledFocuslessHighlightedText] = Color.FromArgb(167, 166, 170); // msocbvcrDisabledFocuslessHighlightedText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPCtlTextMouseDown] = Color.FromArgb(255, 51, 153); // msocbvcrWPCtlTextMouseDown + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPTextDisabled] = Color.FromArgb(255, 51, 153); // msocbvcrWPTextDisabled + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPInfoTipBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrWPInfoTipBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrWPInfoTipText] = Color.FromArgb(255, 51, 153); // msocbvcrWPInfoTipText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWActiveTabBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrDWActiveTabBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWActiveTabText] = Color.FromArgb(255, 51, 153); // msocbvcrDWActiveTabText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWActiveTabTextDisabled] = Color.FromArgb(255, 51, 153); // msocbvcrDWActiveTabTextDisabled + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWInactiveTabBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrDWInactiveTabBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWInactiveTabText] = Color.FromArgb(255, 51, 153); // msocbvcrDWInactiveTabText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWTabBkgdMouseOver] = Color.FromArgb(255, 51, 153); // msocbvcrDWTabBkgdMouseOver + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWTabTextMouseOver] = Color.FromArgb(255, 51, 153); // msocbvcrDWTabTextMouseOver + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWTabBkgdMouseDown] = Color.FromArgb(255, 51, 153); // msocbvcrDWTabBkgdMouseDown + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDWTabTextMouseDown] = Color.FromArgb(255, 51, 153); // msocbvcrDWTabTextMouseDown + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPLightBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrGSPLightBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPDarkBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrGSPDarkBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPGroupHeaderLightBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrGSPGroupHeaderLightBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPGroupHeaderDarkBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrGSPGroupHeaderDarkBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPGroupHeaderText] = Color.FromArgb(255, 51, 153); // msocbvcrGSPGroupHeaderText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPGroupContentLightBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrGSPGroupContentLightBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPGroupContentDarkBkgd] = Color.FromArgb(255, 51, 153); // msocbvcrGSPGroupContentDarkBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPGroupContentText] = Color.FromArgb(255, 51, 153); // msocbvcrGSPGroupContentText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPGroupContentTextDisabled] = Color.FromArgb(255, 51, 153); // msocbvcrGSPGroupContentTextDisabled + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPGroupline] = Color.FromArgb(255, 51, 153); // msocbvcrGSPGroupline + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrGSPHyperlink] = Color.FromArgb(255, 51, 153); // msocbvcrGSPHyperlink + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBkgd] = Color.FromArgb(212, 212, 226); // msocbvcrDocTabBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabText] = Color.FromArgb(000, 000, 000); // msocbvcrDocTabText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdr] = Color.FromArgb(118, 116, 146); // msocbvcrDocTabBdr + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrLight] = Color.FromArgb(255, 255, 255); // msocbvcrDocTabBdrLight + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrDark] = Color.FromArgb(186, 185, 206); // msocbvcrDocTabBdrDark + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBkgdSelected] = Color.FromArgb(255, 255, 255); // msocbvcrDocTabBkgdSelected + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabTextSelected] = Color.FromArgb(000, 000, 000); // msocbvcrDocTabTextSelected + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrSelected] = Color.FromArgb(124, 124, 148); // msocbvcrDocTabBdrSelected + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBkgdMouseOver] = Color.FromArgb(193, 210, 238); // msocbvcrDocTabBkgdMouseOver + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabTextMouseOver] = Color.FromArgb(49, 106, 197); // msocbvcrDocTabTextMouseOver + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrMouseOver] = Color.FromArgb(49, 106, 197); // msocbvcrDocTabBdrMouseOver + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrLightMouseOver] = Color.FromArgb(49, 106, 197); // msocbvcrDocTabBdrLightMouseOver + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrDarkMouseOver] = Color.FromArgb(49, 106, 197); // msocbvcrDocTabBdrDarkMouseOver + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBkgdMouseDown] = Color.FromArgb(154, 183, 228); // msocbvcrDocTabBkgdMouseDown + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabTextMouseDown] = Color.FromArgb(000, 000, 000); // msocbvcrDocTabTextMouseDown + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrMouseDown] = Color.FromArgb(75, 75, 111); // msocbvcrDocTabBdrMouseDown + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrLightMouseDown] = Color.FromArgb(75, 75, 111); // msocbvcrDocTabBdrLightMouseDown + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrDocTabBdrDarkMouseDown] = Color.FromArgb(75, 75, 111); // msocbvcrDocTabBdrDarkMouseDown + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrToastGradBegin] = Color.FromArgb(246, 244, 236); // msocbvcrToastGradBegin + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrToastGradEnd] = Color.FromArgb(179, 178, 204); // msocbvcrToastGradEnd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrJotNavUIGradBegin] = Color.FromArgb(236, 233, 216); // msocbvcrJotNavUIGradBegin + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrJotNavUIGradMiddle] = Color.FromArgb(236, 233, 216); // msocbvcrJotNavUIGradMiddle + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrJotNavUIGradEnd] = Color.FromArgb(255, 255, 255); // msocbvcrJotNavUIGradEnd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrJotNavUIText] = Color.FromArgb(000, 000, 000); // msocbvcrJotNavUIText + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrJotNavUIBdr] = Color.FromArgb(172, 168, 153); // msocbvcrJotNavUIBdr + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPlacesBarBkgd] = Color.FromArgb(224, 223, 227); // msocbvcrPlacesBarBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPubPrintDocScratchPageBkgd] = Color.FromArgb(152, 181, 226); // msocbvcrPubPrintDocScratchPageBkgd + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrPubWebDocScratchPageBkgd] = Color.FromArgb(193, 210, 238); // msocbvcrPubWebDocScratchPageBkgd + + } + + + + + internal void InitThemedColors(ref Dictionary rgbTable) + { string colorScheme = VisualStyleInformation.ColorScheme; string themeFileName = System.IO.Path.GetFileName(VisualStyleInformation.ThemeFilename); bool initializedTable = false; // VS compares the filename of the theme to determine luna v. royale. - if (string.Equals(lunaFileName, themeFileName, StringComparison.OrdinalIgnoreCase)) { + if (string.Equals(lunaFileName, themeFileName, StringComparison.OrdinalIgnoreCase)) + { // once we know it's luna we've got to pick between // normal (blue) homestead (olive) and metallic (silver) - if (colorScheme == normalColorScheme) { + if (colorScheme == normalColorScheme) + { InitBlueLunaColors(ref rgbTable); usingSystemColors = false; initializedTable = true; } - else if (colorScheme == oliveColorScheme) { + else if (colorScheme == oliveColorScheme) + { InitOliveLunaColors(ref rgbTable); usingSystemColors = false; initializedTable = true; } - else if (colorScheme == silverColorScheme) { + else if (colorScheme == silverColorScheme) + { InitSilverLunaColors(ref rgbTable); usingSystemColors = false; initializedTable = true; } } - else if (string.Equals(aeroFileName, themeFileName, StringComparison.OrdinalIgnoreCase)) { + else if (string.Equals(aeroFileName, themeFileName, StringComparison.OrdinalIgnoreCase)) + { // On Vista running Aero theme, Office looks like it's using SystemColors // With the exception of the MenuItemSelected Color for MenuStrip items that // are contained in DropDowns. We're going to copy their behavior InitSystemColors(ref rgbTable); usingSystemColors = true; initializedTable = true; - + // Exception to SystemColors, use the ButtonSelectedHighlight color otherwise // the background for DropDown MenuStrip items will have no contrast rgbTable[KnownColors.msocbvcrCBCtlBkgdMouseOver] = rgbTable[KnownColors.ButtonSelectedHighlight]; @@ -1560,20 +1673,23 @@ internal void InitThemedColors(ref Dictionary rgbTable) { // CheckedBackground of ToolStripMenuItem rgbTable[KnownColors.msocbvcrCBCtlBkgdSelected] = rgbTable[KnownColors.msocbvcrCBCtlBkgdMouseOver]; } - else if (string.Equals(royaleFileName, themeFileName,StringComparison.OrdinalIgnoreCase)) { + else if (string.Equals(royaleFileName, themeFileName, StringComparison.OrdinalIgnoreCase)) + { // once we know it's royale (TabletPC/MCE) we know about two color scheme names // which should do exactly the same thing - if (colorScheme == normalColorScheme || colorScheme == royaleColorScheme ) { + if (colorScheme == normalColorScheme || colorScheme == royaleColorScheme) + { InitRoyaleColors(ref rgbTable); usingSystemColors = false; initializedTable = true; } } - - - if (!initializedTable) { + + + if (!initializedTable) + { // unknown color scheme - bailing InitSystemColors(ref rgbTable); @@ -1581,11 +1697,12 @@ internal void InitThemedColors(ref Dictionary rgbTable) { } InitCommonColors(ref rgbTable); - + } - internal void InitBlueLunaColors(ref Dictionary rgbTable) { - + internal void InitBlueLunaColors(ref Dictionary rgbTable) + { + rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBdrOuterDocked] = Color.FromArgb(196, 205, 218); rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBdrOuterDocked] = Color.FromArgb(196, 205, 218); rgbTable[ProfessionalColorTable.KnownColors.msocbvcrCBBdrOuterFloating] = Color.FromArgb(42, 102, 201); @@ -1830,9 +1947,10 @@ internal void InitBlueLunaColors(ref Dictionary rgbTable) { rgbTable[ProfessionalColorTable.KnownColors.msocbvcrXLFormulaBarBkgd] = Color.FromArgb(158, 190, 245); } - - internal enum KnownColors { + + internal enum KnownColors + { msocbvcrCBBdrOuterDocked, msocbvcrCBBdrOuterFloating, msocbvcrCBBkgd, @@ -2051,6 +2169,6 @@ internal enum KnownColors { } - + } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ProfessionalColors.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ProfessionalColors.cs index 2d1e915fbcc..aecedd66b88 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ProfessionalColors.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ProfessionalColors.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; @@ -10,8 +11,9 @@ namespace System.Windows.Forms { using System.Drawing; using System.Collections; using System.Diagnostics; - - public sealed class ProfessionalColors { + + public sealed class ProfessionalColors + { [ThreadStatic] private static ProfessionalColorTable professionalColorTable = null; @@ -21,364 +23,432 @@ public sealed class ProfessionalColors { [ThreadStatic] private static object colorFreshnessKey = null; - - internal static ProfessionalColorTable ColorTable { - get { - if (professionalColorTable == null) { + + internal static ProfessionalColorTable ColorTable + { + get + { + if (professionalColorTable == null) + { professionalColorTable = new ProfessionalColorTable(); } return professionalColorTable; } } - static ProfessionalColors() { + static ProfessionalColors() + { SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(OnUserPreferenceChanged); SetScheme(); } - private ProfessionalColors() { + private ProfessionalColors() + { } - - internal static string ColorScheme { + + internal static string ColorScheme + { get { return colorScheme; } } // internal object used between professional color tables // to identify when a userpreferencechanged has occurred - internal static object ColorFreshnessKey { + internal static object ColorFreshnessKey + { get { return colorFreshnessKey; } } -#region Colors + #region Colors [SRDescription(nameof(SR.ProfessionalColorsButtonSelectedHighlightDescr))] - public static Color ButtonSelectedHighlight { + public static Color ButtonSelectedHighlight + { get { return ColorTable.ButtonSelectedHighlight; } } [SRDescription(nameof(SR.ProfessionalColorsButtonSelectedHighlightBorderDescr))] - public static Color ButtonSelectedHighlightBorder { + public static Color ButtonSelectedHighlightBorder + { get { return ColorTable.ButtonSelectedHighlightBorder; } } [SRDescription(nameof(SR.ProfessionalColorsButtonPressedHighlightDescr))] - public static Color ButtonPressedHighlight { - get { return ColorTable.ButtonPressedHighlight; } + public static Color ButtonPressedHighlight + { + get { return ColorTable.ButtonPressedHighlight; } } [SRDescription(nameof(SR.ProfessionalColorsButtonPressedHighlightBorderDescr))] - public static Color ButtonPressedHighlightBorder { - get { return ColorTable.ButtonPressedHighlightBorder; } + public static Color ButtonPressedHighlightBorder + { + get { return ColorTable.ButtonPressedHighlightBorder; } } - + [SRDescription(nameof(SR.ProfessionalColorsButtonCheckedHighlightDescr))] - public static Color ButtonCheckedHighlight { + public static Color ButtonCheckedHighlight + { get { return ColorTable.ButtonCheckedHighlight; } } [SRDescription(nameof(SR.ProfessionalColorsButtonCheckedHighlightBorderDescr))] - public static Color ButtonCheckedHighlightBorder { + public static Color ButtonCheckedHighlightBorder + { get { return ColorTable.ButtonCheckedHighlightBorder; } } [SRDescription(nameof(SR.ProfessionalColorsButtonPressedBorderDescr))] - public static Color ButtonPressedBorder { + public static Color ButtonPressedBorder + { get { return ColorTable.ButtonPressedBorder; } } [SRDescription(nameof(SR.ProfessionalColorsButtonSelectedBorderDescr))] - public static Color ButtonSelectedBorder { + public static Color ButtonSelectedBorder + { get { return ColorTable.ButtonSelectedBorder; } } [SRDescription(nameof(SR.ProfessionalColorsButtonCheckedGradientBeginDescr))] - public static Color ButtonCheckedGradientBegin { + public static Color ButtonCheckedGradientBegin + { get { return ColorTable.ButtonCheckedGradientBegin; } } [SRDescription(nameof(SR.ProfessionalColorsButtonCheckedGradientMiddleDescr))] - public static Color ButtonCheckedGradientMiddle { + public static Color ButtonCheckedGradientMiddle + { get { return ColorTable.ButtonCheckedGradientMiddle; } } [SRDescription(nameof(SR.ProfessionalColorsButtonCheckedGradientEndDescr))] - public static Color ButtonCheckedGradientEnd { + public static Color ButtonCheckedGradientEnd + { get { return ColorTable.ButtonCheckedGradientEnd; } } [SRDescription(nameof(SR.ProfessionalColorsButtonSelectedGradientBeginDescr))] - public static Color ButtonSelectedGradientBegin { + public static Color ButtonSelectedGradientBegin + { get { return ColorTable.ButtonSelectedGradientBegin; } } [SRDescription(nameof(SR.ProfessionalColorsButtonSelectedGradientMiddleDescr))] - public static Color ButtonSelectedGradientMiddle { + public static Color ButtonSelectedGradientMiddle + { get { return ColorTable.ButtonSelectedGradientMiddle; } } [SRDescription(nameof(SR.ProfessionalColorsButtonSelectedGradientEndDescr))] - public static Color ButtonSelectedGradientEnd { + public static Color ButtonSelectedGradientEnd + { get { return ColorTable.ButtonSelectedGradientEnd; } } [SRDescription(nameof(SR.ProfessionalColorsButtonPressedGradientBeginDescr))] - public static Color ButtonPressedGradientBegin { + public static Color ButtonPressedGradientBegin + { get { return ColorTable.ButtonPressedGradientBegin; } } - + [SRDescription(nameof(SR.ProfessionalColorsButtonPressedGradientMiddleDescr))] - public static Color ButtonPressedGradientMiddle { + public static Color ButtonPressedGradientMiddle + { get { return ColorTable.ButtonPressedGradientMiddle; } } - + [SRDescription(nameof(SR.ProfessionalColorsButtonPressedGradientEndDescr))] - public static Color ButtonPressedGradientEnd { + public static Color ButtonPressedGradientEnd + { get { return ColorTable.ButtonPressedGradientEnd; } } [SRDescription(nameof(SR.ProfessionalColorsCheckBackgroundDescr))] - public static Color CheckBackground { + public static Color CheckBackground + { get { return ColorTable.CheckBackground; } } - + [SRDescription(nameof(SR.ProfessionalColorsCheckSelectedBackgroundDescr))] - public static Color CheckSelectedBackground { + public static Color CheckSelectedBackground + { get { return ColorTable.CheckSelectedBackground; } } - + [SRDescription(nameof(SR.ProfessionalColorsCheckPressedBackgroundDescr))] - public static Color CheckPressedBackground { + public static Color CheckPressedBackground + { get { return ColorTable.CheckPressedBackground; } } - + [SRDescription(nameof(SR.ProfessionalColorsGripDarkDescr))] - public static Color GripDark { + public static Color GripDark + { get { return ColorTable.GripDark; } } [SRDescription(nameof(SR.ProfessionalColorsGripLightDescr))] - public static Color GripLight { + public static Color GripLight + { get { return ColorTable.GripLight; } } - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + [SRDescription(nameof(SR.ProfessionalColorsImageMarginGradientBeginDescr))] - public static Color ImageMarginGradientBegin { + public static Color ImageMarginGradientBegin + { get { return ColorTable.ImageMarginGradientBegin; } } [SRDescription(nameof(SR.ProfessionalColorsImageMarginGradientMiddleDescr))] - public static Color ImageMarginGradientMiddle { + public static Color ImageMarginGradientMiddle + { get { return ColorTable.ImageMarginGradientMiddle; } } [SRDescription(nameof(SR.ProfessionalColorsImageMarginGradientEndDescr))] - public static Color ImageMarginGradientEnd { + public static Color ImageMarginGradientEnd + { get { return ColorTable.ImageMarginGradientEnd; } } [SRDescription(nameof(SR.ProfessionalColorsImageMarginRevealedGradientBeginDescr))] - public static Color ImageMarginRevealedGradientBegin { + public static Color ImageMarginRevealedGradientBegin + { get { return ColorTable.ImageMarginRevealedGradientBegin; } } [SRDescription(nameof(SR.ProfessionalColorsImageMarginRevealedGradientMiddleDescr))] - public static Color ImageMarginRevealedGradientMiddle { + public static Color ImageMarginRevealedGradientMiddle + { get { return ColorTable.ImageMarginRevealedGradientMiddle; } } [SRDescription(nameof(SR.ProfessionalColorsImageMarginRevealedGradientEndDescr))] - public static Color ImageMarginRevealedGradientEnd { + public static Color ImageMarginRevealedGradientEnd + { get { return ColorTable.ImageMarginRevealedGradientEnd; } } [SRDescription(nameof(SR.ProfessionalColorsMenuStripGradientBeginDescr))] - public static Color MenuStripGradientBegin { + public static Color MenuStripGradientBegin + { get { return ColorTable.MenuStripGradientBegin; } } [SRDescription(nameof(SR.ProfessionalColorsMenuStripGradientEndDescr))] - public static Color MenuStripGradientEnd{ + public static Color MenuStripGradientEnd + { get { return ColorTable.MenuStripGradientEnd; } } [SRDescription(nameof(SR.ProfessionalColorsMenuBorderDescr))] - public static Color MenuBorder { + public static Color MenuBorder + { get { return ColorTable.MenuBorder; } } [SRDescription(nameof(SR.ProfessionalColorsMenuItemSelectedDescr))] - public static Color MenuItemSelected { - get { return ColorTable.MenuItemSelected; } + public static Color MenuItemSelected + { + get { return ColorTable.MenuItemSelected; } } [SRDescription(nameof(SR.ProfessionalColorsMenuItemBorderDescr))] - public static Color MenuItemBorder { + public static Color MenuItemBorder + { get { return ColorTable.MenuItemBorder; } } [SRDescription(nameof(SR.ProfessionalColorsMenuItemSelectedGradientBeginDescr))] - public static Color MenuItemSelectedGradientBegin { + public static Color MenuItemSelectedGradientBegin + { get { return ColorTable.MenuItemSelectedGradientBegin; } } [SRDescription(nameof(SR.ProfessionalColorsMenuItemSelectedGradientEndDescr))] - public static Color MenuItemSelectedGradientEnd { + public static Color MenuItemSelectedGradientEnd + { get { return ColorTable.MenuItemSelectedGradientEnd; } } [SRDescription(nameof(SR.ProfessionalColorsMenuItemPressedGradientBeginDescr))] - public static Color MenuItemPressedGradientBegin { + public static Color MenuItemPressedGradientBegin + { get { return ColorTable.MenuItemPressedGradientBegin; } } [SRDescription(nameof(SR.ProfessionalColorsMenuItemPressedGradientMiddleDescr))] - public static Color MenuItemPressedGradientMiddle { + public static Color MenuItemPressedGradientMiddle + { get { return ColorTable.MenuItemPressedGradientMiddle; } } [SRDescription(nameof(SR.ProfessionalColorsMenuItemPressedGradientEndDescr))] - public static Color MenuItemPressedGradientEnd { + public static Color MenuItemPressedGradientEnd + { get { return ColorTable.MenuItemPressedGradientEnd; } } - + [SRDescription(nameof(SR.ProfessionalColorsRaftingContainerGradientBeginDescr))] - public static Color RaftingContainerGradientBegin { + public static Color RaftingContainerGradientBegin + { get { return ColorTable.RaftingContainerGradientBegin; } } [SRDescription(nameof(SR.ProfessionalColorsRaftingContainerGradientEndDescr))] - public static Color RaftingContainerGradientEnd { + public static Color RaftingContainerGradientEnd + { get { return ColorTable.RaftingContainerGradientEnd; } } [SRDescription(nameof(SR.ProfessionalColorsSeparatorDarkDescr))] - public static Color SeparatorDark { + public static Color SeparatorDark + { get { return ColorTable.SeparatorDark; } } [SRDescription(nameof(SR.ProfessionalColorsSeparatorLightDescr))] - public static Color SeparatorLight { + public static Color SeparatorLight + { get { return ColorTable.SeparatorLight; } } [SRDescription(nameof(SR.ProfessionalColorsStatusStripGradientBeginDescr))] - public static Color StatusStripGradientBegin { + public static Color StatusStripGradientBegin + { get { return ColorTable.StatusStripGradientBegin; } } - + [SRDescription(nameof(SR.ProfessionalColorsStatusStripGradientEndDescr))] - public static Color StatusStripGradientEnd { + public static Color StatusStripGradientEnd + { get { return ColorTable.StatusStripGradientEnd; } } [SRDescription(nameof(SR.ProfessionalColorsToolStripBorderDescr))] - public static Color ToolStripBorder { + public static Color ToolStripBorder + { get { return ColorTable.ToolStripBorder; } } [SRDescription(nameof(SR.ProfessionalColorsToolStripDropDownBackgroundDescr))] - public static Color ToolStripDropDownBackground { + public static Color ToolStripDropDownBackground + { get { return ColorTable.ToolStripDropDownBackground; } } [SRDescription(nameof(SR.ProfessionalColorsToolStripGradientBeginDescr))] - public static Color ToolStripGradientBegin { + public static Color ToolStripGradientBegin + { get { return ColorTable.ToolStripGradientBegin; } } [SRDescription(nameof(SR.ProfessionalColorsToolStripGradientMiddleDescr))] - public static Color ToolStripGradientMiddle { + public static Color ToolStripGradientMiddle + { get { return ColorTable.ToolStripGradientMiddle; } } [SRDescription(nameof(SR.ProfessionalColorsToolStripGradientEndDescr))] - public static Color ToolStripGradientEnd { + public static Color ToolStripGradientEnd + { get { return ColorTable.ToolStripGradientEnd; } } [SRDescription(nameof(SR.ProfessionalColorsToolStripContentPanelGradientBeginDescr))] - public static Color ToolStripContentPanelGradientBegin { + public static Color ToolStripContentPanelGradientBegin + { get { return ColorTable.ToolStripContentPanelGradientBegin; } } - + [SRDescription(nameof(SR.ProfessionalColorsToolStripContentPanelGradientEndDescr))] - public static Color ToolStripContentPanelGradientEnd { + public static Color ToolStripContentPanelGradientEnd + { get { return ColorTable.ToolStripContentPanelGradientEnd; } } - + [SRDescription(nameof(SR.ProfessionalColorsToolStripPanelGradientBeginDescr))] - public static Color ToolStripPanelGradientBegin { + public static Color ToolStripPanelGradientBegin + { get { return ColorTable.ToolStripPanelGradientBegin; } } - + [SRDescription(nameof(SR.ProfessionalColorsToolStripPanelGradientEndDescr))] - public static Color ToolStripPanelGradientEnd { + public static Color ToolStripPanelGradientEnd + { get { return ColorTable.ToolStripPanelGradientEnd; } } [SRDescription(nameof(SR.ProfessionalColorsOverflowButtonGradientBeginDescr))] - public static Color OverflowButtonGradientBegin { + public static Color OverflowButtonGradientBegin + { get { return ColorTable.OverflowButtonGradientBegin; } } [SRDescription(nameof(SR.ProfessionalColorsOverflowButtonGradientMiddleDescr))] - public static Color OverflowButtonGradientMiddle { + public static Color OverflowButtonGradientMiddle + { get { return ColorTable.OverflowButtonGradientMiddle; } } [SRDescription(nameof(SR.ProfessionalColorsOverflowButtonGradientEndDescr))] - public static Color OverflowButtonGradientEnd { + public static Color OverflowButtonGradientEnd + { get { return ColorTable.OverflowButtonGradientEnd; } } -#endregion Colors + #endregion Colors + + /* public static Color ControlLight { + get { return FromKnownColor(KnownColors.msocbvcrCBCtlBkgdLight); } + } */ - /* public static Color ControlLight { - get { return FromKnownColor(KnownColors.msocbvcrCBCtlBkgdLight); } - } */ - - - private static void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e) { + + private static void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e) + { SetScheme(); - if (e.Category == UserPreferenceCategory.Color) { + if (e.Category == UserPreferenceCategory.Color) + { colorFreshnessKey = new object(); } } - private static void SetScheme() { - if (VisualStyleRenderer.IsSupported) { + private static void SetScheme() + { + if (VisualStyleRenderer.IsSupported) + { colorScheme = VisualStyleInformation.ColorScheme; } - else { + else + { colorScheme = null; } } } - + } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs index 7c34a5c452b..bcbef49b28f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -30,7 +31,8 @@ namespace System.Windows.Forms { DefaultBindingProperty(nameof(Value)), SRDescription(nameof(SR.DescriptionProgressBar)) ] - public class ProgressBar : Control { + public class ProgressBar : Control + { //# VS7 205: simcooke @@ -63,7 +65,8 @@ public class ProgressBar : Control { /// /// public ProgressBar() - : base() { + : base() + { SetStyle(ControlStyles.UserPaint | ControlStyles.UseTextForAccessibility | ControlStyles.Selectable, false); @@ -78,18 +81,23 @@ public ProgressBar() /// correctly. /// /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ClassName = NativeMethods.WC_PROGRESS; - if (this.Style == ProgressBarStyle.Continuous) { + if (this.Style == ProgressBarStyle.Continuous) + { cp.Style |= NativeMethods.PBS_SMOOTH; } - else if (this.Style == ProgressBarStyle.Marquee && !DesignMode) { + else if (this.Style == ProgressBarStyle.Marquee && !DesignMode) + { cp.Style |= NativeMethods.PBS_MARQUEE; } - if (RightToLeft == RightToLeft.Yes && RightToLeftLayout == true) { + if (RightToLeft == RightToLeft.Yes && RightToLeftLayout == true) + { //We want to turn on mirroring for Form explicitly. cp.ExStyle |= NativeMethods.WS_EX_LAYOUTRTL; //Don't need these styles when mirroring is turned on. @@ -102,11 +110,14 @@ protected override CreateParams CreateParams { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override bool AllowDrop { - get { + public override bool AllowDrop + { + get + { return base.AllowDrop; } - set { + set + { base.AllowDrop = value; } } @@ -114,11 +125,14 @@ public override bool AllowDrop { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } @@ -136,14 +150,19 @@ public override Image BackgroundImage { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ProgressBarStyleDescr)) ] - public ProgressBarStyle Style { - get { + public ProgressBarStyle Style + { + get + { return style; } - set { - if (style != value) { + set + { + if (style != value) + { //valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)ProgressBarStyle.Blocks, (int)ProgressBarStyle.Marquee)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)ProgressBarStyle.Blocks, (int)ProgressBarStyle.Marquee)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ProgressBarStyle)); } style = value; @@ -158,7 +177,8 @@ public ProgressBarStyle Style { } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged { + new public event EventHandler BackgroundImageChanged + { add => base.BackgroundImageChanged += value; remove => base.BackgroundImageChanged -= value; } @@ -167,17 +187,21 @@ public ProgressBarStyle Style { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { + new public event EventHandler BackgroundImageLayoutChanged + { add => base.BackgroundImageLayoutChanged += value; remove => base.BackgroundImageLayoutChanged -= value; } @@ -185,23 +209,29 @@ public override ImageLayout BackgroundImageLayout { /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new bool CausesValidation { - get { + public new bool CausesValidation + { + get + { return base.CausesValidation; } - set { + set + { base.CausesValidation = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler CausesValidationChanged { + new public event EventHandler CausesValidationChanged + { add => base.CausesValidationChanged += value; remove => base.CausesValidationChanged -= value; } - protected override ImeMode DefaultImeMode { - get { + protected override ImeMode DefaultImeMode + { + get + { return ImeMode.Disable; } } @@ -210,8 +240,10 @@ protected override ImeMode DefaultImeMode { /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(100, 23); } } @@ -221,11 +253,14 @@ protected override Size DefaultSize { /// on controls that are based on Win32 Native Controls. /// [EditorBrowsable(EditorBrowsableState.Never)] - protected override bool DoubleBuffered { - get { + protected override bool DoubleBuffered + { + get + { return base.DoubleBuffered; } - set { + set + { base.DoubleBuffered = value; } } @@ -236,33 +271,41 @@ protected override bool DoubleBuffered { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Font Font { - get { + public override Font Font + { + get + { return base.Font; } - set { + set + { base.Font = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler FontChanged { + new public event EventHandler FontChanged + { add => base.FontChanged += value; remove => base.FontChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public ImeMode ImeMode { - get { + new public ImeMode ImeMode + { + get + { return base.ImeMode; } - set { + set + { base.ImeMode = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler ImeModeChanged { + public new event EventHandler ImeModeChanged + { add => base.ImeModeChanged += value; remove => base.ImeModeChanged -= value; } @@ -275,20 +318,25 @@ public override Font Font { /// /// [ - DefaultValue(100), - SRCategory(nameof(SR.CatBehavior)), + DefaultValue(100), + SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ProgressBarMarqueeAnimationSpeed))] - public int MarqueeAnimationSpeed { - get { + public int MarqueeAnimationSpeed + { + get + { return marqueeSpeed; - } + } [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] - set { - if (value < 0) { + set + { + if (value < 0) + { throw new ArgumentOutOfRangeException("MarqueeAnimationSpeed must be non-negative"); } marqueeSpeed = value; - if (!DesignMode) { + if (!DesignMode) + { StartMarquee(); } } @@ -326,27 +374,34 @@ private void StartMarquee() RefreshProperties(RefreshProperties.Repaint), SRDescription(nameof(SR.ProgressBarMaximumDescr)) ] - public int Maximum { - get { + public int Maximum + { + get + { return maximum; } - set { - if (maximum != value) { + set + { + if (maximum != value) + { // Ensure that value is in the Win32 control's acceptable range // Message: '%1' is not a valid value for '%0'. '%0' must be greater than %2. // Should this set a boundary for the top end too? if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(Maximum), value, 0)); - if (minimum > value) minimum = value; + if (minimum > value) + minimum = value; maximum = value; - if (this.value > maximum) this.value = maximum; + if (this.value > maximum) + this.value = maximum; - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(NativeMethods.PBM_SETRANGE32, minimum, maximum); - UpdatePos() ; + UpdatePos(); } } } @@ -363,26 +418,33 @@ public int Maximum { RefreshProperties(RefreshProperties.Repaint), SRDescription(nameof(SR.ProgressBarMinimumDescr)) ] - public int Minimum { - get { + public int Minimum + { + get + { return minimum; } - set { - if (minimum != value) { + set + { + if (minimum != value) + { // Ensure that value is in the Win32 control's acceptable range // Message: '%1' is not a valid value for '%0'. '%0' must be greater than %2. // Should this set a boundary for the top end too? if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(Minimum), value, 0)); - if (maximum < value) maximum = value; + if (maximum < value) + maximum = value; minimum = value; - if (this.value < minimum) this.value = minimum; + if (this.value < minimum) + this.value = minimum; - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(NativeMethods.PBM_SETRANGE32, minimum, maximum); - UpdatePos() ; + UpdatePos(); } } } @@ -411,17 +473,19 @@ protected override void OnForeColorChanged(EventArgs e) EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Padding Padding { + public new Padding Padding + { get { return base.Padding; } - set { base.Padding = value;} + set { base.Padding = value; } } [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public new event EventHandler PaddingChanged { - add => base.PaddingChanged += value; + public new event EventHandler PaddingChanged + { + add => base.PaddingChanged += value; remove => base.PaddingChanged -= value; } @@ -437,16 +501,21 @@ protected override void OnForeColorChanged(EventArgs e) DefaultValue(false), SRDescription(nameof(SR.ControlRightToLeftLayoutDescr)) ] - public virtual bool RightToLeftLayout { - get { + public virtual bool RightToLeftLayout + { + get + { return rightToLeftLayout; } - set { - if (value != rightToLeftLayout) { + set + { + if (value != rightToLeftLayout) + { rightToLeftLayout = value; - using(new LayoutTransaction(this, this, PropertyNames.RightToLeftLayout)) { + using (new LayoutTransaction(this, this, PropertyNames.RightToLeftLayout)) + { OnRightToLeftLayoutChanged(EventArgs.Empty); } } @@ -455,7 +524,8 @@ public virtual bool RightToLeftLayout { [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnRightToLeftLayoutChangedDescr))] - public event EventHandler RightToLeftLayoutChanged { + public event EventHandler RightToLeftLayoutChanged + { add => onRightToLeftLayoutChanged += value; remove => onRightToLeftLayoutChanged -= value; } @@ -471,30 +541,38 @@ public event EventHandler RightToLeftLayoutChanged { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ProgressBarStepDescr)) ] - public int Step { - get { + public int Step + { + get + { return step; } - set { + set + { step = value; - if (IsHandleCreated) SendMessage(NativeMethods.PBM_SETSTEP, step, 0); + if (IsHandleCreated) + SendMessage(NativeMethods.PBM_SETSTEP, step, 0); } } /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public bool TabStop { - get { + new public bool TabStop + { + get + { return base.TabStop; } - set { + set + { base.TabStop = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TabStopChanged { + new public event EventHandler TabStopChanged + { add => base.TabStopChanged += value; remove => base.TabStopChanged -= value; } @@ -502,17 +580,21 @@ public int Step { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Bindable(false)] - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TextChanged { + new public event EventHandler TextChanged + { add => base.TextChanged += value; remove => base.TextChanged -= value; } @@ -528,63 +610,74 @@ public override string Text { Bindable(true), SRDescription(nameof(SR.ProgressBarValueDescr)) ] - public int Value { - get { + public int Value + { + get + { return value; } - set { - if (this.value != value) { + set + { + if (this.value != value) + { if ((value < minimum) || (value > maximum)) throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidBoundArgument, nameof(Value), value, "'minimum'", "'maximum'")); this.value = value; - UpdatePos() ; + UpdatePos(); } } } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler DoubleClick { + public new event EventHandler DoubleClick + { add => base.DoubleClick += value; remove => base.DoubleClick -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event MouseEventHandler MouseDoubleClick { + public new event MouseEventHandler MouseDoubleClick + { add => base.MouseDoubleClick += value; remove => base.MouseDoubleClick -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event KeyEventHandler KeyUp { + public new event KeyEventHandler KeyUp + { add => base.KeyUp += value; remove => base.KeyUp -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event KeyEventHandler KeyDown { + public new event KeyEventHandler KeyDown + { add => base.KeyDown += value; remove => base.KeyDown -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event KeyPressEventHandler KeyPress { + public new event KeyPressEventHandler KeyPress + { add => base.KeyPress += value; remove => base.KeyPress -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler Enter { + public new event EventHandler Enter + { add => base.Enter += value; remove => base.Enter -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler Leave { + public new event EventHandler Leave + { add => base.Leave += value; remove => base.Leave -= value; } @@ -594,7 +687,8 @@ public int Value { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event PaintEventHandler Paint { + public new event PaintEventHandler Paint + { add => base.Paint += value; remove => base.Paint -= value; } @@ -602,15 +696,19 @@ public int Value { /// /// - protected override void CreateHandle() { - if (!RecreatingHandle) { - IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); - try { + protected override void CreateHandle() + { + if (!RecreatingHandle) + { + IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); + try + { NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); icc.dwICC = NativeMethods.ICC_PROGRESS_CLASS; SafeNativeMethods.InitCommonControlsEx(icc); } - finally { + finally + { UnsafeNativeMethods.ThemingScope.Deactivate(userCookie); } } @@ -623,17 +721,21 @@ protected override void CreateHandle() { /// specified increment and redraws the control to reflect the new position. /// /// - public void Increment(int value) { - if (this.Style == ProgressBarStyle.Marquee) { + public void Increment(int value) + { + if (this.Style == ProgressBarStyle.Marquee) + { throw new InvalidOperationException(SR.ProgressBarIncrementMarqueeException); } this.value += value; // Enforce that value is within the range (minimum, maximum) - if (this.value < minimum) { + if (this.value < minimum) + { this.value = minimum; } - if (this.value > maximum) { + if (this.value > maximum) + { this.value = maximum; } @@ -643,7 +745,8 @@ public void Increment(int value) { /// /// Overridden to set up our properties. /// - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { base.OnHandleCreated(e); SendMessage(NativeMethods.PBM_SETRANGE32, minimum, maximum); SendMessage(NativeMethods.PBM_SETSTEP, step, 0); @@ -664,17 +767,21 @@ protected override void OnHandleDestroyed(EventArgs e) } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnRightToLeftLayoutChanged(EventArgs e) { - if (GetAnyDisposingInHierarchy()) { + protected virtual void OnRightToLeftLayoutChanged(EventArgs e) + { + if (GetAnyDisposingInHierarchy()) + { return; } - if (RightToLeft == RightToLeft.Yes) { + if (RightToLeft == RightToLeft.Yes) + { RecreateHandle(); } - if (onRightToLeftLayoutChanged != null) { - onRightToLeftLayoutChanged(this, e); + if (onRightToLeftLayoutChanged != null) + { + onRightToLeftLayoutChanged(this, e); } } @@ -687,8 +794,10 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) { /// property, and redraws the control to reflect the new position. /// /// - public void PerformStep() { - if (this.Style == ProgressBarStyle.Marquee) { + public void PerformStep() + { + if (this.Style == ProgressBarStyle.Marquee) + { throw new InvalidOperationException(SR.ProgressBarPerformStepMarqueeException); } Increment(step); @@ -698,7 +807,8 @@ public void PerformStep() { /// Resets the fore color to be based on the parent's fore color. /// [EditorBrowsable(EditorBrowsableState.Never)] - public override void ResetForeColor() { + public override void ResetForeColor() + { ForeColor = defaultForeColor; } @@ -707,7 +817,8 @@ public override void ResetForeColor() { /// Returns true if the ForeColor should be persisted in code gen. /// [EditorBrowsable(EditorBrowsableState.Never)] - internal override bool ShouldSerializeForeColor() { + internal override bool ShouldSerializeForeColor() + { return ForeColor != defaultForeColor; } @@ -716,7 +827,8 @@ internal override bool ShouldSerializeForeColor() { /// /// Returns a string representation for this control. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); return s + ", Minimum: " + Minimum.ToString(CultureInfo.CurrentCulture) + ", Maximum: " + Maximum.ToString(CultureInfo.CurrentCulture) + ", Value: " + value; @@ -726,8 +838,10 @@ public override string ToString() { /// Sends the underlying window a PBM_SETPOS message to update /// the current value of the progressbar. /// - private void UpdatePos() { - if (IsHandleCreated) SendMessage(NativeMethods.PBM_SETPOS, value, 0); + private void UpdatePos() + { + if (IsHandleCreated) + SendMessage(NativeMethods.PBM_SETPOS, value, 0); } //Note: ProgressBar doesn't work like other controls as far as setting ForeColor/ @@ -750,14 +864,17 @@ private void UserPreferenceChangedHandler(object o, UserPreferenceChangedEventAr /// /// AccessibleObject for this ProgressBar instance. /// - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new ProgressBarAccessibleObject(this); } [ComVisible(true)] - internal class ProgressBarAccessibleObject : ControlAccessibleObject { + internal class ProgressBarAccessibleObject : ControlAccessibleObject + { - internal ProgressBarAccessibleObject(ProgressBar owner) : base(owner) { + internal ProgressBarAccessibleObject(ProgressBar owner) : base(owner) + { } private ProgressBar OwningProgressBar @@ -770,17 +887,21 @@ private ProgressBar OwningProgressBar internal override bool IsIAccessibleExSupported() => true; - internal override bool IsPatternSupported(int patternId) { + internal override bool IsPatternSupported(int patternId) + { if (patternId == NativeMethods.UIA_ValuePatternId || - patternId == NativeMethods.UIA_RangeValuePatternId) { + patternId == NativeMethods.UIA_RangeValuePatternId) + { return true; } return base.IsPatternSupported(patternId); } - internal override object GetPropertyValue(int propertyID) { - switch (propertyID) { + internal override object GetPropertyValue(int propertyID) + { + switch (propertyID) + { case NativeMethods.UIA_NamePropertyId: return this.Name; case NativeMethods.UIA_ControlTypePropertyId: @@ -801,42 +922,55 @@ internal override object GetPropertyValue(int propertyID) { return base.GetPropertyValue(propertyID); } - internal override void SetValue(double newValue) { + internal override void SetValue(double newValue) + { throw new InvalidOperationException("Progress Bar is read-only."); } - internal override double LargeChange { - get { + internal override double LargeChange + { + get + { return double.NaN; } } - internal override double Maximum { - get { + internal override double Maximum + { + get + { return this.OwningProgressBar?.Maximum ?? double.NaN; } } - internal override double Minimum { - get { + internal override double Minimum + { + get + { return this.OwningProgressBar?.Minimum ?? double.NaN; } } - internal override double SmallChange { - get { + internal override double SmallChange + { + get + { return double.NaN; } } - internal override double RangeValue { - get { + internal override double RangeValue + { + get + { return this.OwningProgressBar?.Value ?? double.NaN; } } - internal override bool IsReadOnly { - get { + internal override bool IsReadOnly + { + get + { return true; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBarRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBarRenderer.cs index 8aa4f7eee6f..d9a2e46f423 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBarRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBarRenderer.cs @@ -2,130 +2,146 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ -using System; -using System.Drawing; -using System.Diagnostics.CodeAnalysis; -using System.Windows.Forms.VisualStyles; -using Microsoft.Win32; + using System; + using System.Drawing; + using System.Diagnostics.CodeAnalysis; + using System.Windows.Forms.VisualStyles; + using Microsoft.Win32; /// /// /// This is a rendering class for the ProgressBar control. /// /// - public sealed class ProgressBarRenderer { + public sealed class ProgressBarRenderer + { + + //Make this per-thread, so that different threads can safely use these methods. + [ThreadStatic] + private static VisualStyleRenderer visualStyleRenderer = null; - //Make this per-thread, so that different threads can safely use these methods. - [ThreadStatic] - private static VisualStyleRenderer visualStyleRenderer = null; - //cannot instantiate - private ProgressBarRenderer() { - } - - /// - /// - /// Returns true if this class is supported for the current OS and user/application settings, - /// otherwise returns false. - /// - /// - public static bool IsSupported { - get { - return VisualStyleRenderer.IsSupported; // no downlevel support - } - } - - /// - /// - /// Renders a horizontal bar. - /// - /// - [ - SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally - ] - public static void DrawHorizontalBar(Graphics g, Rectangle bounds) { - InitializeRenderer(VisualStyleElement.ProgressBar.Bar.Normal); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Renders a vertical bar. - /// - /// - [ - SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally - ] - public static void DrawVerticalBar(Graphics g, Rectangle bounds) { - InitializeRenderer(VisualStyleElement.ProgressBar.BarVertical.Normal); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Renders a number of constant size horizontal chunks in the given bounds. - /// - /// - [ - SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally - ] - public static void DrawHorizontalChunks(Graphics g, Rectangle bounds) { - InitializeRenderer(VisualStyleElement.ProgressBar.Chunk.Normal); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Renders a number of constant size vertical chunks in the given bounds. - /// - /// - [ - SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally - ] - public static void DrawVerticalChunks(Graphics g, Rectangle bounds) { - InitializeRenderer(VisualStyleElement.ProgressBar.ChunkVertical.Normal); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Returns the width/height of a single horizontal/vertical progress bar chunk. - /// - /// - public static int ChunkThickness { - get { - InitializeRenderer(VisualStyleElement.ProgressBar.Chunk.Normal); - - return (visualStyleRenderer.GetInteger(IntegerProperty.ProgressChunkSize)); - } - } - - /// - /// - /// Returns the width/height of the space between horizontal/vertical progress bar chunks. - /// - /// - public static int ChunkSpaceThickness { - get { - InitializeRenderer(VisualStyleElement.ProgressBar.Chunk.Normal); - - return (visualStyleRenderer.GetInteger(IntegerProperty.ProgressSpaceSize)); - } - } - - private static void InitializeRenderer(VisualStyleElement element) { - if (visualStyleRenderer == null) { - visualStyleRenderer = new VisualStyleRenderer(element); - } - else { - visualStyleRenderer.SetParameters(element); - } - } + private ProgressBarRenderer() + { + } + + /// + /// + /// Returns true if this class is supported for the current OS and user/application settings, + /// otherwise returns false. + /// + /// + public static bool IsSupported + { + get + { + return VisualStyleRenderer.IsSupported; // no downlevel support + } + } + + /// + /// + /// Renders a horizontal bar. + /// + /// + [ + SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally + ] + public static void DrawHorizontalBar(Graphics g, Rectangle bounds) + { + InitializeRenderer(VisualStyleElement.ProgressBar.Bar.Normal); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Renders a vertical bar. + /// + /// + [ + SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally + ] + public static void DrawVerticalBar(Graphics g, Rectangle bounds) + { + InitializeRenderer(VisualStyleElement.ProgressBar.BarVertical.Normal); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Renders a number of constant size horizontal chunks in the given bounds. + /// + /// + [ + SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally + ] + public static void DrawHorizontalChunks(Graphics g, Rectangle bounds) + { + InitializeRenderer(VisualStyleElement.ProgressBar.Chunk.Normal); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Renders a number of constant size vertical chunks in the given bounds. + /// + /// + [ + SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally + ] + public static void DrawVerticalChunks(Graphics g, Rectangle bounds) + { + InitializeRenderer(VisualStyleElement.ProgressBar.ChunkVertical.Normal); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Returns the width/height of a single horizontal/vertical progress bar chunk. + /// + /// + public static int ChunkThickness + { + get + { + InitializeRenderer(VisualStyleElement.ProgressBar.Chunk.Normal); + + return (visualStyleRenderer.GetInteger(IntegerProperty.ProgressChunkSize)); + } + } + + /// + /// + /// Returns the width/height of the space between horizontal/vertical progress bar chunks. + /// + /// + public static int ChunkSpaceThickness + { + get + { + InitializeRenderer(VisualStyleElement.ProgressBar.Chunk.Normal); + + return (visualStyleRenderer.GetInteger(IntegerProperty.ProgressSpaceSize)); + } + } + + private static void InitializeRenderer(VisualStyleElement element) + { + if (visualStyleRenderer == null) + { + visualStyleRenderer = new VisualStyleRenderer(element); + } + else + { + visualStyleRenderer.SetParameters(element); + } + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs index c4060ae1bd0..6c2f6c2eeba 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Collections; @@ -26,146 +27,152 @@ namespace System.Windows.Forms { [ClassInterface(ClassInterfaceType.AutoDispatch)] [Designer("System.Windows.Forms.Design.PropertyGridDesigner, " + AssemblyRef.SystemDesign)] [SRDescription(nameof(SR.DescriptionPropertyGrid))] - public class PropertyGrid : ContainerControl, IComPropertyBrowser, UnsafeNativeMethods.IPropertyNotifySink { + public class PropertyGrid : ContainerControl, IComPropertyBrowser, UnsafeNativeMethods.IPropertyNotifySink + { - private DocComment doccomment; - private int dcSizeRatio = -1; - private int hcSizeRatio = -1; - private HotCommands hotcommands; - private ToolStrip toolStrip; - - private bool helpVisible = true; - private bool toolbarVisible = true; + private DocComment doccomment; + private int dcSizeRatio = -1; + private int hcSizeRatio = -1; + private HotCommands hotcommands; + private ToolStrip toolStrip; + + private bool helpVisible = true; + private bool toolbarVisible = true; - private ImageList[] imageList = new ImageList[2]; - private Bitmap bmpAlpha; - private Bitmap bmpCategory; - private Bitmap bmpPropPage; + private ImageList[] imageList = new ImageList[2]; + private Bitmap bmpAlpha; + private Bitmap bmpCategory; + private Bitmap bmpPropPage; // our array of viewTabs - private bool viewTabsDirty = true; - private bool drawFlatToolBar = false; - private PropertyTab[] viewTabs = new PropertyTab[0]; - private PropertyTabScope[] viewTabScopes = new PropertyTabScope[0]; - private Hashtable viewTabProps; + private bool viewTabsDirty = true; + private bool drawFlatToolBar = false; + private PropertyTab[] viewTabs = new PropertyTab[0]; + private PropertyTabScope[] viewTabScopes = new PropertyTabScope[0]; + private Hashtable viewTabProps; // the tab view buttons - private ToolStripButton[] viewTabButtons; + private ToolStripButton[] viewTabButtons; // the index of the currently selected tab view - private int selectedViewTab; - - + private int selectedViewTab; + + // our view type buttons (Alpha vs. categorized) - private ToolStripButton[] viewSortButtons; - private int selectedViewSort; - private PropertySort propertySortValue; + private ToolStripButton[] viewSortButtons; + private int selectedViewSort; + private PropertySort propertySortValue; // this guy's kind of an odd one...he gets special treatment - private ToolStripButton btnViewPropertyPages; - private ToolStripSeparator separator1; - private ToolStripSeparator separator2; - private int buttonType = NORMAL_BUTTONS; + private ToolStripButton btnViewPropertyPages; + private ToolStripSeparator separator1; + private ToolStripSeparator separator2; + private int buttonType = NORMAL_BUTTONS; // our main baby - private PropertyGridView gridView; + private PropertyGridView gridView; - - private IDesignerHost designerHost; - private IDesignerEventService designerEventService; - - private Hashtable designerSelections; + + private IDesignerHost designerHost; + private IDesignerEventService designerEventService; + + private Hashtable designerSelections; private GridEntry peDefault; private GridEntry peMain; private GridEntryCollection currentPropEntries; - private object[] currentObjects; - - private int paintFrozen; - private Color lineColor = SystemInformation.HighContrast ? SystemColors.ControlDarkDark : SystemColors.InactiveBorder; - internal bool developerOverride = false; - internal Brush lineBrush = null; - private Color categoryForeColor = SystemColors.ControlText; - private Color categorySplitterColor = SystemColors.Control; - private Color viewBorderColor = SystemColors.ControlDark; - private Color selectedItemWithFocusForeColor = SystemColors.HighlightText; - private Color selectedItemWithFocusBackColor = SystemColors.Highlight; - internal Brush selectedItemWithFocusBackBrush = null; - private bool canShowVisualStyleGlyphs = true; + private object[] currentObjects; + + private int paintFrozen; + private Color lineColor = SystemInformation.HighContrast ? SystemColors.ControlDarkDark : SystemColors.InactiveBorder; + internal bool developerOverride = false; + internal Brush lineBrush = null; + private Color categoryForeColor = SystemColors.ControlText; + private Color categorySplitterColor = SystemColors.Control; + private Color viewBorderColor = SystemColors.ControlDark; + private Color selectedItemWithFocusForeColor = SystemColors.HighlightText; + private Color selectedItemWithFocusBackColor = SystemColors.Highlight; + internal Brush selectedItemWithFocusBackBrush = null; + private bool canShowVisualStyleGlyphs = true; private AttributeCollection browsableAttributes; - private SnappableControl targetMove = null; - private int dividerMoveY = -1; - private const int CYDIVIDER = 3; - private static int cyDivider = CYDIVIDER; - private const int CXINDENT = 0; - private const int CYINDENT = 2; - private const int MIN_GRID_HEIGHT = 20; - - private const int PROPERTIES = 0; - private const int EVENTS = 1; - private const int ALPHA = 1; - private const int CATEGORIES = 0; - private const int NO_SORT = 2; - - private const int NORMAL_BUTTONS = 0; - private const int LARGE_BUTTONS = 1; - - private const int TOOLSTRIP_BUTTON_PADDING_Y = 9; - private int toolStripButtonPaddingY = TOOLSTRIP_BUTTON_PADDING_Y; - private static readonly Size DEFAULT_LARGE_BUTTON_SIZE = new Size(32, 32); - private static readonly Size DEFAULT_NORMAL_BUTTON_SIZE = new Size(16, 16); - private static Size largeButtonSize = DEFAULT_LARGE_BUTTON_SIZE; - private static Size normalButtonSize = DEFAULT_NORMAL_BUTTON_SIZE; - private static bool isScalingInitialized = false; - - private const ushort PropertiesChanged = 0x0001; - private const ushort GotDesignerEventService = 0x0002; - private const ushort InternalChange = 0x0004; - private const ushort TabsChanging = 0x0008; - private const ushort BatchMode = 0x0010; - private const ushort ReInitTab = 0x0020; - private const ushort SysColorChangeRefresh = 0x0040; - private const ushort FullRefreshAfterBatch = 0x0080; - private const ushort BatchModeChange = 0x0100; - private const ushort RefreshingProperties = 0x0200; - - private ushort flags; - - private bool GetFlag(ushort flag) { + private SnappableControl targetMove = null; + private int dividerMoveY = -1; + private const int CYDIVIDER = 3; + private static int cyDivider = CYDIVIDER; + private const int CXINDENT = 0; + private const int CYINDENT = 2; + private const int MIN_GRID_HEIGHT = 20; + + private const int PROPERTIES = 0; + private const int EVENTS = 1; + private const int ALPHA = 1; + private const int CATEGORIES = 0; + private const int NO_SORT = 2; + + private const int NORMAL_BUTTONS = 0; + private const int LARGE_BUTTONS = 1; + + private const int TOOLSTRIP_BUTTON_PADDING_Y = 9; + private int toolStripButtonPaddingY = TOOLSTRIP_BUTTON_PADDING_Y; + private static readonly Size DEFAULT_LARGE_BUTTON_SIZE = new Size(32, 32); + private static readonly Size DEFAULT_NORMAL_BUTTON_SIZE = new Size(16, 16); + private static Size largeButtonSize = DEFAULT_LARGE_BUTTON_SIZE; + private static Size normalButtonSize = DEFAULT_NORMAL_BUTTON_SIZE; + private static bool isScalingInitialized = false; + + private const ushort PropertiesChanged = 0x0001; + private const ushort GotDesignerEventService = 0x0002; + private const ushort InternalChange = 0x0004; + private const ushort TabsChanging = 0x0008; + private const ushort BatchMode = 0x0010; + private const ushort ReInitTab = 0x0020; + private const ushort SysColorChangeRefresh = 0x0040; + private const ushort FullRefreshAfterBatch = 0x0080; + private const ushort BatchModeChange = 0x0100; + private const ushort RefreshingProperties = 0x0200; + + private ushort flags; + + private bool GetFlag(ushort flag) + { return (flags & flag) != (ushort)0; } - private void SetFlag(ushort flag, bool value) { - if (value) { + private void SetFlag(ushort flag, bool value) + { + if (value) + { flags |= flag; } - else { + else + { flags &= (ushort)~flag; } } - private readonly ComponentEventHandler onComponentAdd; - private readonly ComponentEventHandler onComponentRemove; - private readonly ComponentChangedEventHandler onComponentChanged; - + private readonly ComponentEventHandler onComponentAdd; + private readonly ComponentEventHandler onComponentRemove; + private readonly ComponentChangedEventHandler onComponentChanged; + // the cookies for our connection points on objects that support IPropertyNotifySink // private AxHost.ConnectionPointCookie[] connectionPointCookies = null; - private static object EventPropertyValueChanged = new object(); - private static object EventComComponentNameChanged = new object(); - private static object EventPropertyTabChanged = new object(); - private static object EventSelectedGridItemChanged = new object(); - private static object EventPropertySortChanged = new object(); - private static object EventSelectedObjectsChanged = new object(); - + private static object EventPropertyValueChanged = new object(); + private static object EventComComponentNameChanged = new object(); + private static object EventPropertyTabChanged = new object(); + private static object EventSelectedGridItemChanged = new object(); + private static object EventPropertySortChanged = new object(); + private static object EventSelectedObjectsChanged = new object(); + [ SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // the "PropertyGridToolBar" caption is for testing. // So we don't have to localize it. ] - public PropertyGrid() { + public PropertyGrid() + { onComponentAdd = new ComponentEventHandler(OnComponentAdd); onComponentRemove = new ComponentEventHandler(OnComponentRemove); @@ -176,12 +183,16 @@ public PropertyGrid() { // static variables are problem in a child level mixed mode scenario. Changing static variables cause compatibility issue. // So, recalculate static variables everytime property grid initialized. - if (DpiHelper.IsPerMonitorV2Awareness) { + if (DpiHelper.IsPerMonitorV2Awareness) + { RescaleConstants(); } - else { - if (!isScalingInitialized) { - if (DpiHelper.IsScalingRequired) { + else + { + if (!isScalingInitialized) + { + if (DpiHelper.IsScalingRequired) + { normalButtonSize = LogicalToDeviceUnits(DEFAULT_NORMAL_BUTTON_SIZE); largeButtonSize = LogicalToDeviceUnits(DEFAULT_LARGE_BUTTON_SIZE); } @@ -251,7 +262,7 @@ public PropertyGrid() { hotcommands.Visible = false; hotcommands.MouseMove += new MouseEventHandler(this.OnChildMouseMove); hotcommands.MouseDown += new MouseEventHandler(this.OnChildMouseDown); - + Controls.AddRange(new Control[] { doccomment, hotcommands, gridView, toolStrip }); SetActiveControl(gridView); @@ -265,40 +276,51 @@ public PropertyGrid() { { Debug.WriteLine(ex.ToString()); } - finally { - if (doccomment != null) { + finally + { + if (doccomment != null) + { doccomment.ResumeLayout(false); } - if (hotcommands != null) { + if (hotcommands != null) + { hotcommands.ResumeLayout(false); } ResumeLayout(true); } } - internal IDesignerHost ActiveDesigner { - get{ - if (this.designerHost == null) { + internal IDesignerHost ActiveDesigner + { + get + { + if (this.designerHost == null) + { designerHost = (IDesignerHost)GetService(typeof(IDesignerHost)); } return this.designerHost; } - set{ - if (value != designerHost) { + set + { + if (value != designerHost) + { SetFlag(ReInitTab, true); - if (this.designerHost != null) { + if (this.designerHost != null) + { IComponentChangeService cs = (IComponentChangeService)designerHost.GetService(typeof(IComponentChangeService)); - if (cs != null) { + if (cs != null) + { cs.ComponentAdded -= onComponentAdd; cs.ComponentRemoved -= onComponentRemove; cs.ComponentChanged -= onComponentChanged; } - + IPropertyValueUIService pvSvc = (IPropertyValueUIService)designerHost.GetService(typeof(IPropertyValueUIService)); - if (pvSvc != null) { + if (pvSvc != null) + { pvSvc.PropertyUIValueItemsChanged -= new EventHandler(this.OnNotifyPropertyValueUIItemsChanged); } - + designerHost.TransactionOpened -= new EventHandler(this.OnTransactionOpened); designerHost.TransactionClosed -= new DesignerTransactionCloseEventHandler(this.OnTransactionClosed); SetFlag(BatchMode, false); @@ -306,11 +328,13 @@ internal IDesignerHost ActiveDesigner { this.designerHost = null; } - - if (value != null) { + + if (value != null) + { IComponentChangeService cs = (IComponentChangeService)value.GetService(typeof(IComponentChangeService)); - if (cs != null) { + if (cs != null) + { cs.ComponentAdded += onComponentAdd; cs.ComponentRemoved += onComponentRemove; cs.ComponentChanged += onComponentChanged; @@ -319,15 +343,17 @@ internal IDesignerHost ActiveDesigner { value.TransactionOpened += new EventHandler(this.OnTransactionOpened); value.TransactionClosed += new DesignerTransactionCloseEventHandler(this.OnTransactionClosed); SetFlag(BatchMode, false); - + IPropertyValueUIService pvSvc = (IPropertyValueUIService)value.GetService(typeof(IPropertyValueUIService)); - if (pvSvc != null) { + if (pvSvc != null) + { pvSvc.PropertyUIValueItemsChanged += new EventHandler(this.OnNotifyPropertyValueUIItemsChanged); } } - + designerHost = value; - if (peMain != null) { + if (peMain != null) + { peMain.DesignerHost = value; } RefreshTabs(PropertyTabScope.Document); @@ -336,20 +362,26 @@ internal IDesignerHost ActiveDesigner { } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override bool AutoScroll { - get { + public override bool AutoScroll + { + get + { return base.AutoScroll; } - set { + set + { base.AutoScroll = value; } } - public override Color BackColor { - get { + public override Color BackColor + { + get + { return base.BackColor; } - set { + set + { base.BackColor = value; toolStrip.BackColor = value; toolStrip.Invalidate(true); @@ -357,86 +389,110 @@ public override Color BackColor { } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged { + new public event EventHandler BackgroundImageChanged + { add => base.BackgroundImageChanged += value; remove => base.BackgroundImageChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { + new public event EventHandler BackgroundImageLayoutChanged + { add => base.BackgroundImageLayoutChanged += value; remove => base.BackgroundImageLayoutChanged -= value; } [ - Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), + Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public AttributeCollection BrowsableAttributes { - set { - if (value == null || value == AttributeCollection.Empty) { - browsableAttributes = new AttributeCollection(new Attribute[]{BrowsableAttribute.Yes}); + ] + public AttributeCollection BrowsableAttributes + { + set + { + if (value == null || value == AttributeCollection.Empty) + { + browsableAttributes = new AttributeCollection(new Attribute[] { BrowsableAttribute.Yes }); } - else { + else + { Attribute[] attributes = new Attribute[value.Count]; value.CopyTo(attributes, 0); browsableAttributes = new AttributeCollection(attributes); } - if (currentObjects != null && currentObjects.Length > 0) { - if (peMain != null) { + if (currentObjects != null && currentObjects.Length > 0) + { + if (peMain != null) + { peMain.BrowsableAttributes = BrowsableAttributes; Refresh(true); } } } - get { - if (browsableAttributes == null) { - browsableAttributes = new AttributeCollection(new Attribute[]{new BrowsableAttribute(true)}); + get + { + if (browsableAttributes == null) + { + browsableAttributes = new AttributeCollection(new Attribute[] { new BrowsableAttribute(true) }); } return browsableAttributes; } } - - private bool CanCopy { - get { + + private bool CanCopy + { + get + { return gridView.CanCopy; } } - - private bool CanCut { - get { + + private bool CanCut + { + get + { return gridView.CanCut; } } - - private bool CanPaste { - get { + + private bool CanPaste + { + get + { return gridView.CanPaste; } } - - private bool CanUndo { - get { + + private bool CanUndo + { + get + { return gridView.CanUndo; } } @@ -448,8 +504,10 @@ private bool CanUndo { /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), SRDescription(nameof(SR.PropertyGridCanShowCommandsDesc))] - public virtual bool CanShowCommands { - get { + public virtual bool CanShowCommands + { + get + { return hotcommands.WouldBeVisible; } } @@ -462,12 +520,16 @@ public virtual bool CanShowCommands { SRDescription(nameof(SR.PropertyGridCategoryForeColorDesc)), DefaultValue(typeof(Color), "ControlText") ] - public Color CategoryForeColor { - get { + public Color CategoryForeColor + { + get + { return categoryForeColor; } - set { - if (categoryForeColor != value) { + set + { + if (categoryForeColor != value) + { categoryForeColor = value; gridView.Invalidate(); } @@ -481,11 +543,14 @@ public Color CategoryForeColor { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.PropertyGridCommandsBackColorDesc)) ] - public Color CommandsBackColor { - get { + public Color CommandsBackColor + { + get + { return hotcommands.BackColor; } - set { + set + { hotcommands.BackColor = value; hotcommands.Label.BackColor = value; } @@ -498,11 +563,14 @@ public Color CommandsBackColor { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.PropertyGridCommandsForeColorDesc)) ] - public Color CommandsForeColor { - get { + public Color CommandsForeColor + { + get + { return hotcommands.ForeColor; } - set { + set + { hotcommands.ForeColor = value; hotcommands.Label.ForeColor = value; } @@ -515,11 +583,14 @@ public Color CommandsForeColor { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.PropertyGridCommandsLinkColorDesc)) ] - public Color CommandsLinkColor { - get { + public Color CommandsLinkColor + { + get + { return hotcommands.Label.LinkColor; } - set { + set + { hotcommands.Label.LinkColor = value; } } @@ -531,11 +602,14 @@ public Color CommandsLinkColor { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.PropertyGridCommandsActiveLinkColorDesc)) ] - public Color CommandsActiveLinkColor { - get { + public Color CommandsActiveLinkColor + { + get + { return hotcommands.Label.ActiveLinkColor; } - set { + set + { hotcommands.Label.ActiveLinkColor = value; } } @@ -547,11 +621,14 @@ public Color CommandsActiveLinkColor { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.PropertyGridCommandsDisabledLinkColorDesc)) ] - public Color CommandsDisabledLinkColor { - get { + public Color CommandsDisabledLinkColor + { + get + { return hotcommands.Label.DisabledLinkColor; } - set { + set + { hotcommands.Label.DisabledLinkColor = value; } } @@ -564,11 +641,14 @@ public Color CommandsDisabledLinkColor { SRDescription(nameof(SR.PropertyGridCommandsBorderColorDesc)), DefaultValue(typeof(Color), "ControlDark") ] - public Color CommandsBorderColor { - get { + public Color CommandsBorderColor + { + get + { return hotcommands.BorderColor; } - set { + set + { hotcommands.BorderColor = value; } } @@ -577,8 +657,10 @@ public Color CommandsBorderColor { /// Returns true if the commands pane is currently shown. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public virtual bool CommandsVisible { - get { + public virtual bool CommandsVisible + { + get + { return hotcommands.Visible; } } @@ -592,15 +674,19 @@ public virtual bool CommandsVisible { DefaultValue(true), SRDescription(nameof(SR.PropertyGridCommandsVisibleIfAvailable)) ] - public virtual bool CommandsVisibleIfAvailable { - get { + public virtual bool CommandsVisibleIfAvailable + { + get + { return hotcommands.AllowVisible; } - set { + set + { bool hotcommandsVisible = hotcommands.Visible; hotcommands.AllowVisible = value; //PerformLayout(); - if (hotcommandsVisible != hotcommands.Visible) { + if (hotcommandsVisible != hotcommands.Visible) + { OnLayoutInternal(false); hotcommands.Invalidate(); } @@ -617,28 +703,34 @@ public virtual bool CommandsVisibleIfAvailable { Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public Point ContextMenuDefaultLocation { - get { + public Point ContextMenuDefaultLocation + { + get + { return GetPropertyGridView().ContextMenuDefaultLocation; } } - - /// + + /// /// Collection of child controls. /// [ - Browsable(false), EditorBrowsable(EditorBrowsableState.Never), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new ControlCollection Controls { - get { + public new ControlCollection Controls + { + get + { return base.Controls; } } - - protected override Size DefaultSize { - get { + + protected override Size DefaultSize + { + get + { return new Size(130, 130); } } @@ -647,18 +739,24 @@ protected override Size DefaultSize { Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - protected virtual Type DefaultTabType { - get { - return typeof(PropertiesTab); + protected virtual Type DefaultTabType + { + get + { + return typeof(PropertiesTab); } } - - protected bool DrawFlatToolbar { - get { + + protected bool DrawFlatToolbar + { + get + { return drawFlatToolBar; } - set { - if (drawFlatToolBar != value) { + set + { + if (drawFlatToolBar != value) + { drawFlatToolBar = value; SetToolStripRenderer(); } @@ -668,55 +766,69 @@ protected bool DrawFlatToolbar { } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Color ForeColor { - get { + public override Color ForeColor + { + get + { return base.ForeColor; } - set { + set + { base.ForeColor = value; } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler ForeColorChanged { + new public event EventHandler ForeColorChanged + { add => base.ForeColorChanged += value; remove => base.ForeColorChanged -= value; } - private bool FreezePainting { - get { - return paintFrozen > 0; - } - set { - - if (value && IsHandleCreated && this.Visible) { - if (0 == paintFrozen++) { - SendMessage(Interop.WindowMessages.WM_SETREDRAW, 0, 0); - } - } - if (!value) { - if (paintFrozen == 0) { - return; - } - - if (0 == --paintFrozen) { - SendMessage(Interop.WindowMessages.WM_SETREDRAW, 1, 0); - Invalidate(true); - } - - } + private bool FreezePainting + { + get + { + return paintFrozen > 0; + } + set + { + + if (value && IsHandleCreated && this.Visible) + { + if (0 == paintFrozen++) + { + SendMessage(Interop.WindowMessages.WM_SETREDRAW, 0, 0); + } + } + if (!value) + { + if (paintFrozen == 0) + { + return; + } + + if (0 == --paintFrozen) + { + SendMessage(Interop.WindowMessages.WM_SETREDRAW, 1, 0); + Invalidate(true); + } + + } } } /// /// Gets the help control accessibility object. /// - internal AccessibleObject HelpAccessibleObject { - get { + internal AccessibleObject HelpAccessibleObject + { + get + { return doccomment.AccessibilityObject; } } - + /// /// The background color for the help region. /// @@ -725,11 +837,14 @@ internal AccessibleObject HelpAccessibleObject { SRDescription(nameof(SR.PropertyGridHelpBackColorDesc)), DefaultValue(typeof(Color), "Control") ] - public Color HelpBackColor { - get { + public Color HelpBackColor + { + get + { return doccomment.BackColor; } - set { + set + { doccomment.BackColor = value; } } @@ -742,11 +857,14 @@ public Color HelpBackColor { SRDescription(nameof(SR.PropertyGridHelpForeColorDesc)), DefaultValue(typeof(Color), "ControlText") ] - public Color HelpForeColor { - get { + public Color HelpForeColor + { + get + { return doccomment.ForeColor; } - set { + set + { doccomment.ForeColor = value; } } @@ -759,11 +877,14 @@ public Color HelpForeColor { SRDescription(nameof(SR.PropertyGridHelpBorderColorDesc)), DefaultValue(typeof(Color), "ControlDark") ] - public Color HelpBorderColor { - get { + public Color HelpBorderColor + { + get + { return doccomment.BorderColor; } - set { + set + { doccomment.BorderColor = value; } } @@ -777,11 +898,14 @@ public Color HelpBorderColor { Localizable(true), SRDescription(nameof(SR.PropertyGridHelpVisibleDesc)) ] - public virtual bool HelpVisible { - get { + public virtual bool HelpVisible + { + get + { return this.helpVisible; } - set { + set + { this.helpVisible = value; doccomment.Visible = value; @@ -794,8 +918,10 @@ public virtual bool HelpVisible { /// /// Gets the hot commands control accessible object. /// - internal AccessibleObject HotCommandsAccessibleObject { - get { + internal AccessibleObject HotCommandsAccessibleObject + { + get + { return hotcommands.AccessibilityObject; } } @@ -803,8 +929,10 @@ internal AccessibleObject HotCommandsAccessibleObject { /// /// Gets the main entry accessible object. /// - internal AccessibleObject GridViewAccessibleObject { - get { + internal AccessibleObject GridViewAccessibleObject + { + get + { return gridView.AccessibilityObject; } } @@ -812,8 +940,10 @@ internal AccessibleObject GridViewAccessibleObject { /// /// Gets the value indicating whether the main entry is visible. /// - internal bool GridViewVisible { - get { + internal bool GridViewVisible + { + get + { return gridView != null && gridView.Visible; } } @@ -826,11 +956,14 @@ internal bool GridViewVisible { SRDescription(nameof(SR.PropertyGridSelectedItemWithFocusBackColorDesc)), DefaultValue(typeof(Color), "Highlight") ] - public Color SelectedItemWithFocusBackColor { - get { + public Color SelectedItemWithFocusBackColor + { + get + { return selectedItemWithFocusBackColor; } - set { + set + { if (selectedItemWithFocusBackColor != value) { selectedItemWithFocusBackColor = value; @@ -847,11 +980,14 @@ public Color SelectedItemWithFocusBackColor { SRDescription(nameof(SR.PropertyGridSelectedItemWithFocusForeColorDesc)), DefaultValue(typeof(Color), "HighlightText") ] - public Color SelectedItemWithFocusForeColor { - get { + public Color SelectedItemWithFocusForeColor + { + get + { return selectedItemWithFocusForeColor; } - set { + set + { if (selectedItemWithFocusForeColor != value) { selectedItemWithFocusForeColor = value; @@ -868,11 +1004,14 @@ public Color SelectedItemWithFocusForeColor { SRDescription(nameof(SR.PropertyGridDisabledItemForeColorDesc)), DefaultValue(typeof(Color), "GrayText") ] - public Color DisabledItemForeColor { - get { + public Color DisabledItemForeColor + { + get + { return gridView.GrayTextColor; } - set { + set + { gridView.GrayTextColor = value; gridView.Invalidate(); } @@ -886,12 +1025,16 @@ public Color DisabledItemForeColor { SRDescription(nameof(SR.PropertyGridCategorySplitterColorDesc)), DefaultValue(typeof(Color), "Control") ] - public Color CategorySplitterColor { - get { + public Color CategorySplitterColor + { + get + { return categorySplitterColor; } - set { - if (categorySplitterColor != value) { + set + { + if (categorySplitterColor != value) + { categorySplitterColor = value; gridView.Invalidate(); } @@ -906,38 +1049,49 @@ public Color CategorySplitterColor { SRDescription(nameof(SR.PropertyGridCanShowVisualStyleGlyphsDesc)), DefaultValue(true) ] - public bool CanShowVisualStyleGlyphs { - get { + public bool CanShowVisualStyleGlyphs + { + get + { return canShowVisualStyleGlyphs; } - set { - if (canShowVisualStyleGlyphs != value) { + set + { + if (canShowVisualStyleGlyphs != value) + { canShowVisualStyleGlyphs = value; gridView.Invalidate(); } } } - bool IComPropertyBrowser.InPropertySet { - get { + bool IComPropertyBrowser.InPropertySet + { + get + { return GetPropertyGridView().GetInPropertySet(); } } - + [ SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.PropertyGridLineColorDesc)), DefaultValue(typeof(Color), "InactiveBorder") ] - public Color LineColor { - get { + public Color LineColor + { + get + { return lineColor; } - set { - if (lineColor != value) { + set + { + if (lineColor != value) + { lineColor = value; developerOverride = true; - if (lineBrush != null) { + if (lineBrush != null) + { lineBrush.Dispose(); lineBrush = null; } @@ -951,18 +1105,21 @@ public Color LineColor { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Padding Padding { + public new Padding Padding + { get { return base.Padding; } - set { base.Padding = value;} + set { base.Padding = value; } } [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public new event EventHandler PaddingChanged { - add => base.PaddingChanged += value; - remove => base.PaddingChanged -= value; } + public new event EventHandler PaddingChanged + { + add => base.PaddingChanged += value; + remove => base.PaddingChanged -= value; + } /// /// Sets or gets the current property sort type, which can be @@ -973,55 +1130,67 @@ public Color LineColor { DefaultValue(PropertySort.CategorizedAlphabetical), SRDescription(nameof(SR.PropertyGridPropertySortDesc)) ] - public PropertySort PropertySort { - get { - return propertySortValue; + public PropertySort PropertySort + { + get + { + return propertySortValue; } - set { + set + { //valid values are 0x0 to 0x3 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)PropertySort.NoSort, (int)PropertySort.CategorizedAlphabetical)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)PropertySort.NoSort, (int)PropertySort.CategorizedAlphabetical)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(PropertySort)); } ToolStripButton newButton; - - if ((value & PropertySort.Categorized) != 0) { + + if ((value & PropertySort.Categorized) != 0) + { newButton = viewSortButtons[CATEGORIES]; } - else if ((value & PropertySort.Alphabetical) != 0) { + else if ((value & PropertySort.Alphabetical) != 0) + { newButton = viewSortButtons[ALPHA]; } - else { + else + { newButton = viewSortButtons[NO_SORT]; } - + GridItem selectedGridItem = SelectedGridItem; - - + + OnViewSortButtonClick(newButton, EventArgs.Empty); - + this.propertySortValue = value; - - if (selectedGridItem != null) { - try { + + if (selectedGridItem != null) + { + try + { SelectedGridItem = selectedGridItem; } - catch (System.ArgumentException) { + catch (System.ArgumentException) + { // When no row is selected, SelectedGridItem returns grid entry for root // object. But this is not a selectable item. So don't worry if setting SelectedGridItem // cause an argument exception whe ntrying to re-select the root object. Just leave the // the grid with no selected row. } } - + } } - + [ Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public PropertyTabCollection PropertyTabs { - get { + public PropertyTabCollection PropertyTabs + { + get + { return new PropertyTabCollection(this); } } @@ -1037,139 +1206,169 @@ public PropertyTabCollection PropertyTabs { SRCategory(nameof(SR.CatBehavior)), TypeConverter(typeof(SelectedObjectConverter)) ] - public object SelectedObject { - get { - if (currentObjects == null || currentObjects.Length == 0) { + public object SelectedObject + { + get + { + if (currentObjects == null || currentObjects.Length == 0) + { return null; } return currentObjects[0]; } - set { - if (value == null) { + set + { + if (value == null) + { SelectedObjects = new object[0]; } - else { - SelectedObjects = new object[]{value}; + else + { + SelectedObjects = new object[] { value }; } } } - + [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public object[] SelectedObjects { - set { - try { + public object[] SelectedObjects + { + set + { + try + { this.FreezePainting = true; SetFlag(FullRefreshAfterBatch, false); - if (GetFlag(BatchMode)) { - SetFlag(BatchModeChange, false); + if (GetFlag(BatchMode)) + { + SetFlag(BatchModeChange, false); } - + gridView.EnsurePendingChangesCommitted(); - + bool isSame = false; bool classesSame = false; bool showEvents = true; - + // validate the array coming in - if (value != null && value.Length > 0) { - for (int count = 0; count < value.Length; count++) { - if (value[count] == null) { - throw new ArgumentException(string.Format(SR.PropertyGridSetNull, count.ToString(CultureInfo.CurrentCulture), value.Length.ToString(CultureInfo.CurrentCulture))); - } - else if (value[count] is IUnimplemented) { - throw new NotSupportedException(string.Format(SR.PropertyGridRemotedObject, value[count].GetType().FullName)); - } - } + if (value != null && value.Length > 0) + { + for (int count = 0; count < value.Length; count++) + { + if (value[count] == null) + { + throw new ArgumentException(string.Format(SR.PropertyGridSetNull, count.ToString(CultureInfo.CurrentCulture), value.Length.ToString(CultureInfo.CurrentCulture))); + } + else if (value[count] is IUnimplemented) + { + throw new NotSupportedException(string.Format(SR.PropertyGridRemotedObject, value[count].GetType().FullName)); + } + } } - else { + else + { showEvents = false; } - + // make sure we actually changed something before we inspect tabs if (currentObjects != null && value != null && - currentObjects.Length == value.Length) { + currentObjects.Length == value.Length) + { isSame = true; classesSame = true; - for (int i = 0; i < value.Length && (isSame || classesSame); i++) { - if (isSame && currentObjects[i] != value[i]) { + for (int i = 0; i < value.Length && (isSame || classesSame); i++) + { + if (isSame && currentObjects[i] != value[i]) + { isSame = false; } - + Type oldType = GetUnwrappedObject(i).GetType(); object objTemp = value[i]; - - if (objTemp is ICustomTypeDescriptor) { + + if (objTemp is ICustomTypeDescriptor) + { objTemp = ((ICustomTypeDescriptor)objTemp).GetPropertyOwner(null); } - Type newType = objTemp.GetType(); - + Type newType = objTemp.GetType(); + // check if the types are the same. If they are, and they // are COM objects, check their GUID's. If they are different // or Guid.Emtpy, assume the classes are different. // - if (classesSame && - (oldType != newType || oldType.IsCOMObject && newType.IsCOMObject)) { + if (classesSame && + (oldType != newType || oldType.IsCOMObject && newType.IsCOMObject)) + { classesSame = false; } } } - - if (!isSame) { + + if (!isSame) + { EnsureDesignerEventService(); showEvents = showEvents && GetFlag(GotDesignerEventService); - + SetStatusBox("", ""); - + ClearCachedProps(); // The default selected entry might still reference the previous selected // objects. Set it to null to avoid leaks. peDefault = null; - if (value == null) { + if (value == null) + { currentObjects = new object[0]; } - else { + else + { currentObjects = (object[])value.Clone(); } - + SinkPropertyNotifyEvents(); SetFlag(PropertiesChanged, true); // Since we are changing the selection, we need to make sure that the // keywords for the currently selected grid entry gets removed - if (gridView != null) { + if (gridView != null) + { // TypeResolutionService is needed to access the HelpKeyword. However, // TypeResolutionService might be disposed when project is closing. We // need swallow the exception in this case. - try { + try + { gridView.RemoveSelectedEntryHelpAttributes(); } - catch (COMException) {} + catch (COMException) { } } - - if (peMain != null) { + + if (peMain != null) + { peMain.Dispose(); } - + // throw away any extra component only tabs - if (!classesSame && !GetFlag(TabsChanging) && selectedViewTab < viewTabButtons.Length) { - + if (!classesSame && !GetFlag(TabsChanging) && selectedViewTab < viewTabButtons.Length) + { + Type tabType = selectedViewTab == -1 ? null : viewTabs[selectedViewTab].GetType(); ToolStripButton viewTabButton = null; RefreshTabs(PropertyTabScope.Component); EnableTabs(); - if (tabType != null) { - for (int i = 0; i < viewTabs.Length;i++) { - if (viewTabs[i].GetType() == tabType && viewTabButtons[i].Visible) { + if (tabType != null) + { + for (int i = 0; i < viewTabs.Length; i++) + { + if (viewTabs[i].GetType() == tabType && viewTabButtons[i].Visible) + { viewTabButton = viewTabButtons[i]; break; } @@ -1177,66 +1376,75 @@ public object[] SelectedObjects { } SelectViewTabButtonDefault(viewTabButton); } - + // make sure we've also got events on all the objects - if (showEvents && viewTabs != null && viewTabs.Length > EVENTS && (viewTabs[EVENTS] is EventsTab)) { + if (showEvents && viewTabs != null && viewTabs.Length > EVENTS && (viewTabs[EVENTS] is EventsTab)) + { showEvents = viewTabButtons[EVENTS].Visible; object tempObj; PropertyDescriptorCollection events; Attribute[] attrs = new Attribute[BrowsableAttributes.Count]; BrowsableAttributes.CopyTo(attrs, 0); - + Hashtable eventTypes = null; - - if (currentObjects.Length > 10) { - eventTypes = new Hashtable(); + + if (currentObjects.Length > 10) + { + eventTypes = new Hashtable(); } - - for (int i = 0; i < currentObjects.Length && showEvents; i++) { - tempObj = currentObjects[i]; - - if (tempObj is ICustomTypeDescriptor) { - tempObj = ((ICustomTypeDescriptor)tempObj).GetPropertyOwner(null); - } - - Type objType = tempObj.GetType(); - - if (eventTypes != null && eventTypes.Contains(objType)) { - continue; - } - - // make sure these things are sited components as well - showEvents = showEvents && (tempObj is IComponent && ((IComponent)tempObj).Site != null); - - // make sure we've also got events on all the objects - events = ((EventsTab)viewTabs[EVENTS]).GetProperties(tempObj, attrs); - showEvents = showEvents && events != null && events.Count > 0; - - if (showEvents && eventTypes != null) { - eventTypes[objType] = objType; - } + + for (int i = 0; i < currentObjects.Length && showEvents; i++) + { + tempObj = currentObjects[i]; + + if (tempObj is ICustomTypeDescriptor) + { + tempObj = ((ICustomTypeDescriptor)tempObj).GetPropertyOwner(null); + } + + Type objType = tempObj.GetType(); + + if (eventTypes != null && eventTypes.Contains(objType)) + { + continue; + } + + // make sure these things are sited components as well + showEvents = showEvents && (tempObj is IComponent && ((IComponent)tempObj).Site != null); + + // make sure we've also got events on all the objects + events = ((EventsTab)viewTabs[EVENTS]).GetProperties(tempObj, attrs); + showEvents = showEvents && events != null && events.Count > 0; + + if (showEvents && eventTypes != null) + { + eventTypes[objType] = objType; + } } } ShowEventsButton(showEvents && currentObjects.Length > 0); DisplayHotCommands(); - - if (currentObjects.Length == 1) { + + if (currentObjects.Length == 1) + { EnablePropPageButton(currentObjects[0]); } - else { + else + { EnablePropPageButton(null); } OnSelectedObjectsChanged(EventArgs.Empty); } - - + + /* Microsoft, hopefully this won't be a big perf problem, but it looks like we need to refresh even if we didn't change the selected objects. if (propertiesChanged) {*/ - if (!GetFlag(TabsChanging)) { + if (!GetFlag(TabsChanging)) + { // ReInitTab means that we should set the tab back to what is used to be for a given designer. // Basically, if you select an events tab for your designer and double click to go to code, it should @@ -1245,58 +1453,68 @@ public object[] SelectedObjects { // so we set that bit when designers get switched, and makes sure we select and refresh that tab // when we load. // - if (currentObjects.Length > 0 && GetFlag(ReInitTab)) { + if (currentObjects.Length > 0 && GetFlag(ReInitTab)) + { object designerKey = ActiveDesigner; // get the active designer, see if we've stashed away state for it. // - if (designerKey != null && designerSelections != null && designerSelections.ContainsKey(designerKey.GetHashCode())) { + if (designerKey != null && designerSelections != null && designerSelections.ContainsKey(designerKey.GetHashCode())) + { int nButton = (int)designerSelections[designerKey.GetHashCode()]; // yep, we know this one. Make sure it's selected. // - if (nButton < viewTabs.Length && (nButton == PROPERTIES || viewTabButtons[nButton].Visible)) { + if (nButton < viewTabs.Length && (nButton == PROPERTIES || viewTabButtons[nButton].Visible)) + { SelectViewTabButton(viewTabButtons[nButton], true); } } - else { + else + { Refresh(false); } SetFlag(ReInitTab, false); } - else { + else + { Refresh(true); } - - if (currentObjects.Length > 0) { + + if (currentObjects.Length > 0) + { SaveTabSelection(); } } - /*}else { - Invalidate(); - gridView.Invalidate(); - //}*/ + /*}else { + Invalidate(); + gridView.Invalidate(); + //}*/ } - finally { - this.FreezePainting = false; + finally + { + this.FreezePainting = false; } } - get + get { - if (currentObjects == null) { + if (currentObjects == null) + { return new object[0]; } return (object[])currentObjects.Clone(); } } - + [ Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public PropertyTab SelectedTab { - get { + public PropertyTab SelectedTab + { + get + { Debug.Assert(selectedViewTab < viewTabs.Length && selectedViewTab >= 0, "Invalid tab selection!"); return viewTabs[selectedViewTab]; } @@ -1308,45 +1526,56 @@ public PropertyTab SelectedTab { Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public GridItem SelectedGridItem { - get { + public GridItem SelectedGridItem + { + get + { GridItem g = gridView.SelectedGridEntry; - if (g == null) { + if (g == null) + { return this.peMain; } return g; } - set { + set + { gridView.SelectedGridEntry = (GridEntry)value; } } - - protected internal override bool ShowFocusCues { - get { + + protected internal override bool ShowFocusCues + { + get + { return true; } } - public override ISite Site { - get { + public override ISite Site + { + get + { return base.Site; } - set { - + set + { + // Perf - the base class is possibly going to change the font via ambient properties service SuspendAllLayout(this); - + base.Site = value; gridView.ServiceProvider = value; - if (value == null) { + if (value == null) + { this.ActiveDesigner = null; } - else { + else + { this.ActiveDesigner = (IDesignerHost)value.GetService(typeof(IDesignerHost)); } - - ResumeAllLayout(this,true); + + ResumeAllLayout(this, true); } } @@ -1354,25 +1583,31 @@ public override ISite Site { /// /// Gets the value indicating whether the Property grid is sorted by categories. /// - internal bool SortedByCategories { - get { + internal bool SortedByCategories + { + get + { return (PropertySort & PropertySort.Categorized) != 0; } } - [Browsable(false), + [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; } } [Browsable(false)] - new public event EventHandler TextChanged { + new public event EventHandler TextChanged + { add => base.TextChanged += value; remove => base.TextChanged -= value; } @@ -1383,28 +1618,36 @@ public override string Text { SRDescription(nameof(SR.PropertyGridLargeButtonsDesc)), DefaultValue(false) ] - public bool LargeButtons { - get { + public bool LargeButtons + { + get + { return buttonType == LARGE_BUTTONS; } - set { - if (value == (buttonType == LARGE_BUTTONS)) { + set + { + if (value == (buttonType == LARGE_BUTTONS)) + { return; } - this.buttonType = (value ? LARGE_BUTTONS : NORMAL_BUTTONS); - if (value) { + this.buttonType = (value ? LARGE_BUTTONS : NORMAL_BUTTONS); + if (value) + { EnsureLargeButtons(); - if (this.imageList != null && this.imageList[LARGE_BUTTONS] != null) { + if (this.imageList != null && this.imageList[LARGE_BUTTONS] != null) + { toolStrip.ImageScalingSize = this.imageList[LARGE_BUTTONS].ImageSize; } } - else { - if (this.imageList != null && this.imageList[NORMAL_BUTTONS] != null) { + else + { + if (this.imageList != null && this.imageList[NORMAL_BUTTONS] != null) + { toolStrip.ImageScalingSize = this.imageList[NORMAL_BUTTONS].ImageSize; } } - + toolStrip.ImageList = imageList[this.buttonType]; OnLayoutInternal(false); Invalidate(); @@ -1415,8 +1658,10 @@ public bool LargeButtons { /// /// Gets the toolbar control accessibility object. /// - internal AccessibleObject ToolbarAccessibleObject { - get { + internal AccessibleObject ToolbarAccessibleObject + { + get + { return toolStrip.AccessibilityObject; } } @@ -1429,16 +1674,20 @@ internal AccessibleObject ToolbarAccessibleObject { DefaultValue(true), SRDescription(nameof(SR.PropertyGridToolbarVisibleDesc)) ] - public virtual bool ToolbarVisible { - get { + public virtual bool ToolbarVisible + { + get + { return this.toolbarVisible; } - set { + set + { this.toolbarVisible = value; toolStrip.Visible = value; OnLayoutInternal(false); - if (value) { + if (value) + { SetupToolbar(this.viewTabsDirty); } Invalidate(); @@ -1448,51 +1697,62 @@ public virtual bool ToolbarVisible { // PM team has reviewed and decided on naming changes already [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] - protected ToolStripRenderer ToolStripRenderer { - get { - if (toolStrip != null) { + protected ToolStripRenderer ToolStripRenderer + { + get + { + if (toolStrip != null) + { return toolStrip.Renderer; } - return null; + return null; } - set { - if (toolStrip != null) { - toolStrip.Renderer = value; + set + { + if (toolStrip != null) + { + toolStrip.Renderer = value; } } } - + [ SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.PropertyGridViewBackColorDesc)), DefaultValue(typeof(Color), "Window") ] - public Color ViewBackColor { - get { + public Color ViewBackColor + { + get + { return gridView.BackColor; } - set { + set + { gridView.BackColor = value; gridView.Invalidate(); } } - + [ SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.PropertyGridViewForeColorDesc)), DefaultValue(typeof(Color), "WindowText") ] - public Color ViewForeColor { - get { + public Color ViewForeColor + { + get + { return gridView.ForeColor; } - set { + set + { gridView.ForeColor = value; gridView.Invalidate(); - + } } - + /// /// Border color for the property grid view. /// @@ -1501,24 +1761,31 @@ public Color ViewForeColor { SRDescription(nameof(SR.PropertyGridViewBorderColorDesc)), DefaultValue(typeof(Color), "ControlDark") ] - public Color ViewBorderColor { - get { + public Color ViewBorderColor + { + get + { return viewBorderColor; } - set { - if (viewBorderColor != value) { + set + { + if (viewBorderColor != value) + { viewBorderColor = value; gridView.Invalidate(); } } } - private int AddImage(Bitmap image) { - if (image.RawFormat.Guid != ImageFormat.Icon.Guid) { + private int AddImage(Bitmap image) + { + if (image.RawFormat.Guid != ImageFormat.Icon.Guid) + { image.MakeTransparent(); } // Resize bitmap only if resizing is needed in order to avoid image distortion. - if (DpiHelper.IsScalingRequired && (image.Size.Width != normalButtonSize.Width || image.Size.Height != normalButtonSize.Height)) { + if (DpiHelper.IsScalingRequired && (image.Size.Width != normalButtonSize.Width || image.Size.Height != normalButtonSize.Height)) + { image = DpiHelper.CreateResizedBitmap(image, normalButtonSize); } int result = imageList[NORMAL_BUTTONS].Images.Count; @@ -1528,7 +1795,8 @@ private int AddImage(Bitmap image) { /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event KeyEventHandler KeyDown { + public new event KeyEventHandler KeyDown + { add => base.KeyDown += value; remove => base.KeyDown -= value; } @@ -1536,7 +1804,8 @@ private int AddImage(Bitmap image) { /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event KeyPressEventHandler KeyPress { + public new event KeyPressEventHandler KeyPress + { add => base.KeyPress += value; remove => base.KeyPress -= value; } @@ -1544,116 +1813,135 @@ private int AddImage(Bitmap image) { /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event KeyEventHandler KeyUp { + public new event KeyEventHandler KeyUp + { add => base.KeyUp += value; remove => base.KeyUp -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event MouseEventHandler MouseDown { + public new event MouseEventHandler MouseDown + { add => base.MouseDown += value; remove => base.MouseDown -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event MouseEventHandler MouseUp { + public new event MouseEventHandler MouseUp + { add => base.MouseUp += value; remove => base.MouseUp -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event MouseEventHandler MouseMove { + public new event MouseEventHandler MouseMove + { add => base.MouseMove += value; remove => base.MouseMove -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event EventHandler MouseEnter { + public new event EventHandler MouseEnter + { add => base.MouseEnter += value; remove => base.MouseEnter -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public new event EventHandler MouseLeave { + public new event EventHandler MouseLeave + { add => base.MouseLeave += value; remove => base.MouseLeave -= value; } /// Event that is fired when a property value is modified. [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.PropertyGridPropertyValueChangedDescr))] - public event PropertyValueChangedEventHandler PropertyValueChanged { + public event PropertyValueChangedEventHandler PropertyValueChanged + { add => Events.AddHandler(EventPropertyValueChanged, value); remove => Events.RemoveHandler(EventPropertyValueChanged, value); } - event ComponentRenameEventHandler IComPropertyBrowser.ComComponentNameChanged { + event ComponentRenameEventHandler IComPropertyBrowser.ComComponentNameChanged + { add => Events.AddHandler(EventComComponentNameChanged, value); remove => Events.RemoveHandler(EventComComponentNameChanged, value); } - + /// Event that is fired when the current view tab is changed, such as changing from Properties to Events [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.PropertyGridPropertyTabchangedDescr))] - public event PropertyTabChangedEventHandler PropertyTabChanged { + public event PropertyTabChangedEventHandler PropertyTabChanged + { add => Events.AddHandler(EventPropertyTabChanged, value); remove => Events.RemoveHandler(EventPropertyTabChanged, value); } - + /// Event that is fired when the sort mode is changed. [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.PropertyGridPropertySortChangedDescr))] - public event EventHandler PropertySortChanged { + public event EventHandler PropertySortChanged + { add => Events.AddHandler(EventPropertySortChanged, value); remove => Events.RemoveHandler(EventPropertySortChanged, value); } - + /// Event that is fired when the selected GridItem is changed [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.PropertyGridSelectedGridItemChangedDescr))] - public event SelectedGridItemChangedEventHandler SelectedGridItemChanged { + public event SelectedGridItemChangedEventHandler SelectedGridItemChanged + { add => Events.AddHandler(EventSelectedGridItemChanged, value); - remove => Events.RemoveHandler(EventSelectedGridItemChanged, value); + remove => Events.RemoveHandler(EventSelectedGridItemChanged, value); } - + [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.PropertyGridSelectedObjectsChangedDescr))] - public event EventHandler SelectedObjectsChanged { + public event EventHandler SelectedObjectsChanged + { add => Events.AddHandler(EventSelectedObjectsChanged, value); remove => Events.RemoveHandler(EventSelectedObjectsChanged, value); } - - - internal void AddTab(Type tabType, PropertyTabScope scope) { + + + internal void AddTab(Type tabType, PropertyTabScope scope) + { AddRefTab(tabType, null, scope, true); } - - internal void AddRefTab(Type tabType, object component, PropertyTabScope type, bool setupToolbar) { + + internal void AddRefTab(Type tabType, object component, PropertyTabScope type, bool setupToolbar) + { PropertyTab tab = null; int tabIndex = -1; - if (viewTabs != null) { + if (viewTabs != null) + { // check to see if we've already got a tab of this type - for (int i = 0; i < viewTabs.Length; i++) { + for (int i = 0; i < viewTabs.Length; i++) + { Debug.Assert(viewTabs[i] != null, "Null item in tab array!"); - if (tabType == viewTabs[i].GetType()) { + if (tabType == viewTabs[i].GetType()) + { tab = viewTabs[i]; tabIndex = i; break; } } } - else { + else + { tabIndex = 0; } - if (tab == null) { + if (tab == null) + { // the tabs need service providers. The one we hold onto is not good enough, // so try to get the one off of the component's site. IDesignerHost host = null; - if (component != null && component is IComponent && ((IComponent) component).Site != null) - host = (IDesignerHost) ((IComponent) component).Site.GetService(typeof(IDesignerHost)); + if (component != null && component is IComponent && ((IComponent)component).Site != null) + host = (IDesignerHost)((IComponent)component).Site.GetService(typeof(IDesignerHost)); try { @@ -1665,27 +1953,34 @@ internal void AddRefTab(Type tabType, object component, PropertyTabScope type, b } // add it at the end of the array - if (viewTabs != null) { + if (viewTabs != null) + { tabIndex = viewTabs.Length; // find the insertion position...special case for event's and properties - if (tabType == DefaultTabType) { + if (tabType == DefaultTabType) + { tabIndex = PROPERTIES; } - else if (typeof(EventsTab).IsAssignableFrom(tabType)) { + else if (typeof(EventsTab).IsAssignableFrom(tabType)) + { tabIndex = EVENTS; } - else { + else + { // order tabs alphabetically, we've always got a property tab, so // start after that - for (int i = 1; i < viewTabs.Length; i++) { + for (int i = 1; i < viewTabs.Length; i++) + { // skip the event tab - if (viewTabs[i] is EventsTab) { + if (viewTabs[i] is EventsTab) + { continue; } - if (string.Compare(tab.TabName, viewTabs[i].TabName, false, CultureInfo.InvariantCulture) < 0) { + if (string.Compare(tab.TabName, viewTabs[i].TabName, false, CultureInfo.InvariantCulture) < 0) + { tabIndex = i; break; } @@ -1711,44 +2006,54 @@ internal void AddRefTab(Type tabType, object component, PropertyTabScope type, b Debug.Assert(viewTabs != null, "Tab array destroyed!"); } - if (tab != null && component != null) { - try { + if (tab != null && component != null) + { + try + { object[] tabComps = tab.Components; int oldArraySize = tabComps == null ? 0 : tabComps.Length; object[] newComps = new object[oldArraySize + 1]; - if (oldArraySize > 0) { + if (oldArraySize > 0) + { Array.Copy(tabComps, newComps, oldArraySize); } newComps[oldArraySize] = component; tab.Components = newComps; } - catch (Exception e) { + catch (Exception e) + { Debug.Fail("Bad tab. We're going to remove it.", e.ToString()); RemoveTab(tabIndex, false); } } - if (setupToolbar) { + if (setupToolbar) + { SetupToolbar(); ShowEventsButton(false); } - } - + } + /// Collapses all the nodes in the PropertyGrid - public void CollapseAllGridItems() { + public void CollapseAllGridItems() + { gridView.RecursivelyExpand(peMain, false, false, -1); } - - private void ClearCachedProps() { - if (viewTabProps != null) { - viewTabProps.Clear(); + + private void ClearCachedProps() + { + if (viewTabProps != null) + { + viewTabProps.Clear(); } - } - - internal void ClearValueCaches() { - if (peMain != null) { - peMain.ClearCachedValues(); + } + + internal void ClearValueCaches() + { + if (peMain != null) + { + peMain.ClearCachedValues(); } } @@ -1757,72 +2062,87 @@ internal void ClearValueCaches() { /// Clears the tabs of the given scope or smaller. /// tabScope must be PropertyTabScope.Component or PropertyTabScope.Document. /// - internal void ClearTabs(PropertyTabScope tabScope) { - if (tabScope < PropertyTabScope.Document) { + internal void ClearTabs(PropertyTabScope tabScope) + { + if (tabScope < PropertyTabScope.Document) + { throw new ArgumentException(SR.PropertyGridTabScope); } RemoveTabs(tabScope, true); } - #if DEBUG - internal bool inGridViewCreate = false; - #endif +#if DEBUG + internal bool inGridViewCreate = false; +#endif /// /// Constructs the new instance of the accessibility object for current PropertyGrid control. /// /// - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new PropertyGridAccessibleObject(this); } - private /*protected virtual*/ PropertyGridView CreateGridView(IServiceProvider sp) { + private /*protected virtual*/ PropertyGridView CreateGridView(IServiceProvider sp) + { #if DEBUG - try { - inGridViewCreate = true; -#endif - return new PropertyGridView(sp, this); + try + { + inGridViewCreate = true; +#endif + return new PropertyGridView(sp, this); #if DEBUG } - finally { - inGridViewCreate = false; - } + finally + { + inGridViewCreate = false; + } #endif } - private ToolStripSeparator CreateSeparatorButton() { + private ToolStripSeparator CreateSeparatorButton() + { ToolStripSeparator button = new ToolStripSeparator(); return button; } - protected virtual PropertyTab CreatePropertyTab(Type tabType) { - return null; + protected virtual PropertyTab CreatePropertyTab(Type tabType) + { + return null; } - private PropertyTab CreateTab(Type tabType, IDesignerHost host) { + private PropertyTab CreateTab(Type tabType, IDesignerHost host) + { PropertyTab tab = CreatePropertyTab(tabType); - if (tab == null) { - ConstructorInfo constructor = tabType.GetConstructor(new Type[] {typeof(IServiceProvider)}); + if (tab == null) + { + ConstructorInfo constructor = tabType.GetConstructor(new Type[] { typeof(IServiceProvider) }); object param = null; - if (constructor == null) { - + if (constructor == null) + { + // try a IDesignerHost ctor - constructor = tabType.GetConstructor(new Type[] {typeof(IDesignerHost)}); - - if (constructor != null) { + constructor = tabType.GetConstructor(new Type[] { typeof(IDesignerHost) }); + + if (constructor != null) + { param = host; } } - else { + else + { param = this.Site; } - - - if (param != null && constructor != null) { - tab = (PropertyTab) constructor.Invoke(new object[] {param}); + + + if (param != null && constructor != null) + { + tab = (PropertyTab)constructor.Invoke(new object[] { param }); } - else { + else + { // just call the default ctor // tab = (PropertyTab)Activator.CreateInstance(tabType); @@ -1831,18 +2151,20 @@ private PropertyTab CreateTab(Type tabType, IDesignerHost host) { Debug.Assert(tab != null, "Failed to create tab!"); - if (tab != null) { + if (tab != null) + { // ensure it's a valid tab Bitmap bitmap = tab.Bitmap; - + if (bitmap == null) throw new ArgumentException(string.Format(SR.PropertyGridNoBitmap, tab.GetType().FullName)); Size size = bitmap.Size; - if (size.Width != 16 || size.Height != 16) { + if (size.Width != 16 || size.Height != 16) + { // resize it to 16x16 if it isn't already. // - bitmap = new Bitmap(bitmap, new Size(16,16)); + bitmap = new Bitmap(bitmap, new Size(16, 16)); } string name = tab.TabName; @@ -1868,7 +2190,8 @@ private ToolStripButton CreateToggleButton(string toolTipText, int imageIndex, E } */ - private ToolStripButton CreatePushButton(string toolTipText, int imageIndex, EventHandler eventHandler, bool useCheckButtonRole = false) { + private ToolStripButton CreatePushButton(string toolTipText, int imageIndex, EventHandler eventHandler, bool useCheckButtonRole = false) + { ToolStripButton button = new ToolStripButton(); button.Text = toolTipText; button.AutoToolTip = true; @@ -1877,18 +2200,21 @@ private ToolStripButton CreatePushButton(string toolTipText, int imageIndex, Eve button.Click += eventHandler; button.ImageScaling = ToolStripItemImageScaling.SizeToFit; - if (useCheckButtonRole) { + if (useCheckButtonRole) + { button.AccessibleRole = AccessibleRole.CheckButton; } return button; } - - internal void DumpPropsToConsole() { + + internal void DumpPropsToConsole() + { gridView.DumpPropsToConsole(peMain, ""); } - private void DisplayHotCommands() { + private void DisplayHotCommands() + { bool hotCommandsDisplayed = hotcommands.Visible; IComponent component = null; @@ -1898,22 +2224,28 @@ private void DisplayHotCommands() { // verbs. If we fail that, we will go straight to the // designer. // - if (currentObjects != null && currentObjects.Length > 0) { - for (int i = 0; i < currentObjects.Length; i++) { + if (currentObjects != null && currentObjects.Length > 0) + { + for (int i = 0; i < currentObjects.Length; i++) + { object obj = GetUnwrappedObject(i); - if (obj is IComponent) { + if (obj is IComponent) + { component = (IComponent)obj; break; } } - if (component != null) { + if (component != null) + { ISite site = component.Site; - if (site != null) { + if (site != null) + { IMenuCommandService mcs = (IMenuCommandService)site.GetService(typeof(IMenuCommandService)); - if (mcs != null) { + if (mcs != null) + { // Got the menu command service. Let it deal with the set of verbs for // this component. @@ -1921,18 +2253,22 @@ private void DisplayHotCommands() { verbs = new DesignerVerb[mcs.Verbs.Count]; mcs.Verbs.CopyTo(verbs, 0); } - else { + else + { // No menu command service. Go straight to the component's designer. We // can only do this if the Object count is 1, because desginers do not // support verbs across a multi-selection. // - if (currentObjects.Length == 1 && GetUnwrappedObject(0) is IComponent) { + if (currentObjects.Length == 1 && GetUnwrappedObject(0) is IComponent) + { - IDesignerHost designerHost = (IDesignerHost) site.GetService(typeof(IDesignerHost)); - if (designerHost != null) { + IDesignerHost designerHost = (IDesignerHost)site.GetService(typeof(IDesignerHost)); + if (designerHost != null) + { IDesigner designer = designerHost.GetDesigner(component); - if (designer != null) { + if (designer != null) + { verbs = new DesignerVerb[designer.Verbs.Count]; designer.Verbs.CopyTo(verbs, 0); } @@ -1944,91 +2280,111 @@ private void DisplayHotCommands() { } // don't show verbs if a prop grid is on the form at design time. - if (!DesignMode) { - + if (!DesignMode) + { - if (verbs != null && verbs.Length > 0) { + + if (verbs != null && verbs.Length > 0) + { hotcommands.SetVerbs(component, verbs); } - else { + else + { hotcommands.SetVerbs(null, null); } - - if (hotCommandsDisplayed != hotcommands.Visible) { + + if (hotCommandsDisplayed != hotcommands.Visible) + { OnLayoutInternal(false); } } } - - protected override void Dispose(bool disposing) { - if (disposing) { + protected override void Dispose(bool disposing) + { + + if (disposing) + { // Unhook IDesignerEventService.ActiveDesignerChanged event // - if (GetFlag(GotDesignerEventService)) { + if (GetFlag(GotDesignerEventService)) + { Debug.Assert(designerEventService != null, "GetFlag(GotDesignerEventService) inconsistent with designerEventService == null"); - if (designerEventService != null) { + if (designerEventService != null) + { designerEventService.ActiveDesignerChanged -= new ActiveDesignerEventHandler(this.OnActiveDesignerChanged); - } + } designerEventService = null; SetFlag(GotDesignerEventService, false); } this.ActiveDesigner = null; - if (viewTabs != null) { - for (int i = 0; i < viewTabs.Length; i++) { + if (viewTabs != null) + { + for (int i = 0; i < viewTabs.Length; i++) + { viewTabs[i].Dispose(); } viewTabs = null; } - if (imageList != null) { - for (int i = 0; i < imageList.Length; i++) { - if(imageList[i] != null) { + if (imageList != null) + { + for (int i = 0; i < imageList.Length; i++) + { + if (imageList[i] != null) + { imageList[i].Dispose(); } } imageList = null; } - if (bmpAlpha != null) { + if (bmpAlpha != null) + { bmpAlpha.Dispose(); bmpAlpha = null; } - - if (bmpCategory != null) { + + if (bmpCategory != null) + { bmpCategory.Dispose(); bmpCategory = null; } - - if (bmpPropPage != null) { + + if (bmpPropPage != null) + { bmpPropPage.Dispose(); bmpPropPage = null; } - - if (lineBrush != null) { + + if (lineBrush != null) + { lineBrush.Dispose(); lineBrush = null; } - if (peMain != null) { + if (peMain != null) + { peMain.Dispose(); peMain = null; } - if (currentObjects != null) { + if (currentObjects != null) + { currentObjects = null; SinkPropertyNotifyEvents(); } ClearCachedProps(); - currentPropEntries = null; + currentPropEntries = null; } base.Dispose(disposing); } - private void DividerDraw(int y) { + private void DividerDraw(int y) + { if (y == -1) return; @@ -2036,41 +2392,50 @@ private void DividerDraw(int y) { rectangle.Y = y - cyDivider; rectangle.Height = cyDivider; - DrawXorBar(this,rectangle); + DrawXorBar(this, rectangle); } - private SnappableControl DividerInside(int x, int y) { + private SnappableControl DividerInside(int x, int y) + { int useGrid = -1; - if (hotcommands.Visible) { + if (hotcommands.Visible) + { Point locDoc = hotcommands.Location; if (y >= (locDoc.Y - cyDivider) && - y <= (locDoc.Y + 1)) { + y <= (locDoc.Y + 1)) + { return hotcommands; } useGrid = 0; } - if (doccomment.Visible) { + if (doccomment.Visible) + { Point locDoc = doccomment.Location; if (y >= (locDoc.Y - cyDivider) && - y <= (locDoc.Y+1)) { + y <= (locDoc.Y + 1)) + { return doccomment; } - if (useGrid == -1) { + if (useGrid == -1) + { useGrid = 1; } } // also the bottom line of the grid - if (useGrid != -1) { + if (useGrid != -1) + { int gridTop = gridView.Location.Y; int gridBottom = gridTop + gridView.Size.Height; - if (Math.Abs(gridBottom - y) <= 1 && y > gridTop) { - switch (useGrid) { + if (Math.Abs(gridBottom - y) <= 1 && y > gridTop) + { + switch (useGrid) + { case 0: return hotcommands; case 1: @@ -2081,49 +2446,59 @@ private SnappableControl DividerInside(int x, int y) { return null; } - private int DividerLimitHigh(SnappableControl target) { + private int DividerLimitHigh(SnappableControl target) + { int high = gridView.Location.Y + MIN_GRID_HEIGHT; if (target == doccomment && hotcommands.Visible) high += hotcommands.Size.Height + 2; return high; } - private int DividerLimitMove(SnappableControl target, int y) { + private int DividerLimitMove(SnappableControl target, int y) + { Rectangle rectTarget = target.Bounds; int cyNew = y; // make sure we're not going to make ourselves zero height -- make 15 the min size - cyNew = Math.Min((rectTarget.Y + rectTarget.Height - 15),cyNew); + cyNew = Math.Min((rectTarget.Y + rectTarget.Height - 15), cyNew); // make sure we're not going to make ourselves cover up the grid cyNew = Math.Max(DividerLimitHigh(target), cyNew); // just return what we got here - return(cyNew); + return (cyNew); } - - private static void DrawXorBar(Control ctlDrawTo, Rectangle rcFrame) { + + private static void DrawXorBar(Control ctlDrawTo, Rectangle rcFrame) + { Rectangle rc = ctlDrawTo.RectangleToScreen(rcFrame); - if (rc.Width < rc.Height) { - for (int i = 0; i < rc.Width; i++) { - ControlPaint.DrawReversibleLine(new Point(rc.X+i, rc.Y), new Point(rc.X+i, rc.Y+rc.Height), ctlDrawTo.BackColor); + if (rc.Width < rc.Height) + { + for (int i = 0; i < rc.Width; i++) + { + ControlPaint.DrawReversibleLine(new Point(rc.X + i, rc.Y), new Point(rc.X + i, rc.Y + rc.Height), ctlDrawTo.BackColor); } } - else { - for (int i = 0; i < rc.Height; i++) { - ControlPaint.DrawReversibleLine(new Point(rc.X, rc.Y+i), new Point(rc.X+rc.Width, rc.Y+i), ctlDrawTo.BackColor); + else + { + for (int i = 0; i < rc.Height; i++) + { + ControlPaint.DrawReversibleLine(new Point(rc.X, rc.Y + i), new Point(rc.X + rc.Width, rc.Y + i), ctlDrawTo.BackColor); } } } - void IComPropertyBrowser.DropDownDone() { + void IComPropertyBrowser.DropDownDone() + { GetPropertyGridView().DropDownDone(); } - - private bool EnablePropPageButton(object obj) { - if (obj == null) { + + private bool EnablePropPageButton(object obj) + { + if (obj == null) + { btnViewPropertyPages.Enabled = false; return false; } @@ -2131,10 +2506,12 @@ private bool EnablePropPageButton(object obj) { IUIService uiSvc = (IUIService)GetService(typeof(IUIService)); bool enable = false; - if (uiSvc != null) { + if (uiSvc != null) + { enable = uiSvc.CanShowComponentEditor(obj); } - else { + else + { enable = (TypeDescriptor.GetEditor(obj, typeof(ComponentEditor)) != null); } @@ -2143,23 +2520,27 @@ private bool EnablePropPageButton(object obj) { } // walk through the current tabs to see if they're all valid for this Object - private void EnableTabs() { - if (currentObjects != null) { + private void EnableTabs() + { + if (currentObjects != null) + { // make sure our toolbars is okay SetupToolbar(); Debug.Assert(viewTabs != null, "Invalid tab array"); - Debug.Assert(viewTabs.Length == viewTabScopes.Length && viewTabScopes.Length == viewTabButtons.Length,"Uh oh, tab arrays aren't all the same length! tabs=" + viewTabs.Length.ToString(CultureInfo.InvariantCulture) + ", scopes=" + viewTabScopes.Length.ToString(CultureInfo.InvariantCulture) + ", buttons=" + viewTabButtons.Length.ToString(CultureInfo.InvariantCulture)); + Debug.Assert(viewTabs.Length == viewTabScopes.Length && viewTabScopes.Length == viewTabButtons.Length, "Uh oh, tab arrays aren't all the same length! tabs=" + viewTabs.Length.ToString(CultureInfo.InvariantCulture) + ", scopes=" + viewTabScopes.Length.ToString(CultureInfo.InvariantCulture) + ", buttons=" + viewTabButtons.Length.ToString(CultureInfo.InvariantCulture)); // skip the property tab since it's always valid - for (int i = 1; i < viewTabs.Length; i++) { + for (int i = 1; i < viewTabs.Length; i++) + { Debug.Assert(viewTabs[i] != null, "Invalid tab array entry"); bool canExtend = true; // make sure the tab is valid for all objects - for (int j = 0; j < currentObjects.Length; j++) { + for (int j = 0; j < currentObjects.Length; j++) + { try { if (!viewTabs[i].CanExtend(GetUnwrappedObject(j))) @@ -2176,9 +2557,11 @@ private void EnableTabs() { } } - if (canExtend != viewTabButtons[i].Visible) { + if (canExtend != viewTabButtons[i].Visible) + { viewTabButtons[i].Visible = canExtend; - if (!canExtend && i == selectedViewTab) { + if (!canExtend && i == selectedViewTab) + { SelectViewTabButton(viewTabButtons[PROPERTIES], true); } } @@ -2186,39 +2569,49 @@ private void EnableTabs() { } } - private void EnsureDesignerEventService() { - if (GetFlag(GotDesignerEventService)) { + private void EnsureDesignerEventService() + { + if (GetFlag(GotDesignerEventService)) + { return; } designerEventService = (IDesignerEventService)GetService(typeof(IDesignerEventService)); - if (designerEventService != null) { + if (designerEventService != null) + { SetFlag(GotDesignerEventService, true); designerEventService.ActiveDesignerChanged += new ActiveDesignerEventHandler(this.OnActiveDesignerChanged); OnActiveDesignerChanged(null, new ActiveDesignerEventArgs(null, designerEventService.ActiveDesigner)); } } - private void EnsureLargeButtons() { - if (this.imageList[LARGE_BUTTONS] == null) { + private void EnsureLargeButtons() + { + if (this.imageList[LARGE_BUTTONS] == null) + { this.imageList[LARGE_BUTTONS] = new ImageList(); this.imageList[LARGE_BUTTONS].ImageSize = largeButtonSize; - if (DpiHelper.IsScalingRequired) { + if (DpiHelper.IsScalingRequired) + { AddLargeImage(bmpAlpha); AddLargeImage(bmpCategory); - foreach (PropertyTab tab in viewTabs) { + foreach (PropertyTab tab in viewTabs) + { AddLargeImage(tab.Bitmap); } AddLargeImage(bmpPropPage); } - else { + else + { ImageList.ImageCollection images = imageList[NORMAL_BUTTONS].Images; - for (int i = 0; i < images.Count; i++) { - if (images[i] is Bitmap) { + for (int i = 0; i < images.Count; i++) + { + if (images[i] is Bitmap) + { this.imageList[LARGE_BUTTONS].Images.Add(new Bitmap((Bitmap)images[i], largeButtonSize.Width, largeButtonSize.Height)); } } @@ -2227,71 +2620,87 @@ private void EnsureLargeButtons() { } // this method should be called only inside a if (DpiHelper.IsScalingRequired) clause - private void AddLargeImage(Bitmap originalBitmap) { - if (originalBitmap == null) { + private void AddLargeImage(Bitmap originalBitmap) + { + if (originalBitmap == null) + { return; } Bitmap largeBitmap = null; - try { + try + { Bitmap transparentBitmap = new Bitmap(originalBitmap); largeBitmap = DpiHelper.CreateResizedBitmap(transparentBitmap, largeButtonSize); transparentBitmap.Dispose(); this.imageList[LARGE_BUTTONS].Images.Add(largeBitmap); } - catch (Exception ex) { + catch (Exception ex) + { Debug.Fail("Failed to add a large property grid toolstrip button, " + ex.ToString()); } } - bool IComPropertyBrowser.EnsurePendingChangesCommitted() { + bool IComPropertyBrowser.EnsurePendingChangesCommitted() + { // The commits sometimes cause transactions to open // and close, which will cause refreshes, which we want to ignore. - try { + try + { - if (this.designerHost != null) { + if (this.designerHost != null) + { designerHost.TransactionOpened -= new EventHandler(this.OnTransactionOpened); designerHost.TransactionClosed -= new DesignerTransactionCloseEventHandler(this.OnTransactionClosed); } - + return GetPropertyGridView().EnsurePendingChangesCommitted(); } - finally { - if (this.designerHost != null) { + finally + { + if (this.designerHost != null) + { designerHost.TransactionOpened += new EventHandler(this.OnTransactionOpened); designerHost.TransactionClosed += new DesignerTransactionCloseEventHandler(this.OnTransactionClosed); } } } - - public void ExpandAllGridItems() { + + public void ExpandAllGridItems() + { gridView.RecursivelyExpand(peMain, false, true, PropertyGridView.MaxRecurseExpand); } - private static Type[] GetCommonTabs(object[] objs, PropertyTabScope tabScope) { + private static Type[] GetCommonTabs(object[] objs, PropertyTabScope tabScope) + { - if (objs == null || objs.Length == 0) { + if (objs == null || objs.Length == 0) + { return new Type[0]; } Type[] tabTypes = new Type[5]; - int types = 0; - int i,j,k; - PropertyTabAttribute tabAttr = (PropertyTabAttribute) TypeDescriptor.GetAttributes(objs[0])[typeof(PropertyTabAttribute)]; + int types = 0; + int i, j, k; + PropertyTabAttribute tabAttr = (PropertyTabAttribute)TypeDescriptor.GetAttributes(objs[0])[typeof(PropertyTabAttribute)]; - if (tabAttr == null) { + if (tabAttr == null) + { return new Type[0]; } // filter out all the types of the current scope - for (i = 0; i < tabAttr.TabScopes.Length; i++) { - PropertyTabScope item = tabAttr.TabScopes[i]; + for (i = 0; i < tabAttr.TabScopes.Length; i++) + { + PropertyTabScope item = tabAttr.TabScopes[i]; - if (item == tabScope) { - if (types == tabTypes.Length) { + if (item == tabScope) + { + if (types == tabTypes.Length) + { Type[] newTabs = new Type[types * 2]; Array.Copy(tabTypes, 0, newTabs, 0, types); tabTypes = newTabs; @@ -2300,38 +2709,45 @@ private static Type[] GetCommonTabs(object[] objs, PropertyTabScope tabScope) { } } - if (types == 0) { + if (types == 0) + { return new Type[0]; } bool found; - for (i = 1; i < objs.Length && types > 0; i++) { + for (i = 1; i < objs.Length && types > 0; i++) + { // get the tab attribute - tabAttr = (PropertyTabAttribute) TypeDescriptor.GetAttributes(objs[i])[typeof(PropertyTabAttribute)]; + tabAttr = (PropertyTabAttribute)TypeDescriptor.GetAttributes(objs[i])[typeof(PropertyTabAttribute)]; - if (tabAttr == null) { + if (tabAttr == null) + { // if this guy has no tabs at all, we can fail right now return new Type[0]; } // make sure this guy has all the items in the array, // if not, remove the items he doesn't have - for (j = 0; j < types; j++) { + for (j = 0; j < types; j++) + { found = false; - for (k = 0; k < tabAttr.TabClasses.Length; k++) { - if (tabAttr.TabClasses[k] == tabTypes[j]) { + for (k = 0; k < tabAttr.TabClasses.Length; k++) + { + if (tabAttr.TabClasses[k] == tabTypes[j]) + { found = true; break; } } // if we didn't find an item, remove it from the list - if (!found) { + if (!found) + { // swap in with the last item and decrement - tabTypes[j] = tabTypes[types-1]; - tabTypes[types-1] = null; + tabTypes[j] = tabTypes[types - 1]; + tabTypes[types - 1] = null; types--; // recheck this item since we'll be ending sooner @@ -2341,14 +2757,17 @@ private static Type[] GetCommonTabs(object[] objs, PropertyTabScope tabScope) { } Type[] returnTypes = new Type[types]; - if (types > 0) { + if (types > 0) + { Array.Copy(tabTypes, 0, returnTypes, 0, types); } return returnTypes; } - internal GridEntry GetDefaultGridEntry() { - if (peDefault == null && currentPropEntries != null) { + internal GridEntry GetDefaultGridEntry() + { + if (peDefault == null && currentPropEntries != null) + { peDefault = (GridEntry)currentPropEntries[0]; } return peDefault; @@ -2359,41 +2778,51 @@ internal GridEntry GetDefaultGridEntry() { /// /// The point where to search the element. /// The element found in the current point. - internal Control GetElementFromPoint(Point point) { - if (ToolbarAccessibleObject.Bounds.Contains(point)) { + internal Control GetElementFromPoint(Point point) + { + if (ToolbarAccessibleObject.Bounds.Contains(point)) + { return toolStrip; } - if (GridViewAccessibleObject.Bounds.Contains(point)) { + if (GridViewAccessibleObject.Bounds.Contains(point)) + { return gridView; } - if (HotCommandsAccessibleObject.Bounds.Contains(point)) { + if (HotCommandsAccessibleObject.Bounds.Contains(point)) + { return hotcommands; } - if (HelpAccessibleObject.Bounds.Contains(point)) { + if (HelpAccessibleObject.Bounds.Contains(point)) + { return doccomment; } return null; } - private object GetUnwrappedObject(int index) { - if (currentObjects == null || index < 0 || index > currentObjects.Length) { + private object GetUnwrappedObject(int index) + { + if (currentObjects == null || index < 0 || index > currentObjects.Length) + { return null; } object obj = currentObjects[index]; - if (obj is ICustomTypeDescriptor) { + if (obj is ICustomTypeDescriptor) + { obj = ((ICustomTypeDescriptor)obj).GetPropertyOwner(null); } return obj; } - internal GridEntryCollection GetPropEntries() { + internal GridEntryCollection GetPropEntries() + { - if (currentPropEntries == null) { + if (currentPropEntries == null) + { UpdateSelection(); } SetFlag(PropertiesChanged, false); @@ -2401,36 +2830,45 @@ internal GridEntryCollection GetPropEntries() { } - private PropertyGridView GetPropertyGridView() { + private PropertyGridView GetPropertyGridView() + { return gridView; } - - - void IComPropertyBrowser.HandleF4() { - - if (gridView.ContainsFocus) { + + + void IComPropertyBrowser.HandleF4() + { + + if (gridView.ContainsFocus) + { return; } - - if (this.ActiveControl != gridView) { + + if (this.ActiveControl != gridView) + { this.SetActiveControl(gridView); } gridView.Focus(); } - internal bool HavePropEntriesChanged() { + internal bool HavePropEntriesChanged() + { return GetFlag(PropertiesChanged); } - void IComPropertyBrowser.LoadState(RegistryKey optRoot) { - if (optRoot != null) { + void IComPropertyBrowser.LoadState(RegistryKey optRoot) + { + if (optRoot != null) + { object val = optRoot.GetValue("PbrsAlpha", "0"); - if (val != null && val.ToString().Equals("1")) { + if (val != null && val.ToString().Equals("1")) + { this.PropertySort = PropertySort.Alphabetical; } - else { + else + { this.PropertySort = PropertySort.Categorized | PropertySort.Alphabetical; } @@ -2444,45 +2882,54 @@ void IComPropertyBrowser.LoadState(RegistryKey optRoot) { val = optRoot.GetValue("PbrsDescHeightRatio", "-1"); bool update = false; - if (val is string) { + if (val is string) + { int ratio = int.Parse((string)val, CultureInfo.InvariantCulture); - if (ratio > 0) { + if (ratio > 0) + { dcSizeRatio = ratio; update = true; } } val = optRoot.GetValue("PbrsHotCommandHeightRatio", "-1"); - if (val is string) { + if (val is string) + { int ratio = int.Parse((string)val, CultureInfo.InvariantCulture); - if (ratio > 0) { + if (ratio > 0) + { dcSizeRatio = ratio; update = true; } } - if (update) { + if (update) + { OnLayoutInternal(false); } } - else { + else + { // apply the same defaults from above. // this.PropertySort = PropertySort.Categorized | PropertySort.Alphabetical; this.HelpVisible = true; - this.CommandsVisibleIfAvailable = false; + this.CommandsVisibleIfAvailable = false; } } // when the active document is changed, check all the components so see if they // are offering up any new tabs - private void OnActiveDesignerChanged(object sender, ActiveDesignerEventArgs e) { + private void OnActiveDesignerChanged(object sender, ActiveDesignerEventArgs e) + { - if (e.OldDesigner != null && e.OldDesigner == designerHost) { + if (e.OldDesigner != null && e.OldDesigner == designerHost) + { this.ActiveDesigner = null; } - if (e.NewDesigner != null && e.NewDesigner != designerHost) { + if (e.NewDesigner != null && e.NewDesigner != designerHost) + { this.ActiveDesigner = e.NewDesigner; } } @@ -2491,7 +2938,8 @@ private void OnActiveDesignerChanged(object sender, ActiveDesignerEventArgs e) { /// Called when a property on an Ole32 Object changes. /// See IPropertyNotifySink::OnChanged /// - void UnsafeNativeMethods.IPropertyNotifySink.OnChanged(int dispID) { + void UnsafeNativeMethods.IPropertyNotifySink.OnChanged(int dispID) + { // we don't want the grid's own property sets doing this, but if we're getting // an OnChanged that isn't the DispID of the property we're currently changing, // we need to cause a refresh. @@ -2499,26 +2947,31 @@ void UnsafeNativeMethods.IPropertyNotifySink.OnChanged(int dispID) { // bool fullRefresh = false; PropertyDescriptorGridEntry selectedEntry = gridView.SelectedGridEntry as PropertyDescriptorGridEntry; - if (selectedEntry != null && selectedEntry.PropertyDescriptor != null && selectedEntry.PropertyDescriptor.Attributes != null) { + if (selectedEntry != null && selectedEntry.PropertyDescriptor != null && selectedEntry.PropertyDescriptor.Attributes != null) + { // fish out the DispIdAttribute which will tell us the DispId of the // property that we're changing. // DispIdAttribute dispIdAttr = (DispIdAttribute)selectedEntry.PropertyDescriptor.Attributes[(typeof(DispIdAttribute))]; - if (dispIdAttr != null && !dispIdAttr.IsDefaultAttribute()) { + if (dispIdAttr != null && !dispIdAttr.IsDefaultAttribute()) + { fullRefresh = (dispID != dispIdAttr.Value); } } - if (!GetFlag(RefreshingProperties)) { - if (!gridView.GetInPropertySet() || fullRefresh) { + if (!GetFlag(RefreshingProperties)) + { + if (!gridView.GetInPropertySet() || fullRefresh) + { Refresh(fullRefresh); } // this is so changes to names of native // objects will be reflected in the combo box object obj = GetUnwrappedObject(0); - if (ComNativeDescriptor.Instance.IsNameDispId(obj, dispID) || dispID == NativeMethods.ActiveX.DISPID_Name) { + if (ComNativeDescriptor.Instance.IsNameDispId(obj, dispID) || dispID == NativeMethods.ActiveX.DISPID_Name) + { OnComComponentNameChanged(new ComponentRenameEventArgs(obj, null, TypeDescriptor.GetClassName(obj))); } } @@ -2528,9 +2981,11 @@ void UnsafeNativeMethods.IPropertyNotifySink.OnChanged(int dispID) { /// We forward messages from several of our children /// to our mouse move so we can put up the spliter over their borders /// - private void OnChildMouseMove(object sender, MouseEventArgs me) { + private void OnChildMouseMove(object sender, MouseEventArgs me) + { Point newPt = Point.Empty; - if (ShouldForwardChildMouseMessage((Control)sender, me, ref newPt)) { + if (ShouldForwardChildMouseMessage((Control)sender, me, ref newPt)) + { // forward the message this.OnMouseMove(new MouseEventArgs(me.Button, me.Clicks, newPt.X, newPt.Y, me.Delta)); return; @@ -2541,82 +2996,102 @@ private void OnChildMouseMove(object sender, MouseEventArgs me) { /// We forward messages from several of our children /// to our mouse move so we can put up the spliter over their borders /// - private void OnChildMouseDown(object sender, MouseEventArgs me) { + private void OnChildMouseDown(object sender, MouseEventArgs me) + { Point newPt = Point.Empty; - if (ShouldForwardChildMouseMessage((Control)sender, me, ref newPt)) { + if (ShouldForwardChildMouseMessage((Control)sender, me, ref newPt)) + { // forward the message this.OnMouseDown(new MouseEventArgs(me.Button, me.Clicks, newPt.X, newPt.Y, me.Delta)); return; } } - - private void OnComponentAdd(object sender, ComponentEventArgs e) { - PropertyTabAttribute attribute = (PropertyTabAttribute) TypeDescriptor.GetAttributes(e.Component.GetType())[typeof(PropertyTabAttribute)]; + private void OnComponentAdd(object sender, ComponentEventArgs e) + { + + PropertyTabAttribute attribute = (PropertyTabAttribute)TypeDescriptor.GetAttributes(e.Component.GetType())[typeof(PropertyTabAttribute)]; - if (attribute == null) { + if (attribute == null) + { return; } // add all the document items - for (int i=0; i < attribute.TabClasses.Length; i++) { - if (attribute.TabScopes[i] == PropertyTabScope.Document) { + for (int i = 0; i < attribute.TabClasses.Length; i++) + { + if (attribute.TabScopes[i] == PropertyTabScope.Document) + { AddRefTab(attribute.TabClasses[i], e.Component, PropertyTabScope.Document, true); } } } - private void OnComponentChanged(object sender, ComponentChangedEventArgs e) { + private void OnComponentChanged(object sender, ComponentChangedEventArgs e) + { bool batchMode = GetFlag(BatchMode); if (batchMode || GetFlag(InternalChange) || gridView.GetInPropertySet() || - (currentObjects == null) || (currentObjects.Length == 0)) { - - if (batchMode && !gridView.GetInPropertySet()) { + (currentObjects == null) || (currentObjects.Length == 0)) + { + + if (batchMode && !gridView.GetInPropertySet()) + { SetFlag(BatchModeChange, true); } return; } int objectCount = currentObjects.Length; - for (int i = 0; i < objectCount; i++) { - if (currentObjects[i] == e.Component) { + for (int i = 0; i < objectCount; i++) + { + if (currentObjects[i] == e.Component) + { Refresh(false); break; } } } - private void OnComponentRemove(object sender, ComponentEventArgs e) { + private void OnComponentRemove(object sender, ComponentEventArgs e) + { - PropertyTabAttribute attribute = (PropertyTabAttribute) TypeDescriptor.GetAttributes(e.Component.GetType())[typeof(PropertyTabAttribute)]; + PropertyTabAttribute attribute = (PropertyTabAttribute)TypeDescriptor.GetAttributes(e.Component.GetType())[typeof(PropertyTabAttribute)]; - if (attribute == null) { + if (attribute == null) + { return; } // remove all the document items - for (int i=0; i < attribute.TabClasses.Length; i++) { - if (attribute.TabScopes[i] == PropertyTabScope.Document) { + for (int i = 0; i < attribute.TabClasses.Length; i++) + { + if (attribute.TabScopes[i] == PropertyTabScope.Document) + { ReleaseTab(attribute.TabClasses[i], e.Component); } } - - for (int i = 0; i < currentObjects.Length; i++) { - if (e.Component == currentObjects[i]) { - - object[] newObjects = new object[currentObjects.Length - 1]; - Array.Copy(currentObjects, 0, newObjects, 0, i); - if (i < newObjects.Length) { - // Dev10 - - Array.Copy(currentObjects, i + 1, newObjects, i, newObjects.Length - i); - } - if (!GetFlag(BatchMode)) { + for (int i = 0; i < currentObjects.Length; i++) + { + if (e.Component == currentObjects[i]) + { + + object[] newObjects = new object[currentObjects.Length - 1]; + Array.Copy(currentObjects, 0, newObjects, 0, i); + if (i < newObjects.Length) + { + // Dev10 + + Array.Copy(currentObjects, i + 1, newObjects, i, newObjects.Length - i); + } + + if (!GetFlag(BatchMode)) + { this.SelectedObjects = newObjects; } - else { + else + { // otherwise, just dump the selection // gridView.ClearProps(); @@ -2627,68 +3102,79 @@ private void OnComponentRemove(object sender, ComponentEventArgs e) { } SetupToolbar(); - + } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] // - protected override void OnEnabledChanged(EventArgs e) { + protected override void OnEnabledChanged(EventArgs e) + { base.OnEnabledChanged(e); Refresh(); } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] // - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { base.OnFontChanged(e); Refresh(); - } + } /// /// - internal void OnGridViewMouseWheel(MouseEventArgs e) { + internal void OnGridViewMouseWheel(MouseEventArgs e) + { this.OnMouseWheel(e); } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] // - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { base.OnHandleCreated(e); OnLayoutInternal(false); TypeDescriptor.Refreshed += new RefreshEventHandler(this.OnTypeDescriptorRefreshed); - if (currentObjects != null && currentObjects.Length > 0) { + if (currentObjects != null && currentObjects.Length > 0) + { Refresh(true); } } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] // - protected override void OnHandleDestroyed(EventArgs e) { + protected override void OnHandleDestroyed(EventArgs e) + { TypeDescriptor.Refreshed -= new RefreshEventHandler(this.OnTypeDescriptorRefreshed); base.OnHandleDestroyed(e); } - + [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] // - protected override void OnGotFocus(EventArgs e) { - + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); - - if (this.ActiveControl == null) { + + if (this.ActiveControl == null) + { this.SetActiveControl(gridView); } - else { + else + { // sometimes the edit is still the active control // when it's hidden or disabled... - if (!this.ActiveControl.Focus()) { + if (!this.ActiveControl.Focus()) + { this.SetActiveControl(gridView); } } } [EditorBrowsable(EditorBrowsableState.Never)] - protected override void ScaleCore(float dx, float dy) { + protected override void ScaleCore(float dx, float dy) + { int sx = (int)Math.Round(Left * dx); int sy = (int)Math.Round(Top * dy); int sw = Width; @@ -2698,32 +3184,38 @@ protected override void ScaleCore(float dx, float dy) { SetBounds(sx, sy, sw, sh, BoundsSpecified.All); } - private void OnLayoutInternal(bool dividerOnly) { - - if (!IsHandleCreated || !this.Visible) { + private void OnLayoutInternal(bool dividerOnly) + { + + if (!IsHandleCreated || !this.Visible) + { return; } - try { + try + { this.FreezePainting = true; - if (!dividerOnly) { + if (!dividerOnly) + { // no toolbar or doc comment or commands, just // fill the whole thing with the grid - if (!toolStrip.Visible && !doccomment.Visible && !hotcommands.Visible) { - gridView.Location = new Point(0,0); + if (!toolStrip.Visible && !doccomment.Visible && !hotcommands.Visible) + { + gridView.Location = new Point(0, 0); gridView.Size = Size; return; } - if (toolStrip.Visible) { + if (toolStrip.Visible) + { int toolStripWidth = this.Width; - int toolStripHeight = ((LargeButtons) ? largeButtonSize : normalButtonSize).Height + toolStripButtonPaddingY; - Rectangle toolStripBounds = new Rectangle(0,1,toolStripWidth, toolStripHeight); + int toolStripHeight = ((LargeButtons) ? largeButtonSize : normalButtonSize).Height + toolStripButtonPaddingY; + Rectangle toolStripBounds = new Rectangle(0, 1, toolStripWidth, toolStripHeight); toolStrip.Bounds = toolStripBounds; - + int oldY = gridView.Location.Y; gridView.Location = new Point(0, toolStrip.Height + toolStrip.Top); /*if (oldY < gridView.Location.Y) { @@ -2737,7 +3229,8 @@ private void OnLayoutInternal(bool dividerOnly) { toolbar.Invalidate(); }*/ } - else { + else + { gridView.Location = new Point(0, 0); } } @@ -2745,7 +3238,8 @@ private void OnLayoutInternal(bool dividerOnly) { // now work up from the bottom int endSize = Size.Height; - if (endSize < MIN_GRID_HEIGHT) { + if (endSize < MIN_GRID_HEIGHT) + { return; } @@ -2758,52 +3252,66 @@ private void OnLayoutInternal(bool dividerOnly) { int dcOptHeight = 0; int hcOptHeight = 0; - if (dividerOnly) { + if (dividerOnly) + { dcRequestedHeight = doccomment.Visible ? doccomment.Size.Height : 0; hcRequestedHeight = hotcommands.Visible ? hotcommands.Size.Height : 0; } - else { - if (doccomment.Visible) { + else + { + if (doccomment.Visible) + { dcOptHeight = doccomment.GetOptimalHeight(Size.Width - cyDivider); - if (doccomment.userSized) { + if (doccomment.userSized) + { dcRequestedHeight = doccomment.Size.Height; } - else if (dcSizeRatio != -1) { + else if (dcSizeRatio != -1) + { dcRequestedHeight = (this.Height * dcSizeRatio) / 100; } - else { + else + { dcRequestedHeight = dcOptHeight; } } - if (hotcommands.Visible) { + if (hotcommands.Visible) + { hcOptHeight = hotcommands.GetOptimalHeight(Size.Width - cyDivider); - if (hotcommands.userSized) { + if (hotcommands.userSized) + { hcRequestedHeight = hotcommands.Size.Height; } - else if (hcSizeRatio != -1) { + else if (hcSizeRatio != -1) + { hcRequestedHeight = (this.Height * hcSizeRatio) / 100; } - else { + else + { hcRequestedHeight = hcOptHeight; } } } // place the help comment window - if (dcRequestedHeight > 0) { + if (dcRequestedHeight > 0) + { maxSpace -= cyDivider; - if (hcRequestedHeight == 0 || (dcRequestedHeight + hcRequestedHeight) < maxSpace) { + if (hcRequestedHeight == 0 || (dcRequestedHeight + hcRequestedHeight) < maxSpace) + { // full size height = Math.Min(dcRequestedHeight, maxSpace); } - else if (hcRequestedHeight > 0 && hcRequestedHeight < maxSpace) { + else if (hcRequestedHeight > 0 && hcRequestedHeight < maxSpace) + { // give most of the space to the hot commands height = maxSpace - hcRequestedHeight; } - else { + else + { // split the difference height = Math.Min(dcRequestedHeight, maxSpace / 2 - 1); } @@ -2813,10 +3321,12 @@ private void OnLayoutInternal(bool dividerOnly) { doccomment.SetBounds(0, endSize - height, Size.Width, height); // if we've modified the height to less than the optimal, clear the userSized item - if (height <= dcOptHeight && height < dcRequestedHeight) { + if (height <= dcOptHeight && height < dcRequestedHeight) + { doccomment.userSized = false; } - else if (dcSizeRatio != -1 || doccomment.userSized) { + else if (dcSizeRatio != -1 || doccomment.userSized) + { dcSizeRatio = (doccomment.Height * 100) / this.Height; } @@ -2826,15 +3336,18 @@ private void OnLayoutInternal(bool dividerOnly) { } // place the hot commands - if (hcRequestedHeight > 0) { + if (hcRequestedHeight > 0) + { maxSpace -= cyDivider; - if (maxSpace > hcRequestedHeight) { + if (maxSpace > hcRequestedHeight) + { // full size height = Math.Min(hcRequestedHeight, maxSpace); } - else { + else + { // what's left height = maxSpace; } @@ -2842,10 +3355,12 @@ private void OnLayoutInternal(bool dividerOnly) { height = Math.Max(height, cyDivider * 2); // if we've modified the height, clear the userSized item - if (height <= hcOptHeight && height < hcRequestedHeight) { + if (height <= hcOptHeight && height < hcRequestedHeight) + { hotcommands.userSized = false; } - else if (hcSizeRatio != -1 || hotcommands.userSized) { + else if (hcSizeRatio != -1 || hotcommands.userSized) + { hcSizeRatio = (hotcommands.Height * 100) / this.Height; } @@ -2856,17 +3371,20 @@ private void OnLayoutInternal(bool dividerOnly) { gridView.Size = new Size(Size.Width, endSize - gridView.Location.Y); } - finally { + finally + { this.FreezePainting = false; } } - - + + [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] // - protected override void OnMouseDown(MouseEventArgs me) { - SnappableControl target = DividerInside(me.X,me.Y); - if (target != null && me.Button == MouseButtons.Left) { + protected override void OnMouseDown(MouseEventArgs me) + { + SnappableControl target = DividerInside(me.X, me.Y); + if (target != null && me.Button == MouseButtons.Left) + { // capture mouse. CaptureInternal = true; targetMove = target; @@ -2876,16 +3394,20 @@ protected override void OnMouseDown(MouseEventArgs me) { base.OnMouseDown(me); } - + [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] // - protected override void OnMouseMove(MouseEventArgs me) { + protected override void OnMouseMove(MouseEventArgs me) + { - if (dividerMoveY == -1) { - if (DividerInside(me.X,me.Y) != null) { + if (dividerMoveY == -1) + { + if (DividerInside(me.X, me.Y) != null) + { Cursor = Cursors.HSplit; } - else { + else + { Cursor = null; } return; @@ -2893,7 +3415,8 @@ protected override void OnMouseMove(MouseEventArgs me) { int yNew = DividerLimitMove(targetMove, me.Y); - if (yNew != dividerMoveY) { + if (yNew != dividerMoveY) + { DividerDraw(dividerMoveY); dividerMoveY = yNew; DividerDraw(dividerMoveY); @@ -2901,10 +3424,11 @@ protected override void OnMouseMove(MouseEventArgs me) { base.OnMouseMove(me); } - + [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] // - protected override void OnMouseUp(MouseEventArgs me) { + protected override void OnMouseUp(MouseEventArgs me) + { if (dividerMoveY == -1) return; @@ -2913,10 +3437,11 @@ protected override void OnMouseUp(MouseEventArgs me) { DividerDraw(dividerMoveY); dividerMoveY = DividerLimitMove(targetMove, me.Y); Rectangle rectDoc = targetMove.Bounds; - if (dividerMoveY != rectDoc.Y) { + if (dividerMoveY != rectDoc.Y) + { int yNew = rectDoc.Height + rectDoc.Y - dividerMoveY - (cyDivider / 2); // we subtract two so the mouse is still over the divider Size size = targetMove.Size; - size.Height = Math.Max(0,yNew); + size.Height = Math.Max(0, yNew); targetMove.Size = size; targetMove.userSized = true; OnLayoutInternal(true); @@ -2941,16 +3466,19 @@ protected override void OnMouseUp(MouseEventArgs me) { /// with "requestedit" is about to be edited. /// See IPropertyNotifySink::OnRequestEdit /// - int UnsafeNativeMethods.IPropertyNotifySink.OnRequestEdit(int dispID) { + int UnsafeNativeMethods.IPropertyNotifySink.OnRequestEdit(int dispID) + { // we don't do anything here... return NativeMethods.S_OK; } - + [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] // - protected override void OnResize(EventArgs e) { - if (IsHandleCreated && this.Visible) { + protected override void OnResize(EventArgs e) + { + if (IsHandleCreated && this.Visible) + { OnLayoutInternal(false); } base.OnResize(e); @@ -2958,69 +3486,81 @@ protected override void OnResize(EventArgs e) { - private void OnButtonClick(object sender, EventArgs e) { + private void OnButtonClick(object sender, EventArgs e) + { // we don't want to steal focus from the property pages... - if (sender != btnViewPropertyPages) { + if (sender != btnViewPropertyPages) + { gridView.Focus(); } } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] // - protected void OnComComponentNameChanged(ComponentRenameEventArgs e) { + protected void OnComComponentNameChanged(ComponentRenameEventArgs e) + { ComponentRenameEventHandler handler = (ComponentRenameEventHandler)Events[EventComComponentNameChanged]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } - - + + // Seems safe - doesn't do anything interesting [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] - protected void OnNotifyPropertyValueUIItemsChanged(object sender, EventArgs e) { + protected void OnNotifyPropertyValueUIItemsChanged(object sender, EventArgs e) + { gridView.LabelPaintMargin = 0; gridView.Invalidate(true); } - + // Seems safe - doesn't do anything interesting [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] - protected override void OnPaint(PaintEventArgs pevent) { - + protected override void OnPaint(PaintEventArgs pevent) + { + // just erase the stuff above and below the properties window // so we don't flicker. Point psheetLoc = gridView.Location; int width = Size.Width; - + Brush background; - if (BackColor.IsSystemColor) { + if (BackColor.IsSystemColor) + { background = SystemBrushes.FromSystemColor(BackColor); } - else { + else + { background = new SolidBrush(BackColor); } - pevent.Graphics.FillRectangle(background, new Rectangle(0,0,width, psheetLoc.Y)); + pevent.Graphics.FillRectangle(background, new Rectangle(0, 0, width, psheetLoc.Y)); int yLast = psheetLoc.Y + gridView.Size.Height; // fill above hotcommands - if (hotcommands.Visible) { + if (hotcommands.Visible) + { pevent.Graphics.FillRectangle(background, new Rectangle(0, yLast, width, hotcommands.Location.Y - yLast)); yLast += hotcommands.Size.Height; } // fill above doccomment - if (doccomment.Visible) { + if (doccomment.Visible) + { pevent.Graphics.FillRectangle(background, new Rectangle(0, yLast, width, doccomment.Location.Y - yLast)); yLast += doccomment.Size.Height; } // anything that might be left pevent.Graphics.FillRectangle(background, new Rectangle(0, yLast, width, Size.Height - yLast)); - - if (!BackColor.IsSystemColor) { + + if (!BackColor.IsSystemColor) + { background.Dispose(); } base.OnPaint(pevent); - if (lineBrush != null) { + if (lineBrush != null) + { lineBrush.Dispose(); lineBrush = null; } @@ -3028,77 +3568,95 @@ protected override void OnPaint(PaintEventArgs pevent) { // Seems safe - just fires an event [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] - protected virtual void OnPropertySortChanged(EventArgs e) { + protected virtual void OnPropertySortChanged(EventArgs e) + { EventHandler handler = (EventHandler)Events[EventPropertySortChanged]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } // Seems safe - just fires an event [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] - protected virtual void OnPropertyTabChanged (PropertyTabChangedEventArgs e) { + protected virtual void OnPropertyTabChanged(PropertyTabChangedEventArgs e) + { PropertyTabChangedEventHandler handler = (PropertyTabChangedEventHandler)Events[EventPropertyTabChanged]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } - + // Seems safe - just fires an event [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] - protected virtual void OnPropertyValueChanged(PropertyValueChangedEventArgs e) { + protected virtual void OnPropertyValueChanged(PropertyValueChangedEventArgs e) + { PropertyValueChangedEventHandler handler = (PropertyValueChangedEventHandler)Events[EventPropertyValueChanged]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } - internal void OnPropertyValueSet(GridItem changedItem, object oldValue) { + internal void OnPropertyValueSet(GridItem changedItem, object oldValue) + { OnPropertyValueChanged(new PropertyValueChangedEventArgs(changedItem, oldValue)); // Announce the property value change like standalone combobox control do: "[something] selected". bool dropDown = false; Type propertyType = changedItem.PropertyDescriptor.PropertyType; UITypeEditor editor = (UITypeEditor)TypeDescriptor.GetEditor(propertyType, typeof(UITypeEditor)); - if (editor != null) { + if (editor != null) + { dropDown = editor.GetEditStyle() == UITypeEditorEditStyle.DropDown; } - else { + else + { var gridEntry = changedItem as GridEntry; - if (gridEntry != null && gridEntry.Enumerable) { + if (gridEntry != null && gridEntry.Enumerable) + { dropDown = true; } } - if (dropDown && !gridView.DropDownVisible) { + if (dropDown && !gridView.DropDownVisible) + { this.AccessibilityObject.RaiseAutomationNotification( Automation.AutomationNotificationKind.ActionCompleted, Automation.AutomationNotificationProcessing.All, string.Format(SR.PropertyGridPropertyValueSelectedFormat, changedItem.Value)); } } - - internal void OnSelectedGridItemChanged(GridEntry oldEntry, GridEntry newEntry) { + + internal void OnSelectedGridItemChanged(GridEntry oldEntry, GridEntry newEntry) + { OnSelectedGridItemChanged(new SelectedGridItemChangedEventArgs(oldEntry, newEntry)); } - - + + [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] // - protected virtual void OnSelectedGridItemChanged(SelectedGridItemChangedEventArgs e) { + protected virtual void OnSelectedGridItemChanged(SelectedGridItemChangedEventArgs e) + { SelectedGridItemChangedEventHandler handler = (SelectedGridItemChangedEventHandler)Events[EventSelectedGridItemChanged]; - - if (handler != null) { + + if (handler != null) + { handler(this, e); } } - - + + [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] // - protected virtual void OnSelectedObjectsChanged(EventArgs e) { + protected virtual void OnSelectedObjectsChanged(EventArgs e) + { EventHandler handler = (EventHandler)Events[EventSelectedObjectsChanged]; - if (handler != null) { + if (handler != null) + { handler(this, e); } } - private void OnTransactionClosed(object sender, DesignerTransactionCloseEventArgs e) { - if (e.LastTransaction) { + private void OnTransactionClosed(object sender, DesignerTransactionCloseEventArgs e) + { + if (e.LastTransaction) + { // We should not refresh the grid if the selectedObject is no longer sited. IComponent currentSelection = SelectedObject as IComponent; if (currentSelection != null) @@ -3111,35 +3669,45 @@ private void OnTransactionClosed(object sender, DesignerTransactionCloseEventArg } } SetFlag(BatchMode, false); - if (GetFlag(FullRefreshAfterBatch)) { + if (GetFlag(FullRefreshAfterBatch)) + { this.SelectedObjects = currentObjects; SetFlag(FullRefreshAfterBatch, false); } - else if (GetFlag(BatchModeChange)){ + else if (GetFlag(BatchModeChange)) + { Refresh(false); } SetFlag(BatchModeChange, false); } } - - private void OnTransactionOpened(object sender, EventArgs e) { + + private void OnTransactionOpened(object sender, EventArgs e) + { SetFlag(BatchMode, true); } - private void OnTypeDescriptorRefreshed(RefreshEventArgs e) { - if (InvokeRequired) { + private void OnTypeDescriptorRefreshed(RefreshEventArgs e) + { + if (InvokeRequired) + { BeginInvoke(new RefreshEventHandler(this.OnTypeDescriptorRefreshedInvoke), new object[] { e }); } - else { + else + { OnTypeDescriptorRefreshedInvoke(e); } } - private void OnTypeDescriptorRefreshedInvoke(RefreshEventArgs e) { - if (currentObjects != null) { - for (int i = 0; i < currentObjects.Length; i++) { + private void OnTypeDescriptorRefreshedInvoke(RefreshEventArgs e) + { + if (currentObjects != null) + { + for (int i = 0; i < currentObjects.Length; i++) + { Type typeChanged = e.TypeChanged; - if (currentObjects[i] == e.ComponentChanged || typeChanged != null && typeChanged.IsAssignableFrom(currentObjects[i].GetType())) { + if (currentObjects[i] == e.ComponentChanged || typeChanged != null && typeChanged.IsAssignableFrom(currentObjects[i].GetType())) + { // clear our property hashes ClearCachedProps(); Refresh(true); @@ -3148,76 +3716,88 @@ private void OnTypeDescriptorRefreshedInvoke(RefreshEventArgs e) { } } } - - private void OnViewSortButtonClick(object sender, EventArgs e) { - try { - - this.FreezePainting = true; - - // is this tab selected? If so, do nothing. - if (sender == viewSortButtons[selectedViewSort]) { - viewSortButtons[selectedViewSort].Checked = true; - return; - } - - // check new button and uncheck old button. - viewSortButtons[selectedViewSort].Checked = false; - - // find the new button in the list - int index = 0; - for (index = 0; index < viewSortButtons.Length; index++) { - if (viewSortButtons[index] == sender) { - break; - } - } - - selectedViewSort = index; - viewSortButtons[selectedViewSort].Checked = true; - - switch (selectedViewSort) { - case ALPHA: - propertySortValue = PropertySort.Alphabetical; - break; - case CATEGORIES: - propertySortValue = PropertySort.Alphabetical | PropertySort.Categorized; - break; - case NO_SORT: - propertySortValue = PropertySort.NoSort; - break; - } - - OnPropertySortChanged(EventArgs.Empty); - - Refresh(false); - OnLayoutInternal(false); - } - finally { - this.FreezePainting = false; + + private void OnViewSortButtonClick(object sender, EventArgs e) + { + try + { + + this.FreezePainting = true; + + // is this tab selected? If so, do nothing. + if (sender == viewSortButtons[selectedViewSort]) + { + viewSortButtons[selectedViewSort].Checked = true; + return; + } + + // check new button and uncheck old button. + viewSortButtons[selectedViewSort].Checked = false; + + // find the new button in the list + int index = 0; + for (index = 0; index < viewSortButtons.Length; index++) + { + if (viewSortButtons[index] == sender) + { + break; + } + } + + selectedViewSort = index; + viewSortButtons[selectedViewSort].Checked = true; + + switch (selectedViewSort) + { + case ALPHA: + propertySortValue = PropertySort.Alphabetical; + break; + case CATEGORIES: + propertySortValue = PropertySort.Alphabetical | PropertySort.Categorized; + break; + case NO_SORT: + propertySortValue = PropertySort.NoSort; + break; + } + + OnPropertySortChanged(EventArgs.Empty); + + Refresh(false); + OnLayoutInternal(false); + } + finally + { + this.FreezePainting = false; } OnButtonClick(sender, e); - + } - private void OnViewTabButtonClick(object sender, EventArgs e) { - try { - - this.FreezePainting = true; - SelectViewTabButton((ToolStripButton)sender, true); - OnLayoutInternal(false); - SaveTabSelection(); + private void OnViewTabButtonClick(object sender, EventArgs e) + { + try + { + + this.FreezePainting = true; + SelectViewTabButton((ToolStripButton)sender, true); + OnLayoutInternal(false); + SaveTabSelection(); } - finally { - this.FreezePainting = false; + finally + { + this.FreezePainting = false; } OnButtonClick(sender, e); - + } - private void OnViewButtonClickPP(object sender, EventArgs e) { + private void OnViewButtonClickPP(object sender, EventArgs e) + { if (btnViewPropertyPages.Enabled && currentObjects != null && - currentObjects.Length > 0) { + currentObjects.Length > 0) + { object baseObject = currentObjects[0]; object obj = baseObject; @@ -3225,53 +3805,70 @@ private void OnViewButtonClickPP(object sender, EventArgs e) { IUIService uiSvc = (IUIService)GetService(typeof(IUIService)); - try { - if (uiSvc != null) { + try + { + if (uiSvc != null) + { success = uiSvc.ShowComponentEditor(obj, this); } - else { - try { + else + { + try + { ComponentEditor editor = (ComponentEditor)TypeDescriptor.GetEditor(obj, typeof(ComponentEditor)); - if (editor != null) { - if (editor is WindowsFormsComponentEditor) { + if (editor != null) + { + if (editor is WindowsFormsComponentEditor) + { success = ((WindowsFormsComponentEditor)editor).EditComponent(null, obj, (IWin32Window)this); } - else { + else + { success = editor.EditComponent(obj); } } } - catch { + catch + { } } - if (success) { + if (success) + { if (baseObject is IComponent && - connectionPointCookies[0] == null) { + connectionPointCookies[0] == null) + { ISite site = ((IComponent)baseObject).Site; - if (site != null) { + if (site != null) + { IComponentChangeService changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); - if (changeService != null) { - try { + if (changeService != null) + { + try + { changeService.OnComponentChanging(baseObject, null); } - catch (CheckoutException coEx) { - if (coEx == CheckoutException.Canceled) { + catch (CheckoutException coEx) + { + if (coEx == CheckoutException.Canceled) + { return; } throw coEx; } - try { + try + { // Now notify the change service that the change was successful. // SetFlag(InternalChange, true); changeService.OnComponentChanged(baseObject, null, null, null); } - finally { + finally + { SetFlag(InternalChange, false); } @@ -3298,13 +3895,15 @@ private void OnViewButtonClickPP(object sender, EventArgs e) { } OnButtonClick(sender, e); } - - + + [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] // - protected override void OnVisibleChanged(EventArgs e) { + protected override void OnVisibleChanged(EventArgs e) + { base.OnVisibleChanged(e); - if (Visible && IsHandleCreated) { + if (Visible && IsHandleCreated) + { OnLayoutInternal(false); SetupToolbar(); } @@ -3404,112 +4003,141 @@ private Control LastFocusableChild { */ - + /// /// Returns the last child control that can take focus /// protected override bool ProcessDialogKey(Keys keyData) { - switch (keyData & Keys.KeyCode) { + switch (keyData & Keys.KeyCode) + { case Keys.Tab: - if (((keyData & Keys.Control) != 0) || - ((keyData & Keys.Alt) != 0)) { + if (((keyData & Keys.Control) != 0) || + ((keyData & Keys.Alt) != 0)) + { break; - } - + } + // are we going forward? - if ((keyData & Keys.Shift) != 0) { + if ((keyData & Keys.Shift) != 0) + { // this is backward - if (hotcommands.Visible && hotcommands.ContainsFocus) { + if (hotcommands.Visible && hotcommands.ContainsFocus) + { gridView.ReverseFocus(); } - else if (gridView.FocusInside) { - if (toolStrip.Visible) { + else if (gridView.FocusInside) + { + if (toolStrip.Visible) + { toolStrip.Focus(); // we need to select first ToolStrip item, otherwise, ToolStrip container has the focus - if (toolStrip.Items.Count > 0) { + if (toolStrip.Items.Count > 0) + { toolStrip.SelectNextToolStripItem(null, /*forward =*/ true); } } - else { + else + { return base.ProcessDialogKey(keyData); } } - else { + else + { // if we get here and the toolbar has focus, // it means we're processing normally, so // pass the focus to the parent - if (toolStrip.Focused || !toolStrip.Visible) { + if (toolStrip.Focused || !toolStrip.Visible) + { return base.ProcessDialogKey(keyData); } - else { + else + { // otherwise, we're processing a message from elsewhere, // wo we select our bottom guy. - if (hotcommands.Visible) { + if (hotcommands.Visible) + { hotcommands.Select(false); } - else if (peMain != null) { + else if (peMain != null) + { gridView.ReverseFocus(); } - else if (toolStrip.Visible) { + else if (toolStrip.Visible) + { toolStrip.Focus(); } - else { + else + { return base.ProcessDialogKey(keyData); } } } return true; } - else { + else + { bool passToParent = false; // this is forward - if (toolStrip.Focused) { + if (toolStrip.Focused) + { // normal stuff, just do the propsheet - if (peMain != null) { + if (peMain != null) + { gridView.Focus(); } - else { + else + { base.ProcessDialogKey(keyData); } return true; } - else if (gridView.FocusInside) { - if (hotcommands.Visible) { + else if (gridView.FocusInside) + { + if (hotcommands.Visible) + { hotcommands.Select(true); return true; } - else { + else + { passToParent = true; } } - else if (hotcommands.ContainsFocus) { + else if (hotcommands.ContainsFocus) + { passToParent = true; } - else { + else + { // coming from out side, start with the toolStrip - if (toolStrip.Visible) { + if (toolStrip.Visible) + { toolStrip.Focus(); } - else { + else + { gridView.Focus(); } } // nobody's claimed the focus, pass it on... - if (passToParent) { + if (passToParent) + { // properties window is already selected // pass on to parent bool result = base.ProcessDialogKey(keyData); // if we're not hosted in a windows forms thing, just give the parent the focus - if (!result && this.Parent == null) { + if (!result && this.Parent == null) + { IntPtr hWndParent = UnsafeNativeMethods.GetParent(new HandleRef(this, Handle)); - if (hWndParent != IntPtr.Zero) { + if (hWndParent != IntPtr.Zero) + { UnsafeNativeMethods.SetFocus(new HandleRef(null, hWndParent)); } } @@ -3517,73 +4145,84 @@ protected override bool ProcessDialogKey(Keys keyData) } } return true; - /* This conflicts with VS tab linking - case Keys.Prior: // PAGE_UP - if ((keyData & Keys.Control) != 0) { - SelectPriorView(); - return true; - } - break; - case Keys.Next: //PAGE_DOWN - if ((keyData & Keys.Control) != 0) { - SelectNextView(); - return true; - } - break; - */ + /* This conflicts with VS tab linking + case Keys.Prior: // PAGE_UP + if ((keyData & Keys.Control) != 0) { + SelectPriorView(); + return true; + } + break; + case Keys.Next: //PAGE_DOWN + if ((keyData & Keys.Control) != 0) { + SelectNextView(); + return true; + } + break; + */ } return base.ProcessDialogKey(keyData); } - public override void Refresh() { - if (GetFlag(RefreshingProperties)) { + public override void Refresh() + { + if (GetFlag(RefreshingProperties)) + { return; } Refresh(true); base.Refresh(); } - - - private void Refresh(bool clearCached) { - if (Disposing) { + + private void Refresh(bool clearCached) + { + + if (Disposing) + { return; } - - if (GetFlag(RefreshingProperties)) { + + if (GetFlag(RefreshingProperties)) + { return; } - try { - this.FreezePainting = true; - SetFlag(RefreshingProperties, true); - - if (clearCached) { - ClearCachedProps(); - } - RefreshProperties(clearCached); - gridView.Refresh(); - DisplayHotCommands(); - } - finally { - this.FreezePainting = false; - SetFlag(RefreshingProperties, false); - } - } - - internal void RefreshProperties(bool clearCached) { - + try + { + this.FreezePainting = true; + SetFlag(RefreshingProperties, true); + + if (clearCached) + { + ClearCachedProps(); + } + RefreshProperties(clearCached); + gridView.Refresh(); + DisplayHotCommands(); + } + finally + { + this.FreezePainting = false; + SetFlag(RefreshingProperties, false); + } + } + + internal void RefreshProperties(bool clearCached) + { + // Clear our current cache so we can do a full refresh. - if (clearCached && selectedViewTab != -1 && viewTabs != null) { - PropertyTab tab = viewTabs[selectedViewTab]; - if (tab != null && viewTabProps != null) { - string tabName = tab.TabName + propertySortValue.ToString(); - viewTabProps.Remove(tabName); - } - } - + if (clearCached && selectedViewTab != -1 && viewTabs != null) + { + PropertyTab tab = viewTabs[selectedViewTab]; + if (tab != null && viewTabProps != null) + { + string tabName = tab.TabName + propertySortValue.ToString(); + viewTabProps.Remove(tabName); + } + } + SetFlag(PropertiesChanged, true); UpdateSelection(); } @@ -3593,22 +4232,28 @@ internal void RefreshProperties(bool clearCached) { /// Refreshes the tabs of the given scope by deleting them and requerying objects and documents /// for them. /// - public void RefreshTabs(PropertyTabScope tabScope) { - - if (tabScope < PropertyTabScope.Document) { + public void RefreshTabs(PropertyTabScope tabScope) + { + + if (tabScope < PropertyTabScope.Document) + { throw new ArgumentException(SR.PropertyGridTabScope); } RemoveTabs(tabScope, false); // check the component level tabs - if (tabScope <= PropertyTabScope.Component) { - if (currentObjects != null && currentObjects.Length > 0) { + if (tabScope <= PropertyTabScope.Component) + { + if (currentObjects != null && currentObjects.Length > 0) + { // get the subset of PropertyTabs that's common to all objects Type[] tabTypes = GetCommonTabs(currentObjects, PropertyTabScope.Component); - for (int i = 0; i < tabTypes.Length; i++) { - for (int j = 0; j < currentObjects.Length; j++) { + for (int i = 0; i < tabTypes.Length; i++) + { + for (int j = 0; j < currentObjects.Length; j++) + { AddRefTab(tabTypes[i], currentObjects[j], PropertyTabScope.Component, false); } } @@ -3616,17 +4261,24 @@ public void RefreshTabs(PropertyTabScope tabScope) { } // check the document level tabs - if (tabScope <= PropertyTabScope.Document && designerHost != null) { + if (tabScope <= PropertyTabScope.Document && designerHost != null) + { IContainer container = designerHost.Container; - if (container != null) { + if (container != null) + { ComponentCollection components = container.Components; - if (components != null) { - foreach (IComponent comp in components) { - PropertyTabAttribute attribute = (PropertyTabAttribute) TypeDescriptor.GetAttributes(comp.GetType())[typeof(PropertyTabAttribute)]; + if (components != null) + { + foreach (IComponent comp in components) + { + PropertyTabAttribute attribute = (PropertyTabAttribute)TypeDescriptor.GetAttributes(comp.GetType())[typeof(PropertyTabAttribute)]; - if (attribute != null) { - for (int j = 0; j < attribute.TabClasses.Length; j++) { - if (attribute.TabScopes[j] == PropertyTabScope.Document) { + if (attribute != null) + { + for (int j = 0; j < attribute.TabClasses.Length; j++) + { + if (attribute.TabScopes[j] == PropertyTabScope.Document) + { AddRefTab(attribute.TabClasses[j], comp, PropertyTabScope.Document, false); } } @@ -3639,30 +4291,36 @@ public void RefreshTabs(PropertyTabScope tabScope) { SetupToolbar(); } - internal void ReleaseTab(Type tabType, object component) { + internal void ReleaseTab(Type tabType, object component) + { PropertyTab tab = null; int tabIndex = -1; - for (int i = 0; i < viewTabs.Length; i++) { - if (tabType == viewTabs[i].GetType()) { + for (int i = 0; i < viewTabs.Length; i++) + { + if (tabType == viewTabs[i].GetType()) + { tab = viewTabs[i]; tabIndex = i; break; } } - if (tab == null) { + if (tab == null) + { return; } object[] components = tab.Components; bool killTab = false; - try { + try + { int index = -1; if (components != null) index = Array.IndexOf(components, component); - if (index >= 0) { + if (index >= 0) + { object[] newComponents = new object[components.Length - 1]; Array.Copy(components, 0, newComponents, 0, index); Array.Copy(components, index + 1, newComponents, index, components.Length - index - 1); @@ -3678,43 +4336,53 @@ internal void ReleaseTab(Type tabType, object component) { } // we don't remove PropertyTabScope.Global tabs here. Our owner has to do that. - if (killTab && viewTabScopes[tabIndex] > PropertyTabScope.Global) { + if (killTab && viewTabScopes[tabIndex] > PropertyTabScope.Global) + { RemoveTab(tabIndex, false); } } - private void RemoveImage(int index) { + private void RemoveImage(int index) + { imageList[NORMAL_BUTTONS].Images.RemoveAt(index); - if (imageList[LARGE_BUTTONS] != null) { + if (imageList[LARGE_BUTTONS] != null) + { imageList[LARGE_BUTTONS].Images.RemoveAt(index); } } // removes all the tabs with a classification greater than or equal to the specified classification. // for example, removing PropertyTabScope.Document will remove PropertyTabScope.Document and PropertyTabScope.Component tabs - internal void RemoveTabs(PropertyTabScope classification, bool setupToolbar) { - if (classification == PropertyTabScope.Static) { + internal void RemoveTabs(PropertyTabScope classification, bool setupToolbar) + { + if (classification == PropertyTabScope.Static) + { throw new ArgumentException(SR.PropertyGridRemoveStaticTabs); } - + // in case we've been disposed - if (viewTabButtons == null || viewTabs == null || viewTabScopes == null) { + if (viewTabButtons == null || viewTabs == null || viewTabScopes == null) + { return; } - ToolStripButton selectedButton = (selectedViewTab >=0 && selectedViewTab < viewTabButtons.Length ? viewTabButtons[selectedViewTab] : null); + ToolStripButton selectedButton = (selectedViewTab >= 0 && selectedViewTab < viewTabButtons.Length ? viewTabButtons[selectedViewTab] : null); - for (int i = viewTabs.Length-1; i >= 0; i--) { - if (viewTabScopes[i] >= classification) { + for (int i = viewTabs.Length - 1; i >= 0; i--) + { + if (viewTabScopes[i] >= classification) + { // adjust the selected view tab because we're deleting. - if (selectedViewTab == i) { + if (selectedViewTab == i) + { selectedViewTab = -1; } - else if (selectedViewTab > i) { + else if (selectedViewTab > i) + { selectedViewTab--; } - + PropertyTab[] newTabs = new PropertyTab[viewTabs.Length - 1]; Array.Copy(viewTabs, 0, newTabs, 0, i); Array.Copy(viewTabs, i + 1, newTabs, i, viewTabs.Length - i - 1); @@ -3729,7 +4397,8 @@ internal void RemoveTabs(PropertyTabScope classification, bool setupToolbar) { } } - if (setupToolbar && viewTabsDirty) { + if (setupToolbar && viewTabsDirty) + { SetupToolbar(); Debug.Assert(viewTabs != null && viewTabs.Length > 0, "Holy Moly! We don't have any tabs left!"); @@ -3738,35 +4407,42 @@ internal void RemoveTabs(PropertyTabScope classification, bool setupToolbar) { SelectViewTabButtonDefault(selectedButton); // clear the component refs of the tabs - for (int i = 0; i < viewTabs.Length; i++) { + for (int i = 0; i < viewTabs.Length; i++) + { viewTabs[i].Components = new object[0]; } } } - internal void RemoveTab(int tabIndex, bool setupToolbar) { + internal void RemoveTab(int tabIndex, bool setupToolbar) + { Debug.Assert(viewTabs != null, "Tab array destroyed!"); - if (tabIndex >= viewTabs.Length || tabIndex < 0) { + if (tabIndex >= viewTabs.Length || tabIndex < 0) + { throw new ArgumentOutOfRangeException(nameof(tabIndex), SR.PropertyGridBadTabIndex); } - if (viewTabScopes[tabIndex] == PropertyTabScope.Static) { + if (viewTabScopes[tabIndex] == PropertyTabScope.Static) + { throw new ArgumentException(SR.PropertyGridRemoveStaticTabs); } - if (selectedViewTab == tabIndex) { + if (selectedViewTab == tabIndex) + { selectedViewTab = PROPERTIES; } - + // Remove this tab from our "last selected" group // - if (!GetFlag(ReInitTab) && ActiveDesigner != null) { - int hashCode = ActiveDesigner.GetHashCode(); - if (designerSelections != null && designerSelections.ContainsKey(hashCode) && (int)designerSelections[hashCode] == tabIndex) { - designerSelections.Remove(hashCode); - } + if (!GetFlag(ReInitTab) && ActiveDesigner != null) + { + int hashCode = ActiveDesigner.GetHashCode(); + if (designerSelections != null && designerSelections.ContainsKey(hashCode) && (int)designerSelections[hashCode] == tabIndex) + { + designerSelections.Remove(hashCode); + } } ToolStripButton selectedButton = viewTabButtons[selectedViewTab]; @@ -3783,18 +4459,22 @@ internal void RemoveTab(int tabIndex, bool setupToolbar) { viewTabsDirty = true; - if (setupToolbar) { + if (setupToolbar) + { SetupToolbar(); selectedViewTab = -1; SelectViewTabButtonDefault(selectedButton); } } - internal void RemoveTab(Type tabType) { + internal void RemoveTab(Type tabType) + { PropertyTab tab = null; int tabIndex = -1; - for (int i = 0; i < viewTabs.Length; i++) { - if (tabType == viewTabs[i].GetType()) { + for (int i = 0; i < viewTabs.Length; i++) + { + if (tabType == viewTabs[i].GetType()) + { tab = viewTabs[i]; tabIndex = i; break; @@ -3802,7 +4482,8 @@ internal void RemoveTab(Type tabType) { } // just quit if the tab isn't present. - if (tabIndex == -1) { + if (tabIndex == -1) + { return; } @@ -3815,36 +4496,43 @@ internal void RemoveTab(Type tabType) { Array.Copy(viewTabScopes, 0, newTabScopes, 0, tabIndex); Array.Copy(viewTabScopes, tabIndex + 1, newTabScopes, tabIndex, viewTabScopes.Length - tabIndex - 1); viewTabScopes = newTabScopes; - + viewTabsDirty = true; SetupToolbar(); } - private void ResetCommandsBackColor() { + private void ResetCommandsBackColor() + { hotcommands.ResetBackColor(); } - private void ResetCommandsForeColor() { + private void ResetCommandsForeColor() + { hotcommands.ResetForeColor(); } - private void ResetCommandsLinkColor() { + private void ResetCommandsLinkColor() + { hotcommands.Label.ResetLinkColor(); } - private void ResetCommandsActiveLinkColor() { + private void ResetCommandsActiveLinkColor() + { hotcommands.Label.ResetActiveLinkColor(); } - private void ResetCommandsDisabledLinkColor() { + private void ResetCommandsDisabledLinkColor() + { hotcommands.Label.ResetDisabledLinkColor(); } - private void ResetHelpBackColor() { + private void ResetHelpBackColor() + { doccomment.ResetBackColor(); } - private void ResetHelpForeColor() { + private void ResetHelpForeColor() + { doccomment.ResetBackColor(); } @@ -3852,11 +4540,14 @@ private void ResetHelpForeColor() { // another object of the same exact type. Scenario: An immutable root object being // replaced with a new instance because one of its properties was changed by the user. // - internal void ReplaceSelectedObject(object oldObject, object newObject) { + internal void ReplaceSelectedObject(object oldObject, object newObject) + { Debug.Assert(oldObject != null && newObject != null && oldObject.GetType() == newObject.GetType()); - for (int i = 0; i < currentObjects.Length; ++i) { - if (currentObjects[i] == oldObject) { + for (int i = 0; i < currentObjects.Length; ++i) + { + if (currentObjects[i] == oldObject) + { currentObjects[i] = newObject; Refresh(true); break; @@ -3864,113 +4555,137 @@ internal void ReplaceSelectedObject(object oldObject, object newObject) { } } - public void ResetSelectedProperty() { + public void ResetSelectedProperty() + { GetPropertyGridView().Reset(); } - private void SaveTabSelection() { - if (designerHost != null) { - if (designerSelections == null) { - designerSelections = new Hashtable(); - } - designerSelections[designerHost.GetHashCode()] = selectedViewTab; + private void SaveTabSelection() + { + if (designerHost != null) + { + if (designerSelections == null) + { + designerSelections = new Hashtable(); + } + designerSelections[designerHost.GetHashCode()] = selectedViewTab; } } - - void IComPropertyBrowser.SaveState(RegistryKey optRoot) { - if (optRoot == null) { + void IComPropertyBrowser.SaveState(RegistryKey optRoot) + { + + if (optRoot == null) + { return; } - + optRoot.SetValue("PbrsAlpha", (this.PropertySort == PropertySort.Alphabetical ? "1" : "0")); optRoot.SetValue("PbrsShowDesc", (this.HelpVisible ? "1" : "0")); optRoot.SetValue("PbrsShowCommands", (this.CommandsVisibleIfAvailable ? "1" : "0")); optRoot.SetValue("PbrsDescHeightRatio", dcSizeRatio.ToString(CultureInfo.InvariantCulture)); optRoot.SetValue("PbrsHotCommandHeightRatio", hcSizeRatio.ToString(CultureInfo.InvariantCulture)); - } - - void SetHotCommandColors(bool vscompat) { - if (vscompat) { + } + + void SetHotCommandColors(bool vscompat) + { + if (vscompat) + { hotcommands.SetColors(SystemColors.Control, SystemColors.ControlText, SystemColors.ActiveCaption, SystemColors.ActiveCaption, SystemColors.ActiveCaption, SystemColors.ControlDark); } - else { + else + { hotcommands.SetColors(SystemColors.Control, SystemColors.ControlText, Color.Empty, Color.Empty, Color.Empty, Color.Empty); } } - internal void SetStatusBox(string title,string desc) { - doccomment.SetComment(title,desc); + internal void SetStatusBox(string title, string desc) + { + doccomment.SetComment(title, desc); } - private void SelectViewTabButton(ToolStripButton button, bool updateSelection) { - - Debug.Assert(viewTabButtons != null, "No view tab buttons to select!"); - - int oldTab = selectedViewTab; - - if (!SelectViewTabButtonDefault(button)) { - Debug.Fail("Failed to find the tab!"); - } - - if (updateSelection) { - Refresh(false); - } + private void SelectViewTabButton(ToolStripButton button, bool updateSelection) + { + + Debug.Assert(viewTabButtons != null, "No view tab buttons to select!"); + + int oldTab = selectedViewTab; + + if (!SelectViewTabButtonDefault(button)) + { + Debug.Fail("Failed to find the tab!"); + } + + if (updateSelection) + { + Refresh(false); + } } - private bool SelectViewTabButtonDefault(ToolStripButton button) { - // make sure our selection number is valid - if (selectedViewTab >= 0 && selectedViewTab >= viewTabButtons.Length) { - selectedViewTab = -1; - } - - // is this tab button checked? If so, do nothing. - if (selectedViewTab >=0 && selectedViewTab < viewTabButtons.Length && - button == viewTabButtons[selectedViewTab]) { - viewTabButtons[selectedViewTab].Checked = true; - return true; - } - - PropertyTab oldTab = null; - - // unselect what's selected - if (selectedViewTab != -1) { - viewTabButtons[selectedViewTab].Checked = false; - oldTab = viewTabs[selectedViewTab]; - } - - // get the new index of the button - for (int i = 0; i < viewTabButtons.Length; i++) { - if (viewTabButtons[i] == button) { - selectedViewTab = i; - viewTabButtons[i].Checked = true; - try { - SetFlag(TabsChanging, true); - OnPropertyTabChanged(new PropertyTabChangedEventArgs(oldTab, viewTabs[i])); - } - finally { - SetFlag(TabsChanging, false); - } - return true; + private bool SelectViewTabButtonDefault(ToolStripButton button) + { + // make sure our selection number is valid + if (selectedViewTab >= 0 && selectedViewTab >= viewTabButtons.Length) + { + selectedViewTab = -1; + } + + // is this tab button checked? If so, do nothing. + if (selectedViewTab >= 0 && selectedViewTab < viewTabButtons.Length && + button == viewTabButtons[selectedViewTab]) + { + viewTabButtons[selectedViewTab].Checked = true; + return true; + } + + PropertyTab oldTab = null; + + // unselect what's selected + if (selectedViewTab != -1) + { + viewTabButtons[selectedViewTab].Checked = false; + oldTab = viewTabs[selectedViewTab]; + } + + // get the new index of the button + for (int i = 0; i < viewTabButtons.Length; i++) + { + if (viewTabButtons[i] == button) + { + selectedViewTab = i; + viewTabButtons[i].Checked = true; + try + { + SetFlag(TabsChanging, true); + OnPropertyTabChanged(new PropertyTabChangedEventArgs(oldTab, viewTabs[i])); } + finally + { + SetFlag(TabsChanging, false); + } + return true; } - - // select the first tab if we didn't find that one. - selectedViewTab = PROPERTIES; - Debug.Assert(viewTabs[PROPERTIES].GetType() == DefaultTabType, "First item is not property tab!"); - SelectViewTabButton(viewTabButtons[PROPERTIES], false); - return false; + } + + // select the first tab if we didn't find that one. + selectedViewTab = PROPERTIES; + Debug.Assert(viewTabs[PROPERTIES].GetType() == DefaultTabType, "First item is not property tab!"); + SelectViewTabButton(viewTabButtons[PROPERTIES], false); + return false; } - - private void SetSelectState(int state) { - - - if (state >= (viewTabs.Length * viewSortButtons.Length)) { + + private void SetSelectState(int state) + { + + + if (state >= (viewTabs.Length * viewSortButtons.Length)) + { state = 0; } - else if (state < 0) { + else if (state < 0) + { state = (viewTabs.Length * viewSortButtons.Length) - 1; } @@ -3985,229 +4700,270 @@ private void SetSelectState(int state) { // state -> view = state % views int viewTypes = viewSortButtons.Length; - - if (viewTypes > 0) { - + + if (viewTypes > 0) + { + int tab = state / viewTypes; int view = state % viewTypes; - + Debug.Assert(view < viewSortButtons.Length, "Can't select view type > 1"); - + OnViewTabButtonClick(viewTabButtons[tab], EventArgs.Empty); OnViewSortButtonClick(viewSortButtons[view], EventArgs.Empty); } } - private void SetToolStripRenderer() { - if (DrawFlatToolbar || SystemInformation.HighContrast) { + private void SetToolStripRenderer() + { + if (DrawFlatToolbar || SystemInformation.HighContrast) + { // use an office look and feel with system colors ProfessionalColorTable colorTable = new ProfessionalColorTable(); colorTable.UseSystemColors = true; ToolStripRenderer = new ToolStripProfessionalRenderer(colorTable); } - else { + else + { ToolStripRenderer = new ToolStripSystemRenderer(); } } - - - private void SetupToolbar() { + + + private void SetupToolbar() + { SetupToolbar(false); } - private void SetupToolbar(bool fullRebuild) { + private void SetupToolbar(bool fullRebuild) + { // if the tab array hasn't changed, don't bother to do all // this work. // - if (!viewTabsDirty && !fullRebuild) { + if (!viewTabsDirty && !fullRebuild) + { return; } - - try { - this.FreezePainting = true; - - - if (imageList[NORMAL_BUTTONS] == null || fullRebuild) { - imageList[NORMAL_BUTTONS] = new ImageList(); - if (DpiHelper.IsScalingRequired) { - imageList[NORMAL_BUTTONS].ImageSize = normalButtonSize; - } - } - - // setup our event handlers - EventHandler ehViewTab = new EventHandler(this.OnViewTabButtonClick); - EventHandler ehViewType = new EventHandler(this.OnViewSortButtonClick); - EventHandler ehPP = new EventHandler(this.OnViewButtonClickPP); - - Bitmap b; - int i; - - - // we manange the buttons as a seperate list so the toobar doesn't flash - ArrayList buttonList; - - if (fullRebuild) { - buttonList = new ArrayList(); - } - else { - buttonList = new ArrayList(toolStrip.Items); - } - - // setup the view type buttons. We only need to do this once - if (viewSortButtons == null || fullRebuild) { - viewSortButtons = new ToolStripButton[3]; - - int alphaIndex = -1; - int categoryIndex = -1; - - try { - if (bmpAlpha == null) { - bmpAlpha = SortByPropertyImage; - } - alphaIndex = AddImage(bmpAlpha); - } - catch (Exception) { - } - - try { - if (bmpCategory == null) { - bmpCategory = SortByCategoryImage; - } - categoryIndex = AddImage(bmpCategory); - } - catch (Exception) { - } - - viewSortButtons[ALPHA] = CreatePushButton(SR.PBRSToolTipAlphabetic, alphaIndex, ehViewType, true); - viewSortButtons[CATEGORIES] = CreatePushButton(SR.PBRSToolTipCategorized, categoryIndex, ehViewType, true); - - // we create a dummy hidden button for view sort - viewSortButtons[NO_SORT] = CreatePushButton("", 0, ehViewType, true); - viewSortButtons[NO_SORT].Visible = false; - - // add the viewType buttons and a separator - for (i = 0; i < viewSortButtons.Length; i++) { - buttonList.Add(viewSortButtons[i]); - } - } - else { - // clear all the items from the toolStrip and image list after the first two - int items = buttonList.Count; - - for (i = items-1; i >= 2; i--) { - buttonList.RemoveAt(i); - } - - items = imageList[NORMAL_BUTTONS].Images.Count; - - for (i = items-1; i >= 2; i--) { - RemoveImage(i); - } - } - - buttonList.Add(separator1); - - // here's our buttons array - viewTabButtons = new ToolStripButton[viewTabs.Length]; - bool doAdd = viewTabs.Length > 1; - - // if we've only got the properties tab, don't add - // the button (or we'll just have a properties button that you can't do anything with) - // setup the view tab buttons - for (i = 0; i < viewTabs.Length; i++) { - try { - b = viewTabs[i].Bitmap; - viewTabButtons[i] = CreatePushButton(viewTabs[i].TabName, AddImage(b), ehViewTab, true); - if (doAdd) { - buttonList.Add(viewTabButtons[i]); - } - } - catch (Exception ex) { - Debug.Fail(ex.ToString()); - } - } - - // if we didn't add anything, we don't need another separator either. - if (doAdd) { - buttonList.Add(separator2); - } - - // add the design page button - int designpg = 0; - - try { - if (bmpPropPage == null) { - bmpPropPage = ShowPropertyPageImage; - } - designpg = AddImage(bmpPropPage); - } - catch (Exception) { - } - - // we recreate this every time to ensure it's at the end - // - btnViewPropertyPages = CreatePushButton(SR.PBRSToolTipPropertyPages, designpg, ehPP, false); - btnViewPropertyPages.Enabled = false; - buttonList.Add(btnViewPropertyPages); - - // Dispose this so it will get recreated for any new buttons. - if (imageList[LARGE_BUTTONS] != null) { - imageList[LARGE_BUTTONS].Dispose(); - imageList[LARGE_BUTTONS] = null; - } - - if (buttonType != NORMAL_BUTTONS) { - EnsureLargeButtons(); - } - - toolStrip.ImageList = imageList[this.buttonType]; - - toolStrip.SuspendLayout(); - toolStrip.Items.Clear(); - for (int j = 0; j < buttonList.Count; j++) { + + try + { + this.FreezePainting = true; + + + if (imageList[NORMAL_BUTTONS] == null || fullRebuild) + { + imageList[NORMAL_BUTTONS] = new ImageList(); + if (DpiHelper.IsScalingRequired) + { + imageList[NORMAL_BUTTONS].ImageSize = normalButtonSize; + } + } + + // setup our event handlers + EventHandler ehViewTab = new EventHandler(this.OnViewTabButtonClick); + EventHandler ehViewType = new EventHandler(this.OnViewSortButtonClick); + EventHandler ehPP = new EventHandler(this.OnViewButtonClickPP); + + Bitmap b; + int i; + + + // we manange the buttons as a seperate list so the toobar doesn't flash + ArrayList buttonList; + + if (fullRebuild) + { + buttonList = new ArrayList(); + } + else + { + buttonList = new ArrayList(toolStrip.Items); + } + + // setup the view type buttons. We only need to do this once + if (viewSortButtons == null || fullRebuild) + { + viewSortButtons = new ToolStripButton[3]; + + int alphaIndex = -1; + int categoryIndex = -1; + + try + { + if (bmpAlpha == null) + { + bmpAlpha = SortByPropertyImage; + } + alphaIndex = AddImage(bmpAlpha); + } + catch (Exception) + { + } + + try + { + if (bmpCategory == null) + { + bmpCategory = SortByCategoryImage; + } + categoryIndex = AddImage(bmpCategory); + } + catch (Exception) + { + } + + viewSortButtons[ALPHA] = CreatePushButton(SR.PBRSToolTipAlphabetic, alphaIndex, ehViewType, true); + viewSortButtons[CATEGORIES] = CreatePushButton(SR.PBRSToolTipCategorized, categoryIndex, ehViewType, true); + + // we create a dummy hidden button for view sort + viewSortButtons[NO_SORT] = CreatePushButton("", 0, ehViewType, true); + viewSortButtons[NO_SORT].Visible = false; + + // add the viewType buttons and a separator + for (i = 0; i < viewSortButtons.Length; i++) + { + buttonList.Add(viewSortButtons[i]); + } + } + else + { + // clear all the items from the toolStrip and image list after the first two + int items = buttonList.Count; + + for (i = items - 1; i >= 2; i--) + { + buttonList.RemoveAt(i); + } + + items = imageList[NORMAL_BUTTONS].Images.Count; + + for (i = items - 1; i >= 2; i--) + { + RemoveImage(i); + } + } + + buttonList.Add(separator1); + + // here's our buttons array + viewTabButtons = new ToolStripButton[viewTabs.Length]; + bool doAdd = viewTabs.Length > 1; + + // if we've only got the properties tab, don't add + // the button (or we'll just have a properties button that you can't do anything with) + // setup the view tab buttons + for (i = 0; i < viewTabs.Length; i++) + { + try + { + b = viewTabs[i].Bitmap; + viewTabButtons[i] = CreatePushButton(viewTabs[i].TabName, AddImage(b), ehViewTab, true); + if (doAdd) + { + buttonList.Add(viewTabButtons[i]); + } + } + catch (Exception ex) + { + Debug.Fail(ex.ToString()); + } + } + + // if we didn't add anything, we don't need another separator either. + if (doAdd) + { + buttonList.Add(separator2); + } + + // add the design page button + int designpg = 0; + + try + { + if (bmpPropPage == null) + { + bmpPropPage = ShowPropertyPageImage; + } + designpg = AddImage(bmpPropPage); + } + catch (Exception) + { + } + + // we recreate this every time to ensure it's at the end + // + btnViewPropertyPages = CreatePushButton(SR.PBRSToolTipPropertyPages, designpg, ehPP, false); + btnViewPropertyPages.Enabled = false; + buttonList.Add(btnViewPropertyPages); + + // Dispose this so it will get recreated for any new buttons. + if (imageList[LARGE_BUTTONS] != null) + { + imageList[LARGE_BUTTONS].Dispose(); + imageList[LARGE_BUTTONS] = null; + } + + if (buttonType != NORMAL_BUTTONS) + { + EnsureLargeButtons(); + } + + toolStrip.ImageList = imageList[this.buttonType]; + + toolStrip.SuspendLayout(); + toolStrip.Items.Clear(); + for (int j = 0; j < buttonList.Count; j++) + { toolStrip.Items.Add(buttonList[j] as ToolStripItem); - } - toolStrip.ResumeLayout(); - - if (viewTabsDirty) { - // if we're redoing our tabs make sure - // we setup the toolbar area correctly. - // - OnLayoutInternal(false); - } - - viewTabsDirty = false; - } - finally { - this.FreezePainting = false; - } - } - - protected void ShowEventsButton(bool value) { - if (viewTabs != null && viewTabs.Length > EVENTS && (viewTabs[EVENTS] is EventsTab)) { - + } + toolStrip.ResumeLayout(); + + if (viewTabsDirty) + { + // if we're redoing our tabs make sure + // we setup the toolbar area correctly. + // + OnLayoutInternal(false); + } + + viewTabsDirty = false; + } + finally + { + this.FreezePainting = false; + } + } + + protected void ShowEventsButton(bool value) + { + if (viewTabs != null && viewTabs.Length > EVENTS && (viewTabs[EVENTS] is EventsTab)) + { + Debug.Assert(viewTabButtons != null && viewTabButtons.Length > EVENTS && viewTabButtons[EVENTS] != null, "Events button is not at EVENTS position"); viewTabButtons[EVENTS].Visible = value; - if (!value && selectedViewTab == EVENTS) { + if (!value && selectedViewTab == EVENTS) + { SelectViewTabButton(viewTabButtons[PROPERTIES], true); } } - UpdatePropertiesViewTabVisibility(); + UpdatePropertiesViewTabVisibility(); } /// /// This 16x16 Bitmap is applied to the button which orders properties alphabetically. /// [ - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - protected virtual Bitmap SortByPropertyImage { - get { + protected virtual Bitmap SortByPropertyImage + { + get + { return DpiHelper.GetBitmapFromIcon(typeof(PropertyGrid), "PBAlpha"); } } @@ -4216,12 +4972,14 @@ protected virtual Bitmap SortByPropertyImage { /// This 16x16 Bitmap is applied to the button which displays properties under the assigned categories. /// [ - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - protected virtual Bitmap SortByCategoryImage { - get { + protected virtual Bitmap SortByCategoryImage + { + get + { return DpiHelper.GetBitmapFromIcon(typeof(PropertyGrid), "PBCatego"); } } @@ -4230,33 +4988,40 @@ protected virtual Bitmap SortByCategoryImage { /// This 16x16 Bitmap is applied to the button which displays property page in the designer pane. /// [ - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - protected virtual Bitmap ShowPropertyPageImage { - get { + protected virtual Bitmap ShowPropertyPageImage + { + get + { return DpiHelper.GetBitmapFromIcon(typeof(PropertyGrid), "PBPPage"); } } - private bool ShouldSerializeCommandsBackColor() { + private bool ShouldSerializeCommandsBackColor() + { return hotcommands.ShouldSerializeBackColor(); } - private bool ShouldSerializeCommandsForeColor() { + private bool ShouldSerializeCommandsForeColor() + { return hotcommands.ShouldSerializeForeColor(); } - private bool ShouldSerializeCommandsLinkColor() { + private bool ShouldSerializeCommandsLinkColor() + { return hotcommands.Label.ShouldSerializeLinkColor(); } - private bool ShouldSerializeCommandsActiveLinkColor() { + private bool ShouldSerializeCommandsActiveLinkColor() + { return hotcommands.Label.ShouldSerializeActiveLinkColor(); } - private bool ShouldSerializeCommandsDisabledLinkColor() { + private bool ShouldSerializeCommandsDisabledLinkColor() + { return hotcommands.Label.ShouldSerializeDisabledLinkColor(); } @@ -4266,46 +5031,57 @@ private bool ShouldSerializeCommandsDisabledLinkColor() { /// /// See IPropertyNotifySink /// - private void SinkPropertyNotifyEvents() { + private void SinkPropertyNotifyEvents() + { // first clear any existing sinks. - for (int i = 0;connectionPointCookies != null && i < connectionPointCookies.Length; i++) { - if (connectionPointCookies[i] != null) { + for (int i = 0; connectionPointCookies != null && i < connectionPointCookies.Length; i++) + { + if (connectionPointCookies[i] != null) + { connectionPointCookies[i].Disconnect(); connectionPointCookies[i] = null; } } - if (currentObjects == null || currentObjects.Length == 0) { + if (currentObjects == null || currentObjects.Length == 0) + { connectionPointCookies = null; return; } // it's okay if our array is too big...we'll just reuse it and ignore the empty slots. - if (connectionPointCookies == null || (currentObjects.Length > connectionPointCookies.Length)) { + if (connectionPointCookies == null || (currentObjects.Length > connectionPointCookies.Length)) + { connectionPointCookies = new AxHost.ConnectionPointCookie[currentObjects.Length]; } - - for (int i = 0; i < currentObjects.Length; i++) { - try { + + for (int i = 0; i < currentObjects.Length; i++) + { + try + { object obj = GetUnwrappedObject(i); - if (!Marshal.IsComObject(obj)) { + if (!Marshal.IsComObject(obj)) + { continue; } connectionPointCookies[i] = new AxHost.ConnectionPointCookie(obj, this, typeof(UnsafeNativeMethods.IPropertyNotifySink), /*throwException*/ false); } - catch { + catch + { // guess we failed eh? } } } - private bool ShouldForwardChildMouseMessage(Control child, MouseEventArgs me, ref Point pt) { + private bool ShouldForwardChildMouseMessage(Control child, MouseEventArgs me, ref Point pt) + { Size size = child.Size; // are we within two pixels of the edge? - if (me.Y <= 1 || (size.Height - me.Y) <= 1) { + if (me.Y <= 1 || (size.Height - me.Y) <= 1) + { // convert the coordinates to NativeMethods.POINT temp = new NativeMethods.POINT(); temp.x = me.X; @@ -4320,68 +5096,85 @@ private bool ShouldForwardChildMouseMessage(Control child, MouseEventArgs me, re return false; } - private void UpdatePropertiesViewTabVisibility() { + private void UpdatePropertiesViewTabVisibility() + { // If the only view available is properties-view, there's no need to show the button. // - if (viewTabButtons != null) { + if (viewTabButtons != null) + { int nOtherViewsVisible = 0; - for(int i=1; i < viewTabButtons.Length; i++) { // Starts at index 1, since index 0 is properties-view - if (viewTabButtons[i].Visible) { + for (int i = 1; i < viewTabButtons.Length; i++) + { // Starts at index 1, since index 0 is properties-view + if (viewTabButtons[i].Visible) + { nOtherViewsVisible++; } } - if (nOtherViewsVisible > 0) { + if (nOtherViewsVisible > 0) + { viewTabButtons[PROPERTIES].Visible = true; separator2.Visible = true; } - else { + else + { viewTabButtons[PROPERTIES].Visible = false; separator2.Visible = false; } } } - internal void UpdateSelection() { + internal void UpdateSelection() + { - if (!GetFlag(PropertiesChanged)) { + if (!GetFlag(PropertiesChanged)) + { return; } - - if (viewTabs == null) { + + if (viewTabs == null) + { return; } - + string tabName = viewTabs[selectedViewTab].TabName + propertySortValue.ToString(); - if (viewTabProps != null && viewTabProps.ContainsKey(tabName)) { - peMain = (GridEntry)viewTabProps[tabName]; - if (peMain != null) { - peMain.Refresh(); - } - } - else { - if (currentObjects != null && currentObjects.Length > 0) { - peMain = (GridEntry)GridEntry.Create(gridView, currentObjects, new PropertyGridServiceProvider(this), designerHost, this.SelectedTab, propertySortValue); - } - else { - peMain = null; - } - - if (peMain == null) { - currentPropEntries = new GridEntryCollection(null, new GridEntry[0]); - gridView.ClearProps(); - return; - } - - if (BrowsableAttributes != null) { - peMain.BrowsableAttributes = BrowsableAttributes; - } - - if (viewTabProps == null) { + if (viewTabProps != null && viewTabProps.ContainsKey(tabName)) + { + peMain = (GridEntry)viewTabProps[tabName]; + if (peMain != null) + { + peMain.Refresh(); + } + } + else + { + if (currentObjects != null && currentObjects.Length > 0) + { + peMain = (GridEntry)GridEntry.Create(gridView, currentObjects, new PropertyGridServiceProvider(this), designerHost, this.SelectedTab, propertySortValue); + } + else + { + peMain = null; + } + + if (peMain == null) + { + currentPropEntries = new GridEntryCollection(null, new GridEntry[0]); + gridView.ClearProps(); + return; + } + + if (BrowsableAttributes != null) + { + peMain.BrowsableAttributes = BrowsableAttributes; + } + + if (viewTabProps == null) + { viewTabProps = new Hashtable(); - } - - viewTabProps[tabName] = peMain; + } + + viewTabProps[tabName] = peMain; } // get entries. @@ -4398,11 +5191,14 @@ internal void UpdateSelection() { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.UseCompatibleTextRenderingDescr)) ] - public bool UseCompatibleTextRendering { - get{ + public bool UseCompatibleTextRendering + { + get + { return base.UseCompatibleTextRenderingInt; } - set{ + set + { base.UseCompatibleTextRenderingInt = value; doccomment.UpdateTextRenderingEngine(); gridView.Invalidate(); @@ -4420,53 +5216,63 @@ public bool UseCompatibleTextRendering { /// This is provided for container controls to iterate through its children to set UseCompatibleTextRendering to the same /// value if the child control supports it. /// - internal override bool SupportsUseCompatibleTextRendering { - get { + internal override bool SupportsUseCompatibleTextRendering + { + get + { return true; } } - internal override bool AllowsKeyboardToolTip() { + internal override bool AllowsKeyboardToolTip() + { return false; } // a mini version of process dialog key // for responding to WM_GETDLGCODE - internal bool WantsTab(bool forward) { - if (forward) { + internal bool WantsTab(bool forward) + { + if (forward) + { return toolStrip.Visible && toolStrip.Focused; } - else { + else + { return gridView.ContainsFocus && toolStrip.Visible; } } private string propName; - private int dwMsg; + private int dwMsg; - private void GetDataFromCopyData(IntPtr lparam) { + private void GetDataFromCopyData(IntPtr lparam) + { NativeMethods.COPYDATASTRUCT cds = Marshal.PtrToStructure(lparam); - if (cds != null && cds.lpData != IntPtr.Zero) { + if (cds != null && cds.lpData != IntPtr.Zero) + { propName = Marshal.PtrToStringAuto(cds.lpData); dwMsg = cds.dwData; } } - - + + [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] // - protected override void OnSystemColorsChanged(EventArgs e) { + protected override void OnSystemColorsChanged(EventArgs e) + { // refresh the toolbar buttons SetupToolbar(true); - + // this doesn't stick the first time we do it... // either probably a toolbar issue, maybe GDI+, so we call it again // fortunately this doesn't happen very often. // - if (!GetFlag(SysColorChangeRefresh)) { - SetupToolbar(true); - SetFlag(SysColorChangeRefresh, true); + if (!GetFlag(SysColorChangeRefresh)) + { + SetupToolbar(true); + SetFlag(SysColorChangeRefresh, true); } base.OnSystemColorsChanged(e); } @@ -4474,11 +5280,12 @@ protected override void OnSystemColorsChanged(EventArgs e) { /// /// Rescaling constants. /// - private void RescaleConstants() { + private void RescaleConstants() + { normalButtonSize = LogicalToDeviceUnits(DEFAULT_NORMAL_BUTTON_SIZE); largeButtonSize = LogicalToDeviceUnits(DEFAULT_LARGE_BUTTON_SIZE); cyDivider = LogicalToDeviceUnits(CYDIVIDER); - toolStripButtonPaddingY = LogicalToDeviceUnits(TOOLSTRIP_BUTTON_PADDING_Y); + toolStripButtonPaddingY = LogicalToDeviceUnits(TOOLSTRIP_BUTTON_PADDING_Y); } /// @@ -4486,69 +5293,85 @@ private void RescaleConstants() { /// /// old dpi /// new dpi - protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) { + protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) + { base.RescaleConstantsForDpi(deviceDpiOld, deviceDpiNew); RescaleConstants(); SetupToolbar(true); } - protected override void WndProc(ref Message m) { + protected override void WndProc(ref Message m) + { - switch (m.Msg) { + switch (m.Msg) + { case Interop.WindowMessages.WM_UNDO: - if ((long)m.LParam == 0) { + if ((long)m.LParam == 0) + { gridView.DoUndoCommand(); } - else { + else + { m.Result = CanUndo ? (IntPtr)1 : (IntPtr)0; } return; case Interop.WindowMessages.WM_CUT: - if ((long)m.LParam == 0) { + if ((long)m.LParam == 0) + { gridView.DoCutCommand(); } - else { + else + { m.Result = CanCut ? (IntPtr)1 : (IntPtr)0; } return; case Interop.WindowMessages.WM_COPY: - if ((long)m.LParam == 0) { + if ((long)m.LParam == 0) + { gridView.DoCopyCommand(); } - else { + else + { m.Result = CanCopy ? (IntPtr)1 : (IntPtr)0; } return; case Interop.WindowMessages.WM_PASTE: - if ((long)m.LParam == 0) { + if ((long)m.LParam == 0) + { gridView.DoPasteCommand(); } - else { + else + { m.Result = CanPaste ? (IntPtr)1 : (IntPtr)0; } return; - + case Interop.WindowMessages.WM_COPYDATA: GetDataFromCopyData(m.LParam); m.Result = (IntPtr)1; return; case AutomationMessages.PGM_GETBUTTONCOUNT: - if (toolStrip != null) { + if (toolStrip != null) + { m.Result = (IntPtr)toolStrip.Items.Count; return; } break; case AutomationMessages.PGM_GETBUTTONSTATE: - if (toolStrip != null) { + if (toolStrip != null) + { int index = unchecked((int)(long)m.WParam); - if( index >= 0 && index < toolStrip.Items.Count ) { + if (index >= 0 && index < toolStrip.Items.Count) + { ToolStripButton button = toolStrip.Items[index] as ToolStripButton; - if (button != null) { + if (button != null) + { m.Result = (IntPtr)(button.Checked ? 1 : 0); } - else { + else + { m.Result = IntPtr.Zero; } } @@ -4556,19 +5379,25 @@ protected override void WndProc(ref Message m) { } break; case AutomationMessages.PGM_SETBUTTONSTATE: - if (toolStrip != null) { + if (toolStrip != null) + { int index = unchecked((int)(long)m.WParam); - if( index >= 0 && index < toolStrip.Items.Count ) { + if (index >= 0 && index < toolStrip.Items.Count) + { ToolStripButton button = toolStrip.Items[index] as ToolStripButton; - if (button != null) { + if (button != null) + { button.Checked = !button.Checked; // special treatment for the properies page button - if (button == btnViewPropertyPages) { + if (button == btnViewPropertyPages) + { OnViewButtonClickPP(button, EventArgs.Empty); } - else { - switch (unchecked((int)(long)m.WParam)) { + else + { + switch (unchecked((int)(long)m.WParam)) + { case ALPHA: case CATEGORIES: OnViewSortButtonClick(button, EventArgs.Empty); @@ -4586,14 +5415,18 @@ protected override void WndProc(ref Message m) { case AutomationMessages.PGM_GETBUTTONTEXT: case AutomationMessages.PGM_GETBUTTONTOOLTIPTEXT: - if (toolStrip != null) { + if (toolStrip != null) + { int index = unchecked((int)(long)m.WParam); - if( index >= 0 && index < toolStrip.Items.Count ) { + if (index >= 0 && index < toolStrip.Items.Count) + { string text = string.Empty; - if (m.Msg == AutomationMessages.PGM_GETBUTTONTEXT) { + if (m.Msg == AutomationMessages.PGM_GETBUTTONTEXT) + { text = toolStrip.Items[index].Text; } - else { + else + { text = toolStrip.Items[index].ToolTipText; } @@ -4603,17 +5436,19 @@ protected override void WndProc(ref Message m) { return; } break; - - case AutomationMessages.PGM_GETTESTINGINFO: { - // Get "testing info" string for Nth grid entry (or active entry if N < 0) - string testingInfo = gridView.GetTestingInfo(unchecked((int) (long) m.WParam)); - m.Result = AutomationMessages.WriteAutomationText(testingInfo); - return; + + case AutomationMessages.PGM_GETTESTINGINFO: + { + // Get "testing info" string for Nth grid entry (or active entry if N < 0) + string testingInfo = gridView.GetTestingInfo(unchecked((int)(long)m.WParam)); + m.Result = AutomationMessages.WriteAutomationText(testingInfo); + return; } - + case AutomationMessages.PGM_GETROWCOORDS: - if (m.Msg == this.dwMsg) { - m.Result = (IntPtr) gridView.GetPropertyLocation(propName, m.LParam == IntPtr.Zero, m.WParam == IntPtr.Zero); + if (m.Msg == this.dwMsg) + { + m.Result = (IntPtr)gridView.GetPropertyLocation(propName, m.LParam == IntPtr.Zero, m.WParam == IntPtr.Zero); return; } break; @@ -4622,15 +5457,18 @@ protected override void WndProc(ref Message m) { m.Result = gridView.SendMessage(m.Msg, m.WParam, m.LParam); return; case AutomationMessages.PGM_SETSELECTEDTAB: - if( m.LParam != IntPtr.Zero ) { + if (m.LParam != IntPtr.Zero) + { string tabTypeName = AutomationMessages.ReadAutomationText(m.LParam); - for (int i = 0; i < viewTabs.Length;i++) { - if (viewTabs[i].GetType().FullName == tabTypeName && viewTabButtons[i].Visible) { - SelectViewTabButtonDefault(viewTabButtons[i]); - m.Result = (IntPtr)1; - break; - } + for (int i = 0; i < viewTabs.Length; i++) + { + if (viewTabs[i].GetType().FullName == tabTypeName && viewTabButtons[i].Visible) + { + SelectViewTabButtonDefault(viewTabButtons[i]); + m.Result = (IntPtr)1; + break; + } } } m.Result = (IntPtr)0; @@ -4640,33 +5478,39 @@ protected override void WndProc(ref Message m) { base.WndProc(ref m); } - internal abstract class SnappableControl : Control { + internal abstract class SnappableControl : Control + { private Color borderColor = SystemColors.ControlDark; protected PropertyGrid ownerGrid; internal bool userSized = false; public abstract int GetOptimalHeight(int width); public abstract int SnapHeightRequest(int request); - - public SnappableControl(PropertyGrid ownerGrid) { + + public SnappableControl(PropertyGrid ownerGrid) + { this.ownerGrid = ownerGrid; SetStyle(ControlStyles.OptimizedDoubleBuffer, true); } - public override Cursor Cursor { - get { - return Cursors.Default; - } - set { - base.Cursor = value; - } + public override Cursor Cursor + { + get + { + return Cursors.Default; + } + set + { + base.Cursor = value; + } } - protected override void OnControlAdded(ControlEventArgs ce) { + protected override void OnControlAdded(ControlEventArgs ce) + { //ce.Control.MouseEnter += new EventHandler(this.OnChildMouseEnter); } - + /* private void OnChildMouseEnter(object sender, EventArgs e) { if (sender is Control) { @@ -4675,124 +5519,154 @@ private void OnChildMouseEnter(object sender, EventArgs e) { } */ - public Color BorderColor { - get { + public Color BorderColor + { + get + { return borderColor; } - set { + set + { borderColor = value; } } - protected override void OnPaint(PaintEventArgs e) { + protected override void OnPaint(PaintEventArgs e) + { base.OnPaint(e); Rectangle r = this.ClientRectangle; - r.Width --; + r.Width--; r.Height--; - using (Pen borderPen = new Pen(BorderColor, 1)) { + using (Pen borderPen = new Pen(BorderColor, 1)) + { e.Graphics.DrawRectangle(borderPen, r); } } } - public class PropertyTabCollection : ICollection { - + public class PropertyTabCollection : ICollection + { + internal static PropertyTabCollection Empty = new PropertyTabCollection(null); - - private PropertyGrid owner; - - internal PropertyTabCollection(PropertyGrid owner) { + + private PropertyGrid owner; + + internal PropertyTabCollection(PropertyGrid owner) + { this.owner = owner; } - + /// /// Retrieves the number of member attributes. /// - public int Count { - get { - if (owner == null) { + public int Count + { + get + { + if (owner == null) + { return 0; } return owner.viewTabs.Length; } } - - object ICollection.SyncRoot { - get { + + object ICollection.SyncRoot + { + get + { return this; } } - - bool ICollection.IsSynchronized { - get { + + bool ICollection.IsSynchronized + { + get + { return false; } } - + /// /// Retrieves the member attribute with the specified index. /// - public PropertyTab this[int index] { - get { - if (owner == null) { + public PropertyTab this[int index] + { + get + { + if (owner == null) + { throw new InvalidOperationException(SR.PropertyGridPropertyTabCollectionReadOnly); } return owner.viewTabs[index]; } } - - public void AddTabType(Type propertyTabType) { - if (owner == null) { + + public void AddTabType(Type propertyTabType) + { + if (owner == null) + { throw new InvalidOperationException(SR.PropertyGridPropertyTabCollectionReadOnly); } owner.AddTab(propertyTabType, PropertyTabScope.Global); } - - public void AddTabType(Type propertyTabType, PropertyTabScope tabScope) { - if (owner == null) { + + public void AddTabType(Type propertyTabType, PropertyTabScope tabScope) + { + if (owner == null) + { throw new InvalidOperationException(SR.PropertyGridPropertyTabCollectionReadOnly); } owner.AddTab(propertyTabType, tabScope); } - + /// /// Clears the tabs of the given scope or smaller. /// tabScope must be PropertyTabScope.Component or PropertyTabScope.Document. /// - public void Clear(PropertyTabScope tabScope) { - if (owner == null) { + public void Clear(PropertyTabScope tabScope) + { + if (owner == null) + { throw new InvalidOperationException(SR.PropertyGridPropertyTabCollectionReadOnly); } owner.ClearTabs(tabScope); } - - - void ICollection.CopyTo(Array dest, int index) { - if (owner == null) { + + + void ICollection.CopyTo(Array dest, int index) + { + if (owner == null) + { return; } - if (owner.viewTabs.Length > 0) { + if (owner.viewTabs.Length > 0) + { System.Array.Copy(owner.viewTabs, 0, dest, index, owner.viewTabs.Length); } } /// /// Creates and retrieves a new enumerator for this collection. /// - public IEnumerator GetEnumerator() { - if (owner == null) { + public IEnumerator GetEnumerator() + { + if (owner == null) + { return new PropertyTab[0].GetEnumerator(); } - + return owner.viewTabs.GetEnumerator(); } - - public void RemoveTabType(Type propertyTabType) { - if (owner == null) { + + public void RemoveTabType(Type propertyTabType) + { + if (owner == null) + { throw new InvalidOperationException(SR.PropertyGridPropertyTabCollectionReadOnly); } owner.RemoveTab(propertyTabType); } - + } /// @@ -4811,89 +5685,108 @@ public void RemoveTabType(Type propertyTabType) { /// during parameter validation to see if an object implements IUnimplemented. If it /// does, we know that what we really have is a lying remoting proxy, and we bail. /// - private interface IUnimplemented {} + private interface IUnimplemented { } - internal class SelectedObjectConverter : ReferenceConverter { - public SelectedObjectConverter() : base(typeof(IComponent)) { + internal class SelectedObjectConverter : ReferenceConverter + { + public SelectedObjectConverter() : base(typeof(IComponent)) + { } } - private class PropertyGridServiceProvider : IServiceProvider { + private class PropertyGridServiceProvider : IServiceProvider + { PropertyGrid owner; - - public PropertyGridServiceProvider(PropertyGrid owner) { + + public PropertyGridServiceProvider(PropertyGrid owner) + { this.owner = owner; } - public object GetService(Type serviceType) { - object s = null; - - if (owner.ActiveDesigner != null) { - s = owner.ActiveDesigner.GetService(serviceType); - } + public object GetService(Type serviceType) + { + object s = null; + + if (owner.ActiveDesigner != null) + { + s = owner.ActiveDesigner.GetService(serviceType); + } - if (s == null) { - s = owner.gridView.GetService(serviceType); - } + if (s == null) + { + s = owner.gridView.GetService(serviceType); + } - if (s == null && owner.Site != null) { - s = owner.Site.GetService(serviceType); - } - return s; + if (s == null && owner.Site != null) + { + s = owner.Site.GetService(serviceType); + } + return s; } } - + /// /// Helper class to support rendering text using either GDI or GDI+. /// - internal static class MeasureTextHelper{ - public static SizeF MeasureText(PropertyGrid owner, Graphics g, string text, Font font ){ - return MeasureTextSimple(owner, g, text, font, new SizeF(0,0)); + internal static class MeasureTextHelper + { + public static SizeF MeasureText(PropertyGrid owner, Graphics g, string text, Font font) + { + return MeasureTextSimple(owner, g, text, font, new SizeF(0, 0)); } - public static SizeF MeasureText(PropertyGrid owner, Graphics g, string text, Font font, int width ){ - return MeasureText(owner, g, text, font, new SizeF(width,999999)); + public static SizeF MeasureText(PropertyGrid owner, Graphics g, string text, Font font, int width) + { + return MeasureText(owner, g, text, font, new SizeF(width, 999999)); } - public static SizeF MeasureTextSimple(PropertyGrid owner, Graphics g, string text, Font font, SizeF size ){ + public static SizeF MeasureTextSimple(PropertyGrid owner, Graphics g, string text, Font font, SizeF size) + { SizeF bindingSize; - if( owner.UseCompatibleTextRendering ){ - bindingSize = g.MeasureString(text, font, size ); + if (owner.UseCompatibleTextRendering) + { + bindingSize = g.MeasureString(text, font, size); } - else{ - bindingSize = (SizeF) TextRenderer.MeasureText(g, text, font, Size.Ceiling(size), GetTextRendererFlags() ); + else + { + bindingSize = (SizeF)TextRenderer.MeasureText(g, text, font, Size.Ceiling(size), GetTextRendererFlags()); } return bindingSize; } - public static SizeF MeasureText(PropertyGrid owner, Graphics g, string text, Font font, SizeF size ){ + public static SizeF MeasureText(PropertyGrid owner, Graphics g, string text, Font font, SizeF size) + { SizeF bindingSize; - if( owner.UseCompatibleTextRendering ){ - bindingSize = g.MeasureString(text, font, size ); - } - else{ - TextFormatFlags flags = - GetTextRendererFlags() | - TextFormatFlags.LeftAndRightPadding | - TextFormatFlags.WordBreak | + if (owner.UseCompatibleTextRendering) + { + bindingSize = g.MeasureString(text, font, size); + } + else + { + TextFormatFlags flags = + GetTextRendererFlags() | + TextFormatFlags.LeftAndRightPadding | + TextFormatFlags.WordBreak | TextFormatFlags.NoFullWidthCharacterBreak; - - bindingSize = (SizeF) TextRenderer.MeasureText(g, text, font, Size.Ceiling(size), flags ); + + bindingSize = (SizeF)TextRenderer.MeasureText(g, text, font, Size.Ceiling(size), flags); } return bindingSize; } - public static TextFormatFlags GetTextRendererFlags(){ - return TextFormatFlags.PreserveGraphicsClipping | + public static TextFormatFlags GetTextRendererFlags() + { + return TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.PreserveGraphicsTranslateTransform; } - } + } } - internal static class AutomationMessages { + internal static class AutomationMessages + { internal const int PGM_GETBUTTONCOUNT = Interop.WindowMessages.WM_USER + 0x50; internal const int PGM_GETBUTTONSTATE = Interop.WindowMessages.WM_USER + 0x52; internal const int PGM_SETBUTTONSTATE = Interop.WindowMessages.WM_USER + 0x51; @@ -5003,7 +5896,8 @@ private static string GenerateLogFileName(ref IntPtr fileId) /// Is used only in Accessibility Improvements of level3 to show correct accessible hierarchy. /// [ComVisible(true)] - internal class PropertyGridAccessibleObject : Control.ControlAccessibleObject { + internal class PropertyGridAccessibleObject : Control.ControlAccessibleObject + { private PropertyGrid _owningPropertyGrid; @@ -5011,7 +5905,8 @@ internal class PropertyGridAccessibleObject : Control.ControlAccessibleObject { /// Initializes new instance of PropertyGridAccessibleObject /// /// The PropertyGrid owning control. - public PropertyGridAccessibleObject(PropertyGrid owningPropertyGrid) : base(owningPropertyGrid) { + public PropertyGridAccessibleObject(PropertyGrid owningPropertyGrid) : base(owningPropertyGrid) + { _owningPropertyGrid = owningPropertyGrid; } @@ -5026,11 +5921,13 @@ public PropertyGridAccessibleObject(PropertyGrid owningPropertyGrid) : base(owni /// otherwise return this element if the point is on this element, /// otherwise return null. /// - internal override UnsafeNativeMethods.IRawElementProviderFragment ElementProviderFromPoint(double x, double y) { + internal override UnsafeNativeMethods.IRawElementProviderFragment ElementProviderFromPoint(double x, double y) + { Point clientPoint = _owningPropertyGrid.PointToClient(new Point((int)x, (int)y)); var element = _owningPropertyGrid.GetElementFromPoint(clientPoint); - if (element != null) { + if (element != null) + { return element.AccessibilityObject; } @@ -5042,15 +5939,18 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment ElementProvide /// /// Indicates the direction in which to navigate. /// Returns the element in the specified direction. - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - switch(direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { + switch (direction) + { case UnsafeNativeMethods.NavigateDirection.Parent: return null; case UnsafeNativeMethods.NavigateDirection.FirstChild: return GetChildFragment(0); case UnsafeNativeMethods.NavigateDirection.LastChild: var childFragmentCount = GetChildFragmentCount(); - if (childFragmentCount > 0) { + if (childFragmentCount > 0) + { return GetChildFragment(childFragmentCount - 1); } break; @@ -5065,15 +5965,18 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga /// The child element regarding which the target element is searched. /// Indicates the direction in which to navigate. /// Returns the element in the specified direction. - internal UnsafeNativeMethods.IRawElementProviderFragment ChildFragmentNavigate(AccessibleObject childFragment, UnsafeNativeMethods.NavigateDirection direction) { - switch(direction) { + internal UnsafeNativeMethods.IRawElementProviderFragment ChildFragmentNavigate(AccessibleObject childFragment, UnsafeNativeMethods.NavigateDirection direction) + { + switch (direction) + { case UnsafeNativeMethods.NavigateDirection.Parent: return this; case UnsafeNativeMethods.NavigateDirection.NextSibling: int fragmentCount = GetChildFragmentCount(); int childFragmentIndex = GetChildFragmentIndex(childFragment); int nextChildFragmentIndex = childFragmentIndex + 1; - if (fragmentCount > nextChildFragmentIndex) { + if (fragmentCount > nextChildFragmentIndex) + { return GetChildFragment(nextChildFragmentIndex); } @@ -5081,7 +5984,8 @@ internal UnsafeNativeMethods.IRawElementProviderFragment ChildFragmentNavigate(A case UnsafeNativeMethods.NavigateDirection.PreviousSibling: fragmentCount = GetChildFragmentCount(); childFragmentIndex = GetChildFragmentIndex(childFragment); - if (childFragmentIndex > 0) { + if (childFragmentIndex > 0) + { return GetChildFragment(childFragmentIndex - 1); } @@ -5094,8 +5998,10 @@ internal UnsafeNativeMethods.IRawElementProviderFragment ChildFragmentNavigate(A /// /// Return the element that is the root node of this fragment of UI. /// - internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot { - get { + internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot + { + get + { return this; } } @@ -5105,37 +6011,47 @@ internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRo /// /// The child index. /// The accessible child. - internal AccessibleObject GetChildFragment(int index) { - if (index < 0) { + internal AccessibleObject GetChildFragment(int index) + { + if (index < 0) + { return null; } - - if (_owningPropertyGrid.ToolbarVisible) { - if (index == 0) { + + if (_owningPropertyGrid.ToolbarVisible) + { + if (index == 0) + { return _owningPropertyGrid.ToolbarAccessibleObject; } index--; } - if (_owningPropertyGrid.GridViewVisible) { - if (index == 0) { + if (_owningPropertyGrid.GridViewVisible) + { + if (index == 0) + { return _owningPropertyGrid.GridViewAccessibleObject; } index--; } - - if (_owningPropertyGrid.CommandsVisible) { - if (index == 0) { + + if (_owningPropertyGrid.CommandsVisible) + { + if (index == 0) + { return _owningPropertyGrid.HotCommandsAccessibleObject; } index--; } - - if (_owningPropertyGrid.HelpVisible) { - if (index == 0) { + + if (_owningPropertyGrid.HelpVisible) + { + if (index == 0) + { return _owningPropertyGrid.HelpAccessibleObject; } } @@ -5147,22 +6063,27 @@ internal AccessibleObject GetChildFragment(int index) { /// Gets the number of children belonging to an accessible object. /// /// The number of children. - internal int GetChildFragmentCount() { + internal int GetChildFragmentCount() + { int childCount = 0; - if (_owningPropertyGrid.ToolbarVisible) { + if (_owningPropertyGrid.ToolbarVisible) + { childCount++; } - if (_owningPropertyGrid.GridViewVisible) { + if (_owningPropertyGrid.GridViewVisible) + { childCount++; } - if (_owningPropertyGrid.CommandsVisible) { + if (_owningPropertyGrid.CommandsVisible) + { childCount++; } - if (_owningPropertyGrid.HelpVisible) { + if (_owningPropertyGrid.HelpVisible) + { childCount++; } @@ -5174,7 +6095,8 @@ internal int GetChildFragmentCount() { /// /// Return the element in this fragment which has the keyboard focus, /// if any; otherwise return null. - internal override UnsafeNativeMethods.IRawElementProviderFragment GetFocus() { + internal override UnsafeNativeMethods.IRawElementProviderFragment GetFocus() + { return GetFocused(); } @@ -5183,11 +6105,14 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment GetFocus() { /// /// The control accessible object which index should be found. /// The child accessible index or -1 if not found. - internal int GetChildFragmentIndex(AccessibleObject controlAccessibleObject) { + internal int GetChildFragmentIndex(AccessibleObject controlAccessibleObject) + { int childFragmentCount = GetChildFragmentCount(); - for (int i = 0; i < childFragmentCount; i++) { + for (int i = 0; i < childFragmentCount; i++) + { var childFragment = GetChildFragment(i); - if (childFragment == controlAccessibleObject) { + if (childFragment == controlAccessibleObject) + { return i; } } @@ -5200,7 +6125,8 @@ internal int GetChildFragmentIndex(AccessibleObject controlAccessibleObject) { /// Represents the PropertyGrid inner ToolStrip control. /// Is used starting with Accessibility Improvements of level 3. /// - internal class PropertyGridToolStrip : ToolStrip { + internal class PropertyGridToolStrip : ToolStrip + { private PropertyGrid _parentPropertyGrid; @@ -5208,7 +6134,8 @@ internal class PropertyGridToolStrip : ToolStrip { /// Initializes new instance of PropertyGridToolStrip control. /// /// The parent PropertyGrid control. - public PropertyGridToolStrip(PropertyGrid parentPropertyGrid) { + public PropertyGridToolStrip(PropertyGrid parentPropertyGrid) + { _parentPropertyGrid = parentPropertyGrid; } @@ -5222,7 +6149,8 @@ public PropertyGridToolStrip(PropertyGrid parentPropertyGrid) { /// Constructs the new instance of the accessibility object for this control. /// /// The accessibility object for this control. - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new PropertyGridToolStripAccessibleObject(this, _parentPropertyGrid); } } @@ -5231,7 +6159,8 @@ protected override AccessibleObject CreateAccessibilityInstance() { /// Represents the PropertyGridToolStrip control accessibility object. /// [ComVisible(true)] - internal class PropertyGridToolStripAccessibleObject : ToolStrip.ToolStripAccessibleObject { + internal class PropertyGridToolStripAccessibleObject : ToolStrip.ToolStripAccessibleObject + { private PropertyGrid _parentPropertyGrid; @@ -5240,7 +6169,8 @@ internal class PropertyGridToolStripAccessibleObject : ToolStrip.ToolStripAccess /// /// The PropertyGridToolStrip owning control. /// The parent PropertyGrid control. - public PropertyGridToolStripAccessibleObject(PropertyGridToolStrip owningPropertyGridToolStrip, PropertyGrid parentPropertyGrid) : base(owningPropertyGridToolStrip) { + public PropertyGridToolStripAccessibleObject(PropertyGridToolStrip owningPropertyGridToolStrip, PropertyGrid parentPropertyGrid) : base(owningPropertyGridToolStrip) + { _parentPropertyGrid = parentPropertyGrid; } @@ -5249,11 +6179,14 @@ public PropertyGridToolStripAccessibleObject(PropertyGridToolStrip owningPropert /// /// Indicates the direction in which to navigate. /// Returns the element in the specified direction. - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { var propertyGridAccessibleObject = _parentPropertyGrid.AccessibilityObject as PropertyGridAccessibleObject; - if (propertyGridAccessibleObject != null) { + if (propertyGridAccessibleObject != null) + { var navigationTarget = propertyGridAccessibleObject.ChildFragmentNavigate(this, direction); - if (navigationTarget != null) { + if (navigationTarget != null) + { return navigationTarget; } } @@ -5266,10 +6199,14 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga /// /// Identifier indicating the property to return /// Returns a ValInfo indicating whether the element supports this property, or has no value for it. - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_ControlTypePropertyId) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_ControlTypePropertyId) + { return NativeMethods.UIA_ToolBarControlTypeId; - } else if (propertyID == NativeMethods.UIA_NamePropertyId) { + } + else if (propertyID == NativeMethods.UIA_NamePropertyId) + { return Name; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/ArrayElementGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/ArrayElementGridEntry.cs index 97f86467ee0..e875defca50 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/ArrayElementGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/ArrayElementGridEntry.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.PropertyGridInternal { +namespace System.Windows.Forms.PropertyGridInternal +{ using System.Diagnostics; @@ -17,60 +18,75 @@ namespace System.Windows.Forms.PropertyGridInternal { using Microsoft.Win32; using System.Globalization; - internal class ArrayElementGridEntry : GridEntry { + internal class ArrayElementGridEntry : GridEntry + { protected int index; public ArrayElementGridEntry(PropertyGrid ownerGrid, GridEntry peParent, int index) - : base(ownerGrid, peParent) { + : base(ownerGrid, peParent) + { this.index = index; this.SetFlag(FLAG_RENDER_READONLY, (peParent.Flags & FLAG_RENDER_READONLY) != 0 || peParent.ForceReadOnly); } - - public override GridItemType GridItemType { - get { + + public override GridItemType GridItemType + { + get + { return GridItemType.ArrayValue; } } - public override bool IsValueEditable { - get{ + public override bool IsValueEditable + { + get + { return ParentGridEntry.IsValueEditable; } } - public override string PropertyLabel { - get { + public override string PropertyLabel + { + get + { return "[" + index.ToString(CultureInfo.CurrentCulture) + "]"; } } - public override Type PropertyType { - get { + public override Type PropertyType + { + get + { return parentPE.PropertyType.GetElementType(); } } - public override object PropertyValue { - get { + public override object PropertyValue + { + get + { object owner = GetValueOwner(); Debug.Assert(owner is Array, "Owner is not array type!"); - return((Array)owner).GetValue(index); + return ((Array)owner).GetValue(index); } - set { + set + { object owner = GetValueOwner(); Debug.Assert(owner is Array, "Owner is not array type!"); - ((Array)owner).SetValue(value,index); + ((Array)owner).SetValue(value, index); } } - public override bool ShouldRenderReadOnly { - get { + public override bool ShouldRenderReadOnly + { + get + { return ParentGridEntry.ShouldRenderReadOnly; } } @@ -100,6 +116,6 @@ public override bool CanSetPropertyValue() { public override bool CanSetReadOnlyPropertyValue() { return this.ParentGridEntry.CanSetReadOnlyPropertyValue(); }*/ - + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/CategoryGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/CategoryGridEntry.cs index 57806afe69c..7be8b4e1797 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/CategoryGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/CategoryGridEntry.cs @@ -4,22 +4,24 @@ //#define PAINT_CATEGORY_TRIANGLE -namespace System.Windows.Forms.PropertyGridInternal { +namespace System.Windows.Forms.PropertyGridInternal +{ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; - using System; - using System.Collections; - using System.Reflection; - - using System.ComponentModel; - using System.ComponentModel.Design; - using System.Windows.Forms; - using System.Drawing; - using Microsoft.Win32; + using System; + using System.Collections; + using System.Reflection; - internal class CategoryGridEntry : GridEntry { + using System.ComponentModel; + using System.ComponentModel.Design; + using System.Windows.Forms; + using System.Drawing; + using Microsoft.Win32; + + internal class CategoryGridEntry : GridEntry + { internal string name; private Brush backBrush = null; @@ -29,75 +31,91 @@ internal class CategoryGridEntry : GridEntry { SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // GridEntry classes are internal so we have complete // control over who does what in the constructor. ] - public CategoryGridEntry(PropertyGrid ownerGrid, GridEntry peParent,string name, GridEntry[] childGridEntries) - : base(ownerGrid, peParent) { + public CategoryGridEntry(PropertyGrid ownerGrid, GridEntry peParent, string name, GridEntry[] childGridEntries) + : base(ownerGrid, peParent) + { this.name = name; #if DEBUG - for (int n = 0;n < childGridEntries.Length; n++) { + for (int n = 0; n < childGridEntries.Length; n++) + { Debug.Assert(childGridEntries[n] != null, "Null item in category subproperty list"); } #endif - if (categoryStates == null) { + if (categoryStates == null) + { categoryStates = new Hashtable(); } - lock (categoryStates) { - if (!categoryStates.ContainsKey(name)) { + lock (categoryStates) + { + if (!categoryStates.ContainsKey(name)) + { categoryStates.Add(name, true); } } this.IsExpandable = true; - - for (int i = 0; i < childGridEntries.Length; i++) { + + for (int i = 0; i < childGridEntries.Length; i++) + { childGridEntries[i].ParentGridEntry = this; } - + this.ChildCollection = new GridEntryCollection(this, childGridEntries); - lock (categoryStates) { + lock (categoryStates) + { this.InternalExpanded = (bool)categoryStates[name]; } - this.SetFlag(GridEntry.FLAG_LABEL_BOLD,true); + this.SetFlag(GridEntry.FLAG_LABEL_BOLD, true); } - - + + /// /// Returns true if this GridEntry has a value field in the right hand column. /// - internal override bool HasValue { - get { - return false; + internal override bool HasValue + { + get + { + return false; } } - protected override void Dispose(bool disposing) { - if (disposing) { - if (backBrush != null) { + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (backBrush != null) + { backBrush.Dispose(); backBrush = null; } - if (ChildCollection != null) { + if (ChildCollection != null) + { ChildCollection = null; } } base.Dispose(disposing); } - public override void DisposeChildren() { + public override void DisposeChildren() + { // categories should never dispose // return; } - - + + // we don't want this guy participating in property depth. - public override int PropertyDepth { - get { + public override int PropertyDepth + { + get + { return base.PropertyDepth - 1; } } @@ -106,69 +124,89 @@ public override int PropertyDepth { /// Gets the accessibility object for the current category grid entry. /// /// - protected override GridEntryAccessibleObject GetAccessibilityObject() { + protected override GridEntryAccessibleObject GetAccessibilityObject() + { return new CategoryGridEntryAccessibleObject(this); } - protected override Brush GetBackgroundBrush(Graphics g) { + protected override Brush GetBackgroundBrush(Graphics g) + { return this.GridEntryHost.GetLineBrush(g); } - protected override Color LabelTextColor { - get { + protected override Color LabelTextColor + { + get + { return ownerGrid.CategoryForeColor; } } - public override bool Expandable { - get { + public override bool Expandable + { + get + { return !GetFlagSet(FL_EXPANDABLE_FAILED); } } - - internal override bool InternalExpanded { - set { + + internal override bool InternalExpanded + { + set + { base.InternalExpanded = value; - lock (categoryStates) { + lock (categoryStates) + { categoryStates[this.name] = value; } } } - - public override GridItemType GridItemType { - get { + + public override GridItemType GridItemType + { + get + { return GridItemType.Category; } } - public override string HelpKeyword { - get { - return null; + public override string HelpKeyword + { + get + { + return null; } } - public override string PropertyLabel { - get { + public override string PropertyLabel + { + get + { return name; } } - - internal override int PropertyLabelIndent { - get { + + internal override int PropertyLabelIndent + { + get + { // we give an extra pixel for breathing room // we want to make sure that we return 0 for property depth here instead of PropertyGridView gridHost = this.GridEntryHost; - + // we call base.PropertyDepth here because we don't want the subratction to happen. - return 1+gridHost.GetOutlineIconSize()+OUTLINE_ICON_PADDING + (base.PropertyDepth * gridHost.GetDefaultOutlineIndent()); + return 1 + gridHost.GetOutlineIconSize() + OUTLINE_ICON_PADDING + (base.PropertyDepth * gridHost.GetDefaultOutlineIndent()); } } - public override string GetPropertyTextValue(object o) { + public override string GetPropertyTextValue(object o) + { return ""; } - public override Type PropertyType { - get { + public override Type PropertyType + { + get + { return typeof(void); } } @@ -177,62 +215,75 @@ public override Type PropertyType { /// Gets the owner of the current value. This is usually the value of the /// root entry, which is the object being browsed /// - public override object GetChildValueOwner(GridEntry childEntry) { + public override object GetChildValueOwner(GridEntry childEntry) + { return ParentGridEntry.GetChildValueOwner(childEntry); } - protected override bool CreateChildren(bool diffOldChildren) { + protected override bool CreateChildren(bool diffOldChildren) + { return true; } - public override string GetTestingInfo() { + public override string GetTestingInfo() + { string str = "object = ("; str += FullLabel; str += "), Category = (" + this.PropertyLabel + ")"; return str; } - public override void PaintLabel(System.Drawing.Graphics g, Rectangle rect, Rectangle clipRect, bool selected, bool paintFullLabel) { + public override void PaintLabel(System.Drawing.Graphics g, Rectangle rect, Rectangle clipRect, bool selected, bool paintFullLabel) + { base.PaintLabel(g, rect, clipRect, false, true); // now draw the focus rect - if (selected && hasFocus) { + if (selected && hasFocus) + { bool bold = ((this.Flags & GridEntry.FLAG_LABEL_BOLD) != 0); Font font = GetFont(bold); int labelWidth = GetLabelTextWidth(this.PropertyLabel, g, font); - int indent = PropertyLabelIndent-2; - Rectangle focusRect = new Rectangle(indent, rect.Y, labelWidth+3, rect.Height-1); - if (SystemInformation.HighContrast && !OwnerGrid.developerOverride) { + int indent = PropertyLabelIndent - 2; + Rectangle focusRect = new Rectangle(indent, rect.Y, labelWidth + 3, rect.Height - 1); + if (SystemInformation.HighContrast && !OwnerGrid.developerOverride) + { // we changed line color to SystemColors.ControlDarkDark in high contrast mode ControlPaint.DrawFocusRectangle(g, focusRect, SystemColors.ControlText, OwnerGrid.LineColor); } - else { + else + { ControlPaint.DrawFocusRectangle(g, focusRect); } } // draw the line along the top - if (parentPE.GetChildIndex(this) > 0) { - using (Pen topLinePen = new System.Drawing.Pen(ownerGrid.CategorySplitterColor, 1)) { + if (parentPE.GetChildIndex(this) > 0) + { + using (Pen topLinePen = new System.Drawing.Pen(ownerGrid.CategorySplitterColor, 1)) + { g.DrawLine(topLinePen, rect.X - 1, rect.Y - 1, rect.Width + 2, rect.Y - 1); } } } - public override void PaintValue(object val, System.Drawing.Graphics g, Rectangle rect, Rectangle clipRect, PaintValueFlags paintFlags) { + public override void PaintValue(object val, System.Drawing.Graphics g, Rectangle rect, Rectangle clipRect, PaintValueFlags paintFlags) + { base.PaintValue(val, g, rect, clipRect, paintFlags & ~PaintValueFlags.DrawSelected); // draw the line along the top - if (parentPE.GetChildIndex(this) > 0) { - using (Pen topLinePen = new System.Drawing.Pen(ownerGrid.CategorySplitterColor, 1)) { + if (parentPE.GetChildIndex(this) > 0) + { + using (Pen topLinePen = new System.Drawing.Pen(ownerGrid.CategorySplitterColor, 1)) + { g.DrawLine(topLinePen, rect.X - 2, rect.Y - 1, rect.Width + 1, rect.Y - 1); } } } - internal override bool NotifyChildValue(GridEntry pe, int type) { + internal override bool NotifyChildValue(GridEntry pe, int type) + { return parentPE.NotifyChildValue(pe, type); } @@ -240,7 +291,8 @@ internal override bool NotifyChildValue(GridEntry pe, int type) { /// Defines the Category Grid Entry accessible object that is derived from Grid Entry accessible object. /// [Runtime.InteropServices.ComVisible(true)] - internal class CategoryGridEntryAccessibleObject : GridEntryAccessibleObject { + internal class CategoryGridEntryAccessibleObject : GridEntryAccessibleObject + { private CategoryGridEntry _owningCategoryGridEntry; @@ -248,7 +300,8 @@ internal class CategoryGridEntryAccessibleObject : GridEntryAccessibleObject { /// Initializes new instance of CategoryGridEntryAccessibleObject. /// /// The owning Category Grid Entry object. - public CategoryGridEntryAccessibleObject(CategoryGridEntry owningCategoryGridEntry) : base(owningCategoryGridEntry) { + public CategoryGridEntryAccessibleObject(CategoryGridEntry owningCategoryGridEntry) : base(owningCategoryGridEntry) + { _owningCategoryGridEntry = owningCategoryGridEntry; } @@ -257,10 +310,12 @@ public CategoryGridEntryAccessibleObject(CategoryGridEntry owningCategoryGridEnt /// /// Indicates the direction in which to navigate. /// Returns the element in the specified direction. - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { PropertyGridView.PropertyGridViewAccessibleObject parent = (PropertyGridView.PropertyGridViewAccessibleObject)Parent; - switch (direction) { + switch (direction) + { case UnsafeNativeMethods.NavigateDirection.Parent: return Parent; case UnsafeNativeMethods.NavigateDirection.NextSibling: @@ -276,8 +331,10 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga return base.FragmentNavigate(direction); } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { return AccessibleRole.ButtonDropDownGrid; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs index ae2b25b0214..fe728dd9fbc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs @@ -3,26 +3,28 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.PropertyGridInternal { +namespace System.Windows.Forms.PropertyGridInternal +{ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System; using System.Windows.Forms; - + using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing; using Microsoft.Win32; using System.Windows.Forms.Layout; - internal class DocComment : PropertyGrid.SnappableControl { - + internal class DocComment : PropertyGrid.SnappableControl + { + private Label m_labelTitle; private Label m_labelDesc; private string fullDesc; - + protected int lineHeight; private bool needUpdateUIWithFont = true; @@ -36,7 +38,8 @@ internal class DocComment : PropertyGrid.SnappableControl { internal Rectangle rect = Rectangle.Empty; - internal DocComment(PropertyGrid owner) : base(owner) { + internal DocComment(PropertyGrid owner) : base(owner) + { SuspendLayout(); m_labelTitle = new Label(); m_labelTitle.UseMnemonic = false; @@ -49,7 +52,8 @@ internal DocComment(PropertyGrid owner) : base(owner) { Controls.Add(m_labelTitle); Controls.Add(m_labelDesc); - if (DpiHelper.IsScalingRequirementMet) { + if (DpiHelper.IsScalingRequirementMet) + { cBorder = LogicalToDeviceUnits(CBORDER); cydef = LogicalToDeviceUnits(CYDEF); } @@ -61,32 +65,37 @@ internal DocComment(PropertyGrid owner) : base(owner) { ResumeLayout(false); } - public virtual int Lines { - get { + public virtual int Lines + { + get + { UpdateUIWithFont(); - return Height/lineHeight; + return Height / lineHeight; } - set { + set + { UpdateUIWithFont(); Size = new Size(Width, 1 + value * lineHeight); } } - public override int GetOptimalHeight(int width) { + public override int GetOptimalHeight(int width) + { UpdateUIWithFont(); // compute optimal label height as one line only. int height = m_labelTitle.Size.Height; // do this to avoid getting parented to the Parking window. // - if (this.ownerGrid.IsHandleCreated && !IsHandleCreated) { + if (this.ownerGrid.IsHandleCreated && !IsHandleCreated) + { CreateControl(); } // compute optimal text height var isScalingRequirementMet = DpiHelper.IsScalingRequirementMet; Graphics g = m_labelDesc.CreateGraphicsInternal(); - SizeF sizef = PropertyGrid.MeasureTextHelper.MeasureText( this.ownerGrid, g, m_labelTitle.Text, Font, width); + SizeF sizef = PropertyGrid.MeasureTextHelper.MeasureText(this.ownerGrid, g, m_labelTitle.Text, Font, width); Size sz = Size.Ceiling(sizef); g.Dispose(); var padding = isScalingRequirementMet ? LogicalToDeviceUnits(2) : 2; @@ -94,33 +103,40 @@ public override int GetOptimalHeight(int width) { return Math.Max(height + 2 * padding, isScalingRequirementMet ? LogicalToDeviceUnits(CYDEF) : CYDEF); } - internal virtual void LayoutWindow() { + internal virtual void LayoutWindow() + { } - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { needUpdateUIWithFont = true; PerformLayout(); base.OnFontChanged(e); } - protected override void OnLayout(LayoutEventArgs e) { + protected override void OnLayout(LayoutEventArgs e) + { UpdateUIWithFont(); SetChildLabelsBounds(); m_labelDesc.Text = this.fullDesc; m_labelDesc.AccessibleName = this.fullDesc; // Don't crop the description for accessibility clients base.OnLayout(e); } - - protected override void OnResize(EventArgs e) { + + protected override void OnResize(EventArgs e) + { Rectangle newRect = ClientRectangle; - if (!rect.IsEmpty && newRect.Width > rect.Width) { + if (!rect.IsEmpty && newRect.Width > rect.Width) + { Rectangle rectInvalidate = new Rectangle(rect.Width - 1, 0, newRect.Width - rect.Width + 1, rect.Height); Invalidate(rectInvalidate); } - if (DpiHelper.IsScalingRequirementMet) { + if (DpiHelper.IsScalingRequirementMet) + { var lineHeightOld = lineHeight; lineHeight = (int)Font.Height + LogicalToDeviceUnits(2); - if (lineHeightOld != lineHeight) { + if (lineHeightOld != lineHeight) + { m_labelTitle.Location = new Point(cBorder, cBorder); m_labelDesc.Location = new Point(cBorder, cBorder + lineHeight); // Labels were explicitly set bounds. resize of parent is not rescaling labels. @@ -128,14 +144,15 @@ protected override void OnResize(EventArgs e) { } } - rect = newRect; + rect = newRect; base.OnResize(e); } /// /// Setting child label bounds /// - private void SetChildLabelsBounds() { + private void SetChildLabelsBounds() + { Size size = ClientSize; // if the client size is 0, setting this to a negative number @@ -156,7 +173,8 @@ private void SetChildLabelsBounds() { BoundsSpecified.Size); } - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { base.OnHandleCreated(e); UpdateUIWithFont(); } @@ -166,37 +184,44 @@ protected override void OnHandleCreated(EventArgs e) { /// /// old dpi /// new dpi - protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) { + protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) + { base.RescaleConstantsForDpi(deviceDpiOld, deviceDpiNew); - if (DpiHelper.IsScalingRequirementMet) { + if (DpiHelper.IsScalingRequirementMet) + { cBorder = LogicalToDeviceUnits(CBORDER); cydef = LogicalToDeviceUnits(CYDEF); } } - public virtual void SetComment(string title, string desc) { - if (m_labelDesc.Text != title) { + public virtual void SetComment(string title, string desc) + { + if (m_labelDesc.Text != title) + { m_labelTitle.Text = title; } - - if (desc != fullDesc) { + + if (desc != fullDesc) + { this.fullDesc = desc; m_labelDesc.Text = fullDesc; m_labelDesc.AccessibleName = this.fullDesc; // Don't crop the description for accessibility clients } } - public override int SnapHeightRequest(int cyNew) { + public override int SnapHeightRequest(int cyNew) + { UpdateUIWithFont(); - int lines = Math.Max(MIN_LINES, cyNew/lineHeight); - return 1 + lines*lineHeight; + int lines = Math.Max(MIN_LINES, cyNew / lineHeight); + return 1 + lines * lineHeight; } /// /// Constructs the new instance of the accessibility object for this control. /// /// The accessibility object for this control. - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new DocCommentAccessibleObject(this, ownerGrid); } @@ -206,20 +231,25 @@ protected override AccessibleObject CreateAccessibilityInstance() { /// internal override bool SupportsUiaProviders => true; - internal void UpdateTextRenderingEngine() { + internal void UpdateTextRenderingEngine() + { m_labelTitle.UseCompatibleTextRendering = this.ownerGrid.UseCompatibleTextRendering; m_labelDesc.UseCompatibleTextRendering = this.ownerGrid.UseCompatibleTextRendering; } - private void UpdateUIWithFont() { - if (IsHandleCreated && needUpdateUIWithFont) { + private void UpdateUIWithFont() + { + if (IsHandleCreated && needUpdateUIWithFont) + { // Some fonts throw because Bold is not a valid option // for them. Fail gracefully. - try { + try + { m_labelTitle.Font = new Font(Font, FontStyle.Bold); } - catch { + catch + { } lineHeight = (int)Font.Height + 2; @@ -236,7 +266,8 @@ private void UpdateUIWithFont() { /// Represents the DocComment control accessible object. /// [System.Runtime.InteropServices.ComVisible(true)] - internal class DocCommentAccessibleObject : Control.ControlAccessibleObject { + internal class DocCommentAccessibleObject : Control.ControlAccessibleObject + { private PropertyGrid _parentPropertyGrid; @@ -245,7 +276,8 @@ internal class DocCommentAccessibleObject : Control.ControlAccessibleObject { /// /// The owning DocComment control. /// The parent PropertyGrid control. - public DocCommentAccessibleObject(DocComment owningDocComment, PropertyGrid parentPropertyGrid) : base(owningDocComment) { + public DocCommentAccessibleObject(DocComment owningDocComment, PropertyGrid parentPropertyGrid) : base(owningDocComment) + { _parentPropertyGrid = parentPropertyGrid; } @@ -254,11 +286,14 @@ public DocCommentAccessibleObject(DocComment owningDocComment, PropertyGrid pare /// /// Indicates the direction in which to navigate. /// Returns the element in the specified direction. - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { var propertyGridAccessibleObject = _parentPropertyGrid.AccessibilityObject as PropertyGridAccessibleObject; - if (propertyGridAccessibleObject != null) { + if (propertyGridAccessibleObject != null) + { var navigationTarget = propertyGridAccessibleObject.ChildFragmentNavigate(this, direction); - if (navigationTarget != null) { + if (navigationTarget != null) + { return navigationTarget; } } @@ -271,10 +306,14 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga /// /// Identifier indicating the property to return /// Returns a ValInfo indicating whether the element supports this property, or has no value for it. - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_ControlTypePropertyId) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_ControlTypePropertyId) + { return NativeMethods.UIA_PaneControlTypeId; - } else if (propertyID == NativeMethods.UIA_NamePropertyId) { + } + else if (propertyID == NativeMethods.UIA_NamePropertyId) + { return Name; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DropDownButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DropDownButton.cs index 09635aeee26..16efefc7273 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DropDownButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DropDownButton.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.PropertyGridInternal { +namespace System.Windows.Forms.PropertyGridInternal +{ using System.Diagnostics; using System; @@ -14,13 +15,15 @@ namespace System.Windows.Forms.PropertyGridInternal { using System.Windows.Forms.ButtonInternal; using Microsoft.Win32; - internal sealed class DropDownButton : Button { + internal sealed class DropDownButton : Button + { private bool useComboBoxTheme = false; private bool ignoreMouse; - public DropDownButton() { + public DropDownButton() + { SetStyle(ControlStyles.Selectable, true); SetAccessibleName(); } @@ -28,12 +31,15 @@ public DropDownButton() { // when the holder is open, we don't fire clicks // - public bool IgnoreMouse { + public bool IgnoreMouse + { - get { + get + { return ignoreMouse; } - set { + set + { ignoreMouse = value; } } @@ -44,9 +50,12 @@ public bool IgnoreMouse { /// internal override bool SupportsUiaProviders => true; - public bool UseComboBoxTheme { - set { - if (useComboBoxTheme != value) { + public bool UseComboBoxTheme + { + set + { + if (useComboBoxTheme != value) + { useComboBoxTheme = value; SetAccessibleName(); @@ -55,70 +64,89 @@ public bool UseComboBoxTheme { } } - protected override void OnClick(EventArgs e) { - if (!IgnoreMouse) { + protected override void OnClick(EventArgs e) + { + if (!IgnoreMouse) + { base.OnClick(e); } } - protected override void OnMouseUp(MouseEventArgs e) { - if (!IgnoreMouse) { + protected override void OnMouseUp(MouseEventArgs e) + { + if (!IgnoreMouse) + { base.OnMouseUp(e); } } - protected override void OnMouseDown(MouseEventArgs e) { - if (!IgnoreMouse) { + protected override void OnMouseDown(MouseEventArgs e) + { + if (!IgnoreMouse) + { base.OnMouseDown(e); } } - - protected override void OnPaint(PaintEventArgs pevent) { + + protected override void OnPaint(PaintEventArgs pevent) + { base.OnPaint(pevent); - - if (Application.RenderWithVisualStyles & useComboBoxTheme) { + + if (Application.RenderWithVisualStyles & useComboBoxTheme) + { ComboBoxState cbState = ComboBoxState.Normal; - - if (base.MouseIsDown) { + + if (base.MouseIsDown) + { cbState = ComboBoxState.Pressed; } - else if (base.MouseIsOver) { + else if (base.MouseIsOver) + { cbState = ComboBoxState.Hot; } Rectangle dropDownButtonRect = new Rectangle(0, 0, Width, Height); - if (cbState == ComboBoxState.Normal) { + if (cbState == ComboBoxState.Normal) + { pevent.Graphics.FillRectangle(SystemBrushes.Window, dropDownButtonRect); } - if (!DpiHelper.IsScalingRequirementMet) { + if (!DpiHelper.IsScalingRequirementMet) + { ComboBoxRenderer.DrawDropDownButton(pevent.Graphics, dropDownButtonRect, cbState); } - else { + else + { ComboBoxRenderer.DrawDropDownButtonForHandle(pevent.Graphics, dropDownButtonRect, cbState, this.HandleInternal); } // Redraw focus cues // For consistency with other PropertyGrid buttons, i.e. those opening system dialogs ("..."), that always show visual cues when focused, // we need to do the same for this custom button, painted as ComboBox control part (drop-down). - if (Focused) { + if (Focused) + { dropDownButtonRect.Inflate(-1, -1); ControlPaint.DrawFocusRectangle(pevent.Graphics, dropDownButtonRect, ForeColor, BackColor); } } } - internal void PerformButtonClick() { - if (Visible && Enabled) { + internal void PerformButtonClick() + { + if (Visible && Enabled) + { OnClick(EventArgs.Empty); } } - private void SetAccessibleName() { - if (useComboBoxTheme) { + private void SetAccessibleName() + { + if (useComboBoxTheme) + { this.AccessibleName = SR.PropertyGridDropDownButtonComboBoxAccessibleName; } - else { + else + { this.AccessibleName = SR.PropertyGridDropDownButtonAccessibleName; } } @@ -127,22 +155,28 @@ private void SetAccessibleName() { /// Constructs the new instance of the accessibility object for this control. /// /// The accessibility object for this control. - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new DropDownButtonAccessibleObject(this); } - internal override ButtonBaseAdapter CreateStandardAdapter() { + internal override ButtonBaseAdapter CreateStandardAdapter() + { return new DropDownButtonAdapter(this); - } + } } - internal class DropDownButtonAdapter : ButtonStandardAdapter { + internal class DropDownButtonAdapter : ButtonStandardAdapter + { - internal DropDownButtonAdapter(ButtonBase control) : base(control) {} + internal DropDownButtonAdapter(ButtonBase control) : base(control) { } - private void DDB_Draw3DBorder(System.Drawing.Graphics g, Rectangle r, bool raised) { - if (Control.BackColor != SystemColors.Control && SystemInformation.HighContrast) { - if (raised) { + private void DDB_Draw3DBorder(System.Drawing.Graphics g, Rectangle r, bool raised) + { + if (Control.BackColor != SystemColors.Control && SystemInformation.HighContrast) + { + if (raised) + { Color c = ControlPaint.LightLight(Control.BackColor); ControlPaint.DrawBorder(g, r, c, 1, ButtonBorderStyle.Outset, @@ -150,12 +184,15 @@ private void DDB_Draw3DBorder(System.Drawing.Graphics g, Rectangle r, bool raise c, 2, ButtonBorderStyle.Inset, c, 2, ButtonBorderStyle.Inset); } - else { + else + { ControlPaint.DrawBorder(g, r, ControlPaint.Dark(Control.BackColor), ButtonBorderStyle.Solid); } } - else { - if (raised) { + else + { + if (raised) + { Color c = ControlPaint.Light(Control.BackColor); ControlPaint.DrawBorder(g, r, c, 1, ButtonBorderStyle.Solid, @@ -164,7 +201,7 @@ private void DDB_Draw3DBorder(System.Drawing.Graphics g, Rectangle r, bool raise Control.BackColor, 2, ButtonBorderStyle.Outset); Rectangle inside = r; - inside.Offset(1,1); + inside.Offset(1, 1); inside.Width -= 3; inside.Height -= 3; c = ControlPaint.LightLight(Control.BackColor); @@ -174,18 +211,22 @@ private void DDB_Draw3DBorder(System.Drawing.Graphics g, Rectangle r, bool raise c, 1, ButtonBorderStyle.None, c, 1, ButtonBorderStyle.None); } - else { + else + { ControlPaint.DrawBorder(g, r, ControlPaint.Dark(Control.BackColor), ButtonBorderStyle.Solid); } } } - - internal override void PaintUp(PaintEventArgs pevent, CheckState state) { + + internal override void PaintUp(PaintEventArgs pevent, CheckState state) + { base.PaintUp(pevent, state); - if (!Application.RenderWithVisualStyles) { + if (!Application.RenderWithVisualStyles) + { DDB_Draw3DBorder(pevent.Graphics, Control.ClientRectangle, true); } - else { + else + { Color c = SystemColors.Window; Rectangle rect = Control.ClientRectangle; rect.Inflate(0, -1); @@ -197,9 +238,10 @@ internal override void PaintUp(PaintEventArgs pevent, CheckState state) { } } - internal override void DrawImageCore(Graphics graphics, Image image, Rectangle imageBounds, Point imageStart, ButtonBaseAdapter.LayoutData layout) { - ControlPaint.DrawImageReplaceColor(graphics, image, imageBounds, Color.Black, this.IsHighContrastHighlighted() && !this.Control.MouseIsDown ? SystemColors.HighlightText : Control.ForeColor); - } + internal override void DrawImageCore(Graphics graphics, Image image, Rectangle imageBounds, Point imageStart, ButtonBaseAdapter.LayoutData layout) + { + ControlPaint.DrawImageReplaceColor(graphics, image, imageBounds, Color.Black, this.IsHighContrastHighlighted() && !this.Control.MouseIsDown ? SystemColors.HighlightText : Control.ForeColor); + } } /// @@ -207,7 +249,8 @@ internal override void DrawImageCore(Graphics graphics, Image image, Rectangle i /// This DropDownButtonAccessibleObject is available in Level3 only. /// [Runtime.InteropServices.ComVisible(true)] - internal class DropDownButtonAccessibleObject : Control.ControlAccessibleObject { + internal class DropDownButtonAccessibleObject : Control.ControlAccessibleObject + { private DropDownButton _owningDropDownButton; private PropertyGridView _owningPropertyGrid; @@ -216,14 +259,16 @@ internal class DropDownButtonAccessibleObject : Control.ControlAccessibleObject /// Constructs the new instance of DropDownButtonAccessibleObject. /// /// - public DropDownButtonAccessibleObject(DropDownButton owningDropDownButton) : base(owningDropDownButton) { + public DropDownButtonAccessibleObject(DropDownButton owningDropDownButton) : base(owningDropDownButton) + { _owningDropDownButton = owningDropDownButton; _owningPropertyGrid = owningDropDownButton.Parent as PropertyGridView; UseStdAccessibleObjects(owningDropDownButton.Handle); } - public override void DoDefaultAction() { + public override void DoDefaultAction() + { _owningDropDownButton.PerformButtonClick(); } @@ -232,13 +277,16 @@ public override void DoDefaultAction() { /// /// Indicates the direction in which to navigate. /// Returns the element in the specified direction. - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { if (direction == UnsafeNativeMethods.NavigateDirection.Parent && _owningPropertyGrid.SelectedGridEntry != null && - _owningDropDownButton.Visible) { + _owningDropDownButton.Visible) + { return _owningPropertyGrid.SelectedGridEntry?.AccessibilityObject; } - else if (direction == UnsafeNativeMethods.NavigateDirection.PreviousSibling) { + else if (direction == UnsafeNativeMethods.NavigateDirection.PreviousSibling) + { return _owningPropertyGrid.EditAccessibleObject; } @@ -248,8 +296,10 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga /// /// Returns the element that is the root node of this fragment of UI. /// - internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot { - get { + internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot + { + get + { return _owningPropertyGrid.AccessibilityObject; } } @@ -259,8 +309,10 @@ internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRo /// /// Identifier indicating the property to return /// Returns a ValInfo indicating whether the element supports this property, or has no value for it. - internal override object GetPropertyValue(int propertyID) { - switch (propertyID) { + internal override object GetPropertyValue(int propertyID) + { + switch (propertyID) + { case NativeMethods.UIA_ControlTypePropertyId: return NativeMethods.UIA_ButtonControlTypeId; case NativeMethods.UIA_NamePropertyId: @@ -279,8 +331,10 @@ internal override object GetPropertyValue(int propertyID) { /// /// The pattern ID. /// True if specified pattern is supported, otherwise false. - internal override bool IsPatternSupported(int patternId) { - if (patternId == NativeMethods.UIA_LegacyIAccessiblePatternId) { + internal override bool IsPatternSupported(int patternId) + { + if (patternId == NativeMethods.UIA_LegacyIAccessiblePatternId) + { return true; } @@ -290,8 +344,10 @@ internal override bool IsPatternSupported(int patternId) { /// /// Gets the accessible role. /// - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { return AccessibleRole.PushButton; } } @@ -302,7 +358,8 @@ public override AccessibleRole Role { /// focused before calling this method, so this method should only update its internal /// focus state; it should not attempt to give its own HWND the focus, for example. /// - internal override void SetFocus() { + internal override void SetFocus() + { RaiseAutomationEvent(NativeMethods.UIA_AutomationFocusChangedEventId); base.SetFocus(); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs index 3092f3054da..b771b181127 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs @@ -4,7 +4,8 @@ //#define PBRS_PAINT_DEBUG -namespace System.Windows.Forms.PropertyGridInternal { +namespace System.Windows.Forms.PropertyGridInternal +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.ComponentModel; @@ -14,7 +15,7 @@ namespace System.Windows.Forms.PropertyGridInternal { using System.Reflection; using System.Globalization; - using System.Drawing.Design; + using System.Drawing.Design; using System.ComponentModel.Design; using System.Windows.Forms; using System.Windows.Forms.Design; @@ -27,128 +28,136 @@ namespace System.Windows.Forms.PropertyGridInternal { /// /// Base Entry for properties to be displayed in properties window. /// - internal abstract class GridEntry : GridItem, ITypeDescriptorContext { + internal abstract class GridEntry : GridItem, ITypeDescriptorContext + { protected static readonly Point InvalidPoint = new Point(int.MinValue, int.MinValue); private static BooleanSwitch PbrsAssertPropsSwitch = new BooleanSwitch("PbrsAssertProps", "PropertyBrowser : Assert on broken properties"); internal static AttributeTypeSorter AttributeTypeSorter = new AttributeTypeSorter(); - + // Type flags - internal const int FLAG_TEXT_EDITABLE = 0x0001; - internal const int FLAG_ENUMERABLE = 0x0002; - internal const int FLAG_CUSTOM_PAINT = 0x0004; - internal const int FLAG_IMMEDIATELY_EDITABLE = 0x0008; - internal const int FLAG_CUSTOM_EDITABLE = 0x0010; - internal const int FLAG_DROPDOWN_EDITABLE = 0x0020; - internal const int FLAG_LABEL_BOLD = 0x0040; - internal const int FLAG_READONLY_EDITABLE = 0x0080; - internal const int FLAG_RENDER_READONLY = 0x0100; - internal const int FLAG_IMMUTABLE = 0x0200; - internal const int FLAG_FORCE_READONLY = 0x0400; - internal const int FLAG_RENDER_PASSWORD = 0x1000; - - internal const int FLAG_DISPOSED = 0x2000; - - internal const int FL_EXPAND = 0x00010000; - internal const int FL_EXPANDABLE = 0x00020000; + internal const int FLAG_TEXT_EDITABLE = 0x0001; + internal const int FLAG_ENUMERABLE = 0x0002; + internal const int FLAG_CUSTOM_PAINT = 0x0004; + internal const int FLAG_IMMEDIATELY_EDITABLE = 0x0008; + internal const int FLAG_CUSTOM_EDITABLE = 0x0010; + internal const int FLAG_DROPDOWN_EDITABLE = 0x0020; + internal const int FLAG_LABEL_BOLD = 0x0040; + internal const int FLAG_READONLY_EDITABLE = 0x0080; + internal const int FLAG_RENDER_READONLY = 0x0100; + internal const int FLAG_IMMUTABLE = 0x0200; + internal const int FLAG_FORCE_READONLY = 0x0400; + internal const int FLAG_RENDER_PASSWORD = 0x1000; + + internal const int FLAG_DISPOSED = 0x2000; + + internal const int FL_EXPAND = 0x00010000; + internal const int FL_EXPANDABLE = 0x00020000; //protected const int FL_EXPANDABLE_VALID = 0x00040000; - internal const int FL_EXPANDABLE_FAILED = 0x00080000; - internal const int FL_NO_CUSTOM_PAINT = 0x00100000; - internal const int FL_CATEGORIES = 0x00200000; - internal const int FL_CHECKED = unchecked((int)0x80000000); + internal const int FL_EXPANDABLE_FAILED = 0x00080000; + internal const int FL_NO_CUSTOM_PAINT = 0x00100000; + internal const int FL_CATEGORIES = 0x00200000; + internal const int FL_CHECKED = unchecked((int)0x80000000); // rest are GridEntry constants. - protected const int NOTIFY_RESET = 1; - protected const int NOTIFY_CAN_RESET = 2; - protected const int NOTIFY_DBL_CLICK = 3; - protected const int NOTIFY_SHOULD_PERSIST = 4; - protected const int NOTIFY_RETURN = 5; + protected const int NOTIFY_RESET = 1; + protected const int NOTIFY_CAN_RESET = 2; + protected const int NOTIFY_DBL_CLICK = 3; + protected const int NOTIFY_SHOULD_PERSIST = 4; + protected const int NOTIFY_RETURN = 5; + + protected const int OUTLINE_ICON_PADDING = 5; + + protected static IComparer DisplayNameComparer = new DisplayNameSortComparer(); - protected const int OUTLINE_ICON_PADDING = 5; - - protected static IComparer DisplayNameComparer = new DisplayNameSortComparer(); - private static char passwordReplaceChar; //Maximum number of characters we'll show in the property grid. Too many characters leads //to bad performance. private const int maximumLengthOfPropertyString = 1000; [Flags] - internal enum PaintValueFlags{ + internal enum PaintValueFlags + { None = 0, DrawSelected = 0x1, - FetchValue = 0x2, + FetchValue = 0x2, CheckShouldSerialize = 0x4, PaintInPlace = 0x8 } - private class CacheItems { + private class CacheItems + { public string lastLabel; - public Font lastLabelFont; - public int lastLabelWidth; + public Font lastLabelFont; + public int lastLabelWidth; public string lastValueString; - public Font lastValueFont; - public int lastValueTextWidth; + public Font lastValueFont; + public int lastValueTextWidth; public object lastValue; - public bool useValueString; - public bool lastShouldSerialize; - public bool useShouldSerialize; - public bool useCompatTextRendering; + public bool useValueString; + public bool lastShouldSerialize; + public bool useShouldSerialize; + public bool useCompatTextRendering; } private CacheItems cacheItems; // instance variables. - protected TypeConverter converter = null; - protected UITypeEditor editor = null; - internal GridEntry parentPE = null; - private GridEntryCollection childCollection = null; - internal int flags = 0; - private int propertyDepth = 0; - protected bool hasFocus = false; - private Rectangle outlineRect = Rectangle.Empty; - protected PropertySort PropertySort; - - protected Point labelTipPoint = InvalidPoint; - protected Point valueTipPoint = InvalidPoint; - - protected PropertyGrid ownerGrid; - - private static object EVENT_VALUE_CLICK = new object(); - private static object EVENT_LABEL_CLICK = new object(); - private static object EVENT_OUTLINE_CLICK = new object(); - private static object EVENT_VALUE_DBLCLICK = new object(); - private static object EVENT_LABEL_DBLCLICK = new object(); - private static object EVENT_OUTLINE_DBLCLICK = new object(); - private static object EVENT_RECREATE_CHILDREN = new object(); + protected TypeConverter converter = null; + protected UITypeEditor editor = null; + internal GridEntry parentPE = null; + private GridEntryCollection childCollection = null; + internal int flags = 0; + private int propertyDepth = 0; + protected bool hasFocus = false; + private Rectangle outlineRect = Rectangle.Empty; + protected PropertySort PropertySort; + + protected Point labelTipPoint = InvalidPoint; + protected Point valueTipPoint = InvalidPoint; + + protected PropertyGrid ownerGrid; + + private static object EVENT_VALUE_CLICK = new object(); + private static object EVENT_LABEL_CLICK = new object(); + private static object EVENT_OUTLINE_CLICK = new object(); + private static object EVENT_VALUE_DBLCLICK = new object(); + private static object EVENT_LABEL_DBLCLICK = new object(); + private static object EVENT_OUTLINE_DBLCLICK = new object(); + private static object EVENT_RECREATE_CHILDREN = new object(); private GridEntryAccessibleObject accessibleObject = null; - private bool lastPaintWithExplorerStyle = false; + private bool lastPaintWithExplorerStyle = false; - private static Color InvertColor(Color color) { + private static Color InvertColor(Color color) + { return Color.FromArgb(color.A, (byte)~color.R, (byte)~color.G, (byte)~color.B); } - protected GridEntry(PropertyGrid owner, GridEntry peParent) { + protected GridEntry(PropertyGrid owner, GridEntry peParent) + { parentPE = peParent; ownerGrid = owner; - Debug.Assert( this.ownerGrid != null, "GridEntry w/o PropertyGrid owner, text rendering will fail." ); + Debug.Assert(this.ownerGrid != null, "GridEntry w/o PropertyGrid owner, text rendering will fail."); - if (peParent != null) { + if (peParent != null) + { propertyDepth = peParent.PropertyDepth + 1; this.PropertySort = peParent.PropertySort; - if (peParent.ForceReadOnly) { + if (peParent.ForceReadOnly) + { flags |= FLAG_FORCE_READONLY; } } - else { + else + { propertyDepth = -1; } } @@ -156,10 +165,14 @@ protected GridEntry(PropertyGrid owner, GridEntry peParent) { /// /// Outline Icon padding /// - private int OutlineIconPadding { - get { - if (DpiHelper.IsScalingRequirementMet) { - if (this.GridEntryHost != null) { + private int OutlineIconPadding + { + get + { + if (DpiHelper.IsScalingRequirementMet) + { + if (this.GridEntryHost != null) + { return this.GridEntryHost.LogicalToDeviceUnits(OUTLINE_ICON_PADDING); } } @@ -168,23 +181,29 @@ private int OutlineIconPadding { } } - private bool colorInversionNeededInHC { - get { - return SystemInformation.HighContrast && !OwnerGrid.developerOverride; + private bool colorInversionNeededInHC + { + get + { + return SystemInformation.HighContrast && !OwnerGrid.developerOverride; } } - public AccessibleObject AccessibilityObject { + public AccessibleObject AccessibilityObject + { - get { - if (accessibleObject == null) { + get + { + if (accessibleObject == null) + { accessibleObject = GetAccessibilityObject(); } return accessibleObject; } } - protected virtual GridEntryAccessibleObject GetAccessibilityObject() { + protected virtual GridEntryAccessibleObject GetAccessibilityObject() + { return new GridEntryAccessibleObject(this); } @@ -192,20 +211,26 @@ protected virtual GridEntryAccessibleObject GetAccessibilityObject() { /// specify that this grid entry should be allowed to be merged for. /// multi-select. /// - public virtual bool AllowMerge { - get { + public virtual bool AllowMerge + { + get + { return true; } } - - internal virtual bool AlwaysAllowExpand { - get { - return false; + + internal virtual bool AlwaysAllowExpand + { + get + { + return false; } } - internal virtual AttributeCollection Attributes { - get { + internal virtual AttributeCollection Attributes + { + get + { return TypeDescriptor.GetAttributes(PropertyType); } } @@ -215,18 +240,23 @@ internal virtual AttributeCollection Attributes { /// this member to cause the entry to paint it's background in a different color. /// The base implementation returns null. /// - protected virtual Brush GetBackgroundBrush(Graphics g) { + protected virtual Brush GetBackgroundBrush(Graphics g) + { return GridEntryHost.GetBackgroundBrush(g); } /// /// - protected virtual Color LabelTextColor { - get { - if (this.ShouldRenderReadOnly) { + protected virtual Color LabelTextColor + { + get + { + if (this.ShouldRenderReadOnly) + { return GridEntryHost.GrayTextColor; } - else { + else + { return GridEntryHost.GetTextColor(); } } @@ -235,14 +265,18 @@ protected virtual Color LabelTextColor { /// /// The set of attributes that will be used for browse filtering /// - public virtual AttributeCollection BrowsableAttributes { - get{ - if (parentPE != null) { + public virtual AttributeCollection BrowsableAttributes + { + get + { + if (parentPE != null) + { return parentPE.BrowsableAttributes; } return null; } - set{ + set + { parentPE.BrowsableAttributes = value; } } @@ -253,21 +287,27 @@ public virtual AttributeCollection BrowsableAttributes { /// return null if there is no component /// responsible for the call. /// - public virtual IComponent Component { - get { + public virtual IComponent Component + { + get + { object owner = GetValueOwner(); - if (owner is IComponent) { - return(IComponent) owner; + if (owner is IComponent) + { + return (IComponent)owner; } - if (parentPE != null) { + if (parentPE != null) + { return parentPE.Component; } return null; } } - protected virtual IComponentChangeService ComponentChangeService { - get { + protected virtual IComponentChangeService ComponentChangeService + { + get + { return parentPE.ComponentChangeService; } @@ -280,12 +320,16 @@ protected virtual IComponentChangeService ComponentChangeService { /// container, or of the formatter should not /// use any outside objects. /// - public virtual IContainer Container { - get { + public virtual IContainer Container + { + get + { IComponent component = Component; - if (component != null) { + if (component != null) + { ISite site = component.Site; - if (site != null) { + if (site != null) + { return site.Container; } } @@ -293,17 +337,23 @@ public virtual IContainer Container { } } - protected GridEntryCollection ChildCollection{ - get { - if (childCollection == null) { + protected GridEntryCollection ChildCollection + { + get + { + if (childCollection == null) + { childCollection = new GridEntryCollection(this, null); } return childCollection; } - set { + set + { Debug.Assert(value == null || !Disposed, "Why are we putting new children in after we are disposed?"); - if (this.childCollection != value) { - if (this.childCollection != null) { + if (this.childCollection != value) + { + if (this.childCollection != null) + { this.childCollection.Dispose(); this.childCollection = null; } @@ -312,33 +362,44 @@ protected GridEntryCollection ChildCollection{ } } - public int ChildCount { - get { - if (Children != null) { + public int ChildCount + { + get + { + if (Children != null) + { return Children.Count; } return 0; } } - public virtual GridEntryCollection Children { - get { - if (childCollection == null && !Disposed) { + public virtual GridEntryCollection Children + { + get + { + if (childCollection == null && !Disposed) + { CreateChildren(); } return childCollection; } } - public virtual PropertyTab CurrentTab{ - get{ - if (parentPE != null) { + public virtual PropertyTab CurrentTab + { + get + { + if (parentPE != null) + { return parentPE.CurrentTab; } return null; } - set{ - if (parentPE != null) { + set + { + if (parentPE != null) + { parentPE.CurrentTab = value; } } @@ -348,53 +409,69 @@ public virtual PropertyTab CurrentTab{ /// Returns the default child GridEntry of this item. Usually the default property /// of the target object. /// - internal virtual GridEntry DefaultChild { - get { + internal virtual GridEntry DefaultChild + { + get + { return null; } - set{} + set { } } - internal virtual IDesignerHost DesignerHost{ - get{ - if (parentPE != null) { + internal virtual IDesignerHost DesignerHost + { + get + { + if (parentPE != null) + { return parentPE.DesignerHost; } return null; } - set { - if (parentPE != null) { + set + { + if (parentPE != null) + { parentPE.DesignerHost = value; } } } - internal bool Disposed{ - get { + internal bool Disposed + { + get + { return GetFlagSet(FLAG_DISPOSED); } } - internal virtual bool Enumerable { - get { - return(this.Flags & GridEntry.FLAG_ENUMERABLE) != 0; + internal virtual bool Enumerable + { + get + { + return (this.Flags & GridEntry.FLAG_ENUMERABLE) != 0; } } - public override bool Expandable { - get { + public override bool Expandable + { + get + { bool fExpandable = GetFlagSet(FL_EXPANDABLE); - if (fExpandable && childCollection != null && childCollection.Count > 0) { + if (fExpandable && childCollection != null && childCollection.Count > 0) + { return true; } - if (GetFlagSet(FL_EXPANDABLE_FAILED)) { + if (GetFlagSet(FL_EXPANDABLE_FAILED)) + { return false; } - if (fExpandable && (cacheItems == null || cacheItems.lastValue == null) && this.PropertyValue == null) { + if (fExpandable && (cacheItems == null || cacheItems.lastValue == null) && this.PropertyValue == null) + { fExpandable = false; } @@ -402,42 +479,55 @@ public override bool Expandable { } } - public override bool Expanded { - get{ + public override bool Expanded + { + get + { return InternalExpanded; } - set { + set + { GridEntryHost.SetExpand(this, value); } } - internal virtual bool ForceReadOnly { - get { + internal virtual bool ForceReadOnly + { + get + { return (flags & FLAG_FORCE_READONLY) != 0; } } - - internal virtual bool InternalExpanded { - get{ + + internal virtual bool InternalExpanded + { + get + { // short circuit if we don't have children - if (childCollection == null || childCollection.Count == 0) { + if (childCollection == null || childCollection.Count == 0) + { return false; } return GetFlagSet(FL_EXPAND); } - set { - if (!this.Expandable || value == this.InternalExpanded) { + set + { + if (!this.Expandable || value == this.InternalExpanded) + { return; } - if (childCollection != null && childCollection.Count > 0) { - SetFlag(FL_EXPAND,value); + if (childCollection != null && childCollection.Count > 0) + { + SetFlag(FL_EXPAND, value); } - else { - SetFlag(FL_EXPAND,false); - if (value) { + else + { + SetFlag(FL_EXPAND, false); + if (value) + { bool fMakeSure = CreateChildren(); - SetFlag(FL_EXPAND,fMakeSure); + SetFlag(FL_EXPAND, fMakeSure); } } @@ -445,9 +535,11 @@ internal virtual bool InternalExpanded { // StateChange requires NameChange, too - accessible clients won't see this, unless both events are raised // Root item is hidden and should not raise events - if (GridItemType != GridItemType.Root) { + if (GridItemType != GridItemType.Root) + { int id = ((PropertyGridView)GridEntryHost).AccessibilityGetGridEntryChildID(this); - if (id >= 0) { + if (id >= 0) + { PropertyGridView.PropertyGridViewAccessibleObject gridAccObj = (PropertyGridView.PropertyGridViewAccessibleObject)((PropertyGridView)GridEntryHost).AccessibilityObject; @@ -458,56 +550,68 @@ internal virtual bool InternalExpanded { } } - internal virtual int Flags { - get { - if ((flags & FL_CHECKED) != 0) { + internal virtual int Flags + { + get + { + if ((flags & FL_CHECKED) != 0) + { return flags; } flags |= FL_CHECKED; TypeConverter converter = TypeConverter; - UITypeEditor uiEditor = UITypeEditor; + UITypeEditor uiEditor = UITypeEditor; object value = Instance; bool forceReadOnly = this.ForceReadOnly; - if (value != null) { - forceReadOnly |= TypeDescriptor.GetAttributes(value).Contains(InheritanceAttribute.InheritedReadOnly); + if (value != null) + { + forceReadOnly |= TypeDescriptor.GetAttributes(value).Contains(InheritanceAttribute.InheritedReadOnly); } - - if (converter.GetStandardValuesSupported(this)) { + + if (converter.GetStandardValuesSupported(this)) + { flags |= GridEntry.FLAG_ENUMERABLE; } if (!forceReadOnly && converter.CanConvertFrom(this, typeof(string)) && - !converter.GetStandardValuesExclusive(this)) { + !converter.GetStandardValuesExclusive(this)) + { flags |= GridEntry.FLAG_TEXT_EDITABLE; } - + bool isImmutableReadOnly = TypeDescriptor.GetAttributes(this.PropertyType)[typeof(ImmutableObjectAttribute)].Equals(ImmutableObjectAttribute.Yes); bool isImmutable = isImmutableReadOnly || converter.GetCreateInstanceSupported(this); - - if (isImmutable) { + + if (isImmutable) + { flags |= GridEntry.FLAG_IMMUTABLE; } - if (converter.GetPropertiesSupported(this)) { + if (converter.GetPropertiesSupported(this)) + { flags |= GridEntry.FL_EXPANDABLE; // If we're exapndable, but we don't support editing, // make us read only editable so we don't paint grey. // - if (!forceReadOnly && (flags & GridEntry.FLAG_TEXT_EDITABLE) == 0 && !isImmutableReadOnly) { + if (!forceReadOnly && (flags & GridEntry.FLAG_TEXT_EDITABLE) == 0 && !isImmutableReadOnly) + { flags |= GridEntry.FLAG_READONLY_EDITABLE; } } - if (Attributes.Contains(PasswordPropertyTextAttribute.Yes)) { + if (Attributes.Contains(PasswordPropertyTextAttribute.Yes)) + { flags |= GridEntry.FLAG_RENDER_PASSWORD; } - if (uiEditor != null) { - if (uiEditor.GetPaintValueSupported(this)) { + if (uiEditor != null) + { + if (uiEditor.GetPaintValueSupported(this)) + { flags |= GridEntry.FLAG_CUSTOM_PAINT; } @@ -517,12 +621,15 @@ internal virtual int Flags { // sure this is the right thing...is it? bool allowButtons = !forceReadOnly; - - if (allowButtons) { - switch (uiEditor.GetEditStyle(this)) { + + if (allowButtons) + { + switch (uiEditor.GetEditStyle(this)) + { case UITypeEditorEditStyle.Modal: flags |= GridEntry.FLAG_CUSTOM_EDITABLE; - if (!isImmutable && !PropertyType.IsValueType) { + if (!isImmutable && !PropertyType.IsValueType) + { flags |= GridEntry.FLAG_READONLY_EDITABLE; } break; @@ -536,7 +643,8 @@ internal virtual int Flags { return flags; } - set { + set + { flags = value; } } @@ -544,33 +652,41 @@ internal virtual int Flags { /// /// Checks if the entry is currently expanded /// - public bool Focus { - get{ + public bool Focus + { + get + { return this.hasFocus; } - set{ + set + { - if (Disposed) { + if (Disposed) + { return; } - if (cacheItems != null) { + if (cacheItems != null) + { cacheItems.lastValueString = null; cacheItems.useValueString = false; cacheItems.useShouldSerialize = false; } - - if (this.hasFocus != value) { + + if (this.hasFocus != value) + { this.hasFocus = value; // Notify accessibility applications that keyboard focus has changed. // - if (value == true) { + if (value == true) + { int id = ((PropertyGridView)GridEntryHost).AccessibilityGetGridEntryChildID(this); - if (id >= 0) { - PropertyGridView.PropertyGridViewAccessibleObject gridAccObj = + if (id >= 0) + { + PropertyGridView.PropertyGridViewAccessibleObject gridAccObj = (PropertyGridView.PropertyGridViewAccessibleObject)((PropertyGridView)GridEntryHost).AccessibilityObject; - + gridAccObj.NotifyClients(AccessibleEvents.Focus, id); gridAccObj.NotifyClients(AccessibleEvents.Selection, id); @@ -585,17 +701,22 @@ public bool Focus { /// Returns the label including the object name, and properties. For example, the value /// of the Font size property on a Button called Button1 would be "Button1.Font.Size" /// - public string FullLabel { - get { + public string FullLabel + { + get + { string str = null; - if (parentPE != null) { + if (parentPE != null) + { str = parentPE.FullLabel; } - if (str != null) { + if (str != null) + { str += "."; } - else { + else + { str = string.Empty; } str += this.PropertyLabel; @@ -603,35 +724,45 @@ public string FullLabel { return str; } } - - public override GridItemCollection GridItems { - get { - if (Disposed) { + + public override GridItemCollection GridItems + { + get + { + if (Disposed) + { throw new ObjectDisposedException(SR.GridItemDisposed); } - - if (IsExpandable && childCollection != null && childCollection.Count == 0) { + + if (IsExpandable && childCollection != null && childCollection.Count == 0) + { CreateChildren(); } - + return this.Children; } } - internal virtual PropertyGridView GridEntryHost{ - get{ // ACCESSOR: virtual was missing from this get - if (parentPE != null) { + internal virtual PropertyGridView GridEntryHost + { + get + { // ACCESSOR: virtual was missing from this get + if (parentPE != null) + { return parentPE.GridEntryHost; } return null; } - set { + set + { throw new NotSupportedException(); } } - - public override GridItemType GridItemType { - get { + + public override GridItemType GridItemType + { + get + { return GridItemType.Property; } } @@ -639,8 +770,10 @@ public override GridItemType GridItemType { /// /// Returns true if this GridEntry has a value field in the right hand column. /// - internal virtual bool HasValue { - get { + internal virtual bool HasValue + { + get + { return true; } } @@ -649,73 +782,94 @@ internal virtual bool HasValue { /// Retrieves the keyword that the VS help dynamic help window will /// use when this IPE is selected. /// - public virtual string HelpKeyword { - get { + public virtual string HelpKeyword + { + get + { string keyWord = null; - if (parentPE != null) { + if (parentPE != null) + { keyWord = parentPE.HelpKeyword; } - if (keyWord == null) { + if (keyWord == null) + { keyWord = string.Empty; } return keyWord; } } - - internal virtual string HelpKeywordInternal{ - get { - return this.HelpKeyword; + + internal virtual string HelpKeywordInternal + { + get + { + return this.HelpKeyword; } } - public virtual bool IsCustomPaint { - get { + public virtual bool IsCustomPaint + { + get + { // prevent full flag population if possible. - if ((flags & FL_CHECKED) == 0) { + if ((flags & FL_CHECKED) == 0) + { UITypeEditor typeEd = this.UITypeEditor; - if (typeEd != null) { - if ((this.flags & GridEntry.FLAG_CUSTOM_PAINT) != 0 || - (this.flags & GridEntry.FL_NO_CUSTOM_PAINT) != 0) { - return(this.flags & GridEntry.FLAG_CUSTOM_PAINT) != 0; + if (typeEd != null) + { + if ((this.flags & GridEntry.FLAG_CUSTOM_PAINT) != 0 || + (this.flags & GridEntry.FL_NO_CUSTOM_PAINT) != 0) + { + return (this.flags & GridEntry.FLAG_CUSTOM_PAINT) != 0; } - if (typeEd.GetPaintValueSupported(this)) { + if (typeEd.GetPaintValueSupported(this)) + { flags |= GridEntry.FLAG_CUSTOM_PAINT; return true; } - else { + else + { flags |= GridEntry.FL_NO_CUSTOM_PAINT; return false; - } + } } } - return(this.Flags & GridEntry.FLAG_CUSTOM_PAINT) != 0; + return (this.Flags & GridEntry.FLAG_CUSTOM_PAINT) != 0; } } - - public virtual bool IsExpandable { - get { + + public virtual bool IsExpandable + { + get + { return this.Expandable; } - set { - if (value != GetFlagSet(FL_EXPANDABLE)) { + set + { + if (value != GetFlagSet(FL_EXPANDABLE)) + { SetFlag(FL_EXPANDABLE_FAILED, false); SetFlag(FL_EXPANDABLE, value); } } } - public virtual bool IsTextEditable { - get { + public virtual bool IsTextEditable + { + get + { return this.IsValueEditable && (this.Flags & GridEntry.FLAG_TEXT_EDITABLE) != 0; } } - public virtual bool IsValueEditable { - get { + public virtual bool IsValueEditable + { + get + { return !ForceReadOnly && 0 != (Flags & (GridEntry.FLAG_DROPDOWN_EDITABLE | GridEntry.FLAG_TEXT_EDITABLE | GridEntry.FLAG_CUSTOM_EDITABLE | GridEntry.FLAG_ENUMERABLE)); } } @@ -726,68 +880,86 @@ public virtual bool IsValueEditable { /// return null if there is no component /// responsible for the call. /// - public virtual object Instance { - get { + public virtual object Instance + { + get + { object owner = GetValueOwner(); - if (parentPE != null && owner == null) { + if (parentPE != null && owner == null) + { return parentPE.Instance; } return owner; } } - - public override string Label { - get { + + public override string Label + { + get + { return this.PropertyLabel; } } - + /// /// Retrieves the PropertyDescriptor that is surfacing the given object/ /// - public override PropertyDescriptor PropertyDescriptor { - get { + public override PropertyDescriptor PropertyDescriptor + { + get + { return null; } } - + /// /// Returns the pixel indent of the current GridEntry's label. /// - internal virtual int PropertyLabelIndent { - get { + internal virtual int PropertyLabelIndent + { + get + { int borderWidth = this.GridEntryHost.GetOutlineIconSize() + OUTLINE_ICON_PADDING; - return((propertyDepth + 1) * borderWidth) + 1; + return ((propertyDepth + 1) * borderWidth) + 1; } } - internal virtual Point GetLabelToolTipLocation(int mouseX, int mouseY) { + internal virtual Point GetLabelToolTipLocation(int mouseX, int mouseY) + { return labelTipPoint; } - internal virtual string LabelToolTipText { - get { + internal virtual string LabelToolTipText + { + get + { return this.PropertyLabel; } } - public virtual bool NeedsDropDownButton{ - get { - return(this.Flags & GridEntry.FLAG_DROPDOWN_EDITABLE) != 0; + public virtual bool NeedsDropDownButton + { + get + { + return (this.Flags & GridEntry.FLAG_DROPDOWN_EDITABLE) != 0; } } - public virtual bool NeedsCustomEditorButton{ - get { - return(this.Flags & GridEntry.FLAG_CUSTOM_EDITABLE) != 0 && (IsValueEditable || (Flags & GridEntry.FLAG_READONLY_EDITABLE) !=0); + public virtual bool NeedsCustomEditorButton + { + get + { + return (this.Flags & GridEntry.FLAG_CUSTOM_EDITABLE) != 0 && (IsValueEditable || (Flags & GridEntry.FLAG_READONLY_EDITABLE) != 0); } } - public PropertyGrid OwnerGrid{ - get{ + public PropertyGrid OwnerGrid + { + get + { return this.ownerGrid; } } @@ -796,9 +968,12 @@ public PropertyGrid OwnerGrid{ /// Returns rect that the outline icon (+ or - or arrow) will be drawn into, relative /// to the upper left corner of the GridEntry. /// - public Rectangle OutlineRect { - get { - if (!outlineRect.IsEmpty) { + public Rectangle OutlineRect + { + get + { + if (!outlineRect.IsEmpty) + { return outlineRect; } PropertyGridView gridHost = this.GridEntryHost; @@ -810,42 +985,53 @@ public Rectangle OutlineRect { outlineRect = new Rectangle(left, top, outlineSize, outlineSize); return outlineRect; } - set { + set + { // set property is required to reset cached value when dpi changed. - if (value != outlineRect) { + if (value != outlineRect) + { outlineRect = value; } } } - public virtual GridEntry ParentGridEntry{ - get { + public virtual GridEntry ParentGridEntry + { + get + { return this.parentPE; } - set { + set + { Debug.Assert(value != this, "how can we be our own parent?"); this.parentPE = value; - if (value != null) { - propertyDepth = value.PropertyDepth+1; + if (value != null) + { + propertyDepth = value.PropertyDepth + 1; // Microsoft, why do we do this? - if (this.childCollection != null) { - for (int i = 0; i < childCollection.Count; i++) { + if (this.childCollection != null) + { + for (int i = 0; i < childCollection.Count; i++) + { childCollection.GetEntry(i).ParentGridEntry = this; } } } } } - - public override GridItem Parent { - get { - if (Disposed) { + + public override GridItem Parent + { + get + { + if (Disposed) + { throw new ObjectDisposedException(SR.GridItemDisposed); } - + GridItem parent = this.ParentGridEntry; - + // don't allow walking all the way up to the parent. // //if (parent is IRootGridEntry) { @@ -858,8 +1044,10 @@ public override GridItem Parent { /// /// Returns category name of the current property /// - public virtual string PropertyCategory { - get { + public virtual string PropertyCategory + { + get + { return CategoryAttribute.Default.Category; } } @@ -868,8 +1056,10 @@ public virtual string PropertyCategory { /// Returns "depth" of this property. That is, how many parent's between /// this property and the root property. The root property has a depth of -1. /// - public virtual int PropertyDepth { - get { + public virtual int PropertyDepth + { + get + { return propertyDepth; } } @@ -878,8 +1068,10 @@ public virtual int PropertyDepth { /// /// Returns the description helpstring for this GridEntry. /// - public virtual string PropertyDescription { - get { + public virtual string PropertyDescription + { + get + { return null; } } @@ -888,8 +1080,10 @@ public virtual string PropertyDescription { /// Returns the label of this property. Usually /// this is the property name. /// - public virtual string PropertyLabel { - get { + public virtual string PropertyLabel + { + get + { return null; } } @@ -897,8 +1091,10 @@ public virtual string PropertyLabel { /// /// Returns non-localized name of this property. /// - public virtual string PropertyName { - get { + public virtual string PropertyName + { + get + { return this.PropertyLabel; } } @@ -906,13 +1102,17 @@ public virtual string PropertyName { /// /// Returns the Type of the value of this GridEntry, or null if the value is null. /// - public virtual Type PropertyType { - get { + public virtual Type PropertyType + { + get + { object obj = this.PropertyValue; - if (obj != null) { + if (obj != null) + { return obj.GetType(); } - else { + else + { return null; } } @@ -922,25 +1122,33 @@ public virtual Type PropertyType { /// Gets or sets the value for the property that is represented /// by this GridEntry. /// - public virtual object PropertyValue{ - get { - if (cacheItems != null) { + public virtual object PropertyValue + { + get + { + if (cacheItems != null) + { return cacheItems.lastValue; } return null; } - set { + set + { } } - public virtual bool ShouldRenderPassword { - get { + public virtual bool ShouldRenderPassword + { + get + { return (this.Flags & GridEntry.FLAG_RENDER_PASSWORD) != 0; } } - public virtual bool ShouldRenderReadOnly { - get { + public virtual bool ShouldRenderReadOnly + { + get + { return ForceReadOnly || (0 != (this.Flags & GridEntry.FLAG_RENDER_READONLY) || (!this.IsValueEditable && (0 == (this.Flags & GridEntry.FLAG_READONLY_EDITABLE)))); } } @@ -948,14 +1156,19 @@ public virtual bool ShouldRenderReadOnly { /// /// Returns the type converter for this entry. /// - internal virtual TypeConverter TypeConverter { - get { - if (converter == null) { + internal virtual TypeConverter TypeConverter + { + get + { + if (converter == null) + { object value = this.PropertyValue; - if (value == null) { + if (value == null) + { converter = TypeDescriptor.GetConverter(this.PropertyType); } - else { + else + { converter = TypeDescriptor.GetConverter(value); } } @@ -967,41 +1180,53 @@ internal virtual TypeConverter TypeConverter { /// Returns the type editor for this entry. This may return null if there /// is no type editor. /// - internal virtual UITypeEditor UITypeEditor { - get { - if (editor == null && this.PropertyType != null) { + internal virtual UITypeEditor UITypeEditor + { + get + { + if (editor == null && this.PropertyType != null) + { editor = (UITypeEditor)TypeDescriptor.GetEditor(this.PropertyType, typeof(System.Drawing.Design.UITypeEditor)); } return editor; } } - - public override object Value { - get { + + public override object Value + { + get + { return this.PropertyValue; } // note: we don't do set because of the value class semantics, etc. } - internal Point ValueToolTipLocation { - get { + internal Point ValueToolTipLocation + { + get + { return ShouldRenderPassword ? InvalidPoint : valueTipPoint; } - set{ + set + { valueTipPoint = value; } } - internal int VisibleChildCount { - get{ - if (!Expanded) { + internal int VisibleChildCount + { + get + { + if (!Expanded) + { return 0; } int count = ChildCount; int totalCount = count; - for (int i = 0; i < count; i++) { - totalCount += ChildCollection.GetEntry(i).VisibleChildCount; + for (int i = 0; i < count; i++) + { + totalCount += ChildCollection.GetEntry(i).VisibleChildCount; } return totalCount; } @@ -1012,7 +1237,8 @@ internal int VisibleChildCount { /// Add an event handler to be invoked when the label portion of /// the prop entry is clicked /// - public virtual void AddOnLabelClick(EventHandler h) { + public virtual void AddOnLabelClick(EventHandler h) + { AddEventHandler(EVENT_LABEL_CLICK, h); } @@ -1020,7 +1246,8 @@ public virtual void AddOnLabelClick(EventHandler h) { /// Add an event handler to be invoked when the label portion of /// the prop entry is double /// - public virtual void AddOnLabelDoubleClick(EventHandler h) { + public virtual void AddOnLabelDoubleClick(EventHandler h) + { AddEventHandler(EVENT_LABEL_DBLCLICK, h); } @@ -1028,7 +1255,8 @@ public virtual void AddOnLabelDoubleClick(EventHandler h) { /// Add an event handler to be invoked when the value portion of /// the prop entry is clicked /// - public virtual void AddOnValueClick(EventHandler h) { + public virtual void AddOnValueClick(EventHandler h) + { AddEventHandler(EVENT_VALUE_CLICK, h); } @@ -1037,7 +1265,8 @@ public virtual void AddOnValueClick(EventHandler h) { /// Add an event handler to be invoked when the value portion of /// the prop entry is double-clicked /// - public virtual void AddOnValueDoubleClick(EventHandler h) { + public virtual void AddOnValueDoubleClick(EventHandler h) + { AddEventHandler(EVENT_VALUE_DBLCLICK, h); } @@ -1045,7 +1274,8 @@ public virtual void AddOnValueDoubleClick(EventHandler h) { /// Add an event handler to be invoked when the outline icone portion of /// the prop entry is clicked /// - public virtual void AddOnOutlineClick(EventHandler h) { + public virtual void AddOnOutlineClick(EventHandler h) + { AddEventHandler(EVENT_OUTLINE_CLICK, h); } @@ -1053,39 +1283,48 @@ public virtual void AddOnOutlineClick(EventHandler h) { /// Add an event handler to be invoked when the outline icone portion of /// the prop entry is double clicked /// - public virtual void AddOnOutlineDoubleClick(EventHandler h) { + public virtual void AddOnOutlineDoubleClick(EventHandler h) + { AddEventHandler(EVENT_OUTLINE_DBLCLICK, h); } /// /// Add an event handler to be invoked when the children grid entries are re-created. /// - public virtual void AddOnRecreateChildren(GridEntryRecreateChildrenEventHandler h) { + public virtual void AddOnRecreateChildren(GridEntryRecreateChildrenEventHandler h) + { AddEventHandler(EVENT_RECREATE_CHILDREN, h); } - internal void ClearCachedValues() { + internal void ClearCachedValues() + { ClearCachedValues(true); } - internal void ClearCachedValues(bool clearChildren) { - if (cacheItems != null) { - cacheItems.useValueString = false; - cacheItems.lastValue = null; - cacheItems.useShouldSerialize = false; - } - if (clearChildren) { - for (int i = 0; i < ChildCollection.Count; i++) { - ChildCollection.GetEntry(i).ClearCachedValues(); - } - } + internal void ClearCachedValues(bool clearChildren) + { + if (cacheItems != null) + { + cacheItems.useValueString = false; + cacheItems.lastValue = null; + cacheItems.useShouldSerialize = false; + } + if (clearChildren) + { + for (int i = 0; i < ChildCollection.Count; i++) + { + ChildCollection.GetEntry(i).ClearCachedValues(); + } + } } /// /// Converts the given string of text to a value. /// - public object ConvertTextToValue(string text) { - if (TypeConverter.CanConvertFrom(this, typeof(string))) { + public object ConvertTextToValue(string text) + { + if (TypeConverter.CanConvertFrom(this, typeof(string))) + { return TypeConverter.ConvertFromString(this, text); } return text; @@ -1094,10 +1333,12 @@ public object ConvertTextToValue(string text) { /// /// Create the base prop entries given an object or set of objects /// - internal static IRootGridEntry Create(PropertyGridView view, object[] rgobjs, IServiceProvider baseProvider, IDesignerHost currentHost, PropertyTab tab, PropertySort initialSortType) { + internal static IRootGridEntry Create(PropertyGridView view, object[] rgobjs, IServiceProvider baseProvider, IDesignerHost currentHost, PropertyTab tab, PropertySort initialSortType) + { IRootGridEntry pe = null; - if (rgobjs == null || rgobjs.Length == 0) { + if (rgobjs == null || rgobjs.Length == 0) + { return null; } @@ -1124,104 +1365,126 @@ internal static IRootGridEntry Create(PropertyGridView view, object[] rgobjs, IS /// /// Populates the children of this grid entry /// - protected virtual bool CreateChildren() { + protected virtual bool CreateChildren() + { return CreateChildren(false); } /// /// Populates the children of this grid entry /// - protected virtual bool CreateChildren(bool diffOldChildren) { + protected virtual bool CreateChildren(bool diffOldChildren) + { Debug.Assert(!Disposed, "Why are we creating children after we are disposed?"); - if (!GetFlagSet(FL_EXPANDABLE)) { - if (this.childCollection != null) { + if (!GetFlagSet(FL_EXPANDABLE)) + { + if (this.childCollection != null) + { this.childCollection.Clear(); } - else { + else + { this.childCollection = new GridEntryCollection(this, new GridEntry[0]); } return false; } - if (!diffOldChildren && childCollection != null && childCollection.Count > 0) { + if (!diffOldChildren && childCollection != null && childCollection.Count > 0) + { return true; } - GridEntry [] childProps = GetPropEntries(this, + GridEntry[] childProps = GetPropEntries(this, this.PropertyValue, this.PropertyType); - bool fExpandable = (childProps != null && childProps.Length > 0); + bool fExpandable = (childProps != null && childProps.Length > 0); - if (diffOldChildren && childCollection != null && childCollection.Count > 0) { + if (diffOldChildren && childCollection != null && childCollection.Count > 0) + { bool same = true; - if (childProps.Length == childCollection.Count) { - for (int i = 0; i < childProps.Length; i++) { - if (!childProps[i].NonParentEquals(childCollection[i])) { + if (childProps.Length == childCollection.Count) + { + for (int i = 0; i < childProps.Length; i++) + { + if (!childProps[i].NonParentEquals(childCollection[i])) + { same = false; break; } } } - else { + else + { same = false; } - if (same) { + if (same) + { return true; } } - if (!fExpandable) { - SetFlag(FL_EXPANDABLE_FAILED,true); - if (this.childCollection != null) { + if (!fExpandable) + { + SetFlag(FL_EXPANDABLE_FAILED, true); + if (this.childCollection != null) + { this.childCollection.Clear(); } - else { + else + { this.childCollection = new GridEntryCollection(this, new GridEntry[0]); } - if (this.InternalExpanded) { + if (this.InternalExpanded) + { this.InternalExpanded = false; } } - else { - if (this.childCollection != null) { + else + { + if (this.childCollection != null) + { this.childCollection.Clear(); this.childCollection.AddRange(childProps); } - else { + else + { this.childCollection = new GridEntryCollection(this, childProps); } } return fExpandable; } - public void Dispose() { + public void Dispose() + { Dispose(true); GC.SuppressFinalize(this); } - protected virtual void Dispose(bool disposing) { + protected virtual void Dispose(bool disposing) + { // make sure we don't accidentally // check flags in this state... - flags |= FL_CHECKED; + flags |= FL_CHECKED; SetFlag(FLAG_DISPOSED, true); - + cacheItems = null; converter = null; editor = null; accessibleObject = null; - if (disposing) { + if (disposing) + { DisposeChildren(); } } @@ -1230,15 +1493,18 @@ protected virtual void Dispose(bool disposing) { /// /// Disposes the array of children /// - public virtual void DisposeChildren() { - if (childCollection != null) { + public virtual void DisposeChildren() + { + if (childCollection != null) + { childCollection.Dispose(); childCollection = null; } } - ~GridEntry() { + ~GridEntry() + { Dispose(false); } @@ -1246,9 +1512,12 @@ public virtual void DisposeChildren() { /// /// Invokes the type editor for editing this item. /// - internal virtual void EditPropertyValue(PropertyGridView iva) { - if (UITypeEditor != null) { - try { + internal virtual void EditPropertyValue(PropertyGridView iva) + { + if (UITypeEditor != null) + { + try + { // Since edit value can push a modal loop // there is a chance that this gridentry will be zombied before // it returns. Make sure we're not disposed. @@ -1256,16 +1525,19 @@ internal virtual void EditPropertyValue(PropertyGridView iva) { object originalValue = PropertyValue; object value = UITypeEditor.EditValue(this, (IServiceProvider)(ITypeDescriptorContext)this, originalValue); - if (Disposed) { + if (Disposed) + { return; } // Push the new value back into the property - if (value != originalValue && this.IsValueEditable) { + if (value != originalValue && this.IsValueEditable) + { iva.CommitValue(this, value); } - if (this.InternalExpanded) { + if (this.InternalExpanded) + { // QFE#3299: If edited property is expanded to show sub-properties, then we want to // preserve the expanded states of it and all of its descendants. RecreateChildren() // has logic that is supposed to do this, but which is fundamentally flawed. @@ -1274,7 +1546,8 @@ internal virtual void EditPropertyValue(PropertyGridView iva) { RecreateChildren(); positionData.Restore(GridEntryHost); } - else { + else + { // If edited property has no children or is collapsed, don't need to preserve expanded states. // This limits the scope of the above QFE fix to just those cases where it is actually required. RecreateChildren(); @@ -1299,10 +1572,12 @@ internal virtual void EditPropertyValue(PropertyGridView iva) { /// /// Tests two GridEntries for equality /// - public override bool Equals(object obj) { + public override bool Equals(object obj) + { - if (NonParentEquals(obj)) { - return((GridEntry)obj).ParentGridEntry == this.ParentGridEntry; + if (NonParentEquals(obj)) + { + return ((GridEntry)obj).ParentGridEntry == this.ParentGridEntry; } return false; } @@ -1310,10 +1585,12 @@ public override bool Equals(object obj) { /// /// Searches for a value of a given property for a value editor user /// - public virtual object FindPropertyValue(string propertyName, Type propertyType) { + public virtual object FindPropertyValue(string propertyName, Type propertyType) + { object owner = GetValueOwner(); PropertyDescriptor property = TypeDescriptor.GetProperties(owner)[propertyName]; - if (property != null && property.PropertyType == propertyType) { + if (property != null && property.PropertyType == propertyType) + { return property.GetValue(owner); } @@ -1326,7 +1603,8 @@ public virtual object FindPropertyValue(string propertyName, Type propertyType) /// /// Returns the index of a child GridEntry /// - internal virtual int GetChildIndex(GridEntry pe) { + internal virtual int GetChildIndex(GridEntry pe) + { return this.Children.GetEntry(pe); } @@ -1335,26 +1613,31 @@ internal virtual int GetChildIndex(GridEntry pe) { /// root entry, which is the object being browsed. Walks up the GridEntry tree /// looking for an owner that is an IComponent /// - public virtual IComponent[] GetComponents() { + public virtual IComponent[] GetComponents() + { IComponent component = Component; - if (component != null) { - return new IComponent[] { component}; + if (component != null) + { + return new IComponent[] { component }; } return null; } - protected int GetLabelTextWidth(string labelText, Graphics g, Font f) { + protected int GetLabelTextWidth(string labelText, Graphics g, Font f) + { - if (cacheItems == null) { + if (cacheItems == null) + { cacheItems = new CacheItems(); } - else if (cacheItems.useCompatTextRendering == ownerGrid.UseCompatibleTextRendering && cacheItems.lastLabel == labelText && f.Equals(cacheItems.lastLabelFont)) { + else if (cacheItems.useCompatTextRendering == ownerGrid.UseCompatibleTextRendering && cacheItems.lastLabel == labelText && f.Equals(cacheItems.lastLabelFont)) + { return cacheItems.lastLabelWidth; } - SizeF textSize = PropertyGrid.MeasureTextHelper.MeasureText( this.ownerGrid, g, labelText, f); + SizeF textSize = PropertyGrid.MeasureTextHelper.MeasureText(this.ownerGrid, g, labelText, f); - cacheItems.lastLabelWidth = (int) textSize.Width; + cacheItems.lastLabelWidth = (int)textSize.Width; cacheItems.lastLabel = labelText; cacheItems.lastLabelFont = f; cacheItems.useCompatTextRendering = ownerGrid.UseCompatibleTextRendering; @@ -1362,36 +1645,42 @@ protected int GetLabelTextWidth(string labelText, Graphics g, Font f) { return cacheItems.lastLabelWidth; } - internal int GetValueTextWidth(string valueString, Graphics g, Font f) { + internal int GetValueTextWidth(string valueString, Graphics g, Font f) + { - if (cacheItems == null) { - cacheItems = new CacheItems(); - } - else if (cacheItems.lastValueTextWidth != -1 && cacheItems.lastValueString == valueString && f.Equals(cacheItems.lastValueFont)) { - return cacheItems.lastValueTextWidth; + if (cacheItems == null) + { + cacheItems = new CacheItems(); + } + else if (cacheItems.lastValueTextWidth != -1 && cacheItems.lastValueString == valueString && f.Equals(cacheItems.lastValueFont)) + { + return cacheItems.lastValueTextWidth; } // Value text is rendered using GDI directly (No TextRenderer) but measured/adjusted using GDI+ (since previous releases), so don't use MeasureTextHelper. - cacheItems.lastValueTextWidth = (int) g.MeasureString(valueString, f).Width; + cacheItems.lastValueTextWidth = (int)g.MeasureString(valueString, f).Width; cacheItems.lastValueString = valueString; cacheItems.lastValueFont = f; return cacheItems.lastValueTextWidth; } // To check if text contains multiple lines // - internal bool GetMultipleLines(string valueString) { + internal bool GetMultipleLines(string valueString) + { - if (valueString.IndexOf('\n') > 0 || valueString.IndexOf('\r') > 0 ) + if (valueString.IndexOf('\n') > 0 || valueString.IndexOf('\r') > 0) return true; - else + else return false; } /// /// Gets the owner of the current value. This is usually the value of the /// root entry, which is the object being browsed /// - public virtual object GetValueOwner() { - if (parentPE == null) { + public virtual object GetValueOwner() + { + if (parentPE == null) + { return this.PropertyValue; } @@ -1402,10 +1691,12 @@ public virtual object GetValueOwner() { /// Gets the owners of the current value. This is usually the value of the /// root entry, which is the objects being browsed for a multiselect item /// - public virtual object[] GetValueOwners() { + public virtual object[] GetValueOwners() + { object owner = GetValueOwner(); - if (owner != null) { - return new object[] { owner}; + if (owner != null) + { + return new object[] { owner }; } return null; } @@ -1414,7 +1705,8 @@ public virtual object[] GetValueOwners() { /// Gets the owner of the current value. This is usually the value of the /// root entry, which is the object being browsed /// - public virtual object GetChildValueOwner(GridEntry childEntry) { + public virtual object GetChildValueOwner(GridEntry childEntry) + { /*// make sure this is one of our children int index = GetChildIndex(childEntry); @@ -1432,40 +1724,48 @@ public virtual object GetChildValueOwner(GridEntry childEntry) { /// /// Returns a string with info about the currently selected GridEntry /// - public virtual string GetTestingInfo() { + public virtual string GetTestingInfo() + { string str = "object = ("; string textVal = GetPropertyTextValue(); - if (textVal == null) { + if (textVal == null) + { textVal = "(null)"; } - else { + else + { // make sure we clear any embedded nulls textVal = textVal.Replace((char)0, ' '); } Type type = this.PropertyType; - if (type==null) { + if (type == null) + { type = typeof(object); } str += this.FullLabel; - str += "), property = (" + this.PropertyLabel + "," + type.AssemblyQualifiedName + "), value = " + "[" + textVal + "], expandable = " + this.Expandable.ToString() + ", readOnly = " + ShouldRenderReadOnly;; + str += "), property = (" + this.PropertyLabel + "," + type.AssemblyQualifiedName + "), value = " + "[" + textVal + "], expandable = " + this.Expandable.ToString() + ", readOnly = " + ShouldRenderReadOnly; + ; return str; } /// /// Retrieves the type of the value for this GridEntry /// - public virtual Type GetValueType() { + public virtual Type GetValueType() + { return this.PropertyType; } /// /// Returns the child GridEntries for this item. /// - protected virtual GridEntry[] GetPropEntries(GridEntry peParent, object obj, Type objType) { + protected virtual GridEntry[] GetPropEntries(GridEntry peParent, object obj, Type objType) + { // we don't want to create subprops for null objects. - if (obj == null) { + if (obj == null) + { return null; } @@ -1612,7 +1912,8 @@ protected virtual GridEntry[] GetPropEntries(GridEntry peParent, object obj, Typ catch (Exception e) { #if DEBUG - if (PbrsAssertPropsSwitch.Enabled) { + if (PbrsAssertPropsSwitch.Enabled) + { // Checked builds are not giving us enough information here. So, output as much stuff as // we can. System.Text.StringBuilder b = new System.Text.StringBuilder(); @@ -1638,7 +1939,8 @@ protected virtual GridEntry[] GetPropEntries(GridEntry peParent, object obj, Typ /// /// Resets the current item /// - public virtual void ResetPropertyValue() { + public virtual void ResetPropertyValue() + { NotifyValue(NOTIFY_RESET); Refresh(); } @@ -1673,14 +1975,16 @@ public virtual bool CanSetReadOnlyPropertyValue() { /// /// Returns if the property can be reset /// - public virtual bool CanResetPropertyValue() { + public virtual bool CanResetPropertyValue() + { return NotifyValue(NOTIFY_CAN_RESET); } /// /// Called when the item is double clicked. /// - public virtual bool DoubleClickPropertyValue() { + public virtual bool DoubleClickPropertyValue() + { return NotifyValue(NOTIFY_DBL_CLICK); } @@ -1688,14 +1992,16 @@ public virtual bool DoubleClickPropertyValue() { /// /// Returns the text value of this property. /// - public virtual string GetPropertyTextValue() { + public virtual string GetPropertyTextValue() + { return GetPropertyTextValue(this.PropertyValue); } /// /// Returns the text value of this property. /// - public virtual string GetPropertyTextValue(object value) { + public virtual string GetPropertyTextValue(object value) + { string str = null; TypeConverter converter = TypeConverter; @@ -1708,7 +2014,8 @@ public virtual string GetPropertyTextValue(object value) { Debug.Fail("Bad Type Converter! " + t.GetType().Name + ", " + t.Message + "," + converter.ToString(), t.ToString()); } - if (str == null) { + if (str == null) + { str = string.Empty; } return str; @@ -1717,9 +2024,11 @@ public virtual string GetPropertyTextValue(object value) { /// /// Returns the text values of this property. /// - public virtual object[] GetPropertyValueList() { + public virtual object[] GetPropertyValueList() + { ICollection values = TypeConverter.GetStandardValues(this); - if (values != null) { + if (values != null) + { object[] valueArray = new object[values.Count]; values.CopyTo(valueArray, 0); return valueArray; @@ -1727,32 +2036,36 @@ public virtual object[] GetPropertyValueList() { return new object[0]; } - public override int GetHashCode() { + public override int GetHashCode() + { // These can be null, so workaround giving hashcode = 0 for null objects. object label = this.PropertyLabel; object type = this.PropertyType; - uint h1 = (uint)((label == null) ? 0 : label.GetHashCode()); - uint h2 = (uint)((type == null) ? 0 : type.GetHashCode()); + uint h1 = (uint)((label == null) ? 0 : label.GetHashCode()); + uint h2 = (uint)((type == null) ? 0 : type.GetHashCode()); uint h3 = (uint)GetType().GetHashCode(); - return(int)(h1 ^ ((h2 << 13) | (h2 >> 19)) ^ ((h3 << 26) | (h3 >> 6))); + return (int)(h1 ^ ((h2 << 13) | (h2 >> 19)) ^ ((h3 << 26) | (h3 >> 6))); } /// /// Checks if a given flag is set /// - protected virtual bool GetFlagSet(int flag) { - return((flag & Flags) != 0); + protected virtual bool GetFlagSet(int flag) + { + return ((flag & Flags) != 0); } - protected Font GetFont(bool boldFont) { + protected Font GetFont(bool boldFont) + { if (boldFont) return GridEntryHost.GetBoldFont(); else return GridEntryHost.GetBaseFont(); } - protected IntPtr GetHfont(bool boldFont) { + protected IntPtr GetHfont(bool boldFont) + { if (boldFont) return GridEntryHost.GetBoldHfont(); else @@ -1764,26 +2077,33 @@ protected IntPtr GetHfont(bool boldFont) { /// return null if the requested service is not /// available. /// - public virtual object GetService(Type serviceType) { - - if (serviceType == typeof(GridItem)) { + public virtual object GetService(Type serviceType) + { + + if (serviceType == typeof(GridItem)) + { return (GridItem)this; } - - if (parentPE != null) { + + if (parentPE != null) + { return parentPE.GetService(serviceType); } return null; } - internal virtual bool NonParentEquals(object obj) { - if (obj == this) return true; - if (obj == null) return false; - if (!(obj is GridEntry)) return false; + internal virtual bool NonParentEquals(object obj) + { + if (obj == this) + return true; + if (obj == null) + return false; + if (!(obj is GridEntry)) + return false; GridEntry pe = (GridEntry)obj; return pe.PropertyLabel.Equals(this.PropertyLabel) && - pe.PropertyType.Equals(this.PropertyType) && pe.PropertyDepth == this.PropertyDepth; + pe.PropertyType.Equals(this.PropertyType) && pe.PropertyDepth == this.PropertyDepth; } @@ -1792,17 +2112,19 @@ internal virtual bool NonParentEquals(object obj) { /// is called by the GridEntry host (the PropertyGridView) when this GridEntry is /// to be painted. /// - public virtual void PaintLabel(System.Drawing.Graphics g, Rectangle rect, Rectangle clipRect, bool selected, bool paintFullLabel) { + public virtual void PaintLabel(System.Drawing.Graphics g, Rectangle rect, Rectangle clipRect, bool selected, bool paintFullLabel) + { PropertyGridView gridHost = this.GridEntryHost; Debug.Assert(gridHost != null, "No propEntryHost"); string strLabel = this.PropertyLabel; - - int borderWidth = gridHost.GetOutlineIconSize()+OUTLINE_ICON_PADDING; + + int borderWidth = gridHost.GetOutlineIconSize() + OUTLINE_ICON_PADDING; // fill the background if necessary Brush bkBrush = selected ? gridHost.GetSelectedItemWithFocusBackBrush(g) : this.GetBackgroundBrush(g); // if we don't have focus, paint with the line color - if (selected && !hasFocus) { + if (selected && !hasFocus) + { bkBrush = gridHost.GetLineBrush(g); } @@ -1815,14 +2137,15 @@ public virtual void PaintLabel(System.Drawing.Graphics g, Rectangle rect, Rectan int stringX = rect.X + this.PropertyLabelIndent; Brush blank = bkBrush; - if (paintFullLabel && (neededWidth >= (rect.Width-(stringX+2)))) { + if (paintFullLabel && (neededWidth >= (rect.Width - (stringX + 2)))) + { int totalWidth = stringX + neededWidth + PropertyGridView.GDIPLUS_SPACE; // 5 = extra needed to ensure text draws completely and isn't clipped. #if PBRS_PAINT_DEBUG blank = Brushes.Green; #endif // blank out the space we're going to use - g.FillRectangle(blank, borderWidth-1, rect.Y, totalWidth-borderWidth+3, rect.Height); + g.FillRectangle(blank, borderWidth - 1, rect.Y, totalWidth - borderWidth + 3, rect.Height); // draw an end line Pen linePen = new Pen(gridHost.GetLineColor()); @@ -1832,7 +2155,8 @@ public virtual void PaintLabel(System.Drawing.Graphics g, Rectangle rect, Rectan // set the new width that we can draw into rect.Width = totalWidth - rect.X; } - else { // Normal case -- no pseudo-tooltip for the label + else + { // Normal case -- no pseudo-tooltip for the label #if PBRS_PAINT_DEBUG blank = Brushes.Red; @@ -1840,52 +2164,59 @@ public virtual void PaintLabel(System.Drawing.Graphics g, Rectangle rect, Rectan // Debug.WriteLine(rect.X.ToString() +" "+ rect.Y.ToString() +" "+ rect.Width.ToString() +" "+ rect.Height.ToString()); g.FillRectangle(blank, rect.X, rect.Y, rect.Width, rect.Height); } - + // draw the border stripe on the left Brush stripeBrush = gridHost.GetLineBrush(g); g.FillRectangle(stripeBrush, rect.X, rect.Y, borderWidth, rect.Height); - - if (selected && hasFocus) { + + if (selected && hasFocus) + { g.FillRectangle(gridHost.GetSelectedItemWithFocusBackBrush(g), stringX, rect.Y, rect.Width - stringX - 1, rect.Height); } - - int maxSpace = Math.Min(rect.Width-stringX-1, labelWidth + PropertyGridView.GDIPLUS_SPACE); + + int maxSpace = Math.Min(rect.Width - stringX - 1, labelWidth + PropertyGridView.GDIPLUS_SPACE); Rectangle textRect = new Rectangle(stringX, rect.Y + 1, maxSpace, rect.Height - 1); - - if (!Rectangle.Intersect(textRect, clipRect).IsEmpty) { + + if (!Rectangle.Intersect(textRect, clipRect).IsEmpty) + { Region oldClip = g.Clip; g.SetClip(textRect); - + //We need to Invert color only if in Highcontrast mode, targeting 4.7.1 and above, Gridcategory and not a developer override. This is required to achieve required contrast ratio. var shouldInvertForHC = colorInversionNeededInHC && (fBold || (selected && !hasFocus)); // Do actual drawing // A brush is needed if using GDI+ only (UseCompatibleTextRendering); if using GDI, only the color is needed. Color textColor = selected && hasFocus ? gridHost.GetSelectedItemWithFocusForeColor() : shouldInvertForHC ? InvertColor(ownerGrid.LineColor) : g.GetNearestColor(this.LabelTextColor); - - if( this.ownerGrid.UseCompatibleTextRendering ) { - using( Brush textBrush = new SolidBrush(textColor)){ + + if (this.ownerGrid.UseCompatibleTextRendering) + { + using (Brush textBrush = new SolidBrush(textColor)) + { StringFormat stringFormat = new StringFormat(StringFormatFlags.NoWrap); stringFormat.Trimming = StringTrimming.None; g.DrawString(strLabel, font, textBrush, textRect, stringFormat); } } - else{ - TextRenderer.DrawText( g, strLabel, font, textRect, textColor, PropertyGrid.MeasureTextHelper.GetTextRendererFlags() ); + else + { + TextRenderer.DrawText(g, strLabel, font, textRect, textColor, PropertyGrid.MeasureTextHelper.GetTextRendererFlags()); } - #if PBRS_PAINT_DEBUG +#if PBRS_PAINT_DEBUG textRect.Width --; textRect.Height--; g.DrawRectangle(new Pen(Color.Blue), textRect); - #endif +#endif g.SetClip(oldClip, CombineMode.Replace); oldClip.Dispose(); // clip is actually copied out. - if (maxSpace <= labelWidth) { - this.labelTipPoint = new Point(stringX+2, rect.Y+1); + if (maxSpace <= labelWidth) + { + this.labelTipPoint = new Point(stringX + 2, rect.Y + 1); } - else { + else + { this.labelTipPoint = InvalidPoint; } } @@ -1901,27 +2232,32 @@ public virtual void PaintLabel(System.Drawing.Graphics g, Rectangle rect, Rectan /// is called by the GridEntry host (the PropertyGridView) when this GridEntry is /// to be painted. /// - public virtual void PaintOutline(System.Drawing.Graphics g, Rectangle r) { + public virtual void PaintOutline(System.Drawing.Graphics g, Rectangle r) + { // draw tree-view glyphs as triangles on Vista and Windows afterword // when Vistual style is enabled - if (GridEntryHost.IsExplorerTreeSupported) { + if (GridEntryHost.IsExplorerTreeSupported) + { // size of Explorer Tree style glyph (triangle) is different from +/- glyph, // so when we change the visual style (such as changing Windows theme), // we need to recaculate outlineRect - if(!lastPaintWithExplorerStyle) { + if (!lastPaintWithExplorerStyle) + { outlineRect = Rectangle.Empty; lastPaintWithExplorerStyle = true; } - PaintOutlineWithExplorerTreeStyle(g, r, (GridEntryHost!=null) ? this.GridEntryHost.HandleInternal: IntPtr.Zero); + PaintOutlineWithExplorerTreeStyle(g, r, (GridEntryHost != null) ? this.GridEntryHost.HandleInternal : IntPtr.Zero); } // draw tree-view glyphs as +/- - else { + else + { // size of Explorer Tree style glyph (triangle) is different from +/- glyph, // so when we change the visual style (such as changing Windows theme), // we need to recaculate outlineRect - if (lastPaintWithExplorerStyle) { + if (lastPaintWithExplorerStyle) + { outlineRect = Rectangle.Empty; lastPaintWithExplorerStyle = false; } @@ -1930,45 +2266,53 @@ public virtual void PaintOutline(System.Drawing.Graphics g, Rectangle r) { } } - private void PaintOutlineWithExplorerTreeStyle(System.Drawing.Graphics g, Rectangle r, IntPtr handle) { - if (this.Expandable) { + private void PaintOutlineWithExplorerTreeStyle(System.Drawing.Graphics g, Rectangle r, IntPtr handle) + { + if (this.Expandable) + { bool fExpanded = this.InternalExpanded; Rectangle outline = this.OutlineRect; // make sure we're in our bounds outline = Rectangle.Intersect(r, outline); - if (outline.IsEmpty) return; + if (outline.IsEmpty) + return; VisualStyleElement element = null; if (fExpanded) element = VisualStyleElement.ExplorerTreeView.Glyph.Opened; else element = VisualStyleElement.ExplorerTreeView.Glyph.Closed; - + // Invert color if it is not overriden by developer. - if (colorInversionNeededInHC) { + if (colorInversionNeededInHC) + { Color textColor = InvertColor(ownerGrid.LineColor); - if (g != null) { + if (g != null) + { Brush b = new SolidBrush(textColor); g.FillRectangle(b, outline); b.Dispose(); } - } + } VisualStyleRenderer explorerTreeRenderer = new VisualStyleRenderer(element); explorerTreeRenderer.DrawBackground(g, outline, handle); } } - private void PaintOutlineWithClassicStyle(System.Drawing.Graphics g, Rectangle r) { + private void PaintOutlineWithClassicStyle(System.Drawing.Graphics g, Rectangle r) + { // draw outline box. - if (this.Expandable) { + if (this.Expandable) + { bool fExpanded = this.InternalExpanded; Rectangle outline = this.OutlineRect; // make sure we're in our bounds outline = Rectangle.Intersect(r, outline); - if (outline.IsEmpty) return; + if (outline.IsEmpty) + return; // draw border area box Brush b = this.GetBackgroundBrush(g); @@ -1976,19 +2320,23 @@ private void PaintOutlineWithClassicStyle(System.Drawing.Graphics g, Rectangle r Color penColor = GridEntryHost.GetTextColor(); // inverting text color to back ground to get required contrast ratio - if (colorInversionNeededInHC) { + if (colorInversionNeededInHC) + { penColor = InvertColor(ownerGrid.LineColor); } - else { + else + { // Filling rectangle as it was in all cases where we do not invert colors. - g.FillRectangle(b, outline); + g.FillRectangle(b, outline); } - - if (penColor.IsSystemColor) { + + if (penColor.IsSystemColor) + { p = SystemPens.FromSystemColor(penColor); } - else { + else + { p = new Pen(penColor); } @@ -1996,16 +2344,18 @@ private void PaintOutlineWithClassicStyle(System.Drawing.Graphics g, Rectangle r // draw horizontal line for +/- int indent = 2; - g.DrawLine(p, outline.X + indent,outline.Y + outline.Height / 2, - outline.X + outline.Width - indent - 1,outline.Y + outline.Height/2); + g.DrawLine(p, outline.X + indent, outline.Y + outline.Height / 2, + outline.X + outline.Width - indent - 1, outline.Y + outline.Height / 2); // draw vertical line to make a + - if (!fExpanded) { - g.DrawLine(p, outline.X + outline.Width/2, outline.Y + indent, - outline.X + outline.Width/2, outline.Y + outline.Height - indent - 1); + if (!fExpanded) + { + g.DrawLine(p, outline.X + outline.Width / 2, outline.Y + indent, + outline.X + outline.Width / 2, outline.Y + outline.Height - indent - 1); } - if (!penColor.IsSystemColor) { + if (!penColor.IsSystemColor) + { p.Dispose(); } } @@ -2016,45 +2366,53 @@ private void PaintOutlineWithClassicStyle(System.Drawing.Graphics g, Rectangle r /// is called by the GridEntry host (the PropertyGridView) when this GridEntry is /// to be painted. /// - public virtual void PaintValue(object val, System.Drawing.Graphics g, Rectangle rect, Rectangle clipRect, PaintValueFlags paintFlags) { + public virtual void PaintValue(object val, System.Drawing.Graphics g, Rectangle rect, Rectangle clipRect, PaintValueFlags paintFlags) + { PropertyGridView gridHost = this.GridEntryHost; Debug.Assert(gridHost != null, "No propEntryHost"); int cPaint = 0; Color textColor = gridHost.GetTextColor(); - if (this.ShouldRenderReadOnly) { + if (this.ShouldRenderReadOnly) + { textColor = GridEntryHost.GrayTextColor; } - + string strValue; - - if ((paintFlags & PaintValueFlags.FetchValue) != PaintValueFlags.None) { - if (cacheItems != null && cacheItems.useValueString) { - strValue = cacheItems.lastValueString; - val = cacheItems.lastValue; - } - else { - val = this.PropertyValue; - strValue = GetPropertyTextValue(val); - if (cacheItems == null) { - cacheItems = new CacheItems(); - } - cacheItems.lastValueString = strValue; - cacheItems.useValueString = true; - cacheItems.lastValueTextWidth = -1; - cacheItems.lastValueFont = null; - cacheItems.lastValue = val; - } - } - else { - strValue = GetPropertyTextValue(val); + + if ((paintFlags & PaintValueFlags.FetchValue) != PaintValueFlags.None) + { + if (cacheItems != null && cacheItems.useValueString) + { + strValue = cacheItems.lastValueString; + val = cacheItems.lastValue; + } + else + { + val = this.PropertyValue; + strValue = GetPropertyTextValue(val); + if (cacheItems == null) + { + cacheItems = new CacheItems(); + } + cacheItems.lastValueString = strValue; + cacheItems.useValueString = true; + cacheItems.lastValueTextWidth = -1; + cacheItems.lastValueFont = null; + cacheItems.lastValue = val; + } + } + else + { + strValue = GetPropertyTextValue(val); } // paint out the main rect using the appropriate brush Brush bkBrush = this.GetBackgroundBrush(g); Debug.Assert(bkBrush != null, "We didn't find a good background brush for PaintValue"); - if ((paintFlags & PaintValueFlags.DrawSelected) != PaintValueFlags.None) { + if ((paintFlags & PaintValueFlags.DrawSelected) != PaintValueFlags.None) + { bkBrush = gridHost.GetSelectedItemWithFocusBackBrush(g); textColor = gridHost.GetSelectedItemWithFocusForeColor(); } @@ -2065,21 +2423,24 @@ public virtual void PaintValue(object val, System.Drawing.Graphics g, Rectangle #endif //g.FillRectangle(blank, rect.X-1, rect.Y, rect.Width+1, rect.Height); g.FillRectangle(blank, clipRect); - - if (IsCustomPaint) { + + if (IsCustomPaint) + { cPaint = gridHost.GetValuePaintIndent(); Rectangle rectPaint = new Rectangle(rect.X + 1, rect.Y + 1, gridHost.GetValuePaintWidth(), gridHost.GetGridEntryHeight() - 2); - - if (!Rectangle.Intersect(rectPaint, clipRect).IsEmpty) { - UITypeEditor uie = UITypeEditor; - if (uie != null) { - uie.PaintValue(new PaintValueEventArgs(this, val, g, rectPaint)); - } - - // paint a border around the area - rectPaint.Width --; - rectPaint.Height--; - g.DrawRectangle(SystemPens.WindowText, rectPaint); + + if (!Rectangle.Intersect(rectPaint, clipRect).IsEmpty) + { + UITypeEditor uie = UITypeEditor; + if (uie != null) + { + uie.PaintValue(new PaintValueEventArgs(this, val, g, rectPaint)); + } + + // paint a border around the area + rectPaint.Width--; + rectPaint.Height--; + g.DrawRectangle(SystemPens.WindowText, rectPaint); } } @@ -2088,10 +2449,11 @@ public virtual void PaintValue(object val, System.Drawing.Graphics g, Rectangle // bold the property if we need to persist it (e.g. it's not the default value) bool valueModified = ((paintFlags & PaintValueFlags.CheckShouldSerialize) != PaintValueFlags.None) && ShouldSerializePropertyValue(); - + // If we have text to paint, paint it - if (strValue != null && strValue.Length > 0) { - + if (strValue != null && strValue.Length > 0) + { + Font f = GetFont(valueModified); if (strValue.Length > maximumLengthOfPropertyString) @@ -2100,45 +2462,50 @@ public virtual void PaintValue(object val, System.Drawing.Graphics g, Rectangle } int textWidth = GetValueTextWidth(strValue, g, f); bool doToolTip = false; - + // To check if text contains multiple lines // - if (textWidth >= rect.Width || GetMultipleLines(strValue)) - doToolTip = true; - - if (Rectangle.Intersect(rect, clipRect).IsEmpty) { - return; + if (textWidth >= rect.Width || GetMultipleLines(strValue)) + doToolTip = true; + + if (Rectangle.Intersect(rect, clipRect).IsEmpty) + { + return; } - + // Do actual drawing - + //strValue = ReplaceCRLF(strValue); // bump the text down 2 pixels and over 1 pixel. - if ((paintFlags & PaintValueFlags.PaintInPlace) != PaintValueFlags.None) { + if ((paintFlags & PaintValueFlags.PaintInPlace) != PaintValueFlags.None) + { rect.Offset(1, 2); } - else { + else + { // only go down one pixel when we're painting in the listbox rect.Offset(1, 1); - } + } Matrix m = g.Transform; IntPtr hdc = g.GetHdc(); IntNativeMethods.RECT lpRect = IntNativeMethods.RECT.FromXYWH(rect.X + (int)m.OffsetX + 2, rect.Y + (int)m.OffsetY - 1, rect.Width - 4, rect.Height); IntPtr hfont = GetHfont(valueModified); - + int oldTextColor = 0; int oldBkColor = 0; Color bkColor = ((paintFlags & PaintValueFlags.DrawSelected) != PaintValueFlags.None) ? GridEntryHost.GetSelectedItemWithFocusBackColor() : GridEntryHost.BackColor; - - try { + + try + { oldTextColor = SafeNativeMethods.SetTextColor(new HandleRef(g, hdc), SafeNativeMethods.RGBToCOLORREF(textColor.ToArgb())); oldBkColor = SafeNativeMethods.SetBkColor(new HandleRef(g, hdc), SafeNativeMethods.RGBToCOLORREF(bkColor.ToArgb())); hfont = SafeNativeMethods.SelectObject(new HandleRef(g, hdc), new HandleRef(null, hfont)); int format = IntNativeMethods.DT_EDITCONTROL | IntNativeMethods.DT_EXPANDTABS | IntNativeMethods.DT_NOCLIP | IntNativeMethods.DT_SINGLELINE | IntNativeMethods.DT_NOPREFIX; - if (gridHost.DrawValuesRightToLeft) { + if (gridHost.DrawValuesRightToLeft) + { format |= IntNativeMethods.DT_RIGHT | IntNativeMethods.DT_RTLREADING; } @@ -2156,38 +2523,46 @@ public virtual void PaintValue(object val, System.Drawing.Graphics g, Rectangle IntUnsafeNativeMethods.DrawText(new HandleRef(g, hdc), strValue, ref lpRect, format); } - finally { + finally + { SafeNativeMethods.SetTextColor(new HandleRef(g, hdc), oldTextColor); SafeNativeMethods.SetBkColor(new HandleRef(g, hdc), oldBkColor); hfont = SafeNativeMethods.SelectObject(new HandleRef(g, hdc), new HandleRef(null, hfont)); g.ReleaseHdcInternal(hdc); } - - - #if PBRS_PAINT_DEBUG + + +#if PBRS_PAINT_DEBUG rect.Width --; rect.Height--; g.DrawRectangle(new Pen(Color.Purple), rect); - #endif - - if (doToolTip) { - this.ValueToolTipLocation = new Point(rect.X+2, rect.Y-1); +#endif + + if (doToolTip) + { + this.ValueToolTipLocation = new Point(rect.X + 2, rect.Y - 1); } - else { - this.ValueToolTipLocation = InvalidPoint; + else + { + this.ValueToolTipLocation = InvalidPoint; } } return; } - public virtual bool OnComponentChanging() { - if (ComponentChangeService != null) { - try { + public virtual bool OnComponentChanging() + { + if (ComponentChangeService != null) + { + try + { ComponentChangeService.OnComponentChanging(GetValueOwner(), PropertyDescriptor); } - catch (CheckoutException coEx) { - if (coEx == CheckoutException.Canceled) { + catch (CheckoutException coEx) + { + if (coEx == CheckoutException.Canceled) + { return false; } throw coEx; @@ -2196,8 +2571,10 @@ public virtual bool OnComponentChanging() { return true; } - public virtual void OnComponentChanged() { - if (ComponentChangeService != null) { + public virtual void OnComponentChanged() + { + if (ComponentChangeService != null) + { ComponentChangeService.OnComponentChanged(GetValueOwner(), PropertyDescriptor, null, null); } } @@ -2207,7 +2584,8 @@ public virtual void OnComponentChanged() { /// Default implmentation fired the event to any listeners, so be sure /// to call base.OnLabelClick(e) if this is overrideen. /// - protected virtual void OnLabelClick(EventArgs e) { + protected virtual void OnLabelClick(EventArgs e) + { RaiseEvent(EVENT_LABEL_CLICK, e); } @@ -2216,47 +2594,57 @@ protected virtual void OnLabelClick(EventArgs e) { /// Default implmentation fired the event to any listeners, so be sure /// to call base.OnLabelDoubleClick(e) if this is overrideen. /// - protected virtual void OnLabelDoubleClick(EventArgs e) { + protected virtual void OnLabelDoubleClick(EventArgs e) + { RaiseEvent(EVENT_LABEL_DBLCLICK, e); } /// /// Called when the GridEntry is clicked. /// - public virtual bool OnMouseClick(int x, int y, int count, MouseButtons button) { + public virtual bool OnMouseClick(int x, int y, int count, MouseButtons button) + { // where are we at? PropertyGridView gridHost = this.GridEntryHost; Debug.Assert(gridHost != null, "No prop entry host!"); // make sure it's the left button - if ((button & MouseButtons.Left) != MouseButtons.Left) { + if ((button & MouseButtons.Left) != MouseButtons.Left) + { return false; } - int labelWidth = gridHost.GetLabelWidth(); + int labelWidth = gridHost.GetLabelWidth(); // are we in the label? - if (x >= 0 && x <= labelWidth) { + if (x >= 0 && x <= labelWidth) + { // are we on the outline? - if (Expandable) { + if (Expandable) + { Rectangle outlineRect = OutlineRect; - if (outlineRect.Contains(x, y)) { - if (count % 2 == 0) { + if (outlineRect.Contains(x, y)) + { + if (count % 2 == 0) + { OnOutlineDoubleClick(EventArgs.Empty); } - else { + else + { OnOutlineClick(EventArgs.Empty); } return true; } } - if (count % 2 == 0) { + if (count % 2 == 0) + { OnLabelDoubleClick(EventArgs.Empty); } - else { + else + { OnLabelClick(EventArgs.Empty); } return true; @@ -2264,11 +2652,14 @@ public virtual bool OnMouseClick(int x, int y, int count, MouseButtons button) { // are we in the value? labelWidth += gridHost.GetSplitterWidth(); - if (x >= labelWidth && x <= labelWidth + gridHost.GetValueWidth()) { - if (count % 2 == 0) { + if (x >= labelWidth && x <= labelWidth + gridHost.GetValueWidth()) + { + if (count % 2 == 0) + { OnValueDoubleClick(EventArgs.Empty); } - else { + else + { OnValueClick(EventArgs.Empty); } return true; @@ -2281,7 +2672,8 @@ public virtual bool OnMouseClick(int x, int y, int count, MouseButtons button) { /// Default implmentation fired the event to any listeners, so be sure /// to call base.OnOutlineClick(e) if this is overrideen. /// - protected virtual void OnOutlineClick(EventArgs e) { + protected virtual void OnOutlineClick(EventArgs e) + { RaiseEvent(EVENT_OUTLINE_CLICK, e); } @@ -2290,7 +2682,8 @@ protected virtual void OnOutlineClick(EventArgs e) { /// Default implmentation fired the event to any listeners, so be sure /// to call base.OnOutlineDoubleClick(e) if this is overrideen. /// - protected virtual void OnOutlineDoubleClick(EventArgs e) { + protected virtual void OnOutlineDoubleClick(EventArgs e) + { RaiseEvent(EVENT_OUTLINE_DBLCLICK, e); } @@ -2299,9 +2692,11 @@ protected virtual void OnOutlineDoubleClick(EventArgs e) { /// Default implmentation fired the event to any listeners, so be sure /// to call base.OnOutlineDoubleClick(e) if this is overrideen. /// - protected virtual void OnRecreateChildren(GridEntryRecreateChildrenEventArgs e) { + protected virtual void OnRecreateChildren(GridEntryRecreateChildrenEventArgs e) + { Delegate handler = GetEventHandler(EVENT_RECREATE_CHILDREN); - if (handler != null) ((GridEntryRecreateChildrenEventHandler)handler)(this, e); + if (handler != null) + ((GridEntryRecreateChildrenEventHandler)handler)(this, e); } /// @@ -2309,7 +2704,8 @@ protected virtual void OnRecreateChildren(GridEntryRecreateChildrenEventArgs e) /// Default implmentation fired the event to any listeners, so be sure /// to call base.OnValueClick(e) if this is overrideen. /// - protected virtual void OnValueClick(EventArgs e) { + protected virtual void OnValueClick(EventArgs e) + { RaiseEvent(EVENT_VALUE_CLICK, e); } @@ -2318,27 +2714,31 @@ protected virtual void OnValueClick(EventArgs e) { /// Default implmentation fired the event to any listeners, so be sure /// to call base.OnValueDoubleClick(e) if this is overrideen. /// - protected virtual void OnValueDoubleClick(EventArgs e) { + protected virtual void OnValueDoubleClick(EventArgs e) + { RaiseEvent(EVENT_VALUE_DBLCLICK, e); } - - internal bool OnValueReturnKey() { + + internal bool OnValueReturnKey() + { return NotifyValue(NOTIFY_RETURN); } /// /// Sets the specified flag /// - protected virtual void SetFlag(int flag, bool fVal) { + protected virtual void SetFlag(int flag, bool fVal) + { SetFlag(flag, (fVal ? flag : 0)); } /// /// Sets the default child of this entry, given a valid value mask. /// - protected virtual void SetFlag(int flag_valid, int flag, bool fVal) { + protected virtual void SetFlag(int flag_valid, int flag, bool fVal) + { SetFlag(flag_valid | flag, flag_valid | (fVal ? flag : 0)); } @@ -2346,20 +2746,25 @@ protected virtual void SetFlag(int flag_valid, int flag, bool fVal) { /// /// Sets the value of a flag /// - protected virtual void SetFlag(int flag, int val) { + protected virtual void SetFlag(int flag, int val) + { Flags = (Flags & ~(flag)) | val; } - - public override bool Select() { - if (Disposed) { + + public override bool Select() + { + if (Disposed) + { return false; } - - try { + + try + { GridEntryHost.SelectedGridEntry = this; return true; } - catch { + catch + { } return false; } @@ -2367,35 +2772,44 @@ public override bool Select() { /// /// Checks if this value should be persisited. /// - internal virtual bool ShouldSerializePropertyValue() { - - if (cacheItems != null) { - if (cacheItems.useShouldSerialize) { - return cacheItems.lastShouldSerialize; + internal virtual bool ShouldSerializePropertyValue() + { + + if (cacheItems != null) + { + if (cacheItems.useShouldSerialize) + { + return cacheItems.lastShouldSerialize; } - else { + else + { cacheItems.lastShouldSerialize = NotifyValue(NOTIFY_SHOULD_PERSIST); cacheItems.useShouldSerialize = true; } } - else { - cacheItems = new CacheItems(); - cacheItems.lastShouldSerialize = NotifyValue(NOTIFY_SHOULD_PERSIST); - cacheItems.useShouldSerialize = true; + else + { + cacheItems = new CacheItems(); + cacheItems.lastShouldSerialize = NotifyValue(NOTIFY_SHOULD_PERSIST); + cacheItems.useShouldSerialize = true; } return cacheItems.lastShouldSerialize; } - private PropertyDescriptor[] SortParenProperties(PropertyDescriptor[] props) { + private PropertyDescriptor[] SortParenProperties(PropertyDescriptor[] props) + { PropertyDescriptor[] newProps = null; int newPos = 0; // first scan the list and move any parentesized properties to the front. - for (int i = 0; i < props.Length; i++) { - if (((ParenthesizePropertyNameAttribute)props[i].Attributes[typeof(ParenthesizePropertyNameAttribute)]).NeedParenthesis) { - if (newProps == null) { + for (int i = 0; i < props.Length; i++) + { + if (((ParenthesizePropertyNameAttribute)props[i].Attributes[typeof(ParenthesizePropertyNameAttribute)]).NeedParenthesis) + { + if (newProps == null) + { newProps = new PropertyDescriptor[props.Length]; } newProps[newPos++] = props[i]; @@ -2405,12 +2819,15 @@ private PropertyDescriptor[] SortParenProperties(PropertyDescriptor[] props) { // second pass, copy any that didn't have the parens. - if (newPos > 0) { - for (int i = 0; i < props.Length; i++) { - if (props[i] != null) { + if (newPos > 0) + { + for (int i = 0; i < props.Length; i++) + { + if (props[i] != null) + { newProps[newPos++] = props[i]; } - } + } props = newProps; } return props; @@ -2419,49 +2836,59 @@ private PropertyDescriptor[] SortParenProperties(PropertyDescriptor[] props) { /// /// Sends a notify message to this GridEntry, and returns the success result /// - internal virtual bool NotifyValueGivenParent(object obj, int type) { + internal virtual bool NotifyValueGivenParent(object obj, int type) + { return false; } /// /// Sends a notify message to the child GridEntry, and returns the success result /// - internal virtual bool NotifyChildValue(GridEntry pe, int type) { - - return pe.NotifyValueGivenParent(pe.GetValueOwner(),type); + internal virtual bool NotifyChildValue(GridEntry pe, int type) + { + + return pe.NotifyValueGivenParent(pe.GetValueOwner(), type); } - internal virtual bool NotifyValue(int type) { - if (parentPE == null) { + internal virtual bool NotifyValue(int type) + { + if (parentPE == null) + { return true; } - else { + else + { return parentPE.NotifyChildValue(this, type); } } - internal void RecreateChildren() { + internal void RecreateChildren() + { RecreateChildren(-1); } - - internal void RecreateChildren(int oldCount) { - + + internal void RecreateChildren(int oldCount) + { + // cause the flags to be rebuilt as well... bool wasExpanded = this.InternalExpanded || oldCount > 0; - - if (oldCount == -1) { + + if (oldCount == -1) + { oldCount = this.VisibleChildCount; } - + ResetState(); - if (oldCount == 0) { + if (oldCount == 0) + { return; } - - foreach(GridEntry child in ChildCollection) { + + foreach (GridEntry child in ChildCollection) + { child.RecreateChildren(); } - + DisposeChildren(); this.InternalExpanded = wasExpanded; OnRecreateChildren(new GridEntryRecreateChildrenEventArgs(oldCount, VisibleChildCount)); @@ -2470,33 +2897,40 @@ internal void RecreateChildren(int oldCount) { /// /// Refresh the current GridEntry's value and it's children /// - public virtual void Refresh() { + public virtual void Refresh() + { Type type = this.PropertyType; - if (type != null && type.IsArray) { + if (type != null && type.IsArray) + { CreateChildren(true); } - if (this.childCollection != null) { - + if (this.childCollection != null) + { + // check to see if the value has changed. // - if (this.InternalExpanded && cacheItems != null && cacheItems.lastValue != null && cacheItems.lastValue != this.PropertyValue) { + if (this.InternalExpanded && cacheItems != null && cacheItems.lastValue != null && cacheItems.lastValue != this.PropertyValue) + { ClearCachedValues(); RecreateChildren(); return; } - else if (this.InternalExpanded) { + else if (this.InternalExpanded) + { // otherwise just do a refresh. IEnumerator childEnum = childCollection.GetEnumerator(); - while (childEnum.MoveNext()) { + while (childEnum.MoveNext()) + { object o = childEnum.Current; Debug.Assert(o != null, "Collection contains a null element. But how? Garbage collector hole? GDI+ corrupting memory?"); - GridEntry e = (GridEntry) o; + GridEntry e = (GridEntry)o; e.Refresh(); } } - else { + else + { DisposeChildren(); } } @@ -2504,30 +2938,37 @@ public virtual void Refresh() { ClearCachedValues(); } - public virtual void RemoveOnLabelClick(EventHandler h) { + public virtual void RemoveOnLabelClick(EventHandler h) + { RemoveEventHandler(EVENT_LABEL_CLICK, h); } - public virtual void RemoveOnLabelDoubleClick(EventHandler h) { + public virtual void RemoveOnLabelDoubleClick(EventHandler h) + { RemoveEventHandler(EVENT_LABEL_DBLCLICK, h); } - public virtual void RemoveOnValueClick(EventHandler h) { + public virtual void RemoveOnValueClick(EventHandler h) + { RemoveEventHandler(EVENT_VALUE_CLICK, h); } - public virtual void RemoveOnValueDoubleClick(EventHandler h) { + public virtual void RemoveOnValueDoubleClick(EventHandler h) + { RemoveEventHandler(EVENT_VALUE_DBLCLICK, h); } - public virtual void RemoveOnOutlineClick(EventHandler h) { + public virtual void RemoveOnOutlineClick(EventHandler h) + { RemoveEventHandler(EVENT_OUTLINE_CLICK, h); } - public virtual void RemoveOnOutlineDoubleClick(EventHandler h) { + public virtual void RemoveOnOutlineDoubleClick(EventHandler h) + { RemoveEventHandler(EVENT_OUTLINE_DBLCLICK, h); } - public virtual void RemoveOnRecreateChildren(GridEntryRecreateChildrenEventHandler h) { + public virtual void RemoveOnRecreateChildren(GridEntryRecreateChildrenEventHandler h) + { RemoveEventHandler(EVENT_RECREATE_CHILDREN, h); } @@ -2539,7 +2980,8 @@ private string ReplaceCRLF(string str) { } */ - protected void ResetState() { + protected void ResetState() + { this.Flags = 0; ClearCachedValues(); } @@ -2547,15 +2989,17 @@ protected void ResetState() { /// /// Sets the value of this GridEntry from text /// - public virtual bool SetPropertyTextValue(string str) { + public virtual bool SetPropertyTextValue(string str) + { bool fChildrenPrior = (childCollection != null && childCollection.Count > 0); this.PropertyValue = ConvertTextToValue(str); CreateChildren(); bool fChildrenAfter = (childCollection != null && childCollection.Count > 0); - return(fChildrenPrior != fChildrenAfter); + return (fChildrenPrior != fChildrenAfter); } - public override string ToString() { + public override string ToString() + { return GetType().FullName + " " + this.PropertyLabel; } @@ -2564,12 +3008,17 @@ public override string ToString() { #if !DONT_SUPPORT_ADD_EVENT_HANDLER private EventEntry eventList; - protected virtual void AddEventHandler(object key, Delegate handler) { + protected virtual void AddEventHandler(object key, Delegate handler) + { // Locking 'this' here is ok since this is an internal class. - lock(this) { - if (handler == null) return; - for (EventEntry e = eventList; e != null; e = e.next) { - if (e.key == key) { + lock (this) + { + if (handler == null) + return; + for (EventEntry e = eventList; e != null; e = e.next) + { + if (e.key == key) + { e.handler = Delegate.Combine(e.handler, handler); return; } @@ -2578,33 +3027,47 @@ protected virtual void AddEventHandler(object key, Delegate handler) { } } - protected virtual void RaiseEvent(object key, EventArgs e) { + protected virtual void RaiseEvent(object key, EventArgs e) + { Delegate handler = GetEventHandler(key); - if (handler != null) ((EventHandler)handler)(this, e); + if (handler != null) + ((EventHandler)handler)(this, e); } - protected virtual Delegate GetEventHandler(object key) { + protected virtual Delegate GetEventHandler(object key) + { // Locking 'this' here is ok since this is an internal class. - lock(this) { - for (EventEntry e = eventList; e != null; e = e.next) { - if (e.key == key) return e.handler; + lock (this) + { + for (EventEntry e = eventList; e != null; e = e.next) + { + if (e.key == key) + return e.handler; } return null; } } - protected virtual void RemoveEventHandler(object key, Delegate handler) { + protected virtual void RemoveEventHandler(object key, Delegate handler) + { // Locking this here is ok since this is an internal class. - lock(this) { - if (handler == null) return; - for (EventEntry e = eventList, prev = null; e != null; prev = e, e = e.next) { - if (e.key == key) { + lock (this) + { + if (handler == null) + return; + for (EventEntry e = eventList, prev = null; e != null; prev = e, e = e.next) + { + if (e.key == key) + { e.handler = Delegate.Remove(e.handler, handler); - if (e.handler == null) { - if (prev == null) { + if (e.handler == null) + { + if (prev == null) + { eventList = e.next; } - else { + else + { prev.next = e.next; } } @@ -2614,18 +3077,21 @@ protected virtual void RemoveEventHandler(object key, Delegate handler) { } } - protected virtual void RemoveEventHandlers() { + protected virtual void RemoveEventHandlers() + { eventList = null; } /// /// - private sealed class EventEntry { + private sealed class EventEntry + { internal EventEntry next; internal object key; internal Delegate handler; - internal EventEntry(EventEntry next, object key, Delegate handler) { + internal EventEntry(EventEntry next, object key, Delegate handler) + { this.next = next; this.key = key; this.handler = handler; @@ -2634,63 +3100,81 @@ internal EventEntry(EventEntry next, object key, Delegate handler) { #endif [ComVisible(true)] - public class GridEntryAccessibleObject : AccessibleObject { + public class GridEntryAccessibleObject : AccessibleObject + { protected GridEntry owner = null; private delegate void SelectDelegate(AccessibleSelection flags); private int[] runtimeId = null; // Used by UIAutomation - public GridEntryAccessibleObject(GridEntry owner) : base() { + public GridEntryAccessibleObject(GridEntry owner) : base() + { Debug.Assert(owner != null, "GridEntryAccessibleObject must have a valid owner GridEntry"); this.owner = owner; } - public override Rectangle Bounds { - get { + public override Rectangle Bounds + { + get + { return PropertyGridView.AccessibilityGetGridEntryBounds(owner); } } - public override string DefaultAction { - get { - if (!owner.Expandable) { + public override string DefaultAction + { + get + { + if (!owner.Expandable) + { return base.DefaultAction; } - else if (owner.Expanded) { + else if (owner.Expanded) + { return SR.AccessibleActionCollapse; } - else { + else + { return SR.AccessibleActionExpand; } } } - public override string Description { - get { + public override string Description + { + get + { return owner.PropertyDescription; } } - public override string Help { - get { + public override string Help + { + get + { return owner.PropertyDescription; } } - /// + /// /// Request to return the element in the specified direction. /// /// Indicates the direction in which to navigate. /// Returns the element in the specified direction. - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - switch(direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { + switch (direction) + { case UnsafeNativeMethods.NavigateDirection.Parent: var parentGridEntry = owner.ParentGridEntry; - if (parentGridEntry != null) { - if (parentGridEntry is SingleSelectRootGridEntry) { + if (parentGridEntry != null) + { + if (parentGridEntry is SingleSelectRootGridEntry) + { return owner.OwnerGrid.GridViewAccessibleObject; } - else { + else + { return parentGridEntry.AccessibilityObject; } } @@ -2708,26 +3192,34 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga /// /// Return the element that is the root node of this fragment of UI. /// - internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot { - get { + internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot + { + get + { return (PropertyGridView.PropertyGridViewAccessibleObject)Parent; } } #region IAccessibleEx - patterns and properties - internal override bool IsIAccessibleExSupported() { - if (owner.Expandable) { + internal override bool IsIAccessibleExSupported() + { + if (owner.Expandable) + { return true; } - else { + else + { return false; } } - internal override int[] RuntimeId { - get { - if (runtimeId == null) { + internal override int[] RuntimeId + { + get + { + if (runtimeId == null) + { // we need to provide a unique ID // others are implementing this in the same manner // first item is static - 0x2a @@ -2745,8 +3237,10 @@ internal override int[] RuntimeId { } } - internal override object GetPropertyValue(int propertyID) { - switch (propertyID) { + internal override object GetPropertyValue(int propertyID) + { + switch (propertyID) + { case NativeMethods.UIA_NamePropertyId: return Name; case NativeMethods.UIA_ControlTypePropertyId: @@ -2759,7 +3253,8 @@ internal override object GetPropertyValue(int propertyID) { return (Object)IsPatternSupported(NativeMethods.UIA_ExpandCollapsePatternId); } - switch (propertyID) { + switch (propertyID) + { case NativeMethods.UIA_AccessKeyPropertyId: return string.Empty; case NativeMethods.UIA_HasKeyboardFocusPropertyId: @@ -2785,38 +3280,49 @@ internal override object GetPropertyValue(int propertyID) { } } - internal override bool IsPatternSupported(int patternId) { + internal override bool IsPatternSupported(int patternId) + { if (owner.Expandable && - patternId == NativeMethods.UIA_ExpandCollapsePatternId) { + patternId == NativeMethods.UIA_ExpandCollapsePatternId) + { return true; } if (patternId == NativeMethods.UIA_InvokePatternId || - patternId == NativeMethods.UIA_LegacyIAccessiblePatternId) { + patternId == NativeMethods.UIA_LegacyIAccessiblePatternId) + { return true; } return false; } - internal override void Expand() { - if (owner.Expandable && owner.Expanded == false) { + internal override void Expand() + { + if (owner.Expandable && owner.Expanded == false) + { owner.Expanded = true; } } - internal override void Collapse() { - if (owner.Expandable && owner.Expanded == true) { + internal override void Collapse() + { + if (owner.Expandable && owner.Expanded == true) + { owner.Expanded = false; } } - internal override UnsafeNativeMethods.ExpandCollapseState ExpandCollapseState { - get { - if (owner.Expandable) { + internal override UnsafeNativeMethods.ExpandCollapseState ExpandCollapseState + { + get + { + if (owner.Expandable) + { return owner.Expanded ? UnsafeNativeMethods.ExpandCollapseState.Expanded : UnsafeNativeMethods.ExpandCollapseState.Collapsed; } - else { + else + { return UnsafeNativeMethods.ExpandCollapseState.LeafNode; } } @@ -2824,41 +3330,53 @@ internal override UnsafeNativeMethods.ExpandCollapseState ExpandCollapseState { #endregion - public override void DoDefaultAction() { + public override void DoDefaultAction() + { owner.OnOutlineClick(EventArgs.Empty); } - public override string Name { - get { + public override string Name + { + get + { return owner.PropertyLabel; } } - public override AccessibleObject Parent { - get { - return((Control)this.owner.GridEntryHost).AccessibilityObject; + public override AccessibleObject Parent + { + get + { + return ((Control)this.owner.GridEntryHost).AccessibilityObject; } } - private PropertyGridView PropertyGridView { - get { - return(PropertyGridView)((PropertyGridView.PropertyGridViewAccessibleObject)Parent).Owner; + private PropertyGridView PropertyGridView + { + get + { + return (PropertyGridView)((PropertyGridView.PropertyGridViewAccessibleObject)Parent).Owner; } } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { return AccessibleRole.Cell; } } - public override AccessibleStates State { - get { + public override AccessibleStates State + { + get + { AccessibleStates state = AccessibleStates.Selectable | AccessibleStates.Focusable; // Determine focus // - if (owner.Focus) { + if (owner.Focus) + { state |= AccessibleStates.Focused; } @@ -2866,30 +3384,36 @@ public override AccessibleStates State { // Debug.Assert(Parent != null, "GridEntry AO does not have a parent AO"); PropertyGridView.PropertyGridViewAccessibleObject parent = (PropertyGridView.PropertyGridViewAccessibleObject)Parent; - if (parent.GetSelected() == this) { + if (parent.GetSelected() == this) + { state |= AccessibleStates.Selected; } - + // Determine expanded/collapsed state // - if (owner.Expandable) { - if (owner.Expanded) { + if (owner.Expandable) + { + if (owner.Expanded) + { state |= AccessibleStates.Expanded; } - else { + else + { state |= AccessibleStates.Collapsed; } } // Determine readonly/editable state // - if (owner.ShouldRenderReadOnly) { + if (owner.ShouldRenderReadOnly) + { state |= AccessibleStates.ReadOnly; } // Determine password state // - if (owner.ShouldRenderPassword) { + if (owner.ShouldRenderPassword) + { state |= AccessibleStates.Protected; } @@ -2897,26 +3421,32 @@ public override AccessibleStates State { } } - public override string Value { - get { + public override string Value + { + get + { return owner.GetPropertyTextValue(); } - set { + set + { owner.SetPropertyTextValue(value); - } + } } /// /// Returns the currently focused child, if any. /// Returns this if the object itself is focused. /// - public override AccessibleObject GetFocused() { + public override AccessibleObject GetFocused() + { - if (owner.Focus) { + if (owner.Focus) + { return this; } - else { + else + { return null; } } @@ -2925,12 +3455,14 @@ public override AccessibleObject GetFocused() { /// /// Navigate to the next or previous grid entry. /// - public override AccessibleObject Navigate(AccessibleNavigation navdir) { + public override AccessibleObject Navigate(AccessibleNavigation navdir) + { PropertyGridView.PropertyGridViewAccessibleObject parent = (PropertyGridView.PropertyGridViewAccessibleObject)Parent; - switch (navdir) { + switch (navdir) + { case AccessibleNavigation.Down: case AccessibleNavigation.Right: case AccessibleNavigation.Next: @@ -2952,97 +3484,116 @@ public override AccessibleObject Navigate(AccessibleNavigation navdir) { } - public override void Select(AccessibleSelection flags) { + public override void Select(AccessibleSelection flags) + { // make sure we're on the right thread. // - if (PropertyGridView.InvokeRequired) { - PropertyGridView.Invoke(new SelectDelegate(this.Select), new object[]{flags}); + if (PropertyGridView.InvokeRequired) + { + PropertyGridView.Invoke(new SelectDelegate(this.Select), new object[] { flags }); return; } // Focus the PropertyGridView window // - if ( (flags & AccessibleSelection.TakeFocus) == AccessibleSelection.TakeFocus) { + if ((flags & AccessibleSelection.TakeFocus) == AccessibleSelection.TakeFocus) + { bool focused = PropertyGridView.Focus(); } // Select the grid entry // - if ( (flags & AccessibleSelection.TakeSelection) == AccessibleSelection.TakeSelection) { + if ((flags & AccessibleSelection.TakeSelection) == AccessibleSelection.TakeSelection) + { PropertyGridView.AccessibilitySelect(this.owner); } } - internal override void SetFocus() { + internal override void SetFocus() + { base.SetFocus(); RaiseAutomationEvent(NativeMethods.UIA_AutomationFocusChangedEventId); } } - public class DisplayNameSortComparer : IComparer { - public int Compare(object left, object right) { - // review: (Microsoft) Is CurrentCulture correct here? This was already reviewed as invariant... + public class DisplayNameSortComparer : IComparer + { + public int Compare(object left, object right) + { + // review: (Microsoft) Is CurrentCulture correct here? This was already reviewed as invariant... return string.Compare(((PropertyDescriptor)left).DisplayName, ((PropertyDescriptor)right).DisplayName, true, CultureInfo.CurrentCulture); } } } - internal class AttributeTypeSorter : IComparer{ + internal class AttributeTypeSorter : IComparer + { private static IDictionary typeIds; - private static string GetTypeIdString(Attribute a) { + private static string GetTypeIdString(Attribute a) + { string result; object typeId = a.TypeId; - if (typeId == null) { - Debug.Fail("Attribute '" + a.GetType().FullName + "' does not have a typeid."); + if (typeId == null) + { + Debug.Fail("Attribute '" + a.GetType().FullName + "' does not have a typeid."); return ""; } - if (typeIds == null) { + if (typeIds == null) + { typeIds = new Hashtable(); result = null; } - else { + else + { result = typeIds[typeId] as string; } - if (result == null) { + if (result == null) + { result = typeId.ToString(); typeIds[typeId] = result; } return result; } - public int Compare(object obj1, object obj2) { + public int Compare(object obj1, object obj2) + { Attribute a1 = obj1 as Attribute; Attribute a2 = obj2 as Attribute; - - if (a1 == null && a2 == null) { + + if (a1 == null && a2 == null) + { return 0; } - else if (a1 == null) { + else if (a1 == null) + { return -1; } - else if (a2 == null) { + else if (a2 == null) + { return 1; } return string.Compare(AttributeTypeSorter.GetTypeIdString(a1), AttributeTypeSorter.GetTypeIdString(a2), false, CultureInfo.InvariantCulture); } } - + internal delegate void GridEntryRecreateChildrenEventHandler(object sender, GridEntryRecreateChildrenEventArgs rce); - - internal class GridEntryRecreateChildrenEventArgs : EventArgs { + + internal class GridEntryRecreateChildrenEventArgs : EventArgs + { public readonly int OldChildCount; public readonly int NewChildCount; - - public GridEntryRecreateChildrenEventArgs(int oldCount, int newCount) { + + public GridEntryRecreateChildrenEventArgs(int oldCount, int newCount) + { this.OldChildCount = oldCount; this.NewChildCount = newCount; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridErrorDlg.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridErrorDlg.cs index 216cbacde31..21717cc3b33 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridErrorDlg.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridErrorDlg.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.PropertyGridInternal { +namespace System.Windows.Forms.PropertyGridInternal +{ using System.Runtime.Serialization.Formatters; using System.Threading; using System.Runtime.InteropServices; @@ -11,16 +12,16 @@ namespace System.Windows.Forms.PropertyGridInternal { using System.Diagnostics.CodeAnalysis; using System.Globalization; using System; - using System.Collections; + using System.Collections; using System.Windows.Forms; using System.Windows.Forms.ComponentModel; - using System.Windows.Forms.Design; + using System.Windows.Forms.Design; using System.ComponentModel.Design; using System.IO; using System.Drawing; using Microsoft.Win32; using Message = System.Windows.Forms.Message; - using System.Drawing.Drawing2D; + using System.Drawing.Drawing2D; /// /// Implements a dialog that is displayed when an unhandled exception occurs in @@ -29,7 +30,8 @@ namespace System.Windows.Forms.PropertyGridInternal { /// Use caution and check at all DPI scaling factors if adding a new message /// to be displayed in the top pane. /// - internal class GridErrorDlg : Form { + internal class GridErrorDlg : Form + { private TableLayoutPanel overarchingTableLayoutPanel; private TableLayoutPanel buttonTableLayoutPanel; private PictureBox pictureBox; @@ -46,22 +48,28 @@ internal class GridErrorDlg : Form { private bool detailsButtonExpanded = false; - public bool DetailsButtonExpanded { - get { + public bool DetailsButtonExpanded + { + get + { return detailsButtonExpanded; } } - public string Details { - set { + public string Details + { + set + { this.details.Text = value; } } - - public string Message { - set { - this.lblMessage.Text = value; + + public string Message + { + set + { + this.lblMessage.Text = value; } } @@ -69,21 +77,26 @@ public string Message { SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // We use " " for the text so we leave a small amount of test. // So we don't have to localize it. ] - public GridErrorDlg(PropertyGrid owner) { + public GridErrorDlg(PropertyGrid owner) + { ownerGrid = owner; expandImage = DpiHelper.GetBitmapFromIcon(typeof(ThreadExceptionDialog), "down"); - if (DpiHelper.IsScalingRequired) { + if (DpiHelper.IsScalingRequired) + { DpiHelper.ScaleBitmapLogicalToDevice(ref expandImage); } collapseImage = DpiHelper.GetBitmapFromIcon(typeof(ThreadExceptionDialog), "up"); - if (DpiHelper.IsScalingRequired) { + if (DpiHelper.IsScalingRequired) + { DpiHelper.ScaleBitmapLogicalToDevice(ref collapseImage); } InitializeComponent(); - foreach( Control c in this.Controls ){ - if( c.SupportsUseCompatibleTextRendering ){ + foreach (Control c in this.Controls) + { + if (c.SupportsUseCompatibleTextRendering) + { c.UseCompatibleTextRenderingInt = ownerGrid.UseCompatibleTextRendering; } } @@ -92,7 +105,7 @@ public GridErrorDlg(PropertyGrid owner) { detailsBtn.Text = " " + SR.ExDlgShowDetails; details.AccessibleName = SR.ExDlgDetailsText; - + okBtn.Text = SR.ExDlgOk; cancelBtn.Text = SR.ExDlgCancel; detailsBtn.Image = expandImage; @@ -101,15 +114,18 @@ public GridErrorDlg(PropertyGrid owner) { /// /// Called when the details button is clicked. /// - private void DetailsClick(object sender, EventArgs devent) { + private void DetailsClick(object sender, EventArgs devent) + { int delta = details.Height + 8; - if (details.Visible) { + if (details.Visible) + { detailsBtn.Image = expandImage; detailsButtonExpanded = false; Height -= delta; } - else { + else + { detailsBtn.Image = collapseImage; detailsButtonExpanded = true; details.Width = overarchingTableLayoutPanel.Width - details.Margin.Horizontal; @@ -122,7 +138,8 @@ private void DetailsClick(object sender, EventArgs devent) { AccessibilityNotifyClients(AccessibleEvents.NameChange, -1); details.TabStop = !details.TabStop; - if (details.Visible) { + if (details.Visible) + { details.Focus(); } } @@ -131,14 +148,18 @@ private void DetailsClick(object sender, EventArgs devent) { /// Tells whether the current resources for this dll have been /// localized for a RTL language. /// - private static bool IsRTLResources { - get { + private static bool IsRTLResources + { + get + { return SR.RTL != "RTL_False"; } } - private void InitializeComponent() { - if (IsRTLResources) { + private void InitializeComponent() + { + if (IsRTLResources) + { this.RightToLeft = RightToLeft.Yes; } @@ -300,20 +321,24 @@ private void InitializeComponent() { this.PerformLayout(); } - private void OnButtonClick(object s, EventArgs e) { + private void OnButtonClick(object s, EventArgs e) + { DialogResult = ((Button)s).DialogResult; Close(); } - protected override void OnVisibleChanged(EventArgs e) { - if (this.Visible) { + protected override void OnVisibleChanged(EventArgs e) + { + if (this.Visible) + { // make sure the details button is sized properly // - using (Graphics g = CreateGraphics()) { - SizeF sizef = PropertyGrid.MeasureTextHelper.MeasureText( this.ownerGrid, g, detailsBtn.Text, detailsBtn.Font); - int detailsWidth = (int) Math.Ceiling(sizef.Width); + using (Graphics g = CreateGraphics()) + { + SizeF sizef = PropertyGrid.MeasureTextHelper.MeasureText(this.ownerGrid, g, detailsBtn.Text, detailsBtn.Font); + int detailsWidth = (int)Math.Ceiling(sizef.Width); detailsWidth += detailsBtn.Image.Width; - detailsBtn.Width = (int) Math.Ceiling(detailsWidth * (ownerGrid.UseCompatibleTextRendering ? 1.15f : 1.4f)); + detailsBtn.Width = (int)Math.Ceiling(detailsWidth * (ownerGrid.UseCompatibleTextRendering ? 1.15f : 1.4f)); detailsBtn.Height = okBtn.Height; } @@ -324,14 +349,16 @@ protected override void OnVisibleChanged(EventArgs e) { // Location is relative to its parent, // therefore, we need to take its parent into consideration Control parent = detailsBtn.Parent; - while(parent != null && !(parent is Form)) { + while (parent != null && !(parent is Form)) + { y += parent.Location.Y; parent = parent.Parent; } details.Location = new System.Drawing.Point(x, y); - if (details.Visible) { + if (details.Visible) + { DetailsClick(details, EventArgs.Empty); } } @@ -339,67 +366,87 @@ protected override void OnVisibleChanged(EventArgs e) { } } - internal class DetailsButton: Button { + internal class DetailsButton : Button + { private GridErrorDlg parent; - public DetailsButton(GridErrorDlg form){ + public DetailsButton(GridErrorDlg form) + { parent = form; } - public bool Expanded { - get { - return parent.DetailsButtonExpanded; - } + public bool Expanded + { + get + { + return parent.DetailsButtonExpanded; + } } - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new DetailsButtonAccessibleObject(this); } } - internal class DetailsButtonAccessibleObject: Control.ControlAccessibleObject { - - private DetailsButton ownerItem = null; - - public DetailsButtonAccessibleObject(DetailsButton owner): base(owner) { + internal class DetailsButtonAccessibleObject : Control.ControlAccessibleObject + { + + private DetailsButton ownerItem = null; + + public DetailsButtonAccessibleObject(DetailsButton owner) : base(owner) + { ownerItem = owner; } - internal override bool IsIAccessibleExSupported() { + internal override bool IsIAccessibleExSupported() + { Debug.Assert(ownerItem != null, "AccessibleObject owner cannot be null"); return true; } - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_ControlTypePropertyId) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_ControlTypePropertyId) + { return NativeMethods.UIA_ButtonControlTypeId; } - else { + else + { return base.GetPropertyValue(propertyID); } } - internal override bool IsPatternSupported(int patternId) { - if (patternId == NativeMethods.UIA_ExpandCollapsePatternId) { + internal override bool IsPatternSupported(int patternId) + { + if (patternId == NativeMethods.UIA_ExpandCollapsePatternId) + { return true; } - else { + else + { return base.IsPatternSupported(patternId); } } - internal override UnsafeNativeMethods.ExpandCollapseState ExpandCollapseState { - get { + internal override UnsafeNativeMethods.ExpandCollapseState ExpandCollapseState + { + get + { return ownerItem.Expanded ? UnsafeNativeMethods.ExpandCollapseState.Expanded : UnsafeNativeMethods.ExpandCollapseState.Collapsed; } } - internal override void Expand() { - if (ownerItem !=null && !ownerItem.Expanded) { + internal override void Expand() + { + if (ownerItem != null && !ownerItem.Expanded) + { DoDefaultAction(); } } - internal override void Collapse() { - if (ownerItem != null && ownerItem.Expanded) { + internal override void Collapse() + { + if (ownerItem != null && ownerItem.Expanded) + { DoDefaultAction(); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridToolTip.cs index 696254d02ff..3f6d72c5262 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridToolTip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridToolTip.cs @@ -12,76 +12,90 @@ namespace System.Windows.Forms.PropertyGridInternal using System.Windows.Forms; using Message = System.Windows.Forms.Message; - internal class GridToolTip : Control { - - Control[] controls; - string toolTipText; - NativeMethods.TOOLINFO_T[] toolInfos; - bool dontShow; - Point lastMouseMove = Point.Empty; + internal class GridToolTip : Control + { + + Control[] controls; + string toolTipText; + NativeMethods.TOOLINFO_T[] toolInfos; + bool dontShow; + Point lastMouseMove = Point.Empty; private int maximumToolTipLength = 1000; - internal GridToolTip(Control[] controls) { + internal GridToolTip(Control[] controls) + { this.controls = controls; SetStyle(ControlStyles.UserPaint, false); this.Font = controls[0].Font; this.toolInfos = new NativeMethods.TOOLINFO_T[controls.Length]; - - for (int i = 0; i < controls.Length; i++) { - controls[i].HandleCreated += new EventHandler(this.OnControlCreateHandle); - controls[i].HandleDestroyed += new EventHandler(this.OnControlDestroyHandle); - - if (controls[i].IsHandleCreated) { - SetupToolTip(controls[i]); - } + + for (int i = 0; i < controls.Length; i++) + { + controls[i].HandleCreated += new EventHandler(this.OnControlCreateHandle); + controls[i].HandleDestroyed += new EventHandler(this.OnControlDestroyHandle); + + if (controls[i].IsHandleCreated) + { + SetupToolTip(controls[i]); + } } } - public string ToolTip{ - get { - return toolTipText; + public string ToolTip + { + get + { + return toolTipText; } - set { - if (this.IsHandleCreated || !string.IsNullOrEmpty(value)) { - this.Reset(); - } - - if (value != null && value.Length > maximumToolTipLength) - { - //Let the user know the text was truncated by throwing on an ellipsis - value = value.Substring(0, maximumToolTipLength) + "..."; - } - this.toolTipText = value; - - if (this.IsHandleCreated) { - - bool visible = this.Visible; - - if (visible){ + set + { + if (this.IsHandleCreated || !string.IsNullOrEmpty(value)) + { + this.Reset(); + } + + if (value != null && value.Length > maximumToolTipLength) + { + //Let the user know the text was truncated by throwing on an ellipsis + value = value.Substring(0, maximumToolTipLength) + "..."; + } + this.toolTipText = value; + + if (this.IsHandleCreated) + { + + bool visible = this.Visible; + + if (visible) + { this.Visible = false; - } - - // here's a workaround. if we give - // the tooltip an empty string, it won't come back - // so we just force it hidden instead - // - if (value == null || value.Length == 0){ + } + + // here's a workaround. if we give + // the tooltip an empty string, it won't come back + // so we just force it hidden instead + // + if (value == null || value.Length == 0) + { dontShow = true; value = string.Empty; - } - else{ + } + else + { dontShow = false; - } - - for (int i = 0; i < controls.Length; i++) { + } + + for (int i = 0; i < controls.Length; i++) + { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_UPDATETIPTEXT, 0, GetTOOLINFO(controls[i])); - } + } - if (visible && !dontShow){ + if (visible && !dontShow) + { this.Visible = true; - } - - } + } + + } } } @@ -89,8 +103,10 @@ public string ToolTip{ /// /// The createParams to create the window. /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); icc.dwICC = NativeMethods.ICC_TAB_CLASSES; SafeNativeMethods.InitCommonControlsEx(icc); @@ -104,16 +120,18 @@ protected override CreateParams CreateParams { } } - private NativeMethods.TOOLINFO_T GetTOOLINFO(Control c) { - + private NativeMethods.TOOLINFO_T GetTOOLINFO(Control c) + { + int index = Array.IndexOf(controls, c); - + Debug.Assert(index != -1, "Failed to find control in tooltip array"); - - if (toolInfos[index] == null){ - toolInfos[index] = new NativeMethods.TOOLINFO_T(); - toolInfos[index].cbSize = Marshal.SizeOf(); - toolInfos[index].uFlags |= NativeMethods.TTF_IDISHWND | NativeMethods.TTF_TRANSPARENT | NativeMethods.TTF_SUBCLASS; + + if (toolInfos[index] == null) + { + toolInfos[index] = new NativeMethods.TOOLINFO_T(); + toolInfos[index].cbSize = Marshal.SizeOf(); + toolInfos[index].uFlags |= NativeMethods.TTF_IDISHWND | NativeMethods.TTF_TRANSPARENT | NativeMethods.TTF_SUBCLASS; } toolInfos[index].lpszText = this.toolTipText; toolInfos[index].hwnd = c.Handle; @@ -137,44 +155,54 @@ private bool MouseMoved(Message msg){ } */ - private void OnControlCreateHandle(object sender, EventArgs e){ + private void OnControlCreateHandle(object sender, EventArgs e) + { SetupToolTip((Control)sender); } - private void OnControlDestroyHandle(object sender, EventArgs e){ - if (IsHandleCreated) { + private void OnControlDestroyHandle(object sender, EventArgs e) + { + if (IsHandleCreated) + { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_DELTOOL, 0, GetTOOLINFO((Control)sender)); } } - - protected override void OnHandleCreated(EventArgs e) { + + protected override void OnHandleCreated(EventArgs e) + { base.OnHandleCreated(e); - for (int i = 0; i < controls.Length; i++) { - if (controls[i].IsHandleCreated) { - SetupToolTip(controls[i]); - } + for (int i = 0; i < controls.Length; i++) + { + if (controls[i].IsHandleCreated) + { + SetupToolTip(controls[i]); + } } } - private void SetupToolTip(Control c) { - if (this.IsHandleCreated) { - SafeNativeMethods.SetWindowPos(new HandleRef(this, Handle), NativeMethods.HWND_TOPMOST, - 0, 0, 0, 0, - NativeMethods.SWP_NOMOVE | NativeMethods.SWP_NOSIZE | - NativeMethods.SWP_NOACTIVATE); - - if (0 == (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_ADDTOOL, 0, GetTOOLINFO(c))) { - Debug.Fail("TTM_ADDTOOL failed for " + c.GetType().Name); - } - - // Setting the max width has the added benefit of enabling multiline - // tool tips!) - // - UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_SETMAXTIPWIDTH, 0, SystemInformation.MaxWindowTrackSize.Width); + private void SetupToolTip(Control c) + { + if (this.IsHandleCreated) + { + SafeNativeMethods.SetWindowPos(new HandleRef(this, Handle), NativeMethods.HWND_TOPMOST, + 0, 0, 0, 0, + NativeMethods.SWP_NOMOVE | NativeMethods.SWP_NOSIZE | + NativeMethods.SWP_NOACTIVATE); + + if (0 == (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_ADDTOOL, 0, GetTOOLINFO(c))) + { + Debug.Fail("TTM_ADDTOOL failed for " + c.GetType().Name); + } + + // Setting the max width has the added benefit of enabling multiline + // tool tips!) + // + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_SETMAXTIPWIDTH, 0, SystemInformation.MaxWindowTrackSize.Width); } } - public void Reset(){ + public void Reset() + { // okay, this resets the tooltip state, // which can get broken when we leave the window // then reenter. So we set the tooltip to null, @@ -183,31 +211,36 @@ public void Reset(){ // string oldText = this.ToolTip; this.toolTipText = string.Empty; - for (int i = 0; i < controls.Length; i++) { - if (0 == (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_UPDATETIPTEXT, 0, GetTOOLINFO(controls[i]))) { + for (int i = 0; i < controls.Length; i++) + { + if (0 == (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_UPDATETIPTEXT, 0, GetTOOLINFO(controls[i]))) + { //Debug.Fail("TTM_UPDATETIPTEXT failed for " + controls[i].GetType().Name); - } + } } this.toolTipText = oldText; this.SendMessage(NativeMethods.TTM_UPDATE, 0, 0); } - protected override void WndProc(ref Message msg) { - switch (msg.Msg) { - case Interop.WindowMessages.WM_SHOWWINDOW: - if (unchecked( (int) (long)msg.WParam) != 0 && dontShow){ - msg.WParam = IntPtr.Zero; - } - break; - case Interop.WindowMessages.WM_NCHITTEST: - // When using v6 common controls, the native - // tooltip does not end up returning HTTRANSPARENT all the time, so its TTF_TRANSPARENT - // behavior does not work, ie. mouse events do not fall thru to controls underneath. This - // is due to a combination of old app-specific code in comctl32, functional changes between - // v5 and v6, and the specfic way the property grid drives its tooltip. Workaround is to just - // force HTTRANSPARENT all the time. - msg.Result = (IntPtr) NativeMethods.HTTRANSPARENT; - return; + protected override void WndProc(ref Message msg) + { + switch (msg.Msg) + { + case Interop.WindowMessages.WM_SHOWWINDOW: + if (unchecked((int)(long)msg.WParam) != 0 && dontShow) + { + msg.WParam = IntPtr.Zero; + } + break; + case Interop.WindowMessages.WM_NCHITTEST: + // When using v6 common controls, the native + // tooltip does not end up returning HTTRANSPARENT all the time, so its TTF_TRANSPARENT + // behavior does not work, ie. mouse events do not fall thru to controls underneath. This + // is due to a combination of old app-specific code in comctl32, functional changes between + // v5 and v6, and the specfic way the property grid drives its tooltip. Workaround is to just + // force HTTRANSPARENT all the time. + msg.Result = (IntPtr)NativeMethods.HTTRANSPARENT; + return; } base.WndProc(ref msg); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs index 407548f67be..06df7c77196 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.PropertyGridInternal { +namespace System.Windows.Forms.PropertyGridInternal +{ using System.Text; using System.Diagnostics; @@ -16,7 +17,8 @@ namespace System.Windows.Forms.PropertyGridInternal { using System.Drawing; using Microsoft.Win32; - internal class HotCommands : PropertyGrid.SnappableControl { + internal class HotCommands : PropertyGrid.SnappableControl + { private object component; private DesignerVerb[] verbs; @@ -28,16 +30,21 @@ internal class HotCommands : PropertyGrid.SnappableControl { SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // HotCommands window is not visible // So we don't have to localize its text. ] - internal HotCommands(PropertyGrid owner) : base(owner) { + internal HotCommands(PropertyGrid owner) : base(owner) + { this.Text = "Command Pane"; } - public virtual bool AllowVisible { - get { + public virtual bool AllowVisible + { + get + { return allowVisible; } - set { - if (this.allowVisible != value) { + set + { + if (this.allowVisible != value) + { this.allowVisible = value; if (value && WouldBeVisible) this.Visible = true; @@ -51,24 +58,30 @@ public virtual bool AllowVisible { /// Constructs the new instance of the accessibility object for this control. /// /// The accessibility object for this control. - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new HotCommandsAccessibleObject(this, ownerGrid); } - public override Rectangle DisplayRectangle { - get { + public override Rectangle DisplayRectangle + { + get + { Size sz = ClientSize; return new Rectangle(4, 4, sz.Width - 8, sz.Height - 8); } } - public LinkLabel Label { - get { - if (label == null) { + public LinkLabel Label + { + get + { + if (label == null) + { label = new LinkLabel(); label.Dock = DockStyle.Fill; label.LinkBehavior = LinkBehavior.AlwaysUnderline; - + // use default LinkLabel colors for regular, active, and visited label.DisabledLinkColor = SystemColors.ControlDark; label.LinkClicked += new LinkLabelLinkClickedEventHandler(this.LinkClicked); @@ -79,24 +92,30 @@ public LinkLabel Label { } - public virtual bool WouldBeVisible { - get { + public virtual bool WouldBeVisible + { + get + { return (component != null); } } - public override int GetOptimalHeight(int width) { - if (optimalHeight == -1) { + public override int GetOptimalHeight(int width) + { + if (optimalHeight == -1) + { int lineHeight = (int)(1.5 * Font.Height); int verbCount = 0; - if (verbs != null) { + if (verbs != null) + { verbCount = verbs.Length; } optimalHeight = verbCount * lineHeight + 8; } return optimalHeight; } - public override int SnapHeightRequest(int request) { + public override int SnapHeightRequest(int request) + { return request; } @@ -106,7 +125,8 @@ public override int SnapHeightRequest(int request) { /// internal override bool SupportsUiaProviders => true; - private void LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { + private void LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) + { try { if (!e.Link.Enabled) @@ -123,21 +143,25 @@ private void LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { } } - private void OnCommandChanged(object sender, EventArgs e) { + private void OnCommandChanged(object sender, EventArgs e) + { SetupLabel(); } - - protected override void OnGotFocus(EventArgs e) { + + protected override void OnGotFocus(EventArgs e) + { Label.Focus(); Label.Invalidate(); - } + } - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { base.OnFontChanged(e); optimalHeight = -1; } - internal void SetColors(Color background, Color normalText, Color link, Color activeLink, Color visitedLink, Color disabledLink) { + internal void SetColors(Color background, Color normalText, Color link, Color activeLink, Color visitedLink, Color disabledLink) + { Label.BackColor = background; Label.ForeColor = normalText; Label.LinkColor = link; @@ -146,33 +170,41 @@ internal void SetColors(Color background, Color normalText, Color link, Color ac Label.DisabledLinkColor = disabledLink; } - public void Select(bool forward) { + public void Select(bool forward) + { Label.Focus(); } - public virtual void SetVerbs(object component, DesignerVerb[] verbs) { - if (this.verbs != null) { - for (int i = 0; i < this.verbs.Length; i++){ + public virtual void SetVerbs(object component, DesignerVerb[] verbs) + { + if (this.verbs != null) + { + for (int i = 0; i < this.verbs.Length; i++) + { this.verbs[i].CommandChanged -= new EventHandler(this.OnCommandChanged); } this.component = null; this.verbs = null; } - if (component == null || verbs == null || verbs.Length == 0) { + if (component == null || verbs == null || verbs.Length == 0) + { Visible = false; Label.Links.Clear(); Label.Text = null; } - else { + else + { this.component = component; this.verbs = verbs; - for (int i = 0; i < verbs.Length; i++){ + for (int i = 0; i < verbs.Length; i++) + { verbs[i].CommandChanged += new EventHandler(this.OnCommandChanged); } - if (allowVisible) { + if (allowVisible) + { Visible = true; } SetupLabel(); @@ -181,16 +213,20 @@ public virtual void SetVerbs(object component, DesignerVerb[] verbs) { optimalHeight = -1; } - private void SetupLabel() { + private void SetupLabel() + { Label.Links.Clear(); StringBuilder sb = new StringBuilder(); Point[] links = new Point[verbs.Length]; int charLoc = 0; bool firstVerb = true; - for (int i=0; i [Runtime.InteropServices.ComVisible(true)] - internal class HotCommandsAccessibleObject : Control.ControlAccessibleObject { + internal class HotCommandsAccessibleObject : Control.ControlAccessibleObject + { private PropertyGrid _parentPropertyGrid; @@ -231,7 +271,8 @@ internal class HotCommandsAccessibleObject : Control.ControlAccessibleObject { /// /// The owning HotCommands control. /// The parent PropertyGrid control. - public HotCommandsAccessibleObject(HotCommands owningHotCommands, PropertyGrid parentPropertyGrid) : base(owningHotCommands) { + public HotCommandsAccessibleObject(HotCommands owningHotCommands, PropertyGrid parentPropertyGrid) : base(owningHotCommands) + { _parentPropertyGrid = parentPropertyGrid; } @@ -240,11 +281,14 @@ public HotCommandsAccessibleObject(HotCommands owningHotCommands, PropertyGrid p /// /// Indicates the direction in which to navigate. /// Returns the element in the specified direction. - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { var propertyGridAccessibleObject = _parentPropertyGrid.AccessibilityObject as PropertyGridAccessibleObject; - if (propertyGridAccessibleObject != null) { + if (propertyGridAccessibleObject != null) + { var navigationTarget = propertyGridAccessibleObject.ChildFragmentNavigate(this, direction); - if (navigationTarget != null) { + if (navigationTarget != null) + { return navigationTarget; } } @@ -257,10 +301,14 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga /// /// Identifier indicating the property to return /// Returns a ValInfo indicating whether the element supports this property, or has no value for it. - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_ControlTypePropertyId) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_ControlTypePropertyId) + { return NativeMethods.UIA_PaneControlTypeId; - } else if (propertyID == NativeMethods.UIA_NamePropertyId) { + } + else if (propertyID == NativeMethods.UIA_NamePropertyId) + { return Name; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/ImmutablePropertyDescriptorGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/ImmutablePropertyDescriptorGridEntry.cs index 2c9435ac7a9..923e5008343 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/ImmutablePropertyDescriptorGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/ImmutablePropertyDescriptorGridEntry.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.PropertyGridInternal { +namespace System.Windows.Forms.PropertyGridInternal +{ using System.Runtime.Serialization.Formatters; using System.Diagnostics; @@ -25,21 +26,26 @@ namespace System.Windows.Forms.PropertyGridInternal { // we never go through the property descriptor to change the value, but recreate each // time. // - internal class ImmutablePropertyDescriptorGridEntry : PropertyDescriptorGridEntry { + internal class ImmutablePropertyDescriptorGridEntry : PropertyDescriptorGridEntry + { internal ImmutablePropertyDescriptorGridEntry(PropertyGrid ownerGrid, GridEntry peParent, PropertyDescriptor propInfo, bool hide) - : base(ownerGrid, peParent, propInfo, hide) { + : base(ownerGrid, peParent, propInfo, hide) + { } - internal override bool IsPropertyReadOnly { - get { + internal override bool IsPropertyReadOnly + { + get + { return ShouldRenderReadOnly; } } public override object PropertyValue { - get { + get + { return base.PropertyValue; } [SuppressMessage("Microsoft.Security", "CA2102:CatchNonClsCompliantExceptionsInGeneralHandlers")] @@ -55,20 +61,26 @@ public override object PropertyValue IDictionary values = new Hashtable(props.Count); object newObject = null; - for (int i = 0; i < props.Count; i++) { - if (propertyInfo.Name != null && propertyInfo.Name.Equals(props[i].Name)) { + for (int i = 0; i < props.Count; i++) + { + if (propertyInfo.Name != null && propertyInfo.Name.Equals(props[i].Name)) + { values[props[i].Name] = value; } - else { + else + { values[props[i].Name] = props[i].GetValue(owner); } } - try { + try + { newObject = parentConverter.CreateInstance(parentEntry, values); } - catch (Exception e) { - if (string.IsNullOrEmpty(e.Message)) { + catch (Exception e) + { + if (string.IsNullOrEmpty(e.Message)) + { throw new TargetInvocationException(string.Format(SR.ExceptionCreatingObject, InstanceParentGridEntry.PropertyType.FullName, e.ToString()), e); @@ -77,27 +89,34 @@ public override object PropertyValue throw; // rethrow the same exception } - if (newObject != null) { + if (newObject != null) + { parentEntry.PropertyValue = newObject; } } } - internal override bool NotifyValueGivenParent(object obj, int type) { + internal override bool NotifyValueGivenParent(object obj, int type) + { return ParentGridEntry.NotifyValue(type); } - public override bool ShouldRenderReadOnly { - get { + public override bool ShouldRenderReadOnly + { + get + { return InstanceParentGridEntry.ShouldRenderReadOnly; } } - private GridEntry InstanceParentGridEntry { - get { + private GridEntry InstanceParentGridEntry + { + get + { GridEntry parent = this.ParentGridEntry; - if (parent is CategoryGridEntry) { + if (parent is CategoryGridEntry) + { parent = parent.ParentGridEntry; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs index 9a6f783bf83..a584770e702 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.PropertyGridInternal { +namespace System.Windows.Forms.PropertyGridInternal +{ using System.Runtime.Serialization.Formatters; using System.Runtime.Serialization.Formatters.Binary; using System.ComponentModel; @@ -12,21 +13,23 @@ namespace System.Windows.Forms.PropertyGridInternal { using System.IO; using System.Collections; using System.Globalization; - using System.Reflection; + using System.Reflection; using System.ComponentModel.Design; using System.ComponentModel.Design.Serialization; using System.Windows.Forms; using System.Drawing; using Microsoft.Win32; - - internal class MergePropertyDescriptor : PropertyDescriptor { + + internal class MergePropertyDescriptor : PropertyDescriptor + { private PropertyDescriptor[] descriptors; - private enum TriState { - Unknown, - Yes, - No + private enum TriState + { + Unknown, + Yes, + No } private TriState localizable = TriState.Unknown; @@ -35,8 +38,9 @@ private enum TriState { private MultiMergeCollection collection; - - public MergePropertyDescriptor(PropertyDescriptor[] descriptors) : base(descriptors[0].Name, null) { + + public MergePropertyDescriptor(PropertyDescriptor[] descriptors) : base(descriptors[0].Name, null) + { this.descriptors = descriptors; } @@ -48,10 +52,12 @@ public MergePropertyDescriptor(PropertyDescriptor[] descriptors) : base(descript /// is bound to. /// /// - public override Type ComponentType { - get { - return descriptors[0].ComponentType; - } + public override Type ComponentType + { + get + { + return descriptors[0].ComponentType; + } } /// @@ -59,14 +65,18 @@ public override Type ComponentType { /// Gets the type converter for this property. /// /// - public override TypeConverter Converter { - get { + public override TypeConverter Converter + { + get + { return descriptors[0].Converter; } } - public override string DisplayName { - get { + public override string DisplayName + { + get + { return descriptors[0].DisplayName; } } @@ -78,12 +88,17 @@ public override string DisplayName { /// specified in the . /// /// - public override bool IsLocalizable { - get { - if (localizable == TriState.Unknown) { + public override bool IsLocalizable + { + get + { + if (localizable == TriState.Unknown) + { localizable = TriState.Yes; - foreach (PropertyDescriptor pd in descriptors) { - if (!pd.IsLocalizable) { + foreach (PropertyDescriptor pd in descriptors) + { + if (!pd.IsLocalizable) + { localizable = TriState.No; break; } @@ -100,12 +115,17 @@ public override bool IsLocalizable { /// indicating whether this property is read-only. /// /// - public override bool IsReadOnly { - get { - if (readOnly == TriState.Unknown) { + public override bool IsReadOnly + { + get + { + if (readOnly == TriState.Unknown) + { readOnly = TriState.No; - foreach (PropertyDescriptor pd in descriptors) { - if (pd.IsReadOnly) { + foreach (PropertyDescriptor pd in descriptors) + { + if (pd.IsReadOnly) + { readOnly = TriState.Yes; break; } @@ -115,21 +135,25 @@ public override bool IsReadOnly { } } - + /// /// /// When overridden in a derived class, /// gets the type of the property. /// /// - public override Type PropertyType { - get { + public override Type PropertyType + { + get + { return descriptors[0].PropertyType; } } - public PropertyDescriptor this[int index] { - get { + public PropertyDescriptor this[int index] + { + get + { return descriptors[index]; } } @@ -141,20 +165,24 @@ public PropertyDescriptor this[int index] { /// . /// /// - public override bool CanResetValue(object component) { + public override bool CanResetValue(object component) + { Debug.Assert(component is Array, "MergePropertyDescriptor::CanResetValue called with non-array value"); - if (canReset == TriState.Unknown) { - canReset = TriState.Yes; - Array a = (Array)component; - for (int i = 0; i < descriptors.Length; i++) { - if (!descriptors[i].CanResetValue(GetPropertyOwnerForComponent(a, i))) { - canReset = TriState.No; - break; - } - } - - } - return (canReset == TriState.Yes); + if (canReset == TriState.Unknown) + { + canReset = TriState.Yes; + Array a = (Array)component; + for (int i = 0; i < descriptors.Length; i++) + { + if (!descriptors[i].CanResetValue(GetPropertyOwnerForComponent(a, i))) + { + canReset = TriState.No; + break; + } + } + + } + return (canReset == TriState.Yes); } /// @@ -162,17 +190,20 @@ public override bool CanResetValue(object component) { /// always passed to each object. If the object cannot be copied it /// will be returned. /// - private object CopyValue(object value) { + private object CopyValue(object value) + { // null is always OK - if (value == null) { + if (value == null) + { return value; } Type type = value.GetType(); // value types are always copies - if (type.IsValueType) { + if (type.IsValueType) + { return value; } @@ -180,33 +211,39 @@ private object CopyValue(object value) { // ICloneable is the next easiest thing ICloneable clone = value as ICloneable; - if (clone != null) { + if (clone != null) + { clonedValue = clone.Clone(); } // Next, access the type converter - if (clonedValue == null) { + if (clonedValue == null) + { TypeConverter converter = TypeDescriptor.GetConverter(value); - if (converter.CanConvertTo(typeof(InstanceDescriptor))) { + if (converter.CanConvertTo(typeof(InstanceDescriptor))) + { // Instance descriptors provide full fidelity unless // they are marked as incomplete. InstanceDescriptor desc = (InstanceDescriptor)converter.ConvertTo(null, CultureInfo.InvariantCulture, value, typeof(InstanceDescriptor)); - if (desc != null && desc.IsComplete) { + if (desc != null && desc.IsComplete) + { clonedValue = desc.Invoke(); } } // If that didn't work, try conversion to/from string - if (clonedValue == null && converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string))) { + if (clonedValue == null && converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string))) + { object stringRep = converter.ConvertToInvariantString(value); clonedValue = converter.ConvertFromInvariantString((string)stringRep); } } - + // How about serialization? - if (clonedValue == null && type.IsSerializable) { + if (clonedValue == null && type.IsSerializable) + { BinaryFormatter f = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); f.Serialize(ms, value); @@ -214,7 +251,8 @@ private object CopyValue(object value) { clonedValue = f.Deserialize(ms); } - if (clonedValue != null) { + if (clonedValue != null) + { return clonedValue; } @@ -228,15 +266,18 @@ private object CopyValue(object value) { /// array of attributes that you passed to the constructor. /// /// - protected override AttributeCollection CreateAttributeCollection() { + protected override AttributeCollection CreateAttributeCollection() + { return new MergedAttributeCollection(this); } - private object GetPropertyOwnerForComponent(Array a, int i) { + private object GetPropertyOwnerForComponent(Array a, int i) + { object propertyOwner = a.GetValue(i); - if (propertyOwner is ICustomTypeDescriptor) { - propertyOwner = ((ICustomTypeDescriptor) propertyOwner).GetPropertyOwner(descriptors[i]); + if (propertyOwner is ICustomTypeDescriptor) + { + propertyOwner = ((ICustomTypeDescriptor)propertyOwner).GetPropertyOwner(descriptors[i]); } return propertyOwner; } @@ -246,7 +287,8 @@ private object GetPropertyOwnerForComponent(Array a, int i) { /// Gets an editor of the specified type. /// /// - public override object GetEditor(Type editorBaseType) { + public override object GetEditor(Type editorBaseType) + { return descriptors[0].GetEditor(editorBaseType); } @@ -259,59 +301,73 @@ public override object GetEditor(Type editorBaseType) { /// property on a component. /// /// - public override object GetValue(object component) { + public override object GetValue(object component) + { Debug.Assert(component is Array, "MergePropertyDescriptor::GetValue called with non-array value"); bool temp; return GetValue((Array)component, out temp); } - public object GetValue(Array components, out bool allEqual) { + public object GetValue(Array components, out bool allEqual) + { allEqual = true; object obj = descriptors[0].GetValue(GetPropertyOwnerForComponent(components, 0)); - - if (obj is ICollection) { - if (collection == null) { - collection = new MultiMergeCollection((ICollection)obj); - } - else if (collection.Locked) { - return collection; - } - else { - collection.SetItems((ICollection)obj); - } - } - - for (int i = 1; i < descriptors.Length; i++) { + + if (obj is ICollection) + { + if (collection == null) + { + collection = new MultiMergeCollection((ICollection)obj); + } + else if (collection.Locked) + { + return collection; + } + else + { + collection.SetItems((ICollection)obj); + } + } + + for (int i = 1; i < descriptors.Length; i++) + { object objCur = descriptors[i].GetValue(GetPropertyOwnerForComponent(components, i)); - if (collection != null) { - if (!collection.MergeCollection((ICollection)objCur)){ - allEqual = false; - return null; - } + if (collection != null) + { + if (!collection.MergeCollection((ICollection)objCur)) + { + allEqual = false; + return null; + } } else if ((obj == null && objCur == null) || - (obj != null && obj.Equals(objCur))) { - - continue; + (obj != null && obj.Equals(objCur))) + { + + continue; } - else { + else + { allEqual = false; return null; } } - - if (allEqual && collection != null && collection.Count == 0) { + + if (allEqual && collection != null && collection.Count == 0) + { return null; } - + return (collection != null ? collection : obj); } - internal object[] GetValues(Array components) { + internal object[] GetValues(Array components) + { object[] values = new object[components.Length]; - for (int i = 0; i < components.Length; i++) { + for (int i = 0; i < components.Length; i++) + { values[i] = descriptors[i].GetValue(GetPropertyOwnerForComponent(components, i)); } return values; @@ -325,44 +381,54 @@ internal object[] GetValues(Array components) { /// of the component. /// /// - public override void ResetValue(object component) { + public override void ResetValue(object component) + { Debug.Assert(component is Array, "MergePropertyDescriptor::ResetValue called with non-array value"); Array a = (Array)component; - for (int i = 0; i < descriptors.Length; i++) { + for (int i = 0; i < descriptors.Length; i++) + { descriptors[i].ResetValue(GetPropertyOwnerForComponent(a, i)); } } - private void SetCollectionValues(Array a, IList listValue) { - - try { - if (collection != null) { - collection.Locked = true; + private void SetCollectionValues(Array a, IList listValue) + { + + try + { + if (collection != null) + { + collection.Locked = true; } // now we have to copy the value into each property. object[] values = new object[listValue.Count]; - + listValue.CopyTo(values, 0); - - for (int i = 0; i < descriptors.Length; i++) { + + for (int i = 0; i < descriptors.Length; i++) + { IList propList = descriptors[i].GetValue(GetPropertyOwnerForComponent(a, i)) as IList; - if (propList == null) { - continue; + if (propList == null) + { + continue; } - + propList.Clear(); - foreach (object val in values) { + foreach (object val in values) + { propList.Add(val); } } } - finally { - if (collection != null) { - collection.Locked = false; - } + finally + { + if (collection != null) + { + collection.Locked = false; + } } } @@ -373,14 +439,18 @@ private void SetCollectionValues(Array a, IList listValue) { /// the component to a different value. /// /// - public override void SetValue(object component, object value) { + public override void SetValue(object component, object value) + { Debug.Assert(component is Array, "MergePropertyDescriptor::SetValue called with non-array value"); Array a = (Array)component; - if (value is IList && typeof(IList).IsAssignableFrom(PropertyType)) { + if (value is IList && typeof(IList).IsAssignableFrom(PropertyType)) + { SetCollectionValues(a, (IList)value); } - else { - for (int i = 0; i < descriptors.Length; i++) { + else + { + for (int i = 0; i < descriptors.Length; i++) + { object clonedValue = CopyValue(value); descriptors[i].SetValue(GetPropertyOwnerForComponent(a, i), clonedValue); } @@ -395,135 +465,167 @@ public override void SetValue(object component, object value) { /// /// - public override bool ShouldSerializeValue(object component) { + public override bool ShouldSerializeValue(object component) + { Debug.Assert(component is Array, "MergePropertyDescriptor::ShouldSerializeValue called with non-array value"); Array a = (Array)component; - for (int i = 0; i < descriptors.Length; i++) { - if (!descriptors[i].ShouldSerializeValue(GetPropertyOwnerForComponent(a, i))) { + for (int i = 0; i < descriptors.Length; i++) + { + if (!descriptors[i].ShouldSerializeValue(GetPropertyOwnerForComponent(a, i))) + { return false; } } return true; } - private class MultiMergeCollection : ICollection { - + private class MultiMergeCollection : ICollection + { + private object[] items; - private bool locked; - - public MultiMergeCollection(ICollection original) { - SetItems(original); + private bool locked; + + public MultiMergeCollection(ICollection original) + { + SetItems(original); } - + /// /// Retrieves the number of items. /// - public int Count { - get { - if (items != null) { + public int Count + { + get + { + if (items != null) + { return items.Length; } - else { + else + { return 0; } } } - - + + /// /// Prevents the contents of the collection from being re-initialized; /// - public bool Locked { - get { - return locked; - } - set { - this.locked = value; - } + public bool Locked + { + get + { + return locked; + } + set + { + this.locked = value; + } } - object ICollection.SyncRoot { - get { + object ICollection.SyncRoot + { + get + { return this; } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return false; } } - - public void CopyTo(Array array, int index) { - if (items == null) return; - - Array.Copy(items, 0, array, index, items.Length); + + public void CopyTo(Array array, int index) + { + if (items == null) + return; + + Array.Copy(items, 0, array, index, items.Length); } - - public IEnumerator GetEnumerator(){ - if (items != null) { - return items.GetEnumerator(); - } - else { - return new object[0].GetEnumerator(); - } + + public IEnumerator GetEnumerator() + { + if (items != null) + { + return items.GetEnumerator(); + } + else + { + return new object[0].GetEnumerator(); + } } - + /// /// Ensures that the new collection equals the exisitng one. /// Otherwise, it wipes out the contents of the new collection. /// - public bool MergeCollection(ICollection newCollection) { - - if (locked) { - return true; + public bool MergeCollection(ICollection newCollection) + { + + if (locked) + { + return true; } - - if (items.Length != newCollection.Count) { - items = new object[0]; - return false; + + if (items.Length != newCollection.Count) + { + items = new object[0]; + return false; } - + object[] newItems = new object[newCollection.Count]; newCollection.CopyTo(newItems, 0); - for (int i = 0;i < newItems.Length; i++) { - if (((newItems[i] == null) != (items[i] == null)) || - (items[i] != null && !items[i].Equals(newItems[i]))){ - items = new object[0]; - return false; - } - + for (int i = 0; i < newItems.Length; i++) + { + if (((newItems[i] == null) != (items[i] == null)) || + (items[i] != null && !items[i].Equals(newItems[i]))) + { + items = new object[0]; + return false; + } + } return true; } - - public void SetItems(ICollection collection) { - if (locked) { - return; + + public void SetItems(ICollection collection) + { + if (locked) + { + return; } items = new object[collection.Count]; collection.CopyTo(items, 0); } - + } - private class MergedAttributeCollection : AttributeCollection { + private class MergedAttributeCollection : AttributeCollection + { private MergePropertyDescriptor owner; private AttributeCollection[] attributeCollections = null; - private IDictionary foundAttributes = null; - - public MergedAttributeCollection(MergePropertyDescriptor owner) : base((Attribute[])null) { + private IDictionary foundAttributes = null; + + public MergedAttributeCollection(MergePropertyDescriptor owner) : base((Attribute[])null) + { this.owner = owner; } - public override Attribute this[Type attributeType] { - get { + public override Attribute this[Type attributeType] + { + get + { return GetCommonAttribute(attributeType); } } - #if false +#if false private void FullMerge() { Attribute[][] collections = new Attribute[owner.descriptors.Length][]; for (int i = 0; i < owner.descriptors.Length; i++) { @@ -600,43 +702,53 @@ private void FullMerge() { mergedList.CopyTo(mergedAttrs, 0); } - #endif +#endif - private Attribute GetCommonAttribute(Type attributeType) { - if (attributeCollections == null) { + private Attribute GetCommonAttribute(Type attributeType) + { + if (attributeCollections == null) + { attributeCollections = new AttributeCollection[owner.descriptors.Length]; - for (int i = 0; i < owner.descriptors.Length; i++) { + for (int i = 0; i < owner.descriptors.Length; i++) + { attributeCollections[i] = owner.descriptors[i].Attributes; } } - if (attributeCollections.Length == 0) { + if (attributeCollections.Length == 0) + { return GetDefaultAttribute(attributeType); } Attribute value; - if (foundAttributes != null) { + if (foundAttributes != null) + { value = foundAttributes[attributeType] as Attribute; - if (value != null) { + if (value != null) + { return value; } } value = attributeCollections[0][attributeType]; - if (value == null) { + if (value == null) + { return null; } - - for (int i = 1; i < attributeCollections.Length; i++) { + + for (int i = 1; i < attributeCollections.Length; i++) + { Attribute newValue = attributeCollections[i][attributeType]; - if (!value.Equals(newValue)) { + if (!value.Equals(newValue)) + { value = GetDefaultAttribute(attributeType); break; } } - if (foundAttributes == null) { + if (foundAttributes == null) + { foundAttributes = new Hashtable(); } foundAttributes[attributeType] = value; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiPropertyDescriptorGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiPropertyDescriptorGridEntry.cs index eac211518ae..084804143cc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiPropertyDescriptorGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiPropertyDescriptorGridEntry.cs @@ -3,53 +3,63 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.PropertyGridInternal { +namespace System.Windows.Forms.PropertyGridInternal +{ using System.Runtime.Serialization.Formatters; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System; using System.Collections; - using System.Reflection; + using System.Reflection; using System.ComponentModel.Design; using System.Windows.Forms; using System.Drawing; using Microsoft.Win32; - internal class MultiPropertyDescriptorGridEntry : PropertyDescriptorGridEntry { + internal class MultiPropertyDescriptorGridEntry : PropertyDescriptorGridEntry + { private MergePropertyDescriptor mergedPd; - private object[] objs; + private object[] objs; [ SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // GridEntry classes are internal so we have complete // control over who does what in the constructor. ] - public MultiPropertyDescriptorGridEntry(PropertyGrid ownerGrid, GridEntry peParent, object[] objectArray, PropertyDescriptor[] propInfo, bool hide) - : base (ownerGrid, peParent, hide) { + public MultiPropertyDescriptorGridEntry(PropertyGrid ownerGrid, GridEntry peParent, object[] objectArray, PropertyDescriptor[] propInfo, bool hide) + : base(ownerGrid, peParent, hide) + { mergedPd = new MergePropertyDescriptor(propInfo); this.objs = objectArray; base.Initialize(mergedPd); } - public override IContainer Container { - get { + public override IContainer Container + { + get + { IContainer c = null; - foreach (object o in objs) { + foreach (object o in objs) + { IComponent comp = o as IComponent; - if (comp == null) { + if (comp == null) + { c = null; break; } - if (comp.Site != null) { - if (c == null) { + if (comp.Site != null) + { + if (c == null) + { c = comp.Site.Container; continue; } - else if (c == comp.Site.Container) { + else if (c == comp.Site.Container) + { continue; } } @@ -60,27 +70,35 @@ public override IContainer Container { } } - public override bool Expandable { - get { + public override bool Expandable + { + get + { bool fExpandable = GetFlagSet(FL_EXPANDABLE); - if (fExpandable && ChildCollection.Count > 0) { + if (fExpandable && ChildCollection.Count > 0) + { return true; } - if (GetFlagSet(FL_EXPANDABLE_FAILED)) { + if (GetFlagSet(FL_EXPANDABLE_FAILED)) + { return false; } - try { - foreach (object o in mergedPd.GetValues(objs)) { - if (o == null) { + try + { + foreach (object o in mergedPd.GetValues(objs)) + { + if (o == null) + { fExpandable = false; break; } } } - catch { + catch + { fExpandable = false; } @@ -88,8 +106,10 @@ public override bool Expandable { } } - public override object PropertyValue{ - set { + public override object PropertyValue + { + set + { base.PropertyValue = value; RecreateChildren(); @@ -99,14 +119,18 @@ public override object PropertyValue{ } } - protected override bool CreateChildren() { + protected override bool CreateChildren() + { return CreateChildren(false); } - protected override bool CreateChildren(bool diffOldChildren) { - try { + protected override bool CreateChildren(bool diffOldChildren) + { + try + { - if (mergedPd.PropertyType.IsValueType || (Flags & GridEntry.FLAG_IMMUTABLE) != 0) { + if (mergedPd.PropertyType.IsValueType || (Flags & GridEntry.FLAG_IMMUTABLE) != 0) + { return base.CreateChildren(diffOldChildren); } @@ -116,28 +140,34 @@ protected override bool CreateChildren(bool diffOldChildren) { Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose && mergedProps == null, "PropertyGridView: MergedProps returned null!"); - if (mergedProps != null) { + if (mergedProps != null) + { ChildCollection.AddRange(mergedProps); } bool fExpandable = this.Children.Count > 0; - if (!fExpandable) { - SetFlag(GridEntry.FL_EXPANDABLE_FAILED,true); + if (!fExpandable) + { + SetFlag(GridEntry.FL_EXPANDABLE_FAILED, true); } return fExpandable; } - catch { + catch + { return false; } } - public override object GetChildValueOwner(GridEntry childEntry) { - if (mergedPd.PropertyType.IsValueType || (Flags & GridEntry.FLAG_IMMUTABLE) != 0) { + public override object GetChildValueOwner(GridEntry childEntry) + { + if (mergedPd.PropertyType.IsValueType || (Flags & GridEntry.FLAG_IMMUTABLE) != 0) + { return base.GetChildValueOwner(childEntry); } return mergedPd.GetValues(objs); } - public override IComponent[] GetComponents() { + public override IComponent[] GetComponents() + { IComponent[] temp = new IComponent[objs.Length]; Array.Copy(objs, 0, temp, 0, objs.Length); return temp; @@ -146,82 +176,104 @@ public override IComponent[] GetComponents() { /// /// Returns the text value of this property. /// - public override string GetPropertyTextValue(object value) { + public override string GetPropertyTextValue(object value) + { bool allEqual = true; - try{ - if (value == null && mergedPd.GetValue(objs, out allEqual) == null) { - if (!allEqual) { + try + { + if (value == null && mergedPd.GetValue(objs, out allEqual) == null) + { + if (!allEqual) + { return ""; } } } - catch{ + catch + { return ""; } return base.GetPropertyTextValue(value); } - internal override bool NotifyChildValue(GridEntry pe, int type) { + internal override bool NotifyChildValue(GridEntry pe, int type) + { bool success = false; IDesignerHost host = DesignerHost; DesignerTransaction trans = null; - if (host != null) { + if (host != null) + { trans = host.CreateTransaction(); } - try { + try + { success = base.NotifyChildValue(pe, type); } - finally { - if (trans != null) { + finally + { + if (trans != null) + { trans.Commit(); } } return success; } - protected override void NotifyParentChange(GridEntry ge) { + protected override void NotifyParentChange(GridEntry ge) + { // now see if we need to notify the parent(s) up the chain while (ge != null && ge is PropertyDescriptorGridEntry && - ((PropertyDescriptorGridEntry)ge).propertyInfo.Attributes.Contains(NotifyParentPropertyAttribute.Yes)) { + ((PropertyDescriptorGridEntry)ge).propertyInfo.Attributes.Contains(NotifyParentPropertyAttribute.Yes)) + { // find the next parent property with a differnet value owner object owner = ge.GetValueOwner(); // find the next property descriptor with a different parent - while (!(ge is PropertyDescriptorGridEntry) || OwnersEqual(owner, ge.GetValueOwner())) { + while (!(ge is PropertyDescriptorGridEntry) || OwnersEqual(owner, ge.GetValueOwner())) + { ge = ge.ParentGridEntry; - if (ge == null) { + if (ge == null) + { break; } } // fire the change on that owner - if (ge != null) { + if (ge != null) + { owner = ge.GetValueOwner(); IComponentChangeService changeService = ComponentChangeService; - if (changeService != null) { + if (changeService != null) + { Array ownerArray = owner as Array; - if (ownerArray != null) { - for (int i = 0; i < ownerArray.Length; i++) { - PropertyDescriptor pd = ((PropertyDescriptorGridEntry)ge).propertyInfo;; - - if (pd is MergePropertyDescriptor) { + if (ownerArray != null) + { + for (int i = 0; i < ownerArray.Length; i++) + { + PropertyDescriptor pd = ((PropertyDescriptorGridEntry)ge).propertyInfo; + ; + + if (pd is MergePropertyDescriptor) + { pd = ((MergePropertyDescriptor)pd)[i]; } - if (pd != null) { + if (pd != null) + { changeService.OnComponentChanging(ownerArray.GetValue(i), pd); changeService.OnComponentChanged(ownerArray.GetValue(i), pd, null, null); } } } - else { + else + { changeService.OnComponentChanging(owner, ((PropertyDescriptorGridEntry)ge).propertyInfo); changeService.OnComponentChanged(owner, ((PropertyDescriptorGridEntry)ge).propertyInfo, null, null); } @@ -230,50 +282,62 @@ ge is PropertyDescriptorGridEntry && } } - internal override bool NotifyValueGivenParent(object obj, int type) { - if (obj is ICustomTypeDescriptor) { + internal override bool NotifyValueGivenParent(object obj, int type) + { + if (obj is ICustomTypeDescriptor) + { obj = ((ICustomTypeDescriptor)obj).GetPropertyOwner(propertyInfo); } - switch (type) { + switch (type) + { case NOTIFY_RESET: object[] objects = (object[])obj; - if (objects != null && objects.Length > 0) { - + if (objects != null && objects.Length > 0) + { + IDesignerHost host = DesignerHost; DesignerTransaction trans = null; - - if (host != null) { + + if (host != null) + { trans = host.CreateTransaction(string.Format(SR.PropertyGridResetValue, this.PropertyName)); } - try { - + try + { + bool needChangeNotify = !(objects[0] is IComponent) || ((IComponent)objects[0]).Site == null; - if (needChangeNotify) { - if (!OnComponentChanging()) { - if (trans != null) { + if (needChangeNotify) + { + if (!OnComponentChanging()) + { + if (trans != null) + { trans.Cancel(); trans = null; } return false; } } - + this.mergedPd.ResetValue(obj); - - if (needChangeNotify) { + + if (needChangeNotify) + { OnComponentChanged(); } NotifyParentChange(this); } - finally { - if (trans != null) { + finally + { + if (trans != null) + { trans.Commit(); } } - } + } return false; case NOTIFY_DBL_CLICK: case NOTIFY_RETURN: @@ -281,24 +345,29 @@ internal override bool NotifyValueGivenParent(object obj, int type) { Debug.Assert(obj is object[], "Did not get an array of objects!!"); MergePropertyDescriptor mpd = propertyInfo as MergePropertyDescriptor; - - if (mpd != null) { + + if (mpd != null) + { object[] objs = (object[])obj; - if (eventBindings == null) { + if (eventBindings == null) + { eventBindings = (IEventBindingService)GetService(typeof(IEventBindingService)); } - if (eventBindings != null) { + if (eventBindings != null) + { EventDescriptor descriptor = eventBindings.GetEvent(mpd[0]); - if (descriptor != null) { + if (descriptor != null) + { return ViewEvent(obj, null, descriptor, true); } } - + return false; } - else { + else + { return base.NotifyValueGivenParent(obj, type); } } @@ -306,17 +375,23 @@ internal override bool NotifyValueGivenParent(object obj, int type) { return base.NotifyValueGivenParent(obj, type); } - private bool OwnersEqual(object owner1, object owner2) { - if (!(owner1 is Array)) { + private bool OwnersEqual(object owner1, object owner2) + { + if (!(owner1 is Array)) + { return owner1 == owner2; } - else { + else + { Array a1 = owner1 as Array; Array a2 = owner2 as Array; - if (a1 != null && a2 != null && a1.Length == a2.Length) { - for (int i = 0; i < a1.Length; i++) { - if (a1.GetValue(i) != a2.GetValue(i)) { + if (a1 != null && a2 != null && a1.Length == a2.Length) + { + for (int i = 0; i < a1.Length; i++) + { + if (a1.GetValue(i) != a2.GetValue(i)) + { return false; } } @@ -327,15 +402,21 @@ private bool OwnersEqual(object owner1, object owner2) { } - public override bool OnComponentChanging() { - if (ComponentChangeService != null) { + public override bool OnComponentChanging() + { + if (ComponentChangeService != null) + { int cLength = objs.Length; - for (int i = 0; i < cLength; i++) { - try { + for (int i = 0; i < cLength; i++) + { + try + { ComponentChangeService.OnComponentChanging(objs[i], mergedPd[i]); } - catch (CheckoutException co) { - if (co == CheckoutException.Canceled) { + catch (CheckoutException co) + { + if (co == CheckoutException.Canceled) + { return false; } throw co; @@ -345,10 +426,13 @@ public override bool OnComponentChanging() { return true; } - public override void OnComponentChanged() { - if (ComponentChangeService != null) { + public override void OnComponentChanged() + { + if (ComponentChangeService != null) + { int cLength = objs.Length; - for (int i = 0; i < cLength; i++) { + for (int i = 0; i < cLength; i++) + { ComponentChangeService.OnComponentChanged(objs[i], mergedPd[i], null, null); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiSelectRootGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiSelectRootGridEntry.cs index 2d01219a40f..b302637c61b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiSelectRootGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiSelectRootGridEntry.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.PropertyGridInternal { +namespace System.Windows.Forms.PropertyGridInternal +{ using System.Runtime.InteropServices; using System.Diagnostics; @@ -19,27 +20,35 @@ namespace System.Windows.Forms.PropertyGridInternal { using Microsoft.Win32; using System.Globalization; - internal class MultiSelectRootGridEntry : SingleSelectRootGridEntry { + internal class MultiSelectRootGridEntry : SingleSelectRootGridEntry + { private static PDComparer PropertyComparer = new PDComparer(); - + internal MultiSelectRootGridEntry(PropertyGridView view, object obj, IServiceProvider baseProvider, IDesignerHost host, PropertyTab tab, PropertySort sortType) - : base(view,obj, baseProvider, host, tab, sortType) { + : base(view, obj, baseProvider, host, tab, sortType) + { } - internal override bool ForceReadOnly { - get { - if (!forceReadOnlyChecked) { + internal override bool ForceReadOnly + { + get + { + if (!forceReadOnlyChecked) + { bool anyRO = false; - foreach (object obj in (Array)objValue) { + foreach (object obj in (Array)objValue) + { ReadOnlyAttribute readOnlyAttr = (ReadOnlyAttribute)TypeDescriptor.GetAttributes(obj)[typeof(ReadOnlyAttribute)]; - if ((readOnlyAttr != null && !readOnlyAttr.IsDefaultAttribute()) || TypeDescriptor.GetAttributes(obj).Contains(InheritanceAttribute.InheritedReadOnly)) { + if ((readOnlyAttr != null && !readOnlyAttr.IsDefaultAttribute()) || TypeDescriptor.GetAttributes(obj).Contains(InheritanceAttribute.InheritedReadOnly)) + { anyRO = true; break; } } - if (anyRO) { + if (anyRO) + { flags |= FLAG_FORCE_READONLY; } forceReadOnlyChecked = true; @@ -48,215 +57,253 @@ internal override bool ForceReadOnly { } } - protected override bool CreateChildren() { - return CreateChildren(false); + protected override bool CreateChildren() + { + return CreateChildren(false); } - protected override bool CreateChildren(bool diffOldChildren) { - try { + protected override bool CreateChildren(bool diffOldChildren) + { + try + { object[] rgobjs = (object[])objValue; - + ChildCollection.Clear(); MultiPropertyDescriptorGridEntry[] mergedProps = PropertyMerger.GetMergedProperties(rgobjs, this, this.PropertySort, CurrentTab); - + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose && mergedProps == null, "PropertyGridView: MergedProps returned null!"); - if (mergedProps != null) { + if (mergedProps != null) + { ChildCollection.AddRange(mergedProps); } bool fExpandable = this.Children.Count > 0; - if (!fExpandable) { + if (!fExpandable) + { //Debug.WriteLine("Object " + rgobjs[0].GetType().FullName + " is not expandable because it has no children"); - SetFlag(GridEntry.FL_EXPANDABLE_FAILED,true); + SetFlag(GridEntry.FL_EXPANDABLE_FAILED, true); } CategorizePropEntries(); return fExpandable; } - catch { + catch + { return false; } } - - internal static class PropertyMerger { - public static MultiPropertyDescriptorGridEntry[] GetMergedProperties(object[] rgobjs, GridEntry parentEntry, PropertySort sort, PropertyTab tab) { + internal static class PropertyMerger + { + + public static MultiPropertyDescriptorGridEntry[] GetMergedProperties(object[] rgobjs, GridEntry parentEntry, PropertySort sort, PropertyTab tab) + { MultiPropertyDescriptorGridEntry[] result = null; - try { + try + { int cLength = rgobjs.Length; object[] rgobjArgs = new object[1]; - - if((sort & PropertySort.Alphabetical) != 0) { + + if ((sort & PropertySort.Alphabetical) != 0) + { ArrayList props = GetCommonProperties(rgobjs, true, tab, parentEntry); - + MultiPropertyDescriptorGridEntry[] entries = new MultiPropertyDescriptorGridEntry[props.Count]; - for (int i=0; i < entries.Length; i++) { + for (int i = 0; i < entries.Length; i++) + { entries[i] = new MultiPropertyDescriptorGridEntry(parentEntry.OwnerGrid, parentEntry, rgobjs, (PropertyDescriptor[])props[i], false); } - + result = SortParenEntries(entries); } - else { + else + { object[] sortObjs = new object[cLength - 1]; Array.Copy(rgobjs, 1, sortObjs, 0, cLength - 1); - + ArrayList props = GetCommonProperties(sortObjs, true, tab, parentEntry); - + // this'll work for just one as well - ArrayList firstProps = GetCommonProperties(new object[]{rgobjs[0]}, false, tab, parentEntry); - + ArrayList firstProps = GetCommonProperties(new object[] { rgobjs[0] }, false, tab, parentEntry); + PropertyDescriptor[] firstPds = new PropertyDescriptor[firstProps.Count]; - for (int i = 0; i < firstProps.Count; i++) { + for (int i = 0; i < firstProps.Count; i++) + { firstPds[i] = ((PropertyDescriptor[])firstProps[i])[0]; } - + props = UnsortedMerge(firstPds, props); - + MultiPropertyDescriptorGridEntry[] entries = new MultiPropertyDescriptorGridEntry[props.Count]; - - for (int i=0; i < entries.Length; i++) { + + for (int i = 0; i < entries.Length; i++) + { entries[i] = new MultiPropertyDescriptorGridEntry(parentEntry.OwnerGrid, parentEntry, rgobjs, (PropertyDescriptor[])props[i], false); } - + result = SortParenEntries(entries); } } - catch { + catch + { } - + return result; - + } // this returns an array list of the propertydescriptor arrays, one for each // component // - private static ArrayList GetCommonProperties(object[] objs, bool presort, PropertyTab tab, GridEntry parentEntry) { + private static ArrayList GetCommonProperties(object[] objs, bool presort, PropertyTab tab, GridEntry parentEntry) + { PropertyDescriptorCollection[] propCollections = new PropertyDescriptorCollection[objs.Length]; - + Attribute[] attrs = new Attribute[parentEntry.BrowsableAttributes.Count]; parentEntry.BrowsableAttributes.CopyTo(attrs, 0); - - for (int i = 0; i < objs.Length; i++) { + + for (int i = 0; i < objs.Length; i++) + { PropertyDescriptorCollection pdc = tab.GetProperties(parentEntry, objs[i], attrs); - if (presort) { + if (presort) + { pdc = pdc.Sort(PropertyComparer); } propCollections[i] = pdc; } - + ArrayList mergedList = new ArrayList(); PropertyDescriptor[] matchArray = new PropertyDescriptor[objs.Length]; - - // - // Merge the property descriptors - // - int[] posArray = new int[propCollections.Length]; - for (int i = 0; i < propCollections[0].Count; i++) { - PropertyDescriptor pivotDesc = propCollections[0][i]; - - bool match = pivotDesc.Attributes[typeof(MergablePropertyAttribute)].IsDefaultAttribute(); - - for (int j = 1; match && j < propCollections.Length; j++) { - - if (posArray[j] >= propCollections[j].Count) { - match = false; - break; - } - - // check to see if we're on a match - // - PropertyDescriptor jProp = propCollections[j][posArray[j]]; - if (pivotDesc.Equals(jProp)) { - posArray[j] += 1; - - if (!jProp.Attributes[typeof(MergablePropertyAttribute)].IsDefaultAttribute()) { + + // + // Merge the property descriptors + // + int[] posArray = new int[propCollections.Length]; + for (int i = 0; i < propCollections[0].Count; i++) + { + PropertyDescriptor pivotDesc = propCollections[0][i]; + + bool match = pivotDesc.Attributes[typeof(MergablePropertyAttribute)].IsDefaultAttribute(); + + for (int j = 1; match && j < propCollections.Length; j++) + { + + if (posArray[j] >= propCollections[j].Count) + { + match = false; + break; + } + + // check to see if we're on a match + // + PropertyDescriptor jProp = propCollections[j][posArray[j]]; + if (pivotDesc.Equals(jProp)) + { + posArray[j] += 1; + + if (!jProp.Attributes[typeof(MergablePropertyAttribute)].IsDefaultAttribute()) + { match = false; break; - } - matchArray[j] = jProp; - continue; - } - - int jPos = posArray[j]; - jProp = propCollections[j][jPos]; - - match = false; - - // if we aren't on a match, check all the items until we're past - // where the matching item would be - while (PropertyComparer.Compare(jProp, pivotDesc) <= 0) { - - // got a match! - if (pivotDesc.Equals(jProp)) { - - if (!jProp.Attributes[typeof(MergablePropertyAttribute)].IsDefaultAttribute()) { - match = false; - jPos++; - } - else { - match = true; - matchArray[j] = jProp; - posArray[j] = jPos + 1; - } - break; - } - - // try again - jPos++; - if (jPos < propCollections[j].Count) { - jProp = propCollections[j][jPos]; - } - else { - break; - } - } - - // if we got here, there is no match, quit for this guy - if (!match) { + } + matchArray[j] = jProp; + continue; + } + + int jPos = posArray[j]; + jProp = propCollections[j][jPos]; + + match = false; + + // if we aren't on a match, check all the items until we're past + // where the matching item would be + while (PropertyComparer.Compare(jProp, pivotDesc) <= 0) + { + + // got a match! + if (pivotDesc.Equals(jProp)) + { + + if (!jProp.Attributes[typeof(MergablePropertyAttribute)].IsDefaultAttribute()) + { + match = false; + jPos++; + } + else + { + match = true; + matchArray[j] = jProp; + posArray[j] = jPos + 1; + } + break; + } + + // try again + jPos++; + if (jPos < propCollections[j].Count) + { + jProp = propCollections[j][jPos]; + } + else + { + break; + } + } + + // if we got here, there is no match, quit for this guy + if (!match) + { posArray[j] = jPos; break; - } - } - - // do we have a match? - if (match) { - matchArray[0] = pivotDesc; - mergedList.Add(matchArray.Clone()); - } - } - - return mergedList; + } + } + + // do we have a match? + if (match) + { + matchArray[0] = pivotDesc; + mergedList.Add(matchArray.Clone()); + } + } + + return mergedList; } - private static MultiPropertyDescriptorGridEntry[] SortParenEntries(MultiPropertyDescriptorGridEntry[] entries) { + private static MultiPropertyDescriptorGridEntry[] SortParenEntries(MultiPropertyDescriptorGridEntry[] entries) + { MultiPropertyDescriptorGridEntry[] newEntries = null; int newPos = 0; - + // first scan the list and move any parentesized properties to the front. - for (int i = 0; i < entries.Length; i++) { - if (entries[i].ParensAroundName) { - if (newEntries == null) { + for (int i = 0; i < entries.Length; i++) + { + if (entries[i].ParensAroundName) + { + if (newEntries == null) + { newEntries = new MultiPropertyDescriptorGridEntry[entries.Length]; } newEntries[newPos++] = entries[i]; entries[i] = null; } } - + // second pass, copy any that didn't have the parens. - if (newPos > 0) { - for (int i = 0; i < entries.Length; i++) { - if (entries[i] != null) { + if (newPos > 0) + { + for (int i = 0; i < entries.Length; i++) + { + if (entries[i] != null) + { newEntries[newPos++] = entries[i]; } - } + } entries = newEntries; } return entries; @@ -267,47 +314,54 @@ private static MultiPropertyDescriptorGridEntry[] SortParenEntries(MultiProperty /// have already been merged. The resulting array is the intersection of entries between the two, /// but in the order of baseEntries. /// - private static ArrayList UnsortedMerge(PropertyDescriptor[] baseEntries, ArrayList sortedMergedEntries) { - + private static ArrayList UnsortedMerge(PropertyDescriptor[] baseEntries, ArrayList sortedMergedEntries) + { + ArrayList mergedEntries = new ArrayList(); PropertyDescriptor[] mergeArray = new PropertyDescriptor[((PropertyDescriptor[])sortedMergedEntries[0]).Length + 1]; - - for (int i = 0; i < baseEntries.Length; i++) { - + + for (int i = 0; i < baseEntries.Length; i++) + { + PropertyDescriptor basePd = baseEntries[i]; - + // first, do a binary search for a matching item PropertyDescriptor[] mergedEntryList = null; string entryName = basePd.Name + " " + basePd.PropertyType.FullName; - + int len = sortedMergedEntries.Count; // perform a binary search int offset = len / 2; int start = 0; - - while (len > 0) { + + while (len > 0) + { PropertyDescriptor[] pdList = (PropertyDescriptor[])sortedMergedEntries[start + offset]; PropertyDescriptor pd = pdList[0]; string sortString = pd.Name + " " + pd.PropertyType.FullName; int result = string.Compare(entryName, sortString, false, CultureInfo.InvariantCulture); - if (result == 0) { + if (result == 0) + { mergedEntryList = pdList; break; } - else if (result < 0) { + else if (result < 0) + { len = offset; } - else { + else + { int delta = offset + 1; start += delta; len -= delta; } offset = len / 2; } - - if (mergedEntryList != null) { + + if (mergedEntryList != null) + { mergeArray[0] = basePd; - Array.Copy(mergedEntryList, 0, mergeArray, 1, mergedEntryList.Length); + Array.Copy(mergedEntryList, 0, mergeArray, 1, mergedEntryList.Length); mergedEntries.Add(mergeArray.Clone()); } } @@ -315,30 +369,36 @@ private static ArrayList UnsortedMerge(PropertyDescriptor[] baseEntries, ArrayLi } } - - private class PDComparer : IComparer { - public int Compare(object obj1, object obj2) { + + private class PDComparer : IComparer + { + public int Compare(object obj1, object obj2) + { PropertyDescriptor a1 = obj1 as PropertyDescriptor; PropertyDescriptor a2 = obj2 as PropertyDescriptor; - - if (a1 == null && a2 == null) { + + if (a1 == null && a2 == null) + { return 0; } - else if (a1 == null) { + else if (a1 == null) + { return -1; } - else if (a2 == null) { + else if (a2 == null) + { return 1; } int result = string.Compare(a1.Name, a2.Name, false, CultureInfo.InvariantCulture); - if (result == 0) { + if (result == 0) + { // result = string.Compare(a1.PropertyType.FullName, a2.PropertyType.FullName, true, System.Globalization.CultureInfo.CurrentCulture); } return result; } } - } + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertiesTab.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertiesTab.cs index 900415a0d42..dff72d8d9cd 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertiesTab.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertiesTab.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.PropertyGridInternal { +namespace System.Windows.Forms.PropertyGridInternal +{ using System.Runtime.InteropServices; using System.Diagnostics; @@ -15,56 +16,73 @@ namespace System.Windows.Forms.PropertyGridInternal { using System.Collections; using Microsoft.Win32; - public class PropertiesTab : PropertyTab { + public class PropertiesTab : PropertyTab + { - public override string TabName { - get { + public override string TabName + { + get + { return SR.PBRSToolTipProperties; } } - - public override string HelpKeyword { - get { + + public override string HelpKeyword + { + get + { return "vs.properties"; // do not localize. } } - public override PropertyDescriptor GetDefaultProperty(object obj) { - PropertyDescriptor def = base.GetDefaultProperty(obj); + public override PropertyDescriptor GetDefaultProperty(object obj) + { + PropertyDescriptor def = base.GetDefaultProperty(obj); - if (def == null) { - PropertyDescriptorCollection props = GetProperties(obj); - if (props != null) { - for (int i = 0; i < props.Count; i++) { - if ("Name".Equals(props[i].Name)) { - def = props[i]; - break; - } - } - } - } - return def; + if (def == null) + { + PropertyDescriptorCollection props = GetProperties(obj); + if (props != null) + { + for (int i = 0; i < props.Count; i++) + { + if ("Name".Equals(props[i].Name)) + { + def = props[i]; + break; + } + } + } + } + return def; } - public override PropertyDescriptorCollection GetProperties(object component, Attribute[] attributes) { - return GetProperties(null, component, attributes); + public override PropertyDescriptorCollection GetProperties(object component, Attribute[] attributes) + { + return GetProperties(null, component, attributes); } - - public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object component, Attribute[] attributes) { - if (attributes == null) { - attributes = new Attribute[]{BrowsableAttribute.Yes}; + + public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object component, Attribute[] attributes) + { + if (attributes == null) + { + attributes = new Attribute[] { BrowsableAttribute.Yes }; } - if (context == null) { - return TypeDescriptor.GetProperties(component, attributes); + if (context == null) + { + return TypeDescriptor.GetProperties(component, attributes); } - else { + else + { TypeConverter tc = (context.PropertyDescriptor == null ? TypeDescriptor.GetConverter(component) : context.PropertyDescriptor.Converter); - if (tc == null || !tc.GetPropertiesSupported(context)) { + if (tc == null || !tc.GetPropertiesSupported(context)) + { return TypeDescriptor.GetProperties(component, attributes); } - else { + else + { return tc.GetProperties(context, component, attributes); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs index 5721f1eadef..92812247aa6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.PropertyGridInternal { +namespace System.Windows.Forms.PropertyGridInternal +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.ComponentModel; @@ -11,7 +12,7 @@ namespace System.Windows.Forms.PropertyGridInternal { using System.Diagnostics.CodeAnalysis; using System; using System.Collections; - using System.Reflection; + using System.Reflection; using System.ComponentModel.Design; using System.Windows.Forms; using System.Windows.Forms.Design; @@ -21,29 +22,30 @@ namespace System.Windows.Forms.PropertyGridInternal { using System.Globalization; - internal class PropertyDescriptorGridEntry : GridEntry { - internal PropertyDescriptor propertyInfo; + internal class PropertyDescriptorGridEntry : GridEntry + { + internal PropertyDescriptor propertyInfo; private TypeConverter exceptionConverter = null; - private UITypeEditor exceptionEditor = null; - private bool isSerializeContentsProp = false; - private byte parensAroundName = ParensAroundNameUnknown; + private UITypeEditor exceptionEditor = null; + private bool isSerializeContentsProp = false; + private byte parensAroundName = ParensAroundNameUnknown; private IPropertyValueUIService pvSvc; - protected IEventBindingService eventBindings = null; - private bool pvSvcChecked; - private PropertyValueUIItem[] pvUIItems = null; - private Rectangle [] uiItemRects; - private bool readOnlyVerified = false; - private bool forceRenderReadOnly = false; - private string helpKeyword; - private string toolTipText = null; - private bool activeXHide = false; - private static int scaledImageSizeX = IMAGE_SIZE; - private static int scaledImageSizeY = IMAGE_SIZE; - private static bool isScalingInitialized = false; - - - private const int IMAGE_SIZE = 8; + protected IEventBindingService eventBindings = null; + private bool pvSvcChecked; + private PropertyValueUIItem[] pvUIItems = null; + private Rectangle[] uiItemRects; + private bool readOnlyVerified = false; + private bool forceRenderReadOnly = false; + private string helpKeyword; + private string toolTipText = null; + private bool activeXHide = false; + private static int scaledImageSizeX = IMAGE_SIZE; + private static int scaledImageSizeY = IMAGE_SIZE; + private static bool isScalingInitialized = false; + + + private const int IMAGE_SIZE = 8; private const byte ParensAroundNameUnknown = (byte)0xFF; private const byte ParensAroundNameNo = (byte)0; private const byte ParensAroundNameYes = (byte)1; @@ -56,8 +58,9 @@ internal class PropertyDescriptorGridEntry : GridEntry { SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // GridEntry classes are internal so we have complete // control over who does what in the constructor. ] - internal PropertyDescriptorGridEntry(PropertyGrid ownerGrid, GridEntry peParent, bool hide) - : base(ownerGrid, peParent){ + internal PropertyDescriptorGridEntry(PropertyGrid ownerGrid, GridEntry peParent, bool hide) + : base(ownerGrid, peParent) + { this.activeXHide = hide; } @@ -66,26 +69,31 @@ internal PropertyDescriptorGridEntry(PropertyGrid ownerGrid, GridEntry peParent, // control over who does what in the constructor. ] internal PropertyDescriptorGridEntry(PropertyGrid ownerGrid, GridEntry peParent, PropertyDescriptor propInfo, bool hide) - : base(ownerGrid, peParent) { + : base(ownerGrid, peParent) + { this.activeXHide = hide; Initialize(propInfo); } - - + + /// /// specify that this grid entry should be allowed to be merged for. /// multi-select. /// - public override bool AllowMerge { - get { - MergablePropertyAttribute mpa = (MergablePropertyAttribute)propertyInfo.Attributes[typeof(MergablePropertyAttribute)]; - return mpa == null || mpa.IsDefaultAttribute(); + public override bool AllowMerge + { + get + { + MergablePropertyAttribute mpa = (MergablePropertyAttribute)propertyInfo.Attributes[typeof(MergablePropertyAttribute)]; + return mpa == null || mpa.IsDefaultAttribute(); } } - - internal override AttributeCollection Attributes { - get { + + internal override AttributeCollection Attributes + { + get + { return propertyInfo.Attributes; } } @@ -94,46 +102,56 @@ internal override AttributeCollection Attributes { /// Retrieves the keyword that the VS help dynamic help window will /// use when this IPE is selected. /// - public override string HelpKeyword { - get { - if (this.helpKeyword == null) { + public override string HelpKeyword + { + get + { + if (this.helpKeyword == null) + { - object owner = GetValueOwner(); - if (owner == null) - return null; //null exception protection. + object owner = GetValueOwner(); + if (owner == null) + return null; //null exception protection. - HelpKeywordAttribute helpAttribute = (HelpKeywordAttribute)propertyInfo.Attributes[typeof(HelpKeywordAttribute)]; + HelpKeywordAttribute helpAttribute = (HelpKeywordAttribute)propertyInfo.Attributes[typeof(HelpKeywordAttribute)]; - if (helpAttribute != null && !helpAttribute.IsDefaultAttribute()) { + if (helpAttribute != null && !helpAttribute.IsDefaultAttribute()) + { return helpAttribute.HelpKeyword; - } - else if (this is ImmutablePropertyDescriptorGridEntry) { - helpKeyword = this.PropertyName; - - GridEntry ge = this; - - while (ge.ParentGridEntry != null) { - - ge = ge.ParentGridEntry; - - // for value classes, the equality will never work, so - // just try the type equality - if (ge.PropertyValue == owner || (owner.GetType().IsValueType && owner.GetType() == ge.PropertyValue.GetType())) { - helpKeyword = ge.PropertyName + "." + helpKeyword; - break; - } - } - } - else { + } + else if (this is ImmutablePropertyDescriptorGridEntry) + { + helpKeyword = this.PropertyName; + + GridEntry ge = this; + + while (ge.ParentGridEntry != null) + { + + ge = ge.ParentGridEntry; + + // for value classes, the equality will never work, so + // just try the type equality + if (ge.PropertyValue == owner || (owner.GetType().IsValueType && owner.GetType() == ge.PropertyValue.GetType())) + { + helpKeyword = ge.PropertyName + "." + helpKeyword; + break; + } + } + } + else + { string typeName = string.Empty; Type componentType = propertyInfo.ComponentType; - - if (componentType.IsCOMObject) { + + if (componentType.IsCOMObject) + { typeName = TypeDescriptor.GetClassName(owner); } - else { + else + { // make sure this property is declared on a class that // is related to the component we're looking at. @@ -141,20 +159,25 @@ public override string HelpKeyword { // to try to find the real property. // Type ownerType = owner.GetType(); - if (!componentType.IsPublic || !componentType.IsAssignableFrom(ownerType)) { + if (!componentType.IsPublic || !componentType.IsAssignableFrom(ownerType)) + { PropertyDescriptor componentProperty = TypeDescriptor.GetProperties(ownerType)[this.PropertyName]; - if (componentProperty != null) { + if (componentProperty != null) + { componentType = componentProperty.ComponentType; } - else { + else + { componentType = null; } } - if (componentType == null) { + if (componentType == null) + { typeName = TypeDescriptor.GetClassName(owner); } - else { + else + { // @@ -166,61 +189,78 @@ public override string HelpKeyword { // typeName = helpAttribute.HelpKeyword; //} //else { - typeName = componentType.FullName; + typeName = componentType.FullName; //} } } helpKeyword = typeName + "." + propertyInfo.Name; - } + } } return this.helpKeyword; } } - internal override string LabelToolTipText { - get { + internal override string LabelToolTipText + { + get + { return (toolTipText != null ? toolTipText : base.LabelToolTipText); } } - - internal override string HelpKeywordInternal{ - get { - return this.PropertyLabel; + + internal override string HelpKeywordInternal + { + get + { + return this.PropertyLabel; } } - internal override bool Enumerable { - get { + internal override bool Enumerable + { + get + { return base.Enumerable && !IsPropertyReadOnly; } } - internal virtual bool IsPropertyReadOnly { - get { + internal virtual bool IsPropertyReadOnly + { + get + { return propertyInfo.IsReadOnly; } } - public override bool IsValueEditable { - get { + public override bool IsValueEditable + { + get + { return this.exceptionConverter == null && !IsPropertyReadOnly && base.IsValueEditable; } } - public override bool NeedsDropDownButton{ - get { + public override bool NeedsDropDownButton + { + get + { return base.NeedsDropDownButton && !IsPropertyReadOnly; } } - internal bool ParensAroundName { - get { - if (ParensAroundNameUnknown == this.parensAroundName) { - if (((ParenthesizePropertyNameAttribute)propertyInfo.Attributes[typeof(ParenthesizePropertyNameAttribute)]).NeedParenthesis) { + internal bool ParensAroundName + { + get + { + if (ParensAroundNameUnknown == this.parensAroundName) + { + if (((ParenthesizePropertyNameAttribute)propertyInfo.Attributes[typeof(ParenthesizePropertyNameAttribute)]).NeedParenthesis) + { this.parensAroundName = ParensAroundNameYes; } - else { + else + { this.parensAroundName = ParensAroundNameNo; } } @@ -228,37 +268,47 @@ internal bool ParensAroundName { } } - - public override string PropertyCategory { - get { + + public override string PropertyCategory + { + get + { string category = propertyInfo.Category; - if (category == null || category.Length == 0) { + if (category == null || category.Length == 0) + { category = base.PropertyCategory; } return category; } } - + /// /// Retrieves the PropertyDescriptor that is surfacing the given object/ /// - public override PropertyDescriptor PropertyDescriptor { - get { + public override PropertyDescriptor PropertyDescriptor + { + get + { return propertyInfo; } } - public override string PropertyDescription { - get { + public override string PropertyDescription + { + get + { return propertyInfo.Description; } } - public override string PropertyLabel { - get { + public override string PropertyLabel + { + get + { string label = propertyInfo.DisplayName; - if (ParensAroundName) { + if (ParensAroundName) + { label = "(" + label + ")"; } return label; @@ -268,9 +318,12 @@ public override string PropertyLabel { /// /// Returns non-localized name of this property. /// - public override string PropertyName { - get { - if (propertyInfo != null) { + public override string PropertyName + { + get + { + if (propertyInfo != null) + { return propertyInfo.Name; } return null; @@ -279,8 +332,10 @@ public override string PropertyName { - public override Type PropertyType { - get { + public override Type PropertyType + { + get + { return propertyInfo.PropertyType; } } @@ -290,8 +345,10 @@ public override Type PropertyType { /// Gets or sets the value for the property that is represented /// by this GridEntry. /// - public override object PropertyValue{ - get { + public override object PropertyValue + { + get + { try { object objRet = GetPropertyValueCore(GetValueOwner()); @@ -314,14 +371,18 @@ public override object PropertyValue{ return e; } } - set { + set + { SetPropertyValue(GetValueOwner(), value, false, null); } } - private IPropertyValueUIService PropertyValueUIService { - get { - if (!pvSvcChecked && this.pvSvc == null) { + private IPropertyValueUIService PropertyValueUIService + { + get + { + if (!pvSvcChecked && this.pvSvc == null) + { this.pvSvc = (IPropertyValueUIService)GetService(typeof(IPropertyValueUIService)); pvSvcChecked = true; } @@ -338,43 +399,53 @@ private void SetFlagsAndExceptionInfo(int flags, ExceptionConverter converter, E public override bool ShouldRenderReadOnly { - get { - if (base.ForceReadOnly || forceRenderReadOnly) { - return true; - } - - // if read only editable is set, make sure it's valid - // - if (propertyInfo.IsReadOnly && !readOnlyVerified && GetFlagSet(GridEntry.FLAG_READONLY_EDITABLE)) { - Type propType = this.PropertyType; - - if (propType != null && (propType.IsArray || propType.IsValueType || propType.IsPrimitive)) { - SetFlag(FLAG_READONLY_EDITABLE,false); + get + { + if (base.ForceReadOnly || forceRenderReadOnly) + { + return true; + } + + // if read only editable is set, make sure it's valid + // + if (propertyInfo.IsReadOnly && !readOnlyVerified && GetFlagSet(GridEntry.FLAG_READONLY_EDITABLE)) + { + Type propType = this.PropertyType; + + if (propType != null && (propType.IsArray || propType.IsValueType || propType.IsPrimitive)) + { + SetFlag(FLAG_READONLY_EDITABLE, false); SetFlag(FLAG_RENDER_READONLY, true); forceRenderReadOnly = true; - } - } - readOnlyVerified = true; - - if (base.ShouldRenderReadOnly){ - if (!this.isSerializeContentsProp && !base.NeedsCustomEditorButton) { + } + } + readOnlyVerified = true; + + if (base.ShouldRenderReadOnly) + { + if (!this.isSerializeContentsProp && !base.NeedsCustomEditorButton) + { return true; - } - } - return false; + } + } + return false; } } /// /// Returns the type converter for this entry. /// - internal override TypeConverter TypeConverter { - get { - if (exceptionConverter != null) { + internal override TypeConverter TypeConverter + { + get + { + if (exceptionConverter != null) + { return exceptionConverter; } - if (converter == null) { + if (converter == null) + { converter = propertyInfo.Converter; } return base.TypeConverter; @@ -385,38 +456,48 @@ internal override TypeConverter TypeConverter { /// Returns the type editor for this entry. This may return null if there /// is no type editor. /// - internal override UITypeEditor UITypeEditor { - get { - if (exceptionEditor != null) { + internal override UITypeEditor UITypeEditor + { + get + { + if (exceptionEditor != null) + { return exceptionEditor; } editor = (UITypeEditor)propertyInfo.GetEditor(typeof(System.Drawing.Design.UITypeEditor)); - + return base.UITypeEditor; } } - - + + /// /// Invokes the type editor for editing this item. /// - internal override void EditPropertyValue(PropertyGridView iva) { + internal override void EditPropertyValue(PropertyGridView iva) + { base.EditPropertyValue(iva); - - if (!IsValueEditable) { - RefreshPropertiesAttribute refreshAttr = (RefreshPropertiesAttribute)propertyInfo.Attributes[typeof(RefreshPropertiesAttribute)]; - if ((refreshAttr != null && !refreshAttr.RefreshProperties.Equals(RefreshProperties.None))) { - this.GridEntryHost.Refresh(refreshAttr != null && refreshAttr.Equals(RefreshPropertiesAttribute.All)); - } + + if (!IsValueEditable) + { + RefreshPropertiesAttribute refreshAttr = (RefreshPropertiesAttribute)propertyInfo.Attributes[typeof(RefreshPropertiesAttribute)]; + if ((refreshAttr != null && !refreshAttr.RefreshProperties.Equals(RefreshProperties.None))) + { + this.GridEntryHost.Refresh(refreshAttr != null && refreshAttr.Equals(RefreshPropertiesAttribute.All)); + } } } - internal override Point GetLabelToolTipLocation(int mouseX, int mouseY){ - if (pvUIItems != null) { - for (int i = 0; i < pvUIItems.Length; i++) { - if (uiItemRects[i].Contains(mouseX, GridEntryHost.GetGridEntryHeight() / 2)) { + internal override Point GetLabelToolTipLocation(int mouseX, int mouseY) + { + if (pvUIItems != null) + { + for (int i = 0; i < pvUIItems.Length; i++) + { + if (uiItemRects[i].Contains(mouseX, GridEntryHost.GetGridEntryHeight() / 2)) + { this.toolTipText = pvUIItems[i].ToolTip; return new Point(mouseX, mouseY); } @@ -426,44 +507,54 @@ internal override Point GetLabelToolTipLocation(int mouseX, int mouseY){ return base.GetLabelToolTipLocation(mouseX, mouseY); } - protected object GetPropertyValueCore(object target) { - if (propertyInfo == null) { + protected object GetPropertyValueCore(object target) + { + if (propertyInfo == null) + { return null; } - if (target is ICustomTypeDescriptor) { + if (target is ICustomTypeDescriptor) + { target = ((ICustomTypeDescriptor)target).GetPropertyOwner(propertyInfo); } - try { + try + { return propertyInfo.GetValue(target); } - catch { + catch + { throw; - } + } } - protected void Initialize(PropertyDescriptor propInfo) { + protected void Initialize(PropertyDescriptor propInfo) + { propertyInfo = propInfo; this.isSerializeContentsProp = (propertyInfo.SerializationVisibility == DesignerSerializationVisibility.Content); - + Debug.Assert(propInfo != null, "Can't create propEntry because of null prop info"); - if (!this.activeXHide && IsPropertyReadOnly) { + if (!this.activeXHide && IsPropertyReadOnly) + { SetFlag(FLAG_TEXT_EDITABLE, false); } - if (isSerializeContentsProp && TypeConverter.GetPropertiesSupported()) { + if (isSerializeContentsProp && TypeConverter.GetPropertiesSupported()) + { SetFlag(FL_EXPANDABLE, true); } } - protected virtual void NotifyParentChange(GridEntry ge) { + protected virtual void NotifyParentChange(GridEntry ge) + { // now see if we need to notify the parent(s) up the chain while (ge != null && ge is PropertyDescriptorGridEntry && - ((PropertyDescriptorGridEntry)ge).propertyInfo.Attributes.Contains(NotifyParentPropertyAttribute.Yes)) { + ((PropertyDescriptorGridEntry)ge).propertyInfo.Attributes.Contains(NotifyParentPropertyAttribute.Yes)) + { // find the next parent property with a differnet value owner object owner = ge.GetValueOwner(); @@ -473,57 +564,70 @@ ge is PropertyDescriptorGridEntry && bool isValueType = owner.GetType().IsValueType; // find the next property descriptor with a different parent - while (!(ge is PropertyDescriptorGridEntry) - || isValueType ? owner.Equals(ge.GetValueOwner()) : owner == ge.GetValueOwner()) { + while (!(ge is PropertyDescriptorGridEntry) + || isValueType ? owner.Equals(ge.GetValueOwner()) : owner == ge.GetValueOwner()) + { ge = ge.ParentGridEntry; - if (ge == null) { + if (ge == null) + { break; } } // fire the change on that owner - if (ge != null) { + if (ge != null) + { owner = ge.GetValueOwner(); IComponentChangeService changeService = ComponentChangeService; - - if (changeService != null) { + + if (changeService != null) + { changeService.OnComponentChanging(owner, ((PropertyDescriptorGridEntry)ge).propertyInfo); changeService.OnComponentChanged(owner, ((PropertyDescriptorGridEntry)ge).propertyInfo, null, null); } ge.ClearCachedValues(false); //clear the value so it paints correctly next time. PropertyGridView gv = this.GridEntryHost; - if (gv != null) { + if (gv != null) + { gv.InvalidateGridEntryValue(ge); } } } } - - internal override bool NotifyValueGivenParent(object obj, int type) { - if (obj is ICustomTypeDescriptor) { + + internal override bool NotifyValueGivenParent(object obj, int type) + { + if (obj is ICustomTypeDescriptor) + { obj = ((ICustomTypeDescriptor)obj).GetPropertyOwner(propertyInfo); } - switch (type) { + switch (type) + { case NOTIFY_RESET: - + SetPropertyValue(obj, null, true, string.Format(SR.PropertyGridResetValue, this.PropertyName)); - if (pvUIItems != null) { - for (int i = 0; i < pvUIItems.Length; i++) { + if (pvUIItems != null) + { + for (int i = 0; i < pvUIItems.Length; i++) + { pvUIItems[i].Reset(); } } pvUIItems = null; return false; - case NOTIFY_CAN_RESET: - try { + case NOTIFY_CAN_RESET: + try + { return propertyInfo.CanResetValue(obj) || (pvUIItems != null && pvUIItems.Length > 0); } - catch { - - if (this.exceptionConverter == null) { + catch + { + + if (this.exceptionConverter == null) + { // clear the flags this.Flags = 0; this.exceptionConverter = new ExceptionConverter(); @@ -531,38 +635,45 @@ internal override bool NotifyValueGivenParent(object obj, int type) { } return false; } - case NOTIFY_SHOULD_PERSIST: - try{ - return propertyInfo.ShouldSerializeValue(obj); - } - catch { - - if (this.exceptionConverter == null) { - // clear the flags - this.Flags = 0; - this.exceptionConverter = new ExceptionConverter(); - this.exceptionEditor = new ExceptionEditor(); + case NOTIFY_SHOULD_PERSIST: + try + { + return propertyInfo.ShouldSerializeValue(obj); } - return false; - } - + catch + { + + if (this.exceptionConverter == null) + { + // clear the flags + this.Flags = 0; + this.exceptionConverter = new ExceptionConverter(); + this.exceptionEditor = new ExceptionEditor(); + } + return false; + } + case NOTIFY_DBL_CLICK: case NOTIFY_RETURN: - if (eventBindings == null) { + if (eventBindings == null) + { eventBindings = (IEventBindingService)GetService(typeof(IEventBindingService)); } - if (eventBindings != null) { + if (eventBindings != null) + { EventDescriptor descriptor = eventBindings.GetEvent(propertyInfo); - if (descriptor != null) { + if (descriptor != null) + { return ViewEvent(obj, null, null, true); } } - break; + break; } return false; } - - public override void OnComponentChanged() { + + public override void OnComponentChanged() + { base.OnComponentChanged(); // If we got this it means someone called ITypeDescriptorContext.OnCompnentChanged. // so we need to echo that change up the inheritance change in case the owner object isn't a sited component. @@ -570,10 +681,14 @@ public override void OnComponentChanged() { } - public override bool OnMouseClick(int x, int y, int count, MouseButtons button) { - if (pvUIItems != null && count == 2 && ((button & MouseButtons.Left) == MouseButtons.Left)) { - for (int i = 0; i < pvUIItems.Length; i++) { - if (uiItemRects[i].Contains(x, GridEntryHost.GetGridEntryHeight() / 2)) { + public override bool OnMouseClick(int x, int y, int count, MouseButtons button) + { + if (pvUIItems != null && count == 2 && ((button & MouseButtons.Left) == MouseButtons.Left)) + { + for (int i = 0; i < pvUIItems.Length; i++) + { + if (uiItemRects[i].Contains(x, GridEntryHost.GetGridEntryHeight() / 2)) + { pvUIItems[i].InvokeHandler(this, propertyInfo, pvUIItems[i]); return true; } @@ -582,31 +697,38 @@ public override bool OnMouseClick(int x, int y, int count, MouseButtons button) return base.OnMouseClick(x, y, count, button); } - public override void PaintLabel(System.Drawing.Graphics g, Rectangle rect, Rectangle clipRect, bool selected, bool paintFullLabel) { + public override void PaintLabel(System.Drawing.Graphics g, Rectangle rect, Rectangle clipRect, bool selected, bool paintFullLabel) + { base.PaintLabel(g, rect, clipRect, selected, paintFullLabel); IPropertyValueUIService propValSvc = this.PropertyValueUIService; - if (propValSvc == null) { + if (propValSvc == null) + { return; } pvUIItems = propValSvc.GetPropertyUIValueItems(this, propertyInfo); - if (pvUIItems != null) { - if (uiItemRects == null || uiItemRects.Length != pvUIItems.Length) { + if (pvUIItems != null) + { + if (uiItemRects == null || uiItemRects.Length != pvUIItems.Length) + { uiItemRects = new Rectangle[pvUIItems.Length]; } - if (!isScalingInitialized) { - if (DpiHelper.IsScalingRequired) { + if (!isScalingInitialized) + { + if (DpiHelper.IsScalingRequired) + { scaledImageSizeX = DpiHelper.LogicalToDeviceUnitsX(IMAGE_SIZE); - scaledImageSizeY = DpiHelper.LogicalToDeviceUnitsY(IMAGE_SIZE); + scaledImageSizeY = DpiHelper.LogicalToDeviceUnitsY(IMAGE_SIZE); } isScalingInitialized = true; } - for (int i = 0; i < pvUIItems.Length; i++) { + for (int i = 0; i < pvUIItems.Length; i++) + { uiItemRects[i] = new Rectangle(rect.Right - ((scaledImageSizeX + 1) * (i + 1)), (rect.Height - scaledImageSizeY) / 2, scaledImageSizeX, scaledImageSizeY); g.DrawImage(pvUIItems[i].Image, uiItemRects[i]); } @@ -616,7 +738,8 @@ public override void PaintLabel(System.Drawing.Graphics g, Rectangle rect, Recta - private object SetPropertyValue(object obj,object objVal, bool reset, string undoText) { + private object SetPropertyValue(object obj, object objVal, bool reset, string undoText) + { DesignerTransaction trans = null; try { @@ -701,7 +824,7 @@ private object SetPropertyValue(object obj,object objVal, bool reset, string und eventDesc = eventBindings.GetEvent(propertyInfo); } - // For a merged set of properties, the event binding service won't + // For a merged set of propertius, the event binding service won't // find an event. So, we ask type descriptor directly. // if (eventDesc == null) @@ -759,8 +882,9 @@ private object SetPropertyValue(object obj,object objVal, bool reset, string und if (needsRefresh && this.GridEntryHost != null) { RecreateChildren(childCount); - if (setSuccessful) { - this.GridEntryHost.Refresh(refreshAttr != null && refreshAttr.Equals(RefreshPropertiesAttribute.All)); + if (setSuccessful) + { + this.GridEntryHost.Refresh(refreshAttr != null && refreshAttr.Equals(RefreshPropertiesAttribute.All)); } } } @@ -789,29 +913,35 @@ private object SetPropertyValue(object obj,object objVal, bool reset, string und throw; } - finally { - if (trans != null) { + finally + { + if (trans != null) + { trans.Commit(); } } return obj; } - protected void SetPropertyValueCore(object obj, object value, bool doUndo) { - - if (propertyInfo == null) { + protected void SetPropertyValueCore(object obj, object value, bool doUndo) + { + + if (propertyInfo == null) + { return; } // Store the current cursor and set it to the HourGlass. // Cursor oldCursor = Cursor.Current; - try { + try + { Cursor.Current = Cursors.WaitCursor; object target = obj; - if (target is ICustomTypeDescriptor) { + if (target is ICustomTypeDescriptor) + { target = ((ICustomTypeDescriptor)target).GetPropertyOwner(propertyInfo); } @@ -820,12 +950,14 @@ protected void SetPropertyValueCore(object obj, object value, bool doUndo) { // bool treatAsValueType = false; - if (ParentGridEntry != null) { + if (ParentGridEntry != null) + { Type propType = ParentGridEntry.PropertyType; treatAsValueType = propType.IsValueType || propType.IsArray; } - if (target != null) { + if (target != null) + { propertyInfo.SetValue(target, value); @@ -836,15 +968,18 @@ protected void SetPropertyValueCore(object obj, object value, bool doUndo) { // to the object they relate to. So we modify the Point object and // push it back into the object we got it from. // - if (treatAsValueType) { + if (treatAsValueType) + { GridEntry parent = this.ParentGridEntry; - if (parent != null && parent.IsValueEditable) { + if (parent != null && parent.IsValueEditable) + { parent.PropertyValue = obj; } } } } - finally { + finally + { // Flip back to the old cursor. // Cursor.Current = oldCursor; @@ -854,106 +989,133 @@ protected void SetPropertyValueCore(object obj, object value, bool doUndo) { /// /// Navigates code to the given event. /// - protected bool ViewEvent(object obj, string newHandler, EventDescriptor eventdesc, bool alwaysNavigate) { + protected bool ViewEvent(object obj, string newHandler, EventDescriptor eventdesc, bool alwaysNavigate) + { object value = GetPropertyValueCore(obj); string handler = value as string; - if (handler == null && value != null && TypeConverter != null && TypeConverter.CanConvertTo(typeof(string))) { + if (handler == null && value != null && TypeConverter != null && TypeConverter.CanConvertTo(typeof(string))) + { handler = TypeConverter.ConvertToString(value); } - if (newHandler == null && !string.IsNullOrEmpty(handler)) { + if (newHandler == null && !string.IsNullOrEmpty(handler)) + { newHandler = handler; } - else if (handler == newHandler && !string.IsNullOrEmpty(newHandler)) { + else if (handler == newHandler && !string.IsNullOrEmpty(newHandler)) + { return true; } - + IComponent component = obj as IComponent; - - if (component == null && propertyInfo is MergePropertyDescriptor) { - + + if (component == null && propertyInfo is MergePropertyDescriptor) + { + // It's possible that multiple objects are selected, and we're trying to create an event for each of them // Array objArray = obj as Array; - if (objArray != null && objArray.Length > 0) { + if (objArray != null && objArray.Length > 0) + { component = objArray.GetValue(0) as IComponent; } } - - if (component == null) { + + if (component == null) + { return false; } - - if (propertyInfo.IsReadOnly) { + + if (propertyInfo.IsReadOnly) + { return false; } - - if (eventdesc == null) { - if (eventBindings == null) { + + if (eventdesc == null) + { + if (eventBindings == null) + { eventBindings = (IEventBindingService)GetService(typeof(IEventBindingService)); } - if (eventBindings != null) { + if (eventBindings != null) + { eventdesc = eventBindings.GetEvent(propertyInfo); } } - + IDesignerHost host = this.DesignerHost; DesignerTransaction trans = null; - try { + try + { // This check can cause exceptions if the event has unreferenced dependencies, which we want to cath. // This must be done before the transaction is started or the commit/cancel will also throw. - if (eventdesc.EventType == null) { + if (eventdesc.EventType == null) + { return false; } - - if (host != null) { + + if (host != null) + { string compName = component.Site != null ? component.Site.Name : component.GetType().Name; trans = DesignerHost.CreateTransaction(string.Format(SR.WindowsFormsSetEvent, compName + "." + this.PropertyName)); } - - if (eventBindings == null) { + + if (eventBindings == null) + { ISite site = component.Site; - if (site != null) { + if (site != null) + { eventBindings = (IEventBindingService)site.GetService(typeof(IEventBindingService)); } } - - if (newHandler == null && eventBindings != null) { + + if (newHandler == null && eventBindings != null) + { newHandler = eventBindings.CreateUniqueMethodName(component, eventdesc); } - - if (newHandler != null) { + + if (newHandler != null) + { // now walk through all the matching methods to see if this one exists. // if it doesn't we'll wanna show code. // - if (eventBindings != null) { + if (eventBindings != null) + { bool methodExists = false; - foreach (string methodName in eventBindings.GetCompatibleMethods(eventdesc)) { - if (newHandler == methodName) { + foreach (string methodName in eventBindings.GetCompatibleMethods(eventdesc)) + { + if (newHandler == methodName) + { methodExists = true; break; } } - if (!methodExists) { + if (!methodExists) + { alwaysNavigate = true; } } - try { + try + { propertyInfo.SetValue(obj, newHandler); - } catch (InvalidOperationException ex) { - if (trans != null) { + } + catch (InvalidOperationException ex) + { + if (trans != null) + { trans.Cancel(); trans = null; } - if (this.GridEntryHost != null && this.GridEntryHost is PropertyGridView) { + if (this.GridEntryHost != null && this.GridEntryHost is PropertyGridView) + { PropertyGridView pgv = this.GridEntryHost as PropertyGridView; pgv.ShowInvalidMessage(newHandler, obj, ex); } @@ -961,23 +1123,28 @@ protected bool ViewEvent(object obj, string newHandler, EventDescriptor eventdes return false; } } - - if (alwaysNavigate && eventBindings != null) { + + if (alwaysNavigate && eventBindings != null) + { targetBindingService = eventBindings; targetComponent = component; targetEventdesc = eventdesc; - Application.Idle += new EventHandler(PropertyDescriptorGridEntry.ShowCodeIdle); + Application.Idle += new EventHandler(PropertyDescriptorGridEntry.ShowCodeIdle); } } - catch { - if (trans != null) { + catch + { + if (trans != null) + { trans.Cancel(); trans = null; } throw; } - finally { - if (trans != null) { + finally + { + if (trans != null) + { trans.Commit(); } } @@ -988,9 +1155,11 @@ protected bool ViewEvent(object obj, string newHandler, EventDescriptor eventdes /// Displays the user code for the given event. This will return true if the user /// code could be displayed, or false otherwise. /// - static private void ShowCodeIdle(object sender, EventArgs e) { + static private void ShowCodeIdle(object sender, EventArgs e) + { Application.Idle -= new EventHandler(PropertyDescriptorGridEntry.ShowCodeIdle); - if (targetBindingService != null) { + if (targetBindingService != null) + { targetBindingService.ShowCode(targetComponent, targetEventdesc); targetBindingService = null; targetComponent = null; @@ -1007,16 +1176,19 @@ static private void ShowCodeIdle(object sender, EventArgs e) { /// /// AccessibleObject for this PropertyDescriptorGridEntry instance. /// - protected override GridEntryAccessibleObject GetAccessibilityObject() { + protected override GridEntryAccessibleObject GetAccessibilityObject() + { return new PropertyDescriptorGridEntryAccessibleObject(this); } [ComVisible(true)] - protected class PropertyDescriptorGridEntryAccessibleObject : GridEntryAccessibleObject { + protected class PropertyDescriptorGridEntryAccessibleObject : GridEntryAccessibleObject + { private PropertyDescriptorGridEntry _owningPropertyDescriptorGridEntry; - public PropertyDescriptorGridEntryAccessibleObject(PropertyDescriptorGridEntry owner) : base(owner) { + public PropertyDescriptorGridEntryAccessibleObject(PropertyDescriptorGridEntry owner) : base(owner) + { _owningPropertyDescriptorGridEntry = owner; } @@ -1027,8 +1199,10 @@ public PropertyDescriptorGridEntryAccessibleObject(PropertyDescriptorGridEntry o /// /// Indicates the direction in which to navigate. /// Returns the element in the specified direction. - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - switch (direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { + switch (direction) + { case UnsafeNativeMethods.NavigateDirection.NextSibling: var propertyGridViewAccessibleObject = (PropertyGridView.PropertyGridViewAccessibleObject)Parent; var propertyGridView = propertyGridViewAccessibleObject.Owner as PropertyGridView; @@ -1048,15 +1222,19 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga return base.FragmentNavigate(direction); } - private UnsafeNativeMethods.IRawElementProviderFragment GetFirstChild() { - if (_owningPropertyDescriptorGridEntry.ChildCount > 0) { + private UnsafeNativeMethods.IRawElementProviderFragment GetFirstChild() + { + if (_owningPropertyDescriptorGridEntry.ChildCount > 0) + { return _owningPropertyDescriptorGridEntry.Children.GetEntry(0).AccessibilityObject; } var propertyGridViewAccessibleObject = (PropertyGridView.PropertyGridViewAccessibleObject)Parent; var propertyGridView = propertyGridViewAccessibleObject.Owner as PropertyGridView; - if (_owningPropertyDescriptorGridEntry == propertyGridView.SelectedGridEntry) { - if (propertyGridView.SelectedGridEntry.Enumerable) { + if (_owningPropertyDescriptorGridEntry == propertyGridView.SelectedGridEntry) + { + if (propertyGridView.SelectedGridEntry.Enumerable) + { return propertyGridView.DropDownListBoxAccessibleObject; } @@ -1066,16 +1244,20 @@ private UnsafeNativeMethods.IRawElementProviderFragment GetFirstChild() { return null; } - private UnsafeNativeMethods.IRawElementProviderFragment GetLastChild() { - if (_owningPropertyDescriptorGridEntry.ChildCount > 0) { + private UnsafeNativeMethods.IRawElementProviderFragment GetLastChild() + { + if (_owningPropertyDescriptorGridEntry.ChildCount > 0) + { return _owningPropertyDescriptorGridEntry.Children .GetEntry(_owningPropertyDescriptorGridEntry.ChildCount - 1).AccessibilityObject; } var propertyGridViewAccessibleObject = (PropertyGridView.PropertyGridViewAccessibleObject)Parent; var propertyGridView = propertyGridViewAccessibleObject.Owner as PropertyGridView; - if (_owningPropertyDescriptorGridEntry == propertyGridView.SelectedGridEntry) { - if (propertyGridView.SelectedGridEntry.Enumerable && propertyGridView.DropDownButton.Visible) { + if (_owningPropertyDescriptorGridEntry == propertyGridView.SelectedGridEntry) + { + if (propertyGridView.SelectedGridEntry.Enumerable && propertyGridView.DropDownButton.Visible) + { return propertyGridView.DropDownButton.AccessibilityObject; } @@ -1085,22 +1267,28 @@ private UnsafeNativeMethods.IRawElementProviderFragment GetLastChild() { return null; } - internal override bool IsPatternSupported(int patternId) { - if (patternId == NativeMethods.UIA_ValuePatternId) { + internal override bool IsPatternSupported(int patternId) + { + if (patternId == NativeMethods.UIA_ValuePatternId) + { return true; } return base.IsPatternSupported(patternId); } - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_IsEnabledPropertyId) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_IsEnabledPropertyId) + { return !((PropertyDescriptorGridEntry)owner).IsPropertyReadOnly; } - else if (propertyID == NativeMethods.UIA_LegacyIAccessibleDefaultActionPropertyId) { + else if (propertyID == NativeMethods.UIA_LegacyIAccessibleDefaultActionPropertyId) + { return string.Empty; } - else if (propertyID == NativeMethods.UIA_IsValuePatternAvailablePropertyId) { + else if (propertyID == NativeMethods.UIA_IsValuePatternAvailablePropertyId) + { return true; } @@ -1111,7 +1299,8 @@ internal override object GetPropertyValue(int propertyID) { /// /// The exception converter is a type converter that displays an exception to the user. /// - private class ExceptionConverter : TypeConverter { + private class ExceptionConverter : TypeConverter + { /// /// Converts the given object to another type. The most common types to convert @@ -1120,11 +1309,15 @@ private class ExceptionConverter : TypeConverter { /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == typeof(string)) { - if (value is Exception) { + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == typeof(string)) + { + if (value is Exception) + { Exception ex = (Exception)value; - if (ex.InnerException != null) { + if (ex.InnerException != null) + { ex = ex.InnerException; } return ex.Message; @@ -1138,30 +1331,37 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul /// /// The exception editor displays a message to the user. /// - private class ExceptionEditor : UITypeEditor { + private class ExceptionEditor : UITypeEditor + { /// /// Edits the given object value using the editor style provided by /// GetEditorStyle. A service provider is provided so that any /// required editing services can be obtained. /// - public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { + public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) + { Exception except = value as Exception; - if (except != null) { + if (except != null) + { IUIService uis = null; - if (context != null) { + if (context != null) + { uis = (IUIService)context.GetService(typeof(IUIService)); } - if (uis != null) { + if (uis != null) + { uis.ShowError(except); } - else { + else + { string message = except.Message; - if (message == null || message.Length == 0) message = except.ToString(); - + if (message == null || message.Length == 0) + message = except.ToString(); + RTLAwareMessageBox.Show(null, message, SR.PropertyGridExceptionInfo, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); } @@ -1173,7 +1373,8 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide /// Retrieves the editing style of the Edit method. If the method /// is not supported, this will return None. /// - public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { + public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) + { return UITypeEditorEditStyle.Modal; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridCommands.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridCommands.cs index 44dc7187c6a..c9db87dd5db 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridCommands.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridCommands.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.PropertyGridInternal { +namespace System.Windows.Forms.PropertyGridInternal +{ using System.Diagnostics; using System; @@ -14,7 +15,8 @@ namespace System.Windows.Forms.PropertyGridInternal { /// This class contains the set of menu commands our property browser /// uses. /// - public class PropertyGridCommands{ + public class PropertyGridCommands + { /// /// This guid corresponds to the menu grouping windows forms will use for its menus. This is @@ -28,10 +30,10 @@ public class PropertyGridCommands{ /// protected static readonly Guid wfcMenuCommand = new Guid("{5a51cf82-7619-4a5d-b054-47f438425aa7}"); - public static readonly CommandID Reset = new CommandID(wfcMenuCommand, 0x3000); - public static readonly CommandID Description = new CommandID(wfcMenuCommand, 0x3001); - public static readonly CommandID Hide = new CommandID(wfcMenuCommand, 0x3002); - public static readonly CommandID Commands = new CommandID(wfcMenuCommand, 0x3010); + public static readonly CommandID Reset = new CommandID(wfcMenuCommand, 0x3000); + public static readonly CommandID Description = new CommandID(wfcMenuCommand, 0x3001); + public static readonly CommandID Hide = new CommandID(wfcMenuCommand, 0x3002); + public static readonly CommandID Commands = new CommandID(wfcMenuCommand, 0x3010); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs index bc99f329c73..c9d4ba13198 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.PropertyGridInternal { +namespace System.Windows.Forms.PropertyGridInternal +{ using System.Runtime.Serialization.Formatters; using System.Threading; using System.Runtime.InteropServices; @@ -13,11 +14,11 @@ namespace System.Windows.Forms.PropertyGridInternal { using System.Diagnostics.CodeAnalysis; using System.Globalization; using System; - using System.Collections; + using System.Collections; using System.Windows.Forms; using System.Windows.Forms.Internal; using System.Windows.Forms.ComponentModel; - using System.Windows.Forms.Design; + using System.Windows.Forms.Design; using System.ComponentModel.Design; using System.Windows.Forms.VisualStyles; using System.IO; @@ -31,7 +32,8 @@ internal class PropertyGridView : Control, IWin32Window, IWindowsFormsEditorService, - IServiceProvider { + IServiceProvider + { protected static readonly Point InvalidPoint = new Point(int.MinValue, int.MinValue); @@ -54,26 +56,26 @@ internal class PropertyGridView : private const int LEFTDOT_SIZE = 4; #endif // constants - private const int EDIT_INDENT = 0; - private const int OUTLINE_INDENT = 10; - private const int OUTLINE_SIZE = 9; - private const int OUTLINE_SIZE_EXPLORER_TREE_STYLE = 16; - private int outlineSize = OUTLINE_SIZE; - private int outlineSizeExplorerTreeStyle = OUTLINE_SIZE_EXPLORER_TREE_STYLE; - private const int PAINT_WIDTH = 20; - private int paintWidth = PAINT_WIDTH; - private const int PAINT_INDENT = 26; - private int paintIndent = PAINT_INDENT; - private const int ROWLABEL = 1; - private const int ROWVALUE = 2; - private const int MAX_LISTBOX_HEIGHT = 200; - private int maxListBoxHeight = MAX_LISTBOX_HEIGHT; - - private const short ERROR_NONE = 0; - private const short ERROR_THROWN = 1; - private const short ERROR_MSGBOX_UP = 2; - internal const short GDIPLUS_SPACE = 2; - internal const int MaxRecurseExpand = 10; + private const int EDIT_INDENT = 0; + private const int OUTLINE_INDENT = 10; + private const int OUTLINE_SIZE = 9; + private const int OUTLINE_SIZE_EXPLORER_TREE_STYLE = 16; + private int outlineSize = OUTLINE_SIZE; + private int outlineSizeExplorerTreeStyle = OUTLINE_SIZE_EXPLORER_TREE_STYLE; + private const int PAINT_WIDTH = 20; + private int paintWidth = PAINT_WIDTH; + private const int PAINT_INDENT = 26; + private int paintIndent = PAINT_INDENT; + private const int ROWLABEL = 1; + private const int ROWVALUE = 2; + private const int MAX_LISTBOX_HEIGHT = 200; + private int maxListBoxHeight = MAX_LISTBOX_HEIGHT; + + private const short ERROR_NONE = 0; + private const short ERROR_THROWN = 1; + private const short ERROR_MSGBOX_UP = 2; + internal const short GDIPLUS_SPACE = 2; + internal const int MaxRecurseExpand = 10; private const int DOTDOTDOT_ICONWIDTH = 7; private const int DOTDOTDOT_ICONHEIGHT = 8; @@ -87,82 +89,82 @@ internal class PropertyGridView : // colors and fonts - private Brush backgroundBrush = null; - private Font fontBold = null; - private Color grayTextColor; + private Brush backgroundBrush = null; + private Font fontBold = null; + private Color grayTextColor; // for backwards compatibility of default colors - private bool grayTextColorModified = false; // true if someone has set the grayTextColor property + private bool grayTextColorModified = false; // true if someone has set the grayTextColor property // property collections - private GridEntryCollection topLevelGridEntries = null; // top level props - private GridEntryCollection allGridEntries = null; // cache of viewable props - + private GridEntryCollection topLevelGridEntries = null; // top level props + private GridEntryCollection allGridEntries = null; // cache of viewable props + // row information - internal int totalProps = -1; // # of viewable props - private int visibleRows = -1; // # of visible rows - private int labelWidth = -1; - public double labelRatio = 2; // ratio of whole row to label width - - private short requiredLabelPaintMargin = GDIPLUS_SPACE; + internal int totalProps = -1; // # of viewable props + private int visibleRows = -1; // # of visible rows + private int labelWidth = -1; + public double labelRatio = 2; // ratio of whole row to label width + + private short requiredLabelPaintMargin = GDIPLUS_SPACE; // current selected row and tooltip. - private int selectedRow = -1; - private GridEntry selectedGridEntry = null; - private int tipInfo = -1; + private int selectedRow = -1; + private GridEntry selectedGridEntry = null; + private int tipInfo = -1; // editors & controls - private GridViewEdit edit = null; - private DropDownButton btnDropDown = null; - private DropDownButton btnDialog = null; - private GridViewListBox listBox = null; - private DropDownHolder dropDownHolder = null; - private Rectangle lastClientRect = Rectangle.Empty; - private Control currentEditor = null; - private ScrollBar scrollBar = null; - internal GridToolTip toolTip = null; - private GridErrorDlg errorDlg = null; - + private GridViewEdit edit = null; + private DropDownButton btnDropDown = null; + private DropDownButton btnDialog = null; + private GridViewListBox listBox = null; + private DropDownHolder dropDownHolder = null; + private Rectangle lastClientRect = Rectangle.Empty; + private Control currentEditor = null; + private ScrollBar scrollBar = null; + internal GridToolTip toolTip = null; + private GridErrorDlg errorDlg = null; + // flags - private const short FlagNeedsRefresh = 0x0001; - private const short FlagIsNewSelection = 0x0002; - private const short FlagIsSplitterMove = 0x0004; - private const short FlagIsSpecialKey = 0x0008; - private const short FlagInPropertySet = 0x0010; - private const short FlagDropDownClosing = 0x0020; - private const short FlagDropDownCommit = 0x0040; + private const short FlagNeedsRefresh = 0x0001; + private const short FlagIsNewSelection = 0x0002; + private const short FlagIsSplitterMove = 0x0004; + private const short FlagIsSpecialKey = 0x0008; + private const short FlagInPropertySet = 0x0010; + private const short FlagDropDownClosing = 0x0020; + private const short FlagDropDownCommit = 0x0040; private const short FlagNeedUpdateUIBasedOnFont = 0x0080; - private const short FlagBtnLaunchedEditor = 0x0100; - private const short FlagNoDefault = 0x0200; - private const short FlagResizableDropDown = 0x0400; - + private const short FlagBtnLaunchedEditor = 0x0100; + private const short FlagNoDefault = 0x0200; + private const short FlagResizableDropDown = 0x0400; - private short flags = FlagNeedsRefresh | FlagIsNewSelection | FlagNeedUpdateUIBasedOnFont; - private short errorState = ERROR_NONE; - private Point ptOurLocation = new Point(1,1); - - private string originalTextValue = null; // original text, in case of ESC - private int cumulativeVerticalWheelDelta = 0; - private long rowSelectTime = 0; - private Point rowSelectPos = Point.Empty; // the position that we clicked on a row to test for double clicks - private Point lastMouseDown = InvalidPosition; - private int lastMouseMove; - private GridEntry lastClickedEntry; - - private IServiceProvider serviceProvider; - private IHelpService topHelpService; - private IHelpService helpService; - - private EventHandler ehValueClick; - private EventHandler ehLabelClick; - private EventHandler ehOutlineClick; - private EventHandler ehValueDblClick; - private EventHandler ehLabelDblClick; + private short flags = FlagNeedsRefresh | FlagIsNewSelection | FlagNeedUpdateUIBasedOnFont; + private short errorState = ERROR_NONE; + + private Point ptOurLocation = new Point(1, 1); + + private string originalTextValue = null; // original text, in case of ESC + private int cumulativeVerticalWheelDelta = 0; + private long rowSelectTime = 0; + private Point rowSelectPos = Point.Empty; // the position that we clicked on a row to test for double clicks + private Point lastMouseDown = InvalidPosition; + private int lastMouseMove; + private GridEntry lastClickedEntry; + + private IServiceProvider serviceProvider; + private IHelpService topHelpService; + private IHelpService helpService; + + private EventHandler ehValueClick; + private EventHandler ehLabelClick; + private EventHandler ehOutlineClick; + private EventHandler ehValueDblClick; + private EventHandler ehLabelDblClick; private GridEntryRecreateChildrenEventHandler ehRecreateChildren; - private int cachedRowHeight = -1; + private int cachedRowHeight = -1; IntPtr baseHfont; IntPtr boldHfont; @@ -171,8 +173,10 @@ internal class PropertyGridView : // So we don't have to localize its text. ] public PropertyGridView(IServiceProvider serviceProvider, PropertyGrid propertyGrid) - : base() { - if (DpiHelper.IsScalingRequired) { + : base() + { + if (DpiHelper.IsScalingRequired) + { paintWidth = DpiHelper.LogicalToDeviceUnitsX(PAINT_WIDTH); paintIndent = DpiHelper.LogicalToDeviceUnitsX(PAINT_INDENT); outlineSizeExplorerTreeStyle = DpiHelper.LogicalToDeviceUnitsX(OUTLINE_SIZE_EXPLORER_TREE_STYLE); @@ -189,11 +193,11 @@ public PropertyGridView(IServiceProvider serviceProvider, PropertyGrid propertyG ownerGrid = propertyGrid; this.serviceProvider = serviceProvider; - + SetStyle(ControlStyles.OptimizedDoubleBuffer, true); SetStyle(ControlStyles.ResizeRedraw, false); SetStyle(ControlStyles.UserMouse, true); - + // properties BackColor = SystemColors.Window; @@ -201,77 +205,96 @@ public PropertyGridView(IServiceProvider serviceProvider, PropertyGrid propertyG grayTextColor = SystemColors.GrayText; backgroundBrush = SystemBrushes.Window; TabStop = true; - + this.Text = "PropertyGridView"; CreateUI(); - LayoutWindow(true); + LayoutWindow(true); } - - public override Color BackColor { - get { + + public override Color BackColor + { + get + { return base.BackColor; } - set { + set + { this.backgroundBrush = new SolidBrush(value); base.BackColor = value; } } - internal Brush GetBackgroundBrush(Graphics g) { + internal Brush GetBackgroundBrush(Graphics g) + { return backgroundBrush; } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public bool CanCopy { - get { - if (selectedGridEntry == null) { + public bool CanCopy + { + get + { + if (selectedGridEntry == null) + { return false; } - if (!Edit.Focused) { + if (!Edit.Focused) + { string val = selectedGridEntry.GetPropertyTextValue(); return val != null && val.Length > 0; } - + return true; } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public bool CanCut { - get { - return CanCopy && selectedGridEntry.IsTextEditable; + public bool CanCut + { + get + { + return CanCopy && selectedGridEntry.IsTextEditable; } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public bool CanPaste { - get { + public bool CanPaste + { + get + { return selectedGridEntry != null && selectedGridEntry.IsTextEditable; // return gridView.CanPaste; } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public bool CanUndo { - get { - if (!Edit.Visible || !Edit.Focused) { + public bool CanUndo + { + get + { + if (!Edit.Visible || !Edit.Focused) + { return false; } return (0 != (int)Edit.SendMessage(Interop.EditMessages.EM_CANUNDO, 0, 0)); } } - internal DropDownButton DropDownButton { - get { - if (btnDropDown == null) { - #if DEBUG - if (ownerGrid.inGridViewCreate) { - throw new Exception("PERF REGRESSION - Creating item in grid view create"); - } - #endif - + internal DropDownButton DropDownButton + { + get + { + if (btnDropDown == null) + { +#if DEBUG + if (ownerGrid.inGridViewCreate) + { + throw new Exception("PERF REGRESSION - Creating item in grid view create"); + } +#endif + btnDropDown = new DropDownButton(); btnDropDown.UseComboBoxTheme = true; Bitmap bitmap = CreateResizedBitmap("Arrow", DOWNARROW_ICONWIDTH, DOWNARROW_ICONHEIGHT); @@ -289,15 +312,19 @@ internal DropDownButton DropDownButton { } } - private Button DialogButton { - get { - if (btnDialog == null) { + private Button DialogButton + { + get + { + if (btnDialog == null) + { - #if DEBUG - if (ownerGrid.inGridViewCreate) { +#if DEBUG + if (ownerGrid.inGridViewCreate) + { throw new Exception("PERF REGRESSION - Creating item in grid view create"); } - #endif +#endif btnDialog = new DropDownButton(); btnDialog.BackColor = SystemColors.Control; btnDialog.ForeColor = SystemColors.ControlText; @@ -314,17 +341,20 @@ private Button DialogButton { } } - - - private static Bitmap GetBitmapFromIcon(string iconName, int iconsWidth, int iconsHeight) { + + + private static Bitmap GetBitmapFromIcon(string iconName, int iconsWidth, int iconsHeight) + { Size desiredSize = new Size(iconsWidth, iconsHeight); Icon icon = new Icon(new Icon(typeof(PropertyGrid), iconName), desiredSize); Bitmap b = icon.ToBitmap(); icon.Dispose(); - - if ((b.Size.Width != iconsWidth || b.Size.Height != iconsHeight)) { + + if ((b.Size.Width != iconsWidth || b.Size.Height != iconsHeight)) + { Bitmap scaledBitmap = DpiHelper.CreateResizedBitmap(b, desiredSize); - if (scaledBitmap != null) { + if (scaledBitmap != null) + { b.Dispose(); b = scaledBitmap; } @@ -332,15 +362,19 @@ private static Bitmap GetBitmapFromIcon(string iconName, int iconsWidth, int ico return b; } - private GridViewEdit Edit { - get{ - if (edit == null) { + private GridViewEdit Edit + { + get + { + if (edit == null) + { - #if DEBUG - if (ownerGrid.inGridViewCreate) { +#if DEBUG + if (ownerGrid.inGridViewCreate) + { throw new Exception("PERF REGRESSION - Creating item in grid view create"); } - #endif +#endif edit = new GridViewEdit(this); edit.BorderStyle = BorderStyle.None; @@ -366,20 +400,26 @@ private GridViewEdit Edit { /// /// Represents the Editor's control accessible object. /// - internal AccessibleObject EditAccessibleObject { - get { + internal AccessibleObject EditAccessibleObject + { + get + { return Edit.AccessibilityObject; } } - private GridViewListBox DropDownListBox { - get { - if (listBox == null) { - #if DEBUG - if (ownerGrid.inGridViewCreate) { + private GridViewListBox DropDownListBox + { + get + { + if (listBox == null) + { +#if DEBUG + if (ownerGrid.inGridViewCreate) + { throw new Exception("PERF REGRESSION - Creating item in grid view create"); } - #endif +#endif listBox = new GridViewListBox(this); listBox.DrawMode = DrawMode.OwnerDrawFixed; @@ -399,137 +439,175 @@ private GridViewListBox DropDownListBox { /// /// Represents the DropDownListBox accessible object. /// - internal AccessibleObject DropDownListBoxAccessibleObject { - get { - if (DropDownListBox.Visible) { + internal AccessibleObject DropDownListBoxAccessibleObject + { + get + { + if (DropDownListBox.Visible) + { return DropDownListBox.AccessibilityObject; } return null; } } - - internal bool DrawValuesRightToLeft { - get { - if (edit != null && edit.IsHandleCreated) { + + internal bool DrawValuesRightToLeft + { + get + { + if (edit != null && edit.IsHandleCreated) + { int exStyle = unchecked((int)((long)UnsafeNativeMethods.GetWindowLong(new HandleRef(edit, edit.Handle), NativeMethods.GWL_EXSTYLE))); return ((exStyle & NativeMethods.WS_EX_RTLREADING) != 0); } - else { + else + { return false; } } } - internal bool DropDownVisible { - get { + internal bool DropDownVisible + { + get + { return dropDownHolder != null && dropDownHolder.Visible; } } - - public bool FocusInside { - get { - return(this.ContainsFocus || (dropDownHolder != null && dropDownHolder.ContainsFocus)); + + public bool FocusInside + { + get + { + return (this.ContainsFocus || (dropDownHolder != null && dropDownHolder.ContainsFocus)); } } - - internal Color GrayTextColor{ - get { + + internal Color GrayTextColor + { + get + { // if changed from the default, then the set value is returned - if (grayTextColorModified) { + if (grayTextColorModified) + { return grayTextColor; } - if (this.ForeColor.ToArgb() == SystemColors.WindowText.ToArgb()) { + if (this.ForeColor.ToArgb() == SystemColors.WindowText.ToArgb()) + { return SystemColors.GrayText; } - + // compute the new color by halving the value of the old one. // int colorRGB = this.ForeColor.ToArgb(); - + int alphaValue = (colorRGB >> 24) & 0xff; - if (alphaValue != 0) { + if (alphaValue != 0) + { alphaValue /= 2; colorRGB &= 0xFFFFFF; colorRGB |= (int)((alphaValue << 24) & 0xFF000000); } - else { + else + { colorRGB /= 2; } return Color.FromArgb(colorRGB); } - set { + set + { grayTextColor = value; grayTextColorModified = true; } } - // This dialog's width is defined by the summary message - // in the top pane. We don't restrict dialog width in any way. - // Use caution and check at all DPI scaling factors if adding a new message - // to be displayed in the top pane. - private GridErrorDlg ErrorDialog { - get { - if (this.errorDlg == null) { + // This dialog's width is defined by the summary message + // in the top pane. We don't restrict dialog width in any way. + // Use caution and check at all DPI scaling factors if adding a new message + // to be displayed in the top pane. + private GridErrorDlg ErrorDialog + { + get + { + if (this.errorDlg == null) + { errorDlg = new GridErrorDlg(this.ownerGrid); } return errorDlg; } } - private bool HasEntries { - get{ + private bool HasEntries + { + get + { return topLevelGridEntries != null && topLevelGridEntries.Count > 0; } } - - protected int InternalLabelWidth { - get { - if (GetFlag(FlagNeedUpdateUIBasedOnFont)) { + + protected int InternalLabelWidth + { + get + { + if (GetFlag(FlagNeedUpdateUIBasedOnFont)) + { UpdateUIBasedOnFont(true); } - if (labelWidth == -1) { + if (labelWidth == -1) + { SetConstants(); } return labelWidth; } } - - internal int LabelPaintMargin { - - set { + + internal int LabelPaintMargin + { + + set + { requiredLabelPaintMargin = (short)Math.Max(Math.Max(value, requiredLabelPaintMargin), GDIPLUS_SPACE); } } - protected bool NeedsCommit{ - get { + protected bool NeedsCommit + { + get + { string text; - if (edit==null || !Edit.Visible) { + if (edit == null || !Edit.Visible) + { return false; } text = Edit.Text; if (((text == null || text.Length == 0) && (originalTextValue == null || originalTextValue.Length == 0)) || - (text != null && originalTextValue != null && text.Equals(originalTextValue))) { + (text != null && originalTextValue != null && text.Equals(originalTextValue))) + { return false; } return true; } } - public PropertyGrid OwnerGrid{ - get{ + public PropertyGrid OwnerGrid + { + get + { return this.ownerGrid; } } - protected int RowHeight { - get { - if (cachedRowHeight == -1) { + protected int RowHeight + { + get + { + if (cachedRowHeight == -1) + { cachedRowHeight = (int)Font.Height + 2; } return cachedRowHeight; @@ -542,23 +620,29 @@ protected int RowHeight { /// is used useful to position the context menu when the menu is invoked /// via the keyboard. /// - public Point ContextMenuDefaultLocation { - get { + public Point ContextMenuDefaultLocation + { + get + { // get the rect for the currently selected prop name, find the middle - Rectangle rect = GetRectangle( selectedRow, ROWLABEL ); - Point pt = PointToScreen( new Point( rect.X, rect.Y ) ); + Rectangle rect = GetRectangle(selectedRow, ROWLABEL); + Point pt = PointToScreen(new Point(rect.X, rect.Y)); return new Point(pt.X + (rect.Width / 2), pt.Y + (rect.Height / 2)); } } - private ScrollBar ScrollBar { - get { - if (scrollBar == null) { - #if DEBUG - if (ownerGrid.inGridViewCreate) { + private ScrollBar ScrollBar + { + get + { + if (scrollBar == null) + { +#if DEBUG + if (ownerGrid.inGridViewCreate) + { throw new Exception("PERF REGRESSION - Creating item in grid view create"); } - #endif +#endif scrollBar = new VScrollBar(); scrollBar.Scroll += new ScrollEventHandler(this.OnScroll); Controls.Add(scrollBar); @@ -566,28 +650,35 @@ private ScrollBar ScrollBar { return scrollBar; } } - - internal GridEntry SelectedGridEntry { - get { + + internal GridEntry SelectedGridEntry + { + get + { return selectedGridEntry; } - set { - if (allGridEntries != null) { - foreach (GridEntry e in allGridEntries) { - if (e == value) { + set + { + if (allGridEntries != null) + { + foreach (GridEntry e in allGridEntries) + { + if (e == value) + { SelectGridEntry(value, true); return; } } } - - GridEntry gr = FindEquivalentGridEntry(new GridEntryCollection(null, new GridEntry[]{value})); - - if (gr != null) { + + GridEntry gr = FindEquivalentGridEntry(new GridEntryCollection(null, new GridEntry[] { value })); + + if (gr != null) + { SelectGridEntry(gr, true); return; } - + throw new ArgumentException(SR.PropertyGridInvalidGridEntry); } } @@ -678,40 +769,47 @@ public string SelectedPropertyName { } } */ - + /// /// Returns or sets the IServiceProvider the PropertyGridView will use to obtain /// services. This may be null. /// - public IServiceProvider ServiceProvider { - get { - return serviceProvider; + public IServiceProvider ServiceProvider + { + get + { + return serviceProvider; } - set { - if (value != serviceProvider) { + set + { + if (value != serviceProvider) + { this.serviceProvider = value; - + topHelpService = null; if (helpService != null && helpService is IDisposable) ((IDisposable)helpService).Dispose(); helpService = null; - } + } } - } - + } + /// /// Indicates whether or not the control supports UIA Providers via /// IRawElementProviderFragment/IRawElementProviderFragmentRoot interfaces. /// internal override bool SupportsUiaProviders => true; - - private int TipColumn { - get{ - return(tipInfo & unchecked((int)0xFFFF0000)) >> 16; + + private int TipColumn + { + get + { + return (tipInfo & unchecked((int)0xFFFF0000)) >> 16; } - set{ + set + { // clear the column tipInfo &= 0xFFFF; @@ -721,11 +819,14 @@ private int TipColumn { } } - private int TipRow { - get{ + private int TipRow + { + get + { return tipInfo & 0xFFFF; } - set{ + set + { // clear the row tipInfo &= unchecked((int)0xFFFF0000); @@ -735,18 +836,22 @@ private int TipRow { } } - private GridToolTip ToolTip { - get { - if (toolTip == null) { - #if DEBUG - if (ownerGrid.inGridViewCreate) { + private GridToolTip ToolTip + { + get + { + if (toolTip == null) + { +#if DEBUG + if (ownerGrid.inGridViewCreate) + { throw new Exception("PERF REGRESSION - Creating item in grid view create"); } - #endif - toolTip = new GridToolTip(new Control[]{this, Edit}); +#endif + toolTip = new GridToolTip(new Control[] { this, Edit }); toolTip.ToolTip = string.Empty; toolTip.Font = this.Font; - } + } return toolTip; } } @@ -754,19 +859,24 @@ private GridToolTip ToolTip { /// /// Gets the top level grid entries. /// - internal GridEntryCollection TopLevelGridEntries { - get { + internal GridEntryCollection TopLevelGridEntries + { + get + { return topLevelGridEntries; } } - internal GridEntryCollection AccessibilityGetGridEntries() { + internal GridEntryCollection AccessibilityGetGridEntries() + { return GetAllGridEntries(); } - internal Rectangle AccessibilityGetGridEntryBounds(GridEntry gridEntry) { + internal Rectangle AccessibilityGetGridEntryBounds(GridEntry gridEntry) + { int row = GetRowFromGridEntry(gridEntry); - if (row == -1) { + if (row == -1) + { return new Rectangle(0, 0, 0, 0); } Rectangle rect = GetRectangle(row, ROWVALUE | ROWLABEL); @@ -778,42 +888,52 @@ internal Rectangle AccessibilityGetGridEntryBounds(GridEntry gridEntry) { return new Rectangle(pt.x, pt.y, rect.Width, rect.Height); } - - internal int AccessibilityGetGridEntryChildID(GridEntry gridEntry) { - + + internal int AccessibilityGetGridEntryChildID(GridEntry gridEntry) + { + GridEntryCollection ipes = GetAllGridEntries(); - - if (ipes == null) { + + if (ipes == null) + { return -1; } - + // Find the grid entry and return its ID // - for(int index = 0; index < ipes.Count; ++index) { - if (ipes[index].Equals(gridEntry)) { + for (int index = 0; index < ipes.Count; ++index) + { + if (ipes[index].Equals(gridEntry)) + { return index; } } - + return -1; } - internal void AccessibilitySelect(GridEntry entry) { - SelectGridEntry(entry, true); + internal void AccessibilitySelect(GridEntry entry) + { + SelectGridEntry(entry, true); Focus(); } - private void AddGridEntryEvents(GridEntryCollection ipeArray, int startIndex, int count) { - if (ipeArray == null) { + private void AddGridEntryEvents(GridEntryCollection ipeArray, int startIndex, int count) + { + if (ipeArray == null) + { return; } - - if (count == -1) { + + if (count == -1) + { count = ipeArray.Count - startIndex; } - for (int i= startIndex; i < (startIndex + count); i++) { - if (ipeArray[i] != null) { + for (int i = startIndex; i < (startIndex + count); i++) + { + if (ipeArray[i] != null) + { GridEntry ge = ipeArray.GetEntry(i); ge.AddOnValueClick(ehValueClick); ge.AddOnLabelClick(ehLabelClick); @@ -825,44 +945,54 @@ private void AddGridEntryEvents(GridEntryCollection ipeArray, int startIndex, in } } } - - protected virtual void AdjustOrigin(System.Drawing.Graphics g, Point newOrigin, ref Rectangle r) { - - Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Adjusting paint origin to (" + newOrigin.X.ToString(CultureInfo.InvariantCulture) + "," + newOrigin.Y.ToString(CultureInfo.InvariantCulture) + ")"); + + protected virtual void AdjustOrigin(System.Drawing.Graphics g, Point newOrigin, ref Rectangle r) + { + + Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Adjusting paint origin to (" + newOrigin.X.ToString(CultureInfo.InvariantCulture) + "," + newOrigin.Y.ToString(CultureInfo.InvariantCulture) + ")"); g.ResetTransform(); g.TranslateTransform(newOrigin.X, newOrigin.Y); r.Offset(-newOrigin.X, -newOrigin.Y); } - private void CancelSplitterMove() { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:CancelSplitterMove"); - if (GetFlag(FlagIsSplitterMove)) { + private void CancelSplitterMove() + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:CancelSplitterMove"); + if (GetFlag(FlagIsSplitterMove)) + { SetFlag(FlagIsSplitterMove, false); CaptureInternal = false; - - if (selectedRow != -1) { + + if (selectedRow != -1) + { SelectRow(selectedRow); } } } - internal GridPositionData CaptureGridPositionData() { + internal GridPositionData CaptureGridPositionData() + { return new GridPositionData(this); } - private void ClearGridEntryEvents(GridEntryCollection ipeArray, int startIndex, int count) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:ClearGridEntryEvents"); - if (ipeArray == null) { + private void ClearGridEntryEvents(GridEntryCollection ipeArray, int startIndex, int count) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:ClearGridEntryEvents"); + if (ipeArray == null) + { return; } - - if (count == -1) { + + if (count == -1) + { count = ipeArray.Count - startIndex; } - for (int i = startIndex ; i < (startIndex + count); i++) { - if (ipeArray[i] != null) { + for (int i = startIndex; i < (startIndex + count); i++) + { + if (ipeArray[i] != null) + { GridEntry ge = ipeArray.GetEntry(i); ge.RemoveOnValueClick(ehValueClick); ge.RemoveOnLabelClick(ehLabelClick); @@ -875,11 +1005,13 @@ private void ClearGridEntryEvents(GridEntryCollection ipeArray, int startIndex, } } - public void ClearProps() { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:ClearProps"); + public void ClearProps() + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:ClearProps"); - if (!HasEntries) { + if (!HasEntries) + { return; } @@ -896,28 +1028,34 @@ public void ClearProps() { /// Closes a previously opened drop down. This should be called by the /// drop down when the user does something that should close it. /// - public void /* IWindowsFormsEditorService. */ CloseDropDown() { + public void /* IWindowsFormsEditorService. */ CloseDropDown() + { CloseDropDownInternal(true); } - private void CloseDropDownInternal(bool resetFocus) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:CloseDropDown"); + private void CloseDropDownInternal(bool resetFocus) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:CloseDropDown"); // the activation code in the DropDownHolder can cause this to recurse... - if (GetFlag(FlagDropDownClosing)) { + if (GetFlag(FlagDropDownClosing)) + { return; } - try { + try + { SetFlag(FlagDropDownClosing, true); - if (dropDownHolder != null && dropDownHolder.Visible) { + if (dropDownHolder != null && dropDownHolder.Visible) + { - if (dropDownHolder.Component == DropDownListBox && GetFlag(FlagDropDownCommit)) { - OnListClick(null, null); + if (dropDownHolder.Component == DropDownListBox && GetFlag(FlagDropDownCommit)) + { + OnListClick(null, null); } Edit.Filter = false; - + // disable the ddh so it wont' steal the focus back // dropDownHolder.SetComponent(null, false); @@ -925,94 +1063,113 @@ private void CloseDropDownInternal(bool resetFocus) { // when we disable the dropdown holder, focus will be lost, // so put it onto one of our children first. - if (resetFocus) { - if (DialogButton.Visible) { + if (resetFocus) + { + if (DialogButton.Visible) + { DialogButton.Focus(); } - else if (DropDownButton.Visible) { + else if (DropDownButton.Visible) + { DropDownButton.Focus(); } - else if (Edit.Visible) { + else if (Edit.Visible) + { Edit.Focus(); } - else { + else + { Focus(); } - - if (selectedRow != -1) { + + if (selectedRow != -1) + { SelectRow(selectedRow); } } } } - finally { + finally + { SetFlag(FlagDropDownClosing, false); } } - private void CommonEditorHide() { - CommonEditorHide(false); + private void CommonEditorHide() + { + CommonEditorHide(false); } - private void CommonEditorHide(bool always) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:CommonEditorHide"); + private void CommonEditorHide(bool always) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:CommonEditorHide"); - if (!always && !HasEntries) { + if (!always && !HasEntries) + { return; } - + CloseDropDown(); bool gotfocus = false; - - if (Edit.Focused || DialogButton.Focused || DropDownButton.Focused) { - if (IsHandleCreated && Visible && Enabled) { + if (Edit.Focused || DialogButton.Focused || DropDownButton.Focused) + { + + if (IsHandleCreated && Visible && Enabled) + { gotfocus = IntPtr.Zero != UnsafeNativeMethods.SetFocus(new HandleRef(this, Handle)); } } - - try { - // We do this becuase the Focus call above doesn't always stick, so - // we make the Edit think that it doesn't have focus. this prevents - // ActiveControl code on the containercontrol from moving focus elsewhere - // when the dropdown closes. - Edit.DontFocus = true; - if (Edit.Focused && !gotfocus) { - gotfocus = this.Focus(); - } - Edit.Visible = false; - - Edit.SelectionStart = 0; - Edit.SelectionLength = 0; - - if (DialogButton.Focused && !gotfocus) { - gotfocus = this.Focus(); - } - DialogButton.Visible = false; - - if (DropDownButton.Focused && !gotfocus) { - gotfocus = this.Focus(); - } - DropDownButton.Visible = false; - currentEditor = null; + + try + { + // We do this becuase the Focus call above doesn't always stick, so + // we make the Edit think that it doesn't have focus. this prevents + // ActiveControl code on the containercontrol from moving focus elsewhere + // when the dropdown closes. + Edit.DontFocus = true; + if (Edit.Focused && !gotfocus) + { + gotfocus = this.Focus(); + } + Edit.Visible = false; + + Edit.SelectionStart = 0; + Edit.SelectionLength = 0; + + if (DialogButton.Focused && !gotfocus) + { + gotfocus = this.Focus(); + } + DialogButton.Visible = false; + + if (DropDownButton.Focused && !gotfocus) + { + gotfocus = this.Focus(); + } + DropDownButton.Visible = false; + currentEditor = null; } - finally { - Edit.DontFocus = false; + finally + { + Edit.DontFocus = false; } } - protected virtual void CommonEditorSetup(Control ctl) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:CommonEditorSetup"); + protected virtual void CommonEditorSetup(Control ctl) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:CommonEditorSetup"); ctl.Visible = false; Controls.Add(ctl); } - protected virtual void CommonEditorUse(Control ctl, Rectangle rectTarget) { + protected virtual void CommonEditorUse(Control ctl, Rectangle rectTarget) + { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:CommonEditorUse"); - Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Showing common editors"); + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:CommonEditorUse"); + Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Showing common editors"); Debug.Assert(ctl != null, "Null control passed to CommonEditorUse"); @@ -1021,27 +1178,32 @@ protected virtual void CommonEditorUse(Control ctl, Rectangle rectTarget) { // the client rect minus the border line Rectangle clientRect = this.ClientRectangle; - clientRect.Inflate(-1,-1); + clientRect.Inflate(-1, -1); - try { + try + { rectTarget = Rectangle.Intersect(clientRect, rectTarget); - //if (ctl is Button) - // Debug.WriteStackTrace(); + //if (ctl is Button) + // Debug.WriteStackTrace(); - if (!rectTarget.IsEmpty) { - if (!rectTarget.Equals(rectCur)) { - ctl.SetBounds(rectTarget.X,rectTarget.Y, - rectTarget.Width,rectTarget.Height); + if (!rectTarget.IsEmpty) + { + if (!rectTarget.Equals(rectCur)) + { + ctl.SetBounds(rectTarget.X, rectTarget.Y, + rectTarget.Width, rectTarget.Height); } ctl.Visible = true; } } - catch { + catch + { rectTarget = Rectangle.Empty; } - if (rectTarget.IsEmpty) { + if (rectTarget.IsEmpty) + { ctl.Visible = false; } @@ -1050,11 +1212,14 @@ protected virtual void CommonEditorUse(Control ctl, Rectangle rectTarget) { } - private /*protected virtual*/ int CountPropsFromOutline(GridEntryCollection rgipes) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:CountPropsFromOutLine"); - if (rgipes == null) return 0; + private /*protected virtual*/ int CountPropsFromOutline(GridEntryCollection rgipes) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:CountPropsFromOutLine"); + if (rgipes == null) + return 0; int cProps = rgipes.Count; - for (int i = 0; i < rgipes.Count; i++) { + for (int i = 0; i < rgipes.Count; i++) + { if (((GridEntry)rgipes[i]).InternalExpanded) cProps += CountPropsFromOutline(((GridEntry)rgipes[i]).Children); } @@ -1065,23 +1230,28 @@ protected virtual void CommonEditorUse(Control ctl, Rectangle rectTarget) { /// Constructs the new instance of the accessibility object for this control. Subclasses /// should not call base.CreateAccessibilityObject. /// - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new PropertyGridViewAccessibleObject(this, ownerGrid); } - - - private Bitmap CreateResizedBitmap(string icon, int width, int height) { + + + private Bitmap CreateResizedBitmap(string icon, int width, int height) + { Bitmap bitmap = null; var scaledIconWidth = width; var scaledIconHeight = height; - try { + try + { //scale for per-monitor DPI. - if (DpiHelper.IsPerMonitorV2Awareness) { + if (DpiHelper.IsPerMonitorV2Awareness) + { scaledIconWidth = LogicalToDeviceUnits(width); scaledIconHeight = LogicalToDeviceUnits(height); } - else if (DpiHelper.IsScalingRequired) { + else if (DpiHelper.IsScalingRequired) + { // only primary monitor scaling. scaledIconWidth = DpiHelper.LogicalToDeviceUnitsX(width); scaledIconHeight = DpiHelper.LogicalToDeviceUnitsY(height); @@ -1089,24 +1259,31 @@ private Bitmap CreateResizedBitmap(string icon, int width, int height) { bitmap = GetBitmapFromIcon(icon, scaledIconWidth, scaledIconHeight); } - catch (Exception e) { + catch (Exception e) + { Debug.Fail(e.ToString()); bitmap = new Bitmap(scaledIconWidth, scaledIconHeight); } return bitmap; } - - protected virtual void CreateUI() { + + protected virtual void CreateUI() + { UpdateUIBasedOnFont(false); } - protected override void Dispose(bool disposing) { - if (disposing) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:Dispose"); - if (scrollBar != null) scrollBar.Dispose(); - if (listBox != null) listBox.Dispose(); - if (dropDownHolder != null) dropDownHolder.Dispose(); + protected override void Dispose(bool disposing) + { + if (disposing) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:Dispose"); + if (scrollBar != null) + scrollBar.Dispose(); + if (listBox != null) + listBox.Dispose(); + if (dropDownHolder != null) + dropDownHolder.Dispose(); scrollBar = null; listBox = null; dropDownHolder = null; @@ -1115,7 +1292,7 @@ protected override void Dispose(bool disposing) { topLevelGridEntries = null; allGridEntries = null; serviceProvider = null; - + topHelpService = null; if (helpService != null && helpService is IDisposable) @@ -1123,28 +1300,33 @@ protected override void Dispose(bool disposing) { helpService = null; - if (edit != null) { + if (edit != null) + { edit.Dispose(); edit = null; } - if (fontBold != null) { + if (fontBold != null) + { fontBold.Dispose(); fontBold = null; } - if (btnDropDown != null) { + if (btnDropDown != null) + { btnDropDown.Dispose(); btnDropDown = null; } - if (btnDialog != null) { + if (btnDialog != null) + { btnDialog.Dispose(); btnDialog = null; } - if (toolTip != null) { + if (toolTip != null) + { toolTip.Dispose(); toolTip = null; } @@ -1152,110 +1334,136 @@ protected override void Dispose(bool disposing) { base.Dispose(disposing); } - - public void DoCopyCommand() { - if (this.CanCopy) { - if (Edit.Focused) { + + public void DoCopyCommand() + { + if (this.CanCopy) + { + if (Edit.Focused) + { Edit.Copy(); - } - else { - Clipboard.SetDataObject(selectedGridEntry.GetPropertyTextValue()); - } + } + else + { + Clipboard.SetDataObject(selectedGridEntry.GetPropertyTextValue()); + } } } - - public void DoCutCommand() { - if (this.CanCut) { - DoCopyCommand(); - if (Edit.Visible) { + + public void DoCutCommand() + { + if (this.CanCut) + { + DoCopyCommand(); + if (Edit.Visible) + { Edit.Cut(); - } + } } } - public void DoPasteCommand() { - if (this.CanPaste && Edit.Visible) { - if (Edit.Focused) { + public void DoPasteCommand() + { + if (this.CanPaste && Edit.Visible) + { + if (Edit.Focused) + { Edit.Paste(); - } - else { - IDataObject dataObj = Clipboard.GetDataObject(); - if (dataObj != null) { - string data = (string)dataObj.GetData(typeof(string)); - if (data != null) { - Edit.Focus(); - Edit.Text = data; - SetCommitError(ERROR_NONE, true); - } - } - } + } + else + { + IDataObject dataObj = Clipboard.GetDataObject(); + if (dataObj != null) + { + string data = (string)dataObj.GetData(typeof(string)); + if (data != null) + { + Edit.Focus(); + Edit.Text = data; + SetCommitError(ERROR_NONE, true); + } + } + } } } - - public void DoUndoCommand() { - if (this.CanUndo && Edit.Visible) { - Edit.SendMessage(Interop.WindowMessages.WM_UNDO, 0, 0); + + public void DoUndoCommand() + { + if (this.CanUndo && Edit.Visible) + { + Edit.SendMessage(Interop.WindowMessages.WM_UNDO, 0, 0); } } - - internal void DumpPropsToConsole(GridEntry entry, string prefix) { - + + internal void DumpPropsToConsole(GridEntry entry, string prefix) + { + Type propType = entry.PropertyType; - - if (entry.PropertyValue != null) { - propType = entry.PropertyValue.GetType(); + + if (entry.PropertyValue != null) + { + propType = entry.PropertyValue.GetType(); } - - System.Console.WriteLine(prefix + entry.PropertyLabel + ", value type=" + (propType == null ? "(null)" : propType.FullName) + ", value=" + (entry.PropertyValue == null ? "(null)" : entry.PropertyValue.ToString()) + - ", flags=" + entry.Flags.ToString(CultureInfo.InvariantCulture) + + + System.Console.WriteLine(prefix + entry.PropertyLabel + ", value type=" + (propType == null ? "(null)" : propType.FullName) + ", value=" + (entry.PropertyValue == null ? "(null)" : entry.PropertyValue.ToString()) + + ", flags=" + entry.Flags.ToString(CultureInfo.InvariantCulture) + ", TypeConverter=" + (entry.TypeConverter == null ? "(null)" : entry.TypeConverter.GetType().FullName) + ", UITypeEditor=" + ((entry.UITypeEditor == null ? "(null)" : entry.UITypeEditor.GetType().FullName))); GridEntryCollection children = entry.Children; - - if (children != null) { - foreach(GridEntry g in children) { - DumpPropsToConsole(g, prefix + "\t"); - } + + if (children != null) + { + foreach (GridEntry g in children) + { + DumpPropsToConsole(g, prefix + "\t"); + } } } - private int GetIPELabelIndent(GridEntry gridEntry) { + private int GetIPELabelIndent(GridEntry gridEntry) + { //return OUTLINE_INDENT*(gridEntry.PropertyDepth + 1); return gridEntry.PropertyLabelIndent + 1; } - private int GetIPELabelLength(System.Drawing.Graphics g, GridEntry gridEntry) { + private int GetIPELabelLength(System.Drawing.Graphics g, GridEntry gridEntry) + { SizeF sizeF = PropertyGrid.MeasureTextHelper.MeasureText(this.ownerGrid, g, gridEntry.PropertyLabel, Font); Size size = Size.Ceiling(sizeF); return ptOurLocation.X + GetIPELabelIndent(gridEntry) + size.Width; } - private bool IsIPELabelLong(System.Drawing.Graphics g,GridEntry gridEntry) { - if (gridEntry == null) return false; - int length = GetIPELabelLength(g,gridEntry); - return(length > ptOurLocation.X + InternalLabelWidth); + private bool IsIPELabelLong(System.Drawing.Graphics g, GridEntry gridEntry) + { + if (gridEntry == null) + return false; + int length = GetIPELabelLength(g, gridEntry); + return (length > ptOurLocation.X + InternalLabelWidth); } - protected virtual void DrawLabel(System.Drawing.Graphics g, int row, Rectangle rect, bool selected, bool fLongLabelRequest, ref Rectangle clipRect) { + protected virtual void DrawLabel(System.Drawing.Graphics g, int row, Rectangle rect, bool selected, bool fLongLabelRequest, ref Rectangle clipRect) + { GridEntry gridEntry = GetGridEntryFromRow(row); if (gridEntry == null || rect.IsEmpty) return; - Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Drawing label for property " + gridEntry.PropertyLabel); - + Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Drawing label for property " + gridEntry.PropertyLabel); + Point newOrigin = new Point(rect.X, rect.Y); Rectangle cr = Rectangle.Intersect(rect, clipRect); - - if (cr.IsEmpty) { + + if (cr.IsEmpty) + { return; } - + AdjustOrigin(g, newOrigin, ref rect); cr.Offset(-newOrigin.X, -newOrigin.Y); - - try { + + try + { try { bool fLongLabel = false; @@ -1275,88 +1483,109 @@ protected virtual void DrawLabel(System.Drawing.Graphics g, int row, Rectangle r Debug.Fail(ex.ToString()); } } - finally { + finally + { ResetOrigin(g); } } - protected virtual void DrawValueEntry(System.Drawing.Graphics g, int row, ref Rectangle clipRect) { + protected virtual void DrawValueEntry(System.Drawing.Graphics g, int row, ref Rectangle clipRect) + { GridEntry gridEntry = GetGridEntryFromRow(row); if (gridEntry == null) return; - Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Drawing value for property " + gridEntry.PropertyLabel); + Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Drawing value for property " + gridEntry.PropertyLabel); - Rectangle r = GetRectangle(row,ROWVALUE); + Rectangle r = GetRectangle(row, ROWVALUE); Point newOrigin = new Point(r.X, r.Y); Rectangle cr = Rectangle.Intersect(clipRect, r); - if (cr.IsEmpty) { + if (cr.IsEmpty) + { return; } - + AdjustOrigin(g, newOrigin, ref r); cr.Offset(-newOrigin.X, -newOrigin.Y); - try { - try { - DrawValueEntry(g,r, cr,gridEntry,null, true); + try + { + try + { + DrawValueEntry(g, r, cr, gridEntry, null, true); } - catch { + catch + { } } - finally { + finally + { ResetOrigin(g); } } - private /*protected virtual*/ void DrawValueEntry(System.Drawing.Graphics g, Rectangle rect, Rectangle clipRect, GridEntry gridEntry, object value, bool fetchValue) { + private /*protected virtual*/ void DrawValueEntry(System.Drawing.Graphics g, Rectangle rect, Rectangle clipRect, GridEntry gridEntry, object value, bool fetchValue) + { DrawValue(g, rect, clipRect, gridEntry, value, false, true, fetchValue, true); } - private void DrawValue(System.Drawing.Graphics g, Rectangle rect, Rectangle clipRect, GridEntry gridEntry, object value, bool drawSelected, bool checkShouldSerialize, bool fetchValue, bool paintInPlace) { + private void DrawValue(System.Drawing.Graphics g, Rectangle rect, Rectangle clipRect, GridEntry gridEntry, object value, bool drawSelected, bool checkShouldSerialize, bool fetchValue, bool paintInPlace) + { GridEntry.PaintValueFlags paintFlags = GridEntry.PaintValueFlags.None; - if (drawSelected) { + if (drawSelected) + { paintFlags |= GridEntry.PaintValueFlags.DrawSelected; } - if (checkShouldSerialize) { - paintFlags |= GridEntry.PaintValueFlags.CheckShouldSerialize; + if (checkShouldSerialize) + { + paintFlags |= GridEntry.PaintValueFlags.CheckShouldSerialize; } - if (fetchValue) { + if (fetchValue) + { paintFlags |= GridEntry.PaintValueFlags.FetchValue; } - if (paintInPlace) { + if (paintInPlace) + { paintFlags |= GridEntry.PaintValueFlags.PaintInPlace; } gridEntry.PaintValue(value, g, rect, clipRect, paintFlags); } - - private void F4Selection(bool popupModalDialog) { + + private void F4Selection(bool popupModalDialog) + { GridEntry gridEntry = GetGridEntryFromRow(selectedRow); - if (gridEntry == null) return; + if (gridEntry == null) + return; // if we are in an errorState, just put the focus back on the Edit - if (errorState != ERROR_NONE && Edit.Visible) { + if (errorState != ERROR_NONE && Edit.Visible) + { Edit.Focus(); return; } - if (DropDownButton.Visible) { + if (DropDownButton.Visible) + { PopupDialog(selectedRow); } - else if (DialogButton.Visible) { - if (popupModalDialog) { + else if (DialogButton.Visible) + { + if (popupModalDialog) + { PopupDialog(selectedRow); } - else { + else + { DialogButton.Focus(); } } - else if (Edit.Visible) { + else if (Edit.Visible) + { Edit.Focus(); SelectEdit(false); } @@ -1368,23 +1597,29 @@ private void F4Selection(bool popupModalDialog) { //is read-only. This code is a duplicate of the error handling in //CommitValue(). [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")] - public void DoubleClickRow(int row, bool toggleExpand, int type) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:DoubleClickRow"); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")] + public void DoubleClickRow(int row, bool toggleExpand, int type) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:DoubleClickRow"); GridEntry gridEntry = GetGridEntryFromRow(row); - if (gridEntry == null) return; + if (gridEntry == null) + return; - Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Property " + gridEntry.PropertyLabel + " double clicked"); + Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Property " + gridEntry.PropertyLabel + " double clicked"); - if (!toggleExpand || type == ROWVALUE) { - try { + if (!toggleExpand || type == ROWVALUE) + { + try + { bool action = gridEntry.DoubleClickPropertyValue(); - if (action) { + if (action) + { SelectRow(row); return; } } - catch (Exception ex) { + catch (Exception ex) + { SetCommitError(ERROR_THROWN); ShowInvalidMessage(gridEntry.PropertyLabel, null, ex); return; @@ -1393,21 +1628,26 @@ public void DoubleClickRow(int row, bool toggleExpand, int type) { SelectGridEntry(gridEntry, true); - if (type == ROWLABEL && toggleExpand && gridEntry.Expandable) { - SetExpand(gridEntry,!gridEntry.InternalExpanded); + if (type == ROWLABEL && toggleExpand && gridEntry.Expandable) + { + SetExpand(gridEntry, !gridEntry.InternalExpanded); return; } - - if (gridEntry.IsValueEditable && gridEntry.Enumerable) { + + if (gridEntry.IsValueEditable && gridEntry.Enumerable) + { int index = GetCurrentValueIndex(gridEntry); - if (index != -1) { + if (index != -1) + { object[] values = gridEntry.GetPropertyValueList(); - if (values == null || index >= (values.Length - 1)) { + if (values == null || index >= (values.Length - 1)) + { index = 0; } - else { + else + { index++; } @@ -1417,27 +1657,33 @@ public void DoubleClickRow(int row, bool toggleExpand, int type) { return; } } - - if (Edit.Visible) { + + if (Edit.Visible) + { Edit.Focus(); SelectEdit(false); return; } } - public Font GetBaseFont() { + public Font GetBaseFont() + { return Font; } - public Font GetBoldFont() { - if (fontBold == null) { + public Font GetBoldFont() + { + if (fontBold == null) + { fontBold = new Font(this.Font, FontStyle.Bold); } return fontBold; } - internal IntPtr GetBaseHfont() { - if (baseHfont == IntPtr.Zero) { + internal IntPtr GetBaseHfont() + { + if (baseHfont == IntPtr.Zero) + { baseHfont = GetBaseFont().ToHfont(); } return baseHfont; @@ -1449,19 +1695,24 @@ internal IntPtr GetBaseHfont() { /// The point x coordinate. /// The point y coordinate. /// The found grid element. - internal GridEntry GetElementFromPoint(int x, int y) { + internal GridEntry GetElementFromPoint(int x, int y) + { Point point = new Point(x, y); var allGridEntries = GetAllGridEntries(); GridEntry[] targetEntries = new GridEntry[allGridEntries.Count]; - try { + try + { GetGridEntriesFromOutline(allGridEntries, 0, allGridEntries.Count - 1, targetEntries); } - catch (Exception ex) { + catch (Exception ex) + { Debug.Fail(ex.ToString()); } - foreach (GridEntry gridEntry in targetEntries) { - if (gridEntry.AccessibilityObject.Bounds.Contains(point)) { + foreach (GridEntry gridEntry in targetEntries) + { + if (gridEntry.AccessibilityObject.Bounds.Contains(point)) + { return gridEntry; } } @@ -1469,24 +1720,30 @@ internal GridEntry GetElementFromPoint(int x, int y) { return null; } - internal IntPtr GetBoldHfont() { - if (boldHfont == IntPtr.Zero) { + internal IntPtr GetBoldHfont() + { + if (boldHfont == IntPtr.Zero) + { boldHfont = GetBoldFont().ToHfont(); } return boldHfont; } - private bool GetFlag(short flag) { + private bool GetFlag(short flag) + { return (this.flags & flag) != 0; } - public virtual Color GetLineColor() { + public virtual Color GetLineColor() + { return ownerGrid.LineColor; } - public virtual Brush GetLineBrush(Graphics g) { - if (ownerGrid.lineBrush == null) { + public virtual Brush GetLineBrush(Graphics g) + { + if (ownerGrid.lineBrush == null) + { Color clr = g.GetNearestColor(ownerGrid.LineColor); ownerGrid.lineBrush = new SolidBrush(clr); } @@ -1505,18 +1762,21 @@ public virtual Color GetSelectedItemWithFocusBackColor() public virtual Brush GetSelectedItemWithFocusBackBrush(Graphics g) { - if (ownerGrid.selectedItemWithFocusBackBrush == null) { + if (ownerGrid.selectedItemWithFocusBackBrush == null) + { Color clr = g.GetNearestColor(ownerGrid.SelectedItemWithFocusBackColor); ownerGrid.selectedItemWithFocusBackBrush = new SolidBrush(clr); } return ownerGrid.selectedItemWithFocusBackBrush; } - public virtual IntPtr GetHostHandle() { + public virtual IntPtr GetHostHandle() + { return Handle; } - public virtual int GetLabelWidth() { + public virtual int GetLabelWidth() + { return InternalLabelWidth; } @@ -1525,36 +1785,48 @@ internal bool IsExplorerTreeSupported get => ownerGrid.CanShowVisualStyleGlyphs && VisualStyleRenderer.IsSupported; } - public virtual int GetOutlineIconSize() { - if (IsExplorerTreeSupported) { + public virtual int GetOutlineIconSize() + { + if (IsExplorerTreeSupported) + { return outlineSizeExplorerTreeStyle; } - else { + else + { return outlineSize; } } - public virtual int GetGridEntryHeight() { + public virtual int GetGridEntryHeight() + { return RowHeight; } // for qa automation - internal int GetPropertyLocation(string propName, bool getXY, bool rowValue) { - if (allGridEntries != null && allGridEntries.Count > 0) { - for (int i = 0; i < allGridEntries.Count; i++) { - if (0 == string.Compare(propName, allGridEntries.GetEntry(i).PropertyLabel, true, CultureInfo.InvariantCulture)) { - if (getXY) { + internal int GetPropertyLocation(string propName, bool getXY, bool rowValue) + { + if (allGridEntries != null && allGridEntries.Count > 0) + { + for (int i = 0; i < allGridEntries.Count; i++) + { + if (0 == string.Compare(propName, allGridEntries.GetEntry(i).PropertyLabel, true, CultureInfo.InvariantCulture)) + { + if (getXY) + { int row = GetRowFromGridEntry(allGridEntries.GetEntry(i)); - if (row < 0 || row >= this.visibleRows) { + if (row < 0 || row >= this.visibleRows) + { return -1; } - else { + else + { Rectangle r = GetRectangle(row, rowValue ? ROWVALUE : ROWLABEL); - return(r.Y << 16 | (r.X & 0xFFFF)); + return (r.Y << 16 | (r.X & 0xFFFF)); } } - else { + else + { return i; } } @@ -1563,38 +1835,47 @@ internal int GetPropertyLocation(string propName, bool getXY, bool rowValue) { return -1; } - public new object GetService(Type classService) { - if (classService == typeof(IWindowsFormsEditorService)) { + public new object GetService(Type classService) + { + if (classService == typeof(IWindowsFormsEditorService)) + { return this; } - if (ServiceProvider != null) { + if (ServiceProvider != null) + { return serviceProvider.GetService(classService); } return null; } - public virtual int GetSplitterWidth() { + public virtual int GetSplitterWidth() + { return 1; } - public virtual int GetTotalWidth() { + public virtual int GetTotalWidth() + { return GetLabelWidth() + GetSplitterWidth() + GetValueWidth(); } - public virtual int GetValuePaintIndent() { + public virtual int GetValuePaintIndent() + { return paintIndent; } - public virtual int GetValuePaintWidth() { + public virtual int GetValuePaintWidth() + { return paintWidth; } - public virtual int GetValueStringIndent() { + public virtual int GetValueStringIndent() + { return EDIT_INDENT; } - public virtual int GetValueWidth() { - return(int)(InternalLabelWidth * (labelRatio - 1)); + public virtual int GetValueWidth() + { + return (int)(InternalLabelWidth * (labelRatio - 1)); } /// @@ -1605,32 +1886,36 @@ public virtual int GetValueWidth() { /// nicely. If the user performs an action that would cause the drop down /// to prematurely disappear the control will be hidden. /// - public void /* cpr IWindowsFormsEditorService. */ DropDownControl(Control ctl) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:DropDownControl"); - Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "DropDownControl(ctl = " + ctl.GetType().Name + ")"); - if (dropDownHolder == null) { + public void /* cpr IWindowsFormsEditorService. */ DropDownControl(Control ctl) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:DropDownControl"); + Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "DropDownControl(ctl = " + ctl.GetType().Name + ")"); + if (dropDownHolder == null) + { dropDownHolder = new DropDownHolder(this); } dropDownHolder.Visible = false; dropDownHolder.SetComponent(ctl, GetFlag(FlagResizableDropDown)); - Rectangle rect = GetRectangle(selectedRow,ROWVALUE); + Rectangle rect = GetRectangle(selectedRow, ROWVALUE); Size size = dropDownHolder.Size; Point loc = PointToScreen(new Point(0, 0)); Rectangle rectScreen = Screen.FromControl(Edit).WorkingArea; - size.Width = Math.Max(rect.Width+1,size.Width); + size.Width = Math.Max(rect.Width + 1, size.Width); // Not needed... CYMAXDDLHEIGHT used to be 200, but why limit it??? //size.Height = Math.Min(size.Height,CYMAXDDLHEIGHT); loc.X = Math.Min(rectScreen.X + rectScreen.Width - size.Width, - Math.Max(rectScreen.X,loc.X + rect.X + rect.Width - size.Width)); + Math.Max(rectScreen.X, loc.X + rect.X + rect.Width - size.Width)); loc.Y += rect.Y; - if (rectScreen.Y + rectScreen.Height < (size.Height + loc.Y + Edit.Height)) { + if (rectScreen.Y + rectScreen.Height < (size.Height + loc.Y + Edit.Height)) + { loc.Y -= size.Height; dropDownHolder.ResizeUp = true; } - else { + else + { loc.Y += rect.Height + 1; dropDownHolder.ResizeUp = false; } @@ -1646,43 +1931,53 @@ public virtual int GetValueWidth() { dropDownHolder.FocusComponent(); SelectEdit(false); - try { + try + { DropDownButton.IgnoreMouse = true; dropDownHolder.DoModalLoop(); - } - finally { + } + finally + { DropDownButton.IgnoreMouse = false; } - if (selectedRow != -1) { + if (selectedRow != -1) + { Focus(); SelectRow(selectedRow); } } - public virtual void DropDownDone() { + public virtual void DropDownDone() + { CloseDropDown(); } - public virtual void DropDownUpdate() { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "DropDownHolder:DropDownUpdate"); - if (dropDownHolder != null && dropDownHolder.GetUsed()) { + public virtual void DropDownUpdate() + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "DropDownHolder:DropDownUpdate"); + if (dropDownHolder != null && dropDownHolder.GetUsed()) + { int row = selectedRow; GridEntry gridEntry = GetGridEntryFromRow(row); Edit.Text = gridEntry.GetPropertyTextValue(); } } - - public bool EnsurePendingChangesCommitted() { + + public bool EnsurePendingChangesCommitted() + { this.CloseDropDown(); return this.Commit(); } - - private bool FilterEditWndProc(ref Message m) { + + private bool FilterEditWndProc(ref Message m) + { // if it's the TAB key, we keep it since we'll give them focus with it. - if (dropDownHolder != null && dropDownHolder.Visible && m.Msg == Interop.WindowMessages.WM_KEYDOWN && (int)m.WParam != (int)Keys.Tab) { + if (dropDownHolder != null && dropDownHolder.Visible && m.Msg == Interop.WindowMessages.WM_KEYDOWN && (int)m.WParam != (int)Keys.Tab) + { Control ctl = dropDownHolder.Component; - if (ctl != null) { + if (ctl != null) + { m.Result = ctl.SendMessage(m.Msg, m.WParam, m.LParam); return true; } @@ -1690,19 +1985,24 @@ private bool FilterEditWndProc(ref Message m) { return false; } - private bool FilterReadOnlyEditKeyPress(char keyChar) { + private bool FilterReadOnlyEditKeyPress(char keyChar) + { GridEntry gridEntry = GetGridEntryFromRow(selectedRow); - if (gridEntry.Enumerable && gridEntry.IsValueEditable) { + if (gridEntry.Enumerable && gridEntry.IsValueEditable) + { int index = GetCurrentValueIndex(gridEntry); object[] values = gridEntry.GetPropertyValueList(); - string letter = new string(new char[] {keyChar}); - for (int i = 0; i < values.Length; i++) { + string letter = new string(new char[] { keyChar }); + for (int i = 0; i < values.Length; i++) + { object valueCur = values[(i + index + 1) % values.Length]; string text = gridEntry.GetPropertyTextValue(valueCur); - if (text != null && text.Length > 0 && string.Compare(text.Substring(0,1), letter, true, CultureInfo.InvariantCulture) == 0) { + if (text != null && text.Length > 0 && string.Compare(text.Substring(0, 1), letter, true, CultureInfo.InvariantCulture) == 0) + { CommitValue(valueCur); - if (Edit.Focused) { + if (Edit.Focused) + { SelectEdit(false); } return true; @@ -1713,13 +2013,16 @@ private bool FilterReadOnlyEditKeyPress(char keyChar) { return false; } - public virtual bool WillFilterKeyPress(char charPressed) { - if (!Edit.Visible) { + public virtual bool WillFilterKeyPress(char charPressed) + { + if (!Edit.Visible) + { return false; } Keys modifiers = ModifierKeys; - if ((int)(modifiers & ~Keys.Shift) != 0) { + if ((int)(modifiers & ~Keys.Shift) != 0) + { return false; } @@ -1728,13 +2031,15 @@ public virtual bool WillFilterKeyPress(char charPressed) { // for the tree. // - if (selectedGridEntry != null) { - switch (charPressed) { + if (selectedGridEntry != null) + { + switch (charPressed) + { case '+': case '-': case '*': return !selectedGridEntry.Expandable; - case unchecked( (char)(int)(long)Keys.Tab): + case unchecked((char)(int)(long)Keys.Tab): return false; } } @@ -1742,23 +2047,26 @@ public virtual bool WillFilterKeyPress(char charPressed) { return true; } - public void FilterKeyPress(char keyChar) { + public void FilterKeyPress(char keyChar) + { GridEntry gridEntry = GetGridEntryFromRow(selectedRow); if (gridEntry == null) return; - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:FilterKeyPress()"); + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:FilterKeyPress()"); Edit.FilterKeyPress(keyChar); } - private /*protected virtual*/ GridEntry FindEquivalentGridEntry(GridEntryCollection ipeHier) { + private /*protected virtual*/ GridEntry FindEquivalentGridEntry(GridEntryCollection ipeHier) + { if (ipeHier == null || ipeHier.Count == 0) return null; GridEntryCollection rgipes = GetAllGridEntries(); - if (rgipes == null || rgipes.Count == 0) { + if (rgipes == null || rgipes.Count == 0) + { return null; } @@ -1766,23 +2074,27 @@ public void FilterKeyPress(char keyChar) { int row = 0; int count = rgipes.Count; - for (int i = 0; i < ipeHier.Count; i++) { + for (int i = 0; i < ipeHier.Count; i++) + { - if (ipeHier[i] == null) { + if (ipeHier[i] == null) + { continue; } // if we've got one above, and it's expandable, // expand it - if (targetEntry != null) { + if (targetEntry != null) + { // how many do we have? int items = rgipes.Count; // expand and get the new count - if (!targetEntry.InternalExpanded) { - SetExpand(targetEntry, true); - rgipes = GetAllGridEntries(); + if (!targetEntry.InternalExpanded) + { + SetExpand(targetEntry, true); + rgipes = GetAllGridEntries(); } count = targetEntry.VisibleChildCount; } @@ -1791,8 +2103,10 @@ public void FilterKeyPress(char keyChar) { targetEntry = null; // now, we will only go as many as were expanded... - for (; row < rgipes.Count && ((row - start) <= count); row++) { - if (ipeHier.GetEntry(i).NonParentEquals(rgipes[row])) { + for (; row < rgipes.Count && ((row - start) <= count); row++) + { + if (ipeHier.GetEntry(i).NonParentEquals(rgipes[row])) + { targetEntry = rgipes.GetEntry(row); row++; break; @@ -1800,7 +2114,8 @@ public void FilterKeyPress(char keyChar) { } // didn't find it... - if (targetEntry == null) { + if (targetEntry == null) + { break; } } @@ -1808,37 +2123,44 @@ public void FilterKeyPress(char keyChar) { return targetEntry; } - protected virtual Point FindPosition(int x, int y) { + protected virtual Point FindPosition(int x, int y) + { if (RowHeight == -1) return InvalidPosition; Size size = this.GetOurSize(); if (x < 0 || x > size.Width + ptOurLocation.X) return InvalidPosition; - Point pt = new Point(ROWLABEL,0); + Point pt = new Point(ROWLABEL, 0); if (x > InternalLabelWidth + ptOurLocation.X) pt.X = ROWVALUE; - pt.Y = (y-ptOurLocation.Y)/(1+RowHeight); + pt.Y = (y - ptOurLocation.Y) / (1 + RowHeight); return pt; } - public virtual void Flush() { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView::Flush()"); - if (Commit() && Edit.Focused) { + public virtual void Flush() + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView::Flush()"); + if (Commit() && Edit.Focused) + { this.Focus(); } } - private GridEntryCollection GetAllGridEntries() { + private GridEntryCollection GetAllGridEntries() + { return GetAllGridEntries(false); } - private GridEntryCollection GetAllGridEntries(bool fUpdateCache) { - if (visibleRows == -1 || totalProps == -1 || !HasEntries) { + private GridEntryCollection GetAllGridEntries(bool fUpdateCache) + { + if (visibleRows == -1 || totalProps == -1 || !HasEntries) + { return null; } - if (allGridEntries != null && !fUpdateCache) { + if (allGridEntries != null && !fUpdateCache) + { return allGridEntries; } @@ -1857,76 +2179,94 @@ private GridEntryCollection GetAllGridEntries(bool fUpdateCache) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] - private int GetCurrentValueIndex(GridEntry gridEntry) { + private int GetCurrentValueIndex(GridEntry gridEntry) + { - if (!gridEntry.Enumerable) { + if (!gridEntry.Enumerable) + { return -1; } - try { + try + { object[] values = gridEntry.GetPropertyValueList(); object value = gridEntry.PropertyValue; string textValue = gridEntry.TypeConverter.ConvertToString(gridEntry, value); - if (values != null && values.Length > 0) { + if (values != null && values.Length > 0) + { string itemTextValue; int stringMatch = -1; int equalsMatch = -1; - for (int i = 0; i < values.Length; i++) { + for (int i = 0; i < values.Length; i++) + { object curValue = values[i]; // check real values against string values. itemTextValue = gridEntry.TypeConverter.ConvertToString(curValue); - if (value == curValue || 0 == string.Compare(textValue, itemTextValue, true, CultureInfo.InvariantCulture)) { + if (value == curValue || 0 == string.Compare(textValue, itemTextValue, true, CultureInfo.InvariantCulture)) + { stringMatch = i; } // now try .equals if they are both non-null - if (value != null && curValue != null && curValue.Equals(value)) { + if (value != null && curValue != null && curValue.Equals(value)) + { equalsMatch = i; } - if (stringMatch == equalsMatch && stringMatch != -1) { + if (stringMatch == equalsMatch && stringMatch != -1) + { return stringMatch; } } - if (stringMatch != -1) { + if (stringMatch != -1) + { return stringMatch; } - if (equalsMatch != -1) { + if (equalsMatch != -1) + { return equalsMatch; } } } - catch (Exception e) { + catch (Exception e) + { Debug.Fail(e.ToString()); } return -1; } - public virtual int GetDefaultOutlineIndent() { + public virtual int GetDefaultOutlineIndent() + { return OUTLINE_INDENT; } - private IHelpService GetHelpService() { - if (helpService == null && ServiceProvider != null) { + private IHelpService GetHelpService() + { + if (helpService == null && ServiceProvider != null) + { topHelpService = (IHelpService)ServiceProvider.GetService(typeof(IHelpService)); - if (topHelpService != null) { - IHelpService localHelpService = topHelpService.CreateLocalContext(HelpContextType.ToolWindowSelection); - if (localHelpService != null) { + if (topHelpService != null) + { + IHelpService localHelpService = topHelpService.CreateLocalContext(HelpContextType.ToolWindowSelection); + if (localHelpService != null) + { helpService = localHelpService; - } + } } } return helpService; } - public virtual int GetScrollOffset() { + public virtual int GetScrollOffset() + { //Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:GetScrollOffset"); - if (scrollBar == null) { + if (scrollBar == null) + { return 0; } int pos = ScrollBar.Value; @@ -1937,32 +2277,39 @@ public virtual int GetScrollOffset() { /// returns an array of IPE specifying the current heirarchy of ipes from the given /// gridEntry through its parents to the root. /// - private GridEntryCollection GetGridEntryHierarchy(GridEntry gridEntry) { - if (gridEntry == null) { + private GridEntryCollection GetGridEntryHierarchy(GridEntry gridEntry) + { + if (gridEntry == null) + { return null; } int depth = gridEntry.PropertyDepth; - if (depth > 0) { + if (depth > 0) + { GridEntry[] entries = new GridEntry[depth + 1]; - while (gridEntry != null && depth >= 0) { + while (gridEntry != null && depth >= 0) + { entries[depth] = gridEntry; gridEntry = gridEntry.ParentGridEntry; depth = gridEntry.PropertyDepth; } return new GridEntryCollection(null, entries); } - return new GridEntryCollection(null, new GridEntry[]{gridEntry}); + return new GridEntryCollection(null, new GridEntry[] { gridEntry }); } - private /*protected virtual*/ GridEntry GetGridEntryFromRow(int row) { + private /*protected virtual*/ GridEntry GetGridEntryFromRow(int row) + { return GetGridEntryFromOffset(row + GetScrollOffset()); } - private /*protected virtual*/ GridEntry GetGridEntryFromOffset(int offset) { + private /*protected virtual*/ GridEntry GetGridEntryFromOffset(int offset) + { GridEntryCollection rgipesAll = GetAllGridEntries(); - if (rgipesAll != null) { + if (rgipesAll != null) + { if (offset >= 0 && offset < rgipesAll.Count) return rgipesAll.GetEntry(offset); } @@ -1970,14 +2317,16 @@ private GridEntryCollection GetGridEntryHierarchy(GridEntry gridEntry) { } private /*protected virtual*/ int GetGridEntriesFromOutline(GridEntryCollection rgipe, int cCur, - int cTarget, GridEntry[] rgipeTarget) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:GetGridEntriesFromOutline"); + int cTarget, GridEntry[] rgipeTarget) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:GetGridEntriesFromOutline"); if (rgipe == null || rgipe.Count == 0) return cCur; cCur--; // want to account for each entry as we find it. - for (int cLocal = 0; cLocal < rgipe.Count; cLocal++) { + for (int cLocal = 0; cLocal < rgipe.Count; cLocal++) + { cCur++; if (cCur >= cTarget + rgipeTarget.Length) break; @@ -1990,12 +2339,14 @@ private GridEntryCollection GetGridEntryHierarchy(GridEntry gridEntry) { if (cCur >= cTarget) rgipeTarget[cCur - cTarget] = ipeCur; - if (ipeCur.InternalExpanded) { + if (ipeCur.InternalExpanded) + { GridEntryCollection subGridEntry = ipeCur.Children; //Debug.Assert(subGridEntry != null && subGridEntry.Length > 0 && subGridEntry[0] != null, "Expanded property " + ipeCur.PropertyLabel + " has no children!"); - if (subGridEntry != null && subGridEntry.Count > 0) { + if (subGridEntry != null && subGridEntry.Count > 0) + { cCur = GetGridEntriesFromOutline(subGridEntry, - cCur+1,cTarget,rgipeTarget); + cCur + 1, cTarget, rgipeTarget); } } } @@ -2003,85 +2354,101 @@ private GridEntryCollection GetGridEntryHierarchy(GridEntry gridEntry) { return cCur; } - private Size GetOurSize() { - Size size = ClientSize; - if (size.Width == 0) { - Size sizeWindow = Size; - if (sizeWindow.Width > 10) { - Debug.Fail("We have a bad client width!"); - size.Width = sizeWindow.Width; - size.Height = sizeWindow.Height; - } - } - if (!GetScrollbarHidden()) { - Size sizeScroll = ScrollBar.Size; - size.Width -= sizeScroll.Width; + private Size GetOurSize() + { + Size size = ClientSize; + if (size.Width == 0) + { + Size sizeWindow = Size; + if (sizeWindow.Width > 10) + { + Debug.Fail("We have a bad client width!"); + size.Width = sizeWindow.Width; + size.Height = sizeWindow.Height; } - size.Width -= 2; - size.Height -= 2; - return size; + } + if (!GetScrollbarHidden()) + { + Size sizeScroll = ScrollBar.Size; + size.Width -= sizeScroll.Width; + } + size.Width -= 2; + size.Height -= 2; + return size; } - public Rectangle GetRectangle(int row, int flRow) { - Rectangle rect = new Rectangle(0,0,0,0); + public Rectangle GetRectangle(int row, int flRow) + { + Rectangle rect = new Rectangle(0, 0, 0, 0); Size size = this.GetOurSize(); - + rect.X = ptOurLocation.X; bool fLabel = ((flRow & ROWLABEL) != 0); bool fValue = ((flRow & ROWVALUE) != 0); - if (fLabel && fValue) { + if (fLabel && fValue) + { rect.X = 1; rect.Width = size.Width - 1; } - else if (fLabel) { + else if (fLabel) + { rect.X = 1; rect.Width = InternalLabelWidth - 1; } - else if (fValue) { + else if (fValue) + { rect.X = ptOurLocation.X + InternalLabelWidth; rect.Width = size.Width - InternalLabelWidth; } - rect.Y = (row)*(RowHeight+1)+1+ptOurLocation.Y; + rect.Y = (row) * (RowHeight + 1) + 1 + ptOurLocation.Y; rect.Height = RowHeight; return rect; } - private /*protected virtual*/ int GetRowFromGridEntry(GridEntry gridEntry) { + private /*protected virtual*/ int GetRowFromGridEntry(GridEntry gridEntry) + { GridEntryCollection rgipesAll = GetAllGridEntries(); if (gridEntry == null || rgipesAll == null) return -1; int bestMatch = -1; - for (int i = 0; i < rgipesAll.Count; i++) { + for (int i = 0; i < rgipesAll.Count; i++) + { // try for an exact match. semantics of equals are a bit loose here... // - if (gridEntry == rgipesAll[i]) { + if (gridEntry == rgipesAll[i]) + { return i - GetScrollOffset(); } - else if (bestMatch == -1 && gridEntry.Equals(rgipesAll[i])) { + else if (bestMatch == -1 && gridEntry.Equals(rgipesAll[i])) + { bestMatch = i - GetScrollOffset(); } } - if (bestMatch != -1) { + if (bestMatch != -1) + { return bestMatch; } return -1 - GetScrollOffset(); } - public virtual bool GetInPropertySet() { + public virtual bool GetInPropertySet() + { return GetFlag(FlagInPropertySet); } - protected virtual bool GetScrollbarHidden() { - if (scrollBar == null) { + protected virtual bool GetScrollbarHidden() + { + if (scrollBar == null) + { return true; } return !ScrollBar.Visible; @@ -2092,7 +2459,8 @@ protected virtual bool GetScrollbarHidden() { /// entry collection (ie. nested entries are not accessible). Or specify -1 to get info for the current /// selected entry (which can be any entry, top-level or nested). /// - public virtual string GetTestingInfo(int entry) { + public virtual string GetTestingInfo(int entry) + { GridEntry gridEntry = (entry < 0) ? GetGridEntryFromRow(selectedRow) : GetGridEntryFromOffset(entry); if (gridEntry == null) @@ -2101,15 +2469,18 @@ public virtual string GetTestingInfo(int entry) { return gridEntry.GetTestingInfo(); } - public Color GetTextColor() { + public Color GetTextColor() + { return this.ForeColor; } - private void LayoutWindow(bool invalidate) { + private void LayoutWindow(bool invalidate) + { Rectangle rect = ClientRectangle; - Size sizeWindow = new Size(rect.Width,rect.Height); + Size sizeWindow = new Size(rect.Width, rect.Height); - if (scrollBar != null) { + if (scrollBar != null) + { Rectangle boundsScroll = ScrollBar.Bounds; boundsScroll.X = sizeWindow.Width - boundsScroll.Width - 1; boundsScroll.Y = 1; @@ -2117,77 +2488,93 @@ private void LayoutWindow(bool invalidate) { ScrollBar.Bounds = boundsScroll; } - if (invalidate) { + if (invalidate) + { Invalidate(); } } - internal void InvalidateGridEntryValue(GridEntry ge) { + internal void InvalidateGridEntryValue(GridEntry ge) + { int row = GetRowFromGridEntry(ge); - if (row != -1) { + if (row != -1) + { InvalidateRows(row, row, ROWVALUE); } } - private void InvalidateRow(int row) { + private void InvalidateRow(int row) + { InvalidateRows(row, row, ROWVALUE | ROWLABEL); } - - private void InvalidateRows(int startRow, int endRow) { + + private void InvalidateRows(int startRow, int endRow) + { InvalidateRows(startRow, endRow, ROWVALUE | ROWLABEL); } - private void InvalidateRows(int startRow, int endRow, int type) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:InvalidateRows"); + private void InvalidateRows(int startRow, int endRow, int type) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:InvalidateRows"); - Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Invalidating rows " + startRow.ToString(CultureInfo.InvariantCulture) + " through " + endRow.ToString(CultureInfo.InvariantCulture)); + Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Invalidating rows " + startRow.ToString(CultureInfo.InvariantCulture) + " through " + endRow.ToString(CultureInfo.InvariantCulture)); Rectangle rect; // invalidate from the start row down - if (endRow == -1) { + if (endRow == -1) + { rect = GetRectangle(startRow, type); rect.Height = (Size.Height - rect.Y) - 1; Invalidate(rect); } - else { - for (int i = startRow; i <= endRow; i++) { + else + { + for (int i = startRow; i <= endRow; i++) + { rect = GetRectangle(i, type); Invalidate(rect); } } } - + /// /// Overridden to handle TAB key. /// - protected override bool IsInputKey(Keys keyData) { - switch (keyData & Keys.KeyCode) { + protected override bool IsInputKey(Keys keyData) + { + switch (keyData & Keys.KeyCode) + { case Keys.Escape: case Keys.Tab: case Keys.F4: return false; case Keys.Return: - if (Edit.Focused) { + if (Edit.Focused) + { return false; - } - break; + } + break; } return base.IsInputKey(keyData); } - private bool IsMyChild(Control c) { + private bool IsMyChild(Control c) + { - if (c == this || c == null) { + if (c == this || c == null) + { return false; } Control cParent = c.ParentInternal; - while (cParent != null) { - if (cParent == this) { + while (cParent != null) + { + if (cParent == this) + { return true; } cParent = cParent.ParentInternal; @@ -2195,7 +2582,8 @@ private bool IsMyChild(Control c) { return false; } - private bool IsScrollValueValid(int newValue) { + private bool IsScrollValueValid(int newValue) + { /*Debug.WriteLine("se.newValue = " + se.newValue.ToString()); Debug.WriteLine("ScrollBar.Value = " + ScrollBar.Value.ToString()); Debug.WriteLine("visibleRows = " + visibleRows.ToString()); @@ -2207,20 +2595,24 @@ private bool IsScrollValueValid(int newValue) { if (newValue == ScrollBar.Value || newValue < 0 || newValue > ScrollBar.Maximum || - (newValue + (ScrollBar.LargeChange-1) >= totalProps)) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView: move not needed, returning"); + (newValue + (ScrollBar.LargeChange - 1) >= totalProps)) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView: move not needed, returning"); return false; } return true; } - internal bool IsSiblingControl(Control c1, Control c2) { + internal bool IsSiblingControl(Control c1, Control c2) + { Control parent1 = c1.ParentInternal; Control parent2 = c2.ParentInternal; - while (parent2 != null) { - if (parent1 == parent2) { + while (parent2 != null) + { + if (parent1 == parent2) + { return true; } parent2 = parent2.ParentInternal; @@ -2228,31 +2620,35 @@ internal bool IsSiblingControl(Control c1, Control c2) { return false; } - private void MoveSplitterTo(int xpos) { + private void MoveSplitterTo(int xpos) + { int widthPS = GetOurSize().Width; int startPS = ptOurLocation.X; - int pos = Math.Max(Math.Min(xpos,widthPS-10),GetOutlineIconSize() * 2); + int pos = Math.Max(Math.Min(xpos, widthPS - 10), GetOutlineIconSize() * 2); int oldLabelWidth = InternalLabelWidth; - labelRatio = ((double)widthPS / (double) (pos - startPS)); + labelRatio = ((double)widthPS / (double)(pos - startPS)); SetConstants(); - if (selectedRow != -1) { + if (selectedRow != -1) + { // do this to move any editor we have SelectRow(selectedRow); } - + Rectangle r = ClientRectangle; - + // if we're moving to the left, just invalidate the values - if (oldLabelWidth > InternalLabelWidth) { + if (oldLabelWidth > InternalLabelWidth) + { int left = InternalLabelWidth - requiredLabelPaintMargin; Invalidate(new Rectangle(left, 0, Size.Width - left, Size.Height)); } - else { + else + { // to the right, just invalidate from where the splitter was // to the right r.X = oldLabelWidth - requiredLabelPaintMargin; @@ -2261,90 +2657,111 @@ private void MoveSplitterTo(int xpos) { } } - private void OnBtnClick(object sender, EventArgs e) { + private void OnBtnClick(object sender, EventArgs e) + { - if (GetFlag(FlagBtnLaunchedEditor)) { + if (GetFlag(FlagBtnLaunchedEditor)) + { return; } - if (sender == DialogButton && !Commit()) { + if (sender == DialogButton && !Commit()) + { return; } SetCommitError(ERROR_NONE); - try { + try + { Commit(); SetFlag(FlagBtnLaunchedEditor, true); PopupDialog(selectedRow); } - finally { + finally + { SetFlag(FlagBtnLaunchedEditor, false); } } - private void OnBtnKeyDown(object sender, KeyEventArgs ke) { - OnKeyDown(sender,ke); + private void OnBtnKeyDown(object sender, KeyEventArgs ke) + { + OnKeyDown(sender, ke); } - private void OnChildLostFocus(object sender, EventArgs e) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnChildLostFocus"); + private void OnChildLostFocus(object sender, EventArgs e) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnChildLostFocus"); this.InvokeLostFocus(this, e); } - private void OnDropDownButtonGotFocus(object sender, EventArgs e) { + private void OnDropDownButtonGotFocus(object sender, EventArgs e) + { DropDownButton dropDownButton = sender as DropDownButton; - if (dropDownButton != null) { + if (dropDownButton != null) + { dropDownButton.AccessibilityObject.SetFocus(); } } - protected override void OnGotFocus(EventArgs e) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnGotFocus"); - + protected override void OnGotFocus(EventArgs e) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnGotFocus"); + base.OnGotFocus(e); - - if (e != null && !GetInPropertySet()) { - if (!Commit()) { + + if (e != null && !GetInPropertySet()) + { + if (!Commit()) + { Edit.Focus(); return; } } - if (selectedGridEntry != null && GetRowFromGridEntry(selectedGridEntry) != -1) { + if (selectedGridEntry != null && GetRowFromGridEntry(selectedGridEntry) != -1) + { selectedGridEntry.Focus = true; SelectGridEntry(selectedGridEntry, false); } - else { + else + { SelectRow(0); } - if (selectedGridEntry != null && selectedGridEntry.GetValueOwner() != null) { + if (selectedGridEntry != null && selectedGridEntry.GetValueOwner() != null) + { UpdateHelpAttributes(null, selectedGridEntry); } // For empty GridView, draw a focus-indicator rectangle, just inside GridView borders - if (totalProps <= 0) { + if (totalProps <= 0) + { int doubleOffset = 2 * offset_2Units; - if ((Size.Width > doubleOffset) && (Size.Height > doubleOffset)) { - using (Graphics g = CreateGraphicsInternal()) { + if ((Size.Width > doubleOffset) && (Size.Height > doubleOffset)) + { + using (Graphics g = CreateGraphicsInternal()) + { ControlPaint.DrawFocusRectangle(g, new Rectangle(offset_2Units, offset_2Units, Size.Width - doubleOffset, Size.Height - doubleOffset)); } } } } - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { base.OnHandleCreated(e); SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(this.OnSysColorChange); } - protected override void OnHandleDestroyed(EventArgs e) { + protected override void OnHandleDestroyed(EventArgs e) + { SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(this.OnSysColorChange); // We can leak this if we aren't disposed. // - if (toolTip != null && !RecreatingHandle) { + if (toolTip != null && !RecreatingHandle) + { toolTip.Dispose(); toolTip = null; } @@ -2387,9 +2804,11 @@ protected override void OnImeModeChanged(EventArgs e) { } */ - private void OnListChange(object sender, EventArgs e) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnListChange"); - if (!DropDownListBox.InSetSelectedIndex()) { + private void OnListChange(object sender, EventArgs e) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnListChange"); + if (!DropDownListBox.InSetSelectedIndex()) + { GridEntry gridEntry = GetGridEntryFromRow(selectedRow); Edit.Text = gridEntry.GetPropertyTextValue(DropDownListBox.SelectedItem); Edit.Focus(); @@ -2398,96 +2817,115 @@ private void OnListChange(object sender, EventArgs e) { SetFlag(FlagDropDownCommit, true); } - private void OnListMouseUp(object sender, MouseEventArgs me) { + private void OnListMouseUp(object sender, MouseEventArgs me) + { OnListClick(sender, me); } - private void OnListClick(object sender, EventArgs e) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnListClick"); + private void OnListClick(object sender, EventArgs e) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnListClick"); GridEntry gridEntry = GetGridEntryFromRow(selectedRow); - - if (DropDownListBox.Items.Count == 0) { - CommonEditorHide(); - SetCommitError(ERROR_NONE); - SelectRow(selectedRow); - return; - } - else { + + if (DropDownListBox.Items.Count == 0) + { + CommonEditorHide(); + SetCommitError(ERROR_NONE); + SelectRow(selectedRow); + return; + } + else + { object value = DropDownListBox.SelectedItem; // don't need the commit becuase we're committing anyway. // SetFlag(FlagDropDownCommit, false); - if (value != null && !CommitText((string)value)) { + if (value != null && !CommitText((string)value)) + { SetCommitError(ERROR_NONE); SelectRow(selectedRow); } } } - - private void OnListDrawItem(object sender, DrawItemEventArgs die) { + + private void OnListDrawItem(object sender, DrawItemEventArgs die) + { int index = die.Index; - if (index < 0 || selectedGridEntry == null) { + if (index < 0 || selectedGridEntry == null) + { return; } string text = (string)DropDownListBox.Items[die.Index]; - Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Drawing list item, value='" + text + "'"); + Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Drawing list item, value='" + text + "'"); die.DrawBackground(); die.DrawFocusRectangle(); Rectangle drawBounds = die.Bounds; drawBounds.Y += 1; drawBounds.X -= 1; - + GridEntry gridEntry = GetGridEntryFromRow(selectedRow); - try { + try + { DrawValue(die.Graphics, drawBounds, drawBounds, gridEntry, gridEntry.ConvertTextToValue(text), (int)(die.State & DrawItemState.Selected) != 0, false, false, false); } - catch (FormatException ex) { + catch (FormatException ex) + { ShowFormatExceptionMessage(gridEntry.PropertyLabel, text, ex); if (DropDownListBox.IsHandleCreated) DropDownListBox.Visible = false; } } - private void OnListKeyDown(object sender, KeyEventArgs ke) { - if (ke.KeyCode == Keys.Return) { + private void OnListKeyDown(object sender, KeyEventArgs ke) + { + if (ke.KeyCode == Keys.Return) + { OnListClick(null, null); - if (selectedGridEntry != null) { + if (selectedGridEntry != null) + { selectedGridEntry.OnValueReturnKey(); } } - OnKeyDown(sender,ke); + OnKeyDown(sender, ke); } - protected override void OnLostFocus(EventArgs e) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnLostFocus"); - Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "PropertyGridView lost focus"); - - if (e != null) { + protected override void OnLostFocus(EventArgs e) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnLostFocus"); + Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "PropertyGridView lost focus"); + + if (e != null) + { base.OnLostFocus(e); } - if (this.FocusInside) { + if (this.FocusInside) + { base.OnLostFocus(e); return; } GridEntry gridEntry = GetGridEntryFromRow(selectedRow); - if (gridEntry != null) { - Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "removing gridEntry focus"); - gridEntry.Focus = false;; + if (gridEntry != null) + { + Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "removing gridEntry focus"); + gridEntry.Focus = false; + ; CommonEditorHide(); InvalidateRow(selectedRow); } base.OnLostFocus(e); // For empty GridView, clear the focus indicator that was painted in OnGotFocus() - if (totalProps <= 0) { - using (Graphics g = CreateGraphicsInternal()) { + if (totalProps <= 0) + { + using (Graphics g = CreateGraphicsInternal()) + { Rectangle clearRect = new Rectangle(1, 1, Size.Width - 2, Size.Height - 2); Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Filling empty gridview rect=" + clearRect.ToString()); @@ -2496,52 +2934,61 @@ protected override void OnLostFocus(EventArgs e) { } } - private void OnEditChange(object sender, EventArgs e) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnEditChange"); + private void OnEditChange(object sender, EventArgs e) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnEditChange"); SetCommitError(ERROR_NONE, Edit.Focused); - + ToolTip.ToolTip = string.Empty; ToolTip.Visible = false; - - if (!Edit.InSetText()) { + + if (!Edit.InSetText()) + { GridEntry gridEntry = GetGridEntryFromRow(selectedRow); if (gridEntry != null && (gridEntry.Flags & GridEntry.FLAG_IMMEDIATELY_EDITABLE) != 0) Commit(); } } - private void OnEditGotFocus(object sender, EventArgs e) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnEditGotFocus"); + private void OnEditGotFocus(object sender, EventArgs e) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnEditGotFocus"); - if (!Edit.Visible) { + if (!Edit.Visible) + { this.Focus(); return; } - switch (errorState) { + switch (errorState) + { case ERROR_MSGBOX_UP: return; case ERROR_THROWN: - if (Edit.Visible) { + if (Edit.Visible) + { Edit.HookMouseDown = true; } break; default: - if (this.NeedsCommit) { + if (this.NeedsCommit) + { SetCommitError(ERROR_NONE, true); } break; } - if (selectedGridEntry != null && GetRowFromGridEntry(selectedGridEntry) != -1) { - Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "adding gridEntry focus"); + if (selectedGridEntry != null && GetRowFromGridEntry(selectedGridEntry) != -1) + { + Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "adding gridEntry focus"); selectedGridEntry.Focus = true; InvalidateRow(selectedRow); (Edit.AccessibilityObject as ControlAccessibleObject).NotifyClients(AccessibleEvents.Focus); Edit.AccessibilityObject.SetFocus(); } - else { + else + { SelectRow(0); } } @@ -2559,29 +3006,39 @@ private void OnEditImeModeChanged(object sender, EventArgs e) { } */ - private bool ProcessEnumUpAndDown(GridEntry gridEntry, Keys keyCode, bool closeDropDown = true) { + private bool ProcessEnumUpAndDown(GridEntry gridEntry, Keys keyCode, bool closeDropDown = true) + { object value = gridEntry.PropertyValue; object[] rgvalues = gridEntry.GetPropertyValueList(); - if (rgvalues != null) { - for (int i = 0; i < rgvalues.Length; i++) { + if (rgvalues != null) + { + for (int i = 0; i < rgvalues.Length; i++) + { object rgvalue = rgvalues[i]; - if (value != null && rgvalue != null && value.GetType() != rgvalue.GetType() && gridEntry.TypeConverter.CanConvertTo(gridEntry, value.GetType())) { + if (value != null && rgvalue != null && value.GetType() != rgvalue.GetType() && gridEntry.TypeConverter.CanConvertTo(gridEntry, value.GetType())) + { rgvalue = gridEntry.TypeConverter.ConvertTo(gridEntry, CultureInfo.CurrentCulture, rgvalue, value.GetType()); } bool equal = (value == rgvalue) || (value != null && value.Equals(rgvalue)); - if (!equal && value is string && rgvalue != null) { + if (!equal && value is string && rgvalue != null) + { equal = 0 == string.Compare((string)value, rgvalue.ToString(), true, CultureInfo.CurrentCulture); } - if (equal) { + if (equal) + { object valueNew = null; - if (keyCode == Keys.Up) { - if (i == 0) return true; + if (keyCode == Keys.Up) + { + if (i == 0) + return true; valueNew = rgvalues[i - 1]; } - else { - if (i == rgvalues.Length - 1) return true; + else + { + if (i == rgvalues.Length - 1) + return true; valueNew = rgvalues[i + 1]; } @@ -2595,70 +3052,84 @@ private bool ProcessEnumUpAndDown(GridEntry gridEntry, Keys keyCode, bool closeD return false; } - private void OnEditKeyDown(object sender, KeyEventArgs ke) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnEditKeyDown"); + private void OnEditKeyDown(object sender, KeyEventArgs ke) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnEditKeyDown"); bool fAlt = ke.Alt; - if (!fAlt && (ke.KeyCode == Keys.Up || ke.KeyCode == Keys.Down)) { + if (!fAlt && (ke.KeyCode == Keys.Up || ke.KeyCode == Keys.Down)) + { GridEntry gridEntry = GetGridEntryFromRow(selectedRow); - if (!gridEntry.Enumerable || !gridEntry.IsValueEditable) { + if (!gridEntry.Enumerable || !gridEntry.IsValueEditable) + { return; } ke.Handled = true; bool processed = ProcessEnumUpAndDown(gridEntry, ke.KeyCode); - if (processed) { + if (processed) + { return; } } // Handle non-expand/collapse case of left & right as up & down else if ((ke.KeyCode == Keys.Left || ke.KeyCode == Keys.Right) && - (ke.Modifiers & ~Keys.Shift) != 0) { + (ke.Modifiers & ~Keys.Shift) != 0) + { return; } - OnKeyDown(sender,ke); + OnKeyDown(sender, ke); } - private void OnEditKeyPress(object sender, KeyPressEventArgs ke) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnEditKeyPress"); + private void OnEditKeyPress(object sender, KeyPressEventArgs ke) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnEditKeyPress"); GridEntry gridEntry = GetGridEntryFromRow(selectedRow); if (gridEntry == null) return; - if (!gridEntry.IsTextEditable) { + if (!gridEntry.IsTextEditable) + { ke.Handled = FilterReadOnlyEditKeyPress(ke.KeyChar); } } - private void OnEditLostFocus(object sender, EventArgs e) { + private void OnEditLostFocus(object sender, EventArgs e) + { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnEditLostFocus"); + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnEditLostFocus"); // believe it or not, this can actually happen. - if (Edit.Focused || (errorState == ERROR_MSGBOX_UP) || (errorState == ERROR_THROWN)|| GetInPropertySet()) { + if (Edit.Focused || (errorState == ERROR_MSGBOX_UP) || (errorState == ERROR_THROWN) || GetInPropertySet()) + { return; } // check to see if the focus is on the drop down or one of it's children // if so, return; - if (dropDownHolder != null && dropDownHolder.Visible) { + if (dropDownHolder != null && dropDownHolder.Visible) + { bool found = false; for (IntPtr hwnd = UnsafeNativeMethods.GetForegroundWindow(); - hwnd != IntPtr.Zero; hwnd = UnsafeNativeMethods.GetParent(new HandleRef(null, hwnd))) { - if (hwnd == dropDownHolder.Handle) { + hwnd != IntPtr.Zero; hwnd = UnsafeNativeMethods.GetParent(new HandleRef(null, hwnd))) + { + if (hwnd == dropDownHolder.Handle) + { found = true; } } if (found) return; } - - if (this.FocusInside) { - return; + + if (this.FocusInside) + { + return; } - + // if the focus isn't goint to a child of the view - if (!Commit()) { + if (!Commit()) + { Edit.Focus(); return; } @@ -2666,47 +3137,55 @@ private void OnEditLostFocus(object sender, EventArgs e) { this.InvokeLostFocus(this, EventArgs.Empty); } - private void OnEditMouseDown(object sender, MouseEventArgs me) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnEditMouseDown"); - - if (!FocusInside) { - SelectGridEntry(selectedGridEntry, false); + private void OnEditMouseDown(object sender, MouseEventArgs me) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnEditMouseDown"); + + if (!FocusInside) + { + SelectGridEntry(selectedGridEntry, false); } - - if (me.Clicks % 2 == 0) { - DoubleClickRow(selectedRow,false, ROWVALUE); + + if (me.Clicks % 2 == 0) + { + DoubleClickRow(selectedRow, false, ROWVALUE); Edit.SelectAll(); } - - if (rowSelectTime == 0) { + + if (rowSelectTime == 0) + { return; } - + // check if the click happened within the double click time since the row was selected. // this allows the edits to be selected with two clicks instead of 3 (select row, double click). // long timeStamp = DateTime.Now.Ticks; int delta = (int)((timeStamp - rowSelectTime) / 10000); // make it milleseconds - - if (delta < SystemInformation.DoubleClickTime) { + + if (delta < SystemInformation.DoubleClickTime) + { Point screenPoint = Edit.PointToScreen(new Point(me.X, me.Y)); if (Math.Abs(screenPoint.X - rowSelectPos.X) < SystemInformation.DoubleClickSize.Width && - Math.Abs(screenPoint.Y - rowSelectPos.Y) < SystemInformation.DoubleClickSize.Height) { - DoubleClickRow(selectedRow,false, ROWVALUE); + Math.Abs(screenPoint.Y - rowSelectPos.Y) < SystemInformation.DoubleClickSize.Height) + { + DoubleClickRow(selectedRow, false, ROWVALUE); Edit.SendMessage(Interop.WindowMessages.WM_LBUTTONUP, 0, (int)(me.Y << 16 | (me.X & 0xFFFF))); - Edit.SelectAll(); + Edit.SelectAll(); } rowSelectPos = Point.Empty; - + rowSelectTime = 0; } } - - private bool OnF4(Control sender) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnF4"); - if (ModifierKeys != 0) { + + private bool OnF4(Control sender) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnF4"); + if (ModifierKeys != 0) + { return false; } if (sender == this || sender == this.ownerGrid) @@ -2716,47 +3195,58 @@ private bool OnF4(Control sender) { return true; } - private bool OnEscape(Control sender) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnEscape"); - if ((ModifierKeys & (Keys.Alt | Keys.Control)) != 0) { + private bool OnEscape(Control sender) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnEscape"); + if ((ModifierKeys & (Keys.Alt | Keys.Control)) != 0) + { return false; } SetFlag(FlagDropDownCommit, false); - if (sender == Edit && Edit.Focused) { - + if (sender == Edit && Edit.Focused) + { + // if we aren't in an error state, just quit - if (errorState == ERROR_NONE) { - Edit.Text = originalTextValue; - Focus(); - return true; + if (errorState == ERROR_NONE) + { + Edit.Text = originalTextValue; + Focus(); + return true; } - - if (this.NeedsCommit) { + + if (this.NeedsCommit) + { bool success = false; Edit.Text = originalTextValue; bool needReset = true; - if (selectedGridEntry != null) { - + if (selectedGridEntry != null) + { + string curTextValue = selectedGridEntry.GetPropertyTextValue(); needReset = originalTextValue != curTextValue && !(string.IsNullOrEmpty(originalTextValue) && string.IsNullOrEmpty(curTextValue)); } - - if (needReset) { - try { + + if (needReset) + { + try + { success = CommitText(originalTextValue); } - catch { + catch + { } } - else { + else + { success = true; } // this would be an odd thing to happen, but... - if (!success) { + if (!success) + { Edit.Focus(); SelectEdit(false); return true; @@ -2767,25 +3257,29 @@ private bool OnEscape(Control sender) { Focus(); return true; } - else if (sender != this) { + else if (sender != this) + { CloseDropDown(); Focus(); } return false; } - protected override void OnKeyDown(KeyEventArgs ke) { - OnKeyDown(this,ke); + protected override void OnKeyDown(KeyEventArgs ke) + { + OnKeyDown(this, ke); } [ SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // We want to commit empty text. // So we don't have to localize it. ] - private void OnKeyDown(object sender, KeyEventArgs ke) { + private void OnKeyDown(object sender, KeyEventArgs ke) + { GridEntry gridEntry = GetGridEntryFromRow(selectedRow); - if (gridEntry == null) return; + if (gridEntry == null) + return; ke.Handled = true; bool fControl = ke.Control; @@ -2800,136 +3294,158 @@ private void OnKeyDown(object sender, KeyEventArgs ke) { // peek at the messages, we just get called, // so we have to do this here... // - if (keyCode == Keys.Tab) { - if (ProcessDialogKey(ke.KeyData)) { + if (keyCode == Keys.Tab) + { + if (ProcessDialogKey(ke.KeyData)) + { ke.Handled = true; return; } } // Alt-Arrow support... sigh... - if (keyCode == Keys.Down && fAlt && DropDownButton.Visible) { + if (keyCode == Keys.Down && fAlt && DropDownButton.Visible) + { F4Selection(false); return; } - if (keyCode == Keys.Up && fAlt && DropDownButton.Visible && (dropDownHolder != null) && dropDownHolder.Visible) { + if (keyCode == Keys.Up && fAlt && DropDownButton.Visible && (dropDownHolder != null) && dropDownHolder.Visible) + { UnfocusSelection(); return; } - if (ToolTip.Visible) { + if (ToolTip.Visible) + { ToolTip.ToolTip = string.Empty; } - if (fBoth || sender == this || sender == this.ownerGrid) { - switch (keyCode) { + if (fBoth || sender == this || sender == this.ownerGrid) + { + switch (keyCode) + { case Keys.Up: case Keys.Down: int pos = (keyCode == Keys.Up ? selectedRow - 1 : selectedRow + 1); - SelectGridEntry(GetGridEntryFromRow(pos),true); + SelectGridEntry(GetGridEntryFromRow(pos), true); SetFlag(FlagNoDefault, false); return; case Keys.Left: - if (fControl) { + if (fControl) + { // move the splitter 3 pixels to the left MoveSplitterTo(InternalLabelWidth - 3); return; } if (gridEntry.InternalExpanded) - SetExpand(gridEntry,false); - else { + SetExpand(gridEntry, false); + else + { // Handle non-expand/collapse case of left & right as up & down - SelectGridEntry( GetGridEntryFromRow( selectedRow - 1 ), true ); + SelectGridEntry(GetGridEntryFromRow(selectedRow - 1), true); } return; case Keys.Right: - if (fControl) { + if (fControl) + { // move the splitter 3 pixels to the right MoveSplitterTo(InternalLabelWidth + 3); return; } - if (gridEntry.Expandable) { - if (gridEntry.InternalExpanded) { + if (gridEntry.Expandable) + { + if (gridEntry.InternalExpanded) + { GridEntryCollection rgipes2 = gridEntry.Children; - SelectGridEntry(rgipes2.GetEntry(0),true); + SelectGridEntry(rgipes2.GetEntry(0), true); } else - SetExpand(gridEntry,true); + SetExpand(gridEntry, true); } - else { + else + { // Handle non-expand/collapse case of left & right as up & down - SelectGridEntry( GetGridEntryFromRow( selectedRow + 1 ), true ); + SelectGridEntry(GetGridEntryFromRow(selectedRow + 1), true); } return; case Keys.Return: - if (gridEntry.Expandable) { - SetExpand(gridEntry,!gridEntry.InternalExpanded); + if (gridEntry.Expandable) + { + SetExpand(gridEntry, !gridEntry.InternalExpanded); } - else { - gridEntry.OnValueReturnKey(); + else + { + gridEntry.OnValueReturnKey(); } - + return; case Keys.Home: case Keys.End: GridEntryCollection rgipes = GetAllGridEntries(); - int pos2 = (keyCode == Keys.Home ? 0 : rgipes.Count-1); - SelectGridEntry(rgipes.GetEntry(pos2),true); + int pos2 = (keyCode == Keys.Home ? 0 : rgipes.Count - 1); + SelectGridEntry(rgipes.GetEntry(pos2), true); return; case Keys.Add: case Keys.Oemplus: case Keys.OemMinus: case Keys.Subtract: - if (!gridEntry.Expandable) { + if (!gridEntry.Expandable) + { break; } - + SetFlag(FlagIsSpecialKey, true); bool expand = (keyCode == Keys.Add || keyCode == Keys.Oemplus); - SetExpand(gridEntry,expand); + SetExpand(gridEntry, expand); Invalidate(); ke.Handled = true; return; - - case Keys.D8: - if (fShift) { + + case Keys.D8: + if (fShift) + { goto case Keys.Multiply; } break; - case Keys.Multiply: + case Keys.Multiply: SetFlag(FlagIsSpecialKey, true); - RecursivelyExpand(gridEntry,true, true, MaxRecurseExpand); + RecursivelyExpand(gridEntry, true, true, MaxRecurseExpand); ke.Handled = false; return; - - + + case Keys.Prior: //PAGE_UP: case Keys.Next: //PAGE_DOWN - + bool next = (keyCode == Keys.Next); //int rowGoal = next ? visibleRows - 1 : 0; int offset = next ? visibleRows - 1 : 1 - visibleRows; int row = selectedRow; - if (fControl && !fShift) { + if (fControl && !fShift) + { return; } - if (selectedRow != -1) { // actual paging. + if (selectedRow != -1) + { // actual paging. int start = GetScrollOffset(); SetScrollOffset(start + offset); SetConstants(); - if (GetScrollOffset() != (start + offset)) { + if (GetScrollOffset() != (start + offset)) + { // we didn't make a full page - if (next) { + if (next) + { row = visibleRows - 1; } - else { + else + { row = 0; } } @@ -2937,54 +3453,61 @@ private void OnKeyDown(object sender, KeyEventArgs ke) { SelectRow(row); Refresh(); - return; - + return; + // Copy/paste support... - + case Keys.Insert: - if (fShift && !fControl && !fAlt) { - fallingThorugh = true; - goto case Keys.V; + if (fShift && !fControl && !fAlt) + { + fallingThorugh = true; + goto case Keys.V; } goto case Keys.C; case Keys.C: // copy text in current property - if (fControl && !fAlt && !fShift) { - DoCopyCommand(); - return; + if (fControl && !fAlt && !fShift) + { + DoCopyCommand(); + return; } break; case Keys.Delete: // cut text in current property - if (fShift && !fControl && !fAlt) { - fallingThorugh = true; - goto case Keys.X; + if (fShift && !fControl && !fAlt) + { + fallingThorugh = true; + goto case Keys.X; } break; case Keys.X: // cut text in current property - if (fallingThorugh || (fControl && !fAlt && !fShift)) { - Clipboard.SetDataObject(gridEntry.GetPropertyTextValue()); - CommitText(""); - return; + if (fallingThorugh || (fControl && !fAlt && !fShift)) + { + Clipboard.SetDataObject(gridEntry.GetPropertyTextValue()); + CommitText(""); + return; } break; case Keys.V: // paste the text - if (fallingThorugh || (fControl && !fAlt && !fShift)) { - DoPasteCommand(); + if (fallingThorugh || (fControl && !fAlt && !fShift)) + { + DoPasteCommand(); } break; case Keys.A: - if (fControl && !fAlt && !fShift && Edit.Visible) { - Edit.Focus(); - Edit.SelectAll(); + if (fControl && !fAlt && !fShift && Edit.Visible) + { + Edit.Focus(); + Edit.SelectAll(); } break; } } - if (gridEntry != null && ke.KeyData == (Keys.C | Keys.Alt | Keys.Shift | Keys.Control)) { + if (gridEntry != null && ke.KeyData == (Keys.C | Keys.Alt | Keys.Shift | Keys.Control)) + { Clipboard.SetDataObject(gridEntry.GetTestingInfo()); return; } @@ -3036,7 +3559,8 @@ we are removing this functionality. return; } - protected override void OnKeyPress(KeyPressEventArgs ke) { + protected override void OnKeyPress(KeyPressEventArgs ke) + { bool fControl = false; //ke.getControl(); bool fShift = false; //ke.getShift(); @@ -3047,18 +3571,22 @@ protected override void OnKeyPress(KeyPressEventArgs ke) { SetFlag(FlagIsSpecialKey, false); } - protected override void OnMouseDown(MouseEventArgs me) { + protected override void OnMouseDown(MouseEventArgs me) + { // check for a splitter - if (me.Button == MouseButtons.Left && SplitterInside(me.X,me.Y) && totalProps != 0) { - if (!Commit()) { + if (me.Button == MouseButtons.Left && SplitterInside(me.X, me.Y) && totalProps != 0) + { + if (!Commit()) + { return; } - - if (me.Clicks == 2) { - MoveSplitterTo(this.Width / 2); - return; + + if (me.Clicks == 2) + { + MoveSplitterTo(this.Width / 2); + return; } - + UnfocusSelection(); SetFlag(FlagIsSplitterMove, true); tipInfo = -1; @@ -3067,9 +3595,10 @@ protected override void OnMouseDown(MouseEventArgs me) { } // are ew on a propentry? - Point pos = FindPosition(me.X,me.Y); + Point pos = FindPosition(me.X, me.Y); - if (pos == InvalidPosition) { + if (pos == InvalidPosition) + { return; } @@ -3077,18 +3606,21 @@ protected override void OnMouseDown(MouseEventArgs me) { // it's coords first...we really just need the x, y GridEntry gridEntry = GetGridEntryFromRow(pos.Y); - if (gridEntry != null) { + if (gridEntry != null) + { // get the origin of this pe Rectangle r = GetRectangle(pos.Y, ROWLABEL); - + lastMouseDown = new Point(me.X, me.Y); // offset the mouse points // notify the prop entry - if (me.Button == MouseButtons.Left) { + if (me.Button == MouseButtons.Left) + { gridEntry.OnMouseClick(me.X - r.X, me.Y - r.Y, me.Clicks, me.Button); } - else { + else + { SelectGridEntry(gridEntry, false); } lastMouseDown = InvalidPosition; @@ -3098,58 +3630,71 @@ protected override void OnMouseDown(MouseEventArgs me) { } // this will make tool tip go away. - protected override void OnMouseLeave(EventArgs e) { + protected override void OnMouseLeave(EventArgs e) + { if (!GetFlag(FlagIsSplitterMove)) Cursor = Cursors.Default; // Cursor = null;; base.OnMouseLeave(e); } - protected override void OnMouseMove(MouseEventArgs me) { + protected override void OnMouseMove(MouseEventArgs me) + { int rowMoveCur; Point pt = Point.Empty; bool onLabel = false; - if (me == null) { + if (me == null) + { rowMoveCur = -1; pt = InvalidPosition; } - else { - pt = FindPosition(me.X,me.Y); - if (pt == InvalidPosition || (pt.X != ROWLABEL && pt.X != ROWVALUE)) { + else + { + pt = FindPosition(me.X, me.Y); + if (pt == InvalidPosition || (pt.X != ROWLABEL && pt.X != ROWVALUE)) + { rowMoveCur = -1; ToolTip.ToolTip = string.Empty; } - else { + else + { rowMoveCur = pt.Y; onLabel = pt.X == ROWLABEL; } } - if (pt == InvalidPosition || me == null) { + if (pt == InvalidPosition || me == null) + { return; } - if (GetFlag(FlagIsSplitterMove)) { + if (GetFlag(FlagIsSplitterMove)) + { MoveSplitterTo(me.X); } - - if ((rowMoveCur != this.TipRow || pt.X != this.TipColumn) && !GetFlag(FlagIsSplitterMove)) { + + if ((rowMoveCur != this.TipRow || pt.X != this.TipColumn) && !GetFlag(FlagIsSplitterMove)) + { GridEntry gridItem = GetGridEntryFromRow(rowMoveCur); string tip = string.Empty; tipInfo = -1; - if (gridItem != null) { + if (gridItem != null) + { Rectangle itemRect = GetRectangle(pt.Y, pt.X); - if (onLabel && gridItem.GetLabelToolTipLocation(me.X - itemRect.X, me.Y - itemRect.Y) != InvalidPoint) { + if (onLabel && gridItem.GetLabelToolTipLocation(me.X - itemRect.X, me.Y - itemRect.Y) != InvalidPoint) + { tip = gridItem.LabelToolTipText; this.TipRow = rowMoveCur; this.TipColumn = pt.X; } - else if (!onLabel && gridItem.ValueToolTipLocation != InvalidPoint && !Edit.Focused) { - if (!this.NeedsCommit) { - tip = gridItem.GetPropertyTextValue(); + else if (!onLabel && gridItem.ValueToolTipLocation != InvalidPoint && !Edit.Focused) + { + if (!this.NeedsCommit) + { + tip = gridItem.GetPropertyTextValue(); } this.TipRow = rowMoveCur; this.TipColumn = pt.X; @@ -3158,49 +3703,60 @@ protected override void OnMouseMove(MouseEventArgs me) { // Ensure that tooltips don't display when host application is not foreground app. // Assume that we don't want to display the tooltips - IntPtr foregroundWindow = UnsafeNativeMethods.GetForegroundWindow(); - if (UnsafeNativeMethods.IsChild(new HandleRef(null, foregroundWindow), new HandleRef(null, this.Handle))) { + IntPtr foregroundWindow = UnsafeNativeMethods.GetForegroundWindow(); + if (UnsafeNativeMethods.IsChild(new HandleRef(null, foregroundWindow), new HandleRef(null, this.Handle))) + { // Don't show the tips if a dropdown is showing - if ((dropDownHolder == null || dropDownHolder.Component == null) || rowMoveCur == selectedRow) { + if ((dropDownHolder == null || dropDownHolder.Component == null) || rowMoveCur == selectedRow) + { ToolTip.ToolTip = tip; } } - else { + else + { ToolTip.ToolTip = string.Empty; } } - if (totalProps != 0 && (SplitterInside(me.X,me.Y) || GetFlag(FlagIsSplitterMove))) { + if (totalProps != 0 && (SplitterInside(me.X, me.Y) || GetFlag(FlagIsSplitterMove))) + { Cursor = Cursors.VSplit; } - else { + else + { Cursor = Cursors.Default; // Cursor = null;; } base.OnMouseMove(me); } - protected override void OnMouseUp(MouseEventArgs me) { + protected override void OnMouseUp(MouseEventArgs me) + { CancelSplitterMove(); } - protected override void OnMouseWheel(MouseEventArgs me) { - + protected override void OnMouseWheel(MouseEventArgs me) + { + this.ownerGrid.OnGridViewMouseWheel(me); HandledMouseEventArgs e = me as HandledMouseEventArgs; - if (e != null) { - if (e.Handled) { - return; - } - e.Handled = true; + if (e != null) + { + if (e.Handled) + { + return; + } + e.Handled = true; } - - if ((ModifierKeys & (Keys.Shift | Keys.Alt)) != 0 || MouseButtons != MouseButtons.None) { + + if ((ModifierKeys & (Keys.Shift | Keys.Alt)) != 0 || MouseButtons != MouseButtons.None) + { return; // Do not scroll when Shift or Alt key is down, or when a mouse button is down. } int wheelScrollLines = SystemInformation.MouseWheelScrollLines; - if (wheelScrollLines == 0) { + if (wheelScrollLines == 0) + { return; // Do not scroll when the user system setting is 0 lines per notch } @@ -3211,155 +3767,184 @@ protected override void OnMouseWheel(MouseEventArgs me) { // we use the mouse wheel to change the values in the dropdown if it's // an enumerable value. // - if (selectedGridEntry != null && selectedGridEntry.Enumerable && Edit.Focused && selectedGridEntry.IsValueEditable) { - int index = GetCurrentValueIndex(selectedGridEntry); - if (index != -1) { - int delta = me.Delta > 0 ? -1 : 1; - object[] values = selectedGridEntry.GetPropertyValueList(); + if (selectedGridEntry != null && selectedGridEntry.Enumerable && Edit.Focused && selectedGridEntry.IsValueEditable) + { + int index = GetCurrentValueIndex(selectedGridEntry); + if (index != -1) + { + int delta = me.Delta > 0 ? -1 : 1; + object[] values = selectedGridEntry.GetPropertyValueList(); - if (delta > 0 && index >= (values.Length - 1)) { + if (delta > 0 && index >= (values.Length - 1)) + { index = 0; - } - else if (delta < 0 && index == 0) { + } + else if (delta < 0 && index == 0) + { index = values.Length - 1; - } - else { + } + else + { index += delta; - } + } - CommitValue(values[index]); - SelectGridEntry(selectedGridEntry, true); - Edit.Focus(); - return; - } + CommitValue(values[index]); + SelectGridEntry(selectedGridEntry, true); + Edit.Focus(); + return; + } } int initialOffset = GetScrollOffset(); cumulativeVerticalWheelDelta += me.Delta; float partialNotches = (float)cumulativeVerticalWheelDelta / (float)NativeMethods.WHEEL_DELTA; - int fullNotches = (int) partialNotches; + int fullNotches = (int)partialNotches; + + if (wheelScrollLines == -1) + { - if (wheelScrollLines == -1) { + // Equivalent to large change scrolls + if (fullNotches != 0) + { - // Equivalent to large change scrolls - if (fullNotches != 0) { - int originalOffset = initialOffset; - int large = fullNotches * this.scrollBar.LargeChange; - int newOffset = Math.Max(0,initialOffset - large); - newOffset = Math.Min(newOffset, totalProps - visibleRows+1); + int large = fullNotches * this.scrollBar.LargeChange; + int newOffset = Math.Max(0, initialOffset - large); + newOffset = Math.Min(newOffset, totalProps - visibleRows + 1); + - initialOffset -= fullNotches * this.scrollBar.LargeChange; - if (Math.Abs(initialOffset - originalOffset) >= Math.Abs(fullNotches * this.scrollBar.LargeChange)) { + if (Math.Abs(initialOffset - originalOffset) >= Math.Abs(fullNotches * this.scrollBar.LargeChange)) + { this.cumulativeVerticalWheelDelta -= fullNotches * NativeMethods.WHEEL_DELTA; } - else { + else + { this.cumulativeVerticalWheelDelta = 0; } - - if (!ScrollRows(newOffset)) { - this.cumulativeVerticalWheelDelta = 0; + + if (!ScrollRows(newOffset)) + { + this.cumulativeVerticalWheelDelta = 0; return; } } } - else { - - - // SystemInformation.MouseWheelScrollLines doesn't work under terminal server, - // it default to the notches per scroll. - int scrollBands = (int) ((float) wheelScrollLines * partialNotches); - - if (scrollBands != 0) { - - if (ToolTip.Visible) { + else + { + + + // SystemInformation.MouseWheelScrollLines doesn't work under terminal server, + // it default to the notches per scroll. + int scrollBands = (int)((float)wheelScrollLines * partialNotches); + + if (scrollBands != 0) + { + + if (ToolTip.Visible) + { ToolTip.ToolTip = string.Empty; } - int newOffset = Math.Max(0,initialOffset - scrollBands); - newOffset = Math.Min(newOffset, totalProps - visibleRows+1); + int newOffset = Math.Max(0, initialOffset - scrollBands); + newOffset = Math.Min(newOffset, totalProps - visibleRows + 1); - if (scrollBands > 0) { + if (scrollBands > 0) + { - if (this.scrollBar.Value <= this.scrollBar.Minimum) { + if (this.scrollBar.Value <= this.scrollBar.Minimum) + { this.cumulativeVerticalWheelDelta = 0; } - else { - this.cumulativeVerticalWheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); + else + { + this.cumulativeVerticalWheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); } } - else { + else + { - if (this.scrollBar.Value > (scrollBar.Maximum-visibleRows+1)) { + if (this.scrollBar.Value > (scrollBar.Maximum - visibleRows + 1)) + { this.cumulativeVerticalWheelDelta = 0; } - else { + else + { this.cumulativeVerticalWheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); } } - if (!ScrollRows(newOffset)) { - this.cumulativeVerticalWheelDelta = 0; - return; - } + if (!ScrollRows(newOffset)) + { + this.cumulativeVerticalWheelDelta = 0; + return; + } } - else { + else + { this.cumulativeVerticalWheelDelta = 0; } } } - protected override void OnMove(EventArgs e) { + protected override void OnMove(EventArgs e) + { CloseDropDown(); } - - protected override void OnPaintBackground(PaintEventArgs pe) { + + protected override void OnPaintBackground(PaintEventArgs pe) + { } - protected override void OnPaint(PaintEventArgs pe) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnPaint"); - Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "On paint called. Rect=" + pe.ClipRectangle.ToString()); + protected override void OnPaint(PaintEventArgs pe) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnPaint"); + Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "On paint called. Rect=" + pe.ClipRectangle.ToString()); Graphics g = pe.Graphics; int yPos = 0; int startRow = 0; int endRow = visibleRows - 1; - + Rectangle clipRect = pe.ClipRectangle; - + // give ourselves a little breathing room to account for lines, etc., as well // as the entries themselves. // - clipRect.Inflate(0,2); + clipRect.Inflate(0, 2); - try { + try + { Size sizeWindow = this.Size; // figure out what rows we're painting Point posStart = FindPosition(clipRect.X, clipRect.Y); Point posEnd = FindPosition(clipRect.X, clipRect.Y + clipRect.Height); - if (posStart != InvalidPosition) { - startRow = Math.Max(0,posStart.Y); + if (posStart != InvalidPosition) + { + startRow = Math.Max(0, posStart.Y); } - if (posEnd != InvalidPosition) { - endRow = posEnd.Y; + if (posEnd != InvalidPosition) + { + endRow = posEnd.Y; } - int cPropsVisible = Math.Min(totalProps - GetScrollOffset(),1+visibleRows); - + int cPropsVisible = Math.Min(totalProps - GetScrollOffset(), 1 + visibleRows); + #if DEBUG GridEntry debugIPEStart = GetGridEntryFromRow(startRow); - GridEntry debugIPEEnd = GetGridEntryFromRow(endRow); + GridEntry debugIPEEnd = GetGridEntryFromRow(endRow); string startName = debugIPEStart == null ? null : debugIPEStart.PropertyLabel; - if (startName == null) { + if (startName == null) + { startName = "(null)"; } string endName = debugIPEEnd == null ? null : debugIPEEnd.PropertyLabel; - if (endName == null) { + if (endName == null) + { endName = "(null)"; } #endif @@ -3371,28 +3956,30 @@ protected override void OnPaint(PaintEventArgs pe) { Size size = this.GetOurSize(); Point loc = this.ptOurLocation; - if (GetGridEntryFromRow(cPropsVisible-1) == null) { + if (GetGridEntryFromRow(cPropsVisible - 1) == null) + { cPropsVisible--; } // if we actually have some properties, then start drawing the grid // - if (totalProps > 0) { - + if (totalProps > 0) + { + // draw splitter - cPropsVisible = Math.Min(cPropsVisible, endRow+1); + cPropsVisible = Math.Min(cPropsVisible, endRow + 1); - Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Drawing splitter"); + Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Drawing splitter"); Pen splitterPen = new Pen(ownerGrid.LineColor, GetSplitterWidth()); splitterPen.DashStyle = DashStyle.Solid; - g.DrawLine(splitterPen, labelWidth,loc.Y,labelWidth, (cPropsVisible)*(RowHeight+1)+loc.Y); + g.DrawLine(splitterPen, labelWidth, loc.Y, labelWidth, (cPropsVisible) * (RowHeight + 1) + loc.Y); splitterPen.Dispose(); // draw lines. - Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Drawing lines"); + Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Drawing lines"); Pen linePen = new Pen(g.GetNearestColor(ownerGrid.LineColor)); - + int cHeightCurRow = 0; int cLineEnd = loc.X + size.Width; int cLineStart = loc.X; @@ -3402,271 +3989,313 @@ protected override void OnPaint(PaintEventArgs pe) { //g.TextColor = ownerGrid.TextColor; // draw labels. set clip rect. - for (int i = startRow; i < cPropsVisible; i++) { - try { + for (int i = startRow; i < cPropsVisible; i++) + { + try + { // draw the line - cHeightCurRow = (i)*(RowHeight+1) + loc.Y; - g.DrawLine(linePen, cLineStart,cHeightCurRow,cLineEnd,cHeightCurRow); + cHeightCurRow = (i) * (RowHeight + 1) + loc.Y; + g.DrawLine(linePen, cLineStart, cHeightCurRow, cLineEnd, cHeightCurRow); // draw the value - DrawValueEntry(g,i, ref clipRect); + DrawValueEntry(g, i, ref clipRect); // draw the label - Rectangle rect = GetRectangle(i,ROWLABEL); + Rectangle rect = GetRectangle(i, ROWLABEL); yPos = rect.Y + rect.Height; - DrawLabel(g,i, rect, (i==selectedRow),false, ref clipRect); - if (i == selectedRow) { + DrawLabel(g, i, rect, (i == selectedRow), false, ref clipRect); + if (i == selectedRow) + { Edit.Invalidate(); } } - catch { - Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Exception thrown during painting property " + GetGridEntryFromRow(i).PropertyLabel); + catch + { + Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Exception thrown during painting property " + GetGridEntryFromRow(i).PropertyLabel); } } // draw the bottom line - cHeightCurRow = (cPropsVisible)*(RowHeight+1) + loc.Y; - g.DrawLine(linePen, cLineStart,cHeightCurRow,cLineEnd,cHeightCurRow); - + cHeightCurRow = (cPropsVisible) * (RowHeight + 1) + loc.Y; + g.DrawLine(linePen, cLineStart, cHeightCurRow, cLineEnd, cHeightCurRow); + linePen.Dispose(); } // fill anything left with window - if (yPos < Size.Height) { + if (yPos < Size.Height) + { yPos++; Rectangle clearRect = new Rectangle(1, yPos, Size.Width - 2, Size.Height - yPos - 1); - Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Filling remaining area rect=" + clearRect.ToString()); - + Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Filling remaining area rect=" + clearRect.ToString()); + g.FillRectangle(backgroundBrush, clearRect); } // draw outside border - using (Pen borderPen = new Pen(ownerGrid.ViewBorderColor, 1)) { + using (Pen borderPen = new Pen(ownerGrid.ViewBorderColor, 1)) + { g.DrawRectangle(borderPen, 0, 0, sizeWindow.Width - 1, sizeWindow.Height - 1); } - + fontBold = null; } - catch { + catch + { Debug.Fail("Caught exception in OnPaint"); // Do nothing. } - finally { + finally + { ClearCachedFontInfo(); } } - private void OnGridEntryLabelDoubleClick(object s, EventArgs e) { + private void OnGridEntryLabelDoubleClick(object s, EventArgs e) + { GridEntry gridEntry = (GridEntry)s; // if we've changed since the click (probably because we moved a row into view), bail // - if (gridEntry != lastClickedEntry) { + if (gridEntry != lastClickedEntry) + { return; } int row = GetRowFromGridEntry(gridEntry); DoubleClickRow(row, gridEntry.Expandable, ROWLABEL); } - private void OnGridEntryValueDoubleClick(object s, EventArgs e) { + private void OnGridEntryValueDoubleClick(object s, EventArgs e) + { GridEntry gridEntry = (GridEntry)s; // if we've changed since the click (probably because we moved a row into view), bail // - if (gridEntry != lastClickedEntry) { + if (gridEntry != lastClickedEntry) + { return; - } + } int row = GetRowFromGridEntry(gridEntry); DoubleClickRow(row, gridEntry.Expandable, ROWVALUE); } - private void OnGridEntryLabelClick(object s, EventArgs e) { + private void OnGridEntryLabelClick(object s, EventArgs e) + { this.lastClickedEntry = (GridEntry)s; SelectGridEntry(lastClickedEntry, true); } - private void OnGridEntryOutlineClick(object s, EventArgs e) { + private void OnGridEntryOutlineClick(object s, EventArgs e) + { GridEntry gridEntry = (GridEntry)s; Debug.Assert(gridEntry.Expandable, "non-expandable IPE firing outline click"); Cursor oldCursor = Cursor; - if (!ShouldSerializeCursor()) { + if (!ShouldSerializeCursor()) + { oldCursor = null; } Cursor = Cursors.WaitCursor; - try { + try + { SetExpand(gridEntry, !gridEntry.InternalExpanded); SelectGridEntry(gridEntry, false); } - finally { + finally + { Cursor = oldCursor; } } - private void OnGridEntryValueClick(object s, EventArgs e) { - + private void OnGridEntryValueClick(object s, EventArgs e) + { + this.lastClickedEntry = (GridEntry)s; bool setSelectTime = s != selectedGridEntry; SelectGridEntry(lastClickedEntry, true); Edit.Focus(); - - if (lastMouseDown != InvalidPosition) { - - // clear the row select time so we don't interpret this as a double click. - // - rowSelectTime = 0; - - Point editPoint = PointToScreen(lastMouseDown); - editPoint = Edit.PointToClient(editPoint); - Edit.SendMessage(Interop.WindowMessages.WM_LBUTTONDOWN, 0, (int)(editPoint.Y << 16 | (editPoint.X & 0xFFFF))); - Edit.SendMessage(Interop.WindowMessages.WM_LBUTTONUP, 0, (int)(editPoint.Y << 16 | (editPoint.X & 0xFFFF))); - } - - if (setSelectTime) { - rowSelectTime = DateTime.Now.Ticks; - rowSelectPos = PointToScreen(lastMouseDown); - } - else { - rowSelectTime = 0; - rowSelectPos = Point.Empty; - } - } - - private void ClearCachedFontInfo() { - if (baseHfont != IntPtr.Zero) { + + if (lastMouseDown != InvalidPosition) + { + + // clear the row select time so we don't interpret this as a double click. + // + rowSelectTime = 0; + + Point editPoint = PointToScreen(lastMouseDown); + editPoint = Edit.PointToClient(editPoint); + Edit.SendMessage(Interop.WindowMessages.WM_LBUTTONDOWN, 0, (int)(editPoint.Y << 16 | (editPoint.X & 0xFFFF))); + Edit.SendMessage(Interop.WindowMessages.WM_LBUTTONUP, 0, (int)(editPoint.Y << 16 | (editPoint.X & 0xFFFF))); + } + + if (setSelectTime) + { + rowSelectTime = DateTime.Now.Ticks; + rowSelectPos = PointToScreen(lastMouseDown); + } + else + { + rowSelectTime = 0; + rowSelectPos = Point.Empty; + } + } + + private void ClearCachedFontInfo() + { + if (baseHfont != IntPtr.Zero) + { SafeNativeMethods.ExternalDeleteObject(new HandleRef(this, baseHfont)); baseHfont = IntPtr.Zero; } - if (boldHfont != IntPtr.Zero) { + if (boldHfont != IntPtr.Zero) + { SafeNativeMethods.ExternalDeleteObject(new HandleRef(this, boldHfont)); boldHfont = IntPtr.Zero; } } - protected override void OnFontChanged(EventArgs e) { - + protected override void OnFontChanged(EventArgs e) + { + ClearCachedFontInfo(); cachedRowHeight = -1; - if (this.Disposing || this.ParentInternal == null || this.ParentInternal.Disposing) { + if (this.Disposing || this.ParentInternal == null || this.ParentInternal.Disposing) + { return; } - + fontBold = null; // fontBold is cached based on Font - + ToolTip.Font = this.Font; SetFlag(FlagNeedUpdateUIBasedOnFont, true); UpdateUIBasedOnFont(true); base.OnFontChanged(e); - if (selectedGridEntry != null) { + if (selectedGridEntry != null) + { SelectGridEntry(selectedGridEntry, true); } } - protected override void OnVisibleChanged(EventArgs e) { - if (this.Disposing || this.ParentInternal == null || this.ParentInternal.Disposing) { + protected override void OnVisibleChanged(EventArgs e) + { + if (this.Disposing || this.ParentInternal == null || this.ParentInternal.Disposing) + { return; } - - if (this.Visible && this.ParentInternal != null) { - SetConstants(); - if (selectedGridEntry != null) { - SelectGridEntry(selectedGridEntry, true); - } - if (toolTip != null) { - ToolTip.Font = this.Font; - } - + + if (this.Visible && this.ParentInternal != null) + { + SetConstants(); + if (selectedGridEntry != null) + { + SelectGridEntry(selectedGridEntry, true); + } + if (toolTip != null) + { + ToolTip.Font = this.Font; + } + } base.OnVisibleChanged(e); } - + // a GridEntry recreated its children - protected virtual void OnRecreateChildren(object s, GridEntryRecreateChildrenEventArgs e) { - GridEntry parent = (GridEntry) s; + protected virtual void OnRecreateChildren(object s, GridEntryRecreateChildrenEventArgs e) + { + GridEntry parent = (GridEntry)s; + + if (parent.Expanded) + { - if (parent.Expanded) { - GridEntry[] entries = new GridEntry[allGridEntries.Count]; allGridEntries.CopyTo(entries, 0); - + // find the index of the gridEntry that fired the event in our main list. int parentIndex = -1; - for (int i = 0; i < entries.Length; i++) { - if (entries[i] == parent) { + for (int i = 0; i < entries.Length; i++) + { + if (entries[i] == parent) + { parentIndex = i; break; } } - + Debug.Assert(parentIndex != -1, "parent GridEntry not found in allGridEntries"); - + // clear our existing handlers ClearGridEntryEvents(allGridEntries, parentIndex + 1, e.OldChildCount); - + // resize the array if it's changed - if (e.OldChildCount != e.NewChildCount) { + if (e.OldChildCount != e.NewChildCount) + { int newArraySize = entries.Length + (e.NewChildCount - e.OldChildCount); GridEntry[] newEntries = new GridEntry[newArraySize]; - + // copy the existing entries up to the parent Array.Copy(entries, 0, newEntries, 0, parentIndex + 1); - + // copy the entries after the spot we'll be putting the new ones - Array.Copy(entries, parentIndex + e.OldChildCount+1, newEntries, parentIndex + e.NewChildCount+1, entries.Length - (parentIndex + e.OldChildCount + 1)); - + Array.Copy(entries, parentIndex + e.OldChildCount + 1, newEntries, parentIndex + e.NewChildCount + 1, entries.Length - (parentIndex + e.OldChildCount + 1)); + entries = newEntries; } - + // from that point, replace the children with tne new children. GridEntryCollection children = parent.Children; int childCount = children.Count; - + Debug.Assert(childCount == e.NewChildCount, "parent reports " + childCount + " new children, event reports " + e.NewChildCount); - + // replace the changed items - for (int i = 0; i < childCount; i++) { + for (int i = 0; i < childCount; i++) + { entries[parentIndex + i + 1] = children.GetEntry(i); } - + // reset the array, rehook the handlers. allGridEntries.Clear(); allGridEntries.AddRange(entries); - AddGridEntryEvents(allGridEntries, parentIndex + 1, childCount); - + AddGridEntryEvents(allGridEntries, parentIndex + 1, childCount); + } - if (e.OldChildCount != e.NewChildCount) { + if (e.OldChildCount != e.NewChildCount) + { totalProps = CountPropsFromOutline(topLevelGridEntries); SetConstants(); } Invalidate(); } - - protected override void OnResize(EventArgs e) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnResize"); + + protected override void OnResize(EventArgs e) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnResize"); Rectangle newRect = ClientRectangle; - int yDelta = lastClientRect == Rectangle.Empty ? 0 : newRect.Height - lastClientRect.Height; - bool lastRow = (selectedRow+1) == visibleRows; + int yDelta = lastClientRect == Rectangle.Empty ? 0 : newRect.Height - lastClientRect.Height; + bool lastRow = (selectedRow + 1) == visibleRows; // if we are hiding or showing the scroll bar, update the selected row // or if we are changing widths // bool sbVisible = ScrollBar.Visible; - if (!lastClientRect.IsEmpty && newRect.Width > lastClientRect.Width) { - Rectangle rectInvalidate = new Rectangle(lastClientRect.Width-1,0,newRect.Width-lastClientRect.Width+1,lastClientRect.Height); + if (!lastClientRect.IsEmpty && newRect.Width > lastClientRect.Width) + { + Rectangle rectInvalidate = new Rectangle(lastClientRect.Width - 1, 0, newRect.Width - lastClientRect.Width + 1, lastClientRect.Height); Invalidate(rectInvalidate); } - if (!lastClientRect.IsEmpty && yDelta > 0) { - Rectangle rectInvalidate = new Rectangle(0,lastClientRect.Height-1,lastClientRect.Width,newRect.Height-lastClientRect.Height+1); + if (!lastClientRect.IsEmpty && yDelta > 0) + { + Rectangle rectInvalidate = new Rectangle(0, lastClientRect.Height - 1, lastClientRect.Width, newRect.Height - lastClientRect.Height + 1); Invalidate(rectInvalidate); } @@ -3675,7 +4304,8 @@ protected override void OnResize(EventArgs e) { SetConstants(); SetScrollOffset(scroll); - if (DpiHelper.IsScalingRequirementMet) { + if (DpiHelper.IsScalingRequirementMet) + { SetFlag(FlagNeedUpdateUIBasedOnFont, true); UpdateUIBasedOnFont(true); base.OnFontChanged(e); @@ -3685,15 +4315,17 @@ protected override void OnResize(EventArgs e) { LayoutWindow(false); - bool selectionVisible = (selectedGridEntry != null && selectedRow >=0 && selectedRow <= visibleRows); + bool selectionVisible = (selectedGridEntry != null && selectedRow >= 0 && selectedRow <= visibleRows); SelectGridEntry(selectedGridEntry, selectionVisible); lastClientRect = newRect; } - private void OnScroll(object sender, ScrollEventArgs se) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnScroll(" + ScrollBar.Value.ToString(CultureInfo.InvariantCulture) + " -> " + se.NewValue.ToString(CultureInfo.InvariantCulture) +")"); + private void OnScroll(object sender, ScrollEventArgs se) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnScroll(" + ScrollBar.Value.ToString(CultureInfo.InvariantCulture) + " -> " + se.NewValue.ToString(CultureInfo.InvariantCulture) + ")"); - if (!Commit() || !IsScrollValueValid(se.NewValue)) { + if (!Commit() || !IsScrollValueValid(se.NewValue)) + { // cancel the move se.NewValue = ScrollBar.Value; return; @@ -3701,37 +4333,46 @@ private void OnScroll(object sender, ScrollEventArgs se) { int oldRow = -1; GridEntry oldGridEntry = selectedGridEntry; - if (selectedGridEntry != null) { + if (selectedGridEntry != null) + { oldRow = GetRowFromGridEntry(oldGridEntry); - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "OnScroll: SelectedGridEntry=" + oldGridEntry.PropertyLabel); + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "OnScroll: SelectedGridEntry=" + oldGridEntry.PropertyLabel); } ScrollBar.Value = se.NewValue; - if (oldGridEntry != null) { + if (oldGridEntry != null) + { // we need to zero out the selected row so we don't try to commit again...since selectedRow is now bogus. selectedRow = -1; SelectGridEntry(oldGridEntry, (ScrollBar.Value == totalProps ? true : false)); int newRow = GetRowFromGridEntry(oldGridEntry); - if (oldRow != newRow) { - Invalidate(); + if (oldRow != newRow) + { + Invalidate(); } } - else { + else + { Invalidate(); } } - private void OnSysColorChange(object sender, UserPreferenceChangedEventArgs e) { - if (e.Category == UserPreferenceCategory.Color || e.Category == UserPreferenceCategory.Accessibility) { + private void OnSysColorChange(object sender, UserPreferenceChangedEventArgs e) + { + if (e.Category == UserPreferenceCategory.Color || e.Category == UserPreferenceCategory.Accessibility) + { SetFlag(FlagNeedUpdateUIBasedOnFont, true); } } - - public virtual void PopupDialog(int row) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:PopupDialog"); + + public virtual void PopupDialog(int row) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:PopupDialog"); GridEntry gridEntry = GetGridEntryFromRow(row); - if (gridEntry != null) { - if (dropDownHolder != null && dropDownHolder.GetUsed()) { + if (gridEntry != null) + { + if (dropDownHolder != null && dropDownHolder.GetUsed()) + { CloseDropDown(); return; } @@ -3739,7 +4380,8 @@ public virtual void PopupDialog(int row) { bool fBtnDropDown = gridEntry.NeedsDropDownButton; bool fEnum = gridEntry.Enumerable; bool fBtnDialog = gridEntry.NeedsCustomEditorButton; - if (fEnum && !fBtnDropDown) { + if (fEnum && !fBtnDropDown) + { DropDownListBox.Items.Clear(); object value = gridEntry.PropertyValue; object[] rgItems = gridEntry.GetPropertyValueList(); @@ -3753,190 +4395,225 @@ public virtual void PopupDialog(int row) { Interop.HandleCollector.Add(hFont, Interop.CommonHandles.GDI); NativeMethods.TEXTMETRIC tm = new NativeMethods.TEXTMETRIC(); int iSel = -1; - try { + try + { hFont = SafeNativeMethods.SelectObject(new HandleRef(DropDownListBox, hdc), new HandleRef(Font, hFont)); - + iSel = GetCurrentValueIndex(gridEntry); - if (rgItems != null && rgItems.Length > 0) { + if (rgItems != null && rgItems.Length > 0) + { string s; IntNativeMethods.SIZE textSize = new IntNativeMethods.SIZE(); - - for (int i = 0; i < rgItems.Length; i++) { + + for (int i = 0; i < rgItems.Length; i++) + { s = gridEntry.GetPropertyTextValue(rgItems[i]); - DropDownListBox.Items.Add(s); + DropDownListBox.Items.Add(s); IntUnsafeNativeMethods.GetTextExtentPoint32(new HandleRef(DropDownListBox, hdc), s, textSize); - maxWidth = Math.Max((int) textSize.cx, maxWidth); + maxWidth = Math.Max((int)textSize.cx, maxWidth); } } SafeNativeMethods.GetTextMetricsW(new HandleRef(DropDownListBox, hdc), ref tm); - + // border + padding + scrollbar maxWidth += 2 + tm.tmMaxCharWidth + SystemInformation.VerticalScrollBarWidth; - + hFont = SafeNativeMethods.SelectObject(new HandleRef(DropDownListBox, hdc), new HandleRef(Font, hFont)); } - finally { + finally + { SafeNativeMethods.DeleteObject(new HandleRef(Font, hFont)); UnsafeNativeMethods.ReleaseDC(new HandleRef(DropDownListBox, DropDownListBox.Handle), new HandleRef(DropDownListBox, hdc)); } - + // Microsoft, 4/25/1998 - must check for -1 and not call the set... - if (iSel != -1) { + if (iSel != -1) + { DropDownListBox.SelectedIndex = iSel; } SetFlag(FlagDropDownCommit, false); DropDownListBox.Height = Math.Max(tm.tmHeight + 2, Math.Min(maxListBoxHeight, DropDownListBox.PreferredHeight)); - DropDownListBox.Width = Math.Max(maxWidth, GetRectangle(row,ROWVALUE).Width); - try { + DropDownListBox.Width = Math.Max(maxWidth, GetRectangle(row, ROWVALUE).Width); + try + { bool resizable = DropDownListBox.Items.Count > (DropDownListBox.Height / DropDownListBox.ItemHeight); SetFlag(FlagResizableDropDown, resizable); DropDownControl(DropDownListBox); } - finally { + finally + { SetFlag(FlagResizableDropDown, false); } - + Refresh(); } - else if (fBtnDialog || fBtnDropDown) { - try { + else if (fBtnDialog || fBtnDropDown) + { + try + { SetFlag(FlagInPropertySet, true); Edit.DisableMouseHook = true; - try { + try + { SetFlag(FlagResizableDropDown, gridEntry.UITypeEditor.IsDropDownResizable); gridEntry.EditPropertyValue(this); } - finally { + finally + { SetFlag(FlagResizableDropDown, false); } - } - finally { + } + finally + { SetFlag(FlagInPropertySet, false); Edit.DisableMouseHook = false; - } - Refresh(); - - // We can't do this because - // some dialogs are non-modal, and - // this will pull focus from them. - // - //if (fBtnDialog) { - // this.Focus(); - //} - - if (FocusInside) { + } + Refresh(); + + // We can't do this because + // some dialogs are non-modal, and + // this will pull focus from them. + // + //if (fBtnDialog) { + // this.Focus(); + //} + + if (FocusInside) + { SelectGridEntry(gridEntry, false); - } + } } } } - - internal static void PositionTooltip(Control parent, GridToolTip ToolTip, Rectangle itemRect) { + + internal static void PositionTooltip(Control parent, GridToolTip ToolTip, Rectangle itemRect) + { ToolTip.Visible = false; - + NativeMethods.RECT rect = NativeMethods.RECT.FromXYWH(itemRect.X, itemRect.Y, itemRect.Width, itemRect.Height); ToolTip.SendMessage(NativeMethods.TTM_ADJUSTRECT, 1, ref rect); // now offset it back to screen coords Point locPoint = parent.PointToScreen(new Point(rect.left, rect.top)); - + ToolTip.Location = locPoint; // set the position once so it updates it's size with it's real width. - - int overHang = (ToolTip.Location.X + ToolTip.Size.Width) - SystemInformation.VirtualScreen.Width; - if (overHang > 0) { + + int overHang = (ToolTip.Location.X + ToolTip.Size.Width) - SystemInformation.VirtualScreen.Width; + if (overHang > 0) + { locPoint.X -= overHang; ToolTip.Location = locPoint; } // tell the control we've repositioned it. - ToolTip.Visible = true; + ToolTip.Visible = true; } - - - protected override bool ProcessDialogKey(Keys keyData) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:ProcessDialogKey"); - if (HasEntries) { + + + protected override bool ProcessDialogKey(Keys keyData) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:ProcessDialogKey"); + if (HasEntries) + { Keys keyCode = keyData & Keys.KeyCode; - switch (keyCode) { + switch (keyCode) + { case Keys.F4: - if (FocusInside) { + if (FocusInside) + { return OnF4(this); } break; case Keys.Tab: - if (((keyData & Keys.Control) != 0) || - ((keyData & Keys.Alt) != 0)) { + if (((keyData & Keys.Control) != 0) || + ((keyData & Keys.Alt) != 0)) + { break; } - + bool forward = (keyData & Keys.Shift) == 0; Control focusedControl = Control.FromHandle(UnsafeNativeMethods.GetFocus()); - if (focusedControl == null || !IsMyChild(focusedControl)) { - if (forward) { + if (focusedControl == null || !IsMyChild(focusedControl)) + { + if (forward) + { TabSelection(); focusedControl = Control.FromHandle(UnsafeNativeMethods.GetFocus()); // make sure the value actually took the focus - if (IsMyChild(focusedControl)) { + if (IsMyChild(focusedControl)) + { return true; } - else { + else + { return base.ProcessDialogKey(keyData); } } - else { + else + { break; } } - else { + else + { // one of our editors has focus - if (Edit.Focused) { - if (forward) { - if (DropDownButton.Visible) { + if (Edit.Focused) + { + if (forward) + { + if (DropDownButton.Visible) + { DropDownButton.Focus(); return true; } - else if (DialogButton.Visible) { + else if (DialogButton.Visible) + { DialogButton.Focus(); return true; } // fall through } - else { + else + { SelectGridEntry(GetGridEntryFromRow(selectedRow), false); return true; } } - else if (DialogButton.Focused || DropDownButton.Focused) { - if (!forward && Edit.Visible) { + else if (DialogButton.Focused || DropDownButton.Focused) + { + if (!forward && Edit.Visible) + { Edit.Focus(); return true; } // fall through } } - break; + break; case Keys.Up: case Keys.Down: case Keys.Left: case Keys.Right: return false; case Keys.Return: - if (DialogButton.Focused || DropDownButton.Focused) { - OnBtnClick((DialogButton.Focused ? DialogButton : DropDownButton), EventArgs.Empty); - return true; + if (DialogButton.Focused || DropDownButton.Focused) + { + OnBtnClick((DialogButton.Focused ? DialogButton : DropDownButton), EventArgs.Empty); + return true; } - else if (selectedGridEntry != null && selectedGridEntry.Expandable) { - SetExpand(selectedGridEntry, !selectedGridEntry.InternalExpanded); - return true; + else if (selectedGridEntry != null && selectedGridEntry.Expandable) + { + SetExpand(selectedGridEntry, !selectedGridEntry.InternalExpanded); + return true; } break; } @@ -3944,19 +4621,23 @@ protected override bool ProcessDialogKey(Keys keyData) { return base.ProcessDialogKey(keyData); } - protected virtual void RecalculateProps() { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:RecalculateProps"); + protected virtual void RecalculateProps() + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:RecalculateProps"); int props = CountPropsFromOutline(topLevelGridEntries); - if (totalProps != props) { + if (totalProps != props) + { totalProps = props; ClearGridEntryEvents(allGridEntries, 0, -1); allGridEntries = null; } } - internal /*public virtual*/ void RecursivelyExpand(GridEntry gridEntry, bool fInit, bool expand, int maxExpands) { + internal /*public virtual*/ void RecursivelyExpand(GridEntry gridEntry, bool fInit, bool expand, int maxExpands) + { - if (gridEntry == null || (expand && --maxExpands < 0)) { + if (gridEntry == null || (expand && --maxExpands < 0)) + { return; } @@ -3965,26 +4646,31 @@ protected virtual void RecalculateProps() { GridEntryCollection rgipes = gridEntry.Children; if (rgipes != null) for (int i = 0; i < rgipes.Count; i++) - RecursivelyExpand(rgipes.GetEntry(i),false, expand, maxExpands); + RecursivelyExpand(rgipes.GetEntry(i), false, expand, maxExpands); - if (fInit) { + if (fInit) + { GridEntry ipeSelect = selectedGridEntry; Refresh(); - SelectGridEntry(ipeSelect,false); + SelectGridEntry(ipeSelect, false); Invalidate(); } } - public override void Refresh() { + public override void Refresh() + { Refresh(false, -1, -1); //resetting gridoutline rect to recalculate before repaint when viewsort property changed. This is necessary especially when user // changes sort and move to a secondary monitor with different DPI and change view sort back to original. - if (topLevelGridEntries != null && DpiHelper.IsScalingRequirementMet) { + if (topLevelGridEntries != null && DpiHelper.IsScalingRequirementMet) + { var outlineRectIconSize = this.GetOutlineIconSize(); - foreach (GridEntry gridentry in topLevelGridEntries) { - if (gridentry.OutlineRect.Height != outlineRectIconSize || gridentry.OutlineRect.Width != outlineRectIconSize) { + foreach (GridEntry gridentry in topLevelGridEntries) + { + if (gridentry.OutlineRect.Height != outlineRectIconSize || gridentry.OutlineRect.Width != outlineRectIconSize) + { ResetOutline(gridentry); } } @@ -3994,69 +4680,80 @@ public override void Refresh() { Invalidate(); } - public void Refresh(bool fullRefresh) { + public void Refresh(bool fullRefresh) + { Refresh(fullRefresh, -1, -1); } - + GridPositionData positionData; - - private void Refresh(bool fullRefresh, int rowStart, int rowEnd) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:Refresh"); - Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Refresh called for rows " + rowStart.ToString(CultureInfo.InvariantCulture) + " through " + rowEnd.ToString(CultureInfo.InvariantCulture)); + + private void Refresh(bool fullRefresh, int rowStart, int rowEnd) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:Refresh"); + Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Refresh called for rows " + rowStart.ToString(CultureInfo.InvariantCulture) + " through " + rowEnd.ToString(CultureInfo.InvariantCulture)); SetFlag(FlagNeedsRefresh, true); GridEntry gridEntry = null; // There are cases here where the grid could get be disposed. // so just bail. - if (this.IsDisposed) { + if (this.IsDisposed) + { return; } bool pageInGridEntry = true; - - if (rowStart == -1) { + + if (rowStart == -1) + { rowStart = 0; } - - if (fullRefresh || this.ownerGrid.HavePropEntriesChanged()) { - if (HasEntries && !GetInPropertySet() && !Commit()) { + + if (fullRefresh || this.ownerGrid.HavePropEntriesChanged()) + { + if (HasEntries && !GetInPropertySet() && !Commit()) + { OnEscape(this); } - + int oldLength = totalProps; object oldObject = topLevelGridEntries == null || topLevelGridEntries.Count == 0 ? null : ((GridEntry)topLevelGridEntries[0]).GetValueOwner(); - + // walk up to the main IPE and refresh it. - if (fullRefresh) { + if (fullRefresh) + { this.ownerGrid.RefreshProperties(true); } - - if (oldLength > 0 && !GetFlag(FlagNoDefault)) { - positionData = CaptureGridPositionData(); - CommonEditorHide(true); + + if (oldLength > 0 && !GetFlag(FlagNoDefault)) + { + positionData = CaptureGridPositionData(); + CommonEditorHide(true); } UpdateHelpAttributes(selectedGridEntry, null); selectedGridEntry = null; SetFlag(FlagIsNewSelection, true); topLevelGridEntries = this.ownerGrid.GetPropEntries(); - - + + ClearGridEntryEvents(allGridEntries, 0, -1); allGridEntries = null; RecalculateProps(); - + int newLength = totalProps; - if (newLength > 0) { - if (newLength < oldLength) { + if (newLength > 0) + { + if (newLength < oldLength) + { SetScrollbarLength(); SetScrollOffset(0); } - + SetConstants(); - if (positionData != null) { + if (positionData != null) + { gridEntry = positionData.Restore(this); // Upon restoring the grid entry position, we don't @@ -4065,22 +4762,26 @@ private void Refresh(bool fullRefresh, int rowStart, int rowEnd) { object newObject = topLevelGridEntries == null || topLevelGridEntries.Count == 0 ? null : ((GridEntry)topLevelGridEntries[0]).GetValueOwner(); pageInGridEntry = (gridEntry == null) || oldLength != newLength || newObject != oldObject; } - - if (gridEntry == null) { + + if (gridEntry == null) + { gridEntry = this.ownerGrid.GetDefaultGridEntry(); SetFlag(FlagNoDefault, gridEntry == null && totalProps > 0); } InvalidateRows(rowStart, rowEnd); - if (gridEntry == null) { + if (gridEntry == null) + { selectedRow = 0; selectedGridEntry = GetGridEntryFromRow(selectedRow); } } - else if (oldLength == 0) { + else if (oldLength == 0) + { return; } - else { + else + { SetConstants(); } @@ -4090,7 +4791,8 @@ private void Refresh(bool fullRefresh, int rowStart, int rowEnd) { lastClickedEntry = null; } - if (!HasEntries) { + if (!HasEntries) + { CommonEditorHide(selectedRow != -1); this.ownerGrid.SetStatusBox(null, null); SetScrollOffset(0); @@ -4099,108 +4801,130 @@ private void Refresh(bool fullRefresh, int rowStart, int rowEnd) { return; } // in case we added or removed properties - + ownerGrid.ClearValueCaches(); InvalidateRows(rowStart, rowEnd); - if (gridEntry != null) { + if (gridEntry != null) + { SelectGridEntry(gridEntry, pageInGridEntry); } } - public virtual void Reset() { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:Reset"); + public virtual void Reset() + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:Reset"); GridEntry gridEntry = GetGridEntryFromRow(selectedRow); - if (gridEntry == null) return; + if (gridEntry == null) + return; gridEntry.ResetPropertyValue(); SelectRow(selectedRow); } - protected virtual void ResetOrigin(System.Drawing.Graphics g) { + protected virtual void ResetOrigin(System.Drawing.Graphics g) + { g.ResetTransform(); } - - internal void RestoreHierarchyState(ArrayList expandedItems) { - if (expandedItems == null) { - return; + + internal void RestoreHierarchyState(ArrayList expandedItems) + { + if (expandedItems == null) + { + return; } - - foreach(GridEntryCollection gec in expandedItems) { - FindEquivalentGridEntry(gec); + + foreach (GridEntryCollection gec in expandedItems) + { + FindEquivalentGridEntry(gec); } } - public virtual DialogResult RunDialog(Form dialog) { + public virtual DialogResult RunDialog(Form dialog) + { return ShowDialog(dialog); } - - internal ArrayList SaveHierarchyState(GridEntryCollection entries) { + + internal ArrayList SaveHierarchyState(GridEntryCollection entries) + { return SaveHierarchyState(entries, null); } - - private ArrayList SaveHierarchyState(GridEntryCollection entries, ArrayList expandedItems) { - if (entries == null) { - return new ArrayList(); + + private ArrayList SaveHierarchyState(GridEntryCollection entries, ArrayList expandedItems) + { + if (entries == null) + { + return new ArrayList(); } - - if (expandedItems == null) { - expandedItems = new ArrayList(); + + if (expandedItems == null) + { + expandedItems = new ArrayList(); } - - for (int i = 0; i < entries.Count; i++) { - if (((GridEntry)entries[i]).InternalExpanded) { - GridEntry entry = entries.GetEntry(i); - expandedItems.Add(GetGridEntryHierarchy(entry.Children.GetEntry(0))); - SaveHierarchyState(entry.Children, expandedItems); - } + + for (int i = 0; i < entries.Count; i++) + { + if (((GridEntry)entries[i]).InternalExpanded) + { + GridEntry entry = entries.GetEntry(i); + expandedItems.Add(GetGridEntryHierarchy(entry.Children.GetEntry(0))); + SaveHierarchyState(entry.Children, expandedItems); + } } - + return expandedItems; } // Scroll to the new offset - private bool ScrollRows(int newOffset) { - - GridEntry ipeCur = selectedGridEntry; - - if (!IsScrollValueValid(newOffset) || !Commit()) { - return false; - } - - bool showEdit = Edit.Visible; - bool showBtnDropDown = DropDownButton.Visible; - bool showBtnEdit = DialogButton.Visible; - - Edit.Visible = false; - DialogButton.Visible = false; - DropDownButton.Visible = false; - - SetScrollOffset(newOffset); - - if (ipeCur != null) { + private bool ScrollRows(int newOffset) + { + + GridEntry ipeCur = selectedGridEntry; + + if (!IsScrollValueValid(newOffset) || !Commit()) + { + return false; + } + + bool showEdit = Edit.Visible; + bool showBtnDropDown = DropDownButton.Visible; + bool showBtnEdit = DialogButton.Visible; + + Edit.Visible = false; + DialogButton.Visible = false; + DropDownButton.Visible = false; + + SetScrollOffset(newOffset); + + if (ipeCur != null) + { int curRow = GetRowFromGridEntry(ipeCur); - if (curRow >=0 && curRow < visibleRows-1) { + if (curRow >= 0 && curRow < visibleRows - 1) + { Edit.Visible = showEdit; DialogButton.Visible = showBtnEdit; DropDownButton.Visible = showBtnDropDown; SelectGridEntry(ipeCur, true); } - else { + else + { CommonEditorHide(); } - } - else { + } + else + { CommonEditorHide(); - } - - Invalidate(); - return true; + } + + Invalidate(); + return true; } - private void SelectEdit(bool caretAtEnd) { - if (edit != null) { + private void SelectEdit(bool caretAtEnd) + { + if (edit != null) + { Edit.SelectAll(); } } @@ -4208,64 +4932,77 @@ private void SelectEdit(bool caretAtEnd) { // select functions... selectGridEntry and selectRow will select a Row // and install the appropriate editors. // - internal /*protected virtual*/ void SelectGridEntry(GridEntry gridEntry, bool fPageIn) { + internal /*protected virtual*/ void SelectGridEntry(GridEntry gridEntry, bool fPageIn) + { - if (gridEntry == null) return; - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:SelectGridEntry(" + gridEntry.PropertyLabel + ")"); + if (gridEntry == null) + return; + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:SelectGridEntry(" + gridEntry.PropertyLabel + ")"); int row = GetRowFromGridEntry(gridEntry); - if (row + GetScrollOffset() < 0) { + if (row + GetScrollOffset() < 0) + { // throw exception? return false? return; } - int maxRows = (int)Math.Ceiling(((double)GetOurSize().Height)/(1+RowHeight)); + int maxRows = (int)Math.Ceiling(((double)GetOurSize().Height) / (1 + RowHeight)); // Determine whether or not we need to page-in this GridEntry // - if (!fPageIn || (row >= 0 && row < (maxRows-1))) { + if (!fPageIn || (row >= 0 && row < (maxRows - 1))) + { // No need to page-in: either fPageIn is false or the row is already in view // - SelectRow(row); + SelectRow(row); } - else { + else + { // Page-in the selected GridEntry // - + selectedRow = -1; // clear the selected row since it's no longer a valid number - + int cOffset = GetScrollOffset(); - if (row < 0) { + if (row < 0) + { SetScrollOffset(row + cOffset); Invalidate(); SelectRow(0); } - else { + else + { // try to put it one row up from the bottom int newOffset = row + cOffset - (maxRows - 2); - - if (newOffset >= ScrollBar.Minimum && newOffset < ScrollBar.Maximum) { + + if (newOffset >= ScrollBar.Minimum && newOffset < ScrollBar.Maximum) + { SetScrollOffset(newOffset); } Invalidate(); SelectGridEntry(gridEntry, false); } - } + } } - private void SelectRow(int row) { + private void SelectRow(int row) + { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:SelectRow(" + row.ToString(CultureInfo.InvariantCulture) + ")"); + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:SelectRow(" + row.ToString(CultureInfo.InvariantCulture) + ")"); - if (!GetFlag(FlagIsNewSelection)) { - if (this.FocusInside) { + if (!GetFlag(FlagIsNewSelection)) + { + if (this.FocusInside) + { // If we're in an error state, we want to bail out of this. - if (errorState != ERROR_NONE || (row != selectedRow && !Commit())) { + if (errorState != ERROR_NONE || (row != selectedRow && !Commit())) + { return; } } - else { + else + { Focus(); } } @@ -4274,23 +5011,27 @@ private void SelectRow(int row) { // Update our reset command. // - if (row != selectedRow) { + if (row != selectedRow) + { UpdateResetCommand(gridEntry); } - if (GetFlag(FlagIsNewSelection) && GetGridEntryFromRow(selectedRow) == null) { + if (GetFlag(FlagIsNewSelection) && GetGridEntryFromRow(selectedRow) == null) + { CommonEditorHide(); } UpdateHelpAttributes(selectedGridEntry, gridEntry); // tell the old selection it's not focused any more - if (selectedGridEntry != null) { + if (selectedGridEntry != null) + { selectedGridEntry.Focus = false; } // selection not visible. - if (row < 0 || row >= visibleRows) { + if (row < 0 || row >= visibleRows) + { CommonEditorHide(); selectedRow = row; selectedGridEntry = gridEntry; @@ -4304,15 +5045,16 @@ private void SelectRow(int row) { bool newRow = false; int oldSel = selectedRow; - if (selectedRow != row || !gridEntry.Equals(selectedGridEntry)) { + if (selectedRow != row || !gridEntry.Equals(selectedGridEntry)) + { CommonEditorHide(); newRow = true; } - + if (!newRow) CloseDropDown(); - Rectangle rect = GetRectangle(row,ROWVALUE); + Rectangle rect = GetRectangle(row, ROWVALUE); string s = gridEntry.GetPropertyTextValue(); // what components are we using? @@ -4325,30 +5067,34 @@ private void SelectRow(int row) { rect.Width -= 1; // we want to allow builders on read-only properties - if ((fBtnDialog || fBtnDropDown) && !gridEntry.ShouldRenderReadOnly && FocusInside) { + if ((fBtnDialog || fBtnDropDown) && !gridEntry.ShouldRenderReadOnly && FocusInside) + { Control btn = fBtnDropDown ? (Control)DropDownButton : (Control)DialogButton; Size sizeBtn = DpiHelper.IsScalingRequirementMet ? new Size(SystemInformation.VerticalScrollBarArrowHeightForDpi(this.deviceDpi), RowHeight) : new Size(SystemInformation.VerticalScrollBarArrowHeight, RowHeight); - Rectangle rectTarget = new Rectangle(rect.X+rect.Width-sizeBtn.Width, + Rectangle rectTarget = new Rectangle(rect.X + rect.Width - sizeBtn.Width, rect.Y, - sizeBtn.Width,rect.Height); - CommonEditorUse(btn,rectTarget); + sizeBtn.Width, rect.Height); + CommonEditorUse(btn, rectTarget); sizeBtn = btn.Size; rect.Width -= (sizeBtn.Width); btn.Invalidate(); } // if we're painting the value, size the rect between the button and the painted value - if (fPaint) { + if (fPaint) + { rect.X += paintIndent + 1; rect.Width -= paintIndent + 1; } - else { + else + { rect.X += EDIT_INDENT + 1; // +1 to compensate for where GDI+ draws it's string relative to the rect. rect.Width -= EDIT_INDENT + 1; } - - if ((GetFlag(FlagIsNewSelection) || !Edit.Focused) && (s != null && !s.Equals(Edit.Text))) { + + if ((GetFlag(FlagIsNewSelection) || !Edit.Focused) && (s != null && !s.Equals(Edit.Text))) + { Edit.Text = s; originalTextValue = s; Edit.SelectionStart = 0; @@ -4357,17 +5103,21 @@ private void SelectRow(int row) { Edit.AccessibleName = gridEntry.Label; #if true // RENDERMODE - switch (inheritRenderMode) { + switch (inheritRenderMode) + { case RENDERMODE_BOLD: - if (gridEntry.ShouldSerializePropertyValue()) { + if (gridEntry.ShouldSerializePropertyValue()) + { Edit.Font = GetBoldFont(); } - else { + else + { Edit.Font = Font; } break; case RENDERMODE_LEFTDOT: - if (gridEntry.ShouldSerializePropertyValue()) { + if (gridEntry.ShouldSerializePropertyValue()) + { rect.X += (LEFTDOT_SIZE * 2); rect.Width -= (LEFTDOT_SIZE * 2); } @@ -4379,14 +5129,16 @@ private void SelectRow(int row) { } #endif - if (GetFlag(FlagIsSplitterMove) || !gridEntry.HasValue || !FocusInside) { + if (GetFlag(FlagIsSplitterMove) || !gridEntry.HasValue || !FocusInside) + { Edit.Visible = false; } - else { - rect.Offset(1,1); + else + { + rect.Offset(1, 1); rect.Height -= 1; rect.Width -= 1; - CommonEditorUse(Edit,rect); + CommonEditorUse(Edit, rect); bool drawReadOnly = gridEntry.ShouldRenderReadOnly; Edit.ForeColor = drawReadOnly ? this.GrayTextColor : this.ForeColor; Edit.BackColor = this.BackColor; @@ -4397,17 +5149,19 @@ private void SelectRow(int row) { GridEntry oldSelectedGridEntry = selectedGridEntry; selectedRow = row; selectedGridEntry = gridEntry; - this.ownerGrid.SetStatusBox(gridEntry.PropertyLabel,gridEntry.PropertyDescription); + this.ownerGrid.SetStatusBox(gridEntry.PropertyLabel, gridEntry.PropertyDescription); // tell the new focused item that it now has focus - if (selectedGridEntry != null) { + if (selectedGridEntry != null) + { selectedGridEntry.Focus = this.FocusInside; } - if (!GetFlag(FlagIsNewSelection)) { + if (!GetFlag(FlagIsNewSelection)) + { Focus(); } - + // InvalidateRow(oldSel); @@ -4417,72 +5171,86 @@ private void SelectRow(int row) { { SetFlag(FlagIsNewSelection, false); } - - try { - if (selectedGridEntry != oldSelectedGridEntry) { + + try + { + if (selectedGridEntry != oldSelectedGridEntry) + { this.ownerGrid.OnSelectedGridItemChanged(oldSelectedGridEntry, selectedGridEntry); - } + } } - catch { + catch + { } } - public virtual void SetConstants() { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:SetConstants"); + public virtual void SetConstants() + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:SetConstants"); Size size = this.GetOurSize(); - - visibleRows = (int)Math.Ceiling(((double)size.Height)/(1+RowHeight)); - + + visibleRows = (int)Math.Ceiling(((double)size.Height) / (1 + RowHeight)); + size = this.GetOurSize(); - - if (size.Width >= 0) { + + if (size.Width >= 0) + { labelRatio = Math.Max(Math.Min(labelRatio, 9), 1.1); - labelWidth = ptOurLocation.X + (int) ((double)size.Width / labelRatio); + labelWidth = ptOurLocation.X + (int)((double)size.Width / labelRatio); } - + int oldWidth = labelWidth; - + bool adjustWidth = SetScrollbarLength(); GridEntryCollection rgipesAll = GetAllGridEntries(); - if (rgipesAll != null) { + if (rgipesAll != null) + { int scroll = GetScrollOffset(); - if ((scroll + visibleRows) >= rgipesAll.Count) { + if ((scroll + visibleRows) >= rgipesAll.Count) + { visibleRows = rgipesAll.Count - scroll; } } - - - if (adjustWidth && size.Width >= 0) { - labelRatio = ((double) GetOurSize().Width / (double) (oldWidth - ptOurLocation.X)); + + + if (adjustWidth && size.Width >= 0) + { + labelRatio = ((double)GetOurSize().Width / (double)(oldWidth - ptOurLocation.X)); //labelWidth = loc.X + (int) ((double)size.Width / labelRatio); } - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "\tsize :" + size.ToString()); - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "\tlocation :" + ptOurLocation.ToString()); - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "\tvisibleRows:" + (visibleRows).ToString(CultureInfo.InvariantCulture)); - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "\tlabelWidth :" + (labelWidth).ToString(CultureInfo.InvariantCulture)); - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "\tlabelRatio :" + (labelRatio).ToString(CultureInfo.InvariantCulture)); - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "\trowHeight :" + (RowHeight).ToString(CultureInfo.InvariantCulture)); + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "\tsize :" + size.ToString()); + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "\tlocation :" + ptOurLocation.ToString()); + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "\tvisibleRows:" + (visibleRows).ToString(CultureInfo.InvariantCulture)); + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "\tlabelWidth :" + (labelWidth).ToString(CultureInfo.InvariantCulture)); + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "\tlabelRatio :" + (labelRatio).ToString(CultureInfo.InvariantCulture)); + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "\trowHeight :" + (RowHeight).ToString(CultureInfo.InvariantCulture)); #if DEBUG - if (rgipesAll == null) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "\tIPE Count :(null)"); + if (rgipesAll == null) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "\tIPE Count :(null)"); } - else { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "\tIPE Count :" + (rgipesAll.Count).ToString(CultureInfo.InvariantCulture)); + else + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "\tIPE Count :" + (rgipesAll.Count).ToString(CultureInfo.InvariantCulture)); } #endif } - private void SetCommitError(short error) { + private void SetCommitError(short error) + { SetCommitError(error, error == ERROR_THROWN); } - private void SetCommitError(short error, bool capture) { - #if DEBUG - if (CompModSwitches.DebugGridView.TraceVerbose) { + private void SetCommitError(short error, bool capture) + { +#if DEBUG + if (CompModSwitches.DebugGridView.TraceVerbose) + { string err = "UNKNOWN!"; - switch (error) { + switch (error) + { case ERROR_NONE: err = "ERROR_NONE"; break; @@ -4493,20 +5261,23 @@ private void SetCommitError(short error, bool capture) { err = "ERROR_MSGBOX_UP"; break; } - Debug.WriteLine( "PropertyGridView:SetCommitError(error=" + err + ", capture=" + capture.ToString() + ")"); + Debug.WriteLine("PropertyGridView:SetCommitError(error=" + err + ", capture=" + capture.ToString() + ")"); } - #endif +#endif errorState = error; - if (error != ERROR_NONE) { + if (error != ERROR_NONE) + { CancelSplitterMove(); } - + Edit.HookMouseDown = capture; - + } - internal /*public virtual*/ void SetExpand(GridEntry gridEntry, bool value) { - if (gridEntry != null && gridEntry.Expandable) { + internal /*public virtual*/ void SetExpand(GridEntry gridEntry, bool value) + { + if (gridEntry != null && gridEntry.Expandable) + { int row = GetRowFromGridEntry(gridEntry); int countFromEnd = visibleRows - row; @@ -4514,7 +5285,8 @@ private void SetCommitError(short error, bool capture) { // if the currently selected row is below us, we need to commit now // or the offsets will be wrong - if (selectedRow != -1 && row < selectedRow && Edit.Visible) { + if (selectedRow != -1 && row < selectedRow && Edit.Visible) + { // this will cause the commit Focus(); @@ -4526,9 +5298,12 @@ private void SetCommitError(short error, bool capture) { gridEntry.InternalExpanded = value; RecalculateProps(); GridEntry ipeSelect = selectedGridEntry; - if (!value) { - for (GridEntry ipeCur = ipeSelect; ipeCur != null; ipeCur = ipeCur.ParentGridEntry) { - if (ipeCur.Equals(gridEntry)) { + if (!value) + { + for (GridEntry ipeCur = ipeSelect; ipeCur != null; ipeCur = ipeCur.ParentGridEntry) + { + if (ipeCur.Equals(gridEntry)) + { ipeSelect = gridEntry; } } @@ -4539,14 +5314,15 @@ private void SetCommitError(short error, bool capture) { int newItems = totalProps - items; - if (value && newItems > 0 && newItems < visibleRows && (row + (newItems)) >= visibleRows && newItems < curRow) { + if (value && newItems > 0 && newItems < visibleRows && (row + (newItems)) >= visibleRows && newItems < curRow) + { // scroll to show the newly opened items. SetScrollOffset((totalProps - items) + offset); } Invalidate(); - SelectGridEntry(ipeSelect,false); + SelectGridEntry(ipeSelect, false); int scroll = GetScrollOffset(); SetScrollOffset(0); @@ -4555,79 +5331,97 @@ private void SetCommitError(short error, bool capture) { } } - private void SetFlag(short flag, bool value) { - if (value) { - flags = (short)((ushort)flags|(ushort)flag); + private void SetFlag(short flag, bool value) + { + if (value) + { + flags = (short)((ushort)flags | (ushort)flag); } - else { + else + { flags &= (short)~flag; } } - public virtual void SetScrollOffset(int cOffset) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:SetScrollOffset(" + cOffset.ToString(CultureInfo.InvariantCulture) + ")"); + public virtual void SetScrollOffset(int cOffset) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:SetScrollOffset(" + cOffset.ToString(CultureInfo.InvariantCulture) + ")"); int posNew = Math.Max(0, Math.Min(totalProps - visibleRows + 1, cOffset)); int posOld = ScrollBar.Value; - if (posNew != posOld && IsScrollValueValid(posNew) && visibleRows > 0) { + if (posNew != posOld && IsScrollValueValid(posNew) && visibleRows > 0) + { ScrollBar.Value = posNew; - Invalidate(); + Invalidate(); selectedRow = GetRowFromGridEntry(selectedGridEntry); } } // C#r - internal virtual bool _Commit() { + internal virtual bool _Commit() + { return Commit(); } - private bool Commit() { + private bool Commit() + { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:Commit()"); + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:Commit()"); - if (errorState == ERROR_MSGBOX_UP) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:Commit() returning false because an error has been thrown or we are in a property set"); + if (errorState == ERROR_MSGBOX_UP) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:Commit() returning false because an error has been thrown or we are in a property set"); return false; } - if (!this.NeedsCommit) { + if (!this.NeedsCommit) + { SetCommitError(ERROR_NONE); - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:Commit() returning true because no change has been made"); + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:Commit() returning true because no change has been made"); return true; } - if (GetInPropertySet()) { + if (GetInPropertySet()) + { return false; } GridEntry ipeCur = GetGridEntryFromRow(selectedRow); - if (ipeCur == null) { + if (ipeCur == null) + { return true; } bool success = false; - try { + try + { success = CommitText(Edit.Text); } - finally { - - if (!success) { + finally + { + + if (!success) + { Edit.Focus(); SelectEdit(false); } - else { - SetCommitError(ERROR_NONE); + else + { + SetCommitError(ERROR_NONE); } } return success; } - private bool CommitValue(object value) { + private bool CommitValue(object value) + { GridEntry ipeCur = selectedGridEntry; - if (selectedGridEntry == null && selectedRow != -1) { + if (selectedGridEntry == null && selectedRow != -1) + { ipeCur = GetGridEntryFromRow(selectedRow); } - if (ipeCur == null) { + if (ipeCur == null) + { Debug.Fail("Committing with no selected row!"); return true; } @@ -4635,24 +5429,29 @@ private bool CommitValue(object value) { return CommitValue(ipeCur, value); } - internal bool CommitValue(GridEntry ipeCur, object value, bool closeDropDown = true) { + internal bool CommitValue(GridEntry ipeCur, object value, bool closeDropDown = true) + { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:CommitValue(" + (value==null ? "null" :value.ToString()) + ")"); + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:CommitValue(" + (value == null ? "null" : value.ToString()) + ")"); int propCount = ipeCur.ChildCount; bool capture = Edit.HookMouseDown; object originalValue = null; - try { + try + { originalValue = ipeCur.PropertyValue; } - catch { + catch + { // if the getter is failing, we still want to let // the set happen. } - try { - try { + try + { + try + { SetFlag(FlagInPropertySet, true); //if this propentry is enumerable, then once a value is selected from the editor, @@ -4661,33 +5460,39 @@ internal bool CommitValue(GridEntry ipeCur, object value, bool closeDropDown = t //from the editor, without having it close every time. if (ipeCur != null && ipeCur.Enumerable && - closeDropDown) { - CloseDropDown(); + closeDropDown) + { + CloseDropDown(); } - try { + try + { Edit.DisableMouseHook = true; ipeCur.PropertyValue = value; } - finally { + finally + { Edit.DisableMouseHook = false; Edit.HookMouseDown = capture; } } - catch (Exception ex) { + catch (Exception ex) + { SetCommitError(ERROR_THROWN); ShowInvalidMessage(ipeCur.PropertyLabel, value, ex); return false; } } - finally { + finally + { SetFlag(FlagInPropertySet, false); } SetCommitError(ERROR_NONE); string text = ipeCur.GetPropertyTextValue(); - if (!string.Equals(text, Edit.Text)) { + if (!string.Equals(text, Edit.Text)) + { Edit.Text = text; Edit.SelectionStart = 0; Edit.SelectionLength = 0; @@ -4698,22 +5503,25 @@ internal bool CommitValue(GridEntry ipeCur, object value, bool closeDropDown = t // UpdateResetCommand(ipeCur); - if (ipeCur.ChildCount != propCount) { + if (ipeCur.ChildCount != propCount) + { ClearGridEntryEvents(allGridEntries, 0, -1); allGridEntries = null; SelectGridEntry(ipeCur, true); } // in case this guy got disposed... - if (ipeCur.Disposed) { + if (ipeCur.Disposed) + { bool editfocused = (edit != null && edit.Focused); - + // reselect the row to find the replacement. // SelectGridEntry(ipeCur, true); ipeCur = selectedGridEntry; - if (editfocused && edit != null) { + if (editfocused && edit != null) + { edit.Focus(); } } @@ -4723,19 +5531,22 @@ internal bool CommitValue(GridEntry ipeCur, object value, bool closeDropDown = t return true; } - private bool CommitText(string text) { + private bool CommitText(string text) + { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:CommitValue(" + (text==null ? "null" :text.ToString()) + ")"); + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:CommitValue(" + (text == null ? "null" : text.ToString()) + ")"); object value = null; GridEntry ipeCur = selectedGridEntry; - if (selectedGridEntry == null && selectedRow != -1) { + if (selectedGridEntry == null && selectedRow != -1) + { ipeCur = GetGridEntryFromRow(selectedRow); } - if (ipeCur == null) { + if (ipeCur == null) + { Debug.Fail("Committing with no selected row!"); return true; } @@ -4755,53 +5566,68 @@ private bool CommitText(string text) { return CommitValue(value); } - - internal void ReverseFocus() { - if (selectedGridEntry == null) { - Focus(); - } - else { - SelectGridEntry(selectedGridEntry, true); - - if (DialogButton.Visible) { - DialogButton.Focus(); - } - else if (DropDownButton.Visible) { - DropDownButton.Focus(); - } - else if (Edit.Visible) { - Edit.SelectAll(); - Edit.Focus(); - } + + internal void ReverseFocus() + { + if (selectedGridEntry == null) + { + Focus(); + } + else + { + SelectGridEntry(selectedGridEntry, true); + + if (DialogButton.Visible) + { + DialogButton.Focus(); + } + else if (DropDownButton.Visible) + { + DropDownButton.Focus(); + } + else if (Edit.Visible) + { + Edit.SelectAll(); + Edit.Focus(); + } } } - private bool SetScrollbarLength() { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:SetScrollBarLength"); + private bool SetScrollbarLength() + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:SetScrollBarLength"); bool sbChange = false; - if (totalProps != -1) { - if (totalProps < visibleRows) { + if (totalProps != -1) + { + if (totalProps < visibleRows) + { SetScrollOffset(0); } - else if (GetScrollOffset() > totalProps) { - SetScrollOffset((totalProps+1) - visibleRows); + else if (GetScrollOffset() > totalProps) + { + SetScrollOffset((totalProps + 1) - visibleRows); } bool fHidden = !ScrollBar.Visible; - if (visibleRows > 0) { - ScrollBar.LargeChange = visibleRows-1; + if (visibleRows > 0) + { + ScrollBar.LargeChange = visibleRows - 1; } - ScrollBar.Maximum = Math.Max(0,totalProps - 1); - if (fHidden != (totalProps < visibleRows)) { + ScrollBar.Maximum = Math.Max(0, totalProps - 1); + if (fHidden != (totalProps < visibleRows)) + { sbChange = true; ScrollBar.Visible = fHidden; Size size = GetOurSize(); - if (labelWidth != -1 && size.Width > 0) { - if (labelWidth > ptOurLocation.X + size.Width) { - labelWidth = ptOurLocation.X + (int) ((double)size.Width / labelRatio); + if (labelWidth != -1 && size.Width > 0) + { + if (labelWidth > ptOurLocation.X + size.Width) + { + labelWidth = ptOurLocation.X + (int)((double)size.Width / labelRatio); } - else { - labelRatio = ((double) GetOurSize().Width / (double) (labelWidth - ptOurLocation.X)); + else + { + labelRatio = ((double)GetOurSize().Width / (double)(labelWidth - ptOurLocation.X)); } } Invalidate(); @@ -4815,15 +5641,20 @@ private bool SetScrollbarLength() { /// use this method rather than showing the dialog directly, as this will /// properly position the dialog and provide it a dialog owner. /// - public DialogResult /* IWindowsFormsEditorService. */ ShowDialog(Form dialog) { + public DialogResult /* IWindowsFormsEditorService. */ ShowDialog(Form dialog) + { // try to shift down if sitting right on top of existing owner. - if (dialog.StartPosition == FormStartPosition.CenterScreen) { + if (dialog.StartPosition == FormStartPosition.CenterScreen) + { Control topControl = this; - if (topControl != null) { - while (topControl.ParentInternal != null) { + if (topControl != null) + { + while (topControl.ParentInternal != null) + { topControl = topControl.ParentInternal; } - if (topControl.Size.Equals(dialog.Size)) { + if (topControl.Size.Equals(dialog.Size)) + { dialog.StartPosition = FormStartPosition.Manual; Point location = topControl.Location; // @@ -4837,14 +5668,17 @@ private bool SetScrollbarLength() { IUIService service = (IUIService)GetService(typeof(IUIService)); DialogResult result; - if (service != null) { + if (service != null) + { result = service.ShowDialog(dialog); } - else { + else + { result = dialog.ShowDialog(this); } - if (priorFocus != IntPtr.Zero) { + if (priorFocus != IntPtr.Zero) + { UnsafeNativeMethods.SetFocus(new HandleRef(null, priorFocus)); } @@ -4936,17 +5770,20 @@ private void ShowFormatExceptionMessage(string propName, object value, Exception } } - internal void ShowInvalidMessage(string propName, object value, Exception ex) { + internal void ShowInvalidMessage(string propName, object value, Exception ex) + { - if (value == null) { + if (value == null) + { value = "(null)"; } - if (propName == null) { + if (propName == null) + { propName = "(unknown)"; } - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:ShowInvalidMessage(prop=" + propName + ")"); + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:ShowInvalidMessage(prop=" + propName + ")"); // we have to uninstall our hook so the user can push the button! bool hooked = Edit.HookMouseDown; @@ -4968,7 +5805,8 @@ internal void ShowInvalidMessage(string propName, object value, Exception ex) { // These things are just plain useless. // - if (ex is System.Reflection.TargetInvocationException) { + if (ex is System.Reflection.TargetInvocationException) + { ex = ex.InnerException; } @@ -4978,58 +5816,69 @@ internal void ShowInvalidMessage(string propName, object value, Exception ex) { bool revert = false; - while (exMessage == null || exMessage.Length == 0) { + while (exMessage == null || exMessage.Length == 0) + { ex = ex.InnerException; - if (ex == null) { + if (ex == null) + { break; } exMessage = ex.Message; } - + IUIService uiSvc = (IUIService)GetService(typeof(IUIService)); ErrorDialog.Message = SR.PBRSErrorInvalidPropertyValue; ErrorDialog.Text = SR.PBRSErrorTitle; ErrorDialog.Details = exMessage; - - if (uiSvc != null) { + + if (uiSvc != null) + { revert = (DialogResult.Cancel == uiSvc.ShowDialog(ErrorDialog)); } - else { + else + { revert = (DialogResult.Cancel == this.ShowDialog(ErrorDialog)); } - + Edit.DisableMouseHook = false; - if (hooked) { + if (hooked) + { SelectGridEntry(selectedGridEntry, true); } SetCommitError(ERROR_THROWN, hooked); - if (revert) { + if (revert) + { OnEscape(Edit); } } - private bool SplitterInside(int x, int y) { - return(Math.Abs(x - InternalLabelWidth) < 4); + private bool SplitterInside(int x, int y) + { + return (Math.Abs(x - InternalLabelWidth) < 4); } - private void TabSelection() { + private void TabSelection() + { GridEntry gridEntry = GetGridEntryFromRow(selectedRow); if (gridEntry == null) return; - if (Edit.Visible) { + if (Edit.Visible) + { Edit.Focus(); SelectEdit(false); } - else if (dropDownHolder != null && dropDownHolder.Visible) { + else if (dropDownHolder != null && dropDownHolder.Visible) + { dropDownHolder.FocusComponent(); return; } - else if (currentEditor != null) { + else if (currentEditor != null) + { currentEditor.Focus(); } @@ -5037,106 +5886,133 @@ private void TabSelection() { } - internal void RemoveSelectedEntryHelpAttributes() { + internal void RemoveSelectedEntryHelpAttributes() + { UpdateHelpAttributes(selectedGridEntry, null); } - - private void UpdateHelpAttributes(GridEntry oldEntry, GridEntry newEntry) { + + private void UpdateHelpAttributes(GridEntry oldEntry, GridEntry newEntry) + { // Update the help context with the current property // IHelpService hsvc = GetHelpService(); - if (hsvc == null || oldEntry == newEntry) { + if (hsvc == null || oldEntry == newEntry) + { return; } GridEntry temp = oldEntry; - if (oldEntry != null && !oldEntry.Disposed) { - - - while (temp != null) { + if (oldEntry != null && !oldEntry.Disposed) + { + + + while (temp != null) + { hsvc.RemoveContextAttribute("Keyword", temp.HelpKeyword); temp = temp.ParentGridEntry; } } - if (newEntry != null) { + if (newEntry != null) + { temp = newEntry; - + UpdateHelpAttributes(hsvc, temp, true); } } - - private void UpdateHelpAttributes(IHelpService helpSvc, GridEntry entry, bool addAsF1) { - if (entry == null) { - return; + + private void UpdateHelpAttributes(IHelpService helpSvc, GridEntry entry, bool addAsF1) + { + if (entry == null) + { + return; } - + UpdateHelpAttributes(helpSvc, entry.ParentGridEntry, false); string helpKeyword = entry.HelpKeyword; - if (helpKeyword != null) { - helpSvc.AddContextAttribute("Keyword", helpKeyword, addAsF1 ? HelpKeywordType.F1Keyword : HelpKeywordType.GeneralKeyword); + if (helpKeyword != null) + { + helpSvc.AddContextAttribute("Keyword", helpKeyword, addAsF1 ? HelpKeywordType.F1Keyword : HelpKeywordType.GeneralKeyword); } } - private void UpdateUIBasedOnFont(bool layoutRequired) { - if (IsHandleCreated && GetFlag(FlagNeedUpdateUIBasedOnFont)) { - - try { - if (listBox != null) { + private void UpdateUIBasedOnFont(bool layoutRequired) + { + if (IsHandleCreated && GetFlag(FlagNeedUpdateUIBasedOnFont)) + { + + try + { + if (listBox != null) + { DropDownListBox.ItemHeight = RowHeight + 2; } - - if (btnDropDown != null) { + + if (btnDropDown != null) + { var isScalingRequirementMet = DpiHelper.IsScalingRequirementMet; - if (isScalingRequirementMet) { + if (isScalingRequirementMet) + { btnDropDown.Size = new Size(SystemInformation.VerticalScrollBarArrowHeightForDpi(this.deviceDpi), RowHeight); } - else { + else + { btnDropDown.Size = new Size(SystemInformation.VerticalScrollBarArrowHeight, RowHeight); } - if (btnDialog != null) { + if (btnDialog != null) + { DialogButton.Size = DropDownButton.Size; - if (isScalingRequirementMet) { + if (isScalingRequirementMet) + { btnDialog.Image = CreateResizedBitmap("dotdotdot", DOTDOTDOT_ICONWIDTH, DOTDOTDOT_ICONHEIGHT); } } - if (isScalingRequirementMet) { + if (isScalingRequirementMet) + { btnDropDown.Image = CreateResizedBitmap("Arrow", DOWNARROW_ICONWIDTH, DOWNARROW_ICONHEIGHT); } } - if (layoutRequired) { + if (layoutRequired) + { LayoutWindow(true); } } - finally { + finally + { SetFlag(FlagNeedUpdateUIBasedOnFont, false); } } } - private bool UnfocusSelection() { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:UnfocusSelection()"); + private bool UnfocusSelection() + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:UnfocusSelection()"); GridEntry gridEntry = GetGridEntryFromRow(selectedRow); if (gridEntry == null) return true; bool commit = Commit(); - - if (commit && this.FocusInside) { + + if (commit && this.FocusInside) + { Focus(); } return commit; } - private void UpdateResetCommand(GridEntry gridEntry) { - if (totalProps > 0) { + private void UpdateResetCommand(GridEntry gridEntry) + { + if (totalProps > 0) + { IMenuCommandService mcs = (IMenuCommandService)GetService(typeof(IMenuCommandService)); - if (mcs != null) { + if (mcs != null) + { MenuCommand reset = mcs.FindCommand(PropertyGridCommands.Reset); - if (reset != null) { + if (reset != null) + { reset.Enabled = gridEntry == null ? false : gridEntry.CanResetPropertyValue(); } } @@ -5145,144 +6021,168 @@ private void UpdateResetCommand(GridEntry gridEntry) { // a mini version of process dialog key // for responding to WM_GETDLGCODE - internal bool WantsTab(bool forward) { - if (forward) { - if (this.Focused) { + internal bool WantsTab(bool forward) + { + if (forward) + { + if (this.Focused) + { // we want a tab if the grid has focus and // we have a button or an Edit if (DropDownButton.Visible || DialogButton.Visible || - Edit.Visible) { + Edit.Visible) + { return true; } } - else if (Edit.Focused && (DropDownButton.Visible || DialogButton.Visible)) { + else if (Edit.Focused && (DropDownButton.Visible || DialogButton.Visible)) + { // if the Edit has focus, and we have a button, we want the tab as well return true; } return ownerGrid.WantsTab(forward); } - else { - if (Edit.Focused || DropDownButton.Focused || DialogButton.Focused) { + else + { + if (Edit.Focused || DropDownButton.Focused || DialogButton.Focused) + { return true; } return ownerGrid.WantsTab(forward); } } - - private unsafe bool WmNotify(ref Message m) { - if (m.LParam != IntPtr.Zero) { + + private unsafe bool WmNotify(ref Message m) + { + if (m.LParam != IntPtr.Zero) + { NativeMethods.NMHDR* nmhdr = (NativeMethods.NMHDR*)m.LParam; - - if (nmhdr->hwndFrom == ToolTip.Handle) { - switch (nmhdr->code) { + + if (nmhdr->hwndFrom == ToolTip.Handle) + { + switch (nmhdr->code) + { case NativeMethods.TTN_POP: break; case NativeMethods.TTN_SHOW: // we want to move the tooltip over where our text would be Point mouseLoc = Cursor.Position; - + // convert to window coords mouseLoc = this.PointToClient(mouseLoc); - + // figure out where we are and apply the offset mouseLoc = FindPosition(mouseLoc.X, mouseLoc.Y); - - if (mouseLoc == InvalidPosition) { + + if (mouseLoc == InvalidPosition) + { break; } - + GridEntry curEntry = GetGridEntryFromRow(mouseLoc.Y); - - if (curEntry == null) { + + if (curEntry == null) + { break; } - + // get the proper rectangle Rectangle itemRect = GetRectangle(mouseLoc.Y, mouseLoc.X); - Point tipPt = Point.Empty; - + Point tipPt = Point.Empty; + // and if we need a tooltip, move the tooltip control to that point. - if (mouseLoc.X == ROWLABEL) { + if (mouseLoc.X == ROWLABEL) + { tipPt = curEntry.GetLabelToolTipLocation(mouseLoc.X - itemRect.X, mouseLoc.Y - itemRect.Y); } - else if (mouseLoc.X == ROWVALUE) { + else if (mouseLoc.X == ROWVALUE) + { tipPt = curEntry.ValueToolTipLocation; } - else { + else + { break; } - - if (tipPt != InvalidPoint) { + + if (tipPt != InvalidPoint) + { itemRect.Offset(tipPt); PositionTooltip(this, ToolTip, itemRect); m.Result = (IntPtr)1; return true; } - + break; } } } return false; } - - protected override void WndProc(ref Message m) { - switch (m.Msg) { - + + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { + case Interop.WindowMessages.WM_SYSCOLORCHANGE: Invalidate(); break; - // Microsoft -- if we get focus in the error - // state, make sure we push it back to the - // Edit or bad bad things can happen with - // our state... - // + // Microsoft -- if we get focus in the error + // state, make sure we push it back to the + // Edit or bad bad things can happen with + // our state... + // case Interop.WindowMessages.WM_SETFOCUS: - if (!GetInPropertySet() && Edit.Visible && (errorState != ERROR_NONE || !Commit())) { + if (!GetInPropertySet() && Edit.Visible && (errorState != ERROR_NONE || !Commit())) + { base.WndProc(ref m); Edit.Focus(); return; } break; - + case Interop.WindowMessages.WM_IME_STARTCOMPOSITION: Edit.Focus(); Edit.Clear(); - UnsafeNativeMethods.PostMessage(new HandleRef(Edit, Edit.Handle), Interop.WindowMessages.WM_IME_STARTCOMPOSITION, 0, 0); + UnsafeNativeMethods.PostMessage(new HandleRef(Edit, Edit.Handle), Interop.WindowMessages.WM_IME_STARTCOMPOSITION, 0, 0); return; - + case Interop.WindowMessages.WM_IME_COMPOSITION: Edit.Focus(); UnsafeNativeMethods.PostMessage(new HandleRef(Edit, Edit.Handle), Interop.WindowMessages.WM_IME_COMPOSITION, m.WParam, m.LParam); return; - - case Interop.WindowMessages.WM_GETDLGCODE: - int flags = NativeMethods.DLGC_WANTCHARS | NativeMethods.DLGC_WANTARROWS; - + case Interop.WindowMessages.WM_GETDLGCODE: - if (selectedGridEntry != null) { - if ((ModifierKeys & Keys.Shift) == 0) { + int flags = NativeMethods.DLGC_WANTCHARS | NativeMethods.DLGC_WANTARROWS; + + + if (selectedGridEntry != null) + { + if ((ModifierKeys & Keys.Shift) == 0) + { // if we're going backwards, we don't want the tab. // otherwise, we only want it if we have an edit... // - if (edit.Visible) { + if (edit.Visible) + { flags |= NativeMethods.DLGC_WANTTAB; } } } m.Result = (IntPtr)(flags); return; - - case Interop.WindowMessages.WM_MOUSEMOVE: - + + case Interop.WindowMessages.WM_MOUSEMOVE: + // check if it's the same position, of so eat the message - if (unchecked( (int) (long)m.LParam) == lastMouseMove) { + if (unchecked((int)(long)m.LParam) == lastMouseMove) + { return; } - lastMouseMove = unchecked( (int) (long)m.LParam); + lastMouseMove = unchecked((int)(long)m.LParam); break; case Interop.WindowMessages.WM_NOTIFY: @@ -5305,7 +6205,8 @@ protected override void WndProc(ref Message m) { /// /// /// - protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) { + protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) + { base.RescaleConstantsForDpi(deviceDpiOld, deviceDpiNew); RescaleConstants(); } @@ -5313,8 +6214,10 @@ protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNe /// /// Rescale constants on this object /// - private void RescaleConstants() { - if (DpiHelper.IsScalingRequirementMet) { + private void RescaleConstants() + { + if (DpiHelper.IsScalingRequirementMet) + { ClearCachedFontInfo(); cachedRowHeight = -1; paintWidth = LogicalToDeviceUnits(PAINT_WIDTH); @@ -5323,8 +6226,10 @@ private void RescaleConstants() { outlineSize = LogicalToDeviceUnits(OUTLINE_SIZE); maxListBoxHeight = LogicalToDeviceUnits(MAX_LISTBOX_HEIGHT); offset_2Units = LogicalToDeviceUnits(OFFSET_2PIXELS); - if (topLevelGridEntries != null) { - foreach (GridEntry t in topLevelGridEntries) { + if (topLevelGridEntries != null) + { + foreach (GridEntry t in topLevelGridEntries) + { ResetOutline(t); } } @@ -5334,102 +6239,118 @@ private void RescaleConstants() { /// /// private method to recursively reset outlinerect for grid entries ( both visible and invisible) /// - private void ResetOutline(GridEntry entry) { + private void ResetOutline(GridEntry entry) + { entry.OutlineRect = Rectangle.Empty; - if (entry.ChildCount > 0) { - foreach (GridEntry ent in entry.Children) { + if (entry.ChildCount > 0) + { + foreach (GridEntry ent in entry.Children) + { ResetOutline(ent); } } return; } - private class DropDownHolder : Form, IMouseHookClient { + private class DropDownHolder : Form, IMouseHookClient + { + + private Control currentControl = null; // the control that is hosted in the holder + private PropertyGridView gridView; // the owner gridview + private MouseHook mouseHook; // we use this to hook mouse downs, etc. to know when to close the dropdown. + + private LinkLabel createNewLink = null; - private Control currentControl = null; // the control that is hosted in the holder - private PropertyGridView gridView; // the owner gridview - private MouseHook mouseHook; // we use this to hook mouse downs, etc. to know when to close the dropdown. - - private LinkLabel createNewLink = null; - // all the resizing goo... // - private bool resizable = true; // true if we're showing the resize widget. - private bool resizing = false; // true if we're in the middle of a resize operation. - private bool resizeUp = false; // true if the dropdown is above the grid row, which means the resize widget is at the top. - private Point dragStart = Point.Empty; // the point at which the drag started to compute the delta - private Rectangle dragBaseRect = Rectangle.Empty; // the original bounds of our control. - private int currentMoveType = MoveTypeNone; // what type of move are we processing? left, bottom, or both? - - private readonly static int ResizeBarSize; // the thickness of the resize bar - private readonly static int ResizeBorderSize; // the thickness of the 2-way resize area along the outer edge of the resize bar - private readonly static int ResizeGripSize; // the size of the 4-way resize grip at outermost corner of the resize bar - private readonly static Size MinDropDownSize; // the minimum size for the control. - private Bitmap sizeGripGlyph; // our cached size grip glyph. Control paint only does right bottom glyphs, so we cache a mirrored one. See GetSizeGripGlyph - - private const int DropDownHolderBorder = 1; - private const int MoveTypeNone = 0x0; - private const int MoveTypeBottom = 0x1; - private const int MoveTypeLeft = 0x2; - private const int MoveTypeTop = 0x4; - - static DropDownHolder() { + private bool resizable = true; // true if we're showing the resize widget. + private bool resizing = false; // true if we're in the middle of a resize operation. + private bool resizeUp = false; // true if the dropdown is above the grid row, which means the resize widget is at the top. + private Point dragStart = Point.Empty; // the point at which the drag started to compute the delta + private Rectangle dragBaseRect = Rectangle.Empty; // the original bounds of our control. + private int currentMoveType = MoveTypeNone; // what type of move are we processing? left, bottom, or both? + + private readonly static int ResizeBarSize; // the thickness of the resize bar + private readonly static int ResizeBorderSize; // the thickness of the 2-way resize area along the outer edge of the resize bar + private readonly static int ResizeGripSize; // the size of the 4-way resize grip at outermost corner of the resize bar + private readonly static Size MinDropDownSize; // the minimum size for the control. + private Bitmap sizeGripGlyph; // our cached size grip glyph. Control paint only does right bottom glyphs, so we cache a mirrored one. See GetSizeGripGlyph + + private const int DropDownHolderBorder = 1; + private const int MoveTypeNone = 0x0; + private const int MoveTypeBottom = 0x1; + private const int MoveTypeLeft = 0x2; + private const int MoveTypeTop = 0x4; + + static DropDownHolder() + { MinDropDownSize = new Size(SystemInformation.VerticalScrollBarWidth * 4, SystemInformation.HorizontalScrollBarHeight * 4); ResizeGripSize = SystemInformation.HorizontalScrollBarHeight; ResizeBarSize = ResizeGripSize + 1; ResizeBorderSize = ResizeBarSize / 2; } - + [ SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // DropDownHolder's caption is not visible. // So we don't have to localize its text. ] internal DropDownHolder(PropertyGridView psheet) - : base() { - this.ShowInTaskbar = false; - this.ControlBox = false; - this.MinimizeBox = false; - this.MaximizeBox = false; - this.Text = string.Empty; - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; - this.AutoScaleMode = AutoScaleMode.None; // children may scale, but we won't interfere. - mouseHook = new MouseHook(this, this, psheet); - Visible = false; - gridView = psheet; - this.BackColor = gridView.BackColor; - } - - protected override CreateParams CreateParams { - get { + : base() + { + this.ShowInTaskbar = false; + this.ControlBox = false; + this.MinimizeBox = false; + this.MaximizeBox = false; + this.Text = string.Empty; + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; + this.AutoScaleMode = AutoScaleMode.None; // children may scale, but we won't interfere. + mouseHook = new MouseHook(this, this, psheet); + Visible = false; + gridView = psheet; + this.BackColor = gridView.BackColor; + } + + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ExStyle |= NativeMethods.WS_EX_TOOLWINDOW; cp.Style |= NativeMethods.WS_POPUP | NativeMethods.WS_BORDER; - if (OSFeature.IsPresent(SystemParameter.DropShadow)) { + if (OSFeature.IsPresent(SystemParameter.DropShadow)) + { cp.ClassStyle |= NativeMethods.CS_DROPSHADOW; } - if (gridView != null) { + if (gridView != null) + { cp.Parent = gridView.ParentInternal.Handle; } return cp; } } - private LinkLabel CreateNewLink { - get { - if (this.createNewLink == null) { + private LinkLabel CreateNewLink + { + get + { + if (this.createNewLink == null) + { this.createNewLink = new LinkLabel(); this.createNewLink.LinkClicked += new LinkLabelLinkClickedEventHandler(OnNewLinkClicked); } return createNewLink; } } - - public virtual bool HookMouseDown{ - get{ + + public virtual bool HookMouseDown + { + get + { return mouseHook.HookMouseDown; } - set{ + set + { mouseHook.HookMouseDown = value; } } @@ -5439,58 +6360,71 @@ public virtual bool HookMouseDown{ /// row for the drop down, so it appears above the row. In this case, we make the resize /// grip appear at the top left. /// - public bool ResizeUp { - - set { - if (resizeUp != value) { + public bool ResizeUp + { + + set + { + if (resizeUp != value) + { // clear the glyph so we regenerate it. // sizeGripGlyph = null; resizeUp = value; - if (resizable) { + if (resizable) + { this.DockPadding.Bottom = 0; this.DockPadding.Top = 0; - if (value) { + if (value) + { this.DockPadding.Top = ResizeBarSize; } - else { + else + { this.DockPadding.Bottom = ResizeBarSize; } } } } } - - - protected override void DestroyHandle() { - mouseHook.HookMouseDown = false; - base.DestroyHandle(); + + + protected override void DestroyHandle() + { + mouseHook.HookMouseDown = false; + base.DestroyHandle(); } - protected override void Dispose(bool disposing) { + protected override void Dispose(bool disposing) + { - if (disposing && createNewLink != null) { + if (disposing && createNewLink != null) + { createNewLink.Dispose(); createNewLink = null; } base.Dispose(disposing); } - - public void DoModalLoop() { + + public void DoModalLoop() + { // Push a modal loop. This seems expensive, but I think it is a // better user model than returning from DropDownControl immediately. // - while (this.Visible) { + while (this.Visible) + { Application.DoEventsModal(); UnsafeNativeMethods.MsgWaitForMultipleObjectsEx(0, IntPtr.Zero, 250, NativeMethods.QS_ALLINPUT, NativeMethods.MWMO_INPUTAVAILABLE); } } - public virtual Control Component { - get { + public virtual Control Component + { + get + { return currentControl; } } @@ -5501,9 +6435,11 @@ public virtual Control Component { /// the type of DropDown UIType Editor. /// /// - private InstanceCreationEditor GetInstanceCreationEditor(PropertyDescriptorGridEntry entry) { + private InstanceCreationEditor GetInstanceCreationEditor(PropertyDescriptorGridEntry entry) + { - if (entry == null) { + if (entry == null) + { return null; } @@ -5512,15 +6448,18 @@ private InstanceCreationEditor GetInstanceCreationEditor(PropertyDescriptorGridE // check the property type itself. this is the default path. // PropertyDescriptor pd = entry.PropertyDescriptor; - if (pd != null) { + if (pd != null) + { editor = pd.GetEditor(typeof(InstanceCreationEditor)) as InstanceCreationEditor; } // now check if there is a dropdown UI type editor. If so, use that. // - if (editor == null) { + if (editor == null) + { UITypeEditor ute = entry.UITypeEditor; - if (ute != null && ute.GetEditStyle() == UITypeEditorEditStyle.DropDown) { + if (ute != null && ute.GetEditStyle() == UITypeEditorEditStyle.DropDown) + { editor = (InstanceCreationEditor)TypeDescriptor.GetEditor(ute, typeof(InstanceCreationEditor)); } } @@ -5532,23 +6471,25 @@ private InstanceCreationEditor GetInstanceCreationEditor(PropertyDescriptorGridE /// so we do some GDI+ magic to take that glyph and mirror it. That way we can still share the code (in case it changes for theming, etc), /// not have any special cases, and possibly solve world hunger. /// - - - private Bitmap GetSizeGripGlyph(Graphics g) { - if (this.sizeGripGlyph != null) { + + + private Bitmap GetSizeGripGlyph(Graphics g) + { + if (this.sizeGripGlyph != null) + { return sizeGripGlyph; } // create our drawing surface based on the current graphics context. // - sizeGripGlyph = new Bitmap(ResizeGripSize, ResizeGripSize, g); - - using (Graphics glyphGraphics = Graphics.FromImage(sizeGripGlyph)) + sizeGripGlyph = new Bitmap(ResizeGripSize, ResizeGripSize, g); + + using (Graphics glyphGraphics = Graphics.FromImage(sizeGripGlyph)) { // mirror the image around the x-axis to get a gripper handle that works // for the lower left. System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix(); - + // basically, mirroring is just scaling by -1 on the X-axis. So any point that's like (10, 10) goes to (-10, 10). // that mirrors it, but also moves everything to the negative axis, so we just bump the whole thing over by it's width. // @@ -5556,28 +6497,31 @@ private Bitmap GetSizeGripGlyph(Graphics g) { // // resizeUp causes the image to also be mirrored vertically so the grip can be used as a top-left grip instead of bottom-left. // - m.Translate(ResizeGripSize + 1, (resizeUp ? ResizeGripSize + 1: 0)); + m.Translate(ResizeGripSize + 1, (resizeUp ? ResizeGripSize + 1 : 0)); m.Scale(-1, (resizeUp ? -1 : 1)); glyphGraphics.Transform = m; ControlPaint.DrawSizeGrip(glyphGraphics, BackColor, 0, 0, ResizeGripSize, ResizeGripSize); glyphGraphics.ResetTransform(); - + } sizeGripGlyph.MakeTransparent(BackColor); return sizeGripGlyph; } - public virtual bool GetUsed() { - return(currentControl != null); + public virtual bool GetUsed() + { + return (currentControl != null); } - - public virtual void FocusComponent() { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "DropDownHolder:FocusComponent()"); - if (currentControl != null && Visible) { + + public virtual void FocusComponent() + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "DropDownHolder:FocusComponent()"); + if (currentControl != null && Visible) + { currentControl.Focus(); } } - + /// /// General purpose method, based on Control.Contains()... /// @@ -5586,37 +6530,47 @@ public virtual void FocusComponent() { /// and 'owned' windows such as modal dialogs. Using window handles rather /// than Control objects allows it to catch un-managed windows as well. /// - private bool OwnsWindow(IntPtr hWnd) { - while (hWnd != IntPtr.Zero) { + private bool OwnsWindow(IntPtr hWnd) + { + while (hWnd != IntPtr.Zero) + { hWnd = UnsafeNativeMethods.GetWindowLong(new HandleRef(null, hWnd), NativeMethods.GWL_HWNDPARENT); - if (hWnd == IntPtr.Zero) { + if (hWnd == IntPtr.Zero) + { return false; } - if (hWnd == this.Handle) { + if (hWnd == this.Handle) + { return true; } } return false; } - public bool OnClickHooked() { - gridView.CloseDropDownInternal(false); - return false; + public bool OnClickHooked() + { + gridView.CloseDropDownInternal(false); + return false; } - - private void OnCurrentControlResize(object o, EventArgs e) { - if (currentControl != null && !resizing) { + + private void OnCurrentControlResize(object o, EventArgs e) + { + if (currentControl != null && !resizing) + { int oldWidth = this.Width; Size newSize = new Size(2 * DropDownHolderBorder + currentControl.Width, 2 * DropDownHolderBorder + currentControl.Height); - if (resizable) { + if (resizable) + { newSize.Height += ResizeBarSize; } - try { + try + { resizing = true; this.SuspendLayout(); this.Size = newSize; } - finally { + finally + { resizing = false; this.ResumeLayout(false); } @@ -5625,34 +6579,42 @@ private void OnCurrentControlResize(object o, EventArgs e) { } - protected override void OnLayout(LayoutEventArgs levent) { - try { + protected override void OnLayout(LayoutEventArgs levent) + { + try + { resizing = true; base.OnLayout(levent); } - finally { + finally + { resizing = false; } - + } - private void OnNewLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { + private void OnNewLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) + { InstanceCreationEditor ice = e.Link.LinkData as InstanceCreationEditor; Debug.Assert(ice != null, "How do we have a link without the InstanceCreationEditor?"); - if (ice != null) { + if (ice != null) + { Type createType = gridView.SelectedGridEntry.PropertyType; - if (createType != null) { + if (createType != null) + { gridView.CloseDropDown(); - + object newValue = ice.CreateInstance(gridView.SelectedGridEntry, createType); - if (newValue != null) { + if (newValue != null) + { // make sure we got what we asked for. // - if (!createType.IsInstanceOfType(newValue)) { + if (!createType.IsInstanceOfType(newValue)) + { throw new InvalidCastException(string.Format(SR.PropertyGridViewEditorCreatedInvalidObject, createType)); } @@ -5661,64 +6623,68 @@ private void OnNewLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { } } } - + /// /// Just figure out what kind of sizing we would do at a given drag location. /// - private int MoveTypeFromPoint(int x, int y) + private int MoveTypeFromPoint(int x, int y) { Rectangle bGripRect = new Rectangle(0, Height - ResizeGripSize, ResizeGripSize, ResizeGripSize); Rectangle tGripRect = new Rectangle(0, 0, ResizeGripSize, ResizeGripSize); - + if (!resizeUp && bGripRect.Contains(x, y)) { return MoveTypeLeft | MoveTypeBottom; } - else if (resizeUp && tGripRect.Contains(x, y)) { + else if (resizeUp && tGripRect.Contains(x, y)) + { return MoveTypeLeft | MoveTypeTop; } - else if (!resizeUp && Math.Abs(Height - y) < ResizeBorderSize) + else if (!resizeUp && Math.Abs(Height - y) < ResizeBorderSize) { - return MoveTypeBottom; + return MoveTypeBottom; } - else if (resizeUp && Math.Abs(y) < ResizeBorderSize) + else if (resizeUp && Math.Abs(y) < ResizeBorderSize) { - return MoveTypeTop; + return MoveTypeTop; } return MoveTypeNone; } - + /// /// Decide if we're going to be sizing at the given point, and if so, Capture and safe our current state. /// protected override void OnMouseDown(MouseEventArgs e) { - if (e.Button == MouseButtons.Left) { + if (e.Button == MouseButtons.Left) + { this.currentMoveType = MoveTypeFromPoint(e.X, e.Y); - if (this.currentMoveType != MoveTypeNone) + if (this.currentMoveType != MoveTypeNone) { dragStart = PointToScreen(new Point(e.X, e.Y)); dragBaseRect = Bounds; Capture = true; } - else { + else + { gridView.CloseDropDown(); } } - base.OnMouseDown (e); + base.OnMouseDown(e); } - + /// /// Either set the cursor or do a move, depending on what our currentMoveType is/ /// protected override void OnMouseMove(MouseEventArgs e) - { + { // not moving so just set the cursor. // - if (this.currentMoveType == MoveTypeNone) + if (this.currentMoveType == MoveTypeNone) { int cursorMoveType = MoveTypeFromPoint(e.X, e.Y); - switch (cursorMoveType) { + switch (cursorMoveType) + { case (MoveTypeLeft | MoveTypeBottom): Cursor = Cursors.SizeNESW; break; @@ -5734,75 +6700,79 @@ protected override void OnMouseMove(MouseEventArgs e) break; } } - else + else { Point dragPoint = PointToScreen(new Point(e.X, e.Y)); Rectangle newBounds = Bounds; - + // we're in a move operation, so do the resize. // - if ((currentMoveType & MoveTypeBottom) == MoveTypeBottom) + if ((currentMoveType & MoveTypeBottom) == MoveTypeBottom) { newBounds.Height = Math.Max(MinDropDownSize.Height, dragBaseRect.Height + (dragPoint.Y - dragStart.Y)); } - + // for left and top moves, we actually have to resize and move the form simultaneously. // do to that, we compute the xdelta, and apply that to the base rectangle if it's not going to // make the form smaller than the minimum. // - if ((currentMoveType & MoveTypeTop) == MoveTypeTop) + if ((currentMoveType & MoveTypeTop) == MoveTypeTop) { - int delta = dragPoint.Y - dragStart.Y; - - if ((dragBaseRect.Height - delta) > MinDropDownSize.Height) + int delta = dragPoint.Y - dragStart.Y; + + if ((dragBaseRect.Height - delta) > MinDropDownSize.Height) { - newBounds.Y = dragBaseRect.Top + delta; + newBounds.Y = dragBaseRect.Top + delta; newBounds.Height = dragBaseRect.Height - delta; } } - - if ((currentMoveType & MoveTypeLeft) == MoveTypeLeft) + + if ((currentMoveType & MoveTypeLeft) == MoveTypeLeft) { - int delta = dragPoint.X - dragStart.X; - - if ((dragBaseRect.Width - delta) > MinDropDownSize.Width) + int delta = dragPoint.X - dragStart.X; + + if ((dragBaseRect.Width - delta) > MinDropDownSize.Width) { - newBounds.X = dragBaseRect.Left + delta; + newBounds.X = dragBaseRect.Left + delta; newBounds.Width = dragBaseRect.Width - delta; } } - - if (newBounds != Bounds) { - try { + + if (newBounds != Bounds) + { + try + { resizing = true; this.Bounds = newBounds; } - finally { + finally + { resizing = false; } } - + // Redraw! // Invalidate(); } - base.OnMouseMove (e); + base.OnMouseMove(e); } - + protected override void OnMouseLeave(EventArgs e) { // just clear the cursor back to the default. // Cursor = null; - base.OnMouseLeave (e); + base.OnMouseLeave(e); } - + protected override void OnMouseUp(MouseEventArgs e) { - base.OnMouseUp (e); - - if (e.Button == MouseButtons.Left) { - + base.OnMouseUp(e); + + if (e.Button == MouseButtons.Left) + { + // reset the world. // this.currentMoveType = MoveTypeNone; @@ -5811,14 +6781,15 @@ protected override void OnMouseUp(MouseEventArgs e) this.Capture = false; } } - + /// /// Just paint and draw our glyph. /// - protected override void OnPaint(PaintEventArgs pe) + protected override void OnPaint(PaintEventArgs pe) { base.OnPaint(pe); - if (resizable) { + if (resizable) + { // Draw the grip Rectangle lRect = new Rectangle(0, resizeUp ? 0 : Height - ResizeGripSize, ResizeGripSize, ResizeGripSize); pe.Graphics.DrawImage(GetSizeGripGlyph(pe.Graphics), lRect); @@ -5831,10 +6802,13 @@ protected override void OnPaint(PaintEventArgs pe) pen.Dispose(); } } - - protected override bool ProcessDialogKey(Keys keyData) { - if ((keyData & (Keys.Shift | Keys.Control | Keys.Alt)) == 0) { - switch (keyData & Keys.KeyCode) { + + protected override bool ProcessDialogKey(Keys keyData) + { + if ((keyData & (Keys.Shift | Keys.Control | Keys.Alt)) == 0) + { + switch (keyData & Keys.KeyCode) + { case Keys.Escape: gridView.OnEscape(this); return true; @@ -5844,8 +6818,9 @@ protected override bool ProcessDialogKey(Keys keyData) { case Keys.Return: // make sure the return gets forwarded to the control that // is being displayed - if (gridView.UnfocusSelection() && gridView.SelectedGridEntry != null) { - gridView.SelectedGridEntry.OnValueReturnKey(); + if (gridView.UnfocusSelection() && gridView.SelectedGridEntry != null) + { + gridView.SelectedGridEntry.OnValueReturnKey(); } return true; } @@ -5854,18 +6829,20 @@ protected override bool ProcessDialogKey(Keys keyData) { return base.ProcessDialogKey(keyData); } - public void SetComponent(Control ctl, bool resizable) { + public void SetComponent(Control ctl, bool resizable) + { this.resizable = resizable; this.Font = gridView.Font; - + // check to see if we're going to be adding an InstanceCreationEditor // InstanceCreationEditor editor = (ctl == null ? null : GetInstanceCreationEditor(gridView.SelectedGridEntry as PropertyDescriptorGridEntry)); // clear any existing control we have // - if (currentControl != null) { + if (currentControl != null) + { currentControl.Resize -= new EventHandler(this.OnCurrentControlResize); Controls.Remove(currentControl); currentControl = null; @@ -5873,73 +6850,83 @@ public void SetComponent(Control ctl, bool resizable) { // remove the InstanceCreationEditor link // - if (createNewLink != null && createNewLink.Parent == this) { + if (createNewLink != null && createNewLink.Parent == this) + { this.Controls.Remove(createNewLink); } // now set up the new control, top to bottom // - if (ctl != null) { + if (ctl != null) + { currentControl = ctl; - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "DropDownHolder:SetComponent(" + (ctl.GetType().Name) + ")"); - + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "DropDownHolder:SetComponent(" + (ctl.GetType().Name) + ")"); + this.DockPadding.All = 0; // first handle the control. If it's a listbox, make sure it's got some height // to it. // - if (currentControl is GridViewListBox) { + if (currentControl is GridViewListBox) + { ListBox lb = (ListBox)currentControl; - if (lb.Items.Count == 0) { + if (lb.Items.Count == 0) + { lb.Height = Math.Max(lb.Height, lb.ItemHeight); } } // Parent the control now. That way it can inherit our // font and scale itself if it wants to. - try { + try + { SuspendLayout(); Controls.Add(ctl); Size sz = new Size(2 * DropDownHolderBorder + ctl.Width, 2 * DropDownHolderBorder + ctl.Height); - + // now check for an editor, and show the link if there is one. // - if (editor != null) { - + if (editor != null) + { + // set up the link. // CreateNewLink.Text = editor.Text; CreateNewLink.Links.Clear(); CreateNewLink.Links.Add(0, editor.Text.Length, editor); - + // size it as close to the size of the text as possible. // int linkHeight = CreateNewLink.Height; - using (Graphics g = gridView.CreateGraphics()) { + using (Graphics g = gridView.CreateGraphics()) + { SizeF sizef = PropertyGrid.MeasureTextHelper.MeasureText(this.gridView.ownerGrid, g, editor.Text, gridView.GetBaseFont()); linkHeight = (int)sizef.Height; } - + CreateNewLink.Height = linkHeight + DropDownHolderBorder; - + // add the total height plus some border sz.Height += (linkHeight + (DropDownHolderBorder * 2)); } - + // finally, if we're resizable, add the space for the widget. // - if (resizable) { + if (resizable) + { sz.Height += ResizeBarSize; - + // we use dockpadding to save space to draw the widget. // - if (resizeUp) { + if (resizeUp) + { this.DockPadding.Top = ResizeBarSize; } - else { + else + { this.DockPadding.Bottom = ResizeBarSize; } } @@ -5950,12 +6937,14 @@ public void SetComponent(Control ctl, bool resizable) { ctl.Dock = DockStyle.Fill; ctl.Visible = true; - if (editor != null) { + if (editor != null) + { CreateNewLink.Dock = DockStyle.Bottom; Controls.Add(CreateNewLink); } } - finally { + finally + { ResumeLayout(true); } @@ -5966,13 +6955,16 @@ public void SetComponent(Control ctl, bool resizable) { Enabled = currentControl != null; } - protected override void WndProc(ref Message m) { + protected override void WndProc(ref Message m) + { - if (m.Msg == Interop.WindowMessages.WM_ACTIVATE) { + if (m.Msg == Interop.WindowMessages.WM_ACTIVATE) + { SetState(STATE_MODAL, true); Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "DropDownHolder:WM_ACTIVATE()"); IntPtr activatedWindow = (IntPtr)m.LParam; - if (Visible && NativeMethods.Util.LOWORD(m.WParam) == NativeMethods.WA_INACTIVE && !this.OwnsWindow(activatedWindow)) { + if (Visible && NativeMethods.Util.LOWORD(m.WParam) == NativeMethods.WA_INACTIVE && !this.OwnsWindow(activatedWindow)) + { gridView.CloseDropDownInternal(false); return; } @@ -5981,15 +6973,18 @@ protected override void WndProc(ref Message m) { //Active = ((int)m.WParam & 0x0000FFFF) != NativeMethods.WA_INACTIVE; //return; } - else if (m.Msg == Interop.WindowMessages.WM_CLOSE) { + else if (m.Msg == Interop.WindowMessages.WM_CLOSE) + { // don't let an ALT-F4 get you down // - if (Visible) { + if (Visible) + { gridView.CloseDropDown(); } return; } - else if (m.Msg == Interop.WindowMessages.WM_DPICHANGED) { + else if (m.Msg == Interop.WindowMessages.WM_DPICHANGED) + { // Dropdownholder in PropertyGridView is already scaled based on parent font and other properties that were already set for new DPI // This case is to avoid rescaling(double scaling) of this form m.Result = IntPtr.Zero; @@ -6000,19 +6995,23 @@ protected override void WndProc(ref Message m) { } } - private class GridViewListBox : ListBox { + private class GridViewListBox : ListBox + { internal bool fInSetSelectedIndex = false; private PropertyGridView _owningPropertyGridView; - public GridViewListBox(PropertyGridView gridView) { + public GridViewListBox(PropertyGridView gridView) + { base.IntegralHeight = false; _owningPropertyGridView = gridView; base.BackColor = gridView.BackColor; } - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.Style &= ~NativeMethods.WS_BORDER; cp.ExStyle &= ~NativeMethods.WS_EX_CLIENTEDGE; @@ -6020,11 +7019,13 @@ protected override CreateParams CreateParams { } } - /// + /// /// Gets the owning PropertyGridView. /// - internal PropertyGridView OwningPropertyGridView { - get { + internal PropertyGridView OwningPropertyGridView + { + get + { return _owningPropertyGridView; } } @@ -6039,21 +7040,25 @@ internal PropertyGridView OwningPropertyGridView { /// Constructs the new instance of the accessibility object for this control. /// /// The accessibility object instance. - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new GridViewListBoxAccessibleObject(this); } - public virtual bool InSetSelectedIndex() { + public virtual bool InSetSelectedIndex() + { return fInSetSelectedIndex; } - protected override void OnSelectedIndexChanged(EventArgs e) { + protected override void OnSelectedIndexChanged(EventArgs e) + { fInSetSelectedIndex = true; base.OnSelectedIndexChanged(e); fInSetSelectedIndex = false; var gridViewListBoxAccessibleObject = AccessibilityObject as GridViewListBoxAccessibleObject; - if (gridViewListBoxAccessibleObject != null) { + if (gridViewListBoxAccessibleObject != null) + { gridViewListBoxAccessibleObject.SetListBoxItemFocus(); } } @@ -6061,12 +7066,14 @@ protected override void OnSelectedIndexChanged(EventArgs e) { } [ComVisible(true)] - private class GridViewListBoxItemAccessibleObject : AccessibleObject { + private class GridViewListBoxItemAccessibleObject : AccessibleObject + { private GridViewListBox _owningGridViewListBox; private object _owningItem; - public GridViewListBoxItemAccessibleObject(GridViewListBox owningGridViewListBox, object owningItem) { + public GridViewListBoxItemAccessibleObject(GridViewListBox owningGridViewListBox, object owningItem) + { _owningGridViewListBox = owningGridViewListBox; _owningItem = owningItem; @@ -6076,8 +7083,10 @@ public GridViewListBoxItemAccessibleObject(GridViewListBox owningGridViewListBox /// /// Gets the DropDown button bounds. /// - public override Rectangle Bounds { - get { + public override Rectangle Bounds + { + get + { int left; int top; int width; @@ -6091,24 +7100,30 @@ public override Rectangle Bounds { /// /// Gets the DropDown button default action. /// - public override string DefaultAction { - get { + public override string DefaultAction + { + get + { var systemIAccessible = GetSystemIAccessibleInternal(); return systemIAccessible.accDefaultAction[GetChildId()]; } } - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - switch (direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { + switch (direction) + { case UnsafeNativeMethods.NavigateDirection.Parent: return _owningGridViewListBox.AccessibilityObject; case UnsafeNativeMethods.NavigateDirection.NextSibling: int currentIndex = GetCurrentIndex(); var gridViewListBoxAccessibleObject = _owningGridViewListBox.AccessibilityObject as GridViewListBoxAccessibleObject; - if (gridViewListBoxAccessibleObject != null) { + if (gridViewListBoxAccessibleObject != null) + { int itemsCount = gridViewListBoxAccessibleObject.GetChildFragmentCount(); int nextItemIndex = currentIndex + 1; - if (itemsCount > nextItemIndex) { + if (itemsCount > nextItemIndex) + { return gridViewListBoxAccessibleObject.GetChildFragment(nextItemIndex); } } @@ -6116,36 +7131,44 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga case UnsafeNativeMethods.NavigateDirection.PreviousSibling: currentIndex = GetCurrentIndex(); gridViewListBoxAccessibleObject = _owningGridViewListBox.AccessibilityObject as GridViewListBoxAccessibleObject; - if (gridViewListBoxAccessibleObject != null) { + if (gridViewListBoxAccessibleObject != null) + { var itemsCount = gridViewListBoxAccessibleObject.GetChildFragmentCount(); int previousItemIndex = currentIndex - 1; - if (previousItemIndex >= 0) { + if (previousItemIndex >= 0) + { return gridViewListBoxAccessibleObject.GetChildFragment(previousItemIndex); } } - + break; } return base.FragmentNavigate(direction); } - internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot { - get { + internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot + { + get + { return _owningGridViewListBox.AccessibilityObject; } } - private int GetCurrentIndex() { + private int GetCurrentIndex() + { return _owningGridViewListBox.Items.IndexOf(_owningItem); } - - internal override int GetChildId() { + + internal override int GetChildId() + { return GetCurrentIndex() + 1; // Index is zero-based, Child ID is 1-based. } - internal override object GetPropertyValue(int propertyID) { - switch (propertyID) { + internal override object GetPropertyValue(int propertyID) + { + switch (propertyID) + { case NativeMethods.UIA_RuntimeIdPropertyId: return RuntimeId; case NativeMethods.UIA_BoundingRectanglePropertyId: @@ -6176,8 +7199,10 @@ internal override object GetPropertyValue(int propertyID) { /// /// Gets the help text. /// - public override string Help { - get { + public override string Help + { + get + { var systemIAccessible = GetSystemIAccessibleInternal(); return systemIAccessible.accHelp[GetChildId()]; } @@ -6186,8 +7211,10 @@ public override string Help { /// /// Gets the keyboard shortcut. /// - public override string KeyboardShortcut { - get { + public override string KeyboardShortcut + { + get + { var systemIAccessible = GetSystemIAccessibleInternal(); return systemIAccessible.get_accKeyboardShortcut(GetChildId()); } @@ -6198,28 +7225,34 @@ public override string KeyboardShortcut { /// /// The pattern ID. /// True if specified - internal override bool IsPatternSupported(int patternId) { + internal override bool IsPatternSupported(int patternId) + { if (patternId == NativeMethods.UIA_LegacyIAccessiblePatternId || - patternId == NativeMethods.UIA_InvokePatternId) { + patternId == NativeMethods.UIA_InvokePatternId) + { return true; } return base.IsPatternSupported(patternId); } - + /// /// Gets or sets the accessible name. /// - public override string Name { - get { - if (_owningGridViewListBox != null) { + public override string Name + { + get + { + if (_owningGridViewListBox != null) + { return _owningItem.ToString(); } return base.Name; } - set { + set + { base.Name = value; } } @@ -6227,18 +7260,22 @@ public override string Name { /// /// Gets the accessible role. /// - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { var systemIAccessible = GetSystemIAccessibleInternal(); return (AccessibleRole)systemIAccessible.get_accRole(GetChildId()); } } - + /// /// Gets the runtime ID. /// - internal override int[] RuntimeId { - get { + internal override int[] RuntimeId + { + get + { var runtimeId = new int[3]; runtimeId[0] = RuntimeIDFirstItem; runtimeId[1] = (int)(long)_owningGridViewListBox.Handle; @@ -6251,31 +7288,39 @@ internal override int[] RuntimeId { /// /// Gets the accessible state. /// - public override AccessibleStates State { - get { + public override AccessibleStates State + { + get + { var systemIAccessible = GetSystemIAccessibleInternal(); return (AccessibleStates)systemIAccessible.get_accState(GetChildId()); } } - internal override void SetFocus() { + internal override void SetFocus() + { RaiseAutomationEvent(NativeMethods.UIA_AutomationFocusChangedEventId); base.SetFocus(); } } - private class GridViewListBoxItemAccessibleObjectCollection : Hashtable { + private class GridViewListBoxItemAccessibleObjectCollection : Hashtable + { private GridViewListBox _owningGridViewListBox; - public GridViewListBoxItemAccessibleObjectCollection(GridViewListBox owningGridViewListBox) { + public GridViewListBoxItemAccessibleObjectCollection(GridViewListBox owningGridViewListBox) + { _owningGridViewListBox = owningGridViewListBox; } - public override object this[object key] { - get { - if (!ContainsKey(key)) { + public override object this[object key] + { + get + { + if (!ContainsKey(key)) + { var itemAccessibleObject = new GridViewListBoxItemAccessibleObject(_owningGridViewListBox, key); base[key] = itemAccessibleObject; } @@ -6283,7 +7328,8 @@ public override object this[object key] { return base[key]; } - set { + set + { base[key] = value; } } @@ -6293,7 +7339,8 @@ public override object this[object key] { /// Represents the PropertyGridView ListBox accessibility object. /// [ComVisible(true)] - private class GridViewListBoxAccessibleObject : ControlAccessibleObject { + private class GridViewListBoxAccessibleObject : ControlAccessibleObject + { private GridViewListBox _owningGridViewListBox; private PropertyGridView _owningPropertyGridView; @@ -6303,7 +7350,8 @@ private class GridViewListBoxAccessibleObject : ControlAccessibleObject { /// Constructs the new instance of GridViewListBoxAccessibleObject. /// /// The owning GridViewListBox. - public GridViewListBoxAccessibleObject(GridViewListBox owningGridViewListBox) : base(owningGridViewListBox) { + public GridViewListBoxAccessibleObject(GridViewListBox owningGridViewListBox) : base(owningGridViewListBox) + { _owningGridViewListBox = owningGridViewListBox; _owningPropertyGridView = owningGridViewListBox.OwningPropertyGridView; _itemAccessibleObjects = new GridViewListBoxItemAccessibleObjectCollection(owningGridViewListBox); @@ -6314,20 +7362,26 @@ public GridViewListBoxAccessibleObject(GridViewListBox owningGridViewListBox) : /// /// Indicates the direction in which to navigate. /// Returns the element in the specified direction. - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - if (direction == UnsafeNativeMethods.NavigateDirection.Parent) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { + if (direction == UnsafeNativeMethods.NavigateDirection.Parent) + { return _owningPropertyGridView.SelectedGridEntry.AccessibilityObject; } - else if (direction == UnsafeNativeMethods.NavigateDirection.FirstChild) { + else if (direction == UnsafeNativeMethods.NavigateDirection.FirstChild) + { return GetChildFragment(0); } - else if (direction == UnsafeNativeMethods.NavigateDirection.LastChild) { + else if (direction == UnsafeNativeMethods.NavigateDirection.LastChild) + { var childFragmentCount = GetChildFragmentCount(); - if (childFragmentCount > 0) { + if (childFragmentCount > 0) + { return GetChildFragment(childFragmentCount - 1); } } - else if (direction == UnsafeNativeMethods.NavigateDirection.NextSibling) { + else if (direction == UnsafeNativeMethods.NavigateDirection.NextSibling) + { return _owningPropertyGridView.Edit.AccessibilityObject; } @@ -6337,14 +7391,18 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga /// /// Return the element that is the root node of this fragment of UI. /// - internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot { - get { + internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot + { + get + { return _owningPropertyGridView.AccessibilityObject; } } - public AccessibleObject GetChildFragment(int index) { - if (index < 0 || index >= _owningGridViewListBox.Items.Count) { + public AccessibleObject GetChildFragment(int index) + { + if (index < 0 || index >= _owningGridViewListBox.Items.Count) + { return null; } @@ -6353,7 +7411,8 @@ public AccessibleObject GetChildFragment(int index) { } - public int GetChildFragmentCount() { + public int GetChildFragmentCount() + { return _owningGridViewListBox.Items.Count; } @@ -6362,55 +7421,67 @@ public int GetChildFragmentCount() { /// /// Identifier indicating the property to return /// Returns a ValInfo indicating whether the element supports this property, or has no value for it. - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_ControlTypePropertyId) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_ControlTypePropertyId) + { return NativeMethods.UIA_ListControlTypeId; - } else if (propertyID == NativeMethods.UIA_NamePropertyId) { + } + else if (propertyID == NativeMethods.UIA_NamePropertyId) + { return Name; } return base.GetPropertyValue(propertyID); } - internal override void SetFocus() { + internal override void SetFocus() + { RaiseAutomationEvent(NativeMethods.UIA_AutomationFocusChangedEventId); base.SetFocus(); } - internal void SetListBoxItemFocus() { + internal void SetListBoxItemFocus() + { var selectedItem = _owningGridViewListBox.SelectedItem; var itemAccessibleObject = _itemAccessibleObjects[selectedItem] as AccessibleObject; - if (itemAccessibleObject != null) { + if (itemAccessibleObject != null) + { itemAccessibleObject.SetFocus(); } } } - private class GridViewEdit : TextBox , IMouseHookClient { + private class GridViewEdit : TextBox, IMouseHookClient + { internal bool fInSetText = false; internal bool filter = false; internal PropertyGridView psheet = null; - private bool dontFocusMe = false; - private int lastMove; - + private bool dontFocusMe = false; + private int lastMove; + private MouseHook mouseHook; - + // We do this becuase the Focus call above doesn't always stick, so // we make the Edit think that it doesn't have focus. this prevents // ActiveControl code on the containercontrol from moving focus elsewhere // when the dropdown closes. - public bool DontFocus { - set { - dontFocusMe = value; - } + public bool DontFocus + { + set + { + dontFocusMe = value; + } } - - public virtual bool Filter { - get { return filter;} - set { + public virtual bool Filter + { + get { return filter; } + + set + { this.filter = value; } } @@ -6421,9 +7492,12 @@ public virtual bool Filter { /// internal override bool SupportsUiaProviders => true; - public override bool Focused { - get { - if (dontFocusMe) { + public override bool Focused + { + get + { + if (dontFocusMe) + { return false; } return base.Focused; @@ -6431,43 +7505,53 @@ public override bool Focused { } - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { + set + { fInSetText = true; base.Text = value; fInSetText = false; } } - - public bool DisableMouseHook { - - set { + + public bool DisableMouseHook + { + + set + { mouseHook.DisableMouseHook = value; } } - public virtual bool HookMouseDown{ - get{ + public virtual bool HookMouseDown + { + get + { return mouseHook.HookMouseDown; } - set{ + set + { mouseHook.HookMouseDown = value; - if (value) { + if (value) + { this.Focus(); } } } - public GridViewEdit(PropertyGridView psheet) { + public GridViewEdit(PropertyGridView psheet) + { this.psheet = psheet; mouseHook = new MouseHook(this, this, psheet); } - + /// /// Creates a new AccessibleObject for this GridViewEdit instance. /// The AccessibleObject instance returned by this method overrides several UIA properties. @@ -6477,38 +7561,46 @@ public GridViewEdit(PropertyGridView psheet) { /// /// AccessibleObject for this GridViewEdit instance. /// - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new GridViewEditAccessibleObject(this); } - protected override void DestroyHandle() { - mouseHook.HookMouseDown = false; - base.DestroyHandle(); + protected override void DestroyHandle() + { + mouseHook.HookMouseDown = false; + base.DestroyHandle(); } - protected override void Dispose(bool disposing) { - if (disposing) { + protected override void Dispose(bool disposing) + { + if (disposing) + { mouseHook.Dispose(); } base.Dispose(disposing); } - public void FilterKeyPress(char keyChar) { - - if (IsInputChar(keyChar)) { + public void FilterKeyPress(char keyChar) + { + + if (IsInputChar(keyChar)) + { this.Focus(); this.SelectAll(); UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), Interop.WindowMessages.WM_CHAR, (IntPtr)keyChar, IntPtr.Zero); } } - - + + /// /// Overridden to handle TAB key. /// - protected override bool IsInputKey(Keys keyData) { - switch (keyData & Keys.KeyCode) { + protected override bool IsInputKey(Keys keyData) + { + switch (keyData & Keys.KeyCode) + { case Keys.Escape: case Keys.Tab: case Keys.F4: @@ -6516,7 +7608,8 @@ protected override bool IsInputKey(Keys keyData) { case Keys.Return: return false; } - if (psheet.NeedsCommit) { + if (psheet.NeedsCommit) + { return false; } return base.IsInputKey(keyData); @@ -6525,8 +7618,10 @@ protected override bool IsInputKey(Keys keyData) { /// /// Overridden to handle TAB key. /// - protected override bool IsInputChar(char keyChar) { - switch ((Keys)(int)keyChar) { + protected override bool IsInputChar(char keyChar) + { + switch ((Keys)(int)keyChar) + { case Keys.Tab: case Keys.Return: return false; @@ -6534,12 +7629,14 @@ protected override bool IsInputChar(char keyChar) { return base.IsInputChar(keyChar); } - protected override void OnKeyDown(KeyEventArgs ke) { + protected override void OnKeyDown(KeyEventArgs ke) + { // this is because on a dialog we may // not get a chance to pre-process // - if (ProcessDialogKey(ke.KeyData)) { + if (ProcessDialogKey(ke.KeyData)) + { ke.Handled = true; return; } @@ -6547,95 +7644,109 @@ protected override void OnKeyDown(KeyEventArgs ke) { base.OnKeyDown(ke); } - protected override void OnKeyPress(KeyPressEventArgs ke) { - if (!IsInputChar(ke.KeyChar)) { + protected override void OnKeyPress(KeyPressEventArgs ke) + { + if (!IsInputChar(ke.KeyChar)) + { ke.Handled = true; return; } base.OnKeyPress(ke); } - - public bool OnClickHooked() { - // can we commit this value? - // eat the value if we failed to commit. - return !psheet._Commit(); - } - - protected override void OnMouseEnter(EventArgs e) { - base.OnMouseEnter(e); - - if (!this.Focused) { - Graphics g = CreateGraphics(); - if (psheet.SelectedGridEntry != null && - ClientRectangle.Width <= psheet.SelectedGridEntry.GetValueTextWidth(this.Text, g, this.Font)) { - psheet.ToolTip.ToolTip = this.PasswordProtect ? "" : this.Text; - } - g.Dispose(); - } - - } - - protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { - - // make sure we allow the Edit to handle ctrl-z - switch (keyData & Keys.KeyCode) { - case Keys.Z: - case Keys.C: - case Keys.X: - case Keys.V: - if( - ((keyData & Keys.Control) != 0) && + + public bool OnClickHooked() + { + // can we commit this value? + // eat the value if we failed to commit. + return !psheet._Commit(); + } + + protected override void OnMouseEnter(EventArgs e) + { + base.OnMouseEnter(e); + + if (!this.Focused) + { + Graphics g = CreateGraphics(); + if (psheet.SelectedGridEntry != null && + ClientRectangle.Width <= psheet.SelectedGridEntry.GetValueTextWidth(this.Text, g, this.Font)) + { + psheet.ToolTip.ToolTip = this.PasswordProtect ? "" : this.Text; + } + g.Dispose(); + } + + } + + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) + { + + // make sure we allow the Edit to handle ctrl-z + switch (keyData & Keys.KeyCode) + { + case Keys.Z: + case Keys.C: + case Keys.X: + case Keys.V: + if ( + ((keyData & Keys.Control) != 0) && ((keyData & Keys.Shift) == 0) && - ((keyData & Keys.Alt) == 0)) { - return false; + ((keyData & Keys.Alt) == 0)) + { + return false; } break; - - case Keys.A: - if( - ((keyData & Keys.Control) != 0) && + + case Keys.A: + if ( + ((keyData & Keys.Control) != 0) && ((keyData & Keys.Shift) == 0) && - ((keyData & Keys.Alt) == 0)) { - SelectAll(); - return true; + ((keyData & Keys.Alt) == 0)) + { + SelectAll(); + return true; + } + + break; + + case Keys.Insert: + if (((keyData & Keys.Alt) == 0)) + { + if (((keyData & Keys.Control) != 0) ^ ((keyData & Keys.Shift) == 0)) + { + return false; + } + } + break; + + case Keys.Delete: + if ( + ((keyData & Keys.Control) == 0) && + ((keyData & Keys.Shift) != 0) && + ((keyData & Keys.Alt) == 0)) + { + return false; + } + else if ( + ((keyData & Keys.Control) == 0) && + ((keyData & Keys.Shift) == 0) && + ((keyData & Keys.Alt) == 0) + ) + { + // if this is just the delete key and we're on a non-text editable property that is resettable, + // reset it now. + // + if (psheet.SelectedGridEntry != null && !psheet.SelectedGridEntry.Enumerable && !psheet.SelectedGridEntry.IsTextEditable && psheet.SelectedGridEntry.CanResetPropertyValue()) + { + object oldValue = psheet.SelectedGridEntry.PropertyValue; + psheet.SelectedGridEntry.ResetPropertyValue(); + psheet.UnfocusSelection(); + psheet.ownerGrid.OnPropertyValueSet(psheet.SelectedGridEntry, oldValue); + } } - break; - - case Keys.Insert: - if (((keyData & Keys.Alt) == 0)) { - if (((keyData & Keys.Control) != 0) ^ ((keyData & Keys.Shift) == 0)) { - return false; - } - } - break; - - case Keys.Delete: - if( - ((keyData & Keys.Control) == 0) && - ((keyData & Keys.Shift) != 0) && - ((keyData & Keys.Alt) == 0)) { - return false; - } - else if( - ((keyData & Keys.Control) == 0) && - ((keyData & Keys.Shift) == 0) && - ((keyData & Keys.Alt) == 0) - ) - { - // if this is just the delete key and we're on a non-text editable property that is resettable, - // reset it now. - // - if (psheet.SelectedGridEntry != null && !psheet.SelectedGridEntry.Enumerable && !psheet.SelectedGridEntry.IsTextEditable && psheet.SelectedGridEntry.CanResetPropertyValue()) { - object oldValue = psheet.SelectedGridEntry.PropertyValue; - psheet.SelectedGridEntry.ResetPropertyValue(); - psheet.UnfocusSelection(); - psheet.ownerGrid.OnPropertyValueSet(psheet.SelectedGridEntry, oldValue); - } - } - break; - } - return base.ProcessCmdKey(ref msg, keyData); + } + return base.ProcessCmdKey(ref msg, keyData); } @@ -6643,16 +7754,20 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { /// Overrides Control.ProcessDialogKey to handle the Escape and Return /// keys. /// - protected override bool ProcessDialogKey(Keys keyData) { + protected override bool ProcessDialogKey(Keys keyData) + { // We don't do anything with modified keys here. // - if ((keyData & (Keys.Shift | Keys.Control | Keys.Alt)) == 0) { - switch (keyData & Keys.KeyCode) { - case Keys.Return: + if ((keyData & (Keys.Shift | Keys.Control | Keys.Alt)) == 0) + { + switch (keyData & Keys.KeyCode) + { + case Keys.Return: bool fwdReturn = !psheet.NeedsCommit; - if (psheet.UnfocusSelection() && fwdReturn) { - psheet.SelectedGridEntry.OnValueReturnKey(); + if (psheet.UnfocusSelection() && fwdReturn) + { + psheet.SelectedGridEntry.OnValueReturnKey(); } return true; case Keys.Escape: @@ -6663,77 +7778,92 @@ protected override bool ProcessDialogKey(Keys keyData) { return true; } } - + // for the tab key, we want to commit before we allow it to be processed. - if ((keyData & Keys.KeyCode) == Keys.Tab && ((keyData & (Keys.Control | Keys.Alt)) == 0)) { + if ((keyData & Keys.KeyCode) == Keys.Tab && ((keyData & (Keys.Control | Keys.Alt)) == 0)) + { return !psheet._Commit(); } return base.ProcessDialogKey(keyData); } - protected override void SetVisibleCore(bool value) { - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "DropDownHolder:Visible(" + (value.ToString()) + ")"); + protected override void SetVisibleCore(bool value) + { + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "DropDownHolder:Visible(" + (value.ToString()) + ")"); // make sure we dont' have the mouse captured if // we're going invisible - if (value == false && this.HookMouseDown) { + if (value == false && this.HookMouseDown) + { mouseHook.HookMouseDown = false; } base.SetVisibleCore(value); } - + // a mini version of process dialog key // for responding to WM_GETDLGCODE - internal bool WantsTab(bool forward) { + internal bool WantsTab(bool forward) + { return psheet.WantsTab(forward); } - - private unsafe bool WmNotify(ref Message m) { - - if (m.LParam != IntPtr.Zero) { - NativeMethods.NMHDR* nmhdr = (NativeMethods.NMHDR*)m.LParam; - - if (nmhdr->hwndFrom == psheet.ToolTip.Handle) { - switch (nmhdr->code) { - case NativeMethods.TTN_SHOW: - PropertyGridView.PositionTooltip(this, psheet.ToolTip, ClientRectangle); - m.Result = (IntPtr)1; - return true; - default: - psheet.WndProc(ref m); - break; - } - } + + private unsafe bool WmNotify(ref Message m) + { + + if (m.LParam != IntPtr.Zero) + { + NativeMethods.NMHDR* nmhdr = (NativeMethods.NMHDR*)m.LParam; + + if (nmhdr->hwndFrom == psheet.ToolTip.Handle) + { + switch (nmhdr->code) + { + case NativeMethods.TTN_SHOW: + PropertyGridView.PositionTooltip(this, psheet.ToolTip, ClientRectangle); + m.Result = (IntPtr)1; + return true; + default: + psheet.WndProc(ref m); + break; + } + } } return false; } - - protected override void WndProc(ref Message m) { - if (filter) { - if (psheet.FilterEditWndProc(ref m)) { + protected override void WndProc(ref Message m) + { + + if (filter) + { + if (psheet.FilterEditWndProc(ref m)) + { return; } } - switch (m.Msg) { + switch (m.Msg) + { case Interop.WindowMessages.WM_STYLECHANGED: - if ((unchecked( (int) (long)m.WParam) & NativeMethods.GWL_EXSTYLE) != 0) { + if ((unchecked((int)(long)m.WParam) & NativeMethods.GWL_EXSTYLE) != 0) + { psheet.Invalidate(); } break; case Interop.WindowMessages.WM_MOUSEMOVE: - if (unchecked( (int) (long)m.LParam) == lastMove) { + if (unchecked((int)(long)m.LParam) == lastMove) + { return; } - lastMove = unchecked( (int) (long)m.LParam); + lastMove = unchecked((int)(long)m.LParam); break; case Interop.WindowMessages.WM_DESTROY: mouseHook.HookMouseDown = false; break; case Interop.WindowMessages.WM_SHOWWINDOW: - if (IntPtr.Zero == m.WParam) { + if (IntPtr.Zero == m.WParam) + { mouseHook.HookMouseDown = false; } break; @@ -6751,47 +7881,56 @@ protected override void WndProc(ref Message m) { } } }*/ - if (this.ReadOnly) { - return; + if (this.ReadOnly) + { + return; } break; - + case Interop.WindowMessages.WM_GETDLGCODE: m.Result = (IntPtr)((long)m.Result | NativeMethods.DLGC_WANTARROWS | NativeMethods.DLGC_WANTCHARS); - if (psheet.NeedsCommit || this.WantsTab((ModifierKeys & Keys.Shift) == 0)) { + if (psheet.NeedsCommit || this.WantsTab((ModifierKeys & Keys.Shift) == 0)) + { m.Result = (IntPtr)((long)m.Result | NativeMethods.DLGC_WANTALLKEYS | NativeMethods.DLGC_WANTTAB); } return; - + case Interop.WindowMessages.WM_NOTIFY: if (WmNotify(ref m)) return; - break; + break; } base.WndProc(ref m); } - public virtual bool InSetText() { + public virtual bool InSetText() + { return fInSetText; } [ComVisible(true)] - protected class GridViewEditAccessibleObject : ControlAccessibleObject { + protected class GridViewEditAccessibleObject : ControlAccessibleObject + { private PropertyGridView propertyGridView; - public GridViewEditAccessibleObject(GridViewEdit owner) : base(owner) { + public GridViewEditAccessibleObject(GridViewEdit owner) : base(owner) + { this.propertyGridView = owner.psheet; } - public override AccessibleStates State { - get { + public override AccessibleStates State + { + get + { AccessibleStates states = base.State; - if (this.IsReadOnly) { + if (this.IsReadOnly) + { states |= AccessibleStates.ReadOnly; } - else { + else + { states &= ~AccessibleStates.ReadOnly; } return states; @@ -6805,14 +7944,20 @@ public override AccessibleStates State { /// /// Indicates the direction in which to navigate. /// Returns the element in the specified direction. - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - if (direction == UnsafeNativeMethods.NavigateDirection.Parent) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { + if (direction == UnsafeNativeMethods.NavigateDirection.Parent) + { return propertyGridView.SelectedGridEntry.AccessibilityObject; } - else if (direction == UnsafeNativeMethods.NavigateDirection.NextSibling) { - if (propertyGridView.DropDownButton.Visible) { + else if (direction == UnsafeNativeMethods.NavigateDirection.NextSibling) + { + if (propertyGridView.DropDownButton.Visible) + { return propertyGridView.DropDownButton.AccessibilityObject; - } else if (propertyGridView.DialogButton.Visible) { + } + else if (propertyGridView.DialogButton.Visible) + { return propertyGridView.DialogButton.AccessibilityObject; } } @@ -6823,46 +7968,60 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga /// /// Gets the top level element. /// - internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot { - get { + internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot + { + get + { return propertyGridView.AccessibilityObject; } } - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_IsEnabledPropertyId) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_IsEnabledPropertyId) + { return !this.IsReadOnly; } - else if (propertyID == NativeMethods.UIA_IsValuePatternAvailablePropertyId) { + else if (propertyID == NativeMethods.UIA_IsValuePatternAvailablePropertyId) + { return IsPatternSupported(NativeMethods.UIA_ValuePatternId); } - else if (propertyID == NativeMethods.UIA_ControlTypePropertyId) { + else if (propertyID == NativeMethods.UIA_ControlTypePropertyId) + { return NativeMethods.UIA_EditControlTypeId; } - else if (propertyID == NativeMethods.UIA_NamePropertyId) { + else if (propertyID == NativeMethods.UIA_NamePropertyId) + { return Name; } return base.GetPropertyValue(propertyID); } - internal override bool IsPatternSupported(int patternId) { - if (patternId == NativeMethods.UIA_ValuePatternId) { + internal override bool IsPatternSupported(int patternId) + { + if (patternId == NativeMethods.UIA_ValuePatternId) + { return true; } return base.IsPatternSupported(patternId); } - public override string Name { - get { + public override string Name + { + get + { string name = Owner.AccessibleName; - if (name != null) { + if (name != null) + { return name; } - else { + else + { var selectedGridEntry = propertyGridView.SelectedGridEntry; - if (selectedGridEntry != null) { + if (selectedGridEntry != null) + { return selectedGridEntry.AccessibilityObject.Name; } } @@ -6870,15 +8029,18 @@ public override string Name { return base.Name; } - set { + set + { base.Name = value; } } #region IValueProvider - internal override bool IsReadOnly { - get { + internal override bool IsReadOnly + { + get + { PropertyDescriptorGridEntry propertyDescriptorGridEntry = this.propertyGridView.SelectedGridEntry as PropertyDescriptorGridEntry; return propertyDescriptorGridEntry == null || propertyDescriptorGridEntry.IsPropertyReadOnly; } @@ -6886,100 +8048,117 @@ internal override bool IsReadOnly { #endregion - internal override void SetFocus() { + internal override void SetFocus() + { RaiseAutomationEvent(NativeMethods.UIA_AutomationFocusChangedEventId); base.SetFocus(); } } } - + internal interface IMouseHookClient { // return true if the click is handled, false // to pass it on - bool OnClickHooked(); - } - - internal class MouseHook { + bool OnClickHooked(); + } + + internal class MouseHook + { private PropertyGridView gridView; - private Control control; + private Control control; private IMouseHookClient client; - - internal int thisProcessID = 0; - private GCHandle mouseHookRoot; - private IntPtr mouseHookHandle = IntPtr.Zero; - private bool hookDisable = false; - - private bool processing; - - public MouseHook(Control control, IMouseHookClient client, PropertyGridView gridView) { - this.control = control; - this.gridView = gridView; - this.client = client; - #if DEBUG - callingStack = Environment.StackTrace; - #endif - } - - #if DEBUG + + internal int thisProcessID = 0; + private GCHandle mouseHookRoot; + private IntPtr mouseHookHandle = IntPtr.Zero; + private bool hookDisable = false; + + private bool processing; + + public MouseHook(Control control, IMouseHookClient client, PropertyGridView gridView) + { + this.control = control; + this.gridView = gridView; + this.client = client; +#if DEBUG + callingStack = Environment.StackTrace; +#endif + } + +#if DEBUG string callingStack; - ~MouseHook() { + ~MouseHook() + { Debug.Assert(mouseHookHandle == IntPtr.Zero, "Finalizing an active mouse hook. This will crash the process. Calling stack: " + callingStack); } - #endif - - - public bool DisableMouseHook { - - set { +#endif + + + public bool DisableMouseHook + { + + set + { hookDisable = value; - if (value) { + if (value) + { UnhookMouse(); } } } - public virtual bool HookMouseDown{ - get{ + public virtual bool HookMouseDown + { + get + { GC.KeepAlive(this); return mouseHookHandle != IntPtr.Zero; } - set{ - if (value && !hookDisable) { + set + { + if (value && !hookDisable) + { HookMouse(); } - else { + else + { UnhookMouse(); } } } - - public void Dispose() { - UnhookMouse(); - } - + + public void Dispose() + { + UnhookMouse(); + } + /// /// Sets up the needed windows hooks to catch messages. /// - - - private void HookMouse() { + + + private void HookMouse() + { GC.KeepAlive(this); // Locking 'this' here is ok since this is an internal class. - lock(this) { - if (mouseHookHandle != IntPtr.Zero) { + lock (this) + { + if (mouseHookHandle != IntPtr.Zero) + { return; } - - if (thisProcessID == 0) { + + if (thisProcessID == 0) + { SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(control, control.Handle), out thisProcessID); } - - + + NativeMethods.HookProc hook = new NativeMethods.HookProc(new MouseHookObject(this).Callback); mouseHookRoot = GCHandle.Alloc(hook); @@ -6988,19 +8167,23 @@ private void HookMouse() { NativeMethods.NullHandleRef, SafeNativeMethods.GetCurrentThreadId()); Debug.Assert(mouseHookHandle != IntPtr.Zero, "Failed to install mouse hook"); - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "DropDownHolder:HookMouse()"); + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "DropDownHolder:HookMouse()"); } } - + /// /// HookProc used for catch mouse messages. /// - private IntPtr MouseHookProc(int nCode, IntPtr wparam, IntPtr lparam) { + private IntPtr MouseHookProc(int nCode, IntPtr wparam, IntPtr lparam) + { GC.KeepAlive(this); - if (nCode == NativeMethods.HC_ACTION) { + if (nCode == NativeMethods.HC_ACTION) + { NativeMethods.MOUSEHOOKSTRUCT mhs = Marshal.PtrToStructure(lparam); - if (mhs != null) { - switch (unchecked( (int) (long)wparam)) { + if (mhs != null) + { + switch (unchecked((int)(long)wparam)) + { case Interop.WindowMessages.WM_LBUTTONDOWN: case Interop.WindowMessages.WM_MBUTTONDOWN: case Interop.WindowMessages.WM_RBUTTONDOWN: @@ -7008,7 +8191,8 @@ private IntPtr MouseHookProc(int nCode, IntPtr wparam, IntPtr lparam) { case Interop.WindowMessages.WM_NCMBUTTONDOWN: case Interop.WindowMessages.WM_NCRBUTTONDOWN: case Interop.WindowMessages.WM_MOUSEACTIVATE: - if (ProcessMouseDown(mhs.hWnd, mhs.pt_x, mhs.pt_y)) { + if (ProcessMouseDown(mhs.hWnd, mhs.pt_x, mhs.pt_y)) + { return (IntPtr)1; } break; @@ -7019,44 +8203,50 @@ private IntPtr MouseHookProc(int nCode, IntPtr wparam, IntPtr lparam) { return UnsafeNativeMethods.CallNextHookEx(new HandleRef(this, mouseHookHandle), nCode, wparam, lparam); } - + /// /// Removes the windowshook that was installed. /// - private void UnhookMouse() { + private void UnhookMouse() + { GC.KeepAlive(this); // Locking 'this' here is ok since this is an internal class. - lock(this) { - if (mouseHookHandle != IntPtr.Zero) { + lock (this) + { + if (mouseHookHandle != IntPtr.Zero) + { UnsafeNativeMethods.UnhookWindowsHookEx(new HandleRef(this, mouseHookHandle)); mouseHookRoot.Free(); mouseHookHandle = IntPtr.Zero; - Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "DropDownHolder:UnhookMouse()"); + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "DropDownHolder:UnhookMouse()"); } } } - - /* - * Here is where we force validation on any clicks outside the - */ - private bool ProcessMouseDown(IntPtr hWnd, int x, int y) { - - - // if we put up the "invalid" message box, it appears this - // method is getting called re-entrantly when it shouldn't be. - // this prevents us from recursing. - // - if (processing) { - return false; - } - + + /* + * Here is where we force validation on any clicks outside the + */ + private bool ProcessMouseDown(IntPtr hWnd, int x, int y) + { + + + // if we put up the "invalid" message box, it appears this + // method is getting called re-entrantly when it shouldn't be. + // this prevents us from recursing. + // + if (processing) + { + return false; + } + IntPtr hWndAtPoint = hWnd; IntPtr handle = control.Handle; Control ctrlAtPoint = Control.FromHandle(hWndAtPoint); // if it's us or one of our children, just process as normal // - if (hWndAtPoint != handle && !control.Contains(ctrlAtPoint)) { + if (hWndAtPoint != handle && !control.Contains(ctrlAtPoint)) + { Debug.Assert(thisProcessID != 0, "Didn't get our process id!"); // make sure the window is in our process @@ -7064,38 +8254,43 @@ private bool ProcessMouseDown(IntPtr hWnd, int x, int y) { SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(null, hWndAtPoint), out pid); // if this isn't our process, unhook the mouse. - if (pid != thisProcessID) { + if (pid != thisProcessID) + { this.HookMouseDown = false; return false; } - bool needCommit = false; + bool needCommit = false; // if this a sibling control (e.g. the drop down or buttons), just forward the message and skip the commit - needCommit = ctrlAtPoint == null ? true : !gridView.IsSiblingControl(control, ctrlAtPoint); - - try { - processing = true; - - if (needCommit) { - if (client.OnClickHooked()) { - return true; // there was an error, so eat the mouse - } - /* This breaks all sorts of stuff. Need to find a better way to do this but we can't figure - out the scenario this addressed. - else { - // Returning false lets the message go to its destination. Only - // return false if there is still a mouse button down. That might not be the - // case if committing the entry opened a modal dialog. - // - MouseButtons state = Control.MouseButtons; - return (int)state == 0; - } - */ - } + needCommit = ctrlAtPoint == null ? true : !gridView.IsSiblingControl(control, ctrlAtPoint); + + try + { + processing = true; + + if (needCommit) + { + if (client.OnClickHooked()) + { + return true; // there was an error, so eat the mouse + } + /* This breaks all sorts of stuff. Need to find a better way to do this but we can't figure + out the scenario this addressed. + else { + // Returning false lets the message go to its destination. Only + // return false if there is still a mouse button down. That might not be the + // case if committing the entry opened a modal dialog. + // + MouseButtons state = Control.MouseButtons; + return (int)state == 0; + } + */ + } } - finally { - processing = false; + finally + { + processing = false; } // cancel our hook at this point @@ -7104,26 +8299,32 @@ out the scenario this addressed. } return false; } - - /// + + /// /// Forwards messageHook calls to ToolTip.messageHookProc /// - private class MouseHookObject { + private class MouseHookObject + { internal WeakReference reference; - public MouseHookObject(MouseHook parent) { + public MouseHookObject(MouseHook parent) + { this.reference = new WeakReference(parent, false); } - public virtual IntPtr Callback(int nCode, IntPtr wparam, IntPtr lparam) { + public virtual IntPtr Callback(int nCode, IntPtr wparam, IntPtr lparam) + { IntPtr ret = IntPtr.Zero; - try { + try + { MouseHook control = (MouseHook)reference.Target; - if (control != null) { + if (control != null) + { ret = control.MouseHookProc(nCode, wparam, lparam); } } - catch { + catch + { // ignore } return ret; @@ -7135,8 +8336,9 @@ public virtual IntPtr Callback(int nCode, IntPtr wparam, IntPtr lparam) { /// The accessible object class for a PropertyGridView. The child accessible objects /// are accessible objects corresponding to the property grid entries. /// - [System.Runtime.InteropServices.ComVisible(true)] - internal class PropertyGridViewAccessibleObject : ControlAccessibleObject { + [System.Runtime.InteropServices.ComVisible(true)] + internal class PropertyGridViewAccessibleObject : ControlAccessibleObject + { private PropertyGridView _owningPropertyGridView; private PropertyGrid _parentPropertyGrid; @@ -7144,7 +8346,8 @@ internal class PropertyGridViewAccessibleObject : ControlAccessibleObject { /// /// Construct a PropertyGridViewAccessibleObject /// - public PropertyGridViewAccessibleObject(PropertyGridView owner, PropertyGrid parentPropertyGrid) : base(owner) { + public PropertyGridViewAccessibleObject(PropertyGridView owner, PropertyGrid parentPropertyGrid) : base(owner) + { _owningPropertyGridView = owner; _parentPropertyGrid = parentPropertyGrid; } @@ -7160,7 +8363,8 @@ public PropertyGridViewAccessibleObject(PropertyGridView owner, PropertyGrid par /// otherwise return this element if the point is on this element, /// otherwise return null. /// - internal override UnsafeNativeMethods.IRawElementProviderFragment ElementProviderFromPoint(double x, double y) { + internal override UnsafeNativeMethods.IRawElementProviderFragment ElementProviderFromPoint(double x, double y) + { return HitTest((int)x, (int)y); } @@ -7169,30 +8373,38 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment ElementProvide /// /// Indicates the direction in which to navigate. /// Returns the element in the specified direction. - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { var propertyGridAccessibleObject = _parentPropertyGrid.AccessibilityObject as PropertyGridAccessibleObject; - if (propertyGridAccessibleObject != null) { + if (propertyGridAccessibleObject != null) + { var navigationTarget = propertyGridAccessibleObject.ChildFragmentNavigate(this, direction); - if (navigationTarget != null) { + if (navigationTarget != null) + { return navigationTarget; } } - if (_owningPropertyGridView.OwnerGrid.SortedByCategories) { - switch (direction) { + if (_owningPropertyGridView.OwnerGrid.SortedByCategories) + { + switch (direction) + { case UnsafeNativeMethods.NavigateDirection.FirstChild: return GetFirstCategory(); case UnsafeNativeMethods.NavigateDirection.LastChild: return GetLastCategory(); } } - else { - switch (direction) { + else + { + switch (direction) + { case UnsafeNativeMethods.NavigateDirection.FirstChild: return GetChild(0); case UnsafeNativeMethods.NavigateDirection.LastChild: int childCount = GetChildCount(); - if (childCount > 0) { + if (childCount > 0) + { return GetChild(childCount - 1); } @@ -7206,8 +8418,10 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga /// /// Return the element that is the root node of this fragment of UI. /// - internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot { - get { + internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot + { + get + { return _owningPropertyGridView.OwnerGrid.AccessibilityObject; } } @@ -7216,7 +8430,8 @@ internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRo /// Gets the accessible object for the currently focused grid entry. /// /// The accessible object for the currently focused grid entry. - internal override UnsafeNativeMethods.IRawElementProviderFragment GetFocus() { + internal override UnsafeNativeMethods.IRawElementProviderFragment GetFocus() + { return GetFocused(); } @@ -7225,57 +8440,74 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment GetFocus() { /// /// Identifier indicating the property to return /// Returns a ValInfo indicating whether the element supports this property, or has no value for it. - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_ControlTypePropertyId) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_ControlTypePropertyId) + { return NativeMethods.UIA_TableControlTypeId; - } else if (propertyID == NativeMethods.UIA_NamePropertyId) { + } + else if (propertyID == NativeMethods.UIA_NamePropertyId) + { return Name; } return base.GetPropertyValue(propertyID); } - - public override string Name { - get { + + public override string Name + { + get + { string name = Owner.AccessibleName; - if (name != null) { + if (name != null) + { return name; } - else { + else + { return SR.PropertyGridDefaultAccessibleName; } } } - - public override AccessibleRole Role { - get { + + public override AccessibleRole Role + { + get + { AccessibleRole role = Owner.AccessibleRole; - if (role != AccessibleRole.Default) { + if (role != AccessibleRole.Default) + { return role; } - else { + else + { return AccessibleRole.Table; } } - } + } - public AccessibleObject Next(GridEntry current) { + public AccessibleObject Next(GridEntry current) + { int row = ((PropertyGridView)Owner).GetRowFromGridEntry(current); GridEntry nextEntry = ((PropertyGridView)Owner).GetGridEntryFromRow(++row); - if (nextEntry != null) { + if (nextEntry != null) + { return nextEntry.AccessibilityObject; } return null; } - internal AccessibleObject GetCategory(int categoryIndex) { + internal AccessibleObject GetCategory(int categoryIndex) + { GridEntry[] targetEntries = new GridEntry[1]; var topLevelGridEntries = _owningPropertyGridView.TopLevelGridEntries; var topLevelGridEntriesCount = topLevelGridEntries.Count; - if (topLevelGridEntriesCount > 0) { + if (topLevelGridEntriesCount > 0) + { var targetEntry = topLevelGridEntries[categoryIndex]; var categoryGridEntry = targetEntry as CategoryGridEntry; - if (categoryGridEntry != null) { + if (categoryGridEntry != null) + { return categoryGridEntry.AccessibilityObject; } } @@ -7283,11 +8515,13 @@ internal AccessibleObject GetCategory(int categoryIndex) { return null; } - internal AccessibleObject GetFirstCategory() { + internal AccessibleObject GetFirstCategory() + { return GetCategory(0); } - internal AccessibleObject GetLastCategory() { + internal AccessibleObject GetLastCategory() + { var topLevelGridEntries = _owningPropertyGridView.TopLevelGridEntries; var topLevelGridEntriesCount = topLevelGridEntries.Count; return GetCategory(topLevelGridEntries.Count - 1); @@ -7300,31 +8534,40 @@ internal AccessibleObject GetLastCategory() { /// The grid entry collection. /// Indicates whether the current grid entry is found. /// The previous grid entry. - internal AccessibleObject GetPreviousGridEntry(GridEntry currentGridEntry, GridEntryCollection gridEntryCollection, out bool currentGridEntryFound) { + internal AccessibleObject GetPreviousGridEntry(GridEntry currentGridEntry, GridEntryCollection gridEntryCollection, out bool currentGridEntryFound) + { GridEntry previousGridEntry = null; currentGridEntryFound = false; - foreach (GridEntry gridEntry in gridEntryCollection) { - if (currentGridEntry == gridEntry) { + foreach (GridEntry gridEntry in gridEntryCollection) + { + if (currentGridEntry == gridEntry) + { // Set to true to return the previous iterable element. currentGridEntryFound = true; - if (previousGridEntry != null) { + if (previousGridEntry != null) + { // In the current iteration return previous entry if the current entry == iterated grid entry. return previousGridEntry.AccessibilityObject; } - else { + else + { return null; } } - else { + else + { previousGridEntry = gridEntry; - if (gridEntry.ChildCount > 0) { + if (gridEntry.ChildCount > 0) + { var foundChild = GetPreviousGridEntry(currentGridEntry, gridEntry.Children, out currentGridEntryFound); - if (foundChild != null) { + if (foundChild != null) + { // Return some down-level child if found. return foundChild; } - else if (currentGridEntryFound) { + else if (currentGridEntryFound) + { // If the passed current is found but there is no next near this current. return null; } @@ -7342,26 +8585,33 @@ internal AccessibleObject GetPreviousGridEntry(GridEntry currentGridEntry, GridE /// The grid entry collection. /// Indicates whether the current grid entry is found. /// The next grid entry. - internal AccessibleObject GetNextGridEntry(GridEntry currentGridEntry, GridEntryCollection gridEntryCollection, out bool currentGridEntryFound) { + internal AccessibleObject GetNextGridEntry(GridEntry currentGridEntry, GridEntryCollection gridEntryCollection, out bool currentGridEntryFound) + { currentGridEntryFound = false; - foreach (GridEntry gridEntry in gridEntryCollection) { - if (currentGridEntryFound) { + foreach (GridEntry gridEntry in gridEntryCollection) + { + if (currentGridEntryFound) + { // Return the next entry via IEnumerable.Next() if previous entry == passed current. return gridEntry.AccessibilityObject; } - if (currentGridEntry == gridEntry) { + if (currentGridEntry == gridEntry) + { // Set to true to return the next iterable element. (see above) currentGridEntryFound = true; } - else if (gridEntry.ChildCount > 0) { + else if (gridEntry.ChildCount > 0) + { var foundChild = GetNextGridEntry(currentGridEntry, gridEntry.Children, out currentGridEntryFound); - if (foundChild != null) { + if (foundChild != null) + { // Return some down-level child if found. return foundChild; } - else if (currentGridEntryFound) { + else if (currentGridEntryFound) + { // If the passed current is found but there is no next near this current. return null; } @@ -7376,15 +8626,20 @@ internal AccessibleObject GetNextGridEntry(GridEntry currentGridEntry, GridEntry /// /// The current grid entry. /// The first child property. - internal AccessibleObject GetFirstChildProperty(CategoryGridEntry current) { - if (current.ChildCount > 0) { + internal AccessibleObject GetFirstChildProperty(CategoryGridEntry current) + { + if (current.ChildCount > 0) + { GridEntryCollection subGridEntry = current.Children; - if (subGridEntry != null && subGridEntry.Count > 0) { + if (subGridEntry != null && subGridEntry.Count > 0) + { GridEntry[] targetEntries = new GridEntry[1]; - try { + try + { _owningPropertyGridView.GetGridEntriesFromOutline(subGridEntry, 0, 0, targetEntries); } - catch (Exception ex) { + catch (Exception ex) + { Debug.Fail(ex.ToString()); } @@ -7400,15 +8655,20 @@ internal AccessibleObject GetFirstChildProperty(CategoryGridEntry current) { /// /// The current grid entry. /// The last child property. - internal AccessibleObject GetLastChildProperty(CategoryGridEntry current) { - if (current.ChildCount > 0) { + internal AccessibleObject GetLastChildProperty(CategoryGridEntry current) + { + if (current.ChildCount > 0) + { GridEntryCollection subGridEntry = current.Children; - if (subGridEntry != null && subGridEntry.Count > 0) { + if (subGridEntry != null && subGridEntry.Count > 0) + { GridEntry[] targetEntries = new GridEntry[1]; - try { + try + { _owningPropertyGridView.GetGridEntriesFromOutline(subGridEntry, 0, subGridEntry.Count - 1, targetEntries); } - catch (Exception ex) { + catch (Exception ex) + { Debug.Fail(ex.ToString()); } @@ -7424,14 +8684,17 @@ internal AccessibleObject GetLastChildProperty(CategoryGridEntry current) { /// /// The current grid entry. /// The next category. - internal AccessibleObject GetNextCategory(CategoryGridEntry current) { + internal AccessibleObject GetNextCategory(CategoryGridEntry current) + { int row = _owningPropertyGridView.GetRowFromGridEntry(current); GridEntry nextEntry; - do { + do + { nextEntry = _owningPropertyGridView.GetGridEntryFromRow(++row); - if (nextEntry is CategoryGridEntry) { + if (nextEntry is CategoryGridEntry) + { return nextEntry.AccessibilityObject; } } @@ -7440,10 +8703,12 @@ internal AccessibleObject GetNextCategory(CategoryGridEntry current) { return null; } - public AccessibleObject Previous(GridEntry current) { + public AccessibleObject Previous(GridEntry current) + { int row = ((PropertyGridView)Owner).GetRowFromGridEntry(current); GridEntry prevEntry = ((PropertyGridView)Owner).GetGridEntryFromRow(--row); - if (prevEntry != null) { + if (prevEntry != null) + { return prevEntry.AccessibilityObject; } return null; @@ -7454,14 +8719,17 @@ public AccessibleObject Previous(GridEntry current) { /// /// The current grid entry. /// The previous category. - internal AccessibleObject GetPreviousCategory(CategoryGridEntry current) { + internal AccessibleObject GetPreviousCategory(CategoryGridEntry current) + { int row = _owningPropertyGridView.GetRowFromGridEntry(current); GridEntry previousEntry; - do { + do + { previousEntry = _owningPropertyGridView.GetGridEntryFromRow(--row); - if (previousEntry is CategoryGridEntry) { + if (previousEntry is CategoryGridEntry) + { return previousEntry.AccessibilityObject; } } @@ -7475,13 +8743,16 @@ internal AccessibleObject GetPreviousCategory(CategoryGridEntry current) { /// The accessible children of a PropertyGridView are accessible objects /// corresponding to the property grid entries. /// - public override AccessibleObject GetChild(int index) { + public override AccessibleObject GetChild(int index) + { GridEntryCollection properties = ((PropertyGridView)Owner).AccessibilityGetGridEntries(); - if (properties != null && index >= 0 && index < properties.Count) { + if (properties != null && index >= 0 && index < properties.Count) + { return properties.GetEntry(index).AccessibilityObject; } - else { + else + { return null; } } @@ -7491,13 +8762,16 @@ public override AccessibleObject GetChild(int index) { /// The accessible children of a PropertyGridView are accessible objects /// corresponding to the property grid entries. /// - public override int GetChildCount() { + public override int GetChildCount() + { GridEntryCollection properties = ((PropertyGridView)Owner).AccessibilityGetGridEntries(); - if (properties != null) { + if (properties != null) + { return properties.Count; } - else { + else + { return 0; } } @@ -7505,10 +8779,12 @@ public override int GetChildCount() { /// /// Get the accessible object for the currently focused grid entry. /// - public override AccessibleObject GetFocused() { - + public override AccessibleObject GetFocused() + { + GridEntry gridEntry = ((PropertyGridView)Owner).SelectedGridEntry; - if (gridEntry != null && gridEntry.Focus) { + if (gridEntry != null && gridEntry.Focus) + { return gridEntry.AccessibilityObject; } return null; @@ -7517,9 +8793,11 @@ public override AccessibleObject GetFocused() { /// /// Get the accessible object for the currently selected grid entry. /// - public override AccessibleObject GetSelected() { + public override AccessibleObject GetSelected() + { GridEntry gridEntry = ((PropertyGridView)Owner).SelectedGridEntry; - if (gridEntry != null) { + if (gridEntry != null) + { return gridEntry.AccessibilityObject; } return null; @@ -7532,7 +8810,8 @@ public override AccessibleObject GetSelected() { /// The accessible children of a PropertyGridView are accessible objects /// corresponding to the property grid entries. /// - public override AccessibleObject HitTest(int x, int y) { + public override AccessibleObject HitTest(int x, int y) + { // Convert to client coordinates // @@ -7542,9 +8821,11 @@ public override AccessibleObject HitTest(int x, int y) { // Find the grid entry at the given client coordinates // Point pos = ((PropertyGridView)Owner).FindPosition(pt.x, pt.y); - if (pos != PropertyGridView.InvalidPosition) { + if (pos != PropertyGridView.InvalidPosition) + { GridEntry gridEntry = ((PropertyGridView)Owner).GetGridEntryFromRow(pos.Y); - if (gridEntry != null) { + if (gridEntry != null) + { // Return the accessible object for this grid entry // @@ -7560,11 +8841,14 @@ public override AccessibleObject HitTest(int x, int y) { /// /// Navigate to another object. /// - public override AccessibleObject Navigate(AccessibleNavigation navdir) { + public override AccessibleObject Navigate(AccessibleNavigation navdir) + { - if (GetChildCount() > 0) { + if (GetChildCount() > 0) + { // We're only handling FirstChild and LastChild here - switch(navdir) { + switch (navdir) + { case AccessibleNavigation.FirstChild: return GetChild(0); case AccessibleNavigation.LastChild: @@ -7575,44 +8859,52 @@ public override AccessibleObject Navigate(AccessibleNavigation navdir) { } } - internal class GridPositionData { + internal class GridPositionData + { ArrayList expandedState; GridEntryCollection selectedItemTree; - int itemRow; - int itemCount; + int itemRow; + int itemCount; - public GridPositionData(PropertyGridView gridView) { + public GridPositionData(PropertyGridView gridView) + { selectedItemTree = gridView.GetGridEntryHierarchy(gridView.selectedGridEntry); expandedState = gridView.SaveHierarchyState(gridView.topLevelGridEntries); itemRow = gridView.selectedRow; itemCount = gridView.totalProps; } - public GridEntry Restore(PropertyGridView gridView) { - gridView.RestoreHierarchyState(expandedState); - GridEntry entry = gridView.FindEquivalentGridEntry(selectedItemTree); - - if (entry != null) { - gridView.SelectGridEntry(entry, true); - - int delta = gridView.selectedRow - itemRow; - if (delta != 0 && gridView.ScrollBar.Visible) { - if (itemRow < gridView.visibleRows) { - delta += gridView.GetScrollOffset(); - - if (delta < 0) { - delta = 0; - } - else if (delta > gridView.ScrollBar.Maximum) { - delta = gridView.ScrollBar.Maximum - 1; - } - gridView.SetScrollOffset(delta); + public GridEntry Restore(PropertyGridView gridView) + { + gridView.RestoreHierarchyState(expandedState); + GridEntry entry = gridView.FindEquivalentGridEntry(selectedItemTree); + + if (entry != null) + { + gridView.SelectGridEntry(entry, true); + + int delta = gridView.selectedRow - itemRow; + if (delta != 0 && gridView.ScrollBar.Visible) + { + if (itemRow < gridView.visibleRows) + { + delta += gridView.GetScrollOffset(); + + if (delta < 0) + { + delta = 0; + } + else if (delta > gridView.ScrollBar.Maximum) + { + delta = gridView.ScrollBar.Maximum - 1; } - + gridView.SetScrollOffset(delta); } + } - return entry; + } + return entry; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/SingleSelectRootGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/SingleSelectRootGridEntry.cs index 248d8c758b1..2f98e2988f1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/SingleSelectRootGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/SingleSelectRootGridEntry.cs @@ -3,14 +3,15 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms.PropertyGridInternal { +namespace System.Windows.Forms.PropertyGridInternal +{ using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System; using System.Collections; - using System.Reflection; + using System.Reflection; using System.ComponentModel.Design; using System.Windows.Forms; using System.Windows.Forms.Design; @@ -18,25 +19,27 @@ namespace System.Windows.Forms.PropertyGridInternal { using Microsoft.Win32; - internal class SingleSelectRootGridEntry : GridEntry, IRootGridEntry { - protected object objValue; + internal class SingleSelectRootGridEntry : GridEntry, IRootGridEntry + { + protected object objValue; protected string objValueClassName; - protected GridEntry propDefault; - protected IDesignerHost host; + protected GridEntry propDefault; + protected IDesignerHost host; protected IServiceProvider baseProvider = null; - protected PropertyTab tab = null; - protected PropertyGridView gridEntryHost = null; - protected AttributeCollection browsableAttributes = null; - private IComponentChangeService changeService; + protected PropertyTab tab = null; + protected PropertyGridView gridEntryHost = null; + protected AttributeCollection browsableAttributes = null; + private IComponentChangeService changeService; protected bool forceReadOnlyChecked; - + [ SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // GridEntry classes are internal so we have complete // control over who does what in the constructor. ] internal SingleSelectRootGridEntry(PropertyGridView gridEntryHost, object value, GridEntry parent, IServiceProvider baseProvider, IDesignerHost host, PropertyTab tab, PropertySort sortType) - : base(gridEntryHost.OwnerGrid, parent) { - Debug.Assert(value != null,"Can't browse a null object!"); + : base(gridEntryHost.OwnerGrid, parent) + { + Debug.Assert(value != null, "Can't browse a null object!"); this.host = host; this.gridEntryHost = gridEntryHost; this.baseProvider = baseProvider; @@ -54,102 +57,131 @@ internal SingleSelectRootGridEntry(PropertyGridView gridEntryHost, object value, SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // GridEntry classes are internal so we have complete // control over who does what in the constructor. ] - internal SingleSelectRootGridEntry(PropertyGridView view, object value, IServiceProvider baseProvider, IDesignerHost host, PropertyTab tab, PropertySort sortType) : this(view, value,null, baseProvider, host, tab, sortType) { - } + internal SingleSelectRootGridEntry(PropertyGridView view, object value, IServiceProvider baseProvider, IDesignerHost host, PropertyTab tab, PropertySort sortType) : this(view, value, null, baseProvider, host, tab, sortType) + { + } /// /// The set of attributes that will be used for browse filtering /// - public override AttributeCollection BrowsableAttributes { - get { - if (browsableAttributes == null) { - browsableAttributes = new AttributeCollection(new Attribute[]{BrowsableAttribute.Yes}); + public override AttributeCollection BrowsableAttributes + { + get + { + if (browsableAttributes == null) + { + browsableAttributes = new AttributeCollection(new Attribute[] { BrowsableAttribute.Yes }); } return this.browsableAttributes; } - set { - if (value == null) { + set + { + if (value == null) + { ResetBrowsableAttributes(); return; } bool same = true; - if (this.browsableAttributes != null && value != null && this.browsableAttributes.Count == value.Count) { + if (this.browsableAttributes != null && value != null && this.browsableAttributes.Count == value.Count) + { Attribute[] attr1 = new Attribute[browsableAttributes.Count]; Attribute[] attr2 = new Attribute[value.Count]; browsableAttributes.CopyTo(attr1, 0); value.CopyTo(attr2, 0); - + Array.Sort(attr1, GridEntry.AttributeTypeSorter); Array.Sort(attr2, GridEntry.AttributeTypeSorter); - for (int i = 0; i < attr1.Length; i++) { - if (!attr1[i].Equals(attr2[i])) { + for (int i = 0; i < attr1.Length; i++) + { + if (!attr1[i].Equals(attr2[i])) + { same = false; break; } } } - else { + else + { same = false; } this.browsableAttributes = value; - if (!same && Children != null && Children.Count > 0) { + if (!same && Children != null && Children.Count > 0) + { DisposeChildren(); } } } - - protected override IComponentChangeService ComponentChangeService { - get { - if (changeService == null) { + + protected override IComponentChangeService ComponentChangeService + { + get + { + if (changeService == null) + { changeService = (IComponentChangeService)GetService(typeof(IComponentChangeService)); - } - return changeService; + } + return changeService; } } - - internal override bool AlwaysAllowExpand { - get { - return true; + + internal override bool AlwaysAllowExpand + { + get + { + return true; } } - public override PropertyTab CurrentTab { - get { + public override PropertyTab CurrentTab + { + get + { return tab; } - set { + set + { this.tab = value; } } - internal override GridEntry DefaultChild { - get { + internal override GridEntry DefaultChild + { + get + { return propDefault; } - set { + set + { this.propDefault = value; } } - internal override IDesignerHost DesignerHost { - get { + internal override IDesignerHost DesignerHost + { + get + { return host; } - set { + set + { host = value; } } - internal override bool ForceReadOnly { - get { - if (!forceReadOnlyChecked) { + internal override bool ForceReadOnly + { + get + { + if (!forceReadOnlyChecked) + { ReadOnlyAttribute readOnlyAttr = (ReadOnlyAttribute)TypeDescriptor.GetAttributes(this.objValue)[typeof(ReadOnlyAttribute)]; - if ((readOnlyAttr != null && !readOnlyAttr.IsDefaultAttribute()) || TypeDescriptor.GetAttributes(this.objValue).Contains(InheritanceAttribute.InheritedReadOnly)) { + if ((readOnlyAttr != null && !readOnlyAttr.IsDefaultAttribute()) || TypeDescriptor.GetAttributes(this.objValue).Contains(InheritanceAttribute.InheritedReadOnly)) + { flags |= FLAG_FORCE_READONLY; } forceReadOnlyChecked = true; @@ -158,65 +190,82 @@ internal override bool ForceReadOnly { } } - internal override PropertyGridView GridEntryHost { - get { + internal override PropertyGridView GridEntryHost + { + get + { return this.gridEntryHost; } - set { + set + { this.gridEntryHost = value; } } - - public override GridItemType GridItemType { - get { + + public override GridItemType GridItemType + { + get + { return GridItemType.Root; } - } + } /// /// Retrieves the keyword that the VS help dynamic help window will /// use when this IPE is selected. /// - public override string HelpKeyword { - get { - - HelpKeywordAttribute helpAttribute = (HelpKeywordAttribute)TypeDescriptor.GetAttributes(objValue)[typeof(HelpKeywordAttribute)]; + public override string HelpKeyword + { + get + { + + HelpKeywordAttribute helpAttribute = (HelpKeywordAttribute)TypeDescriptor.GetAttributes(objValue)[typeof(HelpKeywordAttribute)]; - if (helpAttribute != null && !helpAttribute.IsDefaultAttribute()) { + if (helpAttribute != null && !helpAttribute.IsDefaultAttribute()) + { return helpAttribute.HelpKeyword; - } + } - return this.objValueClassName; + return this.objValueClassName; } } - public override string PropertyLabel { - get { - if (objValue is IComponent) { + public override string PropertyLabel + { + get + { + if (objValue is IComponent) + { ISite site = ((IComponent)objValue).Site; - if (site == null) { + if (site == null) + { return objValue.GetType().Name; } - else { + else + { return site.Name; } } - else if (objValue != null) { + else if (objValue != null) + { return objValue.ToString(); } return null; } } - + /// /// Gets or sets the value for the property that is represented /// by this GridEntry. /// - public override object PropertyValue{ - get { + public override object PropertyValue + { + get + { return objValue; } - set { + set + { object old = objValue; objValue = value; objValueClassName = TypeDescriptor.GetClassName(objValue); @@ -224,14 +273,17 @@ public override object PropertyValue{ } } - protected override bool CreateChildren() { + protected override bool CreateChildren() + { bool fReturn = base.CreateChildren(); CategorizePropEntries(); return fReturn; } - - protected override void Dispose(bool disposing) { - if (disposing) { + + protected override void Dispose(bool disposing) + { + if (disposing) + { host = null; baseProvider = null; tab = null; @@ -244,13 +296,16 @@ protected override void Dispose(bool disposing) { base.Dispose(disposing); } - public override object GetService(Type serviceType) { + public override object GetService(Type serviceType) + { object service = null; - - if (host != null) { + + if (host != null) + { service = host.GetService(serviceType); } - if (service == null && baseProvider != null) { + if (service == null && baseProvider != null) + { service = baseProvider.GetService(serviceType); } return service; @@ -259,39 +314,48 @@ public override object GetService(Type serviceType) { /// /// Reset the Browsable attributes to the default (BrowsableAttribute.Yes) /// - public void ResetBrowsableAttributes() { - this.browsableAttributes = new AttributeCollection(new Attribute[]{BrowsableAttribute.Yes}); + public void ResetBrowsableAttributes() + { + this.browsableAttributes = new AttributeCollection(new Attribute[] { BrowsableAttribute.Yes }); } /// /// Sets the value of this GridEntry from text /// - public virtual void ShowCategories(bool fCategories) { - if (((this.PropertySort &= PropertySort.Categorized) !=0) != fCategories) { - - if (fCategories) { - this.PropertySort |= PropertySort.Categorized; + public virtual void ShowCategories(bool fCategories) + { + if (((this.PropertySort &= PropertySort.Categorized) != 0) != fCategories) + { + + if (fCategories) + { + this.PropertySort |= PropertySort.Categorized; } - else { - this.PropertySort &= ~PropertySort.Categorized; + else + { + this.PropertySort &= ~PropertySort.Categorized; } - - + + // recreate the children - if (this.Expandable && this.ChildCollection != null) { + if (this.Expandable && this.ChildCollection != null) + { CreateChildren(); } } } - internal void CategorizePropEntries() { - if (Children.Count > 0) { - + internal void CategorizePropEntries() + { + if (Children.Count > 0) + { + GridEntry[] childEntries = new GridEntry[this.Children.Count]; this.Children.CopyTo(childEntries, 0); - - if ((this.PropertySort & PropertySort.Categorized) != 0) { + + if ((this.PropertySort & PropertySort.Categorized) != 0) + { // first, walk through all the entires and @@ -299,18 +363,21 @@ internal void CategorizePropEntries() { // them to a hashtable of arraylists. // Hashtable bins = new Hashtable(); - for (int i = 0; i < childEntries.Length; i++) { + for (int i = 0; i < childEntries.Length; i++) + { GridEntry pe = childEntries[i]; - Debug.Assert(pe != null); - if (pe != null) { - string category = pe.PropertyCategory; - ArrayList bin = (ArrayList)bins[category]; - if (bin == null) { - bin = new ArrayList(); - bins[category] = bin; - } - bin.Add(pe); - } + Debug.Assert(pe != null); + if (pe != null) + { + string category = pe.PropertyCategory; + ArrayList bin = (ArrayList)bins[category]; + if (bin == null) + { + bin = new ArrayList(); + bins[category] = bin; + } + bin.Add(pe); + } } // now walk through the hashtable @@ -320,17 +387,22 @@ internal void CategorizePropEntries() { // ArrayList propList = new ArrayList(); IDictionaryEnumerator enumBins = (IDictionaryEnumerator)bins.GetEnumerator(); - while (enumBins.MoveNext()) { + while (enumBins.MoveNext()) + { ArrayList bin = (ArrayList)enumBins.Value; - if (bin != null) { + if (bin != null) + { string category = (string)enumBins.Key; - if (bin.Count > 0) { + if (bin.Count > 0) + { GridEntry[] rgpes = new GridEntry[bin.Count]; bin.CopyTo(rgpes, 0); - try { + try + { propList.Add(new CategoryGridEntry(this.ownerGrid, this, category, rgpes)); } - catch { + catch + { } } } @@ -339,11 +411,11 @@ internal void CategorizePropEntries() { childEntries = new GridEntry[propList.Count]; propList.CopyTo(childEntries, 0); StringSorter.Sort(childEntries); - + ChildCollection.Clear(); ChildCollection.AddRange(childEntries); - } - } + } + } } - } + } } 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 35647f0ef77..59562ee5fe6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyStore.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyStore.cs @@ -139,7 +139,7 @@ public Rectangle GetRectangle(int key, out bool found) /// This will set value to zero and return false if the /// list does not contain the given key. /// - public int GetInteger(int key) => GetInteger(key, out _); + public int GetInteger(int key) => GetInteger(key, out _); /// /// Retrieves an integer value from our property list. @@ -448,7 +448,7 @@ private bool LocateObjectEntry(short entryKey, out int index) { index++; } - + return false; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyTabChangedEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyTabChangedEventArgs.cs index 9f832ea67b6..c83c4001f1f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyTabChangedEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyTabChangedEventArgs.cs @@ -15,9 +15,9 @@ public PropertyTabChangedEventArgs(PropertyTab oldTab, PropertyTab newTab) OldTab = oldTab; NewTab = newTab; } - + public PropertyTab OldTab { get; } - + public PropertyTab NewTab { get; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyValueChangedEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyValueChangedEventArgs.cs index c69ca0f6cd4..bef013b0667 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyValueChangedEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyValueChangedEventArgs.cs @@ -19,7 +19,7 @@ public PropertyValueChangedEventArgs(GridItem changedItem, object oldValue) } public GridItem ChangedItem { get; } - + public object OldValue { get; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/QueryAccessibilityHelpEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/QueryAccessibilityHelpEventArgs.cs index 4e4953ca222..5a4a0ef0b6b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/QueryAccessibilityHelpEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/QueryAccessibilityHelpEventArgs.cs @@ -11,7 +11,7 @@ namespace System.Windows.Forms /// to accessibility applications. /// [ComVisible(true)] - public class QueryAccessibilityHelpEventArgs : EventArgs + public class QueryAccessibilityHelpEventArgs : EventArgs { public QueryAccessibilityHelpEventArgs() { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs index 0d2fa1f48d7..1cc1525e29e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.InteropServices; using System.Diagnostics; @@ -38,17 +39,18 @@ namespace System.Windows.Forms { Designer("System.Windows.Forms.Design.RadioButtonDesigner, " + AssemblyRef.SystemDesign), SRDescription(nameof(SR.DescriptionRadioButton)) ] - public class RadioButton : ButtonBase { + public class RadioButton : ButtonBase + { private static readonly object EVENT_CHECKEDCHANGED = new object(); - private static readonly ContentAlignment anyRight = ContentAlignment.TopRight | ContentAlignment.MiddleRight | ContentAlignment.BottomRight; + private static readonly ContentAlignment anyRight = ContentAlignment.TopRight | ContentAlignment.MiddleRight | ContentAlignment.BottomRight; // Used to see if we need to iterate through the autochecked items and modify their tabstops. private bool firstfocus = true; private bool isChecked; private bool autoCheck = true; private ContentAlignment checkAlign = ContentAlignment.MiddleLeft; - private Appearance appearance = System.Windows.Forms.Appearance.Normal; + private Appearance appearance = System.Windows.Forms.Appearance.Normal; private const int FlatSystemStylePaddingWidth = 24; private const int FlatSystemStyleMinimumHeight = 13; @@ -62,8 +64,10 @@ public class RadioButton : ButtonBase { /// class. /// /// - public RadioButton() : base() { - if (DpiHelper.IsScalingRequirementMet) { + public RadioButton() : base() + { + if (DpiHelper.IsScalingRequirementMet) + { flatSystemStylePaddingWidth = LogicalToDeviceUnits(FlatSystemStylePaddingWidth); flatSystemStyleMinimumHeight = LogicalToDeviceUnits(FlatSystemStyleMinimumHeight); } @@ -86,13 +90,17 @@ public RadioButton() : base() { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.RadioButtonAutoCheckDescr)) ] - public bool AutoCheck { - get { + public bool AutoCheck + { + get + { return autoCheck; } - set { - if (autoCheck != value) { + set + { + if (autoCheck != value) + { autoCheck = value; PerformAutoUpdates(false); } @@ -112,27 +120,35 @@ public bool AutoCheck { Localizable(true), SRDescription(nameof(SR.RadioButtonAppearanceDescr)) ] - public Appearance Appearance { - get { + public Appearance Appearance + { + get + { return appearance; } - set { - if (appearance != value) { + set + { + if (appearance != value) + { //valid values are 0x0 to 0x1 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)Appearance.Normal, (int)Appearance.Button)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)Appearance.Normal, (int)Appearance.Button)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(Appearance)); } - using (LayoutTransaction.CreateTransactionIf(AutoSize, this.ParentInternal, this, PropertyNames.Appearance)) { + using (LayoutTransaction.CreateTransactionIf(AutoSize, this.ParentInternal, this, PropertyNames.Appearance)) + { appearance = value; - if (OwnerDraw) { + if (OwnerDraw) + { Refresh(); } - else { + else + { UpdateStyles(); } - + OnAppearanceChanged(EventArgs.Empty); } } @@ -142,7 +158,8 @@ public Appearance Appearance { private static readonly object EVENT_APPEARANCECHANGED = new object(); [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.RadioButtonOnAppearanceChangedDescr))] - public event EventHandler AppearanceChanged { + public event EventHandler AppearanceChanged + { add => Events.AddHandler(EVENT_APPEARANCECHANGED, value); remove => Events.RemoveHandler(EVENT_APPEARANCECHANGED, value); @@ -162,20 +179,26 @@ public event EventHandler AppearanceChanged { DefaultValue(ContentAlignment.MiddleLeft), SRDescription(nameof(SR.RadioButtonCheckAlignDescr)) ] - public ContentAlignment CheckAlign { - get { + public ContentAlignment CheckAlign + { + get + { return checkAlign; } - set { - if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) { + set + { + if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ContentAlignment)); } checkAlign = value; - if (OwnerDraw) { + if (OwnerDraw) + { Invalidate(); } - else { + else + { UpdateStyles(); } } @@ -195,16 +218,21 @@ public ContentAlignment CheckAlign { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.RadioButtonCheckedDescr)) ] - public bool Checked { - get { + public bool Checked + { + get + { return isChecked; } - set { - if (isChecked != value) { + set + { + if (isChecked != value) + { isChecked = value; - if (IsHandleCreated) SendMessage(NativeMethods.BM_SETCHECK, value? 1: 0, 0); + if (IsHandleCreated) + SendMessage(NativeMethods.BM_SETCHECK, value ? 1 : 0, 0); Invalidate(); Update(); PerformAutoUpdates(false); @@ -215,50 +243,60 @@ public bool Checked { /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler DoubleClick { + public new event EventHandler DoubleClick + { add => base.DoubleClick += value; remove => base.DoubleClick -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event MouseEventHandler MouseDoubleClick { + public new event MouseEventHandler MouseDoubleClick + { add => base.MouseDoubleClick += value; remove => base.MouseDoubleClick -= value; } /// /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ClassName = "BUTTON"; - if (OwnerDraw) { + if (OwnerDraw) + { cp.Style |= NativeMethods.BS_OWNERDRAW; } - else { + else + { cp.Style |= NativeMethods.BS_RADIOBUTTON; - if (Appearance == Appearance.Button) { + if (Appearance == Appearance.Button) + { cp.Style |= NativeMethods.BS_PUSHLIKE; } - + // Determine the alignment of the radio button // - ContentAlignment align = RtlTranslateContent(CheckAlign); - if ((int)(align & anyRight) != 0) { + ContentAlignment align = RtlTranslateContent(CheckAlign); + if ((int)(align & anyRight) != 0) + { cp.Style |= NativeMethods.BS_RIGHTBUTTON; } } return cp; } } - + /// /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(104, 24); } } @@ -272,17 +310,21 @@ protected override Size DefaultSize { /// /// Old DPI value /// New DPI value - protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) { + protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) + { base.RescaleConstantsForDpi(deviceDpiOld, deviceDpiNew); - if (DpiHelper.IsScalingRequirementMet) { + if (DpiHelper.IsScalingRequirementMet) + { flatSystemStylePaddingWidth = LogicalToDeviceUnits(FlatSystemStylePaddingWidth); flatSystemStyleMinimumHeight = LogicalToDeviceUnits(FlatSystemStyleMinimumHeight); } } - internal override Size GetPreferredSizeCore(Size proposedConstraints) { - if(FlatStyle != FlatStyle.System) { + internal override Size GetPreferredSizeCore(Size proposedConstraints) + { + if (FlatStyle != FlatStyle.System) + { return base.GetPreferredSizeCore(proposedConstraints); } @@ -290,44 +332,57 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) { Size size = SizeFromClientSize(textSize); size.Width += flatSystemStylePaddingWidth; size.Height = DpiHelper.IsScalingRequirementMet ? Math.Max(size.Height + 5, flatSystemStyleMinimumHeight) : size.Height + 5; // ensure minimum height to avoid truncation of RadioButton circle or text - return size; + return size; } - internal override Rectangle OverChangeRectangle { - get { - if (Appearance == Appearance.Button) { + internal override Rectangle OverChangeRectangle + { + get + { + if (Appearance == Appearance.Button) + { return base.OverChangeRectangle; } - else { - if (FlatStyle == FlatStyle.Standard) { + else + { + if (FlatStyle == FlatStyle.Standard) + { // this Rectangle will cause no Invalidation // can't use Rectangle.Empty because it will cause Invalidate(ClientRectangle) return new Rectangle(-1, -1, 1, 1); } - else { + else + { return Adapter.CommonLayout().Layout().checkBounds; } } } } - internal override Rectangle DownChangeRectangle { - get { - if (Appearance == Appearance.Button || FlatStyle == FlatStyle.System) { + internal override Rectangle DownChangeRectangle + { + get + { + if (Appearance == Appearance.Button || FlatStyle == FlatStyle.System) + { return base.DownChangeRectangle; } - else { + else + { return Adapter.CommonLayout().Layout().checkBounds; } } } [DefaultValue(false)] - new public bool TabStop { - get { + new public bool TabStop + { + get + { return base.TabStop; } - set { + set + { base.TabStop = value; } } @@ -343,11 +398,14 @@ internal override Rectangle DownChangeRectangle { Localizable(true), DefaultValue(ContentAlignment.MiddleLeft) ] - public override ContentAlignment TextAlign { - get { + public override ContentAlignment TextAlign + { + get + { return base.TextAlign; } - set { + set + { base.TextAlign = value; } } @@ -360,7 +418,8 @@ public override ContentAlignment TextAlign { /// /// [SRDescription(nameof(SR.RadioButtonOnCheckedChangedDescr))] - public event EventHandler CheckedChanged { + public event EventHandler CheckedChanged + { add => Events.AddHandler(EVENT_CHECKEDCHANGED, value); remove => Events.RemoveHandler(EVENT_CHECKEDCHANGED, value); } @@ -371,19 +430,22 @@ public event EventHandler CheckedChanged { /// should not call base.CreateAccessibilityObject. /// /// - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new RadioButtonAccessibleObject(this); } /// /// - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { base.OnHandleCreated(e); //Since this is protected override, this can be called directly in a overriden class //and the handle doesn't need to be created. //So check for the handle to improve performance - if (IsHandleCreated) { - SendMessage(NativeMethods.BM_SETCHECK, isChecked? 1: 0, 0); + if (IsHandleCreated) + { + SendMessage(NativeMethods.BM_SETCHECK, isChecked ? 1 : 0, 0); } } @@ -393,18 +455,22 @@ protected override void OnHandleCreated(EventArgs e) { /// event. /// /// - protected virtual void OnCheckedChanged(EventArgs e) { + protected virtual void OnCheckedChanged(EventArgs e) + { AccessibilityNotifyClients(AccessibleEvents.StateChange, -1); AccessibilityNotifyClients(AccessibleEvents.NameChange, -1); EventHandler handler = (EventHandler)Events[EVENT_CHECKEDCHANGED]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// We override this to implement the autoCheck functionality. /// - protected override void OnClick(EventArgs e) { - if (autoCheck) { + protected override void OnClick(EventArgs e) + { + if (autoCheck) + { Checked = true; } base.OnClick(e); @@ -412,21 +478,26 @@ protected override void OnClick(EventArgs e) { /// /// - protected override void OnEnter(EventArgs e) { + protected override void OnEnter(EventArgs e) + { // Just like the Win32 RadioButton, fire a click if the // user arrows onto the control.. // - if (MouseButtons == MouseButtons.None) { - if (UnsafeNativeMethods.GetKeyState((int)Keys.Tab) >= 0) { + if (MouseButtons == MouseButtons.None) + { + if (UnsafeNativeMethods.GetKeyState((int)Keys.Tab) >= 0) + { //We enter the radioButton by using arrow keys //Paint in raised state... // ResetFlagsandPaint(); - if(!ValidationCancelled){ + if (!ValidationCancelled) + { OnClick(e); } } - else { + else + { //we enter the radioButton by pressing Tab PerformAutoUpdates(true); //reset the TabStop so we can come back later @@ -440,21 +511,29 @@ protected override void OnEnter(EventArgs e) { /// /// - private void PerformAutoUpdates(bool tabbedInto) { - if (autoCheck) { - if (firstfocus) { + private void PerformAutoUpdates(bool tabbedInto) + { + if (autoCheck) + { + if (firstfocus) + { WipeTabStops(tabbedInto); } TabStop = isChecked; - if (isChecked) { + if (isChecked) + { Control parent = ParentInternal; - if (parent != null) { + if (parent != null) + { Control.ControlCollection children = parent.Controls; - for (int i = 0; i < children.Count; i++) { + for (int i = 0; i < children.Count; i++) + { Control ctl = children[i]; - if (ctl != this && ctl is RadioButton) { + if (ctl != this && ctl is RadioButton) + { RadioButton button = (RadioButton)ctl; - if (button.autoCheck && button.Checked) { + if (button.autoCheck && button.Checked) + { PropertyDescriptor propDesc = TypeDescriptor.GetProperties(this)["Checked"]; propDesc.SetValue(button, false); } @@ -468,18 +547,24 @@ private void PerformAutoUpdates(bool tabbedInto) { /// /// Removes tabstops from all radio buttons, other than the one that currently has the focus. /// - private void WipeTabStops(bool tabbedInto) { - Control parent = ParentInternal; - if (parent != null) { + private void WipeTabStops(bool tabbedInto) + { + Control parent = ParentInternal; + if (parent != null) + { Control.ControlCollection children = parent.Controls; - for (int i = 0; i < children.Count; i++) { + for (int i = 0; i < children.Count; i++) + { Control ctl = children[i]; - if (ctl is RadioButton) { - RadioButton button = (RadioButton) ctl; - if (!tabbedInto) { + if (ctl is RadioButton) + { + RadioButton button = (RadioButton)ctl; + if (!tabbedInto) + { button.firstfocus = false; } - if (button.autoCheck) { + if (button.autoCheck) + { button.TabStop = false; } } @@ -487,21 +572,26 @@ private void WipeTabStops(bool tabbedInto) { } } - internal override ButtonBaseAdapter CreateFlatAdapter() { + internal override ButtonBaseAdapter CreateFlatAdapter() + { return new RadioButtonFlatAdapter(this); } - internal override ButtonBaseAdapter CreatePopupAdapter() { + internal override ButtonBaseAdapter CreatePopupAdapter() + { return new RadioButtonPopupAdapter(this); } - - internal override ButtonBaseAdapter CreateStandardAdapter() { + + internal override ButtonBaseAdapter CreateStandardAdapter() + { return new RadioButtonStandardAdapter(this); } - private void OnAppearanceChanged(EventArgs e) { + private void OnAppearanceChanged(EventArgs e) + { EventHandler eh = Events[EVENT_APPEARANCECHANGED] as EventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); } } @@ -512,19 +602,24 @@ private void OnAppearanceChanged(EventArgs e) { /// /// /// - protected override void OnMouseUp(MouseEventArgs mevent) { - if (mevent.Button == MouseButtons.Left && GetStyle(ControlStyles.UserPaint)) { - if (base.MouseIsDown) { + protected override void OnMouseUp(MouseEventArgs mevent) + { + if (mevent.Button == MouseButtons.Left && GetStyle(ControlStyles.UserPaint)) + { + if (base.MouseIsDown) + { Point pt = PointToScreen(new Point(mevent.X, mevent.Y)); - if (UnsafeNativeMethods.WindowFromPoint(pt.X, pt.Y) == Handle) { + if (UnsafeNativeMethods.WindowFromPoint(pt.X, pt.Y) == Handle) + { //Paint in raised state... // ResetFlagsandPaint(); - if (!ValidationCancelled) { + if (!ValidationCancelled) + { OnClick(mevent); OnMouseClick(mevent); } - + } } } @@ -537,26 +632,33 @@ protected override void OnMouseUp(MouseEventArgs mevent) { /// button, simulating a click by a user. /// /// - public void PerformClick() { - if (CanSelect) { + public void PerformClick() + { + if (CanSelect) + { //Paint in raised state... // ResetFlagsandPaint(); - if (!ValidationCancelled) { + if (!ValidationCancelled) + { OnClick(EventArgs.Empty); } } - + } /// /// - protected internal override bool ProcessMnemonic(char charCode) { - if (UseMnemonic && IsMnemonic(charCode, Text) && CanSelect) { - if (!Focused) { + protected internal override bool ProcessMnemonic(char charCode) + { + if (UseMnemonic && IsMnemonic(charCode, Text) && CanSelect) + { + if (!Focused) + { Focus(); // This will cause an OnEnter event, which in turn will fire the click event } - else { + else + { PerformClick(); // Generate a click if already focused } return true; @@ -567,7 +669,8 @@ protected internal override bool ProcessMnemonic(char charCode) { /// /// Returns a string representation for this control. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); return s + ", Checked: " + Checked.ToString(); @@ -575,16 +678,21 @@ public override string ToString() { /// /// - [System.Runtime.InteropServices.ComVisible(true)] - public class RadioButtonAccessibleObject : ButtonBaseAccessibleObject { + [System.Runtime.InteropServices.ComVisible(true)] + public class RadioButtonAccessibleObject : ButtonBaseAccessibleObject + { - public RadioButtonAccessibleObject(RadioButton owner) : base(owner) { + public RadioButtonAccessibleObject(RadioButton owner) : base(owner) + { } - public override string DefaultAction { - get { + public override string DefaultAction + { + get + { string defaultAction = Owner.AccessibleDefaultActionDescription; - if (defaultAction != null) { + if (defaultAction != null) + { return defaultAction; } @@ -592,26 +700,33 @@ public override string DefaultAction { } } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { AccessibleRole role = Owner.AccessibleRole; - if (role != AccessibleRole.Default) { + if (role != AccessibleRole.Default) + { return role; } return AccessibleRole.RadioButton; } } - public override AccessibleStates State { - get { - if (((RadioButton)Owner).Checked) { + public override AccessibleStates State + { + get + { + if (((RadioButton)Owner).Checked) + { return AccessibleStates.Checked | base.State; } return base.State; } } - public override void DoDefaultAction() { + public override void DoDefaultAction() + { ((RadioButton)Owner).PerformClick(); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RadioButtonRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RadioButtonRenderer.cs index 01000eeb64b..dd2731edb9f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RadioButtonRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RadioButtonRenderer.cs @@ -2,14 +2,15 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ -using System; -using System.Drawing; -using System.Diagnostics.CodeAnalysis; -using System.Windows.Forms.Internal; -using System.Windows.Forms.VisualStyles; -using Microsoft.Win32; + using System; + using System.Drawing; + using System.Diagnostics.CodeAnalysis; + using System.Windows.Forms.Internal; + using System.Windows.Forms.VisualStyles; + using Microsoft.Win32; /// /// @@ -17,147 +18,170 @@ namespace System.Windows.Forms { /// without visual styles applied.) /// /// - public sealed class RadioButtonRenderer { + public sealed class RadioButtonRenderer + { - //Make this per-thread, so that different threads can safely use these methods. - [ThreadStatic] - private static VisualStyleRenderer visualStyleRenderer = null; - private static readonly VisualStyleElement RadioElement = VisualStyleElement.Button.RadioButton.UncheckedNormal; + //Make this per-thread, so that different threads can safely use these methods. + [ThreadStatic] + private static VisualStyleRenderer visualStyleRenderer = null; + private static readonly VisualStyleElement RadioElement = VisualStyleElement.Button.RadioButton.UncheckedNormal; private static bool renderMatchingApplicationState = true; - //cannot instantiate - private RadioButtonRenderer() { - } - - /// - /// - /// If this property is true, then the renderer will use the setting from Application.RenderWithVisualStyles to - /// determine how to render. - /// If this property is false, the renderer will always render with visualstyles. - /// - /// - public static bool RenderMatchingApplicationState { - get { - return renderMatchingApplicationState; - } - set { - renderMatchingApplicationState = value; - } - } - - private static bool RenderWithVisualStyles { - get { - return (!renderMatchingApplicationState || Application.RenderWithVisualStyles); - } - } - - /// - /// - /// Returns true if the background corresponding to the given state is partially transparent, else false. - /// - /// - public static bool IsBackgroundPartiallyTransparent(RadioButtonState state) { - if (RenderWithVisualStyles) { - InitializeRenderer((int)state); - - return visualStyleRenderer.IsBackgroundPartiallyTransparent(); - } - else { - return false; //for downlevel, this is false - } - } - - /// - /// - /// This is just a convenience wrapper for VisualStyleRenderer.DrawThemeParentBackground. For downlevel, - /// this isn't required and does nothing. - /// - /// - [ - SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally - ] - public static void DrawParentBackground(Graphics g, Rectangle bounds, Control childControl) { - if (RenderWithVisualStyles) { - InitializeRenderer(0); - - visualStyleRenderer.DrawParentBackground(g, bounds, childControl); - } - } + //cannot instantiate + private RadioButtonRenderer() + { + } + + /// + /// + /// If this property is true, then the renderer will use the setting from Application.RenderWithVisualStyles to + /// determine how to render. + /// If this property is false, the renderer will always render with visualstyles. + /// + /// + public static bool RenderMatchingApplicationState + { + get + { + return renderMatchingApplicationState; + } + set + { + renderMatchingApplicationState = value; + } + } + + private static bool RenderWithVisualStyles + { + get + { + return (!renderMatchingApplicationState || Application.RenderWithVisualStyles); + } + } + + /// + /// + /// Returns true if the background corresponding to the given state is partially transparent, else false. + /// + /// + public static bool IsBackgroundPartiallyTransparent(RadioButtonState state) + { + if (RenderWithVisualStyles) + { + InitializeRenderer((int)state); + + return visualStyleRenderer.IsBackgroundPartiallyTransparent(); + } + else + { + return false; //for downlevel, this is false + } + } + + /// + /// + /// This is just a convenience wrapper for VisualStyleRenderer.DrawThemeParentBackground. For downlevel, + /// this isn't required and does nothing. + /// + /// + [ + SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally + ] + public static void DrawParentBackground(Graphics g, Rectangle bounds, Control childControl) + { + if (RenderWithVisualStyles) + { + InitializeRenderer(0); + + visualStyleRenderer.DrawParentBackground(g, bounds, childControl); + } + } /// /// /// Renders a RadioButton control. /// /// - public static void DrawRadioButton(Graphics g, Point glyphLocation, RadioButtonState state) { + public static void DrawRadioButton(Graphics g, Point glyphLocation, RadioButtonState state) + { DrawRadioButton(g, glyphLocation, state, IntPtr.Zero); } - internal static void DrawRadioButton(Graphics g, Point glyphLocation, RadioButtonState state, IntPtr hWnd) { - Rectangle glyphBounds = new Rectangle(glyphLocation, GetGlyphSize(g, state, hWnd)); - - if (RenderWithVisualStyles) { - InitializeRenderer((int)state); - - visualStyleRenderer.DrawBackground(g, glyphBounds, hWnd); - } - else { - ControlPaint.DrawRadioButton(g, glyphBounds, ConvertToButtonState(state)); - } - } - - /// - /// - /// Renders a RadioButton control. - /// - /// - public static void DrawRadioButton(Graphics g, Point glyphLocation, Rectangle textBounds, string radioButtonText, Font font, bool focused, RadioButtonState state) { - DrawRadioButton(g, glyphLocation, textBounds, radioButtonText, font, - TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine, - focused, state); - } + internal static void DrawRadioButton(Graphics g, Point glyphLocation, RadioButtonState state, IntPtr hWnd) + { + Rectangle glyphBounds = new Rectangle(glyphLocation, GetGlyphSize(g, state, hWnd)); + + if (RenderWithVisualStyles) + { + InitializeRenderer((int)state); + + visualStyleRenderer.DrawBackground(g, glyphBounds, hWnd); + } + else + { + ControlPaint.DrawRadioButton(g, glyphBounds, ConvertToButtonState(state)); + } + } + + /// + /// + /// Renders a RadioButton control. + /// + /// + public static void DrawRadioButton(Graphics g, Point glyphLocation, Rectangle textBounds, string radioButtonText, Font font, bool focused, RadioButtonState state) + { + DrawRadioButton(g, glyphLocation, textBounds, radioButtonText, font, + TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine, + focused, state); + } /// /// /// Renders a RadioButton control. /// /// - public static void DrawRadioButton(Graphics g, Point glyphLocation, Rectangle textBounds, string radioButtonText, Font font, TextFormatFlags flags, bool focused, RadioButtonState state) { + public static void DrawRadioButton(Graphics g, Point glyphLocation, Rectangle textBounds, string radioButtonText, Font font, TextFormatFlags flags, bool focused, RadioButtonState state) + { DrawRadioButton(g, glyphLocation, textBounds, radioButtonText, font, flags, focused, state, IntPtr.Zero); } - internal static void DrawRadioButton(Graphics g, Point glyphLocation, Rectangle textBounds, string radioButtonText, Font font, TextFormatFlags flags, bool focused, RadioButtonState state, IntPtr hWnd) { - Rectangle glyphBounds = new Rectangle(glyphLocation, GetGlyphSize(g, state, hWnd)); - Color textColor; - - if (RenderWithVisualStyles) { - InitializeRenderer((int)state); - - visualStyleRenderer.DrawBackground(g, glyphBounds); - textColor = visualStyleRenderer.GetColor(ColorProperty.TextColor); - } - else { - ControlPaint.DrawRadioButton(g, glyphBounds, ConvertToButtonState(state)); - textColor = SystemColors.ControlText; - } - - TextRenderer.DrawText(g, radioButtonText, font, textBounds, textColor, flags); - - if (focused) { - ControlPaint.DrawFocusRectangle(g, textBounds); - } - } - - /// - /// - /// Renders a RadioButton control. - /// - /// - public static void DrawRadioButton(Graphics g, Point glyphLocation, Rectangle textBounds, string radioButtonText, Font font, Image image, Rectangle imageBounds, bool focused, RadioButtonState state) { - DrawRadioButton(g, glyphLocation, textBounds, radioButtonText, font, - TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine, - image, imageBounds, focused, state); - } + internal static void DrawRadioButton(Graphics g, Point glyphLocation, Rectangle textBounds, string radioButtonText, Font font, TextFormatFlags flags, bool focused, RadioButtonState state, IntPtr hWnd) + { + Rectangle glyphBounds = new Rectangle(glyphLocation, GetGlyphSize(g, state, hWnd)); + Color textColor; + + if (RenderWithVisualStyles) + { + InitializeRenderer((int)state); + + visualStyleRenderer.DrawBackground(g, glyphBounds); + textColor = visualStyleRenderer.GetColor(ColorProperty.TextColor); + } + else + { + ControlPaint.DrawRadioButton(g, glyphBounds, ConvertToButtonState(state)); + textColor = SystemColors.ControlText; + } + + TextRenderer.DrawText(g, radioButtonText, font, textBounds, textColor, flags); + + if (focused) + { + ControlPaint.DrawFocusRectangle(g, textBounds); + } + } + + /// + /// + /// Renders a RadioButton control. + /// + /// + public static void DrawRadioButton(Graphics g, Point glyphLocation, Rectangle textBounds, string radioButtonText, Font font, Image image, Rectangle imageBounds, bool focused, RadioButtonState state) + { + DrawRadioButton(g, glyphLocation, textBounds, radioButtonText, font, + TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine, + image, imageBounds, focused, state); + } @@ -166,119 +190,142 @@ public static void DrawRadioButton(Graphics g, Point glyphLocation, Rectangle te /// Renders a RadioButton control. /// /// - public static void DrawRadioButton(Graphics g, Point glyphLocation, Rectangle textBounds, string radioButtonText, Font font, TextFormatFlags flags, Image image, Rectangle imageBounds, bool focused, RadioButtonState state) { + public static void DrawRadioButton(Graphics g, Point glyphLocation, Rectangle textBounds, string radioButtonText, Font font, TextFormatFlags flags, Image image, Rectangle imageBounds, bool focused, RadioButtonState state) + { DrawRadioButton(g, glyphLocation, textBounds, radioButtonText, font, flags, image, imageBounds, focused, state, IntPtr.Zero); } - internal static void DrawRadioButton(Graphics g, Point glyphLocation, Rectangle textBounds, string radioButtonText, Font font, TextFormatFlags flags, Image image, Rectangle imageBounds, bool focused, RadioButtonState state, IntPtr hWnd) { - Rectangle glyphBounds = new Rectangle(glyphLocation, GetGlyphSize(g, state, hWnd)); - Color textColor; - - if (RenderWithVisualStyles) { - InitializeRenderer((int)state); - - //Keep this drawing order! It matches default drawing order. - visualStyleRenderer.DrawImage(g, imageBounds, image); - visualStyleRenderer.DrawBackground(g, glyphBounds); - textColor = visualStyleRenderer.GetColor(ColorProperty.TextColor); - } - else { - g.DrawImage(image, imageBounds); - ControlPaint.DrawRadioButton(g, glyphBounds, ConvertToButtonState(state)); - textColor = SystemColors.ControlText; - } - - TextRenderer.DrawText(g, radioButtonText, font, textBounds, textColor, flags); - - if (focused) { - ControlPaint.DrawFocusRectangle(g, textBounds); - } - } - - /// - /// - /// Returns the size of the RadioButton glyph. - /// - /// - [ - SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally - ] - public static Size GetGlyphSize(Graphics g, RadioButtonState state) { - return GetGlyphSize(g, state, IntPtr.Zero); - } - - internal static Size GetGlyphSize(Graphics g, RadioButtonState state, IntPtr hWnd) { - if (RenderWithVisualStyles) { - InitializeRenderer((int)state); - - return visualStyleRenderer.GetPartSize(g, ThemeSizeType.Draw, hWnd); - } - - return new Size(13, 13); - } - - internal static ButtonState ConvertToButtonState(RadioButtonState state) { - switch (state) { - case RadioButtonState.CheckedNormal: - case RadioButtonState.CheckedHot: - return ButtonState.Checked; - case RadioButtonState.CheckedPressed: - return (ButtonState.Checked | ButtonState.Pushed); - case RadioButtonState.CheckedDisabled: - return (ButtonState.Checked | ButtonState.Inactive); - - case RadioButtonState.UncheckedPressed: - return ButtonState.Pushed; - case RadioButtonState.UncheckedDisabled: - return ButtonState.Inactive; - - default: - return ButtonState.Normal; - } - } - - internal static RadioButtonState ConvertFromButtonState(ButtonState state, bool isHot) { - if ((state & ButtonState.Checked) == ButtonState.Checked) { - if ((state & ButtonState.Pushed) == ButtonState.Pushed) { - return RadioButtonState.CheckedPressed; - } - else if ((state & ButtonState.Inactive) == ButtonState.Inactive) { - return RadioButtonState.CheckedDisabled; - } - else if (isHot) { - return RadioButtonState.CheckedHot; - } - - return RadioButtonState.CheckedNormal; - } - else { //unchecked - if ((state & ButtonState.Pushed) == ButtonState.Pushed) { - return RadioButtonState.UncheckedPressed; - } - else if ((state & ButtonState.Inactive) == ButtonState.Inactive) { - return RadioButtonState.UncheckedDisabled; - } - else if (isHot) { - return RadioButtonState.UncheckedHot; - } - - return RadioButtonState.UncheckedNormal; - } - } - - private static void InitializeRenderer(int state) { + internal static void DrawRadioButton(Graphics g, Point glyphLocation, Rectangle textBounds, string radioButtonText, Font font, TextFormatFlags flags, Image image, Rectangle imageBounds, bool focused, RadioButtonState state, IntPtr hWnd) + { + Rectangle glyphBounds = new Rectangle(glyphLocation, GetGlyphSize(g, state, hWnd)); + Color textColor; + + if (RenderWithVisualStyles) + { + InitializeRenderer((int)state); + + //Keep this drawing order! It matches default drawing order. + visualStyleRenderer.DrawImage(g, imageBounds, image); + visualStyleRenderer.DrawBackground(g, glyphBounds); + textColor = visualStyleRenderer.GetColor(ColorProperty.TextColor); + } + else + { + g.DrawImage(image, imageBounds); + ControlPaint.DrawRadioButton(g, glyphBounds, ConvertToButtonState(state)); + textColor = SystemColors.ControlText; + } + + TextRenderer.DrawText(g, radioButtonText, font, textBounds, textColor, flags); + + if (focused) + { + ControlPaint.DrawFocusRectangle(g, textBounds); + } + } + + /// + /// + /// Returns the size of the RadioButton glyph. + /// + /// + [ + SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally + ] + public static Size GetGlyphSize(Graphics g, RadioButtonState state) + { + return GetGlyphSize(g, state, IntPtr.Zero); + } + + internal static Size GetGlyphSize(Graphics g, RadioButtonState state, IntPtr hWnd) + { + if (RenderWithVisualStyles) + { + InitializeRenderer((int)state); + + return visualStyleRenderer.GetPartSize(g, ThemeSizeType.Draw, hWnd); + } + + return new Size(13, 13); + } + + internal static ButtonState ConvertToButtonState(RadioButtonState state) + { + switch (state) + { + case RadioButtonState.CheckedNormal: + case RadioButtonState.CheckedHot: + return ButtonState.Checked; + case RadioButtonState.CheckedPressed: + return (ButtonState.Checked | ButtonState.Pushed); + case RadioButtonState.CheckedDisabled: + return (ButtonState.Checked | ButtonState.Inactive); + + case RadioButtonState.UncheckedPressed: + return ButtonState.Pushed; + case RadioButtonState.UncheckedDisabled: + return ButtonState.Inactive; + + default: + return ButtonState.Normal; + } + } + + internal static RadioButtonState ConvertFromButtonState(ButtonState state, bool isHot) + { + if ((state & ButtonState.Checked) == ButtonState.Checked) + { + if ((state & ButtonState.Pushed) == ButtonState.Pushed) + { + return RadioButtonState.CheckedPressed; + } + else if ((state & ButtonState.Inactive) == ButtonState.Inactive) + { + return RadioButtonState.CheckedDisabled; + } + else if (isHot) + { + return RadioButtonState.CheckedHot; + } + + return RadioButtonState.CheckedNormal; + } + else + { //unchecked + if ((state & ButtonState.Pushed) == ButtonState.Pushed) + { + return RadioButtonState.UncheckedPressed; + } + else if ((state & ButtonState.Inactive) == ButtonState.Inactive) + { + return RadioButtonState.UncheckedDisabled; + } + else if (isHot) + { + return RadioButtonState.UncheckedHot; + } + + return RadioButtonState.UncheckedNormal; + } + } + + private static void InitializeRenderer(int state) + { RadioButtonState radioButtonState = (RadioButtonState)state; int part = RadioElement.Part; - if (SystemInformation.HighContrast + if (SystemInformation.HighContrast && (radioButtonState == RadioButtonState.CheckedDisabled || radioButtonState == RadioButtonState.UncheckedDisabled) - && VisualStyleRenderer.IsCombinationDefined(RadioElement.ClassName, VisualStyleElement.Button.RadioButton.HighContrastDisabledPart)) { - part = VisualStyleElement.Button.RadioButton.HighContrastDisabledPart; + && VisualStyleRenderer.IsCombinationDefined(RadioElement.ClassName, VisualStyleElement.Button.RadioButton.HighContrastDisabledPart)) + { + part = VisualStyleElement.Button.RadioButton.HighContrastDisabledPart; } - if (visualStyleRenderer == null) { + if (visualStyleRenderer == null) + { visualStyleRenderer = new VisualStyleRenderer(RadioElement.ClassName, part, state); } - else { + else + { visualStyleRenderer.SetParameters(RadioElement.ClassName, part, state); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RelatedCurrencyManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RelatedCurrencyManager.cs index 0e22094d43a..d6ce463f006 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RelatedCurrencyManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RelatedCurrencyManager.cs @@ -2,11 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using Microsoft.Win32; - using System.Diagnostics; + using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.ComponentModel; using System.Collections; @@ -16,22 +17,25 @@ namespace System.Windows.Forms { /// Represents the child version of the System.Windows.Forms.ListManager /// that is used when a parent/child relationship exists in a System.Windows.Forms.DataSet. /// - internal class RelatedCurrencyManager : CurrencyManager { + internal class RelatedCurrencyManager : CurrencyManager + { BindingManagerBase parentManager; string dataField; PropertyDescriptor fieldInfo; static List IgnoreItemChangedTable = new List(); - + [ SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // If the constructor does not set the dataSource // it would be a breaking change. ] - internal RelatedCurrencyManager(BindingManagerBase parentManager, string dataField) : base(null) { + internal RelatedCurrencyManager(BindingManagerBase parentManager, string dataField) : base(null) + { Bind(parentManager, dataField); } - - internal void Bind(BindingManagerBase parentManager, string dataField) { + + internal void Bind(BindingManagerBase parentManager, string dataField) + { Debug.Assert(parentManager != null, "How could this be a null parentManager."); // Unwire previous BindingManagerBase @@ -40,7 +44,8 @@ internal void Bind(BindingManagerBase parentManager, string dataField) { this.parentManager = parentManager; this.dataField = dataField; this.fieldInfo = parentManager.GetItemProperties().Find(dataField, true); - if (fieldInfo == null || !typeof(IList).IsAssignableFrom(fieldInfo.PropertyType)) { + if (fieldInfo == null || !typeof(IList).IsAssignableFrom(fieldInfo.PropertyType)) + { throw new ArgumentException(string.Format(SR.RelatedListManagerChild, dataField)); } this.finalType = fieldInfo.PropertyType; @@ -51,34 +56,43 @@ internal void Bind(BindingManagerBase parentManager, string dataField) { ParentManager_CurrentItemChanged(parentManager, EventArgs.Empty); } - private void UnwireParentManager(BindingManagerBase bmb) { - if (bmb != null) { + private void UnwireParentManager(BindingManagerBase bmb) + { + if (bmb != null) + { bmb.CurrentItemChanged -= new EventHandler(ParentManager_CurrentItemChanged); - if (bmb is CurrencyManager) { + if (bmb is CurrencyManager) + { (bmb as CurrencyManager).MetaDataChanged -= new EventHandler(ParentManager_MetaDataChanged); } } } - private void WireParentManager(BindingManagerBase bmb) { - if (bmb != null) { + private void WireParentManager(BindingManagerBase bmb) + { + if (bmb != null) + { bmb.CurrentItemChanged += new EventHandler(ParentManager_CurrentItemChanged); - if (bmb is CurrencyManager) { + if (bmb is CurrencyManager) + { (bmb as CurrencyManager).MetaDataChanged += new EventHandler(ParentManager_MetaDataChanged); } } } - internal override PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors) { + internal override PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors) + { PropertyDescriptor[] accessors; - if (listAccessors != null && listAccessors.Length > 0) { + if (listAccessors != null && listAccessors.Length > 0) + { accessors = new PropertyDescriptor[listAccessors.Length + 1]; listAccessors.CopyTo(accessors, 1); } - else { + else + { accessors = new PropertyDescriptor[1]; } @@ -92,36 +106,43 @@ internal override PropertyDescriptorCollection GetItemProperties(PropertyDescrip /// /// Gets the properties of the item. /// - public override PropertyDescriptorCollection GetItemProperties() { + public override PropertyDescriptorCollection GetItemProperties() + { return GetItemProperties(null); } // // Gets the name of the list. // - internal override string GetListName() { + internal override string GetListName() + { string name = GetListName(new ArrayList()); - if (name.Length > 0) { + if (name.Length > 0) + { return name; } return base.GetListName(); } - + /// /// Gets the name of the specified list. /// - protected internal override string GetListName(ArrayList listAccessors) { + protected internal override string GetListName(ArrayList listAccessors) + { listAccessors.Insert(0, fieldInfo); return parentManager.GetListName(listAccessors); } - - private void ParentManager_MetaDataChanged(object sender, EventArgs e) { + + private void ParentManager_MetaDataChanged(object sender, EventArgs e) + { // Propagate MetaDataChanged events from the parent manager base.OnMetaDataChanged(e); } - - private void ParentManager_CurrentItemChanged(object sender, EventArgs e) { - if (IgnoreItemChangedTable.Contains(parentManager)) { + + private void ParentManager_CurrentItemChanged(object sender, EventArgs e) + { + if (IgnoreItemChangedTable.Contains(parentManager)) + { return; } @@ -129,20 +150,26 @@ private void ParentManager_CurrentItemChanged(object sender, EventArgs e) { // we only pull the data from the controls into the backEnd. we do not care about keeping the lastGoodKnownRow // when we are about to change the entire list in this currencymanager. - try { + try + { PullData(); } - catch (Exception ex) { + catch (Exception ex) + { OnDataError(ex); } - if (parentManager is CurrencyManager) { - CurrencyManager curManager = (CurrencyManager) parentManager; - if (curManager.Count > 0) { + if (parentManager is CurrencyManager) + { + CurrencyManager curManager = (CurrencyManager)parentManager; + if (curManager.Count > 0) + { // Parent list has a current row, so get the related list from the relevant property on that row. SetDataSource(fieldInfo.GetValue(curManager.Current)); listposition = (Count > 0 ? 0 : -1); - } else { + } + else + { // APPCOMPAT: bring back the Everett behavior where the currency manager adds an item and // then it cancels the addition. // @@ -156,16 +183,22 @@ private void ParentManager_CurrentItemChanged(object sender, EventArgs e) { // we then call CancelCurrentEdit to remove the dummy row, but making sure to ignore any // OnCurrentItemChanged that results from this action (to avoid infinite recursion) curManager.AddNew(); - try { + try + { IgnoreItemChangedTable.Add(curManager); curManager.CancelCurrentEdit(); - } finally { - if (IgnoreItemChangedTable.Contains(curManager)) { + } + finally + { + if (IgnoreItemChangedTable.Contains(curManager)) + { IgnoreItemChangedTable.Remove(curManager); } } } - } else { + } + else + { // Case where the parent is not a list, but a single object SetDataSource(fieldInfo.GetValue(parentManager.Current)); listposition = (Count > 0 ? 0 : -1); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RelatedImageListAttribute.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RelatedImageListAttribute.cs index b00d180416b..8d0bf74a596 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RelatedImageListAttribute.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RelatedImageListAttribute.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ /// /// @@ -10,16 +11,20 @@ namespace System.Windows.Forms { /// specific ImageList property /// /// - [AttributeUsage(AttributeTargets.Property, AllowMultiple=false, Inherited=true)] - public sealed class RelatedImageListAttribute : Attribute { - private string relatedImageList=null; + [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] + public sealed class RelatedImageListAttribute : Attribute + { + private string relatedImageList = null; - public RelatedImageListAttribute(string relatedImageList) { + public RelatedImageListAttribute(string relatedImageList) + { this.relatedImageList = relatedImageList; } - public string RelatedImageList { - get { + public string RelatedImageList + { + get + { return relatedImageList; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RelatedPropertyManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RelatedPropertyManager.cs index 35ef4f14364..95b8f817d8f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RelatedPropertyManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RelatedPropertyManager.cs @@ -2,30 +2,34 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using Microsoft.Win32; - using System.Diagnostics; + using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.ComponentModel; using System.Collections; - internal class RelatedPropertyManager : PropertyManager { + internal class RelatedPropertyManager : PropertyManager + { BindingManagerBase parentManager; string dataField; PropertyDescriptor fieldInfo; - + [ SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // If the constructor does not set the dataSource // it would be a breaking change. ] - internal RelatedPropertyManager(BindingManagerBase parentManager, string dataField) : base(GetCurrentOrNull(parentManager), dataField) { + internal RelatedPropertyManager(BindingManagerBase parentManager, string dataField) : base(GetCurrentOrNull(parentManager), dataField) + { Bind(parentManager, dataField); } - private void Bind(BindingManagerBase parentManager, string dataField) { + private void Bind(BindingManagerBase parentManager, string dataField) + { Debug.Assert(parentManager != null, "How could this be a null parentManager."); this.parentManager = parentManager; this.dataField = dataField; @@ -37,27 +41,33 @@ private void Bind(BindingManagerBase parentManager, string dataField) { Refresh(); } - internal override string GetListName() { + internal override string GetListName() + { string name = GetListName(new ArrayList()); - if (name.Length > 0) { + if (name.Length > 0) + { return name; } return base.GetListName(); } - - protected internal override string GetListName(ArrayList listAccessors) { + + protected internal override string GetListName(ArrayList listAccessors) + { listAccessors.Insert(0, fieldInfo); return parentManager.GetListName(listAccessors); } - - internal override PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors) { + + internal override PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors) + { PropertyDescriptor[] accessors; - if (listAccessors != null && listAccessors.Length > 0) { + if (listAccessors != null && listAccessors.Length > 0) + { accessors = new PropertyDescriptor[listAccessors.Length + 1]; listAccessors.CopyTo(accessors, 1); } - else { + else + { accessors = new PropertyDescriptor[1]; } @@ -68,30 +78,37 @@ internal override PropertyDescriptorCollection GetItemProperties(PropertyDescrip return parentManager.GetItemProperties(accessors); } - private void ParentManager_CurrentItemChanged(object sender, EventArgs e) { + private void ParentManager_CurrentItemChanged(object sender, EventArgs e) + { Refresh(); } - private void Refresh() { + private void Refresh() + { EndCurrentEdit(); SetDataSource(GetCurrentOrNull(parentManager)); OnCurrentChanged(EventArgs.Empty); } - - internal override Type BindType { - get { + + internal override Type BindType + { + get + { return fieldInfo.PropertyType; } } - public override object Current { - get { + public override object Current + { + get + { return (this.DataSource != null) ? fieldInfo.GetValue(this.DataSource) : null; } } - static private object GetCurrentOrNull(BindingManagerBase parentManager) { + static private object GetCurrentOrNull(BindingManagerBase parentManager) + { bool anyCurrent = (parentManager.Position >= 0 && parentManager.Position < parentManager.Count); return anyCurrent ? parentManager.Current : null; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs index 76724b925f3..61d0c8e0b61 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System; using System.Collections.Specialized; @@ -22,7 +23,7 @@ namespace System.Windows.Forms { using System.Runtime.Versioning; using IComDataObject = System.Runtime.InteropServices.ComTypes.IDataObject; - using Util = NativeMethods.Util; + using Util = NativeMethods.Util; // @@ -42,11 +43,15 @@ namespace System.Windows.Forms { Designer("System.Windows.Forms.Design.RichTextBoxDesigner, " + AssemblyRef.SystemDesign), SRDescription(nameof(SR.DescriptionRichTextBox)) ] - public class RichTextBox : TextBoxBase { + public class RichTextBox : TextBoxBase + { static TraceSwitch richTextDbg; - static TraceSwitch RichTextDbg { - get { - if (richTextDbg == null) { + static TraceSwitch RichTextDbg + { + get + { + if (richTextDbg == null) + { richTextDbg = new TraceSwitch("RichTextDbg", "Debug info about RichTextBox"); } return richTextDbg; @@ -56,46 +61,46 @@ static TraceSwitch RichTextDbg { /// /// Paste special flags. /// - private const int DV_E_DVASPECT = unchecked((int)0x8004006B); - private const int DVASPECT_CONTENT = 1; + private const int DV_E_DVASPECT = unchecked((int)0x8004006B); + private const int DVASPECT_CONTENT = 1; private const int DVASPECT_THUMBNAIL = 2; - private const int DVASPECT_ICON = 4; - private const int DVASPECT_DOCPRINT = 8; - - internal const int INPUT = 0x0001; - internal const int OUTPUT = 0x0002; - internal const int DIRECTIONMASK = INPUT | OUTPUT; - internal const int ANSI = 0x0004; - internal const int UNICODE = 0x0008; - internal const int FORMATMASK = ANSI | UNICODE; - internal const int TEXTLF = 0x0010; - internal const int TEXTCRLF = 0x0020; - internal const int RTF = 0x0040; - internal const int KINDMASK = TEXTLF | TEXTCRLF | RTF; + private const int DVASPECT_ICON = 4; + private const int DVASPECT_DOCPRINT = 8; + + internal const int INPUT = 0x0001; + internal const int OUTPUT = 0x0002; + internal const int DIRECTIONMASK = INPUT | OUTPUT; + internal const int ANSI = 0x0004; + internal const int UNICODE = 0x0008; + internal const int FORMATMASK = ANSI | UNICODE; + internal const int TEXTLF = 0x0010; + internal const int TEXTCRLF = 0x0020; + internal const int RTF = 0x0040; + internal const int KINDMASK = TEXTLF | TEXTCRLF | RTF; // This is where we store the reched library. private static IntPtr moduleHandle; - private static readonly string SZ_RTF_TAG = "{\\rtf"; - private const int CHAR_BUFFER_LEN = 512; + private static readonly string SZ_RTF_TAG = "{\\rtf"; + private const int CHAR_BUFFER_LEN = 512; // Event objects // - private static readonly object EVENT_HSCROLL = new object(); - private static readonly object EVENT_LINKACTIVATE = new object(); - private static readonly object EVENT_IMECHANGE = new object(); - private static readonly object EVENT_PROTECTED = new object(); - private static readonly object EVENT_REQUESTRESIZE = new object(); - private static readonly object EVENT_SELCHANGE = new object(); - private static readonly object EVENT_VSCROLL = new object(); + private static readonly object EVENT_HSCROLL = new object(); + private static readonly object EVENT_LINKACTIVATE = new object(); + private static readonly object EVENT_IMECHANGE = new object(); + private static readonly object EVENT_PROTECTED = new object(); + private static readonly object EVENT_REQUESTRESIZE = new object(); + private static readonly object EVENT_SELCHANGE = new object(); + private static readonly object EVENT_VSCROLL = new object(); // Persistent state // - private int bulletIndent; - private int rightMargin; - private string textRtf; // If not null, takes precedence over cached Text value - private string textPlain; + private int bulletIndent; + private int rightMargin; + private string textRtf; // If not null, takes precedence over cached Text value + private string textPlain; private Color selectionBackColorToSetOnHandleCreated; RichTextBoxLanguageOptions languageOption = RichTextBoxLanguageOptions.AutoFont | RichTextBoxLanguageOptions.DualFont; @@ -127,13 +132,14 @@ static TraceSwitch RichTextDbg { private static readonly BitVector32.Section callOnContentsResizedSection = BitVector32.CreateSection(1, suppressTextChangedEventSection); private static readonly BitVector32.Section richTextShortcutsEnabledSection = BitVector32.CreateSection(1, callOnContentsResizedSection); private static readonly BitVector32.Section allowOleObjectsSection = BitVector32.CreateSection(1, richTextShortcutsEnabledSection); - private static readonly BitVector32.Section scrollBarsSection = BitVector32.CreateSection((short) RichTextBoxScrollBars.ForcedBoth, allowOleObjectsSection); + private static readonly BitVector32.Section scrollBarsSection = BitVector32.CreateSection((short)RichTextBoxScrollBars.ForcedBoth, allowOleObjectsSection); private static readonly BitVector32.Section enableAutoDragDropSection = BitVector32.CreateSection(1, scrollBarsSection); /// /// Constructs a new RichTextBox. /// - public RichTextBox() { + public RichTextBox() + { InConstructor = true; richTextBoxFlags[autoWordSelectionSection] = 0;// This is false by default DetectUrls = true; @@ -151,21 +157,27 @@ public RichTextBox() { /// may still be used: this should be hidden in the property grid, but not in code /// [Browsable(false)] - public override bool AllowDrop { - get { + public override bool AllowDrop + { + get + { return richTextBoxFlags[allowOleDropSection] != 0; } - set { + set + { richTextBoxFlags[allowOleDropSection] = value ? 1 : 0; UpdateOleCallback(); } } - internal bool AllowOleObjects { - get { + internal bool AllowOleObjects + { + get + { return richTextBoxFlags[allowOleObjectsSection] != 0; } - set { + set + { richTextBoxFlags[allowOleObjectsSection] = value ? 1 : 0; } } @@ -186,11 +198,14 @@ internal bool AllowOleObjects { Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible) ] - public override bool AutoSize { - get { + public override bool AutoSize + { + get + { return base.AutoSize; } - set { + set + { base.AutoSize = value; } } @@ -203,11 +218,14 @@ public override bool AutoSize { DefaultValue(false), SRDescription(nameof(SR.RichTextBoxAutoWordSelection)) ] - public bool AutoWordSelection { + public bool AutoWordSelection + { get { return richTextBoxFlags[autoWordSelectionSection] != 0; } - set { + set + { richTextBoxFlags[autoWordSelectionSection] = value ? 1 : 0; - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(Interop.EditMessages.EM_SETOPTIONS, value ? RichTextBoxConstants.ECOOP_OR : RichTextBoxConstants.ECOOP_XOR, RichTextBoxConstants.ECO_AUTOWORDSELECTION); @@ -216,33 +234,41 @@ public bool AutoWordSelection { } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged { + new public event EventHandler BackgroundImageChanged + { add => base.BackgroundImageChanged += value; remove => base.BackgroundImageChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { + new public event EventHandler BackgroundImageLayoutChanged + { add => base.BackgroundImageLayoutChanged += value; remove => base.BackgroundImageLayoutChanged -= value; } @@ -257,14 +283,18 @@ public override ImageLayout BackgroundImageLayout { Localizable(true), SRDescription(nameof(SR.RichTextBoxBulletIndent)) ] - public int BulletIndent { - get { + public int BulletIndent + { + get + { return bulletIndent; } - set { + set + { - if (value < 0) { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(BulletIndent), value)); } @@ -276,13 +306,16 @@ public int BulletIndent { } } - private bool CallOnContentsResized { + private bool CallOnContentsResized + { get { return richTextBoxFlags[callOnContentsResizedSection] != 0; } set { richTextBoxFlags[callOnContentsResizedSection] = value ? 1 : 0; } } - internal override bool CanRaiseTextChangedEvent { - get { + internal override bool CanRaiseTextChangedEvent + { + get + { return !SuppressTextChangedEvent; } } @@ -295,11 +328,14 @@ internal override bool CanRaiseTextChangedEvent { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.RichTextBoxCanRedoDescr)) ] - public bool CanRedo { - get { - if (IsHandleCreated) { + public bool CanRedo + { + get + { + if (IsHandleCreated) + { bool b; - b = unchecked( (int) (long)SendMessage(Interop.EditMessages.EM_CANREDO, 0, 0)) != 0; + b = unchecked((int)(long)SendMessage(Interop.EditMessages.EM_CANREDO, 0, 0)) != 0; return b; } @@ -307,10 +343,13 @@ public bool CanRedo { } } - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { // Check for library - if (moduleHandle == IntPtr.Zero) { + if (moduleHandle == IntPtr.Zero) + { string richEditControlDllVersion = LocalAppContextSwitches.DoNotLoadLatestRichEditControl ? RichTextBoxConstants.DLL_RICHEDIT : RichTextBoxConstants.DLL_RICHEDIT_41; moduleHandle = UnsafeNativeMethods.LoadLibraryFromSystemPathIfAvailable(richEditControlDllVersion); @@ -319,7 +358,8 @@ protected override CreateParams CreateParams { // This code has been here since the inception of the project, // we can't determine why we have to compare w/ 32 here. // This fails on 3-GB mode, (once the dll is loaded above 3GB memory space) (see Dev10 - if ((ulong)moduleHandle < (ulong)32) { + if ((ulong)moduleHandle < (ulong)32) + { throw new Win32Exception(lastWin32Error, string.Format(SR.LoadDLLError, richEditControlDllVersion)); } @@ -331,10 +371,12 @@ protected override CreateParams CreateParams { FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(path); Debug.Assert(versionInfo != null && !string.IsNullOrEmpty(versionInfo.ProductVersion), "Couldn't get the version info for the richedit dll"); - if (versionInfo != null && !string.IsNullOrEmpty(versionInfo.ProductVersion)) { + if (versionInfo != null && !string.IsNullOrEmpty(versionInfo.ProductVersion)) + { //Note: this only allows for one digit version int parsedValue; - if (int.TryParse(versionInfo.ProductVersion[0].ToString(), out parsedValue)) { + if (int.TryParse(versionInfo.ProductVersion[0].ToString(), out parsedValue)) + { richEditMajorVersion = parsedValue; } } @@ -343,15 +385,18 @@ protected override CreateParams CreateParams { CreateParams cp = base.CreateParams; cp.ClassName = LocalAppContextSwitches.DoNotLoadLatestRichEditControl ? RichTextBoxConstants.WC_RICHEDITW : RichTextBoxConstants.WC_RICHEDITW_41; - if (Multiline) { - if (((int)ScrollBars & RichTextBoxConstants.RTB_HORIZ) != 0 && !WordWrap) { + if (Multiline) + { + if (((int)ScrollBars & RichTextBoxConstants.RTB_HORIZ) != 0 && !WordWrap) + { // RichEd infers word wrap from the absence of horizontal scroll bars cp.Style |= NativeMethods.WS_HSCROLL; if (((int)ScrollBars & RichTextBoxConstants.RTB_FORCE) != 0) cp.Style |= RichTextBoxConstants.ES_DISABLENOSCROLL; } - if (((int)ScrollBars & RichTextBoxConstants.RTB_VERT) != 0) { + if (((int)ScrollBars & RichTextBoxConstants.RTB_VERT) != 0) + { cp.Style |= NativeMethods.WS_VSCROLL; if (((int)ScrollBars & RichTextBoxConstants.RTB_FORCE) != 0) cp.Style |= RichTextBoxConstants.ES_DISABLENOSCROLL; @@ -360,7 +405,8 @@ protected override CreateParams CreateParams { // Remove the WS_BORDER style from the control, if we're trying to set it, // to prevent the control from displaying the single point rectangle around the 3D border - if (BorderStyle.FixedSingle == BorderStyle && ((cp.Style & NativeMethods.WS_BORDER) != 0)) { + if (BorderStyle.FixedSingle == BorderStyle && ((cp.Style & NativeMethods.WS_BORDER) != 0)) + { cp.Style &= (~NativeMethods.WS_BORDER); cp.ExStyle |= NativeMethods.WS_EX_CLIENTEDGE; } @@ -382,14 +428,19 @@ protected override CreateParams CreateParams { DefaultValue(true), SRDescription(nameof(SR.RichTextBoxDetectURLs)) ] - public bool DetectUrls { - get { + public bool DetectUrls + { + get + { return richTextBoxFlags[autoUrlDetectSection] != 0; } - set { - if (value != DetectUrls) { + set + { + if (value != DetectUrls) + { richTextBoxFlags[autoUrlDetectSection] = value ? 1 : 0; - if (IsHandleCreated) { + if (IsHandleCreated) + { this.SendMessage(Interop.EditMessages.EM_AUTOURLDETECT, value ? 1 : 0, 0); RecreateHandle(); } @@ -397,8 +448,10 @@ public bool DetectUrls { } } - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(100, 96); } } @@ -425,38 +478,52 @@ public bool EnableAutoDragDrop } } - public override Color ForeColor { - get { + public override Color ForeColor + { + get + { return base.ForeColor; } - set { - if (IsHandleCreated) { - if (InternalSetForeColor(value)) { + set + { + if (IsHandleCreated) + { + if (InternalSetForeColor(value)) + { base.ForeColor = value; } } - else { + else + { base.ForeColor = value; } } } - public override Font Font { - get { + public override Font Font + { + get + { return base.Font; } - set { + set + { if (IsHandleCreated) { - if (Interop.User32.GetWindowTextLengthW(new HandleRef(this, Handle)) > 0) { - if (value == null) { + if (Interop.User32.GetWindowTextLengthW(new HandleRef(this, Handle)) > 0) + { + if (value == null) + { base.Font = null; SetCharFormatFont(false, Font); } - else { - try{ + else + { + try + { Font f = GetCharFormatFont(false); - if (f == null || !f.Equals (value)) { + if (f == null || !f.Equals(value)) + { SetCharFormatFont(false, value); // update controlfont from "resolved" font from the attempt // to set the document font... @@ -465,41 +532,48 @@ public override Font Font { base.Font = GetCharFormatFont(false); } } - finally{ + finally + { CallOnContentsResized = false; } } } - else { + else + { base.Font = value; } } - else { + else + { base.Font = value; } } } - internal override Size GetPreferredSizeCore(Size proposedConstraints) { + internal override Size GetPreferredSizeCore(Size proposedConstraints) + { Size scrollBarPadding = Size.Empty; //If the RTB is multiline, we won't have a horizontal scrollbar. - if (!WordWrap && Multiline && (ScrollBars & RichTextBoxScrollBars.Horizontal) != 0) { + if (!WordWrap && Multiline && (ScrollBars & RichTextBoxScrollBars.Horizontal) != 0) + { scrollBarPadding.Height += SystemInformation.HorizontalScrollBarHeight; } - if (Multiline && (ScrollBars & RichTextBoxScrollBars.Vertical) != 0) { + if (Multiline && (ScrollBars & RichTextBoxScrollBars.Vertical) != 0) + { scrollBarPadding.Width += SystemInformation.VerticalScrollBarWidth; } // Subtract the scroll bar padding before measuring proposedConstraints -= scrollBarPadding; - + Size prefSize = base.GetPreferredSizeCore(proposedConstraints); return prefSize + scrollBarPadding; } - private bool InConstructor { + private bool InConstructor + { get { return richTextBoxFlags[fInCtorSection] != 0; } set { richTextBoxFlags[fInCtorSection] = value ? 1 : 0; } } @@ -518,10 +592,12 @@ public RichTextBoxLanguageOptions LanguageOption get { RichTextBoxLanguageOptions opt; - if (IsHandleCreated) { + if (IsHandleCreated) + { opt = (RichTextBoxLanguageOptions)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_GETLANGOPTIONS, 0, 0); } - else { + else + { opt = languageOption; } return opt; @@ -531,14 +607,16 @@ public RichTextBoxLanguageOptions LanguageOption if (this.LanguageOption != value) { this.languageOption = value; - if (IsHandleCreated) { - UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_SETLANGOPTIONS, 0, (int) value); + if (IsHandleCreated) + { + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_SETLANGOPTIONS, 0, (int)value); } } } } - private bool LinkCursor { + private bool LinkCursor + { get { return richTextBoxFlags[linkcursorSection] != 0; } set { richTextBoxFlags[linkcursorSection] = value ? 1 : 0; } } @@ -546,25 +624,32 @@ private bool LinkCursor { [ DefaultValue(int.MaxValue), ] - public override int MaxLength { - get { + public override int MaxLength + { + get + { return base.MaxLength; } - set { + set + { base.MaxLength = value; } } [DefaultValue(true)] - public override bool Multiline { - get { + public override bool Multiline + { + get + { return base.Multiline; } - set { + set + { base.Multiline = value; } } - private bool ProtectedError { + private bool ProtectedError + { get { return richTextBoxFlags[protectedErrorSection] != 0; } set { richTextBoxFlags[protectedErrorSection] = value ? 1 : 0; } } @@ -582,11 +667,14 @@ private bool ProtectedError { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.RichTextBoxRedoActionNameDescr)) ] - public string RedoActionName { - get { - if (!CanRedo) return ""; + public string RedoActionName + { + get + { + if (!CanRedo) + return ""; int n; - n = unchecked( (int) (long)SendMessage(Interop.EditMessages.EM_GETREDONAME, 0, 0)); + n = unchecked((int)(long)SendMessage(Interop.EditMessages.EM_GETREDONAME, 0, 0)); return GetEditorActionName(n); } } @@ -597,13 +685,16 @@ public string RedoActionName { Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public bool RichTextShortcutsEnabled { + public bool RichTextShortcutsEnabled + { get { return richTextBoxFlags[richTextShortcutsEnabledSection] != 0; } - set { - if (shortcutsToDisable == null) { - shortcutsToDisable = new int[] {(int)Shortcut.CtrlL, (int)Shortcut.CtrlR, (int)Shortcut.CtrlE, (int)Shortcut.CtrlJ}; + set + { + if (shortcutsToDisable == null) + { + shortcutsToDisable = new int[] { (int)Shortcut.CtrlL, (int)Shortcut.CtrlR, (int)Shortcut.CtrlE, (int)Shortcut.CtrlJ }; } - richTextBoxFlags[richTextShortcutsEnabledSection] = value ? 1 : 0; + richTextBoxFlags[richTextShortcutsEnabledSection] = value ? 1 : 0; } } @@ -616,28 +707,37 @@ public bool RichTextShortcutsEnabled { Localizable(true), SRDescription(nameof(SR.RichTextBoxRightMargin)) ] - public int RightMargin { - get { + public int RightMargin + { + get + { return rightMargin; } - set { - if (this.rightMargin != value) { + set + { + if (this.rightMargin != value) + { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(RightMargin), value, 0)); this.rightMargin = value; - if (value == 0) { + if (value == 0) + { // Once you set EM_SETTARGETDEVICE to something nonzero, RichEd will assume // word wrap forever and ever. RecreateHandle(); } - else if (IsHandleCreated) { + else if (IsHandleCreated) + { IntPtr hDC = UnsafeNativeMethods.CreateIC("DISPLAY", null, null, new HandleRef(null, IntPtr.Zero)); - try { + try + { SendMessage(Interop.EditMessages.EM_SETTARGETDEVICE, hDC, (IntPtr)Pixel2Twip(hDC, value, true)); } - finally { - if (hDC != IntPtr.Zero) { + finally + { + if (hDC != IntPtr.Zero) + { UnsafeNativeMethods.DeleteDC(new HandleRef(null, hDC)); } } @@ -655,8 +755,10 @@ public int RightMargin { SRDescription(nameof(SR.RichTextBoxRTF)), RefreshProperties(RefreshProperties.All) ] - public string Rtf { - get { + public string Rtf + { + get + { if (IsHandleCreated) { return StreamOut(RichTextBoxConstants.SF_RTF); @@ -671,8 +773,10 @@ public string Rtf { return textRtf; } } - set { - if (value == null) value = string.Empty; + set + { + if (value == null) + value = string.Empty; if (value.Equals(Rtf)) return; @@ -680,7 +784,8 @@ public string Rtf { ForceHandleCreate(); textRtf = value; StreamIn(value, RichTextBoxConstants.SF_RTF); - if (CanRaiseTextChangedEvent) { + if (CanRaiseTextChangedEvent) + { OnTextChanged(EventArgs.Empty); } } @@ -696,14 +801,17 @@ public string Rtf { Localizable(true), SRDescription(nameof(SR.RichTextBoxScrollBars)) ] - public RichTextBoxScrollBars ScrollBars { - get { - return (RichTextBoxScrollBars) richTextBoxFlags[scrollBarsSection]; + public RichTextBoxScrollBars ScrollBars + { + get + { + return (RichTextBoxScrollBars)richTextBoxFlags[scrollBarsSection]; } - set { + set + { // we could be more clever here, but it doesnt seem like this would get set enough // to warrant a clever bitmask. - if (!ClientUtils.IsEnumValid_NotSequential(value, + if (!ClientUtils.IsEnumValid_NotSequential(value, (int)value, (int)RichTextBoxScrollBars.Both, (int)RichTextBoxScrollBars.None, @@ -711,14 +819,17 @@ public RichTextBoxScrollBars ScrollBars { (int)RichTextBoxScrollBars.Vertical, (int)RichTextBoxScrollBars.ForcedHorizontal, (int)RichTextBoxScrollBars.ForcedVertical, - (int)RichTextBoxScrollBars.ForcedBoth)) { + (int)RichTextBoxScrollBars.ForcedBoth)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(RichTextBoxScrollBars)); } - if (value != ScrollBars) { - using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.ScrollBars)) { - richTextBoxFlags[scrollBarsSection] = (int) value; + if (value != ScrollBars) + { + using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.ScrollBars)) + { + richTextBoxFlags[scrollBarsSection] = (int)value; RecreateHandle(); } } @@ -734,8 +845,10 @@ public RichTextBoxScrollBars ScrollBars { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.RichTextBoxSelAlignment)) ] - public HorizontalAlignment SelectionAlignment { - get { + public HorizontalAlignment SelectionAlignment + { + get + { HorizontalAlignment selectionAlignment = HorizontalAlignment.Left; ForceHandleCreate(); @@ -746,8 +859,10 @@ public HorizontalAlignment SelectionAlignment { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_GETPARAFORMAT, 0, pf); // check if alignment has been set yet - if ((RichTextBoxConstants.PFM_ALIGNMENT & pf.dwMask) != 0) { - switch (pf.wAlignment) { + if ((RichTextBoxConstants.PFM_ALIGNMENT & pf.dwMask) != 0) + { + switch (pf.wAlignment) + { case RichTextBoxConstants.PFA_LEFT: selectionAlignment = HorizontalAlignment.Left; break; @@ -764,7 +879,8 @@ public HorizontalAlignment SelectionAlignment { return selectionAlignment; } - set { + set + { //valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)HorizontalAlignment.Left, (int)HorizontalAlignment.Center)) { @@ -774,8 +890,9 @@ public HorizontalAlignment SelectionAlignment { ForceHandleCreate(); NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT(); pf.dwMask = RichTextBoxConstants.PFM_ALIGNMENT; - switch (value) { - + switch (value) + { + case HorizontalAlignment.Left: pf.wAlignment = RichTextBoxConstants.PFA_LEFT; break; @@ -804,8 +921,10 @@ public HorizontalAlignment SelectionAlignment { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.RichTextBoxSelBullet)) ] - public bool SelectionBullet { - get { + public bool SelectionBullet + { + get + { RichTextBoxSelectionAttribute selectionBullet = RichTextBoxSelectionAttribute.None; ForceHandleCreate(); @@ -816,29 +935,35 @@ public bool SelectionBullet { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_GETPARAFORMAT, 0, pf); // check if alignment has been set yet - if ((RichTextBoxConstants.PFM_NUMBERING & pf.dwMask) != 0) { - if (RichTextBoxConstants.PFN_BULLET == pf.wNumbering) { + if ((RichTextBoxConstants.PFM_NUMBERING & pf.dwMask) != 0) + { + if (RichTextBoxConstants.PFN_BULLET == pf.wNumbering) + { selectionBullet = RichTextBoxSelectionAttribute.All; } } - else { + else + { // For paragraphs with mixed SelectionBullets, we just return false return false; - } + } return selectionBullet == RichTextBoxSelectionAttribute.All; } - set { + set + { ForceHandleCreate(); NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT(); pf.dwMask = RichTextBoxConstants.PFM_NUMBERING | RichTextBoxConstants.PFM_OFFSET; - if (!value) { + if (!value) + { pf.wNumbering = 0; pf.dxOffset = 0; } - else { + else + { pf.wNumbering = RichTextBoxConstants.PFN_BULLET; pf.dxOffset = Pixel2Twip(IntPtr.Zero, bulletIndent, true); } @@ -858,25 +983,30 @@ public bool SelectionBullet { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.RichTextBoxSelCharOffset)) ] - public int SelectionCharOffset { - get { + public int SelectionCharOffset + { + get + { int selCharOffset = 0; ForceHandleCreate(); NativeMethods.CHARFORMATA cf = GetCharFormat(true); // if the effects member contains valid info - if ((cf.dwMask & RichTextBoxConstants.CFM_OFFSET) != 0) { + if ((cf.dwMask & RichTextBoxConstants.CFM_OFFSET) != 0) + { selCharOffset = cf.yOffset; } - else { + else + { // The selection contains characters of different offsets, // so we just return the offset of the first character. selCharOffset = cf.yOffset; } - return Twip2Pixel(IntPtr.Zero,selCharOffset,false); + return Twip2Pixel(IntPtr.Zero, selCharOffset, false); } - set { + set + { if (value > 2000 || value < -2000) throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidBoundArgument, nameof(SelectionCharOffset), value, -2000, 2000)); @@ -904,8 +1034,10 @@ public int SelectionCharOffset { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.RichTextBoxSelColor)) ] - public Color SelectionColor { - get { + public Color SelectionColor + { + get + { Color selColor = Color.Empty; ForceHandleCreate(); @@ -916,7 +1048,8 @@ public Color SelectionColor { return selColor; } - set { + set + { ForceHandleCreate(); NativeMethods.CHARFORMATA cf = GetCharFormat(true); cf.dwMask = RichTextBoxConstants.CFM_COLOR; @@ -937,21 +1070,27 @@ public Color SelectionColor { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.RichTextBoxSelBackColor)) ] - public Color SelectionBackColor { - get { + public Color SelectionBackColor + { + get + { Color selColor = Color.Empty; - if (IsHandleCreated) { + if (IsHandleCreated) + { NativeMethods.CHARFORMAT2A cf2 = GetCharFormat2(true); // If the effects member contains valid info - if ((cf2.dwEffects & RichTextBoxConstants.CFE_AUTOBACKCOLOR) != 0) { + if ((cf2.dwEffects & RichTextBoxConstants.CFE_AUTOBACKCOLOR) != 0) + { selColor = this.BackColor; } - else if ((cf2.dwMask & RichTextBoxConstants.CFM_BACKCOLOR) != 0) { + else if ((cf2.dwMask & RichTextBoxConstants.CFM_BACKCOLOR) != 0) + { selColor = ColorTranslator.FromOle(cf2.crBackColor); } } - else { + else + { selColor = selectionBackColorToSetOnHandleCreated; } return selColor; @@ -989,11 +1128,14 @@ public Color SelectionBackColor { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.RichTextBoxSelFont)) ] - public Font SelectionFont { - get { + public Font SelectionFont + { + get + { return GetCharFormatFont(true); } - set { + set + { SetCharFormatFont(true, value); } } @@ -1010,8 +1152,10 @@ public Font SelectionFont { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.RichTextBoxSelHangingIndent)) ] - public int SelectionHangingIndent { - get { + public int SelectionHangingIndent + { + get + { int selHangingIndent = 0; ForceHandleCreate(); @@ -1027,7 +1171,8 @@ public int SelectionHangingIndent { return Twip2Pixel(IntPtr.Zero, selHangingIndent, true); } - set { + set + { ForceHandleCreate(); NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT(); @@ -1050,8 +1195,10 @@ public int SelectionHangingIndent { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.RichTextBoxSelIndent)) ] - public int SelectionIndent { - get { + public int SelectionIndent + { + get + { int selIndent = 0; ForceHandleCreate(); @@ -1067,7 +1214,8 @@ public int SelectionIndent { return Twip2Pixel(IntPtr.Zero, selIndent, true); } - set { + set + { ForceHandleCreate(); NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT(); @@ -1091,10 +1239,13 @@ public int SelectionIndent { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.TextBoxSelectionLengthDescr)) ] - public override int SelectionLength { - get { + public override int SelectionLength + { + get + { - if (!IsHandleCreated) { + if (!IsHandleCreated) + { return base.SelectionLength; } @@ -1106,7 +1257,8 @@ public override int SelectionLength { return SelectedText.Length; } - set { + set + { base.SelectionLength = value; } } @@ -1120,12 +1272,15 @@ public override int SelectionLength { Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public bool SelectionProtected { - get { + public bool SelectionProtected + { + get + { ForceHandleCreate(); return GetCharFormat(RichTextBoxConstants.CFM_PROTECTED, RichTextBoxConstants.CFM_PROTECTED) == RichTextBoxSelectionAttribute.All; } - set { + set + { ForceHandleCreate(); SetCharFormat(RichTextBoxConstants.CFM_PROTECTED, value ? RichTextBoxConstants.CFE_PROTECTED : 0, RichTextBoxSelectionAttribute.All); } @@ -1141,14 +1296,18 @@ public bool SelectionProtected { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.RichTextBoxSelRTF)) ] - public string SelectedRtf { - get { + public string SelectedRtf + { + get + { ForceHandleCreate(); return StreamOut(RichTextBoxConstants.SFF_SELECTION | RichTextBoxConstants.SF_RTF); } - set { + set + { ForceHandleCreate(); - if (value == null) value = string.Empty; + if (value == null) + value = string.Empty; StreamIn(value, RichTextBoxConstants.SFF_SELECTION | RichTextBoxConstants.SF_RTF); } } @@ -1164,8 +1323,10 @@ public string SelectedRtf { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.RichTextBoxSelRightIndent)) ] - public int SelectionRightIndent { - get { + public int SelectionRightIndent + { + get + { int selRightIndent = 0; ForceHandleCreate(); @@ -1182,7 +1343,8 @@ public int SelectionRightIndent { return Twip2Pixel(IntPtr.Zero, selRightIndent, true); } - set { + set + { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(SelectionRightIndent), value, 0)); @@ -1204,8 +1366,10 @@ public int SelectionRightIndent { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.RichTextBoxSelTabs)) ] - public int[] SelectionTabs { - get { + public int[] SelectionTabs + { + get + { int[] selTabs = new int[0]; ForceHandleCreate(); @@ -1216,7 +1380,8 @@ public int[] SelectionTabs { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_GETPARAFORMAT, 0, pf); // check if alignment has been set yet - if ((RichTextBoxConstants.PFM_TABSTOPS & pf.dwMask) != 0) { + if ((RichTextBoxConstants.PFM_TABSTOPS & pf.dwMask) != 0) + { selTabs = new int[pf.cTabCount]; for (int x = 0; x < pf.cTabCount; x++) selTabs[x] = Twip2Pixel(IntPtr.Zero, pf.rgxTabs[x], true); @@ -1224,7 +1389,8 @@ public int[] SelectionTabs { return selTabs; } - set { + set + { // Verify the argument, and throw an error if is bad if (value != null && value.Length > RichTextBoxConstants.MAX_TAB_STOPS) throw new ArgumentOutOfRangeException(nameof(SelectionTabs), SR.SelTabCountRange); @@ -1257,14 +1423,17 @@ public int[] SelectionTabs { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.RichTextBoxSelText)) ] - public override string SelectedText { - get { + public override string SelectedText + { + get + { ForceHandleCreate(); string text = StreamOut(RichTextBoxConstants.SFF_SELECTION | RichTextBoxConstants.SF_TEXT | RichTextBoxConstants.SF_UNICODE); return text; } - set { + set + { ForceHandleCreate(); StreamIn(value, RichTextBoxConstants.SFF_SELECTION | RichTextBoxConstants.SF_TEXT | RichTextBoxConstants.SF_UNICODE); } @@ -1280,15 +1449,19 @@ public override string SelectedText { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.RichTextBoxSelTypeDescr)) ] - public RichTextBoxSelectionTypes SelectionType { - get { + public RichTextBoxSelectionTypes SelectionType + { + get + { ForceHandleCreate(); - if (SelectionLength > 0) { + if (SelectionLength > 0) + { int n; - n = unchecked( (int) (long)SendMessage(Interop.EditMessages.EM_SELECTIONTYPE, 0, 0)); + n = unchecked((int)(long)SendMessage(Interop.EditMessages.EM_SELECTIONTYPE, 0, 0)); return (RichTextBoxSelectionTypes)n; } - else { + else + { return RichTextBoxSelectionTypes.Empty; } } @@ -1303,12 +1476,16 @@ public RichTextBoxSelectionTypes SelectionType { DefaultValue(false), SRDescription(nameof(SR.RichTextBoxSelMargin)) ] - public bool ShowSelectionMargin { + public bool ShowSelectionMargin + { get { return richTextBoxFlags[showSelBarSection] != 0; } - set { - if (value != ShowSelectionMargin) { + set + { + if (value != ShowSelectionMargin) + { richTextBoxFlags[showSelBarSection] = value ? 1 : 0; - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(Interop.EditMessages.EM_SETOPTIONS, value ? RichTextBoxConstants.ECOOP_OR : RichTextBoxConstants.ECOOP_XOR, @@ -1322,26 +1499,34 @@ public bool ShowSelectionMargin { Localizable(true), RefreshProperties(RefreshProperties.All) ] - public override string Text { - get { - if (IsDisposed) { + public override string Text + { + get + { + if (IsDisposed) + { return base.Text; } - if (RecreatingHandle || GetAnyDisposingInHierarchy()) { + if (RecreatingHandle || GetAnyDisposingInHierarchy()) + { // We can return any old garbage if we're in the process of recreating the handle return ""; } - if (!IsHandleCreated && textRtf == null) { - if (textPlain != null) { + if (!IsHandleCreated && textRtf == null) + { + if (textPlain != null) + { return textPlain; } - else { + else + { return base.Text; } } - else { + else + { // if the handle is created, we are golden, however // if the handle isn't created, but textRtf was // specified, we need the RichEdit to translate @@ -1352,15 +1537,20 @@ public override string Text { return StreamOut(RichTextBoxConstants.SF_TEXT | RichTextBoxConstants.SF_UNICODE); } } - set { - using(LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.Text)) { + set + { + using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.Text)) + { textRtf = null; - if (!IsHandleCreated) { + if (!IsHandleCreated) + { textPlain = value; } - else { + else + { textPlain = null; - if (value == null) { + if (value == null) + { value = string.Empty; } StreamIn(value, RichTextBoxConstants.SF_TEXT | RichTextBoxConstants.SF_UNICODE); @@ -1371,19 +1561,23 @@ public override string Text { } } - private bool SuppressTextChangedEvent { + private bool SuppressTextChangedEvent + { get { return richTextBoxFlags[suppressTextChangedEventSection] != 0; } - set { + set + { bool oldValue = SuppressTextChangedEvent; - if (value != oldValue) { - richTextBoxFlags[suppressTextChangedEventSection] = value ? 1 : 0; + if (value != oldValue) + { + richTextBoxFlags[suppressTextChangedEventSection] = value ? 1 : 0; CommonProperties.xClearPreferredSizeCache(this); } } } [Browsable(false)] - public override int TextLength { + public override int TextLength + { get { NativeMethods.GETTEXTLENGTHEX gtl = new NativeMethods.GETTEXTLENGTHEX @@ -1409,17 +1603,22 @@ public override int TextLength { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.RichTextBoxUndoActionNameDescr)) ] - public string UndoActionName { - get { - if (!CanUndo) return ""; + public string UndoActionName + { + get + { + if (!CanUndo) + return ""; int n; - n = unchecked( (int) (long)SendMessage(Interop.EditMessages.EM_GETUNDONAME, 0, 0)); + n = unchecked((int)(long)SendMessage(Interop.EditMessages.EM_GETUNDONAME, 0, 0)); return GetEditorActionName(n); } } - private string GetEditorActionName(int actionID) { - switch (actionID) { + private string GetEditorActionName(int actionID) + { + switch (actionID) + { case 0: return string.Format(SR.RichTextBox_IDUnknown); case 1: @@ -1449,21 +1648,27 @@ private string GetEditorActionName(int actionID) { Localizable(true), SRDescription(nameof(SR.RichTextBoxZoomFactor)) ] - public float ZoomFactor { - get { - if (IsHandleCreated) { + public float ZoomFactor + { + get + { + if (IsHandleCreated) + { int numerator = 0; int denominator = 0; SendMessage(Interop.EditMessages.EM_GETZOOM, ref numerator, ref denominator); - if ( (numerator != 0) && (denominator != 0) ) { - zoomMultiplier = ((float)numerator)/((float)denominator); + if ((numerator != 0) && (denominator != 0)) + { + zoomMultiplier = ((float)numerator) / ((float)denominator); } - else { + else + { zoomMultiplier = 1.0f; } return zoomMultiplier; } - else return zoomMultiplier; + else + return zoomMultiplier; } set @@ -1482,10 +1687,11 @@ public float ZoomFactor { [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.RichTextBoxContentsResized))] - public event ContentsResizedEventHandler ContentsResized { + public event ContentsResizedEventHandler ContentsResized + { add => Events.AddHandler(EVENT_REQUESTRESIZE, value); remove => Events.RemoveHandler(EVENT_REQUESTRESIZE, value); - } + } /// @@ -1493,7 +1699,8 @@ public event ContentsResizedEventHandler ContentsResized { /// may still be used: this should be hidden in the property grid, but not in code /// [Browsable(false)] - public new event DragEventHandler DragDrop { + public new event DragEventHandler DragDrop + { add => base.DragDrop += value; remove => base.DragDrop -= value; } @@ -1503,82 +1710,94 @@ public event ContentsResizedEventHandler ContentsResized { /// may still be used: this should be hidden in the property grid, but not in code /// [Browsable(false)] - public new event DragEventHandler DragEnter { + public new event DragEventHandler DragEnter + { add => base.DragEnter += value; remove => base.DragEnter -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler DragLeave { + public new event EventHandler DragLeave + { add => base.DragLeave += value; remove => base.DragLeave -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event DragEventHandler DragOver { + public new event DragEventHandler DragOver + { add => base.DragOver += value; remove => base.DragOver -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event GiveFeedbackEventHandler GiveFeedback { + public new event GiveFeedbackEventHandler GiveFeedback + { add => base.GiveFeedback += value; remove => base.GiveFeedback -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event QueryContinueDragEventHandler QueryContinueDrag { + public new event QueryContinueDragEventHandler QueryContinueDrag + { add => base.QueryContinueDrag += value; remove => base.QueryContinueDrag -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.RichTextBoxHScroll))] - public event EventHandler HScroll { + public event EventHandler HScroll + { add => Events.AddHandler(EVENT_HSCROLL, value); remove => Events.RemoveHandler(EVENT_HSCROLL, value); - } + } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.RichTextBoxLinkClick))] - public event LinkClickedEventHandler LinkClicked { + public event LinkClickedEventHandler LinkClicked + { add => Events.AddHandler(EVENT_LINKACTIVATE, value); remove => Events.RemoveHandler(EVENT_LINKACTIVATE, value); - } + } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.RichTextBoxIMEChange))] - public event EventHandler ImeChange { + public event EventHandler ImeChange + { add => Events.AddHandler(EVENT_IMECHANGE, value); remove => Events.RemoveHandler(EVENT_IMECHANGE, value); - } + } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.RichTextBoxProtected))] - public event EventHandler Protected { + public event EventHandler Protected + { add => Events.AddHandler(EVENT_PROTECTED, value); remove => Events.RemoveHandler(EVENT_PROTECTED, value); - } + } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.RichTextBoxSelChange))] - public event EventHandler SelectionChanged { + public event EventHandler SelectionChanged + { add => Events.AddHandler(EVENT_SELCHANGE, value); remove => Events.RemoveHandler(EVENT_SELCHANGE, value); - } + } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.RichTextBoxVScroll))] - public event EventHandler VScroll { + public event EventHandler VScroll + { add => Events.AddHandler(EVENT_VSCROLL, value); remove => Events.RemoveHandler(EVENT_VSCROLL, value); } - + /// /// Returns a boolean indicating whether the RichTextBoxConstants control can paste the /// given clipboard format. /// - public bool CanPaste(DataFormats.Format clipFormat) { + public bool CanPaste(DataFormats.Format clipFormat) + { bool b = false; - b = unchecked( (int) (long)SendMessage(Interop.EditMessages.EM_CANPASTE, clipFormat.Id, 0)) != 0; + b = unchecked((int)(long)SendMessage(Interop.EditMessages.EM_CANPASTE, clipFormat.Id, 0)) != 0; return b; } @@ -1591,111 +1810,131 @@ public bool CanPaste(DataFormats.Format clipFormat) { base.DrawToBitmap(bitmap, targetBounds); } - private unsafe int EditStreamProc(IntPtr dwCookie, IntPtr buf, int cb, out int transferred) { + private unsafe int EditStreamProc(IntPtr dwCookie, IntPtr buf, int cb, out int transferred) + { int ret = 0; // assume that everything is Okay byte[] bytes = new byte[cb]; int cookieVal = (int)dwCookie; - + transferred = 0; - try { - switch (cookieVal & DIRECTIONMASK) { - case RichTextBox.OUTPUT: { - if (editStream == null) { - editStream = new MemoryStream(); - } + try + { + switch (cookieVal & DIRECTIONMASK) + { + case RichTextBox.OUTPUT: + { + if (editStream == null) + { + editStream = new MemoryStream(); + } - switch (cookieVal & KINDMASK) { - case RichTextBox.RTF: - case RichTextBox.TEXTCRLF: - Marshal.Copy(buf, bytes, 0, cb); - editStream.Write(bytes, 0, cb); - break; - case RichTextBox.TEXTLF: - // Strip out \r characters so that we consistently return - // \n for linefeeds. In a future version the RichEdit control - // may support a SF_NOXLATCRLF flag which would do this for - // us. Internally the RichEdit stores the text with only - // a \n, so we want to keep that the same here. - // - if ((cookieVal & UNICODE) != 0) { - Debug.Assert(cb % 2 == 0, "EditStreamProc call out of cycle. Expected to always get character boundary calls"); - int requestedCharCount = cb/2; - int consumedCharCount = 0; - - fixed (byte* pb = bytes) { - char* pChars = (char*)pb; - char* pBuffer = (char*)(long)buf; - - for (int i=0; i /// Searches the text in a RichTextBox control for a given string. /// - public int Find(string str) { + public int Find(string str) + { return Find(str, 0, 0, RichTextBoxFinds.None); } /// /// Searches the text in a RichTextBox control for a given string. /// - public int Find(string str, RichTextBoxFinds options) { + public int Find(string str, RichTextBoxFinds options) + { return Find(str, 0, 0, options); } /// /// Searches the text in a RichTextBox control for a given string. /// - public int Find(string str, int start, RichTextBoxFinds options) { + public int Find(string str, int start, RichTextBoxFinds options) + { return Find(str, start, -1, options); - } + } /// /// Searches the text in a RichTextBox control for a given string. /// - public int Find(string str, int start, int end, RichTextBoxFinds options) { + public int Find(string str, int start, int end, RichTextBoxFinds options) + { int textLen = TextLength; @@ -1752,21 +1995,25 @@ public int Find(string str, int start, int end, RichTextBoxFinds options) { // set up the default values for the FINDTEXT structure, that is // the given string and the whole range of the text stream ft.lpstrText = str; - if (end == -1) { + if (end == -1) + { end = textLen; } - if (start > end) { + if (start > end) + { throw new ArgumentException(string.Format(SR.RichTextFindEndInvalid, end)); } - if ((options & RichTextBoxFinds.Reverse) != RichTextBoxFinds.Reverse) { + if ((options & RichTextBoxFinds.Reverse) != RichTextBoxFinds.Reverse) + { // normal // ft.chrg.cpMin = start; ft.chrg.cpMax = end; } - else { + else + { // reverse // ft.chrg.cpMin = end; @@ -1774,12 +2021,15 @@ public int Find(string str, int start, int end, RichTextBoxFinds options) { } // force complete search if we ended up with a zero length search - if (ft.chrg.cpMin == ft.chrg.cpMax) { - if ((options & RichTextBoxFinds.Reverse) != RichTextBoxFinds.Reverse) { + if (ft.chrg.cpMin == ft.chrg.cpMax) + { + if ((options & RichTextBoxFinds.Reverse) != RichTextBoxFinds.Reverse) + { ft.chrg.cpMin = 0; ft.chrg.cpMax = -1; } - else { + else + { ft.chrg.cpMin = textLen; ft.chrg.cpMax = 0; } @@ -1793,7 +2043,8 @@ public int Find(string str, int start, int end, RichTextBoxFinds options) { findOptions |= RichTextBoxConstants.FR_MATCHCASE; if ((options & RichTextBoxFinds.NoHighlight) == RichTextBoxFinds.NoHighlight) selectWord = false; - if ((options & RichTextBoxFinds.Reverse) != RichTextBoxFinds.Reverse) { + if ((options & RichTextBoxFinds.Reverse) != RichTextBoxFinds.Reverse) + { // The default for RichEdit 2.0 is to search in reverse findOptions |= RichTextBoxConstants.FR_DOWN; } @@ -1802,11 +2053,12 @@ public int Find(string str, int start, int end, RichTextBoxFinds options) { int position; position = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_FINDTEXT, findOptions, ft); - + // if we didn't find anything, or we don't have to select what was found, // we're done - if (position != -1 && selectWord) { + if (position != -1 && selectWord) + { // Select the string found, this is done in ubyte units NativeMethods.CHARRANGE chrg = new NativeMethods.CHARRANGE(); chrg.cpMin = position; @@ -1850,21 +2102,24 @@ public int Find(string str, int start, int end, RichTextBoxFinds options) { /// /// Searches the text in a RichTextBox control for the given characters. /// - public int Find(char[] characterSet) { + public int Find(char[] characterSet) + { return Find(characterSet, 0, -1); } /// /// Searches the text in a RichTextBox control for the given characters. /// - public int Find(char[] characterSet, int start) { + public int Find(char[] characterSet, int start) + { return Find(characterSet, start, -1); } /// /// Searches the text in a RichTextBox control for the given characters. /// - public int Find(char[] characterSet, int start, int end) { + public int Find(char[] characterSet, int start, int end) + { // Code used to support ability to search backwards and negate character sets. // The API no longer supports this, but in case we change our mind, I'm leaving // the ability in here. @@ -1885,11 +2140,13 @@ public int Find(char[] characterSet, int start, int end) { return -1; int textLen = Interop.User32.GetWindowTextLengthW(new HandleRef(this, Handle)); - if (start == end) { + if (start == end) + { start = 0; end = textLen; } - if (end == -1) { + if (end == -1) + { end = textLen; } @@ -1905,25 +2162,29 @@ public int Find(char[] characterSet, int start, int end) { txrg.chrg.cpMax = chrg.cpMax; UnsafeNativeMethods.CharBuffer charBuffer; charBuffer = UnsafeNativeMethods.CharBuffer.CreateBuffer(CHAR_BUFFER_LEN + 1); - + txrg.lpstrText = charBuffer.AllocCoTaskMem(); if (txrg.lpstrText == IntPtr.Zero) throw new OutOfMemoryException(); - try { + try + { bool done = false; // We want to loop as long as it takes. This loop will grab a // chunk of text out from the control as directed by txrg.chrg; - while (!done) { - if (forward) { + while (!done) + { + if (forward) + { // Move forward by starting at the end of the // previous text window and extending by the // size of our buffer txrg.chrg.cpMin = chrg.cpMax; txrg.chrg.cpMax += CHAR_BUFFER_LEN; } - else { + else + { // Move backwards by anchoring at the start // of the previous buffer window, and backing // up by the desired size of our buffer @@ -1942,7 +2203,8 @@ public int Find(char[] characterSet, int start, int end) { // go get the text in this range, if we didn't get any text then punt int len; len = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_GETTEXTRANGE, 0, txrg); - if (len == 0) { + if (len == 0) + { chrg.cpMax = chrg.cpMin = -1; // Hit end of control without finding what we wanted break; } @@ -1950,15 +2212,18 @@ public int Find(char[] characterSet, int start, int end) { // get the data from RichTextBoxConstants into a string for us to use. charBuffer.PutCoTaskMem(txrg.lpstrText); string str = charBuffer.GetString(); - + // Loop through our text - if (forward) { + if (forward) + { // Start at the begining of the buffer - for (int x = 0; x < len; x++) { + for (int x = 0; x < len; x++) + { // Is it in char set? bool found = GetCharInCharSet(str[x], characterSet, negate); - if (found) { + if (found) + { done = true; break; } @@ -1967,13 +2232,16 @@ public int Find(char[] characterSet, int start, int end) { chrg.cpMax++; } } - else { // Span reverse. + else + { // Span reverse. int x = len; - while (x-- != 0) { + while (x-- != 0) + { // Is it in char set? bool found = GetCharInCharSet(str[x], characterSet, negate); - if (found) { + if (found) + { done = true; break; } @@ -1984,16 +2252,19 @@ public int Find(char[] characterSet, int start, int end) { } } } - finally { + finally + { // release the resources we got for our GETTEXTRANGE operation. - if (txrg.lpstrText != IntPtr.Zero) Marshal.FreeCoTaskMem(txrg.lpstrText); + if (txrg.lpstrText != IntPtr.Zero) + Marshal.FreeCoTaskMem(txrg.lpstrText); } int index = (forward) ? chrg.cpMax : chrg.cpMin; return index; } - private void ForceHandleCreate() { + private void ForceHandleCreate() + { if (!IsHandleCreated) { CreateHandle(); @@ -2001,10 +2272,12 @@ private void ForceHandleCreate() { } // Sends set color message to HWND; doesn't call Control.SetForeColor - private bool InternalSetForeColor(Color value) { + private bool InternalSetForeColor(Color value) + { NativeMethods.CHARFORMATA cf = GetCharFormat(false); - if ((cf.dwMask & RichTextBoxConstants.CFM_COLOR) != 0 - && ColorTranslator.ToWin32(value) == cf.crTextColor) { + if ((cf.dwMask & RichTextBoxConstants.CFM_COLOR) != 0 + && ColorTranslator.ToWin32(value) == cf.crTextColor) + { return true; } @@ -2016,13 +2289,15 @@ private bool InternalSetForeColor(Color value) { } - private NativeMethods.CHARFORMATA GetCharFormat(bool fSelection) { + private NativeMethods.CHARFORMATA GetCharFormat(bool fSelection) + { NativeMethods.CHARFORMATA cf = new NativeMethods.CHARFORMATA(); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_GETCHARFORMAT, fSelection ? RichTextBoxConstants.SCF_SELECTION : RichTextBoxConstants.SCF_DEFAULT, cf); return cf; } - private NativeMethods.CHARFORMAT2A GetCharFormat2(bool fSelection) { + private NativeMethods.CHARFORMAT2A GetCharFormat2(bool fSelection) + { NativeMethods.CHARFORMAT2A cf2 = new NativeMethods.CHARFORMAT2A(); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_GETCHARFORMAT, fSelection ? RichTextBoxConstants.SCF_SELECTION : RichTextBoxConstants.SCF_DEFAULT, cf2); return cf2; @@ -2030,11 +2305,13 @@ private NativeMethods.CHARFORMAT2A GetCharFormat2(bool fSelection) { /// /// - private RichTextBoxSelectionAttribute GetCharFormat(int mask, int effect) { + private RichTextBoxSelectionAttribute GetCharFormat(int mask, int effect) + { RichTextBoxSelectionAttribute charFormat = RichTextBoxSelectionAttribute.None; // check to see if the control has been created - if (IsHandleCreated) { + if (IsHandleCreated) + { NativeMethods.CHARFORMATA cf = GetCharFormat(true); // if the effects member contains valid info if ((cf.dwMask & mask) != 0) @@ -2046,24 +2323,29 @@ private RichTextBoxSelectionAttribute GetCharFormat(int mask, int effect) { return charFormat; } - Font GetCharFormatFont(bool selectionOnly) { + Font GetCharFormatFont(bool selectionOnly) + { ForceHandleCreate(); NativeMethods.CHARFORMATA cf = GetCharFormat(selectionOnly); - if ((cf.dwMask & RichTextBoxConstants.CFM_FACE) == 0) { + if ((cf.dwMask & RichTextBoxConstants.CFM_FACE) == 0) + { return null; } string fontName = Encoding.Default.GetString(cf.szFaceName); int index = fontName.IndexOf('\0'); - if (index != -1) { + if (index != -1) + { fontName = fontName.Substring(0, index); } float fontSize = 13; - if ((cf.dwMask & RichTextBoxConstants.CFM_SIZE) != 0) { - fontSize = (float)cf.yHeight/(float)20.0; - if (fontSize == 0 && cf.yHeight > 0) { + if ((cf.dwMask & RichTextBoxConstants.CFM_SIZE) != 0) + { + fontSize = (float)cf.yHeight / (float)20.0; + if (fontSize == 0 && cf.yHeight > 0) + { fontSize = 1; } } @@ -2078,10 +2360,12 @@ Font GetCharFormatFont(bool selectionOnly) { if ((cf.dwMask & RichTextBoxConstants.CFM_UNDERLINE) != 0 && (cf.dwEffects & RichTextBoxConstants.CFE_UNDERLINE) != 0) style |= FontStyle.Underline; - try { + try + { return new Font(fontName, fontSize, style, GraphicsUnit.Point, cf.bCharSet); } - catch { + catch + { } return null; @@ -2090,7 +2374,8 @@ Font GetCharFormatFont(bool selectionOnly) { /// /// Returns the index of the character nearest to the given point. /// - public override int GetCharIndexFromPosition(Point pt) { + public override int GetCharIndexFromPosition(Point pt) + { NativeMethods.POINT wpt = new NativeMethods.POINT(pt.X, pt.Y); int index = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_CHARFROMPOS, 0, wpt); @@ -2098,7 +2383,8 @@ public override int GetCharIndexFromPosition(Point pt) { // EM_CHARFROMPOS will return an invalid number if the last character in the RichEdit // is a newline. // - if (index >= t.Length) { + if (index >= t.Length) + { index = Math.Max(t.Length - 1, 0); } return index; @@ -2106,7 +2392,8 @@ public override int GetCharIndexFromPosition(Point pt) { /// /// - private bool GetCharInCharSet(char c, char[] charSet, bool negate) { + private bool GetCharInCharSet(char c, char[] charSet, bool negate) + { bool match = false; int charSetLen = charSet.Length; @@ -2125,19 +2412,23 @@ private bool GetCharInCharSet(char c, char[] charSet, bool negate) { /// you pass the index of a overflowed character, GetLineFromCharIndex would /// return 1 and not 0. /// - public override int GetLineFromCharIndex(int index) { - return unchecked( (int) (long)SendMessage(Interop.EditMessages.EM_EXLINEFROMCHAR, 0, index)); + public override int GetLineFromCharIndex(int index) + { + return unchecked((int)(long)SendMessage(Interop.EditMessages.EM_EXLINEFROMCHAR, 0, index)); } /// /// Returns the location of the character at the given index. /// - public override Point GetPositionFromCharIndex(int index) { - if (richEditMajorVersion == 2) { + public override Point GetPositionFromCharIndex(int index) + { + if (richEditMajorVersion == 2) + { return base.GetPositionFromCharIndex(index); } - if (index < 0 || index > Text.Length) { + if (index < 0 || index > Text.Length) + { return Point.Empty; } @@ -2148,8 +2439,10 @@ public override Point GetPositionFromCharIndex(int index) { /// /// - private bool GetProtectedError() { - if (ProtectedError) { + private bool GetProtectedError() + { + if (ProtectedError) + { ProtectedError = false; return true; } @@ -2160,28 +2453,33 @@ private bool GetProtectedError() { /// /// Loads the contents of the given RTF or text file into a RichTextBox control. /// - - - public void LoadFile(string path) { + + + public void LoadFile(string path) + { LoadFile(path, RichTextBoxStreamType.RichText); } /// /// Loads the contents of a RTF or text into a RichTextBox control. /// - - - public void LoadFile(string path, RichTextBoxStreamType fileType) { + + + public void LoadFile(string path, RichTextBoxStreamType fileType) + { //valid values are 0x0 to 0x4 - if (!ClientUtils.IsEnumValid(fileType, (int)fileType, (int)RichTextBoxStreamType.RichText, (int)RichTextBoxStreamType.UnicodePlainText)){ + if (!ClientUtils.IsEnumValid(fileType, (int)fileType, (int)RichTextBoxStreamType.RichText, (int)RichTextBoxStreamType.UnicodePlainText)) + { throw new InvalidEnumArgumentException(nameof(fileType), (int)fileType, typeof(RichTextBoxStreamType)); } - + Stream file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); - try { + try + { LoadFile(file, fileType); } - finally { + finally + { file.Close(); } } @@ -2189,15 +2487,17 @@ public void LoadFile(string path, RichTextBoxStreamType fileType) { /// /// Loads the contents of a RTF or text into a RichTextBox control. /// - public void LoadFile(Stream data, RichTextBoxStreamType fileType) { + public void LoadFile(Stream data, RichTextBoxStreamType fileType) + { //valid values are 0x0 to 0x4 if (!ClientUtils.IsEnumValid(fileType, (int)fileType, (int)RichTextBoxStreamType.RichText, (int)RichTextBoxStreamType.UnicodePlainText)) { throw new InvalidEnumArgumentException(nameof(fileType), (int)fileType, typeof(RichTextBoxStreamType)); } - + int flags; - switch (fileType) { + switch (fileType) + { case RichTextBoxStreamType.RichText: flags = RichTextBoxConstants.SF_RTF; break; @@ -2216,7 +2516,8 @@ public void LoadFile(Stream data, RichTextBoxStreamType fileType) { } - protected override void OnBackColorChanged(EventArgs e) { + protected override void OnBackColorChanged(EventArgs e) + { if (IsHandleCreated) { SendMessage(Interop.EditMessages.EM_SETBKGNDCOLOR, 0, ColorTranslator.ToWin32(BackColor)); @@ -2230,7 +2531,8 @@ protected override void OnContextMenuChanged(EventArgs e) UpdateOleCallback(); } - protected override void OnRightToLeftChanged(EventArgs e) { + protected override void OnRightToLeftChanged(EventArgs e) + { base.OnRightToLeftChanged(e); // When the RTL property is changed, here's what happens. Let's assume that we change from // RTL.No to RTL.Yes. @@ -2256,7 +2558,7 @@ protected override void OnRightToLeftChanged(EventArgs e) { // So the fix is to force windowtext, whether or not that window text is equal to what's already there. // Note that in doing so we will lose any formatting info you might have set on the RTF. We are okay with that. - + // We use WindowText rather than Text because this way we can avoid // spurious TextChanged events. // @@ -2269,12 +2571,15 @@ protected override void OnRightToLeftChanged(EventArgs e) { /// Fires an event when the user changes the control's contents /// are either smaller or larger than the control's window size. /// - protected virtual void OnContentsResized(ContentsResizedEventArgs e) { + protected virtual void OnContentsResized(ContentsResizedEventArgs e) + { ContentsResizedEventHandler handler = (ContentsResizedEventHandler)Events[EVENT_REQUESTRESIZE]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { // base.OnHandleCreated is called somewhere in the middle of this curSelStart = curSelEnd = curSelType = -1; @@ -2293,7 +2598,7 @@ protected override void OnHandleCreated(EventArgs e) { RichTextBoxConstants.ENM_PROTECTED | RichTextBoxConstants.ENM_SELCHANGE | RichTextBoxConstants.ENM_DROPFILES | RichTextBoxConstants.ENM_REQUESTRESIZE | RichTextBoxConstants.ENM_IMECHANGE | RichTextBoxConstants.ENM_CHANGE | - RichTextBoxConstants.ENM_UPDATE | RichTextBoxConstants.ENM_SCROLL | + RichTextBoxConstants.ENM_UPDATE | RichTextBoxConstants.ENM_SCROLL | RichTextBoxConstants.ENM_KEYEVENTS | RichTextBoxConstants.ENM_MOUSEEVENTS | RichTextBoxConstants.ENM_SCROLLEVENTS | RichTextBoxConstants.ENM_LINK); @@ -2305,7 +2610,8 @@ protected override void OnHandleCreated(EventArgs e) { this.SendMessage(Interop.EditMessages.EM_AUTOURLDETECT, DetectUrls ? 1 : 0, 0); - if (selectionBackColorToSetOnHandleCreated != Color.Empty) { + if (selectionBackColorToSetOnHandleCreated != Color.Empty) + { this.SelectionBackColor = selectionBackColorToSetOnHandleCreated; } @@ -2314,59 +2620,67 @@ protected override void OnHandleCreated(EventArgs e) { AutoWordSelection = AutoWordSelection; SendMessage(Interop.EditMessages.EM_SETBKGNDCOLOR, 0, ColorTranslator.ToWin32(BackColor)); InternalSetForeColor(ForeColor); - + // base sets the Text property. It's important to do this *after* setting EM_AUTOUrlDETECT. base.OnHandleCreated(e); - + // For some reason, we need to set the OleCallback before setting the RTF property. UpdateOleCallback(); // RTF property takes precedence over Text property // - try { + try + { SuppressTextChangedEvent = true; - if (textRtf != null) { + if (textRtf != null) + { // setting RTF calls back on Text, which relies on textRTF being null string text = textRtf; textRtf = null; Rtf = text; } - else if (textPlain != null) { + else if (textPlain != null) + { string text = textPlain; textPlain = null; Text = text; } } - finally { + finally + { SuppressTextChangedEvent = false; } - + // Since we can't send EM_SETSEL until RTF has been set, // we can't rely on base to do it for us. base.SetSelectionOnHandle(); - if (ShowSelectionMargin) { + if (ShowSelectionMargin) + { // If you call SendMessage instead of PostMessage, the control // will resize itself to the size of the parent's client area. Don't know why... UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_SETOPTIONS, (IntPtr)RichTextBoxConstants.ECOOP_OR, (IntPtr)RichTextBoxConstants.ECO_SELECTIONBAR); } - if (languageOption != this.LanguageOption) { + if (languageOption != this.LanguageOption) + { this.LanguageOption = languageOption; } ClearUndo(); - SendZoomFactor(zoomMultiplier); + SendZoomFactor(zoomMultiplier); SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(UserPreferenceChangedHandler); } - protected override void OnHandleDestroyed(EventArgs e) { + protected override void OnHandleDestroyed(EventArgs e) + { base.OnHandleDestroyed(e); - - if (!InConstructor) { + + if (!InConstructor) + { textRtf = Rtf; if (textRtf.Length == 0) textRtf = null; @@ -2380,55 +2694,67 @@ protected override void OnHandleDestroyed(EventArgs e) { /// Fires an event when the user clicks a RichTextBox control's horizontal /// scroll bar. /// - protected virtual void OnHScroll(EventArgs e) { + protected virtual void OnHScroll(EventArgs e) + { EventHandler handler = (EventHandler)Events[EVENT_HSCROLL]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// /// Fires an event when the user clicks on a link /// in a rich-edit control. /// - protected virtual void OnLinkClicked(LinkClickedEventArgs e) { + protected virtual void OnLinkClicked(LinkClickedEventArgs e) + { LinkClickedEventHandler handler = (LinkClickedEventHandler)Events[EVENT_LINKACTIVATE]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// /// Fires an event when the user changes the control's IME conversion status. /// - protected virtual void OnImeChange(EventArgs e) { + protected virtual void OnImeChange(EventArgs e) + { EventHandler handler = (EventHandler)Events[EVENT_IMECHANGE]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// /// Fires an event when the user is taking an action that would change /// a protected range of text in the RichTextBox control. /// - protected virtual void OnProtected(EventArgs e) { + protected virtual void OnProtected(EventArgs e) + { ProtectedError = true; EventHandler handler = (EventHandler)Events[EVENT_PROTECTED]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// /// Fires an event when the current selection of text in the RichTextBox /// control has changed or the insertion point has moved. /// - protected virtual void OnSelectionChanged(EventArgs e) { + protected virtual void OnSelectionChanged(EventArgs e) + { EventHandler handler = (EventHandler)Events[EVENT_SELCHANGE]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } - + /// /// Fires an event when the user clicks a RichTextBox control's vertical /// scroll bar. /// - protected virtual void OnVScroll(EventArgs e) { + protected virtual void OnVScroll(EventArgs e) + { EventHandler handler = (EventHandler)Events[EVENT_VSCROLL]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// @@ -2439,10 +2765,14 @@ public void Paste(DataFormats.Format clipFormat) UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_PASTESPECIAL, clipFormat.Id, 0); } - protected override bool ProcessCmdKey(ref Message m, Keys keyData) { - if (this.RichTextShortcutsEnabled == false) { - foreach (int shortcutValue in shortcutsToDisable) { - if ((int)keyData == shortcutValue) { + protected override bool ProcessCmdKey(ref Message m, Keys keyData) + { + if (this.RichTextShortcutsEnabled == false) + { + foreach (int shortcutValue in shortcutsToDisable) + { + if ((int)keyData == shortcutValue) + { return true; } } @@ -2453,7 +2783,8 @@ protected override bool ProcessCmdKey(ref Message m, Keys keyData) { /// /// Redoes the last undone editing operation. /// - public void Redo() { + public void Redo() + { SendMessage(Interop.EditMessages.EM_REDO, 0, 0); } @@ -2462,29 +2793,33 @@ public void Redo() { /// /// Saves the contents of a RichTextBox control to a file. /// - - - public void SaveFile(string path) { + + + public void SaveFile(string path) + { SaveFile(path, RichTextBoxStreamType.RichText); } /// /// Saves the contents of a RichTextBox control to a file. /// - - - public void SaveFile(string path, RichTextBoxStreamType fileType) { + + + public void SaveFile(string path, RichTextBoxStreamType fileType) + { //valid values are 0x0 to 0x4 if (!ClientUtils.IsEnumValid(fileType, (int)fileType, (int)RichTextBoxStreamType.RichText, (int)RichTextBoxStreamType.UnicodePlainText)) { throw new InvalidEnumArgumentException(nameof(fileType), (int)fileType, typeof(RichTextBoxStreamType)); } - + Stream file = File.Create(path); - try { + try + { SaveFile(file, fileType); } - finally { + finally + { file.Close(); } } @@ -2492,9 +2827,11 @@ public void SaveFile(string path, RichTextBoxStreamType fileType) { /// /// Saves the contents of a RichTextBox control to a file. /// - public void SaveFile(Stream data, RichTextBoxStreamType fileType) { + public void SaveFile(Stream data, RichTextBoxStreamType fileType) + { int flags; - switch (fileType) { + switch (fileType) + { case RichTextBoxStreamType.RichText: flags = RichTextBoxConstants.SF_RTF; break; @@ -2516,28 +2853,33 @@ public void SaveFile(Stream data, RichTextBoxStreamType fileType) { StreamOut(data, flags, true); } - + /// /// Core Zoom calculation and message passing (used by ZoomFactor property and CreateHandle() /// - private void SendZoomFactor(float zoom) { + private void SendZoomFactor(float zoom) + { int numerator; int denominator; - if (zoom == 1.0f) { + if (zoom == 1.0f) + { denominator = 0; numerator = 0; } - else { - denominator = 1000; + else + { + denominator = 1000; float multiplier = 1000 * zoom; numerator = (int)Math.Ceiling(multiplier); - if (numerator >= 64000) { + if (numerator >= 64000) + { numerator = (int)Math.Floor(multiplier); } } - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(Interop.EditMessages.EM_SETZOOM, numerator, denominator); #if DEBUG @@ -2550,24 +2892,29 @@ private void SendZoomFactor(float zoom) { #endif } - if (numerator != 0) { - zoomMultiplier = ((float)numerator)/((float)denominator); + if (numerator != 0) + { + zoomMultiplier = ((float)numerator) / ((float)denominator); } - else { + else + { zoomMultiplier = 1.0f; } } /// /// - private bool SetCharFormat(int mask, int effect, RichTextBoxSelectionAttribute charFormat) { + private bool SetCharFormat(int mask, int effect, RichTextBoxSelectionAttribute charFormat) + { // check to see if the control has been created - if (IsHandleCreated) { + if (IsHandleCreated) + { NativeMethods.CHARFORMATA cf = new NativeMethods.CHARFORMATA(); cf.dwMask = mask; - switch (charFormat) { + switch (charFormat) + { case RichTextBoxSelectionAttribute.All: cf.dwEffects = effect; break; @@ -2584,11 +2931,13 @@ private bool SetCharFormat(int mask, int effect, RichTextBoxSelectionAttribute c return false; } - private bool SetCharFormat(int charRange, NativeMethods.CHARFORMATA cf) { + private bool SetCharFormat(int charRange, NativeMethods.CHARFORMATA cf) + { return IntPtr.Zero != UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_SETCHARFORMAT, charRange, cf); } - private void SetCharFormatFont(bool selectionOnly, Font value) { + private void SetCharFormatFont(bool selectionOnly, Font value) + { ForceHandleCreate(); NativeMethods.LOGFONT logfont = new NativeMethods.LOGFONT(); @@ -2601,18 +2950,23 @@ private void SetCharFormatFont(bool selectionOnly, Font value) { RichTextBoxConstants.CFM_CHARSET; int dwEffects = 0; - if (value.Bold) dwEffects |= RichTextBoxConstants.CFE_BOLD; - if (value.Italic) dwEffects |= RichTextBoxConstants.CFE_ITALIC; - if (value.Strikeout) dwEffects |= RichTextBoxConstants.CFE_STRIKEOUT; - if (value.Underline) dwEffects |= RichTextBoxConstants.CFE_UNDERLINE; + if (value.Bold) + dwEffects |= RichTextBoxConstants.CFE_BOLD; + if (value.Italic) + dwEffects |= RichTextBoxConstants.CFE_ITALIC; + if (value.Strikeout) + dwEffects |= RichTextBoxConstants.CFE_STRIKEOUT; + if (value.Underline) + dwEffects |= RichTextBoxConstants.CFE_UNDERLINE; bytesFaceName = Encoding.Unicode.GetBytes(logfont.lfFaceName); NativeMethods.CHARFORMATW cfW = new NativeMethods.CHARFORMATW(); - for (int i=0; i /// - private static void SetupLogPixels(IntPtr hDC) { + private static void SetupLogPixels(IntPtr hDC) + { bool release = false; - if (hDC == IntPtr.Zero) { + if (hDC == IntPtr.Zero) + { hDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef); release = true; } - if (hDC == IntPtr.Zero) return; + if (hDC == IntPtr.Zero) + return; logPixelsX = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, hDC), NativeMethods.LOGPIXELSX); logPixelsY = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, hDC), NativeMethods.LOGPIXELSY); if (release) UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, hDC)); } - private static int Pixel2Twip(IntPtr hDC, int v, bool xDirection) { + private static int Pixel2Twip(IntPtr hDC, int v, bool xDirection) + { SetupLogPixels(hDC); int logP = xDirection ? logPixelsX : logPixelsY; - return(int) ((((double)v) / logP) * 72.0 * 20.0); + return (int)((((double)v) / logP) * 72.0 * 20.0); } - private static int Twip2Pixel(IntPtr hDC, int v, bool xDirection) { + private static int Twip2Pixel(IntPtr hDC, int v, bool xDirection) + { SetupLogPixels(hDC); int logP = xDirection ? logPixelsX : logPixelsY; - return(int) (((((double) v) / 20.0) / 72.0) * logP); + return (int)(((((double)v) / 20.0) / 72.0) * logP); } /// /// - private void StreamIn(string str, int flags) { - if (str.Length == 0 ) { + private void StreamIn(string str, int flags) + { + if (str.Length == 0) + { // Destroy the selection if callers was setting // selection text // - if ((RichTextBoxConstants.SFF_SELECTION & flags) != 0) { + if ((RichTextBoxConstants.SFF_SELECTION & flags) != 0) + { SendMessage(Interop.WindowMessages.WM_CLEAR, 0, 0); ProtectedError = false; return; @@ -2666,17 +3028,20 @@ private void StreamIn(string str, int flags) { // Rather than work only some of the time with null characters, // we're going to be consistent and never work with them. - int nullTerminatedLength = str.IndexOf((char) 0); - if (nullTerminatedLength != -1) { + int nullTerminatedLength = str.IndexOf((char)0); + if (nullTerminatedLength != -1) + { str = str.Substring(0, nullTerminatedLength); } // get the string into a byte array byte[] encodedBytes; - if ((flags & RichTextBoxConstants.SF_UNICODE) != 0) { + if ((flags & RichTextBoxConstants.SF_UNICODE) != 0) + { encodedBytes = Encoding.Unicode.GetBytes(str); } - else { + else + { encodedBytes = Encoding.Default.GetBytes(str); } editStream = new MemoryStream(encodedBytes.Length); @@ -2685,22 +3050,26 @@ private void StreamIn(string str, int flags) { StreamIn(editStream, flags); } - private void StreamIn(Stream data, int flags) { + private void StreamIn(Stream data, int flags) + { // clear out the selection only if we are replacing all the text // - if ((flags & RichTextBoxConstants.SFF_SELECTION) == 0) { + if ((flags & RichTextBoxConstants.SFF_SELECTION) == 0) + { NativeMethods.CHARRANGE cr = new NativeMethods.CHARRANGE(); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_EXSETSEL, 0, cr); } - try { + try + { editStream = data; Debug.Assert(data != null, "StreamIn passed a null stream"); // If SF_RTF is requested then check for the RTF tag at the start // of the file. We don't load if the tag is not there // - if ((flags & RichTextBoxConstants.SF_RTF) != 0) { + if ((flags & RichTextBoxConstants.SF_RTF) != 0) + { long streamStart = editStream.Position; byte[] bytes = new byte[SZ_RTF_TAG.Length]; editStream.Read(bytes, (int)streamStart, SZ_RTF_TAG.Length); @@ -2715,19 +3084,23 @@ private void StreamIn(Stream data, int flags) { int cookieVal = 0; // set up structure to do stream operation NativeMethods.EDITSTREAM es = new NativeMethods.EDITSTREAM(); - if ((flags & RichTextBoxConstants.SF_UNICODE) != 0) { + if ((flags & RichTextBoxConstants.SF_UNICODE) != 0) + { cookieVal = INPUT | UNICODE; } - else { + else + { cookieVal = INPUT | ANSI; } - if ((flags & RichTextBoxConstants.SF_RTF) != 0) { + if ((flags & RichTextBoxConstants.SF_RTF) != 0) + { cookieVal |= RTF; } - else { + else + { cookieVal |= TEXTLF; } - es.dwCookie = (IntPtr) cookieVal; + es.dwCookie = (IntPtr)cookieVal; es.pfnCallback = new NativeMethods.EditStreamCallback(this.EditStreamProc); // gives us TextBox compatible behavior, programatic text change shouldn't @@ -2736,20 +3109,22 @@ private void StreamIn(Stream data, int flags) { SendMessage(Interop.EditMessages.EM_EXLIMITTEXT, 0, int.MaxValue); - + // go get the text for the control // Needed for 64-bit - if (IntPtr.Size == 8) { + if (IntPtr.Size == 8) + { NativeMethods.EDITSTREAM64 es64 = ConvertToEDITSTREAM64(es); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_STREAMIN, flags, es64); //Assign back dwError value es.dwError = GetErrorValue64(es64); } - else { + else + { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_STREAMIN, flags, es); } - + UpdateMaxLength(); // If we failed to load because of protected @@ -2766,10 +3141,11 @@ private void StreamIn(Stream data, int flags) { // EM_GETLINECOUNT will cause the RichTextBoxConstants to recalculate its line indexes SendMessage(Interop.EditMessages.EM_GETLINECOUNT, 0, 0); - - + + } - finally { + finally + { // release any storage space held. editStream = null; } @@ -2777,71 +3153,86 @@ private void StreamIn(Stream data, int flags) { /// /// - private string StreamOut(int flags) { + private string StreamOut(int flags) + { Stream stream = new MemoryStream(); StreamOut(stream, flags, false); stream.Position = 0; int streamLength = (int)stream.Length; string result = string.Empty; - - if (streamLength > 0) { + + if (streamLength > 0) + { byte[] bytes = new byte[streamLength]; stream.Read(bytes, 0, streamLength); - if ((flags & RichTextBoxConstants.SF_UNICODE) != 0) { - result = Encoding.Unicode.GetString(bytes,0 , bytes.Length); + if ((flags & RichTextBoxConstants.SF_UNICODE) != 0) + { + result = Encoding.Unicode.GetString(bytes, 0, bytes.Length); } - else { + else + { result = Encoding.Default.GetString(bytes, 0, bytes.Length); } // workaround ??? for - if(!string.IsNullOrEmpty(result) && (result[result.Length-1] == '\0')) { - result = result.Substring(0, result.Length-1); + if (!string.IsNullOrEmpty(result) && (result[result.Length - 1] == '\0')) + { + result = result.Substring(0, result.Length - 1); } } return result; } - private void StreamOut(Stream data, int flags, bool includeCrLfs) { + private void StreamOut(Stream data, int flags, bool includeCrLfs) + { // set up the EDITSTREAM structure for the callback. Debug.Assert(data != null, "StreamOut passed a null stream"); editStream = data; - try { + try + { int cookieVal = 0; NativeMethods.EDITSTREAM es = new NativeMethods.EDITSTREAM(); - if ((flags & RichTextBoxConstants.SF_UNICODE) != 0) { + if ((flags & RichTextBoxConstants.SF_UNICODE) != 0) + { cookieVal = OUTPUT | UNICODE; } - else { + else + { cookieVal = OUTPUT | ANSI; } - if ((flags & RichTextBoxConstants.SF_RTF) != 0) { + if ((flags & RichTextBoxConstants.SF_RTF) != 0) + { cookieVal |= RTF; } - else { - if (includeCrLfs) { + else + { + if (includeCrLfs) + { cookieVal |= TEXTCRLF; } - else { + else + { cookieVal |= TEXTLF; } } - es.dwCookie = (IntPtr) cookieVal; + es.dwCookie = (IntPtr)cookieVal; es.pfnCallback = new NativeMethods.EditStreamCallback(this.EditStreamProc); // Get Text // Needed for 64-bit - if (IntPtr.Size == 8) { + if (IntPtr.Size == 8) + { NativeMethods.EDITSTREAM64 es64 = ConvertToEDITSTREAM64(es); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_STREAMOUT, flags, es64); //Assign back dwError value es.dwError = GetErrorValue64(es64); } - else { + else + { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_STREAMOUT, flags, es); } @@ -2849,83 +3240,92 @@ private void StreamOut(Stream data, int flags, bool includeCrLfs) { if (es.dwError != 0) throw new InvalidOperationException(SR.SaveTextError); } - finally { + finally + { // release any storage space held. editStream = null; } } - private unsafe NativeMethods.EDITSTREAM64 ConvertToEDITSTREAM64(NativeMethods.EDITSTREAM es) { + private unsafe NativeMethods.EDITSTREAM64 ConvertToEDITSTREAM64(NativeMethods.EDITSTREAM es) + { NativeMethods.EDITSTREAM64 es64 = new NativeMethods.EDITSTREAM64(); - fixed (byte* es64p = &es64.contents[0]) { - byte *bp; + fixed (byte* es64p = &es64.contents[0]) + { + byte* bp; long l; - + /* l = (long) es.dwCookie; bp = (byte *) &l; for (int i=0; i < sizeof(long); i++) { es64.contents[i] = bp[i]; }*/ - *((long *)es64p) = (long) es.dwCookie; + *((long*)es64p) = (long)es.dwCookie; /* int il = es.dwError; bp = (byte *) &il; for (int i=0; i < sizeof(int); i++) { es64.contents[i+8] = bp[i]; }*/ - *((int *)(es64p + 8)) = es.dwError; - - l = (long) Marshal.GetFunctionPointerForDelegate(es.pfnCallback); - bp = (byte *) &l; - for (int i=0; i < sizeof(long); i++) { - es64.contents[i+12] = bp[i]; + *((int*)(es64p + 8)) = es.dwError; + + l = (long)Marshal.GetFunctionPointerForDelegate(es.pfnCallback); + bp = (byte*)&l; + for (int i = 0; i < sizeof(long); i++) + { + es64.contents[i + 12] = bp[i]; } //*((long *)(es64p + 12)) = (long) Marshal.GetFunctionPointerForDelegate(es.pfnCallback); } - + return es64; } - private unsafe int GetErrorValue64(NativeMethods.EDITSTREAM64 es64) { + private unsafe int GetErrorValue64(NativeMethods.EDITSTREAM64 es64) + { int errorVal; - fixed (byte* es64p = &es64.contents[0]) { - errorVal = *((int *)(es64p + 8)); + fixed (byte* es64p = &es64.contents[0]) + { + errorVal = *((int*)(es64p + 8)); } return errorVal; } -/* FOR 64 BIT DEBUGGING - private unsafe string PrintBytes(NativeMethods.EDITSTREAM es) { - StringBuilder sb = new StringBuilder(); - fixed (IntPtr *ip = &es.dwCookie) { - byte *bytep = (byte *) ip; - for (int i=0; i < Marshal.SizeOf(es); i++) { - sb.Append(bytep[i].ToString() + " "); + /* FOR 64 BIT DEBUGGING + private unsafe string PrintBytes(NativeMethods.EDITSTREAM es) { + StringBuilder sb = new StringBuilder(); + fixed (IntPtr *ip = &es.dwCookie) { + byte *bytep = (byte *) ip; + for (int i=0; i < Marshal.SizeOf(es); i++) { + sb.Append(bytep[i].ToString() + " "); + } + } + return sb.ToString(); } - } - return sb.ToString(); - } - private unsafe string PrintBytes(NativeMethods.EDITSTREAM64 es64) { - StringBuilder sb = new StringBuilder(); - fixed (byte *bytep = &es64.contents[0]) { - for (int i=0; i < Marshal.SizeOf(es64); i++) { - sb.Append(bytep[i].ToString() + " "); + private unsafe string PrintBytes(NativeMethods.EDITSTREAM64 es64) { + StringBuilder sb = new StringBuilder(); + fixed (byte *bytep = &es64.contents[0]) { + for (int i=0; i < Marshal.SizeOf(es64); i++) { + sb.Append(bytep[i].ToString() + " "); + } + } + return sb.ToString(); } - } - return sb.ToString(); - } -*/ + */ - private void UpdateOleCallback() { + private void UpdateOleCallback() + { Debug.WriteLineIf(RichTextDbg.TraceVerbose, "update ole callback (" + AllowDrop + ")"); - if (IsHandleCreated) { - if (oleCallback == null) { + if (IsHandleCreated) + { + if (oleCallback == null) + { Debug.WriteLineIf(RichTextDbg.TraceVerbose, "binding ole callback"); this.AllowOleObjects = true; @@ -2936,17 +3336,22 @@ private void UpdateOleCallback() { // definitions of the interface. // IntPtr punk = Marshal.GetIUnknownForObject(oleCallback); - try { + try + { IntPtr pRichEditOleCallback; Guid iidRichEditOleCallback = typeof(UnsafeNativeMethods.IRichEditOleCallback).GUID; Marshal.QueryInterface(punk, ref iidRichEditOleCallback, out pRichEditOleCallback); - try { + try + { UnsafeNativeMethods.SendCallbackMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_SETOLECALLBACK, IntPtr.Zero, pRichEditOleCallback); } - finally { + finally + { Marshal.Release(pRichEditOleCallback); } - } finally { + } + finally + { Marshal.Release(punk); } } @@ -2976,25 +3381,30 @@ private void UserPreferenceChangedHandler(object o, UserPreferenceChangedEventAr /// information look up the MSDN info on this interface. This is designed to be a back door of /// sorts, which is why it is fairly obscure, and uses the RichEdit name instead of RichTextBox. /// - protected virtual object CreateRichEditOleCallback() { + protected virtual object CreateRichEditOleCallback() + { return new OleCallback(this); } /// /// Handles link messages (mouse move, down, up, dblclk, etc) /// - private void EnLinkMsgHandler(ref Message m) { + private void EnLinkMsgHandler(ref Message m) + { NativeMethods.ENLINK enlink; //On 64-bit, we do some custom marshalling to get this to work. The richedit control //unfortunately does not respect IA64 struct alignment conventions. - if (IntPtr.Size == 8) { + if (IntPtr.Size == 8) + { enlink = ConvertFromENLINK64((NativeMethods.ENLINK64)m.GetLParam(typeof(NativeMethods.ENLINK64))); } - else { + else + { enlink = (NativeMethods.ENLINK)m.GetLParam(typeof(NativeMethods.ENLINK)); } - switch (enlink.msg) { + switch (enlink.msg) + { case Interop.WindowMessages.WM_SETCURSOR: LinkCursor = true; m.Result = (IntPtr)1; @@ -3018,18 +3428,20 @@ private void EnLinkMsgHandler(ref Message m) { /// class name being used. We have to create a CharBuffer of the type of RichTextBox DLL we're using, /// not based on the SystemCharWidth. /// - private string CharRangeToString(NativeMethods.CHARRANGE c) { + private string CharRangeToString(NativeMethods.CHARRANGE c) + { NativeMethods.TEXTRANGE txrg = new NativeMethods.TEXTRANGE(); txrg.chrg = c; - Debug.Assert((c.cpMax-c.cpMin)>0, "CHARRANGE was null or negative - can't do it!"); + Debug.Assert((c.cpMax - c.cpMin) > 0, "CHARRANGE was null or negative - can't do it!"); //Windows - if (c.cpMax > Text.Length || c.cpMax-c.cpMin <= 0) { + if (c.cpMax > Text.Length || c.cpMax - c.cpMin <= 0) + { return string.Empty; } - int characters = (c.cpMax-c.cpMin) + 1; // +1 for null termination + int characters = (c.cpMax - c.cpMin) + 1; // +1 for null termination UnsafeNativeMethods.CharBuffer charBuffer = UnsafeNativeMethods.CharBuffer.CreateBuffer(characters); IntPtr unmanagedBuffer = charBuffer.AllocCoTaskMem(); if (unmanagedBuffer == IntPtr.Zero) @@ -3045,24 +3457,28 @@ private string CharRangeToString(NativeMethods.CHARRANGE c) { string result = charBuffer.GetString(); return result; } - - internal override void UpdateMaxLength() { - if (IsHandleCreated) { + + internal override void UpdateMaxLength() + { + if (IsHandleCreated) + { SendMessage(Interop.EditMessages.EM_EXLIMITTEXT, 0, MaxLength); } } /// /// - private void WmReflectCommand(ref Message m) { + private void WmReflectCommand(ref Message m) + { // We check if we're in the middle of handle creation because // the rich edit control fires spurious events during this time. // if (m.LParam == Handle && !GetState(STATE_CREATINGHANDLE)) { - switch (Util.HIWORD(m.WParam)) { - + switch (Util.HIWORD(m.WParam)) + { + case NativeMethods.EN_HSCROLL: OnHScroll(EventArgs.Empty); break; @@ -3076,17 +3492,21 @@ private void WmReflectCommand(ref Message m) { break; } } - else { + else + { base.WndProc(ref m); } } /// /// - internal void WmReflectNotify(ref Message m) { - if (m.HWnd == Handle) { + internal void WmReflectNotify(ref Message m) + { + if (m.HWnd == Handle) + { NativeMethods.NMHDR nmhdr = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR)); - switch (nmhdr.code) { + switch (nmhdr.code) + { case RichTextBoxConstants.EN_LINK: EnLinkMsgHandler(ref m); break; @@ -3119,46 +3539,53 @@ internal void WmReflectNotify(ref Message m) { break; case RichTextBoxConstants.EN_REQUESTRESIZE: - if (!CallOnContentsResized) { + if (!CallOnContentsResized) + { NativeMethods.REQRESIZE reqResize = (NativeMethods.REQRESIZE)m.GetLParam(typeof(NativeMethods.REQRESIZE)); - if (BorderStyle == System.Windows.Forms.BorderStyle.Fixed3D) { + if (BorderStyle == System.Windows.Forms.BorderStyle.Fixed3D) + { reqResize.rc.bottom++; } OnContentsResized(new ContentsResizedEventArgs(Rectangle.FromLTRB(reqResize.rc.left, reqResize.rc.top, reqResize.rc.right, reqResize.rc.bottom))); - } - break; + } + break; case RichTextBoxConstants.EN_SELCHANGE: NativeMethods.SELCHANGE selChange = (NativeMethods.SELCHANGE)m.GetLParam(typeof(NativeMethods.SELCHANGE)); WmSelectionChange(selChange); break; - case RichTextBoxConstants.EN_PROTECTED: { + case RichTextBoxConstants.EN_PROTECTED: + { NativeMethods.ENPROTECTED enprotected; - + //On 64-bit, we do some custom marshalling to get this to work. The richedit control //unfortunately does not respect IA64 struct alignment conventions. - if (IntPtr.Size == 8) { + if (IntPtr.Size == 8) + { enprotected = ConvertFromENPROTECTED64((NativeMethods.ENPROTECTED64)m.GetLParam(typeof(NativeMethods.ENPROTECTED64))); } - else { + else + { enprotected = (NativeMethods.ENPROTECTED)m.GetLParam(typeof(NativeMethods.ENPROTECTED)); } - switch (enprotected.msg) { + switch (enprotected.msg) + { case Interop.EditMessages.EM_SETCHARFORMAT: // Allow change of protected style // NativeMethods.CHARFORMATA charFormat = Marshal.PtrToStructure(enprotected.lParam); - if ((charFormat.dwMask & RichTextBoxConstants.CFM_PROTECTED) != 0) { + if ((charFormat.dwMask & RichTextBoxConstants.CFM_PROTECTED) != 0) + { m.Result = IntPtr.Zero; return; } break; - // Throw an exception for the following - // + // Throw an exception for the following + // case Interop.EditMessages.EM_SETPARAFORMAT: case Interop.EditMessages.EM_REPLACESEL: break; @@ -3166,21 +3593,21 @@ internal void WmReflectNotify(ref Message m) { case Interop.EditMessages.EM_STREAMIN: // Don't allow STREAMIN to replace protected selection // - if ((unchecked( (int) (long)enprotected.wParam) & RichTextBoxConstants.SFF_SELECTION) != 0) + if ((unchecked((int)(long)enprotected.wParam) & RichTextBoxConstants.SFF_SELECTION) != 0) break; m.Result = IntPtr.Zero; return; - // Allow the following - // + // Allow the following + // case Interop.WindowMessages.WM_COPY: case Interop.WindowMessages.WM_SETTEXT: case Interop.EditMessages.EM_EXLIMITTEXT: m.Result = IntPtr.Zero; return; - // Beep and disallow change for all other messages - // + // Beep and disallow change for all other messages + // default: SafeNativeMethods.MessageBeep(0); break; @@ -3196,17 +3623,20 @@ internal void WmReflectNotify(ref Message m) { break; } } - else { + else + { base.WndProc(ref m); } } - private unsafe NativeMethods.ENPROTECTED ConvertFromENPROTECTED64(NativeMethods.ENPROTECTED64 es64) { + private unsafe NativeMethods.ENPROTECTED ConvertFromENPROTECTED64(NativeMethods.ENPROTECTED64 es64) + { NativeMethods.ENPROTECTED es = new NativeMethods.ENPROTECTED(); - fixed (byte* es64p = &es64.contents[0]) { + fixed (byte* es64p = &es64.contents[0]) + { es.nmhdr = new NativeMethods.NMHDR(); - es.chrg = new NativeMethods.CHARRANGE(); + es.chrg = new NativeMethods.CHARRANGE(); es.nmhdr.hwndFrom = Marshal.ReadIntPtr((IntPtr)es64p); es.nmhdr.idFrom = Marshal.ReadIntPtr((IntPtr)(es64p + 8)); @@ -3217,16 +3647,18 @@ private unsafe NativeMethods.ENPROTECTED ConvertFromENPROTECTED64(NativeMethods. es.chrg.cpMin = Marshal.ReadInt32((IntPtr)(es64p + 44)); es.chrg.cpMax = Marshal.ReadInt32((IntPtr)(es64p + 48)); } - + return es; } - private static unsafe NativeMethods.ENLINK ConvertFromENLINK64(NativeMethods.ENLINK64 es64) { + private static unsafe NativeMethods.ENLINK ConvertFromENLINK64(NativeMethods.ENLINK64 es64) + { NativeMethods.ENLINK es = new NativeMethods.ENLINK(); - fixed (byte* es64p = &es64.contents[0]) { + fixed (byte* es64p = &es64.contents[0]) + { es.nmhdr = new NativeMethods.NMHDR(); - es.charrange = new NativeMethods.CHARRANGE(); + es.charrange = new NativeMethods.CHARRANGE(); es.nmhdr.hwndFrom = Marshal.ReadIntPtr((IntPtr)es64p); es.nmhdr.idFrom = Marshal.ReadIntPtr((IntPtr)(es64p + 8)); @@ -3237,13 +3669,14 @@ private static unsafe NativeMethods.ENLINK ConvertFromENLINK64(NativeMethods.ENL es.charrange.cpMin = Marshal.ReadInt32((IntPtr)(es64p + 44)); es.charrange.cpMax = Marshal.ReadInt32((IntPtr)(es64p + 48)); } - + return es; } /// /// - private void WmSelectionChange(NativeMethods.SELCHANGE selChange) { + private void WmSelectionChange(NativeMethods.SELCHANGE selChange) + { int selStart = selChange.chrg.cpMin; int selEnd = selChange.chrg.cpMax; short selType = (short)selChange.seltyp; @@ -3263,14 +3696,17 @@ private void WmSelectionChange(NativeMethods.SELCHANGE selChange) { // remove the last completed character typed. // Is either the Hangul or HangulFull IME currently in use? - if( ImeMode == ImeMode.Hangul || ImeMode == ImeMode.HangulFull ) { + if (ImeMode == ImeMode.Hangul || ImeMode == ImeMode.HangulFull) + { // Is the IME CompositionWindow open? - int compMode = unchecked( (int) (long)SendMessage(Interop.EditMessages.EM_GETIMECOMPMODE, 0, 0)); - if (RichTextBoxConstants.ICM_NOTOPEN != compMode) { + int compMode = unchecked((int)(long)SendMessage(Interop.EditMessages.EM_GETIMECOMPMODE, 0, 0)); + if (RichTextBoxConstants.ICM_NOTOPEN != compMode) + { int textLength = Interop.User32.GetWindowTextLengthW(new HandleRef(this, Handle)); - if (selStart == selEnd && textLength == MaxLength) { + if (selStart == selEnd && textLength == MaxLength) + { SendMessage(Interop.WindowMessages.WM_KILLFOCUS, 0, 0); SendMessage(Interop.WindowMessages.WM_SETFOCUS, 0, 0); @@ -3279,27 +3715,31 @@ private void WmSelectionChange(NativeMethods.SELCHANGE selChange) { } } - if (selStart != curSelStart || selEnd != curSelEnd || selType != curSelType) { + if (selStart != curSelStart || selEnd != curSelEnd || selType != curSelType) + { curSelStart = selStart; - curSelEnd = selEnd; - curSelType = selType; + curSelEnd = selEnd; + curSelType = selType; OnSelectionChanged(EventArgs.Empty); } } /// /// - private void WmSetFont(ref Message m) { + private void WmSetFont(ref Message m) + { // This function would normally cause two TextChanged events to be fired, one // from the base.WndProc, and another from InternalSetForeColor. // To prevent this, we suppress the first event fire. // - try { + try + { SuppressTextChangedEvent = true; base.WndProc(ref m); } - finally { + finally + { SuppressTextChangedEvent = false; } @@ -3309,8 +3749,10 @@ private void WmSetFont(ref Message m) { // // // - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_NOTIFY: WmReflectNotify(ref m); break; @@ -3331,11 +3773,13 @@ protected override void WndProc(ref Message m) { // Similarly, LinkCursor = false; DefWndProc(ref m); - if (LinkCursor && !Cursor.Equals(Cursors.WaitCursor)) { + if (LinkCursor && !Cursor.Equals(Cursors.WaitCursor)) + { UnsafeNativeMethods.SetCursor(new HandleRef(Cursors.Hand, Cursors.Hand.Handle)); m.Result = (IntPtr)1; } - else { + else + { base.WndProc(ref m); } break; @@ -3343,7 +3787,7 @@ protected override void WndProc(ref Message m) { case Interop.WindowMessages.WM_SETFONT: WmSetFont(ref m); break; - + case Interop.WindowMessages.WM_IME_NOTIFY: OnImeChange(EventArgs.Empty); base.WndProc(ref m); @@ -3351,7 +3795,7 @@ protected override void WndProc(ref Message m) { case Interop.WindowMessages.WM_GETDLGCODE: base.WndProc(ref m); - m.Result = (IntPtr)((AcceptsTab) ? unchecked( (int) (long)m.Result) | NativeMethods.DLGC_WANTTAB : unchecked( (int) (long)m.Result) & ~NativeMethods.DLGC_WANTTAB); + m.Result = (IntPtr)((AcceptsTab) ? unchecked((int)(long)m.Result) | NativeMethods.DLGC_WANTTAB : unchecked((int)(long)m.Result) & ~NativeMethods.DLGC_WANTTAB); break; case Interop.WindowMessages.WM_GETOBJECT: @@ -3361,8 +3805,9 @@ protected override void WndProc(ref Message m) { // classes. Usually this doesn't matter, because system controls always identify their window class explicitly through // the WM_GETOBJECT+OBJID_QUERYCLASSNAMEIDX message. But RICHEDIT20 doesn't do that - so we must do it ourselves. // Otherwise OLEACC will treat rich edit controls as custom controls, so the accessible Role and Value will be wrong. - if (unchecked((int)(long)m.LParam) == NativeMethods.OBJID_QUERYCLASSNAMEIDX) { - m.Result = (IntPtr)(65536+30); + if (unchecked((int)(long)m.LParam) == NativeMethods.OBJID_QUERYCLASSNAMEIDX) + { + m.Result = (IntPtr)(65536 + 30); } break; @@ -3383,11 +3828,12 @@ protected override void WndProc(ref Message m) { if (loWord == NativeMethods.SB_THUMBTRACK) { OnVScroll(EventArgs.Empty); - } else + } + else if (loWord == NativeMethods.SB_THUMBPOSITION) - { - OnVScroll(EventArgs.Empty); - } + { + OnVScroll(EventArgs.Empty); + } break; case Interop.WindowMessages.WM_HSCROLL: @@ -3410,20 +3856,24 @@ protected override void WndProc(ref Message m) { } // I used the visual basic 6 RichText (REOleCB.CPP) as a guide for this - private class OleCallback : UnsafeNativeMethods.IRichEditOleCallback { + private class OleCallback : UnsafeNativeMethods.IRichEditOleCallback + { private RichTextBox owner; IDataObject lastDataObject; DragDropEffects lastEffect; - internal OleCallback(RichTextBox owner) { + internal OleCallback(RichTextBox owner) + { this.owner = owner; } - public int GetNewStorage(out UnsafeNativeMethods.IStorage storage) { + public int GetNewStorage(out UnsafeNativeMethods.IStorage storage) + { Debug.WriteLineIf(RichTextDbg.TraceVerbose, "IRichEditOleCallback::GetNewStorage"); - if (!this.owner.AllowOleObjects) { + if (!this.owner.AllowOleObjects) + { storage = null; return NativeMethods.E_FAIL; } @@ -3442,12 +3892,14 @@ public int GetNewStorage(out UnsafeNativeMethods.IStorage storage) { public int GetInPlaceContext(IntPtr lplpFrame, IntPtr lplpDoc, - IntPtr lpFrameInfo) { + IntPtr lpFrameInfo) + { Debug.WriteLineIf(RichTextDbg.TraceVerbose, "IRichEditOleCallback::GetInPlaceContext"); return NativeMethods.E_NOTIMPL; } - public int ShowContainerUI(int fShow) { + public int ShowContainerUI(int fShow) + { Debug.WriteLineIf(RichTextDbg.TraceVerbose, "IRichEditOleCallback::ShowContainerUI"); // Do nothing return NativeMethods.S_OK; @@ -3460,7 +3912,8 @@ public int QueryInsertObject(ref Guid lpclsid, IntPtr lpstg, int cp) return NativeMethods.S_OK; } - public int DeleteObject(IntPtr lpoleobj) { + public int DeleteObject(IntPtr lpoleobj) + { Debug.WriteLineIf(RichTextDbg.TraceVerbose, "IRichEditOleCallback::DeleteObject"); // Do nothing return NativeMethods.S_OK; @@ -3468,56 +3921,66 @@ public int DeleteObject(IntPtr lpoleobj) { public int QueryAcceptData(IComDataObject lpdataobj, /* CLIPFORMAT* */ IntPtr lpcfFormat, int reco, - int fReally, IntPtr hMetaPict) { - + int fReally, IntPtr hMetaPict) + { + Debug.WriteLineIf(RichTextDbg.TraceVerbose, "IRichEditOleCallback::QueryAcceptData(reco=" + reco + ")"); - if (reco == NativeMethods.RECO_DROP) { - if (owner.AllowDrop || owner.EnableAutoDragDrop) { - + if (reco == NativeMethods.RECO_DROP) + { + if (owner.AllowDrop || owner.EnableAutoDragDrop) + { + MouseButtons b = Control.MouseButtons; Keys k = Control.ModifierKeys; - + int keyState = 0; // Due to the order in which we get called, we have to set up the keystate here. // First GetDragDropEffect is called with grfKeyState == 0, and then // QueryAcceptData is called. Since this is the time we want to fire // OnDragEnter, but we have yet to get the keystate, we set it up ourselves. - - if ((b & MouseButtons.Left) == MouseButtons.Left) { + + if ((b & MouseButtons.Left) == MouseButtons.Left) + { keyState |= NativeMethods.MK_LBUTTON; } - - if ((b & MouseButtons.Right) == MouseButtons.Right) { + + if ((b & MouseButtons.Right) == MouseButtons.Right) + { keyState |= NativeMethods.MK_RBUTTON; } - - if ((b & MouseButtons.Middle) == MouseButtons.Middle) { + + if ((b & MouseButtons.Middle) == MouseButtons.Middle) + { keyState |= NativeMethods.MK_MBUTTON; } - if ((k & Keys.Control) == Keys.Control) { + if ((k & Keys.Control) == Keys.Control) + { keyState |= NativeMethods.MK_CONTROL; } - if ((k & Keys.Shift) == Keys.Shift) { + if ((k & Keys.Shift) == Keys.Shift) + { keyState |= NativeMethods.MK_SHIFT; } - + lastDataObject = new DataObject(lpdataobj); - - if (!owner.EnableAutoDragDrop) { + + if (!owner.EnableAutoDragDrop) + { lastEffect = DragDropEffects.None; } - DragEventArgs e = new DragEventArgs(lastDataObject, - keyState, - Control.MousePosition.X, - Control.MousePosition.Y, - DragDropEffects.All, + DragEventArgs e = new DragEventArgs(lastDataObject, + keyState, + Control.MousePosition.X, + Control.MousePosition.Y, + DragDropEffects.All, lastEffect); - if (fReally == 0) { + if (fReally == 0) + { // we are just querying // We can get here without GetDragDropEffects actually being called first. @@ -3529,86 +3992,100 @@ public int QueryAcceptData(IComDataObject lpdataobj, e.Effect = ((keyState & NativeMethods.MK_CONTROL) == NativeMethods.MK_CONTROL) ? DragDropEffects.Copy : DragDropEffects.Move; owner.OnDragEnter(e); } - else { + else + { owner.OnDragDrop(e); lastDataObject = null; } - + lastEffect = e.Effect; - if (e.Effect == DragDropEffects.None) { + if (e.Effect == DragDropEffects.None) + { Debug.WriteLineIf(RichTextDbg.TraceVerbose, "\tCancel data"); return NativeMethods.E_FAIL; } - else { + else + { Debug.WriteLineIf(RichTextDbg.TraceVerbose, "\tAccept data"); return NativeMethods.S_OK; } } - else { + else + { Debug.WriteLineIf(RichTextDbg.TraceVerbose, "\tCancel data, allowdrop == false"); lastDataObject = null; return NativeMethods.E_FAIL; } } - else { + else + { return NativeMethods.E_NOTIMPL; } } - public int ContextSensitiveHelp(int fEnterMode) { + public int ContextSensitiveHelp(int fEnterMode) + { Debug.WriteLineIf(RichTextDbg.TraceVerbose, "IRichEditOleCallback::ContextSensitiveHelp"); return NativeMethods.E_NOTIMPL; } public int GetClipboardData(NativeMethods.CHARRANGE lpchrg, int reco, - IntPtr lplpdataobj) { + IntPtr lplpdataobj) + { Debug.WriteLineIf(RichTextDbg.TraceVerbose, "IRichEditOleCallback::GetClipboardData"); return NativeMethods.E_NOTIMPL; } - public int GetDragDropEffect(bool fDrag, int grfKeyState, ref int pdwEffect) { + public int GetDragDropEffect(bool fDrag, int grfKeyState, ref int pdwEffect) + { Debug.WriteLineIf(RichTextDbg.TraceVerbose, "IRichEditOleCallback::GetDragDropEffect"); - if (owner.AllowDrop || owner.EnableAutoDragDrop) { - - if (fDrag && grfKeyState == 0) { + if (owner.AllowDrop || owner.EnableAutoDragDrop) + { + + if (fDrag && grfKeyState == 0) + { // This is the very first call we receive in a Drag-Drop operation, // so we will let the control know what we support. // Note that we haven't gotten any data yet, so we will let QueryAcceptData // do the OnDragEnter. Note too, that grfKeyState does not yet reflect the // current keystate - if (owner.EnableAutoDragDrop) { - lastEffect = (DragDropEffects.All | DragDropEffects.None); + if (owner.EnableAutoDragDrop) + { + lastEffect = (DragDropEffects.All | DragDropEffects.None); } else lastEffect = DragDropEffects.None; - + } - else { + else + { // We are either dragging over or dropping - + // The below is the complete reverse of what the docs on MSDN suggest, // but if we follow the docs, we would be firing OnDragDrop all the // time instead of OnDragOver (see - + // drag - fDrag = false, grfKeyState != 0 // drop - fDrag = false, grfKeyState = 0 // We only care about the drag. // // When we drop, lastEffect will have the right state - if (!fDrag && lastDataObject != null && grfKeyState != 0) { + if (!fDrag && lastDataObject != null && grfKeyState != 0) + { - DragEventArgs e = new DragEventArgs(lastDataObject, - grfKeyState, - Control.MousePosition.X, - Control.MousePosition.Y, - DragDropEffects.All, + DragEventArgs e = new DragEventArgs(lastDataObject, + grfKeyState, + Control.MousePosition.X, + Control.MousePosition.Y, + DragDropEffects.All, lastEffect); // Now tell which of the allowable effects we want to use, but only if we are not already none - if (lastEffect != DragDropEffects.None) { + if (lastEffect != DragDropEffects.None) + { e.Effect = ((grfKeyState & NativeMethods.MK_CONTROL) == NativeMethods.MK_CONTROL) ? DragDropEffects.Copy : DragDropEffects.Move; } @@ -3618,20 +4095,23 @@ public int GetDragDropEffect(bool fDrag, int grfKeyState, ref int pdwEffect) { } pdwEffect = (int)lastEffect; - + } - else { + else + { pdwEffect = (int)DragDropEffects.None; } return NativeMethods.S_OK; } - public int GetContextMenu(short seltype, IntPtr lpoleobj, NativeMethods.CHARRANGE lpchrg, out IntPtr hmenu) { + public int GetContextMenu(short seltype, IntPtr lpoleobj, NativeMethods.CHARRANGE lpchrg, out IntPtr hmenu) + { Debug.WriteLineIf(RichTextDbg.TraceVerbose, "IRichEditOleCallback::GetContextMenu"); ContextMenu cm = owner.ContextMenu; if (cm == null || owner.ShortcutsEnabled == false) hmenu = IntPtr.Zero; - else { + else + { cm.sourceControl = owner; cm.OnPopup(EventArgs.Empty); // RichEd calls DestroyMenu after displaying the context menu @@ -3640,16 +4120,20 @@ public int GetContextMenu(short seltype, IntPtr lpoleobj, NativeMethods.CHARRANG // then we have to mark the context menu's handles empty because // RichTextBox will delete the menu handles once the popup menu is dismissed. Menu menu = cm; - while (true) { + while (true) + { int i = 0; int count = menu.ItemCount; - for (; i< count; i++) { - if (menu.items[i].handle != IntPtr.Zero) { + for (; i < count; i++) + { + if (menu.items[i].handle != IntPtr.Zero) + { menu = menu.items[i]; break; } } - if (i == count) { + if (i == count) + { menu.handle = IntPtr.Zero; menu.created = false; if (menu == cm) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBoxConstants.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBoxConstants.cs index db329663b3a..40aa16723a7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBoxConstants.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBoxConstants.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; @@ -12,7 +13,8 @@ namespace System.Windows.Forms { /// /// - internal static class RichTextBoxConstants { + internal static class RichTextBoxConstants + { // flags for enum that we don't want public // @@ -21,263 +23,263 @@ internal static class RichTextBoxConstants { internal const int RTB_FORCE = 0x0010; /* Richedit dll name */ - internal const string RICHEDIT_DLL10 = "RichEd32.DLL"; - internal const string RICHEDIT_DLL20 = "RichEd20.DLL"; - internal const string RICHEDIT_DLL30 = RICHEDIT_DLL20; - internal const string RICHEDIT_DLL41 = "MsftEdit.DLL"; + internal const string RICHEDIT_DLL10 = "RichEd32.DLL"; + internal const string RICHEDIT_DLL20 = "RichEd20.DLL"; + internal const string RICHEDIT_DLL30 = RICHEDIT_DLL20; + internal const string RICHEDIT_DLL41 = "MsftEdit.DLL"; /* Richedit1.0 Window Class */ - internal const string RICHEDIT_CLASS10A = "RICHEDIT"; + internal const string RICHEDIT_CLASS10A = "RICHEDIT"; /* Richedit2.0 Window Class. */ - internal const string RICHEDIT_CLASS20A = "RichEdit20A"; - internal const string RICHEDIT_CLASS20W = "RichEdit20W"; + internal const string RICHEDIT_CLASS20A = "RichEdit20A"; + internal const string RICHEDIT_CLASS20W = "RichEdit20W"; /* Richedit3.0 Window Class */ - internal const string RICHEDIT_CLASS30A = RICHEDIT_CLASS20A; - internal const string RICHEDIT_CLASS30W = RICHEDIT_CLASS20W; + internal const string RICHEDIT_CLASS30A = RICHEDIT_CLASS20A; + internal const string RICHEDIT_CLASS30W = RICHEDIT_CLASS20W; internal const string DLL_RICHEDIT = RICHEDIT_DLL30; internal const string WC_RICHEDITA = RICHEDIT_CLASS30A; internal const string WC_RICHEDITW = RICHEDIT_CLASS30W; /* Richedit4.1 Window Class */ - internal const string RICHEDIT_CLASS41A = "RICHEDIT50A"; - internal const string RICHEDIT_CLASS41W = "RICHEDIT50W"; + internal const string RICHEDIT_CLASS41A = "RICHEDIT50A"; + internal const string RICHEDIT_CLASS41W = "RICHEDIT50W"; - internal const string DLL_RICHEDIT_41 = RICHEDIT_DLL41; - internal const string WC_RICHEDITA_41 = RICHEDIT_CLASS41A; - internal const string WC_RICHEDITW_41 = RICHEDIT_CLASS41W; + internal const string DLL_RICHEDIT_41 = RICHEDIT_DLL41; + internal const string WC_RICHEDITA_41 = RICHEDIT_CLASS41A; + internal const string WC_RICHEDITW_41 = RICHEDIT_CLASS41W; /* RichTextBox messages */ // Extended edit style masks - internal const int SES_EMULATESYSEDIT = 1; - internal const int SES_BEEPONMAXTEXT = 2; - internal const int SES_EXTENDBACKCOLOR = 4; - internal const int SES_MAPCPS = 8; - internal const int SES_EMULATE10 = 16; - internal const int SES_USECRLF = 32; - internal const int SES_USEAIMM = 64; - internal const int SES_NOIME = 128; - internal const int SES_ALLOWBEEPS = 256; - internal const int SES_UPPERCASE = 512; - internal const int SES_LOWERCASE = 1024; - internal const int SES_NOINPUTSEQUENCECHK = 2048; - internal const int SES_BIDI = 4096; - internal const int SES_SCROLLONKILLFOCUS = 8192; - internal const int SES_XLTCRCRLFTOCR = 16384; + internal const int SES_EMULATESYSEDIT = 1; + internal const int SES_BEEPONMAXTEXT = 2; + internal const int SES_EXTENDBACKCOLOR = 4; + internal const int SES_MAPCPS = 8; + internal const int SES_EMULATE10 = 16; + internal const int SES_USECRLF = 32; + internal const int SES_USEAIMM = 64; + internal const int SES_NOIME = 128; + internal const int SES_ALLOWBEEPS = 256; + internal const int SES_UPPERCASE = 512; + internal const int SES_LOWERCASE = 1024; + internal const int SES_NOINPUTSEQUENCECHK = 2048; + internal const int SES_BIDI = 4096; + internal const int SES_SCROLLONKILLFOCUS = 8192; + internal const int SES_XLTCRCRLFTOCR = 16384; // Options for EM_SETLANGOPTIONS and EM_GETLANGOPTIONS - internal const int IMF_AUTOKEYBOARD = 0x0001; - internal const int IMF_AUTOFONT = 0x0002; - internal const int IMF_IMECANCELCOMPLETE = 0x0004; // high completes the comp string when aborting, low cancels. + internal const int IMF_AUTOKEYBOARD = 0x0001; + internal const int IMF_AUTOFONT = 0x0002; + internal const int IMF_IMECANCELCOMPLETE = 0x0004; // high completes the comp string when aborting, low cancels. internal const int IMF_IMEALWAYSSENDNOTIFY = 0x0008; - internal const int IMF_AUTOFONTSIZEADJUST = 0x0010; - internal const int IMF_UIFONTS = 0x0020; - internal const int IMF_DUALFONT = 0x0080; + internal const int IMF_AUTOFONTSIZEADJUST = 0x0010; + internal const int IMF_UIFONTS = 0x0020; + internal const int IMF_DUALFONT = 0x0080; // Values for EM_GETIMECOMPMODE - internal const int ICM_NOTOPEN = 0x0000; - internal const int ICM_LEVEL3 = 0x0001; - internal const int ICM_LEVEL2 = 0x0002; - internal const int ICM_LEVEL2_5 = 0x0003; - internal const int ICM_LEVEL2_SUI = 0x0004; + internal const int ICM_NOTOPEN = 0x0000; + internal const int ICM_LEVEL3 = 0x0001; + internal const int ICM_LEVEL2 = 0x0002; + internal const int ICM_LEVEL2_5 = 0x0003; + internal const int ICM_LEVEL2_SUI = 0x0004; // Outline mode wparam values - internal const int EMO_EXIT = 0; // enter normal mode, lparam ignored - internal const int EMO_ENTER = 1; // enter outline mode, lparam ignored + internal const int EMO_EXIT = 0; // enter normal mode, lparam ignored + internal const int EMO_ENTER = 1; // enter outline mode, lparam ignored internal const int EMO_PROMOTE = 2; // LOWORD(lparam) == 0 ==> // promote to body-text // LOWORD(lparam) != 0 ==> // promote/demote current selection // by indicated number of levels - internal const int EMO_EXPAND = 3; // HIWORD(lparam) = EMO_EXPANDSELECTION - // -> expands selection to level - // indicated in LOWORD(lparam) - // LOWORD(lparam) = -1/+1 corresponds - // to collapse/expand button presses - // in winword (other values are - // equivalent to having pressed these - // buttons more than once) - // HIWORD(lparam) = EMO_EXPANDDOCUMENT - // -> expands whole document to - // indicated level + internal const int EMO_EXPAND = 3; // HIWORD(lparam) = EMO_EXPANDSELECTION + // -> expands selection to level + // indicated in LOWORD(lparam) + // LOWORD(lparam) = -1/+1 corresponds + // to collapse/expand button presses + // in winword (other values are + // equivalent to having pressed these + // buttons more than once) + // HIWORD(lparam) = EMO_EXPANDDOCUMENT + // -> expands whole document to + // indicated level internal const int EMO_MOVESELECTION = 4; // LOWORD(lparam) != 0 -> move current // selection up/down by indicated // amount - internal const int EMO_GETVIEWMODE = 5; // Returns VM_NORMAL or VM_OUTLINE + internal const int EMO_GETVIEWMODE = 5; // Returns VM_NORMAL or VM_OUTLINE // EMO_EXPAND options - internal const int EMO_EXPANDSELECTION = 0; - internal const int EMO_EXPANDDOCUMENT = 1; - internal const int VM_NORMAL = 4; // Agrees with RTF \viewkindN - internal const int VM_OUTLINE = 2; + internal const int EMO_EXPANDSELECTION = 0; + internal const int EMO_EXPANDDOCUMENT = 1; + internal const int VM_NORMAL = 4; // Agrees with RTF \viewkindN + internal const int VM_OUTLINE = 2; // New notifications - internal const int EN_MSGFILTER = 0x0700; - internal const int EN_REQUESTRESIZE = 0x0701; - internal const int EN_SELCHANGE = 0x0702; - internal const int EN_DROPFILES = 0x0703; - internal const int EN_PROTECTED = 0x0704; - internal const int EN_CORRECTTEXT = 0x0705; /* PenWin specific */ - internal const int EN_STOPNOUNDO = 0x0706; - internal const int EN_IMECHANGE = 0x0707; /* Asia specific */ - internal const int EN_SAVECLIPBOARD = 0x0708; - internal const int EN_OLEOPFAILED = 0x0709; - internal const int EN_OBJECTPOSITIONS = 0x070a; - internal const int EN_LINK = 0x070b; - internal const int EN_DRAGDROPDONE = 0x070c; - internal const int EN_PARAGRAPHEXPANDED = 0x070d; + internal const int EN_MSGFILTER = 0x0700; + internal const int EN_REQUESTRESIZE = 0x0701; + internal const int EN_SELCHANGE = 0x0702; + internal const int EN_DROPFILES = 0x0703; + internal const int EN_PROTECTED = 0x0704; + internal const int EN_CORRECTTEXT = 0x0705; /* PenWin specific */ + internal const int EN_STOPNOUNDO = 0x0706; + internal const int EN_IMECHANGE = 0x0707; /* Asia specific */ + internal const int EN_SAVECLIPBOARD = 0x0708; + internal const int EN_OLEOPFAILED = 0x0709; + internal const int EN_OBJECTPOSITIONS = 0x070a; + internal const int EN_LINK = 0x070b; + internal const int EN_DRAGDROPDONE = 0x070c; + internal const int EN_PARAGRAPHEXPANDED = 0x070d; // BiDi specific notifications - internal const int EN_ALIGNLTR = 0x0710; - internal const int EN_ALIGNRTL = 0x0711; + internal const int EN_ALIGNLTR = 0x0710; + internal const int EN_ALIGNRTL = 0x0711; // Event notification masks */ - internal const int ENM_NONE = 0x00000000; - internal const int ENM_CHANGE = 0x00000001; - internal const int ENM_UPDATE = 0x00000002; - internal const int ENM_SCROLL = 0x00000004; - internal const int ENM_KEYEVENTS = 0x00010000; - internal const int ENM_MOUSEEVENTS = 0x00020000; - internal const int ENM_REQUESTRESIZE = 0x00040000; - internal const int ENM_SELCHANGE = 0x00080000; - internal const int ENM_DROPFILES = 0x00100000; - internal const int ENM_PROTECTED = 0x00200000; - internal const int ENM_CORRECTTEXT = 0x00400000; /* PenWin specific */ - internal const int ENM_SCROLLEVENTS = 0x00000008; - internal const int ENM_DRAGDROPDONE = 0x00000010; - internal const int ENM_PARAGRAPHEXPANDED = 0x00000020; + internal const int ENM_NONE = 0x00000000; + internal const int ENM_CHANGE = 0x00000001; + internal const int ENM_UPDATE = 0x00000002; + internal const int ENM_SCROLL = 0x00000004; + internal const int ENM_KEYEVENTS = 0x00010000; + internal const int ENM_MOUSEEVENTS = 0x00020000; + internal const int ENM_REQUESTRESIZE = 0x00040000; + internal const int ENM_SELCHANGE = 0x00080000; + internal const int ENM_DROPFILES = 0x00100000; + internal const int ENM_PROTECTED = 0x00200000; + internal const int ENM_CORRECTTEXT = 0x00400000; /* PenWin specific */ + internal const int ENM_SCROLLEVENTS = 0x00000008; + internal const int ENM_DRAGDROPDONE = 0x00000010; + internal const int ENM_PARAGRAPHEXPANDED = 0x00000020; /* Asia specific notification mask */ - internal const int ENM_IMECHANGE = 0x00800000; /* unused by RE2.0 */ - internal const int ENM_LANGCHANGE = 0x01000000; - internal const int ENM_OBJECTPOSITIONS = 0x02000000; - internal const int ENM_LINK = 0x04000000; + internal const int ENM_IMECHANGE = 0x00800000; /* unused by RE2.0 */ + internal const int ENM_LANGCHANGE = 0x01000000; + internal const int ENM_OBJECTPOSITIONS = 0x02000000; + internal const int ENM_LINK = 0x04000000; /* New edit control styles */ - internal const int ES_SAVESEL = 0x00008000; - internal const int ES_SUNKEN = 0x00004000; - internal const int ES_DISABLENOSCROLL = 0x00002000; + internal const int ES_SAVESEL = 0x00008000; + internal const int ES_SUNKEN = 0x00004000; + internal const int ES_DISABLENOSCROLL = 0x00002000; /* same as WS_MAXIMIZE, but that doesn't make sense so we re-use the value */ - internal const int ES_SELECTIONBAR = 0x01000000; + internal const int ES_SELECTIONBAR = 0x01000000; /* same as ES_UPPERCASE, but re-used to completely disable OLE drag'n'drop */ - internal const int ES_NOOLEDRAGDROP = 0x00000008; + internal const int ES_NOOLEDRAGDROP = 0x00000008; /* New edit control extended style */ - internal const int ES_EX_NOCALLOLEINIT = 0x01000000; + internal const int ES_EX_NOCALLOLEINIT = 0x01000000; /* These flags are used in FE Windows */ - internal const int ES_VERTICAL = 0x00400000; // NOT IN RE3.0/2.0 - internal const int ES_NOIME = 0x00080000; - internal const int ES_SELFIME = 0x00040000; + internal const int ES_VERTICAL = 0x00400000; // NOT IN RE3.0/2.0 + internal const int ES_NOIME = 0x00080000; + internal const int ES_SELFIME = 0x00040000; /* TextBox control options */ - internal const int ECO_AUTOWORDSELECTION = 0x00000001; - internal const int ECO_AUTOVSCROLL = 0x00000040; - internal const int ECO_AUTOHSCROLL = 0x00000080; - internal const int ECO_NOHIDESEL = 0x00000100; - internal const int ECO_READONLY = 0x00000800; - internal const int ECO_WANTRETURN = 0x00001000; - internal const int ECO_SAVESEL = 0x00008000; - internal const int ECO_SELECTIONBAR = 0x01000000; // guessing this is selection margin - internal const int ECO_VERTICAL = 0x00400000; /* FE specific */ + internal const int ECO_AUTOWORDSELECTION = 0x00000001; + internal const int ECO_AUTOVSCROLL = 0x00000040; + internal const int ECO_AUTOHSCROLL = 0x00000080; + internal const int ECO_NOHIDESEL = 0x00000100; + internal const int ECO_READONLY = 0x00000800; + internal const int ECO_WANTRETURN = 0x00001000; + internal const int ECO_SAVESEL = 0x00008000; + internal const int ECO_SELECTIONBAR = 0x01000000; // guessing this is selection margin + internal const int ECO_VERTICAL = 0x00400000; /* FE specific */ /* ECO operations */ - internal const int ECOOP_SET = 0x0001; - internal const int ECOOP_OR = 0x0002; - internal const int ECOOP_AND = 0x0003; - internal const int ECOOP_XOR = 0x0004; + internal const int ECOOP_SET = 0x0001; + internal const int ECOOP_OR = 0x0002; + internal const int ECOOP_AND = 0x0003; + internal const int ECOOP_XOR = 0x0004; /* new word break function actions */ - internal const int WB_CLASSIFY = 3; - internal const int WB_MOVEWORDLEFT = 4; - internal const int WB_MOVEWORDRIGHT = 5; - internal const int WB_LEFTBREAK = 6; - internal const int WB_RIGHTBREAK = 7; + internal const int WB_CLASSIFY = 3; + internal const int WB_MOVEWORDLEFT = 4; + internal const int WB_MOVEWORDRIGHT = 5; + internal const int WB_LEFTBREAK = 6; + internal const int WB_RIGHTBREAK = 7; /* Asia specific flags */ - internal const int WB_MOVEWORDPREV = 4; - internal const int WB_MOVEWORDNEXT = 5; - internal const int WB_PREVBREAK = 6; - internal const int WB_NEXTBREAK = 7; - - internal const int PC_FOLLOWING = 1; - internal const int PC_LEADING = 2; - internal const int PC_OVERFLOW = 3; - internal const int PC_DELIMITER = 4; - - internal const int WBF_WORDWRAP = 0x010; - internal const int WBF_WORDBREAK = 0x020; - internal const int WBF_OVERFLOW = 0x040; - internal const int WBF_LEVEL1 = 0x080; - internal const int WBF_LEVEL2 = 0x100; - internal const int WBF_CUSTOM = 0x200; + internal const int WB_MOVEWORDPREV = 4; + internal const int WB_MOVEWORDNEXT = 5; + internal const int WB_PREVBREAK = 6; + internal const int WB_NEXTBREAK = 7; + + internal const int PC_FOLLOWING = 1; + internal const int PC_LEADING = 2; + internal const int PC_OVERFLOW = 3; + internal const int PC_DELIMITER = 4; + + internal const int WBF_WORDWRAP = 0x010; + internal const int WBF_WORDBREAK = 0x020; + internal const int WBF_OVERFLOW = 0x040; + internal const int WBF_LEVEL1 = 0x080; + internal const int WBF_LEVEL2 = 0x100; + internal const int WBF_CUSTOM = 0x200; /* for use with EM_GET/SETTEXTMODE */ - internal const int TM_PLAINTEXT = 1; - internal const int TM_RICHTEXT = 2; /* default behavior */ - internal const int TM_SINGLELEVELUNDO = 4; - internal const int TM_MULTILEVELUNDO = 8; /* default behavior */ - internal const int TM_SINGLECODEPAGE = 16; - internal const int TM_MULTICODEPAGE = 32; /* default behavior */ + internal const int TM_PLAINTEXT = 1; + internal const int TM_RICHTEXT = 2; /* default behavior */ + internal const int TM_SINGLELEVELUNDO = 4; + internal const int TM_MULTILEVELUNDO = 8; /* default behavior */ + internal const int TM_SINGLECODEPAGE = 16; + internal const int TM_MULTICODEPAGE = 32; /* default behavior */ /* Asia specific flags */ - internal const int IMF_FORCENONE = 0x0001; - internal const int IMF_FORCEENABLE = 0x0002; - internal const int IMF_FORCEDISABLE = 0x0004; - internal const int IMF_CLOSESTATUSWINDOW = 0x0008; - internal const int IMF_VERTICAL = 0x0020; - internal const int IMF_FORCEACTIVE = 0x0040; - internal const int IMF_FORCEINACTIVE = 0x0080; - internal const int IMF_FORCEREMEMBER = 0x0100; - internal const int IMF_MULTIPLEEDIT = 0x0400; + internal const int IMF_FORCENONE = 0x0001; + internal const int IMF_FORCEENABLE = 0x0002; + internal const int IMF_FORCEDISABLE = 0x0004; + internal const int IMF_CLOSESTATUSWINDOW = 0x0008; + internal const int IMF_VERTICAL = 0x0020; + internal const int IMF_FORCEACTIVE = 0x0040; + internal const int IMF_FORCEINACTIVE = 0x0080; + internal const int IMF_FORCEREMEMBER = 0x0100; + internal const int IMF_MULTIPLEEDIT = 0x0400; /* Word break flags (used with WB_CLASSIFY) */ - internal const int WBF_CLASS = 0x0F; - internal const int WBF_ISWHITE = 0x10; - internal const int WBF_BREAKLINE = 0x20; - internal const int WBF_BREAKAFTER = 0x40; + internal const int WBF_CLASS = 0x0F; + internal const int WBF_ISWHITE = 0x10; + internal const int WBF_BREAKLINE = 0x20; + internal const int WBF_BREAKAFTER = 0x40; - internal const int cchTextLimitDefault = 32767; + internal const int cchTextLimitDefault = 32767; /* CHARFORMAT masks */ - internal const int CFM_BOLD = 0x00000001; - internal const int CFM_ITALIC = 0x00000002; - internal const int CFM_UNDERLINE = 0x00000004; - internal const int CFM_STRIKEOUT = 0x00000008; - internal const int CFM_PROTECTED = 0x00000010; - internal const int CFM_LINK = 0x00000020; /* Exchange hyperlink extension */ - internal const int CFM_SIZE = unchecked((int)0x80000000); - internal const int CFM_COLOR = 0x40000000; - internal const int CFM_FACE = 0x20000000; - internal const int CFM_OFFSET = 0x10000000; - internal const int CFM_CHARSET = 0x08000000; + internal const int CFM_BOLD = 0x00000001; + internal const int CFM_ITALIC = 0x00000002; + internal const int CFM_UNDERLINE = 0x00000004; + internal const int CFM_STRIKEOUT = 0x00000008; + internal const int CFM_PROTECTED = 0x00000010; + internal const int CFM_LINK = 0x00000020; /* Exchange hyperlink extension */ + internal const int CFM_SIZE = unchecked((int)0x80000000); + internal const int CFM_COLOR = 0x40000000; + internal const int CFM_FACE = 0x20000000; + internal const int CFM_OFFSET = 0x10000000; + internal const int CFM_CHARSET = 0x08000000; /* CHARFORMAT effects */ - internal const int CFE_BOLD = 0x0001; - internal const int CFE_ITALIC = 0x0002; - internal const int CFE_UNDERLINE = 0x0004; - internal const int CFE_STRIKEOUT = 0x0008; - internal const int CFE_PROTECTED = 0x0010; - internal const int CFE_LINK = 0x0020; - internal const int CFE_AUTOCOLOR = 0x40000000; /* NOTE: this corresponds to */ - /* CFM_COLOR, which controls it */ - internal const int yHeightCharPtsMost = 1638; + internal const int CFE_BOLD = 0x0001; + internal const int CFE_ITALIC = 0x0002; + internal const int CFE_UNDERLINE = 0x0004; + internal const int CFE_STRIKEOUT = 0x0008; + internal const int CFE_PROTECTED = 0x0010; + internal const int CFE_LINK = 0x0020; + internal const int CFE_AUTOCOLOR = 0x40000000; /* NOTE: this corresponds to */ + /* CFM_COLOR, which controls it */ + internal const int yHeightCharPtsMost = 1638; /* EM_SETCHARFORMAT wparam masks */ - internal const int SCF_SELECTION = 0x0001; - internal const int SCF_WORD = 0x0002; - internal const int SCF_DEFAULT = 0x0000; // set the default charformat or paraformat - internal const int SCF_ALL = 0x0004; // not valid with SCF_SELECTION or SCF_WORD - internal const int SCF_USEUIRULES = 0x0008; // modifier for SCF_SELECTION; says that - // the format came from a toolbar, etc. and - // therefore UI formatting rules should be - // used instead of strictly formatting the - // selection. + internal const int SCF_SELECTION = 0x0001; + internal const int SCF_WORD = 0x0002; + internal const int SCF_DEFAULT = 0x0000; // set the default charformat or paraformat + internal const int SCF_ALL = 0x0004; // not valid with SCF_SELECTION or SCF_WORD + internal const int SCF_USEUIRULES = 0x0008; // modifier for SCF_SELECTION; says that + // the format came from a toolbar, etc. and + // therefore UI formatting rules should be + // used instead of strictly formatting the + // selection. /* stream formats */ internal const int SF_TEXT = 0x0001; @@ -289,45 +291,45 @@ internal static class RichTextBoxConstants { /* Flag telling stream operations to operate on the selection only */ /* EM_STREAMIN will replace the current selection */ /* EM_STREAMOUT will stream out the current selection */ - internal const int SFF_SELECTION = 0x8000; + internal const int SFF_SELECTION = 0x8000; /* Flag telling stream operations to operate on the common RTF keyword only */ /* EM_STREAMIN will accept the only common RTF keyword */ /* EM_STREAMOUT will stream out the only common RTF keyword */ - internal const int SFF_PLAINRTF = 0x4000; + internal const int SFF_PLAINRTF = 0x4000; /* all paragraph measurements are in twips */ - internal const int MAX_TAB_STOPS = 32; - internal const int lDefaultTab = 720; + internal const int MAX_TAB_STOPS = 32; + internal const int lDefaultTab = 720; /* PARAFORMAT mask values */ - internal const int PFM_STARTINDENT = 0x00000001; - internal const int PFM_RIGHTINDENT = 0x00000002; - internal const int PFM_OFFSET = 0x00000004; - internal const int PFM_ALIGNMENT = 0x00000008; - internal const int PFM_TABSTOPS = 0x00000010; - internal const int PFM_NUMBERING = 0x00000020; - internal const int PFM_OFFSETINDENT = unchecked((int)0x80000000); + internal const int PFM_STARTINDENT = 0x00000001; + internal const int PFM_RIGHTINDENT = 0x00000002; + internal const int PFM_OFFSET = 0x00000004; + internal const int PFM_ALIGNMENT = 0x00000008; + internal const int PFM_TABSTOPS = 0x00000010; + internal const int PFM_NUMBERING = 0x00000020; + internal const int PFM_OFFSETINDENT = unchecked((int)0x80000000); /* PARAFORMAT numbering options */ - internal const int PFN_BULLET = 0x0001; + internal const int PFN_BULLET = 0x0001; /* PARAFORMAT alignment options */ - internal const int PFA_LEFT = 0x0001; - internal const int PFA_RIGHT = 0x0002; - internal const int PFA_CENTER = 0x0003; + internal const int PFA_LEFT = 0x0001; + internal const int PFA_RIGHT = 0x0002; + internal const int PFA_CENTER = 0x0003; /* CHARFORMAT and PARAFORMAT "ALL" masks CFM_COLOR mirrors CFE_AUTOCOLOR, a little code to easily deal with autocolor */ - internal const int CFM_EFFECTS = (CFM_BOLD | CFM_ITALIC | + internal const int CFM_EFFECTS = (CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE | CFM_COLOR | CFM_STRIKEOUT | CFE_PROTECTED | CFM_LINK); - internal const int CFM_ALL = (CFM_EFFECTS | CFM_SIZE | + internal const int CFM_ALL = (CFM_EFFECTS | CFM_SIZE | CFM_FACE | CFM_OFFSET | CFM_CHARSET); - internal const int PFM_ALL = (PFM_STARTINDENT | PFM_RIGHTINDENT | + internal const int PFM_ALL = (PFM_STARTINDENT | PFM_RIGHTINDENT | PFM_OFFSET | PFM_ALIGNMENT | PFM_TABSTOPS | PFM_NUMBERING | PFM_OFFSETINDENT); @@ -335,33 +337,33 @@ code to easily deal with autocolor */ /* New masks and effects -- a parenthesized asterisk indicates that the data is stored by RichEdit2.0, but not displayed */ - internal const int CFM_SMALLCAPS = 0x0040; /* (*) */ - internal const int CFM_ALLCAPS = 0x0080; /* (*) */ - internal const int CFM_HIDDEN = 0x0100; /* (*) */ - internal const int CFM_OUTLINE = 0x0200; /* (*) */ - internal const int CFM_SHADOW = 0x0400; /* (*) */ - internal const int CFM_EMBOSS = 0x0800; /* (*) */ - internal const int CFM_IMPRINT = 0x1000; /* (*) */ - internal const int CFM_DISABLED = 0x2000; - internal const int CFM_REVISED = 0x4000; - - internal const int CFM_BACKCOLOR = 0x04000000; - internal const int CFM_LCID = 0x02000000; - internal const int CFM_UNDERLINETYPE = 0x00800000; /* (*) */ - internal const int CFM_WEIGHT = 0x00400000; - internal const int CFM_SPACING = 0x00200000; /* (*) */ - internal const int CFM_KERNING = 0x00100000; /* (*) */ - internal const int CFM_STYLE = 0x00080000; /* (*) */ - internal const int CFM_ANIMATION = 0x00040000; /* (*) */ - internal const int CFM_REVAUTHOR = 0x00008000; - - internal const int CFE_SUBSCRIPT = 0x00010000; /* Superscript and subscript are */ - internal const int CFE_SUPERSCRIPT = 0x00020000; /* mutually exclusive */ - - internal const int CFM_SUBSCRIPT = (CFE_SUBSCRIPT | CFE_SUPERSCRIPT); - internal const int CFM_SUPERSCRIPT = CFM_SUBSCRIPT; - - internal const int CFM_EFFECTS2 = (CFM_EFFECTS | CFM_DISABLED | + internal const int CFM_SMALLCAPS = 0x0040; /* (*) */ + internal const int CFM_ALLCAPS = 0x0080; /* (*) */ + internal const int CFM_HIDDEN = 0x0100; /* (*) */ + internal const int CFM_OUTLINE = 0x0200; /* (*) */ + internal const int CFM_SHADOW = 0x0400; /* (*) */ + internal const int CFM_EMBOSS = 0x0800; /* (*) */ + internal const int CFM_IMPRINT = 0x1000; /* (*) */ + internal const int CFM_DISABLED = 0x2000; + internal const int CFM_REVISED = 0x4000; + + internal const int CFM_BACKCOLOR = 0x04000000; + internal const int CFM_LCID = 0x02000000; + internal const int CFM_UNDERLINETYPE = 0x00800000; /* (*) */ + internal const int CFM_WEIGHT = 0x00400000; + internal const int CFM_SPACING = 0x00200000; /* (*) */ + internal const int CFM_KERNING = 0x00100000; /* (*) */ + internal const int CFM_STYLE = 0x00080000; /* (*) */ + internal const int CFM_ANIMATION = 0x00040000; /* (*) */ + internal const int CFM_REVAUTHOR = 0x00008000; + + internal const int CFE_SUBSCRIPT = 0x00010000; /* Superscript and subscript are */ + internal const int CFE_SUPERSCRIPT = 0x00020000; /* mutually exclusive */ + + internal const int CFM_SUBSCRIPT = (CFE_SUBSCRIPT | CFE_SUPERSCRIPT); + internal const int CFM_SUPERSCRIPT = CFM_SUBSCRIPT; + + internal const int CFM_EFFECTS2 = (CFM_EFFECTS | CFM_DISABLED | CFM_SMALLCAPS | CFM_ALLCAPS | CFM_HIDDEN | CFM_OUTLINE | CFM_SHADOW | CFM_EMBOSS | @@ -369,85 +371,85 @@ code to easily deal with autocolor */ CFM_REVISED | CFM_SUBSCRIPT | CFM_SUPERSCRIPT | CFM_BACKCOLOR); - internal const int CFM_ALL2 = (CFM_ALL | CFM_EFFECTS2 | + internal const int CFM_ALL2 = (CFM_ALL | CFM_EFFECTS2 | CFM_BACKCOLOR | CFM_LCID | CFM_UNDERLINETYPE | CFM_WEIGHT | CFM_REVAUTHOR | CFM_SPACING | CFM_KERNING | CFM_STYLE | CFM_ANIMATION); - internal const int CFE_SMALLCAPS = CFM_SMALLCAPS; - internal const int CFE_ALLCAPS = CFM_ALLCAPS; - internal const int CFE_HIDDEN = CFM_HIDDEN; - internal const int CFE_OUTLINE = CFM_OUTLINE; - internal const int CFE_SHADOW = CFM_SHADOW; - internal const int CFE_EMBOSS = CFM_EMBOSS; - internal const int CFE_IMPRINT = CFM_IMPRINT; - internal const int CFE_DISABLED = CFM_DISABLED; - internal const int CFE_REVISED = CFM_REVISED; + internal const int CFE_SMALLCAPS = CFM_SMALLCAPS; + internal const int CFE_ALLCAPS = CFM_ALLCAPS; + internal const int CFE_HIDDEN = CFM_HIDDEN; + internal const int CFE_OUTLINE = CFM_OUTLINE; + internal const int CFE_SHADOW = CFM_SHADOW; + internal const int CFE_EMBOSS = CFM_EMBOSS; + internal const int CFE_IMPRINT = CFM_IMPRINT; + internal const int CFE_DISABLED = CFM_DISABLED; + internal const int CFE_REVISED = CFM_REVISED; /* NOTE: CFE_AUTOCOLOR and CFE_AUTOBACKCOLOR correspond to CFM_COLOR and CFM_BACKCOLOR, respectively, which control them */ - internal const int CFE_AUTOBACKCOLOR = CFM_BACKCOLOR; + internal const int CFE_AUTOBACKCOLOR = CFM_BACKCOLOR; /* Underline types */ - internal const int CFU_CF1UNDERLINE = 0xFF; /* map charformat's bit underline to CF2.*/ - internal const int CFU_INVERT = 0xFE; /* For IME composition fake a selection.*/ - internal const int CFU_UNDERLINEDOTTED = 0x4; /* (*) displayed as ordinary underline */ - internal const int CFU_UNDERLINEDOUBLE = 0x3; /* (*) displayed as ordinary underline */ - internal const int CFU_UNDERLINEWORD = 0x2; /* (*) displayed as ordinary underline */ - internal const int CFU_UNDERLINE = 0x1; - internal const int CFU_UNDERLINENONE = 0; + internal const int CFU_CF1UNDERLINE = 0xFF; /* map charformat's bit underline to CF2.*/ + internal const int CFU_INVERT = 0xFE; /* For IME composition fake a selection.*/ + internal const int CFU_UNDERLINEDOTTED = 0x4; /* (*) displayed as ordinary underline */ + internal const int CFU_UNDERLINEDOUBLE = 0x3; /* (*) displayed as ordinary underline */ + internal const int CFU_UNDERLINEWORD = 0x2; /* (*) displayed as ordinary underline */ + internal const int CFU_UNDERLINE = 0x1; + internal const int CFU_UNDERLINENONE = 0; /* PARAFORMAT 2.0 masks and effects */ - internal const int PFM_SPACEBEFORE = 0x00000040; - internal const int PFM_SPACEAFTER = 0x00000080; - internal const int PFM_LINESPACING = 0x00000100; - internal const int PFM_STYLE = 0x00000400; - internal const int PFM_BORDER = 0x00000800; /* (*) */ - internal const int PFM_SHADING = 0x00001000; /* (*) */ - internal const int PFM_NUMBERINGSTYLE = 0x00002000; /* (*) */ - internal const int PFM_NUMBERINGTAB = 0x00004000; /* (*) */ - internal const int PFM_NUMBERINGSTART = 0x00008000; /* (*) */ - - internal const int PFM_RTLPARA = 0x00010000; - internal const int PFM_KEEP = 0x00020000; /* (*) */ - internal const int PFM_KEEPNEXT = 0x00040000; /* (*) */ - internal const int PFM_PAGEBREAKBEFORE = 0x00080000; /* (*) */ - internal const int PFM_NOLINENUMBER = 0x00100000; /* (*) */ - internal const int PFM_NOWIDOWCONTROL = 0x00200000; /* (*) */ - internal const int PFM_DONOTHYPHEN = 0x00400000; /* (*) */ - internal const int PFM_SIDEBYSIDE = 0x00800000; /* (*) */ - - internal const int PFM_TABLE = unchecked((int)0xc0000000); /* (*) */ + internal const int PFM_SPACEBEFORE = 0x00000040; + internal const int PFM_SPACEAFTER = 0x00000080; + internal const int PFM_LINESPACING = 0x00000100; + internal const int PFM_STYLE = 0x00000400; + internal const int PFM_BORDER = 0x00000800; /* (*) */ + internal const int PFM_SHADING = 0x00001000; /* (*) */ + internal const int PFM_NUMBERINGSTYLE = 0x00002000; /* (*) */ + internal const int PFM_NUMBERINGTAB = 0x00004000; /* (*) */ + internal const int PFM_NUMBERINGSTART = 0x00008000; /* (*) */ + + internal const int PFM_RTLPARA = 0x00010000; + internal const int PFM_KEEP = 0x00020000; /* (*) */ + internal const int PFM_KEEPNEXT = 0x00040000; /* (*) */ + internal const int PFM_PAGEBREAKBEFORE = 0x00080000; /* (*) */ + internal const int PFM_NOLINENUMBER = 0x00100000; /* (*) */ + internal const int PFM_NOWIDOWCONTROL = 0x00200000; /* (*) */ + internal const int PFM_DONOTHYPHEN = 0x00400000; /* (*) */ + internal const int PFM_SIDEBYSIDE = 0x00800000; /* (*) */ + + internal const int PFM_TABLE = unchecked((int)0xc0000000); /* (*) */ /* Note: PARAFORMAT has no effects */ - internal const int PFM_EFFECTS = (PFM_RTLPARA | PFM_KEEP | + internal const int PFM_EFFECTS = (PFM_RTLPARA | PFM_KEEP | PFM_KEEPNEXT | PFM_TABLE | PFM_PAGEBREAKBEFORE | PFM_NOLINENUMBER | PFM_NOWIDOWCONTROL | PFM_DONOTHYPHEN | PFM_SIDEBYSIDE | PFM_TABLE); - internal const int PFM_ALL2 = (PFM_ALL | PFM_EFFECTS | + internal const int PFM_ALL2 = (PFM_ALL | PFM_EFFECTS | PFM_SPACEBEFORE | PFM_SPACEAFTER | PFM_LINESPACING | PFM_STYLE | PFM_SHADING | PFM_BORDER | PFM_NUMBERINGTAB | PFM_NUMBERINGSTART | PFM_NUMBERINGSTYLE); - internal const int PFE_RTLPARA = (PFM_RTLPARA >> 16); - internal const int PFE_KEEP = (PFM_KEEP >> 16); /* (*) */ - internal const int PFE_KEEPNEXT = (PFM_KEEPNEXT >> 16); /* (*) */ - internal const int PFE_PAGEBREAKBEFORE = (PFM_PAGEBREAKBEFORE >> 16); /* (*) */ - internal const int PFE_NOLINENUMBER = (PFM_NOLINENUMBER >> 16); /* (*) */ - internal const int PFE_NOWIDOWCONTROL = (PFM_NOWIDOWCONTROL >> 16); /* (*) */ - internal const int PFE_DONOTHYPHEN = (PFM_DONOTHYPHEN >> 16); /* (*) */ - internal const int PFE_SIDEBYSIDE = (PFM_SIDEBYSIDE >> 16); /* (*) */ + internal const int PFE_RTLPARA = (PFM_RTLPARA >> 16); + internal const int PFE_KEEP = (PFM_KEEP >> 16); /* (*) */ + internal const int PFE_KEEPNEXT = (PFM_KEEPNEXT >> 16); /* (*) */ + internal const int PFE_PAGEBREAKBEFORE = (PFM_PAGEBREAKBEFORE >> 16); /* (*) */ + internal const int PFE_NOLINENUMBER = (PFM_NOLINENUMBER >> 16); /* (*) */ + internal const int PFE_NOWIDOWCONTROL = (PFM_NOWIDOWCONTROL >> 16); /* (*) */ + internal const int PFE_DONOTHYPHEN = (PFM_DONOTHYPHEN >> 16); /* (*) */ + internal const int PFE_SIDEBYSIDE = (PFM_SIDEBYSIDE >> 16); /* (*) */ - internal const int PFE_TABLEROW = 0xc000; /* These 3 options are mutually */ - internal const int PFE_TABLECELLEND = 0x8000; /* exclusive and each imply */ - internal const int PFE_TABLECELL = 0x4000; /* that para is part of a table*/ + internal const int PFE_TABLEROW = 0xc000; /* These 3 options are mutually */ + internal const int PFE_TABLECELLEND = 0x8000; /* exclusive and each imply */ + internal const int PFE_TABLECELL = 0x4000; /* that para is part of a table*/ /* * PARAFORMAT numbering options (values for wNumbering): @@ -464,15 +466,15 @@ code to easily deal with autocolor */ * * Other valid Unicode chars are Unicodes for bullets. */ - internal const int PFA_JUSTIFY = 4; /* New paragraph-alignment option 2.0 (*) */ + internal const int PFA_JUSTIFY = 4; /* New paragraph-alignment option 2.0 (*) */ - internal const int SEL_EMPTY = 0x0000; - internal const int SEL_TEXT = 0x0001; - internal const int SEL_OBJECT = 0x0002; - internal const int SEL_MULTICHAR = 0x0004; - internal const int SEL_MULTIOBJECT = 0x0008; + internal const int SEL_EMPTY = 0x0000; + internal const int SEL_TEXT = 0x0001; + internal const int SEL_OBJECT = 0x0002; + internal const int SEL_MULTICHAR = 0x0004; + internal const int SEL_MULTIOBJECT = 0x0008; - internal const int tomTrue = -1, + internal const int tomTrue = -1, tomFalse = 0, tomNone = 0, tomUndefined = -9999999, @@ -483,44 +485,44 @@ code to easily deal with autocolor */ a right-mouse drag drop should be generated. The IOleObject parameter will really be the IDataObject for the drop */ - internal const int GCM_RIGHTMOUSEDROP = 0x8000; + internal const int GCM_RIGHTMOUSEDROP = 0x8000; - internal const int OLEOP_DOVERB = 1; + internal const int OLEOP_DOVERB = 1; /* clipboard formats - use as parameter to RegisterClipboardFormat() */ - internal const string CF_RTF = "Rich Text Format"; - internal const string CF_RTFNOOBJS = "Rich Text Format Without Objects"; - internal const string CF_RETEXTOBJ = "RichEdit Text and Objects"; + internal const string CF_RTF = "Rich Text Format"; + internal const string CF_RTFNOOBJS = "Rich Text Format Without Objects"; + internal const string CF_RETEXTOBJ = "RichEdit Text and Objects"; /* UndoName info */ - internal const int UID_UNKNOWN = 0; - internal const int UID_TYPING = 1; - internal const int UID_DELETE = 2; - internal const int UID_DRAGDROP = 3; - internal const int UID_CUT = 4; - internal const int UID_PASTE = 5; + internal const int UID_UNKNOWN = 0; + internal const int UID_TYPING = 1; + internal const int UID_DELETE = 2; + internal const int UID_DRAGDROP = 3; + internal const int UID_CUT = 4; + internal const int UID_PASTE = 5; /* flags for the GETEXTEX data structure */ - internal const int GT_DEFAULT = 0; - internal const int GT_USECRLF = 1; + internal const int GT_DEFAULT = 0; + internal const int GT_USECRLF = 1; /* flags for the GETTEXTLENGTHEX data structure */ - internal const int GTL_DEFAULT = 0; /* do the default (return # of chars) */ - internal const int GTL_USECRLF = 1; /* compute answer using CRLFs for paragraphs*/ - internal const int GTL_PRECISE = 2; /* compute a precise answer */ - internal const int GTL_CLOSE = 4; /* fast computation of a "close" answer */ - internal const int GTL_NUMCHARS = 8; /* return the number of characters */ - internal const int GTL_NUMBYTES = 16; /* return the number of _bytes_ */ + internal const int GTL_DEFAULT = 0; /* do the default (return # of chars) */ + internal const int GTL_USECRLF = 1; /* compute answer using CRLFs for paragraphs*/ + internal const int GTL_PRECISE = 2; /* compute a precise answer */ + internal const int GTL_CLOSE = 4; /* fast computation of a "close" answer */ + internal const int GTL_NUMCHARS = 8; /* return the number of characters */ + internal const int GTL_NUMBYTES = 16; /* return the number of _bytes_ */ /* UNICODE embedding character */ -// disable csharp compiler warning #0414: field assigned unused value + // disable csharp compiler warning #0414: field assigned unused value #pragma warning disable 0414 - internal static readonly char WCH_EMBEDDING = (char)0xFFFC; + internal static readonly char WCH_EMBEDDING = (char)0xFFFC; #pragma warning restore 0414 /* flags for the find text options */ - internal const int FR_DOWN = 0x00000001; - internal const int FR_WHOLEWORD = 0x00000002; - internal const int FR_MATCHCASE = 0x00000004; + internal const int FR_DOWN = 0x00000001; + internal const int FR_WHOLEWORD = 0x00000002; + internal const int FR_MATCHCASE = 0x00000004; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBoxFinds.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBoxFinds.cs index a7999c20e23..bbf76f23f72 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBoxFinds.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBoxFinds.cs @@ -29,7 +29,7 @@ public enum RichTextBoxFinds /// If the text is found, do not highlight it. /// NoHighlight = 0x00000008, - + /// /// Search from the end of the current selection to the beginning of the /// document. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBoxLanguageOptions.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBoxLanguageOptions.cs index 672322abb1e..2ca49966366 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBoxLanguageOptions.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBoxLanguageOptions.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms +namespace System.Windows.Forms { /// /// Rich edit control's option settings for Input Method Editor (IME) and @@ -10,7 +10,7 @@ namespace System.Windows.Forms /// [Flags] public enum RichTextBoxLanguageOptions - { + { /// /// If this flag is set, the control automatically changes fonts when the /// user explicitly changes to a different keyboard layout. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SaveFileDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SaveFileDialog.cs index f85af0800a3..fa66241a497 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SaveFileDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SaveFileDialog.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; @@ -26,7 +27,8 @@ namespace System.Windows.Forms { Designer("System.Windows.Forms.Design.SaveFileDialogDesigner, " + AssemblyRef.SystemDesign), SRDescription(nameof(SR.DescriptionSaveFileDialog)) ] - public sealed class SaveFileDialog : FileDialog { + public sealed class SaveFileDialog : FileDialog + { /// /// @@ -35,15 +37,18 @@ public sealed class SaveFileDialog : FileDialog { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(false), SRDescription(nameof(SR.SaveFileDialogCreatePrompt)) ] - public bool CreatePrompt { - get { + public bool CreatePrompt + { + get + { return GetOption(NativeMethods.OFN_CREATEPROMPT); } - set { + set + { SetOption(NativeMethods.OFN_CREATEPROMPT, value); } } @@ -55,15 +60,18 @@ public bool CreatePrompt { /// /// [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), DefaultValue(true), SRDescription(nameof(SR.SaveFileDialogOverWritePrompt)) ] - public bool OverwritePrompt { - get { + public bool OverwritePrompt + { + get + { return GetOption(NativeMethods.OFN_OVERWRITEPROMPT); } - set { + set + { SetOption(NativeMethods.OFN_OVERWRITEPROMPT, value); } } @@ -73,15 +81,16 @@ public bool OverwritePrompt { /// Opens the file with read/write permission selected by the user. /// /// - + [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] - public Stream OpenFile() { + public Stream OpenFile() + { string filename = FileNames[0]; if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException(nameof(FileName)); } - + return new FileStream(filename, FileMode.Create, FileAccess.ReadWrite); } @@ -94,7 +103,7 @@ public Stream OpenFile() { /// closing. /// /// - private bool PromptFileCreate(string fileName) + private bool PromptFileCreate(string fileName) { return MessageBoxWithFocusRestore(string.Format(SR.FileDialogCreatePrompt, fileName), DialogCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Warning); @@ -109,7 +118,8 @@ private bool PromptFileCreate(string fileName) /// /// /// - private bool PromptFileOverwrite(string fileName) { + private bool PromptFileOverwrite(string fileName) + { return MessageBoxWithFocusRestore(string.Format(SR.FileDialogOverwritePrompt, fileName), DialogCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Warning); } @@ -117,24 +127,30 @@ private bool PromptFileOverwrite(string fileName) { // If it's necessary to throw up a "This file exists, are you sure?" kind of // MessageBox, here's where we do it. // Return value is whether or not the user hit "okay". - private protected override bool PromptUserIfAppropriate(string fileName) { - if (!base.PromptUserIfAppropriate(fileName)) { + private protected override bool PromptUserIfAppropriate(string fileName) + { + if (!base.PromptUserIfAppropriate(fileName)) + { return false; } //Note: When we are using the Vista dialog mode we get two prompts (one from us and one from the OS) if we do this - if ((_options & NativeMethods.OFN_OVERWRITEPROMPT) != 0 && FileExists(fileName) && !this.UseVistaDialogInternal) { - if (!PromptFileOverwrite(fileName)) { + if ((_options & NativeMethods.OFN_OVERWRITEPROMPT) != 0 && FileExists(fileName) && !this.UseVistaDialogInternal) + { + if (!PromptFileOverwrite(fileName)) + { return false; } } - if ((_options & NativeMethods.OFN_CREATEPROMPT) != 0 && !FileExists(fileName)) { - if (!PromptFileCreate(fileName)) { + if ((_options & NativeMethods.OFN_CREATEPROMPT) != 0 && !FileExists(fileName)) + { + if (!PromptFileCreate(fileName)) + { return false; } } - + return true; } @@ -144,26 +160,30 @@ private protected override bool PromptUserIfAppropriate(string fileName) { /// values. /// /// - public override void Reset() { + public override void Reset() + { base.Reset(); SetOption(NativeMethods.OFN_OVERWRITEPROMPT, true); } /// /// - private protected override bool RunFileDialog(NativeMethods.OPENFILENAME_I ofn) { + private protected override bool RunFileDialog(NativeMethods.OPENFILENAME_I ofn) + { bool result = UnsafeNativeMethods.GetSaveFileName(ofn); - if (!result) { + if (!result) + { // Something may have gone wrong - check for error condition // int errorCode = SafeNativeMethods.CommDlgExtendedError(); - switch(errorCode) { + switch (errorCode) + { case NativeMethods.FNERR_INVALIDFILENAME: throw new InvalidOperationException(string.Format(SR.FileDialogInvalidFileName, FileName)); } } - + return result; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Screen.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Screen.cs index 30690ca3a1d..3a9b9e4af45 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Screen.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Screen.cs @@ -4,7 +4,8 @@ -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Threading; using System.Runtime.InteropServices; using System.Diagnostics; @@ -21,28 +22,29 @@ namespace System.Windows.Forms { /// multiple display devices on a single system. /// /// - public class Screen { + public class Screen + { readonly IntPtr hmonitor; /// /// Bounds of the screen /// - readonly Rectangle bounds; + readonly Rectangle bounds; /// /// Available working area on the screen. This excludes taskbars and other /// docked windows. /// - private Rectangle workingArea = Rectangle.Empty; + private Rectangle workingArea = Rectangle.Empty; /// /// Set to true if this screen is the primary monitor /// - readonly bool primary; + readonly bool primary; /// /// Device name associated with this monitor /// - readonly string deviceName; + readonly string deviceName; - readonly int bitDepth; + readonly int bitDepth; private static object syncLock = new object();//used to lock this class before sync'ing to SystemEvents @@ -56,29 +58,33 @@ public class Screen { // private const int PRIMARY_MONITOR = unchecked((int)0xBAADF00D); - private const int MONITOR_DEFAULTTONULL = 0x00000000; - private const int MONITOR_DEFAULTTOPRIMARY = 0x00000001; - private const int MONITOR_DEFAULTTONEAREST = 0x00000002; - private const int MONITORINFOF_PRIMARY = 0x00000001; + private const int MONITOR_DEFAULTTONULL = 0x00000000; + private const int MONITOR_DEFAULTTOPRIMARY = 0x00000001; + private const int MONITOR_DEFAULTTONEAREST = 0x00000002; + private const int MONITORINFOF_PRIMARY = 0x00000001; private static bool multiMonitorSupport = (UnsafeNativeMethods.GetSystemMetrics(NativeMethods.SM_CMONITORS) != 0); private static Screen[] screens; - internal Screen(IntPtr monitor) : this(monitor, IntPtr.Zero) { + internal Screen(IntPtr monitor) : this(monitor, IntPtr.Zero) + { } - internal Screen(IntPtr monitor, IntPtr hdc) { + internal Screen(IntPtr monitor, IntPtr hdc) + { IntPtr screenDC = hdc; - if (!multiMonitorSupport || monitor == (IntPtr)PRIMARY_MONITOR) { + if (!multiMonitorSupport || monitor == (IntPtr)PRIMARY_MONITOR) + { // Single monitor system // bounds = SystemInformation.VirtualScreen; primary = true; deviceName = "DISPLAY"; } - else { + else + { // Multiple monitor system var info = new NativeMethods.MONITORINFOEX(); SafeNativeMethods.GetMonitorInfo(new HandleRef(null, monitor), info); @@ -88,7 +94,8 @@ internal Screen(IntPtr monitor, IntPtr hdc) { deviceName = new string(info.szDevice); deviceName = deviceName.TrimEnd((char)0); - if (hdc == IntPtr.Zero) { + if (hdc == IntPtr.Zero) + { screenDC = UnsafeNativeMethods.CreateDC(deviceName); } } @@ -97,7 +104,8 @@ internal Screen(IntPtr monitor, IntPtr hdc) { this.bitDepth = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, screenDC), NativeMethods.BITSPIXEL); this.bitDepth *= UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, screenDC), NativeMethods.PLANES); - if (hdc != screenDC) { + if (hdc != screenDC) + { UnsafeNativeMethods.DeleteDC(new HandleRef(null, screenDC)); } } @@ -107,25 +115,32 @@ internal Screen(IntPtr monitor, IntPtr hdc) { /// Gets an array of all of the displays on the system. /// /// - public static Screen[] AllScreens { - get { - if (screens == null) { - if (multiMonitorSupport) { + public static Screen[] AllScreens + { + get + { + if (screens == null) + { + if (multiMonitorSupport) + { MonitorEnumCallback closure = new MonitorEnumCallback(); NativeMethods.MonitorEnumProc proc = new NativeMethods.MonitorEnumProc(closure.Callback); SafeNativeMethods.EnumDisplayMonitors(NativeMethods.NullHandleRef, null, proc, IntPtr.Zero); - if (closure.screens.Count > 0) { + if (closure.screens.Count > 0) + { Screen[] temp = new Screen[closure.screens.Count]; closure.screens.CopyTo(temp, 0); screens = temp; } - else { - screens = new Screen[] {new Screen((IntPtr)PRIMARY_MONITOR)}; + else + { + screens = new Screen[] { new Screen((IntPtr)PRIMARY_MONITOR) }; } } - else { - screens = new Screen[] {PrimaryScreen}; + else + { + screens = new Screen[] { PrimaryScreen }; } // Now that we have our screens, attach a display setting changed @@ -137,14 +152,16 @@ public static Screen[] AllScreens { return screens; } } - + /// /// /// Gets Bits per Pixel value. /// /// - public int BitsPerPixel { - get { + public int BitsPerPixel + { + get + { return bitDepth; } } @@ -154,8 +171,10 @@ public int BitsPerPixel { /// Gets the bounds of the display. /// /// - public Rectangle Bounds { - get { + public Rectangle Bounds + { + get + { return bounds; } } @@ -165,8 +184,10 @@ public Rectangle Bounds { /// Gets the device name associated with a display. /// /// - public string DeviceName { - get { + public string DeviceName + { + get + { return deviceName; } } @@ -177,8 +198,10 @@ public string DeviceName { /// the primary device. /// /// - public bool Primary { - get { + public bool Primary + { + get + { return primary; } } @@ -189,18 +212,24 @@ public bool Primary { /// primary display. /// /// - public static Screen PrimaryScreen { - get { - if (multiMonitorSupport) { + public static Screen PrimaryScreen + { + get + { + if (multiMonitorSupport) + { Screen[] screens = AllScreens; - for (int i=0; i /// - public Rectangle WorkingArea { - get { + public Rectangle WorkingArea + { + get + { //if the static Screen class has a different desktop change count //than this instance then update the count and recalculate our working area - if (currentDesktopChangedCount != Screen.DesktopChangedCount) { + if (currentDesktopChangedCount != Screen.DesktopChangedCount) + { Interlocked.Exchange(ref currentDesktopChangedCount, Screen.DesktopChangedCount); - if (!multiMonitorSupport ||hmonitor == (IntPtr)PRIMARY_MONITOR) { + if (!multiMonitorSupport || hmonitor == (IntPtr)PRIMARY_MONITOR) + { // Single monitor system // workingArea = SystemInformation.WorkingArea; } - else { + else + { // Multiple monitor System var info = new NativeMethods.MONITORINFOEX(); SafeNativeMethods.GetMonitorInfo(new HandleRef(null, hmonitor), info); workingArea = Rectangle.FromLTRB(info.rcWork.left, info.rcWork.top, info.rcWork.right, info.rcWork.bottom); } } - + return workingArea; } } @@ -241,14 +275,19 @@ public Rectangle WorkingArea { /// Screen instances call this property to determine /// if their WorkingArea cache needs to be invalidated. /// - private static int DesktopChangedCount { - get { - if (desktopChangedCount == -1) { + private static int DesktopChangedCount + { + get + { + if (desktopChangedCount == -1) + { - lock (syncLock) { + lock (syncLock) + { //now that we have a lock, verify (again) our changecount... - if (desktopChangedCount == -1) { + if (desktopChangedCount == -1) + { //sync the UserPreference.Desktop change event. We'll keep count //of desktop changes so that the WorkingArea property on Screen //instances know when to invalidate their cache. @@ -268,10 +307,13 @@ private static int DesktopChangedCount { /// this one. /// /// - public override bool Equals(object obj) { - if (obj is Screen) { + public override bool Equals(object obj) + { + if (obj is Screen) + { Screen comp = (Screen)obj; - if (hmonitor == comp.hmonitor) { + if (hmonitor == comp.hmonitor) + { return true; } } @@ -285,12 +327,15 @@ public override bool Equals(object obj) { /// /// /// - public static Screen FromPoint(Point point) { - if (multiMonitorSupport) { + public static Screen FromPoint(Point point) + { + if (multiMonitorSupport) + { NativeMethods.POINTSTRUCT pt = new NativeMethods.POINTSTRUCT(point.X, point.Y); return new Screen(SafeNativeMethods.MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST)); } - else { + else + { return new Screen((IntPtr)PRIMARY_MONITOR); } } @@ -303,12 +348,15 @@ public static Screen FromPoint(Point point) { /// /// /// - public static Screen FromRectangle(Rectangle rect) { - if (multiMonitorSupport) { + public static Screen FromRectangle(Rectangle rect) + { + if (multiMonitorSupport) + { NativeMethods.RECT rc = NativeMethods.RECT.FromXYWH(rect.X, rect.Y, rect.Width, rect.Height); return new Screen(SafeNativeMethods.MonitorFromRect(ref rc, MONITOR_DEFAULTTONEAREST)); } - else { + else + { return new Screen((IntPtr)PRIMARY_MONITOR, IntPtr.Zero); } } @@ -342,7 +390,8 @@ public static Screen FromHandle(IntPtr hwnd) /// /// /// - public static Rectangle GetWorkingArea(Point pt) { + public static Rectangle GetWorkingArea(Point pt) + { return Screen.FromPoint(pt).WorkingArea; } /// @@ -352,7 +401,8 @@ public static Rectangle GetWorkingArea(Point pt) { /// /// /// - public static Rectangle GetWorkingArea(Rectangle rect) { + public static Rectangle GetWorkingArea(Rectangle rect) + { return Screen.FromRectangle(rect).WorkingArea; } /// @@ -362,7 +412,8 @@ public static Rectangle GetWorkingArea(Rectangle rect) { /// /// /// - public static Rectangle GetWorkingArea(Control ctl) { + public static Rectangle GetWorkingArea(Control ctl) + { return Screen.FromControl(ctl).WorkingArea; } @@ -372,7 +423,8 @@ public static Rectangle GetWorkingArea(Control ctl) { /// point. /// /// - public static Rectangle GetBounds(Point pt) { + public static Rectangle GetBounds(Point pt) + { return Screen.FromPoint(pt).Bounds; } /// @@ -381,7 +433,8 @@ public static Rectangle GetBounds(Point pt) { /// specified rectangle. /// /// - public static Rectangle GetBounds(Rectangle rect) { + public static Rectangle GetBounds(Rectangle rect) + { return Screen.FromRectangle(rect).Bounds; } /// @@ -390,7 +443,8 @@ public static Rectangle GetBounds(Rectangle rect) { /// that contains the largest region of the specified control. /// /// - public static Rectangle GetBounds(Control ctl) { + public static Rectangle GetBounds(Control ctl) + { return Screen.FromControl(ctl).Bounds; } @@ -399,8 +453,9 @@ public static Rectangle GetBounds(Control ctl) { /// Computes and retrieves a hash code for an object. /// /// - public override int GetHashCode() { - return(int)hmonitor; + public override int GetHashCode() + { + return (int)hmonitor; } /// @@ -408,7 +463,8 @@ public override int GetHashCode() { /// changing. We cache screen information and at this point we must /// invalidate our cache. /// - private static void OnDisplaySettingsChanging(object sender, EventArgs e) { + private static void OnDisplaySettingsChanging(object sender, EventArgs e) + { // Now that we've responded to this event, we don't need it again until // someone re-queries. We will re-add the event at that time. @@ -425,9 +481,11 @@ private static void OnDisplaySettingsChanging(object sender, EventArgs e) { /// changed. Here, we increment a static counter that Screen instances /// can check against to invalidate their cache. /// - private static void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e) { + private static void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e) + { - if (e.Category == UserPreferenceCategory.Desktop) { + if (e.Category == UserPreferenceCategory.Desktop) + { Interlocked.Increment(ref desktopChangedCount); } } @@ -437,17 +495,20 @@ private static void OnUserPreferenceChanged(object sender, UserPreferenceChanged /// Retrieves a string representing this object. /// /// - public override string ToString() { + public override string ToString() + { return GetType().Name + "[Bounds=" + bounds.ToString() + " WorkingArea=" + WorkingArea.ToString() + " Primary=" + primary.ToString() + " DeviceName=" + deviceName; } /// /// - private class MonitorEnumCallback { + private class MonitorEnumCallback + { public ArrayList screens = new ArrayList(); - public virtual bool Callback(IntPtr monitor, IntPtr hdc, IntPtr lprcMonitor, IntPtr lparam) { + public virtual bool Callback(IntPtr monitor, IntPtr hdc, IntPtr lprcMonitor, IntPtr lparam) + { screens.Add(new Screen(monitor, hdc)); return true; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollBarRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollBarRenderer.cs index 35e1e22955d..04e86cf4d6a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollBarRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollBarRenderer.cs @@ -2,192 +2,212 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ -using System; -using System.Drawing; -using System.Windows.Forms.VisualStyles; -using System.Diagnostics.CodeAnalysis; -using Microsoft.Win32; + using System; + using System.Drawing; + using System.Windows.Forms.VisualStyles; + using System.Diagnostics.CodeAnalysis; + using Microsoft.Win32; /// /// /// This is a rendering class for the ScrollBar control. /// /// - public sealed class ScrollBarRenderer { + public sealed class ScrollBarRenderer + { + + //Make this per-thread, so that different threads can safely use these methods. + [ThreadStatic] + private static VisualStyleRenderer visualStyleRenderer = null; - //Make this per-thread, so that different threads can safely use these methods. - [ThreadStatic] - private static VisualStyleRenderer visualStyleRenderer = null; - //cannot instantiate - private ScrollBarRenderer() { - } - - /// - /// - /// Returns true if this class is supported for the current OS and user/application settings, - /// otherwise returns false. - /// - /// - public static bool IsSupported { - get { - return VisualStyleRenderer.IsSupported; // no downlevel support - } - } - - /// - /// - /// Renders a ScrollBar arrow button. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static void DrawArrowButton(Graphics g, Rectangle bounds, ScrollBarArrowButtonState state) { - InitializeRenderer(VisualStyleElement.ScrollBar.ArrowButton.LeftNormal, (int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Renders a horizontal ScrollBar thumb. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static void DrawHorizontalThumb(Graphics g, Rectangle bounds, ScrollBarState state) { - InitializeRenderer(VisualStyleElement.ScrollBar.ThumbButtonHorizontal.Normal, (int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Renders a vertical ScrollBar thumb. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static void DrawVerticalThumb(Graphics g, Rectangle bounds, ScrollBarState state) { - InitializeRenderer(VisualStyleElement.ScrollBar.ThumbButtonVertical.Normal, (int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Renders a horizontal ScrollBar thumb grip. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static void DrawHorizontalThumbGrip(Graphics g, Rectangle bounds, ScrollBarState state) { - InitializeRenderer(VisualStyleElement.ScrollBar.GripperHorizontal.Normal, (int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Renders a vertical ScrollBar thumb grip. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static void DrawVerticalThumbGrip(Graphics g, Rectangle bounds, ScrollBarState state) { - InitializeRenderer(VisualStyleElement.ScrollBar.GripperVertical.Normal, (int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Renders a horizontal ScrollBar thumb. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static void DrawRightHorizontalTrack(Graphics g, Rectangle bounds, ScrollBarState state) { - InitializeRenderer(VisualStyleElement.ScrollBar.RightTrackHorizontal.Normal, (int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Renders a horizontal ScrollBar thumb. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static void DrawLeftHorizontalTrack(Graphics g, Rectangle bounds, ScrollBarState state) { - InitializeRenderer(VisualStyleElement.ScrollBar.LeftTrackHorizontal.Normal, (int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Renders a vertical ScrollBar thumb in the center of the given bounds. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static void DrawUpperVerticalTrack(Graphics g, Rectangle bounds, ScrollBarState state) { - InitializeRenderer(VisualStyleElement.ScrollBar.UpperTrackVertical.Normal, (int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Renders a vertical ScrollBar thumb in the center of the given bounds. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static void DrawLowerVerticalTrack(Graphics g, Rectangle bounds, ScrollBarState state) { - InitializeRenderer(VisualStyleElement.ScrollBar.LowerTrackVertical.Normal, (int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Renders a ScrollBar size box in the center of the given bounds. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static void DrawSizeBox(Graphics g, Rectangle bounds, ScrollBarSizeBoxState state) { - InitializeRenderer(VisualStyleElement.ScrollBar.SizeBox.LeftAlign, (int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Returns the size of the ScrollBar thumb grip. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static Size GetThumbGripSize(Graphics g, ScrollBarState state) { - InitializeRenderer(VisualStyleElement.ScrollBar.GripperHorizontal.Normal, (int)state); - - return visualStyleRenderer.GetPartSize(g, ThemeSizeType.True); - } - - /// - /// - /// Returns the size of the ScrollBar size box. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static Size GetSizeBoxSize(Graphics g, ScrollBarState state) { - InitializeRenderer(VisualStyleElement.ScrollBar.SizeBox.LeftAlign, (int)state); - - return visualStyleRenderer.GetPartSize(g, ThemeSizeType.True); - } - - private static void InitializeRenderer(VisualStyleElement element, int state) { - if (visualStyleRenderer == null) { - visualStyleRenderer = new VisualStyleRenderer(element.ClassName, element.Part, state); - } - else { - visualStyleRenderer.SetParameters(element.ClassName, element.Part, state); - } - } + private ScrollBarRenderer() + { + } + + /// + /// + /// Returns true if this class is supported for the current OS and user/application settings, + /// otherwise returns false. + /// + /// + public static bool IsSupported + { + get + { + return VisualStyleRenderer.IsSupported; // no downlevel support + } + } + + /// + /// + /// Renders a ScrollBar arrow button. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static void DrawArrowButton(Graphics g, Rectangle bounds, ScrollBarArrowButtonState state) + { + InitializeRenderer(VisualStyleElement.ScrollBar.ArrowButton.LeftNormal, (int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Renders a horizontal ScrollBar thumb. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static void DrawHorizontalThumb(Graphics g, Rectangle bounds, ScrollBarState state) + { + InitializeRenderer(VisualStyleElement.ScrollBar.ThumbButtonHorizontal.Normal, (int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Renders a vertical ScrollBar thumb. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static void DrawVerticalThumb(Graphics g, Rectangle bounds, ScrollBarState state) + { + InitializeRenderer(VisualStyleElement.ScrollBar.ThumbButtonVertical.Normal, (int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Renders a horizontal ScrollBar thumb grip. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static void DrawHorizontalThumbGrip(Graphics g, Rectangle bounds, ScrollBarState state) + { + InitializeRenderer(VisualStyleElement.ScrollBar.GripperHorizontal.Normal, (int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Renders a vertical ScrollBar thumb grip. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static void DrawVerticalThumbGrip(Graphics g, Rectangle bounds, ScrollBarState state) + { + InitializeRenderer(VisualStyleElement.ScrollBar.GripperVertical.Normal, (int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Renders a horizontal ScrollBar thumb. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static void DrawRightHorizontalTrack(Graphics g, Rectangle bounds, ScrollBarState state) + { + InitializeRenderer(VisualStyleElement.ScrollBar.RightTrackHorizontal.Normal, (int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Renders a horizontal ScrollBar thumb. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static void DrawLeftHorizontalTrack(Graphics g, Rectangle bounds, ScrollBarState state) + { + InitializeRenderer(VisualStyleElement.ScrollBar.LeftTrackHorizontal.Normal, (int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Renders a vertical ScrollBar thumb in the center of the given bounds. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static void DrawUpperVerticalTrack(Graphics g, Rectangle bounds, ScrollBarState state) + { + InitializeRenderer(VisualStyleElement.ScrollBar.UpperTrackVertical.Normal, (int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Renders a vertical ScrollBar thumb in the center of the given bounds. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static void DrawLowerVerticalTrack(Graphics g, Rectangle bounds, ScrollBarState state) + { + InitializeRenderer(VisualStyleElement.ScrollBar.LowerTrackVertical.Normal, (int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Renders a ScrollBar size box in the center of the given bounds. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static void DrawSizeBox(Graphics g, Rectangle bounds, ScrollBarSizeBoxState state) + { + InitializeRenderer(VisualStyleElement.ScrollBar.SizeBox.LeftAlign, (int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Returns the size of the ScrollBar thumb grip. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static Size GetThumbGripSize(Graphics g, ScrollBarState state) + { + InitializeRenderer(VisualStyleElement.ScrollBar.GripperHorizontal.Normal, (int)state); + + return visualStyleRenderer.GetPartSize(g, ThemeSizeType.True); + } + + /// + /// + /// Returns the size of the ScrollBar size box. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static Size GetSizeBoxSize(Graphics g, ScrollBarState state) + { + InitializeRenderer(VisualStyleElement.ScrollBar.SizeBox.LeftAlign, (int)state); + + return visualStyleRenderer.GetPartSize(g, ThemeSizeType.True); + } + + private static void InitializeRenderer(VisualStyleElement element, int state) + { + if (visualStyleRenderer == null) + { + visualStyleRenderer = new VisualStyleRenderer(element.ClassName, element.Part, state); + } + else + { + visualStyleRenderer.SetParameters(element.ClassName, element.Part, state); + } + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollBars.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollBars.cs index 040ef684b3f..f80c8eeee46 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollBars.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollBars.cs @@ -23,13 +23,13 @@ public enum ScrollBars /// Only vertical scroll bars are shown. /// /// - Vertical = 2, + Vertical = 2, /// /// Both horizontal and vertical scroll bars are shown. /// /// - Both = 3, + Both = 3, } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollEventArgs.cs index fe36ea31197..892c67f4bcc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollEventArgs.cs @@ -42,7 +42,8 @@ public ScrollEventArgs(ScrollEventType type, int oldValue, int newValue) } - public ScrollEventArgs(ScrollEventType type, int oldValue, int newValue, ScrollOrientation scroll) { + public ScrollEventArgs(ScrollEventType type, int oldValue, int newValue, ScrollOrientation scroll) + { Type = type; NewValue = newValue; OldValue = oldValue; @@ -59,10 +60,10 @@ public ScrollEventArgs(ScrollEventType type, int oldValue, int newValue, Scroll /// public int NewValue { get; set; } - /// - /// Specifies the last position within the scroll bar. - /// - public int OldValue { get; } + /// + /// Specifies the last position within the scroll bar. + /// + public int OldValue { get; } /// /// Specifies the type of scroll event that occurred. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs index 86d3074ac48..a78b6b7fd4b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; @@ -17,7 +18,7 @@ namespace System.Windows.Forms { using System.ComponentModel.Design; using System.Drawing; using Microsoft.Win32; - + /// /// /// Defines a base class for controls that support auto-scrolling behavior. @@ -28,50 +29,51 @@ namespace System.Windows.Forms { ClassInterface(ClassInterfaceType.AutoDispatch), Designer("System.Windows.Forms.Design.ScrollableControlDesigner, " + AssemblyRef.SystemDesign) ] - public class ScrollableControl : Control, IArrangedElement { + public class ScrollableControl : Control, IArrangedElement + { #if DEBUG internal static readonly TraceSwitch AutoScrolling = new TraceSwitch("AutoScrolling", "Debug autoscrolling logic"); #else internal static readonly TraceSwitch AutoScrolling; #endif - protected const int ScrollStateAutoScrolling = 0x0001; + protected const int ScrollStateAutoScrolling = 0x0001; /// /// - protected const int ScrollStateHScrollVisible = 0x0002; + protected const int ScrollStateHScrollVisible = 0x0002; /// /// - protected const int ScrollStateVScrollVisible = 0x0004; + protected const int ScrollStateVScrollVisible = 0x0004; /// /// - protected const int ScrollStateUserHasScrolled = 0x0008; + protected const int ScrollStateUserHasScrolled = 0x0008; /// /// - protected const int ScrollStateFullDrag = 0x0010; + protected const int ScrollStateFullDrag = 0x0010; + - - private Size userAutoScrollMinSize = System.Drawing.Size.Empty; + private Size userAutoScrollMinSize = System.Drawing.Size.Empty; /// /// Current size of the displayRect. /// - private Rectangle displayRect = Rectangle.Empty; + private Rectangle displayRect = Rectangle.Empty; /// /// Current margins for autoscrolling. /// - private Size scrollMargin = System.Drawing.Size.Empty; + private Size scrollMargin = System.Drawing.Size.Empty; /// /// User requested margins for autoscrolling. /// - private Size requestedScrollMargin = System.Drawing.Size.Empty; + private Size requestedScrollMargin = System.Drawing.Size.Empty; /// /// User requested autoscroll position - used for form creation only. /// - internal Point scrollPosition = Point.Empty; + internal Point scrollPosition = Point.Empty; private DockPaddingEdges dockPadding = null; - private int scrollState; - + private int scrollState; + VScrollProperties verticalScroll = null; HScrollProperties horizontalScroll = null; private static readonly object EVENT_SCROLL = new object(); @@ -87,7 +89,8 @@ public class ScrollableControl : Control, IArrangedElement { /// /// public ScrollableControl() - : base() { + : base() + { SetStyle(ControlStyles.ContainerControl, true); SetStyle(ControlStyles.AllPaintingInWmPaint, false); SetScrollState(ScrollStateAutoScrolling, false); @@ -107,17 +110,21 @@ public ScrollableControl() DefaultValue(false), SRDescription(nameof(SR.FormAutoScrollDescr)) ] - public virtual bool AutoScroll { - get { + public virtual bool AutoScroll + { + get + { return GetScrollState(ScrollStateAutoScrolling); } - set { - if (value) { + set + { + if (value) + { UpdateFullDrag(); } - SetScrollState(ScrollStateAutoScrolling, value); + SetScrollState(ScrollStateAutoScrolling, value); LayoutTransaction.DoLayout(this, this, PropertyNames.AutoScroll); } } @@ -134,13 +141,17 @@ public virtual bool AutoScroll { Localizable(true), SRDescription(nameof(SR.FormAutoScrollMarginDescr)) ] - public Size AutoScrollMargin { - get { + public Size AutoScrollMargin + { + get + { return requestedScrollMargin; } - set { - if (value.Width < 0 || value.Height < 0) { + set + { + if (value.Width < 0 || value.Height < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(AutoScrollMargin), value)); } SetAutoScrollMargin(value.Width, value.Height); @@ -152,18 +163,22 @@ public Size AutoScrollMargin { /// [ SRCategory(nameof(SR.CatLayout)), - Browsable(false), + Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - SRDescription(nameof(SR.FormAutoScrollPositionDescr)) + SRDescription(nameof(SR.FormAutoScrollPositionDescr)) ] - public Point AutoScrollPosition { - get { + public Point AutoScrollPosition + { + get + { Rectangle rect = GetDisplayRectInternal(); return new Point(rect.X, rect.Y); } - set { - if (Created) { + set + { + if (Created) + { SetDisplayRectLocation(-value.X, -value.Y); SyncScrollbars(true); } @@ -180,13 +195,17 @@ public Point AutoScrollPosition { Localizable(true), SRDescription(nameof(SR.FormAutoScrollMinSizeDescr)) ] - public Size AutoScrollMinSize { - get { + public Size AutoScrollMinSize + { + get + { return userAutoScrollMinSize; } - set { - if (value != userAutoScrollMinSize) { + set + { + if (value != userAutoScrollMinSize) + { userAutoScrollMinSize = value; AutoScroll = true; PerformLayout(); @@ -200,20 +219,26 @@ public Size AutoScrollMinSize { /// If a subclass overrides this function, it must call the base implementation. /// /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; - if (HScroll || HorizontalScroll.Visible) { + if (HScroll || HorizontalScroll.Visible) + { cp.Style |= NativeMethods.WS_HSCROLL; } - else { + else + { cp.Style &= (~NativeMethods.WS_HSCROLL); } - if (VScroll || VerticalScroll.Visible) { + if (VScroll || VerticalScroll.Visible) + { cp.Style |= NativeMethods.WS_VSCROLL; } - else { + else + { cp.Style &= (~NativeMethods.WS_VSCROLL); } @@ -229,17 +254,22 @@ protected override CreateParams CreateParams { /// change during autoScroll. /// /// - public override Rectangle DisplayRectangle { + public override Rectangle DisplayRectangle + { [SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces")] - get { + get + { Rectangle rect = base.ClientRectangle; - if (!displayRect.IsEmpty) { + if (!displayRect.IsEmpty) + { rect.X = displayRect.X; rect.Y = displayRect.Y; - if (HScroll) { + if (HScroll) + { rect.Width = displayRect.Width; } - if (VScroll) { + if (VScroll) + { rect.Height = displayRect.Height; } } @@ -247,12 +277,15 @@ public override Rectangle DisplayRectangle { } } - Rectangle IArrangedElement.DisplayRectangle { - get { + Rectangle IArrangedElement.DisplayRectangle + { + get + { Rectangle displayRectangle = this.DisplayRectangle; // V7#79 : Controls anchored the bottom of their container may disappear (be scrunched) // when scrolling is used. - if(AutoScrollMinSize.Width != 0 && AutoScrollMinSize.Height != 0) { + if (AutoScrollMinSize.Width != 0 && AutoScrollMinSize.Height != 0) + { displayRectangle.Width = Math.Max(displayRectangle.Width, AutoScrollMinSize.Width); displayRectangle.Height = Math.Max(displayRectangle.Height, AutoScrollMinSize.Height); } @@ -266,11 +299,14 @@ Rectangle IArrangedElement.DisplayRectangle { /// sets a value indicating whether the horizontal scroll bar is visible. /// /// - protected bool HScroll { - get { + protected bool HScroll + { + get + { return GetScrollState(ScrollStateHScrollVisible); } - set { + set + { SetScrollState(ScrollStateHScrollVisible, value); } } @@ -283,17 +319,20 @@ protected bool HScroll { SRDescription(nameof(SR.ScrollableControlHorizontalScrollDescr)), Browsable(false), EditorBrowsable(EditorBrowsableState.Always) ] - public HScrollProperties HorizontalScroll { - get { - if (horizontalScroll == null) { + public HScrollProperties HorizontalScroll + { + get + { + if (horizontalScroll == null) + { horizontalScroll = new HScrollProperties(this); } - return horizontalScroll; + return horizontalScroll; } } - + /// @@ -302,11 +341,14 @@ public HScrollProperties HorizontalScroll { /// sets a value indicating whether the vertical scroll bar is visible. /// /// - protected bool VScroll { - get { + protected bool VScroll + { + get + { return GetScrollState(ScrollStateVScrollVisible); } - set { + set + { SetScrollState(ScrollStateVScrollVisible, value); } } @@ -320,12 +362,15 @@ protected bool VScroll { SRDescription(nameof(SR.ScrollableControlVerticalScrollDescr)), Browsable(false), EditorBrowsable(EditorBrowsableState.Always) ] - public VScrollProperties VerticalScroll { - get { - if (verticalScroll == null) { + public VScrollProperties VerticalScroll + { + get + { + if (verticalScroll == null) + { verticalScroll = new VScrollProperties(this); } - return verticalScroll; + return verticalScroll; } } @@ -338,9 +383,12 @@ public VScrollProperties VerticalScroll { Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public DockPaddingEdges DockPadding { - get { - if (dockPadding == null) { + public DockPaddingEdges DockPadding + { + get + { + if (dockPadding == null) + { dockPadding = new DockPaddingEdges(this); } return dockPadding; @@ -355,30 +403,36 @@ public DockPaddingEdges DockPadding { /// /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void AdjustFormScrollbars(bool displayScrollbars) { + protected virtual void AdjustFormScrollbars(bool displayScrollbars) + { bool needLayout = false; Rectangle display = GetDisplayRectInternal(); - if (!displayScrollbars && (HScroll || VScroll)) { + if (!displayScrollbars && (HScroll || VScroll)) + { needLayout = SetVisibleScrollbars(false, false); } - if (!displayScrollbars) { + if (!displayScrollbars) + { Rectangle client = ClientRectangle; display.Width = client.Width; display.Height = client.Height; } - else { + else + { needLayout |= ApplyScrollbarChanges(display); } - if (needLayout) { + if (needLayout) + { LayoutTransaction.DoLayout(this, this, PropertyNames.DisplayRectangle); } } - - private bool ApplyScrollbarChanges(Rectangle display) { + + private bool ApplyScrollbarChanges(Rectangle display) + { Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, GetType().Name + "::ApplyScrollbarChanges(" + display + ") {"); Debug.Indent(); @@ -388,36 +442,43 @@ private bool ApplyScrollbarChanges(Rectangle display) { Rectangle currentClient = ClientRectangle; Rectangle fullClient = currentClient; Rectangle minClient = fullClient; - if (HScroll) { + if (HScroll) + { fullClient.Height += SystemInformation.HorizontalScrollBarHeight; } - else { + else + { minClient.Height -= SystemInformation.HorizontalScrollBarHeight; } - - if (VScroll) { + + if (VScroll) + { fullClient.Width += SystemInformation.VerticalScrollBarWidth; } - else { + else + { minClient.Width -= SystemInformation.VerticalScrollBarWidth; } - + int maxX = minClient.Width; int maxY = minClient.Height; - if (Controls.Count != 0) { + if (Controls.Count != 0) + { // Compute the actual scroll margins (take into account docked // things.) // scrollMargin = requestedScrollMargin; - - if (dockPadding != null) { + + if (dockPadding != null) + { scrollMargin.Height += Padding.Bottom; scrollMargin.Width += Padding.Right; } - - for (int i=0; i maxX) { + if (layoutBounds.Width > maxX) + { needHscroll = true; maxX = layoutBounds.Width; } - if (layoutBounds.Height > maxY) { + if (layoutBounds.Height > maxY) + { needVscroll = true; maxY = layoutBounds.Height; - } + } } - else if (Controls.Count != 0) { - + else if (Controls.Count != 0) + { + // Compute the dimensions of the display rect // - for (int i=0; i < Controls.Count; i++) { + for (int i = 0; i < Controls.Count; i++) + { bool watchHoriz = true; bool watchVert = true; @@ -479,11 +548,14 @@ private bool ApplyScrollbarChanges(Rectangle display) { // Same logic as the margin calc - you need to see if the // control *will* be visible... // - if (current != null && current.GetState(STATE_VISIBLE)) { - if (defaultLayoutEngine) { + if (current != null && current.GetState(STATE_VISIBLE)) + { + if (defaultLayoutEngine) + { Control richCurrent = (Control)current; - switch (richCurrent.Dock) { + switch (richCurrent.Dock) + { case DockStyle.Top: watchHoriz = false; break; @@ -498,23 +570,28 @@ private bool ApplyScrollbarChanges(Rectangle display) { break; default: AnchorStyles anchor = richCurrent.Anchor; - if ((anchor & AnchorStyles.Right) == AnchorStyles.Right) { + if ((anchor & AnchorStyles.Right) == AnchorStyles.Right) + { watchHoriz = false; } - if ((anchor & AnchorStyles.Left) != AnchorStyles.Left) { + if ((anchor & AnchorStyles.Left) != AnchorStyles.Left) + { watchHoriz = false; } - if ((anchor & AnchorStyles.Bottom) == AnchorStyles.Bottom) { + if ((anchor & AnchorStyles.Bottom) == AnchorStyles.Bottom) + { watchVert = false; } - if ((anchor & AnchorStyles.Top) != AnchorStyles.Top) { + if ((anchor & AnchorStyles.Top) != AnchorStyles.Top) + { watchVert = false; } break; } } - if (watchHoriz || watchVert) { + if (watchHoriz || watchVert) + { Rectangle bounds = current.Bounds; int ctlRight = -display.X + bounds.X + bounds.Width + scrollMargin.Width; int ctlBottom = -display.Y + bounds.Y + bounds.Height + scrollMargin.Height; @@ -523,13 +600,15 @@ private bool ApplyScrollbarChanges(Rectangle display) { { ctlRight += current.Margin.Right; ctlBottom += current.Margin.Bottom; - } + } - if (ctlRight > maxX && watchHoriz) { + if (ctlRight > maxX && watchHoriz) + { needHscroll = true; maxX = ctlRight; } - if (ctlBottom > maxY && watchVert) { + if (ctlBottom > maxY && watchVert) + { needVscroll = true; maxY = ctlBottom; } @@ -543,29 +622,37 @@ private bool ApplyScrollbarChanges(Rectangle display) { // the clientRect with the "new" scrollbars. This will make the // scrollbars show and hide themselves correctly at the boundaries. // - if (maxX <= fullClient.Width) { + if (maxX <= fullClient.Width) + { needHscroll = false; } - if (maxY <= fullClient.Height) { + if (maxY <= fullClient.Height) + { needVscroll = false; } Rectangle clientToBe = fullClient; - if (needHscroll) { + if (needHscroll) + { clientToBe.Height -= SystemInformation.HorizontalScrollBarHeight; } - if (needVscroll) { + if (needVscroll) + { clientToBe.Width -= SystemInformation.VerticalScrollBarWidth; } - if (needHscroll && maxY > clientToBe.Height) { + if (needHscroll && maxY > clientToBe.Height) + { needVscroll = true; } - if (needVscroll && maxX > clientToBe.Width) { + if (needVscroll && maxX > clientToBe.Width) + { needHscroll = true; } - if (!needHscroll) { + if (!needHscroll) + { maxX = clientToBe.Width; } - if (!needVscroll) { + if (!needVscroll) + { maxY = clientToBe.Height; } @@ -578,13 +665,15 @@ private bool ApplyScrollbarChanges(Rectangle display) { // If needed, adjust the size... // - if (HScroll || VScroll) { + if (HScroll || VScroll) + { needLayout = (SetDisplayRectangleSize(maxX, maxY) || needLayout); } // Else just update the display rect size... this keeps it as big as the client // area in a resize scenario // - else { + else + { SetDisplayRectangleSize(maxX, maxY); } @@ -598,15 +687,19 @@ private bool ApplyScrollbarChanges(Rectangle display) { return needLayout; } - private Rectangle GetDisplayRectInternal() { - if (displayRect.IsEmpty) { + private Rectangle GetDisplayRectInternal() + { + if (displayRect.IsEmpty) + { displayRect = ClientRectangle; } - if (!AutoScroll && this.HorizontalScroll._visible == true) { - displayRect = new Rectangle(displayRect.X, displayRect.Y, this.HorizontalScroll.Maximum, this.displayRect.Height); + if (!AutoScroll && this.HorizontalScroll._visible == true) + { + displayRect = new Rectangle(displayRect.X, displayRect.Y, this.HorizontalScroll.Maximum, this.displayRect.Height); } - if (!AutoScroll && this.VerticalScroll._visible == true) { - displayRect = new Rectangle(displayRect.X, displayRect.Y, this.displayRect.Width, this.VerticalScroll.Maximum); + if (!AutoScroll && this.VerticalScroll._visible == true) + { + displayRect = new Rectangle(displayRect.X, displayRect.Y, this.displayRect.Width, this.VerticalScroll.Maximum); } return displayRect; } @@ -618,16 +711,18 @@ private Rectangle GetDisplayRectInternal() { /// /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected bool GetScrollState(int bit) { - return(bit & scrollState) == bit; + protected bool GetScrollState(int bit) + { + return (bit & scrollState) == bit; } - + /// /// Forces the layout of any docked or anchored child controls. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnLayout(LayoutEventArgs levent) { + protected override void OnLayout(LayoutEventArgs levent) + { // We get into a problem when you change the docking of a control // with autosizing on. Since the control (affectedControl) has @@ -642,26 +737,29 @@ protected override void OnLayout(LayoutEventArgs levent) { // affect a control's layout, we are forced to layout twice. There // isn't any noticible flicker, but this could be a perf problem... // - if (levent.AffectedControl != null && AutoScroll) { + if (levent.AffectedControl != null && AutoScroll) + { base.OnLayout(levent); } - + AdjustFormScrollbars(AutoScroll); base.OnLayout(levent); - + } /// /// Handles mouse wheel processing for our scrollbars. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnMouseWheel(MouseEventArgs e) { + protected override void OnMouseWheel(MouseEventArgs e) + { // Favor the vertical scroll bar, since it's the most // common use. However, if there isn't a vertical // scroll and the horizontal is on, then wheel it around. // - if (VScroll) { + if (VScroll) + { Rectangle client = ClientRectangle; int pos = -displayRect.Y; int maxPos = -(client.Height - displayRect.Height); @@ -676,7 +774,8 @@ protected override void OnMouseWheel(MouseEventArgs e) { ((HandledMouseEventArgs)e).Handled = true; } } - else if (HScroll) { + else if (HScroll) + { Rectangle client = ClientRectangle; int pos = -displayRect.X; int maxPos = -(client.Width - displayRect.Width); @@ -699,39 +798,48 @@ protected override void OnMouseWheel(MouseEventArgs e) { } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnRightToLeftChanged(EventArgs e) { + protected override void OnRightToLeftChanged(EventArgs e) + { base.OnRightToLeftChanged(e); resetRTLHScrollValue = true; // When the page becomes visible, we need to call OnLayout to adjust the scrollbars. LayoutTransaction.DoLayout(this, this, PropertyNames.RightToLeft); } - protected override void OnPaintBackground (PaintEventArgs e) { + protected override void OnPaintBackground(PaintEventArgs e) + { if ((HScroll || VScroll) && - BackgroundImage != null && - (BackgroundImageLayout == ImageLayout.Zoom || BackgroundImageLayout == ImageLayout.Stretch || BackgroundImageLayout == ImageLayout.Center)) { - if (ControlPaint.IsImageTransparent(BackgroundImage)) { - PaintTransparentBackground(e, displayRect); - } - ControlPaint.DrawBackgroundImage(e.Graphics, BackgroundImage, BackColor, BackgroundImageLayout, displayRect, displayRect, displayRect.Location); + BackgroundImage != null && + (BackgroundImageLayout == ImageLayout.Zoom || BackgroundImageLayout == ImageLayout.Stretch || BackgroundImageLayout == ImageLayout.Center)) + { + if (ControlPaint.IsImageTransparent(BackgroundImage)) + { + PaintTransparentBackground(e, displayRect); + } + ControlPaint.DrawBackgroundImage(e.Graphics, BackgroundImage, BackColor, BackgroundImageLayout, displayRect, displayRect, displayRect.Location); } - else { + else + { base.OnPaintBackground(e); } } - protected override void OnPaddingChanged(EventArgs e) { + protected override void OnPaddingChanged(EventArgs e) + { // DockPaddingEdges compat. // dont call base in this instance - for App compat we should not fire Invalidate when // the padding has changed. EventHandler handler = (EventHandler)Events[Control.EventPaddingChanged]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnVisibleChanged(EventArgs e) { - if (Visible) { + protected override void OnVisibleChanged(EventArgs e) + { + if (Visible) + { // When the page becomes visible, we need to call OnLayout to adjust the scrollbars. LayoutTransaction.DoLayout(this, this, PropertyNames.Visible); } @@ -740,14 +848,17 @@ protected override void OnVisibleChanged(EventArgs e) { // internal for Form to call // - internal void ScaleDockPadding(float dx, float dy) { - if (dockPadding != null) { + internal void ScaleDockPadding(float dx, float dy) + { + if (dockPadding != null) + { dockPadding.Scale(dx, dy); } } [EditorBrowsable(EditorBrowsableState.Never)] - protected override void ScaleCore(float dx, float dy) { + protected override void ScaleCore(float dx, float dy) + { ScaleDockPadding(dx, dy); base.ScaleCore(dx, dy); } @@ -755,7 +866,8 @@ protected override void ScaleCore(float dx, float dy) { /// /// Scale this form. Form overrides this to enforce a maximum / minimum size. /// - protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { + protected override void ScaleControl(SizeF factor, BoundsSpecified specified) + { ScaleDockPadding(factor.Width, factor.Height); base.ScaleControl(factor, specified); } @@ -765,11 +877,11 @@ protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { // internal void SetDisplayFromScrollProps(int x, int y) { - Rectangle display = GetDisplayRectInternal(); - ApplyScrollbarChanges(display); - SetDisplayRectLocation(x, y); + Rectangle display = GetDisplayRectInternal(); + ApplyScrollbarChanges(display); + SetDisplayRectLocation(x, y); } - + /// /// Adjusts the displayRect to be at the offset x, y. The contents of the /// Form is scrolled using Windows.ScrollWindowEx. @@ -777,7 +889,8 @@ internal void SetDisplayFromScrollProps(int x, int y) // // - protected void SetDisplayRectLocation(int x, int y) { + protected void SetDisplayRectLocation(int x, int y) + { int xDelta = 0; int yDelta = 0; @@ -791,51 +904,58 @@ protected void SetDisplayRectLocation(int x, int y) { int minX = Math.Min(client.Width - displayRectangle.Width, 0); int minY = Math.Min(client.Height - displayRectangle.Height, 0); - if (x > 0) { + if (x > 0) + { x = 0; } - if (y > 0) { + if (y > 0) + { y = 0; } - if (x < minX) { + if (x < minX) + { x = minX; } - if (y < minY) { + if (y < minY) + { y = minY; } - if (displayRectangle.X != x) - { - xDelta = x - displayRectangle.X; + if (displayRectangle.X != x) + { + xDelta = x - displayRectangle.X; } - if (displayRectangle.Y != y) - { - yDelta = y - displayRectangle.Y; + if (displayRectangle.Y != y) + { + yDelta = y - displayRectangle.Y; } - displayRect.X = x; - displayRect.Y = y; + displayRect.X = x; + displayRect.Y = y; - if (xDelta != 0 || yDelta != 0 && IsHandleCreated) { + if (xDelta != 0 || yDelta != 0 && IsHandleCreated) + { Rectangle cr = ClientRectangle; NativeMethods.RECT rcClip = NativeMethods.RECT.FromXYWH(cr.X, cr.Y, cr.Width, cr.Height); NativeMethods.RECT rcUpdate = NativeMethods.RECT.FromXYWH(cr.X, cr.Y, cr.Width, cr.Height); - SafeNativeMethods.ScrollWindowEx(new HandleRef(this, Handle), xDelta, yDelta, + SafeNativeMethods.ScrollWindowEx(new HandleRef(this, Handle), xDelta, yDelta, null, - ref rcClip, - NativeMethods.NullHandleRef, + ref rcClip, + NativeMethods.NullHandleRef, ref rcUpdate, NativeMethods.SW_INVALIDATE | NativeMethods.SW_ERASE | NativeMethods.SW_SCROLLCHILDREN); } - + // Force child controls to update bounds. // - for (int i=0; i 0 && client.Height > 0)) { + && (client.Width > 0 && client.Height > 0)) + { Debug.WriteLineIf(ScrollableControl.AutoScrolling.TraceVerbose, "Calculating..."); - + Point scrollLocation = ScrollToControl(activeControl); - + SetScrollState(ScrollStateUserHasScrolled, false); SetDisplayRectLocation(scrollLocation.X, scrollLocation.Y); @@ -888,7 +1009,8 @@ public void ScrollControlIntoView(Control activeControl) /// listBox1.AutoScrollOffset = parent.AutoScrollPosition; /// /// - protected virtual Point ScrollToControl(Control activeControl) { + protected virtual Point ScrollToControl(Control activeControl) + { Rectangle client = ClientRectangle; int xCalc = displayRect.X; @@ -897,32 +1019,39 @@ protected virtual Point ScrollToControl(Control activeControl) { int yMargin = scrollMargin.Height; Rectangle bounds = activeControl.Bounds; - if (activeControl.ParentInternal != this) { + if (activeControl.ParentInternal != this) + { Debug.WriteLineIf(ScrollableControl.AutoScrolling.TraceVerbose, "not direct child, original bounds: " + bounds); bounds = this.RectangleToClient(activeControl.ParentInternal.RectangleToScreen(bounds)); } Debug.WriteLineIf(ScrollableControl.AutoScrolling.TraceVerbose, "adjusted bounds: " + bounds); - if (bounds.X < xMargin) { + if (bounds.X < xMargin) + { xCalc = displayRect.X + xMargin - bounds.X; } - else if (bounds.X + bounds.Width + xMargin > client.Width) { + else if (bounds.X + bounds.Width + xMargin > client.Width) + { xCalc = client.Width - (bounds.X + bounds.Width + xMargin - displayRect.X); - if (bounds.X + xCalc - displayRect.X < xMargin) { + if (bounds.X + xCalc - displayRect.X < xMargin) + { xCalc = displayRect.X + xMargin - bounds.X; } } - if (bounds.Y < yMargin) { + if (bounds.Y < yMargin) + { yCalc = displayRect.Y + yMargin - bounds.Y; } - else if (bounds.Y + bounds.Height + yMargin > client.Height) { + else if (bounds.Y + bounds.Height + yMargin > client.Height) + { yCalc = client.Height - (bounds.Y + bounds.Height + yMargin - displayRect.Y); - if (bounds.Y + yCalc - displayRect.Y < yMargin) { + if (bounds.Y + yCalc - displayRect.Y < yMargin) + { yCalc = displayRect.Y + yMargin - bounds.Y; } } @@ -933,7 +1062,8 @@ protected virtual Point ScrollToControl(Control activeControl) { return new Point(xCalc, yCalc); } - private int ScrollThumbPosition(int fnBar) { + private int ScrollThumbPosition(int fnBar) + { NativeMethods.SCROLLINFO si = new NativeMethods.SCROLLINFO(); si.fMask = NativeMethods.SIF_TRACKPOS; SafeNativeMethods.GetScrollInfo(new HandleRef(this, Handle), fnBar, si); @@ -947,7 +1077,8 @@ private int ScrollThumbPosition(int fnBar) { /// /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ScrollBarOnScrollDescr))] - public event ScrollEventHandler Scroll { + public event ScrollEventHandler Scroll + { add => Events.AddHandler(EVENT_SCROLL, value); remove => Events.RemoveHandler(EVENT_SCROLL, value); } @@ -957,20 +1088,25 @@ public event ScrollEventHandler Scroll { /// Raises the event. /// /// - protected virtual void OnScroll(ScrollEventArgs se) { + protected virtual void OnScroll(ScrollEventArgs se) + { ScrollEventHandler handler = (ScrollEventHandler)Events[EVENT_SCROLL]; - if (handler != null) handler(this,se); + if (handler != null) + handler(this, se); } - private void ResetAutoScrollMargin() { - AutoScrollMargin = Size.Empty; - } + private void ResetAutoScrollMargin() + { + AutoScrollMargin = Size.Empty; + } - private void ResetAutoScrollMinSize() { - AutoScrollMinSize = Size.Empty; - } + private void ResetAutoScrollMinSize() + { + AutoScrollMinSize = Size.Empty; + } - private void ResetScrollProperties(ScrollProperties scrollProperties) { + private void ResetScrollProperties(ScrollProperties scrollProperties) + { // Set only these two values as when the ScrollBars are not visible ... // there is no meaning of the "value" property. scrollProperties._visible = false; @@ -983,20 +1119,25 @@ private void ResetScrollProperties(ScrollProperties scrollProperties) { /// of the auto-scroll margins. /// /// - public void SetAutoScrollMargin(int x, int y) { + public void SetAutoScrollMargin(int x, int y) + { // Make sure we're not setting the margins to negative numbers - if (x < 0) { + if (x < 0) + { x = 0; } - if (y < 0) { + if (y < 0) + { y = 0; } if (x != requestedScrollMargin.Width - || y != requestedScrollMargin.Height) { + || y != requestedScrollMargin.Height) + { requestedScrollMargin = new Size(x, y); - if (AutoScroll) { + if (AutoScroll) + { PerformLayout(); } } @@ -1007,13 +1148,15 @@ public void SetAutoScrollMargin(int x, int y) { /// Actually displays or hides the horiz and vert autoscrollbars. This will /// also adjust the values of formState to reflect the new state /// - private bool SetVisibleScrollbars(bool horiz, bool vert) { + private bool SetVisibleScrollbars(bool horiz, bool vert) + { bool needLayout = false; if (!horiz && HScroll || horiz && !HScroll || !vert && VScroll - || vert && !VScroll) { + || vert && !VScroll) + { needLayout = true; } @@ -1021,18 +1164,22 @@ private bool SetVisibleScrollbars(bool horiz, bool vert) { // If we are about to show the horizontal scrollbar, then // set this flag, so that we can set the right initial value // based on whether we are right to left. - if (horiz && !HScroll && (RightToLeft == RightToLeft.Yes)) { + if (horiz && !HScroll && (RightToLeft == RightToLeft.Yes)) + { resetRTLHScrollValue = true; } - - if (needLayout) { + + if (needLayout) + { int x = displayRect.X; int y = displayRect.Y; - if (!horiz) { + if (!horiz) + { x = 0; } - if (!vert) { + if (!vert) + { y = 0; } SetDisplayRectLocation(x, y); @@ -1066,11 +1213,13 @@ private bool SetVisibleScrollbars(bool horiz, bool vert) { /// autoscrolling. This will also adjust the x and y location of the /// virtual client area if the new size forces it. /// - private bool SetDisplayRectangleSize(int width, int height) { + private bool SetDisplayRectangleSize(int width, int height) + { bool needLayout = false; if (displayRect.Width != width - || displayRect.Height != height) { + || displayRect.Height != height) + { displayRect.Width = width; displayRect.Height = height; @@ -1080,23 +1229,29 @@ private bool SetDisplayRectangleSize(int width, int height) { int minX = ClientRectangle.Width - width; int minY = ClientRectangle.Height - height; - if (minX > 0) minX = 0; - if (minY > 0) minY = 0; + if (minX > 0) + minX = 0; + if (minY > 0) + minY = 0; int x = displayRect.X; int y = displayRect.Y; - if (!HScroll) { + if (!HScroll) + { x = 0; } - if (!VScroll) { + if (!VScroll) + { y = 0; } - if (x < minX) { + if (x < minX) + { x = minX; } - if (y < minY) { + if (y < minY) + { y = minY; } SetDisplayRectLocation(x, y); @@ -1109,11 +1264,14 @@ private bool SetDisplayRectangleSize(int width, int height) { /// Sets a given scroll state bit. /// /// - protected void SetScrollState(int bit, bool value) { - if (value) { + protected void SetScrollState(int bit, bool value) + { + if (value) + { scrollState |= bit; } - else { + else + { scrollState &= (~bit); } } @@ -1124,10 +1282,13 @@ protected void SetScrollState(int bit, bool value) { /// property should be persisted. /// /// - private bool ShouldSerializeAutoScrollPosition() { - if (AutoScroll) { + private bool ShouldSerializeAutoScrollPosition() + { + if (AutoScroll) + { Point pt = AutoScrollPosition; - if (pt.X != 0 || pt.Y != 0) { + if (pt.X != 0 || pt.Y != 0) + { return true; } } @@ -1139,8 +1300,9 @@ private bool ShouldSerializeAutoScrollPosition() { /// Indicates whether the property should be persisted. /// /// - private bool ShouldSerializeAutoScrollMargin() { - return !AutoScrollMargin.Equals(new Size(0,0)); + private bool ShouldSerializeAutoScrollMargin() + { + return !AutoScrollMargin.Equals(new Size(0, 0)); } /// @@ -1149,8 +1311,9 @@ private bool ShouldSerializeAutoScrollMargin() { /// property should be persisted. /// /// - private bool ShouldSerializeAutoScrollMinSize() { - return !AutoScrollMinSize.Equals(new Size(0,0)); + private bool ShouldSerializeAutoScrollMinSize() + { + return !AutoScrollMinSize.Equals(new Size(0, 0)); } @@ -1158,90 +1321,114 @@ private bool ShouldSerializeAutoScrollMinSize() { /// Updates the value of the autoscroll scrollbars based on the current form /// state. This is a one-way sync, updating the scrollbars only. /// - private void SyncScrollbars(bool autoScroll) { + private void SyncScrollbars(bool autoScroll) + { Rectangle displayRect = this.displayRect; - if (autoScroll) { - if (!IsHandleCreated) { + if (autoScroll) + { + if (!IsHandleCreated) + { return; } - - if (HScroll) { - if (!HorizontalScroll._maximumSetExternally) { - HorizontalScroll._maximum = displayRect.Width-1; + + if (HScroll) + { + if (!HorizontalScroll._maximumSetExternally) + { + HorizontalScroll._maximum = displayRect.Width - 1; } - if (!HorizontalScroll._largeChangeSetExternally) { + if (!HorizontalScroll._largeChangeSetExternally) + { HorizontalScroll._largeChange = ClientRectangle.Width; } - if (!HorizontalScroll._smallChangeSetExternally) { + if (!HorizontalScroll._smallChangeSetExternally) + { HorizontalScroll._smallChange = 5; } - if (resetRTLHScrollValue && !IsMirrored) { + if (resetRTLHScrollValue && !IsMirrored) + { resetRTLHScrollValue = false; BeginInvoke(new EventHandler(this.OnSetScrollPosition)); } - else if(-displayRect.X >= HorizontalScroll._minimum && -displayRect.X < HorizontalScroll._maximum) { + else if (-displayRect.X >= HorizontalScroll._minimum && -displayRect.X < HorizontalScroll._maximum) + { HorizontalScroll._value = -displayRect.X; - } - HorizontalScroll.UpdateScrollInfo (); + } + HorizontalScroll.UpdateScrollInfo(); } - if (VScroll) { - if (!VerticalScroll._maximumSetExternally) { - VerticalScroll._maximum = displayRect.Height-1; + if (VScroll) + { + if (!VerticalScroll._maximumSetExternally) + { + VerticalScroll._maximum = displayRect.Height - 1; } - if (!VerticalScroll._largeChangeSetExternally) { + if (!VerticalScroll._largeChangeSetExternally) + { VerticalScroll._largeChange = ClientRectangle.Height; } - if (!VerticalScroll._smallChangeSetExternally) { + if (!VerticalScroll._smallChangeSetExternally) + { VerticalScroll._smallChange = 5; } - if (-displayRect.Y >= VerticalScroll._minimum && -displayRect.Y < VerticalScroll._maximum) { + if (-displayRect.Y >= VerticalScroll._minimum && -displayRect.Y < VerticalScroll._maximum) + { VerticalScroll._value = -displayRect.Y; } - VerticalScroll.UpdateScrollInfo (); + VerticalScroll.UpdateScrollInfo(); } } - else { - if (this.HorizontalScroll.Visible) { + else + { + if (this.HorizontalScroll.Visible) + { HorizontalScroll.Value = -displayRect.X; } - else { + else + { ResetScrollProperties(HorizontalScroll); } - if (this.VerticalScroll.Visible) { + if (this.VerticalScroll.Visible) + { VerticalScroll.Value = -displayRect.Y; } - else { + else + { ResetScrollProperties(VerticalScroll); } } } - private void OnSetScrollPosition(object sender, EventArgs e) { - if (!IsMirrored) { - SendMessage(Interop.WindowMessages.WM_HSCROLL, - NativeMethods.Util.MAKELPARAM((RightToLeft == RightToLeft.Yes) ? NativeMethods.SB_RIGHT : NativeMethods.SB_LEFT,0), 0); + private void OnSetScrollPosition(object sender, EventArgs e) + { + if (!IsMirrored) + { + SendMessage(Interop.WindowMessages.WM_HSCROLL, + NativeMethods.Util.MAKELPARAM((RightToLeft == RightToLeft.Yes) ? NativeMethods.SB_RIGHT : NativeMethods.SB_LEFT, 0), 0); } } - + /// /// Queries the system to determine the users preference for full drag /// of windows. /// - private void UpdateFullDrag() { + private void UpdateFullDrag() + { SetScrollState(ScrollStateFullDrag, SystemInformation.DragFullWindows); } /// /// WM_VSCROLL handler /// - private void WmVScroll(ref Message m) { + private void WmVScroll(ref Message m) + { // The lparam is handle of the sending scrollbar, or NULL when // the scrollbar sending the message is the "form" scrollbar... // - if (m.LParam != IntPtr.Zero) { + if (m.LParam != IntPtr.Zero) + { base.WndProc(ref m); return; } @@ -1252,44 +1439,54 @@ private void WmVScroll(ref Message m) { int oldValue = pos; int maxPos = -(client.Height - displayRect.Height); - if (!AutoScroll) { + if (!AutoScroll) + { maxPos = this.VerticalScroll.Maximum; - } - - switch (NativeMethods.Util.LOWORD(m.WParam)) { + } + + switch (NativeMethods.Util.LOWORD(m.WParam)) + { case NativeMethods.SB_THUMBPOSITION: case NativeMethods.SB_THUMBTRACK: - pos = ScrollThumbPosition(NativeMethods.SB_VERT); + pos = ScrollThumbPosition(NativeMethods.SB_VERT); break; case NativeMethods.SB_LINEUP: - if (pos > 0) { - pos-=VerticalScroll.SmallChange; + if (pos > 0) + { + pos -= VerticalScroll.SmallChange; } - else { + else + { pos = 0; } break; case NativeMethods.SB_LINEDOWN: - if (pos < maxPos-VerticalScroll.SmallChange) { - pos+=VerticalScroll.SmallChange; + if (pos < maxPos - VerticalScroll.SmallChange) + { + pos += VerticalScroll.SmallChange; } - else { + else + { pos = maxPos; } break; case NativeMethods.SB_PAGEUP: - if (pos > VerticalScroll.LargeChange) { - pos-=VerticalScroll.LargeChange; + if (pos > VerticalScroll.LargeChange) + { + pos -= VerticalScroll.LargeChange; } - else { + else + { pos = 0; } break; case NativeMethods.SB_PAGEDOWN: - if (pos < maxPos-VerticalScroll.LargeChange) { - pos+=VerticalScroll.LargeChange; + if (pos < maxPos - VerticalScroll.LargeChange) + { + pos += VerticalScroll.LargeChange; } - else { + else + { pos = maxPos; } break; @@ -1302,7 +1499,8 @@ private void WmVScroll(ref Message m) { } // This bugs reproes on all those machine which have SystemInformation.DragFullWindows set to false // "thumbTrack" was incorrectly used... the usage should be identical to WnHScroll which follows. - if (GetScrollState(ScrollStateFullDrag) || thumbTrack ) { + if (GetScrollState(ScrollStateFullDrag) || thumbTrack) + { SetScrollState(ScrollStateUserHasScrolled, true); SetDisplayRectLocation(displayRect.X, -pos); SyncScrollbars(AutoScroll); @@ -1313,59 +1511,71 @@ private void WmVScroll(ref Message m) { /// /// WM_HSCROLL handler /// - private void WmHScroll(ref Message m) { + private void WmHScroll(ref Message m) + { // The lparam is handle of the sending scrollbar, or NULL when // the scrollbar sending the message is the "form" scrollbar... // - if (m.LParam != IntPtr.Zero) { + if (m.LParam != IntPtr.Zero) + { base.WndProc(ref m); return; } Rectangle client = ClientRectangle; - + int pos = -displayRect.X; int oldValue = pos; int maxPos = -(client.Width - displayRect.Width); - if (!AutoScroll) { + if (!AutoScroll) + { maxPos = this.HorizontalScroll.Maximum; } - switch (NativeMethods.Util.LOWORD(m.WParam)) { + switch (NativeMethods.Util.LOWORD(m.WParam)) + { case NativeMethods.SB_THUMBPOSITION: case NativeMethods.SB_THUMBTRACK: pos = ScrollThumbPosition(NativeMethods.SB_HORZ); break; case NativeMethods.SB_LINEUP: - if (pos > HorizontalScroll.SmallChange) { - pos-=HorizontalScroll.SmallChange; + if (pos > HorizontalScroll.SmallChange) + { + pos -= HorizontalScroll.SmallChange; } - else { + else + { pos = 0; } break; case NativeMethods.SB_LINEDOWN: - if (pos < maxPos-HorizontalScroll.SmallChange) { - pos+=HorizontalScroll.SmallChange; + if (pos < maxPos - HorizontalScroll.SmallChange) + { + pos += HorizontalScroll.SmallChange; } - else { + else + { pos = maxPos; } break; case NativeMethods.SB_PAGEUP: - if (pos > HorizontalScroll.LargeChange) { - pos-=HorizontalScroll.LargeChange; + if (pos > HorizontalScroll.LargeChange) + { + pos -= HorizontalScroll.LargeChange; } - else { + else + { pos = 0; } break; case NativeMethods.SB_PAGEDOWN: - if (pos < maxPos-HorizontalScroll.LargeChange) { - pos+=HorizontalScroll.LargeChange; + if (pos < maxPos - HorizontalScroll.LargeChange) + { + pos += HorizontalScroll.LargeChange; } - else { + else + { pos = maxPos; } break; @@ -1376,7 +1586,8 @@ private void WmHScroll(ref Message m) { pos = maxPos; break; } - if (GetScrollState(ScrollStateFullDrag) || NativeMethods.Util.LOWORD(m.WParam) != NativeMethods.SB_THUMBTRACK) { + if (GetScrollState(ScrollStateFullDrag) || NativeMethods.Util.LOWORD(m.WParam) != NativeMethods.SB_THUMBTRACK) + { SetScrollState(ScrollStateUserHasScrolled, true); SetDisplayRectLocation(-pos, displayRect.Y); SyncScrollbars(AutoScroll); @@ -1388,15 +1599,18 @@ private void WmHScroll(ref Message m) { /// This function gets called which populates the eventArgs and fires the OnScroll( ) event passing /// the appropriate scroll event and scroll bar. /// - private void WmOnScroll(ref Message m, int oldValue, int value, ScrollOrientation scrollOrientation) { + private void WmOnScroll(ref Message m, int oldValue, int value, ScrollOrientation scrollOrientation) + { ScrollEventType type = (ScrollEventType)NativeMethods.Util.LOWORD(m.WParam); - if (type != ScrollEventType.EndScroll) { + if (type != ScrollEventType.EndScroll) + { ScrollEventArgs se = new ScrollEventArgs(type, oldValue, value, scrollOrientation); OnScroll(se); } } - private void WmSettingChange(ref Message m) { + private void WmSettingChange(ref Message m) + { base.WndProc(ref m); UpdateFullDrag(); } @@ -1407,8 +1621,10 @@ private void WmSettingChange(ref Message m) { /// base.wndProc(m); to ensure the button continues to function properly. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { case Interop.WindowMessages.WM_VSCROLL: WmVScroll(ref m); break; @@ -1420,7 +1636,7 @@ protected override void WndProc(ref Message m) { break; default: base.WndProc(ref m); - break; + break; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SearchForVirtualItemEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SearchForVirtualItemEventArgs.cs index 0bbe231441e..b942385bfe8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SearchForVirtualItemEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SearchForVirtualItemEventArgs.cs @@ -27,7 +27,7 @@ public SearchForVirtualItemEventArgs(bool isTextSearch, bool isPrefixSearch, boo public int Index { get; set; } = -1; - public string Text{ get; } + public string Text { get; } public Point StartingPoint { get; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SelectedGridItemChangedEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SelectedGridItemChangedEventArgs.cs index 71537cff89d..0138cf5a38f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SelectedGridItemChangedEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SelectedGridItemChangedEventArgs.cs @@ -27,5 +27,5 @@ public SelectedGridItemChangedEventArgs(GridItem oldSel, GridItem newSel) /// The newly selected GridItem object /// public GridItem NewSelection { get; } - } + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SelectionRange.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SelectionRange.cs index b6e9097790c..7faf4c9709f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SelectionRange.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SelectionRange.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Diagnostics; @@ -21,7 +22,8 @@ namespace System.Windows.Forms { [ TypeConverterAttribute(typeof(SelectionRangeConverter)) ] - public sealed class SelectionRange { + public sealed class SelectionRange + { /// /// The lower limit of the selection range. /// @@ -35,33 +37,38 @@ public sealed class SelectionRange { /// /// Create a new SelectionRange object with the range [null, null]. /// - public SelectionRange() { + public SelectionRange() + { } /// /// Create a new SelectionRange object with the given range. /// - public SelectionRange(DateTime lower, DateTime upper) { + public SelectionRange(DateTime lower, DateTime upper) + { //NOTE: simcooke: we explicitly DO NOT want to throw an exception here - just silently // swap them around. This is because the win32 control can return non- // normalized ranges. - + // We use lower.Date and upper.Date to remove any time component // - if (lower < upper) { + if (lower < upper) + { start = lower.Date; end = upper.Date; } - else { + else + { start = upper.Date; end = lower.Date; - } + } } /// /// Create a new SelectionRange object given an existing SelectionRange object. /// - public SelectionRange(SelectionRange range) { + public SelectionRange(SelectionRange range) + { this.start = range.start; this.end = range.end; } @@ -69,11 +76,14 @@ public SelectionRange(SelectionRange range) { /// /// Returns the ending time of this range. /// - public DateTime End { - get { + public DateTime End + { + get + { return end; } - set { + set + { end = value.Date; } } @@ -81,11 +91,14 @@ public DateTime End { /// /// Starting time of this range /// - public DateTime Start { - get { + public DateTime Start + { + get + { return start; } - set { + set + { start = value.Date; } } @@ -93,7 +106,8 @@ public DateTime Start { /// /// Returns a string representation for this control. /// - public override string ToString() { + public override string ToString() + { return "SelectionRange: Start: " + start.ToString() + ", End: " + end.ToString(); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SelectionRangeConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SelectionRangeConverter.cs index 91d879dd032..759c10b49fc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SelectionRangeConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SelectionRangeConverter.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; @@ -21,14 +22,17 @@ namespace System.Windows.Forms { /// SelectionRange objects from one data type to another. Access this /// class through the TypeDescriptor. /// - public class SelectionRangeConverter : TypeConverter { - + public class SelectionRangeConverter : TypeConverter + { + /// /// Determines if this converter can convert an object in the given source /// type to the native type of the converter. /// - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { - if (sourceType == typeof(string) || sourceType == typeof(DateTime)) { + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + { + if (sourceType == typeof(string) || sourceType == typeof(DateTime)) + { return true; } return base.CanConvertFrom(context, sourceType); @@ -38,52 +42,61 @@ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceT /// Gets a value indicating whether this converter can /// convert an object to the given destination type using the context. /// - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { - if (destinationType == typeof(InstanceDescriptor) || destinationType == typeof(DateTime)) { + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) + { + if (destinationType == typeof(InstanceDescriptor) || destinationType == typeof(DateTime)) + { return true; } return base.CanConvertTo(context, destinationType); } - + /// /// Converts the given object to the converter's native type. /// - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - if (value is string) { + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + { + if (value is string) + { string text = ((string)value).Trim(); - if (text.Length == 0) { + if (text.Length == 0) + { return new SelectionRange(DateTime.Now.Date, DateTime.Now.Date); } - + // Separate the string into the two dates, and parse each one // - if (culture == null) { + if (culture == null) + { culture = CultureInfo.CurrentCulture; - } + } char separator = culture.TextInfo.ListSeparator[0]; - string[] tokens = text.Split(new char[] {separator}); - - if (tokens.Length == 2) { + string[] tokens = text.Split(new char[] { separator }); + + if (tokens.Length == 2) + { TypeConverter dateTimeConverter = TypeDescriptor.GetConverter(typeof(DateTime)); DateTime start = (DateTime)dateTimeConverter.ConvertFromString(context, culture, tokens[0]); - DateTime end = (DateTime)dateTimeConverter.ConvertFromString(context, culture, tokens[1]); + DateTime end = (DateTime)dateTimeConverter.ConvertFromString(context, culture, tokens[1]); return new SelectionRange(start, end); } - else { + else + { throw new ArgumentException(string.Format(SR.TextParseFailedFormat, text, "Start" + separator + " End")); } } - else if (value is DateTime) { + else if (value is DateTime) + { DateTime dt = (DateTime)value; return new SelectionRange(dt, dt); } - + return base.ConvertFrom(context, culture, value); } - + /// /// Converts the given object to another type. The most common types to convert /// are to and from a string object. The default implementation will make a call @@ -91,48 +104,58 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) { + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == null) + { throw new ArgumentNullException(nameof(destinationType)); } SelectionRange range = value as SelectionRange; - if (range != null) { - if (destinationType == typeof(string)) { - if (culture == null) { - culture = CultureInfo.CurrentCulture; + if (range != null) + { + if (destinationType == typeof(string)) + { + if (culture == null) + { + culture = CultureInfo.CurrentCulture; } string sep = culture.TextInfo.ListSeparator + " "; PropertyDescriptorCollection props = GetProperties(value); string[] args = new string[props.Count]; - - for (int i = 0; i < props.Count; i++) { + + for (int i = 0; i < props.Count; i++) + { object propValue = props[i].GetValue(value); args[i] = TypeDescriptor.GetConverter(propValue).ConvertToString(context, culture, propValue); } - + return string.Join(sep, args); } - if (destinationType == typeof(DateTime)) { + if (destinationType == typeof(DateTime)) + { return range.Start; } - if (destinationType == typeof(InstanceDescriptor)) { + if (destinationType == typeof(InstanceDescriptor)) + { ConstructorInfo ctor = typeof(SelectionRange).GetConstructor(new Type[] { typeof(DateTime), typeof(DateTime)}); - if (ctor != null) { - return new InstanceDescriptor(ctor, new object[] {range.Start, range.End}); + if (ctor != null) + { + return new InstanceDescriptor(ctor, new object[] { range.Start, range.End }); } } - } + } return base.ConvertTo(context, culture, value, destinationType); } - + /// /// Creates an instance of this type given a set of property values /// for the object. This is useful for objects that are immutable, but still /// want to provide changable properties. /// - public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) { + public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) + { try { return new SelectionRange((DateTime)propertyValues["Start"], @@ -152,7 +175,8 @@ public override object CreateInstance(ITypeDescriptorContext context, IDictionar /// Determines if changing a value on this object should require a call to /// CreateInstance to create a new value. /// - public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) { + public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) + { return true; } @@ -161,16 +185,18 @@ public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) /// does not return any properties. An easy implementation of this method /// can just call TypeDescriptor.GetProperties for the correct data type. /// - public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { + public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) + { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(SelectionRange), attributes); - return props.Sort(new string[] {"Start", "End"}); + return props.Sort(new string[] { "Start", "End" }); } - + /// /// Determines if this object supports properties. By default, this /// is false. /// - public override bool GetPropertiesSupported(ITypeDescriptorContext context) { + public override bool GetPropertiesSupported(ITypeDescriptorContext context) + { return true; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SendKeys.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SendKeys.cs index ad85733b120..ea5fadfaf9d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SendKeys.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SendKeys.cs @@ -3,34 +3,36 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.InteropServices; using System.Diagnostics; using System; - + using System.Drawing; using System.Collections; using System.ComponentModel; using System.Globalization; - + /// /// Provides methods for sending keystrokes to an application. /// - public class SendKeys { - private const int HAVESHIFT = 0; - private const int HAVECTRL = 1; - private const int HAVEALT = 2; - + public class SendKeys + { + private const int HAVESHIFT = 0; + private const int HAVECTRL = 1; + private const int HAVEALT = 2; + // I'm unsure what significance the value 10 has, but it seems to make sense // to make this a constant rather than have 10 sprinkled throughout the code. // It appears to be a sentinel value of some sort - indicating an unknown // grouping level. // - private const int UNKNOWN_GROUPING = 10; + private const int UNKNOWN_GROUPING = 10; - private static KeywordVk [] keywords = new KeywordVk[] { + private static KeywordVk[] keywords = new KeywordVk[] { new KeywordVk("ENTER", (int)Keys.Return), new KeywordVk("TAB", (int)Keys.Tab), new KeywordVk("ESC", (int)Keys.Escape), @@ -82,9 +84,9 @@ public class SendKeys { new KeywordVk("^", (int)(Keys.D6 | Keys.Shift)), }; - private const int SHIFTKEYSCAN = 0x0100; - private const int CTRLKEYSCAN = 0x0200; - private const int ALTKEYSCAN = 0x0400; + private const int SHIFTKEYSCAN = 0x0100; + private const int CTRLKEYSCAN = 0x0200; + private const int ALTKEYSCAN = 0x0400; /// /// should we stop using the hook? @@ -104,7 +106,7 @@ public class SendKeys { private static Queue events; private static bool fStartNewChar; - + private static SKWindow messageWindow; private enum SendMethodTypes @@ -124,72 +126,86 @@ private enum SendMethodTypes private static bool scrollLockChanged; private static bool kanaChanged; - static SendKeys() { + static SendKeys() + { Application.ThreadExit += new EventHandler(OnThreadExit); messageWindow = new SKWindow(); messageWindow.CreateControl(); } - + /// /// private constructor to prevent people from creating one of these. they /// should use public static methods /// - private SendKeys() { + private SendKeys() + { } /// /// adds an event to our list of events for the hook /// - private static void AddEvent(SKEvent skevent) { + private static void AddEvent(SKEvent skevent) + { - if (events == null) { + if (events == null) + { events = new Queue(); } events.Enqueue(skevent); } // Helper function for ParseKeys for doing simple, self-describing characters. - private static bool AddSimpleKey(char character, int repeat, IntPtr hwnd, int[] haveKeys, bool fStartNewChar, int cGrp) { + private static bool AddSimpleKey(char character, int repeat, IntPtr hwnd, int[] haveKeys, bool fStartNewChar, int cGrp) + { int vk = UnsafeNativeMethods.VkKeyScan(character); - if (vk != -1) { - if (haveKeys[HAVESHIFT] == 0 && (vk & SHIFTKEYSCAN) != 0) { + if (vk != -1) + { + if (haveKeys[HAVESHIFT] == 0 && (vk & SHIFTKEYSCAN) != 0) + { AddEvent(new SKEvent(Interop.WindowMessages.WM_KEYDOWN, (int)Keys.ShiftKey, fStartNewChar, hwnd)); fStartNewChar = false; haveKeys[HAVESHIFT] = UNKNOWN_GROUPING; } - if (haveKeys[HAVECTRL] == 0 && (vk & CTRLKEYSCAN) != 0) { + if (haveKeys[HAVECTRL] == 0 && (vk & CTRLKEYSCAN) != 0) + { AddEvent(new SKEvent(Interop.WindowMessages.WM_KEYDOWN, (int)Keys.ControlKey, fStartNewChar, hwnd)); fStartNewChar = false; haveKeys[HAVECTRL] = UNKNOWN_GROUPING; } - if (haveKeys[HAVEALT] == 0 && (vk & ALTKEYSCAN) != 0) { + if (haveKeys[HAVEALT] == 0 && (vk & ALTKEYSCAN) != 0) + { AddEvent(new SKEvent(Interop.WindowMessages.WM_KEYDOWN, (int)Keys.Menu, fStartNewChar, hwnd)); fStartNewChar = false; haveKeys[HAVEALT] = UNKNOWN_GROUPING; } - + AddMsgsForVK(vk & 0xff, repeat, haveKeys[HAVEALT] > 0 && haveKeys[HAVECTRL] == 0, hwnd); CancelMods(haveKeys, UNKNOWN_GROUPING, hwnd); } - else { + else + { int oemVal = SafeNativeMethods.OemKeyScan((short)(0xFF & (int)character)); - for (int i = 0; i < repeat; i++) { + for (int i = 0; i < repeat; i++) + { AddEvent(new SKEvent(Interop.WindowMessages.WM_CHAR, character, (int)(oemVal & 0xFFFF), hwnd)); } } - if (cGrp != 0) fStartNewChar = true; + if (cGrp != 0) + fStartNewChar = true; return fStartNewChar; } /// /// given the vk, add the appropriate messages for it /// - private static void AddMsgsForVK(int vk, int repeat, bool altnoctrldown, IntPtr hwnd) { - for (int i = 0; i < repeat; i++) { + private static void AddMsgsForVK(int vk, int repeat, bool altnoctrldown, IntPtr hwnd) + { + for (int i = 0; i < repeat; i++) + { AddEvent(new SKEvent(altnoctrldown ? Interop.WindowMessages.WM_SYSKEYDOWN : Interop.WindowMessages.WM_KEYDOWN, vk, fStartNewChar, hwnd)); // fStartNewChar = false; AddEvent(new SKEvent(altnoctrldown ? Interop.WindowMessages.WM_SYSKEYUP : Interop.WindowMessages.WM_KEYUP, vk, fStartNewChar, hwnd)); @@ -200,16 +216,20 @@ private static void AddMsgsForVK(int vk, int repeat, bool altnoctrldown, IntPtr /// called whenever there is a closing parenthesis, or the end of a /// character. This generates events for the end of a modifier. /// - private static void CancelMods(int [] haveKeys, int level, IntPtr hwnd) { - if (haveKeys[HAVESHIFT] == level) { + private static void CancelMods(int[] haveKeys, int level, IntPtr hwnd) + { + if (haveKeys[HAVESHIFT] == level) + { AddEvent(new SKEvent(Interop.WindowMessages.WM_KEYUP, (int)Keys.ShiftKey, false, hwnd)); haveKeys[HAVESHIFT] = 0; } - if (haveKeys[HAVECTRL] == level) { + if (haveKeys[HAVECTRL] == level) + { AddEvent(new SKEvent(Interop.WindowMessages.WM_KEYUP, (int)Keys.ControlKey, false, hwnd)); haveKeys[HAVECTRL] = 0; } - if (haveKeys[HAVEALT] == level) { + if (haveKeys[HAVEALT] == level) + { AddEvent(new SKEvent(Interop.WindowMessages.WM_SYSKEYUP, (int)Keys.Menu, false, hwnd)); haveKeys[HAVEALT] = 0; } @@ -218,8 +238,10 @@ private static void CancelMods(int [] haveKeys, int level, IntPtr hwnd) { /// /// install the hook. quite easy /// - private static void InstallHook() { - if (hhook == IntPtr.Zero) { + private static void InstallHook() + { + if (hhook == IntPtr.Zero) + { hook = new NativeMethods.HookProc(new SendKeysHookProc().Callback); stopHook = false; hhook = UnsafeNativeMethods.SetWindowsHookEx(NativeMethods.WH_JOURNALPLAYBACK, @@ -251,7 +273,7 @@ private static void TestHook() UnsafeNativeMethods.UnhookWindowsHookEx(new HandleRef(null, hookHandle)); } } - catch {} // ignore any exceptions to keep existing SendKeys behavior + catch { } // ignore any exceptions to keep existing SendKeys behavior } private static IntPtr EmptyHookCallback(int code, IntPtr wparam, IntPtr lparam) @@ -279,7 +301,7 @@ private static void LoadSendMethodFromConfig() else if (value.Equals("SendInput", StringComparison.OrdinalIgnoreCase)) sendMethod = SendMethodTypes.SendInput; } - catch {} // ignore any exceptions to keep existing SendKeys behavior + catch { } // ignore any exceptions to keep existing SendKeys behavior } } @@ -287,34 +309,40 @@ private static void LoadSendMethodFromConfig() /// tells us to shut down the server, perhaps if we're shutting down and the /// hook is still running /// - private static void JournalCancel() { - if (hhook != IntPtr.Zero) { + private static void JournalCancel() + { + if (hhook != IntPtr.Zero) + { stopHook = false; - if (events != null) { - events.Clear(); + if (events != null) + { + events.Clear(); } hhook = IntPtr.Zero; } } - private static byte[] GetKeyboardState() { - byte [] keystate = new byte[256]; + private static byte[] GetKeyboardState() + { + byte[] keystate = new byte[256]; UnsafeNativeMethods.GetKeyboardState(keystate); return keystate; } - private static void SetKeyboardState(byte[] keystate) { + private static void SetKeyboardState(byte[] keystate) + { UnsafeNativeMethods.SetKeyboardState(keystate); } - + /// /// before we do a sendkeys, we want to clear the state /// of a couple of keys [capslock, numlock, scrolllock] so they don't /// interfere. /// - private static void ClearKeyboardState() { + private static void ClearKeyboardState() + { - byte [] keystate = GetKeyboardState(); + byte[] keystate = GetKeyboardState(); keystate[(int)Keys.Capital] = 0; keystate[(int)Keys.NumLock] = 0; @@ -327,7 +355,8 @@ private static void ClearKeyboardState() { /// given the string, match the keyword to a VK. return -1 if it don't match /// nuthin' /// - private static int MatchKeyword(string keyword) { + private static int MatchKeyword(string keyword) + { for (int i = 0; i < keywords.Length; i++) if (string.Equals(keywords[i].keyword, keyword, StringComparison.OrdinalIgnoreCase)) return keywords[i].vk; @@ -340,24 +369,28 @@ private static int MatchKeyword(string keyword) { /// termiantes. It gives us a chance to uninstall our journal /// hook if we had one installed. /// - private static void OnThreadExit(object sender, EventArgs e) { - try { + private static void OnThreadExit(object sender, EventArgs e) + { + try + { UninstallJournalingHook(); } - catch { + catch + { } } - + /// /// parse the string the user has given us, and generate the appropriate /// events for the journaling hook /// - private static void ParseKeys(string keys, IntPtr hwnd) { + private static void ParseKeys(string keys, IntPtr hwnd) + { int i = 0; // these four variables are used for grouping - int [] haveKeys = new int[] { 0, 0, 0}; // shift, ctrl, alt + int[] haveKeys = new int[] { 0, 0, 0 }; // shift, ctrl, alt int cGrp = 0; // fStartNewChar indicates that the next msg will be the first @@ -369,12 +402,14 @@ private static void ParseKeys(string keys, IntPtr hwnd) { // okay, start whipping through the characters one at a time. // int keysLen = keys.Length; - while (i < keysLen) { + while (i < keysLen) + { int repeat = 1; char ch = keys[i]; int vk = 0; - switch (ch) { + switch (ch) + { case '}': // if these appear at this point they are out of // context, so return an error. KeyStart processes @@ -384,84 +419,100 @@ private static void ParseKeys(string keys, IntPtr hwnd) { case '{': int j = i + 1; - + // There's a unique class of strings of the form "{} n}" where // n is an integer - in this case we want to send n copies of the '}' character. // Here we test for the possibility of this class of problems, and skip the // first '}' in the string if necessary. // - if (j + 1 < keysLen && keys[j] == '}') { + if (j + 1 < keysLen && keys[j] == '}') + { // Scan for the final '}' character int final = j + 1; - while (final < keysLen && keys[final] != '}') { + while (final < keysLen && keys[final] != '}') + { final++; } - if (final < keysLen) { + if (final < keysLen) + { // Found the special case, so skip the first '}' in the string. // The remainder of the code will attempt to find the repeat count. j++; } } - + // okay, we're in a {...} situation. look for the keyword // while (j < keysLen && keys[j] != '}' - && !char.IsWhiteSpace(keys[j])) { + && !char.IsWhiteSpace(keys[j])) + { j++; } - - if (j >= keysLen) { + + if (j >= keysLen) + { throw new ArgumentException(SR.SendKeysKeywordDelimError); } - + // okay, have our KEYWORD. verify it's one we know about // string keyName = keys.Substring(i + 1, j - (i + 1)); // see if we have a space, which would mean a repeat count. // - if (char.IsWhiteSpace(keys[j])) { + if (char.IsWhiteSpace(keys[j])) + { int digit; - while (j < keysLen && char.IsWhiteSpace(keys[j])) { + while (j < keysLen && char.IsWhiteSpace(keys[j])) + { j++; } - - if (j >= keysLen) { - throw new ArgumentException(SR.SendKeysKeywordDelimError); + + if (j >= keysLen) + { + throw new ArgumentException(SR.SendKeysKeywordDelimError); } - - if (char.IsDigit(keys[j])) { + + if (char.IsDigit(keys[j])) + { digit = j; - while (j < keysLen && char.IsDigit(keys[j])) { + while (j < keysLen && char.IsDigit(keys[j])) + { j++; } repeat = int.Parse(keys.Substring(digit, j - digit), CultureInfo.InvariantCulture); } } - - if (j >= keysLen) { - throw new ArgumentException(SR.SendKeysKeywordDelimError); + + if (j >= keysLen) + { + throw new ArgumentException(SR.SendKeysKeywordDelimError); } - if (keys[j] != '}') { + if (keys[j] != '}') + { throw new ArgumentException(SR.InvalidSendKeysRepeat); } vk = MatchKeyword(keyName); - if (vk != -1) { + if (vk != -1) + { // Unlike AddSimpleKey, the bit mask uses Keys, rather than scan keys - if (haveKeys[HAVESHIFT] == 0 && (vk & (int)Keys.Shift) != 0) { + if (haveKeys[HAVESHIFT] == 0 && (vk & (int)Keys.Shift) != 0) + { AddEvent(new SKEvent(Interop.WindowMessages.WM_KEYDOWN, (int)Keys.ShiftKey, fStartNewChar, hwnd)); fStartNewChar = false; haveKeys[HAVESHIFT] = UNKNOWN_GROUPING; } - - if (haveKeys[HAVECTRL] == 0 && (vk & (int)Keys.Control) != 0) { + + if (haveKeys[HAVECTRL] == 0 && (vk & (int)Keys.Control) != 0) + { AddEvent(new SKEvent(Interop.WindowMessages.WM_KEYDOWN, (int)Keys.ControlKey, fStartNewChar, hwnd)); fStartNewChar = false; haveKeys[HAVECTRL] = UNKNOWN_GROUPING; } - - if (haveKeys[HAVEALT] == 0 && (vk & (int)Keys.Alt) != 0) { + + if (haveKeys[HAVEALT] == 0 && (vk & (int)Keys.Alt) != 0) + { AddEvent(new SKEvent(Interop.WindowMessages.WM_KEYDOWN, (int)Keys.Menu, fStartNewChar, hwnd)); fStartNewChar = false; haveKeys[HAVEALT] = UNKNOWN_GROUPING; @@ -469,10 +520,12 @@ private static void ParseKeys(string keys, IntPtr hwnd) { AddMsgsForVK(vk, repeat, haveKeys[HAVEALT] > 0 && haveKeys[HAVECTRL] == 0, hwnd); CancelMods(haveKeys, UNKNOWN_GROUPING, hwnd); } - else if (keyName.Length == 1) { + else if (keyName.Length == 1) + { fStartNewChar = AddSimpleKey(keyName[0], repeat, hwnd, haveKeys, fStartNewChar, cGrp); } - else { + else + { throw new ArgumentException(string.Format(SR.InvalidSendKeysKeyword, keys.Substring(i + 1, j - (i + 1)))); } @@ -481,7 +534,8 @@ private static void ParseKeys(string keys, IntPtr hwnd) { break; case '+': - if (haveKeys[HAVESHIFT] != 0) throw new ArgumentException(string.Format(SR.InvalidSendKeysString, keys)); + if (haveKeys[HAVESHIFT] != 0) + throw new ArgumentException(string.Format(SR.InvalidSendKeysString, keys)); AddEvent(new SKEvent(Interop.WindowMessages.WM_KEYDOWN, (int)Keys.ShiftKey, fStartNewChar, hwnd)); fStartNewChar = false; @@ -489,7 +543,8 @@ private static void ParseKeys(string keys, IntPtr hwnd) { break; case '^': - if (haveKeys[HAVECTRL]!= 0) throw new ArgumentException(string.Format(SR.InvalidSendKeysString, keys)); + if (haveKeys[HAVECTRL] != 0) + throw new ArgumentException(string.Format(SR.InvalidSendKeysString, keys)); AddEvent(new SKEvent(Interop.WindowMessages.WM_KEYDOWN, (int)Keys.ControlKey, fStartNewChar, hwnd)); fStartNewChar = false; @@ -497,7 +552,8 @@ private static void ParseKeys(string keys, IntPtr hwnd) { break; case '%': - if (haveKeys[HAVEALT] != 0) throw new ArgumentException(string.Format(SR.InvalidSendKeysString, keys)); + if (haveKeys[HAVEALT] != 0) + throw new ArgumentException(string.Format(SR.InvalidSendKeysString, keys)); AddEvent(new SKEvent((haveKeys[HAVECTRL] != 0) ? Interop.WindowMessages.WM_KEYDOWN : Interop.WindowMessages.WM_SYSKEYDOWN, (int)Keys.Menu, fStartNewChar, hwnd)); @@ -511,18 +567,24 @@ private static void ParseKeys(string keys, IntPtr hwnd) { // Nests three deep. // cGrp++; - if (cGrp > 3) throw new ArgumentException(SR.SendKeysNestingError); - - if (haveKeys[HAVESHIFT] == UNKNOWN_GROUPING) haveKeys[HAVESHIFT] = cGrp; - if (haveKeys[HAVECTRL] == UNKNOWN_GROUPING) haveKeys[HAVECTRL] = cGrp; - if (haveKeys[HAVEALT] == UNKNOWN_GROUPING) haveKeys[HAVEALT] = cGrp; + if (cGrp > 3) + throw new ArgumentException(SR.SendKeysNestingError); + + if (haveKeys[HAVESHIFT] == UNKNOWN_GROUPING) + haveKeys[HAVESHIFT] = cGrp; + if (haveKeys[HAVECTRL] == UNKNOWN_GROUPING) + haveKeys[HAVECTRL] = cGrp; + if (haveKeys[HAVEALT] == UNKNOWN_GROUPING) + haveKeys[HAVEALT] = cGrp; break; case ')': - if (cGrp < 1) throw new ArgumentException(string.Format(SR.InvalidSendKeysString, keys)); + if (cGrp < 1) + throw new ArgumentException(string.Format(SR.InvalidSendKeysString, keys)); CancelMods(haveKeys, cGrp, hwnd); cGrp--; - if (cGrp == 0) fStartNewChar = true; + if (cGrp == 0) + fStartNewChar = true; break; case '~': @@ -563,7 +625,7 @@ private static void SendInput(byte[] oldKeyboardState, Queue previousEvents) currentInput[1].type = NativeMethods.INPUT_KEYBOARD; // set KeyUp values for currentInput[1] - currentInput[1].inputUnion.ki.wVk = (short) 0; + currentInput[1].inputUnion.ki.wVk = (short)0; currentInput[1].inputUnion.ki.dwFlags = NativeMethods.KEYEVENTF_UNICODE | NativeMethods.KEYEVENTF_KEYUP; // initialize unused members @@ -576,7 +638,7 @@ private static void SendInput(byte[] oldKeyboardState, Queue previousEvents) int INPUTSize = Marshal.SizeOf(); // need these outside the lock below - uint eventsSent=0; + uint eventsSent = 0; int eventsTotal; // A lock here will allow multiple threads to SendInput at the same time. @@ -827,7 +889,8 @@ private static void ResetKeyboardUsingSendInput(int INPUTSize) /// /// Sends keystrokes to the active application. /// - public static void Send(string keys) { + public static void Send(string keys) + { Send(keys, null, false); } @@ -842,19 +905,22 @@ public static void Send(string keys) { // // No one is calling this method so it is safe to comment it out - + //private static void Send(string keys, /*bogus*/ Control control) { // Send(keys, control, false); //} - - private static void Send(string keys, Control control, bool wait) { - if (keys == null || keys.Length == 0) return; + private static void Send(string keys, Control control, bool wait) + { + + if (keys == null || keys.Length == 0) + return; // If we're not going to wait, make sure there is a pump. // - if (!wait && !Application.MessageLoop) { + if (!wait && !Application.MessageLoop) + { throw new InvalidOperationException(SR.SendKeysNoMessageLoop); } @@ -862,7 +928,7 @@ private static void Send(string keys, Control control, bool wait) { Queue previousEvents = null; if ((events != null) && (events.Count != 0)) { - previousEvents = (Queue) events.Clone(); + previousEvents = (Queue)events.Clone(); } // generate the list of events that we're going to fire off with the hook @@ -872,7 +938,8 @@ private static void Send(string keys, Control control, bool wait) { // if there weren't any events posted as a result, we're done! // - if (events == null) return; + if (events == null) + return; LoadSendMethodFromConfig(); @@ -914,7 +981,8 @@ private static void Send(string keys, Control control, bool wait) { /// Sends the given keys to the active application, and then waits for /// the messages to be processed. /// - public static void SendWait(string keys) { + public static void SendWait(string keys) + { SendWait(keys, null); } @@ -928,98 +996,116 @@ public static void SendWait(string keys) { // Windows journaling *looks* like it can be directed to a specific HWND, // it can't. // - private static void SendWait(string keys, Control control) { + private static void SendWait(string keys, Control control) + { Send(keys, control, true); } /// /// Processes all the Windows messages currently in the message queue. /// - public static void Flush() { + public static void Flush() + { Application.DoEvents(); - while (events != null && events.Count > 0) { + while (events != null && events.Count > 0) + { Application.DoEvents(); } } - + /// /// cleans up and uninstalls the hook /// - private static void UninstallJournalingHook() { - if (hhook != IntPtr.Zero) { + private static void UninstallJournalingHook() + { + if (hhook != IntPtr.Zero) + { stopHook = false; - if (events != null) { - events.Clear(); + if (events != null) + { + events.Clear(); } UnsafeNativeMethods.UnhookWindowsHookEx(new HandleRef(null, hhook)); hhook = IntPtr.Zero; } } - + /// /// SendKeys creates a window to monitor WM_CANCELJOURNAL messages. /// - private class SKWindow : Control { - - public SKWindow() { + private class SKWindow : Control + { + + public SKWindow() + { SetState(STATE_TOPLEVEL, true); SetState2(STATE2_INTERESTEDINUSERPREFERENCECHANGED, false); SetBounds(-1, -1, 0, 0); Visible = false; } - - protected override void WndProc(ref Message m) { - if (m.Msg == Interop.WindowMessages.WM_CANCELJOURNAL) { - try { + + protected override void WndProc(ref Message m) + { + if (m.Msg == Interop.WindowMessages.WM_CANCELJOURNAL) + { + try + { SendKeys.JournalCancel(); } - catch { + catch + { } } } } - + /// /// helps us hold information about the various events we're going to journal /// - private class SKEvent { + private class SKEvent + { internal int wm; internal int paramL; internal int paramH; internal IntPtr hwnd; - - public SKEvent(int a, int b, bool c, IntPtr hwnd) { + + public SKEvent(int a, int b, bool c, IntPtr hwnd) + { wm = a; paramL = b; paramH = c ? 1 : 0; this.hwnd = hwnd; } - public SKEvent(int a, int b, int c, IntPtr hwnd) { + public SKEvent(int a, int b, int c, IntPtr hwnd) + { wm = a; paramL = b; paramH = c; this.hwnd = hwnd; } } - + /// /// holds a keyword and the associated VK_ for it /// - private class KeywordVk { + private class KeywordVk + { internal string keyword; - internal int vk; - - public KeywordVk(string key, int v) { + internal int vk; + + public KeywordVk(string key, int v) + { keyword = key; vk = v; } } - + /// /// this class is our callback for the journaling hook we install /// - private class SendKeysHookProc { + private class SendKeysHookProc + { // Microsoft: There appears to be a timing issue where setting and removing and then setting // these hooks via SetWindowsHookEx / UnhookWindowsHookEx can cause messages to be left @@ -1028,37 +1114,42 @@ private class SendKeysHookProc { // until we get an HC_GETNEXT. We also sleep a bit in the Unhook... // private bool gotNextEvent = false; - - public virtual IntPtr Callback(int code, IntPtr wparam, IntPtr lparam) { + + public virtual IntPtr Callback(int code, IntPtr wparam, IntPtr lparam) + { NativeMethods.EVENTMSG eventmsg = Marshal.PtrToStructure(lparam); - - - if (UnsafeNativeMethods.GetAsyncKeyState((int)Keys.Pause) != 0) { + + + if (UnsafeNativeMethods.GetAsyncKeyState((int)Keys.Pause) != 0) + { SendKeys.stopHook = true; } - + // - switch (code) { + switch (code) + { case NativeMethods.HC_SKIP: - if (!gotNextEvent) { + if (!gotNextEvent) + { break; } - if (SendKeys.events != null && SendKeys.events.Count > 0) { - SendKeys.events.Dequeue(); + if (SendKeys.events != null && SendKeys.events.Count > 0) + { + SendKeys.events.Dequeue(); } SendKeys.stopHook = SendKeys.events == null || SendKeys.events.Count == 0; break; - + case NativeMethods.HC_GETNEXT: gotNextEvent = true; - - #if DEBUG + +#if DEBUG Debug.Assert(SendKeys.events != null && SendKeys.events.Count > 0 && !SendKeys.stopHook, "HC_GETNEXT when queue is empty!"); - #endif - +#endif + SKEvent evt = (SKEvent)SendKeys.events.Peek(); eventmsg.message = evt.wm; eventmsg.paramL = evt.paramL; @@ -1067,14 +1158,15 @@ public virtual IntPtr Callback(int code, IntPtr wparam, IntPtr lparam) { eventmsg.time = SafeNativeMethods.GetTickCount(); Marshal.StructureToPtr(eventmsg, lparam, true); break; - + default: if (code < 0) UnsafeNativeMethods.CallNextHookEx(new HandleRef(null, SendKeys.hhook), code, wparam, lparam); break; } - - if (SendKeys.stopHook) { + + if (SendKeys.stopHook) + { SendKeys.UninstallJournalingHook(); gotNextEvent = false; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs index 7050c53c2cc..4144ff80774 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System; @@ -81,7 +82,7 @@ public class SplitContainer : ContainerControl, ISupportInitialize // //Properties used using DRAWING a MOVING SPLITTER // - private int lastDrawSplit =1; + private int lastDrawSplit = 1; private int initialSplitterDistance; private Rectangle initialSplitterRectangle; private Point anchor = Point.Empty; @@ -127,8 +128,8 @@ public class SplitContainer : ContainerControl, ISupportInitialize // private IMessageFilter implementation SplitContainerMessageFilter splitContainerMessageFilter = null; - //This would avoid re-entrant code into SelectNextControl. - private bool selectNextControl = false; + //This would avoid re-entrant code into SelectNextControl. + private bool selectNextControl = false; // Initialization flag for ISupportInitialize private bool initializing = false; @@ -145,7 +146,7 @@ public SplitContainer() // either the left or bottom panel - RTL panel2 = new SplitterPanel(this); splitterRect = new Rectangle(); - + SetStyle(ControlStyles.SupportsTransparentBackColor, true); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); @@ -176,13 +177,16 @@ public SplitContainer() SRDescription(nameof(SR.FormAutoScrollDescr)), Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public override bool AutoScroll { - get { + public override bool AutoScroll + { + get + { //Always return false ... as Splitcontainer doesnt support AutoScroll return false; } - set { + set + { base.AutoScroll = value; } } @@ -192,11 +196,14 @@ public override bool AutoScroll { EditorBrowsable(EditorBrowsableState.Never), DefaultValue(typeof(Point), "0, 0") ] - public override Point AutoScrollOffset { - get { - return base.AutoScrollOffset; + public override Point AutoScrollOffset + { + get + { + return base.AutoScrollOffset; } - set { + set + { base.AutoScrollOffset = value; } } @@ -209,11 +216,14 @@ public override Point AutoScrollOffset { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false) ] - public new Size AutoScrollMinSize { - get { + public new Size AutoScrollMinSize + { + get + { return base.AutoScrollMinSize; } - set { + set + { base.AutoScrollMinSize = value; } } @@ -227,11 +237,14 @@ public override Point AutoScrollOffset { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false) ] - public new Size AutoScrollMargin { - get { + public new Size AutoScrollMargin + { + get + { return base.AutoScrollMargin; } - set { + set + { base.AutoScrollMargin = value; } } @@ -241,14 +254,17 @@ public override Point AutoScrollOffset { SRCategory(nameof(SR.CatLayout)), Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - SRDescription(nameof(SR.FormAutoScrollPositionDescr)) + SRDescription(nameof(SR.FormAutoScrollPositionDescr)) ] - public new Point AutoScrollPosition { - get { + public new Point AutoScrollPosition + { + get + { return base.AutoScrollPosition; } - set { + set + { base.AutoScrollPosition = value; } } @@ -271,28 +287,35 @@ public override bool AutoSize } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler AutoSizeChanged { + new public event EventHandler AutoSizeChanged + { add => base.AutoSizeChanged += value; remove => base.AutoSizeChanged -= value; } [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } @@ -308,11 +331,14 @@ public override ImageLayout BackgroundImageLayout { SRDescription(nameof(SR.ContainerControlBindingContextDescr)), SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly") ] - public override BindingContext BindingContext { - get { + public override BindingContext BindingContext + { + get + { return BindingContextInternal; } - set { + set + { BindingContextInternal = value; } } @@ -327,23 +353,30 @@ public override BindingContext BindingContext { System.Runtime.InteropServices.DispId(NativeMethods.ActiveX.DISPID_BORDERSTYLE), SRDescription(nameof(SR.SplitterBorderStyleDescr)) ] - public BorderStyle BorderStyle { - get { + public BorderStyle BorderStyle + { + get + { return borderStyle; } - set { + set + { //valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(BorderStyle)); } - if (borderStyle != value) { + if (borderStyle != value) + { borderStyle = value; Invalidate(); SetInnerMostBorder(this); - if (this.ParentInternal != null) { - if (this.ParentInternal is SplitterPanel) { + if (this.ParentInternal != null) + { + if (this.ParentInternal is SplitterPanel) + { SplitContainer sc = (SplitContainer)((SplitterPanel)this.ParentInternal).Owner; sc.SetInnerMostBorder(sc); } @@ -352,7 +385,7 @@ public BorderStyle BorderStyle { switch (BorderStyle) { - case BorderStyle.None: + case BorderStyle.None: BORDERSIZE = 0; break; case BorderStyle.FixedSingle: @@ -371,21 +404,25 @@ public BorderStyle BorderStyle { /// [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public new Control.ControlCollection Controls { - get { + public new Control.ControlCollection Controls + { + get + { return base.Controls; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event ControlEventHandler ControlAdded { + public new event ControlEventHandler ControlAdded + { add => base.ControlAdded += value; remove => base.ControlAdded -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event ControlEventHandler ControlRemoved { - add => base.ControlRemoved += value; - remove => base.ControlRemoved -= value; + public new event ControlEventHandler ControlRemoved + { + add => base.ControlRemoved += value; + remove => base.ControlRemoved -= value; } /// /// The dock property. The dock property controls to which edge @@ -393,14 +430,19 @@ public BorderStyle BorderStyle { /// the top of the container, the control will be displayed flush at the /// top of the container, extending the length of the container. /// - public new DockStyle Dock { - get { + public new DockStyle Dock + { + get + { return base.Dock; } - set { + set + { base.Dock = value; - if (this.ParentInternal != null) { - if (this.ParentInternal is SplitterPanel) { + if (this.ParentInternal != null) + { + if (this.ParentInternal is SplitterPanel) + { SplitContainer sc = (SplitContainer)((SplitterPanel)this.ParentInternal).Owner; sc.SetInnerMostBorder(sc); } @@ -413,8 +455,10 @@ public BorderStyle BorderStyle { /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(150, 100); } } @@ -428,31 +472,39 @@ protected override Size DefaultSize { SRCategory(nameof(SR.CatLayout)), SRDescription(nameof(SR.SplitContainerFixedPanelDescr)) ] - public FixedPanel FixedPanel { - get { + public FixedPanel FixedPanel + { + get + { return fixedPanel; } - set { + set + { //valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)FixedPanel.None, (int)FixedPanel.Panel2)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)FixedPanel.None, (int)FixedPanel.Panel2)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(FixedPanel)); } - if (fixedPanel != value) { + if (fixedPanel != value) + { fixedPanel = value; // UpdatePanelSize !! - switch (fixedPanel) { + switch (fixedPanel) + { case FixedPanel.Panel2: - if (Orientation == Orientation.Vertical) { - panelSize = Width - SplitterDistanceInternal - SplitterWidthInternal; + if (Orientation == Orientation.Vertical) + { + panelSize = Width - SplitterDistanceInternal - SplitterWidthInternal; } - else { - panelSize = Height - SplitterDistanceInternal - SplitterWidthInternal; + else + { + panelSize = Height - SplitterDistanceInternal - SplitterWidthInternal; } break; default: - panelSize = SplitterDistanceInternal; + panelSize = SplitterDistanceInternal; break; } } @@ -469,24 +521,31 @@ public FixedPanel FixedPanel { SRDescription(nameof(SR.SplitContainerIsSplitterFixedDescr)) ] - public bool IsSplitterFixed { - get { + public bool IsSplitterFixed + { + get + { return splitterFixed; } - set { + set + { splitterFixed = value; } } //Private property used to check whether the splitter can be moved by the user. - private bool IsSplitterMovable { - get { - if (Orientation == Orientation.Vertical) { - return (Width >= Panel1MinSize + SplitterWidthInternal + Panel2MinSize); - } - else { - return (Height >= Panel1MinSize + SplitterWidthInternal + Panel2MinSize); - } + private bool IsSplitterMovable + { + get + { + if (Orientation == Orientation.Vertical) + { + return (Width >= Panel1MinSize + SplitterWidthInternal + Panel2MinSize); + } + else + { + return (Height >= Panel1MinSize + SplitterWidthInternal + Panel2MinSize); + } } } @@ -509,32 +568,41 @@ internal override bool IsContainerControl Localizable(true), SRDescription(nameof(SR.SplitContainerOrientationDescr)) ] - public Orientation Orientation { - get { return orientation; } - set { + public Orientation Orientation + { + get { return orientation; } + set + { //valid values are 0x0 to 0x1 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)Orientation.Horizontal, (int)Orientation.Vertical)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)Orientation.Horizontal, (int)Orientation.Vertical)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(Orientation)); } - if (orientation != value) { + if (orientation != value) + { orientation = value; - //update the splitterDistance to validate it w.r.t the new Orientation. - splitDistance = 0; - SplitterDistance = SplitterDistanceInternal; + //update the splitterDistance to validate it w.r.t the new Orientation. + splitDistance = 0; + SplitterDistance = SplitterDistanceInternal; UpdateSplitter(); } } } - private Cursor OverrideCursor { - get { + private Cursor OverrideCursor + { + get + { return overrideCursor; } - set { - if (overrideCursor != value) { + set + { + if (overrideCursor != value) + { overrideCursor = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { // We want to instantly change the cursor if the mouse is within our bounds. NativeMethods.POINT p = new NativeMethods.POINT(); NativeMethods.RECT r = new NativeMethods.RECT(); @@ -550,8 +618,10 @@ private Cursor OverrideCursor { /// /// Indicates if either panel is collapsed /// - private bool CollapsedMode { - get { + private bool CollapsedMode + { + get + { return Panel1Collapsed || Panel2Collapsed; } } @@ -565,8 +635,10 @@ private bool CollapsedMode { Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Content) ] - public SplitterPanel Panel1 { - get { + public SplitterPanel Panel1 + { + get + { return this.panel1; } } @@ -574,13 +646,16 @@ public SplitterPanel Panel1 { /// /// Collapses or restores the given panel /// - private void CollapsePanel(SplitterPanel p, bool collapsing) { + private void CollapsePanel(SplitterPanel p, bool collapsing) + { p.Collapsed = collapsing; - if (collapsing) { + if (collapsing) + { p.Visible = false; } - else { + else + { // restore panel p.Visible = true; } @@ -592,18 +667,21 @@ private void CollapsePanel(SplitterPanel p, bool collapsing) { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Padding Padding { + public new Padding Padding + { get { return base.Padding; } - set { base.Padding = value;} + set { base.Padding = value; } } [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public new event EventHandler PaddingChanged { - add => base.PaddingChanged += value; - remove => base.PaddingChanged -= value; } + public new event EventHandler PaddingChanged + { + add => base.PaddingChanged += value; + remove => base.PaddingChanged -= value; + } /// /// Collapses or restores panel1 @@ -613,13 +691,18 @@ private void CollapsePanel(SplitterPanel p, bool collapsing) { DefaultValue(false), SRDescription(nameof(SR.SplitContainerPanel1CollapsedDescr)) ] - public bool Panel1Collapsed { - get { + public bool Panel1Collapsed + { + get + { return panel1.Collapsed; } - set { - if (value != panel1.Collapsed) { - if (value && panel2.Collapsed) { + set + { + if (value != panel1.Collapsed) + { + if (value && panel2.Collapsed) + { CollapsePanel(panel2, false); } CollapsePanel(panel1, value); @@ -636,13 +719,18 @@ public bool Panel1Collapsed { DefaultValue(false), SRDescription(nameof(SR.SplitContainerPanel2CollapsedDescr)) ] - public bool Panel2Collapsed { - get { + public bool Panel2Collapsed + { + get + { return panel2.Collapsed; } - set { - if (value != panel2.Collapsed) { - if (value && panel1.Collapsed) { + set + { + if (value != panel2.Collapsed) + { + if (value && panel1.Collapsed) + { CollapsePanel(panel1, false); } CollapsePanel(panel2, value); @@ -658,15 +746,19 @@ public bool Panel2Collapsed { DefaultValue(25), Localizable(true), SRDescription(nameof(SR.SplitContainerPanel1MinSizeDescr)), - RefreshProperties(RefreshProperties.All) + RefreshProperties(RefreshProperties.All) ] - public int Panel1MinSize { - get { + public int Panel1MinSize + { + get + { return panel1MinSize; } - set { + set + { newPanel1MinSize = value; - if (value != Panel1MinSize && !initializing) { + if (value != Panel1MinSize && !initializing) + { ApplyPanel1MinSize(value); } } @@ -681,8 +773,10 @@ public int Panel1MinSize { Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Content) ] - public SplitterPanel Panel2 { - get { + public SplitterPanel Panel2 + { + get + { return this.panel2; } } @@ -697,13 +791,17 @@ public SplitterPanel Panel2 { SRDescription(nameof(SR.SplitContainerPanel2MinSizeDescr)), RefreshProperties(RefreshProperties.All) ] - public int Panel2MinSize { - get { + public int Panel2MinSize + { + get + { return panel2MinSize; } - set { + set + { newPanel2MinSize = value; - if (value != Panel2MinSize && !initializing) { + if (value != Panel2MinSize && !initializing) + { ApplyPanel2MinSize(value); } } @@ -719,7 +817,7 @@ public int Panel2MinSize { SRDescription(nameof(SR.SplitContainerSplitterDistanceDescr)), DefaultValue(50) ] - public int SplitterDistance + public int SplitterDistance { get { @@ -729,18 +827,20 @@ public int SplitterDistance { if (value != SplitterDistance) { - if (value < 0) { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(SplitterDistance), string.Format(SR.InvalidLowBoundArgument, "SplitterDistance", value, 0)); } - + try { setSplitterDistance = true; - - if (Orientation == Orientation.Vertical) { - if (value < Panel1MinSize) + if (Orientation == Orientation.Vertical) + { + + if (value < Panel1MinSize) { value = Panel1MinSize; } @@ -748,7 +848,8 @@ public int SplitterDistance { value = this.Width - Panel2MinSize - SplitterWidthInternal; } - if (value < 0 ) { + if (value < 0) + { throw new InvalidOperationException(SR.SplitterDistanceNotAllowed); } splitDistance = value; @@ -756,7 +857,8 @@ public int SplitterDistance panel1.WidthInternal = SplitterDistance; } - else { + else + { if (value < Panel1MinSize) { @@ -767,7 +869,8 @@ public int SplitterDistance { value = this.Height - Panel2MinSize - SplitterWidthInternal; } - if (value < 0 ) { + if (value < 0) + { throw new InvalidOperationException(SR.SplitterDistanceNotAllowed); } splitDistance = value; @@ -775,16 +878,19 @@ public int SplitterDistance panel1.HeightInternal = SplitterDistance; } - switch (fixedPanel) { + switch (fixedPanel) + { case FixedPanel.Panel1: - panelSize = SplitterDistance; + panelSize = SplitterDistance; break; case FixedPanel.Panel2: - if (Orientation == Orientation.Vertical) { - panelSize = Width - SplitterDistance - SplitterWidthInternal; + if (Orientation == Orientation.Vertical) + { + panelSize = Width - SplitterDistance - SplitterWidthInternal; } - else { - panelSize = Height - SplitterDistance - SplitterWidthInternal; + else + { + panelSize = Height - SplitterDistance - SplitterWidthInternal; } break; } @@ -794,17 +900,20 @@ public int SplitterDistance { setSplitterDistance = false; } - OnSplitterMoved(new SplitterEventArgs(SplitterRectangle.X + SplitterRectangle.Width/2, SplitterRectangle.Y + SplitterRectangle.Height/2, SplitterRectangle.X, SplitterRectangle.Y)); + OnSplitterMoved(new SplitterEventArgs(SplitterRectangle.X + SplitterRectangle.Width / 2, SplitterRectangle.Y + SplitterRectangle.Height / 2, SplitterRectangle.X, SplitterRectangle.Y)); } } } - private int SplitterDistanceInternal { + private int SplitterDistanceInternal + { - get { + get + { return splitterDistance; } - set { + set + { SplitterDistance = value; } } @@ -818,13 +927,17 @@ private int SplitterDistanceInternal { Localizable(true), SRDescription(nameof(SR.SplitContainerSplitterIncrementDescr)) ] - public int SplitterIncrement { - get { + public int SplitterIncrement + { + get + { return splitterInc; } - set { + set + { - if (value < 1 ) { + if (value < 1) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(SplitterIncrement), value, 1)); } @@ -841,8 +954,10 @@ public int SplitterIncrement { SRDescription(nameof(SR.SplitContainerSplitterRectangleDescr)), Browsable(false) ] - public Rectangle SplitterRectangle { - get { + public Rectangle SplitterRectangle + { + get + { Rectangle r = splitterRect; r.X = splitterRect.X - Left; r.Y = splitterRect.Y - Top; @@ -859,13 +974,17 @@ public Rectangle SplitterRectangle { Localizable(true), DefaultValue(4) ] - public int SplitterWidth { - get { + public int SplitterWidth + { + get + { return splitterWidth; } - set { + set + { newSplitterWidth = value; - if (value != SplitterWidth && !initializing) { + if (value != SplitterWidth && !initializing) + { ApplySplitterWidth(value); } } @@ -875,8 +994,10 @@ public int SplitterWidth { /// We need to have a internal Property for the SplitterWidth which returns zero if we are in collapased mode. /// This property is used to Layout SplitContainer. /// - private int SplitterWidthInternal { - get { + private int SplitterWidthInternal + { + get + { // if CollapsedMode then splitterwidth == 0; return (CollapsedMode) ? 0 : splitterWidth; } @@ -892,12 +1013,16 @@ private int SplitterWidthInternal { DispId(NativeMethods.ActiveX.DISPID_TABSTOP), SRDescription(nameof(SR.ControlTabStopDescr)) ] - public new bool TabStop { - get { + public new bool TabStop + { + get + { return tabStop; } - set { - if (TabStop != value) { + set + { + if (TabStop != value) + { tabStop = value; OnTabStopChanged(EventArgs.Empty); } @@ -907,11 +1032,14 @@ private int SplitterWidthInternal { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Bindable(false)] - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; } } @@ -933,7 +1061,8 @@ public override string Text { /// ISupportInitialize support. Disables splitter panel min size and splitter width /// validation during initialization. /// - public void BeginInit() { + public void BeginInit() + { initializing = true; } @@ -941,17 +1070,21 @@ public void BeginInit() { /// ISupportInitialize support. Enables splitter panel min size and splitter width /// validation after initialization. /// - public void EndInit() { + public void EndInit() + { initializing = false; // validate and apply new value - if (newPanel1MinSize != panel1MinSize) { + if (newPanel1MinSize != panel1MinSize) + { ApplyPanel1MinSize(newPanel1MinSize); } - if (newPanel2MinSize != panel2MinSize) { + if (newPanel2MinSize != panel2MinSize) + { ApplyPanel2MinSize(newPanel2MinSize); } - if (newSplitterWidth != splitterWidth) { + if (newSplitterWidth != splitterWidth) + { ApplySplitterWidth(newSplitterWidth); } } @@ -970,31 +1103,36 @@ public void EndInit() { ///////////////////////////////////////////////////////////////////////////////////////////// [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] - new public event EventHandler BackgroundImageChanged { + new public event EventHandler BackgroundImageChanged + { add => base.BackgroundImageChanged += value; remove => base.BackgroundImageChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { + new public event EventHandler BackgroundImageLayoutChanged + { add => base.BackgroundImageLayoutChanged += value; remove => base.BackgroundImageLayoutChanged -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.SplitterSplitterMovingDescr))] - public event SplitterCancelEventHandler SplitterMoving { + public event SplitterCancelEventHandler SplitterMoving + { add => Events.AddHandler(EVENT_MOVING, value); remove => Events.RemoveHandler(EVENT_MOVING, value); } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.SplitterSplitterMovedDescr))] - public event SplitterEventHandler SplitterMoved { + public event SplitterEventHandler SplitterMoved + { add => Events.AddHandler(EVENT_MOVED, value); remove => Events.RemoveHandler(EVENT_MOVED, value); } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TextChanged { + new public event EventHandler TextChanged + { add => base.TextChanged += value; remove => base.TextChanged -= value; } @@ -1016,7 +1154,8 @@ public event SplitterEventHandler SplitterMoved { /// /// Overides the Control.OnGotFocus to Invalidate... /// - protected override void OnGotFocus(EventArgs e) { + protected override void OnGotFocus(EventArgs e) + { base.OnGotFocus(e); Invalidate(); @@ -1025,12 +1164,15 @@ protected override void OnGotFocus(EventArgs e) { /// /// Overrides the Control.OnKeydown for implementing splitter movements. /// - protected override void OnKeyDown(KeyEventArgs e) { + protected override void OnKeyDown(KeyEventArgs e) + { Debug.Assert(Enabled, "SplitContainer.OnKeyDown should not be called if the button is disabled"); base.OnKeyDown(e); //If the Panel1MinSize + Panel2MinSize < SplitContainer.Size then carry on the splitter move... - if (IsSplitterMovable && !IsSplitterFixed) { - if (e.KeyData == Keys.Escape && splitBegin) { + if (IsSplitterMovable && !IsSplitterFixed) + { + if (e.KeyData == Keys.Escape && splitBegin) + { splitBegin = false; splitBreak = true; return; @@ -1038,46 +1180,56 @@ protected override void OnKeyDown(KeyEventArgs e) { //valid Keys that move the splitter... if (e.KeyData == Keys.Right || e.KeyData == Keys.Down || e.KeyData == Keys.Left || e.KeyData == Keys.Up - && splitterFocused) { - if (splitBegin) { + && splitterFocused) + { + if (splitBegin) + { splitMove = true; } //left OR up - if (e.KeyData == Keys.Left || e.KeyData == Keys.Up && splitterFocused) { + if (e.KeyData == Keys.Left || e.KeyData == Keys.Up && splitterFocused) + { splitterDistance -= SplitterIncrement; splitterDistance = (splitterDistance < Panel1MinSize) ? splitterDistance + SplitterIncrement : Math.Max(splitterDistance, BORDERSIZE); } //right OR down - if (e.KeyData == Keys.Right || e.KeyData == Keys.Down && splitterFocused) { + if (e.KeyData == Keys.Right || e.KeyData == Keys.Down && splitterFocused) + { splitterDistance += SplitterIncrement; - if (Orientation == Orientation.Vertical) { - splitterDistance = (splitterDistance + SplitterWidth > Width - Panel2MinSize -BORDERSIZE) ? splitterDistance - SplitterIncrement : splitterDistance; + if (Orientation == Orientation.Vertical) + { + splitterDistance = (splitterDistance + SplitterWidth > Width - Panel2MinSize - BORDERSIZE) ? splitterDistance - SplitterIncrement : splitterDistance; } - else { + else + { splitterDistance = (splitterDistance + SplitterWidth > Height - Panel2MinSize - BORDERSIZE) ? splitterDistance - SplitterIncrement : splitterDistance; } } - if (!splitBegin) { + if (!splitBegin) + { splitBegin = true; } //draw Helper start - if (splitBegin && !splitMove) { + if (splitBegin && !splitMove) + { initialSplitterDistance = SplitterDistanceInternal; DrawSplitBar(DRAW_START); } - else { //draw helper move + else + { //draw helper move DrawSplitBar(DRAW_MOVE); //Moving by mouse .....gives the origin of the splitter.. // Rectangle r = CalcSplitLine(splitterDistance, 0); int xSplit = r.X; int ySplit = r.Y; - SplitterCancelEventArgs se = new SplitterCancelEventArgs(this.Left + SplitterRectangle.X + SplitterRectangle.Width/2, this.Top + SplitterRectangle.Y + SplitterRectangle.Height/2, xSplit, ySplit); + SplitterCancelEventArgs se = new SplitterCancelEventArgs(this.Left + SplitterRectangle.X + SplitterRectangle.Width / 2, this.Top + SplitterRectangle.Y + SplitterRectangle.Height / 2, xSplit, ySplit); OnSplitterMoving(se); - if (se.Cancel) { + if (se.Cancel) + { SplitEnd(false); } } @@ -1088,42 +1240,51 @@ protected override void OnKeyDown(KeyEventArgs e) { /// /// Overrides the Control.OnKeydown for implementing splitter movements. /// - protected override void OnKeyUp(KeyEventArgs e) { + protected override void OnKeyUp(KeyEventArgs e) + { base.OnKeyUp(e); - if (splitBegin && IsSplitterMovable) { + if (splitBegin && IsSplitterMovable) + { if (e.KeyData == Keys.Right || e.KeyData == Keys.Down || e.KeyData == Keys.Left || e.KeyData == Keys.Up - && splitterFocused) { + && splitterFocused) + { DrawSplitBar(DRAW_END); ApplySplitterDistance(); splitBegin = false; splitMove = false; } } - if (splitBreak) { + if (splitBreak) + { splitBreak = false; SplitEnd(false); } //problem with the Focus rect after Keyup .... //Focus rect and reverible lines leave a trace behind on the splitter... - using (Graphics g = CreateGraphicsInternal()) { - if (BackgroundImage == null) { - using (SolidBrush brush = new SolidBrush(this.BackColor)) { + using (Graphics g = CreateGraphicsInternal()) + { + if (BackgroundImage == null) + { + using (SolidBrush brush = new SolidBrush(this.BackColor)) + { g.FillRectangle(brush, SplitterRectangle); } } DrawFocus(g, SplitterRectangle); } - + } /// /// Overrides the Control.OnLayout. /// - protected override void OnLayout(LayoutEventArgs e) { + protected override void OnLayout(LayoutEventArgs e) + { SetInnerMostBorder(this); - - if (IsSplitterMovable && !setSplitterDistance) { + + if (IsSplitterMovable && !setSplitterDistance) + { ResizeSplitContainer(); } base.OnLayout(e); @@ -1132,7 +1293,8 @@ protected override void OnLayout(LayoutEventArgs e) { /// /// Overrides the Control.OnLostFocus to Invalidate. /// - protected override void OnLostFocus(EventArgs e) { + protected override void OnLostFocus(EventArgs e) + { base.OnLostFocus(e); Invalidate(); } @@ -1141,34 +1303,43 @@ protected override void OnLostFocus(EventArgs e) { /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnMouseMove(MouseEventArgs e) { + protected override void OnMouseMove(MouseEventArgs e) + { base.OnMouseMove(e); - if (!IsSplitterFixed && IsSplitterMovable) { + if (!IsSplitterFixed && IsSplitterMovable) + { //change cursor if default and user hasnt changed the cursor. if (Cursor == DefaultCursor && SplitterRectangle.Contains(e.Location)) { - if (Orientation == Orientation.Vertical) { + if (Orientation == Orientation.Vertical) + { OverrideCursor = Cursors.VSplit; } - else { + else + { OverrideCursor = Cursors.HSplit; } } - else { - OverrideCursor = null;; + else + { + OverrideCursor = null; + ; } - if (splitterClick) { - int x = e.X ; - int y = e.Y ; + if (splitterClick) + { + int x = e.X; + int y = e.Y; splitterDrag = true; SplitMove(x, y); - if (Orientation == Orientation.Vertical) { + if (Orientation == Orientation.Vertical) + { x = Math.Max(Math.Min(x, Width - Panel2MinSize), Panel1MinSize); y = Math.Max(y, 0); } - else { + else + { y = Math.Max(Math.Min(y, Height - Panel2MinSize), Panel1MinSize); x = Math.Max(x, 0); } @@ -1177,7 +1348,8 @@ protected override void OnMouseMove(MouseEventArgs e) { int ySplit = r.Y; SplitterCancelEventArgs se = new SplitterCancelEventArgs(x, y, xSplit, ySplit); OnSplitterMoving(se); - if (se.Cancel) { + if (se.Cancel) + { SplitEnd(false); } @@ -1188,9 +1360,11 @@ protected override void OnMouseMove(MouseEventArgs e) { /// /// Raises the event. /// - protected override void OnMouseLeave(EventArgs e) { + protected override void OnMouseLeave(EventArgs e) + { base.OnMouseLeave(e); - if (!Enabled) { + if (!Enabled) + { return; } OverrideCursor = null; @@ -1199,23 +1373,30 @@ protected override void OnMouseLeave(EventArgs e) { /// /// Raises the event. /// - protected override void OnMouseDown(MouseEventArgs e) { + protected override void OnMouseDown(MouseEventArgs e) + { base.OnMouseDown(e); //If the Panel1MinSize + Panel2MinSize < SplitContainer.Size then carry on the splitter move... - if (IsSplitterMovable && SplitterRectangle.Contains(e.Location)) { - if (!Enabled) { + if (IsSplitterMovable && SplitterRectangle.Contains(e.Location)) + { + if (!Enabled) + { return; } - if (e.Button == MouseButtons.Left && e.Clicks == 1 && !IsSplitterFixed) { + if (e.Button == MouseButtons.Left && e.Clicks == 1 && !IsSplitterFixed) + { // Focus the current splitter OnMouseDown. splitterFocused = true; IContainerControl c = this.ParentInternal.GetContainerControl(); - if (c != null) { + if (c != null) + { ContainerControl cc = c as ContainerControl; - if (cc == null) { + if (cc == null) + { c.ActiveControl = this; } - else { + else + { cc.SetActiveControl(this); } } @@ -1223,7 +1404,7 @@ protected override void OnMouseDown(MouseEventArgs e) { nextActiveControl = panel2; SplitBegin(e.X, e.Y); - splitterClick = true; + splitterClick = true; } } } @@ -1231,45 +1412,52 @@ protected override void OnMouseDown(MouseEventArgs e) { /// /// Raises the event. /// - protected override void OnMouseUp(MouseEventArgs e) { + protected override void OnMouseUp(MouseEventArgs e) + { base.OnMouseUp(e); - if (!Enabled) { + if (!Enabled) + { return; } - if (!IsSplitterFixed && IsSplitterMovable && splitterClick) { + if (!IsSplitterFixed && IsSplitterMovable && splitterClick) + { CaptureInternal = false; - - if (splitterDrag) { + + if (splitterDrag) + { CalcSplitLine(GetSplitterDistance(e.X, e.Y), 0); SplitEnd(true); } - else { + else + { SplitEnd(false); } - splitterClick = false; + splitterClick = false; splitterDrag = false; } } - /// - /// Overrides the Control.OnMove() to synchronize the - /// splitterRect with the position of the SplitContainer. - /// - protected override void OnMove(EventArgs e) - { - base.OnMove(e); - SetSplitterRect(this.Orientation == Orientation.Vertical); - } - + /// + /// Overrides the Control.OnMove() to synchronize the + /// splitterRect with the position of the SplitContainer. + /// + protected override void OnMove(EventArgs e) + { + base.OnMove(e); + SetSplitterRect(this.Orientation == Orientation.Vertical); + } + /// /// Overrides the Control.OnPaint() to focus the Splitter. /// - protected override void OnPaint(PaintEventArgs e) { + protected override void OnPaint(PaintEventArgs e) + { base.OnPaint(e); - if (Focused) { - DrawFocus(e.Graphics,SplitterRectangle); + if (Focused) + { + DrawFocus(e.Graphics, SplitterRectangle); } } @@ -1278,9 +1466,11 @@ protected override void OnPaint(PaintEventArgs e) { /// splitterMoving event. This event occurs while the splitter is /// being moved by the user. /// - public void OnSplitterMoving(SplitterCancelEventArgs e) { + public void OnSplitterMoving(SplitterCancelEventArgs e) + { SplitterCancelEventHandler handler = (SplitterCancelEventHandler)Events[EVENT_MOVING]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } @@ -1289,9 +1479,11 @@ public void OnSplitterMoving(SplitterCancelEventArgs e) { /// splitterMoved event. This event occurs when the user finishes /// moving the splitter. /// - public void OnSplitterMoved(SplitterEventArgs e) { + public void OnSplitterMoved(SplitterEventArgs e) + { SplitterEventHandler handler = (SplitterEventHandler)Events[EVENT_MOVED]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } //////////////////////////////////////////////////////////////////////////////////////////////// @@ -1301,7 +1493,8 @@ public void OnSplitterMoved(SplitterEventArgs e) { //////////////////////////////////////////////////////////////////////////////////////////////// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnRightToLeftChanged(EventArgs e) { + protected override void OnRightToLeftChanged(EventArgs e) + { base.OnRightToLeftChanged(e); // pass the RightToLeft value to the Parent. this.panel1.RightToLeft = this.RightToLeft; @@ -1320,24 +1513,31 @@ protected override void OnRightToLeftChanged(EventArgs e) { /// /// Validate and set the minimum size for Panel1. /// - private void ApplyPanel1MinSize(int value) { - if (value < 0) { + private void ApplyPanel1MinSize(int value) + { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgument, nameof(Panel1MinSize), value)); } - if (Orientation== Orientation.Vertical) { - if (DesignMode && Width != DefaultSize.Width && value + Panel2MinSize + SplitterWidth > Width) { + if (Orientation == Orientation.Vertical) + { + if (DesignMode && Width != DefaultSize.Width && value + Panel2MinSize + SplitterWidth > Width) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(Panel1MinSize), value)); } } - else if (Orientation == Orientation.Horizontal) { - if (DesignMode && Height != DefaultSize.Height && value + Panel2MinSize + SplitterWidth > Height) { + else if (Orientation == Orientation.Horizontal) + { + if (DesignMode && Height != DefaultSize.Height && value + Panel2MinSize + SplitterWidth > Height) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(Panel1MinSize), value)); } } panel1MinSize = value; - if (value > SplitterDistanceInternal) { + if (value > SplitterDistanceInternal) + { SplitterDistanceInternal = value; //Set the Splitter Distance to the end of Panel1 } } @@ -1345,23 +1545,30 @@ private void ApplyPanel1MinSize(int value) { /// /// Validate and set the minimum size for Panel2. /// - private void ApplyPanel2MinSize(int value) { - if (value < 0) { + private void ApplyPanel2MinSize(int value) + { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgument, nameof(Panel2MinSize), value, 0)); } - if (Orientation == Orientation.Vertical) { - if (DesignMode && Width != DefaultSize.Width && value + Panel1MinSize + SplitterWidth > Width) { + if (Orientation == Orientation.Vertical) + { + if (DesignMode && Width != DefaultSize.Width && value + Panel1MinSize + SplitterWidth > Width) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(Panel2MinSize), value.ToString())); } } - else if (Orientation == Orientation.Horizontal) { - if (DesignMode && Height != DefaultSize.Height && value + Panel1MinSize + SplitterWidth > Height) { + else if (Orientation == Orientation.Horizontal) + { + if (DesignMode && Height != DefaultSize.Height && value + Panel1MinSize + SplitterWidth > Height) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(Panel2MinSize), value)); } } panel2MinSize = value; - if (value > Panel2.Width) { + if (value > Panel2.Width) + { SplitterDistanceInternal = Panel2.Width + SplitterWidthInternal; //Set the Splitter Distance to the start of Panel2 } } @@ -1369,18 +1576,24 @@ private void ApplyPanel2MinSize(int value) { /// /// Validate and set the splitter width. /// - private void ApplySplitterWidth(int value) { - if (value < 1) { + private void ApplySplitterWidth(int value) + { + if (value < 1) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(SplitterWidth), value, 1)); } - if (Orientation == Orientation.Vertical) { - if (DesignMode && value + Panel1MinSize + Panel2MinSize > Width) { + if (Orientation == Orientation.Vertical) + { + if (DesignMode && value + Panel1MinSize + Panel2MinSize > Width) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(SplitterWidth), value)); } } - else if (Orientation == Orientation.Horizontal) { - if (DesignMode && value + Panel1MinSize + Panel2MinSize > Height) { + else if (Orientation == Orientation.Horizontal) + { + if (DesignMode && value + Panel1MinSize + Panel2MinSize > Height) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(SplitterWidth), value)); } } @@ -1392,28 +1605,35 @@ private void ApplySplitterWidth(int value) { /// Sets the split position to be the current split size. This is called /// by splitEdit /// - private void ApplySplitterDistance() { + private void ApplySplitterDistance() + { - using (new System.Windows.Forms.Layout.LayoutTransaction(this, this, "SplitterDistance", false)) { + using (new System.Windows.Forms.Layout.LayoutTransaction(this, this, "SplitterDistance", false)) + { SplitterDistanceInternal = splitterDistance; } // We need to invalidate when we have transparent backgournd. - if (this.BackColor == Color.Transparent) { + if (this.BackColor == Color.Transparent) + { // the panel1 retains the focus rect... so Invalidate the rect ... Invalidate(); } - if (Orientation == Orientation.Vertical) { - - if (RightToLeft == RightToLeft.No) { + if (Orientation == Orientation.Vertical) + { + + if (RightToLeft == RightToLeft.No) + { splitterRect.X = this.Location.X + SplitterDistanceInternal; } - else { + else + { splitterRect.X = this.Right - SplitterDistanceInternal - SplitterWidthInternal; } } - else { + else + { splitterRect.Y = this.Location.Y + SplitterDistanceInternal; } } @@ -1422,31 +1642,37 @@ private void ApplySplitterDistance() { /// Calculates the bounding rect of the split line. minWeight refers /// to the minimum height or width of the splitline. /// - private Rectangle CalcSplitLine(int splitSize, int minWeight) { + private Rectangle CalcSplitLine(int splitSize, int minWeight) + { - Rectangle r = new Rectangle(); - switch (Orientation) { + Rectangle r = new Rectangle(); + switch (Orientation) + { case Orientation.Vertical: - r.Width = SplitterWidthInternal ; + r.Width = SplitterWidthInternal; r.Height = Height; - if (r.Width < minWeight) { + if (r.Width < minWeight) + { r.Width = minWeight; } - - if (RightToLeft == RightToLeft.No) { + + if (RightToLeft == RightToLeft.No) + { r.X = panel1.Location.X + splitSize; } - else { + else + { r.X = Width - splitSize - SplitterWidthInternal; } - + break; case Orientation.Horizontal: r.Width = Width; r.Height = SplitterWidthInternal; - if (r.Width < minWeight) { + if (r.Width < minWeight) + { r.Width = minWeight; } r.Y = panel1.Location.Y + splitSize; @@ -1459,30 +1685,38 @@ private Rectangle CalcSplitLine(int splitSize, int minWeight) { /// Draws the splitter bar at the current location. Will automatically /// cleanup anyplace the splitter was drawn previously. /// - private void DrawSplitBar(int mode) { - if (mode != DRAW_START && lastDrawSplit != -1) { + private void DrawSplitBar(int mode) + { + if (mode != DRAW_START && lastDrawSplit != -1) + { DrawSplitHelper(lastDrawSplit); lastDrawSplit = -1; } // Bail if drawing with no old point... // - else if (mode != DRAW_START && lastDrawSplit == -1) { + else if (mode != DRAW_START && lastDrawSplit == -1) + { return; } - if (mode != DRAW_END) { - if (splitMove || splitBegin) { // Splitter is moved by keys and not by mouse - DrawSplitHelper(splitterDistance); - lastDrawSplit = splitterDistance; + if (mode != DRAW_END) + { + if (splitMove || splitBegin) + { // Splitter is moved by keys and not by mouse + DrawSplitHelper(splitterDistance); + lastDrawSplit = splitterDistance; } - else { + else + { DrawSplitHelper(splitterDistance); lastDrawSplit = splitterDistance; } } - else { - if (lastDrawSplit != -1) { + else + { + if (lastDrawSplit != -1) + { DrawSplitHelper(lastDrawSplit); } lastDrawSplit = -1; @@ -1495,8 +1729,9 @@ private void DrawSplitBar(int mode) { /// /// /// - private void DrawFocus(Graphics g, Rectangle r) { - r.Inflate (-1, -1); + private void DrawFocus(Graphics g, Rectangle r) + { + r.Inflate(-1, -1); ControlPaint.DrawFocusRectangle(g, r, this.ForeColor, this.BackColor); } @@ -1504,7 +1739,8 @@ private void DrawFocus(Graphics g, Rectangle r) { /// Draws the splitter line at the requested location. Should only be called /// by drawSpltBar. /// - private void DrawSplitHelper(int splitSize) { + private void DrawSplitHelper(int splitSize) + { Rectangle r = CalcSplitLine(splitSize, 3); IntPtr parentHandle = this.Handle; @@ -1520,25 +1756,31 @@ private void DrawSplitHelper(int splitSize) { /// /// Calculates the split size based on the mouse position (x, y). /// - private int GetSplitterDistance(int x, int y) { + private int GetSplitterDistance(int x, int y) + { int delta; - if (Orientation == Orientation.Vertical) { + if (Orientation == Orientation.Vertical) + { delta = x - anchor.X; } - else { + else + { delta = y - anchor.Y; } // Negative delta - moving to the left // Positive delta - moving to the right - + int size = 0; - switch (Orientation) { + switch (Orientation) + { case Orientation.Vertical: - if (RightToLeft == RightToLeft.No) { + if (RightToLeft == RightToLeft.No) + { size = Math.Max(panel1.Width + delta, BORDERSIZE); } - else { + else + { // In RTL negative delta actually means increasing the size.... size = Math.Max(panel1.Width - delta, BORDERSIZE); } @@ -1547,10 +1789,12 @@ private int GetSplitterDistance(int x, int y) { size = Math.Max(panel1.Height + delta, BORDERSIZE); break; } - if (Orientation == Orientation.Vertical) { + if (Orientation == Orientation.Vertical) + { return Math.Max(Math.Min(size, Width - Panel2MinSize), Panel1MinSize); } - else { + else + { return Math.Max(Math.Min(size, Height - Panel2MinSize), Panel1MinSize); } } @@ -1559,9 +1803,11 @@ private int GetSplitterDistance(int x, int y) { /// Process an arrowKey press by selecting the next control in the group /// that the activeControl belongs to. /// - private bool ProcessArrowKey(bool forward) { + private bool ProcessArrowKey(bool forward) + { Control group = this; - if (ActiveControl != null) { + if (ActiveControl != null) + { group = ActiveControl.ParentInternal; } return group.SelectNextControl(ActiveControl, forward, false, false, true); @@ -1572,16 +1818,21 @@ private bool ProcessArrowKey(bool forward) { /// private void RepaintSplitterRect() { - if (IsHandleCreated) { + if (IsHandleCreated) + { Graphics g = this.CreateGraphicsInternal(); - if (BackgroundImage != null) { + if (BackgroundImage != null) + { - using (TextureBrush textureBrush = new TextureBrush(BackgroundImage,WrapMode.Tile)) { + using (TextureBrush textureBrush = new TextureBrush(BackgroundImage, WrapMode.Tile)) + { g.FillRectangle(textureBrush, ClientRectangle); } } - else{ - using (SolidBrush solidBrush = new SolidBrush(this.BackColor)) { + else + { + using (SolidBrush solidBrush = new SolidBrush(this.BackColor)) + { g.FillRectangle(solidBrush, splitterRect); } } @@ -1590,7 +1841,8 @@ private void RepaintSplitterRect() } - private void SetSplitterRect(bool vertical) { + private void SetSplitterRect(bool vertical) + { if (vertical) { splitterRect.X = ((RightToLeft == RightToLeft.Yes) ? this.Width - splitterDistance - SplitterWidthInternal : this.Location.X + splitterDistance); @@ -1606,7 +1858,7 @@ private void SetSplitterRect(bool vertical) { splitterRect.Height = SplitterWidthInternal; } } - + /// /// Reize SplitContainer /// @@ -1619,44 +1871,52 @@ private void ResizeSplitContainer() panel1.SuspendLayout(); panel2.SuspendLayout(); - - if (this.Width == 0) { // Set the correct Width iif the WIDTH has changed to ZERO. + + if (this.Width == 0) + { // Set the correct Width iif the WIDTH has changed to ZERO. panel1.Size = new Size(0, panel1.Height); panel2.Size = new Size(0, panel2.Height); } - else if (this.Height == 0) { // Set the correct Height iif the HEIGHT has changed to ZERO. + else if (this.Height == 0) + { // Set the correct Height iif the HEIGHT has changed to ZERO. panel1.Size = new Size(panel1.Width, 0); panel2.Size = new Size(panel2.Width, 0); } - else + else { - if (Orientation == Orientation.Vertical) + if (Orientation == Orientation.Vertical) { // If no panel is collapsed then do the default ... - if (!CollapsedMode) + if (!CollapsedMode) { - if (this.FixedPanel == FixedPanel.Panel1) { + if (this.FixedPanel == FixedPanel.Panel1) + { panel1.Size = new Size(panelSize, Height); panel2.Size = new Size(Math.Max(Width - panelSize - SplitterWidthInternal, Panel2MinSize), Height); } - if (this.FixedPanel == FixedPanel.Panel2) { + if (this.FixedPanel == FixedPanel.Panel2) + { panel2.Size = new Size(panelSize, Height); splitterDistance = Math.Max(Width - panelSize - SplitterWidthInternal, Panel1MinSize); panel1.WidthInternal = splitterDistance; panel1.HeightInternal = Height; } - if (this.FixedPanel == FixedPanel.None) { - if (ratioWidth != 0.0) { + if (this.FixedPanel == FixedPanel.None) + { + if (ratioWidth != 0.0) + { splitterDistance = Math.Max((int)(Math.Floor(this.Width / ratioWidth)), Panel1MinSize); } panel1.WidthInternal = splitterDistance; //Default splitter distance from left or top. panel1.HeightInternal = Height; panel2.Size = new Size(Math.Max(Width - splitterDistance - SplitterWidthInternal, Panel2MinSize), Height); } - if (RightToLeft == RightToLeft.No) { + if (RightToLeft == RightToLeft.No) + { panel2.Location = new Point(panel1.WidthInternal + SplitterWidthInternal, 0); } - else { + else + { panel1.Location = new Point(Width - panel1.WidthInternal, 0); } RepaintSplitterRect(); @@ -1664,30 +1924,35 @@ private void ResizeSplitContainer() } else { - if (Panel1Collapsed) { + if (Panel1Collapsed) + { panel2.Size = this.Size; - panel2.Location = new Point(0,0); + panel2.Location = new Point(0, 0); } - else if (Panel2Collapsed) { + else if (Panel2Collapsed) + { panel1.Size = this.Size; - panel1.Location = new Point(0,0); + panel1.Location = new Point(0, 0); } } } - else if (Orientation == Orientation.Horizontal) { + else if (Orientation == Orientation.Horizontal) + { // If no panel is collapsed then do the default ... - if (!CollapsedMode) + if (!CollapsedMode) { - if (this.FixedPanel == FixedPanel.Panel1) { + if (this.FixedPanel == FixedPanel.Panel1) + { //Default splitter distance from left or top. panel1.Size = new Size(Width, panelSize); int panel2Start = panelSize + SplitterWidthInternal; panel2.Size = new Size(Width, Math.Max(Height - panel2Start, Panel2MinSize)); - panel2.Location = new Point(0,panel2Start); + panel2.Location = new Point(0, panel2Start); } - if (this.FixedPanel == FixedPanel.Panel2) { + if (this.FixedPanel == FixedPanel.Panel2) + { panel2.Size = new Size(Width, panelSize); splitterDistance = Math.Max(Height - Panel2.Height - SplitterWidthInternal, Panel1MinSize); @@ -1696,18 +1961,19 @@ private void ResizeSplitContainer() int panel2Start = splitterDistance + SplitterWidthInternal; panel2.Location = new Point(0, panel2Start); } - if (this.FixedPanel == FixedPanel.None) { + if (this.FixedPanel == FixedPanel.None) + { //NO PANEL FIXED !! if (ratioHeight != 0.0) { - splitterDistance = Math.Max((int)(Math.Floor(this.Height / ratioHeight )), Panel1MinSize); + splitterDistance = Math.Max((int)(Math.Floor(this.Height / ratioHeight)), Panel1MinSize); } panel1.HeightInternal = splitterDistance; //Default splitter distance from left or top. panel1.WidthInternal = Width; int panel2Start = splitterDistance + SplitterWidthInternal; - panel2.Size = new Size(Width,Math.Max(Height - panel2Start, Panel2MinSize)); - panel2.Location = new Point(0,panel2Start); - + panel2.Size = new Size(Width, Math.Max(Height - panel2Start, Panel2MinSize)); + panel2.Location = new Point(0, panel2Start); + } RepaintSplitterRect(); @@ -1715,21 +1981,25 @@ private void ResizeSplitContainer() } else { - if (Panel1Collapsed) { + if (Panel1Collapsed) + { panel2.Size = this.Size; - panel2.Location = new Point(0,0); + panel2.Location = new Point(0, 0); } - else if (Panel2Collapsed) { + else if (Panel2Collapsed) + { panel1.Size = this.Size; - panel1.Location = new Point(0,0); + panel1.Location = new Point(0, 0); } } } - try { + try + { resizeCalled = true; ApplySplitterDistance(); } - finally { + finally + { resizeCalled = false; } } @@ -1748,17 +2018,20 @@ private void ResizeSplitContainer() /// BoundsSpecified.None. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { + protected override void ScaleControl(SizeF factor, BoundsSpecified specified) + { try { splitContainerScaling = true; base.ScaleControl(factor, specified); float scale; - if (orientation == Orientation.Vertical) { + if (orientation == Orientation.Vertical) + { scale = factor.Width; } - else { + else + { scale = factor.Height; } SplitterWidth = (int)Math.Round((float)SplitterWidth * scale); @@ -1769,7 +2042,8 @@ protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { } } - protected override void Select(bool directed, bool forward) { + protected override void Select(bool directed, bool forward) + { // avoid re-entrant code. // SelectNextControl can call back on us.. and we might end up infinitely recursing. if (selectNextControl) @@ -1777,21 +2051,27 @@ protected override void Select(bool directed, bool forward) { return; } // continue selection iff panels have controls or tabstop is true. - if ((this.Panel1.Controls.Count > 0 || this.Panel2.Controls.Count > 0) || TabStop) { + if ((this.Panel1.Controls.Count > 0 || this.Panel2.Controls.Count > 0) || TabStop) + { SelectNextControlInContainer(this, forward, true, true, false); } - else { //If this SplitContainer cannot be selected let the parent select the next in line - try { + else + { //If this SplitContainer cannot be selected let the parent select the next in line + try + { Control parent = this.ParentInternal; selectNextControl = true; - while (parent != null) { - if (parent.SelectNextControl(this, forward, true, true, parent.ParentInternal == null)) { + while (parent != null) + { + if (parent.SelectNextControl(this, forward, true, true, parent.ParentInternal == null)) + { break; } parent = parent.ParentInternal; } } - finally { + finally + { selectNextControl = false; } } @@ -1801,31 +2081,40 @@ protected override void Select(bool directed, bool forward) { /// Selects the next control following ctl. /// private bool SelectNextControlInContainer(Control ctl, bool forward, bool tabStopOnly, - bool nested, bool wrap) { - if (!Contains(ctl) || !nested && ctl.ParentInternal != this) ctl = null; + bool nested, bool wrap) + { + if (!Contains(ctl) || !nested && ctl.ParentInternal != this) + ctl = null; Control start = ctl; SplitterPanel firstPanel = null; - do { + do + { ctl = GetNextControl(ctl, forward); SplitterPanel panel = ctl as SplitterPanel; - if (panel != null && panel.Visible) { + if (panel != null && panel.Visible) + { //We have crossed over to the second Panel... - if (firstPanel != null) { + if (firstPanel != null) + { break; } firstPanel = panel; } - if (!forward && firstPanel != null && ctl.ParentInternal != firstPanel) { + if (!forward && firstPanel != null && ctl.ParentInternal != firstPanel) + { //goback to start correct re-ordering .... ctl = firstPanel; break; } - if (ctl == null) { + if (ctl == null) + { break; } - else { - if (ctl.CanSelect && ctl.TabStop) { + else + { + if (ctl.CanSelect && ctl.TabStop) + { if (ctl is SplitContainer) { ((SplitContainer)ctl).Select(forward, forward); @@ -1838,16 +2127,20 @@ private bool SelectNextControlInContainer(Control ctl, bool forward, bool tabSto } } } while (ctl != null); - if (ctl != null && this.TabStop) { + if (ctl != null && this.TabStop) + { //we are on Splitter.....Focus it splitterFocused = true; IContainerControl c = this.ParentInternal.GetContainerControl(); - if (c != null) { + if (c != null) + { ContainerControl cc = c as ContainerControl; - if (cc == null) { + if (cc == null) + { c.ActiveControl = this; } - else { + else + { cc.SetActiveControl(this); } } @@ -1856,7 +2149,7 @@ private bool SelectNextControlInContainer(Control ctl, bool forward, bool tabSto return true; } else - { + { // If the splitter cannot be selected select the next control in the splitter bool selected = SelectNextControlInPanel(ctl, forward, tabStopOnly, nested, wrap); if (!selected) @@ -1884,17 +2177,23 @@ private bool SelectNextControlInContainer(Control ctl, bool forward, bool tabSto /// [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] private bool SelectNextControlInPanel(Control ctl, bool forward, bool tabStopOnly, - bool nested, bool wrap) { + bool nested, bool wrap) + { - if (!Contains(ctl) || !nested && ctl.ParentInternal != this) ctl = null; + if (!Contains(ctl) || !nested && ctl.ParentInternal != this) + ctl = null; Control start = ctl; - do { + do + { ctl = GetNextControl(ctl, forward); - if (ctl == null || (ctl is SplitterPanel && ctl.Visible)) { + if (ctl == null || (ctl is SplitterPanel && ctl.Visible)) + { break; } - else { - if (ctl.CanSelect && (!tabStopOnly || ctl.TabStop)) { + else + { + if (ctl.CanSelect && (!tabStopOnly || ctl.TabStop)) + { if (ctl is SplitContainer) { ((SplitContainer)ctl).Select(forward, forward); @@ -1909,7 +2208,8 @@ private bool SelectNextControlInPanel(Control ctl, bool forward, bool tabStopOnl } while (ctl != null); //If CTL == null .. we r out of the Current SplitContainer... - if (ctl == null || (ctl is SplitterPanel && !ctl.Visible)) { + if (ctl == null || (ctl is SplitterPanel && !ctl.Visible)) + { callBaseVersion = true; } @@ -1918,11 +2218,14 @@ private bool SelectNextControlInPanel(Control ctl, bool forward, bool tabStopOnl else { ctl = GetNextControl(ctl, forward); - if (forward) { + if (forward) + { nextActiveControl = panel2; } - else { - if (ctl == null || !(ctl.ParentInternal.Visible)) { + else + { + if (ctl == null || !(ctl.ParentInternal.Visible)) + { callBaseVersion = true; } else @@ -1962,24 +2265,31 @@ private static void SelectNextActiveControl(Control ctl, bool forward, bool tabS /// /// Selects the innermost PANEL. /// - private void SetInnerMostBorder(SplitContainer sc) { - foreach(Control ctl in sc.Controls) { + private void SetInnerMostBorder(SplitContainer sc) + { + foreach (Control ctl in sc.Controls) + { bool foundChildSplitContainer = false; - if (ctl is SplitterPanel) { - foreach (Control c in ctl.Controls) { + if (ctl is SplitterPanel) + { + foreach (Control c in ctl.Controls) + { SplitContainer c1 = c as SplitContainer; - if (c1 != null && c1.Dock == DockStyle.Fill) { - // We need to Overlay borders - // if the Children have matching BorderStyles ... - if (c1.BorderStyle != BorderStyle) { - break; - } + if (c1 != null && c1.Dock == DockStyle.Fill) + { + // We need to Overlay borders + // if the Children have matching BorderStyles ... + if (c1.BorderStyle != BorderStyle) + { + break; + } ((SplitterPanel)ctl).BorderStyle = BorderStyle.None; - SetInnerMostBorder(c1); - foundChildSplitContainer = true; + SetInnerMostBorder(c1); + foundChildSplitContainer = true; } } - if (!foundChildSplitContainer) { + if (!foundChildSplitContainer) + { ((SplitterPanel)ctl).BorderStyle = BorderStyle; } } @@ -1993,10 +2303,12 @@ private void SetInnerMostBorder(SplitContainer sc) { /// Say, the Panel1MinSize == 150 , Panel2MinSize == 50 and SplitterWidth == 4 and the user tries /// to set SplitContainer.Width = 50 ... then this function would try to correct the value to 204.. instead of throwing. /// - protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { + protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) + { // If we are changing Height, check if its greater than minimun else ... make it equal to the minimum - if ((specified & BoundsSpecified.Height) != BoundsSpecified.None && Orientation == Orientation.Horizontal) { + if ((specified & BoundsSpecified.Height) != BoundsSpecified.None && Orientation == Orientation.Horizontal) + { if (height < Panel1MinSize + SplitterWidthInternal + Panel2MinSize) { height = Panel1MinSize + SplitterWidthInternal + Panel2MinSize; @@ -2004,13 +2316,14 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound } // If we are changing Width, check if its greater than minimun else ... make it equal to the minimum - if ((specified & BoundsSpecified.Width) != BoundsSpecified.None && Orientation == Orientation.Vertical) { + if ((specified & BoundsSpecified.Width) != BoundsSpecified.None && Orientation == Orientation.Vertical) + { if (width < Panel1MinSize + SplitterWidthInternal + Panel2MinSize) { width = Panel1MinSize + SplitterWidthInternal + Panel2MinSize; } } - + base.SetBoundsCore(x, y, width, height, specified); SetSplitterRect(this.Orientation == Orientation.Vertical); @@ -2019,7 +2332,8 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound /// /// Begins the splitter moving. /// - private void SplitBegin(int x, int y) { + private void SplitBegin(int x, int y) + { anchor = new Point(x, y); splitterDistance = GetSplitterDistance(x, y); initialSplitterDistance = splitterDistance; @@ -2038,24 +2352,26 @@ private void SplitBegin(int x, int y) { /// /// The split movement. /// - private void SplitMove(int x, int y) { + private void SplitMove(int x, int y) + { int size = GetSplitterDistance(x, y); int delta = size - initialSplitterDistance; int mod = delta % SplitterIncrement; - if (splitterDistance != size) { + if (splitterDistance != size) + { if (Orientation == Orientation.Vertical) { - if (size + SplitterWidthInternal <= this.Width - Panel2MinSize - BORDERSIZE) - { - splitterDistance = size - mod; - } + if (size + SplitterWidthInternal <= this.Width - Panel2MinSize - BORDERSIZE) + { + splitterDistance = size - mod; + } } else { - if (size + SplitterWidthInternal <= this.Height - Panel2MinSize - BORDERSIZE) - { - splitterDistance = size - mod; - } + if (size + SplitterWidthInternal <= this.Height - Panel2MinSize - BORDERSIZE) + { + splitterDistance = size - mod; + } } } DrawSplitBar(DRAW_MOVE); @@ -2064,19 +2380,22 @@ private void SplitMove(int x, int y) { /// /// Finishes the split movement. /// - private void SplitEnd(bool accept) { + private void SplitEnd(bool accept) + { DrawSplitBar(DRAW_END); if (splitContainerMessageFilter != null) { - Application.RemoveMessageFilter(splitContainerMessageFilter); + Application.RemoveMessageFilter(splitContainerMessageFilter); splitContainerMessageFilter = null; } - if (accept) { + if (accept) + { ApplySplitterDistance(); - + } - else if (splitterDistance != initialSplitterDistance) { + else if (splitterDistance != initialSplitterDistance) + { splitterClick = false; splitterDistance = SplitterDistanceInternal = initialSplitterDistance; } @@ -2087,112 +2406,132 @@ private void SplitEnd(bool accept) { /// /// Update Splitter /// - private void UpdateSplitter() { + private void UpdateSplitter() + { if (splitContainerScaling) { return; } panel1.SuspendLayout(); panel2.SuspendLayout(); - if (Orientation == Orientation.Vertical) { + if (Orientation == Orientation.Vertical) + { bool isRTL = RightToLeft == RightToLeft.Yes; //NO PANEL FIXED !! - if (!CollapsedMode) { + if (!CollapsedMode) + { panel1.HeightInternal = Height; panel1.WidthInternal = splitterDistance; //Default splitter distance from left or top. panel2.Size = new Size(Width - splitterDistance - SplitterWidthInternal, Height); - - if (!isRTL) { - panel1.Location = new Point(0,0); + + if (!isRTL) + { + panel1.Location = new Point(0, 0); panel2.Location = new Point(splitterDistance + SplitterWidthInternal, 0); } - else { + else + { panel1.Location = new Point(Width - splitterDistance, 0); panel2.Location = new Point(0, 0); } RepaintSplitterRect(); SetSplitterRect(true /*Vertical*/); - if (!resizeCalled) { - ratioWidth = ((double)(this.Width) / (double)(panel1.Width) > 0) ? (double)(this.Width) / (double)(panel1.Width) : ratioWidth; + if (!resizeCalled) + { + ratioWidth = ((double)(this.Width) / (double)(panel1.Width) > 0) ? (double)(this.Width) / (double)(panel1.Width) : ratioWidth; } - - + + } - else { - if (Panel1Collapsed) { + else + { + if (Panel1Collapsed) + { panel2.Size = this.Size; - panel2.Location = new Point(0,0); + panel2.Location = new Point(0, 0); } - else if (Panel2Collapsed) { + else if (Panel2Collapsed) + { panel1.Size = this.Size; - panel1.Location = new Point(0,0); + panel1.Location = new Point(0, 0); } // Update Ratio when the splitContainer is in CollapsedMode. if (!resizeCalled) { - ratioWidth = ((double)(this.Width) / (double)(splitterDistance) > 0) ? (double)(this.Width) / (double)(splitterDistance) : ratioWidth; + ratioWidth = ((double)(this.Width) / (double)(splitterDistance) > 0) ? (double)(this.Width) / (double)(splitterDistance) : ratioWidth; } } } - else { + else + { //NO PANEL FIXED !! - if (!CollapsedMode) { - panel1.Location = new Point(0,0); + if (!CollapsedMode) + { + panel1.Location = new Point(0, 0); panel1.WidthInternal = Width; panel1.HeightInternal = SplitterDistanceInternal; //Default splitter distance from left or top. int panel2Start = splitterDistance + SplitterWidthInternal; panel2.Size = new Size(Width, Height - panel2Start); - panel2.Location = new Point(0,panel2Start); + panel2.Location = new Point(0, panel2Start); RepaintSplitterRect(); SetSplitterRect(false/*Horizontal*/); - - if (!resizeCalled) { - ratioHeight = ((double)(this.Height) / (double)(panel1.Height) > 0) ? (double)(this.Height) / (double)(panel1.Height) : ratioHeight; + + if (!resizeCalled) + { + ratioHeight = ((double)(this.Height) / (double)(panel1.Height) > 0) ? (double)(this.Height) / (double)(panel1.Height) : ratioHeight; } } - else { - if (Panel1Collapsed) { + else + { + if (Panel1Collapsed) + { panel2.Size = this.Size; - panel2.Location = new Point(0,0); + panel2.Location = new Point(0, 0); } - else if (Panel2Collapsed) { + else if (Panel2Collapsed) + { panel1.Size = this.Size; - panel1.Location = new Point(0,0); + panel1.Location = new Point(0, 0); } // Update Ratio when the splitContainer is in CollapsedMode. if (!resizeCalled) { - ratioHeight = ((double)(this.Height) / (double)(splitterDistance) > 0) ? (double)(this.Height) / (double)(splitterDistance) : ratioHeight; + ratioHeight = ((double)(this.Height) / (double)(splitterDistance) > 0) ? (double)(this.Height) / (double)(splitterDistance) : ratioHeight; } } } panel1.ResumeLayout(); - panel2.ResumeLayout(); - } + panel2.ResumeLayout(); + } /// /// Handles the WM_SETCURSOR message /// - private void WmSetCursor(ref Message m) { + private void WmSetCursor(ref Message m) + { // Accessing through the Handle property has side effects that break this // logic. You must use InternalHandle. // - if (m.WParam == InternalHandle && ((int)m.LParam & 0x0000FFFF) == NativeMethods.HTCLIENT) { - if (OverrideCursor != null) { + if (m.WParam == InternalHandle && ((int)m.LParam & 0x0000FFFF) == NativeMethods.HTCLIENT) + { + if (OverrideCursor != null) + { Cursor.CurrentInternal = OverrideCursor; } - else { + else + { Cursor.CurrentInternal = Cursor; } } - else { + else + { DefWndProc(ref m); } @@ -2213,20 +2552,22 @@ private void WmSetCursor(ref Message m) { // // /////////////////////////////////////////////////////////////////////////////////////////////////// - internal override Rectangle GetToolNativeScreenRectangle() { + internal override Rectangle GetToolNativeScreenRectangle() + { // Return splitter rectangle instead of the whole container rectangle to be consistent with the mouse ToolTip Rectangle containerRectangle = base.GetToolNativeScreenRectangle(); Rectangle splitterRectangle = this.SplitterRectangle; return new Rectangle(containerRectangle.X + splitterRectangle.X, containerRectangle.Y + splitterRectangle.Y, splitterRectangle.Width, splitterRectangle.Height); } - internal override void AfterControlRemoved(Control control, Control oldParent) { + internal override void AfterControlRemoved(Control control, Control oldParent) + { base.AfterControlRemoved(control, oldParent); if (control is SplitContainer && control.Dock == DockStyle.Fill) { - SetInnerMostBorder(this); + SetInnerMostBorder(this); } - + } /// @@ -2238,23 +2579,29 @@ internal override void AfterControlRemoved(Control control, Control oldParent) { /// on the form. For the arrow keys, /// !!! /// - protected override bool ProcessDialogKey(Keys keyData) { + protected override bool ProcessDialogKey(Keys keyData) + { #if DEBUG Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "ContainerControl.ProcessDialogKey [" + keyData.ToString() + "]"); #endif - if ((keyData & (Keys.Alt | Keys.Control)) == Keys.None) { + if ((keyData & (Keys.Alt | Keys.Control)) == Keys.None) + { Keys keyCode = (Keys)keyData & Keys.KeyCode; - switch (keyCode) { + switch (keyCode) + { case Keys.Tab: - if (ProcessTabKey((keyData & Keys.Shift) == Keys.None)) return true; + if (ProcessTabKey((keyData & Keys.Shift) == Keys.None)) + return true; break; case Keys.Left: case Keys.Right: case Keys.Up: case Keys.Down: - if (!splitterFocused) { + if (!splitterFocused) + { if (ProcessArrowKey(keyCode == Keys.Right || - keyCode == Keys.Down)) return true; + keyCode == Keys.Down)) + return true; } else return false; @@ -2269,37 +2616,47 @@ protected override bool ProcessDialogKey(Keys keyData) { /// This will process the TabKey for the SplitContainer. The Focus needs to Shift from controls to the Left of the Splitter /// to the splitter and then to the controls on the right of the splitter. This override implements this Logic. /// - protected override bool ProcessTabKey(bool forward) { + protected override bool ProcessTabKey(bool forward) + { //Dont Focus the Splitter if TabStop == False or if the Splitter is Fixed !! - if (!TabStop || IsSplitterFixed) { + if (!TabStop || IsSplitterFixed) + { return base.ProcessTabKey(forward); } - if (nextActiveControl != null) { + if (nextActiveControl != null) + { SetActiveControl(nextActiveControl); nextActiveControl = null; } - if (SelectNextControlInPanel(ActiveControl, forward, true, true, true)) { + if (SelectNextControlInPanel(ActiveControl, forward, true, true, true)) + { nextActiveControl = null; splitterFocused = false; return true; } - else { - if (callBaseVersion) { + else + { + if (callBaseVersion) + { callBaseVersion = false; return base.ProcessTabKey(forward); } - else { + else + { //We are om Splitter ...... splitterFocused = true; IContainerControl c = this.ParentInternal.GetContainerControl(); - if (c != null) { + if (c != null) + { ContainerControl cc = c as ContainerControl; - if (cc == null) { + if (cc == null) + { c.ActiveControl = this; } - else { + else + { cc.SetActiveControl(this); } } @@ -2309,7 +2666,8 @@ protected override bool ProcessTabKey(bool forward) { } } - protected override void OnMouseCaptureChanged(EventArgs e) { + protected override void OnMouseCaptureChanged(EventArgs e) + { base.OnMouseCaptureChanged(e); if (splitContainerMessageFilter != null) { @@ -2320,8 +2678,10 @@ protected override void OnMouseCaptureChanged(EventArgs e) { /// /// - protected override void WndProc(ref Message msg) { - switch (msg.Msg) { + protected override void WndProc(ref Message msg) + { + switch (msg.Msg) + { case Interop.WindowMessages.WM_SETCURSOR: WmSetCursor(ref msg); break; @@ -2344,7 +2704,8 @@ protected override void WndProc(ref Message msg) { /// /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override Control.ControlCollection CreateControlsInstance() { + protected override Control.ControlCollection CreateControlsInstance() + { return new SplitContainerTypedControlCollection(this, typeof(SplitterPanel), /*isReadOnly*/true); } @@ -2356,7 +2717,7 @@ protected override Control.ControlCollection CreateControlsInstance() { /////////////////////////////////////////////////////////////////////////////////////////////////// - private class SplitContainerMessageFilter : IMessageFilter + private class SplitContainerMessageFilter : IMessageFilter { private SplitContainer owner = null; @@ -2364,18 +2725,21 @@ public SplitContainerMessageFilter(SplitContainer splitContainer) { this.owner = splitContainer; } - + /// /// - bool IMessageFilter.PreFilterMessage(ref Message m) { - if (m.Msg >= Interop.WindowMessages.WM_KEYFIRST && m.Msg <= Interop.WindowMessages.WM_KEYLAST) { + bool IMessageFilter.PreFilterMessage(ref Message m) + { + if (m.Msg >= Interop.WindowMessages.WM_KEYFIRST && m.Msg <= Interop.WindowMessages.WM_KEYLAST) + { if ((m.Msg == Interop.WindowMessages.WM_KEYDOWN && (int)m.WParam == (int)Keys.Escape) - || (m.Msg == Interop.WindowMessages.WM_SYSKEYDOWN)) { + || (m.Msg == Interop.WindowMessages.WM_SYSKEYDOWN)) + { //Notify that splitMOVE was reverted .. //this is used in ONKEYUP!! owner.splitBegin = false; owner.SplitEnd(false); - owner.splitterClick = false; + owner.splitterClick = false; owner.splitterDrag = false; } return true; @@ -2384,22 +2748,27 @@ bool IMessageFilter.PreFilterMessage(ref Message m) { } } - /// - /// This control collection only allows a specific type of control - /// into the controls collection. It optionally supports readonlyness. - /// - internal class SplitContainerTypedControlCollection : WindowsFormsUtils.TypedControlCollection { + /// + /// This control collection only allows a specific type of control + /// into the controls collection. It optionally supports readonlyness. + /// + internal class SplitContainerTypedControlCollection : WindowsFormsUtils.TypedControlCollection + { SplitContainer owner; - public SplitContainerTypedControlCollection(Control c, Type type, bool isReadOnly): base(c, type, isReadOnly) + public SplitContainerTypedControlCollection(Control c, Type type, bool isReadOnly) : base(c, type, isReadOnly) { - this.owner = c as SplitContainer; + this.owner = c as SplitContainer; } - public override void Remove(Control value) { - if (value is SplitterPanel) { - if (!owner.DesignMode) { - if (IsReadOnly) throw new NotSupportedException(SR.ReadonlyControlsCollection); + public override void Remove(Control value) + { + if (value is SplitterPanel) + { + if (!owner.DesignMode) + { + if (IsReadOnly) + throw new NotSupportedException(SR.ReadonlyControlsCollection); } } base.Remove(value); @@ -2407,21 +2776,25 @@ public override void Remove(Control value) { internal override void SetChildIndexInternal(Control child, int newIndex) { - if (child is SplitterPanel) { - if (!owner.DesignMode) { - if (IsReadOnly) { - throw new NotSupportedException(SR.ReadonlyControlsCollection); - } - } - else { - // just no-op it at DT. - return; - } - } - base.SetChildIndexInternal(child, newIndex); + if (child is SplitterPanel) + { + if (!owner.DesignMode) + { + if (IsReadOnly) + { + throw new NotSupportedException(SR.ReadonlyControlsCollection); + } + } + else + { + // just no-op it at DT. + return; + } + } + base.SetChildIndexInternal(child, newIndex); } } } - } +} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Splitter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Splitter.cs index 4713a6a3592..4ed7be4c2d7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Splitter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Splitter.cs @@ -3,8 +3,9 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { - +namespace System.Windows.Forms +{ + using Microsoft.Win32; using System; using System.ComponentModel; @@ -28,7 +29,8 @@ namespace System.Windows.Forms { SRDescription(nameof(SR.DescriptionSplitter)), Designer("System.Windows.Forms.Design.SplitterDesigner, " + AssemblyRef.SystemDesign) ] - public class Splitter : Control { + public class Splitter : Control + { private const int DRAW_START = 1; private const int DRAW_MOVE = 2; private const int DRAW_END = 3; @@ -43,7 +45,7 @@ public class Splitter : Control { private int splitSize = -1; private int splitterThickness = 3; private int initTargetSize; - private int lastDrawSplit = -1; + private int lastDrawSplit = -1; private int maxSize; private static readonly object EVENT_MOVING = new object(); private static readonly object EVENT_MOVED = new object(); @@ -55,12 +57,13 @@ public class Splitter : Control { /// Creates a new Splitter. /// public Splitter() - : base() { + : base() + { SetStyle(ControlStyles.Selectable, false); TabStop = false; minSize = 25; minExtra = 25; - + Dock = DockStyle.Left; } @@ -71,21 +74,27 @@ public Splitter() /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DefaultValue(AnchorStyles.None)] - public override AnchorStyles Anchor { - get { + public override AnchorStyles Anchor + { + get + { return AnchorStyles.None; } - set { + set + { // do nothing! } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override bool AllowDrop { - get { + public override bool AllowDrop + { + get + { return base.AllowDrop; } - set { + set + { base.AllowDrop = value; } } @@ -94,15 +103,20 @@ public override bool AllowDrop { /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(defaultWidth, defaultWidth); } } - protected override Cursor DefaultCursor { - get { - switch (Dock) { + protected override Cursor DefaultCursor + { + get + { + switch (Dock) + { case DockStyle.Top: case DockStyle.Bottom: return Cursors.HSplit; @@ -115,65 +129,81 @@ protected override Cursor DefaultCursor { } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Color ForeColor { - get { + public override Color ForeColor + { + get + { return base.ForeColor; } - set { + set + { base.ForeColor = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler ForeColorChanged { + new public event EventHandler ForeColorChanged + { add => base.ForeColorChanged += value; remove => base.ForeColorChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged { + new public event EventHandler BackgroundImageChanged + { add => base.BackgroundImageChanged += value; remove => base.BackgroundImageChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { + new public event EventHandler BackgroundImageLayoutChanged + { add => base.BackgroundImageLayoutChanged += value; remove => base.BackgroundImageLayoutChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Font Font { - get { + public override Font Font + { + get + { return base.Font; } - set { + set + { base.Font = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler FontChanged { + new public event EventHandler FontChanged + { add => base.FontChanged += value; remove => base.FontChanged -= value; } @@ -188,18 +218,23 @@ public override Font Font { System.Runtime.InteropServices.DispId(NativeMethods.ActiveX.DISPID_BORDERSTYLE), SRDescription(nameof(SR.SplitterBorderStyleDescr)) ] - public BorderStyle BorderStyle { - get { + public BorderStyle BorderStyle + { + get + { return borderStyle; } - set { + set + { //valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(BorderStyle)); } - - if (borderStyle != value) { + + if (borderStyle != value) + { borderStyle = value; UpdateStyles(); } @@ -212,13 +247,16 @@ public BorderStyle BorderStyle { /// however, forget to call base.getCreateParams() first to get the struct /// filled up with the basic info. /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ExStyle &= (~NativeMethods.WS_EX_CLIENTEDGE); cp.Style &= (~NativeMethods.WS_BORDER); - switch (borderStyle) { + switch (borderStyle) + { case BorderStyle.Fixed3D: cp.ExStyle |= NativeMethods.WS_EX_CLIENTEDGE; break; @@ -229,9 +267,11 @@ protected override CreateParams CreateParams { return cp; } } - - protected override ImeMode DefaultImeMode { - get { + + protected override ImeMode DefaultImeMode + { + get + { return ImeMode.Disable; } } @@ -242,28 +282,34 @@ protected override ImeMode DefaultImeMode { Localizable(true), DefaultValue(DockStyle.Left) ] - public override DockStyle Dock { - get { return base.Dock;} + public override DockStyle Dock + { + get { return base.Dock; } + + set + { - set { - - if (!(value == DockStyle.Top || value == DockStyle.Bottom || value == DockStyle.Left || value == DockStyle.Right)) { + if (!(value == DockStyle.Top || value == DockStyle.Bottom || value == DockStyle.Left || value == DockStyle.Right)) + { throw new ArgumentException(SR.SplitterInvalidDockEnum); } - + int requestedSize = splitterThickness; - + base.Dock = value; - switch (Dock) { + switch (Dock) + { case DockStyle.Top: case DockStyle.Bottom: - if (splitterThickness != -1) { + if (splitterThickness != -1) + { Height = requestedSize; } break; case DockStyle.Left: case DockStyle.Right: - if (splitterThickness != -1) { + if (splitterThickness != -1) + { Width = requestedSize; } break; @@ -274,25 +320,31 @@ public override DockStyle Dock { /// /// Determines if the splitter is horizontal. /// - private bool Horizontal { - get { + private bool Horizontal + { + get + { DockStyle dock = Dock; return dock == DockStyle.Left || dock == DockStyle.Right; } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public ImeMode ImeMode { - get { + new public ImeMode ImeMode + { + get + { return base.ImeMode; } - set { + set + { base.ImeMode = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler ImeModeChanged { + public new event EventHandler ImeModeChanged + { add => base.ImeModeChanged += value; remove => base.ImeModeChanged -= value; } @@ -309,12 +361,16 @@ private bool Horizontal { DefaultValue(25), SRDescription(nameof(SR.SplitterMinExtraDescr)) ] - public int MinExtra { - get { + public int MinExtra + { + get + { return minExtra; } - set { - if (value < 0) value = 0; + set + { + if (value < 0) + value = 0; minExtra = value; } } @@ -330,12 +386,16 @@ public int MinExtra { DefaultValue(25), SRDescription(nameof(SR.SplitterMinSizeDescr)) ] - public int MinSize { - get { + public int MinSize + { + get + { return minSize; } - set { - if (value < 0) value = 0; + set + { + if (value < 0) + value = 0; minSize = value; } } @@ -350,32 +410,40 @@ public int MinSize { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.SplitterSplitPositionDescr)) ] - public int SplitPosition { - get { - if (splitSize == -1) splitSize = CalcSplitSize(); + public int SplitPosition + { + get + { + if (splitSize == -1) + splitSize = CalcSplitSize(); return splitSize; } - set { + set + { // calculate maxSize and other bounding conditions SplitData spd = CalcSplitBounds(); // this is not an else-if to handle the maxSize < minSize case... // ie. we give minSize priority over maxSize... - if (value > maxSize) value = maxSize; - if (value < minSize) value = minSize; + if (value > maxSize) + value = maxSize; + if (value < minSize) + value = minSize; // if (value == splitSize) return; -- do we need this check? splitSize = value; DrawSplitBar(DRAW_END); - if (spd.target == null) { + if (spd.target == null) + { splitSize = -1; return; } Rectangle bounds = spd.target.Bounds; - switch (Dock) { + switch (Dock) + { case DockStyle.Top: bounds.Height = value; break; @@ -394,85 +462,100 @@ public int SplitPosition { spd.target.Bounds = bounds; Application.DoEvents(); OnSplitterMoved(new SplitterEventArgs(Left, Top, (Left + bounds.Width / 2), (Top + bounds.Height / 2))); - + } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public bool TabStop { - get { + new public bool TabStop + { + get + { return base.TabStop; } - set { + set + { base.TabStop = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TabStopChanged { + new public event EventHandler TabStopChanged + { add => base.TabStopChanged += value; remove => base.TabStopChanged -= value; } [ - Browsable(false), EditorBrowsable(EditorBrowsableState.Never), - Bindable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never), + Bindable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public override string Text { - get { + ] + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TextChanged { + new public event EventHandler TextChanged + { add => base.TextChanged += value; remove => base.TextChanged -= value; } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler Enter { + public new event EventHandler Enter + { add => base.Enter += value; remove => base.Enter -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event KeyEventHandler KeyUp { + public new event KeyEventHandler KeyUp + { add => base.KeyUp += value; remove => base.KeyUp -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event KeyEventHandler KeyDown { + public new event KeyEventHandler KeyDown + { add => base.KeyDown += value; remove => base.KeyDown -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event KeyPressEventHandler KeyPress { + public new event KeyPressEventHandler KeyPress + { add => base.KeyPress += value; remove => base.KeyPress -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler Leave { + public new event EventHandler Leave + { add => base.Leave += value; remove => base.Leave -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.SplitterSplitterMovingDescr))] - public event SplitterEventHandler SplitterMoving { + public event SplitterEventHandler SplitterMoving + { add => Events.AddHandler(EVENT_MOVING, value); remove => Events.RemoveHandler(EVENT_MOVING, value); } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.SplitterSplitterMovedDescr))] - public event SplitterEventHandler SplitterMoved { + public event SplitterEventHandler SplitterMoved + { add => Events.AddHandler(EVENT_MOVED, value); remove => Events.RemoveHandler(EVENT_MOVED, value); } @@ -481,23 +564,29 @@ public event SplitterEventHandler SplitterMoved { /// Draws the splitter bar at the current location. Will automatically /// cleanup anyplace the splitter was drawn previously. /// - private void DrawSplitBar(int mode) { - if (mode != DRAW_START && lastDrawSplit != -1) { + private void DrawSplitBar(int mode) + { + if (mode != DRAW_START && lastDrawSplit != -1) + { DrawSplitHelper(lastDrawSplit); lastDrawSplit = -1; } // Bail if drawing with no old point... // - else if (mode != DRAW_START && lastDrawSplit == -1) { + else if (mode != DRAW_START && lastDrawSplit == -1) + { return; } - if (mode != DRAW_END) { + if (mode != DRAW_END) + { DrawSplitHelper(splitSize); lastDrawSplit = splitSize; } - else { - if (lastDrawSplit != -1) { + else + { + if (lastDrawSplit != -1) + { DrawSplitHelper(lastDrawSplit); } lastDrawSplit = -1; @@ -508,24 +597,30 @@ private void DrawSplitBar(int mode) { /// Calculates the bounding rect of the split line. minWeight refers /// to the minimum height or width of the splitline. /// - private Rectangle CalcSplitLine(int splitSize, int minWeight) { + private Rectangle CalcSplitLine(int splitSize, int minWeight) + { Rectangle r = Bounds; Rectangle bounds = splitTarget.Bounds; - switch (Dock) { + switch (Dock) + { case DockStyle.Top: - if (r.Height < minWeight) r.Height = minWeight; + if (r.Height < minWeight) + r.Height = minWeight; r.Y = bounds.Y + splitSize; break; case DockStyle.Bottom: - if (r.Height < minWeight) r.Height = minWeight; + if (r.Height < minWeight) + r.Height = minWeight; r.Y = bounds.Y + bounds.Height - splitSize - r.Height; break; case DockStyle.Left: - if (r.Width < minWeight) r.Width = minWeight; + if (r.Width < minWeight) + r.Width = minWeight; r.X = bounds.X + splitSize; break; case DockStyle.Right: - if (r.Width < minWeight) r.Width = minWeight; + if (r.Width < minWeight) + r.Width = minWeight; r.X = bounds.X + bounds.Width - splitSize - r.Width; break; } @@ -535,11 +630,14 @@ private Rectangle CalcSplitLine(int splitSize, int minWeight) { /// /// Calculates the current size of the splitter-target. /// - private int CalcSplitSize() { + private int CalcSplitSize() + { Control target = FindTarget(); - if (target == null) return -1; + if (target == null) + return -1; Rectangle r = target.Bounds; - switch (Dock) { + switch (Dock) + { case DockStyle.Top: case DockStyle.Bottom: return r.Height; @@ -554,12 +652,15 @@ private int CalcSplitSize() { /// /// Calculates the bounding criteria for the splitter. /// - private SplitData CalcSplitBounds() { + private SplitData CalcSplitBounds() + { SplitData spd = new SplitData(); Control target = FindTarget(); spd.target = target; - if (target != null) { - switch (target.Dock) { + if (target != null) + { + switch (target.Dock) + { case DockStyle.Left: case DockStyle.Right: initTargetSize = target.Bounds.Width; @@ -573,10 +674,13 @@ private SplitData CalcSplitBounds() { Control.ControlCollection children = parent.Controls; int count = children.Count; int dockWidth = 0, dockHeight = 0; - for (int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) + { Control ctl = children[i]; - if (ctl != target) { - switch (((Control)ctl).Dock) { + if (ctl != target) + { + switch (((Control)ctl).Dock) + { case DockStyle.Left: case DockStyle.Right: dockWidth += ctl.Width; @@ -589,10 +693,12 @@ private SplitData CalcSplitBounds() { } } Size clientSize = parent.ClientSize; - if (Horizontal) { + if (Horizontal) + { maxSize = clientSize.Width - dockWidth - minExtra; } - else { + else + { maxSize = clientSize.Height - dockHeight - minExtra; } spd.dockWidth = dockWidth; @@ -605,8 +711,10 @@ private SplitData CalcSplitBounds() { /// Draws the splitter line at the requested location. Should only be called /// by drawSpltBar. /// - private void DrawSplitHelper(int splitSize) { - if (splitTarget == null) { + private void DrawSplitHelper(int splitSize) + { + if (splitTarget == null) + { return; } @@ -639,27 +747,36 @@ private void RaiseSplitterEvent(object key, SplitterEventArgs spevent) { /// is docked left, the target is the control that is just to the left /// of the splitter. /// - private Control FindTarget() { + private Control FindTarget() + { Control parent = ParentInternal; - if (parent == null) return null; + if (parent == null) + return null; Control.ControlCollection children = parent.Controls; int count = children.Count; DockStyle dock = Dock; - for (int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) + { Control target = children[i]; - if (target != this) { - switch (dock) { + if (target != this) + { + switch (dock) + { case DockStyle.Top: - if (target.Bottom == Top) return(Control)target; + if (target.Bottom == Top) + return (Control)target; break; case DockStyle.Bottom: - if (target.Top == Bottom) return(Control)target; + if (target.Top == Bottom) + return (Control)target; break; case DockStyle.Left: - if (target.Right == Left) return(Control)target; + if (target.Right == Left) + return (Control)target; break; case DockStyle.Right: - if (target.Left == Right) return(Control)target; + if (target.Left == Right) + return (Control)target; break; } } @@ -670,16 +787,20 @@ private Control FindTarget() { /// /// Calculates the split size based on the mouse position (x, y). /// - private int GetSplitSize(int x, int y) { + private int GetSplitSize(int x, int y) + { int delta; - if (Horizontal) { + if (Horizontal) + { delta = x - anchor.X; } - else { + else + { delta = y - anchor.Y; } int size = 0; - switch (Dock) { + switch (Dock) + { case DockStyle.Top: size = splitTarget.Height + delta; break; @@ -695,30 +816,36 @@ private int GetSplitSize(int x, int y) { } return Math.Max(Math.Min(size, maxSize), minSize); } - + /// /// - protected override void OnKeyDown(KeyEventArgs e) { + protected override void OnKeyDown(KeyEventArgs e) + { base.OnKeyDown(e); - if (splitTarget != null && e.KeyCode == Keys.Escape) { + if (splitTarget != null && e.KeyCode == Keys.Escape) + { SplitEnd(false); } } /// /// - protected override void OnMouseDown(MouseEventArgs e) { + protected override void OnMouseDown(MouseEventArgs e) + { base.OnMouseDown(e); - if (e.Button == MouseButtons.Left && e.Clicks == 1) { + if (e.Button == MouseButtons.Left && e.Clicks == 1) + { SplitBegin(e.X, e.Y); } } /// /// - protected override void OnMouseMove(MouseEventArgs e) { + protected override void OnMouseMove(MouseEventArgs e) + { base.OnMouseMove(e); - if (splitTarget != null) { + if (splitTarget != null) + { int x = e.X + Left; int y = e.Y + Top; Rectangle r = CalcSplitLine(GetSplitSize(e.X, e.Y), 0); @@ -730,9 +857,11 @@ protected override void OnMouseMove(MouseEventArgs e) { /// /// - protected override void OnMouseUp(MouseEventArgs e) { + protected override void OnMouseUp(MouseEventArgs e) + { base.OnMouseUp(e); - if (splitTarget != null) { + if (splitTarget != null) + { int x = e.X + Left; int y = e.Y + Top; Rectangle r = CalcSplitLine(GetSplitSize(e.X, e.Y), 0); @@ -747,10 +876,13 @@ protected override void OnMouseUp(MouseEventArgs e) { /// splitterMoving event. This event occurs while the splitter is /// being moved by the user. /// - protected virtual void OnSplitterMoving(SplitterEventArgs sevent) { + protected virtual void OnSplitterMoving(SplitterEventArgs sevent) + { SplitterEventHandler handler = (SplitterEventHandler)Events[EVENT_MOVING]; - if (handler != null) handler(this,sevent); - if (splitTarget != null) { + if (handler != null) + handler(this, sevent); + if (splitTarget != null) + { SplitMove(sevent.SplitX, sevent.SplitY); } } @@ -760,25 +892,33 @@ protected virtual void OnSplitterMoving(SplitterEventArgs sevent) { /// splitterMoved event. This event occurs when the user finishes /// moving the splitter. /// - protected virtual void OnSplitterMoved(SplitterEventArgs sevent) { + protected virtual void OnSplitterMoved(SplitterEventArgs sevent) + { SplitterEventHandler handler = (SplitterEventHandler)Events[EVENT_MOVED]; - if (handler != null) handler(this,sevent); - if (splitTarget != null) { + if (handler != null) + handler(this, sevent); + if (splitTarget != null) + { SplitMove(sevent.SplitX, sevent.SplitY); } } - - protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { - if (Horizontal) { - if (width < 1) { + + protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) + { + if (Horizontal) + { + if (width < 1) + { width = 3; } splitterThickness = width; } - else { - if (height < 1) { + else + { + if (height < 1) + { height = 3; } splitterThickness = height; @@ -789,9 +929,11 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound /// /// Begins the splitter moving. /// - private void SplitBegin(int x, int y) { + private void SplitBegin(int x, int y) + { SplitData spd = CalcSplitBounds(); - if (spd.target != null && (minSize < maxSize)) { + if (spd.target != null && (minSize < maxSize)) + { anchor = new Point(x, y); splitTarget = spd.target; splitSize = GetSplitSize(x, y); @@ -810,7 +952,8 @@ private void SplitBegin(int x, int y) { /// /// Finishes the split movement. /// - private void SplitEnd(bool accept) { + private void SplitEnd(bool accept) + { DrawSplitBar(DRAW_END); splitTarget = null; CaptureInternal = false; @@ -820,10 +963,12 @@ private void SplitEnd(bool accept) { splitterMessageFilter = null; } - if (accept) { + if (accept) + { ApplySplitPosition(); } - else if (splitSize != initTargetSize) { + else if (splitSize != initTargetSize) + { SplitPosition = initTargetSize; } anchor = Point.Empty; @@ -833,17 +978,20 @@ private void SplitEnd(bool accept) { /// Sets the split position to be the current split size. This is called /// by splitEdit /// - private void ApplySplitPosition() { + private void ApplySplitPosition() + { SplitPosition = splitSize; } - + /// /// Moves the splitter line to the splitSize for the mouse position /// (x, y). /// - private void SplitMove(int x, int y) { - int size = GetSplitSize(x-Left+anchor.X, y-Top+anchor.Y); - if (splitSize != size) { + private void SplitMove(int x, int y) + { + int size = GetSplitSize(x - Left + anchor.X, y - Top + anchor.Y); + if (splitSize != size) + { splitSize = size; DrawSplitBar(DRAW_MOVE); } @@ -852,7 +1000,8 @@ private void SplitMove(int x, int y) { /// /// Returns a string representation for this control. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); return s + ", MinExtra: " + MinExtra.ToString(CultureInfo.CurrentCulture) + ", MinSize: " + MinSize.ToString(CultureInfo.CurrentCulture); @@ -861,14 +1010,15 @@ public override string ToString() { /// /// Return value holder... /// - private class SplitData { + private class SplitData + { public int dockWidth = -1; public int dockHeight = -1; internal Control target; } - private class SplitterMessageFilter : IMessageFilter + private class SplitterMessageFilter : IMessageFilter { private Splitter owner = null; @@ -876,12 +1026,15 @@ public SplitterMessageFilter(Splitter splitter) { this.owner = splitter; } - + /// /// - public bool PreFilterMessage(ref Message m) { - if (m.Msg >= Interop.WindowMessages.WM_KEYFIRST && m.Msg <= Interop.WindowMessages.WM_KEYLAST) { - if (m.Msg == Interop.WindowMessages.WM_KEYDOWN && unchecked((int)(long)m.WParam) == (int)Keys.Escape) { + public bool PreFilterMessage(ref Message m) + { + if (m.Msg >= Interop.WindowMessages.WM_KEYFIRST && m.Msg <= Interop.WindowMessages.WM_KEYLAST) + { + if (m.Msg == Interop.WindowMessages.WM_KEYDOWN && unchecked((int)(long)m.WParam) == (int)Keys.Escape) + { owner.SplitEnd(false); } return true; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SplitterCancelEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SplitterCancelEventArgs.cs index 46f4c7d2f4c..db0ad4fca4b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SplitterCancelEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SplitterCancelEventArgs.cs @@ -15,7 +15,7 @@ public class SplitterCancelEventArgs : CancelEventArgs /// Initializes an instance of the class with the specified coordinates /// of the mouse pointer and the upper-left corner of the . /// - public SplitterCancelEventArgs(int mouseCursorX, int mouseCursorY, int splitX, int splitY) : base (false) + public SplitterCancelEventArgs(int mouseCursorX, int mouseCursorY, int splitX, int splitY) : base(false) { MouseCursorX = mouseCursorX; MouseCursorY = mouseCursorY; @@ -32,7 +32,7 @@ public SplitterCancelEventArgs(int mouseCursorX, int mouseCursorY, int splitX, i /// Gets the y-coordinate of the mouse pointer (in client coordinates). /// public int MouseCursorY { get; } - + /// /// Gets the x-coordinate of the upper-left corner of the (in client coordinates). /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SplitterPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SplitterPanel.cs index fba96f7faab..89cbc42ee6e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SplitterPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SplitterPanel.cs @@ -15,45 +15,53 @@ namespace System.Windows.Forms [ToolboxItem(false)] public sealed class SplitterPanel : Panel { - SplitContainer owner = null; + SplitContainer owner = null; private bool collapsed = false; - + public SplitterPanel(SplitContainer owner) - : base() { - this.owner = owner; - SetStyle(ControlStyles.ResizeRedraw, true); - + : base() + { + this.owner = owner; + SetStyle(ControlStyles.ResizeRedraw, true); + } - internal bool Collapsed { - get { + internal bool Collapsed + { + get + { return collapsed; } - set { + set + { collapsed = value; } } - + /// /// Override AutoSize to make it hidden from the user in the designer /// [ EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) + Browsable(false) ] - public new bool AutoSize { - get { + public new bool AutoSize + { + get + { return base.AutoSize; } - set { + set + { base.AutoSize = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler AutoSizeChanged { + new public event EventHandler AutoSizeChanged + { add => base.AutoSizeChanged += value; remove => base.AutoSizeChanged -= value; } @@ -67,27 +75,33 @@ internal bool Collapsed { Browsable(false), Localizable(false) ] - public override AutoSizeMode AutoSizeMode { - get { + public override AutoSizeMode AutoSizeMode + { + get + { return AutoSizeMode.GrowOnly; } - set { + set + { } } - + /// /// Override Anchor to make it hidden from the user in the designer /// [ EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) + Browsable(false) ] - public new AnchorStyles Anchor { - get { + public new AnchorStyles Anchor + { + get + { return base.Anchor; } - set { + set + { base.Anchor = value; } } @@ -99,13 +113,16 @@ public override AutoSizeMode AutoSizeMode { [ EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) + Browsable(false) ] - public new BorderStyle BorderStyle { - get { + public new BorderStyle BorderStyle + { + get + { return base.BorderStyle; } - set { + set + { base.BorderStyle = value; } } @@ -119,13 +136,16 @@ public override AutoSizeMode AutoSizeMode { [ EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) + Browsable(false) ] - public new DockStyle Dock { - get { + public new DockStyle Dock + { + get + { return base.Dock; } - set { + set + { base.Dock = value; } } @@ -136,10 +156,12 @@ public override AutoSizeMode AutoSizeMode { [ EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) + Browsable(false) ] - new public DockPaddingEdges DockPadding { - get { + new public DockPaddingEdges DockPadding + { + get + { return base.DockPadding; } } @@ -153,23 +175,30 @@ public override AutoSizeMode AutoSizeMode { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlHeightDescr)) ] - public new int Height { - get { - if (Collapsed) { + public new int Height + { + get + { + if (Collapsed) + { return 0; } return base.Height; } - set { - throw new NotSupportedException(SR.SplitContainerPanelHeight); + set + { + throw new NotSupportedException(SR.SplitContainerPanelHeight); } } - internal int HeightInternal { - get { + internal int HeightInternal + { + get + { return ((Panel)this).Height; } - set { + set + { ((Panel)this).Height = value; } } @@ -180,13 +209,16 @@ internal int HeightInternal { [ EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) + Browsable(false) ] - public new Point Location { - get { + public new Point Location + { + get + { return base.Location; } - set { + set + { base.Location = value; } } @@ -195,8 +227,10 @@ internal int HeightInternal { /// 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. /// - protected override Padding DefaultMargin { - get { + protected override Padding DefaultMargin + { + get + { return new Padding(0, 0, 0, 0); } } @@ -208,13 +242,16 @@ protected override Padding DefaultMargin { [ EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) + Browsable(false) ] - public new Size MinimumSize { - get { + public new Size MinimumSize + { + get + { return base.MinimumSize; } - set { + set + { base.MinimumSize = value; } } @@ -226,17 +263,20 @@ protected override Padding DefaultMargin { [ EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) + Browsable(false) ] - public new Size MaximumSize { - get { + public new Size MaximumSize + { + get + { return base.MaximumSize; } - set { + set + { base.MaximumSize = value; } } - + /// /// Name of this control. The designer will set this to the same /// as the programatic Id "(name)" of the control. The name can be @@ -245,22 +285,27 @@ protected override Padding DefaultMargin { [ EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) + Browsable(false) ] - public new string Name { - get { + public new string Name + { + get + { return base.Name; } - set { + set + { base.Name = value; } } - + /// /// The parent of this control. /// - internal SplitContainer Owner { - get { + internal SplitContainer Owner + { + get + { return owner; } } @@ -271,13 +316,16 @@ internal SplitContainer Owner { [ EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) + Browsable(false) ] - public new Control Parent { - get { + public new Control Parent + { + get + { return base.Parent; } - set { + set + { base.Parent = value; } } @@ -288,16 +336,20 @@ internal SplitContainer Owner { [ EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) + Browsable(false) ] - public new Size Size { - get { - if (Collapsed) { + public new Size Size + { + get + { + if (Collapsed) + { return Size.Empty; } return base.Size; } - set { + set + { base.Size = value; } } @@ -308,13 +360,16 @@ internal SplitContainer Owner { [ EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) + Browsable(false) ] - public new int TabIndex { - get { + public new int TabIndex + { + get + { return base.TabIndex; } - set { + set + { base.TabIndex = value; } } @@ -326,13 +381,16 @@ internal SplitContainer Owner { [ EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) + Browsable(false) ] - public new bool TabStop { - get { + public new bool TabStop + { + get + { return base.TabStop; } - set { + set + { base.TabStop = value; } } @@ -343,13 +401,16 @@ internal SplitContainer Owner { [ EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) + Browsable(false) ] - public new bool Visible { - get { + public new bool Visible + { + get + { return base.Visible; } - set { + set + { base.Visible = value; } } @@ -363,23 +424,30 @@ internal SplitContainer Owner { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlWidthDescr)) ] - public new int Width { - get { - if (Collapsed) { + public new int Width + { + get + { + if (Collapsed) + { return 0; } return base.Width; } - set { + set + { throw new NotSupportedException(SR.SplitContainerPanelWidth); } } - internal int WidthInternal { - get { + internal int WidthInternal + { + get + { return ((Panel)this).Width; } - set { + set + { ((Panel)this).Width = value; } } @@ -390,9 +458,10 @@ internal int WidthInternal { [ EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) + Browsable(false) ] - public new event EventHandler VisibleChanged { + public new event EventHandler VisibleChanged + { add => base.VisibleChanged += value; remove => base.VisibleChanged -= value; } @@ -403,9 +472,10 @@ internal int WidthInternal { [ EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) + Browsable(false) ] - public new event EventHandler DockChanged { + public new event EventHandler DockChanged + { add => base.DockChanged += value; remove => base.DockChanged -= value; } @@ -416,9 +486,10 @@ internal int WidthInternal { [ EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) + Browsable(false) ] - public new event EventHandler LocationChanged { + public new event EventHandler LocationChanged + { add => base.LocationChanged += value; remove => base.LocationChanged -= value; } @@ -429,12 +500,13 @@ internal int WidthInternal { [ EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) + Browsable(false) ] - public new event EventHandler TabIndexChanged { + public new event EventHandler TabIndexChanged + { add => base.TabIndexChanged += value; remove => base.TabIndexChanged -= value; - } + } /// /// Override TabStopChanged to make it hidden from the user in the designer @@ -442,9 +514,10 @@ internal int WidthInternal { [ EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) + Browsable(false) ] - public new event EventHandler TabStopChanged { + public new event EventHandler TabStopChanged + { add => base.TabStopChanged += value; remove => base.TabStopChanged -= value; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs index 91e375c7668..2b5be175eea 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.ComponentModel; @@ -28,7 +29,8 @@ namespace System.Windows.Forms { DefaultProperty(nameof(Text)), Designer("System.Windows.Forms.Design.StatusBarDesigner, " + AssemblyRef.SystemDesign), ] - public class StatusBar : Control { + public class StatusBar : Control + { private int sizeGripWidth = 0; private const int SIMPLE_INDEX = 0xFF; @@ -36,15 +38,15 @@ public class StatusBar : Control { private static readonly object EVENT_PANELCLICK = new object(); private static readonly object EVENT_SBDRAWITEM = new object(); - private bool showPanels; - private bool layoutDirty; - private int panelsRealized; - private bool sizeGrip = true; - private string simpleText; - private Point lastClick = new Point(0, 0); - private IList panels = new ArrayList(); - private StatusBarPanelCollection panelsCollection; - private ControlToolTip tooltips; + private bool showPanels; + private bool layoutDirty; + private int panelsRealized; + private bool sizeGrip = true; + private string simpleText; + private Point lastClick = new Point(0, 0); + private IList panels = new ArrayList(); + private StatusBarPanelCollection panelsCollection; + private ControlToolTip tooltips; private ToolTip mainToolTip = null; private bool toolTipSet = false; @@ -55,7 +57,8 @@ public class StatusBar : Control { /// /// public StatusBar() - : base() { + : base() + { base.SetStyle(ControlStyles.UserPaint | ControlStyles.Selectable, false); Dock = DockStyle.Bottom; @@ -67,14 +70,19 @@ public StatusBar() /// /// A VisualStyleRenderer we can use to get information about the current UI theme /// - private static VisualStyleRenderer VisualStyleRenderer { - get { - if (VisualStyleRenderer.IsSupported) { - if (renderer == null) { + private static VisualStyleRenderer VisualStyleRenderer + { + get + { + if (VisualStyleRenderer.IsSupported) + { + if (renderer == null) + { renderer = new VisualStyleRenderer(VisualStyleElement.ToolBar.Button.Normal); } } - else { + else + { renderer = null; } return renderer; @@ -82,10 +90,14 @@ private static VisualStyleRenderer VisualStyleRenderer { } - private int SizeGripWidth { - get { - if (sizeGripWidth == 0) { - if (Application.RenderWithVisualStyles && VisualStyleRenderer != null){ + private int SizeGripWidth + { + get + { + if (sizeGripWidth == 0) + { + if (Application.RenderWithVisualStyles && VisualStyleRenderer != null) + { // Need to build up accurate gripper width to avoid cutting off other panes. VisualStyleRenderer vsRenderer = VisualStyleRenderer; VisualStyleElement thisElement; @@ -106,7 +118,8 @@ private int SizeGripWidth { // Either GetPartSize could have returned a width of zero, so make sure we have a reasonable number: sizeGripWidth = Math.Max(sizeGripWidth, 16); } - else { + else + { sizeGripWidth = 16; } } @@ -121,19 +134,23 @@ private int SizeGripWidth { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Color BackColor { - get { + public override Color BackColor + { + get + { // not supported, always return CONTROL return SystemColors.Control; } - set { + set + { // no op, not supported. } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackColorChanged { + new public event EventHandler BackColorChanged + { add => base.BackColorChanged += value; remove => base.BackColorChanged -= value; } @@ -146,33 +163,41 @@ public override Color BackColor { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged { + new public event EventHandler BackgroundImageChanged + { add => base.BackgroundImageChanged += value; remove => base.BackgroundImageChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { + new public event EventHandler BackgroundImageLayoutChanged + { add => base.BackgroundImageLayoutChanged += value; remove => base.BackgroundImageLayoutChanged -= value; } @@ -183,15 +208,19 @@ public override ImageLayout BackgroundImageLayout { /// Inheriting classes should call base.getCreateParams in the manor below: /// /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ClassName = NativeMethods.WC_STATUSBAR; - if (this.sizeGrip) { + if (this.sizeGrip) + { cp.Style |= NativeMethods.SBARS_SIZEGRIP; } - else { + else + { cp.Style &= (~NativeMethods.SBARS_SIZEGRIP); } cp.Style |= NativeMethods.CCS_NOPARENTALIGN | NativeMethods.CCS_NORESIZE; @@ -200,8 +229,10 @@ protected override CreateParams CreateParams { } } - protected override ImeMode DefaultImeMode { - get { + protected override ImeMode DefaultImeMode + { + get + { return ImeMode.Disable; } } @@ -210,8 +241,10 @@ protected override ImeMode DefaultImeMode { /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(100, 22); } } @@ -221,11 +254,14 @@ protected override Size DefaultSize { /// on controls that are based on Win32 Native Controls. /// [EditorBrowsable(EditorBrowsableState.Never)] - protected override bool DoubleBuffered { - get { + protected override bool DoubleBuffered + { + get + { return base.DoubleBuffered; } - set { + set + { base.DoubleBuffered = value; } } @@ -239,11 +275,14 @@ protected override bool DoubleBuffered { Localizable(true), DefaultValue(DockStyle.Bottom) ] - public override DockStyle Dock { - get { + public override DockStyle Dock + { + get + { return base.Dock; } - set { + set + { base.Dock = value; } } @@ -258,9 +297,11 @@ public override DockStyle Dock { [ Localizable(true) ] - public override Font Font { - get { return base.Font;} - set { + public override Font Font + { + get { return base.Font; } + set + { base.Font = value; SetPanelContentsWidths(false); } @@ -273,33 +314,41 @@ public override Font Font { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Color ForeColor { - get { + public override Color ForeColor + { + get + { return base.ForeColor; } - set { + set + { base.ForeColor = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler ForeColorChanged { + new public event EventHandler ForeColorChanged + { add => base.ForeColorChanged += value; remove => base.ForeColorChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public ImeMode ImeMode { - get { + new public ImeMode ImeMode + { + get + { return base.ImeMode; } - set { + set + { base.ImeMode = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler ImeModeChanged { + public new event EventHandler ImeModeChanged + { add => base.ImeModeChanged += value; remove => base.ImeModeChanged -= value; } @@ -318,9 +367,12 @@ public override Color ForeColor { SRCategory(nameof(SR.CatAppearance)), MergableProperty(false) ] - public StatusBarPanelCollection Panels { - get { - if (panelsCollection == null) { + public StatusBarPanelCollection Panels + { + get + { + if (panelsCollection == null) + { panelsCollection = new StatusBarPanelCollection(this); } @@ -336,18 +388,24 @@ public StatusBarPanelCollection Panels { [ Localizable(true) ] - public override string Text { - get { - if (simpleText == null) { + public override string Text + { + get + { + if (simpleText == null) + { return ""; } - else { + else + { return simpleText; } } - set { + set + { SetSimpleText(value); - if (simpleText != value) { + if (simpleText != value) + { simpleText = value; OnTextChanged(EventArgs.Empty); } @@ -374,26 +432,34 @@ private IntPtr ToolTipHandle { DefaultValue(false), SRDescription(nameof(SR.StatusBarShowPanelsDescr)) ] - public bool ShowPanels { - get { + public bool ShowPanels + { + get + { return showPanels; } - set { - if (showPanels != value) { + set + { + if (showPanels != value) + { showPanels = value; layoutDirty = true; - if (IsHandleCreated) { + if (IsHandleCreated) + { int bShowPanels = (!showPanels) ? 1 : 0; SendMessage(NativeMethods.SB_SIMPLE, bShowPanels, 0); - if (showPanels) { + if (showPanels) + { PerformLayout(); RealizePanels(); } - else if (tooltips != null) { - for (int i=0; i /// [DefaultValue(false)] - new public bool TabStop { - get { + new public bool TabStop + { + get + { return base.TabStop; } - set { + set + { base.TabStop = value; } } - internal bool ToolTipSet { - get { + internal bool ToolTipSet + { + get + { return toolTipSet; } } - internal ToolTip MainToolTip { - get { + internal ToolTip MainToolTip + { + get + { return mainToolTip; } } @@ -462,7 +539,8 @@ internal ToolTip MainToolTip { /// /// [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.StatusBarDrawItem))] - public event StatusBarDrawItemEventHandler DrawItem { + public event StatusBarDrawItemEventHandler DrawItem + { add => Events.AddHandler(EVENT_SBDRAWITEM, value); remove => Events.RemoveHandler(EVENT_SBDRAWITEM, value); } @@ -473,7 +551,8 @@ public event StatusBarDrawItemEventHandler DrawItem { /// /// [SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.StatusBarOnPanelClickDescr))] - public event StatusBarPanelClickEventHandler PanelClick { + public event StatusBarPanelClickEventHandler PanelClick + { add => Events.AddHandler(EVENT_PANELCLICK, value); remove => Events.RemoveHandler(EVENT_PANELCLICK, value); } @@ -483,7 +562,8 @@ public event StatusBarPanelClickEventHandler PanelClick { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event PaintEventHandler Paint { + public new event PaintEventHandler Paint + { add => base.Paint += value; remove => base.Paint -= value; } @@ -491,34 +571,39 @@ public event StatusBarPanelClickEventHandler PanelClick { /// /// Tells whether the panels have been realized. /// - internal bool ArePanelsRealized() { + internal bool ArePanelsRealized() + { return this.showPanels && IsHandleCreated; } /// /// - internal void DirtyLayout() { + internal void DirtyLayout() + { layoutDirty = true; } /// /// Makes the panel according to the sizes in the panel list. /// - private void ApplyPanelWidths() { + private void ApplyPanelWidths() + { // This forces handle creation every time any time the StatusBar // has to be re-laidout. // if (!IsHandleCreated) return; - StatusBarPanel panel = null; + StatusBarPanel panel = null; int length = this.panels.Count; - if (length == 0) { + if (length == 0) + { Size sz = Size; int[] offsets = new int[1]; offsets[0] = sz.Width; - if (sizeGrip) { + if (sizeGrip) + { offsets[0] -= SizeGripWidth; } UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.SB_SETPARTS, 1, offsets); @@ -529,8 +614,9 @@ private void ApplyPanelWidths() { int[] offsets2 = new int[length]; int currentOffset = 0; - for (int i = 0; i < length; i++) { - panel = (StatusBarPanel) this.panels[i]; + for (int i = 0; i < length; i++) + { + panel = (StatusBarPanel)this.panels[i]; currentOffset += panel.Width; offsets2[i] = currentOffset; panel.Right = offsets2[i]; @@ -539,8 +625,9 @@ private void ApplyPanelWidths() { // Tooltip setup... // - for (int i=0; i /// - protected override void CreateHandle() { - if (!RecreatingHandle) { + protected override void CreateHandle() + { + if (!RecreatingHandle) + { IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); - - try { + + try + { NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); icc.dwICC = NativeMethods.ICC_BAR_CLASSES; SafeNativeMethods.InitCommonControlsEx(icc); } - finally { + finally + { UnsafeNativeMethods.ThemingScope.Deactivate(userCookie); } } - + base.CreateHandle(); } /// /// Disposes this control /// - protected override void Dispose(bool disposing) { - if (disposing) { - if (panelsCollection != null) { + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (panelsCollection != null) + { StatusBarPanel[] panelCopy = new StatusBarPanel[panelsCollection.Count]; ((ICollection)panelsCollection).CopyTo(panelCopy, 0); panelsCollection.Clear(); - foreach(StatusBarPanel p in panelCopy) { + foreach (StatusBarPanel p in panelCopy) + { p.Dispose(); } } @@ -587,8 +682,10 @@ protected override void Dispose(bool disposing) { /// /// Forces the panels to be updated, location, repainting, etc. /// - private void ForcePanelUpdate() { - if (ArePanelsRealized()) { + private void ForcePanelUpdate() + { + if (ArePanelsRealized()) + { layoutDirty = true; SetPanelContentsWidths(true); PerformLayout(); @@ -602,17 +699,21 @@ private void ForcePanelUpdate() { /// event. /// /// - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { base.OnHandleCreated(e); - if (!DesignMode) { + if (!DesignMode) + { tooltips = new ControlToolTip(this); } - if (!this.showPanels) { + if (!this.showPanels) + { SendMessage(NativeMethods.SB_SIMPLE, 1, 0); SetSimpleText(simpleText); } - else { + else + { ForcePanelUpdate(); } } @@ -622,9 +723,11 @@ protected override void OnHandleCreated(EventArgs e) { /// Raises the event. /// /// - protected override void OnHandleDestroyed(EventArgs e) { + protected override void OnHandleDestroyed(EventArgs e) + { base.OnHandleDestroyed(e); - if (tooltips != null) { + if (tooltips != null) + { tooltips.Dispose(); tooltips = null; } @@ -660,7 +763,8 @@ public bool Callback(IntPtr hWnd, IntPtr lparam) { /// Raises the event. /// /// - protected override void OnMouseDown(MouseEventArgs e) { + protected override void OnMouseDown(MouseEventArgs e) + { lastClick.X = e.X; lastClick.Y = e.Y; base.OnMouseDown(e); @@ -671,9 +775,11 @@ protected override void OnMouseDown(MouseEventArgs e) { /// Raises the event. /// /// - protected virtual void OnPanelClick(StatusBarPanelClickEventArgs e) { + protected virtual void OnPanelClick(StatusBarPanelClickEventArgs e) + { StatusBarPanelClickEventHandler handler = (StatusBarPanelClickEventHandler)Events[EVENT_PANELCLICK]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// @@ -681,10 +787,13 @@ protected virtual void OnPanelClick(StatusBarPanelClickEventArgs e) { /// Raises the Layout event. /// /// - protected override void OnLayout(LayoutEventArgs levent) { - if (this.showPanels) { + protected override void OnLayout(LayoutEventArgs levent) + { + if (this.showPanels) + { LayoutPanels(); - if (IsHandleCreated && panelsRealized != panels.Count) { + if (IsHandleCreated && panelsRealized != panels.Count) + { RealizePanels(); } } @@ -695,28 +804,34 @@ protected override void OnLayout(LayoutEventArgs levent) { /// This function sets up all the panel on the status bar according to /// the internal this.panels List. /// - internal void RealizePanels() { - StatusBarPanel panel = null; - int length = this.panels.Count; - int old = panelsRealized; + internal void RealizePanels() + { + StatusBarPanel panel = null; + int length = this.panels.Count; + int old = panelsRealized; panelsRealized = 0; - if (length == 0) { + if (length == 0) + { SendMessage(NativeMethods.SB_SETTEXT, 0, ""); } int i; - for (i = 0; i < length; i++) { - panel = (StatusBarPanel) this.panels[i]; - try { + for (i = 0; i < length; i++) + { + panel = (StatusBarPanel)this.panels[i]; + try + { panel.Realize(); panelsRealized++; } - catch { + catch + { } } - for (; i /// Remove the internal list of panels without updating the control. /// - internal void RemoveAllPanelsWithoutUpdate() { + internal void RemoveAllPanelsWithoutUpdate() + { int size = this.panels.Count; // remove the parent reference - for (int i = 0; i < size; i++) { - StatusBarPanel sbp = (StatusBarPanel) this.panels[i]; + for (int i = 0; i < size; i++) + { + StatusBarPanel sbp = (StatusBarPanel)this.panels[i]; sbp.ParentInternal = null; } this.panels.Clear(); - if (this.showPanels == true) { + if (this.showPanels == true) + { ApplyPanelWidths(); ForcePanelUpdate(); } @@ -744,30 +862,38 @@ internal void RemoveAllPanelsWithoutUpdate() { /// Sets the widths of any panels that have the /// StatusBarPanelAutoSize.CONTENTS property set. /// - internal void SetPanelContentsWidths(bool newPanels) { + internal void SetPanelContentsWidths(bool newPanels) + { int size = panels.Count; bool changed = false; - for (int i = 0; i < size; i++) { - StatusBarPanel sbp = (StatusBarPanel) panels[i]; - if (sbp.AutoSize == StatusBarPanelAutoSize.Contents) { + for (int i = 0; i < size; i++) + { + StatusBarPanel sbp = (StatusBarPanel)panels[i]; + if (sbp.AutoSize == StatusBarPanelAutoSize.Contents) + { int newWidth = sbp.GetContentsWidth(newPanels); - if (sbp.Width != newWidth) { + if (sbp.Width != newWidth) + { sbp.Width = newWidth; changed = true; } } } - if (changed) { + if (changed) + { DirtyLayout(); PerformLayout(); } } - private void SetSimpleText(string simpleText) { - if (!showPanels && IsHandleCreated) { + private void SetSimpleText(string simpleText) + { + if (!showPanels && IsHandleCreated) + { int wparam = SIMPLE_INDEX + NativeMethods.SBT_NOBORDERS; - if (RightToLeft == RightToLeft.Yes) { + if (RightToLeft == RightToLeft.Yes) + { wparam |= NativeMethods.SBT_RTLREADING; } @@ -779,16 +905,19 @@ private void SetSimpleText(string simpleText) { /// Sizes the the panels appropriately. It looks at the SPRING AutoSize /// property. /// - private void LayoutPanels() { - StatusBarPanel panel = null; - int barPanelWidth = 0; - int springNum = 0; - StatusBarPanel[] pArray = new StatusBarPanel[this.panels.Count]; - bool changed = false; - - for (int i = 0; i < pArray.Length; i++) { - panel = (StatusBarPanel) this.panels[i]; - if (panel.AutoSize == StatusBarPanelAutoSize.Spring) { + private void LayoutPanels() + { + StatusBarPanel panel = null; + int barPanelWidth = 0; + int springNum = 0; + StatusBarPanel[] pArray = new StatusBarPanel[this.panels.Count]; + bool changed = false; + + for (int i = 0; i < pArray.Length; i++) + { + panel = (StatusBarPanel)this.panels[i]; + if (panel.AutoSize == StatusBarPanelAutoSize.Spring) + { pArray[springNum] = panel; springNum++; } @@ -797,37 +926,45 @@ private void LayoutPanels() { } - if (springNum > 0) { + if (springNum > 0) + { Rectangle rect = Bounds; int springPanelsLeft = springNum; int leftoverWidth = rect.Width - barPanelWidth; - if (sizeGrip) { + if (sizeGrip) + { leftoverWidth -= SizeGripWidth; } int copyOfLeftoverWidth = unchecked((int)0x80000000); - while (springPanelsLeft > 0) { + while (springPanelsLeft > 0) + { int widthOfSpringPanel = (leftoverWidth) / springPanelsLeft; if (leftoverWidth == copyOfLeftoverWidth) break; copyOfLeftoverWidth = leftoverWidth; - for (int i = 0; i < springNum; i++) { + for (int i = 0; i < springNum; i++) + { panel = pArray[i]; if (panel == null) continue; - if (widthOfSpringPanel < panel.MinWidth) { - if (panel.Width != panel.MinWidth) { + if (widthOfSpringPanel < panel.MinWidth) + { + if (panel.Width != panel.MinWidth) + { changed = true; } panel.Width = panel.MinWidth; pArray[i] = null; - springPanelsLeft --; + springPanelsLeft--; leftoverWidth -= panel.MinWidth; } - else { - if (panel.Width != widthOfSpringPanel) { + else + { + if (panel.Width != widthOfSpringPanel) + { changed = true; } panel.Width = widthOfSpringPanel; @@ -836,7 +973,8 @@ private void LayoutPanels() { } } - if (changed || layoutDirty) { + if (changed || layoutDirty) + { ApplyPanelWidths(); } } @@ -847,9 +985,11 @@ private void LayoutPanels() { /// event. /// /// - protected virtual void OnDrawItem(StatusBarDrawItemEventArgs sbdievent) { + protected virtual void OnDrawItem(StatusBarDrawItemEventArgs sbdievent) + { StatusBarDrawItemEventHandler handler = (StatusBarDrawItemEventHandler)Events[EVENT_SBDRAWITEM]; - if (handler != null) handler(this,sbdievent); + if (handler != null) + handler(this, sbdievent); } /// @@ -858,7 +998,8 @@ protected virtual void OnDrawItem(StatusBarDrawItemEventArgs sbdievent) { /// event. /// /// - protected override void OnResize(EventArgs e) { + protected override void OnResize(EventArgs e) + { Invalidate(); base.OnResize(e); } @@ -868,10 +1009,12 @@ protected override void OnResize(EventArgs e) { /// Returns a string representation for this control. /// /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); - if (Panels != null) { + if (Panels != null) + { s += ", Panels.Count: " + Panels.Count.ToString(CultureInfo.CurrentCulture); if (Panels.Count > 0) s += ", Panels[0]: " + Panels[0].ToString(); @@ -880,42 +1023,52 @@ public override string ToString() { } //call this when System.Windows.forms.toolTip is Associated with Statusbar.... - internal void SetToolTip(ToolTip t) { + internal void SetToolTip(ToolTip t) + { this.mainToolTip = t; toolTipSet = true; } - internal void UpdateTooltip(StatusBarPanel panel) { - if (tooltips == null) { - if (IsHandleCreated && !DesignMode) { + internal void UpdateTooltip(StatusBarPanel panel) + { + if (tooltips == null) + { + if (IsHandleCreated && !DesignMode) + { //This shouldn't happen: tooltips should've already been set. The best we can //do here is reset it. tooltips = new ControlToolTip(this); } - else { + else + { return; } } - if (panel.Parent == this && panel.ToolTipText.Length > 0) { + if (panel.Parent == this && panel.ToolTipText.Length > 0) + { int border = SystemInformation.Border3DSize.Width; ControlToolTip.Tool t = tooltips.GetTool(panel); - if (t == null) { + if (t == null) + { t = new ControlToolTip.Tool(); } t.text = panel.ToolTipText; - t.rect = new Rectangle(panel.Right-panel.Width + border, 0, panel.Width - border, Height); + t.rect = new Rectangle(panel.Right - panel.Width + border, 0, panel.Width - border, Height); tooltips.SetTool(panel, t); } - else { + else + { tooltips.SetTool(panel, null); } } - private void UpdatePanelIndex() { + private void UpdatePanelIndex() + { int length = panels.Count; - for (int i=0; i /// Processes messages for ownerdraw panels. /// - private void WmDrawItem(ref Message m) { + private void WmDrawItem(ref Message m) + { NativeMethods.DRAWITEMSTRUCT dis = (NativeMethods.DRAWITEMSTRUCT)m.GetLParam(typeof(NativeMethods.DRAWITEMSTRUCT)); int length = this.panels.Count; @@ -943,28 +1097,34 @@ private void WmDrawItem(ref Message m) { /// /// - private void WmNotifyNMClick(NativeMethods.NMHDR note) { + private void WmNotifyNMClick(NativeMethods.NMHDR note) + { - if (!showPanels) { + if (!showPanels) + { return; } int size = panels.Count; int currentOffset = 0; int index = -1; - for (int i = 0; i < size; i++) { - StatusBarPanel panel = (StatusBarPanel) panels[i]; + for (int i = 0; i < size; i++) + { + StatusBarPanel panel = (StatusBarPanel)panels[i]; currentOffset += panel.Width; - if (lastClick.X < currentOffset) { + if (lastClick.X < currentOffset) + { // this is where the mouse was clicked. index = i; break; } } - if (index != -1) { + if (index != -1) + { MouseButtons button = MouseButtons.Left; int clicks = 0; - switch (note.code) { + switch (note.code) + { case NativeMethods.NM_CLICK: button = MouseButtons.Left; clicks = 1; @@ -984,7 +1144,7 @@ private void WmNotifyNMClick(NativeMethods.NMHDR note) { } Point pt = lastClick; - StatusBarPanel panel = (StatusBarPanel) panels[index]; + StatusBarPanel panel = (StatusBarPanel)panels[index]; StatusBarPanelClickEventArgs sbpce = new StatusBarPanelClickEventArgs(panel, button, clicks, pt.X, pt.Y); @@ -992,7 +1152,8 @@ private void WmNotifyNMClick(NativeMethods.NMHDR note) { } } - private void WmNCHitTest(ref Message m) { + private void WmNCHitTest(ref Message m) + { int x = NativeMethods.Util.LOWORD(m.LParam); Rectangle bounds = Bounds; bool callSuper = true; @@ -1003,29 +1164,37 @@ private void WmNCHitTest(ref Message m) { // : to prevent that we provide a little bit a sanity to only // : allow resizing, when it would resize the form. // - if (x > bounds.X + bounds.Width - SizeGripWidth) { + if (x > bounds.X + bounds.Width - SizeGripWidth) + { Control parent = ParentInternal; - if (parent != null && parent is Form) { + if (parent != null && parent is Form) + { FormBorderStyle bs = ((Form)parent).FormBorderStyle; if (bs != FormBorderStyle.Sizable - && bs != FormBorderStyle.SizableToolWindow) { + && bs != FormBorderStyle.SizableToolWindow) + { callSuper = false; } if (!((Form)parent).TopLevel - || Dock != DockStyle.Bottom) { + || Dock != DockStyle.Bottom) + { callSuper = false; } - if (callSuper) { + if (callSuper) + { Control.ControlCollection children = parent.Controls; int c = children.Count; - for (int i=0; i Top) { + if (ctl != this && ctl.Dock == DockStyle.Bottom) + { + if (ctl.Top > Top) + { callSuper = false; break; } @@ -1033,15 +1202,18 @@ private void WmNCHitTest(ref Message m) { } } } - else { + else + { callSuper = false; } } - if (callSuper) { + if (callSuper) + { base.WndProc(ref m); } - else { + else + { m.Result = (IntPtr)NativeMethods.HTCLIENT; } } @@ -1053,8 +1225,10 @@ private void WmNCHitTest(ref Message m) { /// for any messages that they don't handle. /// /// - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { case Interop.WindowMessages.WM_NCHITTEST: WmNCHitTest(ref m); break; @@ -1064,7 +1238,8 @@ protected override void WndProc(ref Message m) { case Interop.WindowMessages.WM_NOTIFY: case Interop.WindowMessages.WM_NOTIFY + Interop.WindowMessages.WM_REFLECT: NativeMethods.NMHDR note = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR)); - switch (note.code) { + switch (note.code) + { case NativeMethods.NM_CLICK: case NativeMethods.NM_RCLICK: case NativeMethods.NM_DBLCLK: @@ -1092,7 +1267,8 @@ protected override void WndProc(ref Message m) { [ ListBindable(false) ] - public class StatusBarPanelCollection : IList { + public class StatusBarPanelCollection : IList + { private StatusBar owner; /// A caching mechanism for key accessor /// We use an index here rather than control so that we don't have lifetime @@ -1105,58 +1281,70 @@ public class StatusBarPanelCollection : IList { /// Constructor for the StatusBarPanelCollection class /// /// - public StatusBarPanelCollection(StatusBar owner) { + public StatusBarPanelCollection(StatusBar owner) + { this.owner = owner; } /// /// This method will return an individual StatusBarPanel with the appropriate index. /// - public virtual StatusBarPanel this[int index] { - get { - return(StatusBarPanel)owner.panels[index]; + public virtual StatusBarPanel this[int index] + { + get + { + return (StatusBarPanel)owner.panels[index]; } - set { + set + { if (value == null) throw new ArgumentNullException(nameof(StatusBarPanel)); owner.layoutDirty = true; - if (value.Parent != null) { + if (value.Parent != null) + { throw new ArgumentException(SR.ObjectHasParent, "value"); } int length = owner.panels.Count; - if (index < 0|| index >= length) + if (index < 0 || index >= length) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); - StatusBarPanel oldPanel = (StatusBarPanel) owner.panels[index]; + StatusBarPanel oldPanel = (StatusBarPanel)owner.panels[index]; oldPanel.ParentInternal = null; value.ParentInternal = owner; - if (value.AutoSize == StatusBarPanelAutoSize.Contents) { + if (value.AutoSize == StatusBarPanelAutoSize.Contents) + { value.Width = value.GetContentsWidth(true); } owner.panels[index] = value; value.Index = index; - if (owner.ArePanelsRealized()) { + if (owner.ArePanelsRealized()) + { owner.PerformLayout(); value.Realize(); } } } - object IList.this[int index] { - get { + object IList.this[int index] + { + get + { return this[index]; } - set { - if (value is StatusBarPanel) { + set + { + if (value is StatusBarPanel) + { this[index] = (StatusBarPanel)value; } - else { + else + { throw new ArgumentException(SR.StatusBarBadStatusBarPanel, "value"); } } @@ -1164,19 +1352,24 @@ object IList.this[int index] { /// /// Retrieves the child control with the specified key. /// - public virtual StatusBarPanel this[string key] { - get { + public virtual StatusBarPanel this[string key] + { + get + { // We do not support null and empty string as valid keys. - if (string.IsNullOrEmpty(key)){ + if (string.IsNullOrEmpty(key)) + { return null; } // Search for the key in our collection int index = IndexOfKey(key); - if (IsValidIndex(index)) { + if (IsValidIndex(index)) + { return this[index]; } - else { + else + { return null; } @@ -1190,32 +1383,42 @@ public virtual StatusBarPanel this[string key] { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public int Count { - get { + public int Count + { + get + { return owner.panels.Count; } } - object ICollection.SyncRoot { - get { + object ICollection.SyncRoot + { + get + { return this; } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return false; } } - bool IList.IsFixedSize { - get { + bool IList.IsFixedSize + { + get + { return false; } } - public bool IsReadOnly { - get { + public bool IsReadOnly + { + get + { return false; } } @@ -1225,7 +1428,8 @@ public bool IsReadOnly { /// Adds a StatusBarPanel to the collection. /// /// - public virtual StatusBarPanel Add(string text) { + public virtual StatusBarPanel Add(string text) + { StatusBarPanel panel = new StatusBarPanel(); panel.Text = text; Add(panel); @@ -1237,39 +1441,50 @@ public virtual StatusBarPanel Add(string text) { /// Adds a StatusBarPanel to the collection. /// /// - public virtual int Add(StatusBarPanel value) { + public virtual int Add(StatusBarPanel value) + { int index = owner.panels.Count; Insert(index, value); return index; } - int IList.Add(object value) { - if (value is StatusBarPanel) { + int IList.Add(object value) + { + if (value is StatusBarPanel) + { return Add((StatusBarPanel)value); } - else { + else + { throw new ArgumentException(SR.StatusBarBadStatusBarPanel, "value"); } } - public virtual void AddRange(StatusBarPanel[] panels) { - if (panels == null) { + public virtual void AddRange(StatusBarPanel[] panels) + { + if (panels == null) + { throw new ArgumentNullException(nameof(panels)); } - foreach(StatusBarPanel panel in panels) { + foreach (StatusBarPanel panel in panels) + { Add(panel); } } - public bool Contains(StatusBarPanel panel) { + public bool Contains(StatusBarPanel panel) + { return IndexOf(panel) != -1; } - bool IList.Contains(object panel) { - if (panel is StatusBarPanel) { + bool IList.Contains(object panel) + { + if (panel is StatusBarPanel) + { return Contains((StatusBarPanel)panel); } - else { + else + { return false; } } @@ -1277,49 +1492,61 @@ bool IList.Contains(object panel) { /// /// Returns true if the collection contains an item with the specified key, false otherwise. /// - public virtual bool ContainsKey(string key) { - return IsValidIndex(IndexOfKey(key)); + public virtual bool ContainsKey(string key) + { + return IsValidIndex(IndexOfKey(key)); } - public int IndexOf(StatusBarPanel panel) { - for(int index=0; index < Count; ++index) { - if (this[index] == panel) { + public int IndexOf(StatusBarPanel panel) + { + for (int index = 0; index < Count; ++index) + { + if (this[index] == panel) + { return index; } } return -1; } - int IList.IndexOf(object panel) { - if (panel is StatusBarPanel) { + int IList.IndexOf(object panel) + { + if (panel is StatusBarPanel) + { return IndexOf((StatusBarPanel)panel); } - else { + else + { return -1; } } - /// - /// The zero-based index of the first occurrence of value within the entire CollectionBase, if found; otherwise, -1. - /// - public virtual int IndexOfKey(string key) { - // Step 0 - Arg validation - if (string.IsNullOrEmpty(key)){ - return -1; // we dont support empty or null keys. - } + /// + /// The zero-based index of the first occurrence of value within the entire CollectionBase, if found; otherwise, -1. + /// + public virtual int IndexOfKey(string key) + { + // Step 0 - Arg validation + if (string.IsNullOrEmpty(key)) + { + return -1; // we dont support empty or null keys. + } // step 1 - check the last cached item if (IsValidIndex(lastAccessedIndex)) { - if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) { + if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) + { return lastAccessedIndex; } } // step 2 - search for the item - for (int i = 0; i < this.Count; i ++) { - if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { + for (int i = 0; i < this.Count; i++) + { + if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) + { lastAccessedIndex = i; return i; } @@ -1328,7 +1555,7 @@ public virtual int IndexOfKey(string key) { // step 3 - we didn't find it. Invalidate the last accessed index and return -1. lastAccessedIndex = -1; return -1; - } + } /// @@ -1336,7 +1563,8 @@ public virtual int IndexOfKey(string key) { /// Inserts a StatusBarPanel in the collection. /// /// - public virtual void Insert(int index, StatusBarPanel value) { + public virtual void Insert(int index, StatusBarPanel value) + { //check for the value not to be null if (value == null) @@ -1354,7 +1582,8 @@ public virtual void Insert(int index, StatusBarPanel value) { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); value.ParentInternal = owner; - switch (value.AutoSize) { + switch (value.AutoSize) + { case StatusBarPanelAutoSize.None: case StatusBarPanelAutoSize.Spring: break; @@ -1369,20 +1598,24 @@ public virtual void Insert(int index, StatusBarPanel value) { owner.ForcePanelUpdate(); } - void IList.Insert(int index, object value) { - if (value is StatusBarPanel) { + void IList.Insert(int index, object value) + { + if (value is StatusBarPanel) + { Insert(index, (StatusBarPanel)value); } - else { + else + { throw new ArgumentException(SR.StatusBarBadStatusBarPanel, "value"); } } - /// - /// Determines if the index is valid for the collection. - /// - private bool IsValidIndex(int index) { - return ((index >= 0) && (index < this.Count)); + /// + /// Determines if the index is valid for the collection. + /// + private bool IsValidIndex(int index) + { + return ((index >= 0) && (index < this.Count)); } /// @@ -1390,7 +1623,8 @@ private bool IsValidIndex(int index) { /// Removes all the StatusBarPanels in the collection. /// /// - public virtual void Clear() { + public virtual void Clear() + { owner.RemoveAllPanelsWithoutUpdate(); owner.PerformLayout(); @@ -1401,21 +1635,25 @@ public virtual void Clear() { /// Removes an individual StatusBarPanel in the collection. /// /// - public virtual void Remove(StatusBarPanel value) { + public virtual void Remove(StatusBarPanel value) + { //check for the value not to be null if (value == null) throw new ArgumentNullException(nameof(StatusBarPanel)); //end check - if (value.Parent != owner) { + if (value.Parent != owner) + { return; } RemoveAt(value.Index); } - void IList.Remove(object value) { - if (value is StatusBarPanel) { + void IList.Remove(object value) + { + if (value is StatusBarPanel) + { Remove((StatusBarPanel)value); } } @@ -1426,7 +1664,8 @@ void IList.Remove(object value) { /// Removes an individual StatusBarPanel in the collection at the given index. /// /// - public virtual void RemoveAt(int index) { + public virtual void RemoveAt(int index) + { int length = Count; if (index < 0 || index >= length) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); @@ -1450,14 +1689,17 @@ public virtual void RemoveAt(int index) { /// /// Removes the child control with the specified key. /// - public virtual void RemoveByKey(string key) { + public virtual void RemoveByKey(string key) + { int index = IndexOfKey(key); - if (IsValidIndex(index)) { + if (IsValidIndex(index)) + { RemoveAt(index); - } - } + } + } - void ICollection.CopyTo(Array dest, int index) { + void ICollection.CopyTo(Array dest, int index) + { owner.panels.CopyTo(dest, index); } @@ -1466,11 +1708,14 @@ void ICollection.CopyTo(Array dest, int index) { /// Returns the Enumerator for this collection. /// /// - public IEnumerator GetEnumerator() { - if (owner.panels != null) { + public IEnumerator GetEnumerator() + { + if (owner.panels != null) + { return owner.panels.GetEnumerator(); } - else { + else + { return new StatusBarPanel[0].GetEnumerator(); } } @@ -1484,23 +1729,26 @@ public IEnumerator GetEnumerator() { /// this control binds to rectangular regions, instead of /// full controls. /// - private class ControlToolTip { + private class ControlToolTip + { - public class Tool { + public class Tool + { public Rectangle rect = Rectangle.Empty; public string text; internal IntPtr id = new IntPtr(-1); } - private Hashtable tools = new Hashtable(); + private Hashtable tools = new Hashtable(); private ToolTipNativeWindow window = null; - private Control parent = null; - private int nextId = 0; + private Control parent = null; + private int nextId = 0; /// /// Creates a new ControlToolTip. /// - public ControlToolTip(Control parent) { + public ControlToolTip(Control parent) + { window = new ToolTipNativeWindow(this); this.parent = parent; } @@ -1508,8 +1756,10 @@ public ControlToolTip(Control parent) { /// /// Returns the createParams to create the window. /// - protected CreateParams CreateParams { - get { + protected CreateParams CreateParams + { + get + { NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); icc.dwICC = NativeMethods.ICC_TAB_CLASSES; SafeNativeMethods.InitCommonControlsEx(icc); @@ -1525,20 +1775,25 @@ protected CreateParams CreateParams { /// /// - public IntPtr Handle { - get { - if (window.Handle == IntPtr.Zero) { + public IntPtr Handle + { + get + { + if (window.Handle == IntPtr.Zero) + { CreateHandle(); } return window.Handle; } } - private bool IsHandleCreated { - get { return window.Handle != IntPtr.Zero;} + private bool IsHandleCreated + { + get { return window.Handle != IntPtr.Zero; } } - private void AssignId(Tool tool) { + private void AssignId(Tool tool) + { tool.id = (IntPtr)nextId; nextId++; } @@ -1554,43 +1809,54 @@ private void AssignId(Tool tool) { /// tool parameter will result in the tool /// region being removed. /// - public void SetTool(object key, Tool tool) { + public void SetTool(object key, Tool tool) + { bool remove = false; bool add = false; bool update = false; Tool toRemove = null; - if (tools.ContainsKey(key)) { + if (tools.ContainsKey(key)) + { toRemove = (Tool)tools[key]; } - if (toRemove != null) { + if (toRemove != null) + { remove = true; } - if (tool != null) { + if (tool != null) + { add = true; } if (tool != null && toRemove != null - && tool.id == toRemove.id) { + && tool.id == toRemove.id) + { update = true; } - if (update) { + if (update) + { UpdateTool(tool); } - else { - if (remove) { + else + { + if (remove) + { RemoveTool(toRemove); } - if (add) { + if (add) + { AddTool(tool); } } - if (tool != null) { + if (tool != null) + { tools[key] = tool; } - else { + else + { tools.Remove(key); } @@ -1600,34 +1866,44 @@ public void SetTool(object key, Tool tool) { /// Returns the tool associated with the specified key, /// or null if there is no area. /// - public Tool GetTool(object key) { - return(Tool)tools[key]; + public Tool GetTool(object key) + { + return (Tool)tools[key]; } - private void AddTool(Tool tool) { - if (tool != null && tool.text != null && tool.text.Length > 0) { + private void AddTool(Tool tool) + { + if (tool != null && tool.text != null && tool.text.Length > 0) + { int ret; StatusBar p = (StatusBar)parent; - if (p.ToolTipSet) { + if (p.ToolTipSet) + { ret = (int)UnsafeNativeMethods.SendMessage(new HandleRef(p.MainToolTip, p.MainToolTip.Handle), NativeMethods.TTM_ADDTOOL, 0, GetTOOLINFO(tool)); } - else { + else + { ret = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_ADDTOOL, 0, GetTOOLINFO(tool)); } - if (ret == 0) { + if (ret == 0) + { throw new InvalidOperationException(SR.StatusBarAddFailed); } } } - private void RemoveTool(Tool tool) { - if (tool != null && tool.text != null && tool.text.Length > 0 && (int)tool.id >= 0) { + private void RemoveTool(Tool tool) + { + if (tool != null && tool.text != null && tool.text.Length > 0 && (int)tool.id >= 0) + { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_DELTOOL, 0, GetMinTOOLINFO(tool)); } } - private void UpdateTool(Tool tool) { - if (tool != null && tool.text != null && tool.text.Length > 0 && (int)tool.id >= 0) { + private void UpdateTool(Tool tool) + { + if (tool != null && tool.text != null && tool.text.Length > 0 && (int)tool.id >= 0) + { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_SETTOOLINFO, 0, GetTOOLINFO(tool)); } } @@ -1636,8 +1912,10 @@ private void UpdateTool(Tool tool) { /// /// Creates the handle for the control. /// - protected void CreateHandle() { - if (IsHandleCreated) { + protected void CreateHandle() + { + if (IsHandleCreated) + { return; } @@ -1656,8 +1934,10 @@ protected void CreateHandle() { /// /// Destroys the handle for this control. /// - protected void DestroyHandle() { - if (IsHandleCreated) { + protected void DestroyHandle() + { + if (IsHandleCreated) + { window.DestroyHandle(); tools.Clear(); } @@ -1668,7 +1948,8 @@ protected void DestroyHandle() { /// This method removes the component from its container (if the component has a site) /// and triggers the dispose event. /// - public void Dispose() { + public void Dispose() + { DestroyHandle(); } @@ -1677,18 +1958,22 @@ public void Dispose() { /// required data to uniquely identify a region. This is used primarily /// for delete operations. NOTE: This cannot force the creation of a handle. /// - private NativeMethods.TOOLINFO_T GetMinTOOLINFO(Tool tool) { + private NativeMethods.TOOLINFO_T GetMinTOOLINFO(Tool tool) + { NativeMethods.TOOLINFO_T ti = new NativeMethods.TOOLINFO_T(); ti.cbSize = Marshal.SizeOf(); ti.hwnd = parent.Handle; - if ((int)tool.id < 0) { + if ((int)tool.id < 0) + { AssignId(tool); } StatusBar p = (StatusBar)parent; - if (p != null && p.ToolTipSet) { - ti.uId = parent.Handle; + if (p != null && p.ToolTipSet) + { + ti.uId = parent.Handle; } - else { + else + { ti.uId = tool.id; } return ti; @@ -1698,7 +1983,8 @@ private NativeMethods.TOOLINFO_T GetMinTOOLINFO(Tool tool) { /// Returns a detailed TOOLINFO_T structure that represents the specified /// region. NOTE: This may force the creation of a handle. /// - private NativeMethods.TOOLINFO_T GetTOOLINFO(Tool tool) { + private NativeMethods.TOOLINFO_T GetTOOLINFO(Tool tool) + { NativeMethods.TOOLINFO_T ti = GetMinTOOLINFO(tool); ti.cbSize = Marshal.SizeOf(); ti.uFlags |= NativeMethods.TTF_TRANSPARENT | NativeMethods.TTF_SUBCLASS; @@ -1706,7 +1992,8 @@ private NativeMethods.TOOLINFO_T GetTOOLINFO(Tool tool) { // RightToLeft reading order // Control richParent = parent; - if (richParent != null && richParent.RightToLeft == RightToLeft.Yes) { + if (richParent != null && richParent.RightToLeft == RightToLeft.Yes) + { ti.uFlags |= NativeMethods.TTF_RTLREADING; } @@ -1718,7 +2005,8 @@ private NativeMethods.TOOLINFO_T GetTOOLINFO(Tool tool) { /// /// - ~ControlToolTip() { + ~ControlToolTip() + { DestroyHandle(); } @@ -1726,8 +2014,10 @@ private NativeMethods.TOOLINFO_T GetTOOLINFO(Tool tool) { /// WNDPROC /// - protected void WndProc(ref Message msg) { - switch (msg.Msg) { + protected void WndProc(ref Message msg) + { + switch (msg.Msg) + { case Interop.WindowMessages.WM_SETFOCUS: // @@ -1742,15 +2032,19 @@ protected void WndProc(ref Message msg) { /// /// - private class ToolTipNativeWindow : NativeWindow { + private class ToolTipNativeWindow : NativeWindow + { ControlToolTip control; - internal ToolTipNativeWindow(ControlToolTip control) { + internal ToolTipNativeWindow(ControlToolTip control) + { this.control = control; } - protected override void WndProc(ref Message m) { - if (control != null) { + protected override void WndProc(ref Message m) + { + if (control != null) + { control.WndProc(ref m); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/StatusBarPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/StatusBarPanel.cs index 5e0963af4b8..62449f78cfa 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/StatusBarPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/StatusBarPanel.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.ComponentModel; @@ -27,29 +28,30 @@ namespace System.Windows.Forms { DesignTimeVisible(false), DefaultProperty(nameof(Text)) ] - public class StatusBarPanel : Component, ISupportInitialize { + public class StatusBarPanel : Component, ISupportInitialize + { private const int DEFAULTWIDTH = 100; private const int DEFAULTMINWIDTH = 10; private const int PANELTEXTINSET = 3; private const int PANELGAP = 2; - private string text = string.Empty; - private string name = string.Empty; - private string toolTipText = string.Empty; - private Icon icon = null; + private string text = string.Empty; + private string name = string.Empty; + private string toolTipText = string.Empty; + private Icon icon = null; - private HorizontalAlignment alignment = HorizontalAlignment.Left; - private System.Windows.Forms.StatusBarPanelBorderStyle borderStyle = System.Windows.Forms.StatusBarPanelBorderStyle.Sunken; - private StatusBarPanelStyle style = StatusBarPanelStyle.Text; + private HorizontalAlignment alignment = HorizontalAlignment.Left; + private System.Windows.Forms.StatusBarPanelBorderStyle borderStyle = System.Windows.Forms.StatusBarPanelBorderStyle.Sunken; + private StatusBarPanelStyle style = StatusBarPanelStyle.Text; // these are package scope so the parent can get at them. // - private StatusBar parent = null; - private int width = DEFAULTWIDTH; - private int right = 0; - private int minWidth = DEFAULTMINWIDTH; - private int index = 0; + private StatusBar parent = null; + private int width = DEFAULTWIDTH; + private int right = 0; + private int minWidth = DEFAULTMINWIDTH; + private int index = 0; private StatusBarPanelAutoSize autoSize = StatusBarPanelAutoSize.None; private bool initializing = false; @@ -61,7 +63,8 @@ public class StatusBarPanel : Component, ISupportInitialize { /// Initializes a new default instance of the class. /// /// - public StatusBarPanel() { + public StatusBarPanel() + { } /// @@ -77,17 +80,22 @@ public StatusBarPanel() { Localizable(true), SRDescription(nameof(SR.StatusBarPanelAlignmentDescr)) ] - public HorizontalAlignment Alignment { - get { + public HorizontalAlignment Alignment + { + get + { return alignment; } - set { + set + { //valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)HorizontalAlignment.Left, (int)HorizontalAlignment.Center)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)HorizontalAlignment.Left, (int)HorizontalAlignment.Center)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(HorizontalAlignment)); } - if (alignment != value) { + if (alignment != value) + { alignment = value; Realize(); } @@ -107,17 +115,22 @@ public HorizontalAlignment Alignment { RefreshProperties(RefreshProperties.All), SRDescription(nameof(SR.StatusBarPanelAutoSizeDescr)) ] - public StatusBarPanelAutoSize AutoSize { - get { + public StatusBarPanelAutoSize AutoSize + { + get + { return this.autoSize; } - set { + set + { //valid values are 0x1 to 0x3 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)StatusBarPanelAutoSize.None, (int)StatusBarPanelAutoSize.Contents)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)StatusBarPanelAutoSize.None, (int)StatusBarPanelAutoSize.Contents)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(StatusBarPanelAutoSize)); } - if (this.autoSize != value) { + if (this.autoSize != value) + { this.autoSize = value; UpdateSize(); } @@ -139,17 +152,22 @@ public StatusBarPanelAutoSize AutoSize { DispId(NativeMethods.ActiveX.DISPID_BORDERSTYLE), SRDescription(nameof(SR.StatusBarPanelBorderStyleDescr)) ] - public StatusBarPanelBorderStyle BorderStyle { - get { + public StatusBarPanelBorderStyle BorderStyle + { + get + { return borderStyle; } - set { + set + { //valid values are 0x1 to 0x3 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)StatusBarPanelBorderStyle.None, (int)StatusBarPanelBorderStyle.Sunken)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)StatusBarPanelBorderStyle.None, (int)StatusBarPanelBorderStyle.Sunken)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(StatusBarPanelBorderStyle)); } - if (this.borderStyle != value) { + if (this.borderStyle != value) + { this.borderStyle = value; Realize(); if (Created) @@ -160,8 +178,10 @@ public StatusBarPanelBorderStyle BorderStyle { /// /// - internal bool Created { - get { + internal bool Created + { + get + { return this.parent != null && this.parent.ArePanelsRealized(); } } @@ -179,30 +199,37 @@ internal bool Created { Localizable(true), SRDescription(nameof(SR.StatusBarPanelIconDescr)) ] - public Icon Icon { - - get { + public Icon Icon + { + + get + { // unfortunately we have no way of getting the icon from the control. return this.icon; } - - - set { - if (value != null && (((Icon)value).Height > SystemInformation.SmallIconSize.Height || ((Icon)value).Width > SystemInformation.SmallIconSize.Width)) { - this.icon = new Icon(value, SystemInformation.SmallIconSize); + + set + { + + if (value != null && (((Icon)value).Height > SystemInformation.SmallIconSize.Height || ((Icon)value).Width > SystemInformation.SmallIconSize.Width)) + { + this.icon = new Icon(value, SystemInformation.SmallIconSize); } - else { + else + { this.icon = value; } - if (Created) { + if (Created) + { IntPtr handle = (this.icon == null) ? IntPtr.Zero : this.icon.Handle; this.parent.SendMessage(NativeMethods.SB_SETICON, (IntPtr)GetIndex(), handle); } UpdateSize(); - if (Created) { + if (Created) + { this.parent.Invalidate(); } } @@ -238,20 +265,26 @@ internal int Index RefreshProperties(RefreshProperties.All), SRDescription(nameof(SR.StatusBarPanelMinWidthDescr)) ] - public int MinWidth { - get { + public int MinWidth + { + get + { return this.minWidth; } - set { - if (value < 0) { + set + { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(MinWidth), value, 0)); } - if (value != this.minWidth) { + if (value != this.minWidth) + { this.minWidth = value; UpdateSize(); - if (this.minWidth > this.Width) { + if (this.minWidth > this.Width) + { Width = value; } } @@ -263,18 +296,22 @@ public int MinWidth { /// Gets or sets the name of the panel. /// /// - [ - SRCategory(nameof(SR.CatAppearance)), - Localizable(true), - SRDescription(nameof(SR.StatusBarPanelNameDescr)) - ] - public string Name { - get { + [ + SRCategory(nameof(SR.CatAppearance)), + Localizable(true), + SRDescription(nameof(SR.StatusBarPanelNameDescr)) + ] + public string Name + { + get + { return WindowsFormsUtils.GetComponentName(this, name); } - set { + set + { name = value; - if(Site!= null) { + if (Site != null) + { Site.Name = name; } } @@ -289,8 +326,10 @@ public string Name { /// /// [Browsable(false)] - public StatusBar Parent { - get { + public StatusBar Parent + { + get + { return parent; } } @@ -336,17 +375,22 @@ internal int Right DefaultValue(StatusBarPanelStyle.Text), SRDescription(nameof(SR.StatusBarPanelStyleDescr)) ] - public StatusBarPanelStyle Style { - get { return style;} - set { + public StatusBarPanelStyle Style + { + get { return style; } + set + { //valid values are 0x1 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)StatusBarPanelStyle.Text, (int)StatusBarPanelStyle.OwnerDraw)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)StatusBarPanelStyle.Text, (int)StatusBarPanelStyle.OwnerDraw)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(StatusBarPanelStyle)); } - if (this.style != value) { + if (this.style != value) + { this.style = value; Realize(); - if (Created) { + if (Created) + { this.parent.Invalidate(); } } @@ -361,11 +405,14 @@ public StatusBarPanelStyle Style { DefaultValue(null), TypeConverter(typeof(StringConverter)), ] - public object Tag { - get { + public object Tag + { + get + { return userData; } - set { + set + { userData = value; } } @@ -381,26 +428,35 @@ public object Tag { DefaultValue(""), SRDescription(nameof(SR.StatusBarPanelTextDescr)) ] - public string Text { - get { - if (text == null) { + public string Text + { + get + { + if (text == null) + { return ""; } - else { + else + { return text; } } - set { - if (value == null) { + set + { + if (value == null) + { value = string.Empty; } - if (!Text.Equals(value)) { + if (!Text.Equals(value)) + { - if (value.Length == 0) { + if (value.Length == 0) + { this.text = null; } - else { + else + { this.text = value; } Realize(); @@ -421,30 +477,40 @@ public string Text { DefaultValue(""), SRDescription(nameof(SR.StatusBarPanelToolTipTextDescr)) ] - public string ToolTipText { - get { - if (this.toolTipText == null) { + public string ToolTipText + { + get + { + if (this.toolTipText == null) + { return ""; } - else { + else + { return this.toolTipText; } } - set { - if (value == null) { + set + { + if (value == null) + { value = string.Empty; } - if (!ToolTipText.Equals(value)) { + if (!ToolTipText.Equals(value)) + { - if (value.Length == 0) { + if (value.Length == 0) + { this.toolTipText = null; } - else { + else + { this.toolTipText = value; } - if (Created) { + if (Created) + { parent.UpdateTooltip(this); } } @@ -464,11 +530,14 @@ public string ToolTipText { DefaultValue(DEFAULTWIDTH), SRDescription(nameof(SR.StatusBarPanelWidthDescr)) ] - public int Width { - get { + public int Width + { + get + { return this.width; } - set { + set + { if (!initializing && value < this.minWidth) throw new ArgumentOutOfRangeException(nameof(Width), SR.WidthGreaterThanMinWidth); @@ -480,17 +549,22 @@ public int Width { /// /// Handles tasks required when the control is being initialized. /// - public void BeginInit() { + public void BeginInit() + { initializing = true; } /// /// - protected override void Dispose(bool disposing) { - if (disposing) { - if (parent != null) { + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (parent != null) + { int index = GetIndex(); - if (index != -1) { + if (index != -1) + { parent.Panels.RemoveAt(index); } } @@ -501,10 +575,12 @@ protected override void Dispose(bool disposing) { /// /// Called when initialization of the control is complete. /// - public void EndInit() { + public void EndInit() + { initializing = false; - if (Width < MinWidth) { + if (Width < MinWidth) + { Width = MinWidth; } } @@ -512,9 +588,11 @@ public void EndInit() { /// /// Gets the width of the contents of the panel /// - internal int GetContentsWidth(bool newPanel) { + internal int GetContentsWidth(bool newPanel) + { string text; - if (newPanel) { + if (newPanel) + { if (this.text == null) text = string.Empty; else @@ -525,12 +603,13 @@ internal int GetContentsWidth(bool newPanel) { Graphics g = this.parent.CreateGraphicsInternal(); Size sz = Size.Ceiling(g.MeasureString(text, parent.Font)); - if (this.icon != null) { + if (this.icon != null) + { sz.Width += this.icon.Size.Width + 5; } g.Dispose(); - int width = sz.Width + SystemInformation.BorderSize.Width*2 + PANELTEXTINSET*2 + PANELGAP; + int width = sz.Width + SystemInformation.BorderSize.Width * 2 + PANELTEXTINSET * 2 + PANELGAP; return Math.Max(width, minWidth); } @@ -538,31 +617,38 @@ internal int GetContentsWidth(bool newPanel) { /// Returns the index of the panel by making the parent control search /// for it within its list. /// - private int GetIndex() { + private int GetIndex() + { return index; } /// /// Sets all the properties for this panel. /// - internal void Realize() { - if (Created) { + internal void Realize() + { + if (Created) + { string text; - string sendText; - int border = 0; + string sendText; + int border = 0; - if (this.text == null) { + if (this.text == null) + { text = string.Empty; } - else { + else + { text = this.text; } HorizontalAlignment align = alignment; // Translate the alignment for Rtl apps // - if (parent.RightToLeft == RightToLeft.Yes) { - switch (align) { + if (parent.RightToLeft == RightToLeft.Yes) + { + switch (align) + { case HorizontalAlignment.Left: align = HorizontalAlignment.Right; break; @@ -572,7 +658,8 @@ internal void Realize() { } } - switch (align) { + switch (align) + { case HorizontalAlignment.Center: sendText = "\t" + text; break; @@ -583,7 +670,8 @@ internal void Realize() { sendText = text; break; } - switch (borderStyle) { + switch (borderStyle) + { case StatusBarPanelBorderStyle.None: border |= NativeMethods.SBT_NOBORDERS; break; @@ -593,7 +681,8 @@ internal void Realize() { border |= NativeMethods.SBT_POPOUT; break; } - switch (style) { + switch (style) + { case StatusBarPanelStyle.Text: break; case StatusBarPanelStyle.OwnerDraw: @@ -603,52 +692,65 @@ internal void Realize() { int wparam = GetIndex() | border; - if (parent.RightToLeft == RightToLeft.Yes) { + if (parent.RightToLeft == RightToLeft.Yes) + { wparam |= NativeMethods.SBT_RTLREADING; } - int result = (int) UnsafeNativeMethods.SendMessage(new HandleRef(parent, parent.Handle), NativeMethods.SB_SETTEXT, (IntPtr)wparam, sendText); + int result = (int)UnsafeNativeMethods.SendMessage(new HandleRef(parent, parent.Handle), NativeMethods.SB_SETTEXT, (IntPtr)wparam, sendText); if (result == 0) throw new InvalidOperationException(SR.UnableToSetPanelText); - if (this.icon != null && style != StatusBarPanelStyle.OwnerDraw) { + if (this.icon != null && style != StatusBarPanelStyle.OwnerDraw) + { this.parent.SendMessage(NativeMethods.SB_SETICON, (IntPtr)GetIndex(), this.icon.Handle); } - else { + else + { this.parent.SendMessage(NativeMethods.SB_SETICON, (IntPtr)GetIndex(), IntPtr.Zero); } - if (style == StatusBarPanelStyle.OwnerDraw) { + if (style == StatusBarPanelStyle.OwnerDraw) + { NativeMethods.RECT rect = new NativeMethods.RECT(); - result = (int) UnsafeNativeMethods.SendMessage(new HandleRef(parent, parent.Handle), NativeMethods.SB_GETRECT, (IntPtr)GetIndex(), ref rect); + result = (int)UnsafeNativeMethods.SendMessage(new HandleRef(parent, parent.Handle), NativeMethods.SB_GETRECT, (IntPtr)GetIndex(), ref rect); - if (result != 0) { + if (result != 0) + { this.parent.Invalidate(Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom)); } } } } - private void UpdateSize() { - if (this.autoSize == StatusBarPanelAutoSize.Contents) { + private void UpdateSize() + { + if (this.autoSize == StatusBarPanelAutoSize.Contents) + { ApplyContentSizing(); } - else { - if (Created) { + else + { + if (Created) + { parent.DirtyLayout(); parent.PerformLayout(); } } } - private void ApplyContentSizing() { + private void ApplyContentSizing() + { if (this.autoSize == StatusBarPanelAutoSize.Contents && - parent != null) { + parent != null) + { int newWidth = GetContentsWidth(false); - if (newWidth != this.Width) { + if (newWidth != this.Width) + { this.Width = newWidth; - if (Created) { + if (Created) + { parent.DirtyLayout(); parent.PerformLayout(); } @@ -662,7 +764,8 @@ private void ApplyContentSizing() { /// panel. /// /// - public override string ToString() { + public override string ToString() + { return "StatusBarPanel: {" + Text + "}"; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/StatusBarPanelClickEventHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/StatusBarPanelClickEventHandler.cs index 6d0b8bebf2b..b9521119bb4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/StatusBarPanelClickEventHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/StatusBarPanelClickEventHandler.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/StatusStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/StatusStrip.cs index 6b5eb001aa2..ef0b0c2f348 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/StatusStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/StatusStrip.cs @@ -2,38 +2,41 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; - using System.Collections.Specialized; + using System.Collections.Specialized; using System.Runtime.InteropServices; using System.Windows.Forms.Layout; - + [ComVisible(true), ClassInterface(ClassInterfaceType.AutoDispatch), SRDescription(nameof(SR.DescriptionStatusStrip)) ] - public class StatusStrip : ToolStrip { + public class StatusStrip : ToolStrip + { private const AnchorStyles AllAnchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom | AnchorStyles.Top; private const AnchorStyles HorizontalAnchor = AnchorStyles.Left | AnchorStyles.Right; private const AnchorStyles VerticalAnchor = AnchorStyles.Top | AnchorStyles.Bottom; - private BitVector32 state = new BitVector32(); + private BitVector32 state = new BitVector32(); + + private static readonly int stateSizingGrip = BitVector32.CreateMask(); + private static readonly int stateCalledSpringTableLayout = BitVector32.CreateMask(stateSizingGrip); - private static readonly int stateSizingGrip = BitVector32.CreateMask(); - private static readonly int stateCalledSpringTableLayout = BitVector32.CreateMask(stateSizingGrip); - private const int gripWidth = 12; private RightToLeftLayoutGrip rtlLayoutGrip; private Orientation lastOrientation = Orientation.Horizontal; - - public StatusStrip() { + + public StatusStrip() + { SuspendLayout(); this.CanOverflow = false; this.LayoutStyle = ToolStripLayoutStyle.Table; @@ -44,7 +47,7 @@ public StatusStrip() { this.Stretch = true; state[stateSizingGrip] = true; ResumeLayout(true); - + } [ @@ -53,79 +56,101 @@ public StatusStrip() { SRCategory(nameof(SR.CatLayout)), Browsable(false) ] - public new bool CanOverflow { - get { - return base.CanOverflow; + public new bool CanOverflow + { + get + { + return base.CanOverflow; } - set { + set + { base.CanOverflow = value; } } - protected override bool DefaultShowItemToolTips { - get { + protected override bool DefaultShowItemToolTips + { + get + { return false; } } - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(200, 22); } } - - protected override Padding DefaultPadding { - get { - if (Orientation == Orientation.Horizontal) { - if (RightToLeft == RightToLeft.No) { + + protected override Padding DefaultPadding + { + get + { + if (Orientation == Orientation.Horizontal) + { + if (RightToLeft == RightToLeft.No) + { return new Padding(1, 0, 14, 0); } - else { - return new Padding(14, 0, 1, 0); + else + { + return new Padding(14, 0, 1, 0); } } - else { + else + { // vertical // the difference in symmetry here is that the grip does not actually rotate, it remains the same height it // was before, so the DisplayRectangle needs to shrink up by its height. return new Padding(1, 3, 1, DefaultSize.Height); } - + } } - protected override DockStyle DefaultDock { - get { - return DockStyle.Bottom; - } + protected override DockStyle DefaultDock + { + get + { + return DockStyle.Bottom; + } } - - [DefaultValue(DockStyle.Bottom)] - public override DockStyle Dock { - get { - return base.Dock; - } - set { - base.Dock = value; - } - } + + [DefaultValue(DockStyle.Bottom)] + public override DockStyle Dock + { + get + { + return base.Dock; + } + set + { + base.Dock = value; + } + } [DefaultValue(ToolStripGripStyle.Hidden)] - public new ToolStripGripStyle GripStyle { - get { - return base.GripStyle; + public new ToolStripGripStyle GripStyle + { + get + { + return base.GripStyle; } - set { - base.GripStyle = value; + set + { + base.GripStyle = value; } } [DefaultValue(ToolStripLayoutStyle.Table)] - public new ToolStripLayoutStyle LayoutStyle { + public new ToolStripLayoutStyle LayoutStyle + { get { return base.LayoutStyle; } set { base.LayoutStyle = value; } } @@ -133,515 +158,622 @@ public override DockStyle Dock { // we do some custom stuff with padding to accomodate size grip. // changing this is not supported at DT [Browsable(false)] - public new Padding Padding { - get { + public new Padding Padding + { + get + { return base.Padding; } - set { + set + { base.Padding = value; } } [Browsable(false)] - public new event EventHandler PaddingChanged { + public new event EventHandler PaddingChanged + { add => base.PaddingChanged += value; remove => base.PaddingChanged -= value; } - - private Control RTLGrip { - get{ - if (rtlLayoutGrip == null) { - rtlLayoutGrip = new RightToLeftLayoutGrip(); - } - return rtlLayoutGrip; - } - } - - - [DefaultValue(false)] - [SRDescription(nameof(SR.ToolStripShowItemToolTipsDescr))] - [SRCategory(nameof(SR.CatBehavior))] - public new bool ShowItemToolTips { - get { + + private Control RTLGrip + { + get + { + if (rtlLayoutGrip == null) + { + rtlLayoutGrip = new RightToLeftLayoutGrip(); + } + return rtlLayoutGrip; + } + } + + + [DefaultValue(false)] + [SRDescription(nameof(SR.ToolStripShowItemToolTipsDescr))] + [SRCategory(nameof(SR.CatBehavior))] + public new bool ShowItemToolTips + { + get + { return base.ShowItemToolTips; - } - set { + } + set + { base.ShowItemToolTips = value; } - } + } - // return whether we should paint the sizing grip. - private bool ShowSizingGrip { - get{ - if (SizingGrip && IsHandleCreated) { - if (DesignMode) { + // return whether we should paint the sizing grip. + private bool ShowSizingGrip + { + get + { + if (SizingGrip && IsHandleCreated) + { + if (DesignMode) + { return true; // we dont care about the state of VS. } - else { + else + { HandleRef rootHwnd = WindowsFormsUtils.GetRootHWnd(this); - if (rootHwnd.Handle != IntPtr.Zero) { - return !UnsafeNativeMethods.IsZoomed(rootHwnd); + if (rootHwnd.Handle != IntPtr.Zero) + { + return !UnsafeNativeMethods.IsZoomed(rootHwnd); } } } return false; } - } - [ - SRCategory(nameof(SR.CatAppearance)), - DefaultValue(true), - SRDescription(nameof(SR.StatusStripSizingGripDescr)) - ] - public bool SizingGrip { - get { - return state[stateSizingGrip]; - } - set { - if (value != state[stateSizingGrip]) { - state[stateSizingGrip] = value; - EnsureRightToLeftGrip(); - Invalidate(true); - } - } - } - - [Browsable(false)] - public Rectangle SizeGripBounds { - get { - if (SizingGrip) { + } + [ + SRCategory(nameof(SR.CatAppearance)), + DefaultValue(true), + SRDescription(nameof(SR.StatusStripSizingGripDescr)) + ] + public bool SizingGrip + { + get + { + return state[stateSizingGrip]; + } + set + { + if (value != state[stateSizingGrip]) + { + state[stateSizingGrip] = value; + EnsureRightToLeftGrip(); + Invalidate(true); + } + } + } + + [Browsable(false)] + public Rectangle SizeGripBounds + { + get + { + if (SizingGrip) + { Size statusStripSize = this.Size; // we cant necessarily make this the height of the status strip, as // the orientation could change. int gripHeight = Math.Min(DefaultSize.Height, statusStripSize.Height); - - if (RightToLeft == RightToLeft.Yes) { + + if (RightToLeft == RightToLeft.Yes) + { return new Rectangle(0, statusStripSize.Height - gripHeight, gripWidth, gripHeight); } - else { + else + { return new Rectangle(statusStripSize.Width - gripWidth, statusStripSize.Height - gripHeight, gripWidth, gripHeight); } } return Rectangle.Empty; } - } - - - [DefaultValue(true)] - [SRCategory(nameof(SR.CatLayout))] - [SRDescription(nameof(SR.ToolStripStretchDescr))] - public new bool Stretch { - get { - return base.Stretch; - } - set { - base.Stretch = value; - } - } - - - private TableLayoutSettings TableLayoutSettings { - get { return this.LayoutSettings as TableLayoutSettings; } - } - - protected override AccessibleObject CreateAccessibilityInstance() { - return new StatusStripAccessibleObject(this); - } - - protected internal override ToolStripItem CreateDefaultItem(string text, Image image, EventHandler onClick) { - return new ToolStripStatusLabel(text,image,onClick); - } - - protected override void Dispose( bool disposing ) { - if (disposing) { - if (rtlLayoutGrip != null) { + } + + + [DefaultValue(true)] + [SRCategory(nameof(SR.CatLayout))] + [SRDescription(nameof(SR.ToolStripStretchDescr))] + public new bool Stretch + { + get + { + return base.Stretch; + } + set + { + base.Stretch = value; + } + } + + + private TableLayoutSettings TableLayoutSettings + { + get { return this.LayoutSettings as TableLayoutSettings; } + } + + protected override AccessibleObject CreateAccessibilityInstance() + { + return new StatusStripAccessibleObject(this); + } + + protected internal override ToolStripItem CreateDefaultItem(string text, Image image, EventHandler onClick) + { + return new ToolStripStatusLabel(text, image, onClick); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (rtlLayoutGrip != null) + { rtlLayoutGrip.Dispose(); rtlLayoutGrip = null; } } base.Dispose(disposing); - } - - // in RTL, we parent a transparent control over the grip to support mirroring. - private void EnsureRightToLeftGrip() { - if (SizingGrip && RightToLeft == RightToLeft.Yes) { - RTLGrip.Bounds = SizeGripBounds; - if (!this.Controls.Contains(RTLGrip)) { - WindowsFormsUtils.ReadOnlyControlCollection controlCollection = this.Controls as WindowsFormsUtils.ReadOnlyControlCollection; - - if (controlCollection != null) { - controlCollection.AddInternal(RTLGrip); - } - } - } - else if (rtlLayoutGrip != null) { - if (this.Controls.Contains(rtlLayoutGrip)) { - WindowsFormsUtils.ReadOnlyControlCollection controlCollection = this.Controls as WindowsFormsUtils.ReadOnlyControlCollection; - - if (controlCollection != null) { - controlCollection.RemoveInternal(rtlLayoutGrip); - } - rtlLayoutGrip.Dispose(); - rtlLayoutGrip = null; - } - - } - - } - - internal override Size GetPreferredSizeCore(Size proposedSize) { - if (LayoutStyle == ToolStripLayoutStyle.Table) { - - if (proposedSize.Width == 1) { + } + + // in RTL, we parent a transparent control over the grip to support mirroring. + private void EnsureRightToLeftGrip() + { + if (SizingGrip && RightToLeft == RightToLeft.Yes) + { + RTLGrip.Bounds = SizeGripBounds; + if (!this.Controls.Contains(RTLGrip)) + { + WindowsFormsUtils.ReadOnlyControlCollection controlCollection = this.Controls as WindowsFormsUtils.ReadOnlyControlCollection; + + if (controlCollection != null) + { + controlCollection.AddInternal(RTLGrip); + } + } + } + else if (rtlLayoutGrip != null) + { + if (this.Controls.Contains(rtlLayoutGrip)) + { + WindowsFormsUtils.ReadOnlyControlCollection controlCollection = this.Controls as WindowsFormsUtils.ReadOnlyControlCollection; + + if (controlCollection != null) + { + controlCollection.RemoveInternal(rtlLayoutGrip); + } + rtlLayoutGrip.Dispose(); + rtlLayoutGrip = null; + } + + } + + } + + internal override Size GetPreferredSizeCore(Size proposedSize) + { + if (LayoutStyle == ToolStripLayoutStyle.Table) + { + + if (proposedSize.Width == 1) + { proposedSize.Width = int.MaxValue; } - if (proposedSize.Height == 1) { + if (proposedSize.Height == 1) + { proposedSize.Height = int.MaxValue; } - if (Orientation == Orientation.Horizontal) { + if (Orientation == Orientation.Horizontal) + { return GetPreferredSizeHorizontal(this, proposedSize) + Padding.Size; } - else { + else + { return GetPreferredSizeVertical(this, proposedSize) + Padding.Size; } } return base.GetPreferredSizeCore(proposedSize); - } - - protected override void OnPaintBackground(PaintEventArgs e) { - base.OnPaintBackground(e); - - if (ShowSizingGrip) { - Renderer.DrawStatusStripSizingGrip(new ToolStripRenderEventArgs(e.Graphics, this)); - } - } - - - protected override void OnLayout(LayoutEventArgs levent) { - state[stateCalledSpringTableLayout] = false; - bool inDisplayedItemCollecton = false; - ToolStripItem item = levent.AffectedComponent as ToolStripItem; - int itemCount = DisplayedItems.Count; - if (item != null) { - inDisplayedItemCollecton = DisplayedItems.Contains(item); - } - - - if (this.LayoutStyle == ToolStripLayoutStyle.Table) { - OnSpringTableLayoutCore(); - } - base.OnLayout(levent); - - if (itemCount != DisplayedItems.Count || (item != null && (inDisplayedItemCollecton != DisplayedItems.Contains(item)))) { - // calling OnLayout has changed the displayed items collection - // the SpringTableLayoutCore requires the count of displayed items to - // be accurate. - // - so we need to perform layout again. - if (this.LayoutStyle == ToolStripLayoutStyle.Table) { - OnSpringTableLayoutCore(); - base.OnLayout(levent); - } - - } - - EnsureRightToLeftGrip(); - - } - - internal override bool SupportsUiaProviders => true; - - protected override void SetDisplayedItems() { - if (state[stateCalledSpringTableLayout]) { - bool rightToLeft = ((Orientation == Orientation.Horizontal) && (RightToLeft == RightToLeft.Yes)); - - // shove all items that dont fit one pixel outside the displayed region - Rectangle displayRect = DisplayRectangle; - Point noMansLand = displayRect.Location; - noMansLand.X += ClientSize.Width + 1; - noMansLand.Y += ClientSize.Height + 1; - bool overflow = false; - Rectangle lastItemBounds = Rectangle.Empty; - - ToolStripItem lastItem = null; - for (int i = 0; i < Items.Count; i++) { - ToolStripItem item = Items[i]; - - // using spring layout we can get into a situation where there's extra items which arent - // visible. - if (overflow || ((IArrangedElement)item).ParticipatesInLayout) { - - if (overflow || (SizingGrip && item.Bounds.IntersectsWith(SizeGripBounds))) { + } + + protected override void OnPaintBackground(PaintEventArgs e) + { + base.OnPaintBackground(e); + + if (ShowSizingGrip) + { + Renderer.DrawStatusStripSizingGrip(new ToolStripRenderEventArgs(e.Graphics, this)); + } + } + + + protected override void OnLayout(LayoutEventArgs levent) + { + state[stateCalledSpringTableLayout] = false; + bool inDisplayedItemCollecton = false; + ToolStripItem item = levent.AffectedComponent as ToolStripItem; + int itemCount = DisplayedItems.Count; + if (item != null) + { + inDisplayedItemCollecton = DisplayedItems.Contains(item); + } + + + if (this.LayoutStyle == ToolStripLayoutStyle.Table) + { + OnSpringTableLayoutCore(); + } + base.OnLayout(levent); + + if (itemCount != DisplayedItems.Count || (item != null && (inDisplayedItemCollecton != DisplayedItems.Contains(item)))) + { + // calling OnLayout has changed the displayed items collection + // the SpringTableLayoutCore requires the count of displayed items to + // be accurate. + // - so we need to perform layout again. + if (this.LayoutStyle == ToolStripLayoutStyle.Table) + { + OnSpringTableLayoutCore(); + base.OnLayout(levent); + } + + } + + EnsureRightToLeftGrip(); + + } + + internal override bool SupportsUiaProviders => true; + + protected override void SetDisplayedItems() + { + if (state[stateCalledSpringTableLayout]) + { + bool rightToLeft = ((Orientation == Orientation.Horizontal) && (RightToLeft == RightToLeft.Yes)); + + // shove all items that dont fit one pixel outside the displayed region + Rectangle displayRect = DisplayRectangle; + Point noMansLand = displayRect.Location; + noMansLand.X += ClientSize.Width + 1; + noMansLand.Y += ClientSize.Height + 1; + bool overflow = false; + Rectangle lastItemBounds = Rectangle.Empty; + + ToolStripItem lastItem = null; + for (int i = 0; i < Items.Count; i++) + { + ToolStripItem item = Items[i]; + + // using spring layout we can get into a situation where there's extra items which arent + // visible. + if (overflow || ((IArrangedElement)item).ParticipatesInLayout) + { + + if (overflow || (SizingGrip && item.Bounds.IntersectsWith(SizeGripBounds))) + { // if the item collides with the size grip, set the location to nomansland. - SetItemLocation(item, noMansLand); + SetItemLocation(item, noMansLand); item.SetPlacement(ToolStripItemPlacement.None); } - } - else if (lastItem != null && (lastItemBounds.IntersectsWith(item.Bounds))) { - // if it overlaps the previous element, set the location to nomansland. - SetItemLocation(item, noMansLand); - item.SetPlacement(ToolStripItemPlacement.None); - } - else if (item.Bounds.Width == 1) { + } + else if (lastItem != null && (lastItemBounds.IntersectsWith(item.Bounds))) + { + // if it overlaps the previous element, set the location to nomansland. + SetItemLocation(item, noMansLand); + item.SetPlacement(ToolStripItemPlacement.None); + } + else if (item.Bounds.Width == 1) + { ToolStripStatusLabel panel = item as ToolStripStatusLabel; - if (panel != null && panel.Spring) { + if (panel != null && panel.Spring) + { // once we get down to one pixel, there can always be a one pixel // distribution problem with the TLP - there's usually a spare one around. // so set this off to nomansland as well. SetItemLocation(item, noMansLand); item.SetPlacement(ToolStripItemPlacement.None); } - } - - - if (item.Bounds.Location != noMansLand){ - // set the next item to inspect for collisions - lastItem = item; - lastItemBounds = lastItem.Bounds; - } - else { - // we cant fit an item, everything else after it should not be displayed - if (((IArrangedElement)item).ParticipatesInLayout) { - overflow = true; - } - } - } - } - base.SetDisplayedItems(); - } - - internal override void ResetRenderMode() { - RenderMode = ToolStripRenderMode.System; - } - internal override bool ShouldSerializeRenderMode() { - // We should NEVER serialize custom. - return (RenderMode != ToolStripRenderMode.System && RenderMode != ToolStripRenderMode.Custom); - } - - - - /// - /// Override this function if you want to do custom table layouts for the - /// StatusStrip. The default layoutstyle is tablelayout, and we need to play - /// with the row/column styles - /// - protected virtual void OnSpringTableLayoutCore() { - if (this.LayoutStyle == ToolStripLayoutStyle.Table) { - state[stateCalledSpringTableLayout]= true; - - this.SuspendLayout(); - - if (lastOrientation != Orientation) { - TableLayoutSettings settings = this.TableLayoutSettings; - settings.RowCount = 0; - settings.ColumnCount = 0; - settings.ColumnStyles.Clear(); - settings.RowStyles.Clear(); - } - lastOrientation = Orientation; - - if (Orientation == Orientation.Horizontal) { - - // - // Horizontal layout - // - TableLayoutSettings.GrowStyle = TableLayoutPanelGrowStyle.AddColumns; - - int originalColumnCount = this.TableLayoutSettings.ColumnStyles.Count; - - // iterate through the elements which are going to be displayed. - for (int i = 0; i < this.DisplayedItems.Count; i++) { - if (i >= originalColumnCount) { - // add if it's necessary. - this.TableLayoutSettings.ColumnStyles.Add(new ColumnStyle()); - } - - // determine if we "spring" or "autosize" the column - ToolStripStatusLabel panel = DisplayedItems[i] as ToolStripStatusLabel; - bool spring = (panel != null && panel.Spring); - DisplayedItems[i].Anchor = (spring) ? AllAnchor : VerticalAnchor; - - // spring is achieved by using 100% as the column style - ColumnStyle colStyle = this.TableLayoutSettings.ColumnStyles[i]; - colStyle.Width = 100; // this width is ignored in AutoSize. - colStyle.SizeType = (spring) ? SizeType.Percent : SizeType.AutoSize; - } - - if (TableLayoutSettings.RowStyles.Count > 1 || TableLayoutSettings.RowStyles.Count == 0) { - TableLayoutSettings.RowStyles.Clear(); - TableLayoutSettings.RowStyles.Add(new RowStyle()); - } - TableLayoutSettings.RowCount = 1; - - TableLayoutSettings.RowStyles[0].SizeType = SizeType.Absolute; - TableLayoutSettings.RowStyles[0].Height = Math.Max(0,this.DisplayRectangle.Height); - TableLayoutSettings.ColumnCount = DisplayedItems.Count+1; // add an extra cell so it fills the remaining space - - // dont remove the extra column styles, just set them back to autosize. - for (int i = DisplayedItems.Count; i < TableLayoutSettings.ColumnStyles.Count; i++) { + } + + + if (item.Bounds.Location != noMansLand) + { + // set the next item to inspect for collisions + lastItem = item; + lastItemBounds = lastItem.Bounds; + } + else + { + // we cant fit an item, everything else after it should not be displayed + if (((IArrangedElement)item).ParticipatesInLayout) + { + overflow = true; + } + } + } + } + base.SetDisplayedItems(); + } + + internal override void ResetRenderMode() + { + RenderMode = ToolStripRenderMode.System; + } + internal override bool ShouldSerializeRenderMode() + { + // We should NEVER serialize custom. + return (RenderMode != ToolStripRenderMode.System && RenderMode != ToolStripRenderMode.Custom); + } + + + + /// + /// Override this function if you want to do custom table layouts for the + /// StatusStrip. The default layoutstyle is tablelayout, and we need to play + /// with the row/column styles + /// + protected virtual void OnSpringTableLayoutCore() + { + if (this.LayoutStyle == ToolStripLayoutStyle.Table) + { + state[stateCalledSpringTableLayout] = true; + + this.SuspendLayout(); + + if (lastOrientation != Orientation) + { + TableLayoutSettings settings = this.TableLayoutSettings; + settings.RowCount = 0; + settings.ColumnCount = 0; + settings.ColumnStyles.Clear(); + settings.RowStyles.Clear(); + } + lastOrientation = Orientation; + + if (Orientation == Orientation.Horizontal) + { + + // + // Horizontal layout + // + TableLayoutSettings.GrowStyle = TableLayoutPanelGrowStyle.AddColumns; + + int originalColumnCount = this.TableLayoutSettings.ColumnStyles.Count; + + // iterate through the elements which are going to be displayed. + for (int i = 0; i < this.DisplayedItems.Count; i++) + { + if (i >= originalColumnCount) + { + // add if it's necessary. + this.TableLayoutSettings.ColumnStyles.Add(new ColumnStyle()); + } + + // determine if we "spring" or "autosize" the column + ToolStripStatusLabel panel = DisplayedItems[i] as ToolStripStatusLabel; + bool spring = (panel != null && panel.Spring); + DisplayedItems[i].Anchor = (spring) ? AllAnchor : VerticalAnchor; + + // spring is achieved by using 100% as the column style + ColumnStyle colStyle = this.TableLayoutSettings.ColumnStyles[i]; + colStyle.Width = 100; // this width is ignored in AutoSize. + colStyle.SizeType = (spring) ? SizeType.Percent : SizeType.AutoSize; + } + + if (TableLayoutSettings.RowStyles.Count > 1 || TableLayoutSettings.RowStyles.Count == 0) + { + TableLayoutSettings.RowStyles.Clear(); + TableLayoutSettings.RowStyles.Add(new RowStyle()); + } + TableLayoutSettings.RowCount = 1; + + TableLayoutSettings.RowStyles[0].SizeType = SizeType.Absolute; + TableLayoutSettings.RowStyles[0].Height = Math.Max(0, this.DisplayRectangle.Height); + TableLayoutSettings.ColumnCount = DisplayedItems.Count + 1; // add an extra cell so it fills the remaining space + + // dont remove the extra column styles, just set them back to autosize. + for (int i = DisplayedItems.Count; i < TableLayoutSettings.ColumnStyles.Count; i++) + { this.TableLayoutSettings.ColumnStyles[i].SizeType = SizeType.AutoSize; - } - } - else { - // - // Vertical layout - // - - TableLayoutSettings.GrowStyle = TableLayoutPanelGrowStyle.AddRows; - - int originalRowCount = this.TableLayoutSettings.RowStyles.Count; - - // iterate through the elements which are going to be displayed. - for (int i = 0; i < this.DisplayedItems.Count; i++) { - if (i >= originalRowCount) { - // add if it's necessary. - this.TableLayoutSettings.RowStyles.Add(new RowStyle()); - } - - // determine if we "spring" or "autosize" the row - ToolStripStatusLabel panel = DisplayedItems[i] as ToolStripStatusLabel; - bool spring = (panel != null && panel.Spring); - DisplayedItems[i].Anchor = (spring) ? AllAnchor : HorizontalAnchor; - - // spring is achieved by using 100% as the row style - RowStyle rowStyle = this.TableLayoutSettings.RowStyles[i]; - rowStyle.Height = 100; // this width is ignored in AutoSize. - rowStyle.SizeType = (spring) ? SizeType.Percent : SizeType.AutoSize; - } - TableLayoutSettings.ColumnCount = 1; - - if (TableLayoutSettings.ColumnStyles.Count > 1 || TableLayoutSettings.ColumnStyles.Count == 0) { - TableLayoutSettings.ColumnStyles.Clear(); - TableLayoutSettings.ColumnStyles.Add(new ColumnStyle()); - } - - TableLayoutSettings.ColumnCount = 1; - TableLayoutSettings.ColumnStyles[0].SizeType = SizeType.Absolute; - TableLayoutSettings.ColumnStyles[0].Width = Math.Max(0,this.DisplayRectangle.Width); - - TableLayoutSettings.RowCount = DisplayedItems.Count+1; // add an extra cell so it fills the remaining space - - // dont remove the extra column styles, just set them back to autosize. - for (int i = DisplayedItems.Count; i < TableLayoutSettings.RowStyles.Count; i++) { - this.TableLayoutSettings.RowStyles[i].SizeType = SizeType.AutoSize; - } - - } - - this.ResumeLayout(false); - } - } - - protected override void WndProc(ref Message m) { - if ((m.Msg == Interop.WindowMessages.WM_NCHITTEST) && SizingGrip) { - // if we're within the grip bounds tell windows - // that we're the bottom right of the window. - Rectangle sizeGripBounds = SizeGripBounds; - int x = NativeMethods.Util.LOWORD(m.LParam); - int y = NativeMethods.Util.HIWORD(m.LParam); - - - if (sizeGripBounds.Contains(PointToClient(new Point(x, y)))) { - HandleRef rootHwnd = WindowsFormsUtils.GetRootHWnd(this); - - // if the main window isnt maximized - we should paint a resize grip. - // double check that we're at the bottom right hand corner of the window. - if (rootHwnd.Handle != IntPtr.Zero && !UnsafeNativeMethods.IsZoomed(rootHwnd)) { - // get the client area of the topmost window. If we're next to the edge then - // the sizing grip is valid. - NativeMethods.RECT rootHwndClientArea = new NativeMethods.RECT(); - UnsafeNativeMethods.GetClientRect(rootHwnd, ref rootHwndClientArea); - - // map the size grip FROM statusStrip coords TO the toplevel window coords. - NativeMethods.POINT gripLocation; - if (RightToLeft == RightToLeft.Yes) { - gripLocation = new NativeMethods.POINT(SizeGripBounds.Left, SizeGripBounds.Bottom); } - else { - gripLocation = new NativeMethods.POINT(SizeGripBounds.Right, SizeGripBounds.Bottom); + } + else + { + // + // Vertical layout + // + + TableLayoutSettings.GrowStyle = TableLayoutPanelGrowStyle.AddRows; + + int originalRowCount = this.TableLayoutSettings.RowStyles.Count; + + // iterate through the elements which are going to be displayed. + for (int i = 0; i < this.DisplayedItems.Count; i++) + { + if (i >= originalRowCount) + { + // add if it's necessary. + this.TableLayoutSettings.RowStyles.Add(new RowStyle()); + } + + // determine if we "spring" or "autosize" the row + ToolStripStatusLabel panel = DisplayedItems[i] as ToolStripStatusLabel; + bool spring = (panel != null && panel.Spring); + DisplayedItems[i].Anchor = (spring) ? AllAnchor : HorizontalAnchor; + + // spring is achieved by using 100% as the row style + RowStyle rowStyle = this.TableLayoutSettings.RowStyles[i]; + rowStyle.Height = 100; // this width is ignored in AutoSize. + rowStyle.SizeType = (spring) ? SizeType.Percent : SizeType.AutoSize; + } + TableLayoutSettings.ColumnCount = 1; + + if (TableLayoutSettings.ColumnStyles.Count > 1 || TableLayoutSettings.ColumnStyles.Count == 0) + { + TableLayoutSettings.ColumnStyles.Clear(); + TableLayoutSettings.ColumnStyles.Add(new ColumnStyle()); + } + + TableLayoutSettings.ColumnCount = 1; + TableLayoutSettings.ColumnStyles[0].SizeType = SizeType.Absolute; + TableLayoutSettings.ColumnStyles[0].Width = Math.Max(0, this.DisplayRectangle.Width); + + TableLayoutSettings.RowCount = DisplayedItems.Count + 1; // add an extra cell so it fills the remaining space + + // dont remove the extra column styles, just set them back to autosize. + for (int i = DisplayedItems.Count; i < TableLayoutSettings.RowStyles.Count; i++) + { + this.TableLayoutSettings.RowStyles[i].SizeType = SizeType.AutoSize; } - UnsafeNativeMethods.MapWindowPoints(new HandleRef(this, this.Handle), rootHwnd, gripLocation, 1); - - int deltaBottomEdge = Math.Abs(rootHwndClientArea.bottom - gripLocation.y); - int deltaRightEdge = Math.Abs(rootHwndClientArea.right - gripLocation.x); - - if (RightToLeft != RightToLeft.Yes) { - if ((deltaRightEdge + deltaBottomEdge) < 2) { - m.Result = (IntPtr)NativeMethods.HTBOTTOMRIGHT; - return; + + } + + this.ResumeLayout(false); + } + } + + protected override void WndProc(ref Message m) + { + if ((m.Msg == Interop.WindowMessages.WM_NCHITTEST) && SizingGrip) + { + // if we're within the grip bounds tell windows + // that we're the bottom right of the window. + Rectangle sizeGripBounds = SizeGripBounds; + int x = NativeMethods.Util.LOWORD(m.LParam); + int y = NativeMethods.Util.HIWORD(m.LParam); + + + if (sizeGripBounds.Contains(PointToClient(new Point(x, y)))) + { + HandleRef rootHwnd = WindowsFormsUtils.GetRootHWnd(this); + + // if the main window isnt maximized - we should paint a resize grip. + // double check that we're at the bottom right hand corner of the window. + if (rootHwnd.Handle != IntPtr.Zero && !UnsafeNativeMethods.IsZoomed(rootHwnd)) + { + // get the client area of the topmost window. If we're next to the edge then + // the sizing grip is valid. + NativeMethods.RECT rootHwndClientArea = new NativeMethods.RECT(); + UnsafeNativeMethods.GetClientRect(rootHwnd, ref rootHwndClientArea); + + // map the size grip FROM statusStrip coords TO the toplevel window coords. + NativeMethods.POINT gripLocation; + if (RightToLeft == RightToLeft.Yes) + { + gripLocation = new NativeMethods.POINT(SizeGripBounds.Left, SizeGripBounds.Bottom); + } + else + { + gripLocation = new NativeMethods.POINT(SizeGripBounds.Right, SizeGripBounds.Bottom); } + UnsafeNativeMethods.MapWindowPoints(new HandleRef(this, this.Handle), rootHwnd, gripLocation, 1); + + int deltaBottomEdge = Math.Abs(rootHwndClientArea.bottom - gripLocation.y); + int deltaRightEdge = Math.Abs(rootHwndClientArea.right - gripLocation.x); + + if (RightToLeft != RightToLeft.Yes) + { + if ((deltaRightEdge + deltaBottomEdge) < 2) + { + m.Result = (IntPtr)NativeMethods.HTBOTTOMRIGHT; + return; + } + } + + } - - + } - - } - } - base.WndProc(ref m); - } - - // special transparent mirrored window which says it's the bottom left of the form. - private class RightToLeftLayoutGrip : Control { - public RightToLeftLayoutGrip() { + } + base.WndProc(ref m); + } + + // special transparent mirrored window which says it's the bottom left of the form. + private class RightToLeftLayoutGrip : Control + { + public RightToLeftLayoutGrip() + { SetStyle(ControlStyles.SupportsTransparentBackColor, true); this.BackColor = Color.Transparent; - } - protected override CreateParams CreateParams { - get { + } + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ExStyle |= NativeMethods.WS_EX_LAYOUTRTL; - return cp; + return cp; } } - protected override void WndProc(ref Message m) { - if (m.Msg == Interop.WindowMessages.WM_NCHITTEST) { + protected override void WndProc(ref Message m) + { + if (m.Msg == Interop.WindowMessages.WM_NCHITTEST) + { int x = NativeMethods.Util.LOWORD(m.LParam); int y = NativeMethods.Util.HIWORD(m.LParam); - if (ClientRectangle.Contains(PointToClient(new Point(x, y)))) { + if (ClientRectangle.Contains(PointToClient(new Point(x, y)))) + { m.Result = (IntPtr)NativeMethods.HTBOTTOMLEFT; return; } - } - base.WndProc(ref m); + } + base.WndProc(ref m); } - } - + } + - [System.Runtime.InteropServices.ComVisible(true)] - internal class StatusStripAccessibleObject : ToolStripAccessibleObject { - public StatusStripAccessibleObject(StatusStrip owner) : base(owner) { + [System.Runtime.InteropServices.ComVisible(true)] + internal class StatusStripAccessibleObject : ToolStripAccessibleObject + { + public StatusStripAccessibleObject(StatusStrip owner) : base(owner) + { } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { AccessibleRole role = Owner.AccessibleRole; - if (role != AccessibleRole.Default) { + if (role != AccessibleRole.Default) + { return role; } return AccessibleRole.StatusBar; } } - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_ControlTypePropertyId) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_ControlTypePropertyId) + { return NativeMethods.UIA_StatusBarControlTypeId; } return base.GetPropertyValue(propertyID); } - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { StatusStrip statusStrip = Owner as StatusStrip; - if (statusStrip == null || statusStrip.Items.Count == 0) { + if (statusStrip == null || statusStrip.Items.Count == 0) + { return null; } - switch (direction) { + switch (direction) + { case UnsafeNativeMethods.NavigateDirection.FirstChild: AccessibleObject firstChild = null; - for (int i = 0; i < GetChildCount(); i++) { + for (int i = 0; i < GetChildCount(); i++) + { firstChild = GetChild(i); - if (firstChild != null && !(firstChild is ControlAccessibleObject)) { + if (firstChild != null && !(firstChild is ControlAccessibleObject)) + { return firstChild; } } @@ -649,9 +781,11 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga case UnsafeNativeMethods.NavigateDirection.LastChild: AccessibleObject lastChild = null; - for (int i = GetChildCount() - 1; i >= 0; i--) { + for (int i = GetChildCount() - 1; i >= 0; i--) + { lastChild = GetChild(i); - if (lastChild != null && !(lastChild is ControlAccessibleObject)) { + if (lastChild != null && !(lastChild is ControlAccessibleObject)) + { return lastChild; } } @@ -661,11 +795,13 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga return base.FragmentNavigate(direction); } - internal override UnsafeNativeMethods.IRawElementProviderFragment ElementProviderFromPoint(double x, double y) { + internal override UnsafeNativeMethods.IRawElementProviderFragment ElementProviderFromPoint(double x, double y) + { return HitTest((int)x, (int)y); } - internal override UnsafeNativeMethods.IRawElementProviderFragment GetFocus() { + internal override UnsafeNativeMethods.IRawElementProviderFragment GetFocus() + { return GetFocused(); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/StringSorter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/StringSorter.cs index 231d5fd04af..710823f52c0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/StringSorter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/StringSorter.cs @@ -2,8 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { - +namespace System.Windows.Forms +{ + using System.Threading; using System.ComponentModel; using System.Diagnostics; @@ -88,41 +89,49 @@ internal sealed class StringSorter /// Constructs a StringSorter. Instances are created by the sort() routines, /// but never by the user. /// - private StringSorter(CultureInfo culture, string[] keys, object[] items, int options) { - if (keys == null) { - if (items is string[]) { + private StringSorter(CultureInfo culture, string[] keys, object[] items, int options) + { + if (keys == null) + { + if (items is string[]) + { keys = (string[])items; items = null; } - else { + else + { keys = new string[items.Length]; - for (int i = 0; i < items.Length; i++) { + for (int i = 0; i < items.Length; i++) + { object item = items[i]; - if (item != null) keys[i] = item.ToString(); + if (item != null) + keys[i] = item.ToString(); } } } this.keys = keys; this.items = items; - this.lcid = culture == null? SafeNativeMethods.GetThreadLocale(): culture.LCID; + this.lcid = culture == null ? SafeNativeMethods.GetThreadLocale() : culture.LCID; this.options = options & CompareOptions; this.descending = (options & Descending) != 0; } /// /// - internal static int ArrayLength(object[] array) { + internal static int ArrayLength(object[] array) + { if (array == null) return 0; else return array.Length; } - + /// /// Compares two strings using the default locale and no additional string /// comparison flags. /// - public static int Compare(string s1, string s2) { + public static int Compare(string s1, string s2) + { return Compare(SafeNativeMethods.GetThreadLocale(), s1, s2, 0); } @@ -130,7 +139,8 @@ public static int Compare(string s1, string s2) { /// Compares two strings using the default locale with the given set of /// string comparison flags. /// - public static int Compare(string s1, string s2, int options) { + public static int Compare(string s1, string s2, int options) + { return Compare(SafeNativeMethods.GetThreadLocale(), s1, s2, options); } @@ -148,23 +158,28 @@ public static int Compare(string s1, string s2, int options) { /// IGNORENONSPACE, IGNORESYMBOLS, /// IGNOREWIDTH, and STRINGSORT. /// - public static int Compare(CultureInfo culture, string s1, string s2, int options) { + public static int Compare(CultureInfo culture, string s1, string s2, int options) + { return Compare(culture.LCID, s1, s2, options); } /// /// - private static int Compare(int lcid, string s1, string s2, int options) { - if (s1 == null) return s2 == null? 0: -1; - if (s2 == null) return 1; + private static int Compare(int lcid, string s1, string s2, int options) + { + if (s1 == null) + return s2 == null ? 0 : -1; + if (s2 == null) + return 1; return string.Compare(s1, s2, false, CultureInfo.CurrentCulture); } /// /// - private int CompareKeys(string s1, string s2) { + private int CompareKeys(string s1, string s2) + { int result = Compare(lcid, s1, s2, options); - return descending? -result: result; + return descending ? -result : result; } /// @@ -173,20 +188,28 @@ private int CompareKeys(string s1, string s2) { /// side. This bounds the recursive depth by log2(n) in the worst case. /// Otherwise, worst case recursive depth would be n. /// - private void QuickSort(int left, int right) { - do { + private void QuickSort(int left, int right) + { + do + { int i = left; int j = right; string s = keys[(i + j) >> 1]; - do { - while (CompareKeys(keys[i], s) < 0) i++; - while (CompareKeys(s, keys[j]) < 0) j--; - if (i > j) break; - if (i < j) { + do + { + while (CompareKeys(keys[i], s) < 0) + i++; + while (CompareKeys(s, keys[j]) < 0) + j--; + if (i > j) + break; + if (i < j) + { string key = keys[i]; keys[i] = keys[j]; keys[j] = key; - if (items != null) { + if (items != null) + { object item = items[i]; items[i] = items[j]; items[j] = item; @@ -195,12 +218,16 @@ private void QuickSort(int left, int right) { i++; j--; } while (i <= j); - if (j - left <= right - i) { - if (left < j) QuickSort(left, j); + if (j - left <= right - i) + { + if (left < j) + QuickSort(left, j); left = i; } - else { - if (i < right) QuickSort(i, right); + else + { + if (i < right) + QuickSort(i, right); right = j; } } while (left < right); @@ -213,7 +240,8 @@ private void QuickSort(int left, int right) { /// produce the string representation. The objects are then sorted by their /// string representations using the default locale. /// - public static void Sort(object[] items) { + public static void Sort(object[] items) + { Sort(null, null, items, 0, ArrayLength(items), 0); } @@ -224,7 +252,8 @@ public static void Sort(object[] items) { /// produce the string representation. The objects are then sorted by their /// string representations using the default locale. /// - public static void Sort(object[] items, int index, int count) { + public static void Sort(object[] items, int index, int count) + { Sort(null, null, items, index, count, 0); } @@ -232,7 +261,8 @@ public static void Sort(object[] items, int index, int count) { /// Sorts a string array and an object array based on the elements of the /// string array. The arrays are sorted using the default locale. /// - public static void Sort(string[] keys, object[] items) { + public static void Sort(string[] keys, object[] items) + { Sort(null, keys, items, 0, ArrayLength(items), 0); } @@ -241,7 +271,8 @@ public static void Sort(string[] keys, object[] items) { /// the elements of the string array. The arrays are sorted using the /// default locale. /// - public static void Sort(string[] keys, object[] items, int index, int count) { + public static void Sort(string[] keys, object[] items, int index, int count) + { Sort(null, keys, items, index, count, 0); } @@ -253,7 +284,8 @@ public static void Sort(string[] keys, object[] items, int index, int count) { /// string representations using the default locale and the given sorting /// options. /// - public static void Sort(object[] items, int options) { + public static void Sort(object[] items, int options) + { Sort(null, null, items, 0, ArrayLength(items), options); } @@ -265,7 +297,8 @@ public static void Sort(object[] items, int options) { /// string representations using the default locale and the given sorting /// options. /// - public static void Sort(object[] items, int index, int count, int options) { + public static void Sort(object[] items, int index, int count, int options) + { Sort(null, null, items, index, count, options); } @@ -274,7 +307,8 @@ public static void Sort(object[] items, int index, int count, int options) { /// string array. The arrays are sorted using the default locale and the /// given sorting options. /// - public static void Sort(string[] keys, object[] items, int options) { + public static void Sort(string[] keys, object[] items, int options) + { Sort(null, keys, items, 0, ArrayLength(items), options); } @@ -283,7 +317,8 @@ public static void Sort(string[] keys, object[] items, int options) { /// the elements of the string array. The arrays are sorted using the /// default locale and the given sorting options. /// - public static void Sort(string[] keys, object[] items, int index, int count, int options) { + public static void Sort(string[] keys, object[] items, int index, int count, int options) + { Sort(null, keys, items, index, count, options); } @@ -295,7 +330,8 @@ public static void Sort(string[] keys, object[] items, int index, int count, int /// string representations using the given locale and the given sorting /// options. /// - public static void Sort(CultureInfo culture, object[] items, int options) { + public static void Sort(CultureInfo culture, object[] items, int options) + { Sort(culture, null, items, 0, ArrayLength(items), options); } @@ -307,7 +343,8 @@ public static void Sort(CultureInfo culture, object[] items, int options) { /// string representations using the given locale and the given sorting /// options. /// - public static void Sort(CultureInfo culture, object[] items, int index, int count, int options) { + public static void Sort(CultureInfo culture, object[] items, int index, int count, int options) + { Sort(culture, null, items, index, count, options); } @@ -316,7 +353,8 @@ public static void Sort(CultureInfo culture, object[] items, int index, int coun /// string array. The arrays are sorted using the given locale and the /// given sorting options. /// - public static void Sort(CultureInfo culture, string[] keys, object[] items, int options) { + public static void Sort(CultureInfo culture, string[] keys, object[] items, int options) + { Sort(culture, keys, items, 0, ArrayLength(items), options); } @@ -337,7 +375,8 @@ public static void Sort(CultureInfo culture, string[] keys, object[] items, int /// IGNOREWIDTH, STRINGSORT, and /// DESCENDING. /// - public static void Sort(CultureInfo culture, string[] keys, object[] items, int index, int count, int options) { + public static void Sort(CultureInfo culture, string[] keys, object[] items, int index, int count, int options) + { // keys and items have to be the same length // if ((items == null) @@ -345,7 +384,8 @@ public static void Sort(CultureInfo culture, string[] keys, object[] items, int throw new ArgumentException(string.Format(SR.ArraysNotSameSize, "keys", "items")); - if (count > 1) { + if (count > 1) + { StringSorter sorter = new StringSorter(culture, keys, items, options); sorter.QuickSort(index, index + count - 1); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/StringSource.cs b/src/System.Windows.Forms/src/System/Windows/Forms/StringSource.cs index 482cf58ed1f..630dfeb2d2d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/StringSource.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/StringSource.cs @@ -2,14 +2,15 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.InteropServices.ComTypes; using System.Runtime.InteropServices; using System.Collections; using System.Diagnostics.CodeAnalysis; - + /// /// /// Represents an internal class that is used bu ComboBox and TextBox AutoCompleteCustomSoucr property. @@ -17,33 +18,36 @@ namespace System.Windows.Forms { /// The StringSource contains an array of Strings which is passed to the COM object as the custom source. /// /// - internal class StringSource : IEnumString { + internal class StringSource : IEnumString + { private string[] strings; private int current; private int size; private UnsafeNativeMethods.IAutoComplete2 autoCompleteObject2; - + /// /// /// SHAutoComplete COM object CLSID. /// /// - private static Guid autoCompleteClsid = new Guid("{00BB2763-6A77-11D0-A535-00C04FD7D062}"); + private static Guid autoCompleteClsid = new Guid("{00BB2763-6A77-11D0-A535-00C04FD7D062}"); /// /// /// Constructor. /// /// - public StringSource(string[] strings) { - Array.Clear(strings,0, size); - - if (strings != null) { + public StringSource(string[] strings) + { + Array.Clear(strings, 0, size); + + if (strings != null) + { this.strings = strings; } current = 0; - size = (strings == null ) ? 0 : strings.Length; + size = (strings == null) ? 0 : strings.Length; Guid iid_iunknown = typeof(UnsafeNativeMethods.IAutoComplete2).GUID; object obj = UnsafeNativeMethods.CoCreateInstance(ref autoCompleteClsid, null, NativeMethods.CLSCTX_INPROC_SERVER, ref iid_iunknown); @@ -57,11 +61,13 @@ public StringSource(string[] strings) { /// to the edit Control and the "options' are the options that need to be set in the AUTOCOMPLETE mode. /// /// - public bool Bind(HandleRef edit, int options) { - + public bool Bind(HandleRef edit, int options) + { + bool retVal = false; - - if (autoCompleteObject2 != null) { + + if (autoCompleteObject2 != null) + { try { autoCompleteObject2.SetOptions(options); @@ -75,7 +81,7 @@ public bool Bind(HandleRef edit, int options) { } return retVal; } - [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] + [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] public void ReleaseAutoComplete() { if (autoCompleteObject2 != null) @@ -87,13 +93,14 @@ public void ReleaseAutoComplete() public void RefreshList(string[] newSource) { - Array.Clear(strings,0, size); - - if (strings != null) { + Array.Clear(strings, 0, size); + + if (strings != null) + { this.strings = newSource; } current = 0; - size = (strings == null ) ? 0 : strings.Length; + size = (strings == null) ? 0 : strings.Length; } #region IEnumString Members @@ -144,4 +151,4 @@ int IEnumString.Skip(int celt) #endregion } } - + diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SystemInformation.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SystemInformation.cs index 35150ed91b7..b381f15c363 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SystemInformation.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SystemInformation.cs @@ -1421,7 +1421,7 @@ internal static bool InLockedTerminalSession() int error = Marshal.GetLastWin32Error(); return error == NativeMethods.ERROR_ACCESS_DENIED; } - + SafeNativeMethods.CloseDesktop(hDsk); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs index 318dbcb3783..988202f9324 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs @@ -6,7 +6,8 @@ -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Collections; using System.ComponentModel; @@ -34,22 +35,23 @@ namespace System.Windows.Forms { Designer("System.Windows.Forms.Design.TabControlDesigner, " + AssemblyRef.SystemDesign), SRDescription(nameof(SR.DescriptionTabControl)) ] - public class TabControl : Control { + public class TabControl : Control + { private static readonly Size DEFAULT_ITEMSIZE = Size.Empty; private static readonly Point DEFAULT_PADDING = new Point(6, 3); //properties private TabPageCollection tabCollection; - private TabAlignment alignment = TabAlignment.Top; - private TabDrawMode drawMode = TabDrawMode.Normal; - private ImageList imageList = null; - private Size itemSize = DEFAULT_ITEMSIZE; - private Point padding = DEFAULT_PADDING; - private TabSizeMode sizeMode = TabSizeMode.Normal; - private TabAppearance appearance = TabAppearance.Normal; - private Rectangle cachedDisplayRect = Rectangle.Empty; - private bool currentlyScaling = false; + private TabAlignment alignment = TabAlignment.Top; + private TabDrawMode drawMode = TabDrawMode.Normal; + private ImageList imageList = null; + private Size itemSize = DEFAULT_ITEMSIZE; + private Point padding = DEFAULT_PADDING; + private TabSizeMode sizeMode = TabSizeMode.Normal; + private TabAppearance appearance = TabAppearance.Normal; + private Rectangle cachedDisplayRect = Rectangle.Empty; + private bool currentlyScaling = false; private int selectedIndex = -1; private Size cachedSize = Size.Empty; private string controlTipText = string.Empty; @@ -67,19 +69,19 @@ public class TabControl : Control { private static readonly object EVENT_RIGHTTOLEFTLAYOUTCHANGED = new object(); - private const int TABCONTROLSTATE_hotTrack = 0x00000001; - private const int TABCONTROLSTATE_multiline = 0x00000002; - private const int TABCONTROLSTATE_showToolTips = 0x00000004; - private const int TABCONTROLSTATE_getTabRectfromItemSize = 0x00000008; - private const int TABCONTROLSTATE_fromCreateHandles = 0x00000010; - private const int TABCONTROLSTATE_UISelection = 0x00000020; - private const int TABCONTROLSTATE_selectFirstControl = 0x00000040; - private const int TABCONTROLSTATE_insertingItem = 0x00000080; - private const int TABCONTROLSTATE_autoSize = 0x00000100; - + private const int TABCONTROLSTATE_hotTrack = 0x00000001; + private const int TABCONTROLSTATE_multiline = 0x00000002; + private const int TABCONTROLSTATE_showToolTips = 0x00000004; + private const int TABCONTROLSTATE_getTabRectfromItemSize = 0x00000008; + private const int TABCONTROLSTATE_fromCreateHandles = 0x00000010; + private const int TABCONTROLSTATE_UISelection = 0x00000020; + private const int TABCONTROLSTATE_selectFirstControl = 0x00000040; + private const int TABCONTROLSTATE_insertingItem = 0x00000080; + private const int TABCONTROLSTATE_autoSize = 0x00000100; + // PERF: take all the bools and put them into a state variable - private System.Collections.Specialized.BitVector32 tabControlState; // see TABCONTROLSTATE_ consts above + private System.Collections.Specialized.BitVector32 tabControlState; // see TABCONTROLSTATE_ consts above @@ -97,14 +99,15 @@ public class TabControl : Control { private int tabPageCount; private int lastSelection; - private bool rightToLeftLayout = false; - private bool skipUpdateSize; + private bool rightToLeftLayout = false; + private bool skipUpdateSize; /// /// Constructs a TabBase object, usually as the base class for a TabStrip or TabControl. /// public TabControl() - : base() { + : base() + { tabControlState = new System.Collections.Specialized.BitVector32(0x00000000); @@ -126,15 +129,20 @@ public TabControl() RefreshProperties(RefreshProperties.All), SRDescription(nameof(SR.TabBaseAlignmentDescr)) ] - public TabAlignment Alignment { - get { + public TabAlignment Alignment + { + get + { return alignment; } - set { - if (this.alignment != value) { + set + { + if (this.alignment != value) + { //valid values are 0x0 to 0x3 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)TabAlignment.Top, (int)TabAlignment.Right)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)TabAlignment.Top, (int)TabAlignment.Right)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(TabAlignment)); } @@ -158,20 +166,27 @@ public TabAlignment Alignment { DefaultValue(TabAppearance.Normal), SRDescription(nameof(SR.TabBaseAppearanceDescr)) ] - public TabAppearance Appearance { - get { - if (appearance == TabAppearance.FlatButtons && alignment != TabAlignment.Top) { + public TabAppearance Appearance + { + get + { + if (appearance == TabAppearance.FlatButtons && alignment != TabAlignment.Top) + { return TabAppearance.Buttons; } - else { + else + { return appearance; } } - set { - if (this.appearance != value) { + set + { + if (this.appearance != value) + { //valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)TabAppearance.Normal, (int)TabAppearance.FlatButtons)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)TabAppearance.Normal, (int)TabAppearance.FlatButtons)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(TabAppearance)); } @@ -183,54 +198,66 @@ public TabAppearance Appearance { } } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Color BackColor { - get { + public override Color BackColor + { + get + { //The tab control can only be rendered in 1 color: System's Control color. //So, always return this value... otherwise, we're inheriting the forms backcolor //and passing it on to the pab pages. return SystemColors.Control; } - set { + set + { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackColorChanged { + new public event EventHandler BackColorChanged + { add => base.BackColorChanged += value; remove => base.BackColorChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged { + new public event EventHandler BackgroundImageChanged + { add => base.BackgroundImageChanged += value; remove => base.BackgroundImageChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { + new public event EventHandler BackgroundImageLayoutChanged + { add => base.BackgroundImageLayoutChanged += value; remove => base.BackgroundImageLayoutChanged -= value; } @@ -239,8 +266,10 @@ public override ImageLayout BackgroundImageLayout { /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(200, 100); } } @@ -250,27 +279,34 @@ protected override Size DefaultSize { /// on controls that are based on Win32 Native Controls. /// [EditorBrowsable(EditorBrowsableState.Never)] - protected override bool DoubleBuffered { - get { + protected override bool DoubleBuffered + { + get + { return base.DoubleBuffered; } - set { + set + { base.DoubleBuffered = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Color ForeColor { - get { + public override Color ForeColor + { + get + { return base.ForeColor; } - set { + set + { base.ForeColor = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler ForeColorChanged { + new public event EventHandler ForeColorChanged + { add => base.ForeColorChanged += value; remove => base.ForeColorChanged -= value; } @@ -281,16 +317,21 @@ public override Color ForeColor { /// however, forget to call base.getCreateParams() first to get the struct /// filled up with the basic info. /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ClassName = NativeMethods.WC_TABCONTROL; // set up window styles // - if (Multiline == true) cp.Style |= NativeMethods.TCS_MULTILINE; - if (drawMode == TabDrawMode.OwnerDrawFixed) cp.Style |= NativeMethods.TCS_OWNERDRAWFIXED; - if (ShowToolTips && !DesignMode) { + if (Multiline == true) + cp.Style |= NativeMethods.TCS_MULTILINE; + if (drawMode == TabDrawMode.OwnerDrawFixed) + cp.Style |= NativeMethods.TCS_OWNERDRAWFIXED; + if (ShowToolTips && !DesignMode) + { cp.Style |= NativeMethods.TCS_TOOLTIPS; } @@ -302,19 +343,22 @@ protected override CreateParams CreateParams { alignment == TabAlignment.Right) cp.Style |= NativeMethods.TCS_VERTICAL | NativeMethods.TCS_MULTILINE; - if (tabControlState[TABCONTROLSTATE_hotTrack]) { + if (tabControlState[TABCONTROLSTATE_hotTrack]) + { cp.Style |= NativeMethods.TCS_HOTTRACK; } if (appearance == TabAppearance.Normal) cp.Style |= NativeMethods.TCS_TABS; - else { + else + { cp.Style |= NativeMethods.TCS_BUTTONS; if (appearance == TabAppearance.FlatButtons && alignment == TabAlignment.Top) cp.Style |= NativeMethods.TCS_FLATBUTTONS; } - switch (sizeMode) { + switch (sizeMode) + { case TabSizeMode.Normal: cp.Style |= NativeMethods.TCS_RAGGEDRIGHT; break; @@ -326,7 +370,8 @@ protected override CreateParams CreateParams { break; } - if (RightToLeft == RightToLeft.Yes && RightToLeftLayout == true) { + if (RightToLeft == RightToLeft.Yes && RightToLeftLayout == true) + { //We want to turn on mirroring for Form explicitly. cp.ExStyle |= NativeMethods.WS_EX_LAYOUTRTL | NativeMethods.WS_EX_NOINHERITLAYOUT; //Don't need these styles when mirroring is turned on. @@ -343,10 +388,12 @@ protected override CreateParams CreateParams { /// is typically the rectangle you want to use to place the individual /// children of the tab strip. /// - public override Rectangle DisplayRectangle { - get { + public override Rectangle DisplayRectangle + { + get + { + - // Null out cachedDisplayRect whenever we do anything to change it... // if (!cachedDisplayRect.IsEmpty) @@ -355,8 +402,8 @@ public override Rectangle DisplayRectangle { Rectangle bounds = Bounds; NativeMethods.RECT rect = NativeMethods.RECT.FromXYWH(bounds.X, bounds.Y, bounds.Width, bounds.Height); - - + + // We force a handle creation here, because otherwise the DisplayRectangle will be wildly inaccurate // if (!IsDisposed) @@ -365,7 +412,8 @@ public override Rectangle DisplayRectangle { // a ActiveX control, so check if this is ActiveX and dont force Handle Creation here as the native code breaks in this case. if (!IsActiveX) { - if (!IsHandleCreated) { + if (!IsHandleCreated) + { CreateHandle(); } } @@ -395,18 +443,23 @@ public override Rectangle DisplayRectangle { DefaultValue(TabDrawMode.Normal), SRDescription(nameof(SR.TabBaseDrawModeDescr)) ] - public TabDrawMode DrawMode { - get { + public TabDrawMode DrawMode + { + get + { return drawMode; } - set { + set + { //valid values are 0x0 to 0x1 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)TabDrawMode.Normal, (int)TabDrawMode.OwnerDrawFixed)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)TabDrawMode.Normal, (int)TabDrawMode.OwnerDrawFixed)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(TabDrawMode)); } - if (drawMode != value) { + if (drawMode != value) + { drawMode = value; RecreateHandle(); } @@ -421,15 +474,20 @@ public TabDrawMode DrawMode { DefaultValue(false), SRDescription(nameof(SR.TabBaseHotTrackDescr)) ] - public bool HotTrack { - get { + public bool HotTrack + { + get + { return tabControlState[TABCONTROLSTATE_hotTrack]; } - set { - if (HotTrack != value) { + set + { + if (HotTrack != value) + { tabControlState[TABCONTROLSTATE_hotTrack] = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { RecreateHandle(); } } @@ -446,16 +504,21 @@ public bool HotTrack { DefaultValue(null), SRDescription(nameof(SR.TabBaseImageListDescr)) ] - public ImageList ImageList { - get { + public ImageList ImageList + { + get + { return imageList; } - set { - if (this.imageList != value) { + set + { + if (this.imageList != value) + { EventHandler recreateHandler = new EventHandler(ImageListRecreateHandle); EventHandler disposedHandler = new EventHandler(DetachImageList); - if (imageList != null) { + if (imageList != null) + { imageList.RecreateHandle -= recreateHandler; imageList.Disposed -= disposedHandler; } @@ -466,12 +529,14 @@ public ImageList ImageList { SendMessage(NativeMethods.TCM_SETIMAGELIST, IntPtr.Zero, handle); // Update the image list in the tab pages. - foreach (TabPage tabPage in TabPages) { + foreach (TabPage tabPage in TabPages) + { tabPage.ImageIndexer.ImageList = value; } - if (value != null) { + if (value != null) + { value.RecreateHandle += recreateHandler; value.Disposed += disposedHandler; } @@ -488,27 +553,35 @@ public ImageList ImageList { Localizable(true), SRDescription(nameof(SR.TabBaseItemSizeDescr)) ] - public Size ItemSize { - get { - if (itemSize.IsEmpty) { + public Size ItemSize + { + get + { + if (itemSize.IsEmpty) + { // Obtain the current itemsize of the first tab from the winctl control // - if (IsHandleCreated) { + if (IsHandleCreated) + { tabControlState[TABCONTROLSTATE_getTabRectfromItemSize] = true; return GetTabRect(0).Size; } - else { + else + { return DEFAULT_ITEMSIZE; } } - else { + else + { return itemSize; } } - set { - if (value.Width < 0 || value.Height < 0) { + set + { + if (value.Width < 0 || value.Height < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(ItemSize), value)); } itemSize = value; @@ -525,11 +598,14 @@ public Size ItemSize { /// So we keep this flag in order to aviod repeatd addition (only during insert) /// When the Add ends ... we reset this flag. /// - private bool InsertingItem { - get { + private bool InsertingItem + { + get + { return (bool)tabControlState[TABCONTROLSTATE_insertingItem]; } - set { + set + { tabControlState[TABCONTROLSTATE_insertingItem] = value; } } @@ -546,12 +622,16 @@ private bool InsertingItem { DefaultValue(false), SRDescription(nameof(SR.TabBaseMultilineDescr)) ] - public bool Multiline { - get { + public bool Multiline + { + get + { return tabControlState[TABCONTROLSTATE_multiline]; } - set { - if (Multiline != value) { + set + { + if (Multiline != value) + { tabControlState[TABCONTROLSTATE_multiline] = value; if (Multiline == false && (this.alignment == TabAlignment.Left || this.alignment == TabAlignment.Right)) this.alignment = TabAlignment.Top; @@ -569,19 +649,24 @@ public bool Multiline { Localizable(true), SRDescription(nameof(SR.TabBasePaddingDescr)) ] - public new Point Padding { - get { + public new Point Padding + { + get + { return padding; } - set { + set + { if (value.X < 0 || value.Y < 0) { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(Padding), value)); } - if (padding != value) { + if (padding != value) + { padding = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { RecreateHandle(); } } @@ -600,16 +685,21 @@ public bool Multiline { DefaultValue(false), SRDescription(nameof(SR.ControlRightToLeftLayoutDescr)) ] - public virtual bool RightToLeftLayout { - get { + public virtual bool RightToLeftLayout + { + get + { return rightToLeftLayout; } - set { - if (value != rightToLeftLayout) { + set + { + if (value != rightToLeftLayout) + { rightToLeftLayout = value; - using(new LayoutTransaction(this, this, PropertyNames.RightToLeftLayout)) { + using (new LayoutTransaction(this, this, PropertyNames.RightToLeftLayout)) + { OnRightToLeftLayoutChanged(EventArgs.Empty); } } @@ -630,10 +720,12 @@ public virtual bool RightToLeftLayout { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.TabBaseRowCountDescr)) ] - public int RowCount { - get { + public int RowCount + { + get + { int n; - n = unchecked( (int) (long)SendMessage(NativeMethods.TCM_GETROWCOUNT, 0, 0)); + n = unchecked((int)(long)SendMessage(NativeMethods.TCM_GETROWCOUNT, 0, 0)); return n; } } @@ -650,34 +742,45 @@ public int RowCount { DefaultValue(-1), SRDescription(nameof(SR.selectedIndexDescr)) ] - public int SelectedIndex { - get { - if (IsHandleCreated) { + public int SelectedIndex + { + get + { + if (IsHandleCreated) + { int n; - n = unchecked( (int) (long)SendMessage(NativeMethods.TCM_GETCURSEL, 0, 0)); + n = unchecked((int)(long)SendMessage(NativeMethods.TCM_GETCURSEL, 0, 0)); return n; } - else { + else + { return selectedIndex; } } - set { - if (value < -1) { + set + { + if (value < -1) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(SelectedIndex), value, -1)); } - if (SelectedIndex != value) { - if (IsHandleCreated) { + if (SelectedIndex != value) + { + if (IsHandleCreated) + { // Guard Against CreateHandle .. // And also if we are setting SelectedIndex ourselves from SelectNextTab.. - if (!tabControlState[TABCONTROLSTATE_fromCreateHandles] && !tabControlState[TABCONTROLSTATE_selectFirstControl]) { + if (!tabControlState[TABCONTROLSTATE_fromCreateHandles] && !tabControlState[TABCONTROLSTATE_selectFirstControl]) + { tabControlState[TABCONTROLSTATE_UISelection] = true; // Fire Deselecting .. Deselected on currently selected TabPage... - if (WmSelChanging()) { + if (WmSelChanging()) + { tabControlState[TABCONTROLSTATE_UISelection] = false; return; } - if(ValidationCancelled) { + if (ValidationCancelled) + { tabControlState[TABCONTROLSTATE_UISelection] = false; return; } @@ -685,11 +788,13 @@ public int SelectedIndex { SendMessage(NativeMethods.TCM_SETCURSEL, value, 0); - if (!tabControlState[TABCONTROLSTATE_fromCreateHandles] && !tabControlState[TABCONTROLSTATE_selectFirstControl]) { + if (!tabControlState[TABCONTROLSTATE_fromCreateHandles] && !tabControlState[TABCONTROLSTATE_selectFirstControl]) + { // Fire Selecting & Selected .. Also if Selecting is Canceled.. // then retuern as we do not change the SelectedIndex... tabControlState[TABCONTROLSTATE_selectFirstControl] = true; - if (WmSelChange ()) { + if (WmSelChange()) + { tabControlState[TABCONTROLSTATE_UISelection] = false; tabControlState[TABCONTROLSTATE_selectFirstControl] = false; return; @@ -700,7 +805,8 @@ public int SelectedIndex { } } } - else { + else + { selectedIndex = value; } } @@ -718,27 +824,35 @@ public int SelectedIndex { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.TabControlSelectedTabDescr)) ] - public TabPage SelectedTab { - get { + public TabPage SelectedTab + { + get + { return SelectedTabInternal; } - set { + set + { SelectedTabInternal = value; } } - internal TabPage SelectedTabInternal { - get { + internal TabPage SelectedTabInternal + { + get + { int index = SelectedIndex; - if (index == -1) { + if (index == -1) + { return null; } - else { + else + { Debug.Assert(0 <= index && index < tabPages.Length, "SelectedIndex returned an invalid index"); return tabPages[index]; } } - set { + set + { int index = FindTabPage(value); SelectedIndex = index; } @@ -757,15 +871,20 @@ internal TabPage SelectedTabInternal { SRDescription(nameof(SR.TabBaseSizeModeDescr)), RefreshProperties(RefreshProperties.Repaint) ] - public TabSizeMode SizeMode { - get { + public TabSizeMode SizeMode + { + get + { return sizeMode; } - set { - if (sizeMode == value) return; + set + { + if (sizeMode == value) + return; //valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)TabSizeMode.Normal, (int)TabSizeMode.Fixed)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)TabSizeMode.Normal, (int)TabSizeMode.Fixed)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(TabSizeMode)); } @@ -784,12 +903,16 @@ public TabSizeMode SizeMode { Localizable(true), SRDescription(nameof(SR.TabBaseShowToolTipsDescr)) ] - public bool ShowToolTips { - get { + public bool ShowToolTips + { + get + { return tabControlState[TABCONTROLSTATE_showToolTips]; } - set { - if (ShowToolTips != value) { + set + { + if (ShowToolTips != value) + { tabControlState[TABCONTROLSTATE_showToolTips] = value; RecreateHandle(); } @@ -805,8 +928,9 @@ public bool ShowToolTips { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.TabBaseTabCountDescr)) ] - public int TabCount { - get { return tabPageCount;} + public int TabCount + { + get { return tabPageCount; } } /// @@ -819,42 +943,51 @@ public int TabCount { Editor("System.Windows.Forms.Design.TabPageCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), MergableProperty(false) ] - public TabPageCollection TabPages { - get { + public TabPageCollection TabPages + { + get + { return tabCollection; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Bindable(false)] - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TextChanged { + new public event EventHandler TextChanged + { add => base.TextChanged += value; remove => base.TextChanged -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.drawItemEventDescr))] - public event DrawItemEventHandler DrawItem { + public event DrawItemEventHandler DrawItem + { add => onDrawItem += value; remove => onDrawItem -= value; } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnRightToLeftLayoutChangedDescr))] - public event EventHandler RightToLeftLayoutChanged { + public event EventHandler RightToLeftLayoutChanged + { add => Events.AddHandler(EVENT_RIGHTTOLEFTLAYOUTCHANGED, value); remove => Events.RemoveHandler(EVENT_RIGHTTOLEFTLAYOUTCHANGED, value); } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.selectedIndexChangedEventDescr))] - public event EventHandler SelectedIndexChanged { + public event EventHandler SelectedIndexChanged + { add => onSelectedIndexChanged += value; remove => onSelectedIndexChanged -= value; } @@ -866,7 +999,8 @@ public event EventHandler SelectedIndexChanged { /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.TabControlSelectingEventDescr)) ] - public event TabControlCancelEventHandler Selecting { + public event TabControlCancelEventHandler Selecting + { add => Events.AddHandler(EVENT_SELECTING, value); remove => Events.RemoveHandler(EVENT_SELECTING, value); } @@ -878,7 +1012,8 @@ public event TabControlCancelEventHandler Selecting { /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.TabControlSelectedEventDescr)) ] - public event TabControlEventHandler Selected { + public event TabControlEventHandler Selected + { add => Events.AddHandler(EVENT_SELECTED, value); remove => Events.RemoveHandler(EVENT_SELECTED, value); } @@ -890,7 +1025,8 @@ public event TabControlEventHandler Selected { /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.TabControlDeselectingEventDescr)) ] - public event TabControlCancelEventHandler Deselecting { + public event TabControlCancelEventHandler Deselecting + { add => Events.AddHandler(EVENT_DESELECTING, value); remove => Events.RemoveHandler(EVENT_DESELECTING, value); } @@ -902,7 +1038,8 @@ public event TabControlCancelEventHandler Deselecting { /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.TabControlDeselectedEventDescr)) ] - public event TabControlEventHandler Deselected { + public event TabControlEventHandler Deselected + { add => Events.AddHandler(EVENT_DESELECTED, value); remove => Events.RemoveHandler(EVENT_DESELECTED, value); } @@ -912,23 +1049,27 @@ public event TabControlEventHandler Deselected { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event PaintEventHandler Paint { + public new event PaintEventHandler Paint + { add => base.Paint += value; remove => base.Paint -= value; } /// /// - internal int AddTabPage(TabPage tabPage, NativeMethods.TCITEM_T tcitem) { + internal int AddTabPage(TabPage tabPage, NativeMethods.TCITEM_T tcitem) + { int index = AddNativeTabPage(tcitem); - if (index >= 0) { + if (index >= 0) + { Insert(index, tabPage); } return index; } - internal int AddNativeTabPage(NativeMethods.TCITEM_T tcitem) { + internal int AddNativeTabPage(NativeMethods.TCITEM_T tcitem) + { int index = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TCM_INSERTITEM, tabPageCount + 1, tcitem); UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), tabBaseReLayoutMessage, IntPtr.Zero, IntPtr.Zero); return index; @@ -936,8 +1077,10 @@ internal int AddNativeTabPage(NativeMethods.TCITEM_T tcitem) { /// /// - internal void ApplyItemSize() { - if (IsHandleCreated && ShouldSerializeItemSize()) { + internal void ApplyItemSize() + { + if (IsHandleCreated && ShouldSerializeItemSize()) + { SendMessage(NativeMethods.TCM_SETITEMSIZE, 0, (int)NativeMethods.Util.MAKELPARAM(itemSize.Width, itemSize.Height)); } cachedDisplayRect = Rectangle.Empty; @@ -945,34 +1088,41 @@ internal void ApplyItemSize() { /// /// - internal void BeginUpdate() { + internal void BeginUpdate() + { BeginUpdateInternal(); } /// /// - protected override Control.ControlCollection CreateControlsInstance() { + protected override Control.ControlCollection CreateControlsInstance() + { return new ControlCollection(this); } /// /// - protected override void CreateHandle() { - if (!RecreatingHandle) { + protected override void CreateHandle() + { + if (!RecreatingHandle) + { IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); - try { + try + { NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); icc.dwICC = NativeMethods.ICC_TAB_CLASSES; SafeNativeMethods.InitCommonControlsEx(icc); } - finally { + finally + { UnsafeNativeMethods.ThemingScope.Deactivate(userCookie); } } base.CreateHandle(); } - private void DetachImageList(object sender, EventArgs e) { + private void DetachImageList(object sender, EventArgs e) + { ImageList = null; } @@ -980,13 +1130,17 @@ private void DetachImageList(object sender, EventArgs e) { /// /// Allows the user to specify the index in Tabcontrol.TabPageCollection of the tabpage to be hidden. /// - public void DeselectTab(int index) { + public void DeselectTab(int index) + { TabPage t = GetTabPage(index); - if (SelectedTab == t) { - if (0 <= index && index < TabPages.Count -1) { - SelectedTab = GetTabPage(++index); + if (SelectedTab == t) + { + if (0 <= index && index < TabPages.Count - 1) + { + SelectedTab = GetTabPage(++index); } - else { + else + { SelectedTab = GetTabPage(0); } } @@ -995,8 +1149,10 @@ public void DeselectTab(int index) { /// /// Allows the user to specify the tabpage in Tabcontrol.TabPageCollection to be hidden. /// - public void DeselectTab(TabPage tabPage) { - if (tabPage == null) { + public void DeselectTab(TabPage tabPage) + { + if (tabPage == null) + { throw new ArgumentNullException(nameof(tabPage)); } @@ -1007,8 +1163,10 @@ public void DeselectTab(TabPage tabPage) { /// /// Allows the user to specify the name of the tabpage in Tabcontrol.TabPageCollection to be hidden. /// - public void DeselectTab(string tabPageName) { - if (tabPageName == null) { + public void DeselectTab(string tabPageName) + { + if (tabPageName == null) + { throw new ArgumentNullException(nameof(tabPageName)); } @@ -1016,27 +1174,36 @@ public void DeselectTab(string tabPageName) { DeselectTab(tabPage); } - protected override void Dispose(bool disposing) { - if (disposing) { - if (imageList != null) { + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (imageList != null) + { imageList.Disposed -= new EventHandler(this.DetachImageList); } } base.Dispose(disposing); } - internal void EndUpdate() { + internal void EndUpdate() + { EndUpdate(true); } - internal void EndUpdate(bool invalidate) { + internal void EndUpdate(bool invalidate) + { EndUpdateInternal(invalidate); } - internal int FindTabPage(TabPage tabPage) { - if (tabPages != null) { - for (int i = 0; i < tabPageCount; i++) { - if (tabPages[i].Equals(tabPage)) { + internal int FindTabPage(TabPage tabPage) + { + if (tabPages != null) + { + for (int i = 0; i < tabPageCount; i++) + { + if (tabPages[i].Equals(tabPage)) + { return i; } } @@ -1046,13 +1213,16 @@ internal int FindTabPage(TabPage tabPage) { /// /// - public Control GetControl(int index) { - return(Control) GetTabPage(index); + public Control GetControl(int index) + { + return (Control)GetTabPage(index); } - internal TabPage GetTabPage(int index) { + internal TabPage GetTabPage(int index) + { - if (index < 0 || index >= tabPageCount) { + if (index < 0 || index >= tabPageCount) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } return tabPages[index]; @@ -1061,33 +1231,40 @@ internal TabPage GetTabPage(int index) { /// /// This has package scope so that TabStrip and TabControl can call it. /// - protected virtual object[] GetItems() { + protected virtual object[] GetItems() + { TabPage[] result = new TabPage[tabPageCount]; - if (tabPageCount > 0) Array.Copy(tabPages, 0, result, 0, tabPageCount); + if (tabPageCount > 0) + Array.Copy(tabPages, 0, result, 0, tabPageCount); return result; } /// /// This has package scope so that TabStrip and TabControl can call it. /// - protected virtual object[] GetItems(Type baseType) { - object[] result = (object[]) Array.CreateInstance(baseType, tabPageCount); - if (tabPageCount > 0) Array.Copy(tabPages, 0, result, 0, tabPageCount); + protected virtual object[] GetItems(Type baseType) + { + object[] result = (object[])Array.CreateInstance(baseType, tabPageCount); + if (tabPageCount > 0) + Array.Copy(tabPages, 0, result, 0, tabPageCount); return result; } - internal TabPage[] GetTabPages() { + internal TabPage[] GetTabPages() + { return (TabPage[])GetItems(); } /// /// Retrieves the bounding rectangle for the given tab in the tab strip. /// - public Rectangle GetTabRect(int index) { - if (index < 0 || (index >= tabPageCount && !tabControlState[TABCONTROLSTATE_getTabRectfromItemSize])) { + public Rectangle GetTabRect(int index) + { + if (index < 0 || (index >= tabPageCount && !tabControlState[TABCONTROLSTATE_getTabRectfromItemSize])) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - tabControlState[TABCONTROLSTATE_getTabRectfromItemSize] = false ; + tabControlState[TABCONTROLSTATE_getTabRectfromItemSize] = false; NativeMethods.RECT rect = new NativeMethods.RECT(); // normally, we would not want to create the handle for this, but since @@ -1101,34 +1278,41 @@ public Rectangle GetTabRect(int index) { /// /// - protected string GetToolTipText(object item) { - return((TabPage)item).ToolTipText; + protected string GetToolTipText(object item) + { + return ((TabPage)item).ToolTipText; } - private void ImageListRecreateHandle(object sender, EventArgs e) { + private void ImageListRecreateHandle(object sender, EventArgs e) + { if (IsHandleCreated) SendMessage(NativeMethods.TCM_SETIMAGELIST, 0, ImageList.Handle); } /// /// - internal void Insert(int index, TabPage tabPage) { - if (tabPages == null) { + internal void Insert(int index, TabPage tabPage) + { + if (tabPages == null) + { tabPages = new TabPage[4]; } - else if (tabPages.Length == tabPageCount) { + else if (tabPages.Length == tabPageCount) + { TabPage[] newTabPages = new TabPage[tabPageCount * 2]; Array.Copy(tabPages, 0, newTabPages, 0, tabPageCount); tabPages = newTabPages; } - if (index < tabPageCount) { + if (index < tabPageCount) + { Array.Copy(tabPages, index, tabPages, index + 1, tabPageCount - index); } tabPages[index] = tabPage; tabPageCount++; cachedDisplayRect = Rectangle.Empty; ApplyItemSize(); - if (Appearance == TabAppearance.FlatButtons) { + if (Appearance == TabAppearance.FlatButtons) + { Invalidate(); } } @@ -1136,7 +1320,8 @@ internal void Insert(int index, TabPage tabPage) { /// /// This function is used by the Insert Logic to insert a tabPage in the current TabPage in the TabPageCollection. /// - private void InsertItem(int index, TabPage tabPage) { + private void InsertItem(int index, TabPage tabPage) + { if (index < 0 || ((tabPages != null) && index > tabPageCount)) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); @@ -1145,10 +1330,12 @@ private void InsertItem(int index, TabPage tabPage) { int retIndex; - if (IsHandleCreated) { + if (IsHandleCreated) + { NativeMethods.TCITEM_T tcitem = tabPage.GetTCITEM(); retIndex = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TCM_INSERTITEM, index, tcitem); - if (retIndex >= 0) Insert(retIndex, tabPage); + if (retIndex >= 0) + Insert(retIndex, tabPage); } } @@ -1156,9 +1343,12 @@ private void InsertItem(int index, TabPage tabPage) { /// /// Handling special input keys, such as pgup, pgdown, home, end, etc... /// - protected override bool IsInputKey(Keys keyData) { - if ((keyData & Keys.Alt) == Keys.Alt) return false; - switch (keyData & Keys.KeyCode) { + protected override bool IsInputKey(Keys keyData) + { + if ((keyData & Keys.Alt) == Keys.Alt) + return false; + switch (keyData & Keys.KeyCode) + { case Keys.PageUp: case Keys.PageDown: case Keys.Home: @@ -1173,7 +1363,8 @@ protected override bool IsInputKey(Keys keyData) { /// We do some work here to configure the handle. /// Overriders should call base.OnHandleCreated() /// - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { //Add the handle to hashtable for Ids .. NativeWindow.AddWindowToIDTable(this, this.Handle); @@ -1182,21 +1373,25 @@ protected override void OnHandleCreated(EventArgs e) { // Set the padding BEFORE setting the control's font (as done // in base.OnHandleCreated()) so that the tab control will honor both the // horizontal and vertical dimensions of the padding rectangle. - if (!padding.IsEmpty) { + if (!padding.IsEmpty) + { SendMessage(NativeMethods.TCM_SETPADDING, 0, NativeMethods.Util.MAKELPARAM(padding.X, padding.Y)); } base.OnHandleCreated(e); cachedDisplayRect = Rectangle.Empty; ApplyItemSize(); - if (imageList != null) { + if (imageList != null) + { SendMessage(NativeMethods.TCM_SETIMAGELIST, 0, imageList.Handle); } - if (ShowToolTips) { + if (ShowToolTips) + { IntPtr tooltipHwnd; tooltipHwnd = SendMessage(NativeMethods.TCM_GETTOOLTIPS, 0, 0); - if (tooltipHwnd != IntPtr.Zero) { + if (tooltipHwnd != IntPtr.Zero) + { SafeNativeMethods.SetWindowPos(new HandleRef(this, tooltipHwnd), NativeMethods.HWND_TOPMOST, 0, 0, 0, 0, @@ -1207,7 +1402,8 @@ protected override void OnHandleCreated(EventArgs e) { // Add the pages // - foreach(TabPage page in TabPages) { + foreach (TabPage page in TabPages) + { AddNativeTabPage(page.GetTCITEM()); } @@ -1215,12 +1411,15 @@ protected override void OnHandleCreated(EventArgs e) { // ResizePages(); - if (selectedIndex != -1) { - try { + if (selectedIndex != -1) + { + try + { tabControlState[TABCONTROLSTATE_fromCreateHandles] = true; SelectedIndex = selectedIndex; } - finally { + finally + { tabControlState[TABCONTROLSTATE_fromCreateHandles] = false; } selectedIndex = -1; @@ -1228,8 +1427,10 @@ protected override void OnHandleCreated(EventArgs e) { UpdateTabSelection(false); } - protected override void OnHandleDestroyed(EventArgs e) { - if (!Disposing) { + protected override void OnHandleDestroyed(EventArgs e) + { + if (!Disposing) + { selectedIndex = SelectedIndex; } //Remove the Handle from NativewIndow.... @@ -1251,8 +1452,10 @@ protected override void OnHandleDestroyed(EventArgs e) { /// however, remember to call base.onDrawItem(e); to ensure the event is /// still fired to external listeners /// - protected virtual void OnDrawItem(DrawItemEventArgs e) { - if (onDrawItem != null) onDrawItem(this, e); + protected virtual void OnDrawItem(DrawItemEventArgs e) + { + if (onDrawItem != null) + onDrawItem(this, e); } /// @@ -1269,9 +1472,11 @@ protected virtual void OnDrawItem(DrawItemEventArgs e) { /// Focus. To be Backward compatible we have added new bool which can be set to true /// to the get the NEW SANE ENTER-LEAVE EVENTS ON THE TABPAGE. /// - protected override void OnEnter(EventArgs e) { - base.OnEnter (e); - if (SelectedTab != null) { + protected override void OnEnter(EventArgs e) + { + base.OnEnter(e); + if (SelectedTab != null) + { SelectedTab.FireEnter(e); } @@ -1291,8 +1496,10 @@ protected override void OnEnter(EventArgs e) { /// Focus. To be Backward compatible we have added new bool which can be set to true /// to the get the NEW SANE ENTER-LEAVE EVENTS ON THE TABPAGE. /// - protected override void OnLeave(EventArgs e) { - if (SelectedTab != null) { + protected override void OnLeave(EventArgs e) + { + if (SelectedTab != null) + { SelectedTab.FireLeave(e); } base.OnLeave(e); @@ -1302,15 +1509,19 @@ protected override void OnLeave(EventArgs e) { /// We override this to get tabbing functionality. /// If overriding this, remember to call base.onKeyDown. /// - protected override void OnKeyDown(KeyEventArgs ke) { - if (ke.KeyCode == Keys.Tab && (ke.KeyData & Keys.Control) !=0) { + protected override void OnKeyDown(KeyEventArgs ke) + { + if (ke.KeyCode == Keys.Tab && (ke.KeyData & Keys.Control) != 0) + { bool forward = (ke.KeyData & Keys.Shift) == 0; SelectNextTab(ke, forward); } - if (ke.KeyCode == Keys.PageDown && (ke.KeyData & Keys.Control) !=0) { + if (ke.KeyCode == Keys.PageDown && (ke.KeyData & Keys.Control) != 0) + { SelectNextTab(ke, true); } - if (ke.KeyCode == Keys.PageUp && (ke.KeyData & Keys.Control) !=0) { + if (ke.KeyCode == Keys.PageUp && (ke.KeyData & Keys.Control) != 0) + { SelectNextTab(ke, false); } @@ -1322,35 +1533,42 @@ internal override void OnParentHandleRecreated() // Avoid temporarily resizing the TabControl while the parent // recreates its handle to avoid this.skipUpdateSize = true; - try { + try + { base.OnParentHandleRecreated(); } - finally { + finally + { this.skipUpdateSize = false; } } /// /// - protected override void OnResize(EventArgs e) { + protected override void OnResize(EventArgs e) + { base.OnResize(e); cachedDisplayRect = Rectangle.Empty; UpdateTabSelection(false); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnRightToLeftLayoutChanged(EventArgs e) { - if (GetAnyDisposingInHierarchy()) { + protected virtual void OnRightToLeftLayoutChanged(EventArgs e) + { + if (GetAnyDisposingInHierarchy()) + { return; } - if (RightToLeft == RightToLeft.Yes) { + if (RightToLeft == RightToLeft.Yes) + { RecreateHandle(); } EventHandler eh = Events[EVENT_RIGHTTOLEFTLAYOUTCHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } @@ -1361,12 +1579,14 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) { /// however, remember to call base.onSelectedIndexChanged(e); to ensure the event is /// still fired to external listeners /// - protected virtual void OnSelectedIndexChanged(EventArgs e) { + protected virtual void OnSelectedIndexChanged(EventArgs e) + { int index = SelectedIndex; cachedDisplayRect = Rectangle.Empty; UpdateTabSelection(tabControlState[TABCONTROLSTATE_UISelection]); tabControlState[TABCONTROLSTATE_UISelection] = false; - if (onSelectedIndexChanged != null) onSelectedIndexChanged(this, e); + if (onSelectedIndexChanged != null) + onSelectedIndexChanged(this, e); } @@ -1376,9 +1596,11 @@ protected virtual void OnSelectedIndexChanged(EventArgs e) { /// Raises the event. /// /// - protected virtual void OnSelecting(TabControlCancelEventArgs e) { + protected virtual void OnSelecting(TabControlCancelEventArgs e) + { TabControlCancelEventHandler handler = (TabControlCancelEventHandler)Events[EVENT_SELECTING]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// @@ -1386,12 +1608,15 @@ protected virtual void OnSelecting(TabControlCancelEventArgs e) { /// Raises the event. /// /// - protected virtual void OnSelected(TabControlEventArgs e) { + protected virtual void OnSelected(TabControlEventArgs e) + { TabControlEventHandler handler = (TabControlEventHandler)Events[EVENT_SELECTED]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); // Raise the enter event for this tab. - if (SelectedTab != null) { + if (SelectedTab != null) + { SelectedTab.FireEnter(EventArgs.Empty); } @@ -1402,9 +1627,11 @@ protected virtual void OnSelected(TabControlEventArgs e) { /// Raises the event. /// /// - protected virtual void OnDeselecting(TabControlCancelEventArgs e) { + protected virtual void OnDeselecting(TabControlCancelEventArgs e) + { TabControlCancelEventHandler handler = (TabControlCancelEventHandler)Events[EVENT_DESELECTING]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } @@ -1414,12 +1641,15 @@ protected virtual void OnDeselecting(TabControlCancelEventArgs e) { /// Raises the event. /// /// - protected virtual void OnDeselected(TabControlEventArgs e) { + protected virtual void OnDeselected(TabControlEventArgs e) + { TabControlEventHandler handler = (TabControlEventHandler)Events[EVENT_DESELECTED]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); // Raise the Leave event for this tab. - if (SelectedTab != null) { + if (SelectedTab != null) + { SelectedTab.FireLeave(EventArgs.Empty); } } @@ -1427,15 +1657,19 @@ protected virtual void OnDeselected(TabControlEventArgs e) { /// /// We override this to get the Ctrl and Ctrl-Shift Tab functionality. /// - protected override bool ProcessKeyPreview(ref Message m) { - if (ProcessKeyEventArgs(ref m)) return true; + protected override bool ProcessKeyPreview(ref Message m) + { + if (ProcessKeyEventArgs(ref m)) + return true; return base.ProcessKeyPreview(ref m); } /// /// - internal void UpdateSize() { - if (this.skipUpdateSize) { + internal void UpdateSize() + { + if (this.skipUpdateSize) + { return; } // the spin control (left right arrows) won't update without resizing. @@ -1449,22 +1683,25 @@ internal void UpdateSize() { EndUpdate(); } - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { base.OnFontChanged(e); cachedDisplayRect = Rectangle.Empty; UpdateSize(); } - internal override void RecreateHandleCore() { + internal override void RecreateHandleCore() + { // TabPage[] tabPages = GetTabPages(); - int index = ((tabPages.Length > 0) && (SelectedIndex == -1)) ? 0: SelectedIndex; + int index = ((tabPages.Length > 0) && (SelectedIndex == -1)) ? 0 : SelectedIndex; // We don't actually want to remove the windows forms Tabpages - we only // want to remove the corresponding TCITEM structs. // So, no RemoveAll() - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(NativeMethods.TCM_DELETEALLITEMS, 0, 0); } this.tabPages = null; @@ -1472,14 +1709,17 @@ internal override void RecreateHandleCore() { base.RecreateHandleCore(); - for (int i = 0; i < tabPages.Length; i++) { + for (int i = 0; i < tabPages.Length; i++) + { TabPages.Add(tabPages[i]); } - try { + try + { tabControlState[TABCONTROLSTATE_fromCreateHandles] = true; SelectedIndex = index; } - finally { + finally + { tabControlState[TABCONTROLSTATE_fromCreateHandles] = false; } @@ -1489,7 +1729,8 @@ internal override void RecreateHandleCore() { UpdateSize(); } - protected void RemoveAll() { + protected void RemoveAll() + { this.Controls.Clear(); SendMessage(NativeMethods.TCM_DELETEALLITEMS, 0, 0); @@ -1499,33 +1740,40 @@ protected void RemoveAll() { /// /// - internal void RemoveTabPage(int index) { + internal void RemoveTabPage(int index) + { if (index < 0 || index >= tabPageCount) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); tabPageCount--; - if (index < tabPageCount) { + if (index < tabPageCount) + { Array.Copy(tabPages, index + 1, tabPages, index, tabPageCount - index); } tabPages[tabPageCount] = null; - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(NativeMethods.TCM_DELETEITEM, index, 0); } cachedDisplayRect = Rectangle.Empty; } - private void ResetItemSize() { + private void ResetItemSize() + { ItemSize = DEFAULT_ITEMSIZE; } - private void ResetPadding() { + private void ResetPadding() + { Padding = DEFAULT_PADDING; } - private void ResizePages() { + private void ResizePages() + { Rectangle rect = DisplayRectangle; TabPage[] pages = GetTabPages(); - for (int i = 0; i < pages.Length; i++) { + for (int i = 0; i < pages.Length; i++) + { pages[i].Bounds = rect; } } @@ -1533,7 +1781,8 @@ private void ResizePages() { /// /// Called by ToolTip to poke in that Tooltip into this ComCtl so that the Native ChildToolTip is not exposed. /// - internal void SetToolTip(ToolTip toolTip, string controlToolTipText) { + internal void SetToolTip(ToolTip toolTip, string controlToolTipText) + { UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.TCM_SETTOOLTIPS, new HandleRef(toolTip, toolTip.Handle), 0); controlTipText = controlToolTipText; @@ -1541,13 +1790,15 @@ internal void SetToolTip(ToolTip toolTip, string controlToolTipText) { /// /// - internal void SetTabPage(int index, TabPage tabPage, NativeMethods.TCITEM_T tcitem) { + internal void SetTabPage(int index, TabPage tabPage, NativeMethods.TCITEM_T tcitem) + { if (index < 0 || index >= tabPageCount) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); if (IsHandleCreated) UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TCM_SETITEM, index, tcitem); // Make the Updated tab page the currently selected tab page - if (DesignMode && IsHandleCreated) { + if (DesignMode && IsHandleCreated) + { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TCM_SETCURSEL, (IntPtr)index, IntPtr.Zero); } tabPages[index] = tabPage; @@ -1556,9 +1807,10 @@ internal void SetTabPage(int index, TabPage tabPage, NativeMethods.TCITEM_T tcit /// /// Allows the user to specify the index in Tabcontrol.TabPageCollection of the tabpage to be shown. /// - public void SelectTab(int index) { + public void SelectTab(int index) + { TabPage t = GetTabPage(index); - if(t != null) + if (t != null) { SelectedTab = t; } @@ -1567,8 +1819,10 @@ public void SelectTab(int index) { /// /// Allows the user to specify the tabpage in Tabcontrol.TabPageCollection to be shown. /// - public void SelectTab(TabPage tabPage) { - if (tabPage == null) { + public void SelectTab(TabPage tabPage) + { + if (tabPage == null) + { throw new ArgumentNullException(nameof(tabPage)); } @@ -1579,8 +1833,10 @@ public void SelectTab(TabPage tabPage) { /// /// Allows the user to specify the name of the tabpage in Tabcontrol.TabPageCollection to be shown. /// - public void SelectTab(string tabPageName) { - if (tabPageName == null) { + public void SelectTab(string tabPageName) + { + if (tabPageName == null) + { throw new ArgumentNullException(nameof(tabPageName)); } @@ -1596,30 +1852,35 @@ public void SelectTab(string tabPageName) { /// Control + PageDown selects the next tabpage. /// Control + PageUp selects the previous tabpage. /// - private void SelectNextTab(KeyEventArgs ke, bool forward) { + private void SelectNextTab(KeyEventArgs ke, bool forward) + { // WmSelChanging actually changes focus to cause validations. // So cache in the Focused value so that we can reuse it later bool focused = Focused; - + // Fire Deselecting .. Deselected on currently selected TabPage... - if (WmSelChanging()) { + if (WmSelChanging()) + { tabControlState[TABCONTROLSTATE_UISelection] = false; return; } - if(ValidationCancelled) { + if (ValidationCancelled) + { tabControlState[TABCONTROLSTATE_UISelection] = false; return; } - else { + else + { int sel = SelectedIndex; - if (sel != -1) { + if (sel != -1) + { int count = TabCount; if (forward) sel = (sel + 1) % count; else sel = (sel + count - 1) % count; - + // this is special casing.. // this function is called from OnKeyDown( ) which selects the NEXT TABPAGE @@ -1636,7 +1897,7 @@ private void SelectNextTab(KeyEventArgs ke, bool forward) { tabControlState[TABCONTROLSTATE_selectFirstControl] = !focused; // Fire Selecting .. Selected on newly selected TabPage... WmSelChange(); - + } finally { @@ -1651,25 +1912,30 @@ private void SelectNextTab(KeyEventArgs ke, bool forward) { } // TabControl overrides this method to return true. - internal override bool ShouldPerformContainerValidation() { + internal override bool ShouldPerformContainerValidation() + { return true; } - private bool ShouldSerializeItemSize() { + private bool ShouldSerializeItemSize() + { return !itemSize.Equals(DEFAULT_ITEMSIZE); } - private new bool ShouldSerializePadding() { + private new bool ShouldSerializePadding() + { return !padding.Equals(DEFAULT_PADDING); } /// /// Returns a string representation for this control. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); - if (TabPages != null) { + if (TabPages != null) + { s += ", TabPages.Count: " + TabPages.Count.ToString(CultureInfo.CurrentCulture); if (TabPages.Count > 0) s += ", TabPages[0]: " + TabPages[0].ToString(); @@ -1678,7 +1944,8 @@ public override string ToString() { } [EditorBrowsable(EditorBrowsableState.Never)] - protected override void ScaleCore(float dx, float dy) { + protected override void ScaleCore(float dx, float dy) + { currentlyScaling = true; base.ScaleCore(dx, dy); currentlyScaling = false; @@ -1689,18 +1956,22 @@ protected override void ScaleCore(float dx, float dy) { /// /// Set the panel selections appropriately /// - protected void UpdateTabSelection(bool updateFocus) { - if (IsHandleCreated) { + protected void UpdateTabSelection(bool updateFocus) + { + if (IsHandleCreated) + { int index = SelectedIndex; // make current panel invisible TabPage[] tabPages = GetTabPages(); - if (index != -1) { + if (index != -1) + { // Changing the bounds of the tabPage during scaling // will force a layout to occur. After this layout // the tabpage will then be scaled again resulting // in incorrect sizes. Suspend Layout in this case. - if (currentlyScaling) { + if (currentlyScaling) + { tabPages[index].SuspendLayout(); } tabPages[index].Bounds = DisplayRectangle; @@ -1711,22 +1982,29 @@ protected void UpdateTabSelection(bool updateFocus) { // issue, since ReSize is calling low frequence. tabPages[index].Invalidate(); - if (currentlyScaling) { + if (currentlyScaling) + { tabPages[index].ResumeLayout(false); } tabPages[index].Visible = true; - if (updateFocus) { - if (!Focused || tabControlState[TABCONTROLSTATE_selectFirstControl]) { + if (updateFocus) + { + if (!Focused || tabControlState[TABCONTROLSTATE_selectFirstControl]) + { tabControlState[TABCONTROLSTATE_UISelection] = false; bool selectNext = tabPages[index].SelectNextControl(null, true, true, false, false); - if (selectNext) { - if (!ContainsFocus) { + if (selectNext) + { + if (!ContainsFocus) + { IContainerControl c = GetContainerControl(); - if (c != null) { - while (c.ActiveControl is ContainerControl) { - c = (IContainerControl) c.ActiveControl; + if (c != null) + { + while (c.ActiveControl is ContainerControl) + { + c = (IContainerControl)c.ActiveControl; } if (c.ActiveControl != null) { @@ -1735,13 +2013,17 @@ protected void UpdateTabSelection(bool updateFocus) { } } } - else { + else + { IContainerControl c = GetContainerControl(); - if (c != null && !DesignMode) { - if (c is ContainerControl) { + if (c != null && !DesignMode) + { + if (c is ContainerControl) + { ((ContainerControl)c).SetActiveControl(this); } - else { + else + { c.ActiveControl = this; } } @@ -1749,8 +2031,10 @@ protected void UpdateTabSelection(bool updateFocus) { } } } - for (int i = 0; i < tabPages.Length; i++) { - if (i != SelectedIndex) { + for (int i = 0; i < tabPages.Length; i++) + { + if (i != SelectedIndex) + { tabPages[i].Visible = false; } } @@ -1759,7 +2043,8 @@ protected void UpdateTabSelection(bool updateFocus) { /// /// - protected override void OnStyleChanged(EventArgs e) { + protected override void OnStyleChanged(EventArgs e) + { base.OnStyleChanged(e); cachedDisplayRect = Rectangle.Empty; UpdateTabSelection(false); @@ -1769,7 +2054,8 @@ protected override void OnStyleChanged(EventArgs e) { /// /// - internal void UpdateTab(TabPage tabPage) { + internal void UpdateTab(TabPage tabPage) + { int index = FindTabPage(tabPage); SetTabPage(index, tabPage, tabPage.GetTCITEM()); @@ -1783,9 +2069,10 @@ internal void UpdateTab(TabPage tabPage) { /// /// - private void WmNeedText(ref Message m) { - - NativeMethods.TOOLTIPTEXT ttt = (NativeMethods.TOOLTIPTEXT) m.GetLParam(typeof(NativeMethods.TOOLTIPTEXT)); + private void WmNeedText(ref Message m) + { + + NativeMethods.TOOLTIPTEXT ttt = (NativeMethods.TOOLTIPTEXT)m.GetLParam(typeof(NativeMethods.TOOLTIPTEXT)); int commandID = (int)ttt.hdr.idFrom; @@ -1799,24 +2086,28 @@ private void WmNeedText(ref Message m) { // RightToLeft reading order // - if (RightToLeft == RightToLeft.Yes) { + if (RightToLeft == RightToLeft.Yes) + { ttt.uFlags |= NativeMethods.TTF_RTLREADING; } Marshal.StructureToPtr(ttt, m.LParam, false); - + } /// /// - private void WmReflectDrawItem(ref Message m) { + private void WmReflectDrawItem(ref Message m) + { NativeMethods.DRAWITEMSTRUCT dis = (NativeMethods.DRAWITEMSTRUCT)m.GetLParam(typeof(NativeMethods.DRAWITEMSTRUCT)); IntPtr oldPal = SetUpPalette(dis.hDC, false /*force*/, false /*realize*/); - using (Graphics g = Graphics.FromHdcInternal(dis.hDC)) { + using (Graphics g = Graphics.FromHdcInternal(dis.hDC)) + { OnDrawItem(new DrawItemEventArgs(g, Font, Rectangle.FromLTRB(dis.rcItem.left, dis.rcItem.top, dis.rcItem.right, dis.rcItem.bottom), dis.itemID, (DrawItemState)dis.itemState)); } - if (oldPal != IntPtr.Zero) { + if (oldPal != IntPtr.Zero) + { SafeNativeMethods.SelectPalette(new HandleRef(null, dis.hDC), new HandleRef(null, oldPal), 0); } m.Result = (IntPtr)1; @@ -1824,14 +2115,17 @@ private void WmReflectDrawItem(ref Message m) { /// /// - private bool WmSelChange() { + private bool WmSelChange() + { TabControlCancelEventArgs tcc = new TabControlCancelEventArgs(this.SelectedTab, this.SelectedIndex, false, TabControlAction.Selecting); OnSelecting(tcc); - if (!tcc.Cancel) { - OnSelected (new TabControlEventArgs (this.SelectedTab, this.SelectedIndex, TabControlAction.Selected)); + if (!tcc.Cancel) + { + OnSelected(new TabControlEventArgs(this.SelectedTab, this.SelectedIndex, TabControlAction.Selected)); OnSelectedIndexChanged(EventArgs.Empty); } - else { + else + { // user Cancelled the Selection of the new Tab. SendMessage(NativeMethods.TCM_SETCURSEL, lastSelection, 0); UpdateTabSelection(true); @@ -1841,13 +2135,17 @@ private bool WmSelChange() { /// /// - private bool WmSelChanging() { + private bool WmSelChanging() + { IContainerControl c = GetContainerControl(); - if (c != null && !DesignMode) { - if (c is ContainerControl) { + if (c != null && !DesignMode) + { + if (c is ContainerControl) + { ((ContainerControl)c).SetActiveControl(this); } - else { + else + { c.ActiveControl = this; } } @@ -1858,7 +2156,8 @@ private bool WmSelChanging() { lastSelection = SelectedIndex; TabControlCancelEventArgs tcc = new TabControlCancelEventArgs(this.SelectedTab, this.SelectedIndex, false, TabControlAction.Deselecting); OnDeselecting(tcc); - if (!tcc.Cancel) { + if (!tcc.Cancel) + { OnDeselected(new TabControlEventArgs(this.SelectedTab, this.SelectedIndex, TabControlAction.Deselected)); } return tcc.Cancel; @@ -1867,7 +2166,8 @@ private bool WmSelChanging() { /// /// - private void WmTabBaseReLayout(ref Message m) { + private void WmTabBaseReLayout(ref Message m) + { BeginUpdate(); cachedDisplayRect = Rectangle.Empty; UpdateTabSelection(false); @@ -1880,7 +2180,8 @@ private void WmTabBaseReLayout(ref Message m) { while (UnsafeNativeMethods.PeekMessage(ref msg, new HandleRef(this, hwnd), tabBaseReLayoutMessage, tabBaseReLayoutMessage, - NativeMethods.PM_REMOVE)) { + NativeMethods.PM_REMOVE)) + { ; // NULL loop } } @@ -1890,9 +2191,11 @@ private void WmTabBaseReLayout(ref Message m) { /// to add extra functionality, but should not forget to call /// base.wndProc(m); to ensure the tab continues to function properly. /// - protected override void WndProc(ref Message m) { + protected override void WndProc(ref Message m) + { - switch (m.Msg) { + switch (m.Msg) + { case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_DRAWITEM: WmReflectDrawItem(ref m); break; @@ -1903,37 +2206,43 @@ protected override void WndProc(ref Message m) { case Interop.WindowMessages.WM_NOTIFY: case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_NOTIFY: - NativeMethods.NMHDR nmhdr = (NativeMethods.NMHDR) m.GetLParam(typeof(NativeMethods.NMHDR)); - switch (nmhdr.code) { + NativeMethods.NMHDR nmhdr = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR)); + switch (nmhdr.code) + { // new switch added to prevent the TabControl from changing to next TabPage ... //in case of validation cancelled... //Turn tabControlState[TABCONTROLSTATE_UISelection] = false and Return So that no WmSelChange() gets fired. //If validation not cancelled then tabControlState[TABCONTROLSTATE_UISelection] is turned ON to set the focus on to the ... //next TabPage.. - case NativeMethods.TCN_SELCHANGING: - if (WmSelChanging()) { + case NativeMethods.TCN_SELCHANGING: + if (WmSelChanging()) + { m.Result = (IntPtr)1; tabControlState[TABCONTROLSTATE_UISelection] = false; return; } - if(ValidationCancelled) { + if (ValidationCancelled) + { m.Result = (IntPtr)1; tabControlState[TABCONTROLSTATE_UISelection] = false; return; } - else { + else + { tabControlState[TABCONTROLSTATE_UISelection] = true; } break; case NativeMethods.TCN_SELCHANGE: - if (WmSelChange ()) { + if (WmSelChange()) + { m.Result = (IntPtr)1; tabControlState[TABCONTROLSTATE_UISelection] = false; return; } - else { + else + { tabControlState[TABCONTROLSTATE_UISelection] = true; } break; @@ -1949,7 +2258,8 @@ protected override void WndProc(ref Message m) { } break; } - if (m.Msg == tabBaseReLayoutMessage) { + if (m.Msg == tabBaseReLayoutMessage) + { WmTabBaseReLayout(ref m); return; } @@ -1957,7 +2267,8 @@ protected override void WndProc(ref Message m) { } - public class TabPageCollection : IList { + public class TabPageCollection : IList + { private TabControl owner; /// A caching mechanism for key accessor /// We use an index here rather than control so that we don't have lifetime @@ -1965,36 +2276,46 @@ public class TabPageCollection : IList { private int lastAccessedIndex = -1; [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] - public TabPageCollection( TabControl owner ) { - if (owner == null) { + public TabPageCollection(TabControl owner) + { + if (owner == null) + { throw new ArgumentNullException(nameof(owner)); } this.owner = owner; } - public virtual TabPage this[int index] { - get { + public virtual TabPage this[int index] + { + get + { return owner.GetTabPage(index); } - set { + set + { owner.SetTabPage(index, value, value.GetTCITEM()); } } - object IList.this[int index] { - get { + object IList.this[int index] + { + get + { return this[index]; - } + } [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] [ SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // value is the name of the param passed in. // So we don't have to localize it. ] - set { - if (value is TabPage) { + set + { + if (value is TabPage) + { this[index] = (TabPage)value; } - else { + else + { throw new ArgumentException(nameof(value)); } } @@ -2002,19 +2323,24 @@ object IList.this[int index] { /// /// Retrieves the child control with the specified key. /// - public virtual TabPage this[string key] { - get { + public virtual TabPage this[string key] + { + get + { // We do not support null and empty string as valid keys. - if (string.IsNullOrEmpty(key)){ + if (string.IsNullOrEmpty(key)) + { return null; } // Search for the key in our collection int index = IndexOfKey(key); - if (IsValidIndex(index)) { + if (IsValidIndex(index)) + { return this[index]; } - else { + else + { return null; } @@ -2023,41 +2349,53 @@ public virtual TabPage this[string key] { [Browsable(false)] - public int Count { - get { + public int Count + { + get + { return owner.tabPageCount; } } - object ICollection.SyncRoot { - get { + object ICollection.SyncRoot + { + get + { return this; } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return false; } } - bool IList.IsFixedSize { - get { + bool IList.IsFixedSize + { + get + { return false; } } - public bool IsReadOnly { - get { + public bool IsReadOnly + { + get + { return false; } } - + [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] - public void Add(TabPage value) { + public void Add(TabPage value) + { - if (value == null) { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } @@ -2068,34 +2406,40 @@ public void Add(TabPage value) { SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // value is the name of the param passed in. // So we don't have to localize it. ] - + [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] - int IList.Add(object value) { - if (value is TabPage) { + int IList.Add(object value) + { + if (value is TabPage) + { Add((TabPage)value); return IndexOf((TabPage)value); } - else { + else + { throw new ArgumentException(nameof(value)); } } // <-- NEW ADD OVERLOADS FOR WHIDBEY - public void Add(string text) { + public void Add(string text) + { TabPage page = new TabPage(); page.Text = text; Add(page); } - public void Add(string key, string text) { + public void Add(string key, string text) + { TabPage page = new TabPage(); page.Name = key; page.Text = text; Add(page); } - public void Add(string key, string text, int imageIndex) { + public void Add(string key, string text, int imageIndex) + { TabPage page = new TabPage(); page.Name = key; page.Text = text; @@ -2103,7 +2447,8 @@ public void Add(string key, string text, int imageIndex) { Add(page); } - public void Add(string key, string text, string imageKey) { + public void Add(string key, string text, string imageKey) + { TabPage page = new TabPage(); page.Name = key; page.Text = text; @@ -2114,17 +2459,21 @@ public void Add(string key, string text, string imageKey) { // END - NEW ADD OVERLOADS FOR WHIDBEY --> [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] - public void AddRange(TabPage[] pages) { - if (pages == null) { + public void AddRange(TabPage[] pages) + { + if (pages == null) + { throw new ArgumentNullException(nameof(pages)); } - foreach(TabPage page in pages) { + foreach (TabPage page in pages) + { Add(page); } - } + } [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] - public bool Contains(TabPage page) { + public bool Contains(TabPage page) + { //check for the page not to be null if (page == null) @@ -2134,67 +2483,82 @@ public bool Contains(TabPage page) { return IndexOf(page) != -1; } - bool IList.Contains(object page) { - if (page is TabPage) { + bool IList.Contains(object page) + { + if (page is TabPage) + { return Contains((TabPage)page); } - else { + else + { return false; } } - /// - /// Returns true if the collection contains an item with the specified key, false otherwise. - /// - public virtual bool ContainsKey(string key) { + /// + /// Returns true if the collection contains an item with the specified key, false otherwise. + /// + public virtual bool ContainsKey(string key) + { return IsValidIndex(IndexOfKey(key)); - } + } [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] - public int IndexOf(TabPage page) { + public int IndexOf(TabPage page) + { //check for the page not to be null if (page == null) throw new ArgumentNullException(nameof(page)); //end check - for(int index=0; index < Count; ++index) { - if (this[index] == page) { + for (int index = 0; index < Count; ++index) + { + if (this[index] == page) + { return index; } } return -1; } - int IList.IndexOf(object page) { - if (page is TabPage) { + int IList.IndexOf(object page) + { + if (page is TabPage) + { return IndexOf((TabPage)page); } - else { + else + { return -1; } } /// /// The zero-based index of the first occurrence of value within the entire CollectionBase, if found; otherwise, -1. /// - public virtual int IndexOfKey(string key) { - // Step 0 - Arg validation - if (string.IsNullOrEmpty(key)){ + public virtual int IndexOfKey(string key) + { + // Step 0 - Arg validation + if (string.IsNullOrEmpty(key)) + { return -1; // we dont support empty or null keys. } // step 1 - check the last cached item if (IsValidIndex(lastAccessedIndex)) { - if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) { + if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) + { return lastAccessedIndex; } } // step 2 - search for the item - for (int i = 0; i < this.Count; i ++) { - if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { + for (int i = 0; i < this.Count; i++) + { + if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) + { lastAccessedIndex = i; return i; } @@ -2203,20 +2567,23 @@ public virtual int IndexOfKey(string key) { // step 3 - we didn't find it. Invalidate the last accessed index and return -1. lastAccessedIndex = -1; return -1; - } + } /// /// Inserts the supplied Tabpage at the given index. /// - public void Insert(int index, TabPage tabPage) { + public void Insert(int index, TabPage tabPage) + { owner.InsertItem(index, tabPage); - try { + try + { // See InsertingItem property owner.InsertingItem = true; owner.Controls.Add(tabPage); } - finally { + finally + { owner.InsertingItem = false; } owner.Controls.SetChildIndex(tabPage, index); @@ -2227,81 +2594,96 @@ public void Insert(int index, TabPage tabPage) { SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // tabPage is the name of the param passed in. // So we don't have to localize it. ] - void IList.Insert(int index, object tabPage) { - if (tabPage is TabPage) { + void IList.Insert(int index, object tabPage) + { + if (tabPage is TabPage) + { Insert(index, (TabPage)tabPage); } - else { + else + { throw new ArgumentException(nameof(tabPage)); } } // <-- NEW INSERT OVERLOADS FOR WHIDBEY - public void Insert(int index, string text) { + public void Insert(int index, string text) + { TabPage page = new TabPage(); page.Text = text; Insert(index, page); } - public void Insert(int index, string key, string text) { + public void Insert(int index, string key, string text) + { TabPage page = new TabPage(); page.Name = key; page.Text = text; Insert(index, page); } - public void Insert(int index, string key, string text, int imageIndex) { + public void Insert(int index, string key, string text, int imageIndex) + { TabPage page = new TabPage(); page.Name = key; page.Text = text; - Insert(index,page); - // ImageKey and ImageIndex require parenting... - page.ImageIndex = imageIndex; + Insert(index, page); + // ImageKey and ImageIndex require parenting... + page.ImageIndex = imageIndex; } - public void Insert(int index, string key, string text, string imageKey) { + public void Insert(int index, string key, string text, string imageKey) + { TabPage page = new TabPage(); page.Name = key; page.Text = text; Insert(index, page); - // ImageKey and ImageIndex require parenting... - page.ImageKey = imageKey; + // ImageKey and ImageIndex require parenting... + page.ImageKey = imageKey; } // END - NEW INSERT OVERLOADS FOR WHIDBEY --> - /// - /// Determines if the index is valid for the collection. - /// - private bool IsValidIndex(int index) { - return ((index >= 0) && (index < this.Count)); - } + /// + /// Determines if the index is valid for the collection. + /// + private bool IsValidIndex(int index) + { + return ((index >= 0) && (index < this.Count)); + } - public virtual void Clear() { + public virtual void Clear() + { owner.RemoveAll(); } - void ICollection.CopyTo(Array dest, int index) { - if (Count > 0) { + void ICollection.CopyTo(Array dest, int index) + { + if (Count > 0) + { System.Array.Copy(owner.GetTabPages(), 0, dest, index, Count); } } - public IEnumerator GetEnumerator() { + public IEnumerator GetEnumerator() + { TabPage[] tabPages = owner.GetTabPages(); - if (tabPages != null) { + if (tabPages != null) + { return tabPages.GetEnumerator(); } - else { + else + { return new TabPage[0].GetEnumerator(); } } - + [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] - public void Remove(TabPage value) { + public void Remove(TabPage value) + { //check for the value not to be null if (value == null) @@ -2310,13 +2692,16 @@ public void Remove(TabPage value) { owner.Controls.Remove(value); } - void IList.Remove(object value) { - if (value is TabPage) { + void IList.Remove(object value) + { + if (value is TabPage) + { Remove((TabPage)value); } } - public void RemoveAt(int index) { + public void RemoveAt(int index) + { owner.Controls.RemoveAt(index); } @@ -2324,11 +2709,13 @@ public void RemoveAt(int index) { /// /// Removes the child control with the specified key. /// - public virtual void RemoveByKey(string key) { + public virtual void RemoveByKey(string key) + { int index = IndexOfKey(key); - if (IsValidIndex(index)) { + if (IsValidIndex(index)) + { RemoveAt(index); - } + } } } @@ -2338,19 +2725,23 @@ public virtual void RemoveByKey(string key) { /// Collection of controls... /// [ComVisible(false)] - public new class ControlCollection : Control.ControlCollection { + public new class ControlCollection : Control.ControlCollection + { private TabControl owner; /*C#r: protected*/ public ControlCollection(TabControl owner) - : base(owner) { + : base(owner) + { this.owner = owner; } - public override void Add(Control value) { - if (!(value is TabPage)) { + public override void Add(Control value) + { + if (!(value is TabPage)) + { throw new ArgumentException(string.Format(SR.TabControlInvalidTabPageType, value.GetType().Name)); } @@ -2359,10 +2750,12 @@ public override void Add(Control value) { // See InsertingItem property if (!owner.InsertingItem) { - if (owner.IsHandleCreated) { + if (owner.IsHandleCreated) + { owner.AddTabPage(tabPage, tabPage.GetTCITEM()); } - else { + else + { owner.Insert(owner.TabCount, tabPage); } } @@ -2373,15 +2766,18 @@ public override void Add(Control value) { // Without this check, we force handle creation on the tabcontrol // which is not good at all of there are any OCXs on it. // - if (owner.IsHandleCreated) { + if (owner.IsHandleCreated) + { tabPage.Bounds = owner.DisplayRectangle; } // site the tabPage if necessary. ISite site = owner.Site; - if (site != null) { + if (site != null) + { ISite siteTab = tabPage.Site; - if (siteTab == null) { + if (siteTab == null) + { IContainer container = site.Container; if (container != null) { @@ -2394,15 +2790,18 @@ public override void Add(Control value) { } - public override void Remove(Control value) { + public override void Remove(Control value) + { base.Remove(value); - if (!(value is TabPage)) { + if (!(value is TabPage)) + { return; } int index = owner.FindTabPage((TabPage)value); int curSelectedIndex = owner.SelectedIndex; - if (index != -1) { + if (index != -1) + { owner.RemoveTabPage(index); if (index == curSelectedIndex) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TabControlCancelEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TabControlCancelEventArgs.cs index ce24faec5a4..d70431cf68f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TabControlCancelEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TabControlCancelEventArgs.cs @@ -14,7 +14,7 @@ public class TabControlCancelEventArgs : CancelEventArgs { public TabControlCancelEventArgs(TabPage tabPage, int tabPageIndex, bool cancel, TabControlAction action) : base(cancel) { - TabPage = tabPage; + TabPage = tabPage; TabPageIndex = tabPageIndex; Action = action; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TabPage.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TabPage.cs index ee9c4a913e0..ec01857001a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TabPage.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TabPage.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.ComponentModel; using System.Diagnostics; using System; @@ -26,25 +27,27 @@ namespace System.Windows.Forms { ComVisible(true), ClassInterface(ClassInterfaceType.AutoDispatch), Designer("System.Windows.Forms.Design.TabPageDesigner, " + AssemblyRef.SystemDesign), - ToolboxItem (false), - DesignTimeVisible (false), - DefaultEvent ("Click"), - DefaultProperty ("Text") + ToolboxItem(false), + DesignTimeVisible(false), + DefaultEvent("Click"), + DefaultProperty("Text") ] - public class TabPage : Panel { + public class TabPage : Panel + { private ImageList.Indexer imageIndexer; private string toolTipText = string.Empty; private bool enterFired = false; private bool leaveFired = false; private bool useVisualStyleBackColor = false; - + /// /// Constructs an empty TabPage. /// - public TabPage () - : base() { - SetStyle (ControlStyles.CacheText, true); + public TabPage() + : base() + { + SetStyle(ControlStyles.CacheText, true); Text = null; } @@ -57,11 +60,14 @@ public TabPage () Browsable(false), Localizable(false) ] - public override AutoSizeMode AutoSizeMode { - get { + public override AutoSizeMode AutoSizeMode + { + get + { return AutoSizeMode.GrowOnly; } - set { + set + { } } @@ -99,8 +105,10 @@ public override bool AutoSize SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ControlBackColorDescr)) ] - public override Color BackColor { - get { + public override Color BackColor + { + get + { Color color = base.BackColor; // If some color is Set by the user return that... if (color != DefaultBackColor) @@ -109,23 +117,29 @@ public override Color BackColor { } // If user has not set a color and if theming ON and Parent's appearance is Normal, then return the Transparent Color.... TabControl parent = ParentInternal as TabControl; - if (Application.RenderWithVisualStyles && UseVisualStyleBackColor && (parent != null && parent.Appearance == TabAppearance.Normal)) { + if (Application.RenderWithVisualStyles && UseVisualStyleBackColor && (parent != null && parent.Appearance == TabAppearance.Normal)) + { return Color.Transparent; } // return base.Color by default... return color; } - set { - if (DesignMode) { - if (value != Color.Empty) { + set + { + if (DesignMode) + { + if (value != Color.Empty) + { PropertyDescriptor pd = TypeDescriptor.GetProperties(this)["UseVisualStyleBackColor"]; Debug.Assert(pd != null); - if (pd != null) { + if (pd != null) + { pd.SetValue(this, false); } } } - else { + else + { UseVisualStyleBackColor = false; } @@ -138,15 +152,19 @@ public override Color BackColor { /// should not call base.CreateControlsInstance. Our version creates a control /// collection that does not support /// - protected override Control.ControlCollection CreateControlsInstance () { - return new TabPageControlCollection (this); + protected override Control.ControlCollection CreateControlsInstance() + { + return new TabPageControlCollection(this); } - internal ImageList.Indexer ImageIndexer { - get { - if (imageIndexer == null) { - imageIndexer = new ImageList.Indexer (); + internal ImageList.Indexer ImageIndexer + { + get + { + if (imageIndexer == null) + { + imageIndexer = new ImageList.Indexer(); } return imageIndexer; @@ -158,18 +176,21 @@ internal ImageList.Indexer ImageIndexer { /// in the TabControl's associated imageList that will appear on the tab, or be -1. /// [ - TypeConverterAttribute (typeof(ImageIndexConverter)), - Editor ("System.Windows.Forms.Design.ImageIndexEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), - Localizable (true), + TypeConverterAttribute(typeof(ImageIndexConverter)), + Editor("System.Windows.Forms.Design.ImageIndexEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), + Localizable(true), RefreshProperties(RefreshProperties.Repaint), - DefaultValue (-1), - SRDescription (nameof(SR.TabItemImageIndexDescr)) + DefaultValue(-1), + SRDescription(nameof(SR.TabItemImageIndexDescr)) ] - public int ImageIndex { - get { + public int ImageIndex + { + get + { return ImageIndexer.Index; } - set { + set + { if (value < -1) { throw new ArgumentOutOfRangeException(nameof(value), string.Format(SR.InvalidLowBoundArgumentEx, nameof(ImageIndex), value, -1)); @@ -177,12 +198,13 @@ public int ImageIndex { TabControl parent = ParentInternal as TabControl; - if (parent != null) { + if (parent != null) + { this.ImageIndexer.ImageList = parent.ImageList; } this.ImageIndexer.Index = value; - UpdateParent (); + UpdateParent(); } } @@ -191,142 +213,173 @@ public int ImageIndex { /// in the TabControl's associated imageList that will appear on the tab, or be -1. /// [ - TypeConverterAttribute (typeof(ImageKeyConverter)), - Editor ("System.Windows.Forms.Design.ImageIndexEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), - Localizable (true), - DefaultValue (""), + TypeConverterAttribute(typeof(ImageKeyConverter)), + Editor("System.Windows.Forms.Design.ImageIndexEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), + Localizable(true), + DefaultValue(""), RefreshProperties(RefreshProperties.Repaint), SRDescription(nameof(SR.TabItemImageIndexDescr)) ] - public string ImageKey { - get { + public string ImageKey + { + get + { return ImageIndexer.Key; } - set { + set + { this.ImageIndexer.Key = value; TabControl parent = ParentInternal as TabControl; - if (parent != null) { + if (parent != null) + { this.ImageIndexer.ImageList = parent.ImageList; } - UpdateParent (); + UpdateParent(); } } /// /// Constructs a TabPage with text for the tab. /// - public TabPage (string text) : this() { + public TabPage(string text) : this() + { Text = text; } - [Browsable (false), EditorBrowsable (EditorBrowsableState.Never)] - public override AnchorStyles Anchor { - get { + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + public override AnchorStyles Anchor + { + get + { return base.Anchor; } - set { + set + { base.Anchor = value; } } - [Browsable (false), EditorBrowsable (EditorBrowsableState.Never)] - public override DockStyle Dock { - get { + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + public override DockStyle Dock + { + get + { return base.Dock; } - set { + set + { base.Dock = value; } } - [Browsable (false), EditorBrowsable (EditorBrowsableState.Never)] - new public event EventHandler DockChanged { + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + new public event EventHandler DockChanged + { add => base.DockChanged += value; remove => base.DockChanged -= value; } - [Browsable (false), EditorBrowsable (EditorBrowsableState.Never)] - new public bool Enabled { - get { + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + new public bool Enabled + { + get + { return base.Enabled; } - set { + set + { base.Enabled = value; } } - [Browsable (false), EditorBrowsable (EditorBrowsableState.Never)] - new public event EventHandler EnabledChanged { + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + new public event EventHandler EnabledChanged + { add => base.EnabledChanged += value; remove => base.EnabledChanged -= value; } [ - DefaultValue (false), + DefaultValue(false), SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.TabItemUseVisualStyleBackColorDescr)) ] - public bool UseVisualStyleBackColor { - get { + public bool UseVisualStyleBackColor + { + get + { return useVisualStyleBackColor; } - set { + set + { useVisualStyleBackColor = value; this.Invalidate(true); } } - + // Make the Location property non-browsable for the TabPages. - [Browsable (false), EditorBrowsable (EditorBrowsableState.Never)] - new public Point Location { - get { + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + new public Point Location + { + get + { return base.Location; } - set { + set + { base.Location = value; } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler LocationChanged { + new public event EventHandler LocationChanged + { add => base.LocationChanged += value; remove => base.LocationChanged -= value; } [DefaultValue(typeof(Size), "0, 0")] - [Browsable (false), EditorBrowsable (EditorBrowsableState.Never)] - public override Size MaximumSize { + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + public override Size MaximumSize + { get { return base.MaximumSize; } - set { + set + { base.MaximumSize = value; } } - [Browsable (false), EditorBrowsable (EditorBrowsableState.Never)] - public override Size MinimumSize { + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + public override Size MinimumSize + { get { return base.MinimumSize; } - set { + set + { base.MinimumSize = value; } } - [Browsable (false), EditorBrowsable (EditorBrowsableState.Never)] - public new Size PreferredSize { + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + public new Size PreferredSize + { get { return base.PreferredSize; } } - [Browsable (false), EditorBrowsable (EditorBrowsableState.Never)] - new public int TabIndex { - get { + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + new public int TabIndex + { + get + { return base.TabIndex; } - set { + set + { base.TabIndex = value; } } @@ -336,51 +389,62 @@ public override Size MinimumSize { /// 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. /// - internal override bool RenderTransparencyWithVisualStyles { - get { + internal override bool RenderTransparencyWithVisualStyles + { + get + { return true; } } - [Browsable (false), EditorBrowsable (EditorBrowsableState.Never)] - new public event EventHandler TabIndexChanged { + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + new public event EventHandler TabIndexChanged + { add => base.TabIndexChanged += value; remove => base.TabIndexChanged -= value; } - [Browsable (false), EditorBrowsable (EditorBrowsableState.Never)] - new public bool TabStop { - get { + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + new public bool TabStop + { + get + { return base.TabStop; } - set { + set + { base.TabStop = value; } } - [Browsable (false), EditorBrowsable (EditorBrowsableState.Never)] - new public event EventHandler TabStopChanged { + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + new public event EventHandler TabStopChanged + { add => base.TabStopChanged += value; remove => base.TabStopChanged -= value; } [ - Localizable (true), - Browsable (true), - EditorBrowsable (EditorBrowsableState.Always) + Localizable(true), + Browsable(true), + EditorBrowsable(EditorBrowsableState.Always) ] - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; - UpdateParent (); + UpdateParent(); } } - [Browsable (true), EditorBrowsable (EditorBrowsableState.Always)] - new public event EventHandler TextChanged { + [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] + new public event EventHandler TextChanged + { add => base.TextChanged += value; remove => base.TextChanged -= value; } @@ -390,16 +454,20 @@ public override string Text { /// over the tab and the TabControl's showToolTips property is true. /// [ - DefaultValue (""), - Localizable (true), - SRDescription (nameof(SR.TabItemToolTipTextDescr)) + DefaultValue(""), + Localizable(true), + SRDescription(nameof(SR.TabItemToolTipTextDescr)) ] - public string ToolTipText { - get { + public string ToolTipText + { + get + { return toolTipText; } - set { - if (value == null) { + set + { + if (value == null) + { value = string.Empty; } @@ -407,22 +475,26 @@ public string ToolTipText { return; toolTipText = value; - UpdateParent (); + UpdateParent(); } } - [Browsable (false), EditorBrowsable (EditorBrowsableState.Never)] - new public bool Visible { - get { + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + new public bool Visible + { + get + { return base.Visible; } - set { + set + { base.Visible = value; } } - [Browsable (false), EditorBrowsable (EditorBrowsableState.Never)] - new public event EventHandler VisibleChanged { + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + new public event EventHandler VisibleChanged + { add => base.VisibleChanged += value; remove => base.VisibleChanged -= value; } @@ -431,26 +503,31 @@ public string ToolTipText { /// Assigns a new parent control. Sends out the appropriate property change /// notifications for properties that are affected by the change of parent. /// - internal override void AssignParent (Control value) { - if (value != null && !(value is TabControl)) { - throw new ArgumentException (string.Format (SR.TABCONTROLTabPageNotOnTabControl, value.GetType ().FullName)); + internal override void AssignParent(Control value) + { + if (value != null && !(value is TabControl)) + { + throw new ArgumentException(string.Format(SR.TABCONTROLTabPageNotOnTabControl, value.GetType().FullName)); } - base.AssignParent (value); + base.AssignParent(value); } /// /// Given a component, this retrieves the tab page that it's parented to, or /// null if it's not parented to any tab page. /// - public static TabPage GetTabPageOfComponent (object comp) { - if (!(comp is Control)) { + public static TabPage GetTabPageOfComponent(object comp) + { + if (!(comp is Control)) + { return null; } Control c = (Control)comp; - while (c != null && !(c is TabPage)) { + while (c != null && !(c is TabPage)) + { c = c.ParentInternal; } @@ -459,8 +536,9 @@ public static TabPage GetTabPageOfComponent (object comp) { /// /// - internal NativeMethods.TCITEM_T GetTCITEM () { - NativeMethods.TCITEM_T tcitem = new NativeMethods.TCITEM_T (); + internal NativeMethods.TCITEM_T GetTCITEM() + { + NativeMethods.TCITEM_T tcitem = new NativeMethods.TCITEM_T(); tcitem.mask = 0; tcitem.pszText = null; @@ -469,8 +547,9 @@ internal NativeMethods.TCITEM_T GetTCITEM () { string text = Text; - PrefixAmpersands (ref text); - if (text != null) { + PrefixAmpersands(ref text); + if (text != null) + { tcitem.mask |= NativeMethods.TCIF_TEXT; tcitem.pszText = text; tcitem.cchTextMax = text.Length; @@ -483,7 +562,8 @@ internal NativeMethods.TCITEM_T GetTCITEM () { return tcitem; } - private void PrefixAmpersands (ref string value) { + private void PrefixAmpersands(ref string value) + { // Due to a comctl32 problem, ampersands underline the next letter in the // text string, but the accelerators don't work. // So in this function, we prefix ampersands with another ampersand @@ -491,50 +571,58 @@ private void PrefixAmpersands (ref string value) { // // Sanity check parameter // - if (value == null || value.Length == 0) { + if (value == null || value.Length == 0) + { return; } // If there are no ampersands, we don't need to do anything here // - if (value.IndexOf ('&') < 0) { + if (value.IndexOf('&') < 0) + { return; } // Insert extra ampersands // - StringBuilder newString = new StringBuilder (); + StringBuilder newString = new StringBuilder(); - for (int i = 0; i < value.Length; ++i) { - if (value[i] == '&') { - if (i < value.Length - 1 && value[i + 1] == '&') { + for (int i = 0; i < value.Length; ++i) + { + if (value[i] == '&') + { + if (i < value.Length - 1 && value[i + 1] == '&') + { ++i; // Skip the second ampersand } - newString.Append ("&&"); + newString.Append("&&"); } - else { - newString.Append (value[i]); + else + { + newString.Append(value[i]); } } - value = newString.ToString (); + value = newString.ToString(); } /// /// This is an internal method called by the TabControl to fire the Leave event when TabControl leave occurs. /// - internal void FireLeave (EventArgs e) { + internal void FireLeave(EventArgs e) + { leaveFired = true; - OnLeave (e); + OnLeave(e); } /// /// This is an internal method called by the TabControl to fire the Enter event when TabControl leave occurs. /// - internal void FireEnter (EventArgs e) { + internal void FireEnter(EventArgs e) + { enterFired = true; - OnEnter (e); + OnEnter(e); } /// @@ -548,12 +636,15 @@ internal void FireEnter (EventArgs e) { /// TabPage should fire enter when the focus is on the TABPAGE and not when the control /// within the TabPage gets Focused. /// - protected override void OnEnter (EventArgs e) { + protected override void OnEnter(EventArgs e) + { TabControl parent = ParentInternal as TabControl; - if (parent != null) { - if (enterFired) { - base.OnEnter (e); + if (parent != null) + { + if (enterFired) + { + base.OnEnter(e); } enterFired = false; @@ -573,19 +664,23 @@ protected override void OnEnter (EventArgs e) { /// Similary the Leave should fire when the TabControl (and hence the TabPage) looses /// Focus. /// - protected override void OnLeave (EventArgs e) { + protected override void OnLeave(EventArgs e) + { TabControl parent = ParentInternal as TabControl; - if (parent != null) { - if (leaveFired) { - base.OnLeave (e); + if (parent != null) + { + if (leaveFired) + { + base.OnLeave(e); } leaveFired = false; } } - protected override void OnPaintBackground (PaintEventArgs e) { + protected override void OnPaintBackground(PaintEventArgs e) + { // Utilize the TabRenderer new to Whidbey to draw the tab pages so that the // panels are drawn using the correct visual styles when the application supports using visual @@ -595,7 +690,8 @@ protected override void OnPaintBackground (PaintEventArgs e) { // Utilize the UseVisualStyleBackColor property to determine whether or // not the themed background should be utilized. TabControl parent = ParentInternal as TabControl; - if (Application.RenderWithVisualStyles && UseVisualStyleBackColor && (parent != null && parent.Appearance == TabAppearance.Normal)) { + if (Application.RenderWithVisualStyles && UseVisualStyleBackColor && (parent != null && parent.Appearance == TabAppearance.Normal)) + { Color bkcolor = UseVisualStyleBackColor ? Color.Transparent : this.BackColor; Rectangle inflateRect = LayoutUtils.InflateRect(DisplayRectangle, Padding); @@ -618,12 +714,14 @@ protected override void OnPaintBackground (PaintEventArgs e) { // Is there a background image to paint? The TabRenderer does not currently support // painting the background image on the panel, so we need to draw it ourselves. - if (this.BackgroundImage != null) { + if (this.BackgroundImage != null) + { ControlPaint.DrawBackgroundImage(e.Graphics, BackgroundImage, bkcolor, BackgroundImageLayout, inflateRect, inflateRect, DisplayRectangle.Location); } } - else { - base.OnPaintBackground (e); + else + { + base.OnPaintBackground(e); } } @@ -631,43 +729,50 @@ protected override void OnPaintBackground (PaintEventArgs e) { /// overrides main setting of our bounds so that we can control our size and that of our /// TabPages... /// - protected override void SetBoundsCore (int x, int y, int width, int height, BoundsSpecified specified) { + protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) + { Control parent = ParentInternal; - if (parent is TabControl && parent.IsHandleCreated) { + if (parent is TabControl && parent.IsHandleCreated) + { Rectangle r = parent.DisplayRectangle; // LayoutEngines send BoundsSpecified.None so they can know they are the ones causing the size change // in the subsequent InitLayout. We need to be careful preserve a None. - base.SetBoundsCore (r.X, r.Y, r.Width, r.Height, specified == BoundsSpecified.None ? BoundsSpecified.None : BoundsSpecified.All); + base.SetBoundsCore(r.X, r.Y, r.Width, r.Height, specified == BoundsSpecified.None ? BoundsSpecified.None : BoundsSpecified.All); } - else { - base.SetBoundsCore (x, y, width, height, specified); + else + { + base.SetBoundsCore(x, y, width, height, specified); } } /// /// Determines if the Location property needs to be persisted. /// - [EditorBrowsable (EditorBrowsableState.Never)] - private bool ShouldSerializeLocation () { + [EditorBrowsable(EditorBrowsableState.Never)] + private bool ShouldSerializeLocation() + { return Left != 0 || Top != 0; } /// /// The text property is what is returned for the TabPages default printing. /// - public override string ToString () { + public override string ToString() + { return "TabPage: {" + Text + "}"; } /// /// - internal void UpdateParent () { + internal void UpdateParent() + { TabControl parent = ParentInternal as TabControl; - if (parent != null) { - parent.UpdateTab (this); + if (parent != null) + { + parent.UpdateTab(this); } } @@ -675,11 +780,13 @@ internal void UpdateParent () { /// Our control collection will throw an exception if you try to add other tab pages. /// [ComVisible(false)] - public class TabPageControlCollection : Control.ControlCollection { + public class TabPageControlCollection : Control.ControlCollection + { /// /// Creates a new TabPageControlCollection. /// - public TabPageControlCollection (TabPage owner) : base(owner) { + public TabPageControlCollection(TabPage owner) : base(owner) + { } /// @@ -689,12 +796,14 @@ public TabPageControlCollection (TabPage owner) : base(owner) { /// this method to ensure that child tab pages are not added to it, as these /// are illegal. /// - public override void Add (Control value) { - if (value is TabPage) { - throw new ArgumentException (string.Format (SR.TABCONTROLTabPageOnTabPage)); + public override void Add(Control value) + { + if (value is TabPage) + { + throw new ArgumentException(string.Format(SR.TABCONTROLTabPageOnTabPage)); } - base.Add (value); + base.Add(value); } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TabRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TabRenderer.cs index fa8870147b7..4c326ff82f5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TabRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TabRenderer.cs @@ -2,185 +2,206 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ -using System; -using System.Drawing; -using System.Diagnostics.CodeAnalysis; -using System.Windows.Forms.Internal; -using System.Windows.Forms.VisualStyles; -using Microsoft.Win32; + using System; + using System.Drawing; + using System.Diagnostics.CodeAnalysis; + using System.Windows.Forms.Internal; + using System.Windows.Forms.VisualStyles; + using Microsoft.Win32; /// /// /// This is a rendering class for the Tab control. /// /// - public sealed class TabRenderer { + public sealed class TabRenderer + { + + //Make this per-thread, so that different threads can safely use these methods. + [ThreadStatic] + private static VisualStyleRenderer visualStyleRenderer = null; - //Make this per-thread, so that different threads can safely use these methods. - [ThreadStatic] - private static VisualStyleRenderer visualStyleRenderer = null; - //cannot instantiate - private TabRenderer() { - } - - /// - /// - /// Returns true if this class is supported for the current OS and user/application settings, - /// otherwise returns false. - /// - /// - public static bool IsSupported { - get { - return VisualStyleRenderer.IsSupported; // no downlevel support - } - } - - /// - /// - /// Renders a Tab item. - /// - /// - [ - SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally - ] - public static void DrawTabItem(Graphics g, Rectangle bounds, TabItemState state) { - InitializeRenderer(VisualStyleElement.Tab.TabItem.Normal, (int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Renders a Tab item. - /// - /// - public static void DrawTabItem(Graphics g, Rectangle bounds, bool focused, TabItemState state) { - InitializeRenderer(VisualStyleElement.Tab.TabItem.Normal, (int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - - // GetBackgroundContentRectangle() returns same rectangle as bounds for this control! - Rectangle contentBounds = Rectangle.Inflate(bounds, -3, -3); - if (focused) { - ControlPaint.DrawFocusRectangle(g, contentBounds); - } - } - - /// - /// - /// Renders a Tab item. - /// - /// - public static void DrawTabItem(Graphics g, Rectangle bounds, string tabItemText, Font font, TabItemState state) { - DrawTabItem(g, bounds, tabItemText, font, false, state); - } - - /// - /// - /// Renders a Tab item. - /// - /// - public static void DrawTabItem(Graphics g, Rectangle bounds, string tabItemText, Font font, bool focused, TabItemState state) { - DrawTabItem(g, bounds, tabItemText, font, - TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine, - focused, state); - } - - /// - /// - /// Renders a Tab item. - /// - /// - public static void DrawTabItem(Graphics g, Rectangle bounds, string tabItemText, Font font, TextFormatFlags flags, bool focused, TabItemState state) { - InitializeRenderer(VisualStyleElement.Tab.TabItem.Normal, (int)state); - visualStyleRenderer.DrawBackground(g, bounds); - - // GetBackgroundContentRectangle() returns same rectangle as bounds for this control! - Rectangle contentBounds = Rectangle.Inflate(bounds, -3, -3); - Color textColor = visualStyleRenderer.GetColor(ColorProperty.TextColor); - TextRenderer.DrawText(g, tabItemText, font, contentBounds, textColor, flags); - - if (focused) { - ControlPaint.DrawFocusRectangle(g, contentBounds); - } - } - - /// - /// - /// Renders a Tab item. - /// - /// - public static void DrawTabItem(Graphics g, Rectangle bounds, Image image, Rectangle imageRectangle, bool focused, TabItemState state) { - InitializeRenderer(VisualStyleElement.Tab.TabItem.Normal, (int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - - // GetBackgroundContentRectangle() returns same rectangle as bounds for this control! - Rectangle contentBounds = Rectangle.Inflate(bounds, -3, -3); - - visualStyleRenderer.DrawImage(g, imageRectangle, image); - - if (focused) { - ControlPaint.DrawFocusRectangle(g, contentBounds); - } - } - - /// - /// - /// Renders a Tab item. - /// - /// - public static void DrawTabItem(Graphics g, Rectangle bounds, string tabItemText, Font font, Image image, Rectangle imageRectangle, bool focused, TabItemState state) { - DrawTabItem(g, bounds, tabItemText, font, - TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine, - image, imageRectangle, focused, state); - } - - /// - /// - /// Renders a Tab item. - /// - /// - public static void DrawTabItem(Graphics g, Rectangle bounds, string tabItemText, Font font, TextFormatFlags flags, Image image, Rectangle imageRectangle, bool focused, TabItemState state) { - InitializeRenderer(VisualStyleElement.Tab.TabItem.Normal, (int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - - // GetBackgroundContentRectangle() returns same rectangle as bounds for this control! - Rectangle contentBounds = Rectangle.Inflate(bounds, -3, -3); - visualStyleRenderer.DrawImage(g, imageRectangle, image); - Color textColor = visualStyleRenderer.GetColor(ColorProperty.TextColor); - TextRenderer.DrawText(g, tabItemText, font, contentBounds, textColor, flags); - - if (focused) { - ControlPaint.DrawFocusRectangle(g, contentBounds); - } - } - - /// - /// - /// Renders a TabPage. - /// - /// - [ - SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally - ] - public static void DrawTabPage(Graphics g, Rectangle bounds) { - InitializeRenderer(VisualStyleElement.Tab.Pane.Normal, 0); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - private static void InitializeRenderer(VisualStyleElement element, int state) { - if (visualStyleRenderer == null) { - visualStyleRenderer = new VisualStyleRenderer(element.ClassName, element.Part, state); - } - else { - visualStyleRenderer.SetParameters(element.ClassName, element.Part, state); - } - } + private TabRenderer() + { + } + + /// + /// + /// Returns true if this class is supported for the current OS and user/application settings, + /// otherwise returns false. + /// + /// + public static bool IsSupported + { + get + { + return VisualStyleRenderer.IsSupported; // no downlevel support + } + } + + /// + /// + /// Renders a Tab item. + /// + /// + [ + SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally + ] + public static void DrawTabItem(Graphics g, Rectangle bounds, TabItemState state) + { + InitializeRenderer(VisualStyleElement.Tab.TabItem.Normal, (int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Renders a Tab item. + /// + /// + public static void DrawTabItem(Graphics g, Rectangle bounds, bool focused, TabItemState state) + { + InitializeRenderer(VisualStyleElement.Tab.TabItem.Normal, (int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + + // GetBackgroundContentRectangle() returns same rectangle as bounds for this control! + Rectangle contentBounds = Rectangle.Inflate(bounds, -3, -3); + if (focused) + { + ControlPaint.DrawFocusRectangle(g, contentBounds); + } + } + + /// + /// + /// Renders a Tab item. + /// + /// + public static void DrawTabItem(Graphics g, Rectangle bounds, string tabItemText, Font font, TabItemState state) + { + DrawTabItem(g, bounds, tabItemText, font, false, state); + } + + /// + /// + /// Renders a Tab item. + /// + /// + public static void DrawTabItem(Graphics g, Rectangle bounds, string tabItemText, Font font, bool focused, TabItemState state) + { + DrawTabItem(g, bounds, tabItemText, font, + TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine, + focused, state); + } + + /// + /// + /// Renders a Tab item. + /// + /// + public static void DrawTabItem(Graphics g, Rectangle bounds, string tabItemText, Font font, TextFormatFlags flags, bool focused, TabItemState state) + { + InitializeRenderer(VisualStyleElement.Tab.TabItem.Normal, (int)state); + visualStyleRenderer.DrawBackground(g, bounds); + + // GetBackgroundContentRectangle() returns same rectangle as bounds for this control! + Rectangle contentBounds = Rectangle.Inflate(bounds, -3, -3); + Color textColor = visualStyleRenderer.GetColor(ColorProperty.TextColor); + TextRenderer.DrawText(g, tabItemText, font, contentBounds, textColor, flags); + + if (focused) + { + ControlPaint.DrawFocusRectangle(g, contentBounds); + } + } + + /// + /// + /// Renders a Tab item. + /// + /// + public static void DrawTabItem(Graphics g, Rectangle bounds, Image image, Rectangle imageRectangle, bool focused, TabItemState state) + { + InitializeRenderer(VisualStyleElement.Tab.TabItem.Normal, (int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + + // GetBackgroundContentRectangle() returns same rectangle as bounds for this control! + Rectangle contentBounds = Rectangle.Inflate(bounds, -3, -3); + + visualStyleRenderer.DrawImage(g, imageRectangle, image); + + if (focused) + { + ControlPaint.DrawFocusRectangle(g, contentBounds); + } + } + + /// + /// + /// Renders a Tab item. + /// + /// + public static void DrawTabItem(Graphics g, Rectangle bounds, string tabItemText, Font font, Image image, Rectangle imageRectangle, bool focused, TabItemState state) + { + DrawTabItem(g, bounds, tabItemText, font, + TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine, + image, imageRectangle, focused, state); + } + + /// + /// + /// Renders a Tab item. + /// + /// + public static void DrawTabItem(Graphics g, Rectangle bounds, string tabItemText, Font font, TextFormatFlags flags, Image image, Rectangle imageRectangle, bool focused, TabItemState state) + { + InitializeRenderer(VisualStyleElement.Tab.TabItem.Normal, (int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + + // GetBackgroundContentRectangle() returns same rectangle as bounds for this control! + Rectangle contentBounds = Rectangle.Inflate(bounds, -3, -3); + visualStyleRenderer.DrawImage(g, imageRectangle, image); + Color textColor = visualStyleRenderer.GetColor(ColorProperty.TextColor); + TextRenderer.DrawText(g, tabItemText, font, contentBounds, textColor, flags); + + if (focused) + { + ControlPaint.DrawFocusRectangle(g, contentBounds); + } + } + + /// + /// + /// Renders a TabPage. + /// + /// + [ + SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally + ] + public static void DrawTabPage(Graphics g, Rectangle bounds) + { + InitializeRenderer(VisualStyleElement.Tab.Pane.Normal, 0); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + private static void InitializeRenderer(VisualStyleElement element, int state) + { + if (visualStyleRenderer == null) + { + visualStyleRenderer = new VisualStyleRenderer(element.ClassName, element.Part, state); + } + else + { + visualStyleRenderer.SetParameters(element.ClassName, element.Part, state); + } + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutColumnStyleCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutColumnStyleCollection.cs index 54b3b8505e4..20821729748 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutColumnStyleCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutColumnStyleCollection.cs @@ -2,24 +2,27 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Drawing; - using System.Drawing.Design; + using System.Drawing.Design; using System.Globalization; using System.Windows.Forms.Layout; using System.Reflection; - public class TableLayoutColumnStyleCollection : TableLayoutStyleCollection { + public class TableLayoutColumnStyleCollection : TableLayoutStyleCollection + { - internal TableLayoutColumnStyleCollection(IArrangedElement Owner) : base(Owner) {} - internal TableLayoutColumnStyleCollection() : base(null) {} - - internal override string PropertyName { + internal TableLayoutColumnStyleCollection(IArrangedElement Owner) : base(Owner) { } + internal TableLayoutColumnStyleCollection() : base(null) { } + + internal override string PropertyName + { get { return PropertyNames.ColumnStyles; } } @@ -27,7 +30,8 @@ internal override string PropertyName { public void Insert(int index, ColumnStyle columnStyle) { ((IList)this).Insert(index, columnStyle); } - public new ColumnStyle this[int index] { + public new ColumnStyle this[int index] + { get { return (ColumnStyle)((IList)this)[index]; } set { ((IList)this)[index] = value; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanel.cs index eb1a1713acf..e09b28789cc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanel.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Collections; using System.ComponentModel; @@ -20,22 +21,25 @@ namespace System.Windows.Forms { [ProvideProperty("Row", typeof(Control))] [ProvideProperty("Column", typeof(Control))] [ProvideProperty("CellPosition", typeof(Control))] - [DefaultProperty(nameof(ColumnCount))] + [DefaultProperty(nameof(ColumnCount))] [DesignerSerializer("System.Windows.Forms.Design.TableLayoutPanelCodeDomSerializer, " + AssemblyRef.SystemDesign, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + AssemblyRef.SystemDesign)] [Docking(DockingBehavior.Never)] [Designer("System.Windows.Forms.Design.TableLayoutPanelDesigner, " + AssemblyRef.SystemDesign)] [ComVisible(true)] [ClassInterface(ClassInterfaceType.AutoDispatch)] [SRDescription(nameof(SR.DescriptionTableLayoutPanel))] - public class TableLayoutPanel : Panel, IExtenderProvider { + public class TableLayoutPanel : Panel, IExtenderProvider + { private TableLayoutSettings _tableLayoutSettings; private static readonly object EventCellPaint = new object(); - public TableLayoutPanel() { + public TableLayoutPanel() + { _tableLayoutSettings = TableLayout.CreateSettings(this); } - - public override LayoutEngine LayoutEngine { + + public override LayoutEngine LayoutEngine + { get { return TableLayout.Instance; } } @@ -44,74 +48,87 @@ public override LayoutEngine LayoutEngine { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public TableLayoutSettings LayoutSettings { - get { + public TableLayoutSettings LayoutSettings + { + get + { return _tableLayoutSettings; } - set { - if (value != null && value.IsStub) { + set + { + if (value != null && value.IsStub) + { // WINRES only scenario. // we only support table layout settings that have been created from a type converter. // this is here for localization (WinRes) support. - using (new LayoutTransaction(this, this, PropertyNames.LayoutSettings)) { + using (new LayoutTransaction(this, this, PropertyNames.LayoutSettings)) + { // apply RowStyles, ColumnStyles, Row & Column assignments. - _tableLayoutSettings.ApplySettings(value); + _tableLayoutSettings.ApplySettings(value); } } - else { + else + { throw new NotSupportedException(SR.TableLayoutSettingSettingsIsNotSupported); } - + } } - - + + [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Localizable(true) ] - public new BorderStyle BorderStyle { + public new BorderStyle BorderStyle + { get { return base.BorderStyle; } - set { - base.BorderStyle = value; + set + { + base.BorderStyle = value; Debug.Assert(BorderStyle == value, "BorderStyle should be the same as we set it"); } } [ - DefaultValue(TableLayoutPanelCellBorderStyle.None), - SRCategory(nameof(SR.CatAppearance)), + DefaultValue(TableLayoutPanelCellBorderStyle.None), + SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.TableLayoutPanelCellBorderStyleDescr)), Localizable(true) ] - public TableLayoutPanelCellBorderStyle CellBorderStyle { + public TableLayoutPanelCellBorderStyle CellBorderStyle + { get { return _tableLayoutSettings.CellBorderStyle; } - set { - _tableLayoutSettings.CellBorderStyle = value; + set + { + _tableLayoutSettings.CellBorderStyle = value; // PERF: dont turn on ResizeRedraw unless we know we need it. - if (value != TableLayoutPanelCellBorderStyle.None) { + if (value != TableLayoutPanelCellBorderStyle.None) + { SetStyle(ControlStyles.ResizeRedraw, true); - } + } this.Invalidate(); Debug.Assert(CellBorderStyle == value, "CellBorderStyle should be the same as we set it"); } } - private int CellBorderWidth { + private int CellBorderWidth + { get { return _tableLayoutSettings.CellBorderWidth; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [SRDescription(nameof(SR.ControlControlsDescr))] - public new TableLayoutControlCollection Controls { + public new TableLayoutControlCollection Controls + { get { return (TableLayoutControlCollection)base.Controls; } } - + /// /// This sets the maximum number of columns allowed on this table instead of allocating /// actual spaces for these columns. So it is OK to set ColumnCount to Int32.MaxValue without @@ -121,14 +138,16 @@ private int CellBorderWidth { [SRCategory(nameof(SR.CatLayout))] [DefaultValue(0)] [Localizable(true)] - public int ColumnCount { + public int ColumnCount + { get { return _tableLayoutSettings.ColumnCount; } - set { - _tableLayoutSettings.ColumnCount = value; + set + { + _tableLayoutSettings.ColumnCount = value; Debug.Assert(ColumnCount == value, "ColumnCount should be the same as we set it"); } } - + /// /// Specifies if a TableLayoutPanel will gain additional rows or columns once its existing cells /// become full. If the value is 'FixedSize' then the TableLayoutPanel will throw an exception @@ -137,11 +156,14 @@ public int ColumnCount { [SRDescription(nameof(SR.TableLayoutPanelGrowStyleDescr))] [SRCategory(nameof(SR.CatLayout))] [DefaultValue(TableLayoutPanelGrowStyle.AddRows)] - public TableLayoutPanelGrowStyle GrowStyle { - get { + public TableLayoutPanelGrowStyle GrowStyle + { + get + { return _tableLayoutSettings.GrowStyle; } - set { + set + { _tableLayoutSettings.GrowStyle = value; } } @@ -155,7 +177,8 @@ public TableLayoutPanelGrowStyle GrowStyle { [SRCategory(nameof(SR.CatLayout))] [DefaultValue(0)] [Localizable(true)] - public int RowCount { + public int RowCount + { get { return _tableLayoutSettings.RowCount; } set { _tableLayoutSettings.RowCount = value; } } @@ -166,7 +189,8 @@ public int RowCount { [DisplayName("Rows")] [MergableProperty(false)] [Browsable(false)] - public TableLayoutRowStyleCollection RowStyles { + public TableLayoutRowStyleCollection RowStyles + { get { return _tableLayoutSettings.RowStyles; } } @@ -175,25 +199,29 @@ public TableLayoutRowStyleCollection RowStyles { [SRCategory(nameof(SR.CatLayout))] [DisplayName("Columns")] [Browsable(false)] - [MergableProperty(false)] - public TableLayoutColumnStyleCollection ColumnStyles { + [MergableProperty(false)] + public TableLayoutColumnStyleCollection ColumnStyles + { get { return _tableLayoutSettings.ColumnStyles; } } /// /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override Control.ControlCollection CreateControlsInstance() { + protected override Control.ControlCollection CreateControlsInstance() + { return new TableLayoutControlCollection(this); } - private bool ShouldSerializeControls() { + private bool ShouldSerializeControls() + { TableLayoutControlCollection collection = this.Controls; return collection != null && collection.Count > 0; } - + #region Extended Properties - bool IExtenderProvider.CanExtend(object obj) { + bool IExtenderProvider.CanExtend(object obj) + { Control control = obj as Control; return control != null && control.Parent == this; } @@ -202,11 +230,13 @@ bool IExtenderProvider.CanExtend(object obj) { [DefaultValue(1)] [SRCategory(nameof(SR.CatLayout))] [DisplayName("ColumnSpan")] - public int GetColumnSpan(Control control) { + public int GetColumnSpan(Control control) + { return _tableLayoutSettings.GetColumnSpan(control); } - public void SetColumnSpan(Control control, int value) { + public void SetColumnSpan(Control control, int value) + { // layout.SetColumnSpan() throws ArgumentException if out of range. _tableLayoutSettings.SetColumnSpan(control, value); Debug.Assert(GetColumnSpan(control) == value, "GetColumnSpan should be the same as we set it"); @@ -216,11 +246,13 @@ public void SetColumnSpan(Control control, int value) { [DefaultValue(1)] [SRCategory(nameof(SR.CatLayout))] [DisplayName("RowSpan")] - public int GetRowSpan(Control control) { + public int GetRowSpan(Control control) + { return _tableLayoutSettings.GetRowSpan(control); } - - public void SetRowSpan(Control control, int value) { + + public void SetRowSpan(Control control, int value) + { // layout.SetRowSpan() throws ArgumentException if out of range. _tableLayoutSettings.SetRowSpan(control, value); Debug.Assert(GetRowSpan(control) == value, "GetRowSpan should be the same as we set it"); @@ -232,12 +264,14 @@ public void SetRowSpan(Control control, int value) { [SRCategory(nameof(SR.CatLayout))] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [DisplayName("Row")] - public int GetRow(Control control) { + public int GetRow(Control control) + { return _tableLayoutSettings.GetRow(control); } //set the row position of the control - public void SetRow(Control control, int row) { + public void SetRow(Control control, int row) + { _tableLayoutSettings.SetRow(control, row); Debug.Assert(GetRow(control) == row, "GetRow should be the same as we set it"); } @@ -248,16 +282,18 @@ public void SetRow(Control control, int row) { [SRCategory(nameof(SR.CatLayout))] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [DisplayName("Cell")] - public TableLayoutPanelCellPosition GetCellPosition(Control control) { + public TableLayoutPanelCellPosition GetCellPosition(Control control) + { return _tableLayoutSettings.GetCellPosition(control); } //set the row and column of the control - public void SetCellPosition(Control control, TableLayoutPanelCellPosition position) { + public void SetCellPosition(Control control, TableLayoutPanelCellPosition position) + { _tableLayoutSettings.SetCellPosition(control, position); } - + //get the column position of the control [DefaultValue(-1)] //if change this value, also change the SerializeViaAdd in TableLayoutControlCollectionCodeDomSerializer @@ -265,69 +301,80 @@ public void SetCellPosition(Control control, TableLayoutPanelCellPosition positi [SRCategory(nameof(SR.CatLayout))] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [DisplayName("Column")] - public int GetColumn(Control control) { + public int GetColumn(Control control) + { return _tableLayoutSettings.GetColumn(control); } - + //set the column position of the control - public void SetColumn(Control control, int column) { + public void SetColumn(Control control, int column) + { _tableLayoutSettings.SetColumn(control, column); Debug.Assert(GetColumn(control) == column, "GetColumn should be the same as we set it"); } - + /// /// get the control which covers the specified row and column. return null if we can't find one /// - public Control GetControlFromPosition (int column, int row) { + public Control GetControlFromPosition(int column, int row) + { return (Control)_tableLayoutSettings.GetControlFromPosition(column, row); } [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Control instead of IArrangedElement intentionally - public TableLayoutPanelCellPosition GetPositionFromControl (Control control) { + public TableLayoutPanelCellPosition GetPositionFromControl(Control control) + { return _tableLayoutSettings.GetPositionFromControl(control); } - + /// /// This returns an array representing the widths (in pixels) of the columns in the TableLayoutPanel. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public int[] GetColumnWidths() { - TableLayout.ContainerInfo containerInfo = TableLayout.GetContainerInfo(this); - if (containerInfo.Columns == null) { - return new int[0]; - } - - int[] cw = new int[containerInfo.Columns.Length]; - for(int i = 0; i < containerInfo.Columns.Length; i++) { - cw[i] = containerInfo.Columns[i].MinSize; - } - return cw; - } - + public int[] GetColumnWidths() + { + TableLayout.ContainerInfo containerInfo = TableLayout.GetContainerInfo(this); + if (containerInfo.Columns == null) + { + return new int[0]; + } + + int[] cw = new int[containerInfo.Columns.Length]; + for (int i = 0; i < containerInfo.Columns.Length; i++) + { + cw[i] = containerInfo.Columns[i].MinSize; + } + return cw; + } + /// /// This returns an array representing the heights (in pixels) of the rows in the TableLayoutPanel. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public int[] GetRowHeights() { + public int[] GetRowHeights() + { TableLayout.ContainerInfo containerInfo = TableLayout.GetContainerInfo(this); - if (containerInfo.Rows == null) { + if (containerInfo.Rows == null) + { return new int[0]; } - + int[] rh = new int[containerInfo.Rows.Length]; - for(int i = 0; i < containerInfo.Rows.Length; i++) { + for (int i = 0; i < containerInfo.Rows.Length; i++) + { rh[i] = containerInfo.Rows[i].MinSize; } return rh; } - + #endregion #region PaintCode [SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.TableLayoutPanelOnPaintCellDescr))] - public event TableLayoutCellPaintEventHandler CellPaint { + public event TableLayoutCellPaintEventHandler CellPaint + { add => Events.AddHandler(EventCellPaint, value); remove => Events.RemoveHandler(EventCellPaint, value); } @@ -337,35 +384,40 @@ public event TableLayoutCellPaintEventHandler CellPaint { /// cell borders. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnLayout(LayoutEventArgs levent) { + protected override void OnLayout(LayoutEventArgs levent) + { base.OnLayout(levent); this.Invalidate(); } - - protected virtual void OnCellPaint(TableLayoutCellPaintEventArgs e) { + + protected virtual void OnCellPaint(TableLayoutCellPaintEventArgs e) + { TableLayoutCellPaintEventHandler handler = (TableLayoutCellPaintEventHandler)Events[EventCellPaint]; - if (handler != null) { + if (handler != null) + { handler(this, e); } } - - protected override void OnPaintBackground(PaintEventArgs e) { + + protected override void OnPaintBackground(PaintEventArgs e) + { base.OnPaintBackground(e); - - + + // paint borderstyles on top of the background image in WM_ERASEBKGND - + int cellBorderWidth = this.CellBorderWidth; TableLayout.ContainerInfo containerInfo = TableLayout.GetContainerInfo(this); TableLayout.Strip[] colStrips = containerInfo.Columns; TableLayout.Strip[] rowStrips = containerInfo.Rows; TableLayoutPanelCellBorderStyle cellBorderStyle = this.CellBorderStyle; - - - if (colStrips == null || rowStrips == null) { + + + if (colStrips == null || rowStrips == null) + { return; } int cols = colStrips.Length; @@ -378,136 +430,164 @@ protected override void OnPaintBackground(PaintEventArgs e) { Rectangle clipRect = e.ClipRectangle; //leave the space for the border - int startx; + int startx; bool isRTL = (RightToLeft == RightToLeft.Yes); - if (isRTL) { + if (isRTL) + { startx = displayRect.Right - (cellBorderWidth / 2); } - else { - startx = displayRect.X + (cellBorderWidth / 2); + else + { + startx = displayRect.X + (cellBorderWidth / 2); } - - for (int i = 0; i < cols; i++) { + + for (int i = 0; i < cols; i++) + { int starty = displayRect.Y + (cellBorderWidth / 2); - if (isRTL) { + if (isRTL) + { startx -= colStrips[i].MinSize; } - - for (int j = 0; j < rows; j++) { - Rectangle outsideCellBounds = new Rectangle(startx, starty, ((TableLayout.Strip)colStrips[i]).MinSize, ((TableLayout.Strip)rowStrips[j]).MinSize); - - Rectangle insideCellBounds = new Rectangle(outsideCellBounds.X + (cellBorderWidth + 1) / 2, outsideCellBounds.Y + (cellBorderWidth + 1)/ 2, outsideCellBounds.Width - (cellBorderWidth + 1) / 2, outsideCellBounds.Height - (cellBorderWidth + 1) / 2); - if (clipRect.IntersectsWith(insideCellBounds)) { + for (int j = 0; j < rows; j++) + { + Rectangle outsideCellBounds = new Rectangle(startx, starty, ((TableLayout.Strip)colStrips[i]).MinSize, ((TableLayout.Strip)rowStrips[j]).MinSize); + + Rectangle insideCellBounds = new Rectangle(outsideCellBounds.X + (cellBorderWidth + 1) / 2, outsideCellBounds.Y + (cellBorderWidth + 1) / 2, outsideCellBounds.Width - (cellBorderWidth + 1) / 2, outsideCellBounds.Height - (cellBorderWidth + 1) / 2); + + if (clipRect.IntersectsWith(insideCellBounds)) + { //first, call user's painting code - using (TableLayoutCellPaintEventArgs pcea = new TableLayoutCellPaintEventArgs(g, clipRect, insideCellBounds, i, j)) { + using (TableLayoutCellPaintEventArgs pcea = new TableLayoutCellPaintEventArgs(g, clipRect, insideCellBounds, i, j)) + { OnCellPaint(pcea); } // paint the table border on top. - ControlPaint.PaintTableCellBorder(cellBorderStyle, g, outsideCellBounds); + ControlPaint.PaintTableCellBorder(cellBorderStyle, g, outsideCellBounds); } starty += rowStrips[j].MinSize; // Only sum this up once... - if (i == 0) { + if (i == 0) + { totalColumnHeights += rowStrips[j].MinSize; } } - - if (!isRTL) { + + if (!isRTL) + { startx += colStrips[i].MinSize; - } + } totalColumnWidths += colStrips[i].MinSize; } - - if (!HScroll && !VScroll && cellBorderStyle != TableLayoutPanelCellBorderStyle.None) { - Rectangle tableBounds = new Rectangle(cellBorderWidth/2 + displayRect.X, cellBorderWidth/2 + displayRect.Y, displayRect.Width - cellBorderWidth, displayRect.Height - cellBorderWidth); + + if (!HScroll && !VScroll && cellBorderStyle != TableLayoutPanelCellBorderStyle.None) + { + Rectangle tableBounds = new Rectangle(cellBorderWidth / 2 + displayRect.X, cellBorderWidth / 2 + displayRect.Y, displayRect.Width - cellBorderWidth, displayRect.Height - cellBorderWidth); // paint the border of the table if we are not auto scrolling. // if the borderStyle is Inset or Outset, we can only paint the lower bottom half since otherwise we will have 1 pixel loss at the border. - if (cellBorderStyle == TableLayoutPanelCellBorderStyle.Inset) { + if (cellBorderStyle == TableLayoutPanelCellBorderStyle.Inset) + { g.DrawLine(SystemPens.ControlDark, tableBounds.Right, tableBounds.Y, tableBounds.Right, tableBounds.Bottom); g.DrawLine(SystemPens.ControlDark, tableBounds.X, tableBounds.Y + tableBounds.Height - 1, tableBounds.X + tableBounds.Width - 1, tableBounds.Y + tableBounds.Height - 1); } - else if (cellBorderStyle == TableLayoutPanelCellBorderStyle.Outset) { - using (Pen pen = new Pen(SystemColors.Window)) { + else if (cellBorderStyle == TableLayoutPanelCellBorderStyle.Outset) + { + using (Pen pen = new Pen(SystemColors.Window)) + { g.DrawLine(pen, tableBounds.X + tableBounds.Width - 1, tableBounds.Y, tableBounds.X + tableBounds.Width - 1, tableBounds.Y + tableBounds.Height - 1); g.DrawLine(pen, tableBounds.X, tableBounds.Y + tableBounds.Height - 1, tableBounds.X + tableBounds.Width - 1, tableBounds.Y + tableBounds.Height - 1); } } - else { - ControlPaint.PaintTableCellBorder(cellBorderStyle, g, tableBounds); + else + { + ControlPaint.PaintTableCellBorder(cellBorderStyle, g, tableBounds); } ControlPaint.PaintTableControlBorder(cellBorderStyle, g, displayRect); } - else { + else + { ControlPaint.PaintTableControlBorder(cellBorderStyle, g, displayRect); } - + } [EditorBrowsable(EditorBrowsableState.Never)] - protected override void ScaleCore(float dx, float dy) { + protected override void ScaleCore(float dx, float dy) + { base.ScaleCore(dx, dy); - ScaleAbsoluteStyles(new SizeF(dx,dy)); + ScaleAbsoluteStyles(new SizeF(dx, dy)); } /// /// Scale this form. Form overrides this to enforce a maximum / minimum size. /// - protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { + protected override void ScaleControl(SizeF factor, BoundsSpecified specified) + { base.ScaleControl(factor, specified); - ScaleAbsoluteStyles(factor); + ScaleAbsoluteStyles(factor); } - private void ScaleAbsoluteStyles(SizeF factor) { + private void ScaleAbsoluteStyles(SizeF factor) + { TableLayout.ContainerInfo containerInfo = TableLayout.GetContainerInfo(this); int i = 0; - - // The last row/column can be larger than the - // absolutely styled column width. - int lastRowHeight = -1; - int lastRow = containerInfo.Rows.Length -1; - if (containerInfo.Rows.Length > 0) { + + // The last row/column can be larger than the + // absolutely styled column width. + int lastRowHeight = -1; + int lastRow = containerInfo.Rows.Length - 1; + if (containerInfo.Rows.Length > 0) + { lastRowHeight = containerInfo.Rows[lastRow].MinSize; - } - - int lastColumnHeight = -1; - int lastColumn = containerInfo.Columns.Length -1; - if (containerInfo.Columns.Length > 0) { - lastColumnHeight = containerInfo.Columns[containerInfo.Columns.Length -1].MinSize; - } - - foreach(ColumnStyle cs in ColumnStyles) { - if (cs.SizeType == SizeType.Absolute){ - if (i == lastColumn && lastColumnHeight > 0) { - // the last column is typically expanded to fill the table. use the actual - // width in this case. - cs.Width = (float)Math.Round(lastColumnHeight * factor.Width); - } - else { - cs.Width = (float)Math.Round(cs.Width * factor.Width); - } - } - i++; - } - - i = 0; - - foreach(RowStyle rs in RowStyles) { - if (rs.SizeType == SizeType.Absolute) { - if (i == lastRow && lastRowHeight > 0) { - // the last row is typically expanded to fill the table. use the actual - // width in this case. - rs.Height = (float)Math.Round(lastRowHeight * factor.Height); - } - else { - rs.Height = (float)Math.Round(rs.Height * factor.Height); - } - } - } + } + + int lastColumnHeight = -1; + int lastColumn = containerInfo.Columns.Length - 1; + if (containerInfo.Columns.Length > 0) + { + lastColumnHeight = containerInfo.Columns[containerInfo.Columns.Length - 1].MinSize; + } + + foreach (ColumnStyle cs in ColumnStyles) + { + if (cs.SizeType == SizeType.Absolute) + { + if (i == lastColumn && lastColumnHeight > 0) + { + // the last column is typically expanded to fill the table. use the actual + // width in this case. + cs.Width = (float)Math.Round(lastColumnHeight * factor.Width); + } + else + { + cs.Width = (float)Math.Round(cs.Width * factor.Width); + } + } + i++; + } + + i = 0; + + foreach (RowStyle rs in RowStyles) + { + if (rs.SizeType == SizeType.Absolute) + { + if (i == lastRow && lastRowHeight > 0) + { + // the last row is typically expanded to fill the table. use the actual + // width in this case. + rs.Height = (float)Math.Round(lastRowHeight * factor.Height); + } + else + { + rs.Height = (float)Math.Round(rs.Height * factor.Height); + } + } + } } @@ -539,4 +619,4 @@ public virtual void Add(Control control, int column, int row) Container.SetRow(control, row); } } -} +} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanelCellPosition.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanelCellPosition.cs index 279693edfc5..20bcdcd9aa0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanelCellPosition.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanelCellPosition.cs @@ -91,7 +91,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c { return null; } - + // Parse 2 integer values. if (culture == null) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutRowStyleCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutRowStyleCollection.cs index 561684bdaba..1de30ee6e29 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutRowStyleCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutRowStyleCollection.cs @@ -2,32 +2,36 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Drawing; - using System.Drawing.Design; + using System.Drawing.Design; using System.Globalization; using System.Windows.Forms.Layout; using System.Reflection; - - public class TableLayoutRowStyleCollection : TableLayoutStyleCollection { - internal TableLayoutRowStyleCollection(IArrangedElement Owner) : base(Owner) {} - internal TableLayoutRowStyleCollection() : base(null) {} + public class TableLayoutRowStyleCollection : TableLayoutStyleCollection + { - internal override string PropertyName { + internal TableLayoutRowStyleCollection(IArrangedElement Owner) : base(Owner) { } + internal TableLayoutRowStyleCollection() : base(null) { } + + internal override string PropertyName + { get { return PropertyNames.RowStyles; } } public int Add(RowStyle rowStyle) { return ((IList)this).Add(rowStyle); } - + public void Insert(int index, RowStyle rowStyle) { ((IList)this).Insert(index, rowStyle); } - - public new RowStyle this[int index] { + + public new RowStyle this[int index] + { get { return (RowStyle)((IList)this)[index]; } set { ((IList)this)[index] = value; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettings.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettings.cs index 52f92a6ff69..8b0528955f5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettings.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettings.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Collections; using System.Collections.Generic; @@ -11,19 +12,20 @@ namespace System.Windows.Forms { using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; - using System.Drawing.Design; + using System.Drawing.Design; using System.Globalization; using System.Windows.Forms.Layout; using System.Reflection; using System.Runtime.Serialization; - + /// this is a wrapper class to expose interesting properties of TableLayout [ TypeConverter(typeof(TableLayoutSettingsTypeConverter)), Serializable ] - public sealed class TableLayoutSettings : LayoutSettings, ISerializable { - + public sealed class TableLayoutSettings : LayoutSettings, ISerializable + { + static private int[] borderStyleToOffset = { /*None = */ 0, @@ -36,46 +38,55 @@ public sealed class TableLayoutSettings : LayoutSettings, ISerializable { }; private TableLayoutPanelCellBorderStyle _borderStyle; private TableLayoutSettingsStub _stub; - + // used by TableLayoutSettingsTypeConverter - internal TableLayoutSettings() : base(null){ + internal TableLayoutSettings() : base(null) + { _stub = new TableLayoutSettingsStub(); } - internal TableLayoutSettings(IArrangedElement owner) : base(owner) {} + internal TableLayoutSettings(IArrangedElement owner) : base(owner) { } [SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters")] - internal TableLayoutSettings(SerializationInfo serializationInfo, StreamingContext context) : this() { + internal TableLayoutSettings(SerializationInfo serializationInfo, StreamingContext context) : this() + { TypeConverter converter = TypeDescriptor.GetConverter(this); string stringVal = serializationInfo.GetString("SerializedString"); - if (!string.IsNullOrEmpty(stringVal)) { + if (!string.IsNullOrEmpty(stringVal)) + { TableLayoutSettings tls = converter.ConvertFromInvariantString(stringVal) as TableLayoutSettings; - if (tls != null) { + if (tls != null) + { this.ApplySettings(tls); } } } - - public override LayoutEngine LayoutEngine { + + public override LayoutEngine LayoutEngine + { get { return TableLayout.Instance; } } - private TableLayout TableLayout { - get { return (TableLayout) this.LayoutEngine; } + private TableLayout TableLayout + { + get { return (TableLayout)this.LayoutEngine; } } - + /// internal as this is a TableLayoutPanel feature only [DefaultValue(TableLayoutPanelCellBorderStyle.None), SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.TableLayoutPanelCellBorderStyleDescr))] - internal TableLayoutPanelCellBorderStyle CellBorderStyle { + internal TableLayoutPanelCellBorderStyle CellBorderStyle + { get { return _borderStyle; } - set { + set + { //valid values are 0x0 to 0x6 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)TableLayoutPanelCellBorderStyle.None, (int)TableLayoutPanelCellBorderStyle.OutsetPartial)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)TableLayoutPanelCellBorderStyle.None, (int)TableLayoutPanelCellBorderStyle.OutsetPartial)) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(CellBorderStyle), value)); } - _borderStyle = value; + _borderStyle = value; //set the CellBorderWidth according to the current CellBorderStyle. TableLayout.ContainerInfo containerInfo = TableLayout.GetContainerInfo(Owner); containerInfo.CellBorderWidth = borderStyleToOffset[(int)value]; @@ -85,10 +96,11 @@ internal TableLayoutPanelCellBorderStyle CellBorderStyle { } [DefaultValue(0)] - internal int CellBorderWidth { + internal int CellBorderWidth + { get { return TableLayout.GetContainerInfo(Owner).CellBorderWidth; } } - + /// /// This sets the maximum number of columns allowed on this table instead of allocating /// actual spaces for these columns. So it is OK to set ColumnCount to Int32.MaxValue without @@ -97,22 +109,25 @@ internal int CellBorderWidth { [SRDescription(nameof(SR.GridPanelColumnsDescr))] [SRCategory(nameof(SR.CatLayout))] [DefaultValue(0)] - public int ColumnCount { - get { + public int ColumnCount + { + get + { TableLayout.ContainerInfo containerInfo = TableLayout.GetContainerInfo(Owner); return containerInfo.MaxColumns; } - set { + set + { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(ColumnCount), value, 0)); } - TableLayout.ContainerInfo containerInfo = TableLayout.GetContainerInfo(Owner); + TableLayout.ContainerInfo containerInfo = TableLayout.GetContainerInfo(Owner); containerInfo.MaxColumns = value; LayoutTransaction.DoLayout(Owner, Owner, PropertyNames.Columns); Debug.Assert(ColumnCount == value, "the max columns should equal to the value we set it to"); - + } } @@ -124,12 +139,15 @@ public int ColumnCount { [SRDescription(nameof(SR.GridPanelRowsDescr))] [SRCategory(nameof(SR.CatLayout))] [DefaultValue(0)] - public int RowCount { - get { + public int RowCount + { + get + { TableLayout.ContainerInfo containerInfo = TableLayout.GetContainerInfo(Owner); return containerInfo.MaxRows; } - set { + set + { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(RowCount), value, 0)); @@ -139,19 +157,23 @@ public int RowCount { containerInfo.MaxRows = value; LayoutTransaction.DoLayout(Owner, Owner, PropertyNames.Rows); Debug.Assert(RowCount == value, "the max rows should equal to the value we set it to"); - + } } [SRDescription(nameof(SR.GridPanelRowStylesDescr))] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [SRCategory(nameof(SR.CatLayout))] - public TableLayoutRowStyleCollection RowStyles { - get { - if (IsStub) { + public TableLayoutRowStyleCollection RowStyles + { + get + { + if (IsStub) + { return _stub.RowStyles; } - else { + else + { TableLayout.ContainerInfo containerInfo = TableLayout.GetContainerInfo(Owner); return containerInfo.RowStyles; } @@ -161,12 +183,16 @@ public TableLayoutRowStyleCollection RowStyles { [SRDescription(nameof(SR.GridPanelColumnStylesDescr))] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [SRCategory(nameof(SR.CatLayout))] - public TableLayoutColumnStyleCollection ColumnStyles { - get { - if (IsStub) { + public TableLayoutColumnStyleCollection ColumnStyles + { + get + { + if (IsStub) + { return _stub.ColumnStyles; } - else { + else + { TableLayout.ContainerInfo containerInfo = TableLayout.GetContainerInfo(Owner); return containerInfo.ColumnStyles; } @@ -181,46 +207,58 @@ public TableLayoutColumnStyleCollection ColumnStyles { [SRDescription(nameof(SR.TableLayoutPanelGrowStyleDescr))] [SRCategory(nameof(SR.CatLayout))] [DefaultValue(TableLayoutPanelGrowStyle.AddRows)] - public TableLayoutPanelGrowStyle GrowStyle { - get { + public TableLayoutPanelGrowStyle GrowStyle + { + get + { return TableLayout.GetContainerInfo(Owner).GrowStyle; - } - - set { + } + + set + { //valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)TableLayoutPanelGrowStyle.FixedSize, (int)TableLayoutPanelGrowStyle.AddColumns)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)TableLayoutPanelGrowStyle.FixedSize, (int)TableLayoutPanelGrowStyle.AddColumns)) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(GrowStyle), value)); - } - + } + TableLayout.ContainerInfo containerInfo = TableLayout.GetContainerInfo(Owner); - if (containerInfo.GrowStyle != value) { + if (containerInfo.GrowStyle != value) + { containerInfo.GrowStyle = value; LayoutTransaction.DoLayout(Owner, Owner, PropertyNames.GrowStyle); } } } - internal bool IsStub { - get { - if ( _stub != null) { + internal bool IsStub + { + get + { + if (_stub != null) + { return true; } return false; } } - internal void ApplySettings(TableLayoutSettings settings) { - if (settings.IsStub) { - if (!IsStub) { - // we're the real-live thing here, gotta walk through and touch controls - settings._stub.ApplySettings(this); + internal void ApplySettings(TableLayoutSettings settings) + { + if (settings.IsStub) + { + if (!IsStub) + { + // we're the real-live thing here, gotta walk through and touch controls + settings._stub.ApplySettings(this); } - else { - // we're just copying another stub into us, just replace the member - _stub = settings._stub; + else + { + // we're just copying another stub into us, just replace the member + _stub = settings._stub; } } - + } #region Extended Properties @@ -260,7 +298,7 @@ public void SetColumnSpan(object control, int value) } else { - IArrangedElement element = LayoutEngine.CastToArrangedElement(control); + IArrangedElement element = LayoutEngine.CastToArrangedElement(control); if (element.Container != null) { TableLayout.ClearCachedAssignments(TableLayout.GetContainerInfo(element.Container)); @@ -269,7 +307,7 @@ public void SetColumnSpan(object control, int value) LayoutTransaction.DoLayout(element.Container, element, PropertyNames.ColumnSpan); Debug.Assert(GetColumnSpan(element) == value, "column span should equal to the value we set"); } - + } public int GetRowSpan(object control) @@ -289,7 +327,7 @@ public int GetRowSpan(object control) return TableLayout.GetLayoutInfo(element).RowSpan; } } - + public void SetRowSpan(object control, int value) { if (control == null) @@ -339,7 +377,7 @@ public int GetRow(object control) { IArrangedElement element = LayoutEngine.CastToArrangedElement(control); TableLayout.LayoutInfo layoutInfo = TableLayout.GetLayoutInfo(element); - return layoutInfo.RowPosition; + return layoutInfo.RowPosition; } } @@ -415,10 +453,10 @@ public int GetColumn(object control) { IArrangedElement element = LayoutEngine.CastToArrangedElement(control); TableLayout.LayoutInfo layoutInfo = TableLayout.GetLayoutInfo(element); - return layoutInfo.ColumnPosition; - } + return layoutInfo.ColumnPosition; + } } - + /// /// Set the column position of the element /// If we set the column position to -1, it will automatically switch the control from @@ -445,7 +483,7 @@ public void SetColumn(object control, int column) } } - private void SetCellPosition(object control, int row, int column, bool rowSpecified, bool colSpecified) + private void SetCellPosition(object control, int row, int column, bool rowSpecified, bool colSpecified) { if (IsStub) { @@ -479,47 +517,55 @@ private void SetCellPosition(object control, int row, int column, bool rowSpeci Debug.Assert(!rowSpecified || GetRow(element) == row, "row position shoule equal to what we set"); } } - + /// /// Get the element which covers the specified row and column. return null if we can't find one /// - internal IArrangedElement GetControlFromPosition (int column, int row) + internal IArrangedElement GetControlFromPosition(int column, int row) { return TableLayout.GetControlFromPosition(Owner, column, row); } - internal TableLayoutPanelCellPosition GetPositionFromControl (IArrangedElement element) + internal TableLayoutPanelCellPosition GetPositionFromControl(IArrangedElement element) { return TableLayout.GetPositionFromControl(Owner, element); } - + #endregion - - void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) { + + void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) + { TypeConverter converter = TypeDescriptor.GetConverter(this); string stringVal = converter.ConvertToInvariantString(this); - - if (!string.IsNullOrEmpty(stringVal)) { + + if (!string.IsNullOrEmpty(stringVal)) + { si.AddValue("SerializedString", stringVal); } } - internal List GetControlsInformation() { - if (IsStub) { - return _stub.GetControlsInformation(); - } - else { + internal List GetControlsInformation() + { + if (IsStub) + { + return _stub.GetControlsInformation(); + } + else + { List controlsInfo = new List(Owner.Children.Count); - foreach (IArrangedElement element in Owner.Children) { + foreach (IArrangedElement element in Owner.Children) + { Control c = element as Control; - if (c != null) { + if (c != null) + { ControlInformation controlInfo = new ControlInformation(); - + // We need to go through the PropertyDescriptor for the Name property // since it is shadowed. PropertyDescriptor prop = TypeDescriptor.GetProperties(c)["Name"]; - if (prop != null && prop.PropertyType == typeof(string)) { + if (prop != null && prop.PropertyType == typeof(string)) + { controlInfo.Name = prop.GetValue(c); } @@ -527,23 +573,25 @@ internal List GetControlsInformation() { controlInfo.RowSpan = GetRowSpan(c); controlInfo.Column = GetColumn(c); controlInfo.ColumnSpan = GetColumnSpan(c); - controlsInfo.Add(controlInfo); + controlsInfo.Add(controlInfo); } - + } return controlsInfo; - } + } } - internal struct ControlInformation { + internal struct ControlInformation + { internal object Name; internal int Row; internal int Column; internal int RowSpan; internal int ColumnSpan; - - internal ControlInformation(object name, int row, int column, int rowSpan, int columnSpan) { + + internal ControlInformation(object name, int row, int column, int rowSpan, int columnSpan) + { Name = name; Row = row; Column = column; @@ -551,19 +599,21 @@ internal ControlInformation(object name, int row, int column, int rowSpan, int c ColumnSpan = columnSpan; } } - + /// TableLayoutSettingsStub /// contains information about /// - private class TableLayoutSettingsStub { - - private static ControlInformation DefaultControlInfo = new ControlInformation(null, -1, -1, 1, 1); + private class TableLayoutSettingsStub + { + + private static ControlInformation DefaultControlInfo = new ControlInformation(null, -1, -1, 1, 1); private TableLayoutColumnStyleCollection columnStyles; private TableLayoutRowStyleCollection rowStyles; private Dictionary controlsInfo; private bool isValid = true; - public TableLayoutSettingsStub() { + public TableLayoutSettingsStub() + { } /// ApplySettings - applies settings from the stub into a full-fledged @@ -573,31 +623,38 @@ public TableLayoutSettingsStub() { /// as a result of calling this function. we hand as much over to the other guy /// so we dont have to reallocate anything /// - internal void ApplySettings(TableLayoutSettings settings) { + internal void ApplySettings(TableLayoutSettings settings) + { // // apply row,column,rowspan,colspan // TableLayout.ContainerInfo containerInfo = TableLayout.GetContainerInfo(settings.Owner); Control appliedControl = containerInfo.Container as Control; - if (appliedControl != null && controlsInfo != null) { + if (appliedControl != null && controlsInfo != null) + { // we store the control names, look up the controls // in the appliedControl's control collection and apply the row,column settings. - foreach (object controlName in controlsInfo.Keys){ + foreach (object controlName in controlsInfo.Keys) + { ControlInformation controlInfo = controlsInfo[controlName]; // Look for the control in our table, we have to go through // PropertyDescriptor rather than just going using appliedControl.Controls[controlName] // because the Name property is shadowed at design time - foreach (Control tableControl in appliedControl.Controls) { - if (tableControl != null) { + foreach (Control tableControl in appliedControl.Controls) + { + if (tableControl != null) + { string name = null; PropertyDescriptor prop = TypeDescriptor.GetProperties(tableControl)["Name"]; - if (prop != null && prop.PropertyType == typeof(string)) { + if (prop != null && prop.PropertyType == typeof(string)) + { name = prop.GetValue(tableControl) as string; } - if (WindowsFormsUtils.SafeCompareStrings(name, controlName as string, /* ignoreCase = */ false)) { + if (WindowsFormsUtils.SafeCompareStrings(name, controlName as string, /* ignoreCase = */ false)) + { settings.SetRow(tableControl, controlInfo.Row); settings.SetColumn(tableControl, controlInfo.Column); settings.SetRowSpan(tableControl, controlInfo.RowSpan); @@ -621,41 +678,51 @@ internal void ApplySettings(TableLayoutSettings settings) { // set a flag for assertion detection. isValid = false; - + } - - - public TableLayoutColumnStyleCollection ColumnStyles { - get { - if (columnStyles == null) { + + + public TableLayoutColumnStyleCollection ColumnStyles + { + get + { + if (columnStyles == null) + { columnStyles = new TableLayoutColumnStyleCollection(); } return columnStyles; } } - public bool IsValid { + public bool IsValid + { get { return isValid; } } - - public TableLayoutRowStyleCollection RowStyles { - get { - if (rowStyles == null) { + + public TableLayoutRowStyleCollection RowStyles + { + get + { + if (rowStyles == null) + { rowStyles = new TableLayoutRowStyleCollection(); } return rowStyles; } } - internal List GetControlsInformation() { - - if (controlsInfo == null) { + internal List GetControlsInformation() + { + + if (controlsInfo == null) + { return new List(); } List listOfControlInfo = new List(controlsInfo.Count); - foreach (object name in controlsInfo.Keys ) { + foreach (object name in controlsInfo.Keys) + { ControlInformation ci = controlsInfo[name]; ci.Name = name; listOfControlInfo.Add(ci); @@ -663,149 +730,181 @@ internal List GetControlsInformation() { return listOfControlInfo; } - private ControlInformation GetControlInformation(object controlName) { + private ControlInformation GetControlInformation(object controlName) + { - if (controlsInfo == null) { + if (controlsInfo == null) + { return DefaultControlInfo; } - if (!controlsInfo.ContainsKey(controlName)) { + if (!controlsInfo.ContainsKey(controlName)) + { return DefaultControlInfo; } return controlsInfo[controlName]; - + } - public int GetColumn(object controlName) { + public int GetColumn(object controlName) + { return GetControlInformation(controlName).Column; } - public int GetColumnSpan(object controlName) { + public int GetColumnSpan(object controlName) + { return GetControlInformation(controlName).ColumnSpan; } - public int GetRow(object controlName) { - return GetControlInformation(controlName).Row; + public int GetRow(object controlName) + { + return GetControlInformation(controlName).Row; } - public int GetRowSpan(object controlName) { - return GetControlInformation(controlName).RowSpan; + public int GetRowSpan(object controlName) + { + return GetControlInformation(controlName).RowSpan; } - private void SetControlInformation(object controlName, ControlInformation info) { - if (controlsInfo == null) { + private void SetControlInformation(object controlName, ControlInformation info) + { + if (controlsInfo == null) + { controlsInfo = new Dictionary(); } controlsInfo[controlName] = info; } - public void SetColumn(object controlName, int column) { - if (GetColumn(controlName) != column) { + public void SetColumn(object controlName, int column) + { + if (GetColumn(controlName) != column) + { ControlInformation info = GetControlInformation(controlName); info.Column = column; SetControlInformation(controlName, info); - } - + } + } - public void SetColumnSpan(object controlName, int value) { - if (GetColumnSpan(controlName) != value) { + public void SetColumnSpan(object controlName, int value) + { + if (GetColumnSpan(controlName) != value) + { ControlInformation info = GetControlInformation(controlName); info.ColumnSpan = value; SetControlInformation(controlName, info); - } + } } - public void SetRow(object controlName, int row) { - if (GetRow(controlName) != row) { + public void SetRow(object controlName, int row) + { + if (GetRow(controlName) != row) + { ControlInformation info = GetControlInformation(controlName); info.Row = row; SetControlInformation(controlName, info); - } + } } - public void SetRowSpan(object controlName, int value) { - if (GetRowSpan(controlName) != value) { - ControlInformation info = GetControlInformation(controlName); - info.RowSpan = value; - SetControlInformation(controlName, info); - } + public void SetRowSpan(object controlName, int value) + { + if (GetRowSpan(controlName) != value) + { + ControlInformation info = GetControlInformation(controlName); + info.RowSpan = value; + SetControlInformation(controlName, info); + } } - + } // end of System.Windows.Forms.TableLayoutSettings - internal class StyleConverter : TypeConverter { - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { - if (destinationType == typeof(InstanceDescriptor)) { + internal class StyleConverter : TypeConverter + { + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) + { + if (destinationType == typeof(InstanceDescriptor)) + { return true; } return base.CanConvertTo(context, destinationType); } - - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) { + + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == null) + { throw new ArgumentNullException(nameof(destinationType)); } - - if (destinationType == typeof(InstanceDescriptor) && value is TableLayoutStyle) { - TableLayoutStyle style = (TableLayoutStyle) value; - - switch(style.SizeType) { + + if (destinationType == typeof(InstanceDescriptor) && value is TableLayoutStyle) + { + TableLayoutStyle style = (TableLayoutStyle)value; + + switch (style.SizeType) + { case SizeType.AutoSize: return new InstanceDescriptor( - style.GetType().GetConstructor(new Type[] {}), - new object[] {}); + style.GetType().GetConstructor(new Type[] { }), + new object[] { }); case SizeType.Absolute: case SizeType.Percent: return new InstanceDescriptor( - style.GetType().GetConstructor(new Type[] {typeof(SizeType), typeof(int)}), - new object[] {style.SizeType, style.Size}); + style.GetType().GetConstructor(new Type[] { typeof(SizeType), typeof(int) }), + new object[] { style.SizeType, style.Size }); default: break; } } return base.ConvertTo(context, culture, value, destinationType); } - } + } } - public class ColumnStyle : TableLayoutStyle { + public class ColumnStyle : TableLayoutStyle + { - public ColumnStyle() {} + public ColumnStyle() { } - public ColumnStyle(SizeType sizeType) { + public ColumnStyle(SizeType sizeType) + { this.SizeType = sizeType; } - public ColumnStyle(SizeType sizeType, float width) { + public ColumnStyle(SizeType sizeType, float width) + { this.SizeType = sizeType; this.Width = width; } - - public float Width { + + public float Width + { get { return base.Size; } set { base.Size = value; } } } - public class RowStyle : TableLayoutStyle { + public class RowStyle : TableLayoutStyle + { - public RowStyle() {} - - public RowStyle(SizeType sizeType) { + public RowStyle() { } + + public RowStyle(SizeType sizeType) + { this.SizeType = sizeType; } - - - public RowStyle(SizeType sizeType, float height) { + + + public RowStyle(SizeType sizeType, float height) + { this.SizeType = sizeType; this.Height = height; } - - public float Height { + + public float Height + { get { return base.Size; } set { base.Size = value; } } - } + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettingsTypeConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettingsTypeConverter.cs index c908d9c7080..957382e537d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettingsTypeConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettingsTypeConverter.cs @@ -2,8 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA905:SystemAndMicrosoftNamespacesRequireApproval", Scope="namespace", Target="System.Windows.Forms.Layout")] -namespace System.Windows.Forms.Layout { +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA905:SystemAndMicrosoftNamespacesRequireApproval", Scope = "namespace", Target = "System.Windows.Forms.Layout")] +namespace System.Windows.Forms.Layout +{ using System; using System.ComponentModel; @@ -11,27 +12,32 @@ namespace System.Windows.Forms.Layout { using System.Text; using System.Globalization; using System.Diagnostics; - using System.ComponentModel.Design.Serialization; - - public class TableLayoutSettingsTypeConverter : TypeConverter { + using System.ComponentModel.Design.Serialization; + + public class TableLayoutSettingsTypeConverter : TypeConverter + { /// /// Determines if this converter can convert an object in the given source /// type to the native type of the converter. /// - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { - if (sourceType == typeof(string)) { + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + { + if (sourceType == typeof(string)) + { return true; } return base.CanConvertFrom(context, sourceType); } - + /// /// Gets a value indicating whether this converter can /// convert an object to the given destination type using the context. /// - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { - if (destinationType == typeof(InstanceDescriptor) || destinationType == typeof(string)) { + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) + { + if (destinationType == typeof(InstanceDescriptor) || destinationType == typeof(string)) + { return true; } return base.CanConvertTo(context, destinationType); @@ -40,14 +46,16 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati /// /// Converts the given object to the converter's native type. /// - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - - if (value is string) { + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + { + + if (value is string) + { XmlDocument tableLayoutSettingsXml = new XmlDocument(); tableLayoutSettingsXml.LoadXml(value as string); TableLayoutSettings settings = new TableLayoutSettings(); - + ParseControls(settings, tableLayoutSettingsXml.GetElementsByTagName("Control")); ParseStyles(settings, tableLayoutSettingsXml.GetElementsByTagName("Columns"), /*isColumn=*/true); ParseStyles(settings, tableLayoutSettingsXml.GetElementsByTagName("Rows"), /*isColumn=*/false); @@ -57,123 +65,141 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c } - - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) { + + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == null) + { throw new ArgumentNullException(nameof(destinationType)); } - if (value is TableLayoutSettings && (destinationType == typeof(string))) { + if (value is TableLayoutSettings && (destinationType == typeof(string))) + { TableLayoutSettings tableLayoutSettings = value as TableLayoutSettings; - + StringBuilder xmlStringBuilder = new StringBuilder(); XmlWriter xmlWriter = XmlWriter.Create(xmlStringBuilder); xmlWriter.WriteStartElement("TableLayoutSettings"); - + // // write controls // xmlWriter.WriteStartElement("Controls"); - - foreach (TableLayoutSettings.ControlInformation c in tableLayoutSettings.GetControlsInformation()) { - - + + foreach (TableLayoutSettings.ControlInformation c in tableLayoutSettings.GetControlsInformation()) + { + + xmlWriter.WriteStartElement("Control"); xmlWriter.WriteAttributeString("Name", c.Name.ToString()); - xmlWriter.WriteAttributeString("Row",c.Row.ToString(CultureInfo.CurrentCulture)); + xmlWriter.WriteAttributeString("Row", c.Row.ToString(CultureInfo.CurrentCulture)); xmlWriter.WriteAttributeString("RowSpan", c.RowSpan.ToString(CultureInfo.CurrentCulture)); - + xmlWriter.WriteAttributeString("Column", c.Column.ToString(CultureInfo.CurrentCulture)); xmlWriter.WriteAttributeString("ColumnSpan", c.ColumnSpan.ToString(CultureInfo.CurrentCulture)); - + xmlWriter.WriteEndElement(); - + } xmlWriter.WriteEndElement(); // end Controls - + // // write columns // xmlWriter.WriteStartElement("Columns"); StringBuilder columnStyles = new StringBuilder(); - foreach (ColumnStyle colStyle in tableLayoutSettings.ColumnStyles) { + foreach (ColumnStyle colStyle in tableLayoutSettings.ColumnStyles) + { columnStyles.AppendFormat("{0},{1},", colStyle.SizeType, colStyle.Width); } - if (columnStyles.Length > 0) { + if (columnStyles.Length > 0) + { columnStyles.Remove(columnStyles.Length - 1, 1); } xmlWriter.WriteAttributeString("Styles", columnStyles.ToString()); xmlWriter.WriteEndElement(); // end columns - + // // write rows // xmlWriter.WriteStartElement("Rows"); StringBuilder rowStyles = new StringBuilder(); - foreach (RowStyle rowStyle in tableLayoutSettings.RowStyles) { + foreach (RowStyle rowStyle in tableLayoutSettings.RowStyles) + { rowStyles.AppendFormat("{0},{1},", rowStyle.SizeType, rowStyle.Height); } - if (rowStyles.Length > 0) { + if (rowStyles.Length > 0) + { rowStyles.Remove(rowStyles.Length - 1, 1); } xmlWriter.WriteAttributeString("Styles", rowStyles.ToString()); xmlWriter.WriteEndElement(); // end Rows - - + + xmlWriter.WriteEndElement(); // end TableLayoutSettings - + xmlWriter.Close(); return xmlStringBuilder.ToString(); - } + } return base.ConvertTo(context, culture, value, destinationType); } - private string GetAttributeValue(XmlNode node, string attribute) { + private string GetAttributeValue(XmlNode node, string attribute) + { XmlAttribute attr = node.Attributes[attribute]; - if (attr != null) { + if (attr != null) + { return attr.Value; } return null; } - private int GetAttributeValue(XmlNode node, string attribute, int valueIfNotFound) { + private int GetAttributeValue(XmlNode node, string attribute, int valueIfNotFound) + { string attributeValue = GetAttributeValue(node, attribute); - if (!string.IsNullOrEmpty(attributeValue)) { + if (!string.IsNullOrEmpty(attributeValue)) + { int result; - if (int.TryParse(attributeValue, out result)) { + if (int.TryParse(attributeValue, out result)) + { return result; } } return valueIfNotFound; } - - - private void ParseControls(TableLayoutSettings settings, XmlNodeList controlXmlFragments) { - foreach (XmlNode controlXmlNode in controlXmlFragments) { - string name = GetAttributeValue(controlXmlNode, "Name"); - - if (!string.IsNullOrEmpty(name)) { - int row = GetAttributeValue(controlXmlNode, "Row", /*default*/-1); - int rowSpan = GetAttributeValue(controlXmlNode, "RowSpan", /*default*/1); - int column = GetAttributeValue(controlXmlNode, "Column", /*default*/-1); - int columnSpan = GetAttributeValue(controlXmlNode, "ColumnSpan",/*default*/1); - - settings.SetRow(name, row); - settings.SetColumn(name, column); - settings.SetRowSpan(name, rowSpan); - settings.SetColumnSpan(name, columnSpan); - } - - } - - - } - - - private void ParseStyles(TableLayoutSettings settings, XmlNodeList controlXmlFragments, bool columns) { - foreach (XmlNode styleXmlNode in controlXmlFragments) { + + + private void ParseControls(TableLayoutSettings settings, XmlNodeList controlXmlFragments) + { + foreach (XmlNode controlXmlNode in controlXmlFragments) + { + string name = GetAttributeValue(controlXmlNode, "Name"); + + if (!string.IsNullOrEmpty(name)) + { + int row = GetAttributeValue(controlXmlNode, "Row", /*default*/-1); + int rowSpan = GetAttributeValue(controlXmlNode, "RowSpan", /*default*/1); + int column = GetAttributeValue(controlXmlNode, "Column", /*default*/-1); + int columnSpan = GetAttributeValue(controlXmlNode, "ColumnSpan",/*default*/1); + + settings.SetRow(name, row); + settings.SetColumn(name, column); + settings.SetRowSpan(name, rowSpan); + settings.SetColumnSpan(name, columnSpan); + } + + } + + + } + + + private void ParseStyles(TableLayoutSettings settings, XmlNodeList controlXmlFragments, bool columns) + { + foreach (XmlNode styleXmlNode in controlXmlFragments) + { string styleString = GetAttributeValue(styleXmlNode, "Styles"); Type sizeTypeType = typeof(SizeType); @@ -184,49 +210,59 @@ private void ParseStyles(TableLayoutSettings settings, XmlNodeList controlXmlFra // Percent,23,3,Percent,46,7,Percent,30 // Note we get either . or , based on the culture the TableLayoutSettings were serialized in - if (!string.IsNullOrEmpty(styleString)) { + if (!string.IsNullOrEmpty(styleString)) + { int currentIndex = 0; int nextIndex; - while (currentIndex < styleString.Length) { + while (currentIndex < styleString.Length) + { // ---- SizeType Parsing ----------------- nextIndex = currentIndex; - while (char.IsLetter(styleString[nextIndex])) { + while (char.IsLetter(styleString[nextIndex])) + { nextIndex++; } SizeType type = (SizeType)Enum.Parse(sizeTypeType, styleString.Substring(currentIndex, nextIndex - currentIndex), true); - + // ----- Float Parsing -------------- // Find the next Digit (start of the float) - while (!char.IsDigit(styleString[nextIndex])) { + while (!char.IsDigit(styleString[nextIndex])) + { nextIndex++; } // Append digits left of the decimal delimiter(s) StringBuilder floatStringBuilder = new StringBuilder(); - while ((nextIndex < styleString.Length) && (char.IsDigit(styleString[nextIndex]))) { + while ((nextIndex < styleString.Length) && (char.IsDigit(styleString[nextIndex]))) + { floatStringBuilder.Append(styleString[nextIndex]); nextIndex++; } // Append culture invariant delimiter floatStringBuilder.Append('.'); // Append digits right of the decimal delimiter(s) - while ((nextIndex < styleString.Length) && (!char.IsLetter(styleString[nextIndex]))) { - if (char.IsDigit(styleString[nextIndex])) { + while ((nextIndex < styleString.Length) && (!char.IsLetter(styleString[nextIndex]))) + { + if (char.IsDigit(styleString[nextIndex])) + { floatStringBuilder.Append(styleString[nextIndex]); } nextIndex++; } string floatString = floatStringBuilder.ToString(); float width; - if (!float.TryParse(floatString, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out width)) { + if (!float.TryParse(floatString, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out width)) + { width = 0F; } // Add new Column/Row Style - if (columns) { + if (columns) + { settings.ColumnStyles.Add(new ColumnStyle(type, width)); } - else { + else + { settings.RowStyles.Add(new RowStyle(type, width)); } @@ -236,12 +272,12 @@ private void ParseStyles(TableLayoutSettings settings, XmlNodeList controlXmlFra } } } - - + + } } - + diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutStyle.cs index fc214e6e055..b598cbb6e73 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutStyle.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutStyle.cs @@ -2,34 +2,41 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Drawing; - using System.Drawing.Design; + using System.Drawing.Design; using System.Globalization; using System.Windows.Forms.Layout; using System.Reflection; [TypeConverterAttribute(typeof(TableLayoutSettings.StyleConverter))] - public abstract class TableLayoutStyle { + public abstract class TableLayoutStyle + { private IArrangedElement _owner; private SizeType _sizeType = SizeType.AutoSize; private float _size; - + [DefaultValue(SizeType.AutoSize)] - public SizeType SizeType { + public SizeType SizeType + { get { return _sizeType; } - set { - if (_sizeType != value) { - _sizeType = value; - if(Owner != null) { + set + { + if (_sizeType != value) + { + _sizeType = value; + if (Owner != null) + { LayoutTransaction.DoLayout(Owner, Owner, PropertyNames.Style); Control owner = Owner as Control; - if (owner != null) { + if (owner != null) + { owner.Invalidate(); } } @@ -37,18 +44,24 @@ public SizeType SizeType { } } - internal float Size { + internal float Size + { get { return _size; } - set { - if (value < 0) { + set + { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(Size), value, 0)); } - if (_size != value) { + if (_size != value) + { _size = value; - if(Owner != null) { + if (Owner != null) + { LayoutTransaction.DoLayout(Owner, Owner, PropertyNames.Style); Control owner = Owner as Control; - if (owner != null) { + if (owner != null) + { owner.Invalidate(); } } @@ -56,17 +69,20 @@ internal float Size { } } - private bool ShouldSerializeSize() { + private bool ShouldSerializeSize() + { return SizeType != SizeType.AutoSize; } - internal IArrangedElement Owner { + internal IArrangedElement Owner + { get { return _owner; } set { _owner = value; } } //set the size without doing a layout - internal void SetSize(float size) { + internal void SetSize(float size) + { Debug.Assert(size >= 0); _size = size; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutStyleCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutStyleCollection.cs index 34a28c525e5..f27467cf765 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutStyleCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutStyleCollection.cs @@ -94,7 +94,7 @@ void IList.Remove(object style) public void Clear() { - foreach(TableLayoutStyle style in _innerList) + foreach (TableLayoutStyle style in _innerList) { style.Owner = null; } @@ -105,7 +105,7 @@ public void Clear() public void RemoveAt(int index) { - TableLayoutStyle style = (TableLayoutStyle) _innerList[index]; + TableLayoutStyle style = (TableLayoutStyle)_innerList[index]; style.Owner = null; _innerList.RemoveAt(index); PerformLayoutIfOwned(); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TextBox.cs index b8ff76c1a65..d3ec809a52c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TextBox.cs @@ -3,12 +3,13 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.ComponentModel; using System.Diagnostics; using System; using System.Windows.Forms; - using System.ComponentModel.Design; + using System.ComponentModel.Design; using System.Drawing; using Microsoft.Win32; using System.Reflection; @@ -17,7 +18,7 @@ namespace System.Windows.Forms { using System.Collections.Specialized; using System.Drawing.Design; using System.Windows.Forms.VisualStyles; - + /// /// /// Represents a Windows text box control. @@ -31,10 +32,11 @@ namespace System.Windows.Forms { Designer("System.Windows.Forms.Design.TextBoxDesigner, " + AssemblyRef.SystemDesign), SRDescription(nameof(SR.DescriptionTextBox)) ] - public class TextBox : TextBoxBase { - + public class TextBox : TextBoxBase + { + private static readonly object EVENT_TEXTALIGNCHANGED = new object(); - + /// /// Controls whether or not the edit box consumes/respects ENTER key /// presses. While this is typically desired by multiline edits, this @@ -65,7 +67,7 @@ public class TextBox : TextBoxBase { /// Controls text alignment in the edit box. /// private HorizontalAlignment textAlign = HorizontalAlignment.Left; - + /// /// True if the selection has been set by the user. If the selection has /// never been set and we get focus, we focus all the text in the control @@ -78,7 +80,7 @@ public class TextBox : TextBoxBase { /// None, AutoSuggest, AutoAppend or AutoSuggestAppend. /// private AutoCompleteMode autoCompleteMode = AutoCompleteMode.None; - + /// /// This stores the value for the autoCompleteSource mode which can be one of the values /// from AutoCompleteSource enum. @@ -93,10 +95,11 @@ public class TextBox : TextBoxBase { private StringSource stringSource = null; private string placeholderText; - public TextBox(){ + public TextBox() + { } - + /// /// /// Gets or sets a value indicating whether pressing ENTER @@ -110,12 +113,15 @@ public TextBox(){ DefaultValue(false), SRDescription(nameof(SR.TextBoxAcceptsReturnDescr)) ] - public bool AcceptsReturn { - get { + public bool AcceptsReturn + { + get + { return acceptsReturn; } - set { + set + { acceptsReturn = value; } } @@ -131,16 +137,21 @@ public bool AcceptsReturn { SRDescription(nameof(SR.TextBoxAutoCompleteModeDescr)), Browsable(true), EditorBrowsable(EditorBrowsableState.Always) ] - public AutoCompleteMode AutoCompleteMode { - get { + public AutoCompleteMode AutoCompleteMode + { + get + { return autoCompleteMode; } - set { - if (!ClientUtils.IsEnumValid(value, (int)value, (int)AutoCompleteMode.None, (int)AutoCompleteMode.SuggestAppend)){ + set + { + if (!ClientUtils.IsEnumValid(value, (int)value, (int)AutoCompleteMode.None, (int)AutoCompleteMode.SuggestAppend)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AutoCompleteMode)); } bool resetAutoComplete = false; - if (autoCompleteMode != AutoCompleteMode.None && value == AutoCompleteMode.None) { + if (autoCompleteMode != AutoCompleteMode.None && value == AutoCompleteMode.None) + { resetAutoComplete = true; } autoCompleteMode = value; @@ -159,15 +170,18 @@ public AutoCompleteMode AutoCompleteMode { TypeConverterAttribute(typeof(TextBoxAutoCompleteSourceConverter)), Browsable(true), EditorBrowsable(EditorBrowsableState.Always) ] - public AutoCompleteSource AutoCompleteSource { - get { + public AutoCompleteSource AutoCompleteSource + { + get + { return autoCompleteSource; } - set { + set + { // FxCop: Avoid usage of Enum.IsDefined - this looks like an enum that could grow - if (!ClientUtils.IsEnumValid_NotSequential(value, + if (!ClientUtils.IsEnumValid_NotSequential(value, (int)value, - (int)AutoCompleteSource.None, + (int)AutoCompleteSource.None, (int)AutoCompleteSource.AllSystemSources, (int)AutoCompleteSource.AllUrl, (int)AutoCompleteSource.CustomSource, @@ -175,10 +189,12 @@ public AutoCompleteSource AutoCompleteSource { (int)AutoCompleteSource.FileSystemDirectories, (int)AutoCompleteSource.HistoryList, (int)AutoCompleteSource.ListItems, - (int)AutoCompleteSource.RecentlyUsedList)){ + (int)AutoCompleteSource.RecentlyUsedList)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AutoCompleteSource)); } - if (value == AutoCompleteSource.ListItems) { + if (value == AutoCompleteSource.ListItems) + { throw new NotSupportedException(SR.TextBoxAutoCompleteSourceNoItems); } @@ -198,28 +214,35 @@ public AutoCompleteSource AutoCompleteSource { Editor("System.Windows.Forms.Design.ListControlStringCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), Browsable(true), EditorBrowsable(EditorBrowsableState.Always) ] - public AutoCompleteStringCollection AutoCompleteCustomSource { - get { - if (autoCompleteCustomSource == null) { + public AutoCompleteStringCollection AutoCompleteCustomSource + { + get + { + if (autoCompleteCustomSource == null) + { autoCompleteCustomSource = new AutoCompleteStringCollection(); autoCompleteCustomSource.CollectionChanged += new CollectionChangeEventHandler(this.OnAutoCompleteCustomSourceChanged); } return autoCompleteCustomSource; } - set { - if (autoCompleteCustomSource != value) { - if (autoCompleteCustomSource != null) { + set + { + if (autoCompleteCustomSource != value) + { + if (autoCompleteCustomSource != null) + { autoCompleteCustomSource.CollectionChanged -= new CollectionChangeEventHandler(this.OnAutoCompleteCustomSourceChanged); } - + autoCompleteCustomSource = value; - - if (value != null) { + + if (value != null) + { autoCompleteCustomSource.CollectionChanged += new CollectionChangeEventHandler(this.OnAutoCompleteCustomSourceChanged); } SetAutoComplete(false); } - + } } @@ -234,15 +257,20 @@ public AutoCompleteStringCollection AutoCompleteCustomSource { DefaultValue(CharacterCasing.Normal), SRDescription(nameof(SR.TextBoxCharacterCasingDescr)) ] - public CharacterCasing CharacterCasing { - get { + public CharacterCasing CharacterCasing + { + get + { return characterCasing; } - set { - if (characterCasing != value) { + set + { + if (characterCasing != value) + { //verify that 'value' is a valid enum type... //valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)CharacterCasing.Normal, (int)CharacterCasing.Lower)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)CharacterCasing.Normal, (int)CharacterCasing.Lower)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(CharacterCasing)); } @@ -252,12 +280,15 @@ public CharacterCasing CharacterCasing { } } - public override bool Multiline { - get { + public override bool Multiline + { + get + { return base.Multiline; } - set { - + set + { + if (Multiline != value) { base.Multiline = value; @@ -272,13 +303,15 @@ public override bool Multiline { /// /// Determines if the control is in password protect mode. /// - internal override bool PasswordProtect { - get { + internal override bool PasswordProtect + { + get + { return this.PasswordChar != '\0'; } } - + /// /// /// Returns the parameters needed to create the handle. Inheriting classes @@ -287,10 +320,13 @@ internal override bool PasswordProtect { /// filled up with the basic info. /// /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; - switch (characterCasing) { + switch (characterCasing) + { case CharacterCasing.Lower: cp.Style |= NativeMethods.ES_LOWERCASE; break; @@ -303,7 +339,8 @@ protected override CreateParams CreateParams { // HorizontalAlignment align = RtlTranslateHorizontal(textAlign); cp.ExStyle &= ~NativeMethods.WS_EX_RIGHT; // WS_EX_RIGHT overrides the ES_XXXX alignment styles - switch (align) { + switch (align) + { case HorizontalAlignment.Left: cp.Style |= NativeMethods.ES_LEFT; break; @@ -314,23 +351,27 @@ protected override CreateParams CreateParams { cp.Style |= NativeMethods.ES_RIGHT; break; } - - if (Multiline) { + + if (Multiline) + { // Don't show horizontal scroll bars which won't do anything if ((scrollBars & ScrollBars.Horizontal) == ScrollBars.Horizontal && textAlign == HorizontalAlignment.Left - && !WordWrap) { + && !WordWrap) + { cp.Style |= NativeMethods.WS_HSCROLL; } - if ((scrollBars & ScrollBars.Vertical) == ScrollBars.Vertical) { + if ((scrollBars & ScrollBars.Vertical) == ScrollBars.Vertical) + { cp.Style |= NativeMethods.WS_VSCROLL; } } - if (useSystemPasswordChar) { + if (useSystemPasswordChar) + { cp.Style |= NativeMethods.ES_PASSWORD; } - + return cp; } } @@ -348,18 +389,25 @@ protected override CreateParams CreateParams { SRDescription(nameof(SR.TextBoxPasswordCharDescr)), RefreshProperties(RefreshProperties.Repaint) ] - public char PasswordChar { - get { - if (!IsHandleCreated) { + public char PasswordChar + { + get + { + if (!IsHandleCreated) + { CreateHandle(); } return (char)SendMessage(Interop.EditMessages.EM_GETPASSWORDCHAR, 0, 0); } - set { + set + { passwordChar = value; - if (!useSystemPasswordChar) { - if (IsHandleCreated) { - if (PasswordChar != value) { + if (!useSystemPasswordChar) + { + if (IsHandleCreated) + { + if (PasswordChar != value) + { // Set the password mode. SendMessage(Interop.EditMessages.EM_SETPASSWORDCHAR, value, 0); @@ -387,14 +435,19 @@ public char PasswordChar { DefaultValue(ScrollBars.None), SRDescription(nameof(SR.TextBoxScrollBarsDescr)) ] - public ScrollBars ScrollBars { - get { + public ScrollBars ScrollBars + { + get + { return scrollBars; } - set { - if (scrollBars != value) { + set + { + if (scrollBars != value) + { //valid values are 0x0 to 0x3 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)ScrollBars.None, (int)ScrollBars.Both)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)ScrollBars.None, (int)ScrollBars.Both)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ScrollBars)); } @@ -404,19 +457,22 @@ public ScrollBars ScrollBars { } } - internal override Size GetPreferredSizeCore(Size proposedConstraints) { + internal override Size GetPreferredSizeCore(Size proposedConstraints) + { Size scrollBarPadding = Size.Empty; - if(Multiline && !WordWrap && (ScrollBars & ScrollBars.Horizontal) != 0) { + if (Multiline && !WordWrap && (ScrollBars & ScrollBars.Horizontal) != 0) + { scrollBarPadding.Height += SystemInformation.GetHorizontalScrollBarHeightForDpi(deviceDpi); } - if(Multiline && (ScrollBars & ScrollBars.Vertical) != 0) { + if (Multiline && (ScrollBars & ScrollBars.Vertical) != 0) + { scrollBarPadding.Width += SystemInformation.GetVerticalScrollBarWidthForDpi(deviceDpi); } // Subtract the scroll bar padding before measuring proposedConstraints -= scrollBarPadding; - + Size prefSize = base.GetPreferredSizeCore(proposedConstraints); return prefSize + scrollBarPadding; @@ -428,11 +484,14 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) { /// the current text in the text box. /// /// - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; selectionSet = false; } @@ -452,16 +511,21 @@ public override string Text { DefaultValue(HorizontalAlignment.Left), SRDescription(nameof(SR.TextBoxTextAlignDescr)) ] - public HorizontalAlignment TextAlign { - get { + public HorizontalAlignment TextAlign + { + get + { return textAlign; } - set { - if (textAlign != value) { + set + { + if (textAlign != value) + { //verify that 'value' is a valid enum type... //valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)HorizontalAlignment.Left, (int)HorizontalAlignment.Center)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)HorizontalAlignment.Left, (int)HorizontalAlignment.Center)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(HorizontalAlignment)); } @@ -487,39 +551,48 @@ public HorizontalAlignment TextAlign { SRDescription(nameof(SR.TextBoxUseSystemPasswordCharDescr)), RefreshProperties(RefreshProperties.Repaint) ] - public bool UseSystemPasswordChar { - get { + public bool UseSystemPasswordChar + { + get + { return useSystemPasswordChar; } - set { - if (value != useSystemPasswordChar) { + set + { + if (value != useSystemPasswordChar) + { useSystemPasswordChar = value; // RecreateHandle will update IME restricted mode. RecreateHandle(); - if (value) { + if (value) + { ResetAutoComplete(false); } } } } - + [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.RadioButtonOnTextAlignChangedDescr))] - public event EventHandler TextAlignChanged { + public event EventHandler TextAlignChanged + { add => Events.AddHandler(EVENT_TEXTALIGNCHANGED, value); remove => Events.RemoveHandler(EVENT_TEXTALIGNCHANGED, value); } - protected override void Dispose(bool disposing) { - if (disposing) { + protected override void Dispose(bool disposing) + { + if (disposing) + { // Reset this just in case, because the SHAutoComplete stuff // will subclass this guys wndproc (and nativewindow can't know about it). // so this will undo it, but on a dispose we'll be Destroying the window anyay. // ResetAutoComplete(true); - if (autoCompleteCustomSource != null) { + if (autoCompleteCustomSource != null) + { autoCompleteCustomSource.CollectionChanged -= new CollectionChangeEventHandler(this.OnAutoCompleteCustomSourceChanged); } if (stringSource != null) @@ -530,15 +603,18 @@ protected override void Dispose(bool disposing) { } base.Dispose(disposing); } - + /// /// /// Overridden to handle RETURN key. /// /// - protected override bool IsInputKey(Keys keyData) { - if (Multiline && (keyData & Keys.Alt) == 0) { - switch (keyData & Keys.KeyCode) { + protected override bool IsInputKey(Keys keyData) + { + if (Multiline && (keyData & Keys.Alt) == 0) + { + switch (keyData & Keys.KeyCode) + { case Keys.Return: return acceptsReturn; } @@ -547,24 +623,29 @@ protected override bool IsInputKey(Keys keyData) { } - private void OnAutoCompleteCustomSourceChanged(object sender, CollectionChangeEventArgs e) { + private void OnAutoCompleteCustomSourceChanged(object sender, CollectionChangeEventArgs e) + { if (AutoCompleteSource == AutoCompleteSource.CustomSource) { SetAutoComplete(true); } } - protected override void OnBackColorChanged(EventArgs e) { + protected override void OnBackColorChanged(EventArgs e) + { base.OnBackColorChanged(e); // Force repainting of the entire window frame - if (Application.RenderWithVisualStyles && this.IsHandleCreated && this.BorderStyle == BorderStyle.Fixed3D) { + if (Application.RenderWithVisualStyles && this.IsHandleCreated && this.BorderStyle == BorderStyle.Fixed3D) + { SafeNativeMethods.RedrawWindow(new HandleRef(this, this.Handle), null, NativeMethods.NullHandleRef, NativeMethods.RDW_INVALIDATE | NativeMethods.RDW_FRAME); } } - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { base.OnFontChanged(e); - if (this.AutoCompleteMode != AutoCompleteMode.None) { + if (this.AutoCompleteMode != AutoCompleteMode.None) + { //we always will recreate the handle when autocomplete mode is on RecreateHandle(); } @@ -573,15 +654,18 @@ protected override void OnFontChanged(EventArgs e) { /// /// Overrideen to focus the text on first focus. /// - protected override void OnGotFocus(EventArgs e) { + protected override void OnGotFocus(EventArgs e) + { base.OnGotFocus(e); - if (!selectionSet) { + if (!selectionSet) + { // We get one shot at selecting when we first get focus. If we don't // do it, we still want to act like the selection was set. selectionSet = true; // If the user didn't provide a selection, force one in. - if (SelectionLength == 0 && Control.MouseButtons == MouseButtons.None) { + if (SelectionLength == 0 && Control.MouseButtons == MouseButtons.None) + { SelectAll(); } } @@ -591,19 +675,23 @@ protected override void OnGotFocus(EventArgs e) { /// Overridden to update the newly created handle with the settings of the /// PasswordChar properties. /// - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { base.OnHandleCreated(e); base.SetSelectionOnHandle(); - if (passwordChar != 0) { - if (!useSystemPasswordChar) { + if (passwordChar != 0) + { + if (!useSystemPasswordChar) + { SendMessage(Interop.EditMessages.EM_SETPASSWORDCHAR, passwordChar, 0); } } VerifyImeRestrictedModeChanged(); - if (AutoCompleteMode != AutoCompleteMode.None) { + if (AutoCompleteMode != AutoCompleteMode.None) + { try { fromHandleCreate = true; @@ -625,11 +713,13 @@ protected override void OnHandleDestroyed(EventArgs e) } base.OnHandleDestroyed(e); } - - protected virtual void OnTextAlignChanged(EventArgs e) { + + protected virtual void OnTextAlignChanged(EventArgs e) + { EventHandler eh = Events[EVENT_TEXTALIGNCHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } @@ -648,10 +738,12 @@ protected virtual void OnTextAlignChanged(EventArgs e) { /// keyData - bitmask containing one or more keys /// /// - protected override bool ProcessCmdKey(ref Message m, Keys keyData) { + protected override bool ProcessCmdKey(ref Message m, Keys keyData) + { bool returnValue = base.ProcessCmdKey(ref m, keyData); - if (!returnValue && this.Multiline && !LocalAppContextSwitches.DoNotSupportSelectAllShortcutInMultilineTextBox - && this.ShortcutsEnabled && (keyData == (Keys.Control | Keys.A))) { + if (!returnValue && this.Multiline && !LocalAppContextSwitches.DoNotSupportSelectAllShortcutInMultilineTextBox + && this.ShortcutsEnabled && (keyData == (Keys.Control | Keys.A))) + { SelectAll(); return true; } @@ -666,24 +758,27 @@ protected override bool ProcessCmdKey(ref Message m, Keys keyData) { /// Observe that this method does not honor the MaxLength property as the parameter-less base's /// Paste does /// - public void Paste(string text){ + public void Paste(string text) + { base.SetSelectedTextInternal(text, false); } - + /// /// Performs the actual select without doing arg checking. /// - internal override void SelectInternal(int start, int length, int textLen) { + internal override void SelectInternal(int start, int length, int textLen) + { // If user set selection into text box, mark it so we don't // clobber it when we get focus. selectionSet = true; - base.SelectInternal( start, length, textLen ); + base.SelectInternal(start, length, textLen); } private string[] GetStringsForAutoComplete() { string[] strings = new string[AutoCompleteCustomSource.Count]; - for (int i = 0; i < AutoCompleteCustomSource.Count; i++) { + for (int i = 0; i < AutoCompleteCustomSource.Count; i++) + { strings[i] = AutoCompleteCustomSource[i]; } return strings; @@ -697,11 +792,13 @@ private string[] GetStringsForAutoComplete() internal void SetAutoComplete(bool reset) { //Autocomplete Not Enabled for Password enabled and MultiLine Textboxes. - if (Multiline || passwordChar != 0 || useSystemPasswordChar || AutoCompleteSource == AutoCompleteSource.None) { + if (Multiline || passwordChar != 0 || useSystemPasswordChar || AutoCompleteSource == AutoCompleteSource.None) + { return; } - if (AutoCompleteMode != AutoCompleteMode.None) { + if (AutoCompleteMode != AutoCompleteMode.None) + { if (!fromHandleCreate) { //RecreateHandle to avoid Leak. @@ -711,19 +808,23 @@ internal void SetAutoComplete(bool reset) RecreateHandle(); autoCompleteMode = backUpMode; } - - if (AutoCompleteSource == AutoCompleteSource.CustomSource) { - if (IsHandleCreated && AutoCompleteCustomSource != null) { - if (AutoCompleteCustomSource.Count == 0) { + + if (AutoCompleteSource == AutoCompleteSource.CustomSource) + { + if (IsHandleCreated && AutoCompleteCustomSource != null) + { + if (AutoCompleteCustomSource.Count == 0) + { ResetAutoComplete(true); } - else { + else + { if (stringSource == null) { stringSource = new StringSource(GetStringsForAutoComplete()); if (!stringSource.Bind(new HandleRef(this, Handle), (int)AutoCompleteMode)) { - throw new ArgumentException(SR.AutoCompleteFailure); + throw new ArgumentException(SR.AutoCompleteFailure); } } else @@ -732,26 +833,32 @@ internal void SetAutoComplete(bool reset) } } } - + } - else { - if (IsHandleCreated) { + else + { + if (IsHandleCreated) + { int mode = 0; - if (AutoCompleteMode == AutoCompleteMode.Suggest) { - mode |= NativeMethods.AUTOSUGGEST | NativeMethods.AUTOAPPEND_OFF; + if (AutoCompleteMode == AutoCompleteMode.Suggest) + { + mode |= NativeMethods.AUTOSUGGEST | NativeMethods.AUTOAPPEND_OFF; } - if (AutoCompleteMode == AutoCompleteMode.Append) { - mode |= NativeMethods.AUTOAPPEND | NativeMethods.AUTOSUGGEST_OFF; + if (AutoCompleteMode == AutoCompleteMode.Append) + { + mode |= NativeMethods.AUTOAPPEND | NativeMethods.AUTOSUGGEST_OFF; } - if (AutoCompleteMode == AutoCompleteMode.SuggestAppend) { - mode |= NativeMethods.AUTOSUGGEST; - mode |= NativeMethods.AUTOAPPEND; + if (AutoCompleteMode == AutoCompleteMode.SuggestAppend) + { + mode |= NativeMethods.AUTOSUGGEST; + mode |= NativeMethods.AUTOAPPEND; } - int ret = SafeNativeMethods.SHAutoComplete(new HandleRef(this, Handle) , (int)AutoCompleteSource | mode); + int ret = SafeNativeMethods.SHAutoComplete(new HandleRef(this, Handle), (int)AutoCompleteSource | mode); } } } - else if (reset) { + else if (reset) + { ResetAutoComplete(true); } } @@ -760,23 +867,30 @@ internal void SetAutoComplete(bool reset) /// /// Resets the AutoComplete mode in TextBox. /// - private void ResetAutoComplete(bool force) { - if ((AutoCompleteMode != AutoCompleteMode.None || force) && IsHandleCreated) { + private void ResetAutoComplete(bool force) + { + if ((AutoCompleteMode != AutoCompleteMode.None || force) && IsHandleCreated) + { int mode = (int)AutoCompleteSource.AllSystemSources | NativeMethods.AUTOSUGGEST_OFF | NativeMethods.AUTOAPPEND_OFF; - SafeNativeMethods.SHAutoComplete(new HandleRef(this, Handle) , mode); + SafeNativeMethods.SHAutoComplete(new HandleRef(this, Handle), mode); } } - private void ResetAutoCompleteCustomSource() { + private void ResetAutoCompleteCustomSource() + { AutoCompleteCustomSource = null; } - private void WmPrint(ref Message m) { + private void WmPrint(ref Message m) + { base.WndProc(ref m); - if ((NativeMethods.PRF_NONCLIENT & (int)m.LParam) != 0 && Application.RenderWithVisualStyles && this.BorderStyle == BorderStyle.Fixed3D) { - using (Graphics g = Graphics.FromHdc(m.WParam)) { + if ((NativeMethods.PRF_NONCLIENT & (int)m.LParam) != 0 && Application.RenderWithVisualStyles && this.BorderStyle == BorderStyle.Fixed3D) + { + using (Graphics g = Graphics.FromHdc(m.WParam)) + { Rectangle rect = new Rectangle(0, 0, this.Size.Width - 1, this.Size.Height - 1); - using (Pen pen = new Pen(VisualStyleInformation.TextControlBorder)) { + using (Pen pen = new Pen(VisualStyleInformation.TextControlBorder)) + { g.DrawRectangle(pen, rect); } rect.Inflate(-1, -1); @@ -784,7 +898,7 @@ private void WmPrint(ref Message m) { } } } - + /// /// Gets or sets the text that is displayed when the control has no Text and is not on focus. /// @@ -868,21 +982,24 @@ private void DrawPlaceholderText(Graphics graphics) /// to add extra functionality, but should not forget to call /// base.wndProc(m); to ensure the combo continues to function properly. /// - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { // Work around a very obscure Windows issue. case Interop.WindowMessages.WM_LBUTTONDOWN: MouseButtons realState = MouseButtons; bool wasValidationCancelled = ValidationCancelled; Focus(); - if (realState == MouseButtons && - (!ValidationCancelled || wasValidationCancelled)) { - base.WndProc(ref m); - } + if (realState == MouseButtons && + (!ValidationCancelled || wasValidationCancelled)) + { + base.WndProc(ref m); + } break; //for readability ... so that we know whats happening ... // case WM_LBUTTONUP is included here eventhough it just calls the base. - case Interop.WindowMessages.WM_LBUTTONUP: + case Interop.WindowMessages.WM_LBUTTONUP: base.WndProc(ref m); break; case Interop.WindowMessages.WM_PRINT: diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxAutoCompleteSourceConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxAutoCompleteSourceConverter.cs index 4aa878bacf3..2fcd151cec6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxAutoCompleteSourceConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxAutoCompleteSourceConverter.cs @@ -2,33 +2,37 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.ComponentModel; using System.Collections; - - internal class TextBoxAutoCompleteSourceConverter : EnumConverter { - public TextBoxAutoCompleteSourceConverter(Type type) : base(type) { + + internal class TextBoxAutoCompleteSourceConverter : EnumConverter + { + public TextBoxAutoCompleteSourceConverter(Type type) : base(type) + { } /// /// Gets a collection of standard values for the data type this validator is /// designed for. /// - public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { + public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) + { StandardValuesCollection values = base.GetStandardValues(context); ArrayList list = new ArrayList(); int count = values.Count; - for (int i=0; i /// The current border for this edit control. @@ -90,7 +92,7 @@ public abstract class TextBoxBase : Control { /// This is used by TextBox, RichTextBox and MaskedTextBox, code was moved down from TextBox/RichTextBox /// but cannot make it as default behavior to avoid introducing breaking changes. /// - private bool doubleClickFired = false; + private bool doubleClickFired = false; private static int[] shortcutsToDisable; @@ -102,14 +104,15 @@ public abstract class TextBoxBase : Control { /// Creates a new TextBox control. Uses the parent's current font and color /// set. /// - internal TextBoxBase() : base() { - + internal TextBoxBase() : base() + { + // this class overrides GetPreferredSizeCore, let Control automatically cache the result - SetState2(STATE2_USEPREFERREDSIZECACHE, true); - + SetState2(STATE2_USEPREFERREDSIZECACHE, true); + textBoxFlags[autoSize | hideSelection | wordWrap | shortcutsEnabled] = true; SetStyle(ControlStyles.FixedHeight, textBoxFlags[autoSize]); - SetStyle(ControlStyles.StandardClick + SetStyle(ControlStyles.StandardClick | ControlStyles.StandardDoubleClick | ControlStyles.UseTextForAccessibility | ControlStyles.UserPaint, false); @@ -135,12 +138,16 @@ internal TextBoxBase() : base() { DefaultValue(false), SRDescription(nameof(SR.TextBoxAcceptsTabDescr)) ] - public bool AcceptsTab { - get { + public bool AcceptsTab + { + get + { return textBoxFlags[acceptsTab]; } - set { - if (textBoxFlags[acceptsTab] != value) { + set + { + if (textBoxFlags[acceptsTab] != value) + { textBoxFlags[acceptsTab] = value; OnAcceptsTabChanged(EventArgs.Empty); } @@ -148,7 +155,8 @@ public bool AcceptsTab { } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.TextBoxBaseOnAcceptsTabChangedDescr))] - public event EventHandler AcceptsTabChanged { + public event EventHandler AcceptsTabChanged + { add => Events.AddHandler(EVENT_ACCEPTSTABCHANGED, value); remove => Events.RemoveHandler(EVENT_ACCEPTSTABCHANGED, value); } @@ -166,12 +174,16 @@ public event EventHandler AcceptsTabChanged { DefaultValue(true), SRDescription(nameof(SR.TextBoxShortcutsEnabledDescr)) ] - public virtual bool ShortcutsEnabled { - get { + public virtual bool ShortcutsEnabled + { + get + { return textBoxFlags[shortcutsEnabled]; } - set { - if (shortcutsToDisable == null) { + set + { + if (shortcutsToDisable == null) + { shortcutsToDisable = new int[] {(int)Shortcut.CtrlZ, (int)Shortcut.CtrlC, (int)Shortcut.CtrlX, (int)Shortcut.CtrlV, (int)Shortcut.CtrlA, (int)Shortcut.CtrlL, (int)Shortcut.CtrlR, (int)Shortcut.CtrlE, (int)Shortcut.CtrlY, (int)Keys.Control + (int)Keys.Back, @@ -184,15 +196,19 @@ public virtual bool ShortcutsEnabled { /// /// Implements the property. /// - protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) + { // First call parent's ProcessCmdKey, since we don't to eat up // the shortcut key we are not supported in TextBox. bool returnedValue = base.ProcessCmdKey(ref msg, keyData); - if (ShortcutsEnabled == false) { - foreach (int shortcutValue in shortcutsToDisable) { + if (ShortcutsEnabled == false) + { + foreach (int shortcutValue in shortcutsToDisable) + { if ((int)keyData == shortcutValue || - (int)keyData == (shortcutValue | (int)Keys.Shift)) { + (int)keyData == (shortcutValue | (int)Keys.Shift)) + { return true; } } @@ -201,12 +217,14 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { // There are a few keys that change the alignment of the text, but that // are not ignored by the native control when the ReadOnly property is set. // We need to workaround that. - if (textBoxFlags[readOnly]) { + if (textBoxFlags[readOnly]) + { int k = (int)keyData; if (k == (int)Shortcut.CtrlL // align left || k == (int)Shortcut.CtrlR // align right || k == (int)Shortcut.CtrlE // align centre - || k == (int)Shortcut.CtrlJ) { // align justified + || k == (int)Shortcut.CtrlJ) + { // align justified return true; } } @@ -251,21 +269,26 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { RefreshProperties(RefreshProperties.Repaint), Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override bool AutoSize { - get { + public override bool AutoSize + { + get + { return textBoxFlags[autoSize]; } - set { + set + { // Note that we intentionally do not call base. TextBoxes size themselves by // overriding SetBoundsCore (old RTM code). We let CommonProperties.GetAutoSize // continue to return false to keep our LayoutEngines from messing with TextBoxes. // This is done for backwards compatibility since the new AutoSize behavior differs. - if (textBoxFlags[autoSize] != value) { + if (textBoxFlags[autoSize] != value) + { textBoxFlags[autoSize] = value; // AutoSize's effects are ignored for a multi-line textbox // - if (!Multiline) { + if (!Multiline) + { SetStyle(ControlStyles.FixedHeight, value); AdjustHeight(false); } @@ -286,18 +309,25 @@ public override bool AutoSize { DispId(NativeMethods.ActiveX.DISPID_BACKCOLOR), SRDescription(nameof(SR.ControlBackColorDescr)) ] - public override Color BackColor { - get { - if (ShouldSerializeBackColor()) { + public override Color BackColor + { + get + { + if (ShouldSerializeBackColor()) + { return base.BackColor; } - else if (this.ReadOnly) { + else if (this.ReadOnly) + { return SystemColors.Control; - } else { + } + else + { return SystemColors.Window; } } - set { + set + { base.BackColor = value; } } @@ -306,11 +336,14 @@ public override Color BackColor { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } @@ -318,13 +351,15 @@ public override Image BackgroundImage { [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler AutoSizeChanged { + new public event EventHandler AutoSizeChanged + { add => base.AutoSizeChanged += value; remove => base.AutoSizeChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged { + new public event EventHandler BackgroundImageChanged + { add => base.BackgroundImageChanged += value; remove => base.BackgroundImageChanged -= value; } @@ -332,17 +367,21 @@ public override Image BackgroundImage { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { + new public event EventHandler BackgroundImageLayoutChanged + { add => base.BackgroundImageLayoutChanged += value; remove => base.BackgroundImageLayoutChanged -= value; } @@ -359,27 +398,33 @@ public override ImageLayout BackgroundImageLayout { DispId(NativeMethods.ActiveX.DISPID_BORDERSTYLE), SRDescription(nameof(SR.TextBoxBorderDescr)) ] - public BorderStyle BorderStyle { - get { + public BorderStyle BorderStyle + { + get + { return borderStyle; } - set { - if (borderStyle != value) { + set + { + if (borderStyle != value) + { //verify that 'value' is a valid enum type... //valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(BorderStyle)); } borderStyle = value; UpdateStyles(); - RecreateHandle(); + RecreateHandle(); // PreferredSize depends on BorderStyle : thru CreateParams.ExStyle in User32!AdjustRectEx. // So when the BorderStyle changes let the parent of this control know about it. - using(LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.BorderStyle)) { + using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.BorderStyle)) + { OnBorderStyleChanged(EventArgs.Empty); } } @@ -387,13 +432,16 @@ public BorderStyle BorderStyle { } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.TextBoxBaseOnBorderStyleChangedDescr))] - public event EventHandler BorderStyleChanged { + public event EventHandler BorderStyleChanged + { add => Events.AddHandler(EVENT_BORDERSTYLECHANGED, value); remove => Events.RemoveHandler(EVENT_BORDERSTYLECHANGED, value); } - internal virtual bool CanRaiseTextChangedEvent { - get { + internal virtual bool CanRaiseTextChangedEvent + { + get + { return true; } } @@ -401,14 +449,16 @@ internal virtual bool CanRaiseTextChangedEvent { /// /// Specifies whether the ImeMode can be enabled - See also ImeModeBase. /// - protected override bool CanEnableIme { - get { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_CanEnableIme(), this = " + this ); + protected override bool CanEnableIme + { + get + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_CanEnableIme(), this = " + this); Debug.Indent(); - bool canEnable = !( this.ReadOnly || this.PasswordProtect ) && base.CanEnableIme; + bool canEnable = !(this.ReadOnly || this.PasswordProtect) && base.CanEnableIme; - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Value = " + canEnable ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Value = " + canEnable); Debug.Unindent(); return canEnable; @@ -427,11 +477,14 @@ protected override bool CanEnableIme { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.TextBoxCanUndoDescr)) ] - public bool CanUndo { - get { - if (IsHandleCreated) { + public bool CanUndo + { + get + { + if (IsHandleCreated) + { bool b; - b = unchecked( (int) (long)SendMessage(Interop.EditMessages.EM_CANUNDO, 0, 0)) != 0; + b = unchecked((int)(long)SendMessage(Interop.EditMessages.EM_CANUNDO, 0, 0)) != 0; return b; } @@ -447,17 +500,22 @@ public bool CanUndo { /// filled up with the basic info. /// /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ClassName = "EDIT"; cp.Style |= NativeMethods.ES_AUTOHSCROLL | NativeMethods.ES_AUTOVSCROLL; - if (!textBoxFlags[hideSelection]) cp.Style |= NativeMethods.ES_NOHIDESEL; - if (textBoxFlags[readOnly]) cp.Style |= NativeMethods.ES_READONLY; + if (!textBoxFlags[hideSelection]) + cp.Style |= NativeMethods.ES_NOHIDESEL; + if (textBoxFlags[readOnly]) + cp.Style |= NativeMethods.ES_READONLY; cp.ExStyle &= (~NativeMethods.WS_EX_CLIENTEDGE); cp.Style &= (~NativeMethods.WS_BORDER); - switch (borderStyle) { + switch (borderStyle) + { case BorderStyle.Fixed3D: cp.ExStyle |= NativeMethods.WS_EX_CLIENTEDGE; break; @@ -465,9 +523,11 @@ protected override CreateParams CreateParams { cp.Style |= NativeMethods.WS_BORDER; break; } - if (textBoxFlags[multiline]) { + if (textBoxFlags[multiline]) + { cp.Style |= NativeMethods.ES_MULTILINE; - if (textBoxFlags[wordWrap]) cp.Style &= ~NativeMethods.ES_AUTOHSCROLL; + if (textBoxFlags[wordWrap]) + cp.Style &= ~NativeMethods.ES_AUTOHSCROLL; } return cp; @@ -479,29 +539,36 @@ protected override CreateParams CreateParams { /// on controls that are based on Win32 Native Controls. /// [EditorBrowsable(EditorBrowsableState.Never)] - protected override bool DoubleBuffered { - get { + protected override bool DoubleBuffered + { + get + { return base.DoubleBuffered; } - set { + set + { base.DoubleBuffered = value; } } [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] - public new event EventHandler Click { + public new event EventHandler Click + { add => base.Click += value; remove => base.Click -= value; } [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] - public new event MouseEventHandler MouseClick { + public new event MouseEventHandler MouseClick + { add => base.MouseClick += value; remove => base.MouseClick -= value; } - protected override Cursor DefaultCursor { - get { + protected override Cursor DefaultCursor + { + get + { return Cursors.IBeam; } } @@ -510,8 +577,10 @@ protected override Cursor DefaultCursor { /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(100, PreferredHeight); } } @@ -526,16 +595,21 @@ protected override Size DefaultSize { DispId(NativeMethods.ActiveX.DISPID_FORECOLOR), SRDescription(nameof(SR.ControlForeColorDescr)) ] - public override Color ForeColor { - get { - if (ShouldSerializeForeColor()) { + public override Color ForeColor + { + get + { + if (ShouldSerializeForeColor()) + { return base.ForeColor; } - else { + else + { return SystemColors.WindowText; } } - set { + set + { base.ForeColor = value; } } @@ -551,13 +625,17 @@ public override Color ForeColor { DefaultValue(true), SRDescription(nameof(SR.TextBoxHideSelectionDescr)) ] - public bool HideSelection { - get { + public bool HideSelection + { + get + { return textBoxFlags[hideSelection]; } - set { - if (textBoxFlags[hideSelection] != value) { + set + { + if (textBoxFlags[hideSelection] != value) + { textBoxFlags[hideSelection] = value; RecreateHandle(); OnHideSelectionChanged(EventArgs.Empty); @@ -566,7 +644,8 @@ public bool HideSelection { } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.TextBoxBaseOnHideSelectionChangedDescr))] - public event EventHandler HideSelectionChanged { + public event EventHandler HideSelectionChanged + { add => Events.AddHandler(EVENT_HIDESELECTIONCHANGED, value); remove => Events.RemoveHandler(EVENT_HIDESELECTIONCHANGED, value); } @@ -576,23 +655,27 @@ public event EventHandler HideSelectionChanged { /// mode which is determined by the CanEnableIme property which checks whether the control is in Password or /// ReadOnly mode. /// - protected override ImeMode ImeModeBase { - get { - if( DesignMode ) { + protected override ImeMode ImeModeBase + { + get + { + if (DesignMode) + { return base.ImeModeBase; } - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_ImeModeInternal(), this = " + this ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_ImeModeInternal(), this = " + this); Debug.Indent(); ImeMode imeMode = CanEnableIme ? base.ImeModeBase : ImeMode.Disable; - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Value = " + imeMode ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Value = " + imeMode); Debug.Unindent(); return imeMode; } - set { + set + { base.ImeModeBase = value; } } @@ -611,15 +694,19 @@ protected override ImeMode ImeModeBase { SRDescription(nameof(SR.TextBoxLinesDescr)), Editor("System.Windows.Forms.Design.StringArrayEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)) ] - public string[] Lines { - get { + public string[] Lines + { + get + { string text = Text; ArrayList list = new ArrayList(); int lineStart = 0; - while (lineStart < text.Length) { + while (lineStart < text.Length) + { int lineEnd = lineStart; - for (; lineEnd < text.Length; lineEnd++) { + for (; lineEnd < text.Length; lineEnd++) + { char c = text[lineEnd]; if (c == '\r' || c == '\n') break; @@ -641,26 +728,30 @@ public string[] Lines { if (text.Length > 0 && (text[text.Length - 1] == '\r' || text[text.Length - 1] == '\n')) list.Add(""); - return(string[]) list.ToArray(typeof(string)); + return (string[])list.ToArray(typeof(string)); } [ SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // We append a new line to the Text property. // Don't localize the new line character. ] - set { + set + { //unparse this string list... - if (value != null && value.Length > 0) { + if (value != null && value.Length > 0) + { // Using a StringBuilder instead of a String // speeds things up approx 150 times StringBuilder text = new StringBuilder(value[0]); - for (int i=1; i < value.Length; ++i) { + for (int i = 1; i < value.Length; ++i) + { text.Append("\r\n"); text.Append(value[i]); } Text = text.ToString(); } - else { + else + { Text = string.Empty; } } @@ -678,16 +769,21 @@ public string[] Lines { Localizable(true), SRDescription(nameof(SR.TextBoxMaxLengthDescr)) ] - public virtual int MaxLength { - get { + public virtual int MaxLength + { + get + { return maxLength; } - set { - if (value < 0) { + set + { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(MaxLength), value, 0)); } - if (maxLength != value) { + if (maxLength != value) + { maxLength = value; UpdateMaxLength(); } @@ -706,26 +802,34 @@ public virtual int MaxLength { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.TextBoxModifiedDescr)) ] - public bool Modified { - get { - if (IsHandleCreated) { - bool curState = (0 != unchecked( (int) (long)SendMessage(Interop.EditMessages.EM_GETMODIFY, 0, 0))); - if (textBoxFlags[modified] != curState) { + public bool Modified + { + get + { + if (IsHandleCreated) + { + bool curState = (0 != unchecked((int)(long)SendMessage(Interop.EditMessages.EM_GETMODIFY, 0, 0))); + if (textBoxFlags[modified] != curState) + { // Raise ModifiedChanged event. See WmReflectCommand for more info. textBoxFlags[modified] = curState; OnModifiedChanged(EventArgs.Empty); } return curState; } - else{ + else + { return textBoxFlags[modified]; } } - set { - if (Modified != value) { - if (IsHandleCreated) { + set + { + if (Modified != value) + { + if (IsHandleCreated) + { SendMessage(Interop.EditMessages.EM_SETMODIFY, value ? 1 : 0, 0); // Must maintain this state always in order for the // test in the Get method to work properly. @@ -738,7 +842,8 @@ public bool Modified { } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.TextBoxBaseOnModifiedChangedDescr))] - public event EventHandler ModifiedChanged { + public event EventHandler ModifiedChanged + { add => Events.AddHandler(EVENT_MODIFIEDCHANGED, value); remove => Events.RemoveHandler(EVENT_MODIFIEDCHANGED, value); } @@ -756,21 +861,28 @@ public event EventHandler ModifiedChanged { SRDescription(nameof(SR.TextBoxMultilineDescr)), RefreshProperties(RefreshProperties.All) ] - public virtual bool Multiline { - get { + public virtual bool Multiline + { + get + { return textBoxFlags[multiline]; } - set { - if (textBoxFlags[multiline] != value) { - using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.Multiline)) { + set + { + if (textBoxFlags[multiline] != value) + { + using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.Multiline)) + { textBoxFlags[multiline] = value; - if (value) { + if (value) + { // Multi-line textboxes do not have fixed height // SetStyle(ControlStyles.FixedHeight, false); } - else { + else + { // Single-line textboxes may have fixed height, depending on AutoSize SetStyle(ControlStyles.FixedHeight, AutoSize); } @@ -784,7 +896,8 @@ public virtual bool Multiline { } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.TextBoxBaseOnMultilineChangedDescr))] - public event EventHandler MultilineChanged { + public event EventHandler MultilineChanged + { add => Events.AddHandler(EVENT_MULTILINECHANGED, value); remove => Events.RemoveHandler(EVENT_MULTILINECHANGED, value); } @@ -794,9 +907,10 @@ public event EventHandler MultilineChanged { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Padding Padding { + public new Padding Padding + { get { return base.Padding; } - set { base.Padding = value;} + set { base.Padding = value; } } [ @@ -805,7 +919,8 @@ public event EventHandler MultilineChanged { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRCategory(nameof(SR.CatLayout)), SRDescription(nameof(SR.ControlOnPaddingChangedDescr)) ] - public new event EventHandler PaddingChanged { + public new event EventHandler PaddingChanged + { add => base.PaddingChanged += value; remove => base.PaddingChanged -= value; } @@ -817,7 +932,8 @@ public event EventHandler MultilineChanged { /// virtual internal bool PasswordProtect { - get { + get + { return false; } } @@ -834,13 +950,16 @@ virtual internal bool PasswordProtect DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.TextBoxPreferredHeightDescr)) ] - public int PreferredHeight { - get { + public int PreferredHeight + { + get + { // COMPAT we must return the same busted height we did in Everett, even // if it doesnt take multiline and word wrap into account. For better accuracy and/or wrapping use // GetPreferredSize instead. int height = FontHeight; - if (borderStyle != BorderStyle.None) { + if (borderStyle != BorderStyle.None) + { height += SystemInformation.GetBorderSizeForDpi(deviceDpi).Height * 4 + 3; } return height; @@ -850,7 +969,7 @@ public int PreferredHeight { // GetPreferredSizeCore // This method can return a different value than PreferredHeight! It properly handles // border style + multiline and wordwrap. - + internal override Size GetPreferredSizeCore(Size proposedConstraints) { // 3px vertical space is required between the text and the border to keep the last @@ -860,11 +979,13 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) // however the [ ] was only added if borderstyle was not none. Size bordersAndPadding = SizeFromClientSize(Size.Empty) + Padding.Size; - if (BorderStyle != BorderStyle.None) { + if (BorderStyle != BorderStyle.None) + { bordersAndPadding += new Size(0, 3); } - if (BorderStyle == BorderStyle.FixedSingle) { + if (BorderStyle == BorderStyle.FixedSingle) + { // Bump these by 2px to match BorderStyle.Fixed3D - they'll be omitted from the SizeFromClientSize call. bordersAndPadding.Width += 2; bordersAndPadding.Height += 2; @@ -876,9 +997,12 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) // Fix for Dev10 TextFormatFlags format = TextFormatFlags.NoPrefix; - if(!Multiline) { + if (!Multiline) + { format |= TextFormatFlags.SingleLine; - } else if(WordWrap) { + } + else if (WordWrap) + { format |= TextFormatFlags.WordBreak; } Size textSize = TextRenderer.MeasureText(this.Text, this.Font, proposedConstraints, format); @@ -894,28 +1018,31 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) /// to avoid calling SelectionStart + SelectionLength each of which does essentially the /// same (save one message round trip). /// - internal void GetSelectionStartAndLength( out int start, out int length ){ + internal void GetSelectionStartAndLength(out int start, out int length) + { int end = 0; - if( !IsHandleCreated ) { + if (!IsHandleCreated) + { // It is possible that the cached values are no longer valid if the Text has been changed // while the control does not have a handle. We need to return valid values. We also need // to keep the old cached values in case the Text is changed again making the cached values // valid again. - AdjustSelectionStartAndEnd( this.selectionStart, this.selectionLength, out start, out end, -1 ); + AdjustSelectionStartAndEnd(this.selectionStart, this.selectionLength, out start, out end, -1); length = end - start; } - else { + else + { start = 0; - UnsafeNativeMethods.SendMessage( new HandleRef( this, Handle ), Interop.EditMessages.EM_GETSEL, ref start, ref end ); + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_GETSEL, ref start, ref end); //Here, we return the max of either 0 or the # returned by //the windows call. This eliminates a problem on nt4 where // a huge negative # is being returned. // - start = Math.Max( 0, start ); + start = Math.Max(0, start); // ditto for end - end = Math.Max( 0, end ); + end = Math.Max(0, end); length = end - start; } @@ -927,15 +1054,17 @@ internal void GetSelectionStartAndLength( out int start, out int length ){ end = start + length - 1; - if (t == null) { + if (t == null) + { len = 0; } - else { + else + { len = t.Length; } Debug.Assert(end <= len, "SelectionEnd is outside the set of valid caret positions for the current WindowText (end =" - + end + ", WindowText.Length =" + len +")"); + + end + ", WindowText.Length =" + len + ")"); } #endif } @@ -951,15 +1080,20 @@ internal void GetSelectionStartAndLength( out int start, out int length ){ RefreshProperties(RefreshProperties.Repaint), SRDescription(nameof(SR.TextBoxReadOnlyDescr)) ] - public bool ReadOnly { - get { + public bool ReadOnly + { + get + { return textBoxFlags[readOnly]; } - set { - if (textBoxFlags[readOnly] != value) { + set + { + if (textBoxFlags[readOnly] != value) + { textBoxFlags[readOnly] = value; - if (IsHandleCreated) { - SendMessage(Interop.EditMessages.EM_SETREADONLY, value? -1: 0, 0); + if (IsHandleCreated) + { + SendMessage(Interop.EditMessages.EM_SETREADONLY, value ? -1 : 0, 0); } OnReadOnlyChanged(EventArgs.Empty); @@ -970,7 +1104,8 @@ public bool ReadOnly { } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.TextBoxBaseOnReadOnlyChangedDescr))] - public event EventHandler ReadOnlyChanged { + public event EventHandler ReadOnlyChanged + { add => Events.AddHandler(EVENT_READONLYCHANGED, value); remove => Events.RemoveHandler(EVENT_READONLYCHANGED, value); } @@ -986,13 +1121,16 @@ public event EventHandler ReadOnlyChanged { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.TextBoxSelectedTextDescr)) ] - public virtual string SelectedText { - get { + public virtual string SelectedText + { + get + { int selStart, selLength; - GetSelectionStartAndLength( out selStart, out selLength ); + GetSelectionStartAndLength(out selStart, out selLength); return Text.Substring(selStart, selLength); } - set { + set + { SetSelectedTextInternal(value, true); } } @@ -1000,12 +1138,15 @@ public virtual string SelectedText { /// /// Replaces the selected text with the one passed in. /// - internal virtual void SetSelectedTextInternal(string text, bool clearUndo){ - if (!IsHandleCreated) { + internal virtual void SetSelectedTextInternal(string text, bool clearUndo) + { + if (!IsHandleCreated) + { CreateHandle(); } - if( text == null ){ + if (text == null) + { text = string.Empty; } @@ -1014,13 +1155,15 @@ internal virtual void SetSelectedTextInternal(string text, bool clearUndo){ // copied to the edit control by the WM_SETTEXT message. SendMessage(Interop.EditMessages.EM_LIMITTEXT, 0, 0); - if( clearUndo ){ + if (clearUndo) + { SendMessage(Interop.EditMessages.EM_REPLACESEL, 0, text); // For consistency with Text, we clear the modified flag SendMessage(Interop.EditMessages.EM_SETMODIFY, 0, 0); ClearUndo(); } - else{ + else + { SendMessage(Interop.EditMessages.EM_REPLACESEL, /*undoable*/ -1, text); } @@ -1041,24 +1184,29 @@ internal virtual void SetSelectedTextInternal(string text, bool clearUndo){ DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.TextBoxSelectionLengthDescr)) ] - public virtual int SelectionLength { - get { + public virtual int SelectionLength + { + get + { int start, length; - GetSelectionStartAndLength( out start, out length ); + GetSelectionStartAndLength(out start, out length); return length; } - set { - if (value < 0){ + set + { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(SelectionLength), value)); } int selStart, selLength; - GetSelectionStartAndLength( out selStart, out selLength ); + GetSelectionStartAndLength(out selStart, out selLength); - if (value != selLength) { + if (value != selLength) + { Select(selStart, value); } } @@ -1077,16 +1225,20 @@ public virtual int SelectionLength { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.TextBoxSelectionStartDescr)) ] - public int SelectionStart { - get { + public int SelectionStart + { + get + { int selStart, selLength; - GetSelectionStartAndLength( out selStart, out selLength ); + GetSelectionStartAndLength(out selStart, out selLength); return selStart; } - set { - if (value < 0){ + set + { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(SelectionStart), value)); } Select(value, SelectionLength); @@ -1094,8 +1246,10 @@ public int SelectionStart { } // Call SetSelectionOnHandle inside CreateHandle() - internal virtual bool SetSelectionInCreateHandle { - get { + internal virtual bool SetSelectionInCreateHandle + { + get + { return true; } } @@ -1110,14 +1264,19 @@ internal virtual bool SetSelectionInCreateHandle { Localizable(true), Editor("System.ComponentModel.Design.MultilineStringEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)) ] - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { - if (value != base.Text) { + set + { + if (value != base.Text) + { base.Text = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { // clear the modified flag SendMessage(Interop.EditMessages.EM_SETMODIFY, 0, 0); } @@ -1139,19 +1298,26 @@ public virtual int TextLength // /// /// - internal override string WindowText { - get { + internal override string WindowText + { + get + { return base.WindowText; } - set { - if (value == null) value = string.Empty; - if (!WindowText.Equals(value)) { + set + { + if (value == null) + value = string.Empty; + if (!WindowText.Equals(value)) + { textBoxFlags[codeUpdateText] = true; - try { + try + { base.WindowText = value; } - finally { + finally + { textBoxFlags[codeUpdateText] = false; } } @@ -1164,26 +1330,34 @@ internal override string WindowText { /// Make this a method on TextBoxBase rather than RichTextBox (which is the only /// control that needs this at this point), since we need to set codeUpdateText. /// - internal void ForceWindowText(string value) { - if (value == null) { + internal void ForceWindowText(string value) + { + if (value == null) + { value = string.Empty; } - + textBoxFlags[codeUpdateText] = true; - try { - if (IsHandleCreated) { + try + { + if (IsHandleCreated) + { Interop.User32.SetWindowTextW(new HandleRef(this, Handle), value); } - else { - if (value.Length == 0) { + else + { + if (value.Length == 0) + { Text = null; } - else { + else + { Text = value; } } } - finally { + finally + { textBoxFlags[codeUpdateText] = false; } } @@ -1201,13 +1375,18 @@ internal void ForceWindowText(string value) { DefaultValue(true), SRDescription(nameof(SR.TextBoxWordWrapDescr)) ] - public bool WordWrap { - get { + public bool WordWrap + { + get + { return textBoxFlags[wordWrap]; } - set { - using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.WordWrap)) { - if (textBoxFlags[wordWrap] != value) { + set + { + using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.WordWrap)) + { + if (textBoxFlags[wordWrap] != value) + { textBoxFlags[wordWrap] = value; RecreateHandle(); } @@ -1219,21 +1398,26 @@ public bool WordWrap { /// Adjusts the height of a single-line edit control to match the height of /// the control's font. /// - private void AdjustHeight(bool returnIfAnchored) { + private void AdjustHeight(bool returnIfAnchored) + { // If we're anchored to two opposite sides of the form, don't adjust the size because // we'll lose our anchored size by resetting to the requested width. // - if (returnIfAnchored && (this.Anchor & (AnchorStyles.Top | AnchorStyles.Bottom)) == (AnchorStyles.Top | AnchorStyles.Bottom)) { + if (returnIfAnchored && (this.Anchor & (AnchorStyles.Top | AnchorStyles.Bottom)) == (AnchorStyles.Top | AnchorStyles.Bottom)) + { return; } int saveHeight = requestedHeight; - try { - if (textBoxFlags[autoSize] && !textBoxFlags[multiline]) { + try + { + if (textBoxFlags[autoSize] && !textBoxFlags[multiline]) + { Height = PreferredHeight; } - else { + else + { int curHeight = Height; @@ -1241,20 +1425,24 @@ private void AdjustHeight(bool returnIfAnchored) { // The only workaround I can find is to size the textbox big enough for the font, and // then restore its correct size. // - if (textBoxFlags[multiline]) { + if (textBoxFlags[multiline]) + { Height = Math.Max(saveHeight, PreferredHeight + 2); // 2 = fudge factor } integralHeightAdjust = true; - try { + try + { Height = saveHeight; } - finally { + finally + { integralHeightAdjust = false; } } } - finally { + finally + { requestedHeight = saveHeight; } } @@ -1264,25 +1452,30 @@ private void AdjustHeight(bool returnIfAnchored) { /// Append text to the current text of text box. /// /// - public void AppendText( string text ) { - if (text.Length > 0) { + public void AppendText(string text) + { + if (text.Length > 0) + { int selStart, selLength; - GetSelectionStartAndLength( out selStart, out selLength ); + GetSelectionStartAndLength(out selStart, out selLength); - try { + try + { // This enables you to use SelectionColor to AppendText in color. int endOfText = GetEndPosition(); SelectInternal(endOfText, endOfText, endOfText); SelectedText = text; } - finally { + finally + { // If AppendText is called when the control is docked and the form is minimized, // all the text will scroll to the top and the control will look empty when the // form is restored. We work around this by selecting back whatever was originally // selected when AppendText was called. - if (this.Width == 0 || this.Height == 0) { + if (this.Width == 0 || this.Height == 0) + { this.Select(selStart, selLength); } } @@ -1294,7 +1487,8 @@ public void AppendText( string text ) { /// Clears all text from the text box control. /// /// - public void Clear() { + public void Clear() + { Text = null; } @@ -1304,8 +1498,10 @@ public void Clear() { /// from the undo buffer of the text box. /// /// - public void ClearUndo() { - if (IsHandleCreated) { + public void ClearUndo() + { + if (IsHandleCreated) + { SendMessage(Interop.EditMessages.EM_EMPTYUNDOBUFFER, 0, 0); } } @@ -1315,26 +1511,31 @@ public void ClearUndo() { /// Copies the current selection in the text box to the Clipboard. /// /// - public void Copy() { + public void Copy() + { SendMessage(Interop.WindowMessages.WM_COPY, 0, 0); } /// /// - protected override void CreateHandle() { + protected override void CreateHandle() + { // This "creatingHandle" stuff is to avoid property change events // when we set the Text property. textBoxFlags[creatingHandle] = true; - try { + try + { base.CreateHandle(); - if (SetSelectionInCreateHandle) { + if (SetSelectionInCreateHandle) + { // send EM_SETSEL message SetSelectionOnHandle(); } - + } - finally { + finally + { textBoxFlags[creatingHandle] = false; } } @@ -1344,7 +1545,8 @@ protected override void CreateHandle() { /// Moves the current selection in the text box to the Clipboard. /// /// - public void Cut() { + public void Cut() + { SendMessage(Interop.WindowMessages.WM_CUT, 0, 0); } @@ -1352,7 +1554,8 @@ public void Cut() { /// Returns the text end position (one past the last input character). This property is virtual to allow MaskedTextBox /// to set the last input char position as opposed to the last char position which may be a mask character. /// - internal virtual int GetEndPosition(){ + internal virtual int GetEndPosition() + { // +1 because RichTextBox has this funny EOF pseudo-character after all the text. return IsHandleCreated ? TextLength + 1 : TextLength; } @@ -1360,9 +1563,12 @@ internal virtual int GetEndPosition(){ /// /// Overridden to handle TAB key. /// - protected override bool IsInputKey(Keys keyData) { - if ((keyData & Keys.Alt) != Keys.Alt) { - switch (keyData & Keys.KeyCode) { + protected override bool IsInputKey(Keys keyData) + { + if ((keyData & Keys.Alt) != Keys.Alt) + { + switch (keyData & Keys.KeyCode) + { case Keys.Tab: // Single-line RichEd's want tab characters (see WM_GETDLGCODE), // so we don't ask it @@ -1390,7 +1596,8 @@ protected override bool IsInputKey(Keys keyData) { /// Overridden to update the newly created handle with the settings of the /// MaxLength and PasswordChar properties. /// - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { base.OnHandleCreated(e); // it's likely here that the create params could have changed // the border size/etc. @@ -1398,10 +1605,12 @@ protected override void OnHandleCreated(EventArgs e) { AdjustHeight(true); UpdateMaxLength(); - if (textBoxFlags[modified]){ + if (textBoxFlags[modified]) + { SendMessage(Interop.EditMessages.EM_SETMODIFY, 1, 0); } - if (textBoxFlags[scrollToCaretOnHandleCreated]) { + if (textBoxFlags[scrollToCaretOnHandleCreated]) + { ScrollToCaret(); textBoxFlags[scrollToCaretOnHandleCreated] = false; } @@ -1409,11 +1618,12 @@ protected override void OnHandleCreated(EventArgs e) { /// /// - protected override void OnHandleDestroyed(EventArgs e) { + protected override void OnHandleDestroyed(EventArgs e) + { textBoxFlags[modified] = Modified; - textBoxFlags[setSelectionOnHandleCreated] = true; + textBoxFlags[setSelectionOnHandleCreated] = true; // Update text selection cached values to be restored when recreating the handle. - GetSelectionStartAndLength( out this.selectionStart, out this.selectionLength ); + GetSelectionStartAndLength(out this.selectionStart, out this.selectionLength); base.OnHandleDestroyed(e); } @@ -1422,15 +1632,18 @@ protected override void OnHandleDestroyed(EventArgs e) { /// Replaces the current selection in the text box with the contents of the Clipboard. /// /// - public void Paste() { + public void Paste() + { SendMessage(Interop.WindowMessages.WM_PASTE, 0, 0); } - protected override bool ProcessDialogKey(Keys keyData) { + protected override bool ProcessDialogKey(Keys keyData) + { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "TextBoxBase.ProcessDialogKey [" + keyData.ToString() + "]"); Keys keyCode = (Keys)keyData & Keys.KeyCode; - if (keyCode == Keys.Tab && this.AcceptsTab && (keyData & Keys.Control) != 0) { + if (keyCode == Keys.Tab && this.AcceptsTab && (keyData & Keys.Control) != 0) + { // When this control accepts Tabs, Ctrl-Tab is treated exactly like Tab. keyData &= ~Keys.Control; } @@ -1443,58 +1656,73 @@ protected override bool ProcessDialogKey(Keys keyData) { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event PaintEventHandler Paint { + public new event PaintEventHandler Paint + { add => base.Paint += value; remove => base.Paint -= value; } - protected virtual void OnAcceptsTabChanged(EventArgs e) { + protected virtual void OnAcceptsTabChanged(EventArgs e) + { EventHandler eh = Events[EVENT_ACCEPTSTABCHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } - protected virtual void OnBorderStyleChanged(EventArgs e) { + protected virtual void OnBorderStyleChanged(EventArgs e) + { EventHandler eh = Events[EVENT_BORDERSTYLECHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { base.OnFontChanged(e); AdjustHeight(false); } - protected virtual void OnHideSelectionChanged(EventArgs e) { + protected virtual void OnHideSelectionChanged(EventArgs e) + { EventHandler eh = Events[EVENT_HIDESELECTIONCHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } - protected virtual void OnModifiedChanged(EventArgs e) { + protected virtual void OnModifiedChanged(EventArgs e) + { EventHandler eh = Events[EVENT_MODIFIEDCHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } - /// + /// /// Raises the MouseUp event. /// - protected override void OnMouseUp(MouseEventArgs mevent) { + protected override void OnMouseUp(MouseEventArgs mevent) + { Point pt = PointToScreen(mevent.Location); - if (mevent.Button == MouseButtons.Left) { - if (!ValidationCancelled && UnsafeNativeMethods.WindowFromPoint(pt.X, pt.Y) == Handle) { - if (!this.doubleClickFired) { + if (mevent.Button == MouseButtons.Left) + { + if (!ValidationCancelled && UnsafeNativeMethods.WindowFromPoint(pt.X, pt.Y) == Handle) + { + if (!this.doubleClickFired) + { OnClick(mevent); OnMouseClick(mevent); } - else { + else + { this.doubleClickFired = false; OnDoubleClick(mevent); OnMouseDoubleClick(mevent); @@ -1505,27 +1733,33 @@ protected override void OnMouseUp(MouseEventArgs mevent) { base.OnMouseUp(mevent); } - protected virtual void OnMultilineChanged(EventArgs e) { + protected virtual void OnMultilineChanged(EventArgs e) + { EventHandler eh = Events[EVENT_MULTILINECHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } - protected override void OnPaddingChanged(EventArgs e) { + protected override void OnPaddingChanged(EventArgs e) + { base.OnPaddingChanged(e); AdjustHeight(false); } - protected virtual void OnReadOnlyChanged(EventArgs e) { + protected virtual void OnReadOnlyChanged(EventArgs e) + { EventHandler eh = Events[EVENT_READONLYCHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } - protected override void OnTextChanged(EventArgs e) { + protected override void OnTextChanged(EventArgs e) + { // since AutoSize existed in Everett, (and is the default) we can't // relayout the parent when the "preferredsize" of the control changes. // this means a multiline = true textbox wont natrually grow in height when @@ -1537,7 +1771,8 @@ protected override void OnTextChanged(EventArgs e) { /// /// Returns the character nearest to the given point. /// - public virtual char GetCharFromPosition(Point pt) { + public virtual char GetCharFromPosition(Point pt) + { string t = this.Text; int index = GetCharIndexFromPosition(pt); return (index < 0 || index >= t.Length) ? (char)0 : t[index]; @@ -1546,20 +1781,24 @@ public virtual char GetCharFromPosition(Point pt) { /// /// Returns the index of the character nearest to the given point. /// - public virtual int GetCharIndexFromPosition(Point pt) { + public virtual int GetCharIndexFromPosition(Point pt) + { int longPoint = NativeMethods.Util.MAKELONG(pt.X, pt.Y); int index = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_CHARFROMPOS, 0, longPoint); index = NativeMethods.Util.LOWORD(index); - if (index < 0) { + if (index < 0) + { index = 0; } - else { + else + { string t = this.Text; // EM_CHARFROMPOS will return an invalid number if the last character in the RichEdit // is a newline. // - if (index >= t.Length) { + if (index >= t.Length) + { index = Math.Max(t.Length - 1, 0); } } @@ -1574,14 +1813,16 @@ public virtual int GetCharIndexFromPosition(Point pt) { /// you pass the index of a overflowed character, GetLineFromCharIndex would /// return 1 and not 0. /// - public virtual int GetLineFromCharIndex(int index) { - return unchecked( (int) (long)SendMessage(Interop.EditMessages.EM_LINEFROMCHAR, index, 0)); + public virtual int GetLineFromCharIndex(int index) + { + return unchecked((int)(long)SendMessage(Interop.EditMessages.EM_LINEFROMCHAR, index, 0)); } /// /// Returns the location of the character at the given index. /// - public virtual Point GetPositionFromCharIndex(int index) { + public virtual Point GetPositionFromCharIndex(int index) + { if (index < 0 || index >= Text.Length) return Point.Empty; @@ -1592,18 +1833,21 @@ public virtual Point GetPositionFromCharIndex(int index) { /// /// Returns the index of the first character of a given line. Returns -1 of lineNumber is invalid. /// - public int GetFirstCharIndexFromLine(int lineNumber) { - if (lineNumber < 0) { + public int GetFirstCharIndexFromLine(int lineNumber) + { + if (lineNumber < 0) + { throw new ArgumentOutOfRangeException(nameof(lineNumber), lineNumber, string.Format(SR.InvalidArgument, nameof(lineNumber), lineNumber)); } - return unchecked( (int) (long)SendMessage(Interop.EditMessages.EM_LINEINDEX, lineNumber, 0)); + return unchecked((int)(long)SendMessage(Interop.EditMessages.EM_LINEINDEX, lineNumber, 0)); } /// /// Returns the index of the first character of the line where the caret is. /// - public int GetFirstCharIndexOfCurrentLine() { - return unchecked( (int) (long)SendMessage(Interop.EditMessages.EM_LINEINDEX, -1, 0)); + public int GetFirstCharIndexOfCurrentLine() + { + return unchecked((int)(long)SendMessage(Interop.EditMessages.EM_LINEINDEX, -1, 0)); } @@ -1612,9 +1856,12 @@ public int GetFirstCharIndexOfCurrentLine() { /// Ensures that the caret is visible in the TextBox window, by scrolling the /// TextBox control surface if necessary. /// - public void ScrollToCaret() { - if (IsHandleCreated) { - if (string.IsNullOrEmpty(this.WindowText)) { + public void ScrollToCaret() + { + if (IsHandleCreated) + { + if (string.IsNullOrEmpty(this.WindowText)) + { // If there is no text, then there is no place to go. return; } @@ -1622,21 +1869,26 @@ public void ScrollToCaret() { bool scrolled = false; object editOle = null; IntPtr editOlePtr = IntPtr.Zero; - try { - if (UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_GETOLEINTERFACE, 0, out editOle) != 0) { + try + { + if (UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_GETOLEINTERFACE, 0, out editOle) != 0) + { editOlePtr = Marshal.GetIUnknownForObject(editOle); - if (editOlePtr != IntPtr.Zero) { + if (editOlePtr != IntPtr.Zero) + { IntPtr iTextDocument = IntPtr.Zero; Guid iiTextDocumentGuid = typeof(UnsafeNativeMethods.ITextDocument).GUID; - try { + try + { Marshal.QueryInterface(editOlePtr, ref iiTextDocumentGuid, out iTextDocument); UnsafeNativeMethods.ITextDocument textDocument = Marshal.GetObjectForIUnknown(iTextDocument) as UnsafeNativeMethods.ITextDocument; - if (textDocument != null) { + if (textDocument != null) + { int selStart, selLength; // When the user calls RichTextBox::ScrollToCaret we want the RichTextBox to show as @@ -1647,7 +1899,7 @@ public void ScrollToCaret() { // 3. If the first visible line is smaller than the start of the selection, then we are done: // The selection fits inside the RichTextBox display rectangle. // 4. Otherwise, scroll the selection to the top of the RichTextBox. - GetSelectionStartAndLength( out selStart, out selLength ); + GetSelectionStartAndLength(out selStart, out selLength); int selStartLine = GetLineFromCharIndex(selStart); // 1. Scroll the RichTextBox all the way to the bottom @@ -1655,12 +1907,15 @@ public void ScrollToCaret() { textRange.ScrollIntoView(0); // 0 ==> tomEnd // 2. Get the first visible line. - int firstVisibleLine = unchecked( (int) (long)SendMessage(Interop.EditMessages.EM_GETFIRSTVISIBLELINE, 0, 0)); + int firstVisibleLine = unchecked((int)(long)SendMessage(Interop.EditMessages.EM_GETFIRSTVISIBLELINE, 0, 0)); // 3. If the first visible line is smaller than the start of the selection, we are done; - if (firstVisibleLine <= selStartLine) { + if (firstVisibleLine <= selStartLine) + { // we are done - } else { + } + else + { // 4. Scroll the selection to the top of the RichTextBox textRange = textDocument.Range(selStart, selStart + selLength); textRange.ScrollIntoView(32); // 32 ==> tomStart @@ -1668,24 +1923,32 @@ public void ScrollToCaret() { scrolled = true; } - } finally { - if (iTextDocument != IntPtr.Zero) { + } + finally + { + if (iTextDocument != IntPtr.Zero) + { Marshal.Release(iTextDocument); } } } } - } finally { - if (editOlePtr != IntPtr.Zero) { + } + finally + { + if (editOlePtr != IntPtr.Zero) + { Marshal.Release(editOlePtr); } } - if (!scrolled) { + if (!scrolled) + { SendMessage(Interop.EditMessages.EM_SCROLLCARET, 0, 0); } } - else { + else + { textBoxFlags[scrollToCaretOnHandleCreated] = true; } } @@ -1695,7 +1958,8 @@ public void ScrollToCaret() { /// Sets the SelectionLength to 0. /// /// - public void DeselectAll() { + public void DeselectAll() + { this.SelectionLength = 0; } @@ -1704,21 +1968,26 @@ public void DeselectAll() { /// Selects a range of text in the text box. /// /// - public void Select(int start, int length) { - if (start < 0){ + public void Select(int start, int length) + { + if (start < 0) + { throw new ArgumentOutOfRangeException(nameof(start), start, string.Format(SR.InvalidArgument, nameof(start), start)); } int textLen = TextLength; - if (start > textLen) { + if (start > textLen) + { //We shouldn't allow positive length if you're starting at the end, but //should allow negative length. long longLength = Math.Min(0, (long)length + start - textLen); - if (longLength < int.MinValue) { + if (longLength < int.MinValue) + { length = int.MinValue; } - else { + else + { length = (int)longLength; } start = textLen; @@ -1735,9 +2004,11 @@ public void Select(int start, int length) { /// But if you do have it cached, please pass it in. This will avoid /// the expensive call to the TextLength property. /// - internal virtual void SelectInternal(int start, int length, int textLen) { + internal virtual void SelectInternal(int start, int length, int textLen) + { //if our handle is created - send message... - if (IsHandleCreated) { + if (IsHandleCreated) + { int s, e; AdjustSelectionStartAndEnd(start, length, out s, out e, textLen); @@ -1745,7 +2016,8 @@ internal virtual void SelectInternal(int start, int length, int textLen) { // } - else { + else + { //otherwise, wait until handle is created to send this message. //Store the indices until then... this.selectionStart = start; @@ -1759,7 +2031,8 @@ internal virtual void SelectInternal(int start, int length, int textLen) { /// Selects all text in the text box. /// /// - public void SelectAll() { + public void SelectAll() + { int textLen = TextLength; SelectInternal(0, textLen, textLen); } @@ -1767,7 +2040,8 @@ public void SelectAll() { /// /// Overrides Control.setBoundsCore to enforce autoSize. /// - protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { + protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) + { if (!integralHeightAdjust && height != Height) requestedHeight = height; @@ -1778,7 +2052,8 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound base.SetBoundsCore(x, y, width, height, specified); } - private static void Swap(ref int n1, ref int n2) { + private static void Swap(ref int n1, ref int n2) + { int temp = n2; n2 = n1; n1 = temp; @@ -1790,86 +2065,104 @@ private static void Swap(ref int n1, ref int n2) { // please pass in the text length as the last parameter. // This will avoid the expensive call to the TextLength // property. - internal void AdjustSelectionStartAndEnd(int selStart, int selLength, out int start, out int end, int textLen) { + internal void AdjustSelectionStartAndEnd(int selStart, int selLength, out int start, out int end, int textLen) + { start = selStart; end = 0; - if (start <= -1) { + if (start <= -1) + { start = -1; } - else { + else + { int textLength; - if (textLen >= 0) { + if (textLen >= 0) + { textLength = textLen; } - else { + else + { textLength = this.TextLength; } - if (start > textLength) { + if (start > textLength) + { start = textLength; } - checked { - try { + checked + { + try + { end = start + selLength; - } - catch (OverflowException) { + } + catch (OverflowException) + { //Since we overflowed, cap at the max/min value: we'll correct the value below end = start > 0 ? int.MaxValue : int.MinValue; } } // Make sure end is in range - if (end < 0) { + if (end < 0) + { end = 0; } - else if (end > textLength) { + else if (end > textLength) + { end = textLength; } } } // Called by CreateHandle or OnHandleCreated - internal void SetSelectionOnHandle() { + internal void SetSelectionOnHandle() + { Debug.Assert(IsHandleCreated, "Don't call this method until the handle is created."); - if (textBoxFlags[setSelectionOnHandleCreated]) { + if (textBoxFlags[setSelectionOnHandleCreated]) + { textBoxFlags[setSelectionOnHandleCreated] = false; int start, end; AdjustSelectionStartAndEnd(this.selectionStart, this.selectionLength, out start, out end, -1); SendMessage(Interop.EditMessages.EM_SETSEL, start, end); } } - + /// /// Converts byte offsset to unicode offsets. /// When procssing WM_GETSEL/WM_SETSEL, EDIT control works with byte offsets instead of character positions /// as opposed to RICHEDIT which does it always as character positions. /// This method is used when handling the WM_GETSEL message. /// - static void ToUnicodeOffsets(string str, ref int start, ref int end) { + static void ToUnicodeOffsets(string str, ref int start, ref int end) + { Encoding e = Encoding.Default; byte[] bytes = e.GetBytes(str); bool swap = start > end; - if (swap) { + if (swap) + { Swap(ref start, ref end); } // Make sure start and end are within the string // - if (start < 0){ + if (start < 0) + { start = 0; } - if (start > bytes.Length){ + if (start > bytes.Length) + { start = bytes.Length; } - if (end > bytes.Length){ + if (end > bytes.Length) + { end = bytes.Length; } - + // IMPORTANT: Avoid off-by-1 errors! // The end value passed in is the character immediately after the last character selected. @@ -1877,7 +2170,8 @@ static void ToUnicodeOffsets(string str, ref int start, ref int end) { end = newStart + e.GetCharCount(bytes, start, end - start); start = newStart; - if (swap){ + if (swap) + { Swap(ref start, ref end); } } @@ -1888,37 +2182,44 @@ static void ToUnicodeOffsets(string str, ref int start, ref int end) { /// as opposed to RICHEDIT which does it always as character positions. /// This method is used when handling the WM_SETSEL message. /// - static internal void ToDbcsOffsets(string str, ref int start, ref int end) { + static internal void ToDbcsOffsets(string str, ref int start, ref int end) + { Encoding e = Encoding.Default; bool swap = start > end; - if (swap) { + if (swap) + { Swap(ref start, ref end); } // Make sure start and end are within the string // - if (start < 0) { + if (start < 0) + { start = 0; } - if (start > str.Length) { + if (start > str.Length) + { start = str.Length; } - if (end < start) { + if (end < start) + { end = start; } - if (end > str.Length) { + if (end > str.Length) + { end = str.Length; } // IMPORTANT: Avoid off-by-1 errors! // The end value passed in is the character immediately after the last character selected. - int newStart = start == 0 ? 0 : e.GetByteCount(str.Substring(0, start)); + int newStart = start == 0 ? 0 : e.GetByteCount(str.Substring(0, start)); end = newStart + e.GetByteCount(str.Substring(start, end - start)); start = newStart; - if (swap) { + if (swap) + { Swap(ref start, ref end); } } @@ -1929,12 +2230,14 @@ static internal void ToDbcsOffsets(string str, ref int start, ref int end) { /// Provides some interesting information for the TextBox control in /// String form. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); string txt = Text; - if (txt.Length > 40) txt = txt.Substring(0, 40) + "..."; + if (txt.Length > 40) + txt = txt.Substring(0, 40) + "..."; return s + ", Text: " + txt.ToString(); } @@ -1943,38 +2246,47 @@ public override string ToString() { /// Undoes the last edit operation in the text box. /// /// - public void Undo() { + public void Undo() + { SendMessage(Interop.EditMessages.EM_UNDO, 0, 0); } - internal virtual void UpdateMaxLength() { - if (IsHandleCreated) { + internal virtual void UpdateMaxLength() + { + if (IsHandleCreated) + { SendMessage(Interop.EditMessages.EM_LIMITTEXT, maxLength, 0); } } - internal override IntPtr InitializeDCForWmCtlColor (IntPtr dc, int msg) + internal override IntPtr InitializeDCForWmCtlColor(IntPtr dc, int msg) { - if ((msg == Interop.WindowMessages.WM_CTLCOLORSTATIC) && !ShouldSerializeBackColor()) { + if ((msg == Interop.WindowMessages.WM_CTLCOLORSTATIC) && !ShouldSerializeBackColor()) + { // Let the Win32 Edit control handle background colors itself. // This is necessary because a disabled edit control will display a different // BackColor than when enabled. return IntPtr.Zero; } - else { + else + { return base.InitializeDCForWmCtlColor(dc, msg); } } /// /// - private void WmReflectCommand(ref Message m) { - if (!textBoxFlags[codeUpdateText] && !textBoxFlags[creatingHandle]) { - if (NativeMethods.Util.HIWORD(m.WParam) == NativeMethods.EN_CHANGE && CanRaiseTextChangedEvent) { + private void WmReflectCommand(ref Message m) + { + if (!textBoxFlags[codeUpdateText] && !textBoxFlags[creatingHandle]) + { + if (NativeMethods.Util.HIWORD(m.WParam) == NativeMethods.EN_CHANGE && CanRaiseTextChangedEvent) + { OnTextChanged(EventArgs.Empty); } - else if (NativeMethods.Util.HIWORD(m.WParam) == NativeMethods.EN_UPDATE) { + else if (NativeMethods.Util.HIWORD(m.WParam) == NativeMethods.EN_UPDATE) + { // Force update to the Modified property, which will trigger // ModifiedChanged event handlers bool force = this.Modified; @@ -1984,22 +2296,27 @@ private void WmReflectCommand(ref Message m) { /// /// - void WmSetFont(ref Message m) { + void WmSetFont(ref Message m) + { base.WndProc(ref m); - if (!textBoxFlags[multiline]) { + if (!textBoxFlags[multiline]) + { SendMessage(Interop.EditMessages.EM_SETMARGINS, NativeMethods.EC_LEFTMARGIN | NativeMethods.EC_RIGHTMARGIN, 0); } } - void WmGetDlgCode(ref Message m) { + void WmGetDlgCode(ref Message m) + { base.WndProc(ref m); - if (AcceptsTab) { + if (AcceptsTab) + { Debug.WriteLineIf(Control.ControlKeyboardRouting.TraceVerbose, "TextBox wants tabs"); - m.Result = (IntPtr)(unchecked( (int) (long)m.Result) | NativeMethods.DLGC_WANTTAB); + m.Result = (IntPtr)(unchecked((int)(long)m.Result) | NativeMethods.DLGC_WANTTAB); } - else { + else + { Debug.WriteLineIf(Control.ControlKeyboardRouting.TraceVerbose, "TextBox doesn't want tabs"); - m.Result = (IntPtr)(unchecked( (int) (long)m.Result) & ~(NativeMethods.DLGC_WANTTAB | NativeMethods.DLGC_WANTALLKEYS)); + m.Result = (IntPtr)(unchecked((int)(long)m.Result) & ~(NativeMethods.DLGC_WANTTAB | NativeMethods.DLGC_WANTALLKEYS)); } } @@ -2010,9 +2327,11 @@ void WmGetDlgCode(ref Message m) { /// Yes strip context system /// No strip context N/A /// - private void WmTextBoxContextMenu(ref Message m) { + private void WmTextBoxContextMenu(ref Message m) + { - if (ContextMenu != null || ContextMenuStrip != null) { + if (ContextMenu != null || ContextMenuStrip != null) + { int x = NativeMethods.Util.SignedLOWORD(m.LParam); int y = NativeMethods.Util.SignedHIWORD(m.LParam); Point client; @@ -2020,27 +2339,33 @@ private void WmTextBoxContextMenu(ref Message m) { // lparam will be exactly -1 when the user invokes the context menu // with the keyboard. // - if (unchecked((int)(long)m.LParam) == -1) { + if (unchecked((int)(long)m.LParam) == -1) + { keyboardActivated = true; - client = new Point(Width/2, Height/2); + client = new Point(Width / 2, Height / 2); } - else { + else + { client = PointToClient(new Point(x, y)); } // // VisualStudio7 # 156, only show the context menu when clicked in the client area - if (ClientRectangle.Contains( client )) { - if (ContextMenu != null) { + if (ClientRectangle.Contains(client)) + { + if (ContextMenu != null) + { ContextMenu.Show(this, client); } - else if (ContextMenuStrip != null) { + else if (ContextMenuStrip != null) + { ContextMenuStrip.ShowInternal(this, client, keyboardActivated); } - else { - Debug.Fail("contextmenu and contextmenustrip are both null... hmm how did we get here?"); - DefWndProc( ref m ); + else + { + Debug.Fail("contextmenu and contextmenustrip are both null... hmm how did we get here?"); + DefWndProc(ref m); } } } @@ -2051,8 +2376,10 @@ private void WmTextBoxContextMenu(ref Message m) { /// to add extra functionality, but should not forget to call /// base.wndProc(m); to ensure the control continues to function properly. /// - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { case Interop.WindowMessages.WM_LBUTTONDBLCLK: this.doubleClickFired = true; base.WndProc(ref m); @@ -2067,12 +2394,14 @@ protected override void WndProc(ref Message m) { WmSetFont(ref m); break; case Interop.WindowMessages.WM_CONTEXTMENU: - if (ShortcutsEnabled) { + if (ShortcutsEnabled) + { //calling base will find ContextMenus in this order: // 1) ContextMenu 2) ContextMenuStrip 3) SystemMenu base.WndProc(ref m); } - else { + else + { // we'll handle this message so we can hide the // SystemMenu if Context and Strip menus are null WmTextBoxContextMenu(ref m); @@ -2083,5 +2412,5 @@ protected override void WndProc(ref Message m) { break; } } - } + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxRenderer.cs index 93e5c13869c..740d966cd53 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxRenderer.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Drawing; @@ -17,7 +18,8 @@ namespace System.Windows.Forms { /// This is a rendering class for the TextBox control. /// /// - public sealed class TextBoxRenderer { + public sealed class TextBoxRenderer + { //Make this per-thread, so that different threads can safely use these methods. [ThreadStatic] @@ -25,7 +27,8 @@ public sealed class TextBoxRenderer { private static readonly VisualStyleElement TextBoxElement = VisualStyleElement.TextBox.TextEdit.Normal; //cannot instantiate - private TextBoxRenderer() { + private TextBoxRenderer() + { } /// @@ -34,20 +37,26 @@ private TextBoxRenderer() { /// otherwise returns false. /// /// - public static bool IsSupported { - get { + public static bool IsSupported + { + get + { return VisualStyleRenderer.IsSupported; // no downlevel support } } - private static void DrawBackground(Graphics g, Rectangle bounds, TextBoxState state) { + private static void DrawBackground(Graphics g, Rectangle bounds, TextBoxState state) + { visualStyleRenderer.DrawBackground(g, bounds); - if (state != TextBoxState.Disabled) { + if (state != TextBoxState.Disabled) + { Color windowColor = visualStyleRenderer.GetColor(ColorProperty.FillColor); - if (windowColor != SystemColors.Window) { + if (windowColor != SystemColors.Window) + { Rectangle fillRect = visualStyleRenderer.GetBackgroundContentRectangle(g, bounds); //then we need to re-fill the background. - using(SolidBrush brush = new SolidBrush(SystemColors.Window)) { + using (SolidBrush brush = new SolidBrush(SystemColors.Window)) + { g.FillRectangle(brush, fillRect); } } @@ -62,7 +71,8 @@ private static void DrawBackground(Graphics g, Rectangle bounds, TextBoxState st [ SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally ] - public static void DrawTextBox(Graphics g, Rectangle bounds, TextBoxState state) { + public static void DrawTextBox(Graphics g, Rectangle bounds, TextBoxState state) + { InitializeRenderer((int)state); DrawBackground(g, bounds, state); } @@ -72,7 +82,8 @@ public static void DrawTextBox(Graphics g, Rectangle bounds, TextBoxState state) /// Renders a TextBox control. /// /// - public static void DrawTextBox(Graphics g, Rectangle bounds, string textBoxText, Font font, TextBoxState state) { + public static void DrawTextBox(Graphics g, Rectangle bounds, string textBoxText, Font font, TextBoxState state) + { DrawTextBox(g, bounds, textBoxText, font, TextFormatFlags.TextBoxControl, state); } @@ -81,7 +92,8 @@ public static void DrawTextBox(Graphics g, Rectangle bounds, string textBoxText, /// Renders a TextBox control. /// /// - public static void DrawTextBox(Graphics g, Rectangle bounds, string textBoxText, Font font, Rectangle textBounds, TextBoxState state) { + public static void DrawTextBox(Graphics g, Rectangle bounds, string textBoxText, Font font, Rectangle textBounds, TextBoxState state) + { DrawTextBox(g, bounds, textBoxText, font, textBounds, TextFormatFlags.TextBoxControl, state); } @@ -90,7 +102,8 @@ public static void DrawTextBox(Graphics g, Rectangle bounds, string textBoxText, /// Renders a TextBox control. /// /// - public static void DrawTextBox(Graphics g, Rectangle bounds, string textBoxText, Font font, TextFormatFlags flags, TextBoxState state) { + public static void DrawTextBox(Graphics g, Rectangle bounds, string textBoxText, Font font, TextFormatFlags flags, TextBoxState state) + { InitializeRenderer((int)state); Rectangle textBounds = visualStyleRenderer.GetBackgroundContentRectangle(g, bounds); textBounds.Inflate(-2, -2); @@ -105,7 +118,8 @@ public static void DrawTextBox(Graphics g, Rectangle bounds, string textBoxText, [ SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using Graphics instead of IDeviceContext intentionally ] - public static void DrawTextBox(Graphics g, Rectangle bounds, string textBoxText, Font font, Rectangle textBounds, TextFormatFlags flags, TextBoxState state) { + public static void DrawTextBox(Graphics g, Rectangle bounds, string textBoxText, Font font, Rectangle textBounds, TextFormatFlags flags, TextBoxState state) + { InitializeRenderer((int)state); DrawBackground(g, bounds, state); @@ -114,11 +128,14 @@ public static void DrawTextBox(Graphics g, Rectangle bounds, string textBoxText, } - private static void InitializeRenderer(int state) { - if (visualStyleRenderer == null) { + private static void InitializeRenderer(int state) + { + if (visualStyleRenderer == null) + { visualStyleRenderer = new VisualStyleRenderer(TextBoxElement.ClassName, TextBoxElement.Part, state); } - else { + else + { visualStyleRenderer.SetParameters(TextBoxElement.ClassName, TextBoxElement.Part, state); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ThreadExceptionDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ThreadExceptionDialog.cs index 05ee7898ec1..f2e41e778a7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ThreadExceptionDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ThreadExceptionDialog.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System; @@ -21,7 +22,8 @@ namespace System.Windows.Forms { [ ComVisible(true), ClassInterface(ClassInterfaceType.AutoDispatch)] - public class ThreadExceptionDialog : Form { + public class ThreadExceptionDialog : Form + { private const string DownBitmapName = "down"; private const string UpBitmapName = "up"; @@ -80,9 +82,11 @@ public class ThreadExceptionDialog : Form { /// /// Initializes a new instance of the class. /// - public ThreadExceptionDialog(Exception t) { + public ThreadExceptionDialog(Exception t) + { - if (DpiHelper.IsScalingRequirementMet) { + if (DpiHelper.IsScalingRequirementMet) + { scaledMaxWidth = LogicalToDeviceUnits(MAXWIDTH); scaledMaxHeight = LogicalToDeviceUnits(MAXHEIGHT); scaledPaddingWidth = LogicalToDeviceUnits(PADDINGWIDTH); @@ -110,48 +114,61 @@ public ThreadExceptionDialog(Exception t) { bool detailAnchor = false; WarningException w = t as WarningException; - if (w != null) { + if (w != null) + { messageFormat = SR.ExDlgWarningText; messageText = w.Message; - if (w.HelpUrl == null) { - buttons = new Button[] {continueButton}; + if (w.HelpUrl == null) + { + buttons = new Button[] { continueButton }; } - else { - buttons = new Button[] {continueButton, helpButton}; + else + { + buttons = new Button[] { continueButton, helpButton }; } } - else { + else + { messageText = t.Message; detailAnchor = true; - - if (Application.AllowQuit) { - if (t is System.Security.SecurityException) { + + if (Application.AllowQuit) + { + if (t is System.Security.SecurityException) + { messageFormat = SR.ExDlgSecurityErrorText; } - else { + else + { messageFormat = SR.ExDlgErrorText; } - buttons = new Button[] {detailsButton, continueButton, quitButton}; + buttons = new Button[] { detailsButton, continueButton, quitButton }; } - else { - if (t is System.Security.SecurityException) { + else + { + if (t is System.Security.SecurityException) + { messageFormat = SR.ExDlgSecurityContinueErrorText; } - else { + else + { messageFormat = SR.ExDlgContinueErrorText; } - buttons = new Button[] {detailsButton, continueButton}; + buttons = new Button[] { detailsButton, continueButton }; } } - if (messageText.Length == 0) { + if (messageText.Length == 0) + { messageText = t.GetType().Name; } - if (t is System.Security.SecurityException) { + if (t is System.Security.SecurityException) + { messageText = string.Format(messageFormat, t.GetType().Name, Trim(messageText)); } - else { + else + { messageText = string.Format(messageFormat, Trim(messageText)); } @@ -159,10 +176,12 @@ public ThreadExceptionDialog(Exception t) { string newline = "\r\n"; string separator = SR.ExDlgMsgSeperator; string sectionseparator = SR.ExDlgMsgSectionSeperator; - if (Application.CustomThreadExceptionHandlerAttached) { + if (Application.CustomThreadExceptionHandlerAttached) + { detailsTextBuilder.Append(SR.ExDlgMsgHeaderNonSwitchable); } - else { + else + { detailsTextBuilder.Append(SR.ExDlgMsgHeaderSwitchable); } detailsTextBuilder.Append(string.Format(CultureInfo.CurrentCulture, sectionseparator, SR.ExDlgMsgExceptionSection)); @@ -171,29 +190,36 @@ public ThreadExceptionDialog(Exception t) { detailsTextBuilder.Append(newline); detailsTextBuilder.Append(string.Format(CultureInfo.CurrentCulture, sectionseparator, SR.ExDlgMsgLoadedAssembliesSection)); - foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) { + foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) + { AssemblyName name = asm.GetName(); string fileVer = SR.NotAvailable; - try { - if (name.EscapedCodeBase != null && name.EscapedCodeBase.Length > 0) { + try + { + if (name.EscapedCodeBase != null && name.EscapedCodeBase.Length > 0) + { Uri codeBase = new Uri(name.EscapedCodeBase); - if (codeBase.Scheme == "file") { + if (codeBase.Scheme == "file") + { fileVer = FileVersionInfo.GetVersionInfo(NativeMethods.GetLocalPath(name.EscapedCodeBase)).FileVersion; } } } - catch(System.IO.FileNotFoundException){ + catch (System.IO.FileNotFoundException) + { } detailsTextBuilder.Append(string.Format(SR.ExDlgMsgLoadedAssembliesEntry, name.Name, name.Version, fileVer, name.EscapedCodeBase)); detailsTextBuilder.Append(separator); } - + detailsTextBuilder.Append(string.Format(CultureInfo.CurrentCulture, sectionseparator, SR.ExDlgMsgJITDebuggingSection)); - if (Application.CustomThreadExceptionHandlerAttached) { + if (Application.CustomThreadExceptionHandlerAttached) + { detailsTextBuilder.Append(SR.ExDlgMsgFooterNonSwitchable); } - else { + else + { detailsTextBuilder.Append(SR.ExDlgMsgFooterSwitchable); } @@ -206,11 +232,13 @@ public ThreadExceptionDialog(Exception t) { Size textSize = new Size(scaledMaxWidth - scaledPaddingWidth, int.MaxValue); - if (DpiHelper.IsScalingRequirementMet && Label.UseCompatibleTextRenderingDefault == false) { + if (DpiHelper.IsScalingRequirementMet && Label.UseCompatibleTextRenderingDefault == false) + { // we need to measure string using API that matches the rendering engine - TextRenderer.MeasureText for GDI textSize = Size.Ceiling(TextRenderer.MeasureText(messageText, Font, textSize, TextFormatFlags.WordBreak)); } - else { + else + { // if HighDpi improvements are not enabled, or rendering mode is GDI+, use Graphics.MeasureString textSize = Size.Ceiling(g.MeasureString(messageText, Font, textSize.Width)); } @@ -218,17 +246,21 @@ public ThreadExceptionDialog(Exception t) { textSize.Height += scaledExceptionMessageVerticalPadding; g.Dispose(); - if (textSize.Width < scaledMaxTextWidth) textSize.Width = scaledMaxTextWidth; - if (textSize.Height > scaledMaxHeight) textSize.Height = scaledMaxHeight; + if (textSize.Width < scaledMaxTextWidth) + textSize.Width = scaledMaxTextWidth; + if (textSize.Height > scaledMaxHeight) + textSize.Height = scaledMaxHeight; int width = textSize.Width + scaledPaddingWidth; int buttonTop = Math.Max(textSize.Height, scaledMaxTextHeight) + scaledPaddingHeight; Form activeForm = Form.ActiveForm; - if (activeForm == null || activeForm.Text.Length == 0) { + if (activeForm == null || activeForm.Text.Length == 0) + { Text = SR.ExDlgCaption; } - else { + else + { Text = string.Format(SR.ExDlgCaption2, activeForm.Text); } @@ -242,13 +274,15 @@ public ThreadExceptionDialog(Exception t) { ClientSize = new Size(width, buttonTop + scaledButtonTopPadding); TopMost = true; - pictureBox.Location = new Point(scaledPictureWidth/8, scaledPictureHeight/8); - pictureBox.Size = new Size(scaledPictureWidth*3/4, scaledPictureHeight*3/4); + pictureBox.Location = new Point(scaledPictureWidth / 8, scaledPictureHeight / 8); + pictureBox.Size = new Size(scaledPictureWidth * 3 / 4, scaledPictureHeight * 3 / 4); pictureBox.SizeMode = PictureBoxSizeMode.StretchImage; - if (t is System.Security.SecurityException) { + if (t is System.Security.SecurityException) + { pictureBox.Image = SystemIcons.Information.ToBitmap(); } - else { + else + { pictureBox.Image = SystemIcons.Error.ToBitmap(); } Controls.Add(pictureBox); @@ -276,8 +310,9 @@ public ThreadExceptionDialog(Exception t) { Button b = null; int startIndex = 0; - - if (detailAnchor) { + + if (detailAnchor) + { b = detailsButton; expandImage = DpiHelper.GetBitmapFromIcon(GetType(), DownBitmapName); @@ -295,10 +330,11 @@ public ThreadExceptionDialog(Exception t) { Controls.Add(b); startIndex = 1; } - + int buttonLeft = (width - scaledButtonDetailsLeftPadding - ((buttons.Length - startIndex) * scaledButtonAlignmentWidth - scaledButtonAlignmentPadding)); - - for (int i = startIndex; i < buttons.Length; i++) { + + for (int i = startIndex; i < buttons.Length; i++) + { b = buttons[i]; b.SetBounds(buttonLeft, buttonTop, scaledButtonWidth, scaledButtonHeight); Controls.Add(b); @@ -312,22 +348,26 @@ public ThreadExceptionDialog(Exception t) { details.WordWrap = false; details.TabStop = false; details.AcceptsReturn = false; - + details.SetBounds(scaledButtonDetailsLeftPadding, buttonTop + scaledButtonTopPadding, width - scaledDetailsWidthPadding, scaledDetailsHeight); details.Visible = detailsVisible; Controls.Add(details); - if (DpiHelper.IsScalingRequirementMet) { + if (DpiHelper.IsScalingRequirementMet) + { DpiChanged += ThreadExceptionDialog_DpiChanged; } } - private void ThreadExceptionDialog_DpiChanged(object sender, DpiChangedEventArgs e) { - if (expandImage != null) { + private void ThreadExceptionDialog_DpiChanged(object sender, DpiChangedEventArgs e) + { + if (expandImage != null) + { expandImage.Dispose(); } expandImage = DpiHelper.GetBitmapFromIcon(GetType(), DownBitmapName); - if (collapseImage != null) { + if (collapseImage != null) + { collapseImage.Dispose(); } collapseImage = DpiHelper.GetBitmapFromIcon(GetType(), UpBitmapName); @@ -355,24 +395,29 @@ public override bool AutoSize { add => base.AutoSizeChanged += value; remove => base.AutoSizeChanged -= value; - } + } /// /// Called when the details button is clicked. /// - private void DetailsClick(object sender, EventArgs eventargs) { + private void DetailsClick(object sender, EventArgs eventargs) + { int delta = details.Height + scaledHeightPadding; - if (detailsVisible) delta = -delta; + if (detailsVisible) + delta = -delta; Height = Height + delta; detailsVisible = !detailsVisible; details.Visible = detailsVisible; detailsButton.Image = detailsVisible ? collapseImage : expandImage; } - private static string Trim(string s) { - if (s == null) return s; + private static string Trim(string s) + { + if (s == null) + return s; int i = s.Length; - while (i > 0 && s[i - 1] == '.') i--; + while (i > 0 && s[i - 1] == '.') + i--; return s.Substring(0, i); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs index caedbef4f6f..149bed44b32 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.ComponentModel; @@ -25,7 +26,8 @@ namespace System.Windows.Forms { Designer("System.Windows.Forms.Design.ToolBarDesigner, " + AssemblyRef.SystemDesign), DefaultProperty(nameof(Buttons)) ] - public class ToolBar : Control { + public class ToolBar : Control + { private ToolBarButtonCollection buttonsCollection; @@ -59,7 +61,7 @@ public class ToolBar : Control { /// /// The array of buttons we're working with. /// - private ToolBarButton [] buttons; + private ToolBarButton[] buttons; /// /// The number of buttons we're working with @@ -88,11 +90,11 @@ public class ToolBar : Control { private float currentScaleDX = 1.0F; private float currentScaleDY = 1.0F; - private const int TOOLBARSTATE_wrappable = 0x00000001; - private const int TOOLBARSTATE_dropDownArrows = 0x00000002; - private const int TOOLBARSTATE_divider = 0x00000004; - private const int TOOLBARSTATE_showToolTips = 0x00000008; - private const int TOOLBARSTATE_autoSize = 0x00000010; + private const int TOOLBARSTATE_wrappable = 0x00000001; + private const int TOOLBARSTATE_dropDownArrows = 0x00000002; + private const int TOOLBARSTATE_divider = 0x00000004; + private const int TOOLBARSTATE_showToolTips = 0x00000008; + private const int TOOLBARSTATE_autoSize = 0x00000010; // PERF: take all the bools and put them into a state variable private System.Collections.Specialized.BitVector32 toolBarState; // see TOOLBARSTATE_ consts above @@ -107,7 +109,8 @@ public class ToolBar : Control { /// Initializes a new instance of the class. /// public ToolBar() - : base() { + : base() + { // Set this BEFORE calling any other methods so that these defaults will be propagated toolBarState = new System.Collections.Specialized.BitVector32(TOOLBARSTATE_autoSize | @@ -134,18 +137,23 @@ public ToolBar() Localizable(true), SRDescription(nameof(SR.ToolBarAppearanceDescr)) ] - public ToolBarAppearance Appearance { - get { + public ToolBarAppearance Appearance + { + get + { return appearance; } - set { + set + { //valid values are 0x0 to 0x1 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolBarAppearance.Normal, (int)ToolBarAppearance.Flat)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolBarAppearance.Normal, (int)ToolBarAppearance.Flat)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolBarAppearance)); } - if (value != appearance) { + if (value != appearance) + { appearance = value; RecreateHandle(); } @@ -162,27 +170,33 @@ public ToolBarAppearance Appearance { DefaultValue(true), Localizable(true), SRDescription(nameof(SR.ToolBarAutoSizeDescr)), - Browsable(true), + Browsable(true), EditorBrowsable(EditorBrowsableState.Always), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible) ] - public override bool AutoSize { - get { + public override bool AutoSize + { + get + { return toolBarState[TOOLBARSTATE_autoSize]; } - set { + set + { // Note that we intentionally do not call base. Toolbars size themselves by // overriding SetBoundsCore (old RTM code). We let CommonProperties.GetAutoSize // continue to return false to keep our LayoutEngines from messing with TextBoxes. // This is done for backwards compatibility since the new AutoSize behavior differs. - if (AutoSize != value) { + if (AutoSize != value) + { toolBarState[TOOLBARSTATE_autoSize] = value; - if (Dock == DockStyle.Left || Dock == DockStyle.Right) { + if (Dock == DockStyle.Left || Dock == DockStyle.Right) + { SetStyle(ControlStyles.FixedWidth, AutoSize); SetStyle(ControlStyles.FixedHeight, false); } - else { + else + { SetStyle(ControlStyles.FixedHeight, AutoSize); SetStyle(ControlStyles.FixedWidth, false); } @@ -204,49 +218,61 @@ public override bool AutoSize { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Color BackColor { - get { + public override Color BackColor + { + get + { return base.BackColor; } - set { + set + { base.BackColor = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackColorChanged { + new public event EventHandler BackColorChanged + { add => base.BackColorChanged += value; remove => base.BackColorChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged { + new public event EventHandler BackgroundImageChanged + { add => base.BackgroundImageChanged += value; remove => base.BackgroundImageChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { + new public event EventHandler BackgroundImageLayoutChanged + { add => base.BackgroundImageLayoutChanged += value; remove => base.BackgroundImageLayoutChanged -= value; } @@ -261,19 +287,24 @@ public override ImageLayout BackgroundImageLayout { DispId(NativeMethods.ActiveX.DISPID_BORDERSTYLE), SRDescription(nameof(SR.ToolBarBorderStyleDescr)) ] - public BorderStyle BorderStyle { - get { + public BorderStyle BorderStyle + { + get + { return borderStyle; } - set { + set + { //valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(BorderStyle)); } - if (borderStyle != value) { + if (borderStyle != value) + { borderStyle = value; //UpdateStyles(); @@ -293,8 +324,10 @@ public BorderStyle BorderStyle { SRDescription(nameof(SR.ToolBarButtonsDescr)), MergableProperty(false) ] - public ToolBarButtonCollection Buttons { - get { + public ToolBarButtonCollection Buttons + { + get + { return buttonsCollection; } } @@ -309,36 +342,46 @@ public ToolBarButtonCollection Buttons { Localizable(true), SRDescription(nameof(SR.ToolBarButtonSizeDescr)) ] - public Size ButtonSize { - get { - if (buttonSize.IsEmpty) { + public Size ButtonSize + { + get + { + if (buttonSize.IsEmpty) + { // Obtain the current buttonsize of the first button from the winctl control // - if (IsHandleCreated && buttons != null && buttonCount > 0) { - int result = unchecked( (int) (long)SendMessage(NativeMethods.TB_GETBUTTONSIZE, 0, 0)); - if (result > 0) { + if (IsHandleCreated && buttons != null && buttonCount > 0) + { + int result = unchecked((int)(long)SendMessage(NativeMethods.TB_GETBUTTONSIZE, 0, 0)); + if (result > 0) + { return new Size(NativeMethods.Util.LOWORD(result), NativeMethods.Util.HIWORD(result)); } } - if (TextAlign == ToolBarTextAlign.Underneath) { + if (TextAlign == ToolBarTextAlign.Underneath) + { return new Size(39, 36); // Default button size } - else { + else + { return new Size(23, 22); // Default button size } } - else { + else + { return buttonSize; } } - set { + set + { if (value.Width < 0 || value.Height < 0) throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(ButtonSize), value)); - if (buttonSize != value) { + if (buttonSize != value) + { buttonSize = value; maxWidth = -1; // Force recompute of maxWidth RecreateHandle(); @@ -353,8 +396,10 @@ public Size ButtonSize { /// however, forget to get base.CreateParams first to get the struct /// filled up with the basic info. /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ClassName = NativeMethods.WC_TOOLBAR; @@ -364,13 +409,17 @@ protected override CreateParams CreateParams { | NativeMethods.CCS_NORESIZE; // | NativeMethods.WS_CHILD was commented out since setTopLevel should be able to work. - if (!Divider) cp.Style |= NativeMethods.CCS_NODIVIDER ; - if (Wrappable) cp.Style |= NativeMethods.TBSTYLE_WRAPPABLE; - if (ShowToolTips && !DesignMode) cp.Style |= NativeMethods.TBSTYLE_TOOLTIPS; + if (!Divider) + cp.Style |= NativeMethods.CCS_NODIVIDER; + if (Wrappable) + cp.Style |= NativeMethods.TBSTYLE_WRAPPABLE; + if (ShowToolTips && !DesignMode) + cp.Style |= NativeMethods.TBSTYLE_TOOLTIPS; cp.ExStyle &= (~NativeMethods.WS_EX_CLIENTEDGE); cp.Style &= (~NativeMethods.WS_BORDER); - switch (borderStyle) { + switch (borderStyle) + { case BorderStyle.Fixed3D: cp.ExStyle |= NativeMethods.WS_EX_CLIENTEDGE; break; @@ -379,7 +428,8 @@ protected override CreateParams CreateParams { break; } - switch (appearance) { + switch (appearance) + { case ToolBarAppearance.Normal: break; case ToolBarAppearance.Flat: @@ -387,7 +437,8 @@ protected override CreateParams CreateParams { break; } - switch (textAlign) { + switch (textAlign) + { case ToolBarTextAlign.Underneath: break; case ToolBarTextAlign.Right: @@ -399,8 +450,10 @@ protected override CreateParams CreateParams { } } - protected override ImeMode DefaultImeMode { - get { + protected override ImeMode DefaultImeMode + { + get + { return ImeMode.Disable; } } @@ -409,8 +462,10 @@ protected override ImeMode DefaultImeMode { /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(100, 22); } } @@ -424,13 +479,17 @@ protected override Size DefaultSize { DefaultValue(true), SRDescription(nameof(SR.ToolBarDividerDescr)) ] - public bool Divider { - get { + public bool Divider + { + get + { return toolBarState[TOOLBARSTATE_divider]; } - set { - if (Divider != value) { + set + { + if (Divider != value) + { toolBarState[TOOLBARSTATE_divider] = value; RecreateHandle(); @@ -448,21 +507,27 @@ public bool Divider { Localizable(true), DefaultValue(DockStyle.Top) ] - public override DockStyle Dock { - get { return base.Dock;} + public override DockStyle Dock + { + get { return base.Dock; } - set { + set + { //valid values are 0x0 to 0x5 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)DockStyle.None, (int)DockStyle.Fill)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)DockStyle.None, (int)DockStyle.Fill)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DockStyle)); } - if (Dock != value) { - if (value == DockStyle.Left || value == DockStyle.Right) { + if (Dock != value) + { + if (value == DockStyle.Left || value == DockStyle.Right) + { SetStyle(ControlStyles.FixedWidth, AutoSize); SetStyle(ControlStyles.FixedHeight, false); } - else { + else + { SetStyle(ControlStyles.FixedHeight, AutoSize); SetStyle(ControlStyles.FixedWidth, false); } @@ -477,11 +542,14 @@ public override DockStyle Dock { /// on controls that are based on Win32 Native Controls. /// [EditorBrowsable(EditorBrowsableState.Never)] - protected override bool DoubleBuffered { - get { + protected override bool DoubleBuffered + { + get + { return base.DoubleBuffered; } - set { + set + { base.DoubleBuffered = value; } } @@ -496,14 +564,18 @@ protected override bool DoubleBuffered { Localizable(true), SRDescription(nameof(SR.ToolBarDropDownArrowsDescr)) ] - public bool DropDownArrows { - get { + public bool DropDownArrows + { + get + { return toolBarState[TOOLBARSTATE_dropDownArrows]; } - set { + set + { - if (DropDownArrows != value) { + if (DropDownArrows != value) + { toolBarState[TOOLBARSTATE_dropDownArrows] = value; RecreateHandle(); } @@ -513,17 +585,21 @@ public bool DropDownArrows { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Color ForeColor { - get { + public override Color ForeColor + { + get + { return base.ForeColor; } - set { + set + { base.ForeColor = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler ForeColorChanged { + new public event EventHandler ForeColorChanged + { add => base.ForeColorChanged += value; remove => base.ForeColorChanged -= value; } @@ -537,23 +613,29 @@ public override Color ForeColor { DefaultValue(null), SRDescription(nameof(SR.ToolBarImageListDescr)) ] - public ImageList ImageList { - get { + public ImageList ImageList + { + get + { return this.imageList; } - set { - if (value != imageList) { + set + { + if (value != imageList) + { EventHandler recreateHandler = new EventHandler(ImageListRecreateHandle); EventHandler disposedHandler = new EventHandler(DetachImageList); - if (imageList != null) { + if (imageList != null) + { imageList.Disposed -= disposedHandler; imageList.RecreateHandle -= recreateHandler; } imageList = value; - if (value != null) { + if (value != null) + { value.Disposed += disposedHandler; value.RecreateHandle += recreateHandler; } @@ -574,29 +656,37 @@ public ImageList ImageList { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ToolBarImageSizeDescr)) ] - public Size ImageSize { - get { - if (this.imageList != null) { + public Size ImageSize + { + get + { + if (this.imageList != null) + { return this.imageList.ImageSize; } - else { + else + { return new Size(0, 0); } } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public ImeMode ImeMode { - get { + new public ImeMode ImeMode + { + get + { return base.ImeMode; } - set { + set + { base.ImeMode = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler ImeModeChanged { + public new event EventHandler ImeModeChanged + { add => base.ImeModeChanged += value; remove => base.ImeModeChanged -= value; } @@ -605,25 +695,32 @@ public Size ImageSize { /// The preferred height for this ToolBar control. This is /// used by the AutoSizing code. /// - internal int PreferredHeight { - get { + internal int PreferredHeight + { + get + { int height = 0; - if (buttons == null || buttonCount == 0 || !IsHandleCreated) { + if (buttons == null || buttonCount == 0 || !IsHandleCreated) + { height = ButtonSize.Height; } - else { + else + { // get the first visible button and get it's height // NativeMethods.RECT rect = new NativeMethods.RECT(); int firstVisible; - for (firstVisible = 0; firstVisible < buttons.Length; firstVisible++) { - if (buttons[firstVisible] != null && buttons[firstVisible].Visible) { + for (firstVisible = 0; firstVisible < buttons.Length; firstVisible++) + { + if (buttons[firstVisible] != null && buttons[firstVisible].Visible) + { break; } } - if (firstVisible == buttons.Length) { + if (firstVisible == buttons.Length) + { firstVisible = 0; } @@ -637,13 +734,15 @@ internal int PreferredHeight { // if the ToolBar is wrappable, and there is more than one row, make // sure the height is correctly adjusted // - if (Wrappable && IsHandleCreated) { - height = height * unchecked( (int) (long)SendMessage(NativeMethods.TB_GETROWS, 0, 0)); + if (Wrappable && IsHandleCreated) + { + height = height * unchecked((int)(long)SendMessage(NativeMethods.TB_GETROWS, 0, 0)); } height = (height > 0) ? height : 1; - switch(borderStyle) { + switch (borderStyle) + { case BorderStyle.FixedSingle: height += SystemInformation.BorderSize.Height; break; @@ -652,7 +751,8 @@ internal int PreferredHeight { break; } - if (Divider) height += 2; + if (Divider) + height += 2; height += 4; @@ -668,23 +768,28 @@ internal int PreferredHeight { /// if the control is docked left or right [ie, it really /// just returns a max width] /// - internal int PreferredWidth { - get { + internal int PreferredWidth + { + get + { int width; // fortunately, we compute this value sometimes, so we can just // use it if we have it. // - if (maxWidth == -1) { + if (maxWidth == -1) + { // don't have it, have to recompute // if (!IsHandleCreated || buttons == null) maxWidth = ButtonSize.Width; - else { + else + { NativeMethods.RECT rect = new NativeMethods.RECT(); - for (int x = 0; x < buttonCount; x++) { + for (int x = 0; x < buttonCount; x++) + { SendMessage(NativeMethods.TB_GETRECT, 0, ref rect); if ((rect.right - rect.left) > maxWidth) maxWidth = rect.right - rect.left; @@ -694,7 +799,8 @@ internal int PreferredWidth { width = maxWidth; - if (borderStyle != BorderStyle.None) { + if (borderStyle != BorderStyle.None) + { width += SystemInformation.BorderSize.Height * 4 + 3; } @@ -705,17 +811,21 @@ internal int PreferredWidth { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override RightToLeft RightToLeft { - get { + public override RightToLeft RightToLeft + { + get + { return base.RightToLeft; } - set { + set + { base.RightToLeft = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler RightToLeftChanged { + public new event EventHandler RightToLeftChanged + { add => base.RightToLeftChanged += value; remove => base.RightToLeftChanged -= value; } @@ -725,7 +835,8 @@ public override RightToLeft RightToLeft { /// unmanaged control how to scale its buttons. /// [EditorBrowsable(EditorBrowsableState.Never)] - protected override void ScaleCore(float dx, float dy) { + protected override void ScaleCore(float dx, float dy) + { currentScaleDX = dx; currentScaleDY = dy; base.ScaleCore(dx, dy); @@ -736,7 +847,8 @@ protected override void ScaleCore(float dx, float dy) { /// We need to track the current scale factor so that we can tell the /// unmanaged control how to scale its buttons. /// - protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { + protected override void ScaleControl(SizeF factor, BoundsSpecified specified) + { currentScaleDX = factor.Width; currentScaleDY = factor.Height; base.ScaleControl(factor, specified); @@ -753,12 +865,16 @@ protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { Localizable(true), SRDescription(nameof(SR.ToolBarShowToolTipsDescr)) ] - public bool ShowToolTips { - get { + public bool ShowToolTips + { + get + { return toolBarState[TOOLBARSTATE_showToolTips]; } - set { - if (ShowToolTips != value) { + set + { + if (ShowToolTips != value) + { toolBarState[TOOLBARSTATE_showToolTips] = value; RecreateHandle(); @@ -769,11 +885,14 @@ public bool ShowToolTips { /// /// [DefaultValue(false)] - new public bool TabStop { - get { + new public bool TabStop + { + get + { return base.TabStop; } - set { + set + { base.TabStop = value; } } @@ -785,17 +904,21 @@ public bool ShowToolTips { Bindable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TextChanged { + new public event EventHandler TextChanged + { add => base.TextChanged += value; remove => base.TextChanged -= value; } @@ -811,17 +934,22 @@ public override string Text { Localizable(true), SRDescription(nameof(SR.ToolBarTextAlignDescr)) ] - public ToolBarTextAlign TextAlign { - get { + public ToolBarTextAlign TextAlign + { + get + { return textAlign; } - set { + set + { //valid values are 0x0 to 0x1 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolBarTextAlign.Underneath, (int)ToolBarTextAlign.Right)) { + if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolBarTextAlign.Underneath, (int)ToolBarTextAlign.Right)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolBarTextAlign)); } - if (textAlign == value) return; + if (textAlign == value) + return; textAlign = value; RecreateHandle(); } @@ -840,12 +968,16 @@ public ToolBarTextAlign TextAlign { Localizable(true), SRDescription(nameof(SR.ToolBarWrappableDescr)) ] - public bool Wrappable { - get { + public bool Wrappable + { + get + { return toolBarState[TOOLBARSTATE_wrappable]; } - set { - if (Wrappable != value) { + set + { + if (Wrappable != value) + { toolBarState[TOOLBARSTATE_wrappable] = value; RecreateHandle(); } @@ -856,7 +988,8 @@ public bool Wrappable { /// Occurs when a on the is clicked. /// [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ToolBarButtonClickDescr))] - public event ToolBarButtonClickEventHandler ButtonClick { + public event ToolBarButtonClickEventHandler ButtonClick + { add => onButtonClick += value; remove => onButtonClick -= value; } @@ -865,7 +998,8 @@ public event ToolBarButtonClickEventHandler ButtonClick { /// Occurs when a drop-down style or its down arrow is clicked. /// [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ToolBarButtonDropDownDescr))] - public event ToolBarButtonClickEventHandler ButtonDropDown { + public event ToolBarButtonClickEventHandler ButtonDropDown + { add => onButtonDropDown += value; remove => onButtonDropDown -= value; } @@ -875,7 +1009,8 @@ public event ToolBarButtonClickEventHandler ButtonDropDown { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event PaintEventHandler Paint { + public new event PaintEventHandler Paint + { add => base.Paint += value; remove => base.Paint -= value; } @@ -886,17 +1021,22 @@ public event ToolBarButtonClickEventHandler ButtonDropDown { /// // we pass in a value for dock rather than calling Dock ourselves // because we can't change Dock until the size has been properly adjusted. - private void AdjustSize(DockStyle dock) { + private void AdjustSize(DockStyle dock) + { int saveSize = requestedSize; - try { - if (dock == DockStyle.Left || dock == DockStyle.Right) { + try + { + if (dock == DockStyle.Left || dock == DockStyle.Right) + { Width = AutoSize ? PreferredWidth : saveSize; } - else { + else + { Height = AutoSize ? PreferredHeight : saveSize; } } - finally { + finally + { requestedSize = saveSize; } } @@ -906,21 +1046,26 @@ private void AdjustSize(DockStyle dock) { /// having each operation wait for the paint to complete. This must be /// matched up with a call to endUpdate(). /// - internal void BeginUpdate() { + internal void BeginUpdate() + { BeginUpdateInternal(); } /// /// - protected override void CreateHandle() { - if (!RecreatingHandle) { + protected override void CreateHandle() + { + if (!RecreatingHandle) + { IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); - try { + try + { NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); icc.dwICC = NativeMethods.ICC_BAR_CLASSES; SafeNativeMethods.InitCommonControlsEx(icc); } - finally { + finally + { UnsafeNativeMethods.ThemingScope.Deactivate(userCookie); } } @@ -931,39 +1076,48 @@ protected override void CreateHandle() { /// Resets the imageList to null. We wire this method up to the imageList's /// Dispose event, so that we don't hang onto an imageList that's gone away. /// - private void DetachImageList(object sender, EventArgs e) { + private void DetachImageList(object sender, EventArgs e) + { ImageList = null; } /// /// - protected override void Dispose(bool disposing) { - if (disposing) { + protected override void Dispose(bool disposing) + { + if (disposing) + { // - lock(this) { + lock (this) + { // We need to mark the Disposing state here so buttonsCollection won't attempt to update // the buttons. bool currentDisposing = GetState(STATE_DISPOSING); - - try { + + try + { SetState(STATE_DISPOSING, true); - if (imageList != null) { + if (imageList != null) + { imageList.Disposed -= new EventHandler(DetachImageList); imageList = null; } - if (buttonsCollection != null) { + if (buttonsCollection != null) + { ToolBarButton[] buttonCopy = new ToolBarButton[buttonsCollection.Count]; ((ICollection)buttonsCollection).CopyTo(buttonCopy, 0); buttonsCollection.Clear(); - foreach (ToolBarButton b in buttonCopy) { + foreach (ToolBarButton b in buttonCopy) + { b.Dispose(); } } } - finally { + finally + { SetState(STATE_DISPOSING, currentDisposing); } } @@ -977,7 +1131,8 @@ protected override void Dispose(bool disposing) { /// having each operation wait for the paint to complete. This must be /// matched up with a call to beginUpdate(). /// - internal void EndUpdate() { + internal void EndUpdate() + { EndUpdateInternal(); } @@ -987,21 +1142,25 @@ internal void EndUpdate() { /// a little better, and lets us actually show things like DropDown Arrows /// for ToolBars /// - private void ForceButtonWidths() { + private void ForceButtonWidths() + { - if (buttons != null && buttonSize.IsEmpty && IsHandleCreated) { + if (buttons != null && buttonSize.IsEmpty && IsHandleCreated) + { // force ourselves to re-compute this each time // maxWidth = -1; - for (int x = 0; x < buttonCount; x++) { + for (int x = 0; x < buttonCount; x++) + { NativeMethods.TBBUTTONINFO tbbi = new NativeMethods.TBBUTTONINFO(); tbbi.cbSize = Marshal.SizeOf(); tbbi.cx = buttons[x].Width; - if (tbbi.cx > maxWidth) { + if (tbbi.cx > maxWidth) + { maxWidth = tbbi.cx; } @@ -1011,21 +1170,25 @@ private void ForceButtonWidths() { } } - private void ImageListRecreateHandle(object sender, EventArgs e) { + private void ImageListRecreateHandle(object sender, EventArgs e) + { if (IsHandleCreated) RecreateHandle(); } /// /// - private void Insert(int index, ToolBarButton button) { + private void Insert(int index, ToolBarButton button) + { button.parent = this; - if (buttons == null) { + if (buttons == null) + { buttons = new ToolBarButton[4]; } - else if (buttons.Length == buttonCount) { + else if (buttons.Length == buttonCount) + { ToolBarButton[] newButtons = new ToolBarButton[buttonCount + 4]; System.Array.Copy(buttons, 0, newButtons, 0, buttonCount); buttons = newButtons; @@ -1041,7 +1204,8 @@ private void Insert(int index, ToolBarButton button) { /// /// Inserts a button at a given location on the toolbar control. /// - private void InsertButton(int index, ToolBarButton value) { + private void InsertButton(int index, ToolBarButton value) + { if (value == null) throw new ArgumentNullException(nameof(value)); @@ -1052,7 +1216,8 @@ private void InsertButton(int index, ToolBarButton value) { // real windows ToolBar control // Insert(index, value); - if (IsHandleCreated) { + if (IsHandleCreated) + { NativeMethods.TBBUTTON tbbutton = value.GetTBBUTTON(index); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TB_INSERTBUTTON, index, ref tbbutton); } @@ -1062,7 +1227,8 @@ private void InsertButton(int index, ToolBarButton value) { /// /// Adds a button to the ToolBar /// - private int InternalAddButton(ToolBarButton button) { + private int InternalAddButton(ToolBarButton button) + { if (button == null) throw new ArgumentNullException(nameof(button)); int index = buttonCount; @@ -1074,7 +1240,8 @@ private int InternalAddButton(ToolBarButton button) { /// Changes the data for a button in the ToolBar, and then does the appropriate /// work to update the ToolBar control. /// - internal void InternalSetButton(int index, ToolBarButton value, bool recreate, bool updateText) { + internal void InternalSetButton(int index, ToolBarButton value, bool recreate, bool updateText) + { // tragically, there doesn't appear to be a way to remove the // string for the button if it has one, so we just have to leave @@ -1085,18 +1252,22 @@ internal void InternalSetButton(int index, ToolBarButton value, bool recreate, b buttons[index] = value; buttons[index].parent = this; - if (IsHandleCreated) { + if (IsHandleCreated) + { NativeMethods.TBBUTTONINFO tbbi = value.GetTBBUTTONINFO(updateText, index); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TB_SETBUTTONINFO, index, ref tbbi); - if (tbbi.pszText != IntPtr.Zero) { + if (tbbi.pszText != IntPtr.Zero) + { Marshal.FreeHGlobal(tbbi.pszText); } - if (recreate) { + if (recreate) + { UpdateButtons(); } - else { + else + { // after doing anything with the comctl ToolBar control, this // appears to be a good idea. // @@ -1112,16 +1283,20 @@ internal void InternalSetButton(int index, ToolBarButton value, bool recreate, b /// Raises the /// event. /// - protected virtual void OnButtonClick(ToolBarButtonClickEventArgs e) { - if (onButtonClick != null) onButtonClick(this, e); + protected virtual void OnButtonClick(ToolBarButtonClickEventArgs e) + { + if (onButtonClick != null) + onButtonClick(this, e); } /// /// Raises the /// event. /// - protected virtual void OnButtonDropDown(ToolBarButtonClickEventArgs e) { - if (onButtonDropDown != null) onButtonDropDown(this, e); + protected virtual void OnButtonDropDown(ToolBarButtonClickEventArgs e) + { + if (onButtonDropDown != null) + onButtonDropDown(this, e); } /// @@ -1131,7 +1306,8 @@ protected virtual void OnButtonDropDown(ToolBarButtonClickEventArgs e) { /// Don't forget to call base.OnHandleCreated. /// /// - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { base.OnHandleCreated(e); // we have to set the button struct size, because they don't. @@ -1154,12 +1330,14 @@ protected override void OnHandleCreated(EventArgs e) { // (comctl ToolBar is flaky) // BeginUpdate(); - try { + try + { Size size = Size; Size = new Size(size.Width + 1, size.Height); Size = size; } - finally { + finally + { EndUpdate(); } } @@ -1169,9 +1347,11 @@ protected override void OnHandleCreated(EventArgs e) { /// The control is being resized. Make sure the width/height are correct. /// /// - protected override void OnResize(EventArgs e) { + protected override void OnResize(EventArgs e) + { base.OnResize(e); - if (Wrappable) AdjustSize(Dock); + if (Wrappable) + AdjustSize(Dock); } /// @@ -1180,13 +1360,17 @@ protected override void OnResize(EventArgs e) { /// whenever the font changes. /// /// - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { base.OnFontChanged(e); - if (IsHandleCreated) { - if (!buttonSize.IsEmpty) { + if (IsHandleCreated) + { + if (!buttonSize.IsEmpty) + { SendToolbarButtonSizeMessage(); } - else { + else + { AdjustSize(Dock); ForceButtonWidths(); } @@ -1196,19 +1380,25 @@ protected override void OnFontChanged(EventArgs e) { /// /// Sets all the button data into the ToolBar control /// - private void RealizeButtons() { - if (buttons != null) { + private void RealizeButtons() + { + if (buttons != null) + { IntPtr ptbbuttons = IntPtr.Zero; - try { + try + { BeginUpdate(); // go and add in all the strings for all of our buttons // - for (int x = 0; x < buttonCount; x++) { - if (buttons[x].Text.Length > 0) { + for (int x = 0; x < buttonCount; x++) + { + if (buttons[x].Text.Length > 0) + { string addString = buttons[x].Text + '\0'.ToString(); buttons[x].stringIndex = SendMessage(NativeMethods.TB_ADDSTRING, 0, addString); } - else { + else + { buttons[x].stringIndex = (IntPtr)(-1); } } @@ -1219,7 +1409,8 @@ private void RealizeButtons() { int count = buttonCount; ptbbuttons = Marshal.AllocHGlobal(checked(cb * count)); - for (int x = 0; x < count; x++) { + for (int x = 0; x < count; x++) + { NativeMethods.TBBUTTON tbbutton = buttons[x].GetTBBUTTON(x); Marshal.StructureToPtr(tbbutton, (IntPtr)(checked((long)ptbbuttons + (cb * x))), true); @@ -1238,15 +1429,18 @@ private void RealizeButtons() { // buttons. Otherwise, we need to manually set the width of all // the buttons so they look reasonable // - if (!buttonSize.IsEmpty) { - SendToolbarButtonSizeMessage(); + if (!buttonSize.IsEmpty) + { + SendToolbarButtonSizeMessage(); } - else { + else + { ForceButtonWidths(); } AdjustSize(Dock); } - finally { + finally + { Marshal.FreeHGlobal(ptbbuttons); EndUpdate(); } @@ -1255,7 +1449,8 @@ private void RealizeButtons() { /// /// - private void RemoveAt(int index) { + private void RemoveAt(int index) + { buttons[index].parent = null; buttons[index].stringIndex = (IntPtr)(-1); buttonCount--; @@ -1270,43 +1465,54 @@ private void RemoveAt(int index) { /// Resets the toolbar buttons to the minimum /// size. /// - private void ResetButtonSize() { + private void ResetButtonSize() + { buttonSize = Size.Empty; RecreateHandle(); } /// Sends a TB_SETBUTTONSIZE message to the unmanaged control, with size arguments properly scaled. - private void SendToolbarButtonSizeMessage() { - SendMessage(NativeMethods.TB_SETBUTTONSIZE, 0, NativeMethods.Util.MAKELPARAM((int)(buttonSize.Width*currentScaleDX), (int)(buttonSize.Height*currentScaleDY))); + private void SendToolbarButtonSizeMessage() + { + SendMessage(NativeMethods.TB_SETBUTTONSIZE, 0, NativeMethods.Util.MAKELPARAM((int)(buttonSize.Width * currentScaleDX), (int)(buttonSize.Height * currentScaleDY))); } /// /// Overrides Control.setBoundsCore to enforce AutoSize. /// - protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { + protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) + { int originalHeight = height; int originalWidth = width; base.SetBoundsCore(x, y, width, height, specified); Rectangle bounds = Bounds; - if (Dock == DockStyle.Left || Dock == DockStyle.Right) { - if ((specified & BoundsSpecified.Width) != BoundsSpecified.None) requestedSize = width; - if (AutoSize) width = PreferredWidth; - - if (width != originalWidth && Dock == DockStyle.Right) { - int deltaWidth = originalWidth - width; + if (Dock == DockStyle.Left || Dock == DockStyle.Right) + { + if ((specified & BoundsSpecified.Width) != BoundsSpecified.None) + requestedSize = width; + if (AutoSize) + width = PreferredWidth; + + if (width != originalWidth && Dock == DockStyle.Right) + { + int deltaWidth = originalWidth - width; x += deltaWidth; } } - else { - if ((specified & BoundsSpecified.Height) != BoundsSpecified.None) requestedSize = height; - if (AutoSize) height = PreferredHeight; + else + { + if ((specified & BoundsSpecified.Height) != BoundsSpecified.None) + requestedSize = height; + if (AutoSize) + height = PreferredHeight; - if (height != originalHeight && Dock == DockStyle.Bottom) { - int deltaHeight = originalHeight - height; + if (height != originalHeight && Dock == DockStyle.Bottom) + { + int deltaHeight = originalHeight - height; y += deltaHeight; } @@ -1318,14 +1524,16 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound /// /// Determines if the property needs to be persisted. /// - private bool ShouldSerializeButtonSize() { + private bool ShouldSerializeButtonSize() + { return !buttonSize.IsEmpty; } /// /// Called by ToolTip to poke in that Tooltip into this ComCtl so that the Native ChildToolTip is not exposed. /// - internal void SetToolTip(ToolTip toolTip) { + internal void SetToolTip(ToolTip toolTip) + { UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.TB_SETTOOLTIPS, new HandleRef(toolTip, toolTip.Handle), 0); } @@ -1333,7 +1541,8 @@ internal void SetToolTip(ToolTip toolTip) { /// /// Returns a string representation for this control. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); s += ", Buttons.Count: " + buttonCount.ToString(CultureInfo.CurrentCulture); @@ -1347,8 +1556,10 @@ public override string ToString() { /// control is pretty flakey, and the only real choice here is to recreate /// the handle and re-realize all the buttons. /// - internal void UpdateButtons() { - if (IsHandleCreated) { + internal void UpdateButtons() + { + if (IsHandleCreated) + { RecreateHandle(); } } @@ -1357,7 +1568,8 @@ internal void UpdateButtons() { /// The button clicked was a dropdown button. If it has a menu specified, /// show it now. Otherwise, fire an onButtonDropDown event. /// - private void WmNotifyDropDown(ref Message m) { + private void WmNotifyDropDown(ref Message m) + { NativeMethods.NMTOOLBAR nmTB = (NativeMethods.NMTOOLBAR)m.GetLParam(typeof(NativeMethods.NMTOOLBAR)); ToolBarButton tbb = (ToolBarButton)buttons[nmTB.iItem]; @@ -1367,18 +1579,22 @@ private void WmNotifyDropDown(ref Message m) { OnButtonDropDown(new ToolBarButtonClickEventArgs(tbb)); Menu menu = tbb.DropDownMenu; - if (menu != null) { + if (menu != null) + { NativeMethods.RECT rc = new NativeMethods.RECT(); NativeMethods.TPMPARAMS tpm = new NativeMethods.TPMPARAMS(); SendMessage(NativeMethods.TB_GETRECT, nmTB.iItem, ref rc); - if ((menu.GetType()).IsAssignableFrom(typeof(ContextMenu))) { + if ((menu.GetType()).IsAssignableFrom(typeof(ContextMenu))) + { ((ContextMenu)menu).Show(this, new Point(rc.left, rc.bottom)); } - else { + else + { Menu main = menu.GetMainMenu(); - if (main != null) { + if (main != null) + { main.ProcessInitMenuPopup(menu.Handle); } @@ -1400,10 +1616,11 @@ private void WmNotifyDropDown(ref Message m) { } } - private void WmNotifyNeedText(ref Message m) { - NativeMethods.TOOLTIPTEXT ttt = (NativeMethods.TOOLTIPTEXT) m.GetLParam(typeof(NativeMethods.TOOLTIPTEXT)); + private void WmNotifyNeedText(ref Message m) + { + NativeMethods.TOOLTIPTEXT ttt = (NativeMethods.TOOLTIPTEXT)m.GetLParam(typeof(NativeMethods.TOOLTIPTEXT)); int commandID = (int)ttt.hdr.idFrom; - ToolBarButton tbb = (ToolBarButton) buttons[commandID]; + ToolBarButton tbb = (ToolBarButton)buttons[commandID]; if (tbb != null && tbb.ToolTipText != null) ttt.lpszText = tbb.ToolTipText; @@ -1414,7 +1631,8 @@ private void WmNotifyNeedText(ref Message m) { // RightToLeft reading order // - if (RightToLeft == RightToLeft.Yes) { + if (RightToLeft == RightToLeft.Yes) + { ttt.uFlags |= NativeMethods.TTF_RTLREADING; } @@ -1424,7 +1642,8 @@ private void WmNotifyNeedText(ref Message m) { // Track the currently hot item since the user might be using the tab and // arrow keys to navigate the toolbar and if that's the case, we'll need to know where to re- // position the tooltip window when the underlying toolbar control attempts to display it. - private void WmNotifyHotItemChange(ref Message m) { + private void WmNotifyHotItemChange(ref Message m) + { // Should we set the hot item? NativeMethods.NMTBHOTITEM nmTbHotItem = (NativeMethods.NMTBHOTITEM)m.GetLParam(typeof(NativeMethods.NMTBHOTITEM)); if (NativeMethods.HICF_ENTERING == (nmTbHotItem.dwFlags & NativeMethods.HICF_ENTERING)) @@ -1450,12 +1669,14 @@ private void WmNotifyHotItemChange(ref Message m) { /// /// - private void WmReflectCommand(ref Message m) { + private void WmReflectCommand(ref Message m) + { int id = NativeMethods.Util.LOWORD(m.WParam); ToolBarButton tbb = buttons[id]; - if (tbb != null) { + if (tbb != null) + { ToolBarButtonClickEventArgs e = new ToolBarButtonClickEventArgs(tbb); OnButtonClick(e); } @@ -1467,16 +1688,19 @@ private void WmReflectCommand(ref Message m) { /// /// - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { case Interop.WindowMessages.WM_COMMAND + Interop.WindowMessages.WM_REFLECT: WmReflectCommand(ref m); break; case Interop.WindowMessages.WM_NOTIFY: case Interop.WindowMessages.WM_NOTIFY + Interop.WindowMessages.WM_REFLECT: - NativeMethods.NMHDR note = (NativeMethods.NMHDR) m.GetLParam(typeof(NativeMethods.NMHDR)); - switch (note.code) { + NativeMethods.NMHDR note = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR)); + switch (note.code) + { case NativeMethods.TTN_NEEDTEXT: // MSDN: // Setting the max width has the added benefit of enabling multiline @@ -1495,14 +1719,16 @@ protected override void WndProc(ref Message m) { // but nowhere near the toolbar button? if (wndPlacement.rcNormalPosition_left == 0 && wndPlacement.rcNormalPosition_top == 0 && - this.hotItem != -1) { + this.hotItem != -1) + { // Assume that we're going to vertically center the tooltip on the right edge of the current // hot item. // Where is the right edge of the current hot item? int buttonRight = 0; - for(int idx = 0; idx <= this.hotItem; idx++) { + for (int idx = 0; idx <= this.hotItem; idx++) + { // How wide is the item at this index? (It could be a separator, and therefore a different width.) buttonRight += buttonsCollection[idx].GetButtonWidth(); } @@ -1518,19 +1744,22 @@ protected override void WndProc(ref Message m) { UnsafeNativeMethods.ClientToScreen(new HandleRef(this, this.Handle), leftTop); // Will the tooltip bleed off the top? - if (leftTop.y < SystemInformation.WorkingArea.Y) { + if (leftTop.y < SystemInformation.WorkingArea.Y) + { // Reposition the tooltip to be displayed below the button leftTop.y += (this.ButtonSize.Height / 2) + 1; } // Will the tooltip bleed off the bottom? - if (leftTop.y + tooltipHeight > SystemInformation.WorkingArea.Height) { + if (leftTop.y + tooltipHeight > SystemInformation.WorkingArea.Height) + { // Reposition the tooltip to be displayed above the button leftTop.y -= ((this.ButtonSize.Height / 2) + tooltipHeight + 1); } // Will the tooltip bleed off the right edge? - if (leftTop.x + tooltipWidth > SystemInformation.WorkingArea.Right) { + if (leftTop.x + tooltipWidth > SystemInformation.WorkingArea.Right) + { // Move the tooltip far enough left that it will display in the working area leftTop.x -= (this.ButtonSize.Width + tooltipWidth + 2); } @@ -1564,10 +1793,11 @@ protected override void WndProc(ref Message m) { /// Encapsulates a collection of controls for use by the /// class. /// - public class ToolBarButtonCollection : IList { + public class ToolBarButtonCollection : IList + { private ToolBar owner; - private bool suspendUpdate; + private bool suspendUpdate; /// A caching mechanism for key accessor /// We use an index here rather than control so that we don't have lifetime /// issues by holding on to extra references. @@ -1577,7 +1807,8 @@ public class ToolBarButtonCollection : IList { /// /// Initializes a new instance of the class and assigns it to the specified toolbar. /// - public ToolBarButtonCollection(ToolBar owner) { + public ToolBarButtonCollection(ToolBar owner) + { this.owner = owner; } @@ -1585,20 +1816,25 @@ public ToolBarButtonCollection(ToolBar owner) { /// Gets or sets the toolbar button at the specified indexed location in the /// toolbar button collection. /// - public virtual ToolBarButton this[int index] { - get { + public virtual ToolBarButton this[int index] + { + get + { if (index < 0 || ((owner.buttons != null) && (index >= owner.buttonCount))) - throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); - return owner.buttons[index]; + throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + return owner.buttons[index]; } - set { + set + { // Sanity check parameters // - if (index < 0 || ((owner.buttons != null) && index >= owner.buttonCount)) { + if (index < 0 || ((owner.buttons != null) && index >= owner.buttonCount)) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - if (value == null) { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } @@ -1606,35 +1842,45 @@ public virtual ToolBarButton this[int index] { } } - object IList.this[int index] { - get { + object IList.this[int index] + { + get + { return this[index]; } - set { - if (value is ToolBarButton) { + set + { + if (value is ToolBarButton) + { this[index] = (ToolBarButton)value; } - else { - throw new ArgumentException(SR.ToolBarBadToolBarButton,"value"); + else + { + throw new ArgumentException(SR.ToolBarBadToolBarButton, "value"); } } } /// /// Retrieves the child control with the specified key. /// - public virtual ToolBarButton this[string key] { - get { + public virtual ToolBarButton this[string key] + { + get + { // We do not support null and empty string as valid keys. - if (string.IsNullOrEmpty(key)){ + if (string.IsNullOrEmpty(key)) + { return null; } // Search for the key in our collection int index = IndexOfKey(key); - if (IsValidIndex(index)) { + if (IsValidIndex(index)) + { return this[index]; } - else { + else + { return null; } @@ -1644,32 +1890,42 @@ public virtual ToolBarButton this[string key] { /// Gets the number of buttons in the toolbar button collection. /// [Browsable(false)] - public int Count { - get { + public int Count + { + get + { return owner.buttonCount; } } - object ICollection.SyncRoot { - get { + object ICollection.SyncRoot + { + get + { return this; } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return false; } } - bool IList.IsFixedSize { - get { + bool IList.IsFixedSize + { + get + { return false; } } - public bool IsReadOnly { - get { + public bool IsReadOnly + { + get + { return false; } } @@ -1678,42 +1934,53 @@ public bool IsReadOnly { /// Adds a new toolbar button to /// the end of the toolbar button collection. /// - public int Add(ToolBarButton button) { + public int Add(ToolBarButton button) + { int index = owner.InternalAddButton(button); - if (!suspendUpdate) { + if (!suspendUpdate) + { owner.UpdateButtons(); } return index; } - public int Add(string text) { + public int Add(string text) + { ToolBarButton button = new ToolBarButton(text); return Add(button); } - int IList.Add(object button) { - if (button is ToolBarButton) { + int IList.Add(object button) + { + if (button is ToolBarButton) + { return Add((ToolBarButton)button); } - else { - throw new ArgumentException(SR.ToolBarBadToolBarButton,"button"); + else + { + throw new ArgumentException(SR.ToolBarBadToolBarButton, "button"); } } - public void AddRange(ToolBarButton[] buttons) { - if (buttons == null) { + public void AddRange(ToolBarButton[] buttons) + { + if (buttons == null) + { throw new ArgumentNullException(nameof(buttons)); } - try { + try + { suspendUpdate = true; - foreach(ToolBarButton button in buttons) { + foreach (ToolBarButton button in buttons) + { Add(button); } } - finally { + finally + { suspendUpdate = false; owner.UpdateButtons(); } @@ -1724,14 +1991,18 @@ public void AddRange(ToolBarButton[] buttons) { /// Removes /// all buttons from the toolbar button collection. /// - public void Clear() { + public void Clear() + { - if (owner.buttons == null) { + if (owner.buttons == null) + { return; } - for (int x = owner.buttonCount; x > 0; x--) { - if (owner.IsHandleCreated) { + for (int x = owner.buttonCount; x > 0; x--) + { + if (owner.IsHandleCreated) + { owner.SendMessage(NativeMethods.TB_DELETEBUTTON, x - 1, 0); } owner.RemoveAt(x - 1); @@ -1739,53 +2010,67 @@ public void Clear() { owner.buttons = null; owner.buttonCount = 0; - if (!owner.Disposing) { + if (!owner.Disposing) + { owner.UpdateButtons(); } } - public bool Contains(ToolBarButton button) { + public bool Contains(ToolBarButton button) + { return IndexOf(button) != -1; } - bool IList.Contains(object button) { - if (button is ToolBarButton) { + bool IList.Contains(object button) + { + if (button is ToolBarButton) + { return Contains((ToolBarButton)button); } - else { + else + { return false; } } - /// - /// Returns true if the collection contains an item with the specified key, false otherwise. - /// - public virtual bool ContainsKey(string key) { - return IsValidIndex(IndexOfKey(key)); - } + /// + /// Returns true if the collection contains an item with the specified key, false otherwise. + /// + public virtual bool ContainsKey(string key) + { + return IsValidIndex(IndexOfKey(key)); + } - void ICollection.CopyTo(Array dest, int index) { - if (owner.buttonCount > 0) { + void ICollection.CopyTo(Array dest, int index) + { + if (owner.buttonCount > 0) + { System.Array.Copy(owner.buttons, 0, dest, index, owner.buttonCount); } } - public int IndexOf(ToolBarButton button) { - for(int index=0; index < Count; ++index) { - if (this[index] == button) { + public int IndexOf(ToolBarButton button) + { + for (int index = 0; index < Count; ++index) + { + if (this[index] == button) + { return index; } } return -1; } - int IList.IndexOf(object button) { - if (button is ToolBarButton) { + int IList.IndexOf(object button) + { + if (button is ToolBarButton) + { return IndexOf((ToolBarButton)button); } - else { + else + { return -1; } } @@ -1793,23 +2078,28 @@ int IList.IndexOf(object button) { /// /// The zero-based index of the first occurrence of value within the entire CollectionBase, if found; otherwise, -1. /// - public virtual int IndexOfKey(string key) { - // Step 0 - Arg validation - if (string.IsNullOrEmpty(key)){ - return -1; // we dont support empty or null keys. - } + public virtual int IndexOfKey(string key) + { + // Step 0 - Arg validation + if (string.IsNullOrEmpty(key)) + { + return -1; // we dont support empty or null keys. + } // step 1 - check the last cached item if (IsValidIndex(lastAccessedIndex)) { - if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) { + if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) + { return lastAccessedIndex; } } // step 2 - search for the item - for (int i = 0; i < this.Count; i ++) { - if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { + for (int i = 0; i < this.Count; i++) + { + if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) + { lastAccessedIndex = i; return i; } @@ -1820,37 +2110,44 @@ public virtual int IndexOfKey(string key) { return -1; } - public void Insert(int index, ToolBarButton button) { + public void Insert(int index, ToolBarButton button) + { owner.InsertButton(index, button); } - void IList.Insert(int index, object button) { - if (button is ToolBarButton) { + void IList.Insert(int index, object button) + { + if (button is ToolBarButton) + { Insert(index, (ToolBarButton)button); } - else { - throw new ArgumentException(SR.ToolBarBadToolBarButton,"button"); + else + { + throw new ArgumentException(SR.ToolBarBadToolBarButton, "button"); } } - /// - /// Determines if the index is valid for the collection. - /// - private bool IsValidIndex(int index) { - return ((index >= 0) && (index < this.Count)); + /// + /// Determines if the index is valid for the collection. + /// + private bool IsValidIndex(int index) + { + return ((index >= 0) && (index < this.Count)); } /// /// Removes /// a given button from the toolbar button collection. /// - public void RemoveAt(int index) { + public void RemoveAt(int index) + { int count = (owner.buttons == null) ? 0 : owner.buttonCount; if (index < 0 || index >= count) throw new ArgumentOutOfRangeException(nameof(index), string.Format(SR.InvalidArgument, "index", index.ToString(CultureInfo.CurrentCulture))); - if (owner.IsHandleCreated) { + if (owner.IsHandleCreated) + { owner.SendMessage(NativeMethods.TB_DELETEBUTTON, index, 0); } @@ -1861,25 +2158,31 @@ public void RemoveAt(int index) { - /// - /// Removes the child control with the specified key. - /// - public virtual void RemoveByKey(string key) { + /// + /// Removes the child control with the specified key. + /// + public virtual void RemoveByKey(string key) + { int index = IndexOfKey(key); - if (IsValidIndex(index)) { + if (IsValidIndex(index)) + { RemoveAt(index); - } + } } - public void Remove(ToolBarButton button) { + public void Remove(ToolBarButton button) + { int index = IndexOf(button); - if (index != -1) { + if (index != -1) + { RemoveAt(index); } } - void IList.Remove(object button) { - if (button is ToolBarButton) { + void IList.Remove(object button) + { + if (button is ToolBarButton) + { Remove((ToolBarButton)button); } } @@ -1888,7 +2191,8 @@ void IList.Remove(object button) { /// Returns an enumerator that can be used to iterate /// through the toolbar button collection. /// - public IEnumerator GetEnumerator() { + public IEnumerator GetEnumerator() + { return new WindowsFormsUtils.ArraySubsetEnumerator(owner.buttons, owner.buttonCount); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs index 17f1232be68..4fc6fb95262 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.ComponentModel; @@ -14,7 +15,7 @@ namespace System.Windows.Forms { using System.Text; using System.Drawing.Design; using Marshal = System.Runtime.InteropServices.Marshal; - using System.Windows.Forms; + using System.Windows.Forms; using Microsoft.Win32; using System.Globalization; @@ -29,7 +30,8 @@ namespace System.Windows.Forms { ToolboxItem(false), DesignTimeVisible(false), ] - public class ToolBarButton : Component { + public class ToolBarButton : Component + { string text; string name = null; @@ -39,7 +41,7 @@ public class ToolBarButton : Component { bool pushed = false; bool partialPush = false; private int commandId = -1; // the cached command id of the button. - private ToolBarButtonImageIndexer imageIndexer; + private ToolBarButtonImageIndexer imageIndexer; ToolBarButtonStyle style = ToolBarButtonStyle.PushButton; @@ -68,47 +70,57 @@ public class ToolBarButton : Component { /// /// Initializes a new instance of the class. /// - public ToolBarButton() { + public ToolBarButton() + { } - - public ToolBarButton(string text) : base() { + + public ToolBarButton(string text) : base() + { this.Text = text; } - + // We need a special way to defer to the ToolBar's image // list for indexing purposes. - internal class ToolBarButtonImageIndexer : ImageList.Indexer { + internal class ToolBarButtonImageIndexer : ImageList.Indexer + { private ToolBarButton owner; - - public ToolBarButtonImageIndexer(ToolBarButton button) { - owner = button; - } - - public override ImageList ImageList { - get { - if ((owner != null) && (owner.parent != null)) { - return owner.parent.ImageList; - } - return null; + + public ToolBarButtonImageIndexer(ToolBarButton button) + { + owner = button; + } + + public override ImageList ImageList + { + get + { + if ((owner != null) && (owner.parent != null)) + { + return owner.parent.ImageList; } + return null; + } set { Debug.Assert(false, "We should never set the image list"); } } } - internal ToolBarButtonImageIndexer ImageIndexer { - get { - if (imageIndexer == null) { - imageIndexer = new ToolBarButtonImageIndexer(this); - } + internal ToolBarButtonImageIndexer ImageIndexer + { + get + { + if (imageIndexer == null) + { + imageIndexer = new ToolBarButtonImageIndexer(this); + } - return imageIndexer; + return imageIndexer; } } - + /// /// /// Indicates the menu to be displayed in @@ -119,15 +131,19 @@ internal ToolBarButtonImageIndexer ImageIndexer { TypeConverterAttribute(typeof(ReferenceConverter)), SRDescription(nameof(SR.ToolBarButtonMenuDescr)) ] - public Menu DropDownMenu { - get { + public Menu DropDownMenu + { + get + { return dropDownMenu; } - set { + set + { //The dropdownmenu must be of type ContextMenu, Main & Items are invalid. // - if (value != null && !(value is ContextMenu)) { + if (value != null && !(value is ContextMenu)) + { throw new ArgumentException(SR.ToolBarButtonInvalidDropDownMenuType); } dropDownMenu = value; @@ -142,17 +158,22 @@ public Menu DropDownMenu { Localizable(true), SRDescription(nameof(SR.ToolBarButtonEnabledDescr)) ] - public bool Enabled { - get { + public bool Enabled + { + get + { return enabled; } - set { - if (enabled != value) { + set + { + if (enabled != value) + { enabled = value; - if (parent != null && parent.IsHandleCreated) { + if (parent != null && parent.IsHandleCreated) + { parent.SendMessage(NativeMethods.TB_ENABLEBUTTON, FindButtonIndex(), enabled ? 1 : 0); } @@ -168,16 +189,20 @@ public bool Enabled { TypeConverterAttribute(typeof(ImageIndexConverter)), Editor("System.Windows.Forms.Design.ImageIndexEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), DefaultValue(-1), - RefreshProperties(RefreshProperties.Repaint), + RefreshProperties(RefreshProperties.Repaint), Localizable(true), SRDescription(nameof(SR.ToolBarButtonImageIndexDescr)) ] - public int ImageIndex { - get { + public int ImageIndex + { + get + { return ImageIndexer.Index; } - set { - if (ImageIndexer.Index != value) { + set + { + if (ImageIndexer.Index != value) + { if (value < -1) throw new ArgumentOutOfRangeException(nameof(ImageIndex), string.Format(SR.InvalidLowBoundArgumentEx, nameof(ImageIndex), value, -1)); @@ -199,12 +224,16 @@ public int ImageIndex { RefreshProperties(RefreshProperties.Repaint), SRDescription(nameof(SR.ToolBarButtonImageIndexDescr)) ] - public string ImageKey { - get { + public string ImageKey + { + get + { return ImageIndexer.Key; } - set { - if (ImageIndexer.Key != value) { + set + { + if (ImageIndexer.Key != value) + { ImageIndexer.Key = value; UpdateButton(false); } @@ -216,18 +245,24 @@ public string ImageKey { /// property has no bearing on the runtime aspects of this control. /// [Browsable(false)] - public string Name { - get { + public string Name + { + get + { return WindowsFormsUtils.GetComponentName(this, name); } - set { - if (value == null || value.Length == 0) { + set + { + if (value == null || value.Length == 0) + { name = null; } - else { - name = value; + else + { + name = value; } - if(Site!= null) { + if (Site != null) + { Site.Name = name; } } @@ -241,8 +276,10 @@ public string Name { [ Browsable(false), ] - public ToolBar Parent { - get { + public ToolBar Parent + { + get + { return parent; } } @@ -256,11 +293,14 @@ public ToolBar Parent { DefaultValue(false), SRDescription(nameof(SR.ToolBarButtonPartialPushDescr)) ] - public bool PartialPush { - get { + public bool PartialPush + { + get + { if (parent == null || !parent.IsHandleCreated) return partialPush; - else { + else + { if ((int)parent.SendMessage(NativeMethods.TB_ISBUTTONINDETERMINATE, FindButtonIndex(), 0) != 0) partialPush = true; else @@ -269,8 +309,10 @@ public bool PartialPush { return partialPush; } } - set { - if (partialPush != value) { + set + { + if (partialPush != value) + { partialPush = value; UpdateButton(false); } @@ -284,16 +326,21 @@ public bool PartialPush { DefaultValue(false), SRDescription(nameof(SR.ToolBarButtonPushedDescr)) ] - public bool Pushed { - get { + public bool Pushed + { + get + { if (parent == null || !parent.IsHandleCreated) return pushed; - else { + else + { return GetPushedState(); } } - set { - if (value != Pushed) { // Getting property Pushed updates pushed member variable + set + { + if (value != Pushed) + { // Getting property Pushed updates pushed member variable pushed = value; UpdateButton(false, false, false); } @@ -304,9 +351,12 @@ public bool Pushed { /// Indicates the bounding rectangle for a toolbar button. This property is /// read-only. /// - public Rectangle Rectangle { - get { - if (parent != null) { + public Rectangle Rectangle + { + get + { + if (parent != null) + { NativeMethods.RECT rc = new NativeMethods.RECT(); UnsafeNativeMethods.SendMessage(new HandleRef(parent, parent.Handle), NativeMethods.TB_GETRECT, FindButtonIndex(), ref rc); return Rectangle.FromLTRB(rc.left, rc.top, rc.right, rc.bottom); @@ -324,16 +374,21 @@ public Rectangle Rectangle { SRDescription(nameof(SR.ToolBarButtonStyleDescr)), RefreshProperties(RefreshProperties.Repaint) ] - public ToolBarButtonStyle Style { - get { + public ToolBarButtonStyle Style + { + get + { return style; } - set { + set + { //valid values are 0x1 to 0x4 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolBarButtonStyle.PushButton, (int)ToolBarButtonStyle.DropDownButton)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolBarButtonStyle.PushButton, (int)ToolBarButtonStyle.DropDownButton)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolBarButtonStyle)); } - if (style == value) return; + if (style == value) + return; style = value; UpdateButton(true); } @@ -347,11 +402,14 @@ public ToolBarButtonStyle Style { DefaultValue(null), TypeConverter(typeof(StringConverter)), ] - public object Tag { - get { + public object Tag + { + get + { return userData; } - set { + set + { userData = value; } } @@ -364,17 +422,22 @@ public object Tag { DefaultValue(""), SRDescription(nameof(SR.ToolBarButtonTextDescr)) ] - public string Text { - get { - return(text == null) ? "" : text; - } - set { - if (string.IsNullOrEmpty(value)) { + public string Text + { + get + { + return (text == null) ? "" : text; + } + set + { + if (string.IsNullOrEmpty(value)) + { value = null; } - - if ( (value == null && text != null) || - (value != null && (text == null || !text.Equals(value)))) { + + if ((value == null && text != null) || + (value != null && (text == null || !text.Equals(value)))) + { text = value; // Adding a mnemonic requires a handle recreate. UpdateButton(WindowsFormsUtils.ContainsMnemonic(text), true, true); @@ -382,7 +445,7 @@ public string Text { } } - + /// /// @@ -394,11 +457,14 @@ public string Text { DefaultValue(""), SRDescription(nameof(SR.ToolBarButtonToolTipTextDescr)) ] - public string ToolTipText { - get { + public string ToolTipText + { + get + { return tooltipText == null ? "" : tooltipText; } - set { + set + { tooltipText = value; } } @@ -413,12 +479,16 @@ public string ToolTipText { Localizable(true), SRDescription(nameof(SR.ToolBarButtonVisibleDescr)) ] - public bool Visible { - get { + public bool Visible + { + get + { return visible; } - set { - if (visible != value) { + set + { + if (visible != value) + { visible = value; UpdateButton(false); } @@ -431,65 +501,80 @@ public bool Visible { /// algorithm that doesn't include for things like drop down arrows, etc. /// We need to do a bunch of work here to get all the widths correct. Ugh. /// - internal short Width { - get { + internal short Width + { + get + { Debug.Assert(parent != null, "Parent should be non-null when button width is requested"); - + int width = 0; ToolBarButtonStyle style = Style; Size edge = SystemInformation.Border3DSize; - if (style != ToolBarButtonStyle.Separator) { + if (style != ToolBarButtonStyle.Separator) + { // COMPAT: this will force handle creation. // we could use the measurement graphics, but it looks like this has been like this since Everett. - using (Graphics g = this.parent.CreateGraphicsInternal()) { + using (Graphics g = this.parent.CreateGraphicsInternal()) + { - Size buttonSize = this.parent.buttonSize; - if (!(buttonSize.IsEmpty)) { + Size buttonSize = this.parent.buttonSize; + if (!(buttonSize.IsEmpty)) + { width = buttonSize.Width; } - else { - if (this.parent.ImageList != null || !string.IsNullOrEmpty(Text)) { + else + { + if (this.parent.ImageList != null || !string.IsNullOrEmpty(Text)) + { Size imageSize = this.parent.ImageSize; Size textSize = Size.Ceiling(g.MeasureString(Text, parent.Font)); - if (this.parent.TextAlign == ToolBarTextAlign.Right) { + if (this.parent.TextAlign == ToolBarTextAlign.Right) + { if (textSize.Width == 0) width = imageSize.Width + edge.Width * 4; else width = imageSize.Width + textSize.Width + edge.Width * 6; } - else { + else + { if (imageSize.Width > textSize.Width) width = imageSize.Width + edge.Width * 4; else width = textSize.Width + edge.Width * 4; } - if (style == ToolBarButtonStyle.DropDownButton && this.parent.DropDownArrows) { + if (style == ToolBarButtonStyle.DropDownButton && this.parent.DropDownArrows) + { width += ToolBar.DDARROW_WIDTH; } } else - width = this.parent.ButtonSize.Width; + width = this.parent.ButtonSize.Width; } } } - else { + else + { width = edge.Width * 2; } - return(short)width; + return (short)width; } } /// /// - protected override void Dispose(bool disposing) { - if (disposing) { - if (parent != null) { + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (parent != null) + { int index = FindButtonIndex(); - if (index != -1) { + if (index != -1) + { parent.Buttons.RemoveAt(index); } } @@ -500,9 +585,12 @@ protected override void Dispose(bool disposing) { /// /// Finds out index in the parent. /// - private int FindButtonIndex() { - for (int x = 0; x < parent.Buttons.Count; x++) { - if (parent.Buttons[x] == this) { + private int FindButtonIndex() + { + for (int x = 0; x < parent.Buttons.Count; x++) + { + if (parent.Buttons[x] == this) + { return x; } } @@ -512,29 +600,33 @@ private int FindButtonIndex() { // This is necessary to get the width of the buttons in the toolbar, // including the width of separators, so that we can accurately position the tooltip adjacent // to the currently hot button when the user uses keyboard navigation to access the toolbar. - internal int GetButtonWidth() { + internal int GetButtonWidth() + { // Assume that this button is the same width as the parent's ButtonSize's Width int buttonWidth = Parent.ButtonSize.Width; - + NativeMethods.TBBUTTONINFO button = new NativeMethods.TBBUTTONINFO(); button.cbSize = Marshal.SizeOf(); button.dwMask = NativeMethods.TBIF_SIZE; - + int buttonID = (int)UnsafeNativeMethods.SendMessage(new HandleRef(Parent, Parent.Handle), NativeMethods.TB_GETBUTTONINFO, commandId, ref button); - if (buttonID != -1) { + if (buttonID != -1) + { buttonWidth = button.cx; } - + return buttonWidth; } - + private bool GetPushedState() { - if ((int)parent.SendMessage(NativeMethods.TB_ISBUTTONCHECKED, FindButtonIndex(), 0) != 0) { + if ((int)parent.SendMessage(NativeMethods.TB_ISBUTTONCHECKED, FindButtonIndex(), 0) != 0) + { pushed = true; } - else { + else + { pushed = false; } @@ -544,7 +636,8 @@ private bool GetPushedState() /// /// Returns a TBBUTTON object that represents this ToolBarButton. /// - internal NativeMethods.TBBUTTON GetTBBUTTON(int commandId) { + internal NativeMethods.TBBUTTON GetTBBUTTON(int commandId) + { NativeMethods.TBBUTTON button = new NativeMethods.TBBUTTON(); @@ -553,14 +646,19 @@ internal NativeMethods.TBBUTTON GetTBBUTTON(int commandId) { // set up the state of the button // button.fsState = 0; - if (enabled) button.fsState |= NativeMethods.TBSTATE_ENABLED; - if (partialPush && style == ToolBarButtonStyle.ToggleButton) button.fsState |= NativeMethods.TBSTATE_INDETERMINATE; - if (pushed) button.fsState |= NativeMethods.TBSTATE_CHECKED; - if (!visible) button.fsState |= NativeMethods.TBSTATE_HIDDEN; + if (enabled) + button.fsState |= NativeMethods.TBSTATE_ENABLED; + if (partialPush && style == ToolBarButtonStyle.ToggleButton) + button.fsState |= NativeMethods.TBSTATE_INDETERMINATE; + if (pushed) + button.fsState |= NativeMethods.TBSTATE_CHECKED; + if (!visible) + button.fsState |= NativeMethods.TBSTATE_HIDDEN; // set the button style // - switch (style) { + switch (style) + { case ToolBarButtonStyle.PushButton: button.fsStyle = NativeMethods.TBSTYLE_BUTTON; break; @@ -587,7 +685,8 @@ internal NativeMethods.TBBUTTON GetTBBUTTON(int commandId) { /// /// Returns a TBBUTTONINFO object that represents this ToolBarButton. /// - internal NativeMethods.TBBUTTONINFO GetTBBUTTONINFO(bool updateText, int newCommandId) { + internal NativeMethods.TBBUTTONINFO GetTBBUTTONINFO(bool updateText, int newCommandId) + { NativeMethods.TBBUTTONINFO button = new NativeMethods.TBBUTTONINFO(); button.cbSize = Marshal.SizeOf(); @@ -597,13 +696,15 @@ internal NativeMethods.TBBUTTONINFO GetTBBUTTONINFO(bool updateText, int newComm // Older platforms interpret null strings as empty, which forces the button to // leave space for text. // The only workaround is to avoid having comctl update the text. - if (updateText) { + if (updateText) + { button.dwMask |= NativeMethods.TBIF_TEXT; } button.iImage = ImageIndexer.ActualIndex; - if (newCommandId != commandId) { + if (newCommandId != commandId) + { commandId = newCommandId; button.idCommand = newCommandId; button.dwMask |= NativeMethods.TBIF_COMMAND; @@ -612,14 +713,19 @@ internal NativeMethods.TBBUTTONINFO GetTBBUTTONINFO(bool updateText, int newComm // set up the state of the button // button.fsState = 0; - if (enabled) button.fsState |= NativeMethods.TBSTATE_ENABLED; - if (partialPush && style == ToolBarButtonStyle.ToggleButton) button.fsState |= NativeMethods.TBSTATE_INDETERMINATE; - if (pushed) button.fsState |= NativeMethods.TBSTATE_CHECKED; - if (!visible) button.fsState |= NativeMethods.TBSTATE_HIDDEN; + if (enabled) + button.fsState |= NativeMethods.TBSTATE_ENABLED; + if (partialPush && style == ToolBarButtonStyle.ToggleButton) + button.fsState |= NativeMethods.TBSTATE_INDETERMINATE; + if (pushed) + button.fsState |= NativeMethods.TBSTATE_CHECKED; + if (!visible) + button.fsState |= NativeMethods.TBSTATE_HIDDEN; // set the button style // - switch (style) { + switch (style) + { case ToolBarButtonStyle.PushButton: button.fsStyle = NativeMethods.TBSTYLE_BUTTON; break; @@ -632,10 +738,12 @@ internal NativeMethods.TBBUTTONINFO GetTBBUTTONINFO(bool updateText, int newComm } - if (text == null) { + if (text == null) + { button.pszText = Marshal.StringToHGlobalAuto("\0\0"); } - else { + else + { string textValue = this.text; PrefixAmpersands(ref textValue); button.pszText = Marshal.StringToHGlobalAuto(textValue); @@ -643,47 +751,55 @@ internal NativeMethods.TBBUTTONINFO GetTBBUTTONINFO(bool updateText, int newComm return button; } - - private void PrefixAmpersands(ref string value) { + + private void PrefixAmpersands(ref string value) + { // Due to a comctl32 problem, ampersands underline the next letter in the // text string, but the accelerators don't work. // So in this function, we prefix ampersands with another ampersand // so that they actually appear as ampersands. // - + // Sanity check parameter // - if (value == null || value.Length == 0) { + if (value == null || value.Length == 0) + { return; } - + // If there are no ampersands, we don't need to do anything here // - if (value.IndexOf('&') < 0) { + if (value.IndexOf('&') < 0) + { return; } - + // Insert extra ampersands // StringBuilder newString = new StringBuilder(); - for(int i=0; i < value.Length; ++i) { - if (value[i] == '&') { - if (i < value.Length - 1 && value[i+1] == '&') { + for (int i = 0; i < value.Length; ++i) + { + if (value[i] == '&') + { + if (i < value.Length - 1 && value[i + 1] == '&') + { ++i; // Skip the second ampersand } newString.Append("&&"); } - else { - newString.Append(value[i]); + else + { + newString.Append(value[i]); } } - + value = newString.ToString(); } /// /// - public override string ToString() { + public override string ToString() + { return "ToolBarButton: " + Text + ", Style: " + Style.ToString("G"); } @@ -692,20 +808,23 @@ public override string ToString() { /// we need to make sure it gets the new button information. /// If Text was changed, call the next overload. /// - internal void UpdateButton(bool recreate) { - UpdateButton(recreate, false, true); + internal void UpdateButton(bool recreate) + { + UpdateButton(recreate, false, true); } /// /// When a button property changes and the parent control is created, /// we need to make sure it gets the new button information. /// - private void UpdateButton(bool recreate, bool updateText, bool updatePushedState) { + private void UpdateButton(bool recreate, bool updateText, bool updatePushedState) + { // It looks like ToolBarButtons with a DropDownButton tend to // lose the DropDownButton very easily - so we need to recreate // the button each time it changes just to be sure. // - if (style == ToolBarButtonStyle.DropDownButton && parent != null && parent.DropDownArrows) { + if (style == ToolBarButtonStyle.DropDownButton && parent != null && parent.DropDownArrows) + { recreate = true; } @@ -716,14 +835,16 @@ private void UpdateButton(bool recreate, bool updateText, bool updatePushedState // the GetButtonInfo method uses the "pushed" variable.. //rather than setting it ourselves .... we asks the button to set it for us.. - if (updatePushedState && parent != null && parent.IsHandleCreated) { + if (updatePushedState && parent != null && parent.IsHandleCreated) + { GetPushedState(); } - if (parent != null) { + if (parent != null) + { int index = FindButtonIndex(); if (index != -1) parent.InternalSetButton(index, this, recreate, updateText); } - } + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs index 08663280f14..c5bfc0b979a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Configuration; using System.Collections; @@ -35,108 +36,108 @@ namespace System.Windows.Forms { [DefaultProperty(nameof(Items))] [SRDescription(nameof(SR.DescriptionToolStrip))] [DefaultEvent(nameof(ItemClicked))] - - public class ToolStrip : System.Windows.Forms.ScrollableControl, + + public class ToolStrip : System.Windows.Forms.ScrollableControl, IArrangedElement, ISupportToolStripPanel - { - - - private static Size onePixel = new Size(1,1); - internal static Point InvalidMouseEnter = new Point(int.MaxValue, int.MaxValue); - - private ToolStripItemCollection toolStripItemCollection = null; - private ToolStripOverflowButton toolStripOverflowButton = null; - private ToolStripGrip toolStripGrip = null; - private ToolStripItemCollection displayedItems = null; - private ToolStripItemCollection overflowItems = null; - private ToolStripDropTargetManager dropTargetManager = null; - private IntPtr hwndThatLostFocus = IntPtr.Zero; - private ToolStripItem lastMouseActiveItem = null; - private ToolStripItem lastMouseDownedItem = null; - private LayoutEngine layoutEngine = null; - private ToolStripLayoutStyle layoutStyle = ToolStripLayoutStyle.StackWithOverflow; - private LayoutSettings layoutSettings = null; - private Rectangle lastInsertionMarkRect = Rectangle.Empty; - private ImageList imageList = null; - private ToolStripGripStyle toolStripGripStyle = ToolStripGripStyle.Visible; - private ISupportOleDropSource itemReorderDropSource = null; - private IDropTarget itemReorderDropTarget = null; - private int toolStripState = 0; - private bool showItemToolTips = false; - private MouseHoverTimer mouseHoverTimer = null; - private ToolStripItem currentlyActiveTooltipItem; - private NativeWindow dropDownOwnerWindow; - private byte mouseDownID = 0; // NEVER use this directly from another class, 0 should never be returned to another class. - - private Orientation orientation = Orientation.Horizontal; - - private ArrayList activeDropDowns = new ArrayList(1); - private ToolStripRenderer renderer = null; - private Type currentRendererType = typeof(System.Type); - private Hashtable shortcuts = null; - private Stack mergeHistoryStack = null; - private ToolStripDropDownDirection toolStripDropDownDirection = ToolStripDropDownDirection.Default; - private Size largestDisplayedItemSize = Size.Empty; - private CachedItemHdcInfo cachedItemHdcInfo = null; - private bool alreadyHooked = false; - - private Size imageScalingSize; - private const int ICON_DIMENSION = 16; - private static int iconWidth = ICON_DIMENSION; - private static int iconHeight = ICON_DIMENSION; - - private Font defaultFont = null; - private RestoreFocusMessageFilter restoreFocusFilter; - - private bool layoutRequired = false; + { + + + private static Size onePixel = new Size(1, 1); + internal static Point InvalidMouseEnter = new Point(int.MaxValue, int.MaxValue); + + private ToolStripItemCollection toolStripItemCollection = null; + private ToolStripOverflowButton toolStripOverflowButton = null; + private ToolStripGrip toolStripGrip = null; + private ToolStripItemCollection displayedItems = null; + private ToolStripItemCollection overflowItems = null; + private ToolStripDropTargetManager dropTargetManager = null; + private IntPtr hwndThatLostFocus = IntPtr.Zero; + private ToolStripItem lastMouseActiveItem = null; + private ToolStripItem lastMouseDownedItem = null; + private LayoutEngine layoutEngine = null; + private ToolStripLayoutStyle layoutStyle = ToolStripLayoutStyle.StackWithOverflow; + private LayoutSettings layoutSettings = null; + private Rectangle lastInsertionMarkRect = Rectangle.Empty; + private ImageList imageList = null; + private ToolStripGripStyle toolStripGripStyle = ToolStripGripStyle.Visible; + private ISupportOleDropSource itemReorderDropSource = null; + private IDropTarget itemReorderDropTarget = null; + private int toolStripState = 0; + private bool showItemToolTips = false; + private MouseHoverTimer mouseHoverTimer = null; + private ToolStripItem currentlyActiveTooltipItem; + private NativeWindow dropDownOwnerWindow; + private byte mouseDownID = 0; // NEVER use this directly from another class, 0 should never be returned to another class. + + private Orientation orientation = Orientation.Horizontal; + + private ArrayList activeDropDowns = new ArrayList(1); + private ToolStripRenderer renderer = null; + private Type currentRendererType = typeof(System.Type); + private Hashtable shortcuts = null; + private Stack mergeHistoryStack = null; + private ToolStripDropDownDirection toolStripDropDownDirection = ToolStripDropDownDirection.Default; + private Size largestDisplayedItemSize = Size.Empty; + private CachedItemHdcInfo cachedItemHdcInfo = null; + private bool alreadyHooked = false; + + private Size imageScalingSize; + private const int ICON_DIMENSION = 16; + private static int iconWidth = ICON_DIMENSION; + private static int iconHeight = ICON_DIMENSION; + + private Font defaultFont = null; + private RestoreFocusMessageFilter restoreFocusFilter; + + private bool layoutRequired = false; private static readonly Padding defaultPadding = new Padding(0, 0, 1, 0); private static readonly Padding defaultGripMargin = new Padding(2); - private Padding scaledDefaultPadding = defaultPadding; - private Padding scaledDefaultGripMargin = defaultGripMargin; - - - private Point mouseEnterWhenShown = InvalidMouseEnter; - - private const int INSERTION_BEAM_WIDTH = 6; - - internal static int insertionBeamWidth = INSERTION_BEAM_WIDTH; - - private static readonly object EventPaintGrip = new object(); - private static readonly object EventLayoutCompleted = new object(); - private static readonly object EventItemAdded = new object(); - private static readonly object EventItemRemoved = new object(); - private static readonly object EventLayoutStyleChanged = new object(); - private static readonly object EventRendererChanged = new object(); - private static readonly object EventItemClicked = new object(); - private static readonly object EventLocationChanging = new object(); - private static readonly object EventBeginDrag = new object(); - private static readonly object EventEndDrag = new object(); - - private static readonly int PropBindingContext = PropertyStore.CreateKey(); - private static readonly int PropTextDirection = PropertyStore.CreateKey(); - private static readonly int PropToolTip = PropertyStore.CreateKey(); - private static readonly int PropToolStripPanelCell = PropertyStore.CreateKey(); - - internal const int STATE_CANOVERFLOW = 0x00000001; - internal const int STATE_ALLOWITEMREORDER = 0x00000002; - internal const int STATE_DISPOSINGITEMS = 0x00000004; - internal const int STATE_MENUAUTOEXPAND = 0x00000008; - internal const int STATE_MENUAUTOEXPANDDEFAULT = 0x00000010; - internal const int STATE_SCROLLBUTTONS = 0x00000020; - internal const int STATE_USEDEFAULTRENDERER = 0x00000040; - internal const int STATE_ALLOWMERGE = 0x00000080; - internal const int STATE_RAFTING = 0x00000100; - internal const int STATE_STRETCH = 0x00000200; - internal const int STATE_LOCATIONCHANGING = 0x00000400; - internal const int STATE_DRAGGING = 0x00000800; - internal const int STATE_HASVISIBLEITEMS = 0x00001000; - internal const int STATE_SUSPENDCAPTURE = 0x00002000; + private Padding scaledDefaultPadding = defaultPadding; + private Padding scaledDefaultGripMargin = defaultGripMargin; + + + private Point mouseEnterWhenShown = InvalidMouseEnter; + + private const int INSERTION_BEAM_WIDTH = 6; + + internal static int insertionBeamWidth = INSERTION_BEAM_WIDTH; + + private static readonly object EventPaintGrip = new object(); + private static readonly object EventLayoutCompleted = new object(); + private static readonly object EventItemAdded = new object(); + private static readonly object EventItemRemoved = new object(); + private static readonly object EventLayoutStyleChanged = new object(); + private static readonly object EventRendererChanged = new object(); + private static readonly object EventItemClicked = new object(); + private static readonly object EventLocationChanging = new object(); + private static readonly object EventBeginDrag = new object(); + private static readonly object EventEndDrag = new object(); + + private static readonly int PropBindingContext = PropertyStore.CreateKey(); + private static readonly int PropTextDirection = PropertyStore.CreateKey(); + private static readonly int PropToolTip = PropertyStore.CreateKey(); + private static readonly int PropToolStripPanelCell = PropertyStore.CreateKey(); + + internal const int STATE_CANOVERFLOW = 0x00000001; + internal const int STATE_ALLOWITEMREORDER = 0x00000002; + internal const int STATE_DISPOSINGITEMS = 0x00000004; + internal const int STATE_MENUAUTOEXPAND = 0x00000008; + internal const int STATE_MENUAUTOEXPANDDEFAULT = 0x00000010; + internal const int STATE_SCROLLBUTTONS = 0x00000020; + internal const int STATE_USEDEFAULTRENDERER = 0x00000040; + internal const int STATE_ALLOWMERGE = 0x00000080; + internal const int STATE_RAFTING = 0x00000100; + internal const int STATE_STRETCH = 0x00000200; + internal const int STATE_LOCATIONCHANGING = 0x00000400; + internal const int STATE_DRAGGING = 0x00000800; + internal const int STATE_HASVISIBLEITEMS = 0x00001000; + internal const int STATE_SUSPENDCAPTURE = 0x00002000; internal const int STATE_LASTMOUSEDOWNEDITEMCAPTURE = 0x00004000; - internal const int STATE_MENUACTIVE = 0x00008000; - + internal const int STATE_MENUACTIVE = 0x00008000; + #if DEBUG internal static readonly TraceSwitch SelectionDebug = new TraceSwitch("SelectionDebug", "Debug ToolStrip Selection code"); @@ -169,11 +170,14 @@ public class ToolStrip : System.Windows.Forms.ScrollableControl, /// /// Summary of ToolStrip. /// - public ToolStrip() { - if (DpiHelper.IsScalingRequired) { + public ToolStrip() + { + if (DpiHelper.IsScalingRequired) + { iconWidth = DpiHelper.LogicalToDeviceUnitsX(ICON_DIMENSION); iconHeight = DpiHelper.LogicalToDeviceUnitsY(ICON_DIMENSION); - if (DpiHelper.IsScalingRequirementMet) { + if (DpiHelper.IsScalingRequirementMet) + { insertionBeamWidth = DpiHelper.LogicalToDeviceUnitsX(INSERTION_BEAM_WIDTH); scaledDefaultPadding = DpiHelper.LogicalToDeviceUnits(defaultPadding); scaledDefaultGripMargin = DpiHelper.LogicalToDeviceUnits(defaultGripMargin); @@ -186,7 +190,7 @@ public ToolStrip() { this.TabStop = false; this.MenuAutoExpand = false; SetStyle(ControlStyles.OptimizedDoubleBuffer | - ControlStyles.AllPaintingInWmPaint | + ControlStyles.AllPaintingInWmPaint | ControlStyles.SupportsTransparentBackColor, true); SetStyle(ControlStyles.Selectable, false); @@ -206,31 +210,37 @@ public ToolStrip() { Size defaultSize = DefaultSize; SetAutoSizeMode(AutoSizeMode.GrowAndShrink); this.ShowItemToolTips = DefaultShowItemToolTips; - ResumeLayout(true); + ResumeLayout(true); } - public ToolStrip(params ToolStripItem[] items) : this() { + public ToolStrip(params ToolStripItem[] items) : this() + { Items.AddRange(items); } - internal ArrayList ActiveDropDowns { + internal ArrayList ActiveDropDowns + { get { return activeDropDowns; } } - + // returns true when entered into menu mode through this toolstrip/menustrip // this is only really supported for menustrip active event, but to prevent casting everywhere... - internal virtual bool KeyboardActive { + internal virtual bool KeyboardActive + { get { return GetToolStripState(STATE_MENUACTIVE); } - set { SetToolStripState(STATE_MENUACTIVE, value);} + set { SetToolStripState(STATE_MENUACTIVE, value); } } // This is only for use in determining whether to show scroll bars on // ToolStripDropDownMenus. No one else should be using it for anything. - internal virtual bool AllItemsVisible { - get { + internal virtual bool AllItemsVisible + { + get + { return true; } - set { + set + { // we do nothing in repsonse to a set, since we calculate the value above. } } @@ -238,12 +248,16 @@ internal virtual bool AllItemsVisible { [DefaultValue(true), Browsable(true), EditorBrowsable(EditorBrowsableState.Always), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible) ] - public override bool AutoSize { - get { + public override bool AutoSize + { + get + { return base.AutoSize; } - set { - if (IsInToolStripPanel && base.AutoSize && !value) { + set + { + if (IsInToolStripPanel && base.AutoSize && !value) + { // Restoring the bounds can change the location of the toolstrip - // which would join it to a new row. Set the specified bounds to the new location to // prevent this. @@ -270,11 +284,14 @@ public override bool AutoSize { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public override bool AutoScroll { - get { + public override bool AutoScroll + { + get + { return base.AutoScroll; } - set { + set + { throw new NotSupportedException(SR.ToolStripDoesntSupportAutoScroll); } } @@ -284,11 +301,14 @@ public override bool AutoScroll { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Size AutoScrollMargin { - get { + public new Size AutoScrollMargin + { + get + { return base.AutoScrollMargin; } - set { + set + { base.AutoScrollMargin = value; } } @@ -298,11 +318,14 @@ public override bool AutoScroll { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Size AutoScrollMinSize { - get { + public new Size AutoScrollMinSize + { + get + { return base.AutoScrollMinSize; } - set { + set + { base.AutoScrollMinSize = value; } } @@ -312,11 +335,14 @@ public override bool AutoScroll { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Point AutoScrollPosition { - get { + public new Point AutoScrollPosition + { + get + { return base.AutoScrollPosition; } - set { + set + { base.AutoScrollPosition = value; } } @@ -324,12 +350,16 @@ public override bool AutoScroll { /// /// Summary of AllowDrop. /// - public override bool AllowDrop { - get { + public override bool AllowDrop + { + get + { return base.AllowDrop; } - set { - if (value && AllowItemReorder) { + set + { + if (value && AllowItemReorder) + { throw new ArgumentException(SR.ToolStripAllowItemReorderAndAllowDropCannotBeSetToTrue); } @@ -338,11 +368,13 @@ public override bool AllowDrop { // - if (value) { - this.DropTargetManager.EnsureRegistered(this); + if (value) + { + this.DropTargetManager.EnsureRegistered(this); } - else { - this.DropTargetManager.EnsureUnRegistered(this); + else + { + this.DropTargetManager.EnsureUnRegistered(this); } } @@ -355,11 +387,15 @@ public override bool AllowDrop { SRDescription(nameof(SR.ToolStripAllowItemReorderDescr)), SRCategory(nameof(SR.CatBehavior)) ] - public bool AllowItemReorder { + public bool AllowItemReorder + { get { return GetToolStripState(STATE_ALLOWITEMREORDER); } - set { - if (GetToolStripState(STATE_ALLOWITEMREORDER) != value) { - if (AllowDrop && value) { + set + { + if (GetToolStripState(STATE_ALLOWITEMREORDER) != value) + { + if (AllowDrop && value) + { throw new ArgumentException(SR.ToolStripAllowItemReorderAndAllowDropCannotBeSetToTrue); } SetToolStripState(STATE_ALLOWITEMREORDER, value); @@ -367,15 +403,17 @@ public bool AllowItemReorder { // - if (value) { + if (value) + { ToolStripSplitStackDragDropHandler dragDropHandler = new ToolStripSplitStackDragDropHandler(this); - this.ItemReorderDropSource = dragDropHandler; - this.ItemReorderDropTarget = dragDropHandler; + this.ItemReorderDropSource = dragDropHandler; + this.ItemReorderDropTarget = dragDropHandler; this.DropTargetManager.EnsureRegistered(this); } - else { - this.DropTargetManager.EnsureUnRegistered(this); + else + { + this.DropTargetManager.EnsureUnRegistered(this); } } @@ -393,24 +431,31 @@ public bool AllowItemReorder { SRDescription(nameof(SR.ToolStripAllowMergeDescr)), SRCategory(nameof(SR.CatBehavior)) ] - public bool AllowMerge { + public bool AllowMerge + { get { return GetToolStripState(STATE_ALLOWMERGE); } - set { - if (GetToolStripState(STATE_ALLOWMERGE) != value) { + set + { + if (GetToolStripState(STATE_ALLOWMERGE) != value) + { SetToolStripState(STATE_ALLOWMERGE, value); } } } - - public override AnchorStyles Anchor { - get { + + public override AnchorStyles Anchor + { + get + { return base.Anchor; } - set { + set + { // the base calls SetDock, which causes an OnDockChanged to be called // which forces two layouts of the parent. - using (new LayoutTransaction(this, this, PropertyNames.Anchor)) { + using (new LayoutTransaction(this, this, PropertyNames.Anchor)) + { base.Anchor = value; } } @@ -423,24 +468,30 @@ public override AnchorStyles Anchor { SRDescription(nameof(SR.ToolStripBackColorDescr)), SRCategory(nameof(SR.CatAppearance)) ] - public new Color BackColor { - get { + public new Color BackColor + { + get + { return base.BackColor; } - set { + set + { base.BackColor = value; } } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ToolStripOnBeginDrag))] - public event EventHandler BeginDrag { + public event EventHandler BeginDrag + { add => Events.AddHandler(EventBeginDrag, value); remove => Events.RemoveHandler(EventBeginDrag, value); } - public override BindingContext BindingContext { - get { - BindingContext bc = (BindingContext) this.Properties.GetObject(PropBindingContext); + public override BindingContext BindingContext + { + get + { + BindingContext bc = (BindingContext)this.Properties.GetObject(PropBindingContext); if (bc != null) return bc; @@ -453,8 +504,10 @@ public override BindingContext BindingContext { // we don't have a binding context return null; } - set { - if (this.Properties.GetObject(PropBindingContext) != value) { + set + { + if (this.Properties.GetObject(PropBindingContext) != value) + { this.Properties.SetObject(PropBindingContext, value); // re-wire the bindings @@ -474,12 +527,16 @@ public override BindingContext BindingContext { SRDescription(nameof(SR.ToolStripCanOverflowDescr)), SRCategory(nameof(SR.CatLayout)) ] - public bool CanOverflow { - get { + public bool CanOverflow + { + get + { return GetToolStripState(STATE_CANOVERFLOW); } - set { - if (GetToolStripState(STATE_CANOVERFLOW) != value) { + set + { + if (GetToolStripState(STATE_CANOVERFLOW) != value) + { SetToolStripState(STATE_CANOVERFLOW, value); InvalidateLayout(); } @@ -491,13 +548,17 @@ public bool CanOverflow { /// SCENARIO: put focus in combo box, move the mouse over another item... selectioni /// should not shift until the combobox relinquishes its focus. /// - internal bool CanHotTrack { - get { - if (!Focused) { + internal bool CanHotTrack + { + get + { + if (!Focused) + { // if ContainsFocus in one of the children = false, someone is just mousing by, we can hot track return (ContainsFocus == false); } - else { + else + { // if the toolstrip itself contains focus we can definately hottrack. return true; } @@ -505,42 +566,49 @@ internal bool CanHotTrack { } - [ - Browsable(false), - DefaultValue(false), - ] - public new bool CausesValidation { - get { - // By default: CausesValidation is false for a ToolStrip - // we want people to be able to use menus without validating - // their controls. - return base.CausesValidation; - } - set { - base.CausesValidation = value; - } - } + [ + Browsable(false), + DefaultValue(false), + ] + public new bool CausesValidation + { + get + { + // By default: CausesValidation is false for a ToolStrip + // we want people to be able to use menus without validating + // their controls. + return base.CausesValidation; + } + set + { + base.CausesValidation = value; + } + } [Browsable(false)] - public new event EventHandler CausesValidationChanged { + public new event EventHandler CausesValidationChanged + { add => base.CausesValidationChanged += value; remove => base.CausesValidationChanged -= value; } [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public new Control.ControlCollection Controls { + public new Control.ControlCollection Controls + { get { return base.Controls; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event ControlEventHandler ControlAdded { + public new event ControlEventHandler ControlAdded + { add => base.ControlAdded += value; remove => base.ControlAdded -= value; } [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public override Cursor Cursor { + public override Cursor Cursor + { get { return base.Cursor; } set { base.Cursor = value; } } @@ -549,29 +617,36 @@ public override Cursor Cursor { /// Hide browsable property /// [Browsable(false)] - public new event EventHandler CursorChanged { + public new event EventHandler CursorChanged + { add => base.CursorChanged += value; remove => base.CursorChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event ControlEventHandler ControlRemoved { - add => base.ControlRemoved += value; - remove => base.ControlRemoved -= value; + public new event ControlEventHandler ControlRemoved + { + add => base.ControlRemoved += value; + remove => base.ControlRemoved -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ToolStripOnEndDrag))] - public event EventHandler EndDrag { + public event EventHandler EndDrag + { add => Events.AddHandler(EventEndDrag, value); remove => Events.RemoveHandler(EventEndDrag, value); } - public override Font Font { - get { - if (this.IsFontSet()) { + public override Font Font + { + get + { + if (this.IsFontSet()) + { return base.Font; } - if (defaultFont == null) { + if (defaultFont == null) + { // since toolstrip manager default font is thread static, hold onto a copy of the // pointer in an instance variable for perf so we dont have to keep fishing into // thread local storage for it. @@ -579,7 +654,8 @@ public override Font Font { } return defaultFont; } - set { + set + { base.Font = value; } } @@ -588,43 +664,56 @@ public override Font Font { /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(100, 25); } } - protected override Padding DefaultPadding { - get { + protected override Padding DefaultPadding + { + get + { // one pixel from the right edge to prevent the right border from painting over the // aligned-right toolstrip item. return scaledDefaultPadding; } } - protected override Padding DefaultMargin { + protected override Padding DefaultMargin + { get { return Padding.Empty; } } - - protected virtual DockStyle DefaultDock { - get { + + protected virtual DockStyle DefaultDock + { + get + { return DockStyle.Top; } } - protected virtual Padding DefaultGripMargin { - get { - if (toolStripGrip != null) { + protected virtual Padding DefaultGripMargin + { + get + { + if (toolStripGrip != null) + { return toolStripGrip.DefaultMargin; } - else { + else + { return scaledDefaultGripMargin; } } } - protected virtual bool DefaultShowItemToolTips { - get { + protected virtual bool DefaultShowItemToolTips + { + get + { return true; } } @@ -632,59 +721,71 @@ protected virtual bool DefaultShowItemToolTips { [Browsable(false)] [SRDescription(nameof(SR.ToolStripDefaultDropDownDirectionDescr))] [SRCategory(nameof(SR.CatBehavior))] - public virtual ToolStripDropDownDirection DefaultDropDownDirection { - get { + public virtual ToolStripDropDownDirection DefaultDropDownDirection + { + get + { ToolStripDropDownDirection direction = toolStripDropDownDirection; - if (direction == ToolStripDropDownDirection.Default) { - if (Orientation == Orientation.Vertical) { - if (IsInToolStripPanel) { + if (direction == ToolStripDropDownDirection.Default) + { + if (Orientation == Orientation.Vertical) + { + if (IsInToolStripPanel) + { // parent can be null when we're swapping between ToolStripPanels. DockStyle actualDock = (ParentInternal != null) ? ParentInternal.Dock : DockStyle.Left; direction = (actualDock == DockStyle.Right) ? ToolStripDropDownDirection.Left : ToolStripDropDownDirection.Right; if (DesignMode && actualDock == DockStyle.Left) { - direction = ToolStripDropDownDirection.Right ; + direction = ToolStripDropDownDirection.Right; } - - } - else { + + } + else + { direction = ((Dock == DockStyle.Right) && (RightToLeft == RightToLeft.No)) ? ToolStripDropDownDirection.Left : ToolStripDropDownDirection.Right; if (DesignMode && Dock == DockStyle.Left) { - direction = ToolStripDropDownDirection.Right ; + direction = ToolStripDropDownDirection.Right; } - } + } } - else { // horizontal - DockStyle dock = this.Dock; - if (IsInToolStripPanel && ParentInternal != null) { + else + { // horizontal + DockStyle dock = this.Dock; + if (IsInToolStripPanel && ParentInternal != null) + { dock = ParentInternal.Dock; // we want the orientation of the ToolStripPanel; - } - - if (dock == DockStyle.Bottom) { - direction = (RightToLeft == RightToLeft.Yes) ? ToolStripDropDownDirection.AboveLeft : ToolStripDropDownDirection.AboveRight; - } - else { - // assume Dock.Top - direction = (RightToLeft == RightToLeft.Yes) ? ToolStripDropDownDirection.BelowLeft : ToolStripDropDownDirection.BelowRight; - } + } + + if (dock == DockStyle.Bottom) + { + direction = (RightToLeft == RightToLeft.Yes) ? ToolStripDropDownDirection.AboveLeft : ToolStripDropDownDirection.AboveRight; + } + else + { + // assume Dock.Top + direction = (RightToLeft == RightToLeft.Yes) ? ToolStripDropDownDirection.BelowLeft : ToolStripDropDownDirection.BelowRight; + } } } return direction; } - set { + set + { // cant use Enum.IsValid as its not sequential - switch (value) { - case ToolStripDropDownDirection.AboveLeft: - case ToolStripDropDownDirection.AboveRight: - case ToolStripDropDownDirection.BelowLeft: - case ToolStripDropDownDirection.BelowRight: - case ToolStripDropDownDirection.Left: - case ToolStripDropDownDirection.Right: - case ToolStripDropDownDirection.Default: - break; - default: - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripDropDownDirection)); + switch (value) + { + case ToolStripDropDownDirection.AboveLeft: + case ToolStripDropDownDirection.AboveRight: + case ToolStripDropDownDirection.BelowLeft: + case ToolStripDropDownDirection.BelowRight: + case ToolStripDropDownDirection.Left: + case ToolStripDropDownDirection.Right: + case ToolStripDropDownDirection.Default: + break; + default: + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripDropDownDirection)); } toolStripDropDownDirection = value; @@ -694,14 +795,19 @@ public virtual ToolStripDropDownDirection DefaultDropDownDirection { /// Just here so we can add the default value attribute /// [DefaultValue(DockStyle.Top)] - public override DockStyle Dock { - get { + public override DockStyle Dock + { + get + { return base.Dock; } - set { - if (value != Dock) { + set + { + if (value != Dock) + { using (new LayoutTransaction(this, this, PropertyNames.Dock)) - using (new LayoutTransaction(this.ParentInternal, this, PropertyNames.Dock)) { + using (new LayoutTransaction(this.ParentInternal, this, PropertyNames.Dock)) + { // We don't call base.Dock = value, because that would cause us to get 2 LocationChanged events. // The first is when the parent gets a Layout due to the DockChange, and the second comes from when we // change the orientation. Instead we've duplicated the logic of Control.Dock.set here, but with a @@ -719,13 +825,17 @@ public override DockStyle Dock { /// Returns an owner window that can be used to /// own a drop down. /// - internal virtual NativeWindow DropDownOwnerWindow { - get { - if (dropDownOwnerWindow == null) { + internal virtual NativeWindow DropDownOwnerWindow + { + get + { + if (dropDownOwnerWindow == null) + { dropDownOwnerWindow = new NativeWindow(); } - if (dropDownOwnerWindow.Handle == IntPtr.Zero) { + if (dropDownOwnerWindow.Handle == IntPtr.Zero) + { CreateParams cp = new CreateParams(); cp.ExStyle = NativeMethods.WS_EX_TOOLWINDOW; dropDownOwnerWindow.CreateHandle(cp); @@ -740,15 +850,19 @@ internal virtual NativeWindow DropDownOwnerWindow { /// items and this ToolStrip share. this is necessary as /// RegisterDragDrop requires an HWND. /// - internal ToolStripDropTargetManager DropTargetManager { - get { - if (dropTargetManager == null) { + internal ToolStripDropTargetManager DropTargetManager + { + get + { + if (dropTargetManager == null) + { dropTargetManager = new ToolStripDropTargetManager(this); } return dropTargetManager; } - set { + set + { dropTargetManager = value; } @@ -756,9 +870,12 @@ internal ToolStripDropTargetManager DropTargetManager { /// /// Just here so we can add the default value attribute /// - protected internal virtual ToolStripItemCollection DisplayedItems { - get { - if (displayedItems == null) { + protected internal virtual ToolStripItemCollection DisplayedItems + { + get + { + if (displayedItems == null) + { displayedItems = new ToolStripItemCollection(this, false); } return displayedItems; @@ -774,21 +891,26 @@ protected internal virtual ToolStripItemCollection DisplayedItems { /// change during autoScroll. /// /// - public override Rectangle DisplayRectangle { + public override Rectangle DisplayRectangle + { [SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces")] - get { + get + { Rectangle rect = base.DisplayRectangle; - if ((LayoutEngine is ToolStripSplitStackLayout) && (GripStyle == ToolStripGripStyle.Visible)){ + if ((LayoutEngine is ToolStripSplitStackLayout) && (GripStyle == ToolStripGripStyle.Visible)) + { - if (Orientation == Orientation.Horizontal) { - int gripwidth = Grip.GripThickness + Grip.Margin.Horizontal; + if (Orientation == Orientation.Horizontal) + { + int gripwidth = Grip.GripThickness + Grip.Margin.Horizontal; rect.Width -= gripwidth; // in RTL.No we need to shift the rectangle rect.X += (RightToLeft == RightToLeft.No) ? gripwidth : 0; } - else { // Vertical Grip placement - int gripheight = Grip.GripThickness + Grip.Margin.Vertical; + else + { // Vertical Grip placement + int gripheight = Grip.GripThickness + Grip.Margin.Vertical; rect.Y += gripheight; rect.Height -= gripheight; } @@ -802,11 +924,14 @@ public override Rectangle DisplayRectangle { /// Forecolor really has no meaning for ToolStrips - so lets hide it /// [Browsable(false)] - public new Color ForeColor { - get { + public new Color ForeColor + { + get + { return base.ForeColor; } - set { + set + { base.ForeColor = value; } } @@ -823,8 +948,10 @@ public override Rectangle DisplayRectangle { remove => base.ForeColorChanged -= value; } - private bool HasKeyboardInput { - get { + private bool HasKeyboardInput + { + get + { return (ContainsFocus || (ToolStripManager.ModalMenuFilter.InMenuMode && ToolStripManager.ModalMenuFilter.GetActiveToolStrip() == this)); } } @@ -832,12 +959,15 @@ private bool HasKeyboardInput { /// /// Summary of ToolStripGrip. /// - internal ToolStripGrip Grip { - get { - if (toolStripGrip == null) { + internal ToolStripGrip Grip + { + get + { + if (toolStripGrip == null) + { toolStripGrip = new ToolStripGrip(); toolStripGrip.Overflow = ToolStripItemOverflow.Never; - toolStripGrip.Visible = toolStripGripStyle ==ToolStripGripStyle.Visible; + toolStripGrip.Visible = toolStripGripStyle == ToolStripGripStyle.Visible; toolStripGrip.AutoSize = false; toolStripGrip.ParentInternal = this; toolStripGrip.Margin = DefaultGripMargin; @@ -853,18 +983,23 @@ internal ToolStripGrip Grip { SRDescription(nameof(SR.ToolStripGripStyleDescr)), DefaultValue(ToolStripGripStyle.Visible) ] - public ToolStripGripStyle GripStyle { - get { + public ToolStripGripStyle GripStyle + { + get + { return toolStripGripStyle; } - set { + set + { //valid values are 0x0 to 0x1 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripGripStyle.Hidden, (int)ToolStripGripStyle.Visible)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripGripStyle.Hidden, (int)ToolStripGripStyle.Visible)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripGripStyle)); } - if (toolStripGripStyle != value) { + if (toolStripGripStyle != value) + { toolStripGripStyle = value; - Grip.Visible = toolStripGripStyle ==ToolStripGripStyle.Visible; + Grip.Visible = toolStripGripStyle == ToolStripGripStyle.Visible; LayoutTransaction.DoLayout(this, this, PropertyNames.GripStyle); } } @@ -877,8 +1012,10 @@ public ToolStripGripStyle GripStyle { [ Browsable(false) ] - public ToolStripGripDisplayStyle GripDisplayStyle { - get { + public ToolStripGripDisplayStyle GripDisplayStyle + { + get + { return (LayoutStyle == ToolStripLayoutStyle.HorizontalStackWithOverflow) ? ToolStripGripDisplayStyle.Vertical : ToolStripGripDisplayStyle.Horizontal; } @@ -891,11 +1028,14 @@ public ToolStripGripDisplayStyle GripDisplayStyle { SRCategory(nameof(SR.CatLayout)), SRDescription(nameof(SR.ToolStripGripDisplayStyleDescr)) ] - public Padding GripMargin { - get { + public Padding GripMargin + { + get + { return Grip.Margin; } - set { + set + { Grip.Margin = value; } } @@ -906,8 +1046,10 @@ public Padding GripMargin { [ Browsable(false) ] - public Rectangle GripRectangle { - get { + public Rectangle GripRectangle + { + get + { return (GripStyle == ToolStripGripStyle.Visible) ? Grip.Bounds : Rectangle.Empty; } } @@ -916,17 +1058,24 @@ public Rectangle GripRectangle { Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new bool HasChildren { - get { + public new bool HasChildren + { + get + { return base.HasChildren; } } - internal bool HasVisibleItems { - get { - if (!IsHandleCreated) { - foreach(ToolStripItem item in Items) { - if (((IArrangedElement)item).ParticipatesInLayout) { + internal bool HasVisibleItems + { + get + { + if (!IsHandleCreated) + { + foreach (ToolStripItem item in Items) + { + if (((IArrangedElement)item).ParticipatesInLayout) + { // set in the state so that when the handle is created, we're accurate. SetToolStripState(STATE_HASVISIBLEITEMS, true); return true; @@ -938,7 +1087,8 @@ internal bool HasVisibleItems { // after the handle is created, we start layout... so this state is cached. return GetToolStripState(STATE_HASVISIBLEITEMS); } - set { + set + { SetToolStripState(STATE_HASVISIBLEITEMS, value); } } @@ -962,28 +1112,36 @@ internal bool HasVisibleItems { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripImageScalingSizeDescr)), ] - public Size ImageScalingSize { - get { + public Size ImageScalingSize + { + get + { return ImageScalingSizeInternal; } - set { - ImageScalingSizeInternal = value; + set + { + ImageScalingSizeInternal = value; } } - internal virtual Size ImageScalingSizeInternal { - get { + internal virtual Size ImageScalingSizeInternal + { + get + { return imageScalingSize; } - set { - if (imageScalingSize != value) { + set + { + if (imageScalingSize != value) + { imageScalingSize = value; LayoutTransaction.DoLayoutIf((Items.Count > 0), this, this, PropertyNames.ImageScalingSize); - foreach (ToolStripItem item in this.Items) { + foreach (ToolStripItem item in this.Items) + { item.OnImageScalingSizeChanged(EventArgs.Empty); - } - } + } + } } } @@ -998,17 +1156,22 @@ internal virtual Size ImageScalingSizeInternal { SRDescription(nameof(SR.ToolStripImageListDescr)), Browsable(false) ] - public ImageList ImageList { - get { + public ImageList ImageList + { + get + { return imageList; } - set { - if (imageList != value) { + set + { + if (imageList != value) + { EventHandler handler = new EventHandler(ImageListRecreateHandle); // Remove the previous imagelist handle recreate handler // - if (imageList != null) { + if (imageList != null) + { imageList.RecreateHandle -= handler; } @@ -1016,11 +1179,13 @@ public ImageList ImageList { // Add the new imagelist handle recreate handler // - if (value != null) { + if (value != null) + { value.RecreateHandle += handler; } - foreach (ToolStripItem item in Items) { + foreach (ToolStripItem item in Items) + { item.InvalidateImageListImage(); } Invalidate(); @@ -1033,13 +1198,16 @@ public ImageList ImageList { /// internal override bool IsMnemonicsListenerAxSourced { - get{ + get + { return true; } } - internal bool IsInToolStripPanel { - get { + internal bool IsInToolStripPanel + { + get + { return ToolStripPanelRow != null; } @@ -1050,8 +1218,10 @@ internal bool IsInToolStripPanel { /// to another /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public bool IsCurrentlyDragging { - get { + public bool IsCurrentlyDragging + { + get + { return GetToolStripState(STATE_DRAGGING); } } @@ -1060,8 +1230,10 @@ public bool IsCurrentlyDragging { /// /// indicates if the SetBoundsCore is called thru Locationchanging. /// - private bool IsLocationChanging { - get { + private bool IsLocationChanging + { + get + { return GetToolStripState(STATE_LOCATIONCHANGING); } } @@ -1082,9 +1254,12 @@ private bool IsLocationChanging { SRDescription(nameof(SR.ToolStripItemsDescr)), MergableProperty(false) ] - public virtual ToolStripItemCollection Items { - get { - if (toolStripItemCollection == null) { + public virtual ToolStripItemCollection Items + { + get + { + if (toolStripItemCollection == null) + { toolStripItemCollection = new ToolStripItemCollection(this, true); } return toolStripItemCollection; @@ -1093,9 +1268,10 @@ public virtual ToolStripItemCollection Items { [SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripItemAddedDescr))] - public event ToolStripItemEventHandler ItemAdded { - add => Events.AddHandler(EventItemAdded, value); - remove => Events.RemoveHandler(EventItemAdded, value); + public event ToolStripItemEventHandler ItemAdded + { + add => Events.AddHandler(EventItemAdded, value); + remove => Events.RemoveHandler(EventItemAdded, value); } @@ -1103,7 +1279,8 @@ public event ToolStripItemEventHandler ItemAdded { /// Occurs when the control is clicked. /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ToolStripItemOnClickDescr))] - public event ToolStripItemClickedEventHandler ItemClicked { + public event ToolStripItemClickedEventHandler ItemClicked + { add => Events.AddHandler(EventItemClicked, value); remove => Events.RemoveHandler(EventItemClicked, value); } @@ -1123,9 +1300,12 @@ public event ToolStripItemClickedEventHandler ItemClicked { /// because you need to allocate GDI+ Graphics objects for every single item. This method allows us to only /// allocate 1 Graphics object and share it between all the items in OnPaint. /// - private CachedItemHdcInfo ItemHdcInfo { - get { - if (cachedItemHdcInfo == null) { + private CachedItemHdcInfo ItemHdcInfo + { + get + { + if (cachedItemHdcInfo == null) + { cachedItemHdcInfo = new CachedItemHdcInfo(); } return cachedItemHdcInfo; @@ -1133,18 +1313,22 @@ private CachedItemHdcInfo ItemHdcInfo { } [SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripItemRemovedDescr))] - public event ToolStripItemEventHandler ItemRemoved { - add => Events.AddHandler(EventItemRemoved, value); - remove => Events.RemoveHandler(EventItemRemoved, value); + public event ToolStripItemEventHandler ItemRemoved + { + add => Events.AddHandler(EventItemRemoved, value); + remove => Events.RemoveHandler(EventItemRemoved, value); } /// handy check for painting and sizing [Browsable(false)] - public bool IsDropDown { + public bool IsDropDown + { get { return (this is ToolStripDropDown); } } - internal bool IsDisposingItems { - get { + internal bool IsDisposingItems + { + get + { return GetToolStripState(STATE_DISPOSINGITEMS); } } @@ -1154,11 +1338,14 @@ internal bool IsDisposingItems { /// This allows us to have methods that handle drag/drop of the ToolStrip items /// without calling back on the user's code /// - internal IDropTarget ItemReorderDropTarget { - get { + internal IDropTarget ItemReorderDropTarget + { + get + { return itemReorderDropTarget; } - set { + set + { itemReorderDropTarget = value; } } @@ -1170,33 +1357,42 @@ internal IDropTarget ItemReorderDropTarget { /// This allows us to have methods that handle drag/drop of the ToolStrip items /// without calling back on the user's code /// - internal ISupportOleDropSource ItemReorderDropSource { - get { + internal ISupportOleDropSource ItemReorderDropSource + { + get + { return itemReorderDropSource; } - set { + set + { itemReorderDropSource = value; } } - internal bool IsInDesignMode { - get { + internal bool IsInDesignMode + { + get + { return DesignMode; } } - internal bool IsSelectionSuspended { + internal bool IsSelectionSuspended + { get { return GetToolStripState(STATE_LASTMOUSEDOWNEDITEMCAPTURE); } } - internal ToolStripItem LastMouseDownedItem { - get { - if (lastMouseDownedItem != null && - (lastMouseDownedItem.IsDisposed || lastMouseDownedItem.ParentInternal != this)){ + internal ToolStripItem LastMouseDownedItem + { + get + { + if (lastMouseDownedItem != null && + (lastMouseDownedItem.IsDisposed || lastMouseDownedItem.ParentInternal != this)) + { // handle disposal, parent changed since we last mouse downed. lastMouseDownedItem = null; } - return lastMouseDownedItem; + return lastMouseDownedItem; } } @@ -1206,11 +1402,14 @@ internal ToolStripItem LastMouseDownedItem { Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public LayoutSettings LayoutSettings { - get { + public LayoutSettings LayoutSettings + { + get + { return layoutSettings; } - set { + set + { layoutSettings = value; } } @@ -1224,10 +1423,14 @@ public LayoutSettings LayoutSettings { SRCategory(nameof(SR.CatLayout)), AmbientValue(ToolStripLayoutStyle.StackWithOverflow) ] - public ToolStripLayoutStyle LayoutStyle { - get { - if (layoutStyle == ToolStripLayoutStyle.StackWithOverflow) { - switch (this.Orientation) { + public ToolStripLayoutStyle LayoutStyle + { + get + { + if (layoutStyle == ToolStripLayoutStyle.StackWithOverflow) + { + switch (this.Orientation) + { case Orientation.Horizontal: return ToolStripLayoutStyle.HorizontalStackWithOverflow; case Orientation.Vertical: @@ -1236,17 +1439,22 @@ public ToolStripLayoutStyle LayoutStyle { } return layoutStyle; } - set { + set + { //valid values are 0x0 to 0x4 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripLayoutStyle.StackWithOverflow, (int)ToolStripLayoutStyle.Table)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripLayoutStyle.StackWithOverflow, (int)ToolStripLayoutStyle.Table)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripLayoutStyle)); } - if (layoutStyle != value) { + if (layoutStyle != value) + { layoutStyle = value; - switch (value) { + switch (value) + { case ToolStripLayoutStyle.Flow: - if (!(layoutEngine is FlowLayout)) { + if (!(layoutEngine is FlowLayout)) + { layoutEngine = FlowLayout.Instance; } // Orientation really only applies to split stack layout (which swaps based on Dock, ToolStripPanel location) @@ -1254,7 +1462,8 @@ public ToolStripLayoutStyle LayoutStyle { break; case ToolStripLayoutStyle.Table: - if (!(layoutEngine is TableLayout)) { + if (!(layoutEngine is TableLayout)) + { layoutEngine = TableLayout.Instance; } // Orientation really only applies to split stack layout (which swaps based on Dock, ToolStripPanel location) @@ -1265,24 +1474,30 @@ public ToolStripLayoutStyle LayoutStyle { case ToolStripLayoutStyle.VerticalStackWithOverflow: default: - if (value != ToolStripLayoutStyle.StackWithOverflow) { + if (value != ToolStripLayoutStyle.StackWithOverflow) + { UpdateOrientation((value == ToolStripLayoutStyle.VerticalStackWithOverflow) ? Orientation.Vertical : Orientation.Horizontal); } - else { - if (IsInToolStripPanel) { + else + { + if (IsInToolStripPanel) + { UpdateLayoutStyle(ToolStripPanelRow.Orientation); } - else { + else + { UpdateLayoutStyle(this.Dock); } } - if (!(layoutEngine is ToolStripSplitStackLayout)) { + if (!(layoutEngine is ToolStripSplitStackLayout)) + { layoutEngine = new ToolStripSplitStackLayout(this); } break; } - using (LayoutTransaction.CreateTransactionIf(IsHandleCreated, this, this, PropertyNames.LayoutStyle)) { + using (LayoutTransaction.CreateTransactionIf(IsHandleCreated, this, this, PropertyNames.LayoutStyle)) + { LayoutSettings = CreateLayoutSettings(layoutStyle); } OnLayoutStyleChanged(EventArgs.Empty); @@ -1290,51 +1505,66 @@ public ToolStripLayoutStyle LayoutStyle { } } [SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripLayoutCompleteDescr))] - public event EventHandler LayoutCompleted { + public event EventHandler LayoutCompleted + { add => Events.AddHandler(EventLayoutCompleted, value); remove => Events.RemoveHandler(EventLayoutCompleted, value); } - internal bool LayoutRequired { - get { + internal bool LayoutRequired + { + get + { return this.layoutRequired; } - set { + set + { this.layoutRequired = value; } } [SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripLayoutStyleChangedDescr))] - public event EventHandler LayoutStyleChanged { + public event EventHandler LayoutStyleChanged + { add => Events.AddHandler(EventLayoutStyleChanged, value); remove => Events.RemoveHandler(EventLayoutStyleChanged, value); } - public override LayoutEngine LayoutEngine { - get { - // - return layoutEngine; - } + public override LayoutEngine LayoutEngine + { + get + { + // + return layoutEngine; + } } - internal event ToolStripLocationCancelEventHandler LocationChanging { + internal event ToolStripLocationCancelEventHandler LocationChanging + { add => Events.AddHandler(EventLocationChanging, value); remove => Events.RemoveHandler(EventLocationChanging, value); } - protected internal virtual Size MaxItemSize { - get { - return this.DisplayRectangle.Size; + protected internal virtual Size MaxItemSize + { + get + { + return this.DisplayRectangle.Size; } } - internal bool MenuAutoExpand { - get { - if (!DesignMode) { - if (GetToolStripState(STATE_MENUAUTOEXPAND)) { - if (!IsDropDown && !ToolStripManager.ModalMenuFilter.InMenuMode) { + internal bool MenuAutoExpand + { + get + { + if (!DesignMode) + { + if (GetToolStripState(STATE_MENUAUTOEXPAND)) + { + if (!IsDropDown && !ToolStripManager.ModalMenuFilter.InMenuMode) + { SetToolStripState(STATE_MENUAUTOEXPAND, false); return false; } @@ -1344,41 +1574,52 @@ internal bool MenuAutoExpand { return false; } - set { - if (!DesignMode) { + set + { + if (!DesignMode) + { SetToolStripState(STATE_MENUAUTOEXPAND, value); } } } - internal Stack MergeHistoryStack { - get { - if(mergeHistoryStack == null) { + internal Stack MergeHistoryStack + { + get + { + if (mergeHistoryStack == null) + { mergeHistoryStack = new Stack(); } return mergeHistoryStack; } } - - private MouseHoverTimer MouseHoverTimer { - get { - if (mouseHoverTimer == null) { + + private MouseHoverTimer MouseHoverTimer + { + get + { + if (mouseHoverTimer == null) + { mouseHoverTimer = new MouseHoverTimer(); } return mouseHoverTimer; } } - + /// /// Summary of OverflowButton. /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - public ToolStripOverflowButton OverflowButton { - get { - if (toolStripOverflowButton == null) { + public ToolStripOverflowButton OverflowButton + { + get + { + if (toolStripOverflowButton == null) + { toolStripOverflowButton = new ToolStripOverflowButton(this); toolStripOverflowButton.Overflow = ToolStripItemOverflow.Never; toolStripOverflowButton.ParentInternal = this; @@ -1393,9 +1634,12 @@ public ToolStripOverflowButton OverflowButton { // - internal ToolStripItemCollection OverflowItems { - get { - if (overflowItems == null) { + internal ToolStripItemCollection OverflowItems + { + get + { + if (overflowItems == null) + { overflowItems = new ToolStripItemCollection(this, false); } return overflowItems; @@ -1403,87 +1647,110 @@ internal ToolStripItemCollection OverflowItems { } [Browsable(false)] - public Orientation Orientation { - get { + public Orientation Orientation + { + get + { return orientation; } } [SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripPaintGripDescr))] - public event PaintEventHandler PaintGrip { + public event PaintEventHandler PaintGrip + { add => Events.AddHandler(EventPaintGrip, value); remove => Events.RemoveHandler(EventPaintGrip, value); } - internal RestoreFocusMessageFilter RestoreFocusFilter { - get { - if (restoreFocusFilter == null) { + internal RestoreFocusMessageFilter RestoreFocusFilter + { + get + { + if (restoreFocusFilter == null) + { restoreFocusFilter = new RestoreFocusMessageFilter(this); } return restoreFocusFilter; } } - internal ToolStripPanelCell ToolStripPanelCell { + internal ToolStripPanelCell ToolStripPanelCell + { get { return ((ISupportToolStripPanel)this).ToolStripPanelCell; } } - internal ToolStripPanelRow ToolStripPanelRow { + internal ToolStripPanelRow ToolStripPanelRow + { get { return ((ISupportToolStripPanel)this).ToolStripPanelRow; } } // fetches the Cell associated with this toolstrip. - ToolStripPanelCell ISupportToolStripPanel.ToolStripPanelCell { - get { + ToolStripPanelCell ISupportToolStripPanel.ToolStripPanelCell + { + get + { ToolStripPanelCell toolStripPanelCell = null; - if (!IsDropDown && !IsDisposed) { - if (Properties.ContainsObject(ToolStrip.PropToolStripPanelCell)) { + if (!IsDropDown && !IsDisposed) + { + if (Properties.ContainsObject(ToolStrip.PropToolStripPanelCell)) + { toolStripPanelCell = (ToolStripPanelCell)Properties.GetObject(ToolStrip.PropToolStripPanelCell); } - else { + else + { toolStripPanelCell = new ToolStripPanelCell(this); Properties.SetObject(ToolStrip.PropToolStripPanelCell, toolStripPanelCell); } } return toolStripPanelCell; - } + } } - - ToolStripPanelRow ISupportToolStripPanel.ToolStripPanelRow { - get { + + ToolStripPanelRow ISupportToolStripPanel.ToolStripPanelRow + { + get + { ToolStripPanelCell cell = ToolStripPanelCell; - if (cell == null) { + if (cell == null) + { return null; } return ToolStripPanelCell.ToolStripPanelRow; } - set { + set + { ToolStripPanelRow oldToolStripPanelRow = ToolStripPanelRow; - - if (oldToolStripPanelRow != value) { + + if (oldToolStripPanelRow != value) + { ToolStripPanelCell cell = ToolStripPanelCell; - if (cell == null) { + if (cell == null) + { return; } cell.ToolStripPanelRow = value; - if (value != null) { - if (oldToolStripPanelRow == null || oldToolStripPanelRow.Orientation != value.Orientation) { - if (layoutStyle == ToolStripLayoutStyle.StackWithOverflow) - { - UpdateLayoutStyle(value.Orientation); - } - else - { - UpdateOrientation(value.Orientation); - } - - } + if (value != null) + { + if (oldToolStripPanelRow == null || oldToolStripPanelRow.Orientation != value.Orientation) + { + if (layoutStyle == ToolStripLayoutStyle.StackWithOverflow) + { + UpdateLayoutStyle(value.Orientation); + } + else + { + UpdateOrientation(value.Orientation); + } + + } } - else { - if (oldToolStripPanelRow != null && oldToolStripPanelRow.ControlsInternal.Contains(this)) { + else + { + if (oldToolStripPanelRow != null && oldToolStripPanelRow.ControlsInternal.Contains(this)) + { oldToolStripPanelRow.ControlsInternal.Remove(this); } UpdateLayoutStyle(Dock); @@ -1498,13 +1765,17 @@ ToolStripPanelRow ISupportToolStripPanel.ToolStripPanelRow { [DefaultValue(false)] [SRCategory(nameof(SR.CatLayout))] [SRDescription(nameof(SR.ToolStripStretchDescr))] - public bool Stretch { - get { + public bool Stretch + { + get + { return GetToolStripState(STATE_STRETCH); } - set { - if (Stretch != value) { - SetToolStripState(STATE_STRETCH,value); + set + { + if (Stretch != value) + { + SetToolStripState(STATE_STRETCH, value); } } } @@ -1520,35 +1791,44 @@ public bool Stretch { [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] - public ToolStripRenderer Renderer { - get { - - if (IsDropDown) { + public ToolStripRenderer Renderer + { + get + { + + if (IsDropDown) + { // PERF: since this is called a lot we dont want to make it virtual ToolStripDropDown dropDown = this as ToolStripDropDown; - if (dropDown is ToolStripOverflow || dropDown.IsAutoGenerated) { - if (dropDown.OwnerToolStrip != null) { + if (dropDown is ToolStripOverflow || dropDown.IsAutoGenerated) + { + if (dropDown.OwnerToolStrip != null) + { return dropDown.OwnerToolStrip.Renderer; } } } - if (RenderMode == ToolStripRenderMode.ManagerRenderMode) { + if (RenderMode == ToolStripRenderMode.ManagerRenderMode) + { return ToolStripManager.Renderer; } // always return a valid renderer so our paint code // doesn't have to be bogged down by checks for null. SetToolStripState(STATE_USEDEFAULTRENDERER, false); - if (renderer == null) { + if (renderer == null) + { Renderer = ToolStripManager.CreateRenderer(RenderMode); } return renderer; } - set { + set + { // if the value happens to be null, the next get // will autogenerate a new ToolStripRenderer. - if (renderer != value) { + if (renderer != value) + { SetToolStripState(STATE_USEDEFAULTRENDERER, (value == null)); renderer = value; currentRendererType = (renderer != null) ? renderer.GetType() : typeof(System.Type); @@ -1558,55 +1838,68 @@ public ToolStripRenderer Renderer { } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] - public event EventHandler RendererChanged { + public event EventHandler RendererChanged + { add => Events.AddHandler(EventRendererChanged, value); remove => Events.RemoveHandler(EventRendererChanged, value); } - [ - SRDescription(nameof(SR.ToolStripRenderModeDescr)), - SRCategory(nameof(SR.CatAppearance)), - ] - public ToolStripRenderMode RenderMode { - get { - if (GetToolStripState(STATE_USEDEFAULTRENDERER)) { + [ + SRDescription(nameof(SR.ToolStripRenderModeDescr)), + SRCategory(nameof(SR.CatAppearance)), + ] + public ToolStripRenderMode RenderMode + { + get + { + if (GetToolStripState(STATE_USEDEFAULTRENDERER)) + { return ToolStripRenderMode.ManagerRenderMode; - } - if (renderer != null && !renderer.IsAutoGenerated) { + } + if (renderer != null && !renderer.IsAutoGenerated) + { return ToolStripRenderMode.Custom; - } - // check the type of the currently set renderer. - // types are cached as this may be called frequently. - if (currentRendererType == ToolStripManager.ProfessionalRendererType) { - return ToolStripRenderMode.Professional; - } - if (currentRendererType == ToolStripManager.SystemRendererType) { - return ToolStripRenderMode.System; - } - return ToolStripRenderMode.Custom; - - } - set { - //valid values are 0x0 to 0x3 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripRenderMode.Custom, (int)ToolStripRenderMode.ManagerRenderMode)){ - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripRenderMode)); - } - if (value == ToolStripRenderMode.Custom) { - throw new NotSupportedException(SR.ToolStripRenderModeUseRendererPropertyInstead); - } - - if (value == ToolStripRenderMode.ManagerRenderMode) { - if (!GetToolStripState(STATE_USEDEFAULTRENDERER)) { - SetToolStripState(STATE_USEDEFAULTRENDERER, true); - OnRendererChanged(EventArgs.Empty); - } - } - else { + } + // check the type of the currently set renderer. + // types are cached as this may be called frequently. + if (currentRendererType == ToolStripManager.ProfessionalRendererType) + { + return ToolStripRenderMode.Professional; + } + if (currentRendererType == ToolStripManager.SystemRendererType) + { + return ToolStripRenderMode.System; + } + return ToolStripRenderMode.Custom; + + } + set + { + //valid values are 0x0 to 0x3 + if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripRenderMode.Custom, (int)ToolStripRenderMode.ManagerRenderMode)) + { + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripRenderMode)); + } + if (value == ToolStripRenderMode.Custom) + { + throw new NotSupportedException(SR.ToolStripRenderModeUseRendererPropertyInstead); + } + + if (value == ToolStripRenderMode.ManagerRenderMode) + { + if (!GetToolStripState(STATE_USEDEFAULTRENDERER)) + { + SetToolStripState(STATE_USEDEFAULTRENDERER, true); + OnRendererChanged(EventArgs.Empty); + } + } + else + { SetToolStripState(STATE_USEDEFAULTRENDERER, false); Renderer = ToolStripManager.CreateRenderer(value); - } - } - } + } + } + } /// @@ -1614,8 +1907,10 @@ public ToolStripRenderMode RenderMode { /// for their accelerators. Since they are not HWNDs, and this method is protected on control /// we need a way for them to get at it. /// - internal bool ShowKeyboardCuesInternal { - get { + internal bool ShowKeyboardCuesInternal + { + get + { return this.ShowKeyboardCues; } @@ -1625,30 +1920,39 @@ internal bool ShowKeyboardCuesInternal { [DefaultValue(true)] [SRDescription(nameof(SR.ToolStripShowItemToolTipsDescr))] [SRCategory(nameof(SR.CatBehavior))] - public bool ShowItemToolTips { - get { + public bool ShowItemToolTips + { + get + { return showItemToolTips; } - set { - if (showItemToolTips != value) { + set + { + if (showItemToolTips != value) + { showItemToolTips = value; - if (!showItemToolTips) { + if (!showItemToolTips) + { UpdateToolTip(null); } ToolTip internalToolTip = this.ToolTip; - foreach (ToolStripItem item in this.Items) { - if (showItemToolTips) { + foreach (ToolStripItem item in this.Items) + { + if (showItemToolTips) + { KeyboardToolTipStateMachine.Instance.Hook(item, internalToolTip); } - else { + else + { KeyboardToolTipStateMachine.Instance.Unhook(item, internalToolTip); } } // If the overflow button has not been created, don't check its properties // since this will force its creating and cause a re-layout of the control - if (toolStripOverflowButton != null && this.OverflowButton.HasDropDownItems) { + if (toolStripOverflowButton != null && this.OverflowButton.HasDropDownItems) + { this.OverflowButton.DropDown.ShowItemToolTips = value; } } @@ -1656,9 +1960,12 @@ public bool ShowItemToolTips { } /// internal lookup table for shortcuts... intended to speed search time - internal Hashtable Shortcuts { - get { - if (shortcuts == null) { + internal Hashtable Shortcuts + { + get + { + if (shortcuts == null) + { shortcuts = new Hashtable(1); } return shortcuts; @@ -1675,11 +1982,14 @@ internal Hashtable Shortcuts { DispId(NativeMethods.ActiveX.DISPID_TABSTOP), SRDescription(nameof(SR.ControlTabStopDescr)) ] - public new bool TabStop { - get { + public new bool TabStop + { + get + { return base.TabStop; } - set { + set + { base.TabStop = value; } } @@ -1688,14 +1998,18 @@ internal Hashtable Shortcuts { /// this is the ToolTip used for the individual items /// it only works if ShowItemToolTips = true /// - internal ToolTip ToolTip { - get { + internal ToolTip ToolTip + { + get + { ToolTip toolTip; - if (!Properties.ContainsObject(ToolStrip.PropToolTip)) { + if (!Properties.ContainsObject(ToolStrip.PropToolTip)) + { toolTip = new ToolTip(); - Properties.SetObject(ToolStrip.PropToolTip,toolTip ); + Properties.SetObject(ToolStrip.PropToolTip, toolTip); } - else { + else + { toolTip = (ToolTip)Properties.GetObject(ToolStrip.PropToolTip); } return toolTip; @@ -1707,28 +2021,36 @@ internal ToolTip ToolTip { SRDescription(nameof(SR.ToolStripTextDirectionDescr)), SRCategory(nameof(SR.CatAppearance)) ] - public virtual ToolStripTextDirection TextDirection { - get { + public virtual ToolStripTextDirection TextDirection + { + get + { ToolStripTextDirection textDirection = ToolStripTextDirection.Inherit; - if (Properties.ContainsObject(ToolStrip.PropTextDirection)) { - textDirection= (ToolStripTextDirection)Properties.GetObject(ToolStrip.PropTextDirection); + if (Properties.ContainsObject(ToolStrip.PropTextDirection)) + { + textDirection = (ToolStripTextDirection)Properties.GetObject(ToolStrip.PropTextDirection); } - if (textDirection == ToolStripTextDirection.Inherit) { + if (textDirection == ToolStripTextDirection.Inherit) + { textDirection = ToolStripTextDirection.Horizontal; } return textDirection; } - set { + set + { //valid values are 0x0 to 0x3 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripTextDirection.Inherit, (int)ToolStripTextDirection.Vertical270)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripTextDirection.Inherit, (int)ToolStripTextDirection.Vertical270)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripTextDirection)); } Properties.SetObject(ToolStrip.PropTextDirection, value); - using(new LayoutTransaction(this, this, "TextDirection")) { - for (int i = 0; i < Items.Count; i++) { + using (new LayoutTransaction(this, this, "TextDirection")) + { + for (int i = 0; i < Items.Count; i++) + { Items[i].OnOwnerTextDirectionChanged(); } } @@ -1750,28 +2072,35 @@ public virtual ToolStripTextDirection TextDirection { } } - void ISupportToolStripPanel.BeginDrag() { + void ISupportToolStripPanel.BeginDrag() + { OnBeginDrag(EventArgs.Empty); } // Internal so that it's not a public API. - internal virtual void ChangeSelection(ToolStripItem nextItem) { + internal virtual void ChangeSelection(ToolStripItem nextItem) + { - if (nextItem != null) { + if (nextItem != null) + { ToolStripControlHost controlHost = nextItem as ToolStripControlHost; // if we contain focus, we should set focus to ourselves // so we get the focus off the thing that's currently focused // e.g. go from a text box to a toolstrip button - if (ContainsFocus && !Focused) { + if (ContainsFocus && !Focused) + { this.Focus(); - if (controlHost == null) { + if (controlHost == null) + { // if nextItem IS a toolstripcontrolhost, we're going to focus it anyways // we only fire KeyboardActive when "focusing" a non-hwnd backed item KeyboardActive = true; } } - if (controlHost != null) { - if (hwndThatLostFocus == IntPtr.Zero) { + if (controlHost != null) + { + if (hwndThatLostFocus == IntPtr.Zero) + { SnapFocus(UnsafeNativeMethods.GetFocus()); } controlHost.Control.Select(); @@ -1782,17 +2111,20 @@ internal virtual void ChangeSelection(ToolStripItem nextItem) { nextItem.Select(); ToolStripMenuItem tsNextItem = nextItem as ToolStripMenuItem; - if (tsNextItem != null && !IsDropDown) { - // only toplevel menus auto expand when the selection changes. - tsNextItem.HandleAutoExpansion(); + if (tsNextItem != null && !IsDropDown) + { + // only toplevel menus auto expand when the selection changes. + tsNextItem.HandleAutoExpansion(); } - } + } } - protected virtual LayoutSettings CreateLayoutSettings(ToolStripLayoutStyle layoutStyle) { - switch (layoutStyle) { + protected virtual LayoutSettings CreateLayoutSettings(ToolStripLayoutStyle layoutStyle) + { + switch (layoutStyle) + { case ToolStripLayoutStyle.Flow: return new FlowLayoutSettings(this); case ToolStripLayoutStyle.Table: @@ -1802,12 +2134,15 @@ protected virtual LayoutSettings CreateLayoutSettings(ToolStripLayoutStyle layou } } - protected internal virtual ToolStripItem CreateDefaultItem(string text, Image image, EventHandler onClick) { - if (text == "-") { + protected internal virtual ToolStripItem CreateDefaultItem(string text, Image image, EventHandler onClick) + { + if (text == "-") + { return new ToolStripSeparator(); } - else { - return new ToolStripButton(text,image,onClick); + else + { + return new ToolStripButton(text, image, onClick); } } @@ -1815,7 +2150,8 @@ protected internal virtual ToolStripItem CreateDefaultItem(string text, Image im /// /// Summary of ClearAllSelections. /// - private void ClearAllSelections() { + private void ClearAllSelections() + { ClearAllSelectionsExcept(null); } @@ -1823,35 +2159,44 @@ private void ClearAllSelections() { /// Summary of ClearAllSelectionsExcept. /// /// - private void ClearAllSelectionsExcept(ToolStripItem item) { + private void ClearAllSelectionsExcept(ToolStripItem item) + { Rectangle regionRect = (item == null) ? Rectangle.Empty : item.Bounds; Region region = null; - try { + try + { - for (int i = 0; i < DisplayedItems.Count; i++) { - if (DisplayedItems[i] == item) { + for (int i = 0; i < DisplayedItems.Count; i++) + { + if (DisplayedItems[i] == item) + { continue; } - else if (item != null && DisplayedItems[i].Pressed) { + else if (item != null && DisplayedItems[i].Pressed) + { // - ToolStripDropDownItem dropDownItem = DisplayedItems[i] as ToolStripDropDownItem; + ToolStripDropDownItem dropDownItem = DisplayedItems[i] as ToolStripDropDownItem; - if (dropDownItem != null && dropDownItem.HasDropDownItems) { + if (dropDownItem != null && dropDownItem.HasDropDownItems) + { dropDownItem.AutoHide(item); - } + } } bool invalidate = false; - if (DisplayedItems[i].Selected) { + if (DisplayedItems[i].Selected) + { DisplayedItems[i].Unselect(); - Debug.WriteLineIf(SelectionDebug.TraceVerbose,"[SelectDBG ClearAllSelectionsExcept] Unselecting " + DisplayedItems[i].Text); + Debug.WriteLineIf(SelectionDebug.TraceVerbose, "[SelectDBG ClearAllSelectionsExcept] Unselecting " + DisplayedItems[i].Text); invalidate = true; } - if (invalidate) { + if (invalidate) + { // since regions are heavy weight - only use if we need it. - if (region == null) { + if (region == null) + { region = new Region(regionRect); } region.Union(DisplayedItems[i].Bounds); @@ -1859,30 +2204,37 @@ private void ClearAllSelectionsExcept(ToolStripItem item) { } // force an WM_PAINT to happen now to instantly reflect the selection change. - if (region != null) { - Invalidate(region, true); - Update(); + if (region != null) + { + Invalidate(region, true); + Update(); } - else if (regionRect != Rectangle.Empty) { + else if (regionRect != Rectangle.Empty) + { Invalidate(regionRect, true); Update(); } } - finally { - if (region != null) { + finally + { + if (region != null) + { region.Dispose(); } } // fire accessibility - if (IsHandleCreated && item != null) { + if (IsHandleCreated && item != null) + { int focusIndex = DisplayedItems.IndexOf(item); AccessibilityNotifyClients(AccessibleEvents.Focus, focusIndex); } } - internal void ClearInsertionMark() { - if (lastInsertionMarkRect != Rectangle.Empty) { + internal void ClearInsertionMark() + { + if (lastInsertionMarkRect != Rectangle.Empty) + { // stuff away the lastInsertionMarkRect // and clear it out _before_ we call paint OW // the call to invalidate wont help as it will get @@ -1894,12 +2246,15 @@ internal void ClearInsertionMark() { } } - private void ClearLastMouseDownedItem() { + private void ClearLastMouseDownedItem() + { ToolStripItem lastItem = lastMouseDownedItem; lastMouseDownedItem = null; - if (IsSelectionSuspended) { + if (IsSelectionSuspended) + { SetToolStripState(STATE_LASTMOUSEDOWNEDITEMCAPTURE, false); - if (lastItem != null) { + if (lastItem != null) + { lastItem.Invalidate(); } } @@ -1908,15 +2263,19 @@ private void ClearLastMouseDownedItem() { /// /// Clean up any resources being used. /// - protected override void Dispose( bool disposing ) { - if(disposing) { + protected override void Dispose(bool disposing) + { + if (disposing) + { ToolStripOverflow overflow = GetOverflow(); - - try { - this.SuspendLayout(); - if (overflow != null) { - overflow.SuspendLayout(); + try + { + + this.SuspendLayout(); + if (overflow != null) + { + overflow.SuspendLayout(); } // if there's a problem in config, dont be a leaker. SetToolStripState(STATE_DISPOSINGITEMS, true); @@ -1925,130 +2284,159 @@ protected override void Dispose( bool disposing ) { HookStaticEvents(/*hook=*/false); ToolStripPanelCell toolStripPanelCell = Properties.GetObject(ToolStrip.PropToolStripPanelCell) as ToolStripPanelCell; - if (toolStripPanelCell != null) { + if (toolStripPanelCell != null) + { toolStripPanelCell.Dispose(); } - if (cachedItemHdcInfo != null) { + if (cachedItemHdcInfo != null) + { cachedItemHdcInfo.Dispose(); } - if (mouseHoverTimer != null) { + if (mouseHoverTimer != null) + { mouseHoverTimer.Dispose(); } ToolTip toolTip = (ToolTip)Properties.GetObject(ToolStrip.PropToolTip); - if (toolTip != null) { - toolTip.Dispose (); + if (toolTip != null) + { + toolTip.Dispose(); } - if (!Items.IsReadOnly) { + if (!Items.IsReadOnly) + { // only dispose the items we actually own. - for (int i = Items.Count - 1; i >= 0; i--) { + for (int i = Items.Count - 1; i >= 0; i--) + { Items[i].Dispose(); } Items.Clear(); } // clean up items not in the Items list - if (toolStripGrip != null) { + if (toolStripGrip != null) + { toolStripGrip.Dispose(); } - if (toolStripOverflowButton != null) { + if (toolStripOverflowButton != null) + { toolStripOverflowButton.Dispose(); } // remove the restore focus filter - if (restoreFocusFilter != null) { + if (restoreFocusFilter != null) + { // PERF, - Application.ThreadContext.FromCurrent().RemoveMessageFilter(restoreFocusFilter); + Application.ThreadContext.FromCurrent().RemoveMessageFilter(restoreFocusFilter); restoreFocusFilter = null; } // exit menu mode if necessary. bool exitMenuMode = false; - if (ToolStripManager.ModalMenuFilter.GetActiveToolStrip() == this) { + if (ToolStripManager.ModalMenuFilter.GetActiveToolStrip() == this) + { exitMenuMode = true; } ToolStripManager.ModalMenuFilter.RemoveActiveToolStrip(this); // if we were the last toolstrip in the queue, exit menu mode. - if (exitMenuMode && ToolStripManager.ModalMenuFilter.GetActiveToolStrip() == null) { + if (exitMenuMode && ToolStripManager.ModalMenuFilter.GetActiveToolStrip() == null) + { Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "Exiting menu mode because we're the last toolstrip in the queue, and we've disposed."); ToolStripManager.ModalMenuFilter.ExitMenuMode(); } - + ToolStripManager.ToolStrips.Remove(this); - } - finally { - - this.ResumeLayout(false); - if (overflow != null) { - overflow.ResumeLayout(false); - } - SetToolStripState(STATE_DISPOSINGITEMS, false); } - } - base.Dispose( disposing ); + finally + { + + this.ResumeLayout(false); + if (overflow != null) + { + overflow.ResumeLayout(false); + } + SetToolStripState(STATE_DISPOSINGITEMS, false); + } + } + base.Dispose(disposing); } - internal void DoLayoutIfHandleCreated(ToolStripItemEventArgs e) { - if (this.IsHandleCreated) { + internal void DoLayoutIfHandleCreated(ToolStripItemEventArgs e) + { + if (this.IsHandleCreated) + { LayoutTransaction.DoLayout(this, e.Item, PropertyNames.Items); this.Invalidate(); // Adding this item may have added it to the overflow // However, we can't check if it's in OverflowItems, because // it gets added there in Layout, and layout might be suspended. - if (this.CanOverflow && this.OverflowButton.HasDropDown) { - if (DeferOverflowDropDownLayout()) { + if (this.CanOverflow && this.OverflowButton.HasDropDown) + { + if (DeferOverflowDropDownLayout()) + { CommonProperties.xClearPreferredSizeCache(this.OverflowButton.DropDown); this.OverflowButton.DropDown.LayoutRequired = true; } - else { + else + { LayoutTransaction.DoLayout(this.OverflowButton.DropDown, e.Item, PropertyNames.Items); this.OverflowButton.DropDown.Invalidate(); } } } - else { + else + { // next time we fetch the preferred size, recalc it. CommonProperties.xClearPreferredSizeCache(this); this.LayoutRequired = true; - if (this.CanOverflow && this.OverflowButton.HasDropDown) { + if (this.CanOverflow && this.OverflowButton.HasDropDown) + { this.OverflowButton.DropDown.LayoutRequired = true; } } } - private bool DeferOverflowDropDownLayout() { - return this.IsLayoutSuspended - ||!this.OverflowButton.DropDown.Visible + private bool DeferOverflowDropDownLayout() + { + return this.IsLayoutSuspended + || !this.OverflowButton.DropDown.Visible || !this.OverflowButton.DropDown.IsHandleCreated; } - void ISupportToolStripPanel.EndDrag() { + void ISupportToolStripPanel.EndDrag() + { ToolStripPanel.ClearDragFeedback(); OnEndDrag(EventArgs.Empty); } - internal ToolStripOverflow GetOverflow() { - return (toolStripOverflowButton == null || !toolStripOverflowButton.HasDropDown) ? null : toolStripOverflowButton.DropDown as ToolStripOverflow; + internal ToolStripOverflow GetOverflow() + { + return (toolStripOverflowButton == null || !toolStripOverflowButton.HasDropDown) ? null : toolStripOverflowButton.DropDown as ToolStripOverflow; } - internal byte GetMouseId() { + internal byte GetMouseId() + { // never return 0 as the mousedown ID, this is the "reset" value. - if (mouseDownID == 0) { + if (mouseDownID == 0) + { mouseDownID++; } return mouseDownID; } - internal virtual ToolStripItem GetNextItem(ToolStripItem start, ArrowDirection direction, bool rtlAware) { + internal virtual ToolStripItem GetNextItem(ToolStripItem start, ArrowDirection direction, bool rtlAware) + { - if (rtlAware && RightToLeft == RightToLeft.Yes) { - if (direction == ArrowDirection.Right) { + if (rtlAware && RightToLeft == RightToLeft.Yes) + { + if (direction == ArrowDirection.Right) + { direction = ArrowDirection.Left; } - else if (direction == ArrowDirection.Left) { + else if (direction == ArrowDirection.Left) + { direction = ArrowDirection.Right; } } @@ -2076,51 +2464,59 @@ public virtual ToolStripItem GetNextItem(ToolStripItem start, ArrowDirection dir default: throw new InvalidEnumArgumentException(nameof(direction), (int)direction, typeof(ArrowDirection)); } - } + } /// /// Helper function for GetNextItem - do not directly call this. /// - private ToolStripItem GetNextItemHorizontal(ToolStripItem start, bool forward) { + private ToolStripItem GetNextItemHorizontal(ToolStripItem start, bool forward) + { if (DisplayedItems.Count <= 0) return null; - if (start == null) { + if (start == null) + { // The navigation should be consisstent when navigating in forward and // backward direction entering the toolstrip, it means that the first // toolstrip item should be selected irrespectively TAB or SHIFT+TAB // is pressed. - start = (forward) ? DisplayedItems[DisplayedItems.Count -1] : DisplayedItems[DisplayedItems.Count > 1 ? 1 : 0]; + start = (forward) ? DisplayedItems[DisplayedItems.Count - 1] : DisplayedItems[DisplayedItems.Count > 1 ? 1 : 0]; } int current = DisplayedItems.IndexOf(start); - if (current == -1) { + if (current == -1) + { Debug.WriteLineIf(SelectionDebug.TraceVerbose, "Started from a visible = false item"); return null; } - - Debug.WriteLineIf(SelectionDebug.TraceVerbose && (current != -1), "[SelectDBG GetNextToolStripItem] Last selected item was " + ((current != -1) ? DisplayedItems[current].Text : "")); + + Debug.WriteLineIf(SelectionDebug.TraceVerbose && (current != -1), "[SelectDBG GetNextToolStripItem] Last selected item was " + ((current != -1) ? DisplayedItems[current].Text : "")); Debug.WriteLineIf(SelectionDebug.TraceVerbose && (current == -1), "[SelectDBG GetNextToolStripItem] Last selected item was null"); int count = DisplayedItems.Count; - do { + do + { - if (forward) { + if (forward) + { current = ++current % count; } - else { // provide negative wrap if necessary + else + { // provide negative wrap if necessary current = (--current < 0) ? count + current : current; } ToolStripDropDown dropDown = this as ToolStripDropDown; - if (dropDown!= null) + if (dropDown != null) { - if (dropDown.OwnerItem != null && dropDown.OwnerItem.IsInDesignMode) { - return DisplayedItems[current]; + if (dropDown.OwnerItem != null && dropDown.OwnerItem.IsInDesignMode) + { + return DisplayedItems[current]; } } - if (DisplayedItems[current].CanKeyboardSelect) { + if (DisplayedItems[current].CanKeyboardSelect) + { Debug.WriteLineIf(SelectionDebug.TraceVerbose, "[SelectDBG GetNextToolStripItem] selecting " + DisplayedItems[current].Text); //ClearAllSelectionsExcept(Items[current]); return DisplayedItems[current]; @@ -2130,58 +2526,65 @@ private ToolStripItem GetNextItemHorizontal(ToolStripItem start, bool forward) { return null; } - /// - /// Helper function for GetNextItem - do not directly call this. - /// - [SuppressMessage("Microsoft.Portability", "CA1902:AvoidTestingForFloatingPointEquality")] - private ToolStripItem GetNextItemVertical(ToolStripItem selectedItem, bool down) { - - ToolStripItem tanWinner = null; - ToolStripItem hypotenuseWinner = null; - - double minHypotenuse = double.MaxValue; - double minTan = double.MaxValue; - double hypotenuseOfTanWinner = double.MaxValue; - double tanOfHypotenuseWinner = double.MaxValue; - - if (selectedItem == null) { - ToolStripItem item = GetNextItemHorizontal(selectedItem, down); - return item; - } - - ToolStripDropDown dropDown = this as ToolStripDropDown; - if (dropDown != null) - { - if (dropDown.OwnerItem != null && (dropDown.OwnerItem.IsInDesignMode || (dropDown.OwnerItem.Owner != null && dropDown.OwnerItem.Owner.IsInDesignMode))) { - ToolStripItem item = GetNextItemHorizontal(selectedItem, down); - return item; - } - } - - - Point midPointOfCurrent = new Point(selectedItem.Bounds.X + selectedItem.Width / 2, - selectedItem.Bounds.Y + selectedItem.Height / 2); - - - - for(int i = 0; i < DisplayedItems.Count; i++) { - ToolStripItem otherItem = DisplayedItems[i]; - if (otherItem == selectedItem || !otherItem.CanKeyboardSelect) { - continue; - } - if (!down && otherItem.Bounds.Bottom > selectedItem.Bounds.Top) { - // if we are going up the other control has to be above - continue; - } - else if (down && otherItem.Bounds.Top < selectedItem.Bounds.Bottom) { - // if we are going down the other control has to be below - continue; - } - - //[ otherControl ] - // * - Point otherItemMidLocation = new Point(otherItem.Bounds.X + otherItem.Width/2, (down)? otherItem.Bounds.Top : otherItem.Bounds.Bottom); - #if DEBUG_UPDOWN + /// + /// Helper function for GetNextItem - do not directly call this. + /// + [SuppressMessage("Microsoft.Portability", "CA1902:AvoidTestingForFloatingPointEquality")] + private ToolStripItem GetNextItemVertical(ToolStripItem selectedItem, bool down) + { + + ToolStripItem tanWinner = null; + ToolStripItem hypotenuseWinner = null; + + double minHypotenuse = double.MaxValue; + double minTan = double.MaxValue; + double hypotenuseOfTanWinner = double.MaxValue; + double tanOfHypotenuseWinner = double.MaxValue; + + if (selectedItem == null) + { + ToolStripItem item = GetNextItemHorizontal(selectedItem, down); + return item; + } + + ToolStripDropDown dropDown = this as ToolStripDropDown; + if (dropDown != null) + { + if (dropDown.OwnerItem != null && (dropDown.OwnerItem.IsInDesignMode || (dropDown.OwnerItem.Owner != null && dropDown.OwnerItem.Owner.IsInDesignMode))) + { + ToolStripItem item = GetNextItemHorizontal(selectedItem, down); + return item; + } + } + + + Point midPointOfCurrent = new Point(selectedItem.Bounds.X + selectedItem.Width / 2, + selectedItem.Bounds.Y + selectedItem.Height / 2); + + + + for (int i = 0; i < DisplayedItems.Count; i++) + { + ToolStripItem otherItem = DisplayedItems[i]; + if (otherItem == selectedItem || !otherItem.CanKeyboardSelect) + { + continue; + } + if (!down && otherItem.Bounds.Bottom > selectedItem.Bounds.Top) + { + // if we are going up the other control has to be above + continue; + } + else if (down && otherItem.Bounds.Top < selectedItem.Bounds.Bottom) + { + // if we are going down the other control has to be below + continue; + } + + //[ otherControl ] + // * + Point otherItemMidLocation = new Point(otherItem.Bounds.X + otherItem.Width / 2, (down) ? otherItem.Bounds.Top : otherItem.Bounds.Bottom); +#if DEBUG_UPDOWN Graphics g = Graphics.FromHwnd(this.Handle); using (Pen p = new Pen(Color.FromKnownColor((KnownColor)i))) { @@ -2189,238 +2592,273 @@ private ToolStripItem GetNextItemVertical(ToolStripItem selectedItem, bool down) } System.Threading.Thread.Sleep(100); g.Dispose(); - #endif - int oppositeSide = otherItemMidLocation.X - midPointOfCurrent.X; - int adjacentSide = otherItemMidLocation.Y - midPointOfCurrent.Y; - - // use pythagrian theorem to calculate the length of the distance - // between the middle of the current control in question and it's adjacent - // objects. - double hypotenuse = Math.Sqrt(adjacentSide*adjacentSide + oppositeSide*oppositeSide); - - if (adjacentSide != 0) { // avoid divide by zero - we dont do layered controls - // _[o] - // |/ - // [s] - // get the angle between s and o by taking the arctan. - // PERF consider using approximation instead - double tan = Math.Abs(Math.Atan(oppositeSide/adjacentSide)); - - // we want the thing with the smallest angle and smallest distance between midpoints - minTan = Math.Min(minTan, tan); - minHypotenuse = Math.Min(minHypotenuse, hypotenuse); - - if (minTan == tan && minTan != double.NaN) { - tanWinner = otherItem; - hypotenuseOfTanWinner = hypotenuse; - } - - if (minHypotenuse == hypotenuse) { - hypotenuseWinner = otherItem; - tanOfHypotenuseWinner = tan; - } - } - } - - - #if DEBUG_UPDOWN +#endif + int oppositeSide = otherItemMidLocation.X - midPointOfCurrent.X; + int adjacentSide = otherItemMidLocation.Y - midPointOfCurrent.Y; + + // use pythagrian theorem to calculate the length of the distance + // between the middle of the current control in question and it's adjacent + // objects. + double hypotenuse = Math.Sqrt(adjacentSide * adjacentSide + oppositeSide * oppositeSide); + + if (adjacentSide != 0) + { // avoid divide by zero - we dont do layered controls + // _[o] + // |/ + // [s] + // get the angle between s and o by taking the arctan. + // PERF consider using approximation instead + double tan = Math.Abs(Math.Atan(oppositeSide / adjacentSide)); + + // we want the thing with the smallest angle and smallest distance between midpoints + minTan = Math.Min(minTan, tan); + minHypotenuse = Math.Min(minHypotenuse, hypotenuse); + + if (minTan == tan && minTan != double.NaN) + { + tanWinner = otherItem; + hypotenuseOfTanWinner = hypotenuse; + } + + if (minHypotenuse == hypotenuse) + { + hypotenuseWinner = otherItem; + tanOfHypotenuseWinner = tan; + } + } + } + + +#if DEBUG_UPDOWN string tanWinnerString = (tanWinner == null) ? "null" : tanWinner.ToString(); string hypWinnerString = (hypotenuseWinner == null) ? "null": hypotenuseWinner.ToString(); Debug.WriteLine(String.Format("Tangent winner is {0} Hyp winner is {1}", tanWinnerString, hypWinnerString)); - #endif - if ((tanWinner == null) || (hypotenuseWinner == null)) { - return (GetNextItemHorizontal(null,down)); - } - else { - // often times the guy with the best angle will be the guy with the closest hypotenuse. - // however in layouts where things are more randomly spaced, this is not necessarily the case. - if (tanOfHypotenuseWinner == minTan) { - // if the angles match up, such as in the case of items of the same width in vertical flow - // then pick the closest one. - return hypotenuseWinner; - } - else if ((!down && tanWinner.Bounds.Bottom <= hypotenuseWinner.Bounds.Top) - ||(down && tanWinner.Bounds.Top > hypotenuseWinner.Bounds.Bottom)) { - // we prefer the case where the angle is smaller than - // the case where the hypotenuse is smaller. The only - // scenarios where that is not the case is when the hypoteneuse - // winner is clearly closer than the angle winner. - - // [a.winner] | [s] - // | [h.winner] - // [h.winner] | - // [s] | [a.winner] - return hypotenuseWinner; - } - else { - return tanWinner; - } - } - } - - - internal override Size GetPreferredSizeCore(Size proposedSize) { - // We act like a container control - - // Translating 0,0 from ClientSize to actual Size tells us how much space - // is required for the borders. - if (proposedSize.Width == 1) { - proposedSize.Width = int.MaxValue; - } - if (proposedSize.Height == 1) { - proposedSize.Height = int.MaxValue; - } - - Padding padding = Padding; - Size prefSize = LayoutEngine.GetPreferredSize(this, proposedSize - padding.Size); - Padding newPadding = Padding; - - // as a side effect of some of the layouts, we can change the padding. - // if this happens, we need to clear the cache. - if (padding != newPadding) { - CommonProperties.xClearPreferredSizeCache(this); - } - return prefSize + newPadding.Size; - - } - -#region GetPreferredSizeHelpers +#endif + if ((tanWinner == null) || (hypotenuseWinner == null)) + { + return (GetNextItemHorizontal(null, down)); + } + else + { + // often times the guy with the best angle will be the guy with the closest hypotenuse. + // however in layouts where things are more randomly spaced, this is not necessarily the case. + if (tanOfHypotenuseWinner == minTan) + { + // if the angles match up, such as in the case of items of the same width in vertical flow + // then pick the closest one. + return hypotenuseWinner; + } + else if ((!down && tanWinner.Bounds.Bottom <= hypotenuseWinner.Bounds.Top) + || (down && tanWinner.Bounds.Top > hypotenuseWinner.Bounds.Bottom)) + { + // we prefer the case where the angle is smaller than + // the case where the hypotenuse is smaller. The only + // scenarios where that is not the case is when the hypoteneuse + // winner is clearly closer than the angle winner. + + // [a.winner] | [s] + // | [h.winner] + // [h.winner] | + // [s] | [a.winner] + return hypotenuseWinner; + } + else + { + return tanWinner; + } + } + } + + + internal override Size GetPreferredSizeCore(Size proposedSize) + { + // We act like a container control + + // Translating 0,0 from ClientSize to actual Size tells us how much space + // is required for the borders. + if (proposedSize.Width == 1) + { + proposedSize.Width = int.MaxValue; + } + if (proposedSize.Height == 1) + { + proposedSize.Height = int.MaxValue; + } + + Padding padding = Padding; + Size prefSize = LayoutEngine.GetPreferredSize(this, proposedSize - padding.Size); + Padding newPadding = Padding; + + // as a side effect of some of the layouts, we can change the padding. + // if this happens, we need to clear the cache. + if (padding != newPadding) + { + CommonProperties.xClearPreferredSizeCache(this); + } + return prefSize + newPadding.Size; + + } + + #region GetPreferredSizeHelpers // // These are here so they can be shared between splitstack layout and StatusStrip // - internal static Size GetPreferredSizeHorizontal(IArrangedElement container, Size proposedConstraints) { - Size maxSize = Size.Empty; - ToolStrip toolStrip = container as ToolStrip; - - // ensure preferred size respects default size as a minimum. - Size defaultSize = toolStrip.DefaultSize - toolStrip.Padding.Size; - maxSize.Height = Math.Max(0, defaultSize.Height); - - bool requiresOverflow = false; - bool foundItemParticipatingInLayout = false; - - for (int j = 0; j < toolStrip.Items.Count; j++) { - ToolStripItem item = toolStrip.Items[j]; - - if (((IArrangedElement)item).ParticipatesInLayout) { - foundItemParticipatingInLayout =true; - if (item.Overflow != ToolStripItemOverflow.Always) { - Padding itemMargin = item.Margin; - Size prefItemSize = GetPreferredItemSize(item); - maxSize.Width += itemMargin.Horizontal + prefItemSize.Width; - maxSize.Height = Math.Max(maxSize.Height, itemMargin.Vertical + prefItemSize.Height); - } - else { - requiresOverflow = true; - } - } - } - - if (toolStrip.Items.Count == 0 || (!foundItemParticipatingInLayout)) { - // if there are no items there, create something anyways. - maxSize = defaultSize; - } - - - if (requiresOverflow) { - // add in the width of the overflow button - ToolStripOverflowButton overflowItem = toolStrip.OverflowButton; - Padding overflowItemMargin = overflowItem.Margin; - - maxSize.Width += overflowItemMargin.Horizontal + overflowItem.Bounds.Width; - } - else { - maxSize.Width += 2; //add Padding of 2 Pixels to the right if not Overflow. - } - - if (toolStrip.GripStyle == ToolStripGripStyle.Visible) { - // add in the grip width - Padding gripMargin = toolStrip.GripMargin; - maxSize.Width += gripMargin.Horizontal + toolStrip.Grip.GripThickness; - } - - maxSize = LayoutUtils.IntersectSizes(maxSize, proposedConstraints); - return maxSize; - } - - - [SuppressMessage("Microsoft.Portability", "CA1902:AvoidTestingForFloatingPointEquality")] - - internal static Size GetPreferredSizeVertical(IArrangedElement container, Size proposedConstraints) { - Size maxSize = Size.Empty; - bool requiresOverflow = false; - ToolStrip toolStrip = container as ToolStrip; - - bool foundItemParticipatingInLayout = false; - - - for (int j = 0; j < toolStrip.Items.Count; j++) { - ToolStripItem item = toolStrip.Items[j]; - - if (((IArrangedElement)item).ParticipatesInLayout) { - foundItemParticipatingInLayout = true; - if (item.Overflow != ToolStripItemOverflow.Always) { - Size preferredSize = GetPreferredItemSize(item); - Padding itemMargin = item.Margin; - maxSize.Height += itemMargin.Vertical + preferredSize.Height; - maxSize.Width = Math.Max(maxSize.Width, itemMargin.Horizontal + preferredSize.Width); - } - else { - requiresOverflow = true; - } - } - } - - - if (toolStrip.Items.Count == 0 || !foundItemParticipatingInLayout) { - // if there are no items there, create something anyways. - maxSize = LayoutUtils.FlipSize( toolStrip.DefaultSize); - } - - if (requiresOverflow) { - // add in the width of the overflow button - ToolStripOverflowButton overflowItem = toolStrip.OverflowButton; - Padding overflowItemMargin = overflowItem.Margin; - maxSize.Height += overflowItemMargin.Vertical + overflowItem.Bounds.Height; - } - else { - maxSize.Height += 2; //add Padding to the bottom if not Overflow. - } - - if (toolStrip.GripStyle == ToolStripGripStyle.Visible) { - // add in the grip width - Padding gripMargin = toolStrip.GripMargin; - maxSize.Height += gripMargin.Vertical + toolStrip.Grip.GripThickness; - } - - // note here the difference in vertical - we want the strings to fit perfectly so we're not going to constrain by the specified size. - if (toolStrip.Size != maxSize) - { - CommonProperties.xClearPreferredSizeCache(toolStrip); - } - return maxSize; - } - - private static Size GetPreferredItemSize(ToolStripItem item) { + internal static Size GetPreferredSizeHorizontal(IArrangedElement container, Size proposedConstraints) + { + Size maxSize = Size.Empty; + ToolStrip toolStrip = container as ToolStrip; + + // ensure preferred size respects default size as a minimum. + Size defaultSize = toolStrip.DefaultSize - toolStrip.Padding.Size; + maxSize.Height = Math.Max(0, defaultSize.Height); + + bool requiresOverflow = false; + bool foundItemParticipatingInLayout = false; + + for (int j = 0; j < toolStrip.Items.Count; j++) + { + ToolStripItem item = toolStrip.Items[j]; + + if (((IArrangedElement)item).ParticipatesInLayout) + { + foundItemParticipatingInLayout = true; + if (item.Overflow != ToolStripItemOverflow.Always) + { + Padding itemMargin = item.Margin; + Size prefItemSize = GetPreferredItemSize(item); + maxSize.Width += itemMargin.Horizontal + prefItemSize.Width; + maxSize.Height = Math.Max(maxSize.Height, itemMargin.Vertical + prefItemSize.Height); + } + else + { + requiresOverflow = true; + } + } + } + + if (toolStrip.Items.Count == 0 || (!foundItemParticipatingInLayout)) + { + // if there are no items there, create something anyways. + maxSize = defaultSize; + } + + + if (requiresOverflow) + { + // add in the width of the overflow button + ToolStripOverflowButton overflowItem = toolStrip.OverflowButton; + Padding overflowItemMargin = overflowItem.Margin; + + maxSize.Width += overflowItemMargin.Horizontal + overflowItem.Bounds.Width; + } + else + { + maxSize.Width += 2; //add Padding of 2 Pixels to the right if not Overflow. + } + + if (toolStrip.GripStyle == ToolStripGripStyle.Visible) + { + // add in the grip width + Padding gripMargin = toolStrip.GripMargin; + maxSize.Width += gripMargin.Horizontal + toolStrip.Grip.GripThickness; + } + + maxSize = LayoutUtils.IntersectSizes(maxSize, proposedConstraints); + return maxSize; + } + + + [SuppressMessage("Microsoft.Portability", "CA1902:AvoidTestingForFloatingPointEquality")] + + internal static Size GetPreferredSizeVertical(IArrangedElement container, Size proposedConstraints) + { + Size maxSize = Size.Empty; + bool requiresOverflow = false; + ToolStrip toolStrip = container as ToolStrip; + + bool foundItemParticipatingInLayout = false; + + + for (int j = 0; j < toolStrip.Items.Count; j++) + { + ToolStripItem item = toolStrip.Items[j]; + + if (((IArrangedElement)item).ParticipatesInLayout) + { + foundItemParticipatingInLayout = true; + if (item.Overflow != ToolStripItemOverflow.Always) + { + Size preferredSize = GetPreferredItemSize(item); + Padding itemMargin = item.Margin; + maxSize.Height += itemMargin.Vertical + preferredSize.Height; + maxSize.Width = Math.Max(maxSize.Width, itemMargin.Horizontal + preferredSize.Width); + } + else + { + requiresOverflow = true; + } + } + } + + + if (toolStrip.Items.Count == 0 || !foundItemParticipatingInLayout) + { + // if there are no items there, create something anyways. + maxSize = LayoutUtils.FlipSize(toolStrip.DefaultSize); + } + + if (requiresOverflow) + { + // add in the width of the overflow button + ToolStripOverflowButton overflowItem = toolStrip.OverflowButton; + Padding overflowItemMargin = overflowItem.Margin; + maxSize.Height += overflowItemMargin.Vertical + overflowItem.Bounds.Height; + } + else + { + maxSize.Height += 2; //add Padding to the bottom if not Overflow. + } + + if (toolStrip.GripStyle == ToolStripGripStyle.Visible) + { + // add in the grip width + Padding gripMargin = toolStrip.GripMargin; + maxSize.Height += gripMargin.Vertical + toolStrip.Grip.GripThickness; + } + + // note here the difference in vertical - we want the strings to fit perfectly so we're not going to constrain by the specified size. + if (toolStrip.Size != maxSize) + { + CommonProperties.xClearPreferredSizeCache(toolStrip); + } + return maxSize; + } + + private static Size GetPreferredItemSize(ToolStripItem item) + { return item.AutoSize ? item.GetPreferredSize(Size.Empty) : item.Size; } -#endregion -#region MeasurementGraphics + #endregion + #region MeasurementGraphics // - internal static Graphics GetMeasurementGraphics() { + internal static Graphics GetMeasurementGraphics() + { return WindowsFormsUtils.CreateMeasurementGraphics(); } -#endregion + #endregion /// /// Summary of GetSelectedItem. /// - internal ToolStripItem GetSelectedItem() { + internal ToolStripItem GetSelectedItem() + { ToolStripItem selectedItem = null; - for (int i = 0; i < DisplayedItems.Count; i++) { - if (DisplayedItems[i].Selected) { + for (int i = 0; i < DisplayedItems.Count; i++) + { + if (DisplayedItems[i].Selected) + { selectedItem = DisplayedItems[i]; } } @@ -2430,11 +2868,13 @@ internal ToolStripItem GetSelectedItem() { /// /// Retrieves the current value of the specified bit in the control's state. /// - internal bool GetToolStripState(int flag) { + internal bool GetToolStripState(int flag) + { return (toolStripState & flag) != 0; } - internal virtual ToolStrip GetToplevelOwnerToolStrip() { + internal virtual ToolStrip GetToplevelOwnerToolStrip() + { return this; } @@ -2442,26 +2882,32 @@ internal virtual ToolStrip GetToplevelOwnerToolStrip() { /// toolstrip -> toolstrip /// contextmenustrip -> the control that is showing it /// toolstripdropdown -> top most toolstrip - internal virtual Control GetOwnerControl() { + internal virtual Control GetOwnerControl() + { return this; } - private void HandleMouseLeave() { + private void HandleMouseLeave() + { // If we had a particular item that was "entered" // notify it that we have left. - if (lastMouseActiveItem != null) { - if (!DesignMode) { + if (lastMouseActiveItem != null) + { + if (!DesignMode) + { MouseHoverTimer.Cancel(lastMouseActiveItem); } - try { + try + { Debug.WriteLineIf(ToolStripItem.MouseDebugging.TraceVerbose, "firing mouse leave on " + lastMouseActiveItem.ToString()); - lastMouseActiveItem.FireEvent(EventArgs.Empty,ToolStripItemEventType.MouseLeave); + lastMouseActiveItem.FireEvent(EventArgs.Empty, ToolStripItemEventType.MouseLeave); } - finally { + finally + { Debug.WriteLineIf(ToolStripItem.MouseDebugging.TraceVerbose, "setting last active item to null"); lastMouseActiveItem = null; - } + } } ToolStripMenuItem.MenuTimer.HandleToolStripMouseLeave(this); } @@ -2469,17 +2915,20 @@ private void HandleMouseLeave() { /// /// Summary of HandleItemClick. /// - internal void HandleItemClick(ToolStripItem dismissingItem) { - ToolStripItemClickedEventArgs e= new ToolStripItemClickedEventArgs(dismissingItem); + internal void HandleItemClick(ToolStripItem dismissingItem) + { + ToolStripItemClickedEventArgs e = new ToolStripItemClickedEventArgs(dismissingItem); OnItemClicked(e); // Ensure both the overflow and the main toolstrip fire ItemClick event // otherwise the overflow wont dismiss. - if (!IsDropDown && dismissingItem.IsOnOverflow) { + if (!IsDropDown && dismissingItem.IsOnOverflow) + { OverflowButton.DropDown.HandleItemClick(dismissingItem); } } - internal virtual void HandleItemClicked(ToolStripItem dismissingItem) { + internal virtual void HandleItemClicked(ToolStripItem dismissingItem) + { // post processing after the click has happened. /*if (ContainsFocus && !Focused) { RestoreFocusInternal(); @@ -2492,24 +2941,32 @@ internal virtual void HandleItemClicked(ToolStripItem dismissingItem) { } - private void HookStaticEvents(bool hook) { - if (hook) { - if (!alreadyHooked) { - try { + private void HookStaticEvents(bool hook) + { + if (hook) + { + if (!alreadyHooked) + { + try + { ToolStripManager.RendererChanged += new EventHandler(OnDefaultRendererChanged); SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(OnUserPreferenceChanged); } - finally{ + finally + { alreadyHooked = true; - } + } } } - else if (alreadyHooked) { - try { + else if (alreadyHooked) + { + try + { ToolStripManager.RendererChanged -= new EventHandler(OnDefaultRendererChanged); SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(OnUserPreferenceChanged); } - finally { + finally + { alreadyHooked = false; } @@ -2517,41 +2974,52 @@ private void HookStaticEvents(bool hook) { } //initialize ToolStrip - private void InitializeRenderer(ToolStripRenderer renderer) { + private void InitializeRenderer(ToolStripRenderer renderer) + { // wrap this in a LayoutTransaction so that if they change sizes // in this method we've suspended layout. - using(LayoutTransaction.CreateTransactionIf(AutoSize, this, this, PropertyNames.Renderer)) { + using (LayoutTransaction.CreateTransactionIf(AutoSize, this, this, PropertyNames.Renderer)) + { renderer.Initialize(this); - for (int i = 0; i < this.Items.Count; i++) { + for (int i = 0; i < this.Items.Count; i++) + { renderer.InitializeItem(this.Items[i]); } } - Invalidate( this.Controls.Count > 0); + Invalidate(this.Controls.Count > 0); } // sometimes you only want to force a layout if the ToolStrip is visible. - private void InvalidateLayout() { - if (IsHandleCreated) { + private void InvalidateLayout() + { + if (IsHandleCreated) + { LayoutTransaction.DoLayout(this, this, null); } } - internal void InvalidateTextItems() { - using (new LayoutTransaction(this, this, "ShowKeyboardFocusCues", /*PerformLayout=*/Visible)) { - for (int j = 0; j < DisplayedItems.Count; j++) { - if (((DisplayedItems[j].DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text)){ - DisplayedItems[j].InvalidateItemLayout("ShowKeyboardFocusCues"); - } - } + internal void InvalidateTextItems() + { + using (new LayoutTransaction(this, this, "ShowKeyboardFocusCues", /*PerformLayout=*/Visible)) + { + for (int j = 0; j < DisplayedItems.Count; j++) + { + if (((DisplayedItems[j].DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text)) + { + DisplayedItems[j].InvalidateItemLayout("ShowKeyboardFocusCues"); + } + } } } /// /// Summary of IsInputKey. /// /// - protected override bool IsInputKey(Keys keyData) { + protected override bool IsInputKey(Keys keyData) + { ToolStripItem item = this.GetSelectedItem(); - if ((item != null) && item.IsInputKey(keyData)) { + if ((item != null) && item.IsInputKey(keyData)) + { return true; } return base.IsInputKey(keyData); @@ -2560,29 +3028,36 @@ protected override bool IsInputKey(Keys keyData) { /// Summary of IsInputChar. /// /// - protected override bool IsInputChar(char charCode) { + protected override bool IsInputChar(char charCode) + { ToolStripItem item = this.GetSelectedItem(); - if ((item != null) && item.IsInputChar(charCode)) { + if ((item != null) && item.IsInputChar(charCode)) + { return true; } return base.IsInputChar(charCode); } - private static bool IsPseudoMnemonic(char charCode, string text) { - if (!string.IsNullOrEmpty(text)) { - if (!WindowsFormsUtils.ContainsMnemonic(text)) { - char charToCompare = char.ToUpper(charCode, CultureInfo.CurrentCulture); - char firstLetter = char.ToUpper(text[0], CultureInfo.CurrentCulture); - if (firstLetter == charToCompare ||(char.ToLower(charCode, CultureInfo.CurrentCulture) == char.ToLower(text[0], CultureInfo.CurrentCulture)) ) { - return true; - } - } - } + private static bool IsPseudoMnemonic(char charCode, string text) + { + if (!string.IsNullOrEmpty(text)) + { + if (!WindowsFormsUtils.ContainsMnemonic(text)) + { + char charToCompare = char.ToUpper(charCode, CultureInfo.CurrentCulture); + char firstLetter = char.ToUpper(text[0], CultureInfo.CurrentCulture); + if (firstLetter == charToCompare || (char.ToLower(charCode, CultureInfo.CurrentCulture) == char.ToLower(text[0], CultureInfo.CurrentCulture))) + { + return true; + } + } + } return false; } /// Force an item to be painted immediately, rather than waiting for WM_PAINT to occur. - internal void InvokePaintItem(ToolStripItem item) { + internal void InvokePaintItem(ToolStripItem item) + { // Force a WM_PAINT to happen NOW. Invalidate(item.Bounds); Update(); @@ -2590,7 +3065,8 @@ internal void InvokePaintItem(ToolStripItem item) { /// /// Gets or sets the that contains the displayed on a label control /// - private void ImageListRecreateHandle(object sender, EventArgs e) { + private void ImageListRecreateHandle(object sender, EventArgs e) + { Invalidate(); } @@ -2599,36 +3075,46 @@ private void ImageListRecreateHandle(object sender, EventArgs e) { /// 1) We are not currently Rafting .. since this cause this infinite times... /// 2) If we havent been called once .. Since the "LocationChanging" is listened to by the RaftingCell and calls "JOIN" which may call us back. /// - protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { + protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) + { Point location = this.Location; - + if (!IsCurrentlyDragging && !IsLocationChanging && IsInToolStripPanel) { ToolStripLocationCancelEventArgs cae = new ToolStripLocationCancelEventArgs(new Point(x, y), false); - try { - if (location.X != x || location.Y != y) { + try + { + if (location.X != x || location.Y != y) + { SetToolStripState(STATE_LOCATIONCHANGING, true); OnLocationChanging(cae); } - - if (!cae.Cancel) { + + if (!cae.Cancel) + { base.SetBoundsCore(x, y, width, height, specified); } } - finally { + finally + { SetToolStripState(STATE_LOCATIONCHANGING, false); } } - else { - if (IsCurrentlyDragging) { + else + { + if (IsCurrentlyDragging) + { Region transparentRegion = Renderer.GetTransparentRegion(this); - if (transparentRegion != null && (location.X != x || location.Y != y)) { - try { + if (transparentRegion != null && (location.X != x || location.Y != y)) + { + try + { Invalidate(transparentRegion); Update(); } - finally { + finally + { transparentRegion.Dispose(); } } @@ -2639,19 +3125,23 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound } - internal void PaintParentRegion(Graphics g, Region region) { - + internal void PaintParentRegion(Graphics g, Region region) + { + } - internal bool ProcessCmdKeyInternal(ref Message m, Keys keyData) { - return ProcessCmdKey(ref m, keyData); + internal bool ProcessCmdKeyInternal(ref Message m, Keys keyData) + { + return ProcessCmdKey(ref m, keyData); } // This function will print to the PrinterDC. ToolStrip have there own buffered painting and doesnt play very well // with the DC translations done by base Control class. Hence we do our own Painting and the BitBLT the DC into the printerDc. - internal override void PrintToMetaFileRecursive(HandleRef hDC, IntPtr lParam, Rectangle bounds) { + internal override void PrintToMetaFileRecursive(HandleRef hDC, IntPtr lParam, Rectangle bounds) + { using (Bitmap image = new Bitmap(bounds.Width, bounds.Height)) - using (Graphics g = Graphics.FromImage(image)) { + using (Graphics g = Graphics.FromImage(image)) + { IntPtr imageHdc = g.GetHdc(); //send the actual wm_print message UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), Interop.WindowMessages.WM_PRINT, (IntPtr)imageHdc, @@ -2670,50 +3160,63 @@ internal override void PrintToMetaFileRecursive(HandleRef hDC, IntPtr lParam, Re /// /// /// - protected override bool ProcessCmdKey(ref Message m, Keys keyData) { + protected override bool ProcessCmdKey(ref Message m, Keys keyData) + { - if (ToolStripManager.IsMenuKey(keyData)) { - if (!IsDropDown && ToolStripManager.ModalMenuFilter.InMenuMode) { + if (ToolStripManager.IsMenuKey(keyData)) + { + if (!IsDropDown && ToolStripManager.ModalMenuFilter.InMenuMode) + { ClearAllSelections(); ToolStripManager.ModalMenuFilter.MenuKeyToggle = true; Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "[ToolStrip.ProcessCmdKey] Detected a second ALT keypress while in Menu Mode."); ToolStripManager.ModalMenuFilter.ExitMenuMode(); - } + } } - // Give the ToolStripItem very first chance at - // processing keys (except for ALT handling) + // Give the ToolStripItem very first chance at + // processing keys (except for ALT handling) ToolStripItem selectedItem = this.GetSelectedItem(); - if (selectedItem != null){ - if (selectedItem.ProcessCmdKey(ref m, keyData)) { + if (selectedItem != null) + { + if (selectedItem.ProcessCmdKey(ref m, keyData)) + { return true; } } - foreach (ToolStripItem item in this.Items) { - if (item == selectedItem) { + foreach (ToolStripItem item in this.Items) + { + if (item == selectedItem) + { continue; } - if (item.ProcessCmdKey(ref m, keyData)) { + if (item.ProcessCmdKey(ref m, keyData)) + { return true; } } - - if (!IsDropDown) { + + if (!IsDropDown) + { bool isControlTab = (keyData & Keys.Control) == Keys.Control && (keyData & Keys.KeyCode) == Keys.Tab; - if (isControlTab && !TabStop && HasKeyboardInput) { + if (isControlTab && !TabStop && HasKeyboardInput) + { bool handled = false; - if ((keyData & Keys.Shift) == Keys.None) { + if ((keyData & Keys.Shift) == Keys.None) + { handled = ToolStripManager.SelectNextToolStrip(this, /*forward*/true); } - else { + else + { handled = ToolStripManager.SelectNextToolStrip(this, /*forward*/false); } - if (handled) { + if (handled) + { return true; } } @@ -2730,13 +3233,16 @@ protected override bool ProcessCmdKey(ref Message m, Keys keyData) { /// on the form. For the arrow keys, /// !!! /// - protected override bool ProcessDialogKey(Keys keyData) { + protected override bool ProcessDialogKey(Keys keyData) + { bool retVal = false; // Give the ToolStripItem first dibs ToolStripItem item = this.GetSelectedItem(); - if (item != null){ - if(item.ProcessDialogKey(keyData)) { + if (item != null) + { + if (item.ProcessDialogKey(keyData)) + { return true; } } @@ -2745,20 +3251,23 @@ protected override bool ProcessDialogKey(Keys keyData) { // should send the focus back to the last item that // had focus. bool hasModifiers = ((keyData & (Keys.Alt | Keys.Control)) != Keys.None); - + Keys keyCode = (Keys)keyData & Keys.KeyCode; - switch (keyCode) { + switch (keyCode) + { case Keys.Back: // if it's focused itself, process. if it's not focused, make sure a child control // doesnt have focus before processing - if (!ContainsFocus) { + if (!ContainsFocus) + { // shift backspace/backspace work as backspace, which is the same as shift+tab retVal = ProcessTabKey(false); } break; case Keys.Tab: // ctrl+tab does nothing - if (!hasModifiers){ + if (!hasModifiers) + { retVal = ProcessTabKey((keyData & Keys.Shift) == Keys.None); } break; @@ -2769,37 +3278,42 @@ protected override bool ProcessDialogKey(Keys keyData) { retVal = ProcessArrowKey(keyCode); break; case Keys.Home: - SelectNextToolStripItem(null, /*forward =*/ true ); + SelectNextToolStripItem(null, /*forward =*/ true); retVal = true; break; case Keys.End: - SelectNextToolStripItem(null, /*forward =*/ false ); + SelectNextToolStripItem(null, /*forward =*/ false); retVal = true; break; case Keys.Escape: // escape and menu key should restore focus // ctrl+esc does nothing - if (!hasModifiers && !TabStop){ + if (!hasModifiers && !TabStop) + { RestoreFocusInternal(); retVal = true; } break; } - - if (retVal) { + + if (retVal) + { return retVal; } Debug.WriteLineIf(SelectionDebug.TraceVerbose, "[SelectDBG ProcessDialogKey] calling base"); - return base.ProcessDialogKey(keyData); + return base.ProcessDialogKey(keyData); } - internal virtual void ProcessDuplicateMnemonic(ToolStripItem item, char charCode) { - if (!CanProcessMnemonic()) { // Checking again for security... + internal virtual void ProcessDuplicateMnemonic(ToolStripItem item, char charCode) + { + if (!CanProcessMnemonic()) + { // Checking again for security... return; } // - if (item != null) { + if (item != null) + { // SetFocusUnsafe(); item.Select(); @@ -2817,21 +3331,26 @@ internal virtual void ProcessDuplicateMnemonic(ToolStripItem item, char charCode /// Else /// change the selection from the current selected item to the first item that matched. /// - protected internal override bool ProcessMnemonic(char charCode) { + protected internal override bool ProcessMnemonic(char charCode) + { // menus and toolbars only take focus on ALT - if (!CanProcessMnemonic()) { + if (!CanProcessMnemonic()) + { return false; } - if (Focused || ContainsFocus) { + if (Focused || ContainsFocus) + { return ProcessMnemonicInternal(charCode); } bool inMenuMode = ToolStripManager.ModalMenuFilter.InMenuMode; - if (!inMenuMode && Control.ModifierKeys == Keys.Alt) { + if (!inMenuMode && Control.ModifierKeys == Keys.Alt) + { // This is the case where someone hasnt released the ALT key yet, but has pushed another letter. // In some cases we can activate the menu that is not the MainMenuStrip... return ProcessMnemonicInternal(charCode); } - else if (inMenuMode && ToolStripManager.ModalMenuFilter.GetActiveToolStrip() == this) { + else if (inMenuMode && ToolStripManager.ModalMenuFilter.GetActiveToolStrip() == this) + { return ProcessMnemonicInternal(charCode); } @@ -2840,50 +3359,61 @@ protected internal override bool ProcessMnemonic(char charCode) { return false; } - private bool ProcessMnemonicInternal(char charCode) { - if (!CanProcessMnemonic()) { // Checking again for security... + private bool ProcessMnemonicInternal(char charCode) + { + if (!CanProcessMnemonic()) + { // Checking again for security... return false; } // at this point we assume we can process mnemonics as process mnemonic has filtered for use. ToolStripItem startingItem = GetSelectedItem(); int startIndex = 0; - if (startingItem != null) { + if (startingItem != null) + { startIndex = DisplayedItems.IndexOf(startingItem); } startIndex = Math.Max(0, startIndex); - + ToolStripItem firstMatch = null; bool foundMenuItem = false; int index = startIndex; - + // PASS1, iterate through the real mnemonics - for (int i = 0; i < DisplayedItems.Count; i++) { + for (int i = 0; i < DisplayedItems.Count; i++) + { ToolStripItem currentItem = DisplayedItems[index]; - - index = (index +1)%DisplayedItems.Count; - if (string.IsNullOrEmpty(currentItem.Text) || !currentItem.Enabled) { + + index = (index + 1) % DisplayedItems.Count; + if (string.IsNullOrEmpty(currentItem.Text) || !currentItem.Enabled) + { continue; } // Only items which display text should be processed - if ((currentItem.DisplayStyle & ToolStripItemDisplayStyle.Text) != ToolStripItemDisplayStyle.Text) { + if ((currentItem.DisplayStyle & ToolStripItemDisplayStyle.Text) != ToolStripItemDisplayStyle.Text) + { continue; } // keep track whether we've found a menu item - we'll have to do a // second pass for fake mnemonics in that case. - foundMenuItem = (foundMenuItem || (currentItem is ToolStripMenuItem)); - - if (Control.IsMnemonic(charCode,currentItem.Text)) { - if (firstMatch == null) { + foundMenuItem = (foundMenuItem || (currentItem is ToolStripMenuItem)); + + if (Control.IsMnemonic(charCode, currentItem.Text)) + { + if (firstMatch == null) + { firstMatch = currentItem; } - else { + else + { // we've found a second match - we should only change selection. - if (firstMatch == startingItem) { + if (firstMatch == startingItem) + { // change the selection to be the second match as the first is already selected ProcessDuplicateMnemonic(currentItem, charCode); } - else { - ProcessDuplicateMnemonic(firstMatch, charCode); + else + { + ProcessDuplicateMnemonic(firstMatch, charCode); } // we've found two mnemonics, just return. return true; @@ -2891,11 +3421,13 @@ private bool ProcessMnemonicInternal(char charCode) { } } // We've found a singular match. - if (firstMatch != null) { + if (firstMatch != null) + { return firstMatch.ProcessMnemonic(charCode); } - if (!foundMenuItem) { + if (!foundMenuItem) + { return false; } @@ -2904,42 +3436,51 @@ private bool ProcessMnemonicInternal(char charCode) { // MenuStrip parity: key presses should change selection if mnemonic not present // if we havent found a mnemonic, cycle through the menu items and // checbbbMk if we match. - + // PASS2, iterate through the pseudo mnemonics - for (int i = 0; i < DisplayedItems.Count; i++) { + for (int i = 0; i < DisplayedItems.Count; i++) + { ToolStripItem currentItem = DisplayedItems[index]; - index = (index +1)%DisplayedItems.Count; + index = (index + 1) % DisplayedItems.Count; // Menu items only - if (!(currentItem is ToolStripMenuItem) || string.IsNullOrEmpty(currentItem.Text) || !currentItem.Enabled) { + if (!(currentItem is ToolStripMenuItem) || string.IsNullOrEmpty(currentItem.Text) || !currentItem.Enabled) + { continue; } // Only items which display text should be processed - if ((currentItem.DisplayStyle & ToolStripItemDisplayStyle.Text) != ToolStripItemDisplayStyle.Text) { + if ((currentItem.DisplayStyle & ToolStripItemDisplayStyle.Text) != ToolStripItemDisplayStyle.Text) + { continue; } - - if (ToolStrip.IsPseudoMnemonic(charCode,currentItem.Text)) { - if (firstMatch == null) { + + if (ToolStrip.IsPseudoMnemonic(charCode, currentItem.Text)) + { + if (firstMatch == null) + { firstMatch = currentItem; } - else { + else + { // we've found a second match - we should only change selection. - if (firstMatch == startingItem) { + if (firstMatch == startingItem) + { // change the selection to be the second match as the first is already selected - ProcessDuplicateMnemonic(currentItem, charCode); + ProcessDuplicateMnemonic(currentItem, charCode); } - else { - ProcessDuplicateMnemonic(firstMatch, charCode); + else + { + ProcessDuplicateMnemonic(firstMatch, charCode); } // we've found two mnemonics, just return. return true; } } } - - if (firstMatch != null) { + + if (firstMatch != null) + { return firstMatch.ProcessMnemonic(charCode); } @@ -2952,21 +3493,25 @@ private bool ProcessMnemonicInternal(char charCode) { /// Summary of ProcessTabKey. /// /// - private bool ProcessTabKey(bool forward) { - if (TabStop) { - // ToolBar in tab-order parity - // this means we want the toolstrip in the normal tab order - which means it shouldnt wrap. - // First tab gets you into the toolstrip, second tab moves you on your way outside the container. - // arrow keys would continue to wrap. - return false; - } - else { + private bool ProcessTabKey(bool forward) + { + if (TabStop) + { + // ToolBar in tab-order parity + // this means we want the toolstrip in the normal tab order - which means it shouldnt wrap. + // First tab gets you into the toolstrip, second tab moves you on your way outside the container. + // arrow keys would continue to wrap. + return false; + } + else + { // TabStop = false // this means we dont want the toolstrip in the normal tab order (default). // We got focus to the toolstrip by putting focus into a control contained on the toolstrip or // via a mnemonic e.g. Bold. In this case we want to wrap. // arrow keys would continue to wrap - if (RightToLeft == RightToLeft.Yes) { + if (RightToLeft == RightToLeft.Yes) + { forward = !forward; } SelectNextToolStripItem(GetSelectedItem(), forward); @@ -2981,37 +3526,44 @@ private bool ProcessTabKey(bool forward) { /// call down to the base first. Unfortunately doing this would cause the the arrow keys would be eaten /// in the base class. Instead we're providing a separate place to override all arrow key handling. /// - internal virtual bool ProcessArrowKey(Keys keyCode) { + internal virtual bool ProcessArrowKey(Keys keyCode) + { bool retVal = false; Debug.WriteLineIf(MenuAutoExpandDebug.TraceVerbose, "[ToolStrip.ProcessArrowKey] MenuTimer.Cancel called"); ToolStripMenuItem.MenuTimer.Cancel(); - switch (keyCode) { - case Keys.Left: - case Keys.Right: - retVal = ProcessLeftRightArrowKey(keyCode == Keys.Right); - break; - case Keys.Up: - case Keys.Down: - if (IsDropDown || Orientation != Orientation.Horizontal) { - ToolStripItem currentSel = GetSelectedItem(); - if (keyCode == Keys.Down) { - ToolStripItem nextItem = GetNextItem(currentSel, ArrowDirection.Down); - if (nextItem != null) { - ChangeSelection(nextItem); - retVal = true; - } + switch (keyCode) + { + case Keys.Left: + case Keys.Right: + retVal = ProcessLeftRightArrowKey(keyCode == Keys.Right); + break; + case Keys.Up: + case Keys.Down: + if (IsDropDown || Orientation != Orientation.Horizontal) + { + ToolStripItem currentSel = GetSelectedItem(); + if (keyCode == Keys.Down) + { + ToolStripItem nextItem = GetNextItem(currentSel, ArrowDirection.Down); + if (nextItem != null) + { + ChangeSelection(nextItem); + retVal = true; } - else { - ToolStripItem nextItem = GetNextItem(currentSel, ArrowDirection.Up); - if (nextItem != null){ - ChangeSelection(nextItem); - retVal = true; - } + } + else + { + ToolStripItem nextItem = GetNextItem(currentSel, ArrowDirection.Up); + if (nextItem != null) + { + ChangeSelection(nextItem); + retVal = true; } } - break; + } + break; } return retVal; } @@ -3020,7 +3572,8 @@ internal virtual bool ProcessArrowKey(Keys keyCode) { /// Process an arrowKey press by selecting the next control in the group /// that the activeControl belongs to. /// - private bool ProcessLeftRightArrowKey(bool right) { + private bool ProcessLeftRightArrowKey(bool right) + { ToolStripItem selectedItem = GetSelectedItem(); ToolStripItem nextItem = SelectNextToolStripItem(GetSelectedItem(), right); return true; @@ -3030,25 +3583,31 @@ private bool ProcessLeftRightArrowKey(bool right) { /// Summary of NotifySelectionChange. /// /// - internal void NotifySelectionChange(ToolStripItem item) { - if (item == null) { + internal void NotifySelectionChange(ToolStripItem item) + { + if (item == null) + { Debug.WriteLineIf(SelectionDebug.TraceVerbose, "[SelectDBG NotifySelectionChange] none should be selected"); ClearAllSelections(); } - else if (item.Selected) { + else if (item.Selected) + { Debug.WriteLineIf(SelectionDebug.TraceVerbose, "[SelectDBG NotifySelectionChange] Notify selection change: " + item.ToString() + ": " + item.Selected.ToString()); ClearAllSelectionsExcept(item); } } - private void OnDefaultRendererChanged(object sender, EventArgs e) { + private void OnDefaultRendererChanged(object sender, EventArgs e) + { // callback from static event - if (GetToolStripState(STATE_USEDEFAULTRENDERER)) { + if (GetToolStripState(STATE_USEDEFAULTRENDERER)) + { OnRendererChanged(e); } } - protected virtual void OnBeginDrag(EventArgs e) { + protected virtual void OnBeginDrag(EventArgs e) + { SetToolStripState(STATE_DRAGGING, true); Debug.Assert(ToolStripPanelRow != null, "Why is toolstrippanel row null?"); Debug.Assert(this.ParentInternal as ToolStripPanel != null, "Why is our parent not a toolstrip panel?"); @@ -3056,64 +3615,78 @@ protected virtual void OnBeginDrag(EventArgs e) { ClearAllSelections(); UpdateToolTip(null); // supress the tooltip. EventHandler handler = (EventHandler)Events[EventBeginDrag]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } - protected virtual void OnEndDrag(EventArgs e) { + protected virtual void OnEndDrag(EventArgs e) + { SetToolStripState(STATE_DRAGGING, false); Debug.Assert(ToolStripPanelRow != null, "Why is toolstrippanel row null?"); Debug.Assert(this.ParentInternal as ToolStripPanel != null, "Why is our parent not a toolstrip panel?"); Debug.Assert(ToolStripPanelRow == null || ToolStripPanelRow.ToolStripPanel.RowsInternal.Contains(ToolStripPanelRow), "Why are we in an orphaned row?"); - + EventHandler handler = (EventHandler)Events[EventEndDrag]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } - protected override void OnDockChanged(EventArgs e){ + protected override void OnDockChanged(EventArgs e) + { base.OnDockChanged(e); } - protected virtual void OnRendererChanged(EventArgs e) { - InitializeRenderer(Renderer); + protected virtual void OnRendererChanged(EventArgs e) + { + InitializeRenderer(Renderer); - EventHandler handler = (EventHandler)Events[EventRendererChanged]; - if (handler != null) handler(this,e); + EventHandler handler = (EventHandler)Events[EventRendererChanged]; + if (handler != null) + handler(this, e); } /// /// Summary of OnEnabledChanged. /// - protected override void OnEnabledChanged(EventArgs e) { + protected override void OnEnabledChanged(EventArgs e) + { base.OnEnabledChanged(e); // notify items that the parent has changed - for (int i = 0; i < this.Items.Count; i++) { - if (Items[i] != null && Items[i].ParentInternal == this) { + for (int i = 0; i < this.Items.Count; i++) + { + if (Items[i] != null && Items[i].ParentInternal == this) + { Items[i].OnParentEnabledChanged(e); } } } - - internal void OnDefaultFontChanged() { + + internal void OnDefaultFontChanged() + { defaultFont = null; - if (!IsFontSet()) { + if (!IsFontSet()) + { OnFontChanged(EventArgs.Empty); } } - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { base.OnFontChanged(e); - for (int i = 0; i < this.Items.Count; i++) { - Items[i].OnOwnerFontChanged(e); + for (int i = 0; i < this.Items.Count; i++) + { + Items[i].OnOwnerFontChanged(e); } } - protected override void OnInvalidated(InvalidateEventArgs e) { + protected override void OnInvalidated(InvalidateEventArgs e) + { base.OnInvalidated(e); #if false // DEBUG code which is helpful for FlickerFest debugging. @@ -3138,8 +3711,10 @@ protected override void OnInvalidated(InvalidateEventArgs e) { /// /// Summary of OnHandleCreated. /// - protected override void OnHandleCreated(EventArgs e) { - if ((this.AllowDrop || this.AllowItemReorder) && (DropTargetManager != null)) { + protected override void OnHandleCreated(EventArgs e) + { + if ((this.AllowDrop || this.AllowItemReorder) && (DropTargetManager != null)) + { this.DropTargetManager.EnsureRegistered(this); } @@ -3151,18 +3726,22 @@ protected override void OnHandleCreated(EventArgs e) { /// /// Summary of OnHandleDestroyed. /// - protected override void OnHandleDestroyed(EventArgs e) { - if (DropTargetManager != null) { + protected override void OnHandleDestroyed(EventArgs e) + { + if (DropTargetManager != null) + { // Make sure we unregister ourselves as a drop target this.DropTargetManager.EnsureUnRegistered(this); } base.OnHandleDestroyed(e); } - protected internal virtual void OnItemAdded(ToolStripItemEventArgs e) { + protected internal virtual void OnItemAdded(ToolStripItemEventArgs e) + { DoLayoutIfHandleCreated(e); - if (!HasVisibleItems && e.Item != null && ((IArrangedElement)e.Item).ParticipatesInLayout) { + if (!HasVisibleItems && e.Item != null && ((IArrangedElement)e.Item).ParticipatesInLayout) + { // in certain cases, we may not have laid out yet (e.g. a dropdown may not layout until // it becomes visible.) We will recalculate this in SetDisplayedItems, but for the moment // if we find an item that ParticipatesInLayout, mark us as having visible items. @@ -3170,56 +3749,69 @@ protected internal virtual void OnItemAdded(ToolStripItemEventArgs e) { } ToolStripItemEventHandler handler = (ToolStripItemEventHandler)Events[EventItemAdded]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// Called when an item has been clicked on the ToolStrip. /// - protected virtual void OnItemClicked(ToolStripItemClickedEventArgs e) { + protected virtual void OnItemClicked(ToolStripItemClickedEventArgs e) + { ToolStripItemClickedEventHandler handler = (ToolStripItemClickedEventHandler)Events[EventItemClicked]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } - protected internal virtual void OnItemRemoved(ToolStripItemEventArgs e) { + protected internal virtual void OnItemRemoved(ToolStripItemEventArgs e) + { // clear cached item states. OnItemVisibleChanged(e, /*performlayout*/true); ToolStripItemEventHandler handler = (ToolStripItemEventHandler)Events[EventItemRemoved]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } - - internal void OnItemVisibleChanged(ToolStripItemEventArgs e, bool performLayout) { - + + internal void OnItemVisibleChanged(ToolStripItemEventArgs e, bool performLayout) + { + // clear cached item states. - if (e.Item == lastMouseActiveItem) { + if (e.Item == lastMouseActiveItem) + { lastMouseActiveItem = null; } - if (e.Item == LastMouseDownedItem) { + if (e.Item == LastMouseDownedItem) + { lastMouseDownedItem = null; } - if (e.Item == currentlyActiveTooltipItem) { + if (e.Item == currentlyActiveTooltipItem) + { UpdateToolTip(null); } - if (performLayout) { + if (performLayout) + { DoLayoutIfHandleCreated(e); } } - protected override void OnLayout(LayoutEventArgs e) { + protected override void OnLayout(LayoutEventArgs e) + { this.LayoutRequired = false; // we need to do this to prevent autosizing to happen while we're reparenting. ToolStripOverflow overflow = GetOverflow(); - if (overflow != null) { - overflow.SuspendLayout(); - toolStripOverflowButton.Size = toolStripOverflowButton.GetPreferredSize(this.DisplayRectangle.Size - this.Padding.Size); + if (overflow != null) + { + overflow.SuspendLayout(); + toolStripOverflowButton.Size = toolStripOverflowButton.GetPreferredSize(this.DisplayRectangle.Size - this.Padding.Size); } - for (int j = 0; j < Items.Count; j++) { - Items[j].OnLayout(e); + for (int j = 0; j < Items.Count; j++) + { + Items[j].OnLayout(e); } base.OnLayout(e); @@ -3227,53 +3819,66 @@ protected override void OnLayout(LayoutEventArgs e) { OnLayoutCompleted(EventArgs.Empty); Invalidate(); - if (overflow != null) { + if (overflow != null) + { overflow.ResumeLayout(); } } - protected virtual void OnLayoutCompleted(EventArgs e) { + protected virtual void OnLayoutCompleted(EventArgs e) + { EventHandler handler = (EventHandler)Events[EventLayoutCompleted]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } - protected virtual void OnLayoutStyleChanged(EventArgs e) { - EventHandler handler = (EventHandler)Events[EventLayoutStyleChanged]; - if (handler != null) handler(this, e); + protected virtual void OnLayoutStyleChanged(EventArgs e) + { + EventHandler handler = (EventHandler)Events[EventLayoutStyleChanged]; + if (handler != null) + handler(this, e); } - protected override void OnLostFocus(EventArgs e) { + protected override void OnLostFocus(EventArgs e) + { base.OnLostFocus(e); ClearAllSelections(); } - protected override void OnLeave(EventArgs e) { + protected override void OnLeave(EventArgs e) + { base.OnLeave(e); - if (!IsDropDown) { + if (!IsDropDown) + { Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "uninstalling RestoreFocusFilter"); - + // PERF, - Application.ThreadContext.FromCurrent().RemoveMessageFilter(RestoreFocusFilter); + Application.ThreadContext.FromCurrent().RemoveMessageFilter(RestoreFocusFilter); } } - internal virtual void OnLocationChanging(ToolStripLocationCancelEventArgs e) { + internal virtual void OnLocationChanging(ToolStripLocationCancelEventArgs e) + { ToolStripLocationCancelEventHandler handler = (ToolStripLocationCancelEventHandler)Events[EventLocationChanging]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// Delegate mouse down to the ToolStrip and its affected items /// - protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs mea) { + protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs mea) + { // NEVER use this directly from another class. Always use GetMouseID so that // 0 is not returned to another class. mouseDownID++; - + ToolStripItem item = GetItemAt(mea.X, mea.Y); - if (item != null) { - if (!IsDropDown && (!(item is ToolStripDropDownItem))){ + if (item != null) + { + if (!IsDropDown && (!(item is ToolStripDropDownItem))) + { // set capture only when we know we're not on a dropdown (already effectively have capture due to modal menufilter) // and the item in question requires the mouse to be in the same item to be clicked. SetToolStripState(STATE_LASTMOUSEDOWNEDITEMCAPTURE, true); @@ -3281,30 +3886,34 @@ protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs mea) { } MenuAutoExpand = true; - if (mea != null) { + if (mea != null) + { // Transpose this to "client coordinates" of the ToolStripItem. Point itemRelativePoint = item.TranslatePoint(new Point(mea.X, mea.Y), ToolStripPointType.ToolStripCoords, ToolStripPointType.ToolStripItemCoords); - mea = new MouseEventArgs(mea.Button, mea.Clicks,itemRelativePoint.X, itemRelativePoint.Y, mea.Delta); + mea = new MouseEventArgs(mea.Button, mea.Clicks, itemRelativePoint.X, itemRelativePoint.Y, mea.Delta); } lastMouseDownedItem = item; item.FireEvent(mea, ToolStripItemEventType.MouseDown); } - else { + else + { base.OnMouseDown(mea); } } - + /// /// Delegate mouse moves to the ToolStrip and its affected items /// - protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs mea) { - Debug.WriteLineIf(ToolStripItem.MouseDebugging.TraceVerbose,"OnMouseMove called"); - + protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs mea) + { + Debug.WriteLineIf(ToolStripItem.MouseDebugging.TraceVerbose, "OnMouseMove called"); + ToolStripItem item = GetItemAt(mea.X, mea.Y); - if (!Grip.MovingToolStrip) { + if (!Grip.MovingToolStrip) + { // If we had a particular item that was "entered" // notify it that we have entered. It's fair to put @@ -3313,9 +3922,10 @@ protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs mea) { // the actual coordinates. - Debug.WriteLineIf(ToolStripItem.MouseDebugging.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "Item to get mouse move: {0}", (item == null) ? "null" : item.ToString())); - if (item != lastMouseActiveItem) { - Debug.WriteLineIf(ToolStripItem.MouseDebugging.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "This is a new item - last item to get was {0}", (lastMouseActiveItem == null) ? "null" : lastMouseActiveItem.ToString())); + Debug.WriteLineIf(ToolStripItem.MouseDebugging.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "Item to get mouse move: {0}", (item == null) ? "null" : item.ToString())); + if (item != lastMouseActiveItem) + { + Debug.WriteLineIf(ToolStripItem.MouseDebugging.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "This is a new item - last item to get was {0}", (lastMouseActiveItem == null) ? "null" : lastMouseActiveItem.ToString())); // notify the item that we've moved on HandleMouseLeave(); @@ -3323,13 +3933,15 @@ protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs mea) { // track only items that dont get mouse events themselves. lastMouseActiveItem = (item is ToolStripControlHost) ? null : item; - if (lastMouseActiveItem != null) { - Debug.WriteLineIf(ToolStripItem.MouseDebugging.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "Firing MouseEnter on: {0}", (lastMouseActiveItem == null) ? "null" : lastMouseActiveItem.ToString())); + if (lastMouseActiveItem != null) + { + Debug.WriteLineIf(ToolStripItem.MouseDebugging.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "Firing MouseEnter on: {0}", (lastMouseActiveItem == null) ? "null" : lastMouseActiveItem.ToString())); item.FireEvent(EventArgs.Empty, ToolStripItemEventType.MouseEnter); } // - if (!DesignMode) { + if (!DesignMode) + { MouseHoverTimer.Start(lastMouseActiveItem); } @@ -3337,20 +3949,23 @@ protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs mea) { } } - else { + else + { item = this.Grip; } - if (item != null) { - Debug.WriteLineIf(ToolStripItem.MouseDebugging.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "Firing MouseMove on: {0}", (item == null) ? "null" : item.ToString())); + if (item != null) + { + Debug.WriteLineIf(ToolStripItem.MouseDebugging.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "Firing MouseMove on: {0}", (item == null) ? "null" : item.ToString())); // Fire mouse move on the item // Transpose this to "client coordinates" of the ToolStripItem. Point itemRelativePoint = item.TranslatePoint(new Point(mea.X, mea.Y), ToolStripPointType.ToolStripCoords, ToolStripPointType.ToolStripItemCoords); - mea = new MouseEventArgs(mea.Button, mea.Clicks,itemRelativePoint.X, itemRelativePoint.Y, mea.Delta); + mea = new MouseEventArgs(mea.Button, mea.Clicks, itemRelativePoint.X, itemRelativePoint.Y, mea.Delta); item.FireEvent(mea, ToolStripItemEventType.MouseMove); } - else { - Debug.WriteLineIf(ToolStripItem.MouseDebugging.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "Firing MouseMove on: {0}", (this == null) ? "null" : this.ToString())); + else + { + Debug.WriteLineIf(ToolStripItem.MouseDebugging.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "Firing MouseMove on: {0}", (this == null) ? "null" : this.ToString())); base.OnMouseMove(mea); } @@ -3361,211 +3976,240 @@ protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs mea) { /// /// Delegate mouse leave to the ToolStrip and its affected items /// - protected override void OnMouseLeave(System.EventArgs e) { + protected override void OnMouseLeave(System.EventArgs e) + { HandleMouseLeave(); base.OnMouseLeave(e); } - - - protected override void OnMouseCaptureChanged(System.EventArgs e) { - if (!GetToolStripState(STATE_SUSPENDCAPTURE)) { + + + protected override void OnMouseCaptureChanged(System.EventArgs e) + { + if (!GetToolStripState(STATE_SUSPENDCAPTURE)) + { // while we're showing a feedback rect, dont cancel moving the toolstrip. Grip.MovingToolStrip = false; } ClearLastMouseDownedItem(); - - + + base.OnMouseCaptureChanged(e); } /// /// Delegate mouse up to the ToolStrip and its affected items /// - protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs mea) { - + protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs mea) + { + ToolStripItem item = (Grip.MovingToolStrip) ? Grip : GetItemAt(mea.X, mea.Y); - if (item != null) { - if (mea != null) { + if (item != null) + { + if (mea != null) + { // Transpose this to "client coordinates" of the ToolStripItem. Point itemRelativePoint = item.TranslatePoint(new Point(mea.X, mea.Y), ToolStripPointType.ToolStripCoords, ToolStripPointType.ToolStripItemCoords); - mea = new MouseEventArgs(mea.Button, mea.Clicks,itemRelativePoint.X, itemRelativePoint.Y, mea.Delta); + mea = new MouseEventArgs(mea.Button, mea.Clicks, itemRelativePoint.X, itemRelativePoint.Y, mea.Delta); } item.FireEvent(mea, ToolStripItemEventType.MouseUp); } - else { + else + { base.OnMouseUp(mea); } ClearLastMouseDownedItem(); - + } - protected override void OnPaint(PaintEventArgs e) { - base.OnPaint(e); + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + + Graphics toolstripGraphics = e.Graphics; + Size bitmapSize = this.largestDisplayedItemSize; + bool excludedTransparentRegion = false; - Graphics toolstripGraphics = e.Graphics; - Size bitmapSize = this.largestDisplayedItemSize; - bool excludedTransparentRegion = false; + Rectangle viewableArea = this.DisplayRectangle; + Region transparentRegion = Renderer.GetTransparentRegion(this); - Rectangle viewableArea = this.DisplayRectangle; - Region transparentRegion = Renderer.GetTransparentRegion(this); - - try { + try + { - // Paint the items - // The idea here is to let items pretend they are controls. - // they should get paint events at 0,0 and have proper clipping regions - // set up for them. We cannot use g.TranslateTransform as that does - // not translate the GDI world, and things like Visual Styles and the - // TextRenderer only know how to speak GDI. - // - // The previous appropach was to set up the GDI clipping region and allocate a graphics - // from that, but that meant we were allocating graphics objects left and right, which - // turned out to be slow. - // - // So now we allocate an offscreen bitmap of size == MaxItemSize, copy the background - // of the toolstrip into that bitmap, then paint the item on top of the bitmap, then copy - // the contents of the bitmap back onto the toolstrip. This gives us our paint event starting - // at 0,0. Combine this with double buffering of the toolstrip and the entire toolstrip is updated - // after returning from this function. - if (!LayoutUtils.IsZeroWidthOrHeight(bitmapSize)) { + // Paint the items + // The idea here is to let items pretend they are controls. + // they should get paint events at 0,0 and have proper clipping regions + // set up for them. We cannot use g.TranslateTransform as that does + // not translate the GDI world, and things like Visual Styles and the + // TextRenderer only know how to speak GDI. + // + // The previous appropach was to set up the GDI clipping region and allocate a graphics + // from that, but that meant we were allocating graphics objects left and right, which + // turned out to be slow. + // + // So now we allocate an offscreen bitmap of size == MaxItemSize, copy the background + // of the toolstrip into that bitmap, then paint the item on top of the bitmap, then copy + // the contents of the bitmap back onto the toolstrip. This gives us our paint event starting + // at 0,0. Combine this with double buffering of the toolstrip and the entire toolstrip is updated + // after returning from this function. + if (!LayoutUtils.IsZeroWidthOrHeight(bitmapSize)) + { // cant create a 0x0 bmp. - // Supporting RoundedEdges... - // we've got a concept of a region that we shouldnt paint (the TransparentRegion as specified in the Renderer). - // in order to support this we're going to intersect that region with the clipping region. - // this new region will be excluded during the guts of OnPaint, and restored at the end of OnPaint. - if (transparentRegion != null) { - // only use the intersection so we can easily add back in the bits we took out at the end. - transparentRegion.Intersect(toolstripGraphics.Clip); - toolstripGraphics.ExcludeClip(transparentRegion); - excludedTransparentRegion = true; - } - - // Preparing for painting the individual items... - // using WindowsGraphics here because we want to preserve the clipping information. - - // calling GetHdc by itself does not set up the clipping info. - using(WindowsGraphics toolStripWindowsGraphics = WindowsGraphics.FromGraphics(toolstripGraphics, ApplyGraphicsProperties.Clipping)){ - // get the cached item HDC. - HandleRef toolStripHDC = new HandleRef(this, toolStripWindowsGraphics.GetHdc()); - HandleRef itemHDC = ItemHdcInfo.GetCachedItemDC(toolStripHDC, bitmapSize); - - Graphics itemGraphics = Graphics.FromHdcInternal(itemHDC.Handle); - try { - // Painting the individual items... - // iterate through all the items, painting them - // one by one into the compatible offscreen DC, and then copying - // them back onto the main toolstrip. - for (int i = 0; i < DisplayedItems.Count; i++) { - ToolStripItem item = DisplayedItems[i]; - if (item != null) { // - Rectangle clippingRect = e.ClipRectangle; - Rectangle bounds = item.Bounds; - - if (!IsDropDown && item.Owner == this) { - // owned items should not paint outside the client - // area. (this is mainly to prevent obscuring the grip - // and overflowbutton - ToolStripDropDownMenu places items - // outside of the display rectangle - so we need to allow for this - // in dropdoowns). - clippingRect.Intersect(viewableArea); - } - - // get the intersection of these two. - clippingRect.Intersect(bounds); - - if (LayoutUtils.IsZeroWidthOrHeight(clippingRect)) { - continue; // no point newing up a graphics object if there's nothing to paint. - } - - Size itemSize = item.Size; - - // check if our item buffer is large enough to handle. - if (!LayoutUtils.AreWidthAndHeightLarger(bitmapSize, itemSize)) { - // the cached HDC isnt big enough for this item. make it bigger. - this.largestDisplayedItemSize = itemSize; - bitmapSize = itemSize; - // dispose the old graphics - create a new, bigger one. - itemGraphics.Dispose(); - - // calling this should take the existing DC and select in a bigger bitmap. - itemHDC = ItemHdcInfo.GetCachedItemDC(toolStripHDC, bitmapSize); - - // allocate a new graphics. - itemGraphics = Graphics.FromHdcInternal(itemHDC.Handle); - - } - // since the item graphics object will have 0,0 at the - // corner we need to actually shift the origin of the rect over - // so it will be 0,0 too. - clippingRect.Offset(-bounds.X, -bounds.Y); - - // PERF - consider - we only actually need to copy the clipping rect. - // copy the background from the toolstrip onto the offscreen bitmap - SafeNativeMethods.BitBlt(itemHDC, 0, 0, item.Size.Width, item.Size.Height, toolStripHDC, item.Bounds.X, item.Bounds.Y, NativeMethods.SRCCOPY); - - // paint the item into the offscreen bitmap - using (PaintEventArgs itemPaintEventArgs = new PaintEventArgs(itemGraphics, clippingRect)) { - item.FireEvent(itemPaintEventArgs, ToolStripItemEventType.Paint); - } - - // copy the item back onto the toolstrip - SafeNativeMethods.BitBlt(toolStripHDC, item.Bounds.X, item.Bounds.Y, item.Size.Width, item.Size.Height, itemHDC, 0, 0, NativeMethods.SRCCOPY); + // Supporting RoundedEdges... + // we've got a concept of a region that we shouldnt paint (the TransparentRegion as specified in the Renderer). + // in order to support this we're going to intersect that region with the clipping region. + // this new region will be excluded during the guts of OnPaint, and restored at the end of OnPaint. + if (transparentRegion != null) + { + // only use the intersection so we can easily add back in the bits we took out at the end. + transparentRegion.Intersect(toolstripGraphics.Clip); + toolstripGraphics.ExcludeClip(transparentRegion); + excludedTransparentRegion = true; + } + + // Preparing for painting the individual items... + // using WindowsGraphics here because we want to preserve the clipping information. + + // calling GetHdc by itself does not set up the clipping info. + using (WindowsGraphics toolStripWindowsGraphics = WindowsGraphics.FromGraphics(toolstripGraphics, ApplyGraphicsProperties.Clipping)) + { + // get the cached item HDC. + HandleRef toolStripHDC = new HandleRef(this, toolStripWindowsGraphics.GetHdc()); + HandleRef itemHDC = ItemHdcInfo.GetCachedItemDC(toolStripHDC, bitmapSize); + + Graphics itemGraphics = Graphics.FromHdcInternal(itemHDC.Handle); + try + { + // Painting the individual items... + // iterate through all the items, painting them + // one by one into the compatible offscreen DC, and then copying + // them back onto the main toolstrip. + for (int i = 0; i < DisplayedItems.Count; i++) + { + ToolStripItem item = DisplayedItems[i]; + if (item != null) + { // + Rectangle clippingRect = e.ClipRectangle; + Rectangle bounds = item.Bounds; + if (!IsDropDown && item.Owner == this) + { + // owned items should not paint outside the client + // area. (this is mainly to prevent obscuring the grip + // and overflowbutton - ToolStripDropDownMenu places items + // outside of the display rectangle - so we need to allow for this + // in dropdoowns). + clippingRect.Intersect(viewableArea); } + + // get the intersection of these two. + clippingRect.Intersect(bounds); + + if (LayoutUtils.IsZeroWidthOrHeight(clippingRect)) + { + continue; // no point newing up a graphics object if there's nothing to paint. + } + + Size itemSize = item.Size; + + // check if our item buffer is large enough to handle. + if (!LayoutUtils.AreWidthAndHeightLarger(bitmapSize, itemSize)) + { + // the cached HDC isnt big enough for this item. make it bigger. + this.largestDisplayedItemSize = itemSize; + bitmapSize = itemSize; + // dispose the old graphics - create a new, bigger one. + itemGraphics.Dispose(); + + // calling this should take the existing DC and select in a bigger bitmap. + itemHDC = ItemHdcInfo.GetCachedItemDC(toolStripHDC, bitmapSize); + + // allocate a new graphics. + itemGraphics = Graphics.FromHdcInternal(itemHDC.Handle); + + } + // since the item graphics object will have 0,0 at the + // corner we need to actually shift the origin of the rect over + // so it will be 0,0 too. + clippingRect.Offset(-bounds.X, -bounds.Y); + + // PERF - consider - we only actually need to copy the clipping rect. + // copy the background from the toolstrip onto the offscreen bitmap + SafeNativeMethods.BitBlt(itemHDC, 0, 0, item.Size.Width, item.Size.Height, toolStripHDC, item.Bounds.X, item.Bounds.Y, NativeMethods.SRCCOPY); + + // paint the item into the offscreen bitmap + using (PaintEventArgs itemPaintEventArgs = new PaintEventArgs(itemGraphics, clippingRect)) + { + item.FireEvent(itemPaintEventArgs, ToolStripItemEventType.Paint); + } + + // copy the item back onto the toolstrip + SafeNativeMethods.BitBlt(toolStripHDC, item.Bounds.X, item.Bounds.Y, item.Size.Width, item.Size.Height, itemHDC, 0, 0, NativeMethods.SRCCOPY); + } - } - finally { - if (itemGraphics != null) { - itemGraphics.Dispose(); - } - } - } + } + } + finally + { + if (itemGraphics != null) + { + itemGraphics.Dispose(); + } + } + } - } + } + + // Painting the edge effects... + // These would include things like (shadow line on the bottom, some overflow effects) + Renderer.DrawToolStripBorder(new ToolStripRenderEventArgs(toolstripGraphics, this)); - // Painting the edge effects... - // These would include things like (shadow line on the bottom, some overflow effects) - Renderer.DrawToolStripBorder(new ToolStripRenderEventArgs(toolstripGraphics, this)); + // Restoring the clip region to its original state... + // the transparent region should be added back in as the insertion mark should paint over it. + if (excludedTransparentRegion) + { + toolstripGraphics.SetClip(transparentRegion, CombineMode.Union); + } - // Restoring the clip region to its original state... - // the transparent region should be added back in as the insertion mark should paint over it. - if (excludedTransparentRegion) { - toolstripGraphics.SetClip(transparentRegion,CombineMode.Union); - } - - // Paint the item re-order insertion mark... - // This should ignore the transparent region and paint - // over the entire area. - PaintInsertionMark(toolstripGraphics); - } - finally { - if (transparentRegion != null) { - transparentRegion.Dispose(); - } - } + // Paint the item re-order insertion mark... + // This should ignore the transparent region and paint + // over the entire area. + PaintInsertionMark(toolstripGraphics); + } + finally + { + if (transparentRegion != null) + { + transparentRegion.Dispose(); + } + } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnRightToLeftChanged(EventArgs e) { + protected override void OnRightToLeftChanged(EventArgs e) + { base.OnRightToLeftChanged(e); // normally controls just need to do handle recreation, but ToolStrip does it based on layout of items. - using(new LayoutTransaction(this, this, PropertyNames.RightToLeft)) { - for (int i = 0; i < Items.Count; i++) { + using (new LayoutTransaction(this, this, PropertyNames.RightToLeft)) + { + for (int i = 0; i < Items.Count; i++) + { Items[i].OnParentRightToLeftChanged(e); } - if (toolStripOverflowButton != null) { + if (toolStripOverflowButton != null) + { toolStripOverflowButton.OnParentRightToLeftChanged(e); } - if (toolStripGrip != null) { + if (toolStripGrip != null) + { toolStripGrip.OnParentRightToLeftChanged(e); } } @@ -3580,67 +4224,83 @@ protected override void OnRightToLeftChanged(EventArgs e) { /// Windows behavior you must set event.handled to true. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnPaintBackground(PaintEventArgs e) { + protected override void OnPaintBackground(PaintEventArgs e) + { base.OnPaintBackground(e); Graphics g = e.Graphics; GraphicsState graphicsState = g.Save(); - try { - using (Region transparentRegion = Renderer.GetTransparentRegion(this)) { - if (transparentRegion != null) { + try + { + using (Region transparentRegion = Renderer.GetTransparentRegion(this)) + { + if (transparentRegion != null) + { EraseCorners(e, transparentRegion); g.ExcludeClip(transparentRegion); } } Renderer.DrawToolStripBackground(new ToolStripRenderEventArgs(g, this)); - + } - finally { - if (graphicsState != null) { + finally + { + if (graphicsState != null) + { g.Restore(graphicsState); } } } - protected override void OnVisibleChanged(EventArgs e) { + protected override void OnVisibleChanged(EventArgs e) + { base.OnVisibleChanged(e); - if (!Disposing && !IsDisposed) { + if (!Disposing && !IsDisposed) + { HookStaticEvents(Visible); } } - - private void EraseCorners(PaintEventArgs e, Region transparentRegion) { - if (transparentRegion != null) { - PaintTransparentBackground(e, ClientRectangle, transparentRegion); + + private void EraseCorners(PaintEventArgs e, Region transparentRegion) + { + if (transparentRegion != null) + { + PaintTransparentBackground(e, ClientRectangle, transparentRegion); } } /// /// Summary of OnPaint. /// - internal protected virtual void OnPaintGrip(System.Windows.Forms.PaintEventArgs e) { + internal protected virtual void OnPaintGrip(System.Windows.Forms.PaintEventArgs e) + { Renderer.DrawGrip(new ToolStripGripRenderEventArgs(e.Graphics, this)); PaintEventHandler handler = (PaintEventHandler)Events[EventPaintGrip]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } - protected override void OnScroll(ScrollEventArgs se) { + protected override void OnScroll(ScrollEventArgs se) + { - if (se.Type != ScrollEventType.ThumbTrack && se.NewValue != se.OldValue) { - ScrollInternal(se.OldValue - se.NewValue); + if (se.Type != ScrollEventType.ThumbTrack && se.NewValue != se.OldValue) + { + ScrollInternal(se.OldValue - se.NewValue); } base.OnScroll(se); } - private void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e) { - switch (e.Category) { + private void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e) + { + switch (e.Category) + { case UserPreferenceCategory.Window: OnDefaultFontChanged(); break; @@ -3648,10 +4308,11 @@ private void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventAr InvalidateTextItems(); break; } - + } - protected override void OnTabStopChanged(EventArgs e) { + protected override void OnTabStopChanged(EventArgs e) + { // SelectNextControl can select non-tabstop things. // we need to prevent this by changing the value of "CanSelect" SetStyle(ControlStyles.Selectable, TabStop); @@ -3660,30 +4321,34 @@ protected override void OnTabStopChanged(EventArgs e) { /// /// Paints the I beam when items are being reordered /// - internal void PaintInsertionMark(Graphics g) { - if (lastInsertionMarkRect != Rectangle.Empty) { + internal void PaintInsertionMark(Graphics g) + { + if (lastInsertionMarkRect != Rectangle.Empty) + { int widthOfBeam = insertionBeamWidth; - if (Orientation == Orientation.Horizontal) { - int start = lastInsertionMarkRect.X; - int verticalBeamStart = start + 2; + if (Orientation == Orientation.Horizontal) + { + int start = lastInsertionMarkRect.X; + int verticalBeamStart = start + 2; - // draw two vertical lines - g.DrawLines(SystemPens.ControlText, - new Point[] { new Point(verticalBeamStart, lastInsertionMarkRect.Y), new Point(verticalBeamStart, lastInsertionMarkRect.Bottom-1), // first vertical line + // draw two vertical lines + g.DrawLines(SystemPens.ControlText, + new Point[] { new Point(verticalBeamStart, lastInsertionMarkRect.Y), new Point(verticalBeamStart, lastInsertionMarkRect.Bottom-1), // first vertical line new Point(verticalBeamStart+1, lastInsertionMarkRect.Y), new Point(verticalBeamStart+1, lastInsertionMarkRect.Bottom-1), //second vertical line - }); - // then two top horizontal - g.DrawLines(SystemPens.ControlText, - new Point[] { new Point(start, lastInsertionMarkRect.Bottom-1), new Point(start + widthOfBeam-1, lastInsertionMarkRect.Bottom-1), //bottom line + }); + // then two top horizontal + g.DrawLines(SystemPens.ControlText, + new Point[] { new Point(start, lastInsertionMarkRect.Bottom-1), new Point(start + widthOfBeam-1, lastInsertionMarkRect.Bottom-1), //bottom line new Point(start+1, lastInsertionMarkRect.Bottom -2), new Point(start + widthOfBeam-2, lastInsertionMarkRect.Bottom-2),//bottom second line - }); - // then two bottom horizontal - g.DrawLines(SystemPens.ControlText, - new Point[] { new Point(start, lastInsertionMarkRect.Y), new Point(start + widthOfBeam-1, lastInsertionMarkRect.Y), //top line + }); + // then two bottom horizontal + g.DrawLines(SystemPens.ControlText, + new Point[] { new Point(start, lastInsertionMarkRect.Y), new Point(start + widthOfBeam-1, lastInsertionMarkRect.Y), //top line new Point(start+1, lastInsertionMarkRect.Y+1), new Point(start + widthOfBeam-2, lastInsertionMarkRect.Y+1)//top second line - }); + }); } - else { + else + { widthOfBeam = insertionBeamWidth; int start = lastInsertionMarkRect.Y; @@ -3712,8 +4377,10 @@ internal void PaintInsertionMark(Graphics g) { /// /// Paints the I beam when items are being reordered /// - internal void PaintInsertionMark(Rectangle insertionRect) { - if (lastInsertionMarkRect != insertionRect) { + internal void PaintInsertionMark(Rectangle insertionRect) + { + if (lastInsertionMarkRect != insertionRect) + { ClearInsertionMark(); lastInsertionMarkRect = insertionRect; this.Invalidate(insertionRect); @@ -3721,27 +4388,31 @@ internal void PaintInsertionMark(Rectangle insertionRect) { } [EditorBrowsable(EditorBrowsableState.Never)] - public new Control GetChildAtPoint(Point point) { + public new Control GetChildAtPoint(Point point) + { return base.GetChildAtPoint(point); } [EditorBrowsable(EditorBrowsableState.Never)] - public new Control GetChildAtPoint(Point pt, GetChildAtPointSkip skipValue) { + public new Control GetChildAtPoint(Point pt, GetChildAtPointSkip skipValue) + { return base.GetChildAtPoint(pt, skipValue); } // GetNextControl for ToolStrip should always return null // we do our own tabbing/etc - this allows us to pretend // we dont have child controls. - internal override Control GetFirstChildControlInTabOrder(bool forward) { - return null; + internal override Control GetFirstChildControlInTabOrder(bool forward) + { + return null; } /// /// Finds the ToolStripItem contained within a specified client coordinate point /// If item not found - returns null /// - public ToolStripItem GetItemAt(int x, int y) { - return GetItemAt(new Point(x,y)); + public ToolStripItem GetItemAt(int x, int y) + { + return GetItemAt(new Point(x, y)); } @@ -3749,34 +4420,41 @@ public ToolStripItem GetItemAt(int x, int y) { /// Finds the ToolStripItem contained within a specified client coordinate point /// If item not found - returns null /// - public ToolStripItem GetItemAt(Point point) { + public ToolStripItem GetItemAt(Point point) + { Rectangle comparisonRect = new Rectangle(point, onePixel); Rectangle bounds; // Check the last item we had the mouse over - if (lastMouseActiveItem != null) { + if (lastMouseActiveItem != null) + { bounds = lastMouseActiveItem.Bounds; - if (bounds.IntersectsWith(comparisonRect) && lastMouseActiveItem.ParentInternal == this) { + if (bounds.IntersectsWith(comparisonRect) && lastMouseActiveItem.ParentInternal == this) + { return this.lastMouseActiveItem; } } // Walk the ToolStripItem collection - for (int i = 0; i < this.DisplayedItems.Count; i++) { - if (DisplayedItems[i] == null || DisplayedItems[i].ParentInternal != this) { + for (int i = 0; i < this.DisplayedItems.Count; i++) + { + if (DisplayedItems[i] == null || DisplayedItems[i].ParentInternal != this) + { continue; } bounds = DisplayedItems[i].Bounds; - + // inflate the grip so it is easier to access - if (toolStripGrip != null && DisplayedItems[i] == toolStripGrip) { + if (toolStripGrip != null && DisplayedItems[i] == toolStripGrip) + { bounds = LayoutUtils.InflateRect(bounds, GripMargin); } - if (bounds.IntersectsWith(comparisonRect)) { + if (bounds.IntersectsWith(comparisonRect)) + { return this.DisplayedItems[i]; } } @@ -3785,11 +4463,13 @@ public ToolStripItem GetItemAt(Point point) { } - private void RestoreFocusInternal(bool wasInMenuMode) { + private void RestoreFocusInternal(bool wasInMenuMode) + { // This is called from the RestoreFocusFilter. If the state of MenuMode has changed // since we posted this message, we do not know enough information about whether // we should exit menu mode. - if (wasInMenuMode == ToolStripManager.ModalMenuFilter.InMenuMode) { + if (wasInMenuMode == ToolStripManager.ModalMenuFilter.InMenuMode) + { RestoreFocusInternal(); } } @@ -3797,88 +4477,103 @@ private void RestoreFocusInternal(bool wasInMenuMode) { /// RestoreFocus - returns focus to the control who activated us /// See comment on SnapFocus /// - internal void RestoreFocusInternal() { + internal void RestoreFocusInternal() + { ToolStripManager.ModalMenuFilter.MenuKeyToggle = false; ClearAllSelections(); lastMouseDownedItem = null; - + Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "[ToolStrip.RestoreFocus] Someone has called RestoreFocus, exiting MenuMode."); ToolStripManager.ModalMenuFilter.ExitMenuMode(); - - if (!IsDropDown) { + + if (!IsDropDown) + { // reset menu auto expansion. Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "[ToolStrip.RestoreFocus] Setting menu auto expand to false"); Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "[ToolStrip.RestoreFocus] uninstalling RestoreFocusFilter"); // PERF, - Application.ThreadContext.FromCurrent().RemoveMessageFilter(RestoreFocusFilter); + Application.ThreadContext.FromCurrent().RemoveMessageFilter(RestoreFocusFilter); - MenuAutoExpand = false; + MenuAutoExpand = false; - if (!DesignMode && !TabStop && (Focused || ContainsFocus)) { - RestoreFocus(); + if (!DesignMode && !TabStop && (Focused || ContainsFocus)) + { + RestoreFocus(); } - + } - + // this matches the case where you click on a toolstrip control host // then tab off of it, then hit ESC. ESC would "restore focus" and // we should cancel keyboard activation if this method has cancelled focus. - if (KeyboardActive && !Focused && !ContainsFocus) { + if (KeyboardActive && !Focused && !ContainsFocus) + { KeyboardActive = false; } } - + // override if you want to control (when TabStop = false) where the focus returns to [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void RestoreFocus() { + protected virtual void RestoreFocus() + { + + bool focusSuccess = false; - bool focusSuccess = false; - - if ((hwndThatLostFocus != IntPtr.Zero) && (hwndThatLostFocus != this.Handle)) { + if ((hwndThatLostFocus != IntPtr.Zero) && (hwndThatLostFocus != this.Handle)) + { Control c = Control.FromHandle(hwndThatLostFocus); Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "[ToolStrip RestoreFocus]: Will Restore Focus to: " + WindowsFormsUtils.GetControlInformation(hwndThatLostFocus)); hwndThatLostFocus = IntPtr.Zero; - if ((c != null) && c.Visible) { + if ((c != null) && c.Visible) + { focusSuccess = c.Focus(); } } hwndThatLostFocus = IntPtr.Zero; - - if (!focusSuccess) { + + if (!focusSuccess) + { // clear out the focus, we have focus, we're not supposed to anymore. UnsafeNativeMethods.SetFocus(NativeMethods.NullHandleRef); } } - internal virtual void ResetRenderMode() { + internal virtual void ResetRenderMode() + { RenderMode = ToolStripRenderMode.ManagerRenderMode; } [EditorBrowsable(EditorBrowsableState.Never)] - public void ResetMinimumSize() { - CommonProperties.SetMinimumSize(this, new Size(-1,-1)); + public void ResetMinimumSize() + { + CommonProperties.SetMinimumSize(this, new Size(-1, -1)); } - private void ResetGripMargin() { + private void ResetGripMargin() + { GripMargin = Grip.DefaultMargin; } - internal void ResumeCaputureMode() { + internal void ResumeCaputureMode() + { SetToolStripState(STATE_SUSPENDCAPTURE, false); } - internal void SuspendCaputureMode() { + internal void SuspendCaputureMode() + { SetToolStripState(STATE_SUSPENDCAPTURE, true); } - internal virtual void ScrollInternal(int delta) { + internal virtual void ScrollInternal(int delta) + { SuspendLayout(); - foreach (ToolStripItem item in this.Items) { + foreach (ToolStripItem item in this.Items) + { Point newLocation = item.Bounds.Location; newLocation.Y -= delta; @@ -3894,11 +4589,14 @@ internal virtual void ScrollInternal(int delta) { /// Summary of SetItemLocation /// /// - protected internal void SetItemLocation(ToolStripItem item, Point location) { - if (item == null) { + protected internal void SetItemLocation(ToolStripItem item, Point location) + { + if (item == null) + { throw new ArgumentNullException(nameof(item)); } - if (item.Owner != this) { + if (item.Owner != this) + { throw new NotSupportedException(SR.ToolStripCanOnlyPositionItsOwnItems); } @@ -3907,46 +4605,55 @@ protected internal void SetItemLocation(ToolStripItem item, Point location) { /// /// This is needed so that people doing custom layout engines can change the "Parent" property of the item. /// - protected static void SetItemParent(ToolStripItem item, ToolStrip parent) { - item.Parent = parent; + protected static void SetItemParent(ToolStripItem item, ToolStrip parent) + { + item.Parent = parent; } - protected override void SetVisibleCore(bool visible) { - if (visible) { + protected override void SetVisibleCore(bool visible) + { + if (visible) + { SnapMouseLocation(); } - else { + else + { // make sure we reset selection - this is critical for close/reopen dropdowns. - if (!Disposing && !IsDisposed) { + if (!Disposing && !IsDisposed) + { ClearAllSelections(); } - + // when we're not visible, clear off old item HDC. CachedItemHdcInfo lastInfo = cachedItemHdcInfo; cachedItemHdcInfo = null; lastMouseDownedItem = null; - - if (lastInfo != null) { + + if (lastInfo != null) + { lastInfo.Dispose(); } } base.SetVisibleCore(visible); } - internal bool ShouldSelectItem() { + internal bool ShouldSelectItem() + { // we only want to select the item if the cursor position has // actually moved from when the window became visible. // We ALWAYS get a WM_MOUSEMOVE when the window is shown, // which could accidentally change selection. - if (mouseEnterWhenShown == InvalidMouseEnter) { + if (mouseEnterWhenShown == InvalidMouseEnter) + { Debug.WriteLineIf(ToolStripItem.MouseDebugging.TraceVerbose, "[TS: ShouldSelectItem] MouseEnter already reset."); return true; } Point mousePosition = WindowsFormsUtils.LastCursorPoint; - if (mouseEnterWhenShown != mousePosition) { + if (mouseEnterWhenShown != mousePosition) + { Debug.WriteLineIf(ToolStripItem.MouseDebugging.TraceVerbose, "[TS: ShouldSelectItem] Mouse position has changed - call Select()."); mouseEnterWhenShown = InvalidMouseEnter; return true; @@ -3960,18 +4667,22 @@ internal bool ShouldSelectItem() { /// /// /// - protected override void Select(bool directed, bool forward) { + protected override void Select(bool directed, bool forward) + { bool correctParentActiveControl = true; - if (ParentInternal != null) { + if (ParentInternal != null) + { IContainerControl c = ParentInternal.GetContainerControl(); - if (c != null) { + if (c != null) + { c.ActiveControl = this; correctParentActiveControl = (c.ActiveControl == this); } } - if (directed && correctParentActiveControl) { - SelectNextToolStripItem(null, forward); + if (directed && correctParentActiveControl) + { + SelectNextToolStripItem(null, forward); } } @@ -3983,7 +4694,8 @@ protected override void Select(bool directed, bool forward) { /// /// - internal ToolStripItem SelectNextToolStripItem(ToolStripItem start, bool forward) { + internal ToolStripItem SelectNextToolStripItem(ToolStripItem start, bool forward) + { ToolStripItem nextItem = GetNextItem(start, (forward) ? ArrowDirection.Right : ArrowDirection.Left, /*RTLAware=*/true); ChangeSelection(nextItem); @@ -3993,48 +4705,57 @@ internal ToolStripItem SelectNextToolStripItem(ToolStripItem start, bool forward // // - internal void SetFocusUnsafe() { - if (TabStop) { - Debug.WriteLineIf(SnapFocusDebug.TraceVerbose,"[ToolStrip.SetFocus] Focusing toolstrip."); + internal void SetFocusUnsafe() + { + if (TabStop) + { + Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "[ToolStrip.SetFocus] Focusing toolstrip."); Focus(); } - else { - Debug.WriteLineIf(SnapFocusDebug.TraceVerbose,"[ToolStrip.SetFocus] Entering menu mode."); + else + { + Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "[ToolStrip.SetFocus] Entering menu mode."); ToolStripManager.ModalMenuFilter.SetActiveToolStrip(this, /*menuKeyPressed=*/false); } } - - private void SetupGrip() { - Rectangle gripRectangle = Rectangle.Empty; - Rectangle displayRect = DisplayRectangle; - - - if (Orientation == Orientation.Horizontal) { - // the display rectangle already knows about the padding and the grip rectangle width - // so place it relative to that. - gripRectangle.X = Math.Max(0, displayRect.X - Grip.GripThickness); - gripRectangle.Y = Math.Max(0,displayRect.Top - Grip.Margin.Top); - gripRectangle.Width = Grip.GripThickness; - gripRectangle.Height = displayRect.Height; - if (RightToLeft == RightToLeft.Yes) { - gripRectangle.X = ClientRectangle.Right - gripRectangle.Width - Grip.Margin.Horizontal; - gripRectangle.X += Grip.Margin.Left; - } - else { - gripRectangle.X -= Grip.Margin.Right; - } - } - else { - // vertical split stack mode - gripRectangle.X = displayRect.Left; - gripRectangle.Y = displayRect.Top - (Grip.GripThickness + Grip.Margin.Bottom); - gripRectangle.Width = displayRect.Width; - gripRectangle.Height = Grip.GripThickness; - } - - if (Grip.Bounds !=gripRectangle) { - Grip.SetBounds(gripRectangle); - } + + private void SetupGrip() + { + Rectangle gripRectangle = Rectangle.Empty; + Rectangle displayRect = DisplayRectangle; + + + if (Orientation == Orientation.Horizontal) + { + // the display rectangle already knows about the padding and the grip rectangle width + // so place it relative to that. + gripRectangle.X = Math.Max(0, displayRect.X - Grip.GripThickness); + gripRectangle.Y = Math.Max(0, displayRect.Top - Grip.Margin.Top); + gripRectangle.Width = Grip.GripThickness; + gripRectangle.Height = displayRect.Height; + if (RightToLeft == RightToLeft.Yes) + { + gripRectangle.X = ClientRectangle.Right - gripRectangle.Width - Grip.Margin.Horizontal; + gripRectangle.X += Grip.Margin.Left; + } + else + { + gripRectangle.X -= Grip.Margin.Right; + } + } + else + { + // vertical split stack mode + gripRectangle.X = displayRect.Left; + gripRectangle.Y = displayRect.Top - (Grip.GripThickness + Grip.Margin.Bottom); + gripRectangle.Width = displayRect.Width; + gripRectangle.Height = Grip.GripThickness; + } + + if (Grip.Bounds != gripRectangle) + { + Grip.SetBounds(gripRectangle); + } } @@ -4044,16 +4765,20 @@ private void SetupGrip() { /// /// [EditorBrowsable(EditorBrowsableState.Never)] - new public void SetAutoScrollMargin(int x, int y) { + new public void SetAutoScrollMargin(int x, int y) + { base.SetAutoScrollMargin(x, y); } - internal void SetLargestItemSize(Size size) { + internal void SetLargestItemSize(Size size) + { - if (toolStripOverflowButton != null && toolStripOverflowButton.Visible) { + if (toolStripOverflowButton != null && toolStripOverflowButton.Visible) + { size = LayoutUtils.UnionSizes(size, toolStripOverflowButton.Bounds.Size); } - if (toolStripGrip != null && toolStripGrip.Visible) { + if (toolStripGrip != null && toolStripGrip.Visible) + { size = LayoutUtils.UnionSizes(size, toolStripGrip.Bounds.Size); } @@ -4205,17 +4930,19 @@ protected virtual void SetDisplayedItems() SetLargestItemSize(biggestItemSize); } - + /// /// Sets the current value of the specified bit in the control's state. /// - internal void SetToolStripState(int flag, bool value) { - toolStripState = value? toolStripState | flag: toolStripState & ~flag; + internal void SetToolStripState(int flag, bool value) + { + toolStripState = value ? toolStripState | flag : toolStripState & ~flag; } // remembers the current mouse location so we can determine // later if we need to shift selection. - internal void SnapMouseLocation() { + internal void SnapMouseLocation() + { mouseEnterWhenShown = WindowsFormsUtils.LastCursorPoint; } @@ -4232,9 +4959,11 @@ internal void SnapMouseLocation() { /// - make sure it's not a child control of this control. /// - make sure the control is on this window /// - private void SnapFocus(IntPtr otherHwnd) { + private void SnapFocus(IntPtr otherHwnd) + { #if DEBUG - if (SnapFocusDebug.TraceVerbose) { + if (SnapFocusDebug.TraceVerbose) + { string stackTrace = new StackTrace().ToString(); Regex regex = new Regex("FocusInternal"); Debug.WriteLine(!regex.IsMatch(stackTrace), "who is setting focus to us?"); @@ -4242,77 +4971,90 @@ private void SnapFocus(IntPtr otherHwnd) { #endif // we need to know who sent us focus so we know who to send it back to later. - if (!TabStop && !IsDropDown) { - bool snapFocus = false; - if (Focused && (otherHwnd != this.Handle)) { + if (!TabStop && !IsDropDown) + { + bool snapFocus = false; + if (Focused && (otherHwnd != this.Handle)) + { // the case here is a label before a combo box calling FocusInternal in ProcessMnemonic. // we'll filter out children later. snapFocus = true; - } - else if (!ContainsFocus && !Focused) { - snapFocus =true; - } - - if (snapFocus) { - // remember the current mouse position so that we can check later if it actually moved - // otherwise we'd unexpectedly change selection to whatever the cursor was over at this moment. - SnapMouseLocation(); - - // start auto expanding for keyboard and mouse. - // MenuAutoExpand = true; - - HandleRef thisHandle = new HandleRef(this, this.Handle); - HandleRef otherHandle = new HandleRef(null, otherHwnd); - - // make sure the otherHandle is not a child of thisHandle - if ((thisHandle.Handle != otherHandle.Handle) && - !UnsafeNativeMethods.IsChild(thisHandle, otherHandle)) { - - // make sure the root window of the otherHwnd is the same as - // the root window of thisHwnd. - HandleRef thisHwndRoot = WindowsFormsUtils.GetRootHWnd(this); - HandleRef otherHwndRoot = WindowsFormsUtils.GetRootHWnd(otherHandle); - - if (thisHwndRoot.Handle == otherHwndRoot.Handle && (thisHwndRoot.Handle != IntPtr.Zero)) { - Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "[ToolStrip SnapFocus]: Caching for return focus:" + WindowsFormsUtils.GetControlInformation(otherHandle.Handle)); - // we know we're in the same window heirarchy. - hwndThatLostFocus = otherHandle.Handle; - } - } - } - } + } + else if (!ContainsFocus && !Focused) + { + snapFocus = true; + } + + if (snapFocus) + { + // remember the current mouse position so that we can check later if it actually moved + // otherwise we'd unexpectedly change selection to whatever the cursor was over at this moment. + SnapMouseLocation(); + + // start auto expanding for keyboard and mouse. + // MenuAutoExpand = true; + + HandleRef thisHandle = new HandleRef(this, this.Handle); + HandleRef otherHandle = new HandleRef(null, otherHwnd); + + // make sure the otherHandle is not a child of thisHandle + if ((thisHandle.Handle != otherHandle.Handle) && + !UnsafeNativeMethods.IsChild(thisHandle, otherHandle)) + { + + // make sure the root window of the otherHwnd is the same as + // the root window of thisHwnd. + HandleRef thisHwndRoot = WindowsFormsUtils.GetRootHWnd(this); + HandleRef otherHwndRoot = WindowsFormsUtils.GetRootHWnd(otherHandle); + + if (thisHwndRoot.Handle == otherHwndRoot.Handle && (thisHwndRoot.Handle != IntPtr.Zero)) + { + Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "[ToolStrip SnapFocus]: Caching for return focus:" + WindowsFormsUtils.GetControlInformation(otherHandle.Handle)); + // we know we're in the same window heirarchy. + hwndThatLostFocus = otherHandle.Handle; + } + } + } + } } // when we're control tabbing around we need to remember the original // thing that lost focus. - internal void SnapFocusChange(ToolStrip otherToolStrip) { - otherToolStrip.hwndThatLostFocus = this.hwndThatLostFocus; + internal void SnapFocusChange(ToolStrip otherToolStrip) + { + otherToolStrip.hwndThatLostFocus = this.hwndThatLostFocus; } - - private bool ShouldSerializeDefaultDropDownDirection() { + + private bool ShouldSerializeDefaultDropDownDirection() + { return (toolStripDropDownDirection != ToolStripDropDownDirection.Default); } - internal virtual bool ShouldSerializeLayoutStyle() { + internal virtual bool ShouldSerializeLayoutStyle() + { return layoutStyle != ToolStripLayoutStyle.StackWithOverflow; } - internal override bool ShouldSerializeMinimumSize() { - Size invalidDefaultSize = new Size(-1,-1); + internal override bool ShouldSerializeMinimumSize() + { + Size invalidDefaultSize = new Size(-1, -1); return (CommonProperties.GetMinimumSize(this, invalidDefaultSize) != invalidDefaultSize); } - private bool ShouldSerializeGripMargin() { + private bool ShouldSerializeGripMargin() + { return GripMargin != DefaultGripMargin; } - internal virtual bool ShouldSerializeRenderMode() { + internal virtual bool ShouldSerializeRenderMode() + { // We should NEVER serialize custom. return (RenderMode != ToolStripRenderMode.ManagerRenderMode && RenderMode != ToolStripRenderMode.Custom); } - public override string ToString() { + public override string ToString() + { StringBuilder sb = new StringBuilder(base.ToString()); sb.Append(", Name: "); sb.Append(this.Name); @@ -4320,20 +5062,25 @@ public override string ToString() { return sb.ToString(); } - internal void UpdateToolTip(ToolStripItem item) { - if (ShowItemToolTips) { + internal void UpdateToolTip(ToolStripItem item) + { + if (ShowItemToolTips) + { - if (item != currentlyActiveTooltipItem && ToolTip != null) { + if (item != currentlyActiveTooltipItem && ToolTip != null) + { ToolTip.Hide(this); currentlyActiveTooltipItem = item; - if (currentlyActiveTooltipItem != null && !GetToolStripState(STATE_DRAGGING)) { + if (currentlyActiveTooltipItem != null && !GetToolStripState(STATE_DRAGGING)) + { Cursor currentCursor = Cursor.CurrentInternal; - if (currentCursor != null) { + if (currentCursor != null) + { Point cursorLocation = Cursor.Position; cursorLocation.Y += Cursor.Size.Height - currentCursor.HotSpot.Y; @@ -4342,7 +5089,7 @@ internal void UpdateToolTip(ToolStripItem item) { ToolTip.Show(currentlyActiveTooltipItem.ToolTipText, this, PointToClient(cursorLocation), - ToolTip.AutoPopDelay); + ToolTip.AutoPopDelay); } } } @@ -4350,65 +5097,78 @@ internal void UpdateToolTip(ToolStripItem item) { } - private void UpdateLayoutStyle(DockStyle newDock) { - if (!IsInToolStripPanel && layoutStyle != ToolStripLayoutStyle.HorizontalStackWithOverflow && layoutStyle != ToolStripLayoutStyle.VerticalStackWithOverflow) { - using (new LayoutTransaction(this, this, PropertyNames.Orientation)) { + private void UpdateLayoutStyle(DockStyle newDock) + { + if (!IsInToolStripPanel && layoutStyle != ToolStripLayoutStyle.HorizontalStackWithOverflow && layoutStyle != ToolStripLayoutStyle.VerticalStackWithOverflow) + { + using (new LayoutTransaction(this, this, PropertyNames.Orientation)) + { // // We want the ToolStrip to size appropriately when the dock has switched. // - if (newDock == DockStyle.Left || newDock == DockStyle.Right) { + if (newDock == DockStyle.Left || newDock == DockStyle.Right) + { UpdateOrientation(Orientation.Vertical); } - else { + else + { UpdateOrientation(Orientation.Horizontal); } } OnLayoutStyleChanged(EventArgs.Empty); - if (this.ParentInternal != null) { + if (this.ParentInternal != null) + { LayoutTransaction.DoLayout(this.ParentInternal, this, PropertyNames.Orientation); } } } - private void UpdateLayoutStyle(Orientation newRaftingRowOrientation) { - if (layoutStyle != ToolStripLayoutStyle.HorizontalStackWithOverflow && layoutStyle != ToolStripLayoutStyle.VerticalStackWithOverflow) { - using (new LayoutTransaction(this, this, PropertyNames.Orientation)) { - - // - // We want the ToolStrip to size appropriately when the rafting container orientation has switched. - // - /* if (newRaftingRowOrientation != orientation) { - int oldHeight = this.Height; - this.Height = this.Width; - this.Width = oldHeight; - }*/ + private void UpdateLayoutStyle(Orientation newRaftingRowOrientation) + { + if (layoutStyle != ToolStripLayoutStyle.HorizontalStackWithOverflow && layoutStyle != ToolStripLayoutStyle.VerticalStackWithOverflow) + { + using (new LayoutTransaction(this, this, PropertyNames.Orientation)) + { - UpdateOrientation(newRaftingRowOrientation); - if (LayoutEngine is ToolStripSplitStackLayout && layoutStyle == ToolStripLayoutStyle.StackWithOverflow) { - OnLayoutStyleChanged(EventArgs.Empty); - } + // + // We want the ToolStrip to size appropriately when the rafting container orientation has switched. + // + /* if (newRaftingRowOrientation != orientation) { + int oldHeight = this.Height; + this.Height = this.Width; + this.Width = oldHeight; + }*/ + + UpdateOrientation(newRaftingRowOrientation); + if (LayoutEngine is ToolStripSplitStackLayout && layoutStyle == ToolStripLayoutStyle.StackWithOverflow) + { + OnLayoutStyleChanged(EventArgs.Empty); + } - } - } - else { + } + } + else + { // update the orientation but dont force a layout. - UpdateOrientation(newRaftingRowOrientation); + UpdateOrientation(newRaftingRowOrientation); } } - private void UpdateOrientation(Orientation newOrientation) { - if (newOrientation != orientation) { + private void UpdateOrientation(Orientation newOrientation) + { + if (newOrientation != orientation) + { // snap our last dimensions before switching over. // use specifed bounds so that if something is docked or anchored we dont take the extra stretching // effects into account. Size size = CommonProperties.GetSpecifiedBounds(this).Size; orientation = newOrientation; // since the Grip affects the DisplayRectangle, we need to re-adjust the size - SetupGrip(); + SetupGrip(); } } @@ -4416,125 +5176,148 @@ private void UpdateOrientation(Orientation newOrientation) { /// Summary of WndProc. /// /// - protected override void WndProc(ref Message m) { + protected override void WndProc(ref Message m) + { - if (m.Msg == Interop.WindowMessages.WM_SETFOCUS) { + if (m.Msg == Interop.WindowMessages.WM_SETFOCUS) + { SnapFocus(m.WParam); } - if (m.Msg == Interop.WindowMessages.WM_MOUSEACTIVATE) { - // we want to prevent taking focus if someone clicks on the toolstrip dropdown - // itself. the mouse message will still go through, but focus wont be taken. - // if someone clicks on a child control (combobox, textbox, etc) focus will - // be taken - but we'll handle that in WM_NCACTIVATE handler. - Point pt = PointToClient(WindowsFormsUtils.LastCursorPoint); - IntPtr hwndClicked = UnsafeNativeMethods.ChildWindowFromPointEx(new HandleRef(null, Handle), pt.X, pt.Y,(int)(GetChildAtPointSkip.Invisible | GetChildAtPointSkip.Disabled | GetChildAtPointSkip.Transparent)); - // if we click on the toolstrip itself, eat the activation. - // if we click on a child control, allow the toolstrip to activate. - if (hwndClicked == this.Handle) { - lastMouseDownedItem = null; - m.Result = (IntPtr)NativeMethods.MA_NOACTIVATE; - - if (!IsDropDown && !IsInDesignMode) { - - // If our root HWND is not the active hwnd, - // eat the mouse message and bring the form to the front. - HandleRef rootHwnd = WindowsFormsUtils.GetRootHWnd(this); - if (rootHwnd.Handle != IntPtr.Zero) { - - // snap the active window and compare to our root window. - IntPtr hwndActive = UnsafeNativeMethods.GetActiveWindow(); - if (hwndActive != rootHwnd.Handle) { - // Activate the window, and discard the mouse message. - // this appears to be the same behavior as office. - m.Result = (IntPtr)NativeMethods.MA_ACTIVATEANDEAT; - } + if (m.Msg == Interop.WindowMessages.WM_MOUSEACTIVATE) + { + // we want to prevent taking focus if someone clicks on the toolstrip dropdown + // itself. the mouse message will still go through, but focus wont be taken. + // if someone clicks on a child control (combobox, textbox, etc) focus will + // be taken - but we'll handle that in WM_NCACTIVATE handler. + Point pt = PointToClient(WindowsFormsUtils.LastCursorPoint); + IntPtr hwndClicked = UnsafeNativeMethods.ChildWindowFromPointEx(new HandleRef(null, Handle), pt.X, pt.Y, (int)(GetChildAtPointSkip.Invisible | GetChildAtPointSkip.Disabled | GetChildAtPointSkip.Transparent)); + // if we click on the toolstrip itself, eat the activation. + // if we click on a child control, allow the toolstrip to activate. + if (hwndClicked == this.Handle) + { + lastMouseDownedItem = null; + m.Result = (IntPtr)NativeMethods.MA_NOACTIVATE; + + if (!IsDropDown && !IsInDesignMode) + { + + // If our root HWND is not the active hwnd, + // eat the mouse message and bring the form to the front. + HandleRef rootHwnd = WindowsFormsUtils.GetRootHWnd(this); + if (rootHwnd.Handle != IntPtr.Zero) + { + + // snap the active window and compare to our root window. + IntPtr hwndActive = UnsafeNativeMethods.GetActiveWindow(); + if (hwndActive != rootHwnd.Handle) + { + // Activate the window, and discard the mouse message. + // this appears to be the same behavior as office. + m.Result = (IntPtr)NativeMethods.MA_ACTIVATEANDEAT; } } - return; } - else { - // we're setting focus to a child control - remember who gave it to us - // so we can restore it on ESC. - SnapFocus(UnsafeNativeMethods.GetFocus()); - if (!IsDropDown && !TabStop) { - Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "Installing restoreFocusFilter"); - // PERF, + return; + } + else + { + // we're setting focus to a child control - remember who gave it to us + // so we can restore it on ESC. + SnapFocus(UnsafeNativeMethods.GetFocus()); + if (!IsDropDown && !TabStop) + { + Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "Installing restoreFocusFilter"); + // PERF, - Application.ThreadContext.FromCurrent().AddMessageFilter(RestoreFocusFilter); - } + Application.ThreadContext.FromCurrent().AddMessageFilter(RestoreFocusFilter); } + } } - + base.WndProc(ref m); - if (m.Msg == Interop.WindowMessages.WM_NCDESTROY) { + if (m.Msg == Interop.WindowMessages.WM_NCDESTROY) + { // Destroy the owner window, if we created one. We // cannot do this in OnHandleDestroyed, because at // that point our handle is not actually destroyed so // destroying our parent actually causes a recursive // WM_DESTROY. - if (dropDownOwnerWindow != null) { + if (dropDownOwnerWindow != null) + { dropDownOwnerWindow.DestroyHandle(); } } } // Overriden to return Items instead of Controls. - ArrangedElementCollection IArrangedElement.Children { + ArrangedElementCollection IArrangedElement.Children + { get { return Items; } } - void IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) { + void IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) + { SetBoundsCore(bounds.X, bounds.Y, bounds.Width, bounds.Height, specified); } - bool IArrangedElement.ParticipatesInLayout { - get { return GetState(STATE_VISIBLE);} + bool IArrangedElement.ParticipatesInLayout + { + get { return GetState(STATE_VISIBLE); } } - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new ToolStripAccessibleObject(this); } - protected override Control.ControlCollection CreateControlsInstance() { + protected override Control.ControlCollection CreateControlsInstance() + { return new WindowsFormsUtils.ReadOnlyControlCollection(this, /* isReadOnly = */ !DesignMode); } - internal void OnItemAddedInternal(ToolStripItem item) { - if (this.ShowItemToolTips) { + internal void OnItemAddedInternal(ToolStripItem item) + { + if (this.ShowItemToolTips) + { KeyboardToolTipStateMachine.Instance.Hook(item, this.ToolTip); } } - internal void OnItemRemovedInternal(ToolStripItem item) { + internal void OnItemRemovedInternal(ToolStripItem item) + { KeyboardToolTipStateMachine.Instance.Unhook(item, this.ToolTip); } - internal override bool AllowsChildrenToShowToolTips() { + internal override bool AllowsChildrenToShowToolTips() + { return base.AllowsChildrenToShowToolTips() && this.ShowItemToolTips; } [System.Runtime.InteropServices.ComVisible(true)] - public class ToolStripAccessibleObject : ControlAccessibleObject { + public class ToolStripAccessibleObject : ControlAccessibleObject + { private ToolStrip owner; - public ToolStripAccessibleObject(ToolStrip owner) : base(owner) { + public ToolStripAccessibleObject(ToolStrip owner) : base(owner) + { this.owner = owner; } /// /// Return the child object at the given screen coordinates. /// - public override AccessibleObject HitTest(int x, int y) { + public override AccessibleObject HitTest(int x, int y) + { - Point clientHit = owner.PointToClient(new Point(x,y)); + Point clientHit = owner.PointToClient(new Point(x, y)); ToolStripItem item = owner.GetItemAt(clientHit); return ((item != null) && (item.AccessibilityObject != null)) ? item.AccessibilityObject : - base.HitTest(x,y); + base.HitTest(x, y); } @@ -4543,26 +5326,32 @@ public override AccessibleObject HitTest(int x, int y) { /// index. /// // - public override AccessibleObject GetChild(int index) { + public override AccessibleObject GetChild(int index) + { if ((owner == null) || (owner.Items == null)) return null; - if (index == 0 && owner.Grip.Visible) { + if (index == 0 && owner.Grip.Visible) + { return owner.Grip.AccessibilityObject; } - else if (owner.Grip.Visible && index > 0) { + else if (owner.Grip.Visible && index > 0) + { index--; } - if (index < owner.Items.Count) { + if (index < owner.Items.Count) + { ToolStripItem item = null; int myIndex = 0; // First we walk through the head aligned items. for (int i = 0; i < owner.Items.Count; ++i) { - if (owner.Items[i].Available && owner.Items[i].Alignment == ToolStripItemAlignment.Left) { - if (myIndex == index) { + if (owner.Items[i].Available && owner.Items[i].Alignment == ToolStripItemAlignment.Left) + { + if (myIndex == index) + { item = owner.Items[i]; break; } @@ -4571,10 +5360,14 @@ public override AccessibleObject GetChild(int index) { } // If we didn't find it, then we walk through the tail aligned items. - if (item == null) { - for (int i = 0; i < owner.Items.Count; ++i) { - if (owner.Items[i].Available && owner.Items[i].Alignment == ToolStripItemAlignment.Right) { - if (myIndex == index) { + if (item == null) + { + for (int i = 0; i < owner.Items.Count; ++i) + { + if (owner.Items[i].Available && owner.Items[i].Alignment == ToolStripItemAlignment.Right) + { + if (myIndex == index) + { item = owner.Items[i]; break; } @@ -4583,18 +5376,21 @@ public override AccessibleObject GetChild(int index) { } } - if (item == null) { + if (item == null) + { Debug.Fail("No item matched the index??"); return null; } - if (item.Placement == ToolStripItemPlacement.Overflow) { + if (item.Placement == ToolStripItemPlacement.Overflow) + { return new ToolStripAccessibleObjectWrapperForItemsOnOverflow(item); } return item.AccessibilityObject; } - if (owner.CanOverflow && owner.OverflowButton.Visible && index == owner.Items.Count) { + if (owner.CanOverflow && owner.OverflowButton.Visible && index == owner.Items.Count) + { return owner.OverflowButton.AccessibilityObject; } return null; @@ -4604,39 +5400,49 @@ public override AccessibleObject GetChild(int index) { /// When overridden in a derived class, gets the number of children /// belonging to an accessible object. /// - public override int GetChildCount() { + public override int GetChildCount() + { if ((owner == null) || (owner.Items == null)) return -1; int count = 0; - for (int i = 0; i < owner.Items.Count; i++) { - if (owner.Items[i].Available) { + for (int i = 0; i < owner.Items.Count; i++) + { + if (owner.Items[i].Available) + { count++; } } - if (owner.Grip.Visible) { + if (owner.Grip.Visible) + { count++; } - if (owner.CanOverflow && owner.OverflowButton.Visible) { + if (owner.CanOverflow && owner.OverflowButton.Visible) + { count++; } return count; } - internal AccessibleObject GetChildFragment(int fragmentIndex, bool getOverflowItem = false) { + internal AccessibleObject GetChildFragment(int fragmentIndex, bool getOverflowItem = false) + { var items = getOverflowItem ? owner.OverflowItems : owner.DisplayedItems; int childFragmentCount = items.Count; - if (!getOverflowItem && owner.CanOverflow && owner.OverflowButton.Visible && fragmentIndex == childFragmentCount - 1) { + if (!getOverflowItem && owner.CanOverflow && owner.OverflowButton.Visible && fragmentIndex == childFragmentCount - 1) + { return owner.OverflowButton.AccessibilityObject; } - for (int index = 0; index < childFragmentCount; index++) { + for (int index = 0; index < childFragmentCount; index++) + { var item = items[index]; - if (item.Available && item.Alignment == ToolStripItemAlignment.Left && fragmentIndex == index) { + if (item.Available && item.Alignment == ToolStripItemAlignment.Left && fragmentIndex == index) + { var controlHostItem = item as ToolStripControlHost; - if (controlHostItem != null) { + if (controlHostItem != null) + { return controlHostItem.ControlAccessibilityObject; } @@ -4644,11 +5450,14 @@ internal AccessibleObject GetChildFragment(int fragmentIndex, bool getOverflowIt } } - for (int index = 0; index < childFragmentCount; index++) { + for (int index = 0; index < childFragmentCount; index++) + { var item = owner.Items[index]; - if (item.Available && item.Alignment == ToolStripItemAlignment.Right && fragmentIndex == index) { + if (item.Available && item.Alignment == ToolStripItemAlignment.Right && fragmentIndex == index) + { var controlHostItem = item as ToolStripControlHost; - if (controlHostItem != null) { + if (controlHostItem != null) + { return controlHostItem.ControlAccessibilityObject; } @@ -4659,40 +5468,50 @@ internal AccessibleObject GetChildFragment(int fragmentIndex, bool getOverflowIt return null; } - internal int GetChildOverflowFragmentCount() { - if (owner == null || owner.OverflowItems == null) { + internal int GetChildOverflowFragmentCount() + { + if (owner == null || owner.OverflowItems == null) + { return -1; } return owner.OverflowItems.Count; } - internal int GetChildFragmentCount() { - if (owner == null || owner.DisplayedItems == null) { + internal int GetChildFragmentCount() + { + if (owner == null || owner.DisplayedItems == null) + { return -1; } return owner.DisplayedItems.Count; } - internal int GetChildFragmentIndex(ToolStripItem.ToolStripItemAccessibleObject child) { - if (owner == null || owner.Items == null) { + internal int GetChildFragmentIndex(ToolStripItem.ToolStripItemAccessibleObject child) + { + if (owner == null || owner.Items == null) + { return -1; } - if (child.Owner == owner.Grip) { + if (child.Owner == owner.Grip) + { return 0; } ToolStripItemCollection items; var placement = child.Owner.Placement; - if (owner is ToolStripOverflow) { + if (owner is ToolStripOverflow) + { // Overflow items in ToolStripOverflow host are in DisplayedItems collection. items = owner.DisplayedItems; } - else { - if (owner.CanOverflow && owner.OverflowButton.Visible && child.Owner == owner.OverflowButton) { + else + { + if (owner.CanOverflow && owner.OverflowButton.Visible && child.Owner == owner.OverflowButton) + { return GetChildFragmentCount() - 1; } @@ -4701,17 +5520,21 @@ internal int GetChildFragmentIndex(ToolStripItem.ToolStripItemAccessibleObject c } // First we walk through the head aligned items. - for (int index = 0; index < items.Count; index++) { + for (int index = 0; index < items.Count; index++) + { var item = items[index]; - if (item.Available && item.Alignment == ToolStripItemAlignment.Left && child.Owner == items[index]) { + if (item.Available && item.Alignment == ToolStripItemAlignment.Left && child.Owner == items[index]) + { return index; } } // If we didn't find it, then we walk through the tail aligned items. - for (int index = 0; index < items.Count; index++) { + for (int index = 0; index < items.Count; index++) + { var item = items[index]; - if (item.Available && item.Alignment == ToolStripItemAlignment.Right && child.Owner == items[index]) { + if (item.Available && item.Alignment == ToolStripItemAlignment.Right && child.Owner == items[index]) + { return index; } } @@ -4719,27 +5542,35 @@ internal int GetChildFragmentIndex(ToolStripItem.ToolStripItemAccessibleObject c return -1; } - internal int GetChildIndex(ToolStripItem.ToolStripItemAccessibleObject child) { - if ((owner == null) || (owner.Items == null)) { + internal int GetChildIndex(ToolStripItem.ToolStripItemAccessibleObject child) + { + if ((owner == null) || (owner.Items == null)) + { return -1; } int index = 0; - if (owner.Grip.Visible) { - if (child.Owner == owner.Grip) { + if (owner.Grip.Visible) + { + if (child.Owner == owner.Grip) + { return 0; } index = 1; } - if (owner.CanOverflow && owner.OverflowButton.Visible && child.Owner == owner.OverflowButton) { - return owner.Items.Count + index; + if (owner.CanOverflow && owner.OverflowButton.Visible && child.Owner == owner.OverflowButton) + { + return owner.Items.Count + index; } // First we walk through the head aligned items. - for (int i = 0; i < owner.Items.Count; ++i) { - if (owner.Items[i].Available && owner.Items[i].Alignment == ToolStripItemAlignment.Left) { - if (child.Owner == owner.Items[i]) { + for (int i = 0; i < owner.Items.Count; ++i) + { + if (owner.Items[i].Available && owner.Items[i].Alignment == ToolStripItemAlignment.Left) + { + if (child.Owner == owner.Items[i]) + { return index; } index++; @@ -4747,9 +5578,12 @@ internal int GetChildIndex(ToolStripItem.ToolStripItemAccessibleObject child) { } // If we didn't find it, then we walk through the tail aligned items. - for (int i = 0; i < owner.Items.Count; ++i) { - if (owner.Items[i].Available && owner.Items[i].Alignment == ToolStripItemAlignment.Right) { - if (child.Owner == owner.Items[i]) { + for (int i = 0; i < owner.Items.Count; ++i) + { + if (owner.Items[i].Available && owner.Items[i].Alignment == ToolStripItemAlignment.Right) + { + if (child.Owner == owner.Items[i]) + { return index; } index++; @@ -4759,33 +5593,42 @@ internal int GetChildIndex(ToolStripItem.ToolStripItemAccessibleObject child) { return -1; } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { AccessibleRole role = Owner.AccessibleRole; - if (role != AccessibleRole.Default) { + if (role != AccessibleRole.Default) + { return role; } return AccessibleRole.ToolBar; } } - internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot { - get { + internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot + { + get + { return this; } } - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - switch (direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { + switch (direction) + { case UnsafeNativeMethods.NavigateDirection.FirstChild: int childCount = GetChildFragmentCount(); - if (childCount > 0) { + if (childCount > 0) + { return this.GetChildFragment(0); } break; case UnsafeNativeMethods.NavigateDirection.LastChild: childCount = GetChildFragmentCount(); - if (childCount > 0) { + if (childCount > 0) + { return this.GetChildFragment(childCount - 1); } break; @@ -4794,8 +5637,10 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga return base.FragmentNavigate(direction); } - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_ControlTypePropertyId) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_ControlTypePropertyId) + { return NativeMethods.UIA_ToolBarControlTypeId; } @@ -4804,12 +5649,16 @@ internal override object GetPropertyValue(int propertyID) { } - private class ToolStripAccessibleObjectWrapperForItemsOnOverflow : ToolStripItem.ToolStripItemAccessibleObject { + private class ToolStripAccessibleObjectWrapperForItemsOnOverflow : ToolStripItem.ToolStripItemAccessibleObject + { public ToolStripAccessibleObjectWrapperForItemsOnOverflow(ToolStripItem item) - : base(item) { + : base(item) + { } - public override AccessibleStates State { - get { + public override AccessibleStates State + { + get + { AccessibleStates state = base.State; state |= AccessibleStates.Offscreen; state |= AccessibleStates.Invisible; @@ -4820,63 +5669,75 @@ public override AccessibleStates State { // When we click somewhere outside of the toolstrip it should be as if we hit esc. - internal class RestoreFocusMessageFilter : IMessageFilter { - private ToolStrip ownerToolStrip; - - public RestoreFocusMessageFilter(ToolStrip ownerToolStrip) { - this.ownerToolStrip = ownerToolStrip; - } - - public bool PreFilterMessage(ref Message m) { + internal class RestoreFocusMessageFilter : IMessageFilter + { + private ToolStrip ownerToolStrip; - if (ownerToolStrip.Disposing || ownerToolStrip.IsDisposed || ownerToolStrip.IsDropDown) { - return false; - } - // if the app has changed activation, restore focus - - switch (m.Msg) { - - case Interop.WindowMessages.WM_LBUTTONDOWN: - case Interop.WindowMessages.WM_RBUTTONDOWN: - case Interop.WindowMessages.WM_MBUTTONDOWN: - case Interop.WindowMessages.WM_NCLBUTTONDOWN: - case Interop.WindowMessages.WM_NCRBUTTONDOWN: - case Interop.WindowMessages.WM_NCMBUTTONDOWN: - if (ownerToolStrip.ContainsFocus) { - // if we've clicked on something that's not a child of the toolstrip and we - // currently have focus, restore it. - if (!UnsafeNativeMethods.IsChild(new HandleRef(this, ownerToolStrip.Handle), new HandleRef(this,m.HWnd))) { - HandleRef rootHwnd = WindowsFormsUtils.GetRootHWnd(ownerToolStrip); - if (rootHwnd.Handle == m.HWnd || UnsafeNativeMethods.IsChild(rootHwnd, new HandleRef(this,m.HWnd))) { - // Only RestoreFocus if the hwnd is a child of the root window and isnt on the toolstrip. - RestoreFocusInternal(); - } + public RestoreFocusMessageFilter(ToolStrip ownerToolStrip) + { + this.ownerToolStrip = ownerToolStrip; + } + + public bool PreFilterMessage(ref Message m) + { + + if (ownerToolStrip.Disposing || ownerToolStrip.IsDisposed || ownerToolStrip.IsDropDown) + { + return false; + } + // if the app has changed activation, restore focus + + switch (m.Msg) + { + + case Interop.WindowMessages.WM_LBUTTONDOWN: + case Interop.WindowMessages.WM_RBUTTONDOWN: + case Interop.WindowMessages.WM_MBUTTONDOWN: + case Interop.WindowMessages.WM_NCLBUTTONDOWN: + case Interop.WindowMessages.WM_NCRBUTTONDOWN: + case Interop.WindowMessages.WM_NCMBUTTONDOWN: + if (ownerToolStrip.ContainsFocus) + { + // if we've clicked on something that's not a child of the toolstrip and we + // currently have focus, restore it. + if (!UnsafeNativeMethods.IsChild(new HandleRef(this, ownerToolStrip.Handle), new HandleRef(this, m.HWnd))) + { + HandleRef rootHwnd = WindowsFormsUtils.GetRootHWnd(ownerToolStrip); + if (rootHwnd.Handle == m.HWnd || UnsafeNativeMethods.IsChild(rootHwnd, new HandleRef(this, m.HWnd))) + { + // Only RestoreFocus if the hwnd is a child of the root window and isnt on the toolstrip. + RestoreFocusInternal(); } } - return false; - - default: - return false; - } - } - private void RestoreFocusInternal() { - Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "[ToolStrip.RestoreFocusFilter] Detected a click, restoring focus."); - + } + return false; + + default: + return false; + } + } + private void RestoreFocusInternal() + { + Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "[ToolStrip.RestoreFocusFilter] Detected a click, restoring focus."); + - ownerToolStrip.BeginInvoke(new BooleanMethodInvoker(ownerToolStrip.RestoreFocusInternal), new object[]{ ToolStripManager.ModalMenuFilter.InMenuMode } ); + ownerToolStrip.BeginInvoke(new BooleanMethodInvoker(ownerToolStrip.RestoreFocusInternal), new object[] { ToolStripManager.ModalMenuFilter.InMenuMode }); - // PERF, + // PERF, - Application.ThreadContext.FromCurrent().RemoveMessageFilter(this); - } + Application.ThreadContext.FromCurrent().RemoveMessageFilter(this); + } } - internal override bool ShowsOwnKeyboardToolTip() { + internal override bool ShowsOwnKeyboardToolTip() + { bool hasVisibleSelectableItems = false; int i = this.Items.Count; - while (i-- != 0 && !hasVisibleSelectableItems) { + while (i-- != 0 && !hasVisibleSelectableItems) + { ToolStripItem item = this.Items[i]; - if (item.CanKeyboardSelect && item.Visible) { + if (item.CanKeyboardSelect && item.Visible) + { hasVisibleSelectableItems = true; } } @@ -4885,16 +5746,19 @@ internal override bool ShowsOwnKeyboardToolTip() { } } - - - - internal class CachedItemHdcInfo : IDisposable { - internal CachedItemHdcInfo() { + + + internal class CachedItemHdcInfo : IDisposable + { + + internal CachedItemHdcInfo() + { } - ~CachedItemHdcInfo() { + ~CachedItemHdcInfo() + { Dispose(); } @@ -4902,49 +5766,56 @@ internal CachedItemHdcInfo() { private Size cachedHDCSize = Size.Empty; private HandleRef cachedItemBitmap = NativeMethods.NullHandleRef; // this DC is cached and should only be deleted on Dispose or when the size changes. - - - public HandleRef GetCachedItemDC(HandleRef toolStripHDC, Size bitmapSize) { - if ((cachedHDCSize.Width < bitmapSize.Width) - || (cachedHDCSize.Height < bitmapSize.Height)) { - if (cachedItemHDC.Handle == IntPtr.Zero) { - // create a new DC - we dont have one yet. - IntPtr compatibleHDC = UnsafeNativeMethods.CreateCompatibleDC(toolStripHDC); - cachedItemHDC = new HandleRef(this, compatibleHDC); - } + public HandleRef GetCachedItemDC(HandleRef toolStripHDC, Size bitmapSize) + { - // create compatible bitmap with the correct size. - cachedItemBitmap = new HandleRef(this, SafeNativeMethods.CreateCompatibleBitmap(toolStripHDC, bitmapSize.Width, bitmapSize.Height)); - IntPtr oldBitmap = SafeNativeMethods.SelectObject(cachedItemHDC,cachedItemBitmap); + if ((cachedHDCSize.Width < bitmapSize.Width) + || (cachedHDCSize.Height < bitmapSize.Height)) + { - // delete the old bitmap - if (oldBitmap != IntPtr.Zero) { - // ExternalDelete to prevent Handle underflow - SafeNativeMethods.ExternalDeleteObject(new HandleRef(null, oldBitmap)); - oldBitmap = IntPtr.Zero; - } + if (cachedItemHDC.Handle == IntPtr.Zero) + { + // create a new DC - we dont have one yet. + IntPtr compatibleHDC = UnsafeNativeMethods.CreateCompatibleDC(toolStripHDC); + cachedItemHDC = new HandleRef(this, compatibleHDC); + } + // create compatible bitmap with the correct size. + cachedItemBitmap = new HandleRef(this, SafeNativeMethods.CreateCompatibleBitmap(toolStripHDC, bitmapSize.Width, bitmapSize.Height)); + IntPtr oldBitmap = SafeNativeMethods.SelectObject(cachedItemHDC, cachedItemBitmap); - // remember what size we created. - cachedHDCSize = bitmapSize; + // delete the old bitmap + if (oldBitmap != IntPtr.Zero) + { + // ExternalDelete to prevent Handle underflow + SafeNativeMethods.ExternalDeleteObject(new HandleRef(null, oldBitmap)); + oldBitmap = IntPtr.Zero; + } - } - return cachedItemHDC; + + // remember what size we created. + cachedHDCSize = bitmapSize; + + } + return cachedItemHDC; } - private void DeleteCachedItemHDC() { + private void DeleteCachedItemHDC() + { - if (cachedItemHDC.Handle != IntPtr.Zero) { - // delete the bitmap - if (cachedItemBitmap.Handle != IntPtr.Zero) { - SafeNativeMethods.DeleteObject(cachedItemBitmap); - cachedItemBitmap = NativeMethods.NullHandleRef; - } - // delete the DC itself. - UnsafeNativeMethods.DeleteCompatibleDC(cachedItemHDC); + if (cachedItemHDC.Handle != IntPtr.Zero) + { + // delete the bitmap + if (cachedItemBitmap.Handle != IntPtr.Zero) + { + SafeNativeMethods.DeleteObject(cachedItemBitmap); + cachedItemBitmap = NativeMethods.NullHandleRef; + } + // delete the DC itself. + UnsafeNativeMethods.DeleteCompatibleDC(cachedItemHDC); } cachedItemHDC = NativeMethods.NullHandleRef; @@ -4952,298 +5823,352 @@ private void DeleteCachedItemHDC() { cachedHDCSize = Size.Empty; } - public void Dispose() { - DeleteCachedItemHDC(); - GC.SuppressFinalize(this); + public void Dispose() + { + DeleteCachedItemHDC(); + GC.SuppressFinalize(this); } } - internal class MouseHoverTimer : IDisposable { - - private System.Windows.Forms.Timer mouseHoverTimer = new System.Windows.Forms.Timer(); - // consider - weak reference? - private ToolStripItem currentItem = null; - - public MouseHoverTimer() { - mouseHoverTimer.Interval = SystemInformation.MouseHoverTime; - mouseHoverTimer.Tick += new EventHandler(OnTick); - } - - public void Start(ToolStripItem item) { - if (item != currentItem) { - Cancel(currentItem); - } - currentItem = item; - if (currentItem != null) { - mouseHoverTimer.Enabled = true; - } - } - - - public void Cancel() { - mouseHoverTimer.Enabled = false; - currentItem = null; - } - /// cancels if and only if this item was the one that - /// requested the timer - /// - public void Cancel(ToolStripItem item) { - if (item == currentItem) { - Cancel(); - } - } - - public void Dispose() { - if (mouseHoverTimer != null) { - Cancel(); - mouseHoverTimer.Dispose(); - mouseHoverTimer = null; - } - } - - - private void OnTick(object sender, EventArgs e) { - mouseHoverTimer.Enabled = false; - if (currentItem != null && !currentItem.IsDisposed) { - currentItem.FireEvent(EventArgs.Empty,ToolStripItemEventType.MouseHover); - } - } - - - } - - /// - /// This class supports the AllowItemReorder feature. - /// When reordering items ToolStrip and ToolStripItem drag/drop events - /// are routed here. - /// - internal sealed class ToolStripSplitStackDragDropHandler : IDropTarget, ISupportOleDropSource { + internal class MouseHoverTimer : IDisposable + { - private ToolStrip owner; + private System.Windows.Forms.Timer mouseHoverTimer = new System.Windows.Forms.Timer(); + // consider - weak reference? + private ToolStripItem currentItem = null; - public ToolStripSplitStackDragDropHandler(ToolStrip owner) { + public MouseHoverTimer() + { + mouseHoverTimer.Interval = SystemInformation.MouseHoverTime; + mouseHoverTimer.Tick += new EventHandler(OnTick); + } - if (owner == null) { - // - throw new ArgumentNullException(nameof(owner)); - } - this.owner = owner; + public void Start(ToolStripItem item) + { + if (item != currentItem) + { + Cancel(currentItem); } + currentItem = item; + if (currentItem != null) + { + mouseHoverTimer.Enabled = true; + } + } - public void OnDragEnter(DragEventArgs e){ - Debug.WriteLineIf(ToolStrip.ItemReorderDebug.TraceVerbose, "OnDragEnter: " + e.ToString()); - if (e.Data.GetDataPresent(typeof(ToolStripItem))) { - e.Effect = DragDropEffects.Move; - this.ShowItemDropPoint(owner.PointToClient(new Point(e.X, e.Y))); - } + public void Cancel() + { + mouseHoverTimer.Enabled = false; + currentItem = null; + } + /// cancels if and only if this item was the one that + /// requested the timer + /// + public void Cancel(ToolStripItem item) + { + if (item == currentItem) + { + Cancel(); } + } - public void OnDragLeave(System.EventArgs e){ - Debug.WriteLineIf(ToolStrip.ItemReorderDebug.TraceVerbose, "OnDragLeave: " + e.ToString()); - owner.ClearInsertionMark(); + public void Dispose() + { + if (mouseHoverTimer != null) + { + Cancel(); + mouseHoverTimer.Dispose(); + mouseHoverTimer = null; } + } - public void OnDragDrop(DragEventArgs e){ - Debug.WriteLineIf(ToolStrip.ItemReorderDebug.TraceVerbose, "OnDragDrop: " + e.ToString()); + private void OnTick(object sender, EventArgs e) + { + mouseHoverTimer.Enabled = false; + if (currentItem != null && !currentItem.IsDisposed) + { + currentItem.FireEvent(EventArgs.Empty, ToolStripItemEventType.MouseHover); + } + } - if (e.Data.GetDataPresent(typeof(ToolStripItem))) { - ToolStripItem item = (ToolStripItem)e.Data.GetData(typeof(ToolStripItem)); - OnDropItem(item, owner.PointToClient(new Point(e.X, e.Y))); - } - } - public void OnDragOver(DragEventArgs e){ - Debug.WriteLineIf(ToolStrip.ItemReorderDebug.TraceVerbose, "OnDragOver: " + e.ToString()); + } - if (e.Data.GetDataPresent(typeof(ToolStripItem))) { - if (this.ShowItemDropPoint(owner.PointToClient(new Point(e.X, e.Y)))) { - e.Effect = DragDropEffects.Move; - } - else { - if (owner != null) { - owner.ClearInsertionMark(); - } - e.Effect = DragDropEffects.None; - } - } + /// + /// This class supports the AllowItemReorder feature. + /// When reordering items ToolStrip and ToolStripItem drag/drop events + /// are routed here. + /// + internal sealed class ToolStripSplitStackDragDropHandler : IDropTarget, ISupportOleDropSource + { + private ToolStrip owner; + public ToolStripSplitStackDragDropHandler(ToolStrip owner) + { + + if (owner == null) + { + // + throw new ArgumentNullException(nameof(owner)); } + this.owner = owner; + } + + public void OnDragEnter(DragEventArgs e) + { + Debug.WriteLineIf(ToolStrip.ItemReorderDebug.TraceVerbose, "OnDragEnter: " + e.ToString()); + if (e.Data.GetDataPresent(typeof(ToolStripItem))) + { + e.Effect = DragDropEffects.Move; + this.ShowItemDropPoint(owner.PointToClient(new Point(e.X, e.Y))); - public void OnGiveFeedback(GiveFeedbackEventArgs e) { } + } + + public void OnDragLeave(System.EventArgs e) + { + Debug.WriteLineIf(ToolStrip.ItemReorderDebug.TraceVerbose, "OnDragLeave: " + e.ToString()); + owner.ClearInsertionMark(); + } + + public void OnDragDrop(DragEventArgs e) + { + Debug.WriteLineIf(ToolStrip.ItemReorderDebug.TraceVerbose, "OnDragDrop: " + e.ToString()); - public void OnQueryContinueDrag(QueryContinueDragEventArgs e) { + + if (e.Data.GetDataPresent(typeof(ToolStripItem))) + { + ToolStripItem item = (ToolStripItem)e.Data.GetData(typeof(ToolStripItem)); + OnDropItem(item, owner.PointToClient(new Point(e.X, e.Y))); } - private void OnDropItem(ToolStripItem droppedItem, Point ownerClientAreaRelativeDropPoint) { - Point start = Point.Empty; + } + public void OnDragOver(DragEventArgs e) + { + Debug.WriteLineIf(ToolStrip.ItemReorderDebug.TraceVerbose, "OnDragOver: " + e.ToString()); - int toolStripItemIndex = GetItemInsertionIndex(ownerClientAreaRelativeDropPoint); - if (toolStripItemIndex >= 0) { - ToolStripItem item = owner.Items[toolStripItemIndex]; - if (item == droppedItem) { + if (e.Data.GetDataPresent(typeof(ToolStripItem))) + { + if (this.ShowItemDropPoint(owner.PointToClient(new Point(e.X, e.Y)))) + { + e.Effect = DragDropEffects.Move; + } + else + { + if (owner != null) + { owner.ClearInsertionMark(); - return; // optimization } + e.Effect = DragDropEffects.None; + } + } - RelativeLocation relativeLocation = ComparePositions(item.Bounds, ownerClientAreaRelativeDropPoint); - droppedItem.Alignment = item.Alignment; - // Protect against negative indicies - int insertIndex = Math.Max(0, toolStripItemIndex); + } - if (relativeLocation == RelativeLocation.Above) { - insertIndex = (item.Alignment == ToolStripItemAlignment.Left) ? insertIndex : insertIndex + 1; - } - else if (relativeLocation == RelativeLocation.Below) { - insertIndex = (item.Alignment == ToolStripItemAlignment.Left) ? insertIndex : insertIndex-1; - } - else if (((item.Alignment == ToolStripItemAlignment.Left) && (relativeLocation == RelativeLocation.Left)) || - ((item.Alignment == ToolStripItemAlignment.Right) && (relativeLocation == RelativeLocation.Right))) { + public void OnGiveFeedback(GiveFeedbackEventArgs e) + { + } - // the item alignment is Tail & dropped to right of the center of the item - // or the item alignment is Head & dropped to the left of the center of the item + public void OnQueryContinueDrag(QueryContinueDragEventArgs e) + { + } - // Normally, insert the new item after the item, however in RTL insert before the item - insertIndex = Math.Max(0, (owner.RightToLeft == RightToLeft.Yes) ? insertIndex + 1 : insertIndex); - } - else { - // the item alignment is Tail & dropped to left of the center of the item - // or the item alignment is Head & dropped to the right of the center of the item + private void OnDropItem(ToolStripItem droppedItem, Point ownerClientAreaRelativeDropPoint) + { + Point start = Point.Empty; - - // Normally, insert the new item before the item, however in RTL insert after the item - insertIndex = Math.Max(0, (owner.RightToLeft == RightToLeft.No) ? insertIndex + 1 : insertIndex); - } + int toolStripItemIndex = GetItemInsertionIndex(ownerClientAreaRelativeDropPoint); + if (toolStripItemIndex >= 0) + { + ToolStripItem item = owner.Items[toolStripItemIndex]; + if (item == droppedItem) + { + owner.ClearInsertionMark(); + return; // optimization + } - // If the control is moving from a lower to higher index, you actually want to set it one less than its position. - // This is because it is being removed from its original position, which lowers the index of every control before - // its new drop point by 1. - if (owner.Items.IndexOf(droppedItem) < insertIndex) { - insertIndex--; - } + RelativeLocation relativeLocation = ComparePositions(item.Bounds, ownerClientAreaRelativeDropPoint); + droppedItem.Alignment = item.Alignment; - owner.Items.MoveItem(Math.Max(0,insertIndex), droppedItem); - owner.ClearInsertionMark(); + // Protect against negative indicies + int insertIndex = Math.Max(0, toolStripItemIndex); + if (relativeLocation == RelativeLocation.Above) + { + insertIndex = (item.Alignment == ToolStripItemAlignment.Left) ? insertIndex : insertIndex + 1; } - else if (toolStripItemIndex == -1 && owner.Items.Count == 0) { - owner.Items.Add(droppedItem); - owner.ClearInsertionMark(); + else if (relativeLocation == RelativeLocation.Below) + { + insertIndex = (item.Alignment == ToolStripItemAlignment.Left) ? insertIndex : insertIndex - 1; } - } + else if (((item.Alignment == ToolStripItemAlignment.Left) && (relativeLocation == RelativeLocation.Left)) || + ((item.Alignment == ToolStripItemAlignment.Right) && (relativeLocation == RelativeLocation.Right))) + { + // the item alignment is Tail & dropped to right of the center of the item + // or the item alignment is Head & dropped to the left of the center of the item + // Normally, insert the new item after the item, however in RTL insert before the item + insertIndex = Math.Max(0, (owner.RightToLeft == RightToLeft.Yes) ? insertIndex + 1 : insertIndex); + } + else + { + // the item alignment is Tail & dropped to left of the center of the item + // or the item alignment is Head & dropped to the right of the center of the item - private bool ShowItemDropPoint(Point ownerClientAreaRelativeDropPoint) { - int i = GetItemInsertionIndex(ownerClientAreaRelativeDropPoint); - if (i >= 0) { - ToolStripItem item = owner.Items[i]; - RelativeLocation relativeLocation = ComparePositions(item.Bounds, ownerClientAreaRelativeDropPoint); + // Normally, insert the new item before the item, however in RTL insert after the item + insertIndex = Math.Max(0, (owner.RightToLeft == RightToLeft.No) ? insertIndex + 1 : insertIndex); + } - Debug.WriteLineIf(ToolStrip.ItemReorderDebug.TraceVerbose, "Drop relative loc " + relativeLocation); - Debug.WriteLineIf(ToolStrip.ItemReorderDebug.TraceVerbose, "Index " + i); + // If the control is moving from a lower to higher index, you actually want to set it one less than its position. + // This is because it is being removed from its original position, which lowers the index of every control before + // its new drop point by 1. + if (owner.Items.IndexOf(droppedItem) < insertIndex) + { + insertIndex--; + } - Rectangle insertionRect = Rectangle.Empty; - switch (relativeLocation) { - case RelativeLocation.Above: - insertionRect = new Rectangle(owner.Margin.Left, item.Bounds.Top, owner.Width - (owner.Margin.Horizontal) -1, ToolStrip.insertionBeamWidth); - break; - case RelativeLocation.Below: - insertionRect = new Rectangle(owner.Margin.Left, item.Bounds.Bottom, owner.Width - (owner.Margin.Horizontal) -1, ToolStrip.insertionBeamWidth); - break; - case RelativeLocation.Right: - insertionRect = new Rectangle(item.Bounds.Right, owner.Margin.Top, ToolStrip.insertionBeamWidth, owner.Height- (owner.Margin.Vertical)-1); - break; - case RelativeLocation.Left: - insertionRect = new Rectangle(item.Bounds.Left, owner.Margin.Top, ToolStrip.insertionBeamWidth, owner.Height - (owner.Margin.Vertical) -1); - break; - } + owner.Items.MoveItem(Math.Max(0, insertIndex), droppedItem); + owner.ClearInsertionMark(); - owner.PaintInsertionMark(insertionRect); - return true; - } - else if (owner.Items.Count == 0) { - Rectangle insertionRect = owner.DisplayRectangle; - insertionRect.Width = ToolStrip.insertionBeamWidth; - owner.PaintInsertionMark(insertionRect); - return true; + } + else if (toolStripItemIndex == -1 && owner.Items.Count == 0) + { + owner.Items.Add(droppedItem); + owner.ClearInsertionMark(); + } + } + + + + private bool ShowItemDropPoint(Point ownerClientAreaRelativeDropPoint) + { + + int i = GetItemInsertionIndex(ownerClientAreaRelativeDropPoint); + if (i >= 0) + { + ToolStripItem item = owner.Items[i]; + RelativeLocation relativeLocation = ComparePositions(item.Bounds, ownerClientAreaRelativeDropPoint); + + Debug.WriteLineIf(ToolStrip.ItemReorderDebug.TraceVerbose, "Drop relative loc " + relativeLocation); + Debug.WriteLineIf(ToolStrip.ItemReorderDebug.TraceVerbose, "Index " + i); + + Rectangle insertionRect = Rectangle.Empty; + switch (relativeLocation) + { + case RelativeLocation.Above: + insertionRect = new Rectangle(owner.Margin.Left, item.Bounds.Top, owner.Width - (owner.Margin.Horizontal) - 1, ToolStrip.insertionBeamWidth); + break; + case RelativeLocation.Below: + insertionRect = new Rectangle(owner.Margin.Left, item.Bounds.Bottom, owner.Width - (owner.Margin.Horizontal) - 1, ToolStrip.insertionBeamWidth); + break; + case RelativeLocation.Right: + insertionRect = new Rectangle(item.Bounds.Right, owner.Margin.Top, ToolStrip.insertionBeamWidth, owner.Height - (owner.Margin.Vertical) - 1); + break; + case RelativeLocation.Left: + insertionRect = new Rectangle(item.Bounds.Left, owner.Margin.Top, ToolStrip.insertionBeamWidth, owner.Height - (owner.Margin.Vertical) - 1); + break; } - return false; + + owner.PaintInsertionMark(insertionRect); + return true; + } + else if (owner.Items.Count == 0) + { + Rectangle insertionRect = owner.DisplayRectangle; + insertionRect.Width = ToolStrip.insertionBeamWidth; + owner.PaintInsertionMark(insertionRect); + return true; } + return false; + } - private int GetItemInsertionIndex(Point ownerClientAreaRelativeDropPoint) { - for(int i = 0; i< owner.DisplayedItems.Count; i++) { - Rectangle bounds = owner.DisplayedItems[i].Bounds; - bounds.Inflate(owner.DisplayedItems[i].Margin.Size); - if (bounds.Contains(ownerClientAreaRelativeDropPoint)) { - Debug.WriteLineIf(ToolStrip.DropTargetDebug.TraceVerbose, "MATCH " + owner.DisplayedItems[i].Text + " Bounds: " + owner.DisplayedItems[i].Bounds.ToString()); + private int GetItemInsertionIndex(Point ownerClientAreaRelativeDropPoint) + { + for (int i = 0; i < owner.DisplayedItems.Count; i++) + { + Rectangle bounds = owner.DisplayedItems[i].Bounds; + bounds.Inflate(owner.DisplayedItems[i].Margin.Size); + if (bounds.Contains(ownerClientAreaRelativeDropPoint)) + { + Debug.WriteLineIf(ToolStrip.DropTargetDebug.TraceVerbose, "MATCH " + owner.DisplayedItems[i].Text + " Bounds: " + owner.DisplayedItems[i].Bounds.ToString()); - // consider what to do about items not in the display - return owner.Items.IndexOf(owner.DisplayedItems[i]); - } + // consider what to do about items not in the display + return owner.Items.IndexOf(owner.DisplayedItems[i]); } + } - if (owner.DisplayedItems.Count > 0) { - for (int i = 0; i < owner.DisplayedItems.Count; i++) { - if (owner.DisplayedItems[i].Alignment == ToolStripItemAlignment.Right) { - if (i > 0) { - return owner.Items.IndexOf(owner.DisplayedItems[i - 1]); - } - return owner.Items.IndexOf(owner.DisplayedItems[i]); + if (owner.DisplayedItems.Count > 0) + { + for (int i = 0; i < owner.DisplayedItems.Count; i++) + { + if (owner.DisplayedItems[i].Alignment == ToolStripItemAlignment.Right) + { + if (i > 0) + { + return owner.Items.IndexOf(owner.DisplayedItems[i - 1]); } + return owner.Items.IndexOf(owner.DisplayedItems[i]); } - return owner.Items.IndexOf(owner.DisplayedItems[owner.DisplayedItems.Count - 1]); } - return -1; + return owner.Items.IndexOf(owner.DisplayedItems[owner.DisplayedItems.Count - 1]); } + return -1; + } - private enum RelativeLocation { - Above, - Below, - Right, - Left - } + private enum RelativeLocation + { + Above, + Below, + Right, + Left + } - private RelativeLocation ComparePositions(Rectangle orig, Point check) { + private RelativeLocation ComparePositions(Rectangle orig, Point check) + { - if (owner.Orientation == Orientation.Horizontal) { - int widthUnit = orig.Width / 2; - RelativeLocation relativeLocation = RelativeLocation.Left; + if (owner.Orientation == Orientation.Horizontal) + { + int widthUnit = orig.Width / 2; + RelativeLocation relativeLocation = RelativeLocation.Left; - // we can return here if we are checking abovebelowleftright, because - // the left right calculation is more picky than the above/below calculation - // and the above below calculation will just override this one. - if ((orig.Left + widthUnit) >= check.X) { - relativeLocation = RelativeLocation.Left; - return relativeLocation; - } - else if ((orig.Right - widthUnit) <= check.X) { - relativeLocation = RelativeLocation.Right; - return relativeLocation; - } + // we can return here if we are checking abovebelowleftright, because + // the left right calculation is more picky than the above/below calculation + // and the above below calculation will just override this one. + if ((orig.Left + widthUnit) >= check.X) + { + relativeLocation = RelativeLocation.Left; + return relativeLocation; } - - if (owner.Orientation == Orientation.Vertical) { - int heightUnit = orig.Height/ 2; - RelativeLocation relativeLocation = (check.Y <= (orig.Top + heightUnit)) ? - RelativeLocation.Above - : RelativeLocation.Below; - + else if ((orig.Right - widthUnit) <= check.X) + { + relativeLocation = RelativeLocation.Right; return relativeLocation; } + } + + if (owner.Orientation == Orientation.Vertical) + { + int heightUnit = orig.Height / 2; + RelativeLocation relativeLocation = (check.Y <= (orig.Top + heightUnit)) ? + RelativeLocation.Above + : RelativeLocation.Below; - Debug.Fail("Could not calculate the relative position for AllowItemReorder"); - return RelativeLocation.Left; + return relativeLocation; } + + Debug.Fail("Could not calculate the relative position for AllowItemReorder"); + return RelativeLocation.Left; } + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs index eca9fe519a0..badc2e635a5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs @@ -2,66 +2,79 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Drawing; using System.Windows.Forms; using System.Drawing.Imaging; using System.ComponentModel; - using System.Windows.Forms.Design; - + using System.Windows.Forms.Design; + /// [ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ToolStrip)] - public class ToolStripButton : ToolStripItem { + public class ToolStripButton : ToolStripItem + { - private CheckState checkState = CheckState.Unchecked; - private bool checkOnClick = false; + private CheckState checkState = CheckState.Unchecked; + private bool checkOnClick = false; private const int STANDARD_BUTTON_WIDTH = 23; private int standardButtonWidth = STANDARD_BUTTON_WIDTH; - private static readonly object EventCheckedChanged = new object(); - private static readonly object EventCheckStateChanged = new object(); + private static readonly object EventCheckedChanged = new object(); + private static readonly object EventCheckStateChanged = new object(); /// /// Summary of ToolStripButton. /// - public ToolStripButton() { + public ToolStripButton() + { Initialize(); } - public ToolStripButton(string text):base(text,null,null) { + public ToolStripButton(string text) : base(text, null, null) + { Initialize(); } - public ToolStripButton(Image image):base(null,image,null) { + public ToolStripButton(Image image) : base(null, image, null) + { Initialize(); } - public ToolStripButton(string text, Image image):base(text,image,null) { + public ToolStripButton(string text, Image image) : base(text, image, null) + { Initialize(); } - public ToolStripButton(string text, Image image, EventHandler onClick):base(text,image,onClick) { - Initialize(); + public ToolStripButton(string text, Image image, EventHandler onClick) : base(text, image, onClick) + { + Initialize(); } - public ToolStripButton(string text, Image image, EventHandler onClick, string name):base(text,image,onClick,name) { + public ToolStripButton(string text, Image image, EventHandler onClick, string name) : base(text, image, onClick, name) + { Initialize(); } - + [DefaultValue(true)] - public new bool AutoToolTip { - get { + public new bool AutoToolTip + { + get + { return base.AutoToolTip; } - set { + set + { base.AutoToolTip = value; } } - + /// /// Summary of CanSelect. /// - public override bool CanSelect { - get { - return true; + public override bool CanSelect + { + get + { + return true; } } @@ -70,11 +83,14 @@ public override bool CanSelect { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ToolStripButtonCheckOnClickDescr)) ] - public bool CheckOnClick { - get { + public bool CheckOnClick + { + get + { return checkOnClick; } - set { + set + { checkOnClick = value; } } @@ -89,16 +105,20 @@ public bool CheckOnClick { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripButtonCheckedDescr)) ] - public bool Checked { - get { + public bool Checked + { + get + { return checkState != CheckState.Unchecked; } - set { - if (value != Checked) { + set + { + if (value != Checked) + { CheckState = value ? CheckState.Checked : CheckState.Unchecked; InvokePaint(); - + } } } @@ -112,52 +132,60 @@ public bool Checked { DefaultValue(CheckState.Unchecked), SRDescription(nameof(SR.CheckBoxCheckStateDescr)) ] - public CheckState CheckState { - get { + public CheckState CheckState + { + get + { return checkState; } - set { + set + { //valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)CheckState.Unchecked, (int)CheckState.Indeterminate)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(CheckState)); } - - if (value != checkState) { + + if (value != checkState) + { checkState = value; Invalidate(); OnCheckedChanged(EventArgs.Empty); - OnCheckStateChanged(EventArgs.Empty); + OnCheckStateChanged(EventArgs.Empty); } } } - + /// /// Occurs when the /// value of the /// property changes. /// [SRDescription(nameof(SR.CheckBoxOnCheckedChangedDescr))] - public event EventHandler CheckedChanged { + public event EventHandler CheckedChanged + { add => Events.AddHandler(EventCheckedChanged, value); remove => Events.RemoveHandler(EventCheckedChanged, value); - } + } /// /// Occurs when the /// value of the /// property changes. /// [SRDescription(nameof(SR.CheckBoxOnCheckStateChangedDescr))] - public event EventHandler CheckStateChanged { + public event EventHandler CheckStateChanged + { add => Events.AddHandler(EventCheckStateChanged, value); remove => Events.RemoveHandler(EventCheckStateChanged, value); } - protected override bool DefaultAutoToolTip { - get { - return true; + protected override bool DefaultAutoToolTip + { + get + { + return true; } } @@ -166,22 +194,26 @@ protected override bool DefaultAutoToolTip { /// should not call base.CreateAccessibilityObject. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new ToolStripButtonAccessibleObject(this); } - public override Size GetPreferredSize(Size constrainingSize) { - Size prefSize = base.GetPreferredSize(constrainingSize); - prefSize.Width = Math.Max(prefSize.Width, standardButtonWidth); - return prefSize; + public override Size GetPreferredSize(Size constrainingSize) + { + Size prefSize = base.GetPreferredSize(constrainingSize); + prefSize.Width = Math.Max(prefSize.Width, standardButtonWidth); + return prefSize; } /// /// Called by all constructors of ToolStripButton. /// - private void Initialize() { + private void Initialize() + { SupportsSpaceKey = true; - if (DpiHelper.IsScalingRequirementMet) { + if (DpiHelper.IsScalingRequirementMet) + { standardButtonWidth = DpiHelper.LogicalToDeviceUnitsX(STANDARD_BUTTON_WIDTH); } } @@ -190,44 +222,54 @@ private void Initialize() { /// Raises the /// event. /// - protected virtual void OnCheckedChanged(EventArgs e) { + protected virtual void OnCheckedChanged(EventArgs e) + { EventHandler handler = (EventHandler)Events[EventCheckedChanged]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// /// Raises the event. /// - protected virtual void OnCheckStateChanged(EventArgs e) { + protected virtual void OnCheckStateChanged(EventArgs e) + { AccessibilityNotifyClients(AccessibleEvents.StateChange); EventHandler handler = (EventHandler)Events[EventCheckStateChanged]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } - + /// /// Inheriting classes should override this method to handle this event. /// - protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { + protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) + { - if (this.Owner != null) { + if (this.Owner != null) + { ToolStripRenderer renderer = this.Renderer; - + renderer.DrawButtonBackground(new ToolStripItemRenderEventArgs(e.Graphics, this)); - if ((DisplayStyle & ToolStripItemDisplayStyle.Image) == ToolStripItemDisplayStyle.Image) { + if ((DisplayStyle & ToolStripItemDisplayStyle.Image) == ToolStripItemDisplayStyle.Image) + { ToolStripItemImageRenderEventArgs rea = new ToolStripItemImageRenderEventArgs(e.Graphics, this, InternalLayout.ImageRectangle); rea.ShiftOnPress = true; renderer.DrawItemImage(rea); } - if ((DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) { - renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(e.Graphics, this, this.Text, InternalLayout.TextRectangle, this.ForeColor, this.Font, InternalLayout.TextFormat)); + if ((DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) + { + renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(e.Graphics, this, this.Text, InternalLayout.TextRectangle, this.ForeColor, this.Font, InternalLayout.TextFormat)); } } } - protected override void OnClick(EventArgs e) { - if (checkOnClick) { + protected override void OnClick(EventArgs e) + { + if (checkOnClick) + { this.Checked = !this.Checked; } base.OnClick(e); @@ -236,16 +278,20 @@ protected override void OnClick(EventArgs e) { /// /// An implementation of AccessibleChild for use with ToolStripItems /// - [System.Runtime.InteropServices.ComVisible(true)] - internal class ToolStripButtonAccessibleObject : ToolStripItemAccessibleObject { + [System.Runtime.InteropServices.ComVisible(true)] + internal class ToolStripButtonAccessibleObject : ToolStripItemAccessibleObject + { private ToolStripButton ownerItem = null; - - public ToolStripButtonAccessibleObject(ToolStripButton ownerItem): base(ownerItem) { + + public ToolStripButtonAccessibleObject(ToolStripButton ownerItem) : base(ownerItem) + { this.ownerItem = ownerItem; } - internal override object GetPropertyValue(int propertyID) { - switch (propertyID) { + internal override object GetPropertyValue(int propertyID) + { + switch (propertyID) + { case NativeMethods.UIA_ControlTypePropertyId: return NativeMethods.UIA_ButtonControlTypeId; } @@ -253,32 +299,40 @@ internal override object GetPropertyValue(int propertyID) { return base.GetPropertyValue(propertyID); } - public override AccessibleRole Role { - get { - if (ownerItem.CheckOnClick) { + public override AccessibleRole Role + { + get + { + if (ownerItem.CheckOnClick) + { return AccessibleRole.CheckButton; } - else { + else + { return base.Role; } } } - public override AccessibleStates State { - get { - if (ownerItem.Enabled && ownerItem.Checked) { + public override AccessibleStates State + { + get + { + if (ownerItem.Enabled && ownerItem.Checked) + { return base.State | AccessibleStates.Checked; } // Disabled ToolStripButton, that is selected, must have focus state so that Narrator can announce it - if (!ownerItem.Enabled && ownerItem.Selected) { + if (!ownerItem.Enabled && ownerItem.Selected) + { return base.State | AccessibleStates.Focused; } return base.State; - } + } } - + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripComboBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripComboBox.cs index 68c1137879f..baa243416d8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripComboBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripComboBox.cs @@ -16,31 +16,34 @@ namespace System.Windows.Forms [DefaultProperty(nameof(Items))] public class ToolStripComboBox : ToolStripControlHost { - internal static readonly object EventDropDown = new object(); - internal static readonly object EventDropDownClosed = new object(); - internal static readonly object EventDropDownStyleChanged = new object(); - internal static readonly object EventSelectedIndexChanged = new object(); - internal static readonly object EventSelectionChangeCommitted = new object(); - internal static readonly object EventTextUpdate = new object(); + internal static readonly object EventDropDown = new object(); + internal static readonly object EventDropDownClosed = new object(); + internal static readonly object EventDropDownStyleChanged = new object(); + internal static readonly object EventSelectedIndexChanged = new object(); + internal static readonly object EventSelectionChangeCommitted = new object(); + internal static readonly object EventTextUpdate = new object(); private static readonly Padding dropDownPadding = new Padding(2); private static readonly Padding padding = new Padding(1, 0, 1, 0); private Padding scaledDropDownPadding = dropDownPadding; private Padding scaledPadding = padding; - - public ToolStripComboBox() : base(CreateControlInstance()) { + + public ToolStripComboBox() : base(CreateControlInstance()) + { ToolStripComboBoxControl combo = Control as ToolStripComboBoxControl; combo.Owner = this; - if (DpiHelper.IsScalingRequirementMet) { + if (DpiHelper.IsScalingRequirementMet) + { scaledPadding = DpiHelper.LogicalToDeviceUnits(padding); scaledDropDownPadding = DpiHelper.LogicalToDeviceUnits(dropDownPadding); } } - public ToolStripComboBox(string name) : this() { + public ToolStripComboBox(string name) : this() + { this.Name = name; } @@ -50,7 +53,8 @@ public ToolStripComboBox(string name) : this() { /// /// The new instance of the accessibility object for this ToolStripComboBox ToolStrip item /// - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new ToolStripComboBoxAccessibleObject(this); } @@ -58,22 +62,26 @@ protected override AccessibleObject CreateAccessibilityInstance() { /// Defines the ToolStripComboBox AccessibleObject. /// [System.Runtime.InteropServices.ComVisible(true)] - internal class ToolStripComboBoxAccessibleObject : ToolStripItemAccessibleObject { + internal class ToolStripComboBoxAccessibleObject : ToolStripItemAccessibleObject + { private ToolStripComboBox ownerItem = null; /// /// Initializes the new instance of ToolStripComboBoxAccessibleObject. /// /// The owning ToolStripComboBox. - public ToolStripComboBoxAccessibleObject(ToolStripComboBox ownerItem) : base(ownerItem) { - this.ownerItem = ownerItem; + public ToolStripComboBoxAccessibleObject(ToolStripComboBox ownerItem) : base(ownerItem) + { + this.ownerItem = ownerItem; } /// /// Gets a description of the default action for an object. /// - public override string DefaultAction { - get { + public override string DefaultAction + { + get + { // Note: empty value is provided due to this Accessible object // represents the control container but not the contained ComboBox // control itself. @@ -84,22 +92,26 @@ public override string DefaultAction { /// /// Performs the default action associated with this accessible object. /// - public override void DoDefaultAction() { + public override void DoDefaultAction() + { // Do nothing. } /// /// Gets the role of this accessible object. /// - public override AccessibleRole Role { - get { - AccessibleRole role = Owner.AccessibleRole; - if (role != AccessibleRole.Default) { - return role; - } - - return AccessibleRole.ComboBox; - } + public override AccessibleRole Role + { + get + { + AccessibleRole role = Owner.AccessibleRole; + if (role != AccessibleRole.Default) + { + return role; + } + + return AccessibleRole.ComboBox; + } } /// @@ -107,9 +119,11 @@ public override AccessibleRole Role { /// /// Indicates the direction in which to navigate. /// Returns the element in the specified direction. - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { if (direction == UnsafeNativeMethods.NavigateDirection.FirstChild || - direction == UnsafeNativeMethods.NavigateDirection.LastChild) { + direction == UnsafeNativeMethods.NavigateDirection.LastChild) + { return this.ownerItem.ComboBox.AccessibilityObject; } @@ -120,20 +134,24 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga /// /// Return the element that is the root node of this fragment of UI. /// - internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot { - get { + internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot + { + get + { return this.ownerItem.RootToolStrip.AccessibilityObject; } } } - + [EditorBrowsable(EditorBrowsableState.Never)] - public ToolStripComboBox(Control c) : base(c) { + public ToolStripComboBox(Control c) : base(c) + { throw new NotSupportedException(SR.ToolStripMustSupplyItsOwnComboBox); } - private static Control CreateControlInstance() { - ComboBox comboBox = new ToolStripComboBoxControl(); + private static Control CreateControlInstance() + { + ComboBox comboBox = new ToolStripComboBoxControl(); comboBox.FlatStyle = FlatStyle.Popup; comboBox.Font = ToolStripManager.DefaultFont; return comboBox; @@ -145,9 +163,10 @@ private static Control CreateControlInstance() { Editor("System.Windows.Forms.Design.ListControlStringCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), Browsable(true), EditorBrowsable(EditorBrowsableState.Always) ] - public System.Windows.Forms.AutoCompleteStringCollection AutoCompleteCustomSource { + public System.Windows.Forms.AutoCompleteStringCollection AutoCompleteCustomSource + { get { return ComboBox.AutoCompleteCustomSource; } - set { ComboBox.AutoCompleteCustomSource = value;} + set { ComboBox.AutoCompleteCustomSource = value; } } [ @@ -155,19 +174,21 @@ public System.Windows.Forms.AutoCompleteStringCollection AutoCompleteCustomSourc SRDescription(nameof(SR.ComboBoxAutoCompleteModeDescr)), Browsable(true), EditorBrowsable(EditorBrowsableState.Always) ] - public AutoCompleteMode AutoCompleteMode { + public AutoCompleteMode AutoCompleteMode + { get { return ComboBox.AutoCompleteMode; } - set { ComboBox.AutoCompleteMode = value;} + set { ComboBox.AutoCompleteMode = value; } } - + [ DefaultValue(AutoCompleteSource.None), SRDescription(nameof(SR.ComboBoxAutoCompleteSourceDescr)), Browsable(true), EditorBrowsable(EditorBrowsableState.Always) ] - public AutoCompleteSource AutoCompleteSource { + public AutoCompleteSource AutoCompleteSource + { get { return ComboBox.AutoCompleteSource; } - set { ComboBox.AutoCompleteSource = value;} + set { ComboBox.AutoCompleteSource = value; } } [ @@ -175,11 +196,14 @@ public AutoCompleteSource AutoCompleteSource { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } @@ -189,25 +213,32 @@ public override Image BackgroundImage { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ComboBox ComboBox { - get{ + public ComboBox ComboBox + { + get + { return Control as ComboBox; } } - protected override Size DefaultSize { - get { - return new Size(100,22); + protected override Size DefaultSize + { + get + { + return new Size(100, 22); } } @@ -215,38 +246,46 @@ protected override Size DefaultSize { /// 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. /// - protected internal override Padding DefaultMargin { - get { - if (IsOnDropDown) { + protected internal override Padding DefaultMargin + { + get + { + if (IsOnDropDown) + { return scaledDropDownPadding; } - else { + else + { return scaledPadding; } } } [ - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public new event EventHandler DoubleClick { - add => base.DoubleClick+=value; + public new event EventHandler DoubleClick + { + add => base.DoubleClick += value; remove => base.DoubleClick -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ComboBoxOnDropDownDescr))] - public event EventHandler DropDown { + public event EventHandler DropDown + { add => Events.AddHandler(EventDropDown, value); remove => Events.RemoveHandler(EventDropDown, value); } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ComboBoxOnDropDownClosedDescr))] - public event EventHandler DropDownClosed { + public event EventHandler DropDownClosed + { add => Events.AddHandler(EventDropDownClosed, value); remove => Events.RemoveHandler(EventDropDownClosed, value); } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ComboBoxDropDownStyleChangedDescr))] - public event EventHandler DropDownStyleChanged { + public event EventHandler DropDownStyleChanged + { add => Events.AddHandler(EventDropDownStyleChanged, value); remove => Events.RemoveHandler(EventDropDownStyleChanged, value); } @@ -258,9 +297,10 @@ public event EventHandler DropDownStyleChanged { Browsable(true), EditorBrowsable(EditorBrowsableState.Always), DefaultValue(106) ] - public int DropDownHeight { + public int DropDownHeight + { get { return ComboBox.DropDownHeight; } - set { ComboBox.DropDownHeight = value;} + set { ComboBox.DropDownHeight = value; } } @@ -270,18 +310,20 @@ public int DropDownHeight { SRDescription(nameof(SR.ComboBoxStyleDescr)), RefreshPropertiesAttribute(RefreshProperties.Repaint) ] - public ComboBoxStyle DropDownStyle { + public ComboBoxStyle DropDownStyle + { get { return ComboBox.DropDownStyle; } - set { ComboBox.DropDownStyle = value;} + set { ComboBox.DropDownStyle = value; } } [ SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ComboBoxDropDownWidthDescr)) ] - public int DropDownWidth { + public int DropDownWidth + { get { return ComboBox.DropDownWidth; } - set { ComboBox.DropDownWidth = value;} + set { ComboBox.DropDownWidth = value; } } [ @@ -289,9 +331,10 @@ public int DropDownWidth { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ComboBoxDroppedDownDescr)) ] - public bool DroppedDown { + public bool DroppedDown + { get { return ComboBox.DroppedDown; } - set { ComboBox.DroppedDown = value;} + set { ComboBox.DroppedDown = value; } } [ @@ -300,9 +343,10 @@ public bool DroppedDown { Localizable(true), SRDescription(nameof(SR.ComboBoxFlatStyleDescr)) ] - public FlatStyle FlatStyle { + public FlatStyle FlatStyle + { get { return ComboBox.FlatStyle; } - set { ComboBox.FlatStyle = value;} + set { ComboBox.FlatStyle = value; } } [ @@ -311,9 +355,10 @@ public FlatStyle FlatStyle { Localizable(true), SRDescription(nameof(SR.ComboBoxIntegralHeightDescr)) ] - public bool IntegralHeight { + public bool IntegralHeight + { get { return ComboBox.IntegralHeight; } - set { ComboBox.IntegralHeight = value;} + set { ComboBox.IntegralHeight = value; } } /// /// Collection of the items contained in this ComboBox. @@ -325,8 +370,10 @@ public bool IntegralHeight { SRDescription(nameof(SR.ComboBoxItemsDescr)), Editor("System.Windows.Forms.Design.ListControlStringCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)) ] - public ComboBox.ObjectCollection Items { - get{ + public ComboBox.ObjectCollection Items + { + get + { return ComboBox.Items; } } @@ -337,9 +384,10 @@ public ComboBox.ObjectCollection Items { Localizable(true), SRDescription(nameof(SR.ComboBoxMaxDropDownItemsDescr)) ] - public int MaxDropDownItems { + public int MaxDropDownItems + { get { return ComboBox.MaxDropDownItems; } - set { ComboBox.MaxDropDownItems = value;} + set { ComboBox.MaxDropDownItems = value; } } [ SRCategory(nameof(SR.CatBehavior)), @@ -347,9 +395,10 @@ public int MaxDropDownItems { Localizable(true), SRDescription(nameof(SR.ComboBoxMaxLengthDescr)) ] - public int MaxLength { - get { return ComboBox.MaxLength; } - set { ComboBox.MaxLength = value; } + public int MaxLength + { + get { return ComboBox.MaxLength; } + set { ComboBox.MaxLength = value; } } [ @@ -357,12 +406,14 @@ public int MaxLength { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ComboBoxSelectedIndexDescr)) ] - public int SelectedIndex { + public int SelectedIndex + { get { return ComboBox.SelectedIndex; } - set { ComboBox.SelectedIndex = value;} + set { ComboBox.SelectedIndex = value; } } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.selectedIndexChangedEventDescr))] - public event EventHandler SelectedIndexChanged { + public event EventHandler SelectedIndexChanged + { add => Events.AddHandler(EventSelectedIndexChanged, value); remove => Events.RemoveHandler(EventSelectedIndexChanged, value); } @@ -372,28 +423,31 @@ public event EventHandler SelectedIndexChanged { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ComboBoxSelectedItemDescr)) ] - public object SelectedItem { + public object SelectedItem + { get { return ComboBox.SelectedItem; } - set { ComboBox.SelectedItem = value;} - } + set { ComboBox.SelectedItem = value; } + } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ComboBoxSelectedTextDescr)) ] - public string SelectedText { + public string SelectedText + { get { return ComboBox.SelectedText; } - set { ComboBox.SelectedText = value;} + set { ComboBox.SelectedText = value; } } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ComboBoxSelectionLengthDescr)) ] - public int SelectionLength { + public int SelectionLength + { get { return ComboBox.SelectionLength; } - set { ComboBox.SelectionLength = value;} + set { ComboBox.SelectionLength = value; } } [ @@ -401,28 +455,31 @@ public int SelectionLength { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ComboBoxSelectionStartDescr)) ] - public int SelectionStart { + public int SelectionStart + { get { return ComboBox.SelectionStart; } - set { ComboBox.SelectionStart = value;} + set { ComboBox.SelectionStart = value; } } [ SRCategory(nameof(SR.CatBehavior)), DefaultValue(false), SRDescription(nameof(SR.ComboBoxSortedDescr)) ] - public bool Sorted { + public bool Sorted + { get { return ComboBox.Sorted; } - set {ComboBox.Sorted = value;} + set { ComboBox.Sorted = value; } } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ComboBoxOnTextUpdateDescr))] - public event EventHandler TextUpdate { + public event EventHandler TextUpdate + { add => Events.AddHandler(EventTextUpdate, value); remove => Events.RemoveHandler(EventTextUpdate, value); } -#region WrappedMethods + #region WrappedMethods public void BeginUpdate() { ComboBox.BeginUpdate(); } public void EndUpdate() { ComboBox.EndUpdate(); } @@ -434,9 +491,10 @@ public event EventHandler TextUpdate { public void Select(int start, int length) { ComboBox.Select(start, length); } public void SelectAll() { ComboBox.SelectAll(); } -#endregion WrappedMethods + #endregion WrappedMethods - public override Size GetPreferredSize(Size constrainingSize) { + public override Size GetPreferredSize(Size constrainingSize) + { // Size preferredSize = base.GetPreferredSize(constrainingSize); @@ -444,117 +502,145 @@ public override Size GetPreferredSize(Size constrainingSize) { return preferredSize; } - private void HandleDropDown(object sender, System.EventArgs e) { + private void HandleDropDown(object sender, System.EventArgs e) + { OnDropDown(e); } - private void HandleDropDownClosed(object sender, System.EventArgs e) { + private void HandleDropDownClosed(object sender, System.EventArgs e) + { OnDropDownClosed(e); } - private void HandleDropDownStyleChanged(object sender, System.EventArgs e) { + private void HandleDropDownStyleChanged(object sender, System.EventArgs e) + { OnDropDownStyleChanged(e); } - private void HandleSelectedIndexChanged(object sender, System.EventArgs e) { + private void HandleSelectedIndexChanged(object sender, System.EventArgs e) + { OnSelectedIndexChanged(e); } - private void HandleSelectionChangeCommitted(object sender, System.EventArgs e) { + private void HandleSelectionChangeCommitted(object sender, System.EventArgs e) + { OnSelectionChangeCommitted(e); } - private void HandleTextUpdate(object sender, System.EventArgs e) { + private void HandleTextUpdate(object sender, System.EventArgs e) + { OnTextUpdate(e); } - - protected virtual void OnDropDown(EventArgs e) { - if (ParentInternal != null) { - Application.ThreadContext.FromCurrent().RemoveMessageFilter(ParentInternal.RestoreFocusFilter); + + protected virtual void OnDropDown(EventArgs e) + { + if (ParentInternal != null) + { + Application.ThreadContext.FromCurrent().RemoveMessageFilter(ParentInternal.RestoreFocusFilter); ToolStripManager.ModalMenuFilter.SuspendMenuMode(); - } - RaiseEvent(EventDropDown, e); + } + RaiseEvent(EventDropDown, e); } - protected virtual void OnDropDownClosed(EventArgs e) { - if (ParentInternal != null) { + protected virtual void OnDropDownClosed(EventArgs e) + { + if (ParentInternal != null) + { // PERF, - Application.ThreadContext.FromCurrent().RemoveMessageFilter(ParentInternal.RestoreFocusFilter); + Application.ThreadContext.FromCurrent().RemoveMessageFilter(ParentInternal.RestoreFocusFilter); ToolStripManager.ModalMenuFilter.ResumeMenuMode(); } - RaiseEvent(EventDropDownClosed, e); + RaiseEvent(EventDropDownClosed, e); } - protected virtual void OnDropDownStyleChanged(EventArgs e) { - RaiseEvent(EventDropDownStyleChanged, e); + protected virtual void OnDropDownStyleChanged(EventArgs e) + { + RaiseEvent(EventDropDownStyleChanged, e); } - protected virtual void OnSelectedIndexChanged(EventArgs e) { - RaiseEvent(EventSelectedIndexChanged, e); + protected virtual void OnSelectedIndexChanged(EventArgs e) + { + RaiseEvent(EventSelectedIndexChanged, e); } - protected virtual void OnSelectionChangeCommitted(EventArgs e) { - RaiseEvent(EventSelectionChangeCommitted, e); + protected virtual void OnSelectionChangeCommitted(EventArgs e) + { + RaiseEvent(EventSelectionChangeCommitted, e); } - protected virtual void OnTextUpdate(EventArgs e) { - RaiseEvent(EventTextUpdate, e); + protected virtual void OnTextUpdate(EventArgs e) + { + RaiseEvent(EventTextUpdate, e); } - - protected override void OnSubscribeControlEvents(Control control) { + + protected override void OnSubscribeControlEvents(Control control) + { ComboBox comboBox = control as ComboBox; - if (comboBox != null) { + if (comboBox != null) + { // Please keep this alphabetized and in sync with Unsubscribe // - comboBox.DropDown += new EventHandler(HandleDropDown); - comboBox.DropDownClosed += new EventHandler(HandleDropDownClosed); - comboBox.DropDownStyleChanged += new EventHandler(HandleDropDownStyleChanged); - comboBox.SelectedIndexChanged += new EventHandler(HandleSelectedIndexChanged); - comboBox.SelectionChangeCommitted += new EventHandler(HandleSelectionChangeCommitted); - comboBox.TextUpdate += new EventHandler(HandleTextUpdate); - } - + comboBox.DropDown += new EventHandler(HandleDropDown); + comboBox.DropDownClosed += new EventHandler(HandleDropDownClosed); + comboBox.DropDownStyleChanged += new EventHandler(HandleDropDownStyleChanged); + comboBox.SelectedIndexChanged += new EventHandler(HandleSelectedIndexChanged); + comboBox.SelectionChangeCommitted += new EventHandler(HandleSelectionChangeCommitted); + comboBox.TextUpdate += new EventHandler(HandleTextUpdate); + } + base.OnSubscribeControlEvents(control); } - - protected override void OnUnsubscribeControlEvents(Control control) { + + protected override void OnUnsubscribeControlEvents(Control control) + { ComboBox comboBox = control as ComboBox; - if (comboBox != null) { - // Please keep this alphabetized and in sync with Unsubscribe - // - comboBox.DropDown -= new EventHandler(HandleDropDown); - comboBox.DropDownClosed -= new EventHandler(HandleDropDownClosed); - comboBox.DropDownStyleChanged -= new EventHandler(HandleDropDownStyleChanged); - comboBox.SelectedIndexChanged -= new EventHandler(HandleSelectedIndexChanged); - comboBox.SelectionChangeCommitted -= new EventHandler(HandleSelectionChangeCommitted); - comboBox.TextUpdate -= new EventHandler(HandleTextUpdate); - } + if (comboBox != null) + { + // Please keep this alphabetized and in sync with Unsubscribe + // + comboBox.DropDown -= new EventHandler(HandleDropDown); + comboBox.DropDownClosed -= new EventHandler(HandleDropDownClosed); + comboBox.DropDownStyleChanged -= new EventHandler(HandleDropDownStyleChanged); + comboBox.SelectedIndexChanged -= new EventHandler(HandleSelectedIndexChanged); + comboBox.SelectionChangeCommitted -= new EventHandler(HandleSelectionChangeCommitted); + comboBox.TextUpdate -= new EventHandler(HandleTextUpdate); + } base.OnUnsubscribeControlEvents(control); } - private bool ShouldSerializeDropDownWidth() { + private bool ShouldSerializeDropDownWidth() + { return ComboBox.ShouldSerializeDropDownWidth(); } - internal override bool ShouldSerializeFont() { + internal override bool ShouldSerializeFont() + { return !object.Equals(this.Font, ToolStripManager.DefaultFont); } - public override string ToString() { + public override string ToString() + { return base.ToString() + ", Items.Count: " + Items.Count.ToString(CultureInfo.CurrentCulture); } - internal class ToolStripComboBoxControl : ComboBox { - private ToolStripComboBox owner = null; + internal class ToolStripComboBoxControl : ComboBox + { + private ToolStripComboBox owner = null; - public ToolStripComboBoxControl() { - this.FlatStyle = FlatStyle.Popup; - SetStyle(ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer, true); - } + public ToolStripComboBoxControl() + { + this.FlatStyle = FlatStyle.Popup; + SetStyle(ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer, true); + } - public ToolStripComboBox Owner { + public ToolStripComboBox Owner + { get { return owner; } set { owner = value; } } - private ProfessionalColorTable ColorTable { - get { - if (Owner != null) { + private ProfessionalColorTable ColorTable + { + get + { + if (Owner != null) + { ToolStripProfessionalRenderer renderer = Owner.Renderer as ToolStripProfessionalRenderer; - if (renderer != null) { + if (renderer != null) + { return renderer.ColorTable; } } @@ -568,100 +654,130 @@ private ProfessionalColorTable ColorTable { /// /// The new instance of the accessibility object for this ToolStripComboBoxControl item /// - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new ToolStripComboBoxControlAccessibleObject(this); } - internal override FlatComboAdapter CreateFlatComboAdapterInstance() { + internal override FlatComboAdapter CreateFlatComboAdapterInstance() + { return new ToolStripComboBoxFlatComboAdapter(this); } - internal class ToolStripComboBoxFlatComboAdapter : FlatComboAdapter { + internal class ToolStripComboBoxFlatComboAdapter : FlatComboAdapter + { - public ToolStripComboBoxFlatComboAdapter(ComboBox comboBox) : base(comboBox, /*smallButton=*/true) { + public ToolStripComboBoxFlatComboAdapter(ComboBox comboBox) : base(comboBox, /*smallButton=*/true) + { } - private static bool UseBaseAdapter(ComboBox comboBox) { + private static bool UseBaseAdapter(ComboBox comboBox) + { ToolStripComboBoxControl toolStripComboBox = comboBox as ToolStripComboBoxControl; - if (toolStripComboBox == null || !(toolStripComboBox.Owner.Renderer is ToolStripProfessionalRenderer)) { + if (toolStripComboBox == null || !(toolStripComboBox.Owner.Renderer is ToolStripProfessionalRenderer)) + { Debug.Assert(toolStripComboBox != null, "Why are we here and not a toolstrip combo?"); return true; } return false; } - private static ProfessionalColorTable GetColorTable(ToolStripComboBoxControl toolStripComboBoxControl) { - if (toolStripComboBoxControl != null) { + private static ProfessionalColorTable GetColorTable(ToolStripComboBoxControl toolStripComboBoxControl) + { + if (toolStripComboBoxControl != null) + { return toolStripComboBoxControl.ColorTable; } - return ProfessionalColors.ColorTable; + return ProfessionalColors.ColorTable; } - protected override Color GetOuterBorderColor(ComboBox comboBox) { - if (UseBaseAdapter(comboBox)) { + protected override Color GetOuterBorderColor(ComboBox comboBox) + { + if (UseBaseAdapter(comboBox)) + { return base.GetOuterBorderColor(comboBox); - } + } return (comboBox.Enabled) ? SystemColors.Window : GetColorTable(comboBox as ToolStripComboBoxControl).ComboBoxBorder; } - protected override Color GetPopupOuterBorderColor(ComboBox comboBox, bool focused) { - if (UseBaseAdapter(comboBox)) { + protected override Color GetPopupOuterBorderColor(ComboBox comboBox, bool focused) + { + if (UseBaseAdapter(comboBox)) + { return base.GetPopupOuterBorderColor(comboBox, focused); } - if (!comboBox.Enabled) { + if (!comboBox.Enabled) + { return SystemColors.ControlDark; } return (focused) ? GetColorTable(comboBox as ToolStripComboBoxControl).ComboBoxBorder : SystemColors.Window; } - protected override void DrawFlatComboDropDown(ComboBox comboBox, Graphics g, Rectangle dropDownRect) { - if (UseBaseAdapter(comboBox)) { - base.DrawFlatComboDropDown(comboBox, g, dropDownRect); - return; + protected override void DrawFlatComboDropDown(ComboBox comboBox, Graphics g, Rectangle dropDownRect) + { + if (UseBaseAdapter(comboBox)) + { + base.DrawFlatComboDropDown(comboBox, g, dropDownRect); + return; } - if (!comboBox.Enabled || !ToolStripManager.VisualStylesEnabled) { + if (!comboBox.Enabled || !ToolStripManager.VisualStylesEnabled) + { g.FillRectangle(SystemBrushes.Control, dropDownRect); } - else { + else + { ToolStripComboBoxControl toolStripComboBox = comboBox as ToolStripComboBoxControl; ProfessionalColorTable colorTable = GetColorTable(toolStripComboBox); - if (!comboBox.DroppedDown) { + if (!comboBox.DroppedDown) + { bool focused = comboBox.ContainsFocus || comboBox.MouseIsOver; - if (focused) { - using (Brush b = new LinearGradientBrush(dropDownRect, colorTable.ComboBoxButtonSelectedGradientBegin, colorTable.ComboBoxButtonSelectedGradientEnd, LinearGradientMode.Vertical)) { + if (focused) + { + using (Brush b = new LinearGradientBrush(dropDownRect, colorTable.ComboBoxButtonSelectedGradientBegin, colorTable.ComboBoxButtonSelectedGradientEnd, LinearGradientMode.Vertical)) + { g.FillRectangle(b, dropDownRect); } } - else if (toolStripComboBox.Owner.IsOnOverflow) { - using (Brush b = new SolidBrush(colorTable.ComboBoxButtonOnOverflow)) { + else if (toolStripComboBox.Owner.IsOnOverflow) + { + using (Brush b = new SolidBrush(colorTable.ComboBoxButtonOnOverflow)) + { g.FillRectangle(b, dropDownRect); } } - else { - using (Brush b = new LinearGradientBrush(dropDownRect, colorTable.ComboBoxButtonGradientBegin, colorTable.ComboBoxButtonGradientEnd, LinearGradientMode.Vertical)) { + else + { + using (Brush b = new LinearGradientBrush(dropDownRect, colorTable.ComboBoxButtonGradientBegin, colorTable.ComboBoxButtonGradientEnd, LinearGradientMode.Vertical)) + { g.FillRectangle(b, dropDownRect); } } } - else { - using (Brush b = new LinearGradientBrush(dropDownRect, colorTable.ComboBoxButtonPressedGradientBegin, colorTable.ComboBoxButtonPressedGradientEnd, LinearGradientMode.Vertical)) { + else + { + using (Brush b = new LinearGradientBrush(dropDownRect, colorTable.ComboBoxButtonPressedGradientBegin, colorTable.ComboBoxButtonPressedGradientEnd, LinearGradientMode.Vertical)) + { g.FillRectangle(b, dropDownRect); } } } Brush brush; - if (comboBox.Enabled) { - if (SystemInformation.HighContrast && (comboBox.ContainsFocus || comboBox.MouseIsOver) && ToolStripManager.VisualStylesEnabled) { + if (comboBox.Enabled) + { + if (SystemInformation.HighContrast && (comboBox.ContainsFocus || comboBox.MouseIsOver) && ToolStripManager.VisualStylesEnabled) + { brush = SystemBrushes.HighlightText; } - else { + else + { brush = SystemBrushes.ControlText; } } - else { + else + { brush = SystemBrushes.GrayText; } Point middle = new Point(dropDownRect.Left + dropDownRect.Width / 2, dropDownRect.Top + dropDownRect.Height / 2); @@ -669,46 +785,55 @@ protected override void DrawFlatComboDropDown(ComboBox comboBox, Graphics g, Rec // if the width is odd - favor pushing it over one pixel right. middle.X += (dropDownRect.Width % 2); g.FillPolygon(brush, new Point[] { - new Point(middle.X - FlatComboAdapter.Offset2Pixels, middle.Y - 1), - new Point(middle.X + FlatComboAdapter.Offset2Pixels + 1, middle.Y - 1), + new Point(middle.X - FlatComboAdapter.Offset2Pixels, middle.Y - 1), + new Point(middle.X + FlatComboAdapter.Offset2Pixels + 1, middle.Y - 1), new Point(middle.X, middle.Y + FlatComboAdapter.Offset2Pixels) }); } } - protected override bool IsInputKey(Keys keyData) { - if ((keyData & Keys.Alt) == Keys.Alt) { - if ((keyData & Keys.Down) == Keys.Down || (keyData & Keys.Up) == Keys.Up) { + protected override bool IsInputKey(Keys keyData) + { + if ((keyData & Keys.Alt) == Keys.Alt) + { + if ((keyData & Keys.Down) == Keys.Down || (keyData & Keys.Up) == Keys.Up) + { return true; } } return base.IsInputKey(keyData); } - protected override void OnDropDownClosed(EventArgs e) { + protected override void OnDropDownClosed(EventArgs e) + { base.OnDropDownClosed(e); Invalidate(); - Update(); + Update(); } internal override bool SupportsUiaProviders => true; - internal class ToolStripComboBoxControlAccessibleObject : ComboBox.ComboBoxAccessibleObject { + internal class ToolStripComboBoxControlAccessibleObject : ComboBox.ComboBoxAccessibleObject + { private ComboBox.ChildAccessibleObject childAccessibleObject; - public ToolStripComboBoxControlAccessibleObject(ToolStripComboBoxControl toolStripComboBoxControl) : base(toolStripComboBoxControl) { + public ToolStripComboBoxControlAccessibleObject(ToolStripComboBoxControl toolStripComboBoxControl) : base(toolStripComboBoxControl) + { childAccessibleObject = new ChildAccessibleObject(toolStripComboBoxControl, toolStripComboBoxControl.Handle); } - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - switch (direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { + switch (direction) + { case UnsafeNativeMethods.NavigateDirection.Parent: case UnsafeNativeMethods.NavigateDirection.PreviousSibling: case UnsafeNativeMethods.NavigateDirection.NextSibling: var toolStripComboBoxControl = Owner as ToolStripComboBoxControl; - if (toolStripComboBoxControl != null) { + if (toolStripComboBoxControl != null) + { return toolStripComboBoxControl.Owner.AccessibilityObject.FragmentNavigate(direction); } break; @@ -717,10 +842,13 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga return base.FragmentNavigate(direction); } - internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot { - get { + internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot + { + get + { var toolStripComboBoxControl = this.Owner as ToolStripComboBoxControl; - if (toolStripComboBoxControl != null) { + if (toolStripComboBoxControl != null) + { return toolStripComboBoxControl.Owner.Owner.AccessibilityObject; } @@ -728,8 +856,10 @@ internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRo } } - internal override object GetPropertyValue(int propertyID) { - switch (propertyID) { + internal override object GetPropertyValue(int propertyID) + { + switch (propertyID) + { case NativeMethods.UIA_ControlTypePropertyId: return NativeMethods.UIA_ComboBoxControlTypeId; case NativeMethods.UIA_IsOffscreenPropertyId: @@ -742,7 +872,8 @@ internal override object GetPropertyValue(int propertyID) { internal override bool IsPatternSupported(int patternId) { if (patternId == NativeMethods.UIA_ExpandCollapsePatternId || - patternId == NativeMethods.UIA_ValuePatternId) { + patternId == NativeMethods.UIA_ValuePatternId) + { return true; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs index c341c6262bf..bba32818630 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. /// this is the UBER container for ToolStripPanels. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System; @@ -15,12 +16,13 @@ namespace System.Windows.Forms { using System.Collections; using System.Globalization; using System.Windows.Forms.Layout; - + [ComVisible(true)] [ClassInterface(ClassInterfaceType.AutoDispatch)] [Designer("System.Windows.Forms.Design.ToolStripContainerDesigner, " + AssemblyRef.SystemDesign)] [SRDescription(nameof(SR.ToolStripContainerDesc))] - public class ToolStripContainer : ContainerControl { + public class ToolStripContainer : ContainerControl + { private ToolStripPanel topPanel; private ToolStripPanel bottomPanel; @@ -28,13 +30,15 @@ public class ToolStripContainer : ContainerControl { private ToolStripPanel rightPanel; private ToolStripContentPanel contentPanel; - - public ToolStripContainer() { + + public ToolStripContainer() + { SetStyle(ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor, true); SuspendLayout(); - try { + try + { // undone - smart demand creation topPanel = new ToolStripPanel(this); bottomPanel = new ToolStripPanel(this); @@ -48,7 +52,8 @@ public ToolStripContainer() { leftPanel.Dock = DockStyle.Left; ToolStripContainerTypedControlCollection controlCollection = this.Controls as ToolStripContainerTypedControlCollection; - if (controlCollection != null) { + if (controlCollection != null) + { controlCollection.AddInternal(contentPanel); controlCollection.AddInternal(leftPanel); controlCollection.AddInternal(rightPanel); @@ -58,7 +63,8 @@ public ToolStripContainer() { // else consider throw new exception } - finally { + finally + { ResumeLayout(true); } } @@ -69,7 +75,8 @@ public ToolStripContainer() { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public override bool AutoScroll { + public override bool AutoScroll + { get { return base.AutoScroll; } set { base.AutoScroll = value; } } @@ -79,7 +86,8 @@ public override bool AutoScroll { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Size AutoScrollMargin { + public new Size AutoScrollMargin + { get { return base.AutoScrollMargin; } set { base.AutoScrollMargin = value; } } @@ -89,7 +97,8 @@ public override bool AutoScroll { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Size AutoScrollMinSize { + public new Size AutoScrollMinSize + { get { return base.AutoScrollMinSize; } set { base.AutoScrollMinSize = value; } } @@ -98,7 +107,8 @@ public override bool AutoScroll { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Color BackColor { + public new Color BackColor + { get { return base.BackColor; } set { base.BackColor = value; } } @@ -108,7 +118,8 @@ public override bool AutoScroll { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new event EventHandler BackColorChanged { + public new event EventHandler BackColorChanged + { add => base.BackColorChanged += value; remove => base.BackColorChanged -= value; } @@ -118,7 +129,8 @@ public override bool AutoScroll { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Image BackgroundImage { + public new Image BackgroundImage + { get { return base.BackgroundImage; } set { base.BackgroundImage = value; } } @@ -129,7 +141,8 @@ public override bool AutoScroll { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new event EventHandler BackgroundImageChanged { + public new event EventHandler BackgroundImageChanged + { add => base.BackgroundImageChanged += value; remove => base.BackgroundImageChanged -= value; } @@ -139,7 +152,8 @@ public override bool AutoScroll { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public override ImageLayout BackgroundImageLayout { + public override ImageLayout BackgroundImageLayout + { get { return base.BackgroundImageLayout; } set { base.BackgroundImageLayout = value; } } @@ -149,7 +163,8 @@ public override ImageLayout BackgroundImageLayout { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new event EventHandler BackgroundImageLayoutChanged { + public new event EventHandler BackgroundImageLayoutChanged + { add => base.BackgroundImageLayoutChanged += value; remove => base.BackgroundImageLayoutChanged += value; } @@ -160,8 +175,10 @@ public override ImageLayout BackgroundImageLayout { Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Content) ] - public ToolStripPanel BottomToolStripPanel { - get { + public ToolStripPanel BottomToolStripPanel + { + get + { return bottomPanel; } } @@ -171,11 +188,14 @@ public ToolStripPanel BottomToolStripPanel { SRDescription(nameof(SR.ToolStripContainerBottomToolStripPanelVisibleDescr)), DefaultValue(true) ] - public bool BottomToolStripPanelVisible { - get { + public bool BottomToolStripPanelVisible + { + get + { return BottomToolStripPanel.Visible; } - set { + set + { BottomToolStripPanel.Visible = value; } } @@ -186,8 +206,10 @@ public bool BottomToolStripPanelVisible { Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Content) ] - public ToolStripContentPanel ContentPanel { - get { + public ToolStripContentPanel ContentPanel + { + get + { return contentPanel; } } @@ -197,13 +219,15 @@ public ToolStripContentPanel ContentPanel { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public new bool CausesValidation { + public new bool CausesValidation + { get { return base.CausesValidation; } set { base.CausesValidation = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler CausesValidationChanged { + public new event EventHandler CausesValidationChanged + { add => base.CausesValidationChanged += value; remove => base.CausesValidationChanged -= value; } @@ -213,13 +237,15 @@ public ToolStripContentPanel ContentPanel { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public new ContextMenuStrip ContextMenuStrip { + public new ContextMenuStrip ContextMenuStrip + { get { return base.ContextMenuStrip; } set { base.ContextMenuStrip = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler ContextMenuStripChanged { + public new event EventHandler ContextMenuStripChanged + { add => base.ContextMenuStripChanged += value; remove => base.ContextMenuStripChanged -= value; } @@ -229,7 +255,8 @@ public ToolStripContentPanel ContentPanel { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public override Cursor Cursor { + public override Cursor Cursor + { get { return base.Cursor; } set { base.Cursor = value; } } @@ -239,14 +266,17 @@ public override Cursor Cursor { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public new event EventHandler CursorChanged { + public new event EventHandler CursorChanged + { add => base.CursorChanged += value; remove => base.CursorChanged -= value; } - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(150, 175); } } @@ -256,7 +286,8 @@ protected override Size DefaultSize { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public new Color ForeColor { + public new Color ForeColor + { get { return base.ForeColor; } set { base.ForeColor = value; } } @@ -266,7 +297,8 @@ protected override Size DefaultSize { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public new event EventHandler ForeColorChanged { + public new event EventHandler ForeColorChanged + { add => base.ForeColorChanged += value; remove => base.ForeColorChanged -= value; } @@ -277,8 +309,10 @@ protected override Size DefaultSize { Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Content) ] - public ToolStripPanel LeftToolStripPanel { - get { + public ToolStripPanel LeftToolStripPanel + { + get + { return leftPanel; } } @@ -289,24 +323,29 @@ public ToolStripPanel LeftToolStripPanel { SRDescription(nameof(SR.ToolStripContainerLeftToolStripPanelVisibleDescr)), DefaultValue(true) ] - public bool LeftToolStripPanelVisible { - get { + public bool LeftToolStripPanelVisible + { + get + { return LeftToolStripPanel.Visible; } - set { + set + { LeftToolStripPanel.Visible = value; } } - + [ SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripContainerRightToolStripPanelDescr)), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Content) ] - public ToolStripPanel RightToolStripPanel { - get { + public ToolStripPanel RightToolStripPanel + { + get + { return rightPanel; } } @@ -316,11 +355,14 @@ public ToolStripPanel RightToolStripPanel { SRDescription(nameof(SR.ToolStripContainerRightToolStripPanelVisibleDescr)), DefaultValue(true) ] - public bool RightToolStripPanelVisible { - get { + public bool RightToolStripPanelVisible + { + get + { return RightToolStripPanel.Visible; } - set { + set + { RightToolStripPanel.Visible = value; } } @@ -331,8 +373,10 @@ public bool RightToolStripPanelVisible { Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Content) ] - public ToolStripPanel TopToolStripPanel { - get { + public ToolStripPanel TopToolStripPanel + { + get + { return topPanel; } } @@ -342,11 +386,14 @@ public ToolStripPanel TopToolStripPanel { SRDescription(nameof(SR.ToolStripContainerTopToolStripPanelVisibleDescr)), DefaultValue(true) ] - public bool TopToolStripPanelVisible { - get { + public bool TopToolStripPanelVisible + { + get + { return TopToolStripPanel.Visible; } - set { + set + { TopToolStripPanel.Visible = value; } } @@ -357,100 +404,128 @@ public bool TopToolStripPanelVisible { /// [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public new Control.ControlCollection Controls { - get { + public new Control.ControlCollection Controls + { + get + { return base.Controls; } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override Control.ControlCollection CreateControlsInstance() { + protected override Control.ControlCollection CreateControlsInstance() + { return new ToolStripContainerTypedControlCollection(this, /*isReadOnly*/true); } - protected override void OnRightToLeftChanged(EventArgs e) { + protected override void OnRightToLeftChanged(EventArgs e) + { base.OnRightToLeftChanged(e); RightToLeft rightToLeft = this.RightToLeft; // no need to suspend layout - we're already in a layout transaction. - if (rightToLeft == RightToLeft.Yes) { + if (rightToLeft == RightToLeft.Yes) + { RightToolStripPanel.Dock = DockStyle.Left; LeftToolStripPanel.Dock = DockStyle.Right; } - else { + else + { RightToolStripPanel.Dock = DockStyle.Right; LeftToolStripPanel.Dock = DockStyle.Left; } } - protected override void OnSizeChanged(EventArgs e) { - foreach (Control c in this.Controls) { + protected override void OnSizeChanged(EventArgs e) + { + foreach (Control c in this.Controls) + { c.SuspendLayout(); } base.OnSizeChanged(e); - foreach (Control c in this.Controls) { + foreach (Control c in this.Controls) + { c.ResumeLayout(); } } - internal override void RecreateHandleCore() { + internal override void RecreateHandleCore() + { //If ToolStripContainer's Handle is getting created demand create the childControl handle's - if (IsHandleCreated) { - foreach(Control c in Controls) { - c.CreateControl(true); + if (IsHandleCreated) + { + foreach (Control c in Controls) + { + c.CreateControl(true); } } base.RecreateHandleCore(); - + } - internal override bool AllowsKeyboardToolTip() { + internal override bool AllowsKeyboardToolTip() + { return false; } - internal class ToolStripContainerTypedControlCollection : WindowsFormsUtils.ReadOnlyControlCollection { + internal class ToolStripContainerTypedControlCollection : WindowsFormsUtils.ReadOnlyControlCollection + { ToolStripContainer owner; Type contentPanelType = typeof(ToolStripContentPanel); Type panelType = typeof(ToolStripPanel); public ToolStripContainerTypedControlCollection(Control c, bool isReadOnly) - : base(c, isReadOnly) { + : base(c, isReadOnly) + { this.owner = c as ToolStripContainer; } - public override void Add(Control value) { - if (value == null) { + public override void Add(Control value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } - if (IsReadOnly) { + if (IsReadOnly) + { throw new NotSupportedException(SR.ToolStripContainerUseContentPanel); } Type controlType = value.GetType(); - if (!contentPanelType.IsAssignableFrom(controlType) && !panelType.IsAssignableFrom(controlType)) { + if (!contentPanelType.IsAssignableFrom(controlType) && !panelType.IsAssignableFrom(controlType)) + { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, string.Format(SR.TypedControlCollectionShouldBeOfTypes, contentPanelType.Name, panelType.Name)), value.GetType().Name); } base.Add(value); } - public override void Remove(Control value) { - if (value is ToolStripPanel || value is ToolStripContentPanel) { - if (!owner.DesignMode) { - if (IsReadOnly) throw new NotSupportedException(SR.ReadonlyControlsCollection); + public override void Remove(Control value) + { + if (value is ToolStripPanel || value is ToolStripContentPanel) + { + if (!owner.DesignMode) + { + if (IsReadOnly) + throw new NotSupportedException(SR.ReadonlyControlsCollection); } } base.Remove(value); } - internal override void SetChildIndexInternal(Control child, int newIndex) { - if (child is ToolStripPanel || child is ToolStripContentPanel) { - if (!owner.DesignMode) { - if (IsReadOnly) { + internal override void SetChildIndexInternal(Control child, int newIndex) + { + if (child is ToolStripPanel || child is ToolStripContentPanel) + { + if (!owner.DesignMode) + { + if (IsReadOnly) + { throw new NotSupportedException(SR.ReadonlyControlsCollection); } } - else { + else + { // just no-op it at DT. return; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContentPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContentPanel.cs index b4b8fc5b610..e037bfd29e6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContentPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContentPanel.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; using System; using System.ComponentModel; @@ -11,7 +12,7 @@ namespace System.Windows.Forms { using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.ComponentModel.Design; - + [ ComVisible(true), ClassInterface(ClassInterfaceType.AutoDispatch), @@ -21,101 +22,117 @@ namespace System.Windows.Forms { InitializationEvent(nameof(Load)), ToolboxItem(false) ] - public class ToolStripContentPanel : Panel { - private ToolStripRendererSwitcher rendererSwitcher = null; - private BitVector32 state = new BitVector32(); - private static readonly int stateLastDoubleBuffer = BitVector32.CreateMask(); + public class ToolStripContentPanel : Panel + { + private ToolStripRendererSwitcher rendererSwitcher = null; + private BitVector32 state = new BitVector32(); + private static readonly int stateLastDoubleBuffer = BitVector32.CreateMask(); + + private static readonly object EventRendererChanged = new object(); + private static readonly object EventLoad = new object(); - private static readonly object EventRendererChanged = new object(); - private static readonly object EventLoad = new object(); - - public ToolStripContentPanel() { + public ToolStripContentPanel() + { // Consider: OptimizedDoubleBuffer SetStyle(ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor, true); } - /// - /// Allows the control to optionally shrink when AutoSize is true. - /// - [ - EditorBrowsable(EditorBrowsableState.Never), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false), - Localizable(false) - ] - public override AutoSizeMode AutoSizeMode { - get { + /// + /// Allows the control to optionally shrink when AutoSize is true. + /// + [ + EditorBrowsable(EditorBrowsableState.Never), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), + Browsable(false), + Localizable(false) + ] + public override AutoSizeMode AutoSizeMode + { + get + { return AutoSizeMode.GrowOnly; } - set { + set + { } - } - - [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public override AnchorStyles Anchor { - get { - return base.Anchor; - } - set { - base.Anchor = value; - } - } - - [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never) + } + + [ + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public override bool AutoScroll { + public override AnchorStyles Anchor + { + get + { + return base.Anchor; + } + set + { + base.Anchor = value; + } + } + + [ + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never) + ] + public override bool AutoScroll + { get { return base.AutoScroll; } set { base.AutoScroll = value; } } [ - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Size AutoScrollMargin { + public new Size AutoScrollMargin + { get { return base.AutoScrollMargin; } set { base.AutoScrollMargin = value; } } [ - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Size AutoScrollMinSize { + public new Size AutoScrollMinSize + { get { return base.AutoScrollMinSize; } set { base.AutoScrollMinSize = value; } } [ - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public override bool AutoSize { + public override bool AutoSize + { get { return base.AutoSize; } - set { base.AutoSize = value; } + set { base.AutoSize = value; } } - public override Color BackColor { - get { - return base.BackColor; + public override Color BackColor + { + get + { + return base.BackColor; } - set { + set + { // To support transparency on ToolStripContainer, we need this check // to ensure that background color of the container reflects the // ContentPanel - if (this.ParentInternal is ToolStripContainer && value == Color.Transparent) { - this.ParentInternal.BackColor = Color.Transparent; + if (this.ParentInternal is ToolStripContainer && value == Color.Transparent) + { + this.ParentInternal.BackColor = Color.Transparent; } - base.BackColor = value; + base.BackColor = value; } } @@ -124,7 +141,8 @@ public override Color BackColor { Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new event EventHandler AutoSizeChanged{ + public new event EventHandler AutoSizeChanged + { add => base.AutoSizeChanged += value; remove => base.AutoSizeChanged -= value; } @@ -133,13 +151,15 @@ public override Color BackColor { Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new bool CausesValidation { + public new bool CausesValidation + { get { return base.CausesValidation; } set { base.CausesValidation = value; } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler CausesValidationChanged { + public new event EventHandler CausesValidationChanged + { add => base.CausesValidationChanged += value; remove => base.CausesValidationChanged -= value; } @@ -148,62 +168,71 @@ public override Color BackColor { Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public override DockStyle Dock { - get { + public override DockStyle Dock + { + get + { return base.Dock; } - set { - base.Dock=value; + set + { + base.Dock = value; } } [ - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new event EventHandler DockChanged { - add => base.DockChanged += value; + public new event EventHandler DockChanged + { + add => base.DockChanged += value; remove => base.DockChanged -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ToolStripContentPanelOnLoadDescr))] - public event EventHandler Load { + public event EventHandler Load + { add => Events.AddHandler(EventLoad, value); remove => Events.RemoveHandler(EventLoad, value); } [ - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Point Location { + public new Point Location + { get { return base.Location; } set { base.Location = value; } } [ - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new event EventHandler LocationChanged { - add => base.LocationChanged += value; + public new event EventHandler LocationChanged + { + add => base.LocationChanged += value; remove => base.LocationChanged -= value; } [ - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public override Size MinimumSize { + public override Size MinimumSize + { get { return base.MinimumSize; } set { base.MinimumSize = value; } } [ - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public override Size MaximumSize { + public override Size MaximumSize + { get { return base.MaximumSize; } set { base.MaximumSize = value; } } @@ -211,34 +240,41 @@ public override Size MaximumSize { [ EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) + Browsable(false) ] - public new string Name { - get { + public new string Name + { + get + { return base.Name; } - set { + set + { base.Name = value; } } - + [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new int TabIndex { - get { + public new int TabIndex + { + get + { return base.TabIndex; } - set { + set + { base.TabIndex = value; } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler TabIndexChanged { + public new event EventHandler TabIndexChanged + { add => base.TabIndexChanged += value; remove => base.TabIndexChanged -= value; } @@ -248,24 +284,31 @@ public override Size MaximumSize { Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public new bool TabStop { - get { + public new bool TabStop + { + get + { return base.TabStop; } - set { + set + { base.TabStop = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler TabStopChanged { + public new event EventHandler TabStopChanged + { add => base.TabStopChanged += value; remove => base.TabStopChanged -= value; } - private ToolStripRendererSwitcher RendererSwitcher { - get { - if (rendererSwitcher == null) { + private ToolStripRendererSwitcher RendererSwitcher + { + get + { + if (rendererSwitcher == null) + { rendererSwitcher = new ToolStripRendererSwitcher(this, ToolStripRenderMode.System); HandleRendererChanged(this, EventArgs.Empty); rendererSwitcher.RendererChanged += new EventHandler(HandleRendererChanged); @@ -274,100 +317,120 @@ private ToolStripRendererSwitcher RendererSwitcher { } } - + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] - public ToolStripRenderer Renderer { - get { + public ToolStripRenderer Renderer + { + get + { return RendererSwitcher.Renderer; } - set { + set + { RendererSwitcher.Renderer = value; } } - + [ SRDescription(nameof(SR.ToolStripRenderModeDescr)), SRCategory(nameof(SR.CatAppearance)), ] - public ToolStripRenderMode RenderMode { - get { - return RendererSwitcher.RenderMode; + public ToolStripRenderMode RenderMode + { + get + { + return RendererSwitcher.RenderMode; } - set { + set + { RendererSwitcher.RenderMode = value; } } [SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripRendererChanged))] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] - public event EventHandler RendererChanged { + public event EventHandler RendererChanged + { add => Events.AddHandler(EventRendererChanged, value); remove => Events.RemoveHandler(EventRendererChanged, value); } - private void HandleRendererChanged(object sender, EventArgs e) { - OnRendererChanged(e); + private void HandleRendererChanged(object sender, EventArgs e) + { + OnRendererChanged(e); } - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { base.OnHandleCreated(e); - if (!RecreatingHandle) { + if (!RecreatingHandle) + { OnLoad(EventArgs.Empty); } } - + [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnLoad(EventArgs e) { + protected virtual void OnLoad(EventArgs e) + { // There is no good way to explain this event except to say // that it's just another name for OnControlCreated. EventHandler handler = (EventHandler)Events[EventLoad]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnPaintBackground(PaintEventArgs e) { + protected override void OnPaintBackground(PaintEventArgs e) + { ToolStripContentPanelRenderEventArgs rea = new ToolStripContentPanelRenderEventArgs(e.Graphics, this); - + Renderer.DrawToolStripContentPanelBackground(rea); - if (!rea.Handled) { + if (!rea.Handled) + { base.OnPaintBackground(e); } } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] - protected virtual void OnRendererChanged(EventArgs e) { + protected virtual void OnRendererChanged(EventArgs e) + { - // we dont want to be greedy.... if we're using TSProfessionalRenderer go DBuf, else dont. - if (Renderer is ToolStripProfessionalRenderer) { + // we dont want to be greedy.... if we're using TSProfessionalRenderer go DBuf, else dont. + if (Renderer is ToolStripProfessionalRenderer) + { state[stateLastDoubleBuffer] = this.DoubleBuffered; //this.DoubleBuffered = true; SetStyle(ControlStyles.OptimizedDoubleBuffer, true); - } - else { + } + else + { // restore DBuf this.DoubleBuffered = state[stateLastDoubleBuffer]; - } - - Renderer.InitializeContentPanel(this); + } + + Renderer.InitializeContentPanel(this); + + this.Invalidate(); + + EventHandler handler = (EventHandler)Events[EventRendererChanged]; + if (handler != null) + handler(this, e); - this.Invalidate(); - - EventHandler handler = (EventHandler)Events[EventRendererChanged]; - if (handler != null) handler(this,e); - } - private void ResetRenderMode() { - this.RendererSwitcher.ResetRenderMode(); + private void ResetRenderMode() + { + this.RendererSwitcher.ResetRenderMode(); } - private bool ShouldSerializeRenderMode() { - return this.RendererSwitcher.ShouldSerializeRenderMode(); + private bool ShouldSerializeRenderMode() + { + return this.RendererSwitcher.ShouldSerializeRenderMode(); } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs index cec7f9aa2dc..06d26c59a3e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs @@ -21,31 +21,33 @@ public class ToolStripControlHost : ToolStripItem private int suspendSyncSizeCount = 0; private ContentAlignment controlAlign = ContentAlignment.MiddleCenter; private bool inSetVisibleCore = false; - - internal static readonly object EventGotFocus = new object(); - internal static readonly object EventLostFocus = new object(); - internal static readonly object EventKeyDown = new object(); - internal static readonly object EventKeyPress = new object(); - internal static readonly object EventKeyUp = new object(); - internal static readonly object EventEnter = new object(); - internal static readonly object EventLeave = new object(); - internal static readonly object EventValidated = new object(); - internal static readonly object EventValidating = new object(); + + internal static readonly object EventGotFocus = new object(); + internal static readonly object EventLostFocus = new object(); + internal static readonly object EventKeyDown = new object(); + internal static readonly object EventKeyPress = new object(); + internal static readonly object EventKeyUp = new object(); + internal static readonly object EventEnter = new object(); + internal static readonly object EventLeave = new object(); + internal static readonly object EventValidated = new object(); + internal static readonly object EventValidating = new object(); /// /// Constructs a ToolStripControlHost /// - - public ToolStripControlHost(Control c) { - if (c == null) { + + public ToolStripControlHost(Control c) + { + if (c == null) + { throw new ArgumentNullException(nameof(c), SR.ControlCannotBeNull); } control = c; SyncControlParent(); c.Visible = true; SetBounds(c.Bounds); - + // now that we have a control set in, update the bounds. Rectangle bounds = this.Bounds; CommonProperties.UpdateSpecifiedBounds(c, bounds.X, bounds.Y, bounds.Width, bounds.Height); @@ -54,19 +56,23 @@ public ToolStripControlHost(Control c) { OnSubscribeControlEvents(c); } - public ToolStripControlHost(Control c, string name) : this (c){ + public ToolStripControlHost(Control c, string name) : this(c) + { this.Name = name; } - - public override Color BackColor { - get { + + public override Color BackColor + { + get + { return Control.BackColor; } - set { + set + { Control.BackColor = value; } } - + /// /// /// Gets or sets the image that is displayed on a . @@ -78,37 +84,46 @@ public override Color BackColor { SRDescription(nameof(SR.ToolStripItemImageDescr)), DefaultValue(null) ] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return Control.BackgroundImage; } - set { + set + { Control.BackgroundImage = value; } } - + [ SRCategory(nameof(SR.CatAppearance)), DefaultValue(ImageLayout.Tile), Localizable(true), SRDescription(nameof(SR.ControlBackgroundImageLayoutDescr)) ] - public override ImageLayout BackgroundImageLayout { - get { - return Control.BackgroundImageLayout; - } - set { - Control.BackgroundImageLayout = value; - } + public override ImageLayout BackgroundImageLayout + { + get + { + return Control.BackgroundImageLayout; + } + set + { + Control.BackgroundImageLayout = value; + } } /// /// Overriden to return value from Control.CanSelect. /// - public override bool CanSelect { - get { - if (control != null) { - return (DesignMode || this.Control.CanSelect); - } + public override bool CanSelect + { + get + { + if (control != null) + { + return (DesignMode || this.Control.CanSelect); + } return false; } } @@ -118,19 +133,24 @@ public override bool CanSelect { DefaultValue(true), SRDescription(nameof(SR.ControlCausesValidationDescr)) ] - public bool CausesValidation { + public bool CausesValidation + { get { return Control.CausesValidation; } set { Control.CausesValidation = value; } } [DefaultValue(ContentAlignment.MiddleCenter), Browsable(false)] - public ContentAlignment ControlAlign { + public ContentAlignment ControlAlign + { get { return controlAlign; } - set { - if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) { + set + { + if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ContentAlignment)); } - if (controlAlign != value) { + if (controlAlign != value) + { controlAlign = value; OnBoundsChanged(); } @@ -141,14 +161,18 @@ public ContentAlignment ControlAlign { /// The control that this item is hosting. /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public Control Control { - get { + public Control Control + { + get + { return control; } } - internal AccessibleObject ControlAccessibilityObject { - get { + internal AccessibleObject ControlAccessibilityObject + { + get + { return Control?.AccessibilityObject; } } @@ -157,9 +181,12 @@ internal AccessibleObject ControlAccessibilityObject { /// 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. /// - protected override Size DefaultSize { - get { - if (Control != null) { + protected override Size DefaultSize + { + get + { + if (Control != null) + { // When you create the control - it sets up its size as its default size. // Since the property is protected we dont know for sure, but this is a pretty good guess. return Control.Size; @@ -169,18 +196,22 @@ protected override Size DefaultSize { } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public new ToolStripItemDisplayStyle DisplayStyle { - get { - return base.DisplayStyle; + public new ToolStripItemDisplayStyle DisplayStyle + { + get + { + return base.DisplayStyle; } - set { - base.DisplayStyle = value; + set + { + base.DisplayStyle = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler DisplayStyleChanged { - add => Events.AddHandler(EventDisplayStyleChanged, value); + public new event EventHandler DisplayStyleChanged + { + add => Events.AddHandler(EventDisplayStyleChanged, value); remove => Events.RemoveHandler(EventDisplayStyleChanged, value); } @@ -190,35 +221,45 @@ protected override Size DefaultSize { /// instead. /// [DefaultValue(false), Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new bool DoubleClickEnabled { - get { + public new bool DoubleClickEnabled + { + get + { return base.DoubleClickEnabled; } - set { + set + { base.DoubleClickEnabled = value; } } - public override Font Font { - get { + public override Font Font + { + get + { return Control.Font; } - set { + set + { Control.Font = value; } } - public override bool Enabled { - get { + public override bool Enabled + { + get + { return Control.Enabled; } - set { + set + { Control.Enabled = value; } } [SRCategory(nameof(SR.CatFocus)), SRDescription(nameof(SR.ControlOnEnterDescr))] - public event EventHandler Enter { + public event EventHandler Enter + { add => Events.AddHandler(EventEnter, value); remove => Events.RemoveHandler(EventEnter, value); } @@ -226,151 +267,179 @@ public event EventHandler Enter { [ Browsable(false), EditorBrowsable(EditorBrowsableState.Always) ] - public virtual bool Focused { - get { + public virtual bool Focused + { + get + { return Control.Focused; - } + } } - public override Color ForeColor { - get { + public override Color ForeColor + { + get + { return Control.ForeColor; } - set { + set + { Control.ForeColor = value; } } [ - SRCategory(nameof(SR.CatFocus)), - SRDescription(nameof(SR.ToolStripItemOnGotFocusDescr)), - Browsable(false), + SRCategory(nameof(SR.CatFocus)), + SRDescription(nameof(SR.ToolStripItemOnGotFocusDescr)), + Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced) ] - public event EventHandler GotFocus { + public event EventHandler GotFocus + { add => Events.AddHandler(EventGotFocus, value); remove => Events.RemoveHandler(EventGotFocus, value); } [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public override Image Image { - - - get { + public override Image Image + { + + + get + { return base.Image; } - set { + set + { base.Image = value; } } [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new ToolStripItemImageScaling ImageScaling { - get { + public new ToolStripItemImageScaling ImageScaling + { + get + { return base.ImageScaling; } - set { + set + { base.ImageScaling = value; } } [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Color ImageTransparentColor { - get { + public new Color ImageTransparentColor + { + get + { return base.ImageTransparentColor; } - set { + set + { base.ImageTransparentColor = value; } } [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new ContentAlignment ImageAlign { - get { + public new ContentAlignment ImageAlign + { + get + { return base.ImageAlign; } - set { + set + { base.ImageAlign = value; } } - [SRCategory(nameof(SR.CatFocus)), SRDescription(nameof(SR.ControlOnLeaveDescr))] - public event EventHandler Leave { - add => Events.AddHandler(EventLeave, value); - remove => Events.RemoveHandler(EventLeave, value); - } - - /// - /// Occurs when the control loses focus. - /// - [ - SRCategory(nameof(SR.CatFocus)), - SRDescription(nameof(SR.ToolStripItemOnLostFocusDescr)), - Browsable(false), - EditorBrowsable(EditorBrowsableState.Advanced) - ] - public event EventHandler LostFocus { - add => Events.AddHandler(EventLostFocus, value); - remove => Events.RemoveHandler(EventLostFocus, value); - } - - - /// - /// Occurs when a key is pressed down while the control has focus. - /// - [SRCategory(nameof(SR.CatKey)), SRDescription(nameof(SR.ControlOnKeyDownDescr))] - public event KeyEventHandler KeyDown { - add => Events.AddHandler(EventKeyDown, value); - remove => Events.RemoveHandler(EventKeyDown, value); - } - - /// - /// Occurs when a key is pressed while the control has focus. - /// - [SRCategory(nameof(SR.CatKey)), SRDescription(nameof(SR.ControlOnKeyPressDescr))] - public event KeyPressEventHandler KeyPress { - add => Events.AddHandler(EventKeyPress, value); - remove => Events.RemoveHandler(EventKeyPress, value); - } - - /// - /// Occurs when a key is released while the control has focus. - /// - [SRCategory(nameof(SR.CatKey)), SRDescription(nameof(SR.ControlOnKeyUpDescr))] - public event KeyEventHandler KeyUp { - add => Events.AddHandler(EventKeyUp, value); - remove => Events.RemoveHandler(EventKeyUp, value); - } + [SRCategory(nameof(SR.CatFocus)), SRDescription(nameof(SR.ControlOnLeaveDescr))] + public event EventHandler Leave + { + add => Events.AddHandler(EventLeave, value); + remove => Events.RemoveHandler(EventLeave, value); + } + + /// + /// Occurs when the control loses focus. + /// + [ + SRCategory(nameof(SR.CatFocus)), + SRDescription(nameof(SR.ToolStripItemOnLostFocusDescr)), + Browsable(false), + EditorBrowsable(EditorBrowsableState.Advanced) + ] + public event EventHandler LostFocus + { + add => Events.AddHandler(EventLostFocus, value); + remove => Events.RemoveHandler(EventLostFocus, value); + } + + + /// + /// Occurs when a key is pressed down while the control has focus. + /// + [SRCategory(nameof(SR.CatKey)), SRDescription(nameof(SR.ControlOnKeyDownDescr))] + public event KeyEventHandler KeyDown + { + add => Events.AddHandler(EventKeyDown, value); + remove => Events.RemoveHandler(EventKeyDown, value); + } + + /// + /// Occurs when a key is pressed while the control has focus. + /// + [SRCategory(nameof(SR.CatKey)), SRDescription(nameof(SR.ControlOnKeyPressDescr))] + public event KeyPressEventHandler KeyPress + { + add => Events.AddHandler(EventKeyPress, value); + remove => Events.RemoveHandler(EventKeyPress, value); + } + + /// + /// Occurs when a key is released while the control has focus. + /// + [SRCategory(nameof(SR.CatKey)), SRDescription(nameof(SR.ControlOnKeyUpDescr))] + public event KeyEventHandler KeyUp + { + add => Events.AddHandler(EventKeyUp, value); + remove => Events.RemoveHandler(EventKeyUp, value); + } /// /// 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. /// - public override RightToLeft RightToLeft { - get { - if (control != null) { + public override RightToLeft RightToLeft + { + get + { + if (control != null) + { return control.RightToLeft; } return base.RightToLeft; } - set { - if (control != null) { + set + { + if (control != null) + { control.RightToLeft = value; } } @@ -381,17 +450,22 @@ public override RightToLeft RightToLeft { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new bool RightToLeftAutoMirrorImage { - get { + public new bool RightToLeftAutoMirrorImage + { + get + { return base.RightToLeftAutoMirrorImage; } - set { + set + { base.RightToLeftAutoMirrorImage = value; } } - public override bool Selected { - get { + public override bool Selected + { + get + { if (Control != null) { return Control.Focused; @@ -400,27 +474,33 @@ public override bool Selected { } } - public override Size Size { - get { + public override Size Size + { + get + { return base.Size; } - set { + set + { Rectangle specifiedBounds = Rectangle.Empty; - if (control != null) { + if (control != null) + { // we dont normally update the specified bounds, but if someone explicitly sets // the size we should. specifiedBounds = control.Bounds; specifiedBounds.Size = value; CommonProperties.UpdateSpecifiedBounds(control, specifiedBounds.X, specifiedBounds.Y, specifiedBounds.Width, specifiedBounds.Height); } - + base.Size = value; - if (control != null) { + if (control != null) + { // checking again in case the control has adjusted the size. Rectangle bounds = control.Bounds; - if (bounds != specifiedBounds) { + if (bounds != specifiedBounds) + { CommonProperties.UpdateSpecifiedBounds(control, bounds.X, bounds.Y, bounds.Width, bounds.Height); } } @@ -431,11 +511,14 @@ public override Size Size { /// Overriden to set the Site for the control hosted. This is set at DesignTime when the component is added to the Container. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public override ISite Site { - get { + public override ISite Site + { + get + { return base.Site; } - set { + set + { base.Site = value; if (value != null) { @@ -452,77 +535,94 @@ public override ISite Site { /// Overriden to modify hosted control's text. /// [DefaultValue("")] - public override string Text { - get { + public override string Text + { + get + { return Control.Text; } - set { + set + { Control.Text = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new ContentAlignment TextAlign { - get { - return base.TextAlign; - } - set { - base.TextAlign = value; - } + public new ContentAlignment TextAlign + { + get + { + return base.TextAlign; + } + set + { + base.TextAlign = value; + } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DefaultValue(ToolStripTextDirection.Horizontal)] - public override ToolStripTextDirection TextDirection { - get { - return base.TextDirection; - } - set { - base.TextDirection = value; - } + public override ToolStripTextDirection TextDirection + { + get + { + return base.TextDirection; + } + set + { + base.TextDirection = value; + } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new TextImageRelation TextImageRelation { - get { - return base.TextImageRelation; - } - set { - base.TextImageRelation = value; - } + public new TextImageRelation TextImageRelation + { + get + { + return base.TextImageRelation; + } + set + { + base.TextImageRelation = value; + } } [SRCategory(nameof(SR.CatFocus)), SRDescription(nameof(SR.ControlOnValidatingDescr))] - public event CancelEventHandler Validating { + public event CancelEventHandler Validating + { add => Events.AddHandler(EventValidating, value); remove => Events.RemoveHandler(EventValidating, value); } [SRCategory(nameof(SR.CatFocus)), SRDescription(nameof(SR.ControlOnValidatedDescr))] - public event EventHandler Validated { + public event EventHandler Validated + { add => Events.AddHandler(EventValidated, value); remove => Events.RemoveHandler(EventValidated, value); } - /// + /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return Control.AccessibilityObject; } /// /// Cleans up and destroys the hosted control. /// - protected override void Dispose(bool disposing) { + protected override void Dispose(bool disposing) + { // Call base first so other things stop trying to talk to the control. This will // unparent the host item which will cause a SyncControlParent, so the control // will be correctly unparented before being disposed. - base.Dispose (disposing); - - if (disposing && Control != null) { + base.Dispose(disposing); + + if (disposing && Control != null) + { OnUnsubscribeControlEvents(Control); - + // we only call control.Dispose if we are NOT being disposed in the finalizer. Control.Dispose(); control = null; @@ -530,214 +630,267 @@ protected override void Dispose(bool disposing) { } [EditorBrowsable(EditorBrowsableState.Advanced)] - public void Focus() + public void Focus() { - Control.Focus(); + Control.Focus(); } - - public override Size GetPreferredSize(Size constrainingSize) { - if (control != null) { + + public override Size GetPreferredSize(Size constrainingSize) + { + if (control != null) + { return Control.GetPreferredSize(constrainingSize - Padding.Size) + Padding.Size; } return base.GetPreferredSize(constrainingSize); } - + /// /// Handle* wrappers: /// We sync the event from the hosted control and call resurface it on ToolStripItem. /// - private void HandleClick(object sender, System.EventArgs e) { + private void HandleClick(object sender, System.EventArgs e) + { OnClick(e); - } - private void HandleBackColorChanged(object sender, System.EventArgs e) { + } + private void HandleBackColorChanged(object sender, System.EventArgs e) + { OnBackColorChanged(e); - } - private void HandleDoubleClick(object sender, System.EventArgs e) { + } + private void HandleDoubleClick(object sender, System.EventArgs e) + { OnDoubleClick(e); - } - private void HandleDragDrop(object sender, DragEventArgs e) { + } + private void HandleDragDrop(object sender, DragEventArgs e) + { OnDragDrop(e); } - private void HandleDragEnter(object sender, DragEventArgs e) { + private void HandleDragEnter(object sender, DragEventArgs e) + { OnDragEnter(e); } - private void HandleDragLeave(object sender, EventArgs e) { + private void HandleDragLeave(object sender, EventArgs e) + { OnDragLeave(e); } - private void HandleDragOver(object sender, DragEventArgs e) { + private void HandleDragOver(object sender, DragEventArgs e) + { OnDragOver(e); } - private void HandleEnter(object sender, System.EventArgs e) { + private void HandleEnter(object sender, System.EventArgs e) + { OnEnter(e); - } - private void HandleEnabledChanged(object sender, System.EventArgs e) { + } + private void HandleEnabledChanged(object sender, System.EventArgs e) + { OnEnabledChanged(e); } - private void HandleForeColorChanged(object sender, System.EventArgs e) { + private void HandleForeColorChanged(object sender, System.EventArgs e) + { OnForeColorChanged(e); - } - private void HandleGiveFeedback(object sender, GiveFeedbackEventArgs e) { + } + private void HandleGiveFeedback(object sender, GiveFeedbackEventArgs e) + { OnGiveFeedback(e); } - private void HandleGotFocus(object sender, EventArgs e) { + private void HandleGotFocus(object sender, EventArgs e) + { OnGotFocus(e); } - private void HandleLocationChanged(object sender, EventArgs e) { - OnLocationChanged(e); + private void HandleLocationChanged(object sender, EventArgs e) + { + OnLocationChanged(e); } - private void HandleLostFocus(object sender, EventArgs e) { - OnLostFocus(e); + private void HandleLostFocus(object sender, EventArgs e) + { + OnLostFocus(e); } - private void HandleKeyDown(object sender, KeyEventArgs e) { + private void HandleKeyDown(object sender, KeyEventArgs e) + { OnKeyDown(e); } - private void HandleKeyPress(object sender, KeyPressEventArgs e) { + private void HandleKeyPress(object sender, KeyPressEventArgs e) + { OnKeyPress(e); } - private void HandleKeyUp(object sender, KeyEventArgs e) { + private void HandleKeyUp(object sender, KeyEventArgs e) + { OnKeyUp(e); } - private void HandleLeave(object sender, System.EventArgs e) { + private void HandleLeave(object sender, System.EventArgs e) + { OnLeave(e); - } - private void HandleMouseDown(object sender, MouseEventArgs e) { + } + private void HandleMouseDown(object sender, MouseEventArgs e) + { OnMouseDown(e); RaiseMouseEvent(ToolStripItem.EventMouseDown, e); } - private void HandleMouseEnter(object sender, EventArgs e) { - OnMouseEnter(e); + private void HandleMouseEnter(object sender, EventArgs e) + { + OnMouseEnter(e); RaiseEvent(ToolStripItem.EventMouseEnter, e); } - private void HandleMouseLeave(object sender, EventArgs e) { - OnMouseLeave(e); + private void HandleMouseLeave(object sender, EventArgs e) + { + OnMouseLeave(e); RaiseEvent(ToolStripItem.EventMouseLeave, e); } - private void HandleMouseHover(object sender, EventArgs e) { - OnMouseHover(e); + private void HandleMouseHover(object sender, EventArgs e) + { + OnMouseHover(e); RaiseEvent(ToolStripItem.EventMouseHover, e); } - private void HandleMouseMove(object sender, MouseEventArgs e) { + private void HandleMouseMove(object sender, MouseEventArgs e) + { OnMouseMove(e); RaiseMouseEvent(ToolStripItem.EventMouseMove, e); } - private void HandleMouseUp(object sender, MouseEventArgs e) { + private void HandleMouseUp(object sender, MouseEventArgs e) + { OnMouseUp(e); RaiseMouseEvent(ToolStripItem.EventMouseUp, e); } - private void HandlePaint(object sender, PaintEventArgs e) { + private void HandlePaint(object sender, PaintEventArgs e) + { OnPaint(e); RaisePaintEvent(ToolStripItem.EventPaint, e); } - private void HandleQueryAccessibilityHelp(object sender, QueryAccessibilityHelpEventArgs e) { + private void HandleQueryAccessibilityHelp(object sender, QueryAccessibilityHelpEventArgs e) + { QueryAccessibilityHelpEventHandler handler = (QueryAccessibilityHelpEventHandler)Events[ToolStripItem.EventQueryAccessibilityHelp]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } - private void HandleQueryContinueDrag(object sender, QueryContinueDragEventArgs e) { + private void HandleQueryContinueDrag(object sender, QueryContinueDragEventArgs e) + { OnQueryContinueDrag(e); } - private void HandleRightToLeftChanged(object sender, EventArgs e) { + private void HandleRightToLeftChanged(object sender, EventArgs e) + { OnRightToLeftChanged(e); } - private void HandleResize(object sender, EventArgs e) { - if (suspendSyncSizeCount == 0) { - OnHostedControlResize(e); + private void HandleResize(object sender, EventArgs e) + { + if (suspendSyncSizeCount == 0) + { + OnHostedControlResize(e); } } - - private void HandleTextChanged(object sender, EventArgs e) { + + private void HandleTextChanged(object sender, EventArgs e) + { OnTextChanged(e); } - private void HandleControlVisibleChanged(object sender, EventArgs e) { + private void HandleControlVisibleChanged(object sender, EventArgs e) + { // check the STATE_VISIBLE flag rather than using Control.Visible. // if we check while it's unparented it will return visible false. // the easiest way to do this is to use ParticipatesInLayout. bool controlVisibleStateFlag = ((IArrangedElement)Control).ParticipatesInLayout; bool itemVisibleStateFlag = ((IArrangedElement)(this)).ParticipatesInLayout; - - if (itemVisibleStateFlag != controlVisibleStateFlag) { + + if (itemVisibleStateFlag != controlVisibleStateFlag) + { this.Visible = Control.Visible; // this should fire the OnVisibleChanged and raise events appropriately. }; } - private void HandleValidating(object sender, CancelEventArgs e) { + private void HandleValidating(object sender, CancelEventArgs e) + { OnValidating(e); - } - - private void HandleValidated(object sender, System.EventArgs e) { + } + + private void HandleValidated(object sender, System.EventArgs e) + { OnValidated(e); - } + } - internal override void OnAccessibleDescriptionChanged(EventArgs e) { + internal override void OnAccessibleDescriptionChanged(EventArgs e) + { Control.AccessibleDescription = AccessibleDescription; } - internal override void OnAccessibleNameChanged(EventArgs e) { + internal override void OnAccessibleNameChanged(EventArgs e) + { Control.AccessibleName = AccessibleName; } - internal override void OnAccessibleDefaultActionDescriptionChanged(EventArgs e) { + internal override void OnAccessibleDefaultActionDescriptionChanged(EventArgs e) + { Control.AccessibleDefaultActionDescription = AccessibleDefaultActionDescription; } - internal override void OnAccessibleRoleChanged(EventArgs e) { + internal override void OnAccessibleRoleChanged(EventArgs e) + { Control.AccessibleRole = AccessibleRole; } - - protected virtual void OnEnter(EventArgs e) { + + protected virtual void OnEnter(EventArgs e) + { RaiseEvent(EventEnter, e); } - - + + /// /// called when the control has lost focus /// - protected virtual void OnGotFocus(EventArgs e) { - RaiseEvent(EventGotFocus, e); + protected virtual void OnGotFocus(EventArgs e) + { + RaiseEvent(EventGotFocus, e); } - protected virtual void OnLeave(EventArgs e) { + protected virtual void OnLeave(EventArgs e) + { RaiseEvent(EventLeave, e); } - + /// /// called when the control has lost focus /// - protected virtual void OnLostFocus(EventArgs e) { - RaiseEvent(EventLostFocus, e); - } - protected virtual void OnKeyDown(KeyEventArgs e) { - RaiseKeyEvent(EventKeyDown, e); - } - protected virtual void OnKeyPress(KeyPressEventArgs e) { - RaiseKeyPressEvent(EventKeyPress, e); - } - protected virtual void OnKeyUp(KeyEventArgs e) { - RaiseKeyEvent(EventKeyUp, e); - } + protected virtual void OnLostFocus(EventArgs e) + { + RaiseEvent(EventLostFocus, e); + } + protected virtual void OnKeyDown(KeyEventArgs e) + { + RaiseKeyEvent(EventKeyDown, e); + } + protected virtual void OnKeyPress(KeyPressEventArgs e) + { + RaiseKeyPressEvent(EventKeyPress, e); + } + protected virtual void OnKeyUp(KeyEventArgs e) + { + RaiseKeyEvent(EventKeyUp, e); + } /// /// Called when the items bounds are changed. Here, we update the Control's bounds. /// - protected override void OnBoundsChanged() { - if (control != null) { + protected override void OnBoundsChanged() + { + if (control != null) + { SuspendSizeSync(); IArrangedElement element = control as IArrangedElement; - if (element == null) { + if (element == null) + { Debug.Fail("why are we here? control should not be null"); return; } - + Size size = LayoutUtils.DeflateRect(this.Bounds, this.Padding).Size; Rectangle bounds = LayoutUtils.Align(size, this.Bounds, ControlAlign); - + // use BoundsSpecified.None so we dont deal w/specified bounds - this way we can tell what someone has set the size to. element.SetBounds(bounds, BoundsSpecified.None); // sometimes a control can ignore the size passed in, use the adjustment // to re-align. - if (bounds != control.Bounds) { + if (bounds != control.Bounds) + { bounds = LayoutUtils.Align(control.Size, this.Bounds, ControlAlign); - element.SetBounds(bounds, BoundsSpecified.None); + element.SetBounds(bounds, BoundsSpecified.None); } ResumeSizeSync(); } @@ -746,32 +899,38 @@ protected override void OnBoundsChanged() { /// /// Called when the control fires its Paint event. /// - protected override void OnPaint(PaintEventArgs e) { + protected override void OnPaint(PaintEventArgs e) + { // do nothing.... } - - protected internal override void OnLayout(LayoutEventArgs e) { + + protected internal override void OnLayout(LayoutEventArgs e) + { // do nothing... called via the controls collection } - + /// /// Called when the item's parent has been changed. /// - protected override void OnParentChanged(ToolStrip oldParent, ToolStrip newParent) { - if (oldParent != null && Owner == null && newParent == null && Control != null) { + protected override void OnParentChanged(ToolStrip oldParent, ToolStrip newParent) + { + if (oldParent != null && Owner == null && newParent == null && Control != null) + { // if we've really been removed from the item collection, // politely remove ourselves from the control collection - WindowsFormsUtils.ReadOnlyControlCollection oldControlCollection + WindowsFormsUtils.ReadOnlyControlCollection oldControlCollection = GetControlCollection(Control.ParentInternal as ToolStrip); - if (oldControlCollection != null) { - oldControlCollection.RemoveInternal(Control); + if (oldControlCollection != null) + { + oldControlCollection.RemoveInternal(Control); } } - else { - SyncControlParent(); + else + { + SyncControlParent(); } - + base.OnParentChanged(oldParent, newParent); } @@ -783,209 +942,239 @@ WindowsFormsUtils.ReadOnlyControlCollection oldControlCollection /// Override to add/prevent syncing of control events. /// NOTE: if you override and hook up events here, you should unhook in OnUnsubscribeControlEvents. /// - protected virtual void OnSubscribeControlEvents(Control control) { + protected virtual void OnSubscribeControlEvents(Control control) + { - if (control != null) { + if (control != null) + { // Please keep this alphabetized and in sync with Unsubscribe // - control.Click += new EventHandler(HandleClick); - control.BackColorChanged += new EventHandler(HandleBackColorChanged); - control.DoubleClick += new EventHandler(HandleDoubleClick); - control.DragDrop += new DragEventHandler(HandleDragDrop); - control.DragEnter += new DragEventHandler(HandleDragEnter); - control.DragLeave += new EventHandler(HandleDragLeave); - control.DragOver += new DragEventHandler(HandleDragOver); - control.Enter += new EventHandler(HandleEnter); - control.EnabledChanged += new EventHandler(HandleEnabledChanged); - control.ForeColorChanged += new EventHandler(HandleForeColorChanged); - control.GiveFeedback += new GiveFeedbackEventHandler(HandleGiveFeedback); - control.GotFocus += new EventHandler(HandleGotFocus); - control.Leave += new EventHandler(HandleLeave); - control.LocationChanged += new EventHandler(HandleLocationChanged); - control.LostFocus += new EventHandler(HandleLostFocus); - control.KeyDown += new KeyEventHandler(HandleKeyDown); - control.KeyPress += new KeyPressEventHandler(HandleKeyPress); - control.KeyUp += new KeyEventHandler(HandleKeyUp); - control.MouseDown += new MouseEventHandler(HandleMouseDown); - control.MouseEnter += new EventHandler(HandleMouseEnter); - control.MouseHover += new EventHandler(HandleMouseHover); - control.MouseLeave += new EventHandler(HandleMouseLeave); - control.MouseMove += new MouseEventHandler(HandleMouseMove); - control.MouseUp += new MouseEventHandler(HandleMouseUp); - control.Paint += new PaintEventHandler(HandlePaint); - control.QueryAccessibilityHelp += new QueryAccessibilityHelpEventHandler(HandleQueryAccessibilityHelp); - control.QueryContinueDrag += new QueryContinueDragEventHandler(HandleQueryContinueDrag); - control.Resize += new EventHandler(HandleResize); - control.RightToLeftChanged += new EventHandler(HandleRightToLeftChanged); - control.TextChanged += new EventHandler(HandleTextChanged); - control.VisibleChanged += new EventHandler(HandleControlVisibleChanged); - control.Validating += new CancelEventHandler(HandleValidating); - control.Validated += new EventHandler(HandleValidated); - - } - - } - + control.Click += new EventHandler(HandleClick); + control.BackColorChanged += new EventHandler(HandleBackColorChanged); + control.DoubleClick += new EventHandler(HandleDoubleClick); + control.DragDrop += new DragEventHandler(HandleDragDrop); + control.DragEnter += new DragEventHandler(HandleDragEnter); + control.DragLeave += new EventHandler(HandleDragLeave); + control.DragOver += new DragEventHandler(HandleDragOver); + control.Enter += new EventHandler(HandleEnter); + control.EnabledChanged += new EventHandler(HandleEnabledChanged); + control.ForeColorChanged += new EventHandler(HandleForeColorChanged); + control.GiveFeedback += new GiveFeedbackEventHandler(HandleGiveFeedback); + control.GotFocus += new EventHandler(HandleGotFocus); + control.Leave += new EventHandler(HandleLeave); + control.LocationChanged += new EventHandler(HandleLocationChanged); + control.LostFocus += new EventHandler(HandleLostFocus); + control.KeyDown += new KeyEventHandler(HandleKeyDown); + control.KeyPress += new KeyPressEventHandler(HandleKeyPress); + control.KeyUp += new KeyEventHandler(HandleKeyUp); + control.MouseDown += new MouseEventHandler(HandleMouseDown); + control.MouseEnter += new EventHandler(HandleMouseEnter); + control.MouseHover += new EventHandler(HandleMouseHover); + control.MouseLeave += new EventHandler(HandleMouseLeave); + control.MouseMove += new MouseEventHandler(HandleMouseMove); + control.MouseUp += new MouseEventHandler(HandleMouseUp); + control.Paint += new PaintEventHandler(HandlePaint); + control.QueryAccessibilityHelp += new QueryAccessibilityHelpEventHandler(HandleQueryAccessibilityHelp); + control.QueryContinueDrag += new QueryContinueDragEventHandler(HandleQueryContinueDrag); + control.Resize += new EventHandler(HandleResize); + control.RightToLeftChanged += new EventHandler(HandleRightToLeftChanged); + control.TextChanged += new EventHandler(HandleTextChanged); + control.VisibleChanged += new EventHandler(HandleControlVisibleChanged); + control.Validating += new CancelEventHandler(HandleValidating); + control.Validated += new EventHandler(HandleValidated); + + } + + } + /// /// The events from the hosted control are unsubscribed here. /// Override to unhook events subscribed in OnSubscribeControlEvents. /// - protected virtual void OnUnsubscribeControlEvents(Control control) { - if (control != null) { + protected virtual void OnUnsubscribeControlEvents(Control control) + { + if (control != null) + { // Please keep this alphabetized and in sync with Subscribe // - control.Click -= new EventHandler(HandleClick); - control.BackColorChanged -= new EventHandler(HandleBackColorChanged); - control.DoubleClick -= new EventHandler(HandleDoubleClick); - control.DragDrop -= new DragEventHandler(HandleDragDrop); - control.DragEnter -= new DragEventHandler(HandleDragEnter); - control.DragLeave -= new EventHandler(HandleDragLeave); - control.DragOver -= new DragEventHandler(HandleDragOver); - control.Enter -= new EventHandler(HandleEnter); - control.EnabledChanged -= new EventHandler(HandleEnabledChanged); - control.ForeColorChanged -= new EventHandler(HandleForeColorChanged); - control.GiveFeedback -= new GiveFeedbackEventHandler(HandleGiveFeedback); - control.GotFocus -= new EventHandler(HandleGotFocus); - control.Leave -= new EventHandler(HandleLeave); - control.LocationChanged -= new EventHandler(HandleLocationChanged); - control.LostFocus -= new EventHandler(HandleLostFocus); - control.KeyDown -= new KeyEventHandler(HandleKeyDown); - control.KeyPress -= new KeyPressEventHandler(HandleKeyPress); - control.KeyUp -= new KeyEventHandler(HandleKeyUp); - control.MouseDown -= new MouseEventHandler(HandleMouseDown); - control.MouseEnter -= new EventHandler(HandleMouseEnter); - control.MouseHover -= new EventHandler(HandleMouseHover); - control.MouseLeave -= new EventHandler(HandleMouseLeave); - control.MouseMove -= new MouseEventHandler(HandleMouseMove); - control.MouseUp -= new MouseEventHandler(HandleMouseUp); - control.Paint -= new PaintEventHandler(HandlePaint); - control.QueryAccessibilityHelp -= new QueryAccessibilityHelpEventHandler(HandleQueryAccessibilityHelp); - control.QueryContinueDrag -= new QueryContinueDragEventHandler(HandleQueryContinueDrag); - control.Resize -= new EventHandler(HandleResize); - control.RightToLeftChanged -= new EventHandler(HandleRightToLeftChanged); - control.TextChanged -= new EventHandler(HandleTextChanged); - control.VisibleChanged -= new EventHandler(HandleControlVisibleChanged); - control.Validating -= new CancelEventHandler(HandleValidating); - control.Validated -= new EventHandler(HandleValidated); - - } - - } - - protected virtual void OnValidating(CancelEventArgs e) { + control.Click -= new EventHandler(HandleClick); + control.BackColorChanged -= new EventHandler(HandleBackColorChanged); + control.DoubleClick -= new EventHandler(HandleDoubleClick); + control.DragDrop -= new DragEventHandler(HandleDragDrop); + control.DragEnter -= new DragEventHandler(HandleDragEnter); + control.DragLeave -= new EventHandler(HandleDragLeave); + control.DragOver -= new DragEventHandler(HandleDragOver); + control.Enter -= new EventHandler(HandleEnter); + control.EnabledChanged -= new EventHandler(HandleEnabledChanged); + control.ForeColorChanged -= new EventHandler(HandleForeColorChanged); + control.GiveFeedback -= new GiveFeedbackEventHandler(HandleGiveFeedback); + control.GotFocus -= new EventHandler(HandleGotFocus); + control.Leave -= new EventHandler(HandleLeave); + control.LocationChanged -= new EventHandler(HandleLocationChanged); + control.LostFocus -= new EventHandler(HandleLostFocus); + control.KeyDown -= new KeyEventHandler(HandleKeyDown); + control.KeyPress -= new KeyPressEventHandler(HandleKeyPress); + control.KeyUp -= new KeyEventHandler(HandleKeyUp); + control.MouseDown -= new MouseEventHandler(HandleMouseDown); + control.MouseEnter -= new EventHandler(HandleMouseEnter); + control.MouseHover -= new EventHandler(HandleMouseHover); + control.MouseLeave -= new EventHandler(HandleMouseLeave); + control.MouseMove -= new MouseEventHandler(HandleMouseMove); + control.MouseUp -= new MouseEventHandler(HandleMouseUp); + control.Paint -= new PaintEventHandler(HandlePaint); + control.QueryAccessibilityHelp -= new QueryAccessibilityHelpEventHandler(HandleQueryAccessibilityHelp); + control.QueryContinueDrag -= new QueryContinueDragEventHandler(HandleQueryContinueDrag); + control.Resize -= new EventHandler(HandleResize); + control.RightToLeftChanged -= new EventHandler(HandleRightToLeftChanged); + control.TextChanged -= new EventHandler(HandleTextChanged); + control.VisibleChanged -= new EventHandler(HandleControlVisibleChanged); + control.Validating -= new CancelEventHandler(HandleValidating); + control.Validated -= new EventHandler(HandleValidated); + + } + + } + + protected virtual void OnValidating(CancelEventArgs e) + { RaiseCancelEvent(EventValidating, e); } - protected virtual void OnValidated(EventArgs e) { + protected virtual void OnValidated(EventArgs e) + { RaiseEvent(EventValidated, e); } - private static WindowsFormsUtils.ReadOnlyControlCollection GetControlCollection(ToolStrip toolStrip) { - WindowsFormsUtils.ReadOnlyControlCollection newControls = - toolStrip != null ? (WindowsFormsUtils.ReadOnlyControlCollection) toolStrip.Controls : null; - return newControls; + private static WindowsFormsUtils.ReadOnlyControlCollection GetControlCollection(ToolStrip toolStrip) + { + WindowsFormsUtils.ReadOnlyControlCollection newControls = + toolStrip != null ? (WindowsFormsUtils.ReadOnlyControlCollection)toolStrip.Controls : null; + return newControls; } // Ensures the hosted Control is parented to the ToolStrip hosting this ToolStripItem. - private void SyncControlParent() { - WindowsFormsUtils.ReadOnlyControlCollection newControls = GetControlCollection(ParentInternal); - if (newControls != null) { + private void SyncControlParent() + { + WindowsFormsUtils.ReadOnlyControlCollection newControls = GetControlCollection(ParentInternal); + if (newControls != null) + { newControls.AddInternal(Control); } } - protected virtual void OnHostedControlResize(EventArgs e) { + protected virtual void OnHostedControlResize(EventArgs e) + { // support for syncing the wrapper when the control size has changed this.Size = Control.Size; } - + protected internal override bool ProcessCmdKey(ref Message m, Keys keyData) => false; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] // 'charCode' matches control.cs - protected internal override bool ProcessMnemonic(char charCode) { - if (control != null) { - return control.ProcessMnemonic( charCode ); + protected internal override bool ProcessMnemonic(char charCode) + { + if (control != null) + { + return control.ProcessMnemonic(charCode); } - return base.ProcessMnemonic( charCode ); + return base.ProcessMnemonic(charCode); } protected internal override bool ProcessDialogKey(Keys keyData) => false; - protected override void SetVisibleCore(bool visible) { + protected override void SetVisibleCore(bool visible) + { // This is needed, because if you try and set set visible to true before the parent is visible, // we will get called back into here, and set it back to false, since the parent is not visible. - if (inSetVisibleCore) { + if (inSetVisibleCore) + { return; } inSetVisibleCore = true; Control.SuspendLayout(); - try { + try + { Control.Visible = visible; } - finally { + finally + { Control.ResumeLayout(false); // this will go ahead and perform layout. base.SetVisibleCore(visible); inSetVisibleCore = false; } - + } [EditorBrowsable(EditorBrowsableState.Never)] - public override void ResetBackColor() { + public override void ResetBackColor() + { Control.ResetBackColor(); } [EditorBrowsable(EditorBrowsableState.Never)] - public override void ResetForeColor() { + public override void ResetForeColor() + { Control.ResetForeColor(); } - private void SuspendSizeSync() { + private void SuspendSizeSync() + { this.suspendSyncSizeCount++; } - - private void ResumeSizeSync() { + + private void ResumeSizeSync() + { this.suspendSyncSizeCount--; } - internal override bool ShouldSerializeBackColor() { - if (control != null) { + internal override bool ShouldSerializeBackColor() + { + if (control != null) + { return control.ShouldSerializeBackColor(); } - return base.ShouldSerializeBackColor(); + return base.ShouldSerializeBackColor(); } - internal override bool ShouldSerializeForeColor() { - if (control != null) { + internal override bool ShouldSerializeForeColor() + { + if (control != null) + { return control.ShouldSerializeForeColor(); - } + } return base.ShouldSerializeForeColor(); } - internal override bool ShouldSerializeFont() { - if (control != null) { + internal override bool ShouldSerializeFont() + { + if (control != null) + { return control.ShouldSerializeFont(); } return base.ShouldSerializeFont(); } - internal override bool ShouldSerializeRightToLeft() { - if (control != null) { + internal override bool ShouldSerializeRightToLeft() + { + if (control != null) + { return control.ShouldSerializeRightToLeft(); } - return base.ShouldSerializeRightToLeft(); + return base.ShouldSerializeRightToLeft(); } - internal override void OnKeyboardToolTipHook(ToolTip toolTip) { + internal override void OnKeyboardToolTipHook(ToolTip toolTip) + { base.OnKeyboardToolTipHook(toolTip); KeyboardToolTipStateMachine.Instance.Hook(this.Control, toolTip); } - internal override void OnKeyboardToolTipUnhook(ToolTip toolTip) { + internal override void OnKeyboardToolTipUnhook(ToolTip toolTip) + { base.OnKeyboardToolTipUnhook(toolTip); KeyboardToolTipStateMachine.Instance.Unhook(this.Control, toolTip); @@ -1002,7 +1191,7 @@ private class StubSite : ISite, IDictionaryService private Hashtable _dictionary = null; IComponent comp = null; IComponent owner = null; - + public StubSite(Component control, Component host) { comp = control as IComponent; @@ -1012,29 +1201,34 @@ public StubSite(Component control, Component host) /// /// When implemented by a class, gets the component associated with the . /// - IComponent ISite.Component { + IComponent ISite.Component + { get { return comp; } } - + // The container in which the component is sited. /// /// When implemented by a class, gets the container associated with the . /// - IContainer ISite.Container { - get { + IContainer ISite.Container + { + get + { return owner.Site.Container; } } - + // Indicates whether the component is in design mode. /// /// When implemented by a class, determines whether the component is in design mode. /// - bool ISite.DesignMode { - get { + bool ISite.DesignMode + { + get + { return owner.Site.DesignMode; } } @@ -1045,11 +1239,14 @@ bool ISite.DesignMode { /// When implemented by a class, gets or sets the name of /// the component associated with the . /// - string ISite.Name { - get { + string ISite.Name + { + get + { return owner.Site.Name; } - set { + set + { owner.Site.Name = value; } } @@ -1057,19 +1254,23 @@ string ISite.Name { /// /// Returns the requested service. /// - object IServiceProvider.GetService(Type service) { - if (service == null) { + object IServiceProvider.GetService(Type service) + { + if (service == null) + { throw new ArgumentNullException(nameof(service)); } // We have to implement our own dictionary service. If we don't, // the properties of the underlying component will end up being // overwritten by our own properties when GetProperties is called - if (service == typeof(IDictionaryService)) { + if (service == typeof(IDictionaryService)) + { return this; } - if (owner.Site != null) { + if (owner.Site != null) + { return owner.Site.GetService(service); } return null; @@ -1078,11 +1279,15 @@ object IServiceProvider.GetService(Type service) { /// /// Retrieves the key corresponding to the given value. /// - object IDictionaryService.GetKey(object value) { - if (_dictionary != null) { - foreach (DictionaryEntry de in _dictionary) { + object IDictionaryService.GetKey(object value) + { + if (_dictionary != null) + { + foreach (DictionaryEntry de in _dictionary) + { object o = de.Value; - if (value != null && value.Equals(o)) { + if (value != null && value.Equals(o)) + { return de.Key; } } @@ -1093,8 +1298,10 @@ object IDictionaryService.GetKey(object value) { /// /// Retrieves the value corresponding to the given key. /// - object IDictionaryService.GetValue(object key) { - if (_dictionary != null) { + object IDictionaryService.GetValue(object key) + { + if (_dictionary != null) + { return _dictionary[key]; } return null; @@ -1105,13 +1312,18 @@ object IDictionaryService.GetValue(object key) { /// pair is stored on a per-object basis, and is a handy place to save /// additional information about a component. /// - void IDictionaryService.SetValue(object key, object value) { - if (_dictionary == null) { + void IDictionaryService.SetValue(object key, object value) + { + if (_dictionary == null) + { _dictionary = new Hashtable(); } - if (value == null) { + if (value == null) + { _dictionary.Remove(key); - } else { + } + else + { _dictionary[key] = value; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs index e28c2e4409c..10b768918d6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Collections; using System.ComponentModel; @@ -17,57 +18,58 @@ namespace System.Windows.Forms { using System.Globalization; - + /// /// Summary of ToolStripDropDown. /// [Designer("System.Windows.Forms.Design.ToolStripDropDownDesigner, " + AssemblyRef.SystemDesign)] [ComVisible(true)] [ClassInterface(ClassInterfaceType.AutoDispatch)] - public class ToolStripDropDown : ToolStrip { - - private ToolStripItem ownerItem = null; - private bool isAutoGenerated = false; - private Point dropDownLocation = Point.Empty; - private bool dropShadowEnabled = true; - private bool autoClose = true; - private bool autoSize = true; - private int countDropDownItemsAssignedTo = 0; // the number of dropdown items using this as their dropdown.. - private BitVector32 state = new BitVector32(); - private Point displayLocation = new Point(0,0); - private bool saveSourceControl = false; + public class ToolStripDropDown : ToolStrip + { + + private ToolStripItem ownerItem = null; + private bool isAutoGenerated = false; + private Point dropDownLocation = Point.Empty; + private bool dropShadowEnabled = true; + private bool autoClose = true; + private bool autoSize = true; + private int countDropDownItemsAssignedTo = 0; // the number of dropdown items using this as their dropdown.. + private BitVector32 state = new BitVector32(); + private Point displayLocation = new Point(0, 0); + private bool saveSourceControl = false; private ToolStripDropDownDirection childDropDownDirection = ToolStripDropDownDirection.Default; private ToolStripDropDownCloseReason closeReason = ToolStripDropDownCloseReason.AppFocusChange; - - private static readonly int PropOpacity = PropertyStore.CreateKey(); - private static readonly int PropDDRightToLeft = PropertyStore.CreateKey(); - private static readonly int PropSourceControl = PropertyStore.CreateKey(); - private static readonly object EventOpening = new object(); - private static readonly object EventOpened = new object(); - private static readonly object EventClosed = new object(); - private static readonly object EventClosing = new object(); + private static readonly int PropOpacity = PropertyStore.CreateKey(); + private static readonly int PropDDRightToLeft = PropertyStore.CreateKey(); + private static readonly int PropSourceControl = PropertyStore.CreateKey(); + + private static readonly object EventOpening = new object(); + private static readonly object EventOpened = new object(); + private static readonly object EventClosed = new object(); + private static readonly object EventClosing = new object(); - private static readonly object ToolStripParkingWindowKey = new object(); + private static readonly object ToolStripParkingWindowKey = new object(); - private static readonly Padding defaultPadding = new Padding(1, 2, 1, 2); - private Padding scaledDefaultPadding = defaultPadding; + private static readonly Padding defaultPadding = new Padding(1, 2, 1, 2); + private Padding scaledDefaultPadding = defaultPadding; -#if DEBUG - internal static TraceSwitch DropDownActivateDebug = new TraceSwitch("DropDownActivateDebug", "Debug activation code for dropDown controls"); +#if DEBUG + internal static TraceSwitch DropDownActivateDebug = new TraceSwitch("DropDownActivateDebug", "Debug activation code for dropDown controls"); internal static TraceSwitch DropDownDebugBounds = new TraceSwitch("DropDownDebugBounds", "Debug GetDropDownBounds"); static readonly BooleanSwitch AlwaysRestrictWindows = new BooleanSwitch("AlwaysRestrictWindows", "Always make Form classes behave as though they are restricted"); #else internal static TraceSwitch DropDownActivateDebug; internal static TraceSwitch DropDownDebugBounds; #endif - - private static readonly int stateLayered = BitVector32.CreateMask(); - private static readonly int stateAllowTransparency = BitVector32.CreateMask(stateLayered); - private static readonly int stateNotWorkingAreaConstrained = BitVector32.CreateMask(stateAllowTransparency); - private static readonly int stateInSetVisibleCore = BitVector32.CreateMask(stateNotWorkingAreaConstrained); + + private static readonly int stateLayered = BitVector32.CreateMask(); + private static readonly int stateAllowTransparency = BitVector32.CreateMask(stateLayered); + private static readonly int stateNotWorkingAreaConstrained = BitVector32.CreateMask(stateAllowTransparency); + private static readonly int stateInSetVisibleCore = BitVector32.CreateMask(stateNotWorkingAreaConstrained); public ToolStripDropDown() { @@ -81,25 +83,29 @@ public ToolStripDropDown() ResumeLayout(false); } - internal ToolStripDropDown(ToolStripItem ownerItem): this() + internal ToolStripDropDown(ToolStripItem ownerItem) : this() { this.ownerItem = ownerItem; } - internal ToolStripDropDown(ToolStripItem ownerItem, bool isAutoGenerated) : this(ownerItem) { + internal ToolStripDropDown(ToolStripItem ownerItem, bool isAutoGenerated) : this(ownerItem) + { this.isAutoGenerated = isAutoGenerated; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new bool AllowItemReorder { - get { + public new bool AllowItemReorder + { + get + { return base.AllowItemReorder; } - set { + set + { base.AllowItemReorder = value; } } - + /// /// /// Gets or sets @@ -111,54 +117,67 @@ internal ToolStripDropDown(ToolStripItem ownerItem, bool isAutoGenerated) : this DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlAllowTransparencyDescr)) ] - public bool AllowTransparency { - get { + public bool AllowTransparency + { + get + { return state[stateAllowTransparency]; } - set { - if (value != (state[stateAllowTransparency]) && - OSFeature.Feature.IsPresent(OSFeature.LayeredWindows)) { + set + { + if (value != (state[stateAllowTransparency]) && + OSFeature.Feature.IsPresent(OSFeature.LayeredWindows)) + { state[stateAllowTransparency] = value; state[stateLayered] = state[stateAllowTransparency]; UpdateStyles(); - if (!value) { - if (Properties.ContainsObject(PropOpacity)) { + if (!value) + { + if (Properties.ContainsObject(PropOpacity)) + { Properties.SetObject(PropOpacity, (object)1.0f); } - UpdateLayered(); + UpdateLayered(); } } } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override AnchorStyles Anchor { - get { + public override AnchorStyles Anchor + { + get + { return base.Anchor; } - set { + set + { base.Anchor = value; } } - + [DefaultValue(true)] - public override bool AutoSize { - get { - return autoSize; + public override bool AutoSize + { + get + { + return autoSize; } - set { - if (autoSize != value) { + set + { + if (autoSize != value) + { autoSize = value; // we shadow CommonProperties - LayoutTransaction.DoLayout(this,this,PropertyNames.AutoSize); + LayoutTransaction.DoLayout(this, this, PropertyNames.AutoSize); OnAutoSizeChanged(EventArgs.Empty); } } } - + /// /// specifies whether the dropdown should automatically close when the dropdown has lost /// activation. If you want a dropdown that always stays open, specify AutoClose = false; @@ -168,13 +187,17 @@ public override bool AutoSize { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ToolStripDropDownAutoCloseDescr)) ] - public bool AutoClose { - get { + public bool AutoClose + { + get + { return autoClose; } - set { + set + { // - if (autoClose != value) { + if (autoClose != value) + { autoClose = value; ApplyTopMost(/*topMost=*/!autoClose); } @@ -183,43 +206,52 @@ public bool AutoClose { [Browsable(false)] - public new event EventHandler BackgroundImageChanged { + public new event EventHandler BackgroundImageChanged + { add => base.BackgroundImageChanged += value; remove => base.BackgroundImageChanged -= value; } [Browsable(false)] - public new event EventHandler BackgroundImageLayoutChanged { + public new event EventHandler BackgroundImageLayoutChanged + { add => base.BackgroundImageLayoutChanged += value; remove => base.BackgroundImageLayoutChanged -= value; } [Browsable(false)] - public new event EventHandler BindingContextChanged { + public new event EventHandler BindingContextChanged + { add => base.BindingContextChanged += value; remove => base.BindingContextChanged -= value; } - [DefaultValue(false), - Browsable(false), + [DefaultValue(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new bool CanOverflow { - get { - return base.CanOverflow; + public new bool CanOverflow + { + get + { + return base.CanOverflow; } - set { + set + { base.CanOverflow = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Always)] - new public event UICuesEventHandler ChangeUICues { - add => base.ChangeUICues += value; - remove => base.ChangeUICues -= value; } + new public event UICuesEventHandler ChangeUICues + { + add => base.ChangeUICues += value; + remove => base.ChangeUICues -= value; + } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] - public new ContextMenu ContextMenu { + public new ContextMenu ContextMenu + { get { return base.ContextMenu; } set { base.ContextMenu = value; } } @@ -227,14 +259,17 @@ public bool AutoClose { [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler ContextMenuChanged { - add => base.ContextMenuChanged += value; - remove => base.ContextMenuChanged -= value; } + public new event EventHandler ContextMenuChanged + { + add => base.ContextMenuChanged += value; + remove => base.ContextMenuChanged -= value; + } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] - public new ContextMenuStrip ContextMenuStrip { + public new ContextMenuStrip ContextMenuStrip + { get { return base.ContextMenuStrip; } set { base.ContextMenuStrip = value; } } @@ -242,10 +277,12 @@ public bool AutoClose { [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Always)] - public new event EventHandler ContextMenuStripChanged { - add => base.ContextMenuStripChanged += value; - remove => base.ContextMenuStripChanged -= value; } - + public new event EventHandler ContextMenuStripChanged + { + add => base.ContextMenuStripChanged += value; + remove => base.ContextMenuStripChanged -= value; + } + /// /// /// This is called when creating a window. Inheriting classes can overide @@ -254,17 +291,20 @@ public bool AutoClose { /// correctly. /// /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; // If we're using themes then go ahead - if (DropShadowEnabled) { + if (DropShadowEnabled) + { cp.ClassStyle |= NativeMethods.CS_DROPSHADOW; } // we're a borderless menuless control with no min/max boxes // we dont want to show in the taskbar either - + //HOWTO: Prevent a Window from Appearing on the Taskbar //Give the window the WS_EX_TOOLWINDOW extended style, and remove the WS_EX_APPWINDOW style. As a side effect, the window will have a smaller caption than a normal window. //Give the window the WS_POPUP style and make it owned by a hidden window. (Form) @@ -276,12 +316,14 @@ protected override CreateParams CreateParams { cp.ExStyle |= (NativeMethods.WS_EX_CONTROLPARENT); /* show in taskbar = false */ bool topLevel = TopLevel; - + // opacity - if (topLevel && (state[stateLayered])) { + if (topLevel && (state[stateLayered])) + { cp.ExStyle |= NativeMethods.WS_EX_LAYERED; } - else if (topLevel) { + else if (topLevel) + { //From MSDN: Menus, dialog boxes, and combo list boxes have the CS_SAVEBITS style. When you use this style for a window, //Windows saves a bitmap copy of the screen image that the window obscures. First, Windows asks the display driver to save the bits. //If the display driver has enough memory, it saves the bits for Windows. If the display driver does not have enough memory, Window @@ -289,10 +331,11 @@ protected override CreateParams CreateParams { //When the application removes the window, Windows can restore the screen image quickly by using the stored bits. cp.ClassStyle |= NativeMethods.CS_SAVEBITS; } - else if (!topLevel) { + else if (!topLevel) + { cp.Style |= NativeMethods.WS_CLIPSIBLINGS; } - + // We're turning off CLIPSIBLINGS because in the designer the elements of the form beneath // are actually sibling controls. We want to paint right over them as if we were a toplevel window. @@ -300,67 +343,83 @@ protected override CreateParams CreateParams { } } - protected override Padding DefaultPadding { + protected override Padding DefaultPadding + { get { return scaledDefaultPadding; } } /// We want this to default to true... This way tooltips on overflows and custom dropdowns will show. /// Since menu items don't show tooltips by default we can savely leave it on - protected override bool DefaultShowItemToolTips { - get { - return true; - } - } - - protected override DockStyle DefaultDock { - get { - return DockStyle.None; - } - } - - public override ToolStripDropDownDirection DefaultDropDownDirection { - get { - if (childDropDownDirection == ToolStripDropDownDirection.Default) { - return (RightToLeft == RightToLeft.Yes)? ToolStripDropDownDirection.Left : ToolStripDropDownDirection.Right; - } - return childDropDownDirection; - } - set { - childDropDownDirection = value; - base.DefaultDropDownDirection = value; - } - } - + protected override bool DefaultShowItemToolTips + { + get + { + return true; + } + } + + protected override DockStyle DefaultDock + { + get + { + return DockStyle.None; + } + } + + public override ToolStripDropDownDirection DefaultDropDownDirection + { + get + { + if (childDropDownDirection == ToolStripDropDownDirection.Default) + { + return (RightToLeft == RightToLeft.Yes) ? ToolStripDropDownDirection.Left : ToolStripDropDownDirection.Right; + } + return childDropDownDirection; + } + set + { + childDropDownDirection = value; + base.DefaultDropDownDirection = value; + } + } + [ DefaultValue(DockStyle.None), - Browsable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Always)] - public override DockStyle Dock { - get { - return base.Dock; + public override DockStyle Dock + { + get + { + return base.Dock; } - set{ + set + { base.Dock = value; } } /// changed the browsable attribute [Browsable(false), EditorBrowsable(EditorBrowsableState.Always)] - public new event EventHandler DockChanged { + public new event EventHandler DockChanged + { add => base.DockChanged += value; remove => base.DockChanged -= value; } - + /// /// Returns an owner window that can be used to /// own a drop down. /// - internal override NativeWindow DropDownOwnerWindow { - get { + internal override NativeWindow DropDownOwnerWindow + { + get + { // Re-use the drop down owner from our parenting // tool strip if we can. - if (ownerItem != null && ownerItem.Owner != null) { + if (ownerItem != null && ownerItem.Owner != null) + { return ownerItem.Owner.DropDownOwnerWindow; } @@ -368,18 +427,23 @@ internal override NativeWindow DropDownOwnerWindow { } } - public bool DropShadowEnabled { - get { + public bool DropShadowEnabled + { + get + { // DropShadows are only supported on TopMost windows // due to the flakeyness of the way it's implemented in the OS. (Non toplevel // windows can have parts of the shadow disappear because another window can get // sandwiched between the SysShadow window and the dropdown.) return dropShadowEnabled && TopMost && DisplayInformation.IsDropShadowEnabled; } - set { - if (dropShadowEnabled != value) { + set + { + if (dropShadowEnabled != value) + { dropShadowEnabled = value; - if (IsHandleCreated && !DesignMode) { + if (IsHandleCreated && !DesignMode) + { RecreateHandle(); } } @@ -387,144 +451,186 @@ public bool DropShadowEnabled { } [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ToolStripDropDownClosedDecr))] - public event ToolStripDropDownClosedEventHandler Closed { - add => Events.AddHandler(EventClosed, value); + public event ToolStripDropDownClosedEventHandler Closed + { + add => Events.AddHandler(EventClosed, value); remove => Events.RemoveHandler(EventClosed, value); } [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ToolStripDropDownClosingDecr))] - public event ToolStripDropDownClosingEventHandler Closing { - add => Events.AddHandler(EventClosing, value); + public event ToolStripDropDownClosingEventHandler Closing + { + add => Events.AddHandler(EventClosing, value); remove => Events.RemoveHandler(EventClosing, value); } [Browsable(false), EditorBrowsable(EditorBrowsableState.Always)] - new public event EventHandler Enter { - add => base.Enter += value; - remove => base.Enter -= value; } + new public event EventHandler Enter + { + add => base.Enter += value; + remove => base.Enter -= value; + } - public override Font Font { - get { - if (this.IsFontSet()) { + public override Font Font + { + get + { + if (this.IsFontSet()) + { return base.Font; } // if the FONT isnt set, then return our owner item's font. - if (IsAutoGenerated && OwnerItem != null) { + if (IsAutoGenerated && OwnerItem != null) + { return OwnerItem.Font; } - + return base.Font; } - set { + set + { base.Font = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Always)] - new public event EventHandler FontChanged { - add => base.FontChanged += value; - remove => base.FontChanged -= value; } + new public event EventHandler FontChanged + { + add => base.FontChanged += value; + remove => base.FontChanged -= value; + } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler ForeColorChanged { - add => base.ForeColorChanged += value; - remove => base.ForeColorChanged -= value; } + new public event EventHandler ForeColorChanged + { + add => base.ForeColorChanged += value; + remove => base.ForeColorChanged -= value; + } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event GiveFeedbackEventHandler GiveFeedback { - add => base.GiveFeedback += value; - remove => base.GiveFeedback -= value; } + new public event GiveFeedbackEventHandler GiveFeedback + { + add => base.GiveFeedback += value; + remove => base.GiveFeedback -= value; + } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new ToolStripGripDisplayStyle GripDisplayStyle { - get { + public new ToolStripGripDisplayStyle GripDisplayStyle + { + get + { return base.GripDisplayStyle; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new Rectangle GripRectangle { - get { + public new Rectangle GripRectangle + { + get + { return base.GripRectangle; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public new Padding GripMargin{ - get { + public new Padding GripMargin + { + get + { return base.GripMargin; } - set { + set + { base.GripMargin = value; } } - - [DefaultValue(ToolStripGripStyle.Hidden), - Browsable(false), + + [DefaultValue(ToolStripGripStyle.Hidden), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new ToolStripGripStyle GripStyle { - get { - return base.GripStyle; - } - set { - base.GripStyle = value; - } + public new ToolStripGripStyle GripStyle + { + get + { + return base.GripStyle; + } + set + { + base.GripStyle = value; + } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Always)] [SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] //Everett - new public event HelpEventHandler HelpRequested { - add => base.HelpRequested += value; - remove => base.HelpRequested -= value; } + new public event HelpEventHandler HelpRequested + { + add => base.HelpRequested += value; + remove => base.HelpRequested -= value; + } [Browsable(false), EditorBrowsable(EditorBrowsableState.Always)] - public new event EventHandler ImeModeChanged { - add => base.ImeModeChanged += value; - remove => base.ImeModeChanged -= value; } + public new event EventHandler ImeModeChanged + { + add => base.ImeModeChanged += value; + remove => base.ImeModeChanged -= value; + } /// /// determines whether this dropdown was autogenerated. /// [Browsable(false)] - public bool IsAutoGenerated { - get { + public bool IsAutoGenerated + { + get + { return isAutoGenerated; } } - internal bool IsAssignedToDropDownItem { - get { + internal bool IsAssignedToDropDownItem + { + get + { return IsAutoGenerated || (countDropDownItemsAssignedTo > 0); } } - internal override Size ImageScalingSizeInternal { - get { - if (IsAutoGenerated && OwnerToolStrip != null) { + internal override Size ImageScalingSizeInternal + { + get + { + if (IsAutoGenerated && OwnerToolStrip != null) + { return OwnerToolStrip.ImageScalingSizeInternal; } return base.ImageScalingSizeInternal; } - set { - base.ImageScalingSizeInternal = value; + set + { + base.ImageScalingSizeInternal = value; } } - internal override bool KeyboardActive { - get { + internal override bool KeyboardActive + { + get + { // ripple up the chain until we get the topmost toolstrip (usually the main menu strip is the one we care about) - ToolStrip ownerToolStrip = OwnerToolStrip; - if (ownerToolStrip != null) { + ToolStrip ownerToolStrip = OwnerToolStrip; + if (ownerToolStrip != null) + { return ownerToolStrip.KeyboardActive; } return base.KeyboardActive; } - set { + set + { base.KeyboardActive = value; // ripple up the chain until we get the topmost toolstrip (usually the main menu strip is the one we care about) - ToolStrip ownerToolStrip = OwnerToolStrip; - if (ownerToolStrip != null) { + ToolStrip ownerToolStrip = OwnerToolStrip; + if (ownerToolStrip != null) + { ownerToolStrip.KeyboardActive = value; } @@ -533,24 +639,32 @@ internal override bool KeyboardActive { } [Browsable(false), EditorBrowsable(EditorBrowsableState.Always)] - new public event KeyEventHandler KeyDown { - add => base.KeyDown += value; - remove => base.KeyDown -= value; } + new public event KeyEventHandler KeyDown + { + add => base.KeyDown += value; + remove => base.KeyDown -= value; + } [Browsable(false), EditorBrowsable(EditorBrowsableState.Always)] - new public event KeyPressEventHandler KeyPress { - add => base.KeyPress += value; - remove => base.KeyPress -= value; } + new public event KeyPressEventHandler KeyPress + { + add => base.KeyPress += value; + remove => base.KeyPress -= value; + } [Browsable(false), EditorBrowsable(EditorBrowsableState.Always)] - new public event KeyEventHandler KeyUp { - add => base.KeyUp += value; - remove => base.KeyUp -= value; } + new public event KeyEventHandler KeyUp + { + add => base.KeyUp += value; + remove => base.KeyUp -= value; + } [Browsable(false), EditorBrowsable(EditorBrowsableState.Always)] - public new event EventHandler Leave { - add => base.Leave += value; - remove => base.Leave -= value; } + public new event EventHandler Leave + { + add => base.Leave += value; + remove => base.Leave -= value; + } /// /// Override Location to make it hidden from the user in the designer @@ -558,36 +672,43 @@ internal override bool KeyboardActive { [ EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) + Browsable(false) ] - public new Point Location { - get { + public new Point Location + { + get + { return base.Location; } - set { + set + { base.Location = value; } } [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ToolStripDropDownOpeningDescr))] - public event CancelEventHandler Opening { + public event CancelEventHandler Opening + { add => Events.AddHandler(EventOpening, value); remove => Events.RemoveHandler(EventOpening, value); } - + /// /// Occurs when the control is clicked. /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ToolStripDropDownOpenedDescr))] - public event EventHandler Opened { - add => Events.AddHandler(EventOpened, value); + public event EventHandler Opened + { + add => Events.AddHandler(EventOpened, value); remove => Events.RemoveHandler(EventOpened, value); } - protected internal override Size MaxItemSize { - get { - return Screen.GetWorkingArea(this.Bounds).Size - this.Padding.Size; + protected internal override Size MaxItemSize + { + get + { + return Screen.GetWorkingArea(this.Bounds).Size - this.Padding.Size; } } @@ -609,7 +730,7 @@ public double Opacity { return Convert.ToDouble(opacity, CultureInfo.InvariantCulture); } - + return 1.0f; } set @@ -640,66 +761,83 @@ public double Opacity { UpdateStyles(); } - + UpdateLayered(); } } - - private byte OpacityAsByte { - get { + + private byte OpacityAsByte + { + get + { return (byte)(Opacity * 255.0f); } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new ToolStripOverflowButton OverflowButton { - get { + public new ToolStripOverflowButton OverflowButton + { + get + { return base.OverflowButton; } } - + /// /// Summary of OwnerItem. /// [DefaultValue(null), Browsable(false)] - public ToolStripItem OwnerItem { + public ToolStripItem OwnerItem + { get { return ownerItem; } - set { - if (ownerItem != value) { + set + { + if (ownerItem != value) + { Font originalFont = this.Font; RightToLeft startRightToLeft = this.RightToLeft; ownerItem = value; // RESET ambient properties - if (!originalFont.Equals(Font)) { + if (!originalFont.Equals(Font)) + { OnOwnerItemFontChanged(EventArgs.Empty); } - if (ownerItem != null && RightToLeftInherited && startRightToLeft != this.RightToLeft) { - using (new LayoutTransaction(this,this,PropertyNames.RightToLeft)) { + if (ownerItem != null && RightToLeftInherited && startRightToLeft != this.RightToLeft) + { + using (new LayoutTransaction(this, this, PropertyNames.RightToLeft)) + { OnRightToLeftChanged(EventArgs.Empty); } } - } + } } } - internal ToolStripDropDownItem OwnerDropDownItem { + internal ToolStripDropDownItem OwnerDropDownItem + { get { return OwnerItem as ToolStripDropDownItem; } } - internal ToolStrip OwnerToolStrip { - get { - if (ownerItem != null) { + internal ToolStrip OwnerToolStrip + { + get + { + if (ownerItem != null) + { ToolStrip owner = ownerItem.ParentInternal; - if (owner != null) { + if (owner != null) + { return owner; } // might not actually be placed on the overflow, just check for sure. - if (ownerItem.Placement == ToolStripItemPlacement.Overflow && ownerItem.Owner != null) { + if (ownerItem.Placement == ToolStripItemPlacement.Overflow && ownerItem.Owner != null) + { return ownerItem.Owner.OverflowButton.DropDown; } - if (owner == null) { + if (owner == null) + { return ownerItem.Owner; } } @@ -711,140 +849,179 @@ internal ToolStrip OwnerToolStrip { /// Hide the Region Property /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Always)] - new public Region Region { - get { + new public Region Region + { + get + { return base.Region; } - set { + set + { base.Region = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Always)] - new public event EventHandler RegionChanged { - add => base.RegionChanged += value; - remove => base.RegionChanged -= value; } + new public event EventHandler RegionChanged + { + add => base.RegionChanged += value; + remove => base.RegionChanged -= value; + } + - - internal virtual bool RequiresScrollButtons { - get { - return false; + internal virtual bool RequiresScrollButtons + { + get + { + return false; } - set { + set + { Debug.Fail("You can't set this except on ToolStripDropDownMenu"); } } - [ - SRCategory(nameof(SR.CatAppearance)), - Localizable(true), - AmbientValue(RightToLeft.Inherit), - SRDescription(nameof(SR.ControlRightToLeftDescr)) - ] - public override RightToLeft RightToLeft { - get { + [ + SRCategory(nameof(SR.CatAppearance)), + Localizable(true), + AmbientValue(RightToLeft.Inherit), + SRDescription(nameof(SR.ControlRightToLeftDescr)) + ] + public override RightToLeft RightToLeft + { + get + { // our inheritance is from our owner item. - if (RightToLeftInherited) { - if (SourceControlInternal != null) { + if (RightToLeftInherited) + { + if (SourceControlInternal != null) + { return SourceControlInternal.RightToLeft; } - if (OwnerItem != null) { + if (OwnerItem != null) + { return OwnerItem.RightToLeft; } } return base.RightToLeft; - } - set { - base.RightToLeft = value; - } - } - - private bool RightToLeftInherited { - get { + } + set + { + base.RightToLeft = value; + } + } + + private bool RightToLeftInherited + { + get + { // fish out of control's property store whether or not RTL was set, if it's set to inherit. return !ShouldSerializeRightToLeft(); } - } - + } + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event ScrollEventHandler Scroll { - add => base.Scroll += value; - remove => base.Scroll -= value; } + new public event ScrollEventHandler Scroll + { + add => base.Scroll += value; + remove => base.Scroll -= value; + } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new bool Stretch { - get { + public new bool Stretch + { + get + { return base.Stretch; } - set { + set + { base.Stretch = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Always)] - new public event EventHandler StyleChanged { - add => base.StyleChanged += value; - remove => base.StyleChanged -= value; } + new public event EventHandler StyleChanged + { + add => base.StyleChanged += value; + remove => base.StyleChanged -= value; + } - internal Control SourceControlInternal { - get { + internal Control SourceControlInternal + { + get + { return Properties.GetObject(PropSourceControl) as Control; } - set{ + set + { Properties.SetObject(PropSourceControl, value); } - } - - internal override int ShowParams { - get { - return NativeMethods.SW_SHOWNOACTIVATE; - } - } + } + + internal override int ShowParams + { + get + { + return NativeMethods.SW_SHOWNOACTIVATE; + } + } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TabStopChanged { - add => base.TabStopChanged += value; - remove => base.TabStopChanged -= value; } + new public event EventHandler TabStopChanged + { + add => base.TabStopChanged += value; + remove => base.TabStopChanged -= value; + } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TextChanged { - add => base.TextChanged += value; - remove => base.TextChanged -= value; } - - [ - Browsable(false), - DefaultValue(ToolStripTextDirection.Horizontal), - SRDescription(nameof(SR.ToolStripTextDirectionDescr)), - SRCategory(nameof(SR.CatAppearance)) - ] - public override ToolStripTextDirection TextDirection { - get { - return base.TextDirection; - } - set { - base.TextDirection = value; - } - } - - - //Consistency: match casing of Form.TopMost, which shipped in Everett, even though it's wrong - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - protected virtual bool TopMost - { + new public event EventHandler TextChanged + { + add => base.TextChanged += value; + remove => base.TextChanged -= value; + } + + [ + Browsable(false), + DefaultValue(ToolStripTextDirection.Horizontal), + SRDescription(nameof(SR.ToolStripTextDirectionDescr)), + SRCategory(nameof(SR.CatAppearance)) + ] + public override ToolStripTextDirection TextDirection + { + get + { + return base.TextDirection; + } + set + { + base.TextDirection = value; + } + } + + + //Consistency: match casing of Form.TopMost, which shipped in Everett, even though it's wrong + [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] + protected virtual bool TopMost + { get { return true; } - } + } - [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool TopLevel { - get { + [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool TopLevel + { + get + { return GetTopLevel(); } - set { + set + { // - if (value != GetTopLevel()) { + if (value != GetTopLevel()) + { SetTopLevelInternal(value); SetTopLevelStyle(value); } @@ -852,47 +1029,55 @@ public bool TopLevel { } -// public Color TransparencyKey { -// This property intentionally not available for ToolStripDropDown -// it's not robust enough for our needs -// } - - /// Override base TabIndex property in order to avoid serialization - /// (since a dropdown shouldn't participate in the taborder...) - [ - EditorBrowsable(EditorBrowsableState.Never), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - Browsable(false) - ] - public new int TabIndex { - get { - return base.TabIndex; - } - set { - base.TabIndex = value; - } - } - - [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), - SRCategory(nameof(SR.CatPropertyChanged)), - SRDescription(nameof(SR.ControlOnTabIndexChangedDescr)) - ] - public new event EventHandler TabIndexChanged { - add => base.TabIndexChanged += value; - remove => base.TabIndexChanged -= value; - } + // public Color TransparencyKey { + // This property intentionally not available for ToolStripDropDown + // it's not robust enough for our needs + // } + + /// Override base TabIndex property in order to avoid serialization + /// (since a dropdown shouldn't participate in the taborder...) + [ + EditorBrowsable(EditorBrowsableState.Never), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), + Browsable(false) + ] + public new int TabIndex + { + get + { + return base.TabIndex; + } + set + { + base.TabIndex = value; + } + } + + [ + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), + SRCategory(nameof(SR.CatPropertyChanged)), + SRDescription(nameof(SR.ControlOnTabIndexChangedDescr)) + ] + public new event EventHandler TabIndexChanged + { + add => base.TabIndexChanged += value; + remove => base.TabIndexChanged -= value; + } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler Validated { - add => base.Validated += value; - remove => base.Validated -= value; } + new public event EventHandler Validated + { + add => base.Validated += value; + remove => base.Validated -= value; + } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event CancelEventHandler Validating { - add => base.Validating += value; - remove => base.Validating -= value; } + new public event CancelEventHandler Validating + { + add => base.Validating += value; + remove => base.Validating -= value; + } /// Override base Visible property in order to control serialization by setting default value [ @@ -903,11 +1088,14 @@ public bool TopLevel { Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new bool Visible { - get { + public new bool Visible + { + get + { return base.Visible; } - set { + set + { base.Visible = value; } } @@ -916,43 +1104,52 @@ public bool TopLevel { internal bool WorkingAreaConstrained { get => true; - set + set { bool notConstrained = !value; state[stateNotWorkingAreaConstrained] = !value; } } - internal void AssignToDropDownItem() { + internal void AssignToDropDownItem() + { countDropDownItemsAssignedTo++; } - internal void AdjustSize() { + internal void AdjustSize() + { Size size = GetSuggestedSize(); - if (size != this.Size) { + if (size != this.Size) + { this.Size = size; } } - private void ApplyTopMost(bool topMost) { - if (TopMost) { + private void ApplyTopMost(bool topMost) + { + if (TopMost) + { HandleRef topMostFlag = (topMost) ? NativeMethods.HWND_TOPMOST : NativeMethods.HWND_NOTOPMOST; SafeNativeMethods.SetWindowPos(new HandleRef(this, Handle), topMostFlag, 0, 0, 0, 0, NativeMethods.SWP_NOMOVE | NativeMethods.SWP_NOSIZE | NativeMethods.SWP_NOACTIVATE); } } - protected override void Dispose(bool disposing) { - if (disposing) { + protected override void Dispose(bool disposing) + { + if (disposing) + { SourceControlInternal = null; } base.Dispose(disposing); } - private void CancelAutoExpand() { + private void CancelAutoExpand() + { ToolStrip toplevelOwnerToolStrip = GetToplevelOwnerToolStrip(); - if (toplevelOwnerToolStrip != null) { + if (toplevelOwnerToolStrip != null) + { toplevelOwnerToolStrip.MenuAutoExpand = false; } } @@ -968,14 +1165,17 @@ internal override bool CanProcessMnemonic() return base.CanProcessMnemonic(); } - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new ToolStripDropDownAccessibleObject(this); } - protected override LayoutSettings CreateLayoutSettings(ToolStripLayoutStyle style) { + protected override LayoutSettings CreateLayoutSettings(ToolStripLayoutStyle style) + { LayoutSettings layoutSettings = base.CreateLayoutSettings(style); - - if (style == ToolStripLayoutStyle.Flow) { + + if (style == ToolStripLayoutStyle.Flow) + { FlowLayoutSettings flowLayoutSettings = layoutSettings as FlowLayoutSettings; flowLayoutSettings.FlowDirection = FlowDirection.TopDown; flowLayoutSettings.WrapContents = false; @@ -984,41 +1184,50 @@ protected override LayoutSettings CreateLayoutSettings(ToolStripLayoutStyle styl return layoutSettings; } - protected override void CreateHandle() { + protected override void CreateHandle() + { base.CreateHandle(); - - if (TopLevel) { + + if (TopLevel) + { ReparentToDropDownOwnerWindow(); - if (!AutoClose || !WorkingAreaConstrained) { + if (!AutoClose || !WorkingAreaConstrained) + { ApplyTopMost(true); } } - if (DesignMode) { + if (DesignMode) + { SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, false); } } - public void Close() { + public void Close() + { SetCloseReason(ToolStripDropDownCloseReason.CloseCalled); this.Visible = false; // we were the last one in the chain, roll out of menu mode. - if (ToolStripManager.ModalMenuFilter.GetActiveToolStrip() == null) { + if (ToolStripManager.ModalMenuFilter.GetActiveToolStrip() == null) + { ToolStripManager.ModalMenuFilter.ExitMenuMode(); } } - private void ResetCloseReason() { - closeReason = ToolStripDropDownCloseReason.AppFocusChange; + private void ResetCloseReason() + { + closeReason = ToolStripDropDownCloseReason.AppFocusChange; } - internal void SetCloseReason(ToolStripDropDownCloseReason reason) { - closeReason = reason; + internal void SetCloseReason(ToolStripDropDownCloseReason reason) + { + closeReason = reason; } - - - public void Close(ToolStripDropDownCloseReason reason) { + + + public void Close(ToolStripDropDownCloseReason reason) + { SetCloseReason(reason); this.Visible = false; } @@ -1027,47 +1236,58 @@ public void Close(ToolStripDropDownCloseReason reason) { /// Summary of GetBaseDropDownBounds. /// // called by ToolStripDropDownMenu, - internal Rectangle GetDropDownBounds(Rectangle suggestedBounds) { + internal Rectangle GetDropDownBounds(Rectangle suggestedBounds) + { Rectangle dropDownBounds; - if (TopLevel) { + if (TopLevel) + { Point screenPoint = Point.Empty; - if ((ownerItem != null) && (ownerItem is ToolStripDropDownItem)) { + if ((ownerItem != null) && (ownerItem is ToolStripDropDownItem)) + { screenPoint = ((ToolStripDropDownItem)ownerItem).DropDownLocation; } - else { + else + { screenPoint = suggestedBounds.Location; } - Rectangle suggestedScreenBounds = new Rectangle(screenPoint, suggestedBounds.Size); - if (WorkingAreaConstrained) { - dropDownBounds = WindowsFormsUtils.ConstrainToScreenWorkingAreaBounds(suggestedScreenBounds); + Rectangle suggestedScreenBounds = new Rectangle(screenPoint, suggestedBounds.Size); + if (WorkingAreaConstrained) + { + dropDownBounds = WindowsFormsUtils.ConstrainToScreenWorkingAreaBounds(suggestedScreenBounds); } - else { - dropDownBounds = WindowsFormsUtils.ConstrainToScreenBounds(suggestedScreenBounds); + else + { + dropDownBounds = WindowsFormsUtils.ConstrainToScreenBounds(suggestedScreenBounds); } } - else { + else + { Point parentClientPoint = Point.Empty; - if ((ownerItem != null) && (ownerItem is ToolStripDropDownItem) && (ParentInternal != null)) { + if ((ownerItem != null) && (ownerItem is ToolStripDropDownItem) && (ParentInternal != null)) + { parentClientPoint = ParentInternal.PointToClient(((ToolStripDropDownItem)ownerItem).DropDownLocation); } - else { + else + { parentClientPoint = suggestedBounds.Location; } dropDownBounds = new Rectangle(parentClientPoint, suggestedBounds.Size); } - Debug.WriteLineIf(DropDownDebugBounds.TraceVerbose, "DropDownBounds for " + suggestedBounds + "is" +dropDownBounds); - - return dropDownBounds; - + Debug.WriteLineIf(DropDownDebugBounds.TraceVerbose, "DropDownBounds for " + suggestedBounds + "is" + dropDownBounds); + + return dropDownBounds; + } - - internal Rectangle CalculateDropDownLocation(Point start, ToolStripDropDownDirection dropDownDirection) { + + internal Rectangle CalculateDropDownLocation(Point start, ToolStripDropDownDirection dropDownDirection) + { Point offset = Point.Empty; - if (!IsHandleCreated) { + if (!IsHandleCreated) + { // PERF: // if the handle isnt created yet, then we likely havent performed layout // yet. force a layout here so that we get the correct size. @@ -1075,54 +1295,62 @@ internal Rectangle CalculateDropDownLocation(Point start, ToolStripDropDownDirec } Rectangle dropDownBounds = new Rectangle(Point.Empty, GetSuggestedSize()); // calculate the offset from the upper left hand corner of the item. - switch (dropDownDirection) { + switch (dropDownDirection) + { case ToolStripDropDownDirection.AboveLeft: - offset.X = - dropDownBounds.Width; - offset.Y = - dropDownBounds.Height; + offset.X = -dropDownBounds.Width; + offset.Y = -dropDownBounds.Height; break; - case ToolStripDropDownDirection.AboveRight: - offset.Y = - dropDownBounds.Height; + case ToolStripDropDownDirection.AboveRight: + offset.Y = -dropDownBounds.Height; break; case ToolStripDropDownDirection.BelowRight: case ToolStripDropDownDirection.Right: break; case ToolStripDropDownDirection.BelowLeft: case ToolStripDropDownDirection.Left: - offset.X = - dropDownBounds.Width; + offset.X = -dropDownBounds.Width; break; } - dropDownBounds.Location = new Point(start.X + offset.X, start.Y + offset.Y); - if (WorkingAreaConstrained) { - dropDownBounds = WindowsFormsUtils.ConstrainToScreenWorkingAreaBounds(dropDownBounds); + dropDownBounds.Location = new Point(start.X + offset.X, start.Y + offset.Y); + if (WorkingAreaConstrained) + { + dropDownBounds = WindowsFormsUtils.ConstrainToScreenWorkingAreaBounds(dropDownBounds); } return dropDownBounds; - + } - internal Size GetSuggestedSize() { - if (AutoSize) { + internal Size GetSuggestedSize() + { + if (AutoSize) + { return GetPreferredSize(Size.Empty); } return this.Size; } - + /// /// Returns the ToolStrip from which all the dropdowns started from. This can be null. /// - internal override ToolStrip GetToplevelOwnerToolStrip() { + internal override ToolStrip GetToplevelOwnerToolStrip() + { ToolStripDropDown topmost = GetFirstDropDown(); return (topmost.OwnerItem == null) ? null : topmost.OwnerToolStrip; } - internal ToolStripItem GetToplevelOwnerItem() { - ToolStripDropDown topmost = GetFirstDropDown(); - return topmost.OwnerItem; + internal ToolStripItem GetToplevelOwnerItem() + { + ToolStripDropDown topmost = GetFirstDropDown(); + return topmost.OwnerItem; } - internal override void HandleItemClicked(ToolStripItem dismissingItem) { + internal override void HandleItemClicked(ToolStripItem dismissingItem) + { // Only clear the SourceControl if this is the last click. if (!LocalAppContextSwitches.UseLegacyContextMenuStripSourceControlValue && - this.ActiveDropDowns.Count == 0) { + this.ActiveDropDowns.Count == 0) + { // post processing after the click has happened. SourceControlInternal = null; } @@ -1131,22 +1359,23 @@ internal override void HandleItemClicked(ToolStripItem dismissingItem) { /// /// Set some common properties /// - internal virtual void Initialize() { + internal virtual void Initialize() + { SetState(STATE_VISIBLE, false); SetTopLevelInternal(true); - + // Marking this as a modal form prevents it from being activated // by the IMsoComponentManager, which will break keyboard routing in VS. // SetState(STATE_MODAL, true); - + SetStyle(ControlStyles.ResizeRedraw, true); this.UpdateStyles(); - this.GripStyle = ToolStripGripStyle.Hidden; - this.CanOverflow = false; - this.LayoutStyle = ToolStripLayoutStyle.Flow; + this.GripStyle = ToolStripGripStyle.Hidden; + this.CanOverflow = false; + this.LayoutStyle = ToolStripLayoutStyle.Flow; this.MenuAutoExpand = true; - this.AutoSize = true; + this.AutoSize = true; } @@ -1154,65 +1383,79 @@ internal virtual void Initialize() { /// Summary of OnLayout. /// /// - protected virtual void OnClosed(ToolStripDropDownClosedEventArgs e){ - if (IsHandleCreated) { + protected virtual void OnClosed(ToolStripDropDownClosedEventArgs e) + { + if (IsHandleCreated) + { if (ownerItem == null || !ownerItem.IsInDesignMode) { AccessibilityNotifyClients(AccessibleEvents.SystemMenuPopupEnd, -1); } - } - ToolStripDropDownClosedEventHandler handler = (ToolStripDropDownClosedEventHandler)Events[EventClosed]; - if (handler != null) handler(this, e); + } + ToolStripDropDownClosedEventHandler handler = (ToolStripDropDownClosedEventHandler)Events[EventClosed]; + if (handler != null) + handler(this, e); } - + // - protected virtual void OnClosing(ToolStripDropDownClosingEventArgs e) { - ToolStripDropDownClosingEventHandler handler = (ToolStripDropDownClosingEventHandler)Events[EventClosing]; - if (handler != null) handler(this, e); + protected virtual void OnClosing(ToolStripDropDownClosingEventArgs e) + { + ToolStripDropDownClosingEventHandler handler = (ToolStripDropDownClosingEventHandler)Events[EventClosing]; + if (handler != null) + handler(this, e); } /// /// When our handle is being created, suspend the deactivation /// portion of the WndProc, as we'll never be shown. /// - protected override void OnHandleCreated(EventArgs e) { - UpdateStyles(); // get rid of WS_CAPTION style - base.OnHandleCreated(e); - UpdateLayered(); // update transparency + protected override void OnHandleCreated(EventArgs e) + { + UpdateStyles(); // get rid of WS_CAPTION style + base.OnHandleCreated(e); + UpdateLayered(); // update transparency } - - protected override void OnItemClicked(ToolStripItemClickedEventArgs e) { - try { + + protected override void OnItemClicked(ToolStripItemClickedEventArgs e) + { + try + { base.OnItemClicked(e); } - finally { + finally + { ToolStripDropDownItem dismissingItem = e.ClickedItem as ToolStripDropDownItem; - if (AutoClose) { + if (AutoClose) + { if ((dismissingItem == null) // it's not a dropdownitem || (dismissingItem is ToolStripSplitButton && !dismissingItem.DropDown.Visible) // clicking on the split button button dismisses - || !(dismissingItem.HasDropDownItems)) { // clicking on a item w/dropdown does not dismiss window - Close(ToolStripDropDownCloseReason.ItemClicked); + || !(dismissingItem.HasDropDownItems)) + { // clicking on a item w/dropdown does not dismiss window + Close(ToolStripDropDownCloseReason.ItemClicked); } } } - + } - - - protected override void OnLayout(LayoutEventArgs e) { + + + protected override void OnLayout(LayoutEventArgs e) + { // It's important to size the dropdown first, then layout so that // the layout engine and SetDisplayedItems know how big the container is. AdjustSize(); base.OnLayout(e); - + } - protected virtual void OnOpening(CancelEventArgs e){ + protected virtual void OnOpening(CancelEventArgs e) + { CancelEventHandler handler = (CancelEventHandler)Events[EventOpening]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } @@ -1220,8 +1463,10 @@ protected virtual void OnOpening(CancelEventArgs e){ /// Summary of OnLayout. /// /// - protected virtual void OnOpened(System.EventArgs e) { - if (IsHandleCreated) { + protected virtual void OnOpened(System.EventArgs e) + { + if (IsHandleCreated) + { if (ownerItem == null || !ownerItem.IsInDesignMode) { AccessibilityNotifyClients(AccessibleEvents.SystemMenuPopupStart, -1); @@ -1229,11 +1474,14 @@ protected virtual void OnOpened(System.EventArgs e) { } EventHandler handler = (EventHandler)Events[EventOpened]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } - protected override void OnVisibleChanged(System.EventArgs e) { - if (this.Location != this.displayLocation) { + protected override void OnVisibleChanged(System.EventArgs e) + { + if (this.Location != this.displayLocation) + { // If we adjusted the position from where the user wanted it, // see if we can put it in the right location now that they've changed // the items collection, and store where we actually have it. @@ -1243,73 +1491,91 @@ protected override void OnVisibleChanged(System.EventArgs e) { this.Location = this.displayLocation; this.displayLocation = this.Location; } - if (AutoScroll || this.LayoutRequired) { + if (AutoScroll || this.LayoutRequired) + { // the base here forces a layout... we really only want to do this the first // time we pop the window... the subsequent times should be snappy. base.OnVisibleChanged(e); } - else { + else + { this.SuspendLayout(); - try { + try + { // scrollable control forces a layout here for scrollbar reasons only // since we toggle visibility a lot this is expensive. Let's be clever and // not do it. base.OnVisibleChanged(e); } - finally { + finally + { this.ResumeLayout(false); } } } - protected override void OnParentChanged(System.EventArgs e) { + protected override void OnParentChanged(System.EventArgs e) + { base.OnParentChanged(e); - Rectangle bounds = this.Bounds; + Rectangle bounds = this.Bounds; SetBoundsCore(bounds.X, bounds.Y, bounds.Width, bounds.Height, BoundsSpecified.Location); } - protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs mea) { + protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs mea) + { base.OnMouseUp(mea); Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[ToolStripDropDown.OnMouseUp] mouse up outside of the toolstrip - this should dismiss the entire chain"); // Menus should dismiss when you drag off - if (!ClientRectangle.Contains(mea.Location)) { + if (!ClientRectangle.Contains(mea.Location)) + { bool dismiss = true; - if (OwnerToolStrip != null && OwnerItem != null) { - if (OwnerItem.Bounds.Contains(WindowsFormsUtils.TranslatePoint(mea.Location, this, OwnerToolStrip))) { + if (OwnerToolStrip != null && OwnerItem != null) + { + if (OwnerItem.Bounds.Contains(WindowsFormsUtils.TranslatePoint(mea.Location, this, OwnerToolStrip))) + { dismiss = false; // dont dismiss if we clicked on our owner item } } - if (dismiss) { + if (dismiss) + { DismissAll(); CancelAutoExpand(); } } } - internal void OnOwnerItemFontChanged(EventArgs e) { - if (this.IsAutoGenerated) { - using (new LayoutTransaction(this, OwnerItem, PropertyNames.Font)) { + internal void OnOwnerItemFontChanged(EventArgs e) + { + if (this.IsAutoGenerated) + { + using (new LayoutTransaction(this, OwnerItem, PropertyNames.Font)) + { OnFontChanged(e); } } } - internal void SelectPreviousToolStrip() { + internal void SelectPreviousToolStrip() + { // snap the owner item before calling hide as non-auto created dropdowns will // exit menu mode if there's no OwnerItem. ToolStripItem itemOnPreviousMenuToSelect = this.OwnerItem; this.Hide(); - if (itemOnPreviousMenuToSelect != null) { + if (itemOnPreviousMenuToSelect != null) + { itemOnPreviousMenuToSelect.Select(); KeyboardToolTipStateMachine.Instance.NotifyAboutGotFocus(itemOnPreviousMenuToSelect); - if (OwnerToolStrip != null) { + if (OwnerToolStrip != null) + { // make sure we send keyboard handling where we've just // sent selection - if (!OwnerToolStrip.IsDropDown) { - if (ToolStripManager.ModalMenuFilter.GetActiveToolStrip() != OwnerToolStrip) { + if (!OwnerToolStrip.IsDropDown) + { + if (ToolStripManager.ModalMenuFilter.GetActiveToolStrip() != OwnerToolStrip) + { ToolStripManager.ModalMenuFilter.SetActiveToolStrip(OwnerToolStrip); } // escape should cancel auto expansion @@ -1317,17 +1583,19 @@ internal void SelectPreviousToolStrip() { // When the control cannot be select (TabStop), we can press "Tab" to // navigate inside the owner toolstip. Otherwise, press "Tab" will leave // the owner toolstrip so it should exit the menu mode. - if (OwnerToolStrip.CanSelect) { + if (OwnerToolStrip.CanSelect) + { ToolStripManager.ModalMenuFilter.ExitMenuMode(); } } } } - else { + else + { Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[ToolStripDropDown.SelectPreviousToolStrip] No previous toolstrip to select - exiting menu mode."); ToolStripManager.ModalMenuFilter.ExitMenuMode(); } - + } @@ -1336,30 +1604,36 @@ internal void SelectPreviousToolStrip() { /// if you have one of these dropdowns showing and you hit the arrow key /// and it's not processed by the menu item /// - internal override bool ProcessArrowKey(Keys keyCode) { + internal override bool ProcessArrowKey(Keys keyCode) + { Debug.WriteLineIf(ToolStrip.MenuAutoExpandDebug.TraceVerbose, "[ToolStripDropDown.ProcessArrowKey] MenuTimer.Cancel called"); ToolStripMenuItem.MenuTimer.Cancel(); - - if (keyCode == Keys.Left || keyCode == Keys.Right) { - + + if (keyCode == Keys.Left || keyCode == Keys.Right) + { + bool rightAligned = SystemInformation.RightAlignedMenus; - bool forward = (keyCode == Keys.Left && rightAligned) || (keyCode == Keys.Right && !rightAligned); - - if (!IsFirstDropDown && !forward) { + bool forward = (keyCode == Keys.Left && rightAligned) || (keyCode == Keys.Right && !rightAligned); + + if (!IsFirstDropDown && !forward) + { // this is the case where you've casecaded out to a second level dropdown and you hit the back arrow // key. In this case we want to just hide the current dropdown this.Visible = false; return true; } - else { + else + { bool closeOnHorizontalKey = false; - if (LayoutStyle == ToolStripLayoutStyle.Flow) { + if (LayoutStyle == ToolStripLayoutStyle.Flow) + { closeOnHorizontalKey = FlowLayout.GetFlowDirection(this) == FlowDirection.TopDown && !FlowLayout.GetWrapContents(this); } - if (closeOnHorizontalKey) { + if (closeOnHorizontalKey) + { ToolStrip toplevelToolStrip = GetToplevelOwnerToolStrip(); ToolStripItem rootItem = GetToplevelOwnerItem(); @@ -1370,20 +1644,24 @@ internal override bool ProcessArrowKey(Keys keyCode) { // of the cascade AND the current item has no cascading menu associated with it. bool isOnOverflow = (OwnerItem != null && OwnerItem.IsOnOverflow); - if (forward || !isOnOverflow) { + if (forward || !isOnOverflow) + { SetCloseReason(ToolStripDropDownCloseReason.Keyboard); DismissAll(); } - else if (isOnOverflow) { + else if (isOnOverflow) + { // Going backwards should roll us up and our children but not the overflow. Visible = false; } - if (toplevelToolStrip != null && rootItem != null) { - if (ToolStripManager.ModalMenuFilter.GetActiveToolStrip() != toplevelToolStrip) { + if (toplevelToolStrip != null && rootItem != null) + { + if (ToolStripManager.ModalMenuFilter.GetActiveToolStrip() != toplevelToolStrip) + { ToolStripManager.ModalMenuFilter.SetActiveToolStrip(toplevelToolStrip); } - toplevelToolStrip.SelectNextToolStripItem(rootItem,forward); + toplevelToolStrip.SelectNextToolStripItem(rootItem, forward); } return true; } @@ -1394,29 +1672,35 @@ internal override bool ProcessArrowKey(Keys keyCode) { } - protected override bool ProcessDialogKey(Keys keyData) { - if (this.OwnerItem != null && this.OwnerItem.IsInDesignMode) { + protected override bool ProcessDialogKey(Keys keyData) + { + if (this.OwnerItem != null && this.OwnerItem.IsInDesignMode) + { return false; } - - if (AutoClose && Visible) { - if (ToolStripManager.IsMenuKey(keyData)) { + + if (AutoClose && Visible) + { + if (ToolStripManager.IsMenuKey(keyData)) + { SetCloseReason(ToolStripDropDownCloseReason.Keyboard); DismissAll(); ToolStrip toplevel = GetToplevelOwnerToolStrip(); - if (toplevel != null) { - Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[ToolStripDropDown ProcessDialogKey]: Got Menu Key, finding toplevel toolstrip, calling RestoreFocus."); - toplevel.RestoreFocusInternal(); - ToolStripManager.ModalMenuFilter.MenuKeyToggle = true; + if (toplevel != null) + { + Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[ToolStripDropDown ProcessDialogKey]: Got Menu Key, finding toplevel toolstrip, calling RestoreFocus."); + toplevel.RestoreFocusInternal(); + ToolStripManager.ModalMenuFilter.MenuKeyToggle = true; } ToolStripManager.ModalMenuFilter.ExitMenuMode(); return true; } - else if ((keyData & Keys.KeyCode) == Keys.Escape) { - SetCloseReason(ToolStripDropDownCloseReason.Keyboard); - SelectPreviousToolStrip(); - return true; - + else if ((keyData & Keys.KeyCode) == Keys.Escape) + { + SetCloseReason(ToolStripDropDownCloseReason.Keyboard); + SelectPreviousToolStrip(); + return true; + } } return base.ProcessDialogKey(keyData); @@ -1462,105 +1746,122 @@ internal override void ProcessDuplicateMnemonic(ToolStripItem item, char charCod } } - internal override void RecreateHandleCore() { + internal override void RecreateHandleCore() + { // If we're visible, then we'll have set our parent hwnd to the active control. // That means that re-create handle will set it as our parent, but that's not what // we want, since that means that from now on we'll be displayed in that controls // client co-ordinates. To fix this, we first re-parent ourselves back to the // hidden window, do the re-create, then set the parent again. - if (Visible) { + if (Visible) + { ReparentToDropDownOwnerWindow(); } base.RecreateHandleCore(); - if (Visible) { + if (Visible) + { ReparentToActiveToolStripWindow(); } - } - - private void ResetDropShadowEnabled() { - DropShadowEnabled = true; - } - - private void ReparentToActiveToolStripWindow() { - ToolStripManager.ModalMenuFilter.SetActiveToolStrip(this); - UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_HWNDPARENT, ToolStripManager.ModalMenuFilter.ActiveHwnd); - } - - private void ReparentToDropDownOwnerWindow() { - // when we're toplevel we need to parent ourselves to a hidden window - // this prevents a taskbar entry. - NativeWindow ownerWindow = DropDownOwnerWindow; - HandleRef ownerHandle = new HandleRef(ownerWindow, ownerWindow.Handle); - UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_HWNDPARENT, ownerHandle); - } - - /// - /// VERY similar to Form.ScaleCore - /// - [EditorBrowsable(EditorBrowsableState.Never)] - protected override void ScaleCore(float dx, float dy) { - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, GetType().Name + "::ScaleCore(" + dx + ", " + dy + ")"); - SuspendLayout(); - try { - //Get size values in advance to prevent one change from affecting another. - Size clientSize = ClientSize; - Size minSize = MinimumSize; - Size maxSize = MaximumSize; - ClientSize = ScaleSize(clientSize, dx, dy); - if (!MinimumSize.IsEmpty) { - MinimumSize = ScaleSize(minSize, dx, dy); - } - if (!MaximumSize.IsEmpty) { - MaximumSize = ScaleSize(maxSize, dx, dy); - } - - ScaleDockPadding(dx, dy); - - foreach(Control control in Controls) { - if (control != null) { + } + + private void ResetDropShadowEnabled() + { + DropShadowEnabled = true; + } + + private void ReparentToActiveToolStripWindow() + { + ToolStripManager.ModalMenuFilter.SetActiveToolStrip(this); + UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_HWNDPARENT, ToolStripManager.ModalMenuFilter.ActiveHwnd); + } + + private void ReparentToDropDownOwnerWindow() + { + // when we're toplevel we need to parent ourselves to a hidden window + // this prevents a taskbar entry. + NativeWindow ownerWindow = DropDownOwnerWindow; + HandleRef ownerHandle = new HandleRef(ownerWindow, ownerWindow.Handle); + UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_HWNDPARENT, ownerHandle); + } + + /// + /// VERY similar to Form.ScaleCore + /// + [EditorBrowsable(EditorBrowsableState.Never)] + protected override void ScaleCore(float dx, float dy) + { + Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, GetType().Name + "::ScaleCore(" + dx + ", " + dy + ")"); + SuspendLayout(); + try + { + //Get size values in advance to prevent one change from affecting another. + Size clientSize = ClientSize; + Size minSize = MinimumSize; + Size maxSize = MaximumSize; + ClientSize = ScaleSize(clientSize, dx, dy); + if (!MinimumSize.IsEmpty) + { + MinimumSize = ScaleSize(minSize, dx, dy); + } + if (!MaximumSize.IsEmpty) + { + MaximumSize = ScaleSize(maxSize, dx, dy); + } + + ScaleDockPadding(dx, dy); + + foreach (Control control in Controls) + { + if (control != null) + { #pragma warning disable 618 - control.Scale(dx, dy); + control.Scale(dx, dy); #pragma warning restore 618 - } - } - } - finally { - ResumeLayout(); - } - } - - /// - /// Scale this form. Form overrides this to enforce a maximum / minimum size. - /// - protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { - - base.ScaleControl(factor, specified); - - Size minSize = MinimumSize; - Size maxSize = MaximumSize; - if (!MinimumSize.IsEmpty) { - MinimumSize = ScaleSize(minSize, factor.Width, factor.Height); - } - if (!MaximumSize.IsEmpty) { - MaximumSize = ScaleSize(maxSize, factor.Width, factor.Height); - } - } - - /// - /// This is called when the ToolStripDropDownItem sets the DropDown property using CreateDefaultDropDown. - /// In this case, the IsAutoGenerated should return true. - /// - internal void SetAutoGeneratedInternal(bool autoGenerated) - { - this.isAutoGenerated = autoGenerated; - } + } + } + } + finally + { + ResumeLayout(); + } + } + + /// + /// Scale this form. Form overrides this to enforce a maximum / minimum size. + /// + protected override void ScaleControl(SizeF factor, BoundsSpecified specified) + { + + base.ScaleControl(factor, specified); + + Size minSize = MinimumSize; + Size maxSize = MaximumSize; + if (!MinimumSize.IsEmpty) + { + MinimumSize = ScaleSize(minSize, factor.Width, factor.Height); + } + if (!MaximumSize.IsEmpty) + { + MaximumSize = ScaleSize(maxSize, factor.Width, factor.Height); + } + } + + /// + /// This is called when the ToolStripDropDownItem sets the DropDown property using CreateDefaultDropDown. + /// In this case, the IsAutoGenerated should return true. + /// + internal void SetAutoGeneratedInternal(bool autoGenerated) + { + this.isAutoGenerated = autoGenerated; + } /// /// Sync sizes with the ToolStripDropDown /// - protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { - + protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) + { + Rectangle bounds = new Rectangle(x, y, width, height); bounds = GetDropDownBounds(bounds); @@ -1568,25 +1869,29 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound } - private void SetTopLevelStyle(bool value) { - if (IsHandleCreated) { + private void SetTopLevelStyle(bool value) + { + if (IsHandleCreated) + { // We need to swap they style bits on the window handle // we could recreate the handle, but that seems rather expensive. int styleFlags = WindowStyle; - - if (value) { + + if (value) + { // setting toplevel = true styleFlags &= ~NativeMethods.WS_CHILD; styleFlags |= NativeMethods.WS_POPUP; } - else { + else + { // this is a child window styleFlags &= ~NativeMethods.WS_POPUP; styleFlags |= NativeMethods.WS_CHILD; } WindowStyle = styleFlags; - + } } @@ -1606,7 +1911,7 @@ protected override void SetVisibleCore(bool visible) { LayoutTransaction.DoLayout(this, this, PropertyNames.Visible); } - + // Assume that it's been cancelled so that if we throw we do nothing. bool openingEventCancelled = true; @@ -1729,7 +2034,7 @@ protected override void SetVisibleCore(bool visible) // Preserve the SourceControl value up the chain. saveSourceControl = true; DismissAll(); - + // make sure that when we roll up, our owner item's selection is cleared. ToolStripItem rootOwnerItem = GetToplevelOwnerItem(); rootOwnerItem?.Unselect(); @@ -1826,7 +2131,8 @@ protected override void SetVisibleCore(bool visible) } } - private bool ShouldSerializeDefaultDropDownDirection() { + private bool ShouldSerializeDefaultDropDownDirection() + { return (childDropDownDirection != ToolStripDropDownDirection.Default); } @@ -1834,33 +2140,40 @@ private bool ShouldSerializeDefaultDropDownDirection() { /// Updates the layered window attributes if the control /// is in layered mode. /// - private void UpdateLayered() { - if (state[stateLayered] && IsHandleCreated && TopLevel && OSFeature.Feature.IsPresent(OSFeature.LayeredWindows)) { + private void UpdateLayered() + { + if (state[stateLayered] && IsHandleCreated && TopLevel && OSFeature.Feature.IsPresent(OSFeature.LayeredWindows)) + { bool result; - + result = UnsafeNativeMethods.SetLayeredWindowAttributes(new HandleRef(this, Handle), 0, OpacityAsByte, NativeMethods.LWA_ALPHA); - - if (!result) { + + if (!result) + { throw new Win32Exception(); } } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new void Show() { + public new void Show() + { // don't set displayLocation here, since all the other Show methods call this. base.Show(); } /// show relative to control coordinates - public void Show(Control control, Point position) { - if (control == null) { + public void Show(Control control, Point position) + { + if (control == null) + { throw new ArgumentNullException(nameof(control)); } SourceControlInternal = control; // When we have no owner item and we're set to RTL.Inherit, translate the coordinates // so that the menu looks like it's swooping from the other side - if (this.OwnerItem == null && control.RightToLeft == RightToLeft.Yes) { + if (this.OwnerItem == null && control.RightToLeft == RightToLeft.Yes) + { AdjustSize(); position.Offset(control.IsMirrored ? Width : -Width, 0); } @@ -1868,60 +2181,71 @@ public void Show(Control control, Point position) { this.displayLocation = control.PointToScreen(position); this.Location = this.displayLocation; ShowCore(); - + } - public void Show(Control control, Point position, ToolStripDropDownDirection direction) { - if (control == null) { + public void Show(Control control, Point position, ToolStripDropDownDirection direction) + { + if (control == null) + { throw new ArgumentNullException(nameof(control)); } SourceControlInternal = control; - this.displayLocation = CalculateDropDownLocation(control.PointToScreen(position), direction).Location; + this.displayLocation = CalculateDropDownLocation(control.PointToScreen(position), direction).Location; this.Location = this.displayLocation; ShowCore(); } /// show relative to control coordinates - public void Show(Control control, int x, int y) { - if (control == null) { + public void Show(Control control, int x, int y) + { + if (control == null) + { throw new ArgumentNullException(nameof(control)); } SourceControlInternal = control; - Show(control, new Point(x,y)); + Show(control, new Point(x, y)); } /// show relative to screen coordinates - public void Show(Point screenLocation) { + public void Show(Point screenLocation) + { this.displayLocation = screenLocation; this.Location = this.displayLocation; ShowCore(); } - public void Show(Point position, ToolStripDropDownDirection direction) { + public void Show(Point position, ToolStripDropDownDirection direction) + { this.displayLocation = CalculateDropDownLocation(position, direction).Location; this.Location = this.displayLocation; ShowCore(); } - + /// show relative to screen coordinates - public void Show(int x, int y) { - this.displayLocation = new Point(x,y); + public void Show(int x, int y) + { + this.displayLocation = new Point(x, y); this.Location = this.displayLocation; ShowCore(); } - private void ShowCore() { + private void ShowCore() + { Show(); } - - private bool ShouldSerializeDropShadowEnabled() { - return dropShadowEnabled == false; + + private bool ShouldSerializeDropShadowEnabled() + { + return dropShadowEnabled == false; } - internal override bool ShouldSerializeLayoutStyle() { + internal override bool ShouldSerializeLayoutStyle() + { return LayoutStyle != ToolStripLayoutStyle.VerticalStackWithOverflow; } - internal void UnassignDropDownItem() { + internal void UnassignDropDownItem() + { Debug.Assert(countDropDownItemsAssignedTo > 0, "dropdown assignment underflow"); countDropDownItemsAssignedTo = Math.Max(--countDropDownItemsAssignedTo, 0); } @@ -1972,55 +2296,67 @@ protected override void WndProc(ref Message m) } -#region DropDownSpecific - internal void DismissAll() { - ToolStripDropDown toplevel = this.GetFirstDropDown(); - toplevel.closeReason = this.closeReason; - toplevel.DismissActiveDropDowns(); - if (!LocalAppContextSwitches.UseLegacyContextMenuStripSourceControlValue) { + #region DropDownSpecific + internal void DismissAll() + { + ToolStripDropDown toplevel = this.GetFirstDropDown(); + toplevel.closeReason = this.closeReason; + toplevel.DismissActiveDropDowns(); + if (!LocalAppContextSwitches.UseLegacyContextMenuStripSourceControlValue) + { toplevel.saveSourceControl = this.saveSourceControl; } toplevel.Visible = false; - } - private void DismissActiveDropDowns() { - Debug.WriteLineIf((DropDownActivateDebug.TraceVerbose && ActiveDropDowns.Count > 0), "Dismiss children called - COUNT " + ActiveDropDowns.Count + " \r\n" + new StackTrace().ToString()); - int count = ActiveDropDowns.Count; - if (count == 1) { - // this is the most common case - ToolStripDropDown dropDown = ActiveDropDowns[0] as ToolStripDropDown; - if (dropDown != null) { - dropDown.Visible = false; - } - - } - else { - ArrayList dropDowns = ActiveDropDowns.Clone() as ArrayList; - // We cant iterate through the active dropdown collection - // here as changing visibility changes the collection. - for (int i = 0; i < dropDowns.Count; i++) { - ToolStripDropDown dropDown = dropDowns[i] as ToolStripDropDown; - if (dropDown != null) { - dropDown.Visible = false; - } - } - } - } - -#region WMNCACTIVATE - private bool sendingActivateMessage = false; - - // WmNcActivate - // if someone clicks on a child control of the toolstrip dropdown, we want - // the title bar to continue appearing active. Normally we just show without - // taking window activation (ShowWindow(SHOWNOACTIVATE)) but we cant stop - // child controls from taking focus. - private void WmNCActivate(ref Message m) { - - if (m.WParam != IntPtr.Zero /*activating*/) { - - if (!sendingActivateMessage) { + } + private void DismissActiveDropDowns() + { + Debug.WriteLineIf((DropDownActivateDebug.TraceVerbose && ActiveDropDowns.Count > 0), "Dismiss children called - COUNT " + ActiveDropDowns.Count + " \r\n" + new StackTrace().ToString()); + int count = ActiveDropDowns.Count; + if (count == 1) + { + // this is the most common case + ToolStripDropDown dropDown = ActiveDropDowns[0] as ToolStripDropDown; + if (dropDown != null) + { + dropDown.Visible = false; + } + + } + else + { + ArrayList dropDowns = ActiveDropDowns.Clone() as ArrayList; + // We cant iterate through the active dropdown collection + // here as changing visibility changes the collection. + for (int i = 0; i < dropDowns.Count; i++) + { + ToolStripDropDown dropDown = dropDowns[i] as ToolStripDropDown; + if (dropDown != null) + { + dropDown.Visible = false; + } + } + } + } + + #region WMNCACTIVATE + private bool sendingActivateMessage = false; + + // WmNcActivate + // if someone clicks on a child control of the toolstrip dropdown, we want + // the title bar to continue appearing active. Normally we just show without + // taking window activation (ShowWindow(SHOWNOACTIVATE)) but we cant stop + // child controls from taking focus. + private void WmNCActivate(ref Message m) + { + + if (m.WParam != IntPtr.Zero /*activating*/) + { + + if (!sendingActivateMessage) + { sendingActivateMessage = true; - try { + try + { Debug.WriteLineIf(DropDownActivateDebug.TraceVerbose, "Sending WM_NCACTIVATE to toplevel hwnd" + ToolStripManager.ModalMenuFilter.ActiveHwnd); // we're activating - notify the previous guy that we're activating. HandleRef activeHwndHandleRef = ToolStripManager.ModalMenuFilter.ActiveHwnd; @@ -2029,7 +2365,8 @@ private void WmNCActivate(ref Message m) { SafeNativeMethods.RedrawWindow(activeHwndHandleRef, null, NativeMethods.NullHandleRef, NativeMethods.RDW_FRAME | NativeMethods.RDW_INVALIDATE); m.WParam = (IntPtr)1; } - finally { + finally + { sendingActivateMessage = false; } } @@ -2037,17 +2374,20 @@ private void WmNCActivate(ref Message m) { return; } - else { + else + { base.WndProc(ref m); } } -#endregion + #endregion /// /// Determines if this is the first dropDown in the dropDown chain /// - internal bool IsFirstDropDown { - get { + internal bool IsFirstDropDown + { + get + { return ((OwnerToolStrip as ToolStripDropDown) == null); } } @@ -2055,21 +2395,25 @@ internal bool IsFirstDropDown { /// /// returns the root dropdown in the chain. /// - internal ToolStripDropDown GetFirstDropDown() { + internal ToolStripDropDown GetFirstDropDown() + { ToolStripDropDown topmost = this; // walk back up the chain of windows to get the topmost ToolStripDropDown ownerDropDown = topmost.OwnerToolStrip as ToolStripDropDown; - while (ownerDropDown != null) { + while (ownerDropDown != null) + { topmost = ownerDropDown; ownerDropDown = topmost.OwnerToolStrip as ToolStripDropDown; } return topmost; } - internal static ToolStripDropDown GetFirstDropDown(ToolStrip start) { + internal static ToolStripDropDown GetFirstDropDown(ToolStrip start) + { Debug.Assert(start != null, "Who is passing null to GetFirstDropDown?"); - if ((start == null) || (!start.IsDropDown)) { + if ((start == null) || (!start.IsDropDown)) + { return null; } ToolStripDropDown startDropDown = (start as ToolStripDropDown); @@ -2077,52 +2421,62 @@ internal static ToolStripDropDown GetFirstDropDown(ToolStrip start) { } -#endregion DropDownSpecific + #endregion DropDownSpecific - [System.Runtime.InteropServices.ComVisible(true)] - public class ToolStripDropDownAccessibleObject : ToolStripAccessibleObject { - private ToolStripDropDown owner; - - public ToolStripDropDownAccessibleObject(ToolStripDropDown owner) : base(owner) { - this.owner = owner; - } + [System.Runtime.InteropServices.ComVisible(true)] + public class ToolStripDropDownAccessibleObject : ToolStripAccessibleObject + { + private ToolStripDropDown owner; - public override string Name { - get { - // Special case: If an explicit name has been set in the AccessibleName property, use that. - // Note: Any non-null value in AccessibleName overrides the default accessible name logic, - // even an empty string (this is the only way to *force* the accessible name to be blank). - string name = owner.AccessibleName; - if (name != null) { - return name; - } + public ToolStripDropDownAccessibleObject(ToolStripDropDown owner) : base(owner) + { + this.owner = owner; + } - // NOT localized for testing purposes. Localizers can use AccessibleName. - name = "DropDown"; - - if (owner.OwnerItem != null && owner.OwnerItem.AccessibilityObject.Name != null) { - name = owner.OwnerItem.AccessibilityObject.Name + name; - } - + public override string Name + { + get + { + // Special case: If an explicit name has been set in the AccessibleName property, use that. + // Note: Any non-null value in AccessibleName overrides the default accessible name logic, + // even an empty string (this is the only way to *force* the accessible name to be blank). + string name = owner.AccessibleName; + if (name != null) + { return name; } - set { - // If anyone tries to set the accessible name, just cache the value in the control's - // AccessibleName property. This value will then end up overriding the normal accessible - // name logic, until such time as AccessibleName is set back to null. - owner.AccessibleName = value; + // NOT localized for testing purposes. Localizers can use AccessibleName. + name = "DropDown"; + + if (owner.OwnerItem != null && owner.OwnerItem.AccessibilityObject.Name != null) + { + name = owner.OwnerItem.AccessibilityObject.Name + name; } + + return name; } - public override AccessibleRole Role { - get { - AccessibleRole role = Owner.AccessibleRole; - if (role != AccessibleRole.Default) { - return role; - } - return AccessibleRole.MenuPopup; + + set + { + // If anyone tries to set the accessible name, just cache the value in the control's + // AccessibleName property. This value will then end up overriding the normal accessible + // name logic, until such time as AccessibleName is set back to null. + owner.AccessibleName = value; + } + } + public override AccessibleRole Role + { + get + { + AccessibleRole role = Owner.AccessibleRole; + if (role != AccessibleRole.Default) + { + return role; } + return AccessibleRole.MenuPopup; } + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownButton.cs index 87308fb6cb6..ba35e36d959 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownButton.cs @@ -18,50 +18,63 @@ public class ToolStripDropDownButton : ToolStripDropDownItem { private bool showDropDownArrow = true; private byte openMouseId = 0; - + /// /// Constructs a ToolStripButton that can display a popup. /// - public ToolStripDropDownButton() { + public ToolStripDropDownButton() + { Initialize(); } - public ToolStripDropDownButton(string text):base(text,null,(EventHandler)null) { - Initialize(); + public ToolStripDropDownButton(string text) : base(text, null, (EventHandler)null) + { + Initialize(); } - public ToolStripDropDownButton(Image image):base(null,image,(EventHandler)null) { - Initialize(); + public ToolStripDropDownButton(Image image) : base(null, image, (EventHandler)null) + { + Initialize(); } - public ToolStripDropDownButton(string text, Image image):base(text,image,(EventHandler)null) { - Initialize(); + public ToolStripDropDownButton(string text, Image image) : base(text, image, (EventHandler)null) + { + Initialize(); } - public ToolStripDropDownButton(string text, Image image, EventHandler onClick):base(text,image,onClick) { - Initialize(); + public ToolStripDropDownButton(string text, Image image, EventHandler onClick) : base(text, image, onClick) + { + Initialize(); } - public ToolStripDropDownButton(string text, Image image, EventHandler onClick, string name) :base(text,image,onClick,name){ - Initialize(); + public ToolStripDropDownButton(string text, Image image, EventHandler onClick, string name) : base(text, image, onClick, name) + { + Initialize(); } - public ToolStripDropDownButton(string text, Image image, params ToolStripItem[] dropDownItems):base(text,image,dropDownItems) { - Initialize(); + public ToolStripDropDownButton(string text, Image image, params ToolStripItem[] dropDownItems) : base(text, image, dropDownItems) + { + Initialize(); } - protected override AccessibleObject CreateAccessibilityInstance() { - return new ToolStripDropDownButtonAccessibleObject(this); + protected override AccessibleObject CreateAccessibilityInstance() + { + return new ToolStripDropDownButtonAccessibleObject(this); } - + [DefaultValue(true)] - public new bool AutoToolTip { - get { + public new bool AutoToolTip + { + get + { return base.AutoToolTip; } - set { + set + { base.AutoToolTip = value; } } - - protected override bool DefaultAutoToolTip { - get { - return true; + + protected override bool DefaultAutoToolTip + { + get + { + return true; } } @@ -70,14 +83,18 @@ protected override bool DefaultAutoToolTip { SRDescription(nameof(SR.ToolStripDropDownButtonShowDropDownArrowDescr)), SRCategory(nameof(SR.CatAppearance)) ] - public bool ShowDropDownArrow { - get { + public bool ShowDropDownArrow + { + get + { return showDropDownArrow; } - set { - if (showDropDownArrow != value) { + set + { + if (showDropDownArrow != value) + { showDropDownArrow = value; - this.InvalidateItemLayout(PropertyNames.ShowDropDownArrow); + this.InvalidateItemLayout(PropertyNames.ShowDropDownArrow); } } } @@ -85,90 +102,108 @@ public bool ShowDropDownArrow { /// Creates an instance of the object that defines how image and text /// gets laid out in the ToolStripItem /// - internal override ToolStripItemInternalLayout CreateInternalLayout() { + internal override ToolStripItemInternalLayout CreateInternalLayout() + { return new ToolStripDropDownButtonInternalLayout(this); } - - protected override ToolStripDropDown CreateDefaultDropDown() { - // AutoGenerate a ToolStrip DropDown - set the property so we hook events - return new ToolStripDropDownMenu(this, /*isAutoGenerated=*/true); + + protected override ToolStripDropDown CreateDefaultDropDown() + { + // AutoGenerate a ToolStrip DropDown - set the property so we hook events + return new ToolStripDropDownMenu(this, /*isAutoGenerated=*/true); } /// /// Called by all constructors of ToolStripButton. /// - private void Initialize() { - SupportsSpaceKey = true; + private void Initialize() + { + SupportsSpaceKey = true; } - + /// /// Overriden to invoke displaying the popup. /// - protected override void OnMouseDown(MouseEventArgs e) { + protected override void OnMouseDown(MouseEventArgs e) + { if ((Control.ModifierKeys != Keys.Alt) && - (e.Button == MouseButtons.Left)) { - if (DropDown.Visible) { - ToolStripManager.ModalMenuFilter.CloseActiveDropDown(DropDown, ToolStripDropDownCloseReason.AppClicked); - } - else { - // opening should happen on mouse down. - Debug.Assert(ParentInternal != null, "Parent is null here, not going to get accurate ID"); - openMouseId = (ParentInternal == null) ? (byte)0: ParentInternal.GetMouseId(); - this.ShowDropDown(/*mousePush =*/true); - } + (e.Button == MouseButtons.Left)) + { + if (DropDown.Visible) + { + ToolStripManager.ModalMenuFilter.CloseActiveDropDown(DropDown, ToolStripDropDownCloseReason.AppClicked); + } + else + { + // opening should happen on mouse down. + Debug.Assert(ParentInternal != null, "Parent is null here, not going to get accurate ID"); + openMouseId = (ParentInternal == null) ? (byte)0 : ParentInternal.GetMouseId(); + this.ShowDropDown(/*mousePush =*/true); + } } base.OnMouseDown(e); - } + } - protected override void OnMouseUp(MouseEventArgs e) { + protected override void OnMouseUp(MouseEventArgs e) + { if ((Control.ModifierKeys != Keys.Alt) && - (e.Button == MouseButtons.Left)) { + (e.Button == MouseButtons.Left)) + { Debug.Assert(ParentInternal != null, "Parent is null here, not going to get accurate ID"); - byte closeMouseId = (ParentInternal == null) ? (byte)0: ParentInternal.GetMouseId(); - if (closeMouseId != openMouseId) { + byte closeMouseId = (ParentInternal == null) ? (byte)0 : ParentInternal.GetMouseId(); + if (closeMouseId != openMouseId) + { openMouseId = 0; // reset the mouse id, we should never get this value from toolstrip. ToolStripManager.ModalMenuFilter.CloseActiveDropDown(DropDown, ToolStripDropDownCloseReason.AppClicked); Select(); } } - base.OnMouseUp(e); + base.OnMouseUp(e); } - protected override void OnMouseLeave(EventArgs e) { + protected override void OnMouseLeave(EventArgs e) + { openMouseId = 0; // reset the mouse id, we should never get this value from toolstrip. - base.OnMouseLeave(e); + base.OnMouseLeave(e); } /// /// Inheriting classes should override this method to handle this event. /// - protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { - - if (this.Owner != null) { + protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) + { + + if (this.Owner != null) + { ToolStripRenderer renderer = this.Renderer; Graphics g = e.Graphics; - + renderer.DrawDropDownButtonBackground(new ToolStripItemRenderEventArgs(e.Graphics, this)); - - if ((DisplayStyle & ToolStripItemDisplayStyle.Image) == ToolStripItemDisplayStyle.Image) { + + if ((DisplayStyle & ToolStripItemDisplayStyle.Image) == ToolStripItemDisplayStyle.Image) + { renderer.DrawItemImage(new ToolStripItemImageRenderEventArgs(g, this, InternalLayout.ImageRectangle)); } - if ((DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) { - renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, this.Text, InternalLayout.TextRectangle, this.ForeColor, this.Font, InternalLayout.TextFormat)); + if ((DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) + { + renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, this.Text, InternalLayout.TextRectangle, this.ForeColor, this.Font, InternalLayout.TextFormat)); } - if (ShowDropDownArrow) { + if (ShowDropDownArrow) + { ToolStripDropDownButton.ToolStripDropDownButtonInternalLayout layout = InternalLayout as ToolStripDropDownButtonInternalLayout; - Rectangle dropDownArrowRect = (layout != null) ? layout.DropDownArrowRect :Rectangle.Empty; + Rectangle dropDownArrowRect = (layout != null) ? layout.DropDownArrowRect : Rectangle.Empty; Color arrowColor; - if (Selected && !Pressed && SystemInformation.HighContrast) { + if (Selected && !Pressed && SystemInformation.HighContrast) + { arrowColor = Enabled ? SystemColors.HighlightText : SystemColors.ControlDark; } - else { - arrowColor = Enabled ? SystemColors.ControlText : SystemColors.ControlDark; + else + { + arrowColor = Enabled ? SystemColors.ControlText : SystemColors.ControlDark; } - renderer.DrawArrow(new ToolStripArrowRenderEventArgs(g, this,dropDownArrowRect, arrowColor, ArrowDirection.Down)); + renderer.DrawArrow(new ToolStripArrowRenderEventArgs(g, this, dropDownArrowRect, arrowColor, ArrowDirection.Down)); } } } @@ -176,120 +211,142 @@ protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] // 'charCode' matches control.cs - protected internal override bool ProcessMnemonic(char charCode) { - // checking IsMnemonic is not necesssary - toolstrip does this for us. - if (HasDropDownItems) { - Select(); - ShowDropDown(); - return true; - } - return false; - } + protected internal override bool ProcessMnemonic(char charCode) + { + // checking IsMnemonic is not necesssary - toolstrip does this for us. + if (HasDropDownItems) + { + Select(); + ShowDropDown(); + return true; + } + return false; + } /// /// An implementation of Accessibleobject for use with ToolStripDropDownButton /// [System.Runtime.InteropServices.ComVisible(true)] - internal class ToolStripDropDownButtonAccessibleObject : ToolStripDropDownItemAccessibleObject { + internal class ToolStripDropDownButtonAccessibleObject : ToolStripDropDownItemAccessibleObject + { private ToolStripDropDownButton ownerItem = null; public ToolStripDropDownButtonAccessibleObject(ToolStripDropDownButton ownerItem) - : base(ownerItem) { + : base(ownerItem) + { this.ownerItem = ownerItem; } - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_ControlTypePropertyId) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_ControlTypePropertyId) + { return NativeMethods.UIA_ButtonControlTypeId; } - else { + else + { return base.GetPropertyValue(propertyID); } } } - internal class ToolStripDropDownButtonInternalLayout : ToolStripItemInternalLayout { - private ToolStripDropDownButton ownerItem; - private static readonly Size dropDownArrowSizeUnscaled = new Size(5, 3); - private static Size dropDownArrowSize = dropDownArrowSizeUnscaled; - private const int DROP_DOWN_ARROW_PADDING = 2; - private static Padding dropDownArrowPadding = new Padding(DROP_DOWN_ARROW_PADDING); - private Padding scaledDropDownArrowPadding = dropDownArrowPadding; - private Rectangle dropDownArrowRect = Rectangle.Empty; - - public ToolStripDropDownButtonInternalLayout(ToolStripDropDownButton ownerItem) : base(ownerItem) { - if (DpiHelper.IsScalingRequired) { + internal class ToolStripDropDownButtonInternalLayout : ToolStripItemInternalLayout + { + private ToolStripDropDownButton ownerItem; + private static readonly Size dropDownArrowSizeUnscaled = new Size(5, 3); + private static Size dropDownArrowSize = dropDownArrowSizeUnscaled; + private const int DROP_DOWN_ARROW_PADDING = 2; + private static Padding dropDownArrowPadding = new Padding(DROP_DOWN_ARROW_PADDING); + private Padding scaledDropDownArrowPadding = dropDownArrowPadding; + private Rectangle dropDownArrowRect = Rectangle.Empty; + + public ToolStripDropDownButtonInternalLayout(ToolStripDropDownButton ownerItem) : base(ownerItem) + { + if (DpiHelper.IsScalingRequired) + { // these 2 values are used to calculate size of the clickable drop down button // on the right of the image/text dropDownArrowSize = DpiHelper.LogicalToDeviceUnits(dropDownArrowSizeUnscaled); scaledDropDownArrowPadding = DpiHelper.LogicalToDeviceUnits(dropDownArrowPadding); } - this.ownerItem = ownerItem; + this.ownerItem = ownerItem; } - public override Size GetPreferredSize(Size constrainingSize) { + public override Size GetPreferredSize(Size constrainingSize) + { Size preferredSize = base.GetPreferredSize(constrainingSize); - if (ownerItem.ShowDropDownArrow) { - if (ownerItem.TextDirection == ToolStripTextDirection.Horizontal) { + if (ownerItem.ShowDropDownArrow) + { + if (ownerItem.TextDirection == ToolStripTextDirection.Horizontal) + { preferredSize.Width += DropDownArrowRect.Width + scaledDropDownArrowPadding.Horizontal; } - else { + else + { preferredSize.Height += DropDownArrowRect.Height + scaledDropDownArrowPadding.Vertical; } } return preferredSize; } - protected override ToolStripItemLayoutOptions CommonLayoutOptions() { - ToolStripItemLayoutOptions options = base.CommonLayoutOptions(); + protected override ToolStripItemLayoutOptions CommonLayoutOptions() + { + ToolStripItemLayoutOptions options = base.CommonLayoutOptions(); - if (ownerItem.ShowDropDownArrow) { + if (ownerItem.ShowDropDownArrow) + { - if (ownerItem.TextDirection == ToolStripTextDirection.Horizontal) { + if (ownerItem.TextDirection == ToolStripTextDirection.Horizontal) + { // We're rendering horizontal.... make sure to take care of RTL issues. - + int widthOfDropDown = dropDownArrowSize.Width + scaledDropDownArrowPadding.Horizontal; options.client.Width -= widthOfDropDown; - if (ownerItem.RightToLeft == RightToLeft.Yes) { + if (ownerItem.RightToLeft == RightToLeft.Yes) + { // if RightToLeft.Yes: [ v | rest of drop down button ] options.client.Offset(widthOfDropDown, 0); - dropDownArrowRect = new Rectangle(scaledDropDownArrowPadding.Left,0, dropDownArrowSize.Width, ownerItem.Bounds.Height); + dropDownArrowRect = new Rectangle(scaledDropDownArrowPadding.Left, 0, dropDownArrowSize.Width, ownerItem.Bounds.Height); } - else { - // if RightToLeft.No [ rest of drop down button | v ] - dropDownArrowRect = new Rectangle(options.client.Right,0, dropDownArrowSize.Width, ownerItem.Bounds.Height); - + else + { + // if RightToLeft.No [ rest of drop down button | v ] + dropDownArrowRect = new Rectangle(options.client.Right, 0, dropDownArrowSize.Width, ownerItem.Bounds.Height); + } } - else { + else + { // else we're rendering vertically. int heightOfDropDown = dropDownArrowSize.Height + scaledDropDownArrowPadding.Vertical; options.client.Height -= heightOfDropDown; - + // [ rest of button / v] - dropDownArrowRect = new Rectangle(0,options.client.Bottom + scaledDropDownArrowPadding.Top, ownerItem.Bounds.Width-1, dropDownArrowSize.Height); - + dropDownArrowRect = new Rectangle(0, options.client.Bottom + scaledDropDownArrowPadding.Top, ownerItem.Bounds.Width - 1, dropDownArrowSize.Height); + } - } - return options; + } + return options; } - public Rectangle DropDownArrowRect { - get { - return dropDownArrowRect; + public Rectangle DropDownArrowRect + { + get + { + return dropDownArrowRect; } } - + } } } - + diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownDirection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownDirection.cs index ec7fecc5281..5c91bf609de 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownDirection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownDirection.cs @@ -7,13 +7,13 @@ namespace System.Windows.Forms public enum ToolStripDropDownDirection { - // Dir L=0 - AboveLeft = 0x0000, // 0 0 0 Above =00 + // Dir L=0 + AboveLeft = 0x0000, // 0 0 0 Above =00 AboveRight = 0x0001, // 0 0 1 Below =01 - BelowLeft = 0x0002, // 0 1 0 Side =10 + BelowLeft = 0x0002, // 0 1 0 Side =10 BelowRight = 0x0003, // 0 1 1 Last bit indicates left or right. - Left = 0x0004, // 1 0 0 - Right = 0x0005, // 1 0 1 - Default = 0x0007 // 1 1 1 + Left = 0x0004, // 1 0 0 + Right = 0x0005, // 1 0 1 + Default = 0x0007 // 1 1 1 } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs index fc3c1946d97..e0e1806c06f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs @@ -2,44 +2,51 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Drawing; using System.Windows.Forms; using System.ComponentModel; using System.Diagnostics; using System.Windows.Forms.Layout; - + /// /// Base class for ToolStripItems that display DropDown windows. /// [Designer("System.Windows.Forms.Design.ToolStripMenuItemDesigner, " + AssemblyRef.SystemDesign)] [DefaultProperty(nameof(DropDownItems))] - public abstract class ToolStripDropDownItem : ToolStripItem { + public abstract class ToolStripDropDownItem : ToolStripItem + { - private ToolStripDropDown dropDown = null; + private ToolStripDropDown dropDown = null; private ToolStripDropDownDirection toolStripDropDownDirection = ToolStripDropDownDirection.Default; - private static readonly object EventDropDownShow = new object(); - private static readonly object EventDropDownHide = new object(); - private static readonly object EventDropDownOpened = new object(); - private static readonly object EventDropDownClosed = new object(); - private static readonly object EventDropDownItemClicked = new object(); - + private static readonly object EventDropDownShow = new object(); + private static readonly object EventDropDownHide = new object(); + private static readonly object EventDropDownOpened = new object(); + private static readonly object EventDropDownClosed = new object(); + private static readonly object EventDropDownItemClicked = new object(); + /// /// Protected ctor so you can't create one of these without deriving from it. /// - protected ToolStripDropDownItem() { + protected ToolStripDropDownItem() + { } - protected ToolStripDropDownItem(string text, Image image, EventHandler onClick) : base(text, image, onClick) { + protected ToolStripDropDownItem(string text, Image image, EventHandler onClick) : base(text, image, onClick) + { } - protected ToolStripDropDownItem(string text, Image image, EventHandler onClick, string name) : base(text, image, onClick, name) { + protected ToolStripDropDownItem(string text, Image image, EventHandler onClick, string name) : base(text, image, onClick, name) + { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] - protected ToolStripDropDownItem(string text, Image image, params ToolStripItem[] dropDownItems) : this(text, image, (EventHandler)null) { - if (dropDownItems != null) { + protected ToolStripDropDownItem(string text, Image image, params ToolStripItem[] dropDownItems) : this(text, image, (EventHandler)null) + { + if (dropDownItems != null) + { this.DropDownItems.AddRange(dropDownItems); } } @@ -53,25 +60,32 @@ protected ToolStripDropDownItem(string text, Image image, params ToolStripItem[] SRCategory(nameof(SR.CatData)), SRDescription(nameof(SR.ToolStripDropDownDescr)) ] - public ToolStripDropDown DropDown { - get { - if (dropDown == null) { + public ToolStripDropDown DropDown + { + get + { + if (dropDown == null) + { DropDown = CreateDefaultDropDown(); if (!(this is ToolStripOverflowButton)) { dropDown.SetAutoGeneratedInternal(true); } - if (ParentInternal != null) { + if (ParentInternal != null) + { dropDown.ShowItemToolTips = ParentInternal.ShowItemToolTips; } - } - return dropDown; - } - set { - if (dropDown != value) { + } + return dropDown; + } + set + { + if (dropDown != value) + { - if (dropDown != null) { + if (dropDown != null) + { dropDown.Opened -= new EventHandler(DropDown_Opened); dropDown.Closed -= new ToolStripDropDownClosedEventHandler(DropDown_Closed); dropDown.ItemClicked -= new ToolStripItemClickedEventHandler(DropDown_ItemClicked); @@ -79,90 +93,104 @@ public ToolStripDropDown DropDown { } dropDown = value; - if (dropDown != null) { + if (dropDown != null) + { dropDown.Opened += new EventHandler(DropDown_Opened); dropDown.Closed += new ToolStripDropDownClosedEventHandler(DropDown_Closed); dropDown.ItemClicked += new ToolStripItemClickedEventHandler(DropDown_ItemClicked); dropDown.AssignToDropDownItem(); } - + } - - + + } } // the area which activates the dropdown. - internal virtual Rectangle DropDownButtonArea { + internal virtual Rectangle DropDownButtonArea + { get { return this.Bounds; } } [Browsable(false)] [SRDescription(nameof(SR.ToolStripDropDownItemDropDownDirectionDescr))] [SRCategory(nameof(SR.CatBehavior))] - public ToolStripDropDownDirection DropDownDirection { - get { - if (toolStripDropDownDirection == ToolStripDropDownDirection.Default) { - ToolStrip parent = ParentInternal; - if (parent != null) { - ToolStripDropDownDirection dropDownDirection = parent.DefaultDropDownDirection; - if (OppositeDropDownAlign || this.RightToLeft != parent.RightToLeft && (this.RightToLeft != RightToLeft.Inherit)) { + public ToolStripDropDownDirection DropDownDirection + { + get + { + if (toolStripDropDownDirection == ToolStripDropDownDirection.Default) + { + ToolStrip parent = ParentInternal; + if (parent != null) + { + ToolStripDropDownDirection dropDownDirection = parent.DefaultDropDownDirection; + if (OppositeDropDownAlign || this.RightToLeft != parent.RightToLeft && (this.RightToLeft != RightToLeft.Inherit)) + { dropDownDirection = RTLTranslateDropDownDirection(dropDownDirection, RightToLeft); - } - - if (IsOnDropDown) { - // we gotta make sure that we dont collide with the existing menu. - Rectangle bounds = GetDropDownBounds(dropDownDirection); - Rectangle ownerItemBounds = new Rectangle(TranslatePoint(Point.Empty, ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ScreenCoords), Size); - Rectangle intersectionBetweenChildAndParent = Rectangle.Intersect(bounds, ownerItemBounds); - - // grab the intersection - if (intersectionBetweenChildAndParent.Width >= 2) { - RightToLeft toggledRightToLeft = (RightToLeft == RightToLeft.Yes) ? RightToLeft.No : RightToLeft.Yes; - ToolStripDropDownDirection newDropDownDirection = RTLTranslateDropDownDirection(dropDownDirection, toggledRightToLeft); - - // verify that changing the dropdown direction actually causes less intersection. - int newIntersectionWidth = Rectangle.Intersect(GetDropDownBounds(newDropDownDirection), ownerItemBounds).Width; - if (newIntersectionWidth < intersectionBetweenChildAndParent.Width) { - dropDownDirection = newDropDownDirection; - } - } - - } - return dropDownDirection; - - } + } + + if (IsOnDropDown) + { + // we gotta make sure that we dont collide with the existing menu. + Rectangle bounds = GetDropDownBounds(dropDownDirection); + Rectangle ownerItemBounds = new Rectangle(TranslatePoint(Point.Empty, ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ScreenCoords), Size); + Rectangle intersectionBetweenChildAndParent = Rectangle.Intersect(bounds, ownerItemBounds); + + // grab the intersection + if (intersectionBetweenChildAndParent.Width >= 2) + { + RightToLeft toggledRightToLeft = (RightToLeft == RightToLeft.Yes) ? RightToLeft.No : RightToLeft.Yes; + ToolStripDropDownDirection newDropDownDirection = RTLTranslateDropDownDirection(dropDownDirection, toggledRightToLeft); + + // verify that changing the dropdown direction actually causes less intersection. + int newIntersectionWidth = Rectangle.Intersect(GetDropDownBounds(newDropDownDirection), ownerItemBounds).Width; + if (newIntersectionWidth < intersectionBetweenChildAndParent.Width) + { + dropDownDirection = newDropDownDirection; + } + } + + } + return dropDownDirection; + + } } // someone has set a custom override - return toolStripDropDownDirection; + return toolStripDropDownDirection; } - set { + set + { // cant use Enum.IsValid as its not sequential - switch (value) { - case ToolStripDropDownDirection.AboveLeft: - case ToolStripDropDownDirection.AboveRight: - case ToolStripDropDownDirection.BelowLeft: - case ToolStripDropDownDirection.BelowRight: - case ToolStripDropDownDirection.Left: - case ToolStripDropDownDirection.Right: - case ToolStripDropDownDirection.Default: - break; - default: - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripDropDownDirection)); + switch (value) + { + case ToolStripDropDownDirection.AboveLeft: + case ToolStripDropDownDirection.AboveRight: + case ToolStripDropDownDirection.BelowLeft: + case ToolStripDropDownDirection.BelowRight: + case ToolStripDropDownDirection.Left: + case ToolStripDropDownDirection.Right: + case ToolStripDropDownDirection.Default: + break; + default: + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripDropDownDirection)); } - if (toolStripDropDownDirection != value) { + if (toolStripDropDownDirection != value) + { toolStripDropDownDirection = value; - if (HasDropDownItems && DropDown.Visible) { + if (HasDropDownItems && DropDown.Visible) + { DropDown.Location = DropDownLocation; } } } } - + /// /// Occurs when the dropdown is closed /// @@ -170,16 +198,19 @@ public ToolStripDropDownDirection DropDownDirection { SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ToolStripDropDownClosedDecr)) ] - public event EventHandler DropDownClosed { + public event EventHandler DropDownClosed + { add => Events.AddHandler(EventDropDownClosed, value); remove => Events.RemoveHandler(EventDropDownClosed, value); } - internal protected virtual Point DropDownLocation + internal protected virtual Point DropDownLocation { - get { - - if (ParentInternal == null || !HasDropDownItems){ + get + { + + if (ParentInternal == null || !HasDropDownItems) + { return Point.Empty; } ToolStripDropDownDirection dropDownDirection = DropDownDirection; @@ -191,10 +222,11 @@ internal protected virtual Point DropDownLocation SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ToolStripDropDownOpeningDescr)) ] - public event EventHandler DropDownOpening { + public event EventHandler DropDownOpening + { add => Events.AddHandler(EventDropDownShow, value); remove => Events.RemoveHandler(EventDropDownShow, value); - } + } /// /// Occurs when the dropdown is opened /// @@ -202,10 +234,11 @@ public event EventHandler DropDownOpening { SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ToolStripDropDownOpenedDescr)) ] - public event EventHandler DropDownOpened { + public event EventHandler DropDownOpened + { add => Events.AddHandler(EventDropDownOpened, value); remove => Events.RemoveHandler(EventDropDownOpened, value); - } + } /// /// Returns the DropDown's items collection. @@ -215,8 +248,10 @@ public event EventHandler DropDownOpened { SRCategory(nameof(SR.CatData)), SRDescription(nameof(SR.ToolStripDropDownItemsDescr)) ] - public ToolStripItemCollection DropDownItems { - get { + public ToolStripItemCollection DropDownItems + { + get + { return DropDown.Items; } } @@ -225,102 +260,120 @@ public ToolStripItemCollection DropDownItems { /// Occurs when the dropdown is opened /// [SRCategory(nameof(SR.CatAction))] - public event ToolStripItemClickedEventHandler DropDownItemClicked { + public event ToolStripItemClickedEventHandler DropDownItemClicked + { add => Events.AddHandler(EventDropDownItemClicked, value); remove => Events.RemoveHandler(EventDropDownItemClicked, value); } [Browsable(false)] - public virtual bool HasDropDownItems { - get { + public virtual bool HasDropDownItems + { + get + { //Use count of visible DisplayedItems instead so that we take into account things that arent visible return (dropDown != null) && dropDown.HasVisibleItems; } } [Browsable(false)] - public bool HasDropDown { + public bool HasDropDown + { get { return dropDown != null; } } [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public override bool Pressed { - get { - // - if (dropDown != null) { - if (DropDown.AutoClose || !IsInDesignMode || (IsInDesignMode && !IsOnDropDown)){ - return DropDown.OwnerItem == this && DropDown.Visible; + public override bool Pressed + { + get + { + // + if (dropDown != null) + { + if (DropDown.AutoClose || !IsInDesignMode || (IsInDesignMode && !IsOnDropDown)) + { + return DropDown.OwnerItem == this && DropDown.Visible; } - } - return base.Pressed; + } + return base.Pressed; } } - internal virtual bool OppositeDropDownAlign { + internal virtual bool OppositeDropDownAlign + { get { return false; } } - internal virtual void AutoHide(ToolStripItem otherItemBeingSelected) { + internal virtual void AutoHide(ToolStripItem otherItemBeingSelected) + { HideDropDown(); } - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new ToolStripDropDownItemAccessibleObject(this); } - protected virtual ToolStripDropDown CreateDefaultDropDown() { + protected virtual ToolStripDropDown CreateDefaultDropDown() + { // AutoGenerate a ToolStrip DropDown - set the property so we hook events - return new ToolStripDropDown(this, true); - } - - private Rectangle DropDownDirectionToDropDownBounds(ToolStripDropDownDirection dropDownDirection, Rectangle dropDownBounds) { - Point offset = Point.Empty; - - switch (dropDownDirection) { - case ToolStripDropDownDirection.AboveLeft: - offset.X = - dropDownBounds.Width + this.Width; - offset.Y = - dropDownBounds.Height+1; - break; - case ToolStripDropDownDirection.AboveRight: - offset.Y = - dropDownBounds.Height+1; - break; - case ToolStripDropDownDirection.BelowRight: - offset.Y = this.Height-1; - break; - case ToolStripDropDownDirection.BelowLeft: - offset.X = - dropDownBounds.Width + this.Width; - offset.Y = this.Height-1; - break; - case ToolStripDropDownDirection.Right: - offset.X = this.Width; - if (!IsOnDropDown) { - // overlap the toplevel toolstrip - offset.X--; - } - break; - - case ToolStripDropDownDirection.Left: - offset.X = - dropDownBounds.Width; - break; - } - - Point itemScreenLocation = this.TranslatePoint(Point.Empty, ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ScreenCoords); - dropDownBounds.Location = new Point(itemScreenLocation.X + offset.X, itemScreenLocation.Y + offset.Y); - dropDownBounds = WindowsFormsUtils.ConstrainToScreenWorkingAreaBounds(dropDownBounds); - return dropDownBounds; - } - - - private void DropDown_Closed(object sender, ToolStripDropDownClosedEventArgs e) { + return new ToolStripDropDown(this, true); + } + + private Rectangle DropDownDirectionToDropDownBounds(ToolStripDropDownDirection dropDownDirection, Rectangle dropDownBounds) + { + Point offset = Point.Empty; + + switch (dropDownDirection) + { + case ToolStripDropDownDirection.AboveLeft: + offset.X = -dropDownBounds.Width + this.Width; + offset.Y = -dropDownBounds.Height + 1; + break; + case ToolStripDropDownDirection.AboveRight: + offset.Y = -dropDownBounds.Height + 1; + break; + case ToolStripDropDownDirection.BelowRight: + offset.Y = this.Height - 1; + break; + case ToolStripDropDownDirection.BelowLeft: + offset.X = -dropDownBounds.Width + this.Width; + offset.Y = this.Height - 1; + break; + case ToolStripDropDownDirection.Right: + offset.X = this.Width; + if (!IsOnDropDown) + { + // overlap the toplevel toolstrip + offset.X--; + } + break; + + case ToolStripDropDownDirection.Left: + offset.X = -dropDownBounds.Width; + break; + } + + Point itemScreenLocation = this.TranslatePoint(Point.Empty, ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ScreenCoords); + dropDownBounds.Location = new Point(itemScreenLocation.X + offset.X, itemScreenLocation.Y + offset.Y); + dropDownBounds = WindowsFormsUtils.ConstrainToScreenWorkingAreaBounds(dropDownBounds); + return dropDownBounds; + } + + + private void DropDown_Closed(object sender, ToolStripDropDownClosedEventArgs e) + { OnDropDownClosed(EventArgs.Empty); } - - private void DropDown_Opened(object sender, EventArgs e) { + + private void DropDown_Opened(object sender, EventArgs e) + { OnDropDownOpened(EventArgs.Empty); } - private void DropDown_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { + private void DropDown_ItemClicked(object sender, ToolStripItemClickedEventArgs e) + { OnDropDownItemClicked(e); } /// @@ -328,12 +381,14 @@ private void DropDown_ItemClicked(object sender, ToolStripItemClickedEventArgs e /// protected override void Dispose(bool disposing) { - if (this.dropDown != null) { + if (this.dropDown != null) + { dropDown.Opened -= new EventHandler(DropDown_Opened); dropDown.Closed -= new ToolStripDropDownClosedEventHandler(DropDown_Closed); dropDown.ItemClicked -= new ToolStripItemClickedEventHandler(DropDown_ItemClicked); - if (disposing && dropDown.IsAutoGenerated) { + if (disposing && dropDown.IsAutoGenerated) + { // if we created the dropdown, dispose it and its children. dropDown.Dispose(); dropDown = null; @@ -343,7 +398,8 @@ protected override void Dispose(bool disposing) } - private Rectangle GetDropDownBounds(ToolStripDropDownDirection dropDownDirection) { + private Rectangle GetDropDownBounds(ToolStripDropDownDirection dropDownDirection) + { Rectangle dropDownBounds = new Rectangle(Point.Empty, DropDown.GetSuggestedSize()); // calculate the offset from the upper left hand corner of the item. @@ -352,17 +408,20 @@ private Rectangle GetDropDownBounds(ToolStripDropDownDirection dropDownDirection // we should make sure we dont obscure the owner item. Rectangle itemScreenBounds = new Rectangle(this.TranslatePoint(Point.Empty, ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ScreenCoords), this.Size); - if (Rectangle.Intersect(dropDownBounds, itemScreenBounds).Height > 1) { + if (Rectangle.Intersect(dropDownBounds, itemScreenBounds).Height > 1) + { bool rtl = (RightToLeft == RightToLeft.Yes); // try positioning to the left - if (Rectangle.Intersect(dropDownBounds, itemScreenBounds).Width > 1) { + if (Rectangle.Intersect(dropDownBounds, itemScreenBounds).Width > 1) + { dropDownBounds = DropDownDirectionToDropDownBounds(!rtl ? ToolStripDropDownDirection.Right : ToolStripDropDownDirection.Left, dropDownBounds); } // try positioning to the right - if (Rectangle.Intersect(dropDownBounds, itemScreenBounds).Width > 1) { + if (Rectangle.Intersect(dropDownBounds, itemScreenBounds).Width > 1) + { dropDownBounds = DropDownDirectionToDropDownBounds(!rtl ? ToolStripDropDownDirection.Left : ToolStripDropDownDirection.Right, dropDownBounds); } } @@ -370,33 +429,38 @@ private Rectangle GetDropDownBounds(ToolStripDropDownDirection dropDownDirection return dropDownBounds; } - - + + /// /// Hides the DropDown, if it is visible. /// - public void HideDropDown() { + public void HideDropDown() + { // consider - CloseEventArgs to prevent shutting down. OnDropDownHide(EventArgs.Empty); - - if (this.dropDown != null && this.dropDown.Visible) { - DropDown.Visible = false; - AccessibilityNotifyClients(AccessibleEvents.StateChange); - AccessibilityNotifyClients(AccessibleEvents.NameChange); - } + if (this.dropDown != null && this.dropDown.Visible) + { + DropDown.Visible = false; + + AccessibilityNotifyClients(AccessibleEvents.StateChange); + AccessibilityNotifyClients(AccessibleEvents.NameChange); + } } - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { base.OnFontChanged(e); - if (dropDown != null) { + if (dropDown != null) + { dropDown.OnOwnerItemFontChanged(EventArgs.Empty); } } - protected override void OnBoundsChanged() { + protected override void OnBoundsChanged() + { base.OnBoundsChanged(); //Reset the Bounds... if (this.dropDown != null && this.dropDown.Visible) @@ -405,14 +469,18 @@ protected override void OnBoundsChanged() { } } - protected override void OnRightToLeftChanged(EventArgs e) { + protected override void OnRightToLeftChanged(EventArgs e) + { base.OnRightToLeftChanged(e); - if (HasDropDownItems) { + if (HasDropDownItems) + { // only perform a layout on a visible dropdown - otherwise clear the preferred size cache. - if (DropDown.Visible) { + if (DropDown.Visible) + { LayoutTransaction.DoLayout(DropDown, this, PropertyNames.RightToLeft); } - else { + else + { CommonProperties.xClearPreferredSizeCache(DropDown); DropDown.LayoutRequired = true; } @@ -420,117 +488,142 @@ protected override void OnRightToLeftChanged(EventArgs e) { } - internal override void OnImageScalingSizeChanged(EventArgs e) { + internal override void OnImageScalingSizeChanged(EventArgs e) + { base.OnImageScalingSizeChanged(e); - if (HasDropDown && DropDown.IsAutoGenerated) { + if (HasDropDown && DropDown.IsAutoGenerated) + { DropDown.DoLayoutIfHandleCreated(new ToolStripItemEventArgs(this)); } } /// /// Called as a response to HideDropDown /// - protected virtual void OnDropDownHide(EventArgs e) { + protected virtual void OnDropDownHide(EventArgs e) + { this.Invalidate(); EventHandler handler = (EventHandler)Events[EventDropDownHide]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// Last chance to stick in the DropDown before it is shown. /// - protected virtual void OnDropDownShow(EventArgs e) { + protected virtual void OnDropDownShow(EventArgs e) + { EventHandler handler = (EventHandler)Events[EventDropDownShow]; - if (handler != null) { + if (handler != null) + { handler(this, e); } } - + /// /// called when the default item is clicked /// - protected internal virtual void OnDropDownOpened(System.EventArgs e) { + protected internal virtual void OnDropDownOpened(System.EventArgs e) + { // only send the event if we're the thing that currently owns the DropDown. - - if (DropDown.OwnerItem == this) { + + if (DropDown.OwnerItem == this) + { EventHandler handler = (EventHandler)Events[EventDropDownOpened]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } } /// /// called when the default item is clicked /// - protected internal virtual void OnDropDownClosed(System.EventArgs e) { + protected internal virtual void OnDropDownClosed(System.EventArgs e) + { // only send the event if we're the thing that currently owns the DropDown. - this.Invalidate(); - - if (DropDown.OwnerItem == this) { + this.Invalidate(); + + if (DropDown.OwnerItem == this) + { EventHandler handler = (EventHandler)Events[EventDropDownClosed]; - if (handler != null) handler(this, e); - - if (!DropDown.IsAutoGenerated) { + if (handler != null) + handler(this, e); + + if (!DropDown.IsAutoGenerated) + { DropDown.OwnerItem = null; } } - + } - + /// /// called when the default item is clicked /// - protected internal virtual void OnDropDownItemClicked(ToolStripItemClickedEventArgs e) { + protected internal virtual void OnDropDownItemClicked(ToolStripItemClickedEventArgs e) + { // only send the event if we're the thing that currently owns the DropDown. - - if (DropDown.OwnerItem == this) { + + if (DropDown.OwnerItem == this) + { ToolStripItemClickedEventHandler handler = (ToolStripItemClickedEventHandler)Events[EventDropDownItemClicked]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } } - - protected internal override bool ProcessCmdKey(ref Message m, Keys keyData) { - if (HasDropDownItems) { + + protected internal override bool ProcessCmdKey(ref Message m, Keys keyData) + { + if (HasDropDownItems) + { return DropDown.ProcessCmdKeyInternal(ref m, keyData); } return base.ProcessCmdKey(ref m, keyData); } - protected internal override bool ProcessDialogKey(Keys keyData) { + protected internal override bool ProcessDialogKey(Keys keyData) + { Keys keyCode = (Keys)keyData & Keys.KeyCode; - if (HasDropDownItems) { + if (HasDropDownItems) + { // Items on the overflow should have the same kind of keyboard handling as a toplevel bool isToplevel = (!IsOnDropDown || IsOnOverflow); - - if (isToplevel && (keyCode == Keys.Down || keyCode == Keys.Up || keyCode == Keys.Enter || (SupportsSpaceKey && keyCode == Keys.Space))) { + + if (isToplevel && (keyCode == Keys.Down || keyCode == Keys.Up || keyCode == Keys.Enter || (SupportsSpaceKey && keyCode == Keys.Space))) + { Debug.WriteLineIf(ToolStrip.SelectionDebug.TraceVerbose, "[SelectDBG ProcessDialogKey] open submenu from toplevel item"); - if (Enabled || DesignMode) { - // |__[ * File ]_____| * is where you are. Up or down arrow hit should expand menu - this.ShowDropDown(); - KeyboardToolTipStateMachine.Instance.NotifyAboutLostFocus(this); - this.DropDown.SelectNextToolStripItem(null, true); + if (Enabled || DesignMode) + { + // |__[ * File ]_____| * is where you are. Up or down arrow hit should expand menu + this.ShowDropDown(); + KeyboardToolTipStateMachine.Instance.NotifyAboutLostFocus(this); + this.DropDown.SelectNextToolStripItem(null, true); }// else eat the key return true; - - } - else if (!isToplevel) { - + + } + else if (!isToplevel) + { + // if we're on a DropDown - then cascade out. bool menusCascadeRight = (((int)DropDownDirection & 0x0001) == 0); bool forward = ((keyCode == Keys.Enter) || (SupportsSpaceKey && keyCode == Keys.Space)); - forward = (forward || (menusCascadeRight && keyCode == Keys.Left) || (!menusCascadeRight && keyCode == Keys.Right)); + forward = (forward || (menusCascadeRight && keyCode == Keys.Left) || (!menusCascadeRight && keyCode == Keys.Right)); - - if (forward) { + + if (forward) + { Debug.WriteLineIf(ToolStrip.SelectionDebug.TraceVerbose, "[SelectDBG ProcessDialogKey] open submenu from NON-toplevel item"); - - if (Enabled || DesignMode) { + + if (Enabled || DesignMode) + { this.ShowDropDown(); KeyboardToolTipStateMachine.Instance.NotifyAboutLostFocus(this); this.DropDown.SelectNextToolStripItem(null, true); @@ -542,87 +635,100 @@ protected internal override bool ProcessDialogKey(Keys keyData) { } - if (IsOnDropDown) { + if (IsOnDropDown) + { bool menusCascadeRight = (((int)DropDownDirection & 0x0001) == 0); - bool backward = ((menusCascadeRight && keyCode == Keys.Right) || (!menusCascadeRight && keyCode == Keys.Left)); - - if (backward) { - - - Debug.WriteLineIf(ToolStrip.SelectionDebug.TraceVerbose, "[SelectDBG ProcessDialogKey] close submenu from NON-toplevel item"); - - // we're on a drop down but we're heading back up the chain. - // remember to select the item that displayed this dropdown. - ToolStripDropDown parent = GetCurrentParentDropDown(); - if (parent != null && !parent.IsFirstDropDown) { - // we're walking back up the dropdown chain. - parent.SetCloseReason(ToolStripDropDownCloseReason.Keyboard); - KeyboardToolTipStateMachine.Instance.NotifyAboutLostFocus(this); - parent.SelectPreviousToolStrip(); - return true; - } - // else if (parent.IsFirstDropDown) - // the base handling (ToolStripDropDown.ProcessArrowKey) will perform auto-expansion of - // the previous item in the menu. - + bool backward = ((menusCascadeRight && keyCode == Keys.Right) || (!menusCascadeRight && keyCode == Keys.Left)); + + if (backward) + { + + + Debug.WriteLineIf(ToolStrip.SelectionDebug.TraceVerbose, "[SelectDBG ProcessDialogKey] close submenu from NON-toplevel item"); + + // we're on a drop down but we're heading back up the chain. + // remember to select the item that displayed this dropdown. + ToolStripDropDown parent = GetCurrentParentDropDown(); + if (parent != null && !parent.IsFirstDropDown) + { + // we're walking back up the dropdown chain. + parent.SetCloseReason(ToolStripDropDownCloseReason.Keyboard); + KeyboardToolTipStateMachine.Instance.NotifyAboutLostFocus(this); + parent.SelectPreviousToolStrip(); + return true; + } + // else if (parent.IsFirstDropDown) + // the base handling (ToolStripDropDown.ProcessArrowKey) will perform auto-expansion of + // the previous item in the menu. + } } Debug.WriteLineIf(ToolStrip.SelectionDebug.TraceVerbose, "[SelectDBG ProcessDialogKey] ddi calling base"); return base.ProcessDialogKey(keyData); - + } - - private ToolStripDropDownDirection RTLTranslateDropDownDirection(ToolStripDropDownDirection dropDownDirection, RightToLeft rightToLeft) { - switch (dropDownDirection) { + + private ToolStripDropDownDirection RTLTranslateDropDownDirection(ToolStripDropDownDirection dropDownDirection, RightToLeft rightToLeft) + { + switch (dropDownDirection) + { case ToolStripDropDownDirection.AboveLeft: - return ToolStripDropDownDirection.AboveRight; - case ToolStripDropDownDirection.AboveRight: - return ToolStripDropDownDirection.AboveLeft; - case ToolStripDropDownDirection.BelowRight: - return ToolStripDropDownDirection.BelowLeft; - case ToolStripDropDownDirection.BelowLeft: - return ToolStripDropDownDirection.BelowRight; - case ToolStripDropDownDirection.Right: - return ToolStripDropDownDirection.Left; - case ToolStripDropDownDirection.Left: - return ToolStripDropDownDirection.Right; - } - Debug.Fail("Why are we here"); - - // dont expect it to come to this but just in case here are the real defaults. - if (IsOnDropDown) { - return (rightToLeft == RightToLeft.Yes) ? ToolStripDropDownDirection.Left : ToolStripDropDownDirection.Right; - } - else { - return (rightToLeft == RightToLeft.Yes) ? ToolStripDropDownDirection.BelowLeft : ToolStripDropDownDirection.BelowRight; - } - - - } - + return ToolStripDropDownDirection.AboveRight; + case ToolStripDropDownDirection.AboveRight: + return ToolStripDropDownDirection.AboveLeft; + case ToolStripDropDownDirection.BelowRight: + return ToolStripDropDownDirection.BelowLeft; + case ToolStripDropDownDirection.BelowLeft: + return ToolStripDropDownDirection.BelowRight; + case ToolStripDropDownDirection.Right: + return ToolStripDropDownDirection.Left; + case ToolStripDropDownDirection.Left: + return ToolStripDropDownDirection.Right; + } + Debug.Fail("Why are we here"); + + // dont expect it to come to this but just in case here are the real defaults. + if (IsOnDropDown) + { + return (rightToLeft == RightToLeft.Yes) ? ToolStripDropDownDirection.Left : ToolStripDropDownDirection.Right; + } + else + { + return (rightToLeft == RightToLeft.Yes) ? ToolStripDropDownDirection.BelowLeft : ToolStripDropDownDirection.BelowRight; + } + + + } + /// /// Shows the DropDown, if one is set. /// - public void ShowDropDown() { + public void ShowDropDown() + { this.ShowDropDown(false); } - internal void ShowDropDown(bool mousePush) { + internal void ShowDropDown(bool mousePush) + { this.ShowDropDownInternal(); ToolStripDropDownMenu menu = this.dropDown as ToolStripDropDownMenu; - if (menu != null) { - if (!mousePush) { + if (menu != null) + { + if (!mousePush) + { menu.ResetScrollPosition(); } menu.RestoreScrollPosition(); } } - private void ShowDropDownInternal() { + private void ShowDropDownInternal() + { - if (this.dropDown == null || (!this.dropDown.Visible)) { + if (this.dropDown == null || (!this.dropDown.Visible)) + { // We want to show if there's no dropdown // or if the dropdown is not visible. OnDropDownShow(EventArgs.Empty); @@ -631,13 +737,16 @@ private void ShowDropDownInternal() { // the act of setting the drop down visible the first time sets the parent // it seems that GetVisibleCore returns true if your parent is null. - if (this.dropDown != null && !this.dropDown.Visible) { + if (this.dropDown != null && !this.dropDown.Visible) + { - if (this.dropDown.IsAutoGenerated && this.DropDownItems.Count <= 0) { + if (this.dropDown.IsAutoGenerated && this.DropDownItems.Count <= 0) + { return; // this is a no-op for autogenerated drop downs. } - if (this.DropDown == this.ParentInternal) { + if (this.DropDown == this.ParentInternal) + { throw new InvalidOperationException(SR.ToolStripShowDropDownInvalidOperation); } @@ -651,132 +760,168 @@ private void ShowDropDownInternal() { } } - private bool ShouldSerializeDropDown() { + private bool ShouldSerializeDropDown() + { return dropDown != null && !dropDown.IsAutoGenerated; } - private bool ShouldSerializeDropDownDirection() { + private bool ShouldSerializeDropDownDirection() + { return (toolStripDropDownDirection != ToolStripDropDownDirection.Default); } - private bool ShouldSerializeDropDownItems() { + private bool ShouldSerializeDropDownItems() + { return (dropDown != null && dropDown.IsAutoGenerated); } - internal override void OnKeyboardToolTipHook(ToolTip toolTip) { + internal override void OnKeyboardToolTipHook(ToolTip toolTip) + { base.OnKeyboardToolTipHook(toolTip); KeyboardToolTipStateMachine.Instance.Hook(this.DropDown, toolTip); } - internal override void OnKeyboardToolTipUnhook(ToolTip toolTip) { + internal override void OnKeyboardToolTipUnhook(ToolTip toolTip) + { base.OnKeyboardToolTipUnhook(toolTip); KeyboardToolTipStateMachine.Instance.Unhook(this.DropDown, toolTip); } } - + [System.Runtime.InteropServices.ComVisible(true)] - public class ToolStripDropDownItemAccessibleObject : ToolStripItem.ToolStripItemAccessibleObject { + public class ToolStripDropDownItemAccessibleObject : ToolStripItem.ToolStripItemAccessibleObject + { private ToolStripDropDownItem owner; - public ToolStripDropDownItemAccessibleObject(ToolStripDropDownItem item) : base(item) { + public ToolStripDropDownItemAccessibleObject(ToolStripDropDownItem item) : base(item) + { owner = item; } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { AccessibleRole role = Owner.AccessibleRole; - if (role != AccessibleRole.Default) { + if (role != AccessibleRole.Default) + { return role; } return AccessibleRole.MenuItem; } } - public override void DoDefaultAction() { + public override void DoDefaultAction() + { ToolStripDropDownItem item = Owner as ToolStripDropDownItem; - if (item != null && item.HasDropDownItems) { + if (item != null && item.HasDropDownItems) + { item.ShowDropDown(); } - else { + else + { base.DoDefaultAction(); } } - internal override bool IsIAccessibleExSupported() { - if (owner != null) { + internal override bool IsIAccessibleExSupported() + { + if (owner != null) + { return true; } - else { + else + { return base.IsIAccessibleExSupported(); } } - internal override bool IsPatternSupported(int patternId) { - if (patternId == NativeMethods.UIA_ExpandCollapsePatternId && owner.HasDropDownItems) { + internal override bool IsPatternSupported(int patternId) + { + if (patternId == NativeMethods.UIA_ExpandCollapsePatternId && owner.HasDropDownItems) + { return true; } - else { + else + { return base.IsPatternSupported(patternId); } } - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_IsOffscreenPropertyId && owner != null && owner.Owner is ToolStripDropDown) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_IsOffscreenPropertyId && owner != null && owner.Owner is ToolStripDropDown) + { return !((ToolStripDropDown)owner.Owner).Visible; } return base.GetPropertyValue(propertyID); } - internal override void Expand() { - DoDefaultAction(); + internal override void Expand() + { + DoDefaultAction(); } - internal override void Collapse() { - if (owner != null && owner.DropDown != null && owner.DropDown.Visible) { + internal override void Collapse() + { + if (owner != null && owner.DropDown != null && owner.DropDown.Visible) + { owner.DropDown.Close(); - } + } } - internal override UnsafeNativeMethods.ExpandCollapseState ExpandCollapseState { - get { - return owner.DropDown.Visible ? UnsafeNativeMethods.ExpandCollapseState.Expanded : UnsafeNativeMethods.ExpandCollapseState.Collapsed; + internal override UnsafeNativeMethods.ExpandCollapseState ExpandCollapseState + { + get + { + return owner.DropDown.Visible ? UnsafeNativeMethods.ExpandCollapseState.Expanded : UnsafeNativeMethods.ExpandCollapseState.Collapsed; } } - public override AccessibleObject GetChild(int index) { - if ((owner == null) || !owner.HasDropDownItems) { + public override AccessibleObject GetChild(int index) + { + if ((owner == null) || !owner.HasDropDownItems) + { return null; } return owner.DropDown.AccessibilityObject.GetChild(index); - + } - public override int GetChildCount() { - if ((owner == null) || !owner.HasDropDownItems) { + public override int GetChildCount() + { + if ((owner == null) || !owner.HasDropDownItems) + { return -1; } // Do not expose child items when the submenu is collapsed to prevent Narrator from announcing // invisible menu items when Narrator is in item's mode (CAPSLOCK + Arrow Left/Right) or // in scan mode (CAPSLOCK + Space) - if (ExpandCollapseState == UnsafeNativeMethods.ExpandCollapseState.Collapsed) { + if (ExpandCollapseState == UnsafeNativeMethods.ExpandCollapseState.Collapsed) + { return 0; } - if (owner.DropDown.LayoutRequired) { + if (owner.DropDown.LayoutRequired) + { LayoutTransaction.DoLayout(owner.DropDown, owner.DropDown, PropertyNames.Items); } return owner.DropDown.AccessibilityObject.GetChildCount(); } - internal int GetChildFragmentIndex(ToolStripItem.ToolStripItemAccessibleObject child) { - if ((owner == null) || (owner.DropDownItems == null)) { + internal int GetChildFragmentIndex(ToolStripItem.ToolStripItemAccessibleObject child) + { + if ((owner == null) || (owner.DropDownItems == null)) + { return -1; } - for (int i = 0; i < owner.DropDownItems.Count; i++) { - if (owner.DropDownItems[i].Available && child.Owner == owner.DropDownItems[i]) { + for (int i = 0; i < owner.DropDownItems.Count; i++) + { + if (owner.DropDownItems[i].Available && child.Owner == owner.DropDownItems[i]) + { return i; } } @@ -788,14 +933,18 @@ internal int GetChildFragmentIndex(ToolStripItem.ToolStripItemAccessibleObject c /// Gets the number of children belonging to an accessible object. /// /// The number of children. - internal int GetChildFragmentCount() { - if ((owner == null) || (owner.DropDownItems == null)) { + internal int GetChildFragmentCount() + { + if ((owner == null) || (owner.DropDownItems == null)) + { return -1; } int count = 0; - for (int i = 0; i < owner.DropDownItems.Count; i++) { - if (owner.DropDownItems[i].Available) { + for (int i = 0; i < owner.DropDownItems.Count; i++) + { + if (owner.DropDownItems[i].Available) + { count++; } } @@ -803,31 +952,38 @@ internal int GetChildFragmentCount() { return count; } - internal AccessibleObject GetChildFragment(int index) { + internal AccessibleObject GetChildFragment(int index) + { var toolStripAccessibleObject = owner.DropDown.AccessibilityObject as ToolStrip.ToolStripAccessibleObject; - if (toolStripAccessibleObject != null) { + if (toolStripAccessibleObject != null) + { return toolStripAccessibleObject.GetChildFragment(index); } return null; } - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - if (owner == null || owner.DropDown == null) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { + if (owner == null || owner.DropDown == null) + { return null; } - switch (direction) { + switch (direction) + { case UnsafeNativeMethods.NavigateDirection.FirstChild: int childCount = GetChildCount(); - if (childCount > 0) { + if (childCount > 0) + { return GetChildFragment(0); } return null; case UnsafeNativeMethods.NavigateDirection.LastChild: childCount = GetChildCount(); - if (childCount > 0) { + if (childCount > 0) + { return GetChildFragment(childCount - 1); } @@ -836,22 +992,26 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga case UnsafeNativeMethods.NavigateDirection.PreviousSibling: ToolStripDropDown dropDown = owner.Owner as ToolStripDropDown; - if (dropDown == null) { + if (dropDown == null) + { break; } int index = dropDown.Items.IndexOf(owner); - if (index == -1) { + if (index == -1) + { Debug.Fail("No item matched the index?"); return null; } index += direction == UnsafeNativeMethods.NavigateDirection.NextSibling ? 1 : -1; - if (index >= 0 && index < dropDown.Items.Count) { + if (index >= 0 && index < dropDown.Items.Count) + { var item = dropDown.Items[index]; var controlHostItem = item as ToolStripControlHost; - if (controlHostItem != null) { + if (controlHostItem != null) + { return controlHostItem.ControlAccessibilityObject; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownMenu.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownMenu.cs index d8cb970e671..dcb74056dc6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownMenu.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownMenu.cs @@ -17,792 +17,923 @@ namespace System.Windows.Forms [ClassInterface(ClassInterfaceType.AutoDispatch)] public class ToolStripDropDownMenu : ToolStripDropDown { - private static readonly Padding ImagePadding = new Padding(2); - private static readonly Padding TextPadding = new Padding(8,1,9,1); - private static readonly Padding CheckPadding = new Padding(5,2,2,2); - private static readonly Padding ArrowPadding = new Padding(0,0,8,0); - - // This is totally a UI Fudge - if we have an image or check margin with - // no image or checks in it use this - which is consistent with office - // and an image margin with a 16x16 icon in it. - private static int DefaultImageMarginWidth = 24; // 24+1px border - with scaling we add this 1px to new, scaled, field value - private static int DefaultImageAndCheckMarginWidth = 46; // 46+1px border - with scaling we add this 1px to new, scaled, field value - - private static int ArrowSize = 10; - - private Size maxItemSize = Size.Empty; - private Rectangle checkRectangle = Rectangle.Empty; - private Rectangle imageRectangle = Rectangle.Empty; - private Rectangle arrowRectangle = Rectangle.Empty; - private Rectangle textRectangle = Rectangle.Empty; - private Rectangle imageMarginBounds = Rectangle.Empty; - private int paddingToTrim = 0; - private int tabWidth = -1; - - private ToolStripScrollButton upScrollButton = null; - private ToolStripScrollButton downScrollButton = null; - private int scrollAmount = 0; - private int indexOfFirstDisplayedItem = -1; - - private BitVector32 state = new BitVector32(); - - private static readonly int stateShowImageMargin = BitVector32.CreateMask(); - private static readonly int stateShowCheckMargin = BitVector32.CreateMask(stateShowImageMargin); - private static readonly int stateMaxItemSizeValid = BitVector32.CreateMask(stateShowCheckMargin); - - private static readonly Size DefaultImageSize = new Size(16, 16); - - private Size scaledDefaultImageSize = DefaultImageSize; - private int scaledDefaultImageMarginWidth = DefaultImageMarginWidth + 1; // 1px for border - private int scaledDefaultImageAndCheckMarginWidth = DefaultImageAndCheckMarginWidth + 1; // 1px for border - private Padding scaledImagePadding = ImagePadding; - private Padding scaledTextPadding = TextPadding; - private Padding scaledCheckPadding = CheckPadding; - private Padding scaledArrowPadding = ArrowPadding; - private int scaledArrowSize = ArrowSize; - - /// - /// Summary of ToolStripDropDown. - /// - public ToolStripDropDownMenu(){ - } - - /// - /// Constructor to autogenerate - /// - internal ToolStripDropDownMenu(ToolStripItem ownerItem, bool isAutoGenerated) : base(ownerItem,isAutoGenerated) { - if (DpiHelper.IsScalingRequired) { - scaledDefaultImageSize = DpiHelper.LogicalToDeviceUnits(DefaultImageSize); - scaledDefaultImageMarginWidth = DpiHelper.LogicalToDeviceUnitsX(DefaultImageMarginWidth) + 1; // 1px for border - scaledDefaultImageAndCheckMarginWidth = DpiHelper.LogicalToDeviceUnitsX(DefaultImageAndCheckMarginWidth) + 1; // 1px for border - scaledImagePadding = DpiHelper.LogicalToDeviceUnits(ImagePadding); - scaledTextPadding = DpiHelper.LogicalToDeviceUnits(TextPadding); - scaledCheckPadding = DpiHelper.LogicalToDeviceUnits(CheckPadding); - scaledArrowPadding = DpiHelper.LogicalToDeviceUnits(ArrowPadding); - scaledArrowSize = DpiHelper.LogicalToDeviceUnitsX(ArrowSize); + private static readonly Padding ImagePadding = new Padding(2); + private static readonly Padding TextPadding = new Padding(8, 1, 9, 1); + private static readonly Padding CheckPadding = new Padding(5, 2, 2, 2); + private static readonly Padding ArrowPadding = new Padding(0, 0, 8, 0); + + // This is totally a UI Fudge - if we have an image or check margin with + // no image or checks in it use this - which is consistent with office + // and an image margin with a 16x16 icon in it. + private static int DefaultImageMarginWidth = 24; // 24+1px border - with scaling we add this 1px to new, scaled, field value + private static int DefaultImageAndCheckMarginWidth = 46; // 46+1px border - with scaling we add this 1px to new, scaled, field value + + private static int ArrowSize = 10; + + private Size maxItemSize = Size.Empty; + private Rectangle checkRectangle = Rectangle.Empty; + private Rectangle imageRectangle = Rectangle.Empty; + private Rectangle arrowRectangle = Rectangle.Empty; + private Rectangle textRectangle = Rectangle.Empty; + private Rectangle imageMarginBounds = Rectangle.Empty; + private int paddingToTrim = 0; + private int tabWidth = -1; + + private ToolStripScrollButton upScrollButton = null; + private ToolStripScrollButton downScrollButton = null; + private int scrollAmount = 0; + private int indexOfFirstDisplayedItem = -1; + + private BitVector32 state = new BitVector32(); + + private static readonly int stateShowImageMargin = BitVector32.CreateMask(); + private static readonly int stateShowCheckMargin = BitVector32.CreateMask(stateShowImageMargin); + private static readonly int stateMaxItemSizeValid = BitVector32.CreateMask(stateShowCheckMargin); + + private static readonly Size DefaultImageSize = new Size(16, 16); + + private Size scaledDefaultImageSize = DefaultImageSize; + private int scaledDefaultImageMarginWidth = DefaultImageMarginWidth + 1; // 1px for border + private int scaledDefaultImageAndCheckMarginWidth = DefaultImageAndCheckMarginWidth + 1; // 1px for border + private Padding scaledImagePadding = ImagePadding; + private Padding scaledTextPadding = TextPadding; + private Padding scaledCheckPadding = CheckPadding; + private Padding scaledArrowPadding = ArrowPadding; + private int scaledArrowSize = ArrowSize; + + /// + /// Summary of ToolStripDropDown. + /// + public ToolStripDropDownMenu() + { + } + + /// + /// Constructor to autogenerate + /// + internal ToolStripDropDownMenu(ToolStripItem ownerItem, bool isAutoGenerated) : base(ownerItem, isAutoGenerated) + { + if (DpiHelper.IsScalingRequired) + { + scaledDefaultImageSize = DpiHelper.LogicalToDeviceUnits(DefaultImageSize); + scaledDefaultImageMarginWidth = DpiHelper.LogicalToDeviceUnitsX(DefaultImageMarginWidth) + 1; // 1px for border + scaledDefaultImageAndCheckMarginWidth = DpiHelper.LogicalToDeviceUnitsX(DefaultImageAndCheckMarginWidth) + 1; // 1px for border + scaledImagePadding = DpiHelper.LogicalToDeviceUnits(ImagePadding); + scaledTextPadding = DpiHelper.LogicalToDeviceUnits(TextPadding); + scaledCheckPadding = DpiHelper.LogicalToDeviceUnits(CheckPadding); + scaledArrowPadding = DpiHelper.LogicalToDeviceUnits(ArrowPadding); + scaledArrowSize = DpiHelper.LogicalToDeviceUnitsX(ArrowSize); + } + } + + internal override bool AllItemsVisible + { + get + { + return !RequiresScrollButtons; + } + set + { + RequiresScrollButtons = !value; + } + } + + internal Rectangle ArrowRectangle + { + get + { + return arrowRectangle; + } + } + + internal Rectangle CheckRectangle + { + get + { + return checkRectangle; + } + } + + protected override Padding DefaultPadding + { + get + { + RightToLeft rightToLeft = RightToLeft; + + int textPadding = (rightToLeft == RightToLeft.Yes) ? scaledTextPadding.Right : scaledTextPadding.Left; + int padding = (ShowCheckMargin || ShowImageMargin) ? textPadding + ImageMargin.Width : textPadding; + + // scooch in all the items by the margin. + if (rightToLeft == RightToLeft.Yes) + { + return new Padding(1, 2, padding, 2); } + return new Padding(padding, 2, 1, 2); } + } - internal override bool AllItemsVisible { - get { - return !RequiresScrollButtons; - } - set { - RequiresScrollButtons = !value; + public override Rectangle DisplayRectangle + { + get + { + Rectangle rect = base.DisplayRectangle; + if (GetToolStripState(STATE_SCROLLBUTTONS)) + { + + rect.Y += UpScrollButton.Height + UpScrollButton.Margin.Vertical; + rect.Height -= UpScrollButton.Height + UpScrollButton.Margin.Vertical + DownScrollButton.Height + DownScrollButton.Margin.Vertical; + // Because we're going to draw the scroll buttons on top of the padding, we need to add it back in here. + rect = LayoutUtils.InflateRect(rect, new Padding(0, this.Padding.Top, 0, this.Padding.Bottom)); } + return rect; } + } - internal Rectangle ArrowRectangle { - get { - return arrowRectangle; + private ToolStripScrollButton DownScrollButton + { + get + { + if (downScrollButton == null) + { + downScrollButton = new ToolStripScrollButton(false); + downScrollButton.ParentInternal = this; + } + return downScrollButton; + } + } + /// + /// the rectangle representing + /// + internal Rectangle ImageRectangle + { + get + { + return imageRectangle; + } + } + + internal int PaddingToTrim + { + get + { + return paddingToTrim; + } + set + { + if (paddingToTrim != value) + { + paddingToTrim = value; + AdjustSize(); + } + + } + } + + /// + /// the rectangle representing the color stripe in the menu - this will appear as AffectedBounds + /// in the ToolStripRenderEventArgs + /// + internal Rectangle ImageMargin + { + get + { + imageMarginBounds.Height = this.Height; + return imageMarginBounds; + } + } + + public override LayoutEngine LayoutEngine + { + get + { + return ToolStripDropDownLayoutEngine.LayoutInstance; + } + } + + [ + DefaultValue(ToolStripLayoutStyle.Flow) + ] + public new ToolStripLayoutStyle LayoutStyle + { + get { return base.LayoutStyle; } + set { base.LayoutStyle = value; } + } + + protected internal override Size MaxItemSize + { + get + { + if (!state[stateMaxItemSizeValid]) + { + CalculateInternalLayoutMetrics(); } + return maxItemSize; } - - internal Rectangle CheckRectangle { - get { - return checkRectangle; - } + } + + [ + DefaultValue(true), + SRDescription(nameof(SR.ToolStripDropDownMenuShowImageMarginDescr)), + SRCategory(nameof(SR.CatAppearance)) + ] + public bool ShowImageMargin + { + get + { + return state[stateShowImageMargin]; } - - protected override Padding DefaultPadding { - get { - RightToLeft rightToLeft = RightToLeft; - - int textPadding = (rightToLeft == RightToLeft.Yes) ? scaledTextPadding.Right : scaledTextPadding.Left; - int padding = (ShowCheckMargin || ShowImageMargin) ? textPadding + ImageMargin.Width : textPadding; - - // scooch in all the items by the margin. - if (rightToLeft == RightToLeft.Yes) { - return new Padding(1,2,padding,2); - } - return new Padding(padding,2,1,2); + set + { + if (value != state[stateShowImageMargin]) + { + state[stateShowImageMargin] = value; + LayoutTransaction.DoLayout(this, this, PropertyNames.ShowImageMargin); + } + } + } + + [ + DefaultValue(false), + SRDescription(nameof(SR.ToolStripDropDownMenuShowCheckMarginDescr)), + SRCategory(nameof(SR.CatAppearance)) + ] + public bool ShowCheckMargin + { + get + { + return state[stateShowCheckMargin]; + } + set + { + if (value != state[stateShowCheckMargin]) + { + state[stateShowCheckMargin] = value; + LayoutTransaction.DoLayout(this, this, PropertyNames.ShowCheckMargin); } } + } - public override Rectangle DisplayRectangle { - get { - Rectangle rect = base.DisplayRectangle; - if (GetToolStripState(STATE_SCROLLBUTTONS)) { - rect.Y += UpScrollButton.Height + UpScrollButton.Margin.Vertical; - rect.Height -= UpScrollButton.Height + UpScrollButton.Margin.Vertical + DownScrollButton.Height + DownScrollButton.Margin.Vertical; - // Because we're going to draw the scroll buttons on top of the padding, we need to add it back in here. - rect = LayoutUtils.InflateRect(rect, new Padding(0, this.Padding.Top, 0, this.Padding.Bottom)); - } - return rect; - } + internal Rectangle TextRectangle + { + get + { + return textRectangle; } + } - private ToolStripScrollButton DownScrollButton { - get { - if (downScrollButton == null) { - downScrollButton = new ToolStripScrollButton(false); - downScrollButton.ParentInternal = this; - } - return downScrollButton; - } - } - /// - /// the rectangle representing - /// - internal Rectangle ImageRectangle { - get { - return imageRectangle; + private ToolStripScrollButton UpScrollButton + { + get + { + if (upScrollButton == null) + { + upScrollButton = new ToolStripScrollButton(true); + upScrollButton.ParentInternal = this; } + return upScrollButton; } + } + + /// this takes a native menu and builds up a managed toolstrip around it. + /// Scenario: showing the items from the SystemMenu. + /// targetWindow is the window to send WM_COMMAND, WM_SYSCOMMAND to + /// hmenu is a handle to the native menu + /// + /// + + internal static ToolStripDropDownMenu FromHMenu(IntPtr hmenu, IWin32Window targetWindow) + { + ToolStripDropDownMenu managedDropDown = new ToolStripDropDownMenu(); + managedDropDown.SuspendLayout(); + + + HandleRef menuHandle = new HandleRef(null, hmenu); + int count = UnsafeNativeMethods.GetMenuItemCount(menuHandle); - internal int PaddingToTrim { - get { - return paddingToTrim; + ToolStripItem itemToAdd; + + // surf through the items in the collection, building up TSMenuItems and TSSeparators + // corresponding to the native menu. + for (int i = 0; i < count; i++) + { + // peek at the i'th item. + NativeMethods.MENUITEMINFO_T_RW info = new NativeMethods.MENUITEMINFO_T_RW(); + info.cbSize = Marshal.SizeOf(); + info.fMask = NativeMethods.MIIM_FTYPE; + info.fType = NativeMethods.MIIM_FTYPE; + UnsafeNativeMethods.GetMenuItemInfo(menuHandle, i, /*fByPosition=*/ true, info); + + if (info.fType == NativeMethods.MFT_SEPARATOR) + { + // its a separator. + itemToAdd = new ToolStripSeparator(); } - set { - if (paddingToTrim != value) { - paddingToTrim = value; - AdjustSize(); + else + { + // its a menu item... lets fish out the command id + info = new NativeMethods.MENUITEMINFO_T_RW(); + info.cbSize = Marshal.SizeOf(); + info.fMask = NativeMethods.MIIM_ID; + info.fType = NativeMethods.MIIM_ID; + UnsafeNativeMethods.GetMenuItemInfo(menuHandle, i, /*fByPosition=*/ true, info); + + // create the managed object - toolstripmenu item knows how to grok hmenu for information. + itemToAdd = new ToolStripMenuItem(hmenu, info.wID, targetWindow); + + + // if there is a submenu fetch it. + info = new NativeMethods.MENUITEMINFO_T_RW(); + info.cbSize = Marshal.SizeOf(); + info.fMask = NativeMethods.MIIM_SUBMENU; + info.fType = NativeMethods.MIIM_SUBMENU; + UnsafeNativeMethods.GetMenuItemInfo(menuHandle, i, /*fByPosition=*/ true, info); + + if (info.hSubMenu != IntPtr.Zero) + { + // set the dropdown to be the items from the submenu + ((ToolStripMenuItem)itemToAdd).DropDown = FromHMenu(info.hSubMenu, targetWindow); } - } - } - - /// - /// the rectangle representing the color stripe in the menu - this will appear as AffectedBounds - /// in the ToolStripRenderEventArgs - /// - internal Rectangle ImageMargin { - get { - imageMarginBounds.Height =this.Height; - return imageMarginBounds; - } - } - - public override LayoutEngine LayoutEngine { - get { - return ToolStripDropDownLayoutEngine.LayoutInstance; - } - } - [ - DefaultValue(ToolStripLayoutStyle.Flow) - ] - public new ToolStripLayoutStyle LayoutStyle { - get { return base.LayoutStyle; } - set { base.LayoutStyle = value; } + managedDropDown.Items.Add(itemToAdd); } + managedDropDown.ResumeLayout(); + return managedDropDown; + } + + [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] // using "\t" to figure out the width of tab + private void CalculateInternalLayoutMetrics() + { + + + Size maxTextSize = Size.Empty; + Size maxImageSize = Size.Empty; + Size maxCheckSize = scaledDefaultImageSize; + Size maxArrowSize = Size.Empty; + Size maxNonMenuItemSize = Size.Empty; + + // determine Text Metrics + for (int i = 0; i < Items.Count; i++) + { + ToolStripItem item = Items[i]; + ToolStripMenuItem menuItem = item as ToolStripMenuItem; + + if (menuItem != null) + { - protected internal override Size MaxItemSize { - get { - if (!state[stateMaxItemSizeValid]) { - CalculateInternalLayoutMetrics(); + Size menuItemTextSize = menuItem.GetTextSize(); + + if (menuItem.ShowShortcutKeys) + { + Size shortcutTextSize = menuItem.GetShortcutTextSize(); + if (tabWidth == -1) + { + tabWidth = TextRenderer.MeasureText("\t", this.Font).Width; + } + menuItemTextSize.Width += tabWidth + shortcutTextSize.Width; + menuItemTextSize.Height = Math.Max(menuItemTextSize.Height, shortcutTextSize.Height); } - return maxItemSize; - } - } - - [ - DefaultValue(true), - SRDescription(nameof(SR.ToolStripDropDownMenuShowImageMarginDescr)), - SRCategory(nameof(SR.CatAppearance)) - ] - public bool ShowImageMargin { - get { - return state[stateShowImageMargin]; - } - set { - if (value != state[stateShowImageMargin]) { - state[stateShowImageMargin] = value; - LayoutTransaction.DoLayout(this, this, PropertyNames.ShowImageMargin); + + // we truly only care about the maximum size we find. + maxTextSize.Width = Math.Max(maxTextSize.Width, menuItemTextSize.Width); + maxTextSize.Height = Math.Max(maxTextSize.Height, menuItemTextSize.Height); + + // determine Image Metrics + Size imageSize = Size.Empty; + if (menuItem.Image != null) + { + imageSize = (menuItem.ImageScaling == ToolStripItemImageScaling.SizeToFit) ? ImageScalingSize : menuItem.Image.Size; } - } - } - [ - DefaultValue(false), - SRDescription(nameof(SR.ToolStripDropDownMenuShowCheckMarginDescr)), - SRCategory(nameof(SR.CatAppearance)) - ] - public bool ShowCheckMargin { - get { - return state[stateShowCheckMargin]; - } - set { - if (value != state[stateShowCheckMargin]) { - state[stateShowCheckMargin] = value; - LayoutTransaction.DoLayout(this, this, PropertyNames.ShowCheckMargin); + maxImageSize.Width = Math.Max(maxImageSize.Width, imageSize.Width); + maxImageSize.Height = Math.Max(maxImageSize.Height, imageSize.Height); + + if (menuItem.CheckedImage != null) + { + Size checkedImageSize = menuItem.CheckedImage.Size; + maxCheckSize.Width = Math.Max(checkedImageSize.Width, maxCheckSize.Width); + maxCheckSize.Height = Math.Max(checkedImageSize.Height, maxCheckSize.Height); } } - } - - - internal Rectangle TextRectangle { - get { - return textRectangle; + else if (!(item is ToolStripSeparator)) + { + maxNonMenuItemSize.Height = Math.Max(item.Bounds.Height, maxNonMenuItemSize.Height); + maxNonMenuItemSize.Width = Math.Max(item.Bounds.Width, maxNonMenuItemSize.Width); } } - private ToolStripScrollButton UpScrollButton { - get { - if (upScrollButton == null) { - upScrollButton = new ToolStripScrollButton(true); - upScrollButton.ParentInternal = this; - } - return upScrollButton; - } + this.maxItemSize.Height = Math.Max(maxTextSize.Height + scaledTextPadding.Vertical, Math.Max(maxCheckSize.Height + scaledCheckPadding.Vertical, maxArrowSize.Height + scaledArrowPadding.Vertical)); + + if (ShowImageMargin) + { + // only add in the image into the calculation if we're going to render it. + this.maxItemSize.Height = Math.Max(maxImageSize.Height + scaledImagePadding.Vertical, maxItemSize.Height); } - /// this takes a native menu and builds up a managed toolstrip around it. - /// Scenario: showing the items from the SystemMenu. - /// targetWindow is the window to send WM_COMMAND, WM_SYSCOMMAND to - /// hmenu is a handle to the native menu - /// - /// + bool useDefaultCheckMarginWidth = (ShowCheckMargin && (maxCheckSize.Width == 0)); + bool useDefaultImageMarginWidth = (ShowImageMargin && (maxImageSize.Width == 0)); + // Always save space for an arrow + maxArrowSize = new Size(scaledArrowSize, maxItemSize.Height); - internal static ToolStripDropDownMenu FromHMenu(IntPtr hmenu, IWin32Window targetWindow) { - ToolStripDropDownMenu managedDropDown = new ToolStripDropDownMenu(); - managedDropDown.SuspendLayout(); - + maxTextSize.Height = maxItemSize.Height - scaledTextPadding.Vertical; + maxImageSize.Height = maxItemSize.Height - scaledImagePadding.Vertical; + maxCheckSize.Height = maxItemSize.Height - scaledCheckPadding.Vertical; - HandleRef menuHandle = new HandleRef(null, hmenu); - int count = UnsafeNativeMethods.GetMenuItemCount(menuHandle); + // fixup if there are non-menu items that are larger than our normal menu items + maxTextSize.Width = Math.Max(maxTextSize.Width, maxNonMenuItemSize.Width); - ToolStripItem itemToAdd; + Point nextPoint = Point.Empty; + int checkAndImageMarginWidth = 0; - // surf through the items in the collection, building up TSMenuItems and TSSeparators - // corresponding to the native menu. - for (int i = 0; i < count; i++) { - // peek at the i'th item. - NativeMethods.MENUITEMINFO_T_RW info = new NativeMethods.MENUITEMINFO_T_RW(); - info.cbSize = Marshal.SizeOf(); - info.fMask = NativeMethods.MIIM_FTYPE; - info.fType = NativeMethods.MIIM_FTYPE; - UnsafeNativeMethods.GetMenuItemInfo(menuHandle, i, /*fByPosition=*/ true, info); - - if (info.fType == NativeMethods.MFT_SEPARATOR){ - // its a separator. - itemToAdd = new ToolStripSeparator(); - } - else { - // its a menu item... lets fish out the command id - info = new NativeMethods.MENUITEMINFO_T_RW(); - info.cbSize = Marshal.SizeOf(); - info.fMask = NativeMethods.MIIM_ID; - info.fType = NativeMethods.MIIM_ID; - UnsafeNativeMethods.GetMenuItemInfo(menuHandle, i, /*fByPosition=*/ true, info); - - // create the managed object - toolstripmenu item knows how to grok hmenu for information. - itemToAdd = new ToolStripMenuItem(hmenu, info.wID, targetWindow); - - - // if there is a submenu fetch it. - info = new NativeMethods.MENUITEMINFO_T_RW(); - info.cbSize = Marshal.SizeOf(); - info.fMask = NativeMethods.MIIM_SUBMENU; - info.fType = NativeMethods.MIIM_SUBMENU; - UnsafeNativeMethods.GetMenuItemInfo(menuHandle, i, /*fByPosition=*/ true, info); - - if (info.hSubMenu != IntPtr.Zero) { - // set the dropdown to be the items from the submenu - ((ToolStripMenuItem)itemToAdd).DropDown = FromHMenu(info.hSubMenu, targetWindow); - } - } + int extraImageWidth = Math.Max(0, maxImageSize.Width - scaledDefaultImageSize.Width); - managedDropDown.Items.Add(itemToAdd); - } - managedDropDown.ResumeLayout(); - return managedDropDown; - } - - [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] // using "\t" to figure out the width of tab - private void CalculateInternalLayoutMetrics() { - - - Size maxTextSize = Size.Empty; - Size maxImageSize = Size.Empty; - Size maxCheckSize = scaledDefaultImageSize; - Size maxArrowSize = Size.Empty; - Size maxNonMenuItemSize = Size.Empty; - - // determine Text Metrics - for (int i = 0; i < Items.Count; i++) { - ToolStripItem item = Items[i]; - ToolStripMenuItem menuItem = item as ToolStripMenuItem; - - if (menuItem != null) { - - Size menuItemTextSize = menuItem.GetTextSize(); - - if (menuItem.ShowShortcutKeys) { - Size shortcutTextSize = menuItem.GetShortcutTextSize(); - if (tabWidth == -1) { - tabWidth = TextRenderer.MeasureText("\t", this.Font).Width; - } - menuItemTextSize.Width += tabWidth + shortcutTextSize.Width; - menuItemTextSize.Height = Math.Max(menuItemTextSize.Height, shortcutTextSize.Height); - } + if (ShowCheckMargin && ShowImageMargin) + { + // double column - check margin then image margin + // default to 46px - grow if necessary. + checkAndImageMarginWidth = scaledDefaultImageAndCheckMarginWidth; - // we truly only care about the maximum size we find. - maxTextSize.Width = Math.Max(maxTextSize.Width, menuItemTextSize.Width); - maxTextSize.Height = Math.Max(maxTextSize.Height, menuItemTextSize.Height); + // add in the extra space for the image... since the check size is locked down to 16x16. + checkAndImageMarginWidth += extraImageWidth; - // determine Image Metrics - Size imageSize = Size.Empty; - if (menuItem.Image != null) { - imageSize = (menuItem.ImageScaling == ToolStripItemImageScaling.SizeToFit) ? ImageScalingSize : menuItem.Image.Size; - } - - maxImageSize.Width = Math.Max(maxImageSize.Width, imageSize.Width); - maxImageSize.Height = Math.Max(maxImageSize.Height, imageSize.Height); - - if (menuItem.CheckedImage != null) { - Size checkedImageSize = menuItem.CheckedImage.Size; - maxCheckSize.Width = Math.Max(checkedImageSize.Width, maxCheckSize.Width); - maxCheckSize.Height = Math.Max(checkedImageSize.Height, maxCheckSize.Height); - } - } - else if (!(item is ToolStripSeparator)) { - maxNonMenuItemSize.Height = Math.Max(item.Bounds.Height, maxNonMenuItemSize.Height); - maxNonMenuItemSize.Width = Math.Max(item.Bounds.Width, maxNonMenuItemSize.Width); - } - } - - this.maxItemSize.Height = Math.Max(maxTextSize.Height + scaledTextPadding.Vertical, Math.Max(maxCheckSize.Height + scaledCheckPadding.Vertical, maxArrowSize.Height + scaledArrowPadding.Vertical)); + // align the checkmark + nextPoint = new Point(scaledCheckPadding.Left, scaledCheckPadding.Top); + checkRectangle = LayoutUtils.Align(maxCheckSize, new Rectangle(nextPoint.X, nextPoint.Y, maxCheckSize.Width, maxItemSize.Height), ContentAlignment.MiddleCenter); - if (ShowImageMargin) { - // only add in the image into the calculation if we're going to render it. - this.maxItemSize.Height = Math.Max(maxImageSize.Height + scaledImagePadding.Vertical, maxItemSize.Height); - } - - bool useDefaultCheckMarginWidth = (ShowCheckMargin && (maxCheckSize.Width == 0)); - bool useDefaultImageMarginWidth = (ShowImageMargin && (maxImageSize.Width == 0)); - // Always save space for an arrow - maxArrowSize = new Size(scaledArrowSize, maxItemSize.Height); - - maxTextSize.Height = maxItemSize.Height - scaledTextPadding.Vertical; - maxImageSize.Height = maxItemSize.Height - scaledImagePadding.Vertical; - maxCheckSize.Height = maxItemSize.Height - scaledCheckPadding.Vertical; - - // fixup if there are non-menu items that are larger than our normal menu items - maxTextSize.Width = Math.Max(maxTextSize.Width, maxNonMenuItemSize.Width); - - Point nextPoint = Point.Empty; - int checkAndImageMarginWidth = 0; - - int extraImageWidth = Math.Max(0, maxImageSize.Width - scaledDefaultImageSize.Width); - - if (ShowCheckMargin && ShowImageMargin) { - // double column - check margin then image margin - // default to 46px - grow if necessary. - checkAndImageMarginWidth = scaledDefaultImageAndCheckMarginWidth; - - // add in the extra space for the image... since the check size is locked down to 16x16. - checkAndImageMarginWidth += extraImageWidth; - - // align the checkmark - nextPoint = new Point(scaledCheckPadding.Left, scaledCheckPadding.Top); - checkRectangle = LayoutUtils.Align(maxCheckSize, new Rectangle(nextPoint.X, nextPoint.Y, maxCheckSize.Width, maxItemSize.Height), ContentAlignment.MiddleCenter); - - // align the image rectangle - nextPoint.X = checkRectangle.Right + scaledCheckPadding.Right + scaledImagePadding.Left; - nextPoint.Y = scaledImagePadding.Top; - imageRectangle = LayoutUtils.Align(maxImageSize, new Rectangle(nextPoint.X, nextPoint.Y, maxImageSize.Width, maxItemSize.Height), ContentAlignment.MiddleCenter); - - } - else if (ShowCheckMargin) { - // no images should be shown in a ShowCheckMargin only scenario. - // default to 24px - grow if necessary. - checkAndImageMarginWidth = scaledDefaultImageMarginWidth; - - // align the checkmark - nextPoint = new Point(1,scaledCheckPadding.Top); - // nextPoint = new Point(scaledCheckPadding.Left, scaledCheckPadding.Top); - checkRectangle = LayoutUtils.Align(maxCheckSize, new Rectangle(nextPoint.X, nextPoint.Y, checkAndImageMarginWidth, maxItemSize.Height), ContentAlignment.MiddleCenter); - - imageRectangle = Rectangle.Empty; - - } - else if (ShowImageMargin) { - // checks and images render in the same area. - - // default to 24px - grow if necessary. - checkAndImageMarginWidth = scaledDefaultImageMarginWidth; - - // add in the extra space for the image... since the check size is locked down to 16x16. - checkAndImageMarginWidth += extraImageWidth; - - // NOTE due to the Padding property, we're going to have to recalc the vertical alignment in ToolStripMenuItemInternalLayout. - // Dont fuss here over the Y, X is what's critical. - - // check and image rect are the same - take the max of the image size and the check size and align - nextPoint = new Point(1, scaledCheckPadding.Top); - checkRectangle = LayoutUtils.Align(LayoutUtils.UnionSizes(maxCheckSize,maxImageSize), new Rectangle(nextPoint.X, nextPoint.Y, checkAndImageMarginWidth-1, maxItemSize.Height), ContentAlignment.MiddleCenter); - - // align the image - imageRectangle = checkRectangle; - - } - else { - checkAndImageMarginWidth = 0; - } - nextPoint.X = checkAndImageMarginWidth+1; - - - // calculate space for image - // if we didnt have a check - make sure to ignore check padding - - // consider: should we constrain to a reasonable width? - //imageMarginBounds = new Rectangle(0, 0, Math.Max(imageMarginWidth,DefaultImageMarginWidth), this.Height); - imageMarginBounds = new Rectangle(0,0,checkAndImageMarginWidth, this.Height); - - // calculate space for shortcut and text - nextPoint.X = imageMarginBounds.Right+ scaledTextPadding.Left; - nextPoint.Y = scaledTextPadding.Top; - textRectangle = new Rectangle(nextPoint, maxTextSize); - - // calculate space for arrow - nextPoint.X = textRectangle.Right+ scaledTextPadding.Right + scaledArrowPadding.Left; - nextPoint.Y = scaledArrowPadding.Top; - arrowRectangle = new Rectangle(nextPoint, maxArrowSize); - - // calculate space required for all of these pieces - this.maxItemSize.Width = (arrowRectangle.Right + scaledArrowPadding.Right) - imageMarginBounds.Left; - - this.Padding = DefaultPadding; - int trimPadding = imageMarginBounds.Width; - - if (RightToLeft == RightToLeft.Yes) { - // reverse the rectangle alignment in RightToLeft.Yes - trimPadding += scaledTextPadding.Right; - int width = maxItemSize.Width; - checkRectangle.X = width - checkRectangle.Right; - imageRectangle.X = width - imageRectangle.Right; - textRectangle.X = width - textRectangle.Right; - arrowRectangle.X = width - arrowRectangle.Right; - imageMarginBounds.X = width - imageMarginBounds.Right; - - } - else { - trimPadding += scaledTextPadding.Left; - } + // align the image rectangle + nextPoint.X = checkRectangle.Right + scaledCheckPadding.Right + scaledImagePadding.Left; + nextPoint.Y = scaledImagePadding.Top; + imageRectangle = LayoutUtils.Align(maxImageSize, new Rectangle(nextPoint.X, nextPoint.Y, maxImageSize.Width, maxItemSize.Height), ContentAlignment.MiddleCenter); + } + else if (ShowCheckMargin) + { + // no images should be shown in a ShowCheckMargin only scenario. + // default to 24px - grow if necessary. + checkAndImageMarginWidth = scaledDefaultImageMarginWidth; - - // We need to make sure that the text really appears vertically centered - this can be a problem in - // systems which force the text rectangle to be odd. + // align the checkmark + nextPoint = new Point(1, scaledCheckPadding.Top); + // nextPoint = new Point(scaledCheckPadding.Left, scaledCheckPadding.Top); + checkRectangle = LayoutUtils.Align(maxCheckSize, new Rectangle(nextPoint.X, nextPoint.Y, checkAndImageMarginWidth, maxItemSize.Height), ContentAlignment.MiddleCenter); - // force this to be an even height. - this.maxItemSize.Height += this.maxItemSize.Height%2; + imageRectangle = Rectangle.Empty; - textRectangle.Y = LayoutUtils.VAlign(textRectangle.Size, new Rectangle(Point.Empty, maxItemSize), ContentAlignment.MiddleCenter).Y; - textRectangle.Y += (textRectangle.Height %2); // if the height is odd, push down by one px - state[stateMaxItemSizeValid]=true; - this.PaddingToTrim = trimPadding; - } + else if (ShowImageMargin) + { + // checks and images render in the same area. - internal override void ChangeSelection(ToolStripItem nextItem) { - if (nextItem != null) { - Rectangle displayRect = DisplayRectangle; - if (!displayRect.Contains(displayRect.X, nextItem.Bounds.Top) - || !displayRect.Contains(displayRect.X, nextItem.Bounds.Bottom)) { + // default to 24px - grow if necessary. + checkAndImageMarginWidth = scaledDefaultImageMarginWidth; - int delta; - if (displayRect.Y > nextItem.Bounds.Top) { - delta = nextItem.Bounds.Top - displayRect.Y; - } - else { - delta = nextItem.Bounds.Bottom - (displayRect.Y + displayRect.Height); - // Now adjust so that the item at the top isn't truncated. - int index = this.Items.IndexOf(nextItem); - while (index >= 0) { - // we need to roll back to the index which is visible - if ( (this.Items[index].Visible && displayRect.Contains(displayRect.X, this.Items[index].Bounds.Top - delta)) - || !this.Items[index].Visible) { - --index; - } - else { - break; - } - } + // add in the extra space for the image... since the check size is locked down to 16x16. + checkAndImageMarginWidth += extraImageWidth; - if (index >= 0) { - if (displayRect.Contains(displayRect.X, this.Items[index].Bounds.Bottom - delta)) { - // We found an item which is truncated at the top. - delta += (this.Items[index].Bounds.Bottom - delta) - displayRect.Top; - } - } - } - this.ScrollInternal(delta); - this.UpdateScrollButtonStatus(); - } - } - base.ChangeSelection(nextItem); - } + // NOTE due to the Padding property, we're going to have to recalc the vertical alignment in ToolStripMenuItemInternalLayout. + // Dont fuss here over the Y, X is what's critical. - protected internal override ToolStripItem CreateDefaultItem(string text, Image image, EventHandler onClick) { - if (text == "-") { - return new ToolStripSeparator(); - } - else { - return new ToolStripMenuItem(text,image,onClick); - } - } + // check and image rect are the same - take the max of the image size and the check size and align + nextPoint = new Point(1, scaledCheckPadding.Top); + checkRectangle = LayoutUtils.Align(LayoutUtils.UnionSizes(maxCheckSize, maxImageSize), new Rectangle(nextPoint.X, nextPoint.Y, checkAndImageMarginWidth - 1, maxItemSize.Height), ContentAlignment.MiddleCenter); - internal override ToolStripItem GetNextItem(ToolStripItem start, ArrowDirection direction, bool rtlAware) { - // for up/down we dont care about flipping left/right tab should still take you down. - return GetNextItem(start, direction); - } + // align the image + imageRectangle = checkRectangle; - internal override void Initialize() { - base.Initialize(); - this.Padding = DefaultPadding; - FlowLayoutSettings settings = FlowLayout.CreateSettings(this); - settings.FlowDirection = FlowDirection.TopDown; - state[stateShowImageMargin] = true; } - protected override void OnLayout(LayoutEventArgs e) { - if (!this.IsDisposed) - { - // We always layout as if we don't need scroll buttons. - // If we do, then we'll adjust the positions to match. - this.RequiresScrollButtons = false; - CalculateInternalLayoutMetrics(); - base.OnLayout(e); - if (!this.RequiresScrollButtons) { - this.ResetScrollPosition(); - } - } + else + { + checkAndImageMarginWidth = 0; } + nextPoint.X = checkAndImageMarginWidth + 1; + + + // calculate space for image + // if we didnt have a check - make sure to ignore check padding + + // consider: should we constrain to a reasonable width? + //imageMarginBounds = new Rectangle(0, 0, Math.Max(imageMarginWidth,DefaultImageMarginWidth), this.Height); + imageMarginBounds = new Rectangle(0, 0, checkAndImageMarginWidth, this.Height); + + // calculate space for shortcut and text + nextPoint.X = imageMarginBounds.Right + scaledTextPadding.Left; + nextPoint.Y = scaledTextPadding.Top; + textRectangle = new Rectangle(nextPoint, maxTextSize); + + // calculate space for arrow + nextPoint.X = textRectangle.Right + scaledTextPadding.Right + scaledArrowPadding.Left; + nextPoint.Y = scaledArrowPadding.Top; + arrowRectangle = new Rectangle(nextPoint, maxArrowSize); + + // calculate space required for all of these pieces + this.maxItemSize.Width = (arrowRectangle.Right + scaledArrowPadding.Right) - imageMarginBounds.Left; + + this.Padding = DefaultPadding; + int trimPadding = imageMarginBounds.Width; + + if (RightToLeft == RightToLeft.Yes) + { + // reverse the rectangle alignment in RightToLeft.Yes + trimPadding += scaledTextPadding.Right; + int width = maxItemSize.Width; + checkRectangle.X = width - checkRectangle.Right; + imageRectangle.X = width - imageRectangle.Right; + textRectangle.X = width - textRectangle.Right; + arrowRectangle.X = width - arrowRectangle.Right; + imageMarginBounds.X = width - imageMarginBounds.Right; - protected override void OnFontChanged(EventArgs e) { - tabWidth = -1; - base.OnFontChanged(e); - } - protected override void OnPaintBackground(PaintEventArgs e) { - base.OnPaintBackground(e); - if (ShowCheckMargin || ShowImageMargin) { - Renderer.DrawImageMargin(new ToolStripRenderEventArgs(e.Graphics, this, this.ImageMargin, SystemColors.Control)); - } + else + { + trimPadding += scaledTextPadding.Left; } - internal override bool RequiresScrollButtons { - get { - return GetToolStripState(STATE_SCROLLBUTTONS); - } - set { - bool changed = (RequiresScrollButtons != value); - SetToolStripState(STATE_SCROLLBUTTONS, value); - if (changed) { - UpdateScrollButtonLocations(); - if (this.Items.Count > 0) { - int delta = this.Items[0].Bounds.Top - this.DisplayRectangle.Top; - this.ScrollInternal(delta); - this.scrollAmount -= delta; - if (value) { - RestoreScrollPosition(); - } - } - else { - this.scrollAmount = 0; - } - } - } - } - internal void ResetScrollPosition() { - this.scrollAmount = 0; - } - internal void RestoreScrollPosition() { - if (!RequiresScrollButtons || this.Items.Count == 0) { - return; - } + // We need to make sure that the text really appears vertically centered - this can be a problem in + // systems which force the text rectangle to be odd. + + // force this to be an even height. + this.maxItemSize.Height += this.maxItemSize.Height % 2; + + textRectangle.Y = LayoutUtils.VAlign(textRectangle.Size, new Rectangle(Point.Empty, maxItemSize), ContentAlignment.MiddleCenter).Y; + textRectangle.Y += (textRectangle.Height % 2); // if the height is odd, push down by one px + state[stateMaxItemSizeValid] = true; + this.PaddingToTrim = trimPadding; - // We don't just scroll by the amount, because that might - // cause the bottom of the menu to be blank if some items have - // been removed/hidden since the last time we were displayed. - // This also deals with items of different height, so that we don't truncate - // and items under the top scrollbar. - - Rectangle displayRectangle = this.DisplayRectangle; - int alreadyScrolled = displayRectangle.Top - this.Items[0].Bounds.Top; - - int requiredScrollAmount = this.scrollAmount - alreadyScrolled; - - int deltaToScroll = 0; - if (requiredScrollAmount > 0) { - for (int i = 0; i < this.Items.Count && deltaToScroll < requiredScrollAmount; ++i) { - if (this.Items[i].Available) { - Rectangle adjustedLastItemBounds = this.Items[this.Items.Count - 1].Bounds; - adjustedLastItemBounds.Y -= deltaToScroll; - if (displayRectangle.Contains(displayRectangle.X, adjustedLastItemBounds.Top) - && displayRectangle.Contains(displayRectangle.X, adjustedLastItemBounds.Bottom)) { - // Scrolling this amount would make the last item visible, so don't scroll any more. + } + + internal override void ChangeSelection(ToolStripItem nextItem) + { + if (nextItem != null) + { + Rectangle displayRect = DisplayRectangle; + if (!displayRect.Contains(displayRect.X, nextItem.Bounds.Top) + || !displayRect.Contains(displayRect.X, nextItem.Bounds.Bottom)) + { + + int delta; + if (displayRect.Y > nextItem.Bounds.Top) + { + delta = nextItem.Bounds.Top - displayRect.Y; + } + else + { + delta = nextItem.Bounds.Bottom - (displayRect.Y + displayRect.Height); + // Now adjust so that the item at the top isn't truncated. + int index = this.Items.IndexOf(nextItem); + while (index >= 0) + { + // we need to roll back to the index which is visible + if ((this.Items[index].Visible && displayRect.Contains(displayRect.X, this.Items[index].Bounds.Top - delta)) + || !this.Items[index].Visible) + { + --index; + } + else + { break; } + } - // We use a delta between the tops, since it takes margin's and padding into account. - if (i < this.Items.Count - 1) { - deltaToScroll += this.Items[i + 1].Bounds.Top - this.Items[i].Bounds.Top; - } - else { - deltaToScroll += this.Items[i].Bounds.Height; + if (index >= 0) + { + if (displayRect.Contains(displayRect.X, this.Items[index].Bounds.Bottom - delta)) + { + // We found an item which is truncated at the top. + delta += (this.Items[index].Bounds.Bottom - delta) - displayRect.Top; } } } + this.ScrollInternal(delta); + this.UpdateScrollButtonStatus(); + } + } + base.ChangeSelection(nextItem); + } + + protected internal override ToolStripItem CreateDefaultItem(string text, Image image, EventHandler onClick) + { + if (text == "-") + { + return new ToolStripSeparator(); + } + else + { + return new ToolStripMenuItem(text, image, onClick); + } + } + + internal override ToolStripItem GetNextItem(ToolStripItem start, ArrowDirection direction, bool rtlAware) + { + // for up/down we dont care about flipping left/right tab should still take you down. + return GetNextItem(start, direction); + } + + internal override void Initialize() + { + base.Initialize(); + this.Padding = DefaultPadding; + FlowLayoutSettings settings = FlowLayout.CreateSettings(this); + settings.FlowDirection = FlowDirection.TopDown; + state[stateShowImageMargin] = true; + } + protected override void OnLayout(LayoutEventArgs e) + { + if (!this.IsDisposed) + { + // We always layout as if we don't need scroll buttons. + // If we do, then we'll adjust the positions to match. + this.RequiresScrollButtons = false; + CalculateInternalLayoutMetrics(); + base.OnLayout(e); + if (!this.RequiresScrollButtons) + { + this.ResetScrollPosition(); } - else { - for (int i = this.Items.Count - 1; i >= 0 && deltaToScroll > requiredScrollAmount; --i) { - if (this.Items[i].Available) { - Rectangle adjustedLastItemBounds = this.Items[0].Bounds; - adjustedLastItemBounds.Y -= deltaToScroll; - if (displayRectangle.Contains(displayRectangle.X, adjustedLastItemBounds.Top) - && displayRectangle.Contains(displayRectangle.X, adjustedLastItemBounds.Bottom)) { - // Scrolling this amount would make the last item visible, so don't scroll any more. - break; - } + } + } - // We use a delta between the tops, since it takes margin's and padding into account. - if (i > 0) { - deltaToScroll -= this.Items[i].Bounds.Top - this.Items[i - 1].Bounds.Top; - } - else { - deltaToScroll -= this.Items[i].Bounds.Height; - } + protected override void OnFontChanged(EventArgs e) + { + tabWidth = -1; + base.OnFontChanged(e); + + } + protected override void OnPaintBackground(PaintEventArgs e) + { + base.OnPaintBackground(e); + if (ShowCheckMargin || ShowImageMargin) + { + Renderer.DrawImageMargin(new ToolStripRenderEventArgs(e.Graphics, this, this.ImageMargin, SystemColors.Control)); + } + } + + internal override bool RequiresScrollButtons + { + get + { + return GetToolStripState(STATE_SCROLLBUTTONS); + } + set + { + bool changed = (RequiresScrollButtons != value); + SetToolStripState(STATE_SCROLLBUTTONS, value); + if (changed) + { + UpdateScrollButtonLocations(); + if (this.Items.Count > 0) + { + int delta = this.Items[0].Bounds.Top - this.DisplayRectangle.Top; + this.ScrollInternal(delta); + this.scrollAmount -= delta; + if (value) + { + RestoreScrollPosition(); } } + else + { + this.scrollAmount = 0; + } } - this.ScrollInternal(deltaToScroll); - this.scrollAmount = this.DisplayRectangle.Top - this.Items[0].Bounds.Top; - UpdateScrollButtonLocations(); } + } + internal void ResetScrollPosition() + { + this.scrollAmount = 0; + } - internal override void ScrollInternal(int delta) { - base.ScrollInternal(delta); - this.scrollAmount += delta; + internal void RestoreScrollPosition() + { + if (!RequiresScrollButtons || this.Items.Count == 0) + { + return; } - internal void ScrollInternal(bool up) { - UpdateScrollButtonStatus(); + // We don't just scroll by the amount, because that might + // cause the bottom of the menu to be blank if some items have + // been removed/hidden since the last time we were displayed. + // This also deals with items of different height, so that we don't truncate + // and items under the top scrollbar. - // calling this to get ScrollWindowEx. In actuality it does nothing - // to change the display rect! - int delta; - if (this.indexOfFirstDisplayedItem == -1 || this.indexOfFirstDisplayedItem >= this.Items.Count) { - Debug.Fail("Why wasn't 'UpdateScrollButtonStatus called'? We don't have the item to scroll by"); - int menuHeight = SystemInformation.MenuHeight; + Rectangle displayRectangle = this.DisplayRectangle; + int alreadyScrolled = displayRectangle.Top - this.Items[0].Bounds.Top; - delta = up ? -menuHeight : menuHeight; - } - else { - if (up) { - if (this.indexOfFirstDisplayedItem == 0) { - Debug.Fail("We're trying to scroll up, but the top item is displayed!!!"); - delta = 0; + int requiredScrollAmount = this.scrollAmount - alreadyScrolled; + + int deltaToScroll = 0; + if (requiredScrollAmount > 0) + { + for (int i = 0; i < this.Items.Count && deltaToScroll < requiredScrollAmount; ++i) + { + if (this.Items[i].Available) + { + Rectangle adjustedLastItemBounds = this.Items[this.Items.Count - 1].Bounds; + adjustedLastItemBounds.Y -= deltaToScroll; + if (displayRectangle.Contains(displayRectangle.X, adjustedLastItemBounds.Top) + && displayRectangle.Contains(displayRectangle.X, adjustedLastItemBounds.Bottom)) + { + // Scrolling this amount would make the last item visible, so don't scroll any more. + break; + } + + // We use a delta between the tops, since it takes margin's and padding into account. + if (i < this.Items.Count - 1) + { + deltaToScroll += this.Items[i + 1].Bounds.Top - this.Items[i].Bounds.Top; } - else { - ToolStripItem itemTop = this.Items[this.indexOfFirstDisplayedItem - 1]; - ToolStripItem itemBottom = this.Items[this.indexOfFirstDisplayedItem]; - // We use a delta between the tops, since it takes margin's and padding into account. - delta = itemTop.Bounds.Top - itemBottom.Bounds.Top; + else + { + deltaToScroll += this.Items[i].Bounds.Height; } } - else { - if (this.indexOfFirstDisplayedItem == this.Items.Count - 1) { - Debug.Fail("We're trying to scroll down, but the top item is displayed!!!"); - delta = 0; + } + } + else + { + for (int i = this.Items.Count - 1; i >= 0 && deltaToScroll > requiredScrollAmount; --i) + { + if (this.Items[i].Available) + { + Rectangle adjustedLastItemBounds = this.Items[0].Bounds; + adjustedLastItemBounds.Y -= deltaToScroll; + if (displayRectangle.Contains(displayRectangle.X, adjustedLastItemBounds.Top) + && displayRectangle.Contains(displayRectangle.X, adjustedLastItemBounds.Bottom)) + { + // Scrolling this amount would make the last item visible, so don't scroll any more. + break; } - ToolStripItem itemTop = this.Items[this.indexOfFirstDisplayedItem]; - ToolStripItem itemBottom = this.Items[this.indexOfFirstDisplayedItem + 1]; // We use a delta between the tops, since it takes margin's and padding into account. - delta = itemBottom.Bounds.Top - itemTop.Bounds.Top; + if (i > 0) + { + deltaToScroll -= this.Items[i].Bounds.Top - this.Items[i - 1].Bounds.Top; + } + else + { + deltaToScroll -= this.Items[i].Bounds.Height; + } } } - ScrollInternal(delta); - UpdateScrollButtonLocations(); } + this.ScrollInternal(deltaToScroll); + this.scrollAmount = this.DisplayRectangle.Top - this.Items[0].Bounds.Top; + UpdateScrollButtonLocations(); + } - protected override void SetDisplayedItems() { - base.SetDisplayedItems(); - if (RequiresScrollButtons) { + internal override void ScrollInternal(int delta) + { + base.ScrollInternal(delta); + this.scrollAmount += delta; + } - this.DisplayedItems.Add(UpScrollButton); - this.DisplayedItems.Add(DownScrollButton); - UpdateScrollButtonLocations(); - UpScrollButton.Visible = true; - DownScrollButton.Visible = true; + internal void ScrollInternal(bool up) + { + UpdateScrollButtonStatus(); + + // calling this to get ScrollWindowEx. In actuality it does nothing + // to change the display rect! + int delta; + if (this.indexOfFirstDisplayedItem == -1 || this.indexOfFirstDisplayedItem >= this.Items.Count) + { + Debug.Fail("Why wasn't 'UpdateScrollButtonStatus called'? We don't have the item to scroll by"); + int menuHeight = SystemInformation.MenuHeight; + + delta = up ? -menuHeight : menuHeight; + } + else + { + if (up) + { + if (this.indexOfFirstDisplayedItem == 0) + { + Debug.Fail("We're trying to scroll up, but the top item is displayed!!!"); + delta = 0; + } + else + { + ToolStripItem itemTop = this.Items[this.indexOfFirstDisplayedItem - 1]; + ToolStripItem itemBottom = this.Items[this.indexOfFirstDisplayedItem]; + // We use a delta between the tops, since it takes margin's and padding into account. + delta = itemTop.Bounds.Top - itemBottom.Bounds.Top; + } } - else { - UpScrollButton.Visible = false; - DownScrollButton.Visible = false; + else + { + if (this.indexOfFirstDisplayedItem == this.Items.Count - 1) + { + Debug.Fail("We're trying to scroll down, but the top item is displayed!!!"); + delta = 0; + } + + ToolStripItem itemTop = this.Items[this.indexOfFirstDisplayedItem]; + ToolStripItem itemBottom = this.Items[this.indexOfFirstDisplayedItem + 1]; + // We use a delta between the tops, since it takes margin's and padding into account. + delta = itemBottom.Bounds.Top - itemTop.Bounds.Top; } } + ScrollInternal(delta); + UpdateScrollButtonLocations(); + } - private void UpdateScrollButtonLocations() { + protected override void SetDisplayedItems() + { - if (GetToolStripState(STATE_SCROLLBUTTONS)) { - Size upSize = UpScrollButton.GetPreferredSize(Size.Empty); - // - Point upLocation = new Point(1, 0); + base.SetDisplayedItems(); + if (RequiresScrollButtons) + { - UpScrollButton.SetBounds(new Rectangle(upLocation, upSize)); + this.DisplayedItems.Add(UpScrollButton); + this.DisplayedItems.Add(DownScrollButton); + UpdateScrollButtonLocations(); + UpScrollButton.Visible = true; + DownScrollButton.Visible = true; + } + else + { + UpScrollButton.Visible = false; + DownScrollButton.Visible = false; + } + } - Size downSize = DownScrollButton.GetPreferredSize(Size.Empty); - int height = GetDropDownBounds(this.Bounds).Height; + private void UpdateScrollButtonLocations() + { - Point downLocation = new Point(1, height - downSize.Height); - DownScrollButton.SetBounds(new Rectangle(downLocation, downSize)); - UpdateScrollButtonStatus(); - } + if (GetToolStripState(STATE_SCROLLBUTTONS)) + { + Size upSize = UpScrollButton.GetPreferredSize(Size.Empty); + // + Point upLocation = new Point(1, 0); + + UpScrollButton.SetBounds(new Rectangle(upLocation, upSize)); + + Size downSize = DownScrollButton.GetPreferredSize(Size.Empty); + int height = GetDropDownBounds(this.Bounds).Height; + Point downLocation = new Point(1, height - downSize.Height); + DownScrollButton.SetBounds(new Rectangle(downLocation, downSize)); + UpdateScrollButtonStatus(); } - private void UpdateScrollButtonStatus() { - Rectangle displayRectangle = this.DisplayRectangle; + } - this.indexOfFirstDisplayedItem = -1; - int minY = int.MaxValue, maxY = 0; + private void UpdateScrollButtonStatus() + { + Rectangle displayRectangle = this.DisplayRectangle; - for (int i = 0; i < this.Items.Count; ++i) { - ToolStripItem item = this.Items[i]; - if (UpScrollButton == item) { - continue; - } - if (DownScrollButton == item) { - continue; - } + this.indexOfFirstDisplayedItem = -1; + int minY = int.MaxValue, maxY = 0; - if (!item.Available) { - continue; - } + for (int i = 0; i < this.Items.Count; ++i) + { + ToolStripItem item = this.Items[i]; + if (UpScrollButton == item) + { + continue; + } + if (DownScrollButton == item) + { + continue; + } - if (this.indexOfFirstDisplayedItem == -1 && displayRectangle.Contains(displayRectangle.X, item.Bounds.Top)) { - this.indexOfFirstDisplayedItem = i; - } + if (!item.Available) + { + continue; + } - minY = Math.Min(minY, item.Bounds.Top); - maxY = Math.Max(maxY, item.Bounds.Bottom); + if (this.indexOfFirstDisplayedItem == -1 && displayRectangle.Contains(displayRectangle.X, item.Bounds.Top)) + { + this.indexOfFirstDisplayedItem = i; } - UpScrollButton.Enabled = !displayRectangle.Contains(displayRectangle.X, minY); - DownScrollButton.Enabled = !displayRectangle.Contains(displayRectangle.X, maxY); + minY = Math.Min(minY, item.Bounds.Top); + maxY = Math.Max(maxY, item.Bounds.Bottom); } - internal sealed class ToolStripDropDownLayoutEngine : FlowLayout { + UpScrollButton.Enabled = !displayRectangle.Contains(displayRectangle.X, minY); + DownScrollButton.Enabled = !displayRectangle.Contains(displayRectangle.X, maxY); + } - public static ToolStripDropDownLayoutEngine LayoutInstance = new ToolStripDropDownLayoutEngine(); - - internal override Size GetPreferredSize(IArrangedElement container, Size proposedConstraints) { - Size preferredSize = base.GetPreferredSize(container, proposedConstraints); - ToolStripDropDownMenu dropDownMenu = container as ToolStripDropDownMenu; - if (dropDownMenu != null) { - preferredSize.Width = dropDownMenu.MaxItemSize.Width - dropDownMenu.PaddingToTrim; - } - return preferredSize; + internal sealed class ToolStripDropDownLayoutEngine : FlowLayout + { + + public static ToolStripDropDownLayoutEngine LayoutInstance = new ToolStripDropDownLayoutEngine(); + + internal override Size GetPreferredSize(IArrangedElement container, Size proposedConstraints) + { + Size preferredSize = base.GetPreferredSize(container, proposedConstraints); + ToolStripDropDownMenu dropDownMenu = container as ToolStripDropDownMenu; + if (dropDownMenu != null) + { + preferredSize.Width = dropDownMenu.MaxItemSize.Width - dropDownMenu.PaddingToTrim; } + return preferredSize; + } - } - } + } } +} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropTargetManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropTargetManager.cs index 3ab669c7226..459d60a9fbf 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropTargetManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropTargetManager.cs @@ -36,40 +36,47 @@ internal class ToolStripDropTargetManager : IDropTarget /// Summary of ToolStripDropTargetManager. /// /// - public ToolStripDropTargetManager(ToolStrip owner) { + public ToolStripDropTargetManager(ToolStrip owner) + { this.owner = owner; - if (owner == null) { + if (owner == null) + { throw new ArgumentNullException(nameof(owner)); } } - + /// /// Summary of EnsureRegistered. /// /// - public void EnsureRegistered(IDropTarget dropTarget) { - Debug.WriteLineIf(DragDropDebug.TraceVerbose, "Ensuring drop target registered"); - SetAcceptDrops(true); + public void EnsureRegistered(IDropTarget dropTarget) + { + Debug.WriteLineIf(DragDropDebug.TraceVerbose, "Ensuring drop target registered"); + SetAcceptDrops(true); } /// /// Summary of EnsureUnRegistered. /// /// - public void EnsureUnRegistered(IDropTarget dropTarget) { - + public void EnsureUnRegistered(IDropTarget dropTarget) + { + Debug.WriteLineIf(DragDropDebug.TraceVerbose, "Attempting to unregister droptarget"); - for (int i = 0; i < owner.Items.Count; i++) { - if (owner.Items[i].AllowDrop) { + for (int i = 0; i < owner.Items.Count; i++) + { + if (owner.Items[i].AllowDrop) + { Debug.WriteLineIf(DragDropDebug.TraceVerbose, "An item still has allowdrop set to true - cant unregister"); return; // can't unregister this as a drop target unless everyone is done. } } - if (owner.AllowDrop || owner.AllowItemReorder) { + if (owner.AllowDrop || owner.AllowItemReorder) + { Debug.WriteLineIf(DragDropDebug.TraceVerbose, "The ToolStrip has AllowDrop or AllowItemReorder set to true - cant unregister"); return; // can't unregister this as a drop target if ToolStrip is still accepting drops } - + SetAcceptDrops(false); owner.DropTargetManager = null; } @@ -79,57 +86,65 @@ public void EnsureUnRegistered(IDropTarget dropTarget) { /// /// /// - private ToolStripItem FindItemAtPoint(int x, int y) { - return owner.GetItemAt(owner.PointToClient(new Point(x,y))); - } + private ToolStripItem FindItemAtPoint(int x, int y) + { + return owner.GetItemAt(owner.PointToClient(new Point(x, y))); + } /// /// Summary of OnDragEnter. /// /// - public void OnDragEnter(DragEventArgs e) { - Debug.WriteLineIf(DragDropDebug.TraceVerbose, "[DRAG ENTER] =============="); - + public void OnDragEnter(DragEventArgs e) + { + Debug.WriteLineIf(DragDropDebug.TraceVerbose, "[DRAG ENTER] =============="); + // If we are supporting Item Reordering // and this is a ToolStripItem - snitch it. - if (owner.AllowItemReorder && e.Data.GetDataPresent(typeof(ToolStripItem))) { - Debug.WriteLineIf(DragDropDebug.TraceVerbose, "ItemReorderTarget taking this..."); + if (owner.AllowItemReorder && e.Data.GetDataPresent(typeof(ToolStripItem))) + { + Debug.WriteLineIf(DragDropDebug.TraceVerbose, "ItemReorderTarget taking this..."); lastDropTarget = owner.ItemReorderDropTarget; - + } - else { + else + { ToolStripItem item = FindItemAtPoint(e.X, e.Y); - if ((item != null) && (item.AllowDrop)) { + if ((item != null) && (item.AllowDrop)) + { // the item wants this event Debug.WriteLineIf(DragDropDebug.TraceVerbose, "ToolStripItem taking this: " + item.ToString()); - - lastDropTarget = ((IDropTarget)item); + + lastDropTarget = ((IDropTarget)item); } - else if (owner.AllowDrop) { + else if (owner.AllowDrop) + { // the ToolStrip wants this event - Debug.WriteLineIf(DragDropDebug.TraceVerbose, "ToolStrip taking this because AllowDrop set to true."); + Debug.WriteLineIf(DragDropDebug.TraceVerbose, "ToolStrip taking this because AllowDrop set to true."); lastDropTarget = ((IDropTarget)owner); - - } - else { + + } + else + { // There could be one item that says "AllowDrop == true" which would turn // on this drop target manager. If we're not over that particular item - then // just null out the last drop target manager. - + // the other valid reason for being here is that we've done an AllowItemReorder // and we dont have a ToolStripItem contain within the data (say someone drags a link // from IE over the ToolStrip) Debug.WriteLineIf(DragDropDebug.TraceVerbose, "No one wanted it."); - + lastDropTarget = null; - } + } } - if (lastDropTarget != null) { - Debug.WriteLineIf(DragDropDebug.TraceVerbose, "Calling OnDragEnter on target..."); + if (lastDropTarget != null) + { + Debug.WriteLineIf(DragDropDebug.TraceVerbose, "Calling OnDragEnter on target..."); #if DEBUG - dropTargetIsEntered=true; + dropTargetIsEntered = true; #endif lastDropTarget.OnDragEnter(e); } @@ -139,69 +154,80 @@ public void OnDragEnter(DragEventArgs e) { /// Summary of OnDragOver. /// /// - public void OnDragOver(DragEventArgs e) { + public void OnDragOver(DragEventArgs e) + { + + Debug.WriteLineIf(DragDropDebug.TraceVerbose, "[DRAG OVER] =============="); - Debug.WriteLineIf(DragDropDebug.TraceVerbose, "[DRAG OVER] =============="); - IDropTarget newDropTarget = null; // If we are supporting Item Reordering // and this is a ToolStripItem - snitch it. - if (owner.AllowItemReorder && e.Data.GetDataPresent(typeof(ToolStripItem))) { - Debug.WriteLineIf(DragDropDebug.TraceVerbose, "ItemReorderTarget taking this..."); + if (owner.AllowItemReorder && e.Data.GetDataPresent(typeof(ToolStripItem))) + { + Debug.WriteLineIf(DragDropDebug.TraceVerbose, "ItemReorderTarget taking this..."); newDropTarget = owner.ItemReorderDropTarget; } - else { + else + { ToolStripItem item = FindItemAtPoint(e.X, e.Y); - if ((item != null) && (item.AllowDrop)) { + if ((item != null) && (item.AllowDrop)) + { // the item wants this event Debug.WriteLineIf(DragDropDebug.TraceVerbose, "ToolStripItem taking this: " + item.ToString()); - newDropTarget = ((IDropTarget)item); + newDropTarget = ((IDropTarget)item); } - else if (owner.AllowDrop) { + else if (owner.AllowDrop) + { // the ToolStrip wants this event - Debug.WriteLineIf(DragDropDebug.TraceVerbose, "ToolStrip taking this because AllowDrop set to true."); + Debug.WriteLineIf(DragDropDebug.TraceVerbose, "ToolStrip taking this because AllowDrop set to true."); newDropTarget = ((IDropTarget)owner); - } - else { - Debug.WriteLineIf(DragDropDebug.TraceVerbose, "No one wanted it."); + } + else + { + Debug.WriteLineIf(DragDropDebug.TraceVerbose, "No one wanted it."); newDropTarget = null; - } + } } // if we've switched drop targets - then // we need to create drag enter and leave events - if (newDropTarget != lastDropTarget) { + if (newDropTarget != lastDropTarget) + { Debug.WriteLineIf(DragDropDebug.TraceVerbose, "NEW DROP TARGET!"); UpdateDropTarget(newDropTarget, e); } // now call drag over - if (lastDropTarget != null) { - Debug.WriteLineIf(DragDropDebug.TraceVerbose, "Calling OnDragOver on target..."); + if (lastDropTarget != null) + { + Debug.WriteLineIf(DragDropDebug.TraceVerbose, "Calling OnDragOver on target..."); lastDropTarget.OnDragOver(e); } - + } /// /// Summary of OnDragLeave. /// /// - public void OnDragLeave(System.EventArgs e) { + public void OnDragLeave(System.EventArgs e) + { Debug.WriteLineIf(DragDropDebug.TraceVerbose, "[DRAG LEAVE] =============="); - - if (lastDropTarget != null) { + + if (lastDropTarget != null) + { Debug.WriteLineIf(DragDropDebug.TraceVerbose, "Calling OnDragLeave on current target..."); #if DEBUG - dropTargetIsEntered=false; + dropTargetIsEntered = false; #endif lastDropTarget.OnDragLeave(e); } #if DEBUG - else { + else + { Debug.Assert(!dropTargetIsEntered, "Why do we have an entered droptarget and NO lastDropTarget?"); } #endif @@ -212,19 +238,22 @@ public void OnDragLeave(System.EventArgs e) { /// Summary of OnDragDrop. /// /// - public void OnDragDrop(DragEventArgs e) { + public void OnDragDrop(DragEventArgs e) + { Debug.WriteLineIf(DragDropDebug.TraceVerbose, "[DRAG DROP] =============="); - - if (lastDropTarget != null) { - Debug.WriteLineIf(DragDropDebug.TraceVerbose, "Calling OnDragDrop on current target..."); - + + if (lastDropTarget != null) + { + Debug.WriteLineIf(DragDropDebug.TraceVerbose, "Calling OnDragDrop on current target..."); + lastDropTarget.OnDragDrop(e); } - else { + else + { Debug.Assert(false, "Why is lastDropTarget null?"); } - - lastDropTarget = null; + + lastDropTarget = null; } @@ -232,28 +261,30 @@ public void OnDragDrop(DragEventArgs e) { /// Used to actually register the control as a drop target. /// /// - private void SetAcceptDrops(bool accept) { - if (accept && owner.IsHandleCreated) { - try - { - if (Application.OleRequired() != System.Threading.ApartmentState.STA) - { - throw new ThreadStateException(SR.ThreadMustBeSTA); - } - if (accept) - { - Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "Registering as drop target: " + owner.Handle.ToString()); - // Register - int n = UnsafeNativeMethods.RegisterDragDrop(new HandleRef(owner, owner.Handle), (UnsafeNativeMethods.IOleDropTarget)(new DropTarget(this))); - - Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, " ret:" + n.ToString(CultureInfo.InvariantCulture)); - if (n != 0 && n != NativeMethods.DRAGDROP_E_ALREADYREGISTERED) - { - throw new Win32Exception(n); - } - } - else - { + private void SetAcceptDrops(bool accept) + { + if (accept && owner.IsHandleCreated) + { + try + { + if (Application.OleRequired() != System.Threading.ApartmentState.STA) + { + throw new ThreadStateException(SR.ThreadMustBeSTA); + } + if (accept) + { + Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "Registering as drop target: " + owner.Handle.ToString()); + // Register + int n = UnsafeNativeMethods.RegisterDragDrop(new HandleRef(owner, owner.Handle), (UnsafeNativeMethods.IOleDropTarget)(new DropTarget(this))); + + Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, " ret:" + n.ToString(CultureInfo.InvariantCulture)); + if (n != 0 && n != NativeMethods.DRAGDROP_E_ALREADYREGISTERED) + { + throw new Win32Exception(n); + } + } + else + { Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "Revoking drop target: " + owner.Handle.ToString()); // Revoke @@ -263,12 +294,12 @@ private void SetAcceptDrops(bool accept) { { throw new Win32Exception(n); } - } - } - catch (Exception e) - { - throw new InvalidOperationException(SR.DragDropRegFailed, e); - } + } + } + catch (Exception e) + { + throw new InvalidOperationException(SR.DragDropRegFailed, e); + } } } @@ -280,16 +311,20 @@ private void SetAcceptDrops(bool accept) { /// /// /// - private void UpdateDropTarget(IDropTarget newTarget, DragEventArgs e) { - - if (newTarget != lastDropTarget) { + private void UpdateDropTarget(IDropTarget newTarget, DragEventArgs e) + { + + if (newTarget != lastDropTarget) + { // tell the last drag target you've left - if (lastDropTarget != null) { + if (lastDropTarget != null) + { OnDragLeave(EventArgs.Empty); } lastDropTarget = newTarget; - if (newTarget != null) { + if (newTarget != null) + { DragEventArgs dragEnterArgs = new DragEventArgs(e.Data, e.KeyState, e.X, e.Y, e.AllowedEffect, e.Effect); dragEnterArgs.Effect = DragDropEffects.None; @@ -300,8 +335,8 @@ private void UpdateDropTarget(IDropTarget newTarget, DragEventArgs e) { } - - + + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripGrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripGrip.cs index c2f0f3ebb89..797312c6254 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripGrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripGrip.cs @@ -2,18 +2,20 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Drawing; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; using System.Windows.Forms.Layout; using System.Diagnostics; - + /// /// - internal class ToolStripGrip : ToolStripButton { + internal class ToolStripGrip : ToolStripButton + { private Cursor oldCursor; private int gripThickness = 0; @@ -30,176 +32,218 @@ internal class ToolStripGrip : ToolStripButton { private int scaledGripThicknessVisualStylesEnabled = gripThicknessVisualStylesEnabled; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] - internal ToolStripGrip() { - if (DpiHelper.IsScalingRequirementMet) { + internal ToolStripGrip() + { + if (DpiHelper.IsScalingRequirementMet) + { scaledDefaultPadding = DpiHelper.LogicalToDeviceUnits(defaultPadding); scaledGripThickness = DpiHelper.LogicalToDeviceUnitsX(gripThicknessDefault); scaledGripThicknessVisualStylesEnabled = DpiHelper.LogicalToDeviceUnitsX(gripThicknessVisualStylesEnabled); } // if we're using Visual Styles we've got to be a bit thicker. - gripThickness = ToolStripManager.VisualStylesEnabled ? scaledGripThicknessVisualStylesEnabled : scaledGripThickness; + gripThickness = ToolStripManager.VisualStylesEnabled ? scaledGripThicknessVisualStylesEnabled : scaledGripThickness; SupportsItemClick = false; } - /// + /// /// 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. /// - protected internal override Padding DefaultMargin { - get { + protected internal override Padding DefaultMargin + { + get + { return scaledDefaultPadding; } } - public override bool CanSelect { - get { - return false; - } + public override bool CanSelect + { + get + { + return false; + } } - internal int GripThickness { - get { + internal int GripThickness + { + get + { return gripThickness; } } - internal bool MovingToolStrip { - get { - return ((ToolStripPanelRow != null) && movingToolStrip); + internal bool MovingToolStrip + { + get + { + return ((ToolStripPanelRow != null) && movingToolStrip); } - set { - if ((movingToolStrip != value) && ParentInternal != null) { - if (value) { + set + { + if ((movingToolStrip != value) && ParentInternal != null) + { + if (value) + { // dont let grips move the toolstrip - if (ParentInternal.ToolStripPanelRow == null) { + if (ParentInternal.ToolStripPanelRow == null) + { return; } } movingToolStrip = value; lastEndLocation = ToolStrip.InvalidMouseEnter; - if (movingToolStrip) { - ((ISupportToolStripPanel)this.ParentInternal).BeginDrag(); + if (movingToolStrip) + { + ((ISupportToolStripPanel)this.ParentInternal).BeginDrag(); } - else { - ((ISupportToolStripPanel)this.ParentInternal).EndDrag(); + else + { + ((ISupportToolStripPanel)this.ParentInternal).EndDrag(); } } } } - private ToolStripPanelRow ToolStripPanelRow { - get { + private ToolStripPanelRow ToolStripPanelRow + { + get + { return (ParentInternal == null) ? null : ((ISupportToolStripPanel)ParentInternal).ToolStripPanelRow; } } - - protected override AccessibleObject CreateAccessibilityInstance() { + + protected override AccessibleObject CreateAccessibilityInstance() + { return new ToolStripGripAccessibleObject(this); } - public override Size GetPreferredSize(Size constrainingSize) { + public override Size GetPreferredSize(Size constrainingSize) + { Size preferredSize = Size.Empty; - if (this.ParentInternal != null) { - if (this.ParentInternal.LayoutStyle == ToolStripLayoutStyle.VerticalStackWithOverflow) { + if (this.ParentInternal != null) + { + if (this.ParentInternal.LayoutStyle == ToolStripLayoutStyle.VerticalStackWithOverflow) + { preferredSize = new Size(this.ParentInternal.Width, gripThickness); } - else { + else + { preferredSize = new Size(gripThickness, this.ParentInternal.Height); - + } - + } // Constrain ourselves - if (preferredSize.Width > constrainingSize.Width) { + if (preferredSize.Width > constrainingSize.Width) + { preferredSize.Width = constrainingSize.Width; } - if (preferredSize.Height > constrainingSize.Height) { + if (preferredSize.Height > constrainingSize.Height) + { preferredSize.Height = constrainingSize.Height; } - + return preferredSize; } - private bool LeftMouseButtonIsDown() { - return (Control.MouseButtons == MouseButtons.Left) && (Control.ModifierKeys == Keys.None); + private bool LeftMouseButtonIsDown() + { + return (Control.MouseButtons == MouseButtons.Left) && (Control.ModifierKeys == Keys.None); } - - protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { + + protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) + { // all the grip painting should be on the ToolStrip itself. - if (ParentInternal != null) { + if (ParentInternal != null) + { ParentInternal.OnPaintGrip(e); } } - - + + /// /// /// /// - protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs mea) { - startLocation = TranslatePoint(new Point(mea.X, mea.Y), ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ScreenCoords); + protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs mea) + { + startLocation = TranslatePoint(new Point(mea.X, mea.Y), ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ScreenCoords); base.OnMouseDown(mea); } - protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs mea) { + protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs mea) + { bool leftMouseButtonDown = LeftMouseButtonIsDown(); - if (!MovingToolStrip && leftMouseButtonDown) { + if (!MovingToolStrip && leftMouseButtonDown) + { // determine if we've moved far enough such that the toolstrip // can be considered as moving. - Point currentLocation = TranslatePoint(mea.Location, ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ScreenCoords); + Point currentLocation = TranslatePoint(mea.Location, ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ScreenCoords); int deltaX = currentLocation.X - startLocation.X; - deltaX = (deltaX < 0) ? deltaX *-1 : deltaX; + deltaX = (deltaX < 0) ? deltaX * -1 : deltaX; - if (DragSize == LayoutUtils.MaxSize) { + if (DragSize == LayoutUtils.MaxSize) + { DragSize = SystemInformation.DragSize; } - - if (deltaX >= DragSize.Width) { + + if (deltaX >= DragSize.Width) + { MovingToolStrip = true; } - else { - int deltaY = currentLocation.Y - startLocation.Y; - deltaY = (deltaY < 0) ? deltaY *-1 : deltaY; + else + { + int deltaY = currentLocation.Y - startLocation.Y; + deltaY = (deltaY < 0) ? deltaY * -1 : deltaY; - if (deltaY >= DragSize.Height) { + if (deltaY >= DragSize.Height) + { MovingToolStrip = true; } } - + } - if (MovingToolStrip) { - if (leftMouseButtonDown) { + if (MovingToolStrip) + { + if (leftMouseButtonDown) + { Point endLocation = TranslatePoint(new Point(mea.X, mea.Y), ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ScreenCoords); // protect against calling when the mouse hasnt really moved. moving the toolstrip/creating the feedback rect // can cause extra mousemove events, we want to make sure we're not doing all this work // for nothing. - if (endLocation != lastEndLocation) { - ToolStripPanelRow.ToolStripPanel.MoveControl(ParentInternal, /*startLocation,*/endLocation ); + if (endLocation != lastEndLocation) + { + ToolStripPanelRow.ToolStripPanel.MoveControl(ParentInternal, /*startLocation,*/endLocation); lastEndLocation = endLocation; - } + } startLocation = endLocation; } - else { + else + { // sometimes we dont get mouseup in DT. Release now. MovingToolStrip = false; } } - + base.OnMouseMove(mea); } - protected override void OnMouseEnter(System.EventArgs e) { + protected override void OnMouseEnter(System.EventArgs e) + { // only switch the cursor if we've got a rafting row. - if ((ParentInternal != null) && (ToolStripPanelRow != null) && (!ParentInternal.IsInDesignMode)) { + if ((ParentInternal != null) && (ToolStripPanelRow != null) && (!ParentInternal.IsInDesignMode)) + { oldCursor = ParentInternal.Cursor; SetCursor(ParentInternal, Cursors.SizeAll); } - else { + else + { oldCursor = null; } base.OnMouseEnter(e); @@ -210,25 +254,31 @@ protected override void OnMouseEnter(System.EventArgs e) { /// /// /// - protected override void OnMouseLeave(System.EventArgs e) { - if (oldCursor != null && !ParentInternal.IsInDesignMode) { - SetCursor(ParentInternal,oldCursor); + protected override void OnMouseLeave(System.EventArgs e) + { + if (oldCursor != null && !ParentInternal.IsInDesignMode) + { + SetCursor(ParentInternal, oldCursor); } - if (!MovingToolStrip && LeftMouseButtonIsDown()) { + if (!MovingToolStrip && LeftMouseButtonIsDown()) + { MovingToolStrip = true; } base.OnMouseLeave(e); } - - - protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs mea) { - if (MovingToolStrip) { + + + protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs mea) + { + if (MovingToolStrip) + { Point endLocation = TranslatePoint(new Point(mea.X, mea.Y), ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ScreenCoords); - ToolStripPanelRow.ToolStripPanel.MoveControl(ParentInternal, /*startLocation,*/endLocation ); + ToolStripPanelRow.ToolStripPanel.MoveControl(ParentInternal, /*startLocation,*/endLocation); } - if (!ParentInternal.IsInDesignMode) { + if (!ParentInternal.IsInDesignMode) + { SetCursor(ParentInternal, oldCursor); } ToolStripPanel.ClearDragFeedback(); @@ -236,45 +286,58 @@ protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs mea) { base.OnMouseUp(mea); } - private static void SetCursor(Control control, Cursor cursor) { + private static void SetCursor(Control control, Cursor cursor) + { control.Cursor = cursor; } - internal class ToolStripGripAccessibleObject : ToolStripButtonAccessibleObject { + internal class ToolStripGripAccessibleObject : ToolStripButtonAccessibleObject + { private string stockName; - public ToolStripGripAccessibleObject(ToolStripGrip owner) : base(owner){ + public ToolStripGripAccessibleObject(ToolStripGrip owner) : base(owner) + { } - public override string Name { - get { + public override string Name + { + get + { string name = Owner.AccessibleName; - if (name != null) { + if (name != null) + { return name; } - if (string.IsNullOrEmpty(stockName)) { + if (string.IsNullOrEmpty(stockName)) + { stockName = SR.ToolStripGripAccessibleName; } return stockName; } - set { - base.Name = value; + set + { + base.Name = value; } } - - public override AccessibleRole Role { - get { - AccessibleRole role = Owner.AccessibleRole; - if (role != AccessibleRole.Default) { - return role; - } - return AccessibleRole.Grip; - } + + public override AccessibleRole Role + { + get + { + AccessibleRole role = Owner.AccessibleRole; + if (role != AccessibleRole.Default) + { + return role; + } + return AccessibleRole.Grip; + } } - internal override object GetPropertyValue(int propertyID) { - switch (propertyID) { + internal override object GetPropertyValue(int propertyID) + { + switch (propertyID) + { case NativeMethods.UIA_IsOffscreenPropertyId: return false; case NativeMethods.UIA_ControlTypePropertyId: @@ -286,5 +349,5 @@ internal override object GetPropertyValue(int propertyID) { } } } - + diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripHighContrastRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripHighContrastRenderer.cs index 9e4b5c1654e..1bb00eb84e8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripHighContrastRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripHighContrastRenderer.cs @@ -16,93 +16,111 @@ #endregion -namespace System.Windows.Forms { - - // this renderer supports high contrast for ToolStripProfessional and ToolStripSystemRenderer. - internal class ToolStripHighContrastRenderer : ToolStripSystemRenderer { - - private const int GRIP_PADDING = 4; - - BitVector32 options = new BitVector32(); - private static readonly int optionsDottedBorder = BitVector32.CreateMask(); - private static readonly int optionsDottedGrip = BitVector32.CreateMask(optionsDottedBorder); - private static readonly int optionsFillWhenSelected = BitVector32.CreateMask(optionsDottedGrip); - - public ToolStripHighContrastRenderer(bool systemRenderMode) { - options[optionsDottedBorder | optionsDottedGrip | optionsFillWhenSelected] = !systemRenderMode; - } - - public bool DottedBorder { - get { return options[optionsDottedBorder]; } - } - public bool DottedGrip { - get { return options[optionsDottedGrip]; } - } - public bool FillWhenSelected{ - get { return options[optionsFillWhenSelected]; } - } +namespace System.Windows.Forms +{ + + // this renderer supports high contrast for ToolStripProfessional and ToolStripSystemRenderer. + internal class ToolStripHighContrastRenderer : ToolStripSystemRenderer + { + + private const int GRIP_PADDING = 4; + + BitVector32 options = new BitVector32(); + private static readonly int optionsDottedBorder = BitVector32.CreateMask(); + private static readonly int optionsDottedGrip = BitVector32.CreateMask(optionsDottedBorder); + private static readonly int optionsFillWhenSelected = BitVector32.CreateMask(optionsDottedGrip); + + public ToolStripHighContrastRenderer(bool systemRenderMode) + { + options[optionsDottedBorder | optionsDottedGrip | optionsFillWhenSelected] = !systemRenderMode; + } + + public bool DottedBorder + { + get { return options[optionsDottedBorder]; } + } + public bool DottedGrip + { + get { return options[optionsDottedGrip]; } + } + public bool FillWhenSelected + { + get { return options[optionsFillWhenSelected]; } + } // this is a renderer override, so return null so we dont get into an infinite loop. - internal override ToolStripRenderer RendererOverride { + internal override ToolStripRenderer RendererOverride + { get { return null; } } - - protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e) { + + protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e) + { base.OnRenderArrow(e); } - protected override void OnRenderGrip(ToolStripGripRenderEventArgs e) { + protected override void OnRenderGrip(ToolStripGripRenderEventArgs e) + { + + if (DottedGrip) + { + Graphics g = e.Graphics; + Rectangle bounds = e.GripBounds; + ToolStrip toolStrip = e.ToolStrip; + + int height = (toolStrip.Orientation == Orientation.Horizontal) ? bounds.Height : bounds.Width; + int width = (toolStrip.Orientation == Orientation.Horizontal) ? bounds.Width : bounds.Height; - if (DottedGrip) { - Graphics g = e.Graphics; - Rectangle bounds = e.GripBounds; - ToolStrip toolStrip = e.ToolStrip; + int numRectangles = (height - (GRIP_PADDING * 2)) / 4; - int height = (toolStrip.Orientation == Orientation.Horizontal) ? bounds.Height : bounds.Width; - int width = (toolStrip.Orientation == Orientation.Horizontal) ? bounds.Width : bounds.Height; + if (numRectangles > 0) + { + Rectangle[] shadowRects = new Rectangle[numRectangles]; + int startY = GRIP_PADDING; + int startX = (width / 2); - int numRectangles = (height - (GRIP_PADDING * 2)) / 4; + for (int i = 0; i < numRectangles; i++) + { + shadowRects[i] = (toolStrip.Orientation == Orientation.Horizontal) ? + new Rectangle(startX, startY, 2, 2) : + new Rectangle(startY, startX, 2, 2); - if (numRectangles > 0) { - Rectangle[] shadowRects = new Rectangle[numRectangles]; - int startY = GRIP_PADDING; - int startX = (width / 2); + startY += 4; + } + + g.FillRectangles(SystemBrushes.ControlLight, shadowRects); - for (int i = 0; i < numRectangles; i++) { - shadowRects[i] = (toolStrip.Orientation == Orientation.Horizontal) ? - new Rectangle(startX, startY, 2, 2) : - new Rectangle(startY, startX, 2, 2); - startY += 4; - } - g.FillRectangles(SystemBrushes.ControlLight, shadowRects); + } + } + else + { + base.OnRenderGrip(e); + } + } + protected override void OnRenderDropDownButtonBackground(ToolStripItemRenderEventArgs e) + { - } - } - else { - base.OnRenderGrip(e); - } - } + if (FillWhenSelected) + { + RenderItemInternalFilled(e, false); + } + else + { + base.OnRenderDropDownButtonBackground(e); + if (e.Item.Pressed) + { + e.Graphics.DrawRectangle(SystemPens.ButtonHighlight, new Rectangle(0, 0, e.Item.Width - 1, e.Item.Height - 1)); + } + } - - protected override void OnRenderDropDownButtonBackground(ToolStripItemRenderEventArgs e) { - - if (FillWhenSelected) { - RenderItemInternalFilled(e, false); - } - else { - base.OnRenderDropDownButtonBackground(e); - if (e.Item.Pressed) { - e.Graphics.DrawRectangle(SystemPens.ButtonHighlight, new Rectangle(0, 0, e.Item.Width - 1, e.Item.Height - 1)); - } - } - - } + } - protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) { + protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) + { // The ARGB values came directly from the bitmap. // If the bitmap colors change this code will no longer work and will // need to be updated. @@ -125,84 +143,104 @@ protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) { e.ImageAttributes = imageAttr; base.OnRenderItemCheck(e); - } - - protected override void OnRenderImageMargin(ToolStripRenderEventArgs e) { - // do nothing - } - protected override void OnRenderItemBackground(ToolStripItemRenderEventArgs e) { - base.OnRenderItemBackground(e); - } - - protected override void OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs e) { - ToolStripSplitButton item = e.Item as ToolStripSplitButton; - Rectangle bounds = new Rectangle(Point.Empty, e.Item.Size); - Graphics g = e.Graphics; - - if (item != null) { - Rectangle dropDownRect = item.DropDownButtonBounds; - - if (item.Pressed) { - g.DrawRectangle(SystemPens.ButtonHighlight, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); - - } - else if (item.Selected) { - g.FillRectangle(SystemBrushes.Highlight, bounds); - g.DrawRectangle(SystemPens.ButtonHighlight, bounds.X, bounds.Y, bounds.Width-1, bounds.Height -1); - g.DrawRectangle(SystemPens.ButtonHighlight, dropDownRect); - } - - Color arrowColor = item.Selected && !item.Pressed ? SystemColors.HighlightText : SystemColors.ControlText; - DrawArrow(new ToolStripArrowRenderEventArgs(g, item, dropDownRect, arrowColor, ArrowDirection.Down)); - } - } - - protected override void OnRenderStatusStripSizingGrip(ToolStripRenderEventArgs e) { - base.OnRenderStatusStripSizingGrip(e); - } - - protected override void OnRenderLabelBackground(ToolStripItemRenderEventArgs e) { - if (FillWhenSelected) { - RenderItemInternalFilled(e); - } - else { - base.OnRenderLabelBackground(e); - } - } - protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) { - - base.OnRenderMenuItemBackground(e); - if (!e.Item.IsOnDropDown && e.Item.Pressed) { - e.Graphics.DrawRectangle(SystemPens.ButtonHighlight, 0, 0, e.Item.Width - 1, e.Item.Height - 1); - } - } - protected override void OnRenderOverflowButtonBackground(ToolStripItemRenderEventArgs e) { - if (FillWhenSelected) { - - RenderItemInternalFilled(e, /*pressFill = */false); - ToolStripItem item = e.Item; - Graphics g = e.Graphics; - Color arrowColor = item.Enabled ? SystemColors.ControlText : SystemColors.ControlDark; - DrawArrow(new ToolStripArrowRenderEventArgs(g, item, new Rectangle(Point.Empty, item.Size), arrowColor, ArrowDirection.Down)); - - - } - else { - base.OnRenderOverflowButtonBackground(e); - } - } - - protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e) { - - if (e.Item.Selected && (!e.Item.Pressed || e.Item is ToolStripButton)) { + } + + protected override void OnRenderImageMargin(ToolStripRenderEventArgs e) + { + // do nothing + } + protected override void OnRenderItemBackground(ToolStripItemRenderEventArgs e) + { + base.OnRenderItemBackground(e); + } + + protected override void OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs e) + { + ToolStripSplitButton item = e.Item as ToolStripSplitButton; + Rectangle bounds = new Rectangle(Point.Empty, e.Item.Size); + Graphics g = e.Graphics; + + if (item != null) + { + Rectangle dropDownRect = item.DropDownButtonBounds; + + if (item.Pressed) + { + g.DrawRectangle(SystemPens.ButtonHighlight, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); + + } + else if (item.Selected) + { + g.FillRectangle(SystemBrushes.Highlight, bounds); + g.DrawRectangle(SystemPens.ButtonHighlight, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); + g.DrawRectangle(SystemPens.ButtonHighlight, dropDownRect); + } + + Color arrowColor = item.Selected && !item.Pressed ? SystemColors.HighlightText : SystemColors.ControlText; + DrawArrow(new ToolStripArrowRenderEventArgs(g, item, dropDownRect, arrowColor, ArrowDirection.Down)); + } + } + + protected override void OnRenderStatusStripSizingGrip(ToolStripRenderEventArgs e) + { + base.OnRenderStatusStripSizingGrip(e); + } + + protected override void OnRenderLabelBackground(ToolStripItemRenderEventArgs e) + { + if (FillWhenSelected) + { + RenderItemInternalFilled(e); + } + else + { + base.OnRenderLabelBackground(e); + } + } + protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) + { + + base.OnRenderMenuItemBackground(e); + if (!e.Item.IsOnDropDown && e.Item.Pressed) + { + e.Graphics.DrawRectangle(SystemPens.ButtonHighlight, 0, 0, e.Item.Width - 1, e.Item.Height - 1); + } + } + protected override void OnRenderOverflowButtonBackground(ToolStripItemRenderEventArgs e) + { + if (FillWhenSelected) + { + + RenderItemInternalFilled(e, /*pressFill = */false); + ToolStripItem item = e.Item; + Graphics g = e.Graphics; + Color arrowColor = item.Enabled ? SystemColors.ControlText : SystemColors.ControlDark; + DrawArrow(new ToolStripArrowRenderEventArgs(g, item, new Rectangle(Point.Empty, item.Size), arrowColor, ArrowDirection.Down)); + + + } + else + { + base.OnRenderOverflowButtonBackground(e); + } + } + + protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e) + { + + if (e.Item.Selected && (!e.Item.Pressed || e.Item is ToolStripButton)) + { e.DefaultTextColor = SystemColors.HighlightText; } - else if (e.TextColor != SystemColors.HighlightText && e.TextColor != SystemColors.ControlText) { + else if (e.TextColor != SystemColors.HighlightText && e.TextColor != SystemColors.ControlText) + { // we'll change the DefaultTextColor, if someone wants to change this,manually set the TextColor property. - if (e.Item.Selected || e.Item.Pressed) { + if (e.Item.Selected || e.Item.Pressed) + { e.DefaultTextColor = SystemColors.HighlightText; } - else { + else + { e.DefaultTextColor = SystemColors.ControlText; } } @@ -212,229 +250,270 @@ protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e) { // background. In that case, set the text color to highlight as well. if (typeof(ToolStripButton).IsAssignableFrom(e.Item.GetType()) && ((ToolStripButton)e.Item).DisplayStyle != ToolStripItemDisplayStyle.Image && - ((ToolStripButton)e.Item).Checked) { + ((ToolStripButton)e.Item).Checked) + { e.TextColor = SystemColors.HighlightText; } - + base.OnRenderItemText(e); } - protected override void OnRenderToolStripBackground(ToolStripRenderEventArgs e) { + protected override void OnRenderToolStripBackground(ToolStripRenderEventArgs e) + { // do nothing. LOGO requirements ask us not to paint background effects behind } - protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) { - Rectangle bounds = new Rectangle(Point.Empty, e.ToolStrip.Size); - Graphics g = e.Graphics; - - - if (e.ToolStrip is ToolStripDropDown) { - - g.DrawRectangle(SystemPens.ButtonHighlight, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); - - if (!(e.ToolStrip is ToolStripOverflow)) { - // make the neck connected. - g.FillRectangle(SystemBrushes.Control, e.ConnectedArea); - - } - } - else if (e.ToolStrip is MenuStrip) { - // do nothing - } - else if (e.ToolStrip is StatusStrip) { - g.DrawRectangle(SystemPens.ButtonShadow, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); - - } - else { - RenderToolStripBackgroundInternal(e); - } - } - - private void RenderToolStripBackgroundInternal(ToolStripRenderEventArgs e) { - Rectangle bounds = new Rectangle(Point.Empty, e.ToolStrip.Size); - Graphics g = e.Graphics; - - if (DottedBorder) { - - using (Pen p = new Pen(SystemColors.ButtonShadow)) { - p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot; - - bool oddWidth = ((bounds.Width & 0x1) == 0x1); - bool oddHeight = ((bounds.Height & 0x1) == 0x1); - int indent = 2; - - // top - g.DrawLine(p, bounds.X + indent, bounds.Y, bounds.Width - 1, bounds.Y); - // bottom - g.DrawLine(p, bounds.X + indent, bounds.Height - 1, bounds.Width - 1, bounds.Height - 1); - - // left - g.DrawLine(p, bounds.X, bounds.Y + indent, bounds.X, bounds.Height - 1); - // right - g.DrawLine(p, bounds.Width - 1, bounds.Y + indent, bounds.Width - 1, bounds.Height - 1); - - // connecting pixels - - // top left conntecting pixel - always drawn - g.FillRectangle(SystemBrushes.ButtonShadow, new Rectangle(1, 1, 1, 1)); - - if (oddWidth) { - // top right pixel - g.FillRectangle(SystemBrushes.ButtonShadow, new Rectangle(bounds.Width - 2, 1, 1, 1)); - } - // bottom conntecting pixels - drawn only if height is odd - if (oddHeight) { - // bottom left - g.FillRectangle(SystemBrushes.ButtonShadow, new Rectangle(1, bounds.Height - 2, 1, 1)); - - } - - // top and bottom right conntecting pixel - drawn only if height and width are odd - if (oddHeight && oddWidth) { - // bottom right - g.FillRectangle(SystemBrushes.ButtonShadow, new Rectangle(bounds.Width - 2, bounds.Height - 2, 1, 1)); - } - - } - } - else { - // draw solid border - bounds.Width -= 1; - bounds.Height -= 1; - g.DrawRectangle(SystemPens.ButtonShadow, bounds); - } - - } - protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e) { - - Pen foreColorPen = SystemPens.ButtonShadow; - - Graphics g = e.Graphics; - Rectangle bounds = new Rectangle(Point.Empty, e.Item.Size); - - - if (e.Vertical) { - if (bounds.Height >= 8) { - bounds.Inflate(0, -4); // scoot down 4PX and start drawing - } - // Draw dark line - int startX = bounds.Width / 2; - - g.DrawLine(foreColorPen, startX, bounds.Top, startX, bounds.Bottom - 1); - - } - else { - // - // horizontal separator - if (bounds.Width >= 4) { - bounds.Inflate(-2, 0); // scoot over 2PX and start drawing - } - - // Draw dark line - int startY = bounds.Height / 2; - - g.DrawLine(foreColorPen, bounds.Left, startY, bounds.Right - 1, startY); - - } - - } - - // Indicates whether system is currently set to high contrast 'white on black' mode - internal static bool IsHighContrastWhiteOnBlack() - { - return SystemColors.Control.ToArgb() == Color.Black.ToArgb(); - } - - protected override void OnRenderItemImage(ToolStripItemImageRenderEventArgs e) { - Image image = e.Image; - if (image != null) { - if (Image.GetPixelFormatSize(image.PixelFormat) > 16) { + protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) + { + Rectangle bounds = new Rectangle(Point.Empty, e.ToolStrip.Size); + Graphics g = e.Graphics; + + + if (e.ToolStrip is ToolStripDropDown) + { + + g.DrawRectangle(SystemPens.ButtonHighlight, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); + + if (!(e.ToolStrip is ToolStripOverflow)) + { + // make the neck connected. + g.FillRectangle(SystemBrushes.Control, e.ConnectedArea); + + } + } + else if (e.ToolStrip is MenuStrip) + { + // do nothing + } + else if (e.ToolStrip is StatusStrip) + { + g.DrawRectangle(SystemPens.ButtonShadow, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); + + } + else + { + RenderToolStripBackgroundInternal(e); + } + } + + private void RenderToolStripBackgroundInternal(ToolStripRenderEventArgs e) + { + Rectangle bounds = new Rectangle(Point.Empty, e.ToolStrip.Size); + Graphics g = e.Graphics; + + if (DottedBorder) + { + + using (Pen p = new Pen(SystemColors.ButtonShadow)) + { + p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot; + + bool oddWidth = ((bounds.Width & 0x1) == 0x1); + bool oddHeight = ((bounds.Height & 0x1) == 0x1); + int indent = 2; + + // top + g.DrawLine(p, bounds.X + indent, bounds.Y, bounds.Width - 1, bounds.Y); + // bottom + g.DrawLine(p, bounds.X + indent, bounds.Height - 1, bounds.Width - 1, bounds.Height - 1); + + // left + g.DrawLine(p, bounds.X, bounds.Y + indent, bounds.X, bounds.Height - 1); + // right + g.DrawLine(p, bounds.Width - 1, bounds.Y + indent, bounds.Width - 1, bounds.Height - 1); + + // connecting pixels + + // top left conntecting pixel - always drawn + g.FillRectangle(SystemBrushes.ButtonShadow, new Rectangle(1, 1, 1, 1)); + + if (oddWidth) + { + // top right pixel + g.FillRectangle(SystemBrushes.ButtonShadow, new Rectangle(bounds.Width - 2, 1, 1, 1)); + } + // bottom conntecting pixels - drawn only if height is odd + if (oddHeight) + { + // bottom left + g.FillRectangle(SystemBrushes.ButtonShadow, new Rectangle(1, bounds.Height - 2, 1, 1)); + + } + + // top and bottom right conntecting pixel - drawn only if height and width are odd + if (oddHeight && oddWidth) + { + // bottom right + g.FillRectangle(SystemBrushes.ButtonShadow, new Rectangle(bounds.Width - 2, bounds.Height - 2, 1, 1)); + } + + } + } + else + { + // draw solid border + bounds.Width -= 1; + bounds.Height -= 1; + g.DrawRectangle(SystemPens.ButtonShadow, bounds); + } + + } + protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e) + { + + Pen foreColorPen = SystemPens.ButtonShadow; + + Graphics g = e.Graphics; + Rectangle bounds = new Rectangle(Point.Empty, e.Item.Size); + + + if (e.Vertical) + { + if (bounds.Height >= 8) + { + bounds.Inflate(0, -4); // scoot down 4PX and start drawing + } + // Draw dark line + int startX = bounds.Width / 2; + + g.DrawLine(foreColorPen, startX, bounds.Top, startX, bounds.Bottom - 1); + + } + else + { + // + // horizontal separator + if (bounds.Width >= 4) + { + bounds.Inflate(-2, 0); // scoot over 2PX and start drawing + } + + // Draw dark line + int startY = bounds.Height / 2; + + g.DrawLine(foreColorPen, bounds.Left, startY, bounds.Right - 1, startY); + + } + + } + + // Indicates whether system is currently set to high contrast 'white on black' mode + internal static bool IsHighContrastWhiteOnBlack() + { + return SystemColors.Control.ToArgb() == Color.Black.ToArgb(); + } + + protected override void OnRenderItemImage(ToolStripItemImageRenderEventArgs e) + { + Image image = e.Image; + if (image != null) + { + if (Image.GetPixelFormatSize(image.PixelFormat) > 16) + { // for 24, 32 bit images, just paint normally - mapping the color table is not // going to work when you can have full color. base.OnRenderItemImage(e); return; } - Graphics g = e.Graphics; - - ToolStripItem item = e.Item; - Rectangle imageRect = e.ImageRectangle; - using (ImageAttributes attrs = new ImageAttributes()) { - if (IsHighContrastWhiteOnBlack() && !(FillWhenSelected && (e.Item.Pressed || e.Item.Selected))) { - // translate white, black and blue to colors visible in high contrast mode. - ColorMap cm1 = new ColorMap(); - ColorMap cm2 = new ColorMap(); - ColorMap cm3 = new ColorMap(); - - cm1.OldColor = Color.Black; - cm1.NewColor = Color.White; - cm2.OldColor = Color.White; - cm2.NewColor = Color.Black; - cm3.OldColor = Color.FromArgb(0, 0, 128); - cm3.NewColor = Color.White; - - - attrs.SetRemapTable(new ColorMap[] { cm1, cm2, cm3 }, ColorAdjustType.Bitmap); - } - if (item.ImageScaling == ToolStripItemImageScaling.None) { - g.DrawImage(image, imageRect, 0, 0, imageRect.Width, imageRect.Height, GraphicsUnit.Pixel, attrs); - } - else { - g.DrawImage(image, imageRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attrs); - } - } - } - } - - protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e) { - if (FillWhenSelected) { + Graphics g = e.Graphics; + + ToolStripItem item = e.Item; + Rectangle imageRect = e.ImageRectangle; + using (ImageAttributes attrs = new ImageAttributes()) + { + if (IsHighContrastWhiteOnBlack() && !(FillWhenSelected && (e.Item.Pressed || e.Item.Selected))) + { + // translate white, black and blue to colors visible in high contrast mode. + ColorMap cm1 = new ColorMap(); + ColorMap cm2 = new ColorMap(); + ColorMap cm3 = new ColorMap(); + + cm1.OldColor = Color.Black; + cm1.NewColor = Color.White; + cm2.OldColor = Color.White; + cm2.NewColor = Color.Black; + cm3.OldColor = Color.FromArgb(0, 0, 128); + cm3.NewColor = Color.White; + + + attrs.SetRemapTable(new ColorMap[] { cm1, cm2, cm3 }, ColorAdjustType.Bitmap); + } + if (item.ImageScaling == ToolStripItemImageScaling.None) + { + g.DrawImage(image, imageRect, 0, 0, imageRect.Width, imageRect.Height, GraphicsUnit.Pixel, attrs); + } + else + { + g.DrawImage(image, imageRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attrs); + } + } + } + } + + protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e) + { + if (FillWhenSelected) + { ToolStripButton button = e.Item as ToolStripButton; - if (button != null && button.Checked) { + if (button != null && button.Checked) + { Graphics g = e.Graphics; Rectangle bounds = new Rectangle(Point.Empty, e.Item.Size); - if (button.CheckState == CheckState.Checked) { + if (button.CheckState == CheckState.Checked) + { g.FillRectangle(SystemBrushes.Highlight, bounds); } - if (button.Selected) { + if (button.Selected) + { g.DrawRectangle(SystemPens.Highlight, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); } - else { + else + { g.DrawRectangle(SystemPens.ControlLight, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); } } - else { - RenderItemInternalFilled(e); + else + { + RenderItemInternalFilled(e); } - } - else { - base.OnRenderButtonBackground(e); - } - } - - private void RenderItemInternalFilled(ToolStripItemRenderEventArgs e) { - RenderItemInternalFilled(e, /*pressFill=*/true); - } - - private void RenderItemInternalFilled(ToolStripItemRenderEventArgs e, bool pressFill) { - Graphics g = e.Graphics; - Rectangle bounds = new Rectangle(Point.Empty, e.Item.Size); - - if (e.Item.Pressed) { - if (pressFill) { - g.FillRectangle(SystemBrushes.Highlight, bounds); - } - else { - g.DrawRectangle(SystemPens.ControlLight, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); - } - } - else if (e.Item.Selected) { - g.FillRectangle(SystemBrushes.Highlight, bounds); - g.DrawRectangle(SystemPens.ControlLight, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); - } - - - } - - } + } + else + { + base.OnRenderButtonBackground(e); + } + } + + private void RenderItemInternalFilled(ToolStripItemRenderEventArgs e) + { + RenderItemInternalFilled(e, /*pressFill=*/true); + } + + private void RenderItemInternalFilled(ToolStripItemRenderEventArgs e, bool pressFill) + { + Graphics g = e.Graphics; + Rectangle bounds = new Rectangle(Point.Empty, e.Item.Size); + + if (e.Item.Pressed) + { + if (pressFill) + { + g.FillRectangle(SystemBrushes.Highlight, bounds); + } + else + { + g.DrawRectangle(SystemPens.ControlLight, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); + } + } + else if (e.Item.Selected) + { + g.FillRectangle(SystemBrushes.Highlight, bounds); + g.DrawRectangle(SystemPens.ControlLight, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); + } + + + } + + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs index ef05d35110e..960a19ef8f9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs @@ -5,7 +5,8 @@ //#define SELECTEDCHANGED -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Drawing; using System.Windows.Forms.Internal; @@ -17,7 +18,7 @@ namespace System.Windows.Forms { using System.Windows.Forms.Layout; using System.Collections.Specialized; using System.Drawing.Design; - using System.Configuration; + using System.Configuration; using System.Drawing.Imaging; using System.Diagnostics.CodeAnalysis; using System.Globalization; @@ -30,183 +31,189 @@ namespace System.Windows.Forms { [DefaultEvent(nameof(Click))] [ToolboxItem(false)] [DefaultProperty(nameof(Text))] - public abstract class ToolStripItem : Component, - IDropTarget, + public abstract class ToolStripItem : Component, + IDropTarget, ISupportOleDropSource, IArrangedElement, - IKeyboardToolTip { - - + IKeyboardToolTip + { - -#if DEBUG - internal static readonly TraceSwitch MouseDebugging = new TraceSwitch("MouseDebugging", "Debug ToolStripItem mouse debugging code"); + + + +#if DEBUG + internal static readonly TraceSwitch MouseDebugging = new TraceSwitch("MouseDebugging", "Debug ToolStripItem mouse debugging code"); #else internal static readonly TraceSwitch MouseDebugging; #endif - - private Rectangle bounds = Rectangle.Empty; - private PropertyStore propertyStore; - private ToolStripItemAlignment alignment = ToolStripItemAlignment.Left; - private ToolStrip parent = null; - private ToolStrip owner = null; - private ToolStripItemOverflow overflow = ToolStripItemOverflow.AsNeeded; - private ToolStripItemPlacement placement = ToolStripItemPlacement.None; - private ContentAlignment imageAlign = ContentAlignment.MiddleCenter; - private ContentAlignment textAlign = ContentAlignment.MiddleCenter; - private TextImageRelation textImageRelation = TextImageRelation.ImageBeforeText; - private ToolStripItemImageIndexer imageIndexer = null; - private ToolStripItemInternalLayout toolStripItemInternalLayout = null; - private BitVector32 state = new BitVector32(); - private string toolTipText = null; - private Color imageTransparentColor = Color.Empty; + + private Rectangle bounds = Rectangle.Empty; + private PropertyStore propertyStore; + private ToolStripItemAlignment alignment = ToolStripItemAlignment.Left; + private ToolStrip parent = null; + private ToolStrip owner = null; + private ToolStripItemOverflow overflow = ToolStripItemOverflow.AsNeeded; + private ToolStripItemPlacement placement = ToolStripItemPlacement.None; + private ContentAlignment imageAlign = ContentAlignment.MiddleCenter; + private ContentAlignment textAlign = ContentAlignment.MiddleCenter; + private TextImageRelation textImageRelation = TextImageRelation.ImageBeforeText; + private ToolStripItemImageIndexer imageIndexer = null; + private ToolStripItemInternalLayout toolStripItemInternalLayout = null; + private BitVector32 state = new BitVector32(); + private string toolTipText = null; + private Color imageTransparentColor = Color.Empty; private ToolStripItemImageScaling imageScaling = ToolStripItemImageScaling.SizeToFit; - private Size cachedTextSize = Size.Empty; - - private static readonly Padding defaultMargin = new Padding(0, 1, 0, 2); - private static readonly Padding defaultStatusStripMargin = new Padding(0, 2, 0, 0); - private Padding scaledDefaultMargin = defaultMargin; - private Padding scaledDefaultStatusStripMargin = defaultStatusStripMargin; + private Size cachedTextSize = Size.Empty; + + private static readonly Padding defaultMargin = new Padding(0, 1, 0, 2); + private static readonly Padding defaultStatusStripMargin = new Padding(0, 2, 0, 0); + private Padding scaledDefaultMargin = defaultMargin; + private Padding scaledDefaultStatusStripMargin = defaultStatusStripMargin; - private ToolStripItemDisplayStyle displayStyle = ToolStripItemDisplayStyle.ImageAndText; + private ToolStripItemDisplayStyle displayStyle = ToolStripItemDisplayStyle.ImageAndText; - private static readonly ArrangedElementCollection EmptyChildCollection = new ArrangedElementCollection(); + private static readonly ArrangedElementCollection EmptyChildCollection = new ArrangedElementCollection(); /// /// Adding a new event?? Make sure you dont need to add to ToolStripControlHost.cs /// - internal static readonly object EventMouseDown = new object(); - internal static readonly object EventMouseEnter = new object(); - internal static readonly object EventMouseLeave = new object(); - internal static readonly object EventMouseHover = new object(); - internal static readonly object EventMouseMove = new object(); - internal static readonly object EventMouseUp = new object(); - internal static readonly object EventMouseWheel = new object(); - internal static readonly object EventClick = new object(); - internal static readonly object EventDoubleClick = new object(); - internal static readonly object EventDragDrop = new object(); - internal static readonly object EventDragEnter = new object(); - internal static readonly object EventDragLeave = new object(); - internal static readonly object EventDragOver = new object(); - internal static readonly object EventDisplayStyleChanged = new object(); - internal static readonly object EventEnabledChanged = new object(); - internal static readonly object EventInternalEnabledChanged = new object(); - internal static readonly object EventFontChanged = new object(); - internal static readonly object EventForeColorChanged = new object(); - internal static readonly object EventBackColorChanged = new object(); - internal static readonly object EventGiveFeedback = new object(); - internal static readonly object EventQueryContinueDrag = new object(); - internal static readonly object EventQueryAccessibilityHelp = new object(); - internal static readonly object EventMove = new object(); - internal static readonly object EventResize = new object(); - internal static readonly object EventLayout = new object(); - internal static readonly object EventLocationChanged = new object(); - internal static readonly object EventRightToLeft = new object(); - internal static readonly object EventVisibleChanged = new object(); - internal static readonly object EventAvailableChanged = new object(); - internal static readonly object EventOwnerChanged = new object(); - internal static readonly object EventPaint = new object(); - internal static readonly object EventText = new object(); - internal static readonly object EventSelectedChanged = new object(); - + internal static readonly object EventMouseDown = new object(); + internal static readonly object EventMouseEnter = new object(); + internal static readonly object EventMouseLeave = new object(); + internal static readonly object EventMouseHover = new object(); + internal static readonly object EventMouseMove = new object(); + internal static readonly object EventMouseUp = new object(); + internal static readonly object EventMouseWheel = new object(); + internal static readonly object EventClick = new object(); + internal static readonly object EventDoubleClick = new object(); + internal static readonly object EventDragDrop = new object(); + internal static readonly object EventDragEnter = new object(); + internal static readonly object EventDragLeave = new object(); + internal static readonly object EventDragOver = new object(); + internal static readonly object EventDisplayStyleChanged = new object(); + internal static readonly object EventEnabledChanged = new object(); + internal static readonly object EventInternalEnabledChanged = new object(); + internal static readonly object EventFontChanged = new object(); + internal static readonly object EventForeColorChanged = new object(); + internal static readonly object EventBackColorChanged = new object(); + internal static readonly object EventGiveFeedback = new object(); + internal static readonly object EventQueryContinueDrag = new object(); + internal static readonly object EventQueryAccessibilityHelp = new object(); + internal static readonly object EventMove = new object(); + internal static readonly object EventResize = new object(); + internal static readonly object EventLayout = new object(); + internal static readonly object EventLocationChanged = new object(); + internal static readonly object EventRightToLeft = new object(); + internal static readonly object EventVisibleChanged = new object(); + internal static readonly object EventAvailableChanged = new object(); + internal static readonly object EventOwnerChanged = new object(); + internal static readonly object EventPaint = new object(); + internal static readonly object EventText = new object(); + internal static readonly object EventSelectedChanged = new object(); + /// /// Adding a new event?? Make sure you dont need to add to ToolStripControlHost.cs /// - + // 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 PropText = PropertyStore.CreateKey(); - private static readonly int PropBackColor = PropertyStore.CreateKey(); - private static readonly int PropForeColor = PropertyStore.CreateKey(); - - private static readonly int PropImage = PropertyStore.CreateKey(); - private static readonly int PropFont = PropertyStore.CreateKey(); - private static readonly int PropRightToLeft = PropertyStore.CreateKey(); - private static readonly int PropTag = PropertyStore.CreateKey(); - - private static readonly int PropAccessibility = PropertyStore.CreateKey(); - private static readonly int PropAccessibleName = PropertyStore.CreateKey(); - private static readonly int PropAccessibleRole = PropertyStore.CreateKey(); - private static readonly int PropAccessibleHelpProvider = PropertyStore.CreateKey(); - - private static readonly int PropAccessibleDefaultActionDescription = PropertyStore.CreateKey(); - private static readonly int PropAccessibleDescription = PropertyStore.CreateKey(); - private static readonly int PropTextDirection = PropertyStore.CreateKey(); - private static readonly int PropMirroredImage = PropertyStore.CreateKey(); - - - private static readonly int PropBackgroundImage = PropertyStore.CreateKey(); - private static readonly int PropBackgroundImageLayout = PropertyStore.CreateKey(); - - private static readonly int PropMergeAction = PropertyStore.CreateKey(); - private static readonly int PropMergeIndex = PropertyStore.CreateKey(); - - - private static readonly int stateAllowDrop = BitVector32.CreateMask(); - private static readonly int stateVisible = BitVector32.CreateMask(stateAllowDrop); - private static readonly int stateEnabled = BitVector32.CreateMask(stateVisible); + private static readonly int PropName = PropertyStore.CreateKey(); + private static readonly int PropText = PropertyStore.CreateKey(); + private static readonly int PropBackColor = PropertyStore.CreateKey(); + private static readonly int PropForeColor = PropertyStore.CreateKey(); + + private static readonly int PropImage = PropertyStore.CreateKey(); + private static readonly int PropFont = PropertyStore.CreateKey(); + private static readonly int PropRightToLeft = PropertyStore.CreateKey(); + private static readonly int PropTag = PropertyStore.CreateKey(); + + private static readonly int PropAccessibility = PropertyStore.CreateKey(); + private static readonly int PropAccessibleName = PropertyStore.CreateKey(); + private static readonly int PropAccessibleRole = PropertyStore.CreateKey(); + private static readonly int PropAccessibleHelpProvider = PropertyStore.CreateKey(); + + private static readonly int PropAccessibleDefaultActionDescription = PropertyStore.CreateKey(); + private static readonly int PropAccessibleDescription = PropertyStore.CreateKey(); + private static readonly int PropTextDirection = PropertyStore.CreateKey(); + private static readonly int PropMirroredImage = PropertyStore.CreateKey(); + + + private static readonly int PropBackgroundImage = PropertyStore.CreateKey(); + private static readonly int PropBackgroundImageLayout = PropertyStore.CreateKey(); + + private static readonly int PropMergeAction = PropertyStore.CreateKey(); + private static readonly int PropMergeIndex = PropertyStore.CreateKey(); + + + private static readonly int stateAllowDrop = BitVector32.CreateMask(); + private static readonly int stateVisible = BitVector32.CreateMask(stateAllowDrop); + private static readonly int stateEnabled = BitVector32.CreateMask(stateVisible); private static readonly int stateMouseDownAndNoDrag = BitVector32.CreateMask(stateEnabled); - private static readonly int stateAutoSize = BitVector32.CreateMask(stateMouseDownAndNoDrag); - private static readonly int statePressed = BitVector32.CreateMask(stateAutoSize); - private static readonly int stateSelected = BitVector32.CreateMask(statePressed); - private static readonly int stateContstructing = BitVector32.CreateMask(stateSelected); - private static readonly int stateDisposed = BitVector32.CreateMask(stateContstructing); + private static readonly int stateAutoSize = BitVector32.CreateMask(stateMouseDownAndNoDrag); + private static readonly int statePressed = BitVector32.CreateMask(stateAutoSize); + private static readonly int stateSelected = BitVector32.CreateMask(statePressed); + private static readonly int stateContstructing = BitVector32.CreateMask(stateSelected); + private static readonly int stateDisposed = BitVector32.CreateMask(stateContstructing); private static readonly int stateCurrentlyAnimatingImage = BitVector32.CreateMask(stateDisposed); private static readonly int stateDoubleClickEnabled = BitVector32.CreateMask(stateCurrentlyAnimatingImage); - private static readonly int stateAutoToolTip = BitVector32.CreateMask(stateDoubleClickEnabled); + private static readonly int stateAutoToolTip = BitVector32.CreateMask(stateDoubleClickEnabled); private static readonly int stateSupportsRightClick = BitVector32.CreateMask(stateAutoToolTip); private static readonly int stateSupportsItemClick = BitVector32.CreateMask(stateSupportsRightClick); private static readonly int stateRightToLeftAutoMirrorImage = BitVector32.CreateMask(stateSupportsItemClick); private static readonly int stateInvalidMirroredImage = BitVector32.CreateMask(stateRightToLeftAutoMirrorImage); - private static readonly int stateSupportsSpaceKey = BitVector32.CreateMask(stateInvalidMirroredImage); - private static readonly int stateMouseDownAndUpMustBeInSameItem = BitVector32.CreateMask(stateSupportsSpaceKey); - private static readonly int stateSupportsDisabledHotTracking = BitVector32.CreateMask(stateMouseDownAndUpMustBeInSameItem); - private static readonly int stateUseAmbientMargin = BitVector32.CreateMask(stateSupportsDisabledHotTracking); - private static readonly int stateDisposing = BitVector32.CreateMask(stateUseAmbientMargin); + private static readonly int stateSupportsSpaceKey = BitVector32.CreateMask(stateInvalidMirroredImage); + private static readonly int stateMouseDownAndUpMustBeInSameItem = BitVector32.CreateMask(stateSupportsSpaceKey); + private static readonly int stateSupportsDisabledHotTracking = BitVector32.CreateMask(stateMouseDownAndUpMustBeInSameItem); + private static readonly int stateUseAmbientMargin = BitVector32.CreateMask(stateSupportsDisabledHotTracking); + private static readonly int stateDisposing = BitVector32.CreateMask(stateUseAmbientMargin); + - private long lastClickTime = 0; - + /// /// Constructor /// [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] - protected ToolStripItem() { - if (DpiHelper.IsScalingRequirementMet) { + protected ToolStripItem() + { + if (DpiHelper.IsScalingRequirementMet) + { scaledDefaultMargin = DpiHelper.LogicalToDeviceUnits(defaultMargin); scaledDefaultStatusStripMargin = DpiHelper.LogicalToDeviceUnits(defaultStatusStripMargin); } - state[stateEnabled | stateAutoSize | stateVisible | stateContstructing | stateSupportsItemClick | stateInvalidMirroredImage | stateMouseDownAndUpMustBeInSameItem | stateUseAmbientMargin] = true; + state[stateEnabled | stateAutoSize | stateVisible | stateContstructing | stateSupportsItemClick | stateInvalidMirroredImage | stateMouseDownAndUpMustBeInSameItem | stateUseAmbientMargin] = true; state[stateAllowDrop | stateMouseDownAndNoDrag | stateSupportsRightClick | statePressed | stateSelected | stateDisposed | stateDoubleClickEnabled | stateRightToLeftAutoMirrorImage | stateSupportsSpaceKey] = false; SetAmbientMargin(); this.Size = DefaultSize; this.DisplayStyle = DefaultDisplayStyle; - CommonProperties.SetAutoSize(this,true); + CommonProperties.SetAutoSize(this, true); state[stateContstructing] = false; this.AutoToolTip = DefaultAutoToolTip; - + } - + [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] - protected ToolStripItem(string text, Image image, EventHandler onClick) : this(text, image, onClick, null) { + protected ToolStripItem(string text, Image image, EventHandler onClick) : this(text, image, onClick, null) + { } [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] - protected ToolStripItem(string text, Image image, EventHandler onClick, string name) : this() { + protected ToolStripItem(string text, Image image, EventHandler onClick, string name) : this() + { this.Text = text; this.Image = image; - if (onClick != null) { + if (onClick != null) + { Click += onClick; } this.Name = name; } - + /// /// The Accessibility Object for this Control /// @@ -215,14 +222,17 @@ protected ToolStripItem(string text, Image image, EventHandler onClick, string n DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ToolStripItemAccessibilityObjectDescr)) ] - public AccessibleObject AccessibilityObject { - get { + public AccessibleObject AccessibilityObject + { + get + { AccessibleObject accessibleObject = (AccessibleObject)Properties.GetObject(PropAccessibility); - if (accessibleObject == null) { + if (accessibleObject == null) + { accessibleObject = CreateAccessibilityInstance(); Properties.SetObject(PropAccessibility, accessibleObject); } - + return accessibleObject; } } @@ -232,15 +242,18 @@ public AccessibleObject AccessibilityObject { /// [ SRCategory(nameof(SR.CatAccessibility)), - Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), + Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ToolStripItemAccessibleDefaultActionDescr)) ] - public string AccessibleDefaultActionDescription { - get { + public string AccessibleDefaultActionDescription + { + get + { return (string)Properties.GetObject(PropAccessibleDefaultActionDescription); } - set { + set + { Properties.SetObject(PropAccessibleDefaultActionDescription, value); OnAccessibleDefaultActionDescriptionChanged(EventArgs.Empty); } @@ -254,11 +267,14 @@ public string AccessibleDefaultActionDescription { Localizable(true), SRDescription(nameof(SR.ToolStripItemAccessibleDescriptionDescr)) ] - public string AccessibleDescription { - get { + public string AccessibleDescription + { + get + { return (string)Properties.GetObject(PropAccessibleDescription); } - set { + set + { Properties.SetObject(PropAccessibleDescription, value); OnAccessibleDescriptionChanged(EventArgs.Empty); } @@ -273,12 +289,15 @@ public string AccessibleDescription { Localizable(true), SRDescription(nameof(SR.ToolStripItemAccessibleNameDescr)) ] - public string AccessibleName { - get { + public string AccessibleName + { + get + { return (string)Properties.GetObject(PropAccessibleName); } - set { + set + { Properties.SetObject(PropAccessibleName, value); OnAccessibleNameChanged(EventArgs.Empty); } @@ -292,22 +311,28 @@ public string AccessibleName { DefaultValue(AccessibleRole.Default), SRDescription(nameof(SR.ToolStripItemAccessibleRoleDescr)) ] - public AccessibleRole AccessibleRole { + public AccessibleRole AccessibleRole + { - get { + get + { bool found; int role = Properties.GetInteger(PropAccessibleRole, out found); - if (found) { + if (found) + { return (AccessibleRole)role; } - else { + else + { return AccessibleRole.Default; } } - set { + set + { //valid values are 0xffffffff to 0x40 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)AccessibleRole.Default, (int)AccessibleRole.OutlineButton)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)AccessibleRole.Default, (int)AccessibleRole.OutlineButton)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AccessibleRole)); } Properties.SetInteger(PropAccessibleRole, (int)value); @@ -326,27 +351,32 @@ public AccessibleRole AccessibleRole { SRCategory(nameof(SR.CatLayout)), SRDescription(nameof(SR.ToolStripItemAlignmentDescr)) ] - public ToolStripItemAlignment Alignment { - get { + public ToolStripItemAlignment Alignment + { + get + { return alignment; } - set { + set + { //valid values are 0x0 to 0x1 if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripItemAlignment.Left, (int)ToolStripItemAlignment.Right)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripItemAlignment)); + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripItemAlignment)); } - if (alignment != value) { + if (alignment != value) + { alignment = value; - - if ((this.ParentInternal != null) && this.ParentInternal.IsHandleCreated) { + + if ((this.ParentInternal != null) && this.ParentInternal.IsHandleCreated) + { this.ParentInternal.PerformLayout(); } } } } - + /// /// Determines if this item can be dragged. /// This is EXACTLY like Control.AllowDrop - setting this to true WILL call @@ -361,12 +391,16 @@ public ToolStripItemAlignment Alignment { EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false) ] - public virtual bool AllowDrop { - get { - return state[stateAllowDrop]; + public virtual bool AllowDrop + { + get + { + return state[stateAllowDrop]; } - set { - if (value != state[stateAllowDrop]) { + set + { + if (value != state[stateAllowDrop]) + { EnsureParentDropTargetRegistered(); state[stateAllowDrop] = value; } @@ -382,14 +416,18 @@ public virtual bool AllowDrop { [Localizable(true)] [SRDescription(nameof(SR.ToolStripItemAutoSizeDescr))] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] - public bool AutoSize { - get { + public bool AutoSize + { + get + { return state[stateAutoSize]; } - set { - if (state[stateAutoSize] != value) { + set + { + if (state[stateAutoSize] != value) + { state[stateAutoSize] = value; - CommonProperties.SetAutoSize(this,value); + CommonProperties.SetAutoSize(this, value); InvalidateItemLayout(PropertyNames.AutoSize); } } @@ -402,13 +440,16 @@ public bool AutoSize { [DefaultValue(false)] [SRDescription(nameof(SR.ToolStripItemAutoToolTipDescr))] [SRCategory(nameof(SR.CatBehavior))] - public bool AutoToolTip { - get { + public bool AutoToolTip + { + get + { return state[stateAutoToolTip]; - } - set { + } + set + { state[stateAutoToolTip] = value; - } + } } /// @@ -420,26 +461,30 @@ public bool AutoToolTip { SRDescription(nameof(SR.ToolStripItemAvailableDescr)), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public bool Available{ - get { + public bool Available + { + get + { // MainMenu compat: // the only real diff is the getter - this returns what the item really thinks, // as opposed to whether or not the parent is also Visible. Visible behavior is the same // so that it matches Control behavior (we dont have to do special things for control hosts, etc etc). - return state[stateVisible]; + return state[stateVisible]; } - set { - SetVisibleCore(value); + set + { + SetVisibleCore(value); } } - + [ Browsable(false), - SRCategory(nameof(SR.CatPropertyChanged)), + SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ToolStripItemOnAvailableChangedDescr)) ] - public event EventHandler AvailableChanged { + public event EventHandler AvailableChanged + { add => Events.AddHandler(EventAvailableChanged, value); remove => Events.RemoveHandler(EventAvailableChanged, value); } @@ -455,15 +500,19 @@ public event EventHandler AvailableChanged { SRDescription(nameof(SR.ToolStripItemImageDescr)), DefaultValue(null) ] - public virtual Image BackgroundImage { - get { + public virtual Image BackgroundImage + { + get + { return Properties.GetObject(PropBackgroundImage) as Image; - + } - set { - if (BackgroundImage != value) { - Properties.SetObject(PropBackgroundImage, value); - Invalidate(); + set + { + if (BackgroundImage != value) + { + Properties.SetObject(PropBackgroundImage, value); + Invalidate(); } } } @@ -474,27 +523,33 @@ public virtual Image BackgroundImage { Localizable(true), SRDescription(nameof(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(nameof(value), (int)value, typeof(ImageLayout)); - } - Properties.SetObject(PropBackgroundImageLayout, value); - Invalidate(); - } - } + 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(nameof(value), (int)value, typeof(ImageLayout)); + } + Properties.SetObject(PropBackgroundImageLayout, value); + Invalidate(); + } + } } /// @@ -504,58 +559,71 @@ public virtual ImageLayout BackgroundImageLayout { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripItemBackColorDescr)) ] - public virtual Color BackColor { - get { + public virtual Color BackColor + { + get + { Color c = RawBackColor; // inheritedProperties.BackColor if (!c.IsEmpty) return c; Control p = ParentInternal; - if (p != null) { + if (p != null) + { return p.BackColor; } return Control.DefaultBackColor; } - set { + set + { Color c = BackColor; - if (!value.IsEmpty || Properties.ContainsObject(PropBackColor)) { + if (!value.IsEmpty || Properties.ContainsObject(PropBackColor)) + { Properties.SetColor(PropBackColor, value); } - if (!c.Equals(BackColor)) { + if (!c.Equals(BackColor)) + { OnBackColorChanged(EventArgs.Empty); } } } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ToolStripItemOnBackColorChangedDescr))] - public event EventHandler BackColorChanged { + public event EventHandler BackColorChanged + { add => Events.AddHandler(EventBackColorChanged, value); remove => Events.RemoveHandler(EventBackColorChanged, value); } - + /// /// The bounds of the item /// [Browsable(false)] - public virtual Rectangle Bounds { + public virtual Rectangle Bounds + { [SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces")] - get { + get + { return bounds; } } // Zero-based rectangle, same concept as ClientRect - internal Rectangle ClientBounds { - get { + internal Rectangle ClientBounds + { + get + { Rectangle client = bounds; client.Location = Point.Empty; return client; } } [Browsable(false)] - public Rectangle ContentRectangle { - get { + public Rectangle ContentRectangle + { + get + { Rectangle content = LayoutUtils.InflateRect(InternalLayout.ContentRectangle, this.Padding); content.Size = LayoutUtils.UnionSizes(Size.Empty, content.Size); return content; @@ -566,29 +634,34 @@ public Rectangle ContentRectangle { /// Determines whether or not the item can be selected. /// [Browsable(false)] - public virtual bool CanSelect { - get { - return true; + public virtual bool CanSelect + { + get + { + return true; } } // usually the same as can select, but things like the control box in an MDI window are exceptions - internal virtual bool CanKeyboardSelect { - get { - return CanSelect; - } - } + internal virtual bool CanKeyboardSelect + { + get + { + return CanSelect; + } + } /// /// Occurs when the control is clicked. /// [ - SRCategory(nameof(SR.CatAction)), + SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ToolStripItemOnClickDescr)) ] - public event EventHandler Click { - add => Events.AddHandler(EventClick, value); - remove => Events.RemoveHandler(EventClick, value); + public event EventHandler Click + { + add => Events.AddHandler(EventClick, value); + remove => Events.RemoveHandler(EventClick, value); } [ @@ -596,18 +669,23 @@ public event EventHandler Click { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(CommonProperties.DefaultAnchor) ] - public AnchorStyles Anchor { - get { + public AnchorStyles Anchor + { + get + { // since we dont support DefaultLayout go directly against the CommonProperties return CommonProperties.xGetAnchor(this); } - set { + set + { // flags enum - dont check for validity.... - - if(value != Anchor) { + + if (value != Anchor) + { // since we dont support DefaultLayout go directly against the CommonProperties CommonProperties.xSetAnchor(this, value); - if (ParentInternal != null) { + if (ParentInternal != null) + { LayoutTransaction.DoLayout(this, ParentInternal, PropertyNames.Anchor); } } @@ -617,24 +695,30 @@ public AnchorStyles Anchor { /// This does not show up in the property grid because it only applies to flow and table layouts [ - Browsable(false), + Browsable(false), DefaultValue(CommonProperties.DefaultDock) ] - public DockStyle Dock { - get { - + public DockStyle Dock + { + get + { + // since we dont support DefaultLayout go directly against the CommonProperties return CommonProperties.xGetDock(this); } - set { + set + { //valid values are 0x0 to 0x5 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)DockStyle.None, (int)DockStyle.Fill)){ + if (!ClientUtils.IsEnumValid(value, (int)value, (int)DockStyle.None, (int)DockStyle.Fill)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DockStyle)); } - if(value != Dock) { + if (value != Dock) + { // since we dont support DefaultLayout go directly against the CommonProperties CommonProperties.xSetDock(this, value); - if (ParentInternal != null) { + if (ParentInternal != null) + { LayoutTransaction.DoLayout(this, ParentInternal, PropertyNames.Dock); } } @@ -642,21 +726,27 @@ public DockStyle Dock { } /// default setting of auto tooltip when this object is created - protected virtual bool DefaultAutoToolTip { - get { - return false; - } + protected virtual bool DefaultAutoToolTip + { + get + { + return false; + } } /// /// 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. /// - protected internal virtual Padding DefaultMargin { - get { - if (this.Owner != null && this.Owner is StatusStrip) { + protected internal virtual Padding DefaultMargin + { + get + { + if (this.Owner != null && this.Owner is StatusStrip) + { return scaledDefaultStatusStripMargin; } - else { + else + { return scaledDefaultMargin; } } @@ -665,8 +755,10 @@ protected internal virtual Padding DefaultMargin { /// 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. /// - protected virtual Padding DefaultPadding { - get { + protected virtual Padding DefaultPadding + { + get + { return Padding.Empty; } } @@ -674,14 +766,18 @@ protected virtual Padding DefaultPadding { /// 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. /// - protected virtual Size DefaultSize { - get { + protected virtual Size DefaultSize + { + get + { return new Size(23, 23); } } - protected virtual ToolStripItemDisplayStyle DefaultDisplayStyle { - get { + protected virtual ToolStripItemDisplayStyle DefaultDisplayStyle + { + get + { return ToolStripItemDisplayStyle.ImageAndText; } } @@ -689,8 +785,10 @@ protected virtual ToolStripItemDisplayStyle DefaultDisplayStyle { /// /// specifies the default behavior of these items on ToolStripDropDowns when clicked. /// - internal protected virtual bool DismissWhenClicked { - get { + internal protected virtual bool DismissWhenClicked + { + get + { return true; } } @@ -703,102 +801,118 @@ internal protected virtual bool DismissWhenClicked { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripItemDisplayStyleDescr)) ] - public virtual ToolStripItemDisplayStyle DisplayStyle { - get { - return displayStyle; + public virtual ToolStripItemDisplayStyle DisplayStyle + { + get + { + return displayStyle; } - set { - if (displayStyle != value) { + set + { + if (displayStyle != value) + { //valid values are 0x0 to 0x3 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripItemDisplayStyle.None, (int)ToolStripItemDisplayStyle.ImageAndText)) - { + if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripItemDisplayStyle.None, (int)ToolStripItemDisplayStyle.ImageAndText)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripItemDisplayStyle)); - } + } displayStyle = value; - if (!state[stateContstructing]) { + if (!state[stateContstructing]) + { InvalidateItemLayout(PropertyNames.DisplayStyle); OnDisplayStyleChanged(EventArgs.Empty); } } - + } } /// /// Occurs when the display style has changed /// - public event EventHandler DisplayStyleChanged { - add => Events.AddHandler(EventDisplayStyleChanged, value); + public event EventHandler DisplayStyleChanged + { + add => Events.AddHandler(EventDisplayStyleChanged, value); remove => Events.RemoveHandler(EventDisplayStyleChanged, value); } - [EditorBrowsable(EditorBrowsableState.Advanced)] - private RightToLeft DefaultRightToLeft { - get { - return RightToLeft.Inherit; + [EditorBrowsable(EditorBrowsableState.Advanced)] + private RightToLeft DefaultRightToLeft + { + get + { + return RightToLeft.Inherit; } } /// /// Occurs when the control is double clicked. /// [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ControlOnDoubleClickDescr))] - public event EventHandler DoubleClick { + public event EventHandler DoubleClick + { add => Events.AddHandler(EventDoubleClick, value); remove => Events.RemoveHandler(EventDoubleClick, value); } [ - DefaultValue(false), - SRCategory(nameof(SR.CatBehavior)), + DefaultValue(false), + SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ToolStripItemDoubleClickedEnabledDescr)) ] - public bool DoubleClickEnabled { - get { + public bool DoubleClickEnabled + { + get + { return state[stateDoubleClickEnabled]; } - set { + set + { state[stateDoubleClickEnabled] = value; } } [ - SRCategory(nameof(SR.CatDragDrop)), + SRCategory(nameof(SR.CatDragDrop)), SRDescription(nameof(SR.ToolStripItemOnDragDropDescr)), EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false) ] - public event DragEventHandler DragDrop { + public event DragEventHandler DragDrop + { add => Events.AddHandler(EventDragDrop, value); remove => Events.RemoveHandler(EventDragDrop, value); } [ - SRCategory(nameof(SR.CatDragDrop)), + SRCategory(nameof(SR.CatDragDrop)), SRDescription(nameof(SR.ToolStripItemOnDragEnterDescr)), EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false) ] - public event DragEventHandler DragEnter { + public event DragEventHandler DragEnter + { add => Events.AddHandler(EventDragEnter, value); remove => Events.RemoveHandler(EventDragEnter, value); } [ - SRCategory(nameof(SR.CatDragDrop)), + SRCategory(nameof(SR.CatDragDrop)), SRDescription(nameof(SR.ToolStripItemOnDragOverDescr)), EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false) ] - public event DragEventHandler DragOver { + public event DragEventHandler DragOver + { add => Events.AddHandler(EventDragOver, value); remove => Events.RemoveHandler(EventDragOver, value); } [ - SRCategory(nameof(SR.CatDragDrop)), + SRCategory(nameof(SR.CatDragDrop)), SRDescription(nameof(SR.ToolStripItemOnDragLeaveDescr)), EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false) ] - public event EventHandler DragLeave { + public event EventHandler DragLeave + { add => Events.AddHandler(EventDragLeave, value); remove => Events.RemoveHandler(EventDragLeave, value); } @@ -813,13 +927,16 @@ public event EventHandler DragLeave { /// Else if the parent does not support reordering of items (Parent.AllowItemReorder = false) - /// then call back on the ToolStripItem's OnQueryContinueDrag/OnGiveFeedback methods. /// - private DropSource DropSource { - get { - if ((ParentInternal != null) && (ParentInternal.AllowItemReorder) && (ParentInternal.ItemReorderDropSource != null)) { + private DropSource DropSource + { + get + { + if ((ParentInternal != null) && (ParentInternal.AllowItemReorder) && (ParentInternal.ItemReorderDropSource != null)) + { return new DropSource(ParentInternal.ItemReorderDropSource); } return new DropSource(this); - } + } } /// @@ -831,26 +948,33 @@ private DropSource DropSource { SRDescription(nameof(SR.ToolStripItemEnabledDescr)), DefaultValue(true) ] - public virtual bool Enabled { - get { - bool parentEnabled = true; + public virtual bool Enabled + { + get + { + bool parentEnabled = true; - if (this.Owner != null) { + if (this.Owner != null) + { parentEnabled = this.Owner.Enabled; } - - return state[stateEnabled] && parentEnabled; + + return state[stateEnabled] && parentEnabled; } - set { + set + { // flip disabled bit. - if (state[stateEnabled] != value) { + if (state[stateEnabled] != value) + { state[stateEnabled] = value; - if (!state[stateEnabled]) { + if (!state[stateEnabled]) + { bool wasSelected = state[stateSelected]; // clear all the other states. state[stateSelected | statePressed] = false; - if (wasSelected) { + if (wasSelected) + { KeyboardToolTipStateMachine.Instance.NotifyAboutLostFocus(this); } @@ -865,21 +989,25 @@ public virtual bool Enabled { - [ + [ SRDescription(nameof(SR.ToolStripItemEnabledChangedDescr)) ] - public event EventHandler EnabledChanged { + public event EventHandler EnabledChanged + { add => Events.AddHandler(EventEnabledChanged, value); remove => Events.RemoveHandler(EventEnabledChanged, value); } - internal event EventHandler InternalEnabledChanged { + internal event EventHandler InternalEnabledChanged + { add => Events.AddHandler(EventInternalEnabledChanged, value); remove => Events.RemoveHandler(EventInternalEnabledChanged, value); } - - private void EnsureParentDropTargetRegistered() { - if (ParentInternal != null) { + + private void EnsureParentDropTargetRegistered() + { + if (ParentInternal != null) + { ParentInternal.DropTargetManager.EnsureRegistered(this); } } @@ -892,37 +1020,45 @@ private void EnsureParentDropTargetRegistered() { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripItemForeColorDescr)) ] - public virtual Color ForeColor { - get { + public virtual Color ForeColor + { + get + { Color foreColor = Properties.GetColor(PropForeColor); - if (!foreColor.IsEmpty){ + if (!foreColor.IsEmpty) + { return foreColor; } - + Control p = ParentInternal; - if (p != null) { + if (p != null) + { return p.ForeColor; } return Control.DefaultForeColor; } - - set { + + set + { Color c = ForeColor; - if (!value.IsEmpty || Properties.ContainsObject(PropForeColor)) { + if (!value.IsEmpty || Properties.ContainsObject(PropForeColor)) + { Properties.SetColor(PropForeColor, value); } - if (!c.Equals(ForeColor)) { + if (!c.Equals(ForeColor)) + { OnForeColorChanged(EventArgs.Empty); } } } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ToolStripItemOnForeColorChangedDescr))] - public event EventHandler ForeColorChanged { + public event EventHandler ForeColorChanged + { add => Events.AddHandler(EventForeColorChanged, value); remove => Events.RemoveHandler(EventForeColorChanged, value); } - + /// /// Retrieves the current font for this control. This will be the font used /// by default for painting and text in the control. @@ -932,40 +1068,47 @@ public event EventHandler ForeColorChanged { Localizable(true), SRDescription(nameof(SR.ToolStripItemFontDescr)) ] - public virtual Font Font { - get { + public virtual Font Font + { + get + { Font font = (Font)Properties.GetObject(PropFont); - if (font != null) { + if (font != null) + { return font; } Font f = GetOwnerFont(); - if (f != null) { + if (f != null) + { return f; } - + return ToolStripManager.DefaultFont; } - set { + set + { Font local = (Font)Properties.GetObject(PropFont); - if ((local != value)){ + if ((local != value)) + { Properties.SetObject(PropFont, value); OnFontChanged(EventArgs.Empty); - } + } } } [ - SRCategory(nameof(SR.CatDragDrop)), + SRCategory(nameof(SR.CatDragDrop)), SRDescription(nameof(SR.ToolStripItemOnGiveFeedbackDescr)), EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false) ] - public event GiveFeedbackEventHandler GiveFeedback { + public event GiveFeedbackEventHandler GiveFeedback + { add => Events.AddHandler(EventGiveFeedback, value); remove => Events.RemoveHandler(EventGiveFeedback, value); - } - + } + /// /// The height of this control /// @@ -974,11 +1117,14 @@ public event GiveFeedbackEventHandler GiveFeedback { Browsable(false), EditorBrowsable(EditorBrowsableState.Always), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public int Height { - get { + public int Height + { + get + { return Bounds.Height; } - set{ + set + { Rectangle currentBounds = this.Bounds; SetBounds(currentBounds.X, currentBounds.Y, currentBounds.Width, value); } @@ -988,58 +1134,71 @@ public int Height { /// ToolStripItems do not have children. For perf reasons always return a static empty collection. /// Consider creating readonly collection. /// - ArrangedElementCollection IArrangedElement.Children { - get { - return ToolStripItem.EmptyChildCollection; + ArrangedElementCollection IArrangedElement.Children + { + get + { + return ToolStripItem.EmptyChildCollection; } } /// /// Should not be exposed as this returns an unexposed type. /// - IArrangedElement IArrangedElement.Container { - get { - if (this.ParentInternal == null) { + IArrangedElement IArrangedElement.Container + { + get + { + if (this.ParentInternal == null) + { return this.Owner; } return this.ParentInternal; } } - Rectangle IArrangedElement.DisplayRectangle { - get { + Rectangle IArrangedElement.DisplayRectangle + { + get + { return this.Bounds; } } - bool IArrangedElement.ParticipatesInLayout { - get { + bool IArrangedElement.ParticipatesInLayout + { + get + { // this can be different than "Visible" property as "Visible" takes into account whether or not you // are parented and your parent is visible. return state[stateVisible]; } } - - PropertyStore IArrangedElement.Properties { - get { + + PropertyStore IArrangedElement.Properties + { + get + { return this.Properties; } } - + // Sets the bounds for an element. - void IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) { + void IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) + { // in this case the parent is telling us to refresh our bounds - dont // call PerformLayout SetBounds(bounds); } - void IArrangedElement.PerformLayout(IArrangedElement container, string propertyName) { + void IArrangedElement.PerformLayout(IArrangedElement container, string propertyName) + { return; } - + /// /// /// Gets or sets the alignment of the image on the label control. @@ -1051,16 +1210,21 @@ void IArrangedElement.PerformLayout(IArrangedElement container, string propertyN SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripItemImageAlignDescr)) ] - public ContentAlignment ImageAlign { - get { + public ContentAlignment ImageAlign + { + get + { return imageAlign; } - set { + set + { - if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) { + if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ContentAlignment)); } - if (imageAlign != value) { + if (imageAlign != value) + { imageAlign = value; InvalidateItemLayout(PropertyNames.ImageAlign); } @@ -1077,37 +1241,47 @@ public ContentAlignment ImageAlign { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripItemImageDescr)) ] - public virtual Image Image { - - - get { + public virtual Image Image + { + + + get + { Image image = (Image)Properties.GetObject(PropImage); - - if (image == null && (Owner != null) && (Owner.ImageList != null) && ImageIndexer.ActualIndex >= 0) { - if (ImageIndexer.ActualIndex < Owner.ImageList.Images.Count) { + + if (image == null && (Owner != null) && (Owner.ImageList != null) && ImageIndexer.ActualIndex >= 0) + { + if (ImageIndexer.ActualIndex < Owner.ImageList.Images.Count) + { // CACHE (by design). If we fetched out of the image list every time it would dramatically hit perf. - image = Owner.ImageList.Images[ImageIndexer.ActualIndex]; + image = Owner.ImageList.Images[ImageIndexer.ActualIndex]; state[stateInvalidMirroredImage] = true; Properties.SetObject(PropImage, image); - return image; + return image; } } - else { + else + { return image; } return null; } - set { - if (Image != value) { - StopAnimate(); + set + { + if (Image != value) + { + StopAnimate(); Bitmap bmp = value as Bitmap; - if (bmp != null && ImageTransparentColor != Color.Empty) { - if (bmp.RawFormat.Guid != ImageFormat.Icon.Guid && !ImageAnimator.CanAnimate(bmp)) { + if (bmp != null && ImageTransparentColor != Color.Empty) + { + if (bmp.RawFormat.Guid != ImageFormat.Icon.Guid && !ImageAnimator.CanAnimate(bmp)) + { bmp.MakeTransparent(ImageTransparentColor); } value = bmp; } - if (value != null) { + if (value != null) + { ImageIndex = -1; } Properties.SetObject(PropImage, value); @@ -1123,26 +1297,32 @@ public virtual Image Image { Localizable(true), SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripItemImageTransparentColorDescr)) - ] - public Color ImageTransparentColor { - get { + ] + public Color ImageTransparentColor + { + get + { return imageTransparentColor; } - set { - if (imageTransparentColor != value) { + set + { + if (imageTransparentColor != value) + { imageTransparentColor = value; Bitmap currentImage = Image as Bitmap; - if (currentImage != null && value != Color.Empty) { - if (currentImage.RawFormat.Guid != ImageFormat.Icon.Guid && !ImageAnimator.CanAnimate(currentImage)) { + if (currentImage != null && value != Color.Empty) + { + if (currentImage.RawFormat.Guid != ImageFormat.Icon.Guid && !ImageAnimator.CanAnimate(currentImage)) + { currentImage.MakeTransparent(imageTransparentColor); - } + } } Invalidate(); } - + } } - + /// /// Returns the ToolStripItem's currently set image index /// Here for compat only - this is NOT to be visible at DT. @@ -1151,38 +1331,46 @@ public Color ImageTransparentColor { SRDescription(nameof(SR.ToolStripItemImageIndexDescr)), Localizable(true), SRCategory(nameof(SR.CatBehavior)), - RefreshProperties(RefreshProperties.Repaint), + RefreshProperties(RefreshProperties.Repaint), TypeConverterAttribute(typeof(NoneExcludedImageIndexConverter)), Editor("System.Windows.Forms.Design.ToolStripImageIndexEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), Browsable(false), RelatedImageList("Owner.ImageList") - ] - public int ImageIndex { - get { - if ((Owner != null) && ImageIndexer.Index != -1 && Owner.ImageList != null && ImageIndexer.Index >= Owner.ImageList.Images.Count) { + ] + public int ImageIndex + { + get + { + if ((Owner != null) && ImageIndexer.Index != -1 && Owner.ImageList != null && ImageIndexer.Index >= Owner.ImageList.Images.Count) + { return Owner.ImageList.Images.Count - 1; - } + } return this.ImageIndexer.Index; } - set { - if (value < -1) { + set + { + if (value < -1) + { throw new ArgumentOutOfRangeException(nameof(value), string.Format(SR.InvalidLowBoundArgumentEx, nameof(ImageIndex), value, -1)); } - - + + ImageIndexer.Index = value; state[stateInvalidMirroredImage] = true; // Set the Image Property to null Properties.SetObject(PropImage, null); - + InvalidateItemLayout(PropertyNames.ImageIndex); - } + } } - internal ToolStripItemImageIndexer ImageIndexer { - get { - if (imageIndexer == null) { + internal ToolStripItemImageIndexer ImageIndexer + { + get + { + if (imageIndexer == null) + { imageIndexer = new ToolStripItemImageIndexer(this); } return imageIndexer; @@ -1203,17 +1391,20 @@ internal ToolStripItemImageIndexer ImageIndexer { Browsable(false), RelatedImageList("Owner.ImageList") ] - public string ImageKey { - get { + public string ImageKey + { + get + { return this.ImageIndexer.Key; } - set { + set + { ImageIndexer.Key = value; state[stateInvalidMirroredImage] = true; Properties.SetObject(PropImage, null); - + InvalidateItemLayout(PropertyNames.ImageKey); - + } } @@ -1223,19 +1414,23 @@ public string ImageKey { Localizable(true), SRDescription(nameof(SR.ToolStripItemImageScalingDescr)) ] - public ToolStripItemImageScaling ImageScaling { - get { + public ToolStripItemImageScaling ImageScaling + { + get + { return imageScaling; } - set { + set + { //valid values are 0x0 to 0x1 if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripItemImageScaling.None, (int)ToolStripItemImageScaling.SizeToFit)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripItemImageScaling)); } - if (imageScaling != value) { + if (imageScaling != value) + { imageScaling = value; - + InvalidateItemLayout(PropertyNames.ImageScaling); } } @@ -1246,29 +1441,37 @@ public ToolStripItemImageScaling ImageScaling { /// This object helps determine where the image and text should be drawn. /// /// - internal ToolStripItemInternalLayout InternalLayout { - get { - if (toolStripItemInternalLayout == null) { + internal ToolStripItemInternalLayout InternalLayout + { + get + { + if (toolStripItemInternalLayout == null) + { toolStripItemInternalLayout = CreateInternalLayout(); } return toolStripItemInternalLayout; } } - internal bool IsForeColorSet { - get { + internal bool IsForeColorSet + { + get + { Color color = Properties.GetColor(PropForeColor); - if (!color.IsEmpty) { + if (!color.IsEmpty) + { return true; } - else { + else + { Control parent = ParentInternal; - if (parent != null) { + if (parent != null) + { return parent.ShouldSerializeForeColor(); } - } + } return false; - } + } } /// @@ -1276,40 +1479,50 @@ internal bool IsForeColorSet { /// This is used by ToolStrip to pass on the mouseMessages for ActiveDropDown. /// /// - internal bool IsInDesignMode { - get { + internal bool IsInDesignMode + { + get + { return DesignMode; } } [Browsable(false)] - public bool IsDisposed { - get { + public bool IsDisposed + { + get + { return state[stateDisposed]; } } [Browsable(false)] - public bool IsOnDropDown { - get { - - if (ParentInternal != null) { + public bool IsOnDropDown + { + get + { + + if (ParentInternal != null) + { return ParentInternal.IsDropDown; } - else if (Owner != null && Owner.IsDropDown) { + else if (Owner != null && Owner.IsDropDown) + { return true; } - + return false; } } /// returns whether the item placement is set to overflow. [Browsable(false)] - public bool IsOnOverflow { - get { + public bool IsOnOverflow + { + get + { return (this.Placement == ToolStripItemPlacement.Overflow); } } @@ -1318,19 +1531,21 @@ public bool IsOnOverflow { /// /// Specifies whether the control is willing to process mnemonics when hosted in an container ActiveX (Ax Sourcing). /// - internal virtual bool IsMnemonicsListenerAxSourced + internal virtual bool IsMnemonicsListenerAxSourced { - get{ + get + { return true; } } - + /// /// Occurs when the location of the ToolStripItem has been updated -- usually by layout by its /// owner of ToolStrips /// [SRCategory(nameof(SR.CatLayout)), SRDescription(nameof(SR.ToolStripItemOnLocationChangedDescr))] - public event EventHandler LocationChanged { + public event EventHandler LocationChanged + { add => Events.AddHandler(EventLocationChanged, value); remove => Events.RemoveHandler(EventLocationChanged, value); } @@ -1342,12 +1557,15 @@ public event EventHandler LocationChanged { SRDescription(nameof(SR.ToolStripItemMarginDescr)), SRCategory(nameof(SR.CatLayout)) ] - public Padding Margin { + public Padding Margin + { get { return CommonProperties.GetMargin(this); } - set { - if (Margin != value) { + set + { + if (Margin != value) + { state[stateUseAmbientMargin] = false; - CommonProperties.SetMargin(this, value); + CommonProperties.SetMargin(this, value); } } } @@ -1361,20 +1579,25 @@ public Padding Margin { DefaultValue(MergeAction.Append), SRCategory(nameof(SR.CatLayout)) ] - public MergeAction MergeAction { - get { + public MergeAction MergeAction + { + get + { bool found; int action = Properties.GetInteger(PropMergeAction, out found); - if (found) { + if (found) + { return (MergeAction)action; } - else { + else + { // default value return MergeAction.Append; } } - set { + set + { //valid values are 0x0 to 0x4 if (!ClientUtils.IsEnumValid(value, (int)value, (int)MergeAction.Append, (int)MergeAction.MatchOnly)) { @@ -1392,26 +1615,32 @@ public MergeAction MergeAction { DefaultValue(-1), SRCategory(nameof(SR.CatLayout)) ] - public int MergeIndex { - get { + public int MergeIndex + { + get + { bool found; int index = Properties.GetInteger(PropMergeIndex, out found); - if (found) { + if (found) + { return index; } - else { + else + { // default value return -1; } } - set { + set + { Properties.SetInteger(PropMergeIndex, value); } } // required for menus - internal bool MouseDownAndUpMustBeInSameItem { + internal bool MouseDownAndUpMustBeInSameItem + { get { return state[stateMouseDownAndUpMustBeInSameItem]; } set { state[stateMouseDownAndUpMustBeInSameItem] = value; } } @@ -1421,10 +1650,11 @@ internal bool MouseDownAndUpMustBeInSameItem { /// pressed. /// [ - SRCategory(nameof(SR.CatMouse)), + SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.ToolStripItemOnMouseDownDescr)) ] - public event MouseEventHandler MouseDown { + public event MouseEventHandler MouseDown + { add => Events.AddHandler(EventMouseDown, value); remove => Events.RemoveHandler(EventMouseDown, value); } @@ -1434,10 +1664,11 @@ public event MouseEventHandler MouseDown { /// Occurs when the mouse pointer enters the control. /// [ - SRCategory(nameof(SR.CatMouse)), + SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.ToolStripItemOnMouseEnterDescr)) ] - public event EventHandler MouseEnter { + public event EventHandler MouseEnter + { add => Events.AddHandler(EventMouseEnter, value); remove => Events.RemoveHandler(EventMouseEnter, value); } @@ -1446,10 +1677,11 @@ public event EventHandler MouseEnter { /// Occurs when the mouse pointer leaves the control. /// [ - SRCategory(nameof(SR.CatMouse)), + SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.ToolStripItemOnMouseLeaveDescr)) ] - public event EventHandler MouseLeave { + public event EventHandler MouseLeave + { add => Events.AddHandler(EventMouseLeave, value); remove => Events.RemoveHandler(EventMouseLeave, value); } @@ -1459,22 +1691,24 @@ public event EventHandler MouseLeave { /// Occurs when the mouse pointer hovers over the contro. /// [ - SRCategory(nameof(SR.CatMouse)), + SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.ToolStripItemOnMouseHoverDescr)) ] - public event EventHandler MouseHover { + public event EventHandler MouseHover + { add => Events.AddHandler(EventMouseHover, value); remove => Events.RemoveHandler(EventMouseHover, value); - } + } /// /// Occurs when the mouse pointer is moved over the control. /// [ - SRCategory(nameof(SR.CatMouse)), + SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.ToolStripItemOnMouseMoveDescr)) ] - public event MouseEventHandler MouseMove { + public event MouseEventHandler MouseMove + { add => Events.AddHandler(EventMouseMove, value); remove => Events.RemoveHandler(EventMouseMove, value); } @@ -1483,10 +1717,11 @@ public event MouseEventHandler MouseMove { /// Occurs when the mouse pointer is over the control and a mouse button is released. /// [ - SRCategory(nameof(SR.CatMouse)), + SRCategory(nameof(SR.CatMouse)), SRDescription(nameof(SR.ToolStripItemOnMouseUpDescr)) ] - public event MouseEventHandler MouseUp { + public event MouseEventHandler MouseUp + { add => Events.AddHandler(EventMouseUp, value); remove => Events.RemoveHandler(EventMouseUp, value); } @@ -1500,18 +1735,21 @@ public event MouseEventHandler MouseUp { Browsable(false), DefaultValue(null) ] - public string Name { - get { + public string Name + { + get + { return WindowsFormsUtils.GetComponentName(this, (string)Properties.GetObject(ToolStripItem.PropName)); } - set { + set + { if (DesignMode) //InDesignMode the Extender property will set it to the right value. { return; } Properties.SetObject(ToolStripItem.PropName, value); } - } + } /// /// The owner of this ToolStripItem. The owner is essentially a backpointer to @@ -1522,42 +1760,53 @@ public string Name { Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public ToolStrip Owner { - get { + public ToolStrip Owner + { + get + { return this.owner; } - set { - if (owner != value) { - if (owner != null) { + set + { + if (owner != value) + { + if (owner != null) + { owner.Items.Remove(this); } - if (value != null) { + if (value != null) + { value.Items.Add(this); } - } + } } } - + /// returns the "parent" item on the preceeding menu which has spawned this item. /// e.g. File->Open the OwnerItem of Open is File. [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public ToolStripItem OwnerItem { - get { + public ToolStripItem OwnerItem + { + get + { ToolStripDropDown currentParent = null; - - if (ParentInternal != null) { - currentParent = ParentInternal as ToolStripDropDown; + + if (ParentInternal != null) + { + currentParent = ParentInternal as ToolStripDropDown; } - else if (Owner != null) { + else if (Owner != null) + { // parent may be null, but we may be "owned" by a collection. currentParent = Owner as ToolStripDropDown; } - if (currentParent != null) { + if (currentParent != null) + { return currentParent.OwnerItem; } return null; @@ -1565,19 +1814,21 @@ public ToolStripItem OwnerItem { } [ - SRCategory(nameof(SR.CatBehavior)), + SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ToolStripItemOwnerChangedDescr)) ] - public event EventHandler OwnerChanged { + public event EventHandler OwnerChanged + { add => Events.AddHandler(EventOwnerChanged, value); remove => Events.RemoveHandler(EventOwnerChanged, value); } [ - SRCategory(nameof(SR.CatAppearance)), + SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripItemOnPaintDescr)) ] - public event PaintEventHandler Paint { + public event PaintEventHandler Paint + { add => Events.AddHandler(EventPaint, value); remove => Events.RemoveHandler(EventPaint, value); } @@ -1593,18 +1844,21 @@ public event PaintEventHandler Paint { Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - internal protected ToolStrip Parent { - get { + internal protected ToolStrip Parent + { + get + { // we decided that there is no "parent" protection for toolstripitems. // since toolstrip and toolstripitem are tightly coupled. return ParentInternal; } - set { - ParentInternal = value; + set + { + ParentInternal = value; } } - + /// /// Specifies whether or not the item is glued to the ToolStrip or overflow or /// can float between the two. @@ -1614,21 +1868,26 @@ internal protected ToolStrip Parent { SRDescription(nameof(SR.ToolStripItemOverflowDescr)), SRCategory(nameof(SR.CatLayout)) ] - public ToolStripItemOverflow Overflow { - get { - return overflow; + public ToolStripItemOverflow Overflow + { + get + { + return overflow; } - set { + set + { //valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripItemOverflow.Never, (int)ToolStripItemOverflow.AsNeeded)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripGripStyle)); } - if (overflow != value) { - overflow = value; - if (Owner != null) { - LayoutTransaction.DoLayout(Owner, this.Owner, "Overflow"); - } + if (overflow != value) + { + overflow = value; + if (Owner != null) + { + LayoutTransaction.DoLayout(Owner, this.Owner, "Overflow"); + } } } } @@ -1640,25 +1899,32 @@ public ToolStripItemOverflow Overflow { SRDescription(nameof(SR.ToolStripItemPaddingDescr)), SRCategory(nameof(SR.CatLayout)) ] - public virtual Padding Padding { + public virtual Padding Padding + { get { return CommonProperties.GetPadding(this, DefaultPadding); } - set { - if (Padding != value) { + set + { + if (Padding != value) + { CommonProperties.SetPadding(this, value); InvalidateItemLayout(PropertyNames.Padding); } } - } - + } + /// /// This is explicitly a ToolStrip, because only ToolStrips know how to manage ToolStripitems /// - internal ToolStrip ParentInternal { - get { + internal ToolStrip ParentInternal + { + get + { return parent; } - set { - if (parent != value) { + set + { + if (parent != value) + { ToolStrip oldParent = parent; parent = value; OnParentChanged(oldParent, value); @@ -1670,51 +1936,63 @@ internal ToolStrip ParentInternal { /// Where the item actually ended up. /// [Browsable(false)] - public ToolStripItemPlacement Placement { - get { - return placement; + public ToolStripItemPlacement Placement + { + get + { + return placement; } } - internal Size PreferredImageSize { - get { - - if ((DisplayStyle & ToolStripItemDisplayStyle.Image) != ToolStripItemDisplayStyle.Image) { + internal Size PreferredImageSize + { + get + { + + if ((DisplayStyle & ToolStripItemDisplayStyle.Image) != ToolStripItemDisplayStyle.Image) + { return Size.Empty; } - + Image image = (Image)Properties.GetObject(PropImage); bool usingImageList = ((Owner != null) && (Owner.ImageList != null) && (ImageIndexer.ActualIndex >= 0)); - - if (ImageScaling == ToolStripItemImageScaling.SizeToFit) { + + if (ImageScaling == ToolStripItemImageScaling.SizeToFit) + { ToolStrip ownerToolStrip = Owner; - if (ownerToolStrip != null && (image != null || usingImageList)) { + if (ownerToolStrip != null && (image != null || usingImageList)) + { return ownerToolStrip.ImageScalingSize; } - } + } + - Size imageSize = Size.Empty; - if (usingImageList) { + if (usingImageList) + { imageSize = Owner.ImageList.ImageSize; } - else { - imageSize = (image == null) ? Size.Empty : image.Size; + else + { + imageSize = (image == null) ? Size.Empty : image.Size; } - + return imageSize; - + } - + } /// /// 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. /// - internal PropertyStore Properties { - get { - if (propertyStore == null) { + internal PropertyStore Properties + { + get + { + if (propertyStore == null) + { propertyStore = new PropertyStore(); } return propertyStore; @@ -1726,45 +2004,54 @@ internal PropertyStore Properties { /// Returns true if the state of the item is pushed /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public virtual bool Pressed { - get { + public virtual bool Pressed + { + get + { return CanSelect && state[statePressed]; - + } - } + } [ - SRCategory(nameof(SR.CatDragDrop)), + SRCategory(nameof(SR.CatDragDrop)), SRDescription(nameof(SR.ToolStripItemOnQueryContinueDragDescr)), EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false) ] - public event QueryContinueDragEventHandler QueryContinueDrag { + public event QueryContinueDragEventHandler QueryContinueDrag + { add => Events.AddHandler(EventQueryContinueDrag, value); remove => Events.RemoveHandler(EventQueryContinueDrag, value); } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ToolStripItemOnQueryAccessibilityHelpDescr))] - public event QueryAccessibilityHelpEventHandler QueryAccessibilityHelp { + public event QueryAccessibilityHelpEventHandler QueryAccessibilityHelp + { add => Events.AddHandler(EventQueryAccessibilityHelp, value); remove => Events.RemoveHandler(EventQueryAccessibilityHelp, value); } - - // Returns the value of the backColor field -- no asking the parent with its color is, etc. - internal Color RawBackColor { - get { - return Properties.GetColor(PropBackColor); + + // Returns the value of the backColor field -- no asking the parent with its color is, etc. + internal Color RawBackColor + { + get + { + return Properties.GetColor(PropBackColor); } } - internal ToolStripRenderer Renderer { - get { - if (Owner != null) { + internal ToolStripRenderer Renderer + { + get + { + if (Owner != null) + { return Owner.Renderer; } return (ParentInternal != null) ? ParentInternal.Renderer : null; - + } } @@ -1778,43 +2065,53 @@ internal ToolStripRenderer Renderer { Localizable(true), SRDescription(nameof(SR.ToolStripItemRightToLeftDescr)) ] - public virtual RightToLeft RightToLeft { - get { + public virtual RightToLeft RightToLeft + { + get + { bool found; int rightToLeft = Properties.GetInteger(PropRightToLeft, out found); - if (!found) { + if (!found) + { rightToLeft = (int)RightToLeft.Inherit; } - - if (((RightToLeft)rightToLeft) == RightToLeft.Inherit) { - if (Owner != null) { + + if (((RightToLeft)rightToLeft) == RightToLeft.Inherit) + { + if (Owner != null) + { rightToLeft = (int)Owner.RightToLeft; } - else if (ParentInternal != null) { + else if (ParentInternal != null) + { // case for Overflow & Grip rightToLeft = (int)ParentInternal.RightToLeft; } - else { + else + { rightToLeft = (int)DefaultRightToLeft; } } - return (RightToLeft)rightToLeft; + return (RightToLeft)rightToLeft; } - - set { + + set + { //valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)RightToLeft.No, (int)RightToLeft.Inherit)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(RightToLeft)); } - + RightToLeft oldValue = RightToLeft; - - if (Properties.ContainsInteger(PropRightToLeft) || value != RightToLeft.Inherit) { + + if (Properties.ContainsInteger(PropRightToLeft) || value != RightToLeft.Inherit) + { Properties.SetInteger(PropRightToLeft, (int)value); } - - if (oldValue != RightToLeft) { + + if (oldValue != RightToLeft) + { OnRightToLeftChanged(EventArgs.Empty); } } @@ -1833,33 +2130,42 @@ public virtual RightToLeft RightToLeft { Localizable(true), SRDescription(nameof(SR.ToolStripItemRightToLeftAutoMirrorImageDescr)) ] - public bool RightToLeftAutoMirrorImage { - get { + public bool RightToLeftAutoMirrorImage + { + get + { return state[stateRightToLeftAutoMirrorImage]; } - set { - if (state[stateRightToLeftAutoMirrorImage] != value) { - state[stateRightToLeftAutoMirrorImage] = value; + set + { + if (state[stateRightToLeftAutoMirrorImage] != value) + { + state[stateRightToLeftAutoMirrorImage] = value; Invalidate(); } } } - internal Image MirroredImage { - - - get { - if (state[stateInvalidMirroredImage]) { + internal Image MirroredImage + { + + + get + { + if (state[stateInvalidMirroredImage]) + { Image image = Image; - if (image != null) { + if (image != null) + { Image mirroredImage = image.Clone() as Image; mirroredImage.RotateFlip(RotateFlipType.RotateNoneFlipX); - + Properties.SetObject(PropMirroredImage, mirroredImage); state[stateInvalidMirroredImage] = false; return mirroredImage; } - else { + else + { return null; } } @@ -1867,7 +2173,8 @@ internal Image MirroredImage { } } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ToolStripItemOnRightToLeftChangedDescr))] - public event EventHandler RightToLeftChanged { + public event EventHandler RightToLeftChanged + { add => Events.AddHandler(EventRightToLeft, value); remove => Events.RemoveHandler(EventRightToLeft, value); } @@ -1890,10 +2197,12 @@ public event EventHandler RightToLeftChanged { /// /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public virtual bool Selected { - get { - return CanSelect && !DesignMode && (state[stateSelected] || - (ParentInternal != null && ParentInternal.IsSelectionSuspended && + public virtual bool Selected + { + get + { + return CanSelect && !DesignMode && (state[stateSelected] || + (ParentInternal != null && ParentInternal.IsSelectionSuspended && ParentInternal.LastMouseDownedItem == this)); } } @@ -1906,9 +2215,12 @@ public event EventHandler SelectedChanged { #endif /// - internal protected virtual bool ShowKeyboardCues { - get { - if (!DesignMode) { + internal protected virtual bool ShowKeyboardCues + { + get + { + if (!DesignMode) + { return ToolStripManager.ShowMenuFocusCues; } // default to true. @@ -1922,50 +2234,65 @@ internal protected virtual bool ShowKeyboardCues { Localizable(true), SRDescription(nameof(SR.ToolStripItemSizeDescr)) ] - public virtual Size Size { - get { - return Bounds.Size; + public virtual Size Size + { + get + { + return Bounds.Size; } - set { + set + { Rectangle currentBounds = Bounds; currentBounds.Size = value; - SetBounds(currentBounds); - } + SetBounds(currentBounds); + } } - internal bool SupportsRightClick { - get { + internal bool SupportsRightClick + { + get + { return state[stateSupportsRightClick]; } - set { + set + { state[stateSupportsRightClick] = value; } } - internal bool SupportsItemClick { - get { + internal bool SupportsItemClick + { + get + { return state[stateSupportsItemClick]; } - set { + set + { state[stateSupportsItemClick] = value; } } - internal bool SupportsSpaceKey { - get { + internal bool SupportsSpaceKey + { + get + { return state[stateSupportsSpaceKey]; } - set { + set + { state[stateSupportsSpaceKey] = value; } } - - internal bool SupportsDisabledHotTracking { - get { + + internal bool SupportsDisabledHotTracking + { + get + { return state[stateSupportsDisabledHotTracking]; } - set { + set + { state[stateSupportsDisabledHotTracking] = value; } } @@ -1978,15 +2305,19 @@ internal bool SupportsDisabledHotTracking { SRDescription(nameof(SR.ToolStripItemTagDescr)), TypeConverter(typeof(StringConverter)) ] - public object Tag { - get { - if (Properties.ContainsObject(ToolStripItem.PropTag)) { + public object Tag + { + get + { + if (Properties.ContainsObject(ToolStripItem.PropTag)) + { return propertyStore.GetObject(ToolStripItem.PropTag); } return null; - + } - set { + set + { Properties.SetObject(ToolStripItem.PropTag, value); } } @@ -1998,19 +2329,24 @@ public object Tag { Localizable(true), SRDescription(nameof(SR.ToolStripItemTextDescr)) ] - public virtual string Text { - get { - if (Properties.ContainsObject(ToolStripItem.PropText)) { + public virtual string Text + { + get + { + if (Properties.ContainsObject(ToolStripItem.PropText)) + { return (string)Properties.GetObject(ToolStripItem.PropText); } return ""; - + } - set { - if (value != Text) { + set + { + if (value != Text) + { Properties.SetObject(ToolStripItem.PropText, value); OnTextChanged(EventArgs.Empty); - + } } @@ -2027,23 +2363,29 @@ public virtual string Text { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripItemTextAlignDescr)) ] - public virtual ContentAlignment TextAlign { - get { + public virtual ContentAlignment TextAlign + { + get + { return textAlign; } - set { - if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) { + set + { + if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ContentAlignment)); } - if (textAlign != value) { + if (textAlign != value) + { textAlign = value; InvalidateItemLayout(PropertyNames.TextAlign); } } } - + [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ToolStripItemOnTextChangedDescr))] - public event EventHandler TextChanged { + public event EventHandler TextChanged + { add => Events.AddHandler(EventText, value); remove => Events.RemoveHandler(EventText, value); } @@ -2051,59 +2393,66 @@ public event EventHandler TextChanged { SRDescription(nameof(SR.ToolStripTextDirectionDescr)), SRCategory(nameof(SR.CatAppearance)) ] - public virtual ToolStripTextDirection TextDirection { - get { - ToolStripTextDirection textDirection = ToolStripTextDirection.Inherit; - if (Properties.ContainsObject(ToolStripItem.PropTextDirection)) { - textDirection= (ToolStripTextDirection)Properties.GetObject(ToolStripItem.PropTextDirection); - } - - if (textDirection == ToolStripTextDirection.Inherit) { - if (this.ParentInternal != null) { - // in the case we're on a ToolStripOverflow - textDirection = ParentInternal.TextDirection; - } - else { - textDirection = (Owner == null) ? ToolStripTextDirection.Horizontal : Owner.TextDirection; - } - } - - return textDirection; - } - set { - //valid values are 0x0 to 0x3 - if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripTextDirection.Inherit, (int)ToolStripTextDirection.Vertical270)) - { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripTextDirection)); - } - Properties.SetObject(ToolStripItem.PropTextDirection, value); - InvalidateItemLayout("TextDirection"); - } - } - - [DefaultValue(TextImageRelation.ImageBeforeText)] - [Localizable(true)] - [SRDescription(nameof(SR.ToolStripItemTextImageRelationDescr))] - [SRCategory(nameof(SR.CatAppearance))] - public TextImageRelation TextImageRelation + public virtual ToolStripTextDirection TextDirection { - get => textImageRelation; - set + get { - if (!ClientUtils.IsEnumValid(value, (int)value, (int)TextImageRelation.Overlay, (int)TextImageRelation.TextBeforeImage, 1)) + ToolStripTextDirection textDirection = ToolStripTextDirection.Inherit; + if (Properties.ContainsObject(ToolStripItem.PropTextDirection)) { - throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(TextImageRelation)); + textDirection = (ToolStripTextDirection)Properties.GetObject(ToolStripItem.PropTextDirection); } - if(value != TextImageRelation) + if (textDirection == ToolStripTextDirection.Inherit) { - textImageRelation = value; - InvalidateItemLayout(PropertyNames.TextImageRelation); - } - } - } + if (this.ParentInternal != null) + { + // in the case we're on a ToolStripOverflow + textDirection = ParentInternal.TextDirection; + } + else + { + textDirection = (Owner == null) ? ToolStripTextDirection.Horizontal : Owner.TextDirection; + } + } + + return textDirection; + } + set + { + //valid values are 0x0 to 0x3 + if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripTextDirection.Inherit, (int)ToolStripTextDirection.Vertical270)) + { + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripTextDirection)); + } + Properties.SetObject(ToolStripItem.PropTextDirection, value); + InvalidateItemLayout("TextDirection"); + } + } + + [DefaultValue(TextImageRelation.ImageBeforeText)] + [Localizable(true)] + [SRDescription(nameof(SR.ToolStripItemTextImageRelationDescr))] + [SRCategory(nameof(SR.CatAppearance))] + public TextImageRelation TextImageRelation + { + get => textImageRelation; + set + { + if (!ClientUtils.IsEnumValid(value, (int)value, (int)TextImageRelation.Overlay, (int)TextImageRelation.TextBeforeImage, 1)) + { + throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(TextImageRelation)); + } + + if (value != TextImageRelation) + { + textImageRelation = value; + InvalidateItemLayout(PropertyNames.TextImageRelation); + } + } + } + - /// /// !!!!This property ONLY works when toolStrip.ShowItemToolTips = true!!!! /// if AutoToolTip is set to true we return the Text as the ToolTipText. @@ -2112,19 +2461,24 @@ public TextImageRelation TextImageRelation [SRCategory(nameof(SR.CatBehavior))] [Editor("System.ComponentModel.Design.MultilineStringEditor, " + AssemblyRef.SystemDesign, typeof(System.Drawing.Design.UITypeEditor))] [Localizable(true)] - public string ToolTipText { - get { - if (AutoToolTip && string.IsNullOrEmpty(toolTipText)) { + public string ToolTipText + { + get + { + if (AutoToolTip && string.IsNullOrEmpty(toolTipText)) + { string toolText = Text; - if (WindowsFormsUtils.ContainsMnemonic(toolText)) { - // this shouldnt be called a lot so we can take the perf hit here. - toolText = string.Join("", toolText.Split('&')); + if (WindowsFormsUtils.ContainsMnemonic(toolText)) + { + // this shouldnt be called a lot so we can take the perf hit here. + toolText = string.Join("", toolText.Split('&')); } return toolText; } return toolTipText; } - set { + set + { toolTipText = value; } } @@ -2135,19 +2489,23 @@ public string ToolTipText { Localizable(true), SRDescription(nameof(SR.ToolStripItemVisibleDescr)) ] - public bool Visible { - get { - return (ParentInternal!=null) && (ParentInternal.Visible) && Available; + public bool Visible + { + get + { + return (ParentInternal != null) && (ParentInternal.Visible) && Available; } - set { - SetVisibleCore(value); + set + { + SetVisibleCore(value); } } - + [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ToolStripItemOnVisibleChangedDescr))] - public event EventHandler VisibleChanged { + public event EventHandler VisibleChanged + { add => Events.AddHandler(EventVisibleChanged, value); remove => Events.RemoveHandler(EventVisibleChanged, value); } @@ -2160,63 +2518,79 @@ public event EventHandler VisibleChanged { Browsable(false), EditorBrowsable(EditorBrowsableState.Always), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public int Width { - get { + public int Width + { + get + { return Bounds.Width; } - set { + set + { Rectangle currentBounds = this.Bounds; SetBounds(currentBounds.X, currentBounds.Y, value, currentBounds.Height); } } - - // - // Methods for ToolStripItem - // - internal void AccessibilityNotifyClients(AccessibleEvents accEvent) { - if (ParentInternal != null) { + // + // Methods for ToolStripItem + // + + internal void AccessibilityNotifyClients(AccessibleEvents accEvent) + { + if (ParentInternal != null) + { int index = ParentInternal.DisplayedItems.IndexOf(this); ParentInternal.AccessibilityNotifyClients(accEvent, index); } } - private void Animate() { + private void Animate() + { Animate(!DesignMode && Visible && Enabled && ParentInternal != null); } - private void StopAnimate() { + private void StopAnimate() + { Animate(false); } - private void Animate(bool animate) { - if (animate != state[stateCurrentlyAnimatingImage]) { - if (animate) { - if (Image != null) { - ImageAnimator.Animate(Image, new EventHandler(this.OnAnimationFrameChanged)); - state[stateCurrentlyAnimatingImage] = animate; - } - } - else { - if (Image != null) { - ImageAnimator.StopAnimate(Image, new EventHandler(this.OnAnimationFrameChanged)); - state[stateCurrentlyAnimatingImage] = animate; - } - } - } - } - - - internal bool BeginDragForItemReorder() { - if (Control.ModifierKeys == Keys.Alt) { - - if (this.ParentInternal.Items.Contains(this) && this.ParentInternal.AllowItemReorder) { + private void Animate(bool animate) + { + if (animate != state[stateCurrentlyAnimatingImage]) + { + if (animate) + { + if (Image != null) + { + ImageAnimator.Animate(Image, new EventHandler(this.OnAnimationFrameChanged)); + state[stateCurrentlyAnimatingImage] = animate; + } + } + else + { + if (Image != null) + { + ImageAnimator.StopAnimate(Image, new EventHandler(this.OnAnimationFrameChanged)); + state[stateCurrentlyAnimatingImage] = animate; + } + } + } + } + + + internal bool BeginDragForItemReorder() + { + if (Control.ModifierKeys == Keys.Alt) + { + + if (this.ParentInternal.Items.Contains(this) && this.ParentInternal.AllowItemReorder) + { // we only drag ToolStripItem item = this as ToolStripItem; - DoDragDrop(item,DragDropEffects.Move); + DoDragDrop(item, DragDropEffects.Move); return true; } - + } return false; } @@ -2227,7 +2601,8 @@ internal bool BeginDragForItemReorder() { /// should not call base.CreateAccessibilityObject. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual AccessibleObject CreateAccessibilityInstance() { + protected virtual AccessibleObject CreateAccessibilityInstance() + { return new ToolStripItemAccessibleObject(this); } @@ -2235,8 +2610,9 @@ protected virtual AccessibleObject CreateAccessibilityInstance() { /// Creates an instance of the object that defines how image and text /// gets laid out in the ToolStripItem /// - - internal virtual ToolStripItemInternalLayout CreateInternalLayout() { + + internal virtual ToolStripItemInternalLayout CreateInternalLayout() + { return new ToolStripItemInternalLayout(this); } /// @@ -2244,10 +2620,12 @@ internal virtual ToolStripItemInternalLayout CreateInternalLayout() { /// protected override void Dispose(bool disposing) { - if (disposing) { + if (disposing) + { state[stateDisposing] = true; - - if (this.Owner != null) { + + if (this.Owner != null) + { StopAnimate(); Debug.Assert(this.Owner.Items.Contains(this), "How can there be a owner and not be in the collection?"); this.Owner.Items.Remove(this); @@ -2255,19 +2633,21 @@ protected override void Dispose(bool disposing) state[stateDisposed] = true; } } - base.Dispose (disposing); + base.Dispose(disposing); + + if (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(PropMirroredImage, null); + Properties.SetObject(PropImage, null); + state[stateDisposing] = false; + } - if (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(PropMirroredImage, null); - Properties.SetObject(PropImage, null); - state[stateDisposing] = false; - } - } - internal static long DoubleClickTicks { + internal static long DoubleClickTicks + { // (DoubleClickTime in ms) * 1,000,000 ns/1ms * 1 Tick / 100ns = XXX in Ticks. // Therefore: (DoubleClickTime) * 1,000,000/100 = xxx in Ticks. get { return SystemInformation.DoubleClickTime * 10000; } @@ -2282,19 +2662,23 @@ internal static long DoubleClickTicks { /// implements System.Windows.Forms.IDataObject. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public DragDropEffects DoDragDrop(object data, DragDropEffects allowedEffects) { - int[] finalEffect = new int[] {(int)DragDropEffects.None}; + public DragDropEffects DoDragDrop(object data, DragDropEffects allowedEffects) + { + int[] finalEffect = new int[] { (int)DragDropEffects.None }; UnsafeNativeMethods.IOleDropSource dropSource = this.DropSource; IComDataObject dataObject = null; dataObject = data as IComDataObject; - if (dataObject == null) { + if (dataObject == null) + { DataObject iwdata = null; IDataObject idataObject = data as IDataObject; - if (idataObject != null) { + if (idataObject != null) + { iwdata = new DataObject(idataObject); } - else if (data is ToolStripItem) { + else if (data is ToolStripItem) + { // it seems that the DataObject does string comparison // on the type, so you can't ask for GetDataPresent of @@ -2305,27 +2689,33 @@ public DragDropEffects DoDragDrop(object data, DragDropEffects allowedEffects) { iwdata = new DataObject(); iwdata.SetData(typeof(ToolStripItem).ToString(), data); } - else { + else + { iwdata = new DataObject(); iwdata.SetData(data); } dataObject = (IComDataObject)iwdata; } - try { + try + { SafeNativeMethods.DoDragDrop(dataObject, dropSource, (int)allowedEffects, finalEffect); } - catch { + catch + { } - return(DragDropEffects)finalEffect[0]; + return (DragDropEffects)finalEffect[0]; } - - internal void FireEvent(ToolStripItemEventType met) { + + internal void FireEvent(ToolStripItemEventType met) + { FireEvent(EventArgs.Empty, met); } - internal void FireEvent(EventArgs e, ToolStripItemEventType met) { + internal void FireEvent(EventArgs e, ToolStripItemEventType met) + { - switch (met) { + switch (met) + { case ToolStripItemEventType.LocationChanged: OnLocationChanged(e); break; @@ -2335,10 +2725,12 @@ internal void FireEvent(EventArgs e, ToolStripItemEventType met) { case ToolStripItemEventType.MouseHover: // disabled toolstrip items should show tooltips. // we wont raise mouse events though. - if (!Enabled && ParentInternal != null && !string.IsNullOrEmpty(ToolTipText)) { + if (!Enabled && ParentInternal != null && !string.IsNullOrEmpty(ToolTipText)) + { ParentInternal.UpdateToolTip(this); } - else { + else + { FireEventInteractive(e, met); } break; @@ -2348,42 +2740,49 @@ internal void FireEvent(EventArgs e, ToolStripItemEventType met) { case ToolStripItemEventType.MouseLeave: // disabled toolstrip items should also clear tooltips. // we wont raise mouse events though. - if (!Enabled && ParentInternal != null) { - ParentInternal.UpdateToolTip(null); - } - else { - HandleMouseLeave(e); - } - break; + if (!Enabled && ParentInternal != null) + { + ParentInternal.UpdateToolTip(null); + } + else + { + HandleMouseLeave(e); + } + break; case ToolStripItemEventType.MouseMove: // Disabled items typically dont get mouse move // but they should be allowed to re-order if the ALT key is pressed - if (!Enabled && ParentInternal != null) { + if (!Enabled && ParentInternal != null) + { BeginDragForItemReorder(); } - else { + else + { FireEventInteractive(e, met); } - break; + break; default: FireEventInteractive(e, met); break; } - + } /// /// - [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] - internal void FireEventInteractive(EventArgs e, ToolStripItemEventType met) { - if (Enabled) { - switch (met) { + [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] + internal void FireEventInteractive(EventArgs e, ToolStripItemEventType met) + { + if (Enabled) + { + switch (met) + { case ToolStripItemEventType.MouseMove: HandleMouseMove(e as MouseEventArgs); break; case ToolStripItemEventType.MouseHover: HandleMouseHover(e as EventArgs); - break; + break; case ToolStripItemEventType.MouseUp: HandleMouseUp(e as MouseEventArgs); break; @@ -2394,8 +2793,8 @@ internal void FireEventInteractive(EventArgs e, ToolStripItemEventType met) { HandleClick(e); break; case ToolStripItemEventType.DoubleClick: - HandleDoubleClick(e); - break; + HandleDoubleClick(e); + break; default: Debug.Assert(false, "Invalid event type."); break; @@ -2403,50 +2802,62 @@ internal void FireEventInteractive(EventArgs e, ToolStripItemEventType met) { } } - private Font GetOwnerFont() { - if (Owner != null) { + private Font GetOwnerFont() + { + if (Owner != null) + { return Owner.Font; } return null; } - + /// we dont want a public settable property... and usually owner will work /// except for things like the overflow button - public ToolStrip GetCurrentParent() { + public ToolStrip GetCurrentParent() + { return this.Parent; } - internal ToolStripDropDown GetCurrentParentDropDown() { - if (ParentInternal != null) { + internal ToolStripDropDown GetCurrentParentDropDown() + { + if (ParentInternal != null) + { return ParentInternal as ToolStripDropDown; } - else { + else + { return Owner as ToolStripDropDown; } } [SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces")] - public virtual Size GetPreferredSize(Size constrainingSize) { - - // Switch Size.Empty to maximum possible values - constrainingSize = LayoutUtils.ConvertZeroToUnbounded(constrainingSize); - return InternalLayout.GetPreferredSize(constrainingSize - Padding.Size) + Padding.Size; + public virtual Size GetPreferredSize(Size constrainingSize) + { + + // Switch Size.Empty to maximum possible values + constrainingSize = LayoutUtils.ConvertZeroToUnbounded(constrainingSize); + return InternalLayout.GetPreferredSize(constrainingSize - Padding.Size) + Padding.Size; } - internal Size GetTextSize() { - if (string.IsNullOrEmpty(Text)) { + internal Size GetTextSize() + { + if (string.IsNullOrEmpty(Text)) + { return Size.Empty; - } - else if (cachedTextSize == Size.Empty) { + } + else if (cachedTextSize == Size.Empty) + { cachedTextSize = TextRenderer.MeasureText(Text, Font); - } - return cachedTextSize; + } + return cachedTextSize; } /// /// Invalidates the ToolStripItem /// - public void Invalidate() { - if (this.ParentInternal != null) { + public void Invalidate() + { + if (this.ParentInternal != null) + { ParentInternal.Invalidate(this.Bounds, true); } } @@ -2455,51 +2866,63 @@ public void Invalidate() { /// /// invalidates a rectangle within the ToolStripItem's bounds /// - public void Invalidate(Rectangle r) { + public void Invalidate(Rectangle r) + { // the only value add to this over calling invalidate on the ToolStrip is that // you can specify the rectangle with coordinates relative to the upper left hand // corner of the ToolStripItem. Point rectangleLocation = this.TranslatePoint(r.Location, ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ToolStripCoords); - - if (this.ParentInternal != null) { + + if (this.ParentInternal != null) + { ParentInternal.Invalidate(new Rectangle(rectangleLocation, r.Size), true); } } - internal void InvalidateItemLayout(string affectedProperty, bool invalidatePainting) { + internal void InvalidateItemLayout(string affectedProperty, bool invalidatePainting) + { this.toolStripItemInternalLayout = null; - if (Owner != null) { + if (Owner != null) + { LayoutTransaction.DoLayout(Owner, this, affectedProperty); } - - if (invalidatePainting && Owner != null) { - Owner.Invalidate(); + + if (invalidatePainting && Owner != null) + { + Owner.Invalidate(); } } - internal void InvalidateItemLayout(string affectedProperty) { + internal void InvalidateItemLayout(string affectedProperty) + { InvalidateItemLayout(affectedProperty, /*invalidatePainting*/true); } - internal void InvalidateImageListImage() { + internal void InvalidateImageListImage() + { // invalidate the cache. - if (ImageIndexer.ActualIndex >= 0) { + if (ImageIndexer.ActualIndex >= 0) + { Properties.SetObject(PropImage, null); InvalidateItemLayout(PropertyNames.Image); - } + } } - internal void InvokePaint() { - if (this.ParentInternal != null) { + internal void InvokePaint() + { + if (this.ParentInternal != null) + { this.ParentInternal.InvokePaintItem(this); } } - protected internal virtual bool IsInputKey(Keys keyData) { + protected internal virtual bool IsInputKey(Keys keyData) + { return false; } - - protected internal virtual bool IsInputChar(char charCode) { + + protected internal virtual bool IsInputChar(char charCode) + { return false; } @@ -2507,90 +2930,109 @@ protected internal virtual bool IsInputChar(char charCode) { // Private handlers which are the equivilant of Control.Wm // - private void HandleClick(System.EventArgs e) { - Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] HandleClick"); + private void HandleClick(System.EventArgs e) + { + Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] HandleClick"); - try { - if (!DesignMode) { + try + { + if (!DesignMode) + { state[statePressed] = true; } // force painting w/o using message loop here because it may be quite a long // time before it gets pumped again. InvokePaint(); - if (SupportsItemClick && Owner != null) { - Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] HandleItemClick"); - Owner.HandleItemClick(this); + if (SupportsItemClick && Owner != null) + { + Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] HandleItemClick"); + Owner.HandleItemClick(this); } OnClick(e); - - if (SupportsItemClick && Owner != null) { - Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] HandleItemClicked"); - Owner.HandleItemClicked(this); + + if (SupportsItemClick && Owner != null) + { + Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] HandleItemClicked"); + Owner.HandleItemClicked(this); } } - finally { + finally + { state[statePressed] = false; } // when we get around to it, paint unpressed. Invalidate(); - + } - private void HandleDoubleClick(System.EventArgs e) { + private void HandleDoubleClick(System.EventArgs e) + { OnDoubleClick(e); } - private void HandlePaint(PaintEventArgs e) { + private void HandlePaint(PaintEventArgs e) + { Animate(); ImageAnimator.UpdateFrames(this.Image); OnPaint(e); RaisePaintEvent(EventPaint, e); } - private void HandleMouseEnter(System.EventArgs e) { - - if (!DesignMode) { - if (ParentInternal != null - && ParentInternal.CanHotTrack - && ParentInternal.ShouldSelectItem()) { - - if (Enabled) { - // calling select can dismiss a child dropdown which would break auto-expansion. - // save off auto expand and restore it. - bool autoExpand = ParentInternal.MenuAutoExpand; - - if (ParentInternal.LastMouseDownedItem == this) { - // Same as Control.MouseButtons == MouseButtons.Left, but slightly more efficient. - if (UnsafeNativeMethods.GetKeyState((int)Keys.LButton) < 0) { + private void HandleMouseEnter(System.EventArgs e) + { + + if (!DesignMode) + { + if (ParentInternal != null + && ParentInternal.CanHotTrack + && ParentInternal.ShouldSelectItem()) + { + + if (Enabled) + { + // calling select can dismiss a child dropdown which would break auto-expansion. + // save off auto expand and restore it. + bool autoExpand = ParentInternal.MenuAutoExpand; + + if (ParentInternal.LastMouseDownedItem == this) + { + // Same as Control.MouseButtons == MouseButtons.Left, but slightly more efficient. + if (UnsafeNativeMethods.GetKeyState((int)Keys.LButton) < 0) + { this.Push(true); - } - } - + } + } + Select(); ParentInternal.MenuAutoExpand = autoExpand; } - else if (SupportsDisabledHotTracking) { + else if (SupportsDisabledHotTracking) + { Select(); - } - } + } + } } KeyboardToolTipStateMachine.Instance.NotifyAboutMouseEnter(this); - if (Enabled) { + if (Enabled) + { OnMouseEnter(e); - Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] MouseEnter"); + Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] MouseEnter"); RaiseEvent(EventMouseEnter, e); } - + } - private void HandleMouseMove(System.Windows.Forms.MouseEventArgs mea) { - Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] MouseMove"); + private void HandleMouseMove(System.Windows.Forms.MouseEventArgs mea) + { + Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] MouseMove"); - if (Enabled && CanSelect && !Selected) { - if (ParentInternal != null - && ParentInternal.CanHotTrack - && ParentInternal.ShouldSelectItem()) { + if (Enabled && CanSelect && !Selected) + { + if (ParentInternal != null + && ParentInternal.CanHotTrack + && ParentInternal.ShouldSelectItem()) + { // this is the case where we got a mouse enter, but ShouldSelectItem // returned false. // typically occus when a window first opens - we get a mouse enter on the item @@ -2600,36 +3042,44 @@ private void HandleMouseMove(System.Windows.Forms.MouseEventArgs mea) { } OnMouseMove(mea); RaiseMouseEvent(EventMouseMove, mea); - - } - private void HandleMouseHover(EventArgs e) { - Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] MouseHover"); + + } + private void HandleMouseHover(EventArgs e) + { + Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] MouseHover"); OnMouseHover(e); RaiseEvent(EventMouseHover, e); } - private void HandleLeave() { - if (state[stateMouseDownAndNoDrag] || state[statePressed] || state[stateSelected]) { + private void HandleLeave() + { + if (state[stateMouseDownAndNoDrag] || state[statePressed] || state[stateSelected]) + { state[stateMouseDownAndNoDrag | statePressed | stateSelected] = false; KeyboardToolTipStateMachine.Instance.NotifyAboutLostFocus(this); Invalidate(); - } + } } - private void HandleMouseLeave(System.EventArgs e) { + private void HandleMouseLeave(System.EventArgs e) + { Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] MouseLeave"); HandleLeave(); - if (Enabled) { + if (Enabled) + { OnMouseLeave(e); RaiseEvent(EventMouseLeave, e); } } - private void HandleMouseDown(MouseEventArgs e) { - Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] MouseDown"); - + private void HandleMouseDown(MouseEventArgs e) + { + Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] MouseDown"); + state[stateMouseDownAndNoDrag] = !BeginDragForItemReorder(); - if (state[stateMouseDownAndNoDrag]) { - if (e.Button == MouseButtons.Left) { + if (state[stateMouseDownAndNoDrag]) + { + if (e.Button == MouseButtons.Left) + { this.Push(true); } // @@ -2637,13 +3087,15 @@ private void HandleMouseDown(MouseEventArgs e) { RaiseMouseEvent(EventMouseDown, e); } } - private void HandleMouseUp(MouseEventArgs e) { - - Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] MouseUp"); + private void HandleMouseUp(MouseEventArgs e) + { + + Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] MouseUp"); bool fireMouseUp = (ParentInternal.LastMouseDownedItem == this); - if (!fireMouseUp && !MouseDownAndUpMustBeInSameItem) { + if (!fireMouseUp && !MouseDownAndUpMustBeInSameItem) + { // in the case of menus, you can mouse down on one item and mouse up // on another. We do need to be careful // that the mouse has actually moved from when a dropdown has been opened - @@ -2653,28 +3105,34 @@ private void HandleMouseUp(MouseEventArgs e) { } - if (state[stateMouseDownAndNoDrag] || fireMouseUp) { + if (state[stateMouseDownAndNoDrag] || fireMouseUp) + { this.Push(false); - if (e.Button == MouseButtons.Left || (e.Button == MouseButtons.Right && state[stateSupportsRightClick])) { + if (e.Button == MouseButtons.Left || (e.Button == MouseButtons.Right && state[stateSupportsRightClick])) + { bool shouldFireDoubleClick = false; - if (DoubleClickEnabled) { + if (DoubleClickEnabled) + { long newTime = DateTime.Now.Ticks; long deltaTicks = newTime - lastClickTime; lastClickTime = newTime; // use >= for cases where the delta is so fast DateTime cannot pick up the delta. Debug.Assert(deltaTicks >= 0, "why are deltaticks less than zero? thats some mighty fast clicking"); // if we've seen a mouse up less than the double click time ago, we should fire. - if (deltaTicks >= 0 && deltaTicks < DoubleClickTicks) { + if (deltaTicks >= 0 && deltaTicks < DoubleClickTicks) + { shouldFireDoubleClick = true; } } - if (shouldFireDoubleClick) { + if (shouldFireDoubleClick) + { HandleDoubleClick(EventArgs.Empty); // If we actually fired DoubleClick - reset the lastClickTime. lastClickTime = 0; - } - else { + } + else + { HandleClick(EventArgs.Empty); } } @@ -2682,85 +3140,104 @@ private void HandleMouseUp(MouseEventArgs e) { // OnMouseUp(e); RaiseMouseEvent(EventMouseUp, e); - - + + } } - internal virtual void OnAccessibleDescriptionChanged(EventArgs e) { + internal virtual void OnAccessibleDescriptionChanged(EventArgs e) + { } - internal virtual void OnAccessibleNameChanged(EventArgs e) { + internal virtual void OnAccessibleNameChanged(EventArgs e) + { } - internal virtual void OnAccessibleDefaultActionDescriptionChanged(EventArgs e) { + internal virtual void OnAccessibleDefaultActionDescriptionChanged(EventArgs e) + { } - internal virtual void OnAccessibleRoleChanged(EventArgs e) { + internal virtual void OnAccessibleRoleChanged(EventArgs e) + { } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnBackColorChanged(EventArgs e) { - this.Invalidate(); - RaiseEvent(EventBackColorChanged, e); + protected virtual void OnBackColorChanged(EventArgs e) + { + this.Invalidate(); + RaiseEvent(EventBackColorChanged, e); } - protected virtual void OnBoundsChanged() { + protected virtual void OnBoundsChanged() + { LayoutTransaction.DoLayout(this.ParentInternal, this, PropertyNames.Bounds); InternalLayout.PerformLayout(); } - - - protected virtual void OnClick(System.EventArgs e) { + + + protected virtual void OnClick(System.EventArgs e) + { RaiseEvent(EventClick, e); } - protected internal virtual void OnLayout(LayoutEventArgs e) { + protected internal virtual void OnLayout(LayoutEventArgs e) + { } /// /// Explicit support of DropTarget /// - void IDropTarget.OnDragEnter(DragEventArgs dragEvent) { + void IDropTarget.OnDragEnter(DragEventArgs dragEvent) + { OnDragEnter(dragEvent); } - void IDropTarget.OnDragOver(DragEventArgs dragEvent) { + void IDropTarget.OnDragOver(DragEventArgs dragEvent) + { OnDragOver(dragEvent); } - void IDropTarget.OnDragLeave(EventArgs e) { + void IDropTarget.OnDragLeave(EventArgs e) + { OnDragLeave(e); } - void IDropTarget.OnDragDrop(DragEventArgs dragEvent) { + void IDropTarget.OnDragDrop(DragEventArgs dragEvent) + { OnDragDrop(dragEvent); } /// /// Explicit support of DropSource /// - void ISupportOleDropSource.OnGiveFeedback(GiveFeedbackEventArgs giveFeedbackEventArgs) { + void ISupportOleDropSource.OnGiveFeedback(GiveFeedbackEventArgs giveFeedbackEventArgs) + { OnGiveFeedback(giveFeedbackEventArgs); } - void ISupportOleDropSource.OnQueryContinueDrag(QueryContinueDragEventArgs queryContinueDragEventArgs) { + void ISupportOleDropSource.OnQueryContinueDrag(QueryContinueDragEventArgs queryContinueDragEventArgs) + { OnQueryContinueDrag(queryContinueDragEventArgs); } - private void OnAnimationFrameChanged(object o, EventArgs e) { + private void OnAnimationFrameChanged(object o, EventArgs e) + { + + ToolStrip parent = ParentInternal; + if (parent != null) + { + if (parent.Disposing || parent.IsDisposed) + { + return; + } - ToolStrip parent = ParentInternal; - if (parent != null) { - if (parent.Disposing || parent.IsDisposed) { - return; - } + if (parent.IsHandleCreated && parent.InvokeRequired) + { + parent.BeginInvoke(new EventHandler(this.OnAnimationFrameChanged), new object[] { o, e }); + return; + } - if (parent.IsHandleCreated && parent.InvokeRequired) { - parent.BeginInvoke(new EventHandler(this.OnAnimationFrameChanged), new object[]{o,e}); - return; - } + Invalidate(); + } + } - Invalidate(); - } - } - - protected virtual void OnAvailableChanged(System.EventArgs e) { + protected virtual void OnAvailableChanged(System.EventArgs e) + { RaiseEvent(EventAvailableChanged, e); } @@ -2774,7 +3251,8 @@ protected virtual void OnAvailableChanged(System.EventArgs e) { /// Call base.onDragEnter to send this event to any registered event listeners. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnDragEnter(DragEventArgs dragEvent) { + protected virtual void OnDragEnter(DragEventArgs dragEvent) + { RaiseDragEvent(EventDragEnter, dragEvent); } @@ -2783,24 +3261,27 @@ protected virtual void OnDragEnter(DragEventArgs dragEvent) { /// Call base.onDragOver to send this event to any registered event listeners. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnDragOver(DragEventArgs dragEvent) { - RaiseDragEvent(EventDragOver, dragEvent); + protected virtual void OnDragOver(DragEventArgs dragEvent) + { + RaiseDragEvent(EventDragOver, dragEvent); } /// /// Inheriting classes should override this method to handle this event. /// Call base.onDragLeave to send this event to any registered event listeners. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnDragLeave(EventArgs e) { + protected virtual void OnDragLeave(EventArgs e) + { RaiseEvent(EventDragLeave, e); } - + /// /// Inheriting classes should override this method to handle this event. /// Call base.onDragDrop to send this event to any registered event listeners. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnDragDrop(DragEventArgs dragEvent) { + protected virtual void OnDragDrop(DragEventArgs dragEvent) + { RaiseDragEvent(EventDragDrop, dragEvent); } @@ -2808,7 +3289,8 @@ protected virtual void OnDragDrop(DragEventArgs dragEvent) { /// Inheriting classes should override this method to handle this event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnDisplayStyleChanged(EventArgs e) { + protected virtual void OnDisplayStyleChanged(EventArgs e) + { RaiseEvent(EventDisplayStyleChanged, e); } @@ -2818,12 +3300,15 @@ protected virtual void OnDisplayStyleChanged(EventArgs e) { /// [EditorBrowsable(EditorBrowsableState.Advanced)] [SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces")] // PM review done - protected virtual void OnGiveFeedback(GiveFeedbackEventArgs giveFeedbackEvent) { + protected virtual void OnGiveFeedback(GiveFeedbackEventArgs giveFeedbackEvent) + { GiveFeedbackEventHandler handler = (GiveFeedbackEventHandler)Events[EventGiveFeedback]; - if (handler != null) handler(this,giveFeedbackEvent); + if (handler != null) + handler(this, giveFeedbackEvent); } - internal virtual void OnImageScalingSizeChanged(EventArgs e) { + internal virtual void OnImageScalingSizeChanged(EventArgs e) + { } /// /// Inheriting classes should override this method to handle this event. @@ -2831,111 +3316,134 @@ internal virtual void OnImageScalingSizeChanged(EventArgs e) { /// [EditorBrowsable(EditorBrowsableState.Advanced)] [SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces")] // PM review done - protected virtual void OnQueryContinueDrag(QueryContinueDragEventArgs queryContinueDragEvent) { + protected virtual void OnQueryContinueDrag(QueryContinueDragEventArgs queryContinueDragEvent) + { RaiseQueryContinueDragEvent(EventQueryContinueDrag, queryContinueDragEvent); } /// /// Inheriting classes should override this method to handle this event. /// - protected virtual void OnDoubleClick(System.EventArgs e) { + protected virtual void OnDoubleClick(System.EventArgs e) + { RaiseEvent(EventDoubleClick, e); } /// /// Inheriting classes should override this method to handle this event. /// - protected virtual void OnEnabledChanged(System.EventArgs e) { - RaiseEvent(EventEnabledChanged, e); - Animate(); + protected virtual void OnEnabledChanged(System.EventArgs e) + { + RaiseEvent(EventEnabledChanged, e); + Animate(); } - internal void OnInternalEnabledChanged(System.EventArgs e) { - RaiseEvent(EventInternalEnabledChanged, e); + internal void OnInternalEnabledChanged(System.EventArgs e) + { + RaiseEvent(EventInternalEnabledChanged, e); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnForeColorChanged(EventArgs e) { - this.Invalidate(); - RaiseEvent(EventForeColorChanged, e); + protected virtual void OnForeColorChanged(EventArgs e) + { + this.Invalidate(); + RaiseEvent(EventForeColorChanged, e); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnFontChanged(EventArgs e) { - cachedTextSize = Size.Empty; - // PERF - only invalidate if we actually care about the font - if ((DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) { + protected virtual void OnFontChanged(EventArgs e) + { + cachedTextSize = Size.Empty; + // PERF - only invalidate if we actually care about the font + if ((DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) + { this.InvalidateItemLayout(PropertyNames.Font); - } - else { - this.toolStripItemInternalLayout = null; - } - RaiseEvent(EventFontChanged, e); + } + else + { + this.toolStripItemInternalLayout = null; + } + RaiseEvent(EventFontChanged, e); } - protected virtual void OnLocationChanged (System.EventArgs e) { + protected virtual void OnLocationChanged(System.EventArgs e) + { RaiseEvent(EventLocationChanged, e); } /// /// Inheriting classes should override this method to handle this event. /// - protected virtual void OnMouseEnter(EventArgs e) { - } + protected virtual void OnMouseEnter(EventArgs e) + { + } /// /// Inheriting classes should override this method to handle this event. /// - protected virtual void OnMouseMove(System.Windows.Forms.MouseEventArgs mea) { + protected virtual void OnMouseMove(System.Windows.Forms.MouseEventArgs mea) + { } /// /// Inheriting classes should override this method to handle this event. /// - protected virtual void OnMouseHover(EventArgs e) { - if (ParentInternal != null && !string.IsNullOrEmpty(ToolTipText)) { - ParentInternal.UpdateToolTip(this); + protected virtual void OnMouseHover(EventArgs e) + { + if (ParentInternal != null && !string.IsNullOrEmpty(ToolTipText)) + { + ParentInternal.UpdateToolTip(this); } } /// /// Inheriting classes should override this method to handle this event. /// - protected virtual void OnMouseLeave(EventArgs e) { - if (ParentInternal != null) { + protected virtual void OnMouseLeave(EventArgs e) + { + if (ParentInternal != null) + { ParentInternal.UpdateToolTip(null); } } /// /// Inheriting classes should override this method to handle this event. /// - protected virtual void OnMouseDown(MouseEventArgs e) { + protected virtual void OnMouseDown(MouseEventArgs e) + { } /// /// Inheriting classes should override this method to handle this event. /// - protected virtual void OnMouseUp(MouseEventArgs e) { + protected virtual void OnMouseUp(MouseEventArgs e) + { } /// /// Inheriting classes should override this method to handle this event. /// - protected virtual void OnPaint(System.Windows.Forms.PaintEventArgs e) { + protected virtual void OnPaint(System.Windows.Forms.PaintEventArgs e) + { } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnParentBackColorChanged(EventArgs e) { + protected virtual void OnParentBackColorChanged(EventArgs e) + { Color backColor = Properties.GetColor(PropBackColor); - if (backColor.IsEmpty) { + if (backColor.IsEmpty) + { OnBackColorChanged(e); } } /// /// Inheriting classes should override this method to handle this event. /// - protected virtual void OnParentChanged(ToolStrip oldParent, ToolStrip newParent) { + protected virtual void OnParentChanged(ToolStrip oldParent, ToolStrip newParent) + { SetAmbientMargin(); - if ((oldParent != null) && (oldParent.DropTargetManager != null)) { + if ((oldParent != null) && (oldParent.DropTargetManager != null)) + { oldParent.DropTargetManager.EnsureUnRegistered(this); } - if (AllowDrop && (newParent != null)) { + if (AllowDrop && (newParent != null)) + { EnsureParentDropTargetRegistered(); } Animate(); @@ -2944,9 +3452,10 @@ protected virtual void OnParentChanged(ToolStrip oldParent, ToolStrip newParent) /// /// Occurs when this.Parent.Enabled changes. /// - protected internal virtual void OnParentEnabledChanged(System.EventArgs e) { + protected internal virtual void OnParentEnabledChanged(System.EventArgs e) + { OnEnabledChanged(EventArgs.Empty); - } + } /// /// Occurs when the font property has changed on the parent - used to notify inheritors of the font property that @@ -2954,23 +3463,29 @@ protected internal virtual void OnParentEnabledChanged(System.EventArgs e) { /// /// [EditorBrowsable(EditorBrowsableState.Advanced)] - internal protected virtual void OnOwnerFontChanged(EventArgs e) { - if (Properties.GetObject(PropFont) == null) { + internal protected virtual void OnOwnerFontChanged(EventArgs e) + { + if (Properties.GetObject(PropFont) == null) + { OnFontChanged(e); } } - + [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnParentForeColorChanged(EventArgs e) { + protected virtual void OnParentForeColorChanged(EventArgs e) + { Color foreColor = Properties.GetColor(PropForeColor); - if (foreColor.IsEmpty) { + if (foreColor.IsEmpty) + { OnForeColorChanged(e); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected internal virtual void OnParentRightToLeftChanged(EventArgs e) { - if (!Properties.ContainsInteger(PropRightToLeft) || ((RightToLeft)Properties.GetInteger(PropRightToLeft)) == RightToLeft.Inherit) { + protected internal virtual void OnParentRightToLeftChanged(EventArgs e) + { + if (!Properties.ContainsInteger(PropRightToLeft) || ((RightToLeft)Properties.GetInteger(PropRightToLeft)) == RightToLeft.Inherit) + { OnRightToLeftChanged(e); } } @@ -2979,41 +3494,49 @@ protected internal virtual void OnParentRightToLeftChanged(EventArgs e) { /// /// Occurs when the owner of an item changes. /// - protected virtual void OnOwnerChanged(EventArgs e) { - RaiseEvent(EventOwnerChanged,e); + protected virtual void OnOwnerChanged(EventArgs e) + { + RaiseEvent(EventOwnerChanged, e); SetAmbientMargin(); - if (Owner != null) { + if (Owner != null) + { // check if we need to fire OnRightToLeftChanged bool found = false; int rightToLeft = Properties.GetInteger(PropRightToLeft, out found); - if (!found) { + if (!found) + { rightToLeft = (int)RightToLeft.Inherit; } - if ((rightToLeft == (int)RightToLeft.Inherit) && RightToLeft != DefaultRightToLeft) { + if ((rightToLeft == (int)RightToLeft.Inherit) && RightToLeft != DefaultRightToLeft) + { OnRightToLeftChanged(EventArgs.Empty); } } } [EditorBrowsable(EditorBrowsableState.Advanced)] - internal void OnOwnerTextDirectionChanged() { + internal void OnOwnerTextDirectionChanged() + { ToolStripTextDirection textDirection = ToolStripTextDirection.Inherit; - if (Properties.ContainsObject(ToolStripItem.PropTextDirection)) { - textDirection= (ToolStripTextDirection)Properties.GetObject(ToolStripItem.PropTextDirection); + if (Properties.ContainsObject(ToolStripItem.PropTextDirection)) + { + textDirection = (ToolStripTextDirection)Properties.GetObject(ToolStripItem.PropTextDirection); } - if (textDirection == ToolStripTextDirection.Inherit) { + if (textDirection == ToolStripTextDirection.Inherit) + { InvalidateItemLayout("TextDirection"); } } - + /// /// Inheriting classes should override this method to handle this event. /// - protected virtual void OnRightToLeftChanged(EventArgs e) { - InvalidateItemLayout(PropertyNames.RightToLeft); + protected virtual void OnRightToLeftChanged(EventArgs e) + { + InvalidateItemLayout(PropertyNames.RightToLeft); RaiseEvent(EventRightToLeft, e); - + } #if SELECTEDCHANGED protected virtual void OnSelectedChanged(EventArgs e) { @@ -3021,26 +3544,31 @@ protected virtual void OnSelectedChanged(EventArgs e) { } #endif [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnTextChanged(EventArgs e) { - cachedTextSize = Size.Empty; - // Make sure we clear the cache before we perform the layout. - InvalidateItemLayout(PropertyNames.Text); - RaiseEvent(EventText, e); + protected virtual void OnTextChanged(EventArgs e) + { + cachedTextSize = Size.Empty; + // Make sure we clear the cache before we perform the layout. + InvalidateItemLayout(PropertyNames.Text); + RaiseEvent(EventText, e); } - + /// /// Inheriting classes should override this method to handle this event. /// - protected virtual void OnVisibleChanged(System.EventArgs e) { - if (Owner != null && !(Owner.IsDisposed || Owner.Disposing)) { + protected virtual void OnVisibleChanged(System.EventArgs e) + { + if (Owner != null && !(Owner.IsDisposed || Owner.Disposing)) + { Owner.OnItemVisibleChanged(new ToolStripItemEventArgs(this), /*performLayout*/true); } RaiseEvent(EventVisibleChanged, e); Animate(); } - public void PerformClick() { - if (Enabled && Available) { + public void PerformClick() + { + if (Enabled && Available) + { FireEvent(ToolStripItemEventType.Click); } } @@ -3048,14 +3576,18 @@ public void PerformClick() { /// /// Pushes the button. /// - internal void Push(bool push) { - if (!CanSelect || !Enabled || DesignMode) { - return; + internal void Push(bool push) + { + if (!CanSelect || !Enabled || DesignMode) + { + return; } - if (state[statePressed] != push) { - state[statePressed] = push; - if (Available) { + if (state[statePressed] != push) + { + state[statePressed] = push; + if (Available) + { this.Invalidate(); } } @@ -3063,11 +3595,14 @@ internal void Push(bool push) { /// /// See Control.ProcessDialogKey for more info. /// - protected internal virtual bool ProcessDialogKey(Keys keyData) { + protected internal virtual bool ProcessDialogKey(Keys keyData) + { // - if (keyData == Keys.Enter || (state[stateSupportsSpaceKey] && keyData == Keys.Space)) { + if (keyData == Keys.Enter || (state[stateSupportsSpaceKey] && keyData == Keys.Space)) + { FireEvent(ToolStripItemEventType.Click); - if (ParentInternal != null && !ParentInternal.IsDropDown && Enabled) { + if (ParentInternal != null && !ParentInternal.IsDropDown && Enabled) + { ParentInternal.RestoreFocusInternal(); } return true; @@ -3077,91 +3612,119 @@ protected internal virtual bool ProcessDialogKey(Keys keyData) { /// /// See Control.ProcessCmdKey for more info. /// - protected internal virtual bool ProcessCmdKey(ref Message m, Keys keyData) { + protected internal virtual bool ProcessCmdKey(ref Message m, Keys keyData) + { return false; } - + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] // 'charCode' matches control.cs - protected internal virtual bool ProcessMnemonic(char charCode) { + protected internal virtual bool ProcessMnemonic(char charCode) + { // checking IsMnemonic is not necessary - control does this for us. FireEvent(ToolStripItemEventType.Click); return true; } - - internal void RaiseCancelEvent(object key, CancelEventArgs e) { - CancelEventHandler handler = (CancelEventHandler)Events[key]; - if (handler != null) handler(this, e); + + internal void RaiseCancelEvent(object key, CancelEventArgs e) + { + CancelEventHandler handler = (CancelEventHandler)Events[key]; + if (handler != null) + handler(this, e); } - internal void RaiseDragEvent(object key, DragEventArgs e) { - DragEventHandler handler = (DragEventHandler)Events[key]; - if (handler != null) handler(this, e); + internal void RaiseDragEvent(object key, DragEventArgs e) + { + DragEventHandler handler = (DragEventHandler)Events[key]; + if (handler != null) + handler(this, e); } - internal void RaiseEvent(object key, EventArgs e) { + internal void RaiseEvent(object key, EventArgs e) + { EventHandler handler = (EventHandler)Events[key]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } - internal void RaiseKeyEvent(object key, KeyEventArgs e) { + internal void RaiseKeyEvent(object key, KeyEventArgs e) + { KeyEventHandler handler = (KeyEventHandler)Events[key]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } - internal void RaiseKeyPressEvent(object key, KeyPressEventArgs e) { + internal void RaiseKeyPressEvent(object key, KeyPressEventArgs e) + { KeyPressEventHandler handler = (KeyPressEventHandler)Events[key]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } - internal void RaiseMouseEvent(object key, MouseEventArgs e) { + internal void RaiseMouseEvent(object key, MouseEventArgs e) + { MouseEventHandler handler = (MouseEventHandler)Events[key]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } - internal void RaisePaintEvent(object key, PaintEventArgs e) { + internal void RaisePaintEvent(object key, PaintEventArgs e) + { PaintEventHandler handler = (PaintEventHandler)Events[key]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } - - internal void RaiseQueryContinueDragEvent(object key, QueryContinueDragEventArgs e) { + + internal void RaiseQueryContinueDragEvent(object key, QueryContinueDragEventArgs e) + { QueryContinueDragEventHandler handler = (QueryContinueDragEventHandler)Events[key]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } - private void ResetToolTipText() { + private void ResetToolTipText() + { toolTipText = null; } - - + + /// /// Selects the item /// - public void Select() { - + public void Select() + { + #if DEBUG - // let's not snap the stack trace unless we're debugging selection. - if (ToolStrip.SelectionDebug.TraceVerbose) { - Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "[Selection DBG] WBI.Select: {0} \r\n{1}\r\n", this.ToString(), new StackTrace().ToString().Substring(0,200))); - } + // let's not snap the stack trace unless we're debugging selection. + if (ToolStrip.SelectionDebug.TraceVerbose) + { + Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "[Selection DBG] WBI.Select: {0} \r\n{1}\r\n", this.ToString(), new StackTrace().ToString().Substring(0, 200))); + } #endif - if (!CanSelect) { + if (!CanSelect) + { return; } - if (Owner != null && Owner.IsCurrentlyDragging) { + if (Owner != null && Owner.IsCurrentlyDragging) + { // make sure we dont select during a drag operation. return; } - if (ParentInternal != null && ParentInternal.IsSelectionSuspended) { + if (ParentInternal != null && ParentInternal.IsSelectionSuspended) + { Debug.WriteLineIf(ToolStrip.SelectionDebug.TraceVerbose, "[Selection DBG] BAILING, selection is currently suspended"); return; } - - if (!Selected) { + + if (!Selected) + { state[stateSelected] = true; - if (ParentInternal != null) { + if (ParentInternal != null) + { ParentInternal.NotifySelectionChange(this); Debug.Assert(state[stateSelected], "calling notify selection change changed the selection state of this item"); } - if (IsOnDropDown) { - if (OwnerItem != null && OwnerItem.IsOnDropDown) { + if (IsOnDropDown) + { + if (OwnerItem != null && OwnerItem.IsOnDropDown) + { // ensure the selection is moved back to our owner item. OwnerItem.Select(); } @@ -3169,94 +3732,111 @@ public void Select() { KeyboardToolTipStateMachine.Instance.NotifyAboutGotFocus(this); - if (AccessibilityObject is ToolStripItemAccessibleObject) { + if (AccessibilityObject is ToolStripItemAccessibleObject) + { ((ToolStripItemAccessibleObject)AccessibilityObject).RaiseFocusChanged(); } #if SELECTEDCHANGED OnSelectedChanged(EventArgs.Empty); #endif - } + } } - internal void SetOwner(ToolStrip newOwner) { - if (owner != newOwner) { - Font f = this.Font; - owner = newOwner; + internal void SetOwner(ToolStrip newOwner) + { + if (owner != newOwner) + { + Font f = this.Font; + owner = newOwner; - // clear the parent if the owner is null... - // - if (newOwner == null) { - this.ParentInternal = null; - } - if (!state[stateDisposing] && !IsDisposed) { - OnOwnerChanged(EventArgs.Empty); - if (f != Font) { - OnFontChanged(EventArgs.Empty); - } - } - } + // clear the parent if the owner is null... + // + if (newOwner == null) + { + this.ParentInternal = null; + } + if (!state[stateDisposing] && !IsDisposed) + { + OnOwnerChanged(EventArgs.Empty); + if (f != Font) + { + OnFontChanged(EventArgs.Empty); + } + } + } } - protected virtual void SetVisibleCore(bool visible) { - if (state[stateVisible] != visible) { - state[stateVisible]= visible; + protected virtual void SetVisibleCore(bool visible) + { + if (state[stateVisible] != visible) + { + state[stateVisible] = visible; Unselect(); Push(false); - OnAvailableChanged(EventArgs.Empty); + OnAvailableChanged(EventArgs.Empty); OnVisibleChanged(EventArgs.Empty); } } - + /// /// Sets the bounds of the item /// - internal protected virtual void SetBounds(Rectangle bounds) { + internal protected virtual void SetBounds(Rectangle bounds) + { Rectangle oldBounds = this.bounds; this.bounds = bounds; - if (! state[stateContstructing]) { + if (!state[stateContstructing]) + { // Dont fire while we're in the base constructor as the inherited // class may not have had a chance to initialize yet. - if (this.bounds != oldBounds) { + if (this.bounds != oldBounds) + { OnBoundsChanged(); } - - if (this.bounds.Location != oldBounds.Location) { + + if (this.bounds.Location != oldBounds.Location) + { OnLocationChanged(EventArgs.Empty); } } } - + /// /// Sets the bounds of the item /// - internal void SetBounds(int x, int y, int width, int height) { - SetBounds(new Rectangle(x,y,width,height)); + internal void SetBounds(int x, int y, int width, int height) + { + SetBounds(new Rectangle(x, y, width, height)); } /// /// Sets the placement of the item /// - internal void SetPlacement(ToolStripItemPlacement placement) { + internal void SetPlacement(ToolStripItemPlacement placement) + { this.placement = placement; - } + } // Some implementations of DefaultMargin check which container they // are on. They need to be re-evaluated when the containership changes. // DefaultMargin will stop being honored the moment someone sets the Margin property. - internal void SetAmbientMargin() { - if (state[stateUseAmbientMargin] && Margin != DefaultMargin) { - CommonProperties.SetMargin(this, DefaultMargin); - } + internal void SetAmbientMargin() + { + if (state[stateUseAmbientMargin] && Margin != DefaultMargin) + { + CommonProperties.SetMargin(this, DefaultMargin); + } } [EditorBrowsable(EditorBrowsableState.Never)] - private bool ShouldSerializeImageTransparentColor() { + private bool ShouldSerializeImageTransparentColor() + { return ImageTransparentColor != Color.Empty; } @@ -3264,23 +3844,27 @@ private bool ShouldSerializeImageTransparentColor() { /// Returns true if the backColor should be persisted in code gen. /// [EditorBrowsable(EditorBrowsableState.Never)] - internal virtual bool ShouldSerializeBackColor() { + internal virtual bool ShouldSerializeBackColor() + { Color backColor = Properties.GetColor(PropBackColor); return !backColor.IsEmpty; } - private bool ShouldSerializeDisplayStyle() { + private bool ShouldSerializeDisplayStyle() + { return DisplayStyle != DefaultDisplayStyle; } - - private bool ShouldSerializeToolTipText() { + + private bool ShouldSerializeToolTipText() + { return !string.IsNullOrEmpty(toolTipText); } /// /// Returns true if the foreColor should be persisted in code gen. /// [EditorBrowsable(EditorBrowsableState.Never)] - internal virtual bool ShouldSerializeForeColor() { + internal virtual bool ShouldSerializeForeColor() + { Color foreColor = Properties.GetColor(PropForeColor); return !foreColor.IsEmpty; } @@ -3289,94 +3873,108 @@ internal virtual bool ShouldSerializeForeColor() { /// Returns true if the font should be persisted in code gen. /// [EditorBrowsable(EditorBrowsableState.Never)] - internal virtual bool ShouldSerializeFont() { + internal virtual bool ShouldSerializeFont() + { bool found; object font = Properties.GetObject(PropFont, out found); return (found && font != null); } - + /// /// Determines if the property needs to be persisted. /// [EditorBrowsable(EditorBrowsableState.Never)] - private bool ShouldSerializePadding() { - return (Padding != DefaultPadding); - } + private bool ShouldSerializePadding() + { + return (Padding != DefaultPadding); + } /// /// Determines if the property needs to be persisted. /// [EditorBrowsable(EditorBrowsableState.Never)] - private bool ShouldSerializeMargin() { - return (Margin != DefaultMargin); - } + private bool ShouldSerializeMargin() + { + return (Margin != DefaultMargin); + } /// /// Determines if the property needs to be persisted. /// [EditorBrowsable(EditorBrowsableState.Never)] - private bool ShouldSerializeVisible() { - return !state[stateVisible]; // only serialize if someone turned off visiblilty + private bool ShouldSerializeVisible() + { + return !state[stateVisible]; // only serialize if someone turned off visiblilty } /// /// Determines if the property needs to be persisted. /// [EditorBrowsable(EditorBrowsableState.Never)] - private bool ShouldSerializeImage() { - return (Image != null) && (ImageIndexer.ActualIndex < 0); - } + private bool ShouldSerializeImage() + { + return (Image != null) && (ImageIndexer.ActualIndex < 0); + } /// /// Determines if the property needs to be persisted. /// [EditorBrowsable(EditorBrowsableState.Never)] - private bool ShouldSerializeImageKey() { - return (Image != null) && (ImageIndexer.ActualIndex >= 0) && (ImageIndexer.Key != null && ImageIndexer.Key.Length != 0); + private bool ShouldSerializeImageKey() + { + return (Image != null) && (ImageIndexer.ActualIndex >= 0) && (ImageIndexer.Key != null && ImageIndexer.Key.Length != 0); } /// /// Determines if the property needs to be persisted. /// [EditorBrowsable(EditorBrowsableState.Never)] - private bool ShouldSerializeImageIndex() { - return (Image != null) && (ImageIndexer.ActualIndex >= 0) && (ImageIndexer.Index != -1); + private bool ShouldSerializeImageIndex() + { + return (Image != null) && (ImageIndexer.ActualIndex >= 0) && (ImageIndexer.Index != -1); } /// /// Determines if the property needs to be persisted. /// [EditorBrowsable(EditorBrowsableState.Never)] - internal virtual bool ShouldSerializeRightToLeft() { + internal virtual bool ShouldSerializeRightToLeft() + { bool found = false; int rightToLeft = Properties.GetInteger(PropRightToLeft, out found); - if (!found) { + if (!found) + { return false; } return (rightToLeft != (int)DefaultRightToLeft); } - private bool ShouldSerializeTextDirection() { + private bool ShouldSerializeTextDirection() + { ToolStripTextDirection textDirection = ToolStripTextDirection.Inherit; - if (Properties.ContainsObject(ToolStripItem.PropTextDirection)) { - textDirection= (ToolStripTextDirection)Properties.GetObject(ToolStripItem.PropTextDirection); + if (Properties.ContainsObject(ToolStripItem.PropTextDirection)) + { + textDirection = (ToolStripTextDirection)Properties.GetObject(ToolStripItem.PropTextDirection); } return textDirection != ToolStripTextDirection.Inherit; } - + /// /// Resets the back color to be based on the parent's back color. /// [EditorBrowsable(EditorBrowsableState.Never)] - public virtual void ResetBackColor() { + public virtual void ResetBackColor() + { BackColor = Color.Empty; } - + [EditorBrowsable(EditorBrowsableState.Never)] - public virtual void ResetDisplayStyle() { + public virtual void ResetDisplayStyle() + { DisplayStyle = DefaultDisplayStyle; } - + /// /// Resets the fore color to be based on the parent's fore color. /// [EditorBrowsable(EditorBrowsableState.Never)] - public virtual void ResetForeColor() { + public virtual void ResetForeColor() + { ForeColor = Color.Empty; } @@ -3385,7 +3983,8 @@ public virtual void ResetForeColor() { /// Resets the Font to be based on the parent's Font. /// [EditorBrowsable(EditorBrowsableState.Never)] - public virtual void ResetFont() { + public virtual void ResetFont() + { Font = null; } @@ -3393,31 +3992,36 @@ public virtual void ResetFont() { /// Resets the back color to be based on the parent's back color. /// [EditorBrowsable(EditorBrowsableState.Never)] - public virtual void ResetImage() { + public virtual void ResetImage() + { Image = null; } [EditorBrowsable(EditorBrowsableState.Never)] - private void ResetImageTransparentColor() { + private void ResetImageTransparentColor() + { ImageTransparentColor = Color.Empty; } [EditorBrowsable(EditorBrowsableState.Never)] - public void ResetMargin() { + public void ResetMargin() + { state[stateUseAmbientMargin] = true; SetAmbientMargin(); } [EditorBrowsable(EditorBrowsableState.Never)] - public void ResetPadding() { + public void ResetPadding() + { CommonProperties.ResetPadding(this); } /// /// Resets the RightToLeft to be the default. /// [EditorBrowsable(EditorBrowsableState.Never)] - public virtual void ResetRightToLeft() { + public virtual void ResetRightToLeft() + { RightToLeft = RightToLeft.Inherit; } @@ -3425,26 +4029,31 @@ public virtual void ResetRightToLeft() { /// Resets the TextDirection to be the default. /// [EditorBrowsable(EditorBrowsableState.Never)] - public virtual void ResetTextDirection() { - TextDirection = ToolStripTextDirection.Inherit; + public virtual void ResetTextDirection() + { + TextDirection = ToolStripTextDirection.Inherit; } /// /// Translates a point from one coordinate system to another /// - internal Point TranslatePoint(Point fromPoint, ToolStripPointType fromPointType, ToolStripPointType toPointType) { + internal Point TranslatePoint(Point fromPoint, ToolStripPointType fromPointType, ToolStripPointType toPointType) + { ToolStrip parent = ParentInternal; - - if (parent == null) { - parent = (IsOnOverflow && Owner != null)? Owner.OverflowButton.DropDown : Owner; + + if (parent == null) + { + parent = (IsOnOverflow && Owner != null) ? Owner.OverflowButton.DropDown : Owner; } - if (parent == null) { + if (parent == null) + { // should not throw here as it's an internal function call. Debug.Fail("could not determine current parent"); return fromPoint; } - if (fromPointType == toPointType) { + if (fromPointType == toPointType) + { return fromPoint; } @@ -3453,21 +4062,25 @@ internal Point TranslatePoint(Point fromPoint, ToolStripPointType fromPointType, // From: Screen // To: ToolStrip or ToolStripItem - if (fromPointType == ToolStripPointType.ScreenCoords) { + if (fromPointType == ToolStripPointType.ScreenCoords) + { // Convert ScreenCoords --> ToolStripCoords toPoint = parent.PointToClient(fromPoint); // Convert ToolStripCoords --> ToolStripItemCoords - if (toPointType == ToolStripPointType.ToolStripItemCoords) { + if (toPointType == ToolStripPointType.ToolStripItemCoords) + { toPoint.X += currentToolStripItemLocation.X; toPoint.Y += currentToolStripItemLocation.Y; } } - // From: ToolStrip or ToolStripItem - // To: Screen or ToolStripItem - else { + // From: ToolStrip or ToolStripItem + // To: Screen or ToolStripItem + else + { // Convert "fromPoint" ToolStripItemCoords --> ToolStripCoords - if (fromPointType == ToolStripPointType.ToolStripItemCoords) { + if (fromPointType == ToolStripPointType.ToolStripItemCoords) + { fromPoint.X += currentToolStripItemLocation.X; fromPoint.Y += currentToolStripItemLocation.Y; } @@ -3475,29 +4088,35 @@ internal Point TranslatePoint(Point fromPoint, ToolStripPointType fromPointType, // At this point, fromPoint is now in ToolStrip coordinates. // Convert ToolStripCoords --> ScreenCoords - if (toPointType == ToolStripPointType.ScreenCoords) { + if (toPointType == ToolStripPointType.ScreenCoords) + { toPoint = parent.PointToScreen(fromPoint); } - // Convert ToolStripCoords --> ToolStripItemCoords - else if (toPointType == ToolStripPointType.ToolStripItemCoords) { + // Convert ToolStripCoords --> ToolStripItemCoords + else if (toPointType == ToolStripPointType.ToolStripItemCoords) + { fromPoint.X -= currentToolStripItemLocation.X; fromPoint.Y -= currentToolStripItemLocation.Y; toPoint = fromPoint; - } - else { + } + else + { Debug.Assert((toPointType == ToolStripPointType.ToolStripCoords), "why are we here! - investigate"); toPoint = fromPoint; } - + } return toPoint; - + } - internal ToolStrip RootToolStrip { - get { + internal ToolStrip RootToolStrip + { + get + { ToolStripItem item = this; - while (item.OwnerItem != null) { + while (item.OwnerItem != null) + { item = item.OwnerItem; } return item.ParentInternal; @@ -3507,8 +4126,10 @@ internal ToolStrip RootToolStrip { /// /// ToString support /// - public override string ToString() { - if (Text != null && this.Text.Length != 0) { + public override string ToString() + { + if (Text != null && this.Text.Length != 0) + { return this.Text; } return base.ToString(); @@ -3517,13 +4138,17 @@ public override string ToString() { /// /// removes selection bits from item state /// - internal void Unselect() { + internal void Unselect() + { Debug.WriteLineIf(ToolStrip.SelectionDebug.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "[Selection DBG] WBI.Unselect: {0}", this.ToString())); - if (state[stateSelected]) { - state[stateSelected] = false; - if (Available) { + if (state[stateSelected]) + { + state[stateSelected] = false; + if (Available) + { Invalidate(); - if (ParentInternal != null) { + if (ParentInternal != null) + { ParentInternal.NotifySelectionChange(this); } @@ -3537,34 +4162,43 @@ internal void Unselect() { #region IKeyboardToolTip implementation - bool IKeyboardToolTip.CanShowToolTipsNow() { + bool IKeyboardToolTip.CanShowToolTipsNow() + { return this.Visible && this.parent != null && ((IKeyboardToolTip)this.parent).AllowsChildrenToShowToolTips(); } - Rectangle IKeyboardToolTip.GetNativeScreenRectangle() { + Rectangle IKeyboardToolTip.GetNativeScreenRectangle() + { return this.AccessibilityObject.Bounds; } - IList IKeyboardToolTip.GetNeighboringToolsRectangles() { + IList IKeyboardToolTip.GetNeighboringToolsRectangles() + { List neighbors = new List(3); - if (this.parent != null) { + if (this.parent != null) + { ToolStripItemCollection items = this.parent.DisplayedItems; int i = 0, count = items.Count; bool found = false; - while (!found && i < count) { + while (!found && i < count) + { found = Object.ReferenceEquals(items[i], this); - if (found) { + if (found) + { int previousIndex = i - 1; - if (previousIndex >= 0) { + if (previousIndex >= 0) + { neighbors.Add(((IKeyboardToolTip)items[previousIndex]).GetNativeScreenRectangle()); } int nextIndex = i + 1; - if (nextIndex < count) { + if (nextIndex < count) + { neighbors.Add(((IKeyboardToolTip)items[nextIndex]).GetNativeScreenRectangle()); } } - else { + else + { i++; } } @@ -3572,145 +4206,180 @@ IList IKeyboardToolTip.GetNeighboringToolsRectangles() { } ToolStripDropDown dropDown = this.parent as ToolStripDropDown; - if (dropDown != null && dropDown.OwnerItem != null) { + if (dropDown != null && dropDown.OwnerItem != null) + { neighbors.Add(((IKeyboardToolTip)dropDown.OwnerItem).GetNativeScreenRectangle()); } return neighbors; } - bool IKeyboardToolTip.IsHoveredWithMouse() { + bool IKeyboardToolTip.IsHoveredWithMouse() + { return ((IKeyboardToolTip)this).GetNativeScreenRectangle().Contains(Control.MousePosition); } - bool IKeyboardToolTip.HasRtlModeEnabled() { + bool IKeyboardToolTip.HasRtlModeEnabled() + { return this.parent != null && ((IKeyboardToolTip)this.parent).HasRtlModeEnabled(); } - bool IKeyboardToolTip.AllowsToolTip() { + bool IKeyboardToolTip.AllowsToolTip() + { return true; } - IWin32Window IKeyboardToolTip.GetOwnerWindow() { + IWin32Window IKeyboardToolTip.GetOwnerWindow() + { Debug.Assert(this.ParentInternal != null, "Tool Strip Item Parent is null"); return this.ParentInternal; } - void IKeyboardToolTip.OnHooked(ToolTip toolTip) { + void IKeyboardToolTip.OnHooked(ToolTip toolTip) + { this.OnKeyboardToolTipHook(toolTip); } - void IKeyboardToolTip.OnUnhooked(ToolTip toolTip) { + void IKeyboardToolTip.OnUnhooked(ToolTip toolTip) + { this.OnKeyboardToolTipUnhook(toolTip); } - string IKeyboardToolTip.GetCaptionForTool(ToolTip toolTip) { + string IKeyboardToolTip.GetCaptionForTool(ToolTip toolTip) + { return this.ToolTipText; } - bool IKeyboardToolTip.ShowsOwnToolTip() { + bool IKeyboardToolTip.ShowsOwnToolTip() + { return true; } - bool IKeyboardToolTip.IsBeingTabbedTo() { + bool IKeyboardToolTip.IsBeingTabbedTo() + { return this.IsBeingTabbedTo(); } - bool IKeyboardToolTip.AllowsChildrenToShowToolTips() { + bool IKeyboardToolTip.AllowsChildrenToShowToolTips() + { return true; } #endregion - internal virtual void OnKeyboardToolTipHook(ToolTip toolTip) { + internal virtual void OnKeyboardToolTipHook(ToolTip toolTip) + { } - internal virtual void OnKeyboardToolTipUnhook(ToolTip toolTip) { + internal virtual void OnKeyboardToolTipUnhook(ToolTip toolTip) + { } - internal virtual bool IsBeingTabbedTo() { + internal virtual bool IsBeingTabbedTo() + { return ToolStrip.AreCommonNavigationalKeysDown(); } /// /// An implementation of AccessibleChild for use with ToolStripItems /// - [System.Runtime.InteropServices.ComVisible(true)] - public class ToolStripItemAccessibleObject : AccessibleObject { + [System.Runtime.InteropServices.ComVisible(true)] + public class ToolStripItemAccessibleObject : AccessibleObject + { // Member variables private ToolStripItem ownerItem = null; // The associated ToolStripItem for this AccessibleChild (if any) - - private AccessibleStates additionalState = AccessibleStates.None; // Test hook for the designer + + private AccessibleStates additionalState = AccessibleStates.None; // Test hook for the designer private int[] runtimeId = null; // Used by UIAutomation // constructors - public ToolStripItemAccessibleObject(ToolStripItem ownerItem) { - if (ownerItem == null) { + public ToolStripItemAccessibleObject(ToolStripItem ownerItem) + { + if (ownerItem == null) + { throw new ArgumentNullException(nameof(ownerItem)); } this.ownerItem = ownerItem; } - - public override string DefaultAction { - get { + + public override string DefaultAction + { + get + { string defaultAction = ownerItem.AccessibleDefaultActionDescription; - if (defaultAction != null) { + if (defaultAction != null) + { return defaultAction; } - else { + else + { return SR.AccessibleActionPress; } } } - public override string Description { - get { + public override string Description + { + get + { string description = ownerItem.AccessibleDescription; - if (description != null) { + if (description != null) + { return description; } - else { + else + { return base.Description; } } } - public override string Help { - get { + public override string Help + { + get + { QueryAccessibilityHelpEventHandler handler = (QueryAccessibilityHelpEventHandler)Owner.Events[ToolStripItem.EventQueryAccessibilityHelp]; - if (handler != null) { + if (handler != null) + { QueryAccessibilityHelpEventArgs args = new QueryAccessibilityHelpEventArgs(); handler(Owner, args); return args.HelpString; } - else { + else + { return base.Help; } } - } + } - public override string KeyboardShortcut { - get { + public override string KeyboardShortcut + { + get + { // This really is the Mnemonic - NOT the shortcut. E.g. in notepad Edit->Replace is Control+H // but the KeyboardShortcut comes up as the mnemonic 'r'. char mnemonic = WindowsFormsUtils.GetMnemonic(ownerItem.Text, false); - if (ownerItem.IsOnDropDown) { + if (ownerItem.IsOnDropDown) + { // no ALT on dropdown - return (mnemonic == (char) 0) ? string.Empty : mnemonic.ToString(); + return (mnemonic == (char)0) ? string.Empty : mnemonic.ToString(); } - return (mnemonic == (char) 0) ? string.Empty : ("Alt+" + mnemonic); - + return (mnemonic == (char)0) ? string.Empty : ("Alt+" + mnemonic); + } } - - internal override int[] RuntimeId { - get { - if (runtimeId == null) { + + internal override int[] RuntimeId + { + get + { + if (runtimeId == null) + { // we need to provide a unique ID // others are implementing this in the same manner // first item should be UiaAppendRuntimeId since this is not a top-level element of the fragment. @@ -3730,8 +4399,10 @@ internal override int[] RuntimeId { /// /// The accessible property ID. /// The accessible property value. - internal override object GetPropertyValue(int propertyID) { - switch (propertyID) { + internal override object GetPropertyValue(int propertyID) + { + switch (propertyID) + { case NativeMethods.UIA_NamePropertyId: return Name; case NativeMethods.UIA_IsExpandCollapsePatternAvailablePropertyId: @@ -3755,123 +4426,153 @@ internal override object GetPropertyValue(int propertyID) { return base.GetPropertyValue(propertyID); } - public override string Name { - get { + public override string Name + { + get + { string name = ownerItem.AccessibleName; - if (name != null) { + if (name != null) + { return name; } - + string baseName = base.Name; - - if (baseName == null || baseName.Length == 0) { + + if (baseName == null || baseName.Length == 0) + { return WindowsFormsUtils.TextWithoutMnemonics(ownerItem.Text); } - + return baseName; } - set { + set + { ownerItem.AccessibleName = value; } } - internal ToolStripItem Owner { - get { + internal ToolStripItem Owner + { + get + { return ownerItem; } } - - public override AccessibleRole Role { - get { + + public override AccessibleRole Role + { + get + { AccessibleRole role = ownerItem.AccessibleRole; - if (role != AccessibleRole.Default) { + if (role != AccessibleRole.Default) + { return role; } - else { + else + { return AccessibleRole.PushButton; } } } - public override AccessibleStates State { - get { - if (!ownerItem.CanSelect) { + public override AccessibleStates State + { + get + { + if (!ownerItem.CanSelect) + { return base.State | additionalState; } - - - if (!ownerItem.Enabled) { - if (ownerItem.Selected && ownerItem is ToolStripMenuItem) { + + + if (!ownerItem.Enabled) + { + if (ownerItem.Selected && ownerItem is ToolStripMenuItem) + { return AccessibleStates.Unavailable | additionalState | AccessibleStates.Focused; } // Disabled menu items that are selected must have focus // state so that Narrator can announce them. - if (ownerItem.Selected && ownerItem is ToolStripMenuItem) { + if (ownerItem.Selected && ownerItem is ToolStripMenuItem) + { return AccessibleStates.Focused; } return AccessibleStates.Unavailable | additionalState; } - + AccessibleStates accState = AccessibleStates.Focusable | additionalState; - + // /*if (HasDropDownItems) { accState |= AccessibleState.HasPopup; }*/ - if (ownerItem.Selected || ownerItem.Pressed) { + if (ownerItem.Selected || ownerItem.Pressed) + { accState |= AccessibleStates.Focused | AccessibleStates.HotTracked; } - if (ownerItem.Pressed) { + if (ownerItem.Pressed) + { accState |= AccessibleStates.Pressed; } - return accState; + return accState; } } - public override void DoDefaultAction() { - if (Owner != null) { + public override void DoDefaultAction() + { + if (Owner != null) + { ((ToolStripItem)Owner).PerformClick(); } } - public override int GetHelpTopic(out string fileName) { + public override int GetHelpTopic(out string fileName) + { int topic = 0; - QueryAccessibilityHelpEventHandler handler = (QueryAccessibilityHelpEventHandler)Owner.Events[ToolStripItem.EventQueryAccessibilityHelp]; + QueryAccessibilityHelpEventHandler handler = (QueryAccessibilityHelpEventHandler)Owner.Events[ToolStripItem.EventQueryAccessibilityHelp]; - if (handler != null) { + if (handler != null) + { QueryAccessibilityHelpEventArgs args = new QueryAccessibilityHelpEventArgs(); handler(Owner, args); - fileName = args.HelpNamespace; + fileName = args.HelpNamespace; - try { + try + { topic = int.Parse(args.HelpKeyword, CultureInfo.InvariantCulture); } - catch { + catch + { } return topic; } - else { + else + { return base.GetHelpTopic(out fileName); } } - public override AccessibleObject Navigate(AccessibleNavigation navigationDirection) { + public override AccessibleObject Navigate(AccessibleNavigation navigationDirection) + { ToolStripItem nextItem = null; - if (Owner != null) { - ToolStrip parent = Owner.ParentInternal; - if (parent == null) { + if (Owner != null) + { + ToolStrip parent = Owner.ParentInternal; + if (parent == null) + { return null; } - + bool forwardInCollection = (parent.RightToLeft == RightToLeft.No); - switch(navigationDirection) { + switch (navigationDirection) + { case AccessibleNavigation.FirstChild: nextItem = parent.GetNextItem(null, ArrowDirection.Right, /*RTLAware=*/true); break; @@ -3885,54 +4586,64 @@ public override AccessibleObject Navigate(AccessibleNavigation navigationDirecti case AccessibleNavigation.Next: case AccessibleNavigation.Right: nextItem = parent.GetNextItem(Owner, ArrowDirection.Right, /*RTLAware=*/true); - break; + break; case AccessibleNavigation.Up: - nextItem = (Owner.IsOnDropDown) ? parent.GetNextItem(Owner, ArrowDirection.Up): + nextItem = (Owner.IsOnDropDown) ? parent.GetNextItem(Owner, ArrowDirection.Up) : parent.GetNextItem(Owner, ArrowDirection.Left, /*RTLAware=*/true); - break; + break; case AccessibleNavigation.Down: - nextItem = (Owner.IsOnDropDown) ? parent.GetNextItem(Owner, ArrowDirection.Down): + nextItem = (Owner.IsOnDropDown) ? parent.GetNextItem(Owner, ArrowDirection.Down) : parent.GetNextItem(Owner, ArrowDirection.Right, /*RTLAware=*/true); - break; - + break; + } } - if (nextItem != null) { + if (nextItem != null) + { return nextItem.AccessibilityObject; } - return null; + return null; } // - public void AddState(AccessibleStates state) { - if (state == AccessibleStates.None) { + public void AddState(AccessibleStates state) + { + if (state == AccessibleStates.None) + { additionalState = state; } - else { + else + { additionalState |= state; } } - - public override string ToString() { - if (Owner != null) { - return "ToolStripItemAccessibleObject: Owner = " + Owner.ToString(); + + public override string ToString() + { + if (Owner != null) + { + return "ToolStripItemAccessibleObject: Owner = " + Owner.ToString(); } - else { + else + { return "ToolStripItemAccessibleObject: Owner = null"; } - + } - + /// /// Gets the bounds of the accessible object, in screen coordinates. /// - public override Rectangle Bounds { - get { + public override Rectangle Bounds + { + get + { Rectangle bounds = Owner.Bounds; if (Owner.ParentInternal != null && - Owner.ParentInternal.Visible) { + Owner.ParentInternal.Visible) + { return new Rectangle(Owner.ParentInternal.PointToScreen(bounds.Location), bounds.Size); } return Rectangle.Empty; @@ -3942,17 +4653,21 @@ public override Rectangle Bounds { /// /// When overridden in a derived class, gets or sets the parent of an accessible object. /// - public override AccessibleObject Parent { - get { - if (Owner.IsOnDropDown) { + public override AccessibleObject Parent + { + get + { + if (Owner.IsOnDropDown) + { // Return the owner item as the accessible parent. ToolStripDropDown dropDown = Owner.GetCurrentParentDropDown(); - if (dropDown.OwnerItem != null) { + if (dropDown.OwnerItem != null) + { return dropDown.OwnerItem.AccessibilityObject; } - return dropDown.AccessibilityObject; + return dropDown.AccessibilityObject; } - return (Owner.Parent != null) ? Owner.Parent.AccessibilityObject : base.Parent; + return (Owner.Parent != null) ? Owner.Parent.AccessibilityObject : base.Parent; } @@ -3961,8 +4676,10 @@ public override AccessibleObject Parent { /// /// Gets the top level element. /// - internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot { - get { + internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot + { + get + { return ownerItem.RootToolStrip?.AccessibilityObject; } } @@ -3972,14 +4689,17 @@ internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRo /// /// Indicates the direction in which to navigate. /// Returns the element in the specified direction. - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - switch (direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { + switch (direction) + { case UnsafeNativeMethods.NavigateDirection.Parent: return Parent; case UnsafeNativeMethods.NavigateDirection.NextSibling: case UnsafeNativeMethods.NavigateDirection.PreviousSibling: int index = GetChildFragmentIndex(); - if (index == -1) { + if (index == -1) + { Debug.Fail("No item matched the index?"); return null; } @@ -3989,7 +4709,8 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga index += increment; int itemsCount = GetChildFragmentCount(); - if (index >= 0 && index < itemsCount) { + if (index >= 0 && index < itemsCount) + { sibling = GetChildFragment(index); } @@ -3999,9 +4720,11 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga return base.FragmentNavigate(direction); } - private AccessibleObject GetChildFragment(int index) { + private AccessibleObject GetChildFragment(int index) + { var toolStripParent = Parent as ToolStrip.ToolStripAccessibleObject; - if (toolStripParent != null) { + if (toolStripParent != null) + { return toolStripParent.GetChildFragment(index); } @@ -4009,72 +4732,88 @@ private AccessibleObject GetChildFragment(int index) { // and we should not process ToolStripOverflowButton as a ToolStripDropDownItem here so check for // the ToolStripOverflowButton firstly as more specific condition. var toolStripOverflowButtonParent = Parent as ToolStripOverflowButton.ToolStripOverflowButtonAccessibleObject; - if (toolStripOverflowButtonParent != null) { + if (toolStripOverflowButtonParent != null) + { var toolStripGrandParent = toolStripOverflowButtonParent.Parent as ToolStrip.ToolStripAccessibleObject; - if (toolStripGrandParent != null) { + if (toolStripGrandParent != null) + { return toolStripGrandParent.GetChildFragment(index, true); } } var dropDownItemParent = Parent as ToolStripDropDownItemAccessibleObject; - if (dropDownItemParent != null) { + if (dropDownItemParent != null) + { return dropDownItemParent.GetChildFragment(index); } return null; } - private int GetChildFragmentCount() { + private int GetChildFragmentCount() + { var toolStripParent = Parent as ToolStrip.ToolStripAccessibleObject; - if (toolStripParent != null) { + if (toolStripParent != null) + { return toolStripParent.GetChildFragmentCount(); } var toolStripOverflowButtonParent = Parent as ToolStripOverflowButton.ToolStripOverflowButtonAccessibleObject; - if (toolStripOverflowButtonParent != null) { + if (toolStripOverflowButtonParent != null) + { var toolStripGrandParent = toolStripOverflowButtonParent.Parent as ToolStrip.ToolStripAccessibleObject; - if (toolStripGrandParent != null) { + if (toolStripGrandParent != null) + { return toolStripGrandParent.GetChildOverflowFragmentCount(); } } var dropDownItemParent = Parent as ToolStripDropDownItemAccessibleObject; - if (dropDownItemParent != null) { + if (dropDownItemParent != null) + { return dropDownItemParent.GetChildCount(); } return -1; } - private int GetChildFragmentIndex() { + private int GetChildFragmentIndex() + { var toolStripParent = Parent as ToolStrip.ToolStripAccessibleObject; - if (toolStripParent != null) { + if (toolStripParent != null) + { return toolStripParent.GetChildFragmentIndex(this); } var toolStripOverflowButtonParent = Parent as ToolStripOverflowButton.ToolStripOverflowButtonAccessibleObject; - if (toolStripOverflowButtonParent != null) { + if (toolStripOverflowButtonParent != null) + { var toolStripGrandParent = toolStripOverflowButtonParent.Parent as ToolStrip.ToolStripAccessibleObject; - if (toolStripGrandParent != null) { + if (toolStripGrandParent != null) + { return toolStripGrandParent.GetChildFragmentIndex(this); } } var dropDownItemParent = Parent as ToolStripDropDownItemAccessibleObject; - if (dropDownItemParent != null) { + if (dropDownItemParent != null) + { return dropDownItemParent.GetChildFragmentIndex(this); } return -1; } - internal override void SetFocus() { + internal override void SetFocus() + { Owner.Select(); } - internal void RaiseFocusChanged() { + internal void RaiseFocusChanged() + { ToolStrip root = ownerItem.RootToolStrip; - if (root != null && root.SupportsUiaProviders) { + if (root != null && root.SupportsUiaProviders) + { RaiseAutomationEvent(NativeMethods.UIA_AutomationFocusChangedEventId); } } @@ -4084,105 +4823,129 @@ internal void RaiseFocusChanged() { // We need a special way to defer to the ToolStripItem's image // list for indexing purposes. - internal class ToolStripItemImageIndexer : ImageList.Indexer { - private ToolStripItem item; - - public ToolStripItemImageIndexer(ToolStripItem item) { - this.item = item; - } - - public override ImageList ImageList { - get { - if ((item != null) && (item.Owner != null)) { - return item.Owner.ImageList; - } - return null; + internal class ToolStripItemImageIndexer : ImageList.Indexer + { + private ToolStripItem item; + + public ToolStripItemImageIndexer(ToolStripItem item) + { + this.item = item; + } + + public override ImageList ImageList + { + get + { + if ((item != null) && (item.Owner != null)) + { + return item.Owner.ImageList; } + return null; + } set { Debug.Assert(false, "We should never set the image list"); } } } - - - - + + + + /// /// /// This class helps determine where the image and text should be drawn. /// /// - internal class ToolStripItemInternalLayout { - + internal class ToolStripItemInternalLayout + { + private ToolStripItemLayoutOptions currentLayoutOptions; private ToolStripItem ownerItem; private ButtonBaseAdapter.LayoutData layoutData; private const int BORDER_WIDTH = 2; private const int BORDER_HEIGHT = 3; private readonly static Size INVALID_SIZE = new Size(int.MinValue, int.MinValue); - + private Size lastPreferredSize = INVALID_SIZE; private ToolStripLayoutData parentLayoutData = null; - - public ToolStripItemInternalLayout(ToolStripItem ownerItem) { - if (ownerItem == null) { - throw new ArgumentNullException(nameof(ownerItem)); + + public ToolStripItemInternalLayout(ToolStripItem ownerItem) + { + if (ownerItem == null) + { + throw new ArgumentNullException(nameof(ownerItem)); } this.ownerItem = ownerItem; } - + // the thing that we fetch properties off of -- this can be different than ownerItem - e.g. case of split button. - protected virtual ToolStripItem Owner { - get { return ownerItem; } + protected virtual ToolStripItem Owner + { + get { return ownerItem; } } - - public virtual Rectangle ImageRectangle { - get { + + public virtual Rectangle ImageRectangle + { + get + { Rectangle imageRect = LayoutData.imageBounds; imageRect.Intersect(layoutData.field); return imageRect; } } - - internal ButtonBaseAdapter.LayoutData LayoutData { - get { - EnsureLayout(); - return layoutData; - } + + internal ButtonBaseAdapter.LayoutData LayoutData + { + get + { + EnsureLayout(); + return layoutData; + } } - public Size PreferredImageSize { - get { + public Size PreferredImageSize + { + get + { return Owner.PreferredImageSize; } } - protected virtual ToolStrip ParentInternal { - get { - return (ownerItem != null) ? ownerItem.ParentInternal : null; - } + protected virtual ToolStrip ParentInternal + { + get + { + return (ownerItem != null) ? ownerItem.ParentInternal : null; + } } - - public virtual Rectangle TextRectangle { - get { + + public virtual Rectangle TextRectangle + { + get + { Rectangle textRect = LayoutData.textBounds; textRect.Intersect(layoutData.field); - return textRect; + return textRect; } } - public virtual Rectangle ContentRectangle { - get { + public virtual Rectangle ContentRectangle + { + get + { return LayoutData.field; } } - public virtual TextFormatFlags TextFormat { - get { - if (currentLayoutOptions != null) { + public virtual TextFormatFlags TextFormat + { + get + { + if (currentLayoutOptions != null) + { return currentLayoutOptions.gdiTextFormatFlags; } return CommonLayoutOptions().gdiTextFormatFlags; @@ -4190,82 +4953,90 @@ public virtual TextFormatFlags TextFormat { } - internal static TextFormatFlags ContentAlignToTextFormat(ContentAlignment alignment, bool rightToLeft) { - TextFormatFlags textFormat = TextFormatFlags.Default; - if (rightToLeft) { - //We specifically do not want to turn on TextFormatFlags.Right. - textFormat |= TextFormatFlags.RightToLeft; + internal static TextFormatFlags ContentAlignToTextFormat(ContentAlignment alignment, bool rightToLeft) + { + TextFormatFlags textFormat = TextFormatFlags.Default; + if (rightToLeft) + { + //We specifically do not want to turn on TextFormatFlags.Right. + textFormat |= TextFormatFlags.RightToLeft; } - + // Calculate Text Positioning textFormat |= ControlPaint.TranslateAlignmentForGDI(alignment); textFormat |= ControlPaint.TranslateLineAlignmentForGDI(alignment); return textFormat; - + } - - protected virtual ToolStripItemLayoutOptions CommonLayoutOptions() { + + protected virtual ToolStripItemLayoutOptions CommonLayoutOptions() + { ToolStripItemLayoutOptions layoutOptions = new ToolStripItemLayoutOptions(); - Rectangle bounds = new Rectangle(Point.Empty, ownerItem.Size); - + Rectangle bounds = new Rectangle(Point.Empty, ownerItem.Size); + layoutOptions.client = bounds; - + layoutOptions.growBorderBy1PxWhenDefault = false; - layoutOptions.borderSize = BORDER_WIDTH; - layoutOptions.paddingSize = 0; - layoutOptions.maxFocus = true; - layoutOptions.focusOddEvenFixup = false; - layoutOptions.font = ownerItem.Font; - layoutOptions.text = ((Owner.DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) ? Owner.Text : string.Empty; - layoutOptions.imageSize = PreferredImageSize; - layoutOptions.checkSize = 0; - layoutOptions.checkPaddingSize = 0; - layoutOptions.checkAlign = ContentAlignment.TopLeft; - layoutOptions.imageAlign = Owner.ImageAlign; - layoutOptions.textAlign = Owner.TextAlign; - layoutOptions.hintTextUp = false; - layoutOptions.shadowedText = !ownerItem.Enabled; - layoutOptions.layoutRTL = RightToLeft.Yes == Owner.RightToLeft; - layoutOptions.textImageRelation = Owner.TextImageRelation; + layoutOptions.borderSize = BORDER_WIDTH; + layoutOptions.paddingSize = 0; + layoutOptions.maxFocus = true; + layoutOptions.focusOddEvenFixup = false; + layoutOptions.font = ownerItem.Font; + layoutOptions.text = ((Owner.DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) ? Owner.Text : string.Empty; + layoutOptions.imageSize = PreferredImageSize; + layoutOptions.checkSize = 0; + layoutOptions.checkPaddingSize = 0; + layoutOptions.checkAlign = ContentAlignment.TopLeft; + layoutOptions.imageAlign = Owner.ImageAlign; + layoutOptions.textAlign = Owner.TextAlign; + layoutOptions.hintTextUp = false; + layoutOptions.shadowedText = !ownerItem.Enabled; + layoutOptions.layoutRTL = RightToLeft.Yes == Owner.RightToLeft; + layoutOptions.textImageRelation = Owner.TextImageRelation; //set textImageInset to 0 since we don't draw 3D border for ToolStripItems. - layoutOptions.textImageInset = 0; + layoutOptions.textImageInset = 0; layoutOptions.everettButtonCompat = false; // Support RTL - layoutOptions.gdiTextFormatFlags = ContentAlignToTextFormat(Owner.TextAlign, Owner.RightToLeft == RightToLeft.Yes); - - + layoutOptions.gdiTextFormatFlags = ContentAlignToTextFormat(Owner.TextAlign, Owner.RightToLeft == RightToLeft.Yes); + + // Hide underlined &File unless ALT is pressed layoutOptions.gdiTextFormatFlags = (Owner.ShowKeyboardCues) ? layoutOptions.gdiTextFormatFlags : layoutOptions.gdiTextFormatFlags | TextFormatFlags.HidePrefix; - + return layoutOptions; } - private bool EnsureLayout() { - - if (layoutData == null || parentLayoutData == null || !parentLayoutData.IsCurrent(ParentInternal)) { + private bool EnsureLayout() + { + + if (layoutData == null || parentLayoutData == null || !parentLayoutData.IsCurrent(ParentInternal)) + { PerformLayout(); return true; } return false; } - private ButtonBaseAdapter.LayoutData GetLayoutData() { - + private ButtonBaseAdapter.LayoutData GetLayoutData() + { + currentLayoutOptions = CommonLayoutOptions(); - - if (Owner.TextDirection != ToolStripTextDirection.Horizontal) { + + if (Owner.TextDirection != ToolStripTextDirection.Horizontal) + { currentLayoutOptions.verticalText = true; } - - ButtonBaseAdapter.LayoutData data = currentLayoutOptions.Layout(); + + ButtonBaseAdapter.LayoutData data = currentLayoutOptions.Layout(); return data; - + } - public virtual Size GetPreferredSize(Size constrainingSize) { + public virtual Size GetPreferredSize(Size constrainingSize) + { Size preferredSize = Size.Empty; EnsureLayout(); // we would prefer not to be larger than the ToolStrip itself. @@ -4274,8 +5045,9 @@ public virtual Size GetPreferredSize(Size constrainingSize) { // bigger than the ToolStrip itself. Note this is "Parent" not // "Owner" because we care in this instance what we're currently displayed on. - if (ownerItem != null) { - lastPreferredSize = currentLayoutOptions.GetPreferredSizeCore(constrainingSize); + if (ownerItem != null) + { + lastPreferredSize = currentLayoutOptions.GetPreferredSizeCore(constrainingSize); return lastPreferredSize; } Debug.Fail("Why are we here without an owner?"); @@ -4283,49 +5055,60 @@ public virtual Size GetPreferredSize(Size constrainingSize) { } - internal void PerformLayout() { + internal void PerformLayout() + { layoutData = GetLayoutData(); ToolStrip parent = ParentInternal; - if (parent != null) { + if (parent != null) + { parentLayoutData = new ToolStripLayoutData(parent); } - else { + else + { parentLayoutData = null; } } - internal class ToolStripItemLayoutOptions : ButtonBaseAdapter.LayoutOptions { + internal class ToolStripItemLayoutOptions : ButtonBaseAdapter.LayoutOptions + { Size cachedSize = LayoutUtils.InvalidSize; Size cachedProposedConstraints = LayoutUtils.InvalidSize; - + // override GetTextSize to provide simple text caching. - protected override Size GetTextSize(Size proposedConstraints) { - if (cachedSize != LayoutUtils.InvalidSize + protected override Size GetTextSize(Size proposedConstraints) + { + if (cachedSize != LayoutUtils.InvalidSize && (cachedProposedConstraints == proposedConstraints - || cachedSize.Width <= proposedConstraints.Width)) { + || cachedSize.Width <= proposedConstraints.Width)) + { return cachedSize; } - else { + else + { cachedSize = base.GetTextSize(proposedConstraints); cachedProposedConstraints = proposedConstraints; } return cachedSize; - + } } - private class ToolStripLayoutData { + private class ToolStripLayoutData + { private ToolStripLayoutStyle layoutStyle; private bool autoSize; private Size size; - - public ToolStripLayoutData(ToolStrip toolStrip) { + + public ToolStripLayoutData(ToolStrip toolStrip) + { this.layoutStyle = toolStrip.LayoutStyle; this.autoSize = toolStrip.AutoSize; this.size = toolStrip.Size; } - public bool IsCurrent(ToolStrip toolStrip) { - if (toolStrip == null) { + public bool IsCurrent(ToolStrip toolStrip) + { + if (toolStrip == null) + { return false; } return (toolStrip.Size == size && toolStrip.LayoutStyle == layoutStyle && toolStrip.AutoSize == autoSize); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemAlignment.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemAlignment.cs index fd1a53ce5c0..ee6bca9bf6d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemAlignment.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemAlignment.cs @@ -9,7 +9,7 @@ namespace System.Windows.Forms /// public enum ToolStripItemAlignment { - Left=0x0, - Right=0x1, + Left = 0x0, + Right = 0x1, } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemCollection.cs index ed00dbf6ef5..f477096d66d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemCollection.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Collections; using System.ComponentModel; @@ -11,7 +12,7 @@ namespace System.Windows.Forms { using System.Diagnostics; using System.Windows.Forms.Layout; using System.Drawing; - + /// /// Summary description for ToolStripItemCollection. /// @@ -19,8 +20,9 @@ namespace System.Windows.Forms { Editor("System.Windows.Forms.Design.ToolStripCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), ListBindable(false), ] - public class ToolStripItemCollection : ArrangedElementCollection, IList { - + public class ToolStripItemCollection : ArrangedElementCollection, IList + { + private ToolStrip owner; private bool itemsCollection; private bool isReadOnly = false; @@ -31,22 +33,26 @@ public class ToolStripItemCollection : ArrangedElementCollection, IList { private int lastAccessedIndex = -1; - internal ToolStripItemCollection(ToolStrip owner, bool itemsCollection) : this(owner, itemsCollection, /*isReadOnly=*/false){ + internal ToolStripItemCollection(ToolStrip owner, bool itemsCollection) : this(owner, itemsCollection, /*isReadOnly=*/false) + { } - internal ToolStripItemCollection(ToolStrip owner, bool itemsCollection, bool isReadOnly) { + internal ToolStripItemCollection(ToolStrip owner, bool itemsCollection, bool isReadOnly) + { this.owner = owner; this.itemsCollection = itemsCollection; this.isReadOnly = isReadOnly; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] - public ToolStripItemCollection(ToolStrip owner, ToolStripItem[] value) { - if (owner == null) { + public ToolStripItemCollection(ToolStrip owner, ToolStripItem[] value) + { + if (owner == null) + { throw new ArgumentNullException(nameof(owner)); } - + this.owner = owner; AddRange(value); } @@ -54,161 +60,201 @@ public ToolStripItemCollection(ToolStrip owner, ToolStripItem[] value) { /// /// /// - public new virtual ToolStripItem this[int index] { - get { + public new virtual ToolStripItem this[int index] + { + get + { return (ToolStripItem)(InnerList[index]); } } - + /// /// Retrieves the child control with the specified key. /// - public virtual ToolStripItem this[string key] { - get { + public virtual ToolStripItem this[string key] + { + get + { // We do not support null and empty string as valid keys. - if ((key == null) || (key.Length == 0)){ + if ((key == null) || (key.Length == 0)) + { return null; } // Search for the key in our collection int index = IndexOfKey(key); - if (IsValidIndex(index)) { + if (IsValidIndex(index)) + { return (ToolStripItem)InnerList[index]; } - else { + else + { return null; } } } - - public ToolStripItem Add(string text) { - return Add(text,null,null); + + public ToolStripItem Add(string text) + { + return Add(text, null, null); } - public ToolStripItem Add(Image image) { - return Add(null,image,null); + public ToolStripItem Add(Image image) + { + return Add(null, image, null); } - public ToolStripItem Add(string text, Image image) { - return Add(text,image,null); + public ToolStripItem Add(string text, Image image) + { + return Add(text, image, null); } - public ToolStripItem Add(string text, Image image, EventHandler onClick) { - ToolStripItem item = owner.CreateDefaultItem(text,image,onClick); + public ToolStripItem Add(string text, Image image, EventHandler onClick) + { + ToolStripItem item = owner.CreateDefaultItem(text, image, onClick); Add(item); return item; } - - public int Add(ToolStripItem value) { + + public int Add(ToolStripItem value) + { CheckCanAddOrInsertItem(value); - + SetOwner(value); - int retVal = InnerList.Add(value); - if (itemsCollection && owner != null) { + int retVal = InnerList.Add(value); + if (itemsCollection && owner != null) + { owner.OnItemAddedInternal(value); - owner.OnItemAdded(new ToolStripItemEventArgs(value)); - } + owner.OnItemAdded(new ToolStripItemEventArgs(value)); + } return retVal; - + } - public void AddRange(ToolStripItem[] toolStripItems) { - if (toolStripItems == null) { + public void AddRange(ToolStripItem[] toolStripItems) + { + if (toolStripItems == null) + { throw new ArgumentNullException(nameof(toolStripItems)); } - if (IsReadOnly) { + if (IsReadOnly) + { throw new NotSupportedException(SR.ToolStripItemCollectionIsReadOnly); } // ToolStripDropDown will look for PropertyNames.Items to determine if it needs // to resize itself. - using (new LayoutTransaction(this.owner, this.owner, PropertyNames.Items)) { - for (int i = 0; i < toolStripItems.Length; i++) { + using (new LayoutTransaction(this.owner, this.owner, PropertyNames.Items)) + { + for (int i = 0; i < toolStripItems.Length; i++) + { this.Add(toolStripItems[i]); } } } - public void AddRange(ToolStripItemCollection toolStripItems) { - if (toolStripItems == null) { + public void AddRange(ToolStripItemCollection toolStripItems) + { + if (toolStripItems == null) + { throw new ArgumentNullException(nameof(toolStripItems)); } - if (IsReadOnly) { + if (IsReadOnly) + { throw new NotSupportedException(SR.ToolStripItemCollectionIsReadOnly); } // ToolStripDropDown will look for PropertyNames.Items to determine if it needs // to resize itself. - using (new LayoutTransaction(this.owner, this.owner, PropertyNames.Items)) { + using (new LayoutTransaction(this.owner, this.owner, PropertyNames.Items)) + { int currentCount = toolStripItems.Count; - for (int i = 0; i < currentCount; i++) { + for (int i = 0; i < currentCount; i++) + { this.Add(toolStripItems[i]); } } - + } - public bool Contains(ToolStripItem value) { + public bool Contains(ToolStripItem value) + { return InnerList.Contains(value); } - - public virtual void Clear() { - if (IsReadOnly) { - throw new NotSupportedException(SR.ToolStripItemCollectionIsReadOnly); + + public virtual void Clear() + { + if (IsReadOnly) + { + throw new NotSupportedException(SR.ToolStripItemCollectionIsReadOnly); } - if (Count == 0) { + if (Count == 0) + { return; } ToolStripOverflow overflow = null; - if (owner != null && !owner.IsDisposingItems) { + if (owner != null && !owner.IsDisposingItems) + { owner.SuspendLayout(); overflow = owner.GetOverflow(); - if (overflow != null) { + if (overflow != null) + { overflow.SuspendLayout(); } } - try { - while (Count != 0) { + try + { + while (Count != 0) + { RemoveAt(Count - 1); } } - finally { - if (overflow != null) { + finally + { + if (overflow != null) + { overflow.ResumeLayout(false); } - if (owner != null && !owner.IsDisposingItems) { + if (owner != null && !owner.IsDisposingItems) + { owner.ResumeLayout(); } } } - + /// /// Returns true if the collection contains an item with the specified key, false otherwise. /// - public virtual bool ContainsKey(string key) { - return IsValidIndex(IndexOfKey(key)); + public virtual bool ContainsKey(string key) + { + return IsValidIndex(IndexOfKey(key)); } - private void CheckCanAddOrInsertItem(ToolStripItem value) { - if (value == null) { + private void CheckCanAddOrInsertItem(ToolStripItem value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } - if (IsReadOnly) { + if (IsReadOnly) + { throw new NotSupportedException(SR.ToolStripItemCollectionIsReadOnly); } - - + + ToolStripDropDown dropDown = owner as ToolStripDropDown; - if (dropDown != null) { + if (dropDown != null) + { // If we're on a dropdown, we can only add non-control host items // as we dont want anything on a dropdown to get keyboard messages in the Internet. - if (dropDown.OwnerItem == value) { - throw new NotSupportedException(SR.ToolStripItemCircularReference); + if (dropDown.OwnerItem == value) + { + throw new NotSupportedException(SR.ToolStripItemCircularReference); } } - + } /// @@ -216,20 +262,22 @@ private void CheckCanAddOrInsertItem(ToolStripItem value) { /// of all the controls that match. /// /// - public ToolStripItem[] Find(string key, bool searchAllChildren) { - if ((key == null) || (key.Length == 0)) { - throw new System.ArgumentNullException(nameof(key), SR.FindKeyMayNotBeEmptyOrNull); + public ToolStripItem[] Find(string key, bool searchAllChildren) + { + if ((key == null) || (key.Length == 0)) + { + throw new System.ArgumentNullException(nameof(key), SR.FindKeyMayNotBeEmptyOrNull); } - ArrayList foundItems = FindInternal(key, searchAllChildren, this, new ArrayList()); + ArrayList foundItems = FindInternal(key, searchAllChildren, this, new ArrayList()); // Make this a stongly typed collection. - ToolStripItem[] stronglyTypedFoundItems = new ToolStripItem[foundItems.Count]; + ToolStripItem[] stronglyTypedFoundItems = new ToolStripItem[foundItems.Count]; foundItems.CopyTo(stronglyTypedFoundItems, 0); return stronglyTypedFoundItems; } - + /// /// Searches for Items by their Name property, builds up an array list /// of all the items that match. @@ -237,7 +285,8 @@ public ToolStripItem[] Find(string key, bool searchAllChildren) { /// private ArrayList FindInternal(string key, bool searchAllChildren, ToolStripItemCollection itemsToLookIn, ArrayList foundItems) { - if ((itemsToLookIn == null) || (foundItems == null)) { + if ((itemsToLookIn == null) || (foundItems == null)) + { return null; // } @@ -284,67 +333,79 @@ private ArrayList FindInternal(string key, bool searchAllChildren, ToolStripItem throw; } } - + return foundItems; } - - public override bool IsReadOnly { get { return this.isReadOnly; }} + + public override bool IsReadOnly { get { return this.isReadOnly; } } void IList.Clear() { Clear(); } - bool IList.IsFixedSize { get { return InnerList.IsFixedSize; }} + bool IList.IsFixedSize { get { return InnerList.IsFixedSize; } } bool IList.Contains(object value) { return InnerList.Contains(value); } void IList.RemoveAt(int index) { RemoveAt(index); } void IList.Remove(object value) { Remove(value as ToolStripItem); } int IList.Add(object value) { return Add(value as ToolStripItem); } int IList.IndexOf(object value) { return IndexOf(value as ToolStripItem); } - void IList.Insert(int index, object value) { Insert(index, value as ToolStripItem); } + void IList.Insert(int index, object value) { Insert(index, value as ToolStripItem); } - object IList.this[int index] { - get { return InnerList[index]; } + object IList.this[int index] + { + get { return InnerList[index]; } set { throw new NotSupportedException(SR.ToolStripCollectionMustInsertAndRemove); /* InnerList[index] = value; */ } } - public void Insert(int index, ToolStripItem value) { + public void Insert(int index, ToolStripItem value) + { CheckCanAddOrInsertItem(value); SetOwner(value); InnerList.Insert(index, value); - if (itemsCollection && owner != null) { - if (owner.IsHandleCreated){ + if (itemsCollection && owner != null) + { + if (owner.IsHandleCreated) + { LayoutTransaction.DoLayout(owner, value, PropertyNames.Parent); } - else { + else + { // next time we fetch the preferred size, recalc it. CommonProperties.xClearPreferredSizeCache(owner); } owner.OnItemAddedInternal(value); - owner.OnItemAdded(new ToolStripItemEventArgs(value)); - } + owner.OnItemAdded(new ToolStripItemEventArgs(value)); + } } - - public int IndexOf(ToolStripItem value) { + + public int IndexOf(ToolStripItem value) + { return InnerList.IndexOf(value); } /// /// The zero-based index of the first occurrence of value within the entire CollectionBase, if found; otherwise, -1. /// - public virtual int IndexOfKey(string key) { + public virtual int IndexOfKey(string key) + { // Step 0 - Arg validation - if ((key == null) || (key.Length == 0)){ + if ((key == null) || (key.Length == 0)) + { return -1; // we dont support empty or null keys. } // step 1 - check the last cached item - if (IsValidIndex(lastAccessedIndex)) { - if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) { + if (IsValidIndex(lastAccessedIndex)) + { + if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) + { return lastAccessedIndex; } } // step 2 - search for the item - for (int i = 0; i < this.Count; i ++) { - if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { + for (int i = 0; i < this.Count; i++) + { + if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) + { lastAccessedIndex = i; return i; } @@ -358,81 +419,100 @@ public virtual int IndexOfKey(string key) { /// /// Determines if the index is valid for the collection. /// - private bool IsValidIndex(int index) { + private bool IsValidIndex(int index) + { return ((index >= 0) && (index < this.Count)); } /// /// Do proper cleanup of ownership, etc. /// - private void OnAfterRemove(ToolStripItem item) { - if (itemsCollection) { - ToolStrip parent = null; - if (item != null) { + private void OnAfterRemove(ToolStripItem item) + { + if (itemsCollection) + { + ToolStrip parent = null; + if (item != null) + { parent = item.ParentInternal; item.SetOwner(null); } - if (owner != null) { + if (owner != null) + { owner.OnItemRemovedInternal(item); - if (!owner.IsDisposingItems) { + if (!owner.IsDisposingItems) + { ToolStripItemEventArgs e = new ToolStripItemEventArgs(item); owner.OnItemRemoved(e); // dont fire the ItemRemoved event for Overflow // it would fire constantly.... instead clear any state if the item // is really being removed from the master collection. - if (parent != null && parent != owner) { + if (parent != null && parent != owner) + { parent.OnItemVisibleChanged(e, /*performLayout*/false); } } } } } - - public void Remove(ToolStripItem value) { - if (IsReadOnly) { - throw new NotSupportedException(SR.ToolStripItemCollectionIsReadOnly); + + public void Remove(ToolStripItem value) + { + if (IsReadOnly) + { + throw new NotSupportedException(SR.ToolStripItemCollectionIsReadOnly); } InnerList.Remove(value); OnAfterRemove(value); } - public void RemoveAt(int index) { - if (IsReadOnly) { - throw new NotSupportedException(SR.ToolStripItemCollectionIsReadOnly); + public void RemoveAt(int index) + { + if (IsReadOnly) + { + throw new NotSupportedException(SR.ToolStripItemCollectionIsReadOnly); } ToolStripItem item = null; - if (index < Count && index >= 0) { + if (index < Count && index >= 0) + { item = (ToolStripItem)(InnerList[index]); } InnerList.RemoveAt(index); OnAfterRemove(item); } - + /// /// Removes the child item with the specified key. /// - public virtual void RemoveByKey(string key) { - if (IsReadOnly) { - throw new NotSupportedException(SR.ToolStripItemCollectionIsReadOnly); + public virtual void RemoveByKey(string key) + { + if (IsReadOnly) + { + throw new NotSupportedException(SR.ToolStripItemCollectionIsReadOnly); } int index = IndexOfKey(key); - if (IsValidIndex(index)) { - RemoveAt(index); + if (IsValidIndex(index)) + { + RemoveAt(index); } } - public void CopyTo(ToolStripItem[] array, int index) { + public void CopyTo(ToolStripItem[] array, int index) + { InnerList.CopyTo(array, index); } - + // - internal void MoveItem(ToolStripItem value) { - if (value.ParentInternal != null) { + internal void MoveItem(ToolStripItem value) + { + if (value.ParentInternal != null) + { int indexOfItem = value.ParentInternal.Items.IndexOf(value); - if (indexOfItem >= 0) { + if (indexOfItem >= 0) + { value.ParentInternal.Items.RemoveAt(indexOfItem); } } @@ -440,48 +520,58 @@ internal void MoveItem(ToolStripItem value) { } - internal void MoveItem(int index, ToolStripItem value) { - + internal void MoveItem(int index, ToolStripItem value) + { + // if moving to the end - call add instead. - if (index == this.Count) { + if (index == this.Count) + { MoveItem(value); return; } - - if (value.ParentInternal != null) { + + if (value.ParentInternal != null) + { int indexOfItem = value.ParentInternal.Items.IndexOf(value); - - if (indexOfItem >= 0) { + + if (indexOfItem >= 0) + { value.ParentInternal.Items.RemoveAt(indexOfItem); - - if ((value.ParentInternal == owner) && (index > indexOfItem)) { + + if ((value.ParentInternal == owner) && (index > indexOfItem)) + { index--; } } } - Insert(index,value); + Insert(index, value); } - private void SetOwner(ToolStripItem item) { + private void SetOwner(ToolStripItem item) + { - if (itemsCollection) { - - if (item != null) { - if (item.Owner != null) { + if (itemsCollection) + { + + if (item != null) + { + if (item.Owner != null) + { item.Owner.Items.Remove(item); } item.SetOwner(owner); - if (item.Renderer != null) { + if (item.Renderer != null) + { item.Renderer.InitializeItem(item); } } } } - + } - + } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemDisplayStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemDisplayStyle.cs index 1ec9147e02f..f64f7b1e6ba 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemDisplayStyle.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemDisplayStyle.cs @@ -9,9 +9,9 @@ namespace System.Windows.Forms /// public enum ToolStripItemDisplayStyle { - None = 0x0000, - Text = 0x0001, - Image = 0x0002, - ImageAndText = 0x0003, + None = 0x0000, + Text = 0x0001, + Image = 0x0002, + ImageAndText = 0x0003, } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemEventArgs.cs index 13e9b109c26..f59aa686443 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemEventArgs.cs @@ -8,7 +8,7 @@ public class ToolStripItemEventArgs : EventArgs { public ToolStripItemEventArgs(ToolStripItem item) { - Item = item; + Item = item; } public ToolStripItem Item { get; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemImageRenderEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemImageRenderEventArgs.cs index 62fdad9cad2..ecfec7a5ff5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemImageRenderEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemImageRenderEventArgs.cs @@ -29,10 +29,10 @@ public ToolStripItemImageRenderEventArgs(Graphics g, ToolStripItem item, Image i /// public Image Image { get; } - /// - /// The rectangle to draw the Image in - /// - public Rectangle ImageRectangle { get; } + /// + /// The rectangle to draw the Image in + /// + public Rectangle ImageRectangle { get; } /// /// Not public as it currently pertains to button & system renderer. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemImageScaling.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemImageScaling.cs index d6956b69f1f..7b33fe96d4f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemImageScaling.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemImageScaling.cs @@ -5,8 +5,8 @@ namespace System.Windows.Forms { public enum ToolStripItemImageScaling - { - None, + { + None, SizeToFit } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemRenderEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemRenderEventArgs.cs index efb5e517288..fd282c142f0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemRenderEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemRenderEventArgs.cs @@ -26,10 +26,10 @@ public ToolStripItemRenderEventArgs(Graphics g, ToolStripItem item) /// The item to draw /// public ToolStripItem Item { get; } - - /// - /// The toolstrip the item is currently parented to - /// + + /// + /// The toolstrip the item is currently parented to + /// public ToolStrip ToolStrip => Item.ParentInternal; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemStates.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemStates.cs index 73b69eb708c..59d7447ea9f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemStates.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemStates.cs @@ -6,11 +6,11 @@ namespace System.Windows.Forms { internal enum ToolStripItemStates { - None = 0x00000000, - Selected = 0x00000001, - Focused = 0x00000002, - Hot = 0x00000004, - Pressed = 0x00000008, + None = 0x00000000, + Selected = 0x00000001, + Focused = 0x00000002, + Hot = 0x00000004, + Pressed = 0x00000008, Disabled = 0x00000010 } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemTextRenderEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemTextRenderEventArgs.cs index 878579a8f3c..578f6f360d8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemTextRenderEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemTextRenderEventArgs.cs @@ -58,7 +58,7 @@ public Color TextColor set { _textColor = value; - _textColorChanged=true; + _textColorChanged = true; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripLabel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripLabel.cs index c5b12c949d9..a44e047d23d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripLabel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripLabel.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.ComponentModel; using System.Drawing; @@ -10,48 +11,57 @@ namespace System.Windows.Forms { using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Windows.Forms.ButtonInternal; - using System.Windows.Forms.Design; + using System.Windows.Forms.Design; /// /// A non selectable ToolStrip item /// [ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ToolStrip)] - public class ToolStripLabel : ToolStripItem { + public class ToolStripLabel : ToolStripItem + { private LinkBehavior linkBehavior = LinkBehavior.SystemDefault; private bool isLink = false, linkVisited = false; - + private Color linkColor = Color.Empty; private Color activeLinkColor = Color.Empty; private Color visitedLinkColor = Color.Empty; private Font hoverLinkFont, linkFont; private Cursor lastCursor; - - - + + + /// /// A non selectable ToolStrip item /// - public ToolStripLabel() { + public ToolStripLabel() + { } - public ToolStripLabel(string text):base(text,null,null) { + public ToolStripLabel(string text) : base(text, null, null) + { } - public ToolStripLabel(Image image):base(null,image,null) { + public ToolStripLabel(Image image) : base(null, image, null) + { } - public ToolStripLabel(string text, Image image):base(text,image,null) { + public ToolStripLabel(string text, Image image) : base(text, image, null) + { } - public ToolStripLabel(string text, Image image, bool isLink):this(text,image,isLink, null) { + public ToolStripLabel(string text, Image image, bool isLink) : this(text, image, isLink, null) + { } [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] - public ToolStripLabel(string text, Image image, bool isLink, EventHandler onClick):this(text,image,isLink,onClick,null) { + public ToolStripLabel(string text, Image image, bool isLink, EventHandler onClick) : this(text, image, isLink, onClick, null) + { } [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] - public ToolStripLabel(string text, Image image, bool isLink, EventHandler onClick, string name) : base(text,image,onClick,name) { + public ToolStripLabel(string text, Image image, bool isLink, EventHandler onClick, string name) : base(text, image, onClick, name) + { IsLink = isLink; } - public override bool CanSelect { + public override bool CanSelect + { get { return (IsLink || DesignMode); } } @@ -60,53 +70,69 @@ public override bool CanSelect { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ToolStripLabelIsLinkDescr)) ] - public bool IsLink { - get { - return isLink; - } - set { - if (isLink != value) { - isLink = value; - Invalidate(); - } - } - } - + public bool IsLink + { + get + { + return isLink; + } + set + { + if (isLink != value) + { + isLink = value; + Invalidate(); + } + } + } + [ SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripLabelActiveLinkColorDescr)) ] - public Color ActiveLinkColor { - get { - if (activeLinkColor.IsEmpty) { + public Color ActiveLinkColor + { + get + { + if (activeLinkColor.IsEmpty) + { return IEActiveLinkColor; } - else { + else + { return activeLinkColor; } } - set { - if (activeLinkColor != value) { + set + { + if (activeLinkColor != value) + { activeLinkColor = value; Invalidate(); } } } - private Color IELinkColor { - get { - return LinkUtilities.IELinkColor; - } + private Color IELinkColor + { + get + { + return LinkUtilities.IELinkColor; + } } - private Color IEActiveLinkColor { - get { - return LinkUtilities.IEActiveLinkColor; - } + private Color IEActiveLinkColor + { + get + { + return LinkUtilities.IEActiveLinkColor; + } } - private Color IEVisitedLinkColor { - get { - return LinkUtilities.IEVisitedLinkColor; - } + private Color IEVisitedLinkColor + { + get + { + return LinkUtilities.IEVisitedLinkColor; + } } [ @@ -114,17 +140,21 @@ private Color IEVisitedLinkColor { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ToolStripLabelLinkBehaviorDescr)) ] - public LinkBehavior LinkBehavior { - get { + public LinkBehavior LinkBehavior + { + get + { return linkBehavior; } - set { + set + { //valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(value, (int)value, (int)LinkBehavior.SystemDefault, (int)LinkBehavior.NeverUnderline)) { throw new InvalidEnumArgumentException(nameof(LinkBehavior), (int)value, typeof(LinkBehavior)); } - if (linkBehavior != value) { + if (linkBehavior != value) + { linkBehavior = value; InvalidateLinkFonts(); Invalidate(); @@ -136,17 +166,23 @@ public LinkBehavior LinkBehavior { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripLabelLinkColorDescr)) ] - public Color LinkColor { - get { - if (linkColor.IsEmpty) { + public Color LinkColor + { + get + { + if (linkColor.IsEmpty) + { return IELinkColor; } - else { + else + { return linkColor; } } - set { - if (linkColor != value) { + set + { + if (linkColor != value) + { linkColor = value; Invalidate(); } @@ -158,12 +194,16 @@ public Color LinkColor { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripLabelLinkVisitedDescr)) ] - public bool LinkVisited { - get { + public bool LinkVisited + { + get + { return linkVisited; } - set { - if (linkVisited != value) { + set + { + if (linkVisited != value) + { linkVisited = value; Invalidate(); } @@ -174,226 +214,276 @@ public bool LinkVisited { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripLabelVisitedLinkColorDescr)) ] - public Color VisitedLinkColor { - get { - if (visitedLinkColor.IsEmpty) { + public Color VisitedLinkColor + { + get + { + if (visitedLinkColor.IsEmpty) + { return IEVisitedLinkColor; } - else { + else + { return visitedLinkColor; } } - set { - if (visitedLinkColor != value) { + set + { + if (visitedLinkColor != value) + { visitedLinkColor = value; Invalidate(); } } } - + /// /// Invalidates the current set of fonts we use when painting /// links. The fonts will be recreated when needed. /// - private void InvalidateLinkFonts() { - - if (linkFont != null) { + private void InvalidateLinkFonts() + { + + if (linkFont != null) + { linkFont.Dispose(); } - - if (hoverLinkFont != null && hoverLinkFont != linkFont) { + + if (hoverLinkFont != null && hoverLinkFont != linkFont) + { hoverLinkFont.Dispose(); } - + linkFont = null; hoverLinkFont = null; } - - protected override void OnFontChanged(EventArgs e) { - InvalidateLinkFonts(); - base.OnFontChanged(e); + + protected override void OnFontChanged(EventArgs e) + { + InvalidateLinkFonts(); + base.OnFontChanged(e); } - - protected override void OnMouseEnter(EventArgs e) { - if (IsLink) { + + protected override void OnMouseEnter(EventArgs e) + { + if (IsLink) + { ToolStrip parent = this.Parent; - if (parent != null) { + if (parent != null) + { lastCursor = parent.Cursor; parent.Cursor = Cursors.Hand; } } base.OnMouseEnter(e); - + } - - protected override void OnMouseLeave(EventArgs e) { - if (IsLink) { + + protected override void OnMouseLeave(EventArgs e) + { + if (IsLink) + { ToolStrip parent = this.Parent; - if (parent != null) { + if (parent != null) + { parent.Cursor = lastCursor; } } base.OnMouseLeave(e); - + } - private void ResetActiveLinkColor() - { + private void ResetActiveLinkColor() + { ActiveLinkColor = IEActiveLinkColor; - } + } - private void ResetLinkColor() - { + private void ResetLinkColor() + { LinkColor = IELinkColor; - } + } - private void ResetVisitedLinkColor() - { + private void ResetVisitedLinkColor() + { VisitedLinkColor = IEVisitedLinkColor; - } - - [EditorBrowsable(EditorBrowsableState.Never)] - private bool ShouldSerializeActiveLinkColor() { - return !activeLinkColor.IsEmpty; - } - - [EditorBrowsable(EditorBrowsableState.Never)] - private bool ShouldSerializeLinkColor() { - return !linkColor.IsEmpty; - } - - [EditorBrowsable(EditorBrowsableState.Never)] - private bool ShouldSerializeVisitedLinkColor() { - return !visitedLinkColor.IsEmpty; - } - - + } + + [EditorBrowsable(EditorBrowsableState.Never)] + private bool ShouldSerializeActiveLinkColor() + { + return !activeLinkColor.IsEmpty; + } + + [EditorBrowsable(EditorBrowsableState.Never)] + private bool ShouldSerializeLinkColor() + { + return !linkColor.IsEmpty; + } + + [EditorBrowsable(EditorBrowsableState.Never)] + private bool ShouldSerializeVisitedLinkColor() + { + return !visitedLinkColor.IsEmpty; + } + + /// /// Creates an instance of the object that defines how image and text /// gets laid out in the ToolStripItem /// - internal override ToolStripItemInternalLayout CreateInternalLayout() { + internal override ToolStripItemInternalLayout CreateInternalLayout() + { return new ToolStripLabelLayout(this); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new ToolStripLabelAccessibleObject(this); } /// /// Inheriting classes should override this method to handle this event. /// - protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { + protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) + { - if (this.Owner != null) { + if (this.Owner != null) + { ToolStripRenderer renderer = this.Renderer; - + renderer.DrawLabelBackground(new ToolStripItemRenderEventArgs(e.Graphics, this)); - if ((DisplayStyle & ToolStripItemDisplayStyle.Image) == ToolStripItemDisplayStyle.Image) { + if ((DisplayStyle & ToolStripItemDisplayStyle.Image) == ToolStripItemDisplayStyle.Image) + { renderer.DrawItemImage(new ToolStripItemImageRenderEventArgs(e.Graphics, this, InternalLayout.ImageRectangle)); } PaintText(e.Graphics); } } - internal void PaintText(Graphics g) { + internal void PaintText(Graphics g) + { ToolStripRenderer renderer = this.Renderer; - - if ((DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) { - Font font = this.Font; - Color textColor = this.ForeColor; - if (IsLink) { - LinkUtilities.EnsureLinkFonts(font, this.LinkBehavior, ref this.linkFont, ref this.hoverLinkFont); - - if (this.Pressed) { - font = hoverLinkFont; - textColor = this.ActiveLinkColor; - } - else if (this.Selected) { - font = hoverLinkFont; - textColor = (this.LinkVisited) ? this.VisitedLinkColor : this.LinkColor; - } - else { - font = linkFont; - textColor = (this.LinkVisited) ? this.VisitedLinkColor : this.LinkColor; - } - } - Rectangle textRect = InternalLayout.TextRectangle; - renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, this.Text, textRect, textColor, font, InternalLayout.TextFormat)); - } - } - + + if ((DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) + { + Font font = this.Font; + Color textColor = this.ForeColor; + if (IsLink) + { + LinkUtilities.EnsureLinkFonts(font, this.LinkBehavior, ref this.linkFont, ref this.hoverLinkFont); + + if (this.Pressed) + { + font = hoverLinkFont; + textColor = this.ActiveLinkColor; + } + else if (this.Selected) + { + font = hoverLinkFont; + textColor = (this.LinkVisited) ? this.VisitedLinkColor : this.LinkColor; + } + else + { + font = linkFont; + textColor = (this.LinkVisited) ? this.VisitedLinkColor : this.LinkColor; + } + } + Rectangle textRect = InternalLayout.TextRectangle; + renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, this.Text, textRect, textColor, font, InternalLayout.TextFormat)); + } + } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] // 'charCode' matches control.cs - protected internal override bool ProcessMnemonic(char charCode) { + protected internal override bool ProcessMnemonic(char charCode) + { // checking IsMnemonic is not necessary - toolstrip does this for us. - if (ParentInternal != null) { - if (!CanSelect) { + if (ParentInternal != null) + { + if (!CanSelect) + { ParentInternal.SetFocusUnsafe(); ParentInternal.SelectNextToolStripItem(this, /*forward=*/true); } - else { + else + { FireEvent(ToolStripItemEventType.Click); } return true; - + } return false; } - - [System.Runtime.InteropServices.ComVisible(true)] + + [System.Runtime.InteropServices.ComVisible(true)] [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] - internal class ToolStripLabelAccessibleObject : ToolStripItemAccessibleObject { + internal class ToolStripLabelAccessibleObject : ToolStripItemAccessibleObject + { private ToolStripLabel ownerItem = null; - public ToolStripLabelAccessibleObject(ToolStripLabel ownerItem) : base(ownerItem) { - this.ownerItem = ownerItem; + public ToolStripLabelAccessibleObject(ToolStripLabel ownerItem) : base(ownerItem) + { + this.ownerItem = ownerItem; } - public override string DefaultAction { - get { - if (ownerItem.IsLink) { + public override string DefaultAction + { + get + { + if (ownerItem.IsLink) + { return SR.AccessibleActionClick; } - else { + else + { return string.Empty; } } } - public override void DoDefaultAction() { - if (ownerItem.IsLink) { + public override void DoDefaultAction() + { + if (ownerItem.IsLink) + { base.DoDefaultAction(); } } - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_ControlTypePropertyId) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_ControlTypePropertyId) + { return NativeMethods.UIA_TextControlTypeId; } - else if (propertyID == NativeMethods.UIA_LegacyIAccessibleStatePropertyId) { + else if (propertyID == NativeMethods.UIA_LegacyIAccessibleStatePropertyId) + { return this.State; } return base.GetPropertyValue(propertyID); } - public override AccessibleRole Role { - get { - AccessibleRole role = Owner.AccessibleRole; - if (role != AccessibleRole.Default) { - return role; - } - return (ownerItem.IsLink) ? AccessibleRole.Link : AccessibleRole.StaticText; - } + public override AccessibleRole Role + { + get + { + AccessibleRole role = Owner.AccessibleRole; + if (role != AccessibleRole.Default) + { + return role; + } + return (ownerItem.IsLink) ? AccessibleRole.Link : AccessibleRole.StaticText; + } } - public override AccessibleStates State { - get { + public override AccessibleStates State + { + get + { return base.State | AccessibleStates.ReadOnly; } } @@ -403,24 +493,27 @@ public override AccessibleStates State { /// Its main job is to make sure the inner button has the same parent as the split button, so /// that layout can be performed using the correct graphics context. /// - private class ToolStripLabelLayout : ToolStripItemInternalLayout { + private class ToolStripLabelLayout : ToolStripItemInternalLayout + { - ToolStripLabel owner; + ToolStripLabel owner; - public ToolStripLabelLayout(ToolStripLabel owner) : base(owner) { + public ToolStripLabelLayout(ToolStripLabel owner) : base(owner) + { this.owner = owner; } - protected override ToolStripItemLayoutOptions CommonLayoutOptions() { - ToolStripItemLayoutOptions layoutOptions = base.CommonLayoutOptions(); - layoutOptions.borderSize = 0; - return layoutOptions; + protected override ToolStripItemLayoutOptions CommonLayoutOptions() + { + ToolStripItemLayoutOptions layoutOptions = base.CommonLayoutOptions(); + layoutOptions.borderSize = 0; + return layoutOptions; } } - + } } - + diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripLayoutStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripLayoutStyle.cs index c06aef68820..bfc416f5acb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripLayoutStyle.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripLayoutStyle.cs @@ -8,8 +8,8 @@ public enum ToolStripLayoutStyle { StackWithOverflow = 0x0, HorizontalStackWithOverflow = 0x1, - VerticalStackWithOverflow = 0x2, + VerticalStackWithOverflow = 0x2, Flow = 0x3, - Table = 0x4 + Table = 0x4 } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs index 1289fa27498..16049c60e28 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; @@ -16,7 +17,8 @@ namespace System.Windows.Forms { using Microsoft.Win32; using System.Globalization; - public sealed class ToolStripManager { + public sealed class ToolStripManager + { // WARNING: ThreadStatic initialization happens only on the first thread at class CTOR time. // use InitializeThread mechanism to initialize ThreadStatic members @@ -39,44 +41,57 @@ public sealed class ToolStripManager { private static object internalSyncObject = new object(); - private static void InitalizeThread() { - if (!initialized) { + private static void InitalizeThread() + { + if (!initialized) + { initialized = true; currentRendererType = ProfessionalRendererType; } } - private ToolStripManager() { + private ToolStripManager() + { } - static ToolStripManager() { + static ToolStripManager() + { SystemEvents.UserPreferenceChanging += new UserPreferenceChangingEventHandler(OnUserPreferenceChanging); } - internal static Font DefaultFont { - get { + internal static Font DefaultFont + { + get + { Font sysFont = null; Font retFont = defaultFont; // threadsafe local reference - if (retFont == null) { - lock (internalSyncObject) { + if (retFont == null) + { + lock (internalSyncObject) + { // double check the defaultFont after the lock. retFont = defaultFont; - if (retFont == null) { + if (retFont == null) + { // default to menu font sysFont = SystemFonts.MenuFont; - if (sysFont == null) { + if (sysFont == null) + { // ...or to control font if menu font unavailable sysFont = Control.DefaultFont; } - if (sysFont != null) { + if (sysFont != null) + { // ensure font is in pixels so it displays properly in the property grid at design time. - if (sysFont.Unit != GraphicsUnit.Point) { + if (sysFont.Unit != GraphicsUnit.Point) + { defaultFont = ControlPaint.FontInPoints(sysFont); retFont = defaultFont; sysFont.Dispose(); } - else { + else + { defaultFont = sysFont; retFont = defaultFont; } @@ -89,9 +104,12 @@ internal static Font DefaultFont { } } - internal static ClientUtils.WeakRefCollection ToolStrips { - get { - if (toolStripWeakArrayList == null) { + internal static ClientUtils.WeakRefCollection ToolStrips + { + get + { + if (toolStripWeakArrayList == null) + { toolStripWeakArrayList = new ClientUtils.WeakRefCollection(); } return toolStripWeakArrayList; @@ -100,9 +118,12 @@ internal static ClientUtils.WeakRefCollection ToolStrips { ///Static events only!!! - private static void AddEventHandler(int key, Delegate value) { - lock (internalSyncObject) { - if (staticEventHandlers == null) { + private static void AddEventHandler(int key, Delegate value) + { + lock (internalSyncObject) + { + if (staticEventHandlers == null) + { staticEventHandlers = new Delegate[staticEventCount]; } staticEventHandlers[key] = Delegate.Combine(staticEventHandlers[key], value); @@ -113,11 +134,14 @@ private static void AddEventHandler(int key, Delegate value) { /// /// Find a toolstrip in the weak ref arraylist, return null if nothing was found /// - public static ToolStrip FindToolStrip(string toolStripName) { + public static ToolStrip FindToolStrip(string toolStripName) + { ToolStrip result = null; - for (int i = 0; i < ToolStrips.Count; i++) { + for (int i = 0; i < ToolStrips.Count; i++) + { // is this the right string comparaison? - if (ToolStrips[i] != null && string.Equals(((ToolStrip)ToolStrips[i]).Name, toolStripName, StringComparison.Ordinal)) { + if (ToolStrips[i] != null && string.Equals(((ToolStrip)ToolStrips[i]).Name, toolStripName, StringComparison.Ordinal)) + { result = (ToolStrip)ToolStrips[i]; break; } @@ -137,7 +161,8 @@ internal static ToolStrip FindToolStrip(Form owningForm, string toolStripName) if (ToolStrips[i] != null && string.Equals(((ToolStrip)ToolStrips[i]).Name, toolStripName, StringComparison.Ordinal)) { result = (ToolStrip)ToolStrips[i]; - if (result.FindForm() == owningForm) { + if (result.FindForm() == owningForm) + { break; } } @@ -146,8 +171,10 @@ internal static ToolStrip FindToolStrip(Form owningForm, string toolStripName) } - private static bool CanChangeSelection(ToolStrip start, ToolStrip toolStrip) { - if (toolStrip == null) { + private static bool CanChangeSelection(ToolStrip start, ToolStrip toolStrip) + { + if (toolStrip == null) + { Debug.Fail("passed in bogus toolstrip, why?"); return false; } @@ -160,9 +187,12 @@ private static bool CanChangeSelection(ToolStrip start, ToolStrip toolStrip) { IsOnSameWindow(start, toolStrip); - if (canChange) { - foreach (ToolStripItem item in toolStrip.Items) { - if (item.CanSelect) { + if (canChange) + { + foreach (ToolStripItem item in toolStrip.Items) + { + if (item.CanSelect) + { return true; } } @@ -170,23 +200,29 @@ private static bool CanChangeSelection(ToolStrip start, ToolStrip toolStrip) { return false; } - private static bool ChangeSelection(ToolStrip start, ToolStrip toolStrip) { - if (toolStrip == null || start == null) { + private static bool ChangeSelection(ToolStrip start, ToolStrip toolStrip) + { + if (toolStrip == null || start == null) + { Debug.Assert(toolStrip != null, "passed in bogus toolstrip, why?"); Debug.Assert(start != null, "passed in bogus start, why?"); return false; } - if (start == toolStrip) { + if (start == toolStrip) + { return false; } - if (ModalMenuFilter.InMenuMode) { - if (ModalMenuFilter.GetActiveToolStrip() == start) { + if (ModalMenuFilter.InMenuMode) + { + if (ModalMenuFilter.GetActiveToolStrip() == start) + { ModalMenuFilter.RemoveActiveToolStrip(start); start.NotifySelectionChange(null); } ModalMenuFilter.SetActiveToolStrip(toolStrip); } - else { + else + { toolStrip.Focus(); } // copy over the hwnd that we want to restore focus to on ESC @@ -196,8 +232,10 @@ private static bool ChangeSelection(ToolStrip start, ToolStrip toolStrip) { return true; } - private static Delegate GetEventHandler(int key) { - lock (internalSyncObject) { + private static Delegate GetEventHandler(int key) + { + lock (internalSyncObject) + { if (staticEventHandlers == null) return null; else @@ -206,59 +244,75 @@ private static Delegate GetEventHandler(int key) { } - private static bool IsOnSameWindow(Control control1, Control control2) { + private static bool IsOnSameWindow(Control control1, Control control2) + { return (WindowsFormsUtils.GetRootHWnd(control1).Handle == WindowsFormsUtils.GetRootHWnd(control2).Handle); } - internal static bool IsThreadUsingToolStrips() { + internal static bool IsThreadUsingToolStrips() + { return (toolStripWeakArrayList != null && (toolStripWeakArrayList.Count > 0)); } - private static void OnUserPreferenceChanging(object sender, UserPreferenceChangingEventArgs e) { + private static void OnUserPreferenceChanging(object sender, UserPreferenceChangingEventArgs e) + { // using changing here so that the cache will be cleared by the time the ToolStrip // hooks onto the changed event. // SPI_SETNONCLIENTMETRICS is put up in WM_SETTINGCHANGE if the Menu font changes. // this corresponds to UserPreferenceCategory.Window. - if (e.Category == UserPreferenceCategory.Window) { - lock (internalSyncObject) { + if (e.Category == UserPreferenceCategory.Window) + { + lock (internalSyncObject) + { defaultFont = null; } } } - internal static void NotifyMenuModeChange(bool invalidateText, bool activationChange) { + internal static void NotifyMenuModeChange(bool invalidateText, bool activationChange) + { bool toolStripPruneNeeded = false; // If we've toggled the ShowUnderlines value, we'll need to invalidate - for (int i = 0; i < ToolStrips.Count; i++) { + for (int i = 0; i < ToolStrips.Count; i++) + { ToolStrip toolStrip = ToolStrips[i] as ToolStrip; - if (toolStrip == null) { + if (toolStrip == null) + { toolStripPruneNeeded = true; continue; } - if (invalidateText) { + if (invalidateText) + { toolStrip.InvalidateTextItems(); } - if (activationChange) { + if (activationChange) + { toolStrip.KeyboardActive = false; } } - if (toolStripPruneNeeded) { + if (toolStripPruneNeeded) + { PruneToolStripList(); } } /// removes dead entries from the toolstrip weak reference collection. - internal static void PruneToolStripList() { - if (toolStripWeakArrayList != null) { - if (toolStripWeakArrayList.Count > 0) { - for (int i = toolStripWeakArrayList.Count - 1; i >= 0; i--) { - if (toolStripWeakArrayList[i] == null) { + internal static void PruneToolStripList() + { + if (toolStripWeakArrayList != null) + { + if (toolStripWeakArrayList.Count > 0) + { + for (int i = toolStripWeakArrayList.Count - 1; i >= 0; i--) + { + if (toolStripWeakArrayList[i] == null) + { toolStripWeakArrayList.RemoveAt(i); } } @@ -267,9 +321,12 @@ internal static void PruneToolStripList() { } /// static events only!!! - private static void RemoveEventHandler(int key, Delegate value) { - lock (internalSyncObject) { - if (staticEventHandlers != null) { + private static void RemoveEventHandler(int key, Delegate value) + { + lock (internalSyncObject) + { + if (staticEventHandlers != null) + { staticEventHandlers[key] = Delegate.Remove(staticEventHandlers[key], value); } } @@ -278,9 +335,11 @@ private static void RemoveEventHandler(int key, Delegate value) { // this is a special version of SelectNextControl which looks for ToolStrips // that are TabStop = false in TabOrder. This is used from Control+Tab // handling to swap focus between ToolStrips. - internal static bool SelectNextToolStrip(ToolStrip start, bool forward) { + internal static bool SelectNextToolStrip(ToolStrip start, bool forward) + { - if (start == null || start.ParentInternal == null) { + if (start == null || start.ParentInternal == null) + { Debug.Assert(start != null, "why is null passed here?"); return false; } @@ -291,14 +350,16 @@ internal static bool SelectNextToolStrip(ToolStrip start, bool forward) { int startTabIndex = start.TabIndex; int index = ToolStrips.IndexOf(start); int totalCount = ToolStrips.Count; - for (int i = 0; i < totalCount; i++) { + for (int i = 0; i < totalCount; i++) + { index = (forward) ? (index + 1) % totalCount : (index + totalCount - 1) % totalCount; ToolStrip toolStrip = ToolStrips[index] as ToolStrip; if (toolStrip == null || - toolStrip == start) { + toolStrip == start) + { continue; } @@ -308,63 +369,77 @@ internal static bool SelectNextToolStrip(ToolStrip start, bool forward) { // defer the checking until we think we've got a viable TabIndex candidate. // this brings it to O(n+m) instead of O(n*m) where n is # toolstrips & m is avg number // items/toolstrip - if (forward) { - if (nextControlTabIndex >= startTabIndex && CanChangeSelection(start, toolStrip)) { + if (forward) + { + if (nextControlTabIndex >= startTabIndex && CanChangeSelection(start, toolStrip)) + { Debug.WriteLineIf(ToolStrip.ControlTabDebug.TraceVerbose, "FORWARD considering selection " + toolStrip.Name + " " + toolStrip.TabIndex.ToString(CultureInfo.CurrentCulture)); - if (nextControl == null) { + if (nextControl == null) + { nextControl = toolStrip; } - else if (toolStrip.TabIndex < nextControl.TabIndex) { + else if (toolStrip.TabIndex < nextControl.TabIndex) + { // we want to pick a larger index, but one that's // closest to the start tab index. nextControl = toolStrip; } } else if (((wrappedControl == null) || (toolStrip.TabIndex < wrappedControl.TabIndex)) - && CanChangeSelection(start, toolStrip)) { + && CanChangeSelection(start, toolStrip)) + { // we've found a candidate for wrapping (the one with the smallest tab index in the collection) Debug.WriteLineIf(ToolStrip.ControlTabDebug.TraceVerbose, "\tFORWARD new wrap candidate " + toolStrip.Name); wrappedControl = toolStrip; } } - else { - if (nextControlTabIndex <= startTabIndex && CanChangeSelection(start, toolStrip)) { + else + { + if (nextControlTabIndex <= startTabIndex && CanChangeSelection(start, toolStrip)) + { Debug.WriteLineIf(ToolStrip.ControlTabDebug.TraceVerbose, "\tREVERSE selecting " + toolStrip.Name); - if (nextControl == null) { + if (nextControl == null) + { nextControl = toolStrip; } - else if (toolStrip.TabIndex > nextControl.TabIndex) { + else if (toolStrip.TabIndex > nextControl.TabIndex) + { // we want to pick a smaller index, but one that's // closest to the start tab index. nextControl = toolStrip; } } else if (((wrappedControl == null) || (toolStrip.TabIndex > wrappedControl.TabIndex)) - && CanChangeSelection(start, toolStrip)) { + && CanChangeSelection(start, toolStrip)) + { // we've found a candidate for wrapping (the one with the largest tab index in the collection) Debug.WriteLineIf(ToolStrip.ControlTabDebug.TraceVerbose, "\tREVERSE new wrap candidate " + toolStrip.Name); wrappedControl = toolStrip; } - else { + else + { Debug.WriteLineIf(ToolStrip.ControlTabDebug.TraceVerbose, "\tREVERSE skipping wrap candidate " + toolStrip.Name + toolStrip.TabIndex.ToString(CultureInfo.CurrentCulture)); } } if (nextControl != null - && Math.Abs(nextControl.TabIndex - startTabIndex) <= 1) { + && Math.Abs(nextControl.TabIndex - startTabIndex) <= 1) + { // if we've found a valid candidate AND it's within 1 // then bail, we've found something close enough. break; } } - if (nextControl != null) { + if (nextControl != null) + { Debug.WriteLineIf(ToolStrip.ControlTabDebug.TraceVerbose, "SELECTING " + nextControl.Name); return ChangeSelection(start, nextControl); } - else if (wrappedControl != null) { + else if (wrappedControl != null) + { Debug.WriteLineIf(ToolStrip.ControlTabDebug.TraceVerbose, "WRAPPING " + wrappedControl.Name); return ChangeSelection(start, wrappedControl); @@ -399,18 +474,23 @@ internal static bool SelectNextToolStrip(ToolStrip start, bool forward) { [ThreadStatic] private static Type currentRendererType; - private static Type CurrentRendererType { - get { + private static Type CurrentRendererType + { + get + { InitalizeThread(); return currentRendererType; } - set { + set + { currentRendererType = value; } } - private static Type DefaultRendererType { - get { + private static Type DefaultRendererType + { + get + { return ProfessionalRendererType; } } @@ -420,23 +500,29 @@ private static Type DefaultRendererType { /// is the property used. /// - public static ToolStripRenderer Renderer { - get { - if (defaultRenderer == null) { + public static ToolStripRenderer Renderer + { + get + { + if (defaultRenderer == null) + { defaultRenderer = CreateRenderer(RenderMode); } return defaultRenderer; } - set { + set + { /// - if (defaultRenderer != value) { + if (defaultRenderer != value) + { CurrentRendererType = (value == null) ? DefaultRendererType : value.GetType(); defaultRenderer = value; EventHandler handler = (EventHandler)GetEventHandler(staticEventDefaultRendererChanged); - if (handler != null) { + if (handler != null) + { handler(null, EventArgs.Empty); } @@ -452,7 +538,8 @@ public static ToolStripRenderer Renderer { // // PM team has reviewed and decided on naming changes already [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] - public static event EventHandler RendererChanged { + public static event EventHandler RendererChanged + { add => AddEventHandler(staticEventDefaultRendererChanged, value); remove => RemoveEventHandler(staticEventDefaultRendererChanged, value); } @@ -460,32 +547,40 @@ public static event EventHandler RendererChanged { /// returns the default toolstrip RenderMode for the thread - public static ToolStripManagerRenderMode RenderMode { - get { + public static ToolStripManagerRenderMode RenderMode + { + get + { Type currentType = CurrentRendererType; - if (defaultRenderer != null && !defaultRenderer.IsAutoGenerated) { + if (defaultRenderer != null && !defaultRenderer.IsAutoGenerated) + { return ToolStripManagerRenderMode.Custom; } // check the type of the currently set renderer. // types are cached as this may be called frequently. - if (currentType == ProfessionalRendererType) { + if (currentType == ProfessionalRendererType) + { return ToolStripManagerRenderMode.Professional; } - if (currentType == SystemRendererType) { + if (currentType == SystemRendererType) + { return ToolStripManagerRenderMode.System; } return ToolStripManagerRenderMode.Custom; } - set { + set + { /// - if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripManagerRenderMode.Custom, (int)ToolStripManagerRenderMode.Professional)) { + if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripManagerRenderMode.Custom, (int)ToolStripManagerRenderMode.Professional)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripManagerRenderMode)); } - switch (value) { + switch (value) + { case ToolStripManagerRenderMode.System: case ToolStripManagerRenderMode.Professional: Renderer = CreateRenderer(value); @@ -500,26 +595,33 @@ public static ToolStripManagerRenderMode RenderMode { /// should use visual style information (theming) to render itself. /// potentially you could want a themed app but an unthemed toolstrip. (e.g. Whidbey VS). /// - public static bool VisualStylesEnabled { - get { + public static bool VisualStylesEnabled + { + get + { return visualStylesEnabledIfPossible && Application.RenderWithVisualStyles; } - set { + set + { bool oldVis = VisualStylesEnabled; visualStylesEnabledIfPossible = value; - if (oldVis != VisualStylesEnabled) { + if (oldVis != VisualStylesEnabled) + { EventHandler handler = (EventHandler)GetEventHandler(staticEventDefaultRendererChanged); - if (handler != null) { + if (handler != null) + { handler(null, EventArgs.Empty); } } } } - internal static ToolStripRenderer CreateRenderer(ToolStripManagerRenderMode renderMode) { - switch (renderMode) { + internal static ToolStripRenderer CreateRenderer(ToolStripManagerRenderMode renderMode) + { + switch (renderMode) + { case ToolStripManagerRenderMode.System: return new ToolStripSystemRenderer(/*isAutoGenerated=*/true); case ToolStripManagerRenderMode.Professional: @@ -529,8 +631,10 @@ internal static ToolStripRenderer CreateRenderer(ToolStripManagerRenderMode rend return new ToolStripSystemRenderer(/*isAutoGenerated=*/true); } } - internal static ToolStripRenderer CreateRenderer(ToolStripRenderMode renderMode) { - switch (renderMode) { + internal static ToolStripRenderer CreateRenderer(ToolStripRenderMode renderMode) + { + switch (renderMode) + { case ToolStripRenderMode.System: return new ToolStripSystemRenderer(/*isAutoGenerated=*/true); case ToolStripRenderMode.Professional: @@ -545,9 +649,12 @@ internal static ToolStripRenderer CreateRenderer(ToolStripRenderMode renderMode) #region ToolStripPanel - internal static ClientUtils.WeakRefCollection ToolStripPanels { - get { - if (toolStripPanelWeakArrayList == null) { + internal static ClientUtils.WeakRefCollection ToolStripPanels + { + get + { + if (toolStripPanelWeakArrayList == null) + { toolStripPanelWeakArrayList = new ClientUtils.WeakRefCollection(); } return toolStripPanelWeakArrayList; @@ -555,26 +662,33 @@ internal static ClientUtils.WeakRefCollection ToolStripPanels { } - internal static ToolStripPanel ToolStripPanelFromPoint(Control draggedControl, Point screenLocation) { + internal static ToolStripPanel ToolStripPanelFromPoint(Control draggedControl, Point screenLocation) + { - if (toolStripPanelWeakArrayList != null) { + if (toolStripPanelWeakArrayList != null) + { ISupportToolStripPanel draggedItem = draggedControl as ISupportToolStripPanel; bool rootWindowCheck = draggedItem.IsCurrentlyDragging; - for (int i = 0; i < toolStripPanelWeakArrayList.Count; i++) { + for (int i = 0; i < toolStripPanelWeakArrayList.Count; i++) + { ToolStripPanel toolStripPanel = toolStripPanelWeakArrayList[i] as ToolStripPanel; if (toolStripPanel != null && toolStripPanel.IsHandleCreated && toolStripPanel.Visible && - toolStripPanel.DragBounds.Contains(toolStripPanel.PointToClient(screenLocation))) { + toolStripPanel.DragBounds.Contains(toolStripPanel.PointToClient(screenLocation))) + { // Ensure that we cant drag off one window to another. - if (rootWindowCheck) { - if (IsOnSameWindow(draggedControl, toolStripPanel)) { + if (rootWindowCheck) + { + if (IsOnSameWindow(draggedControl, toolStripPanel)) + { return toolStripPanel; } } - else { + else + { return toolStripPanel; } } @@ -592,8 +706,10 @@ internal static ToolStripPanel ToolStripPanelFromPoint(Control draggedControl, P /// /// Loads settings for the given Form using the form type's fullname as settings key. /// - public static void LoadSettings(Form targetForm) { - if (targetForm == null) { + public static void LoadSettings(Form targetForm) + { + if (targetForm == null) + { throw new ArgumentNullException(nameof(targetForm)); } @@ -603,12 +719,15 @@ public static void LoadSettings(Form targetForm) { /// /// Loads settings for the given Form with the given settings key. /// - public static void LoadSettings(Form targetForm, string key) { - if (targetForm == null) { + public static void LoadSettings(Form targetForm, string key) + { + if (targetForm == null) + { throw new ArgumentNullException(nameof(targetForm)); } - if (string.IsNullOrEmpty(key)) { + if (string.IsNullOrEmpty(key)) + { throw new ArgumentNullException(nameof(key)); } @@ -620,8 +739,10 @@ public static void LoadSettings(Form targetForm, string key) { /// /// Saves settings for the given form using the form type's fullname as settings key. /// - public static void SaveSettings(Form sourceForm) { - if (sourceForm == null) { + public static void SaveSettings(Form sourceForm) + { + if (sourceForm == null) + { throw new ArgumentNullException(nameof(sourceForm)); } @@ -631,16 +752,20 @@ public static void SaveSettings(Form sourceForm) { /// /// Saves settings for the given form with the given settings key. /// - public static void SaveSettings(Form sourceForm, string key) { - if (sourceForm == null) { + public static void SaveSettings(Form sourceForm, string key) + { + if (sourceForm == null) + { throw new ArgumentNullException(nameof(sourceForm)); } - if (string.IsNullOrEmpty(key)) { + if (string.IsNullOrEmpty(key)) + { throw new ArgumentNullException(nameof(key)); } - ToolStripSettingsManager settingsManager = new ToolStripSettingsManager(sourceForm, key); ; + ToolStripSettingsManager settingsManager = new ToolStripSettingsManager(sourceForm, key); + ; settingsManager.Save(); } @@ -668,7 +793,8 @@ public static void SaveSettings(Form sourceForm, string key) { /// the last dropdown has gone away /// This is not part of ToolStripManager because it's DropDown specific and /// we dont want to publicly expose this message filter. - internal class ModalMenuFilter : IMessageModifyAndFilter { + internal class ModalMenuFilter : IMessageModifyAndFilter + { private HandleRef _activeHwnd = NativeMethods.NullHandleRef; // the window that was active when we showed the dropdown private HandleRef _lastActiveWindow = NativeMethods.NullHandleRef; // the window that was last known to be active private List _inputFilterQueue; @@ -691,48 +817,63 @@ internal class ModalMenuFilter : IMessageModifyAndFilter { [ThreadStatic] private static ModalMenuFilter _instance; - internal static ModalMenuFilter Instance { - get { - if (_instance == null) { + internal static ModalMenuFilter Instance + { + get + { + if (_instance == null) + { _instance = new ModalMenuFilter(); } return _instance; } } - private ModalMenuFilter() { + private ModalMenuFilter() + { } /// this is the HWnd that was active when we popped the first dropdown. - internal static HandleRef ActiveHwnd { + internal static HandleRef ActiveHwnd + { get { return Instance.ActiveHwndInternal; } } // returns whether or not we should show focus cues for mnemonics. - public bool ShowUnderlines { - get { + public bool ShowUnderlines + { + get + { return _showUnderlines; } - set { - if (_showUnderlines != value) { + set + { + if (_showUnderlines != value) + { _showUnderlines = value; ToolStripManager.NotifyMenuModeChange(/*textStyleChanged*/true, /*activationChanged*/false); } } } - private HandleRef ActiveHwndInternal { - get { + private HandleRef ActiveHwndInternal + { + get + { return _activeHwnd; } - set { - if (_activeHwnd.Handle != value.Handle) { + set + { + if (_activeHwnd.Handle != value.Handle) + { Control control = null; // unsubscribe from handle recreate. - if (_activeHwnd.Handle != IntPtr.Zero) { + if (_activeHwnd.Handle != IntPtr.Zero) + { control = Control.FromHandle(_activeHwnd.Handle); - if (control != null) { + if (control != null) + { control.HandleCreated -= new EventHandler(OnActiveHwndHandleCreated); } } @@ -741,7 +882,8 @@ private HandleRef ActiveHwndInternal { // make sure we watch out for handle recreates. control = Control.FromHandle(_activeHwnd.Handle); - if (control != null) { + if (control != null) + { control.HandleCreated += new EventHandler(OnActiveHwndHandleCreated); } } @@ -750,17 +892,22 @@ private HandleRef ActiveHwndInternal { } // returns whether or not someone has called EnterMenuMode. - internal static bool InMenuMode { + internal static bool InMenuMode + { get { return Instance._inMenuMode; } } - internal static bool MenuKeyToggle { - get { + internal static bool MenuKeyToggle + { + get + { return Instance.menuKeyToggle; } - set { - if (Instance.menuKeyToggle != value) { + set + { + if (Instance.menuKeyToggle != value) + { Instance.menuKeyToggle = value; } @@ -770,9 +917,12 @@ internal static bool MenuKeyToggle { /// This is used in scenarios where windows forms /// does not own the message pump, but needs access /// to the message queue. - private HostedWindowsFormsMessageHook MessageHook { - get { - if (messageHook == null) { + private HostedWindowsFormsMessageHook MessageHook + { + get + { + if (messageHook == null) + { messageHook = new HostedWindowsFormsMessageHook(); } return messageHook; @@ -780,16 +930,19 @@ private HostedWindowsFormsMessageHook MessageHook { } // ToolStrip analog to WM_ENTERMENULOOP - private void EnterMenuModeCore() { + private void EnterMenuModeCore() + { Debug.Assert(!InMenuMode, "How did we get here if we're already in menu mode?"); - if (!InMenuMode) { + if (!InMenuMode) + { Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "___________Entering MenuMode...."); #if DEBUG _justEnteredMenuMode = true; #endif IntPtr hwndActive = UnsafeNativeMethods.GetActiveWindow(); - if (hwndActive != IntPtr.Zero) { + if (hwndActive != IntPtr.Zero) + { ActiveHwndInternal = new HandleRef(this, hwndActive); } @@ -798,7 +951,8 @@ private void EnterMenuModeCore() { Application.ThreadContext.FromCurrent().AddMessageFilter(this); Application.ThreadContext.FromCurrent().TrackInput(true); - if (!Application.ThreadContext.FromCurrent().GetMessageLoop(true)) { + if (!Application.ThreadContext.FromCurrent().GetMessageLoop(true)) + { // message filter isnt going to help as we dont own the message pump // switch over to a MessageHook MessageHook.HookMessages = true; @@ -813,29 +967,36 @@ private void EnterMenuModeCore() { } - internal void NotifyLastLastFocusedToolAboutFocusLoss() { + internal void NotifyLastLastFocusedToolAboutFocusLoss() + { IKeyboardToolTip lastFocusedTool = KeyboardToolTipStateMachine.Instance.LastFocusedTool; - if (lastFocusedTool != null) { + if (lastFocusedTool != null) + { this.lastFocusedTool.SetTarget(lastFocusedTool); KeyboardToolTipStateMachine.Instance.NotifyAboutLostFocus(lastFocusedTool); } } - internal static void ExitMenuMode() { + internal static void ExitMenuMode() + { Instance.ExitMenuModeCore(); } // ToolStrip analog to WM_EXITMENULOOP - private void ExitMenuModeCore() { - + private void ExitMenuModeCore() + { + // ensure we've cleaned up the timer. ProcessMessages(false); - if (InMenuMode) { - try { + if (InMenuMode) + { + try + { Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "___________Exiting MenuMode...."); - if (messageHook != null) { + if (messageHook != null) + { // message filter isnt going to help as we dont own the message pump // switch over to a MessageHook messageHook.HookMessages = false; @@ -848,28 +1009,34 @@ private void ExitMenuModeCore() { #if DEBUG _justEnteredMenuMode = false; #endif - if (ActiveHwnd.Handle != IntPtr.Zero) { + if (ActiveHwnd.Handle != IntPtr.Zero) + { // unsubscribe from handle creates Control control = Control.FromHandle(ActiveHwnd.Handle); - if (control != null) { + if (control != null) + { control.HandleCreated -= new EventHandler(OnActiveHwndHandleCreated); } ActiveHwndInternal = NativeMethods.NullHandleRef; } - if (_inputFilterQueue != null) { + if (_inputFilterQueue != null) + { _inputFilterQueue.Clear(); } - if (_caretHidden) { + if (_caretHidden) + { _caretHidden = false; SafeNativeMethods.ShowCaret(NativeMethods.NullHandleRef); } IKeyboardToolTip tool; - if(this.lastFocusedTool.TryGetTarget(out tool) && tool != null) { + if (this.lastFocusedTool.TryGetTarget(out tool) && tool != null) + { KeyboardToolTipStateMachine.Instance.NotifyAboutGotFocus(tool); } } - finally { + finally + { _inMenuMode = false; // skip the setter here so we only iterate through the toolstrips once. @@ -884,23 +1051,29 @@ private void ExitMenuModeCore() { - internal static ToolStrip GetActiveToolStrip() { + internal static ToolStrip GetActiveToolStrip() + { return Instance.GetActiveToolStripInternal(); } - internal ToolStrip GetActiveToolStripInternal() { - if (_inputFilterQueue != null && _inputFilterQueue.Count > 0) { + internal ToolStrip GetActiveToolStripInternal() + { + if (_inputFilterQueue != null && _inputFilterQueue.Count > 0) + { return _inputFilterQueue[_inputFilterQueue.Count - 1]; } return null; } // return the toolstrip that is at the root. - private ToolStrip GetCurrentToplevelToolStrip() { - if (_toplevelToolStrip == null) { + private ToolStrip GetCurrentToplevelToolStrip() + { + if (_toplevelToolStrip == null) + { ToolStrip activeToolStrip = GetActiveToolStripInternal(); - if (activeToolStrip != null) { + if (activeToolStrip != null) + { _toplevelToolStrip = activeToolStrip.GetToplevelOwnerToolStrip(); } } @@ -908,15 +1081,18 @@ private ToolStrip GetCurrentToplevelToolStrip() { } - private void OnActiveHwndHandleCreated(object sender, EventArgs e) { + private void OnActiveHwndHandleCreated(object sender, EventArgs e) + { Control topLevel = sender as Control; ActiveHwndInternal = new HandleRef(this, topLevel.Handle); } - internal static void ProcessMenuKeyDown(ref Message m) { + internal static void ProcessMenuKeyDown(ref Message m) + { Keys keyData = (Keys)(int)m.WParam; ToolStrip toolStrip = Control.FromHandle(m.HWnd) as ToolStrip; - if (toolStrip != null && !toolStrip.IsDropDown) { + if (toolStrip != null && !toolStrip.IsDropDown) + { return; } @@ -924,29 +1100,35 @@ internal static void ProcessMenuKeyDown(ref Message m) { // was open. We need to clear off the MenuKeyToggle so the next ALT will activate // the menu. - if (ToolStripManager.IsMenuKey(keyData)) { - if (!InMenuMode && MenuKeyToggle) { + if (ToolStripManager.IsMenuKey(keyData)) + { + if (!InMenuMode && MenuKeyToggle) + { MenuKeyToggle = false; } - else if (!MenuKeyToggle) { + else if (!MenuKeyToggle) + { ModalMenuFilter.Instance.ShowUnderlines = true; } } } - internal static void CloseActiveDropDown(ToolStripDropDown activeToolStripDropDown, ToolStripDropDownCloseReason reason) { + internal static void CloseActiveDropDown(ToolStripDropDown activeToolStripDropDown, ToolStripDropDownCloseReason reason) + { activeToolStripDropDown.SetCloseReason(reason); activeToolStripDropDown.Visible = false; // there's no more dropdowns left in the chain - if (GetActiveToolStrip() == null) { + if (GetActiveToolStrip() == null) + { Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[ModalMenuFilter.CloseActiveDropDown] Calling exit because there are no more dropdowns left to activate."); ExitMenuMode(); // make sure we roll selection off the toplevel toolstrip. - if (activeToolStripDropDown.OwnerItem != null) { + if (activeToolStripDropDown.OwnerItem != null) + { activeToolStripDropDown.OwnerItem.Unselect(); } } @@ -954,48 +1136,59 @@ internal static void CloseActiveDropDown(ToolStripDropDown activeToolStripDropDo } // fire a timer event to ensure we have a message in the queue every 500ms - private void ProcessMessages(bool process) { - if (process) { - if (_ensureMessageProcessingTimer == null) { + private void ProcessMessages(bool process) + { + if (process) + { + if (_ensureMessageProcessingTimer == null) + { _ensureMessageProcessingTimer = new System.Windows.Forms.Timer(); } _ensureMessageProcessingTimer.Interval = MESSAGE_PROCESSING_INTERVAL; _ensureMessageProcessingTimer.Enabled = true; } - else if (_ensureMessageProcessingTimer != null) { + else if (_ensureMessageProcessingTimer != null) + { _ensureMessageProcessingTimer.Enabled = false; _ensureMessageProcessingTimer.Dispose(); _ensureMessageProcessingTimer = null; } } - - private void ProcessMouseButtonPressed(IntPtr hwndMouseMessageIsFrom, int x, int y) { + + private void ProcessMouseButtonPressed(IntPtr hwndMouseMessageIsFrom, int x, int y) + { Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[ModalMenuFilter.ProcessMouseButtonPressed] Found a mouse down."); int countDropDowns = _inputFilterQueue.Count; - for (int i = 0; i < countDropDowns; i++) { + for (int i = 0; i < countDropDowns; i++) + { ToolStrip activeToolStrip = GetActiveToolStripInternal(); - if (activeToolStrip != null) { + if (activeToolStrip != null) + { NativeMethods.POINT pt = new NativeMethods.POINT(); pt.x = x; pt.y = y; UnsafeNativeMethods.MapWindowPoints(new HandleRef(activeToolStrip, hwndMouseMessageIsFrom), new HandleRef(activeToolStrip, activeToolStrip.Handle), pt, 1); - if (!activeToolStrip.ClientRectangle.Contains(pt.x, pt.y)) { + if (!activeToolStrip.ClientRectangle.Contains(pt.x, pt.y)) + { ToolStripDropDown activeToolStripDropDown = activeToolStrip as ToolStripDropDown; - if (activeToolStripDropDown != null) { + if (activeToolStripDropDown != null) + { if (!(activeToolStripDropDown.OwnerToolStrip != null && activeToolStripDropDown.OwnerToolStrip.Handle == hwndMouseMessageIsFrom && activeToolStripDropDown.OwnerDropDownItem != null - && activeToolStripDropDown.OwnerDropDownItem.DropDownButtonArea.Contains(x, y))) { + && activeToolStripDropDown.OwnerDropDownItem.DropDownButtonArea.Contains(x, y))) + { // the owner item should handle closing the dropdown // this allows code such as if (DropDown.Visible) { Hide, Show } etc. CloseActiveDropDown(activeToolStripDropDown, ToolStripDropDownCloseReason.AppClicked); } } - else { + else + { // make sure we clear the selection. activeToolStrip.NotifySelectionChange(/*selectedItem=*/null); // we're a toplevel toolstrip and we've clicked somewhere else. @@ -1004,23 +1197,28 @@ private void ProcessMouseButtonPressed(IntPtr hwndMouseMessageIsFrom, int x, int ExitMenuModeCore(); } } - else { + else + { // we've found a dropdown that intersects with the mouse message break; } } - else { + else + { Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[ModalMenuFilter.ProcessMouseButtonPressed] active toolstrip is null."); break; } } } - private bool ProcessActivationChange() { + private bool ProcessActivationChange() + { int countDropDowns = _inputFilterQueue.Count; - for (int i = 0; i < countDropDowns; i++) { + for (int i = 0; i < countDropDowns; i++) + { ToolStripDropDown activeDropDown = this.GetActiveToolStripInternal() as ToolStripDropDown; - if (activeDropDown != null && activeDropDown.AutoClose) { + if (activeDropDown != null && activeDropDown.AutoClose) + { activeDropDown.Visible = false; } } @@ -1032,31 +1230,39 @@ private bool ProcessActivationChange() { } - internal static void SetActiveToolStrip(ToolStrip toolStrip, bool menuKeyPressed) { - if (!InMenuMode && menuKeyPressed) { + internal static void SetActiveToolStrip(ToolStrip toolStrip, bool menuKeyPressed) + { + if (!InMenuMode && menuKeyPressed) + { Instance.ShowUnderlines = true; } Instance.SetActiveToolStripCore(toolStrip); } - internal static void SetActiveToolStrip(ToolStrip toolStrip) { + internal static void SetActiveToolStrip(ToolStrip toolStrip) + { Instance.SetActiveToolStripCore(toolStrip); } - private void SetActiveToolStripCore(ToolStrip toolStrip) { + private void SetActiveToolStripCore(ToolStrip toolStrip) + { - if (toolStrip == null) { + if (toolStrip == null) + { return; } - if (toolStrip.IsDropDown) { + if (toolStrip.IsDropDown) + { // for something that never closes, dont use menu mode. ToolStripDropDown dropDown = toolStrip as ToolStripDropDown; - - if (dropDown.AutoClose == false) { + + if (dropDown.AutoClose == false) + { // store off the current active hwnd IntPtr hwndActive = UnsafeNativeMethods.GetActiveWindow(); - if (hwndActive != IntPtr.Zero) { + if (hwndActive != IntPtr.Zero) + { ActiveHwndInternal = new HandleRef(this, hwndActive); } // dont actually enter menu mode... @@ -1066,22 +1272,27 @@ private void SetActiveToolStripCore(ToolStrip toolStrip) { toolStrip.KeyboardActive = true; - if (_inputFilterQueue == null) { + if (_inputFilterQueue == null) + { // use list because we want to be able to remove at any point _inputFilterQueue = new List(); } - else { + else + { ToolStrip currentActiveToolStrip = GetActiveToolStripInternal(); // toolstrip dropdowns push/pull their activation based on visibility. // we have to account for the toolstrips that arent dropdowns - if (currentActiveToolStrip != null) { - if (!currentActiveToolStrip.IsDropDown) { + if (currentActiveToolStrip != null) + { + if (!currentActiveToolStrip.IsDropDown) + { _inputFilterQueue.Remove(currentActiveToolStrip); } else if ((toolStrip.IsDropDown) && (ToolStripDropDown.GetFirstDropDown(toolStrip) - != ToolStripDropDown.GetFirstDropDown(currentActiveToolStrip))) { + != ToolStripDropDown.GetFirstDropDown(currentActiveToolStrip))) + { Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[ModalMenuFilter.SetActiveToolStripCore] Detected a new dropdown not in this chain opened, Dismissing everything in the old chain. "); _inputFilterQueue.Remove(currentActiveToolStrip); @@ -1097,62 +1308,76 @@ private void SetActiveToolStripCore(ToolStrip toolStrip) { if (!_inputFilterQueue.Contains(toolStrip)) _inputFilterQueue.Add(toolStrip); - if (!InMenuMode && _inputFilterQueue.Count > 0) { + if (!InMenuMode && _inputFilterQueue.Count > 0) + { Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[ModalMenuFilter.SetActiveToolStripCore] Setting " + WindowsFormsUtils.GetControlInformation(toolStrip.Handle) + " active."); EnterMenuModeCore(); } // hide the caret if we're showing a toolstrip dropdown - if (!_caretHidden && toolStrip.IsDropDown && InMenuMode) { + if (!_caretHidden && toolStrip.IsDropDown && InMenuMode) + { _caretHidden = true; SafeNativeMethods.HideCaret(NativeMethods.NullHandleRef); } } - internal static void SuspendMenuMode() { + internal static void SuspendMenuMode() + { Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[ModalMenuFilter] SuspendMenuMode"); Instance._suspendMenuMode = true; } - internal static void ResumeMenuMode() { + internal static void ResumeMenuMode() + { Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[ModalMenuFilter] ResumeMenuMode"); Instance._suspendMenuMode = false; } - internal static void RemoveActiveToolStrip(ToolStrip toolStrip) { + internal static void RemoveActiveToolStrip(ToolStrip toolStrip) + { Instance.RemoveActiveToolStripCore(toolStrip); } - private void RemoveActiveToolStripCore(ToolStrip toolStrip) { + private void RemoveActiveToolStripCore(ToolStrip toolStrip) + { // precautionary - remove the active toplevel toolstrip. _toplevelToolStrip = null; - if (_inputFilterQueue != null) { + if (_inputFilterQueue != null) + { _inputFilterQueue.Remove(toolStrip); } } - private static bool IsChildOrSameWindow(HandleRef hwndParent, HandleRef hwndChild) { - if (hwndParent.Handle == hwndChild.Handle) { + private static bool IsChildOrSameWindow(HandleRef hwndParent, HandleRef hwndChild) + { + if (hwndParent.Handle == hwndChild.Handle) + { return true; } - if (UnsafeNativeMethods.IsChild(hwndParent, hwndChild)) { + if (UnsafeNativeMethods.IsChild(hwndParent, hwndChild)) + { return true; } return false; } - private static bool IsKeyOrMouseMessage(Message m) { + private static bool IsKeyOrMouseMessage(Message m) + { bool filterMessage = false; - if (m.Msg >= Interop.WindowMessages.WM_MOUSEFIRST && m.Msg <= Interop.WindowMessages.WM_MOUSELAST) { + if (m.Msg >= Interop.WindowMessages.WM_MOUSEFIRST && m.Msg <= Interop.WindowMessages.WM_MOUSELAST) + { filterMessage = true; } - else if (m.Msg >= Interop.WindowMessages.WM_NCLBUTTONDOWN && m.Msg <= Interop.WindowMessages.WM_NCMBUTTONDBLCLK) { + else if (m.Msg >= Interop.WindowMessages.WM_NCLBUTTONDOWN && m.Msg <= Interop.WindowMessages.WM_NCMBUTTONDBLCLK) + { filterMessage = true; } - else if (m.Msg >= Interop.WindowMessages.WM_KEYFIRST && m.Msg <= Interop.WindowMessages.WM_KEYLAST) { + else if (m.Msg >= Interop.WindowMessages.WM_KEYFIRST && m.Msg <= Interop.WindowMessages.WM_KEYLAST) + { filterMessage = true; } return filterMessage; @@ -1160,20 +1385,24 @@ private static bool IsKeyOrMouseMessage(Message m) { - public bool PreFilterMessage(ref Message m) { + public bool PreFilterMessage(ref Message m) + { #if DEBUG Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose && _justEnteredMenuMode, "[ModalMenuFilter.PreFilterMessage] MenuMode MessageFilter installed and working."); _justEnteredMenuMode = false; #endif - if (_suspendMenuMode) { + if (_suspendMenuMode) + { return false; } ToolStrip activeToolStrip = GetActiveToolStrip(); - if (activeToolStrip == null) { + if (activeToolStrip == null) + { return false; } - if (activeToolStrip.IsDisposed) { + if (activeToolStrip.IsDisposed) + { RemoveActiveToolStripCore(activeToolStrip); return false; } @@ -1181,16 +1410,19 @@ public bool PreFilterMessage(ref Message m) { HandleRef hwndCurrentActiveWindow = new HandleRef(null, UnsafeNativeMethods.GetActiveWindow()); // if the active window has changed... - if (hwndCurrentActiveWindow.Handle != _lastActiveWindow.Handle) { + if (hwndCurrentActiveWindow.Handle != _lastActiveWindow.Handle) + { // if another window has gotten activation - we should dismiss. - if (hwndCurrentActiveWindow.Handle == IntPtr.Zero) { + if (hwndCurrentActiveWindow.Handle == IntPtr.Zero) + { // we dont know what it was cause it's on another thread or doesnt exist Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[ModalMenuFilter.PreFilterMessage] Dismissing because: " + WindowsFormsUtils.GetControlInformation(hwndCurrentActiveWindow.Handle) + " has gotten activation. "); ProcessActivationChange(); } else if (!(Control.FromChildHandle(hwndCurrentActiveWindow.Handle) is ToolStripDropDown) // its NOT a dropdown && !IsChildOrSameWindow(hwndCurrentActiveWindow, hwndActiveToolStrip) // and NOT a child of the active toolstrip - && !IsChildOrSameWindow(hwndCurrentActiveWindow, ActiveHwnd)) { // and NOT a child of the active hwnd + && !IsChildOrSameWindow(hwndCurrentActiveWindow, ActiveHwnd)) + { // and NOT a child of the active hwnd Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[ModalMenuFilter.PreFilterMessage] Calling ProcessActivationChange because: " + WindowsFormsUtils.GetControlInformation(hwndCurrentActiveWindow.Handle) + " has gotten activation. "); ProcessActivationChange(); } @@ -1200,11 +1432,13 @@ public bool PreFilterMessage(ref Message m) { _lastActiveWindow = hwndCurrentActiveWindow; // PERF: skip over things like PAINT... - if (!IsKeyOrMouseMessage(m)) { + if (!IsKeyOrMouseMessage(m)) + { return false; } - switch (m.Msg) { + switch (m.Msg) + { case Interop.WindowMessages.WM_MOUSEMOVE: case Interop.WindowMessages.WM_NCMOUSEMOVE: @@ -1212,16 +1446,19 @@ public bool PreFilterMessage(ref Message m) { // this prevents things like ToolTips and mouse over highlights from // being processed. Control control = Control.FromChildHandle(m.HWnd); - if (control == null || !(control.TopLevelControlInternal is ToolStripDropDown)) { + if (control == null || !(control.TopLevelControlInternal is ToolStripDropDown)) + { // double check it's not a child control of the active toolstrip. - if (!IsChildOrSameWindow(hwndActiveToolStrip, new HandleRef(null, m.HWnd))) { + if (!IsChildOrSameWindow(hwndActiveToolStrip, new HandleRef(null, m.HWnd))) + { // it is NOT a child of the current active toolstrip. ToolStrip toplevelToolStrip = GetCurrentToplevelToolStrip(); if (toplevelToolStrip != null && (IsChildOrSameWindow(new HandleRef(toplevelToolStrip, toplevelToolStrip.Handle), - new HandleRef(null, m.HWnd)))) { + new HandleRef(null, m.HWnd)))) + { // DONT EAT mouse message. // The mouse message is from an HWND that is part of the toplevel toolstrip - let the mosue move through so // when you have something like the file menu open and mouse over the edit menu @@ -1229,7 +1466,8 @@ public bool PreFilterMessage(ref Message m) { return false; } - else if (!IsChildOrSameWindow(ActiveHwnd, new HandleRef(null, m.HWnd))) { + else if (!IsChildOrSameWindow(ActiveHwnd, new HandleRef(null, m.HWnd))) + { // DONT EAT mouse message. // the mouse message is from another toplevel HWND. return false; @@ -1276,13 +1514,15 @@ public bool PreFilterMessage(ref Message m) { case Interop.WindowMessages.WM_SYSCHAR: case Interop.WindowMessages.WM_SYSDEADCHAR: - if (!activeToolStrip.ContainsFocus) { + if (!activeToolStrip.ContainsFocus) + { Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[ModalMenuFilter.PreFilterMessage] MODIFYING Keyboard message " + m.ToString()); // route all keyboard messages to the active dropdown. m.HWnd = activeToolStrip.Handle; } - else { + else + { Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[ModalMenuFilter.PreFilterMessage] got Keyboard message " + m.ToString()); } break; @@ -1293,48 +1533,61 @@ public bool PreFilterMessage(ref Message m) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable")] // since this has the lifetime of the thread, theres no great way to dispose. - private class HostedWindowsFormsMessageHook { + private class HostedWindowsFormsMessageHook + { [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr messageHookHandle = IntPtr.Zero; private bool isHooked = false; private NativeMethods.HookProc hookProc; - public HostedWindowsFormsMessageHook() { + public HostedWindowsFormsMessageHook() + { #if DEBUG - try { - callingStack = Environment.StackTrace; - } - catch (System.Security.SecurityException) { - } + try + { + callingStack = Environment.StackTrace; + } + catch (System.Security.SecurityException) + { + } #endif } #if DEBUG - string callingStack; - ~HostedWindowsFormsMessageHook() { - Debug.Assert(messageHookHandle == IntPtr.Zero, "Finalizing an active mouse hook. This will crash the process. Calling stack: " + callingStack); - } + string callingStack; + ~HostedWindowsFormsMessageHook() + { + Debug.Assert(messageHookHandle == IntPtr.Zero, "Finalizing an active mouse hook. This will crash the process. Calling stack: " + callingStack); + } #endif - public bool HookMessages { + public bool HookMessages + { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { + get + { return messageHookHandle != IntPtr.Zero; } - set { - if (value) { + set + { + if (value) + { InstallMessageHook(); } - else { + else + { UninstallMessageHook(); } } } - private void InstallMessageHook() { - lock (this) { - if (messageHookHandle != IntPtr.Zero) { + private void InstallMessageHook() + { + lock (this) + { + if (messageHookHandle != IntPtr.Zero) + { return; } @@ -1345,23 +1598,29 @@ private void InstallMessageHook() { new HandleRef(null, IntPtr.Zero), SafeNativeMethods.GetCurrentThreadId()); - if (messageHookHandle != IntPtr.Zero) { + if (messageHookHandle != IntPtr.Zero) + { isHooked = true; } Debug.Assert(messageHookHandle != IntPtr.Zero, "Failed to install mouse hook"); } } - private unsafe IntPtr MessageHookProc(int nCode, IntPtr wparam, IntPtr lparam) { - if (nCode == NativeMethods.HC_ACTION) { - if (isHooked && (int)wparam == NativeMethods.PM_REMOVE /*only process GetMessage, not PeekMessage*/) { + private unsafe IntPtr MessageHookProc(int nCode, IntPtr wparam, IntPtr lparam) + { + if (nCode == NativeMethods.HC_ACTION) + { + if (isHooked && (int)wparam == NativeMethods.PM_REMOVE /*only process GetMessage, not PeekMessage*/) + { // only process messages we've pulled off the queue NativeMethods.MSG* msg = (NativeMethods.MSG*)lparam; - if (msg != null) { + if (msg != null) + { //Debug.WriteLine("Got " + Message.Create(msg->hwnd, msg->message, wparam, lparam).ToString()); // call pretranslate on the message - this should execute // the message filters and preprocess message. - if (Application.ThreadContext.FromCurrent().PreTranslateMessage(ref *msg)) { + if (Application.ThreadContext.FromCurrent().PreTranslateMessage(ref *msg)) + { msg->message = Interop.WindowMessages.WM_NULL; } } @@ -1371,9 +1630,12 @@ private unsafe IntPtr MessageHookProc(int nCode, IntPtr wparam, IntPtr lparam) { return UnsafeNativeMethods.CallNextHookEx(new HandleRef(this, messageHookHandle), nCode, wparam, lparam); } - private void UninstallMessageHook() { - lock (this) { - if (messageHookHandle != IntPtr.Zero) { + private void UninstallMessageHook() + { + lock (this) + { + if (messageHookHandle != IntPtr.Zero) + { UnsafeNativeMethods.UnhookWindowsHookEx(new HandleRef(this, messageHookHandle)); hookProc = null; messageHookHandle = IntPtr.Zero; @@ -1390,9 +1652,12 @@ private void UninstallMessageHook() { - internal static bool ShowMenuFocusCues { - get { - if (!DisplayInformation.MenuAccessKeysUnderlined) { + internal static bool ShowMenuFocusCues + { + get + { + if (!DisplayInformation.MenuAccessKeysUnderlined) + { return ModalMenuFilter.Instance.ShowUnderlines; } return true; @@ -1403,31 +1668,38 @@ internal static bool ShowMenuFocusCues { /// determines if the key combination is valid for a shortcut. /// must have a modifier key + a regular key. /// - public static bool IsValidShortcut(Keys shortcut) { + public static bool IsValidShortcut(Keys shortcut) + { // should have a key and one or more modifiers. Keys keyCode = (Keys)(shortcut & Keys.KeyCode); Keys modifiers = (Keys)(shortcut & Keys.Modifiers); - if (shortcut == Keys.None) { + if (shortcut == Keys.None) + { return false; } - else if ((keyCode == Keys.Delete) || (keyCode == Keys.Insert)) { + else if ((keyCode == Keys.Delete) || (keyCode == Keys.Insert)) + { return true; } - else if (((int)keyCode >= (int)Keys.F1) && ((int)keyCode <= (int)Keys.F24)) { + else if (((int)keyCode >= (int)Keys.F1) && ((int)keyCode <= (int)Keys.F24)) + { // function keys by themselves are valid return true; } - else if ((keyCode != Keys.None) && (modifiers != Keys.None)) { - switch (keyCode) { + else if ((keyCode != Keys.None) && (modifiers != Keys.None)) + { + switch (keyCode) + { case Keys.Menu: case Keys.ControlKey: case Keys.ShiftKey: // shift, control and alt arent valid on their own. return false; default: - if (modifiers == Keys.Shift) { + if (modifiers == Keys.Shift) + { // shift + somekey isnt a valid modifier either return false; } @@ -1438,15 +1710,19 @@ public static bool IsValidShortcut(Keys shortcut) { return false; } - internal static bool IsMenuKey(Keys keyData) { + internal static bool IsMenuKey(Keys keyData) + { Keys keyCode = keyData & Keys.KeyCode; return (Keys.Menu == keyCode || Keys.F10 == keyCode); } - public static bool IsShortcutDefined(Keys shortcut) { - for (int i = 0; i < ToolStrips.Count; i++) { + public static bool IsShortcutDefined(Keys shortcut) + { + for (int i = 0; i < ToolStrips.Count; i++) + { ToolStrip t = ToolStrips[i] as ToolStrip; - if ((t != null) && t.Shortcuts.Contains(shortcut)) { + if ((t != null) && t.Shortcuts.Contains(shortcut)) + { return true; } } @@ -1457,10 +1733,12 @@ public static bool IsShortcutDefined(Keys shortcut) { /// this function is called for toplevel controls to process shortcuts. /// this function should be called from the topmost container control only. /// - internal static bool ProcessCmdKey(ref Message m, Keys keyData) { + internal static bool ProcessCmdKey(ref Message m, Keys keyData) + { Debug.WriteLineIf(Control.ControlKeyboardRouting.TraceVerbose, "ToolStripManager.ProcessCmdKey - processing: [" + keyData.ToString() + "]"); - if (ToolStripManager.IsValidShortcut(keyData)) { + if (ToolStripManager.IsValidShortcut(keyData)) + { // if we're at the toplevel, check the toolstrips for matching shortcuts. // Win32 menus are handled in Form.ProcessCmdKey, but we cant guarantee that // toolstrips will be hosted in a form. ToolStrips have a hash of shortcuts @@ -1469,7 +1747,8 @@ internal static bool ProcessCmdKey(ref Message m, Keys keyData) { return ToolStripManager.ProcessShortcut(ref m, keyData); } - if (m.Msg == Interop.WindowMessages.WM_SYSKEYDOWN) { + if (m.Msg == Interop.WindowMessages.WM_SYSKEYDOWN) + { Debug.WriteLineIf(Control.ControlKeyboardRouting.TraceVerbose, "ToolStripManager.ProcessCmdKey - Checking if it's a menu key: [" + keyData.ToString() + "]"); ToolStripManager.ModalMenuFilter.ProcessMenuKeyDown(ref m); } @@ -1483,23 +1762,30 @@ internal static bool ProcessCmdKey(ref Message m, Keys keyData) { /// this way the search only takes O(number of toolstrips in the thread) /// ToolStripMenuItem pushes itself into this table as the owner is set or the shortcut changes. /// - internal static bool ProcessShortcut(ref Message m, Keys shortcut) { - if (!IsThreadUsingToolStrips()) { + internal static bool ProcessShortcut(ref Message m, Keys shortcut) + { + if (!IsThreadUsingToolStrips()) + { return false; } Control activeControl = Control.FromChildHandle(m.HWnd); Control activeControlInChain = activeControl; - if (activeControlInChain != null && IsValidShortcut(shortcut)) { + if (activeControlInChain != null && IsValidShortcut(shortcut)) + { Debug.WriteLineIf(Control.ControlKeyboardRouting.TraceVerbose, "ToolStripManager.ProcessShortcut - processing: [" + shortcut.ToString() + "]"); // start from the focused control and work your way up the parent chain - do { + do + { // check the context menu strip first. - if (activeControlInChain.ContextMenuStrip != null) { - if (activeControlInChain.ContextMenuStrip.Shortcuts.ContainsKey(shortcut)) { + if (activeControlInChain.ContextMenuStrip != null) + { + if (activeControlInChain.ContextMenuStrip.Shortcuts.ContainsKey(shortcut)) + { ToolStripMenuItem item = activeControlInChain.ContextMenuStrip.Shortcuts[shortcut] as ToolStripMenuItem; - if (item.ProcessCmdKey(ref m, shortcut)) { + if (item.ProcessCmdKey(ref m, shortcut)) + { Debug.WriteLineIf(Control.ControlKeyboardRouting.TraceVerbose, "ToolStripManager.ProcessShortcut - found item on context menu: [" + item.ToString() + "]"); return true; } @@ -1508,7 +1794,8 @@ internal static bool ProcessShortcut(ref Message m, Keys shortcut) { activeControlInChain = activeControlInChain.ParentInternal; } while (activeControlInChain != null); - if (activeControlInChain != null) { + if (activeControlInChain != null) + { // the keystroke may applies to one of our parents... // a WM_CONTEXTMENU message bubbles up to the parent control activeControl = activeControlInChain; @@ -1518,24 +1805,29 @@ internal static bool ProcessShortcut(ref Message m, Keys shortcut) { bool needsPrune = false; // now search the toolstrips - for (int i = 0; i < ToolStrips.Count; i++) { + for (int i = 0; i < ToolStrips.Count; i++) + { ToolStrip toolStrip = ToolStrips[i] as ToolStrip; bool isAssociatedContextMenu = false; bool isDoublyAssignedContextMenuStrip = false; - if (toolStrip == null) { + if (toolStrip == null) + { // consider prune tree... needsPrune = true; continue; } - else if (activeControl != null && toolStrip == activeControl.ContextMenuStrip) { + else if (activeControl != null && toolStrip == activeControl.ContextMenuStrip) + { continue; } - else if (toolStrip.Shortcuts.ContainsKey(shortcut)) { + else if (toolStrip.Shortcuts.ContainsKey(shortcut)) + { - if (toolStrip.IsDropDown) { + if (toolStrip.IsDropDown) + { // we dont want to process someone else's context menu (e.g. button1 and button2 have context menus) // button2's context menu should not be processed if button1 is the one we're processing. @@ -1545,14 +1837,18 @@ internal static bool ProcessShortcut(ref Message m, Keys shortcut) { // If a context menu is re-used between the main menu and the // and some other control's context menu, we should go ahead and evaluate it. - if (toplevelContextMenu != null) { + if (toplevelContextMenu != null) + { isDoublyAssignedContextMenuStrip = toplevelContextMenu.IsAssignedToDropDownItem; - if (!isDoublyAssignedContextMenuStrip) { - if (toplevelContextMenu != activeControl.ContextMenuStrip) { + if (!isDoublyAssignedContextMenuStrip) + { + if (toplevelContextMenu != activeControl.ContextMenuStrip) + { // the toplevel context menu is NOT the same as the active control's context menu. continue; } - else { + else + { isAssociatedContextMenu = true; } } @@ -1563,34 +1859,42 @@ internal static bool ProcessShortcut(ref Message m, Keys shortcut) { bool rootWindowsMatch = false; - if (!isAssociatedContextMenu) { + if (!isAssociatedContextMenu) + { // make sure that were processing shortcuts for the correct window. // since the shortcut lookup is faster than this check we've postponed this to the last // possible moment. ToolStrip topMostToolStrip = toolStrip.GetToplevelOwnerToolStrip(); - if (topMostToolStrip != null && activeControl != null) { + if (topMostToolStrip != null && activeControl != null) + { HandleRef rootWindowOfToolStrip = WindowsFormsUtils.GetRootHWnd(topMostToolStrip); HandleRef rootWindowOfControl = WindowsFormsUtils.GetRootHWnd(activeControl); rootWindowsMatch = (rootWindowOfToolStrip.Handle == rootWindowOfControl.Handle); - if (rootWindowsMatch) { + if (rootWindowsMatch) + { // Double check this is not an MDIContainer type situation... Form mainForm = Control.FromHandle(rootWindowOfControl.Handle) as Form; - if (mainForm != null && mainForm.IsMdiContainer) { + if (mainForm != null && mainForm.IsMdiContainer) + { Form toolStripForm = topMostToolStrip.FindForm(); - if (toolStripForm != mainForm && toolStripForm != null) { - // we should only process shortcuts of the ActiveMDIChild or the Main Form. - rootWindowsMatch = (toolStripForm == mainForm.ActiveMdiChildInternal); - } + if (toolStripForm != mainForm && toolStripForm != null) + { + // we should only process shortcuts of the ActiveMDIChild or the Main Form. + rootWindowsMatch = (toolStripForm == mainForm.ActiveMdiChildInternal); + } } - + } } } - if (isAssociatedContextMenu || rootWindowsMatch || isDoublyAssignedContextMenuStrip) { + if (isAssociatedContextMenu || rootWindowsMatch || isDoublyAssignedContextMenuStrip) + { ToolStripMenuItem item = toolStrip.Shortcuts[shortcut] as ToolStripMenuItem; - if (item != null) { - if (item.ProcessCmdKey(ref m, shortcut)) { + if (item != null) + { + if (item.ProcessCmdKey(ref m, shortcut)) + { Debug.WriteLineIf(Control.ControlKeyboardRouting.TraceVerbose, "ToolStripManager.ProcessShortcut - found item on toolstrip: [" + item.ToString() + "]"); retVal = true; break; @@ -1599,7 +1903,8 @@ internal static bool ProcessShortcut(ref Message m, Keys shortcut) { } } } - if (needsPrune) { + if (needsPrune) + { PruneToolStripList(); } return retVal; @@ -1615,10 +1920,12 @@ internal static bool ProcessShortcut(ref Message m, Keys shortcut) { /// if it doesnt it returns false. /// if it finds a win32 menu is already associated with the control it bails, returning false. /// - internal static bool ProcessMenuKey(ref Message m) { + internal static bool ProcessMenuKey(ref Message m) + { Debug.WriteLineIf(Control.ControlKeyboardRouting.TraceVerbose, "ToolStripManager.ProcessMenuKey: [" + m.ToString() + "]"); - if (!IsThreadUsingToolStrips()) { + if (!IsThreadUsingToolStrips()) + { return false; } // recievedMenuKeyUp = true; @@ -1632,12 +1939,15 @@ internal static bool ProcessMenuKey(ref Message m) { Control toplevelControl = null; MenuStrip menuStripToActivate = null; - if (intendedControl != null) { + if (intendedControl != null) + { // search for a menustrip to select. toplevelControl = intendedControl.TopLevelControlInternal; - if (toplevelControl != null) { + if (toplevelControl != null) + { IntPtr hMenu = UnsafeNativeMethods.GetMenu(new HandleRef(toplevelControl, toplevelControl.Handle)); - if (hMenu == IntPtr.Zero) { + if (hMenu == IntPtr.Zero) + { // only activate the menu if there's no win32 menu. Win32 menus trump menustrips. menuStripToActivate = GetMainMenuStrip(toplevelControl); } @@ -1647,40 +1957,50 @@ internal static bool ProcessMenuKey(ref Message m) { } // the data that comes into the LParam is the ASCII code, not the VK_* code. // we need to compare against char instead. - if ((char)keyData == ' ') { // dont process system menu + if ((char)keyData == ' ') + { // dont process system menu ModalMenuFilter.MenuKeyToggle = false; } - else if ((char)keyData == '-') { + else if ((char)keyData == '-') + { // deal with MDI system menu Form mdiChild = toplevelControl as Form; - if (mdiChild != null && mdiChild.IsMdiChild) { - if (mdiChild.WindowState == FormWindowState.Maximized) { + if (mdiChild != null && mdiChild.IsMdiChild) + { + if (mdiChild.WindowState == FormWindowState.Maximized) + { ModalMenuFilter.MenuKeyToggle = false; } } } - else { + else + { // this is the same as Control.ModifierKeys - but we save two p/invokes. - if (UnsafeNativeMethods.GetKeyState((int)Keys.ShiftKey) < 0 && (keyData == Keys.None)) { + if (UnsafeNativeMethods.GetKeyState((int)Keys.ShiftKey) < 0 && (keyData == Keys.None)) + { // If it's Shift+F10 and we're already InMenuMode, then we // need to cancel this message, otherwise we'll enter the native modal menu loop. Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[ProcessMenuKey] DETECTED SHIFT+F10" + keyData.ToString()); return ToolStripManager.ModalMenuFilter.InMenuMode; } - else { - if (menuStripToActivate != null && !ModalMenuFilter.MenuKeyToggle) { + else + { + if (menuStripToActivate != null && !ModalMenuFilter.MenuKeyToggle) + { Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[ProcessMenuKey] attempting to set focus to menustrip"); // if we've alt-tabbed away dont snap/restore focus. HandleRef topmostParentOfMenu = WindowsFormsUtils.GetRootHWnd(menuStripToActivate); IntPtr foregroundWindow = UnsafeNativeMethods.GetForegroundWindow(); - if (topmostParentOfMenu.Handle == foregroundWindow) { + if (topmostParentOfMenu.Handle == foregroundWindow) + { Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[ProcessMenuKey] ToolStripManager call MenuStrip.OnMenuKey"); return menuStripToActivate.OnMenuKey(); } } - else if (menuStripToActivate != null) { + else if (menuStripToActivate != null) + { Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[ProcessMenuKey] Resetting MenuKeyToggle"); ModalMenuFilter.MenuKeyToggle = false; return true; @@ -1691,15 +2011,18 @@ internal static bool ProcessMenuKey(ref Message m) { return false; } - internal static MenuStrip GetMainMenuStrip(Control control) { - if (control == null) { + internal static MenuStrip GetMainMenuStrip(Control control) + { + if (control == null) + { Debug.Fail("why are we passing null to GetMainMenuStrip?"); return null; } // look for a particular main menu strip to be set. Form mainForm = control.FindForm(); - if (mainForm != null && mainForm.MainMenuStrip != null) { + if (mainForm != null && mainForm.MainMenuStrip != null) + { return mainForm.MainMenuStrip; } @@ -1707,39 +2030,50 @@ internal static MenuStrip GetMainMenuStrip(Control control) { return GetFirstMenuStripRecursive(control.Controls); } - private static MenuStrip GetFirstMenuStripRecursive(Control.ControlCollection controlsToLookIn) { - try { + private static MenuStrip GetFirstMenuStripRecursive(Control.ControlCollection controlsToLookIn) + { + try + { // Perform breadth first search - as it's likely people will want controls belonging // to the same parent close to each other. - for (int i = 0; i < controlsToLookIn.Count; i++) { - if (controlsToLookIn[i] == null) { + for (int i = 0; i < controlsToLookIn.Count; i++) + { + if (controlsToLookIn[i] == null) + { continue; } - if (controlsToLookIn[i] is MenuStrip) { + if (controlsToLookIn[i] is MenuStrip) + { return controlsToLookIn[i] as MenuStrip; } } // Recursive search for controls in child collections. - for (int i = 0; i < controlsToLookIn.Count; i++) { - if (controlsToLookIn[i] == null) { + for (int i = 0; i < controlsToLookIn.Count; i++) + { + if (controlsToLookIn[i] == null) + { continue; } - if ((controlsToLookIn[i].Controls != null) && controlsToLookIn[i].Controls.Count > 0) { + if ((controlsToLookIn[i].Controls != null) && controlsToLookIn[i].Controls.Count > 0) + { // if it has a valid child collecion, append those results to our collection MenuStrip menuStrip = GetFirstMenuStripRecursive(controlsToLookIn[i].Controls); - if (menuStrip != null) { + if (menuStrip != null) + { return menuStrip; } } } } - catch (Exception e) { + catch (Exception e) + { // Make sure we deal with non-critical failures gracefully. - if (ClientUtils.IsCriticalException(e)) { + if (ClientUtils.IsCriticalException(e)) + { throw; } } @@ -1755,21 +2089,26 @@ private static MenuStrip GetFirstMenuStripRecursive(Control.ControlCollection co #region MenuMerging - private static ToolStripItem FindMatch(ToolStripItem source, ToolStripItemCollection destinationItems) { + private static ToolStripItem FindMatch(ToolStripItem source, ToolStripItemCollection destinationItems) + { // based on MergeAction: // Append, return the last sibling ToolStripItem result = null; - if (source != null) { - for (int i = 0; i < destinationItems.Count; i++) { + if (source != null) + { + for (int i = 0; i < destinationItems.Count; i++) + { ToolStripItem candidateItem = destinationItems[i]; // using SafeCompareKeys so we use the same heuristics as keyed collections. - if (WindowsFormsUtils.SafeCompareStrings(source.Text, candidateItem.Text, true)) { + if (WindowsFormsUtils.SafeCompareStrings(source.Text, candidateItem.Text, true)) + { result = candidateItem; break; // we found it } } - if (result == null && source.MergeIndex > -1 && source.MergeIndex < destinationItems.Count) { + if (result == null && source.MergeIndex > -1 && source.MergeIndex < destinationItems.Count) + { result = destinationItems[source.MergeIndex]; } } @@ -1778,16 +2117,20 @@ private static ToolStripItem FindMatch(ToolStripItem source, ToolStripItemCollec /// /// - internal static ArrayList FindMergeableToolStrips(ContainerControl container) { + internal static ArrayList FindMergeableToolStrips(ContainerControl container) + { ArrayList result = new ArrayList(); - if (container != null) { - for (int i = 0; i < ToolStrips.Count; i++) { + if (container != null) + { + for (int i = 0; i < ToolStrips.Count; i++) + { ToolStrip candidateTS = (ToolStrip)ToolStrips[i]; //if(candidateTS != null) { // Debug.WriteLine("candidate TS: " + candidateTS.Name + " | " + candidateTS.AllowMerge + " | " + (candidateTS.Parent == null ? "null" : candidateTS.Parent.Name) +" | " + container.Name); //} //Debug.WriteLine(candidateTS == null ? "null" : "not null"); - if (candidateTS != null && candidateTS.AllowMerge && container == candidateTS.FindForm()) { + if (candidateTS != null && candidateTS.AllowMerge && container == candidateTS.FindForm()) + { //Debug.WriteLine("adding"); result.Add(candidateTS); } @@ -1797,22 +2140,27 @@ internal static ArrayList FindMergeableToolStrips(ContainerControl container) { return result; } - private static bool IsSpecialMDIStrip(ToolStrip toolStrip) { + private static bool IsSpecialMDIStrip(ToolStrip toolStrip) + { return (toolStrip is MdiControlStrip || toolStrip is MdiWindowListStrip); } /// /// merge two toolstrips /// - public static bool Merge(ToolStrip sourceToolStrip, ToolStrip targetToolStrip) { + public static bool Merge(ToolStrip sourceToolStrip, ToolStrip targetToolStrip) + { // check arguments - if (sourceToolStrip == null) { + if (sourceToolStrip == null) + { throw new ArgumentNullException(nameof(sourceToolStrip)); } - if (targetToolStrip == null) { + if (targetToolStrip == null) + { throw new ArgumentNullException(nameof(targetToolStrip)); } - if (targetToolStrip == sourceToolStrip) { + if (targetToolStrip == sourceToolStrip) + { throw new ArgumentException(SR.ToolStripMergeImpossibleIdentical); } @@ -1824,7 +2172,8 @@ public static bool Merge(ToolStrip sourceToolStrip, ToolStrip targetToolStrip) { ) ); MergeHistory mergeHistory = null; - if (canMerge) { + if (canMerge) + { //Debug.WriteLine("Begin merge between src: " + sourceToolStrip.Name + " and target: " + targetToolStrip.Name); Debug.Indent(); mergeHistory = new MergeHistory(sourceToolStrip); @@ -1832,14 +2181,17 @@ public static bool Merge(ToolStrip sourceToolStrip, ToolStrip targetToolStrip) { int originalCount = sourceToolStrip.Items.Count; - if (originalCount > 0) { + if (originalCount > 0) + { sourceToolStrip.SuspendLayout(); targetToolStrip.SuspendLayout(); - try { + try + { int lastCount = originalCount; // 2. do the actual merging logic - for (int i = 0, itemToLookAt = 0; i < originalCount; i++) { + for (int i = 0, itemToLookAt = 0; i < originalCount; i++) + { ToolStripItem item = sourceToolStrip.Items[itemToLookAt]; //Debug.WriteLine("doing the recursive merge for item " + item.Text); MergeRecursive(item, targetToolStrip.Items, mergeHistory.MergeHistoryItemsStack); @@ -1849,20 +2201,23 @@ public static bool Merge(ToolStrip sourceToolStrip, ToolStrip targetToolStrip) { lastCount = sourceToolStrip.Items.Count; } } - finally { + finally + { Debug.Unindent(); sourceToolStrip.ResumeLayout(); targetToolStrip.ResumeLayout(); } //Debug.WriteLine("pusing mergehistory for toolstrip " + sourceToolStrip.Name + " in target toolstrip MergeHistoryStack property"); - if (mergeHistory.MergeHistoryItemsStack.Count > 0) { + if (mergeHistory.MergeHistoryItemsStack.Count > 0) + { // only push this on the stack if we actually did something targetToolStrip.MergeHistoryStack.Push(mergeHistory); } } } bool result = false; - if (mergeHistory != null && mergeHistory.MergeHistoryItemsStack.Count > 0) { + if (mergeHistory != null && mergeHistory.MergeHistoryItemsStack.Count > 0) + { result = true; // we did merge something } return result; @@ -1870,32 +2225,40 @@ public static bool Merge(ToolStrip sourceToolStrip, ToolStrip targetToolStrip) { - private static void MergeRecursive(ToolStripItem source, ToolStripItemCollection destinationItems, Stack history) { + private static void MergeRecursive(ToolStripItem source, ToolStripItemCollection destinationItems, Stack history) + { Debug.Indent(); MergeHistoryItem maction; - switch (source.MergeAction) { + switch (source.MergeAction) + { case MergeAction.MatchOnly: case MergeAction.Replace: case MergeAction.Remove: ToolStripItem item = FindMatch(source, destinationItems); - if (item != null) { - switch (source.MergeAction) { + if (item != null) + { + switch (source.MergeAction) + { case MergeAction.MatchOnly: //Debug.WriteLine("matchonly"); ToolStripDropDownItem tsddownDest = item as ToolStripDropDownItem; ToolStripDropDownItem tsddownSrc = source as ToolStripDropDownItem; - if (tsddownDest != null && tsddownSrc != null && tsddownSrc.DropDownItems.Count != 0) { + if (tsddownDest != null && tsddownSrc != null && tsddownSrc.DropDownItems.Count != 0) + { int originalCount = tsddownSrc.DropDownItems.Count; - if (originalCount > 0) { + if (originalCount > 0) + { int lastCount = originalCount; tsddownSrc.DropDown.SuspendLayout(); - try { + try + { // the act of walking through this collection removes items from // the dropdown. - for (int i = 0, itemToLookAt = 0; i < originalCount; i++) { + for (int i = 0, itemToLookAt = 0; i < originalCount; i++) + { MergeRecursive(tsddownSrc.DropDownItems[itemToLookAt], tsddownDest.DropDownItems, history); @@ -1904,7 +2267,8 @@ private static void MergeRecursive(ToolStripItem source, ToolStripItemCollection lastCount = tsddownSrc.DropDownItems.Count; } } - finally { + finally + { tsddownSrc.DropDown.ResumeLayout(); } } @@ -1922,7 +2286,8 @@ private static void MergeRecursive(ToolStripItem source, ToolStripItemCollection maction.TargetItem = item; history.Push(maction); //Debug.WriteLine(maction.ToString()); - if (source.MergeAction == MergeAction.Replace) { + if (source.MergeAction == MergeAction.Replace) + { //Debug.WriteLine("replace"); //ToolStripItem clonedItem = source.Clone(); maction = new MergeHistoryItem(MergeAction.Remove); @@ -1940,7 +2305,8 @@ private static void MergeRecursive(ToolStripItem source, ToolStripItemCollection } break; case MergeAction.Insert: - if (source.MergeIndex > -1) { + if (source.MergeIndex > -1) + { maction = new MergeHistoryItem(MergeAction.Remove); maction.PreviousIndexCollection = source.Owner.Items; maction.PreviousIndex = maction.PreviousIndexCollection.IndexOf(source); @@ -1971,19 +2337,24 @@ private static void MergeRecursive(ToolStripItem source, ToolStripItemCollection /// /// merge two toolstrips /// - public static bool Merge(ToolStrip sourceToolStrip, string targetName) { - if (sourceToolStrip == null) { + public static bool Merge(ToolStrip sourceToolStrip, string targetName) + { + if (sourceToolStrip == null) + { throw new ArgumentNullException(nameof(sourceToolStrip)); } - if (targetName == null) { + if (targetName == null) + { throw new ArgumentNullException(nameof(targetName)); } - + ToolStrip target = FindToolStrip(targetName); - if (target == null) { + if (target == null) + { return false; } - else { + else + { return Merge(sourceToolStrip, target); } } @@ -1991,64 +2362,80 @@ public static bool Merge(ToolStrip sourceToolStrip, string targetName) { /// /// doesn't do a null check on source... if it's null we unmerge everything /// - internal static bool RevertMergeInternal(ToolStrip targetToolStrip, ToolStrip sourceToolStrip, bool revertMDIControls) { + internal static bool RevertMergeInternal(ToolStrip targetToolStrip, ToolStrip sourceToolStrip, bool revertMDIControls) + { bool result = false; - if (targetToolStrip == null) { + if (targetToolStrip == null) + { throw new ArgumentNullException(nameof(targetToolStrip)); } - if (targetToolStrip == sourceToolStrip) { + if (targetToolStrip == sourceToolStrip) + { throw new ArgumentException(SR.ToolStripMergeImpossibleIdentical); } bool foundToolStrip = false; - if (sourceToolStrip != null) { + if (sourceToolStrip != null) + { // we have a specific toolstrip to pull out. // make sure the sourceToolStrip is even merged into the targetToolStrip - foreach (MergeHistory history in targetToolStrip.MergeHistoryStack) { + foreach (MergeHistory history in targetToolStrip.MergeHistoryStack) + { foundToolStrip = (history.MergedToolStrip == sourceToolStrip); - if (foundToolStrip) { + if (foundToolStrip) + { break; } } // PERF: if we dont have the toolstrip in our merge history, bail. - if (!foundToolStrip) { + if (!foundToolStrip) + { //Debug.WriteLine("source toolstrip not contained within target " + history.MergedToolStrip.Name); return false; } } - if( sourceToolStrip != null ) { + if (sourceToolStrip != null) + { sourceToolStrip.SuspendLayout(); } targetToolStrip.SuspendLayout(); - try { + try + { //Debug.WriteLine("Reverting merge, playing back history for all merged toolstrip "); Stack reApply = new Stack(); foundToolStrip = false; - while (targetToolStrip.MergeHistoryStack.Count > 0 && !foundToolStrip) { + while (targetToolStrip.MergeHistoryStack.Count > 0 && !foundToolStrip) + { result = true; // we unmerge something... MergeHistory history = targetToolStrip.MergeHistoryStack.Pop(); - if (history.MergedToolStrip == sourceToolStrip) { + if (history.MergedToolStrip == sourceToolStrip) + { foundToolStrip = true; } - else if (!revertMDIControls && sourceToolStrip == null) { + else if (!revertMDIControls && sourceToolStrip == null) + { // Calling ToolStripManager.RevertMerge should not pull out MDIControlStrip && MDIWindowListStrip. - if (IsSpecialMDIStrip(history.MergedToolStrip)) { + if (IsSpecialMDIStrip(history.MergedToolStrip)) + { reApply.Push(history.MergedToolStrip); } } - else { + else + { reApply.Push(history.MergedToolStrip); } //Debug.WriteLine("unmerging " + history.MergedToolStrip.Name); Debug.Indent(); - while (history.MergeHistoryItemsStack.Count > 0) { + while (history.MergeHistoryItemsStack.Count > 0) + { MergeHistoryItem historyItem = history.MergeHistoryItemsStack.Pop(); - switch (historyItem.MergeAction) { + switch (historyItem.MergeAction) + { case MergeAction.Remove: historyItem.IndexCollection.Remove(historyItem.TargetItem); // put it back @@ -2060,17 +2447,20 @@ internal static bool RevertMergeInternal(ToolStrip targetToolStrip, ToolStrip so break; } } - Debug.Unindent(); + Debug.Unindent(); } // re-apply the merges of the toolstrips we had to unmerge first. - while (reApply.Count > 0) { + while (reApply.Count > 0) + { ToolStrip mergeAgain = reApply.Pop(); Merge(mergeAgain, targetToolStrip); } } - finally { - if( sourceToolStrip != null ) { + finally + { + if (sourceToolStrip != null) + { sourceToolStrip.ResumeLayout(); } targetToolStrip.ResumeLayout(); @@ -2083,15 +2473,18 @@ internal static bool RevertMergeInternal(ToolStrip targetToolStrip, ToolStrip so /// /// unmerge two toolstrips /// - public static bool RevertMerge(ToolStrip targetToolStrip) { + public static bool RevertMerge(ToolStrip targetToolStrip) + { return RevertMergeInternal(targetToolStrip, null, /*revertMDIControls*/false); } /// /// unmerge two toolstrips /// - public static bool RevertMerge(ToolStrip targetToolStrip, ToolStrip sourceToolStrip) { - if (sourceToolStrip == null) { + public static bool RevertMerge(ToolStrip targetToolStrip, ToolStrip sourceToolStrip) + { + if (sourceToolStrip == null) + { throw new ArgumentNullException(nameof(sourceToolStrip)); } return RevertMergeInternal(targetToolStrip, sourceToolStrip, /*revertMDIControls*/false); @@ -2100,12 +2493,15 @@ public static bool RevertMerge(ToolStrip targetToolStrip, ToolStrip sourceToolSt /// /// unmerge two toolstrips /// - public static bool RevertMerge(string targetName) { + public static bool RevertMerge(string targetName) + { ToolStrip target = FindToolStrip(targetName); - if (target == null) { + if (target == null) + { return false; } - else { + else + { return RevertMerge(target); } } @@ -2114,44 +2510,57 @@ public static bool RevertMerge(string targetName) { } - internal class ToolStripCustomIComparer : IComparer { - int IComparer.Compare(object x, object y) { - if (x.GetType() == y.GetType()) { + internal class ToolStripCustomIComparer : IComparer + { + int IComparer.Compare(object x, object y) + { + if (x.GetType() == y.GetType()) + { return 0; // same type } - if (x.GetType().IsAssignableFrom(y.GetType())) { + if (x.GetType().IsAssignableFrom(y.GetType())) + { return 1; } - if (y.GetType().IsAssignableFrom(x.GetType())) { + if (y.GetType().IsAssignableFrom(x.GetType())) + { return -1; } return 0; // not the same type, not in each other inheritance chain } } - internal class MergeHistory { + internal class MergeHistory + { private Stack mergeHistoryItemsStack; private ToolStrip mergedToolStrip; - public MergeHistory(ToolStrip mergedToolStrip) { + public MergeHistory(ToolStrip mergedToolStrip) + { this.mergedToolStrip = mergedToolStrip; } - public Stack MergeHistoryItemsStack { - get { - if (mergeHistoryItemsStack == null) { + public Stack MergeHistoryItemsStack + { + get + { + if (mergeHistoryItemsStack == null) + { mergeHistoryItemsStack = new Stack(); } return mergeHistoryItemsStack; } } - public ToolStrip MergedToolStrip { - get { + public ToolStrip MergedToolStrip + { + get + { return mergedToolStrip; } } } - internal class MergeHistoryItem { + internal class MergeHistoryItem + { private MergeAction mergeAction; private ToolStripItem targetItem; private int index = -1; @@ -2159,57 +2568,76 @@ internal class MergeHistoryItem { private ToolStripItemCollection previousIndexCollection; private ToolStripItemCollection indexCollection; - public MergeHistoryItem(MergeAction mergeAction) { + public MergeHistoryItem(MergeAction mergeAction) + { this.mergeAction = mergeAction; } - public MergeAction MergeAction { - get { + public MergeAction MergeAction + { + get + { return mergeAction; } } - public ToolStripItem TargetItem { - get { + public ToolStripItem TargetItem + { + get + { return targetItem; } - set { + set + { targetItem = value; } } - public int Index { - get { + public int Index + { + get + { return index; } - set { + set + { index = value; } } - public int PreviousIndex { - get { + public int PreviousIndex + { + get + { return previousIndex; } - set { + set + { previousIndex = value; } } - public ToolStripItemCollection PreviousIndexCollection { - get { + public ToolStripItemCollection PreviousIndexCollection + { + get + { return previousIndexCollection; } - set { + set + { previousIndexCollection = value; } } - public ToolStripItemCollection IndexCollection { - get { + public ToolStripItemCollection IndexCollection + { + get + { return indexCollection; } - set { + set + { indexCollection = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - public override string ToString() { + public override string ToString() + { return "MergeAction: " + mergeAction.ToString() + " | TargetItem: " + (TargetItem == null ? "null" : TargetItem.Text) + " Index: " + index.ToString(CultureInfo.CurrentCulture); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManagerRenderMode.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManagerRenderMode.cs index e5ea859a924..f9ae422839a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManagerRenderMode.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManagerRenderMode.cs @@ -9,7 +9,7 @@ namespace System.Windows.Forms public enum ToolStripManagerRenderMode { [Browsable(false)] - Custom = ToolStripRenderMode.Custom, + Custom = ToolStripRenderMode.Custom, System = ToolStripRenderMode.System, Professional = ToolStripRenderMode.Professional } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs index 4f5fdbd31f6..ae18bf0a502 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Collections; using System.ComponentModel; @@ -12,41 +13,42 @@ namespace System.Windows.Forms { using System.Threading; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; - using System.Windows.Forms.Layout; + using System.Windows.Forms.Layout; using System.Runtime.InteropServices; using System.ComponentModel.Design.Serialization; - using System.Windows.Forms.Design; + using System.Windows.Forms.Design; using System.Globalization; - using System.Windows.Forms.Internal; + using System.Windows.Forms.Internal; using System.Runtime.Versioning; /// /// ToolStripMenuItem /// [ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.MenuStrip | ToolStripItemDesignerAvailability.ContextMenuStrip)] - [DesignerSerializer("System.Windows.Forms.Design.ToolStripMenuItemCodeDomSerializer, " + AssemblyRef.SystemDesign, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + AssemblyRef.SystemDesign)] - public class ToolStripMenuItem : ToolStripDropDownItem { + [DesignerSerializer("System.Windows.Forms.Design.ToolStripMenuItemCodeDomSerializer, " + AssemblyRef.SystemDesign, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + AssemblyRef.SystemDesign)] + public class ToolStripMenuItem : ToolStripDropDownItem + { - private static MenuTimer menuTimer = new MenuTimer(); + private static MenuTimer menuTimer = new MenuTimer(); - private static readonly int PropShortcutKeys = PropertyStore.CreateKey(); - private static readonly int PropCheckState = PropertyStore.CreateKey(); - private static readonly int PropMdiForm = PropertyStore.CreateKey(); + private static readonly int PropShortcutKeys = PropertyStore.CreateKey(); + private static readonly int PropCheckState = PropertyStore.CreateKey(); + private static readonly int PropMdiForm = PropertyStore.CreateKey(); - private bool checkOnClick = false; - private bool showShortcutKeys = true; - private ToolStrip lastOwner = null; + private bool checkOnClick = false; + private bool showShortcutKeys = true; + private ToolStrip lastOwner = null; // SUPPORT for mapping NATIVE menu commands to ToolStripMenuItems ----- // corresponds to wID in MENUITEMINFO structure - private int nativeMenuCommandID = -1; - private IntPtr targetWindowHandle = IntPtr.Zero; - private IntPtr nativeMenuHandle = IntPtr.Zero; - + private int nativeMenuCommandID = -1; + private IntPtr targetWindowHandle = IntPtr.Zero; + private IntPtr nativeMenuHandle = IntPtr.Zero; + // Keep checked images shared between menu items, but per thread so we dont have locking issues in GDI+ [ThreadStatic] private static Image indeterminateCheckedImage; - + [ThreadStatic] private static Image checkedImage; @@ -62,38 +64,47 @@ public class ToolStripMenuItem : ToolStripDropDownItem { private Size scaledCheckMarkBitmapSize = checkMarkBitmapSize; private byte openMouseId = 0; - + private static readonly object EventCheckedChanged = new object(); private static readonly object EventCheckStateChanged = new object(); - - public ToolStripMenuItem() : base() { + + public ToolStripMenuItem() : base() + { Initialize(); // all additional work should be done in Initialize } - public ToolStripMenuItem(string text):base(text,null,(EventHandler)null) { + public ToolStripMenuItem(string text) : base(text, null, (EventHandler)null) + { Initialize(); } - public ToolStripMenuItem(Image image):base(null,image,(EventHandler)null) { + public ToolStripMenuItem(Image image) : base(null, image, (EventHandler)null) + { Initialize(); } - public ToolStripMenuItem(string text, Image image):base(text,image,(EventHandler)null) { + public ToolStripMenuItem(string text, Image image) : base(text, image, (EventHandler)null) + { Initialize(); } - public ToolStripMenuItem(string text, Image image, EventHandler onClick):base(text,image,onClick) { + public ToolStripMenuItem(string text, Image image, EventHandler onClick) : base(text, image, onClick) + { Initialize(); } - public ToolStripMenuItem(string text, Image image, EventHandler onClick, string name) : base(text,image,onClick, name){ + public ToolStripMenuItem(string text, Image image, EventHandler onClick, string name) : base(text, image, onClick, name) + { Initialize(); - } - public ToolStripMenuItem(string text, Image image, params ToolStripItem[] dropDownItems):base(text,image,dropDownItems) { + } + public ToolStripMenuItem(string text, Image image, params ToolStripItem[] dropDownItems) : base(text, image, dropDownItems) + { Initialize(); } - public ToolStripMenuItem(string text, Image image, EventHandler onClick, Keys shortcutKeys):base(text,image,onClick) { + public ToolStripMenuItem(string text, Image image, EventHandler onClick, Keys shortcutKeys) : base(text, image, onClick) + { Initialize(); this.ShortcutKeys = shortcutKeys; } - internal ToolStripMenuItem(Form mdiForm) { + internal ToolStripMenuItem(Form mdiForm) + { Initialize(); - Properties.SetObject(PropMdiForm,mdiForm); + Properties.SetObject(PropMdiForm, mdiForm); } /// this constructor is only used when we're trying to @@ -102,12 +113,13 @@ internal ToolStripMenuItem(Form mdiForm) { /// target window to send WM_COMMAND/WM_SYSCOMMAND messages to. /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] - internal ToolStripMenuItem(IntPtr hMenu, int nativeMenuCommandId, IWin32Window targetWindow) { + internal ToolStripMenuItem(IntPtr hMenu, int nativeMenuCommandId, IWin32Window targetWindow) + { Initialize(); - this.Overflow = ToolStripItemOverflow.Never; - this.nativeMenuCommandID = nativeMenuCommandId; - this.targetWindowHandle = Control.GetSafeHandle(targetWindow); - this.nativeMenuHandle = hMenu; + this.Overflow = ToolStripItemOverflow.Never; + this.nativeMenuCommandID = nativeMenuCommandId; + this.targetWindowHandle = Control.GetSafeHandle(targetWindow); + this.nativeMenuHandle = hMenu; // Since fetching the image and the text is an awful lot of work // we're going to just cache it and assume the native stuff @@ -124,15 +136,18 @@ internal ToolStripMenuItem(IntPtr hMenu, int nativeMenuCommandId, IWin32Window t string text = GetNativeMenuItemTextAndShortcut(); // the shortcut is tab separated from the item text. - if (text != null) { + if (text != null) + { // separate out the two fields. string[] textFields = text.Split('\t'); - if (textFields.Length >= 1){ + if (textFields.Length >= 1) + { this.Text = textFields[0]; } - if (textFields.Length >= 2) { + if (textFields.Length >= 2) + { // We dont care about the shortcut here, the OS is going to // handle it for us by sending a WM_(SYS)COMMAND during TranslateAcellerator // Just display whatever the OS would have. @@ -142,35 +157,44 @@ internal ToolStripMenuItem(IntPtr hMenu, int nativeMenuCommandId, IWin32Window t } } - internal override void AutoHide(ToolStripItem otherItemBeingSelected) { - if (IsOnDropDown) { - MenuTimer.Transition(this,otherItemBeingSelected as ToolStripMenuItem); + internal override void AutoHide(ToolStripItem otherItemBeingSelected) + { + if (IsOnDropDown) + { + MenuTimer.Transition(this, otherItemBeingSelected as ToolStripMenuItem); } - else { + else + { base.AutoHide(otherItemBeingSelected); } } - private void ClearShortcutCache() { + private void ClearShortcutCache() + { cachedShortcutSize = Size.Empty; cachedShortcutText = null; } - protected override ToolStripDropDown CreateDefaultDropDown() { + protected override ToolStripDropDown CreateDefaultDropDown() + { // AutoGenerate a ToolStrip DropDown - set the property so we hook events - return new ToolStripDropDownMenu(this, true); + return new ToolStripDropDownMenu(this, true); } - internal override ToolStripItemInternalLayout CreateInternalLayout() { - return new ToolStripMenuItemInternalLayout(this); + internal override ToolStripItemInternalLayout CreateInternalLayout() + { + return new ToolStripMenuItemInternalLayout(this); } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new ToolStripMenuItemAccessibleObject(this); } - private void Initialize() { - if (DpiHelper.IsScalingRequirementMet) { + private void Initialize() + { + if (DpiHelper.IsScalingRequirementMet) + { scaledDefaultPadding = DpiHelper.LogicalToDeviceUnits(defaultPadding); scaledDefaultDropDownPadding = DpiHelper.LogicalToDeviceUnits(defaultDropDownPadding); scaledCheckMarkBitmapSize = DpiHelper.LogicalToDeviceUnits(checkMarkBitmapSize); @@ -180,54 +204,68 @@ private void Initialize() { this.MouseDownAndUpMustBeInSameItem = false; this.SupportsDisabledHotTracking = true; } - + /// /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(32, 19); } } - protected internal override Padding DefaultMargin { - get { - return Padding.Empty; + protected internal override Padding DefaultMargin + { + get + { + return Padding.Empty; } } - protected override Padding DefaultPadding { - get { - if (IsOnDropDown) { + protected override Padding DefaultPadding + { + get + { + if (IsOnDropDown) + { return scaledDefaultDropDownPadding; } - else { + else + { return scaledDefaultPadding; } } } - public override bool Enabled { - get{ - if (nativeMenuCommandID != -1) { + public override bool Enabled + { + get + { + if (nativeMenuCommandID != -1) + { // if we're based off a native menu item, // we need to ask it if it's enabled. - if (base.Enabled && nativeMenuHandle != IntPtr.Zero && targetWindowHandle != IntPtr.Zero) { + if (base.Enabled && nativeMenuHandle != IntPtr.Zero && targetWindowHandle != IntPtr.Zero) + { return GetNativeMenuItemEnabled(); } return false; } - else { + else + { return base.Enabled; } - } - set { + } + set + { base.Enabled = value; - } + } } - + /// /// /// Gets or sets a value indicating whether the item is checked. @@ -240,13 +278,17 @@ public override bool Enabled { RefreshProperties(RefreshProperties.All), SRDescription(nameof(SR.CheckBoxCheckedDescr)) ] - public bool Checked { - get { + public bool Checked + { + get + { return CheckState != CheckState.Unchecked; } - set { - if (value != Checked) { + set + { + if (value != Checked) + { CheckState = value ? CheckState.Checked : CheckState.Unchecked; InvokePaint(); } @@ -258,21 +300,29 @@ public bool Checked { /// Keeps a shared copy of the checked image between all menu items /// Fishes out the appropriate one based on CheckState. /// - internal Image CheckedImage { - - - get { + internal Image CheckedImage + { + + + get + { CheckState checkedState = CheckState; - if (checkedState == CheckState.Indeterminate) { - if (indeterminateCheckedImage == null) { - if (DpiHelper.IsScalingRequirementMet) { + if (checkedState == CheckState.Indeterminate) + { + if (indeterminateCheckedImage == null) + { + if (DpiHelper.IsScalingRequirementMet) + { indeterminateCheckedImage = GetBitmapFromIcon("IndeterminateChecked", scaledCheckMarkBitmapSize); } - else { + else + { Bitmap indeterminateCheckedBmp = DpiHelper.GetBitmapFromIcon(typeof(ToolStripMenuItem), "IndeterminateChecked"); - if (indeterminateCheckedBmp != null) { - if (DpiHelper.IsScalingRequired) { + if (indeterminateCheckedBmp != null) + { + if (DpiHelper.IsScalingRequired) + { DpiHelper.ScaleBitmapLogicalToDevice(ref indeterminateCheckedBmp); } indeterminateCheckedImage = indeterminateCheckedBmp; @@ -281,15 +331,21 @@ internal Image CheckedImage { } return indeterminateCheckedImage; } - else if (checkedState == CheckState.Checked) { - if (checkedImage == null) { - if (DpiHelper.IsScalingRequirementMet) { + else if (checkedState == CheckState.Checked) + { + if (checkedImage == null) + { + if (DpiHelper.IsScalingRequirementMet) + { checkedImage = GetBitmapFromIcon("Checked", scaledCheckMarkBitmapSize); } - else { + else + { Bitmap checkedBmp = DpiHelper.GetBitmapFromIcon(typeof(ToolStripMenuItem), "Checked"); - if (checkedBmp != null) { - if (DpiHelper.IsScalingRequired) { + if (checkedBmp != null) + { + if (DpiHelper.IsScalingRequired) + { DpiHelper.ScaleBitmapLogicalToDevice(ref checkedBmp); } checkedImage = checkedBmp; @@ -341,19 +397,22 @@ private static Bitmap GetBitmapFromIcon(string iconName, Size desiredIconSize) return b; } - [ - DefaultValue(false), - SRCategory(nameof(SR.CatBehavior)), - SRDescription(nameof(SR.ToolStripButtonCheckOnClickDescr)) - ] - public bool CheckOnClick { - get { - return checkOnClick; - } - set { - checkOnClick = value; - } - } + [ + DefaultValue(false), + SRCategory(nameof(SR.CatBehavior)), + SRDescription(nameof(SR.ToolStripButtonCheckOnClickDescr)) + ] + public bool CheckOnClick + { + get + { + return checkOnClick; + } + set + { + checkOnClick = value; + } + } /// /// Gets @@ -366,45 +425,51 @@ public bool CheckOnClick { RefreshProperties(RefreshProperties.All), SRDescription(nameof(SR.CheckBoxCheckStateDescr)) ] - public CheckState CheckState { - get { + public CheckState CheckState + { + get + { bool found = false; object checkState = Properties.GetInteger(PropCheckState, out found); return (found) ? (CheckState)checkState : CheckState.Unchecked; } - set { + set + { //valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)CheckState.Unchecked, (int)CheckState.Indeterminate)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(CheckState)); } - - if (value != CheckState) { + + if (value != CheckState) + { Properties.SetInteger(PropCheckState, (int)value); OnCheckedChanged(EventArgs.Empty); - OnCheckStateChanged(EventArgs.Empty); + OnCheckStateChanged(EventArgs.Empty); } } } - + /// /// Occurs when the /// value of the /// property changes. /// [SRDescription(nameof(SR.CheckBoxOnCheckedChangedDescr))] - public event EventHandler CheckedChanged { + public event EventHandler CheckedChanged + { add => Events.AddHandler(EventCheckedChanged, value); remove => Events.RemoveHandler(EventCheckedChanged, value); - } + } /// /// Occurs when the /// value of the /// property changes. /// [SRDescription(nameof(SR.CheckBoxOnCheckStateChangedDescr))] - public event EventHandler CheckStateChanged { + public event EventHandler CheckStateChanged + { add => Events.AddHandler(EventCheckStateChanged, value); remove => Events.RemoveHandler(EventCheckStateChanged, value); } @@ -418,12 +483,15 @@ public event EventHandler CheckStateChanged { DefaultValue(ToolStripItemOverflow.Never), SRDescription(nameof(SR.ToolStripItemOverflowDescr)), SRCategory(nameof(SR.CatLayout)) - ] - public new ToolStripItemOverflow Overflow { - get { + ] + public new ToolStripItemOverflow Overflow + { + get + { return base.Overflow; } - set { + set + { base.Overflow = value; } } @@ -439,46 +507,57 @@ public event EventHandler CheckStateChanged { DefaultValue(Keys.None), SRDescription(nameof(SR.MenuItemShortCutDescr)) ] - public Keys ShortcutKeys { - get { + public Keys ShortcutKeys + { + get + { bool found = false; - object shortcutKeys = Properties.GetInteger(PropShortcutKeys, out found ); + object shortcutKeys = Properties.GetInteger(PropShortcutKeys, out found); return (found) ? (Keys)shortcutKeys : Keys.None; } - set { - if ((value != Keys.None) && !ToolStripManager.IsValidShortcut(value)){ + set + { + if ((value != Keys.None) && !ToolStripManager.IsValidShortcut(value)) + { // prevent use of alt, ctrl, shift modifiers with no key code. throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(Keys)); } Keys originalShortcut = ShortcutKeys; - if (originalShortcut != value) { + if (originalShortcut != value) + { ClearShortcutCache(); ToolStrip owner = this.Owner; - if (owner != null) { + if (owner != null) + { // add to the shortcut caching system. - if (originalShortcut != Keys.None) { + if (originalShortcut != Keys.None) + { owner.Shortcuts.Remove(originalShortcut); } - if (owner.Shortcuts.Contains(value)) { + if (owner.Shortcuts.Contains(value)) + { // last one in wins. owner.Shortcuts[value] = this; } - else { + else + { owner.Shortcuts.Add(value, this); } } Properties.SetInteger(PropShortcutKeys, (int)value); - - if (ShowShortcutKeys && IsOnDropDown) { + + if (ShowShortcutKeys && IsOnDropDown) + { ToolStripDropDownMenu parent = GetCurrentParentDropDown() as ToolStripDropDownMenu; - if (parent != null) { + if (parent != null) + { LayoutTransaction.DoLayout(this.ParentInternal, this, "ShortcutKeys"); parent.AdjustSize(); } } } } - + } [ @@ -487,17 +566,23 @@ public Keys ShortcutKeys { DefaultValue(null), Localizable(true) ] - public string ShortcutKeyDisplayString { - get { + public string ShortcutKeyDisplayString + { + get + { return shortcutKeyDisplayString; } - set { - if (shortcutKeyDisplayString != value) { + set + { + if (shortcutKeyDisplayString != value) + { shortcutKeyDisplayString = value; ClearShortcutCache(); - if (ShowShortcutKeys) { + if (ShowShortcutKeys) + { ToolStripDropDown parent = this.ParentInternal as ToolStripDropDown; - if (parent != null) { + if (parent != null) + { LayoutTransaction.DoLayout(parent, this, "ShortcutKeyDisplayString"); parent.AdjustSize(); } @@ -505,7 +590,7 @@ public string ShortcutKeyDisplayString { } } } - + /// /// /// Gets or sets a value that indicates whether the shortcut @@ -519,19 +604,24 @@ public string ShortcutKeyDisplayString { Localizable(true), SRDescription(nameof(SR.MenuItemShowShortCutDescr)) ] - public bool ShowShortcutKeys { - get { + public bool ShowShortcutKeys + { + get + { return showShortcutKeys; } - set { - if (value != showShortcutKeys) { - ClearShortcutCache(); - showShortcutKeys = value; - ToolStripDropDown parent = this.ParentInternal as ToolStripDropDown; - if (parent != null) { + set + { + if (value != showShortcutKeys) + { + ClearShortcutCache(); + showShortcutKeys = value; + ToolStripDropDown parent = this.ParentInternal as ToolStripDropDown; + if (parent != null) + { LayoutTransaction.DoLayout(parent, this, "ShortcutKeys"); parent.AdjustSize(); - + } } } @@ -542,41 +632,51 @@ public bool ShowShortcutKeys { /// An item is toplevel if it is parented to anything other than a ToolStripDropDownMenu /// This implies that a ToolStripMenuItem in an overflow IS a toplevel item /// - internal bool IsTopLevel { - get { + internal bool IsTopLevel + { + get + { return (this.ParentInternal as ToolStripDropDown == null); } } [Browsable(false)] - public bool IsMdiWindowListEntry { - get{ + public bool IsMdiWindowListEntry + { + get + { return MdiForm != null; } } - internal static MenuTimer MenuTimer { - get { + internal static MenuTimer MenuTimer + { + get + { return menuTimer; } } - + /// Tag property for internal use - internal Form MdiForm { - get { - if (Properties.ContainsObject(PropMdiForm)) { + internal Form MdiForm + { + get + { + if (Properties.ContainsObject(PropMdiForm)) + { return Properties.GetObject(PropMdiForm) as Form; } return null; - + } } - internal ToolStripMenuItem Clone() { + internal ToolStripMenuItem Clone() + { // dirt simple clone - just properties, no subitems - + ToolStripMenuItem menuItem = new ToolStripMenuItem(); menuItem.Events.AddHandlers(this.Events); @@ -609,7 +709,7 @@ internal ToolStripMenuItem Clone() { menuItem.Name = this.Name; menuItem.Overflow = this.Overflow; menuItem.Padding = this.Padding; - menuItem.RightToLeft= this.RightToLeft; + menuItem.RightToLeft = this.RightToLeft; // No settings support for cloned items. // menuItem.SaveSettings= this.SaveSettings; @@ -628,31 +728,39 @@ internal ToolStripMenuItem Clone() { // is visible too.. instead use ParticipatesInLayout as this queries the actual state. menuItem.Visible = ((IArrangedElement)this).ParticipatesInLayout; - if (!AutoSize) { + if (!AutoSize) + { menuItem.Size = this.Size; } return menuItem; - } + } - protected override void Dispose(bool disposing) { - if (disposing) { - if (lastOwner != null) { + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (lastOwner != null) + { Keys shortcut = this.ShortcutKeys; - if (shortcut != Keys.None && lastOwner.Shortcuts.ContainsKey(shortcut)) { + if (shortcut != Keys.None && lastOwner.Shortcuts.ContainsKey(shortcut)) + { lastOwner.Shortcuts.Remove(shortcut); } lastOwner = null; - if (MdiForm != null) { - Properties.SetObject(PropMdiForm,null); + if (MdiForm != null) + { + Properties.SetObject(PropMdiForm, null); } - + } } base.Dispose(disposing); } - private bool GetNativeMenuItemEnabled() { - if (nativeMenuCommandID == -1 || nativeMenuHandle == IntPtr.Zero) { + private bool GetNativeMenuItemEnabled() + { + if (nativeMenuCommandID == -1 || nativeMenuHandle == IntPtr.Zero) + { Debug.Fail("why were we called to fetch native menu item info with nothing assigned?"); return false; } @@ -667,14 +775,16 @@ private bool GetNativeMenuItemEnabled() { } // returns text and shortcut separated by tab. - private string GetNativeMenuItemTextAndShortcut() { - - if (nativeMenuCommandID == -1 || nativeMenuHandle == IntPtr.Zero) { + private string GetNativeMenuItemTextAndShortcut() + { + + if (nativeMenuCommandID == -1 || nativeMenuHandle == IntPtr.Zero) + { Debug.Fail("why were we called to fetch native menu item info with nothing assigned?"); return null; } string text = null; - + // fetch the string length NativeMethods.MENUITEMINFO_T_RW info = new NativeMethods.MENUITEMINFO_T_RW(); info.fMask = NativeMethods.MIIM_STRING; @@ -683,26 +793,31 @@ private string GetNativeMenuItemTextAndShortcut() { info.dwTypeData = IntPtr.Zero; UnsafeNativeMethods.GetMenuItemInfo(new HandleRef(this, nativeMenuHandle), nativeMenuCommandID, /*fByPosition instead of ID=*/ false, info); - if (info.cch > 0) { + if (info.cch > 0) + { // fetch the string info.cch += 1; // according to MSDN we need to increment the count we receive by 1. info.wID = nativeMenuCommandID; IntPtr allocatedStringBuffer = Marshal.AllocCoTaskMem(info.cch * sizeof(char)); info.dwTypeData = allocatedStringBuffer; - - try { + + try + { UnsafeNativeMethods.GetMenuItemInfo(new HandleRef(this, nativeMenuHandle), nativeMenuCommandID, /*fByPosition instead of ID=*/ false, info); // convert the string into managed data. - if (info.dwTypeData != IntPtr.Zero){ + if (info.dwTypeData != IntPtr.Zero) + { // we have to use PtrToStringAuto as we can't use Marshal.SizeOf to determine // the size of the struct with a StringBuilder member. text = Marshal.PtrToStringAuto(info.dwTypeData, info.cch); } } - finally { - if (allocatedStringBuffer != IntPtr.Zero) { + finally + { + if (allocatedStringBuffer != IntPtr.Zero) + { // use our local instead of the info structure member *just* in case windows decides to clobber over it. // we want to be sure to deallocate the memory we know we allocated. Marshal.FreeCoTaskMem(allocatedStringBuffer); @@ -712,28 +827,33 @@ private string GetNativeMenuItemTextAndShortcut() { return text; } - - private Image GetNativeMenuItemImage(){ - if (nativeMenuCommandID == -1 || nativeMenuHandle == IntPtr.Zero) { + private Image GetNativeMenuItemImage() + { + + if (nativeMenuCommandID == -1 || nativeMenuHandle == IntPtr.Zero) + { Debug.Fail("why were we called to fetch native menu item info with nothing assigned?"); return null; } - + NativeMethods.MENUITEMINFO_T_RW info = new NativeMethods.MENUITEMINFO_T_RW(); info.fMask = NativeMethods.MIIM_BITMAP; info.fType = NativeMethods.MIIM_BITMAP; info.wID = nativeMenuCommandID; UnsafeNativeMethods.GetMenuItemInfo(new HandleRef(this, nativeMenuHandle), nativeMenuCommandID, /*fByPosition instead of ID=*/ false, info); - - if (info.hbmpItem != IntPtr.Zero && info.hbmpItem.ToInt32() > NativeMethods.HBMMENU_POPUP_MINIMIZE) { + + if (info.hbmpItem != IntPtr.Zero && info.hbmpItem.ToInt32() > NativeMethods.HBMMENU_POPUP_MINIMIZE) + { return Bitmap.FromHbitmap(info.hbmpItem); } - else { + else + { // its a system defined bitmap int buttonToUse = -1; - switch (info.hbmpItem.ToInt32()) { + switch (info.hbmpItem.ToInt32()) + { case NativeMethods.HBMMENU_MBAR_CLOSE: case NativeMethods.HBMMENU_MBAR_CLOSE_D: case NativeMethods.HBMMENU_POPUP_CLOSE: @@ -756,18 +876,20 @@ private Image GetNativeMenuItemImage(){ break; case NativeMethods.HBMMENU_SYSTEM: - // + // case NativeMethods.HBMMENU_CALLBACK: - // owner draw not supported - default: + // owner draw not supported + default: break; } - if (buttonToUse > -1) { + if (buttonToUse > -1) + { // we've mapped to a system defined bitmap we know how to draw Bitmap image = new Bitmap(16, 16); - using (Graphics g = Graphics.FromImage(image)) { + using (Graphics g = Graphics.FromImage(image)) + { ControlPaint.DrawCaptionButton(g, new Rectangle(Point.Empty, image.Size), (CaptionButton)buttonToUse, ButtonState.Flat); g.DrawRectangle(SystemPens.Control, 0, 0, image.Width - 1, image.Height - 1); } @@ -779,30 +901,38 @@ private Image GetNativeMenuItemImage(){ return null; } - - internal Size GetShortcutTextSize() { - if (!ShowShortcutKeys) { + + internal Size GetShortcutTextSize() + { + if (!ShowShortcutKeys) + { return Size.Empty; - } - string shortcutString = GetShortcutText(); - if (string.IsNullOrEmpty(shortcutString)) { + } + string shortcutString = GetShortcutText(); + if (string.IsNullOrEmpty(shortcutString)) + { return Size.Empty; - } - else if (cachedShortcutSize == Size.Empty) { + } + else if (cachedShortcutSize == Size.Empty) + { cachedShortcutSize = TextRenderer.MeasureText(shortcutString, Font); - } - return cachedShortcutSize; + } + return cachedShortcutSize; } - internal string GetShortcutText() { - if (cachedShortcutText == null) { - cachedShortcutText = ShortcutToText(this.ShortcutKeys, this.ShortcutKeyDisplayString); + internal string GetShortcutText() + { + if (cachedShortcutText == null) + { + cachedShortcutText = ShortcutToText(this.ShortcutKeys, this.ShortcutKeyDisplayString); } return cachedShortcutText; } - - internal void HandleAutoExpansion() { - if (Enabled && ParentInternal != null && ParentInternal.MenuAutoExpand && HasDropDownItems) { + + internal void HandleAutoExpansion() + { + if (Enabled && ParentInternal != null && ParentInternal.MenuAutoExpand && HasDropDownItems) + { ShowDropDown(); KeyboardToolTipStateMachine.Instance.NotifyAboutLostFocus(this); @@ -811,126 +941,149 @@ internal void HandleAutoExpansion() { } } - protected override void OnClick(EventArgs e) { - if (checkOnClick) { + protected override void OnClick(EventArgs e) + { + if (checkOnClick) + { this.Checked = !this.Checked; } base.OnClick(e); - if (nativeMenuCommandID != -1) { + if (nativeMenuCommandID != -1) + { // fire off the appropriate native handler by posting a message to the window target. - if ((nativeMenuCommandID & 0xF000) != 0) { + if ((nativeMenuCommandID & 0xF000) != 0) + { // These are system menu items like Minimize, Maximize, Restore, Resize, Move, Close. - + // use PostMessage instead of SendMessage so that the DefWndProc can appropriately handle // the system message... if we use SendMessage the dismissal of our window // breaks things like the modal sizing loop. - UnsafeNativeMethods.PostMessage( new HandleRef(this, targetWindowHandle), Interop.WindowMessages.WM_SYSCOMMAND,nativeMenuCommandID, 0); + UnsafeNativeMethods.PostMessage(new HandleRef(this, targetWindowHandle), Interop.WindowMessages.WM_SYSCOMMAND, nativeMenuCommandID, 0); } - else { + else + { // These are user added items like ".Net Window..." - + // be consistent with sending a WM_SYSCOMMAND, use POST not SEND. - UnsafeNativeMethods.PostMessage( new HandleRef(this, targetWindowHandle), Interop.WindowMessages.WM_COMMAND, nativeMenuCommandID, 0); + UnsafeNativeMethods.PostMessage(new HandleRef(this, targetWindowHandle), Interop.WindowMessages.WM_COMMAND, nativeMenuCommandID, 0); } this.Invalidate(); } - + } /// /// Raises the /// event. /// - protected virtual void OnCheckedChanged(EventArgs e) { + protected virtual void OnCheckedChanged(EventArgs e) + { EventHandler handler = (EventHandler)Events[EventCheckedChanged]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// /// Raises the event. /// - protected virtual void OnCheckStateChanged(EventArgs e) { + protected virtual void OnCheckStateChanged(EventArgs e) + { AccessibilityNotifyClients(AccessibleEvents.StateChange); EventHandler handler = (EventHandler)Events[EventCheckStateChanged]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } - protected override void OnDropDownHide(EventArgs e) { - + protected override void OnDropDownHide(EventArgs e) + { + Debug.WriteLineIf(ToolStrip.MenuAutoExpandDebug.TraceVerbose, "[ToolStripMenuItem.OnDropDownHide] MenuTimer.Cancel called"); MenuTimer.Cancel(this); base.OnDropDownHide(e); } - protected override void OnDropDownShow(EventArgs e) { + protected override void OnDropDownShow(EventArgs e) + { // if someone has beaten us to the punch by arrowing around // cancel the current menu timer. Debug.WriteLineIf(ToolStrip.MenuAutoExpandDebug.TraceVerbose, "[ToolStripMenuItem.OnDropDownShow] MenuTimer.Cancel called"); MenuTimer.Cancel(this); - if (ParentInternal != null) { + if (ParentInternal != null) + { ParentInternal.MenuAutoExpand = true; } base.OnDropDownShow(e); } - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { ClearShortcutCache(); base.OnFontChanged(e); } /// - internal void OnMenuAutoExpand() { + internal void OnMenuAutoExpand() + { this.ShowDropDown(); } - + /// - protected override void OnMouseDown(MouseEventArgs e) { + protected override void OnMouseDown(MouseEventArgs e) + { // Opening should happen on mouse down // we use a mouse down ID to ensure that the reshow - + Debug.WriteLineIf(ToolStrip.MenuAutoExpandDebug.TraceVerbose, "[ToolStripMenuItem.OnMouseDown] MenuTimer.Cancel called"); MenuTimer.Cancel(this); - OnMouseButtonStateChange(e, /*isMouseDown=*/true); - + OnMouseButtonStateChange(e, /*isMouseDown=*/true); + } - protected override void OnMouseUp(MouseEventArgs e) { - OnMouseButtonStateChange(e, /*isMouseDown=*/false); - base.OnMouseUp(e); + protected override void OnMouseUp(MouseEventArgs e) + { + OnMouseButtonStateChange(e, /*isMouseDown=*/false); + base.OnMouseUp(e); } - private void OnMouseButtonStateChange(MouseEventArgs e, bool isMouseDown) { + private void OnMouseButtonStateChange(MouseEventArgs e, bool isMouseDown) + { bool showDropDown = true; - if (IsOnDropDown) { - ToolStripDropDown dropDown = GetCurrentParentDropDown() as ToolStripDropDown; + if (IsOnDropDown) + { + ToolStripDropDown dropDown = GetCurrentParentDropDown() as ToolStripDropDown; - // Right click support for context menus. - // used in ToolStripItem to determine whether to fire click OnMouseUp. - SupportsRightClick = (dropDown.GetFirstDropDown() is ContextMenuStrip); + // Right click support for context menus. + // used in ToolStripItem to determine whether to fire click OnMouseUp. + SupportsRightClick = (dropDown.GetFirstDropDown() is ContextMenuStrip); } - else { - showDropDown = !DropDown.Visible; - SupportsRightClick = false; + else + { + showDropDown = !DropDown.Visible; + SupportsRightClick = false; } - if (e.Button == MouseButtons.Left || - (e.Button == MouseButtons.Right && SupportsRightClick)) { - - if (isMouseDown && showDropDown) { + if (e.Button == MouseButtons.Left || + (e.Button == MouseButtons.Right && SupportsRightClick)) + { + + if (isMouseDown && showDropDown) + { // opening should happen on mouse down. Debug.Assert(ParentInternal != null, "Parent is null here, not going to get accurate ID"); - openMouseId = (ParentInternal == null) ? (byte)0: ParentInternal.GetMouseId(); + openMouseId = (ParentInternal == null) ? (byte)0 : ParentInternal.GetMouseId(); this.ShowDropDown(/*mousePush =*/true); } - else if (!isMouseDown && !showDropDown) { + else if (!isMouseDown && !showDropDown) + { // closing should happen on mouse up. ensure it's not the mouse // up for the mouse down we opened with. Debug.Assert(ParentInternal != null, "Parent is null here, not going to get accurate ID"); - byte closeMouseId = (ParentInternal == null) ? (byte)0: ParentInternal.GetMouseId(); - int openedMouseID =openMouseId; - if (closeMouseId != openedMouseID) { + byte closeMouseId = (ParentInternal == null) ? (byte)0 : ParentInternal.GetMouseId(); + int openedMouseID = openMouseId; + if (closeMouseId != openedMouseID) + { openMouseId = 0; // reset the mouse id, we should never get this value from toolstrip. ToolStripManager.ModalMenuFilter.CloseActiveDropDown(DropDown, ToolStripDropDownCloseReason.AppClicked); Select(); @@ -941,51 +1094,60 @@ private void OnMouseButtonStateChange(MouseEventArgs e, bool isMouseDown) { } } - - + + /// - protected override void OnMouseEnter(EventArgs e) { - + protected override void OnMouseEnter(EventArgs e) + { + Debug.Assert(this.ParentInternal != null, "Why is parent null"); - + // If we are in a submenu pop down the submenu. - if (this.ParentInternal != null && this.ParentInternal.MenuAutoExpand && Selected) { + if (this.ParentInternal != null && this.ParentInternal.MenuAutoExpand && Selected) + { Debug.WriteLineIf(ToolStripItem.MouseDebugging.TraceVerbose, "received mouse enter - calling drop down"); Debug.WriteLineIf(ToolStrip.MenuAutoExpandDebug.TraceVerbose, "[ToolStripMenuItem.OnMouseEnter] MenuTimer.Cancel / MenuTimer.Start called"); - + MenuTimer.Cancel(this); MenuTimer.Start(this); - + } base.OnMouseEnter(e); } - + /// - protected override void OnMouseLeave(EventArgs e) { - Debug.WriteLineIf(ToolStrip.MenuAutoExpandDebug.TraceVerbose, "[ToolStripMenuItem.OnMouseLeave] MenuTimer.Cancel called"); - MenuTimer.Cancel(this); - base.OnMouseLeave(e); + protected override void OnMouseLeave(EventArgs e) + { + Debug.WriteLineIf(ToolStrip.MenuAutoExpandDebug.TraceVerbose, "[ToolStripMenuItem.OnMouseLeave] MenuTimer.Cancel called"); + MenuTimer.Cancel(this); + base.OnMouseLeave(e); } - protected override void OnOwnerChanged(EventArgs e) { + protected override void OnOwnerChanged(EventArgs e) + { Keys shortcut = this.ShortcutKeys; - if (shortcut != Keys.None) { - if (lastOwner != null) { + if (shortcut != Keys.None) + { + if (lastOwner != null) + { lastOwner.Shortcuts.Remove(shortcut); } - if (Owner != null) { - if (Owner.Shortcuts.Contains(shortcut)) { + if (Owner != null) + { + if (Owner.Shortcuts.Contains(shortcut)) + { // last one in wins Owner.Shortcuts[shortcut] = this; - } - else { + } + else + { Owner.Shortcuts.Add(shortcut, this); - } - lastOwner = Owner; + } + lastOwner = Owner; } } @@ -993,172 +1155,206 @@ protected override void OnOwnerChanged(EventArgs e) { } /// - protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { + protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) + { - if (this.Owner != null) { + if (this.Owner != null) + { ToolStripRenderer renderer = this.Renderer; Graphics g = e.Graphics; renderer.DrawMenuItemBackground(new ToolStripItemRenderEventArgs(g, this)); Color textColor = SystemColors.MenuText; - if (IsForeColorSet) { - textColor = this.ForeColor; + if (IsForeColorSet) + { + textColor = this.ForeColor; } - else if (!this.IsTopLevel || (ToolStripManager.VisualStylesEnabled)) { - if (Selected || Pressed) { + else if (!this.IsTopLevel || (ToolStripManager.VisualStylesEnabled)) + { + if (Selected || Pressed) + { textColor = SystemColors.HighlightText; } - else { - textColor = SystemColors.MenuText; + else + { + textColor = SystemColors.MenuText; } } bool rightToLeft = (RightToLeft == RightToLeft.Yes); - + ToolStripMenuItemInternalLayout menuItemInternalLayout = this.InternalLayout as ToolStripMenuItemInternalLayout; - if (menuItemInternalLayout != null && menuItemInternalLayout.UseMenuLayout) { - + if (menuItemInternalLayout != null && menuItemInternalLayout.UseMenuLayout) + { + // Support for special DropDownMenu layout - #if DEBUG_PAINT +#if DEBUG_PAINT g.DrawRectangle(Pens.Green, menuItemInternalLayout.TextRectangle); g.DrawRectangle(Pens.HotPink, menuItemInternalLayout.ImageRectangle); g.DrawRectangle(Pens.Black, menuItemInternalLayout.CheckRectangle); g.DrawRectangle(Pens.Red, menuItemInternalLayout.ArrowRectangle); g.DrawRectangle(Pens.Blue, new Rectangle(Point.Empty, new Size(-1,-1) + this.Size)); - #endif - if (CheckState != CheckState.Unchecked && menuItemInternalLayout.PaintCheck) { +#endif + if (CheckState != CheckState.Unchecked && menuItemInternalLayout.PaintCheck) + { Rectangle checkRectangle = menuItemInternalLayout.CheckRectangle; - if (!menuItemInternalLayout.ShowCheckMargin) { - checkRectangle = menuItemInternalLayout.ImageRectangle; + if (!menuItemInternalLayout.ShowCheckMargin) + { + checkRectangle = menuItemInternalLayout.ImageRectangle; } - if (checkRectangle.Width != 0) { + if (checkRectangle.Width != 0) + { renderer.DrawItemCheck(new ToolStripItemImageRenderEventArgs(g, this, CheckedImage, checkRectangle)); } } - - - if ((DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) { + + + if ((DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) + { // render text AND shortcut renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, this.Text, InternalLayout.TextRectangle, textColor, this.Font, (rightToLeft) ? ContentAlignment.MiddleRight : ContentAlignment.MiddleLeft)); bool showShortCut = ShowShortcutKeys; - if (!DesignMode){ + if (!DesignMode) + { showShortCut = showShortCut && !HasDropDownItems; } - - if (showShortCut) { + + if (showShortCut) + { renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, GetShortcutText(), InternalLayout.TextRectangle, textColor, this.Font, (rightToLeft) ? ContentAlignment.MiddleLeft : ContentAlignment.MiddleRight)); } - } + } - if (HasDropDownItems) { + if (HasDropDownItems) + { ArrowDirection arrowDir = (rightToLeft) ? ArrowDirection.Left : ArrowDirection.Right; - Color arrowColor = (Selected ||Pressed) ? SystemColors.HighlightText : SystemColors.MenuText; - arrowColor = (Enabled) ? arrowColor : SystemColors.ControlDark; - renderer.DrawArrow(new ToolStripArrowRenderEventArgs(g, this, menuItemInternalLayout.ArrowRectangle, arrowColor, arrowDir)); + Color arrowColor = (Selected || Pressed) ? SystemColors.HighlightText : SystemColors.MenuText; + arrowColor = (Enabled) ? arrowColor : SystemColors.ControlDark; + renderer.DrawArrow(new ToolStripArrowRenderEventArgs(g, this, menuItemInternalLayout.ArrowRectangle, arrowColor, arrowDir)); } - if (menuItemInternalLayout.PaintImage && (DisplayStyle & ToolStripItemDisplayStyle.Image) == ToolStripItemDisplayStyle.Image && Image != null) { - renderer.DrawItemImage(new ToolStripItemImageRenderEventArgs(g, this, InternalLayout.ImageRectangle)); + if (menuItemInternalLayout.PaintImage && (DisplayStyle & ToolStripItemDisplayStyle.Image) == ToolStripItemDisplayStyle.Image && Image != null) + { + renderer.DrawItemImage(new ToolStripItemImageRenderEventArgs(g, this, InternalLayout.ImageRectangle)); } - + } - else { - + else + { + // Toplevel item support, menu items hosted on a plain ToolStrip dropdown - if ((DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) { + if ((DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) + { renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, this.Text, InternalLayout.TextRectangle, textColor, this.Font, InternalLayout.TextFormat)); } - - if ((DisplayStyle & ToolStripItemDisplayStyle.Image) == ToolStripItemDisplayStyle.Image && Image != null) { - renderer.DrawItemImage(new ToolStripItemImageRenderEventArgs(g, this, InternalLayout.ImageRectangle)); + + if ((DisplayStyle & ToolStripItemDisplayStyle.Image) == ToolStripItemDisplayStyle.Image && Image != null) + { + renderer.DrawItemImage(new ToolStripItemImageRenderEventArgs(g, this, InternalLayout.ImageRectangle)); } } - - } - + + } + } /// /// handle shortcut keys here. /// - protected internal override bool ProcessCmdKey(ref Message m, Keys keyData) { + protected internal override bool ProcessCmdKey(ref Message m, Keys keyData) + { - if (Enabled && ShortcutKeys == keyData && !HasDropDownItems) { + if (Enabled && ShortcutKeys == keyData && !HasDropDownItems) + { FireEvent(ToolStripItemEventType.Click); return true; } // call base here to get ESC, ALT, etc.. handling. - return base.ProcessCmdKey(ref m, keyData); + return base.ProcessCmdKey(ref m, keyData); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] // 'charCode' matches control.cs - protected internal override bool ProcessMnemonic(char charCode) { - // no need to check IsMnemonic, toolstrip.ProcessMnemonic checks this already. - if (HasDropDownItems) { - Select(); - ShowDropDown(); + protected internal override bool ProcessMnemonic(char charCode) + { + // no need to check IsMnemonic, toolstrip.ProcessMnemonic checks this already. + if (HasDropDownItems) + { + Select(); + ShowDropDown(); - KeyboardToolTipStateMachine.Instance.NotifyAboutLostFocus(this); + KeyboardToolTipStateMachine.Instance.NotifyAboutLostFocus(this); - DropDown.SelectNextToolStripItem(null, /*forward=*/true); - return true; - } - - return base.ProcessMnemonic(charCode); + DropDown.SelectNextToolStripItem(null, /*forward=*/true); + return true; + } + + return base.ProcessMnemonic(charCode); } /// overridden here so we scooch over when we're in the ToolStripDropDownMenu - internal protected override void SetBounds(Rectangle rect) { + internal protected override void SetBounds(Rectangle rect) + { ToolStripMenuItemInternalLayout internalLayout = InternalLayout as ToolStripMenuItemInternalLayout; - if (internalLayout != null && internalLayout.UseMenuLayout) { - ToolStripDropDownMenu dropDownMenu = Owner as ToolStripDropDownMenu; - - // Scooch over by the padding amount. The padding is added to - // the ToolStripDropDownMenu to keep the non-menu item riffraff - // aligned to the text rectangle. When flow layout comes through to set our position - // via IArrangedElement DEFY IT! - if (dropDownMenu != null) { + if (internalLayout != null && internalLayout.UseMenuLayout) + { + ToolStripDropDownMenu dropDownMenu = Owner as ToolStripDropDownMenu; + + // Scooch over by the padding amount. The padding is added to + // the ToolStripDropDownMenu to keep the non-menu item riffraff + // aligned to the text rectangle. When flow layout comes through to set our position + // via IArrangedElement DEFY IT! + if (dropDownMenu != null) + { rect.X -= dropDownMenu.Padding.Left; - rect.X = Math.Max(rect.X,0); - } + rect.X = Math.Max(rect.X, 0); + } } - base.SetBounds(rect); + base.SetBounds(rect); } /// this is to support routing to native menu commands - internal void SetNativeTargetWindow(IWin32Window window) { + internal void SetNativeTargetWindow(IWin32Window window) + { targetWindowHandle = Control.GetSafeHandle(window); } - + /// this is to support routing to native menu commands - internal void SetNativeTargetMenu(IntPtr hMenu) { + internal void SetNativeTargetMenu(IntPtr hMenu) + { nativeMenuHandle = hMenu; } - internal static string ShortcutToText(Keys shortcutKeys, string shortcutKeyDisplayString) { - if (!string.IsNullOrEmpty(shortcutKeyDisplayString)) { + internal static string ShortcutToText(Keys shortcutKeys, string shortcutKeyDisplayString) + { + if (!string.IsNullOrEmpty(shortcutKeyDisplayString)) + { return shortcutKeyDisplayString; } - else if (shortcutKeys == Keys.None) { + else if (shortcutKeys == Keys.None) + { return string.Empty; } - else { + else + { return TypeDescriptor.GetConverter(typeof(Keys)).ConvertToString(shortcutKeys); } } - internal override bool IsBeingTabbedTo() { - if (base.IsBeingTabbedTo()) { + internal override bool IsBeingTabbedTo() + { + if (base.IsBeingTabbedTo()) + { return true; } - if (ToolStripManager.ModalMenuFilter.InMenuMode) { + if (ToolStripManager.ModalMenuFilter.InMenuMode) + { return true; } @@ -1168,290 +1364,360 @@ internal override bool IsBeingTabbedTo() { /// /// An implementation of AccessibleChild for use with ToolStripItems /// - [System.Runtime.InteropServices.ComVisible(true)] - internal class ToolStripMenuItemAccessibleObject : ToolStripDropDownItemAccessibleObject { + [System.Runtime.InteropServices.ComVisible(true)] + internal class ToolStripMenuItemAccessibleObject : ToolStripDropDownItemAccessibleObject + { private ToolStripMenuItem ownerItem = null; - public ToolStripMenuItemAccessibleObject(ToolStripMenuItem ownerItem) : base(ownerItem) { - this.ownerItem = ownerItem; + public ToolStripMenuItemAccessibleObject(ToolStripMenuItem ownerItem) : base(ownerItem) + { + this.ownerItem = ownerItem; } - public override AccessibleStates State { - get { - if (ownerItem.Enabled ) { - AccessibleStates state = base.State; + public override AccessibleStates State + { + get + { + if (ownerItem.Enabled) + { + AccessibleStates state = base.State; + + if ((state & AccessibleStates.Pressed) == AccessibleStates.Pressed) + { + // for some reason menu items are never "pressed". + state &= ~AccessibleStates.Pressed; + } - if ((state & AccessibleStates.Pressed) == AccessibleStates.Pressed){ - // for some reason menu items are never "pressed". - state &= ~AccessibleStates.Pressed; - } - - if (ownerItem.Checked) { - state |= AccessibleStates.Checked; - } - return state; - } - return base.State; + if (ownerItem.Checked) + { + state |= AccessibleStates.Checked; + } + return state; + } + return base.State; } } - - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_ControlTypePropertyId) { + + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_ControlTypePropertyId) + { return NativeMethods.UIA_MenuItemControlTypeId; } - else if (propertyID == NativeMethods.UIA_AcceleratorKeyPropertyId) { + else if (propertyID == NativeMethods.UIA_AcceleratorKeyPropertyId) + { return ownerItem.GetShortcutText(); } - else { + else + { return base.GetPropertyValue(propertyID); } } } - } + } + + internal class MenuTimer + { - internal class MenuTimer { + private System.Windows.Forms.Timer autoMenuExpandTimer = new System.Windows.Forms.Timer(); - private System.Windows.Forms.Timer autoMenuExpandTimer = new System.Windows.Forms.Timer(); - // consider - weak reference? private ToolStripMenuItem currentItem = null; private ToolStripMenuItem fromItem = null; private bool inTransition = false; - + private int quickShow = 1; - - private int slowShow; - - public MenuTimer() { + + private int slowShow; + + public MenuTimer() + { // MenuShowDelay can be set to 0. In this case, set to something low so it's inperceptable. - autoMenuExpandTimer.Tick += new EventHandler(OnTick); + autoMenuExpandTimer.Tick += new EventHandler(OnTick); // since MenuShowDelay is registry tweakable we've gotta make sure we've got some sort // of interval - slowShow = Math.Max(quickShow, SystemInformation.MenuShowDelay); - + slowShow = Math.Max(quickShow, SystemInformation.MenuShowDelay); + } // the current item to autoexpand. - private ToolStripMenuItem CurrentItem { - get { + private ToolStripMenuItem CurrentItem + { + get + { return currentItem; } - set{ + set + { Debug.WriteLineIf(ToolStrip.MenuAutoExpandDebug.TraceVerbose && currentItem != value, "[MenuTimer.CurrentItem] changed: " + ((value == null) ? "null" : value.ToString())); - currentItem = value; + currentItem = value; } } - public bool InTransition { + public bool InTransition + { get { return inTransition; } set { inTransition = value; } } - - public void Start(ToolStripMenuItem item) { - if (InTransition) { + + public void Start(ToolStripMenuItem item) + { + if (InTransition) + { return; } StartCore(item); } - private void StartCore(ToolStripMenuItem item) { - if (item != CurrentItem) { + private void StartCore(ToolStripMenuItem item) + { + if (item != CurrentItem) + { Cancel(CurrentItem); } CurrentItem = item; - if (item != null) { + if (item != null) + { CurrentItem = item; autoMenuExpandTimer.Interval = item.IsOnDropDown ? slowShow : quickShow; autoMenuExpandTimer.Enabled = true; } - } + } - public void Transition(ToolStripMenuItem fromItem, ToolStripMenuItem toItem) { + public void Transition(ToolStripMenuItem fromItem, ToolStripMenuItem toItem) + { Debug.WriteLineIf(ToolStrip.MenuAutoExpandDebug.TraceVerbose, "[MenuTimer.Transition] transitioning items " + fromItem.ToString() + " " + toItem.ToString()); - if (toItem == null && InTransition) { + if (toItem == null && InTransition) + { Cancel(); // in this case we're likely to have hit an item that's not a menu item // or nothing is selected. EndTransition(/*forceClose*/ true); return; } - - if (this.fromItem != fromItem) { - this.fromItem = fromItem; - CancelCore(); - StartCore(toItem); + + if (this.fromItem != fromItem) + { + this.fromItem = fromItem; + CancelCore(); + StartCore(toItem); } // set up the current item to be the toItem so it will be auto expanded when complete. CurrentItem = toItem; InTransition = true; - + } - public void Cancel() { - if (InTransition) { + public void Cancel() + { + if (InTransition) + { return; } CancelCore(); - + } /// cancels if and only if this item was the one that /// requested the timer /// - public void Cancel(ToolStripMenuItem item) { - if (InTransition) { + public void Cancel(ToolStripMenuItem item) + { + if (InTransition) + { return; } - if (item == CurrentItem) { + if (item == CurrentItem) + { CancelCore(); - } + } } - private void CancelCore() { + private void CancelCore() + { autoMenuExpandTimer.Enabled = false; CurrentItem = null; } - private void EndTransition(bool forceClose) { + private void EndTransition(bool forceClose) + { ToolStripMenuItem lastSelected = fromItem; fromItem = null; // immediately clear BEFORE we call user code. - if (InTransition) { + if (InTransition) + { InTransition = false; - + // we should roolup if the current item has changed and is selected. bool rollup = forceClose || (CurrentItem != null && CurrentItem != lastSelected && CurrentItem.Selected); - if (rollup && lastSelected != null && lastSelected.HasDropDownItems) { - lastSelected.HideDropDown(); + if (rollup && lastSelected != null && lastSelected.HasDropDownItems) + { + lastSelected.HideDropDown(); } } } - internal void HandleToolStripMouseLeave(ToolStrip toolStrip) { - if (InTransition && toolStrip == fromItem.ParentInternal) { + internal void HandleToolStripMouseLeave(ToolStrip toolStrip) + { + if (InTransition && toolStrip == fromItem.ParentInternal) + { // restore the selection back to CurrentItem. // we're about to fall off the edge of the toolstrip, something should be selected // at all times while we're InTransition mode - otherwise it looks really funny // to have an auto expanded item - if (CurrentItem != null) { + if (CurrentItem != null) + { CurrentItem.Select(); } } - else { + else + { // because we've split up selected/pressed, we need to make sure // that onmouseleave we make sure there's a selected menu item. - if (toolStrip.IsDropDown && toolStrip.ActiveDropDowns.Count > 0) { + if (toolStrip.IsDropDown && toolStrip.ActiveDropDowns.Count > 0) + { ToolStripDropDown dropDown = toolStrip.ActiveDropDowns[0] as ToolStripDropDown; - - ToolStripMenuItem menuItem = (dropDown == null) ? null : dropDown.OwnerItem as ToolStripMenuItem; - if (menuItem != null && menuItem.Pressed) { + + ToolStripMenuItem menuItem = (dropDown == null) ? null : dropDown.OwnerItem as ToolStripMenuItem; + if (menuItem != null && menuItem.Pressed) + { menuItem.Select(); - } + } } } } - private void OnTick(object sender, EventArgs e) { + private void OnTick(object sender, EventArgs e) + { autoMenuExpandTimer.Enabled = false; - - if (CurrentItem == null) { + + if (CurrentItem == null) + { return; } EndTransition(/*forceClose*/false); - if (CurrentItem != null && !CurrentItem.IsDisposed && CurrentItem.Selected && CurrentItem.Enabled && ToolStripManager.ModalMenuFilter.InMenuMode) { + if (CurrentItem != null && !CurrentItem.IsDisposed && CurrentItem.Selected && CurrentItem.Enabled && ToolStripManager.ModalMenuFilter.InMenuMode) + { Debug.WriteLineIf(ToolStrip.MenuAutoExpandDebug.TraceVerbose, "[MenuTimer.OnTick] calling OnMenuAutoExpand"); CurrentItem.OnMenuAutoExpand(); } } - + } - internal class ToolStripMenuItemInternalLayout : ToolStripItemInternalLayout { + internal class ToolStripMenuItemInternalLayout : ToolStripItemInternalLayout + { private ToolStripMenuItem ownerItem; - - public ToolStripMenuItemInternalLayout(ToolStripMenuItem ownerItem) : base(ownerItem) { - this.ownerItem = ownerItem; + + public ToolStripMenuItemInternalLayout(ToolStripMenuItem ownerItem) : base(ownerItem) + { + this.ownerItem = ownerItem; } - public bool ShowCheckMargin { - get{ + public bool ShowCheckMargin + { + get + { ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu; - if (menu != null) { + if (menu != null) + { return menu.ShowCheckMargin; } return false; } } - public bool ShowImageMargin { - get{ + public bool ShowImageMargin + { + get + { ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu; - if (menu != null) { + if (menu != null) + { return menu.ShowImageMargin; } return false; } } - public bool PaintCheck { - get { + public bool PaintCheck + { + get + { return ShowCheckMargin || ShowImageMargin; } } - - public bool PaintImage { - get { + + public bool PaintImage + { + get + { return ShowImageMargin; } } - public Rectangle ArrowRectangle { - get { - if (UseMenuLayout) { - ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu; - if (menu != null) { + public Rectangle ArrowRectangle + { + get + { + if (UseMenuLayout) + { + ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu; + if (menu != null) + { // since menuItem.Padding isnt taken into consideration, we've got to recalc the centering of // the arrow rect per item Rectangle arrowRect = menu.ArrowRectangle; arrowRect.Y = LayoutUtils.VAlign(arrowRect.Size, ownerItem.ClientBounds, ContentAlignment.MiddleCenter).Y; return arrowRect; - } - } - return Rectangle.Empty; - } - } - public Rectangle CheckRectangle { - get { - if (UseMenuLayout) { - ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu; - if (menu != null) { - Rectangle checkRectangle = menu.CheckRectangle; - if (ownerItem.CheckedImage != null) { - int imageHeight = ownerItem.CheckedImage.Height; - // make sure we're vertically centered - checkRectangle.Y += (checkRectangle.Height - imageHeight)/2; - checkRectangle.Height = imageHeight; - return checkRectangle; - } - } - } - return Rectangle.Empty; - } - } - public override Rectangle ImageRectangle { - get { - if (UseMenuLayout) { + } + } + return Rectangle.Empty; + } + } + public Rectangle CheckRectangle + { + get + { + if (UseMenuLayout) + { + ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu; + if (menu != null) + { + Rectangle checkRectangle = menu.CheckRectangle; + if (ownerItem.CheckedImage != null) + { + int imageHeight = ownerItem.CheckedImage.Height; + // make sure we're vertically centered + checkRectangle.Y += (checkRectangle.Height - imageHeight) / 2; + checkRectangle.Height = imageHeight; + return checkRectangle; + } + } + } + return Rectangle.Empty; + } + } + public override Rectangle ImageRectangle + { + get + { + if (UseMenuLayout) + { ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu; - if (menu != null) { + if (menu != null) + { // since menuItem.Padding isnt taken into consideration, we've got to recalc the centering of // the image rect per item Rectangle imageRect = menu.ImageRectangle; - if (ownerItem.ImageScaling == ToolStripItemImageScaling.SizeToFit) { + if (ownerItem.ImageScaling == ToolStripItemImageScaling.SizeToFit) + { imageRect.Size = menu.ImageScalingSize; } - else { + else + { //If we don't have an image, use the CheckedImage Image image = ownerItem.Image ?? ownerItem.CheckedImage; imageRect.Size = image.Size; @@ -1463,34 +1729,43 @@ public override Rectangle ImageRectangle { return base.ImageRectangle; } } - - public override Rectangle TextRectangle { - get { - if (UseMenuLayout) { + + public override Rectangle TextRectangle + { + get + { + if (UseMenuLayout) + { ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu; - if (menu != null) { + if (menu != null) + { return menu.TextRectangle; } } return base.TextRectangle; } } - - public bool UseMenuLayout { - get { - return ownerItem.Owner is ToolStripDropDownMenu; + + public bool UseMenuLayout + { + get + { + return ownerItem.Owner is ToolStripDropDownMenu; } } - public override Size GetPreferredSize(Size constrainingSize) { - if (UseMenuLayout) { + public override Size GetPreferredSize(Size constrainingSize) + { + if (UseMenuLayout) + { ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu; - if (menu != null) { + if (menu != null) + { return menu.MaxItemSize; } } return base.GetPreferredSize(constrainingSize); } } - - } + +} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripOverflow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripOverflow.cs index ed8838500fc..296863e26a0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripOverflow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripOverflow.cs @@ -22,57 +22,72 @@ public class ToolStripOverflow : ToolStripDropDown, IArrangedElement private ToolStripOverflowButton ownerItem; - public ToolStripOverflow (ToolStripItem parentItem) : base(parentItem) { - if (parentItem == null) { + public ToolStripOverflow(ToolStripItem parentItem) : base(parentItem) + { + if (parentItem == null) + { throw new ArgumentNullException(nameof(parentItem)); } ownerItem = parentItem as ToolStripOverflowButton; } - protected internal override ToolStripItemCollection DisplayedItems { - get { - if (ParentToolStrip != null) { - ToolStripItemCollection items = ParentToolStrip.OverflowItems; + protected internal override ToolStripItemCollection DisplayedItems + { + get + { + if (ParentToolStrip != null) + { + ToolStripItemCollection items = ParentToolStrip.OverflowItems; return items; } return new ToolStripItemCollection(null, false); - } + } } - public override ToolStripItemCollection Items { - get { + public override ToolStripItemCollection Items + { + get + { return new ToolStripItemCollection(null, /*ownedCollection=*/false, /*readonly=*/true); - } - } + } + } - private ToolStrip ParentToolStrip { - get { - if (ownerItem != null) { - return ownerItem.ParentToolStrip; + private ToolStrip ParentToolStrip + { + get + { + if (ownerItem != null) + { + return ownerItem.ParentToolStrip; } return null; } } - ArrangedElementCollection IArrangedElement.Children { + ArrangedElementCollection IArrangedElement.Children + { get { return DisplayedItems; } } - - IArrangedElement IArrangedElement.Container { + + IArrangedElement IArrangedElement.Container + { get { return ParentInternal; } } - - bool IArrangedElement.ParticipatesInLayout { + + bool IArrangedElement.ParticipatesInLayout + { get { return GetState(STATE_VISIBLE); } } - - PropertyStore IArrangedElement.Properties { + + PropertyStore IArrangedElement.Properties + { get { return Properties; } } - - void IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) { + + void IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) + { SetBoundsCore(bounds.X, bounds.Y, bounds.Width, bounds.Height, specified); } @@ -80,51 +95,65 @@ void IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) { /// Summary of CreateLayoutEngine. /// /// - public override LayoutEngine LayoutEngine { - get { - return FlowLayout.Instance; + public override LayoutEngine LayoutEngine + { + get + { + return FlowLayout.Instance; } } - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new ToolStripOverflowAccessibleObject(this); } [SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces")] - public override Size GetPreferredSize(Size constrainingSize) { + public override Size GetPreferredSize(Size constrainingSize) + { constrainingSize.Width = 200; return base.GetPreferredSize(constrainingSize); } - protected override void OnLayout(LayoutEventArgs e) { + protected override void OnLayout(LayoutEventArgs e) + { - if (ParentToolStrip != null && ParentToolStrip.IsInDesignMode) { - if (FlowLayout.GetFlowDirection(this) != FlowDirection.TopDown) { + if (ParentToolStrip != null && ParentToolStrip.IsInDesignMode) + { + if (FlowLayout.GetFlowDirection(this) != FlowDirection.TopDown) + { FlowLayout.SetFlowDirection(this, FlowDirection.TopDown); } - if (FlowLayout.GetWrapContents(this)) { + if (FlowLayout.GetWrapContents(this)) + { FlowLayout.SetWrapContents(this, false); } } - else { - if (FlowLayout.GetFlowDirection(this) != FlowDirection.LeftToRight) { + else + { + if (FlowLayout.GetFlowDirection(this) != FlowDirection.LeftToRight) + { FlowLayout.SetFlowDirection(this, FlowDirection.LeftToRight); } - if (!FlowLayout.GetWrapContents(this)) { - FlowLayout.SetWrapContents(this, true); + if (!FlowLayout.GetWrapContents(this)) + { + FlowLayout.SetWrapContents(this, true); } } base.OnLayout(e); } - protected override void SetDisplayedItems() { + protected override void SetDisplayedItems() + { // do nothing here.... this is really for the setting the overflow/displayed items on the // main ToolStrip. Our working item collection is our displayed item collection... calling // base would clear it out. Size biggestItemSize = Size.Empty; - for (int j = 0; j < DisplayedItems.Count; j++) { + for (int j = 0; j < DisplayedItems.Count; j++) + { ToolStripItem item = DisplayedItems[j]; - if (((IArrangedElement)item).ParticipatesInLayout) { + if (((IArrangedElement)item).ParticipatesInLayout) + { HasVisibleItems = true; biggestItemSize = LayoutUtils.UnionSizes(biggestItemSize, item.Bounds.Size); } @@ -132,16 +161,20 @@ protected override void SetDisplayedItems() { SetLargestItemSize(biggestItemSize); } - internal class ToolStripOverflowAccessibleObject : ToolStripAccessibleObject { + internal class ToolStripOverflowAccessibleObject : ToolStripAccessibleObject + { public ToolStripOverflowAccessibleObject(ToolStripOverflow owner) - : base(owner) { + : base(owner) + { } - public override AccessibleObject GetChild(int index) { + public override AccessibleObject GetChild(int index) + { return ((ToolStripOverflow)Owner).DisplayedItems[index].AccessibilityObject; } - public override int GetChildCount() { + public override int GetChildCount() + { return ((ToolStripOverflow)Owner).DisplayedItems.Count; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripOverflowButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripOverflowButton.cs index 449f11eb10b..62bc7f8e8d0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripOverflowButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripOverflowButton.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Collections; using System.ComponentModel; @@ -15,19 +16,21 @@ namespace System.Windows.Forms { /// ToolStripOverflowButton /// [ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.None)] - public class ToolStripOverflowButton : ToolStripDropDownButton { + public class ToolStripOverflowButton : ToolStripDropDownButton + { // we need to cache this away as the Parent property gets reset a lot. private ToolStrip parentToolStrip; - + private static bool isScalingInitialized = false; private const int MAX_WIDTH = 16; private const int MAX_HEIGHT = 16; private static int maxWidth = MAX_WIDTH; private static int maxHeight = MAX_HEIGHT; - - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] - internal ToolStripOverflowButton(ToolStrip parentToolStrip) { + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] + internal ToolStripOverflowButton(ToolStrip parentToolStrip) + { if (!isScalingInitialized) { if (DpiHelper.IsScalingRequired) @@ -42,33 +45,41 @@ internal ToolStripOverflowButton(ToolStrip parentToolStrip) { SupportsItemClick = false; this.parentToolStrip = parentToolStrip; } - - protected override void Dispose(bool disposing) { - if (disposing && this.HasDropDownItems) { + + protected override void Dispose(bool disposing) + { + if (disposing && this.HasDropDownItems) + { this.DropDown.Dispose(); } base.Dispose(disposing); } - protected internal override Padding DefaultMargin { - get { + protected internal override Padding DefaultMargin + { + get + { return Padding.Empty; } } - public override bool HasDropDownItems { - get { + public override bool HasDropDownItems + { + get + { return this.ParentInternal.OverflowItems.Count > 0; } } - internal override bool OppositeDropDownAlign { + internal override bool OppositeDropDownAlign + { get { return true; } } - internal ToolStrip ParentToolStrip { + internal ToolStrip ParentToolStrip + { get { return parentToolStrip; } } [ @@ -76,47 +87,60 @@ internal ToolStrip ParentToolStrip { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new bool RightToLeftAutoMirrorImage { - get { + public new bool RightToLeftAutoMirrorImage + { + get + { return base.RightToLeftAutoMirrorImage; } - set { + set + { base.RightToLeftAutoMirrorImage = value; } } - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new ToolStripOverflowButtonAccessibleObject(this); } - protected override ToolStripDropDown CreateDefaultDropDown() { + protected override ToolStripDropDown CreateDefaultDropDown() + { // AutoGenerate a ToolStrip DropDown - set the property so we hook events - return new ToolStripOverflow(this); + return new ToolStripOverflow(this); } - - public override Size GetPreferredSize(Size constrainingSize) { + + public override Size GetPreferredSize(Size constrainingSize) + { Size preferredSize = constrainingSize; - if (this.ParentInternal != null) { - if (this.ParentInternal.Orientation == Orientation.Horizontal) { - preferredSize.Width = Math.Min(constrainingSize.Width, maxWidth); - } - else { - preferredSize.Height = Math.Min(constrainingSize.Height, maxHeight); - } + if (this.ParentInternal != null) + { + if (this.ParentInternal.Orientation == Orientation.Horizontal) + { + preferredSize.Width = Math.Min(constrainingSize.Width, maxWidth); + } + else + { + preferredSize.Height = Math.Min(constrainingSize.Height, maxHeight); + } } return preferredSize + this.Padding.Size; } // make sure the Overflow button extends from edge-edge. (Ignore Padding/Margin). - internal protected override void SetBounds(Rectangle bounds) { - if (ParentInternal != null && ParentInternal.LayoutEngine is ToolStripSplitStackLayout) { - - if (ParentInternal.Orientation == Orientation.Horizontal) { + internal protected override void SetBounds(Rectangle bounds) + { + if (ParentInternal != null && ParentInternal.LayoutEngine is ToolStripSplitStackLayout) + { + + if (ParentInternal.Orientation == Orientation.Horizontal) + { bounds.Height = ParentInternal.Height; bounds.Y = 0; } - else { + else + { bounds.Width = ParentInternal.Width; bounds.X = 0; } @@ -124,38 +148,49 @@ internal protected override void SetBounds(Rectangle bounds) { base.SetBounds(bounds); } - protected override void OnPaint(PaintEventArgs e) { - if (this.ParentInternal != null) { - ToolStripRenderer renderer = this.ParentInternal.Renderer; + protected override void OnPaint(PaintEventArgs e) + { + if (this.ParentInternal != null) + { + ToolStripRenderer renderer = this.ParentInternal.Renderer; renderer.DrawOverflowButtonBackground(new ToolStripItemRenderEventArgs(e.Graphics, this)); } } - internal class ToolStripOverflowButtonAccessibleObject : ToolStripDropDownItemAccessibleObject { + internal class ToolStripOverflowButtonAccessibleObject : ToolStripDropDownItemAccessibleObject + { private string stockName; - public ToolStripOverflowButtonAccessibleObject(ToolStripOverflowButton owner) : base(owner){ + public ToolStripOverflowButtonAccessibleObject(ToolStripOverflowButton owner) : base(owner) + { } - - - public override string Name { - get { + + + public override string Name + { + get + { string name = Owner.AccessibleName; - if (name != null) { + if (name != null) + { return name; } - if (string.IsNullOrEmpty(stockName)) { + if (string.IsNullOrEmpty(stockName)) + { stockName = SR.ToolStripOptions; } return stockName; } - set { - base.Name = value; + set + { + base.Name = value; } } - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_ControlTypePropertyId) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_ControlTypePropertyId) + { return NativeMethods.UIA_MenuItemControlTypeId; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs index 0c38866a240..7df74f11d84 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs @@ -6,7 +6,8 @@ -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Drawing; using System.Windows.Forms.Layout; using System.Collections.Specialized; @@ -23,23 +24,24 @@ namespace System.Windows.Forms { [ClassInterface(ClassInterfaceType.AutoDispatch)] [Designer("System.Windows.Forms.Design.ToolStripPanelDesigner, " + AssemblyRef.SystemDesign)] [ToolboxBitmapAttribute(typeof(ToolStripPanel), "ToolStripPanel_standalone")] - public class ToolStripPanel : ContainerControl, IArrangedElement { + public class ToolStripPanel : ContainerControl, IArrangedElement + { private Orientation orientation = Orientation.Horizontal; - private static readonly Padding rowMargin = new Padding(3,0,0,0); + private static readonly Padding rowMargin = new Padding(3, 0, 0, 0); private Padding scaledRowMargin = rowMargin; private ToolStripRendererSwitcher rendererSwitcher = null; private Type currentRendererType = typeof(System.Type); private BitVector32 state = new BitVector32(); private ToolStripContainer owner; - + #if DEBUG - internal static TraceSwitch ToolStripPanelDebug = new TraceSwitch("ToolStripPanelDebug", "Debug code for rafting mouse movement"); - internal static TraceSwitch ToolStripPanelFeedbackDebug = new TraceSwitch("ToolStripPanelFeedbackDebug", "Debug code for rafting feedback"); - internal static TraceSwitch ToolStripPanelMissingRowDebug = new TraceSwitch("ToolStripPanelMissingRowDebug", "Debug code for rafting feedback"); - + internal static TraceSwitch ToolStripPanelDebug = new TraceSwitch("ToolStripPanelDebug", "Debug code for rafting mouse movement"); + internal static TraceSwitch ToolStripPanelFeedbackDebug = new TraceSwitch("ToolStripPanelFeedbackDebug", "Debug code for rafting feedback"); + internal static TraceSwitch ToolStripPanelMissingRowDebug = new TraceSwitch("ToolStripPanelMissingRowDebug", "Debug code for rafting feedback"); + #else internal static TraceSwitch ToolStripPanelDebug; internal static TraceSwitch ToolStripPanelFeedbackDebug; @@ -59,9 +61,9 @@ public class ToolStripPanel : ContainerControl, IArrangedElement { private static readonly int stateChangingZOrder = BitVector32.CreateMask(stateBeginInit); private static readonly int stateInJoin = BitVector32.CreateMask(stateChangingZOrder); private static readonly int stateEndInit = BitVector32.CreateMask(stateInJoin); - private static readonly int stateLayoutSuspended = BitVector32.CreateMask(stateEndInit); - private static readonly int stateRightToLeftChanged = BitVector32.CreateMask(stateLayoutSuspended); - + private static readonly int stateLayoutSuspended = BitVector32.CreateMask(stateEndInit); + private static readonly int stateRightToLeftChanged = BitVector32.CreateMask(stateLayoutSuspended); + // events @@ -69,8 +71,10 @@ public class ToolStripPanel : ContainerControl, IArrangedElement { private static readonly object EventRendererChanged = new object(); - public ToolStripPanel() { - if (DpiHelper.IsScalingRequirementMet) { + public ToolStripPanel() + { + if (DpiHelper.IsScalingRequirementMet) + { scaledRowMargin = DpiHelper.LogicalToDeviceUnits(rowMargin); } @@ -91,7 +95,8 @@ public ToolStripPanel() { } internal ToolStripPanel(ToolStripContainer owner) - : this() { + : this() + { this.owner = owner; } @@ -100,7 +105,8 @@ internal ToolStripPanel(ToolStripContainer owner) EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public override bool AllowDrop { + public override bool AllowDrop + { get { return base.AllowDrop; } set { base.AllowDrop = value; } } @@ -109,7 +115,8 @@ public override bool AllowDrop { Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public override bool AutoScroll { + public override bool AutoScroll + { get { return base.AutoScroll; } set { base.AutoScroll = value; } } @@ -118,7 +125,8 @@ public override bool AutoScroll { Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public new Size AutoScrollMargin { + public new Size AutoScrollMargin + { get { return base.AutoScrollMargin; } set { base.AutoScrollMargin = value; } } @@ -127,21 +135,25 @@ public override bool AutoScroll { Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public new Size AutoScrollMinSize { + public new Size AutoScrollMinSize + { get { return base.AutoScrollMinSize; } set { base.AutoScrollMinSize = value; } } - + [ DefaultValue(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible) ] - public override bool AutoSize { - get { + public override bool AutoSize + { + get + { return base.AutoSize; } - set { + set + { base.AutoSize = value; } @@ -153,57 +165,73 @@ public override bool AutoSize { Browsable(true), EditorBrowsable(EditorBrowsableState.Always) ] - public new event EventHandler AutoSizeChanged { + public new event EventHandler AutoSizeChanged + { add => base.AutoSizeChanged += value; remove => base.AutoSizeChanged -= value; } - protected override Padding DefaultPadding { + protected override Padding DefaultPadding + { get { return Padding.Empty; } } - protected override Padding DefaultMargin { + protected override Padding DefaultMargin + { get { return Padding.Empty; } } - public Padding RowMargin { + public Padding RowMargin + { get { return scaledRowMargin; } - set { + set + { scaledRowMargin = value; LayoutTransaction.DoLayout(this, this, "RowMargin"); } } - public override DockStyle Dock { - get { + public override DockStyle Dock + { + get + { return base.Dock; } - set { + set + { base.Dock = value; - if (value == DockStyle.Left || value == DockStyle.Right) { + if (value == DockStyle.Left || value == DockStyle.Right) + { Orientation = Orientation.Vertical; } - else { + else + { Orientation = Orientation.Horizontal; } } } - internal Rectangle DragBounds { - get { + internal Rectangle DragBounds + { + get + { return LayoutUtils.InflateRect(this.ClientRectangle, DragMargin); } } - - internal bool IsInDesignMode { - get { + + internal bool IsInDesignMode + { + get + { return DesignMode; } } - public override LayoutEngine LayoutEngine { - get { + public override LayoutEngine LayoutEngine + { + get + { return FlowLayout.Instance; } } @@ -213,35 +241,46 @@ public override LayoutEngine LayoutEngine { Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced) ] - public bool Locked { - get { + public bool Locked + { + get + { return state[stateLocked]; } - set { + set + { state[stateLocked] = value; } } - - public Orientation Orientation { - get { + + public Orientation Orientation + { + get + { return orientation; } - set { - if (orientation != value) { + set + { + if (orientation != value) + { orientation = value; scaledRowMargin = LayoutUtils.FlipPadding(scaledRowMargin); InitFlowLayout(); - foreach (ToolStripPanelRow row in this.RowsInternal) { + foreach (ToolStripPanelRow row in this.RowsInternal) + { row.OnOrientationChanged(); } } } } - private ToolStripRendererSwitcher RendererSwitcher { - get { - if (rendererSwitcher == null) { + private ToolStripRendererSwitcher RendererSwitcher + { + get + { + if (rendererSwitcher == null) + { rendererSwitcher = new ToolStripRendererSwitcher(this); HandleRendererChanged(this, EventArgs.Empty); rendererSwitcher.RendererChanged += new EventHandler(HandleRendererChanged); @@ -254,11 +293,14 @@ private ToolStripRendererSwitcher RendererSwitcher { [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] // PM team has reviewed and decided on naming changes already [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] - public ToolStripRenderer Renderer { - get { + public ToolStripRenderer Renderer + { + get + { return RendererSwitcher.Renderer; } - set { + set + { RendererSwitcher.Renderer = value; } } @@ -268,11 +310,14 @@ public ToolStripRenderer Renderer { SRDescription(nameof(SR.ToolStripRenderModeDescr)), SRCategory(nameof(SR.CatAppearance)), ] - public ToolStripRenderMode RenderMode { - get { + public ToolStripRenderMode RenderMode + { + get + { return RendererSwitcher.RenderMode; } - set { + set + { RendererSwitcher.RenderMode = value; } } @@ -280,7 +325,8 @@ public ToolStripRenderMode RenderMode { [SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.ToolStripRendererChanged))] // PM team has reviewed and decided on naming changes already [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] - public event EventHandler RendererChanged { + public event EventHandler RendererChanged + { add => Events.AddHandler(EventRendererChanged, value); remove => Events.RemoveHandler(EventRendererChanged, value); } @@ -293,11 +339,14 @@ public event EventHandler RendererChanged { DesignerSerializationVisibility(DesignerSerializationVisibility.Content), SRDescription(nameof(SR.ToolStripPanelRowsDescr)) ] - internal ToolStripPanelRowCollection RowsInternal { - get { + internal ToolStripPanelRowCollection RowsInternal + { + get + { ToolStripPanelRowCollection rowCollection = (ToolStripPanelRowCollection)Properties.GetObject(PropToolStripPanelRowCollection); - if (rowCollection == null) { + if (rowCollection == null) + { rowCollection = CreateToolStripPanelRowCollection(); Properties.SetObject(PropToolStripPanelRowCollection, rowCollection); } @@ -308,35 +357,41 @@ internal ToolStripPanelRowCollection RowsInternal { [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), - SRDescription(nameof(SR.ToolStripPanelRowsDescr)), + SRDescription(nameof(SR.ToolStripPanelRowsDescr)), SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays") ] - - public ToolStripPanelRow[] Rows { - get { + + public ToolStripPanelRow[] Rows + { + get + { ToolStripPanelRow[] rows = new ToolStripPanelRow[RowsInternal.Count]; - RowsInternal.CopyTo(rows,0); + RowsInternal.CopyTo(rows, 0); return rows; } } - + [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new int TabIndex { - get { + public new int TabIndex + { + get + { return base.TabIndex; } - set { + set + { base.TabIndex = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler TabIndexChanged { + public new event EventHandler TabIndexChanged + { add => base.TabIndexChanged += value; remove => base.TabIndexChanged -= value; } @@ -346,11 +401,14 @@ public ToolStripPanelRow[] Rows { Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public new bool TabStop { - get { + public new bool TabStop + { + get + { return base.TabStop; } - set { + set + { SetStyle(ControlStyles.Selectable, value); base.TabStop = value; @@ -358,7 +416,8 @@ public ToolStripPanelRow[] Rows { } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler TabStopChanged { + public new event EventHandler TabStopChanged + { add => base.TabStopChanged += value; remove => base.TabStopChanged -= value; } @@ -368,17 +427,21 @@ public ToolStripPanelRow[] Rows { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler TextChanged { + public new event EventHandler TextChanged + { add => base.TextChanged += value; remove => base.TextChanged -= value; } @@ -386,20 +449,25 @@ public override string Text { #region ISupportInitialize - public void BeginInit() { + public void BeginInit() + { state[stateBeginInit] = true; } - public void EndInit() { + public void EndInit() + { state[stateBeginInit] = false; state[stateEndInit] = true; - try { - if (!state[stateInJoin]) { + try + { + if (!state[stateInJoin]) + { JoinControls(); } } - finally { + finally + { state[stateEndInit] = false; } @@ -408,11 +476,13 @@ public void EndInit() { #endregion ISupportInitialize - private ToolStripPanelRowCollection CreateToolStripPanelRowCollection() { + private ToolStripPanelRowCollection CreateToolStripPanelRowCollection() + { return new ToolStripPanelRowCollection(this); } - protected override Control.ControlCollection CreateControlsInstance() { + protected override Control.ControlCollection CreateControlsInstance() + { return new ToolStripPanelControlCollection(this); } @@ -423,34 +493,42 @@ protected override Control.ControlCollection CreateControlsInstance() { /// the /// . /// - protected override void Dispose(bool disposing) { - if (disposing) { + protected override void Dispose(bool disposing) + { + if (disposing) + { ToolStripManager.ToolStripPanels.Remove(this); } base.Dispose(disposing); } - private void InitFlowLayout() { - if (Orientation == Orientation.Horizontal) { + private void InitFlowLayout() + { + if (Orientation == Orientation.Horizontal) + { FlowLayout.SetFlowDirection(this, FlowDirection.TopDown); } - else { + else + { FlowLayout.SetFlowDirection(this, FlowDirection.LeftToRight); } FlowLayout.SetWrapContents(this, false); } - private Point GetStartLocation(ToolStrip toolStripToDrag) { - if (toolStripToDrag.IsCurrentlyDragging - && Orientation == Orientation.Horizontal - && toolStripToDrag.RightToLeft == RightToLeft.Yes ) { + private Point GetStartLocation(ToolStrip toolStripToDrag) + { + if (toolStripToDrag.IsCurrentlyDragging + && Orientation == Orientation.Horizontal + && toolStripToDrag.RightToLeft == RightToLeft.Yes) + { // the grip is on the right side, not left. - return new Point(toolStripToDrag.Right,toolStripToDrag.Top); + return new Point(toolStripToDrag.Right, toolStripToDrag.Top); } return toolStripToDrag.Location; } - private void HandleRendererChanged(object sender, EventArgs e) { + private void HandleRendererChanged(object sender, EventArgs e) + { OnRendererChanged(e); } @@ -469,44 +547,56 @@ protected override void OnPaint(PaintEventArgs e) { #endif [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnPaintBackground(PaintEventArgs e) { - ToolStripPanelRenderEventArgs rea = new ToolStripPanelRenderEventArgs(e.Graphics, this); + protected override void OnPaintBackground(PaintEventArgs e) + { + ToolStripPanelRenderEventArgs rea = new ToolStripPanelRenderEventArgs(e.Graphics, this); Renderer.DrawToolStripPanelBackground(rea); - if (!rea.Handled) { + if (!rea.Handled) + { base.OnPaintBackground(e); } } - protected override void OnControlAdded(ControlEventArgs e) { + protected override void OnControlAdded(ControlEventArgs e) + { base.OnControlAdded(e); - - if (!state[stateBeginInit] && !state[stateInJoin]) { - if (!state[stateLayoutSuspended]) { + + if (!state[stateBeginInit] && !state[stateInJoin]) + { + if (!state[stateLayoutSuspended]) + { this.Join(e.Control as ToolStrip, e.Control.Location); } - else { + else + { BeginInit(); } } } - protected override void OnControlRemoved(ControlEventArgs e) { + protected override void OnControlRemoved(ControlEventArgs e) + { ISupportToolStripPanel controlToBeDragged = e.Control as ISupportToolStripPanel; - - if (controlToBeDragged != null) { - if (controlToBeDragged.ToolStripPanelRow != null/* && controlToBeDragged.ToolStripPanelRow != owner*/) { + + if (controlToBeDragged != null) + { + if (controlToBeDragged.ToolStripPanelRow != null/* && controlToBeDragged.ToolStripPanelRow != owner*/) + { controlToBeDragged.ToolStripPanelRow.ControlsInternal.Remove(e.Control); } } base.OnControlRemoved(e); } - protected override void OnLayout(LayoutEventArgs e) { - if (e.AffectedComponent != ParentInternal && e.AffectedComponent as Control != null) { + protected override void OnLayout(LayoutEventArgs e) + { + if (e.AffectedComponent != ParentInternal && e.AffectedComponent as Control != null) + { ISupportToolStripPanel draggedControl = e.AffectedComponent as ISupportToolStripPanel; - if (draggedControl != null && this.RowsInternal.Contains(draggedControl.ToolStripPanelRow)) { + if (draggedControl != null && this.RowsInternal.Contains(draggedControl.ToolStripPanelRow)) + { // there's a problem in the base onlayout... if toolstrip needs more space it talks to us // not the row that needs layout. LayoutTransaction.DoLayout(draggedControl.ToolStripPanelRow, e.AffectedComponent as IArrangedElement, e.AffectedProperty); @@ -515,32 +605,40 @@ protected override void OnLayout(LayoutEventArgs e) { base.OnLayout(e); } - internal override void OnLayoutSuspended() { + internal override void OnLayoutSuspended() + { base.OnLayoutSuspended(); state[stateLayoutSuspended] = true; - + } - internal override void OnLayoutResuming(bool resumeLayout) { + internal override void OnLayoutResuming(bool resumeLayout) + { base.OnLayoutResuming(resumeLayout); state[stateLayoutSuspended] = false; - if (state[stateBeginInit]) { + if (state[stateBeginInit]) + { EndInit(); } } - protected override void OnRightToLeftChanged(EventArgs e) { + protected override void OnRightToLeftChanged(EventArgs e) + { base.OnRightToLeftChanged(e); - if (!state[stateBeginInit]) { - if (Controls.Count > 0) { + if (!state[stateBeginInit]) + { + if (Controls.Count > 0) + { // rejoin the controls on the other side of the toolstrippanel. SuspendLayout(); Control[] controls = new Control[this.Controls.Count]; Point[] controlLocations = new Point[this.Controls.Count]; int j = 0; - foreach (ToolStripPanelRow row in this.RowsInternal) { - foreach (Control control in row.ControlsInternal) { + foreach (ToolStripPanelRow row in this.RowsInternal) + { + foreach (Control control in row.ControlsInternal) + { controls[j] = control; controlLocations[j] = new Point(row.Bounds.Width - control.Right, control.Top); j++; @@ -549,101 +647,122 @@ protected override void OnRightToLeftChanged(EventArgs e) { this.Controls.Clear(); - for ( int i = 0; i < controls.Length; i++) { + for (int i = 0; i < controls.Length; i++) + { Join(controls[i] as ToolStrip, controlLocations[i]); } ResumeLayout(true); } } - else { + else + { state[stateRightToLeftChanged] = true; } - + } // PM team has reviewed and decided on naming changes already [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] - protected virtual void OnRendererChanged(EventArgs e) { + protected virtual void OnRendererChanged(EventArgs e) + { Renderer.InitializePanel(this); this.Invalidate(); EventHandler handler = (EventHandler)Events[EventRendererChanged]; - if (handler != null) handler(this, e); + if (handler != null) + handler(this, e); } /// /// We want to Set ToolStripPanel at DesignTime when the ToolStripPanel is added to the Form, /// - protected override void OnParentChanged(EventArgs e) { + protected override void OnParentChanged(EventArgs e) + { PerformUpdate(); base.OnParentChanged(e); } - protected override void OnDockChanged(EventArgs e) { + protected override void OnDockChanged(EventArgs e) + { PerformUpdate(); base.OnDockChanged(e); } - internal void PerformUpdate() { + internal void PerformUpdate() + { PerformUpdate(false); } - internal void PerformUpdate(bool forceLayout) { + internal void PerformUpdate(bool forceLayout) + { - if (!state[stateBeginInit] && !state[stateInJoin]) { + if (!state[stateBeginInit] && !state[stateInJoin]) + { JoinControls(forceLayout); } } - private void ResetRenderMode() { - RendererSwitcher.ResetRenderMode(); + private void ResetRenderMode() + { + RendererSwitcher.ResetRenderMode(); } - private bool ShouldSerializeRenderMode() { + private bool ShouldSerializeRenderMode() + { return RendererSwitcher.ShouldSerializeRenderMode(); } - private bool ShouldSerializeDock() { + private bool ShouldSerializeDock() + { return (owner == null && (Dock != DockStyle.None)); } - private void JoinControls() { + private void JoinControls() + { JoinControls(false); } - private void JoinControls(bool forceLayout) { + private void JoinControls(bool forceLayout) + { // undone: config - shift to other container ToolStripPanelControlCollection controls = this.Controls as ToolStripPanelControlCollection; - if (controls.Count > 0) { + if (controls.Count > 0) + { controls.Sort(); // since Join is going to mess with our order - make a copy. (ugh). Control[] controlArray = new Control[controls.Count]; controls.CopyTo(controlArray, 0); - for (int i = 0; i < controlArray.Length; i++) { + for (int i = 0; i < controlArray.Length; i++) + { int numRows = RowsInternal.Count; ISupportToolStripPanel draggedControl = controlArray[i] as ISupportToolStripPanel; - - if (draggedControl != null && draggedControl.ToolStripPanelRow != null && !draggedControl.IsCurrentlyDragging) { + + if (draggedControl != null && draggedControl.ToolStripPanelRow != null && !draggedControl.IsCurrentlyDragging) + { ToolStripPanelRow row = draggedControl.ToolStripPanelRow; - if (row.Bounds.Contains(controlArray[i].Location)) { + if (row.Bounds.Contains(controlArray[i].Location)) + { // this toolstrip does not require join. continue; } } - if (controlArray[i].AutoSize) { + if (controlArray[i].AutoSize) + { controlArray[i].Size = controlArray[i].PreferredSize; } Point controlLocation = controlArray[i].Location; // right to left has changed while layout was deferred... - if (state[stateRightToLeftChanged]) { + if (state[stateRightToLeftChanged]) + { controlLocation = new Point(this.Width - controlArray[i].Right, controlLocation.Y); } this.Join(controlArray[i] as ToolStrip, controlArray[i].Location); - if (numRows < RowsInternal.Count || forceLayout) { + if (numRows < RowsInternal.Count || forceLayout) + { // OK this is wierd but here we're in the midst of a suspend layout. // the only way we can deterministically place these guys is to force a layout // each time we've added a new row. Otherwise we wont find the correct @@ -660,59 +779,72 @@ private void JoinControls(bool forceLayout) { [ThreadStatic] private static FeedbackRectangle feedbackRect; - - private void GiveToolStripPanelFeedback(ToolStrip toolStripToDrag, Point screenLocation) { - - if (Orientation == Orientation.Horizontal && RightToLeft == RightToLeft.Yes) { + + private void GiveToolStripPanelFeedback(ToolStrip toolStripToDrag, Point screenLocation) + { + + if (Orientation == Orientation.Horizontal && RightToLeft == RightToLeft.Yes) + { // paint the feedback in the correct location when RTL.Yes - screenLocation.Offset(-toolStripToDrag.Width,0); + screenLocation.Offset(-toolStripToDrag.Width, 0); } - if (CurrentFeedbackRect == null) { + if (CurrentFeedbackRect == null) + { Debug.WriteLineIf(ToolStripPanelFeedbackDebug.TraceVerbose, "FEEDBACK: creating NEW feedback at " + screenLocation.ToString()); - + CurrentFeedbackRect = new FeedbackRectangle(toolStripToDrag.ClientRectangle); } - if (!CurrentFeedbackRect.Visible) { + if (!CurrentFeedbackRect.Visible) + { Debug.WriteLineIf(ToolStripPanelFeedbackDebug.TraceVerbose, "FEEDBACK: Showing NEW feedback at " + screenLocation.ToString()); toolStripToDrag.SuspendCaputureMode(); - try { + try + { CurrentFeedbackRect.Show(screenLocation); toolStripToDrag.CaptureInternal = true; } - finally { + finally + { toolStripToDrag.ResumeCaputureMode(); - } + } } - else { + else + { Debug.WriteLineIf(ToolStripPanelFeedbackDebug.TraceVerbose, "FEEDBACK: Moving feedback to " + screenLocation.ToString()); CurrentFeedbackRect.Move(screenLocation); - + } } - - - internal static void ClearDragFeedback() { + + + internal static void ClearDragFeedback() + { #if DEBUG - if (ToolStripPanelFeedbackDebug.TraceVerbose){ - Debug.WriteLine("FEEDBACK: clearing old feedback at "/*+ new StackTrace().ToString()*/); + if (ToolStripPanelFeedbackDebug.TraceVerbose) + { + Debug.WriteLine("FEEDBACK: clearing old feedback at "/*+ new StackTrace().ToString()*/); } #endif FeedbackRectangle oldFeedback = feedbackRect; feedbackRect = null; - if (oldFeedback != null) { + if (oldFeedback != null) + { oldFeedback.Dispose(); } - + } - private static FeedbackRectangle CurrentFeedbackRect { - get { + private static FeedbackRectangle CurrentFeedbackRect + { + get + { return feedbackRect; } - set { + set + { feedbackRect = value; } } @@ -721,58 +853,74 @@ private static FeedbackRectangle CurrentFeedbackRect { // The FeedbackRectangle happens to encapsulate a toolstripdropdown // with a special region. The feedback rectangle exposes the minimum // API so the underlying implementation can be replaced if necessary. - private class FeedbackRectangle : IDisposable { + private class FeedbackRectangle : IDisposable + { private FeedbackDropDown dropDown; - - public FeedbackRectangle(Rectangle bounds) { + + public FeedbackRectangle(Rectangle bounds) + { dropDown = new FeedbackDropDown(bounds); - + } - public bool Visible { - get { - if (dropDown != null && !dropDown.IsDisposed) { - return dropDown.Visible; + public bool Visible + { + get + { + if (dropDown != null && !dropDown.IsDisposed) + { + return dropDown.Visible; } return false; } - set { - if (dropDown != null && !dropDown.IsDisposed) { + set + { + if (dropDown != null && !dropDown.IsDisposed) + { dropDown.Visible = value; } } } - public void Show(Point newLocation) { + public void Show(Point newLocation) + { dropDown.Show(newLocation); } - public void Move(Point newLocation) { - dropDown.MoveTo(newLocation); + public void Move(Point newLocation) + { + dropDown.MoveTo(newLocation); } - protected void Dispose(bool disposing) { - if (disposing) { - if (dropDown != null) { + protected void Dispose(bool disposing) + { + if (disposing) + { + if (dropDown != null) + { Visible = false; dropDown.Dispose(); dropDown = null; - } + } } } - public void Dispose() { + public void Dispose() + { Dispose(true); } - - ~FeedbackRectangle() { + + ~FeedbackRectangle() + { Dispose(false); } - private class FeedbackDropDown : ToolStripDropDown { + private class FeedbackDropDown : ToolStripDropDown + { private const int MAX_PAINTS_TO_SERVICE = 20; private int _numPaintsServiced = 0; // member variable to protect against re-entrancy - - public FeedbackDropDown(Rectangle bounds) : base(){ + + public FeedbackDropDown(Rectangle bounds) : base() + { SetStyle(ControlStyles.AllPaintingInWmPaint, false); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); SetStyle(ControlStyles.CacheText, true); @@ -783,68 +931,81 @@ public FeedbackDropDown(Rectangle bounds) : base(){ // caching as this is unlikely to change during the lifetime // of the dropdown. - + Rectangle regionRect = bounds; //create a region the size of the client area - regionRect.Inflate(-1,-1); //squish down by one pixel + regionRect.Inflate(-1, -1); //squish down by one pixel Region rgn = new Region(bounds); // create region rgn.Exclude(regionRect); // exclude the center part // set it into the toolstripdropdown’s region - this.Region = rgn; + this.Region = rgn; } - + // ForceSynchronousPaint - peeks through the message queue, looking for WM_PAINTs // calls UpdateWindow on the hwnd to force the paint to happen now. // // When we're changing the location of the feedback dropdown, we need to // force WM_PAINTS to happen, as things that dont respond to WM_ERASEBKGND // have bits of the dropdown region drawn all over them. - private void ForceSynchronousPaint() { - if (!IsDisposed) { - if (_numPaintsServiced == 0) { // protect against re-entrancy. - try { + private void ForceSynchronousPaint() + { + if (!IsDisposed) + { + if (_numPaintsServiced == 0) + { // protect against re-entrancy. + try + { NativeMethods.MSG msg = new NativeMethods.MSG(); while (UnsafeNativeMethods.PeekMessage(ref msg, new HandleRef(this, IntPtr.Zero), Interop.WindowMessages.WM_PAINT, Interop.WindowMessages.WM_PAINT, - NativeMethods.PM_REMOVE)) { - SafeNativeMethods.UpdateWindow(new HandleRef(null, msg.hwnd)); + NativeMethods.PM_REMOVE)) + { + SafeNativeMethods.UpdateWindow(new HandleRef(null, msg.hwnd)); // Infinite loop protection - if (_numPaintsServiced++ > MAX_PAINTS_TO_SERVICE) { + if (_numPaintsServiced++ > MAX_PAINTS_TO_SERVICE) + { Debug.Fail("somehow we've gotten ourself in a situation where we're pumping an unreasonable number of paint messages, investigate."); break; } } } - finally { + finally + { _numPaintsServiced = 0; } } } } - - protected override void OnPaint(PaintEventArgs e) { + + protected override void OnPaint(PaintEventArgs e) + { } - protected override void OnPaintBackground(PaintEventArgs e) { + protected override void OnPaintBackground(PaintEventArgs e) + { // respond to everything in WM_ERASEBKGND Renderer.DrawToolStripBackground(new ToolStripRenderEventArgs(e.Graphics, this)); Renderer.DrawToolStripBorder(new ToolStripRenderEventArgs(e.Graphics, this)); } - protected override void OnOpening(CancelEventArgs e) { + protected override void OnOpening(CancelEventArgs e) + { base.OnOpening(e); e.Cancel = false; } - public void MoveTo(Point newLocation) { + public void MoveTo(Point newLocation) + { this.Location = newLocation; // if we dont force a paint here, we'll only send WM_ERASEBKGNDs right away // and leave rectangles all over controls that dont respond to that window message. ForceSynchronousPaint(); } - protected override void WndProc(ref Message m){ - if (m.Msg == Interop.WindowMessages.WM_NCHITTEST){ + protected override void WndProc(ref Message m) + { + if (m.Msg == Interop.WindowMessages.WM_NCHITTEST) + { m.Result = (IntPtr)NativeMethods.HTTRANSPARENT; } base.WndProc(ref m); @@ -856,101 +1017,124 @@ protected override void WndProc(ref Message m){ #region JoinAndMove - public void Join(ToolStrip toolStripToDrag) { + public void Join(ToolStrip toolStripToDrag) + { Join(toolStripToDrag, Point.Empty); } - public void Join(ToolStrip toolStripToDrag, int row) { - if (row < 0) { + public void Join(ToolStrip toolStripToDrag, int row) + { + if (row < 0) + { throw new ArgumentOutOfRangeException(nameof(row), string.Format(SR.IndexOutOfRange, row.ToString(CultureInfo.CurrentCulture))); } Point location = Point.Empty; Rectangle dragRect = Rectangle.Empty; - if (row >= RowsInternal.Count) { + if (row >= RowsInternal.Count) + { dragRect = DragBounds; } - else { + else + { dragRect = this.RowsInternal[row].DragBounds; } - if (Orientation == Orientation.Horizontal) { - location = new Point(0, dragRect.Bottom -1); + if (Orientation == Orientation.Horizontal) + { + location = new Point(0, dragRect.Bottom - 1); } - else { - location = new Point(dragRect.Right -1, 0); + else + { + location = new Point(dragRect.Right - 1, 0); } - + Join(toolStripToDrag, location); - + } - public void Join(ToolStrip toolStripToDrag, int x, int y) { + public void Join(ToolStrip toolStripToDrag, int x, int y) + { Join(toolStripToDrag, new Point(x, y)); } - + [ SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // Using ToolStrip instead of Control intentionally ] - public void Join(ToolStrip toolStripToDrag, Point location) { - if (toolStripToDrag == null) { + public void Join(ToolStrip toolStripToDrag, Point location) + { + if (toolStripToDrag == null) + { throw new ArgumentNullException(nameof(toolStripToDrag)); } - if (!state[stateBeginInit] && !state[stateInJoin]) { - try { + if (!state[stateBeginInit] && !state[stateInJoin]) + { + try + { state[stateInJoin] = true; toolStripToDrag.ParentInternal = this; MoveInsideContainer(toolStripToDrag, location); } - finally { + finally + { state[stateInJoin] = false; } } - else { + else + { this.Controls.Add(toolStripToDrag); toolStripToDrag.Location = location; } } - internal void MoveControl(ToolStrip toolStripToDrag, Point screenLocation) { + internal void MoveControl(ToolStrip toolStripToDrag, Point screenLocation) + { ISupportToolStripPanel draggedControl = toolStripToDrag as ISupportToolStripPanel; - - if (draggedControl == null) { + + if (draggedControl == null) + { Debug.Fail("Move called on immovable object."); return; } Point clientLocation = PointToClient(screenLocation); - if (!this.DragBounds.Contains(clientLocation)) { + if (!this.DragBounds.Contains(clientLocation)) + { Debug.WriteLineIf(ToolStripPanelDebug.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "RC.MoveControl - Point {0} is not in current rafting container drag bounds {1}, calling MoveOutsideContainer", clientLocation, DragBounds)); MoveOutsideContainer(toolStripToDrag, screenLocation); return; } - else { + else + { Join(toolStripToDrag as ToolStrip, clientLocation); } } - private void MoveInsideContainer(ToolStrip toolStripToDrag, Point clientLocation) { + private void MoveInsideContainer(ToolStrip toolStripToDrag, Point clientLocation) + { ISupportToolStripPanel draggedControl = toolStripToDrag as ISupportToolStripPanel; // if the point is not in this rafting container forward on to the appropriate container. - if (draggedControl.IsCurrentlyDragging && !this.DragBounds.Contains(clientLocation)) { + if (draggedControl.IsCurrentlyDragging && !this.DragBounds.Contains(clientLocation)) + { return; } // we know we're moving inside the container. bool changedRow = false; - + ClearDragFeedback(); // In design mode we get bogus values for client location. - if (toolStripToDrag.Site != null && toolStripToDrag.Site.DesignMode && IsHandleCreated) { + if (toolStripToDrag.Site != null && toolStripToDrag.Site.DesignMode && IsHandleCreated) + { - if (clientLocation.X < 0 || clientLocation.Y < 0) { + if (clientLocation.X < 0 || clientLocation.Y < 0) + { Point currentCursorLoc = PointToClient(WindowsFormsUtils.LastCursorPoint); - if (ClientRectangle.Contains(currentCursorLoc)) { + if (ClientRectangle.Contains(currentCursorLoc)) + { clientLocation = currentCursorLoc; } } @@ -969,57 +1153,69 @@ private void MoveInsideContainer(ToolStrip toolStripToDrag, Point clientLocation #endif bool pointInCurrentRow = false; - if (currentToolStripPanelRow != null && currentToolStripPanelRow.Visible && currentToolStripPanelRow.ToolStripPanel == this) { - if (toolStripToDrag.IsCurrentlyDragging) { + if (currentToolStripPanelRow != null && currentToolStripPanelRow.Visible && currentToolStripPanelRow.ToolStripPanel == this) + { + if (toolStripToDrag.IsCurrentlyDragging) + { // Dragging with mouse, use DragBounds to check pointInCurrentRow = currentToolStripPanelRow.DragBounds.Contains(clientLocation); } - else { + else + { // Location is set directly, use normal Bounds to check pointInCurrentRow = currentToolStripPanelRow.Bounds.Contains(clientLocation); } } - if (pointInCurrentRow) { + if (pointInCurrentRow) + { // Point INSIDE same rafting row Debug.WriteLineIf(ToolStripPanelDebug.TraceVerbose, "RC.MoveControl - Point " + clientLocation + "is in the same row as the control" + draggedControl.ToolStripPanelRow.DragBounds); draggedControl.ToolStripPanelRow.MoveControl(toolStripToDrag, GetStartLocation(toolStripToDrag), clientLocation); } - else { + else + { // Point OUTSIDE current rafting row. - + Debug.WriteLineIf(ToolStripPanelDebug.TraceVerbose, "RC.MoveControl - Point " + clientLocation + " is outside the current rafting row."); - + ToolStripPanelRow row = PointToRow(clientLocation); - if (row == null) { + if (row == null) + { Debug.WriteLineIf(ToolStripPanelDebug.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "\tThere is no row corresponding to this point, creating a new one.")); // there's no row at this point so lets create one int index = this.RowsInternal.Count; - if (Orientation == Orientation.Horizontal) { + if (Orientation == Orientation.Horizontal) + { // if it's above the first row, insert at the front. index = (clientLocation.Y <= this.Padding.Left) ? 0 : index; } - else { // Orientation.Vertical + else + { // Orientation.Vertical // if it's before the first row, insert at the front. index = (clientLocation.X <= this.Padding.Left) ? 0 : index; } - + ToolStripPanelRow previousRow = null; - if (this.RowsInternal.Count > 0) { - if (index == 0) { + if (this.RowsInternal.Count > 0) + { + if (index == 0) + { previousRow = this.RowsInternal[0]; } - else if (index > 0) { + else if (index > 0) + { previousRow = this.RowsInternal[index - 1]; } } if (previousRow != null /* there was a previous row */ && previousRow.ControlsInternal.Count == 1 /*toolStripToDrag*/ - && previousRow.ControlsInternal.Contains(toolStripToDrag)) { + && previousRow.ControlsInternal.Contains(toolStripToDrag)) + { // if the previous row already contains this control // it's futile to create a new row, we're just going to wind // up disposing this one and causing great amounts of flicker. @@ -1027,12 +1223,14 @@ private void MoveInsideContainer(ToolStrip toolStripToDrag, Point clientLocation Debug.WriteLineIf(ToolStripPanelRow.ToolStripPanelRowCreationDebug.TraceVerbose, "Reusing previous row"); // Move the ToolStrip to the new Location in the existing row. - if (toolStripToDrag.IsInDesignMode) { - Point endLocation = (Orientation == Orientation.Horizontal) ? new Point (clientLocation.X, row.Bounds.Y) : new Point (row.Bounds.X, clientLocation.Y); + if (toolStripToDrag.IsInDesignMode) + { + Point endLocation = (Orientation == Orientation.Horizontal) ? new Point(clientLocation.X, row.Bounds.Y) : new Point(row.Bounds.X, clientLocation.Y); draggedControl.ToolStripPanelRow.MoveControl(toolStripToDrag, GetStartLocation(toolStripToDrag), endLocation); } } - else { + else + { // Create a new row and insert it. // Debug.WriteLineIf(ToolStripPanelRow.ToolStripPanelRowCreationDebug.TraceVerbose, "Inserting a new row at " + index.ToString(CultureInfo.InvariantCulture)); @@ -1041,15 +1239,18 @@ private void MoveInsideContainer(ToolStrip toolStripToDrag, Point clientLocation } } - else if (!row.CanMove(toolStripToDrag)) { + else if (!row.CanMove(toolStripToDrag)) + { Debug.WriteLineIf(ToolStripPanelRow.ToolStripPanelRowCreationDebug.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "\tThere was a row, but we cant add the control to it, creating/inserting new row.")); // we have a row at that point, but its too full or doesnt want // anyone to join it. int index = RowsInternal.IndexOf(row); - if (currentToolStripPanelRow != null && currentToolStripPanelRow.ControlsInternal.Count == 1) { - if (index > 0 && index-1 == RowsInternal.IndexOf(currentToolStripPanelRow)) { + if (currentToolStripPanelRow != null && currentToolStripPanelRow.ControlsInternal.Count == 1) + { + if (index > 0 && index - 1 == RowsInternal.IndexOf(currentToolStripPanelRow)) + { Debug.WriteLineIf(ToolStripPanelRow.ToolStripPanelRowCreationDebug.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "\tAttempts to leave the current row failed as there's no space in the next row. Since there's only one control, just keep the row.")); return; } @@ -1060,75 +1261,90 @@ private void MoveInsideContainer(ToolStrip toolStripToDrag, Point clientLocation } changedRow = (currentToolStripPanelRow != row); - if (!changedRow) { - if (currentToolStripPanelRow != null && currentToolStripPanelRow.ControlsInternal.Count >1) { + if (!changedRow) + { + if (currentToolStripPanelRow != null && currentToolStripPanelRow.ControlsInternal.Count > 1) + { // force a leave/re-enter to occur. currentToolStripPanelRow.LeaveRow(toolStripToDrag); currentToolStripPanelRow = null; changedRow = true; } } - if (changedRow) { + if (changedRow) + { Debug.WriteLineIf(ToolStripPanelDebug.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "\tCalling JoinRow.")); - if (currentToolStripPanelRow != null) { + if (currentToolStripPanelRow != null) + { currentToolStripPanelRow.LeaveRow(toolStripToDrag); } row.JoinRow(toolStripToDrag, clientLocation); } - - if (changedRow && draggedControl.IsCurrentlyDragging) { + + if (changedRow && draggedControl.IsCurrentlyDragging) + { // force the layout of the new row. - for (int i = 0; i < RowsInternal.Count; i++) { + for (int i = 0; i < RowsInternal.Count; i++) + { LayoutTransaction.DoLayout(RowsInternal[i], this, PropertyNames.Rows); } - if (RowsInternal.IndexOf(row) > 0) { + if (RowsInternal.IndexOf(row) > 0) + { // When joining a new row, move the cursor to to the location of // the grip, otherwise budging the mouse can pull it down into the next row. Point cursorLoc = toolStripToDrag.PointToScreen(toolStripToDrag.GripRectangle.Location); - if (Orientation == Orientation.Vertical) { - cursorLoc.X += toolStripToDrag.GripRectangle.Width /2; + if (Orientation == Orientation.Vertical) + { + cursorLoc.X += toolStripToDrag.GripRectangle.Width / 2; cursorLoc.Y = Cursor.Position.Y; } - else { - cursorLoc.Y += toolStripToDrag.GripRectangle.Height /2; - cursorLoc.X = Cursor.Position.X; + else + { + cursorLoc.Y += toolStripToDrag.GripRectangle.Height / 2; + cursorLoc.X = Cursor.Position.X; } Cursor.Position = cursorLoc; } } } - - -#if DEBUG + + +#if DEBUG Debug_VerifyOneToOneCellRowControlMatchup(); -// Debug_VerifyCountRows(); - if (draggedControl.IsCurrentlyDragging && changedRow && !debugModeOnly_ChangedContainers) { + // Debug_VerifyCountRows(); + if (draggedControl.IsCurrentlyDragging && changedRow && !debugModeOnly_ChangedContainers) + { // if we have changed containers, we're in a SuspendLayout. Debug_VerifyNoOverlaps(); } #endif } - private void MoveOutsideContainer(ToolStrip toolStripToDrag, Point screenLocation) { + private void MoveOutsideContainer(ToolStrip toolStripToDrag, Point screenLocation) + { // look for another rafting container. ToolStripPanel panel = ToolStripManager.ToolStripPanelFromPoint(toolStripToDrag, screenLocation); - if (panel != null) { - using (new LayoutTransaction(panel, panel, null)) { + if (panel != null) + { + using (new LayoutTransaction(panel, panel, null)) + { panel.MoveControl(toolStripToDrag, screenLocation); } toolStripToDrag.PerformLayout(); #if DEBUG ISupportToolStripPanel draggedControl = toolStripToDrag as ISupportToolStripPanel; - if (draggedControl.IsCurrentlyDragging) { + if (draggedControl.IsCurrentlyDragging) + { Debug_VerifyNoOverlaps(); } #endif } - else { + else + { GiveToolStripPanelFeedback(toolStripToDrag, screenLocation); } @@ -1138,53 +1354,67 @@ private void MoveOutsideContainer(ToolStrip toolStripToDrag, Point screenLocatio /// Given a point within the ToolStripPanel client area - /// it returns the row. If no such row exists, returns null /// - public ToolStripPanelRow PointToRow(Point clientLocation) { + public ToolStripPanelRow PointToRow(Point clientLocation) + { // PERF: since we're using the PropertyStore for this.RowsInternal, its actually // faster to use foreach. - foreach (ToolStripPanelRow row in this.RowsInternal) { + foreach (ToolStripPanelRow row in this.RowsInternal) + { Rectangle bounds = LayoutUtils.InflateRect(row.Bounds, row.Margin); // at this point we may not be sized correctly. Guess. - if (ParentInternal != null) { - if (Orientation == Orientation.Horizontal && (bounds.Width == 0)) { + if (ParentInternal != null) + { + if (Orientation == Orientation.Horizontal && (bounds.Width == 0)) + { bounds.Width = ParentInternal.DisplayRectangle.Width; } - else if (Orientation == Orientation.Vertical && (bounds.Height == 0)) { + else if (Orientation == Orientation.Vertical && (bounds.Height == 0)) + { bounds.Height = ParentInternal.DisplayRectangle.Height; } } - if (bounds.Contains(clientLocation)) { + if (bounds.Contains(clientLocation)) + { return row; } } return null; } - + #endregion JoinAndMove [Conditional("DEBUG")] - private void Debug_VerifyOneToOneCellRowControlMatchup() { - for (int i = 0; i < this.RowsInternal.Count; i++) { + private void Debug_VerifyOneToOneCellRowControlMatchup() + { + for (int i = 0; i < this.RowsInternal.Count; i++) + { ToolStripPanelRow row = this.RowsInternal[i]; - foreach (ToolStripPanelCell cell in row.Cells) { - - if (cell.Control != null) { + foreach (ToolStripPanelCell cell in row.Cells) + { + + if (cell.Control != null) + { ToolStripPanelRow currentlyAssignedRow = ((ISupportToolStripPanel)cell.Control).ToolStripPanelRow; - if (currentlyAssignedRow != row) { + if (currentlyAssignedRow != row) + { int goodRowIndex = (currentlyAssignedRow != null) ? RowsInternal.IndexOf(currentlyAssignedRow) : -1; - if (goodRowIndex == -1) { + if (goodRowIndex == -1) + { Debug.Fail(string.Format(CultureInfo.CurrentCulture, "ToolStripPanelRow has not been assigned! Should be set to {0}.", i)); } - else { + else + { Debug.Fail(string.Format(CultureInfo.CurrentCulture, "Detected orphan cell! {0} is in row {1}. It shouldnt have a cell in {2}! \r\n\r\nTurn on DEBUG_PAINT in ToolStripPanel and ToolStripPanelRow to investigate.", cell.Control.Name, goodRowIndex, i)); } } } - else { + else + { Debug.Fail("why do we have a cell with a null control in this row?"); } } @@ -1192,59 +1422,70 @@ private void Debug_VerifyOneToOneCellRowControlMatchup() { } [Conditional("DEBUG")] - private void Debug_PrintRows() { - for (int i = 0; i < RowsInternal.Count; i++) { + private void Debug_PrintRows() + { + for (int i = 0; i < RowsInternal.Count; i++) + { Debug.Write("Row " + i.ToString(CultureInfo.CurrentCulture) + ": "); - for (int j = 0; j < RowsInternal[i].ControlsInternal.Count; j++) { - Debug.Write(string.Format(CultureInfo.CurrentCulture, "[{0} {1}] ", RowsInternal[i].ControlsInternal[j].Name, ((ToolStripPanelCell)RowsInternal[i].Cells[j]).Margin)); + for (int j = 0; j < RowsInternal[i].ControlsInternal.Count; j++) + { + Debug.Write(string.Format(CultureInfo.CurrentCulture, "[{0} {1}] ", RowsInternal[i].ControlsInternal[j].Name, ((ToolStripPanelCell)RowsInternal[i].Cells[j]).Margin)); } Debug.Write("\r\n"); - } + } } [Conditional("DEBUG")] - private void Debug_VerifyCountRows() { + private void Debug_VerifyCountRows() + { Debug.Assert(RowsInternal.Count <= Controls.Count, "How did the number of rows get larger than the number of controls?"); } [Conditional("DEBUG")] - private void Debug_VerifyNoOverlaps() { - foreach (Control c1 in this.Controls) { - foreach (Control c2 in this.Controls) { - if (c1 == c2) { + private void Debug_VerifyNoOverlaps() + { + foreach (Control c1 in this.Controls) + { + foreach (Control c2 in this.Controls) + { + if (c1 == c2) + { continue; } Rectangle intersection = c1.Bounds; intersection.Intersect(c2.Bounds); - - if (!LayoutUtils.IsZeroWidthOrHeight(intersection)) { + + if (!LayoutUtils.IsZeroWidthOrHeight(intersection)) + { ISupportToolStripPanel draggedToolStrip1 = c1 as ISupportToolStripPanel; ISupportToolStripPanel draggedToolStrip2 = c2 as ISupportToolStripPanel; - - string fail = string.Format(CultureInfo.CurrentCulture, + + string fail = string.Format(CultureInfo.CurrentCulture, "OVERLAP detection:\r\n{0}: {1} row {2} row bounds {3}", - c1.Name == null ? "" : c1.Name, + c1.Name == null ? "" : c1.Name, c1.Bounds, !RowsInternal.Contains(draggedToolStrip1.ToolStripPanelRow) ? "unknown" : RowsInternal.IndexOf(draggedToolStrip1.ToolStripPanelRow).ToString(CultureInfo.CurrentCulture), draggedToolStrip1.ToolStripPanelRow.Bounds); - - fail += string.Format(CultureInfo.CurrentCulture, - "\r\n{0}: {1} row {2} row bounds {3}", - c2.Name == null ? "" : c2.Name, - c2.Bounds, - !RowsInternal.Contains(draggedToolStrip2.ToolStripPanelRow) ? "unknown" : RowsInternal.IndexOf(draggedToolStrip2.ToolStripPanelRow).ToString(CultureInfo.CurrentCulture), - draggedToolStrip2.ToolStripPanelRow.Bounds); + + fail += string.Format(CultureInfo.CurrentCulture, + "\r\n{0}: {1} row {2} row bounds {3}", + c2.Name == null ? "" : c2.Name, + c2.Bounds, + !RowsInternal.Contains(draggedToolStrip2.ToolStripPanelRow) ? "unknown" : RowsInternal.IndexOf(draggedToolStrip2.ToolStripPanelRow).ToString(CultureInfo.CurrentCulture), + draggedToolStrip2.ToolStripPanelRow.Bounds); Debug.Fail(fail); - + } } - + } - + } - ArrangedElementCollection IArrangedElement.Children { - get { + ArrangedElementCollection IArrangedElement.Children + { + get + { return RowsInternal; } } @@ -1252,16 +1493,19 @@ ArrangedElementCollection IArrangedElement.Children { [ ListBindable(false), ComVisible(false) - ] - [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - public class ToolStripPanelRowCollection : ArrangedElementCollection, IList { + ] + [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] + public class ToolStripPanelRowCollection : ArrangedElementCollection, IList + { private ToolStripPanel owner; - public ToolStripPanelRowCollection(ToolStripPanel owner) { + public ToolStripPanelRowCollection(ToolStripPanel owner) + { this.owner = owner; } - public ToolStripPanelRowCollection(ToolStripPanel owner, ToolStripPanelRow[] value) { + public ToolStripPanelRowCollection(ToolStripPanel owner, ToolStripPanelRow[] value) + { this.owner = owner; AddRange(value); } @@ -1269,14 +1513,18 @@ public ToolStripPanelRowCollection(ToolStripPanel owner, ToolStripPanelRow[] val /// /// /// - public new virtual ToolStripPanelRow this[int index] { - get { + public new virtual ToolStripPanelRow this[int index] + { + get + { return (ToolStripPanelRow)(InnerList[index]); } } - public int Add(ToolStripPanelRow value) { - if (value == null) { + public int Add(ToolStripPanelRow value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } int retVal = InnerList.Add(value); @@ -1286,64 +1534,85 @@ public int Add(ToolStripPanelRow value) { } - public void AddRange(ToolStripPanelRow[] value) { - if (value == null) { + public void AddRange(ToolStripPanelRow[] value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } ToolStripPanel currentOwner = this.owner; - if (currentOwner != null) { + if (currentOwner != null) + { currentOwner.SuspendLayout(); } - try { - for (int i = 0; i < value.Length; i++) { + try + { + for (int i = 0; i < value.Length; i++) + { this.Add(value[i]); } } - finally { - if (currentOwner != null) { + finally + { + if (currentOwner != null) + { currentOwner.ResumeLayout(); } } } - public void AddRange(ToolStripPanelRowCollection value) { - if (value == null) { + public void AddRange(ToolStripPanelRowCollection value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } ToolStripPanel currentOwner = this.owner; - if (currentOwner != null) { + if (currentOwner != null) + { currentOwner.SuspendLayout(); } - try { + try + { int currentCount = value.Count; - for (int i = 0; i < currentCount; i++) { + for (int i = 0; i < currentCount; i++) + { this.Add(value[i]); } } - finally { - if (currentOwner != null) { + finally + { + if (currentOwner != null) + { currentOwner.ResumeLayout(); } } } - public bool Contains(ToolStripPanelRow value) { + public bool Contains(ToolStripPanelRow value) + { return InnerList.Contains(value); } - public virtual void Clear() { - if (owner != null) { + public virtual void Clear() + { + if (owner != null) + { owner.SuspendLayout(); } - try { - while (Count != 0) { + try + { + while (Count != 0) + { RemoveAt(Count - 1); } } - finally { - if (owner != null) { + finally + { + if (owner != null) + { owner.ResumeLayout(); } } @@ -1359,18 +1628,22 @@ public virtual void Clear() { int IList.IndexOf(object value) { return IndexOf(value as ToolStripPanelRow); } void IList.Insert(int index, object value) { Insert(index, value as ToolStripPanelRow); } - object IList.this[int index] { + object IList.this[int index] + { get { return InnerList[index]; } set { throw new NotSupportedException(SR.ToolStripCollectionMustInsertAndRemove); /* InnerList[index] = value; */ } } - public int IndexOf(ToolStripPanelRow value) { + public int IndexOf(ToolStripPanelRow value) + { return InnerList.IndexOf(value); } - public void Insert(int index, ToolStripPanelRow value) { - if (value == null) { + public void Insert(int index, ToolStripPanelRow value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } @@ -1379,8 +1652,10 @@ public void Insert(int index, ToolStripPanelRow value) { } - private void OnAdd(ToolStripPanelRow value, int index) { - if (owner != null) { + private void OnAdd(ToolStripPanelRow value, int index) + { + if (owner != null) + { LayoutTransaction.DoLayout(owner, value, PropertyNames.Parent); } } @@ -1388,28 +1663,34 @@ private void OnAdd(ToolStripPanelRow value, int index) { /// /// Do proper cleanup of ownership, etc. /// - private void OnAfterRemove(ToolStripPanelRow row) { - -#if DEBUG - if (ToolStripPanelMissingRowDebug.TraceVerbose) { - if (row != null) { - Debug.Write("Removing row: "); - row.Debug_PrintRowID(); - Debug.WriteLine(new StackTrace().ToString()); - } - } + private void OnAfterRemove(ToolStripPanelRow row) + { + +#if DEBUG + if (ToolStripPanelMissingRowDebug.TraceVerbose) + { + if (row != null) + { + Debug.Write("Removing row: "); + row.Debug_PrintRowID(); + Debug.WriteLine(new StackTrace().ToString()); + } + } #endif - + } - public void Remove(ToolStripPanelRow value) { + public void Remove(ToolStripPanelRow value) + { InnerList.Remove(value); OnAfterRemove(value); } - public void RemoveAt(int index) { + public void RemoveAt(int index) + { ToolStripPanelRow item = null; - if (index < Count && index >= 0) { + if (index < Count && index >= 0) + { item = (ToolStripPanelRow)(InnerList[index]); } InnerList.RemoveAt(index); @@ -1418,7 +1699,8 @@ public void RemoveAt(int index) { - public void CopyTo(ToolStripPanelRow[] array, int index) { + public void CopyTo(ToolStripPanelRow[] array, int index) + { InnerList.CopyTo(array, index); } @@ -1426,50 +1708,64 @@ public void CopyTo(ToolStripPanelRow[] array, int index) { } - internal class ToolStripPanelControlCollection : WindowsFormsUtils.TypedControlCollection { + internal class ToolStripPanelControlCollection : WindowsFormsUtils.TypedControlCollection + { private ToolStripPanel owner; public ToolStripPanelControlCollection(ToolStripPanel owner) - : base(owner, typeof(ToolStrip)) { + : base(owner, typeof(ToolStrip)) + { this.owner = owner; } - internal override void AddInternal(Control value) { - if (value != null) { - using (new LayoutTransaction(value, value, PropertyNames.Parent)) { + internal override void AddInternal(Control value) + { + if (value != null) + { + using (new LayoutTransaction(value, value, PropertyNames.Parent)) + { base.AddInternal(value); } } - else { + else + { base.AddInternal(value); } } - internal void Sort() { - if (owner.Orientation == Orientation.Horizontal) { + internal void Sort() + { + if (owner.Orientation == Orientation.Horizontal) + { InnerList.Sort(new YXComparer()); } - else { + else + { InnerList.Sort(new XYComparer()); } } // sort by X, then Y - public class XYComparer : IComparer { + public class XYComparer : IComparer + { public XYComparer() { } - public int Compare(object first, object second) { + public int Compare(object first, object second) + { Control one = first as Control; Control two = second as Control; - if (one.Bounds.X < two.Bounds.X) { + if (one.Bounds.X < two.Bounds.X) + { return -1; } - if (one.Bounds.X == two.Bounds.X) { - if (one.Bounds.Y < two.Bounds.Y) { + if (one.Bounds.X == two.Bounds.X) + { + if (one.Bounds.Y < two.Bounds.Y) + { return -1; } return 1; @@ -1480,18 +1776,23 @@ public int Compare(object first, object second) { } // sort by Y, then X - public class YXComparer : IComparer { + public class YXComparer : IComparer + { public YXComparer() { } - public int Compare(object first, object second) { + public int Compare(object first, object second) + { Control one = first as Control; Control two = second as Control; - if (one.Bounds.Y < two.Bounds.Y) { + if (one.Bounds.Y < two.Bounds.Y) + { return -1; } - if (one.Bounds.Y == two.Bounds.Y) { - if (one.Bounds.X < two.Bounds.X) { + if (one.Bounds.Y == two.Bounds.Y) + { + if (one.Bounds.X < two.Bounds.X) + { return -1; } return 1; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelCell.cs index 80d4bcb0c02..8744a737aa8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelCell.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Drawing; using System.Windows.Forms.Layout; using System.Collections.Specialized; @@ -10,7 +11,7 @@ namespace System.Windows.Forms { using System.ComponentModel; using System.Diagnostics; using System.Globalization; - + /// this class is a container for toolstrips on a rafting row. @@ -18,16 +19,17 @@ namespace System.Windows.Forms { /// affect the underlying toolstrip's properties.... so if its /// removed from a rafting container its still got its defaults /// set up for it. - internal class ToolStripPanelCell : ArrangedElement { + internal class ToolStripPanelCell : ArrangedElement + { - private ToolStrip _wrappedToolStrip = null; - private ToolStripPanelRow parent = null; - private Size maxSize = LayoutUtils.MaxSize; - private bool currentlySizing = false; - private bool currentlyDragging = false; + private ToolStrip _wrappedToolStrip = null; + private ToolStripPanelRow parent = null; + private Size maxSize = LayoutUtils.MaxSize; + private bool currentlySizing = false; + private bool currentlyDragging = false; private bool restoreOnVisibleChanged = false; - + private Rectangle cachedBounds = Rectangle.Empty; #if DEBUG private string cellID; @@ -35,10 +37,12 @@ internal class ToolStripPanelCell : ArrangedElement { private static int cellCount; #endif - public ToolStripPanelCell(Control control):this(null, control) { + public ToolStripPanelCell(Control control) : this(null, control) + { } - public ToolStripPanelCell(ToolStripPanelRow parent, Control control) { + public ToolStripPanelCell(ToolStripPanelRow parent, Control control) + { #if DEBUG @@ -49,159 +53,194 @@ public ToolStripPanelCell(ToolStripPanelRow parent, Control control) { this.ToolStripPanelRow = parent; this._wrappedToolStrip = control as ToolStrip; - if (control == null) { + if (control == null) + { throw new ArgumentNullException(nameof(control)); } - else if (_wrappedToolStrip == null) { - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, string.Format(SR.TypedControlCollectionShouldBeOfType, typeof(ToolStrip).Name)), control.GetType().Name); + else if (_wrappedToolStrip == null) + { + throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, string.Format(SR.TypedControlCollectionShouldBeOfType, typeof(ToolStrip).Name)), control.GetType().Name); } CommonProperties.SetAutoSize(this, true); - _wrappedToolStrip.LocationChanging += new ToolStripLocationCancelEventHandler(this.OnToolStripLocationChanging); - _wrappedToolStrip.VisibleChanged += new EventHandler(this.OnToolStripVisibleChanged); + _wrappedToolStrip.LocationChanging += new ToolStripLocationCancelEventHandler(this.OnToolStripLocationChanging); + _wrappedToolStrip.VisibleChanged += new EventHandler(this.OnToolStripVisibleChanged); } - public Rectangle CachedBounds { + public Rectangle CachedBounds + { get { return cachedBounds; } - set { cachedBounds = value; - Debug.Assert(cachedBounds.X >= 0 && cachedBounds.Y >= 0, "cached bounds are outside of the client area, investigate"); + set + { + cachedBounds = value; + Debug.Assert(cachedBounds.X >= 0 && cachedBounds.Y >= 0, "cached bounds are outside of the client area, investigate"); } } - public Control Control { + public Control Control + { get { return _wrappedToolStrip; } } // ToolStripPanelCell is considered to be Visible if the wrapped control is InDesignMode. // This property is accessed from the ToolStripPanelRow in cases where we are moving the toolStrip around // during a drag operation. - public bool ControlInDesignMode { + public bool ControlInDesignMode + { get { return (_wrappedToolStrip != null && _wrappedToolStrip.IsInDesignMode); } } - public IArrangedElement InnerElement { + public IArrangedElement InnerElement + { get { return _wrappedToolStrip as IArrangedElement; } } - public ISupportToolStripPanel DraggedControl { + public ISupportToolStripPanel DraggedControl + { get { return _wrappedToolStrip as ISupportToolStripPanel; } } - - public ToolStripPanelRow ToolStripPanelRow { + + public ToolStripPanelRow ToolStripPanelRow + { get { return parent; } - set { - if (parent != value) { - if (parent != null) { + set + { + if (parent != value) + { + if (parent != null) + { ((IList)parent.Cells).Remove(this); } parent = value; this.Margin = Padding.Empty; - + } - + } } - public override bool Visible { - get { - if (Control != null && Control.ParentInternal == ToolStripPanelRow.ToolStripPanel) { + public override bool Visible + { + get + { + if (Control != null && Control.ParentInternal == ToolStripPanelRow.ToolStripPanel) + { return InnerElement.ParticipatesInLayout; } return false; } - set { + set + { Control.Visible = value; } } - public Size MaximumSize { + public Size MaximumSize + { get { return maxSize; } } - public override LayoutEngine LayoutEngine { + public override LayoutEngine LayoutEngine + { get { return DefaultLayout.Instance; } } - protected override IArrangedElement GetContainer() { + protected override IArrangedElement GetContainer() + { return parent; } - public int Grow(int growBy) { - if (ToolStripPanelRow.Orientation == Orientation.Vertical) { + public int Grow(int growBy) + { + if (ToolStripPanelRow.Orientation == Orientation.Vertical) + { return GrowVertical(growBy); } - else { + else + { return GrowHorizontal(growBy); } - - + + } - private int GrowVertical(int growBy) { + private int GrowVertical(int growBy) + { // Grow ---] // Pref [ ] // Max [ ] - if (MaximumSize.Height >= Control.PreferredSize.Height) { + if (MaximumSize.Height >= Control.PreferredSize.Height) + { // nothing to grow. return 0; } - + // Grow ---] // Pref [ ] // Max [ ] - if (MaximumSize.Height + growBy >= Control.PreferredSize.Height) { - int freed = Control.PreferredSize.Height - MaximumSize.Height; - maxSize=LayoutUtils.MaxSize; - return freed; + if (MaximumSize.Height + growBy >= Control.PreferredSize.Height) + { + int freed = Control.PreferredSize.Height - MaximumSize.Height; + maxSize = LayoutUtils.MaxSize; + return freed; } - + // Grow ---] // Pref [ ] // Max [ ] - if (MaximumSize.Height + growBy < Control.PreferredSize.Height) { - maxSize.Height += growBy; - return growBy; + if (MaximumSize.Height + growBy < Control.PreferredSize.Height) + { + maxSize.Height += growBy; + return growBy; } return 0; } - private int GrowHorizontal(int growBy) { - + private int GrowHorizontal(int growBy) + { + // Grow ---] // Pref [ ] // Max [ ] - if (MaximumSize.Width >= Control.PreferredSize.Width) { + if (MaximumSize.Width >= Control.PreferredSize.Width) + { // nothing to grow. return 0; } - + // Grow ---] // Pref [ ] // Max [ ] - if (MaximumSize.Width + growBy >= Control.PreferredSize.Width) { - int freed = Control.PreferredSize.Width - MaximumSize.Width; - maxSize=LayoutUtils.MaxSize; - return freed; + if (MaximumSize.Width + growBy >= Control.PreferredSize.Width) + { + int freed = Control.PreferredSize.Width - MaximumSize.Width; + maxSize = LayoutUtils.MaxSize; + return freed; } - + // Grow ---] // Pref [ ] // Max [ ] - if (MaximumSize.Width + growBy < Control.PreferredSize.Width) { - maxSize.Width += growBy; - return growBy; + if (MaximumSize.Width + growBy < Control.PreferredSize.Width) + { + maxSize.Width += growBy; + return growBy; } return 0; } - protected override void Dispose(bool disposing) { - try { - if (disposing) { - if (_wrappedToolStrip != null) { + protected override void Dispose(bool disposing) + { + try + { + if (disposing) + { + if (_wrappedToolStrip != null) + { #if DEBUG cellCount--; #endif @@ -209,109 +248,132 @@ protected override void Dispose(bool disposing) { _wrappedToolStrip.VisibleChanged -= new EventHandler(this.OnToolStripVisibleChanged); } _wrappedToolStrip = null; - if (parent != null) { + if (parent != null) + { ((IList)parent.Cells).Remove(this); } parent = null; } #if DEBUG - else { + else + { cellCount--; } #endif - + } - finally { + finally + { base.Dispose(disposing); } } - protected override ArrangedElementCollection GetChildren() { + protected override ArrangedElementCollection GetChildren() + { return ArrangedElementCollection.Empty; } - public override Size GetPreferredSize(Size constrainingSize) { + public override Size GetPreferredSize(Size constrainingSize) + { ISupportToolStripPanel draggedControl = DraggedControl; Size preferredSize = Size.Empty; - - if (draggedControl.Stretch) { - if (ToolStripPanelRow.Orientation == Orientation.Horizontal) { - constrainingSize.Width = ToolStripPanelRow.Bounds.Width; - preferredSize = _wrappedToolStrip.GetPreferredSize(constrainingSize); - preferredSize.Width = constrainingSize.Width; + + if (draggedControl.Stretch) + { + if (ToolStripPanelRow.Orientation == Orientation.Horizontal) + { + constrainingSize.Width = ToolStripPanelRow.Bounds.Width; + preferredSize = _wrappedToolStrip.GetPreferredSize(constrainingSize); + preferredSize.Width = constrainingSize.Width; } - else { + else + { constrainingSize.Height = ToolStripPanelRow.Bounds.Height; preferredSize = _wrappedToolStrip.GetPreferredSize(constrainingSize); preferredSize.Height = constrainingSize.Height; - } + } } - else { + else + { preferredSize = (!_wrappedToolStrip.AutoSize) ? _wrappedToolStrip.Size : _wrappedToolStrip.GetPreferredSize(constrainingSize); } - - // return LayoutUtils.IntersectSizes(constrainingSize, preferredSize); + + // return LayoutUtils.IntersectSizes(constrainingSize, preferredSize); return preferredSize; } - protected override void SetBoundsCore(Rectangle bounds, BoundsSpecified specified) { - + protected override void SetBoundsCore(Rectangle bounds, BoundsSpecified specified) + { + currentlySizing = true; this.CachedBounds = bounds; try { - if (DraggedControl.IsCurrentlyDragging) { - if (ToolStripPanelRow.Cells[ToolStripPanelRow.Cells.Count -1] == this) { + if (DraggedControl.IsCurrentlyDragging) + { + if (ToolStripPanelRow.Cells[ToolStripPanelRow.Cells.Count - 1] == this) + { Rectangle displayRectangle = ToolStripPanelRow.DisplayRectangle; - if (ToolStripPanelRow.Orientation == Orientation.Horizontal) { + if (ToolStripPanelRow.Orientation == Orientation.Horizontal) + { int spaceToFree = bounds.Right - displayRectangle.Right; - if (spaceToFree > 0 && bounds.Width > spaceToFree) { + if (spaceToFree > 0 && bounds.Width > spaceToFree) + { bounds.Width -= spaceToFree; } } - else { + else + { int spaceToFree = bounds.Bottom - displayRectangle.Bottom; - if (spaceToFree > 0 && bounds.Height > spaceToFree) { + if (spaceToFree > 0 && bounds.Height > spaceToFree) + { bounds.Height -= spaceToFree; } } } Debug.WriteLineIf(ToolStripPanelRow.ToolStripPanelMouseDebug.TraceVerbose, "[CELL] DRAGGING calling SetBounds " + bounds.ToString()); - base.SetBoundsCore(bounds,specified); + base.SetBoundsCore(bounds, specified); InnerElement.SetBounds(bounds, specified); } - else { - if (!ToolStripPanelRow.CachedBoundsMode) { + else + { + if (!ToolStripPanelRow.CachedBoundsMode) + { Debug.WriteLineIf(ToolStripPanelRow.ToolStripPanelMouseDebug.TraceVerbose, "[CELL] NOT DRAGGING calling SetBounds " + bounds.ToString()); - base.SetBoundsCore(bounds,specified); + base.SetBoundsCore(bounds, specified); InnerElement.SetBounds(bounds, specified); - - } - + + } + } - + } finally { currentlySizing = false; - } + } } - public int Shrink(int shrinkBy) { - if (ToolStripPanelRow.Orientation == Orientation.Vertical) { + public int Shrink(int shrinkBy) + { + if (ToolStripPanelRow.Orientation == Orientation.Vertical) + { return ShrinkVertical(shrinkBy); } - else { + else + { return ShrinkHorizontal(shrinkBy); } } - private int ShrinkHorizontal(int shrinkBy) { + private int ShrinkHorizontal(int shrinkBy) + { return 0; } - - private int ShrinkVertical(int shrinkBy) { + + private int ShrinkVertical(int shrinkBy) + { return 0; } @@ -322,53 +384,66 @@ private int ShrinkVertical(int shrinkBy) { /// private void OnToolStripLocationChanging(object sender, ToolStripLocationCancelEventArgs e) { - if (ToolStripPanelRow == null) { + if (ToolStripPanelRow == null) + { return; } - if (!currentlySizing && !currentlyDragging) { - try { + if (!currentlySizing && !currentlyDragging) + { + try + { currentlyDragging = true; Point newloc = e.NewLocation; // detect if we havent yet performed a layout - force one so we can // properly join to the row. - if (ToolStripPanelRow != null && ToolStripPanelRow.Bounds == Rectangle.Empty) { - ToolStripPanelRow.ToolStripPanel.PerformUpdate(true); + if (ToolStripPanelRow != null && ToolStripPanelRow.Bounds == Rectangle.Empty) + { + ToolStripPanelRow.ToolStripPanel.PerformUpdate(true); } - if (_wrappedToolStrip != null) { - ToolStripPanelRow.ToolStripPanel.Join(_wrappedToolStrip, newloc); + if (_wrappedToolStrip != null) + { + ToolStripPanelRow.ToolStripPanel.Join(_wrappedToolStrip, newloc); } } - finally { + finally + { currentlyDragging = false; e.Cancel = true; } } } - private void OnToolStripVisibleChanged(object sender, EventArgs e) { + private void OnToolStripVisibleChanged(object sender, EventArgs e) + { + + if (_wrappedToolStrip != null + && !_wrappedToolStrip.IsInDesignMode - if (_wrappedToolStrip != null - && !_wrappedToolStrip.IsInDesignMode - - && !_wrappedToolStrip.IsCurrentlyDragging + && !_wrappedToolStrip.IsCurrentlyDragging && !_wrappedToolStrip.IsDisposed // ensure we have a live-runtime only toolstrip. - && !_wrappedToolStrip.Disposing) { - + && !_wrappedToolStrip.Disposing) + { + // Rejoin the row when visibility is toggled. // we dont want to do this logic at DT, as the DropSourceBehavior // will set the toolstrip visible = false. - if (!Control.Visible) { + if (!Control.Visible) + { // if we are becoming visible = false, remember if we were in a toolstrippanelrow at the time. restoreOnVisibleChanged = (ToolStripPanelRow != null && ((IList)ToolStripPanelRow.Cells).Contains(this)); } - else if (restoreOnVisibleChanged) { - try { + else if (restoreOnVisibleChanged) + { + try + { // if we are becoming visible = true, and we ARE in a toolstrippanelrow, rejoin. - if (ToolStripPanelRow != null && ((IList)ToolStripPanelRow.Cells).Contains(this)) { - ToolStripPanelRow.ToolStripPanel.Join(_wrappedToolStrip, _wrappedToolStrip.Location); + if (ToolStripPanelRow != null && ((IList)ToolStripPanelRow.Cells).Contains(this)) + { + ToolStripPanelRow.ToolStripPanel.Join(_wrappedToolStrip, _wrappedToolStrip.Location); } } - finally { + finally + { restoreOnVisibleChanged = false; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs index f08602eab0d..c5160a7d3a0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs @@ -5,7 +5,8 @@ //#define DEBUG_PAINT -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Drawing; using System.Windows.Forms.Layout; using System.Collections.Specialized; @@ -16,7 +17,8 @@ namespace System.Windows.Forms { using System.Globalization; [ToolboxItem(false)] - public class ToolStripPanelRow : Component, IArrangedElement { + public class ToolStripPanelRow : Component, IArrangedElement + { private Rectangle bounds = Rectangle.Empty; private ToolStripPanel parent = null; private BitVector32 state = new BitVector32(); @@ -34,13 +36,13 @@ public class ToolStripPanelRow : Component, IArrangedElement { private static readonly int stateInitialized = BitVector32.CreateMask(stateLocked); private static readonly int stateCachedBoundsMode = BitVector32.CreateMask(stateInitialized); private static readonly int stateInLayout = BitVector32.CreateMask(stateCachedBoundsMode); - - - - + + + + private static readonly int PropControlsCollection = PropertyStore.CreateKey(); - + #if DEBUG internal static TraceSwitch ToolStripPanelRowCreationDebug = new TraceSwitch("ToolStripPanelRowCreationDebug", "Debug code for rafting row creation"); #else @@ -53,57 +55,68 @@ public class ToolStripPanelRow : Component, IArrangedElement { #endif - public ToolStripPanelRow(ToolStripPanel parent) : this(parent, true){ + public ToolStripPanelRow(ToolStripPanel parent) : this(parent, true) + { } [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] - internal ToolStripPanelRow(ToolStripPanel parent, bool visible) { + internal ToolStripPanelRow(ToolStripPanel parent, bool visible) + { #if DEBUG thisRowID = ++rowCreationCount; #endif - if (DpiHelper.IsScalingRequirementMet) { + if (DpiHelper.IsScalingRequirementMet) + { minAllowedWidth = DpiHelper.LogicalToDeviceUnitsX(MINALLOWEDWIDTH); } this.parent = parent; this.state[stateVisible] = visible; - this.state[stateDisposing | stateLocked| stateInitialized] = false; + this.state[stateDisposing | stateLocked | stateInitialized] = false; Debug.WriteLineIf(ToolStripPanelRowCreationDebug.TraceVerbose, "Created new ToolStripPanelRow"); - using (LayoutTransaction lt = new LayoutTransaction(parent, this, null)) { + using (LayoutTransaction lt = new LayoutTransaction(parent, this, null)) + { this.Margin = DefaultMargin; CommonProperties.SetAutoSize(this, true); } - + } - public Rectangle Bounds { - get { + public Rectangle Bounds + { + get + { return bounds; } } - + [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlControlsDescr)), SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public Control[] Controls { - get { + public Control[] Controls + { + get + { Control[] controls = new Control[ControlsInternal.Count]; - ControlsInternal.CopyTo(controls,0); + ControlsInternal.CopyTo(controls, 0); return controls; } } - + /// /// Collection of child controls. /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlControlsDescr))] - internal ToolStripPanelRowControlCollection ControlsInternal { - get { + internal ToolStripPanelRowControlCollection ControlsInternal + { + get + { ToolStripPanelRowControlCollection controlsCollection = (ToolStripPanelRowControlCollection)Properties.GetObject(PropControlsCollection); - if (controlsCollection == null) { + if (controlsCollection == null) + { controlsCollection = CreateControlsInstance(); Properties.SetObject(PropControlsCollection, controlsCollection); } @@ -112,27 +125,35 @@ internal ToolStripPanelRowControlCollection ControlsInternal { } } - internal ArrangedElementCollection Cells { - get { + internal ArrangedElementCollection Cells + { + get + { return ControlsInternal.Cells; } } - internal bool CachedBoundsMode { - get { + internal bool CachedBoundsMode + { + get + { return state[stateCachedBoundsMode]; } - set { + set + { state[stateCachedBoundsMode] = value; } } - private ToolStripPanelRowManager RowManager { - get { - if (rowManager == null) { - rowManager = (Orientation == Orientation.Horizontal) ? new HorizontalRowManager(this) as ToolStripPanelRowManager + private ToolStripPanelRowManager RowManager + { + get + { + if (rowManager == null) + { + rowManager = (Orientation == Orientation.Horizontal) ? new HorizontalRowManager(this) as ToolStripPanelRowManager : new VerticalRowManager(this) as ToolStripPanelRowManager; Initialized = true; } @@ -141,76 +162,98 @@ private ToolStripPanelRowManager RowManager { } } - protected virtual Padding DefaultMargin { - get { + protected virtual Padding DefaultMargin + { + get + { ToolStripPanelCell cell = RowManager.GetNextVisibleCell(0, /*forward*/true); - if (cell != null && cell.DraggedControl != null) { - if (cell.DraggedControl.Stretch) { + if (cell != null && cell.DraggedControl != null) + { + if (cell.DraggedControl.Stretch) + { Padding padding = ToolStripPanel.RowMargin; // clear out the padding. - if (Orientation == Orientation.Horizontal) { + if (Orientation == Orientation.Horizontal) + { padding.Left = 0; padding.Right = 0; } - else { + else + { padding.Top = 0; padding.Bottom = 0; } return padding; } } - return ToolStripPanel.RowMargin; + return ToolStripPanel.RowMargin; } } - protected virtual Padding DefaultPadding { + protected virtual Padding DefaultPadding + { get { return Padding.Empty; } } - public Rectangle DisplayRectangle { - get { + public Rectangle DisplayRectangle + { + get + { return RowManager.DisplayRectangle; } } - public LayoutEngine LayoutEngine { - get { + public LayoutEngine LayoutEngine + { + get + { return FlowLayout.Instance; } } - internal bool Locked { - get { + internal bool Locked + { + get + { return state[stateLocked]; - } + } } - private bool Initialized { - get { + private bool Initialized + { + get + { return state[stateInitialized]; } - set { + set + { state[stateInitialized] = value; } } - public Padding Margin { + public Padding Margin + { get { return CommonProperties.GetMargin(this); } - set { if (Margin != value ) CommonProperties.SetMargin(this, value); } + set { if (Margin != value) CommonProperties.SetMargin(this, value); } } - public virtual Padding Padding { + public virtual Padding Padding + { get { return CommonProperties.GetPadding(this, DefaultPadding); } - set { - if (Padding != value) CommonProperties.SetPadding(this, value); + set + { + if (Padding != value) + CommonProperties.SetPadding(this, value); } } - internal Control ParentInternal { - get { + internal Control ParentInternal + { + get + { return parent; - } + } } /// @@ -218,32 +261,41 @@ internal Control ParentInternal { /// whose value is not always set, you should store it in here to save /// space. /// - internal PropertyStore Properties { - get { + internal PropertyStore Properties + { + get + { return propertyStore; } } - public ToolStripPanel ToolStripPanel { - get { + public ToolStripPanel ToolStripPanel + { + get + { return parent; } } - internal bool Visible { - get { + internal bool Visible + { + get + { return state[stateVisible]; - } + } } - public Orientation Orientation { - get { + public Orientation Orientation + { + get + { return ToolStripPanel.Orientation; } } #if DEBUG - internal void Debug_PrintRowID() { + internal void Debug_PrintRowID() + { Debug.Write(thisRowID.ToString(CultureInfo.CurrentCulture)); } #endif @@ -252,136 +304,168 @@ internal void Debug_PrintRowID() { /// returns true if there is enough space to "raft" the control /// ow returns false /// - public bool CanMove(ToolStrip toolStripToDrag) { + public bool CanMove(ToolStrip toolStripToDrag) + { return !ToolStripPanel.Locked && !Locked && RowManager.CanMove(toolStripToDrag); } - private ToolStripPanelRowControlCollection CreateControlsInstance() { + private ToolStripPanelRowControlCollection CreateControlsInstance() + { return new ToolStripPanelRowControlCollection(this); } - protected override void Dispose(bool disposing) { - try { - if (disposing) { - + protected override void Dispose(bool disposing) + { + try + { + if (disposing) + { + Debug.WriteLineIf(ToolStripPanelRowCreationDebug.TraceVerbose, "Disposed ToolStripPanelRow"); state[stateDisposing] = true; this.ControlsInternal.Clear(); } } - finally { + finally + { state[stateDisposing] = false; base.Dispose(disposing); } } - protected internal virtual void OnControlAdded(Control control, int index) { + protected internal virtual void OnControlAdded(Control control, int index) + { + - // if previously added - remove. ISupportToolStripPanel controlToBeDragged = control as ISupportToolStripPanel; - - if (controlToBeDragged != null) { + + if (controlToBeDragged != null) + { controlToBeDragged.ToolStripPanelRow = this; } RowManager.OnControlAdded(control, index); } - protected internal virtual void OnOrientationChanged() { + protected internal virtual void OnOrientationChanged() + { this.rowManager = null; } - protected void OnBoundsChanged(Rectangle oldBounds, Rectangle newBounds) { + protected void OnBoundsChanged(Rectangle oldBounds, Rectangle newBounds) + { ((IArrangedElement)this).PerformLayout((IArrangedElement)this, PropertyNames.Size); - RowManager.OnBoundsChanged(oldBounds,newBounds); + RowManager.OnBoundsChanged(oldBounds, newBounds); } - protected internal virtual void OnControlRemoved(Control control, int index) { - if (!state[stateDisposing]) { + protected internal virtual void OnControlRemoved(Control control, int index) + { + if (!state[stateDisposing]) + { this.SuspendLayout(); RowManager.OnControlRemoved(control, index); // if previously added - remove. ISupportToolStripPanel controlToBeDragged = control as ISupportToolStripPanel; - if (controlToBeDragged != null && controlToBeDragged.ToolStripPanelRow == this) { + if (controlToBeDragged != null && controlToBeDragged.ToolStripPanelRow == this) + { controlToBeDragged.ToolStripPanelRow = null; } this.ResumeLayout(true); - if (this.ControlsInternal.Count <= 0) { + if (this.ControlsInternal.Count <= 0) + { ToolStripPanel.RowsInternal.Remove(this); Dispose(); } } } - internal Size GetMinimumSize(ToolStrip toolStrip) { - if (toolStrip.MinimumSize == Size.Empty) { - return new Size(minAllowedWidth,minAllowedWidth); + internal Size GetMinimumSize(ToolStrip toolStrip) + { + if (toolStrip.MinimumSize == Size.Empty) + { + return new Size(minAllowedWidth, minAllowedWidth); } - else { + else + { return toolStrip.MinimumSize; } } - private void ApplyCachedBounds() { - for (int i = 0; i < this.Cells.Count; i++) { + private void ApplyCachedBounds() + { + for (int i = 0; i < this.Cells.Count; i++) + { IArrangedElement element = Cells[i] as IArrangedElement; - if (element.ParticipatesInLayout) { + if (element.ParticipatesInLayout) + { ToolStripPanelCell cell = element as ToolStripPanelCell; element.SetBounds(cell.CachedBounds, BoundsSpecified.None); -// Debug.Assert( cell.Control == null || cell.CachedBounds.Location == cell.Control.Bounds.Location, "CachedBounds out of sync with bounds!"); - } + // Debug.Assert( cell.Control == null || cell.CachedBounds.Location == cell.Control.Bounds.Location, "CachedBounds out of sync with bounds!"); + } } } - protected virtual void OnLayout(LayoutEventArgs e) { - if (Initialized && !state[stateInLayout]) { - state[stateInLayout] = true; - try { + protected virtual void OnLayout(LayoutEventArgs e) + { + if (Initialized && !state[stateInLayout]) + { + state[stateInLayout] = true; + try + { this.Margin = DefaultMargin; CachedBoundsMode = true; - try { + try + { // dont layout in the constructor that's just tacky. bool parentNeedsLayout = LayoutEngine.Layout(this, e); } - finally { + finally + { CachedBoundsMode = false; } - ToolStripPanelCell cell = RowManager.GetNextVisibleCell(this.Cells.Count -1, /*forward*/false); - if (cell == null) { + ToolStripPanelCell cell = RowManager.GetNextVisibleCell(this.Cells.Count - 1, /*forward*/false); + if (cell == null) + { ApplyCachedBounds(); } - else if (Orientation == Orientation.Horizontal) { + else if (Orientation == Orientation.Horizontal) + { OnLayoutHorizontalPostFix(); } - else { + else + { OnLayoutVerticalPostFix(); } - + } - finally { + finally + { state[stateInLayout] = false; } } } - - - private void OnLayoutHorizontalPostFix() { - ToolStripPanelCell cell = RowManager.GetNextVisibleCell(this.Cells.Count -1, /*forward*/false); - if (cell == null) { + + private void OnLayoutHorizontalPostFix() + { + + ToolStripPanelCell cell = RowManager.GetNextVisibleCell(this.Cells.Count - 1, /*forward*/false); + if (cell == null) + { ApplyCachedBounds(); return; } // figure out how much space we actually need to free. int spaceToFree = cell.CachedBounds.Right - RowManager.DisplayRectangle.Right; - - if (spaceToFree <= 0) { + + if (spaceToFree <= 0) + { // we're all good. Just apply the cached bounds. ApplyCachedBounds(); return; @@ -391,7 +475,8 @@ private void OnLayoutHorizontalPostFix() { // since layout sisuspended, we'll need to watch changes to the margin // as a result of calling FreeSpaceFromRow. int[] margins = new int[Cells.Count]; - for (int i = 0; i < Cells.Count; i++) { + for (int i = 0; i < Cells.Count; i++) + { ToolStripPanelCell c = Cells[i] as ToolStripPanelCell; margins[i] = c.Margin.Left; } @@ -399,144 +484,167 @@ private void OnLayoutHorizontalPostFix() { spaceToFree -= RowManager.FreeSpaceFromRow(spaceToFree); // now apply those changes to the cached bounds. - for (int i = 0; i < Cells.Count; i++) { + for (int i = 0; i < Cells.Count; i++) + { ToolStripPanelCell c = Cells[i] as ToolStripPanelCell; Rectangle cachedBounds = c.CachedBounds; cachedBounds.X -= Math.Max(0, margins[i] - c.Margin.Left); c.CachedBounds = cachedBounds; } - - if (spaceToFree <= 0) { + + if (spaceToFree <= 0) + { ApplyCachedBounds(); return; } - - + + // STEP 2 change the size of the remaing ToolStrips from Right to Left. - int[] cellOffsets = null; - for (int i = Cells.Count-1; i >= 0; i--) { - ToolStripPanelCell currentCell =Cells[i] as ToolStripPanelCell; - if (currentCell.Visible) { + int[] cellOffsets = null; + for (int i = Cells.Count - 1; i >= 0; i--) + { + ToolStripPanelCell currentCell = Cells[i] as ToolStripPanelCell; + if (currentCell.Visible) + { Size minSize = GetMinimumSize(currentCell.Control as ToolStrip); Rectangle cachedBounds = currentCell.CachedBounds; // found some space to free. - if (cachedBounds.Width > minSize.Width) { + if (cachedBounds.Width > minSize.Width) + { spaceToFree -= (cachedBounds.Width - minSize.Width); // make sure we dont take more space than we need - if spaceToFree is less than 0, add back in. - cachedBounds.Width = (spaceToFree < 0) ? minSize.Width + -spaceToFree : minSize.Width; + cachedBounds.Width = (spaceToFree < 0) ? minSize.Width + -spaceToFree : minSize.Width; // we're not reperforming a layout, so we need to adjust the next cell - for (int j = i+1; j < Cells.Count; j++) { - if (cellOffsets == null) { + for (int j = i + 1; j < Cells.Count; j++) + { + if (cellOffsets == null) + { cellOffsets = new int[Cells.Count]; } - cellOffsets[j] += Math.Max(0,currentCell.CachedBounds.Width-cachedBounds.Width); + cellOffsets[j] += Math.Max(0, currentCell.CachedBounds.Width - cachedBounds.Width); } currentCell.CachedBounds = cachedBounds; } } - if (spaceToFree <= 0) { + if (spaceToFree <= 0) + { break; } } // fixup for items before it shrinking. - if (cellOffsets != null) { - for (int i = 0; i < Cells.Count; i++) { - ToolStripPanelCell c = Cells[i] as ToolStripPanelCell; - Rectangle cachedBounds = c.CachedBounds; - cachedBounds.X -= cellOffsets[i]; - c.CachedBounds = cachedBounds; - } + if (cellOffsets != null) + { + for (int i = 0; i < Cells.Count; i++) + { + ToolStripPanelCell c = Cells[i] as ToolStripPanelCell; + Rectangle cachedBounds = c.CachedBounds; + cachedBounds.X -= cellOffsets[i]; + c.CachedBounds = cachedBounds; + } } ApplyCachedBounds(); - + } - - private void OnLayoutVerticalPostFix() { - - ToolStripPanelCell cell = RowManager.GetNextVisibleCell(this.Cells.Count -1, /*forward*/false); - // figure out how much space we actually need to free. - int spaceToFree = cell.CachedBounds.Bottom - RowManager.DisplayRectangle.Bottom; - - if (spaceToFree <= 0) { - // we're all good. Just apply the cached bounds. - ApplyCachedBounds(); - return; - } - // STEP 1 remove empty space in the row. - - // since layout sisuspended, we'll need to watch changes to the margin - // as a result of calling FreeSpaceFromRow. - int[] margins = new int[Cells.Count]; - for (int i = 0; i < Cells.Count; i++) { - ToolStripPanelCell c = Cells[i] as ToolStripPanelCell; - margins[i] = c.Margin.Top; - } - - spaceToFree -= RowManager.FreeSpaceFromRow(spaceToFree); - - // now apply those changes to the cached bounds. - for (int i = 0; i < Cells.Count; i++) { - ToolStripPanelCell c = Cells[i] as ToolStripPanelCell; - Rectangle cachedBounds = c.CachedBounds; - cachedBounds.X = Math.Max(0, cachedBounds.X - margins[i] - c.Margin.Top); - c.CachedBounds = cachedBounds; - } - - if (spaceToFree <= 0) { - ApplyCachedBounds(); - return; - } - - - - // STEP 2 change the size of the remaing ToolStrips from Bottom to Top. - int[] cellOffsets = null; - for (int i = Cells.Count-1; i >= 0; i--) { - ToolStripPanelCell currentCell =Cells[i] as ToolStripPanelCell; - if (currentCell.Visible) { - Size minSize = GetMinimumSize(currentCell.Control as ToolStrip); - Rectangle cachedBounds = currentCell.CachedBounds; - - // found some space to free. - if (cachedBounds.Height > minSize.Height) { - spaceToFree -= (cachedBounds.Height - minSize.Height); - // make sure we dont take more space than we need - if spaceToFree is less than 0, add back in. - cachedBounds.Height = (spaceToFree < 0) ? minSize.Height + -spaceToFree : minSize.Height; - - // we're not reperforming a layout, so we need to adjust the next cell - for (int j = i+1; j < Cells.Count; j++) { - if (cellOffsets == null) { - cellOffsets = new int[Cells.Count]; - } - cellOffsets[j] += Math.Max(0,currentCell.CachedBounds.Height-cachedBounds.Height); - } - currentCell.CachedBounds = cachedBounds; - } - } - if (spaceToFree <= 0) { - break; - } - } - - // fixup for items before it shrinking. - if (cellOffsets != null) { - for (int i = 0; i < Cells.Count; i++) { - ToolStripPanelCell c = Cells[i] as ToolStripPanelCell; - Rectangle cachedBounds = c.CachedBounds; - cachedBounds.Y -= cellOffsets[i]; - c.CachedBounds = cachedBounds; - } - } - ApplyCachedBounds(); - - } + private void OnLayoutVerticalPostFix() + { + + ToolStripPanelCell cell = RowManager.GetNextVisibleCell(this.Cells.Count - 1, /*forward*/false); + // figure out how much space we actually need to free. + int spaceToFree = cell.CachedBounds.Bottom - RowManager.DisplayRectangle.Bottom; + + if (spaceToFree <= 0) + { + // we're all good. Just apply the cached bounds. + ApplyCachedBounds(); + return; + } + // STEP 1 remove empty space in the row. + + // since layout sisuspended, we'll need to watch changes to the margin + // as a result of calling FreeSpaceFromRow. + int[] margins = new int[Cells.Count]; + for (int i = 0; i < Cells.Count; i++) + { + ToolStripPanelCell c = Cells[i] as ToolStripPanelCell; + margins[i] = c.Margin.Top; + } + + spaceToFree -= RowManager.FreeSpaceFromRow(spaceToFree); + + // now apply those changes to the cached bounds. + for (int i = 0; i < Cells.Count; i++) + { + ToolStripPanelCell c = Cells[i] as ToolStripPanelCell; + Rectangle cachedBounds = c.CachedBounds; + cachedBounds.X = Math.Max(0, cachedBounds.X - margins[i] - c.Margin.Top); + c.CachedBounds = cachedBounds; + } + + if (spaceToFree <= 0) + { + ApplyCachedBounds(); + return; + } + + + + // STEP 2 change the size of the remaing ToolStrips from Bottom to Top. + int[] cellOffsets = null; + for (int i = Cells.Count - 1; i >= 0; i--) + { + ToolStripPanelCell currentCell = Cells[i] as ToolStripPanelCell; + if (currentCell.Visible) + { + Size minSize = GetMinimumSize(currentCell.Control as ToolStrip); + Rectangle cachedBounds = currentCell.CachedBounds; + + // found some space to free. + if (cachedBounds.Height > minSize.Height) + { + spaceToFree -= (cachedBounds.Height - minSize.Height); + // make sure we dont take more space than we need - if spaceToFree is less than 0, add back in. + cachedBounds.Height = (spaceToFree < 0) ? minSize.Height + -spaceToFree : minSize.Height; + + // we're not reperforming a layout, so we need to adjust the next cell + for (int j = i + 1; j < Cells.Count; j++) + { + if (cellOffsets == null) + { + cellOffsets = new int[Cells.Count]; + } + cellOffsets[j] += Math.Max(0, currentCell.CachedBounds.Height - cachedBounds.Height); + } + currentCell.CachedBounds = cachedBounds; + } + } + if (spaceToFree <= 0) + { + break; + } + } + + // fixup for items before it shrinking. + if (cellOffsets != null) + { + for (int i = 0; i < Cells.Count; i++) + { + ToolStripPanelCell c = Cells[i] as ToolStripPanelCell; + Rectangle cachedBounds = c.CachedBounds; + cachedBounds.Y -= cellOffsets[i]; + c.CachedBounds = cachedBounds; + } + } + + ApplyCachedBounds(); + + } #if DEBUG_PAINT internal void PaintColumns(PaintEventArgs e) { @@ -567,8 +675,10 @@ internal void PaintColumns(PaintEventArgs e) { } #endif - private void SetBounds(Rectangle bounds) { - if (bounds != this.bounds) { + private void SetBounds(Rectangle bounds) + { + if (bounds != this.bounds) + { Rectangle oldBounds = this.bounds; this.bounds = bounds; @@ -576,21 +686,26 @@ private void SetBounds(Rectangle bounds) { } } - private void SuspendLayout() { + private void SuspendLayout() + { suspendCount++; } - private void ResumeLayout(bool performLayout) { + private void ResumeLayout(bool performLayout) + { suspendCount--; - if (performLayout) { + if (performLayout) + { ((IArrangedElement)this).PerformLayout(this, null); } } /// /// - ArrangedElementCollection IArrangedElement.Children { - get { + ArrangedElementCollection IArrangedElement.Children + { + get + { return Cells; } } @@ -598,15 +713,19 @@ ArrangedElementCollection IArrangedElement.Children { /// /// Should not be exposed as this returns an unexposed type. /// - IArrangedElement IArrangedElement.Container { - get { + IArrangedElement IArrangedElement.Container + { + get + { return this.ToolStripPanel; } } - Rectangle IArrangedElement.DisplayRectangle { - get { + Rectangle IArrangedElement.DisplayRectangle + { + get + { Rectangle displayRectangle = this.Bounds; return displayRectangle; @@ -614,25 +733,32 @@ Rectangle IArrangedElement.DisplayRectangle { } - bool IArrangedElement.ParticipatesInLayout { - get { + bool IArrangedElement.ParticipatesInLayout + { + get + { return Visible; } } - PropertyStore IArrangedElement.Properties { - get { + PropertyStore IArrangedElement.Properties + { + get + { return this.Properties; } } - Size IArrangedElement.GetPreferredSize(Size constrainingSize) { + Size IArrangedElement.GetPreferredSize(Size constrainingSize) + { Size preferredSize = LayoutEngine.GetPreferredSize(this, constrainingSize - Padding.Size) + Padding.Size; - if (Orientation == Orientation.Horizontal && ParentInternal != null) { + if (Orientation == Orientation.Horizontal && ParentInternal != null) + { preferredSize.Width = DisplayRectangle.Width; } - else { + else + { preferredSize.Height = DisplayRectangle.Height; } @@ -640,126 +766,151 @@ Size IArrangedElement.GetPreferredSize(Size constrainingSize) { } // Sets the bounds for an element. - void IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) { + void IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) + { // in this case the parent is telling us to refresh our bounds - dont // call PerformLayout SetBounds(bounds); } - - void IArrangedElement.PerformLayout(IArrangedElement container, string propertyName) { - if (suspendCount <= 0) { + + void IArrangedElement.PerformLayout(IArrangedElement container, string propertyName) + { + if (suspendCount <= 0) + { OnLayout(new LayoutEventArgs(container, propertyName)); } } - #region MouseStuff + #region MouseStuff #if DEBUG - internal static readonly TraceSwitch ToolStripPanelMouseDebug = new TraceSwitch("ToolStripPanelMouse", "Debug ToolStrip WM_MOUSEACTIVATE code"); + internal static readonly TraceSwitch ToolStripPanelMouseDebug = new TraceSwitch("ToolStripPanelMouse", "Debug ToolStrip WM_MOUSEACTIVATE code"); #else internal static readonly TraceSwitch ToolStripPanelMouseDebug; #endif - - internal Rectangle DragBounds { - get { + + internal Rectangle DragBounds + { + get + { return RowManager.DragBounds; } } - internal void MoveControl(ToolStrip movingControl, Point startClientLocation, Point endClientLocation) { + internal void MoveControl(ToolStrip movingControl, Point startClientLocation, Point endClientLocation) + { RowManager.MoveControl(movingControl, startClientLocation, endClientLocation); } // - internal void JoinRow(ToolStrip toolStripToDrag, Point locationToDrag) { + internal void JoinRow(ToolStrip toolStripToDrag, Point locationToDrag) + { RowManager.JoinRow(toolStripToDrag, locationToDrag); } - internal void LeaveRow(ToolStrip toolStripToDrag) { + internal void LeaveRow(ToolStrip toolStripToDrag) + { RowManager.LeaveRow(toolStripToDrag); - if (ControlsInternal.Count == 0) { + if (ControlsInternal.Count == 0) + { ToolStripPanel.RowsInternal.Remove(this); Dispose(); } } [Conditional("DEBUG")] - private void PrintPlacements(int index) { - /* Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "Results:\r\n\t-------"); - Debug.Indent(); - Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "ToolStripPanelRow: " + this.Bounds.ToString()); + private void PrintPlacements(int index) + { + /* Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "Results:\r\n\t-------"); + Debug.Indent(); + Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "ToolStripPanelRow: " + this.Bounds.ToString()); - float sumColWidths = 0F; - int sumWidths = 0; + float sumColWidths = 0F; + int sumWidths = 0; - for (int i = 0; i < this.Controls.Count - 1; i++) { - string indicator = (i == index) ? "*" : " "; + for (int i = 0; i < this.Controls.Count - 1; i++) { + string indicator = (i == index) ? "*" : " "; - Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, String.Format("{0} {1} Column Width {2} Control Size {3}", indicator, this.Controls[i].Name, TableLayoutSettings.ColumnStyles[i].Width, this.Controls[i].Bounds)); - sumColWidths += TableLayoutSettings.ColumnStyles[i].Width; - sumWidths += this.Controls[i].Width; - } + Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, String.Format("{0} {1} Column Width {2} Control Size {3}", indicator, this.Controls[i].Name, TableLayoutSettings.ColumnStyles[i].Width, this.Controls[i].Bounds)); + sumColWidths += TableLayoutSettings.ColumnStyles[i].Width; + sumWidths += this.Controls[i].Width; + } - Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "Total Column Width " + sumColWidths.ToString() + " Total control widths " + sumWidths.ToString()); - Debug.Unindent(); - */ + Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "Total Column Width " + sumColWidths.ToString() + " Total control widths " + sumWidths.ToString()); + Debug.Unindent(); + */ } - #endregion + #endregion - private abstract class ToolStripPanelRowManager { + private abstract class ToolStripPanelRowManager + { private FlowLayoutSettings flowLayoutSettings = null; private ToolStripPanelRow owner = null; - public ToolStripPanelRowManager(ToolStripPanelRow owner) { + public ToolStripPanelRowManager(ToolStripPanelRow owner) + { this.owner = owner; } - public virtual bool CanMove(ToolStrip toolStripToDrag) { + public virtual bool CanMove(ToolStrip toolStripToDrag) + { ISupportToolStripPanel raftingControl = toolStripToDrag as ISupportToolStripPanel; - if (raftingControl != null) { - if (raftingControl.Stretch) { + if (raftingControl != null) + { + if (raftingControl.Stretch) + { Debug.WriteLineIf(ToolStripPanelRow.ToolStripPanelRowCreationDebug.TraceVerbose, "TSP RM CanMove returns false - the item moving is stretched."); return false; - } - } - foreach (Control c in Row.ControlsInternal) { - raftingControl = c as ISupportToolStripPanel; - if (raftingControl != null) { - if (raftingControl.Stretch) { - Debug.WriteLineIf(ToolStripPanelRow.ToolStripPanelRowCreationDebug.TraceVerbose, "TSP RM CanMove returns false - the row already contains a stretched item."); - return false; + } + } + foreach (Control c in Row.ControlsInternal) + { + raftingControl = c as ISupportToolStripPanel; + if (raftingControl != null) + { + if (raftingControl.Stretch) + { + Debug.WriteLineIf(ToolStripPanelRow.ToolStripPanelRowCreationDebug.TraceVerbose, "TSP RM CanMove returns false - the row already contains a stretched item."); + return false; } - } + } } return true; } - public virtual Rectangle DragBounds { + public virtual Rectangle DragBounds + { get { return Rectangle.Empty; } } - public virtual Rectangle DisplayRectangle { + public virtual Rectangle DisplayRectangle + { get { return Rectangle.Empty; } } - public ToolStripPanel ToolStripPanel { + public ToolStripPanel ToolStripPanel + { get { return owner.ToolStripPanel; } } - public ToolStripPanelRow Row { + public ToolStripPanelRow Row + { get { return owner; } } - public FlowLayoutSettings FlowLayoutSettings { - get { - if (flowLayoutSettings == null) { + public FlowLayoutSettings FlowLayoutSettings + { + get + { + if (flowLayoutSettings == null) + { flowLayoutSettings = new FlowLayoutSettings(owner); } @@ -767,140 +918,173 @@ public FlowLayoutSettings FlowLayoutSettings { } } - protected internal virtual int FreeSpaceFromRow(int spaceToFree) { + protected internal virtual int FreeSpaceFromRow(int spaceToFree) + { return 0; } - protected virtual int Grow(int index, int growBy) { + protected virtual int Grow(int index, int growBy) + { int freedSpace = 0; - if (index >= 0 && index < Row.ControlsInternal.Count - 1) { + if (index >= 0 && index < Row.ControlsInternal.Count - 1) + { ToolStripPanelCell cell = (ToolStripPanelCell)Row.Cells[index]; - if (cell.Visible) { + if (cell.Visible) + { freedSpace = cell.Grow(growBy); } } - return freedSpace; + return freedSpace; } - public ToolStripPanelCell GetNextVisibleCell(int index, bool forward) { - if (forward) { - for (int i = index; i < Row.Cells.Count; i++) { + public ToolStripPanelCell GetNextVisibleCell(int index, bool forward) + { + if (forward) + { + for (int i = index; i < Row.Cells.Count; i++) + { ToolStripPanelCell cell = Row.Cells[i] as ToolStripPanelCell; - if ((cell.Visible || (owner.parent.Visible && cell.ControlInDesignMode)) && cell.ToolStripPanelRow == this.owner) { + if ((cell.Visible || (owner.parent.Visible && cell.ControlInDesignMode)) && cell.ToolStripPanelRow == this.owner) + { return cell; } } } - else { - for (int i = index; i >=0; i--) { + else + { + for (int i = index; i >= 0; i--) + { ToolStripPanelCell cell = Row.Cells[i] as ToolStripPanelCell; - if ((cell.Visible || (owner.parent.Visible && cell.ControlInDesignMode)) && cell.ToolStripPanelRow == this.owner) { + if ((cell.Visible || (owner.parent.Visible && cell.ControlInDesignMode)) && cell.ToolStripPanelRow == this.owner) + { return cell; } } } return null; - + } - + /// /// grows all controls after the index to be their preferred size. /// reports back how much space was used. /// - protected virtual int GrowControlsAfter(int index, int growBy) { - if (growBy < 0) { - Debug.Fail("why was a negative number given to growControlsAfter?"); - return 0; - } - - int spaceToFree = growBy; - - for (int i = index + 1; i < Row.ControlsInternal.Count; i++) { - // grow the n+1 item first if it was previously shrunk. - int freedSpace = Grow(i, spaceToFree); - - if (freedSpace >= 0) { - spaceToFree -= freedSpace; - if (spaceToFree <= 0) { - return growBy; - } - } - } + protected virtual int GrowControlsAfter(int index, int growBy) + { + if (growBy < 0) + { + Debug.Fail("why was a negative number given to growControlsAfter?"); + return 0; + } + + int spaceToFree = growBy; + + for (int i = index + 1; i < Row.ControlsInternal.Count; i++) + { + // grow the n+1 item first if it was previously shrunk. + int freedSpace = Grow(i, spaceToFree); + + if (freedSpace >= 0) + { + spaceToFree -= freedSpace; + if (spaceToFree <= 0) + { + return growBy; + } + } + } - return growBy - spaceToFree; + return growBy - spaceToFree; } /// /// grows all controls before the index to be their preferred size. /// reports back how much space was used. /// - protected virtual int GrowControlsBefore(int index, int growBy) { - if (growBy < 0) { - Debug.Fail("why was a negative number given to growControlsAfter?"); - return 0; - } - - int spaceToFree = growBy; - - // grow the n-1 item first if it was previously shrunk. - for (int i = index - 1; i >= 0; i--) { - spaceToFree -= Grow(i, spaceToFree); - if (spaceToFree <= 0) { - return growBy; // we've already gotten all the free space. - } - } + protected virtual int GrowControlsBefore(int index, int growBy) + { + if (growBy < 0) + { + Debug.Fail("why was a negative number given to growControlsAfter?"); + return 0; + } + + int spaceToFree = growBy; + + // grow the n-1 item first if it was previously shrunk. + for (int i = index - 1; i >= 0; i--) + { + spaceToFree -= Grow(i, spaceToFree); + if (spaceToFree <= 0) + { + return growBy; // we've already gotten all the free space. + } + } - return growBy - spaceToFree; + return growBy - spaceToFree; } - - public virtual void MoveControl(ToolStrip movingControl, Point startClientLocation, Point endClientLocation) { - // ToolStripPanel.Join(movingControl, endScreenLocation); + + public virtual void MoveControl(ToolStrip movingControl, Point startClientLocation, Point endClientLocation) + { + // ToolStripPanel.Join(movingControl, endScreenLocation); } - public virtual void LeaveRow(ToolStrip toolStripToDrag) { + public virtual void LeaveRow(ToolStrip toolStripToDrag) + { } - public virtual void JoinRow(ToolStrip toolStripToDrag, Point locationToDrag) { + public virtual void JoinRow(ToolStrip toolStripToDrag, Point locationToDrag) + { } - protected internal virtual void OnControlAdded(Control c, int index) { + protected internal virtual void OnControlAdded(Control c, int index) + { } - protected internal virtual void OnControlRemoved(Control c, int index) { + protected internal virtual void OnControlRemoved(Control c, int index) + { } - protected internal virtual void OnBoundsChanged(Rectangle oldBounds, Rectangle newBounds) { + protected internal virtual void OnBoundsChanged(Rectangle oldBounds, Rectangle newBounds) + { } } - private class HorizontalRowManager : ToolStripPanelRowManager { + private class HorizontalRowManager : ToolStripPanelRowManager + { private const int DRAG_BOUNDS_INFLATE = 4; - - public HorizontalRowManager(ToolStripPanelRow owner): base (owner) { + + public HorizontalRowManager(ToolStripPanelRow owner) : base(owner) + { owner.SuspendLayout(); FlowLayoutSettings.WrapContents = false; FlowLayoutSettings.FlowDirection = FlowDirection.LeftToRight; owner.ResumeLayout(false); } - - public override Rectangle DisplayRectangle { - get { + + public override Rectangle DisplayRectangle + { + get + { Rectangle displayRect = ((IArrangedElement)Row).DisplayRectangle; - if (ToolStripPanel != null) { + if (ToolStripPanel != null) + { Rectangle raftingDisplayRectangle = ToolStripPanel.DisplayRectangle; - - if ((!ToolStripPanel.Visible || LayoutUtils.IsZeroWidthOrHeight(raftingDisplayRectangle)) && (ToolStripPanel.ParentInternal != null)){ - + + if ((!ToolStripPanel.Visible || LayoutUtils.IsZeroWidthOrHeight(raftingDisplayRectangle)) && (ToolStripPanel.ParentInternal != null)) + { + // if were layed out before we're visible we have the wrong display rectangle, so we need to calculate it. displayRect.Width = ToolStripPanel.ParentInternal.DisplayRectangle.Width - (ToolStripPanel.Margin.Horizontal + ToolStripPanel.Padding.Horizontal) - Row.Margin.Horizontal; } - else { + else + { displayRect.Width = raftingDisplayRectangle.Width - Row.Margin.Horizontal; - + } } @@ -908,12 +1092,15 @@ public override Rectangle DisplayRectangle { } } - public override Rectangle DragBounds { - get { + public override Rectangle DragBounds + { + get + { Rectangle dragBounds = Row.Bounds; int index = ToolStripPanel.RowsInternal.IndexOf(Row); - if (index > 0) { + if (index > 0) + { Rectangle previousRowBounds = ToolStripPanel.RowsInternal[index - 1].Bounds; int y = previousRowBounds.Y + previousRowBounds.Height - (previousRowBounds.Height >> 2); @@ -921,195 +1108,229 @@ public override Rectangle DragBounds { dragBounds.Y = y; } - if (index < ToolStripPanel.RowsInternal.Count - 1) { + if (index < ToolStripPanel.RowsInternal.Count - 1) + { Rectangle nextRowBounds = ToolStripPanel.RowsInternal[index + 1].Bounds; dragBounds.Height += (nextRowBounds.Height >> 2) + Row.Margin.Bottom + ToolStripPanel.RowsInternal[index + 1].Margin.Top; } - dragBounds.Width += Row.Margin.Horizontal + ToolStripPanel.Padding.Horizontal +5; - dragBounds.X -= Row.Margin.Left + ToolStripPanel.Padding.Left +4; + dragBounds.Width += Row.Margin.Horizontal + ToolStripPanel.Padding.Horizontal + 5; + dragBounds.X -= Row.Margin.Left + ToolStripPanel.Padding.Left + 4; return dragBounds; } } - + /// /// returns true if there is enough space to "raft" the control /// ow returns false /// - public override bool CanMove(ToolStrip toolStripToDrag) { + public override bool CanMove(ToolStrip toolStripToDrag) + { - if (base.CanMove(toolStripToDrag)) { + if (base.CanMove(toolStripToDrag)) + { Size totalSize = Size.Empty; - for (int i = 0; i < Row.ControlsInternal.Count; i++ ){ - totalSize += Row.GetMinimumSize(Row.ControlsInternal[i] as ToolStrip); + for (int i = 0; i < Row.ControlsInternal.Count; i++) + { + totalSize += Row.GetMinimumSize(Row.ControlsInternal[i] as ToolStrip); } - totalSize += Row.GetMinimumSize(toolStripToDrag as ToolStrip); + totalSize += Row.GetMinimumSize(toolStripToDrag as ToolStrip); return totalSize.Width < DisplayRectangle.Width; } - Debug.WriteLineIf(ToolStripPanelRow.ToolStripPanelRowCreationDebug.TraceVerbose, "HorizontalRM.CanMove returns false - not enough room"); + Debug.WriteLineIf(ToolStripPanelRow.ToolStripPanelRowCreationDebug.TraceVerbose, "HorizontalRM.CanMove returns false - not enough room"); return false; } - - protected internal override int FreeSpaceFromRow(int spaceToFree) { - int requiredSpace = spaceToFree; - // take a look at the last guy. if his right edge exceeds - // the new bounds, then we should go ahead and push him into view. - - if (spaceToFree > 0){ - // we should shrink the last guy and then move him. - ToolStripPanelCell lastCellOnRow = GetNextVisibleCell(Row.Cells.Count-1, /*forward*/false); - if (lastCellOnRow == null) { + + protected internal override int FreeSpaceFromRow(int spaceToFree) + { + int requiredSpace = spaceToFree; + // take a look at the last guy. if his right edge exceeds + // the new bounds, then we should go ahead and push him into view. + + if (spaceToFree > 0) + { + // we should shrink the last guy and then move him. + ToolStripPanelCell lastCellOnRow = GetNextVisibleCell(Row.Cells.Count - 1, /*forward*/false); + if (lastCellOnRow == null) + { return 0; - } - Padding cellMargin = lastCellOnRow.Margin; - - // only check margin.left as we are only concerned with getting right edge of - // the toolstrip into view. (space after the fact doesnt count). - if (cellMargin.Left >= spaceToFree) { - cellMargin.Left -= spaceToFree; - cellMargin.Right = 0; - spaceToFree = 0; - - } - else { - spaceToFree -= lastCellOnRow.Margin.Left; - cellMargin.Left = 0; - cellMargin.Right = 0; - } - lastCellOnRow.Margin = cellMargin; - - // start moving the toolstrips before this guy. - spaceToFree -= MoveLeft(Row.Cells.Count -1, spaceToFree); - - if (spaceToFree > 0) { - spaceToFree -= lastCellOnRow.Shrink(spaceToFree); - } - } - return requiredSpace - Math.Max(0,spaceToFree); - } - - public override void MoveControl(ToolStrip movingControl, Point clientStartLocation, Point clientEndLocation) { - if (Row.Locked) { + } + Padding cellMargin = lastCellOnRow.Margin; + + // only check margin.left as we are only concerned with getting right edge of + // the toolstrip into view. (space after the fact doesnt count). + if (cellMargin.Left >= spaceToFree) + { + cellMargin.Left -= spaceToFree; + cellMargin.Right = 0; + spaceToFree = 0; + + } + else + { + spaceToFree -= lastCellOnRow.Margin.Left; + cellMargin.Left = 0; + cellMargin.Right = 0; + } + lastCellOnRow.Margin = cellMargin; + + // start moving the toolstrips before this guy. + spaceToFree -= MoveLeft(Row.Cells.Count - 1, spaceToFree); + + if (spaceToFree > 0) + { + spaceToFree -= lastCellOnRow.Shrink(spaceToFree); + } + } + return requiredSpace - Math.Max(0, spaceToFree); + } + + public override void MoveControl(ToolStrip movingControl, Point clientStartLocation, Point clientEndLocation) + { + if (Row.Locked) + { return; } - if (DragBounds.Contains(clientEndLocation)) { + if (DragBounds.Contains(clientEndLocation)) + { int index = Row.ControlsInternal.IndexOf(movingControl); int deltaX = clientEndLocation.X - clientStartLocation.X; - if (deltaX < 0) { + if (deltaX < 0) + { // moving to the left MoveLeft(index, deltaX * -1); } - else { + else + { MoveRight(index, deltaX); } } - else { + else + { base.MoveControl(movingControl, clientStartLocation, clientEndLocation); } } - private int MoveLeft(int index, int spaceToFree) { + private int MoveLeft(int index, int spaceToFree) + { Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveLeft: " + spaceToFree.ToString(CultureInfo.InvariantCulture)); int freedSpace = 0; - + Row.SuspendLayout(); - try { - if (spaceToFree == 0 || index < 0) { - Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveLeft Early EXIT - 0 "); + try + { + if (spaceToFree == 0 || index < 0) + { + Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveLeft Early EXIT - 0 "); return 0; } - + // remove all margins starting from the index. - for (int i = index; i >= 0; i--) { + for (int i = index; i >= 0; i--) + { ToolStripPanelCell cell = (ToolStripPanelCell)Row.Cells[i]; - if (!cell.Visible && !cell.ControlInDesignMode) { + if (!cell.Visible && !cell.ControlInDesignMode) + { continue; } int requiredSpace = spaceToFree - freedSpace; Padding cellMargin = cell.Margin; - - if (cellMargin.Horizontal >= requiredSpace) { + + if (cellMargin.Horizontal >= requiredSpace) + { freedSpace += requiredSpace; - + cellMargin.Left -= requiredSpace; cellMargin.Right = 0; cell.Margin = cellMargin; - + } - else { + else + { freedSpace += cell.Margin.Horizontal; cellMargin.Left = 0; cellMargin.Right = 0; cell.Margin = cellMargin; } - if (freedSpace >= spaceToFree) { + if (freedSpace >= spaceToFree) + { // add the space we freed to the next guy. - if (index +1 < Row.Cells.Count) { - cell = GetNextVisibleCell(index+1, /*forward*/true); - if (cell != null) { + if (index + 1 < Row.Cells.Count) + { + cell = GetNextVisibleCell(index + 1, /*forward*/true); + if (cell != null) + { cellMargin = cell.Margin; cellMargin.Left += spaceToFree; cell.Margin = cellMargin; } } - + Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveLeft Recovered (Margin only): " + spaceToFree.ToString(CultureInfo.InvariantCulture)); return spaceToFree; } } } - finally { + finally + { Row.ResumeLayout(true); } - + Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveLeft Recovered Partial (Shrink): " + freedSpace.ToString(CultureInfo.InvariantCulture)); return freedSpace; } - private int MoveRight(int index, int spaceToFree) { + private int MoveRight(int index, int spaceToFree) + { Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveRight: " + spaceToFree.ToString(CultureInfo.InvariantCulture)); - int freedSpace = 0; + int freedSpace = 0; Row.SuspendLayout(); - try { - - if (spaceToFree == 0 || index < 0 || index >= Row.ControlsInternal.Count) { - Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveRight Early EXIT - 0 "); + try + { + + if (spaceToFree == 0 || index < 0 || index >= Row.ControlsInternal.Count) + { + Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveRight Early EXIT - 0 "); return 0; } - + ToolStripPanelCell cell; Padding cellMargin; // remove all margins after this point in the index. - for (int i = index+1; i < Row.Cells.Count; i++) { + for (int i = index + 1; i < Row.Cells.Count; i++) + { cell = (ToolStripPanelCell)Row.Cells[i]; - if (!cell.Visible && !cell.ControlInDesignMode) { + if (!cell.Visible && !cell.ControlInDesignMode) + { continue; } int requiredSpace = spaceToFree - freedSpace; cellMargin = cell.Margin; - - if (cellMargin.Horizontal >= requiredSpace) { + + if (cellMargin.Horizontal >= requiredSpace) + { freedSpace += requiredSpace; - + cellMargin.Left -= requiredSpace; cellMargin.Right = 0; cell.Margin = cellMargin; - + } - else { + else + { freedSpace += cell.Margin.Horizontal; cellMargin.Left = 0; cellMargin.Right = 0; @@ -1120,28 +1341,34 @@ private int MoveRight(int index, int spaceToFree) { } // add in the space at the end of the row. - if (Row.Cells.Count > 0 && (spaceToFree > freedSpace)) { - ToolStripPanelCell lastCell = GetNextVisibleCell(Row.Cells.Count -1, /*forward*/false); - if (lastCell != null) { + if (Row.Cells.Count > 0 && (spaceToFree > freedSpace)) + { + ToolStripPanelCell lastCell = GetNextVisibleCell(Row.Cells.Count - 1, /*forward*/false); + if (lastCell != null) + { freedSpace += DisplayRectangle.Right - lastCell.Bounds.Right; } - else { + else + { freedSpace += DisplayRectangle.Width; } - + } // set the margin of the control that's moving. - if (spaceToFree <= freedSpace) { + if (spaceToFree <= freedSpace) + { // add the space we freed to the first guy. cell = GetNextVisibleCell(index, /*forward*/true); - if (cell == null) { + if (cell == null) + { cell = Row.Cells[index] as ToolStripPanelCell; } Debug.Assert(cell != null, "Dont expect cell to be null here, what's going on?"); - if (cell != null) { + if (cell != null) + { cellMargin = cell.Margin; cellMargin.Left += spaceToFree; cell.Margin = cellMargin; @@ -1151,25 +1378,30 @@ private int MoveRight(int index, int spaceToFree) { } // Now start shrinking. - for (int i = index+1; i < Row.Cells.Count; i++) { + for (int i = index + 1; i < Row.Cells.Count; i++) + { cell = (ToolStripPanelCell)Row.Cells[i]; - if (!cell.Visible && !cell.ControlInDesignMode) { + if (!cell.Visible && !cell.ControlInDesignMode) + { continue; } int requiredSpace = spaceToFree - freedSpace; freedSpace += cell.Shrink(requiredSpace); - - if (spaceToFree >= freedSpace) { + + if (spaceToFree >= freedSpace) + { Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveRight Recovered (Shrink): " + spaceToFree.ToString(CultureInfo.InvariantCulture)); Row.ResumeLayout(true); return spaceToFree; - } + } } - if (Row.Cells.Count == 1) { + if (Row.Cells.Count == 1) + { cell = GetNextVisibleCell(index,/*forward*/true); - if (cell != null) { + if (cell != null) + { cellMargin = cell.Margin; cellMargin.Left += freedSpace; cell.Margin = cellMargin; @@ -1177,7 +1409,8 @@ private int MoveRight(int index, int spaceToFree) { } } - finally { + finally + { Row.ResumeLayout(true); } @@ -1186,21 +1419,26 @@ private int MoveRight(int index, int spaceToFree) { return freedSpace; } - - public override void LeaveRow(ToolStrip toolStripToDrag) { + + public override void LeaveRow(ToolStrip toolStripToDrag) + { // this code is here to properly add space to the next control when the // toolStripToDrag has been removed from the row. Row.SuspendLayout(); int index = Row.ControlsInternal.IndexOf(toolStripToDrag); - if (index >= 0) { - if (index < Row.ControlsInternal.Count -1 /*not the last one in the row*/) { + if (index >= 0) + { + if (index < Row.ControlsInternal.Count - 1 /*not the last one in the row*/) + { ToolStripPanelCell cell = (ToolStripPanelCell)Row.Cells[index]; - if (cell.Visible) { + if (cell.Visible) + { int spaceOccupiedByCell = cell.Margin.Horizontal + cell.Bounds.Width; // add the space occupied by the cell to the next one. - ToolStripPanelCell nextCell = GetNextVisibleCell(index+1, /*forward*/true); - if (nextCell != null) { + ToolStripPanelCell nextCell = GetNextVisibleCell(index + 1, /*forward*/true); + if (nextCell != null) + { Padding nextCellMargin = nextCell.Margin; nextCellMargin.Left += spaceOccupiedByCell; nextCell.Margin = nextCellMargin; @@ -1212,41 +1450,51 @@ public override void LeaveRow(ToolStrip toolStripToDrag) { } Row.ResumeLayout(true); } - - protected internal override void OnControlAdded(Control control, int index) { + + protected internal override void OnControlAdded(Control control, int index) + { } - protected internal override void OnControlRemoved(Control control, int index) { + protected internal override void OnControlRemoved(Control control, int index) + { } - public override void JoinRow(ToolStrip toolStripToDrag, Point locationToDrag) { + public override void JoinRow(ToolStrip toolStripToDrag, Point locationToDrag) + { - Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "Horizontal JoinRow called " ); + Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "Horizontal JoinRow called "); int index; - - if (!Row.ControlsInternal.Contains(toolStripToDrag)) { + + if (!Row.ControlsInternal.Contains(toolStripToDrag)) + { Row.SuspendLayout(); - - try { - if (Row.ControlsInternal.Count > 0) { - + + try + { + if (Row.ControlsInternal.Count > 0) + { + // walk through the columns and determine which column you want to insert into. - for (index = 0; index < Row.Cells.Count; index++) { + for (index = 0; index < Row.Cells.Count; index++) + { ToolStripPanelCell cell = Row.Cells[index] as ToolStripPanelCell; - if (!cell.Visible && !cell.ControlInDesignMode) { + if (!cell.Visible && !cell.ControlInDesignMode) + { continue; } - + // [: ] [: x ] - if (Row.Cells[index].Bounds.Contains(locationToDrag)) { + if (Row.Cells[index].Bounds.Contains(locationToDrag)) + { break; } // take into account the following scenarios // [: ] x [: ] // x [: ] [: ] - if (Row.Cells[index].Bounds.X >= locationToDrag.X) { + if (Row.Cells[index].Bounds.X >= locationToDrag.X) + { break; } @@ -1254,161 +1502,186 @@ public override void JoinRow(ToolStrip toolStripToDrag, Point locationToDrag) { Control controlToPushAside = Row.ControlsInternal[index]; // Plop the new control in the midst of the row in question. - if (index < Row.ControlsInternal.Count) { + if (index < Row.ControlsInternal.Count) + { Row.ControlsInternal.Insert(index, toolStripToDrag); } - else { + else + { Row.ControlsInternal.Add(toolStripToDrag); } // since layout is suspended the control may not be set to its preferred size yet int controlToDragWidth = (toolStripToDrag.AutoSize) ? toolStripToDrag.PreferredSize.Width : toolStripToDrag.Width; - - + + // // now make it look like it belongs in the row. // // PUSH the controls after it to the right - + int requiredSpace = controlToDragWidth; - if (index == 0) { + if (index == 0) + { // make sure we account for the left side requiredSpace += locationToDrag.X; } int freedSpace = 0; - - if (index < Row.ControlsInternal.Count -1) { - ToolStripPanelCell nextCell = (ToolStripPanelCell)Row.Cells[index+1]; - Padding nextCellMargin = nextCell.Margin; - + + if (index < Row.ControlsInternal.Count - 1) + { + ToolStripPanelCell nextCell = (ToolStripPanelCell)Row.Cells[index + 1]; + Padding nextCellMargin = nextCell.Margin; + // if we've already got the empty space // (available to us via the margin) use that. - if (nextCellMargin.Left > requiredSpace) { + if (nextCellMargin.Left > requiredSpace) + { nextCellMargin.Left -= requiredSpace; nextCell.Margin = nextCellMargin; freedSpace = requiredSpace; } - else { + else + { // otherwise we've got to // push all controls after this point to the right // this dumps the extra stuff into the margin of index+1 - freedSpace = MoveRight(index+1, requiredSpace - freedSpace); - + freedSpace = MoveRight(index + 1, requiredSpace - freedSpace); + // refetch the margin for "index+1" and remove the freed space // from it - we want to actually put this to use on the control // before this one - we're making room for the control at // position "index" - if (freedSpace > 0) { - nextCellMargin = nextCell.Margin; + if (freedSpace > 0) + { + nextCellMargin = nextCell.Margin; nextCellMargin.Left = Math.Max(0, nextCellMargin.Left - freedSpace); - nextCell.Margin = nextCellMargin; + nextCell.Margin = nextCellMargin; } - + } - - + + } - else { + else + { // we're adding to the end. - ToolStripPanelCell nextCell = GetNextVisibleCell(Row.Cells.Count-2, /*forward*/false); - ToolStripPanelCell lastCell = GetNextVisibleCell(Row.Cells.Count-1, /*forward*/false); - + ToolStripPanelCell nextCell = GetNextVisibleCell(Row.Cells.Count - 2, /*forward*/false); + ToolStripPanelCell lastCell = GetNextVisibleCell(Row.Cells.Count - 1, /*forward*/false); + // count the stuff at the end of the row as freed space - if (nextCell != null && lastCell != null) { + if (nextCell != null && lastCell != null) + { Padding lastCellMargin = lastCell.Margin; - lastCellMargin.Left = Math.Max(0,locationToDrag.X - nextCell.Bounds.Right); + lastCellMargin.Left = Math.Max(0, locationToDrag.X - nextCell.Bounds.Right); lastCell.Margin = lastCellMargin; - freedSpace=requiredSpace; - } + freedSpace = requiredSpace; + } } - + // If we still need more space, then... // PUSH the controls before it to the left - if (freedSpace < requiredSpace && index > 0) { + if (freedSpace < requiredSpace && index > 0) + { freedSpace = MoveLeft(index - 1, requiredSpace - freedSpace); } - - if (index == 0) { + + if (index == 0) + { // if the index is zero and there were controls in the row // we need to take care of pushing over the new cell. - if (freedSpace - controlToDragWidth > 0) { + if (freedSpace - controlToDragWidth > 0) + { ToolStripPanelCell newCell = Row.Cells[index] as ToolStripPanelCell; - Padding newCellMargin = newCell.Margin; + Padding newCellMargin = newCell.Margin; newCellMargin.Left = freedSpace - controlToDragWidth; newCell.Margin = newCellMargin; } } - - - - + + + + } - else { - + else + { + // we're adding to the beginning. Row.ControlsInternal.Add(toolStripToDrag); - + #if DEBUG ISupportToolStripPanel ctg = toolStripToDrag as ISupportToolStripPanel; ToolStripPanelRow newPanelRow = ctg.ToolStripPanelRow; Debug.Assert(newPanelRow == Row, "we should now be in the new panel row."); #endif - if (Row.Cells.Count >0 || toolStripToDrag.IsInDesignMode) { + if (Row.Cells.Count > 0 || toolStripToDrag.IsInDesignMode) + { // we're adding to the beginning. - ToolStripPanelCell cell = GetNextVisibleCell(Row.Cells.Count-1, /*forward*/false); - if (cell == null && toolStripToDrag.IsInDesignMode) { - cell = (ToolStripPanelCell)Row.Cells[Row.Cells.Count-1]; + ToolStripPanelCell cell = GetNextVisibleCell(Row.Cells.Count - 1, /*forward*/false); + if (cell == null && toolStripToDrag.IsInDesignMode) + { + cell = (ToolStripPanelCell)Row.Cells[Row.Cells.Count - 1]; } - if (cell != null) { + if (cell != null) + { Padding cellMargin = cell.Margin; - cellMargin.Left = Math.Max(0,locationToDrag.X-Row.Margin.Left); + cellMargin.Left = Math.Max(0, locationToDrag.X - Row.Margin.Left); cell.Margin = cellMargin; } } - - + + } } - finally { + finally + { Row.ResumeLayout(true); } - } + } } - protected internal override void OnBoundsChanged(Rectangle oldBounds, Rectangle newBounds) { - base.OnBoundsChanged(oldBounds, newBounds); + protected internal override void OnBoundsChanged(Rectangle oldBounds, Rectangle newBounds) + { + base.OnBoundsChanged(oldBounds, newBounds); } - - + + } - - private class VerticalRowManager : ToolStripPanelRowManager { - + + private class VerticalRowManager : ToolStripPanelRowManager + { + private const int DRAG_BOUNDS_INFLATE = 4; - - public VerticalRowManager(ToolStripPanelRow owner): base (owner) { + + public VerticalRowManager(ToolStripPanelRow owner) : base(owner) + { owner.SuspendLayout(); FlowLayoutSettings.WrapContents = false; FlowLayoutSettings.FlowDirection = FlowDirection.TopDown; owner.ResumeLayout(false); } - - public override Rectangle DisplayRectangle { - get { + + public override Rectangle DisplayRectangle + { + get + { Rectangle displayRect = ((IArrangedElement)Row).DisplayRectangle; - if (ToolStripPanel != null) { + if (ToolStripPanel != null) + { Rectangle raftingDisplayRectangle = ToolStripPanel.DisplayRectangle; - - if ((!ToolStripPanel.Visible || LayoutUtils.IsZeroWidthOrHeight(raftingDisplayRectangle)) && (ToolStripPanel.ParentInternal != null)){ + + if ((!ToolStripPanel.Visible || LayoutUtils.IsZeroWidthOrHeight(raftingDisplayRectangle)) && (ToolStripPanel.ParentInternal != null)) + { // if were layed out before we're visible we have the wrong display rectangle, so we need to calculate it. displayRect.Height = ToolStripPanel.ParentInternal.DisplayRectangle.Height - (ToolStripPanel.Margin.Vertical + ToolStripPanel.Padding.Vertical) - Row.Margin.Vertical; } - else { + else + { displayRect.Height = raftingDisplayRectangle.Height - Row.Margin.Vertical; } } @@ -1416,13 +1689,16 @@ public override Rectangle DisplayRectangle { return displayRect; } } - public override Rectangle DragBounds { - get { + public override Rectangle DragBounds + { + get + { Rectangle dragBounds = Row.Bounds; int index = ToolStripPanel.RowsInternal.IndexOf(Row); /// - if (index > 0) { + if (index > 0) + { Rectangle previousRowBounds = ToolStripPanel.RowsInternal[index - 1].Bounds; int x = previousRowBounds.X + previousRowBounds.Width - (previousRowBounds.Width >> 2); @@ -1430,14 +1706,15 @@ public override Rectangle DragBounds { dragBounds.X = x; } - if (index < ToolStripPanel.RowsInternal.Count - 1) { + if (index < ToolStripPanel.RowsInternal.Count - 1) + { Rectangle nextRowBounds = ToolStripPanel.RowsInternal[index + 1].Bounds; dragBounds.Width += (nextRowBounds.Width >> 2) + Row.Margin.Right + ToolStripPanel.RowsInternal[index + 1].Margin.Left; } - dragBounds.Height += Row.Margin.Vertical + ToolStripPanel.Padding.Vertical +5; - dragBounds.Y -= Row.Margin.Top+ ToolStripPanel.Padding.Top +4; + dragBounds.Height += Row.Margin.Vertical + ToolStripPanel.Padding.Vertical + 5; + dragBounds.Y -= Row.Margin.Top + ToolStripPanel.Padding.Top + 4; return dragBounds; @@ -1448,184 +1725,217 @@ public override Rectangle DragBounds { /// returns true if there is enough space to "raft" the control /// ow returns false /// - public override bool CanMove(ToolStrip toolStripToDrag) { + public override bool CanMove(ToolStrip toolStripToDrag) + { - if (base.CanMove(toolStripToDrag)) { + if (base.CanMove(toolStripToDrag)) + { Size totalSize = Size.Empty; - for (int i = 0; i < Row.ControlsInternal.Count; i++ ){ - totalSize += Row.GetMinimumSize(Row.ControlsInternal[i] as ToolStrip); + for (int i = 0; i < Row.ControlsInternal.Count; i++) + { + totalSize += Row.GetMinimumSize(Row.ControlsInternal[i] as ToolStrip); } totalSize += Row.GetMinimumSize(toolStripToDrag); return totalSize.Height < DisplayRectangle.Height; } - - Debug.WriteLineIf(ToolStripPanelRow.ToolStripPanelRowCreationDebug.TraceVerbose, "VerticalRM.CanMove returns false - not enough room"); + + Debug.WriteLineIf(ToolStripPanelRow.ToolStripPanelRowCreationDebug.TraceVerbose, "VerticalRM.CanMove returns false - not enough room"); return false; } - protected internal override int FreeSpaceFromRow(int spaceToFree) { - int requiredSpace = spaceToFree; - // take a look at the last guy. if his right edge exceeds - // the new bounds, then we should go ahead and push him into view. - - if (spaceToFree > 0){ - // we should shrink the last guy and then move him. - ToolStripPanelCell lastCellOnRow = GetNextVisibleCell(Row.Cells.Count-1, /*forward*/false); - if (lastCellOnRow == null) { - return 0; - } - Padding cellMargin = lastCellOnRow.Margin; - - // only check margin.left as we are only concerned with getting right edge of - // the toolstrip into view. (space after the fact doesnt count). - if (cellMargin.Top >= spaceToFree) { - cellMargin.Top -= spaceToFree; - cellMargin.Bottom = 0; - spaceToFree = 0; - - } - else { - spaceToFree -= lastCellOnRow.Margin.Top; - cellMargin.Top = 0; - cellMargin.Bottom = 0; - } - lastCellOnRow.Margin = cellMargin; - - // start moving the toolstrips before this guy. - spaceToFree -= MoveUp(Row.Cells.Count -1, spaceToFree); - - if (spaceToFree > 0) { - spaceToFree -= lastCellOnRow.Shrink(spaceToFree); - } - } - return requiredSpace - Math.Max(0,spaceToFree); + protected internal override int FreeSpaceFromRow(int spaceToFree) + { + int requiredSpace = spaceToFree; + // take a look at the last guy. if his right edge exceeds + // the new bounds, then we should go ahead and push him into view. + + if (spaceToFree > 0) + { + // we should shrink the last guy and then move him. + ToolStripPanelCell lastCellOnRow = GetNextVisibleCell(Row.Cells.Count - 1, /*forward*/false); + if (lastCellOnRow == null) + { + return 0; + } + Padding cellMargin = lastCellOnRow.Margin; + + // only check margin.left as we are only concerned with getting right edge of + // the toolstrip into view. (space after the fact doesnt count). + if (cellMargin.Top >= spaceToFree) + { + cellMargin.Top -= spaceToFree; + cellMargin.Bottom = 0; + spaceToFree = 0; + + } + else + { + spaceToFree -= lastCellOnRow.Margin.Top; + cellMargin.Top = 0; + cellMargin.Bottom = 0; + } + lastCellOnRow.Margin = cellMargin; + + // start moving the toolstrips before this guy. + spaceToFree -= MoveUp(Row.Cells.Count - 1, spaceToFree); + + if (spaceToFree > 0) + { + spaceToFree -= lastCellOnRow.Shrink(spaceToFree); + } + } + return requiredSpace - Math.Max(0, spaceToFree); } - - - public override void MoveControl(ToolStrip movingControl, Point clientStartLocation, Point clientEndLocation) { - if (Row.Locked) { + + public override void MoveControl(ToolStrip movingControl, Point clientStartLocation, Point clientEndLocation) + { + + if (Row.Locked) + { return; } - if (DragBounds.Contains(clientEndLocation)) { - int index = Row.ControlsInternal.IndexOf(movingControl); - int deltaY = clientEndLocation.Y - clientStartLocation.Y; - - if (deltaY < 0) { - // moving to the left - MoveUp(index, deltaY * -1); - } - else { - MoveDown(index, deltaY); - } - } - else { + if (DragBounds.Contains(clientEndLocation)) + { + int index = Row.ControlsInternal.IndexOf(movingControl); + int deltaY = clientEndLocation.Y - clientStartLocation.Y; + + if (deltaY < 0) + { + // moving to the left + MoveUp(index, deltaY * -1); + } + else + { + MoveDown(index, deltaY); + } + } + else + { base.MoveControl(movingControl, clientStartLocation, clientEndLocation); - } + } } - private int MoveUp(int index, int spaceToFree) { + private int MoveUp(int index, int spaceToFree) + { Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveUp: " + spaceToFree.ToString(CultureInfo.InvariantCulture)); int freedSpace = 0; - + Row.SuspendLayout(); - try { - if (spaceToFree == 0 || index < 0) { - Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveUp Early EXIT - 0 "); + try + { + if (spaceToFree == 0 || index < 0) + { + Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveUp Early EXIT - 0 "); return 0; } - + // remove all margins starting from the index. - for (int i = index; i >= 0; i--) { + for (int i = index; i >= 0; i--) + { ToolStripPanelCell cell = (ToolStripPanelCell)Row.Cells[i]; - if (!cell.Visible && !cell.ControlInDesignMode) { + if (!cell.Visible && !cell.ControlInDesignMode) + { continue; } int requiredSpace = spaceToFree - freedSpace; Padding cellMargin = cell.Margin; - - if (cellMargin.Vertical >= requiredSpace) { + + if (cellMargin.Vertical >= requiredSpace) + { freedSpace += requiredSpace; - + cellMargin.Top -= requiredSpace; cellMargin.Bottom = 0; cell.Margin = cellMargin; - + } - else { + else + { freedSpace += cell.Margin.Vertical; cellMargin.Top = 0; cellMargin.Bottom = 0; cell.Margin = cellMargin; } - if (freedSpace >= spaceToFree) { + if (freedSpace >= spaceToFree) + { // add the space we freed to the next guy. - if (index +1 < Row.Cells.Count) { - cell = GetNextVisibleCell(index+1, /*forward*/true); - if (cell != null) { + if (index + 1 < Row.Cells.Count) + { + cell = GetNextVisibleCell(index + 1, /*forward*/true); + if (cell != null) + { cellMargin = cell.Margin; cellMargin.Top += spaceToFree; cell.Margin = cellMargin; } } - + Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveUp Recovered (Margin only): " + spaceToFree.ToString(CultureInfo.InvariantCulture)); return spaceToFree; } } } - finally { + finally + { Row.ResumeLayout(true); } - + Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveLeft Recovered Partial (Shrink): " + freedSpace.ToString(CultureInfo.InvariantCulture)); return freedSpace; } - private int MoveDown(int index, int spaceToFree) { - + private int MoveDown(int index, int spaceToFree) + { + Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveDown: " + spaceToFree.ToString(CultureInfo.InvariantCulture)); - int freedSpace = 0; + int freedSpace = 0; Row.SuspendLayout(); - try { - - if (spaceToFree == 0 || index < 0 || index >= Row.ControlsInternal.Count) { - Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveDown Early EXIT - 0 "); + try + { + + if (spaceToFree == 0 || index < 0 || index >= Row.ControlsInternal.Count) + { + Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveDown Early EXIT - 0 "); return 0; } - + ToolStripPanelCell cell; Padding cellMargin; // remove all margins after this point in the index. - for (int i = index+1; i < Row.Cells.Count; i++) { + for (int i = index + 1; i < Row.Cells.Count; i++) + { cell = (ToolStripPanelCell)Row.Cells[i]; - if (!cell.Visible && !cell.ControlInDesignMode) { + if (!cell.Visible && !cell.ControlInDesignMode) + { continue; } int requiredSpace = spaceToFree - freedSpace; cellMargin = cell.Margin; - - if (cellMargin.Vertical >= requiredSpace) { + + if (cellMargin.Vertical >= requiredSpace) + { freedSpace += requiredSpace; - + cellMargin.Top -= requiredSpace; cellMargin.Bottom = 0; cell.Margin = cellMargin; - + } - else { + else + { freedSpace += cell.Margin.Vertical; cellMargin.Top = 0; cellMargin.Bottom = 0; @@ -1636,48 +1946,57 @@ private int MoveDown(int index, int spaceToFree) { } // add in the space at the end of the row. - if (Row.Cells.Count > 0 && (spaceToFree > freedSpace)) { - ToolStripPanelCell lastCell = GetNextVisibleCell(Row.Cells.Count -1, /*forward*/false); - if (lastCell != null) { + if (Row.Cells.Count > 0 && (spaceToFree > freedSpace)) + { + ToolStripPanelCell lastCell = GetNextVisibleCell(Row.Cells.Count - 1, /*forward*/false); + if (lastCell != null) + { freedSpace += DisplayRectangle.Bottom - lastCell.Bounds.Bottom; } - else { + else + { freedSpace += DisplayRectangle.Height; } } // set the margin of the control that's moving. - if (spaceToFree <= freedSpace) { + if (spaceToFree <= freedSpace) + { // add the space we freed to the first guy. cell = (ToolStripPanelCell)Row.Cells[index]; cellMargin = cell.Margin; cellMargin.Top += spaceToFree; cell.Margin = cellMargin; - + Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveDown Recovered (Margin only): " + spaceToFree.ToString(CultureInfo.InvariantCulture)); return spaceToFree; } // Now start shrinking. - for (int i = index+1; i < Row.Cells.Count; i++) { + for (int i = index + 1; i < Row.Cells.Count; i++) + { cell = (ToolStripPanelCell)Row.Cells[i]; - if (!cell.Visible && !cell.ControlInDesignMode) { + if (!cell.Visible && !cell.ControlInDesignMode) + { continue; - } + } int requiredSpace = spaceToFree - freedSpace; freedSpace += cell.Shrink(requiredSpace); - - if (spaceToFree >= freedSpace) { + + if (spaceToFree >= freedSpace) + { Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveDown Recovered (Shrink): " + spaceToFree.ToString(CultureInfo.InvariantCulture)); Row.ResumeLayout(true); return spaceToFree; - } + } } - if (Row.Cells.Count == 1) { + if (Row.Cells.Count == 1) + { cell = GetNextVisibleCell(index,/*forward*/true); - if (cell != null) { + if (cell != null) + { cellMargin = cell.Margin; cellMargin.Top += freedSpace; cell.Margin = cellMargin; @@ -1685,197 +2004,227 @@ private int MoveDown(int index, int spaceToFree) { } } - finally { + finally + { Row.ResumeLayout(true); } int recoveredSpace = spaceToFree - freedSpace; Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveDown Recovered Partial (Shrink): " + recoveredSpace.ToString(CultureInfo.InvariantCulture)); - + return recoveredSpace; } - protected internal override void OnBoundsChanged(Rectangle oldBounds, Rectangle newBounds) { - + protected internal override void OnBoundsChanged(Rectangle oldBounds, Rectangle newBounds) + { + base.OnBoundsChanged(oldBounds, newBounds); - + // if our bounds have changed - we should shove the toolbars up so they're in view. - if (Row.Cells.Count > 0) { - + if (Row.Cells.Count > 0) + { + // take a look at the last guy. if his right edge exceeds // the new bounds, then we should go ahead and push him into view. - ToolStripPanelCell lastCell = GetNextVisibleCell(Row.Cells.Count -1, /*forward=*/false); - int spaceToFree = (lastCell != null)? lastCell.Bounds.Bottom - newBounds.Height : 0; - - if (spaceToFree > 0){ + ToolStripPanelCell lastCell = GetNextVisibleCell(Row.Cells.Count - 1, /*forward=*/false); + int spaceToFree = (lastCell != null) ? lastCell.Bounds.Bottom - newBounds.Height : 0; + + if (spaceToFree > 0) + { // we should shrink the last guy and then move him. - ToolStripPanelCell lastCellOnRow = GetNextVisibleCell(Row.Cells.Count-1, /*forward*/false); - + ToolStripPanelCell lastCellOnRow = GetNextVisibleCell(Row.Cells.Count - 1, /*forward*/false); + Padding cellMargin = lastCellOnRow.Margin; - + // only check margin.left as we are only concerned with getting bottom edge of // the toolstrip into view. (space after the fact doesnt count). - if (cellMargin.Top >= spaceToFree) { - + if (cellMargin.Top >= spaceToFree) + { + cellMargin.Top -= spaceToFree; cellMargin.Bottom = 0; lastCellOnRow.Margin = cellMargin; spaceToFree = 0; - + } - else { - spaceToFree -= lastCellOnRow.Margin.Top; + else + { + spaceToFree -= lastCellOnRow.Margin.Top; cellMargin.Top = 0; cellMargin.Bottom = 0; lastCellOnRow.Margin = cellMargin; } spaceToFree -= lastCellOnRow.Shrink(spaceToFree); // start moving the toolstrips before this guy. - MoveUp(Row.Cells.Count -1, spaceToFree); - } - + MoveUp(Row.Cells.Count - 1, spaceToFree); + } + } - + } - - - - protected internal override void OnControlRemoved(Control c, int index) { - + + + + protected internal override void OnControlRemoved(Control c, int index) + { + } - protected internal override void OnControlAdded(Control control, int index) { - + protected internal override void OnControlAdded(Control control, int index) + { + } - - public override void JoinRow(ToolStrip toolStripToDrag, Point locationToDrag) { - - Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "Vertical JoinRow called " ); + + public override void JoinRow(ToolStrip toolStripToDrag, Point locationToDrag) + { + + Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "Vertical JoinRow called "); int index; - - if (!Row.ControlsInternal.Contains(toolStripToDrag)) { + + if (!Row.ControlsInternal.Contains(toolStripToDrag)) + { Row.SuspendLayout(); - try { - if (Row.ControlsInternal.Count > 0) { - - + try + { + if (Row.ControlsInternal.Count > 0) + { + + // walk through the columns and determine which column you want to insert into. - for (index = 0; index < Row.Cells.Count; index++) { + for (index = 0; index < Row.Cells.Count; index++) + { ToolStripPanelCell cell = Row.Cells[index] as ToolStripPanelCell; - if (!cell.Visible && !cell.ControlInDesignMode) { + if (!cell.Visible && !cell.ControlInDesignMode) + { continue; } // [: ] [: x ] - if (cell.Bounds.Contains(locationToDrag)) { + if (cell.Bounds.Contains(locationToDrag)) + { break; } - + // take into account the following scenarios // [: ] x [: ] // x [: ] [: ] - if (cell.Bounds.Y >= locationToDrag.Y) { + if (cell.Bounds.Y >= locationToDrag.Y) + { break; } - + } - + Control controlToPushAside = Row.ControlsInternal[index]; // Plop the new control in the midst of the row in question. - if (index < Row.ControlsInternal.Count) { + if (index < Row.ControlsInternal.Count) + { Row.ControlsInternal.Insert(index, toolStripToDrag); } - else { + else + { Row.ControlsInternal.Add(toolStripToDrag); } - + // since layout is suspended the control may not be set to its preferred size yet int controlToDragWidth = (toolStripToDrag.AutoSize) ? toolStripToDrag.PreferredSize.Height : toolStripToDrag.Height; - + // // now make it look like it belongs in the row. // // PUSH the controls after it to the right - + int requiredSpace = controlToDragWidth; - - if (index == 0) { + + if (index == 0) + { // make sure we account for the left side requiredSpace += locationToDrag.Y; } int freedSpace = 0; - - if (index < Row.ControlsInternal.Count -1) { - - ToolStripPanelCell nextCell = GetNextVisibleCell(index+1, /*forward*/true); - if (nextCell != null) { - Padding nextCellMargin = nextCell.Margin; - + + if (index < Row.ControlsInternal.Count - 1) + { + + ToolStripPanelCell nextCell = GetNextVisibleCell(index + 1, /*forward*/true); + if (nextCell != null) + { + Padding nextCellMargin = nextCell.Margin; + // if we've already got the empty space // (available to us via the margin) use that. - if (nextCellMargin.Top > requiredSpace) { + if (nextCellMargin.Top > requiredSpace) + { nextCellMargin.Top -= requiredSpace; - nextCell.Margin = nextCellMargin; + nextCell.Margin = nextCellMargin; freedSpace = requiredSpace; } - else { + else + { // otherwise we've got to // push all controls after this point to the right // this dumps the extra stuff into the margin of index+1 - freedSpace = MoveDown(index+1, requiredSpace - freedSpace); - + freedSpace = MoveDown(index + 1, requiredSpace - freedSpace); + // refetch the margin for "index+1" and remove the freed space // from it - we want to actually put this to use on the control // before this one - we're making room for the control at // position "index" - if (freedSpace > 0) { - nextCellMargin = nextCell.Margin; + if (freedSpace > 0) + { + nextCellMargin = nextCell.Margin; nextCellMargin.Top -= freedSpace; - nextCell.Margin = nextCellMargin; + nextCell.Margin = nextCellMargin; } - + } } - - + + } - else { - // we're adding to the end. - ToolStripPanelCell nextCell = GetNextVisibleCell(Row.Cells.Count-2, /*forward*/false); - ToolStripPanelCell lastCell = GetNextVisibleCell(Row.Cells.Count-1, /*forward*/false); - + else + { + // we're adding to the end. + ToolStripPanelCell nextCell = GetNextVisibleCell(Row.Cells.Count - 2, /*forward*/false); + ToolStripPanelCell lastCell = GetNextVisibleCell(Row.Cells.Count - 1, /*forward*/false); + // count the stuff at the end of the row as freed space - if (nextCell != null && lastCell != null) { - Padding lastCellMargin = lastCell.Margin; - lastCellMargin.Top = Math.Max(0,locationToDrag.Y - nextCell.Bounds.Bottom); + if (nextCell != null && lastCell != null) + { + Padding lastCellMargin = lastCell.Margin; + lastCellMargin.Top = Math.Max(0, locationToDrag.Y - nextCell.Bounds.Bottom); lastCell.Margin = lastCellMargin; - freedSpace=requiredSpace; - } - + freedSpace = requiredSpace; + } + } - + // If we still need more space, then... // PUSH the controls before it to the left - if (freedSpace < requiredSpace && index > 0) { + if (freedSpace < requiredSpace && index > 0) + { freedSpace = MoveUp(index - 1, requiredSpace - freedSpace); } - - if (index == 0) { + + if (index == 0) + { // if the index is zero and there were controls in the row // we need to take care of pushing over the new cell. - if (freedSpace - controlToDragWidth > 0) { + if (freedSpace - controlToDragWidth > 0) + { ToolStripPanelCell newCell = Row.Cells[index] as ToolStripPanelCell; - Padding newCellMargin = newCell.Margin; + Padding newCellMargin = newCell.Margin; newCellMargin.Top = freedSpace - controlToDragWidth; newCell.Margin = newCellMargin; } } - + } - else { - + else + { + // we're adding to the beginning. Row.ControlsInternal.Add(toolStripToDrag); @@ -1884,37 +2233,45 @@ public override void JoinRow(ToolStrip toolStripToDrag, Point locationToDrag) { ToolStripPanelRow newPanelRow = ctg.ToolStripPanelRow; Debug.Assert(newPanelRow == Row, "we should now be in the new panel row."); #endif - if (Row.Cells.Count >0) { - ToolStripPanelCell cell = GetNextVisibleCell(Row.Cells.Count-1, /*forward*/false); - if (cell != null) { + if (Row.Cells.Count > 0) + { + ToolStripPanelCell cell = GetNextVisibleCell(Row.Cells.Count - 1, /*forward*/false); + if (cell != null) + { Padding cellMargin = cell.Margin; - cellMargin.Top = Math.Max(0,locationToDrag.Y-Row.Margin.Top); + cellMargin.Top = Math.Max(0, locationToDrag.Y - Row.Margin.Top); cell.Margin = cellMargin; } } } } - finally { + finally + { Row.ResumeLayout(true); } } } - - public override void LeaveRow(ToolStrip toolStripToDrag) { + + public override void LeaveRow(ToolStrip toolStripToDrag) + { // this code is here to properly add space to the next control when the // toolStripToDrag has been removed from the row. Row.SuspendLayout(); int index = Row.ControlsInternal.IndexOf(toolStripToDrag); - if (index >= 0) { - if (index < Row.ControlsInternal.Count -1 /*not the last one in the row*/) { - + if (index >= 0) + { + if (index < Row.ControlsInternal.Count - 1 /*not the last one in the row*/) + { + ToolStripPanelCell cell = (ToolStripPanelCell)Row.Cells[index]; - if (cell.Visible) { + if (cell.Visible) + { int spaceOccupiedByCell = cell.Margin.Vertical + cell.Bounds.Height; - + // add the space occupied by the cell to the next one. - ToolStripPanelCell nextCell = GetNextVisibleCell(index+1, /*forward*/true); - if (nextCell != null) { + ToolStripPanelCell nextCell = GetNextVisibleCell(index + 1, /*forward*/true); + if (nextCell != null) + { Padding nextCellMargin = nextCell.Margin; nextCellMargin.Top += spaceOccupiedByCell; nextCell.Margin = nextCellMargin; @@ -1927,8 +2284,8 @@ public override void LeaveRow(ToolStrip toolStripToDrag) { Row.ResumeLayout(true); } } - - + + /// /// ToolStripPanelRowControlCollection @@ -1947,51 +2304,64 @@ public override void LeaveRow(ToolStrip toolStripToDrag) { /// is responsible for parenting and unparenting the controls (ToolStripPanelRows do NOT derive from /// Control and thus are NOT hwnd backed). /// - internal class ToolStripPanelRowControlCollection : ArrangedElementCollection, IList, IEnumerable { + internal class ToolStripPanelRowControlCollection : ArrangedElementCollection, IList, IEnumerable + { private ToolStripPanelRow owner; private ArrangedElementCollection cellCollection; - - public ToolStripPanelRowControlCollection(ToolStripPanelRow owner) { + + public ToolStripPanelRowControlCollection(ToolStripPanelRow owner) + { this.owner = owner; } - public ToolStripPanelRowControlCollection(ToolStripPanelRow owner, Control[] value) { + public ToolStripPanelRowControlCollection(ToolStripPanelRow owner, Control[] value) + { this.owner = owner; AddRange(value); } - public new virtual Control this[int index] { - get { + public new virtual Control this[int index] + { + get + { return GetControl(index); } } - public ArrangedElementCollection Cells { - get { - if (cellCollection == null) { + public ArrangedElementCollection Cells + { + get + { + if (cellCollection == null) + { cellCollection = new ArrangedElementCollection(InnerList); } return cellCollection; } } - - public ToolStripPanel ToolStripPanel { - get { + + public ToolStripPanel ToolStripPanel + { + get + { return owner.ToolStripPanel; } } [EditorBrowsable(EditorBrowsableState.Never)] - public int Add(Control value) { + public int Add(Control value) + { ISupportToolStripPanel control = value as ISupportToolStripPanel; - - if (value == null) { + + if (value == null) + { throw new ArgumentNullException(nameof(value)); } - if (control == null) { - throw new NotSupportedException(string.Format(SR.TypedControlCollectionShouldBeOfType, typeof(ToolStrip).Name)); + if (control == null) + { + throw new NotSupportedException(string.Format(SR.TypedControlCollectionShouldBeOfType, typeof(ToolStrip).Name)); } int index = InnerList.Add(control.ToolStripPanelCell); @@ -2002,50 +2372,66 @@ public int Add(Control value) { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [EditorBrowsable(EditorBrowsableState.Never)] - public void AddRange(Control[] value) { - if (value == null) { + public void AddRange(Control[] value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } ToolStripPanel currentOwner = ToolStripPanel; - if (currentOwner != null) { + if (currentOwner != null) + { currentOwner.SuspendLayout(); } - try { - for (int i = 0; i < value.Length; i++) { + try + { + for (int i = 0; i < value.Length; i++) + { this.Add(value[i]); } } - finally { - if (currentOwner != null) { + finally + { + if (currentOwner != null) + { currentOwner.ResumeLayout(); } } } - public bool Contains(Control value) { - for (int i = 0; i < Count; i++) { - if (GetControl(i) == value) { + public bool Contains(Control value) + { + for (int i = 0; i < Count; i++) + { + if (GetControl(i) == value) + { return true; } } return false; } - public virtual void Clear() { - if (owner != null) { + public virtual void Clear() + { + if (owner != null) + { ToolStripPanel.SuspendLayout(); } - try { - while (Count != 0) { + try + { + while (Count != 0) + { RemoveAt(Count - 1); } } - finally { - if (owner != null) { + finally + { + if (owner != null) + { ToolStripPanel.ResumeLayout(); } } @@ -2053,30 +2439,35 @@ public virtual void Clear() { public override IEnumerator GetEnumerator() { return new ToolStripPanelCellToControlEnumerator(InnerList); } - private Control GetControl(int index) { + private Control GetControl(int index) + { Control control = null; ToolStripPanelCell cell = null; - if (index < Count && index >= 0) { - cell = (ToolStripPanelCell)(InnerList[index]); + if (index < Count && index >= 0) + { + cell = (ToolStripPanelCell)(InnerList[index]); control = (cell != null) ? cell.Control : null; } return control; } - private int IndexOfControl(Control c) { - for (int i = 0; i < Count; i++) { - ToolStripPanelCell cell = (ToolStripPanelCell)(InnerList[i]); - if (cell.Control == c) { + private int IndexOfControl(Control c) + { + for (int i = 0; i < Count; i++) + { + ToolStripPanelCell cell = (ToolStripPanelCell)(InnerList[i]); + if (cell.Control == c) + { return i; } } return -1; - + } - - - + + + void IList.Clear() { Clear(); } @@ -2096,9 +2487,12 @@ private int IndexOfControl(Control c) { void IList.Insert(int index, object value) { Insert(index, value as Control); } - public int IndexOf(Control value) { - for (int i = 0; i < Count; i++) { - if (GetControl(i) == value) { + public int IndexOf(Control value) + { + for (int i = 0; i < Count; i++) + { + if (GetControl(i) == value) + { return i; } } @@ -2106,12 +2500,15 @@ public int IndexOf(Control value) { } [EditorBrowsable(EditorBrowsableState.Never)] - public void Insert(int index, Control value) { - if (value == null) { + public void Insert(int index, Control value) + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } ISupportToolStripPanel control = value as ISupportToolStripPanel; - if (control == null) { + if (control == null) + { throw new NotSupportedException(string.Format(SR.TypedControlCollectionShouldBeOfType, typeof(ToolStrip).Name)); } @@ -2122,42 +2519,53 @@ public void Insert(int index, Control value) { /// /// Do proper cleanup of ownership, etc. /// - private void OnAfterRemove(Control control, int index) { - if (owner != null) { + private void OnAfterRemove(Control control, int index) + { + if (owner != null) + { // unfortunately we dont know the index of the control in the ToolStripPanel's // control collection, as all rows share this collection. // To unparent this control we need to use Remove instead of RemoveAt. - using (LayoutTransaction t = new LayoutTransaction(ToolStripPanel, control, PropertyNames.Parent)) { + using (LayoutTransaction t = new LayoutTransaction(ToolStripPanel, control, PropertyNames.Parent)) + { owner.ToolStripPanel.Controls.Remove(control); owner.OnControlRemoved(control, index); } } } - private void OnAdd(ISupportToolStripPanel controlToBeDragged, int index) { - if (owner != null) { + private void OnAdd(ISupportToolStripPanel controlToBeDragged, int index) + { + if (owner != null) + { LayoutTransaction layoutTransaction = null; - if (ToolStripPanel != null && ToolStripPanel.ParentInternal != null) { + if (ToolStripPanel != null && ToolStripPanel.ParentInternal != null) + { layoutTransaction = new LayoutTransaction(ToolStripPanel, ToolStripPanel.ParentInternal, PropertyNames.Parent); } - try { + try + { + + if (controlToBeDragged != null) + { - if (controlToBeDragged != null) { - controlToBeDragged.ToolStripPanelRow = owner; Control control = controlToBeDragged as Control; - if (control != null) { + if (control != null) + { control.ParentInternal = owner.ToolStripPanel; owner.OnControlAdded(control, index); } - } - - } - finally { - if (layoutTransaction != null) { + } + + } + finally + { + if (layoutTransaction != null) + { layoutTransaction.Dispose(); } } @@ -2165,16 +2573,19 @@ private void OnAdd(ISupportToolStripPanel controlToBeDragged, int index) { } } - + [EditorBrowsable(EditorBrowsableState.Never)] - public void Remove(Control value) { + public void Remove(Control value) + { int index = IndexOfControl(value); RemoveAt(index); } [EditorBrowsable(EditorBrowsableState.Never)] - public void RemoveAt(int index) { - if (index >= 0 && index < Count) { + public void RemoveAt(int index) + { + if (index >= 0 && index < Count) + { Control control = GetControl(index); ToolStripPanelCell cell = InnerList[index] as ToolStripPanelCell; InnerList.RemoveAt(index); @@ -2183,52 +2594,64 @@ public void RemoveAt(int index) { } [EditorBrowsable(EditorBrowsableState.Never)] - public void CopyTo(Control[] array, int index) { - if (array == null) { + public void CopyTo(Control[] array, int index) + { + if (array == null) + { throw new ArgumentNullException(nameof(array)); } - if (index < 0) { + if (index < 0) + { throw new ArgumentOutOfRangeException(nameof(index)); } - if (index >= array.Length || InnerList.Count > array.Length - index) { + if (index >= array.Length || InnerList.Count > array.Length - index) + { throw new ArgumentException(SR.ToolStripPanelRowControlCollectionIncorrectIndexLength); } - for (int i = 0; i < InnerList.Count; i++) { - array[index++] = GetControl(i); - } + for (int i = 0; i < InnerList.Count; i++) + { + array[index++] = GetControl(i); + } } - + /// We want to pretend like we're only holding controls... so everywhere we've returned controls. /// but the problem is if you do a foreach, you'll get the cells not the controls. So we've got /// to sort of write a wrapper class around the ArrayList enumerator. - private class ToolStripPanelCellToControlEnumerator : IEnumerator, ICloneable { - private IEnumerator arrayListEnumerator; + private class ToolStripPanelCellToControlEnumerator : IEnumerator, ICloneable + { + private IEnumerator arrayListEnumerator; - internal ToolStripPanelCellToControlEnumerator(ArrayList list) { + internal ToolStripPanelCellToControlEnumerator(ArrayList list) + { arrayListEnumerator = ((IEnumerable)list).GetEnumerator(); } - - public virtual object Current { - get { + + public virtual object Current + { + get + { ToolStripPanelCell cell = arrayListEnumerator.Current as ToolStripPanelCell; Debug.Assert(cell != null, "Expected ToolStripPanel cells only!!!" + arrayListEnumerator.Current.GetType().ToString()); return (cell == null) ? null : cell.Control; } } - - - public object Clone() { + + + public object Clone() + { return MemberwiseClone(); } - - public virtual bool MoveNext() { + + public virtual bool MoveNext() + { return arrayListEnumerator.MoveNext(); } - - public virtual void Reset() { + + public virtual void Reset() + { arrayListEnumerator.Reset(); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProfessionalLowResolutionRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProfessionalLowResolutionRenderer.cs index 06ed0e002ed..392e99e08b3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProfessionalLowResolutionRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProfessionalLowResolutionRenderer.cs @@ -2,50 +2,64 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Drawing; - internal class ToolStripProfessionalLowResolutionRenderer : ToolStripProfessionalRenderer { + internal class ToolStripProfessionalLowResolutionRenderer : ToolStripProfessionalRenderer + { - public ToolStripProfessionalLowResolutionRenderer() { + public ToolStripProfessionalLowResolutionRenderer() + { } - internal override ToolStripRenderer RendererOverride { - get { + internal override ToolStripRenderer RendererOverride + { + get + { return null; } } - protected override void OnRenderToolStripBackground(ToolStripRenderEventArgs e) { - if( e.ToolStrip is ToolStripDropDown ) { - base.OnRenderToolStripBackground(e); - } + protected override void OnRenderToolStripBackground(ToolStripRenderEventArgs e) + { + if (e.ToolStrip is ToolStripDropDown) + { + base.OnRenderToolStripBackground(e); + } } - protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) { - - if(e.ToolStrip is MenuStrip) { - return; - } - else if (e.ToolStrip is StatusStrip ) { - return; - } - else if (e.ToolStrip is ToolStripDropDown) { - base.OnRenderToolStripBorder(e); - } - else { - RenderToolStripBorderInternal(e); + protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) + { + + if (e.ToolStrip is MenuStrip) + { + return; + } + else if (e.ToolStrip is StatusStrip) + { + return; + } + else if (e.ToolStrip is ToolStripDropDown) + { + base.OnRenderToolStripBorder(e); + } + else + { + RenderToolStripBorderInternal(e); } } - private void RenderToolStripBorderInternal(ToolStripRenderEventArgs e) { + private void RenderToolStripBorderInternal(ToolStripRenderEventArgs e) + { Rectangle bounds = new Rectangle(Point.Empty, e.ToolStrip.Size); Graphics g = e.Graphics; // have to create a pen here because we're not allowed to modify the SystemPens. - using( Pen p = new Pen(SystemColors.ButtonShadow) ) { + using (Pen p = new Pen(SystemColors.ButtonShadow)) + { p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot; bool oddWidth = ((bounds.Width & 0x1) == 0x1); @@ -67,21 +81,24 @@ private void RenderToolStripBorderInternal(ToolStripRenderEventArgs e) { // top left conntecting pixel - always drawn g.FillRectangle(SystemBrushes.ButtonShadow, new Rectangle(1, 1, 1, 1)); - if (oddWidth) { - // top right pixel - g.FillRectangle(SystemBrushes.ButtonShadow, new Rectangle(bounds.Width - 2, 1, 1, 1)); + if (oddWidth) + { + // top right pixel + g.FillRectangle(SystemBrushes.ButtonShadow, new Rectangle(bounds.Width - 2, 1, 1, 1)); } // bottom conntecting pixels - drawn only if height is odd - if(oddHeight) { - // bottom left - g.FillRectangle(SystemBrushes.ButtonShadow, new Rectangle(1, bounds.Height - 2, 1, 1)); + if (oddHeight) + { + // bottom left + g.FillRectangle(SystemBrushes.ButtonShadow, new Rectangle(1, bounds.Height - 2, 1, 1)); } // top and bottom right conntecting pixel - drawn only if height and width are odd - if( oddHeight && oddWidth ) { - // bottom right - g.FillRectangle(SystemBrushes.ButtonShadow, new Rectangle(bounds.Width - 2, bounds.Height - 2, 1, 1)); + if (oddHeight && oddWidth) + { + // bottom right + g.FillRectangle(SystemBrushes.ButtonShadow, new Rectangle(bounds.Width - 2, bounds.Height - 2, 1, 1)); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProgressBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProgressBar.cs index c162e57611a..0eb0d5d2ea2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProgressBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProgressBar.cs @@ -19,19 +19,23 @@ public class ToolStripProgressBar : ToolStripControlHost public ToolStripProgressBar() - : base(CreateControlInstance()) { + : base(CreateControlInstance()) + { ToolStripProgressBarControl toolStripProgressBarControl = Control as ToolStripProgressBarControl; - if (toolStripProgressBarControl != null) { + if (toolStripProgressBarControl != null) + { toolStripProgressBarControl.Owner = this; } - if (DpiHelper.IsScalingRequirementMet) { + if (DpiHelper.IsScalingRequirementMet) + { scaledDefaultMargin = DpiHelper.LogicalToDeviceUnits(defaultMargin); scaledDefaultStatusStripMargin = DpiHelper.LogicalToDeviceUnits(defaultStatusStripMargin); } } - public ToolStripProgressBar(string name) : this() { + public ToolStripProgressBar(string name) : this() + { this.Name = name; } @@ -40,8 +44,10 @@ public ToolStripProgressBar(string name) : this() { /// /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ProgressBar ProgressBar { - get { + public ProgressBar ProgressBar + { + get + { return this.Control as ProgressBar; } } @@ -51,11 +57,14 @@ public ProgressBar ProgressBar { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } @@ -65,11 +74,14 @@ public override Image BackgroundImage { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } @@ -78,9 +90,11 @@ public override ImageLayout BackgroundImageLayout { /// Specify what size you want the item to start out at /// /// - protected override System.Drawing.Size DefaultSize { - get { - return new Size(100,15); + protected override System.Drawing.Size DefaultSize + { + get + { + return new Size(100, 15); } } @@ -88,12 +102,16 @@ protected override System.Drawing.Size DefaultSize { /// Specify how far from the edges you want to be /// /// - protected internal override Padding DefaultMargin { - get { - if (this.Owner != null && this.Owner is StatusStrip) { + protected internal override Padding DefaultMargin + { + get + { + if (this.Owner != null && this.Owner is StatusStrip) + { return scaledDefaultStatusStripMargin; } - else { + else + { return scaledDefaultMargin; } } @@ -104,7 +122,8 @@ protected internal override Padding DefaultMargin { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ProgressBarMarqueeAnimationSpeed)) ] - public int MarqueeAnimationSpeed { + public int MarqueeAnimationSpeed + { get { return ProgressBar.MarqueeAnimationSpeed; } set { ProgressBar.MarqueeAnimationSpeed = value; } } @@ -116,11 +135,14 @@ public int MarqueeAnimationSpeed { RefreshProperties(RefreshProperties.Repaint), SRDescription(nameof(SR.ProgressBarMaximumDescr)) ] - public int Maximum { - get { + public int Maximum + { + get + { return ProgressBar.Maximum; } - set { + set + { ProgressBar.Maximum = value; } } @@ -130,11 +152,14 @@ public int Maximum { RefreshProperties(RefreshProperties.Repaint), SRDescription(nameof(SR.ProgressBarMinimumDescr)) ] - public int Minimum { - get { + public int Minimum + { + get + { return ProgressBar.Minimum; } - set { + set + { ProgressBar.Minimum = value; } } @@ -151,13 +176,16 @@ public int Minimum { DefaultValue(false), SRDescription(nameof(SR.ControlRightToLeftLayoutDescr)) ] - public virtual bool RightToLeftLayout { - get { + public virtual bool RightToLeftLayout + { + get + { return ProgressBar.RightToLeftLayout; } - set { + set + { ProgressBar.RightToLeftLayout = value; } } @@ -171,11 +199,14 @@ public virtual bool RightToLeftLayout { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ProgressBarStepDescr)) ] - public int Step { - get { + public int Step + { + get + { return ProgressBar.Step; } - set { + set + { ProgressBar.Step = value; } } @@ -189,11 +220,14 @@ public int Step { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ProgressBarStyleDescr)) ] - public ProgressBarStyle Style { - get { + public ProgressBarStyle Style + { + get + { return ProgressBar.Style; } - set { + set + { ProgressBar.Style = value; } } @@ -202,8 +236,8 @@ public ProgressBarStyle Style { /// Hide the property. /// [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public override string Text @@ -229,11 +263,14 @@ public override string Text Bindable(true), SRDescription(nameof(SR.ProgressBarValueDescr)) ] - public int Value { - get { + public int Value + { + get + { return ProgressBar.Value; } - set { + set + { ProgressBar.Value = value; } } @@ -245,27 +282,33 @@ public int Value { /// The new instance of the accessibility object for this ToolStripProgressBar ToolStrip item /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new ToolStripProgressBarAccessibleObject(this); } - private static Control CreateControlInstance() { + private static Control CreateControlInstance() + { ProgressBar progressBar = new ToolStripProgressBarControl(); - progressBar.Size = new Size(100,15); + progressBar.Size = new Size(100, 15); return progressBar; } - private void HandleRightToLeftLayoutChanged(object sender, EventArgs e) { + private void HandleRightToLeftLayoutChanged(object sender, EventArgs e) + { OnRightToLeftLayoutChanged(e); } - protected virtual void OnRightToLeftLayoutChanged(EventArgs e) { + protected virtual void OnRightToLeftLayoutChanged(EventArgs e) + { RaiseEvent(EventRightToLeftLayoutChanged, e); } - protected override void OnSubscribeControlEvents(Control control) { + protected override void OnSubscribeControlEvents(Control control) + { ProgressBar bar = control as ProgressBar; - if (bar != null) { + if (bar != null) + { // Please keep this alphabetized and in sync with Unsubscribe // bar.RightToLeftLayoutChanged += new EventHandler(HandleRightToLeftLayoutChanged); @@ -274,10 +317,12 @@ protected override void OnSubscribeControlEvents(Control control) { base.OnSubscribeControlEvents(control); } - protected override void OnUnsubscribeControlEvents(Control control) { + protected override void OnUnsubscribeControlEvents(Control control) + { ProgressBar bar = control as ProgressBar; - if (bar != null) { + if (bar != null) + { // Please keep this alphabetized and in sync with Subscribe // bar.RightToLeftLayoutChanged -= new EventHandler(HandleRightToLeftLayoutChanged); @@ -351,7 +396,8 @@ protected override void OnUnsubscribeControlEvents(Control control) { } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnRightToLeftLayoutChangedDescr))] - public event EventHandler RightToLeftLayoutChanged { + public event EventHandler RightToLeftLayoutChanged + { add => Events.AddHandler(EventRightToLeftLayoutChanged, value); remove => Events.RemoveHandler(EventRightToLeftLayoutChanged, value); } @@ -395,36 +441,45 @@ public event EventHandler RightToLeftLayoutChanged { add => base.Validating += value; remove => base.Validating -= value; } - public void Increment(int value) { + public void Increment(int value) + { ProgressBar.Increment(value); } - public void PerformStep() { + public void PerformStep() + { ProgressBar.PerformStep(); } [System.Runtime.InteropServices.ComVisible(true)] - internal class ToolStripProgressBarAccessibleObject : ToolStripItemAccessibleObject { + internal class ToolStripProgressBarAccessibleObject : ToolStripItemAccessibleObject + { private ToolStripProgressBar ownerItem = null; - public ToolStripProgressBarAccessibleObject(ToolStripProgressBar ownerItem) : base(ownerItem) { - this.ownerItem = ownerItem; + public ToolStripProgressBarAccessibleObject(ToolStripProgressBar ownerItem) : base(ownerItem) + { + this.ownerItem = ownerItem; } - - public override AccessibleRole Role { - get { - AccessibleRole role = Owner.AccessibleRole; - if (role != AccessibleRole.Default) { - return role; - } - return AccessibleRole.ProgressBar; - } + public override AccessibleRole Role + { + get + { + AccessibleRole role = Owner.AccessibleRole; + if (role != AccessibleRole.Default) + { + return role; + } + + return AccessibleRole.ProgressBar; + } } - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { if (direction == UnsafeNativeMethods.NavigateDirection.FirstChild || - direction == UnsafeNativeMethods.NavigateDirection.LastChild) { + direction == UnsafeNativeMethods.NavigateDirection.LastChild) + { return this.ownerItem.ProgressBar.AccessibilityObject; } @@ -433,30 +488,38 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga } } - internal class ToolStripProgressBarControl : ProgressBar { + internal class ToolStripProgressBarControl : ProgressBar + { private ToolStripProgressBar ownerItem; - public ToolStripProgressBar Owner { + public ToolStripProgressBar Owner + { get { return ownerItem; } set { ownerItem = value; } } internal override bool SupportsUiaProviders => true; - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new ToolStripProgressBarControlAccessibleObject(this); } } - internal class ToolStripProgressBarControlAccessibleObject : ProgressBar.ProgressBarAccessibleObject { - public ToolStripProgressBarControlAccessibleObject(ToolStripProgressBarControl toolStripProgressBarControl) : base(toolStripProgressBarControl) { + internal class ToolStripProgressBarControlAccessibleObject : ProgressBar.ProgressBarAccessibleObject + { + public ToolStripProgressBarControlAccessibleObject(ToolStripProgressBarControl toolStripProgressBarControl) : base(toolStripProgressBarControl) + { } - internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot { - get { + internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot + { + get + { var toolStripProgressBarControl = this.Owner as ToolStripProgressBarControl; - if (toolStripProgressBarControl != null) { + if (toolStripProgressBarControl != null) + { return toolStripProgressBarControl.Owner.Owner.AccessibilityObject; } @@ -464,13 +527,16 @@ internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRo } } - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - switch (direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { + switch (direction) + { case UnsafeNativeMethods.NavigateDirection.Parent: case UnsafeNativeMethods.NavigateDirection.PreviousSibling: case UnsafeNativeMethods.NavigateDirection.NextSibling: var toolStripProgressBarControl = Owner as ToolStripProgressBarControl; - if (toolStripProgressBarControl != null) { + if (toolStripProgressBarControl != null) + { return toolStripProgressBarControl.Owner.AccessibilityObject.FragmentNavigate(direction); } break; @@ -479,7 +545,8 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga return base.FragmentNavigate(direction); } - internal override object GetPropertyValue(int propertyID) { + internal override object GetPropertyValue(int propertyID) + { return base.GetPropertyValue(propertyID); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRenderEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRenderEventArgs.cs index 9f61a8598bb..814168d9eee 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRenderEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRenderEventArgs.cs @@ -9,7 +9,7 @@ namespace System.Windows.Forms public class ToolStripRenderEventArgs : EventArgs { private Color _backColor = Color.Empty; - + /// /// This class represents all the information to render the toolStrip /// @@ -57,7 +57,8 @@ public Color BackColor { // get the user specified color _backColor = ToolStrip.RawBackColor; - if (_backColor == Color.Empty) { + if (_backColor == Color.Empty) + { if (ToolStrip is ToolStripDropDown) { _backColor = SystemColors.Menu; @@ -97,31 +98,31 @@ public Rectangle ConnectedArea Rectangle bounds = ToolStrip.Bounds; Rectangle overlap = ToolStrip.ClientRectangle; - overlap.Inflate(1,1); + overlap.Inflate(1, 1); if (overlap.IntersectsWith(itemBounds)) { switch (ownerItem.DropDownDirection) { case ToolStripDropDownDirection.AboveLeft: - case ToolStripDropDownDirection.AboveRight: + case ToolStripDropDownDirection.AboveRight: return Rectangle.Empty; case ToolStripDropDownDirection.BelowRight: case ToolStripDropDownDirection.BelowLeft: overlap.Intersect(itemBounds); if (overlap.Height == 2) { - return new Rectangle(itemBounds.X+1, 0, itemBounds.Width -2, 2); + return new Rectangle(itemBounds.X + 1, 0, itemBounds.Width - 2, 2); } - + // If its overlapping more than one pixel, this means we've pushed it to obscure // the menu item. In this case pretend it's not connected. return Rectangle.Empty; case ToolStripDropDownDirection.Right: case ToolStripDropDownDirection.Left: return Rectangle.Empty; - } - } - } + } + } + } } return Rectangle.Empty; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRenderer.cs index b15c0ce8de2..7a5cbf03e1b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRenderer.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Windows.Forms.VisualStyles; using System.Drawing; @@ -11,31 +12,32 @@ namespace System.Windows.Forms { using System.Drawing.Imaging; using System.ComponentModel; using System.Windows.Forms.Layout; - - public abstract class ToolStripRenderer { - - private static readonly object EventRenderSplitButtonBackground = new object(); - private static readonly object EventRenderItemBackground = new object(); - private static readonly object EventRenderItemImage = new object(); - private static readonly object EventRenderItemText = new object(); - private static readonly object EventRenderToolStripBackground = new object(); - private static readonly object EventRenderGrip = new object(); - private static readonly object EventRenderButtonBackground = new object(); - private static readonly object EventRenderLabelBackground = new object(); - private static readonly object EventRenderMenuItemBackground = new object(); - private static readonly object EventRenderDropDownButtonBackground = new object(); - private static readonly object EventRenderOverflowButtonBackground = new object(); - private static readonly object EventRenderImageMargin = new object(); - private static readonly object EventRenderBorder = new object(); - private static readonly object EventRenderArrow = new object(); - private static readonly object EventRenderStatusStripPanelBackground = new object(); - private static readonly object EventRenderToolStripStatusLabelBackground = new object(); - private static readonly object EventRenderSeparator = new object(); - private static readonly object EventRenderItemCheck = new object(); - private static readonly object EventRenderToolStripPanelBackground = new object(); - private static readonly object EventRenderToolStripContentPanelBackground = new object(); - - private static readonly object EventRenderStatusStripSizingGrip = new object(); + + public abstract class ToolStripRenderer + { + + private static readonly object EventRenderSplitButtonBackground = new object(); + private static readonly object EventRenderItemBackground = new object(); + private static readonly object EventRenderItemImage = new object(); + private static readonly object EventRenderItemText = new object(); + private static readonly object EventRenderToolStripBackground = new object(); + private static readonly object EventRenderGrip = new object(); + private static readonly object EventRenderButtonBackground = new object(); + private static readonly object EventRenderLabelBackground = new object(); + private static readonly object EventRenderMenuItemBackground = new object(); + private static readonly object EventRenderDropDownButtonBackground = new object(); + private static readonly object EventRenderOverflowButtonBackground = new object(); + private static readonly object EventRenderImageMargin = new object(); + private static readonly object EventRenderBorder = new object(); + private static readonly object EventRenderArrow = new object(); + private static readonly object EventRenderStatusStripPanelBackground = new object(); + private static readonly object EventRenderToolStripStatusLabelBackground = new object(); + private static readonly object EventRenderSeparator = new object(); + private static readonly object EventRenderItemCheck = new object(); + private static readonly object EventRenderToolStripPanelBackground = new object(); + private static readonly object EventRenderToolStripContentPanelBackground = new object(); + + private static readonly object EventRenderStatusStripSizingGrip = new object(); private static ColorMatrix disabledImageColorMatrix; @@ -61,64 +63,75 @@ public abstract class ToolStripRenderer { new Rectangle(4,4,2,2), new Rectangle(4,8,2,2), new Rectangle(0,8,2,2) }; - - protected ToolStripRenderer() { + + protected ToolStripRenderer() + { } - internal ToolStripRenderer(bool isAutoGenerated) { + internal ToolStripRenderer(bool isAutoGenerated) + { this.isAutoGenerated = isAutoGenerated; } // this is used in building disabled images. - private static ColorMatrix DisabledImageColorMatrix { - get { - if (disabledImageColorMatrix == null) { + private static ColorMatrix DisabledImageColorMatrix + { + get + { + if (disabledImageColorMatrix == null) + { // this is the result of a GreyScale matrix multiplied by a transparency matrix of .5 - - + + float[][] greyscale = new float[5][]; - greyscale[0] = new float[5] {0.2125f, 0.2125f, 0.2125f, 0, 0}; - greyscale[1] = new float[5] {0.2577f, 0.2577f, 0.2577f, 0, 0}; - greyscale[2] = new float[5] {0.0361f, 0.0361f, 0.0361f, 0, 0}; - greyscale[3] = new float[5] {0, 0, 0, 1, 0}; - greyscale[4] = new float[5] {0.38f, 0.38f, 0.38f, 0, 1}; + greyscale[0] = new float[5] { 0.2125f, 0.2125f, 0.2125f, 0, 0 }; + greyscale[1] = new float[5] { 0.2577f, 0.2577f, 0.2577f, 0, 0 }; + greyscale[2] = new float[5] { 0.0361f, 0.0361f, 0.0361f, 0, 0 }; + greyscale[3] = new float[5] { 0, 0, 0, 1, 0 }; + greyscale[4] = new float[5] { 0.38f, 0.38f, 0.38f, 0, 1 }; float[][] transparency = new float[5][]; - transparency[0] = new float[5] {1, 0, 0, 0, 0}; - transparency[1] = new float[5] {0, 1, 0, 0, 0}; - transparency[2] = new float[5] {0, 0, 1, 0, 0}; - transparency[3] = new float[5] {0, 0, 0, .7F, 0}; - transparency[4] = new float[5] {0, 0, 0, 0, 0}; + transparency[0] = new float[5] { 1, 0, 0, 0, 0 }; + transparency[1] = new float[5] { 0, 1, 0, 0, 0 }; + transparency[2] = new float[5] { 0, 0, 1, 0, 0 }; + transparency[3] = new float[5] { 0, 0, 0, .7F, 0 }; + transparency[4] = new float[5] { 0, 0, 0, 0, 0 }; disabledImageColorMatrix = ControlPaint.MultiplyColorMatrix(transparency, greyscale); } - + return disabledImageColorMatrix; } } - + /// /// Gets the list of event handlers that are attached to this component. /// - private EventHandlerList Events { - get { - if (events == null) { + private EventHandlerList Events + { + get + { + if (events == null) + { events = new EventHandlerList(); } return events; } } - internal bool IsAutoGenerated { + internal bool IsAutoGenerated + { get { return isAutoGenerated; } } - + // if we're in a low contrast, high resolution situation, use this renderer under the covers instead. - internal virtual ToolStripRenderer RendererOverride { - get { + internal virtual ToolStripRenderer RendererOverride + { + get + { return null; } } @@ -130,224 +143,256 @@ internal virtual ToolStripRenderer RendererOverride { - public event ToolStripArrowRenderEventHandler RenderArrow { - add => AddHandler(EventRenderArrow, value); + public event ToolStripArrowRenderEventHandler RenderArrow + { + add => AddHandler(EventRenderArrow, value); remove => RemoveHandler(EventRenderArrow, value); } - + /// /// Occurs when the display style has changed /// - public event ToolStripRenderEventHandler RenderToolStripBackground { - add => AddHandler(EventRenderToolStripBackground, value); + public event ToolStripRenderEventHandler RenderToolStripBackground + { + add => AddHandler(EventRenderToolStripBackground, value); remove => RemoveHandler(EventRenderToolStripBackground, value); } - - public event ToolStripPanelRenderEventHandler RenderToolStripPanelBackground { - add => AddHandler(EventRenderToolStripPanelBackground, value); + + public event ToolStripPanelRenderEventHandler RenderToolStripPanelBackground + { + add => AddHandler(EventRenderToolStripPanelBackground, value); remove => RemoveHandler(EventRenderToolStripPanelBackground, value); } - public event ToolStripContentPanelRenderEventHandler RenderToolStripContentPanelBackground { - add => AddHandler(EventRenderToolStripContentPanelBackground, value); - remove => RemoveHandler(EventRenderToolStripContentPanelBackground, value); - } + public event ToolStripContentPanelRenderEventHandler RenderToolStripContentPanelBackground + { + add => AddHandler(EventRenderToolStripContentPanelBackground, value); + remove => RemoveHandler(EventRenderToolStripContentPanelBackground, value); + } /// /// Occurs when the display style has changed /// - public event ToolStripRenderEventHandler RenderToolStripBorder { - add => AddHandler(EventRenderBorder, value); + public event ToolStripRenderEventHandler RenderToolStripBorder + { + add => AddHandler(EventRenderBorder, value); remove => RemoveHandler(EventRenderBorder, value); } /// /// Occurs when the display style has changed /// - public event ToolStripItemRenderEventHandler RenderButtonBackground { - add => AddHandler(EventRenderButtonBackground, value); + public event ToolStripItemRenderEventHandler RenderButtonBackground + { + add => AddHandler(EventRenderButtonBackground, value); remove => RemoveHandler(EventRenderButtonBackground, value); - } + } /// /// Occurs when the display style has changed /// - public event ToolStripItemRenderEventHandler RenderDropDownButtonBackground { - add => AddHandler(EventRenderDropDownButtonBackground, value); + public event ToolStripItemRenderEventHandler RenderDropDownButtonBackground + { + add => AddHandler(EventRenderDropDownButtonBackground, value); remove => RemoveHandler(EventRenderDropDownButtonBackground, value); - } + } /// /// Occurs when the display style has changed /// - public event ToolStripItemRenderEventHandler RenderOverflowButtonBackground { - add => AddHandler(EventRenderOverflowButtonBackground, value); + public event ToolStripItemRenderEventHandler RenderOverflowButtonBackground + { + add => AddHandler(EventRenderOverflowButtonBackground, value); remove => RemoveHandler(EventRenderOverflowButtonBackground, value); - } + } /// /// Occurs when the display style has changed /// - public event ToolStripGripRenderEventHandler RenderGrip { - add => AddHandler(EventRenderGrip, value); + public event ToolStripGripRenderEventHandler RenderGrip + { + add => AddHandler(EventRenderGrip, value); remove => RemoveHandler(EventRenderGrip, value); - } + } /// /// Occurs when the display style has changed /// - public event ToolStripItemRenderEventHandler RenderItemBackground { - add => AddHandler(EventRenderItemBackground, value); + public event ToolStripItemRenderEventHandler RenderItemBackground + { + add => AddHandler(EventRenderItemBackground, value); remove => RemoveHandler(EventRenderItemBackground, value); - } + } /// /// Draws the split button /// - public event ToolStripItemImageRenderEventHandler RenderItemImage { - add => AddHandler(EventRenderItemImage, value); + public event ToolStripItemImageRenderEventHandler RenderItemImage + { + add => AddHandler(EventRenderItemImage, value); remove => RemoveHandler(EventRenderItemImage, value); - } + } /// /// Draws the checkmark /// - public event ToolStripItemImageRenderEventHandler RenderItemCheck { - add => AddHandler(EventRenderItemCheck, value); + public event ToolStripItemImageRenderEventHandler RenderItemCheck + { + add => AddHandler(EventRenderItemCheck, value); remove => RemoveHandler(EventRenderItemCheck, value); - } + } /// /// Draws the split button /// - public event ToolStripItemTextRenderEventHandler RenderItemText { - add => AddHandler(EventRenderItemText, value); + public event ToolStripItemTextRenderEventHandler RenderItemText + { + add => AddHandler(EventRenderItemText, value); remove => RemoveHandler(EventRenderItemText, value); - } + } - public event ToolStripRenderEventHandler RenderImageMargin { - add => AddHandler(EventRenderImageMargin, value); + public event ToolStripRenderEventHandler RenderImageMargin + { + add => AddHandler(EventRenderImageMargin, value); remove => RemoveHandler(EventRenderImageMargin, value); } /// /// Occurs when the display style has changed /// - public event ToolStripItemRenderEventHandler RenderLabelBackground { - add => AddHandler(EventRenderLabelBackground, value); + public event ToolStripItemRenderEventHandler RenderLabelBackground + { + add => AddHandler(EventRenderLabelBackground, value); remove => RemoveHandler(EventRenderLabelBackground, value); - } + } /// /// Occurs when the display style has changed /// - public event ToolStripItemRenderEventHandler RenderMenuItemBackground { - add => AddHandler(EventRenderMenuItemBackground, value); + public event ToolStripItemRenderEventHandler RenderMenuItemBackground + { + add => AddHandler(EventRenderMenuItemBackground, value); remove => RemoveHandler(EventRenderMenuItemBackground, value); - } + } /// /// Draws the split button /// - public event ToolStripItemRenderEventHandler RenderToolStripStatusLabelBackground { - add => AddHandler(EventRenderToolStripStatusLabelBackground, value); + public event ToolStripItemRenderEventHandler RenderToolStripStatusLabelBackground + { + add => AddHandler(EventRenderToolStripStatusLabelBackground, value); remove => RemoveHandler(EventRenderToolStripStatusLabelBackground, value); } - + /// /// Occurs when the display style has changed /// - public event ToolStripRenderEventHandler RenderStatusStripSizingGrip { - add => AddHandler(EventRenderStatusStripSizingGrip, value); + public event ToolStripRenderEventHandler RenderStatusStripSizingGrip + { + add => AddHandler(EventRenderStatusStripSizingGrip, value); remove => RemoveHandler(EventRenderStatusStripSizingGrip, value); } - + /// /// Draws the split button /// - public event ToolStripItemRenderEventHandler RenderSplitButtonBackground { - add => AddHandler(EventRenderSplitButtonBackground, value); + public event ToolStripItemRenderEventHandler RenderSplitButtonBackground + { + add => AddHandler(EventRenderSplitButtonBackground, value); remove => RemoveHandler(EventRenderSplitButtonBackground, value); - } - - - public event ToolStripSeparatorRenderEventHandler RenderSeparator { - add => AddHandler(EventRenderSeparator, value); - remove => RemoveHandler(EventRenderSeparator, value); - } + } + + + public event ToolStripSeparatorRenderEventHandler RenderSeparator + { + add => AddHandler(EventRenderSeparator, value); + remove => RemoveHandler(EventRenderSeparator, value); + } -#region EventHandlerSecurity - /// ----------------------------------------------------------------------------- - /// + #region EventHandlerSecurity + /// ----------------------------------------------------------------------------- + /// - private void AddHandler(object key, Delegate value) { + private void AddHandler(object key, Delegate value) + { Events.AddHandler(key, value); - } + } - private void RemoveHandler(object key, Delegate value) { + private void RemoveHandler(object key, Delegate value) + { Events.RemoveHandler(key, value); - } -#endregion - - public static Image CreateDisabledImage(Image normalImage) { + } + #endregion + + public static Image CreateDisabledImage(Image normalImage) + { return CreateDisabledImage(normalImage, null); - } + } - public void DrawArrow(ToolStripArrowRenderEventArgs e) { + public void DrawArrow(ToolStripArrowRenderEventArgs e) + { OnRenderArrow(e); - + ToolStripArrowRenderEventHandler eh = Events[EventRenderArrow] as ToolStripArrowRenderEventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); - } + } } /// /// Draw the background color /// - public void DrawToolStripBackground(ToolStripRenderEventArgs e) { + public void DrawToolStripBackground(ToolStripRenderEventArgs e) + { OnRenderToolStripBackground(e); - + ToolStripRenderEventHandler eh = Events[EventRenderToolStripBackground] as ToolStripRenderEventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); - } + } } - + /// /// Draw the background color /// - public void DrawGrip(ToolStripGripRenderEventArgs e) { + public void DrawGrip(ToolStripGripRenderEventArgs e) + { OnRenderGrip(e); ToolStripGripRenderEventHandler eh = Events[EventRenderGrip] as ToolStripGripRenderEventHandler; - if (eh != null) { - eh(this, e); - } - } + if (eh != null) + { + eh(this, e); + } + } + - /// /// Draw the item's background. /// public void DrawItemBackground(ToolStripItemRenderEventArgs e) - { - OnRenderItemBackground(e); + { + OnRenderItemBackground(e); ToolStripItemRenderEventHandler eh = Events[EventRenderItemBackground] as ToolStripItemRenderEventHandler; - if (eh != null) { - eh(this, e); - } - - } + if (eh != null) + { + eh(this, e); + } + + } /// /// Draw the background color /// - public void DrawImageMargin(ToolStripRenderEventArgs e) { + public void DrawImageMargin(ToolStripRenderEventArgs e) + { OnRenderImageMargin(e); - + ToolStripRenderEventHandler eh = Events[EventRenderImageMargin] as ToolStripRenderEventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); - } + } } /// @@ -357,69 +402,76 @@ public void DrawLabelBackground(ToolStripItemRenderEventArgs e) { OnRenderLabelBackground(e); ToolStripItemRenderEventHandler eh = Events[EventRenderLabelBackground] as ToolStripItemRenderEventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); - } + } } /// /// Draw the item's background. /// public void DrawButtonBackground(ToolStripItemRenderEventArgs e) - { - OnRenderButtonBackground(e); + { + OnRenderButtonBackground(e); ToolStripItemRenderEventHandler eh = Events[EventRenderButtonBackground] as ToolStripItemRenderEventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); } - } + } public void DrawToolStripBorder(ToolStripRenderEventArgs e) - { - OnRenderToolStripBorder(e); + { + OnRenderToolStripBorder(e); - ToolStripRenderEventHandler eh = Events[EventRenderBorder] as ToolStripRenderEventHandler; - if (eh != null) { - eh(this, e); - } - } + ToolStripRenderEventHandler eh = Events[EventRenderBorder] as ToolStripRenderEventHandler; + if (eh != null) + { + eh(this, e); + } + } /// /// Draw the item's background. /// public void DrawDropDownButtonBackground(ToolStripItemRenderEventArgs e) - { - OnRenderDropDownButtonBackground(e); + { + OnRenderDropDownButtonBackground(e); ToolStripItemRenderEventHandler eh = Events[EventRenderDropDownButtonBackground] as ToolStripItemRenderEventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); } - } + } /// /// Draw the item's background. /// public void DrawOverflowButtonBackground(ToolStripItemRenderEventArgs e) - { - OnRenderOverflowButtonBackground(e); + { + OnRenderOverflowButtonBackground(e); ToolStripItemRenderEventHandler eh = Events[EventRenderOverflowButtonBackground] as ToolStripItemRenderEventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); } - } - + } + /// /// Draw image /// - public void DrawItemImage(ToolStripItemImageRenderEventArgs e) { + public void DrawItemImage(ToolStripItemImageRenderEventArgs e) + { OnRenderItemImage(e); - + ToolStripItemImageRenderEventHandler eh = Events[EventRenderItemImage] as ToolStripItemImageRenderEventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); } } @@ -427,23 +479,27 @@ public void DrawItemImage(ToolStripItemImageRenderEventArgs e) { /// /// Draw image /// - public void DrawItemCheck(ToolStripItemImageRenderEventArgs e) { - OnRenderItemCheck(e); - - ToolStripItemImageRenderEventHandler eh = Events[EventRenderItemCheck] as ToolStripItemImageRenderEventHandler; - if (eh != null) { - eh(this, e); - } + public void DrawItemCheck(ToolStripItemImageRenderEventArgs e) + { + OnRenderItemCheck(e); + + ToolStripItemImageRenderEventHandler eh = Events[EventRenderItemCheck] as ToolStripItemImageRenderEventHandler; + if (eh != null) + { + eh(this, e); + } } /// /// Draw text /// - public void DrawItemText(ToolStripItemTextRenderEventArgs e) { + public void DrawItemText(ToolStripItemTextRenderEventArgs e) + { OnRenderItemText(e); - + ToolStripItemTextRenderEventHandler eh = Events[EventRenderItemText] as ToolStripItemTextRenderEventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); } } @@ -452,106 +508,127 @@ public void DrawItemText(ToolStripItemTextRenderEventArgs e) { /// Draw the item's background. /// public void DrawMenuItemBackground(ToolStripItemRenderEventArgs e) - { - OnRenderMenuItemBackground(e); + { + OnRenderMenuItemBackground(e); ToolStripItemRenderEventHandler eh = Events[EventRenderMenuItemBackground] as ToolStripItemRenderEventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); } - } - - + } + + /// /// Draw the background color /// - public void DrawSplitButton(ToolStripItemRenderEventArgs e) { - - OnRenderSplitButtonBackground(e); + public void DrawSplitButton(ToolStripItemRenderEventArgs e) + { + + OnRenderSplitButtonBackground(e); ToolStripItemRenderEventHandler eh = Events[EventRenderSplitButtonBackground] as ToolStripItemRenderEventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); } - + } /// /// Draw the background color /// - public void DrawToolStripStatusLabelBackground(ToolStripItemRenderEventArgs e) { - - OnRenderToolStripStatusLabelBackground(e); + public void DrawToolStripStatusLabelBackground(ToolStripItemRenderEventArgs e) + { + + OnRenderToolStripStatusLabelBackground(e); ToolStripItemRenderEventHandler eh = Events[EventRenderToolStripStatusLabelBackground] as ToolStripItemRenderEventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); } - + } - + // - public void DrawStatusStripSizingGrip(ToolStripRenderEventArgs e) { - + public void DrawStatusStripSizingGrip(ToolStripRenderEventArgs e) + { + OnRenderStatusStripSizingGrip(e); ToolStripRenderEventHandler eh = Events[EventRenderStatusStripSizingGrip] as ToolStripRenderEventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); } } /// /// Draw the separator /// - public void DrawSeparator(ToolStripSeparatorRenderEventArgs e) { + public void DrawSeparator(ToolStripSeparatorRenderEventArgs e) + { OnRenderSeparator(e); ToolStripSeparatorRenderEventHandler eh = Events[EventRenderSeparator] as ToolStripSeparatorRenderEventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); } } - public void DrawToolStripPanelBackground(ToolStripPanelRenderEventArgs e) { + public void DrawToolStripPanelBackground(ToolStripPanelRenderEventArgs e) + { OnRenderToolStripPanelBackground(e); ToolStripPanelRenderEventHandler eh = Events[EventRenderToolStripPanelBackground] as ToolStripPanelRenderEventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); } } - public void DrawToolStripContentPanelBackground(ToolStripContentPanelRenderEventArgs e) { + public void DrawToolStripContentPanelBackground(ToolStripContentPanelRenderEventArgs e) + { OnRenderToolStripContentPanelBackground(e); ToolStripContentPanelRenderEventHandler eh = Events[EventRenderToolStripContentPanelBackground] as ToolStripContentPanelRenderEventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); } } // consider make public - internal virtual Region GetTransparentRegion(ToolStrip toolStrip) { - return null; + internal virtual Region GetTransparentRegion(ToolStrip toolStrip) + { + return null; } - - protected internal virtual void Initialize(ToolStrip toolStrip){ + + protected internal virtual void Initialize(ToolStrip toolStrip) + { } - protected internal virtual void InitializePanel(ToolStripPanel toolStripPanel){ + protected internal virtual void InitializePanel(ToolStripPanel toolStripPanel) + { } - protected internal virtual void InitializeContentPanel(ToolStripContentPanel contentPanel){ + protected internal virtual void InitializeContentPanel(ToolStripContentPanel contentPanel) + { } - protected internal virtual void InitializeItem (ToolStripItem item){ + protected internal virtual void InitializeItem(ToolStripItem item) + { } - protected static void ScaleArrowOffsetsIfNeeded() { - if (isScalingInitialized) { + protected static void ScaleArrowOffsetsIfNeeded() + { + if (isScalingInitialized) + { return; } - - if (DpiHelper.IsScalingRequired) { + + if (DpiHelper.IsScalingRequired) + { Offset2X = DpiHelper.LogicalToDeviceUnitsX(OFFSET_2PIXELS); Offset2Y = DpiHelper.LogicalToDeviceUnitsY(OFFSET_2PIXELS); offset4X = DpiHelper.LogicalToDeviceUnitsX(OFFSET_4PIXELS); @@ -561,87 +638,97 @@ protected static void ScaleArrowOffsetsIfNeeded() { } - protected virtual void OnRenderArrow(ToolStripArrowRenderEventArgs e){ + protected virtual void OnRenderArrow(ToolStripArrowRenderEventArgs e) + { - if (RendererOverride != null) { - RendererOverride.OnRenderArrow(e); - return; + if (RendererOverride != null) + { + RendererOverride.OnRenderArrow(e); + return; } Graphics g = e.Graphics; Rectangle dropDownRect = e.ArrowRectangle; - using (Brush brush = new SolidBrush(e.ArrowColor)) { - - Point middle = new Point(dropDownRect.Left + dropDownRect.Width / 2, dropDownRect.Top + dropDownRect.Height / 2); - // if the width is odd - favor pushing it over one pixel right. - //middle.X += (dropDownRect.Width % 2); + using (Brush brush = new SolidBrush(e.ArrowColor)) + { + + Point middle = new Point(dropDownRect.Left + dropDownRect.Width / 2, dropDownRect.Top + dropDownRect.Height / 2); + // if the width is odd - favor pushing it over one pixel right. + //middle.X += (dropDownRect.Width % 2); - Point[] arrow = null; + Point[] arrow = null; - ScaleArrowOffsetsIfNeeded(); + ScaleArrowOffsetsIfNeeded(); // using (offset4X - Offset2X) instead of (Offset2X) to compensate for rounding error in scaling int horizontalOffset = DpiHelper.IsScalingRequirementMet ? offset4X - Offset2X : Offset2X; - switch (e.Direction) { - case ArrowDirection.Up: - - arrow = new Point[] { + switch (e.Direction) + { + case ArrowDirection.Up: + + arrow = new Point[] { new Point(middle.X - Offset2X, middle.Y + 1), new Point(middle.X + Offset2X + 1, middle.Y + 1), new Point(middle.X, middle.Y - Offset2Y)}; - - break; - case ArrowDirection.Left: - arrow = new Point[] { + + break; + case ArrowDirection.Left: + arrow = new Point[] { new Point(middle.X + Offset2X, middle.Y - offset4Y), new Point(middle.X + Offset2X, middle.Y + offset4Y), new Point(middle.X - horizontalOffset, middle.Y)}; - - break; - case ArrowDirection.Right: - arrow = new Point[] { + + break; + case ArrowDirection.Right: + arrow = new Point[] { new Point(middle.X - Offset2X, middle.Y - offset4Y), new Point(middle.X - Offset2X, middle.Y + offset4Y), new Point(middle.X + horizontalOffset, middle.Y)}; - - break; - case ArrowDirection.Down: - default: - arrow = new Point[] { + + break; + case ArrowDirection.Down: + default: + arrow = new Point[] { new Point(middle.X - Offset2X, middle.Y - 1), new Point(middle.X + Offset2X + 1, middle.Y - 1), new Point(middle.X, middle.Y + Offset2Y) }; - break; - } - g.FillPolygon(brush, arrow); + break; + } + g.FillPolygon(brush, arrow); } } - + /// /// Draw the ToolStrip background. ToolStrip users should override this if they want to draw differently. /// - protected virtual void OnRenderToolStripBackground(ToolStripRenderEventArgs e) { - if (RendererOverride != null) { - RendererOverride.OnRenderToolStripBackground(e); - return; + protected virtual void OnRenderToolStripBackground(ToolStripRenderEventArgs e) + { + if (RendererOverride != null) + { + RendererOverride.OnRenderToolStripBackground(e); + return; } } - + /// /// Draw the border around the ToolStrip. This should be done as the last step. /// - protected virtual void OnRenderToolStripBorder(ToolStripRenderEventArgs e) { - if (RendererOverride != null) { + protected virtual void OnRenderToolStripBorder(ToolStripRenderEventArgs e) + { + if (RendererOverride != null) + { RendererOverride.OnRenderToolStripBorder(e); return; } } - + /// /// Draw the grip. ToolStrip users should override this if they want to draw differently. /// - protected virtual void OnRenderGrip(ToolStripGripRenderEventArgs e) { - if (RendererOverride != null) { + protected virtual void OnRenderGrip(ToolStripGripRenderEventArgs e) + { + if (RendererOverride != null) + { RendererOverride.OnRenderGrip(e); return; } @@ -650,8 +737,10 @@ protected virtual void OnRenderGrip(ToolStripGripRenderEventArgs e) { /// /// Draw the items background /// - protected virtual void OnRenderItemBackground(ToolStripItemRenderEventArgs e) { - if (RendererOverride != null) { + protected virtual void OnRenderItemBackground(ToolStripItemRenderEventArgs e) + { + if (RendererOverride != null) + { RendererOverride.OnRenderItemBackground(e); return; } @@ -661,8 +750,10 @@ protected virtual void OnRenderItemBackground(ToolStripItemRenderEventArgs e) { /// /// Draw the items background /// - protected virtual void OnRenderImageMargin(ToolStripRenderEventArgs e) { - if (RendererOverride != null) { + protected virtual void OnRenderImageMargin(ToolStripRenderEventArgs e) + { + if (RendererOverride != null) + { RendererOverride.OnRenderImageMargin(e); return; } @@ -671,19 +762,23 @@ protected virtual void OnRenderImageMargin(ToolStripRenderEventArgs e) { /// /// Draw the button background /// - protected virtual void OnRenderButtonBackground(ToolStripItemRenderEventArgs e) { - if (RendererOverride != null) { + protected virtual void OnRenderButtonBackground(ToolStripItemRenderEventArgs e) + { + if (RendererOverride != null) + { RendererOverride.OnRenderButtonBackground(e); return; } } - + /// /// Draw the button background /// - protected virtual void OnRenderDropDownButtonBackground(ToolStripItemRenderEventArgs e) { - if (RendererOverride != null) { + protected virtual void OnRenderDropDownButtonBackground(ToolStripItemRenderEventArgs e) + { + if (RendererOverride != null) + { RendererOverride.OnRenderDropDownButtonBackground(e); return; } @@ -693,8 +788,10 @@ protected virtual void OnRenderDropDownButtonBackground(ToolStripItemRenderEvent /// /// Draw the button background /// - protected virtual void OnRenderOverflowButtonBackground(ToolStripItemRenderEventArgs e) { - if (RendererOverride != null) { + protected virtual void OnRenderOverflowButtonBackground(ToolStripItemRenderEventArgs e) + { + if (RendererOverride != null) + { RendererOverride.OnRenderOverflowButtonBackground(e); return; } @@ -703,94 +800,112 @@ protected virtual void OnRenderOverflowButtonBackground(ToolStripItemRenderEvent /// Draw the item'si mage. ToolStrip users should override this function to change the /// drawing of all images. /// - protected virtual void OnRenderItemImage(ToolStripItemImageRenderEventArgs e) { - if (RendererOverride != null) { + protected virtual void OnRenderItemImage(ToolStripItemImageRenderEventArgs e) + { + if (RendererOverride != null) + { RendererOverride.OnRenderItemImage(e); return; } Rectangle imageRect = e.ImageRectangle; Image image = e.Image; - - if (imageRect != Rectangle.Empty && image != null) { + + if (imageRect != Rectangle.Empty && image != null) + { bool disposeImage = false; - if (e.ShiftOnPress && e.Item.Pressed) { - imageRect.X++; + if (e.ShiftOnPress && e.Item.Pressed) + { + imageRect.X++; } - if (!e.Item.Enabled) { + if (!e.Item.Enabled) + { image = CreateDisabledImage(image, e.ImageAttributes); disposeImage = true; } - if (e.Item.ImageScaling == ToolStripItemImageScaling.None) { - e.Graphics.DrawImage(image, imageRect, new Rectangle(Point.Empty,imageRect.Size), GraphicsUnit.Pixel); + if (e.Item.ImageScaling == ToolStripItemImageScaling.None) + { + e.Graphics.DrawImage(image, imageRect, new Rectangle(Point.Empty, imageRect.Size), GraphicsUnit.Pixel); } - else { + else + { e.Graphics.DrawImage(image, imageRect); } - if (disposeImage) { + if (disposeImage) + { image.Dispose(); } } } - - protected virtual void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) { - if (RendererOverride != null) { + + protected virtual void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) + { + if (RendererOverride != null) + { RendererOverride.OnRenderItemCheck(e); return; } - Rectangle imageRect = e.ImageRectangle; - Image image = e.Image; - - if (imageRect != Rectangle.Empty && image != null) { - if (!e.Item.Enabled) { - image = CreateDisabledImage(image, e.ImageAttributes); - } - - e.Graphics.DrawImage(image, imageRect, 0, 0, imageRect.Width, - imageRect.Height, GraphicsUnit.Pixel, e.ImageAttributes); - } - } + Rectangle imageRect = e.ImageRectangle; + Image image = e.Image; + + if (imageRect != Rectangle.Empty && image != null) + { + if (!e.Item.Enabled) + { + image = CreateDisabledImage(image, e.ImageAttributes); + } + + e.Graphics.DrawImage(image, imageRect, 0, 0, imageRect.Width, + imageRect.Height, GraphicsUnit.Pixel, e.ImageAttributes); + } + } + - /// /// Draw the item's text. ToolStrip users should override this function to change the /// drawing of all text. /// - protected virtual void OnRenderItemText(ToolStripItemTextRenderEventArgs e) { - if (RendererOverride != null) { + protected virtual void OnRenderItemText(ToolStripItemTextRenderEventArgs e) + { + if (RendererOverride != null) + { RendererOverride.OnRenderItemText(e); return; } - - ToolStripItem item = e.Item; - Graphics g = e.Graphics; - Color textColor = e.TextColor; - Font textFont = e.TextFont; - string text = e.Text; - Rectangle textRect = e.TextRectangle; + + ToolStripItem item = e.Item; + Graphics g = e.Graphics; + Color textColor = e.TextColor; + Font textFont = e.TextFont; + string text = e.Text; + Rectangle textRect = e.TextRectangle; TextFormatFlags textFormat = e.TextFormat; // if we're disabled draw in a different color. textColor = (item.Enabled) ? textColor : SystemColors.GrayText; - if (e.TextDirection != ToolStripTextDirection.Horizontal && textRect.Width > 0 && textRect.Height > 0) { + if (e.TextDirection != ToolStripTextDirection.Horizontal && textRect.Width > 0 && textRect.Height > 0) + { // Perf: this is a bit heavy handed.. perhaps we can share the bitmap. Size textSize = LayoutUtils.FlipSize(textRect.Size); - using (Bitmap textBmp = new Bitmap(textSize.Width, textSize.Height,PixelFormat.Format32bppPArgb)) { - - using (Graphics textGraphics = Graphics.FromImage(textBmp)) { + using (Bitmap textBmp = new Bitmap(textSize.Width, textSize.Height, PixelFormat.Format32bppPArgb)) + { + + using (Graphics textGraphics = Graphics.FromImage(textBmp)) + { // now draw the text.. textGraphics.TextRenderingHint = TextRenderingHint.AntiAlias; TextRenderer.DrawText(textGraphics, text, textFont, new Rectangle(Point.Empty, textSize), textColor, textFormat); - textBmp.RotateFlip((e.TextDirection == ToolStripTextDirection.Vertical90) ? RotateFlipType.Rotate90FlipNone : RotateFlipType.Rotate270FlipNone); + textBmp.RotateFlip((e.TextDirection == ToolStripTextDirection.Vertical90) ? RotateFlipType.Rotate90FlipNone : RotateFlipType.Rotate270FlipNone); g.DrawImage(textBmp, textRect); } } } - else { + else + { TextRenderer.DrawText(g, text, textFont, textRect, textColor, textFormat); } } @@ -798,117 +913,142 @@ protected virtual void OnRenderItemText(ToolStripItemTextRenderEventArgs e) { /// /// Draw the button background /// - protected virtual void OnRenderLabelBackground(ToolStripItemRenderEventArgs e) { - if (RendererOverride != null) { + protected virtual void OnRenderLabelBackground(ToolStripItemRenderEventArgs e) + { + if (RendererOverride != null) + { RendererOverride.OnRenderLabelBackground(e); return; } - + } /// /// Draw the items background /// - protected virtual void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) { - if (RendererOverride != null) { - RendererOverride.OnRenderMenuItemBackground(e); - return; - } + protected virtual void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) + { + if (RendererOverride != null) + { + RendererOverride.OnRenderMenuItemBackground(e); + return; + } } - + /// /// Draws a toolbar separator. ToolStrip users should override this function to change the /// drawing of all separators. /// - protected virtual void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e) { - if (RendererOverride != null) { + protected virtual void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e) + { + if (RendererOverride != null) + { RendererOverride.OnRenderSeparator(e); return; } } - protected virtual void OnRenderToolStripPanelBackground(ToolStripPanelRenderEventArgs e) { - if (RendererOverride != null) { + protected virtual void OnRenderToolStripPanelBackground(ToolStripPanelRenderEventArgs e) + { + if (RendererOverride != null) + { RendererOverride.OnRenderToolStripPanelBackground(e); return; } } - protected virtual void OnRenderToolStripContentPanelBackground(ToolStripContentPanelRenderEventArgs e) { - if (RendererOverride != null) { + protected virtual void OnRenderToolStripContentPanelBackground(ToolStripContentPanelRenderEventArgs e) + { + if (RendererOverride != null) + { RendererOverride.OnRenderToolStripContentPanelBackground(e); return; } } - protected virtual void OnRenderToolStripStatusLabelBackground(ToolStripItemRenderEventArgs e) { - if (RendererOverride != null) { + protected virtual void OnRenderToolStripStatusLabelBackground(ToolStripItemRenderEventArgs e) + { + if (RendererOverride != null) + { RendererOverride.OnRenderToolStripStatusLabelBackground(e); return; } } - - protected virtual void OnRenderStatusStripSizingGrip(ToolStripRenderEventArgs e) { - if (RendererOverride != null) { + + protected virtual void OnRenderStatusStripSizingGrip(ToolStripRenderEventArgs e) + { + if (RendererOverride != null) + { RendererOverride.OnRenderStatusStripSizingGrip(e); return; } - + Graphics g = e.Graphics; StatusStrip statusStrip = e.ToolStrip as StatusStrip; // we have a set of stock rectangles. Translate them over to where the grip is to be drawn // for the white set, then translate them up and right one pixel for the grey. - - if (statusStrip != null) { + + if (statusStrip != null) + { Rectangle sizeGripBounds = statusStrip.SizeGripBounds; - if (!LayoutUtils.IsZeroWidthOrHeight(sizeGripBounds)) { + if (!LayoutUtils.IsZeroWidthOrHeight(sizeGripBounds)) + { Rectangle[] whiteRectangles = new Rectangle[baseSizeGripRectangles.Length]; Rectangle[] greyRectangles = new Rectangle[baseSizeGripRectangles.Length]; - - for (int i = 0; i < baseSizeGripRectangles.Length; i++) { + + for (int i = 0; i < baseSizeGripRectangles.Length; i++) + { Rectangle baseRect = baseSizeGripRectangles[i]; - if (statusStrip.RightToLeft == RightToLeft.Yes) { + if (statusStrip.RightToLeft == RightToLeft.Yes) + { baseRect.X = sizeGripBounds.Width - baseRect.X - baseRect.Width; } baseRect.Offset(sizeGripBounds.X, sizeGripBounds.Bottom - 12 /*height of pyramid (10px) + 2px padding from bottom*/); whiteRectangles[i] = baseRect; - if (statusStrip.RightToLeft == RightToLeft.Yes) { + if (statusStrip.RightToLeft == RightToLeft.Yes) + { baseRect.Offset(1, -1); } - else { + else + { baseRect.Offset(-1, -1); } greyRectangles[i] = baseRect; - + } - + g.FillRectangles(SystemBrushes.ButtonHighlight, whiteRectangles); g.FillRectangles(SystemBrushes.ButtonShadow, greyRectangles); } } - + } /// /// Draw the item's background. /// - protected virtual void OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs e) { - if (RendererOverride != null) { + protected virtual void OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs e) + { + if (RendererOverride != null) + { RendererOverride.OnRenderSplitButtonBackground(e); return; } } // Only paint background effects if no backcolor has been set or no background image has been set. - internal bool ShouldPaintBackground (Control control) { + internal bool ShouldPaintBackground(Control control) + { return (control.RawBackColor == Color.Empty && control.BackgroundImage == null); } - private static Image CreateDisabledImage(Image normalImage, ImageAttributes imgAttrib) { - if (imgAttrib == null) { + private static Image CreateDisabledImage(Image normalImage, ImageAttributes imgAttrib) + { + if (imgAttrib == null) + { imgAttrib = new ImageAttributes(); } @@ -917,7 +1057,8 @@ private static Image CreateDisabledImage(Image normalImage, ImageAttributes imgA Size size = normalImage.Size; Bitmap disabledBitmap = new Bitmap(size.Width, size.Height); - using (Graphics graphics = Graphics.FromImage(disabledBitmap)) { + using (Graphics graphics = Graphics.FromImage(disabledBitmap)) + { graphics.DrawImage(normalImage, new Rectangle(0, 0, size.Width, size.Height), @@ -929,5 +1070,5 @@ private static Image CreateDisabledImage(Image normalImage, ImageAttributes imgA return disabledBitmap; } - } + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRendererSwitcher.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRendererSwitcher.cs index 72c319118b4..a9a8fb8281d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRendererSwitcher.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRendererSwitcher.cs @@ -2,159 +2,195 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Drawing; using System.Collections.Specialized; using System.ComponentModel; - + // this class encapsulates the logic for Renderer and RenderMode so it can // be shared across classes. - internal class ToolStripRendererSwitcher { + internal class ToolStripRendererSwitcher + { - private static readonly int stateUseDefaultRenderer = BitVector32.CreateMask(); + private static readonly int stateUseDefaultRenderer = BitVector32.CreateMask(); private static readonly int stateAttachedRendererChanged = BitVector32.CreateMask(stateUseDefaultRenderer); - - private ToolStripRenderer renderer = null; - private Type currentRendererType = typeof(System.Type); - private BitVector32 state = new BitVector32(); - private ToolStripRenderMode defaultRenderMode = ToolStripRenderMode.ManagerRenderMode; + private ToolStripRenderer renderer = null; + private Type currentRendererType = typeof(System.Type); + private BitVector32 state = new BitVector32(); + + private ToolStripRenderMode defaultRenderMode = ToolStripRenderMode.ManagerRenderMode; - public ToolStripRendererSwitcher(Control owner, ToolStripRenderMode defaultRenderMode) : this(owner) { + public ToolStripRendererSwitcher(Control owner, ToolStripRenderMode defaultRenderMode) : this(owner) + { this.defaultRenderMode = defaultRenderMode; this.RenderMode = defaultRenderMode; } - - public ToolStripRendererSwitcher(Control owner) { + + public ToolStripRendererSwitcher(Control owner) + { state[stateUseDefaultRenderer] = true; state[stateAttachedRendererChanged] = false; owner.Disposed += new EventHandler(OnControlDisposed); owner.VisibleChanged += new EventHandler(OnControlVisibleChanged); - if (owner.Visible) { - OnControlVisibleChanged(owner, EventArgs.Empty); + if (owner.Visible) + { + OnControlVisibleChanged(owner, EventArgs.Empty); } } - public ToolStripRenderer Renderer { - get { - if (RenderMode == ToolStripRenderMode.ManagerRenderMode) { + public ToolStripRenderer Renderer + { + get + { + if (RenderMode == ToolStripRenderMode.ManagerRenderMode) + { return ToolStripManager.Renderer; } // always return a valid renderer so our paint code // doesn't have to be bogged down by checks for null. - + state[stateUseDefaultRenderer] = false; - if (renderer == null) { + if (renderer == null) + { Renderer = ToolStripManager.CreateRenderer(RenderMode); } return renderer; - + } - set { - // if the value happens to be null, the next get - // will autogenerate a new ToolStripRenderer. - if (renderer != value) { - state[stateUseDefaultRenderer] = (value == null); - renderer = value; - currentRendererType = (renderer != null) ? renderer.GetType() : typeof(System.Type); - - OnRendererChanged(EventArgs.Empty); - } + set + { + // if the value happens to be null, the next get + // will autogenerate a new ToolStripRenderer. + if (renderer != value) + { + state[stateUseDefaultRenderer] = (value == null); + renderer = value; + currentRendererType = (renderer != null) ? renderer.GetType() : typeof(System.Type); + + OnRendererChanged(EventArgs.Empty); + } } } - public ToolStripRenderMode RenderMode { - get { - if (state[stateUseDefaultRenderer]) { - return ToolStripRenderMode.ManagerRenderMode; + public ToolStripRenderMode RenderMode + { + get + { + if (state[stateUseDefaultRenderer]) + { + return ToolStripRenderMode.ManagerRenderMode; } - if (renderer != null && !renderer.IsAutoGenerated) { + if (renderer != null && !renderer.IsAutoGenerated) + { return ToolStripRenderMode.Custom; } // check the type of the currently set renderer. // types are cached as this may be called frequently. - if (currentRendererType == ToolStripManager.ProfessionalRendererType) { + if (currentRendererType == ToolStripManager.ProfessionalRendererType) + { return ToolStripRenderMode.Professional; } - if (currentRendererType == ToolStripManager.SystemRendererType) { + if (currentRendererType == ToolStripManager.SystemRendererType) + { return ToolStripRenderMode.System; } - return ToolStripRenderMode.Custom; - + return ToolStripRenderMode.Custom; + } - set { + set + { //valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripRenderMode.Custom, (int)ToolStripRenderMode.ManagerRenderMode)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripRenderMode)); } - if (value == ToolStripRenderMode.Custom) { + if (value == ToolStripRenderMode.Custom) + { throw new NotSupportedException(SR.ToolStripRenderModeUseRendererPropertyInstead); } - if (value == ToolStripRenderMode.ManagerRenderMode) { - if (!state[stateUseDefaultRenderer] ) { - state[stateUseDefaultRenderer] = true; + if (value == ToolStripRenderMode.ManagerRenderMode) + { + if (!state[stateUseDefaultRenderer]) + { + state[stateUseDefaultRenderer] = true; OnRendererChanged(EventArgs.Empty); } } - else { - state[stateUseDefaultRenderer] = false; - Renderer = ToolStripManager.CreateRenderer(value); + else + { + state[stateUseDefaultRenderer] = false; + Renderer = ToolStripManager.CreateRenderer(value); } } } - + public event EventHandler RendererChanged; - private void OnRendererChanged(EventArgs e) { - if (this.RendererChanged != null) { + private void OnRendererChanged(EventArgs e) + { + if (this.RendererChanged != null) + { this.RendererChanged(this, e); } } - private void OnDefaultRendererChanged(object sender, EventArgs e) { - if (state[stateUseDefaultRenderer]) { + private void OnDefaultRendererChanged(object sender, EventArgs e) + { + if (state[stateUseDefaultRenderer]) + { OnRendererChanged(e); } } - - private void OnControlDisposed(object sender, EventArgs e) { - if (state[stateAttachedRendererChanged]) { - ToolStripManager.RendererChanged -= new EventHandler(OnDefaultRendererChanged); - state[stateAttachedRendererChanged] = false; + + private void OnControlDisposed(object sender, EventArgs e) + { + if (state[stateAttachedRendererChanged]) + { + ToolStripManager.RendererChanged -= new EventHandler(OnDefaultRendererChanged); + state[stateAttachedRendererChanged] = false; } } - - private void OnControlVisibleChanged(object sender, EventArgs e) { + + private void OnControlVisibleChanged(object sender, EventArgs e) + { Control control = sender as Control; - if (control != null) { - if (control.Visible) { - if (!state[stateAttachedRendererChanged]) { - ToolStripManager.RendererChanged += new EventHandler(OnDefaultRendererChanged); - state[stateAttachedRendererChanged] = true; - } + if (control != null) + { + if (control.Visible) + { + if (!state[stateAttachedRendererChanged]) + { + ToolStripManager.RendererChanged += new EventHandler(OnDefaultRendererChanged); + state[stateAttachedRendererChanged] = true; + } } - else { - if (state[stateAttachedRendererChanged]) { - ToolStripManager.RendererChanged -= new EventHandler(OnDefaultRendererChanged); - state[stateAttachedRendererChanged] = false; - } + else + { + if (state[stateAttachedRendererChanged]) + { + ToolStripManager.RendererChanged -= new EventHandler(OnDefaultRendererChanged); + state[stateAttachedRendererChanged] = false; + } } } } - - public bool ShouldSerializeRenderMode() { + + public bool ShouldSerializeRenderMode() + { // We should NEVER serialize custom. return (RenderMode != defaultRenderMode && RenderMode != ToolStripRenderMode.Custom); } - public void ResetRenderMode() { + public void ResetRenderMode() + { this.RenderMode = defaultRenderMode; } - + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripScrollButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripScrollButton.cs index 5d1c5736abb..270d02f31a1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripScrollButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripScrollButton.cs @@ -2,19 +2,21 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Design; using System.Diagnostics; using System.Windows.Forms.ButtonInternal; - + /// /// A non selectable ToolStrip item /// - internal class ToolStripScrollButton : ToolStripControlHost { + internal class ToolStripScrollButton : ToolStripControlHost + { private bool up = true; [ThreadStatic] @@ -25,74 +27,94 @@ internal class ToolStripScrollButton : ToolStripControlHost { const int AUTOSCROLL_UPDATE = 50; private static readonly int AUTOSCROLL_PAUSE = SystemInformation.DoubleClickTime; - + private Timer mouseDownTimer; - - public ToolStripScrollButton(bool up) : base(CreateControlInstance(up)) { + + public ToolStripScrollButton(bool up) : base(CreateControlInstance(up)) + { this.up = up; } - - private static Control CreateControlInstance(bool up) { + + private static Control CreateControlInstance(bool up) + { StickyLabel label = new StickyLabel(); label.ImageAlign = ContentAlignment.MiddleCenter; label.Image = (up) ? UpImage : DownImage; return label; } - /// - /// 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. - /// - protected internal override Padding DefaultMargin { - get { - return Padding.Empty; - } - } - protected override Padding DefaultPadding { - get { - return Padding.Empty; - } - } - - private static Image DownImage { - get { - if (downScrollImage == null) { + /// + /// 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. + /// + protected internal override Padding DefaultMargin + { + get + { + return Padding.Empty; + } + } + protected override Padding DefaultPadding + { + get + { + return Padding.Empty; + } + } + + private static Image DownImage + { + get + { + if (downScrollImage == null) + { downScrollImage = DpiHelper.GetBitmapFromIcon(typeof(ToolStripScrollButton), "ScrollButtonDown"); } return downScrollImage; } } - - internal StickyLabel Label { - get{ + + internal StickyLabel Label + { + get + { return Control as StickyLabel; } } - - private static Image UpImage { - get { - if (upScrollImage == null) { + + private static Image UpImage + { + get + { + if (upScrollImage == null) + { upScrollImage = DpiHelper.GetBitmapFromIcon(typeof(ToolStripScrollButton), "ScrollButtonUp"); } return upScrollImage; } } - private Timer MouseDownTimer { - get{ - if (mouseDownTimer == null) { + private Timer MouseDownTimer + { + get + { + if (mouseDownTimer == null) + { mouseDownTimer = new Timer(); } return mouseDownTimer; } } - protected override void Dispose(bool disposing) { - if (disposing) { - if (mouseDownTimer != null) { + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (mouseDownTimer != null) + { mouseDownTimer.Enabled = false; mouseDownTimer.Dispose(); mouseDownTimer = null; @@ -100,84 +122,99 @@ protected override void Dispose(bool disposing) { } base.Dispose(disposing); } - protected override void OnMouseDown (MouseEventArgs e) { + protected override void OnMouseDown(MouseEventArgs e) + { UnsubscribeAll(); base.OnMouseDown(e); Scroll(); - - MouseDownTimer.Interval = AUTOSCROLL_PAUSE; + + MouseDownTimer.Interval = AUTOSCROLL_PAUSE; MouseDownTimer.Tick += new EventHandler(OnInitialAutoScrollMouseDown); MouseDownTimer.Enabled = true; } - protected override void OnMouseUp (MouseEventArgs e) { + protected override void OnMouseUp(MouseEventArgs e) + { UnsubscribeAll(); base.OnMouseUp(e); } - protected override void OnMouseLeave (EventArgs e) { + protected override void OnMouseLeave(EventArgs e) + { UnsubscribeAll(); } - private void UnsubscribeAll() { + private void UnsubscribeAll() + { MouseDownTimer.Enabled = false; MouseDownTimer.Tick -= new EventHandler(OnInitialAutoScrollMouseDown); MouseDownTimer.Tick -= new EventHandler(OnAutoScrollAccellerate); } - private void OnAutoScrollAccellerate(object sender, EventArgs e) { + private void OnAutoScrollAccellerate(object sender, EventArgs e) + { Scroll(); } - - private void OnInitialAutoScrollMouseDown(object sender, EventArgs e) { + + private void OnInitialAutoScrollMouseDown(object sender, EventArgs e) + { MouseDownTimer.Tick -= new EventHandler(OnInitialAutoScrollMouseDown); Scroll(); - MouseDownTimer.Interval = AUTOSCROLL_UPDATE; + MouseDownTimer.Interval = AUTOSCROLL_UPDATE; MouseDownTimer.Tick += new EventHandler(OnAutoScrollAccellerate); } - public override Size GetPreferredSize(Size constrainingSize) { + public override Size GetPreferredSize(Size constrainingSize) + { Size preferredSize = Size.Empty; preferredSize.Height = (Label.Image != null) ? Label.Image.Height + 4 : 0; preferredSize.Width = (ParentInternal != null) ? ParentInternal.Width - 2 : preferredSize.Width; // Two for border return preferredSize; } - private void Scroll() { + private void Scroll() + { ToolStripDropDownMenu parent = this.ParentInternal as ToolStripDropDownMenu; - if (parent != null && Label.Enabled) { + if (parent != null && Label.Enabled) + { parent.ScrollInternal(up); } } - internal class StickyLabel : Label { + internal class StickyLabel : Label + { - public StickyLabel() { + public StickyLabel() + { } private bool freezeLocationChange = false; - - public bool FreezeLocationChange { - get { return freezeLocationChange; } + + public bool FreezeLocationChange + { + get { return freezeLocationChange; } } - protected override void SetBoundsCore(int x,int y,int width, int height, BoundsSpecified specified) + protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { - if (((specified & BoundsSpecified.Location) != 0) && FreezeLocationChange) { + if (((specified & BoundsSpecified.Location) != 0) && FreezeLocationChange) + { return; } base.SetBoundsCore(x, y, width, height, specified); } - protected override void WndProc(ref Message m) { + protected override void WndProc(ref Message m) + { - if (m.Msg >= Interop.WindowMessages.WM_KEYFIRST && m.Msg <= Interop.WindowMessages.WM_KEYLAST) { + if (m.Msg >= Interop.WindowMessages.WM_KEYFIRST && m.Msg <= Interop.WindowMessages.WM_KEYLAST) + { // DefWndProc(ref m); return; } - + base.WndProc(ref m); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSeparator.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSeparator.cs index 9ed8f100567..1ea02da2a94 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSeparator.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSeparator.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Drawing; using System.ComponentModel; @@ -16,455 +17,552 @@ namespace System.Windows.Forms { /// /// [ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ToolStrip | ToolStripItemDesignerAvailability.ContextMenuStrip)] - public class ToolStripSeparator : ToolStripItem { - private const int ToolStrip_SEPARATORTHICKNESS = 6; - private const int ToolStrip_SEPARATORHEIGHT = 23; - - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] - public ToolStripSeparator() { - this.ForeColor = SystemColors.ControlDark; - } - - [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public new bool AutoToolTip { - get { - return base.AutoToolTip; - } - set { - base.AutoToolTip = value; - } - } - - - [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public override Image BackgroundImage { - get { - return base.BackgroundImage; - - } - set { - base.BackgroundImage = value; - } - } + public class ToolStripSeparator : ToolStripItem + { + private const int ToolStrip_SEPARATORTHICKNESS = 6; + private const int ToolStrip_SEPARATORHEIGHT = 23; + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] + public ToolStripSeparator() + { + this.ForeColor = SystemColors.ControlDark; + } - [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public override ImageLayout BackgroundImageLayout { - get { - return base.BackgroundImageLayout; - } - set { - base.BackgroundImageLayout = value; - } - } - - public override bool CanSelect { - get { - return DesignMode; - } - } - - - /// - /// 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. - /// - protected override Size DefaultSize { - get { - return new Size(ToolStrip_SEPARATORTHICKNESS, ToolStrip_SEPARATORTHICKNESS); - } + [ + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) + ] + public new bool AutoToolTip + { + get + { + return base.AutoToolTip; + } + set + { + base.AutoToolTip = value; } + } - protected internal override Padding DefaultMargin { - get { - return Padding.Empty; - } - } - - - [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public new bool DoubleClickEnabled { - get { - return base.DoubleClickEnabled; - } - set { - base.DoubleClickEnabled = value; - } - } - - [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public override bool Enabled { - get { - return base.Enabled; - } - set { - base.Enabled = value; - } + [ + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) + ] + public override Image BackgroundImage + { + get + { + return base.BackgroundImage; } + set + { + base.BackgroundImage = value; + } + } - [Browsable (false), EditorBrowsable (EditorBrowsableState.Never)] - new public event EventHandler EnabledChanged { - add => base.EnabledChanged += value; - remove => base.EnabledChanged -= value; + [ + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) + ] + public override ImageLayout BackgroundImageLayout + { + get + { + return base.BackgroundImageLayout; + } + set + { + base.BackgroundImageLayout = value; } + } - [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public new ToolStripItemDisplayStyle DisplayStyle { - get { - return base.DisplayStyle; - } - set { - base.DisplayStyle = value; - } + public override bool CanSelect + { + get + { + return DesignMode; } + } + - [Browsable (false), EditorBrowsable (EditorBrowsableState.Never)] - new public event EventHandler DisplayStyleChanged { - add => base.DisplayStyleChanged += value; - remove => base.DisplayStyleChanged -= value; + /// + /// 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. + /// + protected override Size DefaultSize + { + get + { + return new Size(ToolStrip_SEPARATORTHICKNESS, ToolStrip_SEPARATORTHICKNESS); } + } - [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public override Font Font { - get { - return base.Font; - } - set { - base.Font = value; - } + + protected internal override Padding DefaultMargin + { + get + { + return Padding.Empty; } + } - [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public new ContentAlignment ImageAlign { - get { - return base.ImageAlign; - } - set { - base.ImageAlign = value; - } + + [ + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) + ] + public new bool DoubleClickEnabled + { + get + { + return base.DoubleClickEnabled; } + set + { + base.DoubleClickEnabled = value; + } + } - [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public override Image Image { - - - get { - return base.Image; - } - set { - base.Image = value; - } + [ + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) + ] + public override bool Enabled + { + get + { + return base.Enabled; + } + set + { + base.Enabled = value; } - [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), - RefreshProperties(RefreshProperties.Repaint), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public new int ImageIndex { - get { - return base.ImageIndex; - } - set { - base.ImageIndex = value; - } + } + + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + new public event EventHandler EnabledChanged + { + add => base.EnabledChanged += value; + remove => base.EnabledChanged -= value; + } + + [ + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) + ] + public new ToolStripItemDisplayStyle DisplayStyle + { + get + { + return base.DisplayStyle; + } + set + { + base.DisplayStyle = value; } + } - [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public new string ImageKey { - get { - return base.ImageKey; - } - set { - base.ImageKey = value; - } - } - - [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public new Color ImageTransparentColor { - get { - return base.ImageTransparentColor; - } - set { - base.ImageTransparentColor = value; - } + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + new public event EventHandler DisplayStyleChanged + { + add => base.DisplayStyleChanged += value; + remove => base.DisplayStyleChanged -= value; + } + + [ + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) + ] + public override Font Font + { + get + { + return base.Font; + } + set + { + base.Font = value; } + } - [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public new ToolStripItemImageScaling ImageScaling { - get { - return base.ImageScaling; - } - set { - base.ImageScaling = value; - } + [ + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) + ] + public new ContentAlignment ImageAlign + { + get + { + return base.ImageAlign; + } + set + { + base.ImageAlign = value; } + } - - private bool IsVertical { - get { - ToolStrip parent = this.ParentInternal; - - if (parent == null) { - parent = Owner; - } - ToolStripDropDownMenu dropDownMenu = parent as ToolStripDropDownMenu; - if (dropDownMenu != null) { - return false; - } - switch (parent.LayoutStyle) { - case ToolStripLayoutStyle.VerticalStackWithOverflow: - return false; - case ToolStripLayoutStyle.HorizontalStackWithOverflow: - case ToolStripLayoutStyle.Flow: - case ToolStripLayoutStyle.Table: - default: - return true; - } - } + [ + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) + ] + public override Image Image + { + + + get + { + return base.Image; } - - - [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public override string Text { - get { - return base.Text; - } - set { - base.Text = value; - } - } - - [Browsable (false), EditorBrowsable (EditorBrowsableState.Never)] - new public event EventHandler TextChanged { - add => base.TextChanged += value; - remove => base.TextChanged -= value; - } - - [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public new ContentAlignment TextAlign { - get { - return base.TextAlign; - } - set { - base.TextAlign = value; - } - } - - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DefaultValue(ToolStripTextDirection.Horizontal)] - public override ToolStripTextDirection TextDirection { - get { - return base.TextDirection; - } - set { - base.TextDirection = value; - } - } - - [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public new TextImageRelation TextImageRelation { - get { - return base.TextImageRelation; - } - set { - base.TextImageRelation = value; - } - } - - [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public new string ToolTipText { - get { - return base.ToolTipText; - } - set { - base.ToolTipText = value; - } + set + { + base.Image = value; } - - [ - Browsable(false), - EditorBrowsable(EditorBrowsableState.Never), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public new bool RightToLeftAutoMirrorImage { - get { - return base.RightToLeftAutoMirrorImage; - } - set { - base.RightToLeftAutoMirrorImage = value; - } + } + + [ + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), + RefreshProperties(RefreshProperties.Repaint), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) + ] + public new int ImageIndex + { + get + { + return base.ImageIndex; + } + set + { + base.ImageIndex = value; } + } - [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override AccessibleObject CreateAccessibilityInstance() { - return new ToolStripSeparatorAccessibleObject(this); + [ + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) + ] + public new string ImageKey + { + get + { + return base.ImageKey; + } + set + { + base.ImageKey = value; } + } + [ + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) + ] + public new Color ImageTransparentColor + { + get + { + return base.ImageTransparentColor; + } + set + { + base.ImageTransparentColor = value; + } + } + + [ + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) + ] + public new ToolStripItemImageScaling ImageScaling + { + get + { + return base.ImageScaling; + } + set + { + base.ImageScaling = value; + } + } - public override Size GetPreferredSize(Size constrainingSize) { + + private bool IsVertical + { + get + { ToolStrip parent = this.ParentInternal; - if (parent == null) { + if (parent == null) + { parent = Owner; } - if (parent == null) { - return new Size(ToolStrip_SEPARATORTHICKNESS, ToolStrip_SEPARATORTHICKNESS); - } - ToolStripDropDownMenu dropDownMenu = parent as ToolStripDropDownMenu; - if (dropDownMenu != null) { - return new Size(parent.Width - (parent.Padding.Horizontal - dropDownMenu.ImageMargin.Width), ToolStrip_SEPARATORTHICKNESS); + if (dropDownMenu != null) + { + return false; } - else { - if (parent.LayoutStyle != ToolStripLayoutStyle.HorizontalStackWithOverflow || parent.LayoutStyle != ToolStripLayoutStyle.VerticalStackWithOverflow) { - // we dont actually know what size to make it, so just keep it a stock size. - constrainingSize.Width = ToolStrip_SEPARATORHEIGHT; - constrainingSize.Height = ToolStrip_SEPARATORHEIGHT; - } - if (IsVertical) { - return new Size(ToolStrip_SEPARATORTHICKNESS, constrainingSize.Height); - } - else { - return new Size(constrainingSize.Width, ToolStrip_SEPARATORTHICKNESS); - } + switch (parent.LayoutStyle) + { + case ToolStripLayoutStyle.VerticalStackWithOverflow: + return false; + case ToolStripLayoutStyle.HorizontalStackWithOverflow: + case ToolStripLayoutStyle.Flow: + case ToolStripLayoutStyle.Table: + default: + return true; } - } + } - - protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { - if (this.Owner != null && this.ParentInternal != null) { - this.Renderer.DrawSeparator(new ToolStripSeparatorRenderEventArgs(e.Graphics, this, IsVertical)); - } + + [ + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) + ] + public override string Text + { + get + { + return base.Text; + } + set + { + base.Text = value; } + } - [EditorBrowsable(EditorBrowsableState.Never)] - protected override void OnFontChanged(EventArgs e) { - // PERF: dont call base, we dont care if the font changes - RaiseEvent(EventFontChanged, e); + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + new public event EventHandler TextChanged + { + add => base.TextChanged += value; + remove => base.TextChanged -= value; + } + + [ + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) + ] + public new ContentAlignment TextAlign + { + get + { + return base.TextAlign; + } + set + { + base.TextAlign = value; + } + } + + + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DefaultValue(ToolStripTextDirection.Horizontal)] + public override ToolStripTextDirection TextDirection + { + get + { + return base.TextDirection; + } + set + { + base.TextDirection = value; } + } + + [ + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) + ] + public new TextImageRelation TextImageRelation + { + get + { + return base.TextImageRelation; + } + set + { + base.TextImageRelation = value; + } + } + + [ + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) + ] + public new string ToolTipText + { + get + { + return base.ToolTipText; + } + set + { + base.ToolTipText = value; + } + } - [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] - [EditorBrowsable(EditorBrowsableState.Never)] - internal override bool ShouldSerializeForeColor() { - return (ForeColor != SystemColors.ControlDark); + [ + Browsable(false), + EditorBrowsable(EditorBrowsableState.Never), + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) + ] + public new bool RightToLeftAutoMirrorImage + { + get + { + return base.RightToLeftAutoMirrorImage; + } + set + { + base.RightToLeftAutoMirrorImage = value; } + } + + [EditorBrowsable(EditorBrowsableState.Advanced)] + protected override AccessibleObject CreateAccessibilityInstance() + { + return new ToolStripSeparatorAccessibleObject(this); + } + - internal protected override void SetBounds(Rectangle rect) { + public override Size GetPreferredSize(Size constrainingSize) + { + ToolStrip parent = this.ParentInternal; - ToolStripDropDownMenu dropDownMenu = this.Owner as ToolStripDropDownMenu; - if (dropDownMenu != null) { - - // Scooch over by the padding amount. The padding is added to - // the ToolStripDropDownMenu to keep the non-menu item riffraff - // aligned to the text rectangle. When flow layout comes through to set our position - // via IArrangedElement DEFY IT! - if (dropDownMenu != null) { - rect.X = 2; - rect.Width = dropDownMenu.Width -4; - } + if (parent == null) + { + parent = Owner; + } + if (parent == null) + { + return new Size(ToolStrip_SEPARATORTHICKNESS, ToolStrip_SEPARATORTHICKNESS); + } + + ToolStripDropDownMenu dropDownMenu = parent as ToolStripDropDownMenu; + if (dropDownMenu != null) + { + return new Size(parent.Width - (parent.Padding.Horizontal - dropDownMenu.ImageMargin.Width), ToolStrip_SEPARATORTHICKNESS); + } + else + { + if (parent.LayoutStyle != ToolStripLayoutStyle.HorizontalStackWithOverflow || parent.LayoutStyle != ToolStripLayoutStyle.VerticalStackWithOverflow) + { + // we dont actually know what size to make it, so just keep it a stock size. + constrainingSize.Width = ToolStrip_SEPARATORHEIGHT; + constrainingSize.Height = ToolStrip_SEPARATORHEIGHT; } - base.SetBounds(rect); - } - - /// - /// An implementation of AccessibleChild for use with ToolStripItems - /// - [System.Runtime.InteropServices.ComVisible(true)] - internal class ToolStripSeparatorAccessibleObject : ToolStripItemAccessibleObject { - private ToolStripSeparator ownerItem = null; - - public ToolStripSeparatorAccessibleObject(ToolStripSeparator ownerItem): base(ownerItem) { - this.ownerItem = ownerItem; + if (IsVertical) + { + return new Size(ToolStrip_SEPARATORTHICKNESS, constrainingSize.Height); } + else + { + return new Size(constrainingSize.Width, ToolStrip_SEPARATORTHICKNESS); + } + } - public override AccessibleRole Role { - get { - AccessibleRole role = ownerItem.AccessibleRole; - if (role != AccessibleRole.Default) { - return role; - } - else { - return AccessibleRole.Separator; - } + } - } + + protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) + { + if (this.Owner != null && this.ParentInternal != null) + { + this.Renderer.DrawSeparator(new ToolStripSeparatorRenderEventArgs(e.Graphics, this, IsVertical)); + } + } + + [EditorBrowsable(EditorBrowsableState.Never)] + protected override void OnFontChanged(EventArgs e) + { + // PERF: dont call base, we dont care if the font changes + RaiseEvent(EventFontChanged, e); + } + + [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] + [EditorBrowsable(EditorBrowsableState.Never)] + internal override bool ShouldSerializeForeColor() + { + return (ForeColor != SystemColors.ControlDark); + } + + internal protected override void SetBounds(Rectangle rect) + { + + ToolStripDropDownMenu dropDownMenu = this.Owner as ToolStripDropDownMenu; + if (dropDownMenu != null) + { + + // Scooch over by the padding amount. The padding is added to + // the ToolStripDropDownMenu to keep the non-menu item riffraff + // aligned to the text rectangle. When flow layout comes through to set our position + // via IArrangedElement DEFY IT! + if (dropDownMenu != null) + { + rect.X = 2; + rect.Width = dropDownMenu.Width - 4; } + } + base.SetBounds(rect); + } - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_ControlTypePropertyId) { - return NativeMethods.UIA_SeparatorControlTypeId; + /// + /// An implementation of AccessibleChild for use with ToolStripItems + /// + [System.Runtime.InteropServices.ComVisible(true)] + internal class ToolStripSeparatorAccessibleObject : ToolStripItemAccessibleObject + { + private ToolStripSeparator ownerItem = null; + + public ToolStripSeparatorAccessibleObject(ToolStripSeparator ownerItem) : base(ownerItem) + { + this.ownerItem = ownerItem; + } + + public override AccessibleRole Role + { + get + { + AccessibleRole role = ownerItem.AccessibleRole; + if (role != AccessibleRole.Default) + { + return role; + } + else + { + return AccessibleRole.Separator; } - return base.GetPropertyValue(propertyID); } } + + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_ControlTypePropertyId) + { + return NativeMethods.UIA_SeparatorControlTypeId; + } + + return base.GetPropertyValue(propertyID); + } } - } + } +} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSettings.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSettings.cs index f6cd12c552e..a62481b78a7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSettings.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSettings.cs @@ -2,13 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Diagnostics; - using System.Diagnostics.CodeAnalysis; + using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Text; using System.Text.RegularExpressions; @@ -16,86 +17,109 @@ namespace System.Windows.Forms { /// /// A settings class used by the ToolStripManager to save toolstrip settings. /// - internal class ToolStripSettings : ApplicationSettingsBase { + internal class ToolStripSettings : ApplicationSettingsBase + { + + internal ToolStripSettings(string settingsKey) : base(settingsKey) { } - internal ToolStripSettings(string settingsKey) : base(settingsKey) {} - [UserScopedSetting] [DefaultSettingValue("true")] - public bool IsDefault { - get { - return (bool) this["IsDefault"]; + public bool IsDefault + { + get + { + return (bool)this["IsDefault"]; } - set { + set + { this["IsDefault"] = value; } } - + [UserScopedSetting] - public string ItemOrder { - get { + public string ItemOrder + { + get + { return this["ItemOrder"] as string; } - set { + set + { this["ItemOrder"] = value; } } - + [UserScopedSetting] - public string Name { - get { + public string Name + { + get + { return this["Name"] as string; } - set { + set + { this["Name"] = value; } } [UserScopedSetting] [DefaultSettingValue("0,0")] - public Point Location { - get { - return (Point) this["Location"]; + public Point Location + { + get + { + return (Point)this["Location"]; } - set { + set + { this["Location"] = value; } } [UserScopedSetting] [DefaultSettingValue("0,0")] - public Size Size { - get { - return (Size) this["Size"]; + public Size Size + { + get + { + return (Size)this["Size"]; } - set { + set + { this["Size"] = value; } } [UserScopedSetting] - public string ToolStripPanelName { - get { + public string ToolStripPanelName + { + get + { return this["ToolStripPanelName"] as string; } - set { + set + { this["ToolStripPanelName"] = value; } } - + [UserScopedSetting] [DefaultSettingValue("true")] - public bool Visible { - get { - return (bool) this["Visible"]; + public bool Visible + { + get + { + return (bool)this["Visible"]; } - set { + set + { this["Visible"] = value; } } - - - public override void Save() { + + + public override void Save() + { this.IsDefault = false; base.Save(); } @@ -105,24 +129,30 @@ public override void Save() { /// Helper class used by ToolStripManager that implements most of the logic to save out and apply /// settings for toolstrips on a form. /// - internal class ToolStripSettingsManager { + internal class ToolStripSettingsManager + { private Form form; private string formKey; - - internal ToolStripSettingsManager(Form owner, string formKey) { + + internal ToolStripSettingsManager(Form owner, string formKey) + { this.form = owner; this.formKey = formKey; } - internal void Load() { + internal void Load() + { ArrayList savedToolStripSettingsObjects = new ArrayList(); - foreach (ToolStrip toolStrip in FindToolStrips(true, form.Controls)) { - if (toolStrip != null && !string.IsNullOrEmpty(toolStrip.Name)) { + foreach (ToolStrip toolStrip in FindToolStrips(true, form.Controls)) + { + if (toolStrip != null && !string.IsNullOrEmpty(toolStrip.Name)) + { ToolStripSettings toolStripSettings = new ToolStripSettings(GetSettingsKey(toolStrip)); - + // Check if we have settings saved out for this toolstrip. If so, add it to our apply list. - if (!toolStripSettings.IsDefault) { + if (!toolStripSettings.IsDefault) + { savedToolStripSettingsObjects.Add(new SettingsStub(toolStripSettings)); } } @@ -130,10 +160,13 @@ internal void Load() { ApplySettings(savedToolStripSettingsObjects); } - - internal void Save() { - foreach (ToolStrip toolStrip in FindToolStrips(true, form.Controls)) { - if (toolStrip != null && !string.IsNullOrEmpty(toolStrip.Name)) { + + internal void Save() + { + foreach (ToolStrip toolStrip in FindToolStrips(true, form.Controls)) + { + if (toolStrip != null && !string.IsNullOrEmpty(toolStrip.Name)) + { ToolStripSettings toolStripSettings = new ToolStripSettings(GetSettingsKey(toolStrip)); SettingsStub stub = new SettingsStub(toolStrip); @@ -143,83 +176,100 @@ internal void Save() { toolStripSettings.Size = stub.Size; toolStripSettings.ToolStripPanelName = stub.ToolStripPanelName; toolStripSettings.Visible = stub.Visible; - + toolStripSettings.Save(); } } } - internal static string GetItemOrder(ToolStrip toolStrip) { + internal static string GetItemOrder(ToolStrip toolStrip) + { StringBuilder itemNames = new StringBuilder(toolStrip.Items.Count); - for (int i = 0; i < toolStrip.Items.Count; i++) { + for (int i = 0; i < toolStrip.Items.Count; i++) + { itemNames.Append((toolStrip.Items[i].Name == null) ? "null" : toolStrip.Items[i].Name); - if (i != toolStrip.Items.Count - 1) { + if (i != toolStrip.Items.Count - 1) + { itemNames.Append(','); } } return itemNames.ToString(); } - private void ApplySettings(ArrayList toolStripSettingsToApply) { - if (toolStripSettingsToApply.Count == 0) { + private void ApplySettings(ArrayList toolStripSettingsToApply) + { + if (toolStripSettingsToApply.Count == 0) + { return; } SuspendAllLayout(form); - - + + // iterate through all the toolstrips and build up a hash of where the items // are right now. Dictionary itemLocationHash = BuildItemOriginationHash(); - + // build up a hash of where we want the ToolStrips to go Dictionary> toolStripPanelDestinationHash = new Dictionary>(); - - foreach (SettingsStub toolStripSettings in toolStripSettingsToApply) { + + foreach (SettingsStub toolStripSettings in toolStripSettingsToApply) + { object destinationPanel = !string.IsNullOrEmpty(toolStripSettings.ToolStripPanelName) ? toolStripSettings.ToolStripPanelName : null; - if (destinationPanel == null) { + if (destinationPanel == null) + { // Not in a panel. - if (!string.IsNullOrEmpty(toolStripSettings.Name)) { + if (!string.IsNullOrEmpty(toolStripSettings.Name)) + { // apply the toolstrip settings. ToolStrip toolStrip = ToolStripManager.FindToolStrip(form, toolStripSettings.Name); ApplyToolStripSettings(toolStrip, toolStripSettings, itemLocationHash); } } - else { + else + { // This toolStrip is in a ToolStripPanel. We will process it below. - if (!toolStripPanelDestinationHash.ContainsKey(destinationPanel)) { + if (!toolStripPanelDestinationHash.ContainsKey(destinationPanel)) + { toolStripPanelDestinationHash[destinationPanel] = new List(); } - + toolStripPanelDestinationHash[destinationPanel].Add(toolStripSettings); } } - + // build up a list of the toolstrippanels to party on ArrayList toolStripPanels = FindToolStripPanels(true, form.Controls); - - foreach (ToolStripPanel toolStripPanel in toolStripPanels) { + + foreach (ToolStripPanel toolStripPanel in toolStripPanels) + { // set all the controls to visible false/ - foreach (Control c in toolStripPanel.Controls) { + foreach (Control c in toolStripPanel.Controls) + { c.Visible = false; } - + string toolStripPanelName = toolStripPanel.Name; // Handle the ToolStripPanels inside a ToolStripContainer - if (string.IsNullOrEmpty(toolStripPanelName) && toolStripPanel.Parent is ToolStripContainer && !string.IsNullOrEmpty(toolStripPanel.Parent.Name)) { + if (string.IsNullOrEmpty(toolStripPanelName) && toolStripPanel.Parent is ToolStripContainer && !string.IsNullOrEmpty(toolStripPanel.Parent.Name)) + { toolStripPanelName = toolStripPanel.Parent.Name + "." + toolStripPanel.Dock.ToString(); } toolStripPanel.BeginInit(); // get the associated toolstrips for this panel - if (toolStripPanelDestinationHash.ContainsKey(toolStripPanelName)) { + if (toolStripPanelDestinationHash.ContainsKey(toolStripPanelName)) + { List stubSettings = toolStripPanelDestinationHash[toolStripPanelName]; - - if (stubSettings != null) { - foreach (SettingsStub settings in stubSettings) { - if (!string.IsNullOrEmpty(settings.Name)) { + + if (stubSettings != null) + { + foreach (SettingsStub settings in stubSettings) + { + if (!string.IsNullOrEmpty(settings.Name)) + { // apply the toolstrip settings. ToolStrip toolStrip = ToolStripManager.FindToolStrip(form, settings.Name); ApplyToolStripSettings(toolStrip, settings, itemLocationHash); @@ -234,23 +284,29 @@ private void ApplySettings(ArrayList toolStripSettingsToApply) { ResumeAllLayout(form, true); } - private void ApplyToolStripSettings(ToolStrip toolStrip, SettingsStub settings, Dictionary itemLocationHash) { - if (toolStrip != null) { + private void ApplyToolStripSettings(ToolStrip toolStrip, SettingsStub settings, Dictionary itemLocationHash) + { + if (toolStrip != null) + { toolStrip.Visible = settings.Visible; toolStrip.Size = settings.Size; - + // Apply the item order changes. string itemNames = settings.ItemOrder; - if (!string.IsNullOrEmpty(itemNames)) { + if (!string.IsNullOrEmpty(itemNames)) + { string[] keys = itemNames.Split(','); Regex r = new Regex("(\\S+)"); - + // Shuffle items according to string. - for (int i = 0; ((i < toolStrip.Items.Count) && (i < keys.Length)); i++) { + for (int i = 0; ((i < toolStrip.Items.Count) && (i < keys.Length)); i++) + { Match match = r.Match(keys[i]); - if (match != null && match.Success) { + if (match != null && match.Success) + { string key = match.Value; - if (!string.IsNullOrEmpty(key) && itemLocationHash.ContainsKey(key)) { + if (!string.IsNullOrEmpty(key) && itemLocationHash.ContainsKey(key)) + { toolStrip.Items.Insert(i, itemLocationHash[key].Items[key]); } } @@ -259,99 +315,124 @@ private void ApplyToolStripSettings(ToolStrip toolStrip, SettingsStub settings, } } - private Dictionary BuildItemOriginationHash() { - ArrayList toolStrips = FindToolStrips(true, form.Controls); - Dictionary itemLocationHash = new Dictionary(); - - if (toolStrips != null) { - foreach (ToolStrip toolStrip in toolStrips) { - foreach (ToolStripItem item in toolStrip.Items) { - if (!string.IsNullOrEmpty(item.Name)) { - Debug.Assert(!itemLocationHash.ContainsKey(item.Name), "WARNING: ToolStripItem name not unique."); - itemLocationHash[item.Name] = toolStrip; - } - } - } - } - - return itemLocationHash; + private Dictionary BuildItemOriginationHash() + { + ArrayList toolStrips = FindToolStrips(true, form.Controls); + Dictionary itemLocationHash = new Dictionary(); + + if (toolStrips != null) + { + foreach (ToolStrip toolStrip in toolStrips) + { + foreach (ToolStripItem item in toolStrip.Items) + { + if (!string.IsNullOrEmpty(item.Name)) + { + Debug.Assert(!itemLocationHash.ContainsKey(item.Name), "WARNING: ToolStripItem name not unique."); + itemLocationHash[item.Name] = toolStrip; + } + } + } + } + + return itemLocationHash; } [ SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes") ] - private ArrayList FindControls(Type baseType, bool searchAllChildren, Control.ControlCollection controlsToLookIn, ArrayList foundControls) { - if ((controlsToLookIn == null) || (foundControls == null)) { + private ArrayList FindControls(Type baseType, bool searchAllChildren, Control.ControlCollection controlsToLookIn, ArrayList foundControls) + { + if ((controlsToLookIn == null) || (foundControls == null)) + { return null; } - - try { + + try + { // Perform breadth first search - as it's likely people will want controls belonging // to the same parent close to each other. - - for (int i = 0; i < controlsToLookIn.Count; i++) { - if (controlsToLookIn[i] == null) { + + for (int i = 0; i < controlsToLookIn.Count; i++) + { + if (controlsToLookIn[i] == null) + { continue; } - - if (baseType.IsAssignableFrom(controlsToLookIn[i].GetType())) { + + if (baseType.IsAssignableFrom(controlsToLookIn[i].GetType())) + { foundControls.Add(controlsToLookIn[i]); } } - + // Optional recurive search for controls in child collections. - - if (searchAllChildren) { - for (int i = 0; i < controlsToLookIn.Count; i++) { - if (controlsToLookIn[i] == null || controlsToLookIn[i] is Form) { + + if (searchAllChildren) + { + for (int i = 0; i < controlsToLookIn.Count; i++) + { + if (controlsToLookIn[i] == null || controlsToLookIn[i] is Form) + { continue; } - if ((controlsToLookIn[i].Controls != null) && controlsToLookIn[i].Controls.Count > 0) { + if ((controlsToLookIn[i].Controls != null) && controlsToLookIn[i].Controls.Count > 0) + { // if it has a valid child collecion, append those results to our collection foundControls = FindControls(baseType, searchAllChildren, controlsToLookIn[i].Controls, foundControls); } } } } - catch (Exception e) { - if (ClientUtils.IsCriticalException(e)) { + catch (Exception e) + { + if (ClientUtils.IsCriticalException(e)) + { throw; } } return foundControls; } - private ArrayList FindToolStripPanels(bool searchAllChildren, Control.ControlCollection controlsToLookIn) { + private ArrayList FindToolStripPanels(bool searchAllChildren, Control.ControlCollection controlsToLookIn) + { return FindControls(typeof(ToolStripPanel), true, form.Controls, new ArrayList()); } - - private ArrayList FindToolStrips(bool searchAllChildren, Control.ControlCollection controlsToLookIn) { + + private ArrayList FindToolStrips(bool searchAllChildren, Control.ControlCollection controlsToLookIn) + { return FindControls(typeof(ToolStrip), true, form.Controls, new ArrayList()); } - - private string GetSettingsKey(ToolStrip toolStrip) { - if (toolStrip != null) { + + private string GetSettingsKey(ToolStrip toolStrip) + { + if (toolStrip != null) + { return formKey + "." + toolStrip.Name; } return string.Empty; } - private void ResumeAllLayout(Control start, bool performLayout) { + private void ResumeAllLayout(Control start, bool performLayout) + { Control.ControlCollection controlsCollection = start.Controls; - - for (int i = 0; i < controlsCollection.Count; i++) { + + for (int i = 0; i < controlsCollection.Count; i++) + { ResumeAllLayout(controlsCollection[i], performLayout); } - + start.ResumeLayout(performLayout); } - - private void SuspendAllLayout(Control start) { + + private void SuspendAllLayout(Control start) + { start.SuspendLayout(); - + Control.ControlCollection controlsCollection = start.Controls; - for (int i = 0; i < controlsCollection.Count; i++) { + for (int i = 0; i < controlsCollection.Count; i++) + { SuspendAllLayout(controlsCollection[i]); } } @@ -359,23 +440,28 @@ private void SuspendAllLayout(Control start) { /// /// Light weight structure that captures the properties we want to save as settings. /// - private struct SettingsStub { - public bool Visible; - public string ToolStripPanelName; - public Point Location; - public Size Size; - public string ItemOrder; - public string Name; - - public SettingsStub(ToolStrip toolStrip) { + private struct SettingsStub + { + public bool Visible; + public string ToolStripPanelName; + public Point Location; + public Size Size; + public string ItemOrder; + public string Name; + + public SettingsStub(ToolStrip toolStrip) + { this.ToolStripPanelName = string.Empty; ToolStripPanel parentPanel = toolStrip.Parent as ToolStripPanel; - if (parentPanel != null) { - if (!string.IsNullOrEmpty(parentPanel.Name)) { + if (parentPanel != null) + { + if (!string.IsNullOrEmpty(parentPanel.Name)) + { this.ToolStripPanelName = parentPanel.Name; } - else if (parentPanel.Parent is ToolStripContainer && !string.IsNullOrEmpty(parentPanel.Parent.Name)) { + else if (parentPanel.Parent is ToolStripContainer && !string.IsNullOrEmpty(parentPanel.Parent.Name)) + { // Handle the case when the ToolStripPanel belongs to a ToolStripContainer. this.ToolStripPanelName = parentPanel.Parent.Name + "." + parentPanel.Dock.ToString(); } @@ -388,9 +474,10 @@ public SettingsStub(ToolStrip toolStrip) { this.Location = toolStrip.Location; this.Name = toolStrip.Name; this.ItemOrder = GetItemOrder(toolStrip); - + } - public SettingsStub(ToolStripSettings toolStripSettings) { + public SettingsStub(ToolStripSettings toolStripSettings) + { this.ToolStripPanelName = toolStripSettings.ToolStripPanelName; this.Visible = toolStripSettings.Visible; this.Size = toolStripSettings.Size; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs index dce444086a5..2ebc2e7e22e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs @@ -2,78 +2,90 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Drawing; using System.Windows.Forms; using System.Drawing.Imaging; using System.ComponentModel; - using System.Windows.Forms.Design; + using System.Windows.Forms.Design; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Diagnostics; using System.Windows.Forms.Layout; using System.Runtime.Versioning; - + /// [ ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ToolStrip | ToolStripItemDesignerAvailability.StatusStrip), DefaultEvent(nameof(ButtonClick)) ] - public class ToolStripSplitButton : ToolStripDropDownItem { - - private ToolStripItem defaultItem = null; - private ToolStripSplitButtonButton splitButtonButton = null; - private Rectangle dropDownButtonBounds = Rectangle.Empty; - private ToolStripSplitButtonButtonLayout splitButtonButtonLayout = null; - private int dropDownButtonWidth = 0; - private int splitterWidth = 1; - private Rectangle splitterBounds = Rectangle.Empty; - private byte openMouseId = 0; + public class ToolStripSplitButton : ToolStripDropDownItem + { + + private ToolStripItem defaultItem = null; + private ToolStripSplitButtonButton splitButtonButton = null; + private Rectangle dropDownButtonBounds = Rectangle.Empty; + private ToolStripSplitButtonButtonLayout splitButtonButtonLayout = null; + private int dropDownButtonWidth = 0; + private int splitterWidth = 1; + private Rectangle splitterBounds = Rectangle.Empty; + private byte openMouseId = 0; private long lastClickTime = 0; private const int DEFAULT_DROPDOWN_WIDTH = 11; - private static readonly object EventDefaultItemChanged = new object(); - private static readonly object EventButtonClick = new object(); - private static readonly object EventButtonDoubleClick = new object(); - private static readonly object EventDropDownOpened = new object(); - private static readonly object EventDropDownClosed = new object(); + private static readonly object EventDefaultItemChanged = new object(); + private static readonly object EventButtonClick = new object(); + private static readonly object EventButtonDoubleClick = new object(); + private static readonly object EventDropDownOpened = new object(); + private static readonly object EventDropDownClosed = new object(); private static bool isScalingInitialized = false; private static int scaledDropDownButtonWidth = DEFAULT_DROPDOWN_WIDTH; - + /// /// Summary of ToolStripSplitButton. /// - public ToolStripSplitButton() { + public ToolStripSplitButton() + { Initialize(); // all additional work should be done in Initialize } - public ToolStripSplitButton(string text):base(text,null,(EventHandler)null) { - Initialize(); + public ToolStripSplitButton(string text) : base(text, null, (EventHandler)null) + { + Initialize(); } - public ToolStripSplitButton(Image image):base(null,image,(EventHandler)null) { - Initialize(); + public ToolStripSplitButton(Image image) : base(null, image, (EventHandler)null) + { + Initialize(); } - public ToolStripSplitButton(string text, Image image):base(text,image,(EventHandler)null) { - Initialize(); + public ToolStripSplitButton(string text, Image image) : base(text, image, (EventHandler)null) + { + Initialize(); } - public ToolStripSplitButton(string text, Image image, EventHandler onClick):base(text,image,onClick) { - Initialize(); + public ToolStripSplitButton(string text, Image image, EventHandler onClick) : base(text, image, onClick) + { + Initialize(); } - public ToolStripSplitButton(string text, Image image, EventHandler onClick, string name) :base(text,image,onClick,name){ - Initialize(); + public ToolStripSplitButton(string text, Image image, EventHandler onClick, string name) : base(text, image, onClick, name) + { + Initialize(); } - public ToolStripSplitButton(string text, Image image, params ToolStripItem[] dropDownItems):base(text,image,dropDownItems) { - Initialize(); + public ToolStripSplitButton(string text, Image image, params ToolStripItem[] dropDownItems) : base(text, image, dropDownItems) + { + Initialize(); } [DefaultValue(true)] - public new bool AutoToolTip { - get { + public new bool AutoToolTip + { + get + { return base.AutoToolTip; } - set { + set + { base.AutoToolTip = value; } } @@ -83,8 +95,10 @@ public ToolStripSplitButton(string text, Image image, params ToolStripItem[] dro /// Summary of ToolStripSplitButton. /// [Browsable(false)] - public Rectangle ButtonBounds { - get { + public Rectangle ButtonBounds + { + get + { //Rectangle bounds = SplitButtonButton.Bounds; //bounds.Offset(this.Bounds.Location); return SplitButtonButton.Bounds; @@ -95,8 +109,10 @@ public Rectangle ButtonBounds { /// Summary of ButtonPressed. /// [Browsable(false)] - public bool ButtonPressed { - get { + public bool ButtonPressed + { + get + { return SplitButtonButton.Pressed; } @@ -106,8 +122,10 @@ public bool ButtonPressed { /// Summary of ButtonPressed. /// [Browsable(false)] - public bool ButtonSelected { - get { + public bool ButtonSelected + { + get + { return SplitButtonButton.Selected || DropDownButtonPressed; } } @@ -119,8 +137,9 @@ public bool ButtonSelected { SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ToolStripSplitButtonOnButtonClickDescr)) ] - public event EventHandler ButtonClick { - add => Events.AddHandler(EventButtonClick, value); + public event EventHandler ButtonClick + { + add => Events.AddHandler(EventButtonClick, value); remove => Events.RemoveHandler(EventButtonClick, value); } /// @@ -130,15 +149,18 @@ public event EventHandler ButtonClick { SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ToolStripSplitButtonOnButtonDoubleClickDescr)) ] - public event EventHandler ButtonDoubleClick { + public event EventHandler ButtonDoubleClick + { add => Events.AddHandler(EventButtonDoubleClick, value); remove => Events.RemoveHandler(EventButtonDoubleClick, value); } - protected override bool DefaultAutoToolTip { - get { - return true; + protected override bool DefaultAutoToolTip + { + get + { + return true; } } @@ -146,18 +168,22 @@ protected override bool DefaultAutoToolTip { /// Summary of DefaultItem. /// [DefaultValue(null), Browsable(false)] - public ToolStripItem DefaultItem { - get { - return defaultItem; + public ToolStripItem DefaultItem + { + get + { + return defaultItem; } - set { - if (defaultItem != value) { - OnDefaultItemChanged(EventArgs.Empty); - defaultItem = value; + set + { + if (defaultItem != value) + { + OnDefaultItemChanged(EventArgs.Empty); + defaultItem = value; } } } - + /// /// Occurs when the default item has changed @@ -166,32 +192,38 @@ public ToolStripItem DefaultItem { SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ToolStripSplitButtonOnDefaultItemChangedDescr)) ] - public event EventHandler DefaultItemChanged { - add => Events.AddHandler(EventDefaultItemChanged, value); + public event EventHandler DefaultItemChanged + { + add => Events.AddHandler(EventDefaultItemChanged, value); remove => Events.RemoveHandler(EventDefaultItemChanged, value); } - + /// /// specifies the default behavior of these items on ToolStripDropDowns when clicked. /// - internal protected override bool DismissWhenClicked { - get { + internal protected override bool DismissWhenClicked + { + get + { return DropDown.Visible != true; } } - - internal override Rectangle DropDownButtonArea { - get { return this.DropDownButtonBounds; } + + internal override Rectangle DropDownButtonArea + { + get { return this.DropDownButtonBounds; } } /// /// The bounds of the DropDown in ToolStrip coordinates. /// [Browsable(false)] - public Rectangle DropDownButtonBounds { - get { - return dropDownButtonBounds; + public Rectangle DropDownButtonBounds + { + get + { + return dropDownButtonBounds; } } @@ -199,19 +231,23 @@ public Rectangle DropDownButtonBounds { /// Summary of DropDownButtonBounds. /// [Browsable(false)] - public bool DropDownButtonPressed { - get { + public bool DropDownButtonPressed + { + get + { // - return DropDown.Visible; + return DropDown.Visible; } } /// /// Summary of DropDownButtonSelected. /// [Browsable(false)] - public bool DropDownButtonSelected{ - get { - return this.Selected; + public bool DropDownButtonSelected + { + get + { + return this.Selected; } } /// @@ -221,34 +257,43 @@ public bool DropDownButtonSelected{ SRCategory(nameof(SR.CatLayout)), SRDescription(nameof(SR.ToolStripSplitButtonDropDownButtonWidthDescr)) ] - public int DropDownButtonWidth { - get{ + public int DropDownButtonWidth + { + get + { return dropDownButtonWidth; } - set { - if (value < 0) { + set + { + if (value < 0) + { // throw if less than 0. - throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(DropDownButtonWidth), value, 0)); + throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(DropDownButtonWidth), value, 0)); } - - if (dropDownButtonWidth != value) { + + if (dropDownButtonWidth != value) + { dropDownButtonWidth = value; InvalidateSplitButtonLayout(); InvalidateItemLayout(PropertyNames.DropDownButtonWidth, true); } - } + } } /// /// This is here for serialization purposes. /// - private int DefaultDropDownButtonWidth { - get { + private int DefaultDropDownButtonWidth + { + get + { // lets start off with a size roughly equivalent to a combobox dropdown - if (!isScalingInitialized) { - if (DpiHelper.IsScalingRequired) { + if (!isScalingInitialized) + { + if (DpiHelper.IsScalingRequired) + { scaledDropDownButtonWidth = DpiHelper.LogicalToDeviceUnitsX(DEFAULT_DROPDOWN_WIDTH); - } + } isScalingInitialized = true; } @@ -256,14 +301,17 @@ private int DefaultDropDownButtonWidth { } } - - + + /// /// Just used as a convenience to help manage layout /// - private ToolStripSplitButtonButton SplitButtonButton { - get { - if (splitButtonButton == null) { + private ToolStripSplitButtonButton SplitButtonButton + { + get + { + if (splitButtonButton == null) + { splitButtonButton = new ToolStripSplitButtonButton(this); } splitButtonButton.Image = this.Image; @@ -280,13 +328,16 @@ private ToolStripSplitButtonButton SplitButtonButton { /// /// Summary of SplitButtonButtonLayout. /// - internal ToolStripItemInternalLayout SplitButtonButtonLayout { - get { + internal ToolStripItemInternalLayout SplitButtonButtonLayout + { + get + { // For preferred size caching reasons, we need to keep our two // internal layouts (button, dropdown button) in sync. - + if (InternalLayout != null /*if layout is invalid - calls CreateInternalLayout - which resets splitButtonButtonLayout to null*/ - && splitButtonButtonLayout == null) { + && splitButtonButtonLayout == null) + { splitButtonButtonLayout = new ToolStripSplitButtonButtonLayout(this); } return splitButtonButtonLayout; @@ -302,15 +353,20 @@ internal ToolStripItemInternalLayout SplitButtonButtonLayout { Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced) ] - internal int SplitterWidth { - get { + internal int SplitterWidth + { + get + { return splitterWidth; } - set { - if (value < 0) { + set + { + if (value < 0) + { splitterWidth = 0; } - else { + else + { splitterWidth = value; } InvalidateSplitButtonLayout(); @@ -321,23 +377,26 @@ internal int SplitterWidth { /// painting purposes. /// [Browsable(false)] - public Rectangle SplitterBounds { - get { + public Rectangle SplitterBounds + { + get + { return splitterBounds; } } /// /// Summary of CalculateLayout. /// - private void CalculateLayout() { + private void CalculateLayout() + { // Figure out where the DropDown image goes. Rectangle dropDownButtonBounds = new Rectangle(Point.Empty, this.Size); Rectangle splitButtonButtonBounds = Rectangle.Empty; - - + + dropDownButtonBounds = new Rectangle(Point.Empty, new Size(Math.Min(this.Width, DropDownButtonWidth), this.Height)); - + // Figure out the height and width of the selected item. int splitButtonButtonWidth = Math.Max(0, this.Width - dropDownButtonBounds.Width); int splitButtonButtonHeight = Math.Max(0, this.Height); @@ -345,43 +404,49 @@ private void CalculateLayout() { splitButtonButtonBounds = new Rectangle(Point.Empty, new Size(splitButtonButtonWidth, splitButtonButtonHeight)); // grow the selected item by one since we're overlapping the borders. - splitButtonButtonBounds.Width -= splitterWidth; + splitButtonButtonBounds.Width -= splitterWidth; - if (this.RightToLeft == RightToLeft.No) { + if (this.RightToLeft == RightToLeft.No) + { // the dropdown button goes on the right - dropDownButtonBounds.Offset(splitButtonButtonBounds.Right+splitterWidth, 0); + dropDownButtonBounds.Offset(splitButtonButtonBounds.Right + splitterWidth, 0); splitterBounds = new Rectangle(splitButtonButtonBounds.Right, splitButtonButtonBounds.Top, splitterWidth, splitButtonButtonBounds.Height); } - else { + else + { // the split button goes on the right. - splitButtonButtonBounds.Offset(DropDownButtonWidth+splitterWidth, 0); + splitButtonButtonBounds.Offset(DropDownButtonWidth + splitterWidth, 0); splitterBounds = new Rectangle(dropDownButtonBounds.Right, dropDownButtonBounds.Top, splitterWidth, dropDownButtonBounds.Height); - + } - + this.SplitButtonButton.SetBounds(splitButtonButtonBounds); this.SetDropDownButtonBounds(dropDownButtonBounds); } - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new ToolStripSplitButtonUiaProvider(this); } - protected override ToolStripDropDown CreateDefaultDropDown() { - // AutoGenerate a ToolStrip DropDown - set the property so we hook events - return new ToolStripDropDownMenu(this, /*isAutoGenerated=*/true); - } + protected override ToolStripDropDown CreateDefaultDropDown() + { + // AutoGenerate a ToolStrip DropDown - set the property so we hook events + return new ToolStripDropDownMenu(this, /*isAutoGenerated=*/true); + } - internal override ToolStripItemInternalLayout CreateInternalLayout() { + internal override ToolStripItemInternalLayout CreateInternalLayout() + { // whenever the master layout is invalidated - invalidate the splitbuttonbutton layout. this.splitButtonButtonLayout = null; return new ToolStripItemInternalLayout(this); - + } - public override Size GetPreferredSize(Size constrainingSize) { + public override Size GetPreferredSize(Size constrainingSize) + { Size preferredSize = SplitButtonButtonLayout.GetPreferredSize(constrainingSize); preferredSize.Width += DropDownButtonWidth + SplitterWidth + Padding.Horizontal; return preferredSize; @@ -390,124 +455,151 @@ public override Size GetPreferredSize(Size constrainingSize) { /// /// Summary of InvalidateSplitButtonLayout. /// - private void InvalidateSplitButtonLayout() { - this.splitButtonButtonLayout = null; + private void InvalidateSplitButtonLayout() + { + this.splitButtonButtonLayout = null; CalculateLayout(); } - private void Initialize() { + private void Initialize() + { dropDownButtonWidth = DefaultDropDownButtonWidth; SupportsSpaceKey = true; } - protected internal override bool ProcessDialogKey(Keys keyData) { - if (Enabled && (keyData == Keys.Enter || (SupportsSpaceKey && keyData == Keys.Space))) { - PerformButtonClick(); - return true; + protected internal override bool ProcessDialogKey(Keys keyData) + { + if (Enabled && (keyData == Keys.Enter || (SupportsSpaceKey && keyData == Keys.Space))) + { + PerformButtonClick(); + return true; } - + return base.ProcessDialogKey(keyData); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] // 'charCode' matches control.cs - protected internal override bool ProcessMnemonic(char charCode) { - // checking IsMnemonic is not necessary - toolstrip does this for us - PerformButtonClick(); - return true; + protected internal override bool ProcessMnemonic(char charCode) + { + // checking IsMnemonic is not necessary - toolstrip does this for us + PerformButtonClick(); + return true; } /// /// called when the button portion of a split button is clicked /// if there is a default item, this will route the click to the default item /// - protected virtual void OnButtonClick(System.EventArgs e) { - - if (DefaultItem != null) { + protected virtual void OnButtonClick(System.EventArgs e) + { + + if (DefaultItem != null) + { DefaultItem.FireEvent(ToolStripItemEventType.Click); } EventHandler handler = (EventHandler)Events[EventButtonClick]; - if (handler != null) handler(this, e); - + if (handler != null) + handler(this, e); + } - + /// /// called when the button portion of a split button is double clicked /// if there is a default item, this will route the double click to the default item /// - public virtual void OnButtonDoubleClick(System.EventArgs e) { - if (DefaultItem != null) { + public virtual void OnButtonDoubleClick(System.EventArgs e) + { + if (DefaultItem != null) + { DefaultItem.FireEvent(ToolStripItemEventType.DoubleClick); } - + EventHandler handler = (EventHandler)Events[EventButtonDoubleClick]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// /// Inheriting classes should override this method to handle this event. /// - protected virtual void OnDefaultItemChanged(EventArgs e) { + protected virtual void OnDefaultItemChanged(EventArgs e) + { InvalidateSplitButtonLayout(); - if (CanRaiseEvents) { + if (CanRaiseEvents) + { EventHandler eh = Events[EventDefaultItemChanged] as EventHandler; - if (eh != null) { + if (eh != null) + { eh(this, e); } } - } + } /// /// Summary of OnMouseDown. /// - protected override void OnMouseDown(MouseEventArgs e) { - - if (DropDownButtonBounds.Contains(e.Location)) { - if (e.Button == MouseButtons.Left) { - - if (!DropDown.Visible) { + protected override void OnMouseDown(MouseEventArgs e) + { + + if (DropDownButtonBounds.Contains(e.Location)) + { + if (e.Button == MouseButtons.Left) + { + + if (!DropDown.Visible) + { Debug.Assert(ParentInternal != null, "Parent is null here, not going to get accurate ID"); - openMouseId = (ParentInternal == null) ? (byte)0: ParentInternal.GetMouseId(); + openMouseId = (ParentInternal == null) ? (byte)0 : ParentInternal.GetMouseId(); this.ShowDropDown(/*mousePress = */true); } } } - else { + else + { SplitButtonButton.Push(true); } } - - + + /// /// Summary of OnMouseUp. /// - protected override void OnMouseUp(MouseEventArgs e) { - if (!Enabled) { + protected override void OnMouseUp(MouseEventArgs e) + { + if (!Enabled) + { return; } - + SplitButtonButton.Push(false); - - if (DropDownButtonBounds.Contains(e.Location)) { - if (e.Button == MouseButtons.Left) { - if (DropDown.Visible) { + + if (DropDownButtonBounds.Contains(e.Location)) + { + if (e.Button == MouseButtons.Left) + { + if (DropDown.Visible) + { Debug.Assert(ParentInternal != null, "Parent is null here, not going to get accurate ID"); - byte closeMouseId = (ParentInternal == null) ? (byte)0: ParentInternal.GetMouseId(); - if (closeMouseId != openMouseId) { + byte closeMouseId = (ParentInternal == null) ? (byte)0 : ParentInternal.GetMouseId(); + if (closeMouseId != openMouseId) + { openMouseId = 0; // reset the mouse id, we should never get this value from toolstrip. ToolStripManager.ModalMenuFilter.CloseActiveDropDown(DropDown, ToolStripDropDownCloseReason.AppClicked); Select(); - } + } } } } Point clickPoint = new Point(e.X, e.Y); - if ((e.Button == MouseButtons.Left) && this.SplitButtonButton.Bounds.Contains(clickPoint)) { + if ((e.Button == MouseButtons.Left) && this.SplitButtonButton.Bounds.Contains(clickPoint)) + { bool shouldFireDoubleClick = false; - if (DoubleClickEnabled) { + if (DoubleClickEnabled) + { long newTime = DateTime.Now.Ticks; long deltaTicks = newTime - lastClickTime; lastClickTime = newTime; @@ -515,59 +607,70 @@ protected override void OnMouseUp(MouseEventArgs e) { // DateTime resolution. Debug.Assert(deltaTicks >= 0, "why are deltaticks less than zero? thats some mighty fast clicking"); // if we've seen a mouse up less than the double click time ago, we should fire. - if (deltaTicks >= 0 && deltaTicks < DoubleClickTicks) { + if (deltaTicks >= 0 && deltaTicks < DoubleClickTicks) + { shouldFireDoubleClick = true; } } - if (shouldFireDoubleClick) { + if (shouldFireDoubleClick) + { OnButtonDoubleClick(EventArgs.Empty); // If we actually fired DoubleClick - reset the lastClickTime. lastClickTime = 0; - } - else { + } + else + { OnButtonClick(EventArgs.Empty); - } + } } } - protected override void OnMouseLeave(EventArgs e) { + protected override void OnMouseLeave(EventArgs e) + { openMouseId = 0; // reset the mouse id, we should never get this value from toolstrip. SplitButtonButton.Push(false); base.OnMouseLeave(e); } - + /// /// Summary of OnRightToLeftChanged. /// - protected override void OnRightToLeftChanged(EventArgs e) { + protected override void OnRightToLeftChanged(EventArgs e) + { base.OnRightToLeftChanged(e); - InvalidateSplitButtonLayout(); + InvalidateSplitButtonLayout(); } /// /// Summary of OnPaint. /// /// - protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { + protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) + { - ToolStripRenderer renderer = this.Renderer; - if (renderer != null) { - InvalidateSplitButtonLayout(); - Graphics g = e.Graphics; + ToolStripRenderer renderer = this.Renderer; + if (renderer != null) + { + InvalidateSplitButtonLayout(); + Graphics g = e.Graphics; - renderer.DrawSplitButton(new ToolStripItemRenderEventArgs(g, this)); + renderer.DrawSplitButton(new ToolStripItemRenderEventArgs(g, this)); - if ((DisplayStyle & ToolStripItemDisplayStyle.Image) != ToolStripItemDisplayStyle.None) { - renderer.DrawItemImage(new ToolStripItemImageRenderEventArgs(g, this, SplitButtonButtonLayout.ImageRectangle)); - } + if ((DisplayStyle & ToolStripItemDisplayStyle.Image) != ToolStripItemDisplayStyle.None) + { + renderer.DrawItemImage(new ToolStripItemImageRenderEventArgs(g, this, SplitButtonButtonLayout.ImageRectangle)); + } - if ((DisplayStyle & ToolStripItemDisplayStyle.Text) != ToolStripItemDisplayStyle.None) { - renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, SplitButtonButton.Text, SplitButtonButtonLayout.TextRectangle, this.ForeColor, this.Font, SplitButtonButtonLayout.TextFormat)); - } - } - } + if ((DisplayStyle & ToolStripItemDisplayStyle.Text) != ToolStripItemDisplayStyle.None) + { + renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, SplitButtonButton.Text, SplitButtonButtonLayout.TextRectangle, this.ForeColor, this.Font, SplitButtonButtonLayout.TextFormat)); + } + } + } - public void PerformButtonClick() { - if (Enabled && Available) { + public void PerformButtonClick() + { + if (Enabled && Available) + { PerformClick(); OnButtonClick(EventArgs.Empty); } @@ -577,24 +680,27 @@ public void PerformButtonClick() { /// Resets the RightToLeft to be the default. /// [EditorBrowsable(EditorBrowsableState.Never)] - public virtual void ResetDropDownButtonWidth() { + public virtual void ResetDropDownButtonWidth() + { DropDownButtonWidth = DefaultDropDownButtonWidth; } /// /// Summary of SetDropDownBounds. /// - private void SetDropDownButtonBounds(Rectangle rect) { - dropDownButtonBounds = rect; + private void SetDropDownButtonBounds(Rectangle rect) + { + dropDownButtonBounds = rect; } /// /// Determines if the property needs to be persisted. /// [EditorBrowsable(EditorBrowsableState.Never)] - internal virtual bool ShouldSerializeDropDownButtonWidth() { - return (DropDownButtonWidth != DefaultDropDownButtonWidth); + internal virtual bool ShouldSerializeDropDownButtonWidth() + { + return (DropDownButtonWidth != DefaultDropDownButtonWidth); } - + /// /// This class represents the item to the left of the dropdown [ A |v] (e.g the "A") /// It exists so that we can use our existing methods for text and image layout @@ -603,86 +709,112 @@ internal virtual bool ShouldSerializeDropDownButtonWidth() { /// like MouseOver, wont be laid out by the ToolStrip, etc etc. This is purely internal /// convenience. /// - private class ToolStripSplitButtonButton : ToolStripButton { + private class ToolStripSplitButtonButton : ToolStripButton + { private ToolStripSplitButton owner = null; - public ToolStripSplitButtonButton(ToolStripSplitButton owner) { - this.owner = owner; + public ToolStripSplitButtonButton(ToolStripSplitButton owner) + { + this.owner = owner; } - public override bool Enabled { - get { + public override bool Enabled + { + get + { return owner.Enabled; } - set { + set + { // do nothing } } - - public override ToolStripItemDisplayStyle DisplayStyle { - get { + + public override ToolStripItemDisplayStyle DisplayStyle + { + get + { return owner.DisplayStyle; } - set { + set + { // do nothing } } - public override Padding Padding { - get { + public override Padding Padding + { + get + { return this.owner.Padding; } - set { + set + { // do nothing } } - - public override ToolStripTextDirection TextDirection { - get { + + public override ToolStripTextDirection TextDirection + { + get + { return owner.TextDirection; } } - - - public override Image Image { - - - get { - if ((owner.DisplayStyle & ToolStripItemDisplayStyle.Image) == ToolStripItemDisplayStyle.Image) { + + + public override Image Image + { + + + get + { + if ((owner.DisplayStyle & ToolStripItemDisplayStyle.Image) == ToolStripItemDisplayStyle.Image) + { return owner.Image; } - else { + else + { return null; } } - set { + set + { // do nothing } } - public override bool Selected { - get { - - if (owner != null) { + public override bool Selected + { + get + { + + if (owner != null) + { return owner.Selected; } return base.Selected; } } - public override string Text { - get { - if ((owner.DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) { + public override string Text + { + get + { + if ((owner.DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) + { return owner.Text; } - else { + else + { return null; } } - set { + set + { // do nothing } } @@ -694,109 +826,139 @@ public override string Text { /// Its main job is to make sure the inner button has the same parent as the split button, so /// that layout can be performed using the correct graphics context. /// - private class ToolStripSplitButtonButtonLayout : ToolStripItemInternalLayout { + private class ToolStripSplitButtonButtonLayout : ToolStripItemInternalLayout + { ToolStripSplitButton owner; - public ToolStripSplitButtonButtonLayout(ToolStripSplitButton owner) : base(owner.SplitButtonButton) { + public ToolStripSplitButtonButtonLayout(ToolStripSplitButton owner) : base(owner.SplitButtonButton) + { this.owner = owner; } - protected override ToolStripItem Owner { + protected override ToolStripItem Owner + { get { return owner; } } - protected override ToolStrip ParentInternal { - get { + protected override ToolStrip ParentInternal + { + get + { return owner.ParentInternal; } } - public override Rectangle ImageRectangle { - get { + public override Rectangle ImageRectangle + { + get + { Rectangle imageRect = base.ImageRectangle; // translate to ToolStripItem coordinates imageRect.Offset(owner.SplitButtonButton.Bounds.Location); - return imageRect; + return imageRect; } } - - public override Rectangle TextRectangle { - get { + + public override Rectangle TextRectangle + { + get + { Rectangle textRect = base.TextRectangle; // translate to ToolStripItem coordinates textRect.Offset(owner.SplitButtonButton.Bounds.Location); - return textRect; + return textRect; } } } [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - public class ToolStripSplitButtonAccessibleObject : ToolStripItem.ToolStripItemAccessibleObject { + public class ToolStripSplitButtonAccessibleObject : ToolStripItem.ToolStripItemAccessibleObject + { private ToolStripSplitButton owner; - public ToolStripSplitButtonAccessibleObject(ToolStripSplitButton item) : base(item) { + public ToolStripSplitButtonAccessibleObject(ToolStripSplitButton item) : base(item) + { owner = item; } - public override void DoDefaultAction() { + public override void DoDefaultAction() + { owner.PerformButtonClick(); } } - internal class ToolStripSplitButtonExAccessibleObject: ToolStripSplitButtonAccessibleObject { + internal class ToolStripSplitButtonExAccessibleObject : ToolStripSplitButtonAccessibleObject + { private ToolStripSplitButton ownerItem; public ToolStripSplitButtonExAccessibleObject(ToolStripSplitButton item) - : base(item) { + : base(item) + { ownerItem = item; } - internal override object GetPropertyValue(int propertyID) { - if (propertyID == NativeMethods.UIA_ControlTypePropertyId) { + internal override object GetPropertyValue(int propertyID) + { + if (propertyID == NativeMethods.UIA_ControlTypePropertyId) + { return NativeMethods.UIA_ButtonControlTypeId; } - else { + else + { return base.GetPropertyValue(propertyID); } } - internal override bool IsIAccessibleExSupported() { - if (ownerItem != null) { + internal override bool IsIAccessibleExSupported() + { + if (ownerItem != null) + { return true; } - else { + else + { return base.IsIAccessibleExSupported(); } } - internal override bool IsPatternSupported(int patternId) { - if (patternId == NativeMethods.UIA_ExpandCollapsePatternId && ownerItem.HasDropDownItems) { + internal override bool IsPatternSupported(int patternId) + { + if (patternId == NativeMethods.UIA_ExpandCollapsePatternId && ownerItem.HasDropDownItems) + { return true; } - else { + else + { return base.IsPatternSupported(patternId); } } - internal override void Expand() { + internal override void Expand() + { DoDefaultAction(); } - internal override void Collapse() { - if (ownerItem != null && ownerItem.DropDown != null && ownerItem.DropDown.Visible) { + internal override void Collapse() + { + if (ownerItem != null && ownerItem.DropDown != null && ownerItem.DropDown.Visible) + { ownerItem.DropDown.Close(); } } - internal override UnsafeNativeMethods.ExpandCollapseState ExpandCollapseState { - get { + internal override UnsafeNativeMethods.ExpandCollapseState ExpandCollapseState + { + get + { return ownerItem.DropDown.Visible ? UnsafeNativeMethods.ExpandCollapseState.Expanded : UnsafeNativeMethods.ExpandCollapseState.Collapsed; } } - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - switch (direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { + switch (direction) + { case UnsafeNativeMethods.NavigateDirection.FirstChild: return DropDownItemsCount > 0 ? ownerItem.DropDown.Items[0].AccessibilityObject : null; case UnsafeNativeMethods.NavigateDirection.LastChild: @@ -805,12 +967,15 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga return base.FragmentNavigate(direction); } - private int DropDownItemsCount { - get { + private int DropDownItemsCount + { + get + { // Do not expose child items when the drop-down is collapsed to prevent Narrator from announcing // invisible menu items when Narrator is in item's mode (CAPSLOCK + Arrow Left/Right) or // in scan mode (CAPSLOCK + Space) - if (ExpandCollapseState == UnsafeNativeMethods.ExpandCollapseState.Collapsed) { + if (ExpandCollapseState == UnsafeNativeMethods.ExpandCollapseState.Collapsed) + { return 0; } @@ -819,44 +984,54 @@ private int DropDownItemsCount { } } - internal class ToolStripSplitButtonUiaProvider : ToolStripDropDownItemAccessibleObject { + internal class ToolStripSplitButtonUiaProvider : ToolStripDropDownItemAccessibleObject + { private ToolStripSplitButton _owner; private ToolStripSplitButtonExAccessibleObject _accessibleObject; - public ToolStripSplitButtonUiaProvider(ToolStripSplitButton owner) : base(owner) { + public ToolStripSplitButtonUiaProvider(ToolStripSplitButton owner) : base(owner) + { _owner = owner; _accessibleObject = new ToolStripSplitButtonExAccessibleObject(owner); } - public override void DoDefaultAction() { + public override void DoDefaultAction() + { _accessibleObject.DoDefaultAction(); } - internal override object GetPropertyValue(int propertyID) { + internal override object GetPropertyValue(int propertyID) + { return _accessibleObject.GetPropertyValue(propertyID); } internal override bool IsIAccessibleExSupported() => true; - internal override bool IsPatternSupported(int patternId) { + internal override bool IsPatternSupported(int patternId) + { return _accessibleObject.IsPatternSupported(patternId); } - internal override void Expand() { + internal override void Expand() + { DoDefaultAction(); } - internal override void Collapse() { + internal override void Collapse() + { _accessibleObject.Collapse(); } - internal override UnsafeNativeMethods.ExpandCollapseState ExpandCollapseState { - get { + internal override UnsafeNativeMethods.ExpandCollapseState ExpandCollapseState + { + get + { return _accessibleObject.ExpandCollapseState; } } - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { return _accessibleObject.FragmentNavigate(direction); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitStackLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitStackLayout.cs index 347eb3fb343..c4b9eed244d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitStackLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitStackLayout.cs @@ -2,14 +2,16 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Windows.Forms.Layout; using System.Drawing; using System.Diagnostics; using System.Globalization; - internal class ToolStripSplitStackLayout : LayoutEngine { + internal class ToolStripSplitStackLayout : LayoutEngine + { private int backwardsWalkingIndex; private int forwardsWalkingIndex; private ToolStrip toolStrip; @@ -19,40 +21,50 @@ internal class ToolStripSplitStackLayout : LayoutEngine { private Rectangle displayRectangle = Rectangle.Empty; #if DEBUG - internal static readonly TraceSwitch DebugLayoutTraceSwitch = new TraceSwitch("DebugLayout", "Debug ToolStrip Layout code"); + internal static readonly TraceSwitch DebugLayoutTraceSwitch = new TraceSwitch("DebugLayout", "Debug ToolStrip Layout code"); #else internal static readonly TraceSwitch DebugLayoutTraceSwitch; #endif - internal ToolStripSplitStackLayout(ToolStrip owner) { + internal ToolStripSplitStackLayout(ToolStrip owner) + { this.toolStrip = owner; } - + // this is the index we use to send items to the overflow // if we run out of room - protected int BackwardsWalkingIndex { - get { + protected int BackwardsWalkingIndex + { + get + { return backwardsWalkingIndex; } - set { + set + { backwardsWalkingIndex = value; } } // this is the index we use to walk the items and make // decisions if there is enough room. - protected int ForwardsWalkingIndex { - get { + protected int ForwardsWalkingIndex + { + get + { return forwardsWalkingIndex; } - set { + set + { forwardsWalkingIndex = value; } } - private Size OverflowButtonSize { - get { + private Size OverflowButtonSize + { + get + { ToolStrip toolStrip = this.ToolStrip; - if (!toolStrip.CanOverflow) { + if (!toolStrip.CanOverflow) + { return Size.Empty; } @@ -63,27 +75,35 @@ private Size OverflowButtonSize { } } - private int OverflowSpace { - get { + private int OverflowSpace + { + get + { return overflowSpace; } - set { + set + { overflowSpace = value; } } - private bool OverflowRequired { - get { + private bool OverflowRequired + { + get + { return overflowRequired; } - set { + set + { overflowRequired = value; } } // the current ToolStrip we're operating over. - public ToolStrip ToolStrip { - get { + public ToolStrip ToolStrip + { + get + { return toolStrip; } } @@ -91,31 +111,38 @@ public ToolStrip ToolStrip { // // This method will mark whether items should be placed in the overflow or on the main ToolStrip. // - private void CalculatePlacementsHorizontal() { + private void CalculatePlacementsHorizontal() + { ResetItemPlacements(); ToolStrip toolStrip = this.ToolStrip; int currentWidth = 0; //toolStrip.Padding.Horizontal; - if (ToolStrip.CanOverflow) { + if (ToolStrip.CanOverflow) + { // determine the locations of all the items. - for (ForwardsWalkingIndex = 0; ForwardsWalkingIndex < toolStrip.Items.Count; ForwardsWalkingIndex++) { + for (ForwardsWalkingIndex = 0; ForwardsWalkingIndex < toolStrip.Items.Count; ForwardsWalkingIndex++) + { ToolStripItem item = toolStrip.Items[ForwardsWalkingIndex]; - if (!((IArrangedElement)item).ParticipatesInLayout) { + if (!((IArrangedElement)item).ParticipatesInLayout) + { // skip over items not participating in layout. E.G. not visible items continue; } // if we have something set to overflow always we need to show an overflow button - if (item.Overflow == ToolStripItemOverflow.Always) { + if (item.Overflow == ToolStripItemOverflow.Always) + { #if DEBUG - if (DebugLayoutTraceSwitch.TraceVerbose) { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "OverflowRequired - item set to alaways overflow: {0} ", item)); } + if (DebugLayoutTraceSwitch.TraceVerbose) + { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "OverflowRequired - item set to alaways overflow: {0} ", item)); } #endif OverflowRequired = true; } - if (item.Overflow != ToolStripItemOverflow.Always && item.Placement == ToolStripItemPlacement.None) { + if (item.Overflow != ToolStripItemOverflow.Always && item.Placement == ToolStripItemPlacement.None) + { // since we havent parented the item yet - the auto size wont have reset the size yet. Size itemSize = item.AutoSize ? item.GetPreferredSize(this.displayRectangle.Size) : item.Size; @@ -123,9 +150,11 @@ private void CalculatePlacementsHorizontal() { int overflowWidth = (OverflowRequired) ? OverflowButtonSize.Width : 0; - if (currentWidth > displayRectangle.Width - overflowWidth) { + if (currentWidth > displayRectangle.Width - overflowWidth) + { #if DEBUG - if (DebugLayoutTraceSwitch.TraceVerbose) { Debug.WriteLine("SendNextItemToOverflow to fres space for " + item.ToString()); } + if (DebugLayoutTraceSwitch.TraceVerbose) + { Debug.WriteLine("SendNextItemToOverflow to fres space for " + item.ToString()); } #endif int spaceRecovered = SendNextItemToOverflow((currentWidth + overflowWidth) - displayRectangle.Width, true); @@ -141,42 +170,52 @@ private void CalculatePlacementsHorizontal() { // // This method will mark whether items should be placed in the overflow or on the main ToolStrip. // - private void CalculatePlacementsVertical() { + private void CalculatePlacementsVertical() + { ResetItemPlacements(); ToolStrip toolStrip = this.ToolStrip; int currentHeight = 0; //toolStrip.Padding.Vertical; - if (ToolStrip.CanOverflow) { + if (ToolStrip.CanOverflow) + { // determine the locations of all the items. - for (ForwardsWalkingIndex = 0; ForwardsWalkingIndex < ToolStrip.Items.Count; ForwardsWalkingIndex++) { + for (ForwardsWalkingIndex = 0; ForwardsWalkingIndex < ToolStrip.Items.Count; ForwardsWalkingIndex++) + { ToolStripItem item = toolStrip.Items[ForwardsWalkingIndex]; - if (!((IArrangedElement)item).ParticipatesInLayout) { + if (!((IArrangedElement)item).ParticipatesInLayout) + { // skip over items not participating in layout. E.G. not visible items continue; } // if we have something set to overflow always we need to show an overflow button - if (item.Overflow == ToolStripItemOverflow.Always) { + if (item.Overflow == ToolStripItemOverflow.Always) + { OverflowRequired = true; #if DEBUG - if (DebugLayoutTraceSwitch.TraceVerbose) Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "OverflowRequired - item set to always overflow: {0} ", item)); -#endif + if (DebugLayoutTraceSwitch.TraceVerbose) + Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "OverflowRequired - item set to always overflow: {0} ", item)); +#endif } - if (item.Overflow != ToolStripItemOverflow.Always && item.Placement == ToolStripItemPlacement.None) { + if (item.Overflow != ToolStripItemOverflow.Always && item.Placement == ToolStripItemPlacement.None) + { // since we havent parented the item yet - the auto size wont have reset the size yet. Size itemSize = item.AutoSize ? item.GetPreferredSize(displayRectangle.Size) : item.Size; int overflowWidth = (OverflowRequired) ? OverflowButtonSize.Height : 0; currentHeight += itemSize.Height + item.Margin.Vertical; #if DEBUG - if (DebugLayoutTraceSwitch.TraceVerbose) { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Adding {0} Size {1} to currentHeight = {2}", item.ToString(), itemSize, currentHeight)); } + if (DebugLayoutTraceSwitch.TraceVerbose) + { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Adding {0} Size {1} to currentHeight = {2}", item.ToString(), itemSize, currentHeight)); } #endif - if (currentHeight > displayRectangle.Height - overflowWidth) { + if (currentHeight > displayRectangle.Height - overflowWidth) + { #if DEBUG - if (DebugLayoutTraceSwitch.TraceVerbose) { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Got to {0} and realized that currentHeight = {1} is larger than displayRect {2} minus overflow {3}", item.ToString(), currentHeight, displayRectangle, overflowWidth)); } + if (DebugLayoutTraceSwitch.TraceVerbose) + { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Got to {0} and realized that currentHeight = {1} is larger than displayRect {2} minus overflow {3}", item.ToString(), currentHeight, displayRectangle, overflowWidth)); } #endif int spaceRecovered = SendNextItemToOverflow(currentHeight - displayRectangle.Height, false); @@ -189,35 +228,42 @@ private void CalculatePlacementsVertical() { PlaceItems(); } - internal override Size GetPreferredSize(IArrangedElement container, Size proposedConstraints) { + internal override Size GetPreferredSize(IArrangedElement container, Size proposedConstraints) + { // undone be more clever here - perhaps figure out the biggest element and return that. - if (!(container is ToolStrip)) { + if (!(container is ToolStrip)) + { throw new NotSupportedException(SR.ToolStripSplitStackLayoutContainerMustBeAToolStrip); } - if (toolStrip.LayoutStyle == ToolStripLayoutStyle.HorizontalStackWithOverflow) { + if (toolStrip.LayoutStyle == ToolStripLayoutStyle.HorizontalStackWithOverflow) + { return ToolStrip.GetPreferredSizeHorizontal(container, proposedConstraints); } - else { + else + { return ToolStrip.GetPreferredSizeVertical(container, proposedConstraints); } } - + // each time we perform a complete layout this stuff should be re-initialized - private void InvalidateLayout() { + private void InvalidateLayout() + { forwardsWalkingIndex = 0; backwardsWalkingIndex = -1; overflowSpace = 0; overflowRequired = false; displayRectangle = Rectangle.Empty; } - + // this is part of the LayoutEngine - called when we need to do a layout. - internal override bool LayoutCore(IArrangedElement container, LayoutEventArgs layoutEventArgs) { - if (!(container is ToolStrip)) { + internal override bool LayoutCore(IArrangedElement container, LayoutEventArgs layoutEventArgs) + { + if (!(container is ToolStrip)) + { throw new NotSupportedException(SR.ToolStripSplitStackLayoutContainerMustBeAToolStrip); } @@ -230,21 +276,25 @@ internal override bool LayoutCore(IArrangedElement container, LayoutEventArgs la noMansLand.X += toolStrip.ClientSize.Width + 1; noMansLand.Y += toolStrip.ClientSize.Height + 1; - if (toolStrip.LayoutStyle == ToolStripLayoutStyle.HorizontalStackWithOverflow) { + if (toolStrip.LayoutStyle == ToolStripLayoutStyle.HorizontalStackWithOverflow) + { LayoutHorizontal(); } - else { + else + { LayoutVertical(); } - return CommonProperties.GetAutoSize(container); + return CommonProperties.GetAutoSize(container); } - private bool LayoutHorizontal() { + private bool LayoutHorizontal() + { ToolStrip toolStrip = ToolStrip; Rectangle clientRectangle = toolStrip.ClientRectangle; #if DEBUG - if (DebugLayoutTraceSwitch.TraceVerbose) { Debug.WriteLine("_________________________\r\nHorizontal Layout:" + toolStrip.ToString() + displayRectangle.ToString()); } + if (DebugLayoutTraceSwitch.TraceVerbose) + { Debug.WriteLine("_________________________\r\nHorizontal Layout:" + toolStrip.ToString() + displayRectangle.ToString()); } #endif int lastRight = displayRectangle.Right;// - toolStrip.Padding.Right; int lastLeft = displayRectangle.Left;// + toolStrip.Padding.Left; @@ -252,44 +302,53 @@ private bool LayoutHorizontal() { Size itemSize = Size.Empty; Rectangle alignedLeftItems = Rectangle.Empty; Rectangle alignedRightItems = Rectangle.Empty; - + // this will determine where the item should be placed. CalculatePlacementsHorizontal(); bool needOverflow = toolStrip.CanOverflow && ((OverflowRequired) || (OverflowSpace >= OverflowButtonSize.Width)); - toolStrip.OverflowButton.Visible = needOverflow; + toolStrip.OverflowButton.Visible = needOverflow; // if we require the overflow, it should stick up against the edge of the toolstrip. - if (needOverflow) { - if (toolStrip.RightToLeft == RightToLeft.No) { + if (needOverflow) + { + if (toolStrip.RightToLeft == RightToLeft.No) + { lastRight = clientRectangle.Right; } - else { + else + { lastLeft = clientRectangle.Left; } } - for (int j = -1; j < toolStrip.Items.Count; j++) { + for (int j = -1; j < toolStrip.Items.Count; j++) + { ToolStripItem item = null; - if (j == -1) { + if (j == -1) + { // the first time through place the overflow button if its required. - if (needOverflow) { + if (needOverflow) + { item = toolStrip.OverflowButton; item.SetPlacement(ToolStripItemPlacement.Main); itemSize = OverflowButtonSize; } - else { + else + { item = toolStrip.OverflowButton; item.SetPlacement(ToolStripItemPlacement.None); continue; } } - else { + else + { item = toolStrip.Items[j]; - - if (!((IArrangedElement)item).ParticipatesInLayout) { + + if (!((IArrangedElement)item).ParticipatesInLayout) + { // skip over items not participating in layout. E.G. not visible items continue; } @@ -297,13 +356,15 @@ private bool LayoutHorizontal() { // since we havent parented the item yet - the auto size wont have reset the size yet. itemSize = item.AutoSize ? item.GetPreferredSize(Size.Empty) : item.Size; } - + // if it turns out we dont need the overflow (because there are no Overflow.Always items and the width of everything // in the overflow is less than the width of the overflow button then reset the placement of the as needed items to // main. - if (!needOverflow && (item.Overflow == ToolStripItemOverflow.AsNeeded && item.Placement == ToolStripItemPlacement.Overflow)) { + if (!needOverflow && (item.Overflow == ToolStripItemOverflow.AsNeeded && item.Placement == ToolStripItemPlacement.Overflow)) + { #if DEBUG - if (DebugLayoutTraceSwitch.TraceVerbose) { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Resetting {0} to Main - we dont need it to overflow", item)); } + if (DebugLayoutTraceSwitch.TraceVerbose) + { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Resetting {0} to Main - we dont need it to overflow", item)); } #endif item.SetPlacement(ToolStripItemPlacement.Main); } @@ -313,26 +374,29 @@ private bool LayoutHorizontal() { // We need to honor left to right and head and tail. // In RTL.Yes, Head is to the Right, Tail is to the Left // In RTL.No, Head is to the Left, Tail is to the Right - if ((item != null) && (item.Placement == ToolStripItemPlacement.Main)) { + if ((item != null) && (item.Placement == ToolStripItemPlacement.Main)) + { int x = displayRectangle.Left; int y = displayRectangle.Top; Padding itemMargin = item.Margin; - if (((item.Alignment == ToolStripItemAlignment.Right) && (toolStrip.RightToLeft == RightToLeft.No)) || ((item.Alignment == ToolStripItemAlignment.Left) && (toolStrip.RightToLeft == RightToLeft.Yes))) { + if (((item.Alignment == ToolStripItemAlignment.Right) && (toolStrip.RightToLeft == RightToLeft.No)) || ((item.Alignment == ToolStripItemAlignment.Left) && (toolStrip.RightToLeft == RightToLeft.Yes))) + { // lastRight x Margin.Right // [Item]<----------[Item]----------->| // Margin.Left // this item should be placed to the right // we work backwards from the right edge - that is place items from right to left. - + x = lastRight - (itemMargin.Right + itemSize.Width); y += itemMargin.Top; lastRight = x - itemMargin.Left; - alignedRightItems = (alignedRightItems == Rectangle.Empty) ? new Rectangle(x,y,itemSize.Width, itemSize.Height) - : Rectangle.Union(alignedRightItems, new Rectangle(x,y,itemSize.Width, itemSize.Height)); - + alignedRightItems = (alignedRightItems == Rectangle.Empty) ? new Rectangle(x, y, itemSize.Width, itemSize.Height) + : Rectangle.Union(alignedRightItems, new Rectangle(x, y, itemSize.Width, itemSize.Height)); + } - else { + else + { // x Margin.Right lastLeft // |<----------[Item]------------>| // Margin.Left @@ -341,27 +405,31 @@ private bool LayoutHorizontal() { x = lastLeft + itemMargin.Left; y += itemMargin.Top; lastLeft = x + itemSize.Width + itemMargin.Right; - alignedLeftItems = (alignedLeftItems == Rectangle.Empty) ? new Rectangle(x,y,itemSize.Width, itemSize.Height) - : Rectangle.Union(alignedLeftItems, new Rectangle(x,y,itemSize.Width, itemSize.Height)); - + alignedLeftItems = (alignedLeftItems == Rectangle.Empty) ? new Rectangle(x, y, itemSize.Width, itemSize.Height) + : Rectangle.Union(alignedLeftItems, new Rectangle(x, y, itemSize.Width, itemSize.Height)); + } item.ParentInternal = ToolStrip; - Point itemLocation = new Point(x,y); - if (!clientRectangle.Contains(x, y)) { + Point itemLocation = new Point(x, y); + if (!clientRectangle.Contains(x, y)) + { item.SetPlacement(ToolStripItemPlacement.None); } - else if (alignedRightItems.Width > 0 && alignedLeftItems.Width > 0 && alignedRightItems.IntersectsWith(alignedLeftItems)) { + else if (alignedRightItems.Width > 0 && alignedLeftItems.Width > 0 && alignedRightItems.IntersectsWith(alignedLeftItems)) + { itemLocation = noMansLand; item.SetPlacement(ToolStripItemPlacement.None); } - - if (item.AutoSize) { + + if (item.AutoSize) + { // autosized items stretch from edge-edge itemSize.Height = Math.Max(displayRectangle.Height - itemMargin.Vertical, 0); } - else { + else + { // non autosized items are vertically centered Rectangle bounds = LayoutUtils.VAlign(item.Size, displayRectangle, AnchorStyles.None); itemLocation.Y = bounds.Y; @@ -369,20 +437,24 @@ private bool LayoutHorizontal() { SetItemLocation(item, itemLocation, itemSize); } - else { + else + { item.ParentInternal = (item.Placement == ToolStripItemPlacement.Overflow) ? toolStrip.OverflowButton.DropDown : null; } #if DEBUG - if (DebugLayoutTraceSwitch.TraceVerbose) { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Item {0} Placement {1} Bounds {2} Parent {3}", item.ToString(), item.Placement.ToString(), item.Bounds.ToString(), (item.ParentInternal == null) ? "null" : item.ParentInternal.ToString())); } + if (DebugLayoutTraceSwitch.TraceVerbose) + { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Item {0} Placement {1} Bounds {2} Parent {3}", item.ToString(), item.Placement.ToString(), item.Bounds.ToString(), (item.ParentInternal == null) ? "null" : item.ParentInternal.ToString())); } #endif } // return needsMoreSpace; } - private bool LayoutVertical() { + private bool LayoutVertical() + { #if DEBUG - if (DebugLayoutTraceSwitch.TraceVerbose) { Debug.WriteLine("_________________________\r\nVertical Layout" + displayRectangle.ToString()); } + if (DebugLayoutTraceSwitch.TraceVerbose) + { Debug.WriteLine("_________________________\r\nVertical Layout" + displayRectangle.ToString()); } #endif ToolStrip toolStrip = ToolStrip; Rectangle clientRectangle = toolStrip.ClientRectangle; @@ -392,10 +464,11 @@ private bool LayoutVertical() { Size itemSize = Size.Empty; Rectangle alignedLeftItems = Rectangle.Empty; Rectangle alignedRightItems = Rectangle.Empty; - + Size toolStripPreferredSize = displayRectangle.Size; DockStyle dock = toolStrip.Dock; - if (toolStrip.AutoSize && (!toolStrip.IsInToolStripPanel && (dock == DockStyle.Left) || (dock == DockStyle.Right))) { + if (toolStrip.AutoSize && (!toolStrip.IsInToolStripPanel && (dock == DockStyle.Left) || (dock == DockStyle.Right))) + { // if we're autosizing, make sure we pad out items to the preferred width, not the // width of the display rectangle. toolStripPreferredSize = ToolStrip.GetPreferredSizeVertical(toolStrip, Size.Empty) - toolStrip.Padding.Size; @@ -406,27 +479,33 @@ private bool LayoutVertical() { toolStrip.OverflowButton.Visible = needOverflow; - for (int j = -1; j < ToolStrip.Items.Count; j++) { + for (int j = -1; j < ToolStrip.Items.Count; j++) + { ToolStripItem item = null; - if (j == -1) { + if (j == -1) + { // the first time through place the overflow button if its required. - if (needOverflow) { + if (needOverflow) + { item = toolStrip.OverflowButton; item.SetPlacement(ToolStripItemPlacement.Main); } - else { + else + { item = toolStrip.OverflowButton; item.SetPlacement(ToolStripItemPlacement.None); continue; } itemSize = OverflowButtonSize; - + } - else { + else + { item = toolStrip.Items[j]; - if (!((IArrangedElement)item).ParticipatesInLayout) { + if (!((IArrangedElement)item).ParticipatesInLayout) + { // skip over items not participating in layout. E.G. not visible items continue; } @@ -434,13 +513,15 @@ private bool LayoutVertical() { itemSize = item.AutoSize ? item.GetPreferredSize(Size.Empty) : item.Size; } - + // if it turns out we dont need the overflow (because there are no Overflow.Always items and the height of everything // in the overflow is less than the width of the overflow button then reset the placement of the as needed items to // main. - if (!needOverflow && (item.Overflow == ToolStripItemOverflow.AsNeeded && item.Placement == ToolStripItemPlacement.Overflow)) { + if (!needOverflow && (item.Overflow == ToolStripItemOverflow.AsNeeded && item.Placement == ToolStripItemPlacement.Overflow)) + { #if DEBUG - if (DebugLayoutTraceSwitch.TraceVerbose) { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Resetting {0} to Main - we dont need it to overflow", item)); } + if (DebugLayoutTraceSwitch.TraceVerbose) + { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Resetting {0} to Main - we dont need it to overflow", item)); } #endif item.SetPlacement(ToolStripItemPlacement.Main); } @@ -449,56 +530,64 @@ private bool LayoutVertical() { // Vertical split stack management ignores left to right. // Items aligned to the Head are placed from Top to Bottom // Items aligned to the Tail are placed from Bottom to Top - if ((item != null) && (item.Placement == ToolStripItemPlacement.Main)) { + if ((item != null) && (item.Placement == ToolStripItemPlacement.Main)) + { Padding itemMargin = item.Margin; int x = displayRectangle.Left + itemMargin.Left; int y = displayRectangle.Top; - switch (item.Alignment) { + switch (item.Alignment) + { case ToolStripItemAlignment.Right: y = lastBottom - (itemMargin.Bottom + itemSize.Height); lastBottom = y - itemMargin.Top; - alignedRightItems = (alignedRightItems == Rectangle.Empty) ? new Rectangle(x,y,itemSize.Width, itemSize.Height) - : Rectangle.Union(alignedRightItems, new Rectangle(x,y,itemSize.Width, itemSize.Height)); - break; + alignedRightItems = (alignedRightItems == Rectangle.Empty) ? new Rectangle(x, y, itemSize.Width, itemSize.Height) + : Rectangle.Union(alignedRightItems, new Rectangle(x, y, itemSize.Width, itemSize.Height)); + break; case ToolStripItemAlignment.Left: default: y = lastTop + itemMargin.Top; lastTop = y + itemSize.Height + itemMargin.Bottom; - alignedLeftItems = (alignedLeftItems == Rectangle.Empty) ? new Rectangle(x,y,itemSize.Width, itemSize.Height) - : Rectangle.Union(alignedLeftItems, new Rectangle(x,y,itemSize.Width, itemSize.Height)); + alignedLeftItems = (alignedLeftItems == Rectangle.Empty) ? new Rectangle(x, y, itemSize.Width, itemSize.Height) + : Rectangle.Union(alignedLeftItems, new Rectangle(x, y, itemSize.Width, itemSize.Height)); break; } item.ParentInternal = ToolStrip; - Point itemLocation = new Point(x,y); + Point itemLocation = new Point(x, y); + - - if (!clientRectangle.Contains(x, y)) { + if (!clientRectangle.Contains(x, y)) + { item.SetPlacement(ToolStripItemPlacement.None); } - else if (alignedRightItems.Width > 0 && alignedLeftItems.Width > 0 && alignedRightItems.IntersectsWith(alignedLeftItems)) { + else if (alignedRightItems.Width > 0 && alignedLeftItems.Width > 0 && alignedRightItems.IntersectsWith(alignedLeftItems)) + { itemLocation = noMansLand; item.SetPlacement(ToolStripItemPlacement.None); } - - if (item.AutoSize) { - // autosized items stretch from edge-edge - itemSize.Width = Math.Max(toolStripPreferredSize.Width - itemMargin.Horizontal -1, 0); + + if (item.AutoSize) + { + // autosized items stretch from edge-edge + itemSize.Width = Math.Max(toolStripPreferredSize.Width - itemMargin.Horizontal - 1, 0); } - else { + else + { // non autosized items are horizontally centered Rectangle bounds = LayoutUtils.HAlign(item.Size, displayRectangle, AnchorStyles.None); itemLocation.X = bounds.X; } - - SetItemLocation(item, itemLocation, itemSize); + + SetItemLocation(item, itemLocation, itemSize); } - else { + else + { item.ParentInternal = (item.Placement == ToolStripItemPlacement.Overflow) ? toolStrip.OverflowButton.DropDown : null; } #if DEBUG - if (DebugLayoutTraceSwitch.TraceVerbose) { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Item {0} Placement {1} Bounds {2} Parent {3}", item.ToString(), item.Placement.ToString(), item.Bounds.ToString(), (item.ParentInternal == null) ? "null" : item.ParentInternal.ToString())); } + if (DebugLayoutTraceSwitch.TraceVerbose) + { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Item {0} Placement {1} Bounds {2} Parent {3}", item.ToString(), item.Placement.ToString(), item.Bounds.ToString(), (item.ParentInternal == null) ? "null" : item.ParentInternal.ToString())); } #endif } @@ -507,67 +596,83 @@ private bool LayoutVertical() { return needsMoreSpace; } - private void SetItemLocation(ToolStripItem item, Point itemLocation, Size itemSize) { + private void SetItemLocation(ToolStripItem item, Point itemLocation, Size itemSize) + { // make sure that things that dont fit within the display rectangle arent laid out. - if ((item.Placement == ToolStripItemPlacement.Main) - && !(item is ToolStripOverflowButton)) { // overflow buttons can be placed outside the display rect. - - bool horizontal = (ToolStrip.LayoutStyle == ToolStripLayoutStyle.HorizontalStackWithOverflow); - Rectangle displayRect = displayRectangle; - Rectangle itemBounds = new Rectangle(itemLocation, itemSize); - // in horizontal if something bleeds over the top/bottom that's ok - its left/right we care about - // same in vertical. - if (horizontal) { + if ((item.Placement == ToolStripItemPlacement.Main) + && !(item is ToolStripOverflowButton)) + { // overflow buttons can be placed outside the display rect. + + bool horizontal = (ToolStrip.LayoutStyle == ToolStripLayoutStyle.HorizontalStackWithOverflow); + Rectangle displayRect = displayRectangle; + Rectangle itemBounds = new Rectangle(itemLocation, itemSize); + // in horizontal if something bleeds over the top/bottom that's ok - its left/right we care about + // same in vertical. + if (horizontal) + { if ((itemBounds.Right > displayRectangle.Right) - || (itemBounds.Left < displayRectangle.Left)) { + || (itemBounds.Left < displayRectangle.Left)) + { #if DEBUG - if (DebugLayoutTraceSwitch.TraceVerbose) { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "[SplitStack.SetItemLocation] Sending Item {0} to NoMansLand as it doesnt fit horizontally within the DRect", item)); } + if (DebugLayoutTraceSwitch.TraceVerbose) + { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "[SplitStack.SetItemLocation] Sending Item {0} to NoMansLand as it doesnt fit horizontally within the DRect", item)); } #endif itemLocation = noMansLand; item.SetPlacement(ToolStripItemPlacement.None); } - - } - else { - if ((itemBounds.Bottom > displayRectangle.Bottom) - || (itemBounds.Top < displayRectangle.Top)) { + + } + else + { + if ((itemBounds.Bottom > displayRectangle.Bottom) + || (itemBounds.Top < displayRectangle.Top)) + { #if DEBUG - if (DebugLayoutTraceSwitch.TraceVerbose) { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "[SplitStack.SetItemLocation] Sending Item {0} to NoMansLand as it doesnt fit verticallu within the DRect", item)); } -#endif - - itemLocation = noMansLand; - item.SetPlacement(ToolStripItemPlacement.None); - } - } - } - item.SetBounds(new Rectangle(itemLocation, itemSize)); + if (DebugLayoutTraceSwitch.TraceVerbose) + { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "[SplitStack.SetItemLocation] Sending Item {0} to NoMansLand as it doesnt fit verticallu within the DRect", item)); } +#endif + + itemLocation = noMansLand; + item.SetPlacement(ToolStripItemPlacement.None); + } + } + } + item.SetBounds(new Rectangle(itemLocation, itemSize)); } - private void PlaceItems() { + private void PlaceItems() + { ToolStrip toolStrip = this.ToolStrip; - for (int i = 0; i < toolStrip.Items.Count; i++) { + for (int i = 0; i < toolStrip.Items.Count; i++) + { ToolStripItem item = toolStrip.Items[i]; - // if we havent placed the items, place them now. - if (item.Placement == ToolStripItemPlacement.None) { - if (item.Overflow != ToolStripItemOverflow.Always) { + // if we havent placed the items, place them now. + if (item.Placement == ToolStripItemPlacement.None) + { + if (item.Overflow != ToolStripItemOverflow.Always) + { // as needed items will have already been placed into the overflow if they // needed to move over. item.SetPlacement(ToolStripItemPlacement.Main); } - else { + else + { item.SetPlacement(ToolStripItemPlacement.Overflow); } } } } - private void ResetItemPlacements() { + private void ResetItemPlacements() + { ToolStrip toolStrip = this.ToolStrip; - for (int i = 0; i < toolStrip.Items.Count; i++) { - if (toolStrip.Items[i].Placement == ToolStripItemPlacement.Overflow) { + for (int i = 0; i < toolStrip.Items.Count; i++) + { + if (toolStrip.Items[i].Placement == ToolStripItemPlacement.Overflow) + { toolStrip.Items[i].ParentInternal = null; } @@ -578,20 +683,24 @@ private void ResetItemPlacements() { // // This method is called when we are walking through the item collection and we have realized that we // need to free up "X" amount of space to be able to fit an item onto the ToolStrip. - private int SendNextItemToOverflow(int spaceNeeded, bool horizontal) { + private int SendNextItemToOverflow(int spaceNeeded, bool horizontal) + { #if DEBUG - if (DebugLayoutTraceSwitch.TraceVerbose) { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "SendNextItemToOverflow attempting to free {0}", spaceNeeded)); } + if (DebugLayoutTraceSwitch.TraceVerbose) + { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "SendNextItemToOverflow attempting to free {0}", spaceNeeded)); } #endif Debug.Indent(); int freedSpace = 0; int backIndex = BackwardsWalkingIndex; - BackwardsWalkingIndex = (backIndex == -1) ? ToolStrip.Items.Count - 1 : backIndex -1; - for (; BackwardsWalkingIndex >= 0; BackwardsWalkingIndex--) { + BackwardsWalkingIndex = (backIndex == -1) ? ToolStrip.Items.Count - 1 : backIndex - 1; + for (; BackwardsWalkingIndex >= 0; BackwardsWalkingIndex--) + { ToolStripItem item = ToolStrip.Items[BackwardsWalkingIndex]; - - if (!((IArrangedElement)item).ParticipatesInLayout) { + + if (!((IArrangedElement)item).ParticipatesInLayout) + { // skip over items not participating in layout. E.G. not visible items continue; } @@ -599,32 +708,38 @@ private int SendNextItemToOverflow(int spaceNeeded, bool horizontal) { // look for items that say they're ok for overflowing. // not looking at ones that Always overflow - as the forward walker already skips these. - if (item.Overflow == ToolStripItemOverflow.AsNeeded && item.Placement != ToolStripItemPlacement.Overflow) { + if (item.Overflow == ToolStripItemOverflow.AsNeeded && item.Placement != ToolStripItemPlacement.Overflow) + { #if DEBUG - if (DebugLayoutTraceSwitch.TraceVerbose) { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Found candidate for sending to overflow {0}", item.ToString())); } + if (DebugLayoutTraceSwitch.TraceVerbose) + { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Found candidate for sending to overflow {0}", item.ToString())); } #endif // since we havent parented the item yet - the auto size wont have reset the size yet. Size itemSize = item.AutoSize ? item.GetPreferredSize(displayRectangle.Size) : item.Size; - if (BackwardsWalkingIndex <= ForwardsWalkingIndex) { + if (BackwardsWalkingIndex <= ForwardsWalkingIndex) + { // we've found an item that the forwards walking guy has already marched past, // we need to let him know how much space we're freeing by sending this guy over // to the overflow. freedSpace += (horizontal) ? itemSize.Width + itemMargin.Horizontal : itemSize.Height + itemMargin.Vertical; #if DEBUG - if (DebugLayoutTraceSwitch.TraceVerbose) { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Sweet! {0} FreedSpace - which is now {1}", itemSize, freedSpace.ToString(CultureInfo.InvariantCulture))); } + if (DebugLayoutTraceSwitch.TraceVerbose) + { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Sweet! {0} FreedSpace - which is now {1}", itemSize, freedSpace.ToString(CultureInfo.InvariantCulture))); } #endif } // send the item to the overflow. item.SetPlacement(ToolStripItemPlacement.Overflow); - if (this.OverflowRequired == false) { + if (this.OverflowRequired == false) + { // this is the first item we're sending down. // we now need to account for the width or height of the overflow button spaceNeeded += (horizontal) ? OverflowButtonSize.Width : OverflowButtonSize.Height; #if DEBUG - if (DebugLayoutTraceSwitch.TraceVerbose) { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Turns out we now need an overflow button, space needed now: {0}", spaceNeeded.ToString(CultureInfo.InvariantCulture))); } + if (DebugLayoutTraceSwitch.TraceVerbose) + { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Turns out we now need an overflow button, space needed now: {0}", spaceNeeded.ToString(CultureInfo.InvariantCulture))); } #endif this.OverflowRequired = true; } @@ -632,7 +747,8 @@ private int SendNextItemToOverflow(int spaceNeeded, bool horizontal) { this.OverflowSpace += (horizontal) ? itemSize.Width + itemMargin.Horizontal : itemSize.Height + itemMargin.Vertical; } - if (freedSpace > spaceNeeded) { + if (freedSpace > spaceNeeded) + { break; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripStatusLabel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripStatusLabel.cs index 42b65b74440..303e757c755 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripStatusLabel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripStatusLabel.cs @@ -29,22 +29,28 @@ public class ToolStripStatusLabel : ToolStripLabel, IAutomationLiveRegion /// /// A non selectable ToolStrip item /// - public ToolStripStatusLabel() { + public ToolStripStatusLabel() + { Initialize(); } - public ToolStripStatusLabel(string text):base(text,null,false,null) { + public ToolStripStatusLabel(string text) : base(text, null, false, null) + { Initialize(); } - public ToolStripStatusLabel(Image image):base(null,image,false,null) { + public ToolStripStatusLabel(Image image) : base(null, image, false, null) + { Initialize(); } - public ToolStripStatusLabel(string text, Image image):base(text,image,false,null) { + public ToolStripStatusLabel(string text, Image image) : base(text, image, false, null) + { Initialize(); } - public ToolStripStatusLabel(string text, Image image, EventHandler onClick):base(text,image,/*isLink=*/false,onClick,null) { + public ToolStripStatusLabel(string text, Image image, EventHandler onClick) : base(text, image,/*isLink=*/false, onClick, null) + { Initialize(); } - public ToolStripStatusLabel(string text, Image image, EventHandler onClick, string name) :base(text,image,/*isLink=*/false,onClick, name) { + public ToolStripStatusLabel(string text, Image image, EventHandler onClick, string name) : base(text, image,/*isLink=*/false, onClick, name) + { Initialize(); } @@ -57,7 +63,8 @@ public ToolStripStatusLabel(string text, Image image, EventHandler onClick, stri /// /// AccessibleObject for this ToolStripStatusLabel instance. /// - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new ToolStripStatusLabelAccessibleObject(this); } @@ -65,20 +72,24 @@ protected override AccessibleObject CreateAccessibilityInstance() { /// Creates an instance of the object that defines how image and text /// gets laid out in the ToolStripItem /// - internal override ToolStripItemInternalLayout CreateInternalLayout() { + internal override ToolStripItemInternalLayout CreateInternalLayout() + { return new ToolStripStatusLabelLayout(this); } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Advanced)] - public new ToolStripItemAlignment Alignment { - get { - return base.Alignment; - } - set { - base.Alignment = value; - } - } + public new ToolStripItemAlignment Alignment + { + get + { + return base.Alignment; + } + set + { + base.Alignment = value; + } + } [ @@ -86,12 +97,15 @@ internal override ToolStripItemInternalLayout CreateInternalLayout() { SRDescription(nameof(SR.ToolStripStatusLabelBorderStyleDescr)), SRCategory(nameof(SR.CatAppearance)) ] - public Border3DStyle BorderStyle { - get { + public Border3DStyle BorderStyle + { + get + { return borderStyle; } - set { - if (!ClientUtils.IsEnumValid_NotSequential(value, + set + { + if (!ClientUtils.IsEnumValid_NotSequential(value, (int)value, (int)Border3DStyle.Adjust, (int)Border3DStyle.Bump, @@ -103,11 +117,13 @@ public Border3DStyle BorderStyle { (int)Border3DStyle.Sunken, (int)Border3DStyle.SunkenInner, (int)Border3DStyle.SunkenOuter - )) { + )) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(Border3DStyle)); } - - if (borderStyle != value) { + + if (borderStyle != value) + { borderStyle = value; Invalidate(); } @@ -119,15 +135,19 @@ public Border3DStyle BorderStyle { SRDescription(nameof(SR.ToolStripStatusLabelBorderSidesDescr)), SRCategory(nameof(SR.CatAppearance)) ] - public ToolStripStatusLabelBorderSides BorderSides { - get { + public ToolStripStatusLabelBorderSides BorderSides + { + get + { return borderSides; } - set { + set + { // no Enum.IsDefined as this is a flags enum. - if (borderSides != value) { + if (borderSides != value) + { borderSides = value; - LayoutTransaction.DoLayout(Owner,this, PropertyNames.BorderStyle); + LayoutTransaction.DoLayout(Owner, this, PropertyNames.BorderStyle); Invalidate(); } } @@ -138,13 +158,16 @@ public ToolStripStatusLabelBorderSides BorderSides { /// private void Initialize() { - if (DpiHelper.IsScalingRequirementMet) { + if (DpiHelper.IsScalingRequirementMet) + { scaledDefaultMargin = DpiHelper.LogicalToDeviceUnits(defaultMargin); } } - protected internal override Padding DefaultMargin { - get { + protected internal override Padding DefaultMargin + { + get + { return scaledDefaultMargin; } } @@ -154,15 +177,19 @@ protected internal override Padding DefaultMargin { SRDescription(nameof(SR.ToolStripStatusLabelSpringDescr)), SRCategory(nameof(SR.CatAppearance)) ] - public bool Spring { + public bool Spring + { get { return spring; } - set { - if (spring != value) { + set + { + if (spring != value) + { spring = value; - if (ParentInternal != null) { - LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.Spring); + if (ParentInternal != null) + { + LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.Spring); } - + } } } @@ -178,59 +205,73 @@ public bool Spring { Browsable(true), EditorBrowsable(EditorBrowsableState.Always) ] - public AutomationLiveSetting LiveSetting { - get { + public AutomationLiveSetting LiveSetting + { + get + { return liveSetting; } - set { - if (!ClientUtils.IsEnumValid(value, (int)value, (int)AutomationLiveSetting.Off, (int)AutomationLiveSetting.Assertive)) { + set + { + if (!ClientUtils.IsEnumValid(value, (int)value, (int)AutomationLiveSetting.Off, (int)AutomationLiveSetting.Assertive)) + { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AutomationLiveSetting)); } liveSetting = value; } } - protected override void OnTextChanged(EventArgs e) { + protected override void OnTextChanged(EventArgs e) + { base.OnTextChanged(e); - if (LiveSetting != AutomationLiveSetting.Off) { + if (LiveSetting != AutomationLiveSetting.Off) + { AccessibilityObject.RaiseLiveRegionChanged(); } } - public override System.Drawing.Size GetPreferredSize(System.Drawing.Size constrainingSize) { - if (BorderSides != ToolStripStatusLabelBorderSides.None) { + public override System.Drawing.Size GetPreferredSize(System.Drawing.Size constrainingSize) + { + if (BorderSides != ToolStripStatusLabelBorderSides.None) + { return base.GetPreferredSize(constrainingSize) + new Size(4, 4); - } - else { - return base.GetPreferredSize(constrainingSize); - } + } + else + { + return base.GetPreferredSize(constrainingSize); + } } - + /// /// Inheriting classes should override this method to handle this event. /// - protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { + protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) + { - if (this.Owner != null) { + if (this.Owner != null) + { ToolStripRenderer renderer = this.Renderer; - + renderer.DrawToolStripStatusLabelBackground(new ToolStripItemRenderEventArgs(e.Graphics, this)); - if ((DisplayStyle & ToolStripItemDisplayStyle.Image) == ToolStripItemDisplayStyle.Image) { + if ((DisplayStyle & ToolStripItemDisplayStyle.Image) == ToolStripItemDisplayStyle.Image) + { renderer.DrawItemImage(new ToolStripItemImageRenderEventArgs(e.Graphics, this, InternalLayout.ImageRectangle)); } PaintText(e.Graphics); - } + } } [ComVisible(true)] - internal class ToolStripStatusLabelAccessibleObject : ToolStripLabelAccessibleObject { + internal class ToolStripStatusLabelAccessibleObject : ToolStripLabelAccessibleObject + { private ToolStripStatusLabel ownerItem; - public ToolStripStatusLabelAccessibleObject(ToolStripStatusLabel ownerItem) : base(ownerItem) { + public ToolStripStatusLabelAccessibleObject(ToolStripStatusLabel ownerItem) : base(ownerItem) + { this.ownerItem = ownerItem; } @@ -240,12 +281,15 @@ public ToolStripStatusLabelAccessibleObject(ToolStripStatusLabel ownerItem) : ba /// or opted into this feature using compatibility switches. /// /// True if operation succeeds, False otherwise. - public override bool RaiseLiveRegionChanged() { + public override bool RaiseLiveRegionChanged() + { return RaiseAutomationEvent(NativeMethods.UIA_LiveRegionChangedEventId); } - internal override object GetPropertyValue(int propertyID) { - switch (propertyID) { + internal override object GetPropertyValue(int propertyID) + { + switch (propertyID) + { case NativeMethods.UIA_LiveSettingPropertyId: return ownerItem.LiveSetting; case NativeMethods.UIA_ControlTypePropertyId: @@ -261,25 +305,28 @@ internal override object GetPropertyValue(int propertyID) { /// Its main job is to make sure the inner button has the same parent as the split button, so /// that layout can be performed using the correct graphics context. /// - private class ToolStripStatusLabelLayout : ToolStripItemInternalLayout { + private class ToolStripStatusLabelLayout : ToolStripItemInternalLayout + { - ToolStripStatusLabel owner; + ToolStripStatusLabel owner; - public ToolStripStatusLabelLayout(ToolStripStatusLabel owner) : base(owner) { + public ToolStripStatusLabelLayout(ToolStripStatusLabel owner) : base(owner) + { this.owner = owner; } - protected override ToolStripItemLayoutOptions CommonLayoutOptions() { - ToolStripItemLayoutOptions layoutOptions = base.CommonLayoutOptions(); - layoutOptions.borderSize = 0; - return layoutOptions; + protected override ToolStripItemLayoutOptions CommonLayoutOptions() + { + ToolStripItemLayoutOptions layoutOptions = base.CommonLayoutOptions(); + layoutOptions.borderSize = 0; + return layoutOptions; } } - + } } - + diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSystemRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSystemRenderer.cs index 2d9c55db18e..49777ba3d0f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSystemRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSystemRenderer.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Windows.Forms.VisualStyles; using System.Drawing; @@ -10,29 +11,38 @@ namespace System.Windows.Forms { using System.Drawing.Imaging; using System.ComponentModel; using System.Windows.Forms.Layout; - - public class ToolStripSystemRenderer : ToolStripRenderer { - + + public class ToolStripSystemRenderer : ToolStripRenderer + { + [ThreadStatic()] - private static VisualStyleRenderer renderer = null; + private static VisualStyleRenderer renderer = null; private ToolStripRenderer toolStripHighContrastRenderer; - public ToolStripSystemRenderer() { + public ToolStripSystemRenderer() + { } - internal ToolStripSystemRenderer(bool isDefault) : base(isDefault) { + internal ToolStripSystemRenderer(bool isDefault) : base(isDefault) + { } - internal override ToolStripRenderer RendererOverride { - get { - if (DisplayInformation.HighContrast) { - return HighContrastRenderer; - } - return null; - } - } - - internal ToolStripRenderer HighContrastRenderer { - get { - if (toolStripHighContrastRenderer == null) { + internal override ToolStripRenderer RendererOverride + { + get + { + if (DisplayInformation.HighContrast) + { + return HighContrastRenderer; + } + return null; + } + } + + internal ToolStripRenderer HighContrastRenderer + { + get + { + if (toolStripHighContrastRenderer == null) + { toolStripHighContrastRenderer = new ToolStripHighContrastRenderer(/*renderLikeSystem*/true); } return toolStripHighContrastRenderer; @@ -43,14 +53,19 @@ internal ToolStripRenderer HighContrastRenderer { /// /// Draw the background color /// - private static VisualStyleRenderer VisualStyleRenderer { - get { - if (Application.RenderWithVisualStyles) { - if (renderer == null && VisualStyleRenderer.IsElementDefined(VisualStyleElement.ToolBar.Button.Normal)) { + private static VisualStyleRenderer VisualStyleRenderer + { + get + { + if (Application.RenderWithVisualStyles) + { + if (renderer == null && VisualStyleRenderer.IsElementDefined(VisualStyleElement.ToolBar.Button.Normal)) + { renderer = new VisualStyleRenderer(VisualStyleElement.ToolBar.Button.Normal); } } - else { + else + { renderer = null; } return renderer; @@ -61,13 +76,17 @@ private static VisualStyleRenderer VisualStyleRenderer { /// /// Fill the item's background as bounded by the rectangle /// - private static void FillBackground(Graphics g, Rectangle bounds, Color backColor) { + private static void FillBackground(Graphics g, Rectangle bounds, Color backColor) + { // Fill the background with the item's back color - if (backColor.IsSystemColor) { + if (backColor.IsSystemColor) + { g.FillRectangle(SystemBrushes.FromSystemColor(backColor), bounds); } - else { - using (Brush backBrush = new SolidBrush(backColor)) { + else + { + using (Brush backBrush = new SolidBrush(backColor)) + { g.FillRectangle(backBrush, bounds); } } @@ -76,58 +95,73 @@ private static void FillBackground(Graphics g, Rectangle bounds, Color backColor /// /// returns true if you are required to dispose the pen /// - private static bool GetPen(Color color, ref Pen pen) { - if (color.IsSystemColor) { - pen = SystemPens.FromSystemColor(color); - return false; - } - else{ - pen = new Pen(color); - return true; - } + private static bool GetPen(Color color, ref Pen pen) + { + if (color.IsSystemColor) + { + pen = SystemPens.FromSystemColor(color); + return false; + } + else + { + pen = new Pen(color); + return true; + } } /// /// translates the ToolStrip item state into a toolbar state, which is something the renderer understands /// - private static int GetItemState(ToolStripItem item) { + private static int GetItemState(ToolStripItem item) + { return (int)GetToolBarState(item); } /// /// translates the ToolStrip item state into a toolbar state, which is something the renderer understands /// - private static int GetSplitButtonDropDownItemState(ToolStripSplitButton item) { + private static int GetSplitButtonDropDownItemState(ToolStripSplitButton item) + { return (int)GetSplitButtonToolBarState(item, true); } /// /// translates the ToolStrip item state into a toolbar state, which is something the renderer understands /// - private static int GetSplitButtonItemState(ToolStripSplitButton item) { + private static int GetSplitButtonItemState(ToolStripSplitButton item) + { return (int)GetSplitButtonToolBarState(item, false); } /// /// translates the ToolStrip item state into a toolbar state, which is something the renderer understands /// - private static ToolBarState GetSplitButtonToolBarState(ToolStripSplitButton button, bool dropDownButton) { - ToolBarState state = ToolBarState.Normal; - - if (button != null) { - if (!button.Enabled) { + private static ToolBarState GetSplitButtonToolBarState(ToolStripSplitButton button, bool dropDownButton) + { + ToolBarState state = ToolBarState.Normal; + + if (button != null) + { + if (!button.Enabled) + { state = ToolBarState.Disabled; } - else if (dropDownButton){ - if (button.DropDownButtonPressed || button.ButtonPressed) { + else if (dropDownButton) + { + if (button.DropDownButtonPressed || button.ButtonPressed) + { state = ToolBarState.Pressed; } - else if (button.DropDownButtonSelected || button.ButtonSelected) { - state = ToolBarState.Hot; + else if (button.DropDownButtonSelected || button.ButtonSelected) + { + state = ToolBarState.Hot; } } - else{ - if (button.ButtonPressed) { + else + { + if (button.ButtonPressed) + { state = ToolBarState.Pressed; } - else if (button.ButtonSelected) { - state = ToolBarState.Hot; + else if (button.ButtonSelected) + { + state = ToolBarState.Hot; } } } @@ -137,257 +171,310 @@ private static ToolBarState GetSplitButtonToolBarState(ToolStripSplitButton butt /// /// translates the ToolStrip item state into a toolbar state, which is something the renderer understands /// - private static ToolBarState GetToolBarState(ToolStripItem item) { - ToolBarState state = ToolBarState.Normal; - if (item != null) { - if (!item.Enabled) { + private static ToolBarState GetToolBarState(ToolStripItem item) + { + ToolBarState state = ToolBarState.Normal; + if (item != null) + { + if (!item.Enabled) + { state = ToolBarState.Disabled; } - if (item is ToolStripButton && ((ToolStripButton)item).Checked) { - if (((ToolStripButton)item).Selected) { + if (item is ToolStripButton && ((ToolStripButton)item).Checked) + { + if (((ToolStripButton)item).Selected) + { state = ToolBarState.Hot; // we'd prefer HotChecked here, but Color Theme uses the same color as Checked } - else { + else + { state = ToolBarState.Checked; } } - else if (item.Pressed) { + else if (item.Pressed) + { state = ToolBarState.Pressed; } - else if (item.Selected) { - state = ToolBarState.Hot; + else if (item.Selected) + { + state = ToolBarState.Hot; } } return state; - } - + } + + - /// /// Draw the ToolStrip background. ToolStrip users should override this if they want to draw differently. /// - protected override void OnRenderToolStripBackground(ToolStripRenderEventArgs e) { + protected override void OnRenderToolStripBackground(ToolStripRenderEventArgs e) + { ToolStrip toolStrip = e.ToolStrip; Graphics g = e.Graphics; - Rectangle bounds= e.AffectedBounds; + Rectangle bounds = e.AffectedBounds; - if (!ShouldPaintBackground(toolStrip)) { + if (!ShouldPaintBackground(toolStrip)) + { return; } - if (toolStrip is StatusStrip) { + if (toolStrip is StatusStrip) + { RenderStatusStripBackground(e); } - else { - if (DisplayInformation.HighContrast) { + else + { + if (DisplayInformation.HighContrast) + { FillBackground(g, bounds, SystemColors.ButtonFace); } - else if (DisplayInformation.LowResolution) { + else if (DisplayInformation.LowResolution) + { FillBackground(g, bounds, (toolStrip is ToolStripDropDown) ? SystemColors.ControlLight : e.BackColor); } - else if (toolStrip.IsDropDown) { - FillBackground(g, bounds, (!ToolStripManager.VisualStylesEnabled) ? + else if (toolStrip.IsDropDown) + { + FillBackground(g, bounds, (!ToolStripManager.VisualStylesEnabled) ? e.BackColor : SystemColors.Menu); } - else if (toolStrip is MenuStrip) { + else if (toolStrip is MenuStrip) + { FillBackground(g, bounds, (!ToolStripManager.VisualStylesEnabled) ? e.BackColor : SystemColors.MenuBar); } - else if (ToolStripManager.VisualStylesEnabled && VisualStyleRenderer.IsElementDefined(VisualStyleElement.Rebar.Band.Normal)) { + else if (ToolStripManager.VisualStylesEnabled && VisualStyleRenderer.IsElementDefined(VisualStyleElement.Rebar.Band.Normal)) + { VisualStyleRenderer vsRenderer = VisualStyleRenderer; vsRenderer.SetParameters(VisualStyleElement.ToolBar.Bar.Normal); vsRenderer.DrawBackground(g, bounds); } - else { + else + { FillBackground(g, bounds, (!ToolStripManager.VisualStylesEnabled) ? e.BackColor : SystemColors.MenuBar); } } } - + /// /// Draw the border around the ToolStrip. This should be done as the last step. /// - protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) { - ToolStrip toolStrip = e.ToolStrip; - Graphics g = e.Graphics; - Rectangle bounds = e.ToolStrip.ClientRectangle; + protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) + { + ToolStrip toolStrip = e.ToolStrip; + Graphics g = e.Graphics; + Rectangle bounds = e.ToolStrip.ClientRectangle; - if (toolStrip is StatusStrip) { + if (toolStrip is StatusStrip) + { RenderStatusStripBorder(e); - } - else if (toolStrip is ToolStripDropDown) { + } + else if (toolStrip is ToolStripDropDown) + { ToolStripDropDown toolStripDropDown = toolStrip as ToolStripDropDown; - + // Paint the border for the window depending on whether or not we have a drop shadow effect. - if (toolStripDropDown.DropShadowEnabled && ToolStripManager.VisualStylesEnabled) { + if (toolStripDropDown.DropShadowEnabled && ToolStripManager.VisualStylesEnabled) + { bounds.Width -= 1; bounds.Height -= 1; e.Graphics.DrawRectangle(new Pen(SystemColors.ControlDark), bounds); } - else { + else + { ControlPaint.DrawBorder3D(e.Graphics, bounds, Border3DStyle.Raised); } - } - else { - if (ToolStripManager.VisualStylesEnabled) { - e.Graphics.DrawLine(SystemPens.ButtonHighlight, 0,bounds.Bottom-1,bounds.Width, bounds.Bottom-1); - e.Graphics.DrawLine(SystemPens.InactiveBorder, 0,bounds.Bottom-2,bounds.Width,bounds.Bottom-2); - } - else { - e.Graphics.DrawLine(SystemPens.ButtonHighlight, 0,bounds.Bottom-1,bounds.Width, bounds.Bottom-1); - e.Graphics.DrawLine(SystemPens.ButtonShadow, 0,bounds.Bottom-2,bounds.Width,bounds.Bottom-2); - } - } + } + else + { + if (ToolStripManager.VisualStylesEnabled) + { + e.Graphics.DrawLine(SystemPens.ButtonHighlight, 0, bounds.Bottom - 1, bounds.Width, bounds.Bottom - 1); + e.Graphics.DrawLine(SystemPens.InactiveBorder, 0, bounds.Bottom - 2, bounds.Width, bounds.Bottom - 2); + } + else + { + e.Graphics.DrawLine(SystemPens.ButtonHighlight, 0, bounds.Bottom - 1, bounds.Width, bounds.Bottom - 1); + e.Graphics.DrawLine(SystemPens.ButtonShadow, 0, bounds.Bottom - 2, bounds.Width, bounds.Bottom - 2); + } + } } - + /// /// Draw the grip. ToolStrip users should override this if they want to draw differently. /// - protected override void OnRenderGrip(ToolStripGripRenderEventArgs e) { - + protected override void OnRenderGrip(ToolStripGripRenderEventArgs e) + { + Graphics g = e.Graphics; Rectangle bounds = new Rectangle(Point.Empty, e.GripBounds.Size); bool verticalGrip = e.GripDisplayStyle == ToolStripGripDisplayStyle.Vertical; - - if (ToolStripManager.VisualStylesEnabled && VisualStyleRenderer.IsElementDefined(VisualStyleElement.Rebar.Gripper.Normal)) { + + if (ToolStripManager.VisualStylesEnabled && VisualStyleRenderer.IsElementDefined(VisualStyleElement.Rebar.Gripper.Normal)) + { VisualStyleRenderer vsRenderer = VisualStyleRenderer; - - if (verticalGrip) { - vsRenderer.SetParameters(VisualStyleElement.Rebar.Gripper.Normal); - - bounds.Height = ((bounds.Height -2/*number of pixels for border*/) / 4) * 4; // make sure height is an even interval of 4. - bounds.Y = Math.Max(0,(e.GripBounds.Height - bounds.Height -2/*number of pixels for border*/) / 2); + + if (verticalGrip) + { + vsRenderer.SetParameters(VisualStyleElement.Rebar.Gripper.Normal); + + bounds.Height = ((bounds.Height - 2/*number of pixels for border*/) / 4) * 4; // make sure height is an even interval of 4. + bounds.Y = Math.Max(0, (e.GripBounds.Height - bounds.Height - 2/*number of pixels for border*/) / 2); } - else { - vsRenderer.SetParameters(VisualStyleElement.Rebar.GripperVertical.Normal); + else + { + vsRenderer.SetParameters(VisualStyleElement.Rebar.GripperVertical.Normal); } vsRenderer.DrawBackground(g, bounds); } - else { + else + { // do some fixup so that we dont paint from end to end. Color backColor = e.ToolStrip.BackColor; FillBackground(g, bounds, backColor); - if (verticalGrip) { - if (bounds.Height >= 4) { - bounds.Inflate(0,-2); // scoot down 2PX and start drawing + if (verticalGrip) + { + if (bounds.Height >= 4) + { + bounds.Inflate(0, -2); // scoot down 2PX and start drawing } bounds.Width = 3; } - else { - if (bounds.Width >= 4) { - bounds.Inflate(-2,0); // scoot over 2PX and start drawing + else + { + if (bounds.Width >= 4) + { + bounds.Inflate(-2, 0); // scoot over 2PX and start drawing } bounds.Height = 3; } - + RenderSmall3DBorderInternal(g, bounds, ToolBarState.Hot, (e.ToolStrip.RightToLeft == RightToLeft.Yes)); - + } } /// /// Draw the items background /// - protected override void OnRenderItemBackground(ToolStripItemRenderEventArgs e) { + protected override void OnRenderItemBackground(ToolStripItemRenderEventArgs e) + { } /// /// Draw the items background /// - protected override void OnRenderImageMargin(ToolStripRenderEventArgs e) { + protected override void OnRenderImageMargin(ToolStripRenderEventArgs e) + { } /// /// Draw the button background /// - protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e) { + protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e) + { RenderItemInternal(e); } - + /// /// Draw the button background /// - protected override void OnRenderDropDownButtonBackground(ToolStripItemRenderEventArgs e) { + protected override void OnRenderDropDownButtonBackground(ToolStripItemRenderEventArgs e) + { RenderItemInternal(e); } /// /// Draw the button background /// - protected override void OnRenderOverflowButtonBackground(ToolStripItemRenderEventArgs e) { + protected override void OnRenderOverflowButtonBackground(ToolStripItemRenderEventArgs e) + { ToolStripItem item = e.Item; Graphics g = e.Graphics; - - - if (ToolStripManager.VisualStylesEnabled && VisualStyleRenderer.IsElementDefined(VisualStyleElement.Rebar.Chevron.Normal)) { + + + if (ToolStripManager.VisualStylesEnabled && VisualStyleRenderer.IsElementDefined(VisualStyleElement.Rebar.Chevron.Normal)) + { VisualStyleElement chevronElement = VisualStyleElement.Rebar.Chevron.Normal; VisualStyleRenderer vsRenderer = VisualStyleRenderer; vsRenderer.SetParameters(chevronElement.ClassName, chevronElement.Part, GetItemState(item)); vsRenderer.DrawBackground(g, new Rectangle(Point.Empty, item.Size)); } - else { + else + { RenderItemInternal(e); - Color arrowColor = item.Enabled ? SystemColors.ControlText : SystemColors.ControlDark; + Color arrowColor = item.Enabled ? SystemColors.ControlText : SystemColors.ControlDark; DrawArrow(new ToolStripArrowRenderEventArgs(g, item, new Rectangle(Point.Empty, item.Size), arrowColor, ArrowDirection.Down)); - } + } } - + /// /// Draw the button background /// - protected override void OnRenderLabelBackground(ToolStripItemRenderEventArgs e) { + protected override void OnRenderLabelBackground(ToolStripItemRenderEventArgs e) + { RenderLabelInternal(e); } /// /// Draw the items background /// - protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) { - - ToolStripMenuItem item = e.Item as ToolStripMenuItem; - Graphics g = e.Graphics; - - if (item is MdiControlStrip.SystemMenuItem) { - return; // no highlights are painted behind a system menu item - } - - // - - if (item != null) { - Rectangle bounds = new Rectangle(Point.Empty, item.Size); - if (item.IsTopLevel && !ToolStripManager.VisualStylesEnabled) { + protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) + { + + ToolStripMenuItem item = e.Item as ToolStripMenuItem; + Graphics g = e.Graphics; + + if (item is MdiControlStrip.SystemMenuItem) + { + return; // no highlights are painted behind a system menu item + } + + // + + if (item != null) + { + Rectangle bounds = new Rectangle(Point.Empty, item.Size); + if (item.IsTopLevel && !ToolStripManager.VisualStylesEnabled) + { // Classic Mode (3D edges) // Draw box highlight for toplevel items in downlevel platforms - if (item.BackgroundImage != null) { + if (item.BackgroundImage != null) + { ControlPaint.DrawBackgroundImage(g, item.BackgroundImage, item.BackColor, item.BackgroundImageLayout, item.ContentRectangle, item.ContentRectangle); } - else if (item.RawBackColor != Color.Empty) { + else if (item.RawBackColor != Color.Empty) + { FillBackground(g, item.ContentRectangle, item.BackColor); } // Toplevel menu items do 3D borders. ToolBarState state = GetToolBarState(item); RenderSmall3DBorderInternal(g, bounds, state, (item.RightToLeft == RightToLeft.Yes)); - } - else { - // Modern MODE (no 3D edges) - // Draw blue filled highlight for toplevel items in themed platforms - // or items parented to a drop down - Rectangle fillRect = new Rectangle(Point.Empty, item.Size); - if (item.IsOnDropDown) { - // Scoot in by 2 pixels when selected - fillRect.X += 2; - fillRect.Width -= 3; //its already 1 away from the right edge - } - - if (item.Selected || item.Pressed) { + } + else + { + // Modern MODE (no 3D edges) + // Draw blue filled highlight for toplevel items in themed platforms + // or items parented to a drop down + Rectangle fillRect = new Rectangle(Point.Empty, item.Size); + if (item.IsOnDropDown) + { + // Scoot in by 2 pixels when selected + fillRect.X += 2; + fillRect.Width -= 3; //its already 1 away from the right edge + } + + if (item.Selected || item.Pressed) + { // Legacy behavior is to always paint the menu item background. // The correct behavior is to only paint the background if the menu item is // enabled. - if (item.Enabled) { + if (item.Enabled) + { g.FillRectangle(SystemBrushes.Highlight, fillRect); } @@ -395,144 +482,161 @@ protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs SystemColors.Highlight : ProfessionalColors.MenuItemBorder; // draw selection border - always drawn regardless of Enabled. - using (Pen p = new Pen(borderColor)) { + using (Pen p = new Pen(borderColor)) + { g.DrawRectangle(p, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); } } - else { - if (item.BackgroundImage != null) { + else + { + if (item.BackgroundImage != null) + { ControlPaint.DrawBackgroundImage(g, item.BackgroundImage, item.BackColor, item.BackgroundImageLayout, item.ContentRectangle, fillRect); } - else if (!ToolStripManager.VisualStylesEnabled && (item.RawBackColor != Color.Empty)) { + else if (!ToolStripManager.VisualStylesEnabled && (item.RawBackColor != Color.Empty)) + { FillBackground(g, fillRect, item.BackColor); } } } } - + } - + /// /// Draws a toolbar separator. ToolStrip users should override this function to change the /// drawing of all separators. /// - protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e) { - RenderSeparatorInternal(e.Graphics, e.Item, new Rectangle(Point.Empty, e.Item.Size), e.Vertical); + protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e) + { + RenderSeparatorInternal(e.Graphics, e.Item, new Rectangle(Point.Empty, e.Item.Size), e.Vertical); } - - protected override void OnRenderToolStripStatusLabelBackground(ToolStripItemRenderEventArgs e) { + + protected override void OnRenderToolStripStatusLabelBackground(ToolStripItemRenderEventArgs e) + { RenderLabelInternal(e); ToolStripStatusLabel item = e.Item as ToolStripStatusLabel; - ControlPaint.DrawBorder3D(e.Graphics, new Rectangle(0,0,item.Width-1, item.Height-1), item.BorderStyle, (Border3DSide)item.BorderSides); + ControlPaint.DrawBorder3D(e.Graphics, new Rectangle(0, 0, item.Width - 1, item.Height - 1), item.BorderStyle, (Border3DSide)item.BorderSides); } /// /// Draw the item's background. /// - protected override void OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs e) { + protected override void OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs e) + { ToolStripSplitButton splitButton = e.Item as ToolStripSplitButton; Graphics g = e.Graphics; bool rightToLeft = (splitButton.RightToLeft == RightToLeft.Yes); - Color arrowColor = splitButton.Enabled ? SystemColors.ControlText : SystemColors.ControlDark; + Color arrowColor = splitButton.Enabled ? SystemColors.ControlText : SystemColors.ControlDark; + - // in right to left - we need to swap the parts so we dont draw v][ toolStripSplitButton VisualStyleElement splitButtonDropDownPart = (rightToLeft) ? VisualStyleElement.ToolBar.SplitButton.Normal : VisualStyleElement.ToolBar.SplitButtonDropDown.Normal; - VisualStyleElement splitButtonPart = (rightToLeft) ? VisualStyleElement.ToolBar.DropDownButton.Normal : VisualStyleElement.ToolBar.SplitButton.Normal; - - Rectangle bounds = new Rectangle(Point.Empty, splitButton.Size); + VisualStyleElement splitButtonPart = (rightToLeft) ? VisualStyleElement.ToolBar.DropDownButton.Normal : VisualStyleElement.ToolBar.SplitButton.Normal; + + Rectangle bounds = new Rectangle(Point.Empty, splitButton.Size); if (ToolStripManager.VisualStylesEnabled && VisualStyleRenderer.IsElementDefined(splitButtonDropDownPart) - && VisualStyleRenderer.IsElementDefined(splitButtonPart)) { - - VisualStyleRenderer vsRenderer = VisualStyleRenderer; - - - // Draw the SplitButton Button portion of it. - vsRenderer.SetParameters(splitButtonPart.ClassName, splitButtonPart.Part, GetSplitButtonItemState(splitButton)); - - - // the lovely Windows theming for split button comes in three pieces: - // SplitButtonDropDown: [ v | - // Separator: | - // SplitButton: | ] - // this is great except if you want to swap the button in RTL. In this case we need - // to use the DropDownButton instead of the SplitButtonDropDown and paint the arrow ourselves. - Rectangle splitButtonBounds = splitButton.ButtonBounds; - if (rightToLeft) { - // scoot to the left so we dont draw double shadow like so: ][ - splitButtonBounds.Inflate(2,0); - } - // Draw the button portion of it. - vsRenderer.DrawBackground(g, splitButtonBounds); - - // Draw the SplitButton DropDownButton portion of it. - vsRenderer.SetParameters(splitButtonDropDownPart.ClassName, splitButtonDropDownPart.Part, GetSplitButtonDropDownItemState(splitButton)); - - // Draw the drop down button portion - vsRenderer.DrawBackground(g, splitButton.DropDownButtonBounds); - - // fill in the background image - Rectangle fillRect = splitButton.ContentRectangle; - if (splitButton.BackgroundImage != null) { - ControlPaint.DrawBackgroundImage(g, splitButton.BackgroundImage, splitButton.BackColor, splitButton.BackgroundImageLayout, fillRect, fillRect); - } - - // draw the separator over it. - RenderSeparatorInternal(g,splitButton, splitButton.SplitterBounds, true); - - // and of course, now if we're in RTL we now need to paint the arrow - // because we're no longer using a part that has it built in. - if (rightToLeft || splitButton.BackgroundImage != null) { - DrawArrow(new ToolStripArrowRenderEventArgs(g, splitButton, splitButton.DropDownButtonBounds, arrowColor, ArrowDirection.Down)); - } - } - else { - + && VisualStyleRenderer.IsElementDefined(splitButtonPart)) + { + + VisualStyleRenderer vsRenderer = VisualStyleRenderer; + + + // Draw the SplitButton Button portion of it. + vsRenderer.SetParameters(splitButtonPart.ClassName, splitButtonPart.Part, GetSplitButtonItemState(splitButton)); + + + // the lovely Windows theming for split button comes in three pieces: + // SplitButtonDropDown: [ v | + // Separator: | + // SplitButton: | ] + // this is great except if you want to swap the button in RTL. In this case we need + // to use the DropDownButton instead of the SplitButtonDropDown and paint the arrow ourselves. + Rectangle splitButtonBounds = splitButton.ButtonBounds; + if (rightToLeft) + { + // scoot to the left so we dont draw double shadow like so: ][ + splitButtonBounds.Inflate(2, 0); + } + // Draw the button portion of it. + vsRenderer.DrawBackground(g, splitButtonBounds); + + // Draw the SplitButton DropDownButton portion of it. + vsRenderer.SetParameters(splitButtonDropDownPart.ClassName, splitButtonDropDownPart.Part, GetSplitButtonDropDownItemState(splitButton)); + + // Draw the drop down button portion + vsRenderer.DrawBackground(g, splitButton.DropDownButtonBounds); + + // fill in the background image + Rectangle fillRect = splitButton.ContentRectangle; + if (splitButton.BackgroundImage != null) + { + ControlPaint.DrawBackgroundImage(g, splitButton.BackgroundImage, splitButton.BackColor, splitButton.BackgroundImageLayout, fillRect, fillRect); + } + + // draw the separator over it. + RenderSeparatorInternal(g, splitButton, splitButton.SplitterBounds, true); + + // and of course, now if we're in RTL we now need to paint the arrow + // because we're no longer using a part that has it built in. + if (rightToLeft || splitButton.BackgroundImage != null) + { + DrawArrow(new ToolStripArrowRenderEventArgs(g, splitButton, splitButton.DropDownButtonBounds, arrowColor, ArrowDirection.Down)); + } + } + else + { + // Draw the split button button Rectangle splitButtonButtonRect = splitButton.ButtonBounds; - if (splitButton.BackgroundImage != null) { - // fill in the background image - Rectangle fillRect = (splitButton.Selected) ? splitButton.ContentRectangle :bounds; - if (splitButton.BackgroundImage != null) { - ControlPaint.DrawBackgroundImage(g, splitButton.BackgroundImage, splitButton.BackColor, splitButton.BackgroundImageLayout, bounds, fillRect); + if (splitButton.BackgroundImage != null) + { + // fill in the background image + Rectangle fillRect = (splitButton.Selected) ? splitButton.ContentRectangle : bounds; + if (splitButton.BackgroundImage != null) + { + ControlPaint.DrawBackgroundImage(g, splitButton.BackgroundImage, splitButton.BackColor, splitButton.BackgroundImageLayout, bounds, fillRect); } } - else { - FillBackground(g,splitButtonButtonRect, splitButton.BackColor); + else + { + FillBackground(g, splitButtonButtonRect, splitButton.BackColor); } - + ToolBarState state = GetSplitButtonToolBarState(splitButton, false); RenderSmall3DBorderInternal(g, splitButtonButtonRect, state, rightToLeft); - + // draw the split button drop down Rectangle dropDownRect = splitButton.DropDownButtonBounds; // fill the color in the dropdown button - if (splitButton.BackgroundImage == null) { + if (splitButton.BackgroundImage == null) + { FillBackground(g, dropDownRect, splitButton.BackColor); } - + state = GetSplitButtonToolBarState(splitButton, true); - - if ((state == ToolBarState.Pressed) || (state == ToolBarState.Hot)) { + + if ((state == ToolBarState.Pressed) || (state == ToolBarState.Hot)) + { RenderSmall3DBorderInternal(g, dropDownRect, state, rightToLeft); } - + DrawArrow(new ToolStripArrowRenderEventArgs(g, splitButton, dropDownRect, arrowColor, ArrowDirection.Down)); - + } - + } - + /// /// This exists mainly so that buttons, labels and items, etc can share the same implementation. /// If OnRenderButton called OnRenderItem we would never be able to change the implementation @@ -542,85 +646,99 @@ protected override void OnRenderSplitButtonBackground(ToolStripItemRenderEventAr /// everyone should just call this private shared method. Users need to override each item they want /// to change the look and feel of. /// - private void RenderItemInternal(ToolStripItemRenderEventArgs e) { + private void RenderItemInternal(ToolStripItemRenderEventArgs e) + { ToolStripItem item = e.Item; Graphics g = e.Graphics; - + ToolBarState state = GetToolBarState(item); VisualStyleElement toolBarElement = VisualStyleElement.ToolBar.Button.Normal; - - if (ToolStripManager.VisualStylesEnabled - && (VisualStyleRenderer.IsElementDefined(toolBarElement))) { - + + if (ToolStripManager.VisualStylesEnabled + && (VisualStyleRenderer.IsElementDefined(toolBarElement))) + { + VisualStyleRenderer vsRenderer = VisualStyleRenderer; vsRenderer.SetParameters(toolBarElement.ClassName, toolBarElement.Part, (int)state); vsRenderer.DrawBackground(g, new Rectangle(Point.Empty, item.Size)); } - else { + else + { RenderSmall3DBorderInternal(g, new Rectangle(Point.Empty, item.Size), state, (item.RightToLeft == RightToLeft.Yes)); - } + } Rectangle fillRect = item.ContentRectangle; - if (item.BackgroundImage != null) { + if (item.BackgroundImage != null) + { ControlPaint.DrawBackgroundImage(g, item.BackgroundImage, item.BackColor, item.BackgroundImageLayout, fillRect, fillRect); } - else { + else + { ToolStrip parent = item.GetCurrentParent(); - if ((parent != null) && (state != ToolBarState.Checked) && (item.BackColor != parent.BackColor)) { + if ((parent != null) && (state != ToolBarState.Checked) && (item.BackColor != parent.BackColor)) + { FillBackground(g, fillRect, item.BackColor); } } } - + /// /// - private void RenderSeparatorInternal(Graphics g, ToolStripItem item, Rectangle bounds, bool vertical) { + private void RenderSeparatorInternal(Graphics g, ToolStripItem item, Rectangle bounds, bool vertical) + { VisualStyleElement separator = (vertical) ? VisualStyleElement.ToolBar.SeparatorHorizontal.Normal : VisualStyleElement.ToolBar.SeparatorVertical.Normal; - + if (ToolStripManager.VisualStylesEnabled - && (VisualStyleRenderer.IsElementDefined(separator))){ + && (VisualStyleRenderer.IsElementDefined(separator))) + { VisualStyleRenderer vsRenderer = VisualStyleRenderer; - + vsRenderer.SetParameters(separator.ClassName, separator.Part, GetItemState(item)); vsRenderer.DrawBackground(g, bounds); } - else { - - Color foreColor = item.ForeColor; - Color backColor = item.BackColor; - - Pen foreColorPen = SystemPens.ControlDark; - bool disposeForeColorPen = GetPen(foreColor, ref foreColorPen); - - try { - if (vertical) { - if (bounds.Height >= 4) { - bounds.Inflate(0,-2); // scoot down 2PX and start drawing - } - - bool rightToLeft = (item.RightToLeft == RightToLeft.Yes); - Pen leftPen = (rightToLeft) ? SystemPens.ButtonHighlight : foreColorPen; - Pen rightPen = (rightToLeft) ? foreColorPen : SystemPens.ButtonHighlight; - - // Draw dark line - int startX = bounds.Width / 2; - g.DrawLine(leftPen, startX, bounds.Top, startX, bounds.Bottom); - - // Draw highlight one pixel to the right - startX++; - g.DrawLine(rightPen, startX, bounds.Top, startX, bounds.Bottom); - - } - else { - // - // horizontal separator - if (bounds.Width >= 4) { - bounds.Inflate(-2,0); // scoot over 2PX and start drawing - } + else + { + + Color foreColor = item.ForeColor; + Color backColor = item.BackColor; + + Pen foreColorPen = SystemPens.ControlDark; + bool disposeForeColorPen = GetPen(foreColor, ref foreColorPen); + + try + { + if (vertical) + { + if (bounds.Height >= 4) + { + bounds.Inflate(0, -2); // scoot down 2PX and start drawing + } + + bool rightToLeft = (item.RightToLeft == RightToLeft.Yes); + Pen leftPen = (rightToLeft) ? SystemPens.ButtonHighlight : foreColorPen; + Pen rightPen = (rightToLeft) ? foreColorPen : SystemPens.ButtonHighlight; + + // Draw dark line + int startX = bounds.Width / 2; + g.DrawLine(leftPen, startX, bounds.Top, startX, bounds.Bottom); + + // Draw highlight one pixel to the right + startX++; + g.DrawLine(rightPen, startX, bounds.Top, startX, bounds.Bottom); + + } + else + { + // + // horizontal separator + if (bounds.Width >= 4) + { + bounds.Inflate(-2, 0); // scoot over 2PX and start drawing + } // Draw dark line int startY = bounds.Height / 2; @@ -630,69 +748,83 @@ private void RenderSeparatorInternal(Graphics g, ToolStripItem item, Rectangle b startY++; g.DrawLine(SystemPens.ButtonHighlight, bounds.Left, startY, bounds.Right, startY); } - - } - finally { - if (disposeForeColorPen && foreColorPen != null) { - foreColorPen.Dispose(); + + } + finally + { + if (disposeForeColorPen && foreColorPen != null) + { + foreColorPen.Dispose(); } - } + } } } - private void RenderSmall3DBorderInternal (Graphics g, Rectangle bounds, ToolBarState state, bool rightToLeft) { - if ((state == ToolBarState.Hot) ||(state == ToolBarState.Pressed) || (state == ToolBarState.Checked)) { - Pen leftPen, topPen, rightPen,bottomPen; - topPen = (state == ToolBarState.Hot) ? SystemPens.ButtonHighlight : SystemPens.ButtonShadow; - bottomPen = (state == ToolBarState.Hot)? SystemPens.ButtonShadow : SystemPens.ButtonHighlight; + private void RenderSmall3DBorderInternal(Graphics g, Rectangle bounds, ToolBarState state, bool rightToLeft) + { + if ((state == ToolBarState.Hot) || (state == ToolBarState.Pressed) || (state == ToolBarState.Checked)) + { + Pen leftPen, topPen, rightPen, bottomPen; + topPen = (state == ToolBarState.Hot) ? SystemPens.ButtonHighlight : SystemPens.ButtonShadow; + bottomPen = (state == ToolBarState.Hot) ? SystemPens.ButtonShadow : SystemPens.ButtonHighlight; - leftPen = (rightToLeft) ? bottomPen : topPen; - rightPen = (rightToLeft) ? topPen : bottomPen; + leftPen = (rightToLeft) ? bottomPen : topPen; + rightPen = (rightToLeft) ? topPen : bottomPen; + + g.DrawLine(topPen, bounds.Left, bounds.Top, bounds.Right - 1, bounds.Top); + g.DrawLine(leftPen, bounds.Left, bounds.Top, bounds.Left, bounds.Bottom - 1); + g.DrawLine(rightPen, bounds.Right - 1, bounds.Top, bounds.Right - 1, bounds.Bottom - 1); + g.DrawLine(bottomPen, bounds.Left, bounds.Bottom - 1, bounds.Right - 1, bounds.Bottom - 1); - g.DrawLine(topPen, bounds.Left, bounds.Top, bounds.Right -1, bounds.Top); - g.DrawLine(leftPen, bounds.Left, bounds.Top, bounds.Left, bounds.Bottom-1); - g.DrawLine(rightPen, bounds.Right-1, bounds.Top, bounds.Right -1, bounds.Bottom-1); - g.DrawLine(bottomPen, bounds.Left, bounds.Bottom-1, bounds.Right -1, bounds.Bottom -1); - } } - private void RenderStatusStripBorder(ToolStripRenderEventArgs e) { - if (!Application.RenderWithVisualStyles) { - e.Graphics.DrawLine(SystemPens.ButtonHighlight, 0,0,e.ToolStrip.Width, 0); + private void RenderStatusStripBorder(ToolStripRenderEventArgs e) + { + if (!Application.RenderWithVisualStyles) + { + e.Graphics.DrawLine(SystemPens.ButtonHighlight, 0, 0, e.ToolStrip.Width, 0); } } - private static void RenderStatusStripBackground(ToolStripRenderEventArgs e) { - if (Application.RenderWithVisualStyles) { + private static void RenderStatusStripBackground(ToolStripRenderEventArgs e) + { + if (Application.RenderWithVisualStyles) + { VisualStyleRenderer vsRenderer = VisualStyleRenderer; vsRenderer.SetParameters(VisualStyleElement.Status.Bar.Normal); - vsRenderer.DrawBackground(e.Graphics,new Rectangle(0,0,e.ToolStrip.Width-1, e.ToolStrip.Height-1)); + vsRenderer.DrawBackground(e.Graphics, new Rectangle(0, 0, e.ToolStrip.Width - 1, e.ToolStrip.Height - 1)); } - else { - if (!SystemInformation.InLockedTerminalSession()) { + else + { + if (!SystemInformation.InLockedTerminalSession()) + { e.Graphics.Clear(e.BackColor); } } } - - private static void RenderLabelInternal(ToolStripItemRenderEventArgs e) { - // dont call RenderItemInternal, as we NEVER want to paint hot. - ToolStripItem item = e.Item; - Graphics g = e.Graphics; - - Rectangle fillRect = item.ContentRectangle; - - if (item.BackgroundImage != null) { + + private static void RenderLabelInternal(ToolStripItemRenderEventArgs e) + { + // dont call RenderItemInternal, as we NEVER want to paint hot. + ToolStripItem item = e.Item; + Graphics g = e.Graphics; + + Rectangle fillRect = item.ContentRectangle; + + if (item.BackgroundImage != null) + { ControlPaint.DrawBackgroundImage(g, item.BackgroundImage, item.BackColor, item.BackgroundImageLayout, fillRect, fillRect); - } - else { - VisualStyleRenderer vsRenderer = VisualStyleRenderer; - - if (vsRenderer == null || (item.BackColor != SystemColors.Control)) { - FillBackground(g, fillRect, item.BackColor); - } - } + } + else + { + VisualStyleRenderer vsRenderer = VisualStyleRenderer; + + if (vsRenderer == null || (item.BackColor != SystemColors.Control)) + { + FillBackground(g, fillRect, item.BackColor); + } + } } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripTextBox.cs index 8546e9e1324..f1949895c5a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripTextBox.cs @@ -16,35 +16,39 @@ namespace System.Windows.Forms public class ToolStripTextBox : ToolStripControlHost { - internal static readonly object EventTextBoxTextAlignChanged = new object(); - internal static readonly object EventAcceptsTabChanged = new object(); - internal static readonly object EventBorderStyleChanged = new object(); - internal static readonly object EventHideSelectionChanged = new object(); - internal static readonly object EventReadOnlyChanged = new object(); - internal static readonly object EventMultilineChanged = new object(); - internal static readonly object EventModifiedChanged = new object(); - + internal static readonly object EventTextBoxTextAlignChanged = new object(); + internal static readonly object EventAcceptsTabChanged = new object(); + internal static readonly object EventBorderStyleChanged = new object(); + internal static readonly object EventHideSelectionChanged = new object(); + internal static readonly object EventReadOnlyChanged = new object(); + internal static readonly object EventMultilineChanged = new object(); + internal static readonly object EventModifiedChanged = new object(); + private static readonly Padding defaultMargin = new Padding(1, 0, 1, 0); private static readonly Padding defaultDropDownMargin = new Padding(1); private Padding scaledDefaultMargin = defaultMargin; private Padding scaledDefaultDropDownMargin = defaultDropDownMargin; - public ToolStripTextBox() : base(CreateControlInstance()) { + public ToolStripTextBox() : base(CreateControlInstance()) + { ToolStripTextBoxControl textBox = Control as ToolStripTextBoxControl; textBox.Owner = this; - if (DpiHelper.IsScalingRequirementMet) { + if (DpiHelper.IsScalingRequirementMet) + { scaledDefaultMargin = DpiHelper.LogicalToDeviceUnits(defaultMargin); scaledDefaultDropDownMargin = DpiHelper.LogicalToDeviceUnits(defaultDropDownMargin); } } - public ToolStripTextBox(string name) : this() { + public ToolStripTextBox(string name) : this() + { this.Name = name; } - + [EditorBrowsable(EditorBrowsableState.Never)] - public ToolStripTextBox(Control c): base(c) { + public ToolStripTextBox(Control c) : base(c) + { throw new NotSupportedException(SR.ToolStripMustSupplyItsOwnTextBox); } @@ -53,11 +57,14 @@ public ToolStripTextBox(Control c): base(c) { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } @@ -67,69 +74,88 @@ public override Image BackgroundImage { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } - + /// /// 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. /// - protected internal override Padding DefaultMargin { - get { - if (IsOnDropDown) { + protected internal override Padding DefaultMargin + { + get + { + if (IsOnDropDown) + { return scaledDefaultDropDownMargin; } - else { + else + { return scaledDefaultMargin; } } } - protected override Size DefaultSize { - get { - return new Size(100,22); + protected override Size DefaultSize + { + get + { + return new Size(100, 22); } } [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public TextBox TextBox { - get{ + public TextBox TextBox + { + get + { return Control as TextBox; } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new ToolStripTextBoxAccessibleObject(this); } [System.Runtime.InteropServices.ComVisible(true)] - internal class ToolStripTextBoxAccessibleObject : ToolStripItemAccessibleObject { + internal class ToolStripTextBoxAccessibleObject : ToolStripItemAccessibleObject + { private ToolStripTextBox ownerItem = null; - public ToolStripTextBoxAccessibleObject(ToolStripTextBox ownerItem) : base(ownerItem) { - this.ownerItem = ownerItem; + public ToolStripTextBoxAccessibleObject(ToolStripTextBox ownerItem) : base(ownerItem) + { + this.ownerItem = ownerItem; } - - public override AccessibleRole Role { - get { - AccessibleRole role = Owner.AccessibleRole; - if (role != AccessibleRole.Default) { - return role; - } - return AccessibleRole.Text; - } + public override AccessibleRole Role + { + get + { + AccessibleRole role = Owner.AccessibleRole; + if (role != AccessibleRole.Default) + { + return role; + } + + return AccessibleRole.Text; + } } - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { if (direction == UnsafeNativeMethods.NavigateDirection.FirstChild || - direction == UnsafeNativeMethods.NavigateDirection.LastChild) { + direction == UnsafeNativeMethods.NavigateDirection.LastChild) + { return this.ownerItem.TextBox.AccessibilityObject; } @@ -138,110 +164,131 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga } } - private static Control CreateControlInstance() { - TextBox textBox = new ToolStripTextBoxControl(); + private static Control CreateControlInstance() + { + TextBox textBox = new ToolStripTextBoxControl(); textBox.BorderStyle = BorderStyle.Fixed3D; textBox.AutoSize = true; return textBox; } - - public override Size GetPreferredSize(Size constrainingSize) { + + public override Size GetPreferredSize(Size constrainingSize) + { // dont call TextBox.GPS because it will grow and shrink as the text changes. Rectangle bounds = CommonProperties.GetSpecifiedBounds(TextBox); - return new Size(bounds.Width, TextBox.PreferredHeight); + return new Size(bounds.Width, TextBox.PreferredHeight); } - private void HandleAcceptsTabChanged(object sender, EventArgs e) { + private void HandleAcceptsTabChanged(object sender, EventArgs e) + { OnAcceptsTabChanged(e); } - private void HandleBorderStyleChanged(object sender, EventArgs e) { + private void HandleBorderStyleChanged(object sender, EventArgs e) + { OnBorderStyleChanged(e); } - private void HandleHideSelectionChanged(object sender, EventArgs e) { + private void HandleHideSelectionChanged(object sender, EventArgs e) + { OnHideSelectionChanged(e); } - private void HandleModifiedChanged(object sender, EventArgs e) { + private void HandleModifiedChanged(object sender, EventArgs e) + { OnModifiedChanged(e); - } - private void HandleMultilineChanged(object sender, EventArgs e) { + } + private void HandleMultilineChanged(object sender, EventArgs e) + { OnMultilineChanged(e); - } - private void HandleReadOnlyChanged(object sender, EventArgs e) { + } + private void HandleReadOnlyChanged(object sender, EventArgs e) + { OnReadOnlyChanged(e); - } - private void HandleTextBoxTextAlignChanged(object sender, EventArgs e) { + } + private void HandleTextBoxTextAlignChanged(object sender, EventArgs e) + { RaiseEvent(EventTextBoxTextAlignChanged, e); - } - protected virtual void OnAcceptsTabChanged(EventArgs e) { - RaiseEvent(EventAcceptsTabChanged, e); } - protected virtual void OnBorderStyleChanged(EventArgs e) { - RaiseEvent(EventBorderStyleChanged, e); + protected virtual void OnAcceptsTabChanged(EventArgs e) + { + RaiseEvent(EventAcceptsTabChanged, e); + } + protected virtual void OnBorderStyleChanged(EventArgs e) + { + RaiseEvent(EventBorderStyleChanged, e); } - protected virtual void OnHideSelectionChanged(EventArgs e) { - RaiseEvent(EventHideSelectionChanged, e); + protected virtual void OnHideSelectionChanged(EventArgs e) + { + RaiseEvent(EventHideSelectionChanged, e); } - protected virtual void OnModifiedChanged(EventArgs e) { - RaiseEvent(EventModifiedChanged, e); + protected virtual void OnModifiedChanged(EventArgs e) + { + RaiseEvent(EventModifiedChanged, e); } - protected virtual void OnMultilineChanged(EventArgs e) { - RaiseEvent(EventMultilineChanged, e); + protected virtual void OnMultilineChanged(EventArgs e) + { + RaiseEvent(EventMultilineChanged, e); } - protected virtual void OnReadOnlyChanged(EventArgs e) { - RaiseEvent(EventReadOnlyChanged, e); + protected virtual void OnReadOnlyChanged(EventArgs e) + { + RaiseEvent(EventReadOnlyChanged, e); } - protected override void OnSubscribeControlEvents(Control control) { + protected override void OnSubscribeControlEvents(Control control) + { TextBox textBox = control as TextBox; - if (textBox != null) { + if (textBox != null) + { // Please keep this alphabetized and in sync with Unsubscribe // - textBox.AcceptsTabChanged += new EventHandler(HandleAcceptsTabChanged); - textBox.BorderStyleChanged += new EventHandler(HandleBorderStyleChanged); - textBox.HideSelectionChanged += new EventHandler(HandleHideSelectionChanged); - textBox.ModifiedChanged += new EventHandler(HandleModifiedChanged); - textBox.MultilineChanged += new EventHandler(HandleMultilineChanged); - textBox.ReadOnlyChanged += new EventHandler(HandleReadOnlyChanged); - textBox.TextAlignChanged += new EventHandler(HandleTextBoxTextAlignChanged); - - } - + textBox.AcceptsTabChanged += new EventHandler(HandleAcceptsTabChanged); + textBox.BorderStyleChanged += new EventHandler(HandleBorderStyleChanged); + textBox.HideSelectionChanged += new EventHandler(HandleHideSelectionChanged); + textBox.ModifiedChanged += new EventHandler(HandleModifiedChanged); + textBox.MultilineChanged += new EventHandler(HandleMultilineChanged); + textBox.ReadOnlyChanged += new EventHandler(HandleReadOnlyChanged); + textBox.TextAlignChanged += new EventHandler(HandleTextBoxTextAlignChanged); + + } + base.OnSubscribeControlEvents(control); } - - protected override void OnUnsubscribeControlEvents(Control control) { - - TextBox textBox = control as TextBox; - if (textBox != null) { - // Please keep this alphabetized and in sync with Subscribe - // - textBox.AcceptsTabChanged -= new EventHandler(HandleAcceptsTabChanged); - textBox.BorderStyleChanged -= new EventHandler(HandleBorderStyleChanged); - textBox.HideSelectionChanged -= new EventHandler(HandleHideSelectionChanged); - textBox.ModifiedChanged -= new EventHandler(HandleModifiedChanged); - textBox.MultilineChanged -= new EventHandler(HandleMultilineChanged); - textBox.ReadOnlyChanged -= new EventHandler(HandleReadOnlyChanged); - textBox.TextAlignChanged -= new EventHandler(HandleTextBoxTextAlignChanged); - } - base.OnUnsubscribeControlEvents(control); - - } - - internal override bool ShouldSerializeFont() { + + protected override void OnUnsubscribeControlEvents(Control control) + { + + TextBox textBox = control as TextBox; + if (textBox != null) + { + // Please keep this alphabetized and in sync with Subscribe + // + textBox.AcceptsTabChanged -= new EventHandler(HandleAcceptsTabChanged); + textBox.BorderStyleChanged -= new EventHandler(HandleBorderStyleChanged); + textBox.HideSelectionChanged -= new EventHandler(HandleHideSelectionChanged); + textBox.ModifiedChanged -= new EventHandler(HandleModifiedChanged); + textBox.MultilineChanged -= new EventHandler(HandleMultilineChanged); + textBox.ReadOnlyChanged -= new EventHandler(HandleReadOnlyChanged); + textBox.TextAlignChanged -= new EventHandler(HandleTextBoxTextAlignChanged); + } + base.OnUnsubscribeControlEvents(control); + + } + + internal override bool ShouldSerializeFont() + { return Font != ToolStripManager.DefaultFont; } - -#region WrappedProperties + + #region WrappedProperties [ SRCategory(nameof(SR.CatBehavior)), DefaultValue(false), SRDescription(nameof(SR.TextBoxAcceptsTabDescr)) ] - public bool AcceptsTab { - get { return TextBox.AcceptsTab; } + public bool AcceptsTab + { + get { return TextBox.AcceptsTab; } set { TextBox.AcceptsTab = value; } } @@ -250,8 +297,9 @@ public bool AcceptsTab { DefaultValue(false), SRDescription(nameof(SR.TextBoxAcceptsReturnDescr)) ] - public bool AcceptsReturn { - get { return TextBox.AcceptsReturn; } + public bool AcceptsReturn + { + get { return TextBox.AcceptsReturn; } set { TextBox.AcceptsReturn = value; } } @@ -262,8 +310,9 @@ public bool AcceptsReturn { Editor("System.Windows.Forms.Design.ListControlStringCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), Browsable(true), EditorBrowsable(EditorBrowsableState.Always) ] - public System.Windows.Forms.AutoCompleteStringCollection AutoCompleteCustomSource { - get { return TextBox.AutoCompleteCustomSource; } + public System.Windows.Forms.AutoCompleteStringCollection AutoCompleteCustomSource + { + get { return TextBox.AutoCompleteCustomSource; } set { TextBox.AutoCompleteCustomSource = value; } } @@ -272,8 +321,9 @@ public System.Windows.Forms.AutoCompleteStringCollection AutoCompleteCustomSourc SRDescription(nameof(SR.TextBoxAutoCompleteModeDescr)), Browsable(true), EditorBrowsable(EditorBrowsableState.Always) ] - public AutoCompleteMode AutoCompleteMode { - get { return TextBox.AutoCompleteMode; } + public AutoCompleteMode AutoCompleteMode + { + get { return TextBox.AutoCompleteMode; } set { TextBox.AutoCompleteMode = value; } } @@ -282,8 +332,9 @@ public AutoCompleteMode AutoCompleteMode { SRDescription(nameof(SR.TextBoxAutoCompleteSourceDescr)), Browsable(true), EditorBrowsable(EditorBrowsableState.Always) ] - public AutoCompleteSource AutoCompleteSource { - get { return TextBox.AutoCompleteSource; } + public AutoCompleteSource AutoCompleteSource + { + get { return TextBox.AutoCompleteSource; } set { TextBox.AutoCompleteSource = value; } } @@ -293,8 +344,9 @@ public AutoCompleteSource AutoCompleteSource { DispId(NativeMethods.ActiveX.DISPID_BORDERSTYLE), SRDescription(nameof(SR.TextBoxBorderDescr)) ] - public BorderStyle BorderStyle { - get { return TextBox.BorderStyle; } + public BorderStyle BorderStyle + { + get { return TextBox.BorderStyle; } set { TextBox.BorderStyle = value; } } @@ -304,8 +356,9 @@ public BorderStyle BorderStyle { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.TextBoxCanUndoDescr)) ] - public bool CanUndo { - get { return TextBox.CanUndo; } + public bool CanUndo + { + get { return TextBox.CanUndo; } } [ @@ -313,8 +366,9 @@ public bool CanUndo { DefaultValue(CharacterCasing.Normal), SRDescription(nameof(SR.TextBoxCharacterCasingDescr)) ] - public CharacterCasing CharacterCasing { - get { return TextBox.CharacterCasing; } + public CharacterCasing CharacterCasing + { + get { return TextBox.CharacterCasing; } set { TextBox.CharacterCasing = value; } } @@ -323,8 +377,9 @@ public CharacterCasing CharacterCasing { DefaultValue(true), SRDescription(nameof(SR.TextBoxHideSelectionDescr)) ] - public bool HideSelection { - get { return TextBox.HideSelection; } + public bool HideSelection + { + get { return TextBox.HideSelection; } set { TextBox.HideSelection = value; } } @@ -335,8 +390,9 @@ public bool HideSelection { SRDescription(nameof(SR.TextBoxLinesDescr)), Editor("System.Windows.Forms.Design.StringArrayEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)) ] - public string[] Lines { - get { return TextBox.Lines; } + public string[] Lines + { + get { return TextBox.Lines; } set { TextBox.Lines = value; } } @@ -346,7 +402,8 @@ public string[] Lines { Localizable(true), SRDescription(nameof(SR.TextBoxMaxLengthDescr)) ] - public int MaxLength { + public int MaxLength + { get { return TextBox.MaxLength; } set { TextBox.MaxLength = value; } } @@ -357,7 +414,8 @@ public int MaxLength { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.TextBoxModifiedDescr)) ] - public bool Modified { + public bool Modified + { get { return TextBox.Modified; } set { TextBox.Modified = value; } } @@ -368,9 +426,10 @@ public bool Modified { Localizable(true), SRDescription(nameof(SR.TextBoxMultilineDescr)), RefreshProperties(RefreshProperties.All), - Browsable(false),EditorBrowsable(EditorBrowsableState.Never) + Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public bool Multiline { + public bool Multiline + { get { return TextBox.Multiline; } set { TextBox.Multiline = value; } } @@ -380,7 +439,8 @@ public bool Multiline { DefaultValue(false), SRDescription(nameof(SR.TextBoxReadOnlyDescr)) ] - public bool ReadOnly { + public bool ReadOnly + { get { return TextBox.ReadOnly; } set { TextBox.ReadOnly = value; } } @@ -390,18 +450,20 @@ public bool ReadOnly { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.TextBoxSelectedTextDescr)) ] - public string SelectedText { + public string SelectedText + { get { return TextBox.SelectedText; } set { TextBox.SelectedText = value; } } - + [ SRCategory(nameof(SR.CatAppearance)), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.TextBoxSelectionLengthDescr)) ] - public int SelectionLength { + public int SelectionLength + { get { return TextBox.SelectionLength; } set { TextBox.SelectionLength = value; } } @@ -411,7 +473,8 @@ public int SelectionLength { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.TextBoxSelectionStartDescr)) ] - public int SelectionStart { + public int SelectionStart + { get { return TextBox.SelectionStart; } set { TextBox.SelectionStart = value; } } @@ -420,391 +483,469 @@ public int SelectionStart { DefaultValue(true), SRDescription(nameof(SR.TextBoxShortcutsEnabledDescr)) ] - public bool ShortcutsEnabled { + public bool ShortcutsEnabled + { get { return TextBox.ShortcutsEnabled; } set { TextBox.ShortcutsEnabled = value; } } [Browsable(false)] - public int TextLength { + public int TextLength + { get { return TextBox.TextLength; } } - + [ Localizable(true), SRCategory(nameof(SR.CatAppearance)), DefaultValue(HorizontalAlignment.Left), SRDescription(nameof(SR.TextBoxTextAlignDescr)) ] - public HorizontalAlignment TextBoxTextAlign { - get { return TextBox.TextAlign; } + public HorizontalAlignment TextBoxTextAlign + { + get { return TextBox.TextAlign; } set { TextBox.TextAlign = value; } } - + [ SRCategory(nameof(SR.CatBehavior)), Localizable(true), DefaultValue(true), SRDescription(nameof(SR.TextBoxWordWrapDescr)), - Browsable(false),EditorBrowsable(EditorBrowsableState.Never) + Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public bool WordWrap { - get { return TextBox.WordWrap; } + public bool WordWrap + { + get { return TextBox.WordWrap; } set { TextBox.WordWrap = value; } } - - -#endregion WrappedProperties - -#region WrappedEvents - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.TextBoxBaseOnAcceptsTabChangedDescr))] - public event EventHandler AcceptsTabChanged { + #endregion WrappedProperties + + + + #region WrappedEvents + [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.TextBoxBaseOnAcceptsTabChangedDescr))] + public event EventHandler AcceptsTabChanged + { add => Events.AddHandler(EventAcceptsTabChanged, value); remove => Events.RemoveHandler(EventAcceptsTabChanged, value); } - + [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.TextBoxBaseOnBorderStyleChangedDescr))] - public event EventHandler BorderStyleChanged { + public event EventHandler BorderStyleChanged + { add => Events.AddHandler(EventBorderStyleChanged, value); remove => Events.RemoveHandler(EventBorderStyleChanged, value); } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.TextBoxBaseOnHideSelectionChangedDescr))] - public event EventHandler HideSelectionChanged { + public event EventHandler HideSelectionChanged + { add => Events.AddHandler(EventHideSelectionChanged, value); remove => Events.RemoveHandler(EventHideSelectionChanged, value); } - + [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.TextBoxBaseOnModifiedChangedDescr))] - public event EventHandler ModifiedChanged { + public event EventHandler ModifiedChanged + { add => Events.AddHandler(EventModifiedChanged, value); remove => Events.RemoveHandler(EventModifiedChanged, value); } - [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.TextBoxBaseOnMultilineChangedDescr)),Browsable(false),EditorBrowsable(EditorBrowsableState.Never)] - public event EventHandler MultilineChanged { - add => Events.AddHandler(EventMultilineChanged, value); - remove => Events.RemoveHandler(EventMultilineChanged, value); + [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.TextBoxBaseOnMultilineChangedDescr)), Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] + public event EventHandler MultilineChanged + { + add => Events.AddHandler(EventMultilineChanged, value); + remove => Events.RemoveHandler(EventMultilineChanged, value); } - + [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.TextBoxBaseOnReadOnlyChangedDescr))] - public event EventHandler ReadOnlyChanged { - add => Events.AddHandler(EventReadOnlyChanged, value); - remove => Events.RemoveHandler(EventReadOnlyChanged, value); + public event EventHandler ReadOnlyChanged + { + add => Events.AddHandler(EventReadOnlyChanged, value); + remove => Events.RemoveHandler(EventReadOnlyChanged, value); } - + [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ToolStripTextBoxTextBoxTextAlignChangedDescr))] - public event EventHandler TextBoxTextAlignChanged { + public event EventHandler TextBoxTextAlignChanged + { add => Events.AddHandler(EventTextBoxTextAlignChanged, value); remove => Events.RemoveHandler(EventTextBoxTextAlignChanged, value); } -#endregion WrappedEvents - -#region WrappedMethods - public void AppendText(string text) { TextBox.AppendText(text); } - public void Clear(){ TextBox.Clear(); } - public void ClearUndo() {TextBox.ClearUndo(); } - public void Copy() {TextBox.Copy(); } - public void Cut() {TextBox.Copy(); } - public void DeselectAll() { TextBox.DeselectAll(); } - public char GetCharFromPosition(System.Drawing.Point pt) { return TextBox.GetCharFromPosition(pt); } - public int GetCharIndexFromPosition(System.Drawing.Point pt) { return TextBox.GetCharIndexFromPosition(pt); } - public int GetFirstCharIndexFromLine(int lineNumber) { return TextBox.GetFirstCharIndexFromLine(lineNumber); } - public int GetFirstCharIndexOfCurrentLine() { return TextBox.GetFirstCharIndexOfCurrentLine(); } - public int GetLineFromCharIndex(int index) { return TextBox.GetLineFromCharIndex(index); } - public System.Drawing.Point GetPositionFromCharIndex(int index) { return TextBox.GetPositionFromCharIndex(index); } - public void Paste() { TextBox.Paste(); } - public void ScrollToCaret() { TextBox.ScrollToCaret(); } - public void Select(int start, int length) { TextBox.Select(start, length); } - public void SelectAll() { TextBox.SelectAll(); } - public void Undo() { TextBox.Undo(); } -#endregion - private class ToolStripTextBoxControl : TextBox { - private bool mouseIsOver = false; - private ToolStripTextBox ownerItem; - private bool isFontSet = true; - private bool alreadyHooked; - - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1805:DoNotInitializeUnnecessarily")] // FXCop doesnt understand that setting Font changes the value of isFontSet - public ToolStripTextBoxControl() { - // required to make the text box height match the combo. - this.Font = ToolStripManager.DefaultFont; - isFontSet = false; - } + #endregion WrappedEvents + + #region WrappedMethods + public void AppendText(string text) { TextBox.AppendText(text); } + public void Clear() { TextBox.Clear(); } + public void ClearUndo() { TextBox.ClearUndo(); } + public void Copy() { TextBox.Copy(); } + public void Cut() { TextBox.Copy(); } + public void DeselectAll() { TextBox.DeselectAll(); } + public char GetCharFromPosition(System.Drawing.Point pt) { return TextBox.GetCharFromPosition(pt); } + public int GetCharIndexFromPosition(System.Drawing.Point pt) { return TextBox.GetCharIndexFromPosition(pt); } + public int GetFirstCharIndexFromLine(int lineNumber) { return TextBox.GetFirstCharIndexFromLine(lineNumber); } + public int GetFirstCharIndexOfCurrentLine() { return TextBox.GetFirstCharIndexOfCurrentLine(); } + public int GetLineFromCharIndex(int index) { return TextBox.GetLineFromCharIndex(index); } + public System.Drawing.Point GetPositionFromCharIndex(int index) { return TextBox.GetPositionFromCharIndex(index); } + public void Paste() { TextBox.Paste(); } + public void ScrollToCaret() { TextBox.ScrollToCaret(); } + public void Select(int start, int length) { TextBox.Select(start, length); } + public void SelectAll() { TextBox.SelectAll(); } + public void Undo() { TextBox.Undo(); } + #endregion + private class ToolStripTextBoxControl : TextBox + { + private bool mouseIsOver = false; + private ToolStripTextBox ownerItem; + private bool isFontSet = true; + private bool alreadyHooked; + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1805:DoNotInitializeUnnecessarily")] // FXCop doesnt understand that setting Font changes the value of isFontSet + public ToolStripTextBoxControl() + { + // required to make the text box height match the combo. + this.Font = ToolStripManager.DefaultFont; + isFontSet = false; + } - - // returns the distance from the client rect to the upper left hand corner of the control - private NativeMethods.RECT AbsoluteClientRECT { - get { - NativeMethods.RECT rect = new NativeMethods.RECT(); - CreateParams cp = CreateParams; - AdjustWindowRectEx(ref rect, cp.Style, HasMenu, cp.ExStyle); + // returns the distance from the client rect to the upper left hand corner of the control + private NativeMethods.RECT AbsoluteClientRECT + { + get + { + NativeMethods.RECT rect = new NativeMethods.RECT(); + CreateParams cp = CreateParams; - // the coordinates we get back are negative, we need to translate this back to positive. - int offsetX = -rect.left; // one to get back to 0,0, another to translate - int offsetY = -rect.top; + AdjustWindowRectEx(ref rect, cp.Style, HasMenu, cp.ExStyle); - // fetch the client rect, then apply the offset. - UnsafeNativeMethods.GetClientRect(new HandleRef(this, this.Handle), ref rect); + // the coordinates we get back are negative, we need to translate this back to positive. + int offsetX = -rect.left; // one to get back to 0,0, another to translate + int offsetY = -rect.top; - rect.left += offsetX; - rect.right += offsetX; - rect.top += offsetY; - rect.bottom += offsetY; - - return rect; - } - } - private Rectangle AbsoluteClientRectangle { - get { - NativeMethods.RECT rect = AbsoluteClientRECT; - return Rectangle.FromLTRB(rect.top, rect.top, rect.right, rect.bottom); - } - } + // fetch the client rect, then apply the offset. + UnsafeNativeMethods.GetClientRect(new HandleRef(this, this.Handle), ref rect); + + rect.left += offsetX; + rect.right += offsetX; + rect.top += offsetY; + rect.bottom += offsetY; - - private ProfessionalColorTable ColorTable { - get { - if (Owner != null) { - ToolStripProfessionalRenderer renderer = Owner.Renderer as ToolStripProfessionalRenderer; - if (renderer != null) { - return renderer.ColorTable; - } - } - return ProfessionalColors.ColorTable; - } + return rect; } - - private bool IsPopupTextBox { - get { - return ((BorderStyle == BorderStyle.Fixed3D) && - (Owner != null && (Owner.Renderer is ToolStripProfessionalRenderer))); - } + } + private Rectangle AbsoluteClientRectangle + { + get + { + NativeMethods.RECT rect = AbsoluteClientRECT; + return Rectangle.FromLTRB(rect.top, rect.top, rect.right, rect.bottom); } + } - internal bool MouseIsOver { - get { return mouseIsOver; } - set { - if (mouseIsOver != value) { - mouseIsOver = value; - if (!Focused) { - InvalidateNonClient(); - } + + private ProfessionalColorTable ColorTable + { + get + { + if (Owner != null) + { + ToolStripProfessionalRenderer renderer = Owner.Renderer as ToolStripProfessionalRenderer; + if (renderer != null) + { + return renderer.ColorTable; } } + return ProfessionalColors.ColorTable; } + } - public override Font Font { - get { return base.Font; } - set { - base.Font = value; - isFontSet = ShouldSerializeFont(); + private bool IsPopupTextBox + { + get + { + return ((BorderStyle == BorderStyle.Fixed3D) && + (Owner != null && (Owner.Renderer is ToolStripProfessionalRenderer))); + } + } + + internal bool MouseIsOver + { + get { return mouseIsOver; } + set + { + if (mouseIsOver != value) + { + mouseIsOver = value; + if (!Focused) + { + InvalidateNonClient(); + } } } + } - public ToolStripTextBox Owner { - get { return ownerItem; } - set { ownerItem = value; } + public override Font Font + { + get { return base.Font; } + set + { + base.Font = value; + isFontSet = ShouldSerializeFont(); } + } - internal override bool SupportsUiaProviders => true; + public ToolStripTextBox Owner + { + get { return ownerItem; } + set { ownerItem = value; } + } - private void InvalidateNonClient() { - if (!IsPopupTextBox) { - return; - } - NativeMethods.RECT absoluteClientRectangle = AbsoluteClientRECT; - HandleRef hNonClientRegion = NativeMethods.NullHandleRef; - HandleRef hClientRegion = NativeMethods.NullHandleRef; - HandleRef hTotalRegion = NativeMethods.NullHandleRef; - - try { - // get the total client area, then exclude the client by using XOR - hTotalRegion = new HandleRef(this, SafeNativeMethods.CreateRectRgn(0, 0, this.Width, this.Height)); - hClientRegion = new HandleRef(this, SafeNativeMethods.CreateRectRgn(absoluteClientRectangle.left, absoluteClientRectangle.top, absoluteClientRectangle.right, absoluteClientRectangle.bottom)); - hNonClientRegion = new HandleRef(this, SafeNativeMethods.CreateRectRgn(0,0,0,0)); - - SafeNativeMethods.CombineRgn(hNonClientRegion, hTotalRegion, hClientRegion, NativeMethods.RGN_XOR); - - // Call RedrawWindow with the region. - NativeMethods.RECT ignored = new NativeMethods.RECT(); - SafeNativeMethods.RedrawWindow(new HandleRef(this, Handle), - ref ignored , hNonClientRegion, - NativeMethods.RDW_INVALIDATE | NativeMethods.RDW_ERASE | - NativeMethods.RDW_UPDATENOW | NativeMethods.RDW_ERASENOW | - NativeMethods.RDW_FRAME); + internal override bool SupportsUiaProviders => true; + + private void InvalidateNonClient() + { + if (!IsPopupTextBox) + { + return; + } + NativeMethods.RECT absoluteClientRectangle = AbsoluteClientRECT; + HandleRef hNonClientRegion = NativeMethods.NullHandleRef; + HandleRef hClientRegion = NativeMethods.NullHandleRef; + HandleRef hTotalRegion = NativeMethods.NullHandleRef; + + try + { + // get the total client area, then exclude the client by using XOR + hTotalRegion = new HandleRef(this, SafeNativeMethods.CreateRectRgn(0, 0, this.Width, this.Height)); + hClientRegion = new HandleRef(this, SafeNativeMethods.CreateRectRgn(absoluteClientRectangle.left, absoluteClientRectangle.top, absoluteClientRectangle.right, absoluteClientRectangle.bottom)); + hNonClientRegion = new HandleRef(this, SafeNativeMethods.CreateRectRgn(0, 0, 0, 0)); + + SafeNativeMethods.CombineRgn(hNonClientRegion, hTotalRegion, hClientRegion, NativeMethods.RGN_XOR); + + // Call RedrawWindow with the region. + NativeMethods.RECT ignored = new NativeMethods.RECT(); + SafeNativeMethods.RedrawWindow(new HandleRef(this, Handle), + ref ignored, hNonClientRegion, + NativeMethods.RDW_INVALIDATE | NativeMethods.RDW_ERASE | + NativeMethods.RDW_UPDATENOW | NativeMethods.RDW_ERASENOW | + NativeMethods.RDW_FRAME); + } + finally + { + // clean up our regions. + try + { + if (hNonClientRegion.Handle != IntPtr.Zero) + { + SafeNativeMethods.DeleteObject(hNonClientRegion); + } } - finally { - // clean up our regions. - try { - if (hNonClientRegion.Handle != IntPtr.Zero) { - SafeNativeMethods.DeleteObject(hNonClientRegion); + finally + { + try + { + if (hClientRegion.Handle != IntPtr.Zero) + { + SafeNativeMethods.DeleteObject(hClientRegion); } } - finally { - try { - if (hClientRegion.Handle != IntPtr.Zero) { - SafeNativeMethods.DeleteObject(hClientRegion); - } - } - finally { - if (hTotalRegion.Handle != IntPtr.Zero) { - SafeNativeMethods.DeleteObject(hTotalRegion); - } + finally + { + if (hTotalRegion.Handle != IntPtr.Zero) + { + SafeNativeMethods.DeleteObject(hTotalRegion); } } - - } - - } + } - protected override void OnGotFocus(EventArgs e) { - base.OnGotFocus(e); - InvalidateNonClient(); } - protected override void OnLostFocus(EventArgs e) { - base.OnLostFocus(e); - InvalidateNonClient(); - - } - - protected override void OnMouseEnter(EventArgs e) { - base.OnMouseEnter(e); - MouseIsOver = true; + } - } + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + InvalidateNonClient(); + } - protected override void OnMouseLeave(EventArgs e) { - base.OnMouseLeave(e); - MouseIsOver = false; - } - - - private void HookStaticEvents(bool hook) { - if (hook) { - if (!alreadyHooked) { - try { - SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(OnUserPreferenceChanged); - } - finally{ - alreadyHooked = true; - } - } - } - else if (alreadyHooked) { - try { - SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(OnUserPreferenceChanged); - } - finally { - alreadyHooked = false; - } - } + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + InvalidateNonClient(); - } + } + + protected override void OnMouseEnter(EventArgs e) + { + base.OnMouseEnter(e); + MouseIsOver = true; + + } - private void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e) { - if (e.Category == UserPreferenceCategory.Window) { - if (!isFontSet) { - this.Font = ToolStripManager.DefaultFont; + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + MouseIsOver = false; + } + + + private void HookStaticEvents(bool hook) + { + if (hook) + { + if (!alreadyHooked) + { + try + { + SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(OnUserPreferenceChanged); } + finally + { + alreadyHooked = true; + } + } + } + else if (alreadyHooked) + { + try + { + SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(OnUserPreferenceChanged); + } + finally + { + alreadyHooked = false; } } - protected override void OnVisibleChanged(EventArgs e) { - base.OnVisibleChanged(e); - if (!Disposing && !IsDisposed) { - HookStaticEvents(Visible); + } + + private void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e) + { + if (e.Category == UserPreferenceCategory.Window) + { + if (!isFontSet) + { + this.Font = ToolStripManager.DefaultFont; } } + } - protected override AccessibleObject CreateAccessibilityInstance() { - return new ToolStripTextBoxControlAccessibleObject(this); + protected override void OnVisibleChanged(EventArgs e) + { + base.OnVisibleChanged(e); + if (!Disposing && !IsDisposed) + { + HookStaticEvents(Visible); } + } - protected override void Dispose(bool disposing) { - if(disposing) { - HookStaticEvents(false); - } - base.Dispose(disposing); + protected override AccessibleObject CreateAccessibilityInstance() + { + return new ToolStripTextBoxControlAccessibleObject(this); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + HookStaticEvents(false); } + base.Dispose(disposing); + } - private void WmNCPaint(ref Message m) { + private void WmNCPaint(ref Message m) + { - if (!IsPopupTextBox) { - base.WndProc(ref m); - return; - } + if (!IsPopupTextBox) + { + base.WndProc(ref m); + return; + } + + // Paint over the edges of the text box. + + // Using GetWindowDC instead of GetDCEx as GetDCEx seems to return a null handle and a last error of + // the operation succeeded. We're not going to use the clipping rect anyways - so it's not + // that bigga deal. + HandleRef hdc = new HandleRef(this, UnsafeNativeMethods.GetWindowDC(new HandleRef(this, m.HWnd))); + if (hdc.Handle == IntPtr.Zero) + { + throw new Win32Exception(); + } + try + { + // Don't set the clipping region based on the WParam - windows seems to take out the two pixels intended for the non-client border. - // Paint over the edges of the text box. + Color outerBorderColor = (MouseIsOver || Focused) ? ColorTable.TextBoxBorder : this.BackColor; + Color innerBorderColor = this.BackColor; - // Using GetWindowDC instead of GetDCEx as GetDCEx seems to return a null handle and a last error of - // the operation succeeded. We're not going to use the clipping rect anyways - so it's not - // that bigga deal. - HandleRef hdc = new HandleRef(this, UnsafeNativeMethods.GetWindowDC(new HandleRef(this,m.HWnd))); - if (hdc.Handle == IntPtr.Zero) { - throw new Win32Exception(); + if (!Enabled) + { + outerBorderColor = SystemColors.ControlDark; + innerBorderColor = SystemColors.Control; } - try { - // Don't set the clipping region based on the WParam - windows seems to take out the two pixels intended for the non-client border. - - Color outerBorderColor = (MouseIsOver || Focused) ? ColorTable.TextBoxBorder : this.BackColor; - Color innerBorderColor = this.BackColor; - - if (!Enabled) { - outerBorderColor = SystemColors.ControlDark; - innerBorderColor = SystemColors.Control; + using (Graphics g = Graphics.FromHdcInternal(hdc.Handle)) + { + + Rectangle clientRect = AbsoluteClientRectangle; + + // could have set up a clip and fill-rectangled, thought this would be faster. + using (Brush b = new SolidBrush(innerBorderColor)) + { + g.FillRectangle(b, 0, 0, this.Width, clientRect.Top); // top border + g.FillRectangle(b, 0, 0, clientRect.Left, this.Height); // left border + g.FillRectangle(b, 0, clientRect.Bottom, this.Width, this.Height - clientRect.Height); // bottom border + g.FillRectangle(b, clientRect.Right, 0, this.Width - clientRect.Right, this.Height); // right border } - using (Graphics g = Graphics.FromHdcInternal(hdc.Handle)) { - - Rectangle clientRect = AbsoluteClientRectangle; - // could have set up a clip and fill-rectangled, thought this would be faster. - using (Brush b = new SolidBrush(innerBorderColor)) { - g.FillRectangle(b, 0, 0, this.Width, clientRect.Top); // top border - g.FillRectangle(b, 0, 0, clientRect.Left, this.Height); // left border - g.FillRectangle(b, 0, clientRect.Bottom, this.Width, this.Height - clientRect.Height); // bottom border - g.FillRectangle(b, clientRect.Right, 0, this.Width - clientRect.Right, this.Height); // right border - } - - // paint the outside rect. - using (Pen p = new Pen(outerBorderColor)) { - g.DrawRectangle(p, 0, 0, this.Width - 1, this.Height - 1); - } - + // paint the outside rect. + using (Pen p = new Pen(outerBorderColor)) + { + g.DrawRectangle(p, 0, 0, this.Width - 1, this.Height - 1); } + } - finally { - UnsafeNativeMethods.ReleaseDC(new HandleRef(this, this.Handle),hdc); - } - // we've handled WM_NCPAINT. - m.Result = IntPtr.Zero; + } + finally + { + UnsafeNativeMethods.ReleaseDC(new HandleRef(this, this.Handle), hdc); + } + // we've handled WM_NCPAINT. + m.Result = IntPtr.Zero; + } + protected override void WndProc(ref Message m) + { + if (m.Msg == Interop.WindowMessages.WM_NCPAINT) + { + WmNCPaint(ref m); + return; } - protected override void WndProc(ref Message m) { - if (m.Msg == Interop.WindowMessages.WM_NCPAINT) { - WmNCPaint(ref m); - return; - } - else { - base.WndProc(ref m); - } + else + { + base.WndProc(ref m); } + } } - private class ToolStripTextBoxControlAccessibleObject : Control.ControlAccessibleObject { - public ToolStripTextBoxControlAccessibleObject(ToolStripTextBoxControl toolStripTextBoxControl) : base(toolStripTextBoxControl) { + private class ToolStripTextBoxControlAccessibleObject : Control.ControlAccessibleObject + { + public ToolStripTextBoxControlAccessibleObject(ToolStripTextBoxControl toolStripTextBoxControl) : base(toolStripTextBoxControl) + { } - internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot { - get { + internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot + { + get + { var toolStripTextBoxControl = this.Owner as ToolStripTextBoxControl; - if (toolStripTextBoxControl != null) { + if (toolStripTextBoxControl != null) + { return toolStripTextBoxControl.Owner.Owner.AccessibilityObject; } @@ -812,13 +953,16 @@ internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRo } } - internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - switch (direction) { + internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) + { + switch (direction) + { case UnsafeNativeMethods.NavigateDirection.Parent: case UnsafeNativeMethods.NavigateDirection.PreviousSibling: case UnsafeNativeMethods.NavigateDirection.NextSibling: var toolStripTextBoxControl = Owner as ToolStripTextBoxControl; - if (toolStripTextBoxControl != null) { + if (toolStripTextBoxControl != null) + { return toolStripTextBoxControl.Owner.AccessibilityObject.FragmentNavigate(direction); } break; @@ -827,8 +971,10 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga return base.FragmentNavigate(direction); } - internal override object GetPropertyValue(int propertyID) { - switch (propertyID) { + internal override object GetPropertyValue(int propertyID) + { + switch (propertyID) + { case NativeMethods.UIA_ControlTypePropertyId: return NativeMethods.UIA_EditControlTypeId; case NativeMethods.UIA_HasKeyboardFocusPropertyId: @@ -838,15 +984,17 @@ internal override object GetPropertyValue(int propertyID) { return base.GetPropertyValue(propertyID); } - internal override bool IsPatternSupported(int patternId) { - if (patternId == NativeMethods.UIA_ValuePatternId) { + internal override bool IsPatternSupported(int patternId) + { + if (patternId == NativeMethods.UIA_ValuePatternId) + { return true; } return base.IsPatternSupported(patternId); } } - + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs index e8c5291f776..abb1ba4eb69 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Threading; using System.Runtime.InteropServices; @@ -35,7 +36,8 @@ namespace System.Windows.Forms { ToolboxItemFilter("System.Windows.Forms"), SRDescription(nameof(SR.DescriptionToolTip)) ] - public class ToolTip : Component, IExtenderProvider { + public class ToolTip : Component, IExtenderProvider + { const int DEFAULT_DELAY = 500; const int RESHOW_RATIO = 5; @@ -50,31 +52,31 @@ public class ToolTip : Component, IExtenderProvider { private const int LEFT_LOCATION_INDEX = 3; private const int LOCATION_TOTAL = 4; - Hashtable tools = new Hashtable(); - int[] delayTimes = new int[4]; - bool auto = true; - bool showAlways = false; + Hashtable tools = new Hashtable(); + int[] delayTimes = new int[4]; + bool auto = true; + bool showAlways = false; ToolTipNativeWindow window = null; - Control topLevelControl = null; - bool active = true; - bool ownerDraw = false; - object userData; - Color backColor = SystemColors.Info; - Color foreColor = SystemColors.InfoText; - bool isBalloon; - bool isDisposing; - string toolTipTitle = string.Empty; - ToolTipIcon toolTipIcon = (ToolTipIcon)0; - ToolTipTimer timer; - Hashtable owners = new Hashtable(); - bool stripAmpersands = false; - bool useAnimation = true; - bool useFading = true; - int originalPopupDelay = 0; - + Control topLevelControl = null; + bool active = true; + bool ownerDraw = false; + object userData; + Color backColor = SystemColors.Info; + Color foreColor = SystemColors.InfoText; + bool isBalloon; + bool isDisposing; + string toolTipTitle = string.Empty; + ToolTipIcon toolTipIcon = (ToolTipIcon)0; + ToolTipTimer timer; + Hashtable owners = new Hashtable(); + bool stripAmpersands = false; + bool useAnimation = true; + bool useFading = true; + int originalPopupDelay = 0; + // setting TTM_TRACKPOSITION will cause redundant POP and Draw Messages.. // Hence we gaurd against this by having this private Flag.. - bool trackPosition = false; + bool trackPosition = false; PopupEventHandler onPopup; DrawToolTipEventHandler onDraw; @@ -82,7 +84,7 @@ public class ToolTip : Component, IExtenderProvider { // Adding a tool twice breaks the ToolTip, so we need to track which // tools are created to prevent this... // - Hashtable created = new Hashtable(); + Hashtable created = new Hashtable(); private bool cancelled = false; @@ -91,8 +93,10 @@ public class ToolTip : Component, IExtenderProvider { /// Initializes a new instance of the class, given the container. /// /// - public ToolTip(IContainer cont) : this() { - if (cont == null) { + public ToolTip(IContainer cont) : this() + { + if (cont == null) + { throw new ArgumentNullException(nameof(cont)); } @@ -104,7 +108,8 @@ public ToolTip(IContainer cont) : this() { /// Initializes a new instance of the class in its default state. /// /// - public ToolTip() { + public ToolTip() + { window = new ToolTipNativeWindow(this); auto = true; delayTimes[NativeMethods.TTDT_AUTOMATIC] = DEFAULT_DELAY; @@ -120,24 +125,30 @@ public ToolTip() { SRDescription(nameof(SR.ToolTipActiveDescr)), DefaultValue(true) ] - public bool Active { - get { + public bool Active + { + get + { return active; } - set { - if (active != value) { + set + { + if (active != value) + { active = value; //lets not actually activate the tooltip if we're in the designer (just set the value) - if (!DesignMode && GetHandleCreated()) { - UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_ACTIVATE, (value==true)? 1: 0, 0); + if (!DesignMode && GetHandleCreated()) + { + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_ACTIVATE, (value == true) ? 1 : 0, 0); } } } } - internal void HideToolTip(IKeyboardToolTip currentTool) { + internal void HideToolTip(IKeyboardToolTip currentTool) + { this.Hide(currentTool.GetOwnerWindow()); } @@ -152,20 +163,25 @@ internal void HideToolTip(IKeyboardToolTip currentTool) { SRDescription(nameof(SR.ToolTipAutomaticDelayDescr)), DefaultValue(DEFAULT_DELAY) ] - public int AutomaticDelay { - get { + public int AutomaticDelay + { + get + { return delayTimes[NativeMethods.TTDT_AUTOMATIC]; } - set { - if (value < 0) { + set + { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(AutomaticDelay), value, 0)); } SetDelayTime(NativeMethods.TTDT_AUTOMATIC, value); } } - internal string GetCaptionForTool(Control tool) { + internal string GetCaptionForTool(Control tool) + { Debug.Assert(tool != null, "tool should not be null"); return ((TipInfo)this.tools[tool])?.Caption; } @@ -179,13 +195,17 @@ internal string GetCaptionForTool(Control tool) { RefreshProperties(RefreshProperties.All), SRDescription(nameof(SR.ToolTipAutoPopDelayDescr)) ] - public int AutoPopDelay { - get { + public int AutoPopDelay + { + get + { return delayTimes[NativeMethods.TTDT_AUTOPOP]; } - set { - if (value < 0) { + set + { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(AutoPopDelay), value, 0)); } SetDelayTime(NativeMethods.TTDT_AUTOPOP, value); @@ -199,16 +219,20 @@ public int AutoPopDelay { /// [ SRDescription(nameof(SR.ToolTipBackColorDescr)), - DefaultValue(typeof(Color),"Info") + DefaultValue(typeof(Color), "Info") ] - public Color BackColor { - get { + public Color BackColor + { + get + { return backColor; } - set { + set + { backColor = value; - if (GetHandleCreated()) { + if (GetHandleCreated()) + { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_SETTIPBKCOLOR, ColorTranslator.ToWin32(backColor), 0); } } @@ -217,26 +241,34 @@ public Color BackColor { /// /// The createParams to create the window. /// - protected virtual CreateParams CreateParams { - get { + protected virtual CreateParams CreateParams + { + get + { CreateParams cp = new CreateParams(); - if (TopLevelControl != null && !TopLevelControl.IsDisposed) { + if (TopLevelControl != null && !TopLevelControl.IsDisposed) + { cp.Parent = TopLevelControl.Handle; } cp.ClassName = NativeMethods.TOOLTIPS_CLASS; - if (showAlways) { + if (showAlways) + { cp.Style = NativeMethods.TTS_ALWAYSTIP; } - if (isBalloon) { + if (isBalloon) + { cp.Style |= NativeMethods.TTS_BALLOON; } - if (!stripAmpersands) { + if (!stripAmpersands) + { cp.Style |= NativeMethods.TTS_NOPREFIX; } - if (!useAnimation) { + if (!useAnimation) + { cp.Style |= NativeMethods.TTS_NOANIMATE; } - if (!useFading) { + if (!useFading) + { cp.Style |= NativeMethods.TTS_NOFADE; } cp.ExStyle = 0; @@ -253,29 +285,37 @@ protected virtual CreateParams CreateParams { /// [ SRDescription(nameof(SR.ToolTipForeColorDescr)), - DefaultValue(typeof(Color),"InfoText") + DefaultValue(typeof(Color), "InfoText") ] - public Color ForeColor { - get { + public Color ForeColor + { + get + { return foreColor; } - set { - if (value.IsEmpty) { + set + { + if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.ToolTipEmptyColor, "ForeColor")); } foreColor = value; - if (GetHandleCreated()) { + if (GetHandleCreated()) + { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_SETTIPTEXTCOLOR, ColorTranslator.ToWin32(foreColor), 0); } } } - internal IntPtr Handle { - get { - if (!GetHandleCreated()) { + internal IntPtr Handle + { + get + { + if (!GetHandleCreated()) + { CreateHandle(); } return window.Handle; @@ -291,19 +331,24 @@ internal IntPtr Handle { SRDescription(nameof(SR.ToolTipIsBalloonDescr)), DefaultValue(false) ] - public bool IsBalloon { - get { + public bool IsBalloon + { + get + { return isBalloon; } - set { - if (isBalloon != value) { + set + { + if (isBalloon != value) + { isBalloon = value; - if (GetHandleCreated()) { + if (GetHandleCreated()) + { RecreateHandle(); } } - + } } @@ -317,7 +362,7 @@ private bool IsWindowActive(IWin32Window window) (windowControl.ShowParams & 0xF) != NativeMethods.SW_SHOWNOACTIVATE) { IntPtr hWnd = UnsafeNativeMethods.GetActiveWindow(); - IntPtr rootHwnd =UnsafeNativeMethods.GetAncestor(new HandleRef(window, window.Handle), NativeMethods.GA_ROOT); + IntPtr rootHwnd = UnsafeNativeMethods.GetAncestor(new HandleRef(window, window.Handle), NativeMethods.GA_ROOT); if (hWnd != rootHwnd) { TipInfo tt = (TipInfo)tools[windowControl]; @@ -343,34 +388,38 @@ private bool IsWindowActive(IWin32Window window) RefreshProperties(RefreshProperties.All), SRDescription(nameof(SR.ToolTipInitialDelayDescr)) ] - public int InitialDelay { - get { + public int InitialDelay + { + get + { return delayTimes[NativeMethods.TTDT_INITIAL]; } - set { - if (value < 0) { + set + { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(InitialDelay), value, 0)); } SetDelayTime(NativeMethods.TTDT_INITIAL, value); } } - + /// /// Indicates whether the ToolTip will be drawn by the system or the user. /// [ SRCategory(nameof(SR.CatBehavior)), DefaultValue(false), - SRDescription(nameof(SR.ToolTipOwnerDrawDescr)) + SRDescription(nameof(SR.ToolTipOwnerDrawDescr)) ] - public bool OwnerDraw + public bool OwnerDraw { - get + get { return ownerDraw; } - set + set { ownerDraw = value; } @@ -388,12 +437,16 @@ public bool OwnerDraw RefreshProperties(RefreshProperties.All), SRDescription(nameof(SR.ToolTipReshowDelayDescr)) ] - public int ReshowDelay { - get { + public int ReshowDelay + { + get + { return delayTimes[NativeMethods.TTDT_RESHOW]; } - set { - if (value < 0) { + set + { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(ReshowDelay), value, 0)); } SetDelayTime(NativeMethods.TTDT_RESHOW, value); @@ -410,14 +463,19 @@ public int ReshowDelay { DefaultValue(false), SRDescription(nameof(SR.ToolTipShowAlwaysDescr)) ] - public bool ShowAlways { - get { + public bool ShowAlways + { + get + { return showAlways; } - set { - if (showAlways != value) { + set + { + if (showAlways != value) + { showAlways = value; - if (GetHandleCreated()) { + if (GetHandleCreated()) + { RecreateHandle(); } } @@ -435,14 +493,19 @@ public bool ShowAlways { Browsable(true), DefaultValue(false) ] - public bool StripAmpersands { - get { + public bool StripAmpersands + { + get + { return stripAmpersands; } - set { - if (stripAmpersands != value) { + set + { + if (stripAmpersands != value) + { stripAmpersands = value; - if (GetHandleCreated()) { + if (GetHandleCreated()) + { RecreateHandle(); } } @@ -457,11 +520,14 @@ public bool StripAmpersands { DefaultValue(null), TypeConverter(typeof(StringConverter)), ] - public object Tag { - get { + public object Tag + { + get + { return userData; } - set { + set + { userData = value; } } @@ -475,19 +541,24 @@ public object Tag { DefaultValue(ToolTipIcon.None), SRDescription(nameof(SR.ToolTipToolTipIconDescr)) ] - public ToolTipIcon ToolTipIcon { - get { + public ToolTipIcon ToolTipIcon + { + get + { return toolTipIcon; } - set { - if (toolTipIcon != value) { + set + { + if (toolTipIcon != value) + { //valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolTipIcon.None, (int)ToolTipIcon.Error)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolTipIcon)); } toolTipIcon = value; - if (toolTipIcon > 0 && GetHandleCreated()) { + if (toolTipIcon > 0 && GetHandleCreated()) + { // If the title is null/empty, the icon won't display. string title = !string.IsNullOrEmpty(toolTipTitle) ? toolTipTitle : " "; UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_SETTITLE, (int)toolTipIcon, title); @@ -508,7 +579,7 @@ public ToolTipIcon ToolTipIcon { /// /// [ - DefaultValue(""), + DefaultValue(""), SRDescription(nameof(SR.ToolTipTitleDescr)) ] public string ToolTipTitle @@ -539,34 +610,44 @@ public string ToolTipTitle } } - private Control TopLevelControl { - get { + private Control TopLevelControl + { + get + { Control baseVar = null; - if (topLevelControl == null) { + if (topLevelControl == null) + { Control[] regions = new Control[tools.Keys.Count]; tools.Keys.CopyTo(regions, 0); - if (regions != null && regions.Length > 0) { - for (int i=0; i 0) + { + for (int i = 0; i < regions.Length; i++) + { Control ctl = regions[i]; - + baseVar = ctl.TopLevelControlInternal; - if (baseVar != null) { + if (baseVar != null) + { break; } - if (ctl.IsActiveX) { + if (ctl.IsActiveX) + { baseVar = ctl; break; } // In designer, baseVar can be null since the Parent is not a TopLevel control if (baseVar == null) { - if (ctl != null && ctl.ParentInternal != null) { - while (ctl.ParentInternal != null) { + if (ctl != null && ctl.ParentInternal != null) + { + while (ctl.ParentInternal != null) + { ctl = ctl.ParentInternal; } baseVar = ctl; - if (baseVar != null) { + if (baseVar != null) + { break; } } @@ -574,16 +655,19 @@ private Control TopLevelControl { } } topLevelControl = baseVar; - if (baseVar != null) { + if (baseVar != null) + { baseVar.HandleCreated += new EventHandler(this.TopLevelCreated); baseVar.HandleDestroyed += new EventHandler(this.TopLevelDestroyed); - if (baseVar.IsHandleCreated) { + if (baseVar.IsHandleCreated) + { TopLevelCreated(baseVar, EventArgs.Empty); } baseVar.ParentChanged += new EventHandler(this.OnTopLevelPropertyChanged); } } - else { + else + { baseVar = topLevelControl; } return baseVar; @@ -600,14 +684,19 @@ private Control TopLevelControl { Browsable(true), DefaultValue(true) ] - public bool UseAnimation { - get { + public bool UseAnimation + { + get + { return useAnimation; } - set { - if (useAnimation != value) { + set + { + if (useAnimation != value) + { useAnimation = value; - if (GetHandleCreated()) { + if (GetHandleCreated()) + { RecreateHandle(); } } @@ -625,14 +714,19 @@ public bool UseAnimation { Browsable(true), DefaultValue(true) ] - public bool UseFading { - get { + public bool UseFading + { + get + { return useFading; } - set { - if (useFading != value) { + set + { + if (useFading != value) + { useFading = value; - if (GetHandleCreated()) { + if (GetHandleCreated()) + { RecreateHandle(); } } @@ -642,18 +736,18 @@ public bool UseFading { /// /// Fires in OwnerDraw mode when the tooltip needs to be drawn. /// - [SRCategory(nameof(SR.CatBehavior)),SRDescription(nameof(SR.ToolTipDrawEventDescr))] - public event DrawToolTipEventHandler Draw + [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ToolTipDrawEventDescr))] + public event DrawToolTipEventHandler Draw { add => onDraw += value; remove => onDraw -= value; } - + /// /// Fires when the tooltip is just about to be shown. /// - [SRCategory(nameof(SR.CatBehavior)),SRDescription(nameof(SR.ToolTipPopupEventDescr))] - public event PopupEventHandler Popup + [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.ToolTipPopupEventDescr))] + public event PopupEventHandler Popup { add => onPopup += value; remove => onPopup -= value; @@ -663,13 +757,15 @@ public event PopupEventHandler Popup /// /// Adjusts the other delay values based on the Automatic value. /// - private void AdjustBaseFromAuto() { + private void AdjustBaseFromAuto() + { delayTimes[NativeMethods.TTDT_RESHOW] = delayTimes[NativeMethods.TTDT_AUTOMATIC] / RESHOW_RATIO; delayTimes[NativeMethods.TTDT_AUTOPOP] = delayTimes[NativeMethods.TTDT_AUTOMATIC] * AUTOPOP_RATIO; delayTimes[NativeMethods.TTDT_INITIAL] = delayTimes[NativeMethods.TTDT_AUTOMATIC]; } - - private void HandleCreated(object sender, EventArgs eventargs) { + + private void HandleCreated(object sender, EventArgs eventargs) + { // Reset the toplevel control when the owner's handle is recreated. ClearTopLevelControlEvents(); topLevelControl = null; @@ -682,37 +778,45 @@ private void HandleCreated(object sender, EventArgs eventargs) { KeyboardToolTipStateMachine.Instance.Hook(control, this); } - private void CheckNativeToolTip(Control associatedControl) { + private void CheckNativeToolTip(Control associatedControl) + { //Wait for the Handle Creation.. - if (!GetHandleCreated()) { + if (!GetHandleCreated()) + { return; } - + TreeView treeView = associatedControl as TreeView; - if (treeView != null) { - if (treeView.ShowNodeToolTips) { - treeView.SetToolTip(this,GetToolTip(associatedControl)); + if (treeView != null) + { + if (treeView.ShowNodeToolTips) + { + treeView.SetToolTip(this, GetToolTip(associatedControl)); } } - - if (associatedControl is ToolBar) { - ((ToolBar)associatedControl).SetToolTip(this); + + if (associatedControl is ToolBar) + { + ((ToolBar)associatedControl).SetToolTip(this); } TabControl tabControl = associatedControl as TabControl; - if (tabControl!= null) { + if (tabControl != null) + { if (tabControl.ShowToolTips) { tabControl.SetToolTip(this, GetToolTip(associatedControl)); } } - - if (associatedControl is ListView) { - ((ListView)associatedControl).SetToolTip(this, GetToolTip(associatedControl)); + + if (associatedControl is ListView) + { + ((ListView)associatedControl).SetToolTip(this, GetToolTip(associatedControl)); } - - if (associatedControl is StatusBar) { + + if (associatedControl is StatusBar) + { ((StatusBar)associatedControl).SetToolTip(this); } @@ -720,20 +824,24 @@ private void CheckNativeToolTip(Control associatedControl) { // So this control too falls in special casing... // We need to disable the LABEL AutoEllipsis tooltip and show // this tooltip always... - if (associatedControl is Label) { + if (associatedControl is Label) + { ((Label)associatedControl).SetToolTip(this); } } - private void CheckCompositeControls(Control associatedControl) { - if (associatedControl is UpDownBase) { + private void CheckCompositeControls(Control associatedControl) + { + if (associatedControl is UpDownBase) + { ((UpDownBase)associatedControl).SetToolTip(this, GetToolTip(associatedControl)); } } - private void HandleDestroyed(object sender, EventArgs eventargs) { + private void HandleDestroyed(object sender, EventArgs eventargs) + { Control control = (Control)sender; this.DestroyRegion(control); @@ -743,11 +851,11 @@ private void HandleDestroyed(object sender, EventArgs eventargs) { /// /// Fires the Draw event. /// - private void OnDraw(DrawToolTipEventArgs e) + private void OnDraw(DrawToolTipEventArgs e) { - if(onDraw != null) + if (onDraw != null) { - onDraw(this,e); + onDraw(this, e); } } @@ -755,20 +863,22 @@ private void OnDraw(DrawToolTipEventArgs e) /// /// Fires the Popup event. /// - private void OnPopup(PopupEventArgs e) + private void OnPopup(PopupEventArgs e) { - if(onPopup != null) + if (onPopup != null) { - onPopup(this,e); + onPopup(this, e); } } - private void TopLevelCreated(object sender, EventArgs eventargs) { + private void TopLevelCreated(object sender, EventArgs eventargs) + { CreateHandle(); CreateAllRegions(); } - private void TopLevelDestroyed(object sender, EventArgs eventargs) { + private void TopLevelDestroyed(object sender, EventArgs eventargs) + { DestoyAllRegions(); DestroyHandle(); } @@ -777,18 +887,22 @@ private void TopLevelDestroyed(object sender, EventArgs eventargs) { /// Returns true if the tooltip can offer an extender property to the /// specified target component. /// - public bool CanExtend(object target) { + public bool CanExtend(object target) + { if (target is Control && - !(target is ToolTip)) { + !(target is ToolTip)) + { return true; } return false; } - private void ClearTopLevelControlEvents() { + private void ClearTopLevelControlEvents() + { - if (this.topLevelControl != null) { + if (this.topLevelControl != null) + { this.topLevelControl.ParentChanged -= new EventHandler(this.OnTopLevelPropertyChanged); this.topLevelControl.HandleCreated -= new EventHandler(this.TopLevelCreated); this.topLevelControl.HandleDestroyed -= new EventHandler(this.TopLevelDestroyed); @@ -798,35 +912,41 @@ private void ClearTopLevelControlEvents() { /// /// Creates the handle for the control. /// - private void CreateHandle() { - if (GetHandleCreated()) { + private void CreateHandle() + { + if (GetHandleCreated()) + { return; } IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); - - try { + + try + { NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); icc.dwICC = NativeMethods.ICC_TAB_CLASSES; SafeNativeMethods.InitCommonControlsEx(icc); CreateParams cp = CreateParams; // Avoid reentrant call to CreateHandle - if (GetHandleCreated()) { + if (GetHandleCreated()) + { return; } window.CreateHandle(cp); } - finally { + finally + { UnsafeNativeMethods.ThemingScope.Deactivate(userCookie); } // If in ownerDraw mode, we don't want the default border. - if (ownerDraw) { + if (ownerDraw) + { int style = unchecked((int)((long)UnsafeNativeMethods.GetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_STYLE))); style &= ~NativeMethods.WS_BORDER; UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_STYLE, new HandleRef(null, (IntPtr)style)); } - + // Setting the max width has the added benefit of enabling multiline // tool tips! // @@ -834,15 +954,19 @@ private void CreateHandle() { Debug.Assert(NativeMethods.TTDT_AUTOMATIC == 0, "TTDT_AUTOMATIC != 0"); - if (auto) { + if (auto) + { SetDelayTime(NativeMethods.TTDT_AUTOMATIC, delayTimes[NativeMethods.TTDT_AUTOMATIC]); delayTimes[NativeMethods.TTDT_AUTOPOP] = GetDelayTime(NativeMethods.TTDT_AUTOPOP); delayTimes[NativeMethods.TTDT_INITIAL] = GetDelayTime(NativeMethods.TTDT_INITIAL); delayTimes[NativeMethods.TTDT_RESHOW] = GetDelayTime(NativeMethods.TTDT_RESHOW); } - else { - for (int i=1; i < delayTimes.Length; i++) { - if (delayTimes[i] >= 1) { + else + { + for (int i = 1; i < delayTimes.Length; i++) + { + if (delayTimes[i] >= 1) + { SetDelayTime(i, delayTimes[i]); } } @@ -852,25 +976,31 @@ private void CreateHandle() { // UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_ACTIVATE, (active == true) ? 1 : 0, 0); - if (BackColor != SystemColors.Info) { + if (BackColor != SystemColors.Info) + { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_SETTIPBKCOLOR, ColorTranslator.ToWin32(BackColor), 0); } - if (ForeColor != SystemColors.InfoText) { + if (ForeColor != SystemColors.InfoText) + { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_SETTIPTEXTCOLOR, ColorTranslator.ToWin32(ForeColor), 0); } - if (toolTipIcon > 0 || !string.IsNullOrEmpty(toolTipTitle)) { + if (toolTipIcon > 0 || !string.IsNullOrEmpty(toolTipTitle)) + { // If the title is null/empty, the icon won't display. string title = !string.IsNullOrEmpty(toolTipTitle) ? toolTipTitle : " "; UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_SETTITLE, (int)toolTipIcon, title); } } - private void CreateAllRegions() { + private void CreateAllRegions() + { Control[] ctls = new Control[tools.Keys.Count]; tools.Keys.CopyTo(ctls, 0); - for (int i=0; i 0; @@ -926,13 +1070,15 @@ private void CreateRegion(Control ctl) { && TopLevelControl != null && TopLevelControl.IsHandleCreated; if (!created.ContainsKey(ctl) && captionValid - && handlesCreated && !DesignMode) { + && handlesCreated && !DesignMode) + { //Call the Sendmessage thru a function.. SetToolInfo(ctl, caption); created[ctl] = ctl; } - if (ctl.IsHandleCreated && topLevelControl == null) { + if (ctl.IsHandleCreated && topLevelControl == null) + { // Remove first to purge any duplicates... // ctl.MouseMove -= new MouseEventHandler(this.MouseMove); @@ -940,17 +1086,20 @@ private void CreateRegion(Control ctl) { } } - private void MouseMove(object sender, MouseEventArgs me) { + private void MouseMove(object sender, MouseEventArgs me) + { Control ctl = (Control)sender; if (!created.ContainsKey(ctl) && ctl.IsHandleCreated - && TopLevelControl != null) { + && TopLevelControl != null) + { CreateRegion(ctl); } - if (created.ContainsKey(ctl)) { + if (created.ContainsKey(ctl)) + { ctl.MouseMove -= new MouseEventHandler(this.MouseMove); } } @@ -961,19 +1110,22 @@ private void MouseMove(object sender, MouseEventArgs me) { /// Destroys the handle for this control. /// /// Required by Label to destroy the handle for the toolTip added for AutoEllipses. - internal void DestroyHandle() { + internal void DestroyHandle() + { - if (GetHandleCreated()) { + if (GetHandleCreated()) + { window.DestroyHandle(); } } - private void DestroyRegion(Control ctl) { + private void DestroyRegion(Control ctl) + { // when the toplevelControl is a form and is Modal, the Handle of the tooltip is releasedbefore we come here. // In such a case the tool wont get deleted from the tooltip. // So we dont check "Handle" in the handlesCreate but check it only foe Non-Nodal dialogs later - + bool handlesCreated = ctl.IsHandleCreated && topLevelControl != null && topLevelControl.IsHandleCreated @@ -984,9 +1136,10 @@ private void DestroyRegion(Control ctl) { { handlesCreated = handlesCreated && GetHandleCreated(); } - + if (created.ContainsKey(ctl) - && handlesCreated && !DesignMode) { + && handlesCreated && !DesignMode) + { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_DELTOOL, 0, GetMinTOOLINFO(ctl)); created.Remove(ctl); @@ -999,11 +1152,14 @@ private void DestroyRegion(Control ctl) { /// component. /// /// - protected override void Dispose(bool disposing) { - - if (disposing) { + protected override void Dispose(bool disposing) + { + + if (disposing) + { this.isDisposing = true; - try { + try + { ClearTopLevelControlEvents(); StopTimer(); @@ -1018,32 +1174,38 @@ protected override void Dispose(bool disposing) { // Lets find the Form for associated Control ... // and hook up to the Deactivated event to Hide the Shown tooltip Form baseFrom = TopLevelControl as Form; - if (baseFrom != null) { + if (baseFrom != null) + { baseFrom.Deactivate -= new EventHandler(this.BaseFormDeactivate); } } - finally { + finally + { this.isDisposing = false; } - } + } base.Dispose(disposing); } /// /// Returns the delayTime based on the NativeMethods.TTDT_* values. /// - internal int GetDelayTime(int type) { - if (GetHandleCreated()) { + internal int GetDelayTime(int type) + { + if (GetHandleCreated()) + { return (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_GETDELAYTIME, type, 0); } - else { + else + { return delayTimes[type]; } } // Can't be a property -- there is another method called GetHandleCreated - internal bool GetHandleCreated() { - return (window != null ? window.Handle != IntPtr.Zero: false); + internal bool GetHandleCreated() + { + return (window != null ? window.Handle != IntPtr.Zero : false); } /// @@ -1051,15 +1213,18 @@ internal bool GetHandleCreated() { /// required data to uniquely identify a region. This is used primarily /// for delete operations. NOTE: This cannot force the creation of a handle. /// - private NativeMethods.TOOLINFO_TOOLTIP GetMinTOOLINFO(Control ctl) { + private NativeMethods.TOOLINFO_TOOLTIP GetMinTOOLINFO(Control ctl) + { return this.GetMinToolInfoForHandle(ctl.Handle); } - private NativeMethods.TOOLINFO_TOOLTIP GetMinToolInfoForTool(IWin32Window tool) { + private NativeMethods.TOOLINFO_TOOLTIP GetMinToolInfoForTool(IWin32Window tool) + { return this.GetMinToolInfoForHandle(tool.Handle); } - private NativeMethods.TOOLINFO_TOOLTIP GetMinToolInfoForHandle(IntPtr handle) { + private NativeMethods.TOOLINFO_TOOLTIP GetMinToolInfoForHandle(IntPtr handle) + { NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP(); ti.cbSize = Marshal.SizeOf(); ti.hwnd = handle; @@ -1074,7 +1239,8 @@ private NativeMethods.TOOLINFO_TOOLTIP GetMinToolInfoForHandle(IntPtr handle) { /// If the out parameter allocatedString has been set to true, It is the responsibility of the caller /// to free the string buffer referenced by lpszText (using Marshal.FreeHGlobal). /// - private NativeMethods.TOOLINFO_TOOLTIP GetTOOLINFO(Control ctl, string caption, out bool allocatedString) { + private NativeMethods.TOOLINFO_TOOLTIP GetTOOLINFO(Control ctl, string caption, out bool allocatedString) + { allocatedString = false; NativeMethods.TOOLINFO_TOOLTIP ti = GetMinTOOLINFO(ctl); ti.cbSize = Marshal.SizeOf(); @@ -1083,55 +1249,65 @@ private NativeMethods.TOOLINFO_TOOLTIP GetTOOLINFO(Control ctl, string caption, // RightToLeft reading order // Control richParent = TopLevelControl; - if (richParent != null && richParent.RightToLeft == RightToLeft.Yes && !ctl.IsMirrored) { + if (richParent != null && richParent.RightToLeft == RightToLeft.Yes && !ctl.IsMirrored) + { //Indicates that the ToolTip text will be displayed in the opposite direction //to the text in the parent window. ti.uFlags |= NativeMethods.TTF_RTLREADING; } - - if (ctl is TreeView || ctl is ListView) { + + if (ctl is TreeView || ctl is ListView) + { TreeView tv = ctl as TreeView; - if (tv != null && tv.ShowNodeToolTips) { + if (tv != null && tv.ShowNodeToolTips) + { ti.lpszText = NativeMethods.InvalidIntPtr; } - else { + else + { ListView lv = ctl as ListView; - if (lv != null && lv.ShowItemToolTips) { + if (lv != null && lv.ShowItemToolTips) + { ti.lpszText = NativeMethods.InvalidIntPtr; } - else { + else + { ti.lpszText = Marshal.StringToHGlobalAuto(caption); allocatedString = true; } } } - else { + else + { ti.lpszText = Marshal.StringToHGlobalAuto(caption); allocatedString = true; } - + return ti; } - private NativeMethods.TOOLINFO_TOOLTIP GetWinTOOLINFO(IntPtr hWnd) { + private NativeMethods.TOOLINFO_TOOLTIP GetWinTOOLINFO(IntPtr hWnd) + { NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP(); ti.cbSize = Marshal.SizeOf(); ti.hwnd = hWnd; ti.uFlags |= NativeMethods.TTF_IDISHWND | NativeMethods.TTF_TRANSPARENT | NativeMethods.TTF_SUBCLASS; - + // RightToLeft reading order // Control richParent = TopLevelControl; - if (richParent != null && richParent.RightToLeft == RightToLeft.Yes) { - bool isWindowMirrored = ((unchecked((int)(long)UnsafeNativeMethods.GetWindowLong(new HandleRef(this, hWnd), NativeMethods.GWL_STYLE)) & NativeMethods.WS_EX_LAYOUTRTL) == NativeMethods.WS_EX_LAYOUTRTL); + if (richParent != null && richParent.RightToLeft == RightToLeft.Yes) + { + bool isWindowMirrored = ((unchecked((int)(long)UnsafeNativeMethods.GetWindowLong(new HandleRef(this, hWnd), NativeMethods.GWL_STYLE)) & NativeMethods.WS_EX_LAYOUTRTL) == NativeMethods.WS_EX_LAYOUTRTL); //Indicates that the ToolTip text will be displayed in the opposite direction //to the text in the parent window. - if (!isWindowMirrored) { + if (!isWindowMirrored) + { ti.uFlags |= NativeMethods.TTF_RTLREADING; } } - + ti.uId = ti.hwnd; return ti; } @@ -1147,15 +1323,19 @@ private NativeMethods.TOOLINFO_TOOLTIP GetWinTOOLINFO(IntPtr hWnd) { SRDescription(nameof(SR.ToolTipToolTipDescr)), Editor("System.ComponentModel.Design.MultilineStringEditor, " + AssemblyRef.SystemDesign, typeof(System.Drawing.Design.UITypeEditor)) ] - public string GetToolTip(Control control) { - if (control == null) { - return string.Empty; + public string GetToolTip(Control control) + { + if (control == null) + { + return string.Empty; } TipInfo tt = (TipInfo)tools[control]; - if (tt == null || tt.Caption == null) { + if (tt == null || tt.Caption == null) + { return ""; } - else { + else + { return tt.Caption; } } @@ -1164,7 +1344,8 @@ public string GetToolTip(Control control) { /// Returns the HWND of the window that is at the specified point. This /// handles special cases where one Control owns multiple HWNDs (i.e. ComboBox). /// - private IntPtr GetWindowFromPoint(Point screenCoords, ref bool success) { + private IntPtr GetWindowFromPoint(Point screenCoords, ref bool success) + { Control baseVar = TopLevelControl; //Special case the ActiveX Controls. if (baseVar != null && baseVar.IsActiveX) @@ -1181,52 +1362,65 @@ private IntPtr GetWindowFromPoint(Point screenCoords, ref bool success) { } return IntPtr.Zero; } - + IntPtr baseHwnd = IntPtr.Zero; - if (baseVar != null) { + if (baseVar != null) + { baseHwnd = baseVar.Handle; } IntPtr hwnd = IntPtr.Zero; bool finalMatch = false; - while (!finalMatch) { + while (!finalMatch) + { Point pt = screenCoords; - if (baseVar != null) { + if (baseVar != null) + { pt = baseVar.PointToClient(screenCoords); } IntPtr found = UnsafeNativeMethods.ChildWindowFromPointEx(new HandleRef(null, baseHwnd), pt.X, pt.Y, NativeMethods.CWP_SKIPINVISIBLE); - if (found == baseHwnd) { + if (found == baseHwnd) + { hwnd = found; finalMatch = true; } - else if (found == IntPtr.Zero) { + else if (found == IntPtr.Zero) + { finalMatch = true; } - else { + else + { baseVar = Control.FromHandle(found); - if (baseVar == null) { + if (baseVar == null) + { baseVar = Control.FromChildHandle(found); - if (baseVar != null) { + if (baseVar != null) + { hwnd = baseVar.Handle; } finalMatch = true; } - else { + else + { baseHwnd = baseVar.Handle; } } } - if (hwnd != IntPtr.Zero) { + if (hwnd != IntPtr.Zero) + { Control ctl = Control.FromHandle(hwnd); - if (ctl != null) { + if (ctl != null) + { Control current = ctl; - while (current != null && current.Visible) { + while (current != null && current.Visible) + { current = current.ParentInternal; } - if (current != null) { + if (current != null) + { hwnd = IntPtr.Zero; } success = true; @@ -1236,7 +1430,8 @@ private IntPtr GetWindowFromPoint(Point screenCoords, ref bool success) { return hwnd; } - private void OnTopLevelPropertyChanged(object s, EventArgs e) { + private void OnTopLevelPropertyChanged(object s, EventArgs e) + { ClearTopLevelControlEvents(); this.topLevelControl = null; @@ -1249,9 +1444,12 @@ private void OnTopLevelPropertyChanged(object s, EventArgs e) { /// /// - private void RecreateHandle() { - if (!DesignMode) { - if (GetHandleCreated()) { + private void RecreateHandle() + { + if (!DesignMode) + { + if (GetHandleCreated()) + { DestroyHandle(); } created.Clear(); @@ -1267,11 +1465,14 @@ private void RecreateHandle() { /// with the control. /// /// - public void RemoveAll() { + public void RemoveAll() + { Control[] regions = new Control[tools.Keys.Count]; tools.Keys.CopyTo(regions, 0); - for (int i=0; i /// Sets the delayTime based on the NativeMethods.TTDT_* values. /// - private void SetDelayTime(int type, int time) { - if (type == NativeMethods.TTDT_AUTOMATIC) { + private void SetDelayTime(int type, int time) + { + if (type == NativeMethods.TTDT_AUTOMATIC) + { auto = true; } - else { + else + { auto = false; } delayTimes[type] = time; - if (GetHandleCreated() && time >= 0) { + if (GetHandleCreated() && time >= 0) + { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_SETDELAYTIME, type, time); // Update everyone else if automatic is set... we need to do this // to preserve value in case of handle recreation. // - if (auto) { + if (auto) + { delayTimes[NativeMethods.TTDT_AUTOPOP] = GetDelayTime(NativeMethods.TTDT_AUTOPOP); delayTimes[NativeMethods.TTDT_INITIAL] = GetDelayTime(NativeMethods.TTDT_INITIAL); delayTimes[NativeMethods.TTDT_RESHOW] = GetDelayTime(NativeMethods.TTDT_RESHOW); } } - else if (auto) { + else if (auto) + { AdjustBaseFromAuto(); } } @@ -1324,10 +1531,11 @@ private void SetDelayTime(int type, int time) { /// Associates text with the specified control. /// /// - public void SetToolTip(Control control, string caption) { + public void SetToolTip(Control control, string caption) + { TipInfo info = new TipInfo(caption, TipInfo.Type.Auto); - SetToolTipInternal(control, info); + SetToolTipInternal(control, info); } @@ -1336,64 +1544,80 @@ public void SetToolTip(Control control, string caption) { /// Associates screen.WorkingArea.Right) { + if (moveToLocation.X + tipSize.Width > screen.WorkingArea.Right) + { moveToLocation.X = screen.WorkingArea.Right - tipSize.Width; } // re-adjust the Y position of the tool tip if it bleeds off the screen working area. - if (moveToLocation.Y + tipSize.Height> screen.WorkingArea.Bottom) { + if (moveToLocation.Y + tipSize.Height > screen.WorkingArea.Bottom) + { moveToLocation.Y = screen.WorkingArea.Bottom - tipSize.Height; - } + } SafeNativeMethods.SetWindowPos(new HandleRef(this, this.Handle), NativeMethods.HWND_TOPMOST, @@ -2047,7 +2374,8 @@ private void Reposition(Point tipPosition, Size tipSize) { /// /// Handles the WM_MOVE message. /// - private void WmMove() { + private void WmMove() + { NativeMethods.RECT r = new NativeMethods.RECT(); UnsafeNativeMethods.GetWindowRect(new HandleRef(this, Handle), ref r); NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP(); @@ -2056,24 +2384,29 @@ private void WmMove() { if (ret != 0) { IWin32Window win = (IWin32Window)owners[ti.hwnd]; - if (win == null) { + if (win == null) + { win = (IWin32Window)Control.FromHandle(ti.hwnd); } - - if (win == null) { + + if (win == null) + { return; } - + TipInfo tt = (TipInfo)tools[win]; - if (win == null || tt==null) { - return; + if (win == null || tt == null) + { + return; } // Treeview handles its own ToolTips. TreeView treeView = win as TreeView; - if (treeView != null) { - if (treeView.ShowNodeToolTips) { - return; + if (treeView != null) + { + if (treeView.ShowNodeToolTips) + { + return; } } @@ -2083,27 +2416,31 @@ private void WmMove() { { Reposition(tt.Position, r.Size); } - } + } } /// /// Handles the WM_MOUSEACTIVATE message. /// - private void WmMouseActivate(ref Message msg) { - + private void WmMouseActivate(ref Message msg) + { + NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP(); ti.cbSize = Marshal.SizeOf(); int ret = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_GETCURRENTTOOL, 0, ti); - - if (ret != 0) { + + if (ret != 0) + { IWin32Window win = (IWin32Window)owners[ti.hwnd]; - if (win == null) { + if (win == null) + { win = (IWin32Window)Control.FromHandle(ti.hwnd); } - if (win == null) { + if (win == null) + { return; } @@ -2114,7 +2451,8 @@ private void WmMouseActivate(ref Message msg) { // Do not activate the mouse if its within the bounds of the // the associated tool if (cursorLocation.X >= r.left && cursorLocation.X <= r.right && - cursorLocation.Y >= r.top && cursorLocation.Y <= r.bottom) { + cursorLocation.Y >= r.top && cursorLocation.Y <= r.bottom) + { msg.Result = (IntPtr)NativeMethods.MA_NOACTIVATE; } } @@ -2125,7 +2463,8 @@ private void WmMouseActivate(ref Message msg) { /// /// Handles the WM_WINDOWFROMPOINT message. /// - private void WmWindowFromPoint(ref Message msg) { + private void WmWindowFromPoint(ref Message msg) + { NativeMethods.POINT sc = (NativeMethods.POINT)msg.GetLParam(typeof(NativeMethods.POINT)); Point screenCoords = new Point(sc.x, sc.y); bool result = false; @@ -2137,7 +2476,8 @@ private void WmWindowFromPoint(ref Message msg) { /// /// Handles the TTN_SHOW message. /// - private void WmShow() { + private void WmShow() + { //Get the Bounds.... @@ -2147,22 +2487,25 @@ private void WmShow() { NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP(); ti.cbSize = Marshal.SizeOf(); int ret = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_GETCURRENTTOOL, 0, ti); - - if (ret != 0) { + + if (ret != 0) + { IWin32Window win = (IWin32Window)owners[ti.hwnd]; - if (win == null) { + if (win == null) + { win = (IWin32Window)Control.FromHandle(ti.hwnd); } - - if (win == null) { + + if (win == null) + { return; } Control toolControl = win as Control; Size currentTooltipSize = r.Size; - PopupEventArgs e = new PopupEventArgs(win, toolControl, IsBalloon, currentTooltipSize); + PopupEventArgs e = new PopupEventArgs(win, toolControl, IsBalloon, currentTooltipSize); OnPopup(e); DataGridView dataGridView = toolControl as DataGridView; @@ -2177,13 +2520,15 @@ private void WmShow() { // during the popup event; in which case the size of the tooltip is // affected. e.ToolTipSize is respected over r.Size UnsafeNativeMethods.GetWindowRect(new HandleRef(this, Handle), ref r); - currentTooltipSize = (e.ToolTipSize == currentTooltipSize) ? r.Size:e.ToolTipSize; + currentTooltipSize = (e.ToolTipSize == currentTooltipSize) ? r.Size : e.ToolTipSize; - if (IsBalloon) { - // Get the text display rectangle - UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_ADJUSTRECT, 1, ref r); - if (r.Size.Height > currentTooltipSize.Height) currentTooltipSize.Height = r.Size.Height; + if (IsBalloon) + { + // Get the text display rectangle + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_ADJUSTRECT, 1, ref r); + if (r.Size.Height > currentTooltipSize.Height) + currentTooltipSize.Height = r.Size.Height; } // Set the max possible size of the tooltip to the size we received. @@ -2194,20 +2539,22 @@ private void WmShow() { { Screen screen = Screen.FromPoint(Cursor.Position); int maxwidth = (IsBalloon) ? - Math.Min(currentTooltipSize.Width-2*XBALLOONOFFSET, screen.WorkingArea.Width): + Math.Min(currentTooltipSize.Width - 2 * XBALLOONOFFSET, screen.WorkingArea.Width) : Math.Min(currentTooltipSize.Width, screen.WorkingArea.Width); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_SETMAXTIPWIDTH, 0, maxwidth); } - if (e.Cancel) { + if (e.Cancel) + { cancelled = true; SafeNativeMethods.SetWindowPos(new HandleRef(this, this.Handle), NativeMethods.HWND_TOPMOST, 0, 0, 0, 0, - NativeMethods.SWP_NOACTIVATE | NativeMethods.SWP_NOOWNERZORDER); + NativeMethods.SWP_NOACTIVATE | NativeMethods.SWP_NOOWNERZORDER); } - else { + else + { cancelled = false; // Only width/height changes are respected, so set top,left to what we got earlier SafeNativeMethods.SetWindowPos(new HandleRef(this, this.Handle), @@ -2223,11 +2570,12 @@ private void WmShow() { /// We need to Hide the window since the native tooltip actually calls SetWindowPos in its TTN_SHOW even if we cancel showing the /// tooltip : Hence we need to listen to the WindowPosChanged message can hide the window ourselves. /// - private bool WmWindowPosChanged() { + private bool WmWindowPosChanged() + { if (cancelled) { - SafeNativeMethods.ShowWindow(new HandleRef(this, Handle), NativeMethods.SW_HIDE); - return true; + SafeNativeMethods.ShowWindow(new HandleRef(this, Handle), NativeMethods.SW_HIDE); + return true; } return false; } @@ -2237,30 +2585,34 @@ private bool WmWindowPosChanged() { /// /// Handles the WM_WINDOWPOSCHANGING message. /// - private unsafe void WmWindowPosChanging(ref Message m) { + private unsafe void WmWindowPosChanging(ref Message m) + { if (cancelled || isDisposing) { - return; + return; } - NativeMethods.WINDOWPOS* wp = (NativeMethods.WINDOWPOS *)m.LParam; - + NativeMethods.WINDOWPOS* wp = (NativeMethods.WINDOWPOS*)m.LParam; + Cursor currentCursor = Cursor.CurrentInternal; Point cursorPos = Cursor.Position; - + NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP(); ti.cbSize = Marshal.SizeOf(); int ret = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_GETCURRENTTOOL, 0, ti); - if (ret != 0) { + if (ret != 0) + { IWin32Window win = (IWin32Window)owners[ti.hwnd]; - if (win == null) { + if (win == null) + { win = (IWin32Window)Control.FromHandle(ti.hwnd); } - if (win == null || !IsWindowActive(win)) { + if (win == null || !IsWindowActive(win)) + { return; } @@ -2268,121 +2620,141 @@ private unsafe void WmWindowPosChanging(ref Message m) { if (win != null) { tt = (TipInfo)tools[win]; - if (tt == null) { - return; + if (tt == null) + { + return; } // Treeview handles its own ToolTips. TreeView treeView = win as TreeView; - if (treeView != null) { - if (treeView.ShowNodeToolTips) { - return; + if (treeView != null) + { + if (treeView.ShowNodeToolTips) + { + return; } } } - if (IsBalloon) { - wp->cx += 2*XBALLOONOFFSET; - return; + if (IsBalloon) + { + wp->cx += 2 * XBALLOONOFFSET; + return; } - if ( (tt.TipType & TipInfo.Type.Auto) != 0 && window != null ) + if ((tt.TipType & TipInfo.Type.Auto) != 0 && window != null) { window.DefWndProc(ref m); return; } - if ( ((tt.TipType & TipInfo.Type.SemiAbsolute) != 0) && tt.Position == Point.Empty ) { + if (((tt.TipType & TipInfo.Type.SemiAbsolute) != 0) && tt.Position == Point.Empty) + { - Screen screen = Screen.FromPoint(cursorPos); - if (currentCursor != null) - { + Screen screen = Screen.FromPoint(cursorPos); + if (currentCursor != null) + { wp->x = cursorPos.X; wp->y = cursorPos.Y; - if (wp->y + wp->cy + currentCursor.Size.Height - currentCursor.HotSpot.Y > screen.WorkingArea.Bottom) { + if (wp->y + wp->cy + currentCursor.Size.Height - currentCursor.HotSpot.Y > screen.WorkingArea.Bottom) + { wp->y = cursorPos.Y - wp->cy; } - else { + else + { wp->y = cursorPos.Y + currentCursor.Size.Height - currentCursor.HotSpot.Y; } - } - if (wp->x + wp->cx >screen.WorkingArea.Right) { - wp->x = screen.WorkingArea.Right - wp->cx; - } - - } - else if ((tt.TipType & TipInfo.Type.SemiAbsolute) != 0 && tt.Position != Point.Empty) { - - Screen screen = Screen.FromPoint(tt.Position); - wp->x = tt.Position.X; - if (wp->x + wp->cx >screen.WorkingArea.Right) { - wp->x = screen.WorkingArea.Right - wp->cx; - } - wp->y = tt.Position.Y; - - if (wp->y + wp->cy > screen.WorkingArea.Bottom) { + } + if (wp->x + wp->cx > screen.WorkingArea.Right) + { + wp->x = screen.WorkingArea.Right - wp->cx; + } + + } + else if ((tt.TipType & TipInfo.Type.SemiAbsolute) != 0 && tt.Position != Point.Empty) + { + + Screen screen = Screen.FromPoint(tt.Position); + wp->x = tt.Position.X; + if (wp->x + wp->cx > screen.WorkingArea.Right) + { + wp->x = screen.WorkingArea.Right - wp->cx; + } + wp->y = tt.Position.Y; + + if (wp->y + wp->cy > screen.WorkingArea.Bottom) + { wp->y = screen.WorkingArea.Bottom - wp->cy; - } + } } } - m.Result = IntPtr.Zero; + m.Result = IntPtr.Zero; } /// /// Called just before the tooltip is hidden /// - private void WmPop() { + private void WmPop() + { NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP(); ti.cbSize = Marshal.SizeOf(); int ret = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_GETCURRENTTOOL, 0, ti); - if (ret != 0) { + if (ret != 0) + { IWin32Window win = (IWin32Window)owners[ti.hwnd]; - if (win == null) { + if (win == null) + { win = (IWin32Window)Control.FromHandle(ti.hwnd); } - if (win == null) { + if (win == null) + { return; } Control control = win as Control; TipInfo tt = (TipInfo)tools[win]; - if (tt == null) { - return; + if (tt == null) + { + return; } // Must reset the maxwidth to the screen size. - if ((tt.TipType & TipInfo.Type.Auto) != 0 || (tt.TipType & TipInfo.Type.SemiAbsolute) != 0) { - Screen screen = Screen.FromPoint(Cursor.Position); - UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_SETMAXTIPWIDTH, 0, screen.WorkingArea.Width); + if ((tt.TipType & TipInfo.Type.Auto) != 0 || (tt.TipType & TipInfo.Type.SemiAbsolute) != 0) + { + Screen screen = Screen.FromPoint(Cursor.Position); + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_SETMAXTIPWIDTH, 0, screen.WorkingArea.Width); } // For non-auto tips (those showned through // the show(...) methods, we need to dissassociate // them from the tip control. - if ((tt.TipType & TipInfo.Type.Auto) == 0) { + if ((tt.TipType & TipInfo.Type.Auto) == 0) + { - tools.Remove(control); - owners.Remove(win.Handle); + tools.Remove(control); + owners.Remove(win.Handle); - control.HandleCreated -= new EventHandler(this.HandleCreated); - control.HandleDestroyed -= new EventHandler(this.HandleDestroyed); - created.Remove(control); + control.HandleCreated -= new EventHandler(this.HandleCreated); + control.HandleDestroyed -= new EventHandler(this.HandleDestroyed); + created.Remove(control); - if (originalPopupDelay != 0) { + if (originalPopupDelay != 0) + { AutoPopDelay = originalPopupDelay; originalPopupDelay = 0; - } + } } - else { - // Clear all other flags except for the - // Auto flag to ensure automatic tips can still show - tt.TipType = TipInfo.Type.Auto; - tt.Position = Point.Empty; - tools[control] = tt; + else + { + // Clear all other flags except for the + // Auto flag to ensure automatic tips can still show + tt.TipType = TipInfo.Type.Auto; + tt.Position = Point.Empty; + tools[control] = tt; } } } @@ -2390,169 +2762,195 @@ private void WmPop() { /// /// WNDPROC /// - private void WndProc(ref Message msg) { + private void WndProc(ref Message msg) + { - switch (msg.Msg) { + switch (msg.Msg) + { - case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_NOTIFY: - NativeMethods.NMHDR nmhdr = (NativeMethods.NMHDR) msg.GetLParam(typeof(NativeMethods.NMHDR)); - if (nmhdr.code == NativeMethods.TTN_SHOW && !trackPosition) { - WmShow(); - } - else if (nmhdr.code == NativeMethods.TTN_POP) { - WmPop(); - if (window != null) { - window.DefWndProc(ref msg); + case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_NOTIFY: + NativeMethods.NMHDR nmhdr = (NativeMethods.NMHDR)msg.GetLParam(typeof(NativeMethods.NMHDR)); + if (nmhdr.code == NativeMethods.TTN_SHOW && !trackPosition) + { + WmShow(); } - } - break; - - case Interop.WindowMessages.WM_WINDOWPOSCHANGING: - WmWindowPosChanging(ref msg); - break; - - case Interop.WindowMessages.WM_WINDOWPOSCHANGED: - if (!WmWindowPosChanged() && window != null) - { - window.DefWndProc(ref msg); - } - break; - - case Interop.WindowMessages.WM_MOUSEACTIVATE: - WmMouseActivate(ref msg); - break; - - case Interop.WindowMessages.WM_MOVE: - WmMove(); - break; - - case NativeMethods.TTM_WINDOWFROMPOINT: - WmWindowFromPoint(ref msg); - break; - - case Interop.WindowMessages.WM_PRINTCLIENT: - goto case Interop.WindowMessages.WM_PAINT; - - case Interop.WindowMessages.WM_PAINT: - if (ownerDraw && !isBalloon && !trackPosition) - { - NativeMethods.PAINTSTRUCT ps = new NativeMethods.PAINTSTRUCT(); - IntPtr dc = UnsafeNativeMethods.BeginPaint(new HandleRef(this,Handle),ref ps); - Graphics g = Graphics.FromHdcInternal(dc); - try { - Rectangle bounds = new Rectangle(ps.rcPaint_left,ps.rcPaint_top, - ps.rcPaint_right - ps.rcPaint_left, - ps.rcPaint_bottom - ps.rcPaint_top); - if (bounds == Rectangle.Empty ) { - return; + else if (nmhdr.code == NativeMethods.TTN_POP) + { + WmPop(); + if (window != null) + { + window.DefWndProc(ref msg); } - NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP(); - ti.cbSize = Marshal.SizeOf(); - int ret = unchecked( (int) (long)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_GETCURRENTTOOL, 0, ti)); - if (ret != 0) { - IWin32Window win = (IWin32Window)owners[ti.hwnd]; - Control ac = Control.FromHandle(ti.hwnd); - if (win == null) { - win = (IWin32Window)ac; - } - Font font; - try { - font = Font.FromHfont(UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.WindowMessages.WM_GETFONT, 0, 0)); - } - catch (ArgumentException) { - // If the current default tooltip font is a non-TrueType font, then - // Font.FromHfont throws this exception, so fall back to the default control font. - font = Control.DefaultFont; + } + break; + + case Interop.WindowMessages.WM_WINDOWPOSCHANGING: + WmWindowPosChanging(ref msg); + break; + + case Interop.WindowMessages.WM_WINDOWPOSCHANGED: + if (!WmWindowPosChanged() && window != null) + { + window.DefWndProc(ref msg); + } + break; + + case Interop.WindowMessages.WM_MOUSEACTIVATE: + WmMouseActivate(ref msg); + break; + + case Interop.WindowMessages.WM_MOVE: + WmMove(); + break; + + case NativeMethods.TTM_WINDOWFROMPOINT: + WmWindowFromPoint(ref msg); + break; + + case Interop.WindowMessages.WM_PRINTCLIENT: + goto case Interop.WindowMessages.WM_PAINT; + + case Interop.WindowMessages.WM_PAINT: + if (ownerDraw && !isBalloon && !trackPosition) + { + NativeMethods.PAINTSTRUCT ps = new NativeMethods.PAINTSTRUCT(); + IntPtr dc = UnsafeNativeMethods.BeginPaint(new HandleRef(this, Handle), ref ps); + Graphics g = Graphics.FromHdcInternal(dc); + try + { + Rectangle bounds = new Rectangle(ps.rcPaint_left, ps.rcPaint_top, + ps.rcPaint_right - ps.rcPaint_left, + ps.rcPaint_bottom - ps.rcPaint_top); + if (bounds == Rectangle.Empty) + { + return; } + NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP(); + ti.cbSize = Marshal.SizeOf(); + int ret = unchecked((int)(long)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_GETCURRENTTOOL, 0, ti)); + if (ret != 0) + { + IWin32Window win = (IWin32Window)owners[ti.hwnd]; + Control ac = Control.FromHandle(ti.hwnd); + if (win == null) + { + win = (IWin32Window)ac; + } + Font font; + try + { + font = Font.FromHfont(UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.WindowMessages.WM_GETFONT, 0, 0)); + } + catch (ArgumentException) + { + // If the current default tooltip font is a non-TrueType font, then + // Font.FromHfont throws this exception, so fall back to the default control font. + font = Control.DefaultFont; + } - OnDraw(new DrawToolTipEventArgs(g, win, ac, bounds, GetToolTip(ac), - BackColor, ForeColor, font)); - - break; + OnDraw(new DrawToolTipEventArgs(g, win, ac, bounds, GetToolTip(ac), + BackColor, ForeColor, font)); + + break; + } + } + finally + { + g.Dispose(); + UnsafeNativeMethods.EndPaint(new HandleRef(this, Handle), ref ps); } } - finally + + //If not OwnerDraw, fall through + goto default; + default: + if (window != null) { - g.Dispose(); - UnsafeNativeMethods.EndPaint(new HandleRef(this,Handle),ref ps); + window.DefWndProc(ref msg); } - } - - //If not OwnerDraw, fall through - goto default; - default: - if (window != null) { - window.DefWndProc(ref msg); - } - break; + break; } } /// /// - private class ToolTipNativeWindow : NativeWindow { + private class ToolTipNativeWindow : NativeWindow + { ToolTip control; - internal ToolTipNativeWindow(ToolTip control) { + internal ToolTipNativeWindow(ToolTip control) + { this.control = control; } - - - protected override void WndProc(ref Message m) { - if (control != null) { - control.WndProc(ref m); + + + protected override void WndProc(ref Message m) + { + if (control != null) + { + control.WndProc(ref m); } } } - private class ToolTipTimer : Timer { + private class ToolTipTimer : Timer + { IWin32Window host; - public ToolTipTimer(IWin32Window owner) : base(){ + public ToolTipTimer(IWin32Window owner) : base() + { this.host = owner; } - public IWin32Window Host { - get { + public IWin32Window Host + { + get + { return host; } } } - private class TipInfo { - - [Flags] - public enum Type - { - None = 0x0000, - Auto = 0x0001, - Absolute = 0x0002, - SemiAbsolute = 0x0004 - } - - public Type TipType = Type.Auto; - private string caption; - private string designerText; - public Point Position = Point.Empty; - - public TipInfo(string caption, Type type) { - this.caption = caption; - this.TipType = type; - if (type == Type.Auto) { - this.designerText = caption; - } - } - - public string Caption { - get { - return ((this.TipType & (Type.Absolute | Type.SemiAbsolute)) != 0) ? caption:designerText; - } - set { - this.caption = value; - } - } + private class TipInfo + { + + [Flags] + public enum Type + { + None = 0x0000, + Auto = 0x0001, + Absolute = 0x0002, + SemiAbsolute = 0x0004 + } + + public Type TipType = Type.Auto; + private string caption; + private string designerText; + public Point Position = Point.Empty; + + public TipInfo(string caption, Type type) + { + this.caption = caption; + this.TipType = type; + if (type == Type.Auto) + { + this.designerText = caption; + } + } + + public string Caption + { + get + { + return ((this.TipType & (Type.Absolute | Type.SemiAbsolute)) != 0) ? caption : designerText; + } + set + { + this.caption = value; + } + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolstripProfessionalRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolstripProfessionalRenderer.cs index 96fa1c4b508..46de954ff51 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolstripProfessionalRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolstripProfessionalRenderer.cs @@ -2,8 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { - +namespace System.Windows.Forms +{ + using System; using System.Drawing; using System.Windows.Forms; @@ -14,7 +15,8 @@ namespace System.Windows.Forms { /// /// Summary description for ProfessionalToolStripRenderer. /// - public class ToolStripProfessionalRenderer : ToolStripRenderer { + public class ToolStripProfessionalRenderer : ToolStripRenderer + { private const int GRIP_PADDING = 4; private int gripPadding = GRIP_PADDING; @@ -40,183 +42,222 @@ public class ToolStripProfessionalRenderer : ToolStripRenderer { private ToolStripRenderer toolStripHighContrastRenderer; private ToolStripRenderer toolStripLowResolutionRenderer; - public ToolStripProfessionalRenderer() { + public ToolStripProfessionalRenderer() + { } - internal ToolStripProfessionalRenderer(bool isDefault) : base(isDefault) { + internal ToolStripProfessionalRenderer(bool isDefault) : base(isDefault) + { } - public ToolStripProfessionalRenderer(ProfessionalColorTable professionalColorTable) { - this.professionalColorTable = professionalColorTable; + public ToolStripProfessionalRenderer(ProfessionalColorTable professionalColorTable) + { + this.professionalColorTable = professionalColorTable; } - public ProfessionalColorTable ColorTable { - get { - if (professionalColorTable == null) { + public ProfessionalColorTable ColorTable + { + get + { + if (professionalColorTable == null) + { return ProfessionalColors.ColorTable; } return professionalColorTable; } } - internal override ToolStripRenderer RendererOverride { - get { - if (DisplayInformation.HighContrast) { + internal override ToolStripRenderer RendererOverride + { + get + { + if (DisplayInformation.HighContrast) + { return HighContrastRenderer; } - if (DisplayInformation.LowResolution) { + if (DisplayInformation.LowResolution) + { return LowResolutionRenderer; } return null; } } - internal ToolStripRenderer HighContrastRenderer { - get { - if (toolStripHighContrastRenderer == null) { + internal ToolStripRenderer HighContrastRenderer + { + get + { + if (toolStripHighContrastRenderer == null) + { toolStripHighContrastRenderer = new ToolStripHighContrastRenderer(/*renderLikeSystem*/false); } return toolStripHighContrastRenderer; } } - internal ToolStripRenderer LowResolutionRenderer { - get { - if (toolStripLowResolutionRenderer == null) { + internal ToolStripRenderer LowResolutionRenderer + { + get + { + if (toolStripLowResolutionRenderer == null) + { toolStripLowResolutionRenderer = new ToolStripProfessionalLowResolutionRenderer(); } return toolStripLowResolutionRenderer; } } - - - - public bool RoundedEdges { - get { + + + + public bool RoundedEdges + { + get + { return roundedEdges; } - set { + set + { roundedEdges = value; } } - - private bool UseSystemColors { + + private bool UseSystemColors + { get { return (ColorTable.UseSystemColors || !ToolStripManager.VisualStylesEnabled); } } - protected override void OnRenderToolStripBackground(ToolStripRenderEventArgs e) { - if (RendererOverride != null) { + protected override void OnRenderToolStripBackground(ToolStripRenderEventArgs e) + { + if (RendererOverride != null) + { base.OnRenderToolStripBackground(e); return; } ToolStrip toolStrip = e.ToolStrip; - if (!ShouldPaintBackground(toolStrip)) { + if (!ShouldPaintBackground(toolStrip)) + { return; } - - if (toolStrip is ToolStripDropDown) { + + if (toolStrip is ToolStripDropDown) + { RenderToolStripDropDownBackground(e); } - else if (toolStrip is MenuStrip) { + else if (toolStrip is MenuStrip) + { RenderMenuStripBackground(e); } - else if (toolStrip is StatusStrip) { + else if (toolStrip is StatusStrip) + { RenderStatusStripBackground(e); } - else { + else + { RenderToolStripBackgroundInternal(e); } } - protected override void OnRenderOverflowButtonBackground(ToolStripItemRenderEventArgs e) { - ScaleObjectSizesIfNeeded(); - - if (RendererOverride != null) { + protected override void OnRenderOverflowButtonBackground(ToolStripItemRenderEventArgs e) + { + ScaleObjectSizesIfNeeded(); + + if (RendererOverride != null) + { base.OnRenderOverflowButtonBackground(e); return; } ToolStripItem item = e.Item; Graphics g = e.Graphics; - + // fill in the background colors bool rightToLeft = (item.RightToLeft == RightToLeft.Yes); RenderOverflowBackground(e, rightToLeft); bool horizontal = (e.ToolStrip.Orientation == Orientation.Horizontal); - + Rectangle overflowArrowRect = Rectangle.Empty; - if (rightToLeft) { - overflowArrowRect = new Rectangle(0, item.Height - overflowArrowOffsetY, overflowArrowWidth, overflowArrowHeight); + if (rightToLeft) + { + overflowArrowRect = new Rectangle(0, item.Height - overflowArrowOffsetY, overflowArrowWidth, overflowArrowHeight); } - else { + else + { overflowArrowRect = new Rectangle(item.Width - overflowButtonWidth, item.Height - overflowArrowOffsetY, overflowArrowWidth, overflowArrowHeight); } ArrowDirection direction = (horizontal) ? ArrowDirection.Down : ArrowDirection.Right; // in RTL the white highlight goes BEFORE the black triangle. - int rightToLeftShift = (rightToLeft && horizontal) ? -1: 1; + int rightToLeftShift = (rightToLeft && horizontal) ? -1 : 1; // draw highlight - overflowArrowRect.Offset(1*rightToLeftShift, 1); + overflowArrowRect.Offset(1 * rightToLeftShift, 1); RenderArrowInternal(g, overflowArrowRect, direction, SystemBrushes.ButtonHighlight); // draw black triangle - overflowArrowRect.Offset(-1*rightToLeftShift, -1); + overflowArrowRect.Offset(-1 * rightToLeftShift, -1); Point middle = RenderArrowInternal(g, overflowArrowRect, direction, SystemBrushes.ControlText); // draw lines - if (horizontal) { + if (horizontal) + { rightToLeftShift = (rightToLeft) ? -2 : 0; // width of the both lines is 1 pixel and lines are drawn next to each other, this the highlight line is 1 pixel below the black line - g.DrawLine(SystemPens.ControlText, - middle.X - ToolStripRenderer.Offset2X, - overflowArrowRect.Y - ToolStripRenderer.Offset2Y, - middle.X + ToolStripRenderer.Offset2X, + g.DrawLine(SystemPens.ControlText, + middle.X - ToolStripRenderer.Offset2X, + overflowArrowRect.Y - ToolStripRenderer.Offset2Y, + middle.X + ToolStripRenderer.Offset2X, overflowArrowRect.Y - ToolStripRenderer.Offset2Y); - g.DrawLine(SystemPens.ButtonHighlight, - middle.X - ToolStripRenderer.Offset2X + 1 + rightToLeftShift, - overflowArrowRect.Y - ToolStripRenderer.Offset2Y + 1, - middle.X + ToolStripRenderer.Offset2X + 1 + rightToLeftShift, + g.DrawLine(SystemPens.ButtonHighlight, + middle.X - ToolStripRenderer.Offset2X + 1 + rightToLeftShift, + overflowArrowRect.Y - ToolStripRenderer.Offset2Y + 1, + middle.X + ToolStripRenderer.Offset2X + 1 + rightToLeftShift, overflowArrowRect.Y - ToolStripRenderer.Offset2Y + 1); } - else { - g.DrawLine(SystemPens.ControlText, - overflowArrowRect.X, - middle.Y - ToolStripRenderer.Offset2Y, - overflowArrowRect.X, + else + { + g.DrawLine(SystemPens.ControlText, + overflowArrowRect.X, + middle.Y - ToolStripRenderer.Offset2Y, + overflowArrowRect.X, middle.Y + ToolStripRenderer.Offset2Y); - g.DrawLine(SystemPens.ButtonHighlight, - overflowArrowRect.X + 1, - middle.Y - ToolStripRenderer.Offset2Y + 1, - overflowArrowRect.X + 1, + g.DrawLine(SystemPens.ButtonHighlight, + overflowArrowRect.X + 1, + middle.Y - ToolStripRenderer.Offset2Y + 1, + overflowArrowRect.X + 1, middle.Y + ToolStripRenderer.Offset2Y + 1); } } - protected override void OnRenderDropDownButtonBackground(ToolStripItemRenderEventArgs e) { - if (RendererOverride != null) { + protected override void OnRenderDropDownButtonBackground(ToolStripItemRenderEventArgs e) + { + if (RendererOverride != null) + { base.OnRenderDropDownButtonBackground(e); return; } ToolStripDropDownItem item = e.Item as ToolStripDropDownItem; - if (item != null && item.Pressed && item.HasDropDownItems) { + if (item != null && item.Pressed && item.HasDropDownItems) + { Rectangle bounds = new Rectangle(Point.Empty, item.Size); RenderPressedGradient(e.Graphics, bounds); } - else { + else + { RenderItemInternal(e, /*useHotBorder =*/true); } } - protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e) { - if (RendererOverride != null) { + protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e) + { + if (RendererOverride != null) + { base.OnRenderSeparator(e); return; } @@ -224,8 +265,10 @@ protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e) { RenderSeparatorInternal(e.Graphics, e.Item, new Rectangle(Point.Empty, e.Item.Size), e.Vertical); } - protected override void OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs e) { - if (RendererOverride != null) { + protected override void OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs e) + { + if (RendererOverride != null) + { base.OnRenderSplitButtonBackground(e); return; } @@ -233,21 +276,25 @@ protected override void OnRenderSplitButtonBackground(ToolStripItemRenderEventAr ToolStripSplitButton item = e.Item as ToolStripSplitButton; Graphics g = e.Graphics; - if (item != null) { - + if (item != null) + { + Rectangle bounds = new Rectangle(Point.Empty, item.Size); - if (item.BackgroundImage != null) { + if (item.BackgroundImage != null) + { Rectangle fillRect = (item.Selected) ? item.ContentRectangle : bounds; ControlPaint.DrawBackgroundImage(g, item.BackgroundImage, item.BackColor, item.BackgroundImageLayout, bounds, fillRect); } bool buttonPressedOrSelected = (item.Pressed || item.ButtonPressed || item.Selected || item.ButtonSelected); - if (buttonPressedOrSelected) { + if (buttonPressedOrSelected) + { RenderItemInternal(e, /*useHotBorder =*/true); } - if (item.ButtonPressed) { + if (item.ButtonPressed) + { Rectangle buttonBounds = item.ButtonBounds; // We subtract 1 from each side except the right. // This is because we've already drawn the border, and we don't @@ -257,13 +304,16 @@ protected override void OnRenderSplitButtonBackground(ToolStripItemRenderEventAr buttonBounds = LayoutUtils.DeflateRect(buttonBounds, deflatePadding); RenderPressedButtonFill(g, buttonBounds); } - else if (item.Pressed) { + else if (item.Pressed) + { RenderPressedGradient(e.Graphics, bounds); } Rectangle dropDownRect = item.DropDownButtonBounds; - if (buttonPressedOrSelected && !item.Pressed) { - using (Brush b = new SolidBrush(ColorTable.ButtonSelectedBorder)) { + if (buttonPressedOrSelected && !item.Pressed) + { + using (Brush b = new SolidBrush(ColorTable.ButtonSelectedBorder)) + { g.FillRectangle(b, item.SplitterBounds); } } @@ -271,19 +321,23 @@ protected override void OnRenderSplitButtonBackground(ToolStripItemRenderEventAr } } - protected override void OnRenderToolStripStatusLabelBackground(ToolStripItemRenderEventArgs e) { - if (RendererOverride != null) { + protected override void OnRenderToolStripStatusLabelBackground(ToolStripItemRenderEventArgs e) + { + if (RendererOverride != null) + { base.OnRenderToolStripStatusLabelBackground(e); return; } RenderLabelInternal(e); ToolStripStatusLabel item = e.Item as ToolStripStatusLabel; - ControlPaint.DrawBorder3D(e.Graphics, new Rectangle(0,0,item.Width, item.Height), item.BorderStyle, (Border3DSide)item.BorderSides); + ControlPaint.DrawBorder3D(e.Graphics, new Rectangle(0, 0, item.Width, item.Height), item.BorderStyle, (Border3DSide)item.BorderSides); } - protected override void OnRenderLabelBackground(ToolStripItemRenderEventArgs e) { - if (RendererOverride != null) { + protected override void OnRenderLabelBackground(ToolStripItemRenderEventArgs e) + { + if (RendererOverride != null) + { base.OnRenderLabelBackground(e); return; } @@ -291,9 +345,11 @@ protected override void OnRenderLabelBackground(ToolStripItemRenderEventArgs e) RenderLabelInternal(e); } - - protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e) { - if (RendererOverride != null) { + + protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e) + { + if (RendererOverride != null) + { base.OnRenderButtonBackground(e); return; } @@ -301,48 +357,61 @@ protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e) ToolStripButton item = e.Item as ToolStripButton; Graphics g = e.Graphics; Rectangle bounds = new Rectangle(Point.Empty, item.Size); - - if (item.CheckState == CheckState.Unchecked) { + + if (item.CheckState == CheckState.Unchecked) + { RenderItemInternal(e, /*useHotBorder = */ true); } - else { - Rectangle fillRect = (item.Selected) ? item.ContentRectangle :bounds; - - if (item.BackgroundImage != null) { - ControlPaint.DrawBackgroundImage(g, item.BackgroundImage, item.BackColor, item.BackgroundImageLayout, bounds, fillRect); + else + { + Rectangle fillRect = (item.Selected) ? item.ContentRectangle : bounds; + + if (item.BackgroundImage != null) + { + ControlPaint.DrawBackgroundImage(g, item.BackgroundImage, item.BackColor, item.BackgroundImageLayout, bounds, fillRect); } - if (UseSystemColors) { - if (item.Selected) { + if (UseSystemColors) + { + if (item.Selected) + { RenderPressedButtonFill(g, bounds); } - else { + else + { RenderCheckedButtonFill(g, bounds); } - - using (Pen p = new Pen(ColorTable.ButtonSelectedBorder)) { + + using (Pen p = new Pen(ColorTable.ButtonSelectedBorder)) + { g.DrawRectangle(p, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); } } - else { - if (item.Selected) { - RenderPressedButtonFill(g,bounds); - } - else { - RenderCheckedButtonFill(g,bounds); - } - using (Pen p = new Pen(ColorTable.ButtonSelectedBorder)) { - g.DrawRectangle(p, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); - } - + else + { + if (item.Selected) + { + RenderPressedButtonFill(g, bounds); + } + else + { + RenderCheckedButtonFill(g, bounds); + } + using (Pen p = new Pen(ColorTable.ButtonSelectedBorder)) + { + g.DrawRectangle(p, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); + } + } } } - protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) { - if (RendererOverride != null) { + protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) + { + if (RendererOverride != null) + { base.OnRenderToolStripBorder(e); return; } @@ -350,32 +419,41 @@ protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) { ToolStrip toolStrip = e.ToolStrip; Graphics g = e.Graphics; - - if (toolStrip is ToolStripDropDown) { + + if (toolStrip is ToolStripDropDown) + { RenderToolStripDropDownBorder(e); } - else if (toolStrip is MenuStrip) { + else if (toolStrip is MenuStrip) + { } - else if (toolStrip is StatusStrip) { - RenderStatusStripBorder(e); + else if (toolStrip is StatusStrip) + { + RenderStatusStripBorder(e); } - else { + else + { Rectangle bounds = new Rectangle(Point.Empty, toolStrip.Size); // draw the shadow lines on the bottom and right - using (Pen p = new Pen(ColorTable.ToolStripBorder)) { - if (toolStrip.Orientation == Orientation.Horizontal) { + using (Pen p = new Pen(ColorTable.ToolStripBorder)) + { + if (toolStrip.Orientation == Orientation.Horizontal) + { // horizontal line at bottom g.DrawLine(p, bounds.Left, bounds.Height - 1, bounds.Right, bounds.Height - 1); - if (RoundedEdges) { + if (RoundedEdges) + { // one pix corner rounding (right bottom) g.DrawLine(p, bounds.Width - 2, bounds.Height - 2, bounds.Width - 1, bounds.Height - 3); } } - else { + else + { // draw vertical line on the right - g.DrawLine(p, bounds.Width -1, 0,bounds.Width -1, bounds.Height - 1); - if (RoundedEdges) { + g.DrawLine(p, bounds.Width - 1, 0, bounds.Width - 1, bounds.Height - 1); + if (RoundedEdges) + { // one pix corner rounding (right bottom) g.DrawLine(p, bounds.Width - 2, bounds.Height - 2, bounds.Width - 1, bounds.Height - 3); } @@ -383,20 +461,25 @@ protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) { } } - if (RoundedEdges) { + if (RoundedEdges) + { // OverflowButton rendering - if (toolStrip.OverflowButton.Visible) { + if (toolStrip.OverflowButton.Visible) + { RenderOverflowButtonEffectsOverBorder(e); } - else { + else + { // Draw 1PX edging to round off the toolStrip Rectangle edging = Rectangle.Empty; - if (toolStrip.Orientation == Orientation.Horizontal) { - edging = new Rectangle(bounds.Width - 1, 3, 1, bounds.Height - 3); + if (toolStrip.Orientation == Orientation.Horizontal) + { + edging = new Rectangle(bounds.Width - 1, 3, 1, bounds.Height - 3); } - else { - edging = new Rectangle(3, bounds.Height -1, bounds.Width -3, bounds.Height - 1); + else + { + edging = new Rectangle(3, bounds.Height - 1, bounds.Width - 3, bounds.Height - 1); } ScaleObjectSizesIfNeeded(); @@ -407,8 +490,10 @@ protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) { } } - protected override void OnRenderGrip(ToolStripGripRenderEventArgs e) { - if (RendererOverride != null) { + protected override void OnRenderGrip(ToolStripGripRenderEventArgs e) + { + if (RendererOverride != null) + { base.OnRenderGrip(e); return; } @@ -423,52 +508,61 @@ protected override void OnRenderGrip(ToolStripGripRenderEventArgs e) { int height = (toolStrip.Orientation == Orientation.Horizontal) ? bounds.Height : bounds.Width; int width = (toolStrip.Orientation == Orientation.Horizontal) ? bounds.Width : bounds.Height; - - int numRectangles = (height - (gripPadding * 2)) / 4; - - if (numRectangles > 0) { + int numRectangles = (height - (gripPadding * 2)) / 4; + + + if (numRectangles > 0) + { // a MenuStrip starts its grip lower and has fewer grip rectangles. - int yOffset = (toolStrip is MenuStrip) ? 2 : 0; - + int yOffset = (toolStrip is MenuStrip) ? 2 : 0; + Rectangle[] shadowRects = new Rectangle[numRectangles]; int startY = gripPadding + 1 + yOffset; int startX = (width / 2); - for (int i = 0; i < numRectangles; i++) { + for (int i = 0; i < numRectangles; i++) + { shadowRects[i] = (toolStrip.Orientation == Orientation.Horizontal) ? new Rectangle(startX, startY, 2, 2) : - new Rectangle(startY, startX, 2,2); - + new Rectangle(startY, startX, 2, 2); + startY += 4; } // in RTL the GripLight rects should paint to the left of the GripDark rects. int xOffset = (rightToLeft) ? 1 : -1; - - if (rightToLeft) { + + if (rightToLeft) + { // scoot over the rects in RTL so they fit within the bounds. - for (int i = 0; i < numRectangles; i++) { + for (int i = 0; i < numRectangles; i++) + { shadowRects[i].Offset(-xOffset, 0); } } - using (Brush b = new SolidBrush(ColorTable.GripLight)) { + using (Brush b = new SolidBrush(ColorTable.GripLight)) + { g.FillRectangles(b, shadowRects); } - for (int i = 0; i < numRectangles; i++) { + for (int i = 0; i < numRectangles; i++) + { shadowRects[i].Offset(xOffset, -1); } - using (Brush b = new SolidBrush(ColorTable.GripDark)) { + using (Brush b = new SolidBrush(ColorTable.GripDark)) + { g.FillRectangles(b, shadowRects); } } } - protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) { - if (RendererOverride != null) { + protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) + { + if (RendererOverride != null) + { base.OnRenderMenuItemBackground(e); return; } @@ -477,114 +571,144 @@ protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs Graphics g = e.Graphics; Rectangle bounds = new Rectangle(Point.Empty, item.Size); - if ((bounds.Width == 0) || (bounds.Height == 0)) { + if ((bounds.Width == 0) || (bounds.Height == 0)) + { return; // can't new up a linear gradient brush with no dimension. } - if (item is MdiControlStrip.SystemMenuItem) { + if (item is MdiControlStrip.SystemMenuItem) + { return; // no highlights are painted behind a system menu item } - if (item.IsOnDropDown) { + if (item.IsOnDropDown) + { ScaleObjectSizesIfNeeded(); - + bounds = LayoutUtils.DeflateRect(bounds, scaledDropDownMenuItemPaintPadding); - if (item.Selected) { + if (item.Selected) + { Color borderColor = ColorTable.MenuItemBorder; - if (item.Enabled) { - if (UseSystemColors) { - borderColor = SystemColors.Highlight; - RenderSelectedButtonFill(g, bounds); + if (item.Enabled) + { + if (UseSystemColors) + { + borderColor = SystemColors.Highlight; + RenderSelectedButtonFill(g, bounds); } - else { - using (Brush b = new SolidBrush(ColorTable.MenuItemSelected)) { + else + { + using (Brush b = new SolidBrush(ColorTable.MenuItemSelected)) + { g.FillRectangle(b, bounds); } } } // draw selection border - always drawn regardless of Enabled. - using (Pen p = new Pen(borderColor)) { + using (Pen p = new Pen(borderColor)) + { g.DrawRectangle(p, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); } } - else { + else + { Rectangle fillRect = bounds; - - if (item.BackgroundImage != null) { - ControlPaint.DrawBackgroundImage(g, item.BackgroundImage, item.BackColor, item.BackgroundImageLayout, bounds, fillRect); + + if (item.BackgroundImage != null) + { + ControlPaint.DrawBackgroundImage(g, item.BackgroundImage, item.BackColor, item.BackgroundImageLayout, bounds, fillRect); } - else if (item.Owner != null && item.BackColor != item.Owner.BackColor) { - using (Brush b = new SolidBrush(item.BackColor)) { + else if (item.Owner != null && item.BackColor != item.Owner.BackColor) + { + using (Brush b = new SolidBrush(item.BackColor)) + { g.FillRectangle(b, fillRect); } } } } - else { - - if (item.Pressed) { + else + { + + if (item.Pressed) + { // Toplevel toolstrip rendering - RenderPressedGradient(g, bounds); - + RenderPressedGradient(g, bounds); + } - else if (item.Selected) { + else if (item.Selected) + { //Hot, Pressed behavior // Fill with orange Color borderColor = ColorTable.MenuItemBorder; - if (item.Enabled) { + if (item.Enabled) + { - if (UseSystemColors) { - borderColor = SystemColors.Highlight; - RenderSelectedButtonFill(g, bounds); + if (UseSystemColors) + { + borderColor = SystemColors.Highlight; + RenderSelectedButtonFill(g, bounds); } - else { - using (Brush b = new LinearGradientBrush(bounds, ColorTable.MenuItemSelectedGradientBegin, ColorTable.MenuItemSelectedGradientEnd, LinearGradientMode.Vertical)) { + else + { + using (Brush b = new LinearGradientBrush(bounds, ColorTable.MenuItemSelectedGradientBegin, ColorTable.MenuItemSelectedGradientEnd, LinearGradientMode.Vertical)) + { g.FillRectangle(b, bounds); } } } - + // draw selection border - always drawn regardless of Enabled. - using (Pen p = new Pen(borderColor)) { + using (Pen p = new Pen(borderColor)) + { g.DrawRectangle(p, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); } } - else { + else + { Rectangle fillRect = bounds; - - if (item.BackgroundImage != null) { - ControlPaint.DrawBackgroundImage(g, item.BackgroundImage, item.BackColor, item.BackgroundImageLayout, bounds, fillRect); + + if (item.BackgroundImage != null) + { + ControlPaint.DrawBackgroundImage(g, item.BackgroundImage, item.BackColor, item.BackgroundImageLayout, bounds, fillRect); } - else if (item.Owner != null && item.BackColor != item.Owner.BackColor) { - using (Brush b = new SolidBrush(item.BackColor)) { + else if (item.Owner != null && item.BackColor != item.Owner.BackColor) + { + using (Brush b = new SolidBrush(item.BackColor)) + { g.FillRectangle(b, fillRect); } } } } - + } - protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e) { - if (RendererOverride != null) { + protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e) + { + if (RendererOverride != null) + { base.OnRenderArrow(e); return; } ToolStripItem item = e.Item; - if (item is ToolStripDropDownItem) { + if (item is ToolStripDropDownItem) + { e.DefaultArrowColor = (item.Enabled) ? SystemColors.ControlText : SystemColors.ControlDark; } base.OnRenderArrow(e); } - protected override void OnRenderImageMargin(ToolStripRenderEventArgs e) { - if (RendererOverride != null) { + protected override void OnRenderImageMargin(ToolStripRenderEventArgs e) + { + if (RendererOverride != null) + { base.OnRenderImageMargin(e); return; } @@ -596,27 +720,32 @@ protected override void OnRenderImageMargin(ToolStripRenderEventArgs e) { bounds.Y += 2; bounds.Height -= 4; /*shrink to accomodate 1PX line*/ RightToLeft rightToLeft = e.ToolStrip.RightToLeft; - Color begin = (rightToLeft == RightToLeft.No) ? ColorTable.ImageMarginGradientBegin : ColorTable.ImageMarginGradientEnd; - Color end = (rightToLeft == RightToLeft.No) ? ColorTable.ImageMarginGradientEnd : ColorTable.ImageMarginGradientBegin; - + Color begin = (rightToLeft == RightToLeft.No) ? ColorTable.ImageMarginGradientBegin : ColorTable.ImageMarginGradientEnd; + Color end = (rightToLeft == RightToLeft.No) ? ColorTable.ImageMarginGradientEnd : ColorTable.ImageMarginGradientBegin; + FillWithDoubleGradient(begin, ColorTable.ImageMarginGradientMiddle, end, e.Graphics, bounds, iconWellGradientWidth, iconWellGradientWidth, LinearGradientMode.Horizontal, /*flipHorizontal=*/(e.ToolStrip.RightToLeft == RightToLeft.Yes)); } - protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e) { - if (RendererOverride != null) { + protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e) + { + if (RendererOverride != null) + { base.OnRenderItemText(e); return; } - if (e.Item is ToolStripMenuItem && (e.Item.Selected || e.Item.Pressed)) { + if (e.Item is ToolStripMenuItem && (e.Item.Selected || e.Item.Pressed)) + { e.DefaultTextColor = e.Item.ForeColor; } base.OnRenderItemText(e); } - - protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) { - if (RendererOverride != null) { + + protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) + { + if (RendererOverride != null) + { base.OnRenderItemCheck(e); return; } @@ -624,8 +753,10 @@ protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) RenderCheckBackground(e); base.OnRenderItemCheck(e); } - protected override void OnRenderItemImage(ToolStripItemImageRenderEventArgs e) { - if (RendererOverride != null) { + protected override void OnRenderItemImage(ToolStripItemImageRenderEventArgs e) + { + if (RendererOverride != null) + { base.OnRenderItemImage(e); return; } @@ -633,41 +764,51 @@ protected override void OnRenderItemImage(ToolStripItemImageRenderEventArgs e) { Rectangle imageRect = e.ImageRectangle; Image image = e.Image; - if (e.Item is ToolStripMenuItem) { + if (e.Item is ToolStripMenuItem) + { ToolStripMenuItem item = e.Item as ToolStripMenuItem; - if (item.CheckState != CheckState.Unchecked) { - ToolStripDropDownMenu dropDownMenu = item.ParentInternal as ToolStripDropDownMenu; - if (dropDownMenu != null && !dropDownMenu.ShowCheckMargin && dropDownMenu.ShowImageMargin) { - RenderCheckBackground(e); + if (item.CheckState != CheckState.Unchecked) + { + ToolStripDropDownMenu dropDownMenu = item.ParentInternal as ToolStripDropDownMenu; + if (dropDownMenu != null && !dropDownMenu.ShowCheckMargin && dropDownMenu.ShowImageMargin) + { + RenderCheckBackground(e); } } } - - if (imageRect != Rectangle.Empty && image != null) { - if (!e.Item.Enabled) { + + if (imageRect != Rectangle.Empty && image != null) + { + if (!e.Item.Enabled) + { base.OnRenderItemImage(e); return; } // Since office images dont scoot one px we have to override all painting but enabled = false; - if (e.Item.ImageScaling == ToolStripItemImageScaling.None) { + if (e.Item.ImageScaling == ToolStripItemImageScaling.None) + { e.Graphics.DrawImage(image, imageRect, new Rectangle(Point.Empty, imageRect.Size), GraphicsUnit.Pixel); } - else { + else + { e.Graphics.DrawImage(image, imageRect); } } } - protected override void OnRenderToolStripPanelBackground(ToolStripPanelRenderEventArgs e) { - if (RendererOverride != null) { + protected override void OnRenderToolStripPanelBackground(ToolStripPanelRenderEventArgs e) + { + if (RendererOverride != null) + { base.OnRenderToolStripPanelBackground(e); return; } ToolStripPanel toolStripPanel = e.ToolStripPanel; - - if (!ShouldPaintBackground(toolStripPanel)) { + + if (!ShouldPaintBackground(toolStripPanel)) + { return; } // dont paint background effects @@ -676,38 +817,45 @@ protected override void OnRenderToolStripPanelBackground(ToolStripPanelRenderEve RenderBackgroundGradient(e.Graphics, toolStripPanel, ColorTable.ToolStripPanelGradientBegin, ColorTable.ToolStripPanelGradientEnd); } - protected override void OnRenderToolStripContentPanelBackground(ToolStripContentPanelRenderEventArgs e) { - if (RendererOverride != null) { + protected override void OnRenderToolStripContentPanelBackground(ToolStripContentPanelRenderEventArgs e) + { + if (RendererOverride != null) + { base.OnRenderToolStripContentPanelBackground(e); return; } ToolStripContentPanel toolStripContentPanel = e.ToolStripContentPanel; - if (!ShouldPaintBackground(toolStripContentPanel)) { + if (!ShouldPaintBackground(toolStripContentPanel)) + { return; } - if( SystemInformation.InLockedTerminalSession() ) { + if (SystemInformation.InLockedTerminalSession()) + { return; } // dont paint background effects e.Handled = true; - + e.Graphics.Clear(ColorTable.ToolStripContentPanelGradientEnd); - - // RenderBackgroundGradient(e.Graphics, toolStripContentPanel, ColorTable.ToolStripContentPanelGradientBegin, ColorTable.ToolStripContentPanelGradientEnd); + + // RenderBackgroundGradient(e.Graphics, toolStripContentPanel, ColorTable.ToolStripContentPanelGradientBegin, ColorTable.ToolStripContentPanelGradientEnd); } - #region PrivatePaintHelpers + #region PrivatePaintHelpers // consider make public - internal override Region GetTransparentRegion(ToolStrip toolStrip) { - if (toolStrip is ToolStripDropDown || toolStrip is MenuStrip || toolStrip is StatusStrip) { + internal override Region GetTransparentRegion(ToolStrip toolStrip) + { + if (toolStrip is ToolStripDropDown || toolStrip is MenuStrip || toolStrip is StatusStrip) + { return null; } - if (!RoundedEdges) { + if (!RoundedEdges) + { return null; } Rectangle bounds = new Rectangle(Point.Empty, toolStrip.Size); @@ -715,7 +863,8 @@ internal override Region GetTransparentRegion(ToolStrip toolStrip) { // Render curve // eat away at the corners by drawing the parent background // - if (toolStrip.ParentInternal != null) { + if (toolStrip.ParentInternal != null) + { // // Paint pieces of the parent here to give toolStrip rounded effect // @@ -737,11 +886,13 @@ internal override Region GetTransparentRegion(ToolStrip toolStrip) { // TopSide Rectangle topRightHorizontalPixels, topRightVerticalPixels; - if (toolStrip.OverflowButton.Visible) { + if (toolStrip.OverflowButton.Visible) + { topRightHorizontalPixels = new Rectangle(topRight.X - 1, topRight.Y, 1, 1); topRightVerticalPixels = new Rectangle(topRight.X, topRight.Y, 1, 2); } - else { + else + { topRightHorizontalPixels = new Rectangle(topRight.X - 2, topRight.Y, 2, 1); topRightVerticalPixels = new Rectangle(topRight.X, topRight.Y, 1, 3); } @@ -759,46 +910,53 @@ internal override Region GetTransparentRegion(ToolStrip toolStrip) { } return null; } - + // // We want to make sure the overflow button looks like it's the last thing on // the toolbar. This touches up the few pixels that get clobbered by painting the // border. // - private void RenderOverflowButtonEffectsOverBorder(ToolStripRenderEventArgs e) { - + private void RenderOverflowButtonEffectsOverBorder(ToolStripRenderEventArgs e) + { + ToolStrip toolStrip = e.ToolStrip; ToolStripItem item = toolStrip.OverflowButton; - if (!item.Visible) { + if (!item.Visible) + { return; } - + Graphics g = e.Graphics; - + Color overflowBottomLeftShadow, overflowTopShadow; - if (item.Pressed) { + if (item.Pressed) + { overflowBottomLeftShadow = ColorTable.ButtonPressedGradientBegin; overflowTopShadow = overflowBottomLeftShadow; } - else if (item.Selected) { + else if (item.Selected) + { overflowBottomLeftShadow = ColorTable.ButtonSelectedGradientMiddle; overflowTopShadow = overflowBottomLeftShadow; } - else { + else + { overflowBottomLeftShadow = ColorTable.ToolStripBorder; overflowTopShadow = ColorTable.ToolStripGradientMiddle; } // Extend the gradient color over the border. - using (Brush b = new SolidBrush(overflowBottomLeftShadow)) { + using (Brush b = new SolidBrush(overflowBottomLeftShadow)) + { g.FillRectangle(b, toolStrip.Width - 1, toolStrip.Height - 2, 1, 1); g.FillRectangle(b, toolStrip.Width - 2, toolStrip.Height - 1, 1, 1); } - using (Brush b = new SolidBrush(overflowTopShadow)) { + using (Brush b = new SolidBrush(overflowTopShadow)) + { g.FillRectangle(b, toolStrip.Width - 2, 0, 1, 1); g.FillRectangle(b, toolStrip.Width - 1, 1, 1, 1); } @@ -814,51 +972,62 @@ private void RenderOverflowButtonEffectsOverBorder(ToolStripRenderEventArgs e) { /// /// if there isnt enough room to do (2) and (3) it merges into a single gradient from beginning to end. /// - private void FillWithDoubleGradient(Color beginColor, Color middleColor, Color endColor, Graphics g, Rectangle bounds, int firstGradientWidth, int secondGradientWidth, LinearGradientMode mode, bool flipHorizontal) { - if ((bounds.Width == 0) || (bounds.Height == 0)) { + private void FillWithDoubleGradient(Color beginColor, Color middleColor, Color endColor, Graphics g, Rectangle bounds, int firstGradientWidth, int secondGradientWidth, LinearGradientMode mode, bool flipHorizontal) + { + if ((bounds.Width == 0) || (bounds.Height == 0)) + { return; // can't new up a linear gradient brush with no dimension. } Rectangle endGradient = bounds; Rectangle beginGradient = bounds; bool useDoubleGradient = true; - if (mode == LinearGradientMode.Horizontal) { - if (flipHorizontal) { + if (mode == LinearGradientMode.Horizontal) + { + if (flipHorizontal) + { Color temp = endColor; endColor = beginColor; beginColor = temp; } - + beginGradient.Width = firstGradientWidth; endGradient.Width = secondGradientWidth + 1; endGradient.X = bounds.Right - endGradient.Width; useDoubleGradient = (bounds.Width > (firstGradientWidth + secondGradientWidth)); } - else { + else + { beginGradient.Height = firstGradientWidth; endGradient.Height = secondGradientWidth + 1; endGradient.Y = bounds.Bottom - endGradient.Height; useDoubleGradient = (bounds.Height > (firstGradientWidth + secondGradientWidth)); } - if (useDoubleGradient) { + if (useDoubleGradient) + { // Fill with middleColor - using (Brush b = new SolidBrush(middleColor)) { + using (Brush b = new SolidBrush(middleColor)) + { g.FillRectangle(b, bounds); } // draw first gradient - using (Brush b = new LinearGradientBrush(beginGradient, beginColor, middleColor, mode)) { + using (Brush b = new LinearGradientBrush(beginGradient, beginColor, middleColor, mode)) + { g.FillRectangle(b, beginGradient); } // draw second gradient - using (LinearGradientBrush b = new LinearGradientBrush(endGradient, middleColor, endColor, mode)) { - if (mode == LinearGradientMode.Horizontal) { + using (LinearGradientBrush b = new LinearGradientBrush(endGradient, middleColor, endColor, mode)) + { + if (mode == LinearGradientMode.Horizontal) + { endGradient.X += 1; endGradient.Width -= 1; } - else { + else + { endGradient.Y += 1; endGradient.Height -= 1; } @@ -866,128 +1035,159 @@ private void FillWithDoubleGradient(Color beginColor, Color middleColor, Color e g.FillRectangle(b, endGradient); } } - else { + else + { // not big enough for a swath in the middle. lets just do a single gradient. - using (Brush b = new LinearGradientBrush(bounds, beginColor, endColor, mode)) { + using (Brush b = new LinearGradientBrush(bounds, beginColor, endColor, mode)) + { g.FillRectangle(b, bounds); } } } - private void RenderStatusStripBorder(ToolStripRenderEventArgs e) { - e.Graphics.DrawLine(SystemPens.ButtonHighlight, 0,0,e.ToolStrip.Width, 0); + private void RenderStatusStripBorder(ToolStripRenderEventArgs e) + { + e.Graphics.DrawLine(SystemPens.ButtonHighlight, 0, 0, e.ToolStrip.Width, 0); } - - private void RenderStatusStripBackground(ToolStripRenderEventArgs e) { + + private void RenderStatusStripBackground(ToolStripRenderEventArgs e) + { StatusStrip statusStrip = e.ToolStrip as StatusStrip; RenderBackgroundGradient(e.Graphics, statusStrip, ColorTable.StatusStripGradientBegin, ColorTable.StatusStripGradientEnd, statusStrip.Orientation); } - private void RenderCheckBackground(ToolStripItemImageRenderEventArgs e) { + private void RenderCheckBackground(ToolStripItemImageRenderEventArgs e) + { // - Rectangle bounds = DpiHelper.IsScalingRequired ? new Rectangle(e.ImageRectangle.Left-2, (e.Item.Height - e.ImageRectangle.Height )/2- 1, e.ImageRectangle.Width+4, e.ImageRectangle.Height +2) : - new Rectangle(e.ImageRectangle.Left - 2, 1, e.ImageRectangle.Width + 4, e.Item.Height - 2); + Rectangle bounds = DpiHelper.IsScalingRequired ? new Rectangle(e.ImageRectangle.Left - 2, (e.Item.Height - e.ImageRectangle.Height) / 2 - 1, e.ImageRectangle.Width + 4, e.ImageRectangle.Height + 2) : + new Rectangle(e.ImageRectangle.Left - 2, 1, e.ImageRectangle.Width + 4, e.Item.Height - 2); Graphics g = e.Graphics; - if (!UseSystemColors) { + if (!UseSystemColors) + { Color fill = (e.Item.Selected) ? ColorTable.CheckSelectedBackground : ColorTable.CheckBackground; fill = (e.Item.Pressed) ? ColorTable.CheckPressedBackground : fill; - using (Brush b = new SolidBrush(fill)) { + using (Brush b = new SolidBrush(fill)) + { g.FillRectangle(b, bounds); } - using (Pen p = new Pen(ColorTable.ButtonSelectedBorder)) { + using (Pen p = new Pen(ColorTable.ButtonSelectedBorder)) + { g.DrawRectangle(p, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); } } - else { - if (e.Item.Pressed) { + else + { + if (e.Item.Pressed) + { RenderPressedButtonFill(g, bounds); } - else { + else + { RenderSelectedButtonFill(g, bounds); } g.DrawRectangle(SystemPens.Highlight, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); } } - - private void RenderPressedGradient(Graphics g, Rectangle bounds) { - if ((bounds.Width == 0) || (bounds.Height == 0)) { + + private void RenderPressedGradient(Graphics g, Rectangle bounds) + { + if ((bounds.Width == 0) || (bounds.Height == 0)) + { return; // can't new up a linear gradient brush with no dimension. } // Paints a horizontal gradient similar to the image margin. - using (Brush b = new LinearGradientBrush(bounds, ColorTable.MenuItemPressedGradientBegin, ColorTable.MenuItemPressedGradientEnd, LinearGradientMode.Vertical)) { + using (Brush b = new LinearGradientBrush(bounds, ColorTable.MenuItemPressedGradientBegin, ColorTable.MenuItemPressedGradientEnd, LinearGradientMode.Vertical)) + { g.FillRectangle(b, bounds); } // draw a box around the gradient - using (Pen p = new Pen(ColorTable.MenuBorder)) { + using (Pen p = new Pen(ColorTable.MenuBorder)) + { g.DrawRectangle(p, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); } } - private void RenderMenuStripBackground(ToolStripRenderEventArgs e) { + private void RenderMenuStripBackground(ToolStripRenderEventArgs e) + { RenderBackgroundGradient(e.Graphics, e.ToolStrip, ColorTable.MenuStripGradientBegin, ColorTable.MenuStripGradientEnd, e.ToolStrip.Orientation); } - private static void RenderLabelInternal(ToolStripItemRenderEventArgs e) { + private static void RenderLabelInternal(ToolStripItemRenderEventArgs e) + { Graphics g = e.Graphics; ToolStripItem item = e.Item; Rectangle bounds = new Rectangle(Point.Empty, item.Size); - - Rectangle fillRect = (item.Selected) ? item.ContentRectangle :bounds; - - if (item.BackgroundImage != null) { - ControlPaint.DrawBackgroundImage(g, item.BackgroundImage, item.BackColor, item.BackgroundImageLayout, bounds, fillRect); + + Rectangle fillRect = (item.Selected) ? item.ContentRectangle : bounds; + + if (item.BackgroundImage != null) + { + ControlPaint.DrawBackgroundImage(g, item.BackgroundImage, item.BackColor, item.BackgroundImageLayout, bounds, fillRect); } } - private void RenderBackgroundGradient(Graphics g, Control control, Color beginColor, Color endColor) { - RenderBackgroundGradient(g,control,beginColor,endColor,Orientation.Horizontal); + private void RenderBackgroundGradient(Graphics g, Control control, Color beginColor, Color endColor) + { + RenderBackgroundGradient(g, control, beginColor, endColor, Orientation.Horizontal); } // renders the overall gradient - private void RenderBackgroundGradient(Graphics g, Control control, Color beginColor, Color endColor, Orientation orientation) { - - if (control.RightToLeft == RightToLeft.Yes) { - Color temp = beginColor; - beginColor = endColor; - endColor = temp; - } - - if (orientation == Orientation.Horizontal) { - Control parent = control.ParentInternal; - if (parent != null) { - Rectangle gradientBounds = new Rectangle(Point.Empty, parent.Size); - if (!LayoutUtils.IsZeroWidthOrHeight(gradientBounds)) { - using (LinearGradientBrush b = new LinearGradientBrush(gradientBounds, beginColor, endColor, LinearGradientMode.Horizontal)){ - b.TranslateTransform(parent.Width - control.Location.X, parent.Height -control.Location.Y); - g.FillRectangle(b, new Rectangle(Point.Empty, control.Size)); - } - } - } - else { - Rectangle gradientBounds = new Rectangle(Point.Empty, control.Size); - if (!LayoutUtils.IsZeroWidthOrHeight(gradientBounds)) { - // dont have a parent that we know about so go ahead and paint the gradient as if there wasnt another container. - using (LinearGradientBrush b = new LinearGradientBrush(gradientBounds, beginColor, endColor, LinearGradientMode.Horizontal)){ - g.FillRectangle(b, gradientBounds); - } - } - } - } - else { - using (Brush b = new SolidBrush(beginColor)) { - g.FillRectangle(b, new Rectangle(Point.Empty, control.Size)); - } - } - } - - - private void RenderToolStripBackgroundInternal(ToolStripRenderEventArgs e) { + private void RenderBackgroundGradient(Graphics g, Control control, Color beginColor, Color endColor, Orientation orientation) + { + + if (control.RightToLeft == RightToLeft.Yes) + { + Color temp = beginColor; + beginColor = endColor; + endColor = temp; + } + + if (orientation == Orientation.Horizontal) + { + Control parent = control.ParentInternal; + if (parent != null) + { + Rectangle gradientBounds = new Rectangle(Point.Empty, parent.Size); + if (!LayoutUtils.IsZeroWidthOrHeight(gradientBounds)) + { + using (LinearGradientBrush b = new LinearGradientBrush(gradientBounds, beginColor, endColor, LinearGradientMode.Horizontal)) + { + b.TranslateTransform(parent.Width - control.Location.X, parent.Height - control.Location.Y); + g.FillRectangle(b, new Rectangle(Point.Empty, control.Size)); + } + } + } + else + { + Rectangle gradientBounds = new Rectangle(Point.Empty, control.Size); + if (!LayoutUtils.IsZeroWidthOrHeight(gradientBounds)) + { + // dont have a parent that we know about so go ahead and paint the gradient as if there wasnt another container. + using (LinearGradientBrush b = new LinearGradientBrush(gradientBounds, beginColor, endColor, LinearGradientMode.Horizontal)) + { + g.FillRectangle(b, gradientBounds); + } + } + } + } + else + { + using (Brush b = new SolidBrush(beginColor)) + { + g.FillRectangle(b, new Rectangle(Point.Empty, control.Size)); + } + } + } + + + private void RenderToolStripBackgroundInternal(ToolStripRenderEventArgs e) + { ScaleObjectSizesIfNeeded(); ToolStrip toolStrip = e.ToolStrip; @@ -1000,76 +1200,90 @@ private void RenderToolStripBackgroundInternal(ToolStripRenderEventArgs e) { } - private void RenderToolStripDropDownBackground(ToolStripRenderEventArgs e) { + private void RenderToolStripDropDownBackground(ToolStripRenderEventArgs e) + { ToolStrip toolStrip = e.ToolStrip; Rectangle bounds = new Rectangle(Point.Empty, e.ToolStrip.Size); - using (Brush b = new SolidBrush(ColorTable.ToolStripDropDownBackground)) { + using (Brush b = new SolidBrush(ColorTable.ToolStripDropDownBackground)) + { e.Graphics.FillRectangle(b, bounds); } } - private void RenderToolStripDropDownBorder(ToolStripRenderEventArgs e) { + private void RenderToolStripDropDownBorder(ToolStripRenderEventArgs e) + { ToolStripDropDown toolStripDropDown = e.ToolStrip as ToolStripDropDown; Graphics g = e.Graphics; - if (toolStripDropDown != null) { + if (toolStripDropDown != null) + { Rectangle bounds = new Rectangle(Point.Empty, toolStripDropDown.Size); - using (Pen p = new Pen(ColorTable.MenuBorder)) { + using (Pen p = new Pen(ColorTable.MenuBorder)) + { g.DrawRectangle(p, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); } - if (!(toolStripDropDown is ToolStripOverflow)) { + if (!(toolStripDropDown is ToolStripOverflow)) + { // make the neck connected. - using (Brush b = new SolidBrush(ColorTable.ToolStripDropDownBackground)) { + using (Brush b = new SolidBrush(ColorTable.ToolStripDropDownBackground)) + { g.FillRectangle(b, e.ConnectedArea); } } } } - private void RenderOverflowBackground(ToolStripItemRenderEventArgs e, bool rightToLeft) { + private void RenderOverflowBackground(ToolStripItemRenderEventArgs e, bool rightToLeft) + { ScaleObjectSizesIfNeeded(); Graphics g = e.Graphics; ToolStripOverflowButton item = e.Item as ToolStripOverflowButton; Rectangle overflowBoundsFill = new Rectangle(Point.Empty, e.Item.Size); Rectangle bounds = overflowBoundsFill; - + bool drawCurve = (RoundedEdges && (!(item.GetCurrentParent() is MenuStrip))); bool horizontal = (e.ToolStrip.Orientation == Orientation.Horizontal); // undone RTL - if (horizontal) { + if (horizontal) + { overflowBoundsFill.X += overflowBoundsFill.Width - overflowButtonWidth + 1; overflowBoundsFill.Width = overflowButtonWidth; - if (rightToLeft) { - overflowBoundsFill = LayoutUtils.RTLTranslate(overflowBoundsFill, bounds); + if (rightToLeft) + { + overflowBoundsFill = LayoutUtils.RTLTranslate(overflowBoundsFill, bounds); } } - else { + else + { overflowBoundsFill.Y = overflowBoundsFill.Height - overflowButtonWidth + 1; overflowBoundsFill.Height = overflowButtonWidth; } - + Color overflowButtonGradientBegin, overflowButtonGradientMiddle, overflowButtonGradientEnd, overflowBottomLeftShadow, overflowTopShadow; - if (item.Pressed) { + if (item.Pressed) + { overflowButtonGradientBegin = ColorTable.ButtonPressedGradientBegin; overflowButtonGradientMiddle = ColorTable.ButtonPressedGradientMiddle; overflowButtonGradientEnd = ColorTable.ButtonPressedGradientEnd; overflowBottomLeftShadow = ColorTable.ButtonPressedGradientBegin; overflowTopShadow = overflowBottomLeftShadow; } - else if (item.Selected) { + else if (item.Selected) + { overflowButtonGradientBegin = ColorTable.ButtonSelectedGradientBegin; overflowButtonGradientMiddle = ColorTable.ButtonSelectedGradientMiddle; overflowButtonGradientEnd = ColorTable.ButtonSelectedGradientEnd; overflowBottomLeftShadow = ColorTable.ButtonSelectedGradientMiddle; overflowTopShadow = overflowBottomLeftShadow; } - else { + else + { overflowButtonGradientBegin = ColorTable.OverflowButtonGradientBegin; overflowButtonGradientMiddle = ColorTable.OverflowButtonGradientMiddle; overflowButtonGradientEnd = ColorTable.OverflowButtonGradientEnd; @@ -1077,15 +1291,18 @@ private void RenderOverflowBackground(ToolStripItemRenderEventArgs e, bool right overflowTopShadow = (horizontal) ? ColorTable.ToolStripGradientMiddle : ColorTable.ToolStripGradientEnd; } - if (drawCurve) { + if (drawCurve) + { // draw shadow pixel on bottom left +1, +1 - using (Pen p = new Pen(overflowBottomLeftShadow/*Color.HotPink*/)) { - + using (Pen p = new Pen(overflowBottomLeftShadow/*Color.HotPink*/)) + { + Point start = new Point(overflowBoundsFill.Left - 1, overflowBoundsFill.Height - 2); Point end = new Point(overflowBoundsFill.Left, overflowBoundsFill.Height - 2); - if (rightToLeft) { - start.X = overflowBoundsFill.Right +1; - end.X = overflowBoundsFill.Right; + if (rightToLeft) + { + start.X = overflowBoundsFill.Right + 1; + end.X = overflowBoundsFill.Right; } g.DrawLine(p, start, end); } @@ -1096,47 +1313,57 @@ private void RenderOverflowBackground(ToolStripItemRenderEventArgs e, bool right FillWithDoubleGradient(overflowButtonGradientBegin, overflowButtonGradientMiddle, overflowButtonGradientEnd, g, overflowBoundsFill, iconWellGradientWidth, iconWellGradientWidth, mode, false); // render shadow pixels (ToolStrip only) - if (drawCurve) { + if (drawCurve) + { // top left and top right shadow pixels - using (Brush b = new SolidBrush(overflowTopShadow/*Color.Orange*/)) { - if (horizontal) { + using (Brush b = new SolidBrush(overflowTopShadow/*Color.Orange*/)) + { + if (horizontal) + { Point top1 = new Point(overflowBoundsFill.X - 2, 0); Point top2 = new Point(overflowBoundsFill.X - 1, 1); - if (rightToLeft) { + if (rightToLeft) + { top1.X = overflowBoundsFill.Right + 1; top2.X = overflowBoundsFill.Right; } g.FillRectangle(b, top1.X, top1.Y, 1, 1); g.FillRectangle(b, top2.X, top2.Y, 1, 1); } - else { + else + { g.FillRectangle(b, overflowBoundsFill.Width - 3, overflowBoundsFill.Top - 1, 1, 1); g.FillRectangle(b, overflowBoundsFill.Width - 2, overflowBoundsFill.Top - 2, 1, 1); } } - using (Brush b = new SolidBrush(overflowButtonGradientBegin/*Color.Green*/)) { - if (horizontal) { + using (Brush b = new SolidBrush(overflowButtonGradientBegin/*Color.Green*/)) + { + if (horizontal) + { Rectangle fillRect = new Rectangle(overflowBoundsFill.X - 1, 0, 1, 1); - if (rightToLeft) { + if (rightToLeft) + { fillRect.X = overflowBoundsFill.Right; } g.FillRectangle(b, fillRect); } - else { + else + { g.FillRectangle(b, overflowBoundsFill.X, overflowBoundsFill.Top - 1, 1, 1); } } } - + } - private void RenderToolStripCurve(ToolStripRenderEventArgs e) { + private void RenderToolStripCurve(ToolStripRenderEventArgs e) + { Rectangle bounds = new Rectangle(Point.Empty, e.ToolStrip.Size); ToolStrip toolStrip = e.ToolStrip; Rectangle displayRect = toolStrip.DisplayRectangle; - + Graphics g = e.Graphics; Point topLeft = Point.Empty; @@ -1148,7 +1375,8 @@ private void RenderToolStripCurve(ToolStripRenderEventArgs e) { // // Draw in rounded shadow pixels on the top left & right // consider: if this is slow use precanned corners. - using (Brush b = new SolidBrush(ColorTable.ToolStripGradientMiddle)) { + using (Brush b = new SolidBrush(ColorTable.ToolStripGradientMiddle)) + { // there are two shadow rects (one pixel wide) on the top Rectangle topLeftShadowRect = new Rectangle(topLeft, onePix); topLeftShadowRect.X += 1; @@ -1169,72 +1397,90 @@ private void RenderToolStripCurve(ToolStripRenderEventArgs e) { Rectangle[] paintRects = new Rectangle[] { topLeftShadowRect, topLeftShadowRect2, topRightShadowRect, topRightShadowRect2 }; // prevent the painting of anything that would obscure an item. - for (int i = 0; i < paintRects.Length; i++) { - if (displayRect.IntersectsWith(paintRects[i])) { + for (int i = 0; i < paintRects.Length; i++) + { + if (displayRect.IntersectsWith(paintRects[i])) + { paintRects[i] = Rectangle.Empty; - } + } } g.FillRectangles(b, paintRects); - + } // Draw in rounded shadow pixels on the bottom left - using (Brush b = new SolidBrush(ColorTable.ToolStripGradientEnd)) { + using (Brush b = new SolidBrush(ColorTable.ToolStripGradientEnd)) + { // this gradient is the one just before the dark shadow line starts on pixel #3. Point gradientCopyPixel = bottomLeft; gradientCopyPixel.Offset(1, -1); - if (!displayRect.Contains(gradientCopyPixel)) { - g.FillRectangle(b, new Rectangle(gradientCopyPixel, onePix)); + if (!displayRect.Contains(gradientCopyPixel)) + { + g.FillRectangle(b, new Rectangle(gradientCopyPixel, onePix)); } // set the one dark pixel in the bottom left hand corner Rectangle otherBottom = new Rectangle(bottomLeft.X, bottomLeft.Y - 2, 1, 1); - if (!displayRect.IntersectsWith(otherBottom)) { + if (!displayRect.IntersectsWith(otherBottom)) + { g.FillRectangle(b, otherBottom); - } + } } } - private void RenderSelectedButtonFill(Graphics g, Rectangle bounds) { - if ((bounds.Width == 0) || (bounds.Height == 0)) { + private void RenderSelectedButtonFill(Graphics g, Rectangle bounds) + { + if ((bounds.Width == 0) || (bounds.Height == 0)) + { return; // can't new up a linear gradient brush with no dimension. } - if (!UseSystemColors) { - using (Brush b = new LinearGradientBrush(bounds, ColorTable.ButtonSelectedGradientBegin, ColorTable.ButtonSelectedGradientEnd, LinearGradientMode.Vertical)) { + if (!UseSystemColors) + { + using (Brush b = new LinearGradientBrush(bounds, ColorTable.ButtonSelectedGradientBegin, ColorTable.ButtonSelectedGradientEnd, LinearGradientMode.Vertical)) + { g.FillRectangle(b, bounds); } } - else { + else + { Color fillColor = ColorTable.ButtonSelectedHighlight; - using (Brush b = new SolidBrush(fillColor)) { + using (Brush b = new SolidBrush(fillColor)) + { + g.FillRectangle(b, bounds); + } + } + } + private void RenderCheckedButtonFill(Graphics g, Rectangle bounds) + { + if ((bounds.Width == 0) || (bounds.Height == 0)) + { + return; // can't new up a linear gradient brush with no dimension. + } + + if (!UseSystemColors) + { + using (Brush b = new LinearGradientBrush(bounds, ColorTable.ButtonCheckedGradientBegin, ColorTable.ButtonCheckedGradientEnd, LinearGradientMode.Vertical)) + { + g.FillRectangle(b, bounds); + } + } + else + { + + Color fillColor = ColorTable.ButtonCheckedHighlight; + + using (Brush b = new SolidBrush(fillColor)) + { g.FillRectangle(b, bounds); + } } } - private void RenderCheckedButtonFill(Graphics g, Rectangle bounds) { - if ((bounds.Width == 0) || (bounds.Height == 0)) { - return; // can't new up a linear gradient brush with no dimension. - } - - if (!UseSystemColors) { - using (Brush b = new LinearGradientBrush(bounds, ColorTable.ButtonCheckedGradientBegin, ColorTable.ButtonCheckedGradientEnd, LinearGradientMode.Vertical)) { - g.FillRectangle(b, bounds); - } - } - else { - - Color fillColor = ColorTable.ButtonCheckedHighlight; - - using (Brush b = new SolidBrush(fillColor)) { - g.FillRectangle(b, bounds); - - } - } - } - - private void RenderSeparatorInternal(Graphics g, ToolStripItem item, Rectangle bounds, bool vertical) { + + private void RenderSeparatorInternal(Graphics g, ToolStripItem item, Rectangle bounds, bool vertical) + { Color foreColor = ColorTable.SeparatorDark; Color highlightColor = ColorTable.SeparatorLight; Pen foreColorPen = new Pen(foreColor); @@ -1245,42 +1491,53 @@ private void RenderSeparatorInternal(Graphics g, ToolStripItem item, Rectangle b bool disposeHighlightColorColorPen = true; bool isASeparator = item is ToolStripSeparator; bool isAHorizontalSeparatorNotOnDropDownMenu = false; - - if (isASeparator) { - if (vertical) { - if (!item.IsOnDropDown) { + + if (isASeparator) + { + if (vertical) + { + if (!item.IsOnDropDown) + { // center so that it matches office bounds.Y += 3; - bounds.Height = Math.Max(0, bounds.Height -6); + bounds.Height = Math.Max(0, bounds.Height - 6); } } - else { + else + { // offset after the image margin ToolStripDropDownMenu dropDownMenu = item.GetCurrentParent() as ToolStripDropDownMenu; - if (dropDownMenu != null) { - if (dropDownMenu.RightToLeft == RightToLeft.No) { + if (dropDownMenu != null) + { + if (dropDownMenu.RightToLeft == RightToLeft.No) + { // scoot over by the padding (that will line you up with the text - but go two PX before so that it visually looks // like the line meets up with the text). - bounds.X += dropDownMenu.Padding.Left -2; - bounds.Width = dropDownMenu.Width - bounds.X; + bounds.X += dropDownMenu.Padding.Left - 2; + bounds.Width = dropDownMenu.Width - bounds.X; } - else { - // scoot over by the padding (that will line you up with the text - but go two PX before so that it visually looks - // like the line meets up with the text). - bounds.X += 2; - bounds.Width = dropDownMenu.Width - bounds.X - dropDownMenu.Padding.Right; + else + { + // scoot over by the padding (that will line you up with the text - but go two PX before so that it visually looks + // like the line meets up with the text). + bounds.X += 2; + bounds.Width = dropDownMenu.Width - bounds.X - dropDownMenu.Padding.Right; } } - else { + else + { isAHorizontalSeparatorNotOnDropDownMenu = true; } } } - try { - if (vertical) { - if (bounds.Height >= 4) { + try + { + if (vertical) + { + if (bounds.Height >= 4) + { bounds.Inflate(0, -2); // scoot down 2PX and start drawing } @@ -1297,100 +1554,124 @@ private void RenderSeparatorInternal(Graphics g, ToolStripItem item, Rectangle b startX++; g.DrawLine(rightPen, startX, bounds.Top + 1, startX, bounds.Bottom); } - else { + else + { // // horizontal separator // Draw dark line - if (isAHorizontalSeparatorNotOnDropDownMenu && bounds.Width >= 4) { + if (isAHorizontalSeparatorNotOnDropDownMenu && bounds.Width >= 4) + { bounds.Inflate(-2, 0); // scoot down 2PX and start drawing } int startY = bounds.Height / 2; g.DrawLine(foreColorPen, bounds.Left, startY, bounds.Right - 1, startY); - if (!isASeparator || isAHorizontalSeparatorNotOnDropDownMenu) { + if (!isASeparator || isAHorizontalSeparatorNotOnDropDownMenu) + { // Draw highlight one pixel to the right startY++; g.DrawLine(highlightColorPen, bounds.Left + 1, startY, bounds.Right - 1, startY); } } } - finally { - if (disposeForeColorPen && foreColorPen != null) { + finally + { + if (disposeForeColorPen && foreColorPen != null) + { foreColorPen.Dispose(); } - if (disposeHighlightColorColorPen && highlightColorPen != null) { + if (disposeHighlightColorColorPen && highlightColorPen != null) + { highlightColorPen.Dispose(); } } } - private void RenderPressedButtonFill(Graphics g, Rectangle bounds) { + private void RenderPressedButtonFill(Graphics g, Rectangle bounds) + { - if ((bounds.Width == 0) || (bounds.Height == 0)) { + if ((bounds.Width == 0) || (bounds.Height == 0)) + { return; // can't new up a linear gradient brush with no dimension. } - if (!UseSystemColors) { - using (Brush b = new LinearGradientBrush(bounds, ColorTable.ButtonPressedGradientBegin, ColorTable.ButtonPressedGradientEnd, LinearGradientMode.Vertical)) { + if (!UseSystemColors) + { + using (Brush b = new LinearGradientBrush(bounds, ColorTable.ButtonPressedGradientBegin, ColorTable.ButtonPressedGradientEnd, LinearGradientMode.Vertical)) + { g.FillRectangle(b, bounds); } } - else { - + else + { + Color fillColor = ColorTable.ButtonPressedHighlight; - using (Brush b = new SolidBrush(fillColor)) { + using (Brush b = new SolidBrush(fillColor)) + { g.FillRectangle(b, bounds); } } } - private void RenderItemInternal(ToolStripItemRenderEventArgs e, bool useHotBorder) { + private void RenderItemInternal(ToolStripItemRenderEventArgs e, bool useHotBorder) + { Graphics g = e.Graphics; ToolStripItem item = e.Item; Rectangle bounds = new Rectangle(Point.Empty, item.Size); bool drawHotBorder = false; - Rectangle fillRect = (item.Selected) ? item.ContentRectangle :bounds; + Rectangle fillRect = (item.Selected) ? item.ContentRectangle : bounds; - if (item.BackgroundImage != null) { - ControlPaint.DrawBackgroundImage(g, item.BackgroundImage, item.BackColor, item.BackgroundImageLayout, bounds, fillRect); + if (item.BackgroundImage != null) + { + ControlPaint.DrawBackgroundImage(g, item.BackgroundImage, item.BackColor, item.BackgroundImageLayout, bounds, fillRect); } - if (item.Pressed) { + if (item.Pressed) + { RenderPressedButtonFill(g, bounds); drawHotBorder = useHotBorder; } - else if (item.Selected) { + else if (item.Selected) + { RenderSelectedButtonFill(g, bounds); drawHotBorder = useHotBorder; } - else if (item.Owner != null && item.BackColor != item.Owner.BackColor) { - using (Brush b = new SolidBrush(item.BackColor)) { + else if (item.Owner != null && item.BackColor != item.Owner.BackColor) + { + using (Brush b = new SolidBrush(item.BackColor)) + { g.FillRectangle(b, bounds); } } - if (drawHotBorder) { - using (Pen p = new Pen(ColorTable.ButtonSelectedBorder)) { + if (drawHotBorder) + { + using (Pen p = new Pen(ColorTable.ButtonSelectedBorder)) + { g.DrawRectangle(p, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); } } } - private void ScaleObjectSizesIfNeeded() { - if (isScalingInitialized) { + private void ScaleObjectSizesIfNeeded() + { + if (isScalingInitialized) + { return; - } - if (DpiHelper.IsScalingRequired) { + } + if (DpiHelper.IsScalingRequired) + { ToolStripRenderer.ScaleArrowOffsetsIfNeeded(); overflowButtonWidth = DpiHelper.LogicalToDeviceUnitsX(OVERFLOW_BUTTON_WIDTH); overflowArrowWidth = DpiHelper.LogicalToDeviceUnitsX(OVERFLOW_ARROW_WIDTH); overflowArrowHeight = DpiHelper.LogicalToDeviceUnitsY(OVERFLOW_ARROW_HEIGHT); overflowArrowOffsetY = DpiHelper.LogicalToDeviceUnitsY(OVERFLOW_ARROW_OFFSETY); - if (DpiHelper.IsScalingRequirementMet) { + if (DpiHelper.IsScalingRequirementMet) + { gripPadding = DpiHelper.LogicalToDeviceUnitsY(GRIP_PADDING); iconWellGradientWidth = DpiHelper.LogicalToDeviceUnitsX(ICON_WELL_GRADIENT_WIDTH); int scaledSize = DpiHelper.LogicalToDeviceUnitsX(DROP_DOWN_MENU_ITEM_PAINT_PADDING_SIZE); @@ -1402,7 +1683,8 @@ private void ScaleObjectSizesIfNeeded() { // This draws differently sized arrows than the base one... // used only for drawing the overflow button madness. - private Point RenderArrowInternal(Graphics g, Rectangle dropDownRect, ArrowDirection direction, Brush brush) { + private Point RenderArrowInternal(Graphics g, Rectangle dropDownRect, ArrowDirection direction, Brush brush) + { Point middle = new Point(dropDownRect.Left + dropDownRect.Width / 2, dropDownRect.Top + dropDownRect.Height / 2); @@ -1411,27 +1693,28 @@ private Point RenderArrowInternal(Graphics g, Rectangle dropDownRect, ArrowDirec Point[] arrow = null; - switch (direction) { + switch (direction) + { case ArrowDirection.Up: arrow = new Point[] { - new Point(middle.X - ToolStripRenderer.Offset2X, middle.Y + 1), - new Point(middle.X + ToolStripRenderer.Offset2X + 1, middle.Y + 1), + new Point(middle.X - ToolStripRenderer.Offset2X, middle.Y + 1), + new Point(middle.X + ToolStripRenderer.Offset2X + 1, middle.Y + 1), new Point(middle.X, middle.Y - ToolStripRenderer.Offset2Y) }; break; case ArrowDirection.Left: arrow = new Point[] { - new Point(middle.X + ToolStripRenderer.Offset2X, middle.Y - ToolStripRenderer.Offset2Y - 1), - new Point(middle.X + ToolStripRenderer.Offset2X, middle.Y + ToolStripRenderer.Offset2Y + 1), + new Point(middle.X + ToolStripRenderer.Offset2X, middle.Y - ToolStripRenderer.Offset2Y - 1), + new Point(middle.X + ToolStripRenderer.Offset2X, middle.Y + ToolStripRenderer.Offset2Y + 1), new Point(middle.X - 1, middle.Y) }; break; case ArrowDirection.Right: arrow = new Point[] { - new Point(middle.X - ToolStripRenderer.Offset2X, middle.Y - ToolStripRenderer.Offset2Y - 1), - new Point(middle.X - ToolStripRenderer.Offset2X, middle.Y + ToolStripRenderer.Offset2Y + 1), + new Point(middle.X - ToolStripRenderer.Offset2X, middle.Y - ToolStripRenderer.Offset2Y - 1), + new Point(middle.X - ToolStripRenderer.Offset2X, middle.Y + ToolStripRenderer.Offset2Y + 1), new Point(middle.X + 1, middle.Y) }; break; @@ -1439,8 +1722,8 @@ private Point RenderArrowInternal(Graphics g, Rectangle dropDownRect, ArrowDirec case ArrowDirection.Down: default: arrow = new Point[] { - new Point(middle.X - ToolStripRenderer.Offset2X, middle.Y - 1), - new Point(middle.X + ToolStripRenderer.Offset2X + 1, middle.Y - 1), + new Point(middle.X - ToolStripRenderer.Offset2X, middle.Y - 1), + new Point(middle.X + ToolStripRenderer.Offset2X + 1, middle.Y - 1), new Point(middle.X, middle.Y + ToolStripRenderer.Offset2Y) }; break; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs index 1d953738ea0..bd907b801ac 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; @@ -17,7 +18,7 @@ namespace System.Windows.Forms { using System.ComponentModel.Design; using System.Windows.Forms.Layout; using System.Globalization; - + /// /// The TrackBar is a scrollable control similar to the ScrollBar, but /// has a different UI. You can configure ranges through which it should @@ -34,11 +35,12 @@ namespace System.Windows.Forms { Designer("System.Windows.Forms.Design.TrackBarDesigner, " + AssemblyRef.SystemDesign), SRDescription(nameof(SR.DescriptionTrackBar)) ] - public class TrackBar : Control, ISupportInitialize { + public class TrackBar : Control, ISupportInitialize + { private static readonly object EVENT_SCROLL = new object(); private static readonly object EVENT_VALUECHANGED = new object(); - private static readonly object EVENT_RIGHTTOLEFTLAYOUTCHANGED = new object(); + private static readonly object EVENT_RIGHTTOLEFTLAYOUTCHANGED = new object(); private bool autoSize = true; private int largeChange = 5; @@ -58,19 +60,20 @@ public class TrackBar : Control, ISupportInitialize { // Disable value range checking while initializing the control private bool initializing = false; - private bool rightToLeftLayout = false; + private bool rightToLeftLayout = false; /// /// Creates a new TrackBar control with a default range of 0..10 and /// ticks shown every value. /// public TrackBar() - : base() { + : base() + { SetStyle(ControlStyles.UserPaint, false); SetStyle(ControlStyles.UseTextForAccessibility, false); requestedDim = PreferredDimension; } - + /// /// Indicates if the control is being auto-sized. If true, the /// TrackBar will adjust either its height or width [depending on @@ -85,23 +88,29 @@ public TrackBar() EditorBrowsable(EditorBrowsableState.Always), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible) ] - public override bool AutoSize { - get { + public override bool AutoSize + { + get + { return autoSize; } - set { + set + { // Note that we intentionally do not call base. Labels size themselves by // overriding SetBoundsCore (old RTM code). We let CommonProperties.GetAutoSize // continue to return false to keep our LayoutEngines from messing with TextBoxes. // This is done for backwards compatibility since the new AutoSize behavior differs. - if (autoSize != value) { + if (autoSize != value) + { autoSize = value; - if (orientation == Orientation.Horizontal) { + if (orientation == Orientation.Horizontal) + { SetStyle(ControlStyles.FixedHeight, autoSize); SetStyle(ControlStyles.FixedWidth, false); } - else { + else + { SetStyle(ControlStyles.FixedWidth, autoSize); SetStyle(ControlStyles.FixedHeight, false); } @@ -121,33 +130,41 @@ public override bool AutoSize { [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged { + new public event EventHandler BackgroundImageChanged + { add => base.BackgroundImageChanged += value; remove => base.BackgroundImageChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { + new public event EventHandler BackgroundImageLayoutChanged + { add => base.BackgroundImageLayoutChanged += value; remove => base.BackgroundImageLayoutChanged -= value; } @@ -158,12 +175,15 @@ public override ImageLayout BackgroundImageLayout { /// base.getCreateParams() to make sure the control continues to work /// correctly. /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ClassName = NativeMethods.WC_TRACKBAR; - switch (tickStyle) { + switch (tickStyle) + { case TickStyle.None: cp.Style |= NativeMethods.TBS_NOTICKS; break; @@ -178,11 +198,13 @@ protected override CreateParams CreateParams { break; } - if (orientation == Orientation.Vertical) { + if (orientation == Orientation.Vertical) + { cp.Style |= NativeMethods.TBS_VERT; // HORIZ == 0 } - if (RightToLeft == RightToLeft.Yes && RightToLeftLayout == true) { + if (RightToLeft == RightToLeft.Yes && RightToLeftLayout == true) + { //We want to turn on mirroring for Trackbar explicitly. cp.ExStyle |= NativeMethods.WS_EX_LAYOUTRTL | NativeMethods.WS_EX_NOINHERITLAYOUT; //Don't need these styles when mirroring is turned on. @@ -191,9 +213,11 @@ protected override CreateParams CreateParams { return cp; } } - - protected override ImeMode DefaultImeMode { - get { + + protected override ImeMode DefaultImeMode + { + get + { return ImeMode.Disable; } } @@ -202,8 +226,10 @@ protected override ImeMode DefaultImeMode { /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(104, PreferredDimension); } } @@ -213,27 +239,34 @@ protected override Size DefaultSize { /// on controls that are based on Win32 Native Controls. /// [EditorBrowsable(EditorBrowsableState.Never)] - protected override bool DoubleBuffered { - get { + protected override bool DoubleBuffered + { + get + { return base.DoubleBuffered; } - set { + set + { base.DoubleBuffered = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Font Font { - get { + public override Font Font + { + get + { return base.Font; } - set { + set + { base.Font = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler FontChanged { + new public event EventHandler FontChanged + { add => base.FontChanged += value; remove => base.FontChanged -= value; } @@ -243,32 +276,40 @@ public override Font Font { /// are unable to change this. It is always Color.WINDOWTEXT /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Color ForeColor { - get { + public override Color ForeColor + { + get + { return SystemColors.WindowText; } - set { + set + { } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler ForeColorChanged { + new public event EventHandler ForeColorChanged + { add => base.ForeColorChanged += value; remove => base.ForeColorChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public ImeMode ImeMode { - get { + new public ImeMode ImeMode + { + get + { return base.ImeMode; } - set { + set + { base.ImeMode = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler ImeModeChanged { + public new event EventHandler ImeModeChanged + { add => base.ImeModeChanged += value; remove => base.ImeModeChanged -= value; } @@ -284,16 +325,21 @@ public override Color ForeColor { DefaultValue(5), SRDescription(nameof(SR.TrackBarLargeChangeDescr)) ] - public int LargeChange { - get { + public int LargeChange + { + get + { return largeChange; } - set { - if (value < 0) { + set + { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(LargeChange), string.Format(SR.TrackBarLargeChangeError, value)); } - if (largeChange != value) { + if (largeChange != value) + { largeChange = value; if (IsHandleCreated) { @@ -312,13 +358,18 @@ public int LargeChange { RefreshProperties(RefreshProperties.All), SRDescription(nameof(SR.TrackBarMaximumDescr)) ] - public int Maximum { - get { + public int Maximum + { + get + { return maximum; } - set { - if (maximum != value) { - if (value < minimum) { + set + { + if (maximum != value) + { + if (value < minimum) + { minimum = value; } SetRange(minimum, value); @@ -335,13 +386,18 @@ public int Maximum { RefreshProperties(RefreshProperties.All), SRDescription(nameof(SR.TrackBarMinimumDescr)) ] - public int Minimum { - get { + public int Minimum + { + get + { return minimum; } - set { - if (minimum != value) { - if (value > maximum) { + set + { + if (minimum != value) + { + if (value > maximum) + { maximum = value; } SetRange(value, maximum); @@ -360,32 +416,39 @@ public int Minimum { Localizable(true), SRDescription(nameof(SR.TrackBarOrientationDescr)) ] - public Orientation Orientation { - get { + public Orientation Orientation + { + get + { return orientation; } - set { + set + { //valid values are 0x0 to 0x1 if (!ClientUtils.IsEnumValid(value, (int)value, (int)Orientation.Horizontal, (int)Orientation.Vertical)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(Orientation)); } - if (orientation != value) { + if (orientation != value) + { orientation = value; - if (orientation == Orientation.Horizontal) { + if (orientation == Orientation.Horizontal) + { SetStyle(ControlStyles.FixedHeight, autoSize); SetStyle(ControlStyles.FixedWidth, false); Width = requestedDim; } - else { + else + { SetStyle(ControlStyles.FixedHeight, false); SetStyle(ControlStyles.FixedWidth, autoSize); Height = requestedDim; } - if (IsHandleCreated) { + if (IsHandleCreated) + { Rectangle r = Bounds; RecreateHandle(); SetBounds(r.X, r.Y, r.Height, r.Width, BoundsSpecified.All); @@ -400,29 +463,34 @@ public Orientation Orientation { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Padding Padding { + public new Padding Padding + { get { return base.Padding; } - set { base.Padding = value;} + set { base.Padding = value; } } [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public new event EventHandler PaddingChanged { - add => base.PaddingChanged += value; - remove => base.PaddingChanged -= value; } + public new event EventHandler PaddingChanged + { + add => base.PaddingChanged += value; + remove => base.PaddingChanged -= value; + } /// /// Little private routine that helps with auto-sizing. /// - private int PreferredDimension { - get { + private int PreferredDimension + { + get + { int cyhscroll = UnsafeNativeMethods.GetSystemMetrics(NativeMethods.SM_CYHSCROLL); // this is our preferred size // - return((cyhscroll * 8) / 3); + return ((cyhscroll * 8) / 3); } } @@ -451,16 +519,21 @@ private void RedrawControl() DefaultValue(false), SRDescription(nameof(SR.ControlRightToLeftLayoutDescr)) ] - public virtual bool RightToLeftLayout { - get { + public virtual bool RightToLeftLayout + { + get + { return rightToLeftLayout; } - set { - if (value != rightToLeftLayout) { + set + { + if (value != rightToLeftLayout) + { rightToLeftLayout = value; - using(new LayoutTransaction(this, this, PropertyNames.RightToLeftLayout)) { + using (new LayoutTransaction(this, this, PropertyNames.RightToLeftLayout)) + { OnRightToLeftLayoutChanged(EventArgs.Empty); } } @@ -477,15 +550,20 @@ public virtual bool RightToLeftLayout { DefaultValue(1), SRDescription(nameof(SR.TrackBarSmallChangeDescr)) ] - public int SmallChange { - get { + public int SmallChange + { + get + { return smallChange; } - set { - if (value < 0) { + set + { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(SmallChange), string.Format(SR.TrackBarSmallChangeError, value)); } - if (smallChange != value) { + if (smallChange != value) + { smallChange = value; if (IsHandleCreated) { @@ -494,23 +572,27 @@ public int SmallChange { } } } - - [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Bindable(false)] - public override string Text { - get { + + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Bindable(false)] + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TextChanged { + new public event EventHandler TextChanged + { add => base.TextChanged += value; remove => base.TextChanged -= value; } - + /// /// Indicates how the TrackBar control will draw itself. This affects /// both where the ticks will be drawn in relation to the moveable thumb, @@ -522,11 +604,14 @@ public override string Text { DefaultValue(TickStyle.BottomRight), SRDescription(nameof(SR.TrackBarTickStyleDescr)) ] - public TickStyle TickStyle { - get { + public TickStyle TickStyle + { + get + { return tickStyle; } - set { + set + { // Confirm that value is a valid enum //valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(value, (int)value, (int)TickStyle.None, (int)TickStyle.Both)) @@ -534,7 +619,8 @@ public TickStyle TickStyle { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(TickStyle)); } - if (tickStyle != value) { + if (tickStyle != value) + { tickStyle = value; RecreateHandle(); } @@ -553,14 +639,19 @@ public TickStyle TickStyle { DefaultValue(1), SRDescription(nameof(SR.TrackBarTickFrequencyDescr)) ] - public int TickFrequency { - get { + public int TickFrequency + { + get + { return tickFrequency; } - set { - if (tickFrequency != value) { + set + { + if (tickFrequency != value) + { tickFrequency = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(NativeMethods.TBM_SETTICFREQ, value, 0); Invalidate(); } @@ -578,13 +669,17 @@ public int TickFrequency { Bindable(true), SRDescription(nameof(SR.TrackBarValueDescr)) ] - public int Value { - get { + public int Value + { + get + { GetTrackBarValue(); return value; } - set { - if (this.value != value) { + set + { + if (this.value != value) + { if (!initializing && ((value < minimum) || (value > maximum))) { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidBoundArgument, nameof(Value), value, $"'{nameof(Minimum)}'", $"'${nameof(Maximum)}'")); @@ -595,44 +690,50 @@ public int Value { OnValueChanged(EventArgs.Empty); } } - } + } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler Click { + public new event EventHandler Click + { add => base.Click += value; remove => base.Click -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler DoubleClick { + public new event EventHandler DoubleClick + { add => base.DoubleClick += value; remove => base.DoubleClick -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event MouseEventHandler MouseClick { + public new event MouseEventHandler MouseClick + { add => base.MouseClick += value; remove => base.MouseClick -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event MouseEventHandler MouseDoubleClick { + public new event MouseEventHandler MouseDoubleClick + { add => base.MouseDoubleClick += value; remove => base.MouseDoubleClick -= value; } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnRightToLeftLayoutChangedDescr))] - public event EventHandler RightToLeftLayoutChanged { + public event EventHandler RightToLeftLayoutChanged + { add => Events.AddHandler(EVENT_RIGHTTOLEFTLAYOUTCHANGED, value); remove => Events.RemoveHandler(EVENT_RIGHTTOLEFTLAYOUTCHANGED, value); } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.TrackBarOnScrollDescr))] - public event EventHandler Scroll { + public event EventHandler Scroll + { add => Events.AddHandler(EVENT_SCROLL, value); remove => Events.RemoveHandler(EVENT_SCROLL, value); } @@ -642,13 +743,15 @@ public event EventHandler Scroll { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event PaintEventHandler Paint { + public new event PaintEventHandler Paint + { add => base.Paint += value; remove => base.Paint -= value; } [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.valueChangedEventDescr))] - public event EventHandler ValueChanged { + public event EventHandler ValueChanged + { add => Events.AddHandler(EVENT_VALUECHANGED, value); remove => Events.RemoveHandler(EVENT_VALUECHANGED, value); } @@ -656,16 +759,20 @@ public event EventHandler ValueChanged { /// /// Enforces autoSizing /// - private void AdjustSize() { - if (IsHandleCreated) { + private void AdjustSize() + { + if (IsHandleCreated) + { int saveDim = requestedDim; - try { + try + { if (orientation == Orientation.Horizontal) Height = autoSize ? PreferredDimension : saveDim; else Width = autoSize ? PreferredDimension : saveDim; } - finally { + finally + { requestedDim = saveDim; } } @@ -674,83 +781,101 @@ private void AdjustSize() { /// /// Handles tasks required when the control is being initialized. /// - public void BeginInit() { + public void BeginInit() + { initializing = true; } // Constrain the current value of the control to be within // the minimum and maximum. // - private void ConstrainValue() { + private void ConstrainValue() + { // Don't constrain the value while we're initializing the control - if (initializing) { + if (initializing) + { return; } Debug.Assert(minimum <= maximum, "Minimum should be <= Maximum"); // Keep the current value within the minimum and maximum - if (Value < minimum) { + if (Value < minimum) + { Value = minimum; } - if (Value > maximum) { + if (Value > maximum) + { Value = maximum; } } /// /// - protected override void CreateHandle() { - if (!RecreatingHandle) { + protected override void CreateHandle() + { + if (!RecreatingHandle) + { IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); - try { + try + { NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); icc.dwICC = NativeMethods.ICC_BAR_CLASSES; SafeNativeMethods.InitCommonControlsEx(icc); - } finally { + } + finally + { UnsafeNativeMethods.ThemingScope.Deactivate(userCookie); } } base.CreateHandle(); } - + /// /// Called when initialization of the control is complete. /// - public void EndInit() { + public void EndInit() + { initializing = false; // Make sure the value is constrained by the minimum and maximum ConstrainValue(); } - private void GetTrackBarValue() { - if (IsHandleCreated) { - value = unchecked( (int) (long)SendMessage(NativeMethods.TBM_GETPOS, 0, 0)); - + private void GetTrackBarValue() + { + if (IsHandleCreated) + { + value = unchecked((int)(long)SendMessage(NativeMethods.TBM_GETPOS, 0, 0)); + // See SetTrackBarValue() for a description of why we sometimes reflect the trackbar value // - - if (orientation == Orientation.Vertical) { + + if (orientation == Orientation.Vertical) + { // Reflect value value = Minimum + Maximum - value; } - + // Reflect for a RightToLeft horizontal trackbar // - if (orientation == Orientation.Horizontal && RightToLeft == RightToLeft.Yes && !IsMirrored) { + if (orientation == Orientation.Horizontal && RightToLeft == RightToLeft.Yes && !IsMirrored) + { value = Minimum + Maximum - value; } } - } + } /// /// Handling special input keys, such as pgup, pgdown, home, end, etc... /// - protected override bool IsInputKey(Keys keyData) { - if ((keyData & Keys.Alt) == Keys.Alt) return false; - switch (keyData & Keys.KeyCode) { + protected override bool IsInputKey(Keys keyData) + { + if ((keyData & Keys.Alt) == Keys.Alt) + return false; + switch (keyData & Keys.KeyCode) + { case Keys.PageUp: case Keys.PageDown: case Keys.Home: @@ -759,10 +884,11 @@ protected override bool IsInputKey(Keys keyData) { } return base.IsInputKey(keyData); } - + /// /// - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { base.OnHandleCreated(e); SendMessage(NativeMethods.TBM_SETRANGEMIN, 0, minimum); SendMessage(NativeMethods.TBM_SETRANGEMAX, 0, maximum); @@ -774,18 +900,22 @@ protected override void OnHandleCreated(EventArgs e) { } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnRightToLeftLayoutChanged(EventArgs e) { - if (GetAnyDisposingInHierarchy()) { + protected virtual void OnRightToLeftLayoutChanged(EventArgs e) + { + if (GetAnyDisposingInHierarchy()) + { return; } - if (RightToLeft == RightToLeft.Yes) { + if (RightToLeft == RightToLeft.Yes) + { RecreateHandle(); } EventHandler eh = Events[EVENT_RIGHTTOLEFTLAYOUTCHANGED] as EventHandler; - if (eh != null) { - eh(this, e); + if (eh != null) + { + eh(this, e); } } @@ -795,32 +925,39 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) { /// event. Inheriting classes should not forget to call /// base.onScroll(e) /// - protected virtual void OnScroll(EventArgs e) { + protected virtual void OnScroll(EventArgs e) + { EventHandler handler = (EventHandler)Events[EVENT_SCROLL]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// /// Raises the event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnMouseWheel(MouseEventArgs e) { - base.OnMouseWheel( e ); + protected override void OnMouseWheel(MouseEventArgs e) + { + base.OnMouseWheel(e); HandledMouseEventArgs hme = e as HandledMouseEventArgs; - if (hme != null) { - if (hme.Handled) { - return; - } - hme.Handled = true; + if (hme != null) + { + if (hme.Handled) + { + return; + } + hme.Handled = true; } - if ((ModifierKeys & (Keys.Shift | Keys.Alt)) != 0 || MouseButtons != MouseButtons.None) { + if ((ModifierKeys & (Keys.Shift | Keys.Alt)) != 0 || MouseButtons != MouseButtons.None) + { return; // Do not scroll when Shift or Alt key is down, or when a mouse button is down. } int wheelScrollLines = SystemInformation.MouseWheelScrollLines; - if (wheelScrollLines == 0) { + if (wheelScrollLines == 0) + { return; // Do not scroll when the user system setting is 0 lines per notch } @@ -831,28 +968,33 @@ protected override void OnMouseWheel(MouseEventArgs e) { float partialNotches; partialNotches = (float)this.cumulativeWheelData / (float)NativeMethods.WHEEL_DELTA; - if (wheelScrollLines == -1) { + if (wheelScrollLines == -1) + { wheelScrollLines = TickFrequency; } // Evaluate number of bands to scroll int scrollBands = (int)((float)wheelScrollLines * partialNotches); - if (scrollBands != 0) { - int absScrollBands; - if (scrollBands > 0) { - absScrollBands = scrollBands; - Value = Math.Min(absScrollBands+Value, Maximum); - this.cumulativeWheelData -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); - } - else { - absScrollBands = -scrollBands; - Value = Math.Max(Value-absScrollBands, Minimum); - this.cumulativeWheelData -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); - } + if (scrollBands != 0) + { + int absScrollBands; + if (scrollBands > 0) + { + absScrollBands = scrollBands; + Value = Math.Min(absScrollBands + Value, Maximum); + this.cumulativeWheelData -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); + } + else + { + absScrollBands = -scrollBands; + Value = Math.Max(Value - absScrollBands, Minimum); + this.cumulativeWheelData -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); + } } - if (e.Delta != Value) { + if (e.Delta != Value) + { OnScroll(EventArgs.Empty); OnValueChanged(EventArgs.Empty); } @@ -861,9 +1003,11 @@ protected override void OnMouseWheel(MouseEventArgs e) { /// /// Actually fires the "valueChanged" event. /// - protected virtual void OnValueChanged(EventArgs e) { + protected virtual void OnValueChanged(EventArgs e) + { EventHandler handler = (EventHandler)Events[EVENT_VALUECHANGED]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// @@ -871,20 +1015,23 @@ protected virtual void OnValueChanged(EventArgs e) { /// controls can overide this method to get property change notification on /// basic properties. Inherting controls must call base.propertyChanged. /// - protected override void OnBackColorChanged(EventArgs e) { + protected override void OnBackColorChanged(EventArgs e) + { base.OnBackColorChanged(e); RedrawControl(); } - protected override void OnSystemColorsChanged (EventArgs e) { - base.OnSystemColorsChanged (e); + protected override void OnSystemColorsChanged(EventArgs e) + { + base.OnSystemColorsChanged(e); RedrawControl(); } /// /// Overrides Control.setBoundsCore to enforce autoSize. /// - protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { + protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) + { //SetBoundsCore .. sets the height for a control in designer .. we should obey the requested //height is Autosize is false.. //if (IsHandleCreated) { @@ -892,12 +1039,15 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound ? height : width; - if (autoSize) { - if (orientation == Orientation.Horizontal) { + if (autoSize) + { + if (orientation == Orientation.Horizontal) + { if ((specified & BoundsSpecified.Height) != BoundsSpecified.None) height = PreferredDimension; } - else { + else + { if ((specified & BoundsSpecified.Width) != BoundsSpecified.None) width = PreferredDimension; } @@ -911,14 +1061,17 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound /// The values passed are both the lower and upper limits to the range /// with which the control will work. /// - public void SetRange(int minValue, int maxValue) { - if (minimum != minValue || maximum != maxValue) { - + public void SetRange(int minValue, int maxValue) + { + if (minimum != minValue || maximum != maxValue) + { + // The Minimum and Maximum properties contain the logic for // ensuring that minValue <= maxValue. It is possible, however, // that this function will be called somewhere other than from // these two properties, so we'll check that here anyway. - if (minValue > maxValue) { + if (minValue > maxValue) + { // We'll just adjust maxValue to match minValue maxValue = minValue; } @@ -926,7 +1079,8 @@ public void SetRange(int minValue, int maxValue) { minimum = minValue; maximum = maxValue; - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(NativeMethods.TBM_SETRANGEMIN, 0, minimum); // We must repaint the trackbar after changing @@ -937,24 +1091,28 @@ public void SetRange(int minValue, int maxValue) { Invalidate(); } - + // When we change the range, the comctl32 trackbar's internal position can change // (because of the reflection that occurs with vertical trackbars) // so we make sure to explicitly set the trackbar position. // - if (value < minimum) { + if (value < minimum) + { value = minimum; } - if (value > maximum) { + if (value > maximum) + { value = maximum; } SetTrackBarPosition(); } } - - private void SetTrackBarPosition() { - if (IsHandleCreated) { - + + private void SetTrackBarPosition() + { + if (IsHandleCreated) + { + // There are two situations where we want to reflect the track bar position: // // 1. For a vertical trackbar, it seems to make more sense for the trackbar to increase in value @@ -963,19 +1121,21 @@ private void SetTrackBarPosition() { // 2. For a RightToLeft horizontal trackbar, we want to reflect the position. // int reflectedValue = value; - + // 1. Reflect for a vertical trackbar // - if (orientation == Orientation.Vertical) { + if (orientation == Orientation.Vertical) + { reflectedValue = Minimum + Maximum - value; } - + // 2. Reflect for a RightToLeft horizontal trackbar // - if (orientation == Orientation.Horizontal && RightToLeft == RightToLeft.Yes && !IsMirrored) { + if (orientation == Orientation.Horizontal && RightToLeft == RightToLeft.Yes && !IsMirrored) + { reflectedValue = Minimum + Maximum - value; } - + SendMessage(NativeMethods.TBM_SETPOS, 1, reflectedValue); } } @@ -983,7 +1143,8 @@ private void SetTrackBarPosition() { /// /// Returns a string representation for this control. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); return s + ", Minimum: " + Minimum.ToString(CultureInfo.CurrentCulture) + ", Maximum: " + Maximum.ToString(CultureInfo.CurrentCulture) + ", Value: " + value; @@ -994,21 +1155,25 @@ public override string ToString() { /// to add extra functionality, but should not forget to call /// base.wndProc(m); to ensure the button continues to function properly. /// - protected override void WndProc(ref Message m) { - switch (m.Msg) { - case Interop.WindowMessages.WM_REFLECT+Interop.WindowMessages.WM_HSCROLL: - case Interop.WindowMessages.WM_REFLECT+Interop.WindowMessages.WM_VSCROLL: - switch (NativeMethods.Util.LOWORD(m.WParam)) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { + case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_HSCROLL: + case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_VSCROLL: + switch (NativeMethods.Util.LOWORD(m.WParam)) + { case NativeMethods.TB_LINEUP: case NativeMethods.TB_LINEDOWN: case NativeMethods.TB_PAGEUP: case NativeMethods.TB_PAGEDOWN: - //case NativeMethods.TB_THUMBPOSITION: + //case NativeMethods.TB_THUMBPOSITION: case NativeMethods.TB_THUMBTRACK: case NativeMethods.TB_TOP: case NativeMethods.TB_BOTTOM: case NativeMethods.TB_ENDTRACK: - if (value != Value) { + if (value != Value) + { OnScroll(EventArgs.Empty); OnValueChanged(EventArgs.Empty); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TrackBarRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TrackBarRenderer.cs index 059344e801c..606a1e38348 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TrackBarRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TrackBarRenderer.cs @@ -2,253 +2,281 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ -using System; -using System.Drawing; -using System.Diagnostics.CodeAnalysis; -using System.Windows.Forms.VisualStyles; -using Microsoft.Win32; + using System; + using System.Drawing; + using System.Diagnostics.CodeAnalysis; + using System.Windows.Forms.VisualStyles; + using Microsoft.Win32; /// /// /// This is a rendering class for the TrackBar control. /// /// - public sealed class TrackBarRenderer { + public sealed class TrackBarRenderer + { - //Make this per-thread, so that different threads can safely use these methods. - [ThreadStatic] - private static VisualStyleRenderer visualStyleRenderer = null; - const int lineWidth = 2; + //Make this per-thread, so that different threads can safely use these methods. + [ThreadStatic] + private static VisualStyleRenderer visualStyleRenderer = null; + const int lineWidth = 2; //cannot instantiate - private TrackBarRenderer() { - } - - /// - /// - /// Returns true if this class is supported for the current OS and user/application settings, - /// otherwise returns false. - /// - /// - public static bool IsSupported { - get { - return VisualStyleRenderer.IsSupported; // no downlevel support - } - } - - /// - /// - /// Renders a horizontal track. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static void DrawHorizontalTrack(Graphics g, Rectangle bounds) { - InitializeRenderer(VisualStyleElement.TrackBar.Track.Normal, 1); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Renders a vertical track. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static void DrawVerticalTrack(Graphics g, Rectangle bounds) { - InitializeRenderer(VisualStyleElement.TrackBar.TrackVertical.Normal, 1); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Renders a horizontal thumb. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static void DrawHorizontalThumb(Graphics g, Rectangle bounds, TrackBarThumbState state) { - InitializeRenderer(VisualStyleElement.TrackBar.Thumb.Normal, (int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Renders a vertical thumb. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static void DrawVerticalThumb(Graphics g, Rectangle bounds, TrackBarThumbState state) { - InitializeRenderer(VisualStyleElement.TrackBar.ThumbVertical.Normal, (int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Renders a constant size left pointing thumb centered in the given bounds. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static void DrawLeftPointingThumb(Graphics g, Rectangle bounds, TrackBarThumbState state) { - InitializeRenderer(VisualStyleElement.TrackBar.ThumbLeft.Normal, (int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Renders a constant size right pointing thumb centered in the given bounds. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static void DrawRightPointingThumb(Graphics g, Rectangle bounds, TrackBarThumbState state) { - InitializeRenderer(VisualStyleElement.TrackBar.ThumbRight.Normal, (int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Renders a constant size top pointing thumb centered in the given bounds. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static void DrawTopPointingThumb(Graphics g, Rectangle bounds, TrackBarThumbState state) { - InitializeRenderer(VisualStyleElement.TrackBar.ThumbTop.Normal, (int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Renders a constant size bottom pointing thumb centered in the given bounds. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static void DrawBottomPointingThumb(Graphics g, Rectangle bounds, TrackBarThumbState state) { - InitializeRenderer(VisualStyleElement.TrackBar.ThumbBottom.Normal, (int)state); - - visualStyleRenderer.DrawBackground(g, bounds); - } - - /// - /// - /// Renders a horizontal tick. - /// - /// - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] // PM team has reviewed and decided on naming changes already - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static void DrawHorizontalTicks(Graphics g, Rectangle bounds, int numTicks, EdgeStyle edgeStyle) { - if (numTicks <= 0 || bounds.Height <= 0 || bounds.Width <= 0 || g == null) { - return; - } - - InitializeRenderer(VisualStyleElement.TrackBar.Ticks.Normal, 1); - - //trivial case -- avoid calcs - if (numTicks == 1) { - visualStyleRenderer.DrawEdge(g, new Rectangle(bounds.X, bounds.Y, lineWidth, bounds.Height), Edges.Left, edgeStyle, EdgeEffects.None); - return; - } - - float inc = ((float)bounds.Width - lineWidth) / ((float)numTicks - 1); - - while (numTicks > 0) { - //draw the nth tick - float x = bounds.X + ((float)(numTicks - 1)) * inc; - visualStyleRenderer.DrawEdge(g, new Rectangle((int)Math.Round(x), bounds.Y, lineWidth, bounds.Height), Edges.Left, edgeStyle, EdgeEffects.None); - numTicks--; - } - } - - /// - /// - /// Renders a vertical tick. - /// - /// - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] // PM team has reviewed and decided on naming changes already - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static void DrawVerticalTicks(Graphics g, Rectangle bounds, int numTicks, EdgeStyle edgeStyle) { - if (numTicks<=0 || bounds.Height <= 0 || bounds.Width<=0 || g == null ) { - return; - } - - InitializeRenderer(VisualStyleElement.TrackBar.TicksVertical.Normal, 1); - - //trivial case - if (numTicks == 1) { - visualStyleRenderer.DrawEdge(g, new Rectangle(bounds.X, bounds.Y, bounds.Width, lineWidth), Edges.Top, edgeStyle, EdgeEffects.None); - return; - } - - float inc = ((float)bounds.Height - lineWidth) / ((float)numTicks - 1); - - while (numTicks > 0) { - //draw the nth tick - float y = bounds.Y + ((float)(numTicks - 1)) * inc; - visualStyleRenderer.DrawEdge(g, new Rectangle(bounds.X, (int)Math.Round(y), bounds.Width, lineWidth), Edges.Top, edgeStyle, EdgeEffects.None); - numTicks--; - } - } - - /// - /// - /// Returns the size of a left pointing thumb. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static Size GetLeftPointingThumbSize(Graphics g, TrackBarThumbState state) { - InitializeRenderer(VisualStyleElement.TrackBar.ThumbLeft.Normal, (int)state); - - return (visualStyleRenderer.GetPartSize(g, ThemeSizeType.True)); - } - - /// - /// - /// Returns the size of a right pointing thumb. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static Size GetRightPointingThumbSize(Graphics g, TrackBarThumbState state) { - InitializeRenderer(VisualStyleElement.TrackBar.ThumbRight.Normal, (int)state); - - return (visualStyleRenderer.GetPartSize(g, ThemeSizeType.True)); - } - - /// - /// - /// Returns the size of a top pointing thumb. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static Size GetTopPointingThumbSize(Graphics g, TrackBarThumbState state) { - InitializeRenderer(VisualStyleElement.TrackBar.ThumbTop.Normal, (int)state); - - return (visualStyleRenderer.GetPartSize(g, ThemeSizeType.True)); - } - - /// - /// - /// Returns the size of a bottom pointing thumb. - /// - /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally - public static Size GetBottomPointingThumbSize(Graphics g, TrackBarThumbState state) { - InitializeRenderer(VisualStyleElement.TrackBar.ThumbBottom.Normal, (int)state); - - return (visualStyleRenderer.GetPartSize(g, ThemeSizeType.True)); - } - - private static void InitializeRenderer(VisualStyleElement element, int state) { - if (visualStyleRenderer == null) { - visualStyleRenderer = new VisualStyleRenderer(element.ClassName, element.Part, state); - } - else { - visualStyleRenderer.SetParameters(element.ClassName, element.Part, state); - } - } + private TrackBarRenderer() + { + } + + /// + /// + /// Returns true if this class is supported for the current OS and user/application settings, + /// otherwise returns false. + /// + /// + public static bool IsSupported + { + get + { + return VisualStyleRenderer.IsSupported; // no downlevel support + } + } + + /// + /// + /// Renders a horizontal track. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static void DrawHorizontalTrack(Graphics g, Rectangle bounds) + { + InitializeRenderer(VisualStyleElement.TrackBar.Track.Normal, 1); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Renders a vertical track. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static void DrawVerticalTrack(Graphics g, Rectangle bounds) + { + InitializeRenderer(VisualStyleElement.TrackBar.TrackVertical.Normal, 1); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Renders a horizontal thumb. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static void DrawHorizontalThumb(Graphics g, Rectangle bounds, TrackBarThumbState state) + { + InitializeRenderer(VisualStyleElement.TrackBar.Thumb.Normal, (int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Renders a vertical thumb. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static void DrawVerticalThumb(Graphics g, Rectangle bounds, TrackBarThumbState state) + { + InitializeRenderer(VisualStyleElement.TrackBar.ThumbVertical.Normal, (int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Renders a constant size left pointing thumb centered in the given bounds. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static void DrawLeftPointingThumb(Graphics g, Rectangle bounds, TrackBarThumbState state) + { + InitializeRenderer(VisualStyleElement.TrackBar.ThumbLeft.Normal, (int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Renders a constant size right pointing thumb centered in the given bounds. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static void DrawRightPointingThumb(Graphics g, Rectangle bounds, TrackBarThumbState state) + { + InitializeRenderer(VisualStyleElement.TrackBar.ThumbRight.Normal, (int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Renders a constant size top pointing thumb centered in the given bounds. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static void DrawTopPointingThumb(Graphics g, Rectangle bounds, TrackBarThumbState state) + { + InitializeRenderer(VisualStyleElement.TrackBar.ThumbTop.Normal, (int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Renders a constant size bottom pointing thumb centered in the given bounds. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static void DrawBottomPointingThumb(Graphics g, Rectangle bounds, TrackBarThumbState state) + { + InitializeRenderer(VisualStyleElement.TrackBar.ThumbBottom.Normal, (int)state); + + visualStyleRenderer.DrawBackground(g, bounds); + } + + /// + /// + /// Renders a horizontal tick. + /// + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] // PM team has reviewed and decided on naming changes already + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static void DrawHorizontalTicks(Graphics g, Rectangle bounds, int numTicks, EdgeStyle edgeStyle) + { + if (numTicks <= 0 || bounds.Height <= 0 || bounds.Width <= 0 || g == null) + { + return; + } + + InitializeRenderer(VisualStyleElement.TrackBar.Ticks.Normal, 1); + + //trivial case -- avoid calcs + if (numTicks == 1) + { + visualStyleRenderer.DrawEdge(g, new Rectangle(bounds.X, bounds.Y, lineWidth, bounds.Height), Edges.Left, edgeStyle, EdgeEffects.None); + return; + } + + float inc = ((float)bounds.Width - lineWidth) / ((float)numTicks - 1); + + while (numTicks > 0) + { + //draw the nth tick + float x = bounds.X + ((float)(numTicks - 1)) * inc; + visualStyleRenderer.DrawEdge(g, new Rectangle((int)Math.Round(x), bounds.Y, lineWidth, bounds.Height), Edges.Left, edgeStyle, EdgeEffects.None); + numTicks--; + } + } + + /// + /// + /// Renders a vertical tick. + /// + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] // PM team has reviewed and decided on naming changes already + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static void DrawVerticalTicks(Graphics g, Rectangle bounds, int numTicks, EdgeStyle edgeStyle) + { + if (numTicks <= 0 || bounds.Height <= 0 || bounds.Width <= 0 || g == null) + { + return; + } + + InitializeRenderer(VisualStyleElement.TrackBar.TicksVertical.Normal, 1); + + //trivial case + if (numTicks == 1) + { + visualStyleRenderer.DrawEdge(g, new Rectangle(bounds.X, bounds.Y, bounds.Width, lineWidth), Edges.Top, edgeStyle, EdgeEffects.None); + return; + } + + float inc = ((float)bounds.Height - lineWidth) / ((float)numTicks - 1); + + while (numTicks > 0) + { + //draw the nth tick + float y = bounds.Y + ((float)(numTicks - 1)) * inc; + visualStyleRenderer.DrawEdge(g, new Rectangle(bounds.X, (int)Math.Round(y), bounds.Width, lineWidth), Edges.Top, edgeStyle, EdgeEffects.None); + numTicks--; + } + } + + /// + /// + /// Returns the size of a left pointing thumb. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static Size GetLeftPointingThumbSize(Graphics g, TrackBarThumbState state) + { + InitializeRenderer(VisualStyleElement.TrackBar.ThumbLeft.Normal, (int)state); + + return (visualStyleRenderer.GetPartSize(g, ThemeSizeType.True)); + } + + /// + /// + /// Returns the size of a right pointing thumb. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static Size GetRightPointingThumbSize(Graphics g, TrackBarThumbState state) + { + InitializeRenderer(VisualStyleElement.TrackBar.ThumbRight.Normal, (int)state); + + return (visualStyleRenderer.GetPartSize(g, ThemeSizeType.True)); + } + + /// + /// + /// Returns the size of a top pointing thumb. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static Size GetTopPointingThumbSize(Graphics g, TrackBarThumbState state) + { + InitializeRenderer(VisualStyleElement.TrackBar.ThumbTop.Normal, (int)state); + + return (visualStyleRenderer.GetPartSize(g, ThemeSizeType.True)); + } + + /// + /// + /// Returns the size of a bottom pointing thumb. + /// + /// + [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally + public static Size GetBottomPointingThumbSize(Graphics g, TrackBarThumbState state) + { + InitializeRenderer(VisualStyleElement.TrackBar.ThumbBottom.Normal, (int)state); + + return (visualStyleRenderer.GetPartSize(g, ThemeSizeType.True)); + } + + private static void InitializeRenderer(VisualStyleElement element, int state) + { + if (visualStyleRenderer == null) + { + visualStyleRenderer = new VisualStyleRenderer(element.ClassName, element.Part, state); + } + else + { + visualStyleRenderer.SetParameters(element.ClassName, element.Part, state); + } + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs index eba65ca407d..75163c71d91 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs @@ -4,7 +4,8 @@ -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Text; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; @@ -13,7 +14,7 @@ namespace System.Windows.Forms { using System.Diagnostics.CodeAnalysis; using System; - using System.Drawing.Design; + using System.Drawing.Design; using System.Collections; using System.Globalization; using System.Windows.Forms; @@ -21,7 +22,7 @@ namespace System.Windows.Forms { using System.IO; using System.Drawing; using Microsoft.Win32; - + /// /// @@ -31,15 +32,16 @@ namespace System.Windows.Forms { /// [ TypeConverterAttribute(typeof(TreeNodeConverter)), Serializable, - DefaultProperty(nameof(Text)), + DefaultProperty(nameof(Text)), SuppressMessage("Microsoft.Usage", "CA2240:ImplementISerializableCorrectly") ] - public class TreeNode : MarshalByRefObject, ICloneable, ISerializable { + public class TreeNode : MarshalByRefObject, ICloneable, ISerializable + { private const int SHIFTVAL = 12; private const int CHECKED = 2 << SHIFTVAL; private const int UNCHECKED = 1 << SHIFTVAL; private const int ALLOWEDIMAGES = 14; - + //the threshold value used to optimize AddRange and Clear operations for a big number of nodes internal const int MAX_TREENODES_OPS = 200; @@ -49,15 +51,15 @@ public class TreeNode : MarshalByRefObject, ICloneable, ISerializable { internal OwnerDrawPropertyBag propBag = null; internal IntPtr handle; internal string text; - internal string name; + internal string name; // note: as the checked state of a node is user controlled, and this variable is simply for // state caching when a node hasn't yet been realized, you should use the Checked property to // find out the check state of a node, and not this member variable. //private bool isChecked = false; - private const int TREENODESTATE_isChecked = 0x00000001; + private const int TREENODESTATE_isChecked = 0x00000001; - private System.Collections.Specialized.BitVector32 treeNodeState; + private System.Collections.Specialized.BitVector32 treeNodeState; private TreeNodeImageIndexer imageIndexer; private TreeNodeImageIndexer selectedImageIndexer; @@ -70,57 +72,71 @@ public class TreeNode : MarshalByRefObject, ICloneable, ISerializable { // We need a special way to defer to the TreeView's image // list for indexing purposes. - internal class TreeNodeImageIndexer : ImageList.Indexer { - private TreeNode owner; - + internal class TreeNodeImageIndexer : ImageList.Indexer + { + private TreeNode owner; + public enum ImageListType { - Default, - State + Default, + State } - private ImageListType imageListType; + private ImageListType imageListType; - public TreeNodeImageIndexer(TreeNode node, ImageListType imageListType) { - owner = node; - this.imageListType = imageListType; - } + public TreeNodeImageIndexer(TreeNode node, ImageListType imageListType) + { + owner = node; + this.imageListType = imageListType; + } - public override ImageList ImageList { - get { - if (owner.TreeView != null) { - if (imageListType == ImageListType.State) { + public override ImageList ImageList + { + get + { + if (owner.TreeView != null) + { + if (imageListType == ImageListType.State) + { return owner.TreeView.StateImageList; } - else { + else + { return owner.TreeView.ImageList; } } - else { + else + { return null; } } set { Debug.Assert(false, "We should never set the image list"); } } - + } - internal TreeNodeImageIndexer ImageIndexer { - get { + internal TreeNodeImageIndexer ImageIndexer + { + get + { //Demand create the imageIndexer - if (imageIndexer == null) { - imageIndexer = new TreeNodeImageIndexer(this, TreeNodeImageIndexer.ImageListType.Default); + if (imageIndexer == null) + { + imageIndexer = new TreeNodeImageIndexer(this, TreeNodeImageIndexer.ImageListType.Default); } - return imageIndexer; + return imageIndexer; } - } + } - internal TreeNodeImageIndexer SelectedImageIndexer { - get { + internal TreeNodeImageIndexer SelectedImageIndexer + { + get + { //Demand create the imageIndexer - if (selectedImageIndexer == null) { - selectedImageIndexer = new TreeNodeImageIndexer(this, TreeNodeImageIndexer.ImageListType.Default); + if (selectedImageIndexer == null) + { + selectedImageIndexer = new TreeNodeImageIndexer(this, TreeNodeImageIndexer.ImageListType.Default); } return selectedImageIndexer; @@ -128,16 +144,19 @@ internal TreeNodeImageIndexer SelectedImageIndexer { } } - internal TreeNodeImageIndexer StateImageIndexer { - get { + internal TreeNodeImageIndexer StateImageIndexer + { + get + { //Demand create the imageIndexer - if (stateImageIndexer == null) { - stateImageIndexer = new TreeNodeImageIndexer(this, TreeNodeImageIndexer.ImageListType.State); + if (stateImageIndexer == null) + { + stateImageIndexer = new TreeNodeImageIndexer(this, TreeNodeImageIndexer.ImageListType.State); } - return stateImageIndexer; + return stateImageIndexer; } } - + internal int index; // our index into our parents child array internal int childCount; @@ -148,8 +167,8 @@ internal TreeNodeImageIndexer StateImageIndexer { private bool collapseOnRealization = false; private TreeNodeCollection nodes = null; object userData; - - private readonly static int insertMask = + + private readonly static int insertMask = NativeMethods.TVIF_TEXT | NativeMethods.TVIF_IMAGE | NativeMethods.TVIF_SELECTEDIMAGE; @@ -157,25 +176,29 @@ internal TreeNodeImageIndexer StateImageIndexer { /// /// Creates a TreeNode object. /// - public TreeNode() { + public TreeNode() + { treeNodeState = new System.Collections.Specialized.BitVector32(); } - internal TreeNode(TreeView treeView) : this() { + internal TreeNode(TreeView treeView) : this() + { this.treeView = treeView; } /// /// Creates a TreeNode object. /// - public TreeNode(string text) : this() { + public TreeNode(string text) : this() + { this.text = text; } /// /// Creates a TreeNode object. /// - public TreeNode(string text, TreeNode[] children) : this() { + public TreeNode(string text, TreeNode[] children) : this() + { this.text = text; this.Nodes.AddRange(children); } @@ -183,7 +206,8 @@ public TreeNode(string text, TreeNode[] children) : this() { /// /// Creates a TreeNode object. /// - public TreeNode(string text, int imageIndex, int selectedImageIndex) : this() { + public TreeNode(string text, int imageIndex, int selectedImageIndex) : this() + { this.text = text; this.ImageIndexer.Index = imageIndex; this.SelectedImageIndexer.Index = selectedImageIndex; @@ -192,7 +216,8 @@ public TreeNode(string text, int imageIndex, int selectedImageIndex) : this() { /// /// Creates a TreeNode object. /// - public TreeNode(string text, int imageIndex, int selectedImageIndex, TreeNode[] children) : this() { + public TreeNode(string text, int imageIndex, int selectedImageIndex, TreeNode[] children) : this() + { this.text = text; this.ImageIndexer.Index = imageIndex; this.SelectedImageIndexer.Index = selectedImageIndex; @@ -208,7 +233,8 @@ public TreeNode(string text, int imageIndex, int selectedImageIndex, TreeNode[] SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // Changing Deserialize to be non-virtual // would be a breaking change. ] - protected TreeNode(SerializationInfo serializationInfo, StreamingContext context) : this() { + protected TreeNode(SerializationInfo serializationInfo, StreamingContext context) : this() + { Deserialize(serializationInfo, context); } @@ -221,30 +247,39 @@ protected TreeNode(SerializationInfo serializationInfo, StreamingContext context SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.TreeNodeBackColorDescr)) ] - public Color BackColor { - get { - if (propBag==null) return Color.Empty; + public Color BackColor + { + get + { + if (propBag == null) + return Color.Empty; return propBag.BackColor; } - set { + set + { // get the old value Color oldbk = this.BackColor; // If we're setting the color to the default again, delete the propBag if it doesn't contain // useful data. - if (value.IsEmpty) { - if (propBag!=null) { + if (value.IsEmpty) + { + if (propBag != null) + { propBag.BackColor = Color.Empty; RemovePropBagIfEmpty(); } - if (!oldbk.IsEmpty) InvalidateHostTree(); + if (!oldbk.IsEmpty) + InvalidateHostTree(); return; } // Not the default, so if necessary create a new propBag, and fill it with the backcolor - if (propBag==null) propBag = new OwnerDrawPropertyBag(); + if (propBag == null) + propBag = new OwnerDrawPropertyBag(); propBag.BackColor = value; - if (!value.Equals(oldbk)) InvalidateHostTree(); + if (!value.Equals(oldbk)) + InvalidateHostTree(); } } @@ -253,16 +288,21 @@ public Color BackColor { /// are relative to the upper left corner of the TreeView control. /// [Browsable(false)] - public Rectangle Bounds { - get { + public Rectangle Bounds + { + get + { TreeView tv = this.TreeView; - if (tv == null || tv.IsDisposed) { + if (tv == null || tv.IsDisposed) + { return Rectangle.Empty; } NativeMethods.RECT rc = new NativeMethods.RECT(); - unsafe { *((IntPtr *) &rc.left) = Handle; } + unsafe + { *((IntPtr*)&rc.left) = Handle; } // wparam: 1=include only text, 0=include entire line - if ((int)UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_GETITEMRECT, 1, ref rc) == 0) { + if ((int)UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_GETITEMRECT, 1, ref rc) == 0) + { // This means the node is not visible // return Rectangle.Empty; @@ -275,16 +315,21 @@ public Rectangle Bounds { /// The bounding rectangle for the node (full row). The coordinates /// are relative to the upper left corner of the TreeView control. /// - internal Rectangle RowBounds { - get { + internal Rectangle RowBounds + { + get + { TreeView tv = this.TreeView; NativeMethods.RECT rc = new NativeMethods.RECT(); - unsafe { *((IntPtr *) &rc.left) = Handle; } + unsafe + { *((IntPtr*)&rc.left) = Handle; } // wparam: 1=include only text, 0=include entire line - if (tv == null || tv.IsDisposed) { + if (tv == null || tv.IsDisposed) + { return Rectangle.Empty; } - if ((int)UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_GETITEMRECT, 0, ref rc) == 0) { + if ((int)UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_GETITEMRECT, 0, ref rc) == 0) + { // This means the node is not visible // return Rectangle.Empty; @@ -293,22 +338,28 @@ internal Rectangle RowBounds { } } - internal bool CheckedStateInternal { - get { + internal bool CheckedStateInternal + { + get + { return treeNodeState[TREENODESTATE_isChecked]; } - set { + set + { treeNodeState[TREENODESTATE_isChecked] = value; } } - + // Checked does sanity checking and fires Before/AfterCheck events, then forwards to this // property to get/set the actual checked value. - internal bool CheckedInternal { - get { + internal bool CheckedInternal + { + get + { return CheckedStateInternal; } - set { + set + { CheckedStateInternal = value; if (handle == IntPtr.Zero) return; @@ -323,8 +374,8 @@ internal bool CheckedInternal { item.stateMask = NativeMethods.TVIS_STATEIMAGEMASK; item.state |= value ? CHECKED : UNCHECKED; UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_SETITEM, 0, ref item); - - + + } } @@ -336,13 +387,16 @@ internal bool CheckedInternal { SRDescription(nameof(SR.TreeNodeCheckedDescr)), DefaultValue(false) ] - public bool Checked { - get { + public bool Checked + { + get + { #if DEBUG - if(handle != IntPtr.Zero) { + if (handle != IntPtr.Zero) + { NativeMethods.TV_ITEM item = new NativeMethods.TV_ITEM(); item.mask = NativeMethods.TVIF_HANDLE | NativeMethods.TVIF_STATE; - item.hItem = handle; + item.hItem = handle; item.stateMask = NativeMethods.TVIS_STATEIMAGEMASK; UnsafeNativeMethods.SendMessage(new HandleRef(null, TreeView.Handle), NativeMethods.TVM_GETITEM, 0, ref item); Debug.Assert(!TreeView.CheckBoxes || ((item.state >> SHIFTVAL) > 1) == CheckedInternal, @@ -351,21 +405,25 @@ public bool Checked { #endif return CheckedInternal; } - set { + set + { TreeView tv = TreeView; - if (tv != null) { + if (tv != null) + { bool eventReturn = tv.TreeViewBeforeCheck(this, TreeViewAction.Unknown); - if (!eventReturn) { + if (!eventReturn) + { CheckedInternal = value; tv.TreeViewAfterCheck(this, TreeViewAction.Unknown); } } - else { + else + { CheckedInternal = value; } } } - + /// /// The contextMenu associated with this tree node. The contextMenu /// will be shown when the user right clicks the mouse on the control. @@ -375,11 +433,14 @@ public bool Checked { DefaultValue(null), SRDescription(nameof(SR.ControlContextMenuDescr)) ] - public virtual ContextMenu ContextMenu { - get { + public virtual ContextMenu ContextMenu + { + get + { return contextMenu; } - set { + set + { contextMenu = value; } } @@ -391,30 +452,39 @@ public virtual ContextMenu ContextMenu { DefaultValue(null), SRDescription(nameof(SR.ControlContextMenuDescr)) ] - public virtual ContextMenuStrip ContextMenuStrip { - get { + public virtual ContextMenuStrip ContextMenuStrip + { + get + { return contextMenuStrip; } - set { + set + { contextMenuStrip = value; } } - + /// /// The first child node of this node. /// [Browsable(false)] - public TreeNode FirstNode { - get { - if (childCount == 0) return null; + public TreeNode FirstNode + { + get + { + if (childCount == 0) + return null; return children[0]; } } - - private TreeNode FirstVisibleParent { - get { + + private TreeNode FirstVisibleParent + { + get + { TreeNode node = this; - while (node != null && node.Bounds.IsEmpty) { + while (node != null && node.Bounds.IsEmpty) + { node = node.Parent; } return node; @@ -430,29 +500,38 @@ private TreeNode FirstVisibleParent { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.TreeNodeForeColorDescr)) ] - public Color ForeColor { - get { - if (propBag == null) return Color.Empty; + public Color ForeColor + { + get + { + if (propBag == null) + return Color.Empty; return propBag.ForeColor; } - set { + set + { Color oldfc = this.ForeColor; // If we're setting the color to the default again, delete the propBag if it doesn't contain // useful data. - if (value.IsEmpty) { - if (propBag != null) { + if (value.IsEmpty) + { + if (propBag != null) + { propBag.ForeColor = Color.Empty; RemovePropBagIfEmpty(); } - if (!oldfc.IsEmpty) InvalidateHostTree(); + if (!oldfc.IsEmpty) + InvalidateHostTree(); return; } // Not the default, so if necessary create a new propBag, and fill it with the new forecolor - if (propBag == null) propBag = new OwnerDrawPropertyBag(); + if (propBag == null) + propBag = new OwnerDrawPropertyBag(); propBag.ForeColor = value; - if (!value.Equals(oldfc)) InvalidateHostTree(); + if (!value.Equals(oldfc)) + InvalidateHostTree(); } } @@ -462,15 +541,18 @@ public Color ForeColor { /// each separated by the pathSeperator. /// [Browsable(false)] - public string FullPath { - get { + public string FullPath + { + get + { TreeView tv = TreeView; - if (tv != null) { + if (tv != null) + { StringBuilder path = new StringBuilder(); GetFullPath(path, tv.PathSeparator); return path.ToString(); } - else + else throw new InvalidOperationException(SR.TreeNodeNoParent); } } @@ -479,10 +561,13 @@ public string FullPath { /// The HTREEITEM handle associated with this node. If the handle /// has not yet been created, this will force handle creation. /// - [Browsable(false)] - public IntPtr Handle { - get { - if (handle == IntPtr.Zero) { + [Browsable(false)] + public IntPtr Handle + { + get + { + if (handle == IntPtr.Zero) + { TreeView.CreateControl(); // force handle creation } return handle; @@ -503,9 +588,11 @@ public IntPtr Handle { DefaultValue(-1), RelatedImageList("TreeView.ImageList") ] - public int ImageIndex { - get { return ImageIndexer.Index;} - set { + public int ImageIndex + { + get { return ImageIndexer.Index; } + set + { ImageIndexer.Index = value; UpdateNode(NativeMethods.TVIF_IMAGE); } @@ -526,9 +613,11 @@ public int ImageIndex { RefreshProperties(RefreshProperties.Repaint), RelatedImageList("TreeView.ImageList") ] - public string ImageKey { - get {return ImageIndexer.Key;} - set { + public string ImageKey + { + get { return ImageIndexer.Key; } + set + { ImageIndexer.Key = value; UpdateNode(NativeMethods.TVIF_IMAGE); } @@ -542,16 +631,19 @@ public string ImageKey { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.TreeNodeIndexDescr)), ] - public int Index { - get { return index;} + public int Index + { + get { return index; } } /// /// Specifies whether this node is being edited by the user. /// - [Browsable(false)] - public bool IsEditing { - get { + [Browsable(false)] + public bool IsEditing + { + get + { TreeView tv = TreeView; if (tv != null) @@ -565,23 +657,29 @@ public bool IsEditing { /// Specifies whether this node is in the expanded state. /// [Browsable(false)] - public bool IsExpanded { - get { - if (handle == IntPtr.Zero) { + public bool IsExpanded + { + get + { + if (handle == IntPtr.Zero) + { return expandOnRealization; } - return(State & NativeMethods.TVIS_EXPANDED) != 0; + return (State & NativeMethods.TVIS_EXPANDED) != 0; } } - + /// /// Specifies whether this node is in the selected state. /// [Browsable(false)] - public bool IsSelected { - get { - if (handle == IntPtr.Zero) return false; - return(State & NativeMethods.TVIS_SELECTED) != 0; + public bool IsSelected + { + get + { + if (handle == IntPtr.Zero) + return false; + return (State & NativeMethods.TVIS_SELECTED) != 0; } } @@ -589,19 +687,25 @@ public bool IsSelected { /// Specifies whether this node is visible. /// [Browsable(false)] - public bool IsVisible { - get { - if (handle == IntPtr.Zero) return false; + public bool IsVisible + { + get + { + if (handle == IntPtr.Zero) + return false; TreeView tv = this.TreeView; - if (tv.IsDisposed) { + if (tv.IsDisposed) + { return false; } NativeMethods.RECT rc = new NativeMethods.RECT(); - unsafe { *((IntPtr *) &rc.left) = Handle; } + unsafe + { *((IntPtr*)&rc.left) = Handle; } bool visible = ((int)UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_GETITEMRECT, 1, ref rc) != 0); - if (visible) { + if (visible) + { Size size = tv.ClientSize; visible = (rc.bottom > 0 && rc.right > 0 && rc.top < size.Height && rc.left < size.Width); } @@ -613,10 +717,13 @@ public bool IsVisible { /// The last child node of this node. /// [Browsable(false)] - public TreeNode LastNode { - get { - if (childCount == 0) return null; - return children[childCount-1]; + public TreeNode LastNode + { + get + { + if (childCount == 0) + return null; + return children[childCount - 1]; } } @@ -625,12 +732,16 @@ public TreeNode LastNode { /// This denotes the depth of nesting of the treenode. /// [Browsable(false)] - public int Level { - get { - if (this.Parent == null) { + public int Level + { + get + { + if (this.Parent == null) + { return 0; } - else { + else + { return Parent.Level + 1; } } @@ -642,12 +753,16 @@ public int Level { /// The next sibling node. /// [Browsable(false)] - public TreeNode NextNode { - get { - if (index+1 < parent.Nodes.Count) { - return parent.Nodes[index+1]; + public TreeNode NextNode + { + get + { + if (index + 1 < parent.Nodes.Count) + { + return parent.Nodes[index + 1]; } - else { + else + { return null; } } @@ -658,26 +773,31 @@ public TreeNode NextNode { /// or a node from another branch. /// [Browsable(false)] - public TreeNode NextVisibleNode { - get { + public TreeNode NextVisibleNode + { + get + { // TVGN_NEXTVISIBLE can only be sent if the specified node is visible. // So before sending, we check if this node is visible. If not, we find the first visible parent. // TreeView tv = this.TreeView; - if (tv == null || tv.IsDisposed) { + if (tv == null || tv.IsDisposed) + { return null; } TreeNode node = FirstVisibleParent; - - if (node != null) { + + if (node != null) + { IntPtr next = UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_GETNEXTITEM, NativeMethods.TVGN_NEXTVISIBLE, node.Handle); - if (next != IntPtr.Zero) { + if (next != IntPtr.Zero) + { return tv.NodeFromHandle(next); } } - + return null; } } @@ -695,39 +815,51 @@ public TreeNode NextVisibleNode { SRDescription(nameof(SR.TreeNodeNodeFontDescr)), DefaultValue(null) ] - public Font NodeFont { - get { - if (propBag==null) return null; + public Font NodeFont + { + get + { + if (propBag == null) + return null; return propBag.Font; } - set { + set + { Font oldfont = this.NodeFont; // If we're setting the font to the default again, delete the propBag if it doesn't contain // useful data. - if (value==null) { - if (propBag!=null) { + if (value == null) + { + if (propBag != null) + { propBag.Font = null; RemovePropBagIfEmpty(); } - if (oldfont != null) InvalidateHostTree(); + if (oldfont != null) + InvalidateHostTree(); return; } // Not the default, so if necessary create a new propBag, and fill it with the font - if (propBag==null) propBag = new OwnerDrawPropertyBag(); + if (propBag == null) + propBag = new OwnerDrawPropertyBag(); propBag.Font = value; - if (!value.Equals(oldfont)) InvalidateHostTree(); + if (!value.Equals(oldfont)) + InvalidateHostTree(); } } [ - ListBindable(false), + ListBindable(false), Browsable(false) ] - public TreeNodeCollection Nodes { - get { - if (nodes == null) { + public TreeNodeCollection Nodes + { + get + { + if (nodes == null) + { nodes = new TreeNodeCollection(this); } return nodes; @@ -738,12 +870,15 @@ public TreeNodeCollection Nodes { /// Retrieves parent node. /// [Browsable(false)] - public TreeNode Parent { - get { + public TreeNode Parent + { + get + { TreeView tv = TreeView; // Don't expose the virtual root publicly - if (tv != null && parent == tv.root) { + if (tv != null && parent == tv.root) + { return null; } @@ -755,21 +890,26 @@ public TreeNode Parent { /// The previous sibling node. /// [Browsable(false)] - public TreeNode PrevNode { - get { + public TreeNode PrevNode + { + get + { //fixedIndex is used for perf. optimization in case of adding big ranges of nodes int currentInd = index; int fixedInd = parent.Nodes.FixedIndex; - - if (fixedInd > 0) { - currentInd = fixedInd; + + if (fixedInd > 0) + { + currentInd = fixedInd; } - - if (currentInd > 0 && currentInd <= parent.Nodes.Count) { - return parent.Nodes[currentInd-1]; + + if (currentInd > 0 && currentInd <= parent.Nodes.Count) + { + return parent.Nodes[currentInd - 1]; } - else { - return null; + else + { + return null; } } } @@ -779,26 +919,31 @@ public TreeNode PrevNode { /// or a node from another branch. /// [Browsable(false)] - public TreeNode PrevVisibleNode { - get { + public TreeNode PrevVisibleNode + { + get + { // TVGN_PREVIOUSVISIBLE can only be sent if the specified node is visible. // So before sending, we check if this node is visible. If not, we find the first visible parent. // TreeNode node = FirstVisibleParent; TreeView tv = this.TreeView; - - if (node != null) { - if (tv == null || tv.IsDisposed) { + + if (node != null) + { + if (tv == null || tv.IsDisposed) + { return null; } IntPtr prev = UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_GETNEXTITEM, NativeMethods.TVGN_PREVIOUSVISIBLE, node.Handle); - if (prev != IntPtr.Zero) { + if (prev != IntPtr.Zero) + { return tv.NodeFromHandle(prev); } } - + return null; } } @@ -817,11 +962,14 @@ public TreeNode PrevVisibleNode { Editor("System.Windows.Forms.Design.ImageIndexEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), RelatedImageList("TreeView.ImageList") ] - public int SelectedImageIndex { - get { + public int SelectedImageIndex + { + get + { return SelectedImageIndexer.Index; } - set { + set + { SelectedImageIndexer.Index = value; UpdateNode(NativeMethods.TVIF_SELECTEDIMAGE); } @@ -841,11 +989,14 @@ public int SelectedImageIndex { Editor("System.Windows.Forms.Design.ImageIndexEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), RelatedImageList("TreeView.ImageList") ] - public string SelectedImageKey { - get { - return SelectedImageIndexer.Key; + public string SelectedImageKey + { + get + { + return SelectedImageIndexer.Key; } - set { + set + { SelectedImageIndexer.Key = value; UpdateNode(NativeMethods.TVIF_SELECTEDIMAGE); } @@ -854,13 +1005,16 @@ public string SelectedImageKey { /// /// Retrieve state bits for this node /// - internal int State { - get { + internal int State + { + get + { if (handle == IntPtr.Zero) return 0; TreeView tv = this.TreeView; - if (tv == null || tv.IsDisposed) { + if (tv == null || tv.IsDisposed) + { return 0; } NativeMethods.TV_ITEM item = new NativeMethods.TV_ITEM(); @@ -887,11 +1041,16 @@ internal int State { RefreshProperties(RefreshProperties.Repaint), RelatedImageList("TreeView.StateImageList") ] - public string StateImageKey { - get { - return StateImageIndexer.Key; } - set { - if (StateImageIndexer.Key != value) { + public string StateImageKey + { + get + { + return StateImageIndexer.Key; + } + set + { + if (StateImageIndexer.Key != value) + { StateImageIndexer.Key = value; if (treeView != null && !treeView.CheckBoxes) { @@ -911,12 +1070,16 @@ public string StateImageKey { RefreshProperties(RefreshProperties.Repaint), RelatedImageList("TreeView.StateImageList") ] - public int StateImageIndex { - get { - return (treeView == null || treeView.StateImageList == null) ? -1:StateImageIndexer.Index; + public int StateImageIndex + { + get + { + return (treeView == null || treeView.StateImageList == null) ? -1 : StateImageIndexer.Index; } - set { - if (value < -1 || value > ALLOWEDIMAGES) { + set + { + if (value < -1 || value > ALLOWEDIMAGES) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(StateImageIndex), value)); } StateImageIndexer.Index = value; @@ -935,11 +1098,14 @@ public int StateImageIndex { DefaultValue(null), TypeConverter(typeof(StringConverter)), ] - public object Tag { - get { + public object Tag + { + get + { return userData; } - set { + set + { userData = value; } } @@ -952,11 +1118,14 @@ public object Tag { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.TreeNodeTextDescr)) ] - public string Text { - get { + public string Text + { + get + { return text == null ? "" : text; } - set { + set + { this.text = value; UpdateNode(NativeMethods.TVIF_TEXT); } @@ -972,11 +1141,14 @@ public string Text { SRDescription(nameof(SR.TreeNodeToolTipTextDescr)), DefaultValue("") ] - public string ToolTipText { - get { + public string ToolTipText + { + get + { return toolTipText; } - set { + set + { toolTipText = value; } } @@ -988,24 +1160,29 @@ public string ToolTipText { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.TreeNodeNodeNameDescr)) ] - public string Name { - get { + public string Name + { + get + { return name == null ? "" : name; } - set { + set + { this.name = value; } } - + /// /// Return the TreeView control this node belongs to. /// [Browsable(false)] - public TreeView TreeView { - get { + public TreeView TreeView + { + get + { if (treeView == null) treeView = FindTreeView(); return treeView; @@ -1015,23 +1192,27 @@ public TreeView TreeView { /// /// Adds a new child node at the appropriate sorted position /// - internal int AddSorted(TreeNode node) { + internal int AddSorted(TreeNode node) + { int index = 0; int iMin, iLim, iT; string nodeText = node.Text; TreeView parentTreeView = TreeView; - - if (childCount > 0) { + + if (childCount > 0) + { if (parentTreeView.TreeViewNodeSorter == null) { CompareInfo compare = Application.CurrentCulture.CompareInfo; // Optimize for the case where they're already sorted - if (compare.Compare(children[childCount-1].Text, nodeText) <= 0) + if (compare.Compare(children[childCount - 1].Text, nodeText) <= 0) index = childCount; - else { + else + { // Insert at appropriate sorted spot - for (iMin = 0, iLim = childCount; iMin < iLim;) { + for (iMin = 0, iLim = childCount; iMin < iLim;) + { iT = (iMin + iLim) / 2; if (compare.Compare(children[iT].Text, nodeText) <= 0) iMin = iT + 1; @@ -1041,11 +1222,12 @@ internal int AddSorted(TreeNode node) { index = iMin; } } - else + else { IComparer sorter = parentTreeView.TreeViewNodeSorter; // Insert at appropriate sorted spot - for (iMin = 0, iLim = childCount; iMin < iLim;) { + for (iMin = 0, iLim = childCount; iMin < iLim;) + { iT = (iMin + iLim) / 2; if (sorter.Compare(children[iT] /*previous*/, node/*current*/) <= 0) iMin = iT + 1; @@ -1055,40 +1237,46 @@ internal int AddSorted(TreeNode node) { index = iMin; } } - + node.SortChildren(parentTreeView); InsertNodeAt(index, node); - + return index; } /// /// Returns a TreeNode object for the given HTREEITEM handle /// - public static TreeNode FromHandle(TreeView tree, IntPtr handle) { + public static TreeNode FromHandle(TreeView tree, IntPtr handle) + { return tree.NodeFromHandle(handle); } - private void SortChildren(TreeView parentTreeView) { + private void SortChildren(TreeView parentTreeView) + { // - if (childCount > 0) { + if (childCount > 0) + { TreeNode[] newOrder = new TreeNode[childCount]; if (parentTreeView == null || parentTreeView.TreeViewNodeSorter == null) { CompareInfo compare = Application.CurrentCulture.CompareInfo; - for (int i = 0; i < childCount; i++) { + for (int i = 0; i < childCount; i++) + { int min = -1; - for (int j = 0; j < childCount; j++) { + for (int j = 0; j < childCount; j++) + { if (children[j] == null) continue; - if (min == -1) { + if (min == -1) + { min = j; continue; } if (compare.Compare(children[j].Text, children[min].Text) <= 0) min = j; } - + Debug.Assert(min != -1, "Bad sorting"); newOrder[i] = children[min]; children[min] = null; @@ -1097,22 +1285,25 @@ private void SortChildren(TreeView parentTreeView) { } children = newOrder; } - else + else { IComparer sorter = parentTreeView.TreeViewNodeSorter; - for (int i = 0; i < childCount; i++) { + for (int i = 0; i < childCount; i++) + { int min = -1; - for (int j = 0; j < childCount; j++) { + for (int j = 0; j < childCount; j++) + { if (children[j] == null) continue; - if (min == -1) { + if (min == -1) + { min = j; continue; } if (sorter.Compare(children[j] /*previous*/, children[min] /*current*/) <= 0) min = j; } - + Debug.Assert(min != -1, "Bad sorting"); newOrder[i] = children[min]; children[min] = null; @@ -1120,7 +1311,7 @@ private void SortChildren(TreeView parentTreeView) { newOrder[i].SortChildren(parentTreeView); } children = newOrder; - + } } } @@ -1130,8 +1321,10 @@ private void SortChildren(TreeView parentTreeView) { /// Initiate editing of the node's label. /// Only effective if LabelEdit property is true. /// - public void BeginEdit() { - if (handle != IntPtr.Zero) { + public void BeginEdit() + { + if (handle != IntPtr.Zero) + { TreeView tv = TreeView; if (tv.LabelEdit == false) throw new InvalidOperationException(SR.TreeNodeBeginEditFailed); @@ -1140,14 +1333,15 @@ public void BeginEdit() { UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_EDITLABEL, 0, handle); } } - + /// /// Called by the tree node collection to clear all nodes. We optimize here if /// this is the root node. /// - internal void Clear() { - - + internal void Clear() + { + + // This is a node that is a child of some other node. We have // to selectively remove children here. // @@ -1155,32 +1349,37 @@ internal void Clear() { TreeView tv = TreeView; - - try - { - if (tv != null) { + try + { + + if (tv != null) + { tv.nodesCollectionClear = true; - - if (tv != null && childCount > MAX_TREENODES_OPS) { + + if (tv != null && childCount > MAX_TREENODES_OPS) + { isBulkOperation = true; tv.BeginUpdate(); } } - while(childCount > 0) { + while (childCount > 0) + { children[childCount - 1].Remove(true); } children = null; - if (tv != null && isBulkOperation) { - tv.EndUpdate(); + if (tv != null && isBulkOperation) + { + tv.EndUpdate(); } } finally { - if (tv != null) { + if (tv != null) + { tv.nodesCollectionClear = false; } nodesCleared = true; @@ -1190,56 +1389,64 @@ internal void Clear() { /// /// Clone the entire subtree rooted at this node. /// - public virtual object Clone() { + public virtual object Clone() + { Type clonedType = this.GetType(); TreeNode node = null; - if (clonedType == typeof(TreeNode)){ + if (clonedType == typeof(TreeNode)) + { node = new TreeNode(text, ImageIndexer.Index, SelectedImageIndexer.Index); } - else { + else + { node = (TreeNode)Activator.CreateInstance(clonedType); } - + node.Text = text; node.Name = name; node.ImageIndexer.Index = ImageIndexer.Index; node.SelectedImageIndexer.Index = SelectedImageIndexer.Index; - + node.StateImageIndexer.Index = StateImageIndexer.Index; node.ToolTipText = toolTipText; node.ContextMenu = contextMenu; node.ContextMenuStrip = contextMenuStrip; // only set the key if it's set to something useful - if ( ! (string.IsNullOrEmpty(ImageIndexer.Key))) { + if (!(string.IsNullOrEmpty(ImageIndexer.Key))) + { node.ImageIndexer.Key = ImageIndexer.Key; } // only set the key if it's set to something useful - if (!(string.IsNullOrEmpty(SelectedImageIndexer.Key))) { + if (!(string.IsNullOrEmpty(SelectedImageIndexer.Key))) + { node.SelectedImageIndexer.Key = SelectedImageIndexer.Key; } // only set the key if it's set to something useful - if (!(string.IsNullOrEmpty(StateImageIndexer.Key))) { + if (!(string.IsNullOrEmpty(StateImageIndexer.Key))) + { node.StateImageIndexer.Key = StateImageIndexer.Key; } - - if (childCount > 0) { + + if (childCount > 0) + { node.children = new TreeNode[childCount]; for (int i = 0; i < childCount; i++) node.Nodes.Add((TreeNode)children[i].Clone()); } - + // Clone properties // - if (propBag != null) { + if (propBag != null) + { node.propBag = OwnerDrawPropertyBag.Copy(propBag); } node.Checked = this.Checked; node.Tag = this.Tag; - + return node; } @@ -1250,7 +1457,8 @@ private void CollapseInternal(bool ignoreChildren) collapseOnRealization = false; expandOnRealization = false; - if (tv == null || !tv.IsHandleCreated) { + if (tv == null || !tv.IsHandleCreated) + { collapseOnRealization = true; return; } @@ -1261,15 +1469,19 @@ private void CollapseInternal(bool ignoreChildren) { DoCollapse(tv); } - else { - if (!ignoreChildren && childCount > 0) { + else + { + if (!ignoreChildren && childCount > 0) + { // Virtual root should collapse all its children - for (int i = 0; i < childCount; i++) { - if (tv.SelectedNode == children[i]) { + for (int i = 0; i < childCount; i++) + { + if (tv.SelectedNode == children[i]) + { setSelection = true; } - children[i].DoCollapse(tv); - children[i].Collapse(); + children[i].DoCollapse(tv); + children[i].Collapse(); } } DoCollapse(tv); @@ -1279,7 +1491,7 @@ private void CollapseInternal(bool ignoreChildren) tv.SelectedNode = this; tv.Invalidate(); collapseOnRealization = false; - + } /// @@ -1293,25 +1505,30 @@ public void Collapse(bool ignoreChildren) /// /// Collapse the node. /// - public void Collapse() { - CollapseInternal(false); + public void Collapse() + { + CollapseInternal(false); } /// /// Windows TreeView doesn't send the proper notifications on collapse, so we do it manually. /// - private void DoCollapse(TreeView tv) { - if ((State & NativeMethods.TVIS_EXPANDED) != 0) { + private void DoCollapse(TreeView tv) + { + if ((State & NativeMethods.TVIS_EXPANDED) != 0) + { TreeViewCancelEventArgs e = new TreeViewCancelEventArgs(this, false, TreeViewAction.Collapse); tv.OnBeforeCollapse(e); - if (!e.Cancel) { + if (!e.Cancel) + { UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_EXPAND, NativeMethods.TVE_COLLAPSE, Handle); tv.OnAfterCollapse(new TreeViewEventArgs(this)); } } } - protected virtual void Deserialize(SerializationInfo serializationInfo, StreamingContext context) { + protected virtual void Deserialize(SerializationInfo serializationInfo, StreamingContext context) + { int childCount = 0; int imageIndex = -1; @@ -1322,9 +1539,11 @@ protected virtual void Deserialize(SerializationInfo serializationInfo, Streamin int stateImageIndex = -1; string stateImageKey = null; - - foreach (SerializationEntry entry in serializationInfo) { - switch (entry.Name) { + + foreach (SerializationEntry entry in serializationInfo) + { + switch (entry.Name) + { case "PropBag": // this would throw a InvalidaCastException if improper cast, thus validating the serializationInfo for OwnerDrawPropertyBag propBag = (OwnerDrawPropertyBag)serializationInfo.GetValue(entry.Name, typeof(OwnerDrawPropertyBag)); @@ -1351,11 +1570,11 @@ protected virtual void Deserialize(SerializationInfo serializationInfo, Streamin imageKey = serializationInfo.GetString(entry.Name); break; case "SelectedImageKey": - selectedImageKey= serializationInfo.GetString(entry.Name); - break; + selectedImageKey = serializationInfo.GetString(entry.Name); + break; case "StateImageKey": stateImageKey = serializationInfo.GetString(entry.Name); - break; + break; case "StateImageIndex": stateImageIndex = serializationInfo.GetInt32(entry.Name); break; @@ -1369,33 +1588,41 @@ protected virtual void Deserialize(SerializationInfo serializationInfo, Streamin } // let imagekey take precidence - if (imageKey != null) { - ImageKey = imageKey; - } - else if (imageIndex != -1) { + if (imageKey != null) + { + ImageKey = imageKey; + } + else if (imageIndex != -1) + { ImageIndex = imageIndex; } // let selectedimagekey take precidence - if (selectedImageKey != null) { - SelectedImageKey = selectedImageKey; - } - else if (selectedImageIndex != -1) { + if (selectedImageKey != null) + { + SelectedImageKey = selectedImageKey; + } + else if (selectedImageIndex != -1) + { SelectedImageIndex = selectedImageIndex; } // let stateimagekey take precidence - if (stateImageKey != null) { - StateImageKey = stateImageKey; - } - else if (stateImageIndex != -1) { + if (stateImageKey != null) + { + StateImageKey = stateImageKey; + } + else if (stateImageIndex != -1) + { StateImageIndex = stateImageIndex; } - if (childCount > 0) { + if (childCount > 0) + { TreeNode[] childNodes = new TreeNode[childCount]; - for (int i = 0; i < childCount; i++) { + for (int i = 0; i < childCount; i++) + { childNodes[i] = (TreeNode)serializationInfo.GetValue("children" + i, typeof(TreeNode)); } Nodes.AddRange(childNodes); @@ -1405,30 +1632,37 @@ protected virtual void Deserialize(SerializationInfo serializationInfo, Streamin /// /// Terminate the editing of any tree view item's label. /// - public void EndEdit(bool cancel) { + public void EndEdit(bool cancel) + { TreeView tv = this.TreeView; - if (tv == null || tv.IsDisposed) { + if (tv == null || tv.IsDisposed) + { return; } - UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_ENDEDITLABELNOW, cancel?1:0, 0); + UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_ENDEDITLABELNOW, cancel ? 1 : 0, 0); } /// /// Makes sure there is enough room to add n children /// - internal void EnsureCapacity(int num) { - Debug.Assert(num > 0,"required capacity can not be less than 1"); + internal void EnsureCapacity(int num) + { + Debug.Assert(num > 0, "required capacity can not be less than 1"); int size = num; - if (size < 4) { + if (size < 4) + { size = 4; } - if (children == null) { + if (children == null) + { children = new TreeNode[size]; } - else if (childCount + num > children.Length) { - int newSize = childCount + num; - if (num == 1) { - newSize = childCount * 2; + else if (childCount + num > children.Length) + { + int newSize = childCount + num; + if (num == 1) + { + newSize = childCount * 2; } TreeNode[] bigger = new TreeNode[newSize]; System.Array.Copy(children, 0, bigger, 0, childCount); @@ -1441,19 +1675,23 @@ internal void EnsureCapacity(int num) { /// private void EnsureStateImageValue() { - if (treeView == null) { + if (treeView == null) + { return; } - if (treeView.CheckBoxes && treeView.StateImageList != null) { + if (treeView.CheckBoxes && treeView.StateImageList != null) + { - if (!string.IsNullOrEmpty(this.StateImageKey)) { - this.StateImageIndex = (this.Checked) ? 1 : 0; - this.StateImageKey = treeView.StateImageList.Images.Keys[this.StateImageIndex]; - } - else { - this.StateImageIndex = (this.Checked) ? 1 : 0; - } + if (!string.IsNullOrEmpty(this.StateImageKey)) + { + this.StateImageIndex = (this.Checked) ? 1 : 0; + this.StateImageKey = treeView.StateImageList.Images.Keys[this.StateImageIndex]; + } + else + { + this.StateImageIndex = (this.Checked) ? 1 : 0; + } } } @@ -1461,9 +1699,11 @@ private void EnsureStateImageValue() /// Ensure that the node is visible, expanding nodes and scrolling the /// TreeView control as necessary. /// - public void EnsureVisible() { + public void EnsureVisible() + { TreeView tv = this.TreeView; - if (tv == null || tv.IsDisposed) { + if (tv == null || tv.IsDisposed) + { return; } UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_ENSUREVISIBLE, 0, Handle); @@ -1472,15 +1712,18 @@ public void EnsureVisible() { /// /// Expand the node. /// - public void Expand() { + public void Expand() + { TreeView tv = TreeView; - if (tv == null || !tv.IsHandleCreated) { + if (tv == null || !tv.IsHandleCreated) + { expandOnRealization = true; return; } ResetExpandedState(tv); - if (!IsExpanded) { + if (!IsExpanded) + { UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_EXPAND, NativeMethods.TVE_EXPAND, Handle); } expandOnRealization = false; @@ -1490,19 +1733,22 @@ public void Expand() { /// /// Expand the node. /// - public void ExpandAll() { + public void ExpandAll() + { Expand(); - for (int i = 0; i < childCount; i++) { - children[i].ExpandAll(); + for (int i = 0; i < childCount; i++) + { + children[i].ExpandAll(); } - + } /// /// Locate this tree node's containing tree view control by scanning /// up to the virtual root, whose treeView pointer we know to be /// correct /// - internal TreeView FindTreeView() { + internal TreeView FindTreeView() + { TreeNode node = this; while (node.parent != null) node = node.parent; @@ -1512,8 +1758,10 @@ internal TreeView FindTreeView() { /// /// Helper function for getFullPath(). /// - private void GetFullPath(StringBuilder path, string pathSeparator) { - if (parent != null) { + private void GetFullPath(StringBuilder path, string pathSeparator) + { + if (parent != null) + { parent.GetFullPath(path, pathSeparator); if (parent.parent != null) path.Append(pathSeparator); @@ -1524,9 +1772,11 @@ private void GetFullPath(StringBuilder path, string pathSeparator) { /// /// Returns number of child nodes. /// - public int GetNodeCount(bool includeSubTrees) { + public int GetNodeCount(bool includeSubTrees) + { int total = childCount; - if (includeSubTrees) { + if (includeSubTrees) + { for (int i = 0; i < childCount; i++) total += children[i].GetNodeCount(true); } @@ -1553,12 +1803,14 @@ internal void CheckParentingCycle(TreeNode candidateToAdd) /// /// Helper function to add node at a given index after all validation has been done /// - internal void InsertNodeAt(int index, TreeNode node) { + internal void InsertNodeAt(int index, TreeNode node) + { EnsureCapacity(1); node.parent = this; node.index = index; - for (int i = childCount; i > index; --i) { - (children[i] = children[i-1]).index = i; + for (int i = childCount; i > index; --i) + { + (children[i] = children[i - 1]).index = i; } children[index] = node; childCount++; @@ -1571,21 +1823,26 @@ internal void InsertNodeAt(int index, TreeNode node) { /// /// Invalidates the treeview control that is hosting this node /// - private void InvalidateHostTree() { - if (treeView != null && treeView.IsHandleCreated) treeView.Invalidate(); + private void InvalidateHostTree() + { + if (treeView != null && treeView.IsHandleCreated) + treeView.Invalidate(); } /// /// - internal void Realize(bool insertFirst) { + internal void Realize(bool insertFirst) + { // Debug.assert(handle == 0, "Node already realized"); TreeView tv = this.TreeView; if (tv == null || !tv.IsHandleCreated || tv.IsDisposed) return; - if (parent != null) { // Never realize the virtual root + if (parent != null) + { // Never realize the virtual root - if (tv.InvokeRequired) { + if (tv.InvokeRequired) + { throw new InvalidOperationException(SR.InvalidCrossThreadControlCall); } @@ -1593,10 +1850,12 @@ internal void Realize(bool insertFirst) { tvis.item_mask = insertMask; tvis.hParent = parent.handle; TreeNode prev = PrevNode; - if (insertFirst || prev == null) { + if (insertFirst || prev == null) + { tvis.hInsertAfter = (IntPtr)NativeMethods.TVI_FIRST; } - else { + else + { tvis.hInsertAfter = prev.handle; // Debug.assert(tvis.hInsertAfter != 0); } @@ -1609,20 +1868,24 @@ internal void Realize(bool insertFirst) { tvis.item_stateMask = 0; tvis.item_state = 0; - if (tv.CheckBoxes) { + if (tv.CheckBoxes) + { tvis.item_mask |= NativeMethods.TVIF_STATE; tvis.item_stateMask |= NativeMethods.TVIS_STATEIMAGEMASK; tvis.item_state |= CheckedInternal ? CHECKED : UNCHECKED; } - else if (tv.StateImageList != null && StateImageIndexer.ActualIndex >= 0) { + else if (tv.StateImageList != null && StateImageIndexer.ActualIndex >= 0) + { tvis.item_mask |= NativeMethods.TVIF_STATE; tvis.item_stateMask = NativeMethods.TVIS_STATEIMAGEMASK; tvis.item_state = ((StateImageIndexer.ActualIndex + 1) << SHIFTVAL); } - if (tvis.item_iImage >= 0) tvis.item_mask |= NativeMethods.TVIF_IMAGE; - if (tvis.item_iSelectedImage >= 0) tvis.item_mask |= NativeMethods.TVIF_SELECTEDIMAGE; + if (tvis.item_iImage >= 0) + tvis.item_mask |= NativeMethods.TVIF_IMAGE; + if (tvis.item_iSelectedImage >= 0) + tvis.item_mask |= NativeMethods.TVIF_SELECTEDIMAGE; // If you are editing when you add a new node, then the edit control // gets placed in the wrong place. You must restore the edit mode @@ -1631,7 +1894,8 @@ internal void Realize(bool insertFirst) { // bool editing = false; IntPtr editHandle = UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_GETEDITCONTROL, 0, 0); - if (editHandle != IntPtr.Zero) { + if (editHandle != IntPtr.Zero) + { // currently editing... // editing = true; @@ -1646,13 +1910,15 @@ internal void Realize(bool insertFirst) { Marshal.FreeHGlobal(tvis.item_pszText); - if (editing) { + if (editing) + { UnsafeNativeMethods.PostMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_EDITLABEL, IntPtr.Zero, handle); } SafeNativeMethods.InvalidateRect(new HandleRef(tv, tv.Handle), null, false); - if (parent.nodesCleared && (insertFirst || prev == null) && !tv.Scrollable) { + if (parent.nodesCleared && (insertFirst || prev == null) && !tv.Scrollable) + { // We need to Redraw the TreeView ... // If and only If we are not scrollable ... // and this is the FIRST NODE to get added.. @@ -1669,13 +1935,15 @@ internal void Realize(bool insertFirst) { // If node expansion was requested before the handle was created, // we can expand it now. - if (expandOnRealization) { + if (expandOnRealization) + { Expand(); } // If node collapse was requested before the handle was created, // we can expand it now. - if (collapseOnRealization) { + if (collapseOnRealization) + { Collapse(); } } @@ -1684,13 +1952,15 @@ internal void Realize(bool insertFirst) { /// Remove this node from the TreeView control. Child nodes are also removed from the /// TreeView, but are still attached to this node. /// - public void Remove() { + public void Remove() + { Remove(true); } /// /// - internal void Remove(bool notify) { + internal void Remove(bool notify) + { bool expanded = IsExpanded; // unlink our children @@ -1700,9 +1970,11 @@ internal void Remove(bool notify) { children[i].Remove(false); // children = null; // unlink ourself - if (notify && parent != null) { - for (int i = index; i < parent.childCount-1; ++i) { - (parent.children[i] = parent.children[i+1]).index = i; + if (notify && parent != null) + { + for (int i = index; i < parent.childCount - 1; ++i) + { + (parent.children[i] = parent.children[i + 1]).index = i; } parent.children[parent.childCount - 1] = null; @@ -1714,11 +1986,13 @@ internal void Remove(bool notify) { // unrealize ourself TreeView tv = this.TreeView; - if (tv == null || tv.IsDisposed) { + if (tv == null || tv.IsDisposed) + { return; } - if (handle != IntPtr.Zero) { + if (handle != IntPtr.Zero) + { if (notify && tv.IsHandleCreated) UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_DELETEITEM, 0, handle); treeView.nodeTable.Remove(handle); @@ -1730,13 +2004,17 @@ internal void Remove(bool notify) { /// /// Removes the propBag object if it's now devoid of useful data /// - private void RemovePropBagIfEmpty() { - if (propBag==null) return; - if (propBag.IsEmpty()) propBag = null; + private void RemovePropBagIfEmpty() + { + if (propBag == null) + return; + if (propBag.IsEmpty()) + propBag = null; return; } - private void ResetExpandedState(TreeView tv) { + private void ResetExpandedState(TreeView tv) + { Debug.Assert(tv.IsHandleCreated, "nonexistent handle"); NativeMethods.TV_ITEM item = new NativeMethods.TV_ITEM(); @@ -1747,11 +2025,13 @@ private void ResetExpandedState(TreeView tv) { UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_SETITEM, 0, ref item); } - private bool ShouldSerializeBackColor() { + private bool ShouldSerializeBackColor() + { return BackColor != Color.Empty; } - private bool ShouldSerializeForeColor() { + private bool ShouldSerializeForeColor() + { return ForeColor != Color.Empty; } @@ -1761,8 +2041,10 @@ private bool ShouldSerializeForeColor() { /// Review: Changing this would break VB users. so suppresing this message. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] - protected virtual void Serialize(SerializationInfo si, StreamingContext context) { - if (propBag != null) { + protected virtual void Serialize(SerializationInfo si, StreamingContext context) + { + if (propBag != null) + { si.AddValue("PropBag", propBag, typeof(OwnerDrawPropertyBag)); } @@ -1775,23 +2057,28 @@ protected virtual void Serialize(SerializationInfo si, StreamingContext context) si.AddValue("SelectedImageIndex", SelectedImageIndexer.Index); si.AddValue("SelectedImageKey", SelectedImageIndexer.Key); - if (this.treeView != null && this.treeView.StateImageList != null) { - si.AddValue("StateImageIndex", StateImageIndexer.Index); + if (this.treeView != null && this.treeView.StateImageList != null) + { + si.AddValue("StateImageIndex", StateImageIndexer.Index); } - if (this.treeView != null && this.treeView.StateImageList != null) { - si.AddValue("StateImageKey", StateImageIndexer.Key); + if (this.treeView != null && this.treeView.StateImageList != null) + { + si.AddValue("StateImageKey", StateImageIndexer.Key); } - si.AddValue("ChildCount", childCount); - - if (childCount > 0) { - for (int i = 0; i < childCount; i++) { + si.AddValue("ChildCount", childCount); + + if (childCount > 0) + { + for (int i = 0; i < childCount; i++) + { si.AddValue("children" + i, children[i], typeof(TreeNode)); } } - - if (userData != null && userData.GetType().IsSerializable) { + + if (userData != null && userData.GetType().IsSerializable) + { si.AddValue("UserData", userData, userData.GetType()); } } @@ -1799,32 +2086,38 @@ protected virtual void Serialize(SerializationInfo si, StreamingContext context) /// Toggle the state of the node. Expand if collapsed or collapse if /// expanded. /// - public void Toggle() { + public void Toggle() + { Debug.Assert(parent != null, "toggle on virtual root"); // I don't use the TVE_TOGGLE message 'cuz Windows TreeView doesn't send the appropriate // notifications when collapsing. - if (IsExpanded) { + if (IsExpanded) + { Collapse(); } - else { + else + { Expand(); } } - + /// /// Returns the label text for the tree node /// - public override string ToString() { + public override string ToString() + { return "TreeNode: " + (text == null ? "" : text); } /// /// Tell the TreeView to refresh this node /// - private void UpdateNode(int mask) { - if (handle == IntPtr.Zero) return; + private void UpdateNode(int mask) + { + if (handle == IntPtr.Zero) + return; TreeView tv = TreeView; Debug.Assert(tv != null, "TreeNode has handle but no TreeView"); @@ -1837,31 +2130,36 @@ private void UpdateNode(int mask) { item.iImage = (ImageIndexer.ActualIndex == -1) ? tv.ImageIndexer.ActualIndex : ImageIndexer.ActualIndex; if ((mask & NativeMethods.TVIF_SELECTEDIMAGE) != 0) item.iSelectedImage = (SelectedImageIndexer.ActualIndex == -1) ? tv.SelectedImageIndexer.ActualIndex : SelectedImageIndexer.ActualIndex; - if ((mask & NativeMethods.TVIF_STATE) != 0) { + if ((mask & NativeMethods.TVIF_STATE) != 0) + { item.stateMask = NativeMethods.TVIS_STATEIMAGEMASK; - if (StateImageIndexer.ActualIndex != -1) { + if (StateImageIndexer.ActualIndex != -1) + { item.state = ((StateImageIndexer.ActualIndex + 1) << SHIFTVAL); } // ActualIndex == -1 means "don't use custom image list" // so just leave item.state set to zero, that tells the unmanaged control // to use no state image for this node. } - if ((mask & NativeMethods.TVIF_PARAM) != 0) { - item.lParam = handle; + if ((mask & NativeMethods.TVIF_PARAM) != 0) + { + item.lParam = handle; } UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_SETITEM, 0, ref item); - if ((mask & NativeMethods.TVIF_TEXT) != 0) { + if ((mask & NativeMethods.TVIF_TEXT) != 0) + { Marshal.FreeHGlobal(item.pszText); if (tv.Scrollable) tv.ForceScrollbarUpdate(false); } } - internal void UpdateImage () + internal void UpdateImage() { TreeView tv = this.TreeView; - if (tv.IsDisposed) { + if (tv.IsDisposed) + { return; } @@ -1876,8 +2174,9 @@ internal void UpdateImage () /// /// ISerializable private implementation /// - void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) { - Serialize(si, context); + void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) + { + Serialize(si, context); } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeCollection.cs index 61bcb6e4b1f..44ce34ce555 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeCollection.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.InteropServices; using System; @@ -17,43 +18,51 @@ namespace System.Windows.Forms { [ Editor("System.Windows.Forms.Design.TreeNodeCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)) ] - public class TreeNodeCollection : IList { + public class TreeNodeCollection : IList + { private TreeNode owner; /// A caching mechanism for key accessor /// We use an index here rather than control so that we don't have lifetime /// issues by holding on to extra references. private int lastAccessedIndex = -1; - + //this index is used to optimize performance of AddRange //items are added from last to first after this index //(to work around TV_INSertItem comctl32 perf issue with consecutive adds in the end of the list) private int fixedIndex = -1; - - internal TreeNodeCollection(TreeNode owner) { + + internal TreeNodeCollection(TreeNode owner) + { this.owner = owner; } - + internal int FixedIndex { - get { + get + { return fixedIndex; } - set { + set + { fixedIndex = value; } } - public virtual TreeNode this[int index] { - get { - if (index < 0 || index >= owner.childCount) { + public virtual TreeNode this[int index] + { + get + { + if (index < 0 || index >= owner.childCount) + { throw new ArgumentOutOfRangeException(nameof(index)); } return owner.children[index]; } - set { + set + { if (index < 0 || index >= owner.childCount) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); value.parent = owner; @@ -62,16 +71,21 @@ public virtual TreeNode this[int index] { value.Realize(false); } } - - object IList.this[int index] { - get { + + object IList.this[int index] + { + get + { return this[index]; } - set { - if (value is TreeNode) { + set + { + if (value is TreeNode) + { this[index] = (TreeNode)value; } - else { + else + { throw new ArgumentException(SR.TreeNodeCollectionBadTreeNode, "value"); } } @@ -80,19 +94,24 @@ object IList.this[int index] { /// /// Retrieves the child control with the specified key. /// - public virtual TreeNode this[string key] { - get { + public virtual TreeNode this[string key] + { + get + { // We do not support null and empty string as valid keys. - if (string.IsNullOrEmpty(key)){ + if (string.IsNullOrEmpty(key)) + { return null; } // Search for the key in our collection int index = IndexOfKey(key); - if (IsValidIndex(index)) { + if (IsValidIndex(index)) + { return this[index]; } - else { + else + { return null; } @@ -100,32 +119,42 @@ public virtual TreeNode this[string key] { } // Make this property available to Intellisense. (Removed the EditorBrowsable attribute.) [Browsable(false)] - public int Count { - get { + public int Count + { + get + { return owner.childCount; } } - object ICollection.SyncRoot { - get { + object ICollection.SyncRoot + { + get + { return this; } } - bool ICollection.IsSynchronized { - get { + bool ICollection.IsSynchronized + { + get + { return false; } } - - bool IList.IsFixedSize { - get { + + bool IList.IsFixedSize + { + get + { return false; } } - - public bool IsReadOnly { - get { + + public bool IsReadOnly + { + get + { return false; } } @@ -133,7 +162,8 @@ public bool IsReadOnly { /// /// Creates a new child node under this node. Child node is positioned after siblings. /// - public virtual TreeNode Add(string text) { + public virtual TreeNode Add(string text) + { TreeNode tn = new TreeNode(text); Add(tn); return tn; @@ -144,7 +174,8 @@ public virtual TreeNode Add(string text) { /// /// Creates a new child node under this node. Child node is positioned after siblings. /// - public virtual TreeNode Add(string key, string text) { + public virtual TreeNode Add(string key, string text) + { TreeNode tn = new TreeNode(text); tn.Name = key; Add(tn); @@ -154,7 +185,8 @@ public virtual TreeNode Add(string key, string text) { /// /// Creates a new child node under this node. Child node is positioned after siblings. /// - public virtual TreeNode Add(string key, string text, int imageIndex) { + public virtual TreeNode Add(string key, string text, int imageIndex) + { TreeNode tn = new TreeNode(text); tn.Name = key; tn.ImageIndex = imageIndex; @@ -165,7 +197,8 @@ public virtual TreeNode Add(string key, string text, int imageIndex) { /// /// Creates a new child node under this node. Child node is positioned after siblings. /// - public virtual TreeNode Add(string key, string text, string imageKey) { + public virtual TreeNode Add(string key, string text, string imageKey) + { TreeNode tn = new TreeNode(text); tn.Name = key; tn.ImageKey = imageKey; @@ -176,7 +209,8 @@ public virtual TreeNode Add(string key, string text, string imageKey) { /// /// Creates a new child node under this node. Child node is positioned after siblings. /// - public virtual TreeNode Add(string key, string text, int imageIndex, int selectedImageIndex) { + public virtual TreeNode Add(string key, string text, int imageIndex, int selectedImageIndex) + { TreeNode tn = new TreeNode(text, imageIndex, selectedImageIndex); tn.Name = key; Add(tn); @@ -186,7 +220,8 @@ public virtual TreeNode Add(string key, string text, int imageIndex, int selecte /// /// Creates a new child node under this node. Child node is positioned after siblings. /// - public virtual TreeNode Add(string key, string text, string imageKey, string selectedImageKey) { + public virtual TreeNode Add(string key, string text, string imageKey, string selectedImageKey) + { TreeNode tn = new TreeNode(text); tn.Name = key; tn.ImageKey = imageKey; @@ -196,82 +231,100 @@ public virtual TreeNode Add(string key, string text, string imageKey, string sel } // END - NEW ADD OVERLOADS IN WHIDBEY --> - - public virtual void AddRange(TreeNode[] nodes) { - if (nodes == null) { + + public virtual void AddRange(TreeNode[] nodes) + { + if (nodes == null) + { throw new ArgumentNullException(nameof(nodes)); } if (nodes.Length == 0) return; TreeView tv = owner.TreeView; - if (tv != null && nodes.Length > TreeNode.MAX_TREENODES_OPS) { + if (tv != null && nodes.Length > TreeNode.MAX_TREENODES_OPS) + { tv.BeginUpdate(); } owner.Nodes.FixedIndex = owner.childCount; owner.EnsureCapacity(nodes.Length); - for (int i = nodes.Length-1 ; i >= 0; i--) { - AddInternal(nodes[i],i); + for (int i = nodes.Length - 1; i >= 0; i--) + { + AddInternal(nodes[i], i); } owner.Nodes.FixedIndex = -1; - if (tv != null && nodes.Length > TreeNode.MAX_TREENODES_OPS) { + if (tv != null && nodes.Length > TreeNode.MAX_TREENODES_OPS) + { tv.EndUpdate(); } } - public TreeNode[] Find (string key, bool searchAllChildren) { - ArrayList foundNodes = FindInternal(key, searchAllChildren, this, new ArrayList()); + public TreeNode[] Find(string key, bool searchAllChildren) + { + ArrayList foundNodes = FindInternal(key, searchAllChildren, this, new ArrayList()); - // - TreeNode[] stronglyTypedFoundNodes = new TreeNode[foundNodes.Count]; - foundNodes.CopyTo(stronglyTypedFoundNodes, 0); + // + TreeNode[] stronglyTypedFoundNodes = new TreeNode[foundNodes.Count]; + foundNodes.CopyTo(stronglyTypedFoundNodes, 0); - return stronglyTypedFoundNodes; + return stronglyTypedFoundNodes; } - private ArrayList FindInternal(string key, bool searchAllChildren, TreeNodeCollection treeNodeCollectionToLookIn, ArrayList foundTreeNodes) { - if ((treeNodeCollectionToLookIn == null) || (foundTreeNodes == null)) { - return null; + private ArrayList FindInternal(string key, bool searchAllChildren, TreeNodeCollection treeNodeCollectionToLookIn, ArrayList foundTreeNodes) + { + if ((treeNodeCollectionToLookIn == null) || (foundTreeNodes == null)) + { + return null; } // Perform breadth first search - as it's likely people will want tree nodes belonging // to the same parent close to each other. - - for (int i = 0; i < treeNodeCollectionToLookIn.Count; i++) { - if (treeNodeCollectionToLookIn[i] == null){ - continue; - } - - if (WindowsFormsUtils.SafeCompareStrings(treeNodeCollectionToLookIn[i].Name, key, /* ignoreCase = */ true)) { - foundTreeNodes.Add(treeNodeCollectionToLookIn[i]); - } + + for (int i = 0; i < treeNodeCollectionToLookIn.Count; i++) + { + if (treeNodeCollectionToLookIn[i] == null) + { + continue; + } + + if (WindowsFormsUtils.SafeCompareStrings(treeNodeCollectionToLookIn[i].Name, key, /* ignoreCase = */ true)) + { + foundTreeNodes.Add(treeNodeCollectionToLookIn[i]); + } } // Optional recurive search for controls in child collections. - - if (searchAllChildren){ - for (int i = 0; i < treeNodeCollectionToLookIn.Count; i++) { - if (treeNodeCollectionToLookIn[i] == null){ - continue; - } - if ((treeNodeCollectionToLookIn[i].Nodes != null) && treeNodeCollectionToLookIn[i].Nodes.Count > 0){ + + if (searchAllChildren) + { + for (int i = 0; i < treeNodeCollectionToLookIn.Count; i++) + { + if (treeNodeCollectionToLookIn[i] == null) + { + continue; + } + if ((treeNodeCollectionToLookIn[i].Nodes != null) && treeNodeCollectionToLookIn[i].Nodes.Count > 0) + { // if it has a valid child collecion, append those results to our collection foundTreeNodes = FindInternal(key, searchAllChildren, treeNodeCollectionToLookIn[i].Nodes, foundTreeNodes); } - } + } } return foundTreeNodes; } - /// - /// Adds a new child node to this node. Child node is positioned after siblings. - /// - public virtual int Add(TreeNode node) { - return AddInternal(node, 0); - } + /// + /// Adds a new child node to this node. Child node is positioned after siblings. + /// + public virtual int Add(TreeNode node) + { + return AddInternal(node, 0); + } + - - private int AddInternal(TreeNode node, int delta) { - if (node == null) { + private int AddInternal(TreeNode node, int delta) + { + if (node == null) + { throw new ArgumentNullException(nameof(node)); } if (node.handle != IntPtr.Zero) @@ -282,17 +335,20 @@ private int AddInternal(TreeNode node, int delta) { // If the TreeView is sorted, index is ignored TreeView tv = owner.TreeView; - if (tv != null && tv.Sorted) { - return owner.AddSorted(node); + if (tv != null && tv.Sorted) + { + return owner.AddSorted(node); } node.parent = owner; int fixedIndex = owner.Nodes.FixedIndex; - if (fixedIndex != -1) { + if (fixedIndex != -1) + { node.index = fixedIndex + delta; } - else { + else + { //if fixedIndex != -1 capacity was ensured by AddRange - Debug.Assert(delta == 0,"delta should be 0"); + Debug.Assert(delta == 0, "delta should be 0"); owner.EnsureCapacity(1); node.index = owner.childCount; } @@ -302,62 +358,77 @@ private int AddInternal(TreeNode node, int delta) { if (tv != null && node == tv.selectedNode) tv.SelectedNode = node; // communicate this to the handle - - if (tv != null && tv.TreeViewNodeSorter != null) { + + if (tv != null && tv.TreeViewNodeSorter != null) + { tv.Sort(); } - + return node.index; } - int IList.Add(object node) { - if (node == null) { + int IList.Add(object node) + { + if (node == null) + { throw new ArgumentNullException(nameof(node)); } - else if (node is TreeNode) { + else if (node is TreeNode) + { return Add((TreeNode)node); - } + } else { return Add(node.ToString()).index; } } - public bool Contains(TreeNode node) { + public bool Contains(TreeNode node) + { return IndexOf(node) != -1; } /// /// Returns true if the collection contains an item with the specified key, false otherwise. /// - public virtual bool ContainsKey(string key) { - return IsValidIndex(IndexOfKey(key)); + public virtual bool ContainsKey(string key) + { + return IsValidIndex(IndexOfKey(key)); } - bool IList.Contains(object node) { - if (node is TreeNode) { + bool IList.Contains(object node) + { + if (node is TreeNode) + { return Contains((TreeNode)node); } - else { + else + { return false; } } - public int IndexOf(TreeNode node) { - for(int index=0; index < Count; ++index) { - if (this[index] == node) { + public int IndexOf(TreeNode node) + { + for (int index = 0; index < Count; ++index) + { + if (this[index] == node) + { return index; - } + } } return -1; } - int IList.IndexOf(object node) { - if (node is TreeNode) { + int IList.IndexOf(object node) + { + if (node is TreeNode) + { return IndexOf((TreeNode)node); } - else { + else + { return -1; } } @@ -366,23 +437,28 @@ int IList.IndexOf(object node) { /// /// The zero-based index of the first occurrence of value within the entire CollectionBase, if found; otherwise, -1. /// - public virtual int IndexOfKey(string key) { + public virtual int IndexOfKey(string key) + { // Step 0 - Arg validation - if (string.IsNullOrEmpty(key)){ + if (string.IsNullOrEmpty(key)) + { return -1; // we dont support empty or null keys. } // step 1 - check the last cached item if (IsValidIndex(lastAccessedIndex)) { - if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) { + if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) + { return lastAccessedIndex; } } // step 2 - search for the item - for (int i = 0; i < this.Count; i ++) { - if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { + for (int i = 0; i < this.Count; i++) + { + if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) + { lastAccessedIndex = i; return i; } @@ -397,7 +473,8 @@ public virtual int IndexOfKey(string key) { /// /// Inserts a new child node on this node. Child node is positioned as specified by index. /// - public virtual void Insert(int index, TreeNode node) { + public virtual void Insert(int index, TreeNode node) + { if (node.handle != IntPtr.Zero) throw new ArgumentException(string.Format(SR.OnlyOneControl, node.Text), "node"); @@ -406,21 +483,27 @@ public virtual void Insert(int index, TreeNode node) { // If the TreeView is sorted, index is ignored TreeView tv = owner.TreeView; - if (tv != null && tv.Sorted) { + if (tv != null && tv.Sorted) + { owner.AddSorted(node); return; } - if (index < 0) index = 0; - if (index > owner.childCount) index = owner.childCount; + if (index < 0) + index = 0; + if (index > owner.childCount) + index = owner.childCount; owner.InsertNodeAt(index, node); } - - void IList.Insert(int index, object node) { - if (node is TreeNode) { + + void IList.Insert(int index, object node) + { + if (node is TreeNode) + { Insert(index, (TreeNode)node); } - else { + else + { throw new ArgumentException(SR.TreeNodeCollectionBadTreeNode, "node"); } } @@ -430,7 +513,8 @@ void IList.Insert(int index, object node) { /// /// Inserts a new child node on this node. Child node is positioned as specified by index. /// - public virtual TreeNode Insert(int index, string text) { + public virtual TreeNode Insert(int index, string text) + { TreeNode tn = new TreeNode(text); Insert(index, tn); return tn; @@ -439,7 +523,8 @@ public virtual TreeNode Insert(int index, string text) { /// /// Inserts a new child node on this node. Child node is positioned as specified by index. /// - public virtual TreeNode Insert(int index, string key, string text) { + public virtual TreeNode Insert(int index, string key, string text) + { TreeNode tn = new TreeNode(text); tn.Name = key; Insert(index, tn); @@ -449,7 +534,8 @@ public virtual TreeNode Insert(int index, string key, string text) { /// /// Inserts a new child node on this node. Child node is positioned as specified by index. /// - public virtual TreeNode Insert(int index, string key, string text, int imageIndex) { + public virtual TreeNode Insert(int index, string key, string text, int imageIndex) + { TreeNode tn = new TreeNode(text); tn.Name = key; tn.ImageIndex = imageIndex; @@ -460,7 +546,8 @@ public virtual TreeNode Insert(int index, string key, string text, int imageInde /// /// Inserts a new child node on this node. Child node is positioned as specified by index. /// - public virtual TreeNode Insert(int index, string key, string text, string imageKey) { + public virtual TreeNode Insert(int index, string key, string text, string imageKey) + { TreeNode tn = new TreeNode(text); tn.Name = key; tn.ImageKey = imageKey; @@ -471,7 +558,8 @@ public virtual TreeNode Insert(int index, string key, string text, string imageK /// /// Inserts a new child node on this node. Child node is positioned as specified by index. /// - public virtual TreeNode Insert(int index, string key, string text, int imageIndex, int selectedImageIndex) { + public virtual TreeNode Insert(int index, string key, string text, int imageIndex, int selectedImageIndex) + { TreeNode tn = new TreeNode(text, imageIndex, selectedImageIndex); tn.Name = key; Insert(index, tn); @@ -481,7 +569,8 @@ public virtual TreeNode Insert(int index, string key, string text, int imageInde /// /// Inserts a new child node on this node. Child node is positioned as specified by index. /// - public virtual TreeNode Insert(int index, string key, string text, string imageKey, string selectedImageKey) { + public virtual TreeNode Insert(int index, string key, string text, string imageKey, string selectedImageKey) + { TreeNode tn = new TreeNode(text); tn.Name = key; tn.ImageKey = imageKey; @@ -495,49 +584,60 @@ public virtual TreeNode Insert(int index, string key, string text, string imageK /// /// Determines if the index is valid for the collection. /// - private bool IsValidIndex(int index) { + private bool IsValidIndex(int index) + { return ((index >= 0) && (index < this.Count)); } /// /// Remove all nodes from the tree view. /// - public virtual void Clear() { + public virtual void Clear() + { owner.Clear(); } - public void CopyTo(Array dest, int index) { - if (owner.childCount > 0) { + public void CopyTo(Array dest, int index) + { + if (owner.childCount > 0) + { System.Array.Copy(owner.children, 0, dest, index, owner.childCount); } } - - public void Remove(TreeNode node) { + + public void Remove(TreeNode node) + { node.Remove(); } - - void IList.Remove(object node) { - if (node is TreeNode ) { + + void IList.Remove(object node) + { + if (node is TreeNode) + { Remove((TreeNode)node); } } - public virtual void RemoveAt(int index) { + public virtual void RemoveAt(int index) + { this[index].Remove(); } - + /// /// Removes the child control with the specified key. /// - public virtual void RemoveByKey(string key) { + public virtual void RemoveByKey(string key) + { int index = IndexOfKey(key); - if (IsValidIndex(index)) { - RemoveAt(index); - } + if (IsValidIndex(index)) + { + RemoveAt(index); + } } - public IEnumerator GetEnumerator() { + public IEnumerator GetEnumerator() + { return new WindowsFormsUtils.ArraySubsetEnumerator(owner.children, owner.childCount); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeConverter.cs index bd9ddeed717..6018eb178f9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeConverter.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; @@ -21,19 +22,22 @@ namespace System.Windows.Forms { /// TreeNode objects from one data type to another. Access this /// class through the TypeDescriptor. /// - public class TreeNodeConverter : TypeConverter { - + public class TreeNodeConverter : TypeConverter + { + /// /// Gets a value indicating whether this converter can /// convert an object to the given destination type using the context. /// - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { - if (destinationType == typeof(InstanceDescriptor)) { + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) + { + if (destinationType == typeof(InstanceDescriptor)) + { return true; } return base.CanConvertTo(context, destinationType); } - + /// /// Converts the given object to another type. The most common types to convert /// are to and from a string object. The default implementation will make a call @@ -41,32 +45,40 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) { + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == null) + { throw new ArgumentNullException(nameof(destinationType)); } - if (destinationType == typeof(InstanceDescriptor) && value is TreeNode) { + if (destinationType == typeof(InstanceDescriptor) && value is TreeNode) + { TreeNode node = (TreeNode)value; MemberInfo info = null; object[] args = null; - - if (node.ImageIndex == -1 || node.SelectedImageIndex == -1) { - if (node.Nodes.Count == 0) { - info = typeof(TreeNode).GetConstructor(new Type[] {typeof(string)}); - args = new object[] {node.Text}; + + if (node.ImageIndex == -1 || node.SelectedImageIndex == -1) + { + if (node.Nodes.Count == 0) + { + info = typeof(TreeNode).GetConstructor(new Type[] { typeof(string) }); + args = new object[] { node.Text }; } - else { - info = typeof(TreeNode).GetConstructor(new Type[] {typeof(string), typeof(TreeNode[])}); - + else + { + info = typeof(TreeNode).GetConstructor(new Type[] { typeof(string), typeof(TreeNode[]) }); + TreeNode[] nodesArray = new TreeNode[node.Nodes.Count]; node.Nodes.CopyTo(nodesArray, 0); - - args = new object[] {node.Text, nodesArray}; + + args = new object[] { node.Text, nodesArray }; } } - else { - if (node.Nodes.Count == 0) { + else + { + if (node.Nodes.Count == 0) + { info = typeof(TreeNode).GetConstructor(new Type[] { typeof(string), typeof(int), @@ -76,16 +88,17 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul node.ImageIndex, node.SelectedImageIndex}; } - else { + else + { info = typeof(TreeNode).GetConstructor(new Type[] { typeof(string), typeof(int), typeof(int), typeof(TreeNode[])}); - + TreeNode[] nodesArray = new TreeNode[node.Nodes.Count]; - node.Nodes.CopyTo(nodesArray, 0); - + node.Nodes.CopyTo(nodesArray, 0); + args = new object[] { node.Text, node.ImageIndex, @@ -93,12 +106,13 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul nodesArray}; } } - - if (info != null) { + + if (info != null) + { return new InstanceDescriptor(info, args, false); } } - + return base.ConvertTo(context, culture, value, destinationType); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeMouseHoverEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeMouseHoverEventArgs.cs index 7c9e6a7f135..e19c6030b9e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeMouseHoverEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeMouseHoverEventArgs.cs @@ -16,7 +16,7 @@ public TreeNodeMouseHoverEventArgs(TreeNode node) { Node = node; } - + public TreeNode Node { get; } } } \ No newline at end of file diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs index ca64ef2635d..549ad06b605 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.InteropServices; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -38,7 +39,8 @@ namespace System.Windows.Forms { Designer("System.Windows.Forms.Design.TreeViewDesigner, " + AssemblyRef.SystemDesign), SRDescription(nameof(SR.DescriptionTreeView)) ] - public class TreeView : Control { + public class TreeView : Control + { private const int MaxIndent = 32000; // Maximum allowable TreeView indent private const string backSlash = "\\"; @@ -64,39 +66,43 @@ public class TreeView : Control { private ImageList.Indexer selectedImageIndexer; private bool setOddHeight = false; private TreeNode prevHoveredNode = null; - private bool hoveredAlready = false; + private bool hoveredAlready = false; private bool rightToLeftLayout = false; - + [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr hNodeMouseDown = IntPtr.Zero;//ensures we fire nodeclick on the correct node - private const int TREEVIEWSTATE_hideSelection = 0x00000001; - private const int TREEVIEWSTATE_labelEdit = 0x00000002; - private const int TREEVIEWSTATE_scrollable = 0x00000004; - private const int TREEVIEWSTATE_checkBoxes = 0x00000008; - private const int TREEVIEWSTATE_showLines = 0x00000010; - private const int TREEVIEWSTATE_showPlusMinus = 0x00000020; - private const int TREEVIEWSTATE_showRootLines = 0x00000040; - private const int TREEVIEWSTATE_sorted = 0x00000080; - private const int TREEVIEWSTATE_hotTracking = 0x00000100; - private const int TREEVIEWSTATE_fullRowSelect = 0x00000200; - private const int TREEVIEWSTATE_showNodeToolTips = 0x00000400; - private const int TREEVIEWSTATE_doubleclickFired = 0x00000800; - private const int TREEVIEWSTATE_mouseUpFired = 0x00001000; - private const int TREEVIEWSTATE_showTreeViewContextMenu = 0x00002000; - private const int TREEVIEWSTATE_lastControlValidated = 0x00004000; - private const int TREEVIEWSTATE_stopResizeWindowMsgs = 0x00008000; - private const int TREEVIEWSTATE_ignoreSelects = 0x00010000; + private const int TREEVIEWSTATE_hideSelection = 0x00000001; + private const int TREEVIEWSTATE_labelEdit = 0x00000002; + private const int TREEVIEWSTATE_scrollable = 0x00000004; + private const int TREEVIEWSTATE_checkBoxes = 0x00000008; + private const int TREEVIEWSTATE_showLines = 0x00000010; + private const int TREEVIEWSTATE_showPlusMinus = 0x00000020; + private const int TREEVIEWSTATE_showRootLines = 0x00000040; + private const int TREEVIEWSTATE_sorted = 0x00000080; + private const int TREEVIEWSTATE_hotTracking = 0x00000100; + private const int TREEVIEWSTATE_fullRowSelect = 0x00000200; + private const int TREEVIEWSTATE_showNodeToolTips = 0x00000400; + private const int TREEVIEWSTATE_doubleclickFired = 0x00000800; + private const int TREEVIEWSTATE_mouseUpFired = 0x00001000; + private const int TREEVIEWSTATE_showTreeViewContextMenu = 0x00002000; + private const int TREEVIEWSTATE_lastControlValidated = 0x00004000; + private const int TREEVIEWSTATE_stopResizeWindowMsgs = 0x00008000; + private const int TREEVIEWSTATE_ignoreSelects = 0x00010000; // PERF: take all the bools and put them into a state variable - private System.Collections.Specialized.BitVector32 treeViewState; // see TREEVIEWSTATE_ consts above + private System.Collections.Specialized.BitVector32 treeViewState; // see TREEVIEWSTATE_ consts above private static bool isScalingInitialized = false; private static Size? scaledStateImageSize = null; - private static Size? ScaledStateImageSize { - get { - if (!isScalingInitialized) { - if (DpiHelper.IsScalingRequired) { + private static Size? ScaledStateImageSize + { + get + { + if (!isScalingInitialized) + { + if (DpiHelper.IsScalingRequired) + { scaledStateImageSize = DpiHelper.LogicalToDeviceUnits(new Size(16, 16)); } isScalingInitialized = true; @@ -105,25 +111,31 @@ private static Size? ScaledStateImageSize { } } - internal ImageList.Indexer ImageIndexer { - get { - if (imageIndexer == null) { + internal ImageList.Indexer ImageIndexer + { + get + { + if (imageIndexer == null) + { imageIndexer = new ImageList.Indexer(); } imageIndexer.ImageList = ImageList; return imageIndexer; - } + } } - internal ImageList.Indexer SelectedImageIndexer { - get { - if (selectedImageIndexer == null) { - selectedImageIndexer = new ImageList.Indexer(); - } - selectedImageIndexer.ImageList = ImageList; + internal ImageList.Indexer SelectedImageIndexer + { + get + { + if (selectedImageIndexer == null) + { + selectedImageIndexer = new ImageList.Indexer(); + } + selectedImageIndexer.ImageList = ImageList; - return selectedImageIndexer; - } + return selectedImageIndexer; + } } private ImageList imageList; @@ -149,7 +161,7 @@ internal ImageList.Indexer SelectedImageIndexer { // Sorting private IComparer treeViewNodeSorter = null; - + //Events private TreeNodeMouseClickEventHandler onNodeMouseClick; @@ -159,7 +171,8 @@ internal ImageList.Indexer SelectedImageIndexer { /// Creates a TreeView control /// public TreeView() - : base() { + : base() + { this.treeViewState = new System.Collections.Specialized.BitVector32(TREEVIEWSTATE_showRootLines | TREEVIEWSTATE_showPlusMinus | @@ -183,19 +196,25 @@ public TreeView() /// this parameter sets the /// control's background color to its parent's background color. /// - public override Color BackColor { - get { - if (ShouldSerializeBackColor()) { + public override Color BackColor + { + get + { + if (ShouldSerializeBackColor()) + { return base.BackColor; } - else { + else + { return SystemColors.Window; } } - set { + set + { base.BackColor = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(NativeMethods.TVM_SETBKCOLOR, 0, ColorTranslator.ToWin32(BackColor)); // This is to get around a problem in the comctl control where the lines @@ -207,34 +226,42 @@ public override Color BackColor { } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged { + new public event EventHandler BackgroundImageChanged + { add => base.BackgroundImageChanged += value; remove => base.BackgroundImageChanged -= value; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { + new public event EventHandler BackgroundImageLayoutChanged + { add => base.BackgroundImageLayoutChanged += value; remove => base.BackgroundImageLayoutChanged -= value; } @@ -248,13 +275,17 @@ public override ImageLayout BackgroundImageLayout { DispId(NativeMethods.ActiveX.DISPID_BORDERSTYLE), SRDescription(nameof(SR.borderStyleDescr)) ] - public BorderStyle BorderStyle { - get { + public BorderStyle BorderStyle + { + get + { return borderStyle; } - set { - if (borderStyle != value) { + set + { + if (borderStyle != value) + { //verify that 'value' is a valid enum type... //valid values are 0x0 to 0x2 @@ -279,18 +310,26 @@ public BorderStyle BorderStyle { DefaultValue(false), SRDescription(nameof(SR.TreeViewCheckBoxesDescr)) ] - public bool CheckBoxes { - get { + public bool CheckBoxes + { + get + { return treeViewState[TREEVIEWSTATE_checkBoxes]; } - set { - if (CheckBoxes != value) { + set + { + if (CheckBoxes != value) + { treeViewState[TREEVIEWSTATE_checkBoxes] = value; - if (IsHandleCreated) { - if (CheckBoxes) { + if (IsHandleCreated) + { + if (CheckBoxes) + { UpdateStyles(); - } else { + } + else + { // Going from true to false requires recreation // Reset the Checked state after setting the checkboxes (this was Everett behavior) @@ -306,19 +345,23 @@ public bool CheckBoxes { /// /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ClassName = NativeMethods.WC_TREEVIEW; // Keep the scrollbar if we are just updating styles... // - if (IsHandleCreated) { + if (IsHandleCreated) + { int currentStyle = unchecked((int)((long)UnsafeNativeMethods.GetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_STYLE))); cp.Style |= (currentStyle & (NativeMethods.WS_HSCROLL | NativeMethods.WS_VSCROLL)); } - switch (borderStyle) { + switch (borderStyle) + { case BorderStyle.Fixed3D: cp.ExStyle |= NativeMethods.WS_EX_CLIENTEDGE; break; @@ -344,13 +387,15 @@ protected override CreateParams CreateParams { cp.Style |= NativeMethods.TVS_TRACKSELECT; if (FullRowSelect) cp.Style |= NativeMethods.TVS_FULLROWSELECT; - if (setOddHeight) { + if (setOddHeight) + { cp.Style |= NativeMethods.TVS_NONEVENHEIGHT; } // Don't set TVS_CHECKBOXES here if the window isn't created yet. // See OnHandleCreated for explanation - if (ShowNodeToolTips && IsHandleCreated && !DesignMode) { + if (ShowNodeToolTips && IsHandleCreated && !DesignMode) + { cp.Style |= NativeMethods.TVS_INFOTIP; } @@ -362,14 +407,17 @@ protected override CreateParams CreateParams { // Don't call IsMirrored from CreateParams. That will lead to some nasty problems, since // IsMirrored ends up calling CreateParams - you dig! - if (RightToLeft == RightToLeft.Yes) { - if (RightToLeftLayout == true) { + if (RightToLeft == RightToLeft.Yes) + { + if (RightToLeftLayout == true) + { //We want to turn on mirroring for TreeView explicitly. cp.ExStyle |= NativeMethods.WS_EX_LAYOUTRTL; //Don't need these styles when mirroring is turned on. cp.ExStyle &= ~(NativeMethods.WS_EX_RTLREADING | NativeMethods.WS_EX_RIGHT | NativeMethods.WS_EX_LEFTSCROLLBAR); } - else { + else + { cp.Style |= NativeMethods.TVS_RTLREADING; } } @@ -382,8 +430,10 @@ protected override CreateParams CreateParams { /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(121, 97); } } @@ -393,11 +443,14 @@ protected override Size DefaultSize { /// on controls that are based on Win32 Native Controls. /// [EditorBrowsable(EditorBrowsableState.Never)] - protected override bool DoubleBuffered { - get { + protected override bool DoubleBuffered + { + get + { return base.DoubleBuffered; } - set { + set + { base.DoubleBuffered = value; } } @@ -406,17 +459,22 @@ protected override bool DoubleBuffered { /// The current foreground color for this control, which is the /// color the control uses to draw its text. /// - public override Color ForeColor { - get { - if (ShouldSerializeForeColor()) { + public override Color ForeColor + { + get + { + if (ShouldSerializeForeColor()) + { return base.ForeColor; } - else { + else + { return SystemColors.WindowText; } } - set { + set + { base.ForeColor = value; if (IsHandleCreated) SendMessage(NativeMethods.TVM_SETTEXTCOLOR, 0, ColorTranslator.ToWin32(ForeColor)); @@ -432,12 +490,16 @@ public override Color ForeColor { DefaultValue(false), SRDescription(nameof(SR.TreeViewFullRowSelectDescr)) ] - public bool FullRowSelect { - get { return treeViewState[TREEVIEWSTATE_fullRowSelect];} - set { - if (FullRowSelect != value) { + public bool FullRowSelect + { + get { return treeViewState[TREEVIEWSTATE_fullRowSelect]; } + set + { + if (FullRowSelect != value) + { treeViewState[TREEVIEWSTATE_fullRowSelect] = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { UpdateStyles(); } } @@ -453,15 +515,20 @@ public bool FullRowSelect { DefaultValue(true), SRDescription(nameof(SR.TreeViewHideSelectionDescr)) ] - public bool HideSelection { - get { + public bool HideSelection + { + get + { return treeViewState[TREEVIEWSTATE_hideSelection]; } - set { - if (HideSelection != value) { + set + { + if (HideSelection != value) + { treeViewState[TREEVIEWSTATE_hideSelection] = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { UpdateStyles(); } } @@ -478,15 +545,20 @@ public bool HideSelection { DefaultValue(false), SRDescription(nameof(SR.TreeViewHotTrackingDescr)) ] - public bool HotTracking { - get { + public bool HotTracking + { + get + { return treeViewState[TREEVIEWSTATE_hotTracking]; } - set { - if (HotTracking != value) { + set + { + if (HotTracking != value) + { treeViewState[TREEVIEWSTATE_hotTracking] = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { UpdateStyles(); } } @@ -506,33 +578,42 @@ public bool HotTracking { SRDescription(nameof(SR.TreeViewImageIndexDescr)), RelatedImageList("ImageList") ] - public int ImageIndex { - get { - if (imageList == null) { + public int ImageIndex + { + get + { + if (imageList == null) + { return -1; } - if (ImageIndexer.Index >= imageList.Images.Count) { + if (ImageIndexer.Index >= imageList.Images.Count) + { return Math.Max(0, imageList.Images.Count - 1); } return ImageIndexer.Index; } - set { + set + { // If (none) is selected in the image index editor, we'll just adjust this to // mean image index 0. This is because a treeview must always have an image index - // even if no imagelist exists we want the image index to be 0. // - if (value == -1) { + if (value == -1) + { value = 0; } - if (value < 0) { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(ImageIndex), string.Format(SR.InvalidLowBoundArgumentEx, nameof(ImageIndex), value, 0)); } - if (ImageIndexer.Index != value) { + if (ImageIndexer.Index != value) + { ImageIndexer.Index = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { RecreateHandle(); } } @@ -552,18 +633,24 @@ public int ImageIndex { SRDescription(nameof(SR.TreeViewImageKeyDescr)), RelatedImageList("ImageList") ] - public string ImageKey { - get { + public string ImageKey + { + get + { return ImageIndexer.Key; } - set { - if (ImageIndexer.Key != value) { + set + { + if (ImageIndexer.Key != value) + { ImageIndexer.Key = value; - if (string.IsNullOrEmpty(value) || value.Equals(SR.toStringNone)) { - ImageIndex = (ImageList != null) ? 0:-1; + if (string.IsNullOrEmpty(value) || value.Equals(SR.toStringNone)) + { + ImageIndex = (ImageList != null) ? 0 : -1; } - if (IsHandleCreated) { + if (IsHandleCreated) + { RecreateHandle(); } } @@ -579,13 +666,17 @@ public string ImageKey { SRDescription(nameof(SR.TreeViewImageListDescr)), RefreshProperties(RefreshProperties.Repaint) ] - public ImageList ImageList { - get { + public ImageList ImageList + { + get + { return imageList; } - set { - if (value != imageList) { - + set + { + if (value != imageList) + { + DetachImageListHandlers(); imageList = value; @@ -594,10 +685,12 @@ public ImageList ImageList { // Update TreeView's images // - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(NativeMethods.TVM_SETIMAGELIST, 0, - value==null? IntPtr.Zero: value.Handle); - if (StateImageList != null && StateImageList.Images.Count > 0) { + value == null ? IntPtr.Zero : value.Handle); + if (StateImageList != null && StateImageList.Images.Count > 0) + { SetStateImageList(internalStateImageList.Handle); } } @@ -606,40 +699,48 @@ public ImageList ImageList { } } - private void AttachImageListHandlers() { - if (imageList != null) { - //NOTE: any handlers added here should be removed in DetachImageListHandlers - imageList.RecreateHandle += new EventHandler(ImageListRecreateHandle); - imageList.Disposed += new EventHandler(DetachImageList); - imageList.ChangeHandle += new EventHandler(ImageListChangedHandle); - } - } - - private void DetachImageListHandlers() { - if (imageList != null) { - imageList.RecreateHandle -= new EventHandler(ImageListRecreateHandle); - imageList.Disposed -= new EventHandler(DetachImageList); - imageList.ChangeHandle -= new EventHandler(ImageListChangedHandle); - } - } - - private void AttachStateImageListHandlers() { - if (stateImageList != null) { - //NOTE: any handlers added here should be removed in DetachStateImageListHandlers - stateImageList.RecreateHandle += new EventHandler(StateImageListRecreateHandle); - stateImageList.Disposed += new EventHandler(DetachStateImageList); - stateImageList.ChangeHandle += new EventHandler(StateImageListChangedHandle); - } - } - - private void DetachStateImageListHandlers() { - if (stateImageList != null) { - stateImageList.RecreateHandle -= new EventHandler(StateImageListRecreateHandle); - stateImageList.Disposed -= new EventHandler(DetachStateImageList); - stateImageList.ChangeHandle -= new EventHandler(StateImageListChangedHandle); - } - } - + private void AttachImageListHandlers() + { + if (imageList != null) + { + //NOTE: any handlers added here should be removed in DetachImageListHandlers + imageList.RecreateHandle += new EventHandler(ImageListRecreateHandle); + imageList.Disposed += new EventHandler(DetachImageList); + imageList.ChangeHandle += new EventHandler(ImageListChangedHandle); + } + } + + private void DetachImageListHandlers() + { + if (imageList != null) + { + imageList.RecreateHandle -= new EventHandler(ImageListRecreateHandle); + imageList.Disposed -= new EventHandler(DetachImageList); + imageList.ChangeHandle -= new EventHandler(ImageListChangedHandle); + } + } + + private void AttachStateImageListHandlers() + { + if (stateImageList != null) + { + //NOTE: any handlers added here should be removed in DetachStateImageListHandlers + stateImageList.RecreateHandle += new EventHandler(StateImageListRecreateHandle); + stateImageList.Disposed += new EventHandler(DetachStateImageList); + stateImageList.ChangeHandle += new EventHandler(StateImageListChangedHandle); + } + } + + private void DetachStateImageListHandlers() + { + if (stateImageList != null) + { + stateImageList.RecreateHandle -= new EventHandler(StateImageListRecreateHandle); + stateImageList.Disposed -= new EventHandler(DetachStateImageList); + stateImageList.ChangeHandle -= new EventHandler(StateImageListChangedHandle); + } + } + /// /// Returns the state image list control that is bound to the tree view. @@ -649,12 +750,16 @@ private void DetachStateImageListHandlers() { DefaultValue(null), SRDescription(nameof(SR.TreeViewStateImageListDescr)) ] - public ImageList StateImageList { - get { + public ImageList StateImageList + { + get + { return stateImageList; } - set { - if (value != stateImageList) { + set + { + if (value != stateImageList) + { DetachStateImageListHandlers(); stateImageList = value; @@ -669,12 +774,14 @@ public ImageList StateImageList { // We need to update the checks // and stateimage value for each node. UpdateCheckedState(root, true); - - if((value == null || stateImageList.Images.Count == 0) && CheckBoxes) { + + if ((value == null || stateImageList.Images.Count == 0) && CheckBoxes) + { // Requires Handle Recreate to force on the checkBoxes and states.. RecreateHandle(); } - else { + else + { // The TreeView shows up the state imageList after sending this message even if the nodes dont have any stateImageIndex set. // In order to avoid that we refresh nodes which would "reset" the images to none. // This causes flicker but gives us the right behavior @@ -682,7 +789,7 @@ public ImageList StateImageList { } } - + } } } @@ -696,29 +803,38 @@ public ImageList StateImageList { SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.TreeViewIndentDescr)) ] - public int Indent { - get { - if (indent != -1) { + public int Indent + { + get + { + if (indent != -1) + { return indent; } - else if (IsHandleCreated) { - return unchecked( (int) (long)SendMessage(NativeMethods.TVM_GETINDENT, 0, 0)); + else if (IsHandleCreated) + { + return unchecked((int)(long)SendMessage(NativeMethods.TVM_GETINDENT, 0, 0)); } return DefaultTreeViewIndent; } - set { - if (indent != value) { - if (value < 0) { + set + { + if (indent != value) + { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(Indent), value, 0)); } - if (value > MaxIndent) { + if (value > MaxIndent) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidHighBoundArgumentEx, nameof(Indent), value, MaxIndent)); } indent = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(NativeMethods.TVM_SETINDENT, value, 0); - indent = unchecked( (int) (long)SendMessage(NativeMethods.TVM_GETINDENT, 0, 0)); + indent = unchecked((int)(long)SendMessage(NativeMethods.TVM_GETINDENT, 0, 0)); } } } @@ -731,46 +847,60 @@ public int Indent { SRCategory(nameof(SR.CatAppearance)), SRDescription(nameof(SR.TreeViewItemHeightDescr)) ] - public int ItemHeight { - get { - if (itemHeight != -1) { + public int ItemHeight + { + get + { + if (itemHeight != -1) + { return itemHeight; } - if (IsHandleCreated) { - return unchecked( (int) (long)SendMessage(NativeMethods.TVM_GETITEMHEIGHT, 0, 0)); + if (IsHandleCreated) + { + return unchecked((int)(long)SendMessage(NativeMethods.TVM_GETITEMHEIGHT, 0, 0)); } - else { - if (CheckBoxes && (DrawMode == TreeViewDrawMode.OwnerDrawAll)) { - return Math.Max(16, FontHeight + 3); + else + { + if (CheckBoxes && (DrawMode == TreeViewDrawMode.OwnerDrawAll)) + { + return Math.Max(16, FontHeight + 3); } return FontHeight + 3; } } - set { - if (itemHeight != value) { - if (value < 1) { + set + { + if (itemHeight != value) + { + if (value < 1) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(ItemHeight), value, 1)); } - if (value >= short.MaxValue) { + if (value >= short.MaxValue) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidHighBoundArgument, nameof(ItemHeight), value, short.MaxValue)); } itemHeight = value; - if (IsHandleCreated) { - if (itemHeight % 2 != 0) { + if (IsHandleCreated) + { + if (itemHeight % 2 != 0) + { setOddHeight = true; - try { + try + { RecreateHandle(); } - finally { + finally + { setOddHeight = false; } } SendMessage(NativeMethods.TVM_SETITEMHEIGHT, value, 0); - itemHeight = unchecked( (int) (long)SendMessage(NativeMethods.TVM_GETITEMHEIGHT, 0, 0)); + itemHeight = unchecked((int)(long)SendMessage(NativeMethods.TVM_GETITEMHEIGHT, 0, 0)); } } } @@ -785,14 +915,19 @@ public int ItemHeight { DefaultValue(false), SRDescription(nameof(SR.TreeViewLabelEditDescr)) ] - public bool LabelEdit { - get { + public bool LabelEdit + { + get + { return treeViewState[TREEVIEWSTATE_labelEdit]; } - set { - if (LabelEdit != value) { + set + { + if (LabelEdit != value) + { treeViewState[TREEVIEWSTATE_labelEdit] = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { UpdateStyles(); } } @@ -808,18 +943,24 @@ public bool LabelEdit { SRDescription(nameof(SR.TreeViewLineColorDescr)), DefaultValue(typeof(Color), "Black") ] - public Color LineColor { - get { - if (IsHandleCreated) { + public Color LineColor + { + get + { + if (IsHandleCreated) + { int intColor = unchecked((int)(long)SendMessage(NativeMethods.TVM_GETLINECOLOR, 0, 0)); return ColorTranslator.FromWin32(intColor); } return lineColor; } - set { - if (lineColor != value) { + set + { + if (lineColor != value) + { lineColor = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(NativeMethods.TVM_SETLINECOLOR, 0, ColorTranslator.ToWin32(lineColor)); } @@ -837,9 +978,12 @@ public Color LineColor { SRDescription(nameof(SR.TreeViewNodesDescr)), MergableProperty(false) ] - public TreeNodeCollection Nodes { - get { - if (nodes == null) { + public TreeNodeCollection Nodes + { + get + { + if (nodes == null) + { nodes = new TreeNodeCollection(root); } return nodes; @@ -856,19 +1000,23 @@ public TreeNodeCollection Nodes { DefaultValue(TreeViewDrawMode.Normal), SRDescription(nameof(SR.TreeViewDrawModeDescr)) ] - public TreeViewDrawMode DrawMode { - get { + public TreeViewDrawMode DrawMode + { + get + { return drawMode; } - set { + set + { //valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)TreeViewDrawMode.Normal, (int)TreeViewDrawMode.OwnerDrawAll)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(TreeViewDrawMode)); } - if (drawMode != value) { + if (drawMode != value) + { drawMode = value; Invalidate(); // We need to invalidate when the Control resizes when the we support custom draw. @@ -888,11 +1036,14 @@ public TreeViewDrawMode DrawMode { DefaultValue("\\"), SRDescription(nameof(SR.TreeViewPathSeparatorDescr)) ] - public string PathSeparator { - get { + public string PathSeparator + { + get + { return pathSeparator; } - set { + set + { pathSeparator = value; } } @@ -902,18 +1053,21 @@ public string PathSeparator { EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Padding Padding { + public new Padding Padding + { get { return base.Padding; } - set { base.Padding = value;} + set { base.Padding = value; } } [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public new event EventHandler PaddingChanged { - add => base.PaddingChanged += value; - remove => base.PaddingChanged -= value; } + public new event EventHandler PaddingChanged + { + add => base.PaddingChanged += value; + remove => base.PaddingChanged -= value; + } /// /// This is used for international applications where the language @@ -927,16 +1081,21 @@ public string PathSeparator { DefaultValue(false), SRDescription(nameof(SR.ControlRightToLeftLayoutDescr)) ] - public virtual bool RightToLeftLayout { - get { + public virtual bool RightToLeftLayout + { + get + { return rightToLeftLayout; } - set { - if (value != rightToLeftLayout) { + set + { + if (value != rightToLeftLayout) + { rightToLeftLayout = value; - using(new LayoutTransaction(this, this, PropertyNames.RightToLeftLayout)) { + using (new LayoutTransaction(this, this, PropertyNames.RightToLeftLayout)) + { OnRightToLeftLayoutChanged(EventArgs.Empty); } } @@ -949,12 +1108,16 @@ public virtual bool RightToLeftLayout { DefaultValue(true), SRDescription(nameof(SR.TreeViewScrollableDescr)) ] - public bool Scrollable { - get { + public bool Scrollable + { + get + { return treeViewState[TREEVIEWSTATE_scrollable]; } - set { - if (Scrollable != value) { + set + { + if (Scrollable != value) + { treeViewState[TREEVIEWSTATE_scrollable] = value; RecreateHandle(); } @@ -974,31 +1137,40 @@ public bool Scrollable { SRDescription(nameof(SR.TreeViewSelectedImageIndexDescr)), RelatedImageList("ImageList") ] - public int SelectedImageIndex { - get { - if (imageList == null) { + public int SelectedImageIndex + { + get + { + if (imageList == null) + { return -1; } - if (SelectedImageIndexer.Index >= imageList.Images.Count) { + if (SelectedImageIndexer.Index >= imageList.Images.Count) + { return Math.Max(0, imageList.Images.Count - 1); } return SelectedImageIndexer.Index; } - set { + set + { // If (none) is selected in the image index editor, we'll just adjust this to // mean image index 0. This is because a treeview must always have an image index - // even if no imagelist exists we want the image index to be 0. // - if (value == -1) { + if (value == -1) + { value = 0; } - if (value < 0) { + if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(SelectedImageIndex), value, 0)); } - if (SelectedImageIndexer.Index != value) { + if (SelectedImageIndexer.Index != value) + { SelectedImageIndexer.Index = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { RecreateHandle(); } } @@ -1018,19 +1190,25 @@ public int SelectedImageIndex { SRDescription(nameof(SR.TreeViewSelectedImageKeyDescr)), RelatedImageList("ImageList") ] - public string SelectedImageKey { - get { + public string SelectedImageKey + { + get + { return SelectedImageIndexer.Key; } - set { - if (SelectedImageIndexer.Key != value) { + set + { + if (SelectedImageIndexer.Key != value) + { SelectedImageIndexer.Key = value; - if (string.IsNullOrEmpty(value) || value.Equals(SR.toStringNone)) { + if (string.IsNullOrEmpty(value) || value.Equals(SR.toStringNone)) + { SelectedImageIndex = (ImageList != null) ? 0 : -1; } - if (IsHandleCreated) { + if (IsHandleCreated) + { RecreateHandle(); } } @@ -1046,24 +1224,31 @@ public string SelectedImageKey { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.TreeViewSelectedNodeDescr)) ] - public TreeNode SelectedNode { - get { - if (IsHandleCreated) { + public TreeNode SelectedNode + { + get + { + if (IsHandleCreated) + { Debug.Assert(selectedNode == null || selectedNode.TreeView != this, "handle is created, but we're still caching selectedNode"); IntPtr hItem = SendMessage(NativeMethods.TVM_GETNEXTITEM, NativeMethods.TVGN_CARET, 0); if (hItem == IntPtr.Zero) return null; return NodeFromHandle(hItem); } - else if (selectedNode != null && selectedNode.TreeView == this) { + else if (selectedNode != null && selectedNode.TreeView == this) + { return selectedNode; } - else { + else + { return null; } } - set { - if (IsHandleCreated && (value == null || value.TreeView == this)) { + set + { + if (IsHandleCreated && (value == null || value.TreeView == this)) + { // This class invariant is not quite correct -- if the selected node does not belong to this Treeview, // selectedNode != null even though the handle is created. We will call set_SelectedNode // to inform the handle that the selected node has been added to the TreeView. @@ -1073,7 +1258,8 @@ public TreeNode SelectedNode { SendMessage(NativeMethods.TVM_SELECTITEM, NativeMethods.TVGN_CARET, hnode); selectedNode = null; } - else { + else + { selectedNode = value; } } @@ -1088,14 +1274,19 @@ public TreeNode SelectedNode { DefaultValue(true), SRDescription(nameof(SR.TreeViewShowLinesDescr)) ] - public bool ShowLines { - get { + public bool ShowLines + { + get + { return treeViewState[TREEVIEWSTATE_showLines]; } - set { - if (ShowLines != value) { + set + { + if (ShowLines != value) + { treeViewState[TREEVIEWSTATE_showLines] = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { UpdateStyles(); } } @@ -1110,12 +1301,16 @@ public bool ShowLines { DefaultValue(false), SRDescription(nameof(SR.TreeViewShowShowNodeToolTipsDescr)) ] - public bool ShowNodeToolTips { - get { + public bool ShowNodeToolTips + { + get + { return treeViewState[TREEVIEWSTATE_showNodeToolTips]; } - set { - if (ShowNodeToolTips != value) { + set + { + if (ShowNodeToolTips != value) + { treeViewState[TREEVIEWSTATE_showNodeToolTips] = value; if (ShowNodeToolTips) RecreateHandle(); @@ -1132,14 +1327,19 @@ public bool ShowNodeToolTips { DefaultValue(true), SRDescription(nameof(SR.TreeViewShowPlusMinusDescr)) ] - public bool ShowPlusMinus { - get { + public bool ShowPlusMinus + { + get + { return treeViewState[TREEVIEWSTATE_showPlusMinus]; } - set { - if (ShowPlusMinus != value) { + set + { + if (ShowPlusMinus != value) + { treeViewState[TREEVIEWSTATE_showPlusMinus] = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { UpdateStyles(); } } @@ -1155,12 +1355,16 @@ public bool ShowPlusMinus { DefaultValue(true), SRDescription(nameof(SR.TreeViewShowRootLinesDescr)) ] - public bool ShowRootLines { - get { return treeViewState[TREEVIEWSTATE_showRootLines];} - set { - if (ShowRootLines != value) { + public bool ShowRootLines + { + get { return treeViewState[TREEVIEWSTATE_showRootLines]; } + set + { + if (ShowRootLines != value) + { treeViewState[TREEVIEWSTATE_showRootLines] = value; - if (IsHandleCreated) { + if (IsHandleCreated) + { UpdateStyles(); } } @@ -1176,14 +1380,19 @@ public bool ShowRootLines { SRDescription(nameof(SR.TreeViewSortedDescr)), Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] - public bool Sorted { - get { + public bool Sorted + { + get + { return treeViewState[TREEVIEWSTATE_sorted]; } - set { - if (Sorted != value) { + set + { + if (Sorted != value) + { treeViewState[TREEVIEWSTATE_sorted] = value; - if (Sorted && TreeViewNodeSorter == null && Nodes.Count >= 1) { + if (Sorted && TreeViewNodeSorter == null && Nodes.Count >= 1) + { RefreshNodes(); } } @@ -1200,14 +1409,19 @@ public bool Sorted { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.TreeViewNodeSorterDescr)) ] - public IComparer TreeViewNodeSorter { - get { + public IComparer TreeViewNodeSorter + { + get + { return treeViewNodeSorter; } - set { - if (treeViewNodeSorter != value) { + set + { + if (treeViewNodeSorter != value) + { treeViewNodeSorter = value; - if (value != null) { + if (value != null) + { Sort(); } } @@ -1215,17 +1429,21 @@ public IComparer TreeViewNodeSorter { } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Bindable(false)] - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TextChanged { + new public event EventHandler TextChanged + { add => base.TextChanged += value; remove => base.TextChanged -= value; } @@ -1241,16 +1459,21 @@ public override string Text { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.TreeViewTopNodeDescr)) ] - public TreeNode TopNode { - get { - if (IsHandleCreated) { + public TreeNode TopNode + { + get + { + if (IsHandleCreated) + { IntPtr hitem = SendMessage(NativeMethods.TVM_GETNEXTITEM, NativeMethods.TVGN_FIRSTVISIBLE, 0); - return(hitem == IntPtr.Zero ? null : NodeFromHandle(hitem)); + return (hitem == IntPtr.Zero ? null : NodeFromHandle(hitem)); } return topNode; } - set { - if (IsHandleCreated && (value == null || value.TreeView == this)) { + set + { + if (IsHandleCreated && (value == null || value.TreeView == this)) + { // This class invariant is not quite correct -- if the selected node does not belong to this Treeview, // selectedNode != null even though the handle is created. We will call set_SelectedNode // to inform the handle that the selected node has been added to the TreeView. @@ -1260,7 +1483,8 @@ public TreeNode TopNode { SendMessage(NativeMethods.TVM_SELECTITEM, NativeMethods.TVGN_FIRSTVISIBLE, hnode); topNode = null; } - else { + else + { topNode = value; } @@ -1279,10 +1503,12 @@ public TreeNode TopNode { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.TreeViewVisibleCountDescr)) ] - public int VisibleCount { - get { + public int VisibleCount + { + get + { if (IsHandleCreated) - return unchecked( (int) (long)SendMessage(NativeMethods.TVM_GETVISIBLECOUNT, 0, 0)); + return unchecked((int)(long)SendMessage(NativeMethods.TVM_GETVISIBLECOUNT, 0, 0)); return 0; } @@ -1290,56 +1516,64 @@ public int VisibleCount { [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.TreeViewBeforeEditDescr))] - public event NodeLabelEditEventHandler BeforeLabelEdit { + public event NodeLabelEditEventHandler BeforeLabelEdit + { add => onBeforeLabelEdit += value; remove => onBeforeLabelEdit -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.TreeViewAfterEditDescr))] - public event NodeLabelEditEventHandler AfterLabelEdit { + public event NodeLabelEditEventHandler AfterLabelEdit + { add => onAfterLabelEdit += value; remove => onAfterLabelEdit -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.TreeViewBeforeCheckDescr))] - public event TreeViewCancelEventHandler BeforeCheck { + public event TreeViewCancelEventHandler BeforeCheck + { add => onBeforeCheck += value; remove => onBeforeCheck -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.TreeViewAfterCheckDescr))] - public event TreeViewEventHandler AfterCheck { + public event TreeViewEventHandler AfterCheck + { add => onAfterCheck += value; remove => onAfterCheck -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.TreeViewBeforeCollapseDescr))] - public event TreeViewCancelEventHandler BeforeCollapse { + public event TreeViewCancelEventHandler BeforeCollapse + { add => onBeforeCollapse += value; remove => onBeforeCollapse -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.TreeViewAfterCollapseDescr))] - public event TreeViewEventHandler AfterCollapse { + public event TreeViewEventHandler AfterCollapse + { add => onAfterCollapse += value; remove => onAfterCollapse -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.TreeViewBeforeExpandDescr))] - public event TreeViewCancelEventHandler BeforeExpand { + public event TreeViewCancelEventHandler BeforeExpand + { add => onBeforeExpand += value; remove => onBeforeExpand -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.TreeViewAfterExpandDescr))] - public event TreeViewEventHandler AfterExpand { + public event TreeViewEventHandler AfterExpand + { add => onAfterExpand += value; remove => onAfterExpand -= value; } @@ -1348,19 +1582,22 @@ public event TreeViewEventHandler AfterExpand { /// Fires when a TreeView node needs to be drawn. /// [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.TreeViewDrawNodeEventDescr))] - public event DrawTreeNodeEventHandler DrawNode { + public event DrawTreeNodeEventHandler DrawNode + { add => onDrawNode += value; remove => onDrawNode -= value; } [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.ListViewItemDragDescr))] - public event ItemDragEventHandler ItemDrag { + public event ItemDragEventHandler ItemDrag + { add => onItemDrag += value; remove => onItemDrag -= value; } [SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.TreeViewNodeMouseHoverDescr))] - public event TreeNodeMouseHoverEventHandler NodeMouseHover { + public event TreeNodeMouseHoverEventHandler NodeMouseHover + { add => onNodeMouseHover += value; remove => onNodeMouseHover -= value; } @@ -1368,14 +1605,16 @@ public event TreeNodeMouseHoverEventHandler NodeMouseHover { [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.TreeViewBeforeSelectDescr))] - public event TreeViewCancelEventHandler BeforeSelect { + public event TreeViewCancelEventHandler BeforeSelect + { add => onBeforeSelect += value; remove => onBeforeSelect -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.TreeViewAfterSelectDescr))] - public event TreeViewEventHandler AfterSelect { + public event TreeViewEventHandler AfterSelect + { add => onAfterSelect += value; remove => onAfterSelect -= value; } @@ -1385,25 +1624,29 @@ public event TreeViewEventHandler AfterSelect { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event PaintEventHandler Paint { + public new event PaintEventHandler Paint + { add => base.Paint += value; remove => base.Paint -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.TreeViewNodeMouseClickDescr))] - public event TreeNodeMouseClickEventHandler NodeMouseClick { + public event TreeNodeMouseClickEventHandler NodeMouseClick + { add => onNodeMouseClick += value; remove => onNodeMouseClick -= value; } [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.TreeViewNodeMouseDoubleClickDescr))] - public event TreeNodeMouseClickEventHandler NodeMouseDoubleClick { + public event TreeNodeMouseClickEventHandler NodeMouseDoubleClick + { add => onNodeMouseDoubleClick += value; remove => onNodeMouseDoubleClick -= value; } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnRightToLeftLayoutChangedDescr))] - public event EventHandler RightToLeftLayoutChanged { + public event EventHandler RightToLeftLayoutChanged + { add => onRightToLeftLayoutChanged += value; remove => onRightToLeftLayoutChanged -= value; } @@ -1415,27 +1658,34 @@ public event EventHandler RightToLeftLayoutChanged { /// beginUpdate(), any redrawing caused by operations performed on the /// tree view is deferred until the call to endUpdate(). /// - public void BeginUpdate() { + public void BeginUpdate() + { BeginUpdateInternal(); } /// /// Collapses all nodes at the root level. /// - public void CollapseAll() { + public void CollapseAll() + { root.Collapse(); } /// /// - protected override void CreateHandle() { - if (!RecreatingHandle) { + protected override void CreateHandle() + { + if (!RecreatingHandle) + { IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); - try { + try + { NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); icc.dwICC = NativeMethods.ICC_TREEVIEW_CLASSES; SafeNativeMethods.InitCommonControlsEx(icc); - } finally { + } + finally + { UnsafeNativeMethods.ThemingScope.Deactivate(userCookie); } } @@ -1446,7 +1696,8 @@ protected override void CreateHandle() { /// Resets the imageList to null. We wire this method up to the imageList's /// Dispose event, so that we don't hang onto an imageList that's gone away. /// - private void DetachImageList(object sender, EventArgs e) { + private void DetachImageList(object sender, EventArgs e) + { ImageList = null; } @@ -1454,7 +1705,8 @@ private void DetachImageList(object sender, EventArgs e) { /// Resets the stateimageList to null. We wire this method up to the stateimageList's /// Dispose event, so that we don't hang onto an stateimageList that's gone away. /// - private void DetachStateImageList(object sender, EventArgs e) { + private void DetachStateImageList(object sender, EventArgs e) + { internalStateImageList = null; StateImageList = null; @@ -1462,15 +1714,19 @@ private void DetachStateImageList(object sender, EventArgs e) { /// /// - protected override void Dispose(bool disposing) { - if (disposing) { + protected override void Dispose(bool disposing) + { + if (disposing) + { - foreach (TreeNode node in Nodes) { + foreach (TreeNode node in Nodes) + { node.ContextMenu = null; } // - lock(this) { + lock (this) + { DetachImageListHandlers(); imageList = null; DetachStateImageListHandlers(); @@ -1488,14 +1744,16 @@ protected override void Dispose(bool disposing) { /// beginUpdate(), any redrawing caused by operations performed on the /// combo box is deferred until the call to endUpdate(). /// - public void EndUpdate() { + public void EndUpdate() + { EndUpdateInternal(); } /// /// Expands all nodes at the root level. /// - public void ExpandAll() { + public void ExpandAll() + { root.ExpandAll(); } @@ -1503,7 +1761,8 @@ public void ExpandAll() { /// Forces the TreeView to recalculate all its nodes widths so that it updates the /// scrollbars as appropriate. /// - internal void ForceScrollbarUpdate(bool delayed) { + internal void ForceScrollbarUpdate(bool delayed) + { // ForceScrollbarUpdate call WM_SETREDRAW( FALSE ) followed by WM_SETREDRAW( TRUE ) // So if TreeView.BeginUpdate is called @@ -1511,7 +1770,8 @@ internal void ForceScrollbarUpdate(bool delayed) { // So gaurd against this scenario by using the new internal method on Control. if (!IsUpdating()) { - if (IsHandleCreated) { + if (IsHandleCreated) + { SendMessage(Interop.WindowMessages.WM_SETREDRAW, 0, 0); if (delayed) UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), Interop.WindowMessages.WM_SETREDRAW, (IntPtr)1, IntPtr.Zero); @@ -1524,8 +1784,10 @@ internal void ForceScrollbarUpdate(bool delayed) { /// /// Called by ToolTip to poke in that Tooltip into this ComCtl so that the Native ChildToolTip is not exposed. /// - internal void SetToolTip(ToolTip toolTip, string toolTipText) { - if (toolTip != null) { + internal void SetToolTip(ToolTip toolTip, string toolTipText) + { + if (toolTip != null) + { UnsafeNativeMethods.SendMessage(new HandleRef(toolTip, toolTip.Handle), NativeMethods.TTM_SETMAXTIPWIDTH, 0, SystemInformation.MaxWindowTrackSize.Width); UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.TVM_SETTOOLTIPS, new HandleRef(toolTip, toolTip.Handle), 0); controlToolTipText = toolTipText; @@ -1536,14 +1798,16 @@ internal void SetToolTip(ToolTip toolTip, string toolTipText) { /// /// Gives the information about which part of the treeNode is at the given point. /// - public TreeViewHitTestInfo HitTest(Point pt) { + public TreeViewHitTestInfo HitTest(Point pt) + { return HitTest(pt.X, pt.Y); } /// /// Gives the information about which part of the treeNode is at the given x, y. /// - public TreeViewHitTestInfo HitTest(int x, int y) { + public TreeViewHitTestInfo HitTest(int x, int y) + { NativeMethods.TV_HITTESTINFO tvhi = new NativeMethods.TV_HITTESTINFO(); tvhi.pt_x = x; tvhi.pt_y = y; @@ -1558,13 +1822,15 @@ public TreeViewHitTestInfo HitTest(int x, int y) { /// /// - internal bool TreeViewBeforeCheck(TreeNode node, TreeViewAction actionTaken) { + internal bool TreeViewBeforeCheck(TreeNode node, TreeViewAction actionTaken) + { TreeViewCancelEventArgs tvce = new TreeViewCancelEventArgs(node, false, actionTaken); OnBeforeCheck(tvce); return (tvce.Cancel); } - internal void TreeViewAfterCheck(TreeNode node, TreeViewAction actionTaken) { + internal void TreeViewAfterCheck(TreeNode node, TreeViewAction actionTaken) + { OnAfterCheck(new TreeViewEventArgs(node, actionTaken)); } @@ -1572,21 +1838,24 @@ internal void TreeViewAfterCheck(TreeNode node, TreeViewAction actionTaken) { /// /// Returns count of nodes at root, optionally including all subtrees. /// - public int GetNodeCount(bool includeSubTrees) { + public int GetNodeCount(bool includeSubTrees) + { return root.GetNodeCount(includeSubTrees); } /// /// Returns the TreeNode at the given location in tree view coordinates. /// - public TreeNode GetNodeAt(Point pt) { + public TreeNode GetNodeAt(Point pt) + { return GetNodeAt(pt.X, pt.Y); } /// /// Returns the TreeNode at the given location in tree view coordinates. /// - public TreeNode GetNodeAt(int x, int y) { + public TreeNode GetNodeAt(int x, int y) + { NativeMethods.TV_HITTESTINFO tvhi = new NativeMethods.TV_HITTESTINFO(); tvhi.pt_x = x; @@ -1594,65 +1863,78 @@ public TreeNode GetNodeAt(int x, int y) { IntPtr hnode = UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TVM_HITTEST, 0, tvhi); - return(hnode == IntPtr.Zero ? null : NodeFromHandle(hnode)); + return (hnode == IntPtr.Zero ? null : NodeFromHandle(hnode)); } - private void ImageListRecreateHandle(object sender, EventArgs e) { - if (IsHandleCreated) { + private void ImageListRecreateHandle(object sender, EventArgs e) + { + if (IsHandleCreated) + { IntPtr handle = (ImageList == null) ? IntPtr.Zero : ImageList.Handle; SendMessage(NativeMethods.TVM_SETIMAGELIST, 0, handle); } } - private void UpdateImagesRecursive ( TreeNode node ) + private void UpdateImagesRecursive(TreeNode node) { node.UpdateImage(); // Iterate only through the Nodes collection rather than the // array since an item might have been removed from the collection, and // correspondingly "removed" from the array, but still exist in the array // since the array isn't actually re-dimensioned down to a smaller size. - foreach (TreeNode child in node.Nodes) { + foreach (TreeNode child in node.Nodes) + { UpdateImagesRecursive(child); } } - private void ImageListChangedHandle(object sender, EventArgs e) { - if ((null != sender) && (sender == imageList) && IsHandleCreated) { + private void ImageListChangedHandle(object sender, EventArgs e) + { + if ((null != sender) && (sender == imageList) && IsHandleCreated) + { BeginUpdate(); - foreach (TreeNode node in Nodes) { + foreach (TreeNode node in Nodes) + { UpdateImagesRecursive(node); } EndUpdate(); } } - private void StateImageListRecreateHandle(object sender, EventArgs e) { - if (IsHandleCreated) { + private void StateImageListRecreateHandle(object sender, EventArgs e) + { + if (IsHandleCreated) + { IntPtr handle = IntPtr.Zero; - if (internalStateImageList != null) { + if (internalStateImageList != null) + { handle = internalStateImageList.Handle; } SetStateImageList(handle); } } - private void StateImageListChangedHandle(object sender, EventArgs e) { - if ((null != sender) && (sender == stateImageList) && IsHandleCreated) { + private void StateImageListChangedHandle(object sender, EventArgs e) + { + if ((null != sender) && (sender == stateImageList) && IsHandleCreated) + { // Since the native treeview requires the state imagelist to be 1-indexed we need to // re add the images if the original collection had changed. - if (stateImageList != null && stateImageList.Images.Count > 0) { + if (stateImageList != null && stateImageList.Images.Count > 0) + { Image[] images = new Image[stateImageList.Images.Count + 1]; images[0] = stateImageList.Images[0]; - for (int i = 1; i <= stateImageList.Images.Count ; i++) { - images[i] = stateImageList.Images[i -1]; + for (int i = 1; i <= stateImageList.Images.Count; i++) + { + images[i] = stateImageList.Images[i - 1]; } - + if (internalStateImageList != null) { internalStateImageList.Images.Clear(); internalStateImageList.Images.AddRange(images); } - else + else { internalStateImageList = new ImageList(); internalStateImageList.Images.AddRange(images); @@ -1660,7 +1942,7 @@ private void StateImageListChangedHandle(object sender, EventArgs e) { Debug.Assert(internalStateImageList != null, "Why are changing images when the Imagelist is null?"); if (internalStateImageList != null) - { + { if (ScaledStateImageSize != null) { internalStateImageList.ImageSize = (Size)ScaledStateImageSize; @@ -1681,12 +1963,15 @@ private void StateImageListChangedHandle(object sender, EventArgs e) { /// Overridden to handle RETURN key. /// /// - protected override bool IsInputKey(Keys keyData) { + protected override bool IsInputKey(Keys keyData) + { // If in edit mode, treat Return as an input key, so the form doesn't grab it // and treat it as clicking the Form.AcceptButton. Similarly for Escape // and Form.CancelButton. - if (editNode != null && (keyData & Keys.Alt) == 0) { - switch (keyData & Keys.KeyCode) { + if (editNode != null && (keyData & Keys.Alt) == 0) + { + switch (keyData & Keys.KeyCode) + { case Keys.Return: case Keys.Escape: case Keys.PageUp: @@ -1703,7 +1988,8 @@ protected override bool IsInputKey(Keys keyData) { /// Note this can be null - particularly if any windows messages get generated during /// the insertion of a tree node (TVM_INSERTITEM) /// - internal TreeNode NodeFromHandle(IntPtr handle) { + internal TreeNode NodeFromHandle(IntPtr handle) + { TreeNode node = (TreeNode)nodeTable[handle]; return node; @@ -1712,13 +1998,16 @@ internal TreeNode NodeFromHandle(IntPtr handle) { /// /// Fires the DrawNode event. /// - protected virtual void OnDrawNode(DrawTreeNodeEventArgs e) { - if (onDrawNode != null) onDrawNode(this, e); - } + protected virtual void OnDrawNode(DrawTreeNodeEventArgs e) + { + if (onDrawNode != null) + onDrawNode(this, e); + } /// /// - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { TreeNode savedSelectedNode = this.selectedNode; this.selectedNode = null; @@ -1726,7 +2015,8 @@ protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); int version = unchecked((int)(long)SendMessage(NativeMethods.CCM_GETVERSION, 0, 0)); - if (version < 5) { + if (version < 5) + { SendMessage(NativeMethods.CCM_SETVERSION, 5, 0); } @@ -1735,13 +2025,15 @@ protected override void OnHandleCreated(EventArgs e) { // we set it here after the window is created, and we make sure we don't set it // in getCreateParams so that this will actually change the value of the bit. // This seems to make the Treeview happy. - if (CheckBoxes) { + if (CheckBoxes) + { int style = unchecked((int)(UnsafeNativeMethods.GetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_STYLE))); style |= NativeMethods.TVS_CHECKBOXES; UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_STYLE, new HandleRef(null, (IntPtr)style)); } - if (ShowNodeToolTips && !DesignMode) { + if (ShowNodeToolTips && !DesignMode) + { int style = unchecked((int)(UnsafeNativeMethods.GetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_STYLE))); style |= NativeMethods.TVS_INFOTIP; UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_STYLE, new HandleRef(null, (IntPtr)style)); @@ -1757,7 +2049,8 @@ protected override void OnHandleCreated(EventArgs e) { SendMessage(NativeMethods.TVM_SETTEXTCOLOR, 0, ColorTranslator.ToWin32(c)); /// put the linecolor into the native control only if Set ... - if (lineColor != Color.Empty) { + if (lineColor != Color.Empty) + { SendMessage(NativeMethods.TVM_SETLINECOLOR, 0, ColorTranslator.ToWin32(lineColor)); } @@ -1769,11 +2062,13 @@ protected override void OnHandleCreated(EventArgs e) { UpdateNativeStateImageList(); } - if (indent != -1) { + if (indent != -1) + { SendMessage(NativeMethods.TVM_SETINDENT, indent, 0); } - if (itemHeight != -1) { + if (itemHeight != -1) + { SendMessage(NativeMethods.TVM_SETITEMHEIGHT, ItemHeight, 0); } @@ -1785,7 +2080,7 @@ protected override void OnHandleCreated(EventArgs e) { int oldSize = 0; try { - + treeViewState[TREEVIEWSTATE_stopResizeWindowMsgs] = true; oldSize = this.Width; int flags = NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE | NativeMethods.SWP_NOMOVE; @@ -1845,7 +2140,7 @@ private void SetStateImageList(IntPtr handle) SafeNativeMethods.ImageList_Destroy_Native(new HandleRef(this, handleOld)); } } - + // Destroying the tree-view control does not destroy the native state image list. // We must destroy it explicitly. private void DestroyNativeStateImageList(bool reset) @@ -1863,7 +2158,8 @@ private void DestroyNativeStateImageList(bool reset) /// /// - protected override void OnHandleDestroyed(EventArgs e) { + protected override void OnHandleDestroyed(EventArgs e) + { selectedNode = SelectedNode; // Unfortunately, to avoid the native tree view leaking it's State Image List, we need to @@ -1885,7 +2181,8 @@ protected override void OnHandleDestroyed(EventArgs e) { /// /// We keep track of if we've hovered already so we don't fire multiple hover events /// - protected override void OnMouseLeave(EventArgs e) { + protected override void OnMouseLeave(EventArgs e) + { hoveredAlready = false; base.OnMouseLeave(e); } @@ -1895,7 +2192,8 @@ protected override void OnMouseLeave(EventArgs e) { /// the node the mouse is hovering over is found. Each time a new node is hovered /// over a new event is raised. /// - protected override void OnMouseHover(EventArgs e) { + protected override void OnMouseHover(EventArgs e) + { /// Hover events need to be caught for each node /// within the TreeView so the appropriate @@ -1908,15 +2206,18 @@ protected override void OnMouseHover(EventArgs e) { tvhip.pt_y = pos.Y; IntPtr hnode = UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TVM_HITTEST, 0, tvhip); - if (hnode != IntPtr.Zero && ((tvhip.flags & NativeMethods.TVHT_ONITEM) != 0)) { + if (hnode != IntPtr.Zero && ((tvhip.flags & NativeMethods.TVHT_ONITEM) != 0)) + { TreeNode tn = NodeFromHandle(hnode); - if (tn != prevHoveredNode && tn != null) { - OnNodeMouseHover( new TreeNodeMouseHoverEventArgs(tn)); + if (tn != prevHoveredNode && tn != null) + { + OnNodeMouseHover(new TreeNodeMouseHoverEventArgs(tn)); prevHoveredNode = tn; } } - if (!hoveredAlready) { + if (!hoveredAlready) + { base.OnMouseHover(e); hoveredAlready = true; } @@ -1928,128 +2229,161 @@ protected override void OnMouseHover(EventArgs e) { /// /// Fires the beforeLabelEdit event. /// - protected virtual void OnBeforeLabelEdit(NodeLabelEditEventArgs e) { + protected virtual void OnBeforeLabelEdit(NodeLabelEditEventArgs e) + { Contract.Requires(e != null); - if (onBeforeLabelEdit != null) onBeforeLabelEdit(this, e); + if (onBeforeLabelEdit != null) + onBeforeLabelEdit(this, e); } /// /// Fires the afterLabelEdit event. /// - protected virtual void OnAfterLabelEdit(NodeLabelEditEventArgs e) { + protected virtual void OnAfterLabelEdit(NodeLabelEditEventArgs e) + { Contract.Requires(e != null); - if (onAfterLabelEdit != null) onAfterLabelEdit(this, e); + if (onAfterLabelEdit != null) + onAfterLabelEdit(this, e); } /// /// Fires the beforeCheck event. /// - protected virtual void OnBeforeCheck(TreeViewCancelEventArgs e) { + protected virtual void OnBeforeCheck(TreeViewCancelEventArgs e) + { Contract.Requires(e != null); - if (onBeforeCheck != null) onBeforeCheck(this, e); + if (onBeforeCheck != null) + onBeforeCheck(this, e); } /// /// Fires the afterCheck event. /// - protected virtual void OnAfterCheck(TreeViewEventArgs e) { + protected virtual void OnAfterCheck(TreeViewEventArgs e) + { Contract.Requires(e != null); - if (onAfterCheck != null) onAfterCheck(this, e); + if (onAfterCheck != null) + onAfterCheck(this, e); } /// /// Fires the beforeCollapse event. /// - protected internal virtual void OnBeforeCollapse(TreeViewCancelEventArgs e) { + protected internal virtual void OnBeforeCollapse(TreeViewCancelEventArgs e) + { Contract.Requires(e != null); - if (onBeforeCollapse != null) onBeforeCollapse(this, e); + if (onBeforeCollapse != null) + onBeforeCollapse(this, e); } /// /// Fires the afterCollapse event. /// - protected internal virtual void OnAfterCollapse(TreeViewEventArgs e) { + protected internal virtual void OnAfterCollapse(TreeViewEventArgs e) + { Contract.Requires(e != null); - if (onAfterCollapse != null) onAfterCollapse(this, e); + if (onAfterCollapse != null) + onAfterCollapse(this, e); } /// /// Fires the beforeExpand event. /// - protected virtual void OnBeforeExpand(TreeViewCancelEventArgs e) { + protected virtual void OnBeforeExpand(TreeViewCancelEventArgs e) + { Contract.Requires(e != null); - if (onBeforeExpand != null) onBeforeExpand(this, e); + if (onBeforeExpand != null) + onBeforeExpand(this, e); } /// /// Fires the afterExpand event. /// - protected virtual void OnAfterExpand(TreeViewEventArgs e) { + protected virtual void OnAfterExpand(TreeViewEventArgs e) + { Contract.Requires(e != null); - if (onAfterExpand != null) onAfterExpand(this, e); + if (onAfterExpand != null) + onAfterExpand(this, e); } /// /// Fires the ItemDrag event. /// - protected virtual void OnItemDrag(ItemDragEventArgs e) { + protected virtual void OnItemDrag(ItemDragEventArgs e) + { Contract.Requires(e != null); - if (onItemDrag != null) onItemDrag(this, e); + if (onItemDrag != null) + onItemDrag(this, e); } /// /// Fires the NodeMouseHover event. /// - protected virtual void OnNodeMouseHover(TreeNodeMouseHoverEventArgs e) { + protected virtual void OnNodeMouseHover(TreeNodeMouseHoverEventArgs e) + { Contract.Requires(e != null); - if (onNodeMouseHover != null) onNodeMouseHover(this, e); + if (onNodeMouseHover != null) + onNodeMouseHover(this, e); } /// /// Fires the beforeSelect event. /// - protected virtual void OnBeforeSelect(TreeViewCancelEventArgs e) { + protected virtual void OnBeforeSelect(TreeViewCancelEventArgs e) + { Contract.Requires(e != null); - if (onBeforeSelect != null) onBeforeSelect(this, e); + if (onBeforeSelect != null) + onBeforeSelect(this, e); } /// /// Fires the afterSelect event. /// - protected virtual void OnAfterSelect(TreeViewEventArgs e) { + protected virtual void OnAfterSelect(TreeViewEventArgs e) + { Contract.Requires(e != null); - if (onAfterSelect != null) onAfterSelect(this, e); + if (onAfterSelect != null) + onAfterSelect(this, e); } /// /// Fires the onNodeMouseClick event. /// - protected virtual void OnNodeMouseClick(TreeNodeMouseClickEventArgs e) { + protected virtual void OnNodeMouseClick(TreeNodeMouseClickEventArgs e) + { Contract.Requires(e != null); - if (onNodeMouseClick != null) onNodeMouseClick(this, e); + if (onNodeMouseClick != null) + onNodeMouseClick(this, e); } /// /// Fires the onNodeMouseDoubleClick event. /// - protected virtual void OnNodeMouseDoubleClick(TreeNodeMouseClickEventArgs e) { + protected virtual void OnNodeMouseDoubleClick(TreeNodeMouseClickEventArgs e) + { Contract.Requires(e != null); - if (onNodeMouseDoubleClick != null) onNodeMouseDoubleClick(this, e); + if (onNodeMouseDoubleClick != null) + onNodeMouseDoubleClick(this, e); } /// /// Handles the OnBeforeCheck / OnAfterCheck for keyboard clicks /// - protected override void OnKeyDown(KeyEventArgs e) { + protected override void OnKeyDown(KeyEventArgs e) + { base.OnKeyDown(e); - if (e.Handled) return; + if (e.Handled) + return; // if it's a space, send the check notifications and toggle the checkbox if we're not // cancelled. - if (CheckBoxes && (e.KeyData & Keys.KeyCode) == Keys.Space) { + if (CheckBoxes && (e.KeyData & Keys.KeyCode) == Keys.Space) + { TreeNode node = this.SelectedNode; - if (node != null) { + if (node != null) + { bool eventReturn = TreeViewBeforeCheck(node, TreeViewAction.ByKeyboard); - if (!eventReturn) { + if (!eventReturn) + { node.CheckedInternal = !node.CheckedInternal; TreeViewAfterCheck(node, TreeViewAction.ByKeyboard); } @@ -2062,11 +2396,14 @@ protected override void OnKeyDown(KeyEventArgs e) { /// /// Handles the OnBeforeCheck / OnAfterCheck for keyboard clicks /// - protected override void OnKeyUp(KeyEventArgs e) { + protected override void OnKeyUp(KeyEventArgs e) + { base.OnKeyUp(e); - if (e.Handled) return; + if (e.Handled) + return; // eat the space key - if ((e.KeyData & Keys.KeyCode) == Keys.Space) { + if ((e.KeyData & Keys.KeyCode) == Keys.Space) + { e.Handled = true; return; } @@ -2075,27 +2412,34 @@ protected override void OnKeyUp(KeyEventArgs e) { /// /// Handles the OnBeforeCheck / OnAfterCheck for keyboard clicks /// - protected override void OnKeyPress(KeyPressEventArgs e) { + protected override void OnKeyPress(KeyPressEventArgs e) + { base.OnKeyPress(e); - if (e.Handled) return; + if (e.Handled) + return; // eat the space key - if (e.KeyChar == ' ') e.Handled = true; + if (e.KeyChar == ' ') + e.Handled = true; } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnRightToLeftLayoutChanged(EventArgs e) { + protected virtual void OnRightToLeftLayoutChanged(EventArgs e) + { Contract.Requires(e != null); - if (GetAnyDisposingInHierarchy()) { + if (GetAnyDisposingInHierarchy()) + { return; } - if (RightToLeft == RightToLeft.Yes) { + if (RightToLeft == RightToLeft.Yes) + { RecreateHandle(); } - if (onRightToLeftLayoutChanged != null) { - onRightToLeftLayoutChanged(this, e); + if (onRightToLeftLayoutChanged != null) + { + onRightToLeftLayoutChanged(this, e); } } @@ -2103,7 +2447,8 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) { // Refresh the nodes by clearing the tree and adding the nodes back again // - private void RefreshNodes() { + private void RefreshNodes() + { TreeNode[] nodes = new TreeNode[Nodes.Count]; Nodes.CopyTo(nodes, 0); @@ -2114,7 +2459,8 @@ private void RefreshNodes() { /// /// This resets the indentation to the system default. /// - private void ResetIndent() { + private void ResetIndent() + { indent = -1; // is this overkill? RecreateHandle(); @@ -2123,7 +2469,8 @@ private void ResetIndent() { /// /// This resets the item height to the system default. /// - private void ResetItemHeight() { + private void ResetItemHeight() + { itemHeight = -1; RecreateHandle(); } @@ -2131,49 +2478,58 @@ private void ResetItemHeight() { /// /// Retrieves true if the indent should be persisted in code gen. /// - private bool ShouldSerializeIndent() { - return(indent != -1); + private bool ShouldSerializeIndent() + { + return (indent != -1); } /// /// Retrieves true if the itemHeight should be persisted in code gen. /// - private bool ShouldSerializeItemHeight() { - return(itemHeight != -1); + private bool ShouldSerializeItemHeight() + { + return (itemHeight != -1); } - private bool ShouldSerializeSelectedImageIndex() { - if (imageList != null) { - return (SelectedImageIndex != 0); - } - return (SelectedImageIndex != -1); - } + private bool ShouldSerializeSelectedImageIndex() + { + if (imageList != null) + { + return (SelectedImageIndex != 0); + } + return (SelectedImageIndex != -1); + } - private bool ShouldSerializeImageIndex() { - if (imageList != null) { - return (ImageIndex != 0); - } - return (ImageIndex != -1); - } + private bool ShouldSerializeImageIndex() + { + if (imageList != null) + { + return (ImageIndex != 0); + } + return (ImageIndex != -1); + } /// /// Updated the sorted order /// - public void Sort() { + public void Sort() + { Sorted = true; RefreshNodes(); } - + /// /// Returns a string representation for this control. /// - public override string ToString() { + public override string ToString() + { string s = base.ToString(); - if (Nodes != null) { + if (Nodes != null) + { s += ", Nodes.Count: " + Nodes.Count.ToString(CultureInfo.CurrentCulture); if (Nodes.Count > 0) s += ", Nodes[0]: " + Nodes[0].ToString(); @@ -2181,11 +2537,13 @@ public override string ToString() { return s; } - private unsafe void TvnBeginDrag(MouseButtons buttons, NativeMethods.NMTREEVIEW* nmtv) { + private unsafe void TvnBeginDrag(MouseButtons buttons, NativeMethods.NMTREEVIEW* nmtv) + { NativeMethods.TV_ITEM item = nmtv->itemNew; // Check for invalid node handle - if (item.hItem == IntPtr.Zero) { + if (item.hItem == IntPtr.Zero) + { return; } @@ -2194,31 +2552,37 @@ private unsafe void TvnBeginDrag(MouseButtons buttons, NativeMethods.NMTREEVIEW* OnItemDrag(new ItemDragEventArgs(buttons, node)); } - private unsafe IntPtr TvnExpanding(NativeMethods.NMTREEVIEW* nmtv) { + private unsafe IntPtr TvnExpanding(NativeMethods.NMTREEVIEW* nmtv) + { NativeMethods.TV_ITEM item = nmtv->itemNew; // Check for invalid node handle - if (item.hItem == IntPtr.Zero) { + if (item.hItem == IntPtr.Zero) + { return IntPtr.Zero; } TreeViewCancelEventArgs e = null; - if ((item.state & NativeMethods.TVIS_EXPANDED) == 0) { + if ((item.state & NativeMethods.TVIS_EXPANDED) == 0) + { e = new TreeViewCancelEventArgs(NodeFromHandle(item.hItem), false, TreeViewAction.Expand); OnBeforeExpand(e); } - else { + else + { e = new TreeViewCancelEventArgs(NodeFromHandle(item.hItem), false, TreeViewAction.Collapse); OnBeforeCollapse(e); } - return (IntPtr)(e.Cancel? 1: 0); + return (IntPtr)(e.Cancel ? 1 : 0); } - private unsafe void TvnExpanded(NativeMethods.NMTREEVIEW* nmtv) { + private unsafe void TvnExpanded(NativeMethods.NMTREEVIEW* nmtv) + { NativeMethods.TV_ITEM item = nmtv->itemNew; // Check for invalid node handle - if (item.hItem == IntPtr.Zero) { + if (item.hItem == IntPtr.Zero) + { return; } @@ -2226,30 +2590,35 @@ private unsafe void TvnExpanded(NativeMethods.NMTREEVIEW* nmtv) { TreeNode node = NodeFromHandle(item.hItem); // Note that IsExpanded is invalid for the moment, so we use item item.state to branch. - if ((item.state & NativeMethods.TVIS_EXPANDED) == 0) { + if ((item.state & NativeMethods.TVIS_EXPANDED) == 0) + { e = new TreeViewEventArgs(node, TreeViewAction.Collapse); OnAfterCollapse(e); } - else { + else + { e = new TreeViewEventArgs(node, TreeViewAction.Expand); OnAfterExpand(e); } } - private unsafe IntPtr TvnSelecting(NativeMethods.NMTREEVIEW* nmtv) { - if (treeViewState[ TREEVIEWSTATE_ignoreSelects]) + private unsafe IntPtr TvnSelecting(NativeMethods.NMTREEVIEW* nmtv) + { + if (treeViewState[TREEVIEWSTATE_ignoreSelects]) { return (IntPtr)1; } // Check for invalid node handle - if (nmtv->itemNew.hItem == IntPtr.Zero) { + if (nmtv->itemNew.hItem == IntPtr.Zero) + { return IntPtr.Zero; } TreeNode node = NodeFromHandle(nmtv->itemNew.hItem); TreeViewAction action = TreeViewAction.Unknown; - switch(nmtv->action) { + switch (nmtv->action) + { case NativeMethods.TVC_BYKEYBOARD: action = TreeViewAction.ByKeyboard; break; @@ -2261,17 +2630,20 @@ private unsafe IntPtr TvnSelecting(NativeMethods.NMTREEVIEW* nmtv) { TreeViewCancelEventArgs e = new TreeViewCancelEventArgs(node, false, action); OnBeforeSelect(e); - return (IntPtr)(e.Cancel? 1: 0); + return (IntPtr)(e.Cancel ? 1 : 0); } - private unsafe void TvnSelected(NativeMethods.NMTREEVIEW* nmtv) { + private unsafe void TvnSelected(NativeMethods.NMTREEVIEW* nmtv) + { if (nodesCollectionClear) //if called thru the Clear( ) of treeNodeCollection then just return... { return; } - if (nmtv->itemNew.hItem != IntPtr.Zero) { + if (nmtv->itemNew.hItem != IntPtr.Zero) + { TreeViewAction action = TreeViewAction.Unknown; - switch(nmtv->action) { + switch (nmtv->action) + { case NativeMethods.TVC_BYKEYBOARD: action = TreeViewAction.ByKeyboard; break; @@ -2286,17 +2658,20 @@ private unsafe void TvnSelected(NativeMethods.NMTREEVIEW* nmtv) { // if the unselected image is blank. // NativeMethods.RECT rc = new NativeMethods.RECT(); - *((IntPtr *) &rc.left) = nmtv->itemOld.hItem; - if (nmtv->itemOld.hItem != IntPtr.Zero) { - if (unchecked( (int) (long)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TVM_GETITEMRECT, 1, ref rc)) != 0) + *((IntPtr*)&rc.left) = nmtv->itemOld.hItem; + if (nmtv->itemOld.hItem != IntPtr.Zero) + { + if (unchecked((int)(long)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TVM_GETITEMRECT, 1, ref rc)) != 0) SafeNativeMethods.InvalidateRect(new HandleRef(this, Handle), ref rc, true); } } - private IntPtr TvnBeginLabelEdit(NativeMethods.NMTVDISPINFO nmtvdi) { + private IntPtr TvnBeginLabelEdit(NativeMethods.NMTVDISPINFO nmtvdi) + { // Check for invalid node handle - if (nmtvdi.item.hItem == IntPtr.Zero) { + if (nmtvdi.item.hItem == IntPtr.Zero) + { return IntPtr.Zero; } @@ -2308,11 +2683,13 @@ private IntPtr TvnBeginLabelEdit(NativeMethods.NMTVDISPINFO nmtvdi) { return (IntPtr)(e.CancelEdit ? 1 : 0); } - private IntPtr TvnEndLabelEdit(NativeMethods.NMTVDISPINFO nmtvdi) { + private IntPtr TvnEndLabelEdit(NativeMethods.NMTVDISPINFO nmtvdi) + { editNode = null; // Check for invalid node handle - if (nmtvdi.item.hItem == IntPtr.Zero) { + if (nmtvdi.item.hItem == IntPtr.Zero) + { return (IntPtr)1; } @@ -2320,7 +2697,8 @@ private IntPtr TvnEndLabelEdit(NativeMethods.NMTVDISPINFO nmtvdi) { string newText = (nmtvdi.item.pszText == IntPtr.Zero ? null : Marshal.PtrToStringAuto(nmtvdi.item.pszText)); NodeLabelEditEventArgs e = new NodeLabelEditEventArgs(node, newText); OnAfterLabelEdit(e); - if (newText != null && !e.CancelEdit && node != null) { + if (newText != null && !e.CancelEdit && node != null) + { node.text = newText; if (Scrollable) ForceScrollbarUpdate(true); @@ -2328,14 +2706,18 @@ private IntPtr TvnEndLabelEdit(NativeMethods.NMTVDISPINFO nmtvdi) { return (IntPtr)(e.CancelEdit ? 0 : 1); } - internal override void UpdateStylesCore() { + internal override void UpdateStylesCore() + { base.UpdateStylesCore(); - if (IsHandleCreated && CheckBoxes) { - if (StateImageList != null) { + if (IsHandleCreated && CheckBoxes) + { + if (StateImageList != null) + { // Setting the TVS_CHECKBOXES window style also causes the TreeView to display the default checkbox // images rather than the user specified StateImageList. We send a TVM_SETIMAGELIST to restore the // user's images. - if (internalStateImageList != null) { + if (internalStateImageList != null) + { SetStateImageList(internalStateImageList.Handle); } @@ -2344,26 +2726,30 @@ internal override void UpdateStylesCore() { } // Setting the NativeMethods.TVS_CHECKBOXES style clears the checked state - private void UpdateCheckedState(TreeNode node, bool update) { + private void UpdateCheckedState(TreeNode node, bool update) + { // This looks funny, but CheckedInternal returns the cached isChecked value and the internal // setter will blindly issue TVM_SETITEM so this gets us back in sync. if (update) { node.CheckedInternal = node.CheckedInternal; - for (int i = node.Nodes.Count - 1; i >= 0; i--) { + for (int i = node.Nodes.Count - 1; i >= 0; i--) + { UpdateCheckedState(node.Nodes[i], update); } } else { node.CheckedInternal = false; - for (int i = node.Nodes.Count - 1; i >= 0; i--) { + for (int i = node.Nodes.Count - 1; i >= 0; i--) + { UpdateCheckedState(node.Nodes[i], update); } } } - private void WmMouseDown(ref Message m, MouseButtons button, int clicks) { + private void WmMouseDown(ref Message m, MouseButtons button, int clicks) + { // Required to put the TreeView in sane-state for painting proper highlighting of selectedNodes. // If the user shows the ContextMenu bu overiding the WndProc( ), then the treeview // goes into the weird state where the high-light gets locked to the node on which the ContextMenu was shown. @@ -2376,38 +2762,42 @@ private void WmMouseDown(ref Message m, MouseButtons button, int clicks) { OnMouseDown(new MouseEventArgs(button, clicks, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); //If Validation is cancelled dont fire any events through the Windows TreeView's message loop... - if (!ValidationCancelled) { + if (!ValidationCancelled) + { DefWndProc(ref m); } } - + /// /// Performs custom draw handling /// - private void CustomDraw(ref Message m) { + private void CustomDraw(ref Message m) + { NativeMethods.NMTVCUSTOMDRAW nmcd = (NativeMethods.NMTVCUSTOMDRAW)m.GetLParam(typeof(NativeMethods.NMTVCUSTOMDRAW)); // Find out which stage we're drawing - switch (nmcd.nmcd.dwDrawStage) { + switch (nmcd.nmcd.dwDrawStage) + { // Do we want OwnerDraw for this paint cycle? case NativeMethods.CDDS_PREPAINT: m.Result = (IntPtr)NativeMethods.CDRF_NOTIFYITEMDRAW; // yes, we do... return; - // We've got opt-in on owner draw for items - so handle each one. + // We've got opt-in on owner draw for items - so handle each one. case NativeMethods.CDDS_ITEMPREPAINT: // get the node Debug.Assert(nmcd.nmcd.dwItemSpec != IntPtr.Zero, "Invalid node handle in ITEMPREPAINT"); TreeNode node = NodeFromHandle((IntPtr)nmcd.nmcd.dwItemSpec); - if (node == null) { - // this can happen if we are presently inserting the node - it hasn't yet - // been added to the handle table + if (node == null) + { + // this can happen if we are presently inserting the node - it hasn't yet + // been added to the handle table - m.Result = (IntPtr)(NativeMethods.CDRF_SKIPDEFAULT); - return; + m.Result = (IntPtr)(NativeMethods.CDRF_SKIPDEFAULT); + return; } @@ -2422,7 +2812,7 @@ private void CustomDraw(ref Message m) { { nmcd.clrText = nmcd.clrTextBk; Marshal.StructureToPtr(nmcd, m.LParam, false); - m.Result = (IntPtr) (NativeMethods.CDRF_NEWFONT | NativeMethods.CDRF_NOTIFYPOSTPAINT); + m.Result = (IntPtr)(NativeMethods.CDRF_NEWFONT | NativeMethods.CDRF_NOTIFYPOSTPAINT); return; } else if (drawMode == TreeViewDrawMode.OwnerDrawAll) @@ -2431,13 +2821,15 @@ private void CustomDraw(ref Message m) { DrawTreeNodeEventArgs e; - try { + try + { Rectangle bounds = node.RowBounds; - + NativeMethods.SCROLLINFO si = new NativeMethods.SCROLLINFO(); si.cbSize = Marshal.SizeOf(); si.fMask = NativeMethods.SIF_POS; - if (UnsafeNativeMethods.GetScrollInfo(new HandleRef(this, Handle), NativeMethods.SB_HORZ,si) != false) { + if (UnsafeNativeMethods.GetScrollInfo(new HandleRef(this, Handle), NativeMethods.SB_HORZ, si) != false) + { // need to get the correct bounds if horizontal scroll bar is shown. // In this case the bounds.X needs to be negative and width needs to be updated to the increased width (scrolled region). @@ -2447,15 +2839,17 @@ private void CustomDraw(ref Message m) { bounds.X -= value; bounds.Width += value; } - } - e = new DrawTreeNodeEventArgs(g, node, bounds, (TreeNodeStates) (state)); + } + e = new DrawTreeNodeEventArgs(g, node, bounds, (TreeNodeStates)(state)); OnDrawNode(e); } - finally { + finally + { g.Dispose(); } - if (!e.DrawDefault) { + if (!e.DrawDefault) + { m.Result = (IntPtr)(NativeMethods.CDRF_SKIPDEFAULT); return; } @@ -2476,7 +2870,7 @@ private void CustomDraw(ref Message m) { "\nINDETERMINATE" + (((state & NativeMethods.CDIS_INDETERMINATE) != 0) ? "TRUE" : "FALSE")); #endif - OwnerDrawPropertyBag renderinfo = GetItemRenderStyles(node,state); + OwnerDrawPropertyBag renderinfo = GetItemRenderStyles(node, state); // TreeView has problems with drawing items at times; it gets confused // as to which colors apply to which items (see focus rectangle shifting; @@ -2485,18 +2879,22 @@ private void CustomDraw(ref Message m) { bool colordelta = false; Color riFore = renderinfo.ForeColor; Color riBack = renderinfo.BackColor; - if (renderinfo != null && !riFore.IsEmpty) { + if (renderinfo != null && !riFore.IsEmpty) + { nmcd.clrText = ColorTranslator.ToWin32(riFore); colordelta = true; } - if (renderinfo != null && !riBack.IsEmpty) { + if (renderinfo != null && !riBack.IsEmpty) + { nmcd.clrTextBk = ColorTranslator.ToWin32(riBack); colordelta = true; } - if (colordelta) { + if (colordelta) + { Marshal.StructureToPtr(nmcd, m.LParam, false); } - if (renderinfo != null && renderinfo.Font != null) { + if (renderinfo != null && renderinfo.Font != null) + { // Mess with the DC directly... SafeNativeMethods.SelectObject(new HandleRef(nmcd.nmcd, nmcd.nmcd.hdc), new HandleRef(renderinfo, renderinfo.FontHandle)); // There is a problem in winctl that clips node fonts if the fontsize @@ -2517,7 +2915,8 @@ private void CustomDraw(ref Message m) { // Get the node node = NodeFromHandle((IntPtr)nmcd.nmcd.dwItemSpec); - if (node == null) { + if (node == null) + { // this can happen if we are presently inserting the node - it hasn't yet // been added to the handle table return; @@ -2529,16 +2928,18 @@ private void CustomDraw(ref Message m) { DrawTreeNodeEventArgs e; - try { + try + { Rectangle bounds = node.Bounds; Size textSize = TextRenderer.MeasureText(node.Text, node.TreeView.Font); - Point textLoc = new Point(bounds.X -1, bounds.Y); // required to center the text + Point textLoc = new Point(bounds.X - 1, bounds.Y); // required to center the text bounds = new Rectangle(textLoc, new Size(textSize.Width, bounds.Height)); - - e = new DrawTreeNodeEventArgs(g, node, bounds, (TreeNodeStates) (nmcd.nmcd.uItemState)); + + e = new DrawTreeNodeEventArgs(g, node, bounds, (TreeNodeStates)(nmcd.nmcd.uItemState)); OnDrawNode(e); - if (e.DrawDefault) { + if (e.DrawDefault) + { //Simulate default text drawing here TreeNodeStates curState = e.State; @@ -2548,9 +2949,9 @@ private void CustomDraw(ref Message m) { // Draw the actual node. if ((curState & TreeNodeStates.Selected) == TreeNodeStates.Selected) { - g.FillRectangle(SystemBrushes.Highlight, bounds); - ControlPaint.DrawFocusRectangle(g, bounds, color, SystemColors.Highlight); - TextRenderer.DrawText(g, e.Node.Text, font, bounds, color, TextFormatFlags.Default); + g.FillRectangle(SystemBrushes.Highlight, bounds); + ControlPaint.DrawFocusRectangle(g, bounds, color, SystemColors.Highlight); + TextRenderer.DrawText(g, e.Node.Text, font, bounds, color, TextFormatFlags.Default); } else { @@ -2563,7 +2964,8 @@ private void CustomDraw(ref Message m) { } } } - finally { + finally + { g.Dispose(); } @@ -2577,7 +2979,7 @@ private void CustomDraw(ref Message m) { // just in case we get a spurious message, tell it to do the right thing m.Result = (IntPtr)NativeMethods.CDRF_DODEFAULT; return; - } + } } /// @@ -2585,12 +2987,15 @@ private void CustomDraw(ref Message m) { /// basis, rather than using the ForeColor/BackColor/NodeFont properties on TreeNode. /// /// - protected OwnerDrawPropertyBag GetItemRenderStyles(TreeNode node, int state) { + protected OwnerDrawPropertyBag GetItemRenderStyles(TreeNode node, int state) + { OwnerDrawPropertyBag retval = new OwnerDrawPropertyBag(); - if (node == null || node.propBag == null) return retval; + if (node == null || node.propBag == null) + return retval; // we only change colors if we're displaying things normally - if ((state & (NativeMethods.CDIS_SELECTED | NativeMethods.CDIS_GRAYED | NativeMethods.CDIS_HOT | NativeMethods.CDIS_DISABLED))==0) { + if ((state & (NativeMethods.CDIS_SELECTED | NativeMethods.CDIS_GRAYED | NativeMethods.CDIS_HOT | NativeMethods.CDIS_DISABLED)) == 0) + { retval.ForeColor = node.propBag.ForeColor; retval.BackColor = node.propBag.BackColor; } @@ -2602,8 +3007,8 @@ private unsafe bool WmShowToolTip(ref Message m) { NativeMethods.NMHDR* nmhdr = (NativeMethods.NMHDR*)m.LParam; IntPtr tooltipHandle = nmhdr->hwndFrom; - - + + NativeMethods.TV_HITTESTINFO tvhip = new NativeMethods.TV_HITTESTINFO(); Point pos = Cursor.Position; pos = PointToClient(pos); @@ -2611,10 +3016,11 @@ private unsafe bool WmShowToolTip(ref Message m) tvhip.pt_y = pos.Y; IntPtr hnode = UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TVM_HITTEST, 0, tvhip); - if (hnode != IntPtr.Zero && ((tvhip.flags & NativeMethods.TVHT_ONITEM) != 0)) { + if (hnode != IntPtr.Zero && ((tvhip.flags & NativeMethods.TVHT_ONITEM) != 0)) + { TreeNode tn = NodeFromHandle(hnode); - if (tn != null) + if (tn != null) { if (!ShowNodeToolTips) // default ToolTips { @@ -2633,25 +3039,30 @@ private unsafe bool WmShowToolTip(ref Message m) /// /// - private void WmNeedText(ref Message m) { - NativeMethods.TOOLTIPTEXT ttt = (NativeMethods.TOOLTIPTEXT) m.GetLParam(typeof(NativeMethods.TOOLTIPTEXT)); + private void WmNeedText(ref Message m) + { + NativeMethods.TOOLTIPTEXT ttt = (NativeMethods.TOOLTIPTEXT)m.GetLParam(typeof(NativeMethods.TOOLTIPTEXT)); string tipText = controlToolTipText; - + NativeMethods.TV_HITTESTINFO tvhip = new NativeMethods.TV_HITTESTINFO(); Point pos = Cursor.Position; pos = PointToClient(pos); tvhip.pt_x = pos.X; tvhip.pt_y = pos.Y; IntPtr hnode = UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TVM_HITTEST, 0, tvhip); - if (hnode != IntPtr.Zero && ((tvhip.flags & NativeMethods.TVHT_ONITEM) != 0)) { + if (hnode != IntPtr.Zero && ((tvhip.flags & NativeMethods.TVHT_ONITEM) != 0)) + { TreeNode tn = NodeFromHandle(hnode); - if (ShowNodeToolTips && tn != null && (!string.IsNullOrEmpty(tn.ToolTipText))) { + if (ShowNodeToolTips && tn != null && (!string.IsNullOrEmpty(tn.ToolTipText))) + { tipText = tn.ToolTipText; } - else if (tn != null && tn.Bounds.Right > this.Bounds.Right) { + else if (tn != null && tn.Bounds.Right > this.Bounds.Right) + { tipText = tn.Text; } - else { + else + { tipText = null; } } @@ -2660,26 +3071,31 @@ private void WmNeedText(ref Message m) { // RightToLeft reading order // - if (RightToLeft == RightToLeft.Yes) { + if (RightToLeft == RightToLeft.Yes) + { ttt.uFlags |= NativeMethods.TTF_RTLREADING; } Marshal.StructureToPtr(ttt, m.LParam, false); } - private unsafe void WmNotify(ref Message m) { - NativeMethods.NMHDR* nmhdr = (NativeMethods.NMHDR *)m.LParam; - + private unsafe void WmNotify(ref Message m) + { + NativeMethods.NMHDR* nmhdr = (NativeMethods.NMHDR*)m.LParam; + // Custom draw code is handled separately. // - if ((nmhdr->code == NativeMethods.NM_CUSTOMDRAW)) { + if ((nmhdr->code == NativeMethods.NM_CUSTOMDRAW)) + { CustomDraw(ref m); } - else { - + else + { + NativeMethods.NMTREEVIEW* nmtv = (NativeMethods.NMTREEVIEW*)m.LParam; - switch (nmtv->nmhdr.code) { + switch (nmtv->nmhdr.code) + { case NativeMethods.TVN_ITEMEXPANDING: m.Result = TvnExpanding(nmtv); break; @@ -2715,29 +3131,35 @@ private unsafe void WmNotify(ref Message m) { tvhip.pt_y = pos.Y; IntPtr hnode = UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TVM_HITTEST, 0, tvhip); if (nmtv->nmhdr.code != NativeMethods.NM_CLICK - || (tvhip.flags & NativeMethods.TVHT_ONITEM) != 0) { - button = nmtv->nmhdr.code == NativeMethods.NM_CLICK - ? MouseButtons.Left : MouseButtons.Right; + || (tvhip.flags & NativeMethods.TVHT_ONITEM) != 0) + { + button = nmtv->nmhdr.code == NativeMethods.NM_CLICK + ? MouseButtons.Left : MouseButtons.Right; } // The treeview's WndProc doesn't get the WM_LBUTTONUP messages when // LBUTTONUP happens on TVHT_ONITEM. This is a comctl quirk. // We work around that by calling OnMouseUp here. if (nmtv->nmhdr.code != NativeMethods.NM_CLICK - || (tvhip.flags & NativeMethods.TVHT_ONITEM) != 0 || FullRowSelect) { - if (hnode != IntPtr.Zero && !ValidationCancelled) { + || (tvhip.flags & NativeMethods.TVHT_ONITEM) != 0 || FullRowSelect) + { + if (hnode != IntPtr.Zero && !ValidationCancelled) + { OnNodeMouseClick(new TreeNodeMouseClickEventArgs(NodeFromHandle(hnode), button, 1, pos.X, pos.Y)); OnClick(new MouseEventArgs(button, 1, pos.X, pos.Y, 0)); OnMouseClick(new MouseEventArgs(button, 1, pos.X, pos.Y, 0)); } } - if (nmtv->nmhdr.code == NativeMethods.NM_RCLICK) { + if (nmtv->nmhdr.code == NativeMethods.NM_RCLICK) + { TreeNode treeNode = NodeFromHandle(hnode); - if (treeNode != null && (treeNode.ContextMenu != null || treeNode.ContextMenuStrip != null)) { + if (treeNode != null && (treeNode.ContextMenu != null || treeNode.ContextMenuStrip != null)) + { ShowContextMenu(treeNode); } - else { + else + { treeViewState[TREEVIEWSTATE_showTreeViewContextMenu] = true; SendMessage(Interop.WindowMessages.WM_CONTEXTMENU, Handle, SafeNativeMethods.GetMessagePos()); } @@ -2745,9 +3167,11 @@ private unsafe void WmNotify(ref Message m) { } - if (!treeViewState[TREEVIEWSTATE_mouseUpFired]) { + if (!treeViewState[TREEVIEWSTATE_mouseUpFired]) + { if (nmtv->nmhdr.code != NativeMethods.NM_CLICK - || (tvhip.flags & NativeMethods.TVHT_ONITEM) != 0) { + || (tvhip.flags & NativeMethods.TVHT_ONITEM) != 0) + { // The treeview's WndProc doesn't get the WM_LBUTTONUP messages when // LBUTTONUP happens on TVHT_ONITEM. This is a comctl quirk. // We work around that by calling OnMouseUp here. @@ -2764,27 +3188,29 @@ private unsafe void WmNotify(ref Message m) { /// /// Shows the context menu for the Treenode. /// - private void ShowContextMenu(TreeNode treeNode) { + private void ShowContextMenu(TreeNode treeNode) + { - if (treeNode.ContextMenu != null || treeNode.ContextMenuStrip != null) { + if (treeNode.ContextMenu != null || treeNode.ContextMenuStrip != null) + { ContextMenu contextMenu = treeNode.ContextMenu; ContextMenuStrip menu = treeNode.ContextMenuStrip; - + if (contextMenu != null) { NativeMethods.POINT pt = new NativeMethods.POINT(); UnsafeNativeMethods.GetCursorPos(pt); - + // Summary: the current window must be made the foreground window // before calling TrackPopupMenuEx, and a task switch must be // forced after the call. UnsafeNativeMethods.SetForegroundWindow(new HandleRef(this, this.Handle)); - contextMenu.OnPopup( EventArgs.Empty ); + contextMenu.OnPopup(EventArgs.Empty); SafeNativeMethods.TrackPopupMenuEx(new HandleRef(contextMenu, contextMenu.Handle), NativeMethods.TPM_VERTICAL, @@ -2815,11 +3241,14 @@ private void ContextMenuStripClosing(object sender, ToolStripDropDownClosingEven SendMessage(NativeMethods.TVM_SELECTITEM, NativeMethods.TVGN_DROPHILITE, null); } - private void WmPrint(ref Message m) { + private void WmPrint(ref Message m) + { base.WndProc(ref m); - if ((NativeMethods.PRF_NONCLIENT & (int)m.LParam) != 0 && Application.RenderWithVisualStyles && this.BorderStyle == BorderStyle.Fixed3D) { - using (Graphics g = Graphics.FromHdc(m.WParam)) { + if ((NativeMethods.PRF_NONCLIENT & (int)m.LParam) != 0 && Application.RenderWithVisualStyles && this.BorderStyle == BorderStyle.Fixed3D) + { + using (Graphics g = Graphics.FromHdc(m.WParam)) + { Rectangle rect = new Rectangle(0, 0, this.Size.Width - 1, this.Size.Height - 1); g.DrawRectangle(new Pen(VisualStyleInformation.TextControlBorder), rect); rect.Inflate(-1, -1); @@ -2830,8 +3259,10 @@ private void WmPrint(ref Message m) { /// /// - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { case Interop.WindowMessages.WM_WINDOWPOSCHANGING: case Interop.WindowMessages.WM_NCCALCSIZE: case Interop.WindowMessages.WM_WINDOWPOSCHANGED: @@ -2846,8 +3277,8 @@ protected override void WndProc(ref Message m) { { base.WndProc(ref m); } - break; - case Interop.WindowMessages.WM_HSCROLL: + break; + case Interop.WindowMessages.WM_HSCROLL: base.WndProc(ref m); if (DrawMode == TreeViewDrawMode.OwnerDrawAll) { @@ -2855,15 +3286,17 @@ protected override void WndProc(ref Message m) { } break; - case Interop.WindowMessages.WM_PRINT: - WmPrint(ref m); - break; + case Interop.WindowMessages.WM_PRINT: + WmPrint(ref m); + break; case NativeMethods.TVM_SETITEM: base.WndProc(ref m); - if (this.CheckBoxes) { - NativeMethods.TV_ITEM item = (NativeMethods.TV_ITEM) m.GetLParam(typeof(NativeMethods.TV_ITEM)); + if (this.CheckBoxes) + { + NativeMethods.TV_ITEM item = (NativeMethods.TV_ITEM)m.GetLParam(typeof(NativeMethods.TV_ITEM)); // Check for invalid node handle - if (item.hItem != IntPtr.Zero) { + if (item.hItem != IntPtr.Zero) + { NativeMethods.TV_ITEM item1 = new NativeMethods.TV_ITEM(); item1.mask = NativeMethods.TVIF_HANDLE | NativeMethods.TVIF_STATE; item1.hItem = item.hItem; @@ -2876,8 +3309,9 @@ protected override void WndProc(ref Message m) { } break; case Interop.WindowMessages.WM_NOTIFY: - NativeMethods.NMHDR nmhdr = (NativeMethods.NMHDR) m.GetLParam(typeof(NativeMethods.NMHDR)); - switch (nmhdr.code) { + NativeMethods.NMHDR nmhdr = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR)); + switch (nmhdr.code) + { case NativeMethods.TTN_GETDISPINFO: // MSDN: // Setting the max width has the added benefit of enabling multiline @@ -2891,22 +3325,22 @@ protected override void WndProc(ref Message m) { if (WmShowToolTip(ref m)) { m.Result = (IntPtr)1; - return; + return; } else { base.WndProc(ref m); break; } - + default: - base.WndProc(ref m); - break; + base.WndProc(ref m); + break; } break; case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_NOTIFY: - WmNotify(ref m); - break; + WmNotify(ref m); + break; case Interop.WindowMessages.WM_LBUTTONDBLCLK: WmMouseDown(ref m, MouseButtons.Left, 2); //just maintain state and fire double click.. in final mouseUp... @@ -2925,7 +3359,7 @@ protected override void WndProc(ref Message m) { } finally { - treeViewState[ TREEVIEWSTATE_ignoreSelects] = false; + treeViewState[TREEVIEWSTATE_ignoreSelects] = false; } //Always Reset the MouseupFired.... treeViewState[TREEVIEWSTATE_mouseUpFired] = false; @@ -2936,21 +3370,24 @@ protected override void WndProc(ref Message m) { // This gets around the TreeView behavior of temporarily moving the selection // highlight to a node when the user clicks on its checkbox. - if ((tvhip.flags & NativeMethods.TVHT_ONITEMSTATEICON) != 0) { + if ((tvhip.flags & NativeMethods.TVHT_ONITEMSTATEICON) != 0) + { //We donot pass the Message to the Control .. so fire MouseDowm ... OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); if (!ValidationCancelled && CheckBoxes) { TreeNode node = NodeFromHandle(hNodeMouseDown); bool eventReturn = TreeViewBeforeCheck(node, TreeViewAction.ByMouse); - if (!eventReturn && node != null) { + if (!eventReturn && node != null) + { node.CheckedInternal = !node.CheckedInternal; TreeViewAfterCheck(node, TreeViewAction.ByMouse); } } m.Result = IntPtr.Zero; } - else { + else + { WmMouseDown(ref m, MouseButtons.Left, 1); } downButton = MouseButtons.Left; @@ -2963,27 +3400,32 @@ protected override void WndProc(ref Message m) { IntPtr hnode = UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TVM_HITTEST, 0, tvhi); //Important for CheckBoxes ... click needs to be fired ... // - if(hnode != IntPtr.Zero) { - if (!ValidationCancelled && !treeViewState[TREEVIEWSTATE_doubleclickFired] & !treeViewState[TREEVIEWSTATE_mouseUpFired]) { + if (hnode != IntPtr.Zero) + { + if (!ValidationCancelled && !treeViewState[TREEVIEWSTATE_doubleclickFired] & !treeViewState[TREEVIEWSTATE_mouseUpFired]) + { //OnClick(EventArgs.Empty); //If the hit-tested node here is the same as the node we hit-tested //on mouse down then we will fire our OnNodeMoseClick event. - if (hnode == hNodeMouseDown) { + if (hnode == hNodeMouseDown) + { OnNodeMouseClick(new TreeNodeMouseClickEventArgs(NodeFromHandle(hnode), downButton, 1, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam))); } - + OnClick(new MouseEventArgs(downButton, 1, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); OnMouseClick(new MouseEventArgs(downButton, 1, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); } - if (treeViewState[TREEVIEWSTATE_doubleclickFired]) { + if (treeViewState[TREEVIEWSTATE_doubleclickFired]) + { treeViewState[TREEVIEWSTATE_doubleclickFired] = false; - if (!ValidationCancelled) { - //OnDoubleClick(EventArgs.Empty); - OnNodeMouseDoubleClick(new TreeNodeMouseClickEventArgs(NodeFromHandle(hnode), downButton, 2, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam))); - OnDoubleClick(new MouseEventArgs(downButton, 2, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); - OnMouseDoubleClick(new MouseEventArgs(downButton, 2, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); + if (!ValidationCancelled) + { + //OnDoubleClick(EventArgs.Empty); + OnNodeMouseDoubleClick(new TreeNodeMouseClickEventArgs(NodeFromHandle(hnode), downButton, 2, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam))); + OnDoubleClick(new MouseEventArgs(downButton, 2, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); + OnMouseDoubleClick(new MouseEventArgs(downButton, 2, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); } } } @@ -3031,7 +3473,7 @@ protected override void WndProc(ref Message m) { tvhit.pt_x = NativeMethods.Util.SignedLOWORD(m.LParam); tvhit.pt_y = NativeMethods.Util.SignedHIWORD(m.LParam); hNodeMouseDown = UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TVM_HITTEST, 0, tvhit); - + WmMouseDown(ref m, MouseButtons.Right, 1); downButton = MouseButtons.Right; break; @@ -3040,46 +3482,53 @@ protected override void WndProc(ref Message m) { base.WndProc(ref m); break; case Interop.WindowMessages.WM_SETFOCUS: - // If we get focus through the LBUttonDown .. we might have done the validation... - // so skip it.. - if (treeViewState[TREEVIEWSTATE_lastControlValidated]) - { + // If we get focus through the LBUttonDown .. we might have done the validation... + // so skip it.. + if (treeViewState[TREEVIEWSTATE_lastControlValidated]) + { treeViewState[TREEVIEWSTATE_lastControlValidated] = false; WmImeSetFocus(); DefWndProc(ref m); this.InvokeGotFocus(this, EventArgs.Empty); - } - else - { + } + else + { base.WndProc(ref m); - } - break; + } + break; case Interop.WindowMessages.WM_CONTEXTMENU: - if (treeViewState[TREEVIEWSTATE_showTreeViewContextMenu]) { + if (treeViewState[TREEVIEWSTATE_showTreeViewContextMenu]) + { treeViewState[TREEVIEWSTATE_showTreeViewContextMenu] = false; base.WndProc(ref m); } - else { + else + { // this is the Shift + F10 Case.... TreeNode treeNode = SelectedNode; - if (treeNode != null && (treeNode.ContextMenu != null || treeNode.ContextMenuStrip !=null)) { + if (treeNode != null && (treeNode.ContextMenu != null || treeNode.ContextMenuStrip != null)) + { Point client; - client = new Point(treeNode.Bounds.X , treeNode.Bounds.Y + treeNode.Bounds.Height / 2); + client = new Point(treeNode.Bounds.X, treeNode.Bounds.Y + treeNode.Bounds.Height / 2); // VisualStudio7 # 156, only show the context menu when clicked in the client area - if (ClientRectangle.Contains( client )) { - if (treeNode.ContextMenu != null) { + if (ClientRectangle.Contains(client)) + { + if (treeNode.ContextMenu != null) + { treeNode.ContextMenu.Show(this, client); } - else if (treeNode.ContextMenuStrip !=null) { - bool keyboardActivated = (unchecked((int)(long)m.LParam) == -1); + else if (treeNode.ContextMenuStrip != null) + { + bool keyboardActivated = (unchecked((int)(long)m.LParam) == -1); treeNode.ContextMenuStrip.ShowInternal(this, client, keyboardActivated); } } } - else { + else + { // in this case we dont have a selected node. The base // will ensure we're constrained to the client area. - base.WndProc (ref m); + base.WndProc(ref m); } } break; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewAction.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewAction.cs index 4613ce023da..2ec8dabdc91 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewAction.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewAction.cs @@ -23,12 +23,12 @@ public enum TreeViewAction /// The event was caused by a mouse click. /// ByMouse = 2, - + /// /// The tree node is collapsing. /// Collapse = 3, - + /// /// The tree node is expanding. /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewCancelEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewCancelEventArgs.cs index a22be26a668..f46383b5577 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewCancelEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewCancelEventArgs.cs @@ -4,7 +4,8 @@ -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; @@ -23,24 +24,30 @@ namespace System.Windows.Forms { /// /// /// - public class TreeViewCancelEventArgs : CancelEventArgs { + public class TreeViewCancelEventArgs : CancelEventArgs + { private TreeNode node; private TreeViewAction action; public TreeViewCancelEventArgs(TreeNode node, bool cancel, TreeViewAction action) - : base(cancel) { - this.node = node; + : base(cancel) + { + this.node = node; this.action = action; } - public TreeNode Node { - get { + public TreeNode Node + { + get + { return node; } } - - public TreeViewAction Action { - get { + + public TreeViewAction Action + { + get + { return action; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewEventArgs.cs index 1d7841ecf0a..438f505a89a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewEventArgs.cs @@ -4,7 +4,8 @@ -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; @@ -19,21 +20,26 @@ namespace System.Windows.Forms { /// Provides data for the , , , or event. /// /// - public class TreeViewEventArgs : EventArgs { + public class TreeViewEventArgs : EventArgs + { TreeNode node; TreeViewAction action = TreeViewAction.Unknown; - - public TreeViewEventArgs(TreeNode node) { + + public TreeViewEventArgs(TreeNode node) + { this.node = node; } - - public TreeViewEventArgs(TreeNode node, TreeViewAction action) { - this.node = node; + + public TreeViewEventArgs(TreeNode node, TreeViewAction action) + { + this.node = node; this.action = action; } - - public TreeNode Node { - get { + + public TreeNode Node + { + get + { return node; } } @@ -41,8 +47,10 @@ public TreeNode Node { /// /// An event specific action-flag. /// - public TreeViewAction Action { - get { + public TreeViewAction Action + { + get + { return action; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewHitTestInfo.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewHitTestInfo.cs index fb85af430d9..9d3af7cc857 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewHitTestInfo.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewHitTestInfo.cs @@ -2,17 +2,19 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; using System; - + /// /// /// Specifies the return value for HITTEST on treeview. /// /// - public class TreeViewHitTestInfo { + public class TreeViewHitTestInfo + { private TreeViewHitTestLocations loc; private TreeNode node; @@ -20,26 +22,31 @@ public class TreeViewHitTestInfo { /// /// Creates a TreeViewHitTestInfo instance. /// - public TreeViewHitTestInfo(TreeNode hitNode, TreeViewHitTestLocations hitLocation) { + public TreeViewHitTestInfo(TreeNode hitNode, TreeViewHitTestLocations hitLocation) + { this.node = hitNode; this.loc = hitLocation; } - + /// /// This gives the exact location returned by hit test on treeview. /// - public TreeViewHitTestLocations Location { - get { + public TreeViewHitTestLocations Location + { + get + { return loc; } } - + /// /// This gives the node returned by hit test on treeview. /// - public TreeNode Node { - get { + public TreeNode Node + { + get + { return node; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewHitTestLocation.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewHitTestLocation.cs index 7fad16f8ca4..a8123f966e9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewHitTestLocation.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewHitTestLocation.cs @@ -36,7 +36,7 @@ public enum TreeViewHitTestLocations /// /// AboveClientArea. /// - AboveClientArea = NativeMethods.TVHT_ABOVE, + AboveClientArea = NativeMethods.TVHT_ABOVE, /// /// BelowClientArea. @@ -56,7 +56,7 @@ public enum TreeViewHitTestLocations /// /// RightOfNode. /// - RightOfLabel = NativeMethods.TVHT_ONITEMRIGHT, + RightOfLabel = NativeMethods.TVHT_ONITEMRIGHT, /// /// StateImage. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewImageIndexConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewImageIndexConverter.cs index 215cab64e26..82cfff38701 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewImageIndexConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewImageIndexConverter.cs @@ -4,23 +4,27 @@ - -namespace System.Windows.Forms { + +namespace System.Windows.Forms +{ using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Collections.Specialized; - + /// /// TreeViewImageIndexConverter is a class that can be used to convert /// image index values one data type to another. /// - public class TreeViewImageIndexConverter : ImageIndexConverter { + public class TreeViewImageIndexConverter : ImageIndexConverter + { - protected override bool IncludeNoneAsStandardValue { - get { + protected override bool IncludeNoneAsStandardValue + { + get + { return false; } } @@ -30,19 +34,23 @@ protected override bool IncludeNoneAsStandardValue { /// Converts the given value object to a 32-bit signed integer object. /// /// - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + { string strValue = value as string; - if (strValue != null) { - - if (string.Compare(strValue, SR.toStringDefault, true, culture) == 0) { - return -1; - } - else if (string.Compare(strValue, SR.toStringNone, true, culture) == 0) { - return -2; - } + if (strValue != null) + { + + if (string.Compare(strValue, SR.toStringDefault, true, culture) == 0) + { + return -1; + } + else if (string.Compare(strValue, SR.toStringNone, true, culture) == 0) + { + return -2; + } } - return base.ConvertFrom(context, culture, value); + return base.ConvertFrom(context, culture, value); } @@ -53,18 +61,23 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) { + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == null) + { throw new ArgumentNullException(nameof(destinationType)); } - - if (destinationType == typeof(string) && value is int) { + + if (destinationType == typeof(string) && value is int) + { int intValue = (int)value; - if (intValue == -1) { + if (intValue == -1) + { return SR.toStringDefault; } - else if (intValue == -2) { + else if (intValue == -2) + { return SR.toStringNone; } } @@ -78,31 +91,39 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul /// will return null if the data type does not support a /// standard set of values. /// - public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { - if (context != null && context.Instance != null) { + public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) + { + if (context != null && context.Instance != null) + { object instance = context.Instance; - + PropertyDescriptor imageListProp = ImageListUtils.GetImageListProperty(context.PropertyDescriptor, ref instance); - while (instance != null && imageListProp == null) { + while (instance != null && imageListProp == null) + { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(instance); - foreach (PropertyDescriptor prop in props) { - if (typeof(ImageList).IsAssignableFrom(prop.PropertyType)) { + foreach (PropertyDescriptor prop in props) + { + if (typeof(ImageList).IsAssignableFrom(prop.PropertyType)) + { imageListProp = prop; break; } } - if (imageListProp == null) { + if (imageListProp == null) + { // We didn't find the image list in this component. See if the // component has a "parent" property. If so, walk the tree... // PropertyDescriptor parentProp = props[ParentImageListProperty]; - if (parentProp != null) { + if (parentProp != null) + { instance = parentProp.GetValue(instance); } - else { + else + { // Stick a fork in us, we're done. // instance = null; @@ -110,21 +131,24 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex } } - if (imageListProp != null) { + if (imageListProp != null) + { ImageList imageList = (ImageList)imageListProp.GetValue(instance); - if (imageList != null) { + if (imageList != null) + { // Create array to contain standard values // object[] values; - int nImages = imageList.Images.Count+2; + int nImages = imageList.Images.Count + 2; values = new object[nImages]; - values[nImages-2] = -1; - values[nImages-1] = -2; - + values[nImages - 2] = -1; + values[nImages - 1] = -2; + // Fill in the array // - for (int i = 0; i < nImages-2; i++) { + for (int i = 0; i < nImages - 2; i++) + { values[i] = i; } return new StandardValuesCollection(values); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewImageKeyConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewImageKeyConverter.cs index 2dc66e5c9c1..268df8b0b5d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewImageKeyConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewImageKeyConverter.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System.Collections; @@ -18,7 +19,8 @@ namespace System.Windows.Forms { /// ImageIndexConverter is a class that can be used to convert /// image index values one data type to another. /// - public class TreeViewImageKeyConverter : ImageKeyConverter { + public class TreeViewImageKeyConverter : ImageKeyConverter + { /// /// Converts the given object to another type. The most common types to convert @@ -27,22 +29,27 @@ public class TreeViewImageKeyConverter : ImageKeyConverter { /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - if (destinationType == null) { + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == null) + { throw new ArgumentNullException(nameof(destinationType)); } - - if (destinationType == typeof(string) && (value == null)) { + + if (destinationType == typeof(string) && (value == null)) + { return SR.toStringDefault; } - else { + else + { string strValue = value as string; - if (strValue != null && (strValue.Length == 0)) { + if (strValue != null && (strValue.Length == 0)) + { return SR.toStringDefault; } } - return base.ConvertTo(context, culture, value, destinationType); + return base.ConvertTo(context, culture, value, destinationType); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Triangle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Triangle.cs index 22982dfd88e..a8af7591537 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Triangle.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Triangle.cs @@ -2,11 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Diagnostics; using System; - + using System.Windows.Forms; using System.Drawing; using Microsoft.Win32; @@ -14,9 +15,10 @@ namespace System.Windows.Forms { /// /// This class fully encapsulates the painting logic for a triangle. (Used by DataGrid) /// - internal static class Triangle { + internal static class Triangle + { private const double TRI_HEIGHT_RATIO = 2.5; - private const double TRI_WIDTH_RATIO = 0.8; + private const double TRI_WIDTH_RATIO = 0.8; /* Commenting this overload out until someone actually needs it again... public static void Paint(Graphics g, Rectangle bounds, TriangleDirection dir, Brush backBr, Pen backPen) { @@ -54,17 +56,18 @@ private static Point[] BuildTrianglePoints(TriangleDirection dir, { Point[] points = new Point[3]; - int updnWidth =(int)(bounds.Width * TRI_WIDTH_RATIO); + int updnWidth = (int)(bounds.Width * TRI_WIDTH_RATIO); if (updnWidth % 2 == 1) updnWidth++; - int updnHeight =(int)Math.Ceiling((updnWidth/2) * TRI_HEIGHT_RATIO); + int updnHeight = (int)Math.Ceiling((updnWidth / 2) * TRI_HEIGHT_RATIO); - int lrWidth =(int)(bounds.Height * TRI_WIDTH_RATIO); + int lrWidth = (int)(bounds.Height * TRI_WIDTH_RATIO); if (lrWidth % 2 == 0) lrWidth++; - int lrHeight =(int)Math.Ceiling((lrWidth/2) * TRI_HEIGHT_RATIO); + int lrHeight = (int)Math.Ceiling((lrWidth / 2) * TRI_HEIGHT_RATIO); - switch (dir) { + switch (dir) + { case TriangleDirection.Up: { points[0] = new Point(0, updnHeight); @@ -100,32 +103,36 @@ private static Point[] BuildTrianglePoints(TriangleDirection dir, // we need to center our triangles into the bounds given. // NOTE: On the up/down case, the offsets are different! - switch (dir) { + switch (dir) + { case TriangleDirection.Up: case TriangleDirection.Down: OffsetPoints(points, - bounds.X +(bounds.Width - updnHeight)/2, - bounds.Y +(bounds.Height - updnWidth)/2); + bounds.X + (bounds.Width - updnHeight) / 2, + bounds.Y + (bounds.Height - updnWidth) / 2); break; case TriangleDirection.Left: case TriangleDirection.Right: OffsetPoints(points, - bounds.X +(bounds.Width - lrWidth)/2, - bounds.Y +(bounds.Height - lrHeight)/2); + bounds.X + (bounds.Width - lrWidth) / 2, + bounds.Y + (bounds.Height - lrHeight) / 2); break; } return points; } - private static void OffsetPoints(Point[] points, int xOffset, int yOffset) { - for (int i = 0; i < points.Length; i++) { + private static void OffsetPoints(Point[] points, int xOffset, int yOffset) + { + for (int i = 0; i < points.Length; i++) + { points[i].X += xOffset; points[i].Y += yOffset; } } } - internal enum TriangleDirection { + internal enum TriangleDirection + { Up, Down, Left, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/UICues.cs b/src/System.Windows.Forms/src/System/Windows/Forms/UICues.cs index 95b411f9f3b..9ce9055e238 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/UICues.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/UICues.cs @@ -14,26 +14,26 @@ public enum UICues /// Focus rectangles are shown after the change. /// ShowFocus = 0x01, - + /// /// Keyboard cues are underlined after the change. /// ShowKeyboard = 0x02, - + Shown = ShowFocus | ShowKeyboard, - + /// /// The state of the focus cues has changed. /// ChangeFocus = 0x04, - + /// /// The state of the keyboard cues has changed. /// ChangeKeyboard = 0x08, - + Changed = ChangeFocus | ChangeKeyboard, - + None = 0x00, } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/UICuesEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/UICuesEventArgs.cs index 7a08b6044c1..c461d270102 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/UICuesEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/UICuesEventArgs.cs @@ -18,27 +18,27 @@ public UICuesEventArgs(UICues uicues) { _uicues = uicues; } - + /// /// Focus rectangles are shown after the change. /// public bool ShowFocus => (_uicues & UICues.ShowFocus) != 0; - + /// /// Keyboard cues are underlined after the change. /// public bool ShowKeyboard => (_uicues & UICues.ShowKeyboard) != 0; - + /// /// The state of the focus cues has changed. /// public bool ChangeFocus => (_uicues & UICues.ChangeFocus) != 0; - + /// /// The state of the keyboard cues has changed. /// public bool ChangeKeyboard => (_uicues & UICues.ChangeKeyboard) != 0; - + public UICues Changed => (_uicues & UICues.Changed); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs index a53ebe247b7..f6a74b18139 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System.Runtime.Serialization.Formatters; using System.Threading; using System.Runtime.InteropServices; @@ -23,16 +24,17 @@ namespace System.Windows.Forms { Designer("System.Windows.Forms.Design.UpDownBaseDesigner, " + AssemblyRef.SystemDesign), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1012:AbstractTypesShouldNotHaveConstructors") // Shipped in Everett ] - public abstract class UpDownBase : ContainerControl { - - private const int DefaultWheelScrollLinesPerPage = 1; - private const int DefaultButtonsWidth = 16; - private const int DefaultControlWidth = 120; - private const int ThemedBorderWidth = 1; // width of custom border we draw when themed - private const BorderStyle DefaultBorderStyle = BorderStyle.Fixed3D; - private static readonly bool DefaultInterceptArrowKeys = true; - private const LeftRightAlignment DefaultUpDownAlign = LeftRightAlignment.Right; - private const int DefaultTimerInterval = 500; + public abstract class UpDownBase : ContainerControl + { + + private const int DefaultWheelScrollLinesPerPage = 1; + private const int DefaultButtonsWidth = 16; + private const int DefaultControlWidth = 120; + private const int ThemedBorderWidth = 1; // width of custom border we draw when themed + private const BorderStyle DefaultBorderStyle = BorderStyle.Fixed3D; + private static readonly bool DefaultInterceptArrowKeys = true; + private const LeftRightAlignment DefaultUpDownAlign = LeftRightAlignment.Right; + private const int DefaultTimerInterval = 500; //////////////////////////////////////////////////////////////////////// // Member variables @@ -77,8 +79,10 @@ public abstract class UpDownBase : ContainerControl { /// class. /// /// - public UpDownBase() { - if (DpiHelper.IsScalingRequired) { + public UpDownBase() + { + if (DpiHelper.IsScalingRequired) + { defaultButtonsWidth = LogicalToDeviceUnits(DefaultButtonsWidth); } @@ -95,7 +99,7 @@ public UpDownBase() { upDownButtons.Size = new Size(defaultButtonsWidth, PreferredHeight); upDownButtons.UpDown += new UpDownEventHandler(this.OnUpDown); - Controls.AddRange(new Control[] { upDownButtons, upDownEdit} ); + Controls.AddRange(new Control[] { upDownButtons, upDownEdit }); SetStyle(ControlStyles.Opaque | ControlStyles.FixedHeight | ControlStyles.ResizeRedraw, true); SetStyle(ControlStyles.StandardClick, false); @@ -112,11 +116,14 @@ public UpDownBase() { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public override bool AutoScroll { - get { + public override bool AutoScroll + { + get + { return false; } - set { + set + { // Don't allow AutoScroll to be set to anything } } @@ -126,11 +133,14 @@ public override bool AutoScroll { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - new public Size AutoScrollMargin { - get { + new public Size AutoScrollMargin + { + get + { return base.AutoScrollMargin; } - set { + set + { base.AutoScrollMargin = value; } } @@ -140,11 +150,14 @@ public override bool AutoScroll { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - new public Size AutoScrollMinSize { - get { + new public Size AutoScrollMinSize + { + get + { return base.AutoScrollMinSize; } - set { + set + { base.AutoScrollMinSize = value; } } @@ -173,18 +186,21 @@ public override bool AutoSize add => base.AutoSizeChanged += value; remove => base.AutoSizeChanged -= value; } - + /// /// /// Gets or sets the background color for the /// text box portion of the up-down control. /// /// - public override Color BackColor { - get { + public override Color BackColor + { + get + { return upDownEdit.BackColor; } - set { + set + { base.BackColor = value; // Don't remove this or you will break serialization. upDownEdit.BackColor = value; Invalidate(); @@ -194,17 +210,21 @@ public override Color BackColor { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { base.BackgroundImage = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged { + new public event EventHandler BackgroundImageChanged + { add => base.BackgroundImageChanged += value; remove => base.BackgroundImageChanged -= value; } @@ -212,17 +232,21 @@ public override Image BackgroundImage { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { base.BackgroundImageLayout = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { + new public event EventHandler BackgroundImageLayoutChanged + { add => base.BackgroundImageLayoutChanged += value; remove => base.BackgroundImageLayoutChanged -= value; } @@ -239,19 +263,23 @@ public override ImageLayout BackgroundImageLayout { DispId(NativeMethods.ActiveX.DISPID_BORDERSTYLE), SRDescription(nameof(SR.UpDownBaseBorderStyleDescr)) ] - public BorderStyle BorderStyle { - get { + public BorderStyle BorderStyle + { + get + { return borderStyle; } - set { + set + { //valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(BorderStyle)); } - if (borderStyle != value) { + if (borderStyle != value) + { borderStyle = value; RecreateHandle(); } @@ -264,33 +292,42 @@ public BorderStyle BorderStyle { /// property is being changed internally by its parent class. /// /// - protected bool ChangingText { - get { + protected bool ChangingText + { + get + { return changingText; } - set { + set + { changingText = value; } } /// /// - public override ContextMenu ContextMenu { - get { + public override ContextMenu ContextMenu + { + get + { return base.ContextMenu; } - set { + set + { base.ContextMenu = value; this.upDownEdit.ContextMenu = value; } } - public override ContextMenuStrip ContextMenuStrip { - get { + public override ContextMenuStrip ContextMenuStrip + { + get + { return base.ContextMenuStrip; } - set { + set + { base.ContextMenuStrip = value; this.upDownEdit.ContextMenuStrip = value; } @@ -305,13 +342,17 @@ public override ContextMenuStrip ContextMenuStrip { /// filled up with the basic info. /// /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.Style &= (~NativeMethods.WS_BORDER); - if (!Application.RenderWithVisualStyles) { - switch (borderStyle) { + if (!Application.RenderWithVisualStyles) + { + switch (borderStyle) + { case BorderStyle.Fixed3D: cp.ExStyle |= NativeMethods.WS_EX_CLIENTEDGE; break; @@ -328,8 +369,10 @@ protected override CreateParams CreateParams { /// 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. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(DefaultControlWidth, PreferredHeight); } } @@ -338,8 +381,10 @@ protected override Size DefaultSize { /// /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - new public DockPaddingEdges DockPadding { - get { + new public DockPaddingEdges DockPadding + { + get + { return base.DockPadding; } } @@ -352,8 +397,10 @@ protected override Size DefaultSize { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.ControlFocusedDescr)) ] - public override bool Focused { - get { + public override bool Focused + { + get + { return upDownEdit.Focused; } } @@ -363,11 +410,14 @@ public override bool Focused { /// Indicates the foreground color for the control. /// /// - public override Color ForeColor { - get { + public override Color ForeColor + { + get + { return upDownEdit.ForeColor; } - set { + set + { base.ForeColor = value; upDownEdit.ForeColor = value; } @@ -385,55 +435,66 @@ public override Color ForeColor { DefaultValue(true), SRDescription(nameof(SR.UpDownBaseInterceptArrowKeysDescr)) ] - public bool InterceptArrowKeys { + public bool InterceptArrowKeys + { - get { + get + { return interceptArrowKeys; } - set { + set + { interceptArrowKeys = value; } } - public override Size MaximumSize { + public override Size MaximumSize + { get { return base.MaximumSize; } - set { + set + { base.MaximumSize = new Size(value.Width, 0); } } - public override Size MinimumSize { + public override Size MinimumSize + { get { return base.MinimumSize; } - set { + set + { base.MinimumSize = new Size(value.Width, 0); } } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler MouseEnter { + public new event EventHandler MouseEnter + { add => base.MouseEnter += value; remove => base.MouseEnter -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler MouseLeave { + public new event EventHandler MouseLeave + { add => base.MouseLeave += value; remove => base.MouseLeave -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event EventHandler MouseHover { + public new event EventHandler MouseHover + { add => base.MouseHover += value; remove => base.MouseHover -= value; } /// [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - public new event MouseEventHandler MouseMove { + public new event MouseEventHandler MouseMove + { add => base.MouseMove += value; remove => base.MouseMove -= value; } @@ -450,16 +511,20 @@ public override Size MinimumSize { DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(nameof(SR.UpDownBasePreferredHeightDescr)) ] - public int PreferredHeight { - get { + public int PreferredHeight + { + get + { int height = FontHeight; // Adjust for the border style - if (borderStyle != BorderStyle.None) { + if (borderStyle != BorderStyle.None) + { height += SystemInformation.BorderSize.Height * 4 + 3; } - else { + else + { height += 3; } @@ -482,13 +547,16 @@ public int PreferredHeight { DefaultValue(false), SRDescription(nameof(SR.UpDownBaseReadOnlyDescr)) ] - public bool ReadOnly { + public bool ReadOnly + { - get { + get + { return upDownEdit.ReadOnly; } - set { + set + { upDownEdit.ReadOnly = value; } } @@ -502,12 +570,15 @@ public bool ReadOnly { [ Localizable(true) ] - public override string Text { - get { + public override string Text + { + get + { return upDownEdit.Text; } - set { + set + { upDownEdit.Text = value; // The text changed event will at this point be triggered. // After returning, the value of UserEdit will reflect @@ -522,7 +593,8 @@ public override string Text { // never fires. ChangingText should always be false on exit from // this property. - if (UserEdit) { + if (UserEdit) + { ValidateEditText(); } } @@ -541,11 +613,14 @@ public override string Text { DefaultValue(HorizontalAlignment.Left), SRDescription(nameof(SR.UpDownBaseTextAlignDescr)) ] - public HorizontalAlignment TextAlign { - get { + public HorizontalAlignment TextAlign + { + get + { return upDownEdit.TextAlign; } - set { + set + { //valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)HorizontalAlignment.Left, (int)HorizontalAlignment.Center)) { @@ -555,8 +630,10 @@ public HorizontalAlignment TextAlign { } } - internal TextBox TextBox { - get { + internal TextBox TextBox + { + get + { return upDownEdit; } } @@ -575,20 +652,24 @@ internal TextBox TextBox { DefaultValue(LeftRightAlignment.Right), SRDescription(nameof(SR.UpDownBaseAlignmentDescr)) ] - public LeftRightAlignment UpDownAlign { + public LeftRightAlignment UpDownAlign + { - get { + get + { return upDownAlign; } - set { + set + { //valid values are 0x0 to 0x1 if (!ClientUtils.IsEnumValid(value, (int)value, (int)LeftRightAlignment.Left, (int)LeftRightAlignment.Right)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(LeftRightAlignment)); } - if (upDownAlign != value) { + if (upDownAlign != value) + { upDownAlign = value; PositionControls(); @@ -597,8 +678,10 @@ public LeftRightAlignment UpDownAlign { } } - internal UpDownButtons UpDownButtonsInternal { - get { + internal UpDownButtons UpDownButtonsInternal + { + get + { return upDownButtons; } } @@ -610,12 +693,15 @@ internal UpDownButtons UpDownButtonsInternal { /// user. /// /// - protected bool UserEdit { - get { + protected bool UserEdit + { + get + { return userEdit; } - set { + set + { userEdit = value; } } @@ -625,7 +711,7 @@ protected bool UserEdit { // Methods // //////////////////////////////////////////////////////////////////////// - + /// /// @@ -637,8 +723,9 @@ protected bool UserEdit { // GetPreferredSize and SetBoundsCore call this method to allow controls to self impose // constraints on their size. - internal override Rectangle ApplyBoundsConstraints(int suggestedX, int suggestedY, int proposedWidth, int proposedHeight) { - return base.ApplyBoundsConstraints(suggestedX,suggestedY, proposedWidth, PreferredHeight); + internal override Rectangle ApplyBoundsConstraints(int suggestedX, int suggestedY, int proposedWidth, int proposedHeight) + { + return base.ApplyBoundsConstraints(suggestedX, suggestedY, proposedWidth, PreferredHeight); } /// @@ -646,8 +733,10 @@ internal override Rectangle ApplyBoundsConstraints(int suggestedX, int suggested /// /// The base name. /// The accessible name. - internal string GetAccessibleName(string baseName) { - if (baseName == null) { + internal string GetAccessibleName(string baseName) + { + if (baseName == null) + { return SR.SpinnerAccessibleName; } @@ -661,7 +750,8 @@ internal string GetAccessibleName(string baseName) { /// Application opts-in into the Per-monitor V2 support, targets .NETFX 4.7 and has /// EnableDpiChangedMessageHandling config switch turned on. /// - protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) { + protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) + { base.RescaleConstantsForDpi(deviceDpiOld, deviceDpiNew); defaultButtonsWidth = LogicalToDeviceUnits(DefaultButtonsWidth); upDownButtons.Width = defaultButtonsWidth; @@ -671,7 +761,8 @@ protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNe /// When overridden in a derived class, raises the Changed event. /// event. /// - protected virtual void OnChanged(object source, EventArgs e) { + protected virtual void OnChanged(object source, EventArgs e) + { } /// @@ -701,12 +792,15 @@ protected override void OnHandleDestroyed(EventArgs e) /// Handles painting the buttons on the control. /// /// - protected override void OnPaint(PaintEventArgs e) { + protected override void OnPaint(PaintEventArgs e) + { base.OnPaint(e); - + Rectangle editBounds = upDownEdit.Bounds; - if (Application.RenderWithVisualStyles) { - if (borderStyle != BorderStyle.None) { + if (Application.RenderWithVisualStyles) + { + if (borderStyle != BorderStyle.None) + { Rectangle bounds = ClientRectangle; Rectangle clipBounds = e.ClipRectangle; @@ -726,7 +820,8 @@ protected override void OnPaint(PaintEventArgs e) { vsr.DrawBackground(e.Graphics, bounds, clipRight, HandleInternal); vsr.DrawBackground(e.Graphics, bounds, clipBottom, HandleInternal); // Draw rectangle around edit control with background color - using (Pen pen = new Pen(BackColor)) { + using (Pen pen = new Pen(BackColor)) + { Rectangle backRect = editBounds; backRect.X--; backRect.Y--; @@ -736,7 +831,8 @@ protected override void OnPaint(PaintEventArgs e) { } } } - else { + else + { // Draw rectangle around edit control with background color using (Pen pen = new Pen(BackColor, Enabled ? 2 : 1)) { @@ -752,7 +848,8 @@ protected override void OnPaint(PaintEventArgs e) { e.Graphics.DrawRectangle(pen, backRect); } } - if (!Enabled && BorderStyle != BorderStyle.None && !upDownEdit.ShouldSerializeBackColor()) { + if (!Enabled && BorderStyle != BorderStyle.None && !upDownEdit.ShouldSerializeBackColor()) + { //draws a grayed rectangled around the upDownEdit, since otherwise we will have a white //border around the upDownEdit, which is inconsistent with Windows' behavior //we only want to do this when BackColor is not serialized, since otherwise @@ -766,18 +863,22 @@ protected override void OnPaint(PaintEventArgs e) { /// Raises the /// event. /// - protected virtual void OnTextBoxKeyDown(object source, KeyEventArgs e) { + protected virtual void OnTextBoxKeyDown(object source, KeyEventArgs e) + { this.OnKeyDown(e); - if (interceptArrowKeys) { + if (interceptArrowKeys) + { // Intercept up arrow - if (e.KeyData == Keys.Up) { + if (e.KeyData == Keys.Up) + { UpButton(); e.Handled = true; } // Intercept down arrow - else if (e.KeyData == Keys.Down) { + else if (e.KeyData == Keys.Down) + { DownButton(); e.Handled = true; } @@ -785,7 +886,8 @@ protected virtual void OnTextBoxKeyDown(object source, KeyEventArgs e) { // Perform text validation if ENTER is pressed // - if (e.KeyCode == Keys.Return && UserEdit) { + if (e.KeyCode == Keys.Return && UserEdit) + { ValidateEditText(); } } @@ -794,7 +896,8 @@ protected virtual void OnTextBoxKeyDown(object source, KeyEventArgs e) { /// Raises the /// event. /// - protected virtual void OnTextBoxKeyPress(object source, KeyPressEventArgs e) { + protected virtual void OnTextBoxKeyPress(object source, KeyPressEventArgs e) + { this.OnKeyPress(e); } @@ -802,8 +905,10 @@ protected virtual void OnTextBoxKeyPress(object source, KeyPressEventArgs e) { /// /// Raises the event. /// - protected virtual void OnTextBoxLostFocus(object source, EventArgs e) { - if (UserEdit) { + protected virtual void OnTextBoxLostFocus(object source, EventArgs e) + { + if (UserEdit) + { ValidateEditText(); } } @@ -811,7 +916,8 @@ protected virtual void OnTextBoxLostFocus(object source, EventArgs e) { /// /// Raises the event. /// - protected virtual void OnTextBoxResize(object source, EventArgs e) { + protected virtual void OnTextBoxResize(object source, EventArgs e) + { this.Height = PreferredHeight; PositionControls(); } @@ -820,12 +926,15 @@ protected virtual void OnTextBoxResize(object source, EventArgs e) { /// Raises the TextBoxTextChanged event. /// event. /// - protected virtual void OnTextBoxTextChanged(object source, EventArgs e) { - if (changingText) { + protected virtual void OnTextBoxTextChanged(object source, EventArgs e) + { + if (changingText) + { Debug.Assert(UserEdit == false, "OnTextBoxTextChanged() - UserEdit == true"); ChangingText = false; } - else { + else + { UserEdit = true; } @@ -836,17 +945,21 @@ protected virtual void OnTextBoxTextChanged(object source, EventArgs e) { /// /// Called from the UpDownButtons member. Provided for derived controls to have a finer way to handle the event. /// - internal virtual void OnStartTimer() { + internal virtual void OnStartTimer() + { } - internal virtual void OnStopTimer() { + internal virtual void OnStopTimer() + { } /// /// Raises the event. /// - protected override void OnMouseDown(MouseEventArgs e) { - if (e.Clicks == 2 && e.Button == MouseButtons.Left) { + protected override void OnMouseDown(MouseEventArgs e) + { + if (e.Clicks == 2 && e.Button == MouseButtons.Left) + { doubleClickFired = true; } @@ -859,15 +972,20 @@ protected override void OnMouseDown(MouseEventArgs e) { /// /// /// - protected override void OnMouseUp(MouseEventArgs mevent) { - if (mevent.Button == MouseButtons.Left) { + protected override void OnMouseUp(MouseEventArgs mevent) + { + if (mevent.Button == MouseButtons.Left) + { Point pt = PointToScreen(new Point(mevent.X, mevent.Y)); - if (UnsafeNativeMethods.WindowFromPoint(pt.X, pt.Y) == Handle && !ValidationCancelled) { - if (!doubleClickFired) { + if (UnsafeNativeMethods.WindowFromPoint(pt.X, pt.Y) == Handle && !ValidationCancelled) + { + if (!doubleClickFired) + { OnClick(mevent); OnMouseClick(mevent); } - else { + else + { doubleClickFired = false; OnDoubleClick(mevent); OnMouseDoubleClick(mevent); @@ -881,22 +999,27 @@ protected override void OnMouseUp(MouseEventArgs mevent) { /// /// Raises the event. /// - protected override void OnMouseWheel(MouseEventArgs e) { + protected override void OnMouseWheel(MouseEventArgs e) + { base.OnMouseWheel(e); HandledMouseEventArgs hme = e as HandledMouseEventArgs; - if (hme != null) { - if (hme.Handled) { - return; - } - hme.Handled = true; + if (hme != null) + { + if (hme.Handled) + { + return; + } + hme.Handled = true; } - if ((ModifierKeys & (Keys.Shift | Keys.Alt)) != 0 || MouseButtons != MouseButtons.None) { + if ((ModifierKeys & (Keys.Shift | Keys.Alt)) != 0 || MouseButtons != MouseButtons.None) + { return; // Do not scroll when Shift or Alt key is down, or when a mouse button is down. } int wheelScrollLines = SystemInformation.MouseWheelScrollLines; - if (wheelScrollLines == 0) { + if (wheelScrollLines == 0) + { return; // Do not scroll when the user system setting is 0 lines per notch } @@ -907,30 +1030,36 @@ protected override void OnMouseWheel(MouseEventArgs e) { float partialNotches; partialNotches = (float)this.wheelDelta / (float)NativeMethods.WHEEL_DELTA; - if (wheelScrollLines == -1) { - wheelScrollLines = DefaultWheelScrollLinesPerPage; + if (wheelScrollLines == -1) + { + wheelScrollLines = DefaultWheelScrollLinesPerPage; } // Evaluate number of bands to scroll int scrollBands = (int)((float)wheelScrollLines * partialNotches); - if (scrollBands != 0) { - int absScrollBands; - if (scrollBands > 0) { - absScrollBands = scrollBands; - while (absScrollBands > 0) { - UpButton(); - absScrollBands--; - } - this.wheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); - } - else { - absScrollBands = -scrollBands; - while (absScrollBands > 0) { - DownButton(); - absScrollBands--; - } - this.wheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); - } + if (scrollBands != 0) + { + int absScrollBands; + if (scrollBands > 0) + { + absScrollBands = scrollBands; + while (absScrollBands > 0) + { + UpButton(); + absScrollBands--; + } + this.wheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); + } + else + { + absScrollBands = -scrollBands; + while (absScrollBands > 0) + { + DownButton(); + absScrollBands--; + } + this.wheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); + } } } @@ -939,7 +1068,8 @@ protected override void OnMouseWheel(MouseEventArgs e) { /// Handle the layout event. The size of the upDownEdit control, and the /// position of the UpDown control must be modified. /// - protected override void OnLayout(LayoutEventArgs e) { + protected override void OnLayout(LayoutEventArgs e) + { PositionControls(); base.OnLayout(e); @@ -950,7 +1080,8 @@ protected override void OnLayout(LayoutEventArgs e) { /// Raises the FontChanged event. /// /// - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { // Clear the font height cache FontHeight = -1; @@ -966,7 +1097,8 @@ protected override void OnFontChanged(EventArgs e) { /// the updown buttons in the child updown control. /// /// - private void OnUpDown(object source, UpDownEventArgs e) { + private void OnUpDown(object source, UpDownEventArgs e) + { // Modify the value if (e.ButtonID == (int)ButtonID.Up) UpButton(); @@ -978,14 +1110,15 @@ private void OnUpDown(object source, UpDownEventArgs e) { /// Calculates the size and position of the upDownEdit control and /// the updown buttons. /// - private void PositionControls() { - Rectangle upDownEditBounds = Rectangle.Empty, + private void PositionControls() + { + Rectangle upDownEditBounds = Rectangle.Empty, upDownButtonsBounds = Rectangle.Empty; - Rectangle clientArea = new Rectangle(Point.Empty, ClientSize); - int totalClientWidth = clientArea.Width; - bool themed = Application.RenderWithVisualStyles; - BorderStyle borderStyle = BorderStyle; + Rectangle clientArea = new Rectangle(Point.Empty, ClientSize); + int totalClientWidth = clientArea.Width; + bool themed = Application.RenderWithVisualStyles; + BorderStyle borderStyle = BorderStyle; // determine how much to squish in - Fixed3d and FixedSingle have 2PX border @@ -994,22 +1127,25 @@ private void PositionControls() { // Reposition and resize the upDownEdit control // - if (upDownEdit != null) { + if (upDownEdit != null) + { upDownEditBounds = clientArea; upDownEditBounds.Size = new Size(clientArea.Width - defaultButtonsWidth, clientArea.Height); } // Reposition and resize the updown buttons // - if (upDownButtons != null) { - int borderFixup = (themed) ? 1: 2; - if (borderStyle == BorderStyle.None) { + if (upDownButtons != null) + { + int borderFixup = (themed) ? 1 : 2; + if (borderStyle == BorderStyle.None) + { borderFixup = 0; } - upDownButtonsBounds = new Rectangle(/*x*/clientArea.Right - defaultButtonsWidth+borderFixup, - /*y*/clientArea.Top-borderFixup, + upDownButtonsBounds = new Rectangle(/*x*/clientArea.Right - defaultButtonsWidth + borderFixup, + /*y*/clientArea.Top - borderFixup, /*w*/defaultButtonsWidth, - /*h*/clientArea.Height+(borderFixup*2)); + /*h*/clientArea.Height + (borderFixup * 2)); } // Right to left translation @@ -1017,22 +1153,25 @@ private void PositionControls() { updownAlign = RtlTranslateLeftRight(updownAlign); // left/right updown align translation - if (updownAlign == LeftRightAlignment.Left) { + if (updownAlign == LeftRightAlignment.Left) + { // if the buttons are aligned to the left, swap position of text box/buttons upDownButtonsBounds.X = totalClientWidth - upDownButtonsBounds.Right; upDownEditBounds.X = totalClientWidth - upDownEditBounds.Right; } // apply locations - if (upDownEdit != null) { - upDownEdit.Bounds = upDownEditBounds; + if (upDownEdit != null) + { + upDownEdit.Bounds = upDownEditBounds; } - if (upDownButtons != null) { + if (upDownButtons != null) + { upDownButtons.Bounds = upDownButtonsBounds; upDownButtons.Invalidate(); } - } + } /// /// @@ -1040,7 +1179,8 @@ private void PositionControls() { /// text in the up-down control. /// /// - public void Select(int start, int length) { + public void Select(int start, int length) + { upDownEdit.Select(start, length); } @@ -1048,13 +1188,15 @@ public void Select(int start, int length) { /// /// Child controls run their /// - private MouseEventArgs TranslateMouseEvent(Control child, MouseEventArgs e) { - if (child != null && IsHandleCreated) { + private MouseEventArgs TranslateMouseEvent(Control child, MouseEventArgs e) + { + if (child != null && IsHandleCreated) + { // same control as PointToClient or PointToScreen, just // with two specific controls in mind. NativeMethods.POINT point = new NativeMethods.POINT(e.X, e.Y); UnsafeNativeMethods.MapWindowPoints(new HandleRef(child, child.Handle), new HandleRef(this, Handle), point, 1); - return new MouseEventArgs(e.Button, e.Clicks, point.x, point.y , e.Delta); + return new MouseEventArgs(e.Button, e.Clicks, point.x, point.y, e.Delta); } return e; } @@ -1073,9 +1215,11 @@ private MouseEventArgs TranslateMouseEvent(Control child, MouseEventArgs e) { /// /// protected abstract void UpdateEditText(); - - private void UserPreferenceChanged(object sender, UserPreferenceChangedEventArgs pref) { - if (pref.Category == UserPreferenceCategory.Locale) { + + private void UserPreferenceChanged(object sender, UserPreferenceChangedEventArgs pref) + { + if (pref.Category == UserPreferenceCategory.Locale) + { UpdateEditText(); } } @@ -1086,7 +1230,8 @@ private void UserPreferenceChanged(object sender, UserPreferenceChangedEventArgs /// derived class, validates the text displayed in the up-down control. /// /// - protected virtual void ValidateEditText() { + protected virtual void ValidateEditText() + { } /// @@ -1097,16 +1242,21 @@ protected override void WndProc(ref Message m) switch (m.Msg) { case Interop.WindowMessages.WM_SETFOCUS: - if (!HostedInWin32DialogManager) { - if (ActiveControl == null) { + if (!HostedInWin32DialogManager) + { + if (ActiveControl == null) + { SetActiveControl(TextBox); } - else { + else + { FocusActiveControlInternal(); } } - else { - if (TextBox.CanFocus){ + else + { + if (TextBox.CanFocus) + { UnsafeNativeMethods.SetFocus(new HandleRef(TextBox, TextBox.Handle)); } base.WndProc(ref m); @@ -1124,12 +1274,14 @@ protected override void WndProc(ref Message m) /// /// This Function sets the ToolTip for this composite control. /// - internal void SetToolTip(ToolTip toolTip, string caption) { - toolTip.SetToolTip(this.upDownEdit , caption); - toolTip.SetToolTip(this.upDownButtons , caption); + internal void SetToolTip(ToolTip toolTip, string caption) + { + toolTip.SetToolTip(this.upDownEdit, caption); + toolTip.SetToolTip(this.upDownButtons, caption); } - internal class UpDownEdit : TextBox{ + internal class UpDownEdit : TextBox + { ///////////////////////////////////////////////////////////////////// // Member variables // @@ -1144,7 +1296,8 @@ internal class UpDownEdit : TextBox{ ///////////////////////////////////////////////////////////////////// internal UpDownEdit(UpDownBase parent) - : base() { + : base() + { SetStyle(ControlStyles.FixedHeight | ControlStyles.FixedWidth, true); @@ -1154,25 +1307,32 @@ internal UpDownEdit(UpDownBase parent) this.parent = parent; } - public override string Text { - get { + public override string Text + { + get + { return base.Text; } - set { + set + { bool valueChanged = (value != base.Text); - base.Text = value; - if (valueChanged) { + base.Text = value; + if (valueChanged) + { AccessibilityNotifyClients(AccessibleEvents.NameChange, -1); } } } - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new UpDownEditAccessibleObject(this, parent); } - protected override void OnMouseDown(MouseEventArgs e) { - if (e.Clicks == 2 && e.Button == MouseButtons.Left) { + protected override void OnMouseDown(MouseEventArgs e) + { + if (e.Clicks == 2 && e.Button == MouseButtons.Left) + { doubleClickFired = true; } parent.OnMouseDown(parent.TranslateMouseEvent(this, e)); @@ -1183,19 +1343,24 @@ protected override void OnMouseDown(MouseEventArgs e) { /// Handles detecting when the mouse button is released. /// /// - protected override void OnMouseUp(MouseEventArgs e) { + protected override void OnMouseUp(MouseEventArgs e) + { - Point pt = new Point(e.X,e.Y); + Point pt = new Point(e.X, e.Y); pt = PointToScreen(pt); MouseEventArgs me = parent.TranslateMouseEvent(this, e); - if (e.Button == MouseButtons.Left) { - if (!parent.ValidationCancelled && UnsafeNativeMethods.WindowFromPoint(pt.X, pt.Y) == Handle) { - if (!doubleClickFired) { + if (e.Button == MouseButtons.Left) + { + if (!parent.ValidationCancelled && UnsafeNativeMethods.WindowFromPoint(pt.X, pt.Y) == Handle) + { + if (!doubleClickFired) + { parent.OnClick(me); parent.OnMouseClick(me); } - else { + else + { doubleClickFired = false; parent.OnDoubleClick(me); parent.OnMouseDoubleClick(me); @@ -1207,12 +1372,15 @@ protected override void OnMouseUp(MouseEventArgs e) { parent.OnMouseUp(me); } - internal override void WmContextMenu(ref Message m) { + internal override void WmContextMenu(ref Message m) + { // Want to make the SourceControl to be the UpDownBase, not the Edit. - if (ContextMenu == null && ContextMenuStrip != null) { + if (ContextMenu == null && ContextMenuStrip != null) + { WmContextMenu(ref m, parent); } - else { + else + { WmContextMenu(ref m, this); } } @@ -1222,16 +1390,19 @@ internal override void WmContextMenu(ref Message m) { /// Raises the /// event. /// - protected override void OnKeyUp(KeyEventArgs e) { + protected override void OnKeyUp(KeyEventArgs e) + { parent.OnKeyUp(e); } - protected override void OnGotFocus(EventArgs e) { + protected override void OnGotFocus(EventArgs e) + { parent.SetActiveControl(this); parent.InvokeGotFocus(parent, e); } - protected override void OnLostFocus(EventArgs e) { + protected override void OnLostFocus(EventArgs e) + { parent.InvokeLostFocus(parent, e); } @@ -1244,24 +1415,31 @@ protected override void OnLostFocus(EventArgs e) { // Create our own accessibility object to map the accessible name // back to our parent. They should track. - internal class UpDownEditAccessibleObject : ControlAccessibleObject { + internal class UpDownEditAccessibleObject : ControlAccessibleObject + { UpDownBase parent; - public UpDownEditAccessibleObject(UpDownEdit owner, UpDownBase parent) : base(owner) { + public UpDownEditAccessibleObject(UpDownEdit owner, UpDownBase parent) : base(owner) + { this.parent = parent; } - public override string Name { - get { + public override string Name + { + get + { return parent.AccessibilityObject.Name; } - set { + set + { parent.AccessibilityObject.Name = value; } } - public override string KeyboardShortcut { - get { + public override string KeyboardShortcut + { + get + { return parent.AccessibilityObject.KeyboardShortcut; } } @@ -1278,7 +1456,8 @@ public override string KeyboardShortcut { /// sends UpDownEventArgss to the parent UpDownBase class when a button is pressed, /// or when the acceleration determines that another event should be generated. /// - internal class UpDownButtons : Control { + internal class UpDownButtons : Control + { // ///////////////////////////////////////////////////////////////////// @@ -1310,7 +1489,8 @@ internal class UpDownButtons : Control { internal UpDownButtons(UpDownBase parent) - : base() { + : base() + { SetStyle(ControlStyles.Opaque | ControlStyles.FixedHeight | ControlStyles.FixedWidth, true); @@ -1330,7 +1510,8 @@ internal UpDownButtons(UpDownBase parent) /// /// Adds a handler for the updown button event. /// - public event UpDownEventHandler UpDown { + public event UpDownEventHandler UpDown + { add => upDownEventHandler += value; remove => upDownEventHandler -= value; } @@ -1338,11 +1519,13 @@ public event UpDownEventHandler UpDown { // Called when the mouse button is pressed - we need to start // spinning the value of the updown. // - private void BeginButtonPress(MouseEventArgs e) { + private void BeginButtonPress(MouseEventArgs e) + { int half_height = Size.Height / 2; - if (e.Y < half_height) { + if (e.Y < half_height) + { // Up button // @@ -1350,7 +1533,8 @@ private void BeginButtonPress(MouseEventArgs e) { Invalidate(); } - else { + else + { // Down button // @@ -1371,14 +1555,16 @@ private void BeginButtonPress(MouseEventArgs e) { StartTimer(); } - protected override AccessibleObject CreateAccessibilityInstance() { + protected override AccessibleObject CreateAccessibilityInstance() + { return new UpDownButtonsAccessibleObject(this); } // Called when the mouse button is released - we need to stop // spinning the value of the updown. // - private void EndButtonPress() { + private void EndButtonPress() + { pushed = ButtonID.None; captured = ButtonID.None; @@ -1401,7 +1587,8 @@ private void EndButtonPress() { /// for repeated updown events. /// /// - protected override void OnMouseDown(MouseEventArgs e) { + protected override void OnMouseDown(MouseEventArgs e) + { // Begin spinning the value // @@ -1409,10 +1596,12 @@ protected override void OnMouseDown(MouseEventArgs e) { // this.parent.Focus(); - if (!parent.ValidationCancelled && e.Button == MouseButtons.Left) { + if (!parent.ValidationCancelled && e.Button == MouseButtons.Left) + { BeginButtonPress(e); } - if (e.Clicks == 2 && e.Button == MouseButtons.Left) { + if (e.Clicks == 2 && e.Button == MouseButtons.Left) + { doubleClickFired = true; } // At no stage should a button be pushed, and the mouse @@ -1429,32 +1618,37 @@ protected override void OnMouseDown(MouseEventArgs e) { /// Handles detecting mouse movement. /// /// - protected override void OnMouseMove(MouseEventArgs e) { + protected override void OnMouseMove(MouseEventArgs e) + { // If the mouse is captured by the buttons (i.e. an updown button // was pushed, and the mouse button has not yet been released), // determine the new state of the buttons depending on where // the mouse pointer has moved. - if (Capture) { + if (Capture) + { // Determine button area Rectangle rect = ClientRectangle; rect.Height /= 2; - if (captured == ButtonID.Down) { + if (captured == ButtonID.Down) + { rect.Y += rect.Height; } // Test if the mouse has moved outside the button area - if (rect.Contains(e.X, e.Y)) { + if (rect.Contains(e.X, e.Y)) + { // Inside button // Repush the button if necessary - if (pushed != captured) { + if (pushed != captured) + { // Restart the timer StartTimer(); @@ -1464,14 +1658,16 @@ protected override void OnMouseMove(MouseEventArgs e) { } } - else { + else + { // Outside button // Retain the capture, but pop the button up whilst // the mouse remains outside the button and the // mouse button remains pressed. - if (pushed != ButtonID.None) { + if (pushed != ButtonID.None) + { // Stop the timer for updown events StopTimer(); @@ -1488,11 +1684,13 @@ protected override void OnMouseMove(MouseEventArgs e) { rectDown.Y += rectDown.Height / 2; //Check if the mouse is on the upper or lower button. Note that it could be in neither. - if (rectUp.Contains(e.X, e.Y)) { + if (rectUp.Contains(e.X, e.Y)) + { mouseOver = ButtonID.Up; Invalidate(); } - else if (rectDown.Contains(e.X, e.Y)) { + else if (rectDown.Contains(e.X, e.Y)) + { mouseOver = ButtonID.Down; Invalidate(); } @@ -1510,9 +1708,11 @@ protected override void OnMouseMove(MouseEventArgs e) { /// Handles detecting when the mouse button is released. /// /// - protected override void OnMouseUp(MouseEventArgs e) { + protected override void OnMouseUp(MouseEventArgs e) + { - if (!parent.ValidationCancelled && e.Button == MouseButtons.Left) { + if (!parent.ValidationCancelled && e.Button == MouseButtons.Left) + { EndButtonPress(); } @@ -1521,16 +1721,20 @@ protected override void OnMouseUp(MouseEventArgs e) { Debug.Assert(!(pushed != ButtonID.None && captured == ButtonID.None), "Invalid button pushed/captured combination"); - Point pt = new Point(e.X,e.Y); + Point pt = new Point(e.X, e.Y); pt = PointToScreen(pt); MouseEventArgs me = parent.TranslateMouseEvent(this, e); - if (e.Button == MouseButtons.Left) { - if (!parent.ValidationCancelled && UnsafeNativeMethods.WindowFromPoint(pt.X, pt.Y) == Handle) { - if (!doubleClickFired) { + if (e.Button == MouseButtons.Left) + { + if (!parent.ValidationCancelled && UnsafeNativeMethods.WindowFromPoint(pt.X, pt.Y) == Handle) + { + if (!doubleClickFired) + { this.parent.OnClick(me); } - else { + else + { doubleClickFired = false; this.parent.OnDoubleClick(me); this.parent.OnMouseDoubleClick(me); @@ -1547,7 +1751,8 @@ protected override void OnMouseUp(MouseEventArgs e) { /// Handles detecting when the mouse leaves. /// /// - protected override void OnMouseLeave(EventArgs e) { + protected override void OnMouseLeave(EventArgs e) + { mouseOver = ButtonID.None; Invalidate(); @@ -1558,36 +1763,44 @@ protected override void OnMouseLeave(EventArgs e) { /// Handles painting the buttons on the control. /// /// - protected override void OnPaint(PaintEventArgs e) { + protected override void OnPaint(PaintEventArgs e) + { int half_height = ClientSize.Height / 2; /* Draw the up and down buttons */ - if (Application.RenderWithVisualStyles) { + if (Application.RenderWithVisualStyles) + { VisualStyleRenderer vsr = new VisualStyleRenderer(mouseOver == ButtonID.Up ? VisualStyleElement.Spin.Up.Hot : VisualStyleElement.Spin.Up.Normal); - if (!Enabled) { + if (!Enabled) + { vsr.SetParameters(VisualStyleElement.Spin.Up.Disabled); } - else if (pushed == ButtonID.Up) { + else if (pushed == ButtonID.Up) + { vsr.SetParameters(VisualStyleElement.Spin.Up.Pressed); } vsr.DrawBackground(e.Graphics, new Rectangle(0, 0, parent.defaultButtonsWidth, half_height), HandleInternal); - if (!Enabled) { + if (!Enabled) + { vsr.SetParameters(VisualStyleElement.Spin.Down.Disabled); } - else if (pushed == ButtonID.Down) { + else if (pushed == ButtonID.Down) + { vsr.SetParameters(VisualStyleElement.Spin.Down.Pressed); } - else { + else + { vsr.SetParameters(mouseOver == ButtonID.Down ? VisualStyleElement.Spin.Down.Hot : VisualStyleElement.Spin.Down.Normal); } vsr.DrawBackground(e.Graphics, new Rectangle(0, half_height, parent.defaultButtonsWidth, half_height), HandleInternal); } - else { + else + { ControlPaint.DrawScrollButton(e.Graphics, new Rectangle(0, 0, parent.defaultButtonsWidth, half_height), ScrollButton.Up, @@ -1599,9 +1812,11 @@ protected override void OnPaint(PaintEventArgs e) { pushed == ButtonID.Down ? ButtonState.Pushed : (Enabled ? ButtonState.Normal : ButtonState.Inactive)); } - if (half_height != (ClientSize.Height + 1) / 2) { + if (half_height != (ClientSize.Height + 1) / 2) + { // When control has odd height, a line needs to be drawn below the buttons with the backcolor. - using (Pen pen = new Pen(this.parent.BackColor)) { + using (Pen pen = new Pen(this.parent.BackColor)) + { Rectangle clientRect = ClientRectangle; e.Graphics.DrawLine(pen, clientRect.Left, clientRect.Bottom - 1, clientRect.Right - 1, clientRect.Bottom - 1); } @@ -1613,7 +1828,8 @@ protected override void OnPaint(PaintEventArgs e) { /// /// Occurs when the UpDown buttons are pressed and when the acceleration timer tick event is raised. /// - protected virtual void OnUpDown(UpDownEventArgs upevent) { + protected virtual void OnUpDown(UpDownEventArgs upevent) + { if (upDownEventHandler != null) upDownEventHandler(this, upevent); } @@ -1621,9 +1837,11 @@ protected virtual void OnUpDown(UpDownEventArgs upevent) { /// /// Starts the timer for generating updown events /// - protected void StartTimer() { + protected void StartTimer() + { parent.OnStartTimer(); - if (timer == null) { + if (timer == null) + { timer = new Timer(); // generates UpDown events // Add the timer handler timer.Tick += new EventHandler(TimerHandler); @@ -1638,8 +1856,10 @@ protected void StartTimer() { /// /// Stops the timer for generating updown events /// - protected void StopTimer() { - if (timer != null) { + protected void StopTimer() + { + if (timer != null) + { timer.Stop(); timer.Dispose(); timer = null; @@ -1650,10 +1870,12 @@ protected void StopTimer() { /// /// Generates updown events when the timer calls this function. /// - private void TimerHandler(object source, EventArgs args) { + private void TimerHandler(object source, EventArgs args) + { // Make sure we've got mouse capture - if (!Capture) { + if (!Capture) + { EndButtonPress(); return; } @@ -1662,64 +1884,81 @@ private void TimerHandler(object source, EventArgs args) { // process the mouse button up event, which results in timer being disposed OnUpDown(new UpDownEventArgs((int)pushed)); - if (timer != null) { + if (timer != null) + { // Accelerate timer. this.timerInterval *= 7; this.timerInterval /= 10; - if (this.timerInterval < 1) { + if (this.timerInterval < 1) + { this.timerInterval = 1; } timer.Interval = this.timerInterval; - } + } } - internal class UpDownButtonsAccessibleObject : ControlAccessibleObject { + internal class UpDownButtonsAccessibleObject : ControlAccessibleObject + { private DirectionButtonAccessibleObject upButton; private DirectionButtonAccessibleObject downButton; - public UpDownButtonsAccessibleObject(UpDownButtons owner) : base(owner) { + public UpDownButtonsAccessibleObject(UpDownButtons owner) : base(owner) + { } - public override string Name { - get { + public override string Name + { + get + { string baseName = base.Name; - if (baseName == null || baseName.Length == 0) { + if (baseName == null || baseName.Length == 0) + { // Spinner is already announced so use type name. return Owner.ParentInternal.GetType().Name; } return baseName; } - set { + set + { base.Name = value; } } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { AccessibleRole role = Owner.AccessibleRole; - if (role != AccessibleRole.Default) { + if (role != AccessibleRole.Default) + { return role; } return AccessibleRole.SpinButton; } } - private DirectionButtonAccessibleObject UpButton { - get { - if (upButton == null) { + private DirectionButtonAccessibleObject UpButton + { + get + { + if (upButton == null) + { upButton = new DirectionButtonAccessibleObject(this, true); } return upButton; } } - private DirectionButtonAccessibleObject DownButton { - get { - if (downButton == null) { + private DirectionButtonAccessibleObject DownButton + { + get + { + if (downButton == null) + { downButton = new DirectionButtonAccessibleObject(this, false); } return downButton; @@ -1730,17 +1969,20 @@ private DirectionButtonAccessibleObject DownButton { /// /// - public override AccessibleObject GetChild(int index) { + public override AccessibleObject GetChild(int index) + { // Up button // - if (index == 0) { + if (index == 0) + { return UpButton; } // Down button // - if (index == 1) { + if (index == 1) + { return DownButton; } @@ -1749,26 +1991,32 @@ public override AccessibleObject GetChild(int index) { /// /// - public override int GetChildCount() { + public override int GetChildCount() + { return 2; } - internal class DirectionButtonAccessibleObject : AccessibleObject { + internal class DirectionButtonAccessibleObject : AccessibleObject + { private bool up; private UpDownButtonsAccessibleObject parent; - public DirectionButtonAccessibleObject(UpDownButtonsAccessibleObject parent, bool up) { + public DirectionButtonAccessibleObject(UpDownButtonsAccessibleObject parent, bool up) + { this.parent = parent; this.up = up; } - public override Rectangle Bounds { - get { + public override Rectangle Bounds + { + get + { // Get button bounds // Rectangle bounds = ((UpDownButtons)parent.Owner).Bounds; bounds.Height /= 2; - if (!up) { + if (!up) + { bounds.Y += bounds.Height; } @@ -1778,25 +2026,33 @@ public override Rectangle Bounds { } } - public override string Name { - get { - if (up) { + public override string Name + { + get + { + if (up) + { return SR.UpDownBaseUpButtonAccName; } return SR.UpDownBaseDownButtonAccName; } - set { + set + { } } - public override AccessibleObject Parent { - get { + public override AccessibleObject Parent + { + get + { return parent; } } - public override AccessibleRole Role { - get { + public override AccessibleRole Role + { + get + { return AccessibleRole.PushButton; } } @@ -1807,7 +2063,8 @@ public override AccessibleRole Role { // Button identifiers - internal enum ButtonID { + internal enum ButtonID + { None = 0, Up = 1, Down = 2, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/UserControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/UserControl.cs index 01c3481b930..2b9bf29734f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/UserControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/UserControl.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using Microsoft.Win32; using System; @@ -11,7 +12,7 @@ namespace System.Windows.Forms { using System.ComponentModel.Design; using System.ComponentModel.Design.Serialization; using System.Diagnostics; - using System.Drawing; + using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms.Design; using System.Windows.Forms.Layout; @@ -29,7 +30,8 @@ namespace System.Windows.Forms { DesignerCategory("UserControl"), DefaultEvent(nameof(Load)) ] - public class UserControl : ContainerControl { + public class UserControl : ContainerControl + { private static readonly object EVENT_LOAD = new object(); private BorderStyle borderStyle = System.Windows.Forms.BorderStyle.None; @@ -38,13 +40,14 @@ public class UserControl : ContainerControl { /// will not want to instantiate this class directly, but will be a /// sub-class of it. /// - public UserControl() { + public UserControl() + { SetScrollState(ScrollStateAutoScrolling, false); SetState(STATE_VISIBLE, true); SetState(STATE_TOPLEVEL, false); - SetStyle(ControlStyles.SupportsTransparentBackColor, true); + SetStyle(ControlStyles.SupportsTransparentBackColor, true); } - + /// /// Override to re-expose AutoSize. /// @@ -66,7 +69,8 @@ public override bool AutoSize /// Re-expose AutoSizeChanged. /// [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] - public new event EventHandler AutoSizeChanged { + public new event EventHandler AutoSizeChanged + { add => base.AutoSizeChanged += value; remove => base.AutoSizeChanged -= value; } @@ -81,25 +85,31 @@ public override bool AutoSize DefaultValue(AutoSizeMode.GrowOnly), Localizable(true) ] - public AutoSizeMode AutoSizeMode { - get { + public AutoSizeMode AutoSizeMode + { + get + { return GetAutoSizeMode(); } - set { + set + { if (!ClientUtils.IsEnumValid(value, (int)value, (int)AutoSizeMode.GrowAndShrink, (int)AutoSizeMode.GrowOnly)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AutoSizeMode)); } - - if (GetAutoSizeMode() != value) { + + if (GetAutoSizeMode() != value) + { SetAutoSizeMode(value); Control toLayout = DesignMode || ParentInternal == null ? this : ParentInternal; - - if(toLayout != null) { + + if (toLayout != 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(toLayout.LayoutEngine == DefaultLayout.Instance) { + if (toLayout.LayoutEngine == DefaultLayout.Instance) + { toLayout.LayoutEngine.InitLayout(this, BoundsSpecified.Size); } LayoutTransaction.DoLayout(toLayout, this, PropertyNames.AutoSize); @@ -115,11 +125,14 @@ public AutoSizeMode AutoSizeMode { Browsable(true), EditorBrowsable(EditorBrowsableState.Always), ] - public override AutoValidate AutoValidate { - get { + public override AutoValidate AutoValidate + { + get + { return base.AutoValidate; } - set { + set + { base.AutoValidate = value; } } @@ -128,7 +141,8 @@ public override AutoValidate AutoValidate { Browsable(true), EditorBrowsable(EditorBrowsableState.Always), ] - public new event EventHandler AutoValidateChanged { + public new event EventHandler AutoValidateChanged + { add => base.AutoValidateChanged += value; remove => base.AutoValidateChanged -= value; } @@ -144,13 +158,17 @@ public override AutoValidate AutoValidate { SRDescription(nameof(SR.UserControlBorderStyleDescr)), Browsable(true), EditorBrowsable(EditorBrowsableState.Always) ] - public BorderStyle BorderStyle { - get { + public BorderStyle BorderStyle + { + get + { return borderStyle; } - set { - if (borderStyle != value) { + set + { + if (borderStyle != value) + { //valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)) { @@ -170,15 +188,18 @@ public BorderStyle BorderStyle { /// filled up with the basic info.This is required as we now need to pass the /// styles for appropriate BorderStyle that is set by the user. /// - protected override CreateParams CreateParams { - get { + protected override CreateParams CreateParams + { + get + { CreateParams cp = base.CreateParams; cp.ExStyle |= NativeMethods.WS_EX_CONTROLPARENT; cp.ExStyle &= (~NativeMethods.WS_EX_CLIENTEDGE); cp.Style &= (~NativeMethods.WS_BORDER); - switch (borderStyle) { + switch (borderStyle) + { case BorderStyle.Fixed3D: cp.ExStyle |= NativeMethods.WS_EX_CLIENTEDGE; break; @@ -189,12 +210,14 @@ protected override CreateParams CreateParams { return cp; } } - + /// /// The default size for this user control. /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(150, 150); } } @@ -203,38 +226,44 @@ protected override Size DefaultSize { /// Occurs before the control becomes visible. /// [SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.UserControlOnLoadDescr))] - public event EventHandler Load { + public event EventHandler Load + { add => Events.AddHandler(EVENT_LOAD, value); remove => Events.RemoveHandler(EVENT_LOAD, value); } [ - Browsable(false), EditorBrowsable(EditorBrowsableState.Never), - Bindable(false), + Browsable(false), EditorBrowsable(EditorBrowsableState.Never), + Bindable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] - public override string Text { - get { + ] + public override string Text + { + get + { return base.Text; } - set { + set + { base.Text = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TextChanged { + new public event EventHandler TextChanged + { add => base.TextChanged += value; remove => base.TextChanged -= value; } - + /// /// Validates all selectable child controls in the container, including descendants. This is /// equivalent to calling ValidateChildren(ValidationConstraints.Selectable). See /// for details of exactly which child controls will be validated. /// [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] - public override bool ValidateChildren() { + public override bool ValidateChildren() + { return base.ValidateChildren(); } @@ -243,15 +272,19 @@ public override bool ValidateChildren() { /// validated and which controls are skipped is determined by . /// [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] - public override bool ValidateChildren(ValidationConstraints validationConstraints) { + public override bool ValidateChildren(ValidationConstraints validationConstraints) + { return base.ValidateChildren(validationConstraints); } - private bool FocusInside() { - if (!IsHandleCreated) return false; + private bool FocusInside() + { + if (!IsHandleCreated) + return false; IntPtr hwndFocus = UnsafeNativeMethods.GetFocus(); - if (hwndFocus == IntPtr.Zero) return false; + if (hwndFocus == IntPtr.Zero) + return false; IntPtr hwnd = Handle; if (hwnd == hwndFocus || SafeNativeMethods.IsChild(new HandleRef(this, hwnd), new HandleRef(null, hwndFocus))) @@ -264,9 +297,10 @@ private bool FocusInside() { /// Raises the CreateControl event. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnCreateControl() { + protected override void OnCreateControl() + { base.OnCreateControl(); - + OnLoad(EventArgs.Empty); } @@ -274,44 +308,54 @@ protected override void OnCreateControl() { /// The Load event is fired before the control becomes visible for the first time. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - protected virtual void OnLoad(EventArgs e) { + protected virtual void OnLoad(EventArgs e) + { // There is no good way to explain this event except to say // that it's just another name for OnControlCreated. EventHandler handler = (EventHandler)Events[EVENT_LOAD]; - if (handler != null) handler(this,e); + if (handler != null) + handler(this, e); } /// /// OnResize override to invalidate entire control in Stetch mode /// - protected override void OnResize(EventArgs e) { + protected override void OnResize(EventArgs e) + { base.OnResize(e); - if (BackgroundImage != null) { + if (BackgroundImage != null) + { Invalidate(); } } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnMouseDown(MouseEventArgs e) { + protected override void OnMouseDown(MouseEventArgs e) + { if (!FocusInside()) Focus(); base.OnMouseDown(e); } - private void WmSetFocus(ref Message m) { - if (!HostedInWin32DialogManager) { + private void WmSetFocus(ref Message m) + { + if (!HostedInWin32DialogManager) + { if (ActiveControl == null) SelectNextControl(null, true, true, true, false); } - if (!ValidationCancelled) { + if (!ValidationCancelled) + { base.WndProc(ref m); } - + } [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { case Interop.WindowMessages.WM_SETFOCUS: WmSetFocus(ref m); break; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/BackgroundType.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/BackgroundType.cs index ecba846fe39..26bd711c149 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/BackgroundType.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/BackgroundType.cs @@ -8,13 +8,13 @@ namespace System.Windows.Forms.VisualStyles { - public enum BackgroundType + public enum BackgroundType { - ImageFile = 0, - BorderFill = 1, - None = 2, - // TM_ENUM(0, BT, IMAGEFILE) - // TM_ENUM(1, BT, BORDERFILL) - // TM_ENUM(2, BT, NONE) + ImageFile = 0, + BorderFill = 1, + None = 2, + // TM_ENUM(0, BT, IMAGEFILE) + // TM_ENUM(1, BT, BORDERFILL) + // TM_ENUM(2, BT, NONE) } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/BooleanProperty.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/BooleanProperty.cs index 7d2957a9d3f..0071caa1fe0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/BooleanProperty.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/BooleanProperty.cs @@ -25,18 +25,18 @@ public enum BooleanProperty SourceGrow = 2212, SourceShrink = 2213 - // TM_PROP(2201, TMT, TRANSPARENT, BOOL) // image has transparent areas (see TransparentColor) - // TM_PROP(2202, TMT, AUTOSIZE, BOOL) // if TRUE, nonclient caption width varies with text extent - // TM_PROP(2203, TMT, BORDERONLY, BOOL) // only draw the border area of the image - // TM_PROP(2204, TMT, COMPOSITED, BOOL) // control will handle the composite drawing - // TM_PROP(2205, TMT, BGFILL, BOOL) // if TRUE, TRUESIZE images should be drawn on bg fill - // TM_PROP(2206, TMT, GLYPHTRANSPARENT, BOOL) // glyph has transparent areas (see GlyphTransparentColor) - // TM_PROP(2207, TMT, GLYPHONLY, BOOL) // only draw glyph (not background) - // TM_PROP(2208, TMT, ALWAYSSHOWSIZINGBAR, BOOL) - // TM_PROP(2209, TMT, MIRRORIMAGE, BOOL) // default=TRUE means image gets mirrored in RTL (Mirror) windows - // TM_PROP(2210, TMT, UNIFORMSIZING, BOOL) // if TRUE, height & width must be uniformly sized - // TM_PROP(2211, TMT, INTEGRALSIZING, BOOL) // for TRUESIZE and Border sizing; if TRUE, factor must be integer - // TM_PROP(2212, TMT, SOURCEGROW, BOOL) // if TRUE, will scale up src image when needed - // TM_PROP(2213, TMT, SOURCESHRINK, BOOL) // if TRUE, will scale down src image when needed + // TM_PROP(2201, TMT, TRANSPARENT, BOOL) // image has transparent areas (see TransparentColor) + // TM_PROP(2202, TMT, AUTOSIZE, BOOL) // if TRUE, nonclient caption width varies with text extent + // TM_PROP(2203, TMT, BORDERONLY, BOOL) // only draw the border area of the image + // TM_PROP(2204, TMT, COMPOSITED, BOOL) // control will handle the composite drawing + // TM_PROP(2205, TMT, BGFILL, BOOL) // if TRUE, TRUESIZE images should be drawn on bg fill + // TM_PROP(2206, TMT, GLYPHTRANSPARENT, BOOL) // glyph has transparent areas (see GlyphTransparentColor) + // TM_PROP(2207, TMT, GLYPHONLY, BOOL) // only draw glyph (not background) + // TM_PROP(2208, TMT, ALWAYSSHOWSIZINGBAR, BOOL) + // TM_PROP(2209, TMT, MIRRORIMAGE, BOOL) // default=TRUE means image gets mirrored in RTL (Mirror) windows + // TM_PROP(2210, TMT, UNIFORMSIZING, BOOL) // if TRUE, height & width must be uniformly sized + // TM_PROP(2211, TMT, INTEGRALSIZING, BOOL) // for TRUESIZE and Border sizing; if TRUE, factor must be integer + // TM_PROP(2212, TMT, SOURCEGROW, BOOL) // if TRUE, will scale up src image when needed + // TM_PROP(2213, TMT, SOURCESHRINK, BOOL) // if TRUE, will scale down src image when needed } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/BorderType.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/BorderType.cs index 314ff641544..04078a2f2d4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/BorderType.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/BorderType.cs @@ -8,13 +8,13 @@ namespace System.Windows.Forms.VisualStyles { - public enum BorderType + public enum BorderType { - Rectangle = 0, - RoundedRectangle = 1, - Ellipse = 2, - // TM_ENUM(0, BT, RECT) - // TM_ENUM(1, BT, ROUNDRECT) - // TM_ENUM(2, BT, ELLIPSE) + Rectangle = 0, + RoundedRectangle = 1, + Ellipse = 2, + // TM_ENUM(0, BT, RECT) + // TM_ENUM(1, BT, ROUNDRECT) + // TM_ENUM(2, BT, ELLIPSE) } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/CheckBoxState.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/CheckBoxState.cs index adbe3ebab66..5cf0c15db16 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/CheckBoxState.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/CheckBoxState.cs @@ -11,17 +11,17 @@ namespace System.Windows.Forms.VisualStyles [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")] public enum CheckBoxState { - UncheckedNormal = 1, - UncheckedHot = 2, - UncheckedPressed = 3, - UncheckedDisabled = 4, - CheckedNormal = 5, - CheckedHot = 6, - CheckedPressed = 7, + UncheckedNormal = 1, + UncheckedHot = 2, + UncheckedPressed = 3, + UncheckedDisabled = 4, + CheckedNormal = 5, + CheckedHot = 6, + CheckedPressed = 7, CheckedDisabled = 8, - MixedNormal = 9, - MixedHot = 10, - MixedPressed = 11, + MixedNormal = 9, + MixedHot = 10, + MixedPressed = 11, MixedDisabled = 12 - } + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/ColorProperty.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/ColorProperty.cs index 128ce218bd1..713c075d469 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/ColorProperty.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/ColorProperty.cs @@ -11,51 +11,51 @@ namespace System.Windows.Forms.VisualStyles [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "Maps to native enum.")] public enum ColorProperty { - BorderColor = 3801, - FillColor = 3802, - TextColor = 3803, - EdgeLightColor = 3804, - EdgeHighlightColor = 3805, - EdgeShadowColor = 3806, - EdgeDarkShadowColor = 3807, - EdgeFillColor = 3808, - TransparentColor = 3809, - GradientColor1 = 3810, - GradientColor2 = 3811, - GradientColor3 = 3812, - GradientColor4 = 3813, - GradientColor5 = 3814, - ShadowColor = 3815, - GlowColor = 3816, - TextBorderColor = 3817, - TextShadowColor = 3818, - GlyphTextColor = 3819, - GlyphTransparentColor = 3820, - FillColorHint = 3821, - BorderColorHint = 3822, - AccentColorHint = 3823 - // TM_PROP(3801, TMT, BORDERCOLOR, COLOR) // color of borders for BorderFill - // TM_PROP(3802, TMT, FILLCOLOR, COLOR) // color of bg fill - // TM_PROP(3803, TMT, TEXTCOLOR, COLOR) // color text is drawn in - // TM_PROP(3804, TMT, EDGELIGHTCOLOR, COLOR) // edge color - // TM_PROP(3805, TMT, EDGEHIGHLIGHTCOLOR, COLOR) // edge color - // TM_PROP(3806, TMT, EDGESHADOWCOLOR, COLOR) // edge color - // TM_PROP(3807, TMT, EDGEDKSHADOWCOLOR, COLOR) // edge color - // TM_PROP(3808, TMT, EDGEFILLCOLOR, COLOR) // edge color - // TM_PROP(3809, TMT, TRANSPARENTCOLOR, COLOR) // color of pixels that are treated as transparent (not drawn) - // TM_PROP(3810, TMT, GRADIENTCOLOR1, COLOR) // first color in gradient - // TM_PROP(3811, TMT, GRADIENTCOLOR2, COLOR) // second color in gradient - // TM_PROP(3812, TMT, GRADIENTCOLOR3, COLOR) // third color in gradient - // TM_PROP(3813, TMT, GRADIENTCOLOR4, COLOR) // forth color in gradient - // TM_PROP(3814, TMT, GRADIENTCOLOR5, COLOR) // fifth color in gradient - // TM_PROP(3815, TMT, SHADOWCOLOR, COLOR) // color of text shadow - // TM_PROP(3816, TMT, GLOWCOLOR, COLOR) // color of glow produced by DrawThemeIcon - // TM_PROP(3817, TMT, TEXTBORDERCOLOR, COLOR) // color of text border - // TM_PROP(3818, TMT, TEXTSHADOWCOLOR, COLOR) // color of text shadow - // TM_PROP(3819, TMT, GLYPHTEXTCOLOR, COLOR) // color that font-based glyph is drawn with - // TM_PROP(3820, TMT, GLYPHTRANSPARENTCOLOR, COLOR) // color of transparent pixels in GlyphImageFile - // TM_PROP(3821, TMT, FILLCOLORHINT, COLOR) // hint about fill color used (for custom controls) - // TM_PROP(3822, TMT, BORDERCOLORHINT, COLOR) // hint about border color used (for custom controls) - // TM_PROP(3823, TMT, ACCENTCOLORHINT, COLOR) // hint about accent color used (for custom controls) + BorderColor = 3801, + FillColor = 3802, + TextColor = 3803, + EdgeLightColor = 3804, + EdgeHighlightColor = 3805, + EdgeShadowColor = 3806, + EdgeDarkShadowColor = 3807, + EdgeFillColor = 3808, + TransparentColor = 3809, + GradientColor1 = 3810, + GradientColor2 = 3811, + GradientColor3 = 3812, + GradientColor4 = 3813, + GradientColor5 = 3814, + ShadowColor = 3815, + GlowColor = 3816, + TextBorderColor = 3817, + TextShadowColor = 3818, + GlyphTextColor = 3819, + GlyphTransparentColor = 3820, + FillColorHint = 3821, + BorderColorHint = 3822, + AccentColorHint = 3823 + // TM_PROP(3801, TMT, BORDERCOLOR, COLOR) // color of borders for BorderFill + // TM_PROP(3802, TMT, FILLCOLOR, COLOR) // color of bg fill + // TM_PROP(3803, TMT, TEXTCOLOR, COLOR) // color text is drawn in + // TM_PROP(3804, TMT, EDGELIGHTCOLOR, COLOR) // edge color + // TM_PROP(3805, TMT, EDGEHIGHLIGHTCOLOR, COLOR) // edge color + // TM_PROP(3806, TMT, EDGESHADOWCOLOR, COLOR) // edge color + // TM_PROP(3807, TMT, EDGEDKSHADOWCOLOR, COLOR) // edge color + // TM_PROP(3808, TMT, EDGEFILLCOLOR, COLOR) // edge color + // TM_PROP(3809, TMT, TRANSPARENTCOLOR, COLOR) // color of pixels that are treated as transparent (not drawn) + // TM_PROP(3810, TMT, GRADIENTCOLOR1, COLOR) // first color in gradient + // TM_PROP(3811, TMT, GRADIENTCOLOR2, COLOR) // second color in gradient + // TM_PROP(3812, TMT, GRADIENTCOLOR3, COLOR) // third color in gradient + // TM_PROP(3813, TMT, GRADIENTCOLOR4, COLOR) // forth color in gradient + // TM_PROP(3814, TMT, GRADIENTCOLOR5, COLOR) // fifth color in gradient + // TM_PROP(3815, TMT, SHADOWCOLOR, COLOR) // color of text shadow + // TM_PROP(3816, TMT, GLOWCOLOR, COLOR) // color of glow produced by DrawThemeIcon + // TM_PROP(3817, TMT, TEXTBORDERCOLOR, COLOR) // color of text border + // TM_PROP(3818, TMT, TEXTSHADOWCOLOR, COLOR) // color of text shadow + // TM_PROP(3819, TMT, GLYPHTEXTCOLOR, COLOR) // color that font-based glyph is drawn with + // TM_PROP(3820, TMT, GLYPHTRANSPARENTCOLOR, COLOR) // color of transparent pixels in GlyphImageFile + // TM_PROP(3821, TMT, FILLCOLORHINT, COLOR) // hint about fill color used (for custom controls) + // TM_PROP(3822, TMT, BORDERCOLORHINT, COLOR) // hint about border color used (for custom controls) + // TM_PROP(3823, TMT, ACCENTCOLORHINT, COLOR) // hint about accent color used (for custom controls) } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/ContentAlignment.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/ContentAlignment.cs index 98f05064407..22ad11bf3ae 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/ContentAlignment.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/ContentAlignment.cs @@ -10,11 +10,11 @@ namespace System.Windows.Forms.VisualStyles { public enum ContentAlignment { - Left = 0, - Center = 1, - Right = 2, - // TM_ENUM(0, CA, LEFT) - // TM_ENUM(1, CA, CENTER) - // TM_ENUM(2, CA, RIGHT) + Left = 0, + Center = 1, + Right = 2, + // TM_ENUM(0, CA, LEFT) + // TM_ENUM(1, CA, CENTER) + // TM_ENUM(2, CA, RIGHT) } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/EdgeEffects.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/EdgeEffects.cs index 9ffb582f1d5..d18b5eba46e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/EdgeEffects.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/EdgeEffects.cs @@ -13,11 +13,11 @@ public enum EdgeEffects { None = 0, FillInterior = 0x0800, - Flat = 0x1000, - Soft = 0x4000, - Mono = 0x8000, - // #define BF_SOFT 0x1000 /* For softer buttons */ - // #define BF_FLAT 0x4000 /* For flat rather than 3D borders */ - // #define BF_MONO 0x8000 /* For monochrome borders */ + Flat = 0x1000, + Soft = 0x4000, + Mono = 0x8000, + // #define BF_SOFT 0x1000 /* For softer buttons */ + // #define BF_FLAT 0x4000 /* For flat rather than 3D borders */ + // #define BF_MONO 0x8000 /* For monochrome borders */ } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/EdgeStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/EdgeStyle.cs index d9e6edf5f24..13830d93930 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/EdgeStyle.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/EdgeStyle.cs @@ -12,17 +12,17 @@ namespace System.Windows.Forms.VisualStyles public enum EdgeStyle { Raised = 0x0001 | 0x0004, - Sunken = 0x0002 | 0x0008, + Sunken = 0x0002 | 0x0008, Etched = 0x0002 | 0x0004, Bump = 0x0001 | 0x0008 // #define BDR_RAISEDOUTER 0x0001 - // #define BDR_SUNKENOUTER 0x0002 - // #define BDR_RAISEDINNER 0x0004 - // #define BDR_SUNKENINNER 0x0008 - // #define EDGE_RAISED (BDR_RAISEDOUTER | BDR_RAISEDINNER) - // #define EDGE_SUNKEN (BDR_SUNKENOUTER | BDR_SUNKENINNER) - // #define EDGE_ETCHED (BDR_SUNKENOUTER | BDR_RAISEDINNER) - // #define EDGE_BUMP (BDR_RAISEDOUTER | BDR_SUNKENINNER) + // #define BDR_SUNKENOUTER 0x0002 + // #define BDR_RAISEDINNER 0x0004 + // #define BDR_SUNKENINNER 0x0008 + // #define EDGE_RAISED (BDR_RAISEDOUTER | BDR_RAISEDINNER) + // #define EDGE_SUNKEN (BDR_SUNKENOUTER | BDR_SUNKENINNER) + // #define EDGE_ETCHED (BDR_SUNKENOUTER | BDR_RAISEDINNER) + // #define EDGE_BUMP (BDR_RAISEDOUTER | BDR_SUNKENINNER) } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/Edges.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/Edges.cs index 86fb8757dce..49c9a25c9ab 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/Edges.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/Edges.cs @@ -18,24 +18,24 @@ public enum Edges Bottom = 0x0008, Diagonal = 0x0010, - // #define BF_LEFT 0x0001 - // #define BF_TOP 0x0002 - // #define BF_RIGHT 0x0004 - // #define BF_BOTTOM 0x0008 - // - // #define BF_TOPLEFT (BF_TOP | BF_LEFT) - // #define BF_TOPRIGHT (BF_TOP | BF_RIGHT) - // #define BF_BOTTOMLEFT (BF_BOTTOM | BF_LEFT) - // #define BF_BOTTOMRIGHT (BF_BOTTOM | BF_RIGHT) - // #define BF_RECT (BF_LEFT | BF_TOP | BF_RIGHT | BF_BOTTOM) - // - // #define BF_DIAGONAL 0x0010 + // #define BF_LEFT 0x0001 + // #define BF_TOP 0x0002 + // #define BF_RIGHT 0x0004 + // #define BF_BOTTOM 0x0008 + // + // #define BF_TOPLEFT (BF_TOP | BF_LEFT) + // #define BF_TOPRIGHT (BF_TOP | BF_RIGHT) + // #define BF_BOTTOMLEFT (BF_BOTTOM | BF_LEFT) + // #define BF_BOTTOMRIGHT (BF_BOTTOM | BF_RIGHT) + // #define BF_RECT (BF_LEFT | BF_TOP | BF_RIGHT | BF_BOTTOM) + // + // #define BF_DIAGONAL 0x0010 - // // For diagonal lines, the BF_RECT flags specify the end point of the - // // vector bounded by the rectangle parameter. - // #define BF_DIAGONAL_ENDTOPRIGHT (BF_DIAGONAL | BF_TOP | BF_RIGHT) - // #define BF_DIAGONAL_ENDTOPLEFT (BF_DIAGONAL | BF_TOP | BF_LEFT) - // #define BF_DIAGONAL_ENDBOTTOMLEFT (BF_DIAGONAL | BF_BOTTOM | BF_LEFT) - // #define BF_DIAGONAL_ENDBOTTOMRIGHT (BF_DIAGONAL | BF_BOTTOM | BF_RIGHT) + // // For diagonal lines, the BF_RECT flags specify the end point of the + // // vector bounded by the rectangle parameter. + // #define BF_DIAGONAL_ENDTOPRIGHT (BF_DIAGONAL | BF_TOP | BF_RIGHT) + // #define BF_DIAGONAL_ENDTOPLEFT (BF_DIAGONAL | BF_TOP | BF_LEFT) + // #define BF_DIAGONAL_ENDBOTTOMLEFT (BF_DIAGONAL | BF_BOTTOM | BF_LEFT) + // #define BF_DIAGONAL_ENDBOTTOMRIGHT (BF_DIAGONAL | BF_BOTTOM | BF_RIGHT) } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/EnumProperty.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/EnumProperty.cs index d0bae462e2c..32fd1db0f39 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/EnumProperty.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/EnumProperty.cs @@ -11,35 +11,35 @@ namespace System.Windows.Forms.VisualStyles [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "EnumProperty maps to native enum.")] public enum EnumProperty { - BackgroundType = 4001, - BorderType = 4002, - FillType = 4003, - SizingType = 4004, - HorizontalAlignment = 4005, + BackgroundType = 4001, + BorderType = 4002, + FillType = 4003, + SizingType = 4004, + HorizontalAlignment = 4005, ContentAlignment = 4006, - VerticalAlignment = 4007, - OffsetType = 4008, - IconEffect = 4009, - TextShadowType = 4010, - ImageLayout = 4011, - GlyphType = 4012, - ImageSelectType = 4013, - GlyphFontSizingType = 4014, - TrueSizeScalingType = 4015 - // TM_PROP(4001, TMT, BGTYPE, ENUM) // basic drawing type for each part - // TM_PROP(4002, TMT, BORDERTYPE, ENUM) // type of border for BorderFill parts - // TM_PROP(4003, TMT, FILLTYPE, ENUM) // fill shape for BorderFill parts - // TM_PROP(4004, TMT, SIZINGTYPE, ENUM) // how to size ImageFile parts - // TM_PROP(4005, TMT, HALIGN, ENUM) // horizontal alignment for TRUESIZE parts & glyphs - // TM_PROP(4006, TMT, CONTENTALIGNMENT, ENUM) // custom window prop: how text is aligned in caption - // TM_PROP(4007, TMT, VALIGN, ENUM) // horizontal alignment for TRUESIZE parts & glyphs - // TM_PROP(4008, TMT, OFFSETTYPE, ENUM) // how window part should be placed - // TM_PROP(4009, TMT, ICONEFFECT, ENUM) // type of effect to use with DrawThemeIcon - // TM_PROP(4010, TMT, TEXTSHADOWTYPE, ENUM) // type of shadow to draw with text - // TM_PROP(4011, TMT, IMAGELAYOUT, ENUM) // how multiple images are arranged (horz. or vert.) - // TM_PROP(4012, TMT, GLYPHTYPE, ENUM) // controls type of glyph in imagefile objects - // TM_PROP(4013, TMT, IMAGESELECTTYPE, ENUM) // controls when to select from IMAGEFILE1...IMAGEFILE5 - // TM_PROP(4014, TMT, GLYPHFONTSIZINGTYPE, ENUM) // controls when to select a bigger/small glyph font size - // TM_PROP(4015, TMT, TRUESIZESCALINGTYPE, ENUM) // controls how TrueSize image is scaled + VerticalAlignment = 4007, + OffsetType = 4008, + IconEffect = 4009, + TextShadowType = 4010, + ImageLayout = 4011, + GlyphType = 4012, + ImageSelectType = 4013, + GlyphFontSizingType = 4014, + TrueSizeScalingType = 4015 + // TM_PROP(4001, TMT, BGTYPE, ENUM) // basic drawing type for each part + // TM_PROP(4002, TMT, BORDERTYPE, ENUM) // type of border for BorderFill parts + // TM_PROP(4003, TMT, FILLTYPE, ENUM) // fill shape for BorderFill parts + // TM_PROP(4004, TMT, SIZINGTYPE, ENUM) // how to size ImageFile parts + // TM_PROP(4005, TMT, HALIGN, ENUM) // horizontal alignment for TRUESIZE parts & glyphs + // TM_PROP(4006, TMT, CONTENTALIGNMENT, ENUM) // custom window prop: how text is aligned in caption + // TM_PROP(4007, TMT, VALIGN, ENUM) // horizontal alignment for TRUESIZE parts & glyphs + // TM_PROP(4008, TMT, OFFSETTYPE, ENUM) // how window part should be placed + // TM_PROP(4009, TMT, ICONEFFECT, ENUM) // type of effect to use with DrawThemeIcon + // TM_PROP(4010, TMT, TEXTSHADOWTYPE, ENUM) // type of shadow to draw with text + // TM_PROP(4011, TMT, IMAGELAYOUT, ENUM) // how multiple images are arranged (horz. or vert.) + // TM_PROP(4012, TMT, GLYPHTYPE, ENUM) // controls type of glyph in imagefile objects + // TM_PROP(4013, TMT, IMAGESELECTTYPE, ENUM) // controls when to select from IMAGEFILE1...IMAGEFILE5 + // TM_PROP(4014, TMT, GLYPHFONTSIZINGTYPE, ENUM) // controls when to select a bigger/small glyph font size + // TM_PROP(4015, TMT, TRUESIZESCALINGTYPE, ENUM) // controls how TrueSize image is scaled } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/FilenameProperty.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/FilenameProperty.cs index 44587606ccd..57cbad15481 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/FilenameProperty.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/FilenameProperty.cs @@ -11,21 +11,21 @@ namespace System.Windows.Forms.VisualStyles [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "Maps to native enum.")] public enum FilenameProperty { - ImageFile = 3001, - ImageFile1 = 3002, - ImageFile2 = 3003, - ImageFile3 = 3004, - ImageFile4 = 3005, - ImageFile5 = 3006, - StockImageFile = 3007, - GlyphImageFile = 3008 - // TM_PROP(3001, TMT, IMAGEFILE, FILENAME) // the filename of the image (or basename, for mult. images) - // TM_PROP(3002, TMT, IMAGEFILE1, FILENAME) // multiresolution image file - // TM_PROP(3003, TMT, IMAGEFILE2, FILENAME) // multiresolution image file - // TM_PROP(3004, TMT, IMAGEFILE3, FILENAME) // multiresolution image file - // TM_PROP(3005, TMT, IMAGEFILE4, FILENAME) // multiresolution image file - // TM_PROP(3006, TMT, IMAGEFILE5, FILENAME) // multiresolution image file - // TM_PROP(3007, TMT, STOCKIMAGEFILE, FILENAME) // These are the only images that you can call GetThemeBitmap on - // TM_PROP(3008, TMT, GLYPHIMAGEFILE, FILENAME) // the filename for the glyph image + ImageFile = 3001, + ImageFile1 = 3002, + ImageFile2 = 3003, + ImageFile3 = 3004, + ImageFile4 = 3005, + ImageFile5 = 3006, + StockImageFile = 3007, + GlyphImageFile = 3008 + // TM_PROP(3001, TMT, IMAGEFILE, FILENAME) // the filename of the image (or basename, for mult. images) + // TM_PROP(3002, TMT, IMAGEFILE1, FILENAME) // multiresolution image file + // TM_PROP(3003, TMT, IMAGEFILE2, FILENAME) // multiresolution image file + // TM_PROP(3004, TMT, IMAGEFILE3, FILENAME) // multiresolution image file + // TM_PROP(3005, TMT, IMAGEFILE4, FILENAME) // multiresolution image file + // TM_PROP(3006, TMT, IMAGEFILE5, FILENAME) // multiresolution image file + // TM_PROP(3007, TMT, STOCKIMAGEFILE, FILENAME) // These are the only images that you can call GetThemeBitmap on + // TM_PROP(3008, TMT, GLYPHIMAGEFILE, FILENAME) // the filename for the glyph image } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/FillType.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/FillType.cs index 066f6bf4f1a..a6d6e2b09b1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/FillType.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/FillType.cs @@ -8,17 +8,17 @@ namespace System.Windows.Forms.VisualStyles { - public enum FillType + public enum FillType { - Solid = 0, - VerticalGradient = 1, - HorizontalGradient = 2, - RadialGradient = 3, - TileImage = 4, - // TM_ENUM(0, FT, SOLID) - // TM_ENUM(1, FT, VERTGRADIENT) - // TM_ENUM(2, FT, HORZGRADIENT) - // TM_ENUM(3, FT, RADIALGRADIENT) - // TM_ENUM(4, FT, TILEIMAGE) + Solid = 0, + VerticalGradient = 1, + HorizontalGradient = 2, + RadialGradient = 3, + TileImage = 4, + // TM_ENUM(0, FT, SOLID) + // TM_ENUM(1, FT, VERTGRADIENT) + // TM_ENUM(2, FT, HORZGRADIENT) + // TM_ENUM(3, FT, RADIALGRADIENT) + // TM_ENUM(4, FT, TILEIMAGE) } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/FontProperty.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/FontProperty.cs index 755077826e4..f61b0db0432 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/FontProperty.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/FontProperty.cs @@ -11,7 +11,7 @@ namespace System.Windows.Forms.VisualStyles [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "Maps to native enum.")] public enum FontProperty { - GlyphFont = 2601 - // TM_PROP(2601, TMT, GLYPHFONT, FONT) // the font that the glyph is drawn with + GlyphFont = 2601 + // TM_PROP(2601, TMT, GLYPHFONT, FONT) // the font that the glyph is drawn with } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/GlyphFontSizingType.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/GlyphFontSizingType.cs index 5606b0e53aa..ceed2d10fcf 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/GlyphFontSizingType.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/GlyphFontSizingType.cs @@ -10,11 +10,11 @@ namespace System.Windows.Forms.VisualStyles { public enum GlyphFontSizingType { - None = 0, - Size = 1, - Dpi = 2, - // TM_ENUM(0, GFST, NONE) - // TM_ENUM(1, GFST, SIZE) - // TM_ENUM(2, GFST, DPI) + None = 0, + Size = 1, + Dpi = 2, + // TM_ENUM(0, GFST, NONE) + // TM_ENUM(1, GFST, SIZE) + // TM_ENUM(2, GFST, DPI) } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/GlyphType.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/GlyphType.cs index 6b4bb72b7a7..2f5cb9d7710 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/GlyphType.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/GlyphType.cs @@ -10,11 +10,11 @@ namespace System.Windows.Forms.VisualStyles { public enum GlyphType { - None = 0, - ImageGlyph = 1, - FontGlyph = 2, - // TM_ENUM(0, GT, NONE) - // TM_ENUM(1, GT, IMAGEGLYPH) - // TM_ENUM(2, GT, FONTGLYPH) + None = 0, + ImageGlyph = 1, + FontGlyph = 2, + // TM_ENUM(0, GT, NONE) + // TM_ENUM(1, GT, IMAGEGLYPH) + // TM_ENUM(2, GT, FONTGLYPH) } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/GroupBoxState.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/GroupBoxState.cs index 75d8282075f..153170df3fb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/GroupBoxState.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/GroupBoxState.cs @@ -11,7 +11,7 @@ namespace System.Windows.Forms.VisualStyles [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")] public enum GroupBoxState { - Normal = 1, - Disabled = 2 + Normal = 1, + Disabled = 2 } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/HitTestCode.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/HitTestCode.cs index 18ffc4910e8..df2ff378c24 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/HitTestCode.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/HitTestCode.cs @@ -10,25 +10,25 @@ namespace System.Windows.Forms.VisualStyles { public enum HitTestCode { - Nowhere = 0, - Client = 1, - Left = 10, - Right = 11, - Top = 12, - Bottom = 15, - TopLeft = 13, - TopRight = 14, - BottomLeft = 16, - BottomRight = 17 - // #define HTNOWHERE 0 - // #define HTCLIENT 1 - // #define HTLEFT 10 - // #define HTRIGHT 11 - // #define HTTOP 12 - // #define HTTOPLEFT 13 - // #define HTTOPRIGHT 14 - // #define HTBOTTOM 15 - // #define HTBOTTOMLEFT 16 - // #define HTBOTTOMRIGHT 17 + Nowhere = 0, + Client = 1, + Left = 10, + Right = 11, + Top = 12, + Bottom = 15, + TopLeft = 13, + TopRight = 14, + BottomLeft = 16, + BottomRight = 17 + // #define HTNOWHERE 0 + // #define HTCLIENT 1 + // #define HTLEFT 10 + // #define HTRIGHT 11 + // #define HTTOP 12 + // #define HTTOPLEFT 13 + // #define HTTOPRIGHT 14 + // #define HTBOTTOM 15 + // #define HTBOTTOMLEFT 16 + // #define HTBOTTOMRIGHT 17 } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/HitTestOptions.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/HitTestOptions.cs index 1a05afe0b60..a5bc7b5d9dc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/HitTestOptions.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/HitTestOptions.cs @@ -12,50 +12,50 @@ namespace System.Windows.Forms.VisualStyles [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "Maps to native enum.")] public enum HitTestOptions { - BackgroundSegment = 0x0000, - FixedBorder = 0x0002, - Caption = 0x0004, - ResizingBorderLeft = 0x0010, - ResizingBorderTop = 0x0020, - ResizingBorderRight = 0x0040, - ResizingBorderBottom = 0x0080, - ResizingBorder = ResizingBorderLeft | ResizingBorderTop | ResizingBorderRight | ResizingBorderBottom, - SizingTemplate = 0x0100, - SystemSizingMargins = 0x0200 - - // Theme background segment hit test flag (default). possible return values are: - // HTCLIENT: hit test succeeded in the middle background segment - // HTTOP, HTLEFT, HTTOPLEFT, etc: // hit test succeeded in the the respective theme background segment. - //#define HTTB_BACKGROUNDSEG 0x0000 - - // Fixed border hit test option. possible return values are: - // HTCLIENT: hit test succeeded in the middle background segment - // HTBORDER: hit test succeeded in any other background segment - //#define HTTB_FIXEDBORDER 0x0002 // Return code may be either HTCLIENT or HTBORDER. - - // Caption hit test option. Possible return values are: - // HTCAPTION: hit test succeeded in the top, top left, or top right background segments - // HTNOWHERE or another return code, depending on absence or presence of accompanying flags, resp. - //#define HTTB_CAPTION 0x0004 - - // Resizing border hit test flags. Possible return values are: - // HTCLIENT: hit test succeeded in middle background segment - // HTTOP, HTTOPLEFT, HTLEFT, HTRIGHT, etc: hit test succeeded in the respective system resizing zone - // HTBORDER: hit test failed in middle segment and resizing zones, but succeeded in a background border segment - //#define HTTB_RESIZINGBORDER_LEFT 0x0010 // Hit test left resizing border, - //#define HTTB_RESIZINGBORDER_TOP 0x0020 // Hit test top resizing border - //#define HTTB_RESIZINGBORDER_RIGHT 0x0040 // Hit test right resizing border - //#define HTTB_RESIZINGBORDER_BOTTOM 0x0080 // Hit test bottom resizing border - - //#define HTTB_RESIZINGBORDER (HTTB_RESIZINGBORDER_LEFT|HTTB_RESIZINGBORDER_TOP|\ - // HTTB_RESIZINGBORDER_RIGHT|HTTB_RESIZINGBORDER_BOTTOM) - - // Resizing border is specified as a template, not just window edges. - // This option is mutually exclusive with HTTB_SYSTEMSIZINGWIDTH; HTTB_SIZINGTEMPLATE takes precedence - //#define HTTB_SIZINGTEMPLATE 0x0100 - - // Use system resizing border width rather than theme content margins. - // This option is mutually exclusive with HTTB_SIZINGTEMPLATE, which takes precedence. - //#define HTTB_SYSTEMSIZINGMARGINS 0x0200 + BackgroundSegment = 0x0000, + FixedBorder = 0x0002, + Caption = 0x0004, + ResizingBorderLeft = 0x0010, + ResizingBorderTop = 0x0020, + ResizingBorderRight = 0x0040, + ResizingBorderBottom = 0x0080, + ResizingBorder = ResizingBorderLeft | ResizingBorderTop | ResizingBorderRight | ResizingBorderBottom, + SizingTemplate = 0x0100, + SystemSizingMargins = 0x0200 + + // Theme background segment hit test flag (default). possible return values are: + // HTCLIENT: hit test succeeded in the middle background segment + // HTTOP, HTLEFT, HTTOPLEFT, etc: // hit test succeeded in the the respective theme background segment. + //#define HTTB_BACKGROUNDSEG 0x0000 + + // Fixed border hit test option. possible return values are: + // HTCLIENT: hit test succeeded in the middle background segment + // HTBORDER: hit test succeeded in any other background segment + //#define HTTB_FIXEDBORDER 0x0002 // Return code may be either HTCLIENT or HTBORDER. + + // Caption hit test option. Possible return values are: + // HTCAPTION: hit test succeeded in the top, top left, or top right background segments + // HTNOWHERE or another return code, depending on absence or presence of accompanying flags, resp. + //#define HTTB_CAPTION 0x0004 + + // Resizing border hit test flags. Possible return values are: + // HTCLIENT: hit test succeeded in middle background segment + // HTTOP, HTTOPLEFT, HTLEFT, HTRIGHT, etc: hit test succeeded in the respective system resizing zone + // HTBORDER: hit test failed in middle segment and resizing zones, but succeeded in a background border segment + //#define HTTB_RESIZINGBORDER_LEFT 0x0010 // Hit test left resizing border, + //#define HTTB_RESIZINGBORDER_TOP 0x0020 // Hit test top resizing border + //#define HTTB_RESIZINGBORDER_RIGHT 0x0040 // Hit test right resizing border + //#define HTTB_RESIZINGBORDER_BOTTOM 0x0080 // Hit test bottom resizing border + + //#define HTTB_RESIZINGBORDER (HTTB_RESIZINGBORDER_LEFT|HTTB_RESIZINGBORDER_TOP|\ + // HTTB_RESIZINGBORDER_RIGHT|HTTB_RESIZINGBORDER_BOTTOM) + + // Resizing border is specified as a template, not just window edges. + // This option is mutually exclusive with HTTB_SYSTEMSIZINGWIDTH; HTTB_SIZINGTEMPLATE takes precedence + //#define HTTB_SIZINGTEMPLATE 0x0100 + + // Use system resizing border width rather than theme content margins. + // This option is mutually exclusive with HTTB_SIZINGTEMPLATE, which takes precedence. + //#define HTTB_SYSTEMSIZINGMARGINS 0x0200 } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/HorizontalAlign.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/HorizontalAlign.cs index bb37a69ea4b..cafd40918f2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/HorizontalAlign.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/HorizontalAlign.cs @@ -10,11 +10,11 @@ namespace System.Windows.Forms.VisualStyles { public enum HorizontalAlign { - Left = 0, - Center = 1, - Right = 2, - // TM_ENUM(0, HA, LEFT) - // TM_ENUM(1, HA, CENTER) - // TM_ENUM(2, HA, RIGHT) + Left = 0, + Center = 1, + Right = 2, + // TM_ENUM(0, HA, LEFT) + // TM_ENUM(1, HA, CENTER) + // TM_ENUM(2, HA, RIGHT) } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/IconEffect.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/IconEffect.cs index 86519d2d267..8264b3def87 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/IconEffect.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/IconEffect.cs @@ -10,15 +10,15 @@ namespace System.Windows.Forms.VisualStyles { public enum IconEffect { - None = 0, - Glow = 1, - Shadow = 2, - Pulse = 3, - Alpha = 4, - // TM_ENUM(0, ICE, NONE) - // TM_ENUM(1, ICE, GLOW) - // TM_ENUM(2, ICE, SHADOW) - // TM_ENUM(3, ICE, PULSE) - // TM_ENUM(4, ICE, ALPHA) + None = 0, + Glow = 1, + Shadow = 2, + Pulse = 3, + Alpha = 4, + // TM_ENUM(0, ICE, NONE) + // TM_ENUM(1, ICE, GLOW) + // TM_ENUM(2, ICE, SHADOW) + // TM_ENUM(3, ICE, PULSE) + // TM_ENUM(4, ICE, ALPHA) } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/ImageOrientation.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/ImageOrientation.cs index 3b9d6da25b5..06ea1aa2001 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/ImageOrientation.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/ImageOrientation.cs @@ -8,11 +8,11 @@ namespace System.Windows.Forms.VisualStyles { - public enum ImageOrientation + public enum ImageOrientation { - Vertical = 0, - Horizontal = 1, - // TM_ENUM(0, IL, VERTICAL) - // TM_ENUM(1, IL, HORIZONTAL) + Vertical = 0, + Horizontal = 1, + // TM_ENUM(0, IL, VERTICAL) + // TM_ENUM(1, IL, HORIZONTAL) } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/ImageSelectType.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/ImageSelectType.cs index 64899231530..8ff02e814a6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/ImageSelectType.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/ImageSelectType.cs @@ -10,11 +10,11 @@ namespace System.Windows.Forms.VisualStyles { public enum ImageSelectType { - None = 0, - Size = 1, - Dpi = 2, - // TM_ENUM(0, IST, NONE) - // TM_ENUM(1, IST, SIZE) - // TM_ENUM(2, IST, DPI) + None = 0, + Size = 1, + Dpi = 2, + // TM_ENUM(0, IST, NONE) + // TM_ENUM(1, IST, SIZE) + // TM_ENUM(2, IST, DPI) } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/IntegerProperty.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/IntegerProperty.cs index dccb86bda46..41cca605dce 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/IntegerProperty.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/IntegerProperty.cs @@ -11,53 +11,53 @@ namespace System.Windows.Forms.VisualStyles [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "Maps to native enum.")] public enum IntegerProperty { - ImageCount = 2401, - AlphaLevel = 2402, - BorderSize = 2403, - RoundCornerWidth = 2404, - RoundCornerHeight = 2405, - GradientRatio1 = 2406, - GradientRatio2 = 2407, - GradientRatio3 = 2408, - GradientRatio4 = 2409, - GradientRatio5 = 2410, - ProgressChunkSize = 2411, - ProgressSpaceSize = 2412, - Saturation = 2413, - TextBorderSize = 2414, - AlphaThreshold = 2415, - Width = 2416, - Height = 2417, - GlyphIndex = 2418, - TrueSizeStretchMark = 2419, - MinDpi1 = 2420, - MinDpi2 = 2421, - MinDpi3 = 2422, - MinDpi4 = 2423, - MinDpi5 = 2424 - // TM_PROP(2401, TMT, IMAGECOUNT, INT) // the number of state images in an imagefile - // TM_PROP(2402, TMT, ALPHALEVEL, INT) // (0-255) alpha value for an icon (DrawThemeIcon part) - // TM_PROP(2403, TMT, BORDERSIZE, INT) // the size of the border line for bgtype=BorderFill - // TM_PROP(2404, TMT, ROUNDCORNERWIDTH, INT) // (0-100) % of roundness for rounded rects - // TM_PROP(2405, TMT, ROUNDCORNERHEIGHT, INT) // (0-100) % of roundness for rounded rects - // TM_PROP(2406, TMT, GRADIENTRATIO1, INT) // (0-255) - amt of gradient color 1 to use (all must total=255) - // TM_PROP(2407, TMT, GRADIENTRATIO2, INT) // (0-255) - amt of gradient color 2 to use (all must total=255) - // TM_PROP(2408, TMT, GRADIENTRATIO3, INT) // (0-255) - amt of gradient color 3 to use (all must total=255) - // TM_PROP(2409, TMT, GRADIENTRATIO4, INT) // (0-255) - amt of gradient color 4 to use (all must total=255) - // TM_PROP(2410, TMT, GRADIENTRATIO5, INT) // (0-255) - amt of gradient color 5 to use (all must total=255) - // TM_PROP(2411, TMT, PROGRESSCHUNKSIZE, INT) // size of progress control chunks - // TM_PROP(2412, TMT, PROGRESSSPACESIZE, INT) // size of progress control spaces - // TM_PROP(2413, TMT, SATURATION, INT) // (0-255) amt of saturation for DrawThemeIcon() part - // TM_PROP(2414, TMT, TEXTBORDERSIZE, INT) // size of border around text chars - // TM_PROP(2415, TMT, ALPHATHRESHOLD, INT) // (0-255) the min. alpha value of a pixel that is solid - // TM_PROP(2416, TMT, WIDTH, SIZE) // custom window prop: size of part (min. window) - // TM_PROP(2417, TMT, HEIGHT, SIZE) // custom window prop: size of part (min. window) - // TM_PROP(2418, TMT, GLYPHINDEX, INT) // for font-based glyphs, the char index into the font - // TM_PROP(2419, TMT, TRUESIZESTRETCHMARK, INT) // stretch TrueSize image when target exceeds source by this percent - // TM_PROP(2420, TMT, MINDPI1, INT) // min DPI ImageFile1 was designed for - // TM_PROP(2421, TMT, MINDPI2, INT) // min DPI ImageFile1 was designed for - // TM_PROP(2422, TMT, MINDPI3, INT) // min DPI ImageFile1 was designed for - // TM_PROP(2423, TMT, MINDPI4, INT) // min DPI ImageFile1 was designed for - // TM_PROP(2424, TMT, MINDPI5, INT) // min DPI ImageFile1 was designed for + ImageCount = 2401, + AlphaLevel = 2402, + BorderSize = 2403, + RoundCornerWidth = 2404, + RoundCornerHeight = 2405, + GradientRatio1 = 2406, + GradientRatio2 = 2407, + GradientRatio3 = 2408, + GradientRatio4 = 2409, + GradientRatio5 = 2410, + ProgressChunkSize = 2411, + ProgressSpaceSize = 2412, + Saturation = 2413, + TextBorderSize = 2414, + AlphaThreshold = 2415, + Width = 2416, + Height = 2417, + GlyphIndex = 2418, + TrueSizeStretchMark = 2419, + MinDpi1 = 2420, + MinDpi2 = 2421, + MinDpi3 = 2422, + MinDpi4 = 2423, + MinDpi5 = 2424 + // TM_PROP(2401, TMT, IMAGECOUNT, INT) // the number of state images in an imagefile + // TM_PROP(2402, TMT, ALPHALEVEL, INT) // (0-255) alpha value for an icon (DrawThemeIcon part) + // TM_PROP(2403, TMT, BORDERSIZE, INT) // the size of the border line for bgtype=BorderFill + // TM_PROP(2404, TMT, ROUNDCORNERWIDTH, INT) // (0-100) % of roundness for rounded rects + // TM_PROP(2405, TMT, ROUNDCORNERHEIGHT, INT) // (0-100) % of roundness for rounded rects + // TM_PROP(2406, TMT, GRADIENTRATIO1, INT) // (0-255) - amt of gradient color 1 to use (all must total=255) + // TM_PROP(2407, TMT, GRADIENTRATIO2, INT) // (0-255) - amt of gradient color 2 to use (all must total=255) + // TM_PROP(2408, TMT, GRADIENTRATIO3, INT) // (0-255) - amt of gradient color 3 to use (all must total=255) + // TM_PROP(2409, TMT, GRADIENTRATIO4, INT) // (0-255) - amt of gradient color 4 to use (all must total=255) + // TM_PROP(2410, TMT, GRADIENTRATIO5, INT) // (0-255) - amt of gradient color 5 to use (all must total=255) + // TM_PROP(2411, TMT, PROGRESSCHUNKSIZE, INT) // size of progress control chunks + // TM_PROP(2412, TMT, PROGRESSSPACESIZE, INT) // size of progress control spaces + // TM_PROP(2413, TMT, SATURATION, INT) // (0-255) amt of saturation for DrawThemeIcon() part + // TM_PROP(2414, TMT, TEXTBORDERSIZE, INT) // size of border around text chars + // TM_PROP(2415, TMT, ALPHATHRESHOLD, INT) // (0-255) the min. alpha value of a pixel that is solid + // TM_PROP(2416, TMT, WIDTH, SIZE) // custom window prop: size of part (min. window) + // TM_PROP(2417, TMT, HEIGHT, SIZE) // custom window prop: size of part (min. window) + // TM_PROP(2418, TMT, GLYPHINDEX, INT) // for font-based glyphs, the char index into the font + // TM_PROP(2419, TMT, TRUESIZESTRETCHMARK, INT) // stretch TrueSize image when target exceeds source by this percent + // TM_PROP(2420, TMT, MINDPI1, INT) // min DPI ImageFile1 was designed for + // TM_PROP(2421, TMT, MINDPI2, INT) // min DPI ImageFile1 was designed for + // TM_PROP(2422, TMT, MINDPI3, INT) // min DPI ImageFile1 was designed for + // TM_PROP(2423, TMT, MINDPI4, INT) // min DPI ImageFile1 was designed for + // TM_PROP(2424, TMT, MINDPI5, INT) // min DPI ImageFile1 was designed for } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/MarginProperty.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/MarginProperty.cs index e33d6a47805..c4933ea65ed 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/MarginProperty.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/MarginProperty.cs @@ -11,11 +11,11 @@ namespace System.Windows.Forms.VisualStyles [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "Maps to native enum.")] public enum MarginProperty { - SizingMargins = 3601, - ContentMargins = 3602, - CaptionMargins = 3603 - // TM_PROP(3601, TMT, SIZINGMARGINS, MARGINS) // margins used for 9-grid sizing - // TM_PROP(3602, TMT, CONTENTMARGINS, MARGINS) // margins that define where content can be placed - // TM_PROP(3603, TMT, CAPTIONMARGINS, MARGINS) // margins that define where caption text can be placed + SizingMargins = 3601, + ContentMargins = 3602, + CaptionMargins = 3603 + // TM_PROP(3601, TMT, SIZINGMARGINS, MARGINS) // margins used for 9-grid sizing + // TM_PROP(3602, TMT, CONTENTMARGINS, MARGINS) // margins that define where content can be placed + // TM_PROP(3603, TMT, CAPTIONMARGINS, MARGINS) // margins that define where caption text can be placed } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/OffsetType.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/OffsetType.cs index e7595baa752..16874986fe4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/OffsetType.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/OffsetType.cs @@ -10,33 +10,33 @@ namespace System.Windows.Forms.VisualStyles { public enum OffsetType { - TopLeft = 0, - TopRight = 1, - TopMiddle = 2, - BottomLeft = 3, - BottomRight = 4, - BottomMiddle = 5, - MiddleLeft = 6, - MiddleRight = 7, - LeftOfCaption = 8, - RightOfCaption = 9, - LeftOfLastButton = 10, - RightOfLastButton = 11, - AboveLastButton = 12, - BelowLastButton = 13, - // TM_ENUM(0, OT, TOPLEFT) - // TM_ENUM(1, OT, TOPRIGHT) - // TM_ENUM(2, OT, TOPMIDDLE) - // TM_ENUM(3, OT, BOTTOMLEFT) - // TM_ENUM(4, OT, BOTTOMRIGHT) - // TM_ENUM(5, OT, BOTTOMMIDDLE) - // TM_ENUM(6, OT, MIDDLELEFT) - // TM_ENUM(7, OT, MIDDLERIGHT) - // TM_ENUM(8, OT, LEFTOFCAPTION) - // TM_ENUM(9, OT, RIGHTOFCAPTION) - // TM_ENUM(10, OT, LEFTOFLASTBUTTON) - // TM_ENUM(11, OT, RIGHTOFLASTBUTTON) - // TM_ENUM(12, OT, ABOVELASTBUTTON) - // TM_ENUM(13, OT, BELOWLASTBUTTON) + TopLeft = 0, + TopRight = 1, + TopMiddle = 2, + BottomLeft = 3, + BottomRight = 4, + BottomMiddle = 5, + MiddleLeft = 6, + MiddleRight = 7, + LeftOfCaption = 8, + RightOfCaption = 9, + LeftOfLastButton = 10, + RightOfLastButton = 11, + AboveLastButton = 12, + BelowLastButton = 13, + // TM_ENUM(0, OT, TOPLEFT) + // TM_ENUM(1, OT, TOPRIGHT) + // TM_ENUM(2, OT, TOPMIDDLE) + // TM_ENUM(3, OT, BOTTOMLEFT) + // TM_ENUM(4, OT, BOTTOMRIGHT) + // TM_ENUM(5, OT, BOTTOMMIDDLE) + // TM_ENUM(6, OT, MIDDLELEFT) + // TM_ENUM(7, OT, MIDDLERIGHT) + // TM_ENUM(8, OT, LEFTOFCAPTION) + // TM_ENUM(9, OT, RIGHTOFCAPTION) + // TM_ENUM(10, OT, LEFTOFLASTBUTTON) + // TM_ENUM(11, OT, RIGHTOFLASTBUTTON) + // TM_ENUM(12, OT, ABOVELASTBUTTON) + // TM_ENUM(13, OT, BELOWLASTBUTTON) } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/PointProperty.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/PointProperty.cs index b7187818e66..d4fccb616d1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/PointProperty.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/PointProperty.cs @@ -11,21 +11,21 @@ namespace System.Windows.Forms.VisualStyles [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "Maps to native enum.")] public enum PointProperty { - Offset = 3401, - TextShadowOffset = 3402, - MinSize = 3403, - MinSize1 = 3404, - MinSize2 = 3405, - MinSize3 = 3406, - MinSize4 = 3407, - MinSize5 = 3408 - // TM_PROP(3401, TMT, OFFSET, POSITION) // for window part layout - // TM_PROP(3402, TMT, TEXTSHADOWOFFSET, POSITION) // where char shadows are drawn, relative to orig. chars - // TM_PROP(3403, TMT, MINSIZE, POSITION) // min dest rect than ImageFile was designed for - // TM_PROP(3404, TMT, MINSIZE1, POSITION) // min dest rect than ImageFile1 was designed for - // TM_PROP(3405, TMT, MINSIZE2, POSITION) // min dest rect than ImageFile2 was designed for - // TM_PROP(3406, TMT, MINSIZE3, POSITION) // min dest rect than ImageFile3 was designed for - // TM_PROP(3407, TMT, MINSIZE4, POSITION) // min dest rect than ImageFile4 was designed for - // TM_PROP(3408, TMT, MINSIZE5, POSITION) // min dest rect than ImageFile5 was designed for + Offset = 3401, + TextShadowOffset = 3402, + MinSize = 3403, + MinSize1 = 3404, + MinSize2 = 3405, + MinSize3 = 3406, + MinSize4 = 3407, + MinSize5 = 3408 + // TM_PROP(3401, TMT, OFFSET, POSITION) // for window part layout + // TM_PROP(3402, TMT, TEXTSHADOWOFFSET, POSITION) // where char shadows are drawn, relative to orig. chars + // TM_PROP(3403, TMT, MINSIZE, POSITION) // min dest rect than ImageFile was designed for + // TM_PROP(3404, TMT, MINSIZE1, POSITION) // min dest rect than ImageFile1 was designed for + // TM_PROP(3405, TMT, MINSIZE2, POSITION) // min dest rect than ImageFile2 was designed for + // TM_PROP(3406, TMT, MINSIZE3, POSITION) // min dest rect than ImageFile3 was designed for + // TM_PROP(3407, TMT, MINSIZE4, POSITION) // min dest rect than ImageFile4 was designed for + // TM_PROP(3408, TMT, MINSIZE5, POSITION) // min dest rect than ImageFile5 was designed for } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/RadioButtonState.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/RadioButtonState.cs index 4be83464f24..33c93b8c8d6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/RadioButtonState.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/RadioButtonState.cs @@ -11,13 +11,13 @@ namespace System.Windows.Forms.VisualStyles [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")] public enum RadioButtonState { - UncheckedNormal = 1, - UncheckedHot = 2, - UncheckedPressed = 3, - UncheckedDisabled = 4, - CheckedNormal = 5, - CheckedHot = 6, - CheckedPressed = 7, + UncheckedNormal = 1, + UncheckedHot = 2, + UncheckedPressed = 3, + UncheckedDisabled = 4, + CheckedNormal = 5, + CheckedHot = 6, + CheckedPressed = 7, CheckedDisabled = 8 - } + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/SizingType.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/SizingType.cs index 2c0526a8da5..080f68f7800 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/SizingType.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/SizingType.cs @@ -8,13 +8,13 @@ namespace System.Windows.Forms.VisualStyles { - public enum SizingType + public enum SizingType { - FixedSize = 0, - Stretch = 1, - Tile = 2, - // TM_ENUM(0, ST, TRUESIZE) - // TM_ENUM(1, ST, STRETCH) - // TM_ENUM(2, ST, TILE) + FixedSize = 0, + Stretch = 1, + Tile = 2, + // TM_ENUM(0, ST, TRUESIZE) + // TM_ENUM(1, ST, STRETCH) + // TM_ENUM(2, ST, TILE) } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/StringProperty.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/StringProperty.cs index d6eed31d986..06b8c2e95a9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/StringProperty.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/StringProperty.cs @@ -11,7 +11,7 @@ namespace System.Windows.Forms.VisualStyles [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "Maps to native enum.")] public enum StringProperty { - Text = 3201 - //TM_PROP(3201, TMT, TEXT, STRING) + Text = 3201 + //TM_PROP(3201, TMT, TEXT, STRING) } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/TextMetrics.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/TextMetrics.cs index 8d7979aca1d..8d50f24dd9b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/TextMetrics.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/TextMetrics.cs @@ -9,45 +9,45 @@ namespace System.Windows.Forms.VisualStyles { public struct TextMetrics - { - public int Height { get; set; } + { + public int Height { get; set; } - public int Ascent { get; set; } + public int Ascent { get; set; } - public int Descent { get; set; } + public int Descent { get; set; } - public int InternalLeading { get; set; } + public int InternalLeading { get; set; } - public int ExternalLeading { get; set; } + public int ExternalLeading { get; set; } - public int AverageCharWidth { get; set; } + public int AverageCharWidth { get; set; } - public int MaxCharWidth { get; set; } + public int MaxCharWidth { get; set; } - public int Weight { get; set; } + public int Weight { get; set; } - public int Overhang { get; set; } + public int Overhang { get; set; } - public int DigitizedAspectX { get; set; } + public int DigitizedAspectX { get; set; } - public int DigitizedAspectY { get; set; } + public int DigitizedAspectY { get; set; } - public char FirstChar { get; set; } + public char FirstChar { get; set; } - public char LastChar { get; set; } + public char LastChar { get; set; } - public char DefaultChar { get; set; } + public char DefaultChar { get; set; } - public char BreakChar { get; set; } + public char BreakChar { get; set; } - public bool Italic { get; set; } + public bool Italic { get; set; } - public bool Underlined { get; set; } + public bool Underlined { get; set; } - public bool StruckOut { get; set; } + public bool StruckOut { get; set; } - public TextMetricsPitchAndFamilyValues PitchAndFamily { get; set; } + public TextMetricsPitchAndFamilyValues PitchAndFamily { get; set; } - public TextMetricsCharacterSet CharSet { get; set; } - } + public TextMetricsCharacterSet CharSet { get; set; } + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/TextMetricsCharacterSet.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/TextMetricsCharacterSet.cs index 19f25ea2572..c99d2d81196 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/TextMetricsCharacterSet.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/TextMetricsCharacterSet.cs @@ -10,49 +10,49 @@ namespace System.Windows.Forms.VisualStyles { public enum TextMetricsCharacterSet { - Ansi = 0, - Baltic = 186, - ChineseBig5 = 136, - Default = 1, - EastEurope = 238, - Gb2312 = 134, - Greek = 161, - Hangul = 129, - Mac = 77, - Oem = 255, - Russian = 204, - ShiftJis = 128, - Symbol = 2, - Turkish = 162, - Vietnamese = 163, - Johab = 130, - Arabic = 178, - Hebrew = 177, - Thai = 222, - // #define ANSI_CHARSET 0 - // #define BALTIC_CHARSET 186 - // #define CHINESEBIG5_CHARSET 136 - // #define DEFAULT_CHARSET 1 - // #define EASTEUROPE_CHARSET 238 - // #define GB2312_CHARSET 134 - // #define GREEK_CHARSET 161 - // #define HANGUL_CHARSET 129 - // #define MAC_CHARSET 77 - // #define OEM_CHARSET 255 - // #define RUSSIAN_CHARSET 204 - // #define SHIFTJIS_CHARSET 128 - // #define SYMBOL_CHARSET 2 - // #define TURKISH_CHARSET 162 - // #define VIETNAMESE_CHARSET 163 + Ansi = 0, + Baltic = 186, + ChineseBig5 = 136, + Default = 1, + EastEurope = 238, + Gb2312 = 134, + Greek = 161, + Hangul = 129, + Mac = 77, + Oem = 255, + Russian = 204, + ShiftJis = 128, + Symbol = 2, + Turkish = 162, + Vietnamese = 163, + Johab = 130, + Arabic = 178, + Hebrew = 177, + Thai = 222, + // #define ANSI_CHARSET 0 + // #define BALTIC_CHARSET 186 + // #define CHINESEBIG5_CHARSET 136 + // #define DEFAULT_CHARSET 1 + // #define EASTEUROPE_CHARSET 238 + // #define GB2312_CHARSET 134 + // #define GREEK_CHARSET 161 + // #define HANGUL_CHARSET 129 + // #define MAC_CHARSET 77 + // #define OEM_CHARSET 255 + // #define RUSSIAN_CHARSET 204 + // #define SHIFTJIS_CHARSET 128 + // #define SYMBOL_CHARSET 2 + // #define TURKISH_CHARSET 162 + // #define VIETNAMESE_CHARSET 163 - // Korean - // #define JOHAB_CHARSET 130 + // Korean + // #define JOHAB_CHARSET 130 - // Middle East - // #define ARABIC_CHARSET 178 - // #define HEBREW_CHARSET 177 + // Middle East + // #define ARABIC_CHARSET 178 + // #define HEBREW_CHARSET 177 - // Thai - // #define THAI_CHARSET 222 + // Thai + // #define THAI_CHARSET 222 } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/TextMetricsPitchAndFamilyValues.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/TextMetricsPitchAndFamilyValues.cs index 02c5b53d945..7b3da331bd7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/TextMetricsPitchAndFamilyValues.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/TextMetricsPitchAndFamilyValues.cs @@ -11,14 +11,14 @@ namespace System.Windows.Forms.VisualStyles [Flags] public enum TextMetricsPitchAndFamilyValues { - FixedPitch = 0x01, - Vector = 0x02, + FixedPitch = 0x01, + Vector = 0x02, TrueType = 0x04, - Device = 0x08 + Device = 0x08 - // #define TMPF_FIXED_PITCH 0x01 - // #define TMPF_VECTOR 0x02 - // #define TMPF_DEVICE 0x08 - // #define TMPF_TRUETYPE 0x04 + // #define TMPF_FIXED_PITCH 0x01 + // #define TMPF_VECTOR 0x02 + // #define TMPF_DEVICE 0x08 + // #define TMPF_TRUETYPE 0x04 } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/TextShadowType.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/TextShadowType.cs index 6ed9a58221c..50b07590adc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/TextShadowType.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/TextShadowType.cs @@ -10,11 +10,11 @@ namespace System.Windows.Forms.VisualStyles { public enum TextShadowType { - None = 0, - Single = 1, - Continuous = 2, - // TM_ENUM(0, TST, NONE) - // TM_ENUM(1, TST, SINGLE) - // TM_ENUM(2, TST, CONTINUOUS) + None = 0, + Single = 1, + Continuous = 2, + // TM_ENUM(0, TST, NONE) + // TM_ENUM(1, TST, SINGLE) + // TM_ENUM(2, TST, CONTINUOUS) } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/TrueSizeScalingType.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/TrueSizeScalingType.cs index 5d604ff951c..c07363f5dc8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/TrueSizeScalingType.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/TrueSizeScalingType.cs @@ -10,11 +10,11 @@ namespace System.Windows.Forms.VisualStyles { public enum TrueSizeScalingType { - None = 0, - Size = 1, - Dpi = 2, - // TM_ENUM(0, TSST, NONE) - // TM_ENUM(1, TSST, SIZE) - // TM_ENUM(2, TSST, DPI) + None = 0, + Size = 1, + Dpi = 2, + // TM_ENUM(0, TSST, NONE) + // TM_ENUM(1, TSST, SIZE) + // TM_ENUM(2, TSST, DPI) } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VerticalAlignment.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VerticalAlignment.cs index 8d4bcdd25f7..beed211663c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VerticalAlignment.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VerticalAlignment.cs @@ -10,11 +10,11 @@ namespace System.Windows.Forms.VisualStyles { public enum VerticalAlignment { - Top = 0, - Center = 1, - Bottom = 2, - // TM_ENUM(0, VA, TOP) - // TM_ENUM(1, VA, CENTER) - // TM_ENUM(2, VA, BOTTOM) + Top = 0, + Center = 1, + Bottom = 2, + // TM_ENUM(0, VA, TOP) + // TM_ENUM(1, VA, CENTER) + // TM_ENUM(2, VA, BOTTOM) } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleElement.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleElement.cs index 80ea269823e..f62c13e0cf3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleElement.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleElement.cs @@ -6,20 +6,21 @@ // Using nested types here is an intentional design. -[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope="type", Target="System.Windows.Forms.VisualStyles.VisualStyleElement+Taskbar+SizingBarLeft")] -[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope="type", Target="System.Windows.Forms.VisualStyles.VisualStyleElement+Taskbar+BackgroundLeft")] -[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope="type", Target="System.Windows.Forms.VisualStyles.VisualStyleElement+Taskbar+BackgroundBottom")] -[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope="type", Target="System.Windows.Forms.VisualStyles.VisualStyleElement+Taskbar+SizingBarTop")] -[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope="type", Target="System.Windows.Forms.VisualStyles.VisualStyleElement+TaskbarClock+Time")] -[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope="type", Target="System.Windows.Forms.VisualStyles.VisualStyleElement+Taskbar+BackgroundTop")] -[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope="type", Target="System.Windows.Forms.VisualStyles.VisualStyleElement+Taskbar+SizingBarBottom")] -[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope="type", Target="System.Windows.Forms.VisualStyles.VisualStyleElement+TaskbarClock")] -[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope="type", Target="System.Windows.Forms.VisualStyles.VisualStyleElement+Taskbar")] -[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope="type", Target="System.Windows.Forms.VisualStyles.VisualStyleElement+Taskbar+BackgroundRight")] -[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope="type", Target="System.Windows.Forms.VisualStyles.VisualStyleElement+Taskbar+SizingBarRight")] -[assembly: SuppressMessage("Microsoft.MSInternal", "CA905:SystemAndMicrosoftNamespacesRequireApproval", Scope="namespace", Target="System.Windows.Forms.VisualStyles")] - -namespace System.Windows.Forms.VisualStyles { +[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope = "type", Target = "System.Windows.Forms.VisualStyles.VisualStyleElement+Taskbar+SizingBarLeft")] +[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope = "type", Target = "System.Windows.Forms.VisualStyles.VisualStyleElement+Taskbar+BackgroundLeft")] +[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope = "type", Target = "System.Windows.Forms.VisualStyles.VisualStyleElement+Taskbar+BackgroundBottom")] +[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope = "type", Target = "System.Windows.Forms.VisualStyles.VisualStyleElement+Taskbar+SizingBarTop")] +[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope = "type", Target = "System.Windows.Forms.VisualStyles.VisualStyleElement+TaskbarClock+Time")] +[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope = "type", Target = "System.Windows.Forms.VisualStyles.VisualStyleElement+Taskbar+BackgroundTop")] +[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope = "type", Target = "System.Windows.Forms.VisualStyles.VisualStyleElement+Taskbar+SizingBarBottom")] +[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope = "type", Target = "System.Windows.Forms.VisualStyles.VisualStyleElement+TaskbarClock")] +[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope = "type", Target = "System.Windows.Forms.VisualStyles.VisualStyleElement+Taskbar")] +[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope = "type", Target = "System.Windows.Forms.VisualStyles.VisualStyleElement+Taskbar+BackgroundRight")] +[assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope = "type", Target = "System.Windows.Forms.VisualStyles.VisualStyleElement+Taskbar+SizingBarRight")] +[assembly: SuppressMessage("Microsoft.MSInternal", "CA905:SystemAndMicrosoftNamespacesRequireApproval", Scope = "namespace", Target = "System.Windows.Forms.VisualStyles")] + +namespace System.Windows.Forms.VisualStyles +{ /// /// @@ -28,458 +29,571 @@ namespace System.Windows.Forms.VisualStyles { /// Usage pattern is something like this: new VisualStyleRenderer(VisualStyleElement.Window.Caption.Active); /// /// - public class VisualStyleElement { + public class VisualStyleElement + { internal static readonly int Count = 25; //UPDATE THIS WHEN CLASSES ARE ADDED/REMOVED! private string className; private int part; private int state; - - private VisualStyleElement(string className, int part, int state) { + + private VisualStyleElement(string className, int part, int state) + { this.className = className; this.part = part; this.state = state; } - - public static VisualStyleElement CreateElement(string className, int part, int state) { + + public static VisualStyleElement CreateElement(string className, int part, int state) + { return new VisualStyleElement(className, part, state); } - - public string ClassName { - get { + + public string ClassName + { + get + { return className; } } - public int Part { - get { + public int Part + { + get + { return part; } } - public int State { - get { + public int State + { + get + { return state; } } - public static class Button { + public static class Button + { private static readonly string className = "BUTTON"; - public static class PushButton { + public static class PushButton + { private static readonly int part = 1; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } private static VisualStyleElement hot; - public static VisualStyleElement Hot { - get { - if (hot == null) { + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } private static VisualStyleElement _default; - public static VisualStyleElement Default { - get { - if (_default == null) { + public static VisualStyleElement Default + { + get + { + if (_default == null) + { _default = new VisualStyleElement(className, part, 5); } - + return _default; } } } - public static class RadioButton { + public static class RadioButton + { private static readonly int part = 2; // in Win10 RS3 a new part was added to BUTTONPARTS enum in vsstyle.h - BP_RADIOBUTTON_HCDISABLED = 8 internal static readonly int HighContrastDisabledPart = 8; private static VisualStyleElement uncheckednormal; - - public static VisualStyleElement UncheckedNormal { - get { - if (uncheckednormal == null) { + + public static VisualStyleElement UncheckedNormal + { + get + { + if (uncheckednormal == null) + { uncheckednormal = new VisualStyleElement(className, part, 1); } - + return uncheckednormal; } } private static VisualStyleElement uncheckedhot; - public static VisualStyleElement UncheckedHot { - get { - if (uncheckedhot == null) { + public static VisualStyleElement UncheckedHot + { + get + { + if (uncheckedhot == null) + { uncheckedhot = new VisualStyleElement(className, part, 2); } - + return uncheckedhot; } } - + private static VisualStyleElement uncheckedpressed; - public static VisualStyleElement UncheckedPressed { - get { - if (uncheckedpressed == null) { + public static VisualStyleElement UncheckedPressed + { + get + { + if (uncheckedpressed == null) + { uncheckedpressed = new VisualStyleElement(className, part, 3); } - + return uncheckedpressed; } } private static VisualStyleElement uncheckeddisabled; - - public static VisualStyleElement UncheckedDisabled { - get { - if (uncheckeddisabled == null) { + + public static VisualStyleElement UncheckedDisabled + { + get + { + if (uncheckeddisabled == null) + { uncheckeddisabled = new VisualStyleElement(className, part, 4); } - + return uncheckeddisabled; } } private static VisualStyleElement checkednormal; - - public static VisualStyleElement CheckedNormal { - get { - if (checkednormal == null) { + + public static VisualStyleElement CheckedNormal + { + get + { + if (checkednormal == null) + { checkednormal = new VisualStyleElement(className, part, 5); } - + return checkednormal; } } private static VisualStyleElement checkedhot; - public static VisualStyleElement CheckedHot { - get { - if (checkedhot == null) { + public static VisualStyleElement CheckedHot + { + get + { + if (checkedhot == null) + { checkedhot = new VisualStyleElement(className, part, 6); } - + return checkedhot; } } - + private static VisualStyleElement checkedpressed; - public static VisualStyleElement CheckedPressed { - get { - if (checkedpressed == null) { + public static VisualStyleElement CheckedPressed + { + get + { + if (checkedpressed == null) + { checkedpressed = new VisualStyleElement(className, part, 7); } - + return checkedpressed; } } private static VisualStyleElement checkeddisabled; - - public static VisualStyleElement CheckedDisabled { - get { - if (checkeddisabled == null) { + + public static VisualStyleElement CheckedDisabled + { + get + { + if (checkeddisabled == null) + { checkeddisabled = new VisualStyleElement(className, part, 8); } - + return checkeddisabled; } } } - public static class CheckBox { + public static class CheckBox + { private static readonly int part = 3; // in Win10 RS3 a new part was added to BUTTONPARTS enum in vsstyle.h - BP_CHECKBOX_HCDISABLED = 9 internal static readonly int HighContrastDisabledPart = 9; private static VisualStyleElement uncheckednormal; - - public static VisualStyleElement UncheckedNormal { - get { - if (uncheckednormal == null) { + + public static VisualStyleElement UncheckedNormal + { + get + { + if (uncheckednormal == null) + { uncheckednormal = new VisualStyleElement(className, part, 1); } - + return uncheckednormal; } } private static VisualStyleElement uncheckedhot; - public static VisualStyleElement UncheckedHot { - get { - if (uncheckedhot == null) { + public static VisualStyleElement UncheckedHot + { + get + { + if (uncheckedhot == null) + { uncheckedhot = new VisualStyleElement(className, part, 2); } - + return uncheckedhot; } } - + private static VisualStyleElement uncheckedpressed; - public static VisualStyleElement UncheckedPressed { - get { - if (uncheckedpressed == null) { + public static VisualStyleElement UncheckedPressed + { + get + { + if (uncheckedpressed == null) + { uncheckedpressed = new VisualStyleElement(className, part, 3); } - + return uncheckedpressed; } } private static VisualStyleElement uncheckeddisabled; - - public static VisualStyleElement UncheckedDisabled { - get { - if (uncheckeddisabled == null) { + + public static VisualStyleElement UncheckedDisabled + { + get + { + if (uncheckeddisabled == null) + { uncheckeddisabled = new VisualStyleElement(className, part, 4); } - + return uncheckeddisabled; } } private static VisualStyleElement checkednormal; - - public static VisualStyleElement CheckedNormal { - get { - if (checkednormal == null) { + + public static VisualStyleElement CheckedNormal + { + get + { + if (checkednormal == null) + { checkednormal = new VisualStyleElement(className, part, 5); } - + return checkednormal; } } private static VisualStyleElement checkedhot; - public static VisualStyleElement CheckedHot { - get { - if (checkedhot == null) { + public static VisualStyleElement CheckedHot + { + get + { + if (checkedhot == null) + { checkedhot = new VisualStyleElement(className, part, 6); } - + return checkedhot; } } - + private static VisualStyleElement checkedpressed; - public static VisualStyleElement CheckedPressed { - get { - if (checkedpressed == null) { + public static VisualStyleElement CheckedPressed + { + get + { + if (checkedpressed == null) + { checkedpressed = new VisualStyleElement(className, part, 7); } - + return checkedpressed; } } private static VisualStyleElement checkeddisabled; - - public static VisualStyleElement CheckedDisabled { - get { - if (checkeddisabled == null) { + + public static VisualStyleElement CheckedDisabled + { + get + { + if (checkeddisabled == null) + { checkeddisabled = new VisualStyleElement(className, part, 8); } - + return checkeddisabled; } } private static VisualStyleElement mixednormal; - - public static VisualStyleElement MixedNormal { - get { - if (mixednormal == null) { + + public static VisualStyleElement MixedNormal + { + get + { + if (mixednormal == null) + { mixednormal = new VisualStyleElement(className, part, 9); } - + return mixednormal; } } private static VisualStyleElement mixedhot; - public static VisualStyleElement MixedHot { - get { - if (mixedhot == null) { + public static VisualStyleElement MixedHot + { + get + { + if (mixedhot == null) + { mixedhot = new VisualStyleElement(className, part, 10); } - + return mixedhot; } } - + private static VisualStyleElement mixedpressed; - public static VisualStyleElement MixedPressed { - get { - if (mixedpressed == null) { + public static VisualStyleElement MixedPressed + { + get + { + if (mixedpressed == null) + { mixedpressed = new VisualStyleElement(className, part, 11); } - + return mixedpressed; } } private static VisualStyleElement mixeddisabled; - - public static VisualStyleElement MixedDisabled { - get { - if (mixeddisabled == null) { + + public static VisualStyleElement MixedDisabled + { + get + { + if (mixeddisabled == null) + { mixeddisabled = new VisualStyleElement(className, part, 12); } - + return mixeddisabled; } } } - public static class GroupBox { + public static class GroupBox + { private static readonly int part = 4; // in Win10 RS3 a new part was added to BUTTONPARTS enum in vsstyle.h - BP_GROUPBOX_HCDISABLED = 10 internal static readonly int HighContrastDisabledPart = 10; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 2); } - + return disabled; } } } - public static class UserButton { + public static class UserButton + { private static readonly int part = 5; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } } //END BUTTON - public static class ComboBox { + public static class ComboBox + { private static readonly string className = "COMBOBOX"; - public static class DropDownButton { + public static class DropDownButton + { private static readonly int part = 1; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } @@ -659,2709 +773,3364 @@ public static VisualStyleElement Normal */ } //END COMBOBOX - public static class Page { + public static class Page + { private static readonly string className = "PAGE"; - public static class Up { + public static class Up + { private static readonly int part = 1; private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class Down { + public static class Down + { private static readonly int part = 2; private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class UpHorizontal { + public static class UpHorizontal + { private static readonly int part = 3; private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class DownHorizontal { + public static class DownHorizontal + { private static readonly int part = 4; private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } } //END PAGE - public static class Spin { + public static class Spin + { private static readonly string className = "SPIN"; - public static class Up { + public static class Up + { private static readonly int part = 1; private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class Down { + public static class Down + { private static readonly int part = 2; private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class UpHorizontal { + public static class UpHorizontal + { private static readonly int part = 3; private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class DownHorizontal { + public static class DownHorizontal + { private static readonly int part = 4; private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } } //END SPIN - public static class ScrollBar { + public static class ScrollBar + { private static readonly string className = "SCROLLBAR"; - public static class ArrowButton { + public static class ArrowButton + { private static readonly int part = 1; private static VisualStyleElement upnormal; - - public static VisualStyleElement UpNormal { - get { - if (upnormal == null) { + + public static VisualStyleElement UpNormal + { + get + { + if (upnormal == null) + { upnormal = new VisualStyleElement(className, part, 1); } - + return upnormal; } } - + private static VisualStyleElement uphot; - - public static VisualStyleElement UpHot { - get { - if (uphot == null) { - uphot = new VisualStyleElement(className, part, 2); - } - + + public static VisualStyleElement UpHot + { + get + { + if (uphot == null) + { + uphot = new VisualStyleElement(className, part, 2); + } + return uphot; } } - + private static VisualStyleElement uppressed; - - public static VisualStyleElement UpPressed { - get { - if (uppressed == null) { + + public static VisualStyleElement UpPressed + { + get + { + if (uppressed == null) + { uppressed = new VisualStyleElement(className, part, 3); } - + return uppressed; } } - + private static VisualStyleElement updisabled; - - public static VisualStyleElement UpDisabled { - get { - if (updisabled == null) { + + public static VisualStyleElement UpDisabled + { + get + { + if (updisabled == null) + { updisabled = new VisualStyleElement(className, part, 4); } - + return updisabled; } } private static VisualStyleElement downnormal; - - public static VisualStyleElement DownNormal { - get { - if (downnormal == null) { + + public static VisualStyleElement DownNormal + { + get + { + if (downnormal == null) + { downnormal = new VisualStyleElement(className, part, 5); } - + return downnormal; } } - + private static VisualStyleElement downhot; - - public static VisualStyleElement DownHot { - get { - if (downhot == null) { + + public static VisualStyleElement DownHot + { + get + { + if (downhot == null) + { downhot = new VisualStyleElement(className, part, 6); } - + return downhot; } } - + private static VisualStyleElement downpressed; - - public static VisualStyleElement DownPressed { - get { - if (downpressed == null) { + + public static VisualStyleElement DownPressed + { + get + { + if (downpressed == null) + { downpressed = new VisualStyleElement(className, part, 7); } - + return downpressed; } } - + private static VisualStyleElement downdisabled; - - public static VisualStyleElement DownDisabled { - get { - if (downdisabled == null) { + + public static VisualStyleElement DownDisabled + { + get + { + if (downdisabled == null) + { downdisabled = new VisualStyleElement(className, part, 8); } - + return downdisabled; } } private static VisualStyleElement leftnormal; - - public static VisualStyleElement LeftNormal { - get { - if (leftnormal == null) { + + public static VisualStyleElement LeftNormal + { + get + { + if (leftnormal == null) + { leftnormal = new VisualStyleElement(className, part, 9); } - + return leftnormal; } } - + private static VisualStyleElement lefthot; - - public static VisualStyleElement LeftHot { - get { - if (lefthot == null) { + + public static VisualStyleElement LeftHot + { + get + { + if (lefthot == null) + { lefthot = new VisualStyleElement(className, part, 10); } - + return lefthot; } } - + private static VisualStyleElement leftpressed; - - public static VisualStyleElement LeftPressed { - get { - if (leftpressed == null) { + + public static VisualStyleElement LeftPressed + { + get + { + if (leftpressed == null) + { leftpressed = new VisualStyleElement(className, part, 11); } - + return leftpressed; } } - + private static VisualStyleElement leftdisabled; - - public static VisualStyleElement LeftDisabled { - get { - if (leftdisabled == null) { + + public static VisualStyleElement LeftDisabled + { + get + { + if (leftdisabled == null) + { leftdisabled = new VisualStyleElement(className, part, 12); } - + return leftdisabled; } } private static VisualStyleElement rightnormal; - - public static VisualStyleElement RightNormal { - get { - if (rightnormal == null) { + + public static VisualStyleElement RightNormal + { + get + { + if (rightnormal == null) + { rightnormal = new VisualStyleElement(className, part, 13); } - + return rightnormal; } } - + private static VisualStyleElement righthot; - - public static VisualStyleElement RightHot { - get { - if (righthot == null) { + + public static VisualStyleElement RightHot + { + get + { + if (righthot == null) + { righthot = new VisualStyleElement(className, part, 14); } - + return righthot; } } - + private static VisualStyleElement rightpressed; - - public static VisualStyleElement RightPressed { - get { - if (rightpressed == null) { + + public static VisualStyleElement RightPressed + { + get + { + if (rightpressed == null) + { rightpressed = new VisualStyleElement(className, part, 15); } - + return rightpressed; } } - + private static VisualStyleElement rightdisabled; - - public static VisualStyleElement RightDisabled { - get { - if (rightdisabled == null) { + + public static VisualStyleElement RightDisabled + { + get + { + if (rightdisabled == null) + { rightdisabled = new VisualStyleElement(className, part, 16); } - + return rightdisabled; } } } - public static class ThumbButtonHorizontal { + public static class ThumbButtonHorizontal + { private static readonly int part = 2; - + private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class ThumbButtonVertical { + public static class ThumbButtonVertical + { private static readonly int part = 3; - + private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class RightTrackHorizontal { + public static class RightTrackHorizontal + { private static readonly int part = 4; - + private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class LeftTrackHorizontal { + public static class LeftTrackHorizontal + { private static readonly int part = 5; - + private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class LowerTrackVertical { + public static class LowerTrackVertical + { private static readonly int part = 6; - + private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class UpperTrackVertical { + public static class UpperTrackVertical + { private static readonly int part = 7; private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class GripperHorizontal { + public static class GripperHorizontal + { private static readonly int part = 8; - + private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class GripperVertical { + public static class GripperVertical + { private static readonly int part = 9; private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class SizeBox { + public static class SizeBox + { private static readonly int part = 10; private static VisualStyleElement rightalign; - - public static VisualStyleElement RightAlign { - get { - if (rightalign == null) { + + public static VisualStyleElement RightAlign + { + get + { + if (rightalign == null) + { rightalign = new VisualStyleElement(className, part, 1); } - + return rightalign; } } private static VisualStyleElement leftalign; - - public static VisualStyleElement LeftAlign { - get { - if (leftalign == null) { + + public static VisualStyleElement LeftAlign + { + get + { + if (leftalign == null) + { leftalign = new VisualStyleElement(className, part, 2); } - + return leftalign; } } } } // END SCROLLBAR - public static class Tab { + public static class Tab + { private static readonly string className = "TAB"; - public static class TabItem { + public static class TabItem + { private static readonly int part = 1; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class TabItemLeftEdge { + public static class TabItemLeftEdge + { private static readonly int part = 2; - + private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class TabItemRightEdge { + public static class TabItemRightEdge + { private static readonly int part = 3; - + private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class TabItemBothEdges { + public static class TabItemBothEdges + { private static readonly int part = 4; - + private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class TopTabItem { + public static class TopTabItem + { private static readonly int part = 5; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } - + } - public static class TopTabItemLeftEdge { + public static class TopTabItemLeftEdge + { private static readonly int part = 6; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { - normal = new VisualStyleElement(className, part, 1); - } - - return normal; - } - } - - private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { + normal = new VisualStyleElement(className, part, 1); + } + + return normal; + } + } + + private static VisualStyleElement hot; + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class TopTabItemRightEdge { + public static class TopTabItemRightEdge + { private static readonly int part = 7; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } - + } - public static class TopTabItemBothEdges { + public static class TopTabItemBothEdges + { private static readonly int part = 8; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class Pane { + public static class Pane + { private static readonly int part = 9; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } - + } - public static class Body { + public static class Body + { private static readonly int part = 10; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } - + } } // END TAB - public static class ExplorerBar { + public static class ExplorerBar + { private static readonly string className = "EXPLORERBAR"; - public static class HeaderBackground { + public static class HeaderBackground + { private static readonly int part = 1; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } - + } - public static class HeaderClose { + public static class HeaderClose + { private static readonly int part = 2; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } } - public static class HeaderPin { + public static class HeaderPin + { private static readonly int part = 3; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } private static VisualStyleElement selectednormal; - - public static VisualStyleElement SelectedNormal { - get { - if (selectednormal == null) { + + public static VisualStyleElement SelectedNormal + { + get + { + if (selectednormal == null) + { selectednormal = new VisualStyleElement(className, part, 4); } - + return selectednormal; } } - + private static VisualStyleElement selectedhot; - - public static VisualStyleElement SelectedHot { - get { - if (selectedhot == null) { + + public static VisualStyleElement SelectedHot + { + get + { + if (selectedhot == null) + { selectedhot = new VisualStyleElement(className, part, 5); } - + return selectedhot; } } - + private static VisualStyleElement selectedpressed; - - public static VisualStyleElement SelectedPressed { - get { - if (selectedpressed == null) { + + public static VisualStyleElement SelectedPressed + { + get + { + if (selectedpressed == null) + { selectedpressed = new VisualStyleElement(className, part, 6); } - + return selectedpressed; } } } - public static class IEBarMenu { + public static class IEBarMenu + { private static readonly int part = 4; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } } - public static class NormalGroupBackground { + public static class NormalGroupBackground + { private static readonly int part = 5; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } - + } - - public static class NormalGroupCollapse { + + public static class NormalGroupCollapse + { private static readonly int part = 6; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } } - - public static class NormalGroupExpand { + + public static class NormalGroupExpand + { private static readonly int part = 7; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } } - - public static class NormalGroupHead { + + public static class NormalGroupHead + { private static readonly int part = 8; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - - public static class SpecialGroupBackground { + + public static class SpecialGroupBackground + { private static readonly int part = 9; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } - + } - - public static class SpecialGroupCollapse { + + public static class SpecialGroupCollapse + { private static readonly int part = 10; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } } - - public static class SpecialGroupExpand { + + public static class SpecialGroupExpand + { private static readonly int part = 11; - + private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } } - - public static class SpecialGroupHead { + + public static class SpecialGroupHead + { private static readonly int part = 12; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } - + } } // END EXPLORERBAR - public static class Header { + public static class Header + { private static readonly string className = "HEADER"; - public static class Item { + public static class Item + { private static readonly int part = 1; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } } - public static class ItemLeft { + public static class ItemLeft + { private static readonly int part = 2; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } } - public static class ItemRight { + public static class ItemRight + { private static readonly int part = 3; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } } - public static class SortArrow { + public static class SortArrow + { private static readonly int part = 4; private static VisualStyleElement sortedup; - - public static VisualStyleElement SortedUp { - get { - if (sortedup == null) { + + public static VisualStyleElement SortedUp + { + get + { + if (sortedup == null) + { sortedup = new VisualStyleElement(className, part, 1); } - + return sortedup; } } private static VisualStyleElement sorteddown; - - public static VisualStyleElement SortedDown { - get { - if (sorteddown == null) { + + public static VisualStyleElement SortedDown + { + get + { + if (sorteddown == null) + { sorteddown = new VisualStyleElement(className, part, 2); } - + return sorteddown; } } } } // END HEADER - public static class ListView { + public static class ListView + { private static readonly string className = "LISTVIEW"; - public static class Item { + public static class Item + { private static readonly int part = 1; private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement selected; - - public static VisualStyleElement Selected { - get { - if (selected == null) { + + public static VisualStyleElement Selected + { + get + { + if (selected == null) + { selected = new VisualStyleElement(className, part, 3); } - + return selected; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } private static VisualStyleElement selectednotfocus; - - public static VisualStyleElement SelectedNotFocus { - get { - if (selectednotfocus == null) { + + public static VisualStyleElement SelectedNotFocus + { + get + { + if (selectednotfocus == null) + { selectednotfocus = new VisualStyleElement(className, part, 5); } - + return selectednotfocus; } } } - public static class Group { + public static class Group + { private static readonly int part = 2; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { - normal = new VisualStyleElement(className, part, 0); - } - - return normal; - } - } + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { + normal = new VisualStyleElement(className, part, 0); + } + + return normal; + } + } } - public static class Detail { + public static class Detail + { private static readonly int part = 3; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; - } + } } } - public static class SortedDetail { + public static class SortedDetail + { private static readonly int part = 4; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; - } + } } } - public static class EmptyText { + public static class EmptyText + { private static readonly int part = 5; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; - } + } } } } // END LISTVIEW - public static class MenuBand { + public static class MenuBand + { private static readonly string className = "MENUBAND"; - public static class NewApplicationButton { + public static class NewApplicationButton + { private static readonly int part = 1; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } private static VisualStyleElement _checked; - - public static VisualStyleElement Checked { - get { - if (_checked == null) { + + public static VisualStyleElement Checked + { + get + { + if (_checked == null) + { _checked = new VisualStyleElement(className, part, 5); } - + return _checked; } } private static VisualStyleElement hotchecked; - - public static VisualStyleElement HotChecked { - get { - if (hotchecked == null) { + + public static VisualStyleElement HotChecked + { + get + { + if (hotchecked == null) + { hotchecked = new VisualStyleElement(className, part, 6); } - + return hotchecked; } } } - - public static class Separator { + + public static class Separator + { private static readonly int part = 2; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } } // END MENUBAND - public static class Menu { + public static class Menu + { private static readonly string className = "MENU"; - public static class Item { + public static class Item + { private static readonly int part = 1; private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } private static VisualStyleElement selected; - - public static VisualStyleElement Selected { - get { - if (selected == null) { + + public static VisualStyleElement Selected + { + get + { + if (selected == null) + { selected = new VisualStyleElement(className, part, 2); } - + return selected; } } - + private static VisualStyleElement demoted; - - public static VisualStyleElement Demoted { - get { - if (demoted == null) { + + public static VisualStyleElement Demoted + { + get + { + if (demoted == null) + { demoted = new VisualStyleElement(className, part, 3); } - + return demoted; } } } - public static class DropDown { + public static class DropDown + { private static readonly int part = 2; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class BarItem { + public static class BarItem + { private static readonly int part = 3; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class BarDropDown { + public static class BarDropDown + { private static readonly int part = 4; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class Chevron { + public static class Chevron + { private static readonly int part = 5; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - - public static class Separator { + + public static class Separator + { private static readonly int part = 6; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } } // END MENU - public static class ProgressBar { + public static class ProgressBar + { private static readonly string className = "PROGRESS"; - public static class Bar { + public static class Bar + { private static readonly int part = 1; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class BarVertical { + public static class BarVertical + { private static readonly int part = 2; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class Chunk { + public static class Chunk + { private static readonly int part = 3; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class ChunkVertical { + public static class ChunkVertical + { private static readonly int part = 4; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } } // END PROGRESSBAR - public static class Rebar { + public static class Rebar + { private static readonly string className = "REBAR"; - public static class Gripper { + public static class Gripper + { private static readonly int part = 1; - + private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class GripperVertical { + public static class GripperVertical + { private static readonly int part = 2; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class Band { + public static class Band + { private static readonly int part = 3; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class Chevron { + public static class Chevron + { private static readonly int part = 4; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { - pressed = new VisualStyleElement(className, part, 3); - } - - return pressed; - } - } + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { + pressed = new VisualStyleElement(className, part, 3); + } + + return pressed; + } + } } - public static class ChevronVertical { + public static class ChevronVertical + { private static readonly int part = 5; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } } } // END REBAR - public static class StartPanel { + public static class StartPanel + { private static readonly string className = "STARTPANEL"; - - public static class UserPane { + + public static class UserPane + { private static readonly int part = 1; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class MorePrograms { + public static class MorePrograms + { private static readonly int part = 2; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class MoreProgramsArrow { + public static class MoreProgramsArrow + { private static readonly int part = 3; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } } - public static class ProgList { + public static class ProgList + { private static readonly int part = 4; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class ProgListSeparator { + public static class ProgListSeparator + { private static readonly int part = 5; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class PlaceList { + public static class PlaceList + { private static readonly int part = 6; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class PlaceListSeparator { + public static class PlaceListSeparator + { private static readonly int part = 7; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } @@ -3375,13 +4144,16 @@ public static class LogOff private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } @@ -3395,1449 +4167,1802 @@ public static class LogOffButtons private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } } - public static class UserPicture { + public static class UserPicture + { private static readonly int part = 10; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class Preview { + public static class Preview + { private static readonly int part = 11; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } } // END STARTPANEL - public static class Status { + public static class Status + { private static readonly string className = "STATUS"; - public static class Bar { + public static class Bar + { private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, 0, 0); } - + return normal; } } } - public static class Pane { + public static class Pane + { private static readonly int part = 1; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class GripperPane { + public static class GripperPane + { private static readonly int part = 2; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class Gripper { + public static class Gripper + { private static readonly int part = 3; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } } // END STATUS - public static class TaskBand { + public static class TaskBand + { private static readonly string className = "TASKBAND"; - public static class GroupCount { + public static class GroupCount + { private static readonly int part = 1; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class FlashButton { + public static class FlashButton + { private static readonly int part = 2; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class FlashButtonGroupMenu { + public static class FlashButtonGroupMenu + { private static readonly int part = 3; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } } // END TASKBAND - public static class TaskbarClock { + public static class TaskbarClock + { private static readonly string className = "CLOCK"; - public static class Time { + public static class Time + { private static readonly int part = 1; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } } } // END TASKBARCLOCK - public static class Taskbar { + public static class Taskbar + { private static readonly string className = "TASKBAR"; - public static class BackgroundBottom { + public static class BackgroundBottom + { private static readonly int part = 1; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class BackgroundRight { + public static class BackgroundRight + { private static readonly int part = 2; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class BackgroundTop { + public static class BackgroundTop + { private static readonly int part = 3; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class BackgroundLeft { + public static class BackgroundLeft + { private static readonly int part = 4; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class SizingBarBottom { + public static class SizingBarBottom + { private static readonly int part = 5; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class SizingBarRight { + public static class SizingBarRight + { private static readonly int part = 6; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class SizingBarTop { + public static class SizingBarTop + { private static readonly int part = 7; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class SizingBarLeft { + public static class SizingBarLeft + { private static readonly int part = 8; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } } // END TASKBAR - public static class ToolBar { + public static class ToolBar + { private static readonly string className = "TOOLBAR"; // - internal static class Bar { - private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { - normal = new VisualStyleElement(className, 0, 0); - } - - return normal; - } - } - } - - public static class Button { + internal static class Bar + { + private static VisualStyleElement normal; + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { + normal = new VisualStyleElement(className, 0, 0); + } + + return normal; + } + } + } + + public static class Button + { private static readonly int part = 1; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } private static VisualStyleElement _checked; - - public static VisualStyleElement Checked { - get { - if (_checked == null) { + + public static VisualStyleElement Checked + { + get + { + if (_checked == null) + { _checked = new VisualStyleElement(className, part, 5); } - + return _checked; } } private static VisualStyleElement hotchecked; - - public static VisualStyleElement HotChecked { - get { - if (hotchecked == null) { + + public static VisualStyleElement HotChecked + { + get + { + if (hotchecked == null) + { hotchecked = new VisualStyleElement(className, part, 6); } - + return hotchecked; } } } - public static class DropDownButton { + public static class DropDownButton + { private static readonly int part = 2; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } private static VisualStyleElement _checked; - - public static VisualStyleElement Checked { - get { - if (_checked == null) { + + public static VisualStyleElement Checked + { + get + { + if (_checked == null) + { _checked = new VisualStyleElement(className, part, 5); } - + return _checked; } } private static VisualStyleElement hotchecked; - - public static VisualStyleElement HotChecked { - get { - if (hotchecked == null) { + + public static VisualStyleElement HotChecked + { + get + { + if (hotchecked == null) + { hotchecked = new VisualStyleElement(className, part, 6); } - + return hotchecked; } } } - public static class SplitButton { + public static class SplitButton + { private static readonly int part = 3; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } private static VisualStyleElement _checked; - - public static VisualStyleElement Checked { - get { - if (_checked == null) { + + public static VisualStyleElement Checked + { + get + { + if (_checked == null) + { _checked = new VisualStyleElement(className, part, 5); } - + return _checked; } } private static VisualStyleElement hotchecked; - - public static VisualStyleElement HotChecked { - get { - if (hotchecked == null) { + + public static VisualStyleElement HotChecked + { + get + { + if (hotchecked == null) + { hotchecked = new VisualStyleElement(className, part, 6); } - + return hotchecked; } } } - public static class SplitButtonDropDown { + public static class SplitButtonDropDown + { private static readonly int part = 4; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { - disabled = new VisualStyleElement(className, part, 4); - } - - return disabled; - } - } + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { + disabled = new VisualStyleElement(className, part, 4); + } + + return disabled; + } + } private static VisualStyleElement _checked; - - public static VisualStyleElement Checked { - get { - if (_checked == null) { + + public static VisualStyleElement Checked + { + get + { + if (_checked == null) + { _checked = new VisualStyleElement(className, part, 5); } - + return _checked; } } private static VisualStyleElement hotchecked; - - public static VisualStyleElement HotChecked { - get { - if (hotchecked == null) { + + public static VisualStyleElement HotChecked + { + get + { + if (hotchecked == null) + { hotchecked = new VisualStyleElement(className, part, 6); } - + return hotchecked; } } } - - public static class SeparatorHorizontal { + + public static class SeparatorHorizontal + { private static readonly int part = 5; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class SeparatorVertical { + public static class SeparatorVertical + { private static readonly int part = 6; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - + } // END TOOLBAR - public static class ToolTip { + public static class ToolTip + { private static readonly string className = "TOOLTIP"; - public static class Standard { + public static class Standard + { private static readonly int part = 1; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } private static VisualStyleElement link; - - public static VisualStyleElement Link { - get { - if (link == null) { + + public static VisualStyleElement Link + { + get + { + if (link == null) + { link = new VisualStyleElement(className, part, 2); } - + return link; } } } - public static class StandardTitle { + public static class StandardTitle + { private static readonly int part = 2; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class Balloon { + public static class Balloon + { private static readonly int part = 3; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } private static VisualStyleElement link; - - public static VisualStyleElement Link { - get { - if (link == null) { + + public static VisualStyleElement Link + { + get + { + if (link == null) + { link = new VisualStyleElement(className, part, 2); } - + return link; } } } - public static class BalloonTitle { + public static class BalloonTitle + { private static readonly int part = 4; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class Close { + public static class Close + { private static readonly int part = 5; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } } } // END TOOLTIP - public static class TrackBar { + public static class TrackBar + { private static readonly string className = "TRACKBAR"; - public static class Track { + public static class Track + { private static readonly int part = 1; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } } - public static class TrackVertical { + public static class TrackVertical + { private static readonly int part = 2; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } } - public static class Thumb { + public static class Thumb + { private static readonly int part = 3; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement focused; - - public static VisualStyleElement Focused { - get { - if (focused == null) { + + public static VisualStyleElement Focused + { + get + { + if (focused == null) + { focused = new VisualStyleElement(className, part, 4); } - + return focused; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 5); } - + return disabled; } } } - public static class ThumbBottom { + public static class ThumbBottom + { private static readonly int part = 4; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement focused; - - public static VisualStyleElement Focused { - get { - if (focused == null) { + + public static VisualStyleElement Focused + { + get + { + if (focused == null) + { focused = new VisualStyleElement(className, part, 4); } - + return focused; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 5); } - + return disabled; } } } - public static class ThumbTop { + public static class ThumbTop + { private static readonly int part = 5; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement focused; - - public static VisualStyleElement Focused { - get { - if (focused == null) { - focused = new VisualStyleElement(className, part, 4); - } - - return focused; - } + + public static VisualStyleElement Focused + { + get + { + if (focused == null) + { + focused = new VisualStyleElement(className, part, 4); + } + + return focused; + } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 5); } - + return disabled; } } } - public static class ThumbVertical { + public static class ThumbVertical + { private static readonly int part = 6; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement focused; - - public static VisualStyleElement Focused { - get { - if (focused == null) { + + public static VisualStyleElement Focused + { + get + { + if (focused == null) + { focused = new VisualStyleElement(className, part, 4); } - + return focused; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 5); } - + return disabled; } } } - public static class ThumbLeft { + public static class ThumbLeft + { private static readonly int part = 7; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement focused; - - public static VisualStyleElement Focused { - get { - if (focused == null) { + + public static VisualStyleElement Focused + { + get + { + if (focused == null) + { focused = new VisualStyleElement(className, part, 4); } - + return focused; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 5); } - + return disabled; } } } - public static class ThumbRight { + public static class ThumbRight + { private static readonly int part = 8; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement focused; - - public static VisualStyleElement Focused { - get { - if (focused == null) { + + public static VisualStyleElement Focused + { + get + { + if (focused == null) + { focused = new VisualStyleElement(className, part, 4); } - + return focused; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 5); } - + return disabled; } } } - public static class Ticks { + public static class Ticks + { private static readonly int part = 9; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } } - public static class TicksVertical { + public static class TicksVertical + { private static readonly int part = 10; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } } } // END TRACKBAR - public static class TreeView { + public static class TreeView + { private static readonly string className = "TREEVIEW"; - public static class Item { + public static class Item + { private static readonly int part = 1; private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement selected; - - public static VisualStyleElement Selected { - get { - if (selected == null) { + + public static VisualStyleElement Selected + { + get + { + if (selected == null) + { selected = new VisualStyleElement(className, part, 3); } - + return selected; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } private static VisualStyleElement selectednotfocus; - - public static VisualStyleElement SelectedNotFocus { - get { - if (selectednotfocus == null) { + + public static VisualStyleElement SelectedNotFocus + { + get + { + if (selectednotfocus == null) + { selectednotfocus = new VisualStyleElement(className, part, 5); } - + return selectednotfocus; } } } - public static class Glyph { + public static class Glyph + { private static readonly int part = 2; private static VisualStyleElement closed; - - public static VisualStyleElement Closed { - get { - if (closed == null) { + + public static VisualStyleElement Closed + { + get + { + if (closed == null) + { closed = new VisualStyleElement(className, part, 1); } - + return closed; } } private static VisualStyleElement opened; - - public static VisualStyleElement Opened { - get { - if (opened == null) { + + public static VisualStyleElement Opened + { + get + { + if (opened == null) + { opened = new VisualStyleElement(className, part, 2); } - + return opened; } } } - public static class Branch { + public static class Branch + { private static readonly int part = 3; private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } } // END TREEVIEW - internal static class ExplorerTreeView { + internal static class ExplorerTreeView + { private static readonly string className = "Explorer::TreeView"; - public static class Glyph { + public static class Glyph + { private static readonly int part = 2; private static VisualStyleElement closed; - public static VisualStyleElement Closed { - get { - if (closed == null) { + public static VisualStyleElement Closed + { + get + { + if (closed == null) + { closed = new VisualStyleElement(className, part, 1); } @@ -4847,9 +5972,12 @@ public static VisualStyleElement Closed { private static VisualStyleElement opened; - public static VisualStyleElement Opened { - get { - if (opened == null) { + public static VisualStyleElement Opened + { + get + { + if (opened == null) + { opened = new VisualStyleElement(className, part, 2); } @@ -4859,1506 +5987,1873 @@ public static VisualStyleElement Opened { } } // END Explorer::Tree - public static class TextBox { + public static class TextBox + { private static readonly string className = "EDIT"; - public static class TextEdit { + public static class TextEdit + { private static readonly int part = 1; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } private static VisualStyleElement selected; - - public static VisualStyleElement Selected { - get { - if (selected == null) { - selected = new VisualStyleElement(className, part, 3); - } - - return selected; + + public static VisualStyleElement Selected + { + get + { + if (selected == null) + { + selected = new VisualStyleElement(className, part, 3); + } + + return selected; } } private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } - + private static VisualStyleElement focused; - - public static VisualStyleElement Focused { - get { - if (focused == null) { + + public static VisualStyleElement Focused + { + get + { + if (focused == null) + { focused = new VisualStyleElement(className, part, 5); } - + return focused; } } private static VisualStyleElement _readonly; - - public static VisualStyleElement ReadOnly { - get { - if (_readonly == null) { + + public static VisualStyleElement ReadOnly + { + get + { + if (_readonly == null) + { _readonly = new VisualStyleElement(className, part, 6); } - + return _readonly; } } private static VisualStyleElement assist; - - public static VisualStyleElement Assist { - get { - if (assist == null) { + + public static VisualStyleElement Assist + { + get + { + if (assist == null) + { assist = new VisualStyleElement(className, part, 7); } - + return assist; } } } - public static class Caret { + public static class Caret + { private static readonly int part = 2; private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } } // END TEXTBOX - public static class TrayNotify { + public static class TrayNotify + { private static readonly string className = "TRAYNOTIFY"; - public static class Background { + public static class Background + { private static readonly int part = 1; private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class AnimateBackground { + public static class AnimateBackground + { private static readonly int part = 2; private static VisualStyleElement normal; - public static VisualStyleElement Normal { - get { - if (normal == null) { + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } } // END TRAYNOTIFY - public static class Window { + public static class Window + { private static readonly string className = "WINDOW"; - public static class Caption { + public static class Caption + { private static readonly int part = 1; private static VisualStyleElement active; - - public static VisualStyleElement Active { - get { - if (active == null) { + + public static VisualStyleElement Active + { + get + { + if (active == null) + { active = new VisualStyleElement(className, part, 1); } - + return active; } } private static VisualStyleElement inactive; - - public static VisualStyleElement Inactive { - get { - if (inactive == null) { + + public static VisualStyleElement Inactive + { + get + { + if (inactive == null) + { inactive = new VisualStyleElement(className, part, 2); } - + return inactive; } } private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 3); } - + return disabled; } } } - public static class SmallCaption { + public static class SmallCaption + { private static readonly int part = 2; private static VisualStyleElement active; - - public static VisualStyleElement Active { - get { - if (active == null) { + + public static VisualStyleElement Active + { + get + { + if (active == null) + { active = new VisualStyleElement(className, part, 1); } - + return active; } } private static VisualStyleElement inactive; - - public static VisualStyleElement Inactive { - get { - if (inactive == null) { + + public static VisualStyleElement Inactive + { + get + { + if (inactive == null) + { inactive = new VisualStyleElement(className, part, 2); } - + return inactive; } } private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 3); } - + return disabled; } } } - public static class MinCaption { + public static class MinCaption + { private static readonly int part = 3; private static VisualStyleElement active; - - public static VisualStyleElement Active { - get { - if (active == null) { + + public static VisualStyleElement Active + { + get + { + if (active == null) + { active = new VisualStyleElement(className, part, 1); } - + return active; } } private static VisualStyleElement inactive; - - public static VisualStyleElement Inactive { - get { - if (inactive == null) { + + public static VisualStyleElement Inactive + { + get + { + if (inactive == null) + { inactive = new VisualStyleElement(className, part, 2); } - + return inactive; } } private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 3); } - + return disabled; } } } - public static class SmallMinCaption { + public static class SmallMinCaption + { private static readonly int part = 4; private static VisualStyleElement active; - - public static VisualStyleElement Active { - get { - if (active == null) { + + public static VisualStyleElement Active + { + get + { + if (active == null) + { active = new VisualStyleElement(className, part, 1); } - + return active; } } private static VisualStyleElement inactive; - - public static VisualStyleElement Inactive { - get { - if (inactive == null) { + + public static VisualStyleElement Inactive + { + get + { + if (inactive == null) + { inactive = new VisualStyleElement(className, part, 2); } - + return inactive; } } private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 3); } - + return disabled; } } } - public static class MaxCaption { + public static class MaxCaption + { private static readonly int part = 5; private static VisualStyleElement active; - - public static VisualStyleElement Active { - get { - if (active == null) { + + public static VisualStyleElement Active + { + get + { + if (active == null) + { active = new VisualStyleElement(className, part, 1); } - + return active; } } private static VisualStyleElement inactive; - - public static VisualStyleElement Inactive { - get { - if (inactive == null) { + + public static VisualStyleElement Inactive + { + get + { + if (inactive == null) + { inactive = new VisualStyleElement(className, part, 2); } - + return inactive; } } private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 3); } - + return disabled; } } } - public static class SmallMaxCaption { + public static class SmallMaxCaption + { private static readonly int part = 6; private static VisualStyleElement active; - - public static VisualStyleElement Active { - get { - if (active == null) { + + public static VisualStyleElement Active + { + get + { + if (active == null) + { active = new VisualStyleElement(className, part, 1); } - + return active; } } private static VisualStyleElement inactive; - - public static VisualStyleElement Inactive { - get { - if (inactive == null) { + + public static VisualStyleElement Inactive + { + get + { + if (inactive == null) + { inactive = new VisualStyleElement(className, part, 2); } - + return inactive; } } private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 3); } - + return disabled; } } } - public static class FrameLeft { + public static class FrameLeft + { private static readonly int part = 7; private static VisualStyleElement active; - - public static VisualStyleElement Active { - get { - if (active == null) { + + public static VisualStyleElement Active + { + get + { + if (active == null) + { active = new VisualStyleElement(className, part, 1); } - + return active; } } private static VisualStyleElement inactive; - - public static VisualStyleElement Inactive { - get { - if (inactive == null) { + + public static VisualStyleElement Inactive + { + get + { + if (inactive == null) + { inactive = new VisualStyleElement(className, part, 2); } - + return inactive; } } } - public static class FrameRight { + public static class FrameRight + { private static readonly int part = 8; private static VisualStyleElement active; - - public static VisualStyleElement Active { - get { - if (active == null) { + + public static VisualStyleElement Active + { + get + { + if (active == null) + { active = new VisualStyleElement(className, part, 1); } - + return active; } } private static VisualStyleElement inactive; - - public static VisualStyleElement Inactive { - get { - if (inactive == null) { + + public static VisualStyleElement Inactive + { + get + { + if (inactive == null) + { inactive = new VisualStyleElement(className, part, 2); } - + return inactive; } } } - public static class FrameBottom { + public static class FrameBottom + { private static readonly int part = 9; private static VisualStyleElement active; - - public static VisualStyleElement Active { - get { - if (active == null) { + + public static VisualStyleElement Active + { + get + { + if (active == null) + { active = new VisualStyleElement(className, part, 1); } - + return active; } } private static VisualStyleElement inactive; - - public static VisualStyleElement Inactive { - get { - if (inactive == null) { + + public static VisualStyleElement Inactive + { + get + { + if (inactive == null) + { inactive = new VisualStyleElement(className, part, 2); } - + return inactive; } } } - public static class SmallFrameLeft { + public static class SmallFrameLeft + { private static readonly int part = 10; private static VisualStyleElement active; - - public static VisualStyleElement Active { - get { - if (active == null) { + + public static VisualStyleElement Active + { + get + { + if (active == null) + { active = new VisualStyleElement(className, part, 1); } - + return active; } } private static VisualStyleElement inactive; - - public static VisualStyleElement Inactive { - get { - if (inactive == null) { + + public static VisualStyleElement Inactive + { + get + { + if (inactive == null) + { inactive = new VisualStyleElement(className, part, 2); } - + return inactive; } } } - public static class SmallFrameRight { + public static class SmallFrameRight + { private static readonly int part = 11; private static VisualStyleElement active; - - public static VisualStyleElement Active { - get { - if (active == null) { + + public static VisualStyleElement Active + { + get + { + if (active == null) + { active = new VisualStyleElement(className, part, 1); } - + return active; } } private static VisualStyleElement inactive; - - public static VisualStyleElement Inactive { - get { - if (inactive == null) { + + public static VisualStyleElement Inactive + { + get + { + if (inactive == null) + { inactive = new VisualStyleElement(className, part, 2); } - + return inactive; } } } - public static class SmallFrameBottom { + public static class SmallFrameBottom + { private static readonly int part = 12; private static VisualStyleElement active; - - public static VisualStyleElement Active { - get { - if (active == null) { - active = new VisualStyleElement(className, part, 1); - } - - return active; - } + + public static VisualStyleElement Active + { + get + { + if (active == null) + { + active = new VisualStyleElement(className, part, 1); + } + + return active; + } } private static VisualStyleElement inactive; - - public static VisualStyleElement Inactive { - get { - if (inactive == null) { + + public static VisualStyleElement Inactive + { + get + { + if (inactive == null) + { inactive = new VisualStyleElement(className, part, 2); } - + return inactive; } } } - public static class SysButton { + public static class SysButton + { private static readonly int part = 13; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class MdiSysButton { + public static class MdiSysButton + { private static readonly int part = 14; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class MinButton { + public static class MinButton + { private static readonly int part = 15; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class MdiMinButton { + public static class MdiMinButton + { private static readonly int part = 16; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class MaxButton { + public static class MaxButton + { private static readonly int part = 17; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class CloseButton { + public static class CloseButton + { private static readonly int part = 18; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class SmallCloseButton { + public static class SmallCloseButton + { private static readonly int part = 19; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class MdiCloseButton { + public static class MdiCloseButton + { private static readonly int part = 20; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class RestoreButton { + public static class RestoreButton + { private static readonly int part = 21; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class MdiRestoreButton { + public static class MdiRestoreButton + { private static readonly int part = 22; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class HelpButton { + public static class HelpButton + { private static readonly int part = 23; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class MdiHelpButton { + public static class MdiHelpButton + { private static readonly int part = 24; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class HorizontalScroll { + public static class HorizontalScroll + { private static readonly int part = 25; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class HorizontalThumb { + public static class HorizontalThumb + { private static readonly int part = 26; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class VerticalScroll { + public static class VerticalScroll + { private static readonly int part = 27; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class VerticalThumb { + public static class VerticalThumb + { private static readonly int part = 28; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 1); } - + return normal; } } - + private static VisualStyleElement hot; - - public static VisualStyleElement Hot { - get { - if (hot == null) { + + public static VisualStyleElement Hot + { + get + { + if (hot == null) + { hot = new VisualStyleElement(className, part, 2); } - + return hot; } } - + private static VisualStyleElement pressed; - - public static VisualStyleElement Pressed { - get { - if (pressed == null) { + + public static VisualStyleElement Pressed + { + get + { + if (pressed == null) + { pressed = new VisualStyleElement(className, part, 3); } - + return pressed; } } - + private static VisualStyleElement disabled; - - public static VisualStyleElement Disabled { - get { - if (disabled == null) { + + public static VisualStyleElement Disabled + { + get + { + if (disabled == null) + { disabled = new VisualStyleElement(className, part, 4); } - + return disabled; } } } - public static class Dialog { + public static class Dialog + { private static readonly int part = 29; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class CaptionSizingTemplate { + public static class CaptionSizingTemplate + { private static readonly int part = 30; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class SmallCaptionSizingTemplate { + public static class SmallCaptionSizingTemplate + { private static readonly int part = 31; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class FrameLeftSizingTemplate { + public static class FrameLeftSizingTemplate + { private static readonly int part = 32; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class SmallFrameLeftSizingTemplate { + public static class SmallFrameLeftSizingTemplate + { private static readonly int part = 33; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } @@ -6372,13 +7867,16 @@ public static class FrameRightSizingTemplate private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } @@ -6392,51 +7890,62 @@ public static class SmallFrameRightSizingTemplate private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class FrameBottomSizingTemplate { + public static class FrameBottomSizingTemplate + { private static readonly int part = 36; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } - public static class SmallFrameBottomSizingTemplate { + public static class SmallFrameBottomSizingTemplate + { private static readonly int part = 37; private static VisualStyleElement normal; - - public static VisualStyleElement Normal { - get { - if (normal == null) { + + public static VisualStyleElement Normal + { + get + { + if (normal == null) + { normal = new VisualStyleElement(className, part, 0); } - + return normal; } } } } // END WINDOW - } + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleInformation.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleInformation.cs index 6beca13a939..0501267a7f8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleInformation.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleInformation.cs @@ -3,9 +3,10 @@ // See the LICENSE file in the project root for more information. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA905:SystemAndMicrosoftNamespacesRequireApproval", Scope="namespace", Target="System.Windows.Forms.VisualStyles")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA905:SystemAndMicrosoftNamespacesRequireApproval", Scope = "namespace", Target = "System.Windows.Forms.VisualStyles")] -namespace System.Windows.Forms.VisualStyles { +namespace System.Windows.Forms.VisualStyles +{ using System; using System.Text; @@ -13,7 +14,7 @@ namespace System.Windows.Forms.VisualStyles { using System.Windows.Forms; using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; - + /// /// @@ -25,7 +26,8 @@ namespace System.Windows.Forms.VisualStyles { /// not meaningful unless VisualStyleRenderer.IsSupported is true. /// /// - public static class VisualStyleInformation { + public static class VisualStyleInformation + { //Make this per-thread, so that different threads can safely use these methods. [ThreadStatic] @@ -37,8 +39,10 @@ public static class VisualStyleInformation { /// using the OSFeature class to see if themes are supported. /// /// - public static bool IsSupportedByOS { - get { + public static bool IsSupportedByOS + { + get + { return (OSFeature.Feature.IsPresent(OSFeature.Themes)); } } @@ -48,21 +52,27 @@ public static bool IsSupportedByOS { /// Returns true if a visual style has currently been applied by the user, else false. /// /// - public static bool IsEnabledByUser { - get { - if (!IsSupportedByOS) { + public static bool IsEnabledByUser + { + get + { + if (!IsSupportedByOS) + { return false; } - + return (SafeNativeMethods.IsAppThemed()); } } - internal static string ThemeFilename { - get { - if (IsEnabledByUser) { + internal static string ThemeFilename + { + get + { + if (IsEnabledByUser) + { StringBuilder filename = new StringBuilder(512); - SafeNativeMethods.GetCurrentThemeName(filename, filename.Capacity, null, 0, null, 0); + SafeNativeMethods.GetCurrentThemeName(filename, filename.Capacity, null, 0, null, 0); return (filename.ToString()); } @@ -73,11 +83,14 @@ internal static string ThemeFilename { /// /// The current visual style's color scheme name. /// - public static string ColorScheme { - get { - if (IsEnabledByUser) { + public static string ColorScheme + { + get + { + if (IsEnabledByUser) + { StringBuilder colorScheme = new StringBuilder(512); - SafeNativeMethods.GetCurrentThemeName(null, 0, colorScheme, colorScheme.Capacity, null, 0); + SafeNativeMethods.GetCurrentThemeName(null, 0, colorScheme, colorScheme.Capacity, null, 0); return (colorScheme.ToString()); } @@ -88,11 +101,14 @@ public static string ColorScheme { /// /// The current visual style's size name. /// - public static string Size { - get { - if (IsEnabledByUser) { + public static string Size + { + get + { + if (IsEnabledByUser) + { StringBuilder size = new StringBuilder(512); - SafeNativeMethods.GetCurrentThemeName(null, 0, null, 0, size, size.Capacity); + SafeNativeMethods.GetCurrentThemeName(null, 0, null, 0, size, size.Capacity); return (size.ToString()); } @@ -103,9 +119,12 @@ public static string Size { /// /// The current visual style's display name. /// - public static string DisplayName { - get { - if (IsEnabledByUser) { + public static string DisplayName + { + get + { + if (IsEnabledByUser) + { StringBuilder name = new StringBuilder(512); SafeNativeMethods.GetThemeDocumentationProperty(ThemeFilename, SafeNativeMethods.VisualStyleDocProperty.DisplayName, name, name.Capacity); return name.ToString(); @@ -118,9 +137,12 @@ public static string DisplayName { /// /// The current visual style's company. /// - public static string Company { - get { - if (IsEnabledByUser) { + public static string Company + { + get + { + if (IsEnabledByUser) + { StringBuilder company = new StringBuilder(512); SafeNativeMethods.GetThemeDocumentationProperty(ThemeFilename, SafeNativeMethods.VisualStyleDocProperty.Company, company, company.Capacity); return company.ToString(); @@ -133,9 +155,12 @@ public static string Company { /// /// The name of the current visual style's author. /// - public static string Author { - get { - if (IsEnabledByUser) { + public static string Author + { + get + { + if (IsEnabledByUser) + { StringBuilder author = new StringBuilder(512); SafeNativeMethods.GetThemeDocumentationProperty(ThemeFilename, SafeNativeMethods.VisualStyleDocProperty.Author, author, author.Capacity); return author.ToString(); @@ -144,13 +169,16 @@ public static string Author { return string.Empty; } } - + /// /// The current visual style's copyright information. /// - public static string Copyright { - get { - if (IsEnabledByUser) { + public static string Copyright + { + get + { + if (IsEnabledByUser) + { StringBuilder copyright = new StringBuilder(512); SafeNativeMethods.GetThemeDocumentationProperty(ThemeFilename, SafeNativeMethods.VisualStyleDocProperty.Copyright, copyright, copyright.Capacity); return copyright.ToString(); @@ -164,10 +192,13 @@ public static string Copyright { /// The current visual style's url. /// [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] - public static string Url { + public static string Url + { [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings")] - get { - if (IsEnabledByUser) { + get + { + if (IsEnabledByUser) + { StringBuilder url = new StringBuilder(512); SafeNativeMethods.GetThemeDocumentationProperty(ThemeFilename, SafeNativeMethods.VisualStyleDocProperty.Url, url, url.Capacity); return url.ToString(); @@ -180,9 +211,12 @@ public static string Url { /// /// The current visual style's version. /// - public static string Version { - get { - if (IsEnabledByUser) { + public static string Version + { + get + { + if (IsEnabledByUser) + { StringBuilder version = new StringBuilder(512); SafeNativeMethods.GetThemeDocumentationProperty(ThemeFilename, SafeNativeMethods.VisualStyleDocProperty.Version, version, version.Capacity); return version.ToString(); @@ -195,9 +229,12 @@ public static string Version { /// /// The current visual style's description. /// - public static string Description { - get { - if (IsEnabledByUser) { + public static string Description + { + get + { + if (IsEnabledByUser) + { StringBuilder description = new StringBuilder(512); SafeNativeMethods.GetThemeDocumentationProperty(ThemeFilename, SafeNativeMethods.VisualStyleDocProperty.Description, description, description.Capacity); return description.ToString(); @@ -210,36 +247,46 @@ public static string Description { /// /// Returns true if the current theme supports flat menus, else false. /// - public static bool SupportsFlatMenus { - get { - if (Application.RenderWithVisualStyles) { - if (visualStyleRenderer == null) { + public static bool SupportsFlatMenus + { + get + { + if (Application.RenderWithVisualStyles) + { + if (visualStyleRenderer == null) + { visualStyleRenderer = new VisualStyleRenderer(VisualStyleElement.Window.Caption.Active); } - else { + else + { visualStyleRenderer.SetParameters(VisualStyleElement.Window.Caption.Active); - } + } return (SafeNativeMethods.GetThemeSysBool(new HandleRef(null, visualStyleRenderer.Handle), SafeNativeMethods.VisualStyleSystemProperty.SupportsFlatMenus)); } return false; - } + } } /// /// The minimum color depth supported by the current visual style. /// - public static int MinimumColorDepth { - get { - if (Application.RenderWithVisualStyles) { - if (visualStyleRenderer == null) { + public static int MinimumColorDepth + { + get + { + if (Application.RenderWithVisualStyles) + { + if (visualStyleRenderer == null) + { visualStyleRenderer = new VisualStyleRenderer(VisualStyleElement.Window.Caption.Active); } - else { + else + { visualStyleRenderer.SetParameters(VisualStyleElement.Window.Caption.Active); } - + int mcDepth = 0; SafeNativeMethods.GetThemeSysInt(new HandleRef(null, visualStyleRenderer.Handle), SafeNativeMethods.VisualStyleSystemProperty.MinimumColorDepth, ref mcDepth); @@ -247,19 +294,24 @@ public static int MinimumColorDepth { } return 0; - } + } } /// /// Border Color that Windows renders for controls like TextBox and ComboBox. /// - public static Color TextControlBorder { - get { - if (Application.RenderWithVisualStyles) { - if (visualStyleRenderer == null) { - visualStyleRenderer = new VisualStyleRenderer(VisualStyleElement.TextBox.TextEdit.Normal); + public static Color TextControlBorder + { + get + { + if (Application.RenderWithVisualStyles) + { + if (visualStyleRenderer == null) + { + visualStyleRenderer = new VisualStyleRenderer(VisualStyleElement.TextBox.TextEdit.Normal); } - else { + else + { visualStyleRenderer.SetParameters(VisualStyleElement.TextBox.TextEdit.Normal); } Color borderColor = visualStyleRenderer.GetColor(ColorProperty.BorderColor); @@ -274,14 +326,19 @@ public static Color TextControlBorder { /// /// This is the color buttons and tab pages are highlighted with when they are moused over on themed OS. /// - public static Color ControlHighlightHot { - get { - if (Application.RenderWithVisualStyles) { - if (visualStyleRenderer == null) { + public static Color ControlHighlightHot + { + get + { + if (Application.RenderWithVisualStyles) + { + if (visualStyleRenderer == null) + { visualStyleRenderer = new VisualStyleRenderer(VisualStyleElement.Button.PushButton.Normal); - + } - else { + else + { visualStyleRenderer.SetParameters(VisualStyleElement.Button.PushButton.Normal); } Color accentColor = visualStyleRenderer.GetColor(ColorProperty.AccentColorHint); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleRenderer.cs index f79588fb875..7ba5cacbe93 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleRenderer.cs @@ -2,9 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA905:SystemAndMicrosoftNamespacesRequireApproval", Scope="namespace", Target="System.Windows.Forms.VisualStyles")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA905:SystemAndMicrosoftNamespacesRequireApproval", Scope = "namespace", Target = "System.Windows.Forms.VisualStyles")] -namespace System.Windows.Forms.VisualStyles { +namespace System.Windows.Forms.VisualStyles +{ using System; using System.Drawing; using System.Windows.Forms.Internal; @@ -23,7 +24,8 @@ namespace System.Windows.Forms.VisualStyles { /// This class provides full feature parity with UxTheme API. /// /// - public sealed class VisualStyleRenderer { + public sealed class VisualStyleRenderer + { private const TextFormatFlags AllGraphicsProperties = TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.PreserveGraphicsTranslateTransform; internal const int EdgeAdjust = 0x2000; //used with Edges in VisualStyleRenderer.DrawThemeEdge @@ -32,23 +34,26 @@ public sealed class VisualStyleRenderer { private int state; private int lastHResult = 0; private static int numberOfPossibleClasses = VisualStyleElement.Count; //used as size for themeHandles - + [ThreadStatic] private static Hashtable themeHandles = null; //per-thread cache of ThemeHandle objects. [ThreadStatic] - private static long threadCacheVersion = 0; + private static long threadCacheVersion = 0; private static long globalCacheVersion = 0; - static VisualStyleRenderer() { + static VisualStyleRenderer() + { SystemEvents.UserPreferenceChanging += new UserPreferenceChangingEventHandler(OnUserPreferenceChanging); } /// /// Check if visual styles is supported for client area. /// - private static bool AreClientAreaVisualStylesSupported { - get { + private static bool AreClientAreaVisualStylesSupported + { + get + { return (VisualStyleInformation.IsEnabledByUser && ((Application.VisualStyleState & VisualStyleState.ClientAreaEnabled) == VisualStyleState.ClientAreaEnabled)); } @@ -62,11 +67,14 @@ private static bool AreClientAreaVisualStylesSupported { /// will result in exceptions being thrown. /// /// - public static bool IsSupported { - get { + public static bool IsSupported + { + get + { bool supported = AreClientAreaVisualStylesSupported; - if (supported) { + if (supported) + { // In some cases, this check isn't enough, since the theme handle creation // could fail for some other reason. Try creating a theme handle here - if successful, return true, // else return false. @@ -89,52 +97,66 @@ public static bool IsSupported { /// state instead. /// /// - public static bool IsElementDefined(VisualStyleElement element) { - if (element == null) { + public static bool IsElementDefined(VisualStyleElement element) + { + if (element == null) + { throw new ArgumentNullException(nameof(element)); } return IsCombinationDefined(element.ClassName, element.Part); } - internal static bool IsCombinationDefined(string className, int part) { + internal static bool IsCombinationDefined(string className, int part) + { bool returnVal = false; - if (!IsSupported) { - if (!VisualStyleInformation.IsEnabledByUser) { + if (!IsSupported) + { + if (!VisualStyleInformation.IsEnabledByUser) + { throw new InvalidOperationException(SR.VisualStyleNotActive); } - else { + else + { throw new InvalidOperationException(SR.VisualStylesDisabledInClientArea); } } - if (className == null) { + if (className == null) + { throw new ArgumentNullException(nameof(className)); } IntPtr hTheme = GetHandle(className, false); - if (hTheme != IntPtr.Zero) { + if (hTheme != IntPtr.Zero) + { // IsThemePartDefined doesn't work for part = 0, although there are valid parts numbered 0. We // allow these explicitly here. - if (part == 0) { + if (part == 0) + { returnVal = true; } - else { + else + { returnVal = SafeNativeMethods.IsThemePartDefined(new HandleRef(null, hTheme), part, 0); } } //if the combo isn't defined, check the validity of our theme handle cache - if (!returnVal) { - using (ThemeHandle tHandle = ThemeHandle.Create(className, false)) { - if (tHandle != null) { + if (!returnVal) + { + using (ThemeHandle tHandle = ThemeHandle.Create(className, false)) + { + if (tHandle != null) + { returnVal = SafeNativeMethods.IsThemePartDefined(new HandleRef(null, tHandle.NativeHandle), part, 0); } //if we did, in fact get a new correct theme handle, our cache is out of date -- update it now. - if (returnVal) { + if (returnVal) + { RefreshCache(); } } @@ -148,7 +170,8 @@ internal static bool IsCombinationDefined(string className, int part) { /// Constructor takes a VisualStyleElement. /// /// - public VisualStyleRenderer(VisualStyleElement element) : this(element.ClassName, element.Part, element.State) { + public VisualStyleRenderer(VisualStyleElement element) : this(element.ClassName, element.Part, element.State) + { } /// @@ -157,8 +180,10 @@ public VisualStyleRenderer(VisualStyleElement element) : this(element.ClassName, /// not defined in the VisualStyleElement class.) /// /// - public VisualStyleRenderer(string className, int part, int state) { - if (!IsCombinationDefined(className, part)) { //internally this call takes care of IsSupported. + public VisualStyleRenderer(string className, int part, int state) + { + if (!IsCombinationDefined(className, part)) + { //internally this call takes care of IsSupported. throw new ArgumentException(SR.VisualStylesInvalidCombination); } @@ -172,8 +197,10 @@ public VisualStyleRenderer(string className, int part, int state) { /// Returns the current _class. Use SetParameters to set. /// /// - public string Class { - get { + public string Class + { + get + { return _class; } } @@ -183,8 +210,10 @@ public string Class { /// Returns the current part. Use SetParameters to set. /// /// - public int Part { - get { + public int Part + { + get + { return part; } } @@ -194,8 +223,10 @@ public int Part { /// Returns the current state. Use SetParameters to set. /// /// - public int State { - get { + public int State + { + get + { return state; } } @@ -209,17 +240,22 @@ public int State { /// category. /// /// - public IntPtr Handle { - get { - if (!IsSupported) { - if (!VisualStyleInformation.IsEnabledByUser) { - throw new InvalidOperationException(SR.VisualStyleNotActive); + public IntPtr Handle + { + get + { + if (!IsSupported) + { + if (!VisualStyleInformation.IsEnabledByUser) + { + throw new InvalidOperationException(SR.VisualStyleNotActive); } - else { + else + { throw new InvalidOperationException(SR.VisualStylesDisabledInClientArea); } } - + return GetHandle(_class); } } @@ -229,8 +265,10 @@ public IntPtr Handle { /// Used to set a new VisualStyleElement on this VisualStyleRenderer instance. /// /// - public void SetParameters(VisualStyleElement element) { - if (element == null) { + public void SetParameters(VisualStyleElement element) + { + if (element == null) + { throw new ArgumentNullException(nameof(element)); } @@ -244,9 +282,11 @@ public void SetParameters(VisualStyleElement element) { /// This method is present for extensibility. /// /// - public void SetParameters(string className, int part, int state) { - if (!IsCombinationDefined(className, part)) { //internally this call takes care of IsSupported. - throw new ArgumentException(SR.VisualStylesInvalidCombination); + public void SetParameters(string className, int part, int state) + { + if (!IsCombinationDefined(className, part)) + { //internally this call takes care of IsSupported. + throw new ArgumentException(SR.VisualStylesInvalidCombination); } this._class = className; @@ -259,26 +299,34 @@ public void SetParameters(string className, int part, int state) { /// [See win32 equivalent.] /// /// - public void DrawBackground(IDeviceContext dc, Rectangle bounds) { + public void DrawBackground(IDeviceContext dc, Rectangle bounds) + { DrawBackground(dc, bounds, IntPtr.Zero); } - internal void DrawBackground(IDeviceContext dc, Rectangle bounds, IntPtr hWnd) { - if (dc == null) { + internal void DrawBackground(IDeviceContext dc, Rectangle bounds, IntPtr hWnd) + { + if (dc == null) + { throw new ArgumentNullException(nameof(dc)); } - if (bounds.Width < 0 || bounds.Height < 0) { + if (bounds.Width < 0 || bounds.Height < 0) + { return; } - using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ){ + using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, AllGraphicsProperties)) + { HandleRef hdc = new HandleRef(wgr, wgr.WindowsGraphics.DeviceContext.Hdc); - if (IntPtr.Zero != hWnd) { - using (ThemeHandle hTheme = ThemeHandle.Create(_class, true, new HandleRef(null, hWnd))) { + if (IntPtr.Zero != hWnd) + { + using (ThemeHandle hTheme = ThemeHandle.Create(_class, true, new HandleRef(null, hWnd))) + { lastHResult = SafeNativeMethods.DrawThemeBackground(new HandleRef(this, hTheme.NativeHandle), hdc, part, state, new NativeMethods.COMRECT(bounds), null); } - } - else { + } + else + { lastHResult = SafeNativeMethods.DrawThemeBackground(new HandleRef(this, Handle), hdc, part, state, new NativeMethods.COMRECT(bounds), null); } } @@ -289,29 +337,38 @@ internal void DrawBackground(IDeviceContext dc, Rectangle bounds, IntPtr hWnd) { /// [See win32 equivalent.] /// /// - public void DrawBackground(IDeviceContext dc, Rectangle bounds, Rectangle clipRectangle) { + public void DrawBackground(IDeviceContext dc, Rectangle bounds, Rectangle clipRectangle) + { DrawBackground(dc, bounds, clipRectangle, IntPtr.Zero); } - internal void DrawBackground(IDeviceContext dc, Rectangle bounds, Rectangle clipRectangle, IntPtr hWnd) { - if( dc == null ){ + internal void DrawBackground(IDeviceContext dc, Rectangle bounds, Rectangle clipRectangle, IntPtr hWnd) + { + if (dc == null) + { throw new ArgumentNullException(nameof(dc)); } - if (bounds.Width < 0 || bounds.Height < 0) { + if (bounds.Width < 0 || bounds.Height < 0) + { return; } - if (clipRectangle.Width < 0 || clipRectangle.Height < 0) { + if (clipRectangle.Width < 0 || clipRectangle.Height < 0) + { return; } - using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { - HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); - if (IntPtr.Zero != hWnd) { - using (ThemeHandle hTheme = ThemeHandle.Create(_class, true, new HandleRef(null, hWnd))) { + using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, AllGraphicsProperties)) + { + HandleRef hdc = new HandleRef(wgr, wgr.WindowsGraphics.DeviceContext.Hdc); + if (IntPtr.Zero != hWnd) + { + using (ThemeHandle hTheme = ThemeHandle.Create(_class, true, new HandleRef(null, hWnd))) + { lastHResult = SafeNativeMethods.DrawThemeBackground(new HandleRef(this, hTheme.NativeHandle), hdc, part, state, new NativeMethods.COMRECT(bounds), new NativeMethods.COMRECT(clipRectangle)); } - } - else { + } + else + { lastHResult = SafeNativeMethods.DrawThemeBackground(new HandleRef(this, Handle), hdc, part, state, new NativeMethods.COMRECT(bounds), new NativeMethods.COMRECT(clipRectangle)); } } @@ -322,28 +379,34 @@ internal void DrawBackground(IDeviceContext dc, Rectangle bounds, Rectangle clip /// [See win32 equivalent.] /// /// - public Rectangle DrawEdge(IDeviceContext dc, Rectangle bounds, Edges edges, EdgeStyle style, EdgeEffects effects) { - if (dc == null) { + public Rectangle DrawEdge(IDeviceContext dc, Rectangle bounds, Edges edges, EdgeStyle style, EdgeEffects effects) + { + if (dc == null) + { throw new ArgumentNullException(nameof(dc)); } - if (!ClientUtils.IsEnumValid_Masked(edges, (int)edges,(uint)(Edges.Left | Edges.Top | Edges.Right | Edges.Bottom | Edges.Diagonal))) { + if (!ClientUtils.IsEnumValid_Masked(edges, (int)edges, (uint)(Edges.Left | Edges.Top | Edges.Right | Edges.Bottom | Edges.Diagonal))) + { throw new InvalidEnumArgumentException(nameof(edges), (int)edges, typeof(Edges)); } - if (!ClientUtils.IsEnumValid_NotSequential(style, (int)style, (int)EdgeStyle.Raised,(int)EdgeStyle.Sunken,(int)EdgeStyle.Etched,(int)EdgeStyle.Bump )) { + if (!ClientUtils.IsEnumValid_NotSequential(style, (int)style, (int)EdgeStyle.Raised, (int)EdgeStyle.Sunken, (int)EdgeStyle.Etched, (int)EdgeStyle.Bump)) + { throw new InvalidEnumArgumentException(nameof(style), (int)style, typeof(EdgeStyle)); } - if (!ClientUtils.IsEnumValid_Masked(effects, (int)effects, (uint)(EdgeEffects.FillInterior | EdgeEffects.Flat | EdgeEffects.Soft | EdgeEffects.Mono))) { + if (!ClientUtils.IsEnumValid_Masked(effects, (int)effects, (uint)(EdgeEffects.FillInterior | EdgeEffects.Flat | EdgeEffects.Soft | EdgeEffects.Mono))) + { throw new InvalidEnumArgumentException(nameof(effects), (int)effects, typeof(EdgeEffects)); } NativeMethods.COMRECT rect = new NativeMethods.COMRECT(); - using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { - HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); - lastHResult = SafeNativeMethods.DrawThemeEdge( new HandleRef( this, Handle ), hdc, part, state, new NativeMethods.COMRECT( bounds ), (int) style, (int) edges | (int) effects | EdgeAdjust, rect ); + using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, AllGraphicsProperties)) + { + HandleRef hdc = new HandleRef(wgr, wgr.WindowsGraphics.DeviceContext.Hdc); + lastHResult = SafeNativeMethods.DrawThemeEdge(new HandleRef(this, Handle), hdc, part, state, new NativeMethods.COMRECT(bounds), (int)style, (int)edges | (int)effects | EdgeAdjust, rect); } return Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom); @@ -355,16 +418,20 @@ public Rectangle DrawEdge(IDeviceContext dc, Rectangle bounds, Edges edges, Edge /// This method uses Graphics.DrawImage as a backup if themed drawing does not work. /// /// - public void DrawImage(Graphics g, Rectangle bounds, Image image) { - if (g == null) { + public void DrawImage(Graphics g, Rectangle bounds, Image image) + { + if (g == null) + { throw new ArgumentNullException(nameof(g)); } - if (image == null) { + if (image == null) + { throw new ArgumentNullException(nameof(image)); } - if (bounds.Width < 0 || bounds.Height < 0) { + if (bounds.Width < 0 || bounds.Height < 0) + { return; } @@ -377,20 +444,25 @@ public void DrawImage(Graphics g, Rectangle bounds, Image image) { /// This method uses Graphics.DrawImage as a backup if themed drawing does not work. /// /// - public void DrawImage(Graphics g, Rectangle bounds, ImageList imageList, int imageIndex) { - if (g == null) { + public void DrawImage(Graphics g, Rectangle bounds, ImageList imageList, int imageIndex) + { + if (g == null) + { throw new ArgumentNullException(nameof(g)); } - if (imageList == null) { + if (imageList == null) + { throw new ArgumentNullException(nameof(imageList)); } - - if (imageIndex < 0 || imageIndex >= imageList.Images.Count) { + + if (imageIndex < 0 || imageIndex >= imageList.Images.Count) + { throw new ArgumentOutOfRangeException(nameof(imageIndex), imageIndex, string.Format(SR.InvalidArgument, nameof(imageIndex), imageIndex)); } - if (bounds.Width < 0 || bounds.Height < 0) { + if (bounds.Width < 0 || bounds.Height < 0) + { return; } @@ -415,23 +487,29 @@ public void DrawImage(Graphics g, Rectangle bounds, ImageList imageList, int ima /// to the parent). /// /// - public void DrawParentBackground(IDeviceContext dc, Rectangle bounds, Control childControl) { - if (dc == null) { + public void DrawParentBackground(IDeviceContext dc, Rectangle bounds, Control childControl) + { + if (dc == null) + { throw new ArgumentNullException(nameof(dc)); } - if (childControl == null) { + if (childControl == null) + { throw new ArgumentNullException(nameof(childControl)); } - if (bounds.Width < 0 || bounds.Height < 0) { + if (bounds.Width < 0 || bounds.Height < 0) + { return; } - if (childControl.Handle != IntPtr.Zero) { - using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { - HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); - lastHResult = SafeNativeMethods.DrawThemeParentBackground( new HandleRef( this, childControl.Handle ), hdc, new NativeMethods.COMRECT( bounds ) ); + if (childControl.Handle != IntPtr.Zero) + { + using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, AllGraphicsProperties)) + { + HandleRef hdc = new HandleRef(wgr, wgr.WindowsGraphics.DeviceContext.Hdc); + lastHResult = SafeNativeMethods.DrawThemeParentBackground(new HandleRef(this, childControl.Handle), hdc, new NativeMethods.COMRECT(bounds)); } } } @@ -441,7 +519,8 @@ public void DrawParentBackground(IDeviceContext dc, Rectangle bounds, Control ch /// [See win32 equivalent.] /// /// - public void DrawText(IDeviceContext dc, Rectangle bounds, string textToDraw) { + public void DrawText(IDeviceContext dc, Rectangle bounds, string textToDraw) + { DrawText(dc, bounds, textToDraw, false); } @@ -450,8 +529,9 @@ public void DrawText(IDeviceContext dc, Rectangle bounds, string textToDraw) { /// [See win32 equivalent.] /// /// - public void DrawText(IDeviceContext dc, Rectangle bounds, string textToDraw, bool drawDisabled) { - DrawText(dc, bounds, textToDraw, drawDisabled, TextFormatFlags.HorizontalCenter); + public void DrawText(IDeviceContext dc, Rectangle bounds, string textToDraw, bool drawDisabled) + { + DrawText(dc, bounds, textToDraw, drawDisabled, TextFormatFlags.HorizontalCenter); } /// @@ -459,21 +539,26 @@ public void DrawText(IDeviceContext dc, Rectangle bounds, string textToDraw, boo /// [See win32 equivalent.] /// /// - public void DrawText(IDeviceContext dc, Rectangle bounds, string textToDraw, bool drawDisabled, TextFormatFlags flags) { - if( dc == null ){ + public void DrawText(IDeviceContext dc, Rectangle bounds, string textToDraw, bool drawDisabled, TextFormatFlags flags) + { + if (dc == null) + { throw new ArgumentNullException(nameof(dc)); } - if (bounds.Width < 0 || bounds.Height < 0) { + if (bounds.Width < 0 || bounds.Height < 0) + { return; } - - int disableFlag = drawDisabled?0x1:0; - - if (!string.IsNullOrEmpty(textToDraw)) { - using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { - HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); - lastHResult = SafeNativeMethods.DrawThemeText( new HandleRef( this, Handle ), hdc, part, state, textToDraw, textToDraw.Length, (int) flags, disableFlag, new NativeMethods.COMRECT( bounds ) ); + + int disableFlag = drawDisabled ? 0x1 : 0; + + if (!string.IsNullOrEmpty(textToDraw)) + { + using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, AllGraphicsProperties)) + { + HandleRef hdc = new HandleRef(wgr, wgr.WindowsGraphics.DeviceContext.Hdc); + lastHResult = SafeNativeMethods.DrawThemeText(new HandleRef(this, Handle), hdc, part, state, textToDraw, textToDraw.Length, (int)flags, disableFlag, new NativeMethods.COMRECT(bounds)); } } } @@ -483,19 +568,23 @@ public void DrawText(IDeviceContext dc, Rectangle bounds, string textToDraw, boo /// [See win32 equivalent.] /// /// - public Rectangle GetBackgroundContentRectangle(IDeviceContext dc, Rectangle bounds) { - if( dc == null ){ + public Rectangle GetBackgroundContentRectangle(IDeviceContext dc, Rectangle bounds) + { + if (dc == null) + { throw new ArgumentNullException(nameof(dc)); } - if (bounds.Width < 0 || bounds.Height < 0) { + if (bounds.Width < 0 || bounds.Height < 0) + { return Rectangle.Empty; } - + NativeMethods.COMRECT rect = new NativeMethods.COMRECT(); - using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { - HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); - lastHResult = SafeNativeMethods.GetThemeBackgroundContentRect( new HandleRef( this, Handle ), hdc, part, state, new NativeMethods.COMRECT( bounds ), rect ); + using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, AllGraphicsProperties)) + { + HandleRef hdc = new HandleRef(wgr, wgr.WindowsGraphics.DeviceContext.Hdc); + lastHResult = SafeNativeMethods.GetThemeBackgroundContentRect(new HandleRef(this, Handle), hdc, part, state, new NativeMethods.COMRECT(bounds), rect); } return Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom); @@ -506,19 +595,23 @@ public Rectangle GetBackgroundContentRectangle(IDeviceContext dc, Rectangle boun /// [See win32 equivalent.] /// /// - public Rectangle GetBackgroundExtent(IDeviceContext dc, Rectangle contentBounds) { - if( dc == null ){ + public Rectangle GetBackgroundExtent(IDeviceContext dc, Rectangle contentBounds) + { + if (dc == null) + { throw new ArgumentNullException(nameof(dc)); } - if (contentBounds.Width < 0 || contentBounds.Height < 0) { + if (contentBounds.Width < 0 || contentBounds.Height < 0) + { return Rectangle.Empty; } - + NativeMethods.COMRECT rect = new NativeMethods.COMRECT(); - using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { - HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); - lastHResult = SafeNativeMethods.GetThemeBackgroundExtent( new HandleRef( this, Handle ), hdc, part, state, new NativeMethods.COMRECT( contentBounds ), rect ); + using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, AllGraphicsProperties)) + { + HandleRef hdc = new HandleRef(wgr, wgr.WindowsGraphics.DeviceContext.Hdc); + lastHResult = SafeNativeMethods.GetThemeBackgroundExtent(new HandleRef(this, Handle), hdc, part, state, new NativeMethods.COMRECT(contentBounds), rect); } return Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom); @@ -531,33 +624,38 @@ public Rectangle GetBackgroundExtent(IDeviceContext dc, Rectangle contentBounds) /// [See win32 equivalent.] /// /// - public Region GetBackgroundRegion(IDeviceContext dc, Rectangle bounds) { - if (dc == null) { + public Region GetBackgroundRegion(IDeviceContext dc, Rectangle bounds) + { + if (dc == null) + { throw new ArgumentNullException(nameof(dc)); } - if (bounds.Width < 0 || bounds.Height < 0) { + if (bounds.Width < 0 || bounds.Height < 0) + { return null; } IntPtr hRegion = IntPtr.Zero; - using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { - HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); - lastHResult = SafeNativeMethods.GetThemeBackgroundRegion( new HandleRef( this, Handle ), hdc, part, state, new NativeMethods.COMRECT( bounds ), ref hRegion ); + using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, AllGraphicsProperties)) + { + HandleRef hdc = new HandleRef(wgr, wgr.WindowsGraphics.DeviceContext.Hdc); + lastHResult = SafeNativeMethods.GetThemeBackgroundRegion(new HandleRef(this, Handle), hdc, part, state, new NativeMethods.COMRECT(bounds), ref hRegion); } // GetThemeBackgroundRegion returns a null hRegion if it fails to create one, it could be because the bounding // box is too big. For more info see code in %xpsrc%\shell\themes\uxtheme\imagefile.cpp if you have an enlistment to it. - if (hRegion == IntPtr.Zero) { - return null; - } + if (hRegion == IntPtr.Zero) + { + return null; + } - // From the GDI+ sources it doesn't appear as if they take ownership of the hRegion, so this is safe to do. - // We need to DeleteObject in order to not leak. - Region region = Region.FromHrgn(hRegion); - SafeNativeMethods.ExternalDeleteObject(new HandleRef(null, hRegion)); - return region; + // From the GDI+ sources it doesn't appear as if they take ownership of the hRegion, so this is safe to do. + // We need to DeleteObject in order to not leak. + Region region = Region.FromHrgn(hRegion); + SafeNativeMethods.ExternalDeleteObject(new HandleRef(null, hRegion)); + return region; } @@ -566,8 +664,10 @@ public Region GetBackgroundRegion(IDeviceContext dc, Rectangle bounds) { /// [See win32 equivalent.] /// /// - public bool GetBoolean(BooleanProperty prop) { - if (!ClientUtils.IsEnumValid(prop, (int)prop, (int)BooleanProperty.Transparent, (int)BooleanProperty.SourceShrink)){ + public bool GetBoolean(BooleanProperty prop) + { + if (!ClientUtils.IsEnumValid(prop, (int)prop, (int)BooleanProperty.Transparent, (int)BooleanProperty.SourceShrink)) + { throw new InvalidEnumArgumentException(nameof(prop), (int)prop, typeof(BooleanProperty)); } @@ -581,7 +681,8 @@ public bool GetBoolean(BooleanProperty prop) { /// [See win32 equivalent.] /// /// - public Color GetColor(ColorProperty prop) { + public Color GetColor(ColorProperty prop) + { //valid values are 0xed9 to 0xeef if (!ClientUtils.IsEnumValid(prop, (int)prop, (int)ColorProperty.BorderColor, (int)ColorProperty.AccentColorHint)) { @@ -598,7 +699,8 @@ public Color GetColor(ColorProperty prop) { /// [See win32 equivalent.] /// /// - public int GetEnumValue(EnumProperty prop) { + public int GetEnumValue(EnumProperty prop) + { //valid values are 0xfa1 to 0xfaf if (!ClientUtils.IsEnumValid(prop, (int)prop, (int)EnumProperty.BackgroundType, (int)EnumProperty.TrueSizeScalingType)) { @@ -615,7 +717,8 @@ public int GetEnumValue(EnumProperty prop) { /// [See win32 equivalent.] /// /// - public string GetFilename(FilenameProperty prop) { + public string GetFilename(FilenameProperty prop) + { //valid values are 0xbb9 to 0xbc0 if (!ClientUtils.IsEnumValid(prop, (int)prop, (int)FilenameProperty.ImageFile, (int)FilenameProperty.GlyphImageFile)) { @@ -636,10 +739,11 @@ public string GetFilename(FilenameProperty prop) { [SuppressMessage("Microsoft.Security", "CA2102:CatchNonClsCompliantExceptionsInGeneralHandlers")] public Font GetFont(IDeviceContext dc, FontProperty prop) { - if( dc == null ){ + if (dc == null) + { throw new ArgumentNullException(nameof(dc)); } - + //valid values are 0xa29 to 0xa29 if (!ClientUtils.IsEnumValid(prop, (int)prop, (int)FontProperty.GlyphFont, (int)FontProperty.GlyphFont)) { @@ -648,20 +752,25 @@ public Font GetFont(IDeviceContext dc, FontProperty prop) NativeMethods.LOGFONT logfont = new NativeMethods.LOGFONT(); - using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { - HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); - lastHResult = SafeNativeMethods.GetThemeFont( new HandleRef( this, Handle ), hdc, part, state, (int) prop, logfont ); + using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, AllGraphicsProperties)) + { + HandleRef hdc = new HandleRef(wgr, wgr.WindowsGraphics.DeviceContext.Hdc); + lastHResult = SafeNativeMethods.GetThemeFont(new HandleRef(this, Handle), hdc, part, state, (int)prop, logfont); } Font font = null; //check for a failed HR. - if (NativeMethods.Succeeded(lastHResult)) { - try { + if (NativeMethods.Succeeded(lastHResult)) + { + try + { font = Font.FromLogFont(logfont); } - catch (Exception e) { - if (ClientUtils.IsSecurityOrCriticalException(e)) { + catch (Exception e) + { + if (ClientUtils.IsSecurityOrCriticalException(e)) + { throw; } @@ -678,7 +787,8 @@ public Font GetFont(IDeviceContext dc, FontProperty prop) /// [See win32 equivalent.] /// /// - public int GetInteger(IntegerProperty prop) { + public int GetInteger(IntegerProperty prop) + { //valid values are 0x961 to 0x978 if (!ClientUtils.IsEnumValid(prop, (int)prop, (int)IntegerProperty.ImageCount, (int)IntegerProperty.MinDpi5)) { @@ -695,30 +805,38 @@ public int GetInteger(IntegerProperty prop) { /// [See win32 equivalent.] /// /// - public Size GetPartSize(IDeviceContext dc, ThemeSizeType type) { + public Size GetPartSize(IDeviceContext dc, ThemeSizeType type) + { return GetPartSize(dc, type, IntPtr.Zero); } - internal Size GetPartSize(IDeviceContext dc, ThemeSizeType type, IntPtr hWnd) { - if (dc == null) { + internal Size GetPartSize(IDeviceContext dc, ThemeSizeType type, IntPtr hWnd) + { + if (dc == null) + { throw new ArgumentNullException(nameof(dc)); } - + // valid values are 0x0 to 0x2 - if (!ClientUtils.IsEnumValid(type, (int)type, (int)ThemeSizeType.Minimum, (int)ThemeSizeType.Draw)) { + if (!ClientUtils.IsEnumValid(type, (int)type, (int)ThemeSizeType.Minimum, (int)ThemeSizeType.Draw)) + { throw new InvalidEnumArgumentException(nameof(type), (int)type, typeof(ThemeSizeType)); } NativeMethods.SIZE size = new NativeMethods.SIZE(); - using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties)) { - HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); - if (DpiHelper.IsPerMonitorV2Awareness && (IntPtr.Zero != hWnd)) { - using (ThemeHandle hTheme = ThemeHandle.Create(_class, true, new HandleRef(null, hWnd))) { + using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, AllGraphicsProperties)) + { + HandleRef hdc = new HandleRef(wgr, wgr.WindowsGraphics.DeviceContext.Hdc); + if (DpiHelper.IsPerMonitorV2Awareness && (IntPtr.Zero != hWnd)) + { + using (ThemeHandle hTheme = ThemeHandle.Create(_class, true, new HandleRef(null, hWnd))) + { lastHResult = SafeNativeMethods.GetThemePartSize(new HandleRef(this, hTheme.NativeHandle), hdc, part, state, null, type, size); } } - else { + else + { lastHResult = SafeNativeMethods.GetThemePartSize(new HandleRef(this, Handle), hdc, part, state, null, type, size); } } @@ -731,11 +849,13 @@ internal Size GetPartSize(IDeviceContext dc, ThemeSizeType type, IntPtr hWnd) { /// [See win32 equivalent.] /// /// - public Size GetPartSize(IDeviceContext dc, Rectangle bounds, ThemeSizeType type) { - if( dc == null ){ + public Size GetPartSize(IDeviceContext dc, Rectangle bounds, ThemeSizeType type) + { + if (dc == null) + { throw new ArgumentNullException(nameof(dc)); } - + //valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(type, (int)type, (int)ThemeSizeType.Minimum, (int)ThemeSizeType.Draw)) { @@ -744,20 +864,22 @@ public Size GetPartSize(IDeviceContext dc, Rectangle bounds, ThemeSizeType type) NativeMethods.SIZE size = new NativeMethods.SIZE(); - using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { - HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); - lastHResult = SafeNativeMethods.GetThemePartSize( new HandleRef( this, Handle ), hdc, part, state, new NativeMethods.COMRECT( bounds ), type, size ); + using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, AllGraphicsProperties)) + { + HandleRef hdc = new HandleRef(wgr, wgr.WindowsGraphics.DeviceContext.Hdc); + lastHResult = SafeNativeMethods.GetThemePartSize(new HandleRef(this, Handle), hdc, part, state, new NativeMethods.COMRECT(bounds), type, size); } return new Size(size.cx, size.cy); - } + } /// /// /// [See win32 equivalent.] /// /// - public Point GetPoint(PointProperty prop) { + public Point GetPoint(PointProperty prop) + { //valid values are 0xd49 to 0xd50 if (!ClientUtils.IsEnumValid(prop, (int)prop, (int)PointProperty.Offset, (int)PointProperty.MinSize5)) { @@ -767,18 +889,20 @@ public Point GetPoint(PointProperty prop) { NativeMethods.POINT point = new NativeMethods.POINT(); lastHResult = SafeNativeMethods.GetThemePosition(new HandleRef(this, Handle), part, state, (int)prop, point); return new Point(point.x, point.y); - } - + } + /// /// /// [See win32 equivalent.] /// /// - public Padding GetMargins(IDeviceContext dc, MarginProperty prop) { - if( dc == null ){ + public Padding GetMargins(IDeviceContext dc, MarginProperty prop) + { + if (dc == null) + { throw new ArgumentNullException(nameof(dc)); } - + //valid values are 0xe11 to 0xe13 if (!ClientUtils.IsEnumValid(prop, (int)prop, (int)MarginProperty.SizingMargins, (int)MarginProperty.CaptionMargins)) { @@ -787,21 +911,23 @@ public Padding GetMargins(IDeviceContext dc, MarginProperty prop) { NativeMethods.MARGINS margins = new NativeMethods.MARGINS(); - using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { - HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); - lastHResult = SafeNativeMethods.GetThemeMargins( new HandleRef( this, Handle ), hdc, part, state, (int) prop, prc: null, ref margins ); + using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, AllGraphicsProperties)) + { + HandleRef hdc = new HandleRef(wgr, wgr.WindowsGraphics.DeviceContext.Hdc); + lastHResult = SafeNativeMethods.GetThemeMargins(new HandleRef(this, Handle), hdc, part, state, (int)prop, prc: null, ref margins); } return new Padding(margins.cxLeftWidth, margins.cyTopHeight, margins.cxRightWidth, margins.cyBottomHeight); } - + /// /// /// [See win32 equivalent.] /// /// - public string GetString(StringProperty prop) { + public string GetString(StringProperty prop) + { //valid values are 0xc81 to 0xc81 if (!ClientUtils.IsEnumValid(prop, (int)prop, (int)StringProperty.Text, (int)StringProperty.Text)) { @@ -818,20 +944,24 @@ public string GetString(StringProperty prop) { /// [See win32 equivalent.] /// /// - public Rectangle GetTextExtent(IDeviceContext dc, string textToDraw, TextFormatFlags flags) { - if( dc == null ){ + public Rectangle GetTextExtent(IDeviceContext dc, string textToDraw, TextFormatFlags flags) + { + if (dc == null) + { throw new ArgumentNullException(nameof(dc)); } - if (string.IsNullOrEmpty(textToDraw)) { + if (string.IsNullOrEmpty(textToDraw)) + { throw new ArgumentNullException(nameof(textToDraw)); } NativeMethods.COMRECT rect = new NativeMethods.COMRECT(); - using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { - HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); - lastHResult = SafeNativeMethods.GetThemeTextExtent( new HandleRef( this, Handle ), hdc, part, state, textToDraw, textToDraw.Length, (int) flags, null, rect ); + using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, AllGraphicsProperties)) + { + HandleRef hdc = new HandleRef(wgr, wgr.WindowsGraphics.DeviceContext.Hdc); + lastHResult = SafeNativeMethods.GetThemeTextExtent(new HandleRef(this, Handle), hdc, part, state, textToDraw, textToDraw.Length, (int)flags, null, rect); } return Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom); @@ -842,20 +972,24 @@ public Rectangle GetTextExtent(IDeviceContext dc, string textToDraw, TextFormatF /// [See win32 equivalent.] /// /// - public Rectangle GetTextExtent(IDeviceContext dc, Rectangle bounds, string textToDraw, TextFormatFlags flags) { - if( dc == null ){ + public Rectangle GetTextExtent(IDeviceContext dc, Rectangle bounds, string textToDraw, TextFormatFlags flags) + { + if (dc == null) + { throw new ArgumentNullException(nameof(dc)); } - - if (string.IsNullOrEmpty(textToDraw)) { + + if (string.IsNullOrEmpty(textToDraw)) + { throw new ArgumentNullException(nameof(textToDraw)); } NativeMethods.COMRECT rect = new NativeMethods.COMRECT(); - using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { - HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); - lastHResult = SafeNativeMethods.GetThemeTextExtent( new HandleRef( this, Handle ), hdc, part, state, textToDraw, textToDraw.Length, (int) flags, new NativeMethods.COMRECT( bounds ), rect ); + using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, AllGraphicsProperties)) + { + HandleRef hdc = new HandleRef(wgr, wgr.WindowsGraphics.DeviceContext.Hdc); + lastHResult = SafeNativeMethods.GetThemeTextExtent(new HandleRef(this, Handle), hdc, part, state, textToDraw, textToDraw.Length, (int)flags, new NativeMethods.COMRECT(bounds), rect); } return Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom); @@ -866,16 +1000,19 @@ public Rectangle GetTextExtent(IDeviceContext dc, Rectangle bounds, string textT /// [See win32 equivalent.] /// /// - public TextMetrics GetTextMetrics(IDeviceContext dc) { - if( dc == null ){ + public TextMetrics GetTextMetrics(IDeviceContext dc) + { + if (dc == null) + { throw new ArgumentNullException(nameof(dc)); } - + TextMetrics tm = new TextMetrics(); - using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { - HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); - lastHResult = SafeNativeMethods.GetThemeTextMetrics( new HandleRef( this, Handle ), hdc, part, state, ref tm ); + using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, AllGraphicsProperties)) + { + HandleRef hdc = new HandleRef(wgr, wgr.WindowsGraphics.DeviceContext.Hdc); + lastHResult = SafeNativeMethods.GetThemeTextMetrics(new HandleRef(this, Handle), hdc, part, state, ref tm); } return tm; @@ -888,17 +1025,20 @@ public TextMetrics GetTextMetrics(IDeviceContext dc) { /// // PM team has reviewed and decided on naming changes already [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] - public HitTestCode HitTestBackground(IDeviceContext dc, Rectangle backgroundRectangle, Point pt, HitTestOptions options) { - if( dc == null ){ + public HitTestCode HitTestBackground(IDeviceContext dc, Rectangle backgroundRectangle, Point pt, HitTestOptions options) + { + if (dc == null) + { throw new ArgumentNullException(nameof(dc)); } - + int htCode = 0; NativeMethods.POINTSTRUCT point = new NativeMethods.POINTSTRUCT(pt.X, pt.Y); - using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { - HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); - lastHResult = SafeNativeMethods.HitTestThemeBackground( new HandleRef( this, Handle ), hdc, part, state, (int) options, new NativeMethods.COMRECT( backgroundRectangle ), NativeMethods.NullHandleRef, point, ref htCode ); + using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, AllGraphicsProperties)) + { + HandleRef hdc = new HandleRef(wgr, wgr.WindowsGraphics.DeviceContext.Hdc); + lastHResult = SafeNativeMethods.HitTestThemeBackground(new HandleRef(this, Handle), hdc, part, state, (int)options, new NativeMethods.COMRECT(backgroundRectangle), NativeMethods.NullHandleRef, point, ref htCode); } return (HitTestCode)htCode; @@ -911,8 +1051,10 @@ public HitTestCode HitTestBackground(IDeviceContext dc, Rectangle backgroundRect /// // PM team has reviewed and decided on naming changes already [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] - public HitTestCode HitTestBackground(Graphics g, Rectangle backgroundRectangle, Region region, Point pt, HitTestOptions options) { - if (g == null) { + public HitTestCode HitTestBackground(Graphics g, Rectangle backgroundRectangle, Region region, Point pt, HitTestOptions options) + { + if (g == null) + { throw new ArgumentNullException(nameof(g)); } @@ -929,17 +1071,20 @@ public HitTestCode HitTestBackground(Graphics g, Rectangle backgroundRectangle, /// // PM team has reviewed and decided on naming changes already [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] - public HitTestCode HitTestBackground(IDeviceContext dc, Rectangle backgroundRectangle, IntPtr hRgn, Point pt, HitTestOptions options) { - if( dc == null ){ + public HitTestCode HitTestBackground(IDeviceContext dc, Rectangle backgroundRectangle, IntPtr hRgn, Point pt, HitTestOptions options) + { + if (dc == null) + { throw new ArgumentNullException(nameof(dc)); } - + int htCode = 0; NativeMethods.POINTSTRUCT point = new NativeMethods.POINTSTRUCT(pt.X, pt.Y); - using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { - HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); - lastHResult = SafeNativeMethods.HitTestThemeBackground( new HandleRef( this, Handle ), hdc, part, state, (int) options, new NativeMethods.COMRECT( backgroundRectangle ), new HandleRef( this, hRgn ), point, ref htCode ); + using (WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper(dc, AllGraphicsProperties)) + { + HandleRef hdc = new HandleRef(wgr, wgr.WindowsGraphics.DeviceContext.Hdc); + lastHResult = SafeNativeMethods.HitTestThemeBackground(new HandleRef(this, Handle), hdc, part, state, (int)options, new NativeMethods.COMRECT(backgroundRectangle), new HandleRef(this, hRgn), point, ref htCode); } return (HitTestCode)htCode; @@ -950,7 +1095,8 @@ public HitTestCode HitTestBackground(IDeviceContext dc, Rectangle backgroundRect /// [See win32 equivalent.] /// /// - public bool IsBackgroundPartiallyTransparent() { + public bool IsBackgroundPartiallyTransparent() + { return (SafeNativeMethods.IsThemeBackgroundPartiallyTransparent(new HandleRef(this, Handle), part, state)); } @@ -958,8 +1104,10 @@ public bool IsBackgroundPartiallyTransparent() { /// This is similar to GetLastError in Win32. It returns the last HRESULT returned from a native call /// into theme apis. We eat the errors and let the user handle any errors that occurred. /// - public int LastHResult { - get { + public int LastHResult + { + get + { return lastHResult; } } @@ -969,7 +1117,8 @@ public int LastHResult { /// Instantiates the ThemeHandle cache hashtable. /// /// - private static void CreateThemeHandleHashtable() { + private static void CreateThemeHandleHashtable() + { themeHandles = new Hashtable(numberOfPossibleClasses); } @@ -979,15 +1128,17 @@ private static void CreateThemeHandleHashtable() { /// caches are refreshed. /// /// - private static void OnUserPreferenceChanging(object sender, UserPreferenceChangingEventArgs ea) { - if (ea.Category == UserPreferenceCategory.VisualStyle) { + private static void OnUserPreferenceChanging(object sender, UserPreferenceChangingEventArgs ea) + { + if (ea.Category == UserPreferenceCategory.VisualStyle) + { // Let all threads know their cached handles are no longer valid; // cache refresh will happen at next handle access. // Note that if the theme changes 2^sizeof(long) times before a thread uses // its handle, this whole version check won't work, but it is unlikely to happen. // this is not ideal. - globalCacheVersion++; + globalCacheVersion++; } } @@ -996,24 +1147,30 @@ private static void OnUserPreferenceChanging(object sender, UserPreferenceChangi /// Refreshes this thread's theme handle cache. /// /// - private static void RefreshCache() { + private static void RefreshCache() + { ThemeHandle tHandle = null; - if (themeHandles != null) { + if (themeHandles != null) + { string[] classNames = new string[themeHandles.Keys.Count]; themeHandles.Keys.CopyTo(classNames, 0); - - foreach (string className in classNames) { - tHandle = (ThemeHandle) themeHandles[className]; - if (tHandle != null) { + + foreach (string className in classNames) + { + tHandle = (ThemeHandle)themeHandles[className]; + if (tHandle != null) + { tHandle.Dispose(); } // We don't call IsSupported here, since that could cause RefreshCache to be called again, // leading to stack overflow. - if (AreClientAreaVisualStylesSupported) { + if (AreClientAreaVisualStylesSupported) + { tHandle = ThemeHandle.Create(className, false); - if (tHandle != null) { + if (tHandle != null) + { themeHandles[className] = tHandle; } } @@ -1021,7 +1178,8 @@ private static void RefreshCache() { } } - private static IntPtr GetHandle(string className) { + private static IntPtr GetHandle(string className) + { return GetHandle(className, true); } @@ -1031,52 +1189,64 @@ private static IntPtr GetHandle(string className) { /// present in the cache, it creates a new ThemeHandle object and stores it there. /// /// - private static IntPtr GetHandle(string className, bool throwExceptionOnFail) { + private static IntPtr GetHandle(string className, bool throwExceptionOnFail) + { ThemeHandle tHandle; - if (themeHandles == null) { + if (themeHandles == null) + { CreateThemeHandleHashtable(); } - if (threadCacheVersion != globalCacheVersion) { + if (threadCacheVersion != globalCacheVersion) + { RefreshCache(); threadCacheVersion = globalCacheVersion; } - if (!themeHandles.Contains(className)) { // see if it is already in cache + if (!themeHandles.Contains(className)) + { // see if it is already in cache tHandle = ThemeHandle.Create(className, throwExceptionOnFail); - if (tHandle == null) { + if (tHandle == null) + { return IntPtr.Zero; } themeHandles.Add(className, tHandle); } - else { - tHandle = (ThemeHandle) themeHandles[className]; + else + { + tHandle = (ThemeHandle)themeHandles[className]; } return tHandle.NativeHandle; } // This wrapper class is needed for safely cleaning up TLS cache of handles. - private class ThemeHandle : IDisposable { + private class ThemeHandle : IDisposable + { private IntPtr _hTheme = IntPtr.Zero; - private ThemeHandle(IntPtr hTheme) { + private ThemeHandle(IntPtr hTheme) + { _hTheme = hTheme; - } + } - public IntPtr NativeHandle { - get { + public IntPtr NativeHandle + { + get + { return _hTheme; } } - public static ThemeHandle Create(string className, bool throwExceptionOnFail) { + public static ThemeHandle Create(string className, bool throwExceptionOnFail) + { return Create(className, throwExceptionOnFail, new HandleRef(null, IntPtr.Zero)); } - internal static ThemeHandle Create(string className, bool throwExceptionOnFail, HandleRef hWndRef) { + internal static ThemeHandle Create(string className, bool throwExceptionOnFail, HandleRef hWndRef) + { // HThemes require an HWND when display scaling is different between monitors. IntPtr hTheme = IntPtr.Zero; @@ -1102,26 +1272,32 @@ internal static ThemeHandle Create(string className, bool throwExceptionOnFail, } } - if (hTheme == IntPtr.Zero) { - if (throwExceptionOnFail) { + if (hTheme == IntPtr.Zero) + { + if (throwExceptionOnFail) + { throw new InvalidOperationException(SR.VisualStyleHandleCreationFailed); } - else { + else + { return null; } } - return new ThemeHandle(hTheme); + return new ThemeHandle(hTheme); } - public void Dispose() { - if (_hTheme != IntPtr.Zero) { + public void Dispose() + { + if (_hTheme != IntPtr.Zero) + { SafeNativeMethods.CloseThemeData(new HandleRef(null, _hTheme)); _hTheme = IntPtr.Zero; } GC.SuppressFinalize(this); } - ~ThemeHandle() { + ~ThemeHandle() + { Dispose(); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleState.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleState.cs index 46c855065cd..ea036849450 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleState.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleState.cs @@ -4,7 +4,7 @@ using System.Diagnostics.CodeAnalysis; -[assembly: SuppressMessage("Microsoft.MSInternal", "CA905:SystemAndMicrosoftNamespacesRequireApproval", Scope="namespace", Target="System.Windows.Forms.VisualStyles")] +[assembly: SuppressMessage("Microsoft.MSInternal", "CA905:SystemAndMicrosoftNamespacesRequireApproval", Scope = "namespace", Target = "System.Windows.Forms.VisualStyles")] namespace System.Windows.Forms.VisualStyles { @@ -32,6 +32,6 @@ public enum VisualStyleState /// /// Visual styles enabled only for client and non-client areas. /// - ClientAndNonClientAreasEnabled = NativeMethods.STAP_ALLOW_NONCLIENT | NativeMethods.STAP_ALLOW_CONTROLS + ClientAndNonClientAreasEnabled = NativeMethods.STAP_ALLOW_NONCLIENT | NativeMethods.STAP_ALLOW_CONTROLS } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs index ea038f896f1..5080d87eb56 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs @@ -29,13 +29,14 @@ namespace System.Windows.Forms Docking(DockingBehavior.AutoDock), SRDescription(nameof(SR.DescriptionWebBrowser)), Designer("System.Windows.Forms.Design.WebBrowserDesigner, " + AssemblyRef.SystemDesign)] - public class WebBrowser : WebBrowserBase { + public class WebBrowser : WebBrowserBase + { private static bool createdInIE; // Reference to the native ActiveX control's IWebBrowser2 // Do not reference this directly. Use the AxIWebBrowser2 // property instead. - private UnsafeNativeMethods.IWebBrowser2 axIWebBrowser2; + private UnsafeNativeMethods.IWebBrowser2 axIWebBrowser2; private AxHost.ConnectionPointCookie cookie; // To hook up events from the native WebBrowser private Stream documentStreamToSetOnLoad; @@ -45,13 +46,13 @@ public class WebBrowser : WebBrowserBase { internal string statusText = string.Empty; - private const int WEBBROWSERSTATE_webBrowserShortcutsEnabled = 0x00000001; - private const int WEBBROWSERSTATE_documentStreamJustSet = 0x00000002; - private const int WEBBROWSERSTATE_isWebBrowserContextMenuEnabled = 0x00000004; - private const int WEBBROWSERSTATE_canGoBack = 0x00000008; - private const int WEBBROWSERSTATE_canGoForward = 0x00000010; - private const int WEBBROWSERSTATE_scrollbarsEnabled = 0x00000020; - private const int WEBBROWSERSTATE_allowNavigation = 0x00000040; + private const int WEBBROWSERSTATE_webBrowserShortcutsEnabled = 0x00000001; + private const int WEBBROWSERSTATE_documentStreamJustSet = 0x00000002; + private const int WEBBROWSERSTATE_isWebBrowserContextMenuEnabled = 0x00000004; + private const int WEBBROWSERSTATE_canGoBack = 0x00000008; + private const int WEBBROWSERSTATE_canGoForward = 0x00000010; + private const int WEBBROWSERSTATE_scrollbarsEnabled = 0x00000020; + private const int WEBBROWSERSTATE_allowNavigation = 0x00000040; // PERF: take all the bools and put them into a state variable private System.Collections.Specialized.BitVector32 webBrowserState; // see TREEVIEWSTATE_ consts above @@ -65,9 +66,10 @@ public class WebBrowser : WebBrowserBase { /// Creates an instance of the control. /// /// - public WebBrowser() : base("8856f961-340a-11d0-a96b-00c04fd705a2") { - CheckIfCreatedInIE(); - + public WebBrowser() : base("8856f961-340a-11d0-a96b-00c04fd705a2") + { + CheckIfCreatedInIE(); + webBrowserState = new System.Collections.Specialized.BitVector32(WEBBROWSERSTATE_isWebBrowserContextMenuEnabled | WEBBROWSERSTATE_webBrowserShortcutsEnabled | WEBBROWSERSTATE_scrollbarsEnabled); AllowNavigation = true; @@ -115,20 +117,24 @@ public bool AllowNavigation /// [SRDescription(nameof(SR.WebBrowserAllowWebBrowserDropDescr)), SRCategory(nameof(SR.CatBehavior)), DefaultValue(true)] - public bool AllowWebBrowserDrop { - get { + public bool AllowWebBrowserDrop + { + get + { return this.AxIWebBrowser2.RegisterAsDropTarget; } - set { + set + { //Note: you lose this value when you load a new document: the value needs to be refreshed in //OnDocumentCompleted. - if (value != AllowWebBrowserDrop) { + if (value != AllowWebBrowserDrop) + { this.AxIWebBrowser2.RegisterAsDropTarget = value; this.Refresh(); } } } - + /// /// /// Specifies whether the browser control shows script errors in dialogs or not. @@ -137,12 +143,16 @@ public bool AllowWebBrowserDrop { /// [SRDescription(nameof(SR.WebBrowserScriptErrorsSuppressedDescr)), SRCategory(nameof(SR.CatBehavior)), DefaultValue(false)] - public bool ScriptErrorsSuppressed { - get { + public bool ScriptErrorsSuppressed + { + get + { return this.AxIWebBrowser2.Silent; } - set { - if (value != ScriptErrorsSuppressed) { + set + { + if (value != ScriptErrorsSuppressed) + { this.AxIWebBrowser2.Silent = value; } } @@ -156,11 +166,14 @@ public bool ScriptErrorsSuppressed { /// [SRDescription(nameof(SR.WebBrowserWebBrowserShortcutsEnabledDescr)), SRCategory(nameof(SR.CatBehavior)), DefaultValue(true)] - public bool WebBrowserShortcutsEnabled { - get { + public bool WebBrowserShortcutsEnabled + { + get + { return webBrowserState[WEBBROWSERSTATE_webBrowserShortcutsEnabled]; } - set { + set + { webBrowserState[WEBBROWSERSTATE_webBrowserShortcutsEnabled] = value; } } @@ -173,8 +186,10 @@ public bool WebBrowserShortcutsEnabled { /// /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool CanGoBack { - get { + public bool CanGoBack + { + get + { return CanGoBackInternal; } } @@ -183,18 +198,22 @@ public bool CanGoBack { /// Returns the current WEBBROWSERSTATE_canGoBack value so that this value can be accessed /// from child classes. /// - internal bool CanGoBackInternal { - get { + internal bool CanGoBackInternal + { + get + { return webBrowserState[WEBBROWSERSTATE_canGoBack]; } - set { - if (value != CanGoBackInternal) { + set + { + if (value != CanGoBackInternal) + { webBrowserState[WEBBROWSERSTATE_canGoBack] = value; OnCanGoBackChanged(EventArgs.Empty); } } } - + /// /// /// If true, there is navigation history such that calling GoForward() will succeed. @@ -203,22 +222,28 @@ internal bool CanGoBackInternal { /// /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool CanGoForward { - get { + public bool CanGoForward + { + get + { return CanGoForwardInternal; } } - + /// /// Returns the current WEBBROWSERSTATE_canGoForward value so that this value can /// be accessed from child classes. /// - internal bool CanGoForwardInternal { - get { + internal bool CanGoForwardInternal + { + get + { return webBrowserState[WEBBROWSERSTATE_canGoForward]; } - set { - if (value != CanGoForwardInternal) { + set + { + if (value != CanGoForwardInternal) + { webBrowserState[WEBBROWSERSTATE_canGoForward] = value; OnCanGoForwardChanged(EventArgs.Empty); } @@ -232,25 +257,32 @@ internal bool CanGoForwardInternal { /// /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public HtmlDocument Document { - get { + public HtmlDocument Document + { + get + { object objDoc = this.AxIWebBrowser2.Document; - if (objDoc != null) { + if (objDoc != null) + { // Document is not necessarily an IHTMLDocument, it might be an office document as well. UnsafeNativeMethods.IHTMLDocument2 iHTMLDocument2 = null; - try { + try + { iHTMLDocument2 = objDoc as UnsafeNativeMethods.IHTMLDocument2; - } - catch (InvalidCastException) { } - if (iHTMLDocument2 != null) { + catch (InvalidCastException) + { + } + if (iHTMLDocument2 != null) + { UnsafeNativeMethods.IHTMLLocation iHTMLLocation = iHTMLDocument2.GetLocation(); - if (iHTMLLocation != null) { + if (iHTMLLocation != null) + { string href = iHTMLLocation.GetHref(); if (!string.IsNullOrEmpty(href)) { Uri url = new Uri(href); - return new HtmlDocument (ShimManager, iHTMLDocument2 as UnsafeNativeMethods.IHTMLDocument); + return new HtmlDocument(ShimManager, iHTMLDocument2 as UnsafeNativeMethods.IHTMLDocument); } } } @@ -258,7 +290,7 @@ public HtmlDocument Document { return null; } } - + /// /// /// Get/sets the stream for the html document. @@ -266,19 +298,25 @@ public HtmlDocument Document { /// /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public Stream DocumentStream { - get { - HtmlDocument htmlDocument = this.Document; - if (htmlDocument == null) { + public Stream DocumentStream + { + get + { + HtmlDocument htmlDocument = this.Document; + if (htmlDocument == null) + { return null; } - else { + else + { UnsafeNativeMethods.IPersistStreamInit psi = htmlDocument.DomDocument as UnsafeNativeMethods.IPersistStreamInit; Debug.Assert(psi != null, "Object isn't an IPersistStreamInit!"); - if (psi == null) { + if (psi == null) + { return null; } - else { + else + { MemoryStream memoryStream = new MemoryStream(); UnsafeNativeMethods.IStream iStream = (UnsafeNativeMethods.IStream)new UnsafeNativeMethods.ComStreamFromDataStream(memoryStream); psi.Save(iStream, false); @@ -286,27 +324,32 @@ public Stream DocumentStream { } } } - set { + set + { this.documentStreamToSetOnLoad = value; - try { + try + { webBrowserState[WEBBROWSERSTATE_documentStreamJustSet] = true; // Lets navigate to "about:blank" so that we get a "clean" document this.Url = new Uri("about:blank"); } - finally { + finally + { webBrowserState[WEBBROWSERSTATE_documentStreamJustSet] = false; } } } - + /// /// /// Sets/sets the text of the contained html page. /// /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string DocumentText { - get { + public string DocumentText + { + get + { Stream stream = this.DocumentStream; if (stream == null) { @@ -316,7 +359,8 @@ public string DocumentText { stream.Position = 0; return reader.ReadToEnd(); } - set { + set + { if (value == null) { value = string.Empty; @@ -324,7 +368,7 @@ public string DocumentText { //string length is a good initial guess for capacity -- //if it needs more room, it'll take it. MemoryStream ms = new MemoryStream(value.Length); - StreamWriter sw = new StreamWriter(ms, Encoding.UTF8 ); + StreamWriter sw = new StreamWriter(ms, Encoding.UTF8); sw.Write(value); sw.Flush(); ms.Position = 0; @@ -339,28 +383,34 @@ public string DocumentText { /// /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string DocumentTitle { - get { + public string DocumentTitle + { + get + { string documentTitle; HtmlDocument htmlDocument = this.Document; - if (htmlDocument == null) { + if (htmlDocument == null) + { documentTitle = this.AxIWebBrowser2.LocationName; } - else { + else + { UnsafeNativeMethods.IHTMLDocument2 htmlDocument2 = htmlDocument.DomDocument as UnsafeNativeMethods.IHTMLDocument2; Debug.Assert(htmlDocument2 != null, "The HtmlDocument object must implement IHTMLDocument2."); - try { + try + { documentTitle = htmlDocument2.GetTitle(); } - catch (COMException) { + catch (COMException) + { documentTitle = string.Empty; } } return documentTitle; } } - + /// /// /// A string containing the MIME type of the document hosted in the browser control. @@ -368,24 +418,29 @@ public string DocumentTitle { /// /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string DocumentType { - get { + public string DocumentType + { + get + { string docType = string.Empty; HtmlDocument htmlDocument = this.Document; - if (htmlDocument != null) { + if (htmlDocument != null) + { UnsafeNativeMethods.IHTMLDocument2 htmlDocument2 = htmlDocument.DomDocument as UnsafeNativeMethods.IHTMLDocument2; Debug.Assert(htmlDocument2 != null, "The HtmlDocument object must implement IHTMLDocument2."); - try { + try + { docType = htmlDocument2.GetMimeType(); } - catch (COMException) { + catch (COMException) + { docType = string.Empty; } } return docType; } } - + /// /// /// Initially set to WebBrowserEncryptionLevel.Insecure. @@ -393,44 +448,53 @@ public string DocumentType { /// /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public WebBrowserEncryptionLevel EncryptionLevel { - get { - if (this.Document == null) { + public WebBrowserEncryptionLevel EncryptionLevel + { + get + { + if (this.Document == null) + { encryptionLevel = WebBrowserEncryptionLevel.Unknown; } return encryptionLevel; } } - + /// /// /// True if the browser is engaged in navigation or download. Maps to IWebBrowser2:Busy. /// /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsBusy { - get { - if (this.Document == null) { + public bool IsBusy + { + get + { + if (this.Document == null) + { return false; } - else { + else + { return this.AxIWebBrowser2.Busy; } } } - + /// /// /// Gets the offline state of the browser control. Maps to IWebBrowser2:Offline. /// /// [SRDescription(nameof(SR.WebBrowserIsOfflineDescr)), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsOffline { - get { + public bool IsOffline + { + get + { return this.AxIWebBrowser2.Offline; } } - + /// /// /// Indicates whether to use the WebBrowser context menu. @@ -442,11 +506,14 @@ public bool IsOffline { /// [SRDescription(nameof(SR.WebBrowserIsWebBrowserContextMenuEnabledDescr)), SRCategory(nameof(SR.CatBehavior)), DefaultValue(true)] - public bool IsWebBrowserContextMenuEnabled { - get { + public bool IsWebBrowserContextMenuEnabled + { + get + { return webBrowserState[WEBBROWSERSTATE_isWebBrowserContextMenuEnabled]; } - set { + set + { webBrowserState[WEBBROWSERSTATE_isWebBrowserContextMenuEnabled] = value; } } @@ -460,13 +527,13 @@ public bool IsWebBrowserContextMenuEnabled { /// /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public object ObjectForScripting + public object ObjectForScripting { - get + get { return objectForScripting; } - set + set { if (value != null) { @@ -487,9 +554,10 @@ public object ObjectForScripting EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] - public new Padding Padding { + public new Padding Padding + { get { return base.Padding; } - set { base.Padding = value;} + set { base.Padding = value; } } [ @@ -511,12 +579,16 @@ public object ObjectForScripting /// /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public WebBrowserReadyState ReadyState { - get { - if (this.Document == null) { + public WebBrowserReadyState ReadyState + { + get + { + if (this.Document == null) + { return WebBrowserReadyState.Uninitialized; } - else { + else + { return (WebBrowserReadyState)this.AxIWebBrowser2.ReadyState; } } @@ -531,9 +603,12 @@ public WebBrowserReadyState ReadyState { /// /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public virtual string StatusText { - get { - if (this.Document == null) { + public virtual string StatusText + { + get + { + if (this.Document == null) + { statusText = string.Empty; } return statusText; @@ -555,8 +630,10 @@ public virtual string StatusText { TypeConverter(typeof(System.Windows.Forms.WebBrowserUriTypeConverter)), DefaultValue(null) ] - public Uri Url { - get { + public Uri Url + { + get + { string urlString = this.AxIWebBrowser2.LocationURL; if (string.IsNullOrEmpty(urlString)) @@ -572,7 +649,8 @@ public Uri Url { return null; } } - set { + set + { if (value != null && value.ToString() == "") { value = null; @@ -588,14 +666,16 @@ public Uri Url { /// /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public Version Version { - get { + public Version Version + { + get + { string mshtmlPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "mshtml.dll"); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(mshtmlPath); return new Version(fvi.FileMajorPart, fvi.FileMinorPart, fvi.FileBuildPart, fvi.FilePrivatePart); } } - + // @@ -610,7 +690,8 @@ public Version Version { /// false if there is no page in the navigation history to go back to. /// /// - public bool GoBack() { + public bool GoBack() + { bool retVal = true; try { @@ -626,7 +707,7 @@ public bool GoBack() { } return retVal; } - + /// /// /// Navigates the browser to the next page in the navigation history list. @@ -635,7 +716,8 @@ public bool GoBack() { /// false if there is no page in the navigation history to go forward to. /// /// - public bool GoForward() { + public bool GoForward() + { bool retVal = true; try { @@ -651,22 +733,24 @@ public bool GoForward() { } return retVal; } - + /// /// /// Navigates the browser to user's homepage. Maps to IWebBrowser2:GoHome. /// /// - public void GoHome() { + public void GoHome() + { this.AxIWebBrowser2.GoHome(); } - + /// /// /// Navigates the browser to user's default search page. Maps to IWebBrowser2:GoSearch. /// /// - public void GoSearch() { + public void GoSearch() + { this.AxIWebBrowser2.GoSearch(); } @@ -729,7 +813,8 @@ public void Navigate(string urlString, string targetFrameName) /// Opens a new window if newWindow is true, navigating it to the specified URL. Maps to IWebBrowser2:Navigate. /// /// - public void Navigate(Uri url, bool newWindow) { + public void Navigate(Uri url, bool newWindow) + { PerformNavigateHelper(ReadyNavigateToUrl(url), newWindow, null, null, null); } @@ -781,7 +866,8 @@ public void Navigate(string urlString, string targetFrameName, byte[] postData, /// Maps to IWebBrowser2:ExecWB w/ IDM_PRINT flag & LECMDEXECOPT_DONTPROMPTUSER. /// /// - public void Print() { + public void Print() + { object nullObjectArray = null; try { @@ -795,13 +881,14 @@ public void Print() { } } } - + /// /// /// Refreshes the current page. Maps to IWebBrowser2:Refresh. /// /// - public override void Refresh() { + public override void Refresh() + { try { if (ShouldSerializeDocumentText()) @@ -823,7 +910,7 @@ public override void Refresh() { } } } - + /// /// /// Refreshes the current page w/ the specified refresh option. The refresh option @@ -831,9 +918,11 @@ public override void Refresh() { /// Maps to IWebBrowser2:Refresh2 /// /// - public void Refresh(WebBrowserRefreshOption opt) { - object level = (object) opt; - try { + public void Refresh(WebBrowserRefreshOption opt) + { + object level = (object)opt; + try + { if (ShouldSerializeDocumentText()) { string text = this.DocumentText; @@ -845,13 +934,15 @@ public void Refresh(WebBrowserRefreshOption opt) { this.AxIWebBrowser2.Refresh2(ref level); } } - catch (Exception ex) { - if (ClientUtils.IsSecurityOrCriticalException(ex)) { + catch (Exception ex) + { + if (ClientUtils.IsSecurityOrCriticalException(ex)) + { throw; } } } - + /// /// /// Enables/disables the webbrowser's scrollbars. @@ -859,122 +950,150 @@ public void Refresh(WebBrowserRefreshOption opt) { /// [SRDescription(nameof(SR.WebBrowserScrollBarsEnabledDescr)), SRCategory(nameof(SR.CatBehavior)), DefaultValue(true)] - public bool ScrollBarsEnabled { - get { + public bool ScrollBarsEnabled + { + get + { return webBrowserState[WEBBROWSERSTATE_scrollbarsEnabled]; } - set { - if (value != webBrowserState[WEBBROWSERSTATE_scrollbarsEnabled]) { + set + { + if (value != webBrowserState[WEBBROWSERSTATE_scrollbarsEnabled]) + { webBrowserState[WEBBROWSERSTATE_scrollbarsEnabled] = value; this.Refresh(); } } } - + /// /// /// Opens the IE page setup dialog for the current page. /// Maps to IWebBrowser2:ExecWebBrowser w/ IDM_PAGESETUP flag & LECMDEXECOPT_PROMPTUSER. /// /// - public void ShowPageSetupDialog() { + public void ShowPageSetupDialog() + { object nullObjectArray = null; - try { + try + { this.AxIWebBrowser2.ExecWB(NativeMethods.OLECMDID.OLECMDID_PAGESETUP, NativeMethods.OLECMDEXECOPT.OLECMDEXECOPT_PROMPTUSER, ref nullObjectArray, IntPtr.Zero); } - catch (Exception ex) { - if (ClientUtils.IsSecurityOrCriticalException(ex)) { + catch (Exception ex) + { + if (ClientUtils.IsSecurityOrCriticalException(ex)) + { throw; } } } - + /// /// /// Opens the IE print dialog. /// Maps to IWebBrowser2:ExecWebBrowser w/ IDM_PRINT flag & OLECMDEXECOPT_PROMPTUSER. /// /// - public void ShowPrintDialog() { + public void ShowPrintDialog() + { object nullObjectArray = null; - - try { + + try + { this.AxIWebBrowser2.ExecWB(NativeMethods.OLECMDID.OLECMDID_PRINT, NativeMethods.OLECMDEXECOPT.OLECMDEXECOPT_PROMPTUSER, ref nullObjectArray, IntPtr.Zero); } - catch (Exception ex) { - if (ClientUtils.IsSecurityOrCriticalException(ex)) { + catch (Exception ex) + { + if (ClientUtils.IsSecurityOrCriticalException(ex)) + { throw; } } } - + /// /// /// Opens the IE print preview dialog. Maps to IWebBrowser2:ExecWebBrowser w/ IDM_PRINTPREVIEW flag. /// /// - public void ShowPrintPreviewDialog() { + public void ShowPrintPreviewDialog() + { object nullObjectArray = null; - - try { + + try + { this.AxIWebBrowser2.ExecWB(NativeMethods.OLECMDID.OLECMDID_PRINTPREVIEW, NativeMethods.OLECMDEXECOPT.OLECMDEXECOPT_PROMPTUSER, ref nullObjectArray, IntPtr.Zero); } - catch (Exception ex) { - if (ClientUtils.IsSecurityOrCriticalException(ex)) { + catch (Exception ex) + { + if (ClientUtils.IsSecurityOrCriticalException(ex)) + { throw; } } } - + /// /// /// Opens the properties dialog for the current html page. /// Maps to IWebBrowser2:ExecWebBrowser w/ IDM_PROPERTIES flag & LECMDEXECOPT_PROMPTUSER. /// /// - public void ShowPropertiesDialog() { + public void ShowPropertiesDialog() + { object nullObjectArray = null; - - try { + + try + { this.AxIWebBrowser2.ExecWB(NativeMethods.OLECMDID.OLECMDID_PROPERTIES, NativeMethods.OLECMDEXECOPT.OLECMDEXECOPT_PROMPTUSER, ref nullObjectArray, IntPtr.Zero); } - catch (Exception ex) { - if (ClientUtils.IsSecurityOrCriticalException(ex)) { + catch (Exception ex) + { + if (ClientUtils.IsSecurityOrCriticalException(ex)) + { throw; } } } - + /// /// /// Opens the IE File-Save dialog. /// Maps to IWebBrowser2:ExecWebBrowser w/ IDM_SAVEAS flag & LECMDEXECOPT_PROMPTUSER. /// /// - public void ShowSaveAsDialog() { + public void ShowSaveAsDialog() + { object nullObjectArray = null; - - try { + + try + { this.AxIWebBrowser2.ExecWB(NativeMethods.OLECMDID.OLECMDID_SAVEAS, NativeMethods.OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, ref nullObjectArray, IntPtr.Zero); } - catch (Exception ex) { - if (ClientUtils.IsSecurityOrCriticalException(ex)) { + catch (Exception ex) + { + if (ClientUtils.IsSecurityOrCriticalException(ex)) + { throw; } } } - + /// /// /// Stops the current navigation. Maps to IWebBrowser2:Stop. /// /// - public void Stop() { - try { + public void Stop() + { + try + { this.AxIWebBrowser2.Stop(); } - catch (Exception ex) { - if (ClientUtils.IsSecurityOrCriticalException(ex)) { + catch (Exception ex) + { + if (ClientUtils.IsSecurityOrCriticalException(ex)) + { throw; } } @@ -1090,9 +1209,12 @@ public void Stop() { /// /// Returns true if this control (or any of its child windows) has focus. /// - public override bool Focused { - get { - if (base.Focused) { + public override bool Focused + { + get + { + if (base.Focused) + { return true; } IntPtr hwndFocus = UnsafeNativeMethods.GetFocus(); @@ -1107,8 +1229,10 @@ public override bool Focused { // // // - protected override void Dispose(bool disposing) { - if (disposing) { + protected override void Dispose(bool disposing) + { + if (disposing) + { if (htmlShimManager != null) { htmlShimManager.Dispose(); @@ -1124,8 +1248,10 @@ protected override void Dispose(bool disposing) { /// Overrides the default size property of Control to specify a bigger default size of 250 x 250. /// /// - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(250, 250); } } @@ -1135,7 +1261,8 @@ protected override Size DefaultSize { /// Retrieves IWebBrowser2 from the native object. Overriding classes should first call base.AttachInterfaces. /// /// - protected override void AttachInterfaces(object nativeActiveXObject) { + protected override void AttachInterfaces(object nativeActiveXObject) + { this.axIWebBrowser2 = (UnsafeNativeMethods.IWebBrowser2)nativeActiveXObject; } @@ -1144,16 +1271,18 @@ protected override void AttachInterfaces(object nativeActiveXObject) { /// Discards the IWebBrowser2 reference. Overriding classes should call base.DetachInterfaces. /// /// - protected override void DetachInterfaces() { + protected override void DetachInterfaces() + { this.axIWebBrowser2 = null; } - + /// /// /// Returns a WebBrowserSite object. /// /// - protected override WebBrowserSiteBase CreateWebBrowserSiteBase() { + protected override WebBrowserSiteBase CreateWebBrowserSiteBase() + { return new WebBrowserSite(this); } @@ -1162,35 +1291,42 @@ protected override WebBrowserSiteBase CreateWebBrowserSiteBase() { /// Attaches to the DWebBrowserEvents2 connection point. /// /// - protected override void CreateSink() { + protected override void CreateSink() + { object ax = this.activeXInstance; - if (ax != null) { + if (ax != null) + { webBrowserEvent = new WebBrowserEvent(this); webBrowserEvent.AllowNavigation = AllowNavigation; this.cookie = new AxHost.ConnectionPointCookie(ax, webBrowserEvent, typeof(UnsafeNativeMethods.DWebBrowserEvents2)); } } - + /// /// /// Releases the DWebBrowserEvents2 connection point. /// /// - protected override void DetachSink() { + protected override void DetachSink() + { //If we have a cookie get rid of it - if (this.cookie != null) { + if (this.cookie != null) + { this.cookie.Disconnect(); this.cookie = null; } } - internal override void OnTopMostActiveXParentChanged(EventArgs e) { - if (TopMostParent.IsIEParent) { + internal override void OnTopMostActiveXParentChanged(EventArgs e) + { + if (TopMostParent.IsIEParent) + { WebBrowser.createdInIE = true; CheckIfCreatedInIE(); } - else { + else + { WebBrowser.createdInIE = false; base.OnTopMostActiveXParentChanged(e); } @@ -1369,46 +1505,56 @@ protected virtual void OnStatusTextChanged(EventArgs e) } -#region ShimSupport - private HtmlShimManager htmlShimManager; - internal HtmlShimManager ShimManager { - get { - if (htmlShimManager == null) { + #region ShimSupport + private HtmlShimManager htmlShimManager; + internal HtmlShimManager ShimManager + { + get + { + if (htmlShimManager == null) + { htmlShimManager = new HtmlShimManager(); } return htmlShimManager; } } -#endregion + #endregion // // Private methods: // - private void CheckIfCreatedInIE() { - if (WebBrowser.createdInIE) { - if (this.ParentInternal != null) { + private void CheckIfCreatedInIE() + { + if (WebBrowser.createdInIE) + { + if (this.ParentInternal != null) + { this.ParentInternal.Controls.Remove(this); this.Dispose(); } - else { + else + { this.Dispose(); throw new NotSupportedException(SR.WebBrowserInIENotSupported); } } } - private string ReadyNavigateToUrl(string urlString) { - if (string.IsNullOrEmpty(urlString)) { + private string ReadyNavigateToUrl(string urlString) + { + if (string.IsNullOrEmpty(urlString)) + { urlString = "about:blank"; - } + } // // Nullify any calls to set_DocumentStream which may still be pending - if (!webBrowserState[WEBBROWSERSTATE_documentStreamJustSet]) { + if (!webBrowserState[WEBBROWSERSTATE_documentStreamJustSet]) + { this.documentStreamToSetOnLoad = null; } - + return urlString; } @@ -1439,20 +1585,23 @@ private string ReadyNavigateToUrl(Uri url) private void PerformNavigateHelper(string urlString, bool newWindow, string targetFrameName, byte[] postData, string headers) { object objUrlString = (object)urlString; - object objFlags = (object) (newWindow ? 1 : 0); + object objFlags = (object)(newWindow ? 1 : 0); object objTargetFrameName = (object)targetFrameName; object objPostData = (object)postData; object objHeaders = (object)headers; PerformNavigate2(ref objUrlString, ref objFlags, ref objTargetFrameName, ref objPostData, ref objHeaders); } - private void PerformNavigate2(ref object URL, ref object flags, ref object targetFrameName, ref object postData, ref object headers) + private void PerformNavigate2(ref object URL, ref object flags, ref object targetFrameName, ref object postData, ref object headers) { - try { + try + { this.AxIWebBrowser2.Navigate2(ref URL, ref flags, ref targetFrameName, ref postData, ref headers); } - catch (COMException ce) { - if ((uint)unchecked(ce.ErrorCode) != (uint)unchecked(0x800704c7)) { + catch (COMException ce) + { + if ((uint)unchecked(ce.ErrorCode) != (uint)unchecked(0x800704c7)) + { // "the operation was canceled by the user" - navigation failed // ignore this error, IE has already alerted the user. throw; @@ -1460,7 +1609,8 @@ private void PerformNavigate2(ref object URL, ref object flags, ref object targe } } - private bool ShouldSerializeDocumentText() { + private bool ShouldSerializeDocumentText() + { return IsValidUrl; } @@ -1471,8 +1621,9 @@ bool IsValidUrl return Url == null || Url.AbsoluteUri == "about:blank"; } } - - private bool ShouldSerializeUrl() { + + private bool ShouldSerializeUrl() + { return !ShouldSerializeDocumentText(); } @@ -1480,45 +1631,61 @@ private bool ShouldSerializeUrl() { /// Returns TRUE if there is a context menu to show /// Returns FALSE otherwise /// - private bool ShowContextMenu(int x, int y) { + private bool ShowContextMenu(int x, int y) + { ContextMenuStrip contextMenuStrip = ContextMenuStrip; ContextMenu contextMenu = contextMenuStrip != null ? null : ContextMenu; - if (contextMenuStrip != null || contextMenu != null) { + if (contextMenuStrip != null || contextMenu != null) + { Point client; bool keyboardActivated = false; // X will be exactly -1 when the user invokes the context menu from the keyboard // - if (x == -1) { + if (x == -1) + { keyboardActivated = true; client = new Point(Width / 2, Height / 2); - } else { + } + else + { client = PointToClient(new Point(x, y)); } - if (ClientRectangle.Contains(client)) { - if (contextMenuStrip != null) { + if (ClientRectangle.Contains(client)) + { + if (contextMenuStrip != null) + { contextMenuStrip.ShowInternal(this, client, keyboardActivated); - } else if (contextMenu != null) { + } + else if (contextMenu != null) + { contextMenu.Show(this, client); } return true; - } else { + } + else + { return false; } - } else { + } + else + { return false; } } - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { case Interop.WindowMessages.WM_CONTEXTMENU: int x = NativeMethods.Util.SignedLOWORD(m.LParam); int y = NativeMethods.Util.SignedHIWORD(m.LParam); - if (!ShowContextMenu(x, y)) { + if (!ShowContextMenu(x, y)) + { DefWndProc(ref m); } break; @@ -1527,21 +1694,27 @@ protected override void WndProc(ref Message m) { break; } } - - private UnsafeNativeMethods.IWebBrowser2 AxIWebBrowser2 { - get { - if (this.axIWebBrowser2 == null) { - if (!this.IsDisposed) { + + private UnsafeNativeMethods.IWebBrowser2 AxIWebBrowser2 + { + get + { + if (this.axIWebBrowser2 == null) + { + if (!this.IsDisposed) + { // This should call AttachInterfaces TransitionUpTo(WebBrowserHelper.AXState.InPlaceActive); } - else { + else + { throw new System.ObjectDisposedException(GetType().Name); } } // We still don't have this.axIWebBrowser2. Throw an exception. - if (this.axIWebBrowser2 == null) { - throw new InvalidOperationException(SR.WebBrowserNoCastToIWebBrowser2); + if (this.axIWebBrowser2 == null) + { + throw new InvalidOperationException(SR.WebBrowserNoCastToIWebBrowser2); } return this.axIWebBrowser2; } @@ -1566,21 +1739,27 @@ protected class WebBrowserSite : WebBrowserSiteBase, UnsafeNativeMethods.IDocHos /// Creates an instance of the class. /// /// - public WebBrowserSite(WebBrowser host) : base(host) { + public WebBrowserSite(WebBrowser host) : base(host) + { } // // IDocHostUIHandler Implementation // - int UnsafeNativeMethods.IDocHostUIHandler.ShowContextMenu(int dwID, NativeMethods.POINT pt, object pcmdtReserved, object pdispReserved) { + int UnsafeNativeMethods.IDocHostUIHandler.ShowContextMenu(int dwID, NativeMethods.POINT pt, object pcmdtReserved, object pdispReserved) + { WebBrowser wb = (WebBrowser)this.Host; - if (wb.IsWebBrowserContextMenuEnabled) { + if (wb.IsWebBrowserContextMenuEnabled) + { // let MSHTML display its UI return NativeMethods.S_FALSE; - } else { - if (pt.x == 0 && pt.y == 0) { + } + else + { + if (pt.x == 0 && pt.y == 0) + { // IDocHostUIHandler::ShowContextMenu sends (0,0) when the context menu is invoked via the keyboard // make it (-1, -1) for the WebBrowser::ShowContextMenu method pt.x = -1; @@ -1593,65 +1772,79 @@ int UnsafeNativeMethods.IDocHostUIHandler.ShowContextMenu(int dwID, NativeMethod } - int UnsafeNativeMethods.IDocHostUIHandler.GetHostInfo(NativeMethods.DOCHOSTUIINFO info) { + int UnsafeNativeMethods.IDocHostUIHandler.GetHostInfo(NativeMethods.DOCHOSTUIINFO info) + { WebBrowser wb = (WebBrowser)this.Host; info.dwDoubleClick = (int)NativeMethods.DOCHOSTUIDBLCLICK.DEFAULT; info.dwFlags = (int)NativeMethods.DOCHOSTUIFLAG.NO3DOUTERBORDER | (int)NativeMethods.DOCHOSTUIFLAG.DISABLE_SCRIPT_INACTIVE; - if (wb.ScrollBarsEnabled) { + if (wb.ScrollBarsEnabled) + { info.dwFlags |= (int)NativeMethods.DOCHOSTUIFLAG.FLAT_SCROLLBAR; } - else { + else + { info.dwFlags |= (int)NativeMethods.DOCHOSTUIFLAG.SCROLL_NO; } - if (Application.RenderWithVisualStyles) { + if (Application.RenderWithVisualStyles) + { info.dwFlags |= (int)NativeMethods.DOCHOSTUIFLAG.THEME; } - else { + else + { info.dwFlags |= (int)NativeMethods.DOCHOSTUIFLAG.NOTHEME; } - + return NativeMethods.S_OK; } - int UnsafeNativeMethods.IDocHostUIHandler.EnableModeless(bool fEnable) { + int UnsafeNativeMethods.IDocHostUIHandler.EnableModeless(bool fEnable) + { return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IDocHostUIHandler.ShowUI(int dwID, UnsafeNativeMethods.IOleInPlaceActiveObject activeObject, - NativeMethods.IOleCommandTarget commandTarget, UnsafeNativeMethods.IOleInPlaceFrame frame, - UnsafeNativeMethods.IOleInPlaceUIWindow doc) { + int UnsafeNativeMethods.IDocHostUIHandler.ShowUI(int dwID, UnsafeNativeMethods.IOleInPlaceActiveObject activeObject, + NativeMethods.IOleCommandTarget commandTarget, UnsafeNativeMethods.IOleInPlaceFrame frame, + UnsafeNativeMethods.IOleInPlaceUIWindow doc) + { return NativeMethods.S_FALSE; } - int UnsafeNativeMethods.IDocHostUIHandler.HideUI() { + int UnsafeNativeMethods.IDocHostUIHandler.HideUI() + { return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IDocHostUIHandler.UpdateUI() { + int UnsafeNativeMethods.IDocHostUIHandler.UpdateUI() + { return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IDocHostUIHandler.OnDocWindowActivate(bool fActivate) { + int UnsafeNativeMethods.IDocHostUIHandler.OnDocWindowActivate(bool fActivate) + { return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IDocHostUIHandler.OnFrameWindowActivate(bool fActivate) { + int UnsafeNativeMethods.IDocHostUIHandler.OnFrameWindowActivate(bool fActivate) + { return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IDocHostUIHandler.ResizeBorder(NativeMethods.COMRECT rect, UnsafeNativeMethods.IOleInPlaceUIWindow doc, bool fFrameWindow) { + int UnsafeNativeMethods.IDocHostUIHandler.ResizeBorder(NativeMethods.COMRECT rect, UnsafeNativeMethods.IOleInPlaceUIWindow doc, bool fFrameWindow) + { return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IDocHostUIHandler.GetOptionKeyPath(string[] pbstrKey, int dw) { + int UnsafeNativeMethods.IDocHostUIHandler.GetOptionKeyPath(string[] pbstrKey, int dw) + { return NativeMethods.E_NOTIMPL; } - - int UnsafeNativeMethods.IDocHostUIHandler.GetDropTarget(UnsafeNativeMethods.IOleDropTarget pDropTarget, out UnsafeNativeMethods.IOleDropTarget ppDropTarget) { + + int UnsafeNativeMethods.IDocHostUIHandler.GetDropTarget(UnsafeNativeMethods.IOleDropTarget pDropTarget, out UnsafeNativeMethods.IOleDropTarget ppDropTarget) + { // // Set to null no matter what we return, to prevent the marshaller // from having issues if the pointer points to random stuff. @@ -1659,26 +1852,29 @@ int UnsafeNativeMethods.IDocHostUIHandler.GetDropTarget(UnsafeNativeMethods.IOle return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IDocHostUIHandler.GetExternal(out object ppDispatch) { + int UnsafeNativeMethods.IDocHostUIHandler.GetExternal(out object ppDispatch) + { WebBrowser wb = (WebBrowser)this.Host; ppDispatch = wb.ObjectForScripting; return NativeMethods.S_OK; } - [SuppressMessage("Microsoft.Performance", "CA1803:AvoidCostlyCallsWherePossible")] - int UnsafeNativeMethods.IDocHostUIHandler.TranslateAccelerator(ref NativeMethods.MSG msg, ref Guid group, int nCmdID) { + [SuppressMessage("Microsoft.Performance", "CA1803:AvoidCostlyCallsWherePossible")] + int UnsafeNativeMethods.IDocHostUIHandler.TranslateAccelerator(ref NativeMethods.MSG msg, ref Guid group, int nCmdID) + { // // Returning S_FALSE will allow the native control to do default processing, // i.e., execute the shortcut key. Returning S_OK will cancel the shortcut key. WebBrowser wb = (WebBrowser)this.Host; - + if (!wb.WebBrowserShortcutsEnabled) { int keyCode = (int)msg.wParam | (int)Control.ModifierKeys; if (msg.message != Interop.WindowMessages.WM_CHAR - && Enum.IsDefined(typeof(Shortcut), (Shortcut)keyCode)) { + && Enum.IsDefined(typeof(Shortcut), (Shortcut)keyCode)) + { return NativeMethods.S_OK; } return NativeMethods.S_FALSE; @@ -1686,7 +1882,8 @@ int UnsafeNativeMethods.IDocHostUIHandler.TranslateAccelerator(ref NativeMethods return NativeMethods.S_FALSE; } - int UnsafeNativeMethods.IDocHostUIHandler.TranslateUrl(int dwTranslate, string strUrlIn, out string pstrUrlOut) { + int UnsafeNativeMethods.IDocHostUIHandler.TranslateUrl(int dwTranslate, string strUrlIn, out string pstrUrlOut) + { // // Set to null no matter what we return, to prevent the marshaller // from having issues if the pointer points to random stuff. @@ -1694,7 +1891,7 @@ int UnsafeNativeMethods.IDocHostUIHandler.TranslateUrl(int dwTranslate, string s return NativeMethods.S_FALSE; } - int UnsafeNativeMethods.IDocHostUIHandler.FilterDataObject(IComDataObject pDO, out IComDataObject ppDORet) + int UnsafeNativeMethods.IDocHostUIHandler.FilterDataObject(IComDataObject pDO, out IComDataObject ppDORet) { // // Set to null no matter what we return, to prevent the marshaller @@ -1706,25 +1903,29 @@ int UnsafeNativeMethods.IDocHostUIHandler.FilterDataObject(IComDataObject pDO, o // // Internal methods // - internal override void OnPropertyChanged(int dispid) { - if (dispid != NativeMethods.ActiveX.DISPID_READYSTATE) { + internal override void OnPropertyChanged(int dispid) + { + if (dispid != NativeMethods.ActiveX.DISPID_READYSTATE) + { base.OnPropertyChanged(dispid); } } } - - + + // // Private classes: // [ClassInterface(ClassInterfaceType.None)] - private class WebBrowserEvent : StandardOleMarshalObject, UnsafeNativeMethods.DWebBrowserEvents2{ - + private class WebBrowserEvent : StandardOleMarshalObject, UnsafeNativeMethods.DWebBrowserEvents2 + { + private WebBrowser parent; private bool allowNavigation; private bool haveNavigated = false; - public WebBrowserEvent(WebBrowser parent) { + public WebBrowserEvent(WebBrowser parent) + { this.parent = parent; } @@ -1740,16 +1941,20 @@ public bool AllowNavigation } } - public void CommandStateChange(long command, bool enable) { - if (command == NativeMethods.CSC_NAVIGATEBACK) { + public void CommandStateChange(long command, bool enable) + { + if (command == NativeMethods.CSC_NAVIGATEBACK) + { this.parent.CanGoBackInternal = enable; } - else if (command == NativeMethods.CSC_NAVIGATEFORWARD) { + else if (command == NativeMethods.CSC_NAVIGATEFORWARD) + { this.parent.CanGoForwardInternal = enable; } } - - public void BeforeNavigate2(object pDisp, ref object urlObject, ref object flags, ref object targetFrameName, ref object postData, ref object headers, ref bool cancel) { + + public void BeforeNavigate2(object pDisp, ref object urlObject, ref object flags, ref object targetFrameName, ref object postData, ref object headers, ref bool cancel) + { Debug.Assert(parent != null, "Parent should have been set"); //Note: we want to allow navigation if we haven't already navigated. if (AllowNavigation || !haveNavigated) @@ -1761,10 +1966,12 @@ public void BeforeNavigate2(object pDisp, ref object urlObject, ref object flags // If during running interop code, the variant.bstr value gets set // to -1 on return back to native code, if the original value was null, we // have to set targetFrameName and headers to "". - if (targetFrameName == null) { + if (targetFrameName == null) + { targetFrameName = string.Empty; } - if (headers == null) { + if (headers == null) + { headers = string.Empty; } @@ -1774,18 +1981,21 @@ public void BeforeNavigate2(object pDisp, ref object urlObject, ref object flags this.parent.OnNavigating(e); cancel = e.Cancel; } - else + else { cancel = true; } } - public void DocumentComplete(object pDisp, ref object urlObject) { + public void DocumentComplete(object pDisp, ref object urlObject) + { Debug.Assert(urlObject == null || urlObject is string, "invalid url"); haveNavigated = true; - if (this.parent.documentStreamToSetOnLoad != null && (string)urlObject == "about:blank") { + if (this.parent.documentStreamToSetOnLoad != null && (string)urlObject == "about:blank") + { HtmlDocument htmlDocument = this.parent.Document; - if (htmlDocument != null) { + if (htmlDocument != null) + { UnsafeNativeMethods.IPersistStreamInit psi = htmlDocument.DomDocument as UnsafeNativeMethods.IPersistStreamInit; Debug.Assert(psi != null, "The Document does not implement IPersistStreamInit"); UnsafeNativeMethods.IStream iStream = (UnsafeNativeMethods.IStream)new UnsafeNativeMethods.ComStreamFromDataStream( @@ -1795,51 +2005,59 @@ public void DocumentComplete(object pDisp, ref object urlObject) { } this.parent.documentStreamToSetOnLoad = null; } - else { + else + { string urlString = urlObject == null ? "" : urlObject.ToString(); WebBrowserDocumentCompletedEventArgs e = new WebBrowserDocumentCompletedEventArgs( new Uri(urlString)); this.parent.OnDocumentCompleted(e); } } - - public void TitleChange(string text) { + + public void TitleChange(string text) + { this.parent.OnDocumentTitleChanged(EventArgs.Empty); } - - public void SetSecureLockIcon(int secureLockIcon) { + + public void SetSecureLockIcon(int secureLockIcon) + { this.parent.encryptionLevel = (WebBrowserEncryptionLevel)secureLockIcon; this.parent.OnEncryptionLevelChanged(EventArgs.Empty); } - - public void NavigateComplete2(object pDisp, ref object urlObject) { + + public void NavigateComplete2(object pDisp, ref object urlObject) + { Debug.Assert(urlObject == null || urlObject is string, "invalid url type"); string urlString = urlObject == null ? "" : (string)urlObject; WebBrowserNavigatedEventArgs e = new WebBrowserNavigatedEventArgs( new Uri(urlString)); this.parent.OnNavigated(e); } - - public void NewWindow2(ref object ppDisp, ref bool cancel) { + + public void NewWindow2(ref object ppDisp, ref bool cancel) + { CancelEventArgs e = new CancelEventArgs(); this.parent.OnNewWindow(e); cancel = e.Cancel; } - - public void ProgressChange(int progress, int progressMax) { + + public void ProgressChange(int progress, int progressMax) + { WebBrowserProgressChangedEventArgs e = new WebBrowserProgressChangedEventArgs(progress, progressMax); this.parent.OnProgressChanged(e); } - - public void StatusTextChange(string text) { + + public void StatusTextChange(string text) + { this.parent.statusText = (text == null) ? "" : text; this.parent.OnStatusTextChanged(EventArgs.Empty); } - - public void DownloadBegin() { + + public void DownloadBegin() + { this.parent.OnFileDownload(EventArgs.Empty); } - + public void FileDownload(ref bool cancel) { } public void PrivacyImpactedStateChange(bool bImpacted) { } public void UpdatePageStatus(object pDisp, ref object nPage, ref object fDone) { } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs index 17b81e60995..b1d41e84976 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs @@ -37,7 +37,7 @@ public class WebBrowserBase : Control private WebBrowserHelper.AXState axState = WebBrowserHelper.AXState.Passive; private WebBrowserHelper.AXState axReloadingState = WebBrowserHelper.AXState.Passive; private WebBrowserHelper.AXEditMode axEditMode = WebBrowserHelper.AXEditMode.None; - private bool inRtlRecreate=false; + private bool inRtlRecreate = false; private BitVector32 axHostState = new BitVector32(); private WebBrowserHelper.SelectionStyle selectionStyle = WebBrowserHelper.SelectionStyle.NotSelected; private int noComponentChange = 0; @@ -45,7 +45,7 @@ public class WebBrowserBase : Control private ContainerControl containingControl; private IntPtr hwndFocus = IntPtr.Zero; private EventHandler selectionChangeHandler; - private Guid clsid; + private Guid clsid; // Pointers to the ActiveX object: Interface pointers are cached for perf. private UnsafeNativeMethods.IOleObject axOleObject; private UnsafeNativeMethods.IOleInPlaceObject axOleInPlaceObject; @@ -75,8 +75,10 @@ public class WebBrowserBase : Control /// given by the clsid parameter. /// /// - internal WebBrowserBase(string clsidString) : base() { - if (Application.OleRequired() != ApartmentState.STA) { + internal WebBrowserBase(string clsidString) : base() + { + if (Application.OleRequired() != ApartmentState.STA) + { throw new ThreadStateException(string.Format(SR.AXMTAThread, clsidString)); } @@ -99,8 +101,10 @@ internal WebBrowserBase(string clsidString) : base() { /// /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public object ActiveXInstance { - get { + public object ActiveXInstance + { + get + { return activeXInstance; } } @@ -110,7 +114,7 @@ public object ActiveXInstance { // // The following are virtual methods that derived-classes can override // - + // // The native ActiveX control QI's for interfaces on it's site to see if // it needs to change its behavior. Since the WebBrowserSiteBaseBase class is generic, @@ -129,7 +133,8 @@ public object ActiveXInstance { /// Implementors of the site can derive from class. /// /// - protected virtual WebBrowserSiteBase CreateWebBrowserSiteBase() { + protected virtual WebBrowserSiteBase CreateWebBrowserSiteBase() + { return new WebBrowserSiteBase(this); } @@ -142,7 +147,8 @@ protected virtual WebBrowserSiteBase CreateWebBrowserSiteBase() { /// DetachInterfaces is called (by setting the cached interface variable to null). /// /// - protected virtual void AttachInterfaces(object nativeActiveXObject) { + protected virtual void AttachInterfaces(object nativeActiveXObject) + { } /// @@ -150,7 +156,8 @@ protected virtual void AttachInterfaces(object nativeActiveXObject) { /// See AttachInterfaces for a description of when to override DetachInterfaces. /// /// - protected virtual void DetachInterfaces() { + protected virtual void DetachInterfaces() + { } /// @@ -159,7 +166,8 @@ protected virtual void DetachInterfaces() { /// Inheritors can override this method to hook their own connection points. /// /// - protected virtual void CreateSink() { + protected virtual void CreateSink() + { } /// @@ -168,7 +176,8 @@ protected virtual void CreateSink() { /// This is where inheritors have to disconnect their connection points. /// /// - protected virtual void DetachSink() { + protected virtual void DetachSink() + { } //DrawToBitmap doesn't work for this control, so we should hide it. We'll @@ -189,13 +198,16 @@ protected virtual void DetachSink() { // component has been added to a container, and a null value indicates that // this component is being removed from a container. // - public override ISite Site { - set { + public override ISite Site + { + set + { bool hadSelectionHandler = this.RemoveSelectionHandler(); base.Site = value; - if (hadSelectionHandler) { + if (hadSelectionHandler) + { this.AddSelectionHandler(); } } @@ -209,13 +221,16 @@ internal override void OnBoundsUpdate(int x, int y, int width, int height) // // If the ActiveX control is already InPlaceActive, make sure // it's bounds also change. - if (this.ActiveXState >= WebBrowserHelper.AXState.InPlaceActive) { - try { + if (this.ActiveXState >= WebBrowserHelper.AXState.InPlaceActive) + { + try + { this.webBrowserBaseChangingSize.Width = width; this.webBrowserBaseChangingSize.Height = height; this.AXInPlaceObject.SetObjectRects(new NativeMethods.COMRECT(new Rectangle(0, 0, width, height)), WebBrowserHelper.GetClipRect()); } - finally { + finally + { this.webBrowserBaseChangingSize.Width = -1; // Invalid value. Use WebBrowserBase.Bounds instead, when this is the case. } } @@ -244,8 +259,10 @@ protected override bool ProcessDialogKey(Keys keyData) [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] public override bool PreProcessMessage(ref Message msg) { - if (IsUserMode) { - if (this.GetAXHostState(WebBrowserHelper.siteProcessedInputKey)) { + if (IsUserMode) + { + if (this.GetAXHostState(WebBrowserHelper.siteProcessedInputKey)) + { // In this case, the control called us back through IOleControlSite // and is now giving us a chance to see if we want to process it. return base.PreProcessMessage(ref msg); @@ -260,7 +277,7 @@ public override bool PreProcessMessage(ref Message msg) win32Message.hwnd = msg.HWnd; this.SetAXHostState(WebBrowserHelper.siteProcessedInputKey, false); - try + try { if (axOleInPlaceObject != null) { @@ -312,11 +329,12 @@ public override bool PreProcessMessage(ref Message msg) } } } - finally { + finally + { this.SetAXHostState(WebBrowserHelper.siteProcessedInputKey, false); } } - + return false; } @@ -328,14 +346,18 @@ public override bool PreProcessMessage(ref Message msg) // We can't decide just by ourselves whether we can process the // mnemonic. We have to ask the ActiveX control for it. // - protected internal override bool ProcessMnemonic(char charCode) { + protected internal override bool ProcessMnemonic(char charCode) + { bool processed = false; - if (CanSelect) { - try { + if (CanSelect) + { + try + { NativeMethods.tagCONTROLINFO ctlInfo = new NativeMethods.tagCONTROLINFO(); int hr = this.axOleControl.GetControlInfo(ctlInfo); - if (NativeMethods.Succeeded(hr)) { + if (NativeMethods.Succeeded(hr)) + { // // Sadly, we don't have a message so we must fake one ourselves. // The message we are faking is a WM_SYSKEYDOWN with the right @@ -344,21 +366,24 @@ protected internal override bool ProcessMnemonic(char charCode) { msg.hwnd = IntPtr.Zero; msg.message = Interop.WindowMessages.WM_SYSKEYDOWN; msg.wParam = (IntPtr)char.ToUpper(charCode, CultureInfo.CurrentCulture); - msg.lParam = (IntPtr) 0x20180001; + msg.lParam = (IntPtr)0x20180001; msg.time = SafeNativeMethods.GetTickCount(); NativeMethods.POINT p = new NativeMethods.POINT(); UnsafeNativeMethods.GetCursorPos(p); msg.pt_x = p.x; msg.pt_y = p.y; - if (SafeNativeMethods.IsAccelerator(new HandleRef(ctlInfo, ctlInfo.hAccel), ctlInfo.cAccel, ref msg, null)) { + if (SafeNativeMethods.IsAccelerator(new HandleRef(ctlInfo, ctlInfo.hAccel), ctlInfo.cAccel, ref msg, null)) + { this.axOleControl.OnMnemonic(ref msg); Focus(); processed = true; } } } - catch (Exception ex) { - if (ClientUtils.IsCriticalException(ex)) { + catch (Exception ex) + { + if (ClientUtils.IsCriticalException(ex)) + { throw; } Debug.Fail("error in processMnemonic"); @@ -371,8 +396,10 @@ protected internal override bool ProcessMnemonic(char charCode) { // Certain messages are forwarder directly to the ActiveX control, // others are first processed by the wndproc of Control // - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { // // Things we explicitly ignore and pass to the ActiveX's windproc // @@ -398,7 +425,7 @@ protected override void WndProc(ref Message m) { if (!ReflectMessage(m.LParam, ref m)) DefWndProc(ref m); break; - + case Interop.WindowMessages.WM_HELP: // We want to both fire the event, and let the ActiveX have the message... base.WndProc(ref m); @@ -409,23 +436,27 @@ protected override void WndProc(ref Message m) { case Interop.WindowMessages.WM_MBUTTONDOWN: case Interop.WindowMessages.WM_RBUTTONDOWN: case Interop.WindowMessages.WM_MOUSEACTIVATE: - if (!DesignMode) { - if (containingControl != null && containingControl.ActiveControl != this) { + if (!DesignMode) + { + if (containingControl != null && containingControl.ActiveControl != this) + { Focus(); - } + } } DefWndProc(ref m); break; case Interop.WindowMessages.WM_KILLFOCUS: hwndFocus = (IntPtr)m.WParam; - try { + try + { base.WndProc(ref m); } - finally { - hwndFocus = IntPtr.Zero; + finally + { + hwndFocus = IntPtr.Zero; } - break; + break; case Interop.WindowMessages.WM_DESTROY: // @@ -435,14 +466,17 @@ protected override void WndProc(ref Message m) { // Otherwise we face all sorts of problems when we try to // transition back to a state >= InPlaceActive. // - if (this.ActiveXState >= WebBrowserHelper.AXState.InPlaceActive) { + if (this.ActiveXState >= WebBrowserHelper.AXState.InPlaceActive) + { IntPtr hwndInPlaceObject; - if (NativeMethods.Succeeded(this.AXInPlaceObject.GetWindow(out hwndInPlaceObject))) { + if (NativeMethods.Succeeded(this.AXInPlaceObject.GetWindow(out hwndInPlaceObject))) + { Application.ParkHandle(new HandleRef(this.AXInPlaceObject, hwndInPlaceObject)); } } - if (RecreatingHandle) { + if (RecreatingHandle) + { axReloadingState = axState; } @@ -453,7 +487,8 @@ protected override void WndProc(ref Message m) { // up to InPlaceActivate that the ActiveX control grabs our handle). TransitionDownTo(WebBrowserHelper.AXState.Running); - if (this.axWindow != null) { + if (this.axWindow != null) + { this.axWindow.ReleaseHandle(); } @@ -461,10 +496,12 @@ protected override void WndProc(ref Message m) { break; default: - if (m.Msg == WebBrowserHelper.REGMSG_MSG) { + if (m.Msg == WebBrowserHelper.REGMSG_MSG) + { m.Result = (IntPtr)WebBrowserHelper.REGMSG_RETVAL; } - else { + else + { base.WndProc(ref m); } break; @@ -472,55 +509,66 @@ protected override void WndProc(ref Message m) { } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] - protected override void OnParentChanged(EventArgs e) { + protected override void OnParentChanged(EventArgs e) + { Control parent = ParentInternal; - if ((Visible && parent != null && parent.Visible) || this.IsHandleCreated) { + if ((Visible && parent != null && parent.Visible) || this.IsHandleCreated) + { TransitionUpTo(WebBrowserHelper.AXState.InPlaceActive); } base.OnParentChanged(e); } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] - protected override void OnVisibleChanged(EventArgs e) { - if (Visible && !Disposing && !IsDisposed) { + protected override void OnVisibleChanged(EventArgs e) + { + if (Visible && !Disposing && !IsDisposed) + { TransitionUpTo(WebBrowserHelper.AXState.InPlaceActive); } base.OnVisibleChanged(e); } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] - protected override void OnGotFocus(EventArgs e) { - if (this.ActiveXState < WebBrowserHelper.AXState.UIActive) { + protected override void OnGotFocus(EventArgs e) + { + if (this.ActiveXState < WebBrowserHelper.AXState.UIActive) + { TransitionUpTo(WebBrowserHelper.AXState.UIActive); } base.OnGotFocus(e); } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] - protected override void OnLostFocus(EventArgs e) { + protected override void OnLostFocus(EventArgs e) + { base.OnLostFocus(e); // If the focus goes from our control window to one of the child windows, // we should not deactivate. - if (!this.ContainsFocus) { + if (!this.ContainsFocus) + { TransitionDownTo(WebBrowserHelper.AXState.InPlaceActive); } } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] - protected override void OnRightToLeftChanged(EventArgs e) { + protected override void OnRightToLeftChanged(EventArgs e) + { //Do nothing: no point in recreating the handle when we don't obey RTL } // // Can't select the control until the ActiveX control is InPlaceActive. // - internal override bool CanSelectCore() { + internal override bool CanSelectCore() + { return this.ActiveXState >= WebBrowserHelper.AXState.InPlaceActive ? base.CanSelectCore() : false; } - internal override bool AllowsKeyboardToolTip() { + internal override bool AllowsKeyboardToolTip() + { return false; } @@ -529,7 +577,8 @@ internal override bool AllowsKeyboardToolTip() { // has changed. // [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] - protected override void OnFontChanged(EventArgs e) { + protected override void OnFontChanged(EventArgs e) + { base.OnFontChanged(e); AmbientChanged(NativeMethods.ActiveX.DISPID_AMBIENT_FONT); } @@ -539,7 +588,8 @@ protected override void OnFontChanged(EventArgs e) { // has changed. // [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] - protected override void OnForeColorChanged(EventArgs e) { + protected override void OnForeColorChanged(EventArgs e) + { base.OnForeColorChanged(e); AmbientChanged(NativeMethods.ActiveX.DISPID_AMBIENT_FORECOLOR); } @@ -549,23 +599,28 @@ protected override void OnForeColorChanged(EventArgs e) { // has changed. // [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] - protected override void OnBackColorChanged(EventArgs e) { + protected override void OnBackColorChanged(EventArgs e) + { base.OnBackColorChanged(e); AmbientChanged(NativeMethods.ActiveX.DISPID_AMBIENT_BACKCOLOR); } - internal override void RecreateHandleCore() { - if (!inRtlRecreate) { + internal override void RecreateHandleCore() + { + if (!inRtlRecreate) + { base.RecreateHandleCore(); } } - + // // TransitionDownTo Passive when we are being disposed. // - protected override void Dispose(bool disposing) { - if (disposing) { + protected override void Dispose(bool disposing) + { + if (disposing) + { TransitionDownTo(WebBrowserHelper.AXState.Passive); } base.Dispose(disposing); @@ -587,34 +642,45 @@ internal Guid ClassId { } #endif - internal WebBrowserHelper.AXState ActiveXState { - get { + internal WebBrowserHelper.AXState ActiveXState + { + get + { return axState; } - set { + set + { axState = value; } } - internal bool GetAXHostState(int mask) { + internal bool GetAXHostState(int mask) + { return this.axHostState[mask]; } - - internal void SetAXHostState(int mask, bool value) { + + internal void SetAXHostState(int mask, bool value) + { this.axHostState[mask] = value; } - internal IntPtr GetHandleNoCreate() { + internal IntPtr GetHandleNoCreate() + { return IsHandleCreated ? Handle : IntPtr.Zero; } - internal void TransitionUpTo(WebBrowserHelper.AXState state) { - if (!this.GetAXHostState(WebBrowserHelper.inTransition)) { + internal void TransitionUpTo(WebBrowserHelper.AXState state) + { + if (!this.GetAXHostState(WebBrowserHelper.inTransition)) + { this.SetAXHostState(WebBrowserHelper.inTransition, true); - try { - while (state > this.ActiveXState) { - switch (this.ActiveXState) { + try + { + while (state > this.ActiveXState) + { + switch (this.ActiveXState) + { case WebBrowserHelper.AXState.Passive: TransitionFromPassiveToLoaded(); Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.Loaded, "Failed transition"); @@ -638,19 +704,25 @@ internal void TransitionUpTo(WebBrowserHelper.AXState state) { } } } - finally { - this.SetAXHostState(WebBrowserHelper.inTransition, false); + finally + { + this.SetAXHostState(WebBrowserHelper.inTransition, false); } } } - internal void TransitionDownTo(WebBrowserHelper.AXState state) { - if (!this.GetAXHostState(WebBrowserHelper.inTransition)) { + internal void TransitionDownTo(WebBrowserHelper.AXState state) + { + if (!this.GetAXHostState(WebBrowserHelper.inTransition)) + { this.SetAXHostState(WebBrowserHelper.inTransition, true); - try { - while (state < this.ActiveXState) { - switch (this.ActiveXState) { + try + { + while (state < this.ActiveXState) + { + switch (this.ActiveXState) + { case WebBrowserHelper.AXState.UIActive: TransitionFromUIActiveToInPlaceActive(); Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.InPlaceActive, "Failed transition"); @@ -674,13 +746,15 @@ internal void TransitionDownTo(WebBrowserHelper.AXState state) { } } } - finally { + finally + { this.SetAXHostState(WebBrowserHelper.inTransition, false); } } } - internal bool DoVerb(int verb) { + internal bool DoVerb(int verb) + { int hr = this.axOleObject.DoVerb(verb, IntPtr.Zero, this.ActiveXSite, 0, this.Handle, new NativeMethods.COMRECT(this.Bounds)); @@ -699,13 +773,16 @@ internal bool DoVerb(int verb) { // This property exists only to enable some specific // behaviors of ActiveX controls. [Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)] - internal ContainerControl ContainingControl { - get { + internal ContainerControl ContainingControl + { + get + { if (containingControl == null || - this.GetAXHostState(WebBrowserHelper.recomputeContainingControl)) { + this.GetAXHostState(WebBrowserHelper.recomputeContainingControl)) + { containingControl = FindContainerControlInternal(); } - + return containingControl; } } @@ -719,69 +796,85 @@ internal WebBrowserContainer CreateWebBrowserContainer() return wbContainer; } - internal WebBrowserContainer GetParentContainer() { - if (container == null) { + internal WebBrowserContainer GetParentContainer() + { + if (container == null) + { container = WebBrowserContainer.FindContainerForControl(this); } - if (container == null) { + if (container == null) + { container = CreateWebBrowserContainer(); container.AddControl(this); } return container; } - internal void SetEditMode(WebBrowserHelper.AXEditMode em) { + internal void SetEditMode(WebBrowserHelper.AXEditMode em) + { this.axEditMode = em; } - internal void SetSelectionStyle(WebBrowserHelper.SelectionStyle selectionStyle) { - if (DesignMode) { + internal void SetSelectionStyle(WebBrowserHelper.SelectionStyle selectionStyle) + { + if (DesignMode) + { ISelectionService iss = WebBrowserHelper.GetSelectionService(this); this.selectionStyle = selectionStyle; - if (iss != null && iss.GetComponentSelected(this)) { + if (iss != null && iss.GetComponentSelected(this)) + { // The ActiveX Host designer will offer an extender property // called "SelectionStyle" PropertyDescriptor prop = TypeDescriptor.GetProperties(this)["SelectionStyle"]; - if (prop != null && prop.PropertyType == typeof(int)) { + if (prop != null && prop.PropertyType == typeof(int)) + { prop.SetValue(this, (int)selectionStyle); } } } } - internal void AddSelectionHandler() { - if (!this.GetAXHostState(WebBrowserHelper.addedSelectionHandler)) { + internal void AddSelectionHandler() + { + if (!this.GetAXHostState(WebBrowserHelper.addedSelectionHandler)) + { this.SetAXHostState(WebBrowserHelper.addedSelectionHandler, true); - + ISelectionService iss = WebBrowserHelper.GetSelectionService(this); - if (iss != null) { + if (iss != null) + { iss.SelectionChanging += SelectionChangeHandler; } } } - internal bool RemoveSelectionHandler() { + internal bool RemoveSelectionHandler() + { bool retVal = this.GetAXHostState(WebBrowserHelper.addedSelectionHandler); - if (retVal) { + if (retVal) + { this.SetAXHostState(WebBrowserHelper.addedSelectionHandler, false); ISelectionService iss = WebBrowserHelper.GetSelectionService(this); - if (iss != null) { + if (iss != null) + { iss.SelectionChanging -= SelectionChangeHandler; } } return retVal; } - internal void AttachWindow(IntPtr hwnd) { + internal void AttachWindow(IntPtr hwnd) + { UnsafeNativeMethods.SetParent(new HandleRef(null, hwnd), new HandleRef(this, this.Handle)); - if (this.axWindow != null) { + if (this.axWindow != null) + { this.axWindow.ReleaseHandle(); } this.axWindow = new WebBrowserBaseNativeWindow(this); this.axWindow.AssignHandle(hwnd, false); - + UpdateZOrder(); UpdateBounds(); @@ -792,36 +885,44 @@ internal void AttachWindow(IntPtr hwnd) { Bounds = new Rectangle(location.X, location.Y, extent.Width, extent.Height); } - internal bool IsUserMode { - get { + internal bool IsUserMode + { + get + { return Site == null || !DesignMode; } } - internal void MakeDirty() { + internal void MakeDirty() + { ISite iSite = this.Site; - if (iSite != null) { + if (iSite != null) + { IComponentChangeService ccs = (IComponentChangeService)iSite.GetService(typeof(IComponentChangeService)); - if (ccs != null) { + if (ccs != null) + { ccs.OnComponentChanging(this, null); ccs.OnComponentChanged(this, null, null, null); } } } - internal int NoComponentChangeEvents { - get { + internal int NoComponentChangeEvents + { + get + { return noComponentChange; } - set { + set + { noComponentChange = value; } } - + @@ -829,25 +930,31 @@ internal int NoComponentChangeEvents { // Private helper methods: // - private void StartEvents() { - if (!this.GetAXHostState(WebBrowserHelper.sinkAttached)) { + private void StartEvents() + { + if (!this.GetAXHostState(WebBrowserHelper.sinkAttached)) + { this.SetAXHostState(WebBrowserHelper.sinkAttached, true); CreateSink(); } this.ActiveXSite.StartEvents(); } - private void StopEvents() { - if (this.GetAXHostState(WebBrowserHelper.sinkAttached)) { + private void StopEvents() + { + if (this.GetAXHostState(WebBrowserHelper.sinkAttached)) + { this.SetAXHostState(WebBrowserHelper.sinkAttached, false); DetachSink(); } this.ActiveXSite.StopEvents(); } - private void TransitionFromPassiveToLoaded() { + private void TransitionFromPassiveToLoaded() + { Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.Passive, "Wrong start state to transition from"); - if (this.ActiveXState == WebBrowserHelper.AXState.Passive) { + if (this.ActiveXState == WebBrowserHelper.AXState.Passive) + { // // First, create the ActiveX control Debug.Assert(activeXInstance == null, "activeXInstance must be null"); @@ -865,17 +972,21 @@ private void TransitionFromPassiveToLoaded() { } } - private void TransitionFromLoadedToPassive() { + private void TransitionFromLoadedToPassive() + { Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.Loaded, "Wrong start state to transition from"); - if (this.ActiveXState == WebBrowserHelper.AXState.Loaded) { + if (this.ActiveXState == WebBrowserHelper.AXState.Loaded) + { // // Need to make sure that we don't handle any PropertyChanged // notifications at this point. this.NoComponentChangeEvents++; - try { + try + { // // Release the activeXInstance - if (activeXInstance != null) { + if (activeXInstance != null) + { // // Lets first get the cached interface pointers of activeXInstance released. this.DetachInterfacesInternal(); @@ -884,7 +995,8 @@ private void TransitionFromLoadedToPassive() { this.activeXInstance = null; } } - finally { + finally + { this.NoComponentChangeEvents--; } @@ -894,14 +1006,17 @@ private void TransitionFromLoadedToPassive() { } } - private void TransitionFromLoadedToRunning() { + private void TransitionFromLoadedToRunning() + { Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.Loaded, "Wrong start state to transition from"); - if (this.ActiveXState == WebBrowserHelper.AXState.Loaded) { + if (this.ActiveXState == WebBrowserHelper.AXState.Loaded) + { // // See if the ActiveX control returns OLEMISC_SETCLIENTSITEFIRST int bits = 0; int hr = this.axOleObject.GetMiscStatus(NativeMethods.ActiveX.DVASPECT_CONTENT, out bits); - if (NativeMethods.Succeeded(hr) && ((bits & NativeMethods.ActiveX.OLEMISC_SETCLIENTSITEFIRST) != 0)) { + if (NativeMethods.Succeeded(hr) && ((bits & NativeMethods.ActiveX.OLEMISC_SETCLIENTSITEFIRST) != 0)) + { // // Simply setting the site to the ActiveX control should activate it. // And this will take us to the Running state. @@ -911,7 +1026,8 @@ private void TransitionFromLoadedToRunning() { // // We start receiving events now (but we do this only if we are not // in DesignMode). - if (!DesignMode) { + if (!DesignMode) + { StartEvents(); } @@ -921,15 +1037,18 @@ private void TransitionFromLoadedToRunning() { } } - private void TransitionFromRunningToLoaded() { + private void TransitionFromRunningToLoaded() + { Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.Running, "Wrong start state to transition from"); - if (this.ActiveXState == WebBrowserHelper.AXState.Running) { + if (this.ActiveXState == WebBrowserHelper.AXState.Running) + { StopEvents(); // // Remove ourselves from our parent container... WebBrowserContainer parentContainer = this.GetParentContainer(); - if (parentContainer != null) { + if (parentContainer != null) + { parentContainer.RemoveControl(this); } @@ -943,9 +1062,11 @@ private void TransitionFromRunningToLoaded() { } } - private void TransitionFromRunningToInPlaceActive() { + private void TransitionFromRunningToInPlaceActive() + { Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.Running, "Wrong start state to transition from"); - if (this.ActiveXState == WebBrowserHelper.AXState.Running) { + if (this.ActiveXState == WebBrowserHelper.AXState.Running) + { try { DoVerb(NativeMethods.OLEIVERB_INPLACEACTIVATE); @@ -963,14 +1084,17 @@ private void TransitionFromRunningToInPlaceActive() { } } - private void TransitionFromInPlaceActiveToRunning() { + private void TransitionFromInPlaceActiveToRunning() + { Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.InPlaceActive, "Wrong start state to transition from"); - if (this.ActiveXState == WebBrowserHelper.AXState.InPlaceActive) { + if (this.ActiveXState == WebBrowserHelper.AXState.InPlaceActive) + { // // First, lets make sure we transfer the ContainingControl's ActiveControl // before we InPlaceDeactivate. ContainerControl f = ContainingControl; - if (f != null && f.ActiveControl == this) { + if (f != null && f.ActiveControl == this) + { f.SetActiveControl(null); } @@ -984,13 +1108,17 @@ private void TransitionFromInPlaceActiveToRunning() { } } - private void TransitionFromInPlaceActiveToUIActive() { + private void TransitionFromInPlaceActiveToUIActive() + { Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.InPlaceActive, "Wrong start state to transition from"); - if (this.ActiveXState == WebBrowserHelper.AXState.InPlaceActive) { - try { + if (this.ActiveXState == WebBrowserHelper.AXState.InPlaceActive) + { + try + { DoVerb(NativeMethods.OLEIVERB_UIACTIVATE); } - catch (Exception t) { + catch (Exception t) + { throw new TargetInvocationException(string.Format(SR.AXNohWnd, GetType().Name), t); } @@ -1000,9 +1128,11 @@ private void TransitionFromInPlaceActiveToUIActive() { } } - private void TransitionFromUIActiveToInPlaceActive() { + private void TransitionFromUIActiveToInPlaceActive() + { Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.UIActive, "Wrong start state to transition from"); - if (this.ActiveXState == WebBrowserHelper.AXState.UIActive) { + if (this.ActiveXState == WebBrowserHelper.AXState.UIActive) + { int hr = this.AXInPlaceObject.UIDeactivate(); Debug.Assert(NativeMethods.Succeeded(hr), "Failed to UIDeactivate"); @@ -1011,16 +1141,20 @@ private void TransitionFromUIActiveToInPlaceActive() { } } - internal WebBrowserSiteBase ActiveXSite { - get { - if (axSite == null) { + internal WebBrowserSiteBase ActiveXSite + { + get + { + if (axSite == null) + { this.axSite = CreateWebBrowserSiteBase(); } return axSite; } } - private void AttachInterfacesInternal() { + private void AttachInterfacesInternal() + { Debug.Assert(activeXInstance != null, "The native control is null"); this.axOleObject = (UnsafeNativeMethods.IOleObject)activeXInstance; this.axOleInPlaceObject = (UnsafeNativeMethods.IOleInPlaceObject)activeXInstance; @@ -1031,8 +1165,9 @@ private void AttachInterfacesInternal() { // the ActiveX object to the appropriate interfaces. AttachInterfaces(activeXInstance); } - - private void DetachInterfacesInternal() { + + private void DetachInterfacesInternal() + { this.axOleObject = null; this.axOleInPlaceObject = null; this.axOleInPlaceActiveObject = null; @@ -1042,12 +1177,15 @@ private void DetachInterfacesInternal() { // their cached interfaces of the ActiveX object. DetachInterfaces(); } - + // // We need to change the ActiveX control's state when selection changes. - private EventHandler SelectionChangeHandler { - get { - if (this.selectionChangeHandler == null) { + private EventHandler SelectionChangeHandler + { + get + { + if (this.selectionChangeHandler == null) + { this.selectionChangeHandler = new EventHandler(this.OnNewSelection); } return this.selectionChangeHandler; @@ -1057,28 +1195,36 @@ private EventHandler SelectionChangeHandler { // // We need to do special stuff (convert window messages to interface calls) // during design time when selection changes. - private void OnNewSelection(object sender, EventArgs e) { - if (this.DesignMode) { + private void OnNewSelection(object sender, EventArgs e) + { + if (this.DesignMode) + { ISelectionService iss = WebBrowserHelper.GetSelectionService(this); - if (iss != null) { + if (iss != null) + { // We are no longer selected. - if (!iss.GetComponentSelected(this)) { + if (!iss.GetComponentSelected(this)) + { // // We need to exit editmode if we were in one. - if (this.EditMode) { + if (this.EditMode) + { this.GetParentContainer().OnExitEditMode(this); this.SetEditMode(WebBrowserHelper.AXEditMode.None); } this.SetSelectionStyle(WebBrowserHelper.SelectionStyle.Selected); this.RemoveSelectionHandler(); } - else { + else + { // // The AX Host designer will offer an extender property called "SelectionStyle" PropertyDescriptor prop = TypeDescriptor.GetProperties(this)["SelectionStyle"]; - if (prop != null && prop.PropertyType == typeof(int)) { + if (prop != null && prop.PropertyType == typeof(int)) + { int curSelectionStyle = (int)prop.GetValue(this); - if (curSelectionStyle != (int)this.selectionStyle) { + if (curSelectionStyle != (int)this.selectionStyle) + { prop.SetValue(this, selectionStyle); } } @@ -1087,38 +1233,46 @@ private void OnNewSelection(object sender, EventArgs e) { } } - private Size SetExtent(int width, int height) { + private Size SetExtent(int width, int height) + { NativeMethods.tagSIZEL sz = new NativeMethods.tagSIZEL(); sz.cx = width; sz.cy = height; bool resetExtents = DesignMode; - try { + try + { Pixel2hiMetric(sz, sz); this.axOleObject.SetExtent(NativeMethods.ActiveX.DVASPECT_CONTENT, sz); } - catch (COMException) { + catch (COMException) + { resetExtents = true; } - if (resetExtents) { + if (resetExtents) + { this.axOleObject.GetExtent(NativeMethods.ActiveX.DVASPECT_CONTENT, sz); - try { + try + { this.axOleObject.SetExtent(NativeMethods.ActiveX.DVASPECT_CONTENT, sz); } - catch (COMException e) { + catch (COMException e) + { Debug.Fail(e.ToString()); } } - return GetExtent(); + return GetExtent(); } - private Size GetExtent() { + private Size GetExtent() + { NativeMethods.tagSIZEL sz = new NativeMethods.tagSIZEL(); this.axOleObject.GetExtent(NativeMethods.ActiveX.DVASPECT_CONTENT, sz); HiMetric2Pixel(sz, sz); return new Size(sz.cx, sz.cy); } - private void HiMetric2Pixel(NativeMethods.tagSIZEL sz, NativeMethods.tagSIZEL szout) { + private void HiMetric2Pixel(NativeMethods.tagSIZEL sz, NativeMethods.tagSIZEL szout) + { NativeMethods._POINTL phm = new NativeMethods._POINTL(); phm.x = sz.cx; phm.y = sz.cy; @@ -1128,42 +1282,51 @@ private void HiMetric2Pixel(NativeMethods.tagSIZEL sz, NativeMethods.tagSIZEL sz szout.cy = (int)pcont.y; } - private void Pixel2hiMetric(NativeMethods.tagSIZEL sz, NativeMethods.tagSIZEL szout) { + private void Pixel2hiMetric(NativeMethods.tagSIZEL sz, NativeMethods.tagSIZEL szout) + { NativeMethods.tagPOINTF pcont = new NativeMethods.tagPOINTF(); - pcont.x = (float) sz.cx; - pcont.y = (float) sz.cy; + pcont.x = (float)sz.cx; + pcont.y = (float)sz.cy; NativeMethods._POINTL phm = new NativeMethods._POINTL(); ((UnsafeNativeMethods.IOleControlSite)this.ActiveXSite).TransformCoords(phm, pcont, NativeMethods.ActiveX.XFORMCOORDS_SIZE | NativeMethods.ActiveX.XFORMCOORDS_CONTAINERTOHIMETRIC); szout.cx = phm.x; szout.cy = phm.y; } - private bool EditMode { - get { + private bool EditMode + { + get + { return this.axEditMode != WebBrowserHelper.AXEditMode.None; } } //Find the uppermost ContainerControl that this control lives in - internal ContainerControl FindContainerControlInternal() { - if (Site != null) { + internal ContainerControl FindContainerControlInternal() + { + if (Site != null) + { IDesignerHost host = (IDesignerHost)Site.GetService(typeof(IDesignerHost)); - if (host != null) { + if (host != null) + { IComponent comp = host.RootComponent; - if (comp != null && comp is ContainerControl) { + if (comp != null && comp is ContainerControl) + { return (ContainerControl)comp; } } } ContainerControl cc = null; - for (Control control = this; control != null; control = control.ParentInternal) { + for (Control control = this; control != null; control = control.ParentInternal) + { ContainerControl tempCC = control as ContainerControl; if (tempCC != null) cc = tempCC; } - if (cc == null) { + if (cc == null) + { cc = Control.FromHandle(UnsafeNativeMethods.GetParent(new HandleRef(this, Handle))) as ContainerControl; } @@ -1178,14 +1341,19 @@ internal ContainerControl FindContainerControlInternal() { return cc; } - private void AmbientChanged(int dispid) { - if (activeXInstance != null) { - try { + private void AmbientChanged(int dispid) + { + if (activeXInstance != null) + { + try + { Invalidate(); this.axOleControl.OnAmbientPropertyChange(dispid); } - catch (Exception ex) { - if (ClientUtils.IsCriticalException(ex)) { + catch (Exception ex) + { + if (ClientUtils.IsCriticalException(ex)) + { throw; } Debug.Fail(ex.ToString()); @@ -1252,8 +1420,10 @@ private Object GetAmbientProperty(int dispid) { } #endif - internal UnsafeNativeMethods.IOleInPlaceObject AXInPlaceObject { - get { + internal UnsafeNativeMethods.IOleInPlaceObject AXInPlaceObject + { + get + { return this.axOleInPlaceObject; } } @@ -1267,8 +1437,10 @@ internal UnsafeNativeMethods.IOleInPlaceObject AXInPlaceObject { // Overridden properties: // - protected override Size DefaultSize { - get { + protected override Size DefaultSize + { + get + { return new Size(75, 23); } } @@ -1278,7 +1450,8 @@ protected override Size DefaultSize { // Overridden methods: // - protected override bool IsInputChar(char charCode) { + protected override bool IsInputChar(char charCode) + { return true; } @@ -1288,14 +1461,16 @@ protected override bool IsInputChar(char charCode) { /// [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] [EditorBrowsable(EditorBrowsableState.Advanced)] - protected override void OnHandleCreated(EventArgs e) { + protected override void OnHandleCreated(EventArgs e) + { // // This is needed to prevent some controls (for e.g. Office Web Components) from // failing to InPlaceActivate() when they call RegisterDragDrop() but do not call // OleInitialize(). The EE calls CoInitializeEx() on the thread, but I believe // that is not good enough for DragDrop. // - if (Application.OleRequired() != System.Threading.ApartmentState.STA) { + if (Application.OleRequired() != System.Threading.ApartmentState.STA) + { throw new ThreadStateException(SR.ThreadMustBeSTA); } @@ -1303,11 +1478,14 @@ protected override void OnHandleCreated(EventArgs e) { // make sure we restore whatever running state whad prior to the handle recreate. // - if (axReloadingState != WebBrowserHelper.AXState.Passive && axReloadingState != axState) { - if (axState < axReloadingState) { + if (axReloadingState != WebBrowserHelper.AXState.Passive && axReloadingState != axState) + { + if (axState < axReloadingState) + { TransitionUpTo(axReloadingState); } - else { + else + { TransitionDownTo(axReloadingState); } axReloadingState = WebBrowserHelper.AXState.Passive; @@ -1315,36 +1493,45 @@ protected override void OnHandleCreated(EventArgs e) { } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public override Color BackColor { - get { + public override Color BackColor + { + get + { return base.BackColor; } - set { + set + { base.BackColor = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public override Font Font { - get { + public override Font Font + { + get + { return base.Font; } - set { + set + { base.Font = value; } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public override Color ForeColor { - get { + public override Color ForeColor + { + get + { return base.ForeColor; } - set { + set + { base.ForeColor = value; } } @@ -1371,44 +1558,56 @@ public override Color ForeColor { // [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public override bool AllowDrop { - get { + public override bool AllowDrop + { + get + { return base.AllowDrop; } - set { + set + { throw new NotSupportedException(SR.WebBrowserAllowDropNotSupported); } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public override Image BackgroundImage { - get { + public override Image BackgroundImage + { + get + { return base.BackgroundImage; } - set { + set + { throw new NotSupportedException(SR.WebBrowserBackgroundImageNotSupported); } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public override ImageLayout BackgroundImageLayout { - get { + public override ImageLayout BackgroundImageLayout + { + get + { return base.BackgroundImageLayout; } - set { + set + { throw new NotSupportedException(SR.WebBrowserBackgroundImageLayoutNotSupported); } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public override Cursor Cursor { - get { + public override Cursor Cursor + { + get + { return base.Cursor; } - set { + set + { throw new NotSupportedException(SR.WebBrowserCursorNotSupported); } } @@ -1447,22 +1646,28 @@ public override RightToLeft RightToLeft DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Bindable(false) ] - public override string Text { - get { + public override string Text + { + get + { return ""; } - set { + set + { throw new NotSupportedException(SR.WebBrowserTextNotSupported); } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public new bool UseWaitCursor { - get { + public new bool UseWaitCursor + { + get + { return base.UseWaitCursor; } - set { + set + { throw new NotSupportedException(SR.WebBrowserUseWaitCursorNotSupported); } } @@ -1471,130 +1676,151 @@ public override string Text { // // Unavailable events // - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageLayoutChanged { + new public event EventHandler BackgroundImageLayoutChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "BackgroundImageLayoutChanged")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler Enter { + new public event EventHandler Enter + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "Enter")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler Leave { + new public event EventHandler Leave + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "Leave")); remove { } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler MouseCaptureChanged { + new public event EventHandler MouseCaptureChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "MouseCaptureChanged")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event MouseEventHandler MouseClick { + new public event MouseEventHandler MouseClick + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "MouseClick")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event MouseEventHandler MouseDoubleClick { + new public event MouseEventHandler MouseDoubleClick + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "MouseDoubleClick")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackColorChanged { + new public event EventHandler BackColorChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "BackColorChanged")); remove { } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BackgroundImageChanged { + new public event EventHandler BackgroundImageChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "BackgroundImageChanged")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler BindingContextChanged { + new public event EventHandler BindingContextChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "BindingContextChanged")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler CursorChanged { + new public event EventHandler CursorChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "CursorChanged")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler EnabledChanged { + new public event EventHandler EnabledChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "EnabledChanged")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler FontChanged { + new public event EventHandler FontChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "FontChanged")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler ForeColorChanged { + new public event EventHandler ForeColorChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "ForeColorChanged")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler RightToLeftChanged { + new public event EventHandler RightToLeftChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "RightToLeftChanged")); remove { } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler TextChanged { + new public event EventHandler TextChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "TextChanged")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler Click { + new public event EventHandler Click + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "Click")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event DragEventHandler DragDrop { + new public event DragEventHandler DragDrop + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "DragDrop")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event DragEventHandler DragEnter { + new public event DragEventHandler DragEnter + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "DragEnter")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event DragEventHandler DragOver { + new public event DragEventHandler DragOver + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "DragOver")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler DragLeave { + new public event EventHandler DragLeave + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "DragLeave")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event GiveFeedbackEventHandler GiveFeedback { + new public event GiveFeedbackEventHandler GiveFeedback + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "GiveFeedback")); remove { } } @@ -1608,109 +1834,127 @@ public override string Text { } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event PaintEventHandler Paint { + new public event PaintEventHandler Paint + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "Paint")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event QueryContinueDragEventHandler QueryContinueDrag { + new public event QueryContinueDragEventHandler QueryContinueDrag + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "QueryContinueDrag")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event QueryAccessibilityHelpEventHandler QueryAccessibilityHelp { + new public event QueryAccessibilityHelpEventHandler QueryAccessibilityHelp + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "QueryAccessibilityHelp")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler DoubleClick { + new public event EventHandler DoubleClick + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "DoubleClick")); remove { } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler ImeModeChanged { + new public event EventHandler ImeModeChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "ImeModeChanged")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event KeyEventHandler KeyDown { + new public event KeyEventHandler KeyDown + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "KeyDown")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event KeyPressEventHandler KeyPress { + new public event KeyPressEventHandler KeyPress + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "KeyPress")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event KeyEventHandler KeyUp { + new public event KeyEventHandler KeyUp + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "KeyUp")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event LayoutEventHandler Layout { + new public event LayoutEventHandler Layout + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "Layout")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event MouseEventHandler MouseDown { + new public event MouseEventHandler MouseDown + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "MouseDown")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler MouseEnter { + new public event EventHandler MouseEnter + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "MouseEnter")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler MouseLeave { + new public event EventHandler MouseLeave + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "MouseLeave")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler MouseHover { + new public event EventHandler MouseHover + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "MouseHover")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event MouseEventHandler MouseMove { + new public event MouseEventHandler MouseMove + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "MouseMove")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event MouseEventHandler MouseUp { + new public event MouseEventHandler MouseUp + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "MouseUp")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event MouseEventHandler MouseWheel { + new public event MouseEventHandler MouseWheel + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "MouseWheel")); remove { } } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event UICuesEventHandler ChangeUICues { + new public event UICuesEventHandler ChangeUICues + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "ChangeUICues")); remove { } } - + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - new public event EventHandler StyleChanged { + new public event EventHandler StyleChanged + { add => throw new NotSupportedException(string.Format(SR.AXAddInvalidEvent, "StyleChanged")); remove { } } @@ -1718,18 +1962,22 @@ public override string Text { /// /// Defines a window that the ActiveX window is attached to so that we can override it's wndproc. /// - private class WebBrowserBaseNativeWindow : NativeWindow { + private class WebBrowserBaseNativeWindow : NativeWindow + { private WebBrowserBase WebBrowserBase; - public WebBrowserBaseNativeWindow(WebBrowserBase ax) { + public WebBrowserBaseNativeWindow(WebBrowserBase ax) + { this.WebBrowserBase = ax; } - + /// /// Pass messages on to the NotifyIcon object's wndproc handler. /// - protected override void WndProc(ref Message m) { - switch (m.Msg) { + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { case Interop.WindowMessages.WM_WINDOWPOSCHANGING: WmWindowPosChanging(ref m); break; @@ -1739,16 +1987,19 @@ protected override void WndProc(ref Message m) { } } - private unsafe void WmWindowPosChanging(ref Message m) { - NativeMethods.WINDOWPOS* wp = (NativeMethods.WINDOWPOS *)m.LParam; + private unsafe void WmWindowPosChanging(ref Message m) + { + NativeMethods.WINDOWPOS* wp = (NativeMethods.WINDOWPOS*)m.LParam; wp->x = 0; wp->y = 0; Size s = WebBrowserBase.webBrowserBaseChangingSize; - if (s.Width == -1) { // Invalid value. Use WebBrowserBase.Bounds instead, when this is the case. + if (s.Width == -1) + { // Invalid value. Use WebBrowserBase.Bounds instead, when this is the case. wp->cx = WebBrowserBase.Width; wp->cy = WebBrowserBase.Height; } - else { + else + { wp->cx = s.Width; wp->cy = s.Height; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs index 729eb67018e..188e22a486f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs @@ -22,26 +22,31 @@ internal class WebBrowserContainer : UnsafeNativeMethods.IOleContainer, UnsafeNa private Hashtable components = null; // Control -> any private WebBrowserBase ctlInEditMode = null; - internal WebBrowserContainer(WebBrowserBase parent) { + internal WebBrowserContainer(WebBrowserBase parent) + { this.parent = parent; } // // IOleContainer methods: // - int UnsafeNativeMethods.IOleContainer.ParseDisplayName(object pbc, string pszDisplayName, int[] pchEaten, object[] ppmkOut) { + int UnsafeNativeMethods.IOleContainer.ParseDisplayName(object pbc, string pszDisplayName, int[] pchEaten, object[] ppmkOut) + { if (ppmkOut != null) ppmkOut[0] = null; - return NativeMethods.E_NOTIMPL; + return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleContainer.EnumObjects(int grfFlags, out UnsafeNativeMethods.IEnumUnknown ppenum) { + int UnsafeNativeMethods.IOleContainer.EnumObjects(int grfFlags, out UnsafeNativeMethods.IEnumUnknown ppenum) + { ppenum = null; - if ((grfFlags & 1) != 0) { // 1 == OLECONTF_EMBEDDINGS + if ((grfFlags & 1) != 0) + { // 1 == OLECONTF_EMBEDDINGS Debug.Assert(parent != null, "gotta have it..."); ArrayList list = new ArrayList(); ListAXControls(list, true); - if (list.Count > 0) { + if (list.Count > 0) + { object[] temp = new object[list.Count]; list.CopyTo(temp, 0); ppenum = new AxHost.EnumUnknown(temp); @@ -52,36 +57,45 @@ int UnsafeNativeMethods.IOleContainer.EnumObjects(int grfFlags, out UnsafeNative return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleContainer.LockContainer(bool fLock) { + int UnsafeNativeMethods.IOleContainer.LockContainer(bool fLock) + { return NativeMethods.E_NOTIMPL; } // // IOleInPlaceFrame methods: // - IntPtr UnsafeNativeMethods.IOleInPlaceFrame.GetWindow() { + IntPtr UnsafeNativeMethods.IOleInPlaceFrame.GetWindow() + { return parent.Handle; } - int UnsafeNativeMethods.IOleInPlaceFrame.ContextSensitiveHelp(int fEnterMode) { + int UnsafeNativeMethods.IOleInPlaceFrame.ContextSensitiveHelp(int fEnterMode) + { return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleInPlaceFrame.GetBorder(NativeMethods.COMRECT lprectBorder) { + int UnsafeNativeMethods.IOleInPlaceFrame.GetBorder(NativeMethods.COMRECT lprectBorder) + { return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleInPlaceFrame.RequestBorderSpace(NativeMethods.COMRECT pborderwidths) { + int UnsafeNativeMethods.IOleInPlaceFrame.RequestBorderSpace(NativeMethods.COMRECT pborderwidths) + { return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleInPlaceFrame.SetBorderSpace(NativeMethods.COMRECT pborderwidths) { + int UnsafeNativeMethods.IOleInPlaceFrame.SetBorderSpace(NativeMethods.COMRECT pborderwidths) + { return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleInPlaceFrame.SetActiveObject(UnsafeNativeMethods.IOleInPlaceActiveObject pActiveObject, string pszObjName) { - if (pActiveObject == null) { - if (ctlInEditMode != null) { + int UnsafeNativeMethods.IOleInPlaceFrame.SetActiveObject(UnsafeNativeMethods.IOleInPlaceActiveObject pActiveObject, string pszObjName) + { + if (pActiveObject == null) + { + if (ctlInEditMode != null) + { ctlInEditMode.SetEditMode(WebBrowserHelper.AXEditMode.None); ctlInEditMode = null; } @@ -89,9 +103,11 @@ int UnsafeNativeMethods.IOleInPlaceFrame.SetActiveObject(UnsafeNativeMethods.IOl } WebBrowserBase ctl = null; UnsafeNativeMethods.IOleObject oleObject = pActiveObject as UnsafeNativeMethods.IOleObject; - if (oleObject != null) { + if (oleObject != null) + { UnsafeNativeMethods.IOleClientSite clientSite = null; - try { + try + { clientSite = oleObject.GetClientSite(); WebBrowserSiteBase webBrowserSiteBase = clientSite as WebBrowserSiteBase; if (webBrowserSiteBase != null) @@ -99,20 +115,25 @@ int UnsafeNativeMethods.IOleInPlaceFrame.SetActiveObject(UnsafeNativeMethods.IOl ctl = webBrowserSiteBase.GetAXHost(); } } - catch (COMException t) { + catch (COMException t) + { Debug.Fail(t.ToString()); } - if (ctlInEditMode != null) { + if (ctlInEditMode != null) + { Debug.Fail("control " + ctlInEditMode.ToString() + " did not reset its edit mode to null"); ctlInEditMode.SetSelectionStyle(WebBrowserHelper.SelectionStyle.Selected); ctlInEditMode.SetEditMode(WebBrowserHelper.AXEditMode.None); } - - if (ctl == null) { + + if (ctl == null) + { ctlInEditMode = null; } - else { - if (!ctl.IsUserMode) { + else + { + if (!ctl.IsUserMode) + { ctlInEditMode = ctl; ctl.SetEditMode(WebBrowserHelper.AXEditMode.Object); ctl.AddSelectionHandler(); @@ -124,27 +145,33 @@ int UnsafeNativeMethods.IOleInPlaceFrame.SetActiveObject(UnsafeNativeMethods.IOl return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleInPlaceFrame.InsertMenus(IntPtr hmenuShared, NativeMethods.tagOleMenuGroupWidths lpMenuWidths) { + int UnsafeNativeMethods.IOleInPlaceFrame.InsertMenus(IntPtr hmenuShared, NativeMethods.tagOleMenuGroupWidths lpMenuWidths) + { return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleInPlaceFrame.SetMenu(IntPtr hmenuShared, IntPtr holemenu, IntPtr hwndActiveObject) { + int UnsafeNativeMethods.IOleInPlaceFrame.SetMenu(IntPtr hmenuShared, IntPtr holemenu, IntPtr hwndActiveObject) + { return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleInPlaceFrame.RemoveMenus(IntPtr hmenuShared) { + int UnsafeNativeMethods.IOleInPlaceFrame.RemoveMenus(IntPtr hmenuShared) + { return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleInPlaceFrame.SetStatusText(string pszStatusText) { + int UnsafeNativeMethods.IOleInPlaceFrame.SetStatusText(string pszStatusText) + { return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleInPlaceFrame.EnableModeless(bool fEnable) { + int UnsafeNativeMethods.IOleInPlaceFrame.EnableModeless(bool fEnable) + { return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleInPlaceFrame.TranslateAccelerator(ref NativeMethods.MSG lpmsg, short wID) { + int UnsafeNativeMethods.IOleInPlaceFrame.TranslateAccelerator(ref NativeMethods.MSG lpmsg, short wID) + { return NativeMethods.S_FALSE; } @@ -152,7 +179,8 @@ int UnsafeNativeMethods.IOleInPlaceFrame.TranslateAccelerator(ref NativeMethods. // // Private helper methods: // - private void ListAXControls(ArrayList list, bool fuseOcx) { + private void ListAXControls(ArrayList list, bool fuseOcx) + { Hashtable components = GetComponents(); if (components == null) { @@ -160,18 +188,24 @@ private void ListAXControls(ArrayList list, bool fuseOcx) { } Control[] ctls = new Control[components.Keys.Count]; components.Keys.CopyTo(ctls, 0); - if (ctls != null) { - for (int i = 0; i < ctls.Length; i++) { + if (ctls != null) + { + for (int i = 0; i < ctls.Length; i++) + { Control ctl = ctls[i]; WebBrowserBase webBrowserBase = ctl as WebBrowserBase; - if (webBrowserBase != null) { - if (fuseOcx) { + if (webBrowserBase != null) + { + if (fuseOcx) + { object ax = webBrowserBase.activeXInstance; - if (ax != null) { + if (ax != null) + { list.Add(ax); } } - else { + else + { list.Add(ctl); } } @@ -179,11 +213,13 @@ private void ListAXControls(ArrayList list, bool fuseOcx) { } } - private Hashtable GetComponents() { + private Hashtable GetComponents() + { return GetComponents(GetParentsContainer()); } - private IContainer GetParentsContainer() { + private IContainer GetParentsContainer() + { // IContainer rval = GetParentIContainer(); Debug.Assert(rval == null || assocContainer == null || rval == assocContainer, @@ -191,24 +227,32 @@ private IContainer GetParentsContainer() { return rval == null ? assocContainer : rval; } - private IContainer GetParentIContainer() { + private IContainer GetParentIContainer() + { ISite site = parent.Site; - if (site != null && site.DesignMode) return site.Container; + if (site != null && site.DesignMode) + return site.Container; return null; } - private Hashtable GetComponents(IContainer cont) { + private Hashtable GetComponents(IContainer cont) + { FillComponentsTable(cont); return components; } - private void FillComponentsTable(IContainer container) { - if (container != null) { + private void FillComponentsTable(IContainer container) + { + if (container != null) + { ComponentCollection comps = container.Components; - if (comps != null) { + if (comps != null) + { components = new Hashtable(); - foreach (IComponent comp in comps) { - if (comp is Control && comp != parent && comp.Site != null) { + foreach (IComponent comp in comps) + { + if (comp is Control && comp != parent && comp.Site != null) + { components.Add(comp, comp); } } @@ -221,13 +265,17 @@ private void FillComponentsTable(IContainer container) { bool checkHashTable = true; Control[] ctls = new Control[containerCache.Values.Count]; containerCache.Values.CopyTo(ctls, 0); - if (ctls != null) { - if (ctls.Length > 0 && components == null) { + if (ctls != null) + { + if (ctls.Length > 0 && components == null) + { components = new Hashtable(); checkHashTable = false; } - for (int i = 0; i < ctls.Length; i ++) { - if (checkHashTable && !components.Contains(ctls[i])) { + for (int i = 0; i < ctls.Length; i++) + { + if (checkHashTable && !components.Contains(ctls[i])) + { components.Add(ctls[i], ctls[i]); } } @@ -236,34 +284,43 @@ private void FillComponentsTable(IContainer container) { GetAllChildren(this.parent); } - private void GetAllChildren(Control ctl) { + private void GetAllChildren(Control ctl) + { if (ctl == null) return; - if (components == null) { + if (components == null) + { components = new Hashtable(); } if (ctl != this.parent && !components.Contains(ctl)) components.Add(ctl, ctl); - foreach(Control c in ctl.Controls) { + foreach (Control c in ctl.Controls) + { GetAllChildren(c); } } - private bool RegisterControl(WebBrowserBase ctl) { + private bool RegisterControl(WebBrowserBase ctl) + { ISite site = ctl.Site; - if (site != null) { + if (site != null) + { IContainer cont = site.Container; - if (cont != null) { - if (assocContainer != null) { + if (cont != null) + { + if (assocContainer != null) + { return cont == assocContainer; } - else { + else + { assocContainer = cont; IComponentChangeService ccs = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); - if (ccs != null) { + if (ccs != null) + { ccs.ComponentRemoved += new ComponentEventHandler(this.OnComponentRemoved); } return true; @@ -273,9 +330,11 @@ private bool RegisterControl(WebBrowserBase ctl) { return false; } - private void OnComponentRemoved(object sender, ComponentEventArgs e) { + private void OnComponentRemoved(object sender, ComponentEventArgs e) + { Control c = e.Component as Control; - if (sender == assocContainer && c != null) { + if (sender == assocContainer && c != null) + { RemoveControl(c); } } @@ -283,39 +342,48 @@ private void OnComponentRemoved(object sender, ComponentEventArgs e) { // // Internal helper methods: // - internal void AddControl(Control ctl) { + internal void AddControl(Control ctl) + { if (containerCache.Contains(ctl)) throw new ArgumentException(string.Format(SR.AXDuplicateControl, GetNameForControl(ctl)), "ctl"); containerCache.Add(ctl, ctl); - - if (assocContainer == null) { + + if (assocContainer == null) + { ISite site = ctl.Site; - if (site != null) { + if (site != null) + { assocContainer = site.Container; IComponentChangeService ccs = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); - if (ccs != null) { + if (ccs != null) + { ccs.ComponentRemoved += new ComponentEventHandler(this.OnComponentRemoved); } } } } - internal void RemoveControl(Control ctl) { + internal void RemoveControl(Control ctl) + { //ctl may not be in containerCache: Remove is a no-op if it's not there. containerCache.Remove(ctl); } - internal static WebBrowserContainer FindContainerForControl(WebBrowserBase ctl) { - if (ctl != null) { + internal static WebBrowserContainer FindContainerForControl(WebBrowserBase ctl) + { + if (ctl != null) + { if (ctl.container != null) { return ctl.container; } ScrollableControl f = ctl.ContainingControl; - if (f != null) { + if (f != null) + { WebBrowserContainer container = ctl.CreateWebBrowserContainer(); - if (container.RegisterControl(ctl)) { + if (container.RegisterControl(ctl)) + { container.AddControl(ctl); return container; } @@ -324,19 +392,22 @@ internal static WebBrowserContainer FindContainerForControl(WebBrowserBase ctl) return null; } - internal string GetNameForControl(Control ctl) { + internal string GetNameForControl(Control ctl) + { string name = (ctl.Site != null) ? ctl.Site.Name : ctl.Name; return name ?? ""; } - internal void OnUIActivate(WebBrowserBase site) { + internal void OnUIActivate(WebBrowserBase site) + { // The ShDocVw control repeatedly calls OnUIActivate() with the same // site. This causes the assert below to fire. // if (siteUIActive == site) return; - if (siteUIActive != null && siteUIActive != site) { + if (siteUIActive != null && siteUIActive != site) + { WebBrowserBase tempSite = siteUIActive; tempSite.AXInPlaceObject.UIDeactivate(); } @@ -344,14 +415,17 @@ internal void OnUIActivate(WebBrowserBase site) { Debug.Assert(siteUIActive == null, "Object did not call OnUIDeactivate"); siteUIActive = site; ContainerControl f = site.ContainingControl; - if (f != null && f.Contains(site)) { + if (f != null && f.Contains(site)) + { f.SetActiveControl(site); } } - internal void OnUIDeactivate(WebBrowserBase site) { + internal void OnUIDeactivate(WebBrowserBase site) + { #if DEBUG - if (siteUIActive != null) { + if (siteUIActive != null) + { Debug.Assert(siteUIActive == site, "deactivating when not active..."); } #endif // DEBUG @@ -362,22 +436,27 @@ internal void OnUIDeactivate(WebBrowserBase site) { site.SetEditMode(WebBrowserHelper.AXEditMode.None); } - internal void OnInPlaceDeactivate(WebBrowserBase site) { - if (siteActive == site) { + internal void OnInPlaceDeactivate(WebBrowserBase site) + { + if (siteActive == site) + { siteActive = null; ContainerControl parentContainer = parent.FindContainerControlInternal(); - if (parentContainer != null) { + if (parentContainer != null) + { parentContainer.SetActiveControl(null); } } } - internal void OnExitEditMode(WebBrowserBase ctl) { + internal void OnExitEditMode(WebBrowserBase ctl) + { Debug.Assert(ctlInEditMode == null || ctlInEditMode == ctl, "who is exiting edit mode?"); - if (ctlInEditMode == ctl) { + if (ctlInEditMode == ctl) + { ctlInEditMode = null; } } } - + } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserDocumentCompletedEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserDocumentCompletedEventArgs.cs index ed1dda71bc9..f3432e7235c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserDocumentCompletedEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserDocumentCompletedEventArgs.cs @@ -18,7 +18,7 @@ public WebBrowserDocumentCompletedEventArgs(Uri url) { _url = url; } - + /// /// Url of the Document. /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserEncryptionLevel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserEncryptionLevel.cs index 12fd2f7b059..baebf31c05c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserEncryptionLevel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserEncryptionLevel.cs @@ -10,7 +10,7 @@ namespace System.Windows.Forms /// public enum WebBrowserEncryptionLevel { - Insecure = 0, + Insecure = 0, Mixed = 1, Unknown = 2, Bit40 = 3, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserHelper.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserHelper.cs index 89148b65130..e9dd6da1134 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserHelper.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserHelper.cs @@ -19,7 +19,8 @@ namespace System.Windows.Forms internal static class WebBrowserHelper { // Enumeration of the different states of the ActiveX control - internal enum AXState { + internal enum AXState + { Passive = 0, // Not loaded Loaded = 1, // Loaded, but no server [ocx created] Running = 2, // Server running, invisible [depersisted] @@ -28,24 +29,26 @@ internal enum AXState { } // // Enumeration of the different Edit modes - internal enum AXEditMode { + internal enum AXEditMode + { None = 0, // object not being edited Object = 1, // object provided an edit verb and we invoked it Host = 2 // we invoked our own edit verb }; // // Enumeration of Selection Styles - internal enum SelectionStyle { + internal enum SelectionStyle + { NotSelected = 0, Selected = 1, Active = 2 }; - + // // Static members: // - + // // BitVector32 masks for various internal state flags. internal static readonly int sinkAttached = BitVector32.CreateMask(); @@ -65,9 +68,9 @@ internal enum SelectionStyle { // // Special guids private static Guid ifont_Guid = typeof(UnsafeNativeMethods.IFont).GUID; - internal static Guid windowsMediaPlayer_Clsid = new Guid("{22d6f312-b0f6-11d0-94ab-0080c74c7e95}"); - internal static Guid comctlImageCombo_Clsid = new Guid("{a98a24c0-b06f-3684-8c12-c52ae341e0bc}"); - internal static Guid maskEdit_Clsid = new Guid("{c932ba85-4374-101b-a56c-00aa003668dc}"); + internal static Guid windowsMediaPlayer_Clsid = new Guid("{22d6f312-b0f6-11d0-94ab-0080c74c7e95}"); + internal static Guid comctlImageCombo_Clsid = new Guid("{a98a24c0-b06f-3684-8c12-c52ae341e0bc}"); + internal static Guid maskEdit_Clsid = new Guid("{c932ba85-4374-101b-a56c-00aa003668dc}"); // // Window message to check if we have already sub-classed internal static readonly int REGMSG_MSG = SafeNativeMethods.RegisterWindowMessage(Application.WindowMessagesVersion + "_subclassCheck"); @@ -78,21 +81,27 @@ internal enum SelectionStyle { // Static helper methods: // - internal static int Pix2HM(int pix, int logP) { - return(HMperInch * pix + ( logP >> 1)) / logP; + internal static int Pix2HM(int pix, int logP) + { + return (HMperInch * pix + (logP >> 1)) / logP; } - internal static int HM2Pix(int hm, int logP) { - return(logP * hm + HMperInch / 2) / HMperInch; + internal static int HM2Pix(int hm, int logP) + { + return (logP * hm + HMperInch / 2) / HMperInch; } // // We cache LOGPIXELSX for optimization - internal static int LogPixelsX { - get { - if (logPixelsX == -1) { + internal static int LogPixelsX + { + get + { + if (logPixelsX == -1) + { IntPtr hDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef); - if (hDC != IntPtr.Zero) { + if (hDC != IntPtr.Zero) + { logPixelsX = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, hDC), NativeMethods.LOGPIXELSX); UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, hDC)); } @@ -100,17 +109,22 @@ internal static int LogPixelsX { return logPixelsX; } } - internal static void ResetLogPixelsX() { + internal static void ResetLogPixelsX() + { logPixelsX = -1; } - + // // We cache LOGPIXELSY for optimization - internal static int LogPixelsY { - get { - if (logPixelsY == -1) { + internal static int LogPixelsY + { + get + { + if (logPixelsY == -1) + { IntPtr hDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef); - if (hDC != IntPtr.Zero) { + if (hDC != IntPtr.Zero) + { logPixelsY = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, hDC), NativeMethods.LOGPIXELSY); UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, hDC)); } @@ -118,20 +132,24 @@ internal static int LogPixelsY { return logPixelsY; } } - internal static void ResetLogPixelsY() { + internal static void ResetLogPixelsY() + { logPixelsY = -1; } // // Gets the selection service from the control's site - internal static ISelectionService GetSelectionService(Control ctl) { + internal static ISelectionService GetSelectionService(Control ctl) + { ISite site = ctl.Site; - if (site != null) { + if (site != null) + { object o = site.GetService(typeof(ISelectionService)); Debug.Assert(o == null || o is ISelectionService, "service must implement ISelectionService"); - if (o is ISelectionService) { - return(ISelectionService) o; + if (o is ISelectionService) + { + return (ISelectionService)o; } } return null; @@ -139,7 +157,8 @@ internal static ISelectionService GetSelectionService(Control ctl) { // // Returns a big COMRECT - internal static NativeMethods.COMRECT GetClipRect() { + internal static NativeMethods.COMRECT GetClipRect() + { return new NativeMethods.COMRECT(new Rectangle(0, 0, 32000, 32000)); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserNavigatedEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserNavigatedEventArgs.cs index e0adba3e239..1560b6db4a6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserNavigatedEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserNavigatedEventArgs.cs @@ -18,7 +18,7 @@ public WebBrowserNavigatedEventArgs(Uri url) { _url = url; } - + /// /// Url the browser navigated to. /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserNavigatingEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserNavigatingEventArgs.cs index fd4633956d7..1bc13914fad 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserNavigatingEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserNavigatingEventArgs.cs @@ -13,7 +13,7 @@ public class WebBrowserNavigatingEventArgs : CancelEventArgs { private readonly Uri _url; private readonly string _targetFrameName; - + /// /// Creates an instance of the class. /// @@ -22,7 +22,7 @@ public WebBrowserNavigatingEventArgs(Uri url, string targetFrameName) _url = url; _targetFrameName = targetFrameName; } - + /// /// Url the browser is navigating to. /// @@ -33,7 +33,7 @@ public Uri Url return _url; } } - + /// /// In case an individual frame is about to be navigated, this contains the frame name. /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserProgressChangedEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserProgressChangedEventArgs.cs index 6dfc7cdde11..2092e89e3d3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserProgressChangedEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserProgressChangedEventArgs.cs @@ -17,12 +17,12 @@ public WebBrowserProgressChangedEventArgs(long currentProgress, long maximumProg CurrentProgress = currentProgress; MaximumProgress = maximumProgress; } - + /// /// Specifies current number of bytes donwloaded. CurrentProgress/MaximumProgress*100 = progress percentage. /// public long CurrentProgress { get; } - + /// /// Specifies total number of bytes of item being downloaded. /// CurrentProgress/MaximumProgress*100 = progress percentage. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs index 32da7056aaa..582cee898d4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs @@ -32,8 +32,10 @@ public class WebBrowserSiteBase // this cannot be used as a standalone site. It has to be used in conjunction // with WebBrowserBase. Perhaps we can change it in future. // - internal WebBrowserSiteBase(WebBrowserBase h) { - if (h == null) { + internal WebBrowserSiteBase(WebBrowserBase h) + { + if (h == null) + { throw new ArgumentNullException(nameof(h)); } this.host = h; @@ -66,67 +68,83 @@ protected virtual void Dispose(bool disposing) /// Retrieves the WebBrowserBase object set in the constructor. /// /// - internal WebBrowserBase Host { - get { + internal WebBrowserBase Host + { + get + { return this.host; } } - + // // Interface implementations: // - + // // IOleControlSite methods: // - int UnsafeNativeMethods.IOleControlSite.OnControlInfoChanged() { + int UnsafeNativeMethods.IOleControlSite.OnControlInfoChanged() + { return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleControlSite.LockInPlaceActive(int fLock) { + int UnsafeNativeMethods.IOleControlSite.LockInPlaceActive(int fLock) + { return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleControlSite.GetExtendedControl(out object ppDisp) { + int UnsafeNativeMethods.IOleControlSite.GetExtendedControl(out object ppDisp) + { ppDisp = null; return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleControlSite.TransformCoords(NativeMethods._POINTL pPtlHimetric, NativeMethods.tagPOINTF pPtfContainer, int dwFlags) { - if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_HIMETRICTOCONTAINER) != 0) { - if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_SIZE) != 0) { - pPtfContainer.x = (float) WebBrowserHelper.HM2Pix(pPtlHimetric.x, WebBrowserHelper.LogPixelsX); - pPtfContainer.y = (float) WebBrowserHelper.HM2Pix(pPtlHimetric.y, WebBrowserHelper.LogPixelsY); + int UnsafeNativeMethods.IOleControlSite.TransformCoords(NativeMethods._POINTL pPtlHimetric, NativeMethods.tagPOINTF pPtfContainer, int dwFlags) + { + if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_HIMETRICTOCONTAINER) != 0) + { + if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_SIZE) != 0) + { + pPtfContainer.x = (float)WebBrowserHelper.HM2Pix(pPtlHimetric.x, WebBrowserHelper.LogPixelsX); + pPtfContainer.y = (float)WebBrowserHelper.HM2Pix(pPtlHimetric.y, WebBrowserHelper.LogPixelsY); } - else if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_POSITION) != 0) { - pPtfContainer.x = (float) WebBrowserHelper.HM2Pix(pPtlHimetric.x, WebBrowserHelper.LogPixelsX); - pPtfContainer.y = (float) WebBrowserHelper.HM2Pix(pPtlHimetric.y, WebBrowserHelper.LogPixelsY); + else if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_POSITION) != 0) + { + pPtfContainer.x = (float)WebBrowserHelper.HM2Pix(pPtlHimetric.x, WebBrowserHelper.LogPixelsX); + pPtfContainer.y = (float)WebBrowserHelper.HM2Pix(pPtlHimetric.y, WebBrowserHelper.LogPixelsY); } - else { + else + { return NativeMethods.E_INVALIDARG; } } - else if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_CONTAINERTOHIMETRIC) != 0) { - if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_SIZE) != 0) { + else if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_CONTAINERTOHIMETRIC) != 0) + { + if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_SIZE) != 0) + { pPtlHimetric.x = WebBrowserHelper.Pix2HM((int)pPtfContainer.x, WebBrowserHelper.LogPixelsX); pPtlHimetric.y = WebBrowserHelper.Pix2HM((int)pPtfContainer.y, WebBrowserHelper.LogPixelsY); } - else if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_POSITION) != 0) { + else if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_POSITION) != 0) + { pPtlHimetric.x = WebBrowserHelper.Pix2HM((int)pPtfContainer.x, WebBrowserHelper.LogPixelsX); pPtlHimetric.y = WebBrowserHelper.Pix2HM((int)pPtfContainer.y, WebBrowserHelper.LogPixelsY); } - else { + else + { return NativeMethods.E_INVALIDARG; } } - else { + else + { return NativeMethods.E_INVALIDARG; } return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleControlSite.TranslateAccelerator(ref NativeMethods.MSG pMsg, int grfModifiers) { + int UnsafeNativeMethods.IOleControlSite.TranslateAccelerator(ref NativeMethods.MSG pMsg, int grfModifiers) + { Debug.Assert(!this.Host.GetAXHostState(WebBrowserHelper.siteProcessedInputKey), "Re-entering UnsafeNativeMethods.IOleControlSite.TranslateAccelerator!!!"); this.Host.SetAXHostState(WebBrowserHelper.siteProcessedInputKey, true); @@ -135,72 +153,88 @@ int UnsafeNativeMethods.IOleControlSite.TranslateAccelerator(ref NativeMethods.M msg.WParam = pMsg.wParam; msg.LParam = pMsg.lParam; msg.HWnd = pMsg.hwnd; - - try { + + try + { bool f = ((Control)this.Host).PreProcessControlMessage(ref msg) == PreProcessControlState.MessageProcessed; return f ? NativeMethods.S_OK : NativeMethods.S_FALSE; } - finally { + finally + { this.Host.SetAXHostState(WebBrowserHelper.siteProcessedInputKey, false); } } - int UnsafeNativeMethods.IOleControlSite.OnFocus(int fGotFocus) { + int UnsafeNativeMethods.IOleControlSite.OnFocus(int fGotFocus) + { return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleControlSite.ShowPropertyFrame() { + int UnsafeNativeMethods.IOleControlSite.ShowPropertyFrame() + { return NativeMethods.E_NOTIMPL; } // // IOleClientSite methods: // - int UnsafeNativeMethods.IOleClientSite.SaveObject() { + int UnsafeNativeMethods.IOleClientSite.SaveObject() + { return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleClientSite.GetMoniker(int dwAssign, int dwWhichMoniker, out object moniker) { + int UnsafeNativeMethods.IOleClientSite.GetMoniker(int dwAssign, int dwWhichMoniker, out object moniker) + { moniker = null; return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleClientSite.GetContainer(out UnsafeNativeMethods.IOleContainer container) { + int UnsafeNativeMethods.IOleClientSite.GetContainer(out UnsafeNativeMethods.IOleContainer container) + { container = this.Host.GetParentContainer(); return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleClientSite.ShowObject() { - if (this.Host.ActiveXState >= WebBrowserHelper.AXState.InPlaceActive) { + int UnsafeNativeMethods.IOleClientSite.ShowObject() + { + if (this.Host.ActiveXState >= WebBrowserHelper.AXState.InPlaceActive) + { IntPtr hwnd; - if (NativeMethods.Succeeded(this.Host.AXInPlaceObject.GetWindow(out hwnd))) { - if (this.Host.GetHandleNoCreate() != hwnd) { - if (hwnd != IntPtr.Zero) { + if (NativeMethods.Succeeded(this.Host.AXInPlaceObject.GetWindow(out hwnd))) + { + if (this.Host.GetHandleNoCreate() != hwnd) + { + if (hwnd != IntPtr.Zero) + { this.Host.AttachWindow(hwnd); this.OnActiveXRectChange(new NativeMethods.COMRECT(this.Host.Bounds)); } } } - else if (this.Host.AXInPlaceObject is UnsafeNativeMethods.IOleInPlaceObjectWindowless) { + else if (this.Host.AXInPlaceObject is UnsafeNativeMethods.IOleInPlaceObjectWindowless) + { throw new InvalidOperationException(SR.AXWindowlessControl); } } return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleClientSite.OnShowWindow(int fShow) { + int UnsafeNativeMethods.IOleClientSite.OnShowWindow(int fShow) + { return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleClientSite.RequestNewObjectLayout() { + int UnsafeNativeMethods.IOleClientSite.RequestNewObjectLayout() + { return NativeMethods.E_NOTIMPL; } // // IOleInPlaceSite methods: // - IntPtr UnsafeNativeMethods.IOleInPlaceSite.GetWindow() { + IntPtr UnsafeNativeMethods.IOleInPlaceSite.GetWindow() + { try { return UnsafeNativeMethods.GetParent(new HandleRef(Host, Host.Handle)); @@ -212,38 +246,44 @@ IntPtr UnsafeNativeMethods.IOleInPlaceSite.GetWindow() { } } - int UnsafeNativeMethods.IOleInPlaceSite.ContextSensitiveHelp(int fEnterMode) { + int UnsafeNativeMethods.IOleInPlaceSite.ContextSensitiveHelp(int fEnterMode) + { return NativeMethods.E_NOTIMPL; } - int UnsafeNativeMethods.IOleInPlaceSite.CanInPlaceActivate() { + int UnsafeNativeMethods.IOleInPlaceSite.CanInPlaceActivate() + { return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleInPlaceSite.OnInPlaceActivate() { + int UnsafeNativeMethods.IOleInPlaceSite.OnInPlaceActivate() + { this.Host.ActiveXState = WebBrowserHelper.AXState.InPlaceActive; this.OnActiveXRectChange(new NativeMethods.COMRECT(this.Host.Bounds)); return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleInPlaceSite.OnUIActivate() { + int UnsafeNativeMethods.IOleInPlaceSite.OnUIActivate() + { this.Host.ActiveXState = WebBrowserHelper.AXState.UIActive; this.Host.GetParentContainer().OnUIActivate(this.Host); return NativeMethods.S_OK; } int UnsafeNativeMethods.IOleInPlaceSite.GetWindowContext(out UnsafeNativeMethods.IOleInPlaceFrame ppFrame, out UnsafeNativeMethods.IOleInPlaceUIWindow ppDoc, - NativeMethods.COMRECT lprcPosRect, NativeMethods.COMRECT lprcClipRect, NativeMethods.tagOIFI lpFrameInfo) { + NativeMethods.COMRECT lprcPosRect, NativeMethods.COMRECT lprcClipRect, NativeMethods.tagOIFI lpFrameInfo) + { ppDoc = null; ppFrame = this.Host.GetParentContainer(); - + lprcPosRect.left = this.Host.Bounds.X; lprcPosRect.top = this.Host.Bounds.Y; lprcPosRect.right = this.Host.Bounds.Width + this.Host.Bounds.X; lprcPosRect.bottom = this.Host.Bounds.Height + this.Host.Bounds.Y; - + lprcClipRect = WebBrowserHelper.GetClipRect(); - if (lpFrameInfo != null) { + if (lpFrameInfo != null) + { lpFrameInfo.cb = Marshal.SizeOf(); lpFrameInfo.fMDIApp = false; lpFrameInfo.hAccel = IntPtr.Zero; @@ -253,20 +293,25 @@ int UnsafeNativeMethods.IOleInPlaceSite.GetWindowContext(out UnsafeNativeMethods return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleInPlaceSite.Scroll(NativeMethods.tagSIZE scrollExtant) { + int UnsafeNativeMethods.IOleInPlaceSite.Scroll(NativeMethods.tagSIZE scrollExtant) + { return NativeMethods.S_FALSE; } - int UnsafeNativeMethods.IOleInPlaceSite.OnUIDeactivate(int fUndoable) { + int UnsafeNativeMethods.IOleInPlaceSite.OnUIDeactivate(int fUndoable) + { this.Host.GetParentContainer().OnUIDeactivate(this.Host); - if (this.Host.ActiveXState > WebBrowserHelper.AXState.InPlaceActive) { + if (this.Host.ActiveXState > WebBrowserHelper.AXState.InPlaceActive) + { this.Host.ActiveXState = WebBrowserHelper.AXState.InPlaceActive; } return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleInPlaceSite.OnInPlaceDeactivate() { - if (this.Host.ActiveXState == WebBrowserHelper.AXState.UIActive) { + int UnsafeNativeMethods.IOleInPlaceSite.OnInPlaceDeactivate() + { + if (this.Host.ActiveXState == WebBrowserHelper.AXState.UIActive) + { ((UnsafeNativeMethods.IOleInPlaceSite)this).OnUIDeactivate(0); } @@ -275,33 +320,39 @@ int UnsafeNativeMethods.IOleInPlaceSite.OnInPlaceDeactivate() { return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleInPlaceSite.DiscardUndoState() { + int UnsafeNativeMethods.IOleInPlaceSite.DiscardUndoState() + { return NativeMethods.S_OK; } - int UnsafeNativeMethods.IOleInPlaceSite.DeactivateAndUndo() { + int UnsafeNativeMethods.IOleInPlaceSite.DeactivateAndUndo() + { return this.Host.AXInPlaceObject.UIDeactivate(); } - int UnsafeNativeMethods.IOleInPlaceSite.OnPosRectChange(NativeMethods.COMRECT lprcPosRect) { + int UnsafeNativeMethods.IOleInPlaceSite.OnPosRectChange(NativeMethods.COMRECT lprcPosRect) + { return this.OnActiveXRectChange(lprcPosRect); } // // ISimpleFrameSite methods: // - int UnsafeNativeMethods.ISimpleFrameSite.PreMessageFilter(IntPtr hwnd, int msg, IntPtr wp, IntPtr lp, ref IntPtr plResult, ref int pdwCookie) { + int UnsafeNativeMethods.ISimpleFrameSite.PreMessageFilter(IntPtr hwnd, int msg, IntPtr wp, IntPtr lp, ref IntPtr plResult, ref int pdwCookie) + { return NativeMethods.S_OK; } - int UnsafeNativeMethods.ISimpleFrameSite.PostMessageFilter(IntPtr hwnd, int msg, IntPtr wp, IntPtr lp, ref IntPtr plResult, int dwCookie) { + int UnsafeNativeMethods.ISimpleFrameSite.PostMessageFilter(IntPtr hwnd, int msg, IntPtr wp, IntPtr lp, ref IntPtr plResult, int dwCookie) + { return NativeMethods.S_FALSE; } // // IPropertyNotifySink methods: // - void UnsafeNativeMethods.IPropertyNotifySink.OnChanged(int dispid) { + void UnsafeNativeMethods.IPropertyNotifySink.OnChanged(int dispid) + { // Some controls fire OnChanged() notifications when getting values of some properties. // To prevent this kind of recursion, we check to see if we are already inside a OnChanged() call. // @@ -318,12 +369,14 @@ void UnsafeNativeMethods.IPropertyNotifySink.OnChanged(int dispid) { Debug.Fail(t.ToString()); throw; } - finally { + finally + { this.Host.NoComponentChangeEvents--; } } - int UnsafeNativeMethods.IPropertyNotifySink.OnRequestEdit(int dispid) { + int UnsafeNativeMethods.IPropertyNotifySink.OnRequestEdit(int dispid) + { return NativeMethods.S_OK; } @@ -331,7 +384,8 @@ int UnsafeNativeMethods.IPropertyNotifySink.OnRequestEdit(int dispid) { // // Virtual overrides: // - internal virtual void OnPropertyChanged(int dispid) { + internal virtual void OnPropertyChanged(int dispid) + { try { ISite site = this.Host.Site; @@ -371,16 +425,19 @@ internal virtual void OnPropertyChanged(int dispid) { // // Internal helper methods: // - internal WebBrowserBase GetAXHost() { + internal WebBrowserBase GetAXHost() + { return this.Host; } - internal void StartEvents() { + internal void StartEvents() + { if (connectionPoint != null) return; object nativeObject = this.Host.activeXInstance; - if (nativeObject != null) { + if (nativeObject != null) + { try { connectionPoint = new AxHost.ConnectionPointCookie(nativeObject, this, typeof(UnsafeNativeMethods.IPropertyNotifySink)); @@ -395,14 +452,17 @@ internal void StartEvents() { } } - internal void StopEvents() { - if (connectionPoint != null) { + internal void StopEvents() + { + if (connectionPoint != null) + { connectionPoint.Disconnect(); connectionPoint = null; } } - private int OnActiveXRectChange(NativeMethods.COMRECT lprcPosRect) { + private int OnActiveXRectChange(NativeMethods.COMRECT lprcPosRect) + { this.Host.AXInPlaceObject.SetObjectRects( NativeMethods.COMRECT.FromXYWH(0, 0, lprcPosRect.right - lprcPosRect.left, lprcPosRect.bottom - lprcPosRect.top), WebBrowserHelper.GetClipRect()); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserUriTypeConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserUriTypeConverter.cs index c9fea0778c4..32071b5d4fc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserUriTypeConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserUriTypeConverter.cs @@ -5,9 +5,9 @@ using System; using System.ComponentModel; -namespace System.Windows.Forms +namespace System.Windows.Forms { - class WebBrowserUriTypeConverter : UriTypeConverter + class WebBrowserUriTypeConverter : UriTypeConverter { public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { @@ -16,17 +16,17 @@ public override object ConvertFrom(ITypeDescriptorContext context, System.Global Uri uri = base.ConvertFrom(context, culture, value) as Uri; if (uri != null && !string.IsNullOrEmpty(uri.OriginalString) && !uri.IsAbsoluteUri) { - try + try { uri = new Uri("http://" + uri.OriginalString.Trim()); } - catch (UriFormatException) + catch (UriFormatException) { //We can't throw "http://" on the front: just return the original (relative) Uri, //which will throw an exception with reasonable text later. } } return uri; - } + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WinCategoryAttribute.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WinCategoryAttribute.cs index 17e8b9b24a8..ce3ddc910b7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WinCategoryAttribute.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WinCategoryAttribute.cs @@ -3,10 +3,11 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { - +namespace System.Windows.Forms +{ + using System; - using System.ComponentModel; + using System.ComponentModel; using System.Diagnostics; /// @@ -15,14 +16,16 @@ namespace System.Windows.Forms { /// /// [AttributeUsage(AttributeTargets.All)] - internal sealed class WinCategoryAttribute : CategoryAttribute { + internal sealed class WinCategoryAttribute : CategoryAttribute + { /// /// /// Initializes a new instance of the class. /// /// - public WinCategoryAttribute(string category) : base(category) { + public WinCategoryAttribute(string category) : base(category) + { } /// @@ -33,9 +36,11 @@ public WinCategoryAttribute(string category) : base(category) { /// available for the given value, the method should return it. /// Otherwise, it should return null. /// - protected override string GetLocalizedString(string value) { + protected override string GetLocalizedString(string value) + { string localizedValue = base.GetLocalizedString(value); - if (localizedValue == null) { + if (localizedValue == null) + { localizedValue = (string)GetSRObject("WinFormsCategory" + value); } // This attribute is internal, and we should never have a missing resource string. @@ -47,7 +52,8 @@ protected override string GetLocalizedString(string value) { private static object GetSRObject(string name) { object resourceObject = null; - try { resourceObject = SR.ResourceManager.GetObject(name); } + try + { resourceObject = SR.ResourceManager.GetObject(name); } catch (System.Resources.MissingManifestResourceException) { } return resourceObject; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WinFormsUtils.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WinFormsUtils.cs index 07a4f99f113..ca3edba0cdb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WinFormsUtils.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WinFormsUtils.cs @@ -188,7 +188,7 @@ internal static string GetControlInformation(IntPtr hwnd) else { nameOfControl += "Unknown"; - + // Add some extra debug info for ToolStripDropDowns. if (c is ToolStripDropDown dd && dd.OwnerItem != null) { @@ -428,7 +428,7 @@ public bool MoveNext() _current++; return true; } - + return false; } @@ -531,7 +531,7 @@ public override void Add(Control value) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, string.Format(SR.TypedControlCollectionShouldBeOfType, _typeOfControl.Name)), value.GetType().Name); } - + base.Add(value); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WindowsFormsSectionHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WindowsFormsSectionHandler.cs index 8a900d722b6..d23268a5ea8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WindowsFormsSectionHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WindowsFormsSectionHandler.cs @@ -2,26 +2,31 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.WindowsFormsSectionHandler..ctor()")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.WindowsFormsSectionHandler..ctor()")] -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.Diagnostics; using System.Configuration; - public sealed class WindowsFormsSection : ConfigurationSection { - internal const bool JitDebuggingDefault = false; + public sealed class WindowsFormsSection : ConfigurationSection + { + internal const bool JitDebuggingDefault = false; - private static ConfigurationPropertyCollection s_properties; - private static ConfigurationProperty s_propJitDebugging; + private static ConfigurationPropertyCollection s_properties; + private static ConfigurationProperty s_propJitDebugging; - internal static WindowsFormsSection GetSection() { + internal static WindowsFormsSection GetSection() + { WindowsFormsSection section = null; - try { - section = (WindowsFormsSection) System.Configuration.ConfigurationManager.GetSection("system.windows.forms") ?? new WindowsFormsSection(); + try + { + section = (WindowsFormsSection)System.Configuration.ConfigurationManager.GetSection("system.windows.forms") ?? new WindowsFormsSection(); } - catch { + catch + { Debug.Fail("Exception loading config for windows forms"); section = new WindowsFormsSection(); } @@ -29,8 +34,10 @@ internal static WindowsFormsSection GetSection() { return section; } - private static ConfigurationPropertyCollection EnsureStaticPropertyBag() { - if (s_properties == null) { + private static ConfigurationPropertyCollection EnsureStaticPropertyBag() + { + if (s_properties == null) + { s_propJitDebugging = new ConfigurationProperty("jitDebugging", typeof(bool), JitDebuggingDefault, ConfigurationPropertyOptions.None); ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection(); @@ -41,23 +48,29 @@ private static ConfigurationPropertyCollection EnsureStaticPropertyBag() { return s_properties; } - public WindowsFormsSection() { + public WindowsFormsSection() + { EnsureStaticPropertyBag(); } - protected override ConfigurationPropertyCollection Properties { - get { + protected override ConfigurationPropertyCollection Properties + { + get + { return EnsureStaticPropertyBag(); } } - [ConfigurationProperty("jitDebugging", DefaultValue=JitDebuggingDefault)] - public bool JitDebugging { - get { - return (bool) base[s_propJitDebugging]; + [ConfigurationProperty("jitDebugging", DefaultValue = JitDebuggingDefault)] + public bool JitDebugging + { + get + { + return (bool)base[s_propJitDebugging]; } - set { + set + { base[s_propJitDebugging] = value; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WindowsFormsSynchronizationContext.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WindowsFormsSynchronizationContext.cs index b427bb6636c..f1df61e4b35 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WindowsFormsSynchronizationContext.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WindowsFormsSynchronizationContext.cs @@ -13,7 +13,8 @@ namespace System.Windows.Forms /// /// SynchronizationContext subclass used by the Windows Forms package. /// - public sealed class WindowsFormsSynchronizationContext : SynchronizationContext, IDisposable { + public sealed class WindowsFormsSynchronizationContext : SynchronizationContext, IDisposable + { private Control controlToSendTo; private WeakReference destinationThreadRef; @@ -28,39 +29,50 @@ public sealed class WindowsFormsSynchronizationContext : SynchronizationContext, private static SynchronizationContext previousSyncContext; - public WindowsFormsSynchronizationContext() { + public WindowsFormsSynchronizationContext() + { DestinationThread = Thread.CurrentThread; //store the current thread to ensure its still alive during an invoke. Application.ThreadContext context = Application.ThreadContext.FromCurrent(); Debug.Assert(context != null); - if (context != null) { - controlToSendTo = context.MarshalingControl; + if (context != null) + { + controlToSendTo = context.MarshalingControl; } Debug.Assert(controlToSendTo.IsHandleCreated, "Marshaling control should have created its handle in its ctor."); } - private WindowsFormsSynchronizationContext(Control marshalingControl, Thread destinationThread) { + private WindowsFormsSynchronizationContext(Control marshalingControl, Thread destinationThread) + { controlToSendTo = marshalingControl; this.DestinationThread = destinationThread; Debug.Assert(controlToSendTo.IsHandleCreated, "Marshaling control should have created its handle in its ctor."); } // Directly holding onto the Thread can prevent ThreadStatics from finalizing. - private Thread DestinationThread { - get { - if ((destinationThreadRef != null) && (destinationThreadRef.IsAlive)) { + private Thread DestinationThread + { + get + { + if ((destinationThreadRef != null) && (destinationThreadRef.IsAlive)) + { return destinationThreadRef.Target as Thread; } return null; } - set { - if (value != null) { + set + { + if (value != null) + { destinationThreadRef = new WeakReference(value); } } } - public void Dispose() { - if (controlToSendTo != null) { - if (!controlToSendTo.IsDisposed) { + public void Dispose() + { + if (controlToSendTo != null) + { + if (!controlToSendTo.IsDisposed) + { controlToSendTo.Dispose(); } controlToSendTo = null; @@ -68,97 +80,122 @@ public void Dispose() { } // This is never called because we decide whether to Send or Post and we always post - public override void Send(SendOrPostCallback d, object state) { + public override void Send(SendOrPostCallback d, object state) + { Thread destinationThread = DestinationThread; - if (destinationThread == null || !destinationThread.IsAlive) { + if (destinationThread == null || !destinationThread.IsAlive) + { throw new InvalidAsynchronousStateException(SR.ThreadNoLongerValid); } Debug.Assert(controlToSendTo != null, "Should always have the marshaling control by this point"); - if (controlToSendTo != null) { + if (controlToSendTo != null) + { controlToSendTo.Invoke(d, new object[] { state }); } } - public override void Post(SendOrPostCallback d, object state) { + public override void Post(SendOrPostCallback d, object state) + { Debug.Assert(controlToSendTo != null, "Should always have the marshaling control by this point"); - if (controlToSendTo != null) { + if (controlToSendTo != null) + { controlToSendTo.BeginInvoke(d, new object[] { state }); } } - public override SynchronizationContext CreateCopy() { + public override SynchronizationContext CreateCopy() + { return new WindowsFormsSynchronizationContext(controlToSendTo, DestinationThread); } // Determines whether we install the WindowsFormsSynchronizationContext when we create a control, or // when we start a message loop. Default: true. [EditorBrowsable(EditorBrowsableState.Advanced)] - public static bool AutoInstall { - get { + public static bool AutoInstall + { + get + { return !dontAutoInstall; } - set { + set + { dontAutoInstall = !value; } } // Instantiate and install a WF op sync context, and save off the old one. - internal static void InstallIfNeeded() { + internal static void InstallIfNeeded() + { // Exit if we shouldn't auto-install, if we've already installed and we haven't uninstalled, // or if we're being called recursively (creating the WF // async op sync context can create a parking window control). - if (!AutoInstall || inSyncContextInstallation) { + if (!AutoInstall || inSyncContextInstallation) + { return; } - if (SynchronizationContext.Current == null) { + if (SynchronizationContext.Current == null) + { previousSyncContext = null; } - if (previousSyncContext != null) { + if (previousSyncContext != null) + { return; } inSyncContextInstallation = true; - try { + try + { SynchronizationContext currentContext = AsyncOperationManager.SynchronizationContext; //Make sure we either have no sync context or that we have one of type SynchronizationContext - if (currentContext == null || currentContext.GetType() == typeof(SynchronizationContext)) { + if (currentContext == null || currentContext.GetType() == typeof(SynchronizationContext)) + { previousSyncContext = currentContext; AsyncOperationManager.SynchronizationContext = new WindowsFormsSynchronizationContext(); } } - finally { + finally + { inSyncContextInstallation = false; } } - public static void Uninstall() { + public static void Uninstall() + { Uninstall(true); } - internal static void Uninstall(bool turnOffAutoInstall) { - if (AutoInstall) { + internal static void Uninstall(bool turnOffAutoInstall) + { + if (AutoInstall) + { WindowsFormsSynchronizationContext winFormsSyncContext = AsyncOperationManager.SynchronizationContext as WindowsFormsSynchronizationContext; - if (winFormsSyncContext != null) { - try { - if (previousSyncContext == null) { + if (winFormsSyncContext != null) + { + try + { + if (previousSyncContext == null) + { AsyncOperationManager.SynchronizationContext = new SynchronizationContext(); } - else { + else + { AsyncOperationManager.SynchronizationContext = previousSyncContext; } } - finally { + finally + { previousSyncContext = null; } } } - if (turnOffAutoInstall) { + if (turnOffAutoInstall) + { AutoInstall = false; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs b/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs index f3b7493ad9b..bb8084a43f0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs @@ -62,51 +62,59 @@ public partial class Control : /// /// The ImeMode in the property store. /// - internal ImeMode CachedImeMode { - get { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_CachedImeMode(), this = " + this ); + internal ImeMode CachedImeMode + { + get + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_CachedImeMode(), this = " + this); Debug.Indent(); // Get the ImeMode from the property store // bool found; - ImeMode cachedImeMode = (ImeMode) Properties.GetInteger( PropImeMode, out found ); - if( !found ) { + ImeMode cachedImeMode = (ImeMode)Properties.GetInteger(PropImeMode, out found); + if (!found) + { cachedImeMode = DefaultImeMode; - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "using DefaultImeMode == " + cachedImeMode ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "using DefaultImeMode == " + cachedImeMode); } - else { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "using property store ImeMode == " + cachedImeMode ); + else + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "using property store ImeMode == " + cachedImeMode); } // If inherited, get the mode from this control's parent // - if( cachedImeMode == ImeMode.Inherit ) { + if (cachedImeMode == ImeMode.Inherit) + { Control parent = ParentInternal; - if( parent != null ) { + if (parent != null) + { cachedImeMode = parent.CachedImeMode; - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "inherited from parent = " + parent.GetType() ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "inherited from parent = " + parent.GetType()); } - else { + else + { cachedImeMode = ImeMode.NoControl; } } - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "returning CachedImeMode == " + cachedImeMode ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "returning CachedImeMode == " + cachedImeMode); Debug.Unindent(); return cachedImeMode; } - set { + set + { // When the control is in restricted mode (!CanEnableIme) the CachedImeMode should be changed only programatically, // calls generated by user interaction should be wrapped with a check for CanEnableIme. - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside set_CachedImeMode(), this = " + this ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside set_CachedImeMode(), this = " + this); Debug.Indent(); - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Warning, "Setting cached Ime == " + value ); - Properties.SetInteger( PropImeMode, (int) value ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Warning, "Setting cached Ime == " + value); + Properties.SetInteger(PropImeMode, (int)value); Debug.Unindent(); } @@ -117,12 +125,14 @@ internal ImeMode CachedImeMode { /// Added to support Password & ReadOnly (and maybe other) properties, which when set, should force disabling /// the IME if using one. /// - protected virtual bool CanEnableIme { - get { + protected virtual bool CanEnableIme + { + get + { // Note: If overriding this property make sure to add the Debug tracing code and call this method (base.CanEnableIme). Debug.Indent(); - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, string.Format(CultureInfo.CurrentCulture, "Inside get_CanEnableIme(), value = {0}, this = {1}", ImeSupported, this ) ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, string.Format(CultureInfo.CurrentCulture, "Inside get_CanEnableIme(), value = {0}, this = {1}", ImeSupported, this)); Debug.Unindent(); return ImeSupported; @@ -132,14 +142,18 @@ protected virtual bool CanEnableIme { /// /// Gets the current IME context mode. If no IME associated, ImeMode.Inherit is returned. /// - internal ImeMode CurrentImeContextMode { - get { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_CurrentImeContextMode(), this = " + this ); + internal ImeMode CurrentImeContextMode + { + get + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_CurrentImeContextMode(), this = " + this); - if( this.IsHandleCreated ) { - return ImeContext.GetImeMode( this.Handle ); + if (this.IsHandleCreated) + { + return ImeContext.GetImeMode(this.Handle); } - else { + else + { // window is not yet created hence no IME associated yet. return ImeMode.Inherit; } @@ -148,7 +162,8 @@ internal ImeMode CurrentImeContextMode { /// /// - protected virtual ImeMode DefaultImeMode { + protected virtual ImeMode DefaultImeMode + { get { return ImeMode.Inherit; } } @@ -156,22 +171,25 @@ protected virtual ImeMode DefaultImeMode { /// Flag used to avoid re-entrancy during WM_IME_NOTFIY message processing - see WmImeNotify(). /// Also to avoid raising the ImeModeChanged event more than once during the process of changing the ImeMode. /// - internal int DisableImeModeChangedCount { - get { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_DisableImeModeChangedCount()" ); + internal int DisableImeModeChangedCount + { + get + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_DisableImeModeChangedCount()"); Debug.Indent(); bool dummy; - int val = (int) Properties.GetInteger( PropDisableImeModeChangedCount, out dummy ); + int val = (int)Properties.GetInteger(PropDisableImeModeChangedCount, out dummy); - Debug.Assert( val >= 0, "Counter underflow." ); - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Value: " + val ); + Debug.Assert(val >= 0, "Counter underflow."); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Value: " + val); Debug.Unindent(); return val; } - set { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside set_DisableImeModeChangedCount(): " + value ); + set + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside set_DisableImeModeChangedCount(): " + value); Properties.SetInteger(PropDisableImeModeChangedCount, value); } } @@ -180,8 +198,10 @@ internal int DisableImeModeChangedCount { /// Flag used to prevent setting ImeMode in focused control when losing focus and hosted in a non-Form shell. /// See WmImeKillFocus() for more info. /// - private static bool IgnoreWmImeNotify { - get { + private static bool IgnoreWmImeNotify + { + get + { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_IgnoreWmImeNotify()"); Debug.Indent(); @@ -192,7 +212,8 @@ private static bool IgnoreWmImeNotify { return val; } - set { + set + { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside set_IgnoreWmImeNotify(): " + value); Control.ignoreWmImeNotify = value; } @@ -203,13 +224,15 @@ private static bool IgnoreWmImeNotify { /// object when that object is selected. /// [ - SRCategory( nameof(SR.CatBehavior)), - Localizable( true ), - AmbientValue( ImeMode.Inherit ), - SRDescription( nameof(SR.ControlIMEModeDescr)) + SRCategory(nameof(SR.CatBehavior)), + Localizable(true), + AmbientValue(ImeMode.Inherit), + SRDescription(nameof(SR.ControlIMEModeDescr)) ] - public ImeMode ImeMode { - get { + public ImeMode ImeMode + { + get + { ImeMode imeMode = ImeModeBase; if (imeMode == ImeMode.OnHalf) // This is for compatibility. See QFE#4448. @@ -219,7 +242,8 @@ public ImeMode ImeMode { return imeMode; } - set { + set + { ImeModeBase = value; } } @@ -228,60 +252,71 @@ public ImeMode ImeMode { /// Internal version of ImeMode property. This is provided for controls that override CanEnableIme and that /// return ImeMode.Disable for the ImeMode property when CanEnableIme is false - See TextBoxBase controls. /// - protected virtual ImeMode ImeModeBase { - get { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_ImeModeBase(), this = " + this ); - Debug.Indent(); - + protected virtual ImeMode ImeModeBase + { + get + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_ImeModeBase(), this = " + this); + Debug.Indent(); + ImeMode imeMode = CachedImeMode; - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Value = " + imeMode ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Value = " + imeMode); Debug.Unindent(); return imeMode; } - set { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, string.Format( CultureInfo.CurrentCulture, "Inside set_ImeModeBase({0}), this = {1}", value, this ) ); - Debug.Indent(); - + set + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, string.Format(CultureInfo.CurrentCulture, "Inside set_ImeModeBase({0}), this = {1}", value, this)); + Debug.Indent(); + //valid values are -1 to 0xb - if( !ClientUtils.IsEnumValid( value, (int) value, (int) ImeMode.Inherit, (int) ImeMode.OnHalf ) ) { - throw new InvalidEnumArgumentException( "ImeMode", (int) value, typeof( ImeMode ) ); + if (!ClientUtils.IsEnumValid(value, (int)value, (int)ImeMode.Inherit, (int)ImeMode.OnHalf)) + { + throw new InvalidEnumArgumentException("ImeMode", (int)value, typeof(ImeMode)); } ImeMode oldImeMode = CachedImeMode; CachedImeMode = value; - if( oldImeMode != value ) { + if (oldImeMode != value) + { // Cache current value to determine whether we need to raise the ImeModeChanged. Control ctl = null; - if( !DesignMode && ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable ) { + if (!DesignMode && ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable) + { // Set the context to the new value if control is focused. - if( Focused ) { + if (Focused) + { ctl = this; } - else if( ContainsFocus ) { + else if (ContainsFocus) + { ctl = FromChildHandle(UnsafeNativeMethods.GetFocus()); } - if( ctl != null && ctl.CanEnableIme ) { + if (ctl != null && ctl.CanEnableIme) + { // Block ImeModeChanged since we are checking for it below. DisableImeModeChangedCount++; - try { + try + { ctl.UpdateImeContextMode(); } - finally { + finally + { DisableImeModeChangedCount--; } } } - VerifyImeModeChanged( oldImeMode, CachedImeMode ); + VerifyImeModeChanged(oldImeMode, CachedImeMode); } - - ImeContext.TraceImeStatus( this ); + + ImeContext.TraceImeStatus(this); Debug.Unindent(); } } @@ -289,40 +324,47 @@ protected virtual ImeMode ImeModeBase { /// /// Determines whether the Control supports IME handling by default. /// - private bool ImeSupported { - get { + private bool ImeSupported + { + get + { return DefaultImeMode != ImeMode.Disable; } } - [WinCategory( "Behavior" ), SRDescription( nameof(SR.ControlOnImeModeChangedDescr) )] - public event EventHandler ImeModeChanged { - add => Events.AddHandler( EventImeModeChanged, value ); - remove => Events.RemoveHandler( EventImeModeChanged, value ); + [WinCategory("Behavior"), SRDescription(nameof(SR.ControlOnImeModeChangedDescr))] + public event EventHandler ImeModeChanged + { + add => Events.AddHandler(EventImeModeChanged, value); + remove => Events.RemoveHandler(EventImeModeChanged, value); } /// /// Returns the current number of WM_CHAR messages to ignore after processing corresponding WM_IME_CHAR msgs. /// - internal int ImeWmCharsToIgnore { + internal int ImeWmCharsToIgnore + { // The IME sends WM_IME_CHAR messages for each character in the composition string, and then // after all messages are sent, corresponding WM_CHAR messages are also sent. (in non-unicode // windows two WM_CHAR messages are sent per char in the IME). We need to keep a counter // not to process each character twice or more. - get { - return Properties.GetInteger( PropImeWmCharsToIgnore ); + get + { + return Properties.GetInteger(PropImeWmCharsToIgnore); } - set { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, string.Format( CultureInfo.CurrentCulture, "Inside set_ImeWmCharToIgnore(value={0}), this = {1}", value, this ) ); + set + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, string.Format(CultureInfo.CurrentCulture, "Inside set_ImeWmCharToIgnore(value={0}), this = {1}", value, this)); Debug.Indent(); // WM_CHAR is not send after WM_IME_CHAR when the composition has been closed by either, changing the conversion mode or // dissasociating the IME (for instance when loosing focus and conversion is forced to complete). - if( ImeWmCharsToIgnore != ImeCharsToIgnoreDisabled ) { - Properties.SetInteger( PropImeWmCharsToIgnore, value ); + if (ImeWmCharsToIgnore != ImeCharsToIgnoreDisabled) + { + Properties.SetInteger(PropImeWmCharsToIgnore, value); } - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImeWmCharsToIgnore on leaving setter: " + ImeWmCharsToIgnore ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImeWmCharsToIgnore on leaving setter: " + ImeWmCharsToIgnore); Debug.Unindent(); } } @@ -332,29 +374,34 @@ internal int ImeWmCharsToIgnore { /// This is used by controls that implement some sort of IME restriction mode (like TextBox on Password/ReadOnly mode). /// See the VerifyImeRestrictedModeChanged() method. /// - private bool LastCanEnableIme { - get { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_LastCanEnableIme()" ); + private bool LastCanEnableIme + { + get + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_LastCanEnableIme()"); Debug.Indent(); bool valueFound; - int val = (int) Properties.GetInteger( PropLastCanEnableIme, out valueFound ); + int val = (int)Properties.GetInteger(PropLastCanEnableIme, out valueFound); - if( valueFound ) { + if (valueFound) + { valueFound = val == 1; } - else { + else + { valueFound = true; } - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Value: " + valueFound ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Value: " + valueFound); Debug.Unindent(); return valueFound; } - set { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside set_LastCanEnableIme(): " + value ); - Properties.SetInteger( PropLastCanEnableIme, value ? 1 : 0 ); + set + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside set_LastCanEnableIme(): " + value); + Properties.SetInteger(PropLastCanEnableIme, value ? 1 : 0); } } @@ -363,28 +410,34 @@ private bool LastCanEnableIme { /// only by user interaction and is required to set the IME context appropriately while keeping the ImeMode property /// unchanged. /// - protected static ImeMode PropagatingImeMode { - get { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_PropagatingImeMode()" ); + protected static ImeMode PropagatingImeMode + { + get + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_PropagatingImeMode()"); Debug.Indent(); - if( Control.propagatingImeMode == ImeMode.Inherit ) { + if (Control.propagatingImeMode == ImeMode.Inherit) + { // Initialize the propagating IME mode to the value the IME associated to the focused window currently has, // this enables propagating the IME mode from/to unmanaged applications hosting winforms controls. - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "Initializing PropagatingImeMode" ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "Initializing PropagatingImeMode"); ImeMode imeMode = ImeMode.Inherit; IntPtr focusHandle = UnsafeNativeMethods.GetFocus(); - if( focusHandle != IntPtr.Zero ) { + if (focusHandle != IntPtr.Zero) + { imeMode = ImeContext.GetImeMode(focusHandle); // If focused control is disabled we won't be able to get the app ime context mode, try the top window. // this is the case of a disabled winforms control hosted in a non-Form shell. - if( imeMode == ImeMode.Disable ) { + if (imeMode == ImeMode.Disable) + { focusHandle = UnsafeNativeMethods.GetAncestor(new HandleRef(null, focusHandle), NativeMethods.GA_ROOT); - if( focusHandle != IntPtr.Zero ) { + if (focusHandle != IntPtr.Zero) + { imeMode = ImeContext.GetImeMode(focusHandle); } } @@ -394,17 +447,20 @@ protected static ImeMode PropagatingImeMode { PropagatingImeMode = imeMode; } - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "Value: " + Control.propagatingImeMode ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "Value: " + Control.propagatingImeMode); Debug.Unindent(); return Control.propagatingImeMode; } - private set { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside set_PropagatingImeMode()" ); + private set + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside set_PropagatingImeMode()"); Debug.Indent(); - if (Control.propagatingImeMode != value) { - switch( value ) { + if (Control.propagatingImeMode != value) + { + switch (value) + { case ImeMode.NoControl: case ImeMode.Disable: // Cannot set propagating ImeMode to one of these values. @@ -412,9 +468,9 @@ private set { return; default: - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Warning, string.Format( CultureInfo.CurrentCulture, "Setting PropagatingImeMode: Current value = {0}, New value = {1}", propagatingImeMode, value ) ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Warning, string.Format(CultureInfo.CurrentCulture, "Setting PropagatingImeMode: Current value = {0}, New value = {1}", propagatingImeMode, value)); Control.propagatingImeMode = value; - break; + break; } } @@ -426,13 +482,15 @@ private set { /// Sets the IME context to the appropriate ImeMode according to the control's ImeMode state. /// This method is commonly used when attaching the IME to the control's window. /// - internal void UpdateImeContextMode() { + internal void UpdateImeContextMode() + { ImeMode[] inputLanguageTable = ImeModeConversion.InputLanguageTable; - if (!DesignMode && (inputLanguageTable != ImeModeConversion.UnsupportedTable) && Focused) { + if (!DesignMode && (inputLanguageTable != ImeModeConversion.UnsupportedTable) && Focused) + { // Note: CHN IME won't send WM_IME_NOTIFY msg when getting associated, setting the IME context mode // forces the message to be sent as a side effect. - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside UpdateImeContextMode(), this = " + this ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside UpdateImeContextMode(), this = " + this); Debug.Indent(); // If the value is not supported by the Ime, it will be mapped to a corresponding one, we need @@ -441,12 +499,14 @@ internal void UpdateImeContextMode() { ImeMode newImeContextMode = ImeMode.Disable; ImeMode currentImeMode = CachedImeMode; - if( ImeSupported && CanEnableIme ) { + if (ImeSupported && CanEnableIme) + { newImeContextMode = currentImeMode == ImeMode.NoControl ? PropagatingImeMode : currentImeMode; } // If PropagatingImeMode has not been initialized it will return ImeMode.Inherit above, need to check newImeContextMode for this. - if (CurrentImeContextMode != newImeContextMode && newImeContextMode != ImeMode.Inherit) { + if (CurrentImeContextMode != newImeContextMode && newImeContextMode != ImeMode.Inherit) + { // If the context changes the window will receive one or more WM_IME_NOTIFY messages and as part of its // processing it will raise the ImeModeChanged event if needed. We need to prevent the event from been // raised here from here. @@ -459,35 +519,42 @@ internal void UpdateImeContextMode() { // before setting the IME context to the control's ImeMode value which could be different from the propagating value. ImeMode savedPropagatingImeMode = PropagatingImeMode; - try { - ImeContext.SetImeStatus( newImeContextMode, this.Handle ); + try + { + ImeContext.SetImeStatus(newImeContextMode, this.Handle); } - finally { + finally + { DisableImeModeChangedCount--; - if (newImeContextMode == ImeMode.Disable && inputLanguageTable == ImeModeConversion.ChineseTable) { + if (newImeContextMode == ImeMode.Disable && inputLanguageTable == ImeModeConversion.ChineseTable) + { // Restore saved propagating mode. PropagatingImeMode = savedPropagatingImeMode; } } // Get mapped value from the context. - if( currentImeMode == ImeMode.NoControl ) { - if( CanEnableIme ) { + if (currentImeMode == ImeMode.NoControl) + { + if (CanEnableIme) + { PropagatingImeMode = CurrentImeContextMode; } } - else { - if( CanEnableIme ) { + else + { + if (CanEnableIme) + { CachedImeMode = CurrentImeContextMode; } // Need to raise the ImeModeChanged event? - VerifyImeModeChanged( newImeContextMode, CachedImeMode ); + VerifyImeModeChanged(newImeContextMode, CachedImeMode); } } - ImeContext.TraceImeStatus( this ); + ImeContext.TraceImeStatus(this); Debug.Unindent(); } } @@ -495,13 +562,16 @@ internal void UpdateImeContextMode() { /// /// Checks if specified ImeMode values are different and raise the event if true. /// - private void VerifyImeModeChanged( ImeMode oldMode, ImeMode newMode ) { - if( ImeSupported && (DisableImeModeChangedCount == 0) && (newMode != ImeMode.NoControl) ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, string.Format( CultureInfo.CurrentCulture, "Inside VerifyImeModeChanged(oldMode={0}, newMode={1}), this = {2}", oldMode, newMode, this ) ); + private void VerifyImeModeChanged(ImeMode oldMode, ImeMode newMode) + { + if (ImeSupported && (DisableImeModeChangedCount == 0) && (newMode != ImeMode.NoControl)) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, string.Format(CultureInfo.CurrentCulture, "Inside VerifyImeModeChanged(oldMode={0}, newMode={1}), this = {2}", oldMode, newMode, this)); Debug.Indent(); - if( oldMode != newMode ) { - OnImeModeChanged( EventArgs.Empty ); + if (oldMode != newMode) + { + OnImeModeChanged(EventArgs.Empty); } Debug.Unindent(); @@ -512,22 +582,27 @@ private void VerifyImeModeChanged( ImeMode oldMode, ImeMode newMode ) { /// Verifies whether the IME context mode is correct based on the control's Ime restriction mode (CanEnableIme) /// and updates the IME context if needed. /// - internal void VerifyImeRestrictedModeChanged() { - Debug.Assert( ImeSupported, "This method should not be called from controls that don't support IME input." ); + internal void VerifyImeRestrictedModeChanged() + { + Debug.Assert(ImeSupported, "This method should not be called from controls that don't support IME input."); - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside VerifyImeRestrictedModeChanged(), this = " + this ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside VerifyImeRestrictedModeChanged(), this = " + this); Debug.Indent(); bool currentCanEnableIme = this.CanEnableIme; - if( LastCanEnableIme != currentCanEnableIme ) { - if( Focused ) { + if (LastCanEnableIme != currentCanEnableIme) + { + if (Focused) + { // Disable ImeModeChanged from the following call since we'll raise it here if needed. DisableImeModeChangedCount++; - try { + try + { UpdateImeContextMode(); } - finally { + finally + { DisableImeModeChangedCount--; } } @@ -536,14 +611,15 @@ internal void VerifyImeRestrictedModeChanged() { ImeMode oldImeMode = CachedImeMode; ImeMode newImeMode = ImeMode.Disable; - if( currentCanEnableIme ) { + if (currentCanEnableIme) + { // Control is actually getting unrestricted, swap values. newImeMode = oldImeMode; oldImeMode = ImeMode.Disable; } // Do we need to raise the ImeModeChanged event? - VerifyImeModeChanged( oldImeMode, newImeMode ); + VerifyImeModeChanged(oldImeMode, newImeMode); // Finally update the saved CanEnableIme value. LastCanEnableIme = currentCanEnableIme; @@ -557,26 +633,31 @@ internal void VerifyImeRestrictedModeChanged() { /// This method can be used with a child control when the IME mode is more relevant to it than to the control itself, /// for instance ComboBox and its native ListBox/Edit controls. /// - internal void OnImeContextStatusChanged( IntPtr handle ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside OnImeContextStatusChanged(), this = " + this ); + internal void OnImeContextStatusChanged(IntPtr handle) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside OnImeContextStatusChanged(), this = " + this); Debug.Indent(); - Debug.Assert( ImeSupported, "WARNING: Attempting to update ImeMode properties on IME-Unaware control!" ); - Debug.Assert( !DesignMode, "Shouldn't be updating cached ime mode at design-time" ); + Debug.Assert(ImeSupported, "WARNING: Attempting to update ImeMode properties on IME-Unaware control!"); + Debug.Assert(!DesignMode, "Shouldn't be updating cached ime mode at design-time"); - ImeMode fromContext = ImeContext.GetImeMode( handle ); + ImeMode fromContext = ImeContext.GetImeMode(handle); - if( fromContext != ImeMode.Inherit ) { + if (fromContext != ImeMode.Inherit) + { ImeMode oldImeMode = CachedImeMode; - if( CanEnableIme ) { // Cache or Propagating ImeMode should not be updated by interaction when the control is in restricted mode. - if( oldImeMode != ImeMode.NoControl ) { - CachedImeMode = fromContext; // This could end up in the same value due to ImeMode language mapping. + if (CanEnableIme) + { // Cache or Propagating ImeMode should not be updated by interaction when the control is in restricted mode. + if (oldImeMode != ImeMode.NoControl) + { + CachedImeMode = fromContext; // This could end up in the same value due to ImeMode language mapping. - // ImeMode may be changing by user interaction. - VerifyImeModeChanged( oldImeMode, CachedImeMode ); + // ImeMode may be changing by user interaction. + VerifyImeModeChanged(oldImeMode, CachedImeMode); } - else { + else + { PropagatingImeMode = fromContext; } } @@ -589,65 +670,73 @@ internal void OnImeContextStatusChanged( IntPtr handle ) { /// Raises the /// event. /// - protected virtual void OnImeModeChanged( EventArgs e ) { - Debug.Assert( ImeSupported, "ImeModeChanged should not be raised on an Ime-Unaware control." ); - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside OnImeModeChanged(), this = " + this ); - EventHandler handler = (EventHandler) Events[EventImeModeChanged]; - if( handler != null ) handler( this, e ); + protected virtual void OnImeModeChanged(EventArgs e) + { + Debug.Assert(ImeSupported, "ImeModeChanged should not be raised on an Ime-Unaware control."); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside OnImeModeChanged(), this = " + this); + EventHandler handler = (EventHandler)Events[EventImeModeChanged]; + if (handler != null) + handler(this, e); } /// /// Resets the Ime mode. /// - [EditorBrowsable( EditorBrowsableState.Never )] - public void ResetImeMode() { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside ResetImeMode(), this = " + this ); + [EditorBrowsable(EditorBrowsableState.Never)] + public void ResetImeMode() + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside ResetImeMode(), this = " + this); ImeMode = DefaultImeMode; } /// /// Returns true if the ImeMode should be persisted in code gen. /// - [EditorBrowsable( EditorBrowsableState.Never )] - internal virtual bool ShouldSerializeImeMode() { + [EditorBrowsable(EditorBrowsableState.Never)] + internal virtual bool ShouldSerializeImeMode() + { // This method is for designer support. If the ImeMode has not been changed or it is the same as the // default value it should not be serialized. bool found; - int imeMode = Properties.GetInteger( PropImeMode, out found ); + int imeMode = Properties.GetInteger(PropImeMode, out found); - return ( found && imeMode != (int) DefaultImeMode ); + return (found && imeMode != (int)DefaultImeMode); } /// /// Handles the WM_INPUTLANGCHANGE message /// - private void WmInputLangChange( ref Message m ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside WmInputLangChange(), this = " + this ); + private void WmInputLangChange(ref Message m) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside WmInputLangChange(), this = " + this); Debug.Indent(); // Make sure the IME context is associated with the correct (mapped) mode. UpdateImeContextMode(); // If detaching IME (setting to English) reset propagating IME mode so when reattaching the IME is set to direct input again. - if( ImeModeConversion.InputLanguageTable == ImeModeConversion.UnsupportedTable ) { + if (ImeModeConversion.InputLanguageTable == ImeModeConversion.UnsupportedTable) + { PropagatingImeMode = ImeMode.Off; } - if( ImeModeConversion.InputLanguageTable == ImeModeConversion.ChineseTable ) { + if (ImeModeConversion.InputLanguageTable == ImeModeConversion.ChineseTable) + { IgnoreWmImeNotify = false; } Form form = FindForm(); - if( form != null ) { - InputLanguageChangedEventArgs e = InputLanguage.CreateInputLanguageChangedEventArgs( m ); - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Culture=" + e.Culture ); - form.PerformOnInputLanguageChanged( e ); + if (form != null) + { + InputLanguageChangedEventArgs e = InputLanguage.CreateInputLanguageChangedEventArgs(m); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Culture=" + e.Culture); + form.PerformOnInputLanguageChanged(e); } - DefWndProc( ref m ); + DefWndProc(ref m); - ImeContext.TraceImeStatus( this ); + ImeContext.TraceImeStatus(this); Debug.Unindent(); } @@ -655,22 +744,26 @@ private void WmInputLangChange( ref Message m ) { /// /// Handles the WM_INPUTLANGCHANGEREQUEST message /// - private void WmInputLangChangeRequest( ref Message m ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside WmInputLangChangeRequest(), this=" + this ); + private void WmInputLangChangeRequest(ref Message m) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside WmInputLangChangeRequest(), this=" + this); Debug.Indent(); - InputLanguageChangingEventArgs e = InputLanguage.CreateInputLanguageChangingEventArgs( m ); + InputLanguageChangingEventArgs e = InputLanguage.CreateInputLanguageChangingEventArgs(m); Form form = FindForm(); - if( form != null ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Culture=" + e.Culture ); - form.PerformOnInputLanguageChanging( e ); + if (form != null) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Culture=" + e.Culture); + form.PerformOnInputLanguageChanging(e); } - if( !e.Cancel ) { - DefWndProc( ref m ); + if (!e.Cancel) + { + DefWndProc(ref m); } - else { + else + { m.Result = IntPtr.Zero; } @@ -680,26 +773,30 @@ private void WmInputLangChangeRequest( ref Message m ) { /// /// Handles the WM_IME_CHAR message /// - private void WmImeChar( ref Message m ) { - if( ProcessKeyEventArgs( ref m ) ) { + private void WmImeChar(ref Message m) + { + if (ProcessKeyEventArgs(ref m)) + { return; } - DefWndProc( ref m ); + DefWndProc(ref m); } /// /// Handles the WM_IME_ENDCOMPOSITION message /// - private void WmImeEndComposition( ref Message m ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside WmImeEndComposition() - Disabling ImeWmCharToIgnore, this=" + this ); + private void WmImeEndComposition(ref Message m) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside WmImeEndComposition() - Disabling ImeWmCharToIgnore, this=" + this); this.ImeWmCharsToIgnore = ImeCharsToIgnoreDisabled; - DefWndProc( ref m ); + DefWndProc(ref m); } /// /// Handles the WM_IME_NOTIFY message /// - private void WmImeNotify( ref Message m ) { + private void WmImeNotify(ref Message m) + { ImeMode[] inputLanguageTable = ImeModeConversion.InputLanguageTable; @@ -711,11 +808,13 @@ private void WmImeNotify( ref Message m ) { // // If this is the first time here after conversion to chinese language, wait for WmInputLanguageChange // before listening to WmImeNotifys. - if ((inputLanguageTable == ImeModeConversion.ChineseTable) && !lastLanguageChinese) IgnoreWmImeNotify = true; + if ((inputLanguageTable == ImeModeConversion.ChineseTable) && !lastLanguageChinese) + IgnoreWmImeNotify = true; lastLanguageChinese = (inputLanguageTable == ImeModeConversion.ChineseTable); - if( ImeSupported && inputLanguageTable != ImeModeConversion.UnsupportedTable && !IgnoreWmImeNotify) { - int wparam = (int) m.WParam; + if (ImeSupported && inputLanguageTable != ImeModeConversion.UnsupportedTable && !IgnoreWmImeNotify) + { + int wparam = (int)m.WParam; // The WM_IME_NOTIFY message is not consistent across the different IMEs, particularly the notification type // we care about (IMN_SETCONVERSIONMODE & IMN_SETOPENSTATUS). @@ -734,28 +833,31 @@ private void WmImeNotify( ref Message m ) { // We guard against re-entrancy since the ImeModeChanged event can be raised and any changes from the handler could // lead to another WM_IME_NOTIFY loop. - if( wparam == NativeMethods.IMN_SETCONVERSIONMODE || wparam == NativeMethods.IMN_SETOPENSTATUS ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, string.Format( CultureInfo.CurrentCulture, "Inside WmImeNotify(m.wparam=[{0}]), this={1}", m.WParam, this ) ); + if (wparam == NativeMethods.IMN_SETCONVERSIONMODE || wparam == NativeMethods.IMN_SETOPENSTATUS) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, string.Format(CultureInfo.CurrentCulture, "Inside WmImeNotify(m.wparam=[{0}]), this={1}", m.WParam, this)); Debug.Indent(); // Synchronize internal properties with the IME context mode. - OnImeContextStatusChanged( this.Handle ); + OnImeContextStatusChanged(this.Handle); Debug.Unindent(); } } - DefWndProc( ref m ); + DefWndProc(ref m); } /// /// Handles the WM_SETFOCUS message for IME related stuff. /// - internal void WmImeSetFocus() { - if (ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable) { + internal void WmImeSetFocus() + { + if (ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable) + { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside WmImeSetFocus(), this=" + this); - Debug.Indent(); - + Debug.Indent(); + // Make sure the IME context is set to the correct value. // Consider - Perf improvement: ContainerControl controls should update the IME context only when they don't contain // a focusable control since it will be updated by that control. @@ -768,25 +870,28 @@ internal void WmImeSetFocus() { /// /// Handles the WM_IME_STARTCOMPOSITION message /// - private void WmImeStartComposition( ref Message m ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside WmImeStartComposition() - Enabling ImeWmCharToIgnore, this=" + this ); + private void WmImeStartComposition(ref Message m) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside WmImeStartComposition() - Enabling ImeWmCharToIgnore, this=" + this); // Need to call the property store directly because the WmImeCharsToIgnore property is locked when ImeCharsToIgnoreDisabled. - Properties.SetInteger( PropImeWmCharsToIgnore, ImeCharsToIgnoreEnabled ); - DefWndProc( ref m ); + Properties.SetInteger(PropImeWmCharsToIgnore, ImeCharsToIgnoreEnabled); + DefWndProc(ref m); } /// /// Handles the WM_KILLFOCUS message /// - private void WmImeKillFocus() { + private void WmImeKillFocus() + { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside WmImeKillFocus(), this=" + this); Debug.Indent(); - + Control topMostWinformsParent = TopMostParent; Form appForm = topMostWinformsParent as Form; - if( (appForm == null || appForm.Modal) && !topMostWinformsParent.ContainsFocus ) { + if ((appForm == null || appForm.Modal) && !topMostWinformsParent.ContainsFocus) + { // This means the winforms component container is not a WinForms host and it is no longer focused. // Or it is not the main app host. @@ -799,19 +904,22 @@ private void WmImeKillFocus() { // See the PropagatingImeMode property // Note: We need to check the static field here directly to avoid initialization of the property. - if (Control.propagatingImeMode != ImeMode.Inherit) { + if (Control.propagatingImeMode != ImeMode.Inherit) + { // Setting the ime context of the top window will generate a WM_IME_NOTIFY on the focused control which will // update its ImeMode, we need to prevent this temporarily. IgnoreWmImeNotify = true; - try { + try + { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "Setting IME context to PropagatingImeMode (leaving Winforms container). this = " + this); ImeContext.SetImeStatus(PropagatingImeMode, topMostWinformsParent.Handle); Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "Resetting PropagatingImeMode. this = " + this); PropagatingImeMode = ImeMode.Inherit; } - finally { + finally + { IgnoreWmImeNotify = false; } } @@ -828,7 +936,8 @@ private void WmImeKillFocus() { /// /// Represents the native IME context. /// - public static class ImeContext { + public static class ImeContext + { /// /// The IME context handle obtained when first associating an IME. /// @@ -837,77 +946,90 @@ public static class ImeContext { /// /// Disable the IME /// - public static void Disable( IntPtr handle ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside ImeContext.Disable(" + handle + ")" ); + public static void Disable(IntPtr handle) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside ImeContext.Disable(" + handle + ")"); Debug.Indent(); - if( ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable ) { + if (ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable) + { // Close the IME if necessary // - if( ImeContext.IsOpen( handle ) ) { - ImeContext.SetOpenStatus( false, handle ); + if (ImeContext.IsOpen(handle)) + { + ImeContext.SetOpenStatus(false, handle); } // Disable the IME by disassociating the context from the window. // - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmAssociateContext(" + handle + ", null)" ); - IntPtr oldContext = UnsafeNativeMethods.ImmAssociateContext( new HandleRef( null, handle ), NativeMethods.NullHandleRef ); - if( oldContext != IntPtr.Zero ) { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmAssociateContext(" + handle + ", null)"); + IntPtr oldContext = UnsafeNativeMethods.ImmAssociateContext(new HandleRef(null, handle), NativeMethods.NullHandleRef); + if (oldContext != IntPtr.Zero) + { originalImeContext = oldContext; } } - ImeContext.TraceImeStatus( handle ); + ImeContext.TraceImeStatus(handle); Debug.Unindent(); } /// /// Enable the IME /// - public static void Enable( IntPtr handle ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside ImeContext.Enable(" + handle + ")" ); + public static void Enable(IntPtr handle) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside ImeContext.Enable(" + handle + ")"); Debug.Indent(); - if( ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetContext(" + handle + ")" ); - IntPtr inputContext = UnsafeNativeMethods.ImmGetContext( new HandleRef( null, handle ) ); - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "context = " + inputContext ); + if (ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetContext(" + handle + ")"); + IntPtr inputContext = UnsafeNativeMethods.ImmGetContext(new HandleRef(null, handle)); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "context = " + inputContext); // Enable IME by associating the IME context to the window. - if( inputContext == IntPtr.Zero ) { - if( originalImeContext == IntPtr.Zero ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmCreateContext()" ); + if (inputContext == IntPtr.Zero) + { + if (originalImeContext == IntPtr.Zero) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmCreateContext()"); inputContext = UnsafeNativeMethods.ImmCreateContext(); - if( inputContext != IntPtr.Zero ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmAssociateContext(" + handle + ", " + inputContext + ")" ); - UnsafeNativeMethods.ImmAssociateContext( new HandleRef( null, handle ), new HandleRef( null, inputContext ) ); + if (inputContext != IntPtr.Zero) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmAssociateContext(" + handle + ", " + inputContext + ")"); + UnsafeNativeMethods.ImmAssociateContext(new HandleRef(null, handle), new HandleRef(null, inputContext)); } } - else { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmAssociateContext()" ); - UnsafeNativeMethods.ImmAssociateContext( new HandleRef( null, handle ), new HandleRef( null, originalImeContext ) ); + else + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmAssociateContext()"); + UnsafeNativeMethods.ImmAssociateContext(new HandleRef(null, handle), new HandleRef(null, originalImeContext)); } } - else { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmReleaseContext(" + handle + ", " + inputContext + ")" ); - UnsafeNativeMethods.ImmReleaseContext( new HandleRef( null, handle ), new HandleRef( null, inputContext ) ); + else + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmReleaseContext(" + handle + ", " + inputContext + ")"); + UnsafeNativeMethods.ImmReleaseContext(new HandleRef(null, handle), new HandleRef(null, inputContext)); } // Make sure the IME is opened. - if( !ImeContext.IsOpen( handle ) ) { - ImeContext.SetOpenStatus( true, handle ); + if (!ImeContext.IsOpen(handle)) + { + ImeContext.SetOpenStatus(true, handle); } } - ImeContext.TraceImeStatus( handle ); + ImeContext.TraceImeStatus(handle); Debug.Unindent(); } /// /// Gets the ImeMode that corresponds to ImeMode.Disable based on the current input language ImeMode table. /// - public static ImeMode GetImeMode( IntPtr handle ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Insise ImeContext.GetImeMode(" + handle + ")" ); + public static ImeMode GetImeMode(IntPtr handle) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Insise ImeContext.GetImeMode(" + handle + ")"); Debug.Indent(); IntPtr inputContext = IntPtr.Zero; @@ -916,23 +1038,26 @@ public static ImeMode GetImeMode( IntPtr handle ) { // Get the right table for the current keyboard layout // ImeMode[] countryTable = ImeModeConversion.InputLanguageTable; - if( countryTable == ImeModeConversion.UnsupportedTable ) { + if (countryTable == ImeModeConversion.UnsupportedTable) + { // No IME associated with current culture. retval = ImeMode.Inherit; goto cleanup; } - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetContext(" + handle + ")" ); - inputContext = UnsafeNativeMethods.ImmGetContext( new HandleRef( null, handle ) ); - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "context = " + inputContext ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetContext(" + handle + ")"); + inputContext = UnsafeNativeMethods.ImmGetContext(new HandleRef(null, handle)); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "context = " + inputContext); - if( inputContext == IntPtr.Zero ) { + if (inputContext == IntPtr.Zero) + { // No IME context attached - The Ime has been disabled. retval = ImeMode.Disable; goto cleanup; } - if( !ImeContext.IsOpen( handle ) ) { + if (!ImeContext.IsOpen(handle)) + { // There's an IME associated with the window but is closed - the input is taken from the keyboard as is (English). retval = countryTable[ImeModeConversion.ImeClosed]; goto cleanup; @@ -944,38 +1069,43 @@ public static ImeMode GetImeMode( IntPtr handle ) { int conversion = 0; // Combination of conversion mode values int sentence = 0; // Sentence mode value - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetConversionStatus(" + inputContext + ", conversion, sentence)" ); - UnsafeNativeMethods.ImmGetConversionStatus( new HandleRef( null, inputContext ), ref conversion, ref sentence ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetConversionStatus(" + inputContext + ", conversion, sentence)"); + UnsafeNativeMethods.ImmGetConversionStatus(new HandleRef(null, inputContext), ref conversion, ref sentence); - Debug.Assert( countryTable != null, "countryTable is null" ); + Debug.Assert(countryTable != null, "countryTable is null"); - if( ( conversion & NativeMethods.IME_CMODE_NATIVE ) != 0 ) { - if( ( conversion & NativeMethods.IME_CMODE_KATAKANA ) != 0 ) { - retval = ( ( conversion & NativeMethods.IME_CMODE_FULLSHAPE ) != 0 ) + if ((conversion & NativeMethods.IME_CMODE_NATIVE) != 0) + { + if ((conversion & NativeMethods.IME_CMODE_KATAKANA) != 0) + { + retval = ((conversion & NativeMethods.IME_CMODE_FULLSHAPE) != 0) ? countryTable[ImeModeConversion.ImeNativeFullKatakana] : countryTable[ImeModeConversion.ImeNativeHalfKatakana]; goto cleanup; } - else { // ! Katakana - retval = ( ( conversion & NativeMethods.IME_CMODE_FULLSHAPE ) != 0 ) + else + { // ! Katakana + retval = ((conversion & NativeMethods.IME_CMODE_FULLSHAPE) != 0) ? countryTable[ImeModeConversion.ImeNativeFullHiragana] : countryTable[ImeModeConversion.ImeNativeHalfHiragana]; goto cleanup; } } - else { // ! IME_CMODE_NATIVE - retval = ( ( conversion & NativeMethods.IME_CMODE_FULLSHAPE ) != 0 ) + else + { // ! IME_CMODE_NATIVE + retval = ((conversion & NativeMethods.IME_CMODE_FULLSHAPE) != 0) ? countryTable[ImeModeConversion.ImeAlphaFull] : countryTable[ImeModeConversion.ImeAlphaHalf]; } cleanup: - if( inputContext != IntPtr.Zero ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmReleaseContext(" + handle + ", " + inputContext + ")" ); - UnsafeNativeMethods.ImmReleaseContext( new HandleRef( null, handle ), new HandleRef( null, inputContext ) ); + if (inputContext != IntPtr.Zero) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmReleaseContext(" + handle + ", " + inputContext + ")"); + UnsafeNativeMethods.ImmReleaseContext(new HandleRef(null, handle), new HandleRef(null, inputContext)); } - ImeContext.TraceImeStatus( handle ); + ImeContext.TraceImeStatus(handle); Debug.Unindent(); return retval; @@ -984,36 +1114,43 @@ public static ImeMode GetImeMode( IntPtr handle ) { /// /// Get the actual IME status - This method is for debugging purposes only. /// - [Conditional( "DEBUG" )] - internal static void TraceImeStatus( Control ctl ) { + [Conditional("DEBUG")] + internal static void TraceImeStatus(Control ctl) + { #if DEBUG - if ( ctl.IsHandleCreated ){ - TraceImeStatus( ctl.Handle ); + if (ctl.IsHandleCreated) + { + TraceImeStatus(ctl.Handle); } #endif } - [Conditional( "DEBUG" )] - private static void TraceImeStatus( IntPtr handle ) { + [Conditional("DEBUG")] + private static void TraceImeStatus(IntPtr handle) + { #if DEBUG - if (CompModSwitches.ImeMode.Level >= TraceLevel.Info) { + if (CompModSwitches.ImeMode.Level >= TraceLevel.Info) + { string status = "?"; IntPtr inputContext = IntPtr.Zero; ImeMode[] countryTable = ImeModeConversion.InputLanguageTable; - if (countryTable == ImeModeConversion.UnsupportedTable) { + if (countryTable == ImeModeConversion.UnsupportedTable) + { status = "IME not supported in current language."; goto cleanup; } inputContext = UnsafeNativeMethods.ImmGetContext(new HandleRef(null, handle)); - if (inputContext == IntPtr.Zero) { + if (inputContext == IntPtr.Zero) + { status = string.Format(CultureInfo.CurrentCulture, "No ime context for handle=[{0}]", handle); goto cleanup; } - if (!UnsafeNativeMethods.ImmGetOpenStatus(new HandleRef(null, inputContext))) { + if (!UnsafeNativeMethods.ImmGetOpenStatus(new HandleRef(null, inputContext))) + { status = string.Format(CultureInfo.CurrentCulture, "Ime closed for handle=[{0}]", handle); goto cleanup; } @@ -1024,19 +1161,23 @@ private static void TraceImeStatus( IntPtr handle ) { UnsafeNativeMethods.ImmGetConversionStatus(new HandleRef(null, inputContext), ref conversion, ref sentence); ImeMode retval; - if ((conversion & NativeMethods.IME_CMODE_NATIVE) != 0) { - if ((conversion & NativeMethods.IME_CMODE_KATAKANA) != 0) { + if ((conversion & NativeMethods.IME_CMODE_NATIVE) != 0) + { + if ((conversion & NativeMethods.IME_CMODE_KATAKANA) != 0) + { retval = ((conversion & NativeMethods.IME_CMODE_FULLSHAPE) != 0) ? countryTable[ImeModeConversion.ImeNativeFullKatakana] : countryTable[ImeModeConversion.ImeNativeHalfKatakana]; } - else { // ! Katakana + else + { // ! Katakana retval = ((conversion & NativeMethods.IME_CMODE_FULLSHAPE) != 0) ? countryTable[ImeModeConversion.ImeNativeFullHiragana] : countryTable[ImeModeConversion.ImeNativeHalfHiragana]; } } - else { // ! IME_CMODE_NATIVE + else + { // ! IME_CMODE_NATIVE retval = ((conversion & NativeMethods.IME_CMODE_FULLSHAPE) != 0) ? countryTable[ImeModeConversion.ImeAlphaFull] : countryTable[ImeModeConversion.ImeAlphaHalf]; @@ -1045,7 +1186,8 @@ private static void TraceImeStatus( IntPtr handle ) { status = string.Format(CultureInfo.CurrentCulture, "Ime conversion status mode for handle=[{0}]: {1}", handle, retval); cleanup: - if (inputContext != IntPtr.Zero) { + if (inputContext != IntPtr.Zero) + { UnsafeNativeMethods.ImmReleaseContext(new HandleRef(null, handle), new HandleRef(null, inputContext)); } @@ -1057,24 +1199,26 @@ private static void TraceImeStatus( IntPtr handle ) { /// /// Returns true if the IME is currently open /// - public static bool IsOpen( IntPtr handle ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside ImeContext.IsOpen(" + handle + ")" ); + public static bool IsOpen(IntPtr handle) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside ImeContext.IsOpen(" + handle + ")"); Debug.Indent(); - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetContext(" + handle + ")" ); - IntPtr inputContext = UnsafeNativeMethods.ImmGetContext( new HandleRef( null, handle ) ); - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "context = " + inputContext ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetContext(" + handle + ")"); + IntPtr inputContext = UnsafeNativeMethods.ImmGetContext(new HandleRef(null, handle)); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "context = " + inputContext); bool retval = false; - if( inputContext != IntPtr.Zero ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetOpenStatus(" + inputContext + ")" ); - retval = UnsafeNativeMethods.ImmGetOpenStatus( new HandleRef( null, inputContext ) ); - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmReleaseContext(" + handle + ", " + inputContext + ")" ); - UnsafeNativeMethods.ImmReleaseContext( new HandleRef( null, handle ), new HandleRef( null, inputContext ) ); + if (inputContext != IntPtr.Zero) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetOpenStatus(" + inputContext + ")"); + retval = UnsafeNativeMethods.ImmGetOpenStatus(new HandleRef(null, inputContext)); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmReleaseContext(" + handle + ", " + inputContext + ")"); + UnsafeNativeMethods.ImmReleaseContext(new HandleRef(null, handle), new HandleRef(null, inputContext)); } - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, " IsOpen = " + retval ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, " IsOpen = " + retval); Debug.Unindent(); return retval; @@ -1083,36 +1227,42 @@ public static bool IsOpen( IntPtr handle ) { /// /// Sets the actual IME context value. /// - public static void SetImeStatus( ImeMode imeMode, IntPtr handle ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, string.Format( CultureInfo.CurrentCulture, "Inside ImeContext.SetImeStatus(ImeMode=[{0}, handle=[{1}])", imeMode, handle ) ); + public static void SetImeStatus(ImeMode imeMode, IntPtr handle) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, string.Format(CultureInfo.CurrentCulture, "Inside ImeContext.SetImeStatus(ImeMode=[{0}, handle=[{1}])", imeMode, handle)); Debug.Indent(); - Debug.Assert( imeMode != ImeMode.Inherit, "ImeMode.Inherit is an invalid argument to ImeContext.SetImeStatus" ); + Debug.Assert(imeMode != ImeMode.Inherit, "ImeMode.Inherit is an invalid argument to ImeContext.SetImeStatus"); - if( imeMode == ImeMode.Inherit || imeMode == ImeMode.NoControl ) { + if (imeMode == ImeMode.Inherit || imeMode == ImeMode.NoControl) + { goto cleanup; // No action required } ImeMode[] inputLanguageTable = ImeModeConversion.InputLanguageTable; - if (inputLanguageTable == ImeModeConversion.UnsupportedTable) { + if (inputLanguageTable == ImeModeConversion.UnsupportedTable) + { goto cleanup; // We only support Japanese, Korean and Chinese IME. } int conversion = 0; // Combination of conversion mode values int sentence = 0; // Sentence mode value - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Warning, "\tSetting IME context to " + imeMode ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Warning, "\tSetting IME context to " + imeMode); - if( imeMode == ImeMode.Disable ) { - ImeContext.Disable( handle ); + if (imeMode == ImeMode.Disable) + { + ImeContext.Disable(handle); } - else { + else + { // This will make sure the IME is opened. - ImeContext.Enable( handle ); + ImeContext.Enable(handle); } - switch( imeMode ) { + switch (imeMode) + { case ImeMode.NoControl: case ImeMode.Disable: break; // No action required @@ -1126,7 +1276,8 @@ public static void SetImeStatus( ImeMode imeMode, IntPtr handle ) { case ImeMode.Off: // IME direct input (CHN = Off, JPN = Off, KOR = Alpha). - if (inputLanguageTable == ImeModeConversion.JapaneseTable) { + if (inputLanguageTable == ImeModeConversion.JapaneseTable) + { // Japanese IME interprets Close as Off. goto case ImeMode.Close; } @@ -1136,70 +1287,76 @@ public static void SetImeStatus( ImeMode imeMode, IntPtr handle ) { goto default; case ImeMode.Close: - if (inputLanguageTable == ImeModeConversion.KoreanTable) { + if (inputLanguageTable == ImeModeConversion.KoreanTable) + { // Korean IME has no idea what Close means. imeMode = ImeMode.Alpha; goto default; } - ImeContext.SetOpenStatus( false, handle ); + ImeContext.SetOpenStatus(false, handle); break; default: - if( ImeModeConversion.ImeModeConversionBits.ContainsKey( imeMode ) ) { + if (ImeModeConversion.ImeModeConversionBits.ContainsKey(imeMode)) + { // Update the conversion status // - ImeModeConversion conversionEntry = (ImeModeConversion) ImeModeConversion.ImeModeConversionBits[imeMode]; + ImeModeConversion conversionEntry = (ImeModeConversion)ImeModeConversion.ImeModeConversionBits[imeMode]; - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetContext(" + handle + ")" ); - IntPtr inputContext = UnsafeNativeMethods.ImmGetContext( new HandleRef( null, handle ) ); - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "context = " + inputContext ); - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetConversionStatus(" + inputContext + ", conversion, sentence)" ); - UnsafeNativeMethods.ImmGetConversionStatus( new HandleRef( null, inputContext ), ref conversion, ref sentence ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetContext(" + handle + ")"); + IntPtr inputContext = UnsafeNativeMethods.ImmGetContext(new HandleRef(null, handle)); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "context = " + inputContext); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetConversionStatus(" + inputContext + ", conversion, sentence)"); + UnsafeNativeMethods.ImmGetConversionStatus(new HandleRef(null, inputContext), ref conversion, ref sentence); conversion |= conversionEntry.setBits; conversion &= ~conversionEntry.clearBits; - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmSetConversionStatus(" + inputContext + ", conversion, sentence)" ); - bool retval = UnsafeNativeMethods.ImmSetConversionStatus( new HandleRef( null, inputContext ), conversion, sentence ); - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmReleaseContext(" + handle + ", " + inputContext + ")" ); - UnsafeNativeMethods.ImmReleaseContext( new HandleRef( null, handle ), new HandleRef( null, inputContext ) ); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmSetConversionStatus(" + inputContext + ", conversion, sentence)"); + bool retval = UnsafeNativeMethods.ImmSetConversionStatus(new HandleRef(null, inputContext), conversion, sentence); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmReleaseContext(" + handle + ", " + inputContext + ")"); + UnsafeNativeMethods.ImmReleaseContext(new HandleRef(null, handle), new HandleRef(null, inputContext)); } break; } cleanup: - ImeContext.TraceImeStatus( handle ); + ImeContext.TraceImeStatus(handle); Debug.Unindent(); } /// /// Opens or closes the IME context. /// - public static void SetOpenStatus( bool open, IntPtr handle ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Info, string.Format( CultureInfo.CurrentCulture, "Inside SetOpenStatus(open=[{0}], handle=[{1}])", open, handle ) ); + public static void SetOpenStatus(bool open, IntPtr handle) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, string.Format(CultureInfo.CurrentCulture, "Inside SetOpenStatus(open=[{0}], handle=[{1}])", open, handle)); Debug.Indent(); - if( ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetContext(" + handle + ")" ); - IntPtr inputContext = UnsafeNativeMethods.ImmGetContext( new HandleRef( null, handle ) ); - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "context = " + inputContext ); - - if( inputContext != IntPtr.Zero ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmSetOpenStatus(" + inputContext + ", " + open + ")" ); - bool succeeded = UnsafeNativeMethods.ImmSetOpenStatus( new HandleRef( null, inputContext ), open ); - Debug.Assert( succeeded, "Could not set the IME open status." ); + if (ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmGetContext(" + handle + ")"); + IntPtr inputContext = UnsafeNativeMethods.ImmGetContext(new HandleRef(null, handle)); + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "context = " + inputContext); - if( succeeded ) { - Debug.WriteLineIf( CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmReleaseContext(" + handle + ", " + inputContext + ")" ); - succeeded = UnsafeNativeMethods.ImmReleaseContext( new HandleRef( null, handle ), new HandleRef( null, inputContext ) ); - Debug.Assert( succeeded, "Could not release IME context." ); + if (inputContext != IntPtr.Zero) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmSetOpenStatus(" + inputContext + ", " + open + ")"); + bool succeeded = UnsafeNativeMethods.ImmSetOpenStatus(new HandleRef(null, inputContext), open); + Debug.Assert(succeeded, "Could not set the IME open status."); + + if (succeeded) + { + Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmReleaseContext(" + handle + ", " + inputContext + ")"); + succeeded = UnsafeNativeMethods.ImmReleaseContext(new HandleRef(null, handle), new HandleRef(null, inputContext)); + Debug.Assert(succeeded, "Could not release IME context."); } } } - ImeContext.TraceImeStatus( handle ); + ImeContext.TraceImeStatus(handle); Debug.Unindent(); } }// end ImeContext class @@ -1275,33 +1432,41 @@ public struct ImeModeConversion ImeMode.On, ImeMode.OnHalf, ImeMode.Off, - ImeMode.Off + ImeMode.Off }; private static ImeMode[] unsupportedTable = { }; - internal static ImeMode[] ChineseTable { - get { + internal static ImeMode[] ChineseTable + { + get + { return chineseTable; } } - internal static ImeMode[] JapaneseTable { - get { + internal static ImeMode[] JapaneseTable + { + get + { return japaneseTable; } } - internal static ImeMode[] KoreanTable { - get { + internal static ImeMode[] KoreanTable + { + get + { return koreanTable; } } - internal static ImeMode[] UnsupportedTable { - get { + internal static ImeMode[] UnsupportedTable + { + get + { return unsupportedTable; } } @@ -1313,19 +1478,22 @@ internal static ImeMode[] UnsupportedTable { /// and would render it invalid and since the IME API is not public third party controls would not have a way to update /// the cached value. /// - internal static ImeMode[] InputLanguageTable { - get { + internal static ImeMode[] InputLanguageTable + { + get + { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_InputLanguageTable(), Input Language = " + InputLanguage.CurrentInputLanguage.Culture.DisplayName + ", Thread = " + System.Threading.Thread.CurrentThread.ManagedThreadId); InputLanguage inputLanguage = InputLanguage.CurrentInputLanguage; int lcid = (int)((long)inputLanguage.Handle & (long)0xFFFF); - switch (lcid) { - case 0x0404: - case 0x0804: - case 0x0c04: - case 0x1004: - case 0x1404: + switch (lcid) + { + case 0x0404: + case 0x0804: + case 0x0c04: + case 0x1004: + case 0x1404: return chineseTable; case 0x0412: // Korean @@ -1344,55 +1512,58 @@ internal static ImeMode[] InputLanguageTable { /// /// Dictionary of ImeMode and corresponding convertion flags. /// - public static Dictionary ImeModeConversionBits { - get { - if( imeModeConversionBits == null ) { + public static Dictionary ImeModeConversionBits + { + get + { + if (imeModeConversionBits == null) + { // Create ImeModeConversionBits dictionary - imeModeConversionBits = new Dictionary( 7 ); + imeModeConversionBits = new Dictionary(7); ImeModeConversion conversion; // Hiragana, On // conversion.setBits = NativeMethods.IME_CMODE_FULLSHAPE | NativeMethods.IME_CMODE_NATIVE; conversion.clearBits = NativeMethods.IME_CMODE_KATAKANA; - imeModeConversionBits.Add( ImeMode.Hiragana, conversion ); + imeModeConversionBits.Add(ImeMode.Hiragana, conversion); // Katakana // conversion.setBits = NativeMethods.IME_CMODE_FULLSHAPE | NativeMethods.IME_CMODE_KATAKANA | NativeMethods.IME_CMODE_NATIVE; conversion.clearBits = 0; - imeModeConversionBits.Add( ImeMode.Katakana, conversion ); + imeModeConversionBits.Add(ImeMode.Katakana, conversion); // KatakanaHalf // conversion.setBits = NativeMethods.IME_CMODE_KATAKANA | NativeMethods.IME_CMODE_NATIVE; conversion.clearBits = NativeMethods.IME_CMODE_FULLSHAPE; - imeModeConversionBits.Add( ImeMode.KatakanaHalf, conversion ); + imeModeConversionBits.Add(ImeMode.KatakanaHalf, conversion); // AlphaFull // conversion.setBits = NativeMethods.IME_CMODE_FULLSHAPE; conversion.clearBits = NativeMethods.IME_CMODE_KATAKANA | NativeMethods.IME_CMODE_NATIVE; - imeModeConversionBits.Add( ImeMode.AlphaFull, conversion ); + imeModeConversionBits.Add(ImeMode.AlphaFull, conversion); // Alpha // conversion.setBits = 0; conversion.clearBits = NativeMethods.IME_CMODE_FULLSHAPE | NativeMethods.IME_CMODE_KATAKANA | NativeMethods.IME_CMODE_NATIVE; - imeModeConversionBits.Add( ImeMode.Alpha, conversion ); + imeModeConversionBits.Add(ImeMode.Alpha, conversion); // HangulFull // conversion.setBits = NativeMethods.IME_CMODE_FULLSHAPE | NativeMethods.IME_CMODE_NATIVE; conversion.clearBits = 0; - imeModeConversionBits.Add( ImeMode.HangulFull, conversion ); + imeModeConversionBits.Add(ImeMode.HangulFull, conversion); // Hangul // conversion.setBits = NativeMethods.IME_CMODE_NATIVE; conversion.clearBits = NativeMethods.IME_CMODE_FULLSHAPE; - imeModeConversionBits.Add( ImeMode.Hangul, conversion ); + imeModeConversionBits.Add(ImeMode.Hangul, conversion); // OnHalf // @@ -1405,8 +1576,10 @@ public static Dictionary ImeModeConversionBits { } } - public static bool IsCurrentConversionTableSupported{ - get { + public static bool IsCurrentConversionTableSupported + { + get + { return InputLanguageTable != UnsupportedTable; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/formatter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/formatter.cs index c6688555bba..e88ab4d45cb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/formatter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/formatter.cs @@ -28,13 +28,14 @@ internal class Formatter /// /// public static object FormatObject(object value, - Type targetType, - TypeConverter sourceConverter, - TypeConverter targetConverter, - string formatString, - IFormatProvider formatInfo, + Type targetType, + TypeConverter sourceConverter, + TypeConverter targetConverter, + string formatString, + IFormatProvider formatInfo, object formattedNullValue, - object dataSourceNullValue) { + object dataSourceNullValue) + { // // On the way in, see if value represents 'null' for this back-end field type, and substitute DBNull. // For most types, 'null' is actually represented by DBNull. But for a nullable type, its represented @@ -42,7 +43,8 @@ public static object FormatObject(object value, // simple null reference. // - if (Formatter.IsNullData(value, dataSourceNullValue)) { + if (Formatter.IsNullData(value, dataSourceNullValue)) + { value = System.DBNull.Value; } @@ -52,7 +54,7 @@ public static object FormatObject(object value, Type oldTargetType = targetType; - targetType = NullableUnwrap(targetType); + targetType = NullableUnwrap(targetType); sourceConverter = NullableUnwrap(sourceConverter); targetConverter = NullableUnwrap(targetConverter); @@ -82,13 +84,15 @@ public static object FormatObject(object value, /// /// private static object FormatObjectInternal(object value, - Type targetType, - TypeConverter sourceConverter, - TypeConverter targetConverter, - string formatString, - IFormatProvider formatInfo, - object formattedNullValue) { - if (value == System.DBNull.Value || value == null) { + Type targetType, + TypeConverter sourceConverter, + TypeConverter targetConverter, + string formatString, + IFormatProvider formatInfo, + object formattedNullValue) + { + if (value == System.DBNull.Value || value == null) + { // // Convert DBNull to the formatted representation of 'null' (if possible) // @@ -104,22 +108,25 @@ private static object FormatObjectInternal(object value, { return string.Empty; } - - if (targetType == checkStateType) { + + if (targetType == checkStateType) + { return CheckState.Indeterminate; } - + // Just pass null through: if this is a value type, it's been unwrapped here, so we return null // and the caller has to wrap if appropriate. - return null; + return null; } // // Special case conversions // - if (targetType == stringType) { - if (value is IFormattable && !string.IsNullOrEmpty(formatString)) { + if (targetType == stringType) + { + if (value is IFormattable && !string.IsNullOrEmpty(formatString)) + { return (value as IFormattable).ToString(formatString, formatInfo); } } @@ -128,31 +135,39 @@ private static object FormatObjectInternal(object value, //type's TypeConverter. We're punting the case where the property-provided converter is the same as the type's converter. Type sourceType = value.GetType(); TypeConverter sourceTypeTypeConverter = TypeDescriptor.GetConverter(sourceType); - if (sourceConverter != null && sourceConverter != sourceTypeTypeConverter && sourceConverter.CanConvertTo(targetType)) { + if (sourceConverter != null && sourceConverter != sourceTypeTypeConverter && sourceConverter.CanConvertTo(targetType)) + { return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType); } TypeConverter targetTypeTypeConverter = TypeDescriptor.GetConverter(targetType); - if (targetConverter != null && targetConverter != targetTypeTypeConverter && targetConverter.CanConvertFrom(sourceType)) { + if (targetConverter != null && targetConverter != targetTypeTypeConverter && targetConverter.CanConvertFrom(sourceType)) + { return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value); } - if (targetType == checkStateType) { - if (sourceType == booleanType) { + if (targetType == checkStateType) + { + if (sourceType == booleanType) + { return ((bool)value) ? CheckState.Checked : CheckState.Unchecked; - } - else { - if (sourceConverter == null) { + } + else + { + if (sourceConverter == null) + { sourceConverter = sourceTypeTypeConverter; } - if (sourceConverter != null && sourceConverter.CanConvertTo(booleanType)) { + if (sourceConverter != null && sourceConverter.CanConvertTo(booleanType)) + { return (bool)sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, booleanType) ? CheckState.Checked : CheckState.Unchecked; } } } - if (targetType.IsAssignableFrom(sourceType)) { + if (targetType.IsAssignableFrom(sourceType)) + { return value; } @@ -160,11 +175,13 @@ private static object FormatObjectInternal(object value, // If explicit type converters not provided, supply default ones instead // - if (sourceConverter == null) { + if (sourceConverter == null) + { sourceConverter = sourceTypeTypeConverter; } - if (targetConverter == null) { + if (targetConverter == null) + { targetConverter = targetTypeTypeConverter; } @@ -172,13 +189,16 @@ private static object FormatObjectInternal(object value, // Standardized conversions // - if (sourceConverter != null && sourceConverter.CanConvertTo(targetType)) { + if (sourceConverter != null && sourceConverter.CanConvertTo(targetType)) + { return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType); } - else if (targetConverter != null && targetConverter.CanConvertFrom(sourceType)) { + else if (targetConverter != null && targetConverter.CanConvertFrom(sourceType)) + { return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value); } - else if (value is IConvertible) { + else if (value is IConvertible) + { return ChangeType(value, targetType, formatInfo); } @@ -200,22 +220,23 @@ private static object FormatObjectInternal(object value, /// value back, we must also re-wrap the final result inside a nullable value before returning. /// /// - public static object ParseObject(object value, - Type targetType, - Type sourceType, - TypeConverter targetConverter, - TypeConverter sourceConverter, - IFormatProvider formatInfo, + public static object ParseObject(object value, + Type targetType, + Type sourceType, + TypeConverter targetConverter, + TypeConverter sourceConverter, + IFormatProvider formatInfo, object formattedNullValue, - object dataSourceNullValue) { + object dataSourceNullValue) + { // // Strip away any use of nullable types (eg. Nullable), leaving just the 'real' types // Type oldTargetType = targetType; - sourceType = NullableUnwrap(sourceType); - targetType = NullableUnwrap(targetType); + sourceType = NullableUnwrap(sourceType); + targetType = NullableUnwrap(targetType); sourceConverter = NullableUnwrap(sourceConverter); targetConverter = NullableUnwrap(targetConverter); @@ -232,7 +253,8 @@ public static object ParseObject(object value, // For most types, this is just DBNull. But for a nullable type, its an instance of that type with no value. // - if (result == System.DBNull.Value) { + if (result == System.DBNull.Value) + { return Formatter.NullData(oldTargetType, dataSourceNullValue); } @@ -249,18 +271,20 @@ public static object ParseObject(object value, /// - Throws a FormatException is no suitable conversion can be found /// /// - private static object ParseObjectInternal(object value, - Type targetType, - Type sourceType, - TypeConverter targetConverter, - TypeConverter sourceConverter, - IFormatProvider formatInfo, - object formattedNullValue) { + private static object ParseObjectInternal(object value, + Type targetType, + Type sourceType, + TypeConverter targetConverter, + TypeConverter sourceConverter, + IFormatProvider formatInfo, + object formattedNullValue) + { // // Convert the formatted representation of 'null' to DBNull (if possible) // - if (EqualsFormattedNullValue(value, formattedNullValue, formatInfo) || value == System.DBNull.Value) { + if (EqualsFormattedNullValue(value, formattedNullValue, formatInfo) || value == System.DBNull.Value) + { return System.DBNull.Value; } @@ -269,39 +293,49 @@ private static object ParseObjectInternal(object value, // TypeConverter targetTypeTypeConverter = TypeDescriptor.GetConverter(targetType); - if (targetConverter != null && targetTypeTypeConverter != targetConverter && targetConverter.CanConvertFrom(sourceType)) { + if (targetConverter != null && targetTypeTypeConverter != targetConverter && targetConverter.CanConvertFrom(sourceType)) + { return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value); } TypeConverter sourceTypeTypeConverter = TypeDescriptor.GetConverter(sourceType); - if (sourceConverter != null && sourceTypeTypeConverter != sourceConverter && sourceConverter.CanConvertTo(targetType)) { + if (sourceConverter != null && sourceTypeTypeConverter != sourceConverter && sourceConverter.CanConvertTo(targetType)) + { return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType); } - if (value is string) { + if (value is string) + { // If target type has a suitable Parse method, use that to parse strings object parseResult = InvokeStringParseMethod(value, targetType, formatInfo); - if (parseResult != parseMethodNotFound) { + if (parseResult != parseMethodNotFound) + { return parseResult; } } - else if (value is CheckState) { + else if (value is CheckState) + { CheckState state = (CheckState)value; - if (state == CheckState.Indeterminate) { + if (state == CheckState.Indeterminate) + { return DBNull.Value; } // Explicit conversion from CheckState to Boolean - if (targetType == booleanType) { + if (targetType == booleanType) + { return (state == CheckState.Checked); } - if (targetConverter == null) { + if (targetConverter == null) + { targetConverter = targetTypeTypeConverter; } - if (targetConverter != null && targetConverter.CanConvertFrom(booleanType)) { + if (targetConverter != null && targetConverter.CanConvertFrom(booleanType)) + { return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), state == CheckState.Checked); } } - else if (value != null && targetType.IsAssignableFrom(value.GetType())) { + else if (value != null && targetType.IsAssignableFrom(value.GetType())) + { // If value is already of a compatible type, just go ahead and use it return value; } @@ -310,11 +344,13 @@ private static object ParseObjectInternal(object value, // If explicit type converters not provided, supply default ones instead // - if (targetConverter == null) { + if (targetConverter == null) + { targetConverter = targetTypeTypeConverter; } - if (sourceConverter == null) { + if (sourceConverter == null) + { sourceConverter = sourceTypeTypeConverter; } @@ -322,13 +358,16 @@ private static object ParseObjectInternal(object value, // Standardized conversions // - if (targetConverter != null && targetConverter.CanConvertFrom(sourceType)) { + if (targetConverter != null && targetConverter.CanConvertFrom(sourceType)) + { return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value); } - else if (sourceConverter != null && sourceConverter.CanConvertTo(targetType)) { + else if (sourceConverter != null && sourceConverter.CanConvertTo(targetType)) + { return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType); } - else if (value is IConvertible) { + else if (value is IConvertible) + { return ChangeType(value, targetType, formatInfo); } @@ -342,15 +381,19 @@ private static object ParseObjectInternal(object value, /// /// Converts a value to the specified type using Convert.ChangeType() /// - private static object ChangeType(object value, Type type, IFormatProvider formatInfo) { - try { - if (formatInfo == null) { + private static object ChangeType(object value, Type type, IFormatProvider formatInfo) + { + try + { + if (formatInfo == null) + { formatInfo = CultureInfo.CurrentCulture; } return Convert.ChangeType(value, type, formatInfo); } - catch (InvalidCastException ex) { + catch (InvalidCastException ex) + { throw new FormatException(ex.Message, ex); } } @@ -358,18 +401,22 @@ private static object ChangeType(object value, Type type, IFormatProvider format /// /// Indicates whether the specified value matches the display-formatted representation of 'null data' for a given binding. /// - private static bool EqualsFormattedNullValue(object value, object formattedNullValue, IFormatProvider formatInfo) { + private static bool EqualsFormattedNullValue(object value, object formattedNullValue, IFormatProvider formatInfo) + { string formattedNullValueStr = formattedNullValue as string; string valueStr = value as string; - if (formattedNullValueStr != null && valueStr != null) { + if (formattedNullValueStr != null && valueStr != null) + { // Use same optimization as in WindowsFormsUtils.SafeCompareStrings(...). This addresses - if (formattedNullValueStr.Length != valueStr.Length) { + if (formattedNullValueStr.Length != valueStr.Length) + { return false; } // Always do a case insensitive comparison for strings return string.Compare(valueStr, formattedNullValueStr, true, GetFormatterCulture(formatInfo)) == 0; } - else { + else + { // Otherwise perform default comparison based on object types return Object.Equals(value, formattedNullValue); } @@ -378,7 +425,8 @@ private static bool EqualsFormattedNullValue(object value, object formattedNullV /// /// Returns the FormatException message used when formatting/parsing fails to find any suitable conversion /// - private static string GetCantConvertMessage(object value, Type targetType) { + private static string GetCantConvertMessage(object value, Type targetType) + { string stringResId = (value == null) ? SR.Formatter_CantConvertNull : SR.Formatter_CantConvert; return string.Format(CultureInfo.CurrentCulture, stringResId, value, targetType.Name); } @@ -386,11 +434,14 @@ private static string GetCantConvertMessage(object value, Type targetType) { /// /// Determines the correct culture to use during formatting and parsing /// - private static CultureInfo GetFormatterCulture(IFormatProvider formatInfo) { - if (formatInfo is CultureInfo) { + private static CultureInfo GetFormatterCulture(IFormatProvider formatInfo) + { + if (formatInfo is CultureInfo) + { return formatInfo as CultureInfo; } - else { + else + { return CultureInfo.CurrentCulture; } } @@ -398,40 +449,46 @@ private static CultureInfo GetFormatterCulture(IFormatProvider formatInfo) { /// /// Converts a value to the specified type using best Parse() method on that type /// - public static object InvokeStringParseMethod(object value, Type targetType, IFormatProvider formatInfo) { - try { + public static object InvokeStringParseMethod(object value, Type targetType, IFormatProvider formatInfo) + { + try + { MethodInfo mi; - mi = targetType.GetMethod("Parse", - BindingFlags.Public | BindingFlags.Static, - null, - new Type[] {stringType, typeof(System.Globalization.NumberStyles), typeof(System.IFormatProvider)}, + mi = targetType.GetMethod("Parse", + BindingFlags.Public | BindingFlags.Static, + null, + new Type[] { stringType, typeof(System.Globalization.NumberStyles), typeof(System.IFormatProvider) }, null); - if (mi != null) { - return mi.Invoke(null, new object [] {(string) value, NumberStyles.Any, formatInfo}); + if (mi != null) + { + return mi.Invoke(null, new object[] { (string)value, NumberStyles.Any, formatInfo }); } mi = targetType.GetMethod("Parse", - BindingFlags.Public | BindingFlags.Static, - null, - new Type[] {stringType, typeof(System.IFormatProvider)}, + BindingFlags.Public | BindingFlags.Static, + null, + new Type[] { stringType, typeof(System.IFormatProvider) }, null); - if (mi != null) { - return mi.Invoke(null, new object [] {(string) value, formatInfo}); + if (mi != null) + { + return mi.Invoke(null, new object[] { (string)value, formatInfo }); } mi = targetType.GetMethod("Parse", - BindingFlags.Public | BindingFlags.Static, - null, - new Type[] {stringType}, + BindingFlags.Public | BindingFlags.Static, + null, + new Type[] { stringType }, null); - if (mi != null) { - return mi.Invoke(null, new object [] {(string) value}); + if (mi != null) + { + return mi.Invoke(null, new object[] { (string)value }); } return parseMethodNotFound; } - catch (TargetInvocationException ex) { + catch (TargetInvocationException ex) + { throw new FormatException(ex.InnerException.Message, ex.InnerException); } } @@ -439,7 +496,8 @@ public static object InvokeStringParseMethod(object value, Type targetType, IFor /// /// Indicates whether a given value represents 'null' for data source fields of the same type. /// - public static bool IsNullData(object value, object dataSourceNullValue) { + public static bool IsNullData(object value, object dataSourceNullValue) + { return value == null || value == System.DBNull.Value || Object.Equals(value, NullData(value.GetType(), dataSourceNullValue)); @@ -448,8 +506,10 @@ public static bool IsNullData(object value, object dataSourceNullValue) { /// /// Returns the default representation of 'null' for a given data source field type. /// - public static object NullData(Type type, object dataSourceNullValue) { - if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { + public static object NullData(Type type, object dataSourceNullValue) + { + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) + { // For nullable types, null is represented by an instance of that type with no assigned value. // The value could also be DBNull.Value (the default for dataSourceNullValue). if (dataSourceNullValue == null || dataSourceNullValue == DBNull.Value) @@ -463,7 +523,8 @@ public static object NullData(Type type, object dataSourceNullValue) { return dataSourceNullValue; } } - else { + else + { // For all other types, the default representation of null is defined by // the caller (this will usually be System.DBNull.Value for ADO.NET data // sources, or a null reference for 'business object' data sources). @@ -474,7 +535,8 @@ public static object NullData(Type type, object dataSourceNullValue) { /// /// Extract the inner type from a nullable type /// - private static Type NullableUnwrap(Type type) { + private static Type NullableUnwrap(Type type) + { if (type == stringType) // ...performance optimization for the most common case return stringType; @@ -486,12 +548,14 @@ private static Type NullableUnwrap(Type type) { /// /// Extract the inner type converter from a nullable type converter /// - private static TypeConverter NullableUnwrap(TypeConverter typeConverter) { + private static TypeConverter NullableUnwrap(TypeConverter typeConverter) + { NullableConverter nullableConverter = typeConverter as NullableConverter; return (nullableConverter != null) ? nullableConverter.UnderlyingTypeConverter : typeConverter; } - public static object GetDefaultDataSourceNullValue(Type type) { + public static object GetDefaultDataSourceNullValue(Type type) + { return (type != null && !type.IsValueType) ? null : defaultDataSourceNullValue; } diff --git a/src/System.Windows.Forms/src/misc/CompatibleIComparer.cs b/src/System.Windows.Forms/src/misc/CompatibleIComparer.cs index 557ca04b2c8..d493da3f2d8 100644 --- a/src/System.Windows.Forms/src/misc/CompatibleIComparer.cs +++ b/src/System.Windows.Forms/src/misc/CompatibleIComparer.cs @@ -2,29 +2,36 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Collections.Specialized { +namespace System.Collections.Specialized +{ using Microsoft.Win32; using System.Collections; using System.Runtime.Serialization; using System.Globalization; - internal class BackCompatibleStringComparer : IEqualityComparer { + internal class BackCompatibleStringComparer : IEqualityComparer + { static internal IEqualityComparer Default = new BackCompatibleStringComparer(); - internal BackCompatibleStringComparer() { + internal BackCompatibleStringComparer() + { } //For backcompat - public static int GetHashCode(string obj) { - unsafe { - fixed (char* src = obj) { + public static int GetHashCode(string obj) + { + unsafe + { + fixed (char* src = obj) + { int hash = 5381; int c; char* szStr = src; - while ((c = *szStr) != 0) { + while ((c = *szStr) != 0) + { hash = ((hash << 5) + hash) ^ c; ++szStr; } @@ -33,13 +40,16 @@ public static int GetHashCode(string obj) { } } - bool IEqualityComparer.Equals(object a, object b) { + bool IEqualityComparer.Equals(object a, object b) + { return Object.Equals(a, b); } - public virtual int GetHashCode(object o) { + public virtual int GetHashCode(object o) + { string obj = o as string; - if (obj == null) { + if (obj == null) + { return o.GetHashCode(); } diff --git a/src/System.Windows.Forms/src/misc/CoreSwitches.cs b/src/System.Windows.Forms/src/misc/CoreSwitches.cs index db2e55edbf1..89ca9905240 100644 --- a/src/System.Windows.Forms/src/misc/CoreSwitches.cs +++ b/src/System.Windows.Forms/src/misc/CoreSwitches.cs @@ -2,25 +2,30 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.ComponentModel { +namespace System.ComponentModel +{ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; // Shared between dlls [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal static class CoreSwitches { - - private static BooleanSwitch perfTrack; - - public static BooleanSwitch PerfTrack { + internal static class CoreSwitches + { + + private static BooleanSwitch perfTrack; + + public static BooleanSwitch PerfTrack + { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { - if (perfTrack == null) { - perfTrack = new BooleanSwitch("PERFTRACK", "Debug performance critical sections."); + get + { + if (perfTrack == null) + { + perfTrack = new BooleanSwitch("PERFTRACK", "Debug performance critical sections."); } return perfTrack; } } } -} +} diff --git a/src/System.Windows.Forms/src/misc/DbgUtil.cs b/src/System.Windows.Forms/src/misc/DbgUtil.cs index 662addf354f..88a9325ae46 100644 --- a/src/System.Windows.Forms/src/misc/DbgUtil.cs +++ b/src/System.Windows.Forms/src/misc/DbgUtil.cs @@ -2,15 +2,15 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope="member", Target="System.Windows.Forms.Internal.DbgUtil.AssertFinalization(System.Object,System.Boolean):System.Void")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA902:MovePInvokesToNativeMethodsClass", Scope="member", Target="System.Windows.Forms.Internal.DbgUtil.FormatMessage(System.Int32,System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Text.StringBuilder,System.Int32,System.Runtime.InteropServices.HandleRef):System.Int32")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope="member", Target="System.Windows.Forms.Internal.DbgUtil.FormatMessage(System.Int32,System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Text.StringBuilder,System.Int32,System.Runtime.InteropServices.HandleRef):System.Int32")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope="member", Target="System.Windows.Forms.Internal.DbgUtil.GetLastErrorStr():System.String")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA902:MovePInvokesToNativeMethodsClass", Scope="member", Target="System.Windows.Forms.Internal.DbgUtil.GetUserDefaultLCID():System.Int32")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2205:UseManagedEquivalentsOfWin32Api", Scope="member", Target="System.Windows.Forms.Internal.DbgUtil.GetUserDefaultLCID():System.Int32")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope="member", Target="System.Windows.Forms.Internal.DbgUtil.StackFramesToStr(System.Int32):System.String")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1818:DoNotConcatenateStringsInsideLoops", Scope="member", Target="System.Windows.Forms.Internal.DbgUtil.StackFramesToStr(System.Int32):System.String")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Interoperability", "CA1404:CallGetLastErrorImmediatelyAfterPInvoke", Scope="member", Target="System.Windows.Forms.Internal.DbgUtil.GetLastErrorStr():System.String")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters", Scope = "member", Target = "System.Windows.Forms.Internal.DbgUtil.AssertFinalization(System.Object,System.Boolean):System.Void")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA902:MovePInvokesToNativeMethodsClass", Scope = "member", Target = "System.Windows.Forms.Internal.DbgUtil.FormatMessage(System.Int32,System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Text.StringBuilder,System.Int32,System.Runtime.InteropServices.HandleRef):System.Int32")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "System.Windows.Forms.Internal.DbgUtil.FormatMessage(System.Int32,System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Text.StringBuilder,System.Int32,System.Runtime.InteropServices.HandleRef):System.Int32")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "System.Windows.Forms.Internal.DbgUtil.GetLastErrorStr():System.String")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA902:MovePInvokesToNativeMethodsClass", Scope = "member", Target = "System.Windows.Forms.Internal.DbgUtil.GetUserDefaultLCID():System.Int32")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2205:UseManagedEquivalentsOfWin32Api", Scope = "member", Target = "System.Windows.Forms.Internal.DbgUtil.GetUserDefaultLCID():System.Int32")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "System.Windows.Forms.Internal.DbgUtil.StackFramesToStr(System.Int32):System.String")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1818:DoNotConcatenateStringsInsideLoops", Scope = "member", Target = "System.Windows.Forms.Internal.DbgUtil.StackFramesToStr(System.Int32):System.String")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Interoperability", "CA1404:CallGetLastErrorImmediatelyAfterPInvoke", Scope = "member", Target = "System.Windows.Forms.Internal.DbgUtil.GetLastErrorStr():System.String")] #if DRAWING_DESIGN_NAMESPACE @@ -36,19 +36,19 @@ namespace System.Internal /// internal sealed class DbgUtil { - public const int + public const int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100, - FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200, - FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000, - FORMAT_MESSAGE_DEFAULT = FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM; + FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200, + FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000, + FORMAT_MESSAGE_DEFAULT = FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM; - [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)] + [DllImport(ExternDll.Kernel32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] public static extern int GetUserDefaultLCID(); - [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)] + [DllImport(ExternDll.Kernel32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] public static extern int FormatMessage(int dwFlags, HandleRef lpSource, int dwMessageId, int dwLanguageId, StringBuilder lpBuffer, int nSize, HandleRef arguments); public static int gdipInitMaxFrameCount = 8; -// disable csharp compiler warning #0414: field assigned unused value + // disable csharp compiler warning #0414: field assigned unused value #pragma warning disable 0414 public static int gdiUseMaxFrameCount = 8; public static int finalizeMaxFrameCount = 5; @@ -103,7 +103,7 @@ public static void AssertFinalization(object obj, bool disposing) public static void AssertWin32(bool expression, string message) { #if DEBUG - if( !expression ) + if (!expression) { Debug.Fail(message + "\r\nError: " + DbgUtil.GetLastErrorStr()); } @@ -116,10 +116,10 @@ public static void AssertWin32(bool expression, string message) public static void AssertWin32(bool expression, string format, object arg1) { #if DEBUG - if( !expression ) + if (!expression) { - object[] args = new object[]{ arg1 }; - AssertWin32Impl( expression, format, args ); + object[] args = new object[] { arg1 }; + AssertWin32Impl(expression, format, args); } #endif } @@ -130,10 +130,10 @@ public static void AssertWin32(bool expression, string format, object arg1) public static void AssertWin32(bool expression, string format, object arg1, object arg2) { #if DEBUG - if( !expression ) + if (!expression) { - object[] args = new object[]{ arg1, arg2 }; - AssertWin32Impl( expression, format, args ); + object[] args = new object[] { arg1, arg2 }; + AssertWin32Impl(expression, format, args); } #endif } @@ -144,10 +144,10 @@ public static void AssertWin32(bool expression, string format, object arg1, obje public static void AssertWin32(bool expression, string format, object arg1, object arg2, object arg3) { #if DEBUG - if( !expression ) + if (!expression) { - object[] args = new object[]{ arg1, arg2, arg3 }; - AssertWin32Impl( expression, format, args ); + object[] args = new object[] { arg1, arg2, arg3 }; + AssertWin32Impl(expression, format, args); } #endif } @@ -158,10 +158,10 @@ public static void AssertWin32(bool expression, string format, object arg1, obje public static void AssertWin32(bool expression, string format, object arg1, object arg2, object arg3, object arg4) { #if DEBUG - if( !expression ) + if (!expression) { - object[] args = new object[]{ arg1, arg2, arg3, arg4 }; - AssertWin32Impl( expression, format, args ); + object[] args = new object[] { arg1, arg2, arg3, arg4 }; + AssertWin32Impl(expression, format, args); } #endif } @@ -172,10 +172,10 @@ public static void AssertWin32(bool expression, string format, object arg1, obje public static void AssertWin32(bool expression, string format, object arg1, object arg2, object arg3, object arg4, object arg5) { #if DEBUG - if( !expression ) + if (!expression) { - object[] args = new object[]{ arg1, arg2, arg3, arg4, arg5 }; - AssertWin32Impl( expression, format, args ); + object[] args = new object[] { arg1, arg2, arg3, arg4, arg5 }; + AssertWin32Impl(expression, format, args); } #endif } @@ -186,7 +186,7 @@ public static void AssertWin32(bool expression, string format, object arg1, obje private static void AssertWin32Impl(bool expression, string format, object[] args) { #if DEBUG - if( !expression ) + if (!expression) { string message = string.Format(CultureInfo.CurrentCulture, format, args); Debug.Fail(message + "\r\nError: " + DbgUtil.GetLastErrorStr()); @@ -218,39 +218,39 @@ public static string GetLastErrorStr() { err = Marshal.GetLastWin32Error(); - int retVal = FormatMessage( + int retVal = FormatMessage( FORMAT_MESSAGE_DEFAULT, new HandleRef(null, IntPtr.Zero), err, GetUserDefaultLCID(), buffer, MAX_SIZE, - new HandleRef(null, IntPtr.Zero) ); + new HandleRef(null, IntPtr.Zero)); message = retVal != 0 ? buffer.ToString() : ""; } - catch( Exception ex) + catch (Exception ex) { - if( DbgUtil.IsCriticalException(ex) ) + if (DbgUtil.IsCriticalException(ex)) { throw; //rethrow critical exception. } message = ex.ToString(); - } + } - return string.Format( CultureInfo.CurrentCulture, "0x{0:x8} - {1}", err, message); + return string.Format(CultureInfo.CurrentCulture, "0x{0:x8} - {1}", err, message); } /// /// Duplicated here from ClientUtils not to depend on that code because this class is to be /// compiled into System.Drawing and System.Windows.Forms. /// - private static bool IsCriticalException( Exception ex ) + private static bool IsCriticalException(Exception ex) { - return + return //ex is NullReferenceException || ex is StackOverflowException || - ex is OutOfMemoryException || + ex is OutOfMemoryException || ex is System.Threading.ThreadAbortException; } @@ -268,24 +268,24 @@ public static string StackTrace /// Returns information about the top stack frames in a string format. The input param determines the number of /// frames to include. /// - public static string StackFramesToStr( int maxFrameCount ) + public static string StackFramesToStr(int maxFrameCount) { string trace = string.Empty; try { - StackTrace st = new StackTrace( true ); + StackTrace st = new StackTrace(true); int dbgUtilFrameCount = 0; // // Ignore frames for methods on this library. // Note: The stack frame holds the latest frame at index 0. // - while( dbgUtilFrameCount < st.FrameCount ) + while (dbgUtilFrameCount < st.FrameCount) { StackFrame sf = st.GetFrame(dbgUtilFrameCount); - if( sf == null || sf.GetMethod().DeclaringType != typeof(DbgUtil) ) + if (sf == null || sf.GetMethod().DeclaringType != typeof(DbgUtil)) { break; } @@ -295,23 +295,23 @@ public static string StackFramesToStr( int maxFrameCount ) maxFrameCount += dbgUtilFrameCount; // add ignored frames. - if( maxFrameCount > st.FrameCount ) + if (maxFrameCount > st.FrameCount) { maxFrameCount = st.FrameCount; } - for(int i = dbgUtilFrameCount; i < maxFrameCount; i++ ) + for (int i = dbgUtilFrameCount; i < maxFrameCount; i++) { StackFrame sf = st.GetFrame(i); - if( sf == null ) + if (sf == null) { continue; } MethodBase mi = sf.GetMethod(); - if( mi == null ) + if (mi == null) { continue; } @@ -319,34 +319,34 @@ public static string StackFramesToStr( int maxFrameCount ) string args = string.Empty; string fileName = sf.GetFileName(); - int backSlashIndex = fileName == null ? -1 : fileName.LastIndexOf( '\\' ); + int backSlashIndex = fileName == null ? -1 : fileName.LastIndexOf('\\'); - if( backSlashIndex != -1 ) + if (backSlashIndex != -1) { - fileName = fileName.Substring( backSlashIndex + 1, fileName.Length - backSlashIndex - 1); + fileName = fileName.Substring(backSlashIndex + 1, fileName.Length - backSlashIndex - 1); } - foreach( ParameterInfo pi in mi.GetParameters() ) + foreach (ParameterInfo pi in mi.GetParameters()) { args += pi.ParameterType.Name + ", "; } - if( args.Length > 0 ) // remove last comma. + if (args.Length > 0) // remove last comma. { args = args.Substring(0, args.Length - 2); } - - trace += string.Format(CultureInfo.CurrentCulture, "at {0} {1}.{2}({3})\r\n", fileName, mi.DeclaringType, mi.Name, args ); + + trace += string.Format(CultureInfo.CurrentCulture, "at {0} {1}.{2}({3})\r\n", fileName, mi.DeclaringType, mi.Name, args); } } - catch( Exception ex ) + catch (Exception ex) { - if( DbgUtil.IsCriticalException(ex) ) + if (DbgUtil.IsCriticalException(ex)) { throw; //rethrow critical exception. } trace += ex.ToString(); - } + } return trace.ToString(); } @@ -356,24 +356,24 @@ public static string StackFramesToStr( int maxFrameCount ) /// public static string StackFramesToStr() { - return StackFramesToStr( DbgUtil.gdipInitMaxFrameCount ); + return StackFramesToStr(DbgUtil.gdipInitMaxFrameCount); } /// /// Returns information about the top stack frames in a string format. The input param determines the number of /// frames to include. The 'message' parameter is used as the header of the returned string. /// - public static string StackTraceToStr( string message, int frameCount ) + public static string StackTraceToStr(string message, int frameCount) { - return string.Format( CultureInfo.CurrentCulture, "{0}\r\nTop Stack Trace:\r\n{1}", message, DbgUtil.StackFramesToStr(frameCount)); + return string.Format(CultureInfo.CurrentCulture, "{0}\r\nTop Stack Trace:\r\n{1}", message, DbgUtil.StackFramesToStr(frameCount)); } /// /// Returns information about the top stack frames in a string format. The 'message' parameter is used as the header of the returned string. /// - public static string StackTraceToStr( string message ) + public static string StackTraceToStr(string message) { - return StackTraceToStr(message, DbgUtil.gdipInitMaxFrameCount ); + return StackTraceToStr(message, DbgUtil.gdipInitMaxFrameCount); } } } diff --git a/src/System.Windows.Forms/src/misc/GDI/ApplyGraphicsProperties.cs b/src/System.Windows.Forms/src/misc/GDI/ApplyGraphicsProperties.cs index ec144d45146..e40112d3a71 100644 --- a/src/System.Windows.Forms/src/misc/GDI/ApplyGraphicsProperties.cs +++ b/src/System.Windows.Forms/src/misc/GDI/ApplyGraphicsProperties.cs @@ -26,12 +26,12 @@ namespace System.Experimental.Gdi enum ApplyGraphicsProperties { // No properties to be applied to the DC obtained from the Graphics object. - None = 0x00000000, + None = 0x00000000, // Apply clipping region. - Clipping = 0x00000001, + Clipping = 0x00000001, // Apply coordinate transformation. - TranslateTransform = 0x00000002, + TranslateTransform = 0x00000002, // Apply all supported Graphics properties. - All = Clipping | TranslateTransform + All = Clipping | TranslateTransform } } diff --git a/src/System.Windows.Forms/src/misc/GDI/DeviceCapabilities.cs b/src/System.Windows.Forms/src/misc/GDI/DeviceCapabilities.cs index b6cdba9251f..d4fd2c78f55 100644 --- a/src/System.Windows.Forms/src/misc/GDI/DeviceCapabilities.cs +++ b/src/System.Windows.Forms/src/misc/GDI/DeviceCapabilities.cs @@ -19,26 +19,26 @@ namespace System.Experimental.Gdi internal #endif enum DeviceCapabilities - { + { /* Device Parameters for GetDeviceCaps() */ - DriverVersion = 0, /* device driver version */ - Technology = 2, /* device classification */ - HorizontalSize = 4, /* horizontal size in millimeters */ - VerticalSize = 6, /* vertical size in millimeters */ - HorizontalResolution= 8, /* horizontal width in pixels */ - VerticalResolution = 10, /* vertical height in pixels */ - BitsPerPixel = 12, /* number of bits per pixel */ - LogicalPixelsX = 88, /* Logical pixels/inch in X */ - LogicalPixelsY = 90, /* Logical pixels/inch in Y */ + DriverVersion = 0, /* device driver version */ + Technology = 2, /* device classification */ + HorizontalSize = 4, /* horizontal size in millimeters */ + VerticalSize = 6, /* vertical size in millimeters */ + HorizontalResolution = 8, /* horizontal width in pixels */ + VerticalResolution = 10, /* vertical height in pixels */ + BitsPerPixel = 12, /* number of bits per pixel */ + LogicalPixelsX = 88, /* Logical pixels/inch in X */ + LogicalPixelsY = 90, /* Logical pixels/inch in Y */ // printing related devicecaps. these replace the appropriate escapes - PhysicalWidth = 110, /* physical width in device units */ - PhysicalHeight = 111, /* physical height in device units */ - PhysicalOffsetX = 112, /* physical printable area x margin */ - PhysicalOffsetY = 113, /* physical printable area y margin */ - ScalingFactorX = 114, /* scaling factor x */ - ScalingFactorY = 115, /* scaling factor y */ + PhysicalWidth = 110, /* physical width in device units */ + PhysicalHeight = 111, /* physical height in device units */ + PhysicalOffsetX = 112, /* physical printable area x margin */ + PhysicalOffsetY = 113, /* physical printable area y margin */ + ScalingFactorX = 114, /* scaling factor x */ + ScalingFactorY = 115, /* scaling factor y */ #if CPP_DEFINITIONS /* Device Parameters for GetDeviceCaps() */ diff --git a/src/System.Windows.Forms/src/misc/GDI/DeviceContext.cs b/src/System.Windows.Forms/src/misc/GDI/DeviceContext.cs index a3ecc80ff43..057f7841089 100644 --- a/src/System.Windows.Forms/src/misc/GDI/DeviceContext.cs +++ b/src/System.Windows.Forms/src/misc/GDI/DeviceContext.cs @@ -73,7 +73,7 @@ sealed partial class DeviceContext : MarshalByRefObject, IDeviceContext, IDispos /// See book "Windows Graphics Programming - Feng Yuang", P315 - Device Context Attributes. /// - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] + [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] IntPtr hDC; DeviceContextType dcType; @@ -84,7 +84,7 @@ sealed partial class DeviceContext : MarshalByRefObject, IDeviceContext, IDispos // We cache the hWnd when creating the dc from one, to provide support forIDeviceContext.GetHdc/ReleaseHdc. // This hWnd could be null, in such case it is referring to the screen. [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] - IntPtr hWnd = (IntPtr) (-1); // Unlikely to be a valid hWnd. + IntPtr hWnd = (IntPtr)(-1); // Unlikely to be a valid hWnd. IntPtr hInitialPen; IntPtr hInitialBrush; @@ -96,7 +96,7 @@ sealed partial class DeviceContext : MarshalByRefObject, IDeviceContext, IDispos IntPtr hCurrentBmp; IntPtr hCurrentFont; - Stack contextStack; + Stack contextStack; #if GDI_FINALIZATION_WATCH private string AllocationSite = DbgUtil.StackTrace; @@ -129,13 +129,13 @@ public DeviceContextType DeviceContextType /// public IntPtr Hdc { - - + + get { - if( this.hDC == IntPtr.Zero ) + if (this.hDC == IntPtr.Zero) { - if( this.dcType == DeviceContextType.Display ) + if (this.dcType == DeviceContextType.Display) { Debug.Assert(!this.disposed, "Accessing a disposed DC, forcing recreation of HDC - this will generate a Handle leak!"); @@ -152,7 +152,7 @@ public IntPtr Hdc #endif } - Debug.Assert( this.hDC != IntPtr.Zero, "Attempt to use deleted HDC - DC type: " + this.dcType ); + Debug.Assert(this.hDC != IntPtr.Zero, "Attempt to use deleted HDC - DC type: " + this.dcType); return this.hDC; } @@ -163,41 +163,46 @@ public IntPtr Hdc // we also track which objects are currently selected in the DeviceContext. When // a currently selected object is disposed, it is first replaced in the DC and then // deleted. - - + + private void CacheInitialState() { Debug.Assert(this.hDC != IntPtr.Zero, "Cannot get initial state without a valid HDC"); - hCurrentPen = hInitialPen = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, hDC), IntNativeMethods.OBJ_PEN); + hCurrentPen = hInitialPen = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, hDC), IntNativeMethods.OBJ_PEN); hCurrentBrush = hInitialBrush = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, hDC), IntNativeMethods.OBJ_BRUSH); - hCurrentBmp = hInitialBmp = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, hDC), IntNativeMethods.OBJ_BITMAP); - hCurrentFont = hInitialFont = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, hDC), IntNativeMethods.OBJ_FONT); + hCurrentBmp = hInitialBmp = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, hDC), IntNativeMethods.OBJ_BITMAP); + hCurrentFont = hInitialFont = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, hDC), IntNativeMethods.OBJ_FONT); } - - - public void DeleteObject(IntPtr handle, GdiObjectType type) { + + + public void DeleteObject(IntPtr handle, GdiObjectType type) + { IntPtr handleToDelete = IntPtr.Zero; - switch (type) { + switch (type) + { case GdiObjectType.Pen: - if (handle == hCurrentPen) { - IntPtr currentPen = IntUnsafeNativeMethods.SelectObject(new HandleRef(this, this.Hdc), new HandleRef( this, hInitialPen)); + if (handle == hCurrentPen) + { + IntPtr currentPen = IntUnsafeNativeMethods.SelectObject(new HandleRef(this, this.Hdc), new HandleRef(this, hInitialPen)); Debug.Assert(currentPen == hCurrentPen, "DeviceContext thinks a different pen is selected than the HDC"); hCurrentPen = IntPtr.Zero; } handleToDelete = handle; break; case GdiObjectType.Brush: - if (handle == hCurrentBrush) { - IntPtr currentBrush = IntUnsafeNativeMethods.SelectObject(new HandleRef(this, this.Hdc), new HandleRef( this, hInitialBrush)); + if (handle == hCurrentBrush) + { + IntPtr currentBrush = IntUnsafeNativeMethods.SelectObject(new HandleRef(this, this.Hdc), new HandleRef(this, hInitialBrush)); Debug.Assert(currentBrush == hCurrentBrush, "DeviceContext thinks a different brush is selected than the HDC"); hCurrentBrush = IntPtr.Zero; } handleToDelete = handle; break; case GdiObjectType.Bitmap: - if (handle == hCurrentBmp) { - IntPtr currentBmp = IntUnsafeNativeMethods.SelectObject(new HandleRef(this, this.Hdc), new HandleRef( this, hInitialBmp)); + if (handle == hCurrentBmp) + { + IntPtr currentBmp = IntUnsafeNativeMethods.SelectObject(new HandleRef(this, this.Hdc), new HandleRef(this, hInitialBmp)); Debug.Assert(currentBmp == hCurrentBmp, "DeviceContext thinks a different brush is selected than the HDC"); hCurrentBmp = IntPtr.Zero; } @@ -216,8 +221,8 @@ public void DeleteObject(IntPtr handle, GdiObjectType type) { /// Constructor to contruct a DeviceContext object from an window handle. /// private DeviceContext(IntPtr hWnd) - { - this.hWnd = hWnd; + { + this.hWnd = hWnd; this.dcType = DeviceContextType.Display; DeviceContexts.AddDeviceContext(this); @@ -232,19 +237,19 @@ private DeviceContext(IntPtr hWnd) /// /// Constructor to contruct a DeviceContext object from an existing Win32 device context handle. /// - - + + private DeviceContext(IntPtr hDC, DeviceContextType dcType) - { - this.hDC = hDC; + { + this.hDC = hDC; this.dcType = dcType; CacheInitialState(); DeviceContexts.AddDeviceContext(this); - if( dcType == DeviceContextType.Display ) + if (dcType == DeviceContextType.Display) { - this.hWnd = IntUnsafeNativeMethods.WindowFromDC( new HandleRef( this, this.hDC) ); + this.hWnd = IntUnsafeNativeMethods.WindowFromDC(new HandleRef(this, this.hDC)); } #if TRACK_HDC Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("DeviceContext( hDC=0x{0:X8}, Type={1} )", unchecked((int) hDC), dcType) )); @@ -254,67 +259,67 @@ private DeviceContext(IntPtr hDC, DeviceContextType dcType) /// /// CreateDC creates a DeviceContext object wrapping an hdc created with the Win32 CreateDC function. /// - - + + public static DeviceContext CreateDC(string driverName, string deviceName, string fileName, HandleRef devMode) { // Note: All input params can be null but not at the same time. See MSDN for information. IntPtr hdc = IntUnsafeNativeMethods.CreateDC(driverName, deviceName, fileName, devMode); - return new DeviceContext( hdc, DeviceContextType.NamedDevice ); + return new DeviceContext(hdc, DeviceContextType.NamedDevice); } /// /// CreateIC creates a DeviceContext object wrapping an hdc created with the Win32 CreateIC function. /// - - + + public static DeviceContext CreateIC(string driverName, string deviceName, string fileName, HandleRef devMode) { // Note: All input params can be null but not at the same time. See MSDN for information. - + IntPtr hdc = IntUnsafeNativeMethods.CreateIC(driverName, deviceName, fileName, devMode); - return new DeviceContext( hdc, DeviceContextType.Information ); + return new DeviceContext(hdc, DeviceContextType.Information); } /// /// Creates a DeviceContext object wrapping a memory DC compatible with the specified device. /// - - + + public static DeviceContext FromCompatibleDC(IntPtr hdc) - { - - + { + + // If hdc is null, the function creates a memory DC compatible with the application's current screen. // In this case the thread that calls CreateCompatibleDC owns the HDC that is created. When this thread is destroyed, // the HDC is no longer valid. - IntPtr compatibleDc = IntUnsafeNativeMethods.CreateCompatibleDC( new HandleRef(null, hdc) ); + IntPtr compatibleDc = IntUnsafeNativeMethods.CreateCompatibleDC(new HandleRef(null, hdc)); return new DeviceContext(compatibleDc, DeviceContextType.Memory); } - + /// /// Used for wrapping an existing hdc. In this case, this object doesn't own the hdc /// so calls to GetHdc/ReleaseHdc don't PInvoke into GDI. /// - - + + public static DeviceContext FromHdc(IntPtr hdc) - { - Debug.Assert( hdc != IntPtr.Zero, "hdc == 0" ); + { + Debug.Assert(hdc != IntPtr.Zero, "hdc == 0"); return new DeviceContext(hdc, DeviceContextType.Unknown); } /// /// When hwnd is null, we are getting the screen DC. /// - public static DeviceContext FromHwnd( IntPtr hwnd ) - { + public static DeviceContext FromHwnd(IntPtr hwnd) + { return new DeviceContext(hwnd); } - + ~DeviceContext() { Dispose(false); @@ -339,15 +344,15 @@ internal void Dispose(bool disposing) } this.disposed = true; - + #if !DRAWING_NAMESPACE DisposeFont(disposing); -#endif - - switch( this.dcType ) +#endif + + switch (this.dcType) { case DeviceContextType.Display: - Debug.Assert( disposing, "WARNING: Finalizing a Display DeviceContext.\r\nReleaseDC may fail when not called from the same thread GetDC was called from." ); + Debug.Assert(disposing, "WARNING: Finalizing a Display DeviceContext.\r\nReleaseDC may fail when not called from the same thread GetDC was called from."); ((IDeviceContext)this).ReleaseHdc(); break; @@ -401,14 +406,14 @@ internal void Dispose(bool disposing) /// as a wrapper around an hdc that is always available, and for performance reasons since it caches the hdc /// if used in this way. /// - - + + IntPtr IDeviceContext.GetHdc() { if (this.hDC == IntPtr.Zero) { - Debug.Assert( this.dcType == DeviceContextType.Display, "Calling GetDC from a non display/window device." ); - + Debug.Assert(this.dcType == DeviceContextType.Display, "Calling GetDC from a non display/window device."); + // Note: for common DCs, GetDC assigns default attributes to the DC each time it is retrieved. // For example, the default font is System. this.hDC = IntUnsafeNativeMethods.GetDC(new HandleRef(this, this.hWnd)); @@ -448,11 +453,11 @@ void IDeviceContext.ReleaseHdc() /// public DeviceContextGraphicsMode GraphicsMode { - - + + get { - return (DeviceContextGraphicsMode) IntUnsafeNativeMethods.GetGraphicsMode( new HandleRef( this, this.Hdc ) ); + return (DeviceContextGraphicsMode)IntUnsafeNativeMethods.GetGraphicsMode(new HandleRef(this, this.Hdc)); } #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY set @@ -465,11 +470,11 @@ public DeviceContextGraphicsMode GraphicsMode /// /// Sets the dc graphics mode and returns the old value. /// - - + + public DeviceContextGraphicsMode SetGraphicsMode(DeviceContextGraphicsMode newMode) { - return (DeviceContextGraphicsMode) IntUnsafeNativeMethods.SetGraphicsMode( new HandleRef( this, this.Hdc ), unchecked((int) newMode)); + return (DeviceContextGraphicsMode)IntUnsafeNativeMethods.SetGraphicsMode(new HandleRef(this, this.Hdc), unchecked((int)newMode)); } /// @@ -483,7 +488,7 @@ public DeviceContextGraphicsMode SetGraphicsMode(DeviceContextGraphicsMode newMo /// to the current state. For example, -1 restores the most recently saved state. /// See MSDN for more info. /// - public void RestoreHdc() + public void RestoreHdc() { #if TRACK_HDC bool result = @@ -496,27 +501,31 @@ public void RestoreHdc() #endif Debug.Assert(contextStack != null, "Someone is calling RestoreHdc() before SaveHdc()"); - if (contextStack != null) { - GraphicsState g = (GraphicsState) contextStack.Pop(); - - hCurrentBmp = g.hBitmap; - hCurrentBrush = g.hBrush; - hCurrentPen = g.hPen; - hCurrentFont = g.hFont; + if (contextStack != null) + { + GraphicsState g = (GraphicsState)contextStack.Pop(); + + hCurrentBmp = g.hBitmap; + hCurrentBrush = g.hBrush; + hCurrentPen = g.hPen; + hCurrentFont = g.hFont; #if !DRAWING_NAMESPACE - if (g.font != null && g.font.IsAlive) { - selectedFont = g.font.Target as WindowsFont; + if (g.font != null && g.font.IsAlive) + { + selectedFont = g.font.Target as WindowsFont; } - else { + else + { WindowsFont previousFont = selectedFont; selectedFont = null; - if (previousFont != null && MeasurementDCInfo.IsMeasurementDC(this)) { + if (previousFont != null && MeasurementDCInfo.IsMeasurementDC(this)) + { previousFont.Dispose(); } } #endif - + } #if OPTIMIZED_MEASUREMENTDC @@ -536,33 +545,34 @@ public void RestoreHdc() /// A saved state can be restored by using the RestoreHdc method. /// See MSDN for more details. /// - - - public int SaveHdc() + + + public int SaveHdc() { - HandleRef hdc = new HandleRef( this, this.Hdc); + HandleRef hdc = new HandleRef(this, this.Hdc); int state = IntUnsafeNativeMethods.SaveDC(hdc); - if (contextStack == null) { + if (contextStack == null) + { contextStack = new Stack(); } GraphicsState g = new GraphicsState(); g.hBitmap = hCurrentBmp; - g.hBrush = hCurrentBrush; - g.hPen = hCurrentPen; - g.hFont = hCurrentFont; + g.hBrush = hCurrentBrush; + g.hPen = hCurrentPen; + g.hFont = hCurrentFont; #if !DRAWING_NAMESPACE - g.font = new WeakReference(selectedFont); + g.font = new WeakReference(selectedFont); #endif contextStack.Push(g); - + #if TRACK_HDC Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("state[0]=DC.SaveHdc(hDc=0x{1:x8})", state, unchecked((int) this.hDC)) )); -#endif +#endif return state; } @@ -574,61 +584,65 @@ public int SaveHdc() /// - The SelectClipRgn function assumes that the coordinates for a region are specified in device units. /// - To remove a device-context's clipping region, specify a NULL region handle. /// - - + + public void SetClip(WindowsRegion region) { HandleRef hdc = new HandleRef(this, this.Hdc); HandleRef hRegion = new HandleRef(region, region.HRegion); IntUnsafeNativeMethods.SelectClipRgn(hdc, hRegion); - } + } /// /// Creates a new clipping region from the intersection of the current clipping region and /// the specified rectangle. /// - - + + public void IntersectClip(WindowsRegion wr) { //if the incoming windowsregion is infinite, there is no need to do any intersecting. - if (wr.HRegion == IntPtr.Zero) { + if (wr.HRegion == IntPtr.Zero) + { return; } - WindowsRegion clip = new WindowsRegion(0,0,0,0); - try { - int result = IntUnsafeNativeMethods.GetClipRgn(new HandleRef( this, this.Hdc), new HandleRef(clip, clip.HRegion)); - - // If the function succeeds and there is a clipping region for the given device context, the return value is 1. - if (result == 1) { - Debug.Assert(clip.HRegion != IntPtr.Zero); - wr.CombineRegion(clip, wr, RegionCombineMode.AND); //1 = AND (or Intersect) - } - - SetClip(wr); + WindowsRegion clip = new WindowsRegion(0, 0, 0, 0); + try + { + int result = IntUnsafeNativeMethods.GetClipRgn(new HandleRef(this, this.Hdc), new HandleRef(clip, clip.HRegion)); + + // If the function succeeds and there is a clipping region for the given device context, the return value is 1. + if (result == 1) + { + Debug.Assert(clip.HRegion != IntPtr.Zero); + wr.CombineRegion(clip, wr, RegionCombineMode.AND); //1 = AND (or Intersect) + } + + SetClip(wr); } - finally { - clip.Dispose(); + finally + { + clip.Dispose(); } } /// /// Modifies the viewport origin for a device context using the specified horizontal and vertical offsets in logical units. /// - - - public void TranslateTransform(int dx, int dy) + + + public void TranslateTransform(int dx, int dy) { IntNativeMethods.POINT orgn = new IntNativeMethods.POINT(); - IntUnsafeNativeMethods.OffsetViewportOrgEx( new HandleRef( this, this.Hdc ), dx, dy, orgn ); + IntUnsafeNativeMethods.OffsetViewportOrgEx(new HandleRef(this, this.Hdc), dx, dy, orgn); } /// /// - - + + public override bool Equals(object obj) { DeviceContext other = obj as DeviceContext; @@ -650,15 +664,16 @@ public override bool Equals(object obj) /// /// This allows collections to treat DeviceContext objects wrapping the same HDC as the same objects. /// - - + + public override int GetHashCode() { return this.Hdc.GetHashCode(); } - internal class GraphicsState { + internal class GraphicsState + { internal IntPtr hBrush; internal IntPtr hFont; internal IntPtr hPen; @@ -667,5 +682,5 @@ internal class GraphicsState { internal WeakReference font; #endif } - } + } } diff --git a/src/System.Windows.Forms/src/misc/GDI/DeviceContext2.cs b/src/System.Windows.Forms/src/misc/GDI/DeviceContext2.cs index 94bd7747aae..da7edf9f594 100644 --- a/src/System.Windows.Forms/src/misc/GDI/DeviceContext2.cs +++ b/src/System.Windows.Forms/src/misc/GDI/DeviceContext2.cs @@ -33,15 +33,17 @@ namespace System.Experimental.Gdi sealed partial class DeviceContext : MarshalByRefObject, IDeviceContext, IDisposable { WindowsFont selectedFont; - + /// /// See DeviceContext.cs for information about this class. The class has been split to be able /// to compile the right set of functionalities into different assemblies. /// - - public WindowsFont ActiveFont { - get { + + public WindowsFont ActiveFont + { + get + { return selectedFont; } } @@ -53,7 +55,7 @@ public Color BackgroundColor { get { - return ColorTranslator.FromWin32(IntUnsafeNativeMethods.GetBkColor( new HandleRef( this, this.Hdc ))); + return ColorTranslator.FromWin32(IntUnsafeNativeMethods.GetBkColor(new HandleRef(this, this.Hdc))); } #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY set @@ -66,19 +68,19 @@ public Color BackgroundColor /// /// Sets the DC background color and returns the old value. /// - public Color SetBackgroundColor( Color newColor ) + public Color SetBackgroundColor(Color newColor) { - return ColorTranslator.FromWin32(IntUnsafeNativeMethods.SetBkColor( new HandleRef( this, this.Hdc ), ColorTranslator.ToWin32(newColor))); + return ColorTranslator.FromWin32(IntUnsafeNativeMethods.SetBkColor(new HandleRef(this, this.Hdc), ColorTranslator.ToWin32(newColor))); } /// /// DC background mode. /// - public DeviceContextBackgroundMode BackgroundMode + public DeviceContextBackgroundMode BackgroundMode { get { - return (DeviceContextBackgroundMode) IntUnsafeNativeMethods.GetBkMode( new HandleRef( this, this.Hdc ) ); + return (DeviceContextBackgroundMode)IntUnsafeNativeMethods.GetBkMode(new HandleRef(this, this.Hdc)); } #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY set @@ -91,9 +93,9 @@ public DeviceContextBackgroundMode BackgroundMode /// /// Sets the DC background mode and returns the old value. /// - public DeviceContextBackgroundMode SetBackgroundMode( DeviceContextBackgroundMode newMode ) + public DeviceContextBackgroundMode SetBackgroundMode(DeviceContextBackgroundMode newMode) { - return (DeviceContextBackgroundMode) IntUnsafeNativeMethods.SetBkMode(new HandleRef(this, this.Hdc), (int) newMode); + return (DeviceContextBackgroundMode)IntUnsafeNativeMethods.SetBkMode(new HandleRef(this, this.Hdc), (int)newMode); } @@ -104,7 +106,7 @@ public DeviceContextBinaryRasterOperationFlags BinaryRasterOperation { get { - return (DeviceContextBinaryRasterOperationFlags) IntUnsafeNativeMethods.GetROP2( new HandleRef( this, this.Hdc ) ); + return (DeviceContextBinaryRasterOperationFlags)IntUnsafeNativeMethods.GetROP2(new HandleRef(this, this.Hdc)); } /* * CONSIDER: implement if needed. @@ -120,9 +122,9 @@ public DeviceContextBinaryRasterOperationFlags BinaryRasterOperation /// /// Sets the DC ROP2 and returns the old value. /// - public DeviceContextBinaryRasterOperationFlags SetRasterOperation(DeviceContextBinaryRasterOperationFlags rasterOperation ) + public DeviceContextBinaryRasterOperationFlags SetRasterOperation(DeviceContextBinaryRasterOperationFlags rasterOperation) { - return (DeviceContextBinaryRasterOperationFlags) IntUnsafeNativeMethods.SetROP2(new HandleRef(this, this.Hdc), (int) rasterOperation); + return (DeviceContextBinaryRasterOperationFlags)IntUnsafeNativeMethods.SetROP2(new HandleRef(this, this.Hdc), (int)rasterOperation); } /// @@ -160,34 +162,36 @@ public int DpiY return GetDeviceCapabilities(DeviceCapabilities.LogicalPixelsY); } } - + /// /// The font selected into the device context. /// It's OK to call dispose on it, the HFONT won't be deleted since the WindowsFont did not create it, /// it got it from the HDC. /// - + public WindowsFont Font { - - + + get { #if OPTIMIZED_MEASUREMENTDC - if (MeasurementDCInfo.IsMeasurementDC(this)) - { + if (MeasurementDCInfo.IsMeasurementDC(this)) + { WindowsFont font = MeasurementDCInfo.LastUsedFont; - if (font != null && (font.Hfont != IntPtr.Zero)) { + if (font != null && (font.Hfont != IntPtr.Zero)) + { #if DEBUG - WindowsFont currentDCFont = WindowsFont.FromHdc( this.Hdc ); - if (!font.Equals(currentDCFont) ) { + WindowsFont currentDCFont = WindowsFont.FromHdc(this.Hdc); + if (!font.Equals(currentDCFont)) + { // just use the face name, as ToString will call here re-entrantly. - string lastUsedFontInfo = (font != null) ? font.Name : "null"; - string currentFontInfo = (currentDCFont != null) ? currentDCFont.Name : "null"; + string lastUsedFontInfo = (font != null) ? font.Name : "null"; + string currentFontInfo = (currentDCFont != null) ? currentDCFont.Name : "null"; Debug.Fail("Font does not match... Current: " + currentFontInfo + " Last known: " + lastUsedFontInfo); } - -#endif + +#endif return font; } @@ -196,7 +200,7 @@ public WindowsFont Font // Returns the currently selected object in the dc. // Note: for common DCs, GetDC assigns default attributes to the DC each time it is retrieved, // the default font is System. - return WindowsFont.FromHdc( this.Hdc ); + return WindowsFont.FromHdc(this.Hdc); } #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY set @@ -220,20 +224,24 @@ public static DeviceContext ScreenDC } } - internal void DisposeFont(bool disposing) { - if (disposing) { + internal void DisposeFont(bool disposing) + { + if (disposing) + { DeviceContexts.RemoveDeviceContext(this); - } + } - if (selectedFont != null && selectedFont.Hfont != IntPtr.Zero) { + if (selectedFont != null && selectedFont.Hfont != IntPtr.Zero) + { IntPtr hCurrentFont = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, hDC), IntNativeMethods.OBJ_FONT); - if (hCurrentFont == selectedFont.Hfont) { + if (hCurrentFont == selectedFont.Hfont) + { // select initial font back in - IntUnsafeNativeMethods.SelectObject(new HandleRef(this, this.Hdc), new HandleRef( null, hInitialFont)); + IntUnsafeNativeMethods.SelectObject(new HandleRef(this, this.Hdc), new HandleRef(null, hInitialFont)); hCurrentFont = hInitialFont; } - selectedFont.Dispose(disposing); + selectedFont.Dispose(disposing); selectedFont = null; } } @@ -242,45 +250,47 @@ internal void DisposeFont(bool disposing) { /// Selects the specified object into the dc. If the specified object is the same as the one currently selected /// in the dc, the object is not set and a null value is returned. /// - public IntPtr SelectFont( WindowsFont font ) + public IntPtr SelectFont(WindowsFont font) { - + // Fonts are one of the most expensive objects to select in an hdc and in many cases we are passed a Font that is the // same as the one already selected in the dc so to avoid a perf hit we get the hdc font's log font and compare it // with the one passed in before selecting it in the hdc. // Also, we avoid performing GDI operations that if done on an enhanced metafile DC would add an entry to it, hence // reducing the size of the metafile. - if( font.Equals( this.Font )) + if (font.Equals(this.Font)) { return IntPtr.Zero; } - IntPtr result = SelectObject( font.Hfont, GdiObjectType.Font); + IntPtr result = SelectObject(font.Hfont, GdiObjectType.Font); - WindowsFont previousFont = selectedFont; + WindowsFont previousFont = selectedFont; selectedFont = font; - hCurrentFont = font.Hfont; + hCurrentFont = font.Hfont; // the measurement DC always leaves fonts selected for pref reasons. // in this case, we need to diposse the font since the original // creator didn't fully dispose. - if (previousFont != null) { - if (MeasurementDCInfo.IsMeasurementDC(this)) { + if (previousFont != null) + { + if (MeasurementDCInfo.IsMeasurementDC(this)) + { previousFont.Dispose(); } } - + #if OPTIMIZED_MEASUREMENTDC // once we've changed the font, update the last used font. - if (MeasurementDCInfo.IsMeasurementDC(this)) + if (MeasurementDCInfo.IsMeasurementDC(this)) { - if (result != IntPtr.Zero) + if (result != IntPtr.Zero) { MeasurementDCInfo.LastUsedFont = font; } - else + else { - // there was an error selecting the Font into the DC, we dont know anything about it. - MeasurementDCInfo.Reset(); + // there was an error selecting the Font into the DC, we dont know anything about it. + MeasurementDCInfo.Reset(); } } #endif @@ -289,14 +299,14 @@ public IntPtr SelectFont( WindowsFont font ) public void ResetFont() { - + #if OPTIMIZED_MEASUREMENTDC // in this case, GDI will copy back the previously saved font into the DC. // we dont actually know what the font is in our measurement DC so // we need to clear it off. MeasurementDCInfo.ResetIfIsMeasurementDC(this.Hdc); #endif - IntUnsafeNativeMethods.SelectObject(new HandleRef(this, this.Hdc), new HandleRef( null, hInitialFont )); + IntUnsafeNativeMethods.SelectObject(new HandleRef(this, this.Hdc), new HandleRef(null, hInitialFont)); selectedFont = null; hCurrentFont = hInitialFont; } @@ -304,9 +314,9 @@ public void ResetFont() /// /// Retrieves device-specific information for this device. /// - public int GetDeviceCapabilities( DeviceCapabilities capabilityIndex ) + public int GetDeviceCapabilities(DeviceCapabilities capabilityIndex) { - return IntUnsafeNativeMethods.GetDeviceCaps( new HandleRef( this, this.Hdc ), (int) capabilityIndex ); + return IntUnsafeNativeMethods.GetDeviceCaps(new HandleRef(this, this.Hdc), (int)capabilityIndex); } /// @@ -316,7 +326,7 @@ public DeviceContextMapMode MapMode { get { - return (DeviceContextMapMode) IntUnsafeNativeMethods.GetMapMode( new HandleRef( this, this.Hdc ) ); + return (DeviceContextMapMode)IntUnsafeNativeMethods.GetMapMode(new HandleRef(this, this.Hdc)); } #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY set @@ -328,12 +338,15 @@ public DeviceContextMapMode MapMode public bool IsFontOnContextStack(WindowsFont wf) { - if (contextStack == null) { + if (contextStack == null) + { return false; } - foreach (GraphicsState g in contextStack) { - if (g.hFont == wf.Hfont) { + foreach (GraphicsState g in contextStack) + { + if (g.hFont == wf.Hfont) + { return true; } } @@ -344,9 +357,9 @@ public bool IsFontOnContextStack(WindowsFont wf) /// /// Sets the DC map mode and returns the old value. /// - public DeviceContextMapMode SetMapMode( DeviceContextMapMode newMode ) + public DeviceContextMapMode SetMapMode(DeviceContextMapMode newMode) { - return (DeviceContextMapMode) IntUnsafeNativeMethods.SetMapMode( new HandleRef(this, this.Hdc), (int) newMode ); + return (DeviceContextMapMode)IntUnsafeNativeMethods.SetMapMode(new HandleRef(this, this.Hdc), (int)newMode); } /// @@ -354,7 +367,8 @@ public DeviceContextMapMode SetMapMode( DeviceContextMapMode newMode ) /// public IntPtr SelectObject(IntPtr hObj, GdiObjectType type) { - switch (type) { + switch (type) + { case GdiObjectType.Pen: hCurrentPen = hObj; break; @@ -365,8 +379,8 @@ public IntPtr SelectObject(IntPtr hObj, GdiObjectType type) case GdiObjectType.Bitmap: hCurrentBmp = hObj; break; - } - return IntUnsafeNativeMethods.SelectObject(new HandleRef(this, this.Hdc), new HandleRef( null, hObj)); + } + return IntUnsafeNativeMethods.SelectObject(new HandleRef(this, this.Hdc), new HandleRef(null, hObj)); } /// @@ -376,7 +390,7 @@ public DeviceContextTextAlignment TextAlignment { get { - return (DeviceContextTextAlignment) IntUnsafeNativeMethods.GetTextAlign( new HandleRef( this, this.Hdc ) ); + return (DeviceContextTextAlignment)IntUnsafeNativeMethods.GetTextAlign(new HandleRef(this, this.Hdc)); } #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY set @@ -389,9 +403,9 @@ public DeviceContextTextAlignment TextAlignment /// /// Sets the DC text alignment and returns the old value. /// - public DeviceContextTextAlignment SetTextAlignment( DeviceContextTextAlignment newAligment ) + public DeviceContextTextAlignment SetTextAlignment(DeviceContextTextAlignment newAligment) { - return (DeviceContextTextAlignment) IntUnsafeNativeMethods.SetTextAlign(new HandleRef(this, this.Hdc), (int) newAligment ); + return (DeviceContextTextAlignment)IntUnsafeNativeMethods.SetTextAlign(new HandleRef(this, this.Hdc), (int)newAligment); } @@ -402,7 +416,7 @@ public Color TextColor { get { - return ColorTranslator.FromWin32(IntUnsafeNativeMethods.GetTextColor( new HandleRef( this, this.Hdc ) )); + return ColorTranslator.FromWin32(IntUnsafeNativeMethods.GetTextColor(new HandleRef(this, this.Hdc))); } #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY set @@ -415,9 +429,9 @@ public Color TextColor /// /// Sets the DC text color and returns the old value. /// - public Color SetTextColor( Color newColor ) + public Color SetTextColor(Color newColor) { - return ColorTranslator.FromWin32(IntUnsafeNativeMethods.SetTextColor(new HandleRef( this, this.Hdc), ColorTranslator.ToWin32(newColor))); + return ColorTranslator.FromWin32(IntUnsafeNativeMethods.SetTextColor(new HandleRef(this, this.Hdc), ColorTranslator.ToWin32(newColor))); } /// @@ -428,27 +442,27 @@ public Size ViewportExtent get { IntNativeMethods.SIZE size = new IntNativeMethods.SIZE(); - IntUnsafeNativeMethods.GetViewportExtEx( new HandleRef( this, this.Hdc ), size ); + IntUnsafeNativeMethods.GetViewportExtEx(new HandleRef(this, this.Hdc), size); return size.ToSize(); } - set - { - SetViewportExtent( value ); - } + set + { + SetViewportExtent(value); + } } /// /// Sets the DC Viewport extent to the specified value and returns its previous value; extent values are in device units. /// - public Size SetViewportExtent( Size newExtent ) + public Size SetViewportExtent(Size newExtent) { IntNativeMethods.SIZE oldExtent = new IntNativeMethods.SIZE(); - - IntUnsafeNativeMethods.SetViewportExtEx( new HandleRef( this, this.Hdc ), newExtent.Width, newExtent.Height, oldExtent ); + + IntUnsafeNativeMethods.SetViewportExtEx(new HandleRef(this, this.Hdc), newExtent.Width, newExtent.Height, oldExtent); return oldExtent.ToSize(); - } + } /// /// DC Viewport Origin in device units. @@ -458,27 +472,27 @@ public Point ViewportOrigin get { IntNativeMethods.POINT point = new IntNativeMethods.POINT(); - IntUnsafeNativeMethods.GetViewportOrgEx( new HandleRef( this, this.Hdc ), point ); + IntUnsafeNativeMethods.GetViewportOrgEx(new HandleRef(this, this.Hdc), point); return point.ToPoint(); } - set - { - SetViewportOrigin( value ); - } + set + { + SetViewportOrigin(value); + } } /// /// Sets the DC Viewport origin to the specified value and returns its previous value; origin values are in device units. /// - public Point SetViewportOrigin( Point newOrigin ) + public Point SetViewportOrigin(Point newOrigin) { IntNativeMethods.POINT oldOrigin = new IntNativeMethods.POINT(); - IntUnsafeNativeMethods.SetViewportOrgEx( new HandleRef( this, this.Hdc ), newOrigin.X, newOrigin.Y, oldOrigin ); + IntUnsafeNativeMethods.SetViewportOrgEx(new HandleRef(this, this.Hdc), newOrigin.X, newOrigin.Y, oldOrigin); return oldOrigin.ToPoint(); } - + } } diff --git a/src/System.Windows.Forms/src/misc/GDI/DeviceContextBackgroundMode.cs b/src/System.Windows.Forms/src/misc/GDI/DeviceContextBackgroundMode.cs index 7dcedfabd52..dbb29f180b3 100644 --- a/src/System.Windows.Forms/src/misc/GDI/DeviceContextBackgroundMode.cs +++ b/src/System.Windows.Forms/src/misc/GDI/DeviceContextBackgroundMode.cs @@ -19,7 +19,7 @@ namespace System.Experimental.Gdi internal #endif enum DeviceContextBackgroundMode - { + { Transparent = 1, Opaque = 2 } diff --git a/src/System.Windows.Forms/src/misc/GDI/DeviceContextGraphicsMode.cs b/src/System.Windows.Forms/src/misc/GDI/DeviceContextGraphicsMode.cs index e6d92c21d41..175c9545d6b 100644 --- a/src/System.Windows.Forms/src/misc/GDI/DeviceContextGraphicsMode.cs +++ b/src/System.Windows.Forms/src/misc/GDI/DeviceContextGraphicsMode.cs @@ -19,7 +19,7 @@ namespace System.Experimental.Gdi internal #endif enum DeviceContextGraphicsMode - { + { /* Sets the graphics mode that is compatible with 16-bit Windows. This is the default mode. If this value is specified, the application can only modify the world-to-device transform @@ -36,7 +36,7 @@ and SetWindowExtEx. /// specified device context. In this mode all graphics, including text output, fully /// conform to the world-to-device transformation specified in the device context. /// - Advanced = 2, + Advanced = 2, /* Resets the current world transformation by using the identity matrix. If this mode is specified, diff --git a/src/System.Windows.Forms/src/misc/GDI/DeviceContextLayout.cs b/src/System.Windows.Forms/src/misc/GDI/DeviceContextLayout.cs index 06b8a32ad25..ca27174924d 100644 --- a/src/System.Windows.Forms/src/misc/GDI/DeviceContextLayout.cs +++ b/src/System.Windows.Forms/src/misc/GDI/DeviceContextLayout.cs @@ -22,7 +22,7 @@ namespace System.Experimental.Gdi internal #endif enum DeviceContextLayout - { + { /// /// Right to left. /// @@ -37,7 +37,7 @@ enum DeviceContextLayout /// Bottom to top. LAYOUT_BTT /// BottomToTop = 0x00000002, - + /// /// Vertical before horizontal. LAYOUT_VBH /// diff --git a/src/System.Windows.Forms/src/misc/GDI/DeviceContextMapMode.cs b/src/System.Windows.Forms/src/misc/GDI/DeviceContextMapMode.cs index 0fc1256901a..cb68f67e0a6 100644 --- a/src/System.Windows.Forms/src/misc/GDI/DeviceContextMapMode.cs +++ b/src/System.Windows.Forms/src/misc/GDI/DeviceContextMapMode.cs @@ -19,15 +19,15 @@ namespace System.Experimental.Gdi internal #endif enum DeviceContextMapMode - { - Text = 1, // MM_TEXT - LoMetric = 2, - HiMetric = 3, - LoEnglish = 4, - HiEnglish = 5, - Twips = 6, - Isotropic = 7, - Anisotropic = 8 + { + Text = 1, // MM_TEXT + LoMetric = 2, + HiMetric = 3, + LoEnglish = 4, + HiEnglish = 5, + Twips = 6, + Isotropic = 7, + Anisotropic = 8 /* Mapping Mode Logical Unit x-axis y-axis diff --git a/src/System.Windows.Forms/src/misc/GDI/DeviceContextRasterOperationFlags.cs b/src/System.Windows.Forms/src/misc/GDI/DeviceContextRasterOperationFlags.cs index 548b4bf424b..b7c23d19218 100644 --- a/src/System.Windows.Forms/src/misc/GDI/DeviceContextRasterOperationFlags.cs +++ b/src/System.Windows.Forms/src/misc/GDI/DeviceContextRasterOperationFlags.cs @@ -22,23 +22,23 @@ namespace System.Experimental.Gdi internal #endif enum DeviceContextBinaryRasterOperationFlags - { - Black = 1, // 0 - NotMergePen = 2, // dpon - MaskNotPen = 3, // dpna - NotCopyPen = 4, // pn - MaskPenNot = 5, // pdna - Not = 6, // dn - XorPen = 7, // dpx - NotMaskPen = 8, // dpan - MaskPen = 9, // dpa - NotXorPen = 10, // dpxn - Nop = 11, // d - MergeNotPen = 12, // dpno - CopyPen = 13, // p - MergePenNot = 14, // pdno - MergePen = 15, // dpo - White = 16, // 1 + { + Black = 1, // 0 + NotMergePen = 2, // dpon + MaskNotPen = 3, // dpna + NotCopyPen = 4, // pn + MaskPenNot = 5, // pdna + Not = 6, // dn + XorPen = 7, // dpx + NotMaskPen = 8, // dpan + MaskPen = 9, // dpa + NotXorPen = 10, // dpxn + Nop = 11, // d + MergeNotPen = 12, // dpno + CopyPen = 13, // p + MergePenNot = 14, // pdno + MergePen = 15, // dpo + White = 16, // 1 // Binary raster operations. /* @@ -58,6 +58,6 @@ enum DeviceContextBinaryRasterOperationFlags R2_MERGEPENNOT = 14, // PDno R2_MERGEPEN = 15, // DPo R2_WHITE = 16, // 1 - */ + */ } } diff --git a/src/System.Windows.Forms/src/misc/GDI/DeviceContextTextAlignment.cs b/src/System.Windows.Forms/src/misc/GDI/DeviceContextTextAlignment.cs index 049e6387d33..eedadd5c2af 100644 --- a/src/System.Windows.Forms/src/misc/GDI/DeviceContextTextAlignment.cs +++ b/src/System.Windows.Forms/src/misc/GDI/DeviceContextTextAlignment.cs @@ -19,17 +19,17 @@ namespace System.Experimental.Gdi internal #endif enum DeviceContextTextAlignment - { - BaseLine = 24, // TA_BASELINE The reference point is on the base line of the text. - Bottom = 8, // TA_BOTTOM The reference point is on the bottom edge of the bounding rectangle. - Top = 0, // TA_TOP The reference point is on the top edge of the bounding rectangle. - Center = 6, // TA_CENTER The reference point is aligned horizontally with the center of the bounding rectangle. - Default = 0, // Top, Left, NoUpdateCP - Left = 0, // TA_LEFT The reference point is on the left edge of the bounding rectangle. - Right = 2, // TA_RIGHT The reference point is on the right edge of the bounding rectangle. - RtlReading = 256, // TA_RTLREADING Middle East language edition of Windows: The text is laid out in right to left reading order, as opposed to the default left to right order. This only applies when the font selected into the device context is either Hebrew or Arabic. - NoUpdateCP = 0, // TA_NOUPDATECP The current position is not updated after each text output call. - UpdateCP = 1, // TA_UPDATECP The current position is updated after each text output call. + { + BaseLine = 24, // TA_BASELINE The reference point is on the base line of the text. + Bottom = 8, // TA_BOTTOM The reference point is on the bottom edge of the bounding rectangle. + Top = 0, // TA_TOP The reference point is on the top edge of the bounding rectangle. + Center = 6, // TA_CENTER The reference point is aligned horizontally with the center of the bounding rectangle. + Default = 0, // Top, Left, NoUpdateCP + Left = 0, // TA_LEFT The reference point is on the left edge of the bounding rectangle. + Right = 2, // TA_RIGHT The reference point is on the right edge of the bounding rectangle. + RtlReading = 256, // TA_RTLREADING Middle East language edition of Windows: The text is laid out in right to left reading order, as opposed to the default left to right order. This only applies when the font selected into the device context is either Hebrew or Arabic. + NoUpdateCP = 0, // TA_NOUPDATECP The current position is not updated after each text output call. + UpdateCP = 1, // TA_UPDATECP The current position is updated after each text output call. // When the current font has a vertical default base line (as with Kanji), the following values are used instead of TA_BASELINE and TA_CENTER. // Value Meaning diff --git a/src/System.Windows.Forms/src/misc/GDI/DeviceContextType.cs b/src/System.Windows.Forms/src/misc/GDI/DeviceContextType.cs index 5e1012b2e39..59eba40faf7 100644 --- a/src/System.Windows.Forms/src/misc/GDI/DeviceContextType.cs +++ b/src/System.Windows.Forms/src/misc/GDI/DeviceContextType.cs @@ -21,13 +21,13 @@ namespace System.Experimental.Gdi enum DeviceContextType { // Unknown device - Unknown = 0x00, - + Unknown = 0x00, + // Display DC - obtained from GetDC/GetDCEx/BeginPaint. - Display = 0x01, + Display = 0x01, // Window DC including non-client area - obtained from GetWindowDC - NCWindow = 0x02, + NCWindow = 0x02, // Printer DC - obtained from CreateDC. NamedDevice = 0x03, @@ -36,10 +36,10 @@ enum DeviceContextType Information = 0x04, // Memory dc - obtained from CreateCompatibleDC. - Memory = 0x05, + Memory = 0x05, // Metafile dc - obtained from CreateEnhMetafile. - Metafile = 0x06 // currently not supported. + Metafile = 0x06 // currently not supported. } } diff --git a/src/System.Windows.Forms/src/misc/GDI/DeviceContexts.cs b/src/System.Windows.Forms/src/misc/GDI/DeviceContexts.cs index 20620e0cef9..e61ba168e76 100644 --- a/src/System.Windows.Forms/src/misc/GDI/DeviceContexts.cs +++ b/src/System.Windows.Forms/src/misc/GDI/DeviceContexts.cs @@ -34,20 +34,23 @@ namespace System.Experimental.Gdi #endif static class DeviceContexts { - [ThreadStatic] + [ThreadStatic] private static ClientUtils.WeakRefCollection activeDeviceContexts; /// /// WindowsGraphicsCacheManager needs to track DeviceContext /// objects so it can ask them if a font is in use before they /// it's deleted. - internal static void AddDeviceContext(DeviceContext dc) { - if (activeDeviceContexts == null) { + internal static void AddDeviceContext(DeviceContext dc) + { + if (activeDeviceContexts == null) + { activeDeviceContexts = new ClientUtils.WeakRefCollection(); activeDeviceContexts.RefCheckThreshold = 20; } - if (!activeDeviceContexts.Contains(dc)) { + if (!activeDeviceContexts.Contains(dc)) + { dc.Disposing += new EventHandler(OnDcDisposing); activeDeviceContexts.Add(dc); } @@ -63,30 +66,36 @@ private static void OnDcDisposing(object sender, EventArgs e) RemoveDeviceContext(dc); } } - - internal static void RemoveDeviceContext(DeviceContext dc) { - if (activeDeviceContexts == null) { + + internal static void RemoveDeviceContext(DeviceContext dc) + { + if (activeDeviceContexts == null) + { return; } activeDeviceContexts.RemoveByHashCode(dc); } - #if !DRAWING_NAMESPACE - internal static bool IsFontInUse(WindowsFont wf) { - if (wf == null) { +#if !DRAWING_NAMESPACE + internal static bool IsFontInUse(WindowsFont wf) + { + if (wf == null) + { return false; } - - for (int i = 0; i < activeDeviceContexts.Count; i++) { + + for (int i = 0; i < activeDeviceContexts.Count; i++) + { DeviceContext dc = activeDeviceContexts[i] as DeviceContext; - if (dc != null && (dc.ActiveFont == wf || dc.IsFontOnContextStack(wf))) { + if (dc != null && (dc.ActiveFont == wf || dc.IsFontOnContextStack(wf))) + { return true; } } return false; } - #endif - +#endif + } } diff --git a/src/System.Windows.Forms/src/misc/GDI/FxCopSuppression.cs b/src/System.Windows.Forms/src/misc/GDI/FxCopSuppression.cs index 5a116171746..eb5ee387d66 100644 --- a/src/System.Windows.Forms/src/misc/GDI/FxCopSuppression.cs +++ b/src/System.Windows.Forms/src/misc/GDI/FxCopSuppression.cs @@ -13,84 +13,84 @@ #if DRAWING_DESIGN_NAMESPACE ////////////////////////////////// FxCop suppressions for System.Windows.Forms.dll ////////////////////////////////// -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.DeviceContext.CreateDC(System.String,System.String,System.String,System.Runtime.InteropServices.HandleRef):System.Windows.Forms.Internal.DeviceContext")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.DeviceContext.CreateIC(System.String,System.String,System.String,System.Runtime.InteropServices.HandleRef):System.Windows.Forms.Internal.DeviceContext")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.DeviceContext.get_DeviceContextType():System.Windows.Forms.Internal.DeviceContextType")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.DeviceContext.get_DpiX():System.Int32")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.DeviceContext.TranslateTransform(System.Single,System.Single):System.Void")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.IntNativeMethods+POINT.ToPoint():System.Drawing.Point")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.IntNativeMethods+RECT.ToRectangle():System.Drawing.Rectangle")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.IntNativeMethods+SIZE.ToSize():System.Drawing.Size")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.IntSafeNativeMethods.GdiFlush():System.Boolean")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.IntSafeNativeMethods.GetUserDefaultLCID():System.Int32")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.IntUnsafeNativeMethods.IntArc(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.IntUnsafeNativeMethods.IntCreateDC(System.String,System.String,System.String,System.Runtime.InteropServices.HandleRef):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.IntUnsafeNativeMethods.IntCreateDIBSection(System.Runtime.InteropServices.HandleRef,System.Windows.Forms.Internal.IntNativeMethods+BITMAPINFO&,System.Int32,System.IntPtr&,System.IntPtr,System.Int32):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.IntUnsafeNativeMethods.IntCreateIC(System.String,System.String,System.String,System.Runtime.InteropServices.HandleRef):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.IntUnsafeNativeMethods.IntGetObject(System.Runtime.InteropServices.HandleRef,System.Int32,System.Windows.Forms.Internal.IntNativeMethods+LOGBRUSH):System.Int32")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.IntUnsafeNativeMethods.IntGetObject(System.Runtime.InteropServices.HandleRef,System.Windows.Forms.Internal.IntNativeMethods+LOGBRUSH):System.Int32")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.WindowsFont.ToString():System.String")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.WindowsGraphics.DrawText(System.String,System.Drawing.Point):System.Void")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.WindowsGraphics.DrawText(System.String,System.Drawing.Point,System.Drawing.Color):System.Void")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.DeviceContext.get_Font():System.Windows.Forms.Internal.WindowsFont")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.WindowsFont.FromHdc(System.IntPtr):System.Windows.Forms.Internal.WindowsFont")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.WindowsFont.FromHfont(System.IntPtr):System.Windows.Forms.Internal.WindowsFont")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.WindowsFont.FromHfont(System.IntPtr,System.Boolean):System.Windows.Forms.Internal.WindowsFont")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.WindowsFont.get_Italic():System.Boolean")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.WindowsGraphics.FromHwnd(System.IntPtr):System.Windows.Forms.Internal.WindowsGraphics")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.DeviceContext.get_GraphicsMode():System.Windows.Forms.Internal.DeviceContextGraphicsMode")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.DeviceContext.SetGraphicsMode(System.Windows.Forms.Internal.DeviceContextGraphicsMode):System.Windows.Forms.Internal.DeviceContextGraphicsMode")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.IntUnsafeNativeMethods.Arc(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32):System.Boolean")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.IntUnsafeNativeMethods.CreateDC(System.String,System.String,System.String,System.Runtime.InteropServices.HandleRef):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.IntUnsafeNativeMethods.CreateDIBSection(System.Runtime.InteropServices.HandleRef,System.Windows.Forms.Internal.IntNativeMethods+BITMAPINFO&,System.Int32,System.IntPtr&,System.IntPtr,System.Int32):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.IntUnsafeNativeMethods.CreateIC(System.String,System.String,System.String,System.Runtime.InteropServices.HandleRef):System.IntPtr")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.IntUnsafeNativeMethods.GetGraphicsMode(System.Runtime.InteropServices.HandleRef):System.Int32")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.IntUnsafeNativeMethods.GetObject(System.Runtime.InteropServices.HandleRef,System.Windows.Forms.Internal.IntNativeMethods+LOGBRUSH):System.Int32")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.IntUnsafeNativeMethods.IntSetGraphicsMode(System.Runtime.InteropServices.HandleRef,System.Int32):System.Int32")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.IntUnsafeNativeMethods.SetGraphicsMode(System.Runtime.InteropServices.HandleRef,System.Int32):System.Int32")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Control+ImeModeConversion.get_ChineseTable():System.Windows.Forms.ImeMode[]")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.DeviceContext.CreateDC(System.String,System.String,System.String,System.Runtime.InteropServices.HandleRef):System.Windows.Forms.Internal.DeviceContext")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.DeviceContext.CreateIC(System.String,System.String,System.String,System.Runtime.InteropServices.HandleRef):System.Windows.Forms.Internal.DeviceContext")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.DeviceContext.get_DeviceContextType():System.Windows.Forms.Internal.DeviceContextType")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.DeviceContext.get_DpiX():System.Int32")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.DeviceContext.TranslateTransform(System.Single,System.Single):System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.IntNativeMethods+POINT.ToPoint():System.Drawing.Point")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.IntNativeMethods+RECT.ToRectangle():System.Drawing.Rectangle")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.IntNativeMethods+SIZE.ToSize():System.Drawing.Size")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.IntSafeNativeMethods.GdiFlush():System.Boolean")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.IntSafeNativeMethods.GetUserDefaultLCID():System.Int32")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.IntUnsafeNativeMethods.IntArc(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.IntUnsafeNativeMethods.IntCreateDC(System.String,System.String,System.String,System.Runtime.InteropServices.HandleRef):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.IntUnsafeNativeMethods.IntCreateDIBSection(System.Runtime.InteropServices.HandleRef,System.Windows.Forms.Internal.IntNativeMethods+BITMAPINFO&,System.Int32,System.IntPtr&,System.IntPtr,System.Int32):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.IntUnsafeNativeMethods.IntCreateIC(System.String,System.String,System.String,System.Runtime.InteropServices.HandleRef):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.IntUnsafeNativeMethods.IntGetObject(System.Runtime.InteropServices.HandleRef,System.Int32,System.Windows.Forms.Internal.IntNativeMethods+LOGBRUSH):System.Int32")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.IntUnsafeNativeMethods.IntGetObject(System.Runtime.InteropServices.HandleRef,System.Windows.Forms.Internal.IntNativeMethods+LOGBRUSH):System.Int32")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsFont.ToString():System.String")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsGraphics.DrawText(System.String,System.Drawing.Point):System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsGraphics.DrawText(System.String,System.Drawing.Point,System.Drawing.Color):System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.DeviceContext.get_Font():System.Windows.Forms.Internal.WindowsFont")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsFont.FromHdc(System.IntPtr):System.Windows.Forms.Internal.WindowsFont")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsFont.FromHfont(System.IntPtr):System.Windows.Forms.Internal.WindowsFont")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsFont.FromHfont(System.IntPtr,System.Boolean):System.Windows.Forms.Internal.WindowsFont")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsFont.get_Italic():System.Boolean")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsGraphics.FromHwnd(System.IntPtr):System.Windows.Forms.Internal.WindowsGraphics")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.DeviceContext.get_GraphicsMode():System.Windows.Forms.Internal.DeviceContextGraphicsMode")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.DeviceContext.SetGraphicsMode(System.Windows.Forms.Internal.DeviceContextGraphicsMode):System.Windows.Forms.Internal.DeviceContextGraphicsMode")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.IntUnsafeNativeMethods.Arc(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32):System.Boolean")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.IntUnsafeNativeMethods.CreateDC(System.String,System.String,System.String,System.Runtime.InteropServices.HandleRef):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.IntUnsafeNativeMethods.CreateDIBSection(System.Runtime.InteropServices.HandleRef,System.Windows.Forms.Internal.IntNativeMethods+BITMAPINFO&,System.Int32,System.IntPtr&,System.IntPtr,System.Int32):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.IntUnsafeNativeMethods.CreateIC(System.String,System.String,System.String,System.Runtime.InteropServices.HandleRef):System.IntPtr")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.IntUnsafeNativeMethods.GetGraphicsMode(System.Runtime.InteropServices.HandleRef):System.Int32")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.IntUnsafeNativeMethods.GetObject(System.Runtime.InteropServices.HandleRef,System.Windows.Forms.Internal.IntNativeMethods+LOGBRUSH):System.Int32")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.IntUnsafeNativeMethods.IntSetGraphicsMode(System.Runtime.InteropServices.HandleRef,System.Int32):System.Int32")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.IntUnsafeNativeMethods.SetGraphicsMode(System.Runtime.InteropServices.HandleRef,System.Int32):System.Int32")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Control+ImeModeConversion.get_ChineseTable():System.Windows.Forms.ImeMode[]")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Drawing.Internal.IntNativeMethods+RECT..ctor(System.Drawing.Rectangle)")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Drawing.Internal.IntNativeMethods+RECT..ctor(System.Int32,System.Int32,System.Int32,System.Int32)")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Drawing.Internal.IntNativeMethods+POINT..ctor(System.Int32,System.Int32)")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Drawing.Internal.IntUnsafeNativeMethods.IntersectClipRect(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32,System.Int32):System.Drawing.Internal.IntNativeMethods+RegionFlags")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Drawing.Internal.IntUnsafeNativeMethods.IntIntersectClipRect(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32,System.Int32):System.Drawing.Internal.IntNativeMethods+RegionFlags")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.Internal.IntNativeMethods+RECT..ctor(System.Drawing.Rectangle)")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.Internal.IntNativeMethods+RECT..ctor(System.Int32,System.Int32,System.Int32,System.Int32)")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.Internal.IntNativeMethods+POINT..ctor(System.Int32,System.Int32)")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.Internal.IntUnsafeNativeMethods.IntersectClipRect(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32,System.Int32):System.Drawing.Internal.IntNativeMethods+RegionFlags")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.Internal.IntUnsafeNativeMethods.IntIntersectClipRect(System.Runtime.InteropServices.HandleRef,System.Int32,System.Int32,System.Int32,System.Int32):System.Drawing.Internal.IntNativeMethods+RegionFlags")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Scope="type", Target="System.Windows.Forms.Internal.IntNativeMethods+BITMAPINFO")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Scope="type", Target="System.Windows.Forms.Internal.IntSafeNativeMethods+CommonHandles")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Scope = "type", Target = "System.Windows.Forms.Internal.IntNativeMethods+BITMAPINFO")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Scope = "type", Target = "System.Windows.Forms.Internal.IntSafeNativeMethods+CommonHandles")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Scope="member", Target="System.Windows.Forms.Internal.IntSafeNativeMethods+CommonHandles..cctor()")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Scope="member", Target="System.Windows.Forms.Internal.WindowsGraphicsCacheManager..cctor()")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Scope = "member", Target = "System.Windows.Forms.Internal.IntSafeNativeMethods+CommonHandles..cctor()")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsGraphicsCacheManager..cctor()")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Scope="member", Target="System.Windows.Forms.Internal.WindowsGraphics.FillRectangle(System.Windows.Forms.Internal.WindowsBrush,System.Int32,System.Int32,System.Int32,System.Int32):System.Void")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Scope="member", Target="System.Windows.Forms.Internal.WindowsBrush.FromBrush(System.Drawing.Brush):System.Windows.Forms.Internal.WindowsBrush")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsGraphics.FillRectangle(System.Windows.Forms.Internal.WindowsBrush,System.Int32,System.Int32,System.Int32,System.Int32):System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsBrush.FromBrush(System.Drawing.Brush):System.Windows.Forms.Internal.WindowsBrush")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1803:AvoidCostlyCallsWherePossible", Scope="member", Target="System.Windows.Forms.Internal.WindowsGraphics.get_TextPadding():System.Windows.Forms.Internal.TextPaddingOptions")] -[assembly: SuppressMessage("Microsoft.Performance", "CA1803:AvoidCostlyCallsWherePossible", Scope="member", Target="System.Windows.Forms.Internal.WindowsGraphics.set_TextPadding(System.Windows.Forms.Internal.TextPaddingOptions):System.Void")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1803:AvoidCostlyCallsWherePossible", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsGraphics.get_TextPadding():System.Windows.Forms.Internal.TextPaddingOptions")] +[assembly: SuppressMessage("Microsoft.Performance", "CA1803:AvoidCostlyCallsWherePossible", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsGraphics.set_TextPadding(System.Windows.Forms.Internal.TextPaddingOptions):System.Void")] -[assembly: SuppressMessage("Microsoft.Usage", "CA2205:UseManagedEquivalentsOfWin32Api", Scope="member", Target="System.Windows.Forms.Internal.IntSafeNativeMethods.GetUserDefaultLCID():System.Int32")] -[assembly: SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", Scope="member", Target="System.Windows.Forms.Internal.WindowsGraphics.Dispose():System.Void")] +[assembly: SuppressMessage("Microsoft.Usage", "CA2205:UseManagedEquivalentsOfWin32Api", Scope = "member", Target = "System.Windows.Forms.Internal.IntSafeNativeMethods.GetUserDefaultLCID():System.Int32")] +[assembly: SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsGraphics.Dispose():System.Void")] -[assembly: SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", Scope="member", Target="System.Windows.Forms.Internal.WindowsGraphics.GetOverhangPadding(System.Windows.Forms.Internal.WindowsFont,System.Boolean):System.Int32")] -[assembly: SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Scope="member", Target="System.Windows.Forms.Internal.WindowsFont.ToString():System.String")] +[assembly: SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsGraphics.GetOverhangPadding(System.Windows.Forms.Internal.WindowsFont,System.Boolean):System.Int32")] +[assembly: SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsFont.ToString():System.String")] -[assembly: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope="member", Target="System.Windows.Forms.Internal.WindowsGraphics.Dispose(System.Boolean):System.Void")] -[assembly: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope="member", Target="System.Windows.Forms.Internal.WindowsGraphicsCacheManager.OnApplicationExit(System.Object,System.EventArgs):System.Void")] -[assembly: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope="member", Target="System.Windows.Forms.Internal.WindowsGraphicsCacheManager.OnThreadExit(System.Object,System.EventArgs):System.Void")] +[assembly: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsGraphics.Dispose(System.Boolean):System.Void")] +[assembly: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsGraphicsCacheManager.OnApplicationExit(System.Object,System.EventArgs):System.Void")] +[assembly: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsGraphicsCacheManager.OnThreadExit(System.Object,System.EventArgs):System.Void")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Internal.WindowsBrush.nativeHandle")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Internal.WindowsFont.hFont")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Internal.WindowsPen.nativeHandle")] -[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope="member", Target="System.Windows.Forms.Internal.WindowsBitmap.nativeHandle")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsBrush.nativeHandle")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsFont.hFont")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsPen.nativeHandle")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsBitmap.nativeHandle")] // These are debug calls -[assembly: SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Scope="member", Target="System.Windows.Forms.Control.get_CanEnableIme():System.Boolean")] -[assembly: SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Scope="member", Target="System.Windows.Forms.Control.ImeModeRestricted(System.Boolean,System.Boolean):System.Void")] -[assembly: SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Scope="member", Target="System.Windows.Forms.Control.WmImeNotify(System.Windows.Forms.Message&):System.Void")] -[assembly: SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Scope="member", Target="System.Windows.Forms.Control+ImeContext.SetOpenStatus(System.Boolean,System.IntPtr):System.Void")] -[assembly: SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Scope="member", Target="System.Windows.Forms.Control+ImeContext.SetImeStatus(System.Windows.Forms.ImeMode,System.IntPtr):System.Void")] -[assembly: SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Scope="member", Target="System.Windows.Forms.Control+ImeContext.TraceImeStatus(System.IntPtr):System.Void")] -[assembly: SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Scope="member", Target="System.Windows.Forms.Control+ImeContext.TraceImeStatus(System.IntPtr):System.Void")] +[assembly: SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Scope = "member", Target = "System.Windows.Forms.Control.get_CanEnableIme():System.Boolean")] +[assembly: SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Scope = "member", Target = "System.Windows.Forms.Control.ImeModeRestricted(System.Boolean,System.Boolean):System.Void")] +[assembly: SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Scope = "member", Target = "System.Windows.Forms.Control.WmImeNotify(System.Windows.Forms.Message&):System.Void")] +[assembly: SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Scope = "member", Target = "System.Windows.Forms.Control+ImeContext.SetOpenStatus(System.Boolean,System.IntPtr):System.Void")] +[assembly: SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Scope = "member", Target = "System.Windows.Forms.Control+ImeContext.SetImeStatus(System.Windows.Forms.ImeMode,System.IntPtr):System.Void")] +[assembly: SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Scope = "member", Target = "System.Windows.Forms.Control+ImeContext.TraceImeStatus(System.IntPtr):System.Void")] +[assembly: SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Scope = "member", Target = "System.Windows.Forms.Control+ImeContext.TraceImeStatus(System.IntPtr):System.Void")] namespace System.Windows.Forms.Internal diff --git a/src/System.Windows.Forms/src/misc/GDI/GdiObjectType.cs b/src/System.Windows.Forms/src/misc/GDI/GdiObjectType.cs index 9376f95d81f..afee12e2267 100644 --- a/src/System.Windows.Forms/src/misc/GDI/GdiObjectType.cs +++ b/src/System.Windows.Forms/src/misc/GDI/GdiObjectType.cs @@ -19,21 +19,21 @@ namespace System.Experimental.Gdi internal #endif enum GdiObjectType - { - Pen = 1, - Brush = 2, - DisplayDC = 3, - MetafileDC = 4, - Palette = 5, - Font = 6, - Bitmap = 7, - Region = 8, - Metafile = 9, - MemoryDC = 10, - ExtendedPen = 11, - EnhancedMetafileDC = 12, - EnhMetafile = 13, - ColorSpace = 14 + { + Pen = 1, + Brush = 2, + DisplayDC = 3, + MetafileDC = 4, + Palette = 5, + Font = 6, + Bitmap = 7, + Region = 8, + Metafile = 9, + MemoryDC = 10, + ExtendedPen = 11, + EnhancedMetafileDC = 12, + EnhMetafile = 13, + ColorSpace = 14 /* OBJ_PEN = 1, diff --git a/src/System.Windows.Forms/src/misc/GDI/MeasurementDCInfo.cs b/src/System.Windows.Forms/src/misc/GDI/MeasurementDCInfo.cs index c88cadaa278..355a7efa483 100644 --- a/src/System.Windows.Forms/src/misc/GDI/MeasurementDCInfo.cs +++ b/src/System.Windows.Forms/src/misc/GDI/MeasurementDCInfo.cs @@ -9,7 +9,8 @@ #endif #if DRAWING_DESIGN_NAMESPACE -namespace System.Windows.Forms.Internal { +namespace System.Windows.Forms.Internal +{ #elif DRAWING_NAMESPACE namespace System.Drawing.Internal { #else @@ -20,7 +21,8 @@ namespace System.Experimental.Gdi { #else internal #endif - static class MeasurementDCInfo { + static class MeasurementDCInfo + { /// MeasurementDCInfo /// This class optimizes the MeasurmentGraphics as it caches in the last used font and TextMargins used. @@ -29,52 +31,53 @@ static class MeasurementDCInfo { /// DataGridView with lots of text, etc. /// To turn it on for your DLL, use the OPTIMIZED_MEASUREMENTDC compiler switch and add this class to the sources. - [ThreadStatic] - private static CachedInfo cachedMeasurementDCInfo; + [ThreadStatic] + private static CachedInfo cachedMeasurementDCInfo; - /// IsMeasurementDC - /// Returns whether the IDeviceContext passed in is our static MeasurementDC. - /// If it is, we know a bit more information about it. - internal static bool IsMeasurementDC(DeviceContext dc) - { - WindowsGraphics sharedGraphics = WindowsGraphicsCacheManager.GetCurrentMeasurementGraphics(); + /// IsMeasurementDC + /// Returns whether the IDeviceContext passed in is our static MeasurementDC. + /// If it is, we know a bit more information about it. + internal static bool IsMeasurementDC(DeviceContext dc) + { + WindowsGraphics sharedGraphics = WindowsGraphicsCacheManager.GetCurrentMeasurementGraphics(); return sharedGraphics != null && sharedGraphics.DeviceContext != null && sharedGraphics.DeviceContext.Hdc == dc.Hdc; - } + } - /// LastUsedFont - - /// Returns the font we think was last selected into the MeasurementGraphics. - /// - internal static WindowsFont LastUsedFont - { - get - { - return (cachedMeasurementDCInfo == null) ? null : cachedMeasurementDCInfo.LastUsedFont; - } - set - { - if (cachedMeasurementDCInfo == null) - { - cachedMeasurementDCInfo = new CachedInfo(); - } - cachedMeasurementDCInfo.UpdateFont(value); - } - } + /// LastUsedFont - + /// Returns the font we think was last selected into the MeasurementGraphics. + /// + internal static WindowsFont LastUsedFont + { + get + { + return (cachedMeasurementDCInfo == null) ? null : cachedMeasurementDCInfo.LastUsedFont; + } + set + { + if (cachedMeasurementDCInfo == null) + { + cachedMeasurementDCInfo = new CachedInfo(); + } + cachedMeasurementDCInfo.UpdateFont(value); + } + } - /// GetTextMargins - checks to see if we have cached information about the current font, - /// returns info about it. - /// An MRU of Font margins was considered, but seems like overhead. - internal static IntNativeMethods.DRAWTEXTPARAMS GetTextMargins(WindowsGraphics wg, WindowsFont font) { + /// GetTextMargins - checks to see if we have cached information about the current font, + /// returns info about it. + /// An MRU of Font margins was considered, but seems like overhead. + internal static IntNativeMethods.DRAWTEXTPARAMS GetTextMargins(WindowsGraphics wg, WindowsFont font) + { // PERF: operate on a local reference rather than party directly on the thread static one. CachedInfo currentCachedInfo = cachedMeasurementDCInfo; - - if (currentCachedInfo != null && currentCachedInfo.LeftTextMargin >0 && currentCachedInfo.RightTextMargin >0 && font == currentCachedInfo.LastUsedFont) + + if (currentCachedInfo != null && currentCachedInfo.LeftTextMargin > 0 && currentCachedInfo.RightTextMargin > 0 && font == currentCachedInfo.LastUsedFont) { // we have to return clones as DrawTextEx will modify this struct - return new IntNativeMethods.DRAWTEXTPARAMS(currentCachedInfo.LeftTextMargin,currentCachedInfo.RightTextMargin); + return new IntNativeMethods.DRAWTEXTPARAMS(currentCachedInfo.LeftTextMargin, currentCachedInfo.RightTextMargin); } - else if (currentCachedInfo == null) + else if (currentCachedInfo == null) { currentCachedInfo = new CachedInfo(); cachedMeasurementDCInfo = currentCachedInfo; @@ -82,49 +85,52 @@ internal static IntNativeMethods.DRAWTEXTPARAMS GetTextMargins(WindowsGraphics w IntNativeMethods.DRAWTEXTPARAMS drawTextParams = wg.GetTextMargins(font); currentCachedInfo.LeftTextMargin = drawTextParams.iLeftMargin; currentCachedInfo.RightTextMargin = drawTextParams.iRightMargin; - + // returning a copy here to be consistent with the return value from the cache. - return new IntNativeMethods.DRAWTEXTPARAMS(currentCachedInfo.LeftTextMargin,currentCachedInfo.RightTextMargin); - - } + return new IntNativeMethods.DRAWTEXTPARAMS(currentCachedInfo.LeftTextMargin, currentCachedInfo.RightTextMargin); + + } - internal static void ResetIfIsMeasurementDC(IntPtr hdc) { - WindowsGraphics sharedGraphics = WindowsGraphicsCacheManager.GetCurrentMeasurementGraphics(); - if (sharedGraphics != null && sharedGraphics.DeviceContext != null && sharedGraphics.DeviceContext.Hdc == hdc) { - CachedInfo currentCachedInfo = cachedMeasurementDCInfo; - if (currentCachedInfo != null) - { + internal static void ResetIfIsMeasurementDC(IntPtr hdc) + { + WindowsGraphics sharedGraphics = WindowsGraphicsCacheManager.GetCurrentMeasurementGraphics(); + if (sharedGraphics != null && sharedGraphics.DeviceContext != null && sharedGraphics.DeviceContext.Hdc == hdc) + { + CachedInfo currentCachedInfo = cachedMeasurementDCInfo; + if (currentCachedInfo != null) + { currentCachedInfo.UpdateFont(null); - } - } - } - /// Reset - /// clear the current cached information about the measurement dc. - internal static void Reset() { - CachedInfo currentCachedInfo = cachedMeasurementDCInfo; - if (currentCachedInfo != null) - { + } + } + } + /// Reset + /// clear the current cached information about the measurement dc. + internal static void Reset() + { + CachedInfo currentCachedInfo = cachedMeasurementDCInfo; + if (currentCachedInfo != null) + { currentCachedInfo.UpdateFont(null); - } - } - /// CachedInfo - /// store all the thread statics together so we dont have to fetch individual fields out of TLS - private sealed class CachedInfo - { + } + } + /// CachedInfo + /// store all the thread statics together so we dont have to fetch individual fields out of TLS + private sealed class CachedInfo + { public WindowsFont LastUsedFont; - public int LeftTextMargin; + public int LeftTextMargin; public int RightTextMargin; - - internal void UpdateFont(WindowsFont font) + + internal void UpdateFont(WindowsFont font) { - if (LastUsedFont != font) + if (LastUsedFont != font) { LastUsedFont = font; LeftTextMargin = -1; - RightTextMargin = -1; + RightTextMargin = -1; } } - } + } } } #endif // OPTIMIZED_MEASUREMENTDC diff --git a/src/System.Windows.Forms/src/misc/GDI/NativeMethods.cs b/src/System.Windows.Forms/src/misc/GDI/NativeMethods.cs index 104902a84bb..6e54622913b 100644 --- a/src/System.Windows.Forms/src/misc/GDI/NativeMethods.cs +++ b/src/System.Windows.Forms/src/misc/GDI/NativeMethods.cs @@ -24,79 +24,80 @@ namespace System.Experimental.Gdi #else internal #endif - partial class IntNativeMethods { + partial class IntNativeMethods + { public const int - DT_TOP = 0x00000000, - DT_LEFT = 0x00000000, - DT_CENTER = 0x00000001, - DT_RIGHT = 0x00000002, - DT_VCENTER = 0x00000004, - DT_BOTTOM = 0x00000008, - DT_WORDBREAK = 0x00000010, - DT_SINGLELINE = 0x00000020, - DT_EXPANDTABS = 0x00000040, - DT_TABSTOP = 0x00000080, - DT_NOCLIP = 0x00000100, - DT_EXTERNALLEADING = 0x00000200, - DT_CALCRECT = 0x00000400, - DT_NOPREFIX = 0x00000800, - DT_INTERNAL = 0x00001000, - DT_EDITCONTROL = 0x00002000, - DT_PATH_ELLIPSIS = 0x00004000, - DT_END_ELLIPSIS = 0x00008000, - DT_MODIFYSTRING = 0x00010000, - DT_RTLREADING = 0x00020000, - DT_WORD_ELLIPSIS = 0x00040000, - DT_NOFULLWIDTHCHARBREAK = 0x00080000, - DT_HIDEPREFIX = 0x00100000, - DT_PREFIXONLY = 0x00200000, - - DIB_RGB_COLORS = 0, - BI_BITFIELDS = 3, - BI_RGB = 0, + DT_TOP = 0x00000000, + DT_LEFT = 0x00000000, + DT_CENTER = 0x00000001, + DT_RIGHT = 0x00000002, + DT_VCENTER = 0x00000004, + DT_BOTTOM = 0x00000008, + DT_WORDBREAK = 0x00000010, + DT_SINGLELINE = 0x00000020, + DT_EXPANDTABS = 0x00000040, + DT_TABSTOP = 0x00000080, + DT_NOCLIP = 0x00000100, + DT_EXTERNALLEADING = 0x00000200, + DT_CALCRECT = 0x00000400, + DT_NOPREFIX = 0x00000800, + DT_INTERNAL = 0x00001000, + DT_EDITCONTROL = 0x00002000, + DT_PATH_ELLIPSIS = 0x00004000, + DT_END_ELLIPSIS = 0x00008000, + DT_MODIFYSTRING = 0x00010000, + DT_RTLREADING = 0x00020000, + DT_WORD_ELLIPSIS = 0x00040000, + DT_NOFULLWIDTHCHARBREAK = 0x00080000, + DT_HIDEPREFIX = 0x00100000, + DT_PREFIXONLY = 0x00200000, + + DIB_RGB_COLORS = 0, + BI_BITFIELDS = 3, + BI_RGB = 0, BITMAPINFO_MAX_COLORSIZE = 256, SPI_GETICONTITLELOGFONT = 0x001F, SPI_GETNONCLIENTMETRICS = 41, - DEFAULT_GUI_FONT = 17, - HOLLOW_BRUSH = 5, - - BITSPIXEL = 12, - ALTERNATE = 1, - WINDING = 2, - - SRCCOPY = 0x00CC0020, - SRCPAINT = 0x00EE0086, /* dest = source OR dest */ - SRCAND = 0x008800C6, /* dest = source AND dest */ - SRCINVERT = 0x00660046, /* dest = source XOR dest */ - SRCERASE = 0x00440328, /* dest = source AND (NOT dest ) */ - NOTSRCCOPY = 0x00330008, /* dest = (NOT source) */ - NOTSRCERASE = 0x001100A6, /* dest = (NOT src) AND (NOT dest) */ - MERGECOPY = 0x00C000CA, /* dest = (source AND pattern) */ - MERGEPAINT = 0x00BB0226, /* dest = (NOT source) OR dest */ - PATCOPY = 0x00F00021, /* dest = pattern */ - PATPAINT = 0x00FB0A09, /* dest = DPSnoo */ - PATINVERT = 0x005A0049, /* dest = pattern XOR dest */ - DSTINVERT = 0x00550009, /* dest = (NOT dest) */ - BLACKNESS = 0x00000042, /* dest = BLACK */ - WHITENESS = 0x00FF0062, /* dest = WHITE */ - CAPTUREBLT = 0x40000000, /* Include layered windows */ - - + DEFAULT_GUI_FONT = 17, + HOLLOW_BRUSH = 5, + + BITSPIXEL = 12, + ALTERNATE = 1, + WINDING = 2, + + SRCCOPY = 0x00CC0020, + SRCPAINT = 0x00EE0086, /* dest = source OR dest */ + SRCAND = 0x008800C6, /* dest = source AND dest */ + SRCINVERT = 0x00660046, /* dest = source XOR dest */ + SRCERASE = 0x00440328, /* dest = source AND (NOT dest ) */ + NOTSRCCOPY = 0x00330008, /* dest = (NOT source) */ + NOTSRCERASE = 0x001100A6, /* dest = (NOT src) AND (NOT dest) */ + MERGECOPY = 0x00C000CA, /* dest = (source AND pattern) */ + MERGEPAINT = 0x00BB0226, /* dest = (NOT source) OR dest */ + PATCOPY = 0x00F00021, /* dest = pattern */ + PATPAINT = 0x00FB0A09, /* dest = DPSnoo */ + PATINVERT = 0x005A0049, /* dest = pattern XOR dest */ + DSTINVERT = 0x00550009, /* dest = (NOT dest) */ + BLACKNESS = 0x00000042, /* dest = BLACK */ + WHITENESS = 0x00FF0062, /* dest = WHITE */ + CAPTUREBLT = 0x40000000, /* Include layered windows */ + + /* FONT WEIGHT (BOLD) VALUES */ - FW_DONTCARE = 0, - FW_NORMAL = 400, - FW_BOLD = 700, + FW_DONTCARE = 0, + FW_NORMAL = 400, + FW_BOLD = 700, // some others... /* FONT CHARACTER SET */ - ANSI_CHARSET = 0, - DEFAULT_CHARSET = 1, + ANSI_CHARSET = 0, + DEFAULT_CHARSET = 1, // plus others .... /* Font OutPrecision */ - OUT_DEFAULT_PRECIS = 0, - OUT_TT_PRECIS = 4, - OUT_TT_ONLY_PRECIS = 7, + OUT_DEFAULT_PRECIS = 0, + OUT_TT_PRECIS = 4, + OUT_TT_ONLY_PRECIS = 7, // some others... /* Font clip precision */ @@ -113,23 +114,23 @@ public const int CLEARTYPE_NATURAL_QUALITY = 6, /* Object Definitions for GetCurrentObject() and others. */ - OBJ_PEN = 1, - OBJ_BRUSH = 2, - OBJ_DC = 3, - OBJ_METADC = 4, -// OBJ_PAL = 5, - OBJ_FONT = 6, - OBJ_BITMAP = 7, -// OBJ_REGION = 8, -// OBJ_METAFILE = 9, - OBJ_MEMDC = 10, - OBJ_EXTPEN = 11, + OBJ_PEN = 1, + OBJ_BRUSH = 2, + OBJ_DC = 3, + OBJ_METADC = 4, + // OBJ_PAL = 5, + OBJ_FONT = 6, + OBJ_BITMAP = 7, + // OBJ_REGION = 8, + // OBJ_METAFILE = 9, + OBJ_MEMDC = 10, + OBJ_EXTPEN = 11, OBJ_ENHMETADC = 12, -// OBJ_ENHMETAFILE = 13, -// OBJ_COLORSPACE = 14 + // OBJ_ENHMETAFILE = 13, + // OBJ_COLORSPACE = 14 // Brush styles - BS_SOLID = 0, + BS_SOLID = 0, BS_HATCHED = 2, // BS_PATTERN = 3, // some others... @@ -139,28 +140,28 @@ public const int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100, - FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200, - FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000, - FORMAT_MESSAGE_DEFAULT = FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM; + FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200, + FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000, + FORMAT_MESSAGE_DEFAULT = FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM; // some others... - public enum RegionFlags + public enum RegionFlags { - ERROR = 0, - NULLREGION = 1, - SIMPLEREGION = 2, - COMPLEXREGION = 3, + ERROR = 0, + NULLREGION = 1, + SIMPLEREGION = 2, + COMPLEXREGION = 3, } - + [StructLayout(LayoutKind.Sequential)] - public struct RECT + public struct RECT { public int left; public int top; public int right; public int bottom; - public RECT(int left, int top, int right, int bottom) + public RECT(int left, int top, int right, int bottom) { this.left = left; this.top = top; @@ -176,7 +177,7 @@ public RECT(System.Drawing.Rectangle r) this.bottom = r.Bottom; } - public static RECT FromXYWH(int x, int y, int width, int height) + public static RECT FromXYWH(int x, int y, int width, int height) { return new RECT( x, @@ -185,9 +186,9 @@ public static RECT FromXYWH(int x, int y, int width, int height) y + height); } - public Size Size + public Size Size { - get + get { return new Size(this.right - this.left, this.bottom - this.top); } @@ -211,16 +212,16 @@ public override string ToString() } [StructLayout(LayoutKind.Sequential)] - public class POINT + public class POINT { public int x; public int y; - public POINT() + public POINT() { } - public POINT(int x, int y) + public POINT(int x, int y) { this.x = x; this.y = y; @@ -237,10 +238,10 @@ public override string ToString() } #endif } - + [StructLayout(LayoutKind.Sequential)] - public class DRAWTEXTPARAMS - { + public class DRAWTEXTPARAMS + { private int cbSize = Marshal.SizeOf(); public int iTabLength; public int iLeftMargin; @@ -263,7 +264,7 @@ public DRAWTEXTPARAMS(DRAWTEXTPARAMS original) this.iTabLength = original.iTabLength; } - public DRAWTEXTPARAMS(int leftMargin, int rightMargin ) + public DRAWTEXTPARAMS(int leftMargin, int rightMargin) { this.iLeftMargin = leftMargin; this.iRightMargin = rightMargin; @@ -278,15 +279,15 @@ public override string ToString() } [StructLayout(LayoutKind.Sequential)] - public class LOGBRUSH + public class LOGBRUSH { public int lbStyle; public int lbColor; public int lbHatch; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - public class LOGFONT + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public class LOGFONT { public int lfHeight; public int lfWidth; @@ -301,31 +302,31 @@ public class LOGFONT public byte lfClipPrecision; public byte lfQuality; public byte lfPitchAndFamily; - [MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=32)] - public string lfFaceName; + [MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 32)] + public string lfFaceName; public LOGFONT() { } - public LOGFONT( LOGFONT lf ) + public LOGFONT(LOGFONT lf) { - Debug.Assert( lf != null, "lf is null" ); - - this.lfHeight = lf.lfHeight; - this.lfWidth = lf.lfWidth; - this.lfEscapement = lf.lfEscapement; - this.lfOrientation = lf.lfOrientation; - this.lfWeight = lf.lfWeight; - this.lfItalic = lf.lfItalic; - this.lfUnderline = lf.lfUnderline; - this.lfStrikeOut = lf.lfStrikeOut; - this.lfCharSet = lf.lfCharSet; - this.lfOutPrecision = lf.lfOutPrecision; - this.lfClipPrecision = lf.lfClipPrecision; - this.lfQuality = lf.lfQuality; - this.lfPitchAndFamily = lf.lfPitchAndFamily; - this.lfFaceName = lf.lfFaceName; + Debug.Assert(lf != null, "lf is null"); + + this.lfHeight = lf.lfHeight; + this.lfWidth = lf.lfWidth; + this.lfEscapement = lf.lfEscapement; + this.lfOrientation = lf.lfOrientation; + this.lfWeight = lf.lfWeight; + this.lfItalic = lf.lfItalic; + this.lfUnderline = lf.lfUnderline; + this.lfStrikeOut = lf.lfStrikeOut; + this.lfCharSet = lf.lfCharSet; + this.lfOutPrecision = lf.lfOutPrecision; + this.lfClipPrecision = lf.lfClipPrecision; + this.lfQuality = lf.lfQuality; + this.lfPitchAndFamily = lf.lfPitchAndFamily; + this.lfFaceName = lf.lfFaceName; } #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY @@ -363,56 +364,56 @@ public string DumpObject() #endif } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] - public struct TEXTMETRIC - { - public int tmHeight; - public int tmAscent; - public int tmDescent; - public int tmInternalLeading; - public int tmExternalLeading; - public int tmAveCharWidth; - public int tmMaxCharWidth; - public int tmWeight; - public int tmOverhang; - public int tmDigitizedAspectX; - public int tmDigitizedAspectY; - public char tmFirstChar; - public char tmLastChar; - public char tmDefaultChar; - public char tmBreakChar; - public byte tmItalic; - public byte tmUnderlined; - public byte tmStruckOut; - public byte tmPitchAndFamily; - public byte tmCharSet; + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct TEXTMETRIC + { + public int tmHeight; + public int tmAscent; + public int tmDescent; + public int tmInternalLeading; + public int tmExternalLeading; + public int tmAveCharWidth; + public int tmMaxCharWidth; + public int tmWeight; + public int tmOverhang; + public int tmDigitizedAspectX; + public int tmDigitizedAspectY; + public char tmFirstChar; + public char tmLastChar; + public char tmDefaultChar; + public char tmBreakChar; + public byte tmItalic; + public byte tmUnderlined; + public byte tmStruckOut; + public byte tmPitchAndFamily; + public byte tmCharSet; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)] - public struct TEXTMETRICA - { - public int tmHeight; - public int tmAscent; - public int tmDescent; - public int tmInternalLeading; - public int tmExternalLeading; - public int tmAveCharWidth; - public int tmMaxCharWidth; - public int tmWeight; - public int tmOverhang; - public int tmDigitizedAspectX; - public int tmDigitizedAspectY; - public byte tmFirstChar; - public byte tmLastChar; - public byte tmDefaultChar; - public byte tmBreakChar; - public byte tmItalic; - public byte tmUnderlined; - public byte tmStruckOut; - public byte tmPitchAndFamily; - public byte tmCharSet; + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct TEXTMETRICA + { + public int tmHeight; + public int tmAscent; + public int tmDescent; + public int tmInternalLeading; + public int tmExternalLeading; + public int tmAveCharWidth; + public int tmMaxCharWidth; + public int tmWeight; + public int tmOverhang; + public int tmDigitizedAspectX; + public int tmDigitizedAspectY; + public byte tmFirstChar; + public byte tmLastChar; + public byte tmDefaultChar; + public byte tmBreakChar; + public byte tmItalic; + public byte tmUnderlined; + public byte tmStruckOut; + public byte tmPitchAndFamily; + public byte tmCharSet; } - + [StructLayout(LayoutKind.Sequential)] public class SIZE { diff --git a/src/System.Windows.Forms/src/misc/GDI/SafeNativeMethods.cs b/src/System.Windows.Forms/src/misc/GDI/SafeNativeMethods.cs index abb14bcd673..37b406b228c 100644 --- a/src/System.Windows.Forms/src/misc/GDI/SafeNativeMethods.cs +++ b/src/System.Windows.Forms/src/misc/GDI/SafeNativeMethods.cs @@ -10,7 +10,7 @@ namespace System.Drawing.Internal namespace System.Experimental.Gdi #endif { - using System; + using System; using System.Text; using System.Runtime.InteropServices; using System.ComponentModel; @@ -26,16 +26,16 @@ namespace System.Experimental.Gdi #else internal #endif - static partial class IntSafeNativeMethods + static partial class IntSafeNativeMethods { // Brush. - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, EntryPoint = "CreateSolidBrush", CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateSolidBrush", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + private static extern IntPtr IntCreateSolidBrush(int crColor); - - - public static IntPtr CreateSolidBrush(int crColor) + + + public static IntPtr CreateSolidBrush(int crColor) { IntPtr hBrush = Interop.HandleCollector.Add(IntCreateSolidBrush(crColor), Interop.CommonHandles.GDI); DbgUtil.AssertWin32(hBrush != IntPtr.Zero, "IntCreateSolidBrush(color={0}) failed.", crColor); @@ -44,11 +44,11 @@ public static IntPtr CreateSolidBrush(int crColor) // Pen. - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, EntryPoint = "CreatePen", CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreatePen", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + private static extern IntPtr IntCreatePen(int fnStyle, int nWidth, int crColor); - - + + public static IntPtr CreatePen(int fnStyle, int nWidth, int crColor) { IntPtr hPen = Interop.HandleCollector.Add(IntCreatePen(fnStyle, nWidth, crColor), Interop.CommonHandles.GDI); @@ -56,11 +56,11 @@ public static IntPtr CreatePen(int fnStyle, int nWidth, int crColor) return hPen; } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, EntryPoint = "ExtCreatePen", CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "ExtCreatePen", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + private static extern IntPtr IntExtCreatePen(int fnStyle, int dwWidth, IntNativeMethods.LOGBRUSH lplb, int dwStyleCount, [MarshalAs(UnmanagedType.LPArray)] int[] lpStyle); - - + + public static IntPtr ExtCreatePen(int fnStyle, int dwWidth, IntNativeMethods.LOGBRUSH lplb, int dwStyleCount, int[] lpStyle) { IntPtr hPen = Interop.HandleCollector.Add(IntExtCreatePen(fnStyle, dwWidth, lplb, dwStyleCount, lpStyle), Interop.CommonHandles.GDI); @@ -70,12 +70,12 @@ public static IntPtr ExtCreatePen(int fnStyle, int dwWidth, IntNativeMethods.LOG // Region - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreateRectRgn", CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateRectRgn", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern IntPtr IntCreateRectRgn(int x1, int y1, int x2, int y2); - - - public static IntPtr CreateRectRgn(int x1, int y1, int x2, int y2) + + + public static IntPtr CreateRectRgn(int x1, int y1, int x2, int y2) { IntPtr hRgn = Interop.HandleCollector.Add(IntCreateRectRgn(x1, y1, x2, y2), Interop.CommonHandles.GDI); DbgUtil.AssertWin32(hRgn != IntPtr.Zero, "IntCreateRectRgn([x1={0}, y1={1}, x2={2}, y2={3}]) failed.", x1, y1, x2, y2); @@ -83,13 +83,13 @@ public static IntPtr CreateRectRgn(int x1, int y1, int x2, int y2) } // Misc. - - [DllImport(ExternDll.Kernel32, SetLastError=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + + [DllImport(ExternDll.Kernel32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern int GetUserDefaultLCID(); - - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern bool GdiFlush(); } } diff --git a/src/System.Windows.Forms/src/misc/GDI/TextPaddingOptions.cs b/src/System.Windows.Forms/src/misc/GDI/TextPaddingOptions.cs index 21aaa7df91e..5c70966425b 100644 --- a/src/System.Windows.Forms/src/misc/GDI/TextPaddingOptions.cs +++ b/src/System.Windows.Forms/src/misc/GDI/TextPaddingOptions.cs @@ -28,7 +28,7 @@ enum TextPaddingOptions // observe that the lower left part of the letter is clipped. Also, try selecting the letter, // both the lower-left and the upper-right parts are clipped. // The default value. - GlyphOverhangPadding = 0x00000000, + GlyphOverhangPadding = 0x00000000, NoPadding = 0x00000001, diff --git a/src/System.Windows.Forms/src/misc/GDI/UnsafeNativeMethods.cs b/src/System.Windows.Forms/src/misc/GDI/UnsafeNativeMethods.cs index d3d3d68a3a7..4c0b0352dc1 100644 --- a/src/System.Windows.Forms/src/misc/GDI/UnsafeNativeMethods.cs +++ b/src/System.Windows.Forms/src/misc/GDI/UnsafeNativeMethods.cs @@ -24,14 +24,15 @@ namespace System.Experimental.Gdi #else internal #endif - static partial class IntUnsafeNativeMethods + static partial class IntUnsafeNativeMethods { - [DllImport(ExternDll.User32, SetLastError=true, ExactSpelling=true, EntryPoint="GetDC", CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetDC", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern IntPtr IntGetDC(HandleRef hWnd); - - - public static IntPtr GetDC(HandleRef hWnd) { + + + public static IntPtr GetDC(HandleRef hWnd) + { IntPtr hdc = Interop.HandleCollector.Add(IntGetDC(hWnd), Interop.CommonHandles.HDC); DbgUtil.AssertWin32(hdc != IntPtr.Zero, "GetHdc([hWnd=0x{0:X8}]) failed.", hWnd); return hdc; @@ -42,37 +43,40 @@ public static IntPtr GetDC(HandleRef hWnd) { /// deleted with DeleteHDC. /// [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "DeleteDC", CharSet = CharSet.Auto)] - + public static extern bool IntDeleteDC(HandleRef hDC); - public static bool DeleteDC(HandleRef hDC) { + public static bool DeleteDC(HandleRef hDC) + { Interop.HandleCollector.Remove((IntPtr)hDC, Interop.CommonHandles.GDI); bool retVal = IntDeleteDC(hDC); DbgUtil.AssertWin32(retVal, "DeleteDC([hdc=0x{0:X8}]) failed.", hDC.Handle); return retVal; } - public static bool DeleteHDC(HandleRef hDC) { + public static bool DeleteHDC(HandleRef hDC) + { Interop.HandleCollector.Remove((IntPtr)hDC, Interop.CommonHandles.HDC); bool retVal = IntDeleteDC(hDC); DbgUtil.AssertWin32(retVal, "DeleteHDC([hdc=0x{0:X8}]) failed.", hDC.Handle); return retVal; } - [DllImport(ExternDll.User32, SetLastError=true, ExactSpelling=true, EntryPoint="ReleaseDC", CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, EntryPoint = "ReleaseDC", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern int IntReleaseDC(HandleRef hWnd, HandleRef hDC); - public static int ReleaseDC(HandleRef hWnd, HandleRef hDC) { + public static int ReleaseDC(HandleRef hWnd, HandleRef hDC) + { Interop.HandleCollector.Remove((IntPtr)hDC, Interop.CommonHandles.HDC); // Note: retVal == 0 means it was not released but doesn't necessarily means an error; class or private DCs are never released. return IntReleaseDC(hWnd, hDC); } [SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments")] - [DllImport(ExternDll.Gdi32, SetLastError=true, EntryPoint="CreateDC", CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, EntryPoint = "CreateDC", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern IntPtr IntCreateDC(string lpszDriverName, string lpszDeviceName, string lpszOutput, HandleRef /*DEVMODE*/ lpInitData); - - - public static IntPtr CreateDC(string lpszDriverName, string lpszDeviceName, string lpszOutput, HandleRef /*DEVMODE*/ lpInitData) + + + public static IntPtr CreateDC(string lpszDriverName, string lpszDeviceName, string lpszOutput, HandleRef /*DEVMODE*/ lpInitData) { IntPtr hdc = Interop.HandleCollector.Add(IntCreateDC(lpszDriverName, lpszDeviceName, lpszOutput, lpInitData), Interop.CommonHandles.HDC); DbgUtil.AssertWin32(hdc != IntPtr.Zero, "CreateDC([driverName={0}], [deviceName={1}], [fileName={2}], [devMode={3}]) failed.", lpszDriverName, lpszDeviceName, lpszOutput, lpInitData.Handle); @@ -80,12 +84,12 @@ public static IntPtr CreateDC(string lpszDriverName, string lpszDeviceName, stri } [SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments")] - [DllImport(ExternDll.Gdi32, SetLastError=true, EntryPoint="CreateIC", CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, EntryPoint = "CreateIC", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern IntPtr IntCreateIC(string lpszDriverName, string lpszDeviceName, string lpszOutput, HandleRef /*DEVMODE*/ lpInitData); - - - public static IntPtr CreateIC(string lpszDriverName, string lpszDeviceName, string lpszOutput, HandleRef /*DEVMODE*/ lpInitData) + + + public static IntPtr CreateIC(string lpszDriverName, string lpszDeviceName, string lpszOutput, HandleRef /*DEVMODE*/ lpInitData) { IntPtr hdc = Interop.HandleCollector.Add(IntCreateIC(lpszDriverName, lpszDeviceName, lpszOutput, lpInitData), Interop.CommonHandles.HDC); DbgUtil.AssertWin32(hdc != IntPtr.Zero, "CreateIC([driverName={0}], [deviceName={1}], [fileName={2}], [devMode={3}]) failed.", lpszDriverName, lpszDeviceName, lpszOutput, lpInitData.Handle); @@ -97,10 +101,10 @@ public static IntPtr CreateIC(string lpszDriverName, string lpszDeviceName, stri /// The hdc obtained from this method needs to be deleted with DeleteDC instead of DeleteHDC. /// [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateCompatibleDC", CharSet = CharSet.Auto)] - + public static extern IntPtr IntCreateCompatibleDC(HandleRef hDC); - - + + public static IntPtr CreateCompatibleDC(HandleRef hDC) { IntPtr compatibleDc = Interop.HandleCollector.Add(IntCreateCompatibleDC(hDC), Interop.CommonHandles.GDI); @@ -109,8 +113,8 @@ public static IntPtr CreateCompatibleDC(HandleRef hDC) } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="SaveDC", CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "SaveDC", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern int IntSaveDC(HandleRef hDC); public static int SaveDC(HandleRef hDC) { @@ -118,26 +122,26 @@ public static int SaveDC(HandleRef hDC) DbgUtil.AssertWin32(state != 0, "SaveDC([hdc=0x{0:X8}]) failed", hDC.Handle); return state; } - - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="RestoreDC", CharSet=System.Runtime.InteropServices.CharSet.Auto)] - - public static extern bool IntRestoreDC(HandleRef hDC, int nSavedDC); + + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "RestoreDC", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + + public static extern bool IntRestoreDC(HandleRef hDC, int nSavedDC); public static bool RestoreDC(HandleRef hDC, int nSavedDC) { - bool retVal = IntRestoreDC( hDC, nSavedDC ); + bool retVal = IntRestoreDC(hDC, nSavedDC); return retVal; } - - [DllImport(ExternDll.User32, SetLastError=true, ExactSpelling = true)] - + + [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true)] + public static extern IntPtr WindowFromDC(HandleRef hDC); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)] + public static extern int GetDeviceCaps(HandleRef hDC, int nIndex); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="OffsetViewportOrgEx", CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "OffsetViewportOrgEx", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern bool IntOffsetViewportOrgEx(HandleRef hDC, int nXOffset, int nYOffset, [In, Out] IntNativeMethods.POINT point); public static bool OffsetViewportOrgEx(HandleRef hDC, int nXOffset, int nYOffset, [In, Out] IntNativeMethods.POINT point) { @@ -146,8 +150,8 @@ public static bool OffsetViewportOrgEx(HandleRef hDC, int nXOffset, int nYOffset return retVal; } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="SetGraphicsMode", CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "SetGraphicsMode", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern int IntSetGraphicsMode(HandleRef hDC, int iMode); public static int SetGraphicsMode(HandleRef hDC, int iMode) { @@ -156,29 +160,31 @@ public static int SetGraphicsMode(HandleRef hDC, int iMode) return iMode; } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern int GetGraphicsMode(HandleRef hDC); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true)] + public static extern int GetROP2(HandleRef hdc); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern int SetROP2(HandleRef hDC, int nDrawMode); // Region. [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CombineRgn", CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + public static extern IntNativeMethods.RegionFlags IntCombineRgn(HandleRef hRgnDest, HandleRef hRgnSrc1, HandleRef hRgnSrc2, RegionCombineMode combineMode); - public static IntNativeMethods.RegionFlags CombineRgn(HandleRef hRgnDest, HandleRef hRgnSrc1, HandleRef hRgnSrc2, RegionCombineMode combineMode) { + public static IntNativeMethods.RegionFlags CombineRgn(HandleRef hRgnDest, HandleRef hRgnSrc1, HandleRef hRgnSrc2, RegionCombineMode combineMode) + { Debug.Assert(hRgnDest.Wrapper != null && hRgnDest.Handle != IntPtr.Zero, "Destination region is invalid"); Debug.Assert(hRgnSrc1.Wrapper != null && hRgnSrc1.Handle != IntPtr.Zero, "Source region 1 is invalid"); Debug.Assert(hRgnSrc2.Wrapper != null && hRgnSrc2.Handle != IntPtr.Zero, "Source region 2 is invalid"); - if (hRgnDest.Wrapper == null || hRgnSrc1.Wrapper == null || hRgnSrc2.Wrapper == null) { + if (hRgnDest.Wrapper == null || hRgnSrc1.Wrapper == null || hRgnSrc2.Wrapper == null) + { return IntNativeMethods.RegionFlags.ERROR; } @@ -187,16 +193,17 @@ public static IntNativeMethods.RegionFlags CombineRgn(HandleRef hRgnDest, Handle } [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetClipRgn", CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + public static extern int IntGetClipRgn(HandleRef hDC, HandleRef hRgn); - public static int GetClipRgn(HandleRef hDC, HandleRef hRgn) { + public static int GetClipRgn(HandleRef hDC, HandleRef hRgn) + { int retVal = IntGetClipRgn(hDC, hRgn); DbgUtil.AssertWin32(retVal != -1, "IntGetClipRgn([hdc=0x{0:X8}], [hRgn]) failed.", hDC.Handle); return retVal; } [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "SelectClipRgn", CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + public static extern IntNativeMethods.RegionFlags IntSelectClipRgn(HandleRef hDC, HandleRef hRgn); public static IntNativeMethods.RegionFlags SelectClipRgn(HandleRef hDC, HandleRef hRgn) { @@ -206,7 +213,7 @@ public static IntNativeMethods.RegionFlags SelectClipRgn(HandleRef hDC, HandleRe } [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetRgnBox", CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + public static extern IntNativeMethods.RegionFlags IntGetRgnBox(HandleRef hRgn, [In, Out] ref IntNativeMethods.RECT clipRect); public static IntNativeMethods.RegionFlags GetRgnBox(HandleRef hRgn, [In, Out] ref IntNativeMethods.RECT clipRect) { @@ -218,11 +225,11 @@ public static IntNativeMethods.RegionFlags GetRgnBox(HandleRef hRgn, [In, Out] r // Font. [DllImport(ExternDll.Gdi32, SetLastError = true, EntryPoint = "CreateFontIndirect", CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + public static extern IntPtr IntCreateFontIndirect([In, Out, MarshalAs(UnmanagedType.AsAny)] object lf); // need object here since LOGFONT is not public. - - - public static IntPtr CreateFontIndirect(/*IntNativeMethods.LOGFONT*/ object lf) + + + public static IntPtr CreateFontIndirect(/*IntNativeMethods.LOGFONT*/ object lf) { IntPtr hFont = Interop.HandleCollector.Add(IntCreateFontIndirect(lf), Interop.CommonHandles.GDI); DbgUtil.AssertWin32(hFont != IntPtr.Zero, "CreateFontIndirect(logFont) failed."); @@ -230,8 +237,8 @@ public static IntPtr CreateFontIndirect(/*IntNativeMethods.LOGFONT*/ object lf) } // Common. - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, EntryPoint = "DeleteObject", CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "DeleteObject", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern bool IntDeleteObject(HandleRef hObject); public static bool DeleteObject(HandleRef hObject) { @@ -241,121 +248,121 @@ public static bool DeleteObject(HandleRef hObject) return retVal; } - [DllImport(ExternDll.Gdi32, SetLastError=true, EntryPoint = "GetObject", ExactSpelling=false, CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, EntryPoint = "GetObject", ExactSpelling = false, CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern int IntGetObject(HandleRef hBrush, int nSize, [In, Out] IntNativeMethods.LOGBRUSH lb); - public static int GetObject(HandleRef hBrush, IntNativeMethods.LOGBRUSH lb) + public static int GetObject(HandleRef hBrush, IntNativeMethods.LOGBRUSH lb) { int retVal = IntGetObject(hBrush, System.Runtime.InteropServices.Marshal.SizeOf(), lb); DbgUtil.AssertWin32(retVal != 0, "GetObject(hObj=[0x{0:X8}], [LOGBRUSH]) failed.", hBrush.Handle); return retVal; } - + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments")] - [DllImport(ExternDll.Gdi32, SetLastError=true, EntryPoint = "GetObject", ExactSpelling=false, CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, EntryPoint = "GetObject", ExactSpelling = false, CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern int IntGetObject(HandleRef hFont, int nSize, [In, Out] IntNativeMethods.LOGFONT lf); - public static int GetObject(HandleRef hFont, IntNativeMethods.LOGFONT lp) + public static int GetObject(HandleRef hFont, IntNativeMethods.LOGFONT lp) { int retVal = IntGetObject(hFont, System.Runtime.InteropServices.Marshal.SizeOf(), lp); DbgUtil.AssertWin32(retVal != 0, "GetObject(hObj=[0x{0:X8}], [LOGFONT]) failed.", hFont.Handle); return retVal; } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="SelectObject", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "SelectObject", CharSet = CharSet.Auto)] + public static extern IntPtr IntSelectObject(HandleRef hdc, HandleRef obj); - - + + public static IntPtr SelectObject(HandleRef hdc, HandleRef obj) { IntPtr oldObj = IntSelectObject(hdc, obj); DbgUtil.AssertWin32(oldObj != IntPtr.Zero, "SelectObject(hdc=hObj=[0x{0:X8}], hObj=[0x{1:X8}]) failed.", hdc.Handle, obj.Handle); return oldObj; } - - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, EntryPoint="GetCurrentObject", CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetCurrentObject", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern IntPtr IntGetCurrentObject(HandleRef hDC, int uObjectType); - - + + public static IntPtr GetCurrentObject(HandleRef hDC, int uObjectType) { IntPtr hGdiObj = IntGetCurrentObject(hDC, uObjectType); // If the selected object is a region the return value is HGI_ERROR on failure. - DbgUtil.AssertWin32(hGdiObj != IntPtr.Zero, "GetObject(hdc=[0x{0:X8}], type=[{1}]) failed.", hDC, uObjectType ); + DbgUtil.AssertWin32(hGdiObj != IntPtr.Zero, "GetObject(hdc=[0x{0:X8}], type=[{1}]) failed.", hDC, uObjectType); return hGdiObj; } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="GetStockObject", CharSet=CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetStockObject", CharSet = CharSet.Auto)] + public static extern IntPtr IntGetStockObject(int nIndex); - - + + public static IntPtr GetStockObject(int nIndex) { IntPtr hGdiObj = IntGetStockObject(nIndex); - DbgUtil.AssertWin32(hGdiObj != IntPtr.Zero, "GetStockObject({0}) failed.", nIndex ); + DbgUtil.AssertWin32(hGdiObj != IntPtr.Zero, "GetStockObject({0}) failed.", nIndex); return hGdiObj; } // Drawing. - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern int GetNearestColor(HandleRef hDC, int color); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern int /*COLORREF*/ SetTextColor(HandleRef hDC, int crColor); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern int GetTextAlign(HandleRef hdc); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern int /*COLORREF*/ GetTextColor(HandleRef hDC); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern int SetBkColor(HandleRef hDC, int clr); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, EntryPoint="SetBkMode", CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "SetBkMode", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern int IntSetBkMode(HandleRef hDC, int nBkMode); public static int SetBkMode(HandleRef hDC, int nBkMode) { - int oldMode = IntSetBkMode( hDC, nBkMode ); - DbgUtil.AssertWin32(oldMode != 0, "SetBkMode(hdc=[0x{0:X8}], Mode=[{1}]) failed.", hDC.Handle, nBkMode ); + int oldMode = IntSetBkMode(hDC, nBkMode); + DbgUtil.AssertWin32(oldMode != 0, "SetBkMode(hdc=[0x{0:X8}], Mode=[{1}]) failed.", hDC.Handle, nBkMode); return oldMode; } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, EntryPoint="GetBkMode", CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetBkMode", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern int IntGetBkMode(HandleRef hDC); public static int GetBkMode(HandleRef hDC) { - int mode = IntGetBkMode( hDC ); + int mode = IntGetBkMode(hDC); DbgUtil.AssertWin32(mode != 0, "GetBkMode(hdc=[0x{0:X8}]) failed.", hDC.Handle); return mode; } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern int GetBkColor(HandleRef hDC); - [DllImport( ExternDll.User32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode )] - + [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] + public static extern int DrawTextW(HandleRef hDC, string lpszString, int nCount, ref IntNativeMethods.RECT lpRect, int nFormat); - [DllImport( ExternDll.User32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Ansi )] - + [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Ansi)] + public static extern int DrawTextA(HandleRef hDC, byte[] lpszString, int byteCount, ref IntNativeMethods.RECT lpRect, int nFormat); - public static int DrawText( HandleRef hDC, string text, ref IntNativeMethods.RECT lpRect, int nFormat ) + public static int DrawText(HandleRef hDC, string text, ref IntNativeMethods.RECT lpRect, int nFormat) { int retVal = DrawTextW(hDC, text, text.Length, ref lpRect, nFormat); @@ -363,30 +370,30 @@ public static int DrawText( HandleRef hDC, string text, ref IntNativeMethods.REC return retVal; } - [DllImport(ExternDll.User32, SetLastError=true, CharSet=System.Runtime.InteropServices.CharSet.Unicode)] - + [DllImport(ExternDll.User32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] + public static extern int DrawTextExW(HandleRef hDC, string lpszString, int nCount, ref IntNativeMethods.RECT lpRect, int nFormat, [In, Out] IntNativeMethods.DRAWTEXTPARAMS lpDTParams); - [DllImport(ExternDll.User32, SetLastError=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi)] - + [DllImport(ExternDll.User32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Ansi)] + public static extern int DrawTextExA(HandleRef hDC, byte[] lpszString, int byteCount, ref IntNativeMethods.RECT lpRect, int nFormat, [In, Out] IntNativeMethods.DRAWTEXTPARAMS lpDTParams); public static int DrawTextEx(HandleRef hDC, string text, ref IntNativeMethods.RECT lpRect, int nFormat, [In, Out] IntNativeMethods.DRAWTEXTPARAMS lpDTParams) { int retVal = DrawTextExW(hDC, text, text.Length, ref lpRect, nFormat, lpDTParams); - DbgUtil.AssertWin32(retVal != 0, "DrawTextEx(hdc=[0x{0:X8}], text=[{1}], rect=[{2}], flags=[{3}] failed.", hDC.Handle, text, lpRect, nFormat ); + DbgUtil.AssertWin32(retVal != 0, "DrawTextEx(hdc=[0x{0:X8}], text=[{1}], rect=[{2}], flags=[{3}] failed.", hDC.Handle, text, lpRect, nFormat); return retVal; } - [SuppressMessage("Microsoft.Interoperability", "CA1400:PInvokeEntryPointsShouldExist")] - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Unicode)] - + [SuppressMessage("Microsoft.Interoperability", "CA1400:PInvokeEntryPointsShouldExist")] + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] + public static extern int GetTextExtentPoint32W(HandleRef hDC, string text, int len, [In, Out] IntNativeMethods.SIZE size); - - [SuppressMessage("Microsoft.Interoperability", "CA1400:PInvokeEntryPointsShouldExist")] - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi)] - + + [SuppressMessage("Microsoft.Interoperability", "CA1400:PInvokeEntryPointsShouldExist")] + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Ansi)] + public static extern int GetTextExtentPoint32A(HandleRef hDC, byte[] lpszString, int byteCount, [In, Out] IntNativeMethods.SIZE size); public static int GetTextExtentPoint32(HandleRef hDC, string text, [In, Out] IntNativeMethods.SIZE size) @@ -406,41 +413,41 @@ public static int GetTextExtentPoint32(HandleRef hDC, string text, [In, Out] Int /// point I'm leaving it here. /// [SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments")] - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=false, CharSet=CharSet.Auto)] + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = false, CharSet = CharSet.Auto)] internal static extern bool ExtTextOut(HandleRef hdc, int x, int y, int options, ref IntNativeMethods.RECT rect, string str, int length, int[] spacing); - - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, EntryPoint="LineTo", CharSet = CharSet.Auto)] - + + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "LineTo", CharSet = CharSet.Auto)] + public static extern bool IntLineTo(HandleRef hdc, int x, int y); public static bool LineTo(HandleRef hdc, int x, int y) { bool retVal = IntLineTo(hdc, x, y); - DbgUtil.AssertWin32(retVal, "LineTo(hdc=[0x{0:X8}], x=[{1}], y=[{2}] failed.", hdc.Handle, x, y ); + DbgUtil.AssertWin32(retVal, "LineTo(hdc=[0x{0:X8}], x=[{1}], y=[{2}] failed.", hdc.Handle, x, y); return retVal; } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, EntryPoint="MoveToEx", CharSet = CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "MoveToEx", CharSet = CharSet.Auto)] + public static extern bool IntMoveToEx(HandleRef hdc, int x, int y, IntNativeMethods.POINT pt); public static bool MoveToEx(HandleRef hdc, int x, int y, IntNativeMethods.POINT pt) { bool retVal = IntMoveToEx(hdc, x, y, pt); - DbgUtil.AssertWin32(retVal, "MoveToEx(hdc=[0x{0:X8}], x=[{1}], y=[{2}], pt=[{3}] failed.", hdc.Handle, x, y, pt ); + DbgUtil.AssertWin32(retVal, "MoveToEx(hdc=[0x{0:X8}], x=[{1}], y=[{2}], pt=[{3}] failed.", hdc.Handle, x, y, pt); return retVal; } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, EntryPoint="Rectangle", CharSet = CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "Rectangle", CharSet = CharSet.Auto)] + public static extern bool IntRectangle(HandleRef hdc, int left, int top, int right, int bottom); public static bool Rectangle(HandleRef hdc, int left, int top, int right, int bottom) { - bool retVal = IntRectangle(hdc,left, top, right, bottom); - DbgUtil.AssertWin32(retVal, "Rectangle(hdc=[0x{0:X8}], left=[{1}], top=[{2}], right=[{3}], bottom=[{4}] failed.", hdc.Handle, left, top, right, bottom ); + bool retVal = IntRectangle(hdc, left, top, right, bottom); + DbgUtil.AssertWin32(retVal, "Rectangle(hdc=[0x{0:X8}], left=[{1}], top=[{2}], right=[{3}], bottom=[{4}] failed.", hdc.Handle, left, top, right, bottom); return retVal; } - [DllImport(ExternDll.User32, SetLastError=true, ExactSpelling = true, EntryPoint="FillRect", CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, EntryPoint = "FillRect", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern bool IntFillRect(HandleRef hdc, [In] ref IntNativeMethods.RECT rect, HandleRef hbrush); public static bool FillRect(HandleRef hDC, [In] ref IntNativeMethods.RECT rect, HandleRef hbrush) { @@ -449,8 +456,8 @@ public static bool FillRect(HandleRef hDC, [In] ref IntNativeMethods.RECT rect, return retVal; } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, EntryPoint="SetMapMode", CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "SetMapMode", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern int IntSetMapMode(HandleRef hDC, int nMapMode); public static int SetMapMode(HandleRef hDC, int nMapMode) { @@ -459,8 +466,8 @@ public static int SetMapMode(HandleRef hDC, int nMapMode) return oldMapMode; } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="GetMapMode", CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetMapMode", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern int IntGetMapMode(HandleRef hDC); public static int GetMapMode(HandleRef hDC) { @@ -469,28 +476,28 @@ public static int GetMapMode(HandleRef hDC) return mapMode; } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="GetViewportExtEx")] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetViewportExtEx")] + public static extern bool IntGetViewportExtEx(HandleRef hdc, [In, Out] IntNativeMethods.SIZE lpSize); - public static bool GetViewportExtEx( HandleRef hdc, [In, Out] IntNativeMethods.SIZE lpSize ) + public static bool GetViewportExtEx(HandleRef hdc, [In, Out] IntNativeMethods.SIZE lpSize) { - bool retVal = IntGetViewportExtEx( hdc, lpSize ); + bool retVal = IntGetViewportExtEx(hdc, lpSize); DbgUtil.AssertWin32(retVal, "GetViewportExtEx([hdc=0x{0:X8}], [out size]) failed.", hdc.Handle); return retVal; } - - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="GetViewportOrgEx")] - + + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetViewportOrgEx")] + public static extern bool IntGetViewportOrgEx(HandleRef hdc, [In, Out] IntNativeMethods.POINT lpPoint); - public static bool GetViewportOrgEx( HandleRef hdc, [In, Out] IntNativeMethods.POINT lpPoint ) + public static bool GetViewportOrgEx(HandleRef hdc, [In, Out] IntNativeMethods.POINT lpPoint) { - bool retVal = IntGetViewportOrgEx( hdc, lpPoint ); + bool retVal = IntGetViewportOrgEx(hdc, lpPoint); DbgUtil.AssertWin32(retVal, "GetViewportOrgEx([hdc=0x{0:X8}], [out point]) failed.", hdc.Handle); return retVal; } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="SetViewportExtEx", CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "SetViewportExtEx", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern bool IntSetViewportExtEx(HandleRef hDC, int x, int y, [In, Out] IntNativeMethods.SIZE size); public static bool SetViewportExtEx(HandleRef hDC, int x, int y, [In, Out] IntNativeMethods.SIZE size) { @@ -498,8 +505,8 @@ public static bool SetViewportExtEx(HandleRef hDC, int x, int y, [In, Out] IntNa DbgUtil.AssertWin32(retVal, "SetViewportExtEx([hdc=0x{0:X8}], x=[{1}], y=[{2}], [out size]) failed.", hDC.Handle, x, y); return retVal; } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="SetViewportOrgEx", CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "SetViewportOrgEx", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern bool IntSetViewportOrgEx(HandleRef hDC, int x, int y, [In, Out] IntNativeMethods.POINT point); public static bool SetViewportOrgEx(HandleRef hDC, int x, int y, [In, Out] IntNativeMethods.POINT point) { @@ -508,15 +515,15 @@ public static bool SetViewportOrgEx(HandleRef hDC, int x, int y, [In, Out] IntNa return retVal; } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] + public static extern int GetTextMetricsW(HandleRef hDC, [In, Out] ref IntNativeMethods.TEXTMETRIC lptm); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet = System.Runtime.InteropServices.CharSet.Ansi)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Ansi)] + public static extern int GetTextMetricsA(HandleRef hDC, [In, Out] ref IntNativeMethods.TEXTMETRICA lptm); - public static int GetTextMetrics(HandleRef hDC, ref IntNativeMethods.TEXTMETRIC lptm) + public static int GetTextMetrics(HandleRef hDC, ref IntNativeMethods.TEXTMETRIC lptm) { int retVal = IntUnsafeNativeMethods.GetTextMetricsW(hDC, ref lptm); @@ -524,18 +531,18 @@ public static int GetTextMetrics(HandleRef hDC, ref IntNativeMethods.TEXTMETRIC return retVal; } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="BeginPath", CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "BeginPath", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern bool IntBeginPath(HandleRef hDC); public static bool BeginPath(HandleRef hDC) { bool retVal = IntBeginPath(hDC); - DbgUtil.AssertWin32(retVal, "BeginPath(hdc=[0x{0:X8}]failed.", hDC.Handle ); + DbgUtil.AssertWin32(retVal, "BeginPath(hdc=[0x{0:X8}]failed.", hDC.Handle); return retVal; } - - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="EndPath", CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "EndPath", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern bool IntEndPath(HandleRef hDC); public static bool EndPath(HandleRef hDC) { @@ -544,18 +551,18 @@ public static bool EndPath(HandleRef hDC) return retVal; } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="StrokePath", CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "StrokePath", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern bool IntStrokePath(HandleRef hDC); public static bool StrokePath(HandleRef hDC) { bool retVal = IntStrokePath(hDC); - DbgUtil.AssertWin32(retVal, "StrokePath(hdc=[0x{0:X8}]failed.", hDC.Handle ); + DbgUtil.AssertWin32(retVal, "StrokePath(hdc=[0x{0:X8}]failed.", hDC.Handle); return retVal; } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="AngleArc", CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "AngleArc", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern bool IntAngleArc(HandleRef hDC, int x, int y, int radius, float startAngle, float endAngle); public static bool AngleArc(HandleRef hDC, int x, int y, int radius, float startAngle, float endAngle) { @@ -564,10 +571,10 @@ public static bool AngleArc(HandleRef hDC, int x, int y, int radius, float start return retVal; } - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="Arc", CharSet=System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "Arc", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern bool IntArc( - HandleRef hDC, + HandleRef hDC, int nLeftRect, // x-coord of rectangle's upper-left corner int nTopRect, // y-coord of rectangle's upper-left corner int nRightRect, // x-coord of rectangle's lower-right corner @@ -578,7 +585,7 @@ public static extern bool IntArc( int nYEndArc // y-coord of second radial ending point ); public static bool Arc( - HandleRef hDC, + HandleRef hDC, int nLeftRect, // x-coord of rectangle's upper-left corner int nTopRect, // y-coord of rectangle's upper-left corner int nRightRect, // x-coord of rectangle's lower-right corner @@ -596,12 +603,12 @@ int nYEndArc // y-coord of second radial ending point // Misc. - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern int SetTextAlign(HandleRef hDC, int nMode); - [DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, EntryPoint="Ellipse", CharSet = System.Runtime.InteropServices.CharSet.Auto)] - + [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "Ellipse", CharSet = System.Runtime.InteropServices.CharSet.Auto)] + public static extern bool IntEllipse(HandleRef hDc, int x1, int y1, int x2, int y2); public static bool Ellipse(HandleRef hDc, int x1, int y1, int x2, int y2) { @@ -615,8 +622,8 @@ public static bool Ellipse(HandleRef hDc, int x1, int y1, int x2, int y2) - [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=CharSet.Unicode)] - + [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Unicode)] + public static extern int WideCharToMultiByte(int codePage, int flags, [MarshalAs(UnmanagedType.LPWStr)]string wideStr, int chars, [In, Out]byte[] pOutBytes, int bufferBytes, IntPtr defaultChar, IntPtr pDefaultUsed); } diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsBrush.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsBrush.cs index d8e754e6501..06ca6661a2e 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsBrush.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsBrush.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.WindowsBrush.FromLogBrush(System.Windows.Forms.Internal.IntNativeMethods+LOGBRUSH):System.Windows.Forms.Internal.WindowsBrush")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.WindowsBrush.FromHdc(System.IntPtr):System.Windows.Forms.Internal.WindowsBrush")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope="member", Target="System.Windows.Forms.Internal.WindowsBrush.FromBrush(System.Drawing.Brush):System.Windows.Forms.Internal.WindowsBrush")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsBrush.FromLogBrush(System.Windows.Forms.Internal.IntNativeMethods+LOGBRUSH):System.Windows.Forms.Internal.WindowsBrush")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsBrush.FromHdc(System.IntPtr):System.Windows.Forms.Internal.WindowsBrush")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Windows.Forms.Internal.WindowsBrush.FromBrush(System.Drawing.Brush):System.Windows.Forms.Internal.WindowsBrush")] #if DRAWING_DESIGN_NAMESPACE namespace System.Windows.Forms.Internal @@ -35,7 +35,7 @@ abstract class WindowsBrush : MarshalByRefObject, ICloneable, IDisposable { // Handle to the native Windows brush object. // - private DeviceContext dc; + private DeviceContext dc; private IntPtr nativeHandle; // Cannot be protected because the class is internal (C# doesn't allow it). private Color color = Color.White; // GDI brushes have just one color as opposed to GDI+ that can have background color. // Note: We may need to implement background color too. @@ -52,13 +52,13 @@ abstract class WindowsBrush : MarshalByRefObject, ICloneable, IDisposable /// Parameterless constructor to use default color. /// Notice that the actual object construction is done in the derived classes. /// - + public WindowsBrush(DeviceContext dc) { this.dc = dc; } - + public WindowsBrush(DeviceContext dc, Color color) { this.dc = dc; @@ -70,8 +70,10 @@ public WindowsBrush(DeviceContext dc, Color color) Dispose(false); } - protected DeviceContext DC { - get { + protected DeviceContext DC + { + get + { return this.dc; } } @@ -88,7 +90,7 @@ protected virtual void Dispose(bool disposing) DbgUtil.AssertFinalization(this, disposing); dc.DeleteObject(this.nativeHandle, GdiObjectType.Brush); - + this.nativeHandle = IntPtr.Zero; } @@ -112,17 +114,17 @@ public Color Color protected IntPtr NativeHandle { get - { - if( this.nativeHandle == IntPtr.Zero ) + { + if (this.nativeHandle == IntPtr.Zero) { CreateBrush(); } return this.nativeHandle; } - + set - { + { Debug.Assert(this.nativeHandle == IntPtr.Zero, "WindowsBrush object is immutable"); Debug.Assert(value != IntPtr.Zero, "WARNING: assigning IntPtr.Zero to the nativeHandle object."); @@ -200,7 +202,7 @@ public static WindowsBrush FromLogBrush( DeviceContext dc, IntNativeMethods.LOGB /// /// public IntPtr HBrush - { + { get { return this.NativeHandle; diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs index ea38f9252e0..6d1d28ac90c 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs @@ -29,24 +29,24 @@ namespace System.Experimental.Gdi sealed partial class WindowsFont : MarshalByRefObject, ICloneable, IDisposable { const int LogFontNameOffset = 28; - + // Handle to the native Windows font object. // private IntPtr hFont; - private float fontSize = -1.0f; //invalid value. - private int lineSpacing; - private bool ownHandle; - private bool ownedByCacheManager; - private bool everOwnedByCacheManager; + private float fontSize = -1.0f; //invalid value. + private int lineSpacing; + private bool ownHandle; + private bool ownedByCacheManager; + private bool everOwnedByCacheManager; - private IntNativeMethods.LOGFONT logFont; + private IntNativeMethods.LOGFONT logFont; private FontStyle style; // Note: These defaults are according to the ones in GDI+ but those are not necessarily the same as the system // default font. The GetSystemDefaultHFont() method should be used if needed. - private const string defaultFaceName = "Microsoft Sans Serif"; - private const float defaultFontSize = 8.25f; - private const int defaultFontHeight = 13; + private const string defaultFaceName = "Microsoft Sans Serif"; + private const float defaultFontSize = 8.25f; + private const int defaultFontHeight = 13; #if GDI_FINALIZATION_WATCH private string AllocationSite = DbgUtil.StackTrace; @@ -55,12 +55,12 @@ sealed partial class WindowsFont : MarshalByRefObject, ICloneable, IDisposable /// /// Creates the font handle. /// - - + + private void CreateFont() { - Debug.Assert( hFont == IntPtr.Zero, "hFont is not null, this will generate a handle leak." ); - Debug.Assert( this.logFont != null, "WindowsFont.logFont not initialized." ); + Debug.Assert(hFont == IntPtr.Zero, "hFont is not null, this will generate a handle leak."); + Debug.Assert(this.logFont != null, "WindowsFont.logFont not initialized."); this.hFont = IntUnsafeNativeMethods.CreateFontIndirect(this.logFont); @@ -69,7 +69,7 @@ private void CreateFont() #endif if (this.hFont == IntPtr.Zero) { - this.logFont.lfFaceName = defaultFaceName; + this.logFont.lfFaceName = defaultFaceName; this.logFont.lfOutPrecision = IntNativeMethods.OUT_TT_ONLY_PRECIS; // True Type only. this.hFont = IntUnsafeNativeMethods.CreateFontIndirect(this.logFont); @@ -93,20 +93,20 @@ private void CreateFont() /// /// Contructor to construct font from a face name. /// > - - - public WindowsFont( string faceName ) : + + + public WindowsFont(string faceName) : this(faceName, defaultFontSize, FontStyle.Regular, IntNativeMethods.DEFAULT_CHARSET, WindowsFontQuality.Default) { - // Default size in WinForms is 8.25f. + // Default size in WinForms is 8.25f. } /// /// Contructor to construct font from a face name, a desired size and with the specified style. /// > - - - public WindowsFont( string faceName, float size ) : + + + public WindowsFont(string faceName, float size) : this(faceName, size, FontStyle.Regular, IntNativeMethods.DEFAULT_CHARSET, WindowsFontQuality.Default) { } @@ -114,23 +114,23 @@ public WindowsFont( string faceName, float size ) : /// /// Contructor to construct font from a face name, a desired size and with the specified style. /// > - - - public WindowsFont( string faceName, float size, FontStyle style ) : + + + public WindowsFont(string faceName, float size, FontStyle style) : this(faceName, size, style, IntNativeMethods.DEFAULT_CHARSET, WindowsFontQuality.Default) { } - + /// /// Contructor to construct font from a face name, a desired size in points and with the specified style /// and character set. The screen dc is used for calculating the font em height. /// > - - - public WindowsFont( string faceName, float size, FontStyle style, byte charSet, WindowsFontQuality fontQuality ) - { - Debug.Assert( size > 0.0f, "size has a negative value." ); - const byte True = 1; + + + public WindowsFont(string faceName, float size, FontStyle style, byte charSet, WindowsFontQuality fontQuality) + { + Debug.Assert(size > 0.0f, "size has a negative value."); + const byte True = 1; const byte False = 0; this.logFont = new IntNativeMethods.LOGFONT(); @@ -139,26 +139,26 @@ public WindowsFont( string faceName, float size, FontStyle style, byte charSet, // units (pixels when using MM_TEXT) so we need to make the conversion using the number of // pixels per logical inch along the screen height. // - int pixelsY = (int) Math.Ceiling( WindowsGraphicsCacheManager.MeasurementGraphics.DeviceContext.DpiY * size / 72); // 1 point = 1/72 inch.; + int pixelsY = (int)Math.Ceiling(WindowsGraphicsCacheManager.MeasurementGraphics.DeviceContext.DpiY * size / 72); // 1 point = 1/72 inch.; // // The lfHeight represents the font cell height (line spacing) which includes the internal // leading; we specify a negative size value (in pixels) for the height so the font mapper // provides the closest match for the character height rather than the cell height (MSDN). // - this.logFont.lfHeight = -pixelsY; - this.logFont.lfFaceName = faceName != null ? faceName : defaultFaceName; - this.logFont.lfCharSet = charSet; + this.logFont.lfHeight = -pixelsY; + this.logFont.lfFaceName = faceName != null ? faceName : defaultFaceName; + this.logFont.lfCharSet = charSet; this.logFont.lfOutPrecision = IntNativeMethods.OUT_TT_PRECIS; - this.logFont.lfQuality = (byte) fontQuality; - this.logFont.lfWeight = (style & FontStyle.Bold) == FontStyle.Bold ? IntNativeMethods.FW_BOLD : IntNativeMethods.FW_NORMAL; - this.logFont.lfItalic = (style & FontStyle.Italic) == FontStyle.Italic ? True : False; - this.logFont.lfUnderline = (style & FontStyle.Underline) == FontStyle.Underline ? True : False; - this.logFont.lfStrikeOut = (style & FontStyle.Strikeout) == FontStyle.Strikeout ? True : False; + this.logFont.lfQuality = (byte)fontQuality; + this.logFont.lfWeight = (style & FontStyle.Bold) == FontStyle.Bold ? IntNativeMethods.FW_BOLD : IntNativeMethods.FW_NORMAL; + this.logFont.lfItalic = (style & FontStyle.Italic) == FontStyle.Italic ? True : False; + this.logFont.lfUnderline = (style & FontStyle.Underline) == FontStyle.Underline ? True : False; + this.logFont.lfStrikeOut = (style & FontStyle.Strikeout) == FontStyle.Strikeout ? True : False; // Let the Size be recomputed to be consistent with the Height (there may be some precision loss coming from size to height). // this.fontSize = size; - this.style = style; + this.style = style; CreateFont(); } @@ -168,11 +168,11 @@ public WindowsFont( string faceName, float size, FontStyle style, byte charSet, /// Pass false in the createHandle param to create a 'compatible' font (handle-less, to be used for measuring/comparing) or /// when the handle has already been created. /// - - - private WindowsFont( IntNativeMethods.LOGFONT lf, bool createHandle ) + + + private WindowsFont(IntNativeMethods.LOGFONT lf, bool createHandle) { - Debug.Assert( lf != null, "lf is null" ); + Debug.Assert(lf != null, "lf is null"); this.logFont = lf; @@ -199,7 +199,7 @@ private WindowsFont( IntNativeMethods.LOGFONT lf, bool createHandle ) this.style |= FontStyle.Strikeout; } - if( createHandle ) + if (createHandle) { CreateFont(); } @@ -209,20 +209,20 @@ private WindowsFont( IntNativeMethods.LOGFONT lf, bool createHandle ) /// Contructs a WindowsFont object from an existing System.Drawing.Font object (GDI+), based on the screen dc MapMode /// and resolution (normally: MM_TEXT and 96 dpi). /// - - + + public static WindowsFont FromFont(Font font) { return FromFont(font, WindowsFontQuality.Default); } - - - public static WindowsFont FromFont(Font font, WindowsFontQuality fontQuality) + + + public static WindowsFont FromFont(Font font, WindowsFontQuality fontQuality) { string familyName = font.FontFamily.Name; // Strip vertical-font mark from the name if needed. - if (familyName != null && familyName.Length > 1 && familyName[0] == '@') + if (familyName != null && familyName.Length > 1 && familyName[0] == '@') { familyName = familyName.Substring(1); } @@ -236,44 +236,44 @@ public static WindowsFont FromFont(Font font, WindowsFontQuality fontQuality) return new WindowsFont(familyName, font.SizeInPoints, font.Style, font.GdiCharSet, fontQuality); } - + /// /// Creates a WindowsFont from the font selected in the supplied dc. /// - - - public static WindowsFont FromHdc( IntPtr hdc ) + + + public static WindowsFont FromHdc(IntPtr hdc) { IntPtr hFont = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(null, hdc), IntNativeMethods.OBJ_FONT); // don't call DeleteObject on handle from GetCurrentObject, it is the one selected in the hdc. - return FromHfont( hFont ); + return FromHfont(hFont); } /// /// Creates a WindowsFont from the handle to a native GDI font. It does not take ownership of the /// passed-in handle, the caller needs to delete the hFont when done with the WindowsFont. /// - - - public static WindowsFont FromHfont( IntPtr hFont ) + + + public static WindowsFont FromHfont(IntPtr hFont) { - return FromHfont( hFont, false ); + return FromHfont(hFont, false); } /// /// Creates a WindowsFont from the handle to a native GDI font and optionally takes ownership of managing /// the lifetime of the handle. /// - - - public static WindowsFont FromHfont( IntPtr hFont, bool takeOwnership ) + + + public static WindowsFont FromHfont(IntPtr hFont, bool takeOwnership) { IntNativeMethods.LOGFONT lf = new IntNativeMethods.LOGFONT(); IntUnsafeNativeMethods.GetObject(new HandleRef(null, hFont), lf); - - WindowsFont wf = new WindowsFont( lf, /*createHandle*/ false ); + + WindowsFont wf = new WindowsFont(lf, /*createHandle*/ false); wf.hFont = hFont; wf.ownHandle = takeOwnership; // if true, hFont will be deleted on dispose. @@ -295,17 +295,19 @@ internal void Dispose(bool disposing) bool deletedHandle = false; if (this.ownHandle) { - if (!ownedByCacheManager || !disposing) { + if (!ownedByCacheManager || !disposing) + { // If we were ever owned by the CacheManger and we're being disposed // we can be sure that we're not in use by any DC's (otherwise Dispose() wouldn't have been called) // skip the check IsFontInUse check in this case. // Also skip the check if disposing == false, because the cache is thread-static // and that means we're being called from the finalizer. - if (everOwnedByCacheManager || !disposing || !DeviceContexts.IsFontInUse(this)) { - Debug.Assert( this.hFont != IntPtr.Zero, "Unexpected null hFont." ); + if (everOwnedByCacheManager || !disposing || !DeviceContexts.IsFontInUse(this)) + { + Debug.Assert(this.hFont != IntPtr.Zero, "Unexpected null hFont."); DbgUtil.AssertFinalization(this, disposing); - + IntUnsafeNativeMethods.DeleteObject(new HandleRef(this, this.hFont)); #if TRACK_HFONT Debug.WriteLine( DbgUtil.StackTraceToStr(String.Format( "DeleteObject(HFONT[0x{0:x8}]))", (int) this.hFont))); @@ -326,16 +328,16 @@ internal void Dispose(bool disposing) /// /// Returns a value indicating whether the specified object is a WindowsFont equivalent to this object. /// - public override bool Equals( object font ) + public override bool Equals(object font) { WindowsFont winFont = font as WindowsFont; - if( winFont == null ) + if (winFont == null) { return false; } - if( winFont == this ) + if (winFont == this) { return true; } @@ -344,48 +346,48 @@ public override bool Equals( object font ) // remoting scenario and proxies cannot access internal or private members. // Compare params used to create the font. - return this.Name == winFont.Name && - this.LogFontHeight == winFont.LogFontHeight && // Equivalent to comparing Size but always at hand. - this.Style == winFont.Style && - this.CharSet == winFont.CharSet && - this.Quality == winFont.Quality; + return this.Name == winFont.Name && + this.LogFontHeight == winFont.LogFontHeight && // Equivalent to comparing Size but always at hand. + this.Style == winFont.Style && + this.CharSet == winFont.CharSet && + this.Quality == winFont.Quality; } /// /// Gets the hash code for this WindowsFont. /// - public override int GetHashCode() + public override int GetHashCode() { // similar to Font.GetHashCode(). - return (int)((((uint)this.Style << 13) | ((uint)this.Style >> 19)) ^ - (((uint)this.CharSet << 26) | ((uint)this.CharSet >> 6)) ^ - (((uint)this.Size << 7) | ((uint)this.Size >> 25))); + return (int)((((uint)this.Style << 13) | ((uint)this.Style >> 19)) ^ + (((uint)this.CharSet << 26) | ((uint)this.CharSet >> 6)) ^ + (((uint)this.Size << 7) | ((uint)this.Size >> 25))); } /// /// Clones this object. /// - - + + public object Clone() { - return new WindowsFont( this.logFont, true ); + return new WindowsFont(this.logFont, true); } public override string ToString() { - return string.Format(CultureInfo.CurrentCulture, "[{0}: Name={1}, Size={2} points, Height={3} pixels, Sytle={4}]", GetType().Name, logFont.lfFaceName, this.Size, this.Height, this.Style); + return string.Format(CultureInfo.CurrentCulture, "[{0}: Name={1}, Size={2} points, Height={3} pixels, Sytle={4}]", GetType().Name, logFont.lfFaceName, this.Size, this.Height, this.Style); } //////////////////////////////////////////// /// Properties - + /// /// Returns this object's native Win32 font handle. Should NOT be deleted externally. /// Compare with ToHfont method. /// public IntPtr Hfont - { + { get { //Assert removed. We need to be able to check for Hfont == IntPtr.Zero to determine if the object was disposed. @@ -407,11 +409,14 @@ public bool Italic public bool OwnedByCacheManager { - get { + get + { return ownedByCacheManager; } - set { - if (value) { + set + { + if (value) + { everOwnedByCacheManager = true; } ownedByCacheManager = value; @@ -425,7 +430,7 @@ public WindowsFontQuality Quality { get { - return (WindowsFontQuality) this.logFont.lfQuality; + return (WindowsFontQuality)this.logFont.lfQuality; } } @@ -453,16 +458,16 @@ public int Height get { - if( this.lineSpacing == 0 ) + if (this.lineSpacing == 0) { // Observe that the font text metrics are obtained using the resolution of the screen. - WindowsGraphics wg = WindowsGraphicsCacheManager.MeasurementGraphics; + WindowsGraphics wg = WindowsGraphicsCacheManager.MeasurementGraphics; // No need to reset the font (if changed) since we always set the font before using the MeasurementGraphics // in WindowsGraphics methods. wg.DeviceContext.SelectFont(this); - IntNativeMethods.TEXTMETRIC tm = (IntNativeMethods.TEXTMETRIC) wg.GetTextMetrics(); + IntNativeMethods.TEXTMETRIC tm = (IntNativeMethods.TEXTMETRIC)wg.GetTextMetrics(); this.lineSpacing = tm.tmHeight; } @@ -509,19 +514,19 @@ public string Name /// Gets the character height (as opposed to the cell height) of the font represented by this object in points. /// Consider /// - public float Size + public float Size { get { - if( this.fontSize < 0.0f ) + if (this.fontSize < 0.0f) { - WindowsGraphics wg = WindowsGraphicsCacheManager.MeasurementGraphics; + WindowsGraphics wg = WindowsGraphicsCacheManager.MeasurementGraphics; // No need to reset the font (if changed) since we always set the font before using the MeasurementGraphics // in WindowsGraphics methods. wg.DeviceContext.SelectFont(this); - IntNativeMethods.TEXTMETRIC tm = (IntNativeMethods.TEXTMETRIC) wg.GetTextMetrics(); + IntNativeMethods.TEXTMETRIC tm = (IntNativeMethods.TEXTMETRIC)wg.GetTextMetrics(); // // Convert the font character height to points. If lfHeight is negative, Windows @@ -542,10 +547,10 @@ public float Size case GraphicsUnit.Millimeter: worldEmSize = height * dpi / 25.4f; break; } */ - + this.fontSize = height * 72f / wg.DeviceContext.DpiY; } - + return this.fontSize; } } @@ -580,7 +585,7 @@ public static WindowsFontQuality WindowsFontQualityFromTextRenderingHint(Graphic default: case TextRenderingHint.SystemDefault: return WindowsFontQuality.Default; - + } } } diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsFontQuality.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsFontQuality.cs index 6b2847cf97c..d507be525b5 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsFontQuality.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsFontQuality.cs @@ -58,7 +58,7 @@ enum WindowsFontQuality /// For example, this occurs commonly in East Asian fonts. /// If set, text is rendered (when possible) using ClearType antialiasing method. /// - ClearType = IntNativeMethods.CLEARTYPE_QUALITY, + ClearType = IntNativeMethods.CLEARTYPE_QUALITY, ClearTypeNatural = IntNativeMethods.CLEARTYPE_NATURAL_QUALITY } diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics.cs index e3825daee9d..e366be41e89 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics.cs @@ -19,7 +19,7 @@ namespace System.Experimental.Gdi using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; - using System.Diagnostics.CodeAnalysis; + using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Drawing.Drawing2D; using System.Runtime.Versioning; @@ -55,9 +55,9 @@ sealed partial class WindowsGraphics : MarshalByRefObject, IDisposable, IDeviceC // Construction/destruction API - public WindowsGraphics( DeviceContext dc ) + public WindowsGraphics(DeviceContext dc) { - Debug.Assert( dc != null, "null dc!"); + Debug.Assert(dc != null, "null dc!"); this.dc = dc; this.dc.SaveHdc(); //this.disposeDc = false; // the dc is not owned by this object. @@ -68,14 +68,14 @@ public WindowsGraphics( DeviceContext dc ) /// This object is suitable for performing text measuring but not for drawing into it because it does /// not have a backup bitmap. /// - - + + public static WindowsGraphics CreateMeasurementWindowsGraphics() { DeviceContext dc = DeviceContext.FromCompatibleDC(IntPtr.Zero); WindowsGraphics wg = new WindowsGraphics(dc); wg.disposeDc = true; // we create it, we dispose it. - + return wg; } @@ -84,34 +84,34 @@ public static WindowsGraphics CreateMeasurementWindowsGraphics() /// This object is suitable for performing text measuring but not for drawing into it because it does /// not have a backup bitmap. /// - - + + public static WindowsGraphics CreateMeasurementWindowsGraphics(IntPtr screenDC) { DeviceContext dc = DeviceContext.FromCompatibleDC(screenDC); WindowsGraphics wg = new WindowsGraphics(dc); wg.disposeDc = true; // we create it, we dispose it. - + return wg; } public static WindowsGraphics FromHwnd(IntPtr hWnd) - { - DeviceContext dc = DeviceContext.FromHwnd( hWnd ); - WindowsGraphics wg = new WindowsGraphics( dc ); + { + DeviceContext dc = DeviceContext.FromHwnd(hWnd); + WindowsGraphics wg = new WindowsGraphics(dc); wg.disposeDc = true; // we create it, we dispose it. - - return wg; + + return wg; } - - + + public static WindowsGraphics FromHdc(IntPtr hDc) { - Debug.Assert( hDc != IntPtr.Zero, "null hDc" ); - + Debug.Assert(hDc != IntPtr.Zero, "null hDc"); + DeviceContext dc = DeviceContext.FromHdc(hDc); - WindowsGraphics wg = new WindowsGraphics( dc ); + WindowsGraphics wg = new WindowsGraphics(dc); wg.disposeDc = true; // we create it, we dispose it. return wg; @@ -140,19 +140,19 @@ public static WindowsGraphics FromHdc(IntPtr hDc) /// Please note that this only applies the HDC created graphics, for Bitmap derived graphics, GetHdc creates a new DIBSection and /// things get a lot more complicated. /// - - + + public static WindowsGraphics FromGraphics(Graphics g) { ApplyGraphicsProperties properties = ApplyGraphicsProperties.All; return WindowsGraphics.FromGraphics(g, properties); } - - + + public static WindowsGraphics FromGraphics(Graphics g, ApplyGraphicsProperties properties) { - Debug.Assert( g != null, "null Graphics object." ); + Debug.Assert(g != null, "null Graphics object."); //Debug.Assert( properties != ApplyGraphicsProperties.None, "Consider using other WindowsGraphics constructor if not preserving Graphics properties." ); WindowsRegion wr = null; @@ -165,22 +165,22 @@ public static WindowsGraphics FromGraphics(Graphics g, ApplyGraphicsProperties p { object[] data = g.GetContextInfo() as object[]; - if( data != null && data.Length == 2 ) + if (data != null && data.Length == 2) { clipRgn = data[0] as Region; worldTransf = data[1] as Matrix; } - if( worldTransf != null ) + if (worldTransf != null) { - if ((properties & ApplyGraphicsProperties.TranslateTransform) != 0) + if ((properties & ApplyGraphicsProperties.TranslateTransform) != 0) { elements = worldTransf.Elements; } worldTransf.Dispose(); } - if( clipRgn != null ) + if (clipRgn != null) { if ((properties & ApplyGraphicsProperties.Clipping) != 0) { @@ -188,7 +188,7 @@ public static WindowsGraphics FromGraphics(Graphics g, ApplyGraphicsProperties p // in case of an unlikely exception before releasing the WindowsRegion, the finalizer will do it for us. // (no try-finally block since this method is used frequently - perf). // If the Graphics.Clip has not been set (Region.IsInfinite) we don't need to apply it to the DC. - if (!clipRgn.IsInfinite(g)) + if (!clipRgn.IsInfinite(g)) { wr = WindowsRegion.FromRegion(clipRgn, g); // WindowsRegion will take ownership of the hRegion. } @@ -197,7 +197,7 @@ public static WindowsGraphics FromGraphics(Graphics g, ApplyGraphicsProperties p } } - WindowsGraphics wg = WindowsGraphics.FromHdc( g.GetHdc() ); // This locks the Graphics object. + WindowsGraphics wg = WindowsGraphics.FromHdc(g.GetHdc()); // This locks the Graphics object. wg.graphics = g; // Apply transform and clip @@ -223,13 +223,13 @@ public static WindowsGraphics FromGraphics(Graphics g, ApplyGraphicsProperties p } ~WindowsGraphics() - { + { Dispose(false); } - public DeviceContext DeviceContext + public DeviceContext DeviceContext { - get + get { return this.dc; } @@ -248,11 +248,11 @@ public void Dispose() } [SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed")] - - + + internal void Dispose(bool disposing) { - if (this.dc != null ) + if (this.dc != null) { DbgUtil.AssertFinalization(this, disposing); @@ -261,34 +261,35 @@ internal void Dispose(bool disposing) // Restore original dc. this.dc.RestoreHdc(); - if( this.disposeDc) + if (this.disposeDc) { this.dc.Dispose(disposing); } - if( this.graphics != null ) // if created from a Graphics object... + if (this.graphics != null) // if created from a Graphics object... { this.graphics.ReleaseHdcInternal(this.dc.Hdc); this.graphics = null; } - + } - catch(Exception ex ) + catch (Exception ex) { - if( ClientUtils.IsSecurityOrCriticalException( ex ) ) + if (ClientUtils.IsSecurityOrCriticalException(ex)) { throw; // rethrow the original exception. } Debug.Fail("Exception thrown during disposing: \r\n" + ex.ToString()); } - finally { + finally + { this.dc = null; } } } - - + + public IntPtr GetHdc() { return this.dc.Hdc; diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics2.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics2.cs index 60148ddbcc9..c52a661c98c 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics2.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics2.cs @@ -37,7 +37,7 @@ sealed partial class WindowsGraphics : MarshalByRefObject, IDisposable, IDeviceC // The value of the ItalicPaddingFactor comes from several tests using different fonts & drawing // flags and some benchmarking with GDI+. - private const float ItalicPaddingFactor = 1/2f; + private const float ItalicPaddingFactor = 1 / 2f; private TextPaddingOptions paddingFlags; @@ -50,15 +50,15 @@ public TextPaddingOptions TextPadding [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1803:AvoidCostlyCallsWherePossible")] get { - Debug.Assert( Enum.IsDefined(typeof(TextPaddingOptions), this.paddingFlags)); + Debug.Assert(Enum.IsDefined(typeof(TextPaddingOptions), this.paddingFlags)); return this.paddingFlags; } //Since Enum.IsDefined is only used within a Debug.Assert, it is okay to leave it [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1803:AvoidCostlyCallsWherePossible")] set { - Debug.Assert( Enum.IsDefined(typeof(TextPaddingOptions), value)); - if( this.paddingFlags != value) + Debug.Assert(Enum.IsDefined(typeof(TextPaddingOptions), value)); + if (this.paddingFlags != value) { this.paddingFlags = value; } @@ -69,11 +69,11 @@ public TextPaddingOptions TextPadding /// /// - public void DrawPie(WindowsPen pen, Rectangle bounds, float startAngle, float sweepAngle) + public void DrawPie(WindowsPen pen, Rectangle bounds, float startAngle, float sweepAngle) { - HandleRef hdc = new HandleRef( this.dc, this.dc.Hdc); + HandleRef hdc = new HandleRef(this.dc, this.dc.Hdc); - if( pen != null ) + if (pen != null) { // 1. Select the pen in the DC IntUnsafeNativeMethods.SelectObject(hdc, new HandleRef(pen, pen.HPen)); @@ -85,8 +85,8 @@ public void DrawPie(WindowsPen pen, Rectangle bounds, float startAngle, float sw // then, draw the closing line. // paint the path with the pen int sideLength = Math.Min(bounds.Width, bounds.Height); - Point p = new Point(bounds.X+sideLength/2, bounds.Y+sideLength/2); - int radius = sideLength/2; + Point p = new Point(bounds.X + sideLength / 2, bounds.Y + sideLength / 2); + int radius = sideLength / 2; IntUnsafeNativeMethods.BeginPath(hdc); IntUnsafeNativeMethods.MoveToEx(hdc, p.X, p.Y, null); IntUnsafeNativeMethods.AngleArc(hdc, p.X, p.Y, radius, startAngle, sweepAngle); @@ -99,9 +99,9 @@ private void DrawEllipse(WindowsPen pen, WindowsBrush brush, int nLeftRect, // x-coord of upper-left corner of rectangle int nTopRect, // y-coord of upper-left corner of rectangle int nRightRect, // x-coord of lower-right corner of rectangle - int nBottomRect ) + int nBottomRect) { // y-coord of lower-right corner of rectangle - HandleRef hdc = new HandleRef( this.dc, this.dc.Hdc); + HandleRef hdc = new HandleRef(this.dc, this.dc.Hdc); if (pen != null) { @@ -118,7 +118,7 @@ private void DrawEllipse(WindowsPen pen, WindowsBrush brush, IntUnsafeNativeMethods.Ellipse(hdc, nLeftRect, nTopRect, nRightRect, nBottomRect); } - public void DrawAndFillEllipse(WindowsPen pen, WindowsBrush brush, Rectangle bounds) + public void DrawAndFillEllipse(WindowsPen pen, WindowsBrush brush, Rectangle bounds) { DrawEllipse(pen, brush, bounds.Left, bounds.Top, bounds.Right, bounds.Bottom); } @@ -160,8 +160,8 @@ public void DrawText(string text, WindowsFont font, Point pt, Color foreColor, I /// public void DrawText(string text, WindowsFont font, Point pt, Color foreColor, Color backColor, IntTextFormatFlags flags) { - Rectangle bounds = new Rectangle( pt.X, pt.Y, int.MaxValue, int.MaxValue ); - DrawText( text, font, bounds, foreColor, backColor, flags ); + Rectangle bounds = new Rectangle(pt.X, pt.Y, int.MaxValue, int.MaxValue); + DrawText(text, font, bounds, foreColor, backColor, flags); } /// @@ -185,7 +185,7 @@ public void DrawText(string text, WindowsFont font, Rectangle bounds, Color fore /// public void DrawText(string text, WindowsFont font, Rectangle bounds, Color color, IntTextFormatFlags flags) { - DrawText( text, font, bounds, color, Color.Empty, flags ); + DrawText(text, font, bounds, color, Color.Empty, flags); } /// @@ -196,25 +196,25 @@ public void DrawText(string text, WindowsFont font, Rectangle bounds, Color colo /// public void DrawText(string text, WindowsFont font, Rectangle bounds, Color foreColor, Color backColor, IntTextFormatFlags flags) { - if (string.IsNullOrEmpty(text) || foreColor == Color.Transparent) + if (string.IsNullOrEmpty(text) || foreColor == Color.Transparent) { return; } - Debug.Assert( ((uint)flags & GdiUnsupportedFlagMask) == 0, "Some custom flags were left over and are not GDI compliant!" ); - Debug.Assert( (flags & IntTextFormatFlags.CalculateRectangle) == 0, "CalculateRectangle flag is set, text won't be drawn" ); + Debug.Assert(((uint)flags & GdiUnsupportedFlagMask) == 0, "Some custom flags were left over and are not GDI compliant!"); + Debug.Assert((flags & IntTextFormatFlags.CalculateRectangle) == 0, "CalculateRectangle flag is set, text won't be drawn"); - HandleRef hdc = new HandleRef( this.dc, this.dc.Hdc); + HandleRef hdc = new HandleRef(this.dc, this.dc.Hdc); // DrawText requires default text alignment. - if( this.dc.TextAlignment != DeviceContextTextAlignment.Default ) + if (this.dc.TextAlignment != DeviceContextTextAlignment.Default) { - this.dc.SetTextAlignment(DeviceContextTextAlignment.Default ); + this.dc.SetTextAlignment(DeviceContextTextAlignment.Default); } // color empty means use the one currently selected in the dc. - if( !foreColor.IsEmpty && foreColor != this.dc.TextColor) + if (!foreColor.IsEmpty && foreColor != this.dc.TextColor) { this.dc.SetTextColor(foreColor); } @@ -224,18 +224,18 @@ public void DrawText(string text, WindowsFont font, Rectangle bounds, Color fore this.dc.SelectFont(font); } - DeviceContextBackgroundMode newBackGndMode = (backColor.IsEmpty || backColor == Color.Transparent) ? - DeviceContextBackgroundMode.Transparent : + DeviceContextBackgroundMode newBackGndMode = (backColor.IsEmpty || backColor == Color.Transparent) ? + DeviceContextBackgroundMode.Transparent : DeviceContextBackgroundMode.Opaque; - if( this.dc.BackgroundMode != newBackGndMode ) + if (this.dc.BackgroundMode != newBackGndMode) { - this.dc.SetBackgroundMode( newBackGndMode ); + this.dc.SetBackgroundMode(newBackGndMode); } - if( newBackGndMode != DeviceContextBackgroundMode.Transparent && backColor != this.dc.BackgroundColor ) + if (newBackGndMode != DeviceContextBackgroundMode.Transparent && backColor != this.dc.BackgroundColor) { - this.dc.SetBackgroundColor( backColor ); + this.dc.SetBackgroundColor(backColor); } IntNativeMethods.DRAWTEXTPARAMS dtparams = GetTextMargins(font); @@ -243,19 +243,19 @@ public void DrawText(string text, WindowsFont font, Rectangle bounds, Color fore bounds = AdjustForVerticalAlignment(hdc, text, bounds, flags, dtparams); // Adjust unbounded rect to avoid overflow since Rectangle ctr does not do param validation. - if( bounds.Width == MaxSize.Width ) + if (bounds.Width == MaxSize.Width) { bounds.Width = bounds.Width - bounds.X; } - if( bounds.Height == MaxSize.Height ) + if (bounds.Height == MaxSize.Height) { bounds.Height = bounds.Height - bounds.Y; } IntNativeMethods.RECT rect = new IntNativeMethods.RECT(bounds); - IntUnsafeNativeMethods.DrawTextEx(hdc, text, ref rect, (int) flags, dtparams); - + IntUnsafeNativeMethods.DrawTextEx(hdc, text, ref rect, (int)flags, dtparams); + /* No need to restore previous objects into the dc (see comments on top of the class). * @@ -289,7 +289,7 @@ public void DrawText(string text, WindowsFont font, Rectangle bounds, Color fore /// /// - public Color GetNearestColor(Color color) + public Color GetNearestColor(Color color) { HandleRef hdc = new HandleRef(null, this.dc.Hdc); int colorResult = IntUnsafeNativeMethods.GetNearestColor(hdc, ColorTranslator.ToWin32(color)); @@ -301,21 +301,21 @@ public Color GetNearestColor(Color color) /// Calculates the spacing required for drawing text w/o clipping parts of a glyph. /// /// - public float GetOverhangPadding( WindowsFont font ) + public float GetOverhangPadding(WindowsFont font) { // Some parts of a glyphs may be clipped depending on the font & font style, GDI+ adds 1/6 of tmHeight // to each size of the text bounding box when drawing text to account for that; we do it here as well. WindowsFont tmpfont = font; - - if( tmpfont == null) + + if (tmpfont == null) { tmpfont = this.dc.Font; } float overhangPadding = tmpfont.Height / 6f; - if( tmpfont != font ) + if (tmpfont != font) { tmpfont.Dispose(); } @@ -335,20 +335,20 @@ public IntNativeMethods.DRAWTEXTPARAMS GetTextMargins(WindowsFont font) int rightMargin = 0; float overhangPadding = 0; - switch( this.TextPadding ) + switch (this.TextPadding) { case TextPaddingOptions.GlyphOverhangPadding: // [overhang padding][Text][overhang padding][italic padding] overhangPadding = GetOverhangPadding(font); - leftMargin = (int) Math.Ceiling(overhangPadding); - rightMargin = (int) Math.Ceiling(overhangPadding * (1 + ItalicPaddingFactor)); + leftMargin = (int)Math.Ceiling(overhangPadding); + rightMargin = (int)Math.Ceiling(overhangPadding * (1 + ItalicPaddingFactor)); break; case TextPaddingOptions.LeftAndRightPadding: // [2 * overhang padding][Text][2 * overhang padding][italic padding] overhangPadding = GetOverhangPadding(font); - leftMargin = (int) Math.Ceiling(2 * overhangPadding); - rightMargin = (int) Math.Ceiling(overhangPadding * (2 + ItalicPaddingFactor)); + leftMargin = (int)Math.Ceiling(2 * overhangPadding); + rightMargin = (int)Math.Ceiling(overhangPadding * (2 + ItalicPaddingFactor)); break; case TextPaddingOptions.NoPadding: @@ -389,7 +389,8 @@ public Size GetTextExtent(string text, WindowsFont font) // Unselect, but not from Measurement DC as it keeps the same // font selected for perf reasons. - if (font != null && !MeasurementDCInfo.IsMeasurementDC(this.dc)) { + if (font != null && !MeasurementDCInfo.IsMeasurementDC(this.dc)) + { this.dc.ResetFont(); } @@ -412,7 +413,7 @@ public Size MeasureText(string text, WindowsFont font) /// public Size MeasureText(string text, WindowsFont font, Size proposedSize) { - return MeasureText( text, font, proposedSize, IntTextFormatFlags.Default ); + return MeasureText(text, font, proposedSize, IntTextFormatFlags.Default); } /// @@ -432,14 +433,14 @@ public Size MeasureText(string text, WindowsFont font, Size proposedSize) /// the horizontal and vertical measurements of the text. The application must convert it explicitly. /// - + public Size MeasureText(string text, WindowsFont font, Size proposedSize, IntTextFormatFlags flags) - { - Debug.Assert( ((uint)flags & GdiUnsupportedFlagMask) == 0, "Some custom flags were left over and are not GDI compliant!" ); - + { + Debug.Assert(((uint)flags & GdiUnsupportedFlagMask) == 0, "Some custom flags were left over and are not GDI compliant!"); - - if (string.IsNullOrEmpty(text)) + + + if (string.IsNullOrEmpty(text)) { return Size.Empty; } @@ -453,13 +454,13 @@ public Size MeasureText(string text, WindowsFont font, Size proposedSize, IntTex #if OPTIMIZED_MEASUREMENTDC // use the cache if we've got it - if (MeasurementDCInfo.IsMeasurementDC(this.DeviceContext)) + if (MeasurementDCInfo.IsMeasurementDC(this.DeviceContext)) { - dtparams = MeasurementDCInfo.GetTextMargins(this,font); + dtparams = MeasurementDCInfo.GetTextMargins(this, font); } #endif - if (dtparams == null) + if (dtparams == null) { dtparams = GetTextMargins(font); } @@ -471,10 +472,12 @@ public Size MeasureText(string text, WindowsFont font, Size proposedSize, IntTex int minWidth = 1 + dtparams.iLeftMargin + dtparams.iRightMargin; - if( proposedSize.Width <= minWidth ) { + if (proposedSize.Width <= minWidth) + { proposedSize.Width = minWidth; } - if( proposedSize.Height <= 0 ) { + if (proposedSize.Height <= 0) + { proposedSize.Height = 1; } @@ -497,11 +500,11 @@ public Size MeasureText(string text, WindowsFont font, Size proposedSize, IntTex flags &= ~(IntTextFormatFlags.Bottom | IntTextFormatFlags.VerticalCenter); } - if (proposedSize.Width == MaxSize.Width) + if (proposedSize.Width == MaxSize.Width) { - // PERF: No constraining width means no word break. - // in this case, we dont care about word wrapping - there should be enough room to fit it all - flags &= ~(IntTextFormatFlags.WordBreak); + // PERF: No constraining width means no word break. + // in this case, we dont care about word wrapping - there should be enough room to fit it all + flags &= ~(IntTextFormatFlags.WordBreak); } flags |= IntTextFormatFlags.CalculateRectangle; @@ -514,7 +517,7 @@ public Size MeasureText(string text, WindowsFont font, Size proposedSize, IntTex this.dc.SelectObject(hOldFont); } */ - + return rect.Size; } @@ -533,20 +536,20 @@ public Size MeasureText(string text, WindowsFont font, Size proposedSize, IntTex /// public static Rectangle AdjustForVerticalAlignment(HandleRef hdc, string text, Rectangle bounds, IntTextFormatFlags flags, IntNativeMethods.DRAWTEXTPARAMS dtparams) { - Debug.Assert( ((uint)flags & GdiUnsupportedFlagMask) == 0, "Some custom flags were left over and are not GDI compliant!" ); + Debug.Assert(((uint)flags & GdiUnsupportedFlagMask) == 0, "Some custom flags were left over and are not GDI compliant!"); // Ok if any Top (Cannot test IntTextFormatFlags.Top because it is 0), single line text or measuring text. bool isTop = (flags & IntTextFormatFlags.Bottom) == 0 && (flags & IntTextFormatFlags.VerticalCenter) == 0; - if( isTop ||((flags & IntTextFormatFlags.SingleLine) != 0) || ((flags & IntTextFormatFlags.CalculateRectangle) != 0) ) + if (isTop || ((flags & IntTextFormatFlags.SingleLine) != 0) || ((flags & IntTextFormatFlags.CalculateRectangle) != 0)) { - return bounds; + return bounds; } IntNativeMethods.RECT rect = new IntNativeMethods.RECT(bounds); // Get the text bounds. flags |= IntTextFormatFlags.CalculateRectangle; - int textHeight = IntUnsafeNativeMethods.DrawTextEx(hdc, text, ref rect, (int) flags, dtparams); + int textHeight = IntUnsafeNativeMethods.DrawTextEx(hdc, text, ref rect, (int)flags, dtparams); // if the text does not fit inside the bounds then return the bounds that were passed in if (textHeight > bounds.Height) @@ -556,7 +559,7 @@ public static Rectangle AdjustForVerticalAlignment(HandleRef hdc, string text, R Rectangle adjustedBounds = bounds; - if( (flags & IntTextFormatFlags.VerticalCenter) != 0 ) // Middle + if ((flags & IntTextFormatFlags.VerticalCenter) != 0) // Middle { adjustedBounds.Y = adjustedBounds.Top + adjustedBounds.Height / 2 - textHeight / 2; } @@ -570,36 +573,36 @@ public static Rectangle AdjustForVerticalAlignment(HandleRef hdc, string text, R // DrawRectangle overloads - public void DrawRectangle(WindowsPen pen, Rectangle rect) - { + public void DrawRectangle(WindowsPen pen, Rectangle rect) + { DrawRectangle(pen, rect.X, rect.Y, rect.Width, rect.Height); } - public void DrawRectangle(WindowsPen pen, int x, int y, int width, int height) - { - Debug.Assert( pen != null, "pen == null" ); + public void DrawRectangle(WindowsPen pen, int x, int y, int width, int height) + { + Debug.Assert(pen != null, "pen == null"); HandleRef hdc = new HandleRef(this.dc, this.dc.Hdc); - if( pen != null ) + if (pen != null) { this.dc.SelectObject(pen.HPen, GdiObjectType.Pen); } DeviceContextBinaryRasterOperationFlags rasterOp = this.dc.BinaryRasterOperation; - if( rasterOp != DeviceContextBinaryRasterOperationFlags.CopyPen ) + if (rasterOp != DeviceContextBinaryRasterOperationFlags.CopyPen) { - rasterOp = this.dc.SetRasterOperation(DeviceContextBinaryRasterOperationFlags.CopyPen); + rasterOp = this.dc.SetRasterOperation(DeviceContextBinaryRasterOperationFlags.CopyPen); } IntUnsafeNativeMethods.SelectObject(hdc, new HandleRef(null, IntUnsafeNativeMethods.GetStockObject(IntNativeMethods.HOLLOW_BRUSH))); // Add 1 to widht and height to create the 'bounding box' (convert from point to size). - IntUnsafeNativeMethods.Rectangle(hdc, x, y, x + width , y + height ); - - if( rasterOp != DeviceContextBinaryRasterOperationFlags.CopyPen ) + IntUnsafeNativeMethods.Rectangle(hdc, x, y, x + width, y + height); + + if (rasterOp != DeviceContextBinaryRasterOperationFlags.CopyPen) { - this.dc.SetRasterOperation(rasterOp); + this.dc.SetRasterOperation(rasterOp); } } @@ -612,11 +615,11 @@ public void FillRectangle(WindowsBrush brush, Rectangle rect) public void FillRectangle(WindowsBrush brush, int x, int y, int width, int height) { - Debug.Assert( brush != null, "brush == null" ); + Debug.Assert(brush != null, "brush == null"); - HandleRef hdc = new HandleRef(this.dc, this.dc.Hdc); - IntPtr hBrush = brush.HBrush; // We don't delete this handle since we didn't create it. - IntNativeMethods.RECT rect = new IntNativeMethods.RECT(x, y, x + width, y + height ); + HandleRef hdc = new HandleRef(this.dc, this.dc.Hdc); + IntPtr hBrush = brush.HBrush; // We don't delete this handle since we didn't create it. + IntNativeMethods.RECT rect = new IntNativeMethods.RECT(x, y, x + width, y + height); #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY if (brush is WindowsHatchBrush) @@ -637,26 +640,26 @@ public void FillRectangle(WindowsBrush brush, int x, int y, int width, int heigh /// pixel because if it did the intersection points of connected lines would be drawn multiple /// times turning them back to the background color. /// - public void DrawLine(WindowsPen pen, Point p1, Point p2) + public void DrawLine(WindowsPen pen, Point p1, Point p2) { DrawLine(pen, p1.X, p1.Y, p2.X, p2.Y); } public void DrawLine(WindowsPen pen, int x1, int y1, int x2, int y2) { - HandleRef hdc = new HandleRef(this.dc, this.dc.Hdc); - + HandleRef hdc = new HandleRef(this.dc, this.dc.Hdc); + DeviceContextBinaryRasterOperationFlags rasterOp = this.dc.BinaryRasterOperation; DeviceContextBackgroundMode bckMode = this.dc.BackgroundMode; - if( rasterOp != DeviceContextBinaryRasterOperationFlags.CopyPen ) + if (rasterOp != DeviceContextBinaryRasterOperationFlags.CopyPen) { - rasterOp = this.dc.SetRasterOperation( DeviceContextBinaryRasterOperationFlags.CopyPen ); + rasterOp = this.dc.SetRasterOperation(DeviceContextBinaryRasterOperationFlags.CopyPen); } - if( bckMode != DeviceContextBackgroundMode.Transparent ) + if (bckMode != DeviceContextBackgroundMode.Transparent) { - bckMode = this.dc.SetBackgroundMode( DeviceContextBackgroundMode.Transparent ); + bckMode = this.dc.SetBackgroundMode(DeviceContextBackgroundMode.Transparent); } if (pen != null) @@ -669,16 +672,16 @@ public void DrawLine(WindowsPen pen, int x1, int y1, int x2, int y2) IntUnsafeNativeMethods.MoveToEx(hdc, x1, y1, oldPoint); IntUnsafeNativeMethods.LineTo(hdc, x2, y2); - if( bckMode != DeviceContextBackgroundMode.Transparent ) + if (bckMode != DeviceContextBackgroundMode.Transparent) { - this.dc.SetBackgroundMode( bckMode ); + this.dc.SetBackgroundMode(bckMode); } - if( rasterOp != DeviceContextBinaryRasterOperationFlags.CopyPen ) + if (rasterOp != DeviceContextBinaryRasterOperationFlags.CopyPen) { - this.dc.SetRasterOperation( rasterOp ); + this.dc.SetRasterOperation(rasterOp); } - + IntUnsafeNativeMethods.MoveToEx(hdc, oldPoint.x, oldPoint.y, null); } @@ -688,19 +691,19 @@ public void DrawLine(WindowsPen pen, int x1, int y1, int x2, int y2) /// public IntNativeMethods.TEXTMETRIC GetTextMetrics() { - IntNativeMethods.TEXTMETRIC tm = new IntNativeMethods.TEXTMETRIC(); - HandleRef hdc = new HandleRef( this.dc, this.dc.Hdc ); + IntNativeMethods.TEXTMETRIC tm = new IntNativeMethods.TEXTMETRIC(); + HandleRef hdc = new HandleRef(this.dc, this.dc.Hdc); // Set the mapping mode to MM_TEXT so we deal with units of pixels. DeviceContextMapMode mapMode = dc.MapMode; bool setupDC = mapMode != DeviceContextMapMode.Text; - if( setupDC ) + if (setupDC) { // Changing the MapMode will affect viewport and window extent and origin, we save the dc // state so all those properties can be properly restored once done. - dc.SaveHdc(); + dc.SaveHdc(); } try diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsGraphicsCacheManager.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsGraphicsCacheManager.cs index 430b7e9088f..c817316a4cc 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsGraphicsCacheManager.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsGraphicsCacheManager.cs @@ -47,7 +47,7 @@ class WindowsGraphicsCacheManager [ThreadStatic] private static int currentIndex; [ThreadStatic] - private static List> windowsFontCache; + private static List> windowsFontCache; /// /// Static constructor since this is a utility class. @@ -66,11 +66,11 @@ private WindowsGraphicsCacheManager() /// /// Initializes the WindowsFontCache object. /// - private static List> WindowsFontCache + private static List> WindowsFontCache { - get + get { - if (windowsFontCache == null) + if (windowsFontCache == null) { currentIndex = -1; windowsFontCache = new List>(CacheSize); @@ -79,7 +79,7 @@ private static List> WindowsFontCache return windowsFontCache; } } - + /// /// Get the cached screen (primary monitor) memory dc. /// Users of this class should always use this property to get the WindowsGraphics and never cache it, it could be mistakenly @@ -88,13 +88,13 @@ private static List> WindowsFontCache /// public static WindowsGraphics MeasurementGraphics { - - + + get { if (measurementGraphics == null || measurementGraphics.DeviceContext == null /*object disposed*/) { - Debug.Assert( measurementGraphics == null || measurementGraphics.DeviceContext != null, "TLS MeasurementGraphics was disposed somewhere, enable TRACK_HDC macro to determine who did it, recreating it for now ..." ); + Debug.Assert(measurementGraphics == null || measurementGraphics.DeviceContext != null, "TLS MeasurementGraphics was disposed somewhere, enable TRACK_HDC macro to determine who did it, recreating it for now ..."); #if TRACK_HDC //Debug.WriteLine( DbgUtil.StackTraceToStr(string.Format("Initializing MeasurementGraphics for thread: [0x{0:x8}]", Thread.CurrentThread.ManagedThreadId))); Debug.WriteLine( DbgUtil.StackTraceToStr("Initializing MeasurementGraphics")); @@ -108,7 +108,7 @@ public static WindowsGraphics MeasurementGraphics #if OPTIMIZED_MEASUREMENTDC // in some cases, we dont want to demand create MeasurementGraphics, as creating it has // re-entrant side effects. - internal static WindowsGraphics GetCurrentMeasurementGraphics() + internal static WindowsGraphics GetCurrentMeasurementGraphics() { return measurementGraphics; } @@ -119,19 +119,19 @@ internal static WindowsGraphics GetCurrentMeasurementGraphics() /// Get the cached WindowsFont associated with the specified font if one exists, otherwise create one and /// add it to the cache. /// - - + + public static WindowsFont GetWindowsFont(Font font) - { + { return GetWindowsFont(font, WindowsFontQuality.Default); } - - + + public static WindowsFont GetWindowsFont(Font font, WindowsFontQuality fontQuality) { - if( font == null ) + if (font == null) { return null; } @@ -142,7 +142,7 @@ public static WindowsFont GetWindowsFont(Font font, WindowsFontQuality fontQuali int index = currentIndex; // Search by index of most recently added object. - while( count < WindowsFontCache.Count ) + while (count < WindowsFontCache.Count) { if (WindowsFontCache[index].Key.Equals(font)) // don't do shallow comparison, we could miss cloned fonts. { @@ -152,16 +152,16 @@ public static WindowsFont GetWindowsFont(Font font, WindowsFontQuality fontQuali Debug.Assert(WindowsFontCache[index].Value.Hfont != IntPtr.Zero, "Cached WindowsFont was disposed, enable GDI_FINALIZATION_WATCH to track who did it!"); WindowsFont wf = WindowsFontCache[index].Value; - if(wf.Quality == fontQuality) + if (wf.Quality == fontQuality) { return wf; } - } + } index--; count++; - if( index < 0 ) + if (index < 0) { index = CacheSize - 1; } @@ -171,7 +171,7 @@ public static WindowsFont GetWindowsFont(Font font, WindowsFontQuality fontQuali WindowsFont winFont = WindowsFont.FromFont(font, fontQuality); KeyValuePair newEntry = new KeyValuePair(font, winFont); - + currentIndex++; if (currentIndex == CacheSize) @@ -180,42 +180,48 @@ public static WindowsFont GetWindowsFont(Font font, WindowsFontQuality fontQuali } if (WindowsFontCache.Count == CacheSize) // No more room, update current index. - { - WindowsFont wfont = null; + { + WindowsFont wfont = null; // Go through the existing fonts in the cache, and see if any // are not in use by a DC. If one isn't, replace that. If // all are in use, new up a new font and do not cache it. - + bool finished = false; int startIndex = currentIndex; int loopIndex = startIndex + 1; - while (!finished) { - if (loopIndex >= CacheSize) { + while (!finished) + { + if (loopIndex >= CacheSize) + { loopIndex = 0; } - if (loopIndex == startIndex) { + if (loopIndex == startIndex) + { finished = true; } - + wfont = WindowsFontCache[loopIndex].Value; - if (!DeviceContexts.IsFontInUse(wfont)) { + if (!DeviceContexts.IsFontInUse(wfont)) + { currentIndex = loopIndex; finished = true; break; } - else { + else + { loopIndex++; wfont = null; } } - - if (wfont != null) { + + if (wfont != null) + { WindowsFontCache[currentIndex] = newEntry; winFont.OwnedByCacheManager = true; - + #if GDI_FONT_CACHE_TRACK Debug.WriteLine("Removing from cache: " + wfont); Debug.WriteLine( "Adding to cache: " + winFont ); @@ -225,25 +231,26 @@ public static WindowsFont GetWindowsFont(Font font, WindowsFontQuality fontQuali wfont.OwnedByCacheManager = false; wfont.Dispose(); } - else { + else + { // do not cache font - caller is ALWAYS responsible for // disposing now. If it is owned by the CM, it will not // disposed. winFont.OwnedByCacheManager = false; - + #if GDI_FONT_CACHE_TRACK Debug.WriteLine("Creating uncached font: " + winFont); -#endif - } +#endif + } } else { winFont.OwnedByCacheManager = true; WindowsFontCache.Add(newEntry); - + #if GDI_FONT_CACHE_TRACK Debug.WriteLine( "Adding to cache: " + winFont ); #endif @@ -251,7 +258,7 @@ public static WindowsFont GetWindowsFont(Font font, WindowsFontQuality fontQuali return winFont; } - + #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY /// The following methods are not needed in production code since the cached objects are meant to be reused and should not be explicitly disposed, /// left here for testing purposes. diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsPen.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsPen.cs index 897d5928844..3e74adfe239 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsPen.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsPen.cs @@ -37,76 +37,76 @@ sealed partial class WindowsPen : MarshalByRefObject, ICloneable, IDisposable private IntPtr nativeHandle; private const int dashStyleMask = 0x0000000F; - private const int endCapMask = 0x00000F00; - private const int joinMask = 0x0000F000; + private const int endCapMask = 0x00000F00; + private const int joinMask = 0x0000F000; private DeviceContext dc; - + // // Fields with default values // private WindowsBrush wndBrush; private WindowsPenStyle style; private Color color; - private int width; - + private int width; + private const int cosmeticPenWidth = 1; // Cosmetic pen width. #if GDI_FINALIZATION_WATCH private string AllocationSite = DbgUtil.StackTrace; #endif - - + + public WindowsPen(DeviceContext dc) : - this( dc, WindowsPenStyle.Default, cosmeticPenWidth, Color.Black ) - { + this(dc, WindowsPenStyle.Default, cosmeticPenWidth, Color.Black) + { } - - - public WindowsPen(DeviceContext dc, Color color ) : - this( dc, WindowsPenStyle.Default, cosmeticPenWidth, color ) + + + public WindowsPen(DeviceContext dc, Color color) : + this(dc, WindowsPenStyle.Default, cosmeticPenWidth, color) { } - - - public WindowsPen(DeviceContext dc, WindowsBrush windowsBrush ) : - this( dc, WindowsPenStyle.Default, cosmeticPenWidth, windowsBrush ) + + + public WindowsPen(DeviceContext dc, WindowsBrush windowsBrush) : + this(dc, WindowsPenStyle.Default, cosmeticPenWidth, windowsBrush) { } - + public WindowsPen(DeviceContext dc, WindowsPenStyle style, int width, Color color) { this.style = style; this.width = width; this.color = color; - this.dc = dc; + this.dc = dc; // CreatePen() created on demand. } - - - public WindowsPen(DeviceContext dc, WindowsPenStyle style, int width, WindowsBrush windowsBrush ) + + + public WindowsPen(DeviceContext dc, WindowsPenStyle style, int width, WindowsBrush windowsBrush) { - Debug.Assert(windowsBrush != null, "null windowsBrush" ); - - this.style = style; - this.wndBrush = (WindowsBrush) windowsBrush.Clone(); - this.width = width; - this.color = windowsBrush.Color; - this.dc = dc; - + Debug.Assert(windowsBrush != null, "null windowsBrush"); + + this.style = style; + this.wndBrush = (WindowsBrush)windowsBrush.Clone(); + this.width = width; + this.color = windowsBrush.Color; + this.dc = dc; + // CreatePen() created on demand. } - - + + private void CreatePen() - { + { if (this.width > 1) // Geometric pen. { // From MSDN: if width > 1, the style must be PS_NULL, PS_SOLID, or PS_INSIDEFRAME. @@ -115,27 +115,27 @@ private void CreatePen() if (this.wndBrush == null) { - this.nativeHandle = IntSafeNativeMethods.CreatePen((int) this.style, this.width, ColorTranslator.ToWin32(this.color) ); + this.nativeHandle = IntSafeNativeMethods.CreatePen((int)this.style, this.width, ColorTranslator.ToWin32(this.color)); } else - { + { IntNativeMethods.LOGBRUSH lb = new IntNativeMethods.LOGBRUSH(); - lb.lbColor = ColorTranslator.ToWin32( this.wndBrush.Color ); + lb.lbColor = ColorTranslator.ToWin32(this.wndBrush.Color); lb.lbStyle = IntNativeMethods.BS_SOLID; - lb.lbHatch = 0; - + lb.lbHatch = 0; + // Note: We currently don't support custom styles, that's why 0 and null for last two params. - this.nativeHandle = IntSafeNativeMethods.ExtCreatePen((int)this.style, this.width, lb, 0, null ); + this.nativeHandle = IntSafeNativeMethods.ExtCreatePen((int)this.style, this.width, lb, 0, null); } } - - + + public object Clone() { - return (this.wndBrush != null) ? - new WindowsPen(this.dc, this.style, this.width, (WindowsBrush) this.wndBrush.Clone()) : + return (this.wndBrush != null) ? + new WindowsPen(this.dc, this.style, this.width, (WindowsBrush)this.wndBrush.Clone()) : new WindowsPen(this.dc, this.style, this.width, this.color); } @@ -172,26 +172,26 @@ void Dispose(bool disposing) } public IntPtr HPen - { + { get { - if( this.nativeHandle == IntPtr.Zero ) + if (this.nativeHandle == IntPtr.Zero) { CreatePen(); } - + return this.nativeHandle; } } public override string ToString() { - return string.Format( CultureInfo.InvariantCulture, "{0}: Style={1}, Color={2}, Width={3}, Brush={4}", - this.GetType().Name, - this.style, - this.color, - this.width, - this.wndBrush != null ? this.wndBrush.ToString() : "null" ); + return string.Format(CultureInfo.InvariantCulture, "{0}: Style={1}, Color={2}, Width={3}, Brush={4}", + this.GetType().Name, + this.style, + this.color, + this.width, + this.wndBrush != null ? this.wndBrush.ToString() : "null"); } } diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsPenStyle.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsPenStyle.cs index 8fbd1d56a4d..934e731b570 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsPenStyle.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsPenStyle.cs @@ -20,32 +20,32 @@ namespace System.Experimental.Gdi #endif enum WindowsPenStyle { - Solid = 0, - Dash = 1, /* ------- */ - Dot = 2, /* ....... */ - DashDot = 3, /* _._._._ */ - DashDotDot = 4, /* _.._.._ */ - Null = 5, - InsideFrame = 6, - UserStyle = 7, - Alternate = 8, + Solid = 0, + Dash = 1, /* ------- */ + Dot = 2, /* ....... */ + DashDot = 3, /* _._._._ */ + DashDotDot = 4, /* _.._.._ */ + Null = 5, + InsideFrame = 6, + UserStyle = 7, + Alternate = 8, // endcap style - EndcapRound = 0x00000000, - EndcapSquare = 0x00000100, - EndcapFlat = 0x00000200, - + EndcapRound = 0x00000000, + EndcapSquare = 0x00000100, + EndcapFlat = 0x00000200, + // join style - JoinRound = 0x00000000, - JoinBevel = 0x00001000, - JoinMiter = 0x00002000, + JoinRound = 0x00000000, + JoinBevel = 0x00001000, + JoinMiter = 0x00002000, // pen type style - Cosmetic = 0x00000000, - Geometric = 0x00010000, + Cosmetic = 0x00000000, + Geometric = 0x00010000, + + Default = 0x00000000 // Solid | EndcapRound | JoinRound | Cosmetic - Default = 0x00000000 // Solid | EndcapRound | JoinRound | Cosmetic - // (From wingdi.h) /* Pen Styles */ /* Pen Styles */ diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsRegion.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsRegion.cs index 6459862ca7a..fda79a09f69 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsRegion.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsRegion.cs @@ -30,7 +30,7 @@ namespace System.Experimental.Gdi #else internal #endif - sealed partial class WindowsRegion : MarshalByRefObject, ICloneable, IDisposable + sealed partial class WindowsRegion : MarshalByRefObject, ICloneable, IDisposable { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr nativeHandle; // The hRegion, this class always takes ownership of the hRegion. @@ -42,23 +42,26 @@ sealed partial class WindowsRegion : MarshalByRefObject, ICloneable, IDisposable /// /// - private WindowsRegion() { + private WindowsRegion() + { } /// /// - - - public WindowsRegion(Rectangle rect) { + + + public WindowsRegion(Rectangle rect) + { CreateRegion(rect); } /// /// - - - public WindowsRegion(int x, int y, int width, int height) { - CreateRegion(new Rectangle(x,y,width, height)); + + + public WindowsRegion(int x, int y, int width, int height) + { + CreateRegion(new Rectangle(x, y, width, height)); } // Consider implementing a constructor that calls ExtCreateRegion(XFORM lpXform, DWORD nCount, RGNDATA lpRgnData) if needed. @@ -67,15 +70,18 @@ public WindowsRegion(int x, int y, int width, int height) { /// Creates a WindowsRegion from a region handle, if 'takeOwnership' is true, the handle is added to the HandleCollector /// and is removed & destroyed on dispose. /// - public static WindowsRegion FromHregion(IntPtr hRegion, bool takeOwnership) { + public static WindowsRegion FromHregion(IntPtr hRegion, bool takeOwnership) + { WindowsRegion wr = new WindowsRegion(); // Note: Passing IntPtr.Zero for hRegion is ok. GDI+ infinite regions will have hRegion == null. // GDI's SelectClipRgn interprets null region handle as resetting the clip region (all region will be available for painting). - if( hRegion != IntPtr.Zero ) { + if (hRegion != IntPtr.Zero) + { wr.nativeHandle = hRegion; - if (takeOwnership) { + if (takeOwnership) + { wr.ownHandle = true; Interop.HandleCollector.Add(hRegion, Interop.CommonHandles.GDI); } @@ -86,8 +92,10 @@ public static WindowsRegion FromHregion(IntPtr hRegion, bool takeOwnership) { /// /// Creates a WindowsRegion from a System.Drawing.Region. /// - public static WindowsRegion FromRegion( Region region, Graphics g ){ - if (region.IsInfinite(g)){ + public static WindowsRegion FromRegion(Region region, Graphics g) + { + if (region.IsInfinite(g)) + { // An infinite region would cover the entire device region which is the same as // not having a clipping region. Observe that this is not the same as having an // empty region, which when clipping to it has the effect of excluding the entire @@ -104,13 +112,14 @@ public static WindowsRegion FromRegion( Region region, Graphics g ){ /// /// - - - public object Clone() { + + + public object Clone() + { // WARNING: WindowsRegion currently supports rectangulare regions only, if the WindowsRegion was created // from an HRegion and it is not rectangular this method won't work as expected. // Note: This method is currently not used and is here just to implement ICloneable. - return this.IsInfinite ? + return this.IsInfinite ? new WindowsRegion() : new WindowsRegion(this.ToRectangle()); } @@ -119,63 +128,75 @@ public object Clone() { /// Combines region1 & region2 into this region. The regions cannot be null. /// The three regions need not be distinct. For example, the sourceRgn1 can equal this region. /// - public IntNativeMethods.RegionFlags CombineRegion(WindowsRegion region1, WindowsRegion region2, RegionCombineMode mode) { + public IntNativeMethods.RegionFlags CombineRegion(WindowsRegion region1, WindowsRegion region2, RegionCombineMode mode) + { return IntUnsafeNativeMethods.CombineRgn(new HandleRef(this, this.HRegion), new HandleRef(region1, region1.HRegion), new HandleRef(region2, region2.HRegion), mode); } /// /// - - - private void CreateRegion(Rectangle rect) { + + + private void CreateRegion(Rectangle rect) + { Debug.Assert(nativeHandle == IntPtr.Zero, "nativeHandle should be null, we're leaking handle"); - this.nativeHandle = IntSafeNativeMethods.CreateRectRgn(rect.X, rect.Y, rect.X+rect.Width, rect.Y+rect.Height); + this.nativeHandle = IntSafeNativeMethods.CreateRectRgn(rect.X, rect.Y, rect.X + rect.Width, rect.Y + rect.Height); ownHandle = true; } /// /// - public void Dispose() { + public void Dispose() + { Dispose(true); } /// /// - public void Dispose(bool disposing) { - if (this.nativeHandle != IntPtr.Zero) { + public void Dispose(bool disposing) + { + if (this.nativeHandle != IntPtr.Zero) + { DbgUtil.AssertFinalization(this, disposing); - if( this.ownHandle ) { + if (this.ownHandle) + { IntUnsafeNativeMethods.DeleteObject(new HandleRef(this, this.nativeHandle)); } this.nativeHandle = IntPtr.Zero; - if (disposing) { + if (disposing) + { GC.SuppressFinalize(this); } } } - /// + /// /// - ~WindowsRegion() { + ~WindowsRegion() + { Dispose(false); } /// /// The native region handle. /// - public IntPtr HRegion { - get { + public IntPtr HRegion + { + get + { return this.nativeHandle; } } /// /// - public bool IsInfinite { - get { + public bool IsInfinite + { + get + { return this.nativeHandle == IntPtr.Zero; } } @@ -183,9 +204,11 @@ public bool IsInfinite { /// /// A rectangle representing the window region set with the SetWindowRgn function. /// - public Rectangle ToRectangle() { - if( this.IsInfinite ) { - return new Rectangle( -int.MaxValue, -int.MaxValue, int.MaxValue, int.MaxValue ); + public Rectangle ToRectangle() + { + if (this.IsInfinite) + { + return new Rectangle(-int.MaxValue, -int.MaxValue, int.MaxValue, int.MaxValue); } IntNativeMethods.RECT rect = new IntNativeMethods.RECT(); diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsRegionCombineMode.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsRegionCombineMode.cs index 4d2783a380a..61c47f61917 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsRegionCombineMode.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsRegionCombineMode.cs @@ -18,13 +18,13 @@ namespace System.Experimental.Gdi internal #endif enum RegionCombineMode - { - AND = 1, - OR = 2, - XOR = 3, + { + AND = 1, + OR = 2, + XOR = 3, DIFF = 4, COPY = 5, - MIN = AND, - MAX = COPY + MIN = AND, + MAX = COPY } } diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsSolidBrush.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsSolidBrush.cs index 9ccc1413eb5..883664ec7b5 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsSolidBrush.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsSolidBrush.cs @@ -25,12 +25,12 @@ namespace System.Experimental.Gdi #endif sealed class WindowsSolidBrush : WindowsBrush { - - + + protected override void CreateBrush() - { - IntPtr nativeHandle = IntSafeNativeMethods.CreateSolidBrush(ColorTranslator.ToWin32( this.Color)); - if(nativeHandle == IntPtr.Zero) // Don't use Debug.Assert, DbgUtil.GetLastErrorStr would always be evaluated. + { + IntPtr nativeHandle = IntSafeNativeMethods.CreateSolidBrush(ColorTranslator.ToWin32(this.Color)); + if (nativeHandle == IntPtr.Zero) // Don't use Debug.Assert, DbgUtil.GetLastErrorStr would always be evaluated. { Debug.Fail("CreateSolidBrush failed : " + DbgUtil.GetLastErrorStr()); } @@ -38,30 +38,30 @@ protected override void CreateBrush() this.NativeHandle = nativeHandle; // sets the handle value in the base class. } - - - public WindowsSolidBrush(DeviceContext dc) : base(dc) + + + public WindowsSolidBrush(DeviceContext dc) : base(dc) { // CreateBrush() on demand. } - - - public WindowsSolidBrush(DeviceContext dc, Color color) : base( dc, color ) + + + public WindowsSolidBrush(DeviceContext dc, Color color) : base(dc, color) { // CreateBrush() on demand. } - - + + public override object Clone() - { + { return new WindowsSolidBrush(this.DC, this.Color); } public override string ToString() { - return string.Format( CultureInfo.InvariantCulture, "{0}: Color={1}", this.GetType().Name, this.Color ); + return string.Format(CultureInfo.InvariantCulture, "{0}: Color={1}", this.GetType().Name, this.Color); } } } diff --git a/src/System.Windows.Forms/src/misc/ImageListUtils.cs b/src/System.Windows.Forms/src/misc/ImageListUtils.cs index 750f2b0ffb1..318f2249621 100644 --- a/src/System.Windows.Forms/src/misc/ImageListUtils.cs +++ b/src/System.Windows.Forms/src/misc/ImageListUtils.cs @@ -3,48 +3,58 @@ // See the LICENSE file in the project root for more information. -namespace System.Windows.Forms { +namespace System.Windows.Forms +{ using System; using System.ComponentModel; using System.Diagnostics; - + // Miscellaneous utilities - static internal class ImageListUtils { + static internal class ImageListUtils + { - public static PropertyDescriptor GetImageListProperty(PropertyDescriptor currentComponent, ref object instance) { - if(instance is object[]) //multiple selection is not supported by this class + public static PropertyDescriptor GetImageListProperty(PropertyDescriptor currentComponent, ref object instance) + { + if (instance is object[]) //multiple selection is not supported by this class return null; - + PropertyDescriptor imageListProp = null; object parentInstance = instance; - + RelatedImageListAttribute relILAttr = currentComponent.Attributes[typeof(RelatedImageListAttribute)] as RelatedImageListAttribute; - if (relILAttr != null) + if (relILAttr != null) { string[] pathInfo = relILAttr.RelatedImageList.Split('.'); - for(int i=0;i @@ -47,7 +48,7 @@ public static string GetAssemblyQualifiedName(Type type, Func type // ExecutionEngineException is obsolete and shouldn't be used (to catch, throw or reference) anymore. // Pragma added to prevent converting the "type is obsolete" warning into build error. - #pragma warning disable 618 +#pragma warning disable 618 private static bool IsSecurityOrCriticalException(Exception ex) { return ex is NullReferenceException @@ -59,6 +60,6 @@ private static bool IsSecurityOrCriticalException(Exception ex) || ex is AccessViolationException || ex is System.Security.SecurityException; } - #pragma warning restore 618 +#pragma warning restore 618 } } diff --git a/src/System.Windows.Forms/src/misc/WeakHashtable.cs b/src/System.Windows.Forms/src/misc/WeakHashtable.cs index 219797adf81..48cf42bf70b 100644 --- a/src/System.Windows.Forms/src/misc/WeakHashtable.cs +++ b/src/System.Windows.Forms/src/misc/WeakHashtable.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.ComponentModel { +namespace System.ComponentModel +{ using System; using System.Collections; @@ -16,8 +17,8 @@ internal sealed class WeakHashtable : Hashtable { private static IEqualityComparer _comparer = new WeakKeyComparer(); - private long _lastGlobalMem; - private int _lastHashCount; + private long _lastGlobalMem; + private int _lastHashCount; internal WeakHashtable() : base(_comparer) { @@ -93,7 +94,7 @@ private void ScavengeKeys() // for dead references. // ArrayList cleanupList = null; - foreach(object o in Keys) + foreach (object o in Keys) { WeakReference wr = o as WeakReference; if (wr != null && !wr.IsAlive) @@ -109,13 +110,13 @@ private void ScavengeKeys() if (cleanupList != null) { - foreach(object o in cleanupList) + foreach (object o in cleanupList) { Remove(o); } } } - + _lastGlobalMem = globalMem; _lastHashCount = hashCount; } @@ -157,7 +158,7 @@ bool IEqualityComparer.Equals(object x, object y) return false; } - int IEqualityComparer.GetHashCode (object obj) + int IEqualityComparer.GetHashCode(object obj) { return obj.GetHashCode(); } From 4dc3a0cb129c9d5a06b210267fc7aec6efc0f5d4 Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Thu, 23 May 2019 13:24:25 -0700 Subject: [PATCH 06/27] formatting System.Windows.Forms.Design --- .../Design/ComponentDesigner.cs | 8 +- .../Design/DesignerActionItemCollection.cs | 4 +- .../Design/DesignerActionListCollection.cs | 8 +- .../Design/DesignerActionPanel.cs | 6 +- .../Design/InheritedPropertyDescriptor.cs | 2 +- .../ComponentModel/Design/ReferenceService.cs | 2 +- .../CodeDomComponentSerializationService.cs | 69 +++-- .../CodeDomSerializationProvider.cs | 36 +-- .../Design/Serialization/CodeDomSerializer.cs | 26 +- .../Serialization/CodeDomSerializerBase.cs | 289 ++++++++++-------- .../CollectionCodeDomSerializer.cs | 14 +- .../ComponentCodeDomSerializer.cs | 251 +++++++-------- .../ComponentTypeCodeDomSerializer.cs | 38 +-- .../ContainerCodeDomSerializer.cs | 30 +- .../DesignerSerializationManager.cs | 6 +- .../Serialization/EnumCodeDomSerializer.cs | 42 +-- .../EventMemberCodeDomSerializer.cs | 40 +-- .../PrimitiveCodeDomSerializer.cs | 28 +- .../PropertyMemberCodeDomSerializer.cs | 177 +++++------ .../ResourceCodeDomSerializer.cs | 9 +- .../ToolboxComponentsCreatingEventArgs.cs | 2 +- .../src/System/Drawing/Design/ToolboxItem.cs | 3 +- .../Forms/Design/BaseContextMenuStrip.cs | 2 +- .../Forms/Design/Behavior/BehaviorService.cs | 29 +- .../Design/Behavior/ContainerSelectorGlyph.cs | 4 +- .../DesignerActionKeyboardBehavior.cs | 3 +- .../Design/Behavior/DropSourceBehavior.cs | 4 +- .../Forms/Design/Behavior/GlyphCollection.cs | 6 +- .../Design/Behavior/SelectionGlyphBase.cs | 8 +- .../Windows/Forms/Design/ComponentTray.cs | 6 +- .../Windows/Forms/Design/ControlDesigner.cs | 4 +- .../Forms/Design/DesignerActionService.cs | 2 +- .../Windows/Forms/Design/DesignerActionUI.cs | 35 ++- .../Windows/Forms/Design/DesignerFrame.cs | 2 +- .../ImageCollectionCodeDomSerializer.cs | 2 +- .../Forms/Design/OleDragDropHandler.cs | 18 +- .../Forms/Design/SelectionUIService.cs | 4 +- .../Forms/Design/StandardMenuStripVerb.cs | 2 +- .../Design/ToolStripAdornerWindowService.cs | 2 +- .../Forms/Design/ToolStripDesignerUtils.cs | 16 +- .../ToolStripItemCustomMenuItemCollection.cs | 10 +- .../Forms/Design/ToolStripItemDesigner.cs | 4 +- .../Forms/Design/ToolStripItemGlyph.cs | 2 +- .../Forms/Design/ToolStripMenuItemDesigner.cs | 2 +- .../System/Windows/Forms/Design/UndoEngine.cs | 19 +- 45 files changed, 674 insertions(+), 602 deletions(-) diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/ComponentDesigner.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/ComponentDesigner.cs index bf76439cd04..1a27a96bddb 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/ComponentDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/ComponentDesigner.cs @@ -255,10 +255,10 @@ public IComponent Component } } - /// - /// Gets the design-time verbs supported by the component associated with the designer. - /// - public virtual DesignerVerbCollection Verbs + /// + /// Gets the design-time verbs supported by the component associated with the designer. + /// + public virtual DesignerVerbCollection Verbs { get { diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerActionItemCollection.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerActionItemCollection.cs index 4aed3e2909f..0caec587f53 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerActionItemCollection.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerActionItemCollection.cs @@ -21,9 +21,9 @@ public DesignerActionItem this[int index] public void CopyTo(DesignerActionItem[] array, int index) => List.CopyTo(array, index); public int IndexOf(DesignerActionItem value) => List.IndexOf(value); - + public void Insert(int index, DesignerActionItem value) => List.Insert(index, value); - + public void Remove(DesignerActionItem value) => List.Remove(value); } } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerActionListCollection.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerActionListCollection.cs index 8d708ab5032..ba70d2e0d3b 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerActionListCollection.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerActionListCollection.cs @@ -57,13 +57,13 @@ public void AddRange(DesignerActionListCollection value) public void Insert(int index, DesignerActionList value) => List.Insert(index, value); public int IndexOf(DesignerActionList value) => List.IndexOf(value); - + public bool Contains(DesignerActionList value) => List.Contains(value); - + public void Remove(DesignerActionList value) => List.Remove(value); - + public void CopyTo(DesignerActionList[] array, int index) => List.CopyTo(array, index); - + protected override void OnValidate(object value) { // Don't perform any validation. diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerActionPanel.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerActionPanel.cs index 7b2112afc41..e6bed9f0d82 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerActionPanel.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerActionPanel.cs @@ -1506,7 +1506,7 @@ private sealed class CheckBoxPropertyLine : PropertyLine { private CheckBox _checkBox; - public CheckBoxPropertyLine(IServiceProvider serviceProvider, DesignerActionPanel actionPanel): base(serviceProvider, actionPanel) + public CheckBoxPropertyLine(IServiceProvider serviceProvider, DesignerActionPanel actionPanel) : base(serviceProvider, actionPanel) { } @@ -1523,7 +1523,7 @@ protected override void AddControls(List controls) controls.Add(_checkBox); } - public sealed override void Focus() => _checkBox.Focus(); + public sealed override void Focus() => _checkBox.Focus(); public override Size LayoutControls(int top, int width, bool measureOnly) { @@ -2447,7 +2447,7 @@ public void ShowDropDown(Control parent) { try { - UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_HWNDPARENT, new HandleRef(parent, parent.Handle)); + UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_HWNDPARENT, new HandleRef(parent, parent.Handle)); // Lifted directly from Form.ShowDialog()... IntPtr hWndCapture = UnsafeNativeMethods.GetCapture(); if (hWndCapture != IntPtr.Zero) diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/InheritedPropertyDescriptor.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/InheritedPropertyDescriptor.cs index 0b0eb479a6c..3108c49e0f4 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/InheritedPropertyDescriptor.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/InheritedPropertyDescriptor.cs @@ -27,7 +27,7 @@ internal class InheritedPropertyDescriptor : PropertyDescriptor /// Initializes a new instance of the class. /// [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] - public InheritedPropertyDescriptor( PropertyDescriptor propertyDescriptor, object component, bool rootComponent) : base(propertyDescriptor, new Attribute[] { }) + public InheritedPropertyDescriptor(PropertyDescriptor propertyDescriptor, object component, bool rootComponent) : base(propertyDescriptor, new Attribute[] { }) { Debug.Assert(!(propertyDescriptor is InheritedPropertyDescriptor), "Recursive inheritance propertyDescriptor " + propertyDescriptor.ToString()); this.propertyDescriptor = propertyDescriptor; diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/ReferenceService.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/ReferenceService.cs index 87890c33435..ad84bd591fc 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/ReferenceService.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/ReferenceService.cs @@ -54,7 +54,7 @@ private void CreateReferences(string trailingName, object reference, IComponent { if (property.IsReadOnly) { - CreateReferences( string.Format(CultureInfo.CurrentCulture, "{0}.{1}", trailingName, property.Name), property.GetValue(reference), sitedComponent); + CreateReferences(string.Format(CultureInfo.CurrentCulture, "{0}.{1}", trailingName, property.Name), property.GetValue(reference), sitedComponent); } } } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomComponentSerializationService.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomComponentSerializationService.cs index 9ddc60c5acf..8a4aa96b78d 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomComponentSerializationService.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomComponentSerializationService.cs @@ -60,9 +60,12 @@ public override SerializationStore LoadStore(Stream stream) /// public override void Serialize(SerializationStore store, object value) { - if (store == null) throw new ArgumentNullException(nameof(store)); - if (value == null) throw new ArgumentNullException(nameof(value)); - if (!(store is CodeDomSerializationStore cdStore)) throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceUnknownStore); + if (store == null) + throw new ArgumentNullException(nameof(store)); + if (value == null) + throw new ArgumentNullException(nameof(value)); + if (!(store is CodeDomSerializationStore cdStore)) + throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceUnknownStore); cdStore.AddObject(value, false); } @@ -71,9 +74,12 @@ public override void Serialize(SerializationStore store, object value) /// public override void SerializeAbsolute(SerializationStore store, object value) { - if (store == null) throw new ArgumentNullException(nameof(store)); - if (value == null) throw new ArgumentNullException(nameof(value)); - if (!(store is CodeDomSerializationStore cdStore)) throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceUnknownStore); + if (store == null) + throw new ArgumentNullException(nameof(store)); + if (value == null) + throw new ArgumentNullException(nameof(value)); + if (!(store is CodeDomSerializationStore cdStore)) + throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceUnknownStore); cdStore.AddObject(value, true); } @@ -82,10 +88,14 @@ public override void SerializeAbsolute(SerializationStore store, object value) /// public override void SerializeMember(SerializationStore store, object owningObject, MemberDescriptor member) { - if (store == null) throw new ArgumentNullException(nameof(store)); - if (owningObject == null) throw new ArgumentNullException(nameof(owningObject)); - if (member == null) throw new ArgumentNullException(nameof(member)); - if (!(store is CodeDomSerializationStore cdStore)) throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceUnknownStore); + if (store == null) + throw new ArgumentNullException(nameof(store)); + if (owningObject == null) + throw new ArgumentNullException(nameof(owningObject)); + if (member == null) + throw new ArgumentNullException(nameof(member)); + if (!(store is CodeDomSerializationStore cdStore)) + throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceUnknownStore); cdStore.AddMember(owningObject, member, false); } @@ -95,10 +105,14 @@ public override void SerializeMember(SerializationStore store, object owningObje /// public override void SerializeMemberAbsolute(SerializationStore store, object owningObject, MemberDescriptor member) { - if (store == null) throw new ArgumentNullException(nameof(store)); - if (owningObject == null) throw new ArgumentNullException(nameof(owningObject)); - if (member == null) throw new ArgumentNullException(nameof(member)); - if (!(store is CodeDomSerializationStore cdStore)) throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceUnknownStore); + if (store == null) + throw new ArgumentNullException(nameof(store)); + if (owningObject == null) + throw new ArgumentNullException(nameof(owningObject)); + if (member == null) + throw new ArgumentNullException(nameof(member)); + if (!(store is CodeDomSerializationStore cdStore)) + throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceUnknownStore); cdStore.AddMember(owningObject, member, true); } @@ -107,8 +121,10 @@ public override void SerializeMemberAbsolute(SerializationStore store, object ow /// public override ICollection Deserialize(SerializationStore store) { - if (store == null) throw new ArgumentNullException(nameof(store)); - if (!(store is CodeDomSerializationStore cdStore)) throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceUnknownStore); + if (store == null) + throw new ArgumentNullException(nameof(store)); + if (!(store is CodeDomSerializationStore cdStore)) + throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceUnknownStore); return cdStore.Deserialize(_provider); } @@ -117,9 +133,12 @@ public override ICollection Deserialize(SerializationStore store) /// public override ICollection Deserialize(SerializationStore store, IContainer container) { - if (store == null) throw new ArgumentNullException(nameof(store)); - if (container == null) throw new ArgumentNullException(nameof(container)); - if (!(store is CodeDomSerializationStore cdStore)) throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceUnknownStore); + if (store == null) + throw new ArgumentNullException(nameof(store)); + if (container == null) + throw new ArgumentNullException(nameof(container)); + if (!(store is CodeDomSerializationStore cdStore)) + throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceUnknownStore); return cdStore.Deserialize(_provider, container); } @@ -128,9 +147,12 @@ public override ICollection Deserialize(SerializationStore store, IContainer con /// public override void DeserializeTo(SerializationStore store, IContainer container, bool validateRecycledTypes, bool applyDefaults) { - if (store == null) throw new ArgumentNullException(nameof(store)); - if (container == null) throw new ArgumentNullException(nameof(container)); - if (!(store is CodeDomSerializationStore cdStore)) throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceUnknownStore); + if (store == null) + throw new ArgumentNullException(nameof(store)); + if (container == null) + throw new ArgumentNullException(nameof(container)); + if (!(store is CodeDomSerializationStore cdStore)) + throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceUnknownStore); cdStore.DeserializeTo(_provider, container, validateRecycledTypes, applyDefaults); } @@ -245,7 +267,8 @@ private LocalResourceManager Resources /// internal void AddMember(object value, MemberDescriptor member, bool absolute) { - if (_objectState != null) throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceClosedStore); + if (_objectState != null) + throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceClosedStore); ObjectData data = (ObjectData)_objects[value]; if (data == null) { diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializationProvider.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializationProvider.cs index 289c42664e0..e6b0c5c67da 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializationProvider.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializationProvider.cs @@ -19,17 +19,17 @@ internal sealed class CodeDomSerializationProvider : IDesignerSerializationProvi /// that is of the correct type, it should return it. /// Otherwise, it should return null. /// - object IDesignerSerializationProvider.GetSerializer(IDesignerSerializationManager manager, object currentSerializer, Type objectType, Type serializerType) + object IDesignerSerializationProvider.GetSerializer(IDesignerSerializationManager manager, object currentSerializer, Type objectType, Type serializerType) { - if (serializerType == typeof(CodeDomSerializer)) + if (serializerType == typeof(CodeDomSerializer)) { return GetCodeDomSerializer(manager, currentSerializer, objectType, serializerType); } - else if (serializerType == typeof(MemberCodeDomSerializer)) + else if (serializerType == typeof(MemberCodeDomSerializer)) { return GetMemberCodeDomSerializer(manager, currentSerializer, objectType, serializerType); } - else if (serializerType == typeof(TypeCodeDomSerializer)) + else if (serializerType == typeof(TypeCodeDomSerializer)) { return GetTypeCodeDomSerializer(manager, currentSerializer, objectType, serializerType); } @@ -40,11 +40,11 @@ object IDesignerSerializationProvider.GetSerializer(IDesignerSerializationManage /// /// Returns a code dom serializer /// - private object GetCodeDomSerializer(IDesignerSerializationManager manager, object currentSerializer, Type objectType, Type serializerType) + private object GetCodeDomSerializer(IDesignerSerializationManager manager, object currentSerializer, Type objectType, Type serializerType) { // If this isn't a serializer type we recognize, do nothing. Also, if metadata specified // a custom serializer, then use it. - if (currentSerializer != null) + if (currentSerializer != null) { return null; } @@ -53,13 +53,13 @@ private object GetCodeDomSerializer(IDesignerSerializationManager manager, objec // that the value we need to serialize is null, in which case we handle it // through the PrimitiveCodeDomSerializer. // - if (objectType == null) + if (objectType == null) { return PrimitiveCodeDomSerializer.Default; } // Support for components. - if (typeof(IComponent).IsAssignableFrom(objectType)) + if (typeof(IComponent).IsAssignableFrom(objectType)) { return ComponentCodeDomSerializer.Default; } @@ -67,31 +67,31 @@ private object GetCodeDomSerializer(IDesignerSerializationManager manager, objec // We special case enums. They do have instance descriptors, but we want // better looking code than the instance descriptor can provide for flags, // so we do it ourselves. - if (typeof(Enum).IsAssignableFrom(objectType)) + if (typeof(Enum).IsAssignableFrom(objectType)) { return EnumCodeDomSerializer.Default; } // We will provide a serializer for any intrinsic types. - if (objectType.IsPrimitive || objectType.IsEnum || objectType == typeof(string)) + if (objectType.IsPrimitive || objectType.IsEnum || objectType == typeof(string)) { return PrimitiveCodeDomSerializer.Default; } // And one for collections. - if (typeof(ICollection).IsAssignableFrom(objectType)) + if (typeof(ICollection).IsAssignableFrom(objectType)) { return CollectionCodeDomSerializer.Default; } // And one for IContainer - if (typeof(IContainer).IsAssignableFrom(objectType)) + if (typeof(IContainer).IsAssignableFrom(objectType)) { return ContainerCodeDomSerializer.Default; } // And one for resources - if (typeof(ResourceManager).IsAssignableFrom(objectType)) + if (typeof(ResourceManager).IsAssignableFrom(objectType)) { return ResourceCodeDomSerializer.Default; } @@ -103,20 +103,20 @@ private object GetCodeDomSerializer(IDesignerSerializationManager manager, objec /// /// Returns a code dom serializer for members /// - private object GetMemberCodeDomSerializer(IDesignerSerializationManager manager, object currentSerializer, Type objectType, Type serializerType) + private object GetMemberCodeDomSerializer(IDesignerSerializationManager manager, object currentSerializer, Type objectType, Type serializerType) { // Don't provide our serializer if someone else already had one - if (currentSerializer != null) + if (currentSerializer != null) { return null; } - if (typeof(PropertyDescriptor).IsAssignableFrom(objectType)) + if (typeof(PropertyDescriptor).IsAssignableFrom(objectType)) { return PropertyMemberCodeDomSerializer.Default; } - if (typeof(EventDescriptor).IsAssignableFrom(objectType)) + if (typeof(EventDescriptor).IsAssignableFrom(objectType)) { return EventMemberCodeDomSerializer.Default; } @@ -130,7 +130,7 @@ private object GetMemberCodeDomSerializer(IDesignerSerializationManager manager, private object GetTypeCodeDomSerializer(IDesignerSerializationManager manager, object currentSerializer, Type objectType, Type serializerType) { // Don't provide our serializer if someone else already had one - if (currentSerializer != null) + if (currentSerializer != null) { return null; } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializer.cs index efdb96ef94c..d3e402a4c84 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializer.cs @@ -20,11 +20,11 @@ public class CodeDomSerializer : CodeDomSerializerBase private static readonly Attribute[] _designTimeFilter = new Attribute[] { DesignOnlyAttribute.Yes }; private static CodeThisReferenceExpression _thisRef = new CodeThisReferenceExpression(); - internal static CodeDomSerializer Default + internal static CodeDomSerializer Default { - get + get { - if (s_default == null) + if (s_default == null) { s_default = new CodeDomSerializer(); } @@ -169,7 +169,7 @@ public virtual object Serialize(IDesignerSerializationManager manager, object va { throw new ArgumentNullException(nameof(manager)); } - if(value == null) + if (value == null) { throw new ArgumentNullException(nameof(value)); } @@ -271,9 +271,12 @@ public virtual object SerializeAbsolute(IDesignerSerializationManager manager, o /// public virtual CodeStatementCollection SerializeMember(IDesignerSerializationManager manager, object owningObject, MemberDescriptor member) { - if (manager == null) throw new ArgumentNullException(nameof(manager)); - if (owningObject == null) throw new ArgumentNullException(nameof(owningObject)); - if (member == null) throw new ArgumentNullException(nameof(member)); + if (manager == null) + throw new ArgumentNullException(nameof(manager)); + if (owningObject == null) + throw new ArgumentNullException(nameof(owningObject)); + if (member == null) + throw new ArgumentNullException(nameof(member)); CodeStatementCollection statements = new CodeStatementCollection(); // See if we have an existing expression for this member. If not, fabricate one @@ -308,9 +311,12 @@ public virtual CodeStatementCollection SerializeMember(IDesignerSerializationMan /// public virtual CodeStatementCollection SerializeMemberAbsolute(IDesignerSerializationManager manager, object owningObject, MemberDescriptor member) { - if (manager == null) throw new ArgumentNullException(nameof(manager)); - if (owningObject == null) throw new ArgumentNullException(nameof(owningObject)); - if (member == null) throw new ArgumentNullException(nameof(member)); + if (manager == null) + throw new ArgumentNullException(nameof(manager)); + if (owningObject == null) + throw new ArgumentNullException(nameof(owningObject)); + if (member == null) + throw new ArgumentNullException(nameof(member)); CodeStatementCollection statements; SerializeAbsoluteContext abs = new SerializeAbsoluteContext(member); diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs index 3be489bd7eb..2f86f08be41 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs @@ -42,7 +42,7 @@ protected virtual object DeserializeInstance(IDesignerSerializationManager manag { throw new ArgumentNullException(nameof(manager)); } - if (type == null) + if (type == null) { throw new ArgumentNullException(nameof(type)); } @@ -148,11 +148,11 @@ protected static Type GetReflectionTypeFromTypeHelper(IDesignerSerializationMana internal static void Error(IDesignerSerializationManager manager, string exceptionText, string helpLink) { - if (manager == null) + if (manager == null) { throw new ArgumentNullException(nameof(manager)); } - if (exceptionText == null) + if (exceptionText == null) { throw new ArgumentNullException(nameof(exceptionText)); } @@ -462,7 +462,8 @@ protected void DeserializePropertiesFromResources(IDesignerSerializationManager internal static IDisposable TraceScope(string name) { #if DEBUG - if (traceScope == null) traceScope = new Stack(); + if (traceScope == null) + traceScope = new Stack(); Trace(name); traceScope.Push(name); #endif @@ -472,7 +473,8 @@ internal static IDisposable TraceScope(string name) [Conditional("DEBUG")] internal static void TraceIf(bool condition, string message, params object[] values) { - if (condition) Trace(message, values); + if (condition) + Trace(message, values); } [Conditional("DEBUG")] @@ -483,7 +485,8 @@ internal static void Trace(string message, params object[] values) int indent = 0; int oldIndent = Debug.IndentLevel; - if (traceScope != null) indent = traceScope.Count; + if (traceScope != null) + indent = traceScope.Count; try { Debug.IndentLevel = indent; @@ -500,7 +503,8 @@ private struct TracingScope : IDisposable { public void Dispose() { - if (traceScope != null) traceScope.Pop(); + if (traceScope != null) + traceScope.Pop(); } } @@ -1530,7 +1534,7 @@ private object ExecuteBinaryExpression(IConvertible left, IConvertible right, Co { // "Binary" operator type is actually a combination of several types of operators: boolean, binary and math. Group them into categories here. - CodeBinaryOperatorType[] booleanOperators = new CodeBinaryOperatorType[] + CodeBinaryOperatorType[] booleanOperators = new CodeBinaryOperatorType[] { CodeBinaryOperatorType.IdentityInequality, CodeBinaryOperatorType.IdentityEquality, @@ -1543,7 +1547,7 @@ private object ExecuteBinaryExpression(IConvertible left, IConvertible right, Co CodeBinaryOperatorType.GreaterThanOrEqual }; - CodeBinaryOperatorType[] mathOperators = new CodeBinaryOperatorType[] + CodeBinaryOperatorType[] mathOperators = new CodeBinaryOperatorType[] { CodeBinaryOperatorType.Add, CodeBinaryOperatorType.Subtract, @@ -1552,7 +1556,7 @@ private object ExecuteBinaryExpression(IConvertible left, IConvertible right, Co CodeBinaryOperatorType.Modulus }; - CodeBinaryOperatorType[] binaryOperators = new CodeBinaryOperatorType[] + CodeBinaryOperatorType[] binaryOperators = new CodeBinaryOperatorType[] { CodeBinaryOperatorType.BitwiseOr, CodeBinaryOperatorType.BitwiseAnd @@ -1634,117 +1638,117 @@ private object ExecuteBinaryOperator(IConvertible left, IConvertible right, Code switch (compatibleTypes[maxIndex]) { case TypeCode.Byte: - { - byte leftValue = left.ToByte(null); - byte rightValue = right.ToByte(null); - if (op == CodeBinaryOperatorType.BitwiseOr) { - result = leftValue | rightValue; - } - else - { - result = leftValue & rightValue; + byte leftValue = left.ToByte(null); + byte rightValue = right.ToByte(null); + if (op == CodeBinaryOperatorType.BitwiseOr) + { + result = leftValue | rightValue; + } + else + { + result = leftValue & rightValue; + } + break; } - break; - } case TypeCode.Char: - { - char leftValue = left.ToChar(null); - char rightValue = right.ToChar(null); - if (op == CodeBinaryOperatorType.BitwiseOr) - { - result = leftValue | rightValue; - } - else { - result = leftValue & rightValue; + char leftValue = left.ToChar(null); + char rightValue = right.ToChar(null); + if (op == CodeBinaryOperatorType.BitwiseOr) + { + result = leftValue | rightValue; + } + else + { + result = leftValue & rightValue; + } + break; } - break; - } case TypeCode.Int16: - { - short leftValue = left.ToInt16(null); - short rightValue = right.ToInt16(null); - if (op == CodeBinaryOperatorType.BitwiseOr) - { - result = (short)((ushort)leftValue | (ushort)rightValue); - } - else { - result = leftValue & rightValue; + short leftValue = left.ToInt16(null); + short rightValue = right.ToInt16(null); + if (op == CodeBinaryOperatorType.BitwiseOr) + { + result = (short)((ushort)leftValue | (ushort)rightValue); + } + else + { + result = leftValue & rightValue; + } + break; } - break; - } case TypeCode.UInt16: - { - ushort leftValue = left.ToUInt16(null); - ushort rightValue = right.ToUInt16(null); - if (op == CodeBinaryOperatorType.BitwiseOr) { - result = leftValue | rightValue; - } - else - { - result = leftValue & rightValue; + ushort leftValue = left.ToUInt16(null); + ushort rightValue = right.ToUInt16(null); + if (op == CodeBinaryOperatorType.BitwiseOr) + { + result = leftValue | rightValue; + } + else + { + result = leftValue & rightValue; + } + break; } - break; - } case TypeCode.Int32: - { - int leftValue = left.ToInt32(null); - int rightValue = right.ToInt32(null); - if (op == CodeBinaryOperatorType.BitwiseOr) { - result = leftValue | rightValue; - } - else - { - result = leftValue & rightValue; + int leftValue = left.ToInt32(null); + int rightValue = right.ToInt32(null); + if (op == CodeBinaryOperatorType.BitwiseOr) + { + result = leftValue | rightValue; + } + else + { + result = leftValue & rightValue; + } + break; } - break; - } case TypeCode.UInt32: - { - uint leftValue = left.ToUInt32(null); - uint rightValue = right.ToUInt32(null); - if (op == CodeBinaryOperatorType.BitwiseOr) - { - result = leftValue | rightValue; - } - else { - result = leftValue & rightValue; + uint leftValue = left.ToUInt32(null); + uint rightValue = right.ToUInt32(null); + if (op == CodeBinaryOperatorType.BitwiseOr) + { + result = leftValue | rightValue; + } + else + { + result = leftValue & rightValue; + } + break; } - break; - } case TypeCode.Int64: - { - long leftValue = left.ToInt64(null); - long rightValue = right.ToInt64(null); - if (op == CodeBinaryOperatorType.BitwiseOr) - { - result = leftValue | rightValue; - } - else { - result = leftValue & rightValue; + long leftValue = left.ToInt64(null); + long rightValue = right.ToInt64(null); + if (op == CodeBinaryOperatorType.BitwiseOr) + { + result = leftValue | rightValue; + } + else + { + result = leftValue & rightValue; + } + break; } - break; - } case TypeCode.UInt64: - { - ulong leftValue = left.ToUInt64(null); - ulong rightValue = right.ToUInt64(null); - if (op == CodeBinaryOperatorType.BitwiseOr) { - result = leftValue | rightValue; - } - else - { - result = leftValue & rightValue; + ulong leftValue = left.ToUInt64(null); + ulong rightValue = right.ToUInt64(null); + if (op == CodeBinaryOperatorType.BitwiseOr) + { + result = leftValue | rightValue; + } + else + { + result = leftValue & rightValue; + } + break; } - break; - } } if (result != left && left is Enum) @@ -1799,31 +1803,31 @@ private object ExecuteMathOperator(IConvertible left, IConvertible right, CodeBi { if (op == CodeBinaryOperatorType.Add) { - string leftString = left as string; - string rightString = right as string; + string leftString = left as string; + string rightString = right as string; - if (leftString == null && left is Char) - { - leftString = left.ToString(); - } + if (leftString == null && left is Char) + { + leftString = left.ToString(); + } - if (rightString == null && right is Char) - { - rightString = right.ToString(); - } + if (rightString == null && right is Char) + { + rightString = right.ToString(); + } - if (leftString != null && rightString != null) - { - return leftString + rightString; - } - else - { - Debug.Fail("Addition operator not supported for this type"); - } + if (leftString != null && rightString != null) + { + return leftString + rightString; + } + else + { + Debug.Fail("Addition operator not supported for this type"); + } } else { - Debug.Fail("Math operators are not supported"); + Debug.Fail("Math operators are not supported"); } return left; } @@ -1888,7 +1892,7 @@ internal static void TraceErrorIf(bool condition, string message, params object[ [Conditional("DEBUG")] internal static void TraceWarningIf(bool condition, string message, params object[] values) { - if (condition) + if (condition) { TraceWarning(message, values); } @@ -2290,8 +2294,10 @@ protected bool IsSerialized(IDesignerSerializationManager manager, object value) protected bool IsSerialized(IDesignerSerializationManager manager, object value, bool honorPreset) { bool hasExpression = false; - if (manager == null) throw new ArgumentNullException(nameof(manager)); - if (value == null) throw new ArgumentNullException(nameof(value)); + if (manager == null) + throw new ArgumentNullException(nameof(manager)); + if (value == null) + throw new ArgumentNullException(nameof(value)); // Is the expression part of a prior SetExpression call? if (manager.Context[typeof(ExpressionTable)] is ExpressionTable table && table.GetExpression(value) != null && (!honorPreset || !table.ContainsPresetExpression(value))) @@ -2311,8 +2317,10 @@ protected bool IsSerialized(IDesignerSerializationManager manager, object value, protected CodeExpression SerializeCreationExpression(IDesignerSerializationManager manager, object value, out bool isComplete) { isComplete = false; - if (manager == null) throw new ArgumentNullException(nameof(manager)); - if (value == null) throw new ArgumentNullException(nameof(value)); + if (manager == null) + throw new ArgumentNullException(nameof(manager)); + if (value == null) + throw new ArgumentNullException(nameof(value)); TypeConverter converter = TypeDescriptor.GetConverter(value); // See if there is an ExpressionContext with a preset value we're interested in. If so, that will dictate our creation expression. @@ -2492,11 +2500,11 @@ private CodeExpression SerializeInstanceDescriptor(IDesignerSerializationManager /// protected string GetUniqueName(IDesignerSerializationManager manager, object value) { - if (manager == null) + if (manager == null) { throw new ArgumentNullException(nameof(manager)); } - if (value == null) + if (value == null) { throw new ArgumentNullException(nameof(value)); } @@ -2543,10 +2551,14 @@ protected string GetUniqueName(IDesignerSerializationManager manager, object val /// protected void SerializeEvent(IDesignerSerializationManager manager, CodeStatementCollection statements, object value, EventDescriptor descriptor) { - if (manager == null) throw new ArgumentNullException(nameof(manager)); - if (statements == null) throw new ArgumentNullException(nameof(statements)); - if (value == null) throw new ArgumentNullException(nameof(value)); - if (descriptor == null) throw new ArgumentNullException(nameof(descriptor)); + if (manager == null) + throw new ArgumentNullException(nameof(manager)); + if (statements == null) + throw new ArgumentNullException(nameof(statements)); + if (value == null) + throw new ArgumentNullException(nameof(value)); + if (descriptor == null) + throw new ArgumentNullException(nameof(descriptor)); using (TraceScope("CodeDomSerializerBase::" + nameof(SerializeEvent))) { @@ -2708,10 +2720,14 @@ protected void SerializePropertiesToResources(IDesignerSerializationManager mana /// protected void SerializeProperty(IDesignerSerializationManager manager, CodeStatementCollection statements, object value, PropertyDescriptor propertyToSerialize) { - if (manager == null) throw new ArgumentNullException(nameof(manager)); - if (value == null) throw new ArgumentNullException(nameof(value)); - if (propertyToSerialize == null) throw new ArgumentNullException(nameof(propertyToSerialize)); - if (statements == null) throw new ArgumentNullException(nameof(statements)); + if (manager == null) + throw new ArgumentNullException(nameof(manager)); + if (value == null) + throw new ArgumentNullException(nameof(value)); + if (propertyToSerialize == null) + throw new ArgumentNullException(nameof(propertyToSerialize)); + if (statements == null) + throw new ArgumentNullException(nameof(statements)); Trace("CodeDomSerializerBase::" + nameof(SerializeProperty) + " {0}", propertyToSerialize.Name); // Now look for a MemberCodeDomSerializer for the property. If we can't find one, then we can't serialize the property @@ -3051,9 +3067,12 @@ protected void SetExpression(IDesignerSerializationManager manager, object value [SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters")] protected void SetExpression(IDesignerSerializationManager manager, object value, CodeExpression expression, bool isPreset) { - if (manager == null) throw new ArgumentNullException(nameof(manager)); - if (value == null) throw new ArgumentNullException(nameof(value)); - if (expression == null) throw new ArgumentNullException(nameof(expression)); + if (manager == null) + throw new ArgumentNullException(nameof(manager)); + if (value == null) + throw new ArgumentNullException(nameof(value)); + if (expression == null) + throw new ArgumentNullException(nameof(expression)); ExpressionTable table = (ExpressionTable)manager.Context[typeof(ExpressionTable)]; if (table == null) diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CollectionCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CollectionCodeDomSerializer.cs index 33805db9a58..8cbf6ae9708 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CollectionCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CollectionCodeDomSerializer.cs @@ -25,7 +25,7 @@ public class CollectionCodeDomSerializer : CodeDomSerializer internal new static CollectionCodeDomSerializer Default { get - { + { if (s_defaultSerializer == null) { s_defaultSerializer = new CollectionCodeDomSerializer(); @@ -308,10 +308,14 @@ private static MethodInfo ChooseMethodByType(TypeDescriptionProvider provider, L /// protected virtual object SerializeCollection(IDesignerSerializationManager manager, CodeExpression targetExpression, Type targetType, ICollection originalCollection, ICollection valuesToSerialize) { - if (manager == null) throw new ArgumentNullException(nameof(manager)); - if (targetType == null) throw new ArgumentNullException(nameof(targetType)); - if (originalCollection == null) throw new ArgumentNullException(nameof(originalCollection)); - if (valuesToSerialize == null) throw new ArgumentNullException(nameof(valuesToSerialize)); + if (manager == null) + throw new ArgumentNullException(nameof(manager)); + if (targetType == null) + throw new ArgumentNullException(nameof(targetType)); + if (originalCollection == null) + throw new ArgumentNullException(nameof(originalCollection)); + if (valuesToSerialize == null) + throw new ArgumentNullException(nameof(valuesToSerialize)); object result = null; bool serialized = false; diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentCodeDomSerializer.cs index 2cb9eb41dd5..e13d1ce5061 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentCodeDomSerializer.cs @@ -13,10 +13,10 @@ using System.Reflection; using System.Text; -namespace System.ComponentModel.Design.Serialization +namespace System.ComponentModel.Design.Serialization { - - internal class ComponentCodeDomSerializer : CodeDomSerializer + + internal class ComponentCodeDomSerializer : CodeDomSerializer { private Type[] _containerConstructor = null; @@ -24,30 +24,30 @@ internal class ComponentCodeDomSerializer : CodeDomSerializer private static readonly Attribute[] _designTimeFilter = new Attribute[] { DesignOnlyAttribute.Yes }; private static WeakReference s_defaultSerializerRef; - private Type[] GetContainerConstructor(IDesignerSerializationManager manager) + private Type[] GetContainerConstructor(IDesignerSerializationManager manager) { - if (_containerConstructor == null) + if (_containerConstructor == null) { - _containerConstructor = new Type[] - { - GetReflectionTypeFromTypeHelper(manager, typeof(IContainer)) + _containerConstructor = new Type[] + { + GetReflectionTypeFromTypeHelper(manager, typeof(IContainer)) }; } return _containerConstructor; - } + } /// /// Retrieves a default static instance of this serializer. /// - internal new static ComponentCodeDomSerializer Default + internal new static ComponentCodeDomSerializer Default { - get + get { ComponentCodeDomSerializer defaultSerializer; - if (s_defaultSerializerRef != null) + if (s_defaultSerializerRef != null) { defaultSerializer = s_defaultSerializerRef.Target as ComponentCodeDomSerializer; - if (defaultSerializer != null) + if (defaultSerializer != null) { return defaultSerializer; } @@ -63,28 +63,28 @@ private Type[] GetContainerConstructor(IDesignerSerializationManager manager) /// Determines if we can cache the results of serializing a component. /// private bool CanCacheComponent(IDesignerSerializationManager manager, object value, PropertyDescriptorCollection props) - { - IComponent comp = value as IComponent; + { + IComponent comp = value as IComponent; - if (comp != null) + if (comp != null) { - if (comp.Site != null) + if (comp.Site != null) { INestedSite nestedSite = comp.Site as INestedSite; - if (nestedSite != null && !string.IsNullOrEmpty(nestedSite.FullName)) + if (nestedSite != null && !string.IsNullOrEmpty(nestedSite.FullName)) { return false; } } - - if (props == null) - { - props = TypeDescriptor.GetProperties(comp); - } - foreach (PropertyDescriptor property in props) + + if (props == null) + { + props = TypeDescriptor.GetProperties(comp); + } + foreach (PropertyDescriptor property in props) { - if (typeof(IComponent).IsAssignableFrom(property.PropertyType) && - !property.Attributes.Contains(DesignerSerializationVisibilityAttribute.Hidden)) + if (typeof(IComponent).IsAssignableFrom(property.PropertyType) && + !property.Attributes.Contains(DesignerSerializationVisibilityAttribute.Hidden)) { MemberCodeDomSerializer memberSerializer = (MemberCodeDomSerializer)manager.GetSerializer(property.GetType(), typeof(MemberCodeDomSerializer)); @@ -104,12 +104,12 @@ private bool CanCacheComponent(IDesignerSerializationManager manager, object val /// of the requested type should be returned. This implementation calls base and then tries to deserialize design /// time properties for the component. /// - protected override object DeserializeInstance(IDesignerSerializationManager manager, Type type, object[] parameters, string name, bool addToContainer) + protected override object DeserializeInstance(IDesignerSerializationManager manager, Type type, object[] parameters, string name, bool addToContainer) { object instance = base.DeserializeInstance(manager, type, parameters, name, addToContainer); - if (instance != null) + if (instance != null) { Trace("Deserializing design time properties for {0}", manager.GetName(instance)); DeserializePropertiesFromResources(manager, instance, _designTimeFilter); @@ -122,18 +122,18 @@ protected override object DeserializeInstance(IDesignerSerializationManager mana /// Serializes the given object into a CodeDom object. /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2102:CatchNonClsCompliantExceptionsInGeneralHandlers")] - public override object Serialize(IDesignerSerializationManager manager, object value) + public override object Serialize(IDesignerSerializationManager manager, object value) { CodeStatementCollection statements = null; - PropertyDescriptorCollection props = TypeDescriptor.GetProperties(value); - using (TraceScope("ComponentCodeDomSerializer::Serialize")) + PropertyDescriptorCollection props = TypeDescriptor.GetProperties(value); + using (TraceScope("ComponentCodeDomSerializer::Serialize")) { - if (manager == null || value == null) + if (manager == null || value == null) { throw new ArgumentNullException(manager == null ? "manager" : "value"); } - if (IsSerialized(manager, value)) + if (IsSerialized(manager, value)) { Debug.Fail("Serialize is being called twice for the same component"); return GetExpression(manager, value); @@ -144,7 +144,7 @@ public override object Serialize(IDesignerSerializationManager manager, object v InheritanceLevel inheritanceLevel = InheritanceLevel.NotInherited; InheritanceAttribute inheritanceAttribute = (InheritanceAttribute)TypeDescriptor.GetAttributes(value)[typeof(InheritanceAttribute)]; - if (inheritanceAttribute != null) + if (inheritanceAttribute != null) { inheritanceLevel = inheritanceAttribute.InheritanceLevel; } @@ -152,7 +152,7 @@ public override object Serialize(IDesignerSerializationManager manager, object v // First, skip everything if we're privately inherited. We cannot write any code that would affect this // component. TraceIf(inheritanceLevel == InheritanceLevel.InheritedReadOnly, "Skipping read only inherited component"); - if (inheritanceLevel != InheritanceLevel.InheritedReadOnly) + if (inheritanceLevel != InheritanceLevel.InheritedReadOnly) { // Things we need to know: // @@ -180,47 +180,47 @@ public override object Serialize(IDesignerSerializationManager manager, object v assignLhs = GetExpression(manager, value); - if (assignLhs != null) + if (assignLhs != null) { Trace("Existing expression for LHS of value"); generateLocal = false; generateField = false; generateObject = false; - - // if we have an existing expression and this is not - // a sited component, do not serialize it. We need this for Everett / 1.0 - // backwards compat (even though it's wrong). - IComponent comp = value as IComponent; - if (comp != null && comp.Site == null) - { - // We were in a serialize content - // property and would still serialize it. This code reverses what the - // outer if block does for this specific case. We also need this - // for Everett / 1.0 backwards compat. - ExpressionContext expCxt = manager.Context[typeof(ExpressionContext)] as ExpressionContext; - if (expCxt == null || expCxt.PresetValue != value) - { - isComplete = true; - } - } + + // if we have an existing expression and this is not + // a sited component, do not serialize it. We need this for Everett / 1.0 + // backwards compat (even though it's wrong). + IComponent comp = value as IComponent; + if (comp != null && comp.Site == null) + { + // We were in a serialize content + // property and would still serialize it. This code reverses what the + // outer if block does for this specific case. We also need this + // for Everett / 1.0 backwards compat. + ExpressionContext expCxt = manager.Context[typeof(ExpressionContext)] as ExpressionContext; + if (expCxt == null || expCxt.PresetValue != value) + { + isComplete = true; + } + } } - else + else { Trace("Creating LHS expression"); - if (inheritanceLevel == InheritanceLevel.NotInherited) - { + if (inheritanceLevel == InheritanceLevel.NotInherited) + { // See if there is a "GenerateMember" property. If so, // we might want to generate a local variable. Otherwise, // we want to generate a field. PropertyDescriptor generateProp = props["GenerateMember"]; - if (generateProp != null && generateProp.PropertyType == typeof(bool) && !(bool)generateProp.GetValue(value)) + if (generateProp != null && generateProp.PropertyType == typeof(bool) && !(bool)generateProp.GetValue(value)) { Trace("Object GenerateMember property wants a local variable"); generateLocal = true; generateField = false; } } - else + else { generateObject = false; } @@ -237,7 +237,7 @@ public override object Serialize(IDesignerSerializationManager manager, object v manager.Context.Push(value); manager.Context.Push(statements); - try + try { string name = manager.GetName(value); @@ -245,48 +245,48 @@ public override object Serialize(IDesignerSerializationManager manager, object v string typeName = TypeDescriptor.GetClassName(value); // Output variable / field declarations if we need to - if ((generateField || generateLocal) && name != null) + if ((generateField || generateLocal) && name != null) { - if (generateField) + if (generateField) { - if (inheritanceLevel == InheritanceLevel.NotInherited) + if (inheritanceLevel == InheritanceLevel.NotInherited) { // We need to generate the field declaration. See if there is a modifiers property on // the object. If not, look for a DefaultModifies, and finally assume it's private. CodeMemberField field = new CodeMemberField(typeName, name); PropertyDescriptor modifersProp = props["Modifiers"]; MemberAttributes fieldAttrs; - - if (modifersProp == null) + + if (modifersProp == null) { modifersProp = props["DefaultModifiers"]; } - if (modifersProp != null && modifersProp.PropertyType == typeof(MemberAttributes)) + if (modifersProp != null && modifersProp.PropertyType == typeof(MemberAttributes)) { fieldAttrs = (MemberAttributes)modifersProp.GetValue(value); } - else + else { TraceWarning("No Modifiers or DefaultModifiers property on component {0}. We must assume private.", name); fieldAttrs = MemberAttributes.Private; } - + field.Attributes = fieldAttrs; typeDecl.Members.Add(field); Trace("Field {0} {1} {2} created.", fieldAttrs, typeName, name); } - + // Next, create a nice LHS for our pending assign statement, when we hook up the variable. assignLhs = new CodeFieldReferenceExpression(rootCxt.Expression, name); } - else + else { - if (inheritanceLevel == InheritanceLevel.NotInherited) + if (inheritanceLevel == InheritanceLevel.NotInherited) { CodeVariableDeclarationStatement local = new CodeVariableDeclarationStatement(typeName, name); - + statements.Add(local); Trace("Local {0} {1} created.", typeName, name); } @@ -294,11 +294,11 @@ public override object Serialize(IDesignerSerializationManager manager, object v assignLhs = new CodeVariableReferenceExpression(name); } } - + // Now output an object create if we need to. We always see if there is a // type converter that can provide us guidance - if (generateObject) + if (generateObject) { // Ok, now that we've decided if we have a local or a member variable, its now time to serialize the rest of the code. // The first step is to create an assign statement to "new" the object. For that, we need to know if @@ -306,21 +306,21 @@ public override object Serialize(IDesignerSerializationManager manager, object v // that we can get to an actual IContainer. IContainer container = manager.GetService(typeof(IContainer)) as IContainer; ConstructorInfo ctor = null; - if (container != null) + if (container != null) { ctor = GetReflectionTypeHelper(manager, value).GetConstructor(BindingFlags.ExactBinding | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, GetContainerConstructor(manager), null); } - if (ctor != null) + if (ctor != null) { Trace("Component has IContainer constructor."); - assignRhs = new CodeObjectCreateExpression(typeName, new CodeExpression[] + assignRhs = new CodeObjectCreateExpression(typeName, new CodeExpression[] { SerializeToExpression(manager, container) }); } - else - { + else + { // For compat reasons we ignore the isCompleteOld value here. bool isCompleteOld; assignRhs = SerializeCreationExpression(manager, value, out isCompleteOld); @@ -328,23 +328,23 @@ public override object Serialize(IDesignerSerializationManager manager, object v } TraceErrorIf(assignRhs == null, "No RHS code assign for object {0}", value); - if (assignRhs != null) + if (assignRhs != null) { - if (assignLhs == null) + if (assignLhs == null) { // We cannot do much more for this object. If isComplete is true, // then the RHS now becomes our LHS. Otherwise, I'm afraid we have // just failed to serialize this object. - if (isComplete) + if (isComplete) { assignLhs = assignRhs; } - else + else { TraceError("Incomplete serialization of object, abandoning serialization."); } } - else + else { CodeAssignStatement assign = new CodeAssignStatement(assignLhs, assignRhs); statements.Add(assign); @@ -352,26 +352,26 @@ public override object Serialize(IDesignerSerializationManager manager, object v } } - if (assignLhs != null) + if (assignLhs != null) { SetExpression(manager, value, assignLhs); } // It should practically be an assert that isComplete is false, but someone may // have an unusual component. - if (assignLhs != null && !isComplete) + if (assignLhs != null && !isComplete) { // .NET CF needs us to verify that the ISupportInitialize interface exists // (they do not support this interface and will modify their DSM to resolve the type to null). bool supportInitialize = (value is ISupportInitialize); - if (supportInitialize) + if (supportInitialize) { string fullName = typeof(ISupportInitialize).FullName; supportInitialize = manager.GetType(fullName) != null; } Type reflectionType = null; - if (supportInitialize) + if (supportInitialize) { // Now verify that this control implements ISupportInitialize in the project target framework // Don't use operator "is" but rather use IsAssignableFrom on the reflection types. @@ -384,12 +384,12 @@ public override object Serialize(IDesignerSerializationManager manager, object v } bool persistSettings = (value is IPersistComponentSettings) && ((IPersistComponentSettings)value).SaveSettings; - if (persistSettings) + if (persistSettings) { string fullName = typeof(IPersistComponentSettings).FullName; persistSettings = manager.GetType(fullName) != null; } - if (persistSettings) + if (persistSettings) { reflectionType = reflectionType ?? GetReflectionTypeHelper(manager, value); persistSettings = GetReflectionTypeFromTypeHelper(manager, typeof(IPersistComponentSettings)).IsAssignableFrom(reflectionType); @@ -398,7 +398,7 @@ public override object Serialize(IDesignerSerializationManager manager, object v // serialization managers. How do we tell the difference? The main serialization manager exists as a service. IDesignerSerializationManager mainManager = (IDesignerSerializationManager)manager.GetService(typeof(IDesignerSerializationManager)); - if (supportInitialize) + if (supportInitialize) { Trace("Object implements ISupportInitialize."); SerializeSupportInitialize(manager, statements, assignLhs, value, "BeginInit"); @@ -411,28 +411,29 @@ public override object Serialize(IDesignerSerializationManager manager, object v // code and then see if we can cache the results for later. ComponentCache cache = (ComponentCache)manager.GetService(typeof(ComponentCache)); ComponentCache.Entry entry = null; - if (cache == null) + if (cache == null) { IServiceContainer sc = (IServiceContainer)manager.GetService(typeof(IServiceContainer)); - if (sc != null) + if (sc != null) { cache = new ComponentCache(manager); sc.AddService(typeof(ComponentCache), cache); } } - else + else { - if (manager == mainManager && cache != null && cache.Enabled) { + if (manager == mainManager && cache != null && cache.Enabled) + { entry = cache[value]; } } - - if (entry == null || entry.Tracking) + + if (entry == null || entry.Tracking) { // Pushing the entry here allows it to be found by the resource code dom serializer, // which will add data to the ResourceBlob property on the entry. - if (entry == null) + if (entry == null) { entry = new ComponentCache.Entry(cache); @@ -443,16 +444,16 @@ public override object Serialize(IDesignerSerializationManager manager, object v // we need to make sure we copy over any dependencies that are also tracked. ComponentCache.Entry oldEntry = null; oldEntry = cache.GetEntryAll(value); - if (oldEntry != null && oldEntry.Dependencies != null && oldEntry.Dependencies.Count > 0) + if (oldEntry != null && oldEntry.Dependencies != null && oldEntry.Dependencies.Count > 0) { - foreach(object dependency in oldEntry.Dependencies) + foreach (object dependency in oldEntry.Dependencies) { entry.AddDependency(dependency); } } - + } - entry.Component = value; + entry.Component = value; // we need to link the cached entry with its corresponding component right away, before it's put in the context // see CodeDomSerializerBase.cs::GetExpression for usage @@ -461,49 +462,49 @@ public override object Serialize(IDesignerSerializationManager manager, object v // between components even if they are not cached. See VSWhidbey 263053. bool correctManager = manager == mainManager; entry.Valid = correctManager && CanCacheComponent(manager, value, props); - - if (correctManager && cache != null && cache.Enabled) + + if (correctManager && cache != null && cache.Enabled) { manager.Context.Push(cache); manager.Context.Push(entry); } - try + try { entry.Statements = new CodeStatementCollection(); SerializeProperties(manager, entry.Statements, value, _runTimeFilter); SerializeEvents(manager, entry.Statements, value, null); - foreach (CodeStatement statement in entry.Statements) + foreach (CodeStatement statement in entry.Statements) { CodeVariableDeclarationStatement local = statement as CodeVariableDeclarationStatement; - if (local != null) + if (local != null) { entry.Tracking = true; break; } } - if (entry.Statements.Count > 0) + if (entry.Statements.Count > 0) { // if we added some statements, insert the comments // entry.Statements.Insert(0, new CodeCommentStatement(string.Empty)); entry.Statements.Insert(0, new CodeCommentStatement(name)); entry.Statements.Insert(0, new CodeCommentStatement(string.Empty)); - + // // cache the statements for future usage if possible. We only do this for the main serialization manager, not // for any other seriallization managers that may be calling us for undo or clipboard functions. - if (correctManager && cache != null && cache.Enabled) + if (correctManager && cache != null && cache.Enabled) { cache[value] = entry; } } } - finally + finally { - if (correctManager && cache != null && cache.Enabled) + if (correctManager && cache != null && cache.Enabled) { Debug.Assert(manager.Context.Current == entry, "Context stack corrupted"); manager.Context.Pop(); @@ -511,41 +512,41 @@ public override object Serialize(IDesignerSerializationManager manager, object v } } } - else + else { // If we got a cache entry, we will need to take all the resources out of // it and apply them too. - if ((entry.Resources != null || entry.Metadata != null) && cache != null && cache.Enabled) + if ((entry.Resources != null || entry.Metadata != null) && cache != null && cache.Enabled) { ResourceCodeDomSerializer res = ResourceCodeDomSerializer.Default; res.ApplyCacheEntry(manager, entry); - } + } } // Regarless, apply statements. Either we created them or we got them // out of the cache. statements.AddRange(entry.Statements); - if (persistSettings) + if (persistSettings) { SerializeLoadComponentSettings(manager, statements, assignLhs, value); } - if (supportInitialize) + if (supportInitialize) { SerializeSupportInitialize(manager, statements, assignLhs, value, "EndInit"); } } } - catch (CheckoutException) + catch (CheckoutException) { throw; } - catch (Exception ex) + catch (Exception ex) { manager.ReportError(ex); } - finally + finally { Debug.Assert(manager.Context.Current == statements, "Context stack corrupted"); manager.Context.Pop(); @@ -561,7 +562,7 @@ public override object Serialize(IDesignerSerializationManager manager, object v /// This emits a method invoke to IPersistComponentSettings.LoadComponentSettings. /// private void SerializeLoadComponentSettings(IDesignerSerializationManager manager, CodeStatementCollection statements, CodeExpression valueExpression, object value) - { + { Trace("Emitting LoadComponentSettings"); CodeTypeReference type = new CodeTypeReference(typeof(IPersistComponentSettings)); @@ -573,14 +574,14 @@ private void SerializeLoadComponentSettings(IDesignerSerializationManager manage CodeExpressionStatement statement = new CodeExpressionStatement(methodInvoke); statement.UserData["statement-ordering"] = "end"; - + statements.Add(statement); } - + /// /// This emits a method invoke to ISupportInitialize. /// - private void SerializeSupportInitialize(IDesignerSerializationManager manager, CodeStatementCollection statements, CodeExpression valueExpression, object value, string methodName) + private void SerializeSupportInitialize(IDesignerSerializationManager manager, CodeStatementCollection statements, CodeExpression valueExpression, object value, string methodName) { Trace("Emitting {0}", methodName); @@ -593,11 +594,11 @@ private void SerializeSupportInitialize(IDesignerSerializationManager manager, C CodeExpressionStatement statement = new CodeExpressionStatement(methodInvoke); - if (methodName == "BeginInit") + if (methodName == "BeginInit") { statement.UserData["statement-ordering"] = "begin"; } - else + else { statement.UserData["statement-ordering"] = "end"; } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentTypeCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentTypeCodeDomSerializer.cs index 5423c024724..ce40db3203b 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentTypeCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentTypeCodeDomSerializer.cs @@ -9,22 +9,22 @@ using System.Collections.Generic; using System.Diagnostics; -namespace System.ComponentModel.Design.Serialization -{ +namespace System.ComponentModel.Design.Serialization +{ /// /// This class performs the same tasks as a CodeDomSerializer only serializing an object through this class defines a new type. /// - internal class ComponentTypeCodeDomSerializer : TypeCodeDomSerializer + internal class ComponentTypeCodeDomSerializer : TypeCodeDomSerializer { private static object _initMethodKey = new object(); private const string _initMethodName = "InitializeComponent"; private static ComponentTypeCodeDomSerializer s_default; - internal new static ComponentTypeCodeDomSerializer Default + internal new static ComponentTypeCodeDomSerializer Default { - get + get { - if (s_default == null) + if (s_default == null) { s_default = new ComponentTypeCodeDomSerializer(); } @@ -37,26 +37,26 @@ internal class ComponentTypeCodeDomSerializer : TypeCodeDomSerializer /// This method returns the method to emit all of the initialization code to for the given member. /// The default implementation returns an empty constructor. /// - protected override CodeMemberMethod GetInitializeMethod(IDesignerSerializationManager manager, CodeTypeDeclaration typeDecl, object value) + protected override CodeMemberMethod GetInitializeMethod(IDesignerSerializationManager manager, CodeTypeDeclaration typeDecl, object value) { - if (manager == null) + if (manager == null) { throw new ArgumentNullException(nameof(manager)); } - if (typeDecl == null) + if (typeDecl == null) { throw new ArgumentNullException(nameof(typeDecl)); } - if (value == null) + if (value == null) { throw new ArgumentNullException(nameof(value)); } CodeMemberMethod method = typeDecl.UserData[_initMethodKey] as CodeMemberMethod; - if (method == null) + if (method == null) { method = new CodeMemberMethod(); method.Name = _initMethodName; @@ -77,19 +77,19 @@ protected override CodeMemberMethod GetInitializeMethod(IDesignerSerializationMa /// This method returns an array of methods that need to be interpreted during deserialization. /// The default implementation returns a single element array with the constructor in it. /// - protected override CodeMemberMethod[] GetInitializeMethods(IDesignerSerializationManager manager, CodeTypeDeclaration typeDecl) + protected override CodeMemberMethod[] GetInitializeMethods(IDesignerSerializationManager manager, CodeTypeDeclaration typeDecl) { - if (manager == null) + if (manager == null) { throw new ArgumentNullException(nameof(manager)); } - if (typeDecl == null) + if (typeDecl == null) { throw new ArgumentNullException(nameof(typeDecl)); } - foreach (CodeTypeMember member in typeDecl.Members) + foreach (CodeTypeMember member in typeDecl.Members) { CodeMemberMethod method = member as CodeMemberMethod; @@ -97,11 +97,11 @@ protected override CodeMemberMethod[] GetInitializeMethods(IDesignerSerializatio // method.Parameters causes OnMethodPopulateParameters callback and therefore it is much more // expensive than method.Name.Equals - if (method != null && method.Name.Equals(_initMethodName) && method.Parameters.Count == 0 ) + if (method != null && method.Name.Equals(_initMethodName) && method.Parameters.Count == 0) { - return new CodeMemberMethod[] - { - method + return new CodeMemberMethod[] + { + method }; } } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ContainerCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ContainerCodeDomSerializer.cs index 5599b5a53e7..529bb56fffc 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ContainerCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ContainerCodeDomSerializer.cs @@ -10,25 +10,25 @@ using System.Diagnostics; using System.Reflection; -namespace System.ComponentModel.Design.Serialization +namespace System.ComponentModel.Design.Serialization { /// /// This class is used to serialize things of type "IContainer". We route all containers /// to the designer host's container. /// - internal class ContainerCodeDomSerializer : CodeDomSerializer + internal class ContainerCodeDomSerializer : CodeDomSerializer { private const string _containerName = "components"; private static ContainerCodeDomSerializer s_defaultSerializer; - + /// /// Retrieves a default static instance of this serializer. /// - internal new static ContainerCodeDomSerializer Default + internal new static ContainerCodeDomSerializer Default { - get + get { - if (s_defaultSerializer == null) + if (s_defaultSerializer == null) { s_defaultSerializer = new ContainerCodeDomSerializer(); } @@ -40,13 +40,13 @@ internal class ContainerCodeDomSerializer : CodeDomSerializer /// /// We override this so we can always provide the correct container as a reference. /// - protected override object DeserializeInstance(IDesignerSerializationManager manager, Type type, object[] parameters, string name, bool addToContainer) + protected override object DeserializeInstance(IDesignerSerializationManager manager, Type type, object[] parameters, string name, bool addToContainer) { - if (typeof(IContainer).IsAssignableFrom(type)) + if (typeof(IContainer).IsAssignableFrom(type)) { object obj = manager.GetService(typeof(IContainer)); - if (obj != null) + if (obj != null) { Trace("Returning IContainer service as container"); manager.SetName(obj, name); @@ -62,16 +62,16 @@ protected override object DeserializeInstance(IDesignerSerializationManager mana /// Serializes the given object into a CodeDom object. We serialize an IContainer by /// declaring an IContainer member variable and then assigning a Container into it. /// - public override object Serialize(IDesignerSerializationManager manager, object value) + public override object Serialize(IDesignerSerializationManager manager, object value) { // See if there is a type declaration on the stack. If there is, create a field representing // the container member variable. CodeTypeDeclaration typeDecl = manager.Context[typeof(CodeTypeDeclaration)] as CodeTypeDeclaration; RootContext rootCxt = manager.Context[typeof(RootContext)] as RootContext; CodeStatementCollection statements = new CodeStatementCollection(); - CodeExpression lhs; - - if (typeDecl != null && rootCxt != null) + CodeExpression lhs; + + if (typeDecl != null && rootCxt != null) { CodeMemberField field = new CodeMemberField(typeof(IContainer), _containerName); @@ -79,7 +79,7 @@ public override object Serialize(IDesignerSerializationManager manager, object v typeDecl.Members.Add(field); lhs = new CodeFieldReferenceExpression(rootCxt.Expression, _containerName); } - else + else { CodeVariableDeclarationStatement var = new CodeVariableDeclarationStatement(typeof(IContainer), _containerName); @@ -95,7 +95,7 @@ public override object Serialize(IDesignerSerializationManager manager, object v assign.UserData[nameof(IContainer)] = nameof(IContainer); statements.Add(assign); - return statements; + return statements; } } } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs index 9d947ee8c61..203966b347b 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs @@ -876,8 +876,10 @@ internal ArrayList SerializationProviders void IDesignerSerializationManager.SetName(object instance, string name) { CheckSession(); - if (instance == null) throw new ArgumentNullException(nameof(instance)); - if (name == null) throw new ArgumentNullException(nameof(name)); + if (instance == null) + throw new ArgumentNullException(nameof(instance)); + if (name == null) + throw new ArgumentNullException(nameof(name)); if (instancesByName == null) { diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EnumCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EnumCodeDomSerializer.cs index 0ad047ee9ce..3ef61a29c3f 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EnumCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EnumCodeDomSerializer.cs @@ -10,56 +10,56 @@ using System.Diagnostics; using System.Reflection; -namespace System.ComponentModel.Design.Serialization +namespace System.ComponentModel.Design.Serialization { /// /// Code model serializer for enum types. /// - internal class EnumCodeDomSerializer : CodeDomSerializer + internal class EnumCodeDomSerializer : CodeDomSerializer { private static EnumCodeDomSerializer s_defaultSerializer; - + /// /// Retrieves a default static instance of this serializer. /// - internal new static EnumCodeDomSerializer Default + internal new static EnumCodeDomSerializer Default { - get + get { - if (s_defaultSerializer == null) + if (s_defaultSerializer == null) { s_defaultSerializer = new EnumCodeDomSerializer(); } return s_defaultSerializer; } } - + /// /// Serializes the given object into a CodeDom object. /// - public override object Serialize(IDesignerSerializationManager manager, object value) + public override object Serialize(IDesignerSerializationManager manager, object value) { CodeExpression expression = null; - using (TraceScope("EnumCodeDomSerializer::" + nameof(Serialize))) + using (TraceScope("EnumCodeDomSerializer::" + nameof(Serialize))) { - Trace("Type: {0}", (value == null ? "(null)" : value.GetType().Name)); - if (value is Enum) + Trace("Type: {0}", (value == null ? "(null)" : value.GetType().Name)); + if (value is Enum) { bool needCast = false; Enum[] values; TypeConverter converter = TypeDescriptor.GetConverter(value); - if (converter != null && converter.CanConvertTo(typeof(Enum[]))) + if (converter != null && converter.CanConvertTo(typeof(Enum[]))) { values = (Enum[])converter.ConvertTo(value, typeof(Enum[])); needCast = (values.Length > 1); } - else + else { - values = new Enum[] {(Enum)value}; + values = new Enum[] { (Enum)value }; needCast = true; } - + // EnumConverter (and anything that is overridden to support enums) // should be providing us a conversion to Enum[] for flag styles. // If it doesn't, we will emit a warning and just do a cast from the enum value. @@ -77,18 +77,18 @@ public override object Serialize(IDesignerSerializationManager manager, object v // representation for its values. Hardcoding is okay in this case, since all we want is // the enum's field name. Simply doing ToString() will not give us any validation. TypeConverter enumConverter = new EnumConverter(value.GetType()); - foreach (Enum term in values) + foreach (Enum term in values) { string termString = (enumConverter != null) ? enumConverter.ConvertToString(term) : null; CodeExpression newExpression = !String.IsNullOrEmpty(termString) ? new CodeFieldReferenceExpression(enumType, termString) : null; - if (newExpression != null) + if (newExpression != null) { - if (expression == null) + if (expression == null) { expression = newExpression; } - else + else { expression = new CodeBinaryOperatorExpression(expression, CodeBinaryOperatorType.BitwiseOr, newExpression); } @@ -97,12 +97,12 @@ public override object Serialize(IDesignerSerializationManager manager, object v // If we had to combine multiple names, wrap the result in an appropriate cast. // - if (expression != null && needCast) + if (expression != null && needCast) { expression = new CodeCastExpression(value.GetType(), expression); } } - else + else { Debug.Fail("Enum serializer called for non-enum object."); TraceError("Enum serializer called for non-enum object {0}", (value == null ? "(null)" : value.GetType().Name)); diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EventMemberCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EventMemberCodeDomSerializer.cs index 7f2a3cd1f00..4a4abb9bfaa 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EventMemberCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EventMemberCodeDomSerializer.cs @@ -8,23 +8,23 @@ using System.Diagnostics; using System.Reflection; -namespace System.ComponentModel.Design.Serialization +namespace System.ComponentModel.Design.Serialization { /// /// A MemberCodeDomSerializer for events. /// - internal sealed class EventMemberCodeDomSerializer : MemberCodeDomSerializer + internal sealed class EventMemberCodeDomSerializer : MemberCodeDomSerializer { private static CodeThisReferenceExpression _thisRef = new CodeThisReferenceExpression(); private static EventMemberCodeDomSerializer s_default; - internal static EventMemberCodeDomSerializer Default + internal static EventMemberCodeDomSerializer Default { - get + get { if (s_default == null) { - s_default = new EventMemberCodeDomSerializer(); + s_default = new EventMemberCodeDomSerializer(); } return s_default; @@ -36,66 +36,66 @@ internal static EventMemberCodeDomSerializer Default /// the necessary statements will be added to the statements collection. /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2102:CatchNonClsCompliantExceptionsInGeneralHandlers")] - public override void Serialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements) + public override void Serialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements) { EventDescriptor eventToSerialize = descriptor as EventDescriptor; - if (manager == null) + if (manager == null) { throw new ArgumentNullException(nameof(manager)); } - if (value == null) + if (value == null) { throw new ArgumentNullException(nameof(value)); } - if (eventToSerialize == null) + if (eventToSerialize == null) { throw new ArgumentNullException(nameof(descriptor)); } - if (statements == null) + if (statements == null) { throw new ArgumentNullException(nameof(statements)); } - try + try { IEventBindingService eventBindings = (IEventBindingService)manager.GetService(typeof(IEventBindingService)); // If the IEventBindingService is not available, we don't throw - we just don't do anything. - if (eventBindings != null) + if (eventBindings != null) { PropertyDescriptor prop = eventBindings.GetEventProperty(eventToSerialize); string methodName = (string)prop.GetValue(value); - - if (methodName != null) + + if (methodName != null) { CodeDomSerializer.Trace("Event {0} bound to {1}", eventToSerialize.Name, methodName); CodeExpression eventTarget = SerializeToExpression(manager, value); CodeDomSerializer.TraceWarningIf(eventTarget == null, "Object has no name and no propery ref in context so we cannot serialize events: {0}", value); - if (eventTarget != null) + if (eventTarget != null) { CodeTypeReference delegateTypeRef = new CodeTypeReference(eventToSerialize.EventType); CodeDelegateCreateExpression delegateCreate = new CodeDelegateCreateExpression(delegateTypeRef, _thisRef, methodName); CodeEventReferenceExpression eventRef = new CodeEventReferenceExpression(eventTarget, eventToSerialize.Name); CodeAttachEventStatement attach = new CodeAttachEventStatement(eventRef, delegateCreate); - + attach.UserData[typeof(Delegate)] = eventToSerialize.EventType; statements.Add(attach); } } } } - catch (Exception e) + catch (Exception e) { // Since we usually go through reflection, don't // show what our engine does, show what caused // the problem. // - if (e is TargetInvocationException) + if (e is TargetInvocationException) { e = e.InnerException; } - + manager.ReportError(new CodeDomSerializerException(string.Format(SR.SerializerPropertyGenFailed, eventToSerialize.Name, e.Message), manager)); } } @@ -105,5 +105,5 @@ public override void Serialize(IDesignerSerializationManager manager, object val /// or false if there is no need to serialize the member. /// public override bool ShouldSerialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor) => true; - } + } } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PrimitiveCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PrimitiveCodeDomSerializer.cs index 7be8a164c3e..b5e6923a434 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PrimitiveCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PrimitiveCodeDomSerializer.cs @@ -11,53 +11,53 @@ using System.Diagnostics; using System.Reflection; -namespace System.ComponentModel.Design.Serialization +namespace System.ComponentModel.Design.Serialization { /// /// Code model serializer for primitive types. /// - internal class PrimitiveCodeDomSerializer : CodeDomSerializer + internal class PrimitiveCodeDomSerializer : CodeDomSerializer { private static PrimitiveCodeDomSerializer s_defaultSerializer; - + /// /// Retrieves a default static instance of this serializer. /// - internal new static PrimitiveCodeDomSerializer Default + internal new static PrimitiveCodeDomSerializer Default { - get + get { - if (s_defaultSerializer == null) + if (s_defaultSerializer == null) { s_defaultSerializer = new PrimitiveCodeDomSerializer(); } return s_defaultSerializer; } } - + /// /// Serializes the given object into a CodeDom object. /// - public override object Serialize(IDesignerSerializationManager manager, object value) + public override object Serialize(IDesignerSerializationManager manager, object value) { - using (TraceScope("PrimitiveCodeDomSerializer::" + nameof(Serialize))) + using (TraceScope("PrimitiveCodeDomSerializer::" + nameof(Serialize))) { - Trace("Value: {0}", (value == null ? "(null)" : value.ToString())); + Trace("Value: {0}", (value == null ? "(null)" : value.ToString())); } CodeExpression expression = new CodePrimitiveExpression(value); - if (value != null) + if (value != null) { - if (value is string) + if (value is string) { string stringValue = value as string; - if (stringValue != null && stringValue.Length > 200) + if (stringValue != null && stringValue.Length > 200) { expression = SerializeToResourceExpression(manager, stringValue); } } - else + else { // Generate a cast for all other types because we won't parse them properly otherwise // because we won't know to convert them to the narrow form. diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PropertyMemberCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PropertyMemberCodeDomSerializer.cs index e7e3862c951..33d86f58fc4 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PropertyMemberCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PropertyMemberCodeDomSerializer.cs @@ -8,20 +8,20 @@ using System.Diagnostics; using System.Reflection; -namespace System.ComponentModel.Design.Serialization +namespace System.ComponentModel.Design.Serialization { /// /// A MemberCodeDomSerializer for properties. /// - internal sealed class PropertyMemberCodeDomSerializer : MemberCodeDomSerializer + internal sealed class PropertyMemberCodeDomSerializer : MemberCodeDomSerializer { private static PropertyMemberCodeDomSerializer s_default; - internal static PropertyMemberCodeDomSerializer Default + internal static PropertyMemberCodeDomSerializer Default { - get + get { - if (s_default == null) + if (s_default == null) { s_default = new PropertyMemberCodeDomSerializer(); } @@ -36,7 +36,7 @@ internal static PropertyMemberCodeDomSerializer Default /// This will look for an AmbientValueAttribute and use it if it can. /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2102:CatchNonClsCompliantExceptionsInGeneralHandlers")] - private object GetPropertyValue(IDesignerSerializationManager manager, PropertyDescriptor property, object value, out bool validValue) + private object GetPropertyValue(IDesignerSerializationManager manager, PropertyDescriptor property, object value, out bool validValue) { object propertyValue = null; validValue = true; @@ -50,7 +50,7 @@ private object GetPropertyValue(IDesignerSerializationManager manager, PropertyD AmbientValueAttribute attr = (AmbientValueAttribute)property.Attributes[typeof(AmbientValueAttribute)]; if (attr != null) - { + { return attr.Value; } else @@ -58,25 +58,25 @@ private object GetPropertyValue(IDesignerSerializationManager manager, PropertyD DefaultValueAttribute defAttr = (DefaultValueAttribute)property.Attributes[typeof(DefaultValueAttribute)]; if (defAttr != null) - { + { return defAttr.Value; } else { // nope, we're not valid... // - validValue = false; + validValue = false; } } } - propertyValue = property.GetValue(value); + propertyValue = property.GetValue(value); } catch (Exception e) { // something failed -- we don't have a valid value - validValue = false; + validValue = false; - manager.ReportError(new CodeDomSerializerException(string.Format(SR.SerializerPropertyGenFailed, property.Name, e.Message), manager)); + manager.ReportError(new CodeDomSerializerException(string.Format(SR.SerializerPropertyGenFailed, property.Name, e.Message), manager)); } if ((propertyValue != null) && (!propertyValue.GetType().IsValueType) && !(propertyValue is Type)) @@ -98,71 +98,71 @@ private object GetPropertyValue(IDesignerSerializationManager manager, PropertyD return propertyValue; } - + /// /// This method actually performs the serialization. When the member is serialized /// the necessary statements will be added to the statements collection. /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2102:CatchNonClsCompliantExceptionsInGeneralHandlers")] - public override void Serialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements) + public override void Serialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements) { PropertyDescriptor propertyToSerialize = descriptor as PropertyDescriptor; - if (manager == null) - { + if (manager == null) + { throw new ArgumentNullException(nameof(manager)); } - if (value == null) - { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } - if (propertyToSerialize == null) - { + if (propertyToSerialize == null) + { throw new ArgumentNullException(nameof(descriptor)); } - if (statements == null) - { + if (statements == null) + { throw new ArgumentNullException(nameof(statements)); } - - try + + try { ExtenderProvidedPropertyAttribute exAttr = (ExtenderProvidedPropertyAttribute)propertyToSerialize.Attributes[typeof(ExtenderProvidedPropertyAttribute)]; bool isExtender = (exAttr != null && exAttr.Provider != null); bool serializeContents = propertyToSerialize.Attributes.Contains(DesignerSerializationVisibilityAttribute.Content); CodeDomSerializer.Trace("Serializing property {0}", propertyToSerialize.Name); - if (serializeContents) + if (serializeContents) { SerializeContentProperty(manager, value, propertyToSerialize, isExtender, statements); } - else if (isExtender) + else if (isExtender) { SerializeExtenderProperty(manager, value, propertyToSerialize, statements); } - else + else { SerializeNormalProperty(manager, value, propertyToSerialize, statements); } } - catch (Exception e) + catch (Exception e) { // Since we usually go through reflection, don't // show what our engine does, show what caused // the problem. - if (e is TargetInvocationException) + if (e is TargetInvocationException) { e = e.InnerException; } - - manager.ReportError(new CodeDomSerializerException(string.Format(SR.SerializerPropertyGenFailed, propertyToSerialize.Name, e.Message), manager)); + + manager.ReportError(new CodeDomSerializerException(string.Format(SR.SerializerPropertyGenFailed, propertyToSerialize.Name, e.Message), manager)); } } /// /// This serializes the given property on this object as a content property. /// - private void SerializeContentProperty(IDesignerSerializationManager manager, object value, PropertyDescriptor property, bool isExtender, CodeStatementCollection statements) + private void SerializeContentProperty(IDesignerSerializationManager manager, object value, PropertyDescriptor property, bool isExtender, CodeStatementCollection statements) { CodeDomSerializer.Trace("Property is marked as Visibility.Content. Recursing."); @@ -174,38 +174,38 @@ private void SerializeContentProperty(IDesignerSerializationManager manager, obj // CodeDomSerializer serializer = null; - if (propertyValue == null) + if (propertyValue == null) { CodeDomSerializer.TraceError("Property {0} is marked as Visibility.Content but it is returning null.", property.Name); string name = manager.GetName(value); - if (name == null) + if (name == null) { name = value.GetType().FullName; } manager.ReportError(new CodeDomSerializerException(string.Format(SR.SerializerNullNestedProperty, name, property.Name), manager)); } - else + else { serializer = (CodeDomSerializer)manager.GetSerializer(propertyValue.GetType(), typeof(CodeDomSerializer)); - if (serializer != null) + if (serializer != null) { // Create a property reference expression and push it on the context stack. // This allows the serializer to gain some context as to what it should be // serializing. CodeExpression target = SerializeToExpression(manager, value); - if (target == null) + if (target == null) { CodeDomSerializer.TraceWarning("Unable to convert value to expression object"); } - else + else { CodeExpression propertyRef = null; - if (isExtender) + if (isExtender) { CodeDomSerializer.Trace("Content property is an extender."); ExtenderProvidedPropertyAttribute exAttr = (ExtenderProvidedPropertyAttribute)property.Attributes[typeof(ExtenderProvidedPropertyAttribute)]; @@ -217,7 +217,7 @@ private void SerializeContentProperty(IDesignerSerializationManager manager, obj CodeDomSerializer.TraceWarningIf(extender == null, "Extender object {0} could not be serialized.", manager.GetName(exAttr.Provider)); CodeDomSerializer.TraceWarningIf(extended == null, "Extended object {0} could not be serialized.", manager.GetName(value)); - if (extender != null && extended != null) + if (extender != null && extended != null) { CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression(extender, "Get" + property.Name); CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression(); @@ -226,32 +226,32 @@ private void SerializeContentProperty(IDesignerSerializationManager manager, obj propertyRef = methodInvoke; } } - else + else { propertyRef = new CodePropertyReferenceExpression(target, property.Name); } - if (propertyRef != null) + if (propertyRef != null) { ExpressionContext tree = new ExpressionContext(propertyRef, property.PropertyType, value, propertyValue); manager.Context.Push(tree); object result = null; - try + try { SerializeAbsoluteContext absolute = (SerializeAbsoluteContext)manager.Context[typeof(SerializeAbsoluteContext)]; - - if (IsSerialized(manager, propertyValue, absolute != null)) + + if (IsSerialized(manager, propertyValue, absolute != null)) { result = GetExpression(manager, propertyValue); } - else + else { result = serializer.Serialize(manager, propertyValue); } } - finally + finally { Debug.Assert(manager.Context.Current == tree, "Serializer added a context it didn't remove."); manager.Context.Pop(); @@ -259,18 +259,18 @@ private void SerializeContentProperty(IDesignerSerializationManager manager, obj CodeStatementCollection csc = result as CodeStatementCollection; - if (csc != null) + if (csc != null) { - foreach (CodeStatement statement in csc) + foreach (CodeStatement statement in csc) { statements.Add(statement); } } - else + else { CodeStatement cs = result as CodeStatement; - if (cs != null) + if (cs != null) { statements.Add(cs); } @@ -278,7 +278,7 @@ private void SerializeContentProperty(IDesignerSerializationManager manager, obj } } } - else + else { CodeDomSerializer.TraceError("Property {0} is marked as Visibilty.Content but there is no serializer for it.", property.Name); @@ -290,11 +290,11 @@ private void SerializeContentProperty(IDesignerSerializationManager manager, obj /// /// This serializes the given property on this object. /// - private void SerializeExtenderProperty(IDesignerSerializationManager manager, object value, PropertyDescriptor property, CodeStatementCollection statements) + private void SerializeExtenderProperty(IDesignerSerializationManager manager, object value, PropertyDescriptor property, CodeStatementCollection statements) { AttributeCollection attributes = property.Attributes; - using (CodeDomSerializer.TraceScope("PropertyMemberCodeDomSerializer::" + nameof(SerializeExtenderProperty))) + using (CodeDomSerializer.TraceScope("PropertyMemberCodeDomSerializer::" + nameof(SerializeExtenderProperty))) { ExtenderProvidedPropertyAttribute exAttr = (ExtenderProvidedPropertyAttribute)attributes[typeof(ExtenderProvidedPropertyAttribute)]; @@ -305,7 +305,7 @@ private void SerializeExtenderProperty(IDesignerSerializationManager manager, ob CodeDomSerializer.TraceWarningIf(extender == null, "Extender object {0} could not be serialized.", manager.GetName(exAttr.Provider)); CodeDomSerializer.TraceWarningIf(extended == null, "Extended object {0} could not be serialized.", manager.GetName(value)); - if (extender != null && extended != null) + if (extender != null && extended != null) { CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression(extender, "Set" + property.Name); bool validValue; @@ -314,11 +314,12 @@ private void SerializeExtenderProperty(IDesignerSerializationManager manager, ob // Serialize the value of this property into a code expression. If we can't get one, // then we won't serialize the property. - if (validValue) + if (validValue) { ExpressionContext tree = null; - if (propValue != value) { + if (propValue != value) + { // make sure the value isn't the object or we'll end up printing // this property instead of the value. tree = new ExpressionContext(methodRef, property.PropertyType, value); @@ -329,9 +330,9 @@ private void SerializeExtenderProperty(IDesignerSerializationManager manager, ob { serializedPropertyValue = SerializeToExpression(manager, propValue); } - finally + finally { - if (tree != null) + if (tree != null) { Debug.Assert(manager.Context.Current == tree, "Context stack corrupted."); manager.Context.Pop(); @@ -339,7 +340,7 @@ private void SerializeExtenderProperty(IDesignerSerializationManager manager, ob } } - if (serializedPropertyValue != null) + if (serializedPropertyValue != null) { CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression(); @@ -355,15 +356,15 @@ private void SerializeExtenderProperty(IDesignerSerializationManager manager, ob /// /// This serializes the given property on this object. /// - private void SerializeNormalProperty(IDesignerSerializationManager manager, object value, PropertyDescriptor property, CodeStatementCollection statements) + private void SerializeNormalProperty(IDesignerSerializationManager manager, object value, PropertyDescriptor property, CodeStatementCollection statements) { - using (CodeDomSerializer.TraceScope("CodeDomSerializer::" + nameof(SerializeProperty))) + using (CodeDomSerializer.TraceScope("CodeDomSerializer::" + nameof(SerializeProperty))) { CodeExpression target = SerializeToExpression(manager, value); CodeDomSerializer.TraceWarningIf(target == null, "Unable to serialize target for property {0}", property.Name); - if (target != null) + if (target != null) { CodeExpression propertyRef = new CodePropertyReferenceExpression(target, property.Name); @@ -375,34 +376,34 @@ private void SerializeNormalProperty(IDesignerSerializationManager manager, obje // it isn't, then we're serialize ourselves. MemberRelationshipService relationships = manager.GetService(typeof(MemberRelationshipService)) as MemberRelationshipService; - if (relationships != null) + if (relationships != null) { MemberRelationship relationship = relationships[value, property]; - if (relationship != MemberRelationship.Empty) + if (relationship != MemberRelationship.Empty) { CodeExpression rhsTarget = SerializeToExpression(manager, relationship.Owner); - if (rhsTarget != null) + if (rhsTarget != null) { serializedPropertyValue = new CodePropertyReferenceExpression(rhsTarget, relationship.Member.Name); } } } - if (serializedPropertyValue == null) + if (serializedPropertyValue == null) { // Serialize the value of this property into a code expression. If we can't get one, // then we won't serialize the property. // bool validValue; object propValue = GetPropertyValue(manager, property, value, out validValue); - - if (validValue) + + if (validValue) { ExpressionContext tree = null; - if (propValue != value) + if (propValue != value) { // make sure the value isn't the object or we'll end up printing // this property instead of the value. @@ -410,13 +411,13 @@ private void SerializeNormalProperty(IDesignerSerializationManager manager, obje manager.Context.Push(tree); } - try + try { serializedPropertyValue = SerializeToExpression(manager, propValue); } - finally + finally { - if (tree != null) + if (tree != null) { Debug.Assert(manager.Context.Current == tree, "Context stack corrupted."); manager.Context.Pop(); @@ -425,7 +426,7 @@ private void SerializeNormalProperty(IDesignerSerializationManager manager, obje } } - if (serializedPropertyValue != null) + if (serializedPropertyValue != null) { CodeAssignStatement assign = new CodeAssignStatement(propertyRef, serializedPropertyValue); statements.Add(assign); @@ -443,34 +444,34 @@ public override bool ShouldSerialize(IDesignerSerializationManager manager, obje PropertyDescriptor propertyToSerialize = descriptor as PropertyDescriptor; - if (manager == null) + if (manager == null) { throw new ArgumentNullException(nameof(manager)); } - if (value == null) + if (value == null) { throw new ArgumentNullException(nameof(value)); } - if (propertyToSerialize == null) + if (propertyToSerialize == null) { throw new ArgumentNullException(nameof(descriptor)); } bool shouldSerializeProperty = propertyToSerialize.ShouldSerializeValue(value); - - if (!shouldSerializeProperty) + + if (!shouldSerializeProperty) { SerializeAbsoluteContext absolute = (SerializeAbsoluteContext)manager.Context[typeof(SerializeAbsoluteContext)]; - if (absolute != null && absolute.ShouldSerialize(propertyToSerialize)) - { - + if (absolute != null && absolute.ShouldSerialize(propertyToSerialize)) + { + // For ReadOnly properties, we only want to override the value returned from // ShouldSerializeValue() if the property is marked with DesignerSerializationVisibilityAttribute(Content). // Consider the case of a property with just a getter - we only want to serialize those // if they're marked in this way (see ReflectPropertyDescriptor::ShouldSerializeValue()) - if (!propertyToSerialize.Attributes.Contains(DesignerSerializationVisibilityAttribute.Content)) - { + if (!propertyToSerialize.Attributes.Contains(DesignerSerializationVisibilityAttribute.Content)) + { shouldSerializeProperty = false; // it's already false at this point, but this is clearer. } else @@ -480,10 +481,10 @@ public override bool ShouldSerialize(IDesignerSerializationManager manager, obje } } - if (shouldSerializeProperty) + if (shouldSerializeProperty) { bool isDesignTime = propertyToSerialize.Attributes.Contains(DesignOnlyAttribute.Yes); - if (!isDesignTime) + if (!isDesignTime) { return true; } @@ -494,11 +495,11 @@ public override bool ShouldSerialize(IDesignerSerializationManager manager, obje MemberRelationshipService relationships = manager.GetService(typeof(MemberRelationshipService)) as MemberRelationshipService; - if (relationships != null) + if (relationships != null) { MemberRelationship relationship = relationships[value, descriptor]; - if (relationship != MemberRelationship.Empty) + if (relationship != MemberRelationship.Empty) { return true; } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ResourceCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ResourceCodeDomSerializer.cs index f3b0e53ccb3..f337c49b96c 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ResourceCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ResourceCodeDomSerializer.cs @@ -154,11 +154,11 @@ private SerializationResourceManager CreateResourceManager(IDesignerSerializatio /// protected override object DeserializeInstance(IDesignerSerializationManager manager, Type type, object[] parameters, string name, bool addToContainer) { - if (manager == null) + if (manager == null) { throw new ArgumentNullException(nameof(manager)); } - if (type == null) + if (type == null) { throw new ArgumentNullException(nameof(type)); } @@ -683,7 +683,8 @@ private CompareValue CompareWithParentValue(string name, object value) { Debug.Assert(name != null, "name is null"); // If there is no parent culture, treat that as being different from the parent's resource, which results in the "normal" code path for the caller. - if (ReadCulture.Equals(CultureInfo.InvariantCulture)) return CompareValue.Different; + if (ReadCulture.Equals(CultureInfo.InvariantCulture)) + return CompareValue.Different; CultureInfo culture = ReadCulture; for (; ; ) @@ -750,7 +751,7 @@ private Hashtable CreateResourceSet(IResourceReader reader, CultureInfo culture) if (culture == CultureInfo.InvariantCulture) { se = new SerializationException( - + string.Format(SR.SerializerResourceExceptionInvariant, message), e); } else diff --git a/src/System.Windows.Forms.Design/src/System/Drawing/Design/ToolboxComponentsCreatingEventArgs.cs b/src/System.Windows.Forms.Design/src/System/Drawing/Design/ToolboxComponentsCreatingEventArgs.cs index a104a81ec72..85fad735070 100644 --- a/src/System.Windows.Forms.Design/src/System/Drawing/Design/ToolboxComponentsCreatingEventArgs.cs +++ b/src/System.Windows.Forms.Design/src/System/Drawing/Design/ToolboxComponentsCreatingEventArgs.cs @@ -19,7 +19,7 @@ public ToolboxComponentsCreatingEventArgs(IDesignerHost host) { DesignerHost = host; } - + /// /// An instance of IDesignerHost that has made the creat request. /// This can be null if no designer host was provided to the toolbox item. diff --git a/src/System.Windows.Forms.Design/src/System/Drawing/Design/ToolboxItem.cs b/src/System.Windows.Forms.Design/src/System/Drawing/Design/ToolboxItem.cs index 34b6a07cb11..fca4a756d22 100644 --- a/src/System.Windows.Forms.Design/src/System/Drawing/Design/ToolboxItem.cs +++ b/src/System.Windows.Forms.Design/src/System/Drawing/Design/ToolboxItem.cs @@ -39,7 +39,8 @@ public class ToolboxItem : ISerializable /// /// Initializes a new instance of the ToolboxItem class. /// - public ToolboxItem() { + public ToolboxItem() + { if (!s_isScalingInitialized) { if (DpiHelper.IsScalingRequired) diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/BaseContextMenuStrip.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/BaseContextMenuStrip.cs index a424dc3444b..155791cb761 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/BaseContextMenuStrip.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/BaseContextMenuStrip.cs @@ -204,7 +204,7 @@ private void InitializeContextMenu() ForeColor = (Color)uis.Styles["VsColorPanelText"]; } } - GroupOrdering.AddRange(new string[] { StandardGroups.Code, StandardGroups.ZORder, StandardGroups.Grid, StandardGroups.Lock, StandardGroups.Verbs, StandardGroups.Custom, StandardGroups.Selection, StandardGroups.Edit, StandardGroups.Properties}); + GroupOrdering.AddRange(new string[] { StandardGroups.Code, StandardGroups.ZORder, StandardGroups.Grid, StandardGroups.Lock, StandardGroups.Verbs, StandardGroups.Custom, StandardGroups.Selection, StandardGroups.Edit, StandardGroups.Properties }); // ADD MENUITEMS AddCodeMenuItem(); AddZorderMenuItem(); diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs index 02491ca6702..c1ee0dcfe3f 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs @@ -1307,23 +1307,23 @@ private class MenuCommandHandler : IMenuCommandService private readonly BehaviorService _owner; // ptr back to the behavior service private readonly IMenuCommandService _menuService; // core service used for most implementations of the IMCS interface private readonly Stack _currentCommands = new Stack(); - + public MenuCommandHandler(BehaviorService owner, IMenuCommandService menuService) { _owner = owner; _menuService = menuService; } - + public IMenuCommandService MenuService { get => _menuService; } - + void IMenuCommandService.AddCommand(MenuCommand command) { _menuService.AddCommand(command); } - + void IMenuCommandService.RemoveVerb(DesignerVerb verb) { _menuService.RemoveVerb(verb); @@ -1333,7 +1333,7 @@ void IMenuCommandService.RemoveCommand(MenuCommand command) { _menuService.RemoveCommand(command); } - + MenuCommand IMenuCommandService.FindCommand(CommandID commandID) { try @@ -1355,17 +1355,17 @@ bool IMenuCommandService.GlobalInvoke(CommandID commandID) { return _menuService.GlobalInvoke(commandID); } - + void IMenuCommandService.ShowContextMenu(CommandID menuID, int x, int y) { _menuService.ShowContextMenu(menuID, x, y); } - + void IMenuCommandService.AddVerb(DesignerVerb verb) { _menuService.AddVerb(verb); } - + DesignerVerbCollection IMenuCommandService.Verbs { get => _menuService.Verbs; @@ -1406,15 +1406,18 @@ private MenuCommand FindCommand(CommandID commandID, IMenuCommandService menuSer return menuService.FindCommand(commandID); } - private Behavior GetAppropriateBehavior(Glyph g) { - if (_behaviorStack != null && _behaviorStack.Count > 0) { + private Behavior GetAppropriateBehavior(Glyph g) + { + if (_behaviorStack != null && _behaviorStack.Count > 0) + { return _behaviorStack[0] as Behavior; } - - if (g != null && g.Behavior != null) { + + if (g != null && g.Behavior != null) + { return g.Behavior; } - + return null; } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/ContainerSelectorGlyph.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/ContainerSelectorGlyph.cs index 7012cc0b1e0..3af330e5285 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/ContainerSelectorGlyph.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/ContainerSelectorGlyph.cs @@ -22,7 +22,7 @@ internal ContainerSelectorGlyph(Rectangle containerBounds, int glyphSize, int gl _relatedBehavior = (ContainerSelectorBehavior)behavior; _glyphBounds = new Rectangle(containerBounds.X + glyphOffset, containerBounds.Y - (int)(glyphSize * .5), glyphSize, glyphSize); } - + /// /// The bounds of this Glyph. /// @@ -35,7 +35,7 @@ public Behavior RelatedBehavior { get => _relatedBehavior; } - + /// /// Simple hit test rule: if the point is contained within the bounds - then it is a positive hit test. /// diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/DesignerActionKeyboardBehavior.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/DesignerActionKeyboardBehavior.cs index 21ff6c6082e..6ef0ff6a88c 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/DesignerActionKeyboardBehavior.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/DesignerActionKeyboardBehavior.cs @@ -36,7 +36,8 @@ public override MenuCommand FindCommand(CommandID commandId) // VisualStudio shell implements a mutable derived class from the base CommandID. The mutable class compares overridden properties instead of the read-only backing fields when testing equality of command IDs. Thus Equals method is asymmetrical derived class's override that compares properties is the accurate one. if (commandId.Equals(candidateCommandId)) { - MenuCommand dummyMC = new MenuCommand(delegate { }, commandId) + MenuCommand dummyMC = new MenuCommand(delegate + { }, commandId) { Enabled = false }; diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/DropSourceBehavior.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/DropSourceBehavior.cs index 7ccc19a5d71..587fbf7272d 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/DropSourceBehavior.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/DropSourceBehavior.cs @@ -260,7 +260,7 @@ private void DropControl(int dragComponentIndex, Control dragTarget, Control dra { //between containers dragSource.Controls.Remove(currentControl); - currentControl.Visible = true; + currentControl.Visible = true; dragTarget.Controls.Add(currentControl); } } @@ -798,7 +798,7 @@ internal void GiveFeedback(object sender, GiveFeedbackEventArgs e) { invalidDragRegion.Translate(mouseLoc.X - initialMouseLoc.X + lastSnapOffset.X, mouseLoc.Y - initialMouseLoc.Y + lastSnapOffset.Y); invalidDragRegion.Complement(newImageRect); - invalidDragRegion.Union(invalidRegion); + invalidDragRegion.Union(invalidRegion); behaviorServiceTarget.Invalidate(invalidDragRegion); } invalidRegion.Dispose(); diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/GlyphCollection.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/GlyphCollection.cs index 88c128866fd..1ffc4cb792c 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/GlyphCollection.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/GlyphCollection.cs @@ -57,7 +57,8 @@ public int Add(Glyph value) /// public void AddRange(Glyph[] value) { - for (int i = 0; i < value.Length; i = i + 1) Add(value[i]); + for (int i = 0; i < value.Length; i = i + 1) + Add(value[i]); } /// @@ -65,7 +66,8 @@ public void AddRange(Glyph[] value) /// public void AddRange(GlyphCollection value) { - for (int i = 0; i < value.Count; i = i + 1) Add(value[i]); + for (int i = 0; i < value.Count; i = i + 1) + Add(value[i]); } /// diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/SelectionGlyphBase.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/SelectionGlyphBase.cs index 766efd2c361..261a3875de4 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/SelectionGlyphBase.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/SelectionGlyphBase.cs @@ -15,14 +15,14 @@ internal abstract class SelectionGlyphBase : Glyph protected Rectangle hitBounds; // defines the bounds used for hittest - it could be different than the bounds of the glyph itself protected Cursor hitTestCursor; // the cursor returned if hit test is positive protected SelectionRules rules; // the selection rules - defining how the control can change - + /// /// Standard constructor. /// internal SelectionGlyphBase(Behavior behavior) : base(behavior) { } - + /// /// Read-only property describing the SelecitonRules for these Glyphs. /// @@ -30,7 +30,7 @@ public SelectionRules SelectionRules { get => rules; } - + /// /// Simple hit test rule: if the point is contained within the bounds - then it is a positive hit test. /// @@ -58,7 +58,7 @@ public override Rectangle Bounds { get => bounds; } - + /// /// There's no paint logic on this base class. /// diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentTray.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentTray.cs index a2612b3bed4..1630f596d81 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentTray.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentTray.cs @@ -627,7 +627,7 @@ void ISelectionUIHandler.OnSelectionDoubleClick(IComponent component) } bool ISelectionUIHandler.QueryBeginDrag(object[] components, SelectionRules rules, int initialX, int initialY) => DragHandler.QueryBeginDrag(components, rules, initialX, initialY); - + void ISelectionUIHandler.ShowContextMenu(IComponent component) { Point cur = Control.MousePosition; @@ -658,7 +658,7 @@ private void OnContextMenu(int x, int y, bool useSelection) } void ISelectionUIHandler.OleDragEnter(DragEventArgs de) => GetOleDragHandler().DoOleDragEnter(de); - + void ISelectionUIHandler.OleDragDrop(DragEventArgs de) => GetOleDragHandler().DoOleDragDrop(de); void ISelectionUIHandler.OleDragOver(DragEventArgs de) => GetOleDragHandler().DoOleDragOver(de); @@ -749,7 +749,7 @@ protected virtual bool CanCreateComponentFromTool(ToolboxItem tool) return true; } Type designerType = GetDesignerType(compType, typeof(IDesigner)); - return ! (typeof(ControlDesigner).IsAssignableFrom(designerType)); + return !(typeof(ControlDesigner).IsAssignableFrom(designerType)); } private Type GetDesignerType(Type t, Type designerBaseType) diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlDesigner.cs index eb074f38e7e..07e27f6b799 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlDesigner.cs @@ -1628,7 +1628,7 @@ protected override void PreFilterProperties(IDictionary properties) } // Now we add our own design time properties. - properties["Locked"] = TypeDescriptor .CreateProperty(typeof(ControlDesigner), "Locked", typeof(bool), new DefaultValueAttribute(false), BrowsableAttribute.Yes, CategoryAttribute.Design, DesignOnlyAttribute.Yes, new SRDescriptionAttribute(SR.lockedDescr)); + properties["Locked"] = TypeDescriptor.CreateProperty(typeof(ControlDesigner), "Locked", typeof(bool), new DefaultValueAttribute(false), BrowsableAttribute.Yes, CategoryAttribute.Design, DesignOnlyAttribute.Yes, new SRDescriptionAttribute(SR.lockedDescr)); } /// @@ -2519,7 +2519,7 @@ public override AccessibleObject GetChild(int index) } public override int GetChildCount() => _control.AccessibilityObject.GetChildCount(); - + private AccessibleObject GetDesignerAccessibleObject(Control.ControlAccessibleObject cao) { if (cao == null) diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerActionService.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerActionService.cs index 29fb3c67dc8..29699576135 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerActionService.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerActionService.cs @@ -86,7 +86,7 @@ public void Add(IComponent comp, DesignerActionListCollection designerActionList /// public void Add(IComponent comp, DesignerActionList actionList) { - Add(comp, new DesignerActionListCollection( new[] { actionList } )); + Add(comp, new DesignerActionListCollection(new[] { actionList })); } /// diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerActionUI.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerActionUI.cs index e76bd09c5f5..ba09fa2cb54 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerActionUI.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerActionUI.cs @@ -315,7 +315,7 @@ private void RecreateInternal(IComponent comp) DesignerActionGlyph glyph = GetDesignerActionGlyph(comp); if (glyph != null) { - VerifyGlyphIsInAdorner(glyph); + VerifyGlyphIsInAdorner(glyph); // this could happen when a verb change state or suddendly a control gets a new action in the panel and we are the primary selection in that case there would not be a glyph active in the adorner to be shown because we update that on selection change. We have to do that here too. Sad really... RecreatePanel(glyph); // recreate the DAP itself UpdateDAPLocation(comp, glyph); // reposition the thing @@ -706,7 +706,7 @@ internal void ShowDesignerActionPanel(IComponent relatedComponent, DesignerActio // check that the panel will have at least it's parent glyph visible on the adorner window if (_behaviorService != null && _behaviorService.AdornerWindowControl.DisplayRectangle.IntersectsWith(glyph.Bounds)) - { + { if (_mainParentWindow != null && _mainParentWindow.Handle != IntPtr.Zero) { Debug.WriteLineIf(s_designeActionPanelTraceSwitch.TraceVerbose, "Assigning owner to mainParentWindow"); @@ -951,11 +951,12 @@ private static bool WindowOwnsWindow(IntPtr hWndOwner, IntPtr hWndDescendant) { Debug.WriteLineIf(DesignerActionUI.DropDownVisibilityDebug.TraceVerbose, "[WindowOwnsWindow] Testing if " + hWndOwner.ToString("x") + " is a owned by " + hWndDescendant.ToString("x") + "... "); #if DEBUG - if (DesignerActionUI.DropDownVisibilityDebug.TraceVerbose) { + if (DesignerActionUI.DropDownVisibilityDebug.TraceVerbose) + { Debug.WriteLine("\t\tOWNER: " + GetControlInformation(hWndOwner)); Debug.WriteLine("\t\tOWNEE: " + GetControlInformation(hWndDescendant)); IntPtr claimedOwnerHwnd = UnsafeNativeMethods.GetWindowLong(new HandleRef(null, hWndDescendant), NativeMethods.GWL_HWNDPARENT); - Debug.WriteLine("OWNEE's CLAIMED OWNER: "+ GetControlInformation(claimedOwnerHwnd)); + Debug.WriteLine("OWNEE's CLAIMED OWNER: " + GetControlInformation(claimedOwnerHwnd)); } #endif if (hWndDescendant == hWndOwner) @@ -989,20 +990,24 @@ internal static string GetControlInformation(IntPtr hwnd) return "Handle is IntPtr.Zero"; } #if DEBUG - if (!DesignerActionUI.DropDownVisibilityDebug.TraceVerbose) { + if (!DesignerActionUI.DropDownVisibilityDebug.TraceVerbose) + { return string.Empty; - } + } - string windowText = Interop.User32.GetWindowText(new HandleRef(null, hwnd)); - string typeOfControl = "Unknown"; - string nameOfControl = string.Empty; - Control c = Control.FromHandle(hwnd); - if (c != null) { + string windowText = Interop.User32.GetWindowText(new HandleRef(null, hwnd)); + string typeOfControl = "Unknown"; + string nameOfControl = string.Empty; + Control c = Control.FromHandle(hwnd); + if (c != null) + { typeOfControl = c.GetType().Name; - if (!string.IsNullOrEmpty(c.Name)) { + if (!string.IsNullOrEmpty(c.Name)) + { nameOfControl += c.Name; } - else { + else + { nameOfControl += "Unknown"; // some extra debug info for toolstripdropdowns... if (c is ToolStripDropDown dd) @@ -1013,8 +1018,8 @@ internal static string GetControlInformation(IntPtr hwnd) } } } - } - return windowText + "\r\n\t\t\tType: [" + typeOfControl + "] Name: [" + nameOfControl + "]"; + } + return windowText + "\r\n\t\t\tType: [" + typeOfControl + "] Name: [" + nameOfControl + "]"; #else return string.Empty; #endif diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerFrame.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerFrame.cs index 6c02c83c783..8c711392f95 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerFrame.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerFrame.cs @@ -266,7 +266,7 @@ protected override void WndProc(ref Message m) /// Pushes the given control on top of the overlay list. This is a "push" operation, meaning that it forces this control to the top of the existing overlay list. /// int IOverlayService.PushOverlay(Control control) => _designerRegion.PushOverlay(control); - + /// /// Removes the given control from the overlay list. Unlike pushOverlay, this can remove a control from the middle of the overlay list. /// diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ImageCollectionCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ImageCollectionCodeDomSerializer.cs index 8c53ea0935d..0d20b00a6a5 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ImageCollectionCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ImageCollectionCodeDomSerializer.cs @@ -28,5 +28,5 @@ public override object Serialize(IDesignerSerializationManager manager, object v { throw new NotImplementedException(SR.NotImplementedByDesign); } - } + } } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/OleDragDropHandler.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/OleDragDropHandler.cs index 65572cf9864..5e412a7014a 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/OleDragDropHandler.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/OleDragDropHandler.cs @@ -158,7 +158,7 @@ public virtual object GetData(Type t) throw new NotImplementedException(SR.NotImplementedByDesign); } - /// + /// /// If the there is data store in the data object associated with /// format this will return true. /// @@ -167,7 +167,7 @@ public bool GetDataPresent(string format, bool autoConvert) throw new NotImplementedException(SR.NotImplementedByDesign); } - /// + /// /// If the there is data store in the data object associated with /// format this will return true. /// @@ -176,7 +176,7 @@ public bool GetDataPresent(string format) return GetDataPresent(format, false); } - /// + /// /// If the there is data store in the data object associated with /// format this will return true. /// @@ -185,7 +185,7 @@ public bool GetDataPresent(Type format) throw new NotImplementedException(SR.NotImplementedByDesign); } - /// + /// /// Retrieves a list of all formats stored in this data object. /// public string[] GetFormats(bool autoConvert) @@ -193,7 +193,7 @@ public string[] GetFormats(bool autoConvert) throw new NotImplementedException(SR.NotImplementedByDesign); } - /// + /// /// Retrieves a list of all formats stored in this data object. /// public string[] GetFormats() @@ -201,7 +201,7 @@ public string[] GetFormats() throw new NotImplementedException(SR.NotImplementedByDesign); } - /// + /// /// Sets the data to be associated with the specific data format. For /// a listing of predefined formats see System.Windows.Forms.DataFormats. /// @@ -210,7 +210,7 @@ public void SetData(string format, bool autoConvert, object data) throw new NotImplementedException(SR.NotImplementedByDesign); } - /// + /// /// Sets the data to be associated with the specific data format. For /// a listing of predefined formats see System.Windows.Forms.DataFormats. /// @@ -219,7 +219,7 @@ public void SetData(string format, object data) throw new Exception(SR.DragDropSetDataError); } - /// + /// /// Sets the data to be associated with the specific data format. /// public void SetData(Type format, object data) @@ -227,7 +227,7 @@ public void SetData(Type format, object data) throw new NotImplementedException(SR.NotImplementedByDesign); } - /// + /// /// Stores data in the data object. The format assumed is the /// class of data /// diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/SelectionUIService.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/SelectionUIService.cs index 8a8763f2eea..5571bd87281 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/SelectionUIService.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/SelectionUIService.cs @@ -886,7 +886,7 @@ bool ISelectionUIService.Visible event ContainerSelectorActiveEventHandler ISelectionUIService.ContainerSelectorActive { add => _containerSelectorActive += value; - remove => _containerSelectorActive -= value; + remove => _containerSelectorActive -= value; } /// @@ -1782,7 +1782,7 @@ public virtual bool UpdateSize() if (!_innerRect.IsEmpty) { _innerRect = _selUIsvc.RectangleToClient(_innerRect); - Rectangle rcOuterNew = new Rectangle( _innerRect.X - GRABHANDLE_WIDTH, _innerRect.Y - GRABHANDLE_HEIGHT, _innerRect.Width + 2 * GRABHANDLE_WIDTH, _innerRect.Height + 2 * GRABHANDLE_HEIGHT); + Rectangle rcOuterNew = new Rectangle(_innerRect.X - GRABHANDLE_WIDTH, _innerRect.Y - GRABHANDLE_HEIGHT, _innerRect.Width + 2 * GRABHANDLE_WIDTH, _innerRect.Height + 2 * GRABHANDLE_HEIGHT); if (_outerRect.IsEmpty || !_outerRect.Equals(rcOuterNew)) { if (!_outerRect.IsEmpty) diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/StandardMenuStripVerb.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/StandardMenuStripVerb.cs index a46ae2338f7..7e8b3caa602 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/StandardMenuStripVerb.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/StandardMenuStripVerb.cs @@ -488,7 +488,7 @@ private string NameFromText(string text, Type itemType, INameCreationService nam baseName = name.ToString(); if (adjustCapitalization) { - string nameOfRandomItem = ToolStripDesigner.NameFromText(null, typeof(ToolStripMenuItem), _designer.Component.Site); + string nameOfRandomItem = ToolStripDesigner.NameFromText(null, typeof(ToolStripMenuItem), _designer.Component.Site); if (!string.IsNullOrEmpty(nameOfRandomItem) && char.IsUpper(nameOfRandomItem[0])) { baseName = char.ToUpper(baseName[0], CultureInfo.InvariantCulture) + baseName.Substring(1); diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripAdornerWindowService.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripAdornerWindowService.cs index 741a9f5aa3b..f8b69aef48b 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripAdornerWindowService.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripAdornerWindowService.cs @@ -182,7 +182,7 @@ internal void ProcessPaintMessage(Rectangle paintRect) private class ToolStripAdornerWindow : Control { private Control _designerFrame; //the designer's frame - + [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] internal ToolStripAdornerWindow(Control designerFrame) { diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesignerUtils.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesignerUtils.cs index 87e02836415..51152ff1f05 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesignerUtils.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesignerUtils.cs @@ -38,17 +38,17 @@ private ToolStripDesignerUtils() #region NewItemTypeLists // This section controls the ordering of standard item types in all the various pieces of toolstrip designer UI. // ToolStrip - Default item is determined by being first in the list - private static readonly Type[] s_newItemTypesForToolStrip = - new Type[]{typeof(ToolStripButton), typeof(ToolStripLabel), typeof(ToolStripSplitButton), typeof(ToolStripDropDownButton), typeof(ToolStripSeparator), typeof(ToolStripComboBox), typeof(ToolStripTextBox), typeof(ToolStripProgressBar)}; + private static readonly Type[] s_newItemTypesForToolStrip = + new Type[] { typeof(ToolStripButton), typeof(ToolStripLabel), typeof(ToolStripSplitButton), typeof(ToolStripDropDownButton), typeof(ToolStripSeparator), typeof(ToolStripComboBox), typeof(ToolStripTextBox), typeof(ToolStripProgressBar) }; // StatusStrip - Default item is determined by being first in the list - private static readonly Type[] s_newItemTypesForStatusStrip = - new Type[]{typeof(ToolStripStatusLabel), typeof(ToolStripProgressBar), typeof(ToolStripDropDownButton), typeof(ToolStripSplitButton)}; + private static readonly Type[] s_newItemTypesForStatusStrip = + new Type[] { typeof(ToolStripStatusLabel), typeof(ToolStripProgressBar), typeof(ToolStripDropDownButton), typeof(ToolStripSplitButton) }; // MenuStrip - Default item is determined by being first in the list - private static readonly Type[] s_newItemTypesForMenuStrip = - new Type[]{typeof(ToolStripMenuItem), typeof(ToolStripComboBox), typeof(ToolStripTextBox)}; + private static readonly Type[] s_newItemTypesForMenuStrip = + new Type[] { typeof(ToolStripMenuItem), typeof(ToolStripComboBox), typeof(ToolStripTextBox) }; // ToolStripDropDown - roughly same as menu strip. - private static readonly Type[] s_newItemTypesForToolStripDropDownMenu = - new Type[]{typeof(ToolStripMenuItem), typeof(ToolStripComboBox), typeof(ToolStripSeparator), typeof(ToolStripTextBox)}; + private static readonly Type[] s_newItemTypesForToolStripDropDownMenu = + new Type[] { typeof(ToolStripMenuItem), typeof(ToolStripComboBox), typeof(ToolStripSeparator), typeof(ToolStripTextBox) }; #endregion // Get the Correct bounds for painting... diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs index 3157e67ff23..9506423e650 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs @@ -123,12 +123,12 @@ private void PopulateList() //Add event Handlers imageToolStripMenuItem.Click += new EventHandler(OnImageToolStripMenuItemClick); enabledToolStripMenuItem = CreateBooleanItem("E&nabled", "Enabled"); - this.AddRange(new ToolStripItem[] { imageToolStripMenuItem, enabledToolStripMenuItem}); + this.AddRange(new ToolStripItem[] { imageToolStripMenuItem, enabledToolStripMenuItem }); if (selectedItem is ToolStripMenuItem) { checkedToolStripMenuItem = CreateBooleanItem("C&hecked", "Checked"); showShortcutKeysToolStripMenuItem = CreateBooleanItem("ShowShortcut&Keys", "ShowShortcutKeys"); - this.AddRange(new System.Windows.Forms.ToolStripItem[] { checkedToolStripMenuItem, showShortcutKeysToolStripMenuItem}); + this.AddRange(new System.Windows.Forms.ToolStripItem[] { checkedToolStripMenuItem, showShortcutKeysToolStripMenuItem }); } else { @@ -152,10 +152,10 @@ private void PopulateList() imageTextStyleToolStripMenuItem = CreateEnumValueItem("DisplayStyle", "ImageAndText", ToolStripItemDisplayStyle.ImageAndText); // alignmentToolStripMenuItem alignmentToolStripMenuItem = CreatePropertyBasedItem("Ali&gnment", "Alignment", "alignment.bmp"); - alignmentToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { leftToolStripMenuItem, rightToolStripMenuItem}); + alignmentToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { leftToolStripMenuItem, rightToolStripMenuItem }); // displayStyleToolStripMenuItem displayStyleToolStripMenuItem = CreatePropertyBasedItem("Displa&yStyle", "DisplayStyle", "displaystyle.bmp"); - displayStyleToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { noneStyleToolStripMenuItem, textStyleToolStripMenuItem, imageStyleToolStripMenuItem, imageTextStyleToolStripMenuItem}); + displayStyleToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { noneStyleToolStripMenuItem, textStyleToolStripMenuItem, imageStyleToolStripMenuItem, imageTextStyleToolStripMenuItem }); if (serviceProvider.GetService(typeof(IUIService)) is IUIService uis) { @@ -193,7 +193,7 @@ private void PopulateList() DropDown = ToolStripDesignerUtils.GetNewItemDropDown(ParentTool, currentItem, new EventHandler(AddNewItemClick), false, serviceProvider, true) }; - this.AddRange(new System.Windows.Forms.ToolStripItem[] { convertToolStripMenuItem, insertToolStripMenuItem}); + this.AddRange(new System.Windows.Forms.ToolStripItem[] { convertToolStripMenuItem, insertToolStripMenuItem }); if (currentItem is ToolStripDropDownItem) { diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemDesigner.cs index 4bbb8acf1d1..8f1d07149e6 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemDesigner.cs @@ -87,12 +87,12 @@ private ContextMenuStrip DesignerContextMenu if (selSvc.SelectionCount > 1) { toolStripContextMenu.GroupOrdering.Clear(); - toolStripContextMenu.GroupOrdering.AddRange(new string[] { StandardGroups.Code, StandardGroups.Selection, StandardGroups.Edit, StandardGroups.Properties}); + toolStripContextMenu.GroupOrdering.AddRange(new string[] { StandardGroups.Code, StandardGroups.Selection, StandardGroups.Edit, StandardGroups.Properties }); } else { toolStripContextMenu.GroupOrdering.Clear(); - toolStripContextMenu.GroupOrdering.AddRange(new string[] { StandardGroups.Code, StandardGroups.Custom, StandardGroups.Selection, StandardGroups.Edit, StandardGroups.Properties}); + toolStripContextMenu.GroupOrdering.AddRange(new string[] { StandardGroups.Code, StandardGroups.Custom, StandardGroups.Selection, StandardGroups.Edit, StandardGroups.Properties }); toolStripContextMenu.Text = "CustomContextMenu"; if (toolStripItemCustomMenuItemCollection == null) { diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemGlyph.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemGlyph.cs index 339791195f7..7aa1ab6ddd8 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemGlyph.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemGlyph.cs @@ -49,7 +49,7 @@ public override Cursor GetHitTest(Point p) } return null; } - + /// /// Control host dont draw on Invalidation... /// diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs index 554b23346da..7546d2f86de 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs @@ -2576,7 +2576,7 @@ public override Cursor GetHitTest(Point p) } return null; } - + /// /// Overrides Glyph::Paint - this implementation does nothing. /// diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/UndoEngine.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/UndoEngine.cs index 015ddb33ba1..220f7331c07 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/UndoEngine.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/UndoEngine.cs @@ -97,7 +97,7 @@ public bool UndoInProgress public bool Enabled { get => _enabled; - set => _enabled = value; + set => _enabled = value; } /// @@ -195,7 +195,7 @@ protected virtual UndoUnit CreateUndoUnit(string name, bool primary) internal IComponentChangeService ComponentChangeService { - get =>_componentChangeService; + get => _componentChangeService; } /// @@ -462,7 +462,7 @@ private void OnComponentRemoving(object sender, ComponentEventArgs e) } if (obj != null && object.ReferenceEquals(obj, e.Component)) - { + { if (propsToUpdate == null) { propsToUpdate = new List(); @@ -580,7 +580,7 @@ public UndoUnit(UndoEngine engine, string name) { name = string.Empty; } - + UndoEngine.Trace("Creating undo unit '{0}'", name); Name = name; @@ -785,13 +785,16 @@ public virtual void ComponentChanging(ComponentChangingEventArgs e) #if DEBUG string name = UndoEngine.GetName(e.Component, false); string memberName = "(none)"; - if (e.Member != null && e.Member.Name != null) { - memberName = e.Member.Name; + if (e.Member != null && e.Member.Name != null) + { + memberName = e.Member.Name; } - if (name != null) { + if (name != null) + { Debug.WriteLineIf(s_traceUndo.TraceVerbose && hasChange, "Adding second ChangeEvent for " + name + " Member: " + memberName); } - else { + else + { Debug.Fail("UndoEngine: GetName is failing on successive calls"); } #endif From 19d35c96e9328c451e69374eb4e2741196424384 Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Thu, 23 May 2019 13:25:07 -0700 Subject: [PATCH 07/27] formatting System.Windows.Forms.Design.Editors --- src/Common/src/ClientUtils.cs | 16 +++--- .../src/Misc/CommonUnsafeNativeMethods.cs | 14 ++--- .../src/Misc/ConfigurationOptions.cs | 8 +-- .../src/Misc/DpiHelper.cs | 38 +++++++------- .../src/Misc/NativeMethods.cs | 2 +- .../src/Misc/UnsafeNativeMethods.cs | 8 +-- .../ComponentModel/Design/CollectionEditor.cs | 52 +++++++++---------- .../Design/MultilineStringEditor.cs | 21 ++++---- .../Design/ObjectSelectorEditor.cs | 38 +++++++------- .../src/System/Drawing/Design/ColorEditor.cs | 2 +- .../src/System/Drawing/Design/CursorEditor.cs | 3 +- .../Windows/Forms/Design/AnchorEditor.cs | 21 +++++--- .../Windows/Forms/Design/BorderSidesEditor.cs | 42 ++++++++++----- .../System/Windows/Forms/Design/DockEditor.cs | 16 +++--- .../Windows/Forms/Design/FolderNameEditor.cs | 2 +- .../Forms/Design/ShortcutKeysEditor.cs | 24 ++++++--- 16 files changed, 172 insertions(+), 135 deletions(-) diff --git a/src/Common/src/ClientUtils.cs b/src/Common/src/ClientUtils.cs index 0913d99e0ed..46fd2ad166c 100644 --- a/src/Common/src/ClientUtils.cs +++ b/src/Common/src/ClientUtils.cs @@ -7,12 +7,12 @@ namespace System.Windows.Forms #elif DRAWING_NAMESPACE namespace System.Drawing -#elif WINFORMS_PUBLIC_GRAPHICS_LIBRARY +#elif WINFORMS_PUBLIC_GRAPHICS_LIBRARY namespace System.Internal #elif SYSTEM_NAMESPACE namespace System #else - namespace System.Windows.Forms +namespace System.Windows.Forms #endif { using System; @@ -501,7 +501,7 @@ public void RemoveByHashCode(object value) } } - #region IList Members + #region IList Members public void Clear() { InnerList.Clear(); } public bool IsFixedSize { get { return InnerList.IsFixedSize; } } public bool Contains(object value) { return InnerList.Contains(CreateWeakRefObject(value)); } @@ -517,22 +517,22 @@ public int Add(object value) } return InnerList.Add(CreateWeakRefObject(value)); } - #endregion + #endregion - #region ICollection Members + #region ICollection Members public int Count { get { return InnerList.Count; } } object ICollection.SyncRoot { get { return InnerList.SyncRoot; } } public bool IsReadOnly { get { return InnerList.IsReadOnly; } } public void CopyTo(Array array, int index) { InnerList.CopyTo(array, index); } bool ICollection.IsSynchronized { get { return InnerList.IsSynchronized; } } - #endregion + #endregion - #region IEnumerable Members + #region IEnumerable Members public IEnumerator GetEnumerator() { return InnerList.GetEnumerator(); } - #endregion + #endregion /// /// Wraps a weak ref object. diff --git a/src/System.Windows.Forms.Design.Editors/src/Misc/CommonUnsafeNativeMethods.cs b/src/System.Windows.Forms.Design.Editors/src/Misc/CommonUnsafeNativeMethods.cs index b15a7830fe8..b02e6a4d18b 100644 --- a/src/System.Windows.Forms.Design.Editors/src/Misc/CommonUnsafeNativeMethods.cs +++ b/src/System.Windows.Forms.Design.Editors/src/Misc/CommonUnsafeNativeMethods.cs @@ -124,13 +124,13 @@ public static DpiAwarenessContext TrySetThreadDpiAwarenessContext(DpiAwarenessCo return DpiAwarenessContext.DPI_AWARENESS_CONTEXT_UNSPECIFIED; } } -/* - // Dpi awareness context values. Matching windows values. - public static readonly DPI_AWARENESS_CONTEXT DPI_AWARENESS_CONTEXT_UNAWARE = (-1); - public static readonly DPI_AWARENESS_CONTEXT DPI_AWARENESS_CONTEXT_SYSTEM_AWARE = (-2); - public static readonly DPI_AWARENESS_CONTEXT DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE = (-3); - public static readonly DPI_AWARENESS_CONTEXT DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = (-4); - public static readonly DPI_AWARENESS_CONTEXT DPI_AWARENESS_CONTEXT_UNSPECIFIED = (0);*/ + /* + // Dpi awareness context values. Matching windows values. + public static readonly DPI_AWARENESS_CONTEXT DPI_AWARENESS_CONTEXT_UNAWARE = (-1); + public static readonly DPI_AWARENESS_CONTEXT DPI_AWARENESS_CONTEXT_SYSTEM_AWARE = (-2); + public static readonly DPI_AWARENESS_CONTEXT DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE = (-3); + public static readonly DPI_AWARENESS_CONTEXT DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = (-4); + public static readonly DPI_AWARENESS_CONTEXT DPI_AWARENESS_CONTEXT_UNSPECIFIED = (0);*/ #endregion } } diff --git a/src/System.Windows.Forms.Design.Editors/src/Misc/ConfigurationOptions.cs b/src/System.Windows.Forms.Design.Editors/src/Misc/ConfigurationOptions.cs index fa9cb9d18b4..dac4652b7fa 100644 --- a/src/System.Windows.Forms.Design.Editors/src/Misc/ConfigurationOptions.cs +++ b/src/System.Windows.Forms.Design.Editors/src/Misc/ConfigurationOptions.cs @@ -20,7 +20,7 @@ internal static class ConfigurationOptions private static readonly Version featureSupportedMinimumFrameworkVersion = new Version(4, 7); // RS2 build number - we may need to change once we know RTM version. below is pre-RTM RS2 version. - internal static readonly Version RS2Version = new Version(10, 0, 14933, 0); + internal static readonly Version RS2Version = new Version(10, 0, 14933, 0); static ConfigurationOptions() { @@ -51,12 +51,12 @@ public static Version NetFrameworkVersion { if (netFrameworkVersion == null) { - netFrameworkVersion = new Version(0,0,0,0); // by default version set to 0.0.0.0 + netFrameworkVersion = new Version(0, 0, 0, 0); // by default version set to 0.0.0.0 // TargetFrameworkName can be null in certain scenarios. try { - var targetFrameworkName= AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName; + var targetFrameworkName = AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName; if (!string.IsNullOrEmpty(targetFrameworkName)) { var frameworkName = new FrameworkName(targetFrameworkName); @@ -65,7 +65,7 @@ public static Version NetFrameworkVersion } } catch (Exception e) - { + { Debug.WriteLine("Exception while reading Framework version : " + e.ToString()); } } diff --git a/src/System.Windows.Forms.Design.Editors/src/Misc/DpiHelper.cs b/src/System.Windows.Forms.Design.Editors/src/Misc/DpiHelper.cs index c6213b6400e..9bd232a25f4 100644 --- a/src/System.Windows.Forms.Design.Editors/src/Misc/DpiHelper.cs +++ b/src/System.Windows.Forms.Design.Editors/src/Misc/DpiHelper.cs @@ -35,7 +35,7 @@ internal static partial class DpiHelper private static bool enableHighDpi = false; private static string dpiAwarenessValue = null; private static InterpolationMode interpolationMode = InterpolationMode.Invalid; - + // Following quirks are not used in System.Drawing. Making sure they light up only in the required binaries. #if (!DRAWING_NAMESPACE) private static bool isDpiHelperQuirksInitialized = false; @@ -151,7 +151,7 @@ internal static void InitializeDpiHelperForWinforms() } internal static void InitializeDpiHelperQuirks() - { + { if (isDpiHelperQuirksInitialized) { return; @@ -369,12 +369,12 @@ internal static bool EnableMonthCalendarHighDpiImprovements } #endif - internal static int DeviceDpi + internal static int DeviceDpi { - get + get { Initialize(); - return (int)deviceDpi; + return (int)deviceDpi; } } @@ -393,9 +393,9 @@ private static double LogicalToDeviceUnitsScalingFactor private static InterpolationMode InterpolationMode { - get + get { - if (interpolationMode == InterpolationMode.Invalid) + if (interpolationMode == InterpolationMode.Invalid) { int dpiScalePercent = (int)Math.Round(LogicalToDeviceUnitsScalingFactor * 100); @@ -405,15 +405,15 @@ private static InterpolationMode InterpolationMode // it will not distort the original (which is extremely important for small zoom factors like 125%, 150%). // We'll use Bicubic in those cases, except on reducing (zoom < 100, which we shouldn't have anyway), in which case Linear produces better // results because it uses less neighboring pixels. - if ((dpiScalePercent % 100) == 0) + if ((dpiScalePercent % 100) == 0) { interpolationMode = InterpolationMode.NearestNeighbor; - } - else if (dpiScalePercent < 100) + } + else if (dpiScalePercent < 100) { interpolationMode = InterpolationMode.HighQualityBilinear; - } - else + } + else { interpolationMode = InterpolationMode.HighQualityBicubic; } @@ -447,7 +447,7 @@ private static Bitmap ScaleBitmapToSize(Bitmap logicalImage, Size deviceImageSiz return deviceImage; } - private static Bitmap CreateScaledBitmap(Bitmap logicalImage, int deviceDpi = 0) + private static Bitmap CreateScaledBitmap(Bitmap logicalImage, int deviceDpi = 0) { Size deviceImageSize = DpiHelper.LogicalToDeviceUnits(logicalImage.Size, deviceDpi); return ScaleBitmapToSize(logicalImage, deviceImageSize); @@ -472,9 +472,9 @@ public static bool IsScalingRequired /// /// value in logical units /// value in device units - public static int LogicalToDeviceUnits(int value, int devicePixels = 0) + public static int LogicalToDeviceUnits(int value, int devicePixels = 0) { - if (devicePixels == 0) + if (devicePixels == 0) { return (int)Math.Round(LogicalToDeviceUnitsScalingFactor * (double)value); } @@ -488,7 +488,7 @@ public static int LogicalToDeviceUnits(int value, int devicePixels = 0) /// /// The horizontal value in logical units /// The horizontal value in device units - public static int LogicalToDeviceUnitsX(int value) + public static int LogicalToDeviceUnitsX(int value) { return LogicalToDeviceUnits(value, 0); } @@ -499,11 +499,11 @@ public static int LogicalToDeviceUnitsX(int value) /// /// The vertical value in logical units /// The vertical value in device units - public static int LogicalToDeviceUnitsY(int value) + public static int LogicalToDeviceUnitsY(int value) { return LogicalToDeviceUnits(value, 0); } - + /// /// Returns a new Size with the input's /// dimensions converted from logical units to device units. @@ -538,7 +538,7 @@ public static Bitmap CreateResizedBitmap(Bitmap logicalImage, Size targetImageSi /// The image to scale from logical units to device units public static void ScaleBitmapLogicalToDevice(ref Bitmap logicalBitmap, int deviceDpi = 0) { - if (logicalBitmap == null) + if (logicalBitmap == null) { return; } diff --git a/src/System.Windows.Forms.Design.Editors/src/Misc/NativeMethods.cs b/src/System.Windows.Forms.Design.Editors/src/Misc/NativeMethods.cs index 13abb46c735..2780d5b496f 100644 --- a/src/System.Windows.Forms.Design.Editors/src/Misc/NativeMethods.cs +++ b/src/System.Windows.Forms.Design.Editors/src/Misc/NativeMethods.cs @@ -55,7 +55,7 @@ public class TEXTMETRIC public const int EC_LEFTMARGIN = 0x0001; public const int EC_RIGHTMARGIN = 0x0002; public const int IDOK = 1; - + public const int VK_PROCESSKEY = 0xE5; public const int STGM_READ = 0x00000000; diff --git a/src/System.Windows.Forms.Design.Editors/src/Misc/UnsafeNativeMethods.cs b/src/System.Windows.Forms.Design.Editors/src/Misc/UnsafeNativeMethods.cs index d581f93e55c..34825d73c48 100644 --- a/src/System.Windows.Forms.Design.Editors/src/Misc/UnsafeNativeMethods.cs +++ b/src/System.Windows.Forms.Design.Editors/src/Misc/UnsafeNativeMethods.cs @@ -70,7 +70,7 @@ public static extern int MsgWaitForMultipleObjectsEx(int nCount, IntPtr pHandles [DllImport(ExternDll.User32, ExactSpelling = true, EntryPoint = "GetDC", CharSet = CharSet.Auto)] private static extern IntPtr IntGetDC(HandleRef hWnd); - + public static IntPtr GetDC(HandleRef hWnd) { return Interop.HandleCollector.Add(IntGetDC(hWnd), Interop.CommonHandles.HDC); @@ -103,7 +103,8 @@ public static int ReleaseDC(HandleRef hWnd, HandleRef hDC) //it'll be OK. public static IntPtr GetWindowLong(HandleRef hWnd, int nIndex) { - if (IntPtr.Size == 4) return GetWindowLong32(hWnd, nIndex); + if (IntPtr.Size == 4) + return GetWindowLong32(hWnd, nIndex); return GetWindowLongPtr64(hWnd, nIndex); } @@ -126,7 +127,8 @@ public static IntPtr GetWindowLong(HandleRef hWnd, int nIndex) //it'll be OK. public static IntPtr SetWindowLong(HandleRef hWnd, int nIndex, HandleRef dwNewLong) { - if (IntPtr.Size == 4) return SetWindowLongPtr32(hWnd, nIndex, dwNewLong); + if (IntPtr.Size == 4) + return SetWindowLongPtr32(hWnd, nIndex, dwNewLong); return SetWindowLongPtr64(hWnd, nIndex, dwNewLong); } diff --git a/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/CollectionEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/CollectionEditor.cs index 18b82e47f5b..5182f7c7479 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/CollectionEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/CollectionEditor.cs @@ -20,7 +20,7 @@ namespace System.ComponentModel.Design /// Provides a generic editor for most any collection. /// public class CollectionEditor : UITypeEditor - { + { private Type _collectionItemType; private Type[] _newItemTypes; private ITypeDescriptorContext _currentContext; @@ -493,7 +493,7 @@ protected override bool IsInputKey(Keys keyData) { return true; } - + return base.IsInputKey(keyData); } @@ -825,7 +825,7 @@ private void AddDownMenu_click(object sender, EventArgs e) CreateAndAddInstance(typeMenuItem.ItemType); } } - + /// /// This Function adds the individual objects to the ListBox. /// @@ -909,7 +909,7 @@ private bool AllowRemoveInstance(object value) { return true; } - + return CanRemoveInstance(value); } @@ -1000,7 +1000,7 @@ private void CancelButton_click(object sender, EventArgs e) DisplayError(ex); } } - + /// /// Performs a create instance and then adds the instance to the list box. /// @@ -1629,7 +1629,7 @@ private void RemoveInternal(ListItem item) UpdateItemWidths(null); } } - + /// /// Removes the selected item. /// @@ -1669,7 +1669,7 @@ private void ResumeEnabledUpdates(bool updateNow) /// Calls to UpdateEnabled will return silently until Resume is called /// private void SuspendEnabledUpdates() => _suspendEnabledCount++; - + /// /// Called to show the dialog via the IWindowsFormsEditorService /// @@ -2094,7 +2094,7 @@ public TypeMenuItem(Type itemType, EventHandler handler) : base(itemType.Name, n public Type ItemType { get; } } } - + /// /// List box filled with ListItem objects representing the collection. /// @@ -2205,7 +2205,7 @@ protected abstract class CollectionForm : Form private const short EditableDynamic = 0; private const short EditableYes = 1; private const short EditableNo = 2; - + /// /// Initializes a new instance of the class. /// @@ -2213,17 +2213,17 @@ public CollectionForm(CollectionEditor editor) { _editor = editor ?? throw new ArgumentNullException(nameof(editor)); } - + /// /// Gets or sets the data type of each item in the collection. /// protected Type CollectionItemType => _editor.CollectionItemType; - + /// /// Gets or sets the type of the collection. /// protected Type CollectionType => _editor.CollectionType; - + internal virtual bool CollectionEditable { get @@ -2247,12 +2247,12 @@ internal virtual bool CollectionEditable } set => _editableState = value ? EditableYes : EditableNo; } - + /// /// Gets or sets a type descriptor that indicates the current context. /// protected ITypeDescriptorContext Context => _editor.Context; - + /// /// Gets or sets the value of the item being edited. /// @@ -2265,7 +2265,7 @@ public object EditValue OnEditValueChanged(); } } - + /// /// Gets or sets the array of items this form is to display. /// @@ -2301,32 +2301,32 @@ protected object[] Items } } } - + /// /// Gets or sets the available item types that can be created for this collection. /// protected Type[] NewItemTypes => _editor.NewItemTypes; - + /// /// Gets or sets a value indicating whether original members of the collection can be removed. /// protected bool CanRemoveInstance(object value) => _editor.CanRemoveInstance(value); - + /// /// Gets or sets a value indicating whether multiple collection members can be selected. /// protected virtual bool CanSelectMultipleInstances() => _editor.CanSelectMultipleInstances(); - + /// /// Creates a new instance of the specified collection item type. /// protected object CreateInstance(Type itemType) => _editor.CreateInstance(itemType); - + /// /// Destroys the specified instance of the object. /// - protected void DestroyInstance(object instance) => _editor.DestroyInstance(instance); - + protected void DestroyInstance(object instance) => _editor.DestroyInstance(instance); + /// /// Displays the given exception to the user. /// @@ -2347,12 +2347,12 @@ protected virtual void DisplayError(Exception e) RTLAwareMessageBox.Show(null, message, null, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, 0); } } - + /// /// Gets the requested service, if it is available. /// protected override object GetService(Type serviceType) => _editor.GetService(serviceType); - + /// /// Called to show the dialog via the IWindowsFormsEditorService /// @@ -2365,7 +2365,7 @@ protected internal virtual DialogResult ShowEditorDialog(IWindowsFormsEditorServ return edSvc.ShowDialog(this); } - + /// /// This is called when the value property in the has changed. /// @@ -2409,7 +2409,7 @@ public object GetService(Type t) _inGetService = false; } } - + return null; } } diff --git a/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/MultilineStringEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/MultilineStringEditor.cs index a41fb27a603..d7c4ae873de 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/MultilineStringEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/MultilineStringEditor.cs @@ -287,8 +287,8 @@ public override Size MinimumSize { Rectangle workingArea = Screen.GetWorkingArea(this); _minimumSize = new Size( - (int)Math.Min(Math.Ceiling(WatermarkSize.Width * 1.75), workingArea.Width / 3 ), - (int)Math.Min( Font.Height * 10, workingArea.Height / 3 )); + (int)Math.Min(Math.Ceiling(WatermarkSize.Width * 1.75), workingArea.Width / 3), + (int)Math.Min(Font.Height * 10, workingArea.Height / 3)); } return _minimumSize; } @@ -306,7 +306,8 @@ public override Font Font public void ProcessSurrogateFonts(int start, int length) { string value = Text; - if (value == null) return; + if (value == null) + return; int[] surrogates = StringInfo.ParseCombiningCharacters(value); if (surrogates.Length != value.Length) @@ -393,7 +394,7 @@ private Size WatermarkSize // See how much space we should reserve for watermark using (Graphics g = CreateGraphics()) { - size = g.MeasureString( SR.MultilineStringEditorWatermark, Font); + size = g.MeasureString(SR.MultilineStringEditorWatermark, Font); } _watermarkSize = new Size((int)Math.Ceiling(size.Width), (int)Math.Ceiling(size.Height)); } @@ -435,14 +436,14 @@ protected override void WndProc(ref Message m) switch (m.Msg) { case Interop.WindowMessages.WM_PAINT: - { - if (ShouldShowWatermark) { - using Graphics g = CreateGraphics(); - g.DrawString(SR.MultilineStringEditorWatermark, Font, WatermarkBrush, new RectangleF(0.0f, 0.0f, ClientSize.Width, ClientSize.Height), _watermarkFormat); + if (ShouldShowWatermark) + { + using Graphics g = CreateGraphics(); + g.DrawString(SR.MultilineStringEditorWatermark, Font, WatermarkBrush, new RectangleF(0.0f, 0.0f, ClientSize.Width, ClientSize.Height), _watermarkFormat); + } + break; } - break; - } } } #endregion diff --git a/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/ObjectSelectorEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/ObjectSelectorEditor.cs index d8de2e8bad3..9c4ddd9f792 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/ObjectSelectorEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/ObjectSelectorEditor.cs @@ -19,7 +19,7 @@ public abstract class ObjectSelectorEditor : UITypeEditor protected object prevValue = null; protected object currValue = null; private Selector _selector = null; - + /// /// Default constructor for ObjectSelectorEditor /// @@ -34,7 +34,7 @@ public ObjectSelectorEditor(bool subObjectSelector) { SubObjectSelector = subObjectSelector; } - + /// /// Edits the given object value using the editor style provided by ObjectSelectorEditor.GetEditStyle. /// @@ -68,7 +68,7 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide return value; } - + /// /// Modify a WinForms TreeView control to use the new Explorer style theme /// @@ -98,12 +98,12 @@ private static void TreeView_SetExtendedStyle(IntPtr handle, int extendedStyle, { NativeMethods.SendMessage(handle, NativeMethods.TVM_SETEXTENDEDSTYLE, new IntPtr(mask), new IntPtr(extendedStyle)); } - + public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.DropDown; } - + protected internal bool EqualsToValue(object value) { if (value == currValue) @@ -111,7 +111,7 @@ protected internal bool EqualsToValue(object value) else return false; } - + protected virtual void FillTreeWithData(Selector selector, ITypeDescriptorContext context, IServiceProvider provider) { selector.Clear(); @@ -124,7 +124,7 @@ public virtual void SetValue(object value) { currValue = value; } - + public class Selector : TreeView { private readonly ObjectSelectorEditor _editor = null; @@ -149,7 +149,7 @@ public Selector(ObjectSelectorEditor editor) AfterSelect += new TreeViewEventHandler(OnAfterSelect); } - + /// /// Adds a Node with given label and value to the parent, provided the parent is not null; /// Otherwise, adds that node to the Nodes TreeNodeCollection. Returns the new node. @@ -185,7 +185,7 @@ private bool ChooseSelectedNodeIfEqual() } return false; } - + /// /// Clears the TreeNodeCollection and sets clickSeen to false /// @@ -194,7 +194,7 @@ public void Clear() clickSeen = false; Nodes.Clear(); } - + protected void OnAfterSelect(object sender, TreeViewEventArgs e) { if (clickSeen) @@ -203,7 +203,7 @@ protected void OnAfterSelect(object sender, TreeViewEventArgs e) clickSeen = false; } } - + protected override void OnKeyDown(KeyEventArgs e) { Keys key = e.KeyCode; @@ -224,7 +224,7 @@ protected override void OnKeyDown(KeyEventArgs e) } base.OnKeyDown(e); } - + protected override void OnKeyPress(KeyPressEventArgs e) { switch (e.KeyChar) @@ -235,7 +235,7 @@ protected override void OnKeyPress(KeyPressEventArgs e) } base.OnKeyPress(e); } - + protected override void OnNodeMouseClick(TreeNodeMouseClickEventArgs e) { // we won't get an OnAfterSelect if it's already selected, so use this instead @@ -245,7 +245,7 @@ protected override void OnNodeMouseClick(TreeNodeMouseClickEventArgs e) } base.OnNodeMouseClick(e); } - + /// /// Sets the selection /// @@ -287,7 +287,7 @@ public bool SetSelection(object value, TreeNodeCollection nodes) } return false; } - + /// /// Sets the internal IWindowsFormsEditorService to the given edSvc, and calls SetSelection on the given value /// @@ -297,7 +297,7 @@ public void Start(IWindowsFormsEditorService edSvc, object value) clickSeen = false; SetSelection(value, Nodes); } - + /// /// Sets the internal IWindowsFormsEditorService to null /// @@ -305,7 +305,7 @@ public void Stop() { _edSvc = null; } - + protected override void WndProc(ref Message m) { switch (m.Msg) @@ -330,7 +330,7 @@ protected override void WndProc(ref Message m) base.WndProc(ref m); } } - + /// Suppressed because although the type implements ISerializable --its on the base class and this class /// is not modifying the stream to include its local information. Therefore, we should not publicly advertise this as /// Serializable unless explicitly required. @@ -338,7 +338,7 @@ protected override void WndProc(ref Message m) public class SelectorNode : TreeNode { public object value = null; - + /// /// Sets label and value to given. /// diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/ColorEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/ColorEditor.cs index 0c613fa14f1..5c756dee86e 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/ColorEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/ColorEditor.cs @@ -138,7 +138,7 @@ private class ColorPalette : Control public ColorPalette(ColorUI colorUI, Color[] customColors) { - + if (!isScalingInitialized) { if (DpiHelper.IsScalingRequired) diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/CursorEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/CursorEditor.cs index 165d23bcc99..d74d74f796f 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/CursorEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/CursorEditor.cs @@ -32,7 +32,8 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide { object returnValue = value; - if (provider == null) return value; + if (provider == null) + return value; IWindowsFormsEditorService edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (edSvc != null) diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/AnchorEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/AnchorEditor.cs index f4cea76d2db..c01edac5065 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/AnchorEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/AnchorEditor.cs @@ -32,7 +32,8 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide if (edSvc != null) { - if (anchorUI == null) anchorUI = new AnchorUI(this); + if (anchorUI == null) + anchorUI = new AnchorUI(this); anchorUI.Start(edSvc, value); edSvc.DropDownControl(anchorUI); value = anchorUI.Value; @@ -90,10 +91,14 @@ public void End() public virtual AnchorStyles GetSelectedAnchor() { AnchorStyles baseVar = 0; - if (left.GetSolid()) baseVar |= AnchorStyles.Left; - if (top.GetSolid()) baseVar |= AnchorStyles.Top; - if (bottom.GetSolid()) baseVar |= AnchorStyles.Bottom; - if (right.GetSolid()) baseVar |= AnchorStyles.Right; + if (left.GetSolid()) + baseVar |= AnchorStyles.Left; + if (top.GetSolid()) + baseVar |= AnchorStyles.Top; + if (bottom.GetSolid()) + baseVar |= AnchorStyles.Bottom; + if (right.GetSolid()) + baseVar |= AnchorStyles.Right; return baseVar; } @@ -189,7 +194,8 @@ public void Start(IWindowsFormsEditorService edSvc, object value) private void Teardown(bool saveAnchor) { - if (!saveAnchor) Value = oldAnchor; + if (!saveAnchor) + Value = oldAnchor; edSvc.CloseDropDown(); } @@ -362,7 +368,8 @@ public override AccessibleStates State { AccessibleStates state = base.State; - if (((SpringControl)Owner).GetSolid()) state |= AccessibleStates.Selected; + if (((SpringControl)Owner).GetSolid()) + state |= AccessibleStates.Selected; return state; } diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/BorderSidesEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/BorderSidesEditor.cs index 0ee8f38f6bd..685e5f4cbf5 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/BorderSidesEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/BorderSidesEditor.cs @@ -29,11 +29,13 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (edSvc != null) { - if (borderSidesEditorUI == null) borderSidesEditorUI = new BorderSidesEditorUI(this); + if (borderSidesEditorUI == null) + borderSidesEditorUI = new BorderSidesEditorUI(this); borderSidesEditorUI.Start(edSvc, value); edSvc.DropDownControl(borderSidesEditorUI); - if (borderSidesEditorUI.Value != null) value = borderSidesEditorUI.Value; + if (borderSidesEditorUI.Value != null) + value = borderSidesEditorUI.Value; borderSidesEditorUI.End(); } } @@ -228,7 +230,8 @@ private void rightCheckBox_CheckedChanged(object sender, EventArgs e) } else // this is turned off.... { - if (allCheckBox.Checked) allCheckBox.Checked = false; + if (allCheckBox.Checked) + allCheckBox.Checked = false; } UpdateCurrentValue(); @@ -246,7 +249,8 @@ private void leftCheckBox_CheckedChanged(object sender, EventArgs e) } else // this is turned off.... { - if (allCheckBox.Checked) allCheckBox.Checked = false; + if (allCheckBox.Checked) + allCheckBox.Checked = false; } UpdateCurrentValue(); @@ -264,7 +268,8 @@ private void bottomCheckBox_CheckedChanged(object sender, EventArgs e) } else // this is turned off.... { - if (allCheckBox.Checked) allCheckBox.Checked = false; + if (allCheckBox.Checked) + allCheckBox.Checked = false; } UpdateCurrentValue(); @@ -282,7 +287,8 @@ private void topCheckBox_CheckedChanged(object sender, EventArgs e) } else // this is turned off.... { - if (allCheckBox.Checked) allCheckBox.Checked = false; + if (allCheckBox.Checked) + allCheckBox.Checked = false; } UpdateCurrentValue(); @@ -329,7 +335,8 @@ private void allCheckBox_CheckedChanged(object sender, EventArgs e) /// private void noneCheckBoxClicked(object sender, EventArgs e) { - if (noneChecked) noneCheckBox.Checked = true; + if (noneChecked) + noneCheckBox.Checked = true; } /// @@ -337,7 +344,8 @@ private void noneCheckBoxClicked(object sender, EventArgs e) /// private void allCheckBoxClicked(object sender, EventArgs e) { - if (allChecked) allCheckBox.Checked = true; + if (allChecked) + allCheckBox.Checked = true; } /// @@ -405,7 +413,8 @@ public void Start(IWindowsFormsEditorService edSvc, object value) /// private void UpdateCurrentValue() { - if (!updateCurrentValue) return; + if (!updateCurrentValue) + return; ToolStripStatusLabelBorderSides valueSide = ToolStripStatusLabelBorderSides.None; if (allCheckBox.Checked) @@ -417,11 +426,16 @@ private void UpdateCurrentValue() return; } - if (noneCheckBox.Checked) valueSide |= ToolStripStatusLabelBorderSides.None; - if (topCheckBox.Checked) valueSide |= ToolStripStatusLabelBorderSides.Top; - if (bottomCheckBox.Checked) valueSide |= ToolStripStatusLabelBorderSides.Bottom; - if (leftCheckBox.Checked) valueSide |= ToolStripStatusLabelBorderSides.Left; - if (rightCheckBox.Checked) valueSide |= ToolStripStatusLabelBorderSides.Right; + if (noneCheckBox.Checked) + valueSide |= ToolStripStatusLabelBorderSides.None; + if (topCheckBox.Checked) + valueSide |= ToolStripStatusLabelBorderSides.Top; + if (bottomCheckBox.Checked) + valueSide |= ToolStripStatusLabelBorderSides.Bottom; + if (leftCheckBox.Checked) + valueSide |= ToolStripStatusLabelBorderSides.Left; + if (rightCheckBox.Checked) + valueSide |= ToolStripStatusLabelBorderSides.Right; if (valueSide == ToolStripStatusLabelBorderSides.None) { diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/DockEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/DockEditor.cs index cd063e9e67b..ac9736ae17c 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/DockEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/DockEditor.cs @@ -32,7 +32,8 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide if (edSvc != null) { - if (dockUI == null) dockUI = new DockUI(this); + if (dockUI == null) + dockUI = new DockUI(this); dockUI.Start(edSvc, value); edSvc.DropDownControl(dockUI); value = dockUI.Value; @@ -104,7 +105,7 @@ public DockUI(DockEditor editor) upDownOrder = new[] { top, fill, bottom, none }; leftRightOrder = new[] { left, fill, right }; tabOrder = new[] { top, left, fill, right, bottom, none }; - + if (!isScalingInitialized) { if (DpiHelper.IsScalingRequired) @@ -122,7 +123,7 @@ public DockUI(DockEditor editor) } isScalingInitialized = true; - } + } InitializeComponent(); } @@ -145,7 +146,8 @@ public virtual DockStyle GetDock(CheckBox btn) return DockStyle.Bottom; if (right == btn) return DockStyle.Right; - if (fill == btn) return DockStyle.Fill; + if (fill == btn) + return DockStyle.Fill; return DockStyle.None; } @@ -247,7 +249,8 @@ private void InitializeComponent() private void OnClick(object sender, EventArgs eventargs) { DockStyle val = GetDock((CheckBox)sender); - if (val >= 0) Value = val; + if (val >= 0) + Value = val; Teardown(); } @@ -325,7 +328,8 @@ private void OnKeyDown(object sender, KeyEventArgs e) e.Handled = true; - if (target != null && target != sender) target.Focus(); + if (target != null && target != sender) + target.Focus(); } public void Start(IWindowsFormsEditorService edSvc, object value) diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/FolderNameEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/FolderNameEditor.cs index ff3c60cc5d4..6eea2b82e73 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/FolderNameEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/FolderNameEditor.cs @@ -115,7 +115,7 @@ public unsafe DialogResult ShowDialog(IWin32Window owner) char[] displayName = ArrayPool.Shared.Rent(Interop.Kernel32.MAX_PATH + 1); try { - fixed (char *pDisplayName = displayName) + fixed (char* pDisplayName = displayName) { var bi = new Interop.Shell32.BROWSEINFO(); bi.pidlRoot = listHandle; diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/ShortcutKeysEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/ShortcutKeysEditor.cs index 7328d9cb53f..92af91f1db0 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/ShortcutKeysEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/ShortcutKeysEditor.cs @@ -39,7 +39,8 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide shortcutKeysUI.Start(edSvc, value); edSvc.DropDownControl(shortcutKeysUI); - if (shortcutKeysUI.Value != null) value = shortcutKeysUI.Value; + if (shortcutKeysUI.Value != null) + value = shortcutKeysUI.Value; shortcutKeysUI.End(); } } @@ -135,7 +136,8 @@ private TypeConverter KeysConverter { get { - if (keysConverter == null) keysConverter = TypeDescriptor.GetConverter(typeof(Keys)); + if (keysConverter == null) + keysConverter = TypeDescriptor.GetConverter(typeof(Keys)); Debug.Assert(keysConverter != null); return keysConverter; } @@ -148,7 +150,8 @@ public object Value { get { - if (((Keys)currentValue & Keys.KeyCode) == 0) return Keys.None; + if (((Keys)currentValue & Keys.KeyCode) == 0) + return Keys.None; return currentValue; } } @@ -287,7 +290,8 @@ private void InitializeComponent() cmbKey.Margin = new Padding(12, 4, 3, 3); cmbKey.Padding = cmbKey.Margin; - foreach (Keys keyCode in validKeys) cmbKey.Items.Add(KeysConverter.ConvertToString(keyCode)); + foreach (Keys keyCode in validKeys) + cmbKey.Items.Add(KeysConverter.ConvertToString(keyCode)); cmbKey.SelectedIndexChanged += cmbKey_SelectedIndexChanged; // @@ -438,12 +442,16 @@ public void Start(IWindowsFormsEditorService edSvc, object value) /// private void UpdateCurrentValue() { - if (!updateCurrentValue) return; + if (!updateCurrentValue) + return; int cmbKeySelectedIndex = cmbKey.SelectedIndex; Keys valueKeys = Keys.None; - if (chkCtrl.Checked) valueKeys |= Keys.Control; - if (chkAlt.Checked) valueKeys |= Keys.Alt; - if (chkShift.Checked) valueKeys |= Keys.Shift; + if (chkCtrl.Checked) + valueKeys |= Keys.Control; + if (chkAlt.Checked) + valueKeys |= Keys.Alt; + if (chkShift.Checked) + valueKeys |= Keys.Shift; if (unknownKeyCode != Keys.None && cmbKeySelectedIndex == 0) valueKeys |= unknownKeyCode; else if (cmbKeySelectedIndex != -1) From 92becc1b76d514797c7955039fd3d7bfd4c09b4e Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Thu, 23 May 2019 13:26:52 -0700 Subject: [PATCH 08/27] formatting Internal Utilities for Tests --- .../src/AssertExtensions.cs | 2 +- .../src/PlatformDetection.Windows.cs | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/Common/tests/InternalUtilitiesForTests/src/AssertExtensions.cs b/src/Common/tests/InternalUtilitiesForTests/src/AssertExtensions.cs index deef97e22c1..14c8476c84a 100644 --- a/src/Common/tests/InternalUtilitiesForTests/src/AssertExtensions.cs +++ b/src/Common/tests/InternalUtilitiesForTests/src/AssertExtensions.cs @@ -197,7 +197,7 @@ private static string AddOptionalUserMessage(string message, string userMessage) else return $"{message} {userMessage}"; } - + /// /// Tests whether the specified string contains the specified substring /// and throws an exception if the substring does not occur within the diff --git a/src/Common/tests/InternalUtilitiesForTests/src/PlatformDetection.Windows.cs b/src/Common/tests/InternalUtilitiesForTests/src/PlatformDetection.Windows.cs index 9b7be217619..18c36fe3642 100644 --- a/src/Common/tests/InternalUtilitiesForTests/src/PlatformDetection.Windows.cs +++ b/src/Common/tests/InternalUtilitiesForTests/src/PlatformDetection.Windows.cs @@ -43,17 +43,17 @@ public static partial class PlatformDetection public static bool IsRedHatFamily7 => false; public static bool IsNotRedHatFamily6 => true; - public static bool IsWindows10Version1607OrGreater => + public static bool IsWindows10Version1607OrGreater => GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 14393; - public static bool IsWindows10Version1703OrGreater => + public static bool IsWindows10Version1703OrGreater => GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 15063; - public static bool IsWindows10Version1709OrGreater => + public static bool IsWindows10Version1709OrGreater => GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 16299; public static bool IsWindows10Version1803OrGreater => GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 17134; // Windows OneCoreUAP SKU doesn't have httpapi.dll - public static bool IsNotOneCoreUAP => + public static bool IsNotOneCoreUAP => File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "System32", "httpapi.dll")); public static bool IsWindowsIoTCore @@ -268,10 +268,10 @@ private static extern bool GetProductInfo( out int pdwReturnedProductType ); - [DllImport("ntdll.dll", ExactSpelling=true)] + [DllImport("ntdll.dll", ExactSpelling = true)] private static extern int RtlGetVersion(ref RTL_OSVERSIONINFOEX lpVersionInformation); - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] private unsafe struct RTL_OSVERSIONINFOEX { internal uint dwOSVersionInfoSize; @@ -292,7 +292,7 @@ private static unsafe int GetWindowsVersion() [DllImport("kernel32.dll", ExactSpelling = true)] private static extern int GetCurrentApplicationUserModelId(ref uint applicationUserModelIdLength, byte[] applicationUserModelId); - + [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] private static extern bool CloseHandle(IntPtr handle); From 4947fb7dcee4dcf217c858ce235f13570dfd641a Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Thu, 23 May 2019 13:27:35 -0700 Subject: [PATCH 09/27] formatting straggelers --- src/Common/src/ClientUtils.cs | 12 ++++++------ .../WinformsControlsTest/CurrentDPILabel.cs | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Common/src/ClientUtils.cs b/src/Common/src/ClientUtils.cs index 46fd2ad166c..a33b81382cd 100644 --- a/src/Common/src/ClientUtils.cs +++ b/src/Common/src/ClientUtils.cs @@ -501,7 +501,7 @@ public void RemoveByHashCode(object value) } } - #region IList Members + #region IList Members public void Clear() { InnerList.Clear(); } public bool IsFixedSize { get { return InnerList.IsFixedSize; } } public bool Contains(object value) { return InnerList.Contains(CreateWeakRefObject(value)); } @@ -517,22 +517,22 @@ public int Add(object value) } return InnerList.Add(CreateWeakRefObject(value)); } - #endregion + #endregion - #region ICollection Members + #region ICollection Members public int Count { get { return InnerList.Count; } } object ICollection.SyncRoot { get { return InnerList.SyncRoot; } } public bool IsReadOnly { get { return InnerList.IsReadOnly; } } public void CopyTo(Array array, int index) { InnerList.CopyTo(array, index); } bool ICollection.IsSynchronized { get { return InnerList.IsSynchronized; } } - #endregion + #endregion - #region IEnumerable Members + #region IEnumerable Members public IEnumerator GetEnumerator() { return InnerList.GetEnumerator(); } - #endregion + #endregion /// /// Wraps a weak ref object. diff --git a/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/CurrentDPILabel.cs b/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/CurrentDPILabel.cs index f5e48344ffc..616b82c727c 100644 --- a/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/CurrentDPILabel.cs +++ b/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/CurrentDPILabel.cs @@ -17,7 +17,7 @@ public CurrentDPILabel() } [DefaultValue(false)] - public override bool AutoSize + public override bool AutoSize { get { return base.AutoSize; } set { base.AutoSize = value; } From 5906c69531cf819672610d74f7fcde4cc6e7e265 Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Fri, 24 May 2019 11:32:08 -0700 Subject: [PATCH 10/27] remove all instances of IDE0008 warning - remove unambiguous this. --- src/Common/src/ClientUtils.cs | 20 +- src/Common/src/NativeMethods.cs | 78 +- .../src/System/Drawing/Design/ColorEditor.cs | 14 +- .../ComponentModel/Design/DesignSurface.cs | 2 +- .../Forms/Design/Behavior/BehaviorService.cs | 4 +- .../Forms/Design/ToolStripActionList.cs | 2 +- .../Forms/Design/ToolStripDropDownDesigner.cs | 8 +- .../ToolStripItemCustomMenuItemCollection.cs | 2 +- .../Forms/Design/ToolStripItemDesigner.cs | 4 +- .../Forms/Design/ToolStripMenuItemDesigner.cs | 20 +- .../Forms/Design/ToolStripTemplateNode.cs | 4 +- .../src/SRDescriptionAttribute.cs | 4 +- .../src/System/Resources/ResXDataNode.cs | 66 +- .../System/Resources/ResXResourceReader.cs | 12 +- .../System/Resources/ResXResourceWriter.cs | 14 +- .../src/System/Windows/Forms/Application.cs | 12 +- .../Windows/Forms/ApplicationContext.cs | 2 +- .../System/Windows/Forms/ArrangedElement.cs | 10 +- .../Forms/AutoCompleteStringCollection.cs | 8 +- .../src/System/Windows/Forms/AxHost.cs | 156 +- .../System/Windows/Forms/BindingNavigator.cs | 2 +- .../src/System/Windows/Forms/Button.cs | 2 +- .../src/System/Windows/Forms/ButtonBase.cs | 20 +- .../Forms/ButtonInternal/ButtonBaseAdapter.cs | 40 +- .../Forms/ButtonInternal/ButtonFlatAdapter.cs | 6 +- .../ButtonInternal/ButtonPopupAdapter.cs | 6 +- .../ButtonInternal/ButtonStandardAdapter.cs | 6 +- .../src/System/Windows/Forms/CheckBox.cs | 18 +- .../System/Windows/Forms/CheckedListBox.cs | 12 +- .../src/System/Windows/Forms/ColorDialog.cs | 2 +- .../src/System/Windows/Forms/ColumnHeader.cs | 78 +- .../src/System/Windows/Forms/ComboBox.cs | 170 +- .../ComponentModel/COM2Interop/COM2Enum.cs | 10 +- .../COM2Interop/COM2EnumConverter.cs | 2 +- .../COM2Interop/COM2ExtendedTypeConverter.cs | 2 +- .../COM2Interop/COM2ExtendedUITypeEditor.cs | 4 +- .../COM2ICategorizePropertiesHandler.cs | 2 +- .../COM2Interop/COM2IDispatchConverter.cs | 2 +- .../COM2IManagedPerPropertyBrowsingHandler.cs | 2 +- .../COM2IPerPropertyBrowsingHandler.cs | 20 +- .../COM2IProvidePropertyBuilderHandler.cs | 4 +- .../COM2IVsPerPropertyBrowsingHandler.cs | 16 +- .../COM2Interop/COM2Properties.cs | 22 +- .../COM2PropertyBuilderUITypeEditor.cs | 2 +- .../COM2Interop/COM2PropertyDescriptor.cs | 86 +- .../COM2PropertyPageUITypeConverter.cs | 2 +- .../COM2Interop/COM2TypeInfoProcessor.cs | 6 +- .../System/Windows/Forms/ContainerControl.cs | 44 +- .../System/Windows/Forms/ContextMenuStrip.cs | 2 +- .../src/System/Windows/Forms/Control.cs | 352 +- .../Forms/ControlBindingsCollection.cs | 2 +- .../System/Windows/Forms/CurrencyManager.cs | 40 +- .../src/System/Windows/Forms/Cursor.cs | 8 +- .../src/System/Windows/Forms/DataGrid.cs | 806 +- .../System/Windows/Forms/DataGridAddNewRow.cs | 10 +- .../Windows/Forms/DataGridBoolColumn.cs | 36 +- .../System/Windows/Forms/DataGridCaption.cs | 28 +- .../Windows/Forms/DataGridColumnCollection.cs | 32 +- .../Windows/Forms/DataGridParentRows.cs | 6 +- .../Windows/Forms/DataGridRelationshipRow.cs | 118 +- .../src/System/Windows/Forms/DataGridRow.cs | 66 +- .../src/System/Windows/Forms/DataGridState.cs | 44 +- .../src/System/Windows/Forms/DataGridTable.cs | 146 +- .../Windows/Forms/DataGridTableCollection.cs | 16 +- .../System/Windows/Forms/DataGridTextBox.cs | 4 +- .../Windows/Forms/DataGridTextBoxColumn.cs | 62 +- .../src/System/Windows/Forms/DataGridView.cs | 2058 +-- .../Forms/DataGridViewAccessibleObject.cs | 120 +- .../Forms/DataGridViewAdvancedBorderStyle.cs | 146 +- .../Windows/Forms/DataGridViewButtonCell.cs | 238 +- .../Windows/Forms/DataGridViewButtonColumn.cs | 66 +- .../System/Windows/Forms/DataGridViewCell.cs | 1186 +- .../Forms/DataGridViewCellCollection.cs | 112 +- .../Forms/DataGridViewCellLinkedList.cs | 104 +- .../Windows/Forms/DataGridViewCellStyle.cs | 294 +- .../Windows/Forms/DataGridViewCheckBoxCell.cs | 456 +- .../Forms/DataGridViewCheckBoxColumn.cs | 106 +- .../Windows/Forms/DataGridViewColumn.cs | 322 +- .../Forms/DataGridViewColumnCollection.cs | 342 +- ...ridViewColumnDesignTimeVisibleAttribute.cs | 2 +- .../Forms/DataGridViewColumnHeaderCell.cs | 210 +- .../Windows/Forms/DataGridViewComboBoxCell.cs | 832 +- .../Forms/DataGridViewComboBoxColumn.cs | 174 +- .../DataGridViewComboBoxEditingControl.cs | 40 +- .../Forms/DataGridViewControlCollection.cs | 8 +- .../Forms/DataGridViewDataConnection.cs | 578 +- .../Windows/Forms/DataGridViewHeaderCell.cs | 208 +- .../Windows/Forms/DataGridViewHitTestInfo.cs | 26 +- .../Windows/Forms/DataGridViewImageCell.cs | 128 +- .../Windows/Forms/DataGridViewImageColumn.cs | 94 +- .../Forms/DataGridViewIntLinkedList.cs | 112 +- .../Windows/Forms/DataGridViewLayoutData.cs | 20 +- .../Windows/Forms/DataGridViewLinkCell.cs | 330 +- .../Windows/Forms/DataGridViewLinkColumn.cs | 136 +- .../Windows/Forms/DataGridViewMethods.cs | 10878 ++++++++-------- .../System/Windows/Forms/DataGridViewRow.cs | 8 +- .../Forms/DataGridViewRowCollection.cs | 962 +- .../Forms/DataGridViewRowHeaderCell.cs | 248 +- .../DataGridViewSelectedCellCollection.cs | 24 +- ...taGridViewSelectedCellsAccessibleObject.cs | 22 +- .../DataGridViewSelectedColumnCollection.cs | 22 +- .../DataGridViewSelectedRowCollection.cs | 22 +- .../Forms/DataGridViewSortCompareEventArgs.cs | 14 +- .../Windows/Forms/DataGridViewTextBoxCell.cs | 114 +- .../Forms/DataGridViewTextBoxColumn.cs | 22 +- .../DataGridViewTextBoxEditingControl.cs | 72 +- .../Windows/Forms/DataGridViewToolTip.cs | 38 +- .../Forms/DataGridViewTopLeftHeaderCell.cs | 94 +- .../DataGridViewTopRowAccessibleObject.cs | 58 +- .../src/System/Windows/Forms/DataObject.cs | 2 +- .../Windows/Forms/DataStreamFromComStream.cs | 4 +- .../Forms/DatagridviewDisplayedBandsData.cs | 148 +- .../System/Windows/Forms/DateTimePicker.cs | 28 +- .../Forms/Design/ComponentEditorForm.cs | 54 +- .../Forms/Design/ComponentEditorPage.cs | 2 +- .../System/Windows/Forms/DockingAttribute.cs | 8 +- .../src/System/Windows/Forms/ErrorProvider.cs | 72 +- .../src/System/Windows/Forms/FileDialog.cs | 2 +- .../src/System/Windows/Forms/FontDialog.cs | 4 +- .../src/System/Windows/Forms/Form.cs | 132 +- .../Forms/GDI/WindowsGraphicsWrapper.cs | 28 +- .../src/System/Windows/Forms/GroupBox.cs | 8 +- .../src/System/Windows/Forms/HelpProvider.cs | 8 +- .../src/System/Windows/Forms/HtmlDocument.cs | 106 +- .../src/System/Windows/Forms/HtmlElement.cs | 122 +- .../Windows/Forms/HtmlElementCollection.cs | 42 +- .../src/System/Windows/Forms/HtmlHistory.cs | 24 +- .../src/System/Windows/Forms/HtmlShim.cs | 6 +- .../src/System/Windows/Forms/HtmlWindow.cs | 88 +- .../Windows/Forms/HtmlWindowCollection.cs | 16 +- .../src/System/Windows/Forms/ImageList.cs | 22 +- .../src/System/Windows/Forms/InputLanguage.cs | 2 +- .../Forms/KeyboardToolTipStateMachine.cs | 168 +- .../src/System/Windows/Forms/Label.cs | 38 +- .../Forms/Layout/ArrangedElementCollection.cs | 6 +- .../System/Windows/Forms/Layout/FlowLayout.cs | 4 +- .../Windows/Forms/Layout/LayoutSettings.cs | 2 +- .../Windows/Forms/Layout/LayoutUtils.cs | 4 +- .../src/System/Windows/Forms/LinkLabel.cs | 84 +- .../src/System/Windows/Forms/ListBox.cs | 66 +- .../Forms/ListManagerBindingsCollection.cs | 2 +- .../src/System/Windows/Forms/ListView.cs | 758 +- .../Windows/Forms/ListViewGroupCollection.cs | 8 +- .../Forms/ListViewGroupItemCollection.cs | 4 +- .../Windows/Forms/ListViewHitTestInfo.cs | 6 +- .../src/System/Windows/Forms/ListViewItem.cs | 42 +- .../src/System/Windows/Forms/MDIClient.cs | 6 +- .../System/Windows/Forms/MDIControlStrip.cs | 10 +- .../System/Windows/Forms/MDIWindowDialog.cs | 84 +- .../src/System/Windows/Forms/MaskedTextBox.cs | 598 +- .../Windows/Forms/MdiWindowListStrip.cs | 6 +- .../src/System/Windows/Forms/Menu.cs | 6 +- .../src/System/Windows/Forms/MenuStrip.cs | 6 +- .../src/System/Windows/Forms/MonthCalendar.cs | 64 +- .../src/System/Windows/Forms/NativeWindow.cs | 10 +- .../src/System/Windows/Forms/NotifyIcon.cs | 16 +- .../src/System/Windows/Forms/NumericUpDown.cs | 52 +- .../Forms/NumericUpDownAcceleration.cs | 8 +- .../NumericUpDownAccelerationCollection.cs | 24 +- .../src/System/Windows/Forms/PictureBox.cs | 44 +- .../Windows/Forms/Printing/PageSetupDialog.cs | 2 +- .../PrintControllerWithStatusDialog.cs | 32 +- .../Windows/Forms/Printing/PrintDialog.cs | 2 +- .../Forms/Printing/PrintPreviewDialog.cs | 326 +- .../src/System/Windows/Forms/ProgressBar.cs | 16 +- .../src/System/Windows/Forms/PropertyGrid.cs | 210 +- .../ArrayElementGridEntry.cs | 2 +- .../PropertyGridInternal/CategoryGridEntry.cs | 20 +- .../Forms/PropertyGridInternal/DocComment.cs | 18 +- .../PropertyGridInternal/DropDownButton.cs | 8 +- .../Forms/PropertyGridInternal/GridEntry.cs | 264 +- .../PropertyGridInternal/GridErrorDlg.cs | 262 +- .../Forms/PropertyGridInternal/GridToolTip.cs | 36 +- .../Forms/PropertyGridInternal/HotCommands.cs | 18 +- .../ImmutablePropertyDescriptorGridEntry.cs | 2 +- .../MergePropertyDescriptor.cs | 2 +- .../MultiPropertyDescriptorGridEntry.cs | 10 +- .../MultiSelectRootGridEntry.cs | 4 +- .../PropertyDescriptorGridEntry.cs | 94 +- .../PropertyGridInternal/PropertyGridView.cs | 358 +- .../SingleSelectRootGridEntry.cs | 54 +- .../System/Windows/Forms/PropertyManager.cs | 4 +- .../src/System/Windows/Forms/RadioButton.cs | 4 +- .../Windows/Forms/RelatedCurrencyManager.cs | 8 +- .../Windows/Forms/RelatedPropertyManager.cs | 6 +- .../src/System/Windows/Forms/RichTextBox.cs | 42 +- .../System/Windows/Forms/SaveFileDialog.cs | 2 +- .../src/System/Windows/Forms/Screen.cs | 4 +- .../System/Windows/Forms/ScrollableControl.cs | 22 +- .../System/Windows/Forms/SelectionRange.cs | 4 +- .../System/Windows/Forms/SplitContainer.cs | 136 +- .../src/System/Windows/Forms/Splitter.cs | 2 +- .../src/System/Windows/Forms/StatusBar.cs | 46 +- .../System/Windows/Forms/StatusBarPanel.cs | 80 +- .../src/System/Windows/Forms/StatusStrip.cs | 62 +- .../src/System/Windows/Forms/StringSorter.cs | 4 +- .../src/System/Windows/Forms/StringSource.cs | 2 +- .../src/System/Windows/Forms/TabControl.cs | 48 +- .../src/System/Windows/Forms/TabPage.cs | 14 +- .../System/Windows/Forms/TableLayoutPanel.cs | 10 +- .../Windows/Forms/TableLayoutSettings.cs | 16 +- .../src/System/Windows/Forms/TextBox.cs | 34 +- .../src/System/Windows/Forms/TextBoxBase.cs | 48 +- .../src/System/Windows/Forms/ToolBar.cs | 48 +- .../src/System/Windows/Forms/ToolBarButton.cs | 20 +- .../src/System/Windows/Forms/ToolStrip.cs | 212 +- .../System/Windows/Forms/ToolStripButton.cs | 8 +- .../System/Windows/Forms/ToolStripComboBox.cs | 14 +- .../Windows/Forms/ToolStripContainer.cs | 10 +- .../Windows/Forms/ToolStripContentPanel.cs | 14 +- .../Windows/Forms/ToolStripControlHost.cs | 24 +- .../System/Windows/Forms/ToolStripDropDown.cs | 90 +- .../Windows/Forms/ToolStripDropDownButton.cs | 10 +- .../Windows/Forms/ToolStripDropDownItem.cs | 66 +- .../Windows/Forms/ToolStripDropDownMenu.cs | 126 +- .../src/System/Windows/Forms/ToolStripGrip.cs | 12 +- .../src/System/Windows/Forms/ToolStripItem.cs | 164 +- .../Windows/Forms/ToolStripItemCollection.cs | 16 +- .../System/Windows/Forms/ToolStripLabel.cs | 30 +- .../System/Windows/Forms/ToolStripManager.cs | 6 +- .../System/Windows/Forms/ToolStripMenuItem.cs | 152 +- .../Windows/Forms/ToolStripOverflowButton.cs | 16 +- .../System/Windows/Forms/ToolStripPanel.cs | 86 +- .../Windows/Forms/ToolStripPanelCell.cs | 16 +- .../System/Windows/Forms/ToolStripPanelRow.cs | 38 +- .../Windows/Forms/ToolStripProgressBar.cs | 10 +- .../Forms/ToolStripRendererSwitcher.cs | 8 +- .../Windows/Forms/ToolStripScrollButton.cs | 2 +- .../Windows/Forms/ToolStripSeparator.cs | 12 +- .../System/Windows/Forms/ToolStripSettings.cs | 34 +- .../Windows/Forms/ToolStripSplitButton.cs | 48 +- .../Forms/ToolStripSplitStackLayout.cs | 22 +- .../Windows/Forms/ToolStripStatusLabel.cs | 4 +- .../System/Windows/Forms/ToolStripTextBox.cs | 30 +- .../src/System/Windows/Forms/ToolTip.cs | 118 +- .../src/System/Windows/Forms/TrackBar.cs | 12 +- .../src/System/Windows/Forms/TreeNode.cs | 68 +- .../Windows/Forms/TreeNodeCollection.cs | 4 +- .../src/System/Windows/Forms/TreeView.cs | 40 +- .../Windows/Forms/TreeViewHitTestInfo.cs | 4 +- .../src/System/Windows/Forms/UpDownBase.cs | 68 +- .../Forms/VisualStyles/VisualStyleRenderer.cs | 4 +- .../src/System/Windows/Forms/WebBrowser.cs | 210 +- .../System/Windows/Forms/WebBrowserBase.cs | 268 +- .../Windows/Forms/WebBrowserContainer.cs | 8 +- .../Windows/Forms/WebBrowserSiteBase.cs | 82 +- .../WindowsFormsSynchronizationContext.cs | 2 +- .../src/System/Windows/Forms/control.ime.cs | 12 +- .../src/misc/GDI/DeviceContext.cs | 76 +- .../src/misc/GDI/DeviceContext2.cs | 48 +- .../src/misc/GDI/NativeMethods.cs | 52 +- .../src/misc/GDI/WindowsBrush.cs | 20 +- .../src/misc/GDI/WindowsFont.cs | 102 +- .../src/misc/GDI/WindowsGraphics.cs | 22 +- .../src/misc/GDI/WindowsGraphics2.cs | 82 +- .../src/misc/GDI/WindowsPen.cs | 48 +- .../src/misc/GDI/WindowsRegion.cs | 24 +- .../src/misc/GDI/WindowsSolidBrush.cs | 8 +- .../MenuStripAndCheckedListBox.cs | 4 +- 259 files changed, 15990 insertions(+), 15990 deletions(-) diff --git a/src/Common/src/ClientUtils.cs b/src/Common/src/ClientUtils.cs index a33b81382cd..59b4be1b661 100644 --- a/src/Common/src/ClientUtils.cs +++ b/src/Common/src/ClientUtils.cs @@ -364,11 +364,11 @@ public int RefCheckThreshold { get { - return this.refCheckThreshold; + return refCheckThreshold; } set { - this.refCheckThreshold = value; + refCheckThreshold = value; } } @@ -426,9 +426,9 @@ public override bool Equals(object obj) for (int i = 0; i < Count; i++) { - if (this.InnerList[i] != other.InnerList[i]) + if (InnerList[i] != other.InnerList[i]) { - if (this.InnerList[i] == null || !this.InnerList[i].Equals(other.InnerList[i])) + if (InnerList[i] == null || !InnerList[i].Equals(other.InnerList[i])) { return false; } @@ -491,11 +491,11 @@ public void RemoveByHashCode(object value) int hash = value.GetHashCode(); - for (int idx = 0; idx < this.InnerList.Count; idx++) + for (int idx = 0; idx < InnerList.Count; idx++) { - if (this.InnerList[idx] != null && this.InnerList[idx].GetHashCode() == hash) + if (InnerList[idx] != null && InnerList[idx].GetHashCode() == hash) { - this.RemoveAt(idx); + RemoveAt(idx); return; } } @@ -511,7 +511,7 @@ public void RemoveByHashCode(object value) public void Insert(int index, object value) { InnerList.Insert(index, CreateWeakRefObject(value)); } public int Add(object value) { - if (this.Count > RefCheckThreshold) + if (Count > RefCheckThreshold) { ScavengeReferences(); } @@ -585,9 +585,9 @@ public override bool Equals(object obj) return false; } - if (other.Target != this.Target) + if (other.Target != Target) { - if (this.Target == null || !this.Target.Equals(other.Target)) + if (Target == null || !Target.Equals(other.Target)) { return false; } diff --git a/src/Common/src/NativeMethods.cs b/src/Common/src/NativeMethods.cs index ac72b8afa13..122ee1b2f9e 100644 --- a/src/Common/src/NativeMethods.cs +++ b/src/Common/src/NativeMethods.cs @@ -2380,10 +2380,10 @@ public RECT(int left, int top, int right, int bottom) public RECT(System.Drawing.Rectangle r) { - this.left = r.Left; - this.top = r.Top; - this.right = r.Right; - this.bottom = r.Bottom; + left = r.Left; + top = r.Top; + right = r.Right; + bottom = r.Bottom; } public static RECT FromXYWH(int x, int y, int width, int height) @@ -2395,7 +2395,7 @@ public System.Drawing.Size Size { get { - return new System.Drawing.Size(this.right - this.left, this.bottom - this.top); + return new System.Drawing.Size(right - left, bottom - top); } } } @@ -2933,20 +2933,20 @@ public LOGFONT(LOGFONT lf) { Debug.Assert(lf != null, "lf is null"); - this.lfHeight = lf.lfHeight; - this.lfWidth = lf.lfWidth; - this.lfEscapement = lf.lfEscapement; - this.lfOrientation = lf.lfOrientation; - this.lfWeight = lf.lfWeight; - this.lfItalic = lf.lfItalic; - this.lfUnderline = lf.lfUnderline; - this.lfStrikeOut = lf.lfStrikeOut; - this.lfCharSet = lf.lfCharSet; - this.lfOutPrecision = lf.lfOutPrecision; - this.lfClipPrecision = lf.lfClipPrecision; - this.lfQuality = lf.lfQuality; - this.lfPitchAndFamily = lf.lfPitchAndFamily; - this.lfFaceName = lf.lfFaceName; + lfHeight = lf.lfHeight; + lfWidth = lf.lfWidth; + lfEscapement = lf.lfEscapement; + lfOrientation = lf.lfOrientation; + lfWeight = lf.lfWeight; + lfItalic = lf.lfItalic; + lfUnderline = lf.lfUnderline; + lfStrikeOut = lf.lfStrikeOut; + lfCharSet = lf.lfCharSet; + lfOutPrecision = lf.lfOutPrecision; + lfClipPrecision = lf.lfClipPrecision; + lfQuality = lf.lfQuality; + lfPitchAndFamily = lf.lfPitchAndFamily; + lfFaceName = lf.lfFaceName; } public int lfHeight; public int lfWidth; @@ -3275,10 +3275,10 @@ public COMRECT() public COMRECT(System.Drawing.Rectangle r) { - this.left = r.X; - this.top = r.Y; - this.right = r.Right; - this.bottom = r.Bottom; + left = r.X; + top = r.Y; + right = r.Right; + bottom = r.Bottom; } public COMRECT(int left, int top, int right, int bottom) @@ -3515,18 +3515,18 @@ public bool Byref public void Clear() { - if ((this.vt == (int)tagVT.VT_UNKNOWN || this.vt == (int)tagVT.VT_DISPATCH) && this.data1 != IntPtr.Zero) + if ((vt == (int)tagVT.VT_UNKNOWN || vt == (int)tagVT.VT_DISPATCH) && data1 != IntPtr.Zero) { - Marshal.Release(this.data1); + Marshal.Release(data1); } - if (this.vt == (int)tagVT.VT_BSTR && this.data1 != IntPtr.Zero) + if (vt == (int)tagVT.VT_BSTR && data1 != IntPtr.Zero) { - SysFreeString(this.data1); + SysFreeString(data1); } - this.data1 = this.data2 = IntPtr.Zero; - this.vt = (int)tagVT.VT_EMPTY; + data1 = data2 = IntPtr.Zero; + vt = (int)tagVT.VT_EMPTY; } ~VARIANT() @@ -3553,7 +3553,7 @@ public object ToObject() IntPtr val = data1; long longVal; - int vtType = (int)(this.vt & (short)tagVT.VT_TYPEMASK); + int vtType = (int)(vt & (short)tagVT.VT_TYPEMASK); switch (vtType) { @@ -3704,7 +3704,7 @@ public object ToObject() case (int)tagVT.VT_VECTOR: case (int)tagVT.VT_BYREF: default: - int iVt = this.vt; + int iVt = vt; throw new ArgumentException(string.Format(SR.COM2UnhandledVT, iVt.ToString(CultureInfo.InvariantCulture))); } } @@ -5353,16 +5353,16 @@ public struct tagTYPEATTR public tagTYPEDESC Get_tdescAlias() { tagTYPEDESC td; - td.unionMember = (IntPtr)this.tdescAlias_unionMember; - td.vt = this.tdescAlias_vt; + td.unionMember = (IntPtr)tdescAlias_unionMember; + td.vt = tdescAlias_vt; return td; } public tagIDLDESC Get_idldescType() { tagIDLDESC id = new tagIDLDESC(); - id.dwReserved = this.idldescType_dwReserved; - id.wIDLFlags = this.idldescType_wIDLFlags; + id.dwReserved = idldescType_dwReserved; + id.wIDLFlags = idldescType_wIDLFlags; return id; } } @@ -5536,10 +5536,10 @@ public struct UiaRect public UiaRect(System.Drawing.Rectangle r) { - this.left = r.Left; - this.top = r.Top; - this.width = r.Width; - this.height = r.Height; + left = r.Left; + top = r.Top; + width = r.Width; + height = r.Height; } } diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/ColorEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/ColorEditor.cs index 5c756dee86e..c0786e57d2c 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/ColorEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/ColorEditor.cs @@ -164,7 +164,7 @@ public ColorPalette(ColorUI colorUI, Color[] customColors) for (int i = 0; i < staticCells.Length; i++) staticColors[i] = ColorTranslator.FromOle(staticCells[i]); - this.CustomColors = customColors; + CustomColors = customColors; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] @@ -806,27 +806,27 @@ private void InitializeComponent() tabControl.TabPages.Add(systemTabPage); tabControl.TabStop = false; tabControl.SelectedTab = systemTabPage; - tabControl.SelectedIndexChanged += new EventHandler(this.OnTabControlSelChange); + tabControl.SelectedIndexChanged += new EventHandler(OnTabControlSelChange); tabControl.Dock = DockStyle.Fill; - tabControl.Resize += new EventHandler(this.OnTabControlResize); + tabControl.Resize += new EventHandler(OnTabControlResize); lbSystem = new ColorEditorListBox(); lbSystem.DrawMode = DrawMode.OwnerDrawFixed; lbSystem.BorderStyle = BorderStyle.FixedSingle; lbSystem.IntegralHeight = false; lbSystem.Sorted = false; - lbSystem.Click += new EventHandler(this.OnListClick); + lbSystem.Click += new EventHandler(OnListClick); lbSystem.DrawItem += new DrawItemEventHandler(this.OnListDrawItem); lbSystem.KeyDown += new KeyEventHandler(this.OnListKeyDown); lbSystem.Dock = DockStyle.Fill; - lbSystem.FontChanged += new EventHandler(this.OnFontChanged); + lbSystem.FontChanged += new EventHandler(OnFontChanged); lbCommon = new ColorEditorListBox(); lbCommon.DrawMode = DrawMode.OwnerDrawFixed; lbCommon.BorderStyle = BorderStyle.FixedSingle; lbCommon.IntegralHeight = false; lbCommon.Sorted = false; - lbCommon.Click += new EventHandler(this.OnListClick); + lbCommon.Click += new EventHandler(OnListClick); lbCommon.DrawItem += new DrawItemEventHandler(this.OnListDrawItem); lbCommon.KeyDown += new KeyEventHandler(this.OnListKeyDown); lbCommon.Dock = DockStyle.Fill; @@ -846,7 +846,7 @@ private void InitializeComponent() } pal = new ColorPalette(this, CustomColors); - pal.Picked += new EventHandler(this.OnPalettePick); + pal.Picked += new EventHandler(OnPalettePick); paletteTabPage.Controls.Add(pal); systemTabPage.Controls.Add(lbSystem); diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignSurface.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignSurface.cs index d0da981011f..85af854f6de 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignSurface.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignSurface.cs @@ -78,7 +78,7 @@ public IContainer ComponentContainer { if (_host == null) { - throw new ObjectDisposedException(this.GetType().FullName); + throw new ObjectDisposedException(GetType().FullName); } return ((IDesignerHost)_host).Container; } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs index c1ee0dcfe3f..163c02ad571 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs @@ -610,8 +610,8 @@ private class AdornerWindow : Control [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] internal AdornerWindow(BehaviorService behaviorService, Control designerFrame) { - this._behaviorService = behaviorService; - this._designerFrame = designerFrame; + _behaviorService = behaviorService; + _designerFrame = designerFrame; Dock = DockStyle.Fill; AllowDrop = true; Text = "AdornerWindow"; diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripActionList.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripActionList.cs index ab52e75b0c9..092a034e179 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripActionList.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripActionList.cs @@ -21,7 +21,7 @@ internal class ToolStripActionList : DesignerActionList public ToolStripActionList(ToolStripDesigner designer) : base(designer.Component) { _toolStrip = (ToolStrip)designer.Component; - this._designer = designer; + _designer = designer; _changeParentVerb = new ChangeToolStripParentVerb(string.Format(SR.ToolStripDesignerEmbedVerb), designer); if (!(_toolStrip is StatusStrip)) diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDropDownDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDropDownDesigner.cs index c340dd338d3..b23ef21da3b 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDropDownDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDropDownDesigner.cs @@ -62,7 +62,7 @@ public override DesignerActionListCollection ActionLists actionLists.Add(cmActionList); } // finally add the verbs for this component there... - DesignerVerbCollection cmVerbs = this.Verbs; + DesignerVerbCollection cmVerbs = Verbs; if (cmVerbs != null && cmVerbs.Count != 0) { DesignerVerb[] cmverbsArray = new DesignerVerb[cmVerbs.Count]; @@ -240,8 +240,8 @@ protected override void Dispose(bool disposing) // Unhook our services if (selSvc != null) { - selSvc.SelectionChanged -= new EventHandler(this.OnSelectionChanged); - selSvc.SelectionChanging -= new EventHandler(this.OnSelectionChanging); + selSvc.SelectionChanged -= new EventHandler(OnSelectionChanged); + selSvc.SelectionChanging -= new EventHandler(OnSelectionChanging); } DisposeMenu(); @@ -256,7 +256,7 @@ protected override void Dispose(bool disposing) } if (undoEngine != null) { - undoEngine.Undone -= new EventHandler(this.OnUndone); + undoEngine.Undone -= new EventHandler(OnUndone); } } base.Dispose(disposing); diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs index 9506423e650..dc039bdd236 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs @@ -123,7 +123,7 @@ private void PopulateList() //Add event Handlers imageToolStripMenuItem.Click += new EventHandler(OnImageToolStripMenuItemClick); enabledToolStripMenuItem = CreateBooleanItem("E&nabled", "Enabled"); - this.AddRange(new ToolStripItem[] { imageToolStripMenuItem, enabledToolStripMenuItem }); + AddRange(new ToolStripItem[] { imageToolStripMenuItem, enabledToolStripMenuItem }); if (selectedItem is ToolStripMenuItem) { checkedToolStripMenuItem = CreateBooleanItem("C&hecked", "Checked"); diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemDesigner.cs index 8f1d07149e6..ccc4eff043c 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemDesigner.cs @@ -667,14 +667,14 @@ public override void Initialize(IComponent component) IComponentChangeService cs = (IComponentChangeService)GetService(typeof(IComponentChangeService)); if (cs != null) { - cs.ComponentRename += new ComponentRenameEventHandler(this.OnComponentRename); + cs.ComponentRename += new ComponentRenameEventHandler(OnComponentRename); } //hook our SelectionService. selSvc = (ISelectionService)GetService(typeof(ISelectionService)); if (selSvc != null) { - selSvc.SelectionChanged += new EventHandler(this.OnSelectionChanged); + selSvc.SelectionChanged += new EventHandler(OnSelectionChanged); } } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs index 7546d2f86de..1a3de93ccae 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs @@ -281,7 +281,7 @@ private bool MenuItemSelected } } else if (selectedItem is ContextMenuStrip && - ((ContextMenuStrip)selectedItem).OwnerItem == this.Component && // VSO 214130--SelectedItem must belong to this designer + ((ContextMenuStrip)selectedItem).OwnerItem == Component && // VSO 214130--SelectedItem must belong to this designer MenuItem.DropDown == selectedItem) { return true; @@ -968,12 +968,12 @@ protected override void Dispose(bool disposing) //clean up if (selSvc != null) { - selSvc.SelectionChanged -= new EventHandler(this.OnSelectionChanged); + selSvc.SelectionChanged -= new EventHandler(OnSelectionChanged); } if (undoEngine != null) { - undoEngine.Undoing -= new EventHandler(this.OnUndoing); - undoEngine.Undone -= new EventHandler(this.OnUndone); + undoEngine.Undoing -= new EventHandler(OnUndoing); + undoEngine.Undone -= new EventHandler(OnUndone); } if (MenuItem != null && MenuItem.HasDropDown) { @@ -1475,11 +1475,11 @@ internal void HookEvents() MenuItem.DropDownOpening += new EventHandler(DropDownItem_DropDownOpening); MenuItem.DropDownOpened += new EventHandler(DropDownItem_DropDownOpened); MenuItem.DropDownClosed += new EventHandler(DropDownItem_DropDownClosed); - MenuItem.DropDown.Resize += new System.EventHandler(this.DropDownResize); + MenuItem.DropDown.Resize += new System.EventHandler(DropDownResize); MenuItem.DropDown.ItemAdded += new ToolStripItemEventHandler(OnItemAdded); MenuItem.DropDown.Paint += new PaintEventHandler(this.DropDownPaint); - MenuItem.DropDown.Click += new EventHandler(this.DropDownClick); - MenuItem.DropDown.LocationChanged += new EventHandler(this.DropDownLocationChanged); + MenuItem.DropDown.Click += new EventHandler(DropDownClick); + MenuItem.DropDown.LocationChanged += new EventHandler(DropDownLocationChanged); } } @@ -1496,7 +1496,7 @@ public override void Initialize(IComponent component) selSvc = (ISelectionService)GetService(typeof(ISelectionService)); if (selSvc != null) { - selSvc.SelectionChanged += new EventHandler(this.OnSelectionChanged); + selSvc.SelectionChanged += new EventHandler(OnSelectionChanged); } //hookup to the AdornerService.. @@ -1510,8 +1510,8 @@ public override void Initialize(IComponent component) undoEngine = GetService(typeof(UndoEngine)) as UndoEngine; if (undoEngine != null) { - undoEngine.Undoing += new EventHandler(this.OnUndoing); - undoEngine.Undone += new EventHandler(this.OnUndone); + undoEngine.Undoing += new EventHandler(OnUndoing); + undoEngine.Undone += new EventHandler(OnUndone); } } } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripTemplateNode.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripTemplateNode.cs index d222587faf4..245cde7ac6b 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripTemplateNode.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripTemplateNode.cs @@ -1437,7 +1437,7 @@ private void SetupNewEditNode(ToolStripTemplateNode owner, string text, Image im if (currentItem is ToolStripDropDownItem stripItem) { _miniToolStrip.RightToLeft = stripItem.RightToLeft; - stripItem.RightToLeftChanged += new System.EventHandler(this.OnRightToLeftChanged); + stripItem.RightToLeftChanged += new System.EventHandler(OnRightToLeftChanged); } _miniToolStrip.SuspendLayout(); _miniToolStrip.CanOverflow = false; @@ -1643,7 +1643,7 @@ public override Size GetPreferredSize(Size proposedSize) private bool ProcessTabKey(bool forward) { // Give the ToolStripItem first dibs - ToolStripItem item = this.GetSelectedItem(); + ToolStripItem item = GetSelectedItem(); if (item is ToolStripControlHost) { diff --git a/src/System.Windows.Forms/src/SRDescriptionAttribute.cs b/src/System.Windows.Forms/src/SRDescriptionAttribute.cs index 092005caa6d..745b0950b59 100644 --- a/src/System.Windows.Forms/src/SRDescriptionAttribute.cs +++ b/src/System.Windows.Forms/src/SRDescriptionAttribute.cs @@ -16,9 +16,9 @@ public override string Description { get { - if (!this.replaced) + if (!replaced) { - this.replaced = true; + replaced = true; base.DescriptionValue = SR.GetResourceString(base.Description); } return base.Description; diff --git a/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs b/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs index c381e96caff..f930c67f4d4 100644 --- a/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs +++ b/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs @@ -75,17 +75,17 @@ internal ResXDataNode DeepClone() return new ResXDataNode { // nodeinfo is just made up of immutable objects, we don't need to clone it - nodeInfo = this.nodeInfo?.Clone(), - name = this.name, - comment = this.comment, - typeName = this.typeName, - fileRefFullPath = this.fileRefFullPath, - fileRefType = this.fileRefType, - fileRefTextEncoding = this.fileRefTextEncoding, + nodeInfo = nodeInfo?.Clone(), + name = name, + comment = comment, + typeName = typeName, + fileRefFullPath = fileRefFullPath, + fileRefType = fileRefType, + fileRefTextEncoding = fileRefTextEncoding, // we don't clone the value, because we don't know how - value = this.value, - fileRef = this.fileRef?.Clone(), - typeNameConverter = this.typeNameConverter + value = value, + fileRef = fileRef?.Clone(), + typeNameConverter = typeNameConverter }; } @@ -121,7 +121,7 @@ public ResXDataNode(string name, object value, Func typeNameConver } if (value != null) { - this.typeName = MultitargetUtil.GetAssemblyQualifiedName(valueType, this.typeNameConverter); + typeName = MultitargetUtil.GetAssemblyQualifiedName(valueType, this.typeNameConverter); } this.name = name; @@ -325,7 +325,7 @@ private void FillDataNodeInfoFromObject(DataNodeInfo nodeInfo, object value) if (value is CultureInfo ci) { // special-case CultureInfo, cannot use CultureInfoConverter for serialization nodeInfo.ValueData = ci.Name; - nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(typeof(CultureInfo), this.typeNameConverter); + nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(typeof(CultureInfo), typeNameConverter); } else if (value is string str) { @@ -334,7 +334,7 @@ private void FillDataNodeInfoFromObject(DataNodeInfo nodeInfo, object value) else if (value is byte[] bytes) { nodeInfo.ValueData = ToBase64WrappedString(bytes); - nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(typeof(byte[]), this.typeNameConverter); + nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(typeof(byte[]), typeNameConverter); } else { @@ -351,7 +351,7 @@ private void FillDataNodeInfoFromObject(DataNodeInfo nodeInfo, object value) if (toString && fromString) { nodeInfo.ValueData = tc.ConvertToInvariantString(value); - nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(valueType, this.typeNameConverter); + nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(valueType, typeNameConverter); return; } } @@ -374,14 +374,14 @@ private void FillDataNodeInfoFromObject(DataNodeInfo nodeInfo, object value) byte[] data = (byte[])tc.ConvertTo(value, typeof(byte[])); nodeInfo.ValueData = ToBase64WrappedString(data); nodeInfo.MimeType = ResXResourceWriter.ByteArraySerializedObjectMimeType; - nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(valueType, this.typeNameConverter); + nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(valueType, typeNameConverter); return; } if (value == null) { nodeInfo.ValueData = string.Empty; - nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXNullRef), this.typeNameConverter); + nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXNullRef), typeNameConverter); } else { @@ -389,7 +389,7 @@ private void FillDataNodeInfoFromObject(DataNodeInfo nodeInfo, object value) { binaryFormatter = new BinaryFormatter { - Binder = new ResXSerializationBinder(this.typeNameConverter) + Binder = new ResXSerializationBinder(typeNameConverter) }; } @@ -412,7 +412,7 @@ private object GenerateObjectFromDataNodeInfo(DataNodeInfo dataNodeInfo, ITypeRe // default behavior: if we dont have a type name, it's a string string typeName = string.IsNullOrEmpty(dataNodeInfo.TypeName) - ? MultitargetUtil.GetAssemblyQualifiedName(typeof(string), this.typeNameConverter) + ? MultitargetUtil.GetAssemblyQualifiedName(typeof(string), typeNameConverter) : dataNodeInfo.TypeName; if (!string.IsNullOrEmpty(mimeTypeName)) @@ -553,7 +553,7 @@ internal DataNodeInfo GetDataNodeInfo() { nodeInfo.ValueData = FileRef.ToString(); nodeInfo.MimeType = null; - nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXFileRef), this.typeNameConverter); + nodeInfo.TypeName = MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXFileRef), typeNameConverter); } else { @@ -584,8 +584,8 @@ public string GetValueTypeName(ITypeResolutionService typeResolver) if (!string.IsNullOrEmpty(typeName)) { return - typeName == MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXNullRef), this.typeNameConverter) - ? MultitargetUtil.GetAssemblyQualifiedName(typeof(object), this.typeNameConverter) + typeName == MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXNullRef), typeNameConverter) + ? MultitargetUtil.GetAssemblyQualifiedName(typeof(object), typeNameConverter) : typeName; } string result = FileRefType; @@ -623,18 +623,18 @@ public string GetValueTypeName(ITypeResolutionService typeResolver) } // something went wrong, type is not specified at all or stream is corrupted // return system.object - result = MultitargetUtil.GetAssemblyQualifiedName(typeof(object), this.typeNameConverter); + result = MultitargetUtil.GetAssemblyQualifiedName(typeof(object), typeNameConverter); } if (insideObject != null) { - result = MultitargetUtil.GetAssemblyQualifiedName(insideObject.GetType(), this.typeNameConverter); + result = MultitargetUtil.GetAssemblyQualifiedName(insideObject.GetType(), typeNameConverter); } } else { // no typename, no mimetype, we have a string... - result = MultitargetUtil.GetAssemblyQualifiedName(typeof(string), this.typeNameConverter); + result = MultitargetUtil.GetAssemblyQualifiedName(typeof(string), typeNameConverter); } } else @@ -646,11 +646,11 @@ public string GetValueTypeName(ITypeResolutionService typeResolver) { if (objectType == typeof(ResXNullRef)) { - result = MultitargetUtil.GetAssemblyQualifiedName(typeof(object), this.typeNameConverter); + result = MultitargetUtil.GetAssemblyQualifiedName(typeof(object), typeNameConverter); } else { - result = MultitargetUtil.GetAssemblyQualifiedName(objectType, this.typeNameConverter); + result = MultitargetUtil.GetAssemblyQualifiedName(objectType, typeNameConverter); } } return result; @@ -796,7 +796,7 @@ void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) private ResXDataNode(SerializationInfo info, StreamingContext context) { - this.nodeInfo = new DataNodeInfo + nodeInfo = new DataNodeInfo { Name = (string)info.GetValue("Name", typeof(string)), Comment = (string)info.GetValue("Comment", typeof(string)), @@ -821,12 +821,12 @@ internal DataNodeInfo Clone() { return new DataNodeInfo { - Name = this.Name, - Comment = this.Comment, - TypeName = this.TypeName, - MimeType = this.MimeType, - ValueData = this.ValueData, - ReaderPosition = new Point(this.ReaderPosition.X, this.ReaderPosition.Y) + Name = Name, + Comment = Comment, + TypeName = TypeName, + MimeType = MimeType, + ValueData = ValueData, + ReaderPosition = new Point(ReaderPosition.X, ReaderPosition.Y) }; } } diff --git a/src/System.Windows.Forms/src/System/Resources/ResXResourceReader.cs b/src/System.Windows.Forms/src/System/Resources/ResXResourceReader.cs index 6ea4244301f..8dd7056cc43 100644 --- a/src/System.Windows.Forms/src/System/Resources/ResXResourceReader.cs +++ b/src/System.Windows.Forms/src/System/Resources/ResXResourceReader.cs @@ -51,13 +51,13 @@ public class ResXResourceReader : IResourceReader private ResXResourceReader(ITypeResolutionService typeResolver) { this.typeResolver = typeResolver; - this.aliasResolver = new ReaderAliasResolver(); + aliasResolver = new ReaderAliasResolver(); } private ResXResourceReader(AssemblyName[] assemblyNames) { this.assemblyNames = assemblyNames; - this.aliasResolver = new ReaderAliasResolver(); + aliasResolver = new ReaderAliasResolver(); } @@ -167,7 +167,7 @@ public bool UseResXDataNodes { get { - return this.useResXDataNodes; + return useResXDataNodes; } set { @@ -175,7 +175,7 @@ public bool UseResXDataNodes { throw new InvalidOperationException(SR.InvalidResXBasePathOperation); } - this.useResXDataNodes = value; + useResXDataNodes = value; } } @@ -716,7 +716,7 @@ private sealed class ReaderAliasResolver : IAliasResolver internal ReaderAliasResolver() { - this.cachedAliases = new Hashtable(); + cachedAliases = new Hashtable(); } public AssemblyName ResolveAlias(string alias) @@ -732,7 +732,7 @@ public AssemblyName ResolveAlias(string alias) public void PushAlias(string alias, AssemblyName name) { - if (this.cachedAliases != null && !string.IsNullOrEmpty(alias)) + if (cachedAliases != null && !string.IsNullOrEmpty(alias)) { cachedAliases[alias] = name; } diff --git a/src/System.Windows.Forms/src/System/Resources/ResXResourceWriter.cs b/src/System.Windows.Forms/src/System/Resources/ResXResourceWriter.cs index 35271c029dd..3e0855707a6 100644 --- a/src/System.Windows.Forms/src/System/Resources/ResXResourceWriter.cs +++ b/src/System.Windows.Forms/src/System/Resources/ResXResourceWriter.cs @@ -240,7 +240,7 @@ private void InitializeWriter() xmlTextWriter.WriteAttributeString(NameStr, ReaderStr); xmlTextWriter.WriteStartElement(ValueStr); { - xmlTextWriter.WriteString(MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXResourceReader), this.typeNameConverter)); + xmlTextWriter.WriteString(MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXResourceReader), typeNameConverter)); } xmlTextWriter.WriteEndElement(); } @@ -250,7 +250,7 @@ private void InitializeWriter() xmlTextWriter.WriteAttributeString(NameStr, WriterStr); xmlTextWriter.WriteStartElement(ValueStr); { - xmlTextWriter.WriteString(MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXResourceWriter), this.typeNameConverter)); + xmlTextWriter.WriteString(MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXResourceWriter), typeNameConverter)); } xmlTextWriter.WriteEndElement(); } @@ -405,14 +405,14 @@ private void AddDataRow(string elementName, string name, object value) break; case ResXFileRef fileRef: { - ResXDataNode node = new ResXDataNode(name, fileRef, this.typeNameConverter); + ResXDataNode node = new ResXDataNode(name, fileRef, typeNameConverter); DataNodeInfo info = node.GetDataNodeInfo(); AddDataRow(elementName, info.Name, info.ValueData, info.TypeName, info.MimeType, info.Comment); break; } default: { - ResXDataNode node = new ResXDataNode(name, value, this.typeNameConverter); + ResXDataNode node = new ResXDataNode(name, value, typeNameConverter); DataNodeInfo info = node.GetDataNodeInfo(); AddDataRow(elementName, info.Name, info.ValueData, info.TypeName, info.MimeType, info.Comment); break; @@ -428,7 +428,7 @@ private void AddDataRow(string elementName, string name, string value) // if it's a null string, set it here as a resxnullref string typeName = value == null - ? MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXNullRef), this.typeNameConverter) + ? MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXNullRef), typeNameConverter) : null; AddDataRow(elementName, name, value, typeName, null, null); } @@ -458,7 +458,7 @@ private void AddDataRow(string elementName, string name, string value, string ty } else if (typeObject != null) { - assemblyName = GetFullName(MultitargetUtil.GetAssemblyQualifiedName(typeObject, this.typeNameConverter)); + assemblyName = GetFullName(MultitargetUtil.GetAssemblyQualifiedName(typeObject, typeNameConverter)); alias = GetAliasFromName(new AssemblyName(assemblyName)); } } @@ -642,7 +642,7 @@ static string ToBase64WrappedString(byte[] data) private string TypeNameWithAssembly(Type type) { - string result = MultitargetUtil.GetAssemblyQualifiedName(type, this.typeNameConverter); + string result = MultitargetUtil.GetAssemblyQualifiedName(type, typeNameConverter); return result; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs index 0fad31aee88..b1291272e03 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs @@ -1978,7 +1978,7 @@ int pvLoopData // PVOID return false; } - UnsafeNativeMethods.IMsoComponent prevActive = this.activeComponent; + UnsafeNativeMethods.IMsoComponent prevActive = activeComponent; try { @@ -1997,7 +1997,7 @@ int pvLoopData // PVOID requestingComponent = entry.component; - this.activeComponent = requestingComponent; + activeComponent = requestingComponent; Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ComponentManager : Pushing message loop " + reason.ToString(CultureInfo.InvariantCulture)); Debug.Indent(); @@ -2151,7 +2151,7 @@ int pvLoopData // PVOID finally { currentState = currentLoopState; - this.activeComponent = prevActive; + activeComponent = prevActive; } return !continueLoop; @@ -4103,9 +4103,9 @@ bool UnsafeNativeMethods.IMsoComponent.FQueryTerminate(bool fPromptUser) /// void UnsafeNativeMethods.IMsoComponent.Terminate() { - if (this.messageLoopCount > 0 && !(ComponentManager is ComponentManager)) + if (messageLoopCount > 0 && !(ComponentManager is ComponentManager)) { - this.messageLoopCount--; + messageLoopCount--; } Dispose(false); @@ -4339,7 +4339,7 @@ internal ThreadWindows(bool onlyWinForms) windows = new IntPtr[16]; this.onlyWinForms = onlyWinForms; UnsafeNativeMethods.EnumThreadWindows(SafeNativeMethods.GetCurrentThreadId(), - new NativeMethods.EnumThreadWindowsCallback(this.Callback), + new NativeMethods.EnumThreadWindowsCallback(Callback), NativeMethods.NullHandleRef); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ApplicationContext.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ApplicationContext.cs index a1d24ab7fd9..dfb35085327 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ApplicationContext.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ApplicationContext.cs @@ -34,7 +34,7 @@ public ApplicationContext() : this(null) /// public ApplicationContext(Form mainForm) { - this.MainForm = mainForm; + MainForm = mainForm; } ~ApplicationContext() diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ArrangedElement.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ArrangedElement.cs index 854fbdb3181..441127aea1c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ArrangedElement.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ArrangedElement.cs @@ -37,8 +37,8 @@ internal abstract class ArrangedElement : Component, IArrangedElement internal ArrangedElement() { - this.Padding = DefaultPadding; - this.Margin = DefaultMargin; + Padding = DefaultPadding; + Margin = DefaultMargin; state[stateVisible] = true; } @@ -74,7 +74,7 @@ public virtual Rectangle DisplayRectangle { get { - Rectangle displayRectangle = this.Bounds; + Rectangle displayRectangle = Bounds; return displayRectangle; } } @@ -134,7 +134,7 @@ PropertyStore IArrangedElement.Properties { get { - return this.Properties; + return Properties; } } @@ -160,7 +160,7 @@ public virtual bool Visible state[stateVisible] = value; if (Parent != null) { - LayoutTransaction.DoLayout(this.Parent, this, PropertyNames.Visible); + LayoutTransaction.DoLayout(Parent, this, PropertyNames.Visible); } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AutoCompleteStringCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AutoCompleteStringCollection.cs index 60ed252ff31..bbb3c358945 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AutoCompleteStringCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AutoCompleteStringCollection.cs @@ -72,15 +72,15 @@ bool IList.IsFixedSize public event CollectionChangeEventHandler CollectionChanged { - add => this.onCollectionChanged += value; - remove => this.onCollectionChanged -= value; + add => onCollectionChanged += value; + remove => onCollectionChanged -= value; } protected void OnCollectionChanged(CollectionChangeEventArgs e) { - if (this.onCollectionChanged != null) + if (onCollectionChanged != null) { - this.onCollectionChanged(this, e); + onCollectionChanged(this, e); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs index 808f08b0674..296da3100c7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs @@ -280,17 +280,17 @@ protected AxHost(string clsid, int flags) : base() throw new ThreadStateException(string.Format(SR.AXMTAThread, clsid)); } - this.oleSite = new OleInterfaces(this); - this.selectionChangeHandler = new EventHandler(this.OnNewSelection); + oleSite = new OleInterfaces(this); + selectionChangeHandler = new EventHandler(OnNewSelection); this.clsid = new Guid(clsid); this.flags = flags; - this.axState[assignUniqueID] = !this.GetType().GUID.Equals(comctlImageCombo_Clsid); - this.axState[needLicenseKey] = true; - this.axState[rejectSelection] = true; + axState[assignUniqueID] = !GetType().GUID.Equals(comctlImageCombo_Clsid); + axState[needLicenseKey] = true; + axState[rejectSelection] = true; isMaskEdit = this.clsid.Equals(AxHost.maskEdit_Clsid); - this.onContainerVisibleChanged = new EventHandler(this.OnContainerVisibleChanged); + onContainerVisibleChanged = new EventHandler(OnContainerVisibleChanged); } private bool CanUIActivate @@ -319,12 +319,12 @@ protected override CreateParams CreateParams private bool GetAxState(int mask) { - return this.axState[mask]; + return axState[mask]; } private void SetAxState(int mask, bool value) { - this.axState[mask] = value; + axState[mask] = value; } /// @@ -581,7 +581,7 @@ public void EndInit() ContainerControl f = ContainingControl; if (f != null) { - f.VisibleChanged += this.onContainerVisibleChanged; + f.VisibleChanged += onContainerVisibleChanged; } } } @@ -1062,7 +1062,7 @@ private void OnComponentRename(object sender, ComponentRenameEventArgs e) // if it is, call DISPID_AMBIENT_DISPLAYNAME directly on the // control itself. // - UnsafeNativeMethods.IOleControl oleCtl = this.GetOcx() as UnsafeNativeMethods.IOleControl; + UnsafeNativeMethods.IOleControl oleCtl = GetOcx() as UnsafeNativeMethods.IOleControl; if (oleCtl != null) { oleCtl.OnAmbientPropertyChange(NativeMethods.ActiveX.DISPID_AMBIENT_DISPLAYNAME); @@ -1231,7 +1231,7 @@ private void OnNewSelection(object sender, EventArgs e) if (prop != null && prop.PropertyType == typeof(int)) { int curSelectionStyle = (int)prop.GetValue(this); - if (curSelectionStyle != this.selectionStyle) + if (curSelectionStyle != selectionStyle) { prop.SetValue(this, selectionStyle); } @@ -1505,9 +1505,9 @@ private bool CheckSubclassing() Debug.WriteLineIf(AxHostSwitch.TraceVerbose, "The horrible control subclassed itself w/o calling the old wndproc..."); // we need to resubclass outselves now... Debug.Assert(!OwnWindow(), "why are we here if we own our window?"); - this.WindowReleaseHandle(); + WindowReleaseHandle(); UnsafeNativeMethods.SetWindowLong(new HandleRef(this, handle), NativeMethods.GWL_WNDPROC, new HandleRef(this, currentWndproc)); - this.WindowAssignHandle(handle, axState[assignUniqueID]); + WindowAssignHandle(handle, axState[assignUniqueID]); InformOfNewHandle(); axState[manualUpdate] = true; return false; @@ -1751,7 +1751,7 @@ private void InPlaceDeactivate() private void UiActivate() { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "calling uiActivate for " + this.ToString()); + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "calling uiActivate for " + ToString()); Debug.Assert(GetOcState() >= OC_INPLACE, "we have to be in place in order to ui activate..."); Debug.Assert(CanUIActivate, "we have to be able to uiactivate"); if (CanUIActivate) @@ -2132,23 +2132,23 @@ public State OcxState throw new InvalidOperationException(SR.AXOcxStateLoaded); } - if (this.ocxState == value) + if (ocxState == value) return; - this.ocxState = value; + ocxState = value; - if (this.ocxState != null) + if (ocxState != null) { - this.axState[manualUpdate] = ocxState._GetManualUpdate(); - this.licenseKey = ocxState._GetLicenseKey(); + axState[manualUpdate] = ocxState._GetManualUpdate(); + licenseKey = ocxState._GetLicenseKey(); } else { - this.axState[manualUpdate] = false; - this.licenseKey = null; + axState[manualUpdate] = false; + licenseKey = null; } - if (this.ocxState != null && GetOcState() >= OC_RUNNING) + if (ocxState != null && GetOcState() >= OC_RUNNING) { DepersistControl(); } @@ -2493,9 +2493,9 @@ private void Freeze(bool v) private int UiDeactivate() { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "calling uiDeactivate for " + this.ToString()); - bool ownDispose = this.axState[ownDisposing]; - this.axState[ownDisposing] = true; + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "calling uiDeactivate for " + ToString()); + bool ownDispose = axState[ownDisposing]; + axState[ownDisposing] = true; int hr = 0; try { @@ -2503,7 +2503,7 @@ private int UiDeactivate() } finally { - this.axState[ownDisposing] = ownDispose; + axState[ownDisposing] = ownDispose; } return hr; } @@ -2521,7 +2521,7 @@ private void SetOcState(int nv) private string GetLicenseKey() { - return GetLicenseKey(this.clsid); + return GetLicenseKey(clsid); } private string GetLicenseKey(Guid clsid) @@ -2604,7 +2604,7 @@ private void CreateInstance() //checkThreadingModel(); try { - instance = CreateInstanceCore(this.clsid); + instance = CreateInstanceCore(clsid); Debug.Assert(instance != null, "w/o an exception being thrown we must have an object..."); } catch (ExternalException e) @@ -2688,7 +2688,7 @@ private CategoryAttribute GetCategoryForDispid(int dispid) private void SetSelectionStyle(int selectionStyle) { - if (!this.IsUserMode()) + if (!IsUserMode()) { // selectionStyle can be 0 (not selected), 1 (selected) or 2 (active) Debug.Assert(selectionStyle >= 0 && selectionStyle <= 2, "Invalid selection style"); @@ -2711,7 +2711,7 @@ private void SetSelectionStyle(int selectionStyle) [EditorBrowsable(EditorBrowsableState.Advanced)] public void InvokeEditMode() { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "invoking EditMode for " + this.ToString()); + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "invoking EditMode for " + ToString()); Debug.Assert((flags & AxFlags.PreventEditMode) == 0, "edit mode should have been disabled"); if (editMode != EDITM_NONE) return; @@ -2749,7 +2749,7 @@ AttributeCollection ICustomTypeDescriptor.GetAttributes() if (!axState[editorRefresh] && HasPropertyPages()) { axState[editorRefresh] = true; - TypeDescriptor.Refresh(this.GetType()); + TypeDescriptor.Refresh(GetType()); } return TypeDescriptor.GetAttributes(this, true); } @@ -2829,7 +2829,7 @@ private void OnIdle(object sender, EventArgs e) { if (axState[refreshProperties]) { - TypeDescriptor.Refresh(this.GetType()); + TypeDescriptor.Refresh(GetType()); } } @@ -2844,12 +2844,12 @@ private bool RefreshAllProperties axState[refreshProperties] = value; if (value && !axState[listeningToIdle]) { - Application.Idle += new EventHandler(this.OnIdle); + Application.Idle += new EventHandler(OnIdle); axState[listeningToIdle] = true; } else if (!value && axState[listeningToIdle]) { - Application.Idle -= new EventHandler(this.OnIdle); + Application.Idle -= new EventHandler(OnIdle); axState[listeningToIdle] = false; } } @@ -2900,7 +2900,7 @@ private PropertyDescriptorCollection FillProperties(Attribute[] attributes) { propertyInfos = new Hashtable(); - PropertyInfo[] propInfos = this.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance); + PropertyInfo[] propInfos = GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo propInfo in propInfos) propertyInfos.Add(propInfo.Name, propInfo); @@ -3669,7 +3669,7 @@ private void DetachWindow() } */ } - this.WindowReleaseHandle(); + WindowReleaseHandle(); } } @@ -3693,10 +3693,10 @@ private void InformOfNewHandle() private void AttachWindow(IntPtr hwnd) { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "attaching window for " + this.ToString() + " " + hwnd.ToString()); + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "attaching window for " + ToString() + " " + hwnd.ToString()); if (!axState[fFakingWindow]) { - this.WindowAssignHandle(hwnd, axState[assignUniqueID]); + WindowAssignHandle(hwnd, axState[assignUniqueID]); } UpdateZOrder(); @@ -4566,7 +4566,7 @@ void UnsafeNativeMethods.IPropertyNotifySink.OnChanged(int dispid) prop = host.GetPropertyDescriptorFromDispid(dispid); if (prop != null) { - prop.OnValueChanged(this.host); + prop.OnValueChanged(host); if (!prop.SettingValue) { prop.UpdateTypeConverterAndTypeEditor(true); @@ -4788,12 +4788,12 @@ private void ReleaseAxControl() // (oh, yes, and the crashes seemed to disappear...) //cpr: ComLib.Release(instance); - this.NoComponentChangeEvents++; + NoComponentChangeEvents++; ContainerControl f = ContainingControl; if (f != null) { - f.VisibleChanged -= this.onContainerVisibleChanged; + f.VisibleChanged -= onContainerVisibleChanged; } try @@ -4826,7 +4826,7 @@ private void ReleaseAxControl() } finally { - this.NoComponentChangeEvents--; + NoComponentChangeEvents--; } } @@ -5712,7 +5712,7 @@ internal void AddControl(Control ctl) IComponentChangeService ccs = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); if (ccs != null) { - ccs.ComponentRemoved += new ComponentEventHandler(this.OnComponentRemoved); + ccs.ComponentRemoved += new ComponentEventHandler(OnComponentRemoved); } } } @@ -5934,7 +5934,7 @@ private void FillComponentsTable(IContainer container) } } - GetAllChildren(this.parent); + GetAllChildren(parent); } private void GetAllChildren(Control ctl) @@ -5947,7 +5947,7 @@ private void GetAllChildren(Control ctl) components = new Hashtable(); } - if (ctl != this.parent && !components.Contains(ctl)) + if (ctl != parent && !components.Contains(ctl)) components.Add(ctl, ctl); foreach (Control c in ctl.Controls) @@ -6010,7 +6010,7 @@ private bool RegisterControl(AxHost ctl) IComponentChangeService ccs = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); if (ccs != null) { - ccs.ComponentRemoved += new ComponentEventHandler(this.OnComponentRemoved); + ccs.ComponentRemoved += new ComponentEventHandler(OnComponentRemoved); } return true; } @@ -6747,7 +6747,7 @@ MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr) MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr) { - return new MethodInfo[] { this.GetType().GetMethod("Move") }; + return new MethodInfo[] { GetType().GetMethod("Move") }; } FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr) @@ -6765,7 +6765,7 @@ PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr) PropertyInfo prop = GetP().GetType().GetProperty(name, bindingAttr); if (prop == null) { - prop = this.GetType().GetProperty(name, bindingAttr); + prop = GetType().GetProperty(name, bindingAttr); } return prop; } @@ -6775,14 +6775,14 @@ PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder PropertyInfo prop = GetP().GetType().GetProperty(name, bindingAttr, binder, returnType, types, modifiers); if (prop == null) { - prop = this.GetType().GetProperty(name, bindingAttr, binder, returnType, types, modifiers); + prop = GetType().GetProperty(name, bindingAttr, binder, returnType, types, modifiers); } return prop; } PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr) { - PropertyInfo[] extenderProps = this.GetType().GetProperties(bindingAttr); + PropertyInfo[] extenderProps = GetType().GetProperties(bindingAttr); PropertyInfo[] ctlProps = GetP().GetType().GetProperties(bindingAttr); if (extenderProps == null) @@ -6817,14 +6817,14 @@ MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr) MemberInfo[] memb = GetP().GetType().GetMember(name, bindingAttr); if (memb == null) { - memb = this.GetType().GetMember(name, bindingAttr); + memb = GetType().GetMember(name, bindingAttr); } return memb; } MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr) { - MemberInfo[] extenderMembs = this.GetType().GetMembers(bindingAttr); + MemberInfo[] extenderMembs = GetType().GetMembers(bindingAttr); MemberInfo[] ctlMembs = GetP().GetType().GetMembers(bindingAttr); if (extenderMembs == null) @@ -6851,11 +6851,11 @@ object IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder binder { try { - return this.GetType().InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters); + return GetType().InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters); } catch (MissingMethodException) { - return this.GetP().GetType().InvokeMember(name, invokeAttr, binder, GetP(), args, modifiers, culture, namedParameters); + return GetP().GetType().InvokeMember(name, invokeAttr, binder, GetP(), args, modifiers, culture, namedParameters); } } @@ -6984,8 +6984,8 @@ internal State(MemoryStream ms, int storageType, AxHost ctl, PropertyBagStream p // dangerous? length = (int)ms.Length; this.ms = ms; - this.manualUpdate = ctl.GetAxState(AxHost.manualUpdate); - this.licenseKey = ctl.GetLicenseKey(); + manualUpdate = ctl.GetAxState(AxHost.manualUpdate); + licenseKey = ctl.GetLicenseKey(); } internal State(PropertyBagStream propBag) @@ -6996,7 +6996,7 @@ internal State(PropertyBagStream propBag) internal State(MemoryStream ms) { this.ms = ms; - this.length = (int)ms.Length; + length = (int)ms.Length; InitializeFromStream(ms); } @@ -7015,7 +7015,7 @@ public State(Stream ms, int storageType, bool manualUpdate, string licKey) // dangerous? length = (int)ms.Length; this.manualUpdate = manualUpdate; - this.licenseKey = licKey; + licenseKey = licKey; InitializeBufferFromStream(ms); } @@ -7056,7 +7056,7 @@ protected State(SerializationInfo info, StreamingContext context) byte[] dat = (byte[])sie.Value; if (dat != null) { - this.propBag = new PropertyBagStream(); + propBag = new PropertyBagStream(); propBag.Read(new MemoryStream(dat)); } @@ -7424,13 +7424,13 @@ internal AxPropertyDescriptor(PropertyDescriptor baseProp, AxHost owner) : base( // Look to see if this property has a property page. // If it does, then it needs to be Browsable(true). // - if (!this.IsBrowsable && !this.IsReadOnly) + if (!IsBrowsable && !IsReadOnly) { Guid g = GetPropertyPage(dispid.Value); if (!Guid.Empty.Equals(g)) { - Debug.WriteLineIf(AxPropTraceSwitch.TraceVerbose, "Making property: " + this.Name + " browsable because we found an property page."); + Debug.WriteLineIf(AxPropTraceSwitch.TraceVerbose, "Making property: " + Name + " browsable because we found an property page."); AddAttribute(new BrowsableAttribute(true)); } } @@ -7446,7 +7446,7 @@ internal AxPropertyDescriptor(PropertyDescriptor baseProp, AxHost owner) : base( // Check to see if this a DataSource property. // If it is, we can always get and set the value of this property. // - if (this.PropertyType.GUID.Equals(dataSource_Guid)) + if (PropertyType.GUID.Equals(dataSource_Guid)) { SetFlag(FlagIgnoreCanAccessProperties, true); } @@ -7598,7 +7598,7 @@ public override object GetValue(object component) public void OnValueChanged(object component) { - this.OnValueChanged(component, EventArgs.Empty); + OnValueChanged(component, EventArgs.Empty); } public override void ResetValue(object o) @@ -7630,9 +7630,9 @@ public override void SetValue(object component, object value) try { SetFlag(FlagSettingValue, true); - if (this.PropertyType.IsEnum && (value.GetType() != this.PropertyType)) + if (PropertyType.IsEnum && (value.GetType() != PropertyType)) { - baseProp.SetValue(component, Enum.ToObject(this.PropertyType, value)); + baseProp.SetValue(component, Enum.ToObject(PropertyType, value)); } else { @@ -7800,9 +7800,9 @@ internal void UpdateTypeConverterAndTypeEditorInternal(bool force, int dispid) // Show any non-browsable property that has an editor through a // property page. // - if (!this.IsBrowsable) + if (!IsBrowsable) { - Debug.WriteLineIf(AxPropTraceSwitch.TraceVerbose, "Making property: " + this.Name + " browsable because we found an editor."); + Debug.WriteLineIf(AxPropTraceSwitch.TraceVerbose, "Making property: " + Name + " browsable because we found an editor."); AddAttribute(new BrowsableAttribute(true)); } } @@ -7814,7 +7814,7 @@ internal void UpdateTypeConverterAndTypeEditorInternal(bool force, int dispid) } catch (Exception e) { - Debug.WriteLineIf(AxPropTraceSwitch.TraceVerbose, "could not get the type editor for property: " + this.Name + " Exception: " + e); + Debug.WriteLineIf(AxPropTraceSwitch.TraceVerbose, "could not get the type editor for property: " + Name + " Exception: " + e); } } } @@ -7842,7 +7842,7 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide try { object instance = context.Instance; - propDesc.owner.ShowPropertyPageForDispid(propDesc.Dispid, this.guid); + propDesc.owner.ShowPropertyPageForDispid(propDesc.Dispid, guid); } catch (Exception ex1) { @@ -7908,11 +7908,11 @@ private class AxPerPropertyBrowsingEnum : Com2Enum public AxPerPropertyBrowsingEnum(AxPropertyDescriptor targetObject, AxHost owner, OleStrCAMarshaler names, Int32CAMarshaler values, bool allowUnknowns) : base(new string[0], new object[0], allowUnknowns) { - this.target = targetObject; - this.nameMarshaller = names; - this.valueMarshaller = values; + target = targetObject; + nameMarshaller = names; + valueMarshaller = values; this.owner = owner; - this.arraysFetched = false; + arraysFetched = false; } /// @@ -7944,12 +7944,12 @@ public override string[] Names // private void EnsureArrays() { - if (this.arraysFetched) + if (arraysFetched) { return; } - this.arraysFetched = true; + arraysFetched = true; try { @@ -8007,9 +8007,9 @@ private void EnsureArrays() internal void RefreshArrays(OleStrCAMarshaler names, Int32CAMarshaler values) { - this.nameMarshaller = names; - this.valueMarshaller = values; - this.arraysFetched = false; + nameMarshaller = names; + valueMarshaller = values; + arraysFetched = false; } #if false diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs b/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs index 52605a4abd5..bdb531b280b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs @@ -615,7 +615,7 @@ protected virtual void OnRefreshItems() public bool Validate() { bool validatedControlAllowsFocusChange; - return this.ValidateActiveControl(out validatedControlAllowsFocusChange); + return ValidateActiveControl(out validatedControlAllowsFocusChange); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Button.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Button.cs index 153983228fa..0861108c3fa 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Button.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Button.cs @@ -131,7 +131,7 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) // Note: The result from the BCM_GETIDEALSIZE message isn't accurate if the font has been // changed, because this method is called before the font is set into the device context. - requiredSize = TextRenderer.MeasureText(this.Text, this.Font); + requiredSize = TextRenderer.MeasureText(Text, Font); requiredSize = SizeFromClientSize(requiredSize); // This padding makes FlatStyle.System about the same size as FlatStyle.Standard diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonBase.cs index addd8222578..b6b39977160 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonBase.cs @@ -812,17 +812,17 @@ private void Animate(bool animate) { if (animate) { - if (this.image != null) + if (image != null) { - ImageAnimator.Animate(this.image, new EventHandler(this.OnFrameChanged)); + ImageAnimator.Animate(image, new EventHandler(OnFrameChanged)); SetFlag(FlagCurrentlyAnimating, animate); } } else { - if (this.image != null) + if (image != null) { - ImageAnimator.StopAnimate(this.image, new EventHandler(this.OnFrameChanged)); + ImageAnimator.StopAnimate(image, new EventHandler(OnFrameChanged)); SetFlag(FlagCurrentlyAnimating, animate); } } @@ -848,7 +848,7 @@ protected override void Dispose(bool disposing) StopAnimate(); if (imageList != null) { - imageList.Disposed -= new EventHandler(this.DetachImageList); + imageList.Disposed -= new EventHandler(DetachImageList); } //Dipose the tooltip if one present.. if (textToolTip != null) @@ -1122,7 +1122,7 @@ private void OnFrameChanged(object o, EventArgs e) } if (IsHandleCreated && InvokeRequired) { - BeginInvoke(new EventHandler(this.OnFrameChanged), new object[] { o, e }); + BeginInvoke(new EventHandler(OnFrameChanged), new object[] { o, e }); return; } @@ -1227,7 +1227,7 @@ protected override void OnPaint(PaintEventArgs pevent) if (AutoEllipsis) { Size preferredSize = PreferredSize; - ShowToolTip = (this.ClientRectangle.Width < preferredSize.Width || this.ClientRectangle.Height < preferredSize.Height); + ShowToolTip = (ClientRectangle.Width < preferredSize.Width || ClientRectangle.Height < preferredSize.Height); } else { @@ -1237,7 +1237,7 @@ protected override void OnPaint(PaintEventArgs pevent) if (GetStyle(ControlStyles.UserPaint)) { Animate(); - ImageAnimator.UpdateFrames(this.Image); + ImageAnimator.UpdateFrames(Image); PaintControl(pevent); } @@ -1349,7 +1349,7 @@ public bool UseVisualStyleBackColor { isEnableVisualStyleBackgroundSet = true; enableVisualStyleBackground = value; - this.Invalidate(); + Invalidate(); } } @@ -1357,7 +1357,7 @@ private void ResetUseVisualStyleBackColor() { isEnableVisualStyleBackgroundSet = false; enableVisualStyleBackground = true; - this.Invalidate(); + Invalidate(); } private bool ShouldSerializeUseVisualStyleBackColor() diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonBaseAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonBaseAdapter.cs index 119b6923805..4ed48267cb3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonBaseAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonBaseAdapter.cs @@ -38,7 +38,7 @@ internal ButtonBaseAdapter(ButtonBase control) protected ButtonBase Control { - get { return this.control; } + get { return control; } } internal void Paint(PaintEventArgs pevent) @@ -645,7 +645,7 @@ internal virtual void DrawImageCore(Graphics graphics, Image image, Rectangle im if (!layout.options.everettButtonCompat) { // FOR EVERETT COMPATIBILITY - DO NOT CHANGE - Rectangle bounds = new Rectangle(buttonBorderSize, buttonBorderSize, this.Control.Width - (2 * buttonBorderSize), this.Control.Height - (2 * buttonBorderSize)); + Rectangle bounds = new Rectangle(buttonBorderSize, buttonBorderSize, Control.Width - (2 * buttonBorderSize), Control.Height - (2 * buttonBorderSize)); Region newClip = oldClip.Clone(); newClip.Intersect(bounds); @@ -950,7 +950,7 @@ internal ColorData Calculate() colors.windowText = colors.windowFrame; } - IntPtr hdc = this.graphics.GetHdc(); + IntPtr hdc = graphics.GetHdc(); try { @@ -970,7 +970,7 @@ internal ColorData Calculate() } finally { - this.graphics.ReleaseHdc(); + graphics.ReleaseHdc(); } return colors; @@ -1045,11 +1045,11 @@ public StringFormat StringFormat { StringFormat format = new StringFormat(); - format.FormatFlags = this.gdipFormatFlags; - format.Trimming = this.gdipTrimming; - format.HotkeyPrefix = this.gdipHotkeyPrefix; - format.Alignment = this.gdipAlignment; - format.LineAlignment = this.gdipLineAlignment; + format.FormatFlags = gdipFormatFlags; + format.Trimming = gdipTrimming; + format.HotkeyPrefix = gdipHotkeyPrefix; + format.Alignment = gdipAlignment; + format.LineAlignment = gdipLineAlignment; if (disableWordWrapping) { @@ -1060,11 +1060,11 @@ public StringFormat StringFormat } set { - this.gdipFormatFlags = value.FormatFlags; - this.gdipTrimming = value.Trimming; - this.gdipHotkeyPrefix = value.HotkeyPrefix; - this.gdipAlignment = value.Alignment; - this.gdipLineAlignment = value.LineAlignment; + gdipFormatFlags = value.FormatFlags; + gdipTrimming = value.Trimming; + gdipHotkeyPrefix = value.HotkeyPrefix; + gdipAlignment = value.Alignment; + gdipLineAlignment = value.LineAlignment; } } @@ -1211,12 +1211,12 @@ internal Size GetPreferredSizeCore(Size proposedSize) // If someone has a carriage return in the text we'll honor that for preferred size, but we wont wrap based on constraints. try { - this.disableWordWrapping = true; + disableWordWrapping = true; textSize = GetTextSize(proposedSize) + textImageInsetSize; } finally { - this.disableWordWrapping = false; + disableWordWrapping = false; } } @@ -1260,7 +1260,7 @@ private bool OnePixExtraBorder internal LayoutData Layout() { LayoutData layout = new LayoutData(this); - layout.client = this.client; + layout.client = client; // subtract border size from layout area int fullBorderSize = FullBorderSize; @@ -1281,7 +1281,7 @@ internal LayoutData Layout() layout.focus.Inflate(-1, -1); // Adjust for padding. - layout.focus = LayoutUtils.InflateRect(layout.focus, this.padding); + layout.focus = LayoutUtils.InflateRect(layout.focus, padding); } else { @@ -1649,7 +1649,7 @@ protected virtual Size GetTextSize(Size proposedSize) { // GDI+ text rendering. using (Graphics g = WindowsFormsUtils.CreateMeasurementGraphics()) { - using (StringFormat gdipStringFormat = this.StringFormat) + using (StringFormat gdipStringFormat = StringFormat) { textSize = Size.Ceiling(g.MeasureString(text, font, new SizeF(proposedSize.Width, proposedSize.Height), gdipStringFormat)); } @@ -1657,7 +1657,7 @@ protected virtual Size GetTextSize(Size proposedSize) } else if (!string.IsNullOrEmpty(text)) { // GDI text rendering (Whidbey feature). - textSize = TextRenderer.MeasureText(text, font, proposedSize, this.TextFormatFlags); + textSize = TextRenderer.MeasureText(text, font, proposedSize, TextFormatFlags); } //else skip calling MeasureText, it should return 0,0 diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonFlatAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonFlatAdapter.cs index f2c6c667e82..d2a2f6da96a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonFlatAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonFlatAdapter.cs @@ -96,7 +96,7 @@ internal override void PaintUp(PaintEventArgs e, CheckState state) if (!(Control.IsDefault && Control.Focused && (Control.FlatAppearance.BorderSize == 0))) { - DrawDefaultBorder(g, r, colors.windowFrame, this.Control.IsDefault); + DrawDefaultBorder(g, r, colors.windowFrame, Control.IsDefault); } //Always check if the BorderSize is not the default.If not, we need to paint with the BorderSize set by the user. @@ -184,7 +184,7 @@ internal override void PaintDown(PaintEventArgs e, CheckState state) if (!(Control.IsDefault && Control.Focused && (Control.FlatAppearance.BorderSize == 0))) { - DrawDefaultBorder(g, r, colors.windowFrame, this.Control.IsDefault); + DrawDefaultBorder(g, r, colors.windowFrame, Control.IsDefault); } //Always check if the BorderSize is not the default.If not, we need to paint with the BorderSize set by the user. @@ -288,7 +288,7 @@ internal override void PaintOver(PaintEventArgs e, CheckState state) if (!(Control.IsDefault && Control.Focused && (Control.FlatAppearance.BorderSize == 0))) { - DrawDefaultBorder(g, r, colors.windowFrame, this.Control.IsDefault); + DrawDefaultBorder(g, r, colors.windowFrame, Control.IsDefault); } //Always check if the BorderSize is not the default.If not, we need to paint with the BorderSize set by the user. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonPopupAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonPopupAdapter.cs index 42a888c6756..a2e36cfb2c2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonPopupAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonPopupAdapter.cs @@ -56,7 +56,7 @@ internal override void PaintUp(PaintEventArgs e, CheckState state) PaintImage(e, layout); PaintField(e, layout, colors, state != CheckState.Indeterminate && IsHighContrastHighlighted() ? SystemColors.HighlightText : colors.windowText, true); - DrawDefaultBorder(g, r, colors.options.highContrast ? colors.windowText : colors.buttonShadow, this.Control.IsDefault); + DrawDefaultBorder(g, r, colors.options.highContrast ? colors.windowText : colors.buttonShadow, Control.IsDefault); if (state == CheckState.Unchecked) { @@ -104,7 +104,7 @@ internal override void PaintOver(PaintEventArgs e, CheckState state) PaintImage(e, layout); PaintField(e, layout, colors, IsHighContrastHighlighted() ? SystemColors.HighlightText : colors.windowText, true); - DrawDefaultBorder(g, r, colors.options.highContrast ? colors.windowText : colors.buttonShadow, this.Control.IsDefault); + DrawDefaultBorder(g, r, colors.options.highContrast ? colors.windowText : colors.buttonShadow, Control.IsDefault); if (SystemInformation.HighContrast) { @@ -158,7 +158,7 @@ internal override void PaintDown(PaintEventArgs e, CheckState state) PaintField(e, layout, colors, colors.windowText, true); r.Inflate(1, 1); - DrawDefaultBorder(g, r, colors.options.highContrast ? colors.windowText : colors.windowFrame, this.Control.IsDefault); + DrawDefaultBorder(g, r, colors.options.highContrast ? colors.windowText : colors.windowFrame, Control.IsDefault); ControlPaint.DrawBorder(g, r, colors.options.highContrast ? colors.windowText : colors.buttonShadow, ButtonBorderStyle.Solid); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonStandardAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonStandardAdapter.cs index ce6fe9aec8f..761d6a81ff7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonStandardAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonStandardAdapter.cs @@ -83,7 +83,7 @@ private void PaintThemedButtonBackground(PaintEventArgs e, Rectangle bounds, boo } else { - ButtonRenderer.DrawButtonForHandle(e.Graphics, Control.ClientRectangle, false, pbState, this.Control.HandleInternal); + ButtonRenderer.DrawButtonForHandle(e.Graphics, Control.ClientRectangle, false, pbState, Control.HandleInternal); } // Now overlay the background image or backcolor (the former overrides the latter), leaving a @@ -164,7 +164,7 @@ void PaintWorker(PaintEventArgs e, bool up, CheckState state) Graphics g = e.Graphics; - Button thisbutton = this.Control as Button; + Button thisbutton = Control as Button; if (Application.RenderWithVisualStyles) { PaintThemedButtonBackground(e, Control.ClientRectangle, up); @@ -238,7 +238,7 @@ void PaintWorker(PaintEventArgs e, bool up, CheckState state) r.Inflate(-1, -1); } - DrawDefaultBorder(g, r, colors.windowFrame, this.Control.IsDefault); + DrawDefaultBorder(g, r, colors.windowFrame, Control.IsDefault); if (up) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/CheckBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/CheckBox.cs index 7c03d19e039..7a001e0a926 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/CheckBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/CheckBox.cs @@ -87,11 +87,11 @@ private bool AccObjDoDefaultAction { get { - return this.accObjDoDefaultAction; + return accObjDoDefaultAction; } set { - this.accObjDoDefaultAction = value; + accObjDoDefaultAction = value; } } @@ -123,7 +123,7 @@ public Appearance Appearance if (appearance != value) { - using (LayoutTransaction.CreateTransactionIf(AutoSize, this.ParentInternal, this, PropertyNames.Appearance)) + using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.Appearance)) { appearance = value; if (OwnerDraw) @@ -390,7 +390,7 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) return base.GetPreferredSizeCore(proposedConstraints); } - Size textSize = TextRenderer.MeasureText(this.Text, this.Font); + Size textSize = TextRenderer.MeasureText(Text, Font); Size size = SizeFromClientSize(textSize); size.Width += flatSystemStylePaddingWidth; size.Height = Math.Max(size.Height + 5, flatSystemStyleMinimumHeight); // ensure minimum height to avoid truncation of check-box or text @@ -537,7 +537,7 @@ protected virtual void OnAppearanceChanged(EventArgs e) protected virtual void OnCheckedChanged(EventArgs e) { // accessibility stuff - if (this.FlatStyle == FlatStyle.System) + if (FlatStyle == FlatStyle.System) { AccessibilityNotifyClients(AccessibleEvents.SystemCaptureStart, -1); } @@ -545,7 +545,7 @@ protected virtual void OnCheckedChanged(EventArgs e) AccessibilityNotifyClients(AccessibleEvents.StateChange, -1); AccessibilityNotifyClients(AccessibleEvents.NameChange, -1); - if (this.FlatStyle == FlatStyle.System) + if (FlatStyle == FlatStyle.System) { AccessibilityNotifyClients(AccessibleEvents.SystemCaptureEnd, -1); } @@ -596,7 +596,7 @@ protected override void OnClick(EventArgs e) // If the check box is clicked as a result of AccObj::DoDefaultAction // then the native check box does not fire OBJ_STATE_CHANGE event when going to Indeterminate state. // So the WinForms layer fires the OBJ_STATE_CHANGE event. - if (this.AccObjDoDefaultAction) + if (AccObjDoDefaultAction) { AccessibilityNotifyClients(AccessibleEvents.StateChange, -1); } @@ -671,7 +671,7 @@ protected override void OnMouseUp(MouseEventArgs mevent) ResetFlagsandPaint(); if (!ValidationCancelled) { - if (this.Capture) + if (Capture) { OnClick(mevent); } @@ -796,7 +796,7 @@ public override AccessibleStates State public override void DoDefaultAction() { - CheckBox cb = this.Owner as CheckBox; + CheckBox cb = Owner as CheckBox; if (cb != null) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/CheckedListBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/CheckedListBox.cs index e2f417480c2..b1796bd4c53 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/CheckedListBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/CheckedListBox.cs @@ -347,7 +347,7 @@ public bool ThreeDCheckBoxes CheckedListBox.ObjectCollection items = (CheckedListBox.ObjectCollection)Items; if ((items != null) && (items.Count > 0)) { - this.Invalidate(); + Invalidate(); } } } @@ -608,7 +608,7 @@ protected override void OnDrawItem(DrawItemEventArgs e) if (Font.Height < 0) { - this.Font = Control.DefaultFont; + Font = Control.DefaultFont; } if (e.Index >= 0) @@ -626,7 +626,7 @@ protected override void OnDrawItem(DrawItemEventArgs e) } Rectangle bounds = e.Bounds; - int height = this.ItemHeight; + int height = ItemHeight; // set up the appearance of the checkbox // @@ -1299,7 +1299,7 @@ private ItemArray InnerArray public IEnumerator GetEnumerator() { - int[] indices = new int[this.Count]; + int[] indices = new int[Count]; CopyTo(indices, 0); return indices.GetEnumerator(); } @@ -1554,7 +1554,7 @@ public override AccessibleObject GetChild(int index) { if (index >= 0 && index < CheckedListBox.Items.Count) { - return new CheckedListBoxItemAccessibleObject(this.CheckedListBox.GetItemText(CheckedListBox.Items[index]), index, this); + return new CheckedListBoxItemAccessibleObject(CheckedListBox.GetItemText(CheckedListBox.Items[index]), index, this); } else { @@ -1608,7 +1608,7 @@ public override AccessibleObject HitTest(int x, int y) // Within the CheckedListBox bounds? // - if (this.Bounds.Contains(x, y)) + if (Bounds.Contains(x, y)) { return this; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ColorDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ColorDialog.cs index af56f0cb0c2..f896fe837d3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ColorDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ColorDialog.cs @@ -279,7 +279,7 @@ private void ResetColor() protected override bool RunDialog(IntPtr hwndOwner) { - NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(this.HookProc); + NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(HookProc); NativeMethods.CHOOSECOLOR cc = new NativeMethods.CHOOSECOLOR(); IntPtr custColorPtr = Marshal.AllocCoTaskMem(64); try diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeader.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeader.cs index 785e125125a..c45ffdcbfaa 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeader.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeader.cs @@ -58,12 +58,12 @@ internal ListView OwnerListview } set { - int width = this.Width; + int width = Width; listview = value; // The below properties are set into the listview. - this.Width = width; + Width = width; } } @@ -80,7 +80,7 @@ public ColumnHeader() /// public ColumnHeader(int imageIndex) : this() { - this.ImageIndex = imageIndex; + ImageIndex = imageIndex; } /// @@ -88,15 +88,15 @@ public ColumnHeader(int imageIndex) : this() /// public ColumnHeader(string imageKey) : this() { - this.ImageKey = imageKey; + ImageKey = imageKey; } internal int ActualImageIndex_Internal { get { - int imgIndex = this.imageIndexer.ActualIndex; - if (this.ImageList == null || this.ImageList.Images == null || imgIndex >= this.ImageList.Images.Count) + int imgIndex = imageIndexer.ActualIndex; + if (ImageList == null || ImageList.Images == null || imgIndex >= ImageList.Images.Count) { // the ImageIndex equivalent of a ImageKey that does not exist in the ImageList return -1; @@ -119,7 +119,7 @@ public int DisplayIndex { get { - return this.DisplayIndexInternal; + return DisplayIndexInternal; } set @@ -128,30 +128,30 @@ public int DisplayIndex // When the list is being deserialized we need // to take the display index as is. ListView // does correctly synchronize the indices. - if (this.listview == null) + if (listview == null) { - this.DisplayIndexInternal = value; + DisplayIndexInternal = value; return; } - if (value < 0 || value > (this.listview.Columns.Count - 1)) + if (value < 0 || value > (listview.Columns.Count - 1)) { throw new ArgumentOutOfRangeException(nameof(DisplayIndex), SR.ColumnHeaderBadDisplayIndex); } - int lowDI = Math.Min(this.DisplayIndexInternal, value); - int hiDI = Math.Max(this.DisplayIndexInternal, value); - int[] colsOrder = new int[this.listview.Columns.Count]; + int lowDI = Math.Min(DisplayIndexInternal, value); + int hiDI = Math.Max(DisplayIndexInternal, value); + int[] colsOrder = new int[listview.Columns.Count]; // set the display indices. This is not an expensive operation because // we only set an integer in the column header class - bool hdrMovedForward = value > this.DisplayIndexInternal; + bool hdrMovedForward = value > DisplayIndexInternal; ColumnHeader movedHdr = null; - for (int i = 0; i < this.listview.Columns.Count; i++) + for (int i = 0; i < listview.Columns.Count; i++) { - ColumnHeader hdr = this.listview.Columns[i]; - if (hdr.DisplayIndex == this.DisplayIndexInternal) + ColumnHeader hdr = listview.Columns[i]; + if (hdr.DisplayIndex == DisplayIndexInternal) { movedHdr = hdr; } @@ -159,7 +159,7 @@ public int DisplayIndex { hdr.DisplayIndexInternal -= hdrMovedForward ? 1 : -1; } - if (i != this.Index) + if (i != Index) { colsOrder[hdr.DisplayIndexInternal] = i; } @@ -175,11 +175,11 @@ internal int DisplayIndexInternal { get { - return this.displayIndexInternal; + return displayIndexInternal; } set { - this.displayIndexInternal = value; + displayIndexInternal = value; } } @@ -241,7 +241,7 @@ public ImageList ImageList // we added the ImageList property so that the ImageIndexConverter can find our image list get { - return this.imageIndexer.ImageList; + return imageIndexer.ImageList; } } @@ -280,7 +280,7 @@ public ListView ListView { get { - return this.listview; + return listview; } } @@ -301,11 +301,11 @@ public string Name { if (value == null) { - this.name = string.Empty; + name = string.Empty; } else { - this.name = value; + name = value; } if (Site != null) { @@ -332,11 +332,11 @@ public string Text { if (value == null) { - this.text = string.Empty; + text = string.Empty; } else { - this.text = value; + text = value; } if (listview != null) { @@ -365,10 +365,10 @@ public HorizontalAlignment TextAlign //Added !IsMirrored if ((Index != 0) && (listview.RightToLeft == RightToLeft.Yes) && !listview.IsMirrored) { - this.textAlign = HorizontalAlignment.Right; + textAlign = HorizontalAlignment.Right; } } - return this.textAlign; + return textAlign; } set { @@ -378,12 +378,12 @@ public HorizontalAlignment TextAlign throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(HorizontalAlignment)); } - this.textAlign = value; + textAlign = value; // The first column must be left-aligned - if (Index == 0 && this.textAlign != HorizontalAlignment.Left) + if (Index == 0 && textAlign != HorizontalAlignment.Left) { - this.textAlign = HorizontalAlignment.Left; + textAlign = HorizontalAlignment.Left; } if (listview != null) @@ -457,7 +457,7 @@ public int Width } set { - this.width = value; + width = value; if (listview != null) listview.SetColumnWidth(Index, ColumnHeaderAutoResizeStyle.None); } @@ -471,9 +471,9 @@ public void AutoResize(ColumnHeaderAutoResizeStyle headerAutoResize) throw new InvalidEnumArgumentException(nameof(headerAutoResize), (int)headerAutoResize, typeof(ColumnHeaderAutoResizeStyle)); } - if (this.listview != null) + if (listview != null) { - this.listview.AutoResizeColumn(this.Index, headerAutoResize); + listview.AutoResizeColumn(Index, headerAutoResize); } } @@ -483,7 +483,7 @@ public void AutoResize(ColumnHeaderAutoResizeStyle headerAutoResize) /// public object Clone() { - Type clonedType = this.GetType(); + Type clonedType = GetType(); ColumnHeader columnHeader = null; if (clonedType == typeof(ColumnHeader)) @@ -526,20 +526,20 @@ private void ResetText() private void SetDisplayIndices(int[] cols) { - if (this.listview.IsHandleCreated && !this.listview.Disposing) + if (listview.IsHandleCreated && !listview.Disposing) { - UnsafeNativeMethods.SendMessage(new HandleRef(this.listview, this.listview.Handle), NativeMethods.LVM_SETCOLUMNORDERARRAY, cols.Length, cols); + UnsafeNativeMethods.SendMessage(new HandleRef(listview, listview.Handle), NativeMethods.LVM_SETCOLUMNORDERARRAY, cols.Length, cols); } } private bool ShouldSerializeName() { - return !string.IsNullOrEmpty(this.name); + return !string.IsNullOrEmpty(name); } private bool ShouldSerializeDisplayIndex() { - return this.DisplayIndex != this.Index; + return DisplayIndex != Index; } internal bool ShouldSerializeText() diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs index 006336fe149..d76c1dc9e3c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs @@ -188,8 +188,8 @@ public AutoCompleteMode AutoCompleteMode { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AutoCompleteMode)); } - if (this.DropDownStyle == ComboBoxStyle.DropDownList && - this.AutoCompleteSource != AutoCompleteSource.ListItems && + if (DropDownStyle == ComboBoxStyle.DropDownList && + AutoCompleteSource != AutoCompleteSource.ListItems && value != AutoCompleteMode.None) { throw new NotSupportedException(SR.ComboBoxAutoCompleteModeOnlyNoneAllowed); @@ -241,8 +241,8 @@ public AutoCompleteSource AutoCompleteSource throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AutoCompleteSource)); } - if (this.DropDownStyle == ComboBoxStyle.DropDownList && - this.AutoCompleteMode != AutoCompleteMode.None && + if (DropDownStyle == ComboBoxStyle.DropDownList && + AutoCompleteMode != AutoCompleteMode.None && value != AutoCompleteSource.ListItems) { throw new NotSupportedException(SR.ComboBoxAutoCompleteSourceOnlyListItemsAllowed); @@ -275,7 +275,7 @@ public AutoCompleteStringCollection AutoCompleteCustomSource if (autoCompleteCustomSource == null) { autoCompleteCustomSource = new AutoCompleteStringCollection(); - autoCompleteCustomSource.CollectionChanged += new CollectionChangeEventHandler(this.OnAutoCompleteCustomSourceChanged); + autoCompleteCustomSource.CollectionChanged += new CollectionChangeEventHandler(OnAutoCompleteCustomSourceChanged); } return autoCompleteCustomSource; } @@ -286,14 +286,14 @@ public AutoCompleteStringCollection AutoCompleteCustomSource if (autoCompleteCustomSource != null) { - autoCompleteCustomSource.CollectionChanged -= new CollectionChangeEventHandler(this.OnAutoCompleteCustomSourceChanged); + autoCompleteCustomSource.CollectionChanged -= new CollectionChangeEventHandler(OnAutoCompleteCustomSourceChanged); } autoCompleteCustomSource = value; if (autoCompleteCustomSource != null) { - autoCompleteCustomSource.CollectionChanged += new CollectionChangeEventHandler(this.OnAutoCompleteCustomSourceChanged); + autoCompleteCustomSource.CollectionChanged += new CollectionChangeEventHandler(OnAutoCompleteCustomSourceChanged); } SetAutoComplete(false, true); } @@ -841,7 +841,7 @@ private string MatchingText } set { - if (value != null || this.Properties.ContainsObject(PropMatchingText)) + if (value != null || Properties.ContainsObject(PropMatchingText)) { Properties.SetObject(PropMatchingText, value); } @@ -935,7 +935,7 @@ internal bool MouseIsOver // Nothing to see here... Just keep on walking... // Turns out that with Theming off, we don't get quite the same messages as with theming on, so // our drawing gets a little messed up. So in case theming is off, force a draw here. - if ((!ContainsFocus || !Application.RenderWithVisualStyles) && this.FlatStyle == FlatStyle.Popup) + if ((!ContainsFocus || !Application.RenderWithVisualStyles) && FlatStyle == FlatStyle.Popup) { Invalidate(); Update(); @@ -999,7 +999,7 @@ public int PreferredHeight // if the user manually sets Size = (121, 20) in code (usually height gets forced to 21), then he will see Whidey.(1) above // user usually uses nondefault size and will experience whidbey.(2) above - Size textSize = TextRenderer.MeasureText(LayoutUtils.TestString, this.Font, new Size(short.MaxValue, (int)(FontHeight * 1.25)), TextFormatFlags.SingleLine); + Size textSize = TextRenderer.MeasureText(LayoutUtils.TestString, Font, new Size(short.MaxValue, (int)(FontHeight * 1.25)), TextFormatFlags.SingleLine); prefHeightCache = (short)(textSize.Height + SystemInformation.BorderSize.Height * 8 + Padding.Size.Height); return prefHeightCache; @@ -1011,7 +1011,7 @@ public int PreferredHeight // which is used by GetPreferredSize (infinite loop). if (prefHeightCache < 0) { - Size textSize = TextRenderer.MeasureText(LayoutUtils.TestString, this.Font, new Size(short.MaxValue, (int)(FontHeight * 1.25)), TextFormatFlags.SingleLine); + Size textSize = TextRenderer.MeasureText(LayoutUtils.TestString, Font, new Size(short.MaxValue, (int)(FontHeight * 1.25)), TextFormatFlags.SingleLine); // For a "simple" style combobox, the preferred height depends on the // number of items in the combobox. @@ -1046,7 +1046,7 @@ private int GetComboHeight() // controls to be the same height. Size textExtent = Size.Empty; - using (WindowsFont font = WindowsFont.FromFont(this.Font)) + using (WindowsFont font = WindowsFont.FromFont(Font)) { // this is the character that Windows uses to determine the extent textExtent = WindowsGraphicsCacheManager.MeasurementGraphics.GetTextExtent("0", font); @@ -1299,7 +1299,7 @@ public bool Sorted { if (sorted != value) { - if (this.DataSource != null && value) + if (DataSource != null && value) { throw new ArgumentException(SR.ComboBoxSortWithDataSource); } @@ -1347,10 +1347,10 @@ public ComboBoxStyle DropDownStyle } if (value == ComboBoxStyle.DropDownList && - this.AutoCompleteSource != AutoCompleteSource.ListItems && - this.AutoCompleteMode != AutoCompleteMode.None) + AutoCompleteSource != AutoCompleteSource.ListItems && + AutoCompleteMode != AutoCompleteMode.None) { - this.AutoCompleteMode = AutoCompleteMode.None; + AutoCompleteMode = AutoCompleteMode.None; } // reset preferred height. @@ -1460,8 +1460,8 @@ private void NotifyAutoComplete() // If it matches an item in the list, this will fire SIC and SVC private void NotifyAutoComplete(bool setSelectedIndex) { - string text = this.Text; - bool textChanged = (text != this.lastTextChangedValue); + string text = Text; + bool textChanged = (text != lastTextChangedValue); bool selectedIndexSet = false; if (setSelectedIndex) @@ -1492,7 +1492,7 @@ private void NotifyAutoComplete(bool setSelectedIndex) } // Save the new value - this.lastTextChangedValue = text; + lastTextChangedValue = text; } internal override bool SupportsUiaProviders => true; @@ -1502,7 +1502,7 @@ private bool SystemAutoCompleteEnabled { get { - return ((this.autoCompleteMode != AutoCompleteMode.None) && (this.DropDownStyle != ComboBoxStyle.DropDownList)); + return ((autoCompleteMode != AutoCompleteMode.None) && (DropDownStyle != ComboBoxStyle.DropDownList)); } } @@ -1743,13 +1743,13 @@ private void ChildWndProc(ref Message m) char keyChar = unchecked((char)(long)m.WParam); if (keyChar == (char)(int)Keys.Escape) { - this.DroppedDown = false; + DroppedDown = false; } - else if (keyChar == (char)(int)Keys.Return && this.DroppedDown) + else if (keyChar == (char)(int)Keys.Return && DroppedDown) { UpdateText(); OnSelectionChangeCommittedInternal(EventArgs.Empty); - this.DroppedDown = false; + DroppedDown = false; } } @@ -1810,12 +1810,12 @@ private void ChildWndProc(ref Message m) // once in the combobox and once here. if (fireLostFocus) { - this.InvokeLostFocus(this, EventArgs.Empty); + InvokeLostFocus(this, EventArgs.Empty); } if (FlatStyle == FlatStyle.Popup) { - this.Invalidate(); + Invalidate(); } break; @@ -1850,12 +1850,12 @@ private void ChildWndProc(ref Message m) // once in the combobox and once here. if (fireSetFocus) { - this.InvokeGotFocus(this, EventArgs.Empty); + InvokeGotFocus(this, EventArgs.Empty); } if (FlatStyle == FlatStyle.Popup) { - this.Invalidate(); + Invalidate(); } break; @@ -1992,7 +1992,7 @@ private void ChildWndProc(ref Message m) - if (this.ContextMenu != null || this.ContextMenuStrip != null) + if (ContextMenu != null || ContextMenuStrip != null) CaptureInternal = true; DefChildWndProc(ref m); //the up gets fired from "Combo-box's WndPrc --- So Convert these Coordinates to Combobox coordianate... @@ -2015,7 +2015,7 @@ private void ChildWndProc(ref Message m) mouseEvents = false; //set the mouse capture .. this is the Child Wndproc.. // - if (this.ContextMenu != null) + if (ContextMenu != null) CaptureInternal = false; DefChildWndProc(ref m); //the up gets fired from "Combo-box's WndPrc --- So Convert these Coordinates to Combobox coordianate... @@ -2027,7 +2027,7 @@ private void ChildWndProc(ref Message m) case Interop.WindowMessages.WM_CONTEXTMENU: // Forward context menu messages to the parent control - if (this.ContextMenu != null || this.ContextMenuStrip != null) + if (ContextMenu != null || ContextMenuStrip != null) { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.WindowMessages.WM_CONTEXTMENU, m.WParam, m.LParam); } @@ -2134,7 +2134,7 @@ protected override void Dispose(bool disposing) { if (autoCompleteCustomSource != null) { - autoCompleteCustomSource.CollectionChanged -= new CollectionChangeEventHandler(this.OnAutoCompleteCustomSourceChanged); + autoCompleteCustomSource.CollectionChanged -= new CollectionChangeEventHandler(OnAutoCompleteCustomSourceChanged); } if (stringSource != null) { @@ -2327,9 +2327,9 @@ private bool InterceptAutoCompleteKeystroke(Message m) if ((Keys)unchecked((int)(long)m.WParam) == Keys.Delete) { // Reset matching text and remove any selection - this.MatchingText = string.Empty; - this.autoCompleteTimeStamp = DateTime.Now.Ticks; - if (this.Items.Count > 0) + MatchingText = string.Empty; + autoCompleteTimeStamp = DateTime.Now.Ticks; + if (Items.Count > 0) { SelectedIndex = 0; } @@ -2342,12 +2342,12 @@ private bool InterceptAutoCompleteKeystroke(Message m) char keyChar = unchecked((char)(long)m.WParam); if (keyChar == (char)Keys.Back) { - if (DateTime.Now.Ticks - this.autoCompleteTimeStamp > AutoCompleteTimeout || - this.MatchingText.Length <= 1) + if (DateTime.Now.Ticks - autoCompleteTimeStamp > AutoCompleteTimeout || + MatchingText.Length <= 1) { // Reset matching text and remove any selection - this.MatchingText = string.Empty; - if (this.Items.Count > 0) + MatchingText = string.Empty; + if (Items.Count > 0) { SelectedIndex = 0; } @@ -2355,15 +2355,15 @@ private bool InterceptAutoCompleteKeystroke(Message m) else { // Remove one character from matching text and rematch - this.MatchingText = this.MatchingText.Remove(this.MatchingText.Length - 1); - this.SelectedIndex = FindString(this.MatchingText); + MatchingText = MatchingText.Remove(MatchingText.Length - 1); + SelectedIndex = FindString(MatchingText); } - this.autoCompleteTimeStamp = DateTime.Now.Ticks; + autoCompleteTimeStamp = DateTime.Now.Ticks; return false; } else if (keyChar == (char)Keys.Escape) { - this.MatchingText = string.Empty; + MatchingText = string.Empty; } string newMatchingText; @@ -2372,31 +2372,31 @@ private bool InterceptAutoCompleteKeystroke(Message m) { DroppedDown = true; } - if (DateTime.Now.Ticks - this.autoCompleteTimeStamp > AutoCompleteTimeout) + if (DateTime.Now.Ticks - autoCompleteTimeStamp > AutoCompleteTimeout) { newMatchingText = new string(keyChar, 1); if (FindString(newMatchingText) != -1) { - this.MatchingText = newMatchingText; + MatchingText = newMatchingText; // Select the found item } - this.autoCompleteTimeStamp = DateTime.Now.Ticks; + autoCompleteTimeStamp = DateTime.Now.Ticks; return false; } else { - newMatchingText = this.MatchingText + keyChar; + newMatchingText = MatchingText + keyChar; int itemFound = FindString(newMatchingText); if (itemFound != -1) { - this.MatchingText = newMatchingText; - if (itemFound != this.SelectedIndex) + MatchingText = newMatchingText; + if (itemFound != SelectedIndex) { - this.SelectedIndex = itemFound; + SelectedIndex = itemFound; } } // Do not change the selection - this.autoCompleteTimeStamp = DateTime.Now.Ticks; + autoCompleteTimeStamp = DateTime.Now.Ticks; return true; } } @@ -2425,7 +2425,7 @@ protected override bool IsInputKey(Keys keyData) Keys keyCode = keyData & (Keys.KeyCode | Keys.Alt); if (keyCode == Keys.Return || keyCode == Keys.Escape) { - if (this.DroppedDown || autoCompleteDroppedDown) + if (DroppedDown || autoCompleteDroppedDown) { //old behavior return true; @@ -2878,12 +2878,12 @@ protected override void OnSelectedIndexChanged(EventArgs e) // into the backEnd. We do not need to do that. // // don't change the position if SelectedIndex is -1 because this indicates a selection not from the list. - if (this.DataManager != null && DataManager.Position != SelectedIndex) + if (DataManager != null && DataManager.Position != SelectedIndex) { //read this as "if everett or (whidbey and selindex is valid)" if (!FormattingEnabled || SelectedIndex != -1) { - this.DataManager.Position = this.SelectedIndex; + DataManager.Position = SelectedIndex; } } } @@ -2937,7 +2937,7 @@ protected override void OnFontChanged(EventArgs e) base.OnFontChanged(e); ResetHeightCache(); - if (this.AutoCompleteMode == AutoCompleteMode.None) + if (AutoCompleteMode == AutoCompleteMode.None) { UpdateControl(true); } @@ -3001,11 +3001,11 @@ protected override void OnLostFocus(EventArgs e) { if (canFireLostFocus) { - if (this.AutoCompleteMode != AutoCompleteMode.None && - this.AutoCompleteSource == AutoCompleteSource.ListItems && - this.DropDownStyle == ComboBoxStyle.DropDownList) + if (AutoCompleteMode != AutoCompleteMode.None && + AutoCompleteSource == AutoCompleteSource.ListItems && + DropDownStyle == ComboBoxStyle.DropDownList) { - this.MatchingText = string.Empty; + MatchingText = string.Empty; } base.OnLostFocus(e); canFireLostFocus = false; @@ -3017,16 +3017,16 @@ protected override void OnTextChanged(EventArgs e) { if (SystemAutoCompleteEnabled) { - string text = this.Text; + string text = Text; // Prevent multiple TextChanges... - if (text != this.lastTextChangedValue) + if (text != lastTextChangedValue) { // Need to still fire a TextChanged base.OnTextChanged(e); // Save the new value - this.lastTextChangedValue = text; + lastTextChangedValue = text; } } else @@ -3189,9 +3189,9 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) } protected override bool ProcessKeyEventArgs(ref Message m) { - if (this.AutoCompleteMode != AutoCompleteMode.None && - this.AutoCompleteSource == AutoCompleteSource.ListItems && - this.DropDownStyle == ComboBoxStyle.DropDownList && + if (AutoCompleteMode != AutoCompleteMode.None && + AutoCompleteSource == AutoCompleteSource.ListItems && + DropDownStyle == ComboBoxStyle.DropDownList && InterceptAutoCompleteKeystroke(m)) { return true; @@ -3225,12 +3225,12 @@ protected override void RefreshItems() // if we have a dataSource and a DisplayMember, then use it // to populate the Items collection // - if (this.DataManager != null && this.DataManager.Count != -1) + if (DataManager != null && DataManager.Count != -1) { - newItems = new object[this.DataManager.Count]; + newItems = new object[DataManager.Count]; for (int i = 0; i < newItems.Length; i++) { - newItems[i] = this.DataManager[i]; + newItems[i] = DataManager[i]; } } else if (savedItems != null) @@ -3253,10 +3253,10 @@ protected override void RefreshItems() { Items.AddRangeInternal(newItems); } - if (this.DataManager != null) + if (DataManager != null) { // put the selectedIndex in sync w/ the position in the dataManager - this.SelectedIndex = this.DataManager.Position; + SelectedIndex = DataManager.Position; } else { @@ -3359,7 +3359,7 @@ private void SetAutoComplete(bool reset, bool recreate) { //RecreateHandle to avoid Leak. // notice the use of member variable to avoid re-entrancy - AutoCompleteMode backUpMode = this.AutoCompleteMode; + AutoCompleteMode backUpMode = AutoCompleteMode; autoCompleteMode = AutoCompleteMode.None; RecreateHandle(); autoCompleteMode = backUpMode; @@ -3513,11 +3513,11 @@ protected override void SetItemsCore(IList value) // if the list changed, we want to keep the same selected index // CurrencyManager will provide the PositionChanged event // it will be provided before changing the list though... - if (this.DataManager != null) + if (DataManager != null) { - if (this.DataSource is ICurrencyManagerProvider) + if (DataSource is ICurrencyManagerProvider) { - this.selectedValueChangedFired = false; + selectedValueChangedFired = false; } if (IsHandleCreated) @@ -3928,7 +3928,7 @@ protected override void WndProc(ref Message m) // WM_MOUSELEAVE to ourselves, since that also sets up the right state. Or... at least the state is the same // as with Theming on. - if (!Application.RenderWithVisualStyles && GetStyle(ControlStyles.UserPaint) == false && this.DropDownStyle == ComboBoxStyle.DropDownList && (FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup)) + if (!Application.RenderWithVisualStyles && GetStyle(ControlStyles.UserPaint) == false && DropDownStyle == ComboBoxStyle.DropDownList && (FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup)) { UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), Interop.WindowMessages.WM_MOUSELEAVE, 0, 0); } @@ -4007,11 +4007,11 @@ protected override void WndProc(ref Message m) using (WindowsRegion dr = new WindowsRegion(FlatComboBoxAdapter.dropDownRect)) { - using (WindowsRegion wr = new WindowsRegion(this.Bounds)) + using (WindowsRegion wr = new WindowsRegion(Bounds)) { // Stash off the region we have to update (the base is going to clear this off in BeginPaint) - NativeMethods.RegionFlags updateRegionFlags = (NativeMethods.RegionFlags)SafeNativeMethods.GetUpdateRgn(new HandleRef(this, this.Handle), new HandleRef(this, wr.HRegion), true); + NativeMethods.RegionFlags updateRegionFlags = (NativeMethods.RegionFlags)SafeNativeMethods.GetUpdateRgn(new HandleRef(this, Handle), new HandleRef(this, wr.HRegion), true); dr.CombineRegion(wr, dr, RegionCombineMode.DIFF); @@ -4697,7 +4697,7 @@ internal void SetItemInternal(int index, object value) { bool selected = (index == owner.SelectedIndex); - if (string.Compare(this.owner.GetItemText(value), this.owner.NativeGetItemText(index), true, CultureInfo.CurrentCulture) != 0) + if (string.Compare(owner.GetItemText(value), owner.NativeGetItemText(index), true, CultureInfo.CurrentCulture) != 0) { owner.NativeRemoveAt(index); owner.NativeInsert(index, value); @@ -5175,11 +5175,11 @@ internal override UnsafeNativeMethods.ExpandCollapseState ExpandCollapseState internal override string get_accNameInternal(object childID) { - this.ValidateChildID(ref childID); + ValidateChildID(ref childID); if (childID != null && ((int)childID) == COMBOBOX_ACC_ITEM_INDEX) { - return this.Name; + return Name; } else { @@ -5189,10 +5189,10 @@ internal override string get_accNameInternal(object childID) internal override string get_accKeyboardShortcutInternal(object childID) { - this.ValidateChildID(ref childID); + ValidateChildID(ref childID); if (childID != null && ((int)childID) == COMBOBOX_ACC_ITEM_INDEX) { - return this.KeyboardShortcut; + return KeyboardShortcut; } else { @@ -6221,7 +6221,7 @@ private sealed class ACNativeWindow : NativeWindow internal ACNativeWindow(IntPtr acHandle) { Debug.Assert(!ACWindows.ContainsKey(acHandle)); - this.AssignHandle(acHandle); + AssignHandle(acHandle); ACWindows.Add(acHandle, this); UnsafeNativeMethods.EnumChildWindows(new HandleRef(this, acHandle), new NativeMethods.EnumChildrenCallback(ACNativeWindow.RegisterACWindowRecursive), @@ -6280,8 +6280,8 @@ protected override void WndProc(ref Message m) if (m.Msg == Interop.WindowMessages.WM_NCDESTROY) { - Debug.Assert(ACWindows.ContainsKey(this.Handle)); - ACWindows.Remove(this.Handle); //so we do not leak ac windows. + Debug.Assert(ACWindows.ContainsKey(Handle)); + ACWindows.Remove(Handle); //so we do not leak ac windows. } } @@ -6354,7 +6354,7 @@ internal void FindDropDowns(bool subclass) } // Look for a popped up dropdown shouldSubClass = subclass; - UnsafeNativeMethods.EnumThreadWindows(SafeNativeMethods.GetCurrentThreadId(), new NativeMethods.EnumThreadWindowsCallback(this.Callback), new HandleRef(null, IntPtr.Zero)); + UnsafeNativeMethods.EnumThreadWindows(SafeNativeMethods.GetCurrentThreadId(), new NativeMethods.EnumThreadWindowsCallback(Callback), new HandleRef(null, IntPtr.Zero)); } private bool Callback(IntPtr hWnd, IntPtr lParam) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Enum.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Enum.cs index e649d41d0b0..c271a64bf9a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Enum.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Enum.cs @@ -76,7 +76,7 @@ public bool IsStrictEnum { get { - return !this.allowUnknownValues; + return !allowUnknownValues; } } @@ -87,7 +87,7 @@ public virtual object[] Values { get { - return (object[])this.values.Clone(); + return (object[])values.Clone(); } } @@ -98,7 +98,7 @@ public virtual string[] Names { get { - return (string[])this.names.Clone(); + return (string[])names.Clone(); } } @@ -136,7 +136,7 @@ protected virtual void PopulateArrays(string[] names, object[] values) // setup our values...since we have to walk through // them anyway to do the ToString, we just copy them here. this.names = new string[names.Length]; - this.stringValues = new string[names.Length]; + stringValues = new string[names.Length]; this.values = new object[names.Length]; for (int i = 0; i < names.Length; i++) { @@ -145,7 +145,7 @@ protected virtual void PopulateArrays(string[] names, object[] values) this.values[i] = values[i]; if (values[i] != null) { - this.stringValues[i] = values[i].ToString(); + stringValues[i] = values[i].ToString(); } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2EnumConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2EnumConverter.cs index 1a78d2a6c0a..286babab79f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2EnumConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2EnumConverter.cs @@ -142,7 +142,7 @@ public override bool IsValid(ITypeDescriptorContext context, object value) public void RefreshValues() { - this.values = null; + values = null; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedTypeConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedTypeConverter.cs index 81a3901ff30..04c181dac64 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedTypeConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedTypeConverter.cs @@ -31,7 +31,7 @@ public Com2ExtendedTypeConverter(TypeConverter innerConverter) public Com2ExtendedTypeConverter(Type baseType) { - this.innerConverter = TypeDescriptor.GetConverter(baseType); + innerConverter = TypeDescriptor.GetConverter(baseType); } public TypeConverter InnerConverter diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedUITypeEditor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedUITypeEditor.cs index 0b6ae896036..0ef9acb7770 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedUITypeEditor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedUITypeEditor.cs @@ -28,12 +28,12 @@ internal class Com2ExtendedUITypeEditor : UITypeEditor public Com2ExtendedUITypeEditor(UITypeEditor baseTypeEditor) { - this.innerEditor = baseTypeEditor; + innerEditor = baseTypeEditor; } public Com2ExtendedUITypeEditor(Type baseType) { - this.innerEditor = (UITypeEditor)TypeDescriptor.GetEditor(baseType, typeof(UITypeEditor)); + innerEditor = (UITypeEditor)TypeDescriptor.GetEditor(baseType, typeof(UITypeEditor)); } public UITypeEditor InnerEditor diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ICategorizePropertiesHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ICategorizePropertiesHandler.cs index 7547690756d..253f8b2060b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ICategorizePropertiesHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ICategorizePropertiesHandler.cs @@ -88,7 +88,7 @@ public override void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc) } for (int i = 0; i < propDesc.Length; i++) { - propDesc[i].QueryGetBaseAttributes += new GetAttributesEventHandler(this.OnGetAttributes); + propDesc[i].QueryGetBaseAttributes += new GetAttributesEventHandler(OnGetAttributes); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IDispatchConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IDispatchConverter.cs index 7074c126e7c..6bc78ed6dcf 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IDispatchConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IDispatchConverter.cs @@ -100,7 +100,7 @@ public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContex /// public override bool GetPropertiesSupported(ITypeDescriptorContext context) { - return this.allowExpand; + return allowExpand; } // no dropdown, please! diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IManagedPerPropertyBrowsingHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IManagedPerPropertyBrowsingHandler.cs index 3145fffa20c..0bcb2788632 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IManagedPerPropertyBrowsingHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IManagedPerPropertyBrowsingHandler.cs @@ -32,7 +32,7 @@ public override void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc) } for (int i = 0; i < propDesc.Length; i++) { - propDesc[i].QueryGetDynamicAttributes += new GetAttributesEventHandler(this.OnGetAttributes); + propDesc[i].QueryGetDynamicAttributes += new GetAttributesEventHandler(OnGetAttributes); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs index b7a41fd4e77..d584b2f95c6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs @@ -31,10 +31,10 @@ public override void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc) } for (int i = 0; i < propDesc.Length; i++) { - propDesc[i].QueryGetBaseAttributes += new GetAttributesEventHandler(this.OnGetBaseAttributes); - propDesc[i].QueryGetDisplayValue += new GetNameItemEventHandler(this.OnGetDisplayValue); + propDesc[i].QueryGetBaseAttributes += new GetAttributesEventHandler(OnGetBaseAttributes); + propDesc[i].QueryGetDisplayValue += new GetNameItemEventHandler(OnGetDisplayValue); - propDesc[i].QueryGetTypeConverterAndTypeEditor += new GetTypeConverterAndTypeEditorEventHandler(this.OnGetTypeConverterAndTypeEditor); + propDesc[i].QueryGetTypeConverterAndTypeEditor += new GetTypeConverterAndTypeEditorEventHandler(OnGetTypeConverterAndTypeEditor); } } @@ -211,7 +211,7 @@ private class Com2IPerPropertyEnumConverter : Com2EnumConverter private Com2IPerPropertyBrowsingEnum itemsEnum; public Com2IPerPropertyEnumConverter(Com2IPerPropertyBrowsingEnum items) : base(items) { - this.itemsEnum = items; + itemsEnum = items; } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destType) @@ -250,11 +250,11 @@ private class Com2IPerPropertyBrowsingEnum : Com2Enum public Com2IPerPropertyBrowsingEnum(Com2PropertyDescriptor targetObject, Com2IPerPropertyBrowsingHandler handler, OleStrCAMarshaler names, Int32CAMarshaler values, bool allowUnknowns) : base(new string[0], new object[0], allowUnknowns) { - this.target = targetObject; - this.nameMarshaller = names; - this.valueMarshaller = values; + target = targetObject; + nameMarshaller = names; + valueMarshaller = values; this.handler = handler; - this.arraysFetched = false; + arraysFetched = false; } /// @@ -293,12 +293,12 @@ public override string[] Names // private void EnsureArrays() { - if (this.arraysFetched) + if (arraysFetched) { return; } - this.arraysFetched = true; + arraysFetched = true; try { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IProvidePropertyBuilderHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IProvidePropertyBuilderHandler.cs index 8600b67d6c4..6182e7792f7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IProvidePropertyBuilderHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IProvidePropertyBuilderHandler.cs @@ -61,9 +61,9 @@ public override void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc) } for (int i = 0; i < propDesc.Length; i++) { - propDesc[i].QueryGetBaseAttributes += new GetAttributesEventHandler(this.OnGetBaseAttributes); + propDesc[i].QueryGetBaseAttributes += new GetAttributesEventHandler(OnGetBaseAttributes); - propDesc[i].QueryGetTypeConverterAndTypeEditor += new GetTypeConverterAndTypeEditorEventHandler(this.OnGetTypeConverterAndTypeEditor); + propDesc[i].QueryGetTypeConverterAndTypeEditor += new GetTypeConverterAndTypeEditorEventHandler(OnGetTypeConverterAndTypeEditor); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IVsPerPropertyBrowsingHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IVsPerPropertyBrowsingHandler.cs index a42c1a98c7a..a38cbcfef4e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IVsPerPropertyBrowsingHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IVsPerPropertyBrowsingHandler.cs @@ -60,16 +60,16 @@ public override void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc) } for (int i = 0; i < propDesc.Length; i++) { - propDesc[i].QueryGetDynamicAttributes += new GetAttributesEventHandler(this.OnGetDynamicAttributes); - propDesc[i].QueryGetBaseAttributes += new GetAttributesEventHandler(this.OnGetBaseAttributes); - propDesc[i].QueryGetDisplayName += new GetNameItemEventHandler(this.OnGetDisplayName); - propDesc[i].QueryGetIsReadOnly += new GetBoolValueEventHandler(this.OnGetIsReadOnly); + propDesc[i].QueryGetDynamicAttributes += new GetAttributesEventHandler(OnGetDynamicAttributes); + propDesc[i].QueryGetBaseAttributes += new GetAttributesEventHandler(OnGetBaseAttributes); + propDesc[i].QueryGetDisplayName += new GetNameItemEventHandler(OnGetDisplayName); + propDesc[i].QueryGetIsReadOnly += new GetBoolValueEventHandler(OnGetIsReadOnly); - propDesc[i].QueryShouldSerializeValue += new GetBoolValueEventHandler(this.OnShouldSerializeValue); - propDesc[i].QueryCanResetValue += new GetBoolValueEventHandler(this.OnCanResetPropertyValue); - propDesc[i].QueryResetValue += new Com2EventHandler(this.OnResetPropertyValue); + propDesc[i].QueryShouldSerializeValue += new GetBoolValueEventHandler(OnShouldSerializeValue); + propDesc[i].QueryCanResetValue += new GetBoolValueEventHandler(OnCanResetPropertyValue); + propDesc[i].QueryResetValue += new Com2EventHandler(OnResetPropertyValue); - propDesc[i].QueryGetTypeConverterAndTypeEditor += new GetTypeConverterAndTypeEditorEventHandler(this.OnGetTypeConverterAndTypeEditor); + propDesc[i].QueryGetTypeConverterAndTypeEditor += new GetTypeConverterAndTypeEditorEventHandler(OnGetTypeConverterAndTypeEditor); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Properties.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Properties.cs index 129a037f779..aa3cddadece 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Properties.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Properties.cs @@ -102,15 +102,15 @@ public Com2Properties(object obj, Com2PropertyDescriptor[] props, int defaultInd { #if DEBUG ComNativeDescriptor cnd = new ComNativeDescriptor(); - this.dbgObjName = cnd.GetName(obj); - if (this.dbgObjName == null) + dbgObjName = cnd.GetName(obj); + if (dbgObjName == null) { - this.dbgObjName = "(null)"; + dbgObjName = "(null)"; } - this.dbgObjClass = cnd.GetClassName(obj); - if (this.dbgObjClass == null) + dbgObjClass = cnd.GetClassName(obj); + if (dbgObjClass == null) { - this.dbgObjClass = "(null)"; + dbgObjClass = "(null)"; } if (DbgCom2PropertiesSwitch.TraceVerbose) Debug.WriteLine("Creating Com2Properties for object " + dbgObjName + ", class=" + dbgObjClass); @@ -132,7 +132,7 @@ internal bool AlwaysValid { get { - return this.alwaysValid > 0; + return alwaysValid > 0; } set { @@ -142,13 +142,13 @@ internal bool AlwaysValid { return; } - this.alwaysValid++; + alwaysValid++; } else { if (alwaysValid > 0) { - this.alwaysValid--; + alwaysValid--; } } } @@ -269,7 +269,7 @@ public bool TooOld public void AddExtendedBrowsingHandlers(Hashtable handlers) { - object target = this.TargetObject; + object target = TargetObject; if (target == null) { return; @@ -504,7 +504,7 @@ private unsafe long GetTypeInfoVersion(UnsafeNativeMethods.ITypeInfo pTypeInfo) internal bool CheckValid(bool checkVersions, bool callDispose) { - if (this.AlwaysValid) + if (AlwaysValid) { return true; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyBuilderUITypeEditor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyBuilderUITypeEditor.cs index 2aaf928a256..5c75632b47f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyBuilderUITypeEditor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyBuilderUITypeEditor.cs @@ -29,7 +29,7 @@ public Com2PropertyBuilderUITypeEditor(Com2PropertyDescriptor pd, string guidStr { propDesc = pd; this.guidString = guidString; - this.bldrType = type; + bldrType = type; } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs index 92f6699c189..9019722d925 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs @@ -150,10 +150,10 @@ static Com2PropertyDescriptor() public Com2PropertyDescriptor(int dispid, string name, Attribute[] attrs, bool readOnly, Type propType, object typeData, bool hrHidden) : base(name, attrs) { - this.baseReadOnly = readOnly; + baseReadOnly = readOnly; this.readOnly = readOnly; - this.baseAttrs = attrs; + baseAttrs = attrs; SetNeedsRefresh(Com2PropertyDescriptorRefresh.BaseAttributes, true); this.hrHidden = hrHidden; @@ -161,7 +161,7 @@ public Com2PropertyDescriptor(int dispid, string name, Attribute[] attrs, bool r // readonly to begin with are always read only SetNeedsRefresh(Com2PropertyDescriptorRefresh.ReadOnly, readOnly); - this.propertyType = propType; + propertyType = propType; this.dispid = dispid; @@ -179,7 +179,7 @@ public Com2PropertyDescriptor(int dispid, string name, Attribute[] attrs, bool r } // check if this thing is hidden from metadata - this.canShow = true; + canShow = true; if (attrs != null) { @@ -187,15 +187,15 @@ public Com2PropertyDescriptor(int dispid, string name, Attribute[] attrs, bool r { if (attrs[i].Equals(BrowsableAttribute.No) && !hrHidden) { - this.canShow = false; + canShow = false; break; } } } - if (this.canShow && (propType == typeof(object) || (valueConverter == null && propType == typeof(UnsafeNativeMethods.IDispatch)))) + if (canShow && (propType == typeof(object) || (valueConverter == null && propType == typeof(UnsafeNativeMethods.IDispatch)))) { - this.typeHide = true; + typeHide = true; } } @@ -221,12 +221,12 @@ protected Attribute[] BaseAttributes if (attrList.Count != baseCount) { - this.baseAttrs = new Attribute[attrList.Count]; + baseAttrs = new Attribute[attrList.Count]; } if (baseAttrs != null) { - attrList.CopyTo(this.baseAttrs, 0); + attrList.CopyTo(baseAttrs, 0); } else { @@ -249,13 +249,13 @@ public override AttributeCollection Attributes { get { - if (this.AttributesValid || this.InAttrQuery) + if (AttributesValid || InAttrQuery) { return base.Attributes; } // restore our base attributes - this.AttributeArray = this.BaseAttributes; + AttributeArray = BaseAttributes; ArrayList newAttributes = null; @@ -271,10 +271,10 @@ public override AttributeCollection Attributes else if (hrHidden) { // check to see if the get still fails - object target = this.TargetObject; + object target = TargetObject; if (target != null) { - int hr = new ComNativeDescriptor().GetPropertyValue(target, this.dispid, new object[1]); + int hr = new ComNativeDescriptor().GetPropertyValue(target, dispid, new object[1]); // if not, go ahead and make this a browsable item if (NativeMethods.Succeeded(hr)) @@ -290,7 +290,7 @@ public override AttributeCollection Attributes } } - this.inAttrQuery = true; + inAttrQuery = true; try { @@ -315,7 +315,7 @@ public override AttributeCollection Attributes } finally { - this.inAttrQuery = false; + inAttrQuery = false; } // these are now valid. @@ -362,7 +362,7 @@ public bool CanShow { get { - return this.canShow; + return canShow; } } @@ -395,7 +395,7 @@ public override TypeConverter Converter if (!TypeEditorValid) { - this.editor = typeEd; + editor = typeEd; SetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeEditor, false); } SetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeConverter, false); @@ -433,7 +433,7 @@ public int DISPID { get { - return this.dispid; + return dispid; } } @@ -445,14 +445,14 @@ public override string DisplayName { get { - if (!this.DisplayNameValid) + if (!DisplayNameValid) { GetNameItemEvent gni = new GetNameItemEvent(base.DisplayName); OnGetDisplayName(gni); - this.displayName = gni.NameString; + displayName = gni.NameString; SetNeedsRefresh(Com2PropertyDescriptorRefresh.DisplayName, false); } - return this.displayName; + return displayName; } } @@ -492,7 +492,7 @@ protected bool InAttrQuery { get { - return this.inAttrQuery; + return inAttrQuery; } } @@ -503,15 +503,15 @@ public override bool IsReadOnly { get { - if (!this.ReadOnlyValid) + if (!ReadOnlyValid) { - this.readOnly |= (this.Attributes[typeof(ReadOnlyAttribute)].Equals(ReadOnlyAttribute.Yes)); - GetBoolValueEvent gbv = new GetBoolValueEvent(this.readOnly); + readOnly |= (Attributes[typeof(ReadOnlyAttribute)].Equals(ReadOnlyAttribute.Yes)); + GetBoolValueEvent gbv = new GetBoolValueEvent(readOnly); OnGetIsReadOnly(gbv); - this.readOnly = gbv.Value; + readOnly = gbv.Value; SetNeedsRefresh(Com2PropertyDescriptorRefresh.ReadOnly, false); } - return this.readOnly; + return readOnly; } } @@ -519,11 +519,11 @@ internal Com2Properties PropertyManager { set { - this.com2props = value; + com2props = value; } get { - return this.com2props; + return com2props; } } @@ -691,7 +691,7 @@ public override bool CanResetValue(object component) component = ((ICustomTypeDescriptor)component).GetPropertyOwner(this); } - if (component == this.TargetObject) + if (component == TargetObject) { GetBoolValueEvent gbv = new GetBoolValueEvent(false); OnCanResetValue(gbv); @@ -702,7 +702,7 @@ public override bool CanResetValue(object component) public object Clone() { - return new Com2PropertyDescriptor(this.dispid, this.Name, (Attribute[])this.baseAttrs.Clone(), this.readOnly, this.propertyType, this.typeData, this.hrHidden); + return new Com2PropertyDescriptor(dispid, Name, (Attribute[])baseAttrs.Clone(), readOnly, propertyType, typeData, hrHidden); } /// @@ -780,7 +780,7 @@ private TypeConverter GetBaseTypeConverter() // we don't want to create the value editor for the IDispatch props because // that will create the reference editor. We don't want that guy! // - if (!typeof(UnsafeNativeMethods.IDispatch).IsAssignableFrom(this.PropertyType)) + if (!typeof(UnsafeNativeMethods.IDispatch).IsAssignableFrom(PropertyType)) { localConverter = base.Converter; } @@ -878,7 +878,7 @@ public override object GetEditor(Type editorBaseType) if (!TypeConverterValid) { - this.converter = c; + converter = c; SetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeConverter, false); } SetNeedsRefresh(Com2PropertyDescriptorRefresh.TypeEditor, false); @@ -914,7 +914,7 @@ public object GetNativeValue(object component) NativeMethods.tagEXCEPINFO pExcepInfo = new NativeMethods.tagEXCEPINFO(); Guid g = Guid.Empty; - int hr = pDisp.Invoke(this.dispid, + int hr = pDisp.Invoke(dispid, ref g, SafeNativeMethods.GetThreadLCID(), NativeMethods.DISPATCH_PROPERTYGET, @@ -962,7 +962,7 @@ public override object GetValue(object component) { lastValue = GetNativeValue(component); // do we need to convert the type? - if (this.ConvertingNativeType && lastValue != null) + if (ConvertingNativeType && lastValue != null) { lastValue = valueConverter.ConvertNativeToManaged(lastValue, this); } @@ -1010,7 +1010,7 @@ public void GetTypeConverterAndTypeEditor(ref TypeConverter typeConverter, Type // if this is a object, get the value and attempt to create the correct value editor based on that value. // we don't do this if the state came from an attribute // - if (0 == (refreshState & Com2PropertyDescriptorRefresh.TypeConverterAttr) && this.PropertyType == typeof(Com2Variant)) + if (0 == (refreshState & Com2PropertyDescriptorRefresh.TypeConverterAttr) && PropertyType == typeof(Com2Variant)) { Type editorType = PropertyType; object value = GetValue(TargetObject); @@ -1246,7 +1246,7 @@ public override void ResetValue(object component) component = ((ICustomTypeDescriptor)component).GetPropertyOwner(this); } - if (component == this.TargetObject) + if (component == TargetObject) { OnResetValue(EventArgs.Empty); } @@ -1278,9 +1278,9 @@ internal void SetNeedsRefresh(int mask, bool value) public override void SetValue(object component, object value) { - if (this.readOnly) + if (readOnly) { - throw new NotSupportedException(string.Format(SR.COM2ReadonlyProperty, this.Name)); + throw new NotSupportedException(string.Format(SR.COM2ReadonlyProperty, Name)); } object owner = component; @@ -1327,7 +1327,7 @@ public override void SetValue(object component, object value) { Guid g = Guid.Empty; - int hr = pDisp.Invoke(this.dispid, + int hr = pDisp.Invoke(dispid, ref g, SafeNativeMethods.GetThreadLCID(), NativeMethods.DISPATCH_PROPERTYPUT, @@ -1515,7 +1515,7 @@ public override bool GetPropertiesSupported(ITypeDescriptorContext context) { // special case the font converter here. // - if ((pd.valueConverter != null && pd.valueConverter.AllowExpand) || Com2IVsPerPropertyBrowsingHandler.AllowChildProperties(this.pd)) + if ((pd.valueConverter != null && pd.valueConverter.AllowExpand) || Com2IVsPerPropertyBrowsingHandler.AllowChildProperties(pd)) { subprops = AllowSubprops; } @@ -1552,7 +1552,7 @@ internal class GetNameItemEvent : EventArgs public GetNameItemEvent(object defName) { - this.nameItem = defName; + nameItem = defName; } public object Name @@ -1588,7 +1588,7 @@ internal class GetBoolValueEvent : EventArgs public GetBoolValueEvent(bool defValue) { - this.value = defValue; + value = defValue; } public bool Value diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyPageUITypeConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyPageUITypeConverter.cs index c9ddea2ad41..4ca04124502 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyPageUITypeConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyPageUITypeConverter.cs @@ -63,7 +63,7 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide } } - propPageSvc.ShowPropertyPage(propDesc.Name, instance, propDesc.DISPID, this.guid, hWndParent); + propPageSvc.ShowPropertyPage(propDesc.Name, instance, propDesc.DISPID, guid, hWndParent); } catch (Exception ex1) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs index 08d2506cbae..543ccfcda7e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs @@ -1103,9 +1103,9 @@ internal class CachedProperties internal CachedProperties(PropertyDescriptor[] props, int defIndex, int majVersion, int minVersion) { this.props = ClonePropertyDescriptors(props); - this.MajorVersion = majVersion; - this.MinorVersion = minVersion; - this.defaultIndex = defIndex; + MajorVersion = majVersion; + MinorVersion = minVersion; + defaultIndex = defIndex; } public PropertyDescriptor[] Properties diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs index 196a6e1a6a5..2fc024c1486 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs @@ -233,8 +233,8 @@ public virtual AutoValidate AutoValidate ] public event EventHandler AutoValidateChanged { - add => this.autoValidateChanged += value; - remove => this.autoValidateChanged -= value; + add => autoValidateChanged += value; + remove => autoValidateChanged -= value; } /// @@ -409,13 +409,13 @@ internal bool ActivateControlInternal(Control control) internal bool ActivateControlInternal(Control control, bool originator) { - Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "ContainerControl::ActivateControlInternal(" + (control == null ? "null" : control.Name) + "," + originator.ToString() + ") - " + this.Name); + Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "ContainerControl::ActivateControlInternal(" + (control == null ? "null" : control.Name) + "," + originator.ToString() + ") - " + Name); // Recursive function that makes sure that the chain of active controls // is coherent. bool ret = true; bool updateContainerActiveControl = false; ContainerControl cc = null; - Control parent = this.ParentInternal; + Control parent = ParentInternal; if (parent != null) { cc = (parent.GetContainerControl()) as ContainerControl; @@ -484,17 +484,17 @@ internal virtual void AfterControlRemoved(Control control, Control oldParent) { ContainerControl cc; Debug.Assert(control != null); - Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "ContainerControl::AfterControlRemoved(" + control.Name + ") - " + this.Name); + Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "ContainerControl::AfterControlRemoved(" + control.Name + ") - " + Name); if (control == activeControl || control.Contains(activeControl)) { bool selected = SelectNextControl(control, true, true, true, true); - if (selected && this.activeControl != control) + if (selected && activeControl != control) { // Add the check. If it is set to true, do not call into FocusActiveControlInternal(). // The TOP MDI window could be gone and CreateHandle method will fail // because it try to create a parking window Parent for the MDI children - if (!this.activeControl.Parent.IsTopMdiWindowClosing) + if (!activeControl.Parent.IsTopMdiWindowClosing) { FocusActiveControlInternal(); } @@ -558,7 +558,7 @@ private bool AssignActiveControlInternal(Control value) } #endif - Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "ContainerControl::AssignActiveControlInternal(" + (value == null ? "null" : value.Name) + ") - " + this.Name); + Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "ContainerControl::AssignActiveControlInternal(" + (value == null ? "null" : value.Name) + ") - " + Name); if (activeControl != value) { // cpb: #7318 @@ -627,7 +627,7 @@ internal override bool CanProcessMnemonic() #if DEBUG TraceCanProcessMnemonic(); #endif - if (this.state[stateProcessingMnemonic]) + if (state[stateProcessingMnemonic]) { return true; } @@ -683,10 +683,10 @@ private void EnableRequiredScaling(Control start, bool enable) /// internal void FocusActiveControlInternal() { - Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "ContainerControl::FocusActiveControlInternal() - " + this.Name); + Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "ContainerControl::FocusActiveControlInternal() - " + Name); #if DEBUG // Things really get ugly if you try to pop up an assert dialog here - if (activeControl != null && !this.Contains(activeControl)) + if (activeControl != null && !Contains(activeControl)) Debug.WriteLine("ActiveControl is not a child of this ContainerControl"); #endif @@ -734,13 +734,13 @@ internal override Size GetPreferredSizeCore(Size proposedSize) internal override Rectangle GetToolNativeScreenRectangle() { - if (this.GetTopLevel()) + if (GetTopLevel()) { // Get window's client rectangle (i.e. without chrome) expressed in screen coordinates NativeMethods.RECT clientRectangle = new NativeMethods.RECT(); - UnsafeNativeMethods.GetClientRect(new HandleRef(this, this.Handle), ref clientRectangle); + UnsafeNativeMethods.GetClientRect(new HandleRef(this, Handle), ref clientRectangle); NativeMethods.POINT topLeftPoint = new NativeMethods.POINT(0, 0); - UnsafeNativeMethods.ClientToScreen(new HandleRef(this, this.Handle), topLeftPoint); + UnsafeNativeMethods.ClientToScreen(new HandleRef(this, Handle), topLeftPoint); return new Rectangle(topLeftPoint.x, topLeftPoint.y, clientRectangle.right, clientRectangle.bottom); } else @@ -1323,7 +1323,7 @@ protected internal override bool ProcessMnemonic(char charCode) // Set the processing mnemonic flag so child controls don't check for it when checking if they // can process the mnemonic. - this.state[stateProcessingMnemonic] = true; + state[stateProcessingMnemonic] = true; bool processed = false; @@ -1382,7 +1382,7 @@ protected internal override bool ProcessMnemonic(char charCode) } finally { - this.state[stateProcessingMnemonic] = false; + state[stateProcessingMnemonic] = false; } Debug.Unindent(); @@ -1542,7 +1542,7 @@ protected virtual void UpdateDefaultButton() /// internal void UpdateFocusedControl() { - Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "ContainerControl::UpdateFocusedControl() - " + this.Name); + Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "ContainerControl::UpdateFocusedControl() - " + Name); // Capture the current focusedControl as the unvalidatedControl if we don't have one/are not validating. EnsureUnvalidatedControl(focusedControl); @@ -1809,7 +1809,7 @@ internal bool ValidateInternal(bool checkAutoValidate, out bool validatedControl { validatedControlAllowsFocusChange = false; - if (this.AutoValidate == AutoValidate.EnablePreventFocusChange || + if (AutoValidate == AutoValidate.EnablePreventFocusChange || (activeControl != null && activeControl.CausesValidation)) { if (unvalidatedControl == null) @@ -1895,7 +1895,7 @@ private bool ValidateThroughAncestor(Control ancestorControl, bool preventFocusC if (!ancestorControl.IsDescendant(unvalidatedControl)) return false; - this.state[stateValidating] = true; + state[stateValidating] = true; bool cancel = false; Control currentActiveControl = activeControl; @@ -1977,7 +1977,7 @@ private void ResetValidationFlag() // PERFNOTE: This is more efficient than using Foreach. Foreach // forces the creation of an array subset enum each time we // enumerate - Control.ControlCollection children = this.Controls; + Control.ControlCollection children = Controls; int count = children.Count; for (int i = 0; i < count; i++) { @@ -2006,7 +2006,7 @@ internal virtual bool ShouldSerializeAutoValidate() /// private void WmSetFocus(ref Message m) { - Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "ContainerControl::WmSetFocus() - " + this.Name); + Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "ContainerControl::WmSetFocus() - " + Name); if (!HostedInWin32DialogManager) { if (ActiveControl != null) @@ -2016,7 +2016,7 @@ private void WmSetFocus(ref Message m) // is given to the visible ActiveControl if (!ActiveControl.Visible) { - this.InvokeGotFocus(this, EventArgs.Empty); + InvokeGotFocus(this, EventArgs.Empty); } FocusActiveControlInternal(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenuStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenuStrip.cs index 855f2b10782..d78fbb82a29 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenuStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenuStrip.cs @@ -63,7 +63,7 @@ internal ContextMenuStrip Clone() ContextMenuStrip contextMenuStrip = new ContextMenuStrip(); // copy over events - contextMenuStrip.Events.AddHandlers(this.Events); + contextMenuStrip.Events.AddHandlers(Events); contextMenuStrip.AutoClose = AutoClose; contextMenuStrip.AutoSize = AutoSize; 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 24b69e378ca..89b531f0463 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs @@ -110,7 +110,7 @@ internal void TraceCanProcessMnemonic() string str; try { - str = string.Format(CultureInfo.CurrentCulture, "{0}<{1}>", this.GetType().Name, this.Text); + str = string.Format(CultureInfo.CurrentCulture, "{0}<{1}>", GetType().Name, Text); int maxFrameCount = new StackTrace().FrameCount; if (maxFrameCount > 5) { @@ -481,8 +481,8 @@ 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!"); + Debug.Assert(GetType().BaseType != typeof(Control), "Direct derivative of Control Created: " + GetType().FullName); + Debug.Assert(GetType() != typeof(Control), "Control Created!"); } #endif propertyStore = new PropertyStore(); @@ -575,8 +575,8 @@ public Control(string text, int left, int top, int width, int height) : /// public Control(Control parent, string text) : this() { - this.Parent = parent; - this.Text = text; + Parent = parent; + Text = text; } /// @@ -584,8 +584,8 @@ public Control(Control parent, string text) : this() /// 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); + Location = new Point(left, top); + Size = new Size(width, height); } /// @@ -661,15 +661,15 @@ private AccessibleObject GetAccessibilityObject(int accObjId) switch (accObjId) { case NativeMethods.OBJID_CLIENT: - accessibleObject = this.AccessibilityObject; + accessibleObject = AccessibilityObject; break; case NativeMethods.OBJID_WINDOW: - accessibleObject = this.NcAccessibilityObject; + accessibleObject = NcAccessibilityObject; break; default: if (accObjId > 0) { - accessibleObject = this.GetAccessibilityObjectById(accObjId); + accessibleObject = GetAccessibilityObjectById(accObjId); } else { @@ -688,7 +688,7 @@ protected virtual AccessibleObject GetAccessibilityObjectById(int objectId) { if (this is IAutomationLiveRegion) { - return this.AccessibilityObject; + return AccessibilityObject; } return null; @@ -1290,7 +1290,7 @@ internal bool BecomingActiveControl } set { - if (value != this.BecomingActiveControl) + if (value != BecomingActiveControl) { Application.ThreadContext.FromCurrent().ActivatingControl = (value) ? this : null; SetState2(STATE2_BECOMINGACTIVECONTROL, value); @@ -1300,7 +1300,7 @@ internal bool BecomingActiveControl private bool ShouldSerializeAccessibleName() { - string accName = this.AccessibleName; + string accName = AccessibleName; return accName != null && accName.Length > 0; } @@ -1558,7 +1558,7 @@ public bool CausesValidation } set { - if (value != this.CausesValidation) + if (value != CausesValidation) { SetState(STATE_CAUSESVALIDATION, value); OnCausesValidationChanged(EventArgs.Empty); @@ -1735,12 +1735,12 @@ public bool ContainsFocus return false; } - if (focusHwnd == this.Handle) + if (focusHwnd == Handle) { return true; } - if (UnsafeNativeMethods.IsChild(new HandleRef(this, this.Handle), new HandleRef(this, focusHwnd))) + if (UnsafeNativeMethods.IsChild(new HandleRef(this, Handle), new HandleRef(this, focusHwnd))) { return true; } @@ -1988,7 +1988,7 @@ protected virtual CreateParams CreateParams internal virtual void NotifyValidationResult(object sender, CancelEventArgs ev) { - this.ValidationCancelled = ev.Cancel; + ValidationCancelled = ev.Cancel; } /// @@ -2007,7 +2007,7 @@ internal bool ValidateActiveControl(out bool validatedControlAllowsFocusChange) bool valid = true; validatedControlAllowsFocusChange = false; IContainerControl c = GetContainerControl(); - if (c != null && this.CausesValidation) + if (c != null && CausesValidation) { ContainerControl container = c as ContainerControl; if (container != null) @@ -2055,7 +2055,7 @@ internal bool ValidationCancelled } else { - Control parent = this.ParentInternal; + Control parent = ParentInternal; if (parent != null) { return parent.ValidationCancelled; @@ -2712,7 +2712,7 @@ internal void ScaleFont(float factor) { Font local = (Font)Properties.GetObject(PropFont); Font resolved = Font; - Font newFont = new Font(this.Font.FontFamily, this.Font.Size * factor, this.Font.Style); + Font newFont = new Font(Font.FontFamily, Font.Size * factor, Font.Style); if ((local == null) || !local.Equals(newFont)) { @@ -3851,7 +3851,7 @@ internal bool RenderTransparent { get { - return GetStyle(ControlStyles.SupportsTransparentBackColor) && this.BackColor.A < 255; + return GetStyle(ControlStyles.SupportsTransparentBackColor) && BackColor.A < 255; } } @@ -4304,7 +4304,7 @@ public virtual string Text WindowText = value; OnTextChanged(EventArgs.Empty); - if (this.IsMnemonicsListenerAxSourced) + if (IsMnemonicsListenerAxSourced) { for (Control ctl = this; ctl != null; ctl = ctl.ParentInternal) { @@ -5575,7 +5575,7 @@ internal virtual void AssignParent(Control value) { OnRightToLeftChanged(EventArgs.Empty); } - if (Properties.GetObject(PropBindingManager) == null && this.Created) + if (Properties.GetObject(PropBindingManager) == null && 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, @@ -5689,14 +5689,14 @@ internal virtual bool CanProcessMnemonic() #if DEBUG TraceCanProcessMnemonic(); #endif - if (!this.Enabled || !this.Visible) + if (!Enabled || !Visible) { return false; } - if (this.parent != null) + if (parent != null) { - return this.parent.CanProcessMnemonic(); + return parent.CanProcessMnemonic(); } return true; @@ -5840,7 +5840,7 @@ public System.Drawing.Graphics CreateGraphics() internal System.Drawing.Graphics CreateGraphicsInternal() { - return Graphics.FromHwndInternal(this.Handle); + return Graphics.FromHwndInternal(Handle); } /// @@ -5871,7 +5871,7 @@ protected virtual void CreateHandle() { SetState(STATE_CREATINGHANDLE, true); - originalBounds = this.Bounds; + originalBounds = Bounds; if (Application.UseVisualStyles) { @@ -5924,7 +5924,7 @@ protected virtual void CreateHandle() // 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) + if (Bounds != originalBounds) { LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.Bounds); } @@ -5936,7 +5936,7 @@ protected virtual void CreateHandle() /// public void CreateControl() { - bool controlIsAlreadyCreated = this.Created; + bool controlIsAlreadyCreated = Created; CreateControl(false); if (Properties.GetObject(PropBindingManager) == null && ParentInternal != null && !controlIsAlreadyCreated) @@ -6130,7 +6130,7 @@ protected override void Dispose(bool disposing) } SetState(STATE_DISPOSING, true); - this.SuspendLayout(); + SuspendLayout(); try { DisposeAxControls(); @@ -6172,7 +6172,7 @@ protected override void Dispose(bool disposing) } finally { - this.ResumeLayout(false); + ResumeLayout(false); SetState(STATE_DISPOSING, false); SetState(STATE_DISPOSED, true); } @@ -6296,8 +6296,8 @@ public void DrawToBitmap(Bitmap bitmap, Rectangle targetBounds) } - int width = Math.Min(this.Width, targetBounds.Width); - int height = Math.Min(this.Height, targetBounds.Height); + int width = Math.Min(Width, targetBounds.Width); + int height = Math.Min(Height, targetBounds.Height); using (Bitmap image = new Bitmap(width, height, bitmap.PixelFormat)) { @@ -6305,7 +6305,7 @@ public void DrawToBitmap(Bitmap bitmap, Rectangle targetBounds) { IntPtr hDc = g.GetHdc(); //send the actual wm_print message - UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), Interop.WindowMessages.WM_PRINT, (IntPtr)hDc, + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.WindowMessages.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. @@ -6507,14 +6507,14 @@ public bool Focus() /// private protected virtual bool FocusInternal() { - Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Control::FocusInternal - " + this.Name); + Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Control::FocusInternal - " + Name); if (CanFocus) { UnsafeNativeMethods.SetFocus(new HandleRef(this, Handle)); } - if (Focused && this.ParentInternal != null) + if (Focused && ParentInternal != null) { - IContainerControl c = this.ParentInternal.GetContainerControl(); + IContainerControl c = ParentInternal.GetContainerControl(); if (c != null) { @@ -6977,7 +6977,7 @@ private static ArrayList GetChildWindows(IntPtr hWndParent) private ArrayList GetChildWindowsTabOrderList() { ArrayList holders = new ArrayList(); - ArrayList windows = GetChildWindows(this.Handle); + ArrayList windows = GetChildWindows(Handle); foreach (IntPtr hWnd in windows) { @@ -6994,7 +6994,7 @@ private ArrayList GetChildWindowsTabOrderList() internal virtual Control GetFirstChildControlInTabOrder(bool forward) { - ControlCollection ctlControls = (ControlCollection)this.Properties.GetObject(PropControlsCollection); + ControlCollection ctlControls = (ControlCollection)Properties.GetObject(PropControlsCollection); Control found = null; if (ctlControls != null) @@ -7490,7 +7490,7 @@ public void Invalidate(bool invalidateChildren) } } - NotifyInvalidate(this.ClientRectangle); + NotifyInvalidate(ClientRectangle); } } @@ -7962,13 +7962,13 @@ private void ListenToUserPreferenceChanged(bool listen) if (!listen) { SetState2(STATE2_LISTENINGTOUSERPREFERENCECHANGED, false); - SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(this.UserPreferenceChanged); + SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(UserPreferenceChanged); } } else if (listen) { SetState2(STATE2_LISTENINGTOUSERPREFERENCECHANGED, true); - SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(this.UserPreferenceChanged); + SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(UserPreferenceChanged); } } @@ -8147,14 +8147,14 @@ private void MarshalStringToMessage(string value, ref Message m) // Used by form to notify the control that it has been "entered" internal void NotifyEnter() { - Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Control::NotifyEnter() - " + this.Name); + Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Control::NotifyEnter() - " + 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); + Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Control::NotifyLeave() - " + Name); OnLeave(EventArgs.Empty); } @@ -8650,7 +8650,7 @@ internal virtual void OnParentHandleRecreated() { if (IsHandleCreated) { - UnsafeNativeMethods.SetParent(new HandleRef(this, this.Handle), new HandleRef(parent, parent.Handle)); + UnsafeNativeMethods.SetParent(new HandleRef(this, Handle), new HandleRef(parent, parent.Handle)); UpdateZOrder(); } } @@ -8681,7 +8681,7 @@ internal virtual void OnParentHandleRecreating() // use SetParent directly so as to not raise ParentChanged events if (IsHandleCreated) { - Application.ParkHandle(new HandleRef(this, this.Handle)); + Application.ParkHandle(new HandleRef(this, Handle)); } } @@ -8772,7 +8772,7 @@ protected virtual void OnPrint(PaintEventArgs e) hdc = e.Graphics.GetHdc(); releaseDC = true; } - m = Message.Create(this.Handle, Interop.WindowMessages.WM_PRINTCLIENT, hdc, flags); + m = Message.Create(Handle, Interop.WindowMessages.WM_PRINTCLIENT, hdc, flags); } else { @@ -8835,7 +8835,7 @@ protected virtual void OnTextChanged(EventArgs e) protected virtual void OnVisibleChanged(EventArgs e) { Contract.Requires(e != null); - bool visible = this.Visible; + bool visible = Visible; if (visible) { UnhookMouseEvent(); @@ -8978,7 +8978,7 @@ protected virtual void OnCreateControl() protected virtual void OnHandleCreated(EventArgs e) { Contract.Requires(e != null); - if (this.IsHandleCreated) + if (IsHandleCreated) { // Setting fonts is for some reason incredibly expensive. @@ -8988,7 +8988,7 @@ protected virtual void OnHandleCreated(EventArgs e) SetWindowFont(); } - if (DpiHelper.IsPerMonitorV2Awareness && !(typeof(Form).IsAssignableFrom(this.GetType()))) + if (DpiHelper.IsPerMonitorV2Awareness && !(typeof(Form).IsAssignableFrom(GetType()))) { int old = deviceDpi; deviceDpi = (int)UnsafeNativeMethods.GetDpiForWindow(new HandleRef(this, HandleInternal)); @@ -9054,7 +9054,7 @@ protected virtual void OnHandleCreated(EventArgs e) if (!(this is ScrollableControl) && !IsMirrored && GetState2(STATE2_SETSCROLLPOS) && !GetState2(STATE2_HAVEINVOKED)) { - BeginInvoke(new EventHandler(this.OnSetScrollPosition)); + BeginInvoke(new EventHandler(OnSetScrollPosition)); SetState2(STATE2_HAVEINVOKED, true); SetState2(STATE2_SETSCROLLPOS, false); } @@ -9070,7 +9070,7 @@ protected virtual void OnHandleCreated(EventArgs e) if (handler != null) handler(this, e); - if (this.IsHandleCreated) + if (IsHandleCreated) { // Now, repost the thread callback message if we found it. We should do // this last, so we're as close to the same state as when the message @@ -9718,18 +9718,18 @@ private void OnParentInvalidated(InvalidateEventArgs e) if (!RenderTransparent) return; - if (this.IsHandleCreated) + if (IsHandleCreated) { // move invalid rect into child space Rectangle cliprect = e.InvalidRect; - Point offs = this.Location; + Point offs = Location; cliprect.Offset(-offs.X, -offs.Y); - cliprect = Rectangle.Intersect(this.ClientRectangle, cliprect); + cliprect = Rectangle.Intersect(ClientRectangle, cliprect); // if we don't intersect at all, do nothing if (cliprect.IsEmpty) return; - this.Invalidate(cliprect); + Invalidate(cliprect); } } @@ -9903,7 +9903,7 @@ protected virtual void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew // which does all painting under OnPaint, and tries very hard to avoid double-painting the border pixels. internal void PaintBackground(PaintEventArgs e, Rectangle rectangle) { - PaintBackground(e, rectangle, this.BackColor, Point.Empty); + PaintBackground(e, rectangle, BackColor, Point.Empty); } internal void PaintBackground(PaintEventArgs e, Rectangle rectangle, Color backColor) @@ -9919,7 +9919,7 @@ internal void PaintBackground(PaintEventArgs e, Rectangle rectangle, Color backC } //If the form or mdiclient is mirrored then we do not render the background image due to GDI+ issues. - bool formRTL = ((this is Form || this is MdiClient) && this.IsMirrored); + bool formRTL = ((this is Form || this is MdiClient) && IsMirrored); // The rest of this won't do much if BackColor is transparent and there is no BackgroundImage, // but we need to call it in the partial alpha case. @@ -10099,7 +10099,7 @@ internal void PaintTransparentBackground(PaintEventArgs e, Rectangle rectangle) internal void PaintTransparentBackground(PaintEventArgs e, Rectangle rectangle, Region transparentRegion) { Graphics g = e.Graphics; - Control parent = this.ParentInternal; + Control parent = ParentInternal; if (parent != null) { @@ -10138,14 +10138,14 @@ internal void PaintTransparentBackground(PaintEventArgs e, Rectangle rectangle, { // how to move the rendering area and setup it's size // (we want to translate it to the parent's origin) - Rectangle shift = new Rectangle(-this.Left, -this.Top, parent.Width, parent.Height); + Rectangle shift = new Rectangle(-Left, -Top, parent.Width, parent.Height); // moving the clipping rectangle to the parent coordinate system - Rectangle newClipRect = new Rectangle(rectangle.Left + this.Left, rectangle.Top + this.Top, rectangle.Width, rectangle.Height); + Rectangle newClipRect = new Rectangle(rectangle.Left + Left, rectangle.Top + Top, rectangle.Width, rectangle.Height); using (WindowsGraphics wg = WindowsGraphics.FromGraphics(g)) { - wg.DeviceContext.TranslateTransform(-this.Left, -this.Top); + wg.DeviceContext.TranslateTransform(-Left, -Top); using (PaintEventArgs np = new PaintEventArgs(wg.GetHdc(), newClipRect)) { if (transparentRegion != null) @@ -10237,7 +10237,7 @@ internal ContainerControl ParentContainerControl { get { - for (Control c = this.ParentInternal; c != null; c = c.ParentInternal) + for (Control c = ParentInternal; c != null; c = c.ParentInternal) { if (c is ContainerControl) { @@ -10363,14 +10363,14 @@ internal bool PerformControlValidation(bool bulkValidation) { // Skip validation for controls that don't support it - if (!this.CausesValidation) + if (!CausesValidation) { return false; } // Raise the 'Validating' event. Stop now if handler cancels (ie. control is invalid). // NOTE: Handler may throw an exception here, but we must not attempt to catch it. - if (this.NotifyValidating()) + if (NotifyValidating()) { return true; } @@ -10380,13 +10380,13 @@ internal bool PerformControlValidation(bool bulkValidation) // or the control is being validated as part of a bulk validation operation. if (bulkValidation || NativeWindow.WndProcShouldBeDebuggable) { - this.NotifyValidated(); + NotifyValidated(); } else { try { - this.NotifyValidated(); + NotifyValidated(); } catch (Exception e) { @@ -10710,7 +10710,7 @@ private void PrintToMetaFile(HandleRef hDC, IntPtr lParam) bool success = SafeNativeMethods.GetViewportOrgEx(hDC, viewportOrg); Debug.Assert(success, "GetViewportOrgEx() failed."); - HandleRef hClippingRegion = new HandleRef(null, SafeNativeMethods.CreateRectRgn(viewportOrg.x, viewportOrg.y, viewportOrg.x + this.Width, viewportOrg.y + this.Height)); + HandleRef hClippingRegion = new HandleRef(null, SafeNativeMethods.CreateRectRgn(viewportOrg.x, viewportOrg.y, viewportOrg.x + Width, viewportOrg.y + Height)); Debug.Assert(hClippingRegion.Handle != IntPtr.Zero, "CreateRectRgn() failed."); try @@ -10721,7 +10721,7 @@ private void PrintToMetaFile(HandleRef hDC, IntPtr lParam) selectResult == NativeMethods.RegionFlags.NULLREGION), "SIMPLEREGION or NULLLREGION expected."); - PrintToMetaFileRecursive(hDC, lParam, new Rectangle(Point.Empty, this.Size)); + PrintToMetaFileRecursive(hDC, lParam, new Rectangle(Point.Empty, Size)); } finally { @@ -10741,7 +10741,7 @@ internal virtual void PrintToMetaFileRecursive(HandleRef hDC, IntPtr lParam, Rec // figure out mapping for the client area NativeMethods.RECT windowRect = new NativeMethods.RECT(); - bool success = UnsafeNativeMethods.GetWindowRect(new HandleRef(null, this.Handle), ref windowRect); + bool success = UnsafeNativeMethods.GetWindowRect(new HandleRef(null, Handle), ref windowRect); Debug.Assert(success, "GetWindowRect() failed."); Point clientOffset = PointToScreen(Point.Empty); clientOffset = new Point(clientOffset.X - windowRect.left, clientOffset.Y - windowRect.top); @@ -10787,7 +10787,7 @@ private void PrintToMetaFile_SendPrintMessage(HandleRef hDC, IntPtr lParam) // System controls must be painted into a temporary bitmap // which is then copied into the metafile. (Old GDI line drawing // is 1px thin, which causes borders to disappear, etc.) - using (MetafileDCWrapper dcWrapper = new MetafileDCWrapper(hDC, this.Size)) + using (MetafileDCWrapper dcWrapper = new MetafileDCWrapper(hDC, Size)) { SendMessage(Interop.WindowMessages.WM_PRINT, dcWrapper.HDC, lParam); } @@ -10880,14 +10880,14 @@ protected virtual bool ProcessKeyEventArgs(ref Message m) if (m.Msg == Interop.WindowMessages.WM_CHAR || m.Msg == Interop.WindowMessages.WM_SYSCHAR) { - int charsToIgnore = this.ImeWmCharsToIgnore; + int charsToIgnore = ImeWmCharsToIgnore; if (charsToIgnore > 0) { charsToIgnore--; Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "charsToIgnore decreased, new val = " + charsToIgnore + ", this=" + this); - this.ImeWmCharsToIgnore = charsToIgnore; + ImeWmCharsToIgnore = charsToIgnore; return false; } else @@ -10899,10 +10899,10 @@ protected virtual bool ProcessKeyEventArgs(ref Message m) } else if (m.Msg == Interop.WindowMessages.WM_IME_CHAR) { - int charsToIgnore = this.ImeWmCharsToIgnore; + int charsToIgnore = ImeWmCharsToIgnore; charsToIgnore += (3 - sizeof(char)); - this.ImeWmCharsToIgnore = charsToIgnore; + ImeWmCharsToIgnore = charsToIgnore; kpe = new KeyPressEventArgs(unchecked((char)(long)m.WParam)); @@ -11055,7 +11055,7 @@ internal void ProcessUICues(ref Message msg) // make sure the topmost parent agrees with this as we could be in a mismatched state. if (current == 0 /*accelerator and focus cues are showing*/) { - topMostParent = this.TopMostParent; + topMostParent = TopMostParent; current = (int)topMostParent.SendMessage(Interop.WindowMessages.WM_QUERYUISTATE, 0, 0); } int toClear = 0; @@ -11091,7 +11091,7 @@ internal void ProcessUICues(ref Message msg) // that the entire tree of controls is if (topMostParent == null) { - topMostParent = this.TopMostParent; + topMostParent = TopMostParent; } // A) if we're parented to a native dialog - REFRESH our child states ONLY @@ -11136,10 +11136,10 @@ protected void RaisePaintEvent(object key, PaintEventArgs e) private void RemovePendingMessages(int msgMin, int msgMax) { - if (!this.IsDisposed) + if (!IsDisposed) { NativeMethods.MSG msg = new NativeMethods.MSG(); - IntPtr hwnd = this.Handle; + IntPtr hwnd = Handle; while (UnsafeNativeMethods.PeekMessage(ref msg, new HandleRef(this, hwnd), msgMin, msgMax, NativeMethods.PM_REMOVE)) @@ -11259,7 +11259,7 @@ internal virtual void RecreateHandleCore() UnhookMouseEvent(); } - HandleRef parentHandle = new HandleRef(this, UnsafeNativeMethods.GetParent(new HandleRef(this, this.Handle))); + HandleRef parentHandle = new HandleRef(this, UnsafeNativeMethods.GetParent(new HandleRef(this, Handle))); try { @@ -11329,13 +11329,13 @@ internal virtual void RecreateHandleCore() finally { if (parentHandle.Handle != IntPtr.Zero // the parent was not null - && (Control.FromHandle(parentHandle.Handle) == null || this.parent == null) // but wasnt a windows forms window + && (Control.FromHandle(parentHandle.Handle) == null || parent == null) // but wasnt a windows forms window && UnsafeNativeMethods.IsWindow(parentHandle)) { // and still is a window // correctly parent back up to where we were before. // if we were parented to a proper windows forms control, CreateControl would have properly parented // us back. - UnsafeNativeMethods.SetParent(new HandleRef(this, this.Handle), parentHandle); + UnsafeNativeMethods.SetParent(new HandleRef(this, Handle), parentHandle); } } @@ -11981,7 +11981,7 @@ protected virtual void Select(bool directed, bool forward) /// public bool SelectNextControl(Control ctl, bool forward, bool tabStopOnly, bool nested, bool wrap) { - Control nextSelectableControl = this.GetNextSelectableControl(ctl, forward, tabStopOnly, nested, wrap); + Control nextSelectableControl = GetNextSelectableControl(ctl, forward, tabStopOnly, nested, wrap); if (nextSelectableControl != null) { nextSelectableControl.Select(true, forward); @@ -12550,7 +12550,7 @@ protected virtual void SetVisibleCore(bool value) // PERF - setting Visible=false twice can get us into this else block // which makes us process WM_WINDOWPOS* messages - make sure we've already // visible=false - if not, make it so. - if (!SafeNativeMethods.IsWindowVisible(new HandleRef(this, this.Handle))) + if (!SafeNativeMethods.IsWindowVisible(new HandleRef(this, Handle))) { // we're already invisible - bail. return; @@ -12942,7 +12942,7 @@ protected void UpdateBounds(int x, int y, int width, int height, int clientWidth bool newLocation = this.x != x || this.y != y; - bool newSize = this.Width != width || this.Height != height || + bool newSize = Width != width || Height != height || this.clientWidth != clientWidth || this.clientHeight != clientHeight; this.x = x; @@ -12955,20 +12955,20 @@ protected void UpdateBounds(int x, int y, int width, int height, int clientWidth if (newLocation) { #if DEBUG - Rectangle originalBounds = this.Bounds; + Rectangle originalBounds = Bounds; #endif OnLocationChanged(EventArgs.Empty); #if DEBUG - if (this.Bounds != originalBounds && CompModSwitches.SetBounds.TraceWarning) + if (Bounds != originalBounds && CompModSwitches.SetBounds.TraceWarning) { - Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "WARNING: Bounds changed during OnLocationChanged()\r\nbefore={0} after={1}", originalBounds, this.Bounds)); + Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "WARNING: Bounds changed during OnLocationChanged()\r\nbefore={0} after={1}", originalBounds, Bounds)); } #endif } if (newSize) { #if DEBUG - Rectangle originalBounds = this.Bounds; + Rectangle originalBounds = Bounds; #endif OnSizeChanged(EventArgs.Empty); OnClientSizeChanged(EventArgs.Empty); @@ -12978,9 +12978,9 @@ protected void UpdateBounds(int x, int y, int width, int height, int clientWidth LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.Bounds); #if DEBUG - if (this.Bounds != originalBounds && CompModSwitches.SetBounds.TraceWarning) + if (Bounds != originalBounds && CompModSwitches.SetBounds.TraceWarning) { - Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "WARNING: Bounds changed during OnSizeChanged()\r\nbefore={0} after={1}", originalBounds, this.Bounds)); + Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "WARNING: Bounds changed during OnSizeChanged()\r\nbefore={0} after={1}", originalBounds, Bounds)); } #endif } @@ -13018,21 +13018,21 @@ private void UpdateChildControlIndex(Control ctl) // in order to keep the method private. if (!LocalAppContextSwitches.AllowUpdateChildControlIndexForTabControls) { - if (this.GetType().IsAssignableFrom(typeof(TabControl))) + if (GetType().IsAssignableFrom(typeof(TabControl))) { return; } } int newIndex = 0; - int curIndex = this.Controls.GetChildIndex(ctl); + int curIndex = Controls.GetChildIndex(ctl); IntPtr hWnd = ctl.InternalHandle; while ((hWnd = UnsafeNativeMethods.GetWindow(new HandleRef(null, hWnd), NativeMethods.GW_HWNDPREV)) != IntPtr.Zero) { Control c = FromHandle(hWnd); if (c != null) { - newIndex = this.Controls.GetChildIndex(c, false) + 1; + newIndex = Controls.GetChildIndex(c, false) + 1; break; } } @@ -13042,7 +13042,7 @@ private void UpdateChildControlIndex(Control ctl) } if (newIndex != curIndex) { - this.Controls.SetChildIndex(ctl, newIndex); + Controls.SetChildIndex(ctl, newIndex); } } @@ -13090,7 +13090,7 @@ private void UpdateChildZOrder(Control ctl) if (!IsHandleCreated || !ctl.IsHandleCreated || ctl.parent != this) return; IntPtr prevHandle = (IntPtr)NativeMethods.HWND_TOP; - for (int i = this.Controls.GetChildIndex(ctl); --i >= 0;) + for (int i = Controls.GetChildIndex(ctl); --i >= 0;) { Control c = Controls[i]; if (c.IsHandleCreated && c.parent == this) @@ -13436,13 +13436,13 @@ private void WmGetControlName(ref Message m) { string name; - if (this.Site != null) + if (Site != null) { - name = this.Site.Name; + name = Site.Name; } else { - name = this.Name; + name = Name; } if (name == null) @@ -13466,15 +13466,15 @@ private void WmGetControlType(ref Message m) /// private void WmGetObject(ref Message m) { - Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "In WmGetObject, this = " + this.GetType().FullName + ", lParam = " + m.LParam.ToString()); + Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "In WmGetObject, this = " + GetType().FullName + ", lParam = " + m.LParam.ToString()); InternalAccessibleObject intAccessibleObject = null; - if (m.Msg == Interop.WindowMessages.WM_GETOBJECT && m.LParam == (IntPtr)NativeMethods.UiaRootObjectId && this.SupportsUiaProviders) + if (m.Msg == Interop.WindowMessages.WM_GETOBJECT && m.LParam == (IntPtr)NativeMethods.UiaRootObjectId && SupportsUiaProviders) { // If the requested object identifier is UiaRootObjectId, // we should return an UI Automation provider using the UiaReturnRawElementProvider function. - intAccessibleObject = new InternalAccessibleObject(this.AccessibilityObject); + intAccessibleObject = new InternalAccessibleObject(AccessibilityObject); m.Result = UnsafeNativeMethods.UiaReturnRawElementProvider( new HandleRef(this, Handle), m.WParam, @@ -13787,10 +13787,10 @@ private void WmKeyChar(ref Message m) /// private void WmKillFocus(ref Message m) { - Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Control::WmKillFocus - " + this.Name); + Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Control::WmKillFocus - " + Name); WmImeKillFocus(); DefWndProc(ref m); - this.InvokeLostFocus(this, EventArgs.Empty); + InvokeLostFocus(this, EventArgs.Empty); } /// @@ -13892,7 +13892,7 @@ private void WmDpiChangedBeforeParent(ref Message m) if (local != null) { var factor = (float)deviceDpi / deviceDpiOld; - this.Font = new Font(local.FontFamily, local.Size * factor, local.Style, local.Unit, local.GdiCharSet, local.GdiVerticalFont); + Font = new Font(local.FontFamily, local.Size * factor, local.Style, local.Unit, local.GdiCharSet, local.GdiVerticalFont); } RescaleConstantsForDpi(deviceDpiOld, deviceDpi); @@ -13965,7 +13965,7 @@ private void WmMouseUp(ref Message m, MouseButtons button, int clicks) // we have to do it ourselves. if (button == MouseButtons.Right) { - SendMessage(Interop.WindowMessages.WM_CONTEXTMENU, this.Handle, NativeMethods.Util.MAKELPARAM(pt.X, pt.Y)); + SendMessage(Interop.WindowMessages.WM_CONTEXTMENU, Handle, NativeMethods.Util.MAKELPARAM(pt.X, pt.Y)); } } @@ -14147,7 +14147,7 @@ private void WmPaint(ref Message m) { // Cache Handle not only for perf but to avoid object disposed exception in case the window // is destroyed in an event handler. - hWnd = this.Handle; + hWnd = Handle; dc = UnsafeNativeMethods.BeginPaint(new HandleRef(this, hWnd), ref ps); if (dc == IntPtr.Zero) { @@ -14403,7 +14403,7 @@ private void WmParentNotify(ref Message m) /// private void WmSetFocus(ref Message m) { - Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Control::WmSetFocus - " + this.Name); + Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Control::WmSetFocus - " + Name); WmImeSetFocus(); if (!HostedInWin32DialogManager) @@ -14434,7 +14434,7 @@ private void WmSetFocus(ref Message m) } DefWndProc(ref m); - this.InvokeGotFocus(this, EventArgs.Empty); + InvokeGotFocus(this, EventArgs.Empty); } /// @@ -15101,7 +15101,7 @@ void IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) try { - if (sizeProperty != null && !sizeProperty.IsReadOnly && (bounds.Width != this.Width || bounds.Height != this.Height)) + if (sizeProperty != null && !sizeProperty.IsReadOnly && (bounds.Width != Width || bounds.Height != Height)) { if (!(site is INestedSite)) { @@ -15109,7 +15109,7 @@ void IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) } sizeChanged = true; } - if (locationProperty != null && !locationProperty.IsReadOnly && (bounds.X != this.x || bounds.Y != this.y)) + if (locationProperty != null && !locationProperty.IsReadOnly && (bounds.X != x || bounds.Y != y)) { if (!(site is INestedSite)) { @@ -15180,7 +15180,7 @@ internal Control GetControl() protected override void OnHandleChange() { - target.OnHandleChange(this.Handle); + target.OnHandleChange(Handle); } // IWindowTarget method @@ -15623,7 +15623,7 @@ public virtual int IndexOfKey(string key) } // step 2 - search for the item - for (int i = 0; i < this.Count; i++) + for (int i = 0; i < Count; i++) { if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { @@ -15642,7 +15642,7 @@ public virtual int IndexOfKey(string key) /// private bool IsValidIndex(int index) { - return ((index >= 0) && (index < this.Count)); + return ((index >= 0) && (index < Count)); } /// @@ -15869,7 +15869,7 @@ private class ControlCollectionEnumerator : IEnumerator public ControlCollectionEnumerator(ControlCollection controls) { this.controls = controls; - this.originalCount = controls.Count; + originalCount = controls.Count; current = -1; } @@ -16680,21 +16680,21 @@ void UnsafeNativeMethods.IViewObject2.GetExtent(int dwDrawAspect, int lindex, Na bool IKeyboardToolTip.CanShowToolTipsNow() { - IKeyboardToolTip host = this.ToolStripControlHost; - return this.IsHandleCreated && this.Visible && (host == null || host.CanShowToolTipsNow()); + IKeyboardToolTip host = ToolStripControlHost; + return IsHandleCreated && Visible && (host == null || host.CanShowToolTipsNow()); } Rectangle IKeyboardToolTip.GetNativeScreenRectangle() { - return this.GetToolNativeScreenRectangle(); + return GetToolNativeScreenRectangle(); } IList IKeyboardToolTip.GetNeighboringToolsRectangles() { - IKeyboardToolTip host = this.ToolStripControlHost; + IKeyboardToolTip host = ToolStripControlHost; if (host == null) { - return this.GetOwnNeighboringToolsRectangles(); + return GetOwnNeighboringToolsRectangles(); } else { @@ -16704,19 +16704,19 @@ IList IKeyboardToolTip.GetNeighboringToolsRectangles() bool IKeyboardToolTip.IsHoveredWithMouse() { - return this.ClientRectangle.Contains(this.PointToClient(Control.MousePosition)); + return ClientRectangle.Contains(PointToClient(Control.MousePosition)); } bool IKeyboardToolTip.HasRtlModeEnabled() { Control topLevelControl = TopLevelControlInternal; - return topLevelControl != null && topLevelControl.RightToLeft == RightToLeft.Yes && !this.IsMirrored; + return topLevelControl != null && topLevelControl.RightToLeft == RightToLeft.Yes && !IsMirrored; } bool IKeyboardToolTip.AllowsToolTip() { - IKeyboardToolTip host = this.ToolStripControlHost; - return (host == null || host.AllowsToolTip()) && this.AllowsKeyboardToolTip(); + IKeyboardToolTip host = ToolStripControlHost; + return (host == null || host.AllowsToolTip()) && AllowsKeyboardToolTip(); } IWin32Window IKeyboardToolTip.GetOwnerWindow() @@ -16726,17 +16726,17 @@ IWin32Window IKeyboardToolTip.GetOwnerWindow() void IKeyboardToolTip.OnHooked(ToolTip toolTip) { - this.OnKeyboardToolTipHook(toolTip); + OnKeyboardToolTipHook(toolTip); } void IKeyboardToolTip.OnUnhooked(ToolTip toolTip) { - this.OnKeyboardToolTipUnhook(toolTip); + OnKeyboardToolTipUnhook(toolTip); } string IKeyboardToolTip.GetCaptionForTool(ToolTip toolTip) { - IKeyboardToolTip host = this.ToolStripControlHost; + IKeyboardToolTip host = ToolStripControlHost; if (host == null) { return toolTip.GetCaptionForTool(this); @@ -16749,8 +16749,8 @@ string IKeyboardToolTip.GetCaptionForTool(ToolTip toolTip) bool IKeyboardToolTip.ShowsOwnToolTip() { - IKeyboardToolTip host = this.ToolStripControlHost; - return (host == null || host.ShowsOwnToolTip()) && this.ShowsOwnKeyboardToolTip(); + IKeyboardToolTip host = ToolStripControlHost; + return (host == null || host.ShowsOwnToolTip()) && ShowsOwnKeyboardToolTip(); } bool IKeyboardToolTip.IsBeingTabbedTo() @@ -16760,14 +16760,14 @@ bool IKeyboardToolTip.IsBeingTabbedTo() bool IKeyboardToolTip.AllowsChildrenToShowToolTips() { - return this.AllowsChildrenToShowToolTips(); + return AllowsChildrenToShowToolTips(); } #endregion private IList GetOwnNeighboringToolsRectangles() { - Control controlParent = this.ParentInternal; + Control controlParent = ParentInternal; if (controlParent != null) { Control[] neighboringControls = new Control[4] { @@ -16812,7 +16812,7 @@ internal virtual void OnKeyboardToolTipUnhook(ToolTip toolTip) internal virtual Rectangle GetToolNativeScreenRectangle() { NativeMethods.RECT rectangle = new NativeMethods.RECT(); - UnsafeNativeMethods.GetWindowRect(new HandleRef(this, this.Handle), ref rectangle); + UnsafeNativeMethods.GetWindowRect(new HandleRef(this, Handle), ref rectangle); return Rectangle.FromLTRB(rectangle.left, rectangle.top, rectangle.right, rectangle.bottom); } @@ -16855,12 +16855,12 @@ internal ToolStripControlHost ToolStripControlHost get { ToolStripControlHost value; - this.toolStripControlHostReference.TryGetTarget(out value); + toolStripControlHostReference.TryGetTarget(out value); return value; } set { - this.toolStripControlHostReference.SetTarget(value); + toolStripControlHostReference.SetTarget(value); } } @@ -17981,7 +17981,7 @@ internal void Load(UnsafeNativeMethods.IStorage stg) try { - stream = stg.OpenStream(this.GetStreamName(), IntPtr.Zero, NativeMethods.STGM_READ | NativeMethods.STGM_SHARE_EXCLUSIVE, 0); + stream = stg.OpenStream(GetStreamName(), IntPtr.Zero, NativeMethods.STGM_READ | NativeMethods.STGM_SHARE_EXCLUSIVE, 0); } catch (COMException e) { @@ -18573,7 +18573,7 @@ public SafeIUnknown(object obj, bool addRefIntPtr, Guid iid) } // Preserve the com ptr in the SafeHandle. - this.handle = unknown; + handle = unknown; } } @@ -18625,7 +18625,7 @@ protected sealed override bool ReleaseHandle() /// protected V LoadVtable() { - IntPtr vtblptr = Marshal.ReadIntPtr(this.handle, 0); + IntPtr vtblptr = Marshal.ReadIntPtr(handle, 0); return Marshal.PtrToStructure(vtblptr); } } @@ -18641,7 +18641,7 @@ internal sealed class ComConnectionPointContainer public ComConnectionPointContainer(object obj, bool addRefIntPtr) : base(obj, addRefIntPtr, typeof(System.Runtime.InteropServices.ComTypes.IConnectionPointContainer).GUID) { - this.vtbl = base.LoadVtable(); + vtbl = base.LoadVtable(); } private VTABLE vtbl; @@ -18662,11 +18662,11 @@ private class VTABLE /// public ComConnectionPoint FindConnectionPoint(Type eventInterface) { - FindConnectionPointD findConnectionPoint = (FindConnectionPointD)Marshal.GetDelegateForFunctionPointer(this.vtbl.FindConnectionPointPtr, typeof(FindConnectionPointD)); + FindConnectionPointD findConnectionPoint = (FindConnectionPointD)Marshal.GetDelegateForFunctionPointer(vtbl.FindConnectionPointPtr, typeof(FindConnectionPointD)); IntPtr result = IntPtr.Zero; Guid iid = eventInterface.GUID; - int hresult = findConnectionPoint.Invoke(this.handle, ref iid, out result); + int hresult = findConnectionPoint.Invoke(handle, ref iid, out result); if (hresult != 0 || result == IntPtr.Zero) { throw new ArgumentException(string.Format(SR.AXNoConnectionPoint, eventInterface.Name)); @@ -18690,7 +18690,7 @@ internal sealed class ComConnectionPoint public ComConnectionPoint(object obj, bool addRefIntPtr) : base(obj, addRefIntPtr, typeof(System.Runtime.InteropServices.ComTypes.IConnectionPoint).GUID) { - this.vtbl = this.LoadVtable(); + vtbl = LoadVtable(); } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] @@ -18714,8 +18714,8 @@ private class VTABLE /// public bool Advise(IntPtr punkEventSink, out int cookie) { - AdviseD advise = (AdviseD)Marshal.GetDelegateForFunctionPointer(this.vtbl.AdvisePtr, typeof(AdviseD)); - if (advise.Invoke(this.handle, punkEventSink, out cookie) == 0) + AdviseD advise = (AdviseD)Marshal.GetDelegateForFunctionPointer(vtbl.AdvisePtr, typeof(AdviseD)); + if (advise.Invoke(handle, punkEventSink, out cookie) == 0) { return true; } @@ -18759,7 +18759,7 @@ private static Type GetDefaultEventsInterface(Type controlType) /// internal void Save(UnsafeNativeMethods.IStorage stg, bool fSameAsLoad) { - UnsafeNativeMethods.IStream stream = stg.CreateStream(this.GetStreamName(), NativeMethods.STGM_WRITE | NativeMethods.STGM_SHARE_EXCLUSIVE | NativeMethods.STGM_CREATE, 0, 0); + UnsafeNativeMethods.IStream stream = stg.CreateStream(GetStreamName(), NativeMethods.STGM_WRITE | NativeMethods.STGM_SHARE_EXCLUSIVE | NativeMethods.STGM_CREATE, 0, 0); Debug.Assert(stream != null, "Stream should be non-null, or an exception should have been thrown."); Save(stream, true); Marshal.ReleaseComObject(stream); @@ -18966,7 +18966,7 @@ internal void SetClientSite(UnsafeNativeMethods.IOleClientSite value) if (IsIE) { - this.control.Dispose(); + control.Dispose(); } } else @@ -19484,7 +19484,7 @@ internal void UpdateBounds(ref int x, ref int y, ref int width, ref int height, internal void UpdateAccelTable() { // Setting the count to -1 will recreate the table on demand (when GetControlInfo is called). - this.accelCount = -1; + accelCount = -1; UnsafeNativeMethods.IOleControlSite ioleClientSite = clientSite as UnsafeNativeMethods.IOleControlSite; if (ioleClientSite != null) @@ -19961,8 +19961,8 @@ internal AmbientProperty(string name, int dispID) { this.name = name; this.dispID = dispID; - this.value = null; - this.empty = true; + value = null; + empty = true; } /// @@ -20258,7 +20258,7 @@ public ControlAccessibleObject(Control ownerControl) IntPtr handle = ownerControl.Handle; - this.Handle = handle; + Handle = handle; } internal ControlAccessibleObject(Control ownerControl, int accObjId) @@ -20270,12 +20270,12 @@ internal ControlAccessibleObject(Control ownerControl, int accObjId) throw new ArgumentNullException(nameof(ownerControl)); } - this.AccessibleObjectId = accObjId; // ...must set this *before* setting the Handle property + AccessibleObjectId = accObjId; // ...must set this *before* setting the Handle property this.ownerControl = ownerControl; IntPtr handle = ownerControl.Handle; - this.Handle = handle; + Handle = handle; } /// @@ -20417,7 +20417,7 @@ internal override int[] RuntimeId { runtimeId = new int[2]; runtimeId[0] = 0x2a; - runtimeId[1] = (int)(long)this.Handle; + runtimeId[1] = (int)(long)Handle; } return runtimeId; @@ -20511,7 +20511,7 @@ public override string KeyboardShortcut { // For controls, the default keyboard shortcut comes directly from the accessible // name property. This matches the default behavior of OLEACC.DLL exactly. - char mnemonic = WindowsFormsUtils.GetMnemonic(this.TextLabel, false); + char mnemonic = WindowsFormsUtils.GetMnemonic(TextLabel, false); return (mnemonic == (char)0) ? null : ("Alt+" + mnemonic); } } @@ -20696,7 +20696,7 @@ public override int GetHelpTopic(out string fileName) public void NotifyClients(AccessibleEvents accEvent) { Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "Control.NotifyClients: this = " + - this.ToString() + ", accEvent = " + accEvent.ToString() + ", childID = self"); + ToString() + ", accEvent = " + accEvent.ToString() + ", childID = self"); UnsafeNativeMethods.NotifyWinEvent((int)accEvent, new HandleRef(this, Handle), NativeMethods.OBJID_CLIENT, 0); } @@ -20705,7 +20705,7 @@ public void NotifyClients(AccessibleEvents accEvent, int childID) { Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "Control.NotifyClients: this = " + - this.ToString() + + ToString() + ", accEvent = " + accEvent.ToString() + ", childID = " + childID.ToString(CultureInfo.InvariantCulture)); @@ -20716,7 +20716,7 @@ public void NotifyClients(AccessibleEvents accEvent, int objectID, int childID) { Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "Control.NotifyClients: this = " + - this.ToString() + + ToString() + ", accEvent = " + accEvent.ToString() + ", childID = " + childID.ToString(CultureInfo.InvariantCulture)); @@ -20732,7 +20732,7 @@ public void NotifyClients(AccessibleEvents accEvent, int objectID, int childID) /// True if operation succeeds, False otherwise. public override bool RaiseLiveRegionChanged() { - if (!(this.Owner is IAutomationLiveRegion)) + if (!(Owner is IAutomationLiveRegion)) { throw new InvalidOperationException(SR.OwnerControlIsNotALiveRegion); } @@ -20742,7 +20742,7 @@ public override bool RaiseLiveRegionChanged() internal override bool IsIAccessibleExSupported() { - if (this.Owner is IAutomationLiveRegion) + if (Owner is IAutomationLiveRegion) { return true; } @@ -20896,19 +20896,19 @@ internal ThreadMethodEntry(Control caller, Control marshaler, Delegate method, o this.marshaler = marshaler; this.method = method; this.args = args; - this.exception = null; - this.retVal = null; + exception = null; + retVal = null; this.synchronous = synchronous; - this.isCompleted = false; - this.resetEvent = null; + isCompleted = false; + resetEvent = null; this.executionContext = executionContext; } ~ThreadMethodEntry() { - if (this.resetEvent != null) + if (resetEvent != null) { - this.resetEvent.Close(); + resetEvent.Close(); } } @@ -20924,7 +20924,7 @@ public WaitHandle AsyncWaitHandle { get { - if (this.resetEvent == null) + if (resetEvent == null) { // Locking 'this' here is ok since this is an internal class. lock (invokeSyncObject) @@ -20932,17 +20932,17 @@ public WaitHandle AsyncWaitHandle // BeginInvoke hangs on Multi-proc system: // taking the lock prevents a race condition between IsCompleted // boolean flag and resetEvent mutex in multiproc scenarios. - if (this.resetEvent == null) + if (resetEvent == null) { - this.resetEvent = new ManualResetEvent(false); - if (this.isCompleted) + resetEvent = new ManualResetEvent(false); + if (isCompleted) { - this.resetEvent.Set(); + resetEvent.Set(); } } } } - return (WaitHandle)this.resetEvent; + return (WaitHandle)resetEvent; } } @@ -20950,7 +20950,7 @@ public bool CompletedSynchronously { get { - if (this.isCompleted && this.synchronous) + if (isCompleted && synchronous) return true; return false; @@ -20961,7 +20961,7 @@ public bool IsCompleted { get { - return this.isCompleted; + return isCompleted; } } @@ -20969,10 +20969,10 @@ internal void Complete() { lock (invokeSyncObject) { - this.isCompleted = true; - if (this.resetEvent != null) + isCompleted = true; + if (resetEvent != null) { - this.resetEvent.Set(); + resetEvent.Set(); } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ControlBindingsCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ControlBindingsCollection.cs index 3a33663e44c..63278373888 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ControlBindingsCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ControlBindingsCollection.cs @@ -21,7 +21,7 @@ public class ControlBindingsCollection : BindingsCollection public ControlBindingsCollection(IBindableComponent control) { - this._control = control; + _control = control; } public IBindableComponent BindableComponent => _control; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs index 1603d0b3fc4..8c4d448ce1f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs @@ -164,7 +164,7 @@ internal override Type BindType { get { - return ListBindingHelper.GetListItemType(this.List); + return ListBindingHelper.GetListItemType(List); } } @@ -185,8 +185,8 @@ private protected override void SetDataSource(object dataSource) { Release(); this.dataSource = dataSource; - this.list = null; - this.finalType = null; + list = null; + finalType = null; object tempList = dataSource; if (tempList is Array) @@ -206,7 +206,7 @@ private protected override void SetDataSource(object dataSource) { finalType = tempList.GetType(); } - this.list = (IList)tempList; + list = (IList)tempList; WireEvents(list); if (list.Count > 0) listposition = 0; @@ -351,13 +351,13 @@ public override void CancelCurrentEdit() ICancelAddNew iListWithCancelAddNewSupport = list as ICancelAddNew; if (iListWithCancelAddNewSupport != null) { - iListWithCancelAddNewSupport.CancelNew(this.Position); + iListWithCancelAddNewSupport.CancelNew(Position); } OnItemChanged(new ItemChangedEventArgs(Position)); - if (this.Position != -1) + if (Position != -1) { - OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, this.Position)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, Position)); } } } @@ -368,13 +368,13 @@ private void ChangeRecordState(int newPosition, bool validating, bool endCurrent { if (listposition != -1) { - this.listposition = -1; + listposition = -1; OnPositionChanged(EventArgs.Empty); } return; } - if ((newPosition < 0 || newPosition >= Count) && this.IsBinding) + if ((newPosition < 0 || newPosition >= Count) && IsBinding) { throw new IndexOutOfRangeException(SR.ListManagerBadPosition); } @@ -407,7 +407,7 @@ private void ChangeRecordState(int newPosition, bool validating, bool endCurrent } // EndCurrentEdit or PullData can cause the list managed by the CurrencyManager to shrink. - this.listposition = Math.Min(newPosition, Count - 1); + listposition = Math.Min(newPosition, Count - 1); if (validating) { @@ -519,7 +519,7 @@ public override void EndCurrentEdit() ICancelAddNew iListWithCancelAddNewSupport = list as ICancelAddNew; if (iListWithCancelAddNewSupport != null) { - iListWithCancelAddNewSupport.EndNew(this.Position); + iListWithCancelAddNewSupport.EndNew(Position); } } } @@ -527,7 +527,7 @@ public override void EndCurrentEdit() private void FindGoodRow() { - int rowCount = this.list.Count; + int rowCount = list.Count; for (int i = 0; i < rowCount; i++) { listposition = i; @@ -645,7 +645,7 @@ protected internal override string GetListName(ArrayList listAccessors) /// internal override PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors) { - return ListBindingHelper.GetListItemProperties(this.list, listAccessors); + return ListBindingHelper.GetListItemProperties(list, listAccessors); } /// @@ -758,7 +758,7 @@ private void List_ListChanged(object sender, System.ComponentModel.ListChangedEv OnPositionChanged(EventArgs.Empty); break; } - else if (dbe.NewIndex == this.listposition && this.listposition == list.Count - 1 && this.listposition != -1) + else if (dbe.NewIndex == listposition && listposition == list.Count - 1 && listposition != -1) { // The CurrencyManager has a non-empty list. // The position inside the currency manager is at the end of the list and the list still fired an ItemAdded event. @@ -808,7 +808,7 @@ private void List_ListChanged(object sender, System.ComponentModel.ListChangedEv case System.ComponentModel.ListChangedType.ItemChanged: Debug.WriteLineIf(CompModSwitches.DataCursor.TraceVerbose, "System.ComponentModel.ListChangedType.ItemChanged " + dbe.NewIndex.ToString(CultureInfo.InvariantCulture)); // the current item changed - if (dbe.NewIndex == this.listposition) + if (dbe.NewIndex == listposition) { OnCurrentItemChanged(EventArgs.Empty); } @@ -820,12 +820,12 @@ private void List_ListChanged(object sender, System.ComponentModel.ListChangedEv if (dbe.OldIndex == listposition) { // current got moved. // the position changes, so end the current edit. Make sure there is something that we can end edit... - ChangeRecordState(dbe.NewIndex, true, this.Position > -1 && this.Position < list.Count, true, false); + ChangeRecordState(dbe.NewIndex, true, Position > -1 && Position < list.Count, true, false); } else if (dbe.NewIndex == listposition) { // current was moved // the position changes, so end the current edit. Make sure there is something that we can end edit - ChangeRecordState(dbe.OldIndex, true, this.Position > -1 && this.Position < list.Count, true, false); + ChangeRecordState(dbe.OldIndex, true, Position > -1 && Position < list.Count, true, false); } OnItemChanged(resetEvent); break; @@ -833,7 +833,7 @@ private void List_ListChanged(object sender, System.ComponentModel.ListChangedEv case System.ComponentModel.ListChangedType.PropertyDescriptorDeleted: case System.ComponentModel.ListChangedType.PropertyDescriptorChanged: // reset lastGoodKnownRow because it was computed against property descriptors which changed - this.lastGoodKnownRow = -1; + lastGoodKnownRow = -1; // In Everett, metadata changes did not alter current list position. In Whidbey, this behavior // preserved - except that we will now force the position to stay in valid range if necessary. @@ -1014,7 +1014,7 @@ public override void ResumeBinding() { shouldBind = true; // we need to put the listPosition at the beginning of the list if the list is not empty - this.listposition = (this.list != null && this.list.Count != 0) ? 0 : -1; + listposition = (list != null && list.Count != 0) ? 0 : -1; UpdateIsBinding(); } } @@ -1093,7 +1093,7 @@ private void UpdateLastGoodKnownRow(System.ComponentModel.ListChangedEventArgs e lastGoodKnownRow = -1; break; case System.ComponentModel.ListChangedType.ItemAdded: - if (e.NewIndex <= lastGoodKnownRow && lastGoodKnownRow < this.List.Count - 1) + if (e.NewIndex <= lastGoodKnownRow && lastGoodKnownRow < List.Count - 1) lastGoodKnownRow++; break; case System.ComponentModel.ListChangedType.ItemMoved: diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Cursor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Cursor.cs index 9ebabdbc022..575ea46f42b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Cursor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Cursor.cs @@ -109,7 +109,7 @@ public Cursor(IntPtr handle) } this.handle = handle; - this.ownHandle = false; + ownHandle = false; } /// @@ -270,7 +270,7 @@ public Point HotSpot NativeMethods.ICONINFO info = new NativeMethods.ICONINFO(); Icon currentIcon = null; - currentIcon = Icon.FromHandle(this.Handle); + currentIcon = Icon.FromHandle(Handle); try { @@ -705,7 +705,7 @@ internal void SavePicture(Stream stream) { throw new ArgumentNullException(nameof(stream)); } - if (this.resourceId != 0) + if (resourceId != 0) { throw new FormatException(SR.CursorCannotCovertToBytes); } @@ -747,7 +747,7 @@ public override string ToString() { string s = null; - if (!this.ownHandle) + if (!ownHandle) s = TypeDescriptor.GetConverter(typeof(Cursor)).ConvertToString(this); else s = base.ToString(); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs index bdf37fca0b2..defdd4cc70e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs @@ -326,7 +326,7 @@ public DataGrid() : base() SetStyle(ControlStyles.Opaque, false); SetStyle(ControlStyles.SupportsTransparentBackColor, false); SetStyle(ControlStyles.UserMouse, true); - this.gridState = new System.Collections.Specialized.BitVector32(0x00042827); + gridState = new System.Collections.Specialized.BitVector32(0x00042827); dataGridTables = new GridTableStylesCollection(this); layout = CreateInitialLayoutState(); @@ -355,9 +355,9 @@ public DataGrid() : base() itemChangedHandler = new ItemChangedEventHandler(DataSource_ItemChanged); metaDataChangedHandler = new EventHandler(DataSource_MetaDataChanged); dataGridTableStylesCollectionChanged = new CollectionChangeEventHandler(TableStylesCollectionChanged); - this.dataGridTables.CollectionChanged += dataGridTableStylesCollectionChanged; + dataGridTables.CollectionChanged += dataGridTableStylesCollectionChanged; - SetDataGridTable(this.defaultTableStyle, true); + SetDataGridTable(defaultTableStyle, true); backButtonHandler = new EventHandler(OnBackButtonClicked); downButtonHandler = new EventHandler(OnShowParentDetailsButtonClicked); @@ -396,9 +396,9 @@ public bool AllowSorting if (AllowSorting != value) { gridState[GRIDSTATE_allowSorting] = value; - if (!value && this.listManager != null) + if (!value && listManager != null) { - IList list = this.listManager.List; + IList list = listManager.List; if (list is IBindingList) ((IBindingList)list).RemoveSort(); } @@ -482,9 +482,9 @@ public override Color BackColor public override void ResetBackColor() { - if (!this.BackColor.Equals(DefaultBackBrush.Color)) + if (!BackColor.Equals(DefaultBackBrush.Color)) { - this.BackColor = DefaultBackBrush.Color; + BackColor = DefaultBackBrush.Color; } } @@ -505,9 +505,9 @@ public override Color ForeColor } public override void ResetForeColor() { - if (!this.ForeColor.Equals(DefaultForeBrush.Color)) + if (!ForeColor.Equals(DefaultForeBrush.Color)) { - this.ForeColor = DefaultForeBrush.Color; + ForeColor = DefaultForeBrush.Color; } } @@ -715,16 +715,16 @@ private bool ListHasErrors if (value) { if (myGridTable.IsDefault) - this.RowHeaderWidth += errorRowBitmapWidth; + RowHeaderWidth += errorRowBitmapWidth; else - this.myGridTable.RowHeaderWidth += errorRowBitmapWidth; + myGridTable.RowHeaderWidth += errorRowBitmapWidth; } else { if (myGridTable.IsDefault) - this.RowHeaderWidth -= errorRowBitmapWidth; + RowHeaderWidth -= errorRowBitmapWidth; else - this.myGridTable.RowHeaderWidth -= errorRowBitmapWidth; + myGridTable.RowHeaderWidth -= errorRowBitmapWidth; } } } @@ -953,7 +953,7 @@ public DataGridCell CurrentCell return; // should we throw an exception, maybe? - if (DataGridRowsLength == 0 || this.myGridTable.GridColumnStyles == null || this.myGridTable.GridColumnStyles.Count == 0) + if (DataGridRowsLength == 0 || myGridTable.GridColumnStyles == null || myGridTable.GridColumnStyles.Count == 0) return; EnsureBound(); @@ -996,26 +996,26 @@ public DataGridCell CurrentCell if (currentCol != newCol) { cellChanged = true; - int currentListManagerPosition = this.ListManager.Position; - int currentListManagerCount = this.ListManager.List.Count; + int currentListManagerPosition = ListManager.Position; + int currentListManagerCount = ListManager.List.Count; EndEdit(); - if (this.ListManager.Position != currentListManagerPosition || - currentListManagerCount != this.ListManager.List.Count) + if (ListManager.Position != currentListManagerPosition || + currentListManagerCount != ListManager.List.Count) { // EndEdit changed the list. // Reset the data grid rows and the current row inside the datagrid. // And then exit the method. RecreateDataGridRows(); - if (this.ListManager.List.Count > 0) + if (ListManager.List.Count > 0) { - this.currentRow = this.ListManager.Position; + currentRow = ListManager.Position; Edit(); } else { - this.currentRow = -1; + currentRow = -1; } return; @@ -1030,26 +1030,26 @@ public DataGridCell CurrentCell if (currentRow != newRow) { cellChanged = true; - int currentListManagerPosition = this.ListManager.Position; - int currentListManagerCount = this.ListManager.List.Count; + int currentListManagerPosition = ListManager.Position; + int currentListManagerCount = ListManager.List.Count; EndEdit(); - if (this.ListManager.Position != currentListManagerPosition || - currentListManagerCount != this.ListManager.List.Count) + if (ListManager.Position != currentListManagerPosition || + currentListManagerCount != ListManager.List.Count) { // EndEdit changed the list. // Reset the data grid rows and the current row inside the datagrid. // And then exit the method. RecreateDataGridRows(); - if (this.ListManager.List.Count > 0) + if (ListManager.List.Count > 0) { - this.currentRow = this.ListManager.Position; + currentRow = ListManager.Position; Edit(); } else { - this.currentRow = -1; + currentRow = -1; } return; @@ -1077,23 +1077,23 @@ public DataGridCell CurrentCell else if (gridState[GRIDSTATE_inAddNewRow]) { #if DEBUG - int currentRowCount = this.DataGridRowsLength; + int currentRowCount = DataGridRowsLength; #endif // debug // cancelCurrentEdit will change the position in the list // to the last element in the list. and the grid will get an on position changed // event, and will set the current cell to the last element in the dataSource. // so unhook the PositionChanged event from the listManager; - this.ListManager.PositionChanged -= positionChangedHandler; - this.ListManager.CancelCurrentEdit(); - this.ListManager.Position = this.currentRow; - this.ListManager.PositionChanged += positionChangedHandler; + ListManager.PositionChanged -= positionChangedHandler; + ListManager.CancelCurrentEdit(); + ListManager.Position = currentRow; + ListManager.PositionChanged += positionChangedHandler; #if DEBUG Debug.Assert(currentRowSaved > currentRow, "we can only go up when we are inAddNewRow"); - Debug.Assert(currentRowCount == this.DataGridRowsLength, "the number of rows in the dataGrid should not change"); - Debug.Assert(currentRowCount == this.ListManager.Count + 1, "the listManager should have one less record"); + Debug.Assert(currentRowCount == DataGridRowsLength, "the number of rows in the dataGrid should not change"); + Debug.Assert(currentRowCount == ListManager.Count + 1, "the listManager should have one less record"); #endif // debug - localGridRows[DataGridRowsLength - 1] = new DataGridAddNewRow(this, this.myGridTable, DataGridRowsLength - 1); + localGridRows[DataGridRowsLength - 1] = new DataGridAddNewRow(this, myGridTable, DataGridRowsLength - 1); SetDataGridRows(localGridRows, DataGridRowsLength); gridState[GRIDSTATE_inAddNewRow] = false; } @@ -1119,8 +1119,8 @@ public DataGridCell CurrentCell // in the grid. in this case, we should not be using the old // localGridRows in our assertion, cause they are outdated now // - Debug.Assert(this.DataGridRows[currentRow] is DataGridAddNewRow, "the last row is the DataGridAddNewRow"); - this.AddNewRow(); + Debug.Assert(DataGridRows[currentRow] is DataGridAddNewRow, "the last row is the DataGridAddNewRow"); + AddNewRow(); Debug.Assert(ListManager.Position == currentRow || listManager.Position == -1, "the listManager should be positioned at the last row"); } else @@ -1165,14 +1165,14 @@ public DataGridCell CurrentCell // in this particular scenario, CancelCurrentEdit will cause the last row to be deleted, // and this will ultimately call InvalidateRow w/ a row number larger than the number of rows // so set the currentRow here: - if (currentRow == this.DataGridRowsLength - 1 && currentRowSaved == this.DataGridRowsLength - 2 && DataGridRows[currentRow] is DataGridAddNewRow) + if (currentRow == DataGridRowsLength - 1 && currentRowSaved == DataGridRowsLength - 2 && DataGridRows[currentRow] is DataGridAddNewRow) newRow = currentRowSaved; currentRow = newRow; Debug.Assert(result == DialogResult.No, "we only put cancel and ok on the error message box"); - this.listManager.PositionChanged -= positionChangedHandler; - this.listManager.CancelCurrentEdit(); - this.listManager.Position = newRow; - this.listManager.PositionChanged += positionChangedHandler; + listManager.PositionChanged -= positionChangedHandler; + listManager.CancelCurrentEdit(); + listManager.Position = newRow; + listManager.PositionChanged += positionChangedHandler; currentRow = newRow; currentCol = newCol; if (wasEditing) @@ -1212,13 +1212,13 @@ internal int CurrentCellAccIndex { int currentCellAccIndex = 0; currentCellAccIndex++; // ParentRowsAccessibleObject - currentCellAccIndex += this.myGridTable.GridColumnStyles.Count; // ColumnHeaderAccessibleObject - currentCellAccIndex += this.DataGridRows.Length; // DataGridRowAccessibleObject - if (this.horizScrollBar.Visible) // Horizontal Scroll Bar Accessible Object + currentCellAccIndex += myGridTable.GridColumnStyles.Count; // ColumnHeaderAccessibleObject + currentCellAccIndex += DataGridRows.Length; // DataGridRowAccessibleObject + if (horizScrollBar.Visible) // Horizontal Scroll Bar Accessible Object currentCellAccIndex++; - if (this.vertScrollBar.Visible) // Vertical Scroll Bar Accessible Object + if (vertScrollBar.Visible) // Vertical Scroll Bar Accessible Object currentCellAccIndex++; - currentCellAccIndex += (this.currentRow * this.myGridTable.GridColumnStyles.Count) + this.currentCol; + currentCellAccIndex += (currentRow * myGridTable.GridColumnStyles.Count) + currentCol; return currentCellAccIndex; } } @@ -1238,7 +1238,7 @@ private int CurrentColumn } set { - this.CurrentCell = new DataGridCell(currentRow, value); + CurrentCell = new DataGridCell(currentRow, value); } } @@ -1283,7 +1283,7 @@ internal SolidBrush SelectionBackBrush { get { - return this.selectionBackBrush; + return selectionBackBrush; } } @@ -1291,7 +1291,7 @@ internal SolidBrush SelectionForeBrush { get { - return this.selectionForeBrush; + return selectionForeBrush; } } @@ -1342,7 +1342,7 @@ public void ResetSelectionForeColor() internal override bool ShouldSerializeForeColor() { - return !DefaultForeBrush.Color.Equals(this.ForeColor); + return !DefaultForeBrush.Color.Equals(ForeColor); } /// @@ -1351,7 +1351,7 @@ internal override bool ShouldSerializeForeColor() /// internal override bool ShouldSerializeBackColor() { - return !DefaultBackBrush.Color.Equals(this.BackColor); + return !DefaultBackBrush.Color.Equals(BackColor); } // Don't use dataGridRows, use the accessor!!! @@ -1396,12 +1396,12 @@ private void ResetToolTip() // add toolTips for the backButton and // details button on the caption. - if (!this.parentRows.IsEmpty()) + if (!parentRows.IsEmpty()) { - bool alignRight = this.isRightToLeft(); - int detailsButtonWidth = this.Caption.GetDetailsButtonWidth(); - Rectangle backButton = this.Caption.GetBackButtonRect(this.layout.Caption, alignRight, detailsButtonWidth); - Rectangle detailsButton = this.Caption.GetDetailsButtonRect(this.layout.Caption, alignRight); + bool alignRight = isRightToLeft(); + int detailsButtonWidth = Caption.GetDetailsButtonWidth(); + Rectangle backButton = Caption.GetBackButtonRect(layout.Caption, alignRight, detailsButtonWidth); + Rectangle detailsButton = Caption.GetDetailsButtonRect(layout.Caption, alignRight); // mirror the buttons wrt RTL property backButton.X = MirrorRectangle(backButton, layout.Inside, isRightToLeft()); @@ -1425,7 +1425,7 @@ private void ResetToolTip() private void CreateDataGridRows() { CurrencyManager listManager = ListManager; - DataGridTableStyle dgt = this.myGridTable; + DataGridTableStyle dgt = myGridTable; InitializeColumnWidths(); if (listManager == null) @@ -1446,7 +1446,7 @@ private void CreateDataGridRows() if (policy.AllowAdd) { - this.addNewRow = new DataGridAddNewRow(this, dgt, nDataGridRows - 1); + addNewRow = new DataGridAddNewRow(this, dgt, nDataGridRows - 1); rows[nDataGridRows - 1] = addNewRow; } else @@ -1542,10 +1542,10 @@ public object DataSource } // when the designer resets the dataSource to null, set the dataMember to null, too - if ((value == null || value == Convert.DBNull) && this.DataMember != null && this.DataMember.Length != 0) + if ((value == null || value == Convert.DBNull) && DataMember != null && DataMember.Length != 0) { - this.dataSource = null; - this.DataMember = string.Empty; + dataSource = null; + DataMember = string.Empty; return; } @@ -1561,7 +1561,7 @@ public object DataSource // the same goes for all the caption UI: reset it when the datasource changes. // ResetParentRows(); - Set_ListManager(value, this.DataMember, false); + Set_ListManager(value, DataMember, false); } } @@ -1600,7 +1600,7 @@ public string DataMember // the same goes for all the caption UI: reset it when the datamember changes. // ResetParentRows(); - Set_ListManager(this.DataSource, value, false); + Set_ListManager(DataSource, value, false); } } @@ -1623,8 +1623,8 @@ internal protected CurrencyManager ListManager get { //try to return something useful: - if (listManager == null && this.BindingContext != null && this.DataSource != null) - return (CurrencyManager)this.BindingContext[this.DataSource, this.DataMember]; + if (listManager == null && BindingContext != null && DataSource != null) + return (CurrencyManager)BindingContext[DataSource, DataMember]; else return listManager; } @@ -1648,19 +1648,19 @@ internal void Set_ListManager(object newDataSource, string newDataMember, bool f // internal void Set_ListManager(object newDataSource, string newDataMember, bool force, bool forceColumnCreation) { - bool dataSourceChanged = this.DataSource != newDataSource; - bool dataMemberChanged = this.DataMember != newDataMember; + bool dataSourceChanged = DataSource != newDataSource; + bool dataMemberChanged = DataMember != newDataMember; // if nothing happened, then why do any work? if (!force && !dataSourceChanged && !dataMemberChanged && gridState[GRIDSTATE_inSetListManager]) return; gridState[GRIDSTATE_inSetListManager] = true; - if (this.toBeDisposedEditingControl != null) + if (toBeDisposedEditingControl != null) { - Debug.Assert(this.Controls.Contains(this.toBeDisposedEditingControl)); - this.Controls.Remove(this.toBeDisposedEditingControl); - this.toBeDisposedEditingControl = null; + Debug.Assert(Controls.Contains(toBeDisposedEditingControl)); + Controls.Remove(toBeDisposedEditingControl); + toBeDisposedEditingControl = null; } bool beginUpdateInternal = true; try @@ -1669,7 +1669,7 @@ internal void Set_ListManager(object newDataSource, string newDataMember, bool f UpdateListManager(); // unwire the events: - if (this.listManager != null) + if (listManager != null) UnWireDataSource(); CurrencyManager oldListManager = listManager; @@ -1679,14 +1679,14 @@ internal void Set_ListManager(object newDataSource, string newDataMember, bool f // in the grid. the reason is that if the BindingContext was not yet requested, and it is created in the BindingContext prop // then the grid will call Set_ListManager again, and eventually that means that the dataGrid::listManager will // be hooked up twice to all the events (PositionChanged, ItemChanged, CurrentChanged) - if (newDataSource != null && this.BindingContext != null && !(newDataSource == Convert.DBNull)) - this.listManager = (CurrencyManager)this.BindingContext[newDataSource, newDataMember]; + if (newDataSource != null && BindingContext != null && !(newDataSource == Convert.DBNull)) + listManager = (CurrencyManager)BindingContext[newDataSource, newDataMember]; else listManager = null; // update the dataSource and the dateMember - this.dataSource = newDataSource; - this.dataMember = newDataMember == null ? "" : newDataMember; + dataSource = newDataSource; + dataMember = newDataMember == null ? "" : newDataMember; listManagerChanged = (listManager != oldListManager); @@ -1695,39 +1695,39 @@ internal void Set_ListManager(object newDataSource, string newDataMember, bool f { WireDataSource(); // update the policy - policy.UpdatePolicy(this.listManager, this.ReadOnly); + policy.UpdatePolicy(listManager, ReadOnly); } if (!Initializing) { if (listManager == null) { - if (this.ContainsFocus && this.ParentInternal == null) + if (ContainsFocus && ParentInternal == null) { - Debug.Assert(this.toBeDisposedEditingControl == null, "we should have removed the toBeDisposedEditingControl already"); + Debug.Assert(toBeDisposedEditingControl == null, "we should have removed the toBeDisposedEditingControl already"); // if we unparent the active control then the form won't close - for (int i = 0; i < this.Controls.Count; i++) + for (int i = 0; i < Controls.Count; i++) { - if (this.Controls[i].Focused) + if (Controls[i].Focused) { - this.toBeDisposedEditingControl = this.Controls[i]; + toBeDisposedEditingControl = Controls[i]; break; } } - if (this.toBeDisposedEditingControl == this.horizScrollBar || this.toBeDisposedEditingControl == this.vertScrollBar) + if (toBeDisposedEditingControl == horizScrollBar || toBeDisposedEditingControl == vertScrollBar) { - this.toBeDisposedEditingControl = null; + toBeDisposedEditingControl = null; } #if DEBUG else { - Debug.Assert(this.toBeDisposedEditingControl != null, "if the grid contains the focus, then the active control should be in the children of data grid control"); - Debug.Assert(this.editColumn != null, "if we have an editing control should be a control in the data grid column"); - if (this.editColumn is DataGridTextBoxColumn) + Debug.Assert(toBeDisposedEditingControl != null, "if the grid contains the focus, then the active control should be in the children of data grid control"); + Debug.Assert(editColumn != null, "if we have an editing control should be a control in the data grid column"); + if (editColumn is DataGridTextBoxColumn) { - Debug.Assert(((DataGridTextBoxColumn)this.editColumn).TextBox == this.toBeDisposedEditingControl, "if we have an editing control should be a control in the data grid column"); + Debug.Assert(((DataGridTextBoxColumn)editColumn).TextBox == toBeDisposedEditingControl, "if we have an editing control should be a control in the data grid column"); } } #endif // debug; @@ -1735,12 +1735,12 @@ internal void Set_ListManager(object newDataSource, string newDataMember, bool f } SetDataGridRows(null, 0); - this.defaultTableStyle.GridColumnStyles.Clear(); - SetDataGridTable(this.defaultTableStyle, forceColumnCreation); + defaultTableStyle.GridColumnStyles.Clear(); + SetDataGridTable(defaultTableStyle, forceColumnCreation); - if (this.toBeDisposedEditingControl != null) + if (toBeDisposedEditingControl != null) { - this.Controls.Add(this.toBeDisposedEditingControl); + Controls.Add(toBeDisposedEditingControl); } } } @@ -1755,7 +1755,7 @@ internal void Set_ListManager(object newDataSource, string newDataMember, bool f // if (listManagerChanged || gridState[GRIDSTATE_metaDataChanged]) { - if (this.Visible) + if (Visible) BeginUpdateInternal(); if (listManager != null) @@ -1764,12 +1764,12 @@ internal void Set_ListManager(object newDataSource, string newDataMember, bool f // we need to clear the old column collection even when navigating to // a list that has a table style associated w/ it. Why? because the // old column collection will be used by the parent rows to paint - this.defaultTableStyle.GridColumnStyles.ResetDefaultColumnCollection(); + defaultTableStyle.GridColumnStyles.ResetDefaultColumnCollection(); - DataGridTableStyle newGridTable = this.dataGridTables[listManager.GetListName()]; + DataGridTableStyle newGridTable = dataGridTables[listManager.GetListName()]; if (newGridTable == null) { - SetDataGridTable(this.defaultTableStyle, forceColumnCreation); + SetDataGridTable(defaultTableStyle, forceColumnCreation); } else { @@ -1783,15 +1783,15 @@ internal void Set_ListManager(object newDataSource, string newDataMember, bool f // when we create the rows we need to use the current dataGridTable // RecreateDataGridRows(); - if (this.Visible) + if (Visible) EndUpdateInternal(); beginUpdateInternal = false; ComputeMinimumRowHeaderWidth(); - if (this.myGridTable.IsDefault) - this.RowHeaderWidth = Math.Max(this.minRowHeaderWidth, this.RowHeaderWidth); + if (myGridTable.IsDefault) + RowHeaderWidth = Math.Max(minRowHeaderWidth, RowHeaderWidth); else - this.myGridTable.RowHeaderWidth = Math.Max(this.minRowHeaderWidth, this.RowHeaderWidth); + myGridTable.RowHeaderWidth = Math.Max(minRowHeaderWidth, RowHeaderWidth); ListHasErrors = DataGridSourceHasErrors(); @@ -1811,7 +1811,7 @@ internal void Set_ListManager(object newDataSource, string newDataMember, bool f { gridState[GRIDSTATE_inSetListManager] = false; // start painting again - if (beginUpdateInternal && this.Visible) + if (beginUpdateInternal && Visible) EndUpdateInternal(); } } @@ -1831,30 +1831,30 @@ public int CurrentRowIndex get { if (originalState == null) - return this.listManager == null ? -1 : this.listManager.Position; + return listManager == null ? -1 : listManager.Position; else { - if (this.BindingContext == null) + if (BindingContext == null) return -1; - CurrencyManager originalListManager = (CurrencyManager)this.BindingContext[originalState.DataSource, originalState.DataMember]; + CurrencyManager originalListManager = (CurrencyManager)BindingContext[originalState.DataSource, originalState.DataMember]; return originalListManager.Position; } } set { - if (this.listManager == null) + if (listManager == null) throw new InvalidOperationException(SR.DataGridSetSelectIndex); if (originalState == null) { - this.listManager.Position = value; + listManager.Position = value; currentRow = value; return; } // if we have a this.ListManager, then this.BindingManager cannot be null // - CurrencyManager originalListManager = (CurrencyManager)this.BindingContext[originalState.DataSource, originalState.DataMember]; + CurrencyManager originalListManager = (CurrencyManager)BindingContext[originalState.DataSource, originalState.DataMember]; originalListManager.Position = value; // this is for parent rows @@ -1980,7 +1980,7 @@ public DataGridLineStyle GridLineStyle if (gridLineStyle != value) { gridLineStyle = value; - this.myGridTable.ResetRelationsUI(); + myGridTable.ResetRelationsUI(); Invalidate(layout.Data); } } @@ -1990,7 +1990,7 @@ internal int GridLineWidth { get { - Debug.Assert(this.GridLineStyle == DataGridLineStyle.Solid || this.GridLineStyle == DataGridLineStyle.None, "are there any other styles?"); + Debug.Assert(GridLineStyle == DataGridLineStyle.Solid || GridLineStyle == DataGridLineStyle.None, "are there any other styles?"); return GridLineStyle == DataGridLineStyle.Solid ? 1 : 0; } } @@ -2236,7 +2236,7 @@ public Font HeaderFont { get { - return (headerFont == null ? this.Font : headerFont); + return (headerFont == null ? Font : headerFont); } set { @@ -2323,7 +2323,7 @@ internal SolidBrush HeaderForeBrush { get { - return this.headerForeBrush; + return headerForeBrush; } } @@ -2375,7 +2375,7 @@ internal int HorizontalOffset scroll = Rectangle.Union(scroll, layout.ColumnHeaders); horizontalOffset = value; - this.firstVisibleCol = ComputeFirstVisibleColumn(); + firstVisibleCol = ComputeFirstVisibleColumn(); // update the lastTotallyVisibleCol ComputeVisibleColumns(); @@ -2523,7 +2523,7 @@ public Color LinkHoverColor { get { - return this.LinkColor; + return LinkColor; } set { @@ -2587,8 +2587,8 @@ public bool AllowNavigation { gridState[GRIDSTATE_allowNavigation] = value; // let the Caption know about this: - this.Caption.BackButtonActive = !parentRows.IsEmpty() && (value); - this.Caption.BackButtonVisible = this.Caption.BackButtonActive; + Caption.BackButtonActive = !parentRows.IsEmpty() && (value); + Caption.BackButtonVisible = Caption.BackButtonActive; RecreateDataGridRows(); OnAllowNavigationChanged(EventArgs.Empty); @@ -2698,7 +2698,7 @@ public Color ParentRowsBackColor { if (IsTransparentColor(value)) throw new ArgumentException(SR.DataGridTransparentParentRowsBackColorNotAllowed); - this.parentRows.BackColor = value; + parentRows.BackColor = value; } } @@ -2744,7 +2744,7 @@ public Color ParentRowsForeColor } set { - this.parentRows.ForeColor = value; + parentRows.ForeColor = value; } } @@ -2868,16 +2868,16 @@ public bool ReadOnly } else { - recreateRows |= policy.UpdatePolicy(this.listManager, value); + recreateRows |= policy.UpdatePolicy(listManager, value); } gridState[GRIDSTATE_readOnlyMode] = value; - DataGridRow[] dataGridRows = this.DataGridRows; + DataGridRow[] dataGridRows = DataGridRows; if (recreateRows) { RecreateDataGridRows(); // keep the selected rows - DataGridRow[] currentDataGridRows = this.DataGridRows; + DataGridRow[] currentDataGridRows = DataGridRows; int rowCount = Math.Min(currentDataGridRows.Length, dataGridRows.Length); for (int i = 0; i < rowCount; i++) { @@ -3019,7 +3019,7 @@ public int RowHeaderWidth } set { - value = Math.Max(this.minRowHeaderWidth, value); + value = Math.Max(minRowHeaderWidth, value); if (rowHeaderWidth != value) { rowHeaderWidth = value; @@ -3092,7 +3092,7 @@ public int VisibleColumnCount { get { - return Math.Min(numVisibleCols, this.myGridTable == null ? 0 : this.myGridTable.GridColumnStyles.Count); + return Math.Min(numVisibleCols, myGridTable == null ? 0 : myGridTable.GridColumnStyles.Count); } } @@ -3149,7 +3149,7 @@ public int VisibleRowCount rowIndex >= firstVisibleRow && rowIndex <= firstVisibleRow + numVisibleRows) { Rectangle bounds = GetCellBounds(rowIndex, columnIndex); - this.Invalidate(bounds); + Invalidate(bounds); } } } @@ -3233,7 +3233,7 @@ private void DataSource_Changed(object sender, EventArgs ea) // the grid will receive the dataSource_Changed event when // allowAdd changes on the dataView. - policy.UpdatePolicy(this.ListManager, this.ReadOnly); + policy.UpdatePolicy(ListManager, ReadOnly); if (gridState[GRIDSTATE_inListAddNew]) { // we are adding a new row @@ -3246,7 +3246,7 @@ private void DataSource_Changed(object sender, EventArgs ea) int currentRowCount = DataGridRowsLength; // put the added row: // - gridRows[currentRowCount - 1] = new DataGridRelationshipRow(this, this.myGridTable, currentRowCount - 1); + gridRows[currentRowCount - 1] = new DataGridRelationshipRow(this, myGridTable, currentRowCount - 1); SetDataGridRows(gridRows, currentRowCount); } else if (gridState[GRIDSTATE_inAddNewRow] && !gridState[GRIDSTATE_inDeleteRow]) @@ -3259,7 +3259,7 @@ private void DataSource_Changed(object sender, EventArgs ea) else if (!gridState[GRIDSTATE_inDeleteRow]) { RecreateDataGridRows(); - currentRow = Math.Min(currentRow, this.listManager.Count); + currentRow = Math.Min(currentRow, listManager.Count); } bool oldListHasErrors = ListHasErrors; @@ -3275,7 +3275,7 @@ private void GridLineColorChanged(object sender, EventArgs e) } private void GridLineStyleChanged(object sender, EventArgs e) { - this.myGridTable.ResetRelationsUI(); + myGridTable.ResetRelationsUI(); Invalidate(layout.Data); } private void HeaderBackColorChanged(object sender, EventArgs e) @@ -3311,7 +3311,7 @@ private void LinkHoverColorChanged(object sender, EventArgs e) private void PreferredColumnWidthChanged(object sender, EventArgs e) { // reset the dataGridRows - SetDataGridRows(null, this.DataGridRowsLength); + SetDataGridRows(null, DataGridRowsLength); // layout the horizontal scroll bar PerformLayout(); // invalidate everything @@ -3319,13 +3319,13 @@ private void PreferredColumnWidthChanged(object sender, EventArgs e) } private void RowHeadersVisibleChanged(object sender, EventArgs e) { - layout.RowHeadersVisible = this.myGridTable == null ? false : this.myGridTable.RowHeadersVisible; + layout.RowHeadersVisible = myGridTable == null ? false : myGridTable.RowHeadersVisible; PerformLayout(); InvalidateInside(); } private void ColumnHeadersVisibleChanged(object sender, EventArgs e) { - layout.ColumnHeadersVisible = this.myGridTable == null ? false : this.myGridTable.ColumnHeadersVisible; + layout.ColumnHeadersVisible = myGridTable == null ? false : myGridTable.ColumnHeadersVisible; PerformLayout(); InvalidateInside(); } @@ -3339,9 +3339,9 @@ private void RowHeaderWidthChanged(object sender, EventArgs e) } private void AllowSortingChanged(object sender, EventArgs e) { - if (!this.myGridTable.AllowSorting && this.listManager != null) + if (!myGridTable.AllowSorting && listManager != null) { - IList list = this.listManager.List; + IList list = listManager.List; if (list is IBindingList) ((IBindingList)list).RemoveSort(); } @@ -3354,8 +3354,8 @@ private void DataSource_RowChanged(object sender, EventArgs ea) // to the latest changes in the list : CurrentChanged is fired before // ListChanged. // So invalidate the row if there is something to invalidate - DataGridRow[] rows = this.DataGridRows; - if (currentRow < this.DataGridRowsLength) + DataGridRow[] rows = DataGridRows; + if (currentRow < DataGridRowsLength) { InvalidateRow(currentRow); } @@ -3376,12 +3376,12 @@ private void DataSource_PositionChanged(object sender, EventArgs ea) // before the OnItemChanged event when a row will be deleted in the backEnd; // we still want to keep the old rows when the user deletes the rows using the grid // and we do not want to do the same work twice when the user adds a row via the grid - if (this.DataGridRowsLength > this.listManager.Count + (policy.AllowAdd ? 1 : 0) && !gridState[GRIDSTATE_inDeleteRow]) + if (DataGridRowsLength > listManager.Count + (policy.AllowAdd ? 1 : 0) && !gridState[GRIDSTATE_inDeleteRow]) { Debug.Assert(!gridState[GRIDSTATE_inAddNewRow] && !gridState[GRIDSTATE_inListAddNew], "how can the list decrease when we are adding a row?"); RecreateDataGridRows(); } - if (this.ListManager.Position != currentRow) + if (ListManager.Position != currentRow) { CurrentCell = new DataGridCell(listManager.Position, currentCol); @@ -3398,11 +3398,11 @@ internal void DataSource_MetaDataChanged(object sender, EventArgs e) private bool DataGridSourceHasErrors() { - if (this.listManager == null) + if (listManager == null) return false; - for (int i = 0; i < this.listManager.Count; i++) + for (int i = 0; i < listManager.Count; i++) { - object errObj = this.listManager[i]; + object errObj = listManager[i]; if (errObj is IDataErrorInfo) { string errString = ((IDataErrorInfo)errObj).Error; @@ -3416,17 +3416,17 @@ private bool DataGridSourceHasErrors() private void TableStylesCollectionChanged(object sender, CollectionChangeEventArgs ccea) { // if the users changed the collection of tableStyles - if (sender != this.dataGridTables) + if (sender != dataGridTables) return; - if (this.listManager == null) + if (listManager == null) return; if (ccea.Action == CollectionChangeAction.Add) { DataGridTableStyle tableStyle = (DataGridTableStyle)ccea.Element; - if (this.listManager.GetListName().Equals(tableStyle.MappingName)) + if (listManager.GetListName().Equals(tableStyle.MappingName)) { - Debug.Assert(this.myGridTable.IsDefault, "if the table is not default, then it had a name. how can one add another table to the collection w/ the same name and not throw an exception"); + Debug.Assert(myGridTable.IsDefault, "if the table is not default, then it had a name. how can one add another table to the collection w/ the same name and not throw an exception"); SetDataGridTable(tableStyle, true); // true for forcing column creation SetDataGridRows(null, 0); } @@ -3434,11 +3434,11 @@ private void TableStylesCollectionChanged(object sender, CollectionChangeEventAr else if (ccea.Action == CollectionChangeAction.Remove) { DataGridTableStyle tableStyle = (DataGridTableStyle)ccea.Element; - if (this.myGridTable.MappingName.Equals(tableStyle.MappingName)) + if (myGridTable.MappingName.Equals(tableStyle.MappingName)) { - Debug.Assert(this.myGridTable.IsDefault, "if the table is not default, then it had a name. how can one add another table to the collection w/ the same name and not throw an exception"); - this.defaultTableStyle.GridColumnStyles.ResetDefaultColumnCollection(); - SetDataGridTable(this.defaultTableStyle, true); // true for forcing column creation + Debug.Assert(myGridTable.IsDefault, "if the table is not default, then it had a name. how can one add another table to the collection w/ the same name and not throw an exception"); + defaultTableStyle.GridColumnStyles.ResetDefaultColumnCollection(); + SetDataGridTable(defaultTableStyle, true); // true for forcing column creation SetDataGridRows(null, 0); } } @@ -3448,14 +3448,14 @@ private void TableStylesCollectionChanged(object sender, CollectionChangeEventAr // we have to search to see if the collection of table styles contains one // w/ the same name as the list in the dataGrid - DataGridTableStyle newGridTable = this.dataGridTables[listManager.GetListName()]; + DataGridTableStyle newGridTable = dataGridTables[listManager.GetListName()]; if (newGridTable == null) { - if (!this.myGridTable.IsDefault) + if (!myGridTable.IsDefault) { // get rid of the old gridColumns - this.defaultTableStyle.GridColumnStyles.ResetDefaultColumnCollection(); - SetDataGridTable(this.defaultTableStyle, true); // true for forcing column creation + defaultTableStyle.GridColumnStyles.ResetDefaultColumnCollection(); + SetDataGridTable(defaultTableStyle, true); // true for forcing column creation SetDataGridRows(null, 0); } } @@ -3490,7 +3490,7 @@ private void DataSource_ItemChanged(object sender, ItemChangedEventArgs ea) else { // let's see how we are doing w/ the errors - object errObj = this.listManager[ea.Index]; + object errObj = listManager[ea.Index]; bool oldListHasErrors = ListHasErrors; if (errObj is IDataErrorInfo) { @@ -3511,7 +3511,7 @@ private void DataSource_ItemChanged(object sender, ItemChangedEventArgs ea) // we update the text in the edit box only when the currentRow // equals the ea.Index if (editColumn != null && ea.Index == currentRow) - editColumn.UpdateUI(this.ListManager, ea.Index, null); + editColumn.UpdateUI(ListManager, ea.Index, null); } } @@ -3657,7 +3657,7 @@ internal void OnNodeClick(EventArgs e) // boundaries possibly changed. do this with a call to Edit() // do this only if the firstVisibleColumn is the editColumn // - GridColumnStylesCollection columns = this.myGridTable.GridColumnStyles; + GridColumnStylesCollection columns = myGridTable.GridColumnStyles; if (firstVisibleCol > -1 && firstVisibleCol < columns.Count && columns[firstVisibleCol] == editColumn) Edit(); @@ -3755,20 +3755,20 @@ protected virtual void GridHScrolled(object sender, ScrollEventArgs se) se.Type == ScrollEventType.SmallDecrement) { int dCols = (se.Type == ScrollEventType.SmallIncrement) ? 1 : -1; - if (se.Type == ScrollEventType.SmallDecrement && this.negOffset == 0) + if (se.Type == ScrollEventType.SmallDecrement && negOffset == 0) { - GridColumnStylesCollection cols = this.myGridTable.GridColumnStyles; + GridColumnStylesCollection cols = myGridTable.GridColumnStyles; // if the column before the first visible column has width == 0 then skip it - for (int i = this.firstVisibleCol - 1; i >= 0 && cols[i].Width == 0; i--) + for (int i = firstVisibleCol - 1; i >= 0 && cols[i].Width == 0; i--) { dCols--; } } - if (se.Type == ScrollEventType.SmallIncrement && this.negOffset == 0) + if (se.Type == ScrollEventType.SmallIncrement && negOffset == 0) { - GridColumnStylesCollection cols = this.myGridTable.GridColumnStyles; - for (int i = this.firstVisibleCol; i > -1 && i < cols.Count && cols[i].Width == 0; i++) + GridColumnStylesCollection cols = myGridTable.GridColumnStyles; + for (int i = firstVisibleCol; i > -1 && i < cols.Count && cols[i].Width == 0; i++) { dCols++; } @@ -3782,7 +3782,7 @@ protected virtual void GridHScrolled(object sender, ScrollEventArgs se) HorizontalOffset = se.NewValue; } - this.gridState[GRIDSTATE_isScrolling] = false; + gridState[GRIDSTATE_isScrolling] = false; } /// @@ -3854,10 +3854,10 @@ private void HandleEndCurrentEdit() // and this will ultimately call InvalidateRow w/ a row number larger than the number of rows // so set the currentRow here: Debug.Assert(result == DialogResult.No, "we only put cancel and ok on the error message box"); - this.listManager.PositionChanged -= positionChangedHandler; - this.listManager.CancelCurrentEdit(); - this.listManager.Position = currentRow; - this.listManager.PositionChanged += positionChangedHandler; + listManager.PositionChanged -= positionChangedHandler; + listManager.CancelCurrentEdit(); + listManager.Position = currentRow; + listManager.PositionChanged += positionChangedHandler; } } } @@ -3887,10 +3887,10 @@ protected override void OnBackColorChanged(EventArgs e) protected override void OnBindingContextChanged(EventArgs e) { - if (this.DataSource != null && !gridState[GRIDSTATE_inSetListManager]) + if (DataSource != null && !gridState[GRIDSTATE_inSetListManager]) try { - Set_ListManager(this.DataSource, this.DataMember, true, false); // we do not want to create columns + Set_ListManager(DataSource, DataMember, true, false); // we do not want to create columns // if the columns are already created // the grid should not rely on OnBindingContextChanged // to create columns. @@ -3898,19 +3898,19 @@ protected override void OnBindingContextChanged(EventArgs e) catch { // at runtime we will rethrow the exception - if (this.Site == null || !this.Site.DesignMode) + if (Site == null || !Site.DesignMode) throw; RTLAwareMessageBox.Show(null, SR.DataGridExceptionInPaint, null, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); - if (this.Visible) + if (Visible) BeginUpdateInternal(); ResetParentRows(); Set_ListManager(null, string.Empty, true); - if (this.Visible) + if (Visible) EndUpdateInternal(); } base.OnBindingContextChanged(e); @@ -3936,7 +3936,7 @@ protected void OnShowParentDetailsButtonClicked(object sender, EventArgs e) // we need to fire the ParentRowsVisibleChanged event // and the ParentRowsVisible property just calls SetParentRowsVisibility and // then fires the event. - this.ParentRowsVisible = !caption.ToggleDownButtonDirection(); + ParentRowsVisible = !caption.ToggleDownButtonDirection(); EventHandler handler = (EventHandler)Events[EVENT_DOWNBUTTONCLICK]; if (handler != null) @@ -3955,7 +3955,7 @@ protected override void OnFontChanged(EventArgs e) { // let the caption know about the event changed // - this.Caption.OnGridFontChanged(); + Caption.OnGridFontChanged(); RecalculateFonts(); RecreateDataGridRows(); // get all the rows in the parentRows stack, and modify their height @@ -4114,16 +4114,16 @@ private void OnLeave_Grid() try { EndEdit(); - if (this.listManager != null && !this.gridState[GRIDSTATE_editControlChanging]) + if (listManager != null && !gridState[GRIDSTATE_editControlChanging]) { if (gridState[GRIDSTATE_inAddNewRow]) { // if the user did not type anything // in the addNewRow, then cancel the currentedit - this.listManager.CancelCurrentEdit(); + listManager.CancelCurrentEdit(); // set the addNewRow back - DataGridRow[] localGridRows = this.DataGridRows; - localGridRows[DataGridRowsLength - 1] = new DataGridAddNewRow(this, this.myGridTable, DataGridRowsLength - 1); + DataGridRow[] localGridRows = DataGridRows; + localGridRows[DataGridRowsLength - 1] = new DataGridAddNewRow(this, myGridTable, DataGridRowsLength - 1); SetDataGridRows(localGridRows, DataGridRowsLength); } else @@ -4138,7 +4138,7 @@ private void OnLeave_Grid() gridState[GRIDSTATE_canFocus] = true; // inAddNewRow should be set to false if the control was // not changing - if (!this.gridState[GRIDSTATE_editControlChanging]) + if (!gridState[GRIDSTATE_editControlChanging]) gridState[GRIDSTATE_inAddNewRow] = false; } } @@ -4164,7 +4164,7 @@ protected override void OnKeyPress(KeyPressEventArgs kpe) Debug.WriteLineIf(CompModSwitches.DataGridKeys.TraceVerbose, "DataGridKeys: OnKeyPress " + TypeDescriptor.GetConverter(typeof(Keys)).ConvertToString(kpe.KeyChar)); base.OnKeyPress(kpe); - GridColumnStylesCollection coll = this.myGridTable.GridColumnStyles; + GridColumnStylesCollection coll = myGridTable.GridColumnStyles; if (coll != null && currentCol > 0 && currentCol < coll.Count) { if (!coll[currentCol].ReadOnly) @@ -4225,7 +4225,7 @@ protected override void OnMouseDown(MouseEventArgs e) // Check column headers if (location.type == HitTestType.ColumnHeader) { - trackColumnHeader = this.myGridTable.GridColumnStyles[location.col].PropertyDescriptor; + trackColumnHeader = myGridTable.GridColumnStyles[location.col].PropertyDescriptor; return; } @@ -4257,7 +4257,7 @@ protected override void OnMouseDown(MouseEventArgs e) // check if the row is expanded: if the row is expanded, then the user clicked // on the node. when we navigate to child rows the rows are recreated // and are initially collapsed - localGridRows = this.DataGridRows; + localGridRows = DataGridRows; if (row < DataGridRowsLength && (localGridRows[row] is DataGridRelationshipRow) && ((DataGridRelationshipRow)localGridRows[row]).Expanded) EnsureVisible(row, 0); @@ -4276,11 +4276,11 @@ protected override void OnMouseDown(MouseEventArgs e) EndEdit(); if (!(DataGridRows[location.row] is DataGridAddNewRow)) { - int savedCurrentRow = this.currentRow; + int savedCurrentRow = currentRow; CurrentCell = new DataGridCell(location.row, currentCol); if (location.row != savedCurrentRow && - this.currentRow != location.row && - this.currentRow == savedCurrentRow) + currentRow != location.row && + currentRow == savedCurrentRow) { // The data grid was not able to move away from its previous current row. // Be defensive and don't select the row. @@ -4345,7 +4345,7 @@ protected override void OnMouseDown(MouseEventArgs e) // if (location.type == HitTestType.Cell) { - if (this.myGridTable.GridColumnStyles[location.col].MouseDown(location.row, e.X, e.Y)) + if (myGridTable.GridColumnStyles[location.col].MouseDown(location.row, e.X, e.Y)) return; DataGridCell target = new DataGridCell(location.row, location.col); if (policy.AllowEdit && CurrentCell.Equals(target)) @@ -4387,7 +4387,7 @@ protected override void OnMouseLeave(EventArgs e) internal void TextBoxOnMouseWheel(MouseEventArgs e) { - this.OnMouseWheel(e); + OnMouseWheel(e); } /// @@ -4539,7 +4539,7 @@ protected override void OnMouseUp(MouseEventArgs e) // Check column headers if (ci.type == HitTestType.ColumnHeader) { - PropertyDescriptor prop = this.myGridTable.GridColumnStyles[ci.col].PropertyDescriptor; + PropertyDescriptor prop = myGridTable.GridColumnStyles[ci.col].PropertyDescriptor; if (prop == trackColumnHeader) { ColumnHeaderClicked(trackColumnHeader); @@ -4612,7 +4612,7 @@ protected override void OnPaint(PaintEventArgs pe) { CheckHierarchyState(); - if (this.layout.dirty) + if (layout.dirty) ComputeLayout(); Graphics g = pe.Graphics; @@ -4647,7 +4647,7 @@ protected override void OnPaint(PaintEventArgs pe) catch { // at runtime we will rethrow the exception - if (this.Site == null || !this.Site.DesignMode) + if (Site == null || !Site.DesignMode) throw; gridState[GRIDSTATE_exceptionInPaint] = true; try @@ -4655,7 +4655,7 @@ protected override void OnPaint(PaintEventArgs pe) RTLAwareMessageBox.Show(null, SR.DataGridExceptionInPaint, null, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); - if (this.Visible) + if (Visible) BeginUpdateInternal(); ResetParentRows(); @@ -4665,7 +4665,7 @@ protected override void OnPaint(PaintEventArgs pe) finally { gridState[GRIDSTATE_exceptionInPaint] = false; - if (this.Visible) + if (Visible) EndUpdateInternal(); } } @@ -4699,7 +4699,7 @@ protected override void OnResize(EventArgs e) oldClientRectangle.Width, borderWidth); - Rectangle newClientRectangle = this.ClientRectangle; + Rectangle newClientRectangle = ClientRectangle; if (newClientRectangle.Width != oldClientRectangle.Width) { Invalidate(right); @@ -4720,7 +4720,7 @@ protected override void OnResize(EventArgs e) } //also, invalidate the ResizeBoxRect - if (!this.layout.ResizeBoxRect.IsEmpty) + if (!layout.ResizeBoxRect.IsEmpty) Invalidate(layout.ResizeBoxRect); layout.ClientRectangle = newClientRectangle; @@ -4842,7 +4842,7 @@ public override ISite Site } set { - ISite temp = this.Site; + ISite temp = Site; base.Site = value; if (value != temp && !Disposing) { @@ -4864,7 +4864,7 @@ internal void AddNewRow() gridState[GRIDSTATE_inAddNewRow] = true; try { - this.ListManager.AddNew(); + ListManager.AddNew(); } catch { @@ -4884,7 +4884,7 @@ internal void AddNewRow() /// public bool BeginEdit(DataGridColumnStyle gridColumn, int rowNumber) { - if (this.DataSource == null || this.myGridTable == null) + if (DataSource == null || myGridTable == null) return false; // We deny edit requests if we are already editing a cell. @@ -4893,7 +4893,7 @@ public bool BeginEdit(DataGridColumnStyle gridColumn, int rowNumber) else { int col = -1; - if ((col = this.myGridTable.GridColumnStyles.IndexOf(gridColumn)) < 0) + if ((col = myGridTable.GridColumnStyles.IndexOf(gridColumn)) < 0) return false; CurrentCell = new DataGridCell(rowNumber, col); ResetSelection(); @@ -4942,7 +4942,7 @@ private void CancelCursorUpdate() private void CheckHierarchyState() { - if (checkHierarchy && this.listManager != null && this.myGridTable != null) + if (checkHierarchy && listManager != null && myGridTable != null) { if (myGridTable == null) // there was nothing to check @@ -4988,10 +4988,10 @@ private void ColAutoResize(int col) string columnName = column.HeaderText; Font headerFont; - if (this.myGridTable.IsDefault) - headerFont = this.HeaderFont; + if (myGridTable.IsDefault) + headerFont = HeaderFont; else - headerFont = this.myGridTable.HeaderFont; + headerFont = myGridTable.HeaderFont; size = (int)g.MeasureString(columnName, headerFont).Width + layout.ColumnHeaders.Height + 1; // The sort triangle's width is equal to it's height int rowCount = listManager.Count; for (int row = 0; row < rowCount; ++row) @@ -5009,11 +5009,11 @@ private void ColAutoResize(int col) ComputeVisibleColumns(); bool lastColumnIsLastTotallyVisibleCol = true; - if (this.lastTotallyVisibleCol != -1) + if (lastTotallyVisibleCol != -1) { - for (int i = this.lastTotallyVisibleCol + 1; i < this.myGridTable.GridColumnStyles.Count; i++) + for (int i = lastTotallyVisibleCol + 1; i < myGridTable.GridColumnStyles.Count; i++) { - if (this.myGridTable.GridColumnStyles[i].PropertyDescriptor != null) + if (myGridTable.GridColumnStyles[i].PropertyDescriptor != null) { lastColumnIsLastTotallyVisibleCol = false; break; @@ -5029,21 +5029,21 @@ private void ColAutoResize(int col) // then we need to recompute the horizontalOffset, firstVisibleCol, negOffset. // lastTotallyVisibleCol remains the last column if (lastColumnIsLastTotallyVisibleCol && - (this.negOffset != 0 || this.horizontalOffset != 0)) + (negOffset != 0 || horizontalOffset != 0)) { // update the column width column._width = size; int cx = 0; - int colCount = this.myGridTable.GridColumnStyles.Count; + int colCount = myGridTable.GridColumnStyles.Count; int visibleWidth = layout.Data.Width; - GridColumnStylesCollection cols = this.myGridTable.GridColumnStyles; + GridColumnStylesCollection cols = myGridTable.GridColumnStyles; // assume everything fits - this.negOffset = 0; - this.horizontalOffset = 0; - this.firstVisibleCol = 0; + negOffset = 0; + horizontalOffset = 0; + firstVisibleCol = 0; for (int i = colCount - 1; i >= 0; i--) { @@ -5055,21 +5055,21 @@ private void ColAutoResize(int col) cx += cols[i].Width; if (cx > visibleWidth) { - if (this.negOffset == 0) + if (negOffset == 0) { - this.firstVisibleCol = i; - this.negOffset = cx - visibleWidth; - this.horizontalOffset = this.negOffset; - this.numVisibleCols++; + firstVisibleCol = i; + negOffset = cx - visibleWidth; + horizontalOffset = negOffset; + numVisibleCols++; } else { - this.horizontalOffset += cols[i].Width; + horizontalOffset += cols[i].Width; } } else { - this.numVisibleCols++; + numVisibleCols++; } } @@ -5109,9 +5109,9 @@ private void ColAutoResize(int col) g.Dispose(); } - if (this.horizScrollBar.Visible) + if (horizScrollBar.Visible) { - this.horizScrollBar.Value = HorizontalOffset; + horizScrollBar.Value = HorizontalOffset; } // OnColumnResize(EventArgs.Empty); } @@ -5171,7 +5171,7 @@ private void ColResizeEnd(MouseEventArgs e) Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: ColResizeEnd"); Debug.Assert(myGridTable != null, "Column resizing operations can't be called when myGridTable == null."); - this.gridState[GRIDSTATE_layoutSuspended] = true; + gridState[GRIDSTATE_layoutSuspended] = true; try { if (lastSplitBar != null) @@ -5198,9 +5198,9 @@ private void ColResizeEnd(MouseEventArgs e) ComputeVisibleColumns(); bool lastColumnIsLastTotallyVisibleCol = true; - for (int i = this.lastTotallyVisibleCol + 1; i < this.myGridTable.GridColumnStyles.Count; i++) + for (int i = lastTotallyVisibleCol + 1; i < myGridTable.GridColumnStyles.Count; i++) { - if (this.myGridTable.GridColumnStyles[i].PropertyDescriptor != null) + if (myGridTable.GridColumnStyles[i].PropertyDescriptor != null) { lastColumnIsLastTotallyVisibleCol = false; break; @@ -5208,18 +5208,18 @@ private void ColResizeEnd(MouseEventArgs e) } if (lastColumnIsLastTotallyVisibleCol && - (this.negOffset != 0 || this.horizontalOffset != 0)) + (negOffset != 0 || horizontalOffset != 0)) { int cx = 0; - int colCount = this.myGridTable.GridColumnStyles.Count; - int visibleWidth = this.layout.Data.Width; - GridColumnStylesCollection cols = this.myGridTable.GridColumnStyles; + int colCount = myGridTable.GridColumnStyles.Count; + int visibleWidth = layout.Data.Width; + GridColumnStylesCollection cols = myGridTable.GridColumnStyles; // assume everything fits - this.negOffset = 0; - this.horizontalOffset = 0; - this.firstVisibleCol = 0; + negOffset = 0; + horizontalOffset = 0; + firstVisibleCol = 0; for (int i = colCount - 1; i > -1; i--) { @@ -5232,26 +5232,26 @@ private void ColResizeEnd(MouseEventArgs e) if (cx > visibleWidth) { - if (this.negOffset == 0) + if (negOffset == 0) { - this.negOffset = cx - visibleWidth; - this.firstVisibleCol = i; - this.horizontalOffset = negOffset; - this.numVisibleCols++; + negOffset = cx - visibleWidth; + firstVisibleCol = i; + horizontalOffset = negOffset; + numVisibleCols++; } else { - this.horizontalOffset += cols[i].Width; + horizontalOffset += cols[i].Width; } } else { - this.numVisibleCols++; + numVisibleCols++; } } // and invalidate pretty much everything - Invalidate(Rectangle.Union(this.layout.Data, this.layout.ColumnHeaders)); + Invalidate(Rectangle.Union(layout.Data, layout.ColumnHeaders)); } else { @@ -5268,14 +5268,14 @@ private void ColResizeEnd(MouseEventArgs e) { Cursor.ClipInternal = Rectangle.Empty; CaptureInternal = false; - this.gridState[GRIDSTATE_layoutSuspended] = false; + gridState[GRIDSTATE_layoutSuspended] = false; } PerformLayout(); - if (this.horizScrollBar.Visible) + if (horizScrollBar.Visible) { - this.horizScrollBar.Value = HorizontalOffset; + horizScrollBar.Value = HorizontalOffset; } // OnColumnResize(EventArgs.Empty); } @@ -5301,7 +5301,7 @@ private void MetaDataChanged() } else { - Set_ListManager(this.DataSource, this.DataMember, true); + Set_ListManager(DataSource, DataMember, true); } } finally @@ -5321,7 +5321,7 @@ private void RowAutoResize(int row) Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: RowAutoResize"); EndEdit(); - CurrencyManager listManager = this.ListManager; + CurrencyManager listManager = ListManager; if (listManager == null) return; @@ -5452,8 +5452,8 @@ private void ColumnHeaderClicked(PropertyDescriptor prop) // OnColumnHeaderClick(EventArgs.Empty); bool allowSorting; - if (this.myGridTable.IsDefault) - allowSorting = this.AllowSorting; + if (myGridTable.IsDefault) + allowSorting = AllowSorting; else allowSorting = myGridTable.AllowSorting; @@ -5461,8 +5461,8 @@ private void ColumnHeaderClicked(PropertyDescriptor prop) return; // if (CompModSwitches.DataGridCursor.OutputVerbose) Debug.WriteLine("DataGridCursor: We are about to sort column " + col.ToString()); - ListSortDirection direction = this.ListManager.GetSortDirection(); - PropertyDescriptor sortColumn = this.ListManager.GetSortProperty(); + ListSortDirection direction = ListManager.GetSortDirection(); + PropertyDescriptor sortColumn = ListManager.GetSortProperty(); if (sortColumn != null && sortColumn.Equals(prop)) direction = (direction == ListSortDirection.Ascending) ? ListSortDirection.Descending : ListSortDirection.Ascending; else @@ -5472,7 +5472,7 @@ private void ColumnHeaderClicked(PropertyDescriptor prop) if (listManager.Count == 0) return; - this.ListManager.SetSort(prop, direction); + ListManager.SetSort(prop, direction); ResetSelection(); InvalidateInside(); @@ -5506,18 +5506,18 @@ private bool CommitEdit() if (editColumn.ReadOnly || gridState[GRIDSTATE_inAddNewRow]) { bool focusTheGrid = false; - if (this.ContainsFocus) + if (ContainsFocus) { focusTheGrid = true; } if (focusTheGrid && gridState[GRIDSTATE_canFocus]) - this.Focus(); + Focus(); editColumn.ConcedeFocus(); // set the focus back to the grid if (focusTheGrid && gridState[GRIDSTATE_canFocus] && CanFocus && !Focused) - this.Focus(); + Focus(); // reset the editControl flag gridState[GRIDSTATE_editControlChanging] = false; @@ -5619,7 +5619,7 @@ private void ComputeLayout() Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: ComputeLayout"); bool alignLeft = !isRightToLeft(); - Rectangle oldResizeRect = this.layout.ResizeBoxRect; + Rectangle oldResizeRect = layout.ResizeBoxRect; // hide the EditBox EndEdit(); @@ -5695,10 +5695,10 @@ private void ComputeLayout() newLayout.ColumnHeaders = Rectangle.Empty; } - bool newRowHeadersVisible = this.myGridTable.IsDefault ? this.RowHeadersVisible : this.myGridTable.RowHeadersVisible; - int newRowHeaderWidth = this.myGridTable.IsDefault ? this.RowHeaderWidth : this.myGridTable.RowHeaderWidth; + bool newRowHeadersVisible = myGridTable.IsDefault ? RowHeadersVisible : myGridTable.RowHeadersVisible; + int newRowHeaderWidth = myGridTable.IsDefault ? RowHeaderWidth : myGridTable.RowHeaderWidth; newLayout.RowHeadersVisible = newRowHeadersVisible; - if (this.myGridTable != null && newRowHeadersVisible) + if (myGridTable != null && newRowHeadersVisible) { Rectangle rowHeaders = newLayout.RowHeaders; if (alignLeft) @@ -5754,7 +5754,7 @@ private void ComputeLayout() newLayout.Data = insideLeft; newLayout.Inside = inside; - this.layout = newLayout; + layout = newLayout; LayoutScrollBars(); @@ -5763,10 +5763,10 @@ private void ComputeLayout() // note that we can't take the Invalidate call from the OnResize method, because if the // user enlarges the form then the old area will not be invalidated. // - if (!oldResizeRect.Equals(this.layout.ResizeBoxRect) && !this.layout.ResizeBoxRect.IsEmpty) - Invalidate(this.layout.ResizeBoxRect); + if (!oldResizeRect.Equals(layout.ResizeBoxRect) && !layout.ResizeBoxRect.IsEmpty) + Invalidate(layout.ResizeBoxRect); - this.layout.dirty = false; + layout.dirty = false; Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: " + layout.ToString()); } @@ -5802,9 +5802,9 @@ internal int MinimumRowHeaderWidth() internal void ComputeMinimumRowHeaderWidth() { minRowHeaderWidth = errorRowBitmapWidth; // the size of the pencil, star and row selector images are the same as the image for the error bitmap - if (this.ListHasErrors) + if (ListHasErrors) minRowHeaderWidth += errorRowBitmapWidth; - if (this.myGridTable != null && this.myGridTable.RelationsList.Count != 0) + if (myGridTable != null && myGridTable.RelationsList.Count != 0) minRowHeaderWidth += 15; // the size of the plus/minus glyph and spacing around it } @@ -5879,7 +5879,7 @@ private void ComputeVisibleColumns() lastTotallyVisibleCol = firstVisibleCol + numVisibleCols - 1; if (cx > visibleWidth) { - if (numVisibleCols <= 1 || (numVisibleCols == 2 && this.negOffset != 0)) + if (numVisibleCols <= 1 || (numVisibleCols == 2 && negOffset != 0)) { // no column is entirely visible lastTotallyVisibleCol = -1; @@ -5898,7 +5898,7 @@ private void ComputeVisibleColumns() private int ComputeFirstVisibleColumn() { int first = 0; - if (this.horizontalOffset == 0) + if (horizontalOffset == 0) { negOffset = 0; return 0; @@ -6026,18 +6026,18 @@ private DataGridState CreateChildState(string relationName, DataGridRow source) DataGridState dgs = new DataGridState(); string newDataMember; - if (string.IsNullOrEmpty(this.DataMember)) + if (string.IsNullOrEmpty(DataMember)) { newDataMember = relationName; } else { - newDataMember = this.DataMember + "." + relationName; + newDataMember = DataMember + "." + relationName; } - CurrencyManager childLM = (CurrencyManager)this.BindingContext[this.DataSource, newDataMember]; + CurrencyManager childLM = (CurrencyManager)BindingContext[DataSource, newDataMember]; - dgs.DataSource = this.DataSource; + dgs.DataSource = DataSource; dgs.DataMember = newDataMember; dgs.ListManager = childLM; @@ -6137,17 +6137,17 @@ protected override void Dispose(bool disposing) if (horizScrollBar != null) horizScrollBar.Dispose(); - if (this.toBeDisposedEditingControl != null) + if (toBeDisposedEditingControl != null) { - this.toBeDisposedEditingControl.Dispose(); - this.toBeDisposedEditingControl = null; + toBeDisposedEditingControl.Dispose(); + toBeDisposedEditingControl = null; } - GridTableStylesCollection tables = this.TableStyles; + GridTableStylesCollection tables = TableStyles; if (tables != null) { #if DEBUG - Debug.Assert(this.myGridTable == null || this.myGridTable.IsDefault || tables.Contains(this.myGridTable), "how come that the currentTable is not in the list of tables?"); + Debug.Assert(myGridTable == null || myGridTable.IsDefault || tables.Contains(myGridTable), "how come that the currentTable is not in the list of tables?"); #endif // DEBUG for (int i = 0; i < tables.Count; i++) tables[i].Dispose(); @@ -6240,7 +6240,7 @@ private void Edit(string displayText) editRow = localGridRows[currentRow]; // if the list has no columns, then what good is an edit? - if (this.myGridTable.GridColumnStyles.Count == 0) + if (myGridTable.GridColumnStyles.Count == 0) return; // what if the currentCol does not have a propDesc? @@ -6271,10 +6271,10 @@ private void Edit(string displayText) // everytime the edit column gets edited gridState[GRIDSTATE_editControlChanging] = true; - editColumn.Edit(this.ListManager, + editColumn.Edit(ListManager, currentRow, cellBounds, - myGridTable.ReadOnly || this.ReadOnly || !policy.AllowEdit, + myGridTable.ReadOnly || ReadOnly || !policy.AllowEdit, displayText, cellIsVisible); @@ -6344,18 +6344,18 @@ private void EndEdit() private void EnforceValidDataMember(object value) { Debug.Assert(value != null, "we should not have a null dataSource when we want to check for a valid dataMember"); - if (this.DataMember == null || this.DataMember.Length == 0) + if (DataMember == null || DataMember.Length == 0) return; - if (this.BindingContext == null) + if (BindingContext == null) return; // try { - BindingManagerBase bm = this.BindingContext[value, this.dataMember]; + BindingManagerBase bm = BindingContext[value, dataMember]; } catch { - this.dataMember = string.Empty; + dataMember = string.Empty; } } @@ -6370,12 +6370,12 @@ internal protected virtual void ColumnStartedEditing(Rectangle bounds) Debug.Assert(currentRow >= firstVisibleRow && currentRow <= firstVisibleRow + numVisibleRows, "how can one edit a row which is invisible?"); DataGridRow[] localGridRows = DataGridRows; - if (bounds.IsEmpty && this.editColumn is DataGridTextBoxColumn && this.currentRow != -1 && this.currentCol != -1) + if (bounds.IsEmpty && editColumn is DataGridTextBoxColumn && currentRow != -1 && currentCol != -1) { // set the bounds on the control // this will only work w/ our DataGridTexBox control - DataGridTextBoxColumn col = this.editColumn as DataGridTextBoxColumn; - Rectangle editBounds = this.GetCellBounds(this.currentRow, this.currentCol); + DataGridTextBoxColumn col = editColumn as DataGridTextBoxColumn; + Rectangle editBounds = GetCellBounds(currentRow, currentCol); gridState[GRIDSTATE_editControlChanging] = true; try @@ -6390,7 +6390,7 @@ internal protected virtual void ColumnStartedEditing(Rectangle bounds) if (gridState[GRIDSTATE_inAddNewRow]) { - int currentRowCount = this.DataGridRowsLength; + int currentRowCount = DataGridRowsLength; DataGridRow[] newDataGridRows = new DataGridRow[currentRowCount + 1]; for (int i = 0; i < currentRowCount; i++) { @@ -6399,7 +6399,7 @@ internal protected virtual void ColumnStartedEditing(Rectangle bounds) // put the AddNewRow - newDataGridRows[currentRowCount] = new DataGridAddNewRow(this, this.myGridTable, currentRowCount); + newDataGridRows[currentRowCount] = new DataGridAddNewRow(this, myGridTable, currentRowCount); SetDataGridRows(newDataGridRows, currentRowCount + 1); Edit(); @@ -6413,7 +6413,7 @@ internal protected virtual void ColumnStartedEditing(Rectangle bounds) gridState[GRIDSTATE_isEditing] = true; gridState[GRIDSTATE_isNavigating] = false; - InvalidateRowHeader(this.currentRow); + InvalidateRowHeader(currentRow); // tell the current row to lose the childFocuse if (currentRow < localGridRows.Length) @@ -6528,9 +6528,9 @@ private ListManager ListManagerForChildColumn(ListManager childListManager, Prop public void EndInit() { inInit = false; - if (myGridTable == null && this.ListManager != null) + if (myGridTable == null && ListManager != null) { - SetDataGridTable(this.TableStyles[this.ListManager.GetListName()], true); // true for forcing column creation + SetDataGridTable(TableStyles[ListManager.GetListName()], true); // true for forcing column creation } if (myGridTable != null) myGridTable.DataGrid = this; @@ -6753,17 +6753,17 @@ private void EnsureVisible(int row, int col) ScrollDown(dRows); } - if (this.firstVisibleCol == 0 && this.numVisibleCols == 0 && this.lastTotallyVisibleCol == -1) + if (firstVisibleCol == 0 && numVisibleCols == 0 && lastTotallyVisibleCol == -1) { // no columns are displayed whatsoever // some sanity checks - Debug.Assert(this.negOffset == 0, " no columns are displayed so the negative offset should be 0"); + Debug.Assert(negOffset == 0, " no columns are displayed so the negative offset should be 0"); return; } - int previousFirstVisibleCol = this.firstVisibleCol; - int previousNegOffset = this.negOffset; - int previousLastTotallyVisibleCol = this.lastTotallyVisibleCol; + int previousFirstVisibleCol = firstVisibleCol; + int previousNegOffset = negOffset; + int previousLastTotallyVisibleCol = lastTotallyVisibleCol; while (col < firstVisibleCol || col == firstVisibleCol && negOffset != 0 @@ -6773,17 +6773,17 @@ private void EnsureVisible(int row, int col) ScrollToColumn(col); - if (previousFirstVisibleCol == this.firstVisibleCol && - previousNegOffset == this.negOffset && - previousLastTotallyVisibleCol == this.lastTotallyVisibleCol) + if (previousFirstVisibleCol == firstVisibleCol && + previousNegOffset == negOffset && + previousLastTotallyVisibleCol == lastTotallyVisibleCol) { // nothing changed since the last iteration // don't get into an infinite loop break; } previousFirstVisibleCol = firstVisibleCol; - previousNegOffset = this.negOffset; - previousLastTotallyVisibleCol = this.lastTotallyVisibleCol; + previousNegOffset = negOffset; + previousLastTotallyVisibleCol = lastTotallyVisibleCol; // continue to scroll to the right until the scrollTo column is the totally last visible column or it is the first visible column } @@ -6795,7 +6795,7 @@ private void EnsureVisible(int row, int col) /// public Rectangle GetCurrentCellBounds() { - DataGridCell current = this.CurrentCell; + DataGridCell current = CurrentCell; return GetCellBounds(current.RowNumber, current.ColumnNumber); } @@ -6934,7 +6934,7 @@ private void InitializeColumnWidths() // Resize the columns to a approximation of a best fit. // We find the best fit width of NumRowsForAutoResize rows // and use it for each column. - int preferredColumnWidth = this.myGridTable.IsDefault ? this.PreferredColumnWidth : this.myGridTable.PreferredColumnWidth; + int preferredColumnWidth = myGridTable.IsDefault ? PreferredColumnWidth : myGridTable.PreferredColumnWidth; // if we set the PreferredColumnWidth to something else than AutoColumnSize // then use that value // @@ -6982,7 +6982,7 @@ internal void InvalidateCaptionRect(Rectangle r) /// internal void InvalidateColumn(int column) { - GridColumnStylesCollection gridColumns = this.myGridTable.GridColumnStyles; + GridColumnStylesCollection gridColumns = myGridTable.GridColumnStyles; if (column < 0 || gridColumns == null || gridColumns.Count <= column) return; @@ -7057,7 +7057,7 @@ private void InvalidateRowHeader(int rowNumber) invalid.Y = GetRowTop(rowNumber); invalid.X = layout.RowHeaders.X; invalid.Width = layout.RowHeaders.Width; - invalid.Height = this.DataGridRows[rowNumber].Height; + invalid.Height = DataGridRows[rowNumber].Height; Invalidate(invalid); } } @@ -7151,7 +7151,7 @@ private void LayoutScrollBars() // // and anyway, ComputeVisibleRows will call the DataGridRows accessor // - DataGridRow[] gridRows = this.DataGridRows; + DataGridRow[] gridRows = DataGridRows; // at this stage, the data grid columns may have their width set to -1 ( ie, their width is uninitialized ) // make sure that the totalWidth is at least 0 @@ -7183,7 +7183,7 @@ private void LayoutScrollBars() needVertScrollbar = true; } - this.firstVisibleCol = ComputeFirstVisibleColumn(); + firstVisibleCol = ComputeFirstVisibleColumn(); // we compute the number of visible columns only after we set up the vertical scroll bar. ComputeVisibleColumns(); @@ -7237,7 +7237,7 @@ private void LayoutScrollBars() horizScrollBar.Maximum = totalWidth; horizScrollBar.SmallChange = 1; horizScrollBar.LargeChange = Math.Max(totalWidth - widthNotVisible, 0); - horizScrollBar.Enabled = this.Enabled; + horizScrollBar.Enabled = Enabled; horizScrollBar.RightToLeft = RightToLeft; horizScrollBar.Bounds = new Rectangle(alignToRight ? layout.Inside.X + layout.ResizeBoxRect.Width : layout.Inside.X, layout.Data.Bottom, @@ -7263,7 +7263,7 @@ private void LayoutScrollBars() vertScrollBarTop, vertScrollBar.Width, layout.Data.Height + layout.ColumnHeaders.Height); - vertScrollBar.Enabled = this.Enabled; + vertScrollBar.Enabled = Enabled; vertScrollBar.Visible = true; if (alignToRight) layout.Data.X += vertScrollBar.Width; @@ -7314,13 +7314,13 @@ public void NavigateBack() if (parentRows.GetTopParent() == null) originalState = null; - DataGridRow[] localGridRows = this.DataGridRows; + DataGridRow[] localGridRows = DataGridRows; // what if the user changed the ReadOnly property // on the grid while the user was navigating to the child rows? // // what if the policy does not allow for allowAdd? // - if ((this.ReadOnly || !policy.AllowAdd) == (localGridRows[DataGridRowsLength - 1] is DataGridAddNewRow)) + if ((ReadOnly || !policy.AllowAdd) == (localGridRows[DataGridRowsLength - 1] is DataGridAddNewRow)) { int newDataGridRowsLength = (ReadOnly || !policy.AllowAdd) ? DataGridRowsLength - 1 : DataGridRowsLength + 1; DataGridRow[] newDataGridRows = new DataGridRow[newDataGridRowsLength]; @@ -7328,8 +7328,8 @@ public void NavigateBack() { newDataGridRows[i] = DataGridRows[i]; } - if (!this.ReadOnly && policy.AllowAdd) - newDataGridRows[newDataGridRowsLength - 1] = new DataGridAddNewRow(this, this.myGridTable, newDataGridRowsLength - 1); + if (!ReadOnly && policy.AllowAdd) + newDataGridRows[newDataGridRowsLength - 1] = new DataGridAddNewRow(this, myGridTable, newDataGridRowsLength - 1); SetDataGridRows(newDataGridRows, newDataGridRowsLength); } @@ -7337,14 +7337,14 @@ public void NavigateBack() // it may be the case that in between the user added a tableStyle that is different // from the one that is currently in the grid // in that case, we need to reset the dataGridTableStyle in the rows - localGridRows = this.DataGridRows; + localGridRows = DataGridRows; if (localGridRows != null && localGridRows.Length != 0) { DataGridTableStyle dgTable = localGridRows[0].DataGridTableStyle; - if (dgTable != this.myGridTable) + if (dgTable != myGridTable) { for (int i = 0; i < localGridRows.Length; i++) - localGridRows[i].DataGridTableStyle = this.myGridTable; + localGridRows[i].DataGridTableStyle = myGridTable; } } @@ -7352,21 +7352,21 @@ public void NavigateBack() // we also have the default gridColumns, w/ width = -1 // we need to set the width on the new gridColumns // - if (this.myGridTable.GridColumnStyles.Count > 0 && this.myGridTable.GridColumnStyles[0].Width == -1) + if (myGridTable.GridColumnStyles.Count > 0 && myGridTable.GridColumnStyles[0].Width == -1) { #if DEBUG - GridColumnStylesCollection cols = this.myGridTable.GridColumnStyles; + GridColumnStylesCollection cols = myGridTable.GridColumnStyles; for (int i = 0; i < cols.Count; i++) { Debug.Assert(cols[i].Width == -1, "Sanity check"); } - Debug.Assert(this.myGridTable.IsDefault, "when we navigate to the parent rows and the columns have widths -1 we are using the default table"); + Debug.Assert(myGridTable.IsDefault, "when we navigate to the parent rows and the columns have widths -1 we are using the default table"); #endif // DEBUG InitializeColumnWidths(); } // reset the currentRow to the old position in the listmanager: - currentRow = this.ListManager.Position == -1 ? 0 : this.ListManager.Position; + currentRow = ListManager.Position == -1 ? 0 : ListManager.Position; // if the AllowNavigation changed while the user was navigating the // child tables, so that the new navigation mode does not allow childNavigation anymore @@ -7442,7 +7442,7 @@ internal void NavigateTo(string relationName, DataGridRow source, bool fromRow) // try { - this.listManager.EndCurrentEdit(); + listManager.EndCurrentEdit(); } catch { @@ -7464,7 +7464,7 @@ internal void NavigateTo(string relationName, DataGridRow source, bool fromRow) // and then set the position in the listManager to the new row. // if (source.RowNumber != CurrentRow) - this.listManager.Position = source.RowNumber; + listManager.Position = source.RowNumber; // We save our state if the parent rows stack is empty. if (parentRows.GetTopParent() == null) @@ -7497,9 +7497,9 @@ private void NavigateTo(DataGridState childState) // Retrieve the child state childState.PullState(this, true); // true for creating columns when we navigate to child rows - if (this.listManager.Position != this.currentRow) + if (listManager.Position != currentRow) { - this.currentRow = listManager.Position == -1 ? 0 : listManager.Position; + currentRow = listManager.Position == -1 ? 0 : listManager.Position; } if (parentRows.GetTopParent() != null) @@ -7541,19 +7541,19 @@ private Point NormalizeToRow(int x, int y, int row) internal void OnColumnCollectionChanged(object sender, CollectionChangeEventArgs e) { DataGridTableStyle table = (DataGridTableStyle)sender; - if (table.Equals(this.myGridTable)) + if (table.Equals(myGridTable)) { // if we changed the column collection, then we need to set the property // descriptors in the column collection. // unless the user set the propertyDescriptor in the columnCollection // - if (!this.myGridTable.IsDefault) + if (!myGridTable.IsDefault) { // if the element in the collectionChangeEventArgs is not null // and the action is refresh, then it means that the user // set the propDesc. we do not want to override this. if (e.Action != CollectionChangeAction.Refresh || e.Element == null) - PairTableStylesAndGridColumns(this.listManager, this.myGridTable, false); + PairTableStylesAndGridColumns(listManager, myGridTable, false); } Invalidate(); PerformLayout(); @@ -7594,14 +7594,14 @@ private int PaintColumnHeaderText(Graphics g, Rectangle boundingRect) { int cx = 0; Rectangle textBounds = boundingRect; - GridColumnStylesCollection gridColumns = this.myGridTable.GridColumnStyles; + GridColumnStylesCollection gridColumns = myGridTable.GridColumnStyles; bool alignRight = isRightToLeft(); int nGridCols = gridColumns.Count; // for sorting PropertyDescriptor sortProperty = null; - sortProperty = this.ListManager.GetSortProperty(); + sortProperty = ListManager.GetSortProperty(); // Now paint the column header text! for (int col = firstVisibleCol; col < nGridCols; ++col) @@ -7616,7 +7616,7 @@ private int PaintColumnHeaderText(Graphics g, Rectangle boundingRect) TriangleDirection whichWay = TriangleDirection.Up; if (columnSorted) { - ListSortDirection direction = this.ListManager.GetSortDirection(); + ListSortDirection direction = ListManager.GetSortDirection(); if (direction == ListSortDirection.Descending) whichWay = TriangleDirection.Down; } @@ -7640,10 +7640,10 @@ private int PaintColumnHeaderText(Graphics g, Rectangle boundingRect) // if the user set the HeaderBackBrush property on the // dataGrid, then use that property Brush headerBrush; - if (this.myGridTable.IsDefault) + if (myGridTable.IsDefault) headerBrush = HeaderBackBrush; else - headerBrush = this.myGridTable.HeaderBackBrush; + headerBrush = myGridTable.HeaderBackBrush; g.FillRectangle(headerBrush, textBounds); // granted, the code would be a lot cleaner if we were using a "new Rectangle" @@ -7678,8 +7678,8 @@ private int PaintColumnHeaderText(Graphics g, Rectangle boundingRect) format.Alignment = StringAlignment.Near; } g.DrawString(gridColumns[col].HeaderText, - this.myGridTable.IsDefault ? this.HeaderFont : this.myGridTable.HeaderFont, - this.myGridTable.IsDefault ? this.HeaderForeBrush : this.myGridTable.HeaderForeBrush, + myGridTable.IsDefault ? HeaderFont : myGridTable.HeaderFont, + myGridTable.IsDefault ? HeaderForeBrush : myGridTable.HeaderForeBrush, textBounds, format); format.Dispose(); @@ -7708,8 +7708,8 @@ private int PaintColumnHeaderText(Graphics g, Rectangle boundingRect) int deflateValue = Math.Max(0, (textBounds.Height - 5) / 2); triBounds.Inflate(-deflateValue, -deflateValue); - Pen pen1 = new Pen(this.BackgroundBrush); - Pen pen2 = new Pen(this.myGridTable.BackBrush); + Pen pen1 = new Pen(BackgroundBrush); + Pen pen2 = new Pen(myGridTable.BackBrush); Triangle.Paint(g, triBounds, whichWay, headerBrush, pen1, pen2, pen1, true); pen1.Dispose(); pen2.Dispose(); @@ -7758,10 +7758,10 @@ private void PaintBorder(Graphics g, Rectangle bounds) { Brush br; - if (this.myGridTable.IsDefault) - br = this.HeaderForeBrush; + if (myGridTable.IsDefault) + br = HeaderForeBrush; else - br = this.myGridTable.HeaderForeBrush; + br = myGridTable.HeaderForeBrush; g.FillRectangle(br, bounds.X, bounds.Y, bounds.Width + 2, 2); g.FillRectangle(br, bounds.Right - 2, bounds.Y, 2, bounds.Height + 2); g.FillRectangle(br, bounds.X, bounds.Bottom - 2, bounds.Width + 2, 2); @@ -7786,7 +7786,7 @@ private void PaintGrid(Graphics g, Rectangle gridBounds) Rectangle rc = gridBounds; - if (this.listManager != null) + if (listManager != null) { if (layout.ColumnHeadersVisible) { @@ -7802,10 +7802,10 @@ private void PaintGrid(Graphics g, Rectangle gridBounds) if (layout.TopLeftHeader.Width > 0) { - if (this.myGridTable.IsDefault) - g.FillRectangle(this.HeaderBackBrush, layout.TopLeftHeader); + if (myGridTable.IsDefault) + g.FillRectangle(HeaderBackBrush, layout.TopLeftHeader); else - g.FillRectangle(this.myGridTable.HeaderBackBrush, layout.TopLeftHeader); + g.FillRectangle(myGridTable.HeaderBackBrush, layout.TopLeftHeader); if (!FlatMode) { @@ -7851,7 +7851,7 @@ private void DeleteDataGridRows(int deletedRows) if (gridState[GRIDSTATE_inAddNewRow]) { - newDataGridRows[currentRowCount - selectedEntries] = new DataGridAddNewRow(this, this.myGridTable, currentRowCount - selectedEntries); + newDataGridRows[currentRowCount - selectedEntries] = new DataGridAddNewRow(this, myGridTable, currentRowCount - selectedEntries); gridState[GRIDSTATE_inAddNewRow] = false; } @@ -8056,15 +8056,15 @@ private void DeleteRows(DataGridRow[] localGridRows) { int rowsDeleted = 0; - int currentRowsCount = this.listManager == null ? 0 : this.listManager.Count; + int currentRowsCount = listManager == null ? 0 : listManager.Count; - if (this.Visible) + if (Visible) BeginUpdateInternal(); try { - if (this.ListManager != null) + if (ListManager != null) { - for (int i = 0; i < this.DataGridRowsLength; i++) + for (int i = 0; i < DataGridRowsLength; i++) { if (localGridRows[i].Selected) { @@ -8075,7 +8075,7 @@ private void DeleteRows(DataGridRow[] localGridRows) } else { - this.ListManager.RemoveAt(i - rowsDeleted); + ListManager.RemoveAt(i - rowsDeleted); rowsDeleted++; } } @@ -8090,14 +8090,14 @@ private void DeleteRows(DataGridRow[] localGridRows) // RecreateDataGridRows(); gridState[GRIDSTATE_inDeleteRow] = false; - if (this.Visible) + if (Visible) EndUpdateInternal(); throw; } // keep the copy of the old rows in place // it may be the case that deleting one row could cause multiple rows to be deleted in the same list // - if (this.listManager != null && currentRowsCount == this.listManager.Count + rowsDeleted) + if (listManager != null && currentRowsCount == listManager.Count + rowsDeleted) { DeleteDataGridRows(rowsDeleted); } @@ -8107,10 +8107,10 @@ private void DeleteRows(DataGridRow[] localGridRows) } gridState[GRIDSTATE_inDeleteRow] = false; - if (this.Visible) + if (Visible) EndUpdateInternal(); - if (this.listManager != null && currentRowsCount != this.listManager.Count + rowsDeleted) + if (listManager != null && currentRowsCount != listManager.Count + rowsDeleted) { Invalidate(); } @@ -8177,7 +8177,7 @@ protected bool ProcessGridKey(KeyEventArgs ke) } } - GridColumnStylesCollection cols = this.myGridTable.GridColumnStyles; + GridColumnStylesCollection cols = myGridTable.GridColumnStyles; int firstColumnMarkedVisible = 0; int lastColumnMarkedVisible = cols.Count; for (int i = 0; i < cols.Count; i++) @@ -8204,7 +8204,7 @@ protected bool ProcessGridKey(KeyEventArgs ke) return ProcessTabKey(biDiKe.KeyData); case Keys.Up: gridState[GRIDSTATE_childLinkFocused] = false; - if (this.dataGridRowsLength == 0) + if (dataGridRowsLength == 0) { return true; } @@ -8292,7 +8292,7 @@ protected bool ProcessGridKey(KeyEventArgs ke) break; case Keys.Down: gridState[GRIDSTATE_childLinkFocused] = false; - if (this.dataGridRowsLength == 0) + if (dataGridRowsLength == 0) { return true; } @@ -8406,7 +8406,7 @@ protected bool ProcessGridKey(KeyEventArgs ke) return false; case Keys.Space: gridState[GRIDSTATE_childLinkFocused] = false; - if (this.dataGridRowsLength == 0) + if (dataGridRowsLength == 0) { return true; } @@ -8424,7 +8424,7 @@ protected bool ProcessGridKey(KeyEventArgs ke) return false; case Keys.Next: gridState[GRIDSTATE_childLinkFocused] = false; - if (this.dataGridRowsLength == 0) + if (dataGridRowsLength == 0) { return true; } @@ -8460,7 +8460,7 @@ protected bool ProcessGridKey(KeyEventArgs ke) } break; case Keys.Prior: - if (this.dataGridRowsLength == 0) + if (dataGridRowsLength == 0) { return true; } @@ -8517,13 +8517,13 @@ protected bool ProcessGridKey(KeyEventArgs ke) if (currentCol == firstColumnMarkedVisible && currentRow != 0) { CurrentRow = CurrentRow - 1; - int newCol = MoveLeftRight(this.myGridTable.GridColumnStyles, this.myGridTable.GridColumnStyles.Count, false); + int newCol = MoveLeftRight(myGridTable.GridColumnStyles, myGridTable.GridColumnStyles.Count, false); Debug.Assert(newCol != -1, "there should be at least a visible column, right?"); CurrentColumn = newCol; } else { - int newCol = MoveLeftRight(this.myGridTable.GridColumnStyles, currentCol, false); + int newCol = MoveLeftRight(myGridTable.GridColumnStyles, currentCol, false); if (newCol == -1) { if (currentRow == 0) @@ -8559,7 +8559,7 @@ protected bool ProcessGridKey(KeyEventArgs ke) } else { - int newCol = MoveLeftRight(this.myGridTable.GridColumnStyles, this.currentCol, true); + int newCol = MoveLeftRight(myGridTable.GridColumnStyles, currentCol, true); if (newCol == cols.Count + 1) { // navigate to the first visible column @@ -8585,7 +8585,7 @@ protected bool ProcessGridKey(KeyEventArgs ke) #endif case Keys.Home: gridState[GRIDSTATE_childLinkFocused] = false; - if (this.dataGridRowsLength == 0) + if (dataGridRowsLength == 0) { return true; } @@ -8623,7 +8623,7 @@ protected bool ProcessGridKey(KeyEventArgs ke) // in the listManager is -1, and the currentPosition in the grid is 0 if (ListManager != null && ListManager.Count > 0) { - Debug.Assert(ListManager.Position == this.currentRow, + Debug.Assert(ListManager.Position == currentRow, "Current row out of sync with DataSource", "The DataSource's Position property should be mirrored by the CurrentCell.RowNumber of the DataGrid."); } @@ -8632,7 +8632,7 @@ protected bool ProcessGridKey(KeyEventArgs ke) gridState[GRIDSTATE_inDeleteRow] = true; DeleteRows(localGridRows); // set the currentRow to the position in the list - this.currentRow = this.listManager.Count == 0 ? 0 : this.listManager.Position; + currentRow = listManager.Count == 0 ? 0 : listManager.Position; numSelectedRows = 0; } else @@ -8643,7 +8643,7 @@ protected bool ProcessGridKey(KeyEventArgs ke) break; case Keys.End: gridState[GRIDSTATE_childLinkFocused] = false; - if (this.dataGridRowsLength == 0) + if (dataGridRowsLength == 0) { return true; } @@ -8726,9 +8726,9 @@ protected bool ProcessGridKey(KeyEventArgs ke) AbortEdit(); // we have to invalidate the row header ( make it display the row selector instead of the pencil ) - if (layout.RowHeadersVisible && this.currentRow > -1) + if (layout.RowHeadersVisible && currentRow > -1) { - Rectangle rowHdrRect = GetRowRect(this.currentRow); + Rectangle rowHdrRect = GetRowRect(currentRow); rowHdrRect.Width = layout.RowHeaders.Width; Invalidate(rowHdrRect); } @@ -8800,7 +8800,7 @@ protected override bool ProcessKeyPreview(ref Message m) /// protected bool ProcessTabKey(Keys keyData) { - if (this.listManager == null || myGridTable == null) + if (listManager == null || myGridTable == null) return false; bool wasEditing = false; int columnCount = myGridTable.GridColumnStyles.Count; @@ -8844,7 +8844,7 @@ protected bool ProcessTabKey(Keys keyData) // see if the child relationships can use this TAB key DataGridRow[] localRows = DataGridRows; - GridColumnStylesCollection cols = this.myGridTable.GridColumnStyles; + GridColumnStylesCollection cols = myGridTable.GridColumnStyles; int lastColumnMarkedVisible = 0; int firstColumnMarkedVisible = cols.Count - 1; @@ -8888,14 +8888,14 @@ protected bool ProcessTabKey(Keys keyData) // let the grid regain focus // introduced because of that BeginInvoke thing in the OnLeave method.... if (gridState[GRIDSTATE_canFocus] && CanFocus && !Focused) - this.Focus(); + Focus(); return true; } } // actually, it turns out that we should leave the // control if we are in the last row - if ((this.currentRow == this.DataGridRowsLength - 1) && ((keyData & Keys.Shift) == 0)) + if ((currentRow == DataGridRowsLength - 1) && ((keyData & Keys.Shift) == 0)) { EndEdit(); @@ -8921,7 +8921,7 @@ protected bool ProcessTabKey(Keys keyData) // let the grid regain focus // introduced because of that BeginInvoke thing in the OnLeave method.... if (gridState[GRIDSTATE_canFocus] && CanFocus && !Focused) - this.Focus(); + Focus(); return true; } } @@ -8944,7 +8944,7 @@ protected bool ProcessTabKey(Keys keyData) // if we are on the first cell ( not on the addNewRow ) // then shift - tab should move to the next control on the form - if (this.currentRow == 0 && ((keyData & Keys.Shift) == Keys.Shift)) + if (currentRow == 0 && ((keyData & Keys.Shift) == Keys.Shift)) { EndEdit(); return base.ProcessDialogKey(keyData); @@ -8984,7 +8984,7 @@ protected bool ProcessTabKey(Keys keyData) { // part deux: when we hilite the childLink and then press shift-tab, we // don't want to navigate at the second to last column - InvalidateRow(this.currentRow); + InvalidateRow(currentRow); Edit(); } else @@ -9016,9 +9016,9 @@ virtual protected void CancelEditing() if (gridState[GRIDSTATE_inAddNewRow]) { gridState[GRIDSTATE_inAddNewRow] = false; - DataGridRow[] localGridRows = this.DataGridRows; + DataGridRow[] localGridRows = DataGridRows; - localGridRows[DataGridRowsLength - 1] = new DataGridAddNewRow(this, this.myGridTable, DataGridRowsLength - 1); + localGridRows[DataGridRowsLength - 1] = new DataGridAddNewRow(this, myGridTable, DataGridRowsLength - 1); SetDataGridRows(localGridRows, DataGridRowsLength); } } @@ -9036,8 +9036,8 @@ internal void RecalculateFonts() linkFontHeight = LinkFont.Height; captionFontHeight = CaptionFont.Height; - if (this.myGridTable == null || this.myGridTable.IsDefault) - headerFontHeight = this.HeaderFont.Height; + if (myGridTable == null || myGridTable.IsDefault) + headerFontHeight = HeaderFont.Height; else headerFontHeight = myGridTable.HeaderFont.Height; } @@ -9132,11 +9132,11 @@ private void ScrollDown(int rows) ClearRegionCache(); // we should put "dataGridRowsLength -1" - int newFirstRow = Math.Max(0, Math.Min(firstVisibleRow + rows, this.DataGridRowsLength - 1)); + int newFirstRow = Math.Max(0, Math.Min(firstVisibleRow + rows, DataGridRowsLength - 1)); int oldFirstRow = firstVisibleRow; firstVisibleRow = newFirstRow; vertScrollBar.Value = newFirstRow; - bool wasEditing = this.gridState[GRIDSTATE_isEditing]; + bool wasEditing = gridState[GRIDSTATE_isEditing]; ComputeVisibleRows(); if (gridState[GRIDSTATE_isScrolling]) @@ -9183,15 +9183,15 @@ private void ScrollRight(int columns) // if we try to scroll past the last totally visible column, // then the toolTips will dissapear - if (this.myGridTable.IsDefault) + if (myGridTable.IsDefault) nVisibleCols = nGridCols; else for (int i = 0; i < nGridCols; i++) if (gridColumns[i].PropertyDescriptor != null) nVisibleCols++; - if (this.lastTotallyVisibleCol == nVisibleCols - 1 && columns > 0 || - this.firstVisibleCol == 0 && columns < 0 && negOffset == 0) + if (lastTotallyVisibleCol == nVisibleCols - 1 && columns > 0 || + firstVisibleCol == 0 && columns < 0 && negOffset == 0) return; newCol = Math.Min(newCol, nGridCols - 1); @@ -9322,7 +9322,7 @@ private void PairTableStylesAndGridColumns(CurrencyManager lm, DataGridTableStyl internal void SetDataGridTable(DataGridTableStyle newTable, bool forceColumnCreation) { // we have to listen to the dataGridTable for the propertyChangedEvent - if (this.myGridTable != null) + if (myGridTable != null) { // unwire the propertyChanged event UnWireTableStylePropChanged(myGridTable); @@ -9341,7 +9341,7 @@ internal void SetDataGridTable(DataGridTableStyle newTable, bool forceColumnCrea WireTableStylePropChanged(myGridTable); - this.layout.RowHeadersVisible = newTable.IsDefault ? this.RowHeadersVisible : newTable.RowHeadersVisible; + layout.RowHeadersVisible = newTable.IsDefault ? RowHeadersVisible : newTable.RowHeadersVisible; // we need to force the grid into the dataGridTableStyle // this way the controls in the columns will be parented @@ -9358,8 +9358,8 @@ internal void SetDataGridTable(DataGridTableStyle newTable, bool forceColumnCrea // pair the tableStyles and GridColumns // - if (this.listManager != null) - PairTableStylesAndGridColumns(this.listManager, this.myGridTable, forceColumnCreation); + if (listManager != null) + PairTableStylesAndGridColumns(listManager, myGridTable, forceColumnCreation); // reset the relations UI on the newTable if (newTable != null) @@ -9374,10 +9374,10 @@ internal void SetDataGridTable(DataGridTableStyle newTable, bool forceColumnCrea // if we add a tableStyle that mapps to the // current listName, then we should set the currentRow to the // position in the listManager - if (this.listManager == null) + if (listManager == null) currentRow = 0; else - currentRow = this.listManager.Position == -1 ? 0 : listManager.Position; + currentRow = listManager.Position == -1 ? 0 : listManager.Position; ResetHorizontalOffset(); negOffset = 0; ResetUIState(); @@ -9585,10 +9585,10 @@ private void UpdateListManager() Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: Requesting EndEdit()"); try { - if (this.listManager != null) + if (listManager != null) { EndEdit(); - this.listManager.EndCurrentEdit(); + listManager.EndCurrentEdit(); } } catch @@ -9763,7 +9763,7 @@ public override int GetChildCount() { n++; } - n += this.DataGrid.DataGridRows.Length * this.DataGrid.myGridTable.GridColumnStyles.Count; + n += DataGrid.DataGridRows.Length * DataGrid.myGridTable.GridColumnStyles.Count; return n; } @@ -9779,7 +9779,7 @@ public override AccessibleObject GetFocused() public override AccessibleObject GetSelected() { - if (this.DataGrid.DataGridRows.Length == 0 || this.DataGrid.myGridTable.GridColumnStyles.Count == 0) + if (DataGrid.DataGridRows.Length == 0 || DataGrid.myGridTable.GridColumnStyles.Count == 0) { return null; } @@ -9873,19 +9873,19 @@ public LayoutData(LayoutData src) private void GrabLayout(LayoutData src) { - this.Inside = src.Inside; - this.TopLeftHeader = src.TopLeftHeader; - this.ColumnHeaders = src.ColumnHeaders; - this.RowHeaders = src.RowHeaders; - this.Data = src.Data; - this.Caption = src.Caption; - this.ParentRows = src.ParentRows; - this.ResizeBoxRect = src.ResizeBoxRect; - this.ColumnHeadersVisible = src.ColumnHeadersVisible; - this.RowHeadersVisible = src.RowHeadersVisible; - this.CaptionVisible = src.CaptionVisible; - this.ParentRowsVisible = src.ParentRowsVisible; - this.ClientRectangle = src.ClientRectangle; + Inside = src.Inside; + TopLeftHeader = src.TopLeftHeader; + ColumnHeaders = src.ColumnHeaders; + RowHeaders = src.RowHeaders; + Data = src.Data; + Caption = src.Caption; + ParentRows = src.ParentRows; + ResizeBoxRect = src.ResizeBoxRect; + ColumnHeadersVisible = src.ColumnHeadersVisible; + RowHeadersVisible = src.RowHeadersVisible; + CaptionVisible = src.CaptionVisible; + ParentRowsVisible = src.ParentRowsVisible; + ClientRectangle = src.ClientRectangle; } public override string ToString() diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridAddNewRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridAddNewRow.cs index 5216ec49cde..de82aa60e75 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridAddNewRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridAddNewRow.cs @@ -95,11 +95,11 @@ public override int Paint(Graphics g, { Rectangle dataBounds = bounds; DataGridLineStyle gridStyle; - if (this.dgTable.IsDefault) - gridStyle = this.DataGrid.GridLineStyle; + if (dgTable.IsDefault) + gridStyle = DataGrid.GridLineStyle; else - gridStyle = this.dgTable.GridLineStyle; - int bWidth = this.DataGrid == null ? 0 : gridStyle == DataGridLineStyle.Solid ? 1 : 0; + gridStyle = dgTable.GridLineStyle; + int bWidth = DataGrid == null ? 0 : gridStyle == DataGridLineStyle.Solid ? 1 : 0; dataBounds.Height -= bWidth; int cx = base.PaintData(g, dataBounds, firstVisibleColumn, columnCount, alignToRight); @@ -114,7 +114,7 @@ protected override void PaintCellContents(Graphics g, Rectangle cellBounds, Data if (DataBound) { CurrencyManager listManager = DataGrid.ListManager; - column.Paint(g, cellBounds, listManager, this.RowNumber, alignToRight); + column.Paint(g, cellBounds, listManager, RowNumber, alignToRight); } else { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs index aa40a7de2f2..c778930af97 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs @@ -67,7 +67,7 @@ public object TrueValue { if (!trueValue.Equals(value)) { - this.trueValue = value; + trueValue = value; OnTrueValueChanged(EventArgs.Empty); Invalidate(); } @@ -95,7 +95,7 @@ public object FalseValue { if (!falseValue.Equals(value)) { - this.falseValue = value; + falseValue = value; OnFalseValueChanged(EventArgs.Empty); Invalidate(); } @@ -123,7 +123,7 @@ public object NullValue { if (!nullValue.Equals(value)) { - this.nullValue = value; + nullValue = value; OnFalseValueChanged(EventArgs.Empty); Invalidate(); } @@ -141,8 +141,8 @@ public object NullValue protected internal override void ConcedeFocus() { base.ConcedeFocus(); - this.isSelected = false; - this.isEditing = false; + isSelected = false; + isEditing = false; } private Rectangle GetCheckBoxBounds(Rectangle bounds, bool alignToRight) @@ -179,12 +179,12 @@ protected internal override object GetColumnValueAtRow(CurrencyManager lm, int r private bool IsReadOnly() { - bool ret = this.ReadOnly; - if (this.DataGridTableStyle != null) + bool ret = ReadOnly; + if (DataGridTableStyle != null) { - ret = ret || this.DataGridTableStyle.ReadOnly; - if (this.DataGridTableStyle.DataGrid != null) - ret = ret || this.DataGridTableStyle.DataGrid.ReadOnly; + ret = ret || DataGridTableStyle.ReadOnly; + if (DataGridTableStyle.DataGrid != null) + ret = ret || DataGridTableStyle.DataGrid.ReadOnly; } return ret; } @@ -287,7 +287,7 @@ protected internal override void Edit(CurrencyManager source, // move the focus away from the previous column and give it to the grid // - DataGrid grid = this.DataGridTableStyle.DataGrid; + DataGrid grid = DataGridTableStyle.DataGrid; if (!grid.Focused) grid.Focus(); @@ -340,19 +340,19 @@ internal override bool MouseDown(int rowNum, int x, int y) private void OnTrueValueChanged(EventArgs e) { - EventHandler eh = this.Events[EventTrueValue] as EventHandler; + EventHandler eh = Events[EventTrueValue] as EventHandler; if (eh != null) eh(this, e); } private void OnFalseValueChanged(EventArgs e) { - EventHandler eh = this.Events[EventFalseValue] as EventHandler; + EventHandler eh = Events[EventFalseValue] as EventHandler; if (eh != null) eh(this, e); } private void OnAllowNullChanged(EventArgs e) { - EventHandler eh = this.Events[EventAllowNull] as EventHandler; + EventHandler eh = Events[EventAllowNull] as EventHandler; if (eh != null) eh(this, e); } @@ -374,7 +374,7 @@ protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyMan /// protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, bool alignToRight) { - Paint(g, bounds, source, rowNum, this.DataGridTableStyle.BackBrush, this.DataGridTableStyle.ForeBrush, alignToRight); + Paint(g, bounds, source, rowNum, DataGridTableStyle.BackBrush, DataGridTableStyle.ForeBrush, alignToRight); } /// @@ -397,7 +397,7 @@ protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyMan Region r = g.Clip; g.ExcludeClip(box); - System.Drawing.Brush selectionBrush = this.DataGridTableStyle.IsDefault ? this.DataGridTableStyle.DataGrid.SelectionBackBrush : this.DataGridTableStyle.SelectionBackBrush; + System.Drawing.Brush selectionBrush = DataGridTableStyle.IsDefault ? DataGridTableStyle.DataGrid.SelectionBackBrush : DataGridTableStyle.SelectionBackBrush; if (isSelected && editingRow == rowNum && !IsReadOnly()) { g.FillRectangle(selectionBrush, bounds); @@ -472,7 +472,7 @@ protected internal override void EnterNullValue() { // do not throw an exception when the column is marked as readOnly or // does not allowNull - if (!this.AllowNull || IsReadOnly()) + if (!AllowNull || IsReadOnly()) return; if (currentValue != Convert.DBNull) { @@ -520,7 +520,7 @@ private void ToggleValue() isEditing = true; // tell the dataGrid that things are changing // we put Rectangle.Empty cause toggle will invalidate the row anyhow - this.DataGridTableStyle.DataGrid.ColumnStartedEditing(Rectangle.Empty); + DataGridTableStyle.DataGrid.ColumnStartedEditing(Rectangle.Empty); } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs index 537c7ca3efc..515b8b82ca3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs @@ -79,9 +79,9 @@ internal class DataGridCaption internal DataGridCaption(DataGrid dataGrid) { this.dataGrid = dataGrid; - this.downButtonVisible = dataGrid.ParentRowsVisible; + downButtonVisible = dataGrid.ParentRowsVisible; colorMap[0].OldColor = Color.White; - colorMap[0].NewColor = this.ForeColor; + colorMap[0].NewColor = ForeColor; OnGridFontChanged(); } @@ -91,7 +91,7 @@ internal void OnGridFontChanged() { try { - this.dataGridFont = new Font(dataGrid.Font, FontStyle.Bold); + dataGridFont = new Font(dataGrid.Font, FontStyle.Bold); } catch { @@ -197,7 +197,7 @@ internal Font Font // did not set the CaptionFont // if (textFont == null) - return this.dataGridFont; + return dataGridFont; else return textFont; } @@ -220,7 +220,7 @@ internal Font Font internal bool ShouldSerializeFont() { - return textFont != null && !textFont.Equals(this.dataGridFont); + return textFont != null && !textFont.Equals(dataGridFont); } internal bool ShouldSerializeBackColor() @@ -297,7 +297,7 @@ internal Color ForeColor if (value.IsEmpty) throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "Caption ForeColor")); foreBrush = new SolidBrush(value); - colorMap[0].NewColor = this.ForeColor; + colorMap[0].NewColor = ForeColor; Invalidate(); } } @@ -543,7 +543,7 @@ internal Rectangle GetDetailsButtonRect(Rectangle bounds, bool alignRight) /// internal void Paint(Graphics g, Rectangle bounds, bool alignRight) { - Size textSize = new Size((int)g.MeasureString(text, this.Font).Width + 2, this.Font.Height + 2); + Size textSize = new Size((int)g.MeasureString(text, Font).Width + 2, Font.Height + 2); downButtonRect = GetDetailsButtonRect(bounds, alignRight); int downButtonWidth = GetDetailsButtonWidth(); @@ -651,7 +651,7 @@ private void PaintText(Graphics g, Rectangle bounds, bool alignToRight) if (textBorderVisible) { - g.DrawRectangle(this.textBorderPen, textBounds.X, textBounds.Y, textBounds.Width - 1, textBounds.Height - 1); + g.DrawRectangle(textBorderPen, textBounds.X, textBounds.Y, textBounds.Width - 1, textBounds.Height - 1); textBounds.Inflate(-1, -1); } @@ -659,21 +659,21 @@ private void PaintText(Graphics g, Rectangle bounds, bool alignToRight) { Rectangle border = textBounds; border.Height = textPadding; - g.FillRectangle(this.backBrush, border); + g.FillRectangle(backBrush, border); border.Y = textBounds.Bottom - textPadding; - g.FillRectangle(this.backBrush, border); + g.FillRectangle(backBrush, border); border = new Rectangle(textBounds.X, textBounds.Y + textPadding, textPadding, textBounds.Height - 2 * textPadding); - g.FillRectangle(this.backBrush, border); + g.FillRectangle(backBrush, border); border.X = textBounds.Right - textPadding; - g.FillRectangle(this.backBrush, border); + g.FillRectangle(backBrush, border); textBounds.Inflate(-textPadding, -textPadding); } - g.FillRectangle(this.backBrush, textBounds); + g.FillRectangle(backBrush, textBounds); // Brush foreBrush = new SolidBrush(dataGrid.CaptionForeColor); StringFormat format = new StringFormat(); @@ -682,7 +682,7 @@ private void PaintText(Graphics g, Rectangle bounds, bool alignToRight) format.FormatFlags |= StringFormatFlags.DirectionRightToLeft; format.Alignment = StringAlignment.Far; } - g.DrawString(text, this.Font, foreBrush, textBounds, format); + g.DrawString(text, Font, foreBrush, textBounds, format); format.Dispose(); // foreBrush.Dispose(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs index 72c9c10d3d1..1487ec2d8d1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs @@ -34,12 +34,12 @@ public class GridColumnStylesCollection : BaseCollection, IList // int IList.Add(object value) { - return this.Add((DataGridColumnStyle)value); + return Add((DataGridColumnStyle)value); } void IList.Clear() { - this.Clear(); + Clear(); } bool IList.Contains(object value) @@ -59,12 +59,12 @@ void IList.Insert(int index, object value) void IList.Remove(object value) { - this.Remove((DataGridColumnStyle)value); + Remove((DataGridColumnStyle)value); } void IList.RemoveAt(int index) { - this.RemoveAt(index); + RemoveAt(index); } bool IList.IsFixedSize @@ -85,12 +85,12 @@ object IList.this[int index] void ICollection.CopyTo(Array array, int index) { - this.items.CopyTo(array, index); + items.CopyTo(array, index); } int ICollection.Count { - get { return this.items.Count; } + get { return items.Count; } } bool ICollection.IsSynchronized @@ -239,7 +239,7 @@ internal DataGridTableStyle DataGridTableStyle { get { - return this.owner; + return owner; } } @@ -268,7 +268,7 @@ private void ColumnStylePropDescChanged(object sender, EventArgs pcea) public virtual int Add(DataGridColumnStyle column) { - if (this.isDefault) + if (isDefault) { throw new ArgumentException(SR.DataGridDefaultColumnCollectionChanged); } @@ -281,8 +281,8 @@ public virtual int Add(DataGridColumnStyle column) // columns which are not the default should have a default // width of DataGrid.PreferredColumnWidth - if (this.DataGridTableStyle != null && column.Width == -1) - column._width = this.DataGridTableStyle.PreferredColumnWidth; + if (DataGridTableStyle != null && column.Width == -1) + column._width = DataGridTableStyle.PreferredColumnWidth; #if false column.AddOnPropertyChanged(owner.OnColumnChanged); #endif @@ -308,16 +308,16 @@ public void AddRange(DataGridColumnStyle[] columns) internal void AddDefaultColumn(DataGridColumnStyle column) { #if DEBUG - Debug.Assert(this.isDefault, "we should be calling this function only for default tables"); + Debug.Assert(isDefault, "we should be calling this function only for default tables"); Debug.Assert(column.IsDefault, "we should be a default column"); #endif // DEBUG column.SetDataGridTableInColumn(owner, true); - this.items.Add(column); + items.Add(column); } internal void ResetDefaultColumnCollection() { - Debug.Assert(this.isDefault, "we should be calling this function only for default tables"); + Debug.Assert(isDefault, "we should be calling this function only for default tables"); // unparent the edit controls for (int i = 0; i < Count; i++) { @@ -522,7 +522,7 @@ protected void OnCollectionChanged(CollectionChangeEventArgs e) /// public void Remove(DataGridColumnStyle column) { - if (this.isDefault) + if (isDefault) { throw new ArgumentException(SR.DataGridDefaultColumnCollectionChanged); } @@ -546,7 +546,7 @@ public void Remove(DataGridColumnStyle column) /// public void RemoveAt(int index) { - if (this.isDefault) + if (isDefault) { throw new ArgumentException(SR.DataGridDefaultColumnCollectionChanged); } @@ -564,7 +564,7 @@ public void RemoveAt(int index) public void ResetPropertyDescriptors() { - for (int i = 0; i < this.Count; i++) + for (int i = 0; i < Count; i++) { this[i].PropertyDescriptor = null; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRows.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRows.cs index b83b01a9319..06c9207a5b4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRows.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRows.cs @@ -75,7 +75,7 @@ internal class DataGridParentRows internal DataGridParentRows(DataGrid dataGrid) { - this.colorMap[0].OldColor = Color.Black; + colorMap[0].OldColor = Color.Black; this.dataGrid = dataGrid; // UpdateGridLinePen(); } @@ -390,7 +390,7 @@ internal void OnLayout() if (parentsCount > rowHeights.Count) { Debug.Assert(parentsCount == rowHeights.Count + 1 || rowHeights.Count == 0, "see comment above for more info"); - int rowHeightsCount = this.rowHeights.Count; + int rowHeightsCount = rowHeights.Count; for (int i = rowHeightsCount; i < parentsCount; i++) { DataGridState dgs = (DataGridState)parents[i]; @@ -853,7 +853,7 @@ private void PaintBitmap(Graphics g, Bitmap b, Rectangle bounds) // now draw the bitmap ImageAttributes attr = new ImageAttributes(); - this.colorMap[0].NewColor = this.ForeColor; + colorMap[0].NewColor = ForeColor; attr.SetRemapTable(colorMap, ColorAdjustType.Bitmap); g.DrawImage(b, bmpRect, 0, 0, bmpRect.Width, bmpRect.Height, GraphicsUnit.Pixel, attr); attr.Dispose(); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRelationshipRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRelationshipRow.cs index 7a0cb8844fa..62b6247b90d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRelationshipRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRelationshipRow.cs @@ -64,7 +64,7 @@ internal protected override int MinimumRowHeight(GridColumnStylesCollection cols } */ - return base.MinimumRowHeight(cols) + (this.expanded ? GetRelationshipRect().Height : 0); + return base.MinimumRowHeight(cols) + (expanded ? GetRelationshipRect().Height : 0); } internal protected override int MinimumRowHeight(DataGridTableStyle dgTable) @@ -76,7 +76,7 @@ internal protected override int MinimumRowHeight(DataGridTableStyle dgTable) } */ - return base.MinimumRowHeight(dgTable) + (this.expanded ? GetRelationshipRect().Height : 0); + return base.MinimumRowHeight(dgTable) + (expanded ? GetRelationshipRect().Height : 0); } // =------------------------------------------------------------------ @@ -140,7 +140,7 @@ private int FocusedRelation { get { - return this.dgTable.FocusedRelation; + return dgTable.FocusedRelation; } set { @@ -154,7 +154,7 @@ private int FocusedRelation private void Collapse() { - Debug.Assert(this.dgTable.DataGrid.AllowNavigation, "how can the user collapse the relations if the grid does not allow navigation?"); + Debug.Assert(dgTable.DataGrid.AllowNavigation, "how can the user collapse the relations if the grid does not allow navigation?"); if (expanded) { expanded = false; @@ -172,11 +172,11 @@ protected override AccessibleObject CreateAccessibleObject() private void Expand() { - Debug.Assert(this.dgTable.DataGrid.AllowNavigation, "how can the user expand the relations if the grid does not allow navigation?"); + Debug.Assert(dgTable.DataGrid.AllowNavigation, "how can the user expand the relations if the grid does not allow navigation?"); if (expanded == false && DataGrid != null - && this.dgTable != null - && this.dgTable.RelationsList.Count > 0) + && dgTable != null + && dgTable.RelationsList.Count > 0) { expanded = true; FocusedRelation = -1; @@ -242,9 +242,9 @@ public override Rectangle GetNonScrollableArea() private Rectangle GetRelationshipRect() { - Debug.Assert(this.expanded, "we should need this rectangle only when the row is expanded"); - Rectangle ret = this.dgTable.RelationshipRect; - ret.Y = base.Height - this.dgTable.BorderWidth; + Debug.Assert(expanded, "we should need this rectangle only when the row is expanded"); + Rectangle ret = dgTable.RelationshipRect; + ret.Y = base.Height - dgTable.BorderWidth; return ret; } @@ -285,10 +285,10 @@ private Rectangle GetRelationshipRect() { private Rectangle GetRelationshipRectWithMirroring() { Rectangle relRect = GetRelationshipRect(); - bool rowHeadersVisible = this.dgTable.IsDefault ? this.DataGrid.RowHeadersVisible : this.dgTable.RowHeadersVisible; + bool rowHeadersVisible = dgTable.IsDefault ? DataGrid.RowHeadersVisible : dgTable.RowHeadersVisible; if (rowHeadersVisible) { - int rowHeaderWidth = this.dgTable.IsDefault ? this.DataGrid.RowHeaderWidth : this.dgTable.RowHeaderWidth; + int rowHeaderWidth = dgTable.IsDefault ? DataGrid.RowHeaderWidth : dgTable.RowHeaderWidth; relRect.X += DataGrid.GetRowHeaderRect().X + rowHeaderWidth; } relRect.X = MirrorRelationshipRectangle(relRect, DataGrid.GetRowHeaderRect(), DataGrid.RightToLeft == RightToLeft.Yes); @@ -305,7 +305,7 @@ private bool PointOverPlusMinusGlyph(int x, int y, Rectangle rowHeaders, bool al if (dgTable == null || dgTable.DataGrid == null || !dgTable.DataGrid.AllowNavigation) return false; Rectangle insideRowHeaders = rowHeaders; - if (!this.DataGrid.FlatMode) + if (!DataGrid.FlatMode) { insideRowHeaders.Inflate(-1, -1); } @@ -319,12 +319,12 @@ private bool PointOverPlusMinusGlyph(int x, int y, Rectangle rowHeaders, bool al public override bool OnMouseDown(int x, int y, Rectangle rowHeaders, bool alignToRight) { - bool rowHeadersVisible = this.dgTable.IsDefault ? this.DataGrid.RowHeadersVisible : this.dgTable.RowHeadersVisible; + bool rowHeadersVisible = dgTable.IsDefault ? DataGrid.RowHeadersVisible : dgTable.RowHeadersVisible; if (rowHeadersVisible) { if (PointOverPlusMinusGlyph(x, y, rowHeaders, alignToRight)) { - if (this.dgTable.RelationsList.Count == 0) + if (dgTable.RelationsList.Count == 0) { return false; } @@ -354,7 +354,7 @@ public override bool OnMouseDown(int x, int y, Rectangle rowHeaders, bool alignT { // first, reset the FocusedRelation FocusedRelation = -1; - DataGrid.NavigateTo(((string)this.dgTable.RelationsList[r]), this, true); + DataGrid.NavigateTo(((string)dgTable.RelationsList[r]), this, true); } // DataGrid.OnLinkClick(EventArgs.Empty); return true; @@ -372,11 +372,11 @@ public override bool OnMouseMove(int x, int y, Rectangle rowHeaders, bool alignT if (relRect.Contains(x, y)) { - this.DataGrid.Cursor = Cursors.Hand; + DataGrid.Cursor = Cursors.Hand; return true; } - this.DataGrid.Cursor = Cursors.Default; + DataGrid.Cursor = Cursors.Default; return base.OnMouseMove(x, y, rowHeaders, alignToRight); } @@ -388,7 +388,7 @@ public override void OnMouseLeft(Rectangle rowHeaders, bool alignToRight) return; Rectangle relRect = GetRelationshipRect(); - relRect.X += rowHeaders.X + this.dgTable.RowHeaderWidth; + relRect.X += rowHeaders.X + dgTable.RowHeaderWidth; relRect.X = MirrorRelationshipRectangle(relRect, rowHeaders, alignToRight); if (FocusedRelation != -1) @@ -444,7 +444,7 @@ public override bool OnKeyPress(Keys keyData) { // somebody set the relation number up already // navigate to the relation - DataGrid.NavigateTo(((string)this.dgTable.RelationsList[FocusedRelation]), this, true); + DataGrid.NavigateTo(((string)dgTable.RelationsList[FocusedRelation]), this, true); // now reset the FocusedRelation FocusedRelation = -1; @@ -472,7 +472,7 @@ internal override void LoseChildFocus(Rectangle rowHeaders, bool alignToRight) FocusedRelation = -1; Rectangle relRect = GetRelationshipRect(); - relRect.X += rowHeaders.X + this.dgTable.RowHeaderWidth; + relRect.X += rowHeaders.X + dgTable.RowHeaderWidth; relRect.X = MirrorRelationshipRectangle(relRect, rowHeaders, alignToRight); InvalidateRowRect(relRect); } @@ -494,7 +494,7 @@ internal override bool ProcessTabKey(Keys keyData, Rectangle rowHeaders, bool al // if there are no relationships, this row can't do anything with the // key - if (this.dgTable.RelationsList.Count == 0 || dgTable.DataGrid == null || !dgTable.DataGrid.AllowNavigation) + if (dgTable.RelationsList.Count == 0 || dgTable.DataGrid == null || !dgTable.DataGrid.AllowNavigation) return false; // expand the relationship box @@ -516,21 +516,21 @@ internal override bool ProcessTabKey(Keys keyData, Rectangle rowHeaders, bool al // we need to invalidate the relationshipRectangle, and cause the linkFont to move // to the next relation Rectangle relRect = GetRelationshipRect(); - relRect.X += rowHeaders.X + this.dgTable.RowHeaderWidth; + relRect.X += rowHeaders.X + dgTable.RowHeaderWidth; relRect.X = MirrorRelationshipRectangle(relRect, rowHeaders, alignToRight); InvalidateRowRect(relRect); if (FocusedRelation == -1) // is the first time that the user focuses on this // set of relationships - FocusedRelation = this.dgTable.RelationsList.Count - 1; + FocusedRelation = dgTable.RelationsList.Count - 1; else FocusedRelation--; return true; } else { - if (FocusedRelation == this.dgTable.RelationsList.Count - 1) + if (FocusedRelation == dgTable.RelationsList.Count - 1) { // if the user hits TAB and the focus was on the last relationship then // reset FocusedRelation and let the dataGrid use the key @@ -543,7 +543,7 @@ internal override bool ProcessTabKey(Keys keyData, Rectangle rowHeaders, bool al // we need to invalidate the relationshipRectangle, and cause the linkFont to move // to the next relation Rectangle relRect = GetRelationshipRect(); - relRect.X += rowHeaders.X + this.dgTable.RowHeaderWidth; + relRect.X += rowHeaders.X + dgTable.RowHeaderWidth; relRect.X = MirrorRelationshipRectangle(relRect, rowHeaders, alignToRight); InvalidateRowRect(relRect); @@ -569,7 +569,7 @@ public override int Paint(Graphics g, { if (CompModSwitches.DGRelationShpRowPaint.TraceVerbose) Debug.WriteLine("Painting row " + RowNumber.ToString(CultureInfo.InvariantCulture) + " with bounds " + bounds.ToString()); - int bWidth = this.dgTable.BorderWidth; + int bWidth = dgTable.BorderWidth; // paint the data cells Rectangle dataBounds = bounds; @@ -581,7 +581,7 @@ public override int Paint(Graphics g, if (bWidth > 0) PaintBottomBorder(g, dataBounds, dataWidth, bWidth, alignToRight); - if (expanded && this.dgTable.RelationsList.Count > 0) + if (expanded && dgTable.RelationsList.Count > 0) { // paint the relationships Rectangle relationBounds = new Rectangle(trueRowBounds.X, @@ -607,7 +607,7 @@ protected override void PaintCellContents(Graphics g, Rectangle cellBounds, Data // string errString = string.Empty; Rectangle bounds = cellBounds; - object errInfo = DataGrid.ListManager[this.number]; + object errInfo = DataGrid.ListManager[number]; if (errInfo is IDataErrorInfo) errString = ((IDataErrorInfo)errInfo)[column.PropertyDescriptor.Name]; @@ -627,13 +627,13 @@ protected override void PaintCellContents(Graphics g, Rectangle cellBounds, Data DataGrid.ToolTipProvider.AddToolTip(errString, (IntPtr)(DataGrid.ToolTipId++), errRect); } - column.Paint(g, bounds, listManager, this.RowNumber, backBr, foreBrush, alignToRight); + column.Paint(g, bounds, listManager, RowNumber, backBr, foreBrush, alignToRight); } public override void PaintHeader(Graphics g, Rectangle bounds, bool alignToRight, bool isDirty) { - DataGrid grid = this.DataGrid; + DataGrid grid = DataGrid; Rectangle insideBounds = bounds; @@ -643,10 +643,10 @@ public override void PaintHeader(Graphics g, Rectangle bounds, bool alignToRight insideBounds.Inflate(-1, -1); } - if (this.dgTable.IsDefault) - PaintHeaderInside(g, insideBounds, this.DataGrid.HeaderBackBrush, alignToRight, isDirty); + if (dgTable.IsDefault) + PaintHeaderInside(g, insideBounds, DataGrid.HeaderBackBrush, alignToRight, isDirty); else - PaintHeaderInside(g, insideBounds, this.dgTable.HeaderBackBrush, alignToRight, isDirty); + PaintHeaderInside(g, insideBounds, dgTable.HeaderBackBrush, alignToRight, isDirty); } public void PaintHeaderInside(Graphics g, Rectangle bounds, Brush backBr, bool alignToRight, bool isDirty) @@ -712,7 +712,7 @@ private void PaintRelations(Graphics g, Rectangle bounds, Rectangle trueRowBound // Paint the relations' text g.SetClip(bounds); - relRect.Height -= this.dgTable.BorderWidth; // use bWidth not 1 + relRect.Height -= dgTable.BorderWidth; // use bWidth not 1 g.DrawRectangle(SystemPens.ControlText, relRect.X, relRect.Y, relRect.Width - 1, relRect.Height - 1); relRect.Inflate(-1, -1); @@ -729,10 +729,10 @@ private void PaintRelations(Graphics g, Rectangle bounds, Rectangle trueRowBound if (paintedWidth < bounds.Width) { int bWidth; - if (this.dgTable.IsDefault) - bWidth = this.DataGrid.GridLineWidth; + if (dgTable.IsDefault) + bWidth = DataGrid.GridLineWidth; else - bWidth = this.dgTable.GridLineWidth; + bWidth = dgTable.GridLineWidth; g.FillRectangle(DataGrid.BackgroundBrush, alignToRight ? bounds.X : bounds.X + paintedWidth, bounds.Y, @@ -745,10 +745,10 @@ private void PaintRelations(Graphics g, Rectangle bounds, Rectangle trueRowBound Brush br; // if the user changed the gridLineColor on the dataGrid // from the defaultValue, then use that value; - if (this.dgTable.IsDefault) - br = this.DataGrid.GridLineBrush; + if (dgTable.IsDefault) + br = DataGrid.GridLineBrush; else - br = this.dgTable.GridLineBrush; + br = dgTable.GridLineBrush; g.FillRectangle(br, alignToRight ? bounds.Right - bWidth - paintedWidth : bounds.X + paintedWidth - bWidth, bounds.Y, @@ -763,21 +763,21 @@ private int PaintRelationText(Graphics g, Rectangle bounds, bool alignToRight) { g.FillRectangle(GetBackBrush(), bounds.X, bounds.Y, bounds.Width, System.Windows.Forms.DataGridTableStyle.relationshipSpacing); - int relationshipHeight = this.dgTable.RelationshipHeight; + int relationshipHeight = dgTable.RelationshipHeight; Rectangle textBounds = new Rectangle(bounds.X, bounds.Y + System.Windows.Forms.DataGridTableStyle.relationshipSpacing, bounds.Width, relationshipHeight); int cy = System.Windows.Forms.DataGridTableStyle.relationshipSpacing; - for (int r = 0; r < this.dgTable.RelationsList.Count; ++r) + for (int r = 0; r < dgTable.RelationsList.Count; ++r) { if (cy > bounds.Height) break; - Brush textBrush = this.dgTable.IsDefault ? this.DataGrid.LinkBrush : this.dgTable.LinkBrush; + Brush textBrush = dgTable.IsDefault ? DataGrid.LinkBrush : dgTable.LinkBrush; - Font textFont = this.DataGrid.Font; - textBrush = this.dgTable.IsDefault ? this.DataGrid.LinkBrush : this.dgTable.LinkBrush; - textFont = this.DataGrid.LinkFont; + Font textFont = DataGrid.Font; + textBrush = dgTable.IsDefault ? DataGrid.LinkBrush : dgTable.LinkBrush; + textFont = DataGrid.LinkFont; g.FillRectangle(GetBackBrush(), textBounds); @@ -787,11 +787,11 @@ private int PaintRelationText(Graphics g, Rectangle bounds, bool alignToRight) format.FormatFlags |= StringFormatFlags.DirectionRightToLeft; format.Alignment = StringAlignment.Far; } - g.DrawString(((string)this.dgTable.RelationsList[r]), textFont, textBrush, textBounds, + g.DrawString(((string)dgTable.RelationsList[r]), textFont, textBrush, textBounds, format); - if (r == FocusedRelation && this.number == this.DataGrid.CurrentCell.RowNumber) + if (r == FocusedRelation && number == DataGrid.CurrentCell.RowNumber) { - textBounds.Width = this.dgTable.FocusedTextWidth; + textBounds.Width = dgTable.FocusedTextWidth; ControlPaint.DrawFocusRectangle(g, textBounds, ((SolidBrush)textBrush).Color, ((SolidBrush)GetBackBrush()).Color); textBounds.Width = bounds.Width; } @@ -818,7 +818,7 @@ private void PaintPlusMinusGlyph(Graphics g, Rectangle bounds, Brush backBr, boo if (CompModSwitches.DGRelationShpRowPaint.TraceVerbose) Debug.WriteLine("Painting PlusMinusGlyph with outline -> " + outline.ToString()); // draw the +/- box - Pen drawPen = this.dgTable.IsDefault ? this.DataGrid.HeaderForePen : this.dgTable.HeaderForePen; + Pen drawPen = dgTable.IsDefault ? DataGrid.HeaderForePen : dgTable.HeaderForePen; g.DrawRectangle(drawPen, outline.X, outline.Y, outline.Width - 1, outline.Height - 1); int indent = 2; @@ -850,9 +850,9 @@ private void PaintPlusMinusGlyph(Graphics g, Rectangle bounds, Brush backBr, boo private int RelationFromY(int y) { int relation = -1; - int relationshipHeight = this.dgTable.RelationshipHeight; + int relationshipHeight = dgTable.RelationshipHeight; Rectangle relRect = GetRelationshipRect(); - int cy = base.Height - this.dgTable.BorderWidth + System.Windows.Forms.DataGridTableStyle.relationshipSpacing; + int cy = base.Height - dgTable.BorderWidth + System.Windows.Forms.DataGridTableStyle.relationshipSpacing; while (cy < relRect.Bottom) { if (cy > y) @@ -860,7 +860,7 @@ private int RelationFromY(int y) cy += relationshipHeight; relation++; } - if (relation >= this.dgTable.RelationsList.Count) + if (relation >= dgTable.RelationsList.Count) return -1; return relation; } @@ -1053,8 +1053,8 @@ public override AccessibleStates State get { - DataGridRow[] dgRows = this.DataGrid.DataGridRows; - if (Array.IndexOf(dgRows, this.owner) == -1) + DataGridRow[] dgRows = DataGrid.DataGridRows; + if (Array.IndexOf(dgRows, owner) == -1) { return AccessibleStates.Unavailable; } @@ -1081,8 +1081,8 @@ public override string Value { get { - DataGridRow[] dgRows = this.DataGrid.DataGridRows; - if (Array.IndexOf(dgRows, this.owner) == -1) + DataGridRow[] dgRows = DataGrid.DataGridRows; + if (Array.IndexOf(dgRows, owner) == -1) { return null; } @@ -1110,7 +1110,7 @@ public override void DoDefaultAction() ((DataGridRelationshipRow)Owner).Expanded = true; owner.FocusedRelation = -1; DataGrid.NavigateTo((string)owner.dgTable.RelationsList[relationship], owner, true); - DataGrid.BeginInvoke(new MethodInvoker(this.ResetAccessibilityLayer)); + DataGrid.BeginInvoke(new MethodInvoker(ResetAccessibilityLayer)); } private void ResetAccessibilityLayer() diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRow.cs index 0426747c665..5bd60a08cd8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRow.cs @@ -68,7 +68,7 @@ public DataGridRow(DataGrid dataGrid, DataGridTableStyle dgTable, int rowNumber) if (rowNumber < 0) throw new ArgumentException(SR.DataGridRowRowNumber, "rowNumber"); // this.dataGrid = dataGrid; - this.number = rowNumber; + number = rowNumber; // map the black color in the pictures to the DataGrid's HeaderForeColor // @@ -103,11 +103,11 @@ internal protected virtual int MinimumRowHeight(DataGridTableStyle dgTable) internal protected virtual int MinimumRowHeight(GridColumnStylesCollection columns) { - int h = dgTable.IsDefault ? this.DataGrid.PreferredRowHeight : dgTable.PreferredRowHeight; + int h = dgTable.IsDefault ? DataGrid.PreferredRowHeight : dgTable.PreferredRowHeight; try { - if (this.dgTable.DataGrid.DataSource != null) + if (dgTable.DataGrid.DataSource != null) { int nCols = columns.Count; for (int i = 0; i < nCols; ++i) @@ -135,7 +135,7 @@ public DataGrid DataGrid { get { - return this.dgTable.DataGrid; + return dgTable.DataGrid; } } @@ -143,7 +143,7 @@ internal DataGridTableStyle DataGridTableStyle { get { - return this.dgTable; + return dgTable; } set { @@ -186,7 +186,7 @@ public virtual int Height // when we resize the row, or when we set the PreferredRowHeigth on the // DataGridTableStyle, we change the height of the Row, which will cause to invalidate, // then the grid itself will do another invalidate call. - this.dgTable.DataGrid.OnRowHeightChanged(this); + dgTable.DataGrid.OnRowHeightChanged(this); } } @@ -197,7 +197,7 @@ public int RowNumber { get { - return this.number; + return number; } } @@ -243,17 +243,17 @@ protected Bitmap GetBitmap(string bitmapName) /// public virtual Rectangle GetCellBounds(int col) { - int firstVisibleCol = this.dgTable.DataGrid.FirstVisibleColumn; + int firstVisibleCol = dgTable.DataGrid.FirstVisibleColumn; int cx = 0; Rectangle cellBounds = new Rectangle(); - GridColumnStylesCollection columns = this.dgTable.GridColumnStyles; + GridColumnStylesCollection columns = dgTable.GridColumnStyles; if (columns != null) { for (int i = firstVisibleCol; i < col; i++) if (columns[i].PropertyDescriptor != null) cx += columns[i].Width; - int borderWidth = this.dgTable.GridLineWidth; + int borderWidth = dgTable.GridLineWidth; cellBounds = new Rectangle(cx, 0, columns[col].Width - borderWidth, @@ -318,12 +318,12 @@ protected Bitmap GetRightArrowBitmap() public virtual void InvalidateRow() { - this.dgTable.DataGrid.InvalidateRow(number); + dgTable.DataGrid.InvalidateRow(number); } public virtual void InvalidateRowRect(Rectangle r) { - this.dgTable.DataGrid.InvalidateRowRect(number, r); + dgTable.DataGrid.InvalidateRowRect(number, r); } /// @@ -339,12 +339,12 @@ public virtual void OnEdit() /// public virtual bool OnKeyPress(Keys keyData) { - int currentColIndex = this.dgTable.DataGrid.CurrentCell.ColumnNumber; - GridColumnStylesCollection columns = this.dgTable.GridColumnStyles; + int currentColIndex = dgTable.DataGrid.CurrentCell.ColumnNumber; + GridColumnStylesCollection columns = dgTable.GridColumnStyles; if (columns != null && currentColIndex >= 0 && currentColIndex < columns.Count) { DataGridColumnStyle currentColumn = columns[currentColIndex]; - if (currentColumn.KeyPress(this.RowNumber, keyData)) + if (currentColumn.KeyPress(RowNumber, keyData)) { return true; } @@ -439,7 +439,7 @@ public abstract int Paint(Graphics g, /// protected virtual void PaintBottomBorder(Graphics g, Rectangle bounds, int dataWidth) { - PaintBottomBorder(g, bounds, dataWidth, this.dgTable.GridLineWidth, false); + PaintBottomBorder(g, bounds, dataWidth, dgTable.GridLineWidth, false); } protected virtual void PaintBottomBorder(Graphics g, Rectangle bounds, int dataWidth, int borderWidth, bool alignToRight) @@ -450,12 +450,12 @@ protected virtual void PaintBottomBorder(Graphics g, Rectangle bounds, int dataW dataWidth, borderWidth); - g.FillRectangle(this.dgTable.IsDefault ? this.DataGrid.GridLineBrush : this.dgTable.GridLineBrush, bottomBorder); + g.FillRectangle(dgTable.IsDefault ? DataGrid.GridLineBrush : dgTable.GridLineBrush, bottomBorder); // paint any exposed region to the right if (dataWidth < bounds.Width) { - g.FillRectangle(this.dgTable.DataGrid.BackgroundBrush, + g.FillRectangle(dgTable.DataGrid.BackgroundBrush, alignToRight ? bounds.X : bottomBorder.Right, bottomBorder.Y, bounds.Width - bottomBorder.Width, @@ -483,10 +483,10 @@ public virtual int PaintData(Graphics g, Debug.WriteLineIf(CompModSwitches.DGRowPaint.TraceVerbose, "Painting DataGridAddNewRow: bounds = " + bounds.ToString()); Rectangle cellBounds = bounds; - int bWidth = this.dgTable.IsDefault ? this.DataGrid.GridLineWidth : this.dgTable.GridLineWidth; + int bWidth = dgTable.IsDefault ? DataGrid.GridLineWidth : dgTable.GridLineWidth; int cx = 0; - DataGridCell current = this.dgTable.DataGrid.CurrentCell; + DataGridCell current = dgTable.DataGrid.CurrentCell; GridColumnStylesCollection columns = dgTable.GridColumnStyles; int nCols = columns.Count; @@ -520,7 +520,7 @@ public virtual int PaintData(Graphics g, // Paint the border to the right of each cell if (bWidth > 0) { - g.FillRectangle(this.dgTable.IsDefault ? this.DataGrid.GridLineBrush : this.dgTable.GridLineBrush, + g.FillRectangle(dgTable.IsDefault ? DataGrid.GridLineBrush : dgTable.GridLineBrush, alignToRight ? cellBounds.X - bWidth : cellBounds.Right, cellBounds.Y, bWidth, @@ -532,7 +532,7 @@ public virtual int PaintData(Graphics g, // Paint any exposed area to the right ( or left ) of the data cell area if (cx < bounds.Width) { - g.FillRectangle(this.dgTable.DataGrid.BackgroundBrush, + g.FillRectangle(dgTable.DataGrid.BackgroundBrush, alignToRight ? bounds.X : bounds.X + cx, bounds.Y, bounds.Width - cx, @@ -564,7 +564,7 @@ protected virtual void PaintCellContents(Graphics g, Rectangle cellBounds, DataG protected Rectangle PaintIcon(Graphics g, Rectangle visualBounds, bool paintIcon, bool alignToRight, Bitmap bmp) { return PaintIcon(g, visualBounds, paintIcon, alignToRight, bmp, - this.dgTable.IsDefault ? this.DataGrid.HeaderBackBrush : this.dgTable.HeaderBackBrush); + dgTable.IsDefault ? DataGrid.HeaderBackBrush : dgTable.HeaderBackBrush); } protected Rectangle PaintIcon(Graphics g, Rectangle visualBounds, bool paintIcon, bool alignToRight, Bitmap bmp, Brush backBrush) { @@ -576,7 +576,7 @@ protected Rectangle PaintIcon(Graphics g, Rectangle visualBounds, bool paintIcon g.FillRectangle(backBrush, visualBounds); if (paintIcon) { - colorMap[0].NewColor = this.dgTable.IsDefault ? this.DataGrid.HeaderForeColor : this.dgTable.HeaderForeColor; + colorMap[0].NewColor = dgTable.IsDefault ? DataGrid.HeaderForeColor : dgTable.HeaderForeColor; colorMap[0].OldColor = Color.Black; ImageAttributes attr = new ImageAttributes(); attr.SetRemapTable(colorMap, ColorAdjustType.Bitmap); @@ -620,7 +620,7 @@ public virtual void PaintHeader(Graphics g, Rectangle visualBounds, bool alignTo bmp = GetPencilBitmap(); lock (bmp) { - bounds.X += PaintIcon(g, bounds, RowNumber == this.DataGrid.CurrentCell.RowNumber, alignToRight, bmp).Width + xOffset; + bounds.X += PaintIcon(g, bounds, RowNumber == DataGrid.CurrentCell.RowNumber, alignToRight, bmp).Width + xOffset; } } else @@ -628,13 +628,13 @@ public virtual void PaintHeader(Graphics g, Rectangle visualBounds, bool alignTo bmp = alignToRight ? GetLeftArrowBitmap() : GetRightArrowBitmap(); lock (bmp) { - bounds.X += PaintIcon(g, bounds, RowNumber == this.DataGrid.CurrentCell.RowNumber, alignToRight, bmp).Width + xOffset; + bounds.X += PaintIcon(g, bounds, RowNumber == DataGrid.CurrentCell.RowNumber, alignToRight, bmp).Width + xOffset; } } // Paint the error icon // - object errorInfo = DataGrid.ListManager[this.number]; + object errorInfo = DataGrid.ListManager[number]; if (!(errorInfo is IDataErrorInfo)) return; @@ -671,10 +671,10 @@ public virtual void PaintHeader(Graphics g, Rectangle visualBounds, bool alignTo protected Brush GetBackBrush() { - Brush br = this.dgTable.IsDefault ? DataGrid.BackBrush : this.dgTable.BackBrush; + Brush br = dgTable.IsDefault ? DataGrid.BackBrush : dgTable.BackBrush; if (DataGrid.LedgerStyle && (RowNumber % 2 == 1)) { - br = this.dgTable.IsDefault ? this.DataGrid.AlternatingBackBrush : this.dgTable.AlternatingBackBrush; + br = dgTable.IsDefault ? DataGrid.AlternatingBackBrush : dgTable.AlternatingBackBrush; } return br; } @@ -686,11 +686,11 @@ protected Brush GetBackBrush() /// protected Brush BackBrushForDataPaint(ref DataGridCell current, DataGridColumnStyle gridColumn, int column) { - Brush backBr = this.GetBackBrush(); + Brush backBr = GetBackBrush(); if (Selected) { - backBr = this.dgTable.IsDefault ? this.DataGrid.SelectionBackBrush : this.dgTable.SelectionBackBrush; + backBr = dgTable.IsDefault ? DataGrid.SelectionBackBrush : dgTable.SelectionBackBrush; } /* if (RowNumber == current.RowNumber && column == current.ColumnNumber) { @@ -703,11 +703,11 @@ protected Brush BackBrushForDataPaint(ref DataGridCell current, DataGridColumnSt protected Brush ForeBrushForDataPaint(ref DataGridCell current, DataGridColumnStyle gridColumn, int column) { // Brush foreBrush = gridColumn.ForeBrush; - Brush foreBrush = this.dgTable.IsDefault ? this.DataGrid.ForeBrush : this.dgTable.ForeBrush; + Brush foreBrush = dgTable.IsDefault ? DataGrid.ForeBrush : dgTable.ForeBrush; if (Selected) { - foreBrush = this.dgTable.IsDefault ? this.DataGrid.SelectionForeBrush : this.dgTable.SelectionForeBrush; + foreBrush = dgTable.IsDefault ? DataGrid.SelectionForeBrush : dgTable.SelectionForeBrush; } /* if (RowNumber == current.RowNumber && column == current.ColumnNumber) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs index 46a3b86f770..13647836c2d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs @@ -86,34 +86,34 @@ public object Clone() /// public void PushState(DataGrid dataGrid) { - this.DataSource = dataGrid.DataSource; - this.DataMember = dataGrid.DataMember; - this.DataGrid = dataGrid; - this.DataGridRows = dataGrid.DataGridRows; - this.DataGridRowsLength = dataGrid.DataGridRowsLength; - this.FirstVisibleRow = dataGrid.firstVisibleRow; - this.FirstVisibleCol = dataGrid.firstVisibleCol; - this.CurrentRow = dataGrid.currentRow; - this.GridColumnStyles = new GridColumnStylesCollection(dataGrid.myGridTable); - - this.GridColumnStyles.Clear(); + DataSource = dataGrid.DataSource; + DataMember = dataGrid.DataMember; + DataGrid = dataGrid; + DataGridRows = dataGrid.DataGridRows; + DataGridRowsLength = dataGrid.DataGridRowsLength; + FirstVisibleRow = dataGrid.firstVisibleRow; + FirstVisibleCol = dataGrid.firstVisibleCol; + CurrentRow = dataGrid.currentRow; + GridColumnStyles = new GridColumnStylesCollection(dataGrid.myGridTable); + + GridColumnStyles.Clear(); foreach (DataGridColumnStyle style in dataGrid.myGridTable.GridColumnStyles) { - this.GridColumnStyles.Add(style); + GridColumnStyles.Add(style); } - this.ListManager = dataGrid.ListManager; - this.ListManager.ItemChanged += new ItemChangedEventHandler(DataSource_Changed); - this.ListManager.MetaDataChanged += new EventHandler(DataSource_MetaDataChanged); - this.CurrentCol = dataGrid.currentCol; + ListManager = dataGrid.ListManager; + ListManager.ItemChanged += new ItemChangedEventHandler(DataSource_Changed); + ListManager.MetaDataChanged += new EventHandler(DataSource_MetaDataChanged); + CurrentCol = dataGrid.currentCol; } // this is needed so that the parent rows will remove notification from the list // when the datagridstate is no longer needed; public void RemoveChangeNotification() { - this.ListManager.ItemChanged -= new ItemChangedEventHandler(DataSource_Changed); - this.ListManager.MetaDataChanged -= new EventHandler(DataSource_MetaDataChanged); + ListManager.ItemChanged -= new ItemChangedEventHandler(DataSource_Changed); + ListManager.MetaDataChanged -= new EventHandler(DataSource_MetaDataChanged); } /// @@ -140,19 +140,19 @@ public void PullState(DataGrid dataGrid, bool createColumn) private void DataSource_Changed(object sender, ItemChangedEventArgs e) { - if (this.DataGrid != null && this.ListManager.Position == e.Index) + if (DataGrid != null && ListManager.Position == e.Index) { DataGrid.InvalidateParentRows(); return; } - if (this.DataGrid != null) + if (DataGrid != null) DataGrid.ParentRowsDataChanged(); } private void DataSource_MetaDataChanged(object sender, EventArgs e) { - if (this.DataGrid != null) + if (DataGrid != null) DataGrid.ParentRowsDataChanged(); } @@ -172,7 +172,7 @@ public override Rectangle Bounds { get { - DataGridParentRows dataGridParentRows = ((DataGridParentRows.DataGridParentRowsAccessibleObject)this.Parent).Owner; + DataGridParentRows dataGridParentRows = ((DataGridParentRows.DataGridParentRowsAccessibleObject)Parent).Owner; DataGrid g = owner.LinkingRow.DataGrid; Rectangle r = dataGridParentRows.GetBoundsForDataGridStateAccesibility(owner); r.Y += g.ParentRowsBounds.Y; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs index c4a96d9c285..c290be5a10c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs @@ -123,7 +123,7 @@ public bool AllowSorting } set { - if (this.isDefaultTableStyle) + if (isDefaultTableStyle) { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "AllowSorting")); } @@ -157,7 +157,7 @@ public Color AlternatingBackColor } set { - if (this.isDefaultTableStyle) + if (isDefaultTableStyle) { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "AlternatingBackColor")); } @@ -207,19 +207,19 @@ internal SolidBrush AlternatingBackBrush protected bool ShouldSerializeBackColor() { - return !System.Windows.Forms.DataGridTableStyle.DefaultBackBrush.Equals(this.backBrush); + return !System.Windows.Forms.DataGridTableStyle.DefaultBackBrush.Equals(backBrush); } protected bool ShouldSerializeForeColor() { - return !System.Windows.Forms.DataGridTableStyle.DefaultForeBrush.Equals(this.foreBrush); + return !System.Windows.Forms.DataGridTableStyle.DefaultForeBrush.Equals(foreBrush); } internal SolidBrush BackBrush { get { - return this.backBrush; + return backBrush; } } @@ -231,11 +231,11 @@ public Color BackColor { get { - return this.backBrush.Color; + return backBrush.Color; } set { - if (this.isDefaultTableStyle) + if (isDefaultTableStyle) { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "BackColor")); } @@ -249,7 +249,7 @@ public Color BackColor } if (!backBrush.Color.Equals(value)) { - this.backBrush = new SolidBrush(value); + backBrush = new SolidBrush(value); InvalidateInside(); OnBackColorChanged(EventArgs.Empty); } @@ -264,9 +264,9 @@ public event EventHandler BackColorChanged public void ResetBackColor() { - if (!this.backBrush.Equals(DefaultBackBrush)) + if (!backBrush.Equals(DefaultBackBrush)) { - this.BackColor = DefaultBackBrush.Color; + BackColor = DefaultBackBrush.Color; } } @@ -274,22 +274,22 @@ internal int BorderWidth { get { - DataGrid dataGrid = this.DataGrid; + DataGrid dataGrid = DataGrid; if (dataGrid == null) return 0; // if the user set the GridLineStyle property on the dataGrid. // then use the value of that property DataGridLineStyle gridStyle; int gridLineWidth; - if (this.IsDefault) + if (IsDefault) { - gridStyle = this.DataGrid.GridLineStyle; - gridLineWidth = this.DataGrid.GridLineWidth; + gridStyle = DataGrid.GridLineStyle; + gridLineWidth = DataGrid.GridLineWidth; } else { - gridStyle = this.GridLineStyle; - gridLineWidth = this.GridLineWidth; + gridStyle = GridLineStyle; + gridLineWidth = GridLineWidth; } if (gridStyle == DataGridLineStyle.None) @@ -399,7 +399,7 @@ internal int FocusedTextWidth { get { - return this.focusedTextWidth; + return focusedTextWidth; } } @@ -411,11 +411,11 @@ public Color ForeColor { get { - return this.foreBrush.Color; + return foreBrush.Color; } set { - if (this.isDefaultTableStyle) + if (isDefaultTableStyle) { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "ForeColor")); } @@ -427,7 +427,7 @@ public Color ForeColor } if (!foreBrush.Color.Equals(value)) { - this.foreBrush = new SolidBrush(value); + foreBrush = new SolidBrush(value); InvalidateInside(); OnForeColorChanged(EventArgs.Empty); } @@ -444,15 +444,15 @@ internal SolidBrush ForeBrush { get { - return this.foreBrush; + return foreBrush; } } public void ResetForeColor() { - if (!this.foreBrush.Equals(DefaultForeBrush)) + if (!foreBrush.Equals(DefaultForeBrush)) { - this.ForeColor = DefaultForeBrush.Color; + ForeColor = DefaultForeBrush.Color; } } @@ -468,7 +468,7 @@ public Color GridLineColor } set { - if (this.isDefaultTableStyle) + if (isDefaultTableStyle) { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "GridLineColor")); } @@ -516,7 +516,7 @@ internal int GridLineWidth { get { - Debug.Assert(this.GridLineStyle == DataGridLineStyle.Solid || this.GridLineStyle == DataGridLineStyle.None, "are there any other styles?"); + Debug.Assert(GridLineStyle == DataGridLineStyle.Solid || GridLineStyle == DataGridLineStyle.None, "are there any other styles?"); return GridLineStyle == DataGridLineStyle.Solid ? 1 : 0; } } @@ -534,7 +534,7 @@ public DataGridLineStyle GridLineStyle } set { - if (this.isDefaultTableStyle) + if (isDefaultTableStyle) { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "GridLineStyle")); } @@ -571,7 +571,7 @@ public Color HeaderBackColor } set { - if (this.isDefaultTableStyle) + if (isDefaultTableStyle) { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "HeaderBackColor")); } @@ -633,11 +633,11 @@ public Font HeaderFont { get { - return (headerFont == null ? (this.DataGrid == null ? Control.DefaultFont : this.DataGrid.Font) : headerFont); + return (headerFont == null ? (DataGrid == null ? Control.DefaultFont : DataGrid.Font) : headerFont); } set { - if (this.isDefaultTableStyle) + if (isDefaultTableStyle) { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "HeaderFont")); } @@ -692,7 +692,7 @@ public Color HeaderForeColor } set { - if (this.isDefaultTableStyle) + if (isDefaultTableStyle) { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "HeaderForeColor")); } @@ -739,7 +739,7 @@ internal SolidBrush HeaderForeBrush { get { - return this.headerForeBrush; + return headerForeBrush; } } @@ -763,7 +763,7 @@ public Color LinkColor } set { - if (this.isDefaultTableStyle) + if (isDefaultTableStyle) { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "LinkColor")); } @@ -814,7 +814,7 @@ public Color LinkHoverColor { get { - return this.LinkColor; + return LinkColor; } [SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters")] set @@ -838,11 +838,11 @@ internal Rectangle RelationshipRect { get { - if (this.relationshipRect.IsEmpty) + if (relationshipRect.IsEmpty) { ComputeRelationshipRect(); } - return this.relationshipRect; + return relationshipRect; } } @@ -858,9 +858,9 @@ private Rectangle ComputeRelationshipRect() // Determine the width of the widest relationship name int longestRelationship = 0; - for (int r = 0; r < this.RelationsList.Count; ++r) + for (int r = 0; r < RelationsList.Count; ++r) { - int rwidth = (int)Math.Ceiling(g.MeasureString(((string)this.RelationsList[r]), this.DataGrid.LinkFont).Width) + int rwidth = (int)Math.Ceiling(g.MeasureString(((string)RelationsList[r]), DataGrid.LinkFont).Width) ; if (rwidth > longestRelationship) longestRelationship = rwidth; @@ -870,9 +870,9 @@ private Rectangle ComputeRelationshipRect() relationshipRect.Width = longestRelationship + 5; relationshipRect.Width += 2; // relationshipRect border; - relationshipRect.Height = BorderWidth + relationshipHeight * this.RelationsList.Count; + relationshipRect.Height = BorderWidth + relationshipHeight * RelationsList.Count; relationshipRect.Height += 2; // relationship border - if (this.RelationsList.Count > 0) + if (RelationsList.Count > 0) relationshipRect.Height += 2 * relationshipSpacing; } return relationshipRect; @@ -880,16 +880,16 @@ private Rectangle ComputeRelationshipRect() internal void ResetRelationsUI() { - this.relationshipRect = Rectangle.Empty; - this.focusedRelation = -1; - this.relationshipHeight = this.dataGrid.LinkFontHeight + relationshipSpacing; + relationshipRect = Rectangle.Empty; + focusedRelation = -1; + relationshipHeight = dataGrid.LinkFontHeight + relationshipSpacing; } internal int RelationshipHeight { get { - return this.relationshipHeight; + return relationshipHeight; } } @@ -914,7 +914,7 @@ public int PreferredColumnWidth } set { - if (this.isDefaultTableStyle) + if (isDefaultTableStyle) { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "PreferredColumnWidth")); } @@ -958,7 +958,7 @@ public int PreferredRowHeight } set { - if (this.isDefaultTableStyle) + if (isDefaultTableStyle) { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "PrefferedRowHeight")); } @@ -1085,8 +1085,8 @@ public int RowHeaderWidth } set { - if (this.DataGrid != null) - value = Math.Max(this.DataGrid.MinimumRowHeaderWidth(), value); + if (DataGrid != null) + value = Math.Max(DataGrid.MinimumRowHeaderWidth(), value); if (rowHeaderWidth != value) { rowHeaderWidth = value; @@ -1120,7 +1120,7 @@ public Color SelectionBackColor } set { - if (this.isDefaultTableStyle) + if (isDefaultTableStyle) { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "SelectionBackColor")); } @@ -1150,7 +1150,7 @@ internal SolidBrush SelectionBackBrush { get { - return this.selectionBackBrush; + return selectionBackBrush; } } @@ -1158,7 +1158,7 @@ internal SolidBrush SelectionForeBrush { get { - return this.selectionForeBrush; + return selectionForeBrush; } } @@ -1186,7 +1186,7 @@ public Color SelectionForeColor } set { - if (this.isDefaultTableStyle) + if (isDefaultTableStyle) { throw new ArgumentException(string.Format(SR.DataGridDefaultTableSet, "SelectionForeColor")); } @@ -1225,8 +1225,8 @@ public void ResetSelectionForeColor() // private void InvalidateInside() { - if (this.DataGrid != null) - this.DataGrid.InvalidateInside(); + if (DataGrid != null) + DataGrid.InvalidateInside(); } [ @@ -1241,7 +1241,7 @@ private void InvalidateInside() public DataGridTableStyle(bool isDefaultTableStyle) { gridColumns = new GridColumnStylesCollection(this, isDefaultTableStyle); - gridColumns.CollectionChanged += new CollectionChangeEventHandler(this.OnColumnCollectionChanged); + gridColumns.CollectionChanged += new CollectionChangeEventHandler(OnColumnCollectionChanged); this.isDefaultTableStyle = isDefaultTableStyle; } @@ -1260,7 +1260,7 @@ public DataGridTableStyle() : this(false) public DataGridTableStyle(CurrencyManager listManager) : this() { Debug.Assert(listManager != null, "the DataGridTabel cannot use a null listManager"); - this.mappingName = listManager.GetListName(); + mappingName = listManager.GetListName(); // set up the Relations and the columns SetGridColumnStylesCollection(listManager); } @@ -1268,7 +1268,7 @@ public DataGridTableStyle(CurrencyManager listManager) : this() internal void SetRelationsList(CurrencyManager listManager) { PropertyDescriptorCollection propCollection = listManager.GetItemProperties(); - Debug.Assert(!this.IsDefault, "the grid can set the relations only on a table that was manually added by the user"); + Debug.Assert(!IsDefault, "the grid can set the relations only on a table that was manually added by the user"); int propCount = propCollection.Count; if (relationsList.Count > 0) relationsList.Clear(); @@ -1287,7 +1287,7 @@ internal void SetRelationsList(CurrencyManager listManager) internal void SetGridColumnStylesCollection(CurrencyManager listManager) { // when we are setting the gridColumnStyles, do not handle any gridColumnCollectionChanged events - gridColumns.CollectionChanged -= new CollectionChangeEventHandler(this.OnColumnCollectionChanged); + gridColumns.CollectionChanged -= new CollectionChangeEventHandler(OnColumnCollectionChanged); PropertyDescriptorCollection propCollection = listManager.GetItemProperties(); @@ -1312,8 +1312,8 @@ internal void SetGridColumnStylesCollection(CurrencyManager listManager) else { // column - DataGridColumnStyle col = this.CreateGridColumn(prop, this.isDefaultTableStyle); - if (this.isDefaultTableStyle) + DataGridColumnStyle col = CreateGridColumn(prop, isDefaultTableStyle); + if (isDefaultTableStyle) gridColumns.AddDefaultColumn(col); else { @@ -1325,7 +1325,7 @@ internal void SetGridColumnStylesCollection(CurrencyManager listManager) } // now we are able to handle the collectionChangeEvents - gridColumns.CollectionChanged += new CollectionChangeEventHandler(this.OnColumnCollectionChanged); + gridColumns.CollectionChanged += new CollectionChangeEventHandler(OnColumnCollectionChanged); } private static bool PropertyDescriptorIsARelation(PropertyDescriptor prop) @@ -1335,7 +1335,7 @@ private static bool PropertyDescriptorIsARelation(PropertyDescriptor prop) internal protected virtual DataGridColumnStyle CreateGridColumn(PropertyDescriptor prop) { - return this.CreateGridColumn(prop, false); + return CreateGridColumn(prop, false); } internal protected virtual DataGridColumnStyle CreateGridColumn(PropertyDescriptor prop, bool isDefault) @@ -1373,7 +1373,7 @@ internal protected virtual DataGridColumnStyle CreateGridColumn(PropertyDescript internal void ResetRelationsList() { - if (this.isDefaultTableStyle) + if (isDefaultTableStyle) { relationsList.Clear(); } @@ -1399,18 +1399,18 @@ public string MappingName value = string.Empty; if (value.Equals(mappingName)) return; - string originalMappingName = this.MappingName; + string originalMappingName = MappingName; mappingName = value; // this could throw try { - if (this.DataGrid != null) - this.DataGrid.TableStyles.CheckForMappingNameDuplicates(this); + if (DataGrid != null) + DataGrid.TableStyles.CheckForMappingNameDuplicates(this); } catch { - this.mappingName = originalMappingName; + mappingName = originalMappingName; throw; } OnMappingNameChanged(EventArgs.Empty); @@ -1524,7 +1524,7 @@ public event EventHandler ReadOnlyChanged /// public bool BeginEdit(DataGridColumnStyle gridColumn, int rowNumber) { - DataGrid grid = this.DataGrid; + DataGrid grid = DataGrid; if (grid == null) return false; else @@ -1537,7 +1537,7 @@ public bool BeginEdit(DataGridColumnStyle gridColumn, int rowNumber) /// public bool EndEdit(DataGridColumnStyle gridColumn, int rowNumber, bool shouldAbort) { - DataGrid grid = this.DataGrid; + DataGrid grid = DataGrid; if (grid == null) return false; else @@ -1554,11 +1554,11 @@ internal void InvalidateColumn(DataGridColumnStyle column) private void OnColumnCollectionChanged(object sender, CollectionChangeEventArgs e) { - gridColumns.CollectionChanged -= new CollectionChangeEventHandler(this.OnColumnCollectionChanged); + gridColumns.CollectionChanged -= new CollectionChangeEventHandler(OnColumnCollectionChanged); try { - DataGrid grid = this.DataGrid; + DataGrid grid = DataGrid; DataGridColumnStyle col = e.Element as DataGridColumnStyle; if (e.Action == CollectionChangeAction.Add) { @@ -1586,7 +1586,7 @@ private void OnColumnCollectionChanged(object sender, CollectionChangeEventArgs } finally { - gridColumns.CollectionChanged += new CollectionChangeEventHandler(this.OnColumnCollectionChanged); + gridColumns.CollectionChanged += new CollectionChangeEventHandler(OnColumnCollectionChanged); } } @@ -1731,7 +1731,7 @@ protected override void Dispose(bool disposing) { if (disposing) { - GridColumnStylesCollection cols = this.GridColumnStyles; + GridColumnStylesCollection cols = GridColumnStyles; if (cols != null) { for (int i = 0; i < cols.Count; i++) @@ -1745,7 +1745,7 @@ internal bool IsDefault { get { - return this.isDefaultTableStyle; + return isDefaultTableStyle; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs index da2dfae43fc..e76db7a56eb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs @@ -26,12 +26,12 @@ public class GridTableStylesCollection : BaseCollection, IList int IList.Add(object value) { - return this.Add((DataGridTableStyle)value); + return Add((DataGridTableStyle)value); } void IList.Clear() { - this.Clear(); + Clear(); } bool IList.Contains(object value) @@ -51,12 +51,12 @@ void IList.Insert(int index, object value) void IList.Remove(object value) { - this.Remove((DataGridTableStyle)value); + Remove((DataGridTableStyle)value); } void IList.RemoveAt(int index) { - this.RemoveAt(index); + RemoveAt(index); } bool IList.IsFixedSize @@ -77,12 +77,12 @@ object IList.this[int index] void ICollection.CopyTo(Array array, int index) { - this.items.CopyTo(array, index); + items.CopyTo(array, index); } int ICollection.Count { - get { return this.items.Count; } + get { return items.Count; } } bool ICollection.IsSynchronized @@ -175,8 +175,8 @@ public virtual int Add(DataGridTableStyle table) { // set the rowHeaderWidth on the newly added table to at least the minimum value // on its owner - if (this.owner != null && this.owner.MinimumRowHeaderWidth() > table.RowHeaderWidth) - table.RowHeaderWidth = this.owner.MinimumRowHeaderWidth(); + if (owner != null && owner.MinimumRowHeaderWidth() > table.RowHeaderWidth) + table.RowHeaderWidth = owner.MinimumRowHeaderWidth(); if (table.DataGrid != owner && table.DataGrid != null) throw new ArgumentException(SR.DataGridTableStyleCollectionAddedParentedTableStyle, "table"); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBox.cs index 04f9406dbfa..bbca62f12be 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBox.cs @@ -72,7 +72,7 @@ protected override void OnKeyPress(KeyPressEventArgs e) // if the edit box is in ReadOnly mode, then do not tell the DataGrid about the // edit - if (this.ReadOnly) + if (ReadOnly) return; // Ctrl-* should not put the grid in edit mode @@ -133,7 +133,7 @@ protected internal override bool ProcessKeyMessage(ref Message m) // else, process the KeyEvent // if (SelectionStart + SelectionLength == 0 || - (this.IsInEditOrNavigateMode && this.SelectionLength == Text.Length)) + (IsInEditOrNavigateMode && SelectionLength == Text.Length)) return ProcessKeyPreview(ref m); return ProcessKeyEventArgs(ref m); case Keys.Down: diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs index 376dbeb428a..7858751988b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs @@ -86,7 +86,7 @@ public DataGridTextBoxColumn(PropertyDescriptor prop, string format, bool isDefa edit.Multiline = true; edit.AcceptsReturn = true; edit.Visible = false; - this.Format = format; + Format = format; } [ @@ -171,12 +171,12 @@ public override PropertyDescriptor PropertyDescriptor set { base.PropertyDescriptor = value; - if (this.PropertyDescriptor != null) + if (PropertyDescriptor != null) { - if (this.PropertyDescriptor.PropertyType != typeof(object)) + if (PropertyDescriptor.PropertyType != typeof(object)) { - this.typeConverter = TypeDescriptor.GetConverter(this.PropertyDescriptor.PropertyType); - this.parseMethod = this.PropertyDescriptor.PropertyType.GetMethod("Parse", new Type[] { typeof(string), typeof(IFormatProvider) }); + typeConverter = TypeDescriptor.GetConverter(PropertyDescriptor.PropertyType); + parseMethod = PropertyDescriptor.PropertyType.GetMethod("Parse", new Type[] { typeof(string), typeof(IFormatProvider) }); } } } @@ -197,15 +197,15 @@ public string Format value = string.Empty; if (format == null || !format.Equals(value)) { - this.format = value; + format = value; // if the associated typeConverter cannot convert from string, // then we can't modify the column value. hence, make it readOnly // if (format.Length == 0) { - if (this.typeConverter != null && !typeConverter.CanConvertFrom(typeof(string))) - this.ReadOnly = true; + if (typeConverter != null && !typeConverter.CanConvertFrom(typeof(string))) + ReadOnly = true; } Invalidate(); @@ -218,12 +218,12 @@ public IFormatProvider FormatInfo { get { - return this.formatInfo; + return formatInfo; } set { - if (this.formatInfo == null || !this.formatInfo.Equals(value)) - this.formatInfo = value; + if (formatInfo == null || !formatInfo.Equals(value)) + formatInfo = value; } } @@ -239,7 +239,7 @@ public override bool ReadOnly // the backGround propertyDescriptor, then make the column ReadOnly if (!value && (format == null || format.Length == 0)) { - if (this.typeConverter != null && !this.typeConverter.CanConvertFrom(typeof(string))) + if (typeConverter != null && !typeConverter.CanConvertFrom(typeof(string))) return; } base.ReadOnly = value; @@ -292,9 +292,9 @@ protected void HideEditBox() // before deleting the column will go to the backEnd) // however, in that situation, we are left w/ the editColumn which is not parented. // the grid will call Edit to reset the EditColumn - if (wasFocused && this.DataGridTableStyle != null && this.DataGridTableStyle.DataGrid != null && this.DataGridTableStyle.DataGrid.CanFocus) + if (wasFocused && DataGridTableStyle != null && DataGridTableStyle.DataGrid != null && DataGridTableStyle.DataGrid.CanFocus) { - this.DataGridTableStyle.DataGrid.Focus(); + DataGridTableStyle.DataGrid.Focus(); Debug.Assert(!edit.Focused, "the edit control just conceeded focus to the dataGrid"); } } @@ -326,7 +326,7 @@ protected void EndEdit() protected internal override Size GetPreferredSize(Graphics g, object value) { Size extents = Size.Ceiling(g.MeasureString(GetText(value), DataGridTableStyle.DataGrid.Font)); - extents.Width += xMargin * 2 + this.DataGridTableStyle.GridLineWidth; + extents.Width += xMargin * 2 + DataGridTableStyle.GridLineWidth; extents.Height += yMargin; return extents; } @@ -380,7 +380,7 @@ protected internal override void Abort(int rowNum) /// protected internal override void EnterNullValue() { - if (this.ReadOnly) + if (ReadOnly) return; // if the edit box is not visible, then @@ -397,8 +397,8 @@ protected internal override void EnterNullValue() // edit.Visible = true; edit.IsInEditOrNavigateMode = false; // tell the dataGrid that there is an edit: - if (this.DataGridTableStyle != null && this.DataGridTableStyle.DataGrid != null) - this.DataGridTableStyle.DataGrid.ColumnStartedEditing(edit.Bounds); + if (DataGridTableStyle != null && DataGridTableStyle.DataGrid != null) + DataGridTableStyle.DataGrid.ColumnStartedEditing(edit.Bounds); } /// @@ -423,11 +423,11 @@ protected internal override bool Commit(CurrencyManager dataSource, int rowNum) value = Convert.DBNull; edit.Text = NullText; } - else if (format != null && format.Length != 0 && this.parseMethod != null && this.FormatInfo != null) + else if (format != null && format.Length != 0 && parseMethod != null && FormatInfo != null) { // use reflection to get the Parse method on the // type of the propertyDescriptor. - value = (object)parseMethod.Invoke(null, new object[] { edit.Text, this.FormatInfo }); + value = (object)parseMethod.Invoke(null, new object[] { edit.Text, FormatInfo }); if (value is IFormattable) { edit.Text = ((IFormattable)value).ToString(format, formatInfo); @@ -473,15 +473,15 @@ protected internal override void Edit(CurrencyManager source, Rectangle originalBounds = bounds; - edit.ReadOnly = readOnly || ReadOnly || this.DataGridTableStyle.ReadOnly; + edit.ReadOnly = readOnly || ReadOnly || DataGridTableStyle.ReadOnly; edit.Text = GetText(GetColumnValueAtRow(source, rowNum)); if (!edit.ReadOnly && displayText != null) { // tell the grid that we are changing stuff - this.DataGridTableStyle.DataGrid.ColumnStartedEditing(bounds); + DataGridTableStyle.DataGrid.ColumnStartedEditing(bounds); // tell the edit control that the user changed it - this.edit.IsInEditOrNavigateMode = false; + edit.IsInEditOrNavigateMode = false; edit.Text = displayText; } @@ -495,7 +495,7 @@ protected internal override void Edit(CurrencyManager source, edit.Visible = true; - edit.TextAlign = this.Alignment; + edit.TextAlign = Alignment; } else { @@ -504,7 +504,7 @@ protected internal override void Edit(CurrencyManager source, // edit.Visible = false; } - edit.RightToLeft = this.DataGridTableStyle.DataGrid.RightToLeft; + edit.RightToLeft = DataGridTableStyle.DataGrid.RightToLeft; edit.Focus(); @@ -543,7 +543,7 @@ private string GetText(object value) { try { - return ((IFormattable)value).ToString(format, this.formatInfo); + return ((IFormattable)value).ToString(format, formatInfo); } catch { @@ -553,8 +553,8 @@ private string GetText(object value) else { // use the typeConverter: - if (this.typeConverter != null && this.typeConverter.CanConvertTo(typeof(string))) - return (string)this.typeConverter.ConvertTo(value, typeof(string)); + if (typeConverter != null && typeConverter.CanConvertTo(typeof(string))) + return (string)typeConverter.ConvertTo(value, typeof(string)); } return (value != null ? value.ToString() : ""); } @@ -597,7 +597,7 @@ protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyMan /// protected void PaintText(Graphics g, Rectangle bounds, string text, bool alignToRight) { - PaintText(g, bounds, text, this.DataGridTableStyle.BackBrush, this.DataGridTableStyle.ForeBrush, alignToRight); + PaintText(g, bounds, text, DataGridTableStyle.BackBrush, DataGridTableStyle.ForeBrush, alignToRight); } /// @@ -619,7 +619,7 @@ protected void PaintText(Graphics g, Rectangle textBounds, string text, Brush ba format.FormatFlags |= StringFormatFlags.DirectionRightToLeft; } - format.Alignment = this.Alignment == HorizontalAlignment.Left ? StringAlignment.Near : this.Alignment == HorizontalAlignment.Center ? StringAlignment.Center : StringAlignment.Far; + format.Alignment = Alignment == HorizontalAlignment.Left ? StringAlignment.Near : Alignment == HorizontalAlignment.Center ? StringAlignment.Center : StringAlignment.Far; // do not wrap the text // @@ -630,7 +630,7 @@ protected void PaintText(Graphics g, Rectangle textBounds, string text, Brush ba // so do not deflate the rectangle. rect.Offset(0, 2 * yMargin); rect.Height -= 2 * yMargin; - g.DrawString(text, this.DataGridTableStyle.DataGrid.Font, foreBrush, rect, format); + g.DrawString(text, DataGridTableStyle.DataGrid.Font, foreBrush, rect, format); format.Dispose(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridView.cs index d729ca05025..668ec29b7fe 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridView.cs @@ -424,11 +424,11 @@ public DataGridView() // this class overrides GetPreferredSizeCore, let Control automatically cache the result SetState2(STATE2_USEPREFERREDSIZECACHE, true); - this.dataGridViewState1 = new System.Collections.Specialized.BitVector32(0x00000000); - this.dataGridViewState2 = new System.Collections.Specialized.BitVector32(0x00000000); - this.dataGridViewOper = new System.Collections.Specialized.BitVector32(0x00000000); + dataGridViewState1 = new System.Collections.Specialized.BitVector32(0x00000000); + dataGridViewState2 = new System.Collections.Specialized.BitVector32(0x00000000); + dataGridViewOper = new System.Collections.Specialized.BitVector32(0x00000000); - this.dataGridViewState1[DATAGRIDVIEWSTATE1_columnHeadersVisible + dataGridViewState1[DATAGRIDVIEWSTATE1_columnHeadersVisible | DATAGRIDVIEWSTATE1_rowHeadersVisible | DATAGRIDVIEWSTATE1_autoGenerateColumns | DATAGRIDVIEWSTATE1_allowUserToAddRows @@ -436,7 +436,7 @@ public DataGridView() - this.dataGridViewState2[DATAGRIDVIEWSTATE2_showEditingIcon + dataGridViewState2[DATAGRIDVIEWSTATE2_showEditingIcon | DATAGRIDVIEWSTATE2_enableHeadersVisualStyles | DATAGRIDVIEWSTATE2_mouseEnterExpected | DATAGRIDVIEWSTATE2_allowUserToResizeColumns @@ -448,80 +448,80 @@ public DataGridView() | DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = true; - this.displayedBandsInfo = new DisplayedBandsData(); - this.lstRows = new ArrayList(); + displayedBandsInfo = new DisplayedBandsData(); + lstRows = new ArrayList(); - this.converters = new Hashtable(8); - this.pens = new Hashtable(8); - this.brushes = new Hashtable(10); - this.gridPen = new Pen(DefaultGridColor); + converters = new Hashtable(8); + pens = new Hashtable(8); + brushes = new Hashtable(10); + gridPen = new Pen(DefaultGridColor); - this.selectedBandIndexes = new DataGridViewIntLinkedList(); - this.individualSelectedCells = new DataGridViewCellLinkedList(); - this.individualReadOnlyCells = new DataGridViewCellLinkedList(); + selectedBandIndexes = new DataGridViewIntLinkedList(); + individualSelectedCells = new DataGridViewCellLinkedList(); + individualReadOnlyCells = new DataGridViewCellLinkedList(); - this.advancedCellBorderStyle = new DataGridViewAdvancedBorderStyle(this, + advancedCellBorderStyle = new DataGridViewAdvancedBorderStyle(this, DataGridViewAdvancedCellBorderStyle.OutsetDouble, DataGridViewAdvancedCellBorderStyle.OutsetPartial, DataGridViewAdvancedCellBorderStyle.InsetDouble); - this.advancedRowHeadersBorderStyle = new DataGridViewAdvancedBorderStyle(this); - this.advancedColumnHeadersBorderStyle = new DataGridViewAdvancedBorderStyle(this); - this.advancedCellBorderStyle.All = defaultAdvancedCellBorderStyle; - this.advancedRowHeadersBorderStyle.All = defaultAdvancedRowHeadersBorderStyle; - this.advancedColumnHeadersBorderStyle.All = defaultAdvancedColumnHeadersBorderStyle; - this.borderStyle = defaultBorderStyle; - this.dataGridViewState1[DATAGRIDVIEWSTATE1_multiSelect] = true; - this.selectionMode = defaultSelectionMode; - this.editMode = defaultEditMode; - this.autoSizeRowsMode = DataGridViewAutoSizeRowsMode.None; - this.autoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None; - this.columnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing; - this.rowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing; - - this.clipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithAutoHeaderText; - - this.layout = new LayoutData(); - this.layout.TopLeftHeader = Rectangle.Empty; - this.layout.ColumnHeaders = Rectangle.Empty; - this.layout.RowHeaders = Rectangle.Empty; - this.layout.ColumnHeadersVisible = true; - this.layout.RowHeadersVisible = true; - this.layout.ClientRectangle = this.ClientRectangle; - - this.scrollBars = ScrollBars.Both; - - this.horizScrollBar.RightToLeft = RightToLeft.Inherit; - this.horizScrollBar.AccessibleName = string.Format(SR.DataGridView_AccHorizontalScrollBarAccName); - this.horizScrollBar.Top = this.ClientRectangle.Height - horizScrollBar.Height; - this.horizScrollBar.Left = 0; - this.horizScrollBar.Visible = false; - this.horizScrollBar.Scroll += new ScrollEventHandler(DataGridViewHScrolled); - this.Controls.Add(this.horizScrollBar); - - this.vertScrollBar.Top = 0; - this.vertScrollBar.AccessibleName = string.Format(SR.DataGridView_AccVerticalScrollBarAccName); - this.vertScrollBar.Left = this.ClientRectangle.Width - vertScrollBar.Width; - this.vertScrollBar.Visible = false; - this.vertScrollBar.Scroll += new ScrollEventHandler(DataGridViewVScrolled); - this.Controls.Add(this.vertScrollBar); - - this.ptCurrentCell = new Point(-1, -1); - this.ptAnchorCell = new Point(-1, -1); - this.ptMouseDownCell = new Point(-2, -2); - this.ptMouseEnteredCell = new Point(-2, -2); - this.ptToolTipCell = new Point(-1, -1); - this.ptMouseDownGridCoord = new Point(-1, -1); - - this.sortOrder = SortOrder.None; - - this.lastMouseClickInfo.timeStamp = 0; + advancedRowHeadersBorderStyle = new DataGridViewAdvancedBorderStyle(this); + advancedColumnHeadersBorderStyle = new DataGridViewAdvancedBorderStyle(this); + advancedCellBorderStyle.All = defaultAdvancedCellBorderStyle; + advancedRowHeadersBorderStyle.All = defaultAdvancedRowHeadersBorderStyle; + advancedColumnHeadersBorderStyle.All = defaultAdvancedColumnHeadersBorderStyle; + borderStyle = defaultBorderStyle; + dataGridViewState1[DATAGRIDVIEWSTATE1_multiSelect] = true; + selectionMode = defaultSelectionMode; + editMode = defaultEditMode; + autoSizeRowsMode = DataGridViewAutoSizeRowsMode.None; + autoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None; + columnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing; + rowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing; + + clipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithAutoHeaderText; + + layout = new LayoutData(); + layout.TopLeftHeader = Rectangle.Empty; + layout.ColumnHeaders = Rectangle.Empty; + layout.RowHeaders = Rectangle.Empty; + layout.ColumnHeadersVisible = true; + layout.RowHeadersVisible = true; + layout.ClientRectangle = ClientRectangle; + + scrollBars = ScrollBars.Both; + + horizScrollBar.RightToLeft = RightToLeft.Inherit; + horizScrollBar.AccessibleName = string.Format(SR.DataGridView_AccHorizontalScrollBarAccName); + horizScrollBar.Top = ClientRectangle.Height - horizScrollBar.Height; + horizScrollBar.Left = 0; + horizScrollBar.Visible = false; + horizScrollBar.Scroll += new ScrollEventHandler(DataGridViewHScrolled); + Controls.Add(horizScrollBar); + + vertScrollBar.Top = 0; + vertScrollBar.AccessibleName = string.Format(SR.DataGridView_AccVerticalScrollBarAccName); + vertScrollBar.Left = ClientRectangle.Width - vertScrollBar.Width; + vertScrollBar.Visible = false; + vertScrollBar.Scroll += new ScrollEventHandler(DataGridViewVScrolled); + Controls.Add(vertScrollBar); + + ptCurrentCell = new Point(-1, -1); + ptAnchorCell = new Point(-1, -1); + ptMouseDownCell = new Point(-2, -2); + ptMouseEnteredCell = new Point(-2, -2); + ptToolTipCell = new Point(-1, -1); + ptMouseDownGridCoord = new Point(-1, -1); + + sortOrder = SortOrder.None; + + lastMouseClickInfo.timeStamp = 0; WireScrollBarsEvents(); PerformLayout(); - this.toolTipControl = new DataGridViewToolTip(this); - this.rowHeadersWidth = ScaleToCurrentDpi(defaultRowHeadersWidth); - this.columnHeadersHeight = ScaleToCurrentDpi(defaultColumnHeadersHeight); + toolTipControl = new DataGridViewToolTip(this); + rowHeadersWidth = ScaleToCurrentDpi(defaultRowHeadersWidth); + columnHeadersHeight = ScaleToCurrentDpi(defaultColumnHeadersHeight); Invalidate(); } @@ -543,14 +543,14 @@ public virtual DataGridViewAdvancedBorderStyle AdjustedTopLeftHeaderBorderStyle get { DataGridViewAdvancedBorderStyle dgvabs; - if (this.ApplyVisualStylesToHeaderCells) + if (ApplyVisualStylesToHeaderCells) { - switch (this.AdvancedColumnHeadersBorderStyle.All) + switch (AdvancedColumnHeadersBorderStyle.All) { case DataGridViewAdvancedCellBorderStyle.OutsetDouble: case DataGridViewAdvancedCellBorderStyle.OutsetPartial: dgvabs = new DataGridViewAdvancedBorderStyle(); - if (this.RightToLeftInternal) + if (RightToLeftInternal) { dgvabs.LeftInternal = DataGridViewAdvancedCellBorderStyle.Outset; } @@ -565,7 +565,7 @@ public virtual DataGridViewAdvancedBorderStyle AdjustedTopLeftHeaderBorderStyle case DataGridViewAdvancedCellBorderStyle.InsetDouble: dgvabs = new DataGridViewAdvancedBorderStyle(); - if (this.RightToLeftInternal) + if (RightToLeftInternal) { dgvabs.LeftInternal = DataGridViewAdvancedCellBorderStyle.Inset; } @@ -581,52 +581,52 @@ public virtual DataGridViewAdvancedBorderStyle AdjustedTopLeftHeaderBorderStyle case DataGridViewAdvancedCellBorderStyle.NotSet: // Since the row headers are visible, we should make sure // that there is a left/right border for the TopLeftHeaderCell no matter what. - if ((!this.RightToLeftInternal && this.AdvancedColumnHeadersBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.None) || - (this.RightToLeftInternal && this.AdvancedColumnHeadersBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.None)) + if ((!RightToLeftInternal && AdvancedColumnHeadersBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.None) || + (RightToLeftInternal && AdvancedColumnHeadersBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.None)) { dgvabs = new DataGridViewAdvancedBorderStyle(); - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - dgvabs.LeftInternal = this.AdvancedColumnHeadersBorderStyle.Left; - dgvabs.RightInternal = this.AdvancedRowHeadersBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.OutsetDouble ? - DataGridViewAdvancedCellBorderStyle.Outset : this.AdvancedRowHeadersBorderStyle.Right; + dgvabs.LeftInternal = AdvancedColumnHeadersBorderStyle.Left; + dgvabs.RightInternal = AdvancedRowHeadersBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.OutsetDouble ? + DataGridViewAdvancedCellBorderStyle.Outset : AdvancedRowHeadersBorderStyle.Right; } else { - dgvabs.LeftInternal = this.AdvancedRowHeadersBorderStyle.Left; - dgvabs.RightInternal = this.AdvancedColumnHeadersBorderStyle.Right; + dgvabs.LeftInternal = AdvancedRowHeadersBorderStyle.Left; + dgvabs.RightInternal = AdvancedColumnHeadersBorderStyle.Right; } - dgvabs.TopInternal = this.AdvancedColumnHeadersBorderStyle.Top; - dgvabs.BottomInternal = this.AdvancedColumnHeadersBorderStyle.Bottom; + dgvabs.TopInternal = AdvancedColumnHeadersBorderStyle.Top; + dgvabs.BottomInternal = AdvancedColumnHeadersBorderStyle.Bottom; } else { - dgvabs = this.AdvancedColumnHeadersBorderStyle; + dgvabs = AdvancedColumnHeadersBorderStyle; } break; default: - dgvabs = this.AdvancedColumnHeadersBorderStyle; + dgvabs = AdvancedColumnHeadersBorderStyle; break; } } else { - switch (this.AdvancedColumnHeadersBorderStyle.All) + switch (AdvancedColumnHeadersBorderStyle.All) { case DataGridViewAdvancedCellBorderStyle.OutsetDouble: case DataGridViewAdvancedCellBorderStyle.OutsetPartial: dgvabs = new DataGridViewAdvancedBorderStyle(); - dgvabs.LeftInternal = this.RightToLeftInternal ? DataGridViewAdvancedCellBorderStyle.Outset : DataGridViewAdvancedCellBorderStyle.OutsetDouble; - dgvabs.RightInternal = this.RightToLeftInternal ? DataGridViewAdvancedCellBorderStyle.OutsetDouble : DataGridViewAdvancedCellBorderStyle.Outset; + dgvabs.LeftInternal = RightToLeftInternal ? DataGridViewAdvancedCellBorderStyle.Outset : DataGridViewAdvancedCellBorderStyle.OutsetDouble; + dgvabs.RightInternal = RightToLeftInternal ? DataGridViewAdvancedCellBorderStyle.OutsetDouble : DataGridViewAdvancedCellBorderStyle.Outset; dgvabs.TopInternal = DataGridViewAdvancedCellBorderStyle.OutsetDouble; dgvabs.BottomInternal = DataGridViewAdvancedCellBorderStyle.Outset; break; case DataGridViewAdvancedCellBorderStyle.InsetDouble: dgvabs = new DataGridViewAdvancedBorderStyle(); - dgvabs.LeftInternal = this.RightToLeftInternal ? DataGridViewAdvancedCellBorderStyle.Inset : DataGridViewAdvancedCellBorderStyle.InsetDouble; - dgvabs.RightInternal = this.RightToLeftInternal ? DataGridViewAdvancedCellBorderStyle.InsetDouble : DataGridViewAdvancedCellBorderStyle.Inset; + dgvabs.LeftInternal = RightToLeftInternal ? DataGridViewAdvancedCellBorderStyle.Inset : DataGridViewAdvancedCellBorderStyle.InsetDouble; + dgvabs.RightInternal = RightToLeftInternal ? DataGridViewAdvancedCellBorderStyle.InsetDouble : DataGridViewAdvancedCellBorderStyle.Inset; dgvabs.TopInternal = DataGridViewAdvancedCellBorderStyle.InsetDouble; dgvabs.BottomInternal = DataGridViewAdvancedCellBorderStyle.Inset; break; @@ -634,31 +634,31 @@ public virtual DataGridViewAdvancedBorderStyle AdjustedTopLeftHeaderBorderStyle case DataGridViewAdvancedCellBorderStyle.NotSet: // Since the row headers are visible, we should make sure // that there is a left/right border for the TopLeftHeaderCell no matter what. - if ((!this.RightToLeftInternal && this.AdvancedColumnHeadersBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.None) || - (this.RightToLeftInternal && this.AdvancedColumnHeadersBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.None)) + if ((!RightToLeftInternal && AdvancedColumnHeadersBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.None) || + (RightToLeftInternal && AdvancedColumnHeadersBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.None)) { dgvabs = new DataGridViewAdvancedBorderStyle(); - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - dgvabs.LeftInternal = this.AdvancedColumnHeadersBorderStyle.Left; - dgvabs.RightInternal = this.AdvancedRowHeadersBorderStyle.Right; + dgvabs.LeftInternal = AdvancedColumnHeadersBorderStyle.Left; + dgvabs.RightInternal = AdvancedRowHeadersBorderStyle.Right; } else { - dgvabs.LeftInternal = this.AdvancedRowHeadersBorderStyle.Left; - dgvabs.RightInternal = this.AdvancedColumnHeadersBorderStyle.Right; + dgvabs.LeftInternal = AdvancedRowHeadersBorderStyle.Left; + dgvabs.RightInternal = AdvancedColumnHeadersBorderStyle.Right; } - dgvabs.TopInternal = this.AdvancedColumnHeadersBorderStyle.Top; - dgvabs.BottomInternal = this.AdvancedColumnHeadersBorderStyle.Bottom; + dgvabs.TopInternal = AdvancedColumnHeadersBorderStyle.Top; + dgvabs.BottomInternal = AdvancedColumnHeadersBorderStyle.Bottom; } else { - dgvabs = this.AdvancedColumnHeadersBorderStyle; + dgvabs = AdvancedColumnHeadersBorderStyle; } break; default: - dgvabs = this.AdvancedColumnHeadersBorderStyle; + dgvabs = AdvancedColumnHeadersBorderStyle; break; } } @@ -674,7 +674,7 @@ public DataGridViewAdvancedBorderStyle AdvancedCellBorderStyle { get { - return this.advancedCellBorderStyle; + return advancedCellBorderStyle; } } @@ -686,7 +686,7 @@ public DataGridViewAdvancedBorderStyle AdvancedColumnHeadersBorderStyle { get { - return this.advancedColumnHeadersBorderStyle; + return advancedColumnHeadersBorderStyle; } } @@ -698,7 +698,7 @@ public DataGridViewAdvancedBorderStyle AdvancedRowHeadersBorderStyle { get { - return this.advancedRowHeadersBorderStyle; + return advancedRowHeadersBorderStyle; } } @@ -711,16 +711,16 @@ public bool AllowUserToAddRows { get { - return this.dataGridViewState1[DATAGRIDVIEWSTATE1_allowUserToAddRows]; + return dataGridViewState1[DATAGRIDVIEWSTATE1_allowUserToAddRows]; } set { - if (this.AllowUserToAddRows != value) + if (AllowUserToAddRows != value) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_allowUserToAddRows] = value; - if (this.DataSource != null) + dataGridViewState1[DATAGRIDVIEWSTATE1_allowUserToAddRows] = value; + if (DataSource != null) { - this.dataConnection.ResetCachedAllowUserToAddRowsInternal(); + dataConnection.ResetCachedAllowUserToAddRowsInternal(); } OnAllowUserToAddRowsChanged(EventArgs.Empty); } @@ -731,13 +731,13 @@ internal bool AllowUserToAddRowsInternal { get { - if (this.DataSource == null) + if (DataSource == null) { - return this.AllowUserToAddRows; + return AllowUserToAddRows; } else { - return this.AllowUserToAddRows && this.dataConnection.AllowAdd; + return AllowUserToAddRows && dataConnection.AllowAdd; } } } @@ -748,8 +748,8 @@ internal bool AllowUserToAddRowsInternal ] public event EventHandler AllowUserToAddRowsChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWALLOWUSERTOADDROWSCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWALLOWUSERTOADDROWSCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWALLOWUSERTOADDROWSCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWALLOWUSERTOADDROWSCHANGED, value); } [ @@ -761,13 +761,13 @@ public bool AllowUserToDeleteRows { get { - return this.dataGridViewState1[DATAGRIDVIEWSTATE1_allowUserToDeleteRows]; + return dataGridViewState1[DATAGRIDVIEWSTATE1_allowUserToDeleteRows]; } set { - if (this.AllowUserToDeleteRows != value) + if (AllowUserToDeleteRows != value) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_allowUserToDeleteRows] = value; + dataGridViewState1[DATAGRIDVIEWSTATE1_allowUserToDeleteRows] = value; OnAllowUserToDeleteRowsChanged(EventArgs.Empty); } } @@ -777,13 +777,13 @@ internal bool AllowUserToDeleteRowsInternal { get { - if (this.DataSource == null) + if (DataSource == null) { - return this.AllowUserToDeleteRows; + return AllowUserToDeleteRows; } else { - return this.AllowUserToDeleteRows && this.dataConnection.AllowRemove; + return AllowUserToDeleteRows && dataConnection.AllowRemove; } } } @@ -794,8 +794,8 @@ internal bool AllowUserToDeleteRowsInternal ] public event EventHandler AllowUserToDeleteRowsChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWALLOWUSERTODELETEROWSCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWALLOWUSERTODELETEROWSCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWALLOWUSERTODELETEROWSCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWALLOWUSERTODELETEROWSCHANGED, value); } [ @@ -807,13 +807,13 @@ public bool AllowUserToOrderColumns { get { - return this.dataGridViewState1[DATAGRIDVIEWSTATE1_allowUserToOrderColumns]; + return dataGridViewState1[DATAGRIDVIEWSTATE1_allowUserToOrderColumns]; } set { - if (this.AllowUserToOrderColumns != value) + if (AllowUserToOrderColumns != value) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_allowUserToOrderColumns] = value; + dataGridViewState1[DATAGRIDVIEWSTATE1_allowUserToOrderColumns] = value; OnAllowUserToOrderColumnsChanged(EventArgs.Empty); } } @@ -825,8 +825,8 @@ public bool AllowUserToOrderColumns ] public event EventHandler AllowUserToOrderColumnsChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWALLOWUSERTOORDERCOLUMNSCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWALLOWUSERTOORDERCOLUMNSCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWALLOWUSERTOORDERCOLUMNSCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWALLOWUSERTOORDERCOLUMNSCHANGED, value); } /// @@ -844,13 +844,13 @@ public bool AllowUserToResizeColumns { get { - return this.dataGridViewState2[DATAGRIDVIEWSTATE2_allowUserToResizeColumns]; + return dataGridViewState2[DATAGRIDVIEWSTATE2_allowUserToResizeColumns]; } set { - if (this.AllowUserToResizeColumns != value) + if (AllowUserToResizeColumns != value) { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_allowUserToResizeColumns] = value; + dataGridViewState2[DATAGRIDVIEWSTATE2_allowUserToResizeColumns] = value; OnAllowUserToResizeColumnsChanged(EventArgs.Empty); } } @@ -862,8 +862,8 @@ public bool AllowUserToResizeColumns ] public event EventHandler AllowUserToResizeColumnsChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWALLOWUSERTORESIZECOLUMNSCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWALLOWUSERTORESIZECOLUMNSCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWALLOWUSERTORESIZECOLUMNSCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWALLOWUSERTORESIZECOLUMNSCHANGED, value); } /// @@ -881,13 +881,13 @@ public bool AllowUserToResizeRows { get { - return this.dataGridViewState2[DATAGRIDVIEWSTATE2_allowUserToResizeRows]; + return dataGridViewState2[DATAGRIDVIEWSTATE2_allowUserToResizeRows]; } set { - if (this.AllowUserToResizeRows != value) + if (AllowUserToResizeRows != value) { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_allowUserToResizeRows] = value; + dataGridViewState2[DATAGRIDVIEWSTATE2_allowUserToResizeRows] = value; OnAllowUserToResizeRowsChanged(EventArgs.Empty); } } @@ -899,8 +899,8 @@ public bool AllowUserToResizeRows ] public event EventHandler AllowUserToResizeRowsChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWALLOWUSERTORESIZEROWSCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWALLOWUSERTORESIZEROWSCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWALLOWUSERTORESIZEROWSCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWALLOWUSERTORESIZEROWSCHANGED, value); } [ @@ -911,27 +911,27 @@ public DataGridViewCellStyle AlternatingRowsDefaultCellStyle { get { - if (this.alternatingRowsDefaultCellStyle == null) + if (alternatingRowsDefaultCellStyle == null) { - this.alternatingRowsDefaultCellStyle = new DataGridViewCellStyle(); - this.alternatingRowsDefaultCellStyle.AddScope(this, DataGridViewCellStyleScopes.AlternatingRows); + alternatingRowsDefaultCellStyle = new DataGridViewCellStyle(); + alternatingRowsDefaultCellStyle.AddScope(this, DataGridViewCellStyleScopes.AlternatingRows); } - return this.alternatingRowsDefaultCellStyle; + return alternatingRowsDefaultCellStyle; } set { - DataGridViewCellStyle cs = this.AlternatingRowsDefaultCellStyle; + DataGridViewCellStyle cs = AlternatingRowsDefaultCellStyle; cs.RemoveScope(DataGridViewCellStyleScopes.AlternatingRows); - this.alternatingRowsDefaultCellStyle = value; + alternatingRowsDefaultCellStyle = value; if (value != null) { - this.alternatingRowsDefaultCellStyle.AddScope(this, DataGridViewCellStyleScopes.AlternatingRows); + alternatingRowsDefaultCellStyle.AddScope(this, DataGridViewCellStyleScopes.AlternatingRows); } - DataGridViewCellStyleDifferences dgvcsc = cs.GetDifferencesFrom(this.AlternatingRowsDefaultCellStyle); + DataGridViewCellStyleDifferences dgvcsc = cs.GetDifferencesFrom(AlternatingRowsDefaultCellStyle); if (dgvcsc != DataGridViewCellStyleDifferences.None) { - this.CellStyleChangedEventArgs.ChangeAffectsPreferredSize = (dgvcsc == DataGridViewCellStyleDifferences.AffectPreferredSize); - OnAlternatingRowsDefaultCellStyleChanged(this.CellStyleChangedEventArgs); + CellStyleChangedEventArgs.ChangeAffectsPreferredSize = (dgvcsc == DataGridViewCellStyleDifferences.AffectPreferredSize); + OnAlternatingRowsDefaultCellStyleChanged(CellStyleChangedEventArgs); } } } @@ -942,8 +942,8 @@ public DataGridViewCellStyle AlternatingRowsDefaultCellStyle ] public event EventHandler AlternatingRowsDefaultCellStyleChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWALTERNATINGROWSDEFAULTCELLSTYLECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWALTERNATINGROWSDEFAULTCELLSTYLECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWALTERNATINGROWSDEFAULTCELLSTYLECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWALTERNATINGROWSDEFAULTCELLSTYLECHANGED, value); } internal bool ApplyVisualStylesToInnerCells @@ -958,7 +958,7 @@ internal bool ApplyVisualStylesToHeaderCells { get { - return Application.RenderWithVisualStyles && this.EnableHeadersVisualStyles; + return Application.RenderWithVisualStyles && EnableHeadersVisualStyles; } } @@ -975,13 +975,13 @@ public bool AutoGenerateColumns { get { - return this.dataGridViewState1[DATAGRIDVIEWSTATE1_autoGenerateColumns]; + return dataGridViewState1[DATAGRIDVIEWSTATE1_autoGenerateColumns]; } set { - if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_autoGenerateColumns] != value) + if (dataGridViewState1[DATAGRIDVIEWSTATE1_autoGenerateColumns] != value) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_autoGenerateColumns] = value; + dataGridViewState1[DATAGRIDVIEWSTATE1_autoGenerateColumns] = value; OnAutoGenerateColumnsChanged(EventArgs.Empty); } } @@ -993,8 +993,8 @@ public bool AutoGenerateColumns ] public event EventHandler AutoGenerateColumnsChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWAUTOGENERATECOLUMNSCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWAUTOGENERATECOLUMNSCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWAUTOGENERATECOLUMNSCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWAUTOGENERATECOLUMNSCHANGED, value); } /// @@ -1004,12 +1004,12 @@ public override bool AutoSize { get { - return this.dataGridViewState1[DATAGRIDVIEWSTATE1_isAutoSized]; + return dataGridViewState1[DATAGRIDVIEWSTATE1_isAutoSized]; } set { base.AutoSize = value; - this.dataGridViewState1[DATAGRIDVIEWSTATE1_isAutoSized] = value; + dataGridViewState1[DATAGRIDVIEWSTATE1_isAutoSized] = value; } } @@ -1027,7 +1027,7 @@ public DataGridViewAutoSizeColumnsMode AutoSizeColumnsMode { get { - return this.autoSizeColumnsMode; + return autoSizeColumnsMode; } set @@ -1047,14 +1047,14 @@ public DataGridViewAutoSizeColumnsMode AutoSizeColumnsMode } - if (this.autoSizeColumnsMode != value) + if (autoSizeColumnsMode != value) { - foreach (DataGridViewColumn dataGridViewColumn in this.Columns) + foreach (DataGridViewColumn dataGridViewColumn in Columns) { if (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.NotSet && dataGridViewColumn.Visible) { // Make sure there is no visible column which would have an inherited autosize mode based on the header only. - if (value == DataGridViewAutoSizeColumnsMode.ColumnHeader && !this.ColumnHeadersVisible) + if (value == DataGridViewAutoSizeColumnsMode.ColumnHeader && !ColumnHeadersVisible) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAutoSizeColumnsInvisibleColumnHeaders)); } @@ -1065,8 +1065,8 @@ public DataGridViewAutoSizeColumnsMode AutoSizeColumnsMode } } } - DataGridViewAutoSizeColumnMode[] previousModes = new DataGridViewAutoSizeColumnMode[this.Columns.Count]; - foreach (DataGridViewColumn dataGridViewColumn in this.Columns) + DataGridViewAutoSizeColumnMode[] previousModes = new DataGridViewAutoSizeColumnMode[Columns.Count]; + foreach (DataGridViewColumn dataGridViewColumn in Columns) { /*DataGridViewAutoSizeColumnMode previousInheritedMode = dataGridViewColumn.InheritedAutoSizeMode; bool previousInheritedModeAutoSized = previousInheritedMode != DataGridViewAutoSizeColumnMode.Fill && @@ -1075,7 +1075,7 @@ public DataGridViewAutoSizeColumnsMode AutoSizeColumnsMode previousModes[dataGridViewColumn.Index] = dataGridViewColumn.InheritedAutoSizeMode; } DataGridViewAutoSizeColumnsModeEventArgs dgvcasme = new DataGridViewAutoSizeColumnsModeEventArgs(previousModes); - this.autoSizeColumnsMode = value; + autoSizeColumnsMode = value; OnAutoSizeColumnsModeChanged(dgvcasme); } } @@ -1087,8 +1087,8 @@ public DataGridViewAutoSizeColumnsMode AutoSizeColumnsMode ] public event DataGridViewAutoSizeColumnsModeEventHandler AutoSizeColumnsModeChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWAUTOSIZECOLUMNSMODECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWAUTOSIZECOLUMNSMODECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWAUTOSIZECOLUMNSMODECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWAUTOSIZECOLUMNSMODECHANGED, value); } /// @@ -1103,7 +1103,7 @@ public DataGridViewAutoSizeRowsMode AutoSizeRowsMode { get { - return this.autoSizeRowsMode; + return autoSizeRowsMode; } set { @@ -1121,14 +1121,14 @@ public DataGridViewAutoSizeRowsMode AutoSizeRowsMode throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewAutoSizeRowsMode)); } if ((value == DataGridViewAutoSizeRowsMode.AllHeaders || value == DataGridViewAutoSizeRowsMode.DisplayedHeaders) && - !this.RowHeadersVisible) + !RowHeadersVisible) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAutoSizeRowsInvisibleRowHeader)); } - if (this.autoSizeRowsMode != value) + if (autoSizeRowsMode != value) { - DataGridViewAutoSizeModeEventArgs dgvasme = new DataGridViewAutoSizeModeEventArgs(this.autoSizeRowsMode != DataGridViewAutoSizeRowsMode.None); - this.autoSizeRowsMode = value; + DataGridViewAutoSizeModeEventArgs dgvasme = new DataGridViewAutoSizeModeEventArgs(autoSizeRowsMode != DataGridViewAutoSizeRowsMode.None); + autoSizeRowsMode = value; OnAutoSizeRowsModeChanged(dgvasme); } } @@ -1140,8 +1140,8 @@ public DataGridViewAutoSizeRowsMode AutoSizeRowsMode ] public event DataGridViewAutoSizeModeEventHandler AutoSizeRowsModeChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWAUTOSIZEROWSMODECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWAUTOSIZEROWSMODECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWAUTOSIZEROWSMODECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWAUTOSIZEROWSMODECHANGED, value); } [ @@ -1175,7 +1175,7 @@ internal SolidBrush BackgroundBrush { get { - return this.backgroundBrush; + return backgroundBrush; } } @@ -1190,7 +1190,7 @@ public Color BackgroundColor { get { - return this.backgroundBrush.Color; + return backgroundBrush.Color; } set { @@ -1202,9 +1202,9 @@ public Color BackgroundColor { throw new ArgumentException(string.Format(SR.DataGridView_TransparentColor, "BackgroundColor")); } - if (!value.Equals(this.backgroundBrush.Color)) + if (!value.Equals(backgroundBrush.Color)) { - this.backgroundBrush = new SolidBrush(value); + backgroundBrush = new SolidBrush(value); OnBackgroundColorChanged(EventArgs.Empty); } } @@ -1216,8 +1216,8 @@ public Color BackgroundColor ] public event EventHandler BackgroundColorChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWBACKGROUNDCOLORCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWBACKGROUNDCOLORCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWBACKGROUNDCOLORCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWBACKGROUNDCOLORCHANGED, value); } [ @@ -1274,7 +1274,7 @@ public override ImageLayout BackgroundImageLayout private bool ShouldSerializeBackgroundColor() { - return !this.BackgroundColor.Equals(DefaultBackgroundBrush.Color); + return !BackgroundColor.Equals(DefaultBackgroundBrush.Color); } [ @@ -1286,7 +1286,7 @@ public BorderStyle BorderStyle { get { - return this.borderStyle; + return borderStyle; } set { @@ -1295,12 +1295,12 @@ public BorderStyle BorderStyle { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(BorderStyle)); } - if (this.borderStyle != value) + if (borderStyle != value) { - using (LayoutTransaction.CreateTransactionIf(this.AutoSize, this.ParentInternal, this, PropertyNames.BorderStyle)) + using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.BorderStyle)) { - this.borderStyle = value; - if (!this.AutoSize) + borderStyle = value; + if (!AutoSize) { PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, true /*repositionEditingControl*/); } @@ -1317,19 +1317,19 @@ public BorderStyle BorderStyle ] public event EventHandler BorderStyleChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWBORDERSTYLECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWBORDERSTYLECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWBORDERSTYLECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWBORDERSTYLECHANGED, value); } internal int BorderWidth { get { - if (this.BorderStyle == BorderStyle.Fixed3D) + if (BorderStyle == BorderStyle.Fixed3D) { return Application.RenderWithVisualStyles ? 1 : SystemInformation.Border3DSize.Width; } - else if (this.BorderStyle == BorderStyle.FixedSingle) + else if (BorderStyle == BorderStyle.FixedSingle) { return 1; } @@ -1350,12 +1350,12 @@ protected override bool CanEnableIme Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_CanEnableIme(), this = " + this); Debug.Indent(); - if (this.ptCurrentCell.X != -1 /*&& !this.IsCurrentCellInEditMode*/ && ColumnEditable(this.ptCurrentCell.X)) + if (ptCurrentCell.X != -1 /*&& !this.IsCurrentCellInEditMode*/ && ColumnEditable(ptCurrentCell.X)) { - DataGridViewCell dataGridViewCell = this.CurrentCellInternal; + DataGridViewCell dataGridViewCell = CurrentCellInternal; Debug.Assert(dataGridViewCell != null); - if (!IsSharedCellReadOnly(dataGridViewCell, this.ptCurrentCell.Y)) + if (!IsSharedCellReadOnly(dataGridViewCell, ptCurrentCell.Y)) { canEnable = base.CanEnableIme; } @@ -1378,54 +1378,54 @@ public DataGridViewCellBorderStyle CellBorderStyle { get { - switch (this.advancedCellBorderStyle.All) + switch (advancedCellBorderStyle.All) { case DataGridViewAdvancedCellBorderStyle.NotSet: - if (this.advancedCellBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.None && - this.advancedCellBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.None) + if (advancedCellBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.None && + advancedCellBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.None) { - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - if (this.advancedCellBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.None && - this.advancedCellBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.Single) + if (advancedCellBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.None && + advancedCellBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.Single) { return DataGridViewCellBorderStyle.SingleVertical; } } else { - if (this.advancedCellBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.None && - this.advancedCellBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.Single) + if (advancedCellBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.None && + advancedCellBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.Single) { return DataGridViewCellBorderStyle.SingleVertical; } } - if (this.advancedCellBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.Outset && - this.advancedCellBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.Outset) + if (advancedCellBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.Outset && + advancedCellBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.Outset) { return DataGridViewCellBorderStyle.RaisedVertical; } - if (this.advancedCellBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.Inset && - this.advancedCellBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.Inset) + if (advancedCellBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.Inset && + advancedCellBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.Inset) { return DataGridViewCellBorderStyle.SunkenVertical; } } - if (this.advancedCellBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.None && - this.advancedCellBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.None) + if (advancedCellBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.None && + advancedCellBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.None) { - if (this.advancedCellBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.None && - this.advancedCellBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.Single) + if (advancedCellBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.None && + advancedCellBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.Single) { return DataGridViewCellBorderStyle.SingleHorizontal; } - if (this.advancedCellBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.Outset && - this.advancedCellBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.Outset) + if (advancedCellBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.Outset && + advancedCellBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.Outset) { return DataGridViewCellBorderStyle.RaisedHorizontal; } - if (this.advancedCellBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.Inset && - this.advancedCellBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.Inset) + if (advancedCellBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.Inset && + advancedCellBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.Inset) { return DataGridViewCellBorderStyle.SunkenHorizontal; } @@ -1457,78 +1457,78 @@ public DataGridViewCellBorderStyle CellBorderStyle throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewCellBorderStyle)); } - if (value != this.CellBorderStyle) + if (value != CellBorderStyle) { if (value == DataGridViewCellBorderStyle.Custom) { throw new ArgumentException(string.Format(SR.DataGridView_CustomCellBorderStyleInvalid, "CellBorderStyle")); } - this.dataGridViewOper[DATAGRIDVIEWOPER_inBorderStyleChange] = true; + dataGridViewOper[DATAGRIDVIEWOPER_inBorderStyleChange] = true; try { switch (value) { case DataGridViewCellBorderStyle.Single: - this.advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.Single; + advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.Single; break; case DataGridViewCellBorderStyle.Raised: - this.advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.Outset; + advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.Outset; break; case DataGridViewCellBorderStyle.Sunken: - this.advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.Inset; + advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.Inset; break; case DataGridViewCellBorderStyle.None: - this.advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None; + advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None; break; case DataGridViewCellBorderStyle.SingleVertical: - this.advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None; - if (this.RightToLeftInternal) + advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None; + if (RightToLeftInternal) { - this.advancedCellBorderStyle.LeftInternal = DataGridViewAdvancedCellBorderStyle.Single; + advancedCellBorderStyle.LeftInternal = DataGridViewAdvancedCellBorderStyle.Single; } else { - this.advancedCellBorderStyle.RightInternal = DataGridViewAdvancedCellBorderStyle.Single; + advancedCellBorderStyle.RightInternal = DataGridViewAdvancedCellBorderStyle.Single; } break; case DataGridViewCellBorderStyle.RaisedVertical: - this.advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None; - this.advancedCellBorderStyle.RightInternal = DataGridViewAdvancedCellBorderStyle.Outset; - this.advancedCellBorderStyle.LeftInternal = DataGridViewAdvancedCellBorderStyle.Outset; + advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None; + advancedCellBorderStyle.RightInternal = DataGridViewAdvancedCellBorderStyle.Outset; + advancedCellBorderStyle.LeftInternal = DataGridViewAdvancedCellBorderStyle.Outset; break; case DataGridViewCellBorderStyle.SunkenVertical: - this.advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None; - this.advancedCellBorderStyle.RightInternal = DataGridViewAdvancedCellBorderStyle.Inset; - this.advancedCellBorderStyle.LeftInternal = DataGridViewAdvancedCellBorderStyle.Inset; + advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None; + advancedCellBorderStyle.RightInternal = DataGridViewAdvancedCellBorderStyle.Inset; + advancedCellBorderStyle.LeftInternal = DataGridViewAdvancedCellBorderStyle.Inset; break; case DataGridViewCellBorderStyle.SingleHorizontal: - this.advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None; - this.advancedCellBorderStyle.BottomInternal = DataGridViewAdvancedCellBorderStyle.Single; + advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None; + advancedCellBorderStyle.BottomInternal = DataGridViewAdvancedCellBorderStyle.Single; break; case DataGridViewCellBorderStyle.RaisedHorizontal: - this.advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None; - this.advancedCellBorderStyle.TopInternal = DataGridViewAdvancedCellBorderStyle.Outset; - this.advancedCellBorderStyle.BottomInternal = DataGridViewAdvancedCellBorderStyle.Outset; + advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None; + advancedCellBorderStyle.TopInternal = DataGridViewAdvancedCellBorderStyle.Outset; + advancedCellBorderStyle.BottomInternal = DataGridViewAdvancedCellBorderStyle.Outset; break; case DataGridViewCellBorderStyle.SunkenHorizontal: - this.advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None; - this.advancedCellBorderStyle.TopInternal = DataGridViewAdvancedCellBorderStyle.Inset; - this.advancedCellBorderStyle.BottomInternal = DataGridViewAdvancedCellBorderStyle.Inset; + advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None; + advancedCellBorderStyle.TopInternal = DataGridViewAdvancedCellBorderStyle.Inset; + advancedCellBorderStyle.BottomInternal = DataGridViewAdvancedCellBorderStyle.Inset; break; } } finally { - this.dataGridViewOper[DATAGRIDVIEWOPER_inBorderStyleChange] = false; + dataGridViewOper[DATAGRIDVIEWOPER_inBorderStyleChange] = false; } OnCellBorderStyleChanged(EventArgs.Empty); } @@ -1541,19 +1541,19 @@ public DataGridViewCellBorderStyle CellBorderStyle ] public event EventHandler CellBorderStyleChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLBORDERSTYLECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLBORDERSTYLECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLBORDERSTYLECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLBORDERSTYLECHANGED, value); } internal bool CellMouseDownInContentBounds { get { - return this.dataGridViewState2[DATAGRIDVIEWSTATE2_cellMouseDownInContentBounds]; + return dataGridViewState2[DATAGRIDVIEWSTATE2_cellMouseDownInContentBounds]; } set { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_cellMouseDownInContentBounds] = value; + dataGridViewState2[DATAGRIDVIEWSTATE2_cellMouseDownInContentBounds] = value; } } @@ -1561,11 +1561,11 @@ internal DataGridViewCellPaintingEventArgs CellPaintingEventArgs { get { - if (this.dgvcpe == null) + if (dgvcpe == null) { - this.dgvcpe = new DataGridViewCellPaintingEventArgs(this); + dgvcpe = new DataGridViewCellPaintingEventArgs(this); } - return this.dgvcpe; + return dgvcpe; } } @@ -1573,11 +1573,11 @@ private DataGridViewCellStyleChangedEventArgs CellStyleChangedEventArgs { get { - if (this.dgvcsce == null) + if (dgvcsce == null) { - this.dgvcsce = new DataGridViewCellStyleChangedEventArgs(); + dgvcsce = new DataGridViewCellStyleChangedEventArgs(); } - return this.dgvcsce; + return dgvcsce; } } @@ -1585,11 +1585,11 @@ internal DataGridViewCellValueEventArgs CellValueEventArgs { get { - if (this.dgvcve == null) + if (dgvcve == null) { - this.dgvcve = new DataGridViewCellValueEventArgs(); + dgvcve = new DataGridViewCellValueEventArgs(); } - return this.dgvcve; + return dgvcve; } } @@ -1603,7 +1603,7 @@ public DataGridViewClipboardCopyMode ClipboardCopyMode { get { - return this.clipboardCopyMode; + return clipboardCopyMode; } set { @@ -1612,7 +1612,7 @@ public DataGridViewClipboardCopyMode ClipboardCopyMode { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewClipboardCopyMode)); } - this.clipboardCopyMode = value; + clipboardCopyMode = value; } } @@ -1626,7 +1626,7 @@ public int ColumnCount { get { - return this.Columns.Count; + return Columns.Count; } set { @@ -1634,25 +1634,25 @@ public int ColumnCount { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(ColumnCount), value, 0)); } - if (this.DataSource != null) + if (DataSource != null) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotSetColumnCountOnDataBoundDataGridView)); } - if (value != this.Columns.Count) + if (value != Columns.Count) { if (value == 0) { // Total removal of the columns. This also clears the rows. - this.Columns.Clear(); + Columns.Clear(); } - else if (value < this.Columns.Count) + else if (value < Columns.Count) { // Some columns need to be removed, from the tail of the columns collection - while (value < this.Columns.Count) + while (value < Columns.Count) { - int currentColumnCount = this.Columns.Count; - this.Columns.RemoveAt(currentColumnCount - 1); - if (this.Columns.Count >= currentColumnCount) + int currentColumnCount = Columns.Count; + Columns.RemoveAt(currentColumnCount - 1); + if (Columns.Count >= currentColumnCount) { // Column removal failed. We stop the loop. break; @@ -1662,11 +1662,11 @@ public int ColumnCount else { // Some DataGridViewTextBoxColumn columns need to be appened. - while (value > this.Columns.Count) + while (value > Columns.Count) { - int currentColumnCount = this.Columns.Count; - this.Columns.Add(null /*columnName*/, null /*headerText*/); - if (this.Columns.Count <= currentColumnCount) + int currentColumnCount = Columns.Count; + Columns.Add(null /*columnName*/, null /*headerText*/); + if (Columns.Count <= currentColumnCount) { // Column addition failed. We stop the loop. break; @@ -1687,7 +1687,7 @@ public DataGridViewHeaderBorderStyle ColumnHeadersBorderStyle { get { - switch (this.advancedColumnHeadersBorderStyle.All) + switch (advancedColumnHeadersBorderStyle.All) { case DataGridViewAdvancedCellBorderStyle.NotSet: return DataGridViewHeaderBorderStyle.Custom; @@ -1715,37 +1715,37 @@ public DataGridViewHeaderBorderStyle ColumnHeadersBorderStyle { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewHeaderBorderStyle)); } - if (value != this.ColumnHeadersBorderStyle) + if (value != ColumnHeadersBorderStyle) { if (value == DataGridViewHeaderBorderStyle.Custom) { throw new ArgumentException(string.Format(SR.DataGridView_CustomCellBorderStyleInvalid, "ColumnHeadersBorderStyle")); } - this.dataGridViewOper[DATAGRIDVIEWOPER_inBorderStyleChange] = true; + dataGridViewOper[DATAGRIDVIEWOPER_inBorderStyleChange] = true; try { switch (value) { case DataGridViewHeaderBorderStyle.Single: - this.advancedColumnHeadersBorderStyle.All = DataGridViewAdvancedCellBorderStyle.Single; + advancedColumnHeadersBorderStyle.All = DataGridViewAdvancedCellBorderStyle.Single; break; case DataGridViewHeaderBorderStyle.Raised: - this.advancedColumnHeadersBorderStyle.All = DataGridViewAdvancedCellBorderStyle.OutsetPartial; + advancedColumnHeadersBorderStyle.All = DataGridViewAdvancedCellBorderStyle.OutsetPartial; break; case DataGridViewHeaderBorderStyle.Sunken: - this.advancedColumnHeadersBorderStyle.All = DataGridViewAdvancedCellBorderStyle.InsetDouble; + advancedColumnHeadersBorderStyle.All = DataGridViewAdvancedCellBorderStyle.InsetDouble; break; case DataGridViewHeaderBorderStyle.None: - this.advancedColumnHeadersBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None; + advancedColumnHeadersBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None; break; } } finally { - this.dataGridViewOper[DATAGRIDVIEWOPER_inBorderStyleChange] = false; + dataGridViewOper[DATAGRIDVIEWOPER_inBorderStyleChange] = false; } OnColumnHeadersBorderStyleChanged(EventArgs.Empty); } @@ -1758,8 +1758,8 @@ public DataGridViewHeaderBorderStyle ColumnHeadersBorderStyle ] public event EventHandler ColumnHeadersBorderStyleChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERSBORDERSTYLECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERSBORDERSTYLECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERSBORDERSTYLECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERSBORDERSTYLECHANGED, value); } [ @@ -1771,26 +1771,26 @@ public DataGridViewCellStyle ColumnHeadersDefaultCellStyle { get { - if (this.columnHeadersDefaultCellStyle == null) + if (columnHeadersDefaultCellStyle == null) { - this.columnHeadersDefaultCellStyle = this.DefaultColumnHeadersDefaultCellStyle; + columnHeadersDefaultCellStyle = DefaultColumnHeadersDefaultCellStyle; } - return this.columnHeadersDefaultCellStyle; + return columnHeadersDefaultCellStyle; } set { - DataGridViewCellStyle cs = this.ColumnHeadersDefaultCellStyle; + DataGridViewCellStyle cs = ColumnHeadersDefaultCellStyle; cs.RemoveScope(DataGridViewCellStyleScopes.ColumnHeaders); - this.columnHeadersDefaultCellStyle = value; + columnHeadersDefaultCellStyle = value; if (value != null) { - this.columnHeadersDefaultCellStyle.AddScope(this, DataGridViewCellStyleScopes.ColumnHeaders); + columnHeadersDefaultCellStyle.AddScope(this, DataGridViewCellStyleScopes.ColumnHeaders); } - DataGridViewCellStyleDifferences dgvcsc = cs.GetDifferencesFrom(this.ColumnHeadersDefaultCellStyle); + DataGridViewCellStyleDifferences dgvcsc = cs.GetDifferencesFrom(ColumnHeadersDefaultCellStyle); if (dgvcsc != DataGridViewCellStyleDifferences.None) { - this.CellStyleChangedEventArgs.ChangeAffectsPreferredSize = (dgvcsc == DataGridViewCellStyleDifferences.AffectPreferredSize); - OnColumnHeadersDefaultCellStyleChanged(this.CellStyleChangedEventArgs); + CellStyleChangedEventArgs.ChangeAffectsPreferredSize = (dgvcsc == DataGridViewCellStyleDifferences.AffectPreferredSize); + OnColumnHeadersDefaultCellStyleChanged(CellStyleChangedEventArgs); } } } @@ -1809,7 +1809,7 @@ private DataGridViewCellStyle DefaultColumnHeadersDefaultCellStyle defaultStyle.WrapModeInternal = DataGridViewTriState.True; defaultStyle.AddScope(this, DataGridViewCellStyleScopes.ColumnHeaders); - this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientColumnHeadersFont] = true; + dataGridViewState1[DATAGRIDVIEWSTATE1_ambientColumnHeadersFont] = true; return defaultStyle; } @@ -1821,8 +1821,8 @@ private DataGridViewCellStyle DefaultColumnHeadersDefaultCellStyle ] public event EventHandler ColumnHeadersDefaultCellStyleChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERSDEFAULTCELLSTYLECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERSDEFAULTCELLSTYLECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERSDEFAULTCELLSTYLECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERSDEFAULTCELLSTYLECHANGED, value); } [ @@ -1834,7 +1834,7 @@ public int ColumnHeadersHeight { get { - return this.columnHeadersHeight; + return columnHeadersHeight; } set { @@ -1846,11 +1846,11 @@ public int ColumnHeadersHeight { throw new ArgumentOutOfRangeException(nameof(value), string.Format(SR.InvalidHighBoundArgumentEx, nameof(ColumnHeadersHeight), value, maxHeadersThickness)); } - if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) + if (ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) { - this.cachedColumnHeadersHeight = value; + cachedColumnHeadersHeight = value; } - else if (this.columnHeadersHeight != value) + else if (columnHeadersHeight != value) { SetColumnHeadersHeightInternal(value, true /*invalidInAdjustFillingColumns*/); } @@ -1863,13 +1863,13 @@ public int ColumnHeadersHeight ] public event EventHandler ColumnHeadersHeightChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERSHEIGHTCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERSHEIGHTCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERSHEIGHTCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERSHEIGHTCHANGED, value); } private bool ShouldSerializeColumnHeadersHeight() { - return this.ColumnHeadersHeightSizeMode != DataGridViewColumnHeadersHeightSizeMode.AutoSize && defaultColumnHeadersHeight != this.ColumnHeadersHeight; + return ColumnHeadersHeightSizeMode != DataGridViewColumnHeadersHeightSizeMode.AutoSize && defaultColumnHeadersHeight != ColumnHeadersHeight; } /// @@ -1887,7 +1887,7 @@ public DataGridViewColumnHeadersHeightSizeMode ColumnHeadersHeightSizeMode { get { - return this.columnHeadersHeightSizeMode; + return columnHeadersHeightSizeMode; } set { @@ -1896,14 +1896,14 @@ public DataGridViewColumnHeadersHeightSizeMode ColumnHeadersHeightSizeMode { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewColumnHeadersHeightSizeMode)); } - if (this.columnHeadersHeightSizeMode != value) + if (columnHeadersHeightSizeMode != value) { /*if (value == DataGridViewColumnHeadersHeightSizeMode.AutoSize && !this.ColumnHeadersVisible) { We intentionally don't throw an error because of designer code spit order. }*/ - DataGridViewAutoSizeModeEventArgs dgvasme = new DataGridViewAutoSizeModeEventArgs(this.columnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize); - this.columnHeadersHeightSizeMode = value; + DataGridViewAutoSizeModeEventArgs dgvasme = new DataGridViewAutoSizeModeEventArgs(columnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize); + columnHeadersHeightSizeMode = value; OnColumnHeadersHeightSizeModeChanged(dgvasme); } } @@ -1915,8 +1915,8 @@ public DataGridViewColumnHeadersHeightSizeMode ColumnHeadersHeightSizeMode ] public event DataGridViewAutoSizeModeEventHandler ColumnHeadersHeightSizeModeChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERSHEIGHTSIZEMODECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERSHEIGHTSIZEMODECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERSHEIGHTSIZEMODECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERSHEIGHTSIZEMODECHANGED, value); } /// @@ -1944,33 +1944,33 @@ public bool ColumnHeadersVisible { get { - return this.dataGridViewState1[DATAGRIDVIEWSTATE1_columnHeadersVisible]; + return dataGridViewState1[DATAGRIDVIEWSTATE1_columnHeadersVisible]; } set { - if (this.ColumnHeadersVisible != value) + if (ColumnHeadersVisible != value) { if (!value) { // Make sure that there is no visible column that only counts on the column headers to autosize - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); while (dataGridViewColumn != null) { if (dataGridViewColumn.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.ColumnHeader) { throw new InvalidOperationException(string.Format(SR.DataGridView_ColumnHeadersCannotBeInvisible)); } - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); } } - using (LayoutTransaction.CreateTransactionIf(this.AutoSize, this.ParentInternal, this, PropertyNames.ColumnHeadersVisible)) + using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.ColumnHeadersVisible)) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_columnHeadersVisible] = value; - this.layout.ColumnHeadersVisible = value; - this.displayedBandsInfo.EnsureDirtyState(); - if (!this.AutoSize) + dataGridViewState1[DATAGRIDVIEWSTATE1_columnHeadersVisible] = value; + layout.ColumnHeadersVisible = value; + displayedBandsInfo.EnsureDirtyState(); + if (!AutoSize) { PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, true /*repositionEditingControl*/); } @@ -1990,11 +1990,11 @@ public DataGridViewColumnCollection Columns { get { - if (this.dataGridViewColumns == null) + if (dataGridViewColumns == null) { - this.dataGridViewColumns = CreateColumnsInstance(); + dataGridViewColumns = CreateColumnsInstance(); } - return this.dataGridViewColumns; + return dataGridViewColumns; } } @@ -2006,20 +2006,20 @@ public DataGridViewCell CurrentCell { get { - if (this.ptCurrentCell.X == -1 && this.ptCurrentCell.Y == -1) + if (ptCurrentCell.X == -1 && ptCurrentCell.Y == -1) { return null; } - Debug.Assert(this.ptCurrentCell.X >= 0 && ptCurrentCell.Y >= 0); - Debug.Assert(this.ptCurrentCell.X < this.Columns.Count); - Debug.Assert(this.ptCurrentCell.Y < this.Rows.Count); - DataGridViewRow dataGridViewRow = (DataGridViewRow)this.Rows[this.ptCurrentCell.Y]; // unsharing row - return dataGridViewRow.Cells[this.ptCurrentCell.X]; + Debug.Assert(ptCurrentCell.X >= 0 && ptCurrentCell.Y >= 0); + Debug.Assert(ptCurrentCell.X < Columns.Count); + Debug.Assert(ptCurrentCell.Y < Rows.Count); + DataGridViewRow dataGridViewRow = (DataGridViewRow)Rows[ptCurrentCell.Y]; // unsharing row + return dataGridViewRow.Cells[ptCurrentCell.X]; } set { - if ((value != null && (value.RowIndex != this.ptCurrentCell.Y || value.ColumnIndex != this.ptCurrentCell.X)) || - (value == null && this.ptCurrentCell.X != -1)) + if ((value != null && (value.RowIndex != ptCurrentCell.Y || value.ColumnIndex != ptCurrentCell.X)) || + (value == null && ptCurrentCell.X != -1)) { if (value == null) { @@ -2036,8 +2036,8 @@ public DataGridViewCell CurrentCell { throw new ArgumentException(string.Format(SR.DataGridView_CellDoesNotBelongToDataGridView)); } - if (!this.Columns[value.ColumnIndex].Visible || - (this.Rows.GetRowState(value.RowIndex) & DataGridViewElementStates.Visible) == 0) + if (!Columns[value.ColumnIndex].Visible || + (Rows.GetRowState(value.RowIndex) & DataGridViewElementStates.Visible) == 0) { throw new InvalidOperationException(string.Format(SR.DataGridView_CurrentCellCannotBeInvisible)); } @@ -2066,7 +2066,7 @@ public Point CurrentCellAddress { get { - return this.ptCurrentCell; + return ptCurrentCell; } } @@ -2074,12 +2074,12 @@ private DataGridViewCell CurrentCellInternal { get { - Debug.Assert(this.ptCurrentCell.X >= 0 && this.ptCurrentCell.X < this.Columns.Count); - Debug.Assert(this.ptCurrentCell.Y >= 0 && this.ptCurrentCell.Y < this.Rows.Count); - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(this.ptCurrentCell.Y); + Debug.Assert(ptCurrentCell.X >= 0 && ptCurrentCell.X < Columns.Count); + Debug.Assert(ptCurrentCell.Y >= 0 && ptCurrentCell.Y < Rows.Count); + DataGridViewRow dataGridViewRow = Rows.SharedRow(ptCurrentCell.Y); Debug.Assert(dataGridViewRow != null); - DataGridViewCell dataGridViewCell = dataGridViewRow.Cells[this.ptCurrentCell.X]; - Debug.Assert(this.IsSharedCellVisible(dataGridViewCell, this.ptCurrentCell.Y)); + DataGridViewCell dataGridViewCell = dataGridViewRow.Cells[ptCurrentCell.X]; + Debug.Assert(IsSharedCellVisible(dataGridViewCell, ptCurrentCell.Y)); return dataGridViewCell; } } @@ -2088,14 +2088,14 @@ private bool CurrentCellIsFirstVisibleCell { get { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { return false; } - Debug.Assert(this.ptCurrentCell.Y != -1); + Debug.Assert(ptCurrentCell.Y != -1); - bool previousVisibleColumnExists = (null != this.Columns.GetPreviousColumn(this.Columns[this.ptCurrentCell.X], DataGridViewElementStates.Visible, DataGridViewElementStates.None)); - bool previousVisibleRowExists = (-1 != this.Rows.GetPreviousRow(this.ptCurrentCell.Y, DataGridViewElementStates.Visible)); + bool previousVisibleColumnExists = (null != Columns.GetPreviousColumn(Columns[ptCurrentCell.X], DataGridViewElementStates.Visible, DataGridViewElementStates.None)); + bool previousVisibleRowExists = (-1 != Rows.GetPreviousRow(ptCurrentCell.Y, DataGridViewElementStates.Visible)); return !previousVisibleColumnExists && !previousVisibleRowExists; } @@ -2105,15 +2105,15 @@ private bool CurrentCellIsLastVisibleCell { get { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { return false; } - Debug.Assert(this.ptCurrentCell.Y != -1); + Debug.Assert(ptCurrentCell.Y != -1); - bool nextVisibleColumnExists = (null != this.Columns.GetNextColumn(this.Columns[this.ptCurrentCell.X], DataGridViewElementStates.Visible, DataGridViewElementStates.None)); - bool nextVisibleRowExists = (-1 != this.Rows.GetNextRow(this.ptCurrentCell.Y, DataGridViewElementStates.Visible)); + bool nextVisibleColumnExists = (null != Columns.GetNextColumn(Columns[ptCurrentCell.X], DataGridViewElementStates.Visible, DataGridViewElementStates.None)); + bool nextVisibleRowExists = (-1 != Rows.GetNextRow(ptCurrentCell.Y, DataGridViewElementStates.Visible)); return !nextVisibleColumnExists && !nextVisibleRowExists; } @@ -2123,16 +2123,16 @@ private bool CurrentCellIsEditedAndOnlySelectedCell { get { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { return false; } - Debug.Assert(this.ptCurrentCell.Y != -1); + Debug.Assert(ptCurrentCell.Y != -1); - return this.editingControl != null && + return editingControl != null && GetCellCount(DataGridViewElementStates.Selected) == 1 && - this.CurrentCellInternal.Selected; + CurrentCellInternal.Selected; } } @@ -2143,15 +2143,15 @@ public DataGridViewRow CurrentRow { get { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { return null; } - Debug.Assert(this.ptCurrentCell.Y >= 0); - Debug.Assert(this.ptCurrentCell.Y < this.Rows.Count); + Debug.Assert(ptCurrentCell.Y >= 0); + Debug.Assert(ptCurrentCell.Y < Rows.Count); - return this.Rows[this.ptCurrentCell.Y]; + return Rows[ptCurrentCell.Y]; } } @@ -2159,14 +2159,14 @@ internal Cursor CursorInternal { set { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_ignoreCursorChange] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_ignoreCursorChange] = true; try { - this.Cursor = value; + Cursor = value; } finally { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_ignoreCursorChange] = false; + dataGridViewState2[DATAGRIDVIEWSTATE2_ignoreCursorChange] = false; } } } @@ -2175,7 +2175,7 @@ internal DataGridViewDataConnection DataConnection { get { - return this.dataConnection; + return dataConnection; } } @@ -2189,25 +2189,25 @@ public string DataMember { get { - if (this.dataConnection == null) + if (dataConnection == null) { return string.Empty; } else { - return this.dataConnection.DataMember; + return dataConnection.DataMember; } } set { - if (value != this.DataMember) + if (value != DataMember) { - this.CurrentCell = null; - if (this.dataConnection == null) + CurrentCell = null; + if (dataConnection == null) { - this.dataConnection = new DataGridViewDataConnection(this); + dataConnection = new DataGridViewDataConnection(this); } - this.dataConnection.SetDataConnection(this.DataSource, value); + dataConnection.SetDataConnection(DataSource, value); OnDataMemberChanged(EventArgs.Empty); } } @@ -2219,8 +2219,8 @@ public string DataMember ] public event EventHandler DataMemberChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWDATAMEMBERCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWDATAMEMBERCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWDATAMEMBERCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWDATAMEMBERCHANGED, value); } [ @@ -2234,36 +2234,36 @@ public object DataSource { get { - if (this.dataConnection == null) + if (dataConnection == null) { return null; } else { - return this.dataConnection.DataSource; + return dataConnection.DataSource; } } set { - if (value != this.DataSource) + if (value != DataSource) { - this.CurrentCell = null; - if (this.dataConnection == null) + CurrentCell = null; + if (dataConnection == null) { - this.dataConnection = new DataGridViewDataConnection(this); - this.dataConnection.SetDataConnection(value, this.DataMember); + dataConnection = new DataGridViewDataConnection(this); + dataConnection.SetDataConnection(value, DataMember); } else { - if (this.dataConnection.ShouldChangeDataMember(value)) + if (dataConnection.ShouldChangeDataMember(value)) { // we fire DataMemberChanged event - this.DataMember = string.Empty; + DataMember = string.Empty; } - this.dataConnection.SetDataConnection(value, this.DataMember); + dataConnection.SetDataConnection(value, DataMember); if (value == null) { - this.dataConnection = null; + dataConnection = null; } } OnDataSourceChanged(EventArgs.Empty); @@ -2277,8 +2277,8 @@ public object DataSource ] public event EventHandler DataSourceChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWDATASOURCECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWDATASOURCECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWDATASOURCECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWDATASOURCECHANGED, value); } private static SolidBrush DefaultBackBrush @@ -2306,48 +2306,48 @@ public DataGridViewCellStyle DefaultCellStyle { get { - if (this.defaultCellStyle == null) + if (defaultCellStyle == null) { - this.defaultCellStyle = this.DefaultDefaultCellStyle; - return this.defaultCellStyle; + defaultCellStyle = DefaultDefaultCellStyle; + return defaultCellStyle; } - else if (this.defaultCellStyle.BackColor == Color.Empty || - this.defaultCellStyle.ForeColor == Color.Empty || - this.defaultCellStyle.SelectionBackColor == Color.Empty || - this.defaultCellStyle.SelectionForeColor == Color.Empty || - this.defaultCellStyle.Font == null || - this.defaultCellStyle.Alignment == DataGridViewContentAlignment.NotSet || - this.defaultCellStyle.WrapMode == DataGridViewTriState.NotSet) + else if (defaultCellStyle.BackColor == Color.Empty || + defaultCellStyle.ForeColor == Color.Empty || + defaultCellStyle.SelectionBackColor == Color.Empty || + defaultCellStyle.SelectionForeColor == Color.Empty || + defaultCellStyle.Font == null || + defaultCellStyle.Alignment == DataGridViewContentAlignment.NotSet || + defaultCellStyle.WrapMode == DataGridViewTriState.NotSet) { - DataGridViewCellStyle defaultCellStyleTmp = new DataGridViewCellStyle(this.defaultCellStyle); + DataGridViewCellStyle defaultCellStyleTmp = new DataGridViewCellStyle(defaultCellStyle); defaultCellStyleTmp.Scope = DataGridViewCellStyleScopes.None; - if (this.defaultCellStyle.BackColor == Color.Empty) + if (defaultCellStyle.BackColor == Color.Empty) { defaultCellStyleTmp.BackColor = DefaultBackBrush.Color; } - if (this.defaultCellStyle.ForeColor == Color.Empty) + if (defaultCellStyle.ForeColor == Color.Empty) { defaultCellStyleTmp.ForeColor = base.ForeColor; - this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientForeColor] = true; + dataGridViewState1[DATAGRIDVIEWSTATE1_ambientForeColor] = true; } - if (this.defaultCellStyle.SelectionBackColor == Color.Empty) + if (defaultCellStyle.SelectionBackColor == Color.Empty) { defaultCellStyleTmp.SelectionBackColor = DefaultSelectionBackBrush.Color; } - if (this.defaultCellStyle.SelectionForeColor == Color.Empty) + if (defaultCellStyle.SelectionForeColor == Color.Empty) { defaultCellStyleTmp.SelectionForeColor = DefaultSelectionForeBrush.Color; } - if (this.defaultCellStyle.Font == null) + if (defaultCellStyle.Font == null) { defaultCellStyleTmp.Font = base.Font; - this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientFont] = true; + dataGridViewState1[DATAGRIDVIEWSTATE1_ambientFont] = true; } - if (this.defaultCellStyle.Alignment == DataGridViewContentAlignment.NotSet) + if (defaultCellStyle.Alignment == DataGridViewContentAlignment.NotSet) { defaultCellStyleTmp.AlignmentInternal = DataGridViewContentAlignment.MiddleLeft; } - if (this.defaultCellStyle.WrapMode == DataGridViewTriState.NotSet) + if (defaultCellStyle.WrapMode == DataGridViewTriState.NotSet) { defaultCellStyleTmp.WrapModeInternal = DataGridViewTriState.False; } @@ -2356,23 +2356,23 @@ public DataGridViewCellStyle DefaultCellStyle } else { - return this.defaultCellStyle; + return defaultCellStyle; } } set { - DataGridViewCellStyle cs = this.DefaultCellStyle; + DataGridViewCellStyle cs = DefaultCellStyle; cs.RemoveScope(DataGridViewCellStyleScopes.DataGridView); - this.defaultCellStyle = value; + defaultCellStyle = value; if (value != null) { - this.defaultCellStyle.AddScope(this, DataGridViewCellStyleScopes.DataGridView); + defaultCellStyle.AddScope(this, DataGridViewCellStyleScopes.DataGridView); } - DataGridViewCellStyleDifferences dgvcsc = cs.GetDifferencesFrom(this.DefaultCellStyle); + DataGridViewCellStyleDifferences dgvcsc = cs.GetDifferencesFrom(DefaultCellStyle); if (dgvcsc != DataGridViewCellStyleDifferences.None) { - this.CellStyleChangedEventArgs.ChangeAffectsPreferredSize = (dgvcsc == DataGridViewCellStyleDifferences.AffectPreferredSize); - OnDefaultCellStyleChanged(this.CellStyleChangedEventArgs); + CellStyleChangedEventArgs.ChangeAffectsPreferredSize = (dgvcsc == DataGridViewCellStyleDifferences.AffectPreferredSize); + OnDefaultCellStyleChanged(CellStyleChangedEventArgs); } } } @@ -2391,8 +2391,8 @@ private DataGridViewCellStyle DefaultDefaultCellStyle defaultCellStyle.WrapModeInternal = DataGridViewTriState.False; defaultCellStyle.AddScope(this, DataGridViewCellStyleScopes.DataGridView); - this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientFont] = true; - this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientForeColor] = true; + dataGridViewState1[DATAGRIDVIEWSTATE1_ambientFont] = true; + dataGridViewState1[DATAGRIDVIEWSTATE1_ambientForeColor] = true; return defaultCellStyle; } @@ -2404,8 +2404,8 @@ private DataGridViewCellStyle DefaultDefaultCellStyle ] public event EventHandler DefaultCellStyleChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWDEFAULTCELLSTYLECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWDEFAULTCELLSTYLECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWDEFAULTCELLSTYLECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWDEFAULTCELLSTYLECHANGED, value); } private static SolidBrush DefaultForeBrush @@ -2446,7 +2446,7 @@ private DataGridViewCellStyle DefaultRowHeadersDefaultCellStyle defaultStyle.WrapModeInternal = DataGridViewTriState.True; defaultStyle.AddScope(this, DataGridViewCellStyleScopes.RowHeaders); - this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientRowHeadersFont] = true; + dataGridViewState1[DATAGRIDVIEWSTATE1_ambientRowHeadersFont] = true; return defaultStyle; } @@ -2480,7 +2480,7 @@ internal DisplayedBandsData DisplayedBandsInfo { get { - return this.displayedBandsInfo; + return displayedBandsInfo; } } @@ -2492,17 +2492,17 @@ public override Rectangle DisplayRectangle { get { - Rectangle rectDisplay = this.ClientRectangle; - if (this.horizScrollBar != null && this.horizScrollBar.Visible) + Rectangle rectDisplay = ClientRectangle; + if (horizScrollBar != null && horizScrollBar.Visible) { - rectDisplay.Height -= this.horizScrollBar.Height; + rectDisplay.Height -= horizScrollBar.Height; } - if (this.vertScrollBar != null && this.vertScrollBar.Visible) + if (vertScrollBar != null && vertScrollBar.Visible) { - rectDisplay.Width -= this.vertScrollBar.Width; - if (this.RightToLeftInternal) + rectDisplay.Width -= vertScrollBar.Width; + if (RightToLeftInternal) { - rectDisplay.X = this.vertScrollBar.Width; + rectDisplay.X = vertScrollBar.Width; } } return rectDisplay; @@ -2518,7 +2518,7 @@ public DataGridViewEditMode EditMode { get { - return this.editMode; + return editMode; } set { @@ -2527,9 +2527,9 @@ public DataGridViewEditMode EditMode { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewEditMode)); } - if (this.editMode != value) + if (editMode != value) { - this.editMode = value; + editMode = value; OnEditModeChanged(EventArgs.Empty); } } @@ -2541,15 +2541,15 @@ public DataGridViewEditMode EditMode ] public event EventHandler EditModeChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWEDITMODECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWEDITMODECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWEDITMODECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWEDITMODECHANGED, value); } internal Point MouseEnteredCellAddress { get { - return this.ptMouseEnteredCell; + return ptMouseEnteredCell; } } @@ -2557,10 +2557,10 @@ private bool MouseOverEditingControl { get { - if (this.editingControl != null) + if (editingControl != null) { Point ptMouse = PointToClient(Control.MousePosition); - return this.editingControl.Bounds.Contains(ptMouse); + return editingControl.Bounds.Contains(ptMouse); } return false; } @@ -2570,10 +2570,10 @@ private bool MouseOverEditingPanel { get { - if (this.editingPanel != null) + if (editingPanel != null) { Point ptMouse = PointToClient(Control.MousePosition); - return this.editingPanel.Bounds.Contains(ptMouse); + return editingPanel.Bounds.Contains(ptMouse); } return false; } @@ -2584,16 +2584,16 @@ private bool MouseOverScrollBar get { Point ptMouse = PointToClient(Control.MousePosition); - if (this.vertScrollBar != null && this.vertScrollBar.Visible) + if (vertScrollBar != null && vertScrollBar.Visible) { - if (this.vertScrollBar.Bounds.Contains(ptMouse)) + if (vertScrollBar.Bounds.Contains(ptMouse)) { return true; } } - if (this.horizScrollBar != null && this.horizScrollBar.Visible) + if (horizScrollBar != null && horizScrollBar.Visible) { - return this.horizScrollBar.Bounds.Contains(ptMouse); + return horizScrollBar.Bounds.Contains(ptMouse); } return false; } @@ -2607,7 +2607,7 @@ public Control EditingControl { get { - return this.editingControl; + return editingControl; } } @@ -2627,12 +2627,12 @@ public Panel EditingPanel { get { - if (this.editingPanel == null) + if (editingPanel == null) { - this.editingPanel = new DataGridViewEditingPanel(this); - this.editingPanel.AccessibleName = string.Format(SR.DataGridView_AccEditingPanelAccName); + editingPanel = new DataGridViewEditingPanel(this); + editingPanel.AccessibleName = string.Format(SR.DataGridView_AccEditingPanelAccName); } - return this.editingPanel; + return editingPanel; } } @@ -2640,9 +2640,9 @@ internal DataGridViewEditingPanelAccessibleObject EditingPanelAccessibleObject { get { - if (this.editingPanelAccessibleObject == null) + if (editingPanelAccessibleObject == null) { - editingPanelAccessibleObject = new DataGridViewEditingPanelAccessibleObject(this, this.EditingPanel); + editingPanelAccessibleObject = new DataGridViewEditingPanelAccessibleObject(this, EditingPanel); } return editingPanelAccessibleObject; @@ -2664,13 +2664,13 @@ public bool EnableHeadersVisualStyles { get { - return this.dataGridViewState2[DATAGRIDVIEWSTATE2_enableHeadersVisualStyles]; + return dataGridViewState2[DATAGRIDVIEWSTATE2_enableHeadersVisualStyles]; } set { - if (this.dataGridViewState2[DATAGRIDVIEWSTATE2_enableHeadersVisualStyles] != value) + if (dataGridViewState2[DATAGRIDVIEWSTATE2_enableHeadersVisualStyles] != value) { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_enableHeadersVisualStyles] = value; + dataGridViewState2[DATAGRIDVIEWSTATE2_enableHeadersVisualStyles] = value; //OnEnableHeadersVisualStylesChanged(EventArgs.Empty); // Some autosizing may have to be applied since the margins are potentially changed. OnGlobalAutoSize(); // Put this into OnEnableHeadersVisualStylesChanged if created. @@ -2686,10 +2686,10 @@ public DataGridViewCell FirstDisplayedCell { get { - Point firstDisplayedCellAddress = this.FirstDisplayedCellAddress; + Point firstDisplayedCellAddress = FirstDisplayedCellAddress; if (firstDisplayedCellAddress.X >= 0) { - return this.Rows[firstDisplayedCellAddress.Y].Cells[firstDisplayedCellAddress.X]; // unshares the row of first displayed cell + return Rows[firstDisplayedCellAddress.Y].Cells[firstDisplayedCellAddress.X]; // unshares the row of first displayed cell } return null; } @@ -2708,9 +2708,9 @@ public DataGridViewCell FirstDisplayedCell } Debug.Assert(firstDisplayedCell.RowIndex >= 0 && - firstDisplayedCell.RowIndex < this.Rows.Count && + firstDisplayedCell.RowIndex < Rows.Count && firstDisplayedCell.ColumnIndex >= 0 && - firstDisplayedCell.ColumnIndex < this.Columns.Count); + firstDisplayedCell.ColumnIndex < Columns.Count); if (!firstDisplayedCell.Visible) { @@ -2719,14 +2719,14 @@ public DataGridViewCell FirstDisplayedCell if (!firstDisplayedCell.Frozen) { - if (!this.Rows[firstDisplayedCell.RowIndex].Frozen) + if (!Rows[firstDisplayedCell.RowIndex].Frozen) { - this.FirstDisplayedScrollingRowIndex = firstDisplayedCell.RowIndex; + FirstDisplayedScrollingRowIndex = firstDisplayedCell.RowIndex; } - if (!this.Columns[firstDisplayedCell.ColumnIndex].Frozen) + if (!Columns[firstDisplayedCell.ColumnIndex].Frozen) { - this.FirstDisplayedScrollingColumnIndex = firstDisplayedCell.ColumnIndex; + FirstDisplayedScrollingColumnIndex = firstDisplayedCell.ColumnIndex; } } } @@ -2738,26 +2738,26 @@ private Point FirstDisplayedCellAddress get { Point ptFirstDisplayedCellAddress = new Point(-1, -1); - ptFirstDisplayedCellAddress.Y = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + ptFirstDisplayedCellAddress.Y = Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); if (ptFirstDisplayedCellAddress.Y == -1) { - Debug.Assert(this.displayedBandsInfo.NumTotallyDisplayedFrozenRows == 0); - if (this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0) + Debug.Assert(displayedBandsInfo.NumTotallyDisplayedFrozenRows == 0); + if (displayedBandsInfo.FirstDisplayedScrollingRow >= 0) { - ptFirstDisplayedCellAddress.Y = this.displayedBandsInfo.FirstDisplayedScrollingRow; + ptFirstDisplayedCellAddress.Y = displayedBandsInfo.FirstDisplayedScrollingRow; } #if DEBUG else { - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow == -1); - Debug.Assert(this.displayedBandsInfo.NumDisplayedScrollingRows == 0); - Debug.Assert(this.displayedBandsInfo.NumTotallyDisplayedScrollingRows == 0); + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingRow == -1); + Debug.Assert(displayedBandsInfo.NumDisplayedScrollingRows == 0); + Debug.Assert(displayedBandsInfo.NumTotallyDisplayedScrollingRows == 0); } #endif } if (ptFirstDisplayedCellAddress.Y >= 0) { - ptFirstDisplayedCellAddress.X = this.FirstDisplayedColumnIndex; + ptFirstDisplayedCellAddress.X = FirstDisplayedColumnIndex; } return ptFirstDisplayedCellAddress; } @@ -2767,44 +2767,44 @@ internal int FirstDisplayedColumnIndex { get { - if (!this.IsHandleCreated) + if (!IsHandleCreated) { return -1; } int firstDisplayedColumnIndex = -1; - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); if (dataGridViewColumn != null) { if (dataGridViewColumn.Frozen) { firstDisplayedColumnIndex = dataGridViewColumn.Index; } - else if (this.displayedBandsInfo.FirstDisplayedScrollingCol >= 0) + else if (displayedBandsInfo.FirstDisplayedScrollingCol >= 0) { - firstDisplayedColumnIndex = this.displayedBandsInfo.FirstDisplayedScrollingCol; + firstDisplayedColumnIndex = displayedBandsInfo.FirstDisplayedScrollingCol; } } #if DEBUG - DataGridViewColumn dataGridViewColumnDbg1 = this.Columns.GetFirstColumn(DataGridViewElementStates.Displayed); + DataGridViewColumn dataGridViewColumnDbg1 = Columns.GetFirstColumn(DataGridViewElementStates.Displayed); int firstDisplayedColumnIndexDbg1 = (dataGridViewColumnDbg1 == null) ? -1 : dataGridViewColumnDbg1.Index; int firstDisplayedColumnIndexDbg2 = -1; - DataGridViewColumn dataGridViewColumnDbg = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + DataGridViewColumn dataGridViewColumnDbg = Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); if (dataGridViewColumnDbg != null) { firstDisplayedColumnIndexDbg2 = dataGridViewColumnDbg.Index; } - else if (this.displayedBandsInfo.FirstDisplayedScrollingCol >= 0) + else if (displayedBandsInfo.FirstDisplayedScrollingCol >= 0) { - firstDisplayedColumnIndexDbg2 = this.displayedBandsInfo.FirstDisplayedScrollingCol; + firstDisplayedColumnIndexDbg2 = displayedBandsInfo.FirstDisplayedScrollingCol; } else { - Debug.Assert(this.displayedBandsInfo.LastTotallyDisplayedScrollingCol == -1); + Debug.Assert(displayedBandsInfo.LastTotallyDisplayedScrollingCol == -1); } - Debug.Assert(firstDisplayedColumnIndex == firstDisplayedColumnIndexDbg1 || !this.Visible || this.displayedBandsInfo.Dirty); - Debug.Assert(firstDisplayedColumnIndex == firstDisplayedColumnIndexDbg2 || this.displayedBandsInfo.Dirty); + Debug.Assert(firstDisplayedColumnIndex == firstDisplayedColumnIndexDbg1 || !Visible || displayedBandsInfo.Dirty); + Debug.Assert(firstDisplayedColumnIndex == firstDisplayedColumnIndexDbg2 || displayedBandsInfo.Dirty); #endif return firstDisplayedColumnIndex; } @@ -2814,18 +2814,18 @@ internal int FirstDisplayedRowIndex { get { - if (!this.IsHandleCreated) + if (!IsHandleCreated) { return -1; } - int firstDisplayedRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + int firstDisplayedRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); if (firstDisplayedRowIndex != -1) { - if ((this.Rows.GetRowState(firstDisplayedRowIndex) & DataGridViewElementStates.Frozen) == 0 && - this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0) + if ((Rows.GetRowState(firstDisplayedRowIndex) & DataGridViewElementStates.Frozen) == 0 && + displayedBandsInfo.FirstDisplayedScrollingRow >= 0) { - firstDisplayedRowIndex = this.displayedBandsInfo.FirstDisplayedScrollingRow; + firstDisplayedRowIndex = displayedBandsInfo.FirstDisplayedScrollingRow; } } #if FALSE //DEBUG @@ -2856,7 +2856,7 @@ public int FirstDisplayedScrollingColumnHiddenWidth { get { - return this.negOffset; + return negOffset; } } @@ -2868,47 +2868,47 @@ public int FirstDisplayedScrollingColumnIndex { get { - return this.displayedBandsInfo.FirstDisplayedScrollingCol; + return displayedBandsInfo.FirstDisplayedScrollingCol; } set { - if (value < 0 || value >= this.Columns.Count) + if (value < 0 || value >= Columns.Count) { throw new ArgumentOutOfRangeException(nameof(value)); } - if (!this.Columns[value].Visible) + if (!Columns[value].Visible) { throw new InvalidOperationException(string.Format(SR.DataGridView_FirstDisplayedScrollingColumnCannotBeInvisible)); } - if (this.Columns[value].Frozen) + if (Columns[value].Frozen) { throw new InvalidOperationException(string.Format(SR.DataGridView_FirstDisplayedScrollingColumnCannotBeFrozen)); } - if (!this.IsHandleCreated) + if (!IsHandleCreated) { CreateHandle(); } - int displayWidth = this.layout.Data.Width; + int displayWidth = layout.Data.Width; if (displayWidth <= 0) { throw new InvalidOperationException(string.Format(SR.DataGridView_NoRoomForDisplayedColumns)); } - int totalVisibleFrozenWidth = this.Columns.GetColumnsWidth(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int totalVisibleFrozenWidth = Columns.GetColumnsWidth(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); if (totalVisibleFrozenWidth >= displayWidth) { Debug.Assert(totalVisibleFrozenWidth > 0); throw new InvalidOperationException(string.Format(SR.DataGridView_FrozenColumnsPreventFirstDisplayedScrollingColumn)); } - if (value == this.displayedBandsInfo.FirstDisplayedScrollingCol) + if (value == displayedBandsInfo.FirstDisplayedScrollingCol) { return; } - if (this.ptCurrentCell.X >= 0 && + if (ptCurrentCell.X >= 0 && !CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, false /*forCurrentCellChange*/, false /*forCurrentRowChange*/)) { @@ -2923,12 +2923,12 @@ public int FirstDisplayedScrollingColumnIndex bool success = ScrollColumnIntoView(value, -1, /*committed*/ true, false /*forCurrentCellChange*/); Debug.Assert(success); - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingCol >= 0); - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingCol == value || - this.Columns.DisplayInOrder(this.displayedBandsInfo.FirstDisplayedScrollingCol, value)); - int maxHorizontalOffset = this.Columns.GetColumnsWidth(DataGridViewElementStates.Visible) - displayWidth; - while (this.displayedBandsInfo.FirstDisplayedScrollingCol != value && - this.HorizontalOffset < maxHorizontalOffset) + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingCol >= 0); + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingCol == value || + Columns.DisplayInOrder(displayedBandsInfo.FirstDisplayedScrollingCol, value)); + int maxHorizontalOffset = Columns.GetColumnsWidth(DataGridViewElementStates.Visible) - displayWidth; + while (displayedBandsInfo.FirstDisplayedScrollingCol != value && + HorizontalOffset < maxHorizontalOffset) { ScrollColumns(1); } @@ -2943,47 +2943,47 @@ public int FirstDisplayedScrollingRowIndex { get { - return this.displayedBandsInfo.FirstDisplayedScrollingRow; + return displayedBandsInfo.FirstDisplayedScrollingRow; } set { - if (value < 0 || value >= this.Rows.Count) + if (value < 0 || value >= Rows.Count) { throw new ArgumentOutOfRangeException(nameof(value)); } - if ((this.Rows.GetRowState(value) & DataGridViewElementStates.Visible) == 0) + if ((Rows.GetRowState(value) & DataGridViewElementStates.Visible) == 0) { throw new InvalidOperationException(string.Format(SR.DataGridView_FirstDisplayedScrollingRowCannotBeInvisible)); } - if ((this.Rows.GetRowState(value) & DataGridViewElementStates.Frozen) != 0) + if ((Rows.GetRowState(value) & DataGridViewElementStates.Frozen) != 0) { throw new InvalidOperationException(string.Format(SR.DataGridView_FirstDisplayedScrollingRowCannotBeFrozen)); } - if (!this.IsHandleCreated) + if (!IsHandleCreated) { CreateHandle(); } - int displayHeight = this.layout.Data.Height; + int displayHeight = layout.Data.Height; if (displayHeight <= 0) { throw new InvalidOperationException(string.Format(SR.DataGridView_NoRoomForDisplayedRows)); } - int totalVisibleFrozenHeight = this.Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int totalVisibleFrozenHeight = Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); if (totalVisibleFrozenHeight >= displayHeight) { Debug.Assert(totalVisibleFrozenHeight > 0); throw new InvalidOperationException(string.Format(SR.DataGridView_FrozenRowsPreventFirstDisplayedScrollingRow)); } - if (value == this.displayedBandsInfo.FirstDisplayedScrollingRow) + if (value == displayedBandsInfo.FirstDisplayedScrollingRow) { return; } - if (this.ptCurrentCell.X >= 0 && + if (ptCurrentCell.X >= 0 && !CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, false /*forCurrentCellChange*/, false /*forCurrentRowChange*/)) { @@ -2996,11 +2996,11 @@ public int FirstDisplayedScrollingRowIndex return; } - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0); + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingRow >= 0); - if (value > this.displayedBandsInfo.FirstDisplayedScrollingRow) + if (value > displayedBandsInfo.FirstDisplayedScrollingRow) { - int rowsToScroll = this.Rows.GetRowCount(DataGridViewElementStates.Visible, this.displayedBandsInfo.FirstDisplayedScrollingRow, value); + int rowsToScroll = Rows.GetRowCount(DataGridViewElementStates.Visible, displayedBandsInfo.FirstDisplayedScrollingRow, value); Debug.Assert(rowsToScroll != 0); ScrollRowsByCount(rowsToScroll, rowsToScroll > 1 ? ScrollEventType.LargeIncrement : ScrollEventType.SmallIncrement); } @@ -3076,7 +3076,7 @@ public Color GridColor { get { - return this.gridPen.Color; + return gridPen.Color; } set { @@ -3088,14 +3088,14 @@ public Color GridColor { throw new ArgumentException(string.Format(SR.DataGridView_TransparentColor, "GridColor")); } - if (!value.Equals(this.gridPen.Color)) + if (!value.Equals(gridPen.Color)) { - if (this.gridPen != null) + if (gridPen != null) { - this.gridPen.Dispose(); + gridPen.Dispose(); } - this.gridPen = new Pen(value); + gridPen = new Pen(value); OnGridColorChanged(EventArgs.Empty); } } @@ -3107,20 +3107,20 @@ public Color GridColor ] public event EventHandler GridColorChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWGRIDCOLORCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWGRIDCOLORCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWGRIDCOLORCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWGRIDCOLORCHANGED, value); } private bool ShouldSerializeGridColor() { - return !this.GridPen.Color.Equals(DefaultGridColor); + return !GridPen.Color.Equals(DefaultGridColor); } internal Pen GridPen { get { - return this.gridPen; + return gridPen; } } @@ -3128,7 +3128,7 @@ internal int HorizontalOffset { get { - return this.horizontalOffset; + return horizontalOffset; } set { @@ -3136,65 +3136,65 @@ internal int HorizontalOffset { value = 0; } - int widthNotVisible = this.Columns.GetColumnsWidth(DataGridViewElementStates.Visible) - this.layout.Data.Width; + int widthNotVisible = Columns.GetColumnsWidth(DataGridViewElementStates.Visible) - layout.Data.Width; if (value > widthNotVisible && widthNotVisible > 0) { value = widthNotVisible; } - if (value == this.horizontalOffset) + if (value == horizontalOffset) { return; } ScrollEventType scrollEventType; - int oldFirstVisibleScrollingCol = this.displayedBandsInfo.FirstDisplayedScrollingCol; - int change = this.horizontalOffset - value; - if (this.horizScrollBar.Enabled) + int oldFirstVisibleScrollingCol = displayedBandsInfo.FirstDisplayedScrollingCol; + int change = horizontalOffset - value; + if (horizScrollBar.Enabled) { - this.horizScrollBar.Value = value; + horizScrollBar.Value = value; } - this.horizontalOffset = value; + horizontalOffset = value; - int totalVisibleFrozenWidth = this.Columns.GetColumnsWidth(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int totalVisibleFrozenWidth = Columns.GetColumnsWidth(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); - Rectangle rectTmp = this.layout.Data; - if (this.layout.ColumnHeadersVisible) + Rectangle rectTmp = layout.Data; + if (layout.ColumnHeadersVisible) { // column headers must scroll as well - rectTmp = Rectangle.Union(rectTmp, this.layout.ColumnHeaders); + rectTmp = Rectangle.Union(rectTmp, layout.ColumnHeaders); } - else if (this.SingleVerticalBorderAdded) + else if (SingleVerticalBorderAdded) { - if (!this.RightToLeftInternal) + if (!RightToLeftInternal) { rectTmp.X--; } rectTmp.Width++; } - if (this.SingleVerticalBorderAdded && + if (SingleVerticalBorderAdded && totalVisibleFrozenWidth > 0) { - if (!this.RightToLeftInternal) + if (!RightToLeftInternal) { rectTmp.X++; } rectTmp.Width--; } - if (!this.RightToLeftInternal) + if (!RightToLeftInternal) { rectTmp.X += totalVisibleFrozenWidth; } rectTmp.Width -= totalVisibleFrozenWidth; - this.displayedBandsInfo.FirstDisplayedScrollingCol = ComputeFirstVisibleScrollingColumn(); + displayedBandsInfo.FirstDisplayedScrollingCol = ComputeFirstVisibleScrollingColumn(); // update the lastTotallyDisplayedScrollingCol ComputeVisibleColumns(); - if (this.editingControl != null && - !this.Columns[this.ptCurrentCell.X].Frozen && - this.displayedBandsInfo.FirstDisplayedScrollingCol > -1) + if (editingControl != null && + !Columns[ptCurrentCell.X].Frozen && + displayedBandsInfo.FirstDisplayedScrollingCol > -1) { PositionEditingControl(true /*setLocation*/, false /*setSize*/, false /*setFocus*/); } @@ -3202,29 +3202,29 @@ internal int HorizontalOffset // The mouse probably is not over the same cell after the scroll. UpdateMouseEnteredCell(null /*HitTestInfo*/, null /*MouseEventArgs*/); - if (oldFirstVisibleScrollingCol == this.displayedBandsInfo.FirstDisplayedScrollingCol) + if (oldFirstVisibleScrollingCol == displayedBandsInfo.FirstDisplayedScrollingCol) { scrollEventType = change > 0 ? ScrollEventType.SmallIncrement : ScrollEventType.SmallDecrement; } - else if (this.Columns.DisplayInOrder(oldFirstVisibleScrollingCol, this.displayedBandsInfo.FirstDisplayedScrollingCol)) + else if (Columns.DisplayInOrder(oldFirstVisibleScrollingCol, displayedBandsInfo.FirstDisplayedScrollingCol)) { - scrollEventType = this.Columns.GetColumnCount(DataGridViewElementStates.Visible, oldFirstVisibleScrollingCol, this.displayedBandsInfo.FirstDisplayedScrollingCol) > 1 ? ScrollEventType.LargeIncrement : ScrollEventType.SmallIncrement; + scrollEventType = Columns.GetColumnCount(DataGridViewElementStates.Visible, oldFirstVisibleScrollingCol, displayedBandsInfo.FirstDisplayedScrollingCol) > 1 ? ScrollEventType.LargeIncrement : ScrollEventType.SmallIncrement; } else { - Debug.Assert(this.Columns.DisplayInOrder(this.displayedBandsInfo.FirstDisplayedScrollingCol, oldFirstVisibleScrollingCol)); - scrollEventType = this.Columns.GetColumnCount(DataGridViewElementStates.Visible, this.displayedBandsInfo.FirstDisplayedScrollingCol, oldFirstVisibleScrollingCol) > 1 ? ScrollEventType.LargeDecrement : ScrollEventType.SmallDecrement; + Debug.Assert(Columns.DisplayInOrder(displayedBandsInfo.FirstDisplayedScrollingCol, oldFirstVisibleScrollingCol)); + scrollEventType = Columns.GetColumnCount(DataGridViewElementStates.Visible, displayedBandsInfo.FirstDisplayedScrollingCol, oldFirstVisibleScrollingCol) > 1 ? ScrollEventType.LargeDecrement : ScrollEventType.SmallDecrement; } NativeMethods.RECT[] rects = CreateScrollableRegion(rectTmp); - if (this.RightToLeftInternal) + if (RightToLeftInternal) { change = -change; } ScrollRectangles(rects, change); - if (!this.dataGridViewState2[DATAGRIDVIEWSTATE2_stopRaisingHorizontalScroll]) + if (!dataGridViewState2[DATAGRIDVIEWSTATE2_stopRaisingHorizontalScroll]) { - OnScroll(scrollEventType, this.horizontalOffset + change, this.horizontalOffset, ScrollOrientation.HorizontalScroll); + OnScroll(scrollEventType, horizontalOffset + change, horizontalOffset, ScrollOrientation.HorizontalScroll); } FlushDisplayedChanged(); } @@ -3234,7 +3234,7 @@ protected ScrollBar HorizontalScrollBar { get { - return this.horizScrollBar; + return horizScrollBar; } } @@ -3242,7 +3242,7 @@ internal int HorizontalScrollBarHeight { get { - return this.horizScrollBar.Height; + return horizScrollBar.Height; } } @@ -3250,7 +3250,7 @@ internal bool HorizontalScrollBarVisible { get { - return this.horizScrollBar.Visible; + return horizScrollBar.Visible; } } @@ -3262,7 +3262,7 @@ public int HorizontalScrollingOffset { get { - return this.horizontalOffset; + return horizontalOffset; } set { @@ -3276,18 +3276,18 @@ public int HorizontalScrollingOffset //{ // throw new ArgumentOutOfRangeException(string.Format(SR.DataGridView_PropertyTooLarge, "HorizontalScrollingOffset", (widthNotVisible).ToString())); //} - else if (value > 0 && (this.Columns.GetColumnsWidth(DataGridViewElementStates.Visible) - this.layout.Data.Width) <= 0) + else if (value > 0 && (Columns.GetColumnsWidth(DataGridViewElementStates.Visible) - layout.Data.Width) <= 0) { // Intentionally ignoring the case where dev tries to set value while there is no horizontal scrolling possible. // throw new ArgumentOutOfRangeException(nameof(HorizontalScrollingOffset), string.Format(SR.DataGridView_PropertyMustBeZero)); - Debug.Assert(this.horizontalOffset == 0); + Debug.Assert(horizontalOffset == 0); return; } - if (value == this.horizontalOffset) + if (value == horizontalOffset) { return; } - this.HorizontalOffset = value; + HorizontalOffset = value; } } @@ -3295,12 +3295,12 @@ private System.Windows.Forms.Timer HorizScrollTimer { get { - if (this.horizScrollTimer == null) + if (horizScrollTimer == null) { - this.horizScrollTimer = new System.Windows.Forms.Timer(); - this.horizScrollTimer.Tick += new System.EventHandler(HorizScrollTimer_Tick); + horizScrollTimer = new System.Windows.Forms.Timer(); + horizScrollTimer.Tick += new System.EventHandler(HorizScrollTimer_Tick); } - return this.horizScrollTimer; + return horizScrollTimer; } } @@ -3308,7 +3308,7 @@ private bool InAdjustFillingColumns { get { - return this.dataGridViewOper[DATAGRIDVIEWOPER_inAdjustFillingColumn] || this.dataGridViewOper[DATAGRIDVIEWOPER_inAdjustFillingColumns]; + return dataGridViewOper[DATAGRIDVIEWOPER_inAdjustFillingColumn] || dataGridViewOper[DATAGRIDVIEWOPER_inAdjustFillingColumns]; } } @@ -3316,7 +3316,7 @@ internal bool InBeginEdit { get { - return this.dataGridViewOper[DATAGRIDVIEWOPER_inBeginEdit]; + return dataGridViewOper[DATAGRIDVIEWOPER_inBeginEdit]; } } @@ -3324,11 +3324,11 @@ internal bool InDisplayIndexAdjustments { get { - return this.dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments]; + return dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments]; } set { - this.dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments] = value; + dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments] = value; } } @@ -3336,7 +3336,7 @@ internal bool InEndEdit { get { - return this.dataGridViewOper[DATAGRIDVIEWOPER_inEndEdit]; + return dataGridViewOper[DATAGRIDVIEWOPER_inEndEdit]; } } @@ -3344,12 +3344,12 @@ private DataGridViewCellStyle InheritedEditingCellStyle { get { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { return null; } - return this.CurrentCellInternal.GetInheritedStyleInternal(this.ptCurrentCell.Y); + return CurrentCellInternal.GetInheritedStyleInternal(ptCurrentCell.Y); } } @@ -3357,7 +3357,7 @@ internal bool InInitialization { get { - return this.dataGridViewState2[DATAGRIDVIEWSTATE2_initializing]; + return dataGridViewState2[DATAGRIDVIEWSTATE2_initializing]; } } @@ -3365,7 +3365,7 @@ internal bool InSortOperation { get { - return this.dataGridViewOper[DATAGRIDVIEWOPER_inSort]; + return dataGridViewOper[DATAGRIDVIEWOPER_inSort]; } } @@ -3374,7 +3374,7 @@ public bool IsCurrentCellDirty { get { - return this.dataGridViewState1[DATAGRIDVIEWSTATE1_editedCellChanged]; + return dataGridViewState1[DATAGRIDVIEWSTATE1_editedCellChanged]; } } @@ -3382,9 +3382,9 @@ private bool IsCurrentCellDirtyInternal { set { - if (value != this.dataGridViewState1[DATAGRIDVIEWSTATE1_editedCellChanged]) + if (value != dataGridViewState1[DATAGRIDVIEWSTATE1_editedCellChanged]) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_editedCellChanged] = value; + dataGridViewState1[DATAGRIDVIEWSTATE1_editedCellChanged] = value; OnCurrentCellDirtyStateChanged(EventArgs.Empty); } } @@ -3395,7 +3395,7 @@ public bool IsCurrentCellInEditMode { get { - return this.editingControl != null || this.dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode]; + return editingControl != null || dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode]; } } @@ -3405,13 +3405,13 @@ public bool IsCurrentRowDirty { get { - if (!this.VirtualMode) + if (!VirtualMode) { - return this.dataGridViewState1[DATAGRIDVIEWSTATE1_editedRowChanged] || this.IsCurrentCellDirty; + return dataGridViewState1[DATAGRIDVIEWSTATE1_editedRowChanged] || IsCurrentCellDirty; } else { - QuestionEventArgs qe = new QuestionEventArgs(this.dataGridViewState1[DATAGRIDVIEWSTATE1_editedRowChanged] || this.IsCurrentCellDirty); + QuestionEventArgs qe = new QuestionEventArgs(dataGridViewState1[DATAGRIDVIEWSTATE1_editedRowChanged] || IsCurrentCellDirty); OnRowDirtyStateNeeded(qe); return qe.Response; } @@ -3422,13 +3422,13 @@ internal bool IsCurrentRowDirtyInternal { set { - if (value != this.dataGridViewState1[DATAGRIDVIEWSTATE1_editedRowChanged]) + if (value != dataGridViewState1[DATAGRIDVIEWSTATE1_editedRowChanged]) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_editedRowChanged] = value; - if (this.RowHeadersVisible && this.ShowEditingIcon && this.ptCurrentCell.Y >= 0) + dataGridViewState1[DATAGRIDVIEWSTATE1_editedRowChanged] = value; + if (RowHeadersVisible && ShowEditingIcon && ptCurrentCell.Y >= 0) { // Force the pencil to appear in the row header - InvalidateCellPrivate(-1, this.ptCurrentCell.Y); + InvalidateCellPrivate(-1, ptCurrentCell.Y); } } } @@ -3438,15 +3438,15 @@ private bool IsEscapeKeyEffective { get { - return this.dataGridViewOper[DATAGRIDVIEWOPER_trackColResize] || - this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowResize] || - this.dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize] || - this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize] || - this.dataGridViewOper[DATAGRIDVIEWOPER_trackColRelocation] || - this.IsCurrentCellDirty || - ((this.VirtualMode || this.DataSource != null) && this.IsCurrentRowDirty) || - (this.EditMode != DataGridViewEditMode.EditOnEnter && this.editingControl != null || - this.dataGridViewState1[DATAGRIDVIEWSTATE1_newRowEdited]); + return dataGridViewOper[DATAGRIDVIEWOPER_trackColResize] || + dataGridViewOper[DATAGRIDVIEWOPER_trackRowResize] || + dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize] || + dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize] || + dataGridViewOper[DATAGRIDVIEWOPER_trackColRelocation] || + IsCurrentCellDirty || + ((VirtualMode || DataSource != null) && IsCurrentRowDirty) || + (EditMode != DataGridViewEditMode.EditOnEnter && editingControl != null || + dataGridViewState1[DATAGRIDVIEWSTATE1_newRowEdited]); } } @@ -3454,7 +3454,7 @@ private bool IsMinimized { get { - Form parentForm = this.TopLevelControlInternal as Form; + Form parentForm = TopLevelControlInternal as Form; return parentForm != null && parentForm.WindowState == FormWindowState.Minimized; } } @@ -3463,8 +3463,8 @@ private bool IsSharedCellReadOnly(DataGridViewCell dataGridViewCell, int rowInde { Debug.Assert(dataGridViewCell != null); Debug.Assert(rowIndex >= 0); - DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); - return this.ReadOnly || + DataGridViewElementStates rowState = Rows.GetRowState(rowIndex); + return ReadOnly || (rowState & DataGridViewElementStates.ReadOnly) != 0 || (dataGridViewCell.OwningColumn != null && dataGridViewCell.OwningColumn.ReadOnly) || dataGridViewCell.StateIncludes(DataGridViewElementStates.ReadOnly); @@ -3474,7 +3474,7 @@ internal bool IsSharedCellSelected(DataGridViewCell dataGridViewCell, int rowInd { Debug.Assert(dataGridViewCell != null); Debug.Assert(rowIndex >= 0); - DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); + DataGridViewElementStates rowState = Rows.GetRowState(rowIndex); return (rowState & DataGridViewElementStates.Selected) != 0 || (dataGridViewCell.OwningColumn != null && dataGridViewCell.OwningColumn.Selected) || dataGridViewCell.StateIncludes(DataGridViewElementStates.Selected); @@ -3484,7 +3484,7 @@ internal bool IsSharedCellVisible(DataGridViewCell dataGridViewCell, int rowInde { Debug.Assert(dataGridViewCell != null); Debug.Assert(rowIndex >= 0); - DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); + DataGridViewElementStates rowState = Rows.GetRowState(rowIndex); return (rowState & DataGridViewElementStates.Visible) != 0 && (dataGridViewCell.OwningColumn != null && dataGridViewCell.OwningColumn.Visible); } @@ -3493,11 +3493,11 @@ internal LayoutData LayoutInfo { get { - if (this.layout.dirty && this.IsHandleCreated) + if (layout.dirty && IsHandleCreated) { PerformLayoutPrivate(false /*useRowShortcut*/, true /*computeVisibleRows*/, false /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); } - return this.layout; + return layout; } } @@ -3505,7 +3505,7 @@ internal Point MouseDownCellAddress { get { - return this.ptMouseDownCell; + return ptMouseDownCell; } } @@ -3518,14 +3518,14 @@ public bool MultiSelect { get { - return this.dataGridViewState1[DATAGRIDVIEWSTATE1_multiSelect]; + return dataGridViewState1[DATAGRIDVIEWSTATE1_multiSelect]; } set { - if (this.MultiSelect != value) + if (MultiSelect != value) { ClearSelection(); - this.dataGridViewState1[DATAGRIDVIEWSTATE1_multiSelect] = value; + dataGridViewState1[DATAGRIDVIEWSTATE1_multiSelect] = value; OnMultiSelectChanged(EventArgs.Empty); } } @@ -3537,8 +3537,8 @@ public bool MultiSelect ] public event EventHandler MultiSelectChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWMULTISELECTCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWMULTISELECTCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWMULTISELECTCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWMULTISELECTCHANGED, value); } [ @@ -3549,7 +3549,7 @@ public int NewRowIndex { get { - return this.newRowIndex; + return newRowIndex; } } @@ -3557,7 +3557,7 @@ internal bool NoDimensionChangeAllowed { get { - return this.noDimensionChangeCount > 0; + return noDimensionChangeCount > 0; } } @@ -3565,12 +3565,12 @@ private int NoSelectionChangeCount { get { - return this.noSelectionChangeCount; + return noSelectionChangeCount; } set { Debug.Assert(value >= 0); - this.noSelectionChangeCount = value; + noSelectionChangeCount = value; if (value == 0) { FlushSelectionChanged(); @@ -3610,11 +3610,11 @@ internal DataGridViewCellStyle PlaceholderCellStyle { get { - if (this.placeholderCellStyle == null) + if (placeholderCellStyle == null) { - this.placeholderCellStyle = new DataGridViewCellStyle(); + placeholderCellStyle = new DataGridViewCellStyle(); } - return this.placeholderCellStyle; + return placeholderCellStyle; } } @@ -3628,15 +3628,15 @@ public bool ReadOnly { get { - return this.dataGridViewState1[DATAGRIDVIEWSTATE1_readOnly]; + return dataGridViewState1[DATAGRIDVIEWSTATE1_readOnly]; } set { - if (value != this.dataGridViewState1[DATAGRIDVIEWSTATE1_readOnly]) + if (value != dataGridViewState1[DATAGRIDVIEWSTATE1_readOnly]) { if (value && - this.ptCurrentCell.X != -1 && - this.IsCurrentCellInEditMode) + ptCurrentCell.X != -1 && + IsCurrentCellInEditMode) { // Current cell becomes read-only. Exit editing mode. if (!EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit, @@ -3654,18 +3654,18 @@ public bool ReadOnly } } - this.dataGridViewState1[DATAGRIDVIEWSTATE1_readOnly] = value; + dataGridViewState1[DATAGRIDVIEWSTATE1_readOnly] = value; if (value) { try { - this.dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange] = true; - for (int columnIndex = 0; columnIndex < this.Columns.Count; columnIndex++) + dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange] = true; + for (int columnIndex = 0; columnIndex < Columns.Count; columnIndex++) { SetReadOnlyColumnCore(columnIndex, false); } - int rowCount = this.Rows.Count; + int rowCount = Rows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { SetReadOnlyRowCore(rowIndex, false); @@ -3673,21 +3673,21 @@ public bool ReadOnly } finally { - this.dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange] = false; + dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange] = false; } } #if DEBUG else { - Debug.Assert(this.individualReadOnlyCells.Count == 0); - for (int columnIndex = 0; columnIndex < this.Columns.Count; columnIndex++) + Debug.Assert(individualReadOnlyCells.Count == 0); + for (int columnIndex = 0; columnIndex < Columns.Count; columnIndex++) { - Debug.Assert(this.Columns[columnIndex].ReadOnly == false); + Debug.Assert(Columns[columnIndex].ReadOnly == false); } - int rowCount = this.Rows.Count; + int rowCount = Rows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { - Debug.Assert((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.ReadOnly) == 0); + Debug.Assert((Rows.GetRowState(rowIndex) & DataGridViewElementStates.ReadOnly) == 0); } } #endif @@ -3702,13 +3702,13 @@ public bool ReadOnly ] public event EventHandler ReadOnlyChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWREADONLYCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWREADONLYCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWREADONLYCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWREADONLYCHANGED, value); } private void ResetCurrentCell() { - if (this.ptCurrentCell.X != -1 && + if (ptCurrentCell.X != -1 && !SetCurrentCellAddressCore(-1, -1, true /*setAnchorCellAddress*/, true /*validateCurrentCell*/, false /*throughMouseClick*/)) { // Edited value couldn't be committed or aborted @@ -3720,7 +3720,7 @@ internal bool ResizingOperationAboutToStart { get { - return this.dataGridViewOper[DATAGRIDVIEWOPER_resizingOperationAboutToStart]; + return dataGridViewOper[DATAGRIDVIEWOPER_resizingOperationAboutToStart]; } } @@ -3728,13 +3728,13 @@ internal bool RightToLeftInternal { get { - if (this.dataGridViewState2[DATAGRIDVIEWSTATE2_rightToLeftValid]) + if (dataGridViewState2[DATAGRIDVIEWSTATE2_rightToLeftValid]) { - return this.dataGridViewState2[DATAGRIDVIEWSTATE2_rightToLeftMode]; + return dataGridViewState2[DATAGRIDVIEWSTATE2_rightToLeftMode]; } - this.dataGridViewState2[DATAGRIDVIEWSTATE2_rightToLeftMode] = (this.RightToLeft == RightToLeft.Yes); - this.dataGridViewState2[DATAGRIDVIEWSTATE2_rightToLeftValid] = true; - return this.dataGridViewState2[DATAGRIDVIEWSTATE2_rightToLeftMode]; + dataGridViewState2[DATAGRIDVIEWSTATE2_rightToLeftMode] = (RightToLeft == RightToLeft.Yes); + dataGridViewState2[DATAGRIDVIEWSTATE2_rightToLeftValid] = true; + return dataGridViewState2[DATAGRIDVIEWSTATE2_rightToLeftMode]; } } @@ -3748,11 +3748,11 @@ public int RowCount { get { - return this.Rows.Count; + return Rows.Count; } set { - if (this.AllowUserToAddRowsInternal) + if (AllowUserToAddRowsInternal) { if (value < 1) { @@ -3766,25 +3766,25 @@ public int RowCount throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(RowCount), value, 0)); } } - if (this.DataSource != null) + if (DataSource != null) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotSetRowCountOnDataBoundDataGridView)); } - if (value != this.Rows.Count) + if (value != Rows.Count) { if (value == 0) { // Total removal of the rows. - this.Rows.Clear(); + Rows.Clear(); } - else if (value < this.Rows.Count) + else if (value < Rows.Count) { // Some rows need to be removed, from the tail of the rows collection - while (value < this.Rows.Count) + while (value < Rows.Count) { - int currentRowCount = this.Rows.Count; - this.Rows.RemoveAt(currentRowCount - (this.AllowUserToAddRowsInternal ? 2 : 1)); - if (this.Rows.Count >= currentRowCount) + int currentRowCount = Rows.Count; + Rows.RemoveAt(currentRowCount - (AllowUserToAddRowsInternal ? 2 : 1)); + if (Rows.Count >= currentRowCount) { // Row removal failed. We stop the loop. break; @@ -3794,16 +3794,16 @@ public int RowCount else { // Some rows need to be appened. - if (this.Columns.Count == 0) + if (Columns.Count == 0) { // There are no columns yet, we simply create a single DataGridViewTextBoxColumn. DataGridViewTextBoxColumn dataGridViewTextBoxColumn = new DataGridViewTextBoxColumn(); - this.Columns.Add(dataGridViewTextBoxColumn); + Columns.Add(dataGridViewTextBoxColumn); } - int rowsToAdd = value - this.Rows.Count; + int rowsToAdd = value - Rows.Count; if (rowsToAdd > 0) { - this.Rows.Add(rowsToAdd); + Rows.Add(rowsToAdd); } } } @@ -3820,7 +3820,7 @@ public DataGridViewHeaderBorderStyle RowHeadersBorderStyle { get { - switch (this.advancedRowHeadersBorderStyle.All) + switch (advancedRowHeadersBorderStyle.All) { case DataGridViewAdvancedCellBorderStyle.NotSet: return DataGridViewHeaderBorderStyle.Custom; @@ -3849,37 +3849,37 @@ public DataGridViewHeaderBorderStyle RowHeadersBorderStyle throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewHeaderBorderStyle)); } - if (value != this.RowHeadersBorderStyle) + if (value != RowHeadersBorderStyle) { if (value == DataGridViewHeaderBorderStyle.Custom) { throw new ArgumentException(string.Format(SR.DataGridView_CustomCellBorderStyleInvalid, "RowHeadersBorderStyle")); } - this.dataGridViewOper[DATAGRIDVIEWOPER_inBorderStyleChange] = true; + dataGridViewOper[DATAGRIDVIEWOPER_inBorderStyleChange] = true; try { switch (value) { case DataGridViewHeaderBorderStyle.Single: - this.advancedRowHeadersBorderStyle.All = DataGridViewAdvancedCellBorderStyle.Single; + advancedRowHeadersBorderStyle.All = DataGridViewAdvancedCellBorderStyle.Single; break; case DataGridViewHeaderBorderStyle.Raised: - this.advancedRowHeadersBorderStyle.All = DataGridViewAdvancedCellBorderStyle.OutsetPartial; + advancedRowHeadersBorderStyle.All = DataGridViewAdvancedCellBorderStyle.OutsetPartial; break; case DataGridViewHeaderBorderStyle.Sunken: - this.advancedRowHeadersBorderStyle.All = DataGridViewAdvancedCellBorderStyle.InsetDouble; + advancedRowHeadersBorderStyle.All = DataGridViewAdvancedCellBorderStyle.InsetDouble; break; case DataGridViewHeaderBorderStyle.None: - this.advancedRowHeadersBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None; + advancedRowHeadersBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None; break; } } finally { - this.dataGridViewOper[DATAGRIDVIEWOPER_inBorderStyleChange] = false; + dataGridViewOper[DATAGRIDVIEWOPER_inBorderStyleChange] = false; } OnRowHeadersBorderStyleChanged(EventArgs.Empty); } @@ -3892,8 +3892,8 @@ public DataGridViewHeaderBorderStyle RowHeadersBorderStyle ] public event EventHandler RowHeadersBorderStyleChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWHEADERSBORDERSTYLECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEADERSBORDERSTYLECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWHEADERSBORDERSTYLECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEADERSBORDERSTYLECHANGED, value); } [ @@ -3905,26 +3905,26 @@ public DataGridViewCellStyle RowHeadersDefaultCellStyle { get { - if (this.rowHeadersDefaultCellStyle == null) + if (rowHeadersDefaultCellStyle == null) { - this.rowHeadersDefaultCellStyle = this.DefaultRowHeadersDefaultCellStyle; + rowHeadersDefaultCellStyle = DefaultRowHeadersDefaultCellStyle; } - return this.rowHeadersDefaultCellStyle; + return rowHeadersDefaultCellStyle; } set { - DataGridViewCellStyle cs = this.RowHeadersDefaultCellStyle; + DataGridViewCellStyle cs = RowHeadersDefaultCellStyle; cs.RemoveScope(DataGridViewCellStyleScopes.RowHeaders); - this.rowHeadersDefaultCellStyle = value; + rowHeadersDefaultCellStyle = value; if (value != null) { - this.rowHeadersDefaultCellStyle.AddScope(this, DataGridViewCellStyleScopes.RowHeaders); + rowHeadersDefaultCellStyle.AddScope(this, DataGridViewCellStyleScopes.RowHeaders); } - DataGridViewCellStyleDifferences dgvcsc = cs.GetDifferencesFrom(this.RowHeadersDefaultCellStyle); + DataGridViewCellStyleDifferences dgvcsc = cs.GetDifferencesFrom(RowHeadersDefaultCellStyle); if (dgvcsc != DataGridViewCellStyleDifferences.None) { - this.CellStyleChangedEventArgs.ChangeAffectsPreferredSize = (dgvcsc == DataGridViewCellStyleDifferences.AffectPreferredSize); - OnRowHeadersDefaultCellStyleChanged(this.CellStyleChangedEventArgs); + CellStyleChangedEventArgs.ChangeAffectsPreferredSize = (dgvcsc == DataGridViewCellStyleDifferences.AffectPreferredSize); + OnRowHeadersDefaultCellStyleChanged(CellStyleChangedEventArgs); } } } @@ -3935,8 +3935,8 @@ public DataGridViewCellStyle RowHeadersDefaultCellStyle ] public event EventHandler RowHeadersDefaultCellStyleChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWHEADERSDEFAULTCELLSTYLECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEADERSDEFAULTCELLSTYLECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWHEADERSDEFAULTCELLSTYLECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEADERSDEFAULTCELLSTYLECHANGED, value); } /// @@ -3954,23 +3954,23 @@ public bool RowHeadersVisible { get { - return this.dataGridViewState1[DATAGRIDVIEWSTATE1_rowHeadersVisible]; + return dataGridViewState1[DATAGRIDVIEWSTATE1_rowHeadersVisible]; } set { - if (this.RowHeadersVisible != value) + if (RowHeadersVisible != value) { if (!value && - (this.autoSizeRowsMode == DataGridViewAutoSizeRowsMode.AllHeaders || this.autoSizeRowsMode == DataGridViewAutoSizeRowsMode.DisplayedHeaders)) + (autoSizeRowsMode == DataGridViewAutoSizeRowsMode.AllHeaders || autoSizeRowsMode == DataGridViewAutoSizeRowsMode.DisplayedHeaders)) { throw new InvalidOperationException(string.Format(SR.DataGridView_RowHeadersCannotBeInvisible)); } - using (LayoutTransaction.CreateTransactionIf(this.AutoSize, this.ParentInternal, this, PropertyNames.RowHeadersVisible)) + using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.RowHeadersVisible)) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_rowHeadersVisible] = value; - this.layout.RowHeadersVisible = value; - this.displayedBandsInfo.EnsureDirtyState(); - if (!this.AutoSize) + dataGridViewState1[DATAGRIDVIEWSTATE1_rowHeadersVisible] = value; + layout.RowHeadersVisible = value; + displayedBandsInfo.EnsureDirtyState(); + if (!AutoSize) { PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, true /*repositionEditingControl*/); } @@ -3990,7 +3990,7 @@ public int RowHeadersWidth { get { - return this.rowHeadersWidth; + return rowHeadersWidth; } set { @@ -4003,14 +4003,14 @@ public int RowHeadersWidth throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidHighBoundArgumentEx, nameof(RowHeadersWidth), value, maxHeadersThickness)); } - if (this.RowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.EnableResizing && - this.RowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.DisableResizing) + if (RowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.EnableResizing && + RowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.DisableResizing) { - this.cachedRowHeadersWidth = value; + cachedRowHeadersWidth = value; } - else if (this.rowHeadersWidth != value) + else if (rowHeadersWidth != value) { - this.RowHeadersWidthInternal = value; + RowHeadersWidthInternal = value; } } } @@ -4019,18 +4019,18 @@ private int RowHeadersWidthInternal { set { - using (LayoutTransaction.CreateTransactionIf(this.AutoSize, this.ParentInternal, this, PropertyNames.RowHeadersWidth)) + using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.RowHeadersWidth)) { - Debug.Assert(this.rowHeadersWidth != value); + Debug.Assert(rowHeadersWidth != value); Debug.Assert(value >= minimumRowHeadersWidth); - this.rowHeadersWidth = value; - if (this.AutoSize) + rowHeadersWidth = value; + if (AutoSize) { InvalidateInside(); } else { - if (this.layout.RowHeadersVisible) + if (layout.RowHeadersVisible) { PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, true /*repositionEditingControl*/); InvalidateInside(); @@ -4047,14 +4047,14 @@ private int RowHeadersWidthInternal ] public event EventHandler RowHeadersWidthChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWHEADERSWIDTHCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEADERSWIDTHCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWHEADERSWIDTHCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEADERSWIDTHCHANGED, value); } private bool ShouldSerializeRowHeadersWidth() { - return (this.rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing || this.rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.DisableResizing) && - defaultRowHeadersWidth != this.RowHeadersWidth; + return (rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing || rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.DisableResizing) && + defaultRowHeadersWidth != RowHeadersWidth; } /// @@ -4072,7 +4072,7 @@ public DataGridViewRowHeadersWidthSizeMode RowHeadersWidthSizeMode { get { - return this.rowHeadersWidthSizeMode; + return rowHeadersWidthSizeMode; } set { @@ -4081,7 +4081,7 @@ public DataGridViewRowHeadersWidthSizeMode RowHeadersWidthSizeMode { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewRowHeadersWidthSizeMode)); } - if (this.rowHeadersWidthSizeMode != value) + if (rowHeadersWidthSizeMode != value) { /*if (value != DataGridViewRowHeadersWidthSizeMode.EnableResizing && * value != DataGridViewRowHeadersWidthSizeMode.DisableResizing && @@ -4089,9 +4089,9 @@ public DataGridViewRowHeadersWidthSizeMode RowHeadersWidthSizeMode { We intentionally don't throw an error because of designer code spit order. }*/ - DataGridViewAutoSizeModeEventArgs dgvasme = new DataGridViewAutoSizeModeEventArgs(this.rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.EnableResizing && - this.rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.DisableResizing); - this.rowHeadersWidthSizeMode = value; + DataGridViewAutoSizeModeEventArgs dgvasme = new DataGridViewAutoSizeModeEventArgs(rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.EnableResizing && + rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.DisableResizing); + rowHeadersWidthSizeMode = value; OnRowHeadersWidthSizeModeChanged(dgvasme); } } @@ -4103,8 +4103,8 @@ public DataGridViewRowHeadersWidthSizeMode RowHeadersWidthSizeMode ] public event DataGridViewAutoSizeModeEventHandler RowHeadersWidthSizeModeChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWHEADERSWIDTHSIZEMODECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEADERSWIDTHSIZEMODECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWHEADERSWIDTHSIZEMODECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEADERSWIDTHSIZEMODECHANGED, value); } [ @@ -4114,11 +4114,11 @@ public DataGridViewRowCollection Rows { get { - if (this.dataGridViewRows == null) + if (dataGridViewRows == null) { - this.dataGridViewRows = CreateRowsInstance(); + dataGridViewRows = CreateRowsInstance(); } - return this.dataGridViewRows; + return dataGridViewRows; } } @@ -4130,27 +4130,27 @@ public DataGridViewCellStyle RowsDefaultCellStyle { get { - if (this.rowsDefaultCellStyle == null) + if (rowsDefaultCellStyle == null) { - this.rowsDefaultCellStyle = new DataGridViewCellStyle(); - this.rowsDefaultCellStyle.AddScope(this, DataGridViewCellStyleScopes.Rows); + rowsDefaultCellStyle = new DataGridViewCellStyle(); + rowsDefaultCellStyle.AddScope(this, DataGridViewCellStyleScopes.Rows); } - return this.rowsDefaultCellStyle; + return rowsDefaultCellStyle; } set { - DataGridViewCellStyle cs = this.RowsDefaultCellStyle; + DataGridViewCellStyle cs = RowsDefaultCellStyle; cs.RemoveScope(DataGridViewCellStyleScopes.Rows); - this.rowsDefaultCellStyle = value; + rowsDefaultCellStyle = value; if (value != null) { - this.rowsDefaultCellStyle.AddScope(this, DataGridViewCellStyleScopes.Rows); + rowsDefaultCellStyle.AddScope(this, DataGridViewCellStyleScopes.Rows); } - DataGridViewCellStyleDifferences dgvcsc = cs.GetDifferencesFrom(this.RowsDefaultCellStyle); + DataGridViewCellStyleDifferences dgvcsc = cs.GetDifferencesFrom(RowsDefaultCellStyle); if (dgvcsc != DataGridViewCellStyleDifferences.None) { - this.CellStyleChangedEventArgs.ChangeAffectsPreferredSize = (dgvcsc == DataGridViewCellStyleDifferences.AffectPreferredSize); - OnRowsDefaultCellStyleChanged(this.CellStyleChangedEventArgs); + CellStyleChangedEventArgs.ChangeAffectsPreferredSize = (dgvcsc == DataGridViewCellStyleDifferences.AffectPreferredSize); + OnRowsDefaultCellStyleChanged(CellStyleChangedEventArgs); } } } @@ -4161,8 +4161,8 @@ public DataGridViewCellStyle RowsDefaultCellStyle ] public event EventHandler RowsDefaultCellStyleChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWSDEFAULTCELLSTYLECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWSDEFAULTCELLSTYLECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWSDEFAULTCELLSTYLECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWSDEFAULTCELLSTYLECHANGED, value); } [ @@ -4175,11 +4175,11 @@ public DataGridViewRow RowTemplate { get { - if (this.rowTemplate == null) + if (rowTemplate == null) { - this.rowTemplate = new DataGridViewRow(); + rowTemplate = new DataGridViewRow(); } - return this.rowTemplate; + return rowTemplate; } set { @@ -4195,20 +4195,20 @@ public DataGridViewRow RowTemplate // throw new InvalidOperationException(string.Format(SR.DataGridView_RowTemplateCannotBeSelected)); //} } - this.rowTemplate = dataGridViewRow; + rowTemplate = dataGridViewRow; } } private bool ShouldSerializeRowTemplate() { - return this.rowTemplate != null; + return rowTemplate != null; } internal DataGridViewRow RowTemplateClone { get { - DataGridViewRow rowTemplateClone = (DataGridViewRow)this.RowTemplate.Clone(); + DataGridViewRow rowTemplateClone = (DataGridViewRow)RowTemplate.Clone(); CompleteCellsCollection(rowTemplateClone); return rowTemplateClone; } @@ -4227,7 +4227,7 @@ public ScrollBars ScrollBars { get { - return this.scrollBars; + return scrollBars; } set { @@ -4237,14 +4237,14 @@ public ScrollBars ScrollBars throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ScrollBars)); } - if (this.scrollBars != value) + if (scrollBars != value) { - using (LayoutTransaction.CreateTransactionIf(this.AutoSize, this.ParentInternal, this, PropertyNames.ScrollBars)) + using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.ScrollBars)) { // Before changing the value of this.scrollBars, we scroll to the top-left cell to // avoid inconsitent state of scrollbars. - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); - int firstVisibleRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); + int firstVisibleRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); if (dataGridViewColumn != null && firstVisibleRowIndex != -1) { @@ -4253,12 +4253,12 @@ public ScrollBars ScrollBars throw new InvalidOperationException(string.Format(SR.DataGridView_CellChangeCannotBeCommittedOrAborted)); } } - Debug.Assert(this.HorizontalOffset == 0); - Debug.Assert(this.VerticalOffset == 0); + Debug.Assert(HorizontalOffset == 0); + Debug.Assert(VerticalOffset == 0); - this.scrollBars = value; + scrollBars = value; - if (!this.AutoSize) + if (!AutoSize) { PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, true /*repositionEditingControl*/); } @@ -4280,45 +4280,45 @@ public DataGridViewSelectedCellCollection SelectedCells get { DataGridViewSelectedCellCollection stcc = new DataGridViewSelectedCellCollection(); - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: { // Note: If we change the design and decide that SelectAll() should use band selection, // we need to add those to the selected cells. - stcc.AddCellLinkedList(this.individualSelectedCells); + stcc.AddCellLinkedList(individualSelectedCells); break; } case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: { - foreach (int columnIndex in this.selectedBandIndexes) + foreach (int columnIndex in selectedBandIndexes) { - foreach (DataGridViewRow dataGridViewRow in this.Rows) // unshares all rows! + foreach (DataGridViewRow dataGridViewRow in Rows) // unshares all rows! { stcc.Add(dataGridViewRow.Cells[columnIndex]); } } - if (this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) + if (SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) { - stcc.AddCellLinkedList(this.individualSelectedCells); + stcc.AddCellLinkedList(individualSelectedCells); } break; } case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: { - foreach (int rowIndex in this.selectedBandIndexes) + foreach (int rowIndex in selectedBandIndexes) { - DataGridViewRow dataGridViewRow = (DataGridViewRow)this.Rows[rowIndex]; // unshares the selected row + DataGridViewRow dataGridViewRow = (DataGridViewRow)Rows[rowIndex]; // unshares the selected row foreach (DataGridViewCell dataGridViewCell in dataGridViewRow.Cells) { stcc.Add(dataGridViewCell); } } - if (this.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) + if (SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) { - stcc.AddCellLinkedList(this.individualSelectedCells); + stcc.AddCellLinkedList(individualSelectedCells); } break; } @@ -4338,7 +4338,7 @@ public DataGridViewSelectedColumnCollection SelectedColumns get { DataGridViewSelectedColumnCollection strc = new DataGridViewSelectedColumnCollection(); - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: case DataGridViewSelectionMode.FullRowSelect: @@ -4346,9 +4346,9 @@ public DataGridViewSelectedColumnCollection SelectedColumns break; case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: - foreach (int columnIndex in this.selectedBandIndexes) + foreach (int columnIndex in selectedBandIndexes) { - strc.Add(this.Columns[columnIndex]); + strc.Add(Columns[columnIndex]); } break; } @@ -4368,7 +4368,7 @@ public DataGridViewSelectedRowCollection SelectedRows get { DataGridViewSelectedRowCollection strc = new DataGridViewSelectedRowCollection(); - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: case DataGridViewSelectionMode.FullColumnSelect: @@ -4376,9 +4376,9 @@ public DataGridViewSelectedRowCollection SelectedRows break; case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: - foreach (int rowIndex in this.selectedBandIndexes) + foreach (int rowIndex in selectedBandIndexes) { - strc.Add((DataGridViewRow)this.Rows[rowIndex]); // unshares the selected row + strc.Add((DataGridViewRow)Rows[rowIndex]); // unshares the selected row } break; } @@ -4396,7 +4396,7 @@ public DataGridViewSelectionMode SelectionMode { get { - return this.selectionMode; + return selectionMode; } set { @@ -4406,12 +4406,12 @@ public DataGridViewSelectionMode SelectionMode throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewSelectionMode)); } - if (this.SelectionMode != value) + if (SelectionMode != value) { - if (!this.dataGridViewState2[DATAGRIDVIEWSTATE2_initializing] && + if (!dataGridViewState2[DATAGRIDVIEWSTATE2_initializing] && (value == DataGridViewSelectionMode.FullColumnSelect || value == DataGridViewSelectionMode.ColumnHeaderSelect)) { - foreach (DataGridViewColumn dataGridViewColumn in this.Columns) + foreach (DataGridViewColumn dataGridViewColumn in Columns) { if (dataGridViewColumn.SortMode == DataGridViewColumnSortMode.Automatic) { @@ -4420,7 +4420,7 @@ public DataGridViewSelectionMode SelectionMode } } ClearSelection(); - this.selectionMode = value; + selectionMode = value; } } } @@ -4434,46 +4434,46 @@ public bool ShowCellErrors { get { - return this.dataGridViewState2[DATAGRIDVIEWSTATE2_showCellErrors]; + return dataGridViewState2[DATAGRIDVIEWSTATE2_showCellErrors]; } set { - if (this.ShowCellErrors != value) + if (ShowCellErrors != value) { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_showCellErrors] = value; + dataGridViewState2[DATAGRIDVIEWSTATE2_showCellErrors] = value; // Put this into OnShowCellErrorsChanged if created. - if (this.IsHandleCreated && !this.DesignMode) + if (IsHandleCreated && !DesignMode) { - if (value && !this.ShowRowErrors && !this.ShowCellToolTips) + if (value && !ShowRowErrors && !ShowCellToolTips) { // the tool tip hasn't yet been activated // activate it now - this.toolTipControl.Activate(!string.IsNullOrEmpty(this.toolTipCaption)); + toolTipControl.Activate(!string.IsNullOrEmpty(toolTipCaption)); } - if (!value && !this.ShowRowErrors && !this.ShowCellToolTips) + if (!value && !ShowRowErrors && !ShowCellToolTips) { // there is no reason to keep the tool tip activated // deactivate it - this.toolTipCaption = string.Empty; - this.toolTipControl.Activate(false /*activate*/); + toolTipCaption = string.Empty; + toolTipControl.Activate(false /*activate*/); } - if (!value && (this.ShowRowErrors || this.ShowCellToolTips)) + if (!value && (ShowRowErrors || ShowCellToolTips)) { // reset the tool tip - this.toolTipControl.Activate(!string.IsNullOrEmpty(this.toolTipCaption)); + toolTipControl.Activate(!string.IsNullOrEmpty(toolTipCaption)); } // Some autosizing may have to be applied since the potential presence of error icons influences the preferred sizes. OnGlobalAutoSize(); } - if (!this.layout.dirty && !this.DesignMode) + if (!layout.dirty && !DesignMode) { - this.Invalidate(Rectangle.Union(this.layout.Data, this.layout.ColumnHeaders)); - this.Invalidate(this.layout.TopLeftHeader); + Invalidate(Rectangle.Union(layout.Data, layout.ColumnHeaders)); + Invalidate(layout.TopLeftHeader); } } } @@ -4488,45 +4488,45 @@ public bool ShowCellToolTips { get { - return this.dataGridViewState2[DATAGRIDVIEWSTATE2_showCellToolTips]; + return dataGridViewState2[DATAGRIDVIEWSTATE2_showCellToolTips]; } set { - if (this.ShowCellToolTips != value) + if (ShowCellToolTips != value) { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_showCellToolTips] = value; + dataGridViewState2[DATAGRIDVIEWSTATE2_showCellToolTips] = value; - if (this.IsHandleCreated && !this.DesignMode) + if (IsHandleCreated && !DesignMode) { - if (value && !this.ShowRowErrors && !this.ShowCellErrors) + if (value && !ShowRowErrors && !ShowCellErrors) { // the tool tip hasn't yet been activated // activate it now - this.toolTipControl.Activate(!string.IsNullOrEmpty(this.toolTipCaption) /*activate*/); + toolTipControl.Activate(!string.IsNullOrEmpty(toolTipCaption) /*activate*/); } - if (!value && !this.ShowRowErrors && !this.ShowCellErrors) + if (!value && !ShowRowErrors && !ShowCellErrors) { // there is no reason to keep the tool tip activated // deactivate it - this.toolTipCaption = string.Empty; - this.toolTipControl.Activate(false /*activate*/); + toolTipCaption = string.Empty; + toolTipControl.Activate(false /*activate*/); } - if (!value && (this.ShowRowErrors || this.ShowCellErrors)) + if (!value && (ShowRowErrors || ShowCellErrors)) { - bool activate = !string.IsNullOrEmpty(this.toolTipCaption); + bool activate = !string.IsNullOrEmpty(toolTipCaption); Point mouseCoord = System.Windows.Forms.Control.MousePosition; - activate &= this.ClientRectangle.Contains(PointToClient(mouseCoord)); + activate &= ClientRectangle.Contains(PointToClient(mouseCoord)); // reset the tool tip - this.toolTipControl.Activate(activate); + toolTipControl.Activate(activate); } } - if (!this.layout.dirty && !this.DesignMode) + if (!layout.dirty && !DesignMode) { - Invalidate(this.layout.Data); + Invalidate(layout.Data); } } } @@ -4541,31 +4541,31 @@ public bool ShowEditingIcon { get { - return this.dataGridViewState2[DATAGRIDVIEWSTATE2_showEditingIcon]; + return dataGridViewState2[DATAGRIDVIEWSTATE2_showEditingIcon]; } set { - if (this.ShowEditingIcon != value) + if (ShowEditingIcon != value) { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_showEditingIcon] = value; + dataGridViewState2[DATAGRIDVIEWSTATE2_showEditingIcon] = value; // invalidate the row header to pick up the new ShowEditingIcon value - if (this.RowHeadersVisible) + if (RowHeadersVisible) { - if (this.VirtualMode || this.DataSource != null) + if (VirtualMode || DataSource != null) { - if (this.IsCurrentRowDirty) + if (IsCurrentRowDirty) { - Debug.Assert(this.ptCurrentCell.Y >= 0); - InvalidateCellPrivate(-1, this.ptCurrentCell.Y); + Debug.Assert(ptCurrentCell.Y >= 0); + InvalidateCellPrivate(-1, ptCurrentCell.Y); } } else { - if (this.IsCurrentCellDirty) + if (IsCurrentCellDirty) { - Debug.Assert(this.ptCurrentCell.Y >= 0); - InvalidateCellPrivate(-1, this.ptCurrentCell.Y); + Debug.Assert(ptCurrentCell.Y >= 0); + InvalidateCellPrivate(-1, ptCurrentCell.Y); } } } @@ -4582,41 +4582,41 @@ public bool ShowRowErrors { get { - return this.dataGridViewState2[DATAGRIDVIEWSTATE2_showRowErrors]; + return dataGridViewState2[DATAGRIDVIEWSTATE2_showRowErrors]; } set { - if (this.ShowRowErrors != value) + if (ShowRowErrors != value) { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_showRowErrors] = value; + dataGridViewState2[DATAGRIDVIEWSTATE2_showRowErrors] = value; - if (this.IsHandleCreated && !this.DesignMode) + if (IsHandleCreated && !DesignMode) { - if (value && !this.ShowCellErrors && !this.ShowCellToolTips) + if (value && !ShowCellErrors && !ShowCellToolTips) { // the tool tip hasn't yet been activated // activate it now - this.toolTipControl.Activate(!string.IsNullOrEmpty(this.toolTipCaption)); + toolTipControl.Activate(!string.IsNullOrEmpty(toolTipCaption)); } - if (!value && !this.ShowCellErrors && !this.ShowCellToolTips) + if (!value && !ShowCellErrors && !ShowCellToolTips) { // there is no reason to keep the tool tip activated // deactivate it - this.toolTipCaption = string.Empty; - this.toolTipControl.Activate(false /*activate*/); + toolTipCaption = string.Empty; + toolTipControl.Activate(false /*activate*/); } - if (!value && (this.ShowCellErrors || this.ShowCellToolTips)) + if (!value && (ShowCellErrors || ShowCellToolTips)) { // reset the tool tip - this.toolTipControl.Activate(!string.IsNullOrEmpty(this.toolTipCaption)); + toolTipControl.Activate(!string.IsNullOrEmpty(toolTipCaption)); } } - if (!this.layout.dirty && !this.DesignMode) + if (!layout.dirty && !DesignMode) { - Invalidate(this.layout.RowHeaders); + Invalidate(layout.RowHeaders); } } } @@ -4626,9 +4626,9 @@ internal bool SingleHorizontalBorderAdded { get { - return !this.layout.ColumnHeadersVisible && - (this.AdvancedCellBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Single || - this.CellBorderStyle == DataGridViewCellBorderStyle.SingleHorizontal); + return !layout.ColumnHeadersVisible && + (AdvancedCellBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Single || + CellBorderStyle == DataGridViewCellBorderStyle.SingleHorizontal); } } @@ -4636,9 +4636,9 @@ internal bool SingleVerticalBorderAdded { get { - return !this.layout.RowHeadersVisible && - (this.AdvancedCellBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Single || - this.CellBorderStyle == DataGridViewCellBorderStyle.SingleVertical); + return !layout.RowHeadersVisible && + (AdvancedCellBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Single || + CellBorderStyle == DataGridViewCellBorderStyle.SingleVertical); } } @@ -4649,7 +4649,7 @@ public DataGridViewColumn SortedColumn { get { - return this.sortedColumn; + return sortedColumn; } } @@ -4660,7 +4660,7 @@ public SortOrder SortOrder { get { - return this.sortOrder; + return sortOrder; } } @@ -4678,13 +4678,13 @@ public bool StandardTab { get { - return this.dataGridViewState1[DATAGRIDVIEWSTATE1_standardTab]; + return dataGridViewState1[DATAGRIDVIEWSTATE1_standardTab]; } set { - if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_standardTab] != value) + if (dataGridViewState1[DATAGRIDVIEWSTATE1_standardTab] != value) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_standardTab] = value; + dataGridViewState1[DATAGRIDVIEWSTATE1_standardTab] = value; //OnStandardTabChanged(EventArgs.Empty); } } @@ -4728,12 +4728,12 @@ public override string Text { get { - DataGridViewRow row = this.Rows[rowIndex]; + DataGridViewRow row = Rows[rowIndex]; return row.Cells[columnIndex]; } set { - DataGridViewRow row = this.Rows[rowIndex]; + DataGridViewRow row = Rows[rowIndex]; row.Cells[columnIndex] = value; } } @@ -4747,12 +4747,12 @@ public override string Text { get { - DataGridViewRow row = this.Rows[rowIndex]; + DataGridViewRow row = Rows[rowIndex]; return row.Cells[columnName]; } set { - DataGridViewRow row = this.Rows[rowIndex]; + DataGridViewRow row = Rows[rowIndex]; row.Cells[columnName] = value; } } @@ -4761,7 +4761,7 @@ private string ToolTipPrivate { get { - return this.toolTipCaption; + return toolTipCaption; } } @@ -4773,33 +4773,33 @@ public DataGridViewHeaderCell TopLeftHeaderCell { get { - if (this.topLeftHeaderCell == null) + if (topLeftHeaderCell == null) { - this.TopLeftHeaderCell = new DataGridViewTopLeftHeaderCell(); + TopLeftHeaderCell = new DataGridViewTopLeftHeaderCell(); } - return this.topLeftHeaderCell; + return topLeftHeaderCell; } set { - if (this.topLeftHeaderCell != value) + if (topLeftHeaderCell != value) { - if (this.topLeftHeaderCell != null) + if (topLeftHeaderCell != null) { // Detach existing header cell - this.topLeftHeaderCell.DataGridViewInternal = null; + topLeftHeaderCell.DataGridViewInternal = null; } - this.topLeftHeaderCell = value; + topLeftHeaderCell = value; if (value != null) { - this.topLeftHeaderCell.DataGridViewInternal = this; + topLeftHeaderCell.DataGridViewInternal = this; } - if (this.ColumnHeadersVisible && this.RowHeadersVisible) + if (ColumnHeadersVisible && RowHeadersVisible) { // If headers (rows or columns) are autosized, then this.RowHeadersWidth or this.ColumnHeadersHeight // must be updated based on new cell preferred size OnColumnHeadersGlobalAutoSize(); // In all cases, the top left cell needs to repaint - Invalidate(new Rectangle(this.layout.Inside.X, this.layout.Inside.Y, this.RowHeadersWidth, this.ColumnHeadersHeight)); + Invalidate(new Rectangle(layout.Inside.X, layout.Inside.Y, RowHeadersWidth, ColumnHeadersHeight)); } } } @@ -4813,13 +4813,13 @@ public Cursor UserSetCursor { get { - if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet]) + if (dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet]) { - return this.oldCursor; + return oldCursor; } else { - return this.Cursor; + return Cursor; } } } @@ -4828,7 +4828,7 @@ internal int VerticalOffset { get { - return this.verticalOffset; + return verticalOffset; } set { @@ -4836,21 +4836,21 @@ internal int VerticalOffset { value = 0; } - int totalVisibleFrozenHeight = this.Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int totalVisibleFrozenHeight = Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); int fittingTrailingScrollingRowsHeight = ComputeHeightOfFittingTrailingScrollingRows(totalVisibleFrozenHeight); - if (value > this.vertScrollBar.Maximum - fittingTrailingScrollingRowsHeight) + if (value > vertScrollBar.Maximum - fittingTrailingScrollingRowsHeight) { - value = this.vertScrollBar.Maximum - fittingTrailingScrollingRowsHeight; + value = vertScrollBar.Maximum - fittingTrailingScrollingRowsHeight; } - if (value == this.verticalOffset) + if (value == verticalOffset) { return; } - int change = value - this.verticalOffset; - if (this.vertScrollBar.Enabled) + int change = value - verticalOffset; + if (vertScrollBar.Enabled) { - this.vertScrollBar.Value = value; + vertScrollBar.Value = value; } ScrollRowsByHeight(change); // calculate how many rows need to be scrolled based on 'change' } @@ -4860,7 +4860,7 @@ protected ScrollBar VerticalScrollBar { get { - return this.vertScrollBar; + return vertScrollBar; } } @@ -4872,7 +4872,7 @@ public int VerticalScrollingOffset { get { - return this.verticalOffset; + return verticalOffset; } } @@ -4880,12 +4880,12 @@ private System.Windows.Forms.Timer VertScrollTimer { get { - if (this.vertScrollTimer == null) + if (vertScrollTimer == null) { - this.vertScrollTimer = new System.Windows.Forms.Timer(); - this.vertScrollTimer.Tick += new System.EventHandler(VertScrollTimer_Tick); + vertScrollTimer = new System.Windows.Forms.Timer(); + vertScrollTimer.Tick += new System.EventHandler(VertScrollTimer_Tick); } - return this.vertScrollTimer; + return vertScrollTimer; } } @@ -4903,13 +4903,13 @@ public bool VirtualMode { get { - return this.dataGridViewState1[DATAGRIDVIEWSTATE1_virtualMode]; + return dataGridViewState1[DATAGRIDVIEWSTATE1_virtualMode]; } set { - if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_virtualMode] != value) + if (dataGridViewState1[DATAGRIDVIEWSTATE1_virtualMode] != value) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_virtualMode] = value; + dataGridViewState1[DATAGRIDVIEWSTATE1_virtualMode] = value; InvalidateRowHeights(); //OnVirtualModeChanged(EventArgs.Empty); } @@ -4920,11 +4920,11 @@ private bool VisibleCellExists { get { - if (null == this.Columns.GetFirstColumn(DataGridViewElementStates.Visible)) + if (null == Columns.GetFirstColumn(DataGridViewElementStates.Visible)) { return false; } - return -1 != this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + return -1 != Rows.GetFirstRow(DataGridViewElementStates.Visible); } } @@ -4936,8 +4936,8 @@ private bool VisibleCellExists ] public event DataGridViewAutoSizeColumnModeEventHandler AutoSizeColumnModeChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWAUTOSIZECOLUMNMODECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWAUTOSIZECOLUMNMODECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWAUTOSIZECOLUMNMODECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWAUTOSIZECOLUMNMODECHANGED, value); } [ @@ -4946,8 +4946,8 @@ public event DataGridViewAutoSizeColumnModeEventHandler AutoSizeColumnModeChange ] public event QuestionEventHandler CancelRowEdit { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCANCELROWEDIT, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCANCELROWEDIT, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCANCELROWEDIT, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCANCELROWEDIT, value); } [ @@ -4956,8 +4956,8 @@ public event QuestionEventHandler CancelRowEdit ] public event DataGridViewCellCancelEventHandler CellBeginEdit { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLBEGINEDIT, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLBEGINEDIT, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLBEGINEDIT, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLBEGINEDIT, value); } [ @@ -4966,8 +4966,8 @@ public event DataGridViewCellCancelEventHandler CellBeginEdit ] public event DataGridViewCellEventHandler CellClick { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLCLICK, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLCLICK, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLCLICK, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLCLICK, value); } [ @@ -4976,8 +4976,8 @@ public event DataGridViewCellEventHandler CellClick ] public event DataGridViewCellEventHandler CellContentClick { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLCONTENTCLICK, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLCONTENTCLICK, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLCONTENTCLICK, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLCONTENTCLICK, value); } [ @@ -4986,8 +4986,8 @@ public event DataGridViewCellEventHandler CellContentClick ] public event DataGridViewCellEventHandler CellContentDoubleClick { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLCONTENTDOUBLECLICK, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLCONTENTDOUBLECLICK, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLCONTENTDOUBLECLICK, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLCONTENTDOUBLECLICK, value); } [ @@ -4997,8 +4997,8 @@ public event DataGridViewCellEventHandler CellContentDoubleClick ] public event DataGridViewCellEventHandler CellContextMenuStripChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLCONTEXTMENUSTRIPCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLCONTEXTMENUSTRIPCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLCONTEXTMENUSTRIPCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLCONTEXTMENUSTRIPCHANGED, value); } [ @@ -5008,8 +5008,8 @@ public event DataGridViewCellEventHandler CellContextMenuStripChanged ] public event DataGridViewCellContextMenuStripNeededEventHandler CellContextMenuStripNeeded { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLCONTEXTMENUSTRIPNEEDED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLCONTEXTMENUSTRIPNEEDED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLCONTEXTMENUSTRIPNEEDED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLCONTEXTMENUSTRIPNEEDED, value); } [ @@ -5018,8 +5018,8 @@ public event DataGridViewCellContextMenuStripNeededEventHandler CellContextMenuS ] public event DataGridViewCellEventHandler CellDoubleClick { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLDOUBLECLICK, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLDOUBLECLICK, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLDOUBLECLICK, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLDOUBLECLICK, value); } [ @@ -5028,8 +5028,8 @@ public event DataGridViewCellEventHandler CellDoubleClick ] public event DataGridViewCellEventHandler CellEndEdit { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLENDEDIT, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLENDEDIT, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLENDEDIT, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLENDEDIT, value); } [ @@ -5038,8 +5038,8 @@ public event DataGridViewCellEventHandler CellEndEdit ] public event DataGridViewCellEventHandler CellEnter { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLENTER, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLENTER, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLENTER, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLENTER, value); } [ @@ -5048,8 +5048,8 @@ public event DataGridViewCellEventHandler CellEnter ] public event DataGridViewCellEventHandler CellErrorTextChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLERRORTEXTCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLERRORTEXTCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLERRORTEXTCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLERRORTEXTCHANGED, value); } [ @@ -5059,8 +5059,8 @@ public event DataGridViewCellEventHandler CellErrorTextChanged ] public event DataGridViewCellErrorTextNeededEventHandler CellErrorTextNeeded { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLERRORTEXTNEEDED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLERRORTEXTNEEDED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLERRORTEXTNEEDED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLERRORTEXTNEEDED, value); } [ @@ -5069,8 +5069,8 @@ public event DataGridViewCellErrorTextNeededEventHandler CellErrorTextNeeded ] public event DataGridViewCellFormattingEventHandler CellFormatting { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLFORMATTING, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLFORMATTING, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLFORMATTING, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLFORMATTING, value); } [ @@ -5079,8 +5079,8 @@ public event DataGridViewCellFormattingEventHandler CellFormatting ] public event DataGridViewCellEventHandler CellLeave { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLLEAVE, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLLEAVE, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLLEAVE, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLLEAVE, value); } [ @@ -5089,8 +5089,8 @@ public event DataGridViewCellEventHandler CellLeave ] public event DataGridViewCellMouseEventHandler CellMouseClick { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLMOUSECLICK, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLMOUSECLICK, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLMOUSECLICK, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLMOUSECLICK, value); } [ @@ -5099,8 +5099,8 @@ public event DataGridViewCellMouseEventHandler CellMouseClick ] public event DataGridViewCellMouseEventHandler CellMouseDoubleClick { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLMOUSEDOUBLECLICK, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLMOUSEDOUBLECLICK, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLMOUSEDOUBLECLICK, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLMOUSEDOUBLECLICK, value); } [ @@ -5109,8 +5109,8 @@ public event DataGridViewCellMouseEventHandler CellMouseDoubleClick ] public event DataGridViewCellMouseEventHandler CellMouseDown { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLMOUSEDOWN, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLMOUSEDOWN, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLMOUSEDOWN, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLMOUSEDOWN, value); } [ @@ -5119,8 +5119,8 @@ public event DataGridViewCellMouseEventHandler CellMouseDown ] public event DataGridViewCellEventHandler CellMouseEnter { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLMOUSEENTER, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLMOUSEENTER, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLMOUSEENTER, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLMOUSEENTER, value); } [ @@ -5129,8 +5129,8 @@ public event DataGridViewCellEventHandler CellMouseEnter ] public event DataGridViewCellEventHandler CellMouseLeave { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLMOUSELEAVE, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLMOUSELEAVE, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLMOUSELEAVE, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLMOUSELEAVE, value); } [ @@ -5139,8 +5139,8 @@ public event DataGridViewCellEventHandler CellMouseLeave ] public event DataGridViewCellMouseEventHandler CellMouseMove { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLMOUSEMOVE, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLMOUSEMOVE, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLMOUSEMOVE, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLMOUSEMOVE, value); } [ @@ -5149,8 +5149,8 @@ public event DataGridViewCellMouseEventHandler CellMouseMove ] public event DataGridViewCellMouseEventHandler CellMouseUp { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLMOUSEUP, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLMOUSEUP, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLMOUSEUP, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLMOUSEUP, value); } [ @@ -5159,8 +5159,8 @@ public event DataGridViewCellMouseEventHandler CellMouseUp ] public event DataGridViewCellPaintingEventHandler CellPainting { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLPAINTING, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLPAINTING, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLPAINTING, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLPAINTING, value); } [ @@ -5169,8 +5169,8 @@ public event DataGridViewCellPaintingEventHandler CellPainting ] public event DataGridViewCellParsingEventHandler CellParsing { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLPARSING, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLPARSING, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLPARSING, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLPARSING, value); } [ @@ -5179,8 +5179,8 @@ public event DataGridViewCellParsingEventHandler CellParsing ] public event DataGridViewCellStateChangedEventHandler CellStateChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLSTATECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLSTATECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLSTATECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLSTATECHANGED, value); } [ @@ -5189,8 +5189,8 @@ public event DataGridViewCellStateChangedEventHandler CellStateChanged ] public event DataGridViewCellEventHandler CellStyleChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLSTYLECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLSTYLECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLSTYLECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLSTYLECHANGED, value); } [ @@ -5199,8 +5199,8 @@ public event DataGridViewCellEventHandler CellStyleChanged ] public event DataGridViewCellStyleContentChangedEventHandler CellStyleContentChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLSTYLECONTENTCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLSTYLECONTENTCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLSTYLECONTENTCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLSTYLECONTENTCHANGED, value); } [ @@ -5209,8 +5209,8 @@ public event DataGridViewCellStyleContentChangedEventHandler CellStyleContentCha ] public event DataGridViewCellEventHandler CellToolTipTextChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLTOOLTIPTEXTCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLTOOLTIPTEXTCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLTOOLTIPTEXTCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLTOOLTIPTEXTCHANGED, value); } [ @@ -5220,8 +5220,8 @@ public event DataGridViewCellEventHandler CellToolTipTextChanged ] public event DataGridViewCellToolTipTextNeededEventHandler CellToolTipTextNeeded { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLTOOLTIPTEXTNEEDED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLTOOLTIPTEXTNEEDED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLTOOLTIPTEXTNEEDED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLTOOLTIPTEXTNEEDED, value); } [ @@ -5230,8 +5230,8 @@ public event DataGridViewCellToolTipTextNeededEventHandler CellToolTipTextNeeded ] public event DataGridViewCellEventHandler CellValidated { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLVALIDATED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLVALIDATED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLVALIDATED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLVALIDATED, value); } [ @@ -5240,8 +5240,8 @@ public event DataGridViewCellEventHandler CellValidated ] public event DataGridViewCellValidatingEventHandler CellValidating { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLVALIDATING, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLVALIDATING, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLVALIDATING, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLVALIDATING, value); } [ @@ -5250,8 +5250,8 @@ public event DataGridViewCellValidatingEventHandler CellValidating ] public event DataGridViewCellEventHandler CellValueChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLVALUECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLVALUECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLVALUECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLVALUECHANGED, value); } [ @@ -5261,8 +5261,8 @@ public event DataGridViewCellEventHandler CellValueChanged ] public event DataGridViewCellValueEventHandler CellValueNeeded { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLVALUENEEDED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLVALUENEEDED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLVALUENEEDED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLVALUENEEDED, value); } [ @@ -5272,8 +5272,8 @@ public event DataGridViewCellValueEventHandler CellValueNeeded ] public event DataGridViewCellValueEventHandler CellValuePushed { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCELLVALUEPUSHED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLVALUEPUSHED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCELLVALUEPUSHED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLVALUEPUSHED, value); } [ @@ -5282,8 +5282,8 @@ public event DataGridViewCellValueEventHandler CellValuePushed ] public event DataGridViewColumnEventHandler ColumnAdded { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNADDED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNADDED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNADDED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNADDED, value); } [ @@ -5292,8 +5292,8 @@ public event DataGridViewColumnEventHandler ColumnAdded ] public event DataGridViewColumnEventHandler ColumnContextMenuStripChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNCONTEXTMENUSTRIPCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNCONTEXTMENUSTRIPCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNCONTEXTMENUSTRIPCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNCONTEXTMENUSTRIPCHANGED, value); } [ @@ -5302,8 +5302,8 @@ public event DataGridViewColumnEventHandler ColumnContextMenuStripChanged ] public event DataGridViewColumnEventHandler ColumnDataPropertyNameChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNDATAPROPERTYNAMECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNDATAPROPERTYNAMECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNDATAPROPERTYNAMECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNDATAPROPERTYNAMECHANGED, value); } [ @@ -5312,8 +5312,8 @@ public event DataGridViewColumnEventHandler ColumnDataPropertyNameChanged ] public event DataGridViewColumnEventHandler ColumnDefaultCellStyleChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNDEFAULTCELLSTYLECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNDEFAULTCELLSTYLECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNDEFAULTCELLSTYLECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNDEFAULTCELLSTYLECHANGED, value); } [ @@ -5322,8 +5322,8 @@ public event DataGridViewColumnEventHandler ColumnDefaultCellStyleChanged ] public event DataGridViewColumnEventHandler ColumnDisplayIndexChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNDISPLAYINDEXCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNDISPLAYINDEXCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNDISPLAYINDEXCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNDISPLAYINDEXCHANGED, value); } [ @@ -5332,8 +5332,8 @@ public event DataGridViewColumnEventHandler ColumnDisplayIndexChanged ] public event DataGridViewColumnDividerDoubleClickEventHandler ColumnDividerDoubleClick { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNDIVIDERDOUBLECLICK, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNDIVIDERDOUBLECLICK, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNDIVIDERDOUBLECLICK, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNDIVIDERDOUBLECLICK, value); } [ @@ -5342,8 +5342,8 @@ public event DataGridViewColumnDividerDoubleClickEventHandler ColumnDividerDoubl ] public event DataGridViewColumnEventHandler ColumnDividerWidthChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNDIVIDERWIDTHCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNDIVIDERWIDTHCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNDIVIDERWIDTHCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNDIVIDERWIDTHCHANGED, value); } [ @@ -5352,8 +5352,8 @@ public event DataGridViewColumnEventHandler ColumnDividerWidthChanged ] public event DataGridViewCellMouseEventHandler ColumnHeaderMouseClick { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERMOUSECLICK, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERMOUSECLICK, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERMOUSECLICK, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERMOUSECLICK, value); } [ @@ -5362,8 +5362,8 @@ public event DataGridViewCellMouseEventHandler ColumnHeaderMouseClick ] public event DataGridViewCellMouseEventHandler ColumnHeaderMouseDoubleClick { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERMOUSEDOUBLECLICK, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERMOUSEDOUBLECLICK, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERMOUSEDOUBLECLICK, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERMOUSEDOUBLECLICK, value); } [ @@ -5372,8 +5372,8 @@ public event DataGridViewCellMouseEventHandler ColumnHeaderMouseDoubleClick ] public event DataGridViewColumnEventHandler ColumnHeaderCellChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERCELLCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERCELLCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERCELLCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNHEADERCELLCHANGED, value); } [ @@ -5382,8 +5382,8 @@ public event DataGridViewColumnEventHandler ColumnHeaderCellChanged ] public event DataGridViewColumnEventHandler ColumnMinimumWidthChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNMINIMUMWIDTHCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNMINIMUMWIDTHCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNMINIMUMWIDTHCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNMINIMUMWIDTHCHANGED, value); } [ @@ -5392,8 +5392,8 @@ public event DataGridViewColumnEventHandler ColumnMinimumWidthChanged ] public event DataGridViewColumnEventHandler ColumnNameChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNNAMECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNNAMECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNNAMECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNNAMECHANGED, value); } [ @@ -5402,8 +5402,8 @@ public event DataGridViewColumnEventHandler ColumnNameChanged ] public event DataGridViewColumnEventHandler ColumnRemoved { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNREMOVED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNREMOVED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNREMOVED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNREMOVED, value); } /* @@ -5419,8 +5419,8 @@ public event EventHandler ColumnsDefaultCellStyleChanged ] public event DataGridViewColumnEventHandler ColumnSortModeChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNSORTMODECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNSORTMODECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNSORTMODECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNSORTMODECHANGED, value); } [ @@ -5429,8 +5429,8 @@ public event DataGridViewColumnEventHandler ColumnSortModeChanged ] public event DataGridViewColumnStateChangedEventHandler ColumnStateChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNSTATECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNSTATECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNSTATECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNSTATECHANGED, value); } [ @@ -5439,8 +5439,8 @@ public event DataGridViewColumnStateChangedEventHandler ColumnStateChanged ] public event DataGridViewColumnEventHandler ColumnToolTipTextChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNTOOLTIPTEXTCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNTOOLTIPTEXTCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNTOOLTIPTEXTCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNTOOLTIPTEXTCHANGED, value); } [ @@ -5449,8 +5449,8 @@ public event DataGridViewColumnEventHandler ColumnToolTipTextChanged ] public event DataGridViewColumnEventHandler ColumnWidthChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNWIDTHCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNWIDTHCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCOLUMNWIDTHCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCOLUMNWIDTHCHANGED, value); } [ @@ -5459,8 +5459,8 @@ public event DataGridViewColumnEventHandler ColumnWidthChanged ] public event EventHandler CurrentCellChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCURRENTCELLCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCURRENTCELLCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCURRENTCELLCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCURRENTCELLCHANGED, value); } [ @@ -5470,8 +5470,8 @@ public event EventHandler CurrentCellChanged ] public event EventHandler CurrentCellDirtyStateChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWCURRENTCELLDIRTYSTATECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWCURRENTCELLDIRTYSTATECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWCURRENTCELLDIRTYSTATECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWCURRENTCELLDIRTYSTATECHANGED, value); } [ @@ -5480,8 +5480,8 @@ public event EventHandler CurrentCellDirtyStateChanged ] public event DataGridViewBindingCompleteEventHandler DataBindingComplete { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWDATABINDINGCOMPLETE, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWDATABINDINGCOMPLETE, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWDATABINDINGCOMPLETE, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWDATABINDINGCOMPLETE, value); } [ @@ -5490,8 +5490,8 @@ public event DataGridViewBindingCompleteEventHandler DataBindingComplete ] public event DataGridViewDataErrorEventHandler DataError { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWDATAERROR, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWDATAERROR, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWDATAERROR, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWDATAERROR, value); } [ @@ -5501,8 +5501,8 @@ public event DataGridViewDataErrorEventHandler DataError ] public event DataGridViewRowEventHandler DefaultValuesNeeded { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWDEFAULTVALUESNEEDED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWDEFAULTVALUESNEEDED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWDEFAULTVALUESNEEDED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWDEFAULTVALUESNEEDED, value); } [ @@ -5511,8 +5511,8 @@ public event DataGridViewRowEventHandler DefaultValuesNeeded ] public event DataGridViewEditingControlShowingEventHandler EditingControlShowing { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWEDITINGCONTROLSHOWING, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWEDITINGCONTROLSHOWING, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWEDITINGCONTROLSHOWING, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWEDITINGCONTROLSHOWING, value); } /* @@ -5535,8 +5535,8 @@ public event EventHandler NewRowDiscarded ] public event DataGridViewRowEventHandler NewRowNeeded { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWNEWROWNEEDED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWNEWROWNEEDED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWNEWROWNEEDED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWNEWROWNEEDED, value); } [ @@ -5545,8 +5545,8 @@ public event DataGridViewRowEventHandler NewRowNeeded ] public event DataGridViewRowEventHandler RowContextMenuStripChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWCONTEXTMENUSTRIPCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWCONTEXTMENUSTRIPCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWCONTEXTMENUSTRIPCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWCONTEXTMENUSTRIPCHANGED, value); } [ @@ -5556,8 +5556,8 @@ public event DataGridViewRowEventHandler RowContextMenuStripChanged ] public event DataGridViewRowContextMenuStripNeededEventHandler RowContextMenuStripNeeded { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWCONTEXTMENUSTRIPNEEDED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWCONTEXTMENUSTRIPNEEDED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWCONTEXTMENUSTRIPNEEDED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWCONTEXTMENUSTRIPNEEDED, value); } [ @@ -5566,8 +5566,8 @@ public event DataGridViewRowContextMenuStripNeededEventHandler RowContextMenuStr ] public event DataGridViewRowEventHandler RowDefaultCellStyleChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWDEFAULTCELLSTYLECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWDEFAULTCELLSTYLECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWDEFAULTCELLSTYLECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWDEFAULTCELLSTYLECHANGED, value); } [ @@ -5577,8 +5577,8 @@ public event DataGridViewRowEventHandler RowDefaultCellStyleChanged ] public event QuestionEventHandler RowDirtyStateNeeded { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWDIRTYSTATENEEDED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWDIRTYSTATENEEDED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWDIRTYSTATENEEDED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWDIRTYSTATENEEDED, value); } [ @@ -5587,8 +5587,8 @@ public event QuestionEventHandler RowDirtyStateNeeded ] public event DataGridViewRowDividerDoubleClickEventHandler RowDividerDoubleClick { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWDIVIDERDOUBLECLICK, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWDIVIDERDOUBLECLICK, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWDIVIDERDOUBLECLICK, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWDIVIDERDOUBLECLICK, value); } [ @@ -5597,8 +5597,8 @@ public event DataGridViewRowDividerDoubleClickEventHandler RowDividerDoubleClick ] public event DataGridViewRowEventHandler RowDividerHeightChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWDIVIDERHEIGHTCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWDIVIDERHEIGHTCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWDIVIDERHEIGHTCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWDIVIDERHEIGHTCHANGED, value); } [ @@ -5607,8 +5607,8 @@ public event DataGridViewRowEventHandler RowDividerHeightChanged ] public event DataGridViewCellEventHandler RowEnter { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWENTER, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWENTER, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWENTER, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWENTER, value); } [ @@ -5617,8 +5617,8 @@ public event DataGridViewCellEventHandler RowEnter ] public event DataGridViewRowEventHandler RowErrorTextChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWERRORTEXTCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWERRORTEXTCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWERRORTEXTCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWERRORTEXTCHANGED, value); } [ @@ -5628,8 +5628,8 @@ public event DataGridViewRowEventHandler RowErrorTextChanged ] public event DataGridViewRowErrorTextNeededEventHandler RowErrorTextNeeded { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWERRORTEXTNEEDED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWERRORTEXTNEEDED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWERRORTEXTNEEDED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWERRORTEXTNEEDED, value); } [ @@ -5638,8 +5638,8 @@ public event DataGridViewRowErrorTextNeededEventHandler RowErrorTextNeeded ] public event DataGridViewCellMouseEventHandler RowHeaderMouseClick { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWHEADERMOUSECLICK, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEADERMOUSECLICK, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWHEADERMOUSECLICK, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEADERMOUSECLICK, value); } [ @@ -5648,8 +5648,8 @@ public event DataGridViewCellMouseEventHandler RowHeaderMouseClick ] public event DataGridViewCellMouseEventHandler RowHeaderMouseDoubleClick { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWHEADERMOUSEDOUBLECLICK, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEADERMOUSEDOUBLECLICK, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWHEADERMOUSEDOUBLECLICK, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEADERMOUSEDOUBLECLICK, value); } [ @@ -5658,8 +5658,8 @@ public event DataGridViewCellMouseEventHandler RowHeaderMouseDoubleClick ] public event DataGridViewRowEventHandler RowHeaderCellChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWHEADERCELLCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEADERCELLCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWHEADERCELLCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEADERCELLCHANGED, value); } [ @@ -5668,8 +5668,8 @@ public event DataGridViewRowEventHandler RowHeaderCellChanged ] public event DataGridViewRowEventHandler RowHeightChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWHEIGHTCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEIGHTCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWHEIGHTCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEIGHTCHANGED, value); } [ @@ -5679,19 +5679,19 @@ public event DataGridViewRowEventHandler RowHeightChanged ] public event DataGridViewRowHeightInfoNeededEventHandler RowHeightInfoNeeded { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWHEIGHTINFONEEDED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEIGHTINFONEEDED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWHEIGHTINFONEEDED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEIGHTINFONEEDED, value); } internal DataGridViewRowHeightInfoNeededEventArgs RowHeightInfoNeededEventArgs { get { - if (this.dgvrhine == null) + if (dgvrhine == null) { - this.dgvrhine = new DataGridViewRowHeightInfoNeededEventArgs(); + dgvrhine = new DataGridViewRowHeightInfoNeededEventArgs(); } - return this.dgvrhine; + return dgvrhine; } } @@ -5702,8 +5702,8 @@ internal DataGridViewRowHeightInfoNeededEventArgs RowHeightInfoNeededEventArgs ] public event DataGridViewRowHeightInfoPushedEventHandler RowHeightInfoPushed { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWHEIGHTINFOPUSHED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEIGHTINFOPUSHED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWHEIGHTINFOPUSHED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWHEIGHTINFOPUSHED, value); } [ @@ -5712,8 +5712,8 @@ public event DataGridViewRowHeightInfoPushedEventHandler RowHeightInfoPushed ] public event DataGridViewCellEventHandler RowLeave { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWLEAVE, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWLEAVE, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWLEAVE, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWLEAVE, value); } [ @@ -5722,8 +5722,8 @@ public event DataGridViewCellEventHandler RowLeave ] public event DataGridViewRowEventHandler RowMinimumHeightChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWMINIMUMHEIGHTCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWMINIMUMHEIGHTCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWMINIMUMHEIGHTCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWMINIMUMHEIGHTCHANGED, value); } [ @@ -5732,19 +5732,19 @@ public event DataGridViewRowEventHandler RowMinimumHeightChanged ] public event DataGridViewRowPostPaintEventHandler RowPostPaint { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWPOSTPAINT, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWPOSTPAINT, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWPOSTPAINT, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWPOSTPAINT, value); } internal DataGridViewRowPostPaintEventArgs RowPostPaintEventArgs { get { - if (this.dgvrpope == null) + if (dgvrpope == null) { - this.dgvrpope = new DataGridViewRowPostPaintEventArgs(this); + dgvrpope = new DataGridViewRowPostPaintEventArgs(this); } - return this.dgvrpope; + return dgvrpope; } } @@ -5754,19 +5754,19 @@ internal DataGridViewRowPostPaintEventArgs RowPostPaintEventArgs ] public event DataGridViewRowPrePaintEventHandler RowPrePaint { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWPREPAINT, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWPREPAINT, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWPREPAINT, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWPREPAINT, value); } internal DataGridViewRowPrePaintEventArgs RowPrePaintEventArgs { get { - if (this.dgvrprpe == null) + if (dgvrprpe == null) { - this.dgvrprpe = new DataGridViewRowPrePaintEventArgs(this); + dgvrprpe = new DataGridViewRowPrePaintEventArgs(this); } - return this.dgvrprpe; + return dgvrprpe; } } @@ -5776,8 +5776,8 @@ internal DataGridViewRowPrePaintEventArgs RowPrePaintEventArgs ] public event DataGridViewRowsAddedEventHandler RowsAdded { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWSADDED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWSADDED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWSADDED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWSADDED, value); } [ @@ -5786,8 +5786,8 @@ public event DataGridViewRowsAddedEventHandler RowsAdded ] public event DataGridViewRowsRemovedEventHandler RowsRemoved { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWSREMOVED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWSREMOVED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWSREMOVED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWSREMOVED, value); } [ @@ -5796,8 +5796,8 @@ public event DataGridViewRowsRemovedEventHandler RowsRemoved ] public event DataGridViewRowStateChangedEventHandler RowStateChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWSTATECHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWSTATECHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWSTATECHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWSTATECHANGED, value); } [ @@ -5807,8 +5807,8 @@ public event DataGridViewRowStateChangedEventHandler RowStateChanged ] public event DataGridViewRowEventHandler RowUnshared { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWUNSHARED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWUNSHARED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWUNSHARED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWUNSHARED, value); } [ @@ -5817,8 +5817,8 @@ public event DataGridViewRowEventHandler RowUnshared ] public event DataGridViewCellEventHandler RowValidated { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWVALIDATED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWVALIDATED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWVALIDATED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWVALIDATED, value); } [ @@ -5827,8 +5827,8 @@ public event DataGridViewCellEventHandler RowValidated ] public event DataGridViewCellCancelEventHandler RowValidating { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWROWVALIDATING, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWROWVALIDATING, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWROWVALIDATING, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWROWVALIDATING, value); } [ @@ -5837,8 +5837,8 @@ public event DataGridViewCellCancelEventHandler RowValidating ] public event ScrollEventHandler Scroll { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWSCROLL, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWSCROLL, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWSCROLL, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWSCROLL, value); } [ @@ -5847,8 +5847,8 @@ public event ScrollEventHandler Scroll ] public event EventHandler SelectionChanged { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWSELECTIONCHANGED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWSELECTIONCHANGED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWSELECTIONCHANGED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWSELECTIONCHANGED, value); } [ @@ -5858,8 +5858,8 @@ public event EventHandler SelectionChanged ] public event DataGridViewSortCompareEventHandler SortCompare { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWSORTCOMPARE, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWSORTCOMPARE, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWSORTCOMPARE, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWSORTCOMPARE, value); } [ @@ -5868,8 +5868,8 @@ public event DataGridViewSortCompareEventHandler SortCompare ] public event EventHandler Sorted { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWSORTED, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWSORTED, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWSORTED, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWSORTED, value); } [ @@ -5888,8 +5888,8 @@ public event EventHandler Sorted ] public event DataGridViewRowEventHandler UserAddedRow { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWUSERADDEDROW, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWUSERADDEDROW, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWUSERADDEDROW, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWUSERADDEDROW, value); } /* @@ -5905,8 +5905,8 @@ public event DataGridViewRowCancelEventHandler UserAddingRow ] public event DataGridViewRowEventHandler UserDeletedRow { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWUSERDELETEDROW, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWUSERDELETEDROW, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWUSERDELETEDROW, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWUSERDELETEDROW, value); } [ @@ -5915,8 +5915,8 @@ public event DataGridViewRowEventHandler UserDeletedRow ] public event DataGridViewRowCancelEventHandler UserDeletingRow { - add => this.Events.AddHandler(EVENT_DATAGRIDVIEWUSERDELETINGROW, value); - remove => this.Events.RemoveHandler(EVENT_DATAGRIDVIEWUSERDELETINGROW, value); + add => Events.AddHandler(EVENT_DATAGRIDVIEWUSERDELETINGROW, value); + remove => Events.RemoveHandler(EVENT_DATAGRIDVIEWUSERDELETINGROW, value); } //////////////////////// @@ -5929,12 +5929,12 @@ public event DataGridViewRowCancelEventHandler UserDeletingRow ] void ISupportInitialize.BeginInit() { - if (this.dataGridViewState2[DATAGRIDVIEWSTATE2_initializing]) + if (dataGridViewState2[DATAGRIDVIEWSTATE2_initializing]) { throw new InvalidOperationException(SR.DataGridViewBeginInit); } - this.dataGridViewState2[DATAGRIDVIEWSTATE2_initializing] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_initializing] = true; } [ @@ -5942,9 +5942,9 @@ void ISupportInitialize.BeginInit() ] void ISupportInitialize.EndInit() { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_initializing] = false; + dataGridViewState2[DATAGRIDVIEWSTATE2_initializing] = false; - foreach (DataGridViewColumn dataGridViewColumn in this.Columns) + foreach (DataGridViewColumn dataGridViewColumn in Columns) { if (dataGridViewColumn.Frozen && dataGridViewColumn.Visible && @@ -5954,15 +5954,15 @@ void ISupportInitialize.EndInit() } } - DataGridViewSelectionMode selectionMode = this.SelectionMode; + DataGridViewSelectionMode selectionMode = SelectionMode; if (selectionMode == DataGridViewSelectionMode.FullColumnSelect || selectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) { - foreach (DataGridViewColumn dataGridViewColumn in this.Columns) + foreach (DataGridViewColumn dataGridViewColumn in Columns) { if (dataGridViewColumn.SortMode == DataGridViewColumnSortMode.Automatic) { // Resetting SelectionMode to its acceptable default value. We don't want the control to ever end up in an invalid state. - this.SelectionMode = defaultSelectionMode; // DataGridViewSelectionMode.RowHeaderSelect + SelectionMode = defaultSelectionMode; // DataGridViewSelectionMode.RowHeaderSelect throw new InvalidOperationException(string.Format(SR.DataGridView_SelectionModeReset, string.Format(SR.DataGridView_SelectionModeAndSortModeClash, (selectionMode).ToString()), (defaultSelectionMode).ToString())); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAccessibleObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAccessibleObject.cs index 6b967f3b6f9..2918d03c77b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAccessibleObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAccessibleObject.cs @@ -31,7 +31,7 @@ public override string Name [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] // Don't localize string "DataGridView". get { - string name = this.Owner.AccessibleName; + string name = Owner.AccessibleName; if (!string.IsNullOrEmpty(name)) { return name; @@ -63,12 +63,12 @@ private AccessibleObject TopRowAccessibilityObject { get { - if (this.topRowAccessibilityObject == null) + if (topRowAccessibilityObject == null) { - this.topRowAccessibilityObject = new DataGridViewTopRowAccessibleObject(this.owner); + topRowAccessibilityObject = new DataGridViewTopRowAccessibleObject(owner); } - return this.topRowAccessibilityObject; + return topRowAccessibilityObject; } } @@ -76,46 +76,46 @@ private AccessibleObject SelectedCellsAccessibilityObject { get { - if (this.selectedCellsAccessibilityObject == null) + if (selectedCellsAccessibilityObject == null) { - this.selectedCellsAccessibilityObject = new DataGridViewSelectedCellsAccessibleObject(this.owner); + selectedCellsAccessibilityObject = new DataGridViewSelectedCellsAccessibleObject(owner); } - return this.selectedCellsAccessibilityObject; + return selectedCellsAccessibilityObject; } } public override AccessibleObject GetChild(int index) { - if (this.owner.Columns.Count == 0) + if (owner.Columns.Count == 0) { - System.Diagnostics.Debug.Assert(this.GetChildCount() == 0); + System.Diagnostics.Debug.Assert(GetChildCount() == 0); return null; } - if (index < 1 && this.owner.ColumnHeadersVisible) + if (index < 1 && owner.ColumnHeadersVisible) { - return this.TopRowAccessibilityObject; + return TopRowAccessibilityObject; } - if (this.owner.ColumnHeadersVisible) + if (owner.ColumnHeadersVisible) { index--; } - if (index < this.owner.Rows.GetRowCount(DataGridViewElementStates.Visible)) + if (index < owner.Rows.GetRowCount(DataGridViewElementStates.Visible)) { - int actualRowIndex = this.owner.Rows.DisplayIndexToRowIndex(index); - return this.owner.Rows[actualRowIndex].AccessibilityObject; + int actualRowIndex = owner.Rows.DisplayIndexToRowIndex(index); + return owner.Rows[actualRowIndex].AccessibilityObject; } - index -= this.owner.Rows.GetRowCount(DataGridViewElementStates.Visible); + index -= owner.Rows.GetRowCount(DataGridViewElementStates.Visible); - if (this.owner.horizScrollBar.Visible) + if (owner.horizScrollBar.Visible) { if (index == 0) { - return this.owner.horizScrollBar.AccessibilityObject; + return owner.horizScrollBar.AccessibilityObject; } else { @@ -123,11 +123,11 @@ public override AccessibleObject GetChild(int index) } } - if (this.owner.vertScrollBar.Visible) + if (owner.vertScrollBar.Visible) { if (index == 0) { - return this.owner.vertScrollBar.AccessibilityObject; + return owner.vertScrollBar.AccessibilityObject; } } @@ -136,25 +136,25 @@ public override AccessibleObject GetChild(int index) public override int GetChildCount() { - if (this.owner.Columns.Count == 0) + if (owner.Columns.Count == 0) { return 0; } - int childCount = this.owner.Rows.GetRowCount(DataGridViewElementStates.Visible); + int childCount = owner.Rows.GetRowCount(DataGridViewElementStates.Visible); // the column header collection Accessible Object - if (this.owner.ColumnHeadersVisible) + if (owner.ColumnHeadersVisible) { childCount++; } - if (this.owner.horizScrollBar.Visible) + if (owner.horizScrollBar.Visible) { childCount++; } - if (this.owner.vertScrollBar.Visible) + if (owner.vertScrollBar.Visible) { childCount++; } @@ -164,9 +164,9 @@ public override int GetChildCount() public override AccessibleObject GetFocused() { - if (this.owner.Focused && this.owner.CurrentCell != null) + if (owner.Focused && owner.CurrentCell != null) { - return this.owner.CurrentCell.AccessibilityObject; + return owner.CurrentCell.AccessibilityObject; } else { @@ -176,38 +176,38 @@ public override AccessibleObject GetFocused() public override AccessibleObject GetSelected() { - return this.SelectedCellsAccessibilityObject; + return SelectedCellsAccessibilityObject; } public override AccessibleObject HitTest(int x, int y) { - Point pt = this.owner.PointToClient(new Point(x, y)); - HitTestInfo hti = this.owner.HitTest(pt.X, pt.Y); + Point pt = owner.PointToClient(new Point(x, y)); + HitTestInfo hti = owner.HitTest(pt.X, pt.Y); switch (hti.Type) { case DataGridViewHitTestType.Cell: - return this.owner.Rows[hti.RowIndex].Cells[hti.ColumnIndex].AccessibilityObject; + return owner.Rows[hti.RowIndex].Cells[hti.ColumnIndex].AccessibilityObject; case DataGridViewHitTestType.ColumnHeader: // map the column index to the actual display index - int actualDisplayIndex = this.owner.Columns.ColumnIndexToActualDisplayIndex(hti.ColumnIndex, DataGridViewElementStates.Visible); - if (this.owner.RowHeadersVisible) + int actualDisplayIndex = owner.Columns.ColumnIndexToActualDisplayIndex(hti.ColumnIndex, DataGridViewElementStates.Visible); + if (owner.RowHeadersVisible) { // increment the childIndex because the first child in the TopRowAccessibleObject is the TopLeftHeaderCellAccObj - return this.TopRowAccessibilityObject.GetChild(actualDisplayIndex + 1); + return TopRowAccessibilityObject.GetChild(actualDisplayIndex + 1); } else { - return this.TopRowAccessibilityObject.GetChild(actualDisplayIndex); + return TopRowAccessibilityObject.GetChild(actualDisplayIndex); } case DataGridViewHitTestType.RowHeader: - return this.owner.Rows[hti.RowIndex].AccessibilityObject; + return owner.Rows[hti.RowIndex].AccessibilityObject; case DataGridViewHitTestType.TopLeftHeader: - return this.owner.TopLeftHeaderCell.AccessibilityObject; + return owner.TopLeftHeaderCell.AccessibilityObject; case DataGridViewHitTestType.VerticalScrollBar: - return this.owner.VerticalScrollBar.AccessibilityObject; + return owner.VerticalScrollBar.AccessibilityObject; case DataGridViewHitTestType.HorizontalScrollBar: - return this.owner.HorizontalScrollBar.AccessibilityObject; + return owner.HorizontalScrollBar.AccessibilityObject; default: return null; } @@ -218,9 +218,9 @@ public override AccessibleObject Navigate(AccessibleNavigation navigationDirecti switch (navigationDirection) { case AccessibleNavigation.FirstChild: - return this.GetChild(0); + return GetChild(0); case AccessibleNavigation.LastChild: - return this.GetChild(this.GetChildCount() - 1); + return GetChild(GetChildCount() - 1); default: return null; } @@ -243,7 +243,7 @@ internal override int[] RuntimeId { runtimeId = new int[2]; runtimeId[0] = RuntimeIDFirstItem; // first item is static - 0x2a - runtimeId[1] = this.GetHashCode(); + runtimeId[1] = GetHashCode(); } return runtimeId; @@ -257,7 +257,7 @@ internal override object GetPropertyValue(int propertyID) switch (propertyID) { case NativeMethods.UIA_NamePropertyId: - return this.Name; + return Name; case NativeMethods.UIA_HasKeyboardFocusPropertyId: return false; // Only inner cell should be announced as focused by Narrator but not entire DGV. case NativeMethods.UIA_IsKeyboardFocusablePropertyId: @@ -318,30 +318,30 @@ internal override bool IsPatternSupported(int patternId) internal override UnsafeNativeMethods.IRawElementProviderSimple[] GetRowHeaders() { - if (!this.owner.RowHeadersVisible) + if (!owner.RowHeadersVisible) { return null; } - UnsafeNativeMethods.IRawElementProviderSimple[] result = new UnsafeNativeMethods.IRawElementProviderSimple[this.owner.Rows.Count]; - for (int i = 0; i < this.owner.Rows.Count; i++) + UnsafeNativeMethods.IRawElementProviderSimple[] result = new UnsafeNativeMethods.IRawElementProviderSimple[owner.Rows.Count]; + for (int i = 0; i < owner.Rows.Count; i++) { - result[i] = this.owner.Rows[i].HeaderCell.AccessibilityObject; + result[i] = owner.Rows[i].HeaderCell.AccessibilityObject; } return result; } internal override UnsafeNativeMethods.IRawElementProviderSimple[] GetColumnHeaders() { - if (!this.owner.ColumnHeadersVisible) + if (!owner.ColumnHeadersVisible) { return null; } - UnsafeNativeMethods.IRawElementProviderSimple[] result = new UnsafeNativeMethods.IRawElementProviderSimple[this.owner.Columns.Count]; - for (int i = 0; i < this.owner.Columns.Count; i++) + UnsafeNativeMethods.IRawElementProviderSimple[] result = new UnsafeNativeMethods.IRawElementProviderSimple[owner.Columns.Count]; + for (int i = 0; i < owner.Columns.Count; i++) { - result[i] = this.owner.Columns[i].HeaderCell.AccessibilityObject; + result[i] = owner.Columns[i].HeaderCell.AccessibilityObject; } return result; } @@ -356,10 +356,10 @@ internal override UnsafeNativeMethods.RowOrColumnMajor RowOrColumnMajor internal override UnsafeNativeMethods.IRawElementProviderSimple GetItem(int row, int column) { - if (row >= 0 && row < this.owner.Rows.Count && - column >= 0 && column < this.owner.Columns.Count) + if (row >= 0 && row < owner.Rows.Count && + column >= 0 && column < owner.Columns.Count) { - return this.owner.Rows[row].Cells[column].AccessibilityObject; + return owner.Rows[row].Cells[column].AccessibilityObject; } return null; @@ -369,7 +369,7 @@ internal override int RowCount { get { - return this.owner.RowCount; + return owner.RowCount; } } @@ -377,7 +377,7 @@ internal override int ColumnCount { get { - return this.owner.ColumnCount; + return owner.ColumnCount; } } @@ -387,7 +387,7 @@ internal override Rectangle BoundingRectangle { get { - return this.Bounds; + return Bounds; } } @@ -437,7 +437,7 @@ internal override void SetFocus() internal override UnsafeNativeMethods.IRawElementProviderFragment ElementProviderFromPoint(double x, double y) { - return this.HitTest((int)x, (int)y); + return HitTest((int)x, (int)y); } internal override UnsafeNativeMethods.IRawElementProviderFragment GetFocus() @@ -532,7 +532,7 @@ internal override object GetPropertyValue(int propertyId) case NativeMethods.UIA_IsKeyboardFocusablePropertyId: return true; case NativeMethods.UIA_HasKeyboardFocusPropertyId: - return this.dataGridView.CurrentCell != null; + return dataGridView.CurrentCell != null; case NativeMethods.UIA_IsEnabledPropertyId: return dataGridView.Enabled; case NativeMethods.UIA_IsOffscreenPropertyId: @@ -543,7 +543,7 @@ internal override object GetPropertyValue(int propertyId) case NativeMethods.UIA_IsPasswordPropertyId: return false; case NativeMethods.UIA_AccessKeyPropertyId: - return this.panel.AccessibilityObject.KeyboardShortcut; + return panel.AccessibilityObject.KeyboardShortcut; case NativeMethods.UIA_HelpTextPropertyId: return string.Empty; case NativeMethods.UIA_IsLegacyIAccessiblePatternAvailablePropertyId: diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAdvancedBorderStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAdvancedBorderStyle.cs index 340692ed24c..f2ad6825083 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAdvancedBorderStyle.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAdvancedBorderStyle.cs @@ -51,7 +51,7 @@ public DataGridViewAdvancedCellBorderStyle All { get { - return this.all ? this.top : DataGridViewAdvancedCellBorderStyle.NotSet; + return all ? top : DataGridViewAdvancedCellBorderStyle.NotSet; } set { @@ -62,19 +62,19 @@ public DataGridViewAdvancedCellBorderStyle All throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewAdvancedCellBorderStyle)); } if (value == DataGridViewAdvancedCellBorderStyle.NotSet || - value == this.banned1 || - value == this.banned2 || - value == this.banned3) + value == banned1 || + value == banned2 || + value == banned3) { throw new ArgumentException(string.Format(SR.DataGridView_AdvancedCellBorderStyleInvalid, "All")); } - if (!this.all || this.top != value) + if (!all || top != value) { - this.all = true; - this.top = this.left = this.right = this.bottom = value; - if (this.owner != null) + all = true; + top = left = right = bottom = value; + if (owner != null) { - this.owner.OnAdvancedBorderStyleChanged(this); + owner.OnAdvancedBorderStyleChanged(this); } } } @@ -84,11 +84,11 @@ public DataGridViewAdvancedCellBorderStyle Bottom { get { - if (this.all) + if (all) { - return this.top; + return top; } - return this.bottom; + return bottom; } set { @@ -101,7 +101,7 @@ public DataGridViewAdvancedCellBorderStyle Bottom { throw new ArgumentException(string.Format(SR.DataGridView_AdvancedCellBorderStyleInvalid, "Bottom")); } - this.BottomInternal = value; + BottomInternal = value; } } @@ -111,20 +111,20 @@ internal DataGridViewAdvancedCellBorderStyle BottomInternal { //Debug.Assert(Enum.IsDefined(typeof(DataGridViewAdvancedCellBorderStyle), value)); //Debug.Assert(value != DataGridViewAdvancedCellBorderStyle.NotSet); - if ((this.all && this.top != value) || (!this.all && this.bottom != value)) + if ((all && top != value) || (!all && bottom != value)) { - if (this.all) + if (all) { - if (this.right == DataGridViewAdvancedCellBorderStyle.OutsetDouble) + if (right == DataGridViewAdvancedCellBorderStyle.OutsetDouble) { - this.right = DataGridViewAdvancedCellBorderStyle.Outset; + right = DataGridViewAdvancedCellBorderStyle.Outset; } } - this.all = false; - this.bottom = value; - if (this.owner != null) + all = false; + bottom = value; + if (owner != null) { - this.owner.OnAdvancedBorderStyleChanged(this); + owner.OnAdvancedBorderStyleChanged(this); } } } @@ -134,11 +134,11 @@ public DataGridViewAdvancedCellBorderStyle Left { get { - if (this.all) + if (all) { - return this.top; + return top; } - return this.left; + return left; } set { @@ -151,7 +151,7 @@ public DataGridViewAdvancedCellBorderStyle Left { throw new ArgumentException(string.Format(SR.DataGridView_AdvancedCellBorderStyleInvalid, "Left")); } - this.LeftInternal = value; + LeftInternal = value; } } @@ -161,29 +161,29 @@ internal DataGridViewAdvancedCellBorderStyle LeftInternal { //Debug.Assert(Enum.IsDefined(typeof(DataGridViewAdvancedCellBorderStyle), value)); //Debug.Assert(value != DataGridViewAdvancedCellBorderStyle.NotSet); - if ((this.all && this.top != value) || (!this.all && this.left != value)) + if ((all && top != value) || (!all && left != value)) { - if ((this.owner != null && this.owner.RightToLeftInternal) && + if ((owner != null && owner.RightToLeftInternal) && (value == DataGridViewAdvancedCellBorderStyle.InsetDouble || value == DataGridViewAdvancedCellBorderStyle.OutsetDouble)) { throw new ArgumentException(string.Format(SR.DataGridView_AdvancedCellBorderStyleInvalid, "Left")); } - if (this.all) + if (all) { - if (this.right == DataGridViewAdvancedCellBorderStyle.OutsetDouble) + if (right == DataGridViewAdvancedCellBorderStyle.OutsetDouble) { - this.right = DataGridViewAdvancedCellBorderStyle.Outset; + right = DataGridViewAdvancedCellBorderStyle.Outset; } - if (this.bottom == DataGridViewAdvancedCellBorderStyle.OutsetDouble) + if (bottom == DataGridViewAdvancedCellBorderStyle.OutsetDouble) { - this.bottom = DataGridViewAdvancedCellBorderStyle.Outset; + bottom = DataGridViewAdvancedCellBorderStyle.Outset; } } - this.all = false; - this.left = value; - if (this.owner != null) + all = false; + left = value; + if (owner != null) { - this.owner.OnAdvancedBorderStyleChanged(this); + owner.OnAdvancedBorderStyleChanged(this); } } } @@ -193,11 +193,11 @@ public DataGridViewAdvancedCellBorderStyle Right { get { - if (this.all) + if (all) { - return this.top; + return top; } - return this.right; + return right; } set { @@ -211,7 +211,7 @@ public DataGridViewAdvancedCellBorderStyle Right { throw new ArgumentException(string.Format(SR.DataGridView_AdvancedCellBorderStyleInvalid, "Right")); } - this.RightInternal = value; + RightInternal = value; } } @@ -221,25 +221,25 @@ internal DataGridViewAdvancedCellBorderStyle RightInternal { //Debug.Assert(Enum.IsDefined(typeof(DataGridViewAdvancedCellBorderStyle), value)); //Debug.Assert(value != DataGridViewAdvancedCellBorderStyle.NotSet); - if ((this.all && this.top != value) || (!this.all && this.right != value)) + if ((all && top != value) || (!all && right != value)) { - if ((this.owner != null && !this.owner.RightToLeftInternal) && + if ((owner != null && !owner.RightToLeftInternal) && (value == DataGridViewAdvancedCellBorderStyle.InsetDouble || value == DataGridViewAdvancedCellBorderStyle.OutsetDouble)) { throw new ArgumentException(string.Format(SR.DataGridView_AdvancedCellBorderStyleInvalid, "Right")); } - if (this.all) + if (all) { - if (this.bottom == DataGridViewAdvancedCellBorderStyle.OutsetDouble) + if (bottom == DataGridViewAdvancedCellBorderStyle.OutsetDouble) { - this.bottom = DataGridViewAdvancedCellBorderStyle.Outset; + bottom = DataGridViewAdvancedCellBorderStyle.Outset; } } - this.all = false; - this.right = value; - if (this.owner != null) + all = false; + right = value; + if (owner != null) { - this.owner.OnAdvancedBorderStyleChanged(this); + owner.OnAdvancedBorderStyleChanged(this); } } } @@ -249,7 +249,7 @@ public DataGridViewAdvancedCellBorderStyle Top { get { - return this.top; + return top; } set { @@ -262,7 +262,7 @@ public DataGridViewAdvancedCellBorderStyle Top { throw new ArgumentException(string.Format(SR.DataGridView_AdvancedCellBorderStyleInvalid, "Top")); } - this.TopInternal = value; + TopInternal = value; } } @@ -272,24 +272,24 @@ internal DataGridViewAdvancedCellBorderStyle TopInternal { //Debug.Assert(Enum.IsDefined(typeof(DataGridViewAdvancedCellBorderStyle), value)); //Debug.Assert(value != DataGridViewAdvancedCellBorderStyle.NotSet); - if ((this.all && this.top != value) || (!this.all && this.top != value)) + if ((all && top != value) || (!all && top != value)) { - if (this.all) + if (all) { - if (this.right == DataGridViewAdvancedCellBorderStyle.OutsetDouble) + if (right == DataGridViewAdvancedCellBorderStyle.OutsetDouble) { - this.right = DataGridViewAdvancedCellBorderStyle.Outset; + right = DataGridViewAdvancedCellBorderStyle.Outset; } - if (this.bottom == DataGridViewAdvancedCellBorderStyle.OutsetDouble) + if (bottom == DataGridViewAdvancedCellBorderStyle.OutsetDouble) { - this.bottom = DataGridViewAdvancedCellBorderStyle.Outset; + bottom = DataGridViewAdvancedCellBorderStyle.Outset; } } - this.all = false; - this.top = value; - if (this.owner != null) + all = false; + top = value; + if (owner != null) { - this.owner.OnAdvancedBorderStyleChanged(this); + owner.OnAdvancedBorderStyleChanged(this); } } } @@ -304,28 +304,28 @@ public override bool Equals(object other) return false; } - return dgvabsOther.all == this.all && - dgvabsOther.top == this.top && - dgvabsOther.left == this.left && - dgvabsOther.bottom == this.bottom && - dgvabsOther.right == this.right; + return dgvabsOther.all == all && + dgvabsOther.top == top && + dgvabsOther.left == left && + dgvabsOther.bottom == bottom && + dgvabsOther.right == right; } public override int GetHashCode() => HashCode.Combine(top, left, bottom, right); public override string ToString() { - return "DataGridViewAdvancedBorderStyle { All=" + this.All.ToString() + ", Left=" + this.Left.ToString() + ", Right=" + this.Right.ToString() + ", Top=" + this.Top.ToString() + ", Bottom=" + this.Bottom.ToString() + " }"; + return "DataGridViewAdvancedBorderStyle { All=" + All.ToString() + ", Left=" + Left.ToString() + ", Right=" + Right.ToString() + ", Top=" + Top.ToString() + ", Bottom=" + Bottom.ToString() + " }"; } object ICloneable.Clone() { - DataGridViewAdvancedBorderStyle dgvabs = new DataGridViewAdvancedBorderStyle(this.owner, this.banned1, this.banned2, this.banned3); - dgvabs.all = this.all; - dgvabs.top = this.top; - dgvabs.right = this.right; - dgvabs.bottom = this.bottom; - dgvabs.left = this.left; + DataGridViewAdvancedBorderStyle dgvabs = new DataGridViewAdvancedBorderStyle(owner, banned1, banned2, banned3); + dgvabs.all = all; + dgvabs.top = top; + dgvabs.right = right; + dgvabs.bottom = bottom; + dgvabs.left = left; return dgvabs; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonCell.cs index 3b93ec7d5dd..db1eb83a90c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonCell.cs @@ -46,7 +46,7 @@ private ButtonState ButtonState get { bool found; - int buttonState = this.Properties.GetInteger(PropButtonCellState, out found); + int buttonState = Properties.GetInteger(PropButtonCellState, out found); if (found) { return (ButtonState)buttonState; @@ -58,9 +58,9 @@ private ButtonState ButtonState // ButtonState.Pushed is used for mouse interaction // ButtonState.Checked is used for keyboard interaction Debug.Assert((value & ~(ButtonState.Normal | ButtonState.Pushed | ButtonState.Checked)) == 0); - if (this.ButtonState != value) + if (ButtonState != value) { - this.Properties.SetInteger(PropButtonCellState, (int)value); + Properties.SetInteger(PropButtonCellState, (int)value); } } } @@ -82,7 +82,7 @@ public FlatStyle FlatStyle get { bool found; - int flatStyle = this.Properties.GetInteger(PropButtonCellFlatStyle, out found); + int flatStyle = Properties.GetInteger(PropButtonCellFlatStyle, out found); if (found) { return (FlatStyle)flatStyle; @@ -96,9 +96,9 @@ public FlatStyle FlatStyle { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(FlatStyle)); } - if (value != this.FlatStyle) + if (value != FlatStyle) { - this.Properties.SetInteger(PropButtonCellFlatStyle, (int)value); + Properties.SetInteger(PropButtonCellFlatStyle, (int)value); OnCommonChange(); } } @@ -109,9 +109,9 @@ internal FlatStyle FlatStyleInternal set { Debug.Assert(value >= FlatStyle.Flat && value <= FlatStyle.System); - if (value != this.FlatStyle) + if (value != FlatStyle) { - this.Properties.SetInteger(PropButtonCellFlatStyle, (int)value); + Properties.SetInteger(PropButtonCellFlatStyle, (int)value); } } } @@ -131,7 +131,7 @@ public bool UseColumnTextForButtonValue get { bool found; - int useColumnTextForButtonValue = this.Properties.GetInteger(PropButtonCellUseColumnTextForButtonValue, out found); + int useColumnTextForButtonValue = Properties.GetInteger(PropButtonCellUseColumnTextForButtonValue, out found); if (found) { return useColumnTextForButtonValue == 0 ? false : true; @@ -140,9 +140,9 @@ public bool UseColumnTextForButtonValue } set { - if (value != this.UseColumnTextForButtonValue) + if (value != UseColumnTextForButtonValue) { - this.Properties.SetInteger(PropButtonCellUseColumnTextForButtonValue, value ? 1 : 0); + Properties.SetInteger(PropButtonCellUseColumnTextForButtonValue, value ? 1 : 0); OnCommonChange(); } } @@ -152,9 +152,9 @@ internal bool UseColumnTextForButtonValueInternal { set { - if (value != this.UseColumnTextForButtonValue) + if (value != UseColumnTextForButtonValue) { - this.Properties.SetInteger(PropButtonCellUseColumnTextForButtonValue, value ? 1 : 0); + Properties.SetInteger(PropButtonCellUseColumnTextForButtonValue, value ? 1 : 0); } } } @@ -175,7 +175,7 @@ public override Type ValueType public override object Clone() { DataGridViewButtonCell dataGridViewCell; - Type thisType = this.GetType(); + Type thisType = GetType(); if (thisType == cellType) //performance improvement { @@ -186,8 +186,8 @@ public override object Clone() dataGridViewCell = (DataGridViewButtonCell)System.Activator.CreateInstance(thisType); } base.CloneInternal(dataGridViewCell); - dataGridViewCell.FlatStyleInternal = this.FlatStyle; - dataGridViewCell.UseColumnTextForButtonValueInternal = this.UseColumnTextForButtonValue; + dataGridViewCell.FlatStyleInternal = FlatStyle; + dataGridViewCell.UseColumnTextForButtonValueInternal = UseColumnTextForButtonValue; return dataGridViewCell; } @@ -203,7 +203,7 @@ protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCel throw new ArgumentNullException(nameof(cellStyle)); } - if (this.DataGridView == null || rowIndex < 0 || this.OwningColumn == null) + if (DataGridView == null || rowIndex < 0 || OwningColumn == null) { return Rectangle.Empty; } @@ -256,10 +256,10 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC throw new ArgumentNullException(nameof(cellStyle)); } - if (this.DataGridView == null || + if (DataGridView == null || rowIndex < 0 || - this.OwningColumn == null || - !this.DataGridView.ShowCellErrors || + OwningColumn == null || + !DataGridView.ShowCellErrors || string.IsNullOrEmpty(GetErrorText(rowIndex))) { return Rectangle.Empty; @@ -308,7 +308,7 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize) { - if (this.DataGridView == null) + if (DataGridView == null) { return new Size(-1, -1); } @@ -319,7 +319,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl } Size preferredSize; - Rectangle borderWidthsRect = this.StdBorderWidths; + Rectangle borderWidthsRect = StdBorderWidths; int borderAndPaddingWidths = borderWidthsRect.Left + borderWidthsRect.Width + cellStyle.Padding.Horizontal; int borderAndPaddingHeights = borderWidthsRect.Top + borderWidthsRect.Height + cellStyle.Padding.Vertical; DataGridViewFreeDimension freeDimension = DataGridViewCell.GetFreeDimensionFromConstraint(constraintSize); @@ -329,10 +329,10 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl { formattedString = " "; } - TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); + TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); // Adding space for text padding. - if (this.DataGridView.ApplyVisualStylesToInnerCells) + if (DataGridView.ApplyVisualStylesToInnerCells) { Rectangle rectThemeMargins = DataGridViewButtonCell.GetThemeMargins(graphics); marginWidths = rectThemeMargins.X + rectThemeMargins.Width; @@ -404,7 +404,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl if (freeDimension != DataGridViewFreeDimension.Height) { preferredSize.Width += borderAndPaddingWidths + marginWidths + 2 * DATAGRIDVIEWBUTTONCELL_horizontalTextMargin; - if (this.DataGridView.ShowCellErrors) + if (DataGridView.ShowCellErrors) { // Making sure that there is enough room for the potential error icon preferredSize.Width = Math.Max(preferredSize.Width, borderAndPaddingWidths + DATAGRIDVIEWCELL_iconMarginWidth * 2 + iconsWidth); @@ -413,7 +413,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl if (freeDimension != DataGridViewFreeDimension.Width) { preferredSize.Height += borderAndPaddingHeights + marginHeights + 2 * DATAGRIDVIEWBUTTONCELL_verticalTextMargin; - if (this.DataGridView.ShowCellErrors) + if (DataGridView.ShowCellErrors) { // Making sure that there is enough room for the potential error icon preferredSize.Height = Math.Max(preferredSize.Height, borderAndPaddingHeights + DATAGRIDVIEWCELL_iconMarginHeight * 2 + iconsHeight); @@ -438,13 +438,13 @@ private static Rectangle GetThemeMargins(Graphics g) protected override object GetValue(int rowIndex) { - if (this.UseColumnTextForButtonValue && - this.DataGridView != null && - this.DataGridView.NewRowIndex != rowIndex && - this.OwningColumn != null && - this.OwningColumn is DataGridViewButtonColumn) + if (UseColumnTextForButtonValue && + DataGridView != null && + DataGridView.NewRowIndex != rowIndex && + OwningColumn != null && + OwningColumn is DataGridViewButtonColumn) { - return ((DataGridViewButtonColumn)this.OwningColumn).Text; + return ((DataGridViewButtonColumn)OwningColumn).Text; } return base.GetValue(rowIndex); } @@ -466,12 +466,12 @@ protected override bool MouseDownUnsharesRow(DataGridViewCellMouseEventArgs e) protected override bool MouseEnterUnsharesRow(int rowIndex) { - return this.ColumnIndex == this.DataGridView.MouseDownCellAddress.X && rowIndex == this.DataGridView.MouseDownCellAddress.Y; + return ColumnIndex == DataGridView.MouseDownCellAddress.X && rowIndex == DataGridView.MouseDownCellAddress.Y; } protected override bool MouseLeaveUnsharesRow(int rowIndex) { - return (this.ButtonState & ButtonState.Pushed) != 0; + return (ButtonState & ButtonState.Pushed) != 0; } protected override bool MouseUpUnsharesRow(DataGridViewCellMouseEventArgs e) @@ -481,34 +481,34 @@ protected override bool MouseUpUnsharesRow(DataGridViewCellMouseEventArgs e) protected override void OnKeyDown(KeyEventArgs e, int rowIndex) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } if (e.KeyCode == Keys.Space && !e.Alt && !e.Control && !e.Shift) { - UpdateButtonState(this.ButtonState | ButtonState.Checked, rowIndex); + UpdateButtonState(ButtonState | ButtonState.Checked, rowIndex); e.Handled = true; } } protected override void OnKeyUp(KeyEventArgs e, int rowIndex) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } if (e.KeyCode == Keys.Space) { - UpdateButtonState(this.ButtonState & ~ButtonState.Checked, rowIndex); + UpdateButtonState(ButtonState & ~ButtonState.Checked, rowIndex); if (!e.Alt && !e.Control && !e.Shift) { - RaiseCellClick(new DataGridViewCellEventArgs(this.ColumnIndex, rowIndex)); - if (this.DataGridView != null && - this.ColumnIndex < this.DataGridView.Columns.Count && - rowIndex < this.DataGridView.Rows.Count) + RaiseCellClick(new DataGridViewCellEventArgs(ColumnIndex, rowIndex)); + if (DataGridView != null && + ColumnIndex < DataGridView.Columns.Count && + rowIndex < DataGridView.Rows.Count) { - RaiseCellContentClick(new DataGridViewCellEventArgs(this.ColumnIndex, rowIndex)); + RaiseCellContentClick(new DataGridViewCellEventArgs(ColumnIndex, rowIndex)); } e.Handled = true; } @@ -517,33 +517,33 @@ protected override void OnKeyUp(KeyEventArgs e, int rowIndex) protected override void OnLeave(int rowIndex, bool throughMouseClick) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } - if (this.ButtonState != ButtonState.Normal) + if (ButtonState != ButtonState.Normal) { - Debug.Assert(this.RowIndex >= 0); // Cell is not in a shared row. + Debug.Assert(RowIndex >= 0); // Cell is not in a shared row. UpdateButtonState(ButtonState.Normal, rowIndex); } } protected override void OnMouseDown(DataGridViewCellMouseEventArgs e) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } if (e.Button == MouseButtons.Left && mouseInContentBounds) { - Debug.Assert(this.DataGridView.CellMouseDownInContentBounds); - UpdateButtonState(this.ButtonState | ButtonState.Pushed, e.RowIndex); + Debug.Assert(DataGridView.CellMouseDownInContentBounds); + UpdateButtonState(ButtonState | ButtonState.Pushed, e.RowIndex); } } protected override void OnMouseLeave(int rowIndex) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } @@ -551,25 +551,25 @@ protected override void OnMouseLeave(int rowIndex) if (mouseInContentBounds) { mouseInContentBounds = false; - if (this.ColumnIndex >= 0 && + if (ColumnIndex >= 0 && rowIndex >= 0 && - (this.DataGridView.ApplyVisualStylesToInnerCells || this.FlatStyle == FlatStyle.Flat || this.FlatStyle == FlatStyle.Popup)) + (DataGridView.ApplyVisualStylesToInnerCells || FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup)) { - this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex); + DataGridView.InvalidateCell(ColumnIndex, rowIndex); } } - if ((this.ButtonState & ButtonState.Pushed) != 0 && - this.ColumnIndex == this.DataGridView.MouseDownCellAddress.X && - rowIndex == this.DataGridView.MouseDownCellAddress.Y) + if ((ButtonState & ButtonState.Pushed) != 0 && + ColumnIndex == DataGridView.MouseDownCellAddress.X && + rowIndex == DataGridView.MouseDownCellAddress.Y) { - UpdateButtonState(this.ButtonState & ~ButtonState.Pushed, rowIndex); + UpdateButtonState(ButtonState & ~ButtonState.Pushed, rowIndex); } } protected override void OnMouseMove(DataGridViewCellMouseEventArgs e) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } @@ -578,24 +578,24 @@ protected override void OnMouseMove(DataGridViewCellMouseEventArgs e) mouseInContentBounds = GetContentBounds(e.RowIndex).Contains(e.X, e.Y); if (oldMouseInContentBounds != mouseInContentBounds) { - if (this.DataGridView.ApplyVisualStylesToInnerCells || this.FlatStyle == FlatStyle.Flat || this.FlatStyle == FlatStyle.Popup) + if (DataGridView.ApplyVisualStylesToInnerCells || FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup) { - this.DataGridView.InvalidateCell(this.ColumnIndex, e.RowIndex); + DataGridView.InvalidateCell(ColumnIndex, e.RowIndex); } - if (e.ColumnIndex == this.DataGridView.MouseDownCellAddress.X && - e.RowIndex == this.DataGridView.MouseDownCellAddress.Y && + if (e.ColumnIndex == DataGridView.MouseDownCellAddress.X && + e.RowIndex == DataGridView.MouseDownCellAddress.Y && Control.MouseButtons == MouseButtons.Left) { - if ((this.ButtonState & ButtonState.Pushed) == 0 && + if ((ButtonState & ButtonState.Pushed) == 0 && mouseInContentBounds && - this.DataGridView.CellMouseDownInContentBounds) + DataGridView.CellMouseDownInContentBounds) { - UpdateButtonState(this.ButtonState | ButtonState.Pushed, e.RowIndex); + UpdateButtonState(ButtonState | ButtonState.Pushed, e.RowIndex); } - else if ((this.ButtonState & ButtonState.Pushed) != 0 && !mouseInContentBounds) + else if ((ButtonState & ButtonState.Pushed) != 0 && !mouseInContentBounds) { - UpdateButtonState(this.ButtonState & ~ButtonState.Pushed, e.RowIndex); + UpdateButtonState(ButtonState & ~ButtonState.Pushed, e.RowIndex); } } } @@ -605,13 +605,13 @@ protected override void OnMouseMove(DataGridViewCellMouseEventArgs e) protected override void OnMouseUp(DataGridViewCellMouseEventArgs e) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } if (e.Button == MouseButtons.Left) { - UpdateButtonState(this.ButtonState & ~ButtonState.Pushed, e.RowIndex); + UpdateButtonState(ButtonState & ~ButtonState.Pushed, e.RowIndex); } } @@ -677,15 +677,15 @@ private Rectangle PaintPrivate(Graphics g, Debug.Assert(!computeErrorIconBounds || !paint || !computeContentBounds); Debug.Assert(cellStyle != null); - Point ptCurrentCell = this.DataGridView.CurrentCellAddress; + Point ptCurrentCell = DataGridView.CurrentCellAddress; bool cellSelected = (elementState & DataGridViewElementStates.Selected) != 0; - bool cellCurrent = (ptCurrentCell.X == this.ColumnIndex && ptCurrentCell.Y == rowIndex); + bool cellCurrent = (ptCurrentCell.X == ColumnIndex && ptCurrentCell.Y == rowIndex); Rectangle resultBounds; string formattedString = formattedValue as string; - SolidBrush backBrush = this.DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor); - SolidBrush foreBrush = this.DataGridView.GetCachedBrush(cellSelected ? cellStyle.SelectionForeColor : cellStyle.ForeColor); + SolidBrush backBrush = DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor); + SolidBrush foreBrush = DataGridView.GetCachedBrush(cellSelected ? cellStyle.SelectionForeColor : cellStyle.ForeColor); if (paint && DataGridViewCell.PaintBorder(paintParts)) { @@ -708,7 +708,7 @@ private Rectangle PaintPrivate(Graphics g, if (cellStyle.Padding != Padding.Empty) { - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { valBounds.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top); } @@ -724,27 +724,27 @@ private Rectangle PaintPrivate(Graphics g, if (valBounds.Height > 0 && valBounds.Width > 0 && (paint || computeContentBounds)) { - if (this.FlatStyle == FlatStyle.Standard || this.FlatStyle == FlatStyle.System) + if (FlatStyle == FlatStyle.Standard || FlatStyle == FlatStyle.System) { - if (this.DataGridView.ApplyVisualStylesToInnerCells) + if (DataGridView.ApplyVisualStylesToInnerCells) { if (paint && DataGridViewCell.PaintContentBackground(paintParts)) { VisualStyles.PushButtonState pbState = VisualStyles.PushButtonState.Normal; - if ((this.ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0) + if ((ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0) { pbState = VisualStyles.PushButtonState.Pressed; } - else if (this.DataGridView.MouseEnteredCellAddress.Y == rowIndex && - this.DataGridView.MouseEnteredCellAddress.X == this.ColumnIndex && + else if (DataGridView.MouseEnteredCellAddress.Y == rowIndex && + DataGridView.MouseEnteredCellAddress.X == ColumnIndex && mouseInContentBounds) { pbState = VisualStyles.PushButtonState.Hot; } if (DataGridViewCell.PaintFocus(paintParts) && cellCurrent && - this.DataGridView.ShowFocusCues && - this.DataGridView.Focused) + DataGridView.ShowFocusCues && + DataGridView.Focused) { pbState |= VisualStyles.PushButtonState.Default; } @@ -758,13 +758,13 @@ private Rectangle PaintPrivate(Graphics g, if (paint && DataGridViewCell.PaintContentBackground(paintParts)) { ControlPaint.DrawBorder(g, valBounds, SystemColors.Control, - (this.ButtonState == ButtonState.Normal) ? ButtonBorderStyle.Outset : ButtonBorderStyle.Inset); + (ButtonState == ButtonState.Normal) ? ButtonBorderStyle.Outset : ButtonBorderStyle.Inset); } resultBounds = valBounds; valBounds.Inflate(-SystemInformation.Border3DSize.Width, -SystemInformation.Border3DSize.Height); } } - else if (this.FlatStyle == FlatStyle.Flat) + else if (FlatStyle == FlatStyle.Flat) { // ButtonBase::PaintFlatDown and ButtonBase::PaintFlatUp paint the border in the same way valBounds.Inflate(-1, -1); @@ -774,12 +774,12 @@ private Rectangle PaintPrivate(Graphics g, if (backBrush.Color.A == 255) { - if ((this.ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0) + if ((ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0) { ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintFlatRender(g, cellStyle.ForeColor, cellStyle.BackColor, - this.DataGridView.Enabled).Calculate(); + DataGridView.Enabled).Calculate(); IntPtr hdc = g.GetHdc(); try @@ -811,8 +811,8 @@ private Rectangle PaintPrivate(Graphics g, g.ReleaseHdc(); } } - else if (this.DataGridView.MouseEnteredCellAddress.Y == rowIndex && - this.DataGridView.MouseEnteredCellAddress.X == this.ColumnIndex && + else if (DataGridView.MouseEnteredCellAddress.Y == rowIndex && + DataGridView.MouseEnteredCellAddress.X == ColumnIndex && mouseInContentBounds) { IntPtr hdc = g.GetHdc(); @@ -838,17 +838,17 @@ private Rectangle PaintPrivate(Graphics g, } else { - Debug.Assert(this.FlatStyle == FlatStyle.Popup, "FlatStyle.Popup is the last flat style"); + Debug.Assert(FlatStyle == FlatStyle.Popup, "FlatStyle.Popup is the last flat style"); valBounds.Inflate(-1, -1); if (paint && DataGridViewCell.PaintContentBackground(paintParts)) { - if ((this.ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0) + if ((ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0) { // paint down ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintPopupRender(g, cellStyle.ForeColor, cellStyle.BackColor, - this.DataGridView.Enabled).Calculate(); + DataGridView.Enabled).Calculate(); ButtonBaseAdapter.DrawDefaultBorder(g, valBounds, colors.options.highContrast ? colors.windowText : colors.windowFrame, @@ -858,15 +858,15 @@ private Rectangle PaintPrivate(Graphics g, colors.options.highContrast ? colors.windowText : colors.buttonShadow, ButtonBorderStyle.Solid); } - else if (this.DataGridView.MouseEnteredCellAddress.Y == rowIndex && - this.DataGridView.MouseEnteredCellAddress.X == this.ColumnIndex && + else if (DataGridView.MouseEnteredCellAddress.Y == rowIndex && + DataGridView.MouseEnteredCellAddress.X == ColumnIndex && mouseInContentBounds) { // paint over ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintPopupRender(g, cellStyle.ForeColor, cellStyle.BackColor, - this.DataGridView.Enabled).Calculate(); + DataGridView.Enabled).Calculate(); ButtonBaseAdapter.DrawDefaultBorder(g, valBounds, colors.options.highContrast ? colors.windowText : colors.buttonShadow, @@ -879,7 +879,7 @@ private Rectangle PaintPrivate(Graphics g, ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintPopupRender(g, cellStyle.ForeColor, cellStyle.BackColor, - this.DataGridView.Enabled).Calculate(); + DataGridView.Enabled).Calculate(); ButtonBaseAdapter.DrawDefaultBorder(g, valBounds, colors.options.highContrast ? colors.windowText : colors.buttonShadow, false /*isDefault*/); ButtonBaseAdapter.DrawFlatBorder(g, valBounds, colors.options.highContrast ? colors.windowText : colors.buttonShadow); } @@ -907,25 +907,25 @@ private Rectangle PaintPrivate(Graphics g, if (paint && DataGridViewCell.PaintFocus(paintParts) && cellCurrent && - this.DataGridView.ShowFocusCues && - this.DataGridView.Focused && + DataGridView.ShowFocusCues && + DataGridView.Focused && valBounds.Width > 2 * SystemInformation.Border3DSize.Width + 1 && valBounds.Height > 2 * SystemInformation.Border3DSize.Height + 1) { // Draw focus rectangle - if (this.FlatStyle == FlatStyle.System || this.FlatStyle == FlatStyle.Standard) + if (FlatStyle == FlatStyle.System || FlatStyle == FlatStyle.Standard) { ControlPaint.DrawFocusRectangle(g, Rectangle.Inflate(valBounds, -1, -1), Color.Empty, SystemColors.Control); } - else if (this.FlatStyle == FlatStyle.Flat) + else if (FlatStyle == FlatStyle.Flat) { - if ((this.ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0 || - (this.DataGridView.CurrentCellAddress.Y == rowIndex && this.DataGridView.CurrentCellAddress.X == this.ColumnIndex)) + if ((ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0 || + (DataGridView.CurrentCellAddress.Y == rowIndex && DataGridView.CurrentCellAddress.X == ColumnIndex)) { ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintFlatRender(g, cellStyle.ForeColor, cellStyle.BackColor, - this.DataGridView.Enabled).Calculate(); + DataGridView.Enabled).Calculate(); string text = (formattedString != null) ? formattedString : string.Empty; ButtonBaseAdapter.LayoutOptions options = ButtonInternal.ButtonFlatAdapter.PaintFlatLayout(g, @@ -937,9 +937,9 @@ private Rectangle PaintPrivate(Graphics g, false, cellStyle.Font, text, - this.DataGridView.Enabled, + DataGridView.Enabled, DataGridViewUtilities.ComputeDrawingContentAlignmentForCellStyleAlignment(cellStyle.Alignment), - this.DataGridView.RightToLeft); + DataGridView.RightToLeft); options.everettButtonCompat = false; ButtonBaseAdapter.LayoutData layout = options.Layout(); @@ -950,13 +950,13 @@ private Rectangle PaintPrivate(Graphics g, } else { - Debug.Assert(this.FlatStyle == FlatStyle.Popup, "FlatStyle.Popup is the last flat style"); - if ((this.ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0 || - (this.DataGridView.CurrentCellAddress.Y == rowIndex && this.DataGridView.CurrentCellAddress.X == this.ColumnIndex)) + Debug.Assert(FlatStyle == FlatStyle.Popup, "FlatStyle.Popup is the last flat style"); + if ((ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0 || + (DataGridView.CurrentCellAddress.Y == rowIndex && DataGridView.CurrentCellAddress.X == ColumnIndex)) { // If we are painting the current cell, then paint the text up. // If we are painting the current cell and the current cell is pressed down, then paint the text down. - bool paintUp = (this.ButtonState == ButtonState.Normal); + bool paintUp = (ButtonState == ButtonState.Normal); string text = (formattedString != null) ? formattedString : string.Empty; ButtonBaseAdapter.LayoutOptions options = ButtonInternal.ButtonPopupAdapter.PaintPopupLayout(g, paintUp, @@ -966,9 +966,9 @@ private Rectangle PaintPrivate(Graphics g, false, cellStyle.Font, text, - this.DataGridView.Enabled, + DataGridView.Enabled, DataGridViewUtilities.ComputeDrawingContentAlignmentForCellStyleAlignment(cellStyle.Alignment), - this.DataGridView.RightToLeft); + DataGridView.RightToLeft); options.everettButtonCompat = false; ButtonBaseAdapter.LayoutData layout = options.Layout(); @@ -988,8 +988,8 @@ private Rectangle PaintPrivate(Graphics g, valBounds.Width -= 2 * DATAGRIDVIEWBUTTONCELL_horizontalTextMargin; valBounds.Height -= 2 * DATAGRIDVIEWBUTTONCELL_verticalTextMargin; - if ((this.ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0 && - this.FlatStyle != FlatStyle.Flat && this.FlatStyle != FlatStyle.Popup) + if ((ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0 && + FlatStyle != FlatStyle.Flat && FlatStyle != FlatStyle.Popup) { valBounds.Offset(1, 1); valBounds.Width--; @@ -999,8 +999,8 @@ private Rectangle PaintPrivate(Graphics g, if (valBounds.Width > 0 && valBounds.Height > 0) { Color textColor; - if (this.DataGridView.ApplyVisualStylesToInnerCells && - (this.FlatStyle == FlatStyle.System || this.FlatStyle == FlatStyle.Standard)) + if (DataGridView.ApplyVisualStylesToInnerCells && + (FlatStyle == FlatStyle.System || FlatStyle == FlatStyle.Standard)) { textColor = DataGridViewButtonCellRenderer.DataGridViewButtonRenderer.GetColor(ColorProperty.TextColor); } @@ -1008,7 +1008,7 @@ private Rectangle PaintPrivate(Graphics g, { textColor = foreBrush.Color; } - TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); + TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); TextRenderer.DrawText(g, formattedString, cellStyle.Font, @@ -1018,7 +1018,7 @@ private Rectangle PaintPrivate(Graphics g, } } - if (this.DataGridView.ShowCellErrors && paint && DataGridViewCell.PaintErrorIcon(paintParts)) + if (DataGridView.ShowCellErrors && paint && DataGridViewCell.PaintErrorIcon(paintParts)) { PaintErrorIcon(g, cellStyle, rowIndex, cellBounds, errorBounds, errorText); } @@ -1038,10 +1038,10 @@ public override string ToString() private void UpdateButtonState(ButtonState newButtonState, int rowIndex) { - if (this.ButtonState != newButtonState) + if (ButtonState != newButtonState) { - this.ButtonState = newButtonState; - this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex); + ButtonState = newButtonState; + DataGridView.InvalidateCell(ColumnIndex, rowIndex); } } @@ -1088,7 +1088,7 @@ public override string DefaultAction public override void DoDefaultAction() { - DataGridViewButtonCell dataGridViewCell = (DataGridViewButtonCell)this.Owner; + DataGridViewButtonCell dataGridViewCell = (DataGridViewButtonCell)Owner; DataGridView dataGridView = dataGridViewCell.DataGridView; if (dataGridView != null && dataGridViewCell.RowIndex == -1) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonColumn.cs index 30dd75cecbe..363c9de2edf 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonColumn.cs @@ -27,7 +27,7 @@ public DataGridViewButtonColumn() { DataGridViewCellStyle defaultCellStyle = new DataGridViewCellStyle(); defaultCellStyle.AlignmentInternal = DataGridViewContentAlignment.MiddleCenter; - this.DefaultCellStyle = defaultCellStyle; + DefaultCellStyle = defaultCellStyle; } [ @@ -76,31 +76,31 @@ public FlatStyle FlatStyle { get { - if (this.CellTemplate == null) + if (CellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return ((DataGridViewButtonCell)this.CellTemplate).FlatStyle; + return ((DataGridViewButtonCell)CellTemplate).FlatStyle; } set { - if (this.FlatStyle != value) + if (FlatStyle != value) { - ((DataGridViewButtonCell)this.CellTemplate).FlatStyle = value; - if (this.DataGridView != null) + ((DataGridViewButtonCell)CellTemplate).FlatStyle = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewButtonCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewButtonCell; + DataGridViewButtonCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewButtonCell; if (dataGridViewCell != null) { dataGridViewCell.FlatStyleInternal = value; } } - this.DataGridView.OnColumnCommonChange(this.Index); + DataGridView.OnColumnCommonChange(Index); } } } @@ -115,34 +115,34 @@ public string Text { get { - return this.text; + return text; } set { - if (!string.Equals(value, this.text, StringComparison.Ordinal)) + if (!string.Equals(value, text, StringComparison.Ordinal)) { - this.text = value; - if (this.DataGridView != null) + text = value; + if (DataGridView != null) { - if (this.UseColumnTextForButtonValue) + if (UseColumnTextForButtonValue) { - this.DataGridView.OnColumnCommonChange(this.Index); + DataGridView.OnColumnCommonChange(Index); } else { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewButtonCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewButtonCell; + DataGridViewButtonCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewButtonCell; if (dataGridViewCell != null && dataGridViewCell.UseColumnTextForButtonValue) { - this.DataGridView.OnColumnCommonChange(this.Index); + DataGridView.OnColumnCommonChange(Index); return; } } - this.DataGridView.InvalidateColumn(this.Index); + DataGridView.InvalidateColumn(Index); } } } @@ -158,31 +158,31 @@ public bool UseColumnTextForButtonValue { get { - if (this.CellTemplate == null) + if (CellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return ((DataGridViewButtonCell)this.CellTemplate).UseColumnTextForButtonValue; + return ((DataGridViewButtonCell)CellTemplate).UseColumnTextForButtonValue; } set { - if (this.UseColumnTextForButtonValue != value) + if (UseColumnTextForButtonValue != value) { - ((DataGridViewButtonCell)this.CellTemplate).UseColumnTextForButtonValueInternal = value; - if (this.DataGridView != null) + ((DataGridViewButtonCell)CellTemplate).UseColumnTextForButtonValueInternal = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewButtonCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewButtonCell; + DataGridViewButtonCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewButtonCell; if (dataGridViewCell != null) { dataGridViewCell.UseColumnTextForButtonValueInternal = value; } } - this.DataGridView.OnColumnCommonChange(this.Index); + DataGridView.OnColumnCommonChange(Index); } } } @@ -191,7 +191,7 @@ public bool UseColumnTextForButtonValue public override object Clone() { DataGridViewButtonColumn dataGridViewColumn; - Type thisType = this.GetType(); + Type thisType = GetType(); if (thisType == columnType) //performance improvement { @@ -204,19 +204,19 @@ public override object Clone() if (dataGridViewColumn != null) { base.CloneInternal(dataGridViewColumn); - dataGridViewColumn.Text = this.text; + dataGridViewColumn.Text = text; } return dataGridViewColumn; } private bool ShouldSerializeDefaultCellStyle() { - if (!this.HasDefaultCellStyle) + if (!HasDefaultCellStyle) { return false; } - DataGridViewCellStyle defaultCellStyle = this.DefaultCellStyle; + DataGridViewCellStyle defaultCellStyle = DefaultCellStyle; return (!defaultCellStyle.BackColor.IsEmpty || !defaultCellStyle.ForeColor.IsEmpty || @@ -237,9 +237,9 @@ public override string ToString() { StringBuilder sb = new StringBuilder(64); sb.Append("DataGridViewButtonColumn { Name="); - sb.Append(this.Name); + sb.Append(Name); sb.Append(", Index="); - sb.Append(this.Index.ToString(CultureInfo.CurrentCulture)); + sb.Append(Index.ToString(CultureInfo.CurrentCulture)); sb.Append(" }"); return sb.ToString(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs index 45458eedad9..9070ce485de 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs @@ -80,8 +80,8 @@ protected DataGridViewCell() : base() isScalingInitialized = true; } - this.propertyStore = new PropertyStore(); - this.StateInternal = DataGridViewElementStates.None; + propertyStore = new PropertyStore(); + StateInternal = DataGridViewElementStates.None; } ~DataGridViewCell() @@ -96,11 +96,11 @@ public AccessibleObject AccessibilityObject { get { - AccessibleObject result = (AccessibleObject)this.Properties.GetObject(PropCellAccessibilityObject); + AccessibleObject result = (AccessibleObject)Properties.GetObject(PropCellAccessibilityObject); if (result == null) { - result = this.CreateAccessibilityInstance(); - this.Properties.SetObject(PropCellAccessibilityObject, result); + result = CreateAccessibilityInstance(); + Properties.SetObject(PropCellAccessibilityObject, result); } return result; @@ -114,11 +114,11 @@ public int ColumnIndex { get { - if (this.owningColumn == null) + if (owningColumn == null) { return -1; } - return this.owningColumn.Index; + return owningColumn.Index; } } @@ -129,7 +129,7 @@ public Rectangle ContentBounds { get { - return GetContentBounds(this.RowIndex); + return GetContentBounds(RowIndex); } } @@ -140,11 +140,11 @@ public virtual ContextMenuStrip ContextMenuStrip { get { - return GetContextMenuStrip(this.RowIndex); + return GetContextMenuStrip(RowIndex); } set { - this.ContextMenuStripInternal = value; + ContextMenuStripInternal = value; } } @@ -152,11 +152,11 @@ private ContextMenuStrip ContextMenuStripInternal { get { - return (ContextMenuStrip)this.Properties.GetObject(PropCellContextMenuStrip); + return (ContextMenuStrip)Properties.GetObject(PropCellContextMenuStrip); } set { - ContextMenuStrip oldValue = (ContextMenuStrip)this.Properties.GetObject(PropCellContextMenuStrip); + ContextMenuStrip oldValue = (ContextMenuStrip)Properties.GetObject(PropCellContextMenuStrip); if (oldValue != value) { EventHandler disposedHandler = new EventHandler(DetachContextMenuStrip); @@ -164,14 +164,14 @@ private ContextMenuStrip ContextMenuStripInternal { oldValue.Disposed -= disposedHandler; } - this.Properties.SetObject(PropCellContextMenuStrip, value); + Properties.SetObject(PropCellContextMenuStrip, value); if (value != null) { value.Disposed += disposedHandler; } - if (this.DataGridView != null) + if (DataGridView != null) { - this.DataGridView.OnCellContextMenuStripChanged(this); + DataGridView.OnCellContextMenuStripChanged(this); } } } @@ -181,12 +181,12 @@ private byte CurrentMouseLocation { get { - return (byte)(this.flags & (DATAGRIDVIEWCELL_flagDataArea | DATAGRIDVIEWCELL_flagErrorArea)); + return (byte)(flags & (DATAGRIDVIEWCELL_flagDataArea | DATAGRIDVIEWCELL_flagErrorArea)); } set { - this.flags = (byte)(this.flags & ~(DATAGRIDVIEWCELL_flagDataArea | DATAGRIDVIEWCELL_flagErrorArea)); - this.flags |= value; + flags = (byte)(flags & ~(DATAGRIDVIEWCELL_flagDataArea | DATAGRIDVIEWCELL_flagErrorArea)); + flags |= value; } } @@ -208,18 +208,18 @@ public virtual bool Displayed { get { - Debug.Assert((this.State & DataGridViewElementStates.Displayed) == 0); + Debug.Assert((State & DataGridViewElementStates.Displayed) == 0); - if (this.DataGridView == null) + if (DataGridView == null) { // No detached element is displayed. return false; } - if (this.RowIndex >= 0 && this.ColumnIndex >= 0) + if (RowIndex >= 0 && ColumnIndex >= 0) { - Debug.Assert(this.DataGridView.Rows.GetRowState(this.RowIndex) == this.DataGridView.Rows.SharedRow(this.RowIndex).State); - return this.owningColumn.Displayed && this.owningRow.Displayed; + Debug.Assert(DataGridView.Rows.GetRowState(RowIndex) == DataGridView.Rows.SharedRow(RowIndex).State); + return owningColumn.Displayed && owningRow.Displayed; } return false; @@ -234,13 +234,13 @@ public object EditedFormattedValue { get { - if (this.DataGridView == null) + if (DataGridView == null) { return null; } - Debug.Assert(this.RowIndex >= -1); - DataGridViewCellStyle dataGridViewCellStyle = GetInheritedStyle(null, this.RowIndex, false); - return GetEditedFormattedValue(GetValue(this.RowIndex), this.RowIndex, ref dataGridViewCellStyle, DataGridViewDataErrorContexts.Formatting); + Debug.Assert(RowIndex >= -1); + DataGridViewCellStyle dataGridViewCellStyle = GetInheritedStyle(null, RowIndex, false); + return GetEditedFormattedValue(GetValue(RowIndex), RowIndex, ref dataGridViewCellStyle, DataGridViewDataErrorContexts.Formatting); } } @@ -277,7 +277,7 @@ public Rectangle ErrorIconBounds { get { - return GetErrorIconBounds(this.RowIndex); + return GetErrorIconBounds(RowIndex); } } @@ -288,11 +288,11 @@ public string ErrorText { get { - return GetErrorText(this.RowIndex); + return GetErrorText(RowIndex); } set { - this.ErrorTextInternal = value; + ErrorTextInternal = value; } } @@ -300,19 +300,19 @@ private string ErrorTextInternal { get { - object errorText = this.Properties.GetObject(PropCellErrorText); + object errorText = Properties.GetObject(PropCellErrorText); return (errorText == null) ? string.Empty : (string)errorText; } set { - string errorText = this.ErrorTextInternal; - if (!string.IsNullOrEmpty(value) || this.Properties.ContainsObject(PropCellErrorText)) + string errorText = ErrorTextInternal; + if (!string.IsNullOrEmpty(value) || Properties.ContainsObject(PropCellErrorText)) { - this.Properties.SetObject(PropCellErrorText, value); + Properties.SetObject(PropCellErrorText, value); } - if (this.DataGridView != null && !errorText.Equals(this.ErrorTextInternal)) + if (DataGridView != null && !errorText.Equals(ErrorTextInternal)) { - this.DataGridView.OnCellErrorTextChanged(this); + DataGridView.OnCellErrorTextChanged(this); } } } @@ -324,13 +324,13 @@ public object FormattedValue { get { - if (this.DataGridView == null) + if (DataGridView == null) { return null; } - Debug.Assert(this.RowIndex >= -1); - DataGridViewCellStyle dataGridViewCellStyle = GetInheritedStyle(null, this.RowIndex, false); - return GetFormattedValue(this.RowIndex, ref dataGridViewCellStyle, DataGridViewDataErrorContexts.Formatting); + Debug.Assert(RowIndex >= -1); + DataGridViewCellStyle dataGridViewCellStyle = GetInheritedStyle(null, RowIndex, false); + return GetFormattedValue(RowIndex, ref dataGridViewCellStyle, DataGridViewDataErrorContexts.Formatting); } } @@ -341,7 +341,7 @@ public virtual Type FormattedValueType { get { - return this.ValueType; + return ValueType; } } @@ -350,15 +350,15 @@ private TypeConverter FormattedValueTypeConverter get { TypeConverter formattedValueTypeConverter = null; - if (this.FormattedValueType != null) + if (FormattedValueType != null) { - if (this.DataGridView != null) + if (DataGridView != null) { - formattedValueTypeConverter = this.DataGridView.GetCachedTypeConverter(this.FormattedValueType); + formattedValueTypeConverter = DataGridView.GetCachedTypeConverter(FormattedValueType); } else { - formattedValueTypeConverter = TypeDescriptor.GetConverter(this.FormattedValueType); + formattedValueTypeConverter = TypeDescriptor.GetConverter(FormattedValueType); } } return formattedValueTypeConverter; @@ -372,16 +372,16 @@ public virtual bool Frozen { get { - Debug.Assert((this.State & DataGridViewElementStates.Frozen) == 0); + Debug.Assert((State & DataGridViewElementStates.Frozen) == 0); - if (this.DataGridView != null && this.RowIndex >= 0 && this.ColumnIndex >= 0) + if (DataGridView != null && RowIndex >= 0 && ColumnIndex >= 0) { - Debug.Assert(this.DataGridView.Rows.GetRowState(this.RowIndex) == this.DataGridView.Rows.SharedRow(this.RowIndex).State); - return this.owningColumn.Frozen && this.owningRow.Frozen; + Debug.Assert(DataGridView.Rows.GetRowState(RowIndex) == DataGridView.Rows.SharedRow(RowIndex).State); + return owningColumn.Frozen && owningRow.Frozen; } - else if (this.owningRow != null && (this.owningRow.DataGridView == null || this.RowIndex >= 0)) + else if (owningRow != null && (owningRow.DataGridView == null || RowIndex >= 0)) { - return this.owningRow.Frozen; + return owningRow.Frozen; } return false; } @@ -391,7 +391,7 @@ internal bool HasErrorText { get { - return this.Properties.ContainsObject(PropCellErrorText) && this.Properties.GetObject(PropCellErrorText) != null; + return Properties.ContainsObject(PropCellErrorText) && Properties.GetObject(PropCellErrorText) != null; } } @@ -402,7 +402,7 @@ public bool HasStyle { get { - return this.Properties.ContainsObject(PropCellStyle) && this.Properties.GetObject(PropCellStyle) != null; + return Properties.ContainsObject(PropCellStyle) && Properties.GetObject(PropCellStyle) != null; } } @@ -410,7 +410,7 @@ internal bool HasToolTipText { get { - return this.Properties.ContainsObject(PropCellToolTipText) && this.Properties.GetObject(PropCellToolTipText) != null; + return Properties.ContainsObject(PropCellToolTipText) && Properties.GetObject(PropCellToolTipText) != null; } } @@ -418,7 +418,7 @@ internal bool HasValue { get { - return this.Properties.ContainsObject(PropCellValue) && this.Properties.GetObject(PropCellValue) != null; + return Properties.ContainsObject(PropCellValue) && Properties.GetObject(PropCellValue) != null; } } @@ -426,7 +426,7 @@ internal virtual bool HasValueType { get { - return this.Properties.ContainsObject(PropCellValueType) && this.Properties.GetObject(PropCellValueType) != null; + return Properties.ContainsObject(PropCellValueType) && Properties.GetObject(PropCellValueType) != null; } } @@ -438,7 +438,7 @@ public DataGridViewElementStates InheritedState { get { - return GetInheritedState(this.RowIndex); + return GetInheritedState(RowIndex); } } @@ -453,7 +453,7 @@ public DataGridViewCellStyle InheritedStyle // this.RowIndex could be -1 if: // - the developer makes a mistake & calls dataGridView1.Rows.SharedRow(y).Cells(x).InheritedStyle. // - the InheritedStyle of a ColumnHeaderCell is accessed. - return GetInheritedStyleInternal(this.RowIndex); + return GetInheritedStyleInternal(RowIndex); } } @@ -464,19 +464,19 @@ public bool IsInEditMode { get { - if (this.DataGridView == null) + if (DataGridView == null) { return false; } - if (this.RowIndex == -1) + if (RowIndex == -1) { throw new InvalidOperationException(string.Format(SR.DataGridView_InvalidOperationOnSharedCell)); } - Point ptCurrentCell = this.DataGridView.CurrentCellAddress; + Point ptCurrentCell = DataGridView.CurrentCellAddress; return ptCurrentCell.X != -1 && - ptCurrentCell.X == this.ColumnIndex && - ptCurrentCell.Y == this.RowIndex && - this.DataGridView.IsCurrentCellInEditMode; + ptCurrentCell.X == ColumnIndex && + ptCurrentCell.Y == RowIndex && + DataGridView.IsCurrentCellInEditMode; } } @@ -488,7 +488,7 @@ public DataGridViewColumn OwningColumn { get { - return this.owningColumn; + return owningColumn; } } @@ -496,7 +496,7 @@ internal DataGridViewColumn OwningColumnInternal { set { - this.owningColumn = value; + owningColumn = value; } } @@ -508,7 +508,7 @@ public DataGridViewRow OwningRow { get { - return this.owningRow; + return owningRow; } } @@ -516,7 +516,7 @@ internal DataGridViewRow OwningRowInternal { set { - this.owningRow = value; + owningRow = value; } } @@ -527,7 +527,7 @@ public Size PreferredSize { get { - return GetPreferredSize(this.RowIndex); + return GetPreferredSize(RowIndex); } } @@ -535,7 +535,7 @@ internal PropertyStore Properties { get { - return this.propertyStore; + return propertyStore; } } @@ -547,42 +547,42 @@ public virtual bool ReadOnly { get { - if ((this.State & DataGridViewElementStates.ReadOnly) != 0) + if ((State & DataGridViewElementStates.ReadOnly) != 0) { return true; } - if (this.owningRow != null && (this.owningRow.DataGridView == null || this.RowIndex >= 0) && this.owningRow.ReadOnly) + if (owningRow != null && (owningRow.DataGridView == null || RowIndex >= 0) && owningRow.ReadOnly) { return true; } - if (this.DataGridView != null && this.RowIndex >= 0 && this.ColumnIndex >= 0) + if (DataGridView != null && RowIndex >= 0 && ColumnIndex >= 0) { - Debug.Assert(this.DataGridView.Rows.GetRowState(this.RowIndex) == this.DataGridView.Rows.SharedRow(this.RowIndex).State); - return this.owningColumn.ReadOnly; + Debug.Assert(DataGridView.Rows.GetRowState(RowIndex) == DataGridView.Rows.SharedRow(RowIndex).State); + return owningColumn.ReadOnly; } return false; } set { - if (this.DataGridView != null) + if (DataGridView != null) { - if (this.RowIndex == -1) + if (RowIndex == -1) { throw new InvalidOperationException(string.Format(SR.DataGridView_InvalidOperationOnSharedCell)); } - Debug.Assert(this.ColumnIndex >= 0); + Debug.Assert(ColumnIndex >= 0); // When the whole grid is read-only, we ignore the request. - if (value != this.ReadOnly && !this.DataGridView.ReadOnly) + if (value != ReadOnly && !DataGridView.ReadOnly) { - this.DataGridView.OnDataGridViewElementStateChanging(this, -1, DataGridViewElementStates.ReadOnly); - this.DataGridView.SetReadOnlyCellCore(this.ColumnIndex, this.RowIndex, value); // this may trigger a call to set_ReadOnlyInternal + DataGridView.OnDataGridViewElementStateChanging(this, -1, DataGridViewElementStates.ReadOnly); + DataGridView.SetReadOnlyCellCore(ColumnIndex, RowIndex, value); // this may trigger a call to set_ReadOnlyInternal } } else { - if (this.owningRow == null) + if (owningRow == null) { - if (value != this.ReadOnly) + if (value != ReadOnly) { // We do not allow the read-only flag of a cell to be changed before it is added to a row. throw new InvalidOperationException(string.Format(SR.DataGridViewCell_CannotSetReadOnlyState)); @@ -590,7 +590,7 @@ public virtual bool ReadOnly } else { - this.owningRow.SetReadOnlyCellCore(this, value); + owningRow.SetReadOnlyCellCore(this, value); } } } @@ -600,18 +600,18 @@ internal bool ReadOnlyInternal { set { - Debug.Assert(value != this.ReadOnly); + Debug.Assert(value != ReadOnly); if (value) { - this.StateInternal = this.State | DataGridViewElementStates.ReadOnly; + StateInternal = State | DataGridViewElementStates.ReadOnly; } else { - this.StateInternal = this.State & ~DataGridViewElementStates.ReadOnly; + StateInternal = State & ~DataGridViewElementStates.ReadOnly; } - if (this.DataGridView != null) + if (DataGridView != null) { - this.DataGridView.OnDataGridViewElementStateChanged(this, -1, DataGridViewElementStates.ReadOnly); + DataGridView.OnDataGridViewElementStateChanged(this, -1, DataGridViewElementStates.ReadOnly); } } } @@ -623,17 +623,17 @@ public virtual bool Resizable { get { - Debug.Assert((this.State & DataGridViewElementStates.Resizable) == 0); + Debug.Assert((State & DataGridViewElementStates.Resizable) == 0); - if (this.owningRow != null && (this.owningRow.DataGridView == null || this.RowIndex >= 0) && this.owningRow.Resizable == DataGridViewTriState.True) + if (owningRow != null && (owningRow.DataGridView == null || RowIndex >= 0) && owningRow.Resizable == DataGridViewTriState.True) { return true; } - if (this.DataGridView != null && this.RowIndex >= 0 && this.ColumnIndex >= 0) + if (DataGridView != null && RowIndex >= 0 && ColumnIndex >= 0) { - Debug.Assert(this.DataGridView.Rows.GetRowState(this.RowIndex) == this.DataGridView.Rows.SharedRow(this.RowIndex).State); - return this.owningColumn.Resizable == DataGridViewTriState.True; + Debug.Assert(DataGridView.Rows.GetRowState(RowIndex) == DataGridView.Rows.SharedRow(RowIndex).State); + return owningColumn.Resizable == DataGridViewTriState.True; } return false; @@ -650,11 +650,11 @@ public int RowIndex { get { - if (this.owningRow == null) + if (owningRow == null) { return -1; } - return this.owningRow.Index; + return owningRow.Index; } } @@ -666,34 +666,34 @@ public virtual bool Selected { get { - if ((this.State & DataGridViewElementStates.Selected) != 0) + if ((State & DataGridViewElementStates.Selected) != 0) { return true; } - if (this.owningRow != null && (this.owningRow.DataGridView == null || this.RowIndex >= 0) && this.owningRow.Selected) + if (owningRow != null && (owningRow.DataGridView == null || RowIndex >= 0) && owningRow.Selected) { return true; } - if (this.DataGridView != null && this.RowIndex >= 0 && this.ColumnIndex >= 0) + if (DataGridView != null && RowIndex >= 0 && ColumnIndex >= 0) { - Debug.Assert(this.DataGridView.Rows.GetRowState(this.RowIndex) == this.DataGridView.Rows.SharedRow(this.RowIndex).State); - return this.owningColumn.Selected; + Debug.Assert(DataGridView.Rows.GetRowState(RowIndex) == DataGridView.Rows.SharedRow(RowIndex).State); + return owningColumn.Selected; } return false; } set { - if (this.DataGridView != null) + if (DataGridView != null) { - if (this.RowIndex == -1) + if (RowIndex == -1) { throw new InvalidOperationException(string.Format(SR.DataGridView_InvalidOperationOnSharedCell)); } - Debug.Assert(this.ColumnIndex >= 0); - this.DataGridView.SetSelectedCellCoreInternal(this.ColumnIndex, this.RowIndex, value); // this may trigger a call to set_SelectedInternal + Debug.Assert(ColumnIndex >= 0); + DataGridView.SetSelectedCellCoreInternal(ColumnIndex, RowIndex, value); // this may trigger a call to set_SelectedInternal } else if (value) { @@ -707,18 +707,18 @@ internal bool SelectedInternal { set { - Debug.Assert(value != this.Selected); + Debug.Assert(value != Selected); if (value) { - this.StateInternal = this.State | DataGridViewElementStates.Selected; + StateInternal = State | DataGridViewElementStates.Selected; } else { - this.StateInternal = this.State & ~DataGridViewElementStates.Selected; + StateInternal = State & ~DataGridViewElementStates.Selected; } - if (this.DataGridView != null) + if (DataGridView != null) { - this.DataGridView.OnDataGridViewElementStateChanged(this, -1, DataGridViewElementStates.Selected); + DataGridView.OnDataGridViewElementStateChanged(this, -1, DataGridViewElementStates.Selected); } } } @@ -731,7 +731,7 @@ public Size Size { get { - return GetSize(this.RowIndex); + return GetSize(RowIndex); } } @@ -739,10 +739,10 @@ internal Rectangle StdBorderWidths { get { - if (this.DataGridView != null) + if (DataGridView != null) { DataGridViewAdvancedBorderStyle dataGridViewAdvancedBorderStylePlaceholder = new DataGridViewAdvancedBorderStyle(), dgvabsEffective; - dgvabsEffective = AdjustCellBorderStyle(this.DataGridView.AdvancedCellBorderStyle, + dgvabsEffective = AdjustCellBorderStyle(DataGridView.AdvancedCellBorderStyle, dataGridViewAdvancedBorderStylePlaceholder, false /*singleVerticalBorderAdded*/, false /*singleHorizontalBorderAdded*/, @@ -764,36 +764,36 @@ public DataGridViewCellStyle Style { get { - DataGridViewCellStyle dgvcs = (DataGridViewCellStyle)this.Properties.GetObject(PropCellStyle); + DataGridViewCellStyle dgvcs = (DataGridViewCellStyle)Properties.GetObject(PropCellStyle); if (dgvcs == null) { dgvcs = new DataGridViewCellStyle(); - dgvcs.AddScope(this.DataGridView, DataGridViewCellStyleScopes.Cell); - this.Properties.SetObject(PropCellStyle, dgvcs); + dgvcs.AddScope(DataGridView, DataGridViewCellStyleScopes.Cell); + Properties.SetObject(PropCellStyle, dgvcs); } return dgvcs; } set { DataGridViewCellStyle dgvcs = null; - if (this.HasStyle) + if (HasStyle) { - dgvcs = this.Style; + dgvcs = Style; dgvcs.RemoveScope(DataGridViewCellStyleScopes.Cell); } - if (value != null || this.Properties.ContainsObject(PropCellStyle)) + if (value != null || Properties.ContainsObject(PropCellStyle)) { if (value != null) { - value.AddScope(this.DataGridView, DataGridViewCellStyleScopes.Cell); + value.AddScope(DataGridView, DataGridViewCellStyleScopes.Cell); } - this.Properties.SetObject(PropCellStyle, value); + Properties.SetObject(PropCellStyle, value); } if (((dgvcs != null && value == null) || (dgvcs == null && value != null) || - (dgvcs != null && value != null && !dgvcs.Equals(this.Style))) && this.DataGridView != null) + (dgvcs != null && value != null && !dgvcs.Equals(Style))) && DataGridView != null) { - this.DataGridView.OnCellStyleChanged(this); + DataGridView.OnCellStyleChanged(this); } } } @@ -810,13 +810,13 @@ public object Tag { get { - return this.Properties.GetObject(PropCellTag); + return Properties.GetObject(PropCellTag); } set { - if (value != null || this.Properties.ContainsObject(PropCellTag)) + if (value != null || Properties.ContainsObject(PropCellTag)) { - this.Properties.SetObject(PropCellTag, value); + Properties.SetObject(PropCellTag, value); } } } @@ -829,11 +829,11 @@ public string ToolTipText { get { - return GetToolTipText(this.RowIndex); + return GetToolTipText(RowIndex); } set { - this.ToolTipTextInternal = value; + ToolTipTextInternal = value; } } @@ -841,19 +841,19 @@ private string ToolTipTextInternal { get { - object toolTipText = this.Properties.GetObject(PropCellToolTipText); + object toolTipText = Properties.GetObject(PropCellToolTipText); return (toolTipText == null) ? string.Empty : (string)toolTipText; } set { - string toolTipText = this.ToolTipTextInternal; - if (!string.IsNullOrEmpty(value) || this.Properties.ContainsObject(PropCellToolTipText)) + string toolTipText = ToolTipTextInternal; + if (!string.IsNullOrEmpty(value) || Properties.ContainsObject(PropCellToolTipText)) { - this.Properties.SetObject(PropCellToolTipText, value); + Properties.SetObject(PropCellToolTipText, value); } - if (this.DataGridView != null && !toolTipText.Equals(this.ToolTipTextInternal)) + if (DataGridView != null && !toolTipText.Equals(ToolTipTextInternal)) { - this.DataGridView.OnCellToolTipTextChanged(this); + DataGridView.OnCellToolTipTextChanged(this); } } } @@ -865,13 +865,13 @@ public object Value { get { - Debug.Assert(this.RowIndex >= -1); - return GetValue(this.RowIndex); + Debug.Assert(RowIndex >= -1); + return GetValue(RowIndex); } set { - Debug.Assert(this.RowIndex >= -1); - SetValue(this.RowIndex, value); + Debug.Assert(RowIndex >= -1); + SetValue(RowIndex, value); } } @@ -882,19 +882,19 @@ public virtual Type ValueType { get { - Type cellValueType = (Type)this.Properties.GetObject(PropCellValueType); - if (cellValueType == null && this.OwningColumn != null) + Type cellValueType = (Type)Properties.GetObject(PropCellValueType); + if (cellValueType == null && OwningColumn != null) { - cellValueType = this.OwningColumn.ValueType; + cellValueType = OwningColumn.ValueType; } return cellValueType; } set { - if (value != null || this.Properties.ContainsObject(PropCellValueType)) + if (value != null || Properties.ContainsObject(PropCellValueType)) { - this.Properties.SetObject(PropCellValueType, value); + Properties.SetObject(PropCellValueType, value); } } } @@ -904,19 +904,19 @@ private TypeConverter ValueTypeConverter get { TypeConverter valueTypeConverter = null; - if (this.OwningColumn != null) + if (OwningColumn != null) { - valueTypeConverter = this.OwningColumn.BoundColumnConverter; + valueTypeConverter = OwningColumn.BoundColumnConverter; } - if (valueTypeConverter == null && this.ValueType != null) + if (valueTypeConverter == null && ValueType != null) { - if (this.DataGridView != null) + if (DataGridView != null) { - valueTypeConverter = this.DataGridView.GetCachedTypeConverter(this.ValueType); + valueTypeConverter = DataGridView.GetCachedTypeConverter(ValueType); } else { - valueTypeConverter = TypeDescriptor.GetConverter(this.ValueType); + valueTypeConverter = TypeDescriptor.GetConverter(ValueType); } } return valueTypeConverter; @@ -930,16 +930,16 @@ public virtual bool Visible { get { - Debug.Assert((this.State & DataGridViewElementStates.Visible) == 0); + Debug.Assert((State & DataGridViewElementStates.Visible) == 0); - if (this.DataGridView != null && this.RowIndex >= 0 && this.ColumnIndex >= 0) + if (DataGridView != null && RowIndex >= 0 && ColumnIndex >= 0) { - Debug.Assert(this.DataGridView.Rows.GetRowState(this.RowIndex) == this.DataGridView.Rows.SharedRow(this.RowIndex).State); - return this.owningColumn.Visible && this.owningRow.Visible; + Debug.Assert(DataGridView.Rows.GetRowState(RowIndex) == DataGridView.Rows.SharedRow(RowIndex).State); + return owningColumn.Visible && owningRow.Visible; } - else if (this.owningRow != null && (this.owningRow.DataGridView == null || this.RowIndex >= 0)) + else if (owningRow != null && (owningRow.DataGridView == null || RowIndex >= 0)) { - return this.owningRow.Visible; + return owningRow.Visible; } return false; } @@ -959,7 +959,7 @@ public virtual DataGridViewAdvancedBorderStyle AdjustCellBorderStyle(DataGridVie switch (dataGridViewAdvancedBorderStyleInput.All) { case DataGridViewAdvancedCellBorderStyle.Single: - if (this.DataGridView != null && this.DataGridView.RightToLeftInternal) + if (DataGridView != null && DataGridView.RightToLeftInternal) { dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = DataGridViewAdvancedCellBorderStyle.Single; dataGridViewAdvancedBorderStylePlaceholder.RightInternal = (isFirstDisplayedColumn && singleVerticalBorderAdded) ? DataGridViewAdvancedCellBorderStyle.Single : DataGridViewAdvancedCellBorderStyle.None; @@ -974,12 +974,12 @@ public virtual DataGridViewAdvancedBorderStyle AdjustCellBorderStyle(DataGridVie return dataGridViewAdvancedBorderStylePlaceholder; case DataGridViewAdvancedCellBorderStyle.NotSet: - if (this.DataGridView != null && this.DataGridView.AdvancedCellBorderStyle == dataGridViewAdvancedBorderStyleInput) + if (DataGridView != null && DataGridView.AdvancedCellBorderStyle == dataGridViewAdvancedBorderStyleInput) { - switch (this.DataGridView.CellBorderStyle) + switch (DataGridView.CellBorderStyle) { case DataGridViewCellBorderStyle.SingleVertical: - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = DataGridViewAdvancedCellBorderStyle.Single; dataGridViewAdvancedBorderStylePlaceholder.RightInternal = (isFirstDisplayedColumn && singleVerticalBorderAdded) ? DataGridViewAdvancedCellBorderStyle.Single : DataGridViewAdvancedCellBorderStyle.None; @@ -1034,20 +1034,20 @@ protected virtual Rectangle BorderWidths(DataGridViewAdvancedBorderStyle advance rect.Height++; } - if (this.owningColumn != null) + if (owningColumn != null) { - if (this.DataGridView != null && this.DataGridView.RightToLeftInternal) + if (DataGridView != null && DataGridView.RightToLeftInternal) { - rect.X += this.owningColumn.DividerWidth; + rect.X += owningColumn.DividerWidth; } else { - rect.Width += this.owningColumn.DividerWidth; + rect.Width += owningColumn.DividerWidth; } } - if (this.owningRow != null) + if (owningRow != null) { - rect.Height += this.owningRow.DividerHeight; + rect.Height += owningRow.DividerHeight; } return rect; @@ -1069,13 +1069,13 @@ internal DataGridViewElementStates CellStateFromColumnRowStates() internal DataGridViewElementStates CellStateFromColumnRowStates(DataGridViewElementStates rowState) { - Debug.Assert(this.DataGridView != null); - Debug.Assert(this.ColumnIndex >= 0); + Debug.Assert(DataGridView != null); + Debug.Assert(ColumnIndex >= 0); DataGridViewElementStates orFlags = DataGridViewElementStates.ReadOnly | DataGridViewElementStates.Resizable | DataGridViewElementStates.Selected; DataGridViewElementStates andFlags = DataGridViewElementStates.Displayed | DataGridViewElementStates.Frozen | DataGridViewElementStates.Visible; - DataGridViewElementStates cellState = (this.owningColumn.State & orFlags); + DataGridViewElementStates cellState = (owningColumn.State & orFlags); cellState |= (rowState & orFlags); - cellState |= ((this.owningColumn.State & andFlags) & (rowState & andFlags)); + cellState |= ((owningColumn.State & andFlags) & (rowState & andFlags)); return cellState; } @@ -1094,33 +1094,33 @@ internal bool ClickUnsharesRowInternal(DataGridViewCellEventArgs e) internal void CloneInternal(DataGridViewCell dataGridViewCell) { - if (this.HasValueType) + if (HasValueType) { - dataGridViewCell.ValueType = this.ValueType; + dataGridViewCell.ValueType = ValueType; } - if (this.HasStyle) + if (HasStyle) { - dataGridViewCell.Style = new DataGridViewCellStyle(this.Style); + dataGridViewCell.Style = new DataGridViewCellStyle(Style); } - if (this.HasErrorText) + if (HasErrorText) { - dataGridViewCell.ErrorText = this.ErrorTextInternal; + dataGridViewCell.ErrorText = ErrorTextInternal; } - if (this.HasToolTipText) + if (HasToolTipText) { - dataGridViewCell.ToolTipText = this.ToolTipTextInternal; + dataGridViewCell.ToolTipText = ToolTipTextInternal; } - if (this.ContextMenuStripInternal != null) + if (ContextMenuStripInternal != null) { - dataGridViewCell.ContextMenuStrip = this.ContextMenuStripInternal.Clone(); + dataGridViewCell.ContextMenuStrip = ContextMenuStripInternal.Clone(); } - dataGridViewCell.StateInternal = this.State & ~DataGridViewElementStates.Selected; - dataGridViewCell.Tag = this.Tag; + dataGridViewCell.StateInternal = State & ~DataGridViewElementStates.Selected; + dataGridViewCell.Tag = Tag; } public virtual object Clone() { - DataGridViewCell dataGridViewCell = (DataGridViewCell)System.Activator.CreateInstance(this.GetType()); + DataGridViewCell dataGridViewCell = (DataGridViewCell)System.Activator.CreateInstance(GetType()); CloneInternal(dataGridViewCell); return dataGridViewCell; } @@ -1138,57 +1138,57 @@ internal void ComputeBorderStyleCellStateAndCellBounds(int rowIndex, out DataGridViewElementStates cellState, out Rectangle cellBounds) { - Debug.Assert(this.DataGridView != null); - bool singleVerticalBorderAdded = !this.DataGridView.RowHeadersVisible && this.DataGridView.AdvancedCellBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Single; - bool singleHorizontalBorderAdded = !this.DataGridView.ColumnHeadersVisible && this.DataGridView.AdvancedCellBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Single; + Debug.Assert(DataGridView != null); + bool singleVerticalBorderAdded = !DataGridView.RowHeadersVisible && DataGridView.AdvancedCellBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Single; + bool singleHorizontalBorderAdded = !DataGridView.ColumnHeadersVisible && DataGridView.AdvancedCellBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Single; DataGridViewAdvancedBorderStyle dataGridViewAdvancedBorderStylePlaceholder = new DataGridViewAdvancedBorderStyle(); - if (rowIndex > -1 && this.OwningColumn != null) + if (rowIndex > -1 && OwningColumn != null) { // Inner cell case - dgvabsEffective = AdjustCellBorderStyle(this.DataGridView.AdvancedCellBorderStyle, + dgvabsEffective = AdjustCellBorderStyle(DataGridView.AdvancedCellBorderStyle, dataGridViewAdvancedBorderStylePlaceholder, singleVerticalBorderAdded, singleHorizontalBorderAdded, - this.ColumnIndex == this.DataGridView.FirstDisplayedColumnIndex /*isFirstDisplayedColumn*/, - rowIndex == this.DataGridView.FirstDisplayedRowIndex /*isFirstDisplayedRow*/); - DataGridViewElementStates rowState = this.DataGridView.Rows.GetRowState(rowIndex); - cellState = this.CellStateFromColumnRowStates(rowState); - cellState |= this.State; + ColumnIndex == DataGridView.FirstDisplayedColumnIndex /*isFirstDisplayedColumn*/, + rowIndex == DataGridView.FirstDisplayedRowIndex /*isFirstDisplayedRow*/); + DataGridViewElementStates rowState = DataGridView.Rows.GetRowState(rowIndex); + cellState = CellStateFromColumnRowStates(rowState); + cellState |= State; } - else if (this.OwningColumn != null) + else if (OwningColumn != null) { // Column header cell case Debug.Assert(rowIndex == -1); Debug.Assert(this is DataGridViewColumnHeaderCell, "if the row index == -1 and we have an owning column this should be a column header cell"); - DataGridViewColumn dataGridViewColumn = this.DataGridView.Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.None); - bool isLastVisibleColumn = (dataGridViewColumn != null && dataGridViewColumn.Index == this.ColumnIndex); - dgvabsEffective = this.DataGridView.AdjustColumnHeaderBorderStyle(this.DataGridView.AdvancedColumnHeadersBorderStyle, + DataGridViewColumn dataGridViewColumn = DataGridView.Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.None); + bool isLastVisibleColumn = (dataGridViewColumn != null && dataGridViewColumn.Index == ColumnIndex); + dgvabsEffective = DataGridView.AdjustColumnHeaderBorderStyle(DataGridView.AdvancedColumnHeadersBorderStyle, dataGridViewAdvancedBorderStylePlaceholder, - this.ColumnIndex == this.DataGridView.FirstDisplayedColumnIndex, + ColumnIndex == DataGridView.FirstDisplayedColumnIndex, isLastVisibleColumn); - cellState = this.OwningColumn.State | this.State; + cellState = OwningColumn.State | State; } - else if (this.OwningRow != null) + else if (OwningRow != null) { // Row header cell case Debug.Assert(this is DataGridViewRowHeaderCell); - dgvabsEffective = this.OwningRow.AdjustRowHeaderBorderStyle(this.DataGridView.AdvancedRowHeadersBorderStyle, + dgvabsEffective = OwningRow.AdjustRowHeaderBorderStyle(DataGridView.AdvancedRowHeadersBorderStyle, dataGridViewAdvancedBorderStylePlaceholder, singleVerticalBorderAdded, singleHorizontalBorderAdded, - rowIndex == this.DataGridView.FirstDisplayedRowIndex /*isFirstDisplayedRow*/, - rowIndex == this.DataGridView.Rows.GetLastRow(DataGridViewElementStates.Visible) /*isLastVisibleRow*/); - cellState = this.OwningRow.GetState(rowIndex) | this.State; + rowIndex == DataGridView.FirstDisplayedRowIndex /*isFirstDisplayedRow*/, + rowIndex == DataGridView.Rows.GetLastRow(DataGridViewElementStates.Visible) /*isLastVisibleRow*/); + cellState = OwningRow.GetState(rowIndex) | State; } else { - Debug.Assert(this.OwningColumn == null); - Debug.Assert(this.OwningRow == null); + Debug.Assert(OwningColumn == null); + Debug.Assert(OwningRow == null); Debug.Assert(rowIndex == -1); // TopLeft header cell case - dgvabsEffective = this.DataGridView.AdjustedTopLeftHeaderBorderStyle; - cellState = this.State; + dgvabsEffective = DataGridView.AdjustedTopLeftHeaderBorderStyle; + cellState = State; } cellBounds = new Rectangle(new Point(0, 0), GetSize(rowIndex)); @@ -1199,7 +1199,7 @@ internal Rectangle ComputeErrorIconBounds(Rectangle cellValueBounds) if (cellValueBounds.Width >= DATAGRIDVIEWCELL_iconMarginWidth * 2 + iconsWidth && cellValueBounds.Height >= DATAGRIDVIEWCELL_iconMarginHeight * 2 + iconsHeight) { - Rectangle bmpRect = new Rectangle(this.DataGridView.RightToLeftInternal ? + Rectangle bmpRect = new Rectangle(DataGridView.RightToLeftInternal ? cellValueBounds.Left + DATAGRIDVIEWCELL_iconMarginWidth : cellValueBounds.Right - DATAGRIDVIEWCELL_iconMarginWidth - iconsWidth, cellValueBounds.Y + (cellValueBounds.Height - iconsHeight) / 2, @@ -1246,7 +1246,7 @@ protected virtual AccessibleObject CreateAccessibilityInstance() private void DetachContextMenuStrip(object sender, EventArgs e) { - this.ContextMenuStripInternal = null; + ContextMenuStripInternal = null; } [ @@ -1254,7 +1254,7 @@ private void DetachContextMenuStrip(object sender, EventArgs e) ] public virtual void DetachEditingControl() { - DataGridView dgv = this.DataGridView; + DataGridView dgv = DataGridView; if (dgv == null || dgv.EditingControl == null) { throw new InvalidOperationException(); @@ -1311,7 +1311,7 @@ public virtual void DetachEditingControl() // Since the tooltip is removed when the editing control is shown, // the CurrentMouseLocation is reset to DATAGRIDVIEWCELL_flagAreaNotSet // so that the tooltip appears again on mousemove after the editing. - this.CurrentMouseLocation = DATAGRIDVIEWCELL_flagAreaNotSet; + CurrentMouseLocation = DATAGRIDVIEWCELL_flagAreaNotSet; } public void Dispose() @@ -1324,7 +1324,7 @@ protected virtual void Dispose(bool disposing) { if (disposing) { - ContextMenuStrip contextMenuStrip = (ContextMenuStrip)this.ContextMenuStripInternal; + ContextMenuStrip contextMenuStrip = (ContextMenuStrip)ContextMenuStripInternal; if (contextMenuStrip != null) { contextMenuStrip.Disposed -= new EventHandler(DetachContextMenuStrip); @@ -1496,12 +1496,12 @@ protected virtual object GetClipboardContent(int rowIndex, bool inLastRow, string format) { - if (this.DataGridView == null) + if (DataGridView == null) { return null; } // Header Cell classes override this implementation - this implementation is only for inner cells - if (rowIndex < 0 || rowIndex >= this.DataGridView.Rows.Count) + if (rowIndex < 0 || rowIndex >= DataGridView.Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } @@ -1509,7 +1509,7 @@ protected virtual object GetClipboardContent(int rowIndex, // Assuming (like in other places in this class) that the formatted value is independent of the style colors. DataGridViewCellStyle dataGridViewCellStyle = GetInheritedStyle(null, rowIndex, false); object formattedValue = null; - if (this.DataGridView.IsSharedCellSelected(this, rowIndex)) + if (DataGridView.IsSharedCellSelected(this, rowIndex)) { formattedValue = GetEditedFormattedValue(GetValue(rowIndex), rowIndex, ref dataGridViewCellStyle, DataGridViewDataErrorContexts.Formatting | DataGridViewDataErrorContexts.ClipboardContent); } @@ -1604,18 +1604,18 @@ internal object GetClipboardContentInternal(int rowIndex, internal ContextMenuStrip GetContextMenuStrip(int rowIndex) { - ContextMenuStrip contextMenuStrip = this.ContextMenuStripInternal; - if (this.DataGridView != null && - (this.DataGridView.VirtualMode || this.DataGridView.DataSource != null)) + ContextMenuStrip contextMenuStrip = ContextMenuStripInternal; + if (DataGridView != null && + (DataGridView.VirtualMode || DataGridView.DataSource != null)) { - contextMenuStrip = this.DataGridView.OnCellContextMenuStripNeeded(this.ColumnIndex, rowIndex, contextMenuStrip); + contextMenuStrip = DataGridView.OnCellContextMenuStripNeeded(ColumnIndex, rowIndex, contextMenuStrip); } return contextMenuStrip; } internal void GetContrastedPens(Color baseline, ref Pen darkPen, ref Pen lightPen) { - Debug.Assert(this.DataGridView != null); + Debug.Assert(DataGridView != null); int darkDistance = ColorDistance(baseline, SystemColors.ControlDark); int lightDistance = ColorDistance(baseline, SystemColors.ControlLightLight); @@ -1624,38 +1624,38 @@ internal void GetContrastedPens(Color baseline, ref Pen darkPen, ref Pen lightPe { if (darkDistance < DATAGRIDVIEWCELL_highConstrastThreshold) { - darkPen = this.DataGridView.GetCachedPen(ControlPaint.DarkDark(baseline)); + darkPen = DataGridView.GetCachedPen(ControlPaint.DarkDark(baseline)); } else { - darkPen = this.DataGridView.GetCachedPen(SystemColors.ControlDark); + darkPen = DataGridView.GetCachedPen(SystemColors.ControlDark); } if (lightDistance < DATAGRIDVIEWCELL_highConstrastThreshold) { - lightPen = this.DataGridView.GetCachedPen(ControlPaint.LightLight(baseline)); + lightPen = DataGridView.GetCachedPen(ControlPaint.LightLight(baseline)); } else { - lightPen = this.DataGridView.GetCachedPen(SystemColors.ControlLightLight); + lightPen = DataGridView.GetCachedPen(SystemColors.ControlLightLight); } } else { if (darkDistance < DATAGRIDVIEWCELL_constrastThreshold) { - darkPen = this.DataGridView.GetCachedPen(ControlPaint.Dark(baseline)); + darkPen = DataGridView.GetCachedPen(ControlPaint.Dark(baseline)); } else { - darkPen = this.DataGridView.GetCachedPen(SystemColors.ControlDark); + darkPen = DataGridView.GetCachedPen(SystemColors.ControlDark); } if (lightDistance < DATAGRIDVIEWCELL_constrastThreshold) { - lightPen = this.DataGridView.GetCachedPen(ControlPaint.Light(baseline)); + lightPen = DataGridView.GetCachedPen(ControlPaint.Light(baseline)); } else { - lightPen = this.DataGridView.GetCachedPen(SystemColors.ControlLightLight); + lightPen = DataGridView.GetCachedPen(SystemColors.ControlLightLight); } } } @@ -1711,7 +1711,7 @@ internal void GetContrastedWindowsPens(Color baseline, ref WindowsPen darkPen, r public Rectangle GetContentBounds(int rowIndex) { - if (this.DataGridView == null) + if (DataGridView == null) { return Rectangle.Empty; } @@ -1729,17 +1729,17 @@ protected virtual Rectangle GetContentBounds(Graphics graphics, DataGridViewCell internal object GetEditedFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle dataGridViewCellStyle, DataGridViewDataErrorContexts context) { - Debug.Assert(this.DataGridView != null); - Point ptCurrentCell = this.DataGridView.CurrentCellAddress; - if (this.ColumnIndex == ptCurrentCell.X && rowIndex == ptCurrentCell.Y) + Debug.Assert(DataGridView != null); + Point ptCurrentCell = DataGridView.CurrentCellAddress; + if (ColumnIndex == ptCurrentCell.X && rowIndex == ptCurrentCell.Y) { - IDataGridViewEditingControl dgvectl = (IDataGridViewEditingControl)this.DataGridView.EditingControl; + IDataGridViewEditingControl dgvectl = (IDataGridViewEditingControl)DataGridView.EditingControl; if (dgvectl != null) { return dgvectl.GetEditingControlFormattedValue(context); } IDataGridViewEditingCell dgvecell = this as IDataGridViewEditingCell; - if (dgvecell != null && this.DataGridView.IsCurrentCellInEditMode) + if (dgvecell != null && DataGridView.IsCurrentCellInEditMode) { return dgvecell.GetEditingCellFormattedValue(context); } @@ -1750,7 +1750,7 @@ internal object GetEditedFormattedValue(object value, int rowIndex, ref DataGrid public object GetEditedFormattedValue(int rowIndex, DataGridViewDataErrorContexts context) { - if (this.DataGridView == null) + if (DataGridView == null) { return null; } @@ -1775,32 +1775,32 @@ protected virtual Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewCe protected internal virtual string GetErrorText(int rowIndex) { string errorText = string.Empty; - object objErrorText = this.Properties.GetObject(PropCellErrorText); + object objErrorText = Properties.GetObject(PropCellErrorText); if (objErrorText != null) { errorText = (string)objErrorText; } - else if (this.DataGridView != null && + else if (DataGridView != null && rowIndex != -1 && - rowIndex != this.DataGridView.NewRowIndex && - this.OwningColumn != null && - this.OwningColumn.IsDataBound && - this.DataGridView.DataConnection != null) + rowIndex != DataGridView.NewRowIndex && + OwningColumn != null && + OwningColumn.IsDataBound && + DataGridView.DataConnection != null) { - errorText = this.DataGridView.DataConnection.GetError(this.OwningColumn.BoundColumnIndex, this.ColumnIndex, rowIndex); + errorText = DataGridView.DataConnection.GetError(OwningColumn.BoundColumnIndex, ColumnIndex, rowIndex); } - if (this.DataGridView != null && (this.DataGridView.VirtualMode || this.DataGridView.DataSource != null) && - this.ColumnIndex >= 0 && rowIndex >= 0) + if (DataGridView != null && (DataGridView.VirtualMode || DataGridView.DataSource != null) && + ColumnIndex >= 0 && rowIndex >= 0) { - errorText = this.DataGridView.OnCellErrorTextNeeded(this.ColumnIndex, rowIndex, errorText); + errorText = DataGridView.OnCellErrorTextNeeded(ColumnIndex, rowIndex, errorText); } return errorText; } internal object GetFormattedValue(int rowIndex, ref DataGridViewCellStyle cellStyle, DataGridViewDataErrorContexts context) { - if (this.DataGridView == null) + if (DataGridView == null) { return null; } @@ -1820,27 +1820,27 @@ protected virtual object GetFormattedValue(object value, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context) { - if (this.DataGridView == null) + if (DataGridView == null) { return null; } - DataGridViewCellFormattingEventArgs gdvcfe = this.DataGridView.OnCellFormatting(this.ColumnIndex, rowIndex, value, this.FormattedValueType, cellStyle); + DataGridViewCellFormattingEventArgs gdvcfe = DataGridView.OnCellFormatting(ColumnIndex, rowIndex, value, FormattedValueType, cellStyle); cellStyle = gdvcfe.CellStyle; bool formattingApplied = gdvcfe.FormattingApplied; object formattedValue = gdvcfe.Value; bool checkFormattedValType = true; if (!formattingApplied && - this.FormattedValueType != null && - (formattedValue == null || !this.FormattedValueType.IsAssignableFrom(formattedValue.GetType()))) + FormattedValueType != null && + (formattedValue == null || !FormattedValueType.IsAssignableFrom(formattedValue.GetType()))) { try { formattedValue = Formatter.FormatObject(formattedValue, - this.FormattedValueType, - valueTypeConverter == null ? this.ValueTypeConverter : valueTypeConverter, /*sourceConverter*/ - formattedValueTypeConverter == null ? this.FormattedValueTypeConverter : formattedValueTypeConverter, /*targetConverter*/ + FormattedValueType, + valueTypeConverter == null ? ValueTypeConverter : valueTypeConverter, /*sourceConverter*/ + formattedValueTypeConverter == null ? FormattedValueTypeConverter : formattedValueTypeConverter, /*targetConverter*/ cellStyle.Format, cellStyle.FormatProvider, cellStyle.NullValue, @@ -1854,7 +1854,7 @@ protected virtual object GetFormattedValue(object value, } // Formatting failed, raise OnDataError event. DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs(exception, - this.ColumnIndex, + ColumnIndex, rowIndex, context); RaiseDataError(dgvdee); @@ -1867,18 +1867,18 @@ protected virtual object GetFormattedValue(object value, } if (checkFormattedValType && - (formattedValue == null || this.FormattedValueType == null || !this.FormattedValueType.IsAssignableFrom(formattedValue.GetType()))) + (formattedValue == null || FormattedValueType == null || !FormattedValueType.IsAssignableFrom(formattedValue.GetType()))) { if (formattedValue == null && cellStyle.NullValue == null && - this.FormattedValueType != null && - !typeof(System.ValueType).IsAssignableFrom(this.FormattedValueType)) + FormattedValueType != null && + !typeof(System.ValueType).IsAssignableFrom(FormattedValueType)) { // null is an acceptable formatted value return null; } Exception exception = null; - if (this.FormattedValueType == null) + if (FormattedValueType == null) { exception = new FormatException(string.Format(SR.DataGridViewCell_FormattedValueTypeNull)); } @@ -1887,7 +1887,7 @@ protected virtual object GetFormattedValue(object value, exception = new FormatException(string.Format(SR.DataGridViewCell_FormattedValueHasWrongType)); } DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs(exception, - this.ColumnIndex, + ColumnIndex, rowIndex, context); RaiseDataError(dgvdee); @@ -1931,27 +1931,27 @@ static internal DataGridViewFreeDimension GetFreeDimensionFromConstraint(Size co internal int GetHeight(int rowIndex) { - if (this.DataGridView == null) + if (DataGridView == null) { return -1; } - Debug.Assert(this.owningRow != null); - return this.owningRow.GetHeight(rowIndex); + Debug.Assert(owningRow != null); + return owningRow.GetHeight(rowIndex); } public virtual ContextMenuStrip GetInheritedContextMenuStrip(int rowIndex) { - if (this.DataGridView != null) + if (DataGridView != null) { - if (rowIndex < 0 || rowIndex >= this.DataGridView.Rows.Count) + if (rowIndex < 0 || rowIndex >= DataGridView.Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - if (this.ColumnIndex < 0) + if (ColumnIndex < 0) { throw new InvalidOperationException(); } - Debug.Assert(this.ColumnIndex < this.DataGridView.Columns.Count); + Debug.Assert(ColumnIndex < DataGridView.Columns.Count); } ContextMenuStrip contextMenuStrip = GetContextMenuStrip(rowIndex); @@ -1960,27 +1960,27 @@ public virtual ContextMenuStrip GetInheritedContextMenuStrip(int rowIndex) return contextMenuStrip; } - if (this.owningRow != null) + if (owningRow != null) { - contextMenuStrip = this.owningRow.GetContextMenuStrip(rowIndex); + contextMenuStrip = owningRow.GetContextMenuStrip(rowIndex); if (contextMenuStrip != null) { return contextMenuStrip; } } - if (this.owningColumn != null) + if (owningColumn != null) { - contextMenuStrip = this.owningColumn.ContextMenuStrip; + contextMenuStrip = owningColumn.ContextMenuStrip; if (contextMenuStrip != null) { return contextMenuStrip; } } - if (this.DataGridView != null) + if (DataGridView != null) { - return this.DataGridView.ContextMenuStrip; + return DataGridView.ContextMenuStrip; } else { @@ -1990,19 +1990,19 @@ public virtual ContextMenuStrip GetInheritedContextMenuStrip(int rowIndex) public virtual DataGridViewElementStates GetInheritedState(int rowIndex) { - DataGridViewElementStates state = this.State | DataGridViewElementStates.ResizableSet; + DataGridViewElementStates state = State | DataGridViewElementStates.ResizableSet; - if (this.DataGridView == null) + if (DataGridView == null) { - Debug.Assert(this.RowIndex == -1); + Debug.Assert(RowIndex == -1); if (rowIndex != -1) { throw new ArgumentException(string.Format(SR.InvalidArgument, nameof(rowIndex), rowIndex)); } - if (this.owningRow != null) + if (owningRow != null) { - state |= (this.owningRow.GetState(-1) & (DataGridViewElementStates.Frozen | DataGridViewElementStates.ReadOnly | DataGridViewElementStates.Selected | DataGridViewElementStates.Visible)); - if (this.owningRow.GetResizable(rowIndex) == DataGridViewTriState.True) + state |= (owningRow.GetState(-1) & (DataGridViewElementStates.Frozen | DataGridViewElementStates.ReadOnly | DataGridViewElementStates.Selected | DataGridViewElementStates.Visible)); + if (owningRow.GetResizable(rowIndex) == DataGridViewTriState.True) { state |= DataGridViewElementStates.Resizable; } @@ -2011,93 +2011,93 @@ public virtual DataGridViewElementStates GetInheritedState(int rowIndex) } // Header Cell classes override this implementation - this implementation is only for inner cells - if (rowIndex < 0 || rowIndex >= this.DataGridView.Rows.Count) + if (rowIndex < 0 || rowIndex >= DataGridView.Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - Debug.Assert(this.owningColumn != null); - Debug.Assert(this.owningRow != null); - Debug.Assert(this.ColumnIndex >= 0); + Debug.Assert(owningColumn != null); + Debug.Assert(owningRow != null); + Debug.Assert(ColumnIndex >= 0); - if (this.DataGridView.Rows.SharedRow(rowIndex) != this.owningRow) + if (DataGridView.Rows.SharedRow(rowIndex) != owningRow) { throw new ArgumentException(string.Format(SR.InvalidArgument, nameof(rowIndex), rowIndex)); } - DataGridViewElementStates rowEffectiveState = this.DataGridView.Rows.GetRowState(rowIndex); + DataGridViewElementStates rowEffectiveState = DataGridView.Rows.GetRowState(rowIndex); state |= (rowEffectiveState & (DataGridViewElementStates.ReadOnly | DataGridViewElementStates.Selected)); - state |= (this.owningColumn.State & (DataGridViewElementStates.ReadOnly | DataGridViewElementStates.Selected)); + state |= (owningColumn.State & (DataGridViewElementStates.ReadOnly | DataGridViewElementStates.Selected)); - if (this.owningRow.GetResizable(rowIndex) == DataGridViewTriState.True || - this.owningColumn.Resizable == DataGridViewTriState.True) + if (owningRow.GetResizable(rowIndex) == DataGridViewTriState.True || + owningColumn.Resizable == DataGridViewTriState.True) { state |= DataGridViewElementStates.Resizable; } - if (this.owningColumn.Visible && this.owningRow.GetVisible(rowIndex)) + if (owningColumn.Visible && owningRow.GetVisible(rowIndex)) { state |= DataGridViewElementStates.Visible; - if (this.owningColumn.Displayed && this.owningRow.GetDisplayed(rowIndex)) + if (owningColumn.Displayed && owningRow.GetDisplayed(rowIndex)) { state |= DataGridViewElementStates.Displayed; } } - if (this.owningColumn.Frozen && this.owningRow.GetFrozen(rowIndex)) + if (owningColumn.Frozen && owningRow.GetFrozen(rowIndex)) { state |= DataGridViewElementStates.Frozen; } #if DEBUG DataGridViewElementStates stateDebug = DataGridViewElementStates.ResizableSet; - if (this.Displayed) + if (Displayed) { stateDebug |= DataGridViewElementStates.Displayed; } - if (this.Frozen) + if (Frozen) { stateDebug |= DataGridViewElementStates.Frozen; } - if (this.ReadOnly) + if (ReadOnly) { stateDebug |= DataGridViewElementStates.ReadOnly; } - if (this.Resizable) + if (Resizable) { stateDebug |= DataGridViewElementStates.Resizable; } - if (this.Selected) + if (Selected) { stateDebug |= DataGridViewElementStates.Selected; } - if (this.Visible) + if (Visible) { stateDebug |= DataGridViewElementStates.Visible; } - Debug.Assert(state == stateDebug || this.DataGridView.Rows.SharedRow(rowIndex).Index == -1); + Debug.Assert(state == stateDebug || DataGridView.Rows.SharedRow(rowIndex).Index == -1); #endif return state; } public virtual DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle inheritedCellStyle, int rowIndex, bool includeColors) { - if (this.DataGridView == null) + if (DataGridView == null) { throw new InvalidOperationException(SR.DataGridView_CellNeedsDataGridViewForInheritedStyle); } - if (rowIndex < 0 || rowIndex >= this.DataGridView.Rows.Count) + if (rowIndex < 0 || rowIndex >= DataGridView.Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - if (this.ColumnIndex < 0) + if (ColumnIndex < 0) { throw new InvalidOperationException(); } - Debug.Assert(this.ColumnIndex < this.DataGridView.Columns.Count); + Debug.Assert(ColumnIndex < DataGridView.Columns.Count); DataGridViewCellStyle inheritedCellStyleTmp; if (inheritedCellStyle == null) { - inheritedCellStyleTmp = this.DataGridView.PlaceholderCellStyle; + inheritedCellStyleTmp = DataGridView.PlaceholderCellStyle; if (!includeColors) { inheritedCellStyleTmp.BackColor = Color.Empty; @@ -2112,27 +2112,27 @@ public virtual DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle inh } DataGridViewCellStyle cellStyle = null; - if (this.HasStyle) + if (HasStyle) { - cellStyle = this.Style; + cellStyle = Style; Debug.Assert(cellStyle != null); } DataGridViewCellStyle rowStyle = null; - if (this.DataGridView.Rows.SharedRow(rowIndex).HasDefaultCellStyle) + if (DataGridView.Rows.SharedRow(rowIndex).HasDefaultCellStyle) { - rowStyle = this.DataGridView.Rows.SharedRow(rowIndex).DefaultCellStyle; + rowStyle = DataGridView.Rows.SharedRow(rowIndex).DefaultCellStyle; Debug.Assert(rowStyle != null); } DataGridViewCellStyle columnStyle = null; - if (this.owningColumn.HasDefaultCellStyle) + if (owningColumn.HasDefaultCellStyle) { - columnStyle = this.owningColumn.DefaultCellStyle; + columnStyle = owningColumn.DefaultCellStyle; Debug.Assert(columnStyle != null); } - DataGridViewCellStyle dataGridViewStyle = this.DataGridView.DefaultCellStyle; + DataGridViewCellStyle dataGridViewStyle = DataGridView.DefaultCellStyle; Debug.Assert(dataGridViewStyle != null); if (includeColors) @@ -2145,14 +2145,14 @@ public virtual DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle inh { inheritedCellStyleTmp.BackColor = rowStyle.BackColor; } - else if (!this.DataGridView.RowsDefaultCellStyle.BackColor.IsEmpty && - (rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.BackColor.IsEmpty)) + else if (!DataGridView.RowsDefaultCellStyle.BackColor.IsEmpty && + (rowIndex % 2 == 0 || DataGridView.AlternatingRowsDefaultCellStyle.BackColor.IsEmpty)) { - inheritedCellStyleTmp.BackColor = this.DataGridView.RowsDefaultCellStyle.BackColor; + inheritedCellStyleTmp.BackColor = DataGridView.RowsDefaultCellStyle.BackColor; } - else if (rowIndex % 2 == 1 && !this.DataGridView.AlternatingRowsDefaultCellStyle.BackColor.IsEmpty) + else if (rowIndex % 2 == 1 && !DataGridView.AlternatingRowsDefaultCellStyle.BackColor.IsEmpty) { - inheritedCellStyleTmp.BackColor = this.DataGridView.AlternatingRowsDefaultCellStyle.BackColor; + inheritedCellStyleTmp.BackColor = DataGridView.AlternatingRowsDefaultCellStyle.BackColor; } else if (columnStyle != null && !columnStyle.BackColor.IsEmpty) { @@ -2171,14 +2171,14 @@ public virtual DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle inh { inheritedCellStyleTmp.ForeColor = rowStyle.ForeColor; } - else if (!this.DataGridView.RowsDefaultCellStyle.ForeColor.IsEmpty && - (rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.ForeColor.IsEmpty)) + else if (!DataGridView.RowsDefaultCellStyle.ForeColor.IsEmpty && + (rowIndex % 2 == 0 || DataGridView.AlternatingRowsDefaultCellStyle.ForeColor.IsEmpty)) { - inheritedCellStyleTmp.ForeColor = this.DataGridView.RowsDefaultCellStyle.ForeColor; + inheritedCellStyleTmp.ForeColor = DataGridView.RowsDefaultCellStyle.ForeColor; } - else if (rowIndex % 2 == 1 && !this.DataGridView.AlternatingRowsDefaultCellStyle.ForeColor.IsEmpty) + else if (rowIndex % 2 == 1 && !DataGridView.AlternatingRowsDefaultCellStyle.ForeColor.IsEmpty) { - inheritedCellStyleTmp.ForeColor = this.DataGridView.AlternatingRowsDefaultCellStyle.ForeColor; + inheritedCellStyleTmp.ForeColor = DataGridView.AlternatingRowsDefaultCellStyle.ForeColor; } else if (columnStyle != null && !columnStyle.ForeColor.IsEmpty) { @@ -2197,14 +2197,14 @@ public virtual DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle inh { inheritedCellStyleTmp.SelectionBackColor = rowStyle.SelectionBackColor; } - else if (!this.DataGridView.RowsDefaultCellStyle.SelectionBackColor.IsEmpty && - (rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.SelectionBackColor.IsEmpty)) + else if (!DataGridView.RowsDefaultCellStyle.SelectionBackColor.IsEmpty && + (rowIndex % 2 == 0 || DataGridView.AlternatingRowsDefaultCellStyle.SelectionBackColor.IsEmpty)) { - inheritedCellStyleTmp.SelectionBackColor = this.DataGridView.RowsDefaultCellStyle.SelectionBackColor; + inheritedCellStyleTmp.SelectionBackColor = DataGridView.RowsDefaultCellStyle.SelectionBackColor; } - else if (rowIndex % 2 == 1 && !this.DataGridView.AlternatingRowsDefaultCellStyle.SelectionBackColor.IsEmpty) + else if (rowIndex % 2 == 1 && !DataGridView.AlternatingRowsDefaultCellStyle.SelectionBackColor.IsEmpty) { - inheritedCellStyleTmp.SelectionBackColor = this.DataGridView.AlternatingRowsDefaultCellStyle.SelectionBackColor; + inheritedCellStyleTmp.SelectionBackColor = DataGridView.AlternatingRowsDefaultCellStyle.SelectionBackColor; } else if (columnStyle != null && !columnStyle.SelectionBackColor.IsEmpty) { @@ -2223,14 +2223,14 @@ public virtual DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle inh { inheritedCellStyleTmp.SelectionForeColor = rowStyle.SelectionForeColor; } - else if (!this.DataGridView.RowsDefaultCellStyle.SelectionForeColor.IsEmpty && - (rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.SelectionForeColor.IsEmpty)) + else if (!DataGridView.RowsDefaultCellStyle.SelectionForeColor.IsEmpty && + (rowIndex % 2 == 0 || DataGridView.AlternatingRowsDefaultCellStyle.SelectionForeColor.IsEmpty)) { - inheritedCellStyleTmp.SelectionForeColor = this.DataGridView.RowsDefaultCellStyle.SelectionForeColor; + inheritedCellStyleTmp.SelectionForeColor = DataGridView.RowsDefaultCellStyle.SelectionForeColor; } - else if (rowIndex % 2 == 1 && !this.DataGridView.AlternatingRowsDefaultCellStyle.SelectionForeColor.IsEmpty) + else if (rowIndex % 2 == 1 && !DataGridView.AlternatingRowsDefaultCellStyle.SelectionForeColor.IsEmpty) { - inheritedCellStyleTmp.SelectionForeColor = this.DataGridView.AlternatingRowsDefaultCellStyle.SelectionForeColor; + inheritedCellStyleTmp.SelectionForeColor = DataGridView.AlternatingRowsDefaultCellStyle.SelectionForeColor; } else if (columnStyle != null && !columnStyle.SelectionForeColor.IsEmpty) { @@ -2250,14 +2250,14 @@ public virtual DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle inh { inheritedCellStyleTmp.Font = rowStyle.Font; } - else if (this.DataGridView.RowsDefaultCellStyle.Font != null && - (rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.Font == null)) + else if (DataGridView.RowsDefaultCellStyle.Font != null && + (rowIndex % 2 == 0 || DataGridView.AlternatingRowsDefaultCellStyle.Font == null)) { - inheritedCellStyleTmp.Font = this.DataGridView.RowsDefaultCellStyle.Font; + inheritedCellStyleTmp.Font = DataGridView.RowsDefaultCellStyle.Font; } - else if (rowIndex % 2 == 1 && this.DataGridView.AlternatingRowsDefaultCellStyle.Font != null) + else if (rowIndex % 2 == 1 && DataGridView.AlternatingRowsDefaultCellStyle.Font != null) { - inheritedCellStyleTmp.Font = this.DataGridView.AlternatingRowsDefaultCellStyle.Font; + inheritedCellStyleTmp.Font = DataGridView.AlternatingRowsDefaultCellStyle.Font; } else if (columnStyle != null && columnStyle.Font != null) { @@ -2276,15 +2276,15 @@ public virtual DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle inh { inheritedCellStyleTmp.NullValue = rowStyle.NullValue; } - else if (!this.DataGridView.RowsDefaultCellStyle.IsNullValueDefault && - (rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.IsNullValueDefault)) + else if (!DataGridView.RowsDefaultCellStyle.IsNullValueDefault && + (rowIndex % 2 == 0 || DataGridView.AlternatingRowsDefaultCellStyle.IsNullValueDefault)) { - inheritedCellStyleTmp.NullValue = this.DataGridView.RowsDefaultCellStyle.NullValue; + inheritedCellStyleTmp.NullValue = DataGridView.RowsDefaultCellStyle.NullValue; } else if (rowIndex % 2 == 1 && - !this.DataGridView.AlternatingRowsDefaultCellStyle.IsNullValueDefault) + !DataGridView.AlternatingRowsDefaultCellStyle.IsNullValueDefault) { - inheritedCellStyleTmp.NullValue = this.DataGridView.AlternatingRowsDefaultCellStyle.NullValue; + inheritedCellStyleTmp.NullValue = DataGridView.AlternatingRowsDefaultCellStyle.NullValue; } else if (columnStyle != null && !columnStyle.IsNullValueDefault) { @@ -2303,15 +2303,15 @@ public virtual DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle inh { inheritedCellStyleTmp.DataSourceNullValue = rowStyle.DataSourceNullValue; } - else if (!this.DataGridView.RowsDefaultCellStyle.IsDataSourceNullValueDefault && - (rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.IsDataSourceNullValueDefault)) + else if (!DataGridView.RowsDefaultCellStyle.IsDataSourceNullValueDefault && + (rowIndex % 2 == 0 || DataGridView.AlternatingRowsDefaultCellStyle.IsDataSourceNullValueDefault)) { - inheritedCellStyleTmp.DataSourceNullValue = this.DataGridView.RowsDefaultCellStyle.DataSourceNullValue; + inheritedCellStyleTmp.DataSourceNullValue = DataGridView.RowsDefaultCellStyle.DataSourceNullValue; } else if (rowIndex % 2 == 1 && - !this.DataGridView.AlternatingRowsDefaultCellStyle.IsDataSourceNullValueDefault) + !DataGridView.AlternatingRowsDefaultCellStyle.IsDataSourceNullValueDefault) { - inheritedCellStyleTmp.DataSourceNullValue = this.DataGridView.AlternatingRowsDefaultCellStyle.DataSourceNullValue; + inheritedCellStyleTmp.DataSourceNullValue = DataGridView.AlternatingRowsDefaultCellStyle.DataSourceNullValue; } else if (columnStyle != null && !columnStyle.IsDataSourceNullValueDefault) { @@ -2330,14 +2330,14 @@ public virtual DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle inh { inheritedCellStyleTmp.Format = rowStyle.Format; } - else if (this.DataGridView.RowsDefaultCellStyle.Format.Length != 0 && - (rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.Format.Length == 0)) + else if (DataGridView.RowsDefaultCellStyle.Format.Length != 0 && + (rowIndex % 2 == 0 || DataGridView.AlternatingRowsDefaultCellStyle.Format.Length == 0)) { - inheritedCellStyleTmp.Format = this.DataGridView.RowsDefaultCellStyle.Format; + inheritedCellStyleTmp.Format = DataGridView.RowsDefaultCellStyle.Format; } - else if (rowIndex % 2 == 1 && this.DataGridView.AlternatingRowsDefaultCellStyle.Format.Length != 0) + else if (rowIndex % 2 == 1 && DataGridView.AlternatingRowsDefaultCellStyle.Format.Length != 0) { - inheritedCellStyleTmp.Format = this.DataGridView.AlternatingRowsDefaultCellStyle.Format; + inheritedCellStyleTmp.Format = DataGridView.AlternatingRowsDefaultCellStyle.Format; } else if (columnStyle != null && columnStyle.Format.Length != 0) { @@ -2356,14 +2356,14 @@ public virtual DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle inh { inheritedCellStyleTmp.FormatProvider = rowStyle.FormatProvider; } - else if (!this.DataGridView.RowsDefaultCellStyle.IsFormatProviderDefault && - (rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.IsFormatProviderDefault)) + else if (!DataGridView.RowsDefaultCellStyle.IsFormatProviderDefault && + (rowIndex % 2 == 0 || DataGridView.AlternatingRowsDefaultCellStyle.IsFormatProviderDefault)) { - inheritedCellStyleTmp.FormatProvider = this.DataGridView.RowsDefaultCellStyle.FormatProvider; + inheritedCellStyleTmp.FormatProvider = DataGridView.RowsDefaultCellStyle.FormatProvider; } - else if (rowIndex % 2 == 1 && !this.DataGridView.AlternatingRowsDefaultCellStyle.IsFormatProviderDefault) + else if (rowIndex % 2 == 1 && !DataGridView.AlternatingRowsDefaultCellStyle.IsFormatProviderDefault) { - inheritedCellStyleTmp.FormatProvider = this.DataGridView.AlternatingRowsDefaultCellStyle.FormatProvider; + inheritedCellStyleTmp.FormatProvider = DataGridView.AlternatingRowsDefaultCellStyle.FormatProvider; } else if (columnStyle != null && !columnStyle.IsFormatProviderDefault) { @@ -2382,14 +2382,14 @@ public virtual DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle inh { inheritedCellStyleTmp.AlignmentInternal = rowStyle.Alignment; } - else if (this.DataGridView.RowsDefaultCellStyle.Alignment != DataGridViewContentAlignment.NotSet && - (rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.Alignment == DataGridViewContentAlignment.NotSet)) + else if (DataGridView.RowsDefaultCellStyle.Alignment != DataGridViewContentAlignment.NotSet && + (rowIndex % 2 == 0 || DataGridView.AlternatingRowsDefaultCellStyle.Alignment == DataGridViewContentAlignment.NotSet)) { - inheritedCellStyleTmp.AlignmentInternal = this.DataGridView.RowsDefaultCellStyle.Alignment; + inheritedCellStyleTmp.AlignmentInternal = DataGridView.RowsDefaultCellStyle.Alignment; } - else if (rowIndex % 2 == 1 && this.DataGridView.AlternatingRowsDefaultCellStyle.Alignment != DataGridViewContentAlignment.NotSet) + else if (rowIndex % 2 == 1 && DataGridView.AlternatingRowsDefaultCellStyle.Alignment != DataGridViewContentAlignment.NotSet) { - inheritedCellStyleTmp.AlignmentInternal = this.DataGridView.AlternatingRowsDefaultCellStyle.Alignment; + inheritedCellStyleTmp.AlignmentInternal = DataGridView.AlternatingRowsDefaultCellStyle.Alignment; } else if (columnStyle != null && columnStyle.Alignment != DataGridViewContentAlignment.NotSet) { @@ -2409,14 +2409,14 @@ public virtual DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle inh { inheritedCellStyleTmp.WrapModeInternal = rowStyle.WrapMode; } - else if (this.DataGridView.RowsDefaultCellStyle.WrapMode != DataGridViewTriState.NotSet && - (rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.WrapMode == DataGridViewTriState.NotSet)) + else if (DataGridView.RowsDefaultCellStyle.WrapMode != DataGridViewTriState.NotSet && + (rowIndex % 2 == 0 || DataGridView.AlternatingRowsDefaultCellStyle.WrapMode == DataGridViewTriState.NotSet)) { - inheritedCellStyleTmp.WrapModeInternal = this.DataGridView.RowsDefaultCellStyle.WrapMode; + inheritedCellStyleTmp.WrapModeInternal = DataGridView.RowsDefaultCellStyle.WrapMode; } - else if (rowIndex % 2 == 1 && this.DataGridView.AlternatingRowsDefaultCellStyle.WrapMode != DataGridViewTriState.NotSet) + else if (rowIndex % 2 == 1 && DataGridView.AlternatingRowsDefaultCellStyle.WrapMode != DataGridViewTriState.NotSet) { - inheritedCellStyleTmp.WrapModeInternal = this.DataGridView.AlternatingRowsDefaultCellStyle.WrapMode; + inheritedCellStyleTmp.WrapModeInternal = DataGridView.AlternatingRowsDefaultCellStyle.WrapMode; } else if (columnStyle != null && columnStyle.WrapMode != DataGridViewTriState.NotSet) { @@ -2436,14 +2436,14 @@ public virtual DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle inh { inheritedCellStyleTmp.Tag = rowStyle.Tag; } - else if (this.DataGridView.RowsDefaultCellStyle.Tag != null && - (rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.Tag == null)) + else if (DataGridView.RowsDefaultCellStyle.Tag != null && + (rowIndex % 2 == 0 || DataGridView.AlternatingRowsDefaultCellStyle.Tag == null)) { - inheritedCellStyleTmp.Tag = this.DataGridView.RowsDefaultCellStyle.Tag; + inheritedCellStyleTmp.Tag = DataGridView.RowsDefaultCellStyle.Tag; } - else if (rowIndex % 2 == 1 && this.DataGridView.AlternatingRowsDefaultCellStyle.Tag != null) + else if (rowIndex % 2 == 1 && DataGridView.AlternatingRowsDefaultCellStyle.Tag != null) { - inheritedCellStyleTmp.Tag = this.DataGridView.AlternatingRowsDefaultCellStyle.Tag; + inheritedCellStyleTmp.Tag = DataGridView.AlternatingRowsDefaultCellStyle.Tag; } else if (columnStyle != null && columnStyle.Tag != null) { @@ -2462,14 +2462,14 @@ public virtual DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle inh { inheritedCellStyleTmp.PaddingInternal = rowStyle.Padding; } - else if (this.DataGridView.RowsDefaultCellStyle.Padding != Padding.Empty && - (rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.Padding == Padding.Empty)) + else if (DataGridView.RowsDefaultCellStyle.Padding != Padding.Empty && + (rowIndex % 2 == 0 || DataGridView.AlternatingRowsDefaultCellStyle.Padding == Padding.Empty)) { - inheritedCellStyleTmp.PaddingInternal = this.DataGridView.RowsDefaultCellStyle.Padding; + inheritedCellStyleTmp.PaddingInternal = DataGridView.RowsDefaultCellStyle.Padding; } - else if (rowIndex % 2 == 1 && this.DataGridView.AlternatingRowsDefaultCellStyle.Padding != Padding.Empty) + else if (rowIndex % 2 == 1 && DataGridView.AlternatingRowsDefaultCellStyle.Padding != Padding.Empty) { - inheritedCellStyleTmp.PaddingInternal = this.DataGridView.AlternatingRowsDefaultCellStyle.Padding; + inheritedCellStyleTmp.PaddingInternal = DataGridView.AlternatingRowsDefaultCellStyle.Padding; } else if (columnStyle != null && columnStyle.Padding != Padding.Empty) { @@ -2492,7 +2492,7 @@ internal int GetPreferredHeight(int rowIndex, int width) { Debug.Assert(width > 0); - if (this.DataGridView == null) + if (DataGridView == null) { return -1; } @@ -2506,7 +2506,7 @@ internal int GetPreferredHeight(int rowIndex, int width) internal Size GetPreferredSize(int rowIndex) { - if (this.DataGridView == null) + if (DataGridView == null) { return new Size(-1, -1); } @@ -2548,7 +2548,7 @@ internal int GetPreferredWidth(int rowIndex, int height) { Debug.Assert(height > 0); - if (this.DataGridView == null) + if (DataGridView == null) { return -1; } @@ -2562,7 +2562,7 @@ internal int GetPreferredWidth(int rowIndex, int height) protected virtual Size GetSize(int rowIndex) { - if (this.DataGridView == null) + if (DataGridView == null) { return new Size(-1, -1); } @@ -2570,46 +2570,46 @@ protected virtual Size GetSize(int rowIndex) { throw new InvalidOperationException(string.Format(SR.DataGridView_InvalidPropertyGetOnSharedCell, "Size")); } - Debug.Assert(this.owningColumn != null); - Debug.Assert(this.owningRow != null); - return new Size(this.owningColumn.Thickness, this.owningRow.GetHeight(rowIndex)); + Debug.Assert(owningColumn != null); + Debug.Assert(owningRow != null); + return new Size(owningColumn.Thickness, owningRow.GetHeight(rowIndex)); } private string GetToolTipText(int rowIndex) { - string toolTipText = this.ToolTipTextInternal; - if (this.DataGridView != null && - (this.DataGridView.VirtualMode || this.DataGridView.DataSource != null)) + string toolTipText = ToolTipTextInternal; + if (DataGridView != null && + (DataGridView.VirtualMode || DataGridView.DataSource != null)) { - toolTipText = this.DataGridView.OnCellToolTipTextNeeded(this.ColumnIndex, rowIndex, toolTipText); + toolTipText = DataGridView.OnCellToolTipTextNeeded(ColumnIndex, rowIndex, toolTipText); } return toolTipText; } protected virtual object GetValue(int rowIndex) { - DataGridView dataGridView = this.DataGridView; + DataGridView dataGridView = DataGridView; if (dataGridView != null) { if (rowIndex < 0 || rowIndex >= dataGridView.Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - if (this.ColumnIndex < 0) + if (ColumnIndex < 0) { throw new InvalidOperationException(); } - Debug.Assert(this.ColumnIndex < dataGridView.Columns.Count); + Debug.Assert(ColumnIndex < dataGridView.Columns.Count); } if (dataGridView == null || (dataGridView.AllowUserToAddRowsInternal && rowIndex > -1 && rowIndex == dataGridView.NewRowIndex && rowIndex != dataGridView.CurrentCellAddress.Y) || - (!dataGridView.VirtualMode && this.OwningColumn != null && !this.OwningColumn.IsDataBound) || + (!dataGridView.VirtualMode && OwningColumn != null && !OwningColumn.IsDataBound) || rowIndex == -1 || - this.ColumnIndex == -1) + ColumnIndex == -1) { - return this.Properties.GetObject(PropCellValue); + return Properties.GetObject(PropCellValue); } - else if (this.OwningColumn != null && this.OwningColumn.IsDataBound) + else if (OwningColumn != null && OwningColumn.IsDataBound) { DataGridView.DataGridViewDataConnection dataConnection = dataGridView.DataConnection; if (dataConnection == null) @@ -2618,18 +2618,18 @@ protected virtual object GetValue(int rowIndex) } else if (dataConnection.CurrencyManager.Count <= rowIndex) { - return this.Properties.GetObject(PropCellValue); + return Properties.GetObject(PropCellValue); } else { - return dataConnection.GetValue(this.OwningColumn.BoundColumnIndex, this.ColumnIndex, rowIndex); + return dataConnection.GetValue(OwningColumn.BoundColumnIndex, ColumnIndex, rowIndex); } } else { Debug.Assert(rowIndex >= 0); - Debug.Assert(this.ColumnIndex >= 0); - return dataGridView.OnCellValueNeeded(this.ColumnIndex, rowIndex); + Debug.Assert(ColumnIndex >= 0); + return dataGridView.OnCellValueNeeded(ColumnIndex, rowIndex); } } @@ -2643,7 +2643,7 @@ internal object GetValueInternal(int rowIndex) ] public virtual void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle) { - DataGridView dgv = this.DataGridView; + DataGridView dgv = DataGridView; if (dgv == null || dgv.EditingControl == null) { throw new InvalidOperationException(); @@ -2995,20 +2995,20 @@ internal bool MouseUpUnsharesRowInternal(DataGridViewCellMouseEventArgs e) private void OnCellDataAreaMouseEnterInternal(int rowIndex) { - Debug.Assert(this.DataGridView != null); - if (!this.DataGridView.ShowCellToolTips) + Debug.Assert(DataGridView != null); + if (!DataGridView.ShowCellToolTips) { return; } // Don't show a tooltip for edited cells with an editing control - Point ptCurrentCell = this.DataGridView.CurrentCellAddress; + Point ptCurrentCell = DataGridView.CurrentCellAddress; if (ptCurrentCell.X != -1 && - ptCurrentCell.X == this.ColumnIndex && + ptCurrentCell.X == ColumnIndex && ptCurrentCell.Y == rowIndex && - this.DataGridView.EditingControl != null) + DataGridView.EditingControl != null) { - Debug.Assert(this.DataGridView.IsCurrentCellInEditMode); + Debug.Assert(DataGridView.IsCurrentCellInEditMode); return; } @@ -3017,14 +3017,14 @@ private void OnCellDataAreaMouseEnterInternal(int rowIndex) if (string.IsNullOrEmpty(toolTipText)) { - if (this.FormattedValueType == stringType) + if (FormattedValueType == stringType) { - if (rowIndex != -1 && this.OwningColumn != null) + if (rowIndex != -1 && OwningColumn != null) { - int width = GetPreferredWidth(rowIndex, this.OwningRow.Height); - int height = GetPreferredHeight(rowIndex, this.OwningColumn.Width); + int width = GetPreferredWidth(rowIndex, OwningRow.Height); + int height = GetPreferredHeight(rowIndex, OwningColumn.Width); - if (this.OwningColumn.Width < width || this.OwningRow.Height < height) + if (OwningColumn.Width < width || OwningRow.Height < height) { DataGridViewCellStyle dataGridViewCellStyle = GetInheritedStyle(null, rowIndex, false /*includeColors*/); string editedFormattedValue = GetEditedFormattedValue(GetValue(rowIndex), @@ -3037,7 +3037,7 @@ private void OnCellDataAreaMouseEnterInternal(int rowIndex) } } } - else if ((rowIndex != -1 && this.OwningRow != null && this.DataGridView.RowHeadersVisible && this.DataGridView.RowHeadersWidth > 0 && this.OwningColumn == null) || + else if ((rowIndex != -1 && OwningRow != null && DataGridView.RowHeadersVisible && DataGridView.RowHeadersWidth > 0 && OwningColumn == null) || rowIndex == -1) { // we are on a header cell. @@ -3056,7 +3056,7 @@ private void OnCellDataAreaMouseEnterInternal(int rowIndex) if (contentBounds.Width > 0) { preferredHeight = DataGridViewCell.GetPreferredTextHeight(g, - this.DataGridView.RightToLeftInternal, + DataGridView.RightToLeftInternal, stringValue, dataGridViewCellStyle, contentBounds.Width, @@ -3078,7 +3078,7 @@ private void OnCellDataAreaMouseEnterInternal(int rowIndex) if (!string.IsNullOrEmpty(toolTipText)) { - this.DataGridView.ActivateToolTip(true /*activate*/, toolTipText, this.ColumnIndex, rowIndex); + DataGridView.ActivateToolTip(true /*activate*/, toolTipText, ColumnIndex, rowIndex); } // for debugging @@ -3087,12 +3087,12 @@ private void OnCellDataAreaMouseEnterInternal(int rowIndex) private void OnCellDataAreaMouseLeaveInternal() { - if (this.DataGridView.IsDisposed) + if (DataGridView.IsDisposed) { return; } - this.DataGridView.ActivateToolTip(false /*activate*/, string.Empty, -1, -1); + DataGridView.ActivateToolTip(false /*activate*/, string.Empty, -1, -1); // for debugging // Console.WriteLine("OnCellDATA_AreaMouseLEAVE"); } @@ -3101,7 +3101,7 @@ private void OnCellErrorAreaMouseEnterInternal(int rowIndex) { string errorText = GetErrorText(rowIndex); Debug.Assert(!string.IsNullOrEmpty(errorText), "if we entered the cell error area then an error was painted, so we should have an error"); - this.DataGridView.ActivateToolTip(true /*activate*/, errorText, this.ColumnIndex, rowIndex); + DataGridView.ActivateToolTip(true /*activate*/, errorText, ColumnIndex, rowIndex); // for debugging // Console.WriteLine("OnCellERROR_AreaMouseENTER. ErrorText : " + errorText); @@ -3109,7 +3109,7 @@ private void OnCellErrorAreaMouseEnterInternal(int rowIndex) private void OnCellErrorAreaMouseLeaveInternal() { - this.DataGridView.ActivateToolTip(false /*activate*/, string.Empty, -1, -1); + DataGridView.ActivateToolTip(false /*activate*/, string.Empty, -1, -1); // for debugging // Console.WriteLine("OnCellERROR_AreaMouseLEAVE"); } @@ -3125,17 +3125,17 @@ internal void OnClickInternal(DataGridViewCellEventArgs e) internal void OnCommonChange() { - if (this.DataGridView != null && !this.DataGridView.IsDisposed && !this.DataGridView.Disposing) + if (DataGridView != null && !DataGridView.IsDisposed && !DataGridView.Disposing) { - if (this.RowIndex == -1) + if (RowIndex == -1) { // Invalidate and autosize column - this.DataGridView.OnColumnCommonChange(this.ColumnIndex); + DataGridView.OnColumnCommonChange(ColumnIndex); } else { // Invalidate and autosize cell - this.DataGridView.OnCellCommonChange(this.ColumnIndex, this.RowIndex); + DataGridView.OnCellCommonChange(ColumnIndex, RowIndex); } } } @@ -3236,12 +3236,12 @@ protected virtual void OnMouseDown(DataGridViewCellMouseEventArgs e) internal void OnMouseDownInternal(DataGridViewCellMouseEventArgs e) { - this.DataGridView.CellMouseDownInContentBounds = GetContentBounds(e.RowIndex).Contains(e.X, e.Y); + DataGridView.CellMouseDownInContentBounds = GetContentBounds(e.RowIndex).Contains(e.X, e.Y); - if (((this.ColumnIndex < 0 || e.RowIndex < 0) && this.DataGridView.ApplyVisualStylesToHeaderCells) || - ((this.ColumnIndex >= 0 && e.RowIndex >= 0) && this.DataGridView.ApplyVisualStylesToInnerCells)) + if (((ColumnIndex < 0 || e.RowIndex < 0) && DataGridView.ApplyVisualStylesToHeaderCells) || + ((ColumnIndex >= 0 && e.RowIndex >= 0) && DataGridView.ApplyVisualStylesToInnerCells)) { - DataGridView.InvalidateCell(this.ColumnIndex, e.RowIndex); + DataGridView.InvalidateCell(ColumnIndex, e.RowIndex); } OnMouseDown(e); } @@ -3261,7 +3261,7 @@ protected virtual void OnMouseLeave(int rowIndex) internal void OnMouseLeaveInternal(int rowIndex) { - switch (this.CurrentMouseLocation) + switch (CurrentMouseLocation) { case DATAGRIDVIEWCELL_flagDataArea: OnCellDataAreaMouseLeaveInternal(); @@ -3276,7 +3276,7 @@ internal void OnMouseLeaveInternal(int rowIndex) break; } - this.CurrentMouseLocation = DATAGRIDVIEWCELL_flagAreaNotSet; + CurrentMouseLocation = DATAGRIDVIEWCELL_flagAreaNotSet; OnMouseLeave(rowIndex); } @@ -3286,13 +3286,13 @@ protected virtual void OnMouseMove(DataGridViewCellMouseEventArgs e) internal void OnMouseMoveInternal(DataGridViewCellMouseEventArgs e) { - byte mouseLocation = this.CurrentMouseLocation; + byte mouseLocation = CurrentMouseLocation; UpdateCurrentMouseLocation(e); - Debug.Assert(this.CurrentMouseLocation != DATAGRIDVIEWCELL_flagAreaNotSet); + Debug.Assert(CurrentMouseLocation != DATAGRIDVIEWCELL_flagAreaNotSet); switch (mouseLocation) { case DATAGRIDVIEWCELL_flagAreaNotSet: - if (this.CurrentMouseLocation == DATAGRIDVIEWCELL_flagDataArea) + if (CurrentMouseLocation == DATAGRIDVIEWCELL_flagDataArea) { OnCellDataAreaMouseEnterInternal(e.RowIndex); } @@ -3302,14 +3302,14 @@ internal void OnMouseMoveInternal(DataGridViewCellMouseEventArgs e) } break; case DATAGRIDVIEWCELL_flagDataArea: - if (this.CurrentMouseLocation == DATAGRIDVIEWCELL_flagErrorArea) + if (CurrentMouseLocation == DATAGRIDVIEWCELL_flagErrorArea) { OnCellDataAreaMouseLeaveInternal(); OnCellErrorAreaMouseEnterInternal(e.RowIndex); } break; case DATAGRIDVIEWCELL_flagErrorArea: - if (this.CurrentMouseLocation == DATAGRIDVIEWCELL_flagDataArea) + if (CurrentMouseLocation == DATAGRIDVIEWCELL_flagDataArea) { OnCellErrorAreaMouseLeaveInternal(); OnCellDataAreaMouseEnterInternal(e.RowIndex); @@ -3331,18 +3331,18 @@ internal void OnMouseUpInternal(DataGridViewCellMouseEventArgs e) int x = e.X; int y = e.Y; - if (((this.ColumnIndex < 0 || e.RowIndex < 0) && this.DataGridView.ApplyVisualStylesToHeaderCells) || - ((this.ColumnIndex >= 0 && e.RowIndex >= 0) && this.DataGridView.ApplyVisualStylesToInnerCells)) + if (((ColumnIndex < 0 || e.RowIndex < 0) && DataGridView.ApplyVisualStylesToHeaderCells) || + ((ColumnIndex >= 0 && e.RowIndex >= 0) && DataGridView.ApplyVisualStylesToInnerCells)) { - this.DataGridView.InvalidateCell(this.ColumnIndex, e.RowIndex); + DataGridView.InvalidateCell(ColumnIndex, e.RowIndex); } if (e.Button == MouseButtons.Left && GetContentBounds(e.RowIndex).Contains(x, y)) { - this.DataGridView.OnCommonCellContentClick(e.ColumnIndex, e.RowIndex, e.Clicks > 1); + DataGridView.OnCommonCellContentClick(e.ColumnIndex, e.RowIndex, e.Clicks > 1); } - if (this.DataGridView != null && e.ColumnIndex < this.DataGridView.Columns.Count && e.RowIndex < this.DataGridView.Rows.Count) + if (DataGridView != null && e.ColumnIndex < DataGridView.Columns.Count && e.RowIndex < DataGridView.Rows.Count) { OnMouseUp(e); } @@ -3350,15 +3350,15 @@ internal void OnMouseUpInternal(DataGridViewCellMouseEventArgs e) protected override void OnDataGridViewChanged() { - if (this.HasStyle) + if (HasStyle) { - if (this.DataGridView == null) + if (DataGridView == null) { - this.Style.RemoveScope(DataGridViewCellStyleScopes.Cell); + Style.RemoveScope(DataGridViewCellStyleScopes.Cell); } else { - this.Style.AddScope(this.DataGridView, DataGridViewCellStyleScopes.Cell); + Style.AddScope(DataGridView, DataGridViewCellStyleScopes.Cell); } } base.OnDataGridViewChanged(); @@ -3429,7 +3429,7 @@ protected virtual void PaintBorder(Graphics graphics, throw new ArgumentNullException(nameof(cellStyle)); } - if (this.DataGridView == null) + if (DataGridView == null) { return; } @@ -3438,12 +3438,12 @@ protected virtual void PaintBorder(Graphics graphics, int y1, y2; Pen penControlDark = null, penControlLightLight = null; - Pen penBackColor = this.DataGridView.GetCachedPen(cellStyle.BackColor); - Pen penGridColor = this.DataGridView.GridPen; + Pen penBackColor = DataGridView.GetCachedPen(cellStyle.BackColor); + Pen penGridColor = DataGridView.GridPen; GetContrastedPens(cellStyle.BackColor, ref penControlDark, ref penControlLightLight); - int dividerThickness = this.owningColumn == null ? 0 : this.owningColumn.DividerWidth; + int dividerThickness = owningColumn == null ? 0 : owningColumn.DividerWidth; if (dividerThickness != 0) { if (dividerThickness > bounds.Width) @@ -3454,7 +3454,7 @@ protected virtual void PaintBorder(Graphics graphics, switch (advancedBorderStyle.Right) { case DataGridViewAdvancedCellBorderStyle.Single: - dividerWidthColor = this.DataGridView.GridPen.Color; + dividerWidthColor = DataGridView.GridPen.Color; break; case DataGridViewAdvancedCellBorderStyle.Inset: @@ -3465,12 +3465,12 @@ protected virtual void PaintBorder(Graphics graphics, dividerWidthColor = SystemColors.ControlDark; break; } - graphics.FillRectangle(this.DataGridView.GetCachedBrush(dividerWidthColor), - this.DataGridView.RightToLeftInternal ? bounds.X : bounds.Right - dividerThickness, + graphics.FillRectangle(DataGridView.GetCachedBrush(dividerWidthColor), + DataGridView.RightToLeftInternal ? bounds.X : bounds.Right - dividerThickness, bounds.Y, dividerThickness, bounds.Height); - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { bounds.X += dividerThickness; } @@ -3481,7 +3481,7 @@ protected virtual void PaintBorder(Graphics graphics, } } - dividerThickness = this.owningRow == null ? 0 : this.owningRow.DividerHeight; + dividerThickness = owningRow == null ? 0 : owningRow.DividerHeight; if (dividerThickness != 0) { if (dividerThickness > bounds.Height) @@ -3492,7 +3492,7 @@ protected virtual void PaintBorder(Graphics graphics, switch (advancedBorderStyle.Bottom) { case DataGridViewAdvancedCellBorderStyle.Single: - dividerHeightColor = this.DataGridView.GridPen.Color; + dividerHeightColor = DataGridView.GridPen.Color; break; case DataGridViewAdvancedCellBorderStyle.Inset: @@ -3503,7 +3503,7 @@ protected virtual void PaintBorder(Graphics graphics, dividerHeightColor = SystemColors.ControlDark; break; } - graphics.FillRectangle(this.DataGridView.GetCachedBrush(dividerHeightColor), bounds.X, bounds.Bottom - dividerThickness, bounds.Width, dividerThickness); + graphics.FillRectangle(DataGridView.GetCachedBrush(dividerHeightColor), bounds.X, bounds.Bottom - dividerThickness, bounds.Width, dividerThickness); bounds.Height -= dividerThickness; if (bounds.Height <= 0) { @@ -4267,9 +4267,9 @@ internal void PaintWork(Graphics graphics, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { - Debug.Assert(this.DataGridView != null); - DataGridView dataGridView = this.DataGridView; - int columnIndex = this.ColumnIndex; + Debug.Assert(DataGridView != null); + DataGridView dataGridView = DataGridView; + int columnIndex = ColumnIndex; object formattedValue, value = GetValue(rowIndex); string errorText = GetErrorText(rowIndex); if (columnIndex > -1 && rowIndex > -1) @@ -4319,7 +4319,7 @@ public virtual object ParseFormattedValue(object formattedValue, TypeConverter formattedValueTypeConverter, TypeConverter valueTypeConverter) { - return ParseFormattedValueInternal(this.ValueType, formattedValue, cellStyle, formattedValueTypeConverter, valueTypeConverter); + return ParseFormattedValueInternal(ValueType, formattedValue, cellStyle, formattedValueTypeConverter, valueTypeConverter); } internal object ParseFormattedValueInternal(Type valueType, @@ -4332,7 +4332,7 @@ internal object ParseFormattedValueInternal(Type valueType, { throw new ArgumentNullException(nameof(cellStyle)); } - if (this.FormattedValueType == null) + if (FormattedValueType == null) { throw new FormatException(string.Format(SR.DataGridViewCell_FormattedValueTypeNull)); } @@ -4341,15 +4341,15 @@ internal object ParseFormattedValueInternal(Type valueType, throw new FormatException(string.Format(SR.DataGridViewCell_ValueTypeNull)); } if (formattedValue == null || - !this.FormattedValueType.IsAssignableFrom(formattedValue.GetType())) + !FormattedValueType.IsAssignableFrom(formattedValue.GetType())) { throw new ArgumentException(string.Format(SR.DataGridViewCell_FormattedValueHasWrongType), "formattedValue"); } return Formatter.ParseObject(formattedValue, valueType, - this.FormattedValueType, - valueTypeConverter == null ? this.ValueTypeConverter : valueTypeConverter /*sourceConverter*/, - formattedValueTypeConverter == null ? this.FormattedValueTypeConverter : formattedValueTypeConverter /*targetConverter*/, + FormattedValueType, + valueTypeConverter == null ? ValueTypeConverter : valueTypeConverter /*sourceConverter*/, + formattedValueTypeConverter == null ? FormattedValueTypeConverter : formattedValueTypeConverter /*targetConverter*/, cellStyle.FormatProvider, cellStyle.NullValue, cellStyle.IsDataSourceNullValueDefault ? Formatter.GetDefaultDataSourceNullValue(valueType) : cellStyle.DataSourceNullValue); @@ -4378,11 +4378,11 @@ public virtual void PositionEditingControl( isFirstDisplayedRow); if (setLocation) { - this.DataGridView.EditingControl.Location = new Point(editingControlBounds.X, editingControlBounds.Y); + DataGridView.EditingControl.Location = new Point(editingControlBounds.X, editingControlBounds.Y); } if (setSize) { - this.DataGridView.EditingControl.Size = new Size(editingControlBounds.Width, editingControlBounds.Height); + DataGridView.EditingControl.Size = new Size(editingControlBounds.Width, editingControlBounds.Height); } } @@ -4399,14 +4399,14 @@ public virtual Rectangle PositionEditingPanel(Rectangle cellBounds, bool isFirstDisplayedColumn, bool isFirstDisplayedRow) { - if (this.DataGridView == null) + if (DataGridView == null) { throw new InvalidOperationException(); } DataGridViewAdvancedBorderStyle dataGridViewAdvancedBorderStylePlaceholder = new DataGridViewAdvancedBorderStyle(), dgvabsEffective; - dgvabsEffective = AdjustCellBorderStyle(this.DataGridView.AdvancedCellBorderStyle, + dgvabsEffective = AdjustCellBorderStyle(DataGridView.AdvancedCellBorderStyle, dataGridViewAdvancedBorderStylePlaceholder, singleVerticalBorderAdded, singleHorizontalBorderAdded, @@ -4467,8 +4467,8 @@ public virtual Rectangle PositionEditingPanel(Rectangle cellBounds, yEditingControl = cellBounds.Y - cellClip.Y; hEditingControl = cellBounds.Height - borderAndPaddingWidths.Y - borderAndPaddingWidths.Height; - this.DataGridView.EditingPanel.Location = new Point(xEditingPanel, yEditingPanel); - this.DataGridView.EditingPanel.Size = new Size(wEditingPanel, hEditingPanel); + DataGridView.EditingPanel.Location = new Point(xEditingPanel, yEditingPanel); + DataGridView.EditingPanel.Size = new Size(wEditingPanel, hEditingPanel); /* if (this.DataGridView.RightToLeftInternal) { @@ -4481,13 +4481,13 @@ public virtual Rectangle PositionEditingPanel(Rectangle cellBounds, protected virtual bool SetValue(int rowIndex, object value) { object originalValue = null; - DataGridView dataGridView = this.DataGridView; + DataGridView dataGridView = DataGridView; if (dataGridView != null && !dataGridView.InSortOperation) { originalValue = GetValue(rowIndex); } - if (dataGridView != null && this.OwningColumn != null && this.OwningColumn.IsDataBound) + if (dataGridView != null && OwningColumn != null && OwningColumn.IsDataBound) { DataGridView.DataGridViewDataConnection dataConnection = dataGridView.DataConnection; if (dataConnection == null) @@ -4496,16 +4496,16 @@ protected virtual bool SetValue(int rowIndex, object value) } else if (dataConnection.CurrencyManager.Count <= rowIndex) { - if (value != null || this.Properties.ContainsObject(PropCellValue)) + if (value != null || Properties.ContainsObject(PropCellValue)) { - this.Properties.SetObject(PropCellValue, value); + Properties.SetObject(PropCellValue, value); } } else { - if (dataConnection.PushValue(this.OwningColumn.BoundColumnIndex, this.ColumnIndex, rowIndex, value)) + if (dataConnection.PushValue(OwningColumn.BoundColumnIndex, ColumnIndex, rowIndex, value)) { - if (this.DataGridView == null || this.OwningRow == null || this.OwningRow.DataGridView == null) + if (DataGridView == null || OwningRow == null || OwningRow.DataGridView == null) { // As a result of pushing the value in the back end, the data grid view row and/or data grid view cell // became disconnected from the DataGridView. @@ -4517,12 +4517,12 @@ protected virtual bool SetValue(int rowIndex, object value) return true; } - if (this.OwningRow.Index == this.DataGridView.CurrentCellAddress.Y) + if (OwningRow.Index == DataGridView.CurrentCellAddress.Y) { // The user programatically changed a value in the current row. // The DataGridView already opened a transaction for the current row. // All is left to do is to mark the current row in the DataGridView as being dirty. - this.DataGridView.IsCurrentRowDirtyInternal = true; + DataGridView.IsCurrentRowDirtyInternal = true; } } else @@ -4534,18 +4534,18 @@ protected virtual bool SetValue(int rowIndex, object value) else if (dataGridView == null || !dataGridView.VirtualMode || rowIndex == -1 || - this.ColumnIndex == -1) + ColumnIndex == -1) { - if (value != null || this.Properties.ContainsObject(PropCellValue)) + if (value != null || Properties.ContainsObject(PropCellValue)) { - this.Properties.SetObject(PropCellValue, value); + Properties.SetObject(PropCellValue, value); } } else { Debug.Assert(rowIndex >= 0); - Debug.Assert(this.ColumnIndex >= 0); - dataGridView.OnCellValuePushed(this.ColumnIndex, rowIndex, value); + Debug.Assert(ColumnIndex >= 0); + dataGridView.OnCellValuePushed(ColumnIndex, rowIndex, value); } if (dataGridView != null && @@ -4554,7 +4554,7 @@ protected virtual bool SetValue(int rowIndex, object value) (originalValue != null && value == null) || (originalValue != null && !value.Equals(originalValue)))) { - RaiseCellValueChanged(new DataGridViewCellEventArgs(this.ColumnIndex, rowIndex)); + RaiseCellValueChanged(new DataGridViewCellEventArgs(ColumnIndex, rowIndex)); } return true; } @@ -4578,7 +4578,7 @@ internal static bool TextFitsInBounds(Graphics graphics, string text, Font font, /// public override string ToString() { - return "DataGridViewCell { ColumnIndex=" + this.ColumnIndex.ToString(CultureInfo.CurrentCulture) + ", RowIndex=" + this.RowIndex.ToString(CultureInfo.CurrentCulture) + " }"; + return "DataGridViewCell { ColumnIndex=" + ColumnIndex.ToString(CultureInfo.CurrentCulture) + ", RowIndex=" + RowIndex.ToString(CultureInfo.CurrentCulture) + " }"; } private static string TruncateToolTipText(string toolTipText) @@ -4596,11 +4596,11 @@ private void UpdateCurrentMouseLocation(DataGridViewCellMouseEventArgs e) { if (GetErrorIconBounds(e.RowIndex).Contains(e.X, e.Y)) { - this.CurrentMouseLocation = DATAGRIDVIEWCELL_flagErrorArea; + CurrentMouseLocation = DATAGRIDVIEWCELL_flagErrorArea; } else { - this.CurrentMouseLocation = DATAGRIDVIEWCELL_flagDataArea; + CurrentMouseLocation = DATAGRIDVIEWCELL_flagDataArea; } } @@ -4627,7 +4627,7 @@ public override Rectangle Bounds { get { - return this.GetAccessibleObjectBounds(GetAccessibleObjectParent()); + return GetAccessibleObjectBounds(GetAccessibleObjectParent()); } } @@ -4635,11 +4635,11 @@ public override string DefaultAction { get { - if (this.Owner == null) + if (Owner == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet)); } - if (!this.Owner.ReadOnly) + if (!Owner.ReadOnly) { return string.Format(SR.DataGridView_AccCellDefaultAction); } @@ -4654,17 +4654,17 @@ public override string Name { get { - if (this.owner == null) + if (owner == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet)); } - if (this.owner.OwningColumn != null) + if (owner.OwningColumn != null) { - string name = string.Format(SR.DataGridView_AccDataGridViewCellName, this.owner.OwningColumn.HeaderText, this.owner.OwningRow.Index); + string name = string.Format(SR.DataGridView_AccDataGridViewCellName, owner.OwningColumn.HeaderText, owner.OwningRow.Index); if (owner.OwningColumn.SortMode != DataGridViewColumnSortMode.NotSortable) { - DataGridViewCell dataGridViewCell = this.Owner; + DataGridViewCell dataGridViewCell = Owner; DataGridView dataGridView = dataGridViewCell.DataGridView; if (dataGridViewCell.OwningColumn != null && @@ -4693,15 +4693,15 @@ public DataGridViewCell Owner { get { - return this.owner; + return owner; } set { - if (this.owner != null) + if (owner != null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerAlreadySet)); } - this.owner = value; + owner = value; } } @@ -4709,7 +4709,7 @@ public override AccessibleObject Parent { get { - return this.ParentPrivate; + return ParentPrivate; } } @@ -4717,17 +4717,17 @@ private AccessibleObject ParentPrivate { get { - if (this.owner == null) + if (owner == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet)); } - if (this.owner.OwningRow == null) + if (owner.OwningRow == null) { return null; } else { - return this.owner.OwningRow.AccessibilityObject; + return owner.OwningRow.AccessibilityObject; } } } @@ -4744,46 +4744,46 @@ public override AccessibleStates State { get { - if (this.owner == null) + if (owner == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet)); } AccessibleStates state = AccessibleStates.Selectable | AccessibleStates.Focusable; - if (this.owner == this.owner.DataGridView.CurrentCell) + if (owner == owner.DataGridView.CurrentCell) { state |= AccessibleStates.Focused; } - if (this.owner.Selected) + if (owner.Selected) { state |= AccessibleStates.Selected; } - if (this.owner.ReadOnly) + if (owner.ReadOnly) { state |= AccessibleStates.ReadOnly; } Rectangle cellBounds; - if (this.owner.OwningColumn != null && this.owner.OwningRow != null) + if (owner.OwningColumn != null && owner.OwningRow != null) { - cellBounds = this.owner.DataGridView.GetCellDisplayRectangle(this.owner.OwningColumn.Index, this.owner.OwningRow.Index, false /*cutOverflow*/); + cellBounds = owner.DataGridView.GetCellDisplayRectangle(owner.OwningColumn.Index, owner.OwningRow.Index, false /*cutOverflow*/); } - else if (this.owner.OwningRow != null) + else if (owner.OwningRow != null) { - cellBounds = this.owner.DataGridView.GetCellDisplayRectangle(-1, this.owner.OwningRow.Index, false /*cutOverflow*/); + cellBounds = owner.DataGridView.GetCellDisplayRectangle(-1, owner.OwningRow.Index, false /*cutOverflow*/); } - else if (this.owner.OwningColumn != null) + else if (owner.OwningColumn != null) { - cellBounds = this.owner.DataGridView.GetCellDisplayRectangle(this.owner.OwningColumn.Index, -1, false /*cutOverflow*/); + cellBounds = owner.DataGridView.GetCellDisplayRectangle(owner.OwningColumn.Index, -1, false /*cutOverflow*/); } else { - cellBounds = this.owner.DataGridView.GetCellDisplayRectangle(-1, -1, false /*cutOverflow*/); + cellBounds = owner.DataGridView.GetCellDisplayRectangle(-1, -1, false /*cutOverflow*/); } - if (!cellBounds.IntersectsWith(this.owner.DataGridView.ClientRectangle)) + if (!cellBounds.IntersectsWith(owner.DataGridView.ClientRectangle)) { state |= AccessibleStates.Offscreen; } @@ -4796,12 +4796,12 @@ public override string Value { get { - if (this.owner == null) + if (owner == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet)); } - object formattedValue = this.owner.FormattedValue; + object formattedValue = owner.FormattedValue; string formattedValueAsString = formattedValue as string; if (formattedValue == null || (formattedValueAsString != null && string.IsNullOrEmpty(formattedValueAsString))) { @@ -4811,9 +4811,9 @@ public override string Value { return formattedValueAsString; } - else if (this.owner.OwningColumn != null) + else if (owner.OwningColumn != null) { - TypeConverter converter = this.owner.FormattedValueTypeConverter; + TypeConverter converter = owner.FormattedValueTypeConverter; if (converter != null && converter.CanConvertTo(typeof(string))) { return converter.ConvertToString(formattedValue); @@ -4831,39 +4831,39 @@ public override string Value set { - if (this.owner is DataGridViewHeaderCell) + if (owner is DataGridViewHeaderCell) { return; } - if (this.owner.ReadOnly) + if (owner.ReadOnly) { return; } - if (this.owner.OwningRow == null) + if (owner.OwningRow == null) { return; } - if (this.owner.DataGridView.IsCurrentCellInEditMode) + if (owner.DataGridView.IsCurrentCellInEditMode) { // EndEdit before setting the accessible object value. // This way the value being edited is validated. - this.owner.DataGridView.EndEdit(); + owner.DataGridView.EndEdit(); } - DataGridViewCellStyle dataGridViewCellStyle = this.owner.InheritedStyle; + DataGridViewCellStyle dataGridViewCellStyle = owner.InheritedStyle; // Format string "True" to boolean True. - object formattedValue = this.owner.GetFormattedValue(value, - this.owner.OwningRow.Index, + object formattedValue = owner.GetFormattedValue(value, + owner.OwningRow.Index, ref dataGridViewCellStyle, null /*formattedValueTypeConverter*/ , null /*valueTypeConverter*/, DataGridViewDataErrorContexts.Formatting); // Parse the formatted value and push it into the back end. - this.owner.Value = owner.ParseFormattedValue(formattedValue, + owner.Value = owner.ParseFormattedValue(formattedValue, dataGridViewCellStyle, null /*formattedValueTypeConverter*/, null /*valueTypeConverter*/); @@ -4872,12 +4872,12 @@ public override string Value public override void DoDefaultAction() { - if (this.owner == null) + if (owner == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet)); } - DataGridViewCell dataGridViewCell = (DataGridViewCell)this.Owner; + DataGridViewCell dataGridViewCell = (DataGridViewCell)Owner; DataGridView dataGridView = dataGridViewCell.DataGridView; if (dataGridViewCell is DataGridViewHeaderCell) @@ -4922,34 +4922,34 @@ public override void DoDefaultAction() internal Rectangle GetAccessibleObjectBounds(AccessibleObject parentAccObject) { - if (this.owner == null) + if (owner == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet)); } - if (this.owner.OwningColumn == null) + if (owner.OwningColumn == null) { return Rectangle.Empty; } Rectangle rowRect = parentAccObject.Bounds; Rectangle cellRect = rowRect; - Rectangle columnRect = this.owner.DataGridView.RectangleToScreen(this.owner.DataGridView.GetColumnDisplayRectangle(this.owner.ColumnIndex, false /*cutOverflow*/)); + Rectangle columnRect = owner.DataGridView.RectangleToScreen(owner.DataGridView.GetColumnDisplayRectangle(owner.ColumnIndex, false /*cutOverflow*/)); var cellRight = columnRect.Left + columnRect.Width; var cellLeft = columnRect.Left; int rightToLeftRowHeadersWidth = 0; int leftToRightRowHeadersWidth = 0; - if (this.owner.DataGridView.RowHeadersVisible) + if (owner.DataGridView.RowHeadersVisible) { - if (this.owner.DataGridView.RightToLeft == RightToLeft.Yes) + if (owner.DataGridView.RightToLeft == RightToLeft.Yes) { - rightToLeftRowHeadersWidth = this.owner.DataGridView.RowHeadersWidth; + rightToLeftRowHeadersWidth = owner.DataGridView.RowHeadersWidth; } else { - leftToRightRowHeadersWidth = this.owner.DataGridView.RowHeadersWidth; + leftToRightRowHeadersWidth = owner.DataGridView.RowHeadersWidth; } } @@ -4977,34 +4977,34 @@ private AccessibleObject GetAccessibleObjectParent() { // If this is one of our types, use the shortcut provided by ParentPrivate property. // Otherwise, use the Parent property. - if (this.owner is DataGridViewButtonCell || - this.owner is DataGridViewCheckBoxCell || - this.owner is DataGridViewComboBoxCell || - this.owner is DataGridViewImageCell || - this.owner is DataGridViewLinkCell || - this.owner is DataGridViewTextBoxCell) + if (owner is DataGridViewButtonCell || + owner is DataGridViewCheckBoxCell || + owner is DataGridViewComboBoxCell || + owner is DataGridViewImageCell || + owner is DataGridViewLinkCell || + owner is DataGridViewTextBoxCell) { - return this.ParentPrivate; + return ParentPrivate; } else { - return this.Parent; + return Parent; } } public override AccessibleObject GetChild(int index) { - if (this.owner == null) + if (owner == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet)); } - if (this.owner.DataGridView.EditingControl != null && - this.owner.DataGridView.IsCurrentCellInEditMode && - this.owner.DataGridView.CurrentCell == this.owner && + if (owner.DataGridView.EditingControl != null && + owner.DataGridView.IsCurrentCellInEditMode && + owner.DataGridView.CurrentCell == owner && index == 0) { - return this.owner.DataGridView.EditingControl.AccessibilityObject; + return owner.DataGridView.EditingControl.AccessibilityObject; } else { @@ -5014,14 +5014,14 @@ public override AccessibleObject GetChild(int index) public override int GetChildCount() { - if (this.owner == null) + if (owner == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet)); } - if (this.owner.DataGridView.EditingControl != null && - this.owner.DataGridView.IsCurrentCellInEditMode && - this.owner.DataGridView.CurrentCell == this.owner) + if (owner.DataGridView.EditingControl != null && + owner.DataGridView.IsCurrentCellInEditMode && + owner.DataGridView.CurrentCell == owner) { return 1; } @@ -5043,12 +5043,12 @@ public override AccessibleObject GetSelected() public override AccessibleObject Navigate(AccessibleNavigation navigationDirection) { - if (this.owner == null) + if (owner == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet)); } - if (this.owner.OwningColumn == null || this.owner.OwningRow == null) + if (owner.OwningColumn == null || owner.OwningRow == null) { return null; } @@ -5056,7 +5056,7 @@ public override AccessibleObject Navigate(AccessibleNavigation navigationDirecti switch (navigationDirection) { case AccessibleNavigation.Right: - if (this.owner.DataGridView.RightToLeft == RightToLeft.No) + if (owner.DataGridView.RightToLeft == RightToLeft.No) { return NavigateForward(true /*wrapAround*/); } @@ -5067,7 +5067,7 @@ public override AccessibleObject Navigate(AccessibleNavigation navigationDirecti case AccessibleNavigation.Next: return NavigateForward(false /*wrapAround*/); case AccessibleNavigation.Left: - if (this.owner.DataGridView.RightToLeft == RightToLeft.No) + if (owner.DataGridView.RightToLeft == RightToLeft.No) { return NavigateBackward(true /*wrapAround*/); } @@ -5078,12 +5078,12 @@ public override AccessibleObject Navigate(AccessibleNavigation navigationDirecti case AccessibleNavigation.Previous: return NavigateBackward(false /*wrapAround*/); case AccessibleNavigation.Up: - if (this.owner.OwningRow.Index == this.owner.DataGridView.Rows.GetFirstRow(DataGridViewElementStates.Visible)) + if (owner.OwningRow.Index == owner.DataGridView.Rows.GetFirstRow(DataGridViewElementStates.Visible)) { - if (this.owner.DataGridView.ColumnHeadersVisible) + if (owner.DataGridView.ColumnHeadersVisible) { // Return the column header accessible object. - return this.owner.OwningColumn.HeaderCell.AccessibilityObject; + return owner.OwningColumn.HeaderCell.AccessibilityObject; } else { @@ -5092,18 +5092,18 @@ public override AccessibleObject Navigate(AccessibleNavigation navigationDirecti } else { - int previousVisibleRow = this.owner.DataGridView.Rows.GetPreviousRow(this.owner.OwningRow.Index, DataGridViewElementStates.Visible); - return this.owner.DataGridView.Rows[previousVisibleRow].Cells[this.owner.OwningColumn.Index].AccessibilityObject; + int previousVisibleRow = owner.DataGridView.Rows.GetPreviousRow(owner.OwningRow.Index, DataGridViewElementStates.Visible); + return owner.DataGridView.Rows[previousVisibleRow].Cells[owner.OwningColumn.Index].AccessibilityObject; } case AccessibleNavigation.Down: - if (this.owner.OwningRow.Index == this.owner.DataGridView.Rows.GetLastRow(DataGridViewElementStates.Visible)) + if (owner.OwningRow.Index == owner.DataGridView.Rows.GetLastRow(DataGridViewElementStates.Visible)) { return null; } else { - int nextVisibleRow = this.owner.DataGridView.Rows.GetNextRow(this.owner.OwningRow.Index, DataGridViewElementStates.Visible); - return this.owner.DataGridView.Rows[nextVisibleRow].Cells[this.owner.OwningColumn.Index].AccessibilityObject; + int nextVisibleRow = owner.DataGridView.Rows.GetNextRow(owner.OwningRow.Index, DataGridViewElementStates.Visible); + return owner.DataGridView.Rows[nextVisibleRow].Cells[owner.OwningColumn.Index].AccessibilityObject; } default: return null; @@ -5112,12 +5112,12 @@ public override AccessibleObject Navigate(AccessibleNavigation navigationDirecti private AccessibleObject NavigateBackward(bool wrapAround) { - if (this.owner.OwningColumn == this.owner.DataGridView.Columns.GetFirstColumn(DataGridViewElementStates.Visible)) + if (owner.OwningColumn == owner.DataGridView.Columns.GetFirstColumn(DataGridViewElementStates.Visible)) { if (wrapAround) { // Return the last accessible object in the previous row - AccessibleObject previousRow = this.Owner.OwningRow.AccessibilityObject.Navigate(AccessibleNavigation.Previous); + AccessibleObject previousRow = Owner.OwningRow.AccessibilityObject.Navigate(AccessibleNavigation.Previous); if (previousRow != null && previousRow.GetChildCount() > 0) { return previousRow.GetChild(previousRow.GetChildCount() - 1); @@ -5130,9 +5130,9 @@ private AccessibleObject NavigateBackward(bool wrapAround) else { // return the row header cell if the row headers are visible. - if (this.owner.DataGridView.RowHeadersVisible) + if (owner.DataGridView.RowHeadersVisible) { - return this.owner.OwningRow.AccessibilityObject.GetChild(0); + return owner.OwningRow.AccessibilityObject.GetChild(0); } else { @@ -5142,16 +5142,16 @@ private AccessibleObject NavigateBackward(bool wrapAround) } else { - int previousVisibleColumnIndex = this.owner.DataGridView.Columns.GetPreviousColumn(this.owner.OwningColumn, + int previousVisibleColumnIndex = owner.DataGridView.Columns.GetPreviousColumn(owner.OwningColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None).Index; - return this.owner.OwningRow.Cells[previousVisibleColumnIndex].AccessibilityObject; + return owner.OwningRow.Cells[previousVisibleColumnIndex].AccessibilityObject; } } private AccessibleObject NavigateForward(bool wrapAround) { - if (this.owner.OwningColumn == this.owner.DataGridView.Columns.GetLastColumn(DataGridViewElementStates.Visible, + if (owner.OwningColumn == owner.DataGridView.Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.None)) { @@ -5159,10 +5159,10 @@ private AccessibleObject NavigateForward(bool wrapAround) { // Return the first cell in the next visible row. // - AccessibleObject nextRow = this.Owner.OwningRow.AccessibilityObject.Navigate(AccessibleNavigation.Next); + AccessibleObject nextRow = Owner.OwningRow.AccessibilityObject.Navigate(AccessibleNavigation.Next); if (nextRow != null && nextRow.GetChildCount() > 0) { - if (this.Owner.DataGridView.RowHeadersVisible) + if (Owner.DataGridView.RowHeadersVisible) { return nextRow.GetChild(1); } @@ -5184,37 +5184,37 @@ private AccessibleObject NavigateForward(bool wrapAround) } else { - int nextVisibleColumnIndex = this.owner.DataGridView.Columns.GetNextColumn(this.owner.OwningColumn, + int nextVisibleColumnIndex = owner.DataGridView.Columns.GetNextColumn(owner.OwningColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None).Index; - return this.owner.OwningRow.Cells[nextVisibleColumnIndex].AccessibilityObject; + return owner.OwningRow.Cells[nextVisibleColumnIndex].AccessibilityObject; } } public override void Select(AccessibleSelection flags) { - if (this.owner == null) + if (owner == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet)); } if ((flags & AccessibleSelection.TakeFocus) == AccessibleSelection.TakeFocus) { - this.owner.DataGridView.Focus(); + owner.DataGridView.Focus(); } if ((flags & AccessibleSelection.TakeSelection) == AccessibleSelection.TakeSelection) { - this.owner.Selected = true; - this.owner.DataGridView.CurrentCell = this.owner; // Do not change old selection + owner.Selected = true; + owner.DataGridView.CurrentCell = owner; // Do not change old selection } if ((flags & AccessibleSelection.AddSelection) == AccessibleSelection.AddSelection) { // it seems that in any circumstances a cell can become selected - this.owner.Selected = true; + owner.Selected = true; } if ((flags & AccessibleSelection.RemoveSelection) == AccessibleSelection.RemoveSelection && (flags & (AccessibleSelection.AddSelection | AccessibleSelection.TakeSelection)) == 0) { - this.owner.Selected = false; + owner.Selected = false; } } @@ -5242,7 +5242,7 @@ internal override int[] RuntimeId { runtimeId = new int[2]; runtimeId[0] = RuntimeIDFirstItem; // first item is static - 0x2a - runtimeId[1] = this.GetHashCode(); + runtimeId[1] = GetHashCode(); } return runtimeId; @@ -5271,7 +5271,7 @@ internal override Rectangle BoundingRectangle { get { - return this.Bounds; + return Bounds; } } @@ -5285,12 +5285,12 @@ internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRo internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - if (this.owner == null) + if (owner == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet)); } - if (this.owner.OwningColumn == null || this.owner.OwningRow == null) + if (owner.OwningColumn == null || owner.OwningRow == null) { return null; } @@ -5298,16 +5298,16 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga switch (direction) { case UnsafeNativeMethods.NavigateDirection.Parent: - return this.owner.OwningRow.AccessibilityObject; + return owner.OwningRow.AccessibilityObject; case UnsafeNativeMethods.NavigateDirection.NextSibling: return NavigateForward(false); case UnsafeNativeMethods.NavigateDirection.PreviousSibling: return NavigateBackward(false); case UnsafeNativeMethods.NavigateDirection.FirstChild: case UnsafeNativeMethods.NavigateDirection.LastChild: - if (this.owner.DataGridView.CurrentCell == this.owner && - this.owner.DataGridView.IsCurrentCellInEditMode && - this.owner.DataGridView.EditingControl != null) + if (owner.DataGridView.CurrentCell == owner && + owner.DataGridView.IsCurrentCellInEditMode && + owner.DataGridView.EditingControl != null) { return _child; } @@ -5328,7 +5328,7 @@ internal override object GetPropertyValue(int propertyID) switch (propertyID) { case NativeMethods.UIA_NamePropertyId: - return this.Name; + return Name; case NativeMethods.UIA_HasKeyboardFocusPropertyId: return (State & AccessibleStates.Focused) == AccessibleStates.Focused; // Announce the cell when focusing. case NativeMethods.UIA_IsEnabledPropertyId: @@ -5368,7 +5368,7 @@ internal override bool IsPatternSupported(int patternId) if ((patternId == NativeMethods.UIA_TableItemPatternId || patternId == NativeMethods.UIA_GridItemPatternId) && // We don't want to implement patterns for header cells - this.owner.ColumnIndex != -1 && this.owner.RowIndex != -1) + owner.ColumnIndex != -1 && owner.RowIndex != -1) { return true; } @@ -5380,9 +5380,9 @@ internal override bool IsPatternSupported(int patternId) internal override UnsafeNativeMethods.IRawElementProviderSimple[] GetRowHeaderItems() { - if (this.owner.DataGridView.RowHeadersVisible && this.owner.OwningRow.HasHeaderCell) + if (owner.DataGridView.RowHeadersVisible && owner.OwningRow.HasHeaderCell) { - return new UnsafeNativeMethods.IRawElementProviderSimple[1] { this.owner.OwningRow.HeaderCell.AccessibilityObject }; + return new UnsafeNativeMethods.IRawElementProviderSimple[1] { owner.OwningRow.HeaderCell.AccessibilityObject }; } return null; @@ -5390,9 +5390,9 @@ internal override UnsafeNativeMethods.IRawElementProviderSimple[] GetRowHeaderIt internal override UnsafeNativeMethods.IRawElementProviderSimple[] GetColumnHeaderItems() { - if (this.owner.DataGridView.ColumnHeadersVisible && this.owner.OwningColumn.HasHeaderCell) + if (owner.DataGridView.ColumnHeadersVisible && owner.OwningColumn.HasHeaderCell) { - return new UnsafeNativeMethods.IRawElementProviderSimple[1] { this.owner.OwningColumn.HeaderCell.AccessibilityObject }; + return new UnsafeNativeMethods.IRawElementProviderSimple[1] { owner.OwningColumn.HeaderCell.AccessibilityObject }; } return null; @@ -5402,7 +5402,7 @@ internal override int Row { get { - return this.owner.OwningRow != null ? this.owner.OwningRow.Index : -1; + return owner.OwningRow != null ? owner.OwningRow.Index : -1; } } @@ -5410,7 +5410,7 @@ internal override int Column { get { - return this.owner.OwningColumn != null ? this.owner.OwningColumn.Index : -1; + return owner.OwningColumn != null ? owner.OwningColumn.Index : -1; } } @@ -5418,7 +5418,7 @@ internal override UnsafeNativeMethods.IRawElementProviderSimple ContainingGrid { get { - return this.owner.DataGridView.AccessibilityObject; + return owner.DataGridView.AccessibilityObject; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellCollection.cs index 2cef78a8bec..c96a08037b0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellCollection.cs @@ -28,37 +28,37 @@ public class DataGridViewCellCollection : BaseCollection, IList int IList.Add(object value) { - return this.Add((DataGridViewCell)value); + return Add((DataGridViewCell)value); } void IList.Clear() { - this.Clear(); + Clear(); } bool IList.Contains(object value) { - return this.items.Contains(value); + return items.Contains(value); } int IList.IndexOf(object value) { - return this.items.IndexOf(value); + return items.IndexOf(value); } void IList.Insert(int index, object value) { - this.Insert(index, (DataGridViewCell)value); + Insert(index, (DataGridViewCell)value); } void IList.Remove(object value) { - this.Remove((DataGridViewCell)value); + Remove((DataGridViewCell)value); } void IList.RemoveAt(int index) { - this.RemoveAt(index); + RemoveAt(index); } bool IList.IsFixedSize @@ -79,12 +79,12 @@ object IList.this[int index] void ICollection.CopyTo(Array array, int index) { - this.items.CopyTo(array, index); + items.CopyTo(array, index); } int ICollection.Count { - get { return this.items.Count; } + get { return items.Count; } } bool ICollection.IsSynchronized @@ -99,20 +99,20 @@ object ICollection.SyncRoot IEnumerator IEnumerable.GetEnumerator() { - return this.items.GetEnumerator(); + return items.GetEnumerator(); } public DataGridViewCellCollection(DataGridViewRow dataGridViewRow) { Debug.Assert(dataGridViewRow != null); - this.owner = dataGridViewRow; + owner = dataGridViewRow; } protected override ArrayList List { get { - return this.items; + return items; } } @@ -123,7 +123,7 @@ public DataGridViewCell this[int index] { get { - return (DataGridViewCell)this.items[index]; + return (DataGridViewCell)items[index]; } set { @@ -140,20 +140,20 @@ public DataGridViewCell this[int index] { throw new InvalidOperationException(string.Format(SR.DataGridViewCellCollection_CellAlreadyBelongsToDataGridViewRow)); } - if (this.owner.DataGridView != null) + if (owner.DataGridView != null) { - this.owner.DataGridView.OnReplacingCell(this.owner, index); + owner.DataGridView.OnReplacingCell(owner, index); } - DataGridViewCell oldDataGridViewCell = (DataGridViewCell)this.items[index]; - this.items[index] = dataGridViewCell; - dataGridViewCell.OwningRowInternal = this.owner; + DataGridViewCell oldDataGridViewCell = (DataGridViewCell)items[index]; + items[index] = dataGridViewCell; + dataGridViewCell.OwningRowInternal = owner; dataGridViewCell.StateInternal = oldDataGridViewCell.State; - if (this.owner.DataGridView != null) + if (owner.DataGridView != null) { - dataGridViewCell.DataGridViewInternal = this.owner.DataGridView; - dataGridViewCell.OwningColumnInternal = this.owner.DataGridView.Columns[index]; - this.owner.DataGridView.OnReplacedCell(this.owner, index); + dataGridViewCell.DataGridViewInternal = owner.DataGridView; + dataGridViewCell.OwningColumnInternal = owner.DataGridView.Columns[index]; + owner.DataGridView.OnReplacedCell(owner, index); } oldDataGridViewCell.DataGridViewInternal = null; @@ -178,22 +178,22 @@ public DataGridViewCell this[string columnName] get { DataGridViewColumn dataGridViewColumn = null; - if (this.owner.DataGridView != null) + if (owner.DataGridView != null) { - dataGridViewColumn = this.owner.DataGridView.Columns[columnName]; + dataGridViewColumn = owner.DataGridView.Columns[columnName]; } if (dataGridViewColumn == null) { throw new ArgumentException(string.Format(SR.DataGridViewColumnCollection_ColumnNotFound, columnName), "columnName"); } - return (DataGridViewCell)this.items[dataGridViewColumn.Index]; + return (DataGridViewCell)items[dataGridViewColumn.Index]; } set { DataGridViewColumn dataGridViewColumn = null; - if (this.owner.DataGridView != null) + if (owner.DataGridView != null) { - dataGridViewColumn = this.owner.DataGridView.Columns[columnName]; + dataGridViewColumn = owner.DataGridView.Columns[columnName]; } if (dataGridViewColumn == null) { @@ -205,8 +205,8 @@ public DataGridViewCell this[string columnName] public event CollectionChangeEventHandler CollectionChanged { - add => this.onCollectionChanged += value; - remove => this.onCollectionChanged -= value; + add => onCollectionChanged += value; + remove => onCollectionChanged -= value; } /// @@ -214,7 +214,7 @@ public event CollectionChangeEventHandler CollectionChanged /// public virtual int Add(DataGridViewCell dataGridViewCell) { - if (this.owner.DataGridView != null) + if (owner.DataGridView != null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellCollection_OwningRowAlreadyBelongsToDataGridView)); } @@ -229,9 +229,9 @@ public virtual int Add(DataGridViewCell dataGridViewCell) internal int AddInternal(DataGridViewCell dataGridViewCell) { Debug.Assert(!dataGridViewCell.Selected); - int index = this.items.Add(dataGridViewCell); - dataGridViewCell.OwningRowInternal = this.owner; - DataGridView dataGridView = this.owner.DataGridView; + int index = items.Add(dataGridViewCell); + dataGridViewCell.OwningRowInternal = owner; + DataGridView dataGridView = owner.DataGridView; if (dataGridView != null && dataGridView.Columns.Count > index) { dataGridViewCell.OwningColumnInternal = dataGridView.Columns[index]; @@ -247,7 +247,7 @@ public virtual void AddRange(params DataGridViewCell[] dataGridViewCells) { throw new ArgumentNullException(nameof(dataGridViewCells)); } - if (this.owner.DataGridView != null) + if (owner.DataGridView != null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellCollection_OwningRowAlreadyBelongsToDataGridView)); } @@ -277,10 +277,10 @@ public virtual void AddRange(params DataGridViewCell[] dataGridViewCells) } } - this.items.AddRange(dataGridViewCells); + items.AddRange(dataGridViewCells); foreach (DataGridViewCell dataGridViewCell in dataGridViewCells) { - dataGridViewCell.OwningRowInternal = this.owner; + dataGridViewCell.OwningRowInternal = owner; Debug.Assert(!dataGridViewCell.Selected); } OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null)); @@ -288,21 +288,21 @@ public virtual void AddRange(params DataGridViewCell[] dataGridViewCells) public virtual void Clear() { - if (this.owner.DataGridView != null) + if (owner.DataGridView != null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellCollection_OwningRowAlreadyBelongsToDataGridView)); } - foreach (DataGridViewCell dataGridViewCell in this.items) + foreach (DataGridViewCell dataGridViewCell in items) { dataGridViewCell.OwningRowInternal = null; } - this.items.Clear(); + items.Clear(); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null)); } public void CopyTo(DataGridViewCell[] array, int index) { - this.items.CopyTo(array, index); + items.CopyTo(array, index); } /// @@ -310,18 +310,18 @@ public void CopyTo(DataGridViewCell[] array, int index) /// public virtual bool Contains(DataGridViewCell dataGridViewCell) { - int index = this.items.IndexOf(dataGridViewCell); + int index = items.IndexOf(dataGridViewCell); return index != -1; } public int IndexOf(DataGridViewCell dataGridViewCell) { - return this.items.IndexOf(dataGridViewCell); + return items.IndexOf(dataGridViewCell); } public virtual void Insert(int index, DataGridViewCell dataGridViewCell) { - if (this.owner.DataGridView != null) + if (owner.DataGridView != null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellCollection_OwningRowAlreadyBelongsToDataGridView)); } @@ -331,17 +331,17 @@ public virtual void Insert(int index, DataGridViewCell dataGridViewCell) } Debug.Assert(!dataGridViewCell.ReadOnly); Debug.Assert(!dataGridViewCell.Selected); - this.items.Insert(index, dataGridViewCell); - dataGridViewCell.OwningRowInternal = this.owner; + items.Insert(index, dataGridViewCell); + dataGridViewCell.OwningRowInternal = owner; OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, dataGridViewCell)); } internal void InsertInternal(int index, DataGridViewCell dataGridViewCell) { Debug.Assert(!dataGridViewCell.Selected); - this.items.Insert(index, dataGridViewCell); - dataGridViewCell.OwningRowInternal = this.owner; - DataGridView dataGridView = this.owner.DataGridView; + items.Insert(index, dataGridViewCell); + dataGridViewCell.OwningRowInternal = owner; + DataGridView dataGridView = owner.DataGridView; if (dataGridView != null && dataGridView.Columns.Count > index) { dataGridViewCell.OwningColumnInternal = dataGridView.Columns[index]; @@ -351,23 +351,23 @@ internal void InsertInternal(int index, DataGridViewCell dataGridViewCell) protected void OnCollectionChanged(CollectionChangeEventArgs e) { - if (this.onCollectionChanged != null) + if (onCollectionChanged != null) { - this.onCollectionChanged(this, e); + onCollectionChanged(this, e); } } public virtual void Remove(DataGridViewCell cell) { - if (this.owner.DataGridView != null) + if (owner.DataGridView != null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellCollection_OwningRowAlreadyBelongsToDataGridView)); } int cellIndex = -1; - int itemsCount = this.items.Count; + int itemsCount = items.Count; for (int i = 0; i < itemsCount; ++i) { - if (this.items[i] == cell) + if (items[i] == cell) { cellIndex = i; break; @@ -385,7 +385,7 @@ public virtual void Remove(DataGridViewCell cell) public virtual void RemoveAt(int index) { - if (this.owner.DataGridView != null) + if (owner.DataGridView != null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellCollection_OwningRowAlreadyBelongsToDataGridView)); } @@ -394,8 +394,8 @@ public virtual void RemoveAt(int index) internal void RemoveAtInternal(int index) { - DataGridViewCell dataGridViewCell = (DataGridViewCell)this.items[index]; - this.items.RemoveAt(index); + DataGridViewCell dataGridViewCell = (DataGridViewCell)items[index]; + items.RemoveAt(index); dataGridViewCell.DataGridViewInternal = null; dataGridViewCell.OwningRowInternal = null; if (dataGridViewCell.ReadOnly) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellLinkedList.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellLinkedList.cs index b780a594e54..3c4db1d77cb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellLinkedList.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellLinkedList.cs @@ -21,12 +21,12 @@ internal class DataGridViewCellLinkedList : IEnumerable IEnumerator IEnumerable.GetEnumerator() { - return new DataGridViewCellLinkedListEnumerator(this.headElement); + return new DataGridViewCellLinkedListEnumerator(headElement); } public DataGridViewCellLinkedList() { - this.lastAccessedIndex = -1; + lastAccessedIndex = -1; } public DataGridViewCell this[int index] @@ -34,28 +34,28 @@ public DataGridViewCell this[int index] get { Debug.Assert(index >= 0); - Debug.Assert(index < this.count); - if (this.lastAccessedIndex == -1 || index < this.lastAccessedIndex) + Debug.Assert(index < count); + if (lastAccessedIndex == -1 || index < lastAccessedIndex) { - DataGridViewCellLinkedListElement tmp = this.headElement; + DataGridViewCellLinkedListElement tmp = headElement; int tmpIndex = index; while (tmpIndex > 0) { tmp = tmp.Next; tmpIndex--; } - this.lastAccessedElement = tmp; - this.lastAccessedIndex = index; + lastAccessedElement = tmp; + lastAccessedIndex = index; return tmp.DataGridViewCell; } else { - while (this.lastAccessedIndex < index) + while (lastAccessedIndex < index) { - this.lastAccessedElement = this.lastAccessedElement.Next; - this.lastAccessedIndex++; + lastAccessedElement = lastAccessedElement.Next; + lastAccessedIndex++; } - return this.lastAccessedElement.DataGridViewCell; + return lastAccessedElement.DataGridViewCell; } } } @@ -64,7 +64,7 @@ public int Count { get { - return this.count; + return count; } } @@ -72,8 +72,8 @@ public DataGridViewCell HeadCell { get { - Debug.Assert(this.headElement != null); - return this.headElement.DataGridViewCell; + Debug.Assert(headElement != null); + return headElement.DataGridViewCell; } } @@ -84,35 +84,35 @@ public void Add(DataGridViewCell dataGridViewCell) dataGridViewCell.DataGridView.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect || dataGridViewCell.DataGridView.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect); DataGridViewCellLinkedListElement newHead = new DataGridViewCellLinkedListElement(dataGridViewCell); - if (this.headElement != null) + if (headElement != null) { - newHead.Next = this.headElement; + newHead.Next = headElement; } - this.headElement = newHead; - this.count++; - this.lastAccessedElement = null; - this.lastAccessedIndex = -1; + headElement = newHead; + count++; + lastAccessedElement = null; + lastAccessedIndex = -1; } public void Clear() { - this.lastAccessedElement = null; - this.lastAccessedIndex = -1; - this.headElement = null; - this.count = 0; + lastAccessedElement = null; + lastAccessedIndex = -1; + headElement = null; + count = 0; } public bool Contains(DataGridViewCell dataGridViewCell) { Debug.Assert(dataGridViewCell != null); int index = 0; - DataGridViewCellLinkedListElement tmp = this.headElement; + DataGridViewCellLinkedListElement tmp = headElement; while (tmp != null) { if (tmp.DataGridViewCell == dataGridViewCell) { - this.lastAccessedElement = tmp; - this.lastAccessedIndex = index; + lastAccessedElement = tmp; + lastAccessedIndex = index; return true; } tmp = tmp.Next; @@ -124,7 +124,7 @@ public bool Contains(DataGridViewCell dataGridViewCell) public bool Remove(DataGridViewCell dataGridViewCell) { Debug.Assert(dataGridViewCell != null); - DataGridViewCellLinkedListElement tmp1 = null, tmp2 = this.headElement; + DataGridViewCellLinkedListElement tmp1 = null, tmp2 = headElement; while (tmp2 != null) { if (tmp2.DataGridViewCell == dataGridViewCell) @@ -139,15 +139,15 @@ public bool Remove(DataGridViewCell dataGridViewCell) DataGridViewCellLinkedListElement tmp3 = tmp2.Next; if (tmp1 == null) { - this.headElement = tmp3; + headElement = tmp3; } else { tmp1.Next = tmp3; } - this.count--; - this.lastAccessedElement = null; - this.lastAccessedIndex = -1; + count--; + lastAccessedElement = null; + lastAccessedIndex = -1; return true; } return false; @@ -172,7 +172,7 @@ public DataGridViewCell RemoveHead() public int RemoveAllCellsAtBand(bool column, int bandIndex) { int removedCount = 0; - DataGridViewCellLinkedListElement tmp1 = null, tmp2 = this.headElement; + DataGridViewCellLinkedListElement tmp1 = null, tmp2 = headElement; while (tmp2 != null) { if ((column && tmp2.DataGridViewCell.ColumnIndex == bandIndex) || @@ -181,16 +181,16 @@ public int RemoveAllCellsAtBand(bool column, int bandIndex) DataGridViewCellLinkedListElement tmp3 = tmp2.Next; if (tmp1 == null) { - this.headElement = tmp3; + headElement = tmp3; } else { tmp1.Next = tmp3; } tmp2 = tmp3; - this.count--; - this.lastAccessedElement = null; - this.lastAccessedIndex = -1; + count--; + lastAccessedElement = null; + lastAccessedIndex = -1; removedCount++; } else @@ -215,38 +215,38 @@ internal class DataGridViewCellLinkedListEnumerator : IEnumerator public DataGridViewCellLinkedListEnumerator(DataGridViewCellLinkedListElement headElement) { this.headElement = headElement; - this.reset = true; + reset = true; } object IEnumerator.Current { get { - Debug.Assert(this.current != null); // Since this is for internal use only. - return this.current.DataGridViewCell; + Debug.Assert(current != null); // Since this is for internal use only. + return current.DataGridViewCell; } } bool IEnumerator.MoveNext() { - if (this.reset) + if (reset) { - Debug.Assert(this.current == null); - this.current = this.headElement; - this.reset = false; + Debug.Assert(current == null); + current = headElement; + reset = false; } else { - Debug.Assert(this.current != null); // Since this is for internal use only. - this.current = this.current.Next; + Debug.Assert(current != null); // Since this is for internal use only. + current = current.Next; } - return (this.current != null); + return (current != null); } void IEnumerator.Reset() { - this.reset = true; - this.current = null; + reset = true; + current = null; } } @@ -268,7 +268,7 @@ public DataGridViewCell DataGridViewCell { get { - return this.dataGridViewCell; + return dataGridViewCell; } } @@ -276,11 +276,11 @@ public DataGridViewCellLinkedListElement Next { get { - return this.next; + return next; } set { - this.next = value; + next = value; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyle.cs index cdb07ea5798..ebf989163cf 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyle.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyle.cs @@ -44,8 +44,8 @@ public class DataGridViewCellStyle : ICloneable /// public DataGridViewCellStyle() { - this.propertyStore = new PropertyStore(); - this.scope = DataGridViewCellStyleScopes.None; + propertyStore = new PropertyStore(); + scope = DataGridViewCellStyleScopes.None; } public DataGridViewCellStyle(DataGridViewCellStyle dataGridViewCellStyle) @@ -54,24 +54,24 @@ public DataGridViewCellStyle(DataGridViewCellStyle dataGridViewCellStyle) { throw new ArgumentNullException(nameof(dataGridViewCellStyle)); } - this.propertyStore = new PropertyStore(); - this.scope = DataGridViewCellStyleScopes.None; - this.BackColor = dataGridViewCellStyle.BackColor; - this.ForeColor = dataGridViewCellStyle.ForeColor; - this.SelectionBackColor = dataGridViewCellStyle.SelectionBackColor; - this.SelectionForeColor = dataGridViewCellStyle.SelectionForeColor; - this.Font = dataGridViewCellStyle.Font; - this.NullValue = dataGridViewCellStyle.NullValue; - this.DataSourceNullValue = dataGridViewCellStyle.DataSourceNullValue; - this.Format = dataGridViewCellStyle.Format; + propertyStore = new PropertyStore(); + scope = DataGridViewCellStyleScopes.None; + BackColor = dataGridViewCellStyle.BackColor; + ForeColor = dataGridViewCellStyle.ForeColor; + SelectionBackColor = dataGridViewCellStyle.SelectionBackColor; + SelectionForeColor = dataGridViewCellStyle.SelectionForeColor; + Font = dataGridViewCellStyle.Font; + NullValue = dataGridViewCellStyle.NullValue; + DataSourceNullValue = dataGridViewCellStyle.DataSourceNullValue; + Format = dataGridViewCellStyle.Format; if (!dataGridViewCellStyle.IsFormatProviderDefault) { - this.FormatProvider = dataGridViewCellStyle.FormatProvider; + FormatProvider = dataGridViewCellStyle.FormatProvider; } - this.AlignmentInternal = dataGridViewCellStyle.Alignment; - this.WrapModeInternal = dataGridViewCellStyle.WrapMode; - this.Tag = dataGridViewCellStyle.Tag; - this.PaddingInternal = dataGridViewCellStyle.Padding; + AlignmentInternal = dataGridViewCellStyle.Alignment; + WrapModeInternal = dataGridViewCellStyle.WrapMode; + Tag = dataGridViewCellStyle.Tag; + PaddingInternal = dataGridViewCellStyle.Padding; } [ @@ -85,7 +85,7 @@ public DataGridViewContentAlignment Alignment get { bool found; - int alignment = this.Properties.GetInteger(PropAlignment, out found); + int alignment = Properties.GetInteger(PropAlignment, out found); if (found) { return (DataGridViewContentAlignment)alignment; @@ -110,7 +110,7 @@ public DataGridViewContentAlignment Alignment default: throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewContentAlignment)); } - this.AlignmentInternal = value; + AlignmentInternal = value; } } @@ -122,9 +122,9 @@ internal DataGridViewContentAlignment AlignmentInternal set { Debug.Assert(Enum.IsDefined(typeof(DataGridViewContentAlignment), value)); - if (this.Alignment != value) + if (Alignment != value) { - this.Properties.SetInteger(PropAlignment, (int)value); + Properties.SetInteger(PropAlignment, (int)value); OnPropertyChanged(DataGridViewCellStylePropertyInternal.Other); } } @@ -137,16 +137,16 @@ public Color BackColor { get { - return this.Properties.GetColor(PropBackColor); + return Properties.GetColor(PropBackColor); } set { - Color c = this.BackColor; - if (!value.IsEmpty || this.Properties.ContainsObject(PropBackColor)) + Color c = BackColor; + if (!value.IsEmpty || Properties.ContainsObject(PropBackColor)) { - this.Properties.SetColor(PropBackColor, value); + Properties.SetColor(PropBackColor, value); } - if (!c.Equals(this.BackColor)) + if (!c.Equals(BackColor)) { OnPropertyChanged(DataGridViewCellStylePropertyInternal.Color); } @@ -162,15 +162,15 @@ public object DataSourceNullValue { get { - if (this.Properties.ContainsObject(PropDataSourceNullValue)) + if (Properties.ContainsObject(PropDataSourceNullValue)) { - return this.Properties.GetObject(PropDataSourceNullValue); + return Properties.GetObject(PropDataSourceNullValue); } return System.DBNull.Value; } set { - object oldDataSourceNullValue = this.DataSourceNullValue; + object oldDataSourceNullValue = DataSourceNullValue; if ((oldDataSourceNullValue == value) || (oldDataSourceNullValue != null && oldDataSourceNullValue.Equals(value))) @@ -179,18 +179,18 @@ public object DataSourceNullValue } if (value == System.DBNull.Value && - this.Properties.ContainsObject(PropDataSourceNullValue)) + Properties.ContainsObject(PropDataSourceNullValue)) { - this.Properties.RemoveObject(PropDataSourceNullValue); + Properties.RemoveObject(PropDataSourceNullValue); } else { - this.Properties.SetObject(PropDataSourceNullValue, value); + Properties.SetObject(PropDataSourceNullValue, value); } - Debug.Assert((oldDataSourceNullValue == null && this.DataSourceNullValue != null) || - (oldDataSourceNullValue != null && this.DataSourceNullValue == null) || - (oldDataSourceNullValue != this.DataSourceNullValue && !oldDataSourceNullValue.Equals(this.DataSourceNullValue))); + Debug.Assert((oldDataSourceNullValue == null && DataSourceNullValue != null) || + (oldDataSourceNullValue != null && DataSourceNullValue == null) || + (oldDataSourceNullValue != DataSourceNullValue && !oldDataSourceNullValue.Equals(DataSourceNullValue))); OnPropertyChanged(DataGridViewCellStylePropertyInternal.Other); } @@ -203,18 +203,18 @@ public Font Font { get { - return (Font)this.Properties.GetObject(PropFont); + return (Font)Properties.GetObject(PropFont); } set { - Font f = this.Font; - if (value != null || this.Properties.ContainsObject(PropFont)) + Font f = Font; + if (value != null || Properties.ContainsObject(PropFont)) { - this.Properties.SetObject(PropFont, value); + Properties.SetObject(PropFont, value); } if ((f == null && value != null) || (f != null && value == null) || - (f != null && value != null && !f.Equals(this.Font))) + (f != null && value != null && !f.Equals(Font))) { OnPropertyChanged(DataGridViewCellStylePropertyInternal.Font); } @@ -228,16 +228,16 @@ public Color ForeColor { get { - return this.Properties.GetColor(PropForeColor); + return Properties.GetColor(PropForeColor); } set { - Color c = this.ForeColor; - if (!value.IsEmpty || this.Properties.ContainsObject(PropForeColor)) + Color c = ForeColor; + if (!value.IsEmpty || Properties.ContainsObject(PropForeColor)) { - this.Properties.SetColor(PropForeColor, value); + Properties.SetColor(PropForeColor, value); } - if (!c.Equals(this.ForeColor)) + if (!c.Equals(ForeColor)) { OnPropertyChanged(DataGridViewCellStylePropertyInternal.ForeColor); } @@ -254,7 +254,7 @@ public string Format { get { - object format = this.Properties.GetObject(PropFormat); + object format = Properties.GetObject(PropFormat); if (format == null) { return string.Empty; @@ -266,12 +266,12 @@ public string Format } set { - string format = this.Format; - if ((value != null && value.Length > 0) || this.Properties.ContainsObject(PropFormat)) + string format = Format; + if ((value != null && value.Length > 0) || Properties.ContainsObject(PropFormat)) { - this.Properties.SetObject(PropFormat, value); + Properties.SetObject(PropFormat, value); } - if (!format.Equals(this.Format)) + if (!format.Equals(Format)) { OnPropertyChanged(DataGridViewCellStylePropertyInternal.Other); } @@ -286,7 +286,7 @@ public IFormatProvider FormatProvider { get { - object formatProvider = this.Properties.GetObject(PropFormatProvider); + object formatProvider = Properties.GetObject(PropFormatProvider); if (formatProvider == null) { return System.Globalization.CultureInfo.CurrentCulture; @@ -298,8 +298,8 @@ public IFormatProvider FormatProvider } set { - object originalFormatProvider = this.Properties.GetObject(PropFormatProvider); - this.Properties.SetObject(PropFormatProvider, value); + object originalFormatProvider = Properties.GetObject(PropFormatProvider); + Properties.SetObject(PropFormatProvider, value); if (value != originalFormatProvider) { OnPropertyChanged(DataGridViewCellStylePropertyInternal.Other); @@ -315,11 +315,11 @@ public bool IsDataSourceNullValueDefault { get { - if (!this.Properties.ContainsObject(PropDataSourceNullValue)) + if (!Properties.ContainsObject(PropDataSourceNullValue)) { return true; } - return this.Properties.GetObject(PropDataSourceNullValue) == System.DBNull.Value; + return Properties.GetObject(PropDataSourceNullValue) == System.DBNull.Value; } } @@ -331,7 +331,7 @@ public bool IsFormatProviderDefault { get { - return this.Properties.GetObject(PropFormatProvider) == null; + return Properties.GetObject(PropFormatProvider) == null; } } @@ -343,12 +343,12 @@ public bool IsNullValueDefault { get { - if (!this.Properties.ContainsObject(PropNullValue)) + if (!Properties.ContainsObject(PropNullValue)) { return true; } - object nullValue = this.Properties.GetObject(PropNullValue); + object nullValue = Properties.GetObject(PropNullValue); return nullValue is string nullValueString && nullValueString.Length == 0; } } @@ -360,15 +360,15 @@ public object NullValue { get { - if (this.Properties.ContainsObject(PropNullValue)) + if (Properties.ContainsObject(PropNullValue)) { - return this.Properties.GetObject(PropNullValue); + return Properties.GetObject(PropNullValue); } return string.Empty; } set { - object oldNullValue = this.NullValue; + object oldNullValue = NullValue; if ((oldNullValue == value) || (oldNullValue != null && oldNullValue.Equals(value))) @@ -378,16 +378,16 @@ public object NullValue if (value is string stringValue && stringValue.Length == 0 && Properties.ContainsObject(PropNullValue)) { - this.Properties.RemoveObject(PropNullValue); + Properties.RemoveObject(PropNullValue); } else { - this.Properties.SetObject(PropNullValue, value); + Properties.SetObject(PropNullValue, value); } - Debug.Assert((oldNullValue == null && this.NullValue != null) || - (oldNullValue != null && this.NullValue == null) || - (oldNullValue != this.NullValue && !oldNullValue.Equals(this.NullValue))); + Debug.Assert((oldNullValue == null && NullValue != null) || + (oldNullValue != null && NullValue == null) || + (oldNullValue != NullValue && !oldNullValue.Equals(NullValue))); OnPropertyChanged(DataGridViewCellStylePropertyInternal.Other); } @@ -416,7 +416,7 @@ public Padding Padding value.Bottom = Math.Max(0, value.Bottom); } } - this.PaddingInternal = value; + PaddingInternal = value; } } @@ -428,9 +428,9 @@ internal Padding PaddingInternal Debug.Assert(value.Right >= 0); Debug.Assert(value.Top >= 0); Debug.Assert(value.Bottom >= 0); - if (value != this.Padding) + if (value != Padding) { - this.Properties.SetPadding(PropPadding, value); + Properties.SetPadding(PropPadding, value); OnPropertyChanged(DataGridViewCellStylePropertyInternal.Other); } } @@ -440,7 +440,7 @@ internal PropertyStore Properties { get { - return this.propertyStore; + return propertyStore; } } @@ -448,11 +448,11 @@ internal DataGridViewCellStyleScopes Scope { get { - return this.scope; + return scope; } set { - this.scope = value; + scope = value; } } @@ -463,16 +463,16 @@ public Color SelectionBackColor { get { - return this.Properties.GetColor(PropSelectionBackColor); + return Properties.GetColor(PropSelectionBackColor); } set { - Color c = this.SelectionBackColor; - if (!value.IsEmpty || this.Properties.ContainsObject(PropSelectionBackColor)) + Color c = SelectionBackColor; + if (!value.IsEmpty || Properties.ContainsObject(PropSelectionBackColor)) { - this.Properties.SetColor(PropSelectionBackColor, value); + Properties.SetColor(PropSelectionBackColor, value); } - if (!c.Equals(this.SelectionBackColor)) + if (!c.Equals(SelectionBackColor)) { OnPropertyChanged(DataGridViewCellStylePropertyInternal.Color); } @@ -486,16 +486,16 @@ public Color SelectionForeColor { get { - return this.Properties.GetColor(PropSelectionForeColor); + return Properties.GetColor(PropSelectionForeColor); } set { - Color c = this.SelectionForeColor; - if (!value.IsEmpty || this.Properties.ContainsObject(PropSelectionForeColor)) + Color c = SelectionForeColor; + if (!value.IsEmpty || Properties.ContainsObject(PropSelectionForeColor)) { - this.Properties.SetColor(PropSelectionForeColor, value); + Properties.SetColor(PropSelectionForeColor, value); } - if (!c.Equals(this.SelectionForeColor)) + if (!c.Equals(SelectionForeColor)) { OnPropertyChanged(DataGridViewCellStylePropertyInternal.Color); } @@ -514,7 +514,7 @@ public object Tag } set { - if (value != null || this.Properties.ContainsObject(PropTag)) + if (value != null || Properties.ContainsObject(PropTag)) { Properties.SetObject(PropTag, value); } @@ -531,7 +531,7 @@ public DataGridViewTriState WrapMode get { bool found; - int wrap = this.Properties.GetInteger(PropWrapMode, out found); + int wrap = Properties.GetInteger(PropWrapMode, out found); if (found) { return (DataGridViewTriState)wrap; @@ -545,7 +545,7 @@ public DataGridViewTriState WrapMode { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewTriState)); } - this.WrapModeInternal = value; + WrapModeInternal = value; } } @@ -554,9 +554,9 @@ internal DataGridViewTriState WrapModeInternal set { Debug.Assert(value >= DataGridViewTriState.NotSet && value <= DataGridViewTriState.False); - if (this.WrapMode != value) + if (WrapMode != value) { - this.Properties.SetInteger(PropWrapMode, (int)value); + Properties.SetInteger(PropWrapMode, (int)value); OnPropertyChanged(DataGridViewCellStylePropertyInternal.Other); } } @@ -576,55 +576,55 @@ public virtual void ApplyStyle(DataGridViewCellStyle dataGridViewCellStyle) } if (!dataGridViewCellStyle.BackColor.IsEmpty) { - this.BackColor = dataGridViewCellStyle.BackColor; + BackColor = dataGridViewCellStyle.BackColor; } if (!dataGridViewCellStyle.ForeColor.IsEmpty) { - this.ForeColor = dataGridViewCellStyle.ForeColor; + ForeColor = dataGridViewCellStyle.ForeColor; } if (!dataGridViewCellStyle.SelectionBackColor.IsEmpty) { - this.SelectionBackColor = dataGridViewCellStyle.SelectionBackColor; + SelectionBackColor = dataGridViewCellStyle.SelectionBackColor; } if (!dataGridViewCellStyle.SelectionForeColor.IsEmpty) { - this.SelectionForeColor = dataGridViewCellStyle.SelectionForeColor; + SelectionForeColor = dataGridViewCellStyle.SelectionForeColor; } if (dataGridViewCellStyle.Font != null) { - this.Font = dataGridViewCellStyle.Font; + Font = dataGridViewCellStyle.Font; } if (!dataGridViewCellStyle.IsNullValueDefault) { - this.NullValue = dataGridViewCellStyle.NullValue; + NullValue = dataGridViewCellStyle.NullValue; } if (!dataGridViewCellStyle.IsDataSourceNullValueDefault) { - this.DataSourceNullValue = dataGridViewCellStyle.DataSourceNullValue; + DataSourceNullValue = dataGridViewCellStyle.DataSourceNullValue; } if (dataGridViewCellStyle.Format.Length != 0) { - this.Format = dataGridViewCellStyle.Format; + Format = dataGridViewCellStyle.Format; } if (!dataGridViewCellStyle.IsFormatProviderDefault) { - this.FormatProvider = dataGridViewCellStyle.FormatProvider; + FormatProvider = dataGridViewCellStyle.FormatProvider; } if (dataGridViewCellStyle.Alignment != DataGridViewContentAlignment.NotSet) { - this.AlignmentInternal = dataGridViewCellStyle.Alignment; + AlignmentInternal = dataGridViewCellStyle.Alignment; } if (dataGridViewCellStyle.WrapMode != DataGridViewTriState.NotSet) { - this.WrapModeInternal = dataGridViewCellStyle.WrapMode; + WrapModeInternal = dataGridViewCellStyle.WrapMode; } if (dataGridViewCellStyle.Tag != null) { - this.Tag = dataGridViewCellStyle.Tag; + Tag = dataGridViewCellStyle.Tag; } if (dataGridViewCellStyle.Padding != Padding.Empty) { - this.PaddingInternal = dataGridViewCellStyle.Padding; + PaddingInternal = dataGridViewCellStyle.Padding; } } @@ -651,21 +651,21 @@ internal DataGridViewCellStyleDifferences GetDifferencesFrom(DataGridViewCellSty Debug.Assert(dgvcs != null); bool preferredSizeAffectingPropDifferent = ( - dgvcs.Alignment != this.Alignment || - dgvcs.DataSourceNullValue != this.DataSourceNullValue || - dgvcs.Font != this.Font || - dgvcs.Format != this.Format || - dgvcs.FormatProvider != this.FormatProvider || - dgvcs.NullValue != this.NullValue || - dgvcs.Padding != this.Padding || - dgvcs.Tag != this.Tag || - dgvcs.WrapMode != this.WrapMode); + dgvcs.Alignment != Alignment || + dgvcs.DataSourceNullValue != DataSourceNullValue || + dgvcs.Font != Font || + dgvcs.Format != Format || + dgvcs.FormatProvider != FormatProvider || + dgvcs.NullValue != NullValue || + dgvcs.Padding != Padding || + dgvcs.Tag != Tag || + dgvcs.WrapMode != WrapMode); bool preferredSizeNonAffectingPropDifferent = ( - dgvcs.BackColor != this.BackColor || - dgvcs.ForeColor != this.ForeColor || - dgvcs.SelectionBackColor != this.SelectionBackColor || - dgvcs.SelectionForeColor != this.SelectionForeColor); + dgvcs.BackColor != BackColor || + dgvcs.ForeColor != ForeColor || + dgvcs.SelectionBackColor != SelectionBackColor || + dgvcs.SelectionForeColor != SelectionForeColor); if (preferredSizeAffectingPropDifferent) { @@ -701,9 +701,9 @@ public override int GetHashCode() private void OnPropertyChanged(DataGridViewCellStylePropertyInternal property) { - if (this.dataGridView != null && this.scope != DataGridViewCellStyleScopes.None) + if (dataGridView != null && scope != DataGridViewCellStyleScopes.None) { - this.dataGridView.OnCellStyleContentChanged(this, property); + dataGridView.OnCellStyleContentChanged(this, property); } /* @@ -743,50 +743,50 @@ internal void RemoveScope(DataGridViewCellStyleScopes scope) this.scope &= ~scope; if (this.scope == DataGridViewCellStyleScopes.None) { - this.dataGridView = null; + dataGridView = null; } } private bool ShouldSerializeBackColor() { bool found; - this.Properties.GetColor(PropBackColor, out found); + Properties.GetColor(PropBackColor, out found); return found; } private bool ShouldSerializeFont() { - return this.Properties.GetObject(PropFont) != null; + return Properties.GetObject(PropFont) != null; } private bool ShouldSerializeForeColor() { bool found; - this.Properties.GetColor(PropForeColor, out found); + Properties.GetColor(PropForeColor, out found); return found; } private bool ShouldSerializeFormatProvider() { - return this.Properties.GetObject(PropFormatProvider) != null; + return Properties.GetObject(PropFormatProvider) != null; } private bool ShouldSerializePadding() { - return this.Padding != Padding.Empty; + return Padding != Padding.Empty; } private bool ShouldSerializeSelectionBackColor() { bool found; - this.Properties.GetObject(PropSelectionBackColor, out found); + Properties.GetObject(PropSelectionBackColor, out found); return found; } private bool ShouldSerializeSelectionForeColor() { bool found; - this.Properties.GetColor(PropSelectionForeColor, out found); + Properties.GetColor(PropSelectionForeColor, out found); return found; } @@ -795,108 +795,108 @@ public override string ToString() StringBuilder sb = new StringBuilder(128); sb.Append("DataGridViewCellStyle {"); bool firstPropAdded = true; - if (this.BackColor != Color.Empty) + if (BackColor != Color.Empty) { - sb.Append(" BackColor=" + this.BackColor.ToString()); + sb.Append(" BackColor=" + BackColor.ToString()); firstPropAdded = false; } - if (this.ForeColor != Color.Empty) + if (ForeColor != Color.Empty) { if (!firstPropAdded) { sb.Append(','); } - sb.Append(" ForeColor=" + this.ForeColor.ToString()); + sb.Append(" ForeColor=" + ForeColor.ToString()); firstPropAdded = false; } - if (this.SelectionBackColor != Color.Empty) + if (SelectionBackColor != Color.Empty) { if (!firstPropAdded) { sb.Append(','); } - sb.Append(" SelectionBackColor=" + this.SelectionBackColor.ToString()); + sb.Append(" SelectionBackColor=" + SelectionBackColor.ToString()); firstPropAdded = false; } - if (this.SelectionForeColor != Color.Empty) + if (SelectionForeColor != Color.Empty) { if (!firstPropAdded) { sb.Append(','); } - sb.Append(" SelectionForeColor=" + this.SelectionForeColor.ToString()); + sb.Append(" SelectionForeColor=" + SelectionForeColor.ToString()); firstPropAdded = false; } - if (this.Font != null) + if (Font != null) { if (!firstPropAdded) { sb.Append(','); } - sb.Append(" Font=" + this.Font.ToString()); + sb.Append(" Font=" + Font.ToString()); firstPropAdded = false; } - if (!this.IsNullValueDefault && this.NullValue != null) + if (!IsNullValueDefault && NullValue != null) { if (!firstPropAdded) { sb.Append(','); } - sb.Append(" NullValue=" + this.NullValue.ToString()); + sb.Append(" NullValue=" + NullValue.ToString()); firstPropAdded = false; } - if (!this.IsDataSourceNullValueDefault && this.DataSourceNullValue != null) + if (!IsDataSourceNullValueDefault && DataSourceNullValue != null) { if (!firstPropAdded) { sb.Append(','); } - sb.Append(" DataSourceNullValue=" + this.DataSourceNullValue.ToString()); + sb.Append(" DataSourceNullValue=" + DataSourceNullValue.ToString()); firstPropAdded = false; } - if (!string.IsNullOrEmpty(this.Format)) + if (!string.IsNullOrEmpty(Format)) { if (!firstPropAdded) { sb.Append(','); } - sb.Append(" Format=" + this.Format); + sb.Append(" Format=" + Format); firstPropAdded = false; } - if (this.WrapMode != DataGridViewTriState.NotSet) + if (WrapMode != DataGridViewTriState.NotSet) { if (!firstPropAdded) { sb.Append(','); } - sb.Append(" WrapMode=" + this.WrapMode.ToString()); + sb.Append(" WrapMode=" + WrapMode.ToString()); firstPropAdded = false; } - if (this.Alignment != DataGridViewContentAlignment.NotSet) + if (Alignment != DataGridViewContentAlignment.NotSet) { if (!firstPropAdded) { sb.Append(','); } - sb.Append(" Alignment=" + this.Alignment.ToString()); + sb.Append(" Alignment=" + Alignment.ToString()); firstPropAdded = false; } - if (this.Padding != Padding.Empty) + if (Padding != Padding.Empty) { if (!firstPropAdded) { sb.Append(','); } - sb.Append(" Padding=" + this.Padding.ToString()); + sb.Append(" Padding=" + Padding.ToString()); firstPropAdded = false; } - if (this.Tag != null) + if (Tag != null) { if (!firstPropAdded) { sb.Append(','); } - sb.Append(" Tag=" + this.Tag.ToString()); + sb.Append(" Tag=" + Tag.ToString()); firstPropAdded = false; } sb.Append(" }"); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs index d7e507d3bdd..d294367c542 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs @@ -55,7 +55,7 @@ public DataGridViewCheckBoxCell(bool threeState) { if (threeState) { - this.flags = DATAGRIDVIEWCHECKBOXCELL_threeState; + flags = DATAGRIDVIEWCHECKBOXCELL_threeState; } } @@ -67,11 +67,11 @@ public virtual object EditingCellFormattedValue } set { - if (this.FormattedValueType == null) + if (FormattedValueType == null) { throw new ArgumentException(string.Format(SR.DataGridViewCell_FormattedValueTypeNull)); } - if (value == null || !this.FormattedValueType.IsAssignableFrom(value.GetType())) + if (value == null || !FormattedValueType.IsAssignableFrom(value.GetType())) { // Assigned formatted value may not be of the good type, in cases where the app // is feeding wrong values to the cell in virtual / databound mode. @@ -81,32 +81,32 @@ public virtual object EditingCellFormattedValue { if (((System.Windows.Forms.CheckState)value) == System.Windows.Forms.CheckState.Checked) { - this.flags |= (byte)DATAGRIDVIEWCHECKBOXCELL_checked; - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCHECKBOXCELL_indeterminate); + flags |= (byte)DATAGRIDVIEWCHECKBOXCELL_checked; + flags = (byte)(flags & ~DATAGRIDVIEWCHECKBOXCELL_indeterminate); } else if (((System.Windows.Forms.CheckState)value) == System.Windows.Forms.CheckState.Indeterminate) { - this.flags |= (byte)DATAGRIDVIEWCHECKBOXCELL_indeterminate; - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCHECKBOXCELL_checked); + flags |= (byte)DATAGRIDVIEWCHECKBOXCELL_indeterminate; + flags = (byte)(flags & ~DATAGRIDVIEWCHECKBOXCELL_checked); } else { - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCHECKBOXCELL_checked); - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCHECKBOXCELL_indeterminate); + flags = (byte)(flags & ~DATAGRIDVIEWCHECKBOXCELL_checked); + flags = (byte)(flags & ~DATAGRIDVIEWCHECKBOXCELL_indeterminate); } } else if (value is bool) { if ((bool)value) { - this.flags |= (byte)DATAGRIDVIEWCHECKBOXCELL_checked; + flags |= (byte)DATAGRIDVIEWCHECKBOXCELL_checked; } else { - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCHECKBOXCELL_checked); + flags = (byte)(flags & ~DATAGRIDVIEWCHECKBOXCELL_checked); } - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCHECKBOXCELL_indeterminate); + flags = (byte)(flags & ~DATAGRIDVIEWCHECKBOXCELL_indeterminate); } else { @@ -119,30 +119,30 @@ public virtual bool EditingCellValueChanged { get { - return ((this.flags & DATAGRIDVIEWCHECKBOXCELL_valueChanged) != 0x00); + return ((flags & DATAGRIDVIEWCHECKBOXCELL_valueChanged) != 0x00); } set { if (value) { - this.flags |= (byte)DATAGRIDVIEWCHECKBOXCELL_valueChanged; + flags |= (byte)DATAGRIDVIEWCHECKBOXCELL_valueChanged; } else { - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCHECKBOXCELL_valueChanged); + flags = (byte)(flags & ~DATAGRIDVIEWCHECKBOXCELL_valueChanged); } } } public virtual object GetEditingCellFormattedValue(DataGridViewDataErrorContexts context) { - if (this.FormattedValueType == null) + if (FormattedValueType == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCell_FormattedValueTypeNull)); } - if (this.FormattedValueType.IsAssignableFrom(defaultCheckStateType)) + if (FormattedValueType.IsAssignableFrom(defaultCheckStateType)) { - if ((this.flags & DATAGRIDVIEWCHECKBOXCELL_checked) != 0x00) + if ((flags & DATAGRIDVIEWCHECKBOXCELL_checked) != 0x00) { if ((context & DataGridViewDataErrorContexts.ClipboardContent) != 0) { @@ -150,7 +150,7 @@ public virtual object GetEditingCellFormattedValue(DataGridViewDataErrorContexts } return System.Windows.Forms.CheckState.Checked; } - else if ((this.flags & DATAGRIDVIEWCHECKBOXCELL_indeterminate) != 0x00) + else if ((flags & DATAGRIDVIEWCHECKBOXCELL_indeterminate) != 0x00) { if ((context & DataGridViewDataErrorContexts.ClipboardContent) != 0) { @@ -167,9 +167,9 @@ public virtual object GetEditingCellFormattedValue(DataGridViewDataErrorContexts return System.Windows.Forms.CheckState.Unchecked; } } - else if (this.FormattedValueType.IsAssignableFrom(defaultBooleanType)) + else if (FormattedValueType.IsAssignableFrom(defaultBooleanType)) { - bool ret = (bool)((this.flags & DATAGRIDVIEWCHECKBOXCELL_checked) != 0x00); + bool ret = (bool)((flags & DATAGRIDVIEWCHECKBOXCELL_checked) != 0x00); if ((context & DataGridViewDataErrorContexts.ClipboardContent) != 0) { return string.Format(ret ? SR.DataGridViewCheckBoxCell_ClipboardTrue : SR.DataGridViewCheckBoxCell_ClipboardFalse); @@ -191,7 +191,7 @@ private ButtonState ButtonState get { bool found; - int buttonState = this.Properties.GetInteger(PropButtonCellState, out found); + int buttonState = Properties.GetInteger(PropButtonCellState, out found); if (found) { return (ButtonState)buttonState; @@ -203,9 +203,9 @@ private ButtonState ButtonState // ButtonState.Pushed is used for mouse interaction // ButtonState.Checked is used for keyboard interaction Debug.Assert((value & ~(ButtonState.Normal | ButtonState.Pushed | ButtonState.Checked)) == 0); - if (this.ButtonState != value) + if (ButtonState != value) { - this.Properties.SetInteger(PropButtonCellState, (int)value); + Properties.SetInteger(PropButtonCellState, (int)value); } } } @@ -225,22 +225,22 @@ public object FalseValue { get { - return this.Properties.GetObject(PropFalseValue); + return Properties.GetObject(PropFalseValue); } set { - if (value != null || this.Properties.ContainsObject(PropFalseValue)) + if (value != null || Properties.ContainsObject(PropFalseValue)) { - this.Properties.SetObject(PropFalseValue, value); - if (this.DataGridView != null) + Properties.SetObject(PropFalseValue, value); + if (DataGridView != null) { - if (this.RowIndex != -1) + if (RowIndex != -1) { - this.DataGridView.InvalidateCell(this); + DataGridView.InvalidateCell(this); } else { - this.DataGridView.InvalidateColumnInternal(this.ColumnIndex); + DataGridView.InvalidateColumnInternal(ColumnIndex); } } } @@ -251,9 +251,9 @@ internal object FalseValueInternal { set { - if (value != null || this.Properties.ContainsObject(PropFalseValue)) + if (value != null || Properties.ContainsObject(PropFalseValue)) { - this.Properties.SetObject(PropFalseValue, value); + Properties.SetObject(PropFalseValue, value); } } } @@ -264,7 +264,7 @@ public FlatStyle FlatStyle get { bool found; - int flatStyle = this.Properties.GetInteger(PropFlatStyle, out found); + int flatStyle = Properties.GetInteger(PropFlatStyle, out found); if (found) { return (FlatStyle)flatStyle; @@ -278,9 +278,9 @@ public FlatStyle FlatStyle { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(FlatStyle)); } - if (value != this.FlatStyle) + if (value != FlatStyle) { - this.Properties.SetInteger(PropFlatStyle, (int)value); + Properties.SetInteger(PropFlatStyle, (int)value); OnCommonChange(); } } @@ -291,9 +291,9 @@ internal FlatStyle FlatStyleInternal set { Debug.Assert(value >= FlatStyle.Flat && value <= FlatStyle.System); - if (value != this.FlatStyle) + if (value != FlatStyle) { - this.Properties.SetInteger(PropFlatStyle, (int)value); + Properties.SetInteger(PropFlatStyle, (int)value); } } } @@ -302,7 +302,7 @@ public override Type FormattedValueType { get { - if (this.ThreeState) + if (ThreeState) { return defaultCheckStateType; } @@ -318,22 +318,22 @@ public object IndeterminateValue { get { - return this.Properties.GetObject(PropIndeterminateValue); + return Properties.GetObject(PropIndeterminateValue); } set { - if (value != null || this.Properties.ContainsObject(PropIndeterminateValue)) + if (value != null || Properties.ContainsObject(PropIndeterminateValue)) { - this.Properties.SetObject(PropIndeterminateValue, value); - if (this.DataGridView != null) + Properties.SetObject(PropIndeterminateValue, value); + if (DataGridView != null) { - if (this.RowIndex != -1) + if (RowIndex != -1) { - this.DataGridView.InvalidateCell(this); + DataGridView.InvalidateCell(this); } else { - this.DataGridView.InvalidateColumnInternal(this.ColumnIndex); + DataGridView.InvalidateColumnInternal(ColumnIndex); } } } @@ -344,9 +344,9 @@ internal object IndeterminateValueInternal { set { - if (value != null || this.Properties.ContainsObject(PropIndeterminateValue)) + if (value != null || Properties.ContainsObject(PropIndeterminateValue)) { - this.Properties.SetObject(PropIndeterminateValue, value); + Properties.SetObject(PropIndeterminateValue, value); } } } @@ -356,22 +356,22 @@ public bool ThreeState { get { - return ((this.flags & DATAGRIDVIEWCHECKBOXCELL_threeState) != 0x00); + return ((flags & DATAGRIDVIEWCHECKBOXCELL_threeState) != 0x00); } set { - if (this.ThreeState != value) + if (ThreeState != value) { - this.ThreeStateInternal = value; - if (this.DataGridView != null) + ThreeStateInternal = value; + if (DataGridView != null) { - if (this.RowIndex != -1) + if (RowIndex != -1) { - this.DataGridView.InvalidateCell(this); + DataGridView.InvalidateCell(this); } else { - this.DataGridView.InvalidateColumnInternal(this.ColumnIndex); + DataGridView.InvalidateColumnInternal(ColumnIndex); } } } @@ -382,15 +382,15 @@ internal bool ThreeStateInternal { set { - if (this.ThreeState != value) + if (ThreeState != value) { if (value) { - this.flags |= (byte)DATAGRIDVIEWCHECKBOXCELL_threeState; + flags |= (byte)DATAGRIDVIEWCHECKBOXCELL_threeState; } else { - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCHECKBOXCELL_threeState); + flags = (byte)(flags & ~DATAGRIDVIEWCHECKBOXCELL_threeState); } } } @@ -401,22 +401,22 @@ public object TrueValue { get { - return this.Properties.GetObject(PropTrueValue); + return Properties.GetObject(PropTrueValue); } set { - if (value != null || this.Properties.ContainsObject(PropTrueValue)) + if (value != null || Properties.ContainsObject(PropTrueValue)) { - this.Properties.SetObject(PropTrueValue, value); - if (this.DataGridView != null) + Properties.SetObject(PropTrueValue, value); + if (DataGridView != null) { - if (this.RowIndex != -1) + if (RowIndex != -1) { - this.DataGridView.InvalidateCell(this); + DataGridView.InvalidateCell(this); } else { - this.DataGridView.InvalidateColumnInternal(this.ColumnIndex); + DataGridView.InvalidateColumnInternal(ColumnIndex); } } } @@ -427,9 +427,9 @@ internal object TrueValueInternal { set { - if (value != null || this.Properties.ContainsObject(PropTrueValue)) + if (value != null || Properties.ContainsObject(PropTrueValue)) { - this.Properties.SetObject(PropTrueValue, value); + Properties.SetObject(PropTrueValue, value); } } } @@ -444,7 +444,7 @@ public override Type ValueType return valueType; } - if (this.ThreeState) + if (ThreeState) { return defaultCheckStateType; } @@ -456,14 +456,14 @@ public override Type ValueType set { base.ValueType = value; - this.ThreeState = (value != null && defaultCheckStateType.IsAssignableFrom(value)); + ThreeState = (value != null && defaultCheckStateType.IsAssignableFrom(value)); } } public override object Clone() { DataGridViewCheckBoxCell dataGridViewCell; - Type thisType = this.GetType(); + Type thisType = GetType(); if (thisType == cellType) //performance improvement { dataGridViewCell = new DataGridViewCheckBoxCell(); @@ -475,20 +475,20 @@ public override object Clone() dataGridViewCell = (DataGridViewCheckBoxCell)System.Activator.CreateInstance(thisType); } base.CloneInternal(dataGridViewCell); - dataGridViewCell.ThreeStateInternal = this.ThreeState; - dataGridViewCell.TrueValueInternal = this.TrueValue; - dataGridViewCell.FalseValueInternal = this.FalseValue; - dataGridViewCell.IndeterminateValueInternal = this.IndeterminateValue; - dataGridViewCell.FlatStyleInternal = this.FlatStyle; + dataGridViewCell.ThreeStateInternal = ThreeState; + dataGridViewCell.TrueValueInternal = TrueValue; + dataGridViewCell.FalseValueInternal = FalseValue; + dataGridViewCell.IndeterminateValueInternal = IndeterminateValue; + dataGridViewCell.FlatStyleInternal = FlatStyle; return dataGridViewCell; } private bool CommonContentClickUnsharesRow(DataGridViewCellEventArgs e) { - Point ptCurrentCell = this.DataGridView.CurrentCellAddress; - return ptCurrentCell.X == this.ColumnIndex && + Point ptCurrentCell = DataGridView.CurrentCellAddress; + return ptCurrentCell.X == ColumnIndex && ptCurrentCell.Y == e.RowIndex && - this.DataGridView.IsCurrentCellInEditMode; + DataGridView.IsCurrentCellInEditMode; } protected override bool ContentClickUnsharesRow(DataGridViewCellEventArgs e) @@ -513,7 +513,7 @@ protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCel throw new ArgumentNullException(nameof(cellStyle)); } - if (this.DataGridView == null || rowIndex < 0 || this.OwningColumn == null) + if (DataGridView == null || rowIndex < 0 || OwningColumn == null) { return Rectangle.Empty; } @@ -566,18 +566,18 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC throw new ArgumentNullException(nameof(cellStyle)); } - if (this.DataGridView == null || + if (DataGridView == null || rowIndex < 0 || - this.OwningColumn == null || - !this.DataGridView.ShowCellErrors || + OwningColumn == null || + !DataGridView.ShowCellErrors || string.IsNullOrEmpty(GetErrorText(rowIndex))) { return Rectangle.Empty; } - Point ptCurrentCell = this.DataGridView.CurrentCellAddress; - if (ptCurrentCell.X == this.ColumnIndex && - ptCurrentCell.Y == rowIndex && this.DataGridView.IsCurrentCellInEditMode) + Point ptCurrentCell = DataGridView.CurrentCellAddress; + if (ptCurrentCell.X == ColumnIndex && + ptCurrentCell.Y == rowIndex && DataGridView.IsCurrentCellInEditMode) { // PaintPrivate does not paint the error icon if this is the current cell. // So don't set the ErrorIconBounds either. @@ -617,19 +617,19 @@ protected override object GetFormattedValue(object value, { if (value != null) { - if (this.ThreeState) + if (ThreeState) { - if (value.Equals(this.TrueValue) || + if (value.Equals(TrueValue) || (value is int && (int)value == (int)CheckState.Checked)) { value = CheckState.Checked; } - else if (value.Equals(this.FalseValue) || + else if (value.Equals(FalseValue) || (value is int && (int)value == (int)CheckState.Unchecked)) { value = CheckState.Unchecked; } - else if (value.Equals(this.IndeterminateValue) || + else if (value.Equals(IndeterminateValue) || (value is int && (int)value == (int)CheckState.Indeterminate)) { value = CheckState.Indeterminate; @@ -637,12 +637,12 @@ protected override object GetFormattedValue(object value, } else { - if (value.Equals(this.TrueValue) || + if (value.Equals(TrueValue) || (value is int && (int)value != 0)) { value = true; } - else if (value.Equals(this.FalseValue) || + else if (value.Equals(FalseValue) || (value is int && (int)value == 0)) { value = false; @@ -658,11 +658,11 @@ protected override object GetFormattedValue(object value, bool retBool = (bool)ret; if (retBool) { - return string.Format(this.ThreeState ? SR.DataGridViewCheckBoxCell_ClipboardChecked : SR.DataGridViewCheckBoxCell_ClipboardTrue); + return string.Format(ThreeState ? SR.DataGridViewCheckBoxCell_ClipboardChecked : SR.DataGridViewCheckBoxCell_ClipboardTrue); } else { - return string.Format(this.ThreeState ? SR.DataGridViewCheckBoxCell_ClipboardUnchecked : SR.DataGridViewCheckBoxCell_ClipboardFalse); + return string.Format(ThreeState ? SR.DataGridViewCheckBoxCell_ClipboardUnchecked : SR.DataGridViewCheckBoxCell_ClipboardFalse); } } else if (ret is CheckState) @@ -670,11 +670,11 @@ protected override object GetFormattedValue(object value, CheckState retCheckState = (CheckState)ret; if (retCheckState == CheckState.Checked) { - return string.Format(this.ThreeState ? SR.DataGridViewCheckBoxCell_ClipboardChecked : SR.DataGridViewCheckBoxCell_ClipboardTrue); + return string.Format(ThreeState ? SR.DataGridViewCheckBoxCell_ClipboardChecked : SR.DataGridViewCheckBoxCell_ClipboardTrue); } else if (retCheckState == CheckState.Unchecked) { - return string.Format(this.ThreeState ? SR.DataGridViewCheckBoxCell_ClipboardUnchecked : SR.DataGridViewCheckBoxCell_ClipboardFalse); + return string.Format(ThreeState ? SR.DataGridViewCheckBoxCell_ClipboardUnchecked : SR.DataGridViewCheckBoxCell_ClipboardFalse); } else { @@ -688,7 +688,7 @@ protected override object GetFormattedValue(object value, protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize) { - if (this.DataGridView == null) + if (DataGridView == null) { return new Size(-1, -1); } @@ -699,15 +699,15 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl } DataGridViewFreeDimension freeDimension = DataGridViewCell.GetFreeDimensionFromConstraint(constraintSize); - Rectangle borderWidthsRect = this.StdBorderWidths; + Rectangle borderWidthsRect = StdBorderWidths; int borderAndPaddingWidths = borderWidthsRect.Left + borderWidthsRect.Width + cellStyle.Padding.Horizontal; int borderAndPaddingHeights = borderWidthsRect.Top + borderWidthsRect.Height + cellStyle.Padding.Vertical; Size preferredSize; - if (this.DataGridView.ApplyVisualStylesToInnerCells) + if (DataGridView.ApplyVisualStylesToInnerCells) { // Assuming here that all checkbox states use the same size. We should take the largest of the state specific sizes. Size checkBoxSize = CheckBoxRenderer.GetGlyphSize(graphics, CheckBoxState.UncheckedNormal); - switch (this.FlatStyle) + switch (FlatStyle) { case FlatStyle.Standard: case FlatStyle.System: @@ -744,7 +744,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl else { int checkBoxSize; - switch (this.FlatStyle) + switch (FlatStyle) { case FlatStyle.Flat: checkBoxSize = CheckBoxRenderer.GetGlyphSize(graphics, CheckBoxState.UncheckedNormal).Width - 3; @@ -786,7 +786,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl preferredSize.Width += borderWidths.X; preferredSize.Height += borderWidths.Y; - if (this.DataGridView.ShowCellErrors) + if (DataGridView.ShowCellErrors) { // Making sure that there is enough room for the potential error icon if (freeDimension != DataGridViewFreeDimension.Height) @@ -820,12 +820,12 @@ protected override bool MouseDownUnsharesRow(DataGridViewCellMouseEventArgs e) protected override bool MouseEnterUnsharesRow(int rowIndex) { - return this.ColumnIndex == this.DataGridView.MouseDownCellAddress.X && rowIndex == this.DataGridView.MouseDownCellAddress.Y; + return ColumnIndex == DataGridView.MouseDownCellAddress.X && rowIndex == DataGridView.MouseDownCellAddress.Y; } protected override bool MouseLeaveUnsharesRow(int rowIndex) { - return (this.ButtonState & ButtonState.Pushed) != 0; + return (ButtonState & ButtonState.Pushed) != 0; } protected override bool MouseUpUnsharesRow(DataGridViewCellMouseEventArgs e) @@ -835,20 +835,20 @@ protected override bool MouseUpUnsharesRow(DataGridViewCellMouseEventArgs e) private void NotifyDataGridViewOfValueChange() { - this.flags |= (byte)DATAGRIDVIEWCHECKBOXCELL_valueChanged; - this.DataGridView.NotifyCurrentCellDirty(true); + flags |= (byte)DATAGRIDVIEWCHECKBOXCELL_valueChanged; + DataGridView.NotifyCurrentCellDirty(true); } private void OnCommonContentClick(DataGridViewCellEventArgs e) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } - Point ptCurrentCell = this.DataGridView.CurrentCellAddress; - if (ptCurrentCell.X == this.ColumnIndex && + Point ptCurrentCell = DataGridView.CurrentCellAddress; + if (ptCurrentCell.X == ColumnIndex && ptCurrentCell.Y == e.RowIndex && - this.DataGridView.IsCurrentCellInEditMode) + DataGridView.IsCurrentCellInEditMode) { if (SwitchFormattedValue()) { @@ -869,70 +869,70 @@ protected override void OnContentDoubleClick(DataGridViewCellEventArgs e) protected override void OnKeyDown(KeyEventArgs e, int rowIndex) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } if (e.KeyCode == Keys.Space && !e.Alt && !e.Control && !e.Shift) { - UpdateButtonState(this.ButtonState | ButtonState.Checked, rowIndex); + UpdateButtonState(ButtonState | ButtonState.Checked, rowIndex); e.Handled = true; } } protected override void OnKeyUp(KeyEventArgs e, int rowIndex) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } if (e.KeyCode == Keys.Space) { - UpdateButtonState(this.ButtonState & ~ButtonState.Checked, rowIndex); + UpdateButtonState(ButtonState & ~ButtonState.Checked, rowIndex); if (!e.Alt && !e.Control && !e.Shift) { - RaiseCellClick(new DataGridViewCellEventArgs(this.ColumnIndex, rowIndex)); - if (this.DataGridView != null && - this.ColumnIndex < this.DataGridView.Columns.Count && - rowIndex < this.DataGridView.Rows.Count) + RaiseCellClick(new DataGridViewCellEventArgs(ColumnIndex, rowIndex)); + if (DataGridView != null && + ColumnIndex < DataGridView.Columns.Count && + rowIndex < DataGridView.Rows.Count) { - RaiseCellContentClick(new DataGridViewCellEventArgs(this.ColumnIndex, rowIndex)); + RaiseCellContentClick(new DataGridViewCellEventArgs(ColumnIndex, rowIndex)); } e.Handled = true; } - NotifyMASSClient(new Point(this.ColumnIndex, rowIndex)); + NotifyMASSClient(new Point(ColumnIndex, rowIndex)); } } protected override void OnLeave(int rowIndex, bool throughMouseClick) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } - if (this.ButtonState != ButtonState.Normal) + if (ButtonState != ButtonState.Normal) { - Debug.Assert(this.RowIndex >= 0); // Cell is not in a shared row. + Debug.Assert(RowIndex >= 0); // Cell is not in a shared row. UpdateButtonState(ButtonState.Normal, rowIndex); } } protected override void OnMouseDown(DataGridViewCellMouseEventArgs e) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } if (e.Button == MouseButtons.Left && mouseInContentBounds) { - Debug.Assert(this.DataGridView.CellMouseDownInContentBounds); - UpdateButtonState(this.ButtonState | ButtonState.Pushed, e.RowIndex); + Debug.Assert(DataGridView.CellMouseDownInContentBounds); + UpdateButtonState(ButtonState | ButtonState.Pushed, e.RowIndex); } } protected override void OnMouseLeave(int rowIndex) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } @@ -940,25 +940,25 @@ protected override void OnMouseLeave(int rowIndex) if (mouseInContentBounds) { mouseInContentBounds = false; - if (this.ColumnIndex >= 0 && + if (ColumnIndex >= 0 && rowIndex >= 0 && - (this.DataGridView.ApplyVisualStylesToInnerCells || this.FlatStyle == FlatStyle.Flat || this.FlatStyle == FlatStyle.Popup)) + (DataGridView.ApplyVisualStylesToInnerCells || FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup)) { - this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex); + DataGridView.InvalidateCell(ColumnIndex, rowIndex); } } - if ((this.ButtonState & ButtonState.Pushed) != 0 && - this.ColumnIndex == this.DataGridView.MouseDownCellAddress.X && - rowIndex == this.DataGridView.MouseDownCellAddress.Y) + if ((ButtonState & ButtonState.Pushed) != 0 && + ColumnIndex == DataGridView.MouseDownCellAddress.X && + rowIndex == DataGridView.MouseDownCellAddress.Y) { - UpdateButtonState(this.ButtonState & ~ButtonState.Pushed, rowIndex); + UpdateButtonState(ButtonState & ~ButtonState.Pushed, rowIndex); } } protected override void OnMouseMove(DataGridViewCellMouseEventArgs e) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } @@ -967,24 +967,24 @@ protected override void OnMouseMove(DataGridViewCellMouseEventArgs e) mouseInContentBounds = GetContentBounds(e.RowIndex).Contains(e.X, e.Y); if (oldMouseInContentBounds != mouseInContentBounds) { - if (this.DataGridView.ApplyVisualStylesToInnerCells || this.FlatStyle == FlatStyle.Flat || this.FlatStyle == FlatStyle.Popup) + if (DataGridView.ApplyVisualStylesToInnerCells || FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup) { - this.DataGridView.InvalidateCell(this.ColumnIndex, e.RowIndex); + DataGridView.InvalidateCell(ColumnIndex, e.RowIndex); } - if (e.ColumnIndex == this.DataGridView.MouseDownCellAddress.X && - e.RowIndex == this.DataGridView.MouseDownCellAddress.Y && + if (e.ColumnIndex == DataGridView.MouseDownCellAddress.X && + e.RowIndex == DataGridView.MouseDownCellAddress.Y && Control.MouseButtons == MouseButtons.Left) { - if ((this.ButtonState & ButtonState.Pushed) == 0 && + if ((ButtonState & ButtonState.Pushed) == 0 && mouseInContentBounds && - this.DataGridView.CellMouseDownInContentBounds) + DataGridView.CellMouseDownInContentBounds) { - UpdateButtonState(this.ButtonState | ButtonState.Pushed, e.RowIndex); + UpdateButtonState(ButtonState | ButtonState.Pushed, e.RowIndex); } - else if ((this.ButtonState & ButtonState.Pushed) != 0 && !mouseInContentBounds) + else if ((ButtonState & ButtonState.Pushed) != 0 && !mouseInContentBounds) { - UpdateButtonState(this.ButtonState & ~ButtonState.Pushed, e.RowIndex); + UpdateButtonState(ButtonState & ~ButtonState.Pushed, e.RowIndex); } } } @@ -994,27 +994,27 @@ protected override void OnMouseMove(DataGridViewCellMouseEventArgs e) protected override void OnMouseUp(DataGridViewCellMouseEventArgs e) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } if (e.Button == MouseButtons.Left) { - UpdateButtonState(this.ButtonState & ~ButtonState.Pushed, e.RowIndex); + UpdateButtonState(ButtonState & ~ButtonState.Pushed, e.RowIndex); NotifyMASSClient(new Point(e.ColumnIndex, e.RowIndex)); } } private void NotifyMASSClient(Point position) { - Debug.Assert((position.X >= 0) && (position.X < this.DataGridView.Columns.Count)); - Debug.Assert((position.Y >= 0) && (position.Y < this.DataGridView.Rows.Count)); + Debug.Assert((position.X >= 0) && (position.X < DataGridView.Columns.Count)); + Debug.Assert((position.Y >= 0) && (position.Y < DataGridView.Rows.Count)); - int visibleRowIndex = this.DataGridView.Rows.GetRowCount(DataGridViewElementStates.Visible, 0, position.Y); - int visibleColumnIndex = this.DataGridView.Columns.ColumnIndexToActualDisplayIndex(position.X, DataGridViewElementStates.Visible); + int visibleRowIndex = DataGridView.Rows.GetRowCount(DataGridViewElementStates.Visible, 0, position.Y); + int visibleColumnIndex = DataGridView.Columns.ColumnIndexToActualDisplayIndex(position.X, DataGridViewElementStates.Visible); - int topHeaderRowIncrement = this.DataGridView.ColumnHeadersVisible ? 1 : 0; - int rowHeaderIncrement = this.DataGridView.RowHeadersVisible ? 1 : 0; + int topHeaderRowIncrement = DataGridView.ColumnHeadersVisible ? 1 : 0; + int rowHeaderIncrement = DataGridView.RowHeadersVisible ? 1 : 0; int objectID = visibleRowIndex + topHeaderRowIncrement // + 1 because the top header row acc obj is at index 0 + 1; // + 1 because objectID's need to be positive and non-zero @@ -1022,7 +1022,7 @@ private void NotifyMASSClient(Point position) int childID = visibleColumnIndex + rowHeaderIncrement; // + 1 because the column header cell is at index 0 in top header row acc obj // same thing for the row header cell in the data grid view row acc obj - (this.DataGridView.AccessibilityObject as Control.ControlAccessibleObject).NotifyClients(AccessibleEvents.StateChange, objectID, childID); + (DataGridView.AccessibilityObject as Control.ControlAccessibleObject).NotifyClients(AccessibleEvents.StateChange, objectID, childID); } protected override void Paint(Graphics graphics, @@ -1103,9 +1103,9 @@ private Rectangle PaintPrivate(Graphics g, bool drawAsMixedCheckBox = false, drawErrorText = true; CheckState checkState; ButtonState bs; - Point ptCurrentCell = this.DataGridView.CurrentCellAddress; - if (ptCurrentCell.X == this.ColumnIndex && - ptCurrentCell.Y == rowIndex && this.DataGridView.IsCurrentCellInEditMode) + Point ptCurrentCell = DataGridView.CurrentCellAddress; + if (ptCurrentCell.X == ColumnIndex && + ptCurrentCell.Y == rowIndex && DataGridView.IsCurrentCellInEditMode) { drawErrorText = false; } @@ -1135,11 +1135,11 @@ private Rectangle PaintPrivate(Graphics g, bs = ButtonState.Normal; // Default rendering of the checkbox with wrong formatted value type. checkState = CheckState.Unchecked; } - if ((this.ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0) + if ((ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0) { bs |= ButtonState.Pushed; } - SolidBrush br = this.DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor); + SolidBrush br = DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor); if (paint && DataGridViewCell.PaintBackground(paintParts) && br.Color.A == 255) { @@ -1148,7 +1148,7 @@ private Rectangle PaintPrivate(Graphics g, if (cellStyle.Padding != Padding.Empty) { - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { valBounds.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top); } @@ -1162,9 +1162,9 @@ private Rectangle PaintPrivate(Graphics g, if (paint && DataGridViewCell.PaintFocus(paintParts) && - this.DataGridView.ShowFocusCues && - this.DataGridView.Focused && - ptCurrentCell.X == this.ColumnIndex && + DataGridView.ShowFocusCues && + DataGridView.Focused && + ptCurrentCell.X == ColumnIndex && ptCurrentCell.Y == rowIndex) { // Draw focus rectangle @@ -1179,14 +1179,14 @@ private Rectangle PaintPrivate(Graphics g, CheckBoxState themeCheckBoxState = CheckBoxState.UncheckedNormal; - if (this.DataGridView.ApplyVisualStylesToInnerCells) + if (DataGridView.ApplyVisualStylesToInnerCells) { themeCheckBoxState = CheckBoxRenderer.ConvertFromButtonState(bs, drawAsMixedCheckBox, - this.DataGridView.MouseEnteredCellAddress.Y == rowIndex && - this.DataGridView.MouseEnteredCellAddress.X == this.ColumnIndex && + DataGridView.MouseEnteredCellAddress.Y == rowIndex && + DataGridView.MouseEnteredCellAddress.X == ColumnIndex && mouseInContentBounds); checkBoxSize = CheckBoxRenderer.GetGlyphSize(g, themeCheckBoxState); - switch (this.FlatStyle) + switch (FlatStyle) { case FlatStyle.Standard: case FlatStyle.System: @@ -1203,7 +1203,7 @@ private Rectangle PaintPrivate(Graphics g, } else { - switch (this.FlatStyle) + switch (FlatStyle) { case FlatStyle.Flat: checkBoxSize = CheckBoxRenderer.GetGlyphSize(g, CheckBoxState.UncheckedNormal); @@ -1224,8 +1224,8 @@ private Rectangle PaintPrivate(Graphics g, if (valBounds.Width >= checkBoxSize.Width && valBounds.Height >= checkBoxSize.Height && (paint || computeContentBounds)) { int checkBoxX = 0, checkBoxY = 0; - if ((!this.DataGridView.RightToLeftInternal && (cellStyle.Alignment & anyRight) != 0) || - (this.DataGridView.RightToLeftInternal && (cellStyle.Alignment & anyLeft) != 0)) + if ((!DataGridView.RightToLeftInternal && (cellStyle.Alignment & anyRight) != 0) || + (DataGridView.RightToLeftInternal && (cellStyle.Alignment & anyLeft) != 0)) { checkBoxX = valBounds.Right - checkBoxSize.Width; } @@ -1251,7 +1251,7 @@ private Rectangle PaintPrivate(Graphics g, checkBoxY = valBounds.Top; } - if (this.DataGridView.ApplyVisualStylesToInnerCells && this.FlatStyle != FlatStyle.Flat && this.FlatStyle != FlatStyle.Popup) + if (DataGridView.ApplyVisualStylesToInnerCells && FlatStyle != FlatStyle.Flat && FlatStyle != FlatStyle.Popup) { if (paint && DataGridViewCell.PaintContentForeground(paintParts)) { @@ -1264,7 +1264,7 @@ private Rectangle PaintPrivate(Graphics g, } else { - if (this.FlatStyle == FlatStyle.System || this.FlatStyle == FlatStyle.Standard) + if (FlatStyle == FlatStyle.System || FlatStyle == FlatStyle.Standard) { if (paint && DataGridViewCell.PaintContentForeground(paintParts)) { @@ -1280,7 +1280,7 @@ private Rectangle PaintPrivate(Graphics g, resultBounds = new Rectangle(checkBoxX, checkBoxY, checkBoxSize.Width, checkBoxSize.Height); } - else if (this.FlatStyle == FlatStyle.Flat) + else if (FlatStyle == FlatStyle.Flat) { // CheckBox::Paint will only paint the check box differently when in FlatStyle.Flat // this code is copied from CheckBox::DrawCheckFlat. it was a lot of trouble making this function static @@ -1293,12 +1293,12 @@ private Rectangle PaintPrivate(Graphics g, if (paint && DataGridViewCell.PaintContentForeground(paintParts)) { - foreBrush = this.DataGridView.GetCachedBrush(cellSelected ? cellStyle.SelectionForeColor : cellStyle.ForeColor); - backBrush = this.DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor); + foreBrush = DataGridView.GetCachedBrush(cellSelected ? cellStyle.SelectionForeColor : cellStyle.ForeColor); + backBrush = DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor); highlight = ControlPaint.LightLight(backBrush.Color); - if (this.DataGridView.MouseEnteredCellAddress.Y == rowIndex && - this.DataGridView.MouseEnteredCellAddress.X == this.ColumnIndex && + if (DataGridView.MouseEnteredCellAddress.Y == rowIndex && + DataGridView.MouseEnteredCellAddress.X == ColumnIndex && mouseInContentBounds) { const float lowlight = .1f; @@ -1383,14 +1383,14 @@ private Rectangle PaintPrivate(Graphics g, } else { - Debug.Assert(this.FlatStyle == FlatStyle.Popup); + Debug.Assert(FlatStyle == FlatStyle.Popup); Rectangle checkBounds = new Rectangle(checkBoxX, checkBoxY, checkBoxSize.Width - 1, checkBoxSize.Height - 1); // The CheckBoxAdapter code moves the check box down about 3 pixels so we have to take that into account checkBounds.Y -= 3; - if ((this.ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0) + if ((ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0) { // paint down ButtonBaseAdapter.LayoutOptions options = ButtonInternal.CheckBoxPopupAdapter.PaintPopupLayout(g, @@ -1401,9 +1401,9 @@ private Rectangle PaintPrivate(Graphics g, false, cellStyle.Font, string.Empty, - this.DataGridView.Enabled, + DataGridView.Enabled, DataGridViewUtilities.ComputeDrawingContentAlignmentForCellStyleAlignment(cellStyle.Alignment), - this.DataGridView.RightToLeft); + DataGridView.RightToLeft); options.everettButtonCompat = false; ButtonBaseAdapter.LayoutData layout = options.Layout(); @@ -1413,8 +1413,8 @@ private Rectangle PaintPrivate(Graphics g, ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintPopupRender(g, cellStyle.ForeColor, cellStyle.BackColor, - this.DataGridView.Enabled).Calculate(); - CheckBoxBaseAdapter.DrawCheckBackground(this.DataGridView.Enabled, + DataGridView.Enabled).Calculate(); + CheckBoxBaseAdapter.DrawCheckBackground(DataGridView.Enabled, checkState, g, layout.checkBounds, @@ -1425,7 +1425,7 @@ private Rectangle PaintPrivate(Graphics g, CheckBoxBaseAdapter.DrawPopupBorder(g, layout.checkBounds, colors); CheckBoxBaseAdapter.DrawCheckOnly(checkBoxSize.Width, checkState == CheckState.Checked || checkState == CheckState.Indeterminate, - this.DataGridView.Enabled, + DataGridView.Enabled, checkState, g, layout, @@ -1435,8 +1435,8 @@ private Rectangle PaintPrivate(Graphics g, } resultBounds = layout.checkBounds; } - else if (this.DataGridView.MouseEnteredCellAddress.Y == rowIndex && - this.DataGridView.MouseEnteredCellAddress.X == this.ColumnIndex && + else if (DataGridView.MouseEnteredCellAddress.Y == rowIndex && + DataGridView.MouseEnteredCellAddress.X == ColumnIndex && mouseInContentBounds) { // paint over @@ -1449,9 +1449,9 @@ private Rectangle PaintPrivate(Graphics g, false, cellStyle.Font, string.Empty, - this.DataGridView.Enabled, + DataGridView.Enabled, DataGridViewUtilities.ComputeDrawingContentAlignmentForCellStyleAlignment(cellStyle.Alignment), - this.DataGridView.RightToLeft); + DataGridView.RightToLeft); options.everettButtonCompat = false; ButtonBaseAdapter.LayoutData layout = options.Layout(); @@ -1460,8 +1460,8 @@ private Rectangle PaintPrivate(Graphics g, ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintPopupRender(g, cellStyle.ForeColor, cellStyle.BackColor, - this.DataGridView.Enabled).Calculate(); - CheckBoxBaseAdapter.DrawCheckBackground(this.DataGridView.Enabled, + DataGridView.Enabled).Calculate(); + CheckBoxBaseAdapter.DrawCheckBackground(DataGridView.Enabled, checkState, g, layout.checkBounds, @@ -1472,7 +1472,7 @@ private Rectangle PaintPrivate(Graphics g, CheckBoxBaseAdapter.DrawPopupBorder(g, layout.checkBounds, colors); CheckBoxBaseAdapter.DrawCheckOnly(checkBoxSize.Width, checkState == CheckState.Checked || checkState == CheckState.Indeterminate, - this.DataGridView.Enabled, + DataGridView.Enabled, checkState, g, layout, @@ -1493,9 +1493,9 @@ private Rectangle PaintPrivate(Graphics g, false, cellStyle.Font, string.Empty, - this.DataGridView.Enabled, + DataGridView.Enabled, DataGridViewUtilities.ComputeDrawingContentAlignmentForCellStyleAlignment(cellStyle.Alignment), - this.DataGridView.RightToLeft); + DataGridView.RightToLeft); options.everettButtonCompat = false; ButtonBaseAdapter.LayoutData layout = options.Layout(); @@ -1505,8 +1505,8 @@ private Rectangle PaintPrivate(Graphics g, ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintPopupRender(g, cellStyle.ForeColor, cellStyle.BackColor, - this.DataGridView.Enabled).Calculate(); - CheckBoxBaseAdapter.DrawCheckBackground(this.DataGridView.Enabled, + DataGridView.Enabled).Calculate(); + CheckBoxBaseAdapter.DrawCheckBackground(DataGridView.Enabled, checkState, g, layout.checkBounds, @@ -1517,7 +1517,7 @@ private Rectangle PaintPrivate(Graphics g, ButtonBaseAdapter.DrawFlatBorder(g, layout.checkBounds, colors.buttonShadow); CheckBoxBaseAdapter.DrawCheckOnly(checkBoxSize.Width, checkState == CheckState.Checked || checkState == CheckState.Indeterminate, - this.DataGridView.Enabled, + DataGridView.Enabled, checkState, g, layout, @@ -1547,7 +1547,7 @@ private Rectangle PaintPrivate(Graphics g, resultBounds = Rectangle.Empty; } - if (paint && DataGridViewCell.PaintErrorIcon(paintParts) && drawErrorText && this.DataGridView.ShowCellErrors) + if (paint && DataGridViewCell.PaintErrorIcon(paintParts) && drawErrorText && DataGridView.ShowCellErrors) { PaintErrorIcon(g, cellStyle, rowIndex, cellBounds, errorBounds, errorText); } @@ -1560,7 +1560,7 @@ public override object ParseFormattedValue(object formattedValue, TypeConverter formattedValueTypeConverter, TypeConverter valueTypeConverter) { - Debug.Assert(formattedValue == null || this.FormattedValueType == null || this.FormattedValueType.IsAssignableFrom(formattedValue.GetType())); + Debug.Assert(formattedValue == null || FormattedValueType == null || FormattedValueType.IsAssignableFrom(formattedValue.GetType())); if (formattedValue != null) { @@ -1568,30 +1568,30 @@ public override object ParseFormattedValue(object formattedValue, { if ((bool)formattedValue) { - if (this.TrueValue != null) + if (TrueValue != null) { - return this.TrueValue; + return TrueValue; } - else if (this.ValueType != null && this.ValueType.IsAssignableFrom(defaultBooleanType)) + else if (ValueType != null && ValueType.IsAssignableFrom(defaultBooleanType)) { return true; } - else if (this.ValueType != null && this.ValueType.IsAssignableFrom(defaultCheckStateType)) + else if (ValueType != null && ValueType.IsAssignableFrom(defaultCheckStateType)) { return CheckState.Checked; } } else { - if (this.FalseValue != null) + if (FalseValue != null) { - return this.FalseValue; + return FalseValue; } - else if (this.ValueType != null && this.ValueType.IsAssignableFrom(defaultBooleanType)) + else if (ValueType != null && ValueType.IsAssignableFrom(defaultBooleanType)) { return false; } - else if (this.ValueType != null && this.ValueType.IsAssignableFrom(defaultCheckStateType)) + else if (ValueType != null && ValueType.IsAssignableFrom(defaultCheckStateType)) { return CheckState.Unchecked; } @@ -1602,39 +1602,39 @@ public override object ParseFormattedValue(object formattedValue, switch ((CheckState)formattedValue) { case CheckState.Checked: - if (this.TrueValue != null) + if (TrueValue != null) { - return this.TrueValue; + return TrueValue; } - else if (this.ValueType != null && this.ValueType.IsAssignableFrom(defaultBooleanType)) + else if (ValueType != null && ValueType.IsAssignableFrom(defaultBooleanType)) { return true; } - else if (this.ValueType != null && this.ValueType.IsAssignableFrom(defaultCheckStateType)) + else if (ValueType != null && ValueType.IsAssignableFrom(defaultCheckStateType)) { return CheckState.Checked; } break; case CheckState.Unchecked: - if (this.FalseValue != null) + if (FalseValue != null) { - return this.FalseValue; + return FalseValue; } - else if (this.ValueType != null && this.ValueType.IsAssignableFrom(defaultBooleanType)) + else if (ValueType != null && ValueType.IsAssignableFrom(defaultBooleanType)) { return false; } - else if (this.ValueType != null && this.ValueType.IsAssignableFrom(defaultCheckStateType)) + else if (ValueType != null && ValueType.IsAssignableFrom(defaultCheckStateType)) { return CheckState.Unchecked; } break; case CheckState.Indeterminate: - if (this.IndeterminateValue != null) + if (IndeterminateValue != null) { - return this.IndeterminateValue; + return IndeterminateValue; } - else if (this.ValueType != null && this.ValueType.IsAssignableFrom(defaultCheckStateType)) + else if (ValueType != null && ValueType.IsAssignableFrom(defaultCheckStateType)) { return CheckState.Indeterminate; } @@ -1651,18 +1651,18 @@ public override object ParseFormattedValue(object formattedValue, ] private bool SwitchFormattedValue() { - if (this.FormattedValueType == null) + if (FormattedValueType == null) { return false; } IDataGridViewEditingCell editingCell = (IDataGridViewEditingCell)this; - if (this.FormattedValueType.IsAssignableFrom(typeof(System.Windows.Forms.CheckState))) + if (FormattedValueType.IsAssignableFrom(typeof(System.Windows.Forms.CheckState))) { - if ((this.flags & DATAGRIDVIEWCHECKBOXCELL_checked) != 0x00) + if ((flags & DATAGRIDVIEWCHECKBOXCELL_checked) != 0x00) { editingCell.EditingCellFormattedValue = System.Windows.Forms.CheckState.Indeterminate; } - else if ((this.flags & DATAGRIDVIEWCHECKBOXCELL_indeterminate) != 0x00) + else if ((flags & DATAGRIDVIEWCHECKBOXCELL_indeterminate) != 0x00) { editingCell.EditingCellFormattedValue = System.Windows.Forms.CheckState.Unchecked; } @@ -1671,7 +1671,7 @@ private bool SwitchFormattedValue() editingCell.EditingCellFormattedValue = System.Windows.Forms.CheckState.Checked; } } - else if (this.FormattedValueType.IsAssignableFrom(defaultBooleanType)) + else if (FormattedValueType.IsAssignableFrom(defaultBooleanType)) { editingCell.EditingCellFormattedValue = !((bool)editingCell.GetEditingCellFormattedValue(DataGridViewDataErrorContexts.Formatting)); } @@ -1685,13 +1685,13 @@ private bool SwitchFormattedValue() /// public override string ToString() { - return "DataGridViewCheckBoxCell { ColumnIndex=" + this.ColumnIndex.ToString(CultureInfo.CurrentCulture) + ", RowIndex=" + this.RowIndex.ToString(CultureInfo.CurrentCulture) + " }"; + return "DataGridViewCheckBoxCell { ColumnIndex=" + ColumnIndex.ToString(CultureInfo.CurrentCulture) + ", RowIndex=" + RowIndex.ToString(CultureInfo.CurrentCulture) + " }"; } private void UpdateButtonState(ButtonState newButtonState, int rowIndex) { - this.ButtonState = newButtonState; - this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex); + ButtonState = newButtonState; + DataGridView.InvalidateCell(ColumnIndex, rowIndex); } private class DataGridViewCheckBoxCellRenderer @@ -1760,12 +1760,12 @@ public override string DefaultAction { get { - if (!this.Owner.ReadOnly) + if (!Owner.ReadOnly) { // determine if we switch to Checked/Unchecked value bool switchToCheckedState = true; - object formattedValue = this.Owner.FormattedValue; + object formattedValue = Owner.FormattedValue; if (formattedValue is System.Windows.Forms.CheckState) { @@ -1794,7 +1794,7 @@ public override string DefaultAction public override void DoDefaultAction() { - DataGridViewCheckBoxCell dataGridViewCell = (DataGridViewCheckBoxCell)this.Owner; + DataGridViewCheckBoxCell dataGridViewCell = (DataGridViewCheckBoxCell)Owner; DataGridView dataGridView = dataGridViewCell.DataGridView; if (dataGridView != null && dataGridViewCell.RowIndex == -1) @@ -1848,7 +1848,7 @@ internal override int[] RuntimeId { runtimeId = new int[2]; runtimeId[0] = RuntimeIDFirstItem; // first item is static - 0x2a - runtimeId[1] = this.GetHashCode(); + runtimeId[1] = GetHashCode(); } return runtimeId; @@ -1889,7 +1889,7 @@ internal override UnsafeNativeMethods.ToggleState ToggleState get { bool toggledState = true; - object formattedValue = this.Owner.FormattedValue; + object formattedValue = Owner.FormattedValue; if (formattedValue is System.Windows.Forms.CheckState) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxColumn.cs index 5f99cea703d..c8482392dd3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxColumn.cs @@ -35,7 +35,7 @@ public DataGridViewCheckBoxColumn(bool threeState) { defaultCellStyle.NullValue = false; } - this.DefaultCellStyle = defaultCellStyle; + DefaultCellStyle = defaultCellStyle; } [ @@ -62,7 +62,7 @@ private DataGridViewCheckBoxCell CheckBoxCellTemplate { get { - return (DataGridViewCheckBoxCell)this.CellTemplate; + return (DataGridViewCheckBoxCell)CellTemplate; } } @@ -93,31 +93,31 @@ public object FalseValue { get { - if (this.CheckBoxCellTemplate == null) + if (CheckBoxCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return this.CheckBoxCellTemplate.FalseValue; + return CheckBoxCellTemplate.FalseValue; } set { - if (this.FalseValue != value) + if (FalseValue != value) { - this.CheckBoxCellTemplate.FalseValueInternal = value; - if (this.DataGridView != null) + CheckBoxCellTemplate.FalseValueInternal = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewCheckBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewCheckBoxCell; + DataGridViewCheckBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewCheckBoxCell; if (dataGridViewCell != null) { dataGridViewCell.FalseValueInternal = value; } } - this.DataGridView.InvalidateColumn(this.Index); + DataGridView.InvalidateColumn(Index); } } } @@ -132,31 +132,31 @@ public FlatStyle FlatStyle { get { - if (this.CheckBoxCellTemplate == null) + if (CheckBoxCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return this.CheckBoxCellTemplate.FlatStyle; + return CheckBoxCellTemplate.FlatStyle; } set { - if (this.FlatStyle != value) + if (FlatStyle != value) { - this.CheckBoxCellTemplate.FlatStyle = value; - if (this.DataGridView != null) + CheckBoxCellTemplate.FlatStyle = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewCheckBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewCheckBoxCell; + DataGridViewCheckBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewCheckBoxCell; if (dataGridViewCell != null) { dataGridViewCell.FlatStyleInternal = value; } } - this.DataGridView.OnColumnCommonChange(this.Index); + DataGridView.OnColumnCommonChange(Index); } } } @@ -172,31 +172,31 @@ public object IndeterminateValue { get { - if (this.CheckBoxCellTemplate == null) + if (CheckBoxCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return this.CheckBoxCellTemplate.IndeterminateValue; + return CheckBoxCellTemplate.IndeterminateValue; } set { - if (this.IndeterminateValue != value) + if (IndeterminateValue != value) { - this.CheckBoxCellTemplate.IndeterminateValueInternal = value; - if (this.DataGridView != null) + CheckBoxCellTemplate.IndeterminateValueInternal = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewCheckBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewCheckBoxCell; + DataGridViewCheckBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewCheckBoxCell; if (dataGridViewCell != null) { dataGridViewCell.IndeterminateValueInternal = value; } } - this.DataGridView.InvalidateColumn(this.Index); + DataGridView.InvalidateColumn(Index); } } } @@ -211,47 +211,47 @@ public bool ThreeState { get { - if (this.CheckBoxCellTemplate == null) + if (CheckBoxCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return this.CheckBoxCellTemplate.ThreeState; + return CheckBoxCellTemplate.ThreeState; } [ SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes") // OK to cast a NullValue into a bool and CheckState ] set { - if (this.ThreeState != value) + if (ThreeState != value) { - this.CheckBoxCellTemplate.ThreeStateInternal = value; - if (this.DataGridView != null) + CheckBoxCellTemplate.ThreeStateInternal = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewCheckBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewCheckBoxCell; + DataGridViewCheckBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewCheckBoxCell; if (dataGridViewCell != null) { dataGridViewCell.ThreeStateInternal = value; } } - this.DataGridView.InvalidateColumn(this.Index); + DataGridView.InvalidateColumn(Index); } if (value && - this.DefaultCellStyle.NullValue is bool && - (bool)this.DefaultCellStyle.NullValue == false) + DefaultCellStyle.NullValue is bool && + (bool)DefaultCellStyle.NullValue == false) { - this.DefaultCellStyle.NullValue = CheckState.Indeterminate; + DefaultCellStyle.NullValue = CheckState.Indeterminate; } else if (!value && - this.DefaultCellStyle.NullValue is CheckState && - (CheckState)this.DefaultCellStyle.NullValue == CheckState.Indeterminate) + DefaultCellStyle.NullValue is CheckState && + (CheckState)DefaultCellStyle.NullValue == CheckState.Indeterminate) { - this.DefaultCellStyle.NullValue = false; + DefaultCellStyle.NullValue = false; } } } @@ -267,31 +267,31 @@ public object TrueValue { get { - if (this.CheckBoxCellTemplate == null) + if (CheckBoxCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return this.CheckBoxCellTemplate.TrueValue; + return CheckBoxCellTemplate.TrueValue; } set { - if (this.TrueValue != value) + if (TrueValue != value) { - this.CheckBoxCellTemplate.TrueValueInternal = value; - if (this.DataGridView != null) + CheckBoxCellTemplate.TrueValueInternal = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewCheckBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewCheckBoxCell; + DataGridViewCheckBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewCheckBoxCell; if (dataGridViewCell != null) { dataGridViewCell.TrueValueInternal = value; } } - this.DataGridView.InvalidateColumn(this.Index); + DataGridView.InvalidateColumn(Index); } } } @@ -300,7 +300,7 @@ public object TrueValue private bool ShouldSerializeDefaultCellStyle() { object defaultNullValue; - DataGridViewCheckBoxCell templateCell = this.CellTemplate as DataGridViewCheckBoxCell; + DataGridViewCheckBoxCell templateCell = CellTemplate as DataGridViewCheckBoxCell; if (templateCell == null) { Debug.Fail("we can't compute the default cell style w/o a template cell"); @@ -316,12 +316,12 @@ private bool ShouldSerializeDefaultCellStyle() defaultNullValue = false; } - if (!this.HasDefaultCellStyle) + if (!HasDefaultCellStyle) { return false; } - DataGridViewCellStyle defaultCellStyle = this.DefaultCellStyle; + DataGridViewCellStyle defaultCellStyle = DefaultCellStyle; return (!defaultCellStyle.BackColor.IsEmpty || !defaultCellStyle.ForeColor.IsEmpty || @@ -342,9 +342,9 @@ public override string ToString() { StringBuilder sb = new StringBuilder(64); sb.Append("DataGridViewCheckBoxColumn { Name="); - sb.Append(this.Name); + sb.Append(Name); sb.Append(", Index="); - sb.Append(this.Index.ToString(CultureInfo.CurrentCulture)); + sb.Append(Index.ToString(CultureInfo.CurrentCulture)); sb.Append(" }"); return sb.ToString(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumn.cs index eaa36f091c7..dbc0b3bb1c7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumn.cs @@ -62,15 +62,15 @@ public DataGridViewColumn() : this((DataGridViewCell)null) public DataGridViewColumn(DataGridViewCell cellTemplate) : base() { - this.fillWeight = DATAGRIDVIEWCOLUMN_defaultFillWeight; - this.usedFillWeight = DATAGRIDVIEWCOLUMN_defaultFillWeight; - this.Thickness = ScaleToCurrentDpi(DATAGRIDVIEWCOLUMN_defaultWidth); - this.MinimumThickness = ScaleToCurrentDpi(DATAGRIDVIEWCOLUMN_defaultMinColumnThickness); - this.name = string.Empty; - this._bandIsRow = false; - this.displayIndex = -1; + fillWeight = DATAGRIDVIEWCOLUMN_defaultFillWeight; + usedFillWeight = DATAGRIDVIEWCOLUMN_defaultFillWeight; + Thickness = ScaleToCurrentDpi(DATAGRIDVIEWCOLUMN_defaultWidth); + MinimumThickness = ScaleToCurrentDpi(DATAGRIDVIEWCOLUMN_defaultMinColumnThickness); + name = string.Empty; + _bandIsRow = false; + displayIndex = -1; this.cellTemplate = cellTemplate; - this.autoSizeMode = DataGridViewAutoSizeColumnMode.NotSet; + autoSizeMode = DataGridViewAutoSizeColumnMode.NotSet; } /// @@ -93,7 +93,7 @@ public DataGridViewAutoSizeColumnMode AutoSizeMode { get { - return this.autoSizeMode; + return autoSizeMode; } set { @@ -111,53 +111,53 @@ public DataGridViewAutoSizeColumnMode AutoSizeMode default: throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewAutoSizeColumnMode)); } - if (this.autoSizeMode != value) + if (autoSizeMode != value) { - if (this.Visible && this.DataGridView != null) + if (Visible && DataGridView != null) { - if (!this.DataGridView.ColumnHeadersVisible && + if (!DataGridView.ColumnHeadersVisible && (value == DataGridViewAutoSizeColumnMode.ColumnHeader || - (value == DataGridViewAutoSizeColumnMode.NotSet && this.DataGridView.AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.ColumnHeader))) + (value == DataGridViewAutoSizeColumnMode.NotSet && DataGridView.AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.ColumnHeader))) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_AutoSizeCriteriaCannotUseInvisibleHeaders)); } - if (this.Frozen && + if (Frozen && (value == DataGridViewAutoSizeColumnMode.Fill || - (value == DataGridViewAutoSizeColumnMode.NotSet && this.DataGridView.AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.Fill))) + (value == DataGridViewAutoSizeColumnMode.NotSet && DataGridView.AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.Fill))) { // Cannot set the inherited auto size mode to Fill when the column is frozen throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_FrozenColumnCannotAutoFill)); } } - DataGridViewAutoSizeColumnMode previousInheritedMode = this.InheritedAutoSizeMode; + DataGridViewAutoSizeColumnMode previousInheritedMode = InheritedAutoSizeMode; bool previousInheritedModeAutoSized = previousInheritedMode != DataGridViewAutoSizeColumnMode.Fill && previousInheritedMode != DataGridViewAutoSizeColumnMode.None && previousInheritedMode != DataGridViewAutoSizeColumnMode.NotSet; - this.autoSizeMode = value; - if (this.DataGridView == null) + autoSizeMode = value; + if (DataGridView == null) { - if (this.InheritedAutoSizeMode != DataGridViewAutoSizeColumnMode.Fill && - this.InheritedAutoSizeMode != DataGridViewAutoSizeColumnMode.None && - this.InheritedAutoSizeMode != DataGridViewAutoSizeColumnMode.NotSet) + if (InheritedAutoSizeMode != DataGridViewAutoSizeColumnMode.Fill && + InheritedAutoSizeMode != DataGridViewAutoSizeColumnMode.None && + InheritedAutoSizeMode != DataGridViewAutoSizeColumnMode.NotSet) { if (!previousInheritedModeAutoSized) { // Save current column width for later reuse - this.CachedThickness = this.Thickness; + CachedThickness = Thickness; } } else { - if (this.Thickness != this.CachedThickness && previousInheritedModeAutoSized) + if (Thickness != CachedThickness && previousInheritedModeAutoSized) { // Restoring cached column width - this.ThicknessInternal = this.CachedThickness; + ThicknessInternal = CachedThickness; } } } else { - this.DataGridView.OnAutoSizeColumnModeChanged(this, previousInheritedMode); + DataGridView.OnAutoSizeColumnModeChanged(this, previousInheritedMode); } } } @@ -169,11 +169,11 @@ internal TypeConverter BoundColumnConverter { get { - return this.boundColumnConverter; + return boundColumnConverter; } set { - this.boundColumnConverter = value; + boundColumnConverter = value; } } @@ -181,11 +181,11 @@ internal int BoundColumnIndex { get { - return this.boundColumnIndex; + return boundColumnIndex; } set { - this.boundColumnIndex = value; + boundColumnIndex = value; } } @@ -198,11 +198,11 @@ public virtual DataGridViewCell CellTemplate { get { - return this.cellTemplate; + return cellTemplate; } set { - this.cellTemplate = value; + cellTemplate = value; } } @@ -214,9 +214,9 @@ public Type CellType { get { - if (this.cellTemplate != null) + if (cellTemplate != null) { - return this.cellTemplate.GetType(); + return cellTemplate.GetType(); } else { @@ -254,7 +254,7 @@ public string DataPropertyName { get { - return this.dataPropertyName; + return dataPropertyName; } set { @@ -262,12 +262,12 @@ public string DataPropertyName { value = string.Empty; } - if (value != this.dataPropertyName) + if (value != dataPropertyName) { - this.dataPropertyName = value; - if (this.DataGridView != null) + dataPropertyName = value; + if (DataGridView != null) { - this.DataGridView.OnColumnDataPropertyNameChanged(this); + DataGridView.OnColumnDataPropertyNameChanged(this); } } } @@ -293,12 +293,12 @@ public override DataGridViewCellStyle DefaultCellStyle private bool ShouldSerializeDefaultCellStyle() { - if (!this.HasDefaultCellStyle) + if (!HasDefaultCellStyle) { return false; } - DataGridViewCellStyle defaultCellStyle = this.DefaultCellStyle; + DataGridViewCellStyle defaultCellStyle = DefaultCellStyle; return (!defaultCellStyle.BackColor.IsEmpty || !defaultCellStyle.ForeColor.IsEmpty || @@ -319,11 +319,11 @@ internal int DesiredFillWidth { get { - return this.desiredFillWidth; + return desiredFillWidth; } set { - this.desiredFillWidth = value; + desiredFillWidth = value; } } @@ -331,11 +331,11 @@ internal int DesiredMinimumWidth { get { - return this.desiredMinimumWidth; + return desiredMinimumWidth; } set { - this.desiredMinimumWidth = value; + desiredMinimumWidth = value; } } @@ -347,11 +347,11 @@ public int DisplayIndex { get { - return this.displayIndex; + return displayIndex; } set { - if (this.displayIndex != value) + if (displayIndex != value) { if (value == int.MaxValue) { @@ -363,24 +363,24 @@ public int DisplayIndex { throw new ArgumentOutOfRangeException(nameof(value), value, SR.DataGridViewColumn_DisplayIndexNegative); } - if (value >= this.DataGridView.Columns.Count) + if (value >= DataGridView.Columns.Count) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.DataGridViewColumn_DisplayIndexExceedsColumnCount); } // Will throw an error if a visible frozen column is placed inside a non-frozen area or vice-versa. - this.DataGridView.OnColumnDisplayIndexChanging(this, value); - this.displayIndex = value; + DataGridView.OnColumnDisplayIndexChanging(this, value); + displayIndex = value; try { - this.DataGridView.InDisplayIndexAdjustments = true; - this.DataGridView.OnColumnDisplayIndexChanged_PreNotification(); - this.DataGridView.OnColumnDisplayIndexChanged(this); - this.DataGridView.OnColumnDisplayIndexChanged_PostNotification(); + DataGridView.InDisplayIndexAdjustments = true; + DataGridView.OnColumnDisplayIndexChanged_PreNotification(); + DataGridView.OnColumnDisplayIndexChanged(this); + DataGridView.OnColumnDisplayIndexChanged_PostNotification(); } finally { - this.DataGridView.InDisplayIndexAdjustments = false; + DataGridView.InDisplayIndexAdjustments = false; } } else @@ -389,7 +389,7 @@ public int DisplayIndex { throw new ArgumentOutOfRangeException(nameof(DisplayIndex), value, string.Format(SR.DataGridViewColumn_DisplayIndexTooNegative)); } - this.displayIndex = value; + displayIndex = value; } } } @@ -399,17 +399,17 @@ internal bool DisplayIndexHasChanged { get { - return (this.flags & DATAGRIDVIEWCOLUMN_displayIndexHasChangedInternal) != 0; + return (flags & DATAGRIDVIEWCOLUMN_displayIndexHasChangedInternal) != 0; } set { if (value) { - this.flags |= (byte)DATAGRIDVIEWCOLUMN_displayIndexHasChangedInternal; + flags |= (byte)DATAGRIDVIEWCOLUMN_displayIndexHasChangedInternal; } else { - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOLUMN_displayIndexHasChangedInternal); + flags = (byte)(flags & ~DATAGRIDVIEWCOLUMN_displayIndexHasChangedInternal); } } } @@ -421,7 +421,7 @@ internal int DisplayIndexInternal Debug.Assert(value >= -1); Debug.Assert(value < int.MaxValue); - this.displayIndex = value; + displayIndex = value; } } @@ -431,8 +431,8 @@ internal int DisplayIndexInternal ] public event EventHandler Disposed { - add => this.disposed += value; - remove => this.disposed -= value; + add => disposed += value; + remove => disposed -= value; } [ @@ -444,11 +444,11 @@ public int DividerWidth { get { - return this.DividerThickness; + return DividerThickness; } set { - this.DividerThickness = value; + DividerThickness = value; } } @@ -461,7 +461,7 @@ public float FillWeight { get { - return this.fillWeight; + return fillWeight; } set { @@ -473,15 +473,15 @@ public float FillWeight { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidHighBoundArgumentEx, nameof(FillWeight), value, ushort.MaxValue)); } - if (this.DataGridView != null) + if (DataGridView != null) { - this.DataGridView.OnColumnFillWeightChanging(this, value); - this.fillWeight = value; - this.DataGridView.OnColumnFillWeightChanged(this); + DataGridView.OnColumnFillWeightChanging(this, value); + fillWeight = value; + DataGridView.OnColumnFillWeightChanged(this); } else { - this.fillWeight = value; + fillWeight = value; } } } @@ -491,7 +491,7 @@ internal float FillWeightInternal set { Debug.Assert(value > 0); - this.fillWeight = value; + fillWeight = value; } } @@ -538,9 +538,9 @@ public string HeaderText { get { - if (this.HasHeaderCell) + if (HasHeaderCell) { - string headerValue = this.HeaderCell.Value as string; + string headerValue = HeaderCell.Value as string; if (headerValue != null) { return headerValue; @@ -557,18 +557,18 @@ public string HeaderText } set { - if ((value != null || this.HasHeaderCell) && - this.HeaderCell.ValueType != null && - this.HeaderCell.ValueType.IsAssignableFrom(typeof(string))) + if ((value != null || HasHeaderCell) && + HeaderCell.ValueType != null && + HeaderCell.ValueType.IsAssignableFrom(typeof(string))) { - this.HeaderCell.Value = value; + HeaderCell.Value = value; } } } private bool ShouldSerializeHeaderText() { - return this.HasHeaderCell && ((DataGridViewColumnHeaderCell)this.HeaderCell).ContainsLocalValue; + return HasHeaderCell && ((DataGridViewColumnHeaderCell)HeaderCell).ContainsLocalValue; } [ @@ -580,7 +580,7 @@ public DataGridViewAutoSizeColumnMode InheritedAutoSizeMode { get { - return GetInheritedAutoSizeMode(this.DataGridView); + return GetInheritedAutoSizeMode(DataGridView); } } @@ -592,20 +592,20 @@ public override DataGridViewCellStyle InheritedStyle get { DataGridViewCellStyle columnStyle = null; - Debug.Assert(this.Index > -1); - if (this.HasDefaultCellStyle) + Debug.Assert(Index > -1); + if (HasDefaultCellStyle) { - columnStyle = this.DefaultCellStyle; + columnStyle = DefaultCellStyle; Debug.Assert(columnStyle != null); } - if (this.DataGridView == null) + if (DataGridView == null) { return columnStyle; } DataGridViewCellStyle inheritedCellStyleTmp = new DataGridViewCellStyle(); - DataGridViewCellStyle dataGridViewStyle = this.DataGridView.DefaultCellStyle; + DataGridViewCellStyle dataGridViewStyle = DataGridView.DefaultCellStyle; Debug.Assert(dataGridViewStyle != null); if (columnStyle != null && !columnStyle.BackColor.IsEmpty) @@ -735,17 +735,17 @@ internal bool IsBrowsableInternal { get { - return (this.flags & DATAGRIDVIEWCOLUMN_isBrowsableInternal) != 0; + return (flags & DATAGRIDVIEWCOLUMN_isBrowsableInternal) != 0; } set { if (value) { - this.flags |= (byte)DATAGRIDVIEWCOLUMN_isBrowsableInternal; + flags |= (byte)DATAGRIDVIEWCOLUMN_isBrowsableInternal; } else { - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOLUMN_isBrowsableInternal); + flags = (byte)(flags & ~DATAGRIDVIEWCOLUMN_isBrowsableInternal); } } } @@ -758,7 +758,7 @@ public bool IsDataBound { get { - return this.IsDataBoundInternal; + return IsDataBoundInternal; } } @@ -766,17 +766,17 @@ internal bool IsDataBoundInternal { get { - return (this.flags & DATAGRIDVIEWCOLUMN_isDataBound) != 0; + return (flags & DATAGRIDVIEWCOLUMN_isDataBound) != 0; } set { if (value) { - this.flags |= (byte)DATAGRIDVIEWCOLUMN_isDataBound; + flags |= (byte)DATAGRIDVIEWCOLUMN_isDataBound; } else { - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOLUMN_isDataBound); + flags = (byte)(flags & ~DATAGRIDVIEWCOLUMN_isDataBound); } } } @@ -792,11 +792,11 @@ public int MinimumWidth { get { - return this.MinimumThickness; + return MinimumThickness; } set { - this.MinimumThickness = value; + MinimumThickness = value; } } @@ -825,28 +825,28 @@ public string Name // I talked w/ MarkRi and he is perfectly fine w/ DataGridViewColumn::Name changing w/o ColumnNameChanged // being fired. // - if (this.Site != null && !string.IsNullOrEmpty(this.Site.Name)) + if (Site != null && !string.IsNullOrEmpty(Site.Name)) { - this.name = this.Site.Name; + name = Site.Name; } return name; } set { - string oldName = this.name; + string oldName = name; if (string.IsNullOrEmpty(value)) { - this.name = string.Empty; + name = string.Empty; } else { - this.name = value; + name = value; } - if (this.DataGridView != null && !string.Equals(this.name, oldName, StringComparison.Ordinal)) + if (DataGridView != null && !string.Equals(name, oldName, StringComparison.Ordinal)) { - this.DataGridView.OnColumnNameChanged(this); + DataGridView.OnColumnNameChanged(this); } } } @@ -863,11 +863,11 @@ public override bool ReadOnly } set { - if (this.IsDataBound && - this.DataGridView != null && - this.DataGridView.DataConnection != null && - this.boundColumnIndex != -1 && - this.DataGridView.DataConnection.DataFieldIsReadOnly(this.boundColumnIndex) && + if (IsDataBound && + DataGridView != null && + DataGridView.DataConnection != null && + boundColumnIndex != -1 && + DataGridView.DataConnection.DataFieldIsReadOnly(boundColumnIndex) && !value) { throw new InvalidOperationException(string.Format(SR.DataGridView_ColumnBoundToAReadOnlyFieldMustRemainReadOnly)); @@ -900,11 +900,11 @@ public ISite Site { get { - return this.site; + return site; } set { - this.site = value; + site = value; } } @@ -917,11 +917,11 @@ public DataGridViewColumnSortMode SortMode { get { - if ((this.flags & DATAGRIDVIEWCOLUMN_automaticSort) != 0x00) + if ((flags & DATAGRIDVIEWCOLUMN_automaticSort) != 0x00) { return DataGridViewColumnSortMode.Automatic; } - else if ((this.flags & DATAGRIDVIEWCOLUMN_programmaticSort) != 0x00) + else if ((flags & DATAGRIDVIEWCOLUMN_programmaticSort) != 0x00) { return DataGridViewColumnSortMode.Programmatic; } @@ -932,37 +932,37 @@ public DataGridViewColumnSortMode SortMode } set { - if (value != this.SortMode) + if (value != SortMode) { if (value != DataGridViewColumnSortMode.NotSortable) { - if (this.DataGridView != null && - !this.DataGridView.InInitialization && + if (DataGridView != null && + !DataGridView.InInitialization && value == DataGridViewColumnSortMode.Automatic && - (this.DataGridView.SelectionMode == DataGridViewSelectionMode.FullColumnSelect || - this.DataGridView.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect)) + (DataGridView.SelectionMode == DataGridViewSelectionMode.FullColumnSelect || + DataGridView.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect)) { - throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_SortModeAndSelectionModeClash, (value).ToString(), this.DataGridView.SelectionMode.ToString())); + throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_SortModeAndSelectionModeClash, (value).ToString(), DataGridView.SelectionMode.ToString())); } if (value == DataGridViewColumnSortMode.Automatic) { - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOLUMN_programmaticSort); - this.flags |= (byte)DATAGRIDVIEWCOLUMN_automaticSort; + flags = (byte)(flags & ~DATAGRIDVIEWCOLUMN_programmaticSort); + flags |= (byte)DATAGRIDVIEWCOLUMN_automaticSort; } else { - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOLUMN_automaticSort); - this.flags |= (byte)DATAGRIDVIEWCOLUMN_programmaticSort; + flags = (byte)(flags & ~DATAGRIDVIEWCOLUMN_automaticSort); + flags |= (byte)DATAGRIDVIEWCOLUMN_programmaticSort; } } else { - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOLUMN_automaticSort); - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOLUMN_programmaticSort); + flags = (byte)(flags & ~DATAGRIDVIEWCOLUMN_automaticSort); + flags = (byte)(flags & ~DATAGRIDVIEWCOLUMN_programmaticSort); } - if (this.DataGridView != null) + if (DataGridView != null) { - this.DataGridView.OnColumnSortModeChanged(this); + DataGridView.OnColumnSortModeChanged(this); } } } @@ -978,17 +978,17 @@ public string ToolTipText { get { - return this.HeaderCell.ToolTipText; + return HeaderCell.ToolTipText; } set { - if (string.Compare(this.ToolTipText, value, false /*ignore case*/, CultureInfo.InvariantCulture) != 0) + if (string.Compare(ToolTipText, value, false /*ignore case*/, CultureInfo.InvariantCulture) != 0) { - this.HeaderCell.ToolTipText = value; + HeaderCell.ToolTipText = value; - if (this.DataGridView != null) + if (DataGridView != null) { - this.DataGridView.OnColumnToolTipTextChanged(this); + DataGridView.OnColumnToolTipTextChanged(this); } } } @@ -998,12 +998,12 @@ internal float UsedFillWeight { get { - return this.usedFillWeight; + return usedFillWeight; } set { Debug.Assert(value > 0); - this.usedFillWeight = value; + usedFillWeight = value; } } @@ -1016,12 +1016,12 @@ public Type ValueType { get { - return (Type)this.Properties.GetObject(PropDataGridViewColumnValueType); + return (Type)Properties.GetObject(PropDataGridViewColumnValueType); } set { // what should we do when we modify the ValueType in the dataGridView column??? - this.Properties.SetObject(PropDataGridViewColumnValueType, value); + Properties.SetObject(PropDataGridViewColumnValueType, value); } } @@ -1053,11 +1053,11 @@ public int Width { get { - return this.Thickness; + return Thickness; } set { - this.Thickness = value; + Thickness = value; } } @@ -1065,7 +1065,7 @@ public override object Clone() { // - DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)System.Activator.CreateInstance(this.GetType()); + DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)System.Activator.CreateInstance(GetType()); if (dataGridViewColumn != null) { CloneInternal(dataGridViewColumn); @@ -1077,29 +1077,29 @@ internal void CloneInternal(DataGridViewColumn dataGridViewColumn) { base.CloneInternal(dataGridViewColumn); - dataGridViewColumn.name = this.Name; + dataGridViewColumn.name = Name; dataGridViewColumn.displayIndex = -1; - dataGridViewColumn.HeaderText = this.HeaderText; - dataGridViewColumn.DataPropertyName = this.DataPropertyName; + dataGridViewColumn.HeaderText = HeaderText; + dataGridViewColumn.DataPropertyName = DataPropertyName; // dataGridViewColumn.boundColumnConverter = columnTemplate.BoundColumnConverter; setting the DataPropertyName should also set the bound column converter later on. if (dataGridViewColumn.CellTemplate != null) { - dataGridViewColumn.cellTemplate = (DataGridViewCell)this.CellTemplate.Clone(); + dataGridViewColumn.cellTemplate = (DataGridViewCell)CellTemplate.Clone(); } else { dataGridViewColumn.cellTemplate = null; } - if (this.HasHeaderCell) + if (HasHeaderCell) { - dataGridViewColumn.HeaderCell = (DataGridViewColumnHeaderCell)this.HeaderCell.Clone(); + dataGridViewColumn.HeaderCell = (DataGridViewColumnHeaderCell)HeaderCell.Clone(); } - dataGridViewColumn.AutoSizeMode = this.AutoSizeMode; - dataGridViewColumn.SortMode = this.SortMode; - dataGridViewColumn.FillWeightInternal = this.FillWeight; + dataGridViewColumn.AutoSizeMode = AutoSizeMode; + dataGridViewColumn.SortMode = SortMode; + dataGridViewColumn.FillWeightInternal = FillWeight; } protected override void Dispose(bool disposing) @@ -1111,14 +1111,14 @@ protected override void Dispose(bool disposing) // lock (this) { - if (this.site != null && this.site.Container != null) + if (site != null && site.Container != null) { - this.site.Container.Remove(this); + site.Container.Remove(this); } - if (this.disposed != null) + if (disposed != null) { - this.disposed(this, EventArgs.Empty); + disposed(this, EventArgs.Empty); } } } @@ -1131,7 +1131,7 @@ protected override void Dispose(bool disposing) internal DataGridViewAutoSizeColumnMode GetInheritedAutoSizeMode(DataGridView dataGridView) { - if (dataGridView != null && this.autoSizeMode == DataGridViewAutoSizeColumnMode.NotSet) + if (dataGridView != null && autoSizeMode == DataGridViewAutoSizeColumnMode.NotSet) { switch (dataGridView.AutoSizeColumnsMode) { @@ -1157,7 +1157,7 @@ internal DataGridViewAutoSizeColumnMode GetInheritedAutoSizeMode(DataGridView da return DataGridViewAutoSizeColumnMode.None; } } - return this.autoSizeMode; + return autoSizeMode; } public virtual int GetPreferredWidth(DataGridViewAutoSizeColumnMode autoSizeColumnMode, bool fixedHeight) @@ -1183,9 +1183,9 @@ public virtual int GetPreferredWidth(DataGridViewAutoSizeColumnMode autoSizeColu throw new InvalidEnumArgumentException(nameof(autoSizeColumnMode), (int)autoSizeColumnMode, typeof(DataGridViewAutoSizeColumnMode)); } - DataGridView dataGridView = this.DataGridView; + DataGridView dataGridView = DataGridView; - Debug.Assert(dataGridView == null || this.Index > -1); + Debug.Assert(dataGridView == null || Index > -1); if (dataGridView == null) { @@ -1209,11 +1209,11 @@ public virtual int GetPreferredWidth(DataGridViewAutoSizeColumnMode autoSizeColu { if (fixedHeight) { - preferredCellThickness = this.HeaderCell.GetPreferredWidth(-1, dataGridView.ColumnHeadersHeight); + preferredCellThickness = HeaderCell.GetPreferredWidth(-1, dataGridView.ColumnHeadersHeight); } else { - preferredCellThickness = this.HeaderCell.GetPreferredSize(-1).Width; + preferredCellThickness = HeaderCell.GetPreferredSize(-1).Width; } if (preferredColumnThickness < preferredCellThickness) { @@ -1229,11 +1229,11 @@ public virtual int GetPreferredWidth(DataGridViewAutoSizeColumnMode autoSizeColu dataGridViewRow = dataGridView.Rows.SharedRow(rowIndex); if (fixedHeight) { - preferredCellThickness = dataGridViewRow.Cells[this.Index].GetPreferredWidth(rowIndex, dataGridViewRow.Thickness); + preferredCellThickness = dataGridViewRow.Cells[Index].GetPreferredWidth(rowIndex, dataGridViewRow.Thickness); } else { - preferredCellThickness = dataGridViewRow.Cells[this.Index].GetPreferredSize(rowIndex).Width; + preferredCellThickness = dataGridViewRow.Cells[Index].GetPreferredSize(rowIndex).Width; } if (preferredColumnThickness < preferredCellThickness) { @@ -1252,11 +1252,11 @@ public virtual int GetPreferredWidth(DataGridViewAutoSizeColumnMode autoSizeColu dataGridViewRow = dataGridView.Rows.SharedRow(rowIndex); if (fixedHeight) { - preferredCellThickness = dataGridViewRow.Cells[this.Index].GetPreferredWidth(rowIndex, dataGridViewRow.Thickness); + preferredCellThickness = dataGridViewRow.Cells[Index].GetPreferredWidth(rowIndex, dataGridViewRow.Thickness); } else { - preferredCellThickness = dataGridViewRow.Cells[this.Index].GetPreferredSize(rowIndex).Width; + preferredCellThickness = dataGridViewRow.Cells[Index].GetPreferredSize(rowIndex).Width; } if (preferredColumnThickness < preferredCellThickness) { @@ -1275,11 +1275,11 @@ public virtual int GetPreferredWidth(DataGridViewAutoSizeColumnMode autoSizeColu dataGridViewRow = dataGridView.Rows.SharedRow(rowIndex); if (fixedHeight) { - preferredCellThickness = dataGridViewRow.Cells[this.Index].GetPreferredWidth(rowIndex, dataGridViewRow.Thickness); + preferredCellThickness = dataGridViewRow.Cells[Index].GetPreferredWidth(rowIndex, dataGridViewRow.Thickness); } else { - preferredCellThickness = dataGridViewRow.Cells[this.Index].GetPreferredSize(rowIndex).Width; + preferredCellThickness = dataGridViewRow.Cells[Index].GetPreferredSize(rowIndex).Width; } if (preferredColumnThickness < preferredCellThickness) { @@ -1297,9 +1297,9 @@ public override string ToString() { StringBuilder sb = new StringBuilder(64); sb.Append("DataGridViewColumn { Name="); - sb.Append(this.Name); + sb.Append(Name); sb.Append(", Index="); - sb.Append(this.Index.ToString(CultureInfo.CurrentCulture)); + sb.Append(Index.ToString(CultureInfo.CurrentCulture)); sb.Append(" }"); return sb.ToString(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs index 2c9010aff3a..f15037b6946 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs @@ -54,37 +54,37 @@ object IList.this[int index] int IList.Add(object value) { - return this.Add((DataGridViewColumn)value); + return Add((DataGridViewColumn)value); } void IList.Clear() { - this.Clear(); + Clear(); } bool IList.Contains(object value) { - return this.items.Contains(value); + return items.Contains(value); } int IList.IndexOf(object value) { - return this.items.IndexOf(value); + return items.IndexOf(value); } void IList.Insert(int index, object value) { - this.Insert(index, (DataGridViewColumn)value); + Insert(index, (DataGridViewColumn)value); } void IList.Remove(object value) { - this.Remove((DataGridViewColumn)value); + Remove((DataGridViewColumn)value); } void IList.RemoveAt(int index) { - this.RemoveAt(index); + RemoveAt(index); } @@ -94,7 +94,7 @@ int ICollection.Count { get { - return this.items.Count; + return items.Count; } } @@ -116,7 +116,7 @@ object ICollection.SyncRoot void ICollection.CopyTo(Array array, int index) { - this.items.CopyTo(array, index); + items.CopyTo(array, index); } @@ -124,7 +124,7 @@ void ICollection.CopyTo(Array array, int index) IEnumerator IEnumerable.GetEnumerator() { - return this.items.GetEnumerator(); + return items.GetEnumerator(); } @@ -147,7 +147,7 @@ protected override ArrayList List { get { - return this.items; + return items; } } @@ -155,7 +155,7 @@ protected DataGridView DataGridView { get { - return this.dataGridView; + return dataGridView; } } @@ -166,7 +166,7 @@ public DataGridViewColumn this[int index] { get { - return (DataGridViewColumn)this.items[index]; + return (DataGridViewColumn)items[index]; } } @@ -181,10 +181,10 @@ public DataGridViewColumn this[string columnName] { throw new ArgumentNullException(nameof(columnName)); } - int itemCount = this.items.Count; + int itemCount = items.Count; for (int i = 0; i < itemCount; ++i) { - DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.items[i]; + DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)items[i]; // NOTE: case-insensitive if (string.Equals(dataGridViewColumn.Name, columnName, StringComparison.OrdinalIgnoreCase)) { @@ -197,8 +197,8 @@ public DataGridViewColumn this[string columnName] public event CollectionChangeEventHandler CollectionChanged { - add => this.onCollectionChanged += value; - remove => this.onCollectionChanged -= value; + add => onCollectionChanged += value; + remove => onCollectionChanged -= value; } internal int ActualDisplayIndexToColumnIndex(int actualDisplayIndex, DataGridViewElementStates includeFilter) @@ -230,28 +230,28 @@ public virtual int Add(string columnName, string headerText) /// public virtual int Add(DataGridViewColumn dataGridViewColumn) { - Debug.Assert(this.DataGridView != null); - if (this.DataGridView.NoDimensionChangeAllowed) + Debug.Assert(DataGridView != null); + if (DataGridView.NoDimensionChangeAllowed) { throw new InvalidOperationException(string.Format(SR.DataGridView_ForbiddenOperationInEventHandler)); } - if (this.DataGridView.InDisplayIndexAdjustments) + if (DataGridView.InDisplayIndexAdjustments) { // We are within columns display indexes adjustments. We do not allow changing the column collection while adjusting display indexes. throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAlterDisplayIndexWithinAdjustments)); } - this.DataGridView.OnAddingColumn(dataGridViewColumn); // will throw an exception if the addition is illegal + DataGridView.OnAddingColumn(dataGridViewColumn); // will throw an exception if the addition is illegal InvalidateCachedColumnsOrder(); - int index = this.items.Add(dataGridViewColumn); + int index = items.Add(dataGridViewColumn); dataGridViewColumn.IndexInternal = index; dataGridViewColumn.DataGridViewInternal = dataGridView; UpdateColumnCaches(dataGridViewColumn, true); - this.DataGridView.OnAddedColumn(dataGridViewColumn); + DataGridView.OnAddedColumn(dataGridViewColumn); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, dataGridViewColumn), false /*changeIsInsertion*/, new Point(-1, -1)); #if DEBUG - Debug.Assert(this.itemsSorted == null || VerifyColumnOrderCache()); + Debug.Assert(itemsSorted == null || VerifyColumnOrderCache()); #endif return index; } @@ -263,12 +263,12 @@ public virtual void AddRange(params DataGridViewColumn[] dataGridViewColumns) throw new ArgumentNullException(nameof(dataGridViewColumns)); } - Debug.Assert(this.DataGridView != null); - if (this.DataGridView.NoDimensionChangeAllowed) + Debug.Assert(DataGridView != null); + if (DataGridView.NoDimensionChangeAllowed) { throw new InvalidOperationException(string.Format(SR.DataGridView_ForbiddenOperationInEventHandler)); } - if (this.DataGridView.InDisplayIndexAdjustments) + if (DataGridView.InDisplayIndexAdjustments) { // We are within columns display indexes adjustments. We do not allow changing the column collection while adjusting display indexes. throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAlterDisplayIndexWithinAdjustments)); @@ -328,39 +328,39 @@ public virtual void AddRange(params DataGridViewColumn[] dataGridViewColumns) index++; } - this.DataGridView.OnAddingColumns(dataGridViewColumns); // will throw an exception if the addition is illegal + DataGridView.OnAddingColumns(dataGridViewColumns); // will throw an exception if the addition is illegal foreach (DataGridViewColumn dataGridViewColumn in dataGridViewColumns) { InvalidateCachedColumnsOrder(); - index = this.items.Add(dataGridViewColumn); + index = items.Add(dataGridViewColumn); dataGridViewColumn.IndexInternal = index; dataGridViewColumn.DataGridViewInternal = dataGridView; UpdateColumnCaches(dataGridViewColumn, true); - this.DataGridView.OnAddedColumn(dataGridViewColumn); + DataGridView.OnAddedColumn(dataGridViewColumn); } OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null), false /*changeIsInsertion*/, new Point(-1, -1)); #if DEBUG - Debug.Assert(this.itemsSorted == null || VerifyColumnOrderCache()); + Debug.Assert(itemsSorted == null || VerifyColumnOrderCache()); #endif } public virtual void Clear() { - if (this.Count > 0) + if (Count > 0) { - if (this.DataGridView.NoDimensionChangeAllowed) + if (DataGridView.NoDimensionChangeAllowed) { throw new InvalidOperationException(string.Format(SR.DataGridView_ForbiddenOperationInEventHandler)); } - if (this.DataGridView.InDisplayIndexAdjustments) + if (DataGridView.InDisplayIndexAdjustments) { // We are within columns display indexes adjustments. We do not allow changing the column collection while adjusting display indexes. throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAlterDisplayIndexWithinAdjustments)); } - for (int columnIndex = 0; columnIndex < this.Count; columnIndex++) + for (int columnIndex = 0; columnIndex < Count; columnIndex++) { DataGridViewColumn dataGridViewColumn = this[columnIndex]; // Detach the column... @@ -372,22 +372,22 @@ public virtual void Clear() } } - DataGridViewColumn[] aColumns = new DataGridViewColumn[this.items.Count]; + DataGridViewColumn[] aColumns = new DataGridViewColumn[items.Count]; CopyTo(aColumns, 0); - this.DataGridView.OnClearingColumns(); + DataGridView.OnClearingColumns(); InvalidateCachedColumnsOrder(); - this.items.Clear(); + items.Clear(); InvalidateCachedColumnCounts(); InvalidateCachedColumnsWidths(); foreach (DataGridViewColumn dataGridViewColumn in aColumns) { - this.DataGridView.OnColumnRemoved(dataGridViewColumn); - this.DataGridView.OnColumnHidden(dataGridViewColumn); + DataGridView.OnColumnRemoved(dataGridViewColumn); + DataGridView.OnColumnHidden(dataGridViewColumn); } OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null), false /*changeIsInsertion*/, new Point(-1, -1)); #if DEBUG - Debug.Assert(this.itemsSorted == null || VerifyColumnOrderCache()); + Debug.Assert(itemsSorted == null || VerifyColumnOrderCache()); #endif } } @@ -410,7 +410,7 @@ internal int ColumnIndexToActualDisplayIndex(int columnIndex, DataGridViewElemen /// public virtual bool Contains(DataGridViewColumn dataGridViewColumn) { - return this.items.IndexOf(dataGridViewColumn) != -1; + return items.IndexOf(dataGridViewColumn) != -1; } public virtual bool Contains(string columnName) @@ -419,10 +419,10 @@ public virtual bool Contains(string columnName) { throw new ArgumentNullException(nameof(columnName)); } - int itemCount = this.items.Count; + int itemCount = items.Count; for (int i = 0; i < itemCount; ++i) { - DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.items[i]; + DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)items[i]; // NOTE: case-insensitive if (0 == string.Compare(dataGridViewColumn.Name, columnName, true, CultureInfo.InvariantCulture)) { @@ -434,31 +434,31 @@ public virtual bool Contains(string columnName) public void CopyTo(DataGridViewColumn[] array, int index) { - this.items.CopyTo(array, index); + items.CopyTo(array, index); } internal bool DisplayInOrder(int columnIndex1, int columnIndex2) { - int displayIndex1 = ((DataGridViewColumn)this.items[columnIndex1]).DisplayIndex; - int displayIndex2 = ((DataGridViewColumn)this.items[columnIndex2]).DisplayIndex; + int displayIndex1 = ((DataGridViewColumn)items[columnIndex1]).DisplayIndex; + int displayIndex2 = ((DataGridViewColumn)items[columnIndex2]).DisplayIndex; return displayIndex1 < displayIndex2; } internal DataGridViewColumn GetColumnAtDisplayIndex(int displayIndex) { - if (displayIndex < 0 || displayIndex >= this.items.Count) + if (displayIndex < 0 || displayIndex >= items.Count) { return null; } - DataGridViewColumn dataGridViewColumn = ((DataGridViewColumn)this.items[displayIndex]); + DataGridViewColumn dataGridViewColumn = ((DataGridViewColumn)items[displayIndex]); if (dataGridViewColumn.DisplayIndex == displayIndex) { // Performance gain if display indexes coincide with indexes. return dataGridViewColumn; } - for (int columnIndex = 0; columnIndex < this.items.Count; columnIndex++) + for (int columnIndex = 0; columnIndex < items.Count; columnIndex++) { - dataGridViewColumn = ((DataGridViewColumn)this.items[columnIndex]); + dataGridViewColumn = ((DataGridViewColumn)items[columnIndex]); if (dataGridViewColumn.DisplayIndex == displayIndex) { return dataGridViewColumn; @@ -481,15 +481,15 @@ public int GetColumnCount(DataGridViewElementStates includeFilter) switch (includeFilter) { case DataGridViewElementStates.Visible: - if (this.columnCountsVisible != -1) + if (columnCountsVisible != -1) { - return this.columnCountsVisible; + return columnCountsVisible; } break; case DataGridViewElementStates.Visible | DataGridViewElementStates.Selected: - if (this.columnCountsVisibleSelected != -1) + if (columnCountsVisibleSelected != -1) { - return this.columnCountsVisibleSelected; + return columnCountsVisibleSelected; } break; } @@ -497,9 +497,9 @@ public int GetColumnCount(DataGridViewElementStates includeFilter) int columnCount = 0; if ((includeFilter & DataGridViewElementStates.Resizable) == 0) { - for (int columnIndex = 0; columnIndex < this.items.Count; columnIndex++) + for (int columnIndex = 0; columnIndex < items.Count; columnIndex++) { - if (((DataGridViewColumn)this.items[columnIndex]).StateIncludes(includeFilter)) + if (((DataGridViewColumn)items[columnIndex]).StateIncludes(includeFilter)) { columnCount++; } @@ -507,20 +507,20 @@ public int GetColumnCount(DataGridViewElementStates includeFilter) switch (includeFilter) { case DataGridViewElementStates.Visible: - this.columnCountsVisible = columnCount; + columnCountsVisible = columnCount; break; case DataGridViewElementStates.Visible | DataGridViewElementStates.Selected: - this.columnCountsVisibleSelected = columnCount; + columnCountsVisibleSelected = columnCount; break; } } else { DataGridViewElementStates correctedIncludeFilter = includeFilter & ~DataGridViewElementStates.Resizable; - for (int columnIndex = 0; columnIndex < this.items.Count; columnIndex++) + for (int columnIndex = 0; columnIndex < items.Count; columnIndex++) { - if (((DataGridViewColumn)this.items[columnIndex]).StateIncludes(correctedIncludeFilter) && - ((DataGridViewColumn)this.items[columnIndex]).Resizable == DataGridViewTriState.True) + if (((DataGridViewColumn)items[columnIndex]).StateIncludes(correctedIncludeFilter) && + ((DataGridViewColumn)items[columnIndex]).Resizable == DataGridViewTriState.True) { columnCount++; } @@ -535,12 +535,12 @@ internal int GetColumnCount(DataGridViewElementStates includeFilter, int fromCol DataGridViewElementStates.ReadOnly | DataGridViewElementStates.Selected | DataGridViewElementStates.Visible)) == 0); Debug.Assert((includeFilter & DataGridViewElementStates.Resizable) == 0); Debug.Assert(DisplayInOrder(fromColumnIndex, toColumnIndex)); - Debug.Assert(((DataGridViewColumn)this.items[toColumnIndex]).StateIncludes(includeFilter)); + Debug.Assert(((DataGridViewColumn)items[toColumnIndex]).StateIncludes(includeFilter)); int jumpColumns = 0; - DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.items[fromColumnIndex]; + DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)items[fromColumnIndex]; - while (dataGridViewColumn != (DataGridViewColumn)this.items[toColumnIndex]) + while (dataGridViewColumn != (DataGridViewColumn)items[toColumnIndex]) { dataGridViewColumn = GetNextColumn(dataGridViewColumn, includeFilter, DataGridViewElementStates.None); @@ -556,25 +556,25 @@ internal int GetColumnCount(DataGridViewElementStates includeFilter, int fromCol private int GetColumnSortedIndex(DataGridViewColumn dataGridViewColumn) { Debug.Assert(dataGridViewColumn != null); - Debug.Assert(this.itemsSorted != null); - Debug.Assert(this.lastAccessedSortedIndex == -1 || - this.lastAccessedSortedIndex < this.Count); + Debug.Assert(itemsSorted != null); + Debug.Assert(lastAccessedSortedIndex == -1 || + lastAccessedSortedIndex < Count); #if DEBUG Debug.Assert(VerifyColumnOrderCache()); #endif - if (this.lastAccessedSortedIndex != -1 && - this.itemsSorted[this.lastAccessedSortedIndex] == dataGridViewColumn) + if (lastAccessedSortedIndex != -1 && + itemsSorted[lastAccessedSortedIndex] == dataGridViewColumn) { - return this.lastAccessedSortedIndex; + return lastAccessedSortedIndex; } int index = 0; - while (index < this.itemsSorted.Count) + while (index < itemsSorted.Count) { - if (dataGridViewColumn.Index == ((DataGridViewColumn)this.itemsSorted[index]).Index) + if (dataGridViewColumn.Index == ((DataGridViewColumn)itemsSorted[index]).Index) { - this.lastAccessedSortedIndex = index; + lastAccessedSortedIndex = index; return index; } index++; @@ -588,11 +588,11 @@ internal float GetColumnsFillWeight(DataGridViewElementStates includeFilter) DataGridViewElementStates.ReadOnly | DataGridViewElementStates.Selected | DataGridViewElementStates.Visible)) == 0); float weightSum = 0F; - for (int columnIndex = 0; columnIndex < this.items.Count; columnIndex++) + for (int columnIndex = 0; columnIndex < items.Count; columnIndex++) { - if (((DataGridViewColumn)this.items[columnIndex]).StateIncludes(includeFilter)) + if (((DataGridViewColumn)items[columnIndex]).StateIncludes(includeFilter)) { - weightSum += ((DataGridViewColumn)this.items[columnIndex]).FillWeight; + weightSum += ((DataGridViewColumn)items[columnIndex]).FillWeight; } } return weightSum; @@ -611,35 +611,35 @@ public int GetColumnsWidth(DataGridViewElementStates includeFilter) switch (includeFilter) { case DataGridViewElementStates.Visible: - if (this.columnsWidthVisible != -1) + if (columnsWidthVisible != -1) { - return this.columnsWidthVisible; + return columnsWidthVisible; } break; case DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen: - if (this.columnsWidthVisibleFrozen != -1) + if (columnsWidthVisibleFrozen != -1) { - return this.columnsWidthVisibleFrozen; + return columnsWidthVisibleFrozen; } break; } int columnsWidth = 0; - for (int columnIndex = 0; columnIndex < this.items.Count; columnIndex++) + for (int columnIndex = 0; columnIndex < items.Count; columnIndex++) { - if (((DataGridViewColumn)this.items[columnIndex]).StateIncludes(includeFilter)) + if (((DataGridViewColumn)items[columnIndex]).StateIncludes(includeFilter)) { - columnsWidth += ((DataGridViewColumn)this.items[columnIndex]).Thickness; + columnsWidth += ((DataGridViewColumn)items[columnIndex]).Thickness; } } switch (includeFilter) { case DataGridViewElementStates.Visible: - this.columnsWidthVisible = columnsWidth; + columnsWidthVisible = columnsWidth; break; case DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen: - this.columnsWidthVisibleFrozen = columnsWidth; + columnsWidthVisibleFrozen = columnsWidth; break; } return columnsWidth; @@ -653,7 +653,7 @@ public DataGridViewColumn GetFirstColumn(DataGridViewElementStates includeFilter throw new ArgumentException(string.Format(SR.DataGridView_InvalidDataGridViewElementStateCombination, nameof(includeFilter))); } - if (this.itemsSorted == null) + if (itemsSorted == null) { UpdateColumnOrderCache(); } @@ -661,12 +661,12 @@ public DataGridViewColumn GetFirstColumn(DataGridViewElementStates includeFilter Debug.Assert(VerifyColumnOrderCache()); #endif int index = 0; - while (index < this.itemsSorted.Count) + while (index < itemsSorted.Count) { - DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.itemsSorted[index]; + DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)itemsSorted[index]; if (dataGridViewColumn.StateIncludes(includeFilter)) { - this.lastAccessedSortedIndex = index; + lastAccessedSortedIndex = index; return dataGridViewColumn; } index++; @@ -692,7 +692,7 @@ public DataGridViewColumn GetFirstColumn(DataGridViewElementStates includeFilter throw new ArgumentException(string.Format(SR.DataGridView_InvalidDataGridViewElementStateCombination, nameof(excludeFilter))); } - if (this.itemsSorted == null) + if (itemsSorted == null) { UpdateColumnOrderCache(); } @@ -700,13 +700,13 @@ public DataGridViewColumn GetFirstColumn(DataGridViewElementStates includeFilter Debug.Assert(VerifyColumnOrderCache()); #endif int index = 0; - while (index < this.itemsSorted.Count) + while (index < itemsSorted.Count) { - DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.itemsSorted[index]; + DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)itemsSorted[index]; if (dataGridViewColumn.StateIncludes(includeFilter) && dataGridViewColumn.StateExcludes(excludeFilter)) { - this.lastAccessedSortedIndex = index; + lastAccessedSortedIndex = index; return dataGridViewColumn; } index++; @@ -728,21 +728,21 @@ public DataGridViewColumn GetLastColumn(DataGridViewElementStates includeFilter, throw new ArgumentException(string.Format(SR.DataGridView_InvalidDataGridViewElementStateCombination, nameof(excludeFilter))); } - if (this.itemsSorted == null) + if (itemsSorted == null) { UpdateColumnOrderCache(); } #if DEBUG Debug.Assert(VerifyColumnOrderCache()); #endif - int index = this.itemsSorted.Count - 1; + int index = itemsSorted.Count - 1; while (index >= 0) { - DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.itemsSorted[index]; + DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)itemsSorted[index]; if (dataGridViewColumn.StateIncludes(includeFilter) && dataGridViewColumn.StateExcludes(excludeFilter)) { - this.lastAccessedSortedIndex = index; + lastAccessedSortedIndex = index; return dataGridViewColumn; } index--; @@ -769,7 +769,7 @@ public DataGridViewColumn GetNextColumn(DataGridViewColumn dataGridViewColumnSta throw new ArgumentException(string.Format(SR.DataGridView_InvalidDataGridViewElementStateCombination, nameof(excludeFilter))); } - if (this.itemsSorted == null) + if (itemsSorted == null) { UpdateColumnOrderCache(); } @@ -781,9 +781,9 @@ public DataGridViewColumn GetNextColumn(DataGridViewColumn dataGridViewColumnSta { bool columnFound = false; int indexMin = int.MaxValue, displayIndexMin = int.MaxValue; - for (index = 0; index < this.items.Count; index++) + for (index = 0; index < items.Count; index++) { - DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.items[index]; + DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)items[index]; if (dataGridViewColumn.StateIncludes(includeFilter) && dataGridViewColumn.StateExcludes(excludeFilter) && (dataGridViewColumn.DisplayIndex > dataGridViewColumnStart.DisplayIndex || @@ -800,18 +800,18 @@ public DataGridViewColumn GetNextColumn(DataGridViewColumn dataGridViewColumnSta } } } - return columnFound ? ((DataGridViewColumn)this.items[indexMin]) : null; + return columnFound ? ((DataGridViewColumn)items[indexMin]) : null; } else { index++; - while (index < this.itemsSorted.Count) + while (index < itemsSorted.Count) { - DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.itemsSorted[index]; + DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)itemsSorted[index]; if (dataGridViewColumn.StateIncludes(includeFilter) && dataGridViewColumn.StateExcludes(excludeFilter)) { - this.lastAccessedSortedIndex = index; + lastAccessedSortedIndex = index; return dataGridViewColumn; } @@ -840,7 +840,7 @@ public DataGridViewColumn GetPreviousColumn(DataGridViewColumn dataGridViewColum throw new ArgumentException(string.Format(SR.DataGridView_InvalidDataGridViewElementStateCombination, nameof(excludeFilter))); } - if (this.itemsSorted == null) + if (itemsSorted == null) { UpdateColumnOrderCache(); } @@ -852,9 +852,9 @@ public DataGridViewColumn GetPreviousColumn(DataGridViewColumn dataGridViewColum { bool columnFound = false; int indexMax = -1, displayIndexMax = -1; - for (index = 0; index < this.items.Count; index++) + for (index = 0; index < items.Count; index++) { - DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.items[index]; + DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)items[index]; if (dataGridViewColumn.StateIncludes(includeFilter) && dataGridViewColumn.StateExcludes(excludeFilter) && (dataGridViewColumn.DisplayIndex < dataGridViewColumnStart.DisplayIndex || @@ -871,18 +871,18 @@ public DataGridViewColumn GetPreviousColumn(DataGridViewColumn dataGridViewColum } } } - return columnFound ? ((DataGridViewColumn)this.items[indexMax]) : null; + return columnFound ? ((DataGridViewColumn)items[indexMax]) : null; } else { index--; while (index >= 0) { - DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.itemsSorted[index]; + DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)itemsSorted[index]; if (dataGridViewColumn.StateIncludes(includeFilter) && dataGridViewColumn.StateExcludes(excludeFilter)) { - this.lastAccessedSortedIndex = index; + lastAccessedSortedIndex = index; return dataGridViewColumn; } index--; @@ -893,7 +893,7 @@ public DataGridViewColumn GetPreviousColumn(DataGridViewColumn dataGridViewColum public int IndexOf(DataGridViewColumn dataGridViewColumn) { - return this.items.IndexOf(dataGridViewColumn); + return items.IndexOf(dataGridViewColumn); } /// @@ -901,12 +901,12 @@ public int IndexOf(DataGridViewColumn dataGridViewColumn) /// public virtual void Insert(int columnIndex, DataGridViewColumn dataGridViewColumn) { - Debug.Assert(this.DataGridView != null); - if (this.DataGridView.NoDimensionChangeAllowed) + Debug.Assert(DataGridView != null); + if (DataGridView.NoDimensionChangeAllowed) { throw new InvalidOperationException(string.Format(SR.DataGridView_ForbiddenOperationInEventHandler)); } - if (this.DataGridView.InDisplayIndexAdjustments) + if (DataGridView.InDisplayIndexAdjustments) { // We are within columns display indexes adjustments. We do not allow changing the column collection while adjusting display indexes. throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAlterDisplayIndexWithinAdjustments)); @@ -923,21 +923,21 @@ public virtual void Insert(int columnIndex, DataGridViewColumn dataGridViewColum Point newCurrentCell; try { - this.DataGridView.OnInsertingColumn(columnIndex, dataGridViewColumn, out newCurrentCell); // will throw an exception if the insertion is illegal + DataGridView.OnInsertingColumn(columnIndex, dataGridViewColumn, out newCurrentCell); // will throw an exception if the insertion is illegal } finally { dataGridViewColumn.DisplayIndexInternal = originalDisplayIndex; } InvalidateCachedColumnsOrder(); - this.items.Insert(columnIndex, dataGridViewColumn); + items.Insert(columnIndex, dataGridViewColumn); dataGridViewColumn.IndexInternal = columnIndex; dataGridViewColumn.DataGridViewInternal = dataGridView; UpdateColumnCaches(dataGridViewColumn, true); - this.DataGridView.OnInsertedColumn_PreNotification(dataGridViewColumn); + DataGridView.OnInsertedColumn_PreNotification(dataGridViewColumn); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, dataGridViewColumn), true /*changeIsInsertion*/, newCurrentCell); #if DEBUG - Debug.Assert(this.itemsSorted == null || VerifyColumnOrderCache()); + Debug.Assert(itemsSorted == null || VerifyColumnOrderCache()); #endif } @@ -956,18 +956,18 @@ internal void InvalidateCachedColumnCount(DataGridViewElementStates includeFilte } else if (includeFilter == DataGridViewElementStates.Selected) { - this.columnCountsVisibleSelected = -1; + columnCountsVisibleSelected = -1; } } internal void InvalidateCachedColumnCounts() { - this.columnCountsVisible = this.columnCountsVisibleSelected = -1; + columnCountsVisible = columnCountsVisibleSelected = -1; } internal void InvalidateCachedColumnsOrder() { - this.itemsSorted = null; + itemsSorted = null; } internal void InvalidateCachedColumnsWidth(DataGridViewElementStates includeFilter) @@ -985,20 +985,20 @@ internal void InvalidateCachedColumnsWidth(DataGridViewElementStates includeFilt } else if (includeFilter == DataGridViewElementStates.Frozen) { - this.columnsWidthVisibleFrozen = -1; + columnsWidthVisibleFrozen = -1; } } internal void InvalidateCachedColumnsWidths() { - this.columnsWidthVisible = this.columnsWidthVisibleFrozen = -1; + columnsWidthVisible = columnsWidthVisibleFrozen = -1; } protected virtual void OnCollectionChanged(CollectionChangeEventArgs e) { - if (this.onCollectionChanged != null) + if (onCollectionChanged != null) { - this.onCollectionChanged(this, e); + onCollectionChanged(this, e); } } @@ -1014,24 +1014,24 @@ private void OnCollectionChanged(CollectionChangeEventArgs ccea, bool changeIsIn private void OnCollectionChanged_PreNotification(CollectionChangeEventArgs ccea) { - Debug.Assert(this.DataGridView != null); - this.DataGridView.OnColumnCollectionChanged_PreNotification(ccea); + Debug.Assert(DataGridView != null); + DataGridView.OnColumnCollectionChanged_PreNotification(ccea); } private void OnCollectionChanged_PostNotification(CollectionChangeEventArgs ccea, bool changeIsInsertion, Point newCurrentCell) { - Debug.Assert(this.DataGridView != null); + Debug.Assert(DataGridView != null); DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)ccea.Element; if (ccea.Action == CollectionChangeAction.Add && changeIsInsertion) { - this.DataGridView.OnInsertedColumn_PostNotification(newCurrentCell); + DataGridView.OnInsertedColumn_PostNotification(newCurrentCell); } else if (ccea.Action == CollectionChangeAction.Remove) { - this.DataGridView.OnRemovedColumn_PostNotification(dataGridViewColumn, newCurrentCell); + DataGridView.OnRemovedColumn_PostNotification(dataGridViewColumn, newCurrentCell); } - this.DataGridView.OnColumnCollectionChanged_PostNotification(dataGridViewColumn); + DataGridView.OnColumnCollectionChanged_PostNotification(dataGridViewColumn); } [ @@ -1044,19 +1044,19 @@ public virtual void Remove(DataGridViewColumn dataGridViewColumn) throw new ArgumentNullException(nameof(dataGridViewColumn)); } - if (dataGridViewColumn.DataGridView != this.DataGridView) + if (dataGridViewColumn.DataGridView != DataGridView) { throw new ArgumentException(string.Format(SR.DataGridView_ColumnDoesNotBelongToDataGridView), "dataGridViewColumn"); } - int itemsCount = this.items.Count; + int itemsCount = items.Count; for (int i = 0; i < itemsCount; ++i) { - if (this.items[i] == dataGridViewColumn) + if (items[i] == dataGridViewColumn) { RemoveAt(i); #if DEBUG - Debug.Assert(this.itemsSorted == null || VerifyColumnOrderCache()); + Debug.Assert(itemsSorted == null || VerifyColumnOrderCache()); #endif return; } @@ -1072,10 +1072,10 @@ public virtual void Remove(string columnName) throw new ArgumentNullException(nameof(columnName)); } - int itemsCount = this.items.Count; + int itemsCount = items.Count; for (int i = 0; i < itemsCount; ++i) { - DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.items[i]; + DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)items[i]; // NOTE: case-insensitive if (0 == string.Compare(dataGridViewColumn.Name, columnName, true, CultureInfo.InvariantCulture)) { @@ -1089,17 +1089,17 @@ public virtual void Remove(string columnName) public virtual void RemoveAt(int index) { - if (index < 0 || index >= this.Count) + if (index < 0 || index >= Count) { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - if (this.DataGridView.NoDimensionChangeAllowed) + if (DataGridView.NoDimensionChangeAllowed) { throw new InvalidOperationException(SR.DataGridView_ForbiddenOperationInEventHandler); } - if (this.DataGridView.InDisplayIndexAdjustments) + if (DataGridView.InDisplayIndexAdjustments) { // We are within columns display indexes adjustments. We do not allow changing the column collection while adjusting display indexes. throw new InvalidOperationException(SR.DataGridView_CannotAlterDisplayIndexWithinAdjustments); @@ -1107,7 +1107,7 @@ public virtual void RemoveAt(int index) RemoveAtInternal(index, false /*force*/); #if DEBUG - Debug.Assert(this.itemsSorted == null || VerifyColumnOrderCache()); + Debug.Assert(itemsSorted == null || VerifyColumnOrderCache()); #endif } @@ -1115,63 +1115,63 @@ internal void RemoveAtInternal(int index, bool force) { // If force is true, the underlying data is gone and can't be accessed anymore. - Debug.Assert(index >= 0 && index < this.Count); - Debug.Assert(this.DataGridView != null); - Debug.Assert(!this.DataGridView.NoDimensionChangeAllowed); - Debug.Assert(!this.DataGridView.InDisplayIndexAdjustments); + Debug.Assert(index >= 0 && index < Count); + Debug.Assert(DataGridView != null); + Debug.Assert(!DataGridView.NoDimensionChangeAllowed); + Debug.Assert(!DataGridView.InDisplayIndexAdjustments); - DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)this.items[index]; + DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)items[index]; Point newCurrentCell; - this.DataGridView.OnRemovingColumn(dataGridViewColumn, out newCurrentCell, force); + DataGridView.OnRemovingColumn(dataGridViewColumn, out newCurrentCell, force); InvalidateCachedColumnsOrder(); - this.items.RemoveAt(index); + items.RemoveAt(index); dataGridViewColumn.DataGridViewInternal = null; UpdateColumnCaches(dataGridViewColumn, false); - this.DataGridView.OnRemovedColumn_PreNotification(dataGridViewColumn); + DataGridView.OnRemovedColumn_PreNotification(dataGridViewColumn); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, dataGridViewColumn), false /*changeIsInsertion*/, newCurrentCell); } private void UpdateColumnCaches(DataGridViewColumn dataGridViewColumn, bool adding) { - if (this.columnCountsVisible != -1 || this.columnCountsVisibleSelected != -1 || - this.columnsWidthVisible != -1 || this.columnsWidthVisibleFrozen != -1) + if (columnCountsVisible != -1 || columnCountsVisibleSelected != -1 || + columnsWidthVisible != -1 || columnsWidthVisibleFrozen != -1) { DataGridViewElementStates columnStates = dataGridViewColumn.State; if ((columnStates & DataGridViewElementStates.Visible) != 0) { int columnCountIncrement = adding ? 1 : -1; int columnWidthIncrement = 0; - if (this.columnsWidthVisible != -1 || - (this.columnsWidthVisibleFrozen != -1 && + if (columnsWidthVisible != -1 || + (columnsWidthVisibleFrozen != -1 && ((columnStates & (DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)) == (DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)))) { columnWidthIncrement = adding ? dataGridViewColumn.Width : -dataGridViewColumn.Width; } - if (this.columnCountsVisible != -1) + if (columnCountsVisible != -1) { - this.columnCountsVisible += columnCountIncrement; + columnCountsVisible += columnCountIncrement; } - if (this.columnsWidthVisible != -1) + if (columnsWidthVisible != -1) { Debug.Assert(columnWidthIncrement != 0); - this.columnsWidthVisible += columnWidthIncrement; + columnsWidthVisible += columnWidthIncrement; } if ((columnStates & (DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)) == (DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)) { - if (this.columnsWidthVisibleFrozen != -1) + if (columnsWidthVisibleFrozen != -1) { Debug.Assert(columnWidthIncrement != 0); - this.columnsWidthVisibleFrozen += columnWidthIncrement; + columnsWidthVisibleFrozen += columnWidthIncrement; } } if ((columnStates & (DataGridViewElementStates.Visible | DataGridViewElementStates.Selected)) == (DataGridViewElementStates.Visible | DataGridViewElementStates.Selected)) { - if (this.columnCountsVisibleSelected != -1) + if (columnCountsVisibleSelected != -1) { - this.columnCountsVisibleSelected += columnCountIncrement; + columnCountsVisibleSelected += columnCountIncrement; } } } @@ -1180,15 +1180,15 @@ private void UpdateColumnCaches(DataGridViewColumn dataGridViewColumn, bool addi private void UpdateColumnOrderCache() { - this.itemsSorted = (ArrayList)this.items.Clone(); - this.itemsSorted.Sort(columnOrderComparer); - this.lastAccessedSortedIndex = -1; + itemsSorted = (ArrayList)items.Clone(); + itemsSorted.Sort(columnOrderComparer); + lastAccessedSortedIndex = -1; } #if DEBUG internal bool VerifyColumnDisplayIndexes() { - for (int columnDisplayIndex = 0; columnDisplayIndex < this.items.Count; columnDisplayIndex++) + for (int columnDisplayIndex = 0; columnDisplayIndex < items.Count; columnDisplayIndex++) { if (GetColumnAtDisplayIndex(columnDisplayIndex) == null) { @@ -1200,16 +1200,16 @@ internal bool VerifyColumnDisplayIndexes() private bool VerifyColumnOrderCache() { - if (this.itemsSorted == null) + if (itemsSorted == null) return false; - if (this.itemsSorted.Count != this.items.Count) + if (itemsSorted.Count != items.Count) return false; int index = 0; - while (index < this.itemsSorted.Count - 1) + while (index < itemsSorted.Count - 1) { - if (((DataGridViewColumn)this.itemsSorted[index + 1]).DisplayIndex != - ((DataGridViewColumn)this.itemsSorted[index]).DisplayIndex + 1) + if (((DataGridViewColumn)itemsSorted[index + 1]).DisplayIndex != + ((DataGridViewColumn)itemsSorted[index]).DisplayIndex + 1) return false; index++; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnDesignTimeVisibleAttribute.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnDesignTimeVisibleAttribute.cs index 3664eed4bd0..8574d11af75 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnDesignTimeVisibleAttribute.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnDesignTimeVisibleAttribute.cs @@ -64,7 +64,7 @@ public override int GetHashCode() public override bool IsDefaultAttribute() { - return (this.Visible == Default.Visible); + return (Visible == Default.Visible); } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnHeaderCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnHeaderCell.cs index 0eff3c11e3b..b7376ad5331 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnHeaderCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnHeaderCell.cs @@ -54,15 +54,15 @@ public DataGridViewColumnHeaderCell() } isScalingInitialized = true; } - - this.sortGlyphDirection = SortOrder.None; + + sortGlyphDirection = SortOrder.None; } internal bool ContainsLocalValue { get { - return this.Properties.ContainsObject(PropCellValue); + return Properties.ContainsObject(PropCellValue); } } @@ -71,7 +71,7 @@ public SortOrder SortGlyphDirection { get { - return this.sortGlyphDirection; + return sortGlyphDirection; } set { @@ -80,18 +80,18 @@ public SortOrder SortGlyphDirection { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(SortOrder)); } - if (this.OwningColumn == null || this.DataGridView == null) + if (OwningColumn == null || DataGridView == null) { throw new InvalidOperationException(string.Format(SR.DataGridView_CellDoesNotYetBelongToDataGridView)); } - if (value != this.sortGlyphDirection) + if (value != sortGlyphDirection) { - if (this.OwningColumn.SortMode == DataGridViewColumnSortMode.NotSortable && value != SortOrder.None) + if (OwningColumn.SortMode == DataGridViewColumnSortMode.NotSortable && value != SortOrder.None) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumnHeaderCell_SortModeAndSortGlyphDirectionClash, (value).ToString())); } - this.sortGlyphDirection = value; - this.DataGridView.OnSortGlyphDirectionChanged(this); + sortGlyphDirection = value; + DataGridView.OnSortGlyphDirectionChanged(this); } } } @@ -101,14 +101,14 @@ internal SortOrder SortGlyphDirectionInternal set { Debug.Assert(value >= SortOrder.None && value <= SortOrder.Descending); - this.sortGlyphDirection = value; + sortGlyphDirection = value; } } public override object Clone() { DataGridViewColumnHeaderCell dataGridViewCell; - Type thisType = this.GetType(); + Type thisType = GetType(); if (thisType == cellType) //performance improvement { @@ -121,7 +121,7 @@ public override object Clone() dataGridViewCell = (DataGridViewColumnHeaderCell)System.Activator.CreateInstance(thisType); } base.CloneInternal(dataGridViewCell); - dataGridViewCell.Value = this.Value; + dataGridViewCell.Value = Value; return dataGridViewCell; } @@ -142,7 +142,7 @@ protected override object GetClipboardContent(int rowIndex, throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - if (this.DataGridView == null) + if (DataGridView == null) { return null; } @@ -231,7 +231,7 @@ protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCel throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - if (this.DataGridView == null || this.OwningColumn == null) + if (DataGridView == null || OwningColumn == null) { return Rectangle.Empty; } @@ -290,9 +290,9 @@ public override ContextMenuStrip GetInheritedContextMenuStrip(int rowIndex) return contextMenuStrip; } - if (this.DataGridView != null) + if (DataGridView != null) { - return this.DataGridView.ContextMenuStrip; + return DataGridView.ContextMenuStrip; } else { @@ -314,16 +314,16 @@ public override DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle in DataGridViewCellStyle inheritedCellStyleTmp = (inheritedCellStyle == null) ? new DataGridViewCellStyle() : inheritedCellStyle; DataGridViewCellStyle cellStyle = null; - if (this.HasStyle) + if (HasStyle) { - cellStyle = this.Style; + cellStyle = Style; Debug.Assert(cellStyle != null); } - DataGridViewCellStyle columnHeadersStyle = this.DataGridView.ColumnHeadersDefaultCellStyle; + DataGridViewCellStyle columnHeadersStyle = DataGridView.ColumnHeadersDefaultCellStyle; Debug.Assert(columnHeadersStyle != null); - DataGridViewCellStyle dataGridViewStyle = this.DataGridView.DefaultCellStyle; + DataGridViewCellStyle dataGridViewStyle = DataGridView.DefaultCellStyle; Debug.Assert(dataGridViewStyle != null); if (includeColors) @@ -510,7 +510,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - if (this.DataGridView == null) + if (DataGridView == null) { return new Size(-1, -1); } @@ -522,14 +522,14 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl DataGridViewFreeDimension freeDimension = DataGridViewCell.GetFreeDimensionFromConstraint(constraintSize); DataGridViewAdvancedBorderStyle dgvabsPlaceholder = new DataGridViewAdvancedBorderStyle(), dgvabsEffective; - dgvabsEffective = this.DataGridView.AdjustColumnHeaderBorderStyle(this.DataGridView.AdvancedColumnHeadersBorderStyle, + dgvabsEffective = DataGridView.AdjustColumnHeaderBorderStyle(DataGridView.AdvancedColumnHeadersBorderStyle, dgvabsPlaceholder, false /*isFirstDisplayedColumn*/, false /*isLastVisibleColumn*/); Rectangle borderWidthsRect = BorderWidths(dgvabsEffective); int borderAndPaddingWidths = borderWidthsRect.Left + borderWidthsRect.Width + cellStyle.Padding.Horizontal; int borderAndPaddingHeights = borderWidthsRect.Top + borderWidthsRect.Height + cellStyle.Padding.Vertical; - TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); + TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); Size preferredSize; // approximate preferred sizes @@ -562,8 +562,8 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl } } if (constraintSize.Height - borderAndPaddingHeights - 2 * DATAGRIDVIEWCOLUMNHEADERCELL_verticalMargin > sortGlyphHeight && - this.OwningColumn != null && - this.OwningColumn.SortMode != DataGridViewColumnSortMode.NotSortable) + OwningColumn != null && + OwningColumn.SortMode != DataGridViewColumnSortMode.NotSortable) { preferredSize.Width += sortGlyphWidth + 2 * sortGlyphHorizontalMargin; @@ -582,8 +582,8 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl preferredSize = new Size(0, 0); if (allowedWidth >= sortGlyphWidth + 2 * sortGlyphHorizontalMargin && - this.OwningColumn != null && - this.OwningColumn.SortMode != DataGridViewColumnSortMode.NotSortable) + OwningColumn != null && + OwningColumn.SortMode != DataGridViewColumnSortMode.NotSortable) { glyphSize = new Size(sortGlyphWidth + 2 * sortGlyphHorizontalMargin, sortGlyphHeight); @@ -658,8 +658,8 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl { preferredSize = new Size(0, 0); } - if (this.OwningColumn != null && - this.OwningColumn.SortMode != DataGridViewColumnSortMode.NotSortable) + if (OwningColumn != null && + OwningColumn.SortMode != DataGridViewColumnSortMode.NotSortable) { preferredSize.Width += sortGlyphWidth + 2 * sortGlyphHorizontalMargin; @@ -687,7 +687,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl { preferredSize.Height += 2 * DATAGRIDVIEWCOLUMNHEADERCELL_verticalMargin + borderAndPaddingHeights; } - if (this.DataGridView.ApplyVisualStylesToHeaderCells) + if (DataGridView.ApplyVisualStylesToHeaderCells) { Rectangle rectThemeMargins = DataGridViewHeaderCell.GetThemeMargins(graphics); if (freeDimension != DataGridViewFreeDimension.Height) @@ -708,15 +708,15 @@ protected override object GetValue(int rowIndex) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - if (this.ContainsLocalValue) + if (ContainsLocalValue) { - return this.Properties.GetObject(PropCellValue); + return Properties.GetObject(PropCellValue); } else { - if (this.OwningColumn != null) + if (OwningColumn != null) { - return this.OwningColumn.Name; + return OwningColumn.Name; } else { @@ -789,13 +789,13 @@ private Rectangle PaintPrivate(Graphics g, bool cellSelected = (dataGridViewElementState & DataGridViewElementStates.Selected) != 0; SolidBrush br; - if (this.DataGridView.ApplyVisualStylesToHeaderCells) + if (DataGridView.ApplyVisualStylesToHeaderCells) { if (cellStyle.Padding != Padding.Empty) { if (cellStyle.Padding != Padding.Empty) { - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { valBounds.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top); } @@ -813,17 +813,17 @@ private Rectangle PaintPrivate(Graphics g, int state = (int)HeaderItemState.Normal; // Set the state to Pressed/Hot only if the column can be sorted or selected - if (this.OwningColumn != null && this.OwningColumn.SortMode != DataGridViewColumnSortMode.NotSortable || - this.DataGridView.SelectionMode == DataGridViewSelectionMode.FullColumnSelect || - this.DataGridView.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) + if (OwningColumn != null && OwningColumn.SortMode != DataGridViewColumnSortMode.NotSortable || + DataGridView.SelectionMode == DataGridViewSelectionMode.FullColumnSelect || + DataGridView.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) { - if (this.ButtonState != ButtonState.Normal) + if (ButtonState != ButtonState.Normal) { - Debug.Assert(this.ButtonState == ButtonState.Pushed); + Debug.Assert(ButtonState == ButtonState.Pushed); state = (int)HeaderItemState.Pressed; } - else if (this.DataGridView.MouseEnteredCellAddress.Y == rowIndex && - this.DataGridView.MouseEnteredCellAddress.X == this.ColumnIndex) + else if (DataGridView.MouseEnteredCellAddress.Y == rowIndex && + DataGridView.MouseEnteredCellAddress.X == ColumnIndex) { state = (int)HeaderItemState.Hot; } @@ -840,15 +840,15 @@ private Rectangle PaintPrivate(Graphics g, // Even though Windows provides support for theming the sort glyph, // we rely on our own implementation for painting the sort glyph - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { // Flip the column header background - Bitmap bmFlipXPThemes = this.FlipXPThemesBitmap; + Bitmap bmFlipXPThemes = FlipXPThemesBitmap; if (bmFlipXPThemes == null || bmFlipXPThemes.Width < backgroundBounds.Width || bmFlipXPThemes.Width > 2 * backgroundBounds.Width || bmFlipXPThemes.Height < backgroundBounds.Height || bmFlipXPThemes.Height > 2 * backgroundBounds.Height) { - bmFlipXPThemes = this.FlipXPThemesBitmap = new Bitmap(backgroundBounds.Width, backgroundBounds.Height); + bmFlipXPThemes = FlipXPThemesBitmap = new Bitmap(backgroundBounds.Width, backgroundBounds.Height); } Graphics gFlip = Graphics.FromImage(bmFlipXPThemes); DataGridViewColumnHeaderCellRenderer.DrawHeader(gFlip, new Rectangle(0, 0, backgroundBounds.Width, backgroundBounds.Height), state); @@ -864,7 +864,7 @@ private Rectangle PaintPrivate(Graphics g, Rectangle rectThemeMargins = DataGridViewHeaderCell.GetThemeMargins(g); valBounds.Y += rectThemeMargins.Y; valBounds.Height -= rectThemeMargins.Y + rectThemeMargins.Height; - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { valBounds.X += rectThemeMargins.Width; valBounds.Width -= rectThemeMargins.X + rectThemeMargins.Width; @@ -879,7 +879,7 @@ private Rectangle PaintPrivate(Graphics g, { if (paint && DataGridViewCell.PaintBackground(paintParts) && backgroundBounds.Width > 0 && backgroundBounds.Height > 0) { - br = this.DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) || IsHighlighted() ? + br = DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) || IsHighlighted() ? cellStyle.SelectionBackColor : cellStyle.BackColor); if (br.Color.A == 255) { @@ -888,7 +888,7 @@ private Rectangle PaintPrivate(Graphics g, } if (cellStyle.Padding != Padding.Empty) { - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { valBounds.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top); } @@ -917,7 +917,7 @@ private Rectangle PaintPrivate(Graphics g, valBounds.Width -= DATAGRIDVIEWCOLUMNHEADERCELL_horizontalTextMarginLeft + DATAGRIDVIEWCOLUMNHEADERCELL_horizontalTextMarginRight; Color textColor; - if (this.DataGridView.ApplyVisualStylesToHeaderCells) + if (DataGridView.ApplyVisualStylesToHeaderCells) { textColor = DataGridViewColumnHeaderCellRenderer.VisualStyleRenderer.GetColor(ColorProperty.TextColor); } @@ -926,7 +926,7 @@ private Rectangle PaintPrivate(Graphics g, textColor = cellSelected ? cellStyle.SelectionForeColor : cellStyle.ForeColor; } - if (this.OwningColumn != null && this.OwningColumn.SortMode != DataGridViewColumnSortMode.NotSortable) + if (OwningColumn != null && OwningColumn.SortMode != DataGridViewColumnSortMode.NotSortable) { // Is there enough room to show the glyph? int width = valBounds.Width - @@ -936,14 +936,14 @@ private Rectangle PaintPrivate(Graphics g, if (width > 0) { bool widthTruncated; - int preferredHeight = DataGridViewCell.GetPreferredTextHeight(g, this.DataGridView.RightToLeftInternal, formattedValueStr, cellStyle, width, out widthTruncated); + int preferredHeight = DataGridViewCell.GetPreferredTextHeight(g, DataGridView.RightToLeftInternal, formattedValueStr, cellStyle, width, out widthTruncated); if (preferredHeight <= valBounds.Height && !widthTruncated) { - displaySortGlyph = (this.SortGlyphDirection != SortOrder.None); + displaySortGlyph = (SortGlyphDirection != SortOrder.None); valBounds.Width -= sortGlyphSeparatorWidth + sortGlyphWidth + 2 * sortGlyphHorizontalMargin; - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { valBounds.X += sortGlyphSeparatorWidth + sortGlyphWidth + @@ -968,7 +968,7 @@ private Rectangle PaintPrivate(Graphics g, } } } - TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); + TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); if (paint) { if (DataGridViewCell.PaintContentForeground(paintParts)) @@ -992,7 +992,7 @@ private Rectangle PaintPrivate(Graphics g, } else { - if (paint && this.SortGlyphDirection != SortOrder.None && + if (paint && SortGlyphDirection != SortOrder.None && valBounds.Width >= sortGlyphWidth + 2 * sortGlyphHorizontalMargin && valBounds.Height >= sortGlyphHeight) { @@ -1007,7 +1007,7 @@ private Rectangle PaintPrivate(Graphics g, Pen penControlDark = null, penControlLightLight = null; GetContrastedPens(cellStyle.BackColor, ref penControlDark, ref penControlLightLight); - if (this.SortGlyphDirection == SortOrder.Ascending) + if (SortGlyphDirection == SortOrder.Ascending) { switch (advancedBorderStyle.Right) { @@ -1091,7 +1091,7 @@ private Rectangle PaintPrivate(Graphics g, } else { - Debug.Assert(this.SortGlyphDirection == SortOrder.Descending); + Debug.Assert(SortGlyphDirection == SortOrder.Descending); switch (advancedBorderStyle.Right) { case DataGridViewAdvancedCellBorderStyle.OutsetPartial: @@ -1179,9 +1179,9 @@ private Rectangle PaintPrivate(Graphics g, private bool IsHighlighted() { - return this.DataGridView.SelectionMode == DataGridViewSelectionMode.FullRowSelect && - this.DataGridView.CurrentCell != null && this.DataGridView.CurrentCell.Selected && - this.DataGridView.CurrentCell.OwningColumn == this.OwningColumn; + return DataGridView.SelectionMode == DataGridViewSelectionMode.FullRowSelect && + DataGridView.CurrentCell != null && DataGridView.CurrentCell.Selected && + DataGridView.CurrentCell.OwningColumn == OwningColumn; } protected override bool SetValue(int rowIndex, object value) @@ -1192,10 +1192,10 @@ protected override bool SetValue(int rowIndex, object value) } object originalValue = GetValue(rowIndex); - this.Properties.SetObject(PropCellValue, value); - if (this.DataGridView != null && originalValue != value) + Properties.SetObject(PropCellValue, value); + if (DataGridView != null && originalValue != value) { - RaiseCellValueChanged(new DataGridViewCellEventArgs(this.ColumnIndex, -1)); + RaiseCellValueChanged(new DataGridViewCellEventArgs(ColumnIndex, -1)); } return true; } @@ -1205,7 +1205,7 @@ protected override bool SetValue(int rowIndex, object value) /// public override string ToString() { - return "DataGridViewColumnHeaderCell { ColumnIndex=" + this.ColumnIndex.ToString(CultureInfo.CurrentCulture) + " }"; + return "DataGridViewColumnHeaderCell { ColumnIndex=" + ColumnIndex.ToString(CultureInfo.CurrentCulture) + " }"; } private class DataGridViewColumnHeaderCellRenderer @@ -1257,7 +1257,7 @@ public override Rectangle Bounds { get { - return this.GetAccessibleObjectBounds(this.ParentPrivate); + return GetAccessibleObjectBounds(ParentPrivate); } } @@ -1265,14 +1265,14 @@ public override string DefaultAction { get { - if (this.Owner.OwningColumn != null) + if (Owner.OwningColumn != null) { - if (this.Owner.OwningColumn.SortMode == DataGridViewColumnSortMode.Automatic) + if (Owner.OwningColumn.SortMode == DataGridViewColumnSortMode.Automatic) { return string.Format(SR.DataGridView_AccColumnHeaderCellDefaultAction); } - else if (this.Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.FullColumnSelect || - this.Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) + else if (Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.FullColumnSelect || + Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) { return string.Format(SR.DataGridView_AccColumnHeaderCellSelectDefaultAction); } @@ -1292,9 +1292,9 @@ public override string Name { get { - if (this.Owner.OwningColumn != null) + if (Owner.OwningColumn != null) { - return this.Owner.OwningColumn.HeaderText; + return Owner.OwningColumn.HeaderText; } else { @@ -1307,7 +1307,7 @@ public override AccessibleObject Parent { get { - return this.ParentPrivate; + return ParentPrivate; } } @@ -1316,7 +1316,7 @@ private AccessibleObject ParentPrivate get { // return the top header row accessible object - return this.Owner.DataGridView.AccessibilityObject.GetChild(0); + return Owner.DataGridView.AccessibilityObject.GetChild(0); } } @@ -1341,10 +1341,10 @@ public override AccessibleStates State resultState |= AccessibleStates.Offscreen; } - if (this.Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.FullColumnSelect || - this.Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) + if (Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.FullColumnSelect || + Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) { - if (this.Owner.OwningColumn != null && this.Owner.OwningColumn.Selected) + if (Owner.OwningColumn != null && Owner.OwningColumn.Selected) { resultState |= AccessibleStates.Selected; } @@ -1358,13 +1358,13 @@ public override string Value { get { - return this.Name; + return Name; } } public override void DoDefaultAction() { - DataGridViewColumnHeaderCell dataGridViewCell = (DataGridViewColumnHeaderCell)this.Owner; + DataGridViewColumnHeaderCell dataGridViewCell = (DataGridViewColumnHeaderCell)Owner; DataGridView dataGridView = dataGridViewCell.DataGridView; if (dataGridViewCell.OwningColumn != null) @@ -1388,7 +1388,7 @@ public override void DoDefaultAction() public override AccessibleObject Navigate(AccessibleNavigation navigationDirection) { - if (this.Owner.OwningColumn == null) + if (Owner.OwningColumn == null) { return null; } @@ -1396,7 +1396,7 @@ public override AccessibleObject Navigate(AccessibleNavigation navigationDirecti switch (navigationDirection) { case AccessibleNavigation.Right: - if (this.Owner.DataGridView.RightToLeft == RightToLeft.No) + if (Owner.DataGridView.RightToLeft == RightToLeft.No) { return NavigateForward(); } @@ -1407,7 +1407,7 @@ public override AccessibleObject Navigate(AccessibleNavigation navigationDirecti case AccessibleNavigation.Next: return NavigateForward(); case AccessibleNavigation.Left: - if (this.Owner.DataGridView.RightToLeft == RightToLeft.No) + if (Owner.DataGridView.RightToLeft == RightToLeft.No) { return NavigateBackward(); } @@ -1419,10 +1419,10 @@ public override AccessibleObject Navigate(AccessibleNavigation navigationDirecti return NavigateBackward(); case AccessibleNavigation.FirstChild: // return the top left header cell accessible object - return this.Owner.DataGridView.AccessibilityObject.GetChild(0).GetChild(0); + return Owner.DataGridView.AccessibilityObject.GetChild(0).GetChild(0); case AccessibleNavigation.LastChild: // return the last column header cell in the top row header accessible object - AccessibleObject topRowHeaderAccessibleObject = this.Owner.DataGridView.AccessibilityObject.GetChild(0); + AccessibleObject topRowHeaderAccessibleObject = Owner.DataGridView.AccessibilityObject.GetChild(0); return topRowHeaderAccessibleObject.GetChild(topRowHeaderAccessibleObject.GetChildCount() - 1); default: return null; @@ -1431,12 +1431,12 @@ public override AccessibleObject Navigate(AccessibleNavigation navigationDirecti private AccessibleObject NavigateBackward() { - if (this.Owner.OwningColumn == this.Owner.DataGridView.Columns.GetFirstColumn(DataGridViewElementStates.Visible)) + if (Owner.OwningColumn == Owner.DataGridView.Columns.GetFirstColumn(DataGridViewElementStates.Visible)) { - if (this.Owner.DataGridView.RowHeadersVisible) + if (Owner.DataGridView.RowHeadersVisible) { // return the row header cell accessible object for the current row - return this.Parent.GetChild(0); + return Parent.GetChild(0); } else { @@ -1445,57 +1445,57 @@ private AccessibleObject NavigateBackward() } else { - int previousVisibleColumnIndex = this.Owner.DataGridView.Columns.GetPreviousColumn(this.Owner.OwningColumn, + int previousVisibleColumnIndex = Owner.DataGridView.Columns.GetPreviousColumn(Owner.OwningColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None).Index; - int actualDisplayIndex = this.Owner.DataGridView.Columns.ColumnIndexToActualDisplayIndex(previousVisibleColumnIndex, + int actualDisplayIndex = Owner.DataGridView.Columns.ColumnIndexToActualDisplayIndex(previousVisibleColumnIndex, DataGridViewElementStates.Visible); - if (this.Owner.DataGridView.RowHeadersVisible) + if (Owner.DataGridView.RowHeadersVisible) { - return this.Parent.GetChild(actualDisplayIndex + 1); + return Parent.GetChild(actualDisplayIndex + 1); } else { - return this.Parent.GetChild(actualDisplayIndex); + return Parent.GetChild(actualDisplayIndex); } } } private AccessibleObject NavigateForward() { - if (this.Owner.OwningColumn == this.Owner.DataGridView.Columns.GetLastColumn(DataGridViewElementStates.Visible, + if (Owner.OwningColumn == Owner.DataGridView.Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.None)) { return null; } else { - int nextVisibleColumnIndex = this.Owner.DataGridView.Columns.GetNextColumn(this.Owner.OwningColumn, + int nextVisibleColumnIndex = Owner.DataGridView.Columns.GetNextColumn(Owner.OwningColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None).Index; - int actualDisplayIndex = this.Owner.DataGridView.Columns.ColumnIndexToActualDisplayIndex(nextVisibleColumnIndex, + int actualDisplayIndex = Owner.DataGridView.Columns.ColumnIndexToActualDisplayIndex(nextVisibleColumnIndex, DataGridViewElementStates.Visible); - if (this.Owner.DataGridView.RowHeadersVisible) + if (Owner.DataGridView.RowHeadersVisible) { // + 1 because the top header row accessible object has the top left header cell accessible object at the beginning - return this.Parent.GetChild(actualDisplayIndex + 1); + return Parent.GetChild(actualDisplayIndex + 1); } else { - return this.Parent.GetChild(actualDisplayIndex); + return Parent.GetChild(actualDisplayIndex); } } } public override void Select(AccessibleSelection flags) { - if (this.Owner == null) + if (Owner == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet)); } - DataGridViewColumnHeaderCell dataGridViewCell = (DataGridViewColumnHeaderCell)this.Owner; + DataGridViewColumnHeaderCell dataGridViewCell = (DataGridViewColumnHeaderCell)Owner; DataGridView dataGridView = dataGridViewCell.DataGridView; if (dataGridView == null) @@ -1525,7 +1525,7 @@ public override void Select(AccessibleSelection flags) internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - if (this.Owner.OwningColumn == null) + if (Owner.OwningColumn == null) { return null; } @@ -1558,20 +1558,20 @@ internal override object GetPropertyValue(int propertyId) switch (propertyId) { case NativeMethods.UIA_NamePropertyId: - return this.Name; + return Name; case NativeMethods.UIA_ControlTypePropertyId: return NativeMethods.UIA_HeaderControlTypeId; case NativeMethods.UIA_IsEnabledPropertyId: return Owner.DataGridView.Enabled; case NativeMethods.UIA_HelpTextPropertyId: - return this.Help ?? string.Empty; + return Help ?? string.Empty; case NativeMethods.UIA_IsKeyboardFocusablePropertyId: - return (this.State & AccessibleStates.Focusable) == AccessibleStates.Focusable; + return (State & AccessibleStates.Focusable) == AccessibleStates.Focusable; case NativeMethods.UIA_HasKeyboardFocusPropertyId: case NativeMethods.UIA_IsPasswordPropertyId: return false; case NativeMethods.UIA_IsOffscreenPropertyId: - return (this.State & AccessibleStates.Offscreen) == AccessibleStates.Offscreen; + return (State & AccessibleStates.Offscreen) == AccessibleStates.Offscreen; case NativeMethods.UIA_AccessKeyPropertyId: return string.Empty; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs index ab4c4035841..1af61a2f59d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs @@ -76,7 +76,7 @@ public class DataGridViewComboBoxCell : DataGridViewCell public DataGridViewComboBoxCell() { - this.flags = DATAGRIDVIEWCOMBOBOXCELL_autoComplete; + flags = DATAGRIDVIEWCOMBOBOXCELL_autoComplete; if (!isScalingInitialized) { if (DpiHelper.IsScalingRequired) @@ -109,32 +109,32 @@ public virtual bool AutoComplete { get { - return ((this.flags & DATAGRIDVIEWCOMBOBOXCELL_autoComplete) != 0x00); + return ((flags & DATAGRIDVIEWCOMBOBOXCELL_autoComplete) != 0x00); } set { //CheckNoSharedCell(); - if (value != this.AutoComplete) + if (value != AutoComplete) { if (value) { - this.flags |= (byte)DATAGRIDVIEWCOMBOBOXCELL_autoComplete; + flags |= (byte)DATAGRIDVIEWCOMBOBOXCELL_autoComplete; } else { - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOMBOBOXCELL_autoComplete); + flags = (byte)(flags & ~DATAGRIDVIEWCOMBOBOXCELL_autoComplete); } - if (OwnsEditingComboBox(this.RowIndex)) + if (OwnsEditingComboBox(RowIndex)) { if (value) { - this.EditingComboBox.AutoCompleteSource = AutoCompleteSource.ListItems; - this.EditingComboBox.AutoCompleteMode = AutoCompleteMode.Append; + EditingComboBox.AutoCompleteSource = AutoCompleteSource.ListItems; + EditingComboBox.AutoCompleteMode = AutoCompleteMode.Append; } else { - this.EditingComboBox.AutoCompleteMode = AutoCompleteMode.None; - this.EditingComboBox.AutoCompleteSource = AutoCompleteSource.None; + EditingComboBox.AutoCompleteMode = AutoCompleteMode.None; + EditingComboBox.AutoCompleteSource = AutoCompleteSource.None; } } } @@ -145,13 +145,13 @@ private CurrencyManager DataManager { get { - return GetDataManager(this.DataGridView); + return GetDataManager(DataGridView); } set { - if (value != null || this.Properties.ContainsObject(PropComboBoxCellDataManager)) + if (value != null || Properties.ContainsObject(PropComboBoxCellDataManager)) { - this.Properties.SetObject(PropComboBoxCellDataManager, value); + Properties.SetObject(PropComboBoxCellDataManager, value); } } } @@ -160,7 +160,7 @@ public virtual object DataSource { get { - return this.Properties.GetObject(PropComboBoxCellDataSource); + return Properties.GetObject(PropComboBoxCellDataSource); } set { @@ -170,24 +170,24 @@ public virtual object DataSource { throw new ArgumentException(SR.BadDataSourceForComplexBinding); } - if (this.DataSource != value) + if (DataSource != value) { // Invalidate the currency manager - this.DataManager = null; + DataManager = null; UnwireDataSource(); - this.Properties.SetObject(PropComboBoxCellDataSource, value); + Properties.SetObject(PropComboBoxCellDataSource, value); WireDataSource(value); // Invalidate existing Items collection - this.CreateItemsFromDataSource = true; + CreateItemsFromDataSource = true; cachedDropDownWidth = -1; try { - InitializeDisplayMemberPropertyDescriptor(this.DisplayMember); + InitializeDisplayMemberPropertyDescriptor(DisplayMember); } catch (Exception exception) { @@ -195,13 +195,13 @@ public virtual object DataSource { throw; } - Debug.Assert(this.DisplayMember != null && this.DisplayMember.Length > 0); - this.DisplayMemberInternal = null; + Debug.Assert(DisplayMember != null && DisplayMember.Length > 0); + DisplayMemberInternal = null; } try { - InitializeValueMemberPropertyDescriptor(this.ValueMember); + InitializeValueMemberPropertyDescriptor(ValueMember); } catch (Exception exception) { @@ -209,19 +209,19 @@ public virtual object DataSource { throw; } - Debug.Assert(this.ValueMember != null && this.ValueMember.Length > 0); - this.ValueMemberInternal = null; + Debug.Assert(ValueMember != null && ValueMember.Length > 0); + ValueMemberInternal = null; } if (value == null) { - this.DisplayMemberInternal = null; - this.ValueMemberInternal = null; + DisplayMemberInternal = null; + ValueMemberInternal = null; } - if (OwnsEditingComboBox(this.RowIndex)) + if (OwnsEditingComboBox(RowIndex)) { - this.EditingComboBox.DataSource = value; + EditingComboBox.DataSource = value; InitializeComboBoxText(); } else @@ -237,7 +237,7 @@ public virtual string DisplayMember { get { - object displayMember = this.Properties.GetObject(PropComboBoxCellDisplayMember); + object displayMember = Properties.GetObject(PropComboBoxCellDisplayMember); if (displayMember == null) { return string.Empty; @@ -250,10 +250,10 @@ public virtual string DisplayMember set { //CheckNoSharedCell(); - this.DisplayMemberInternal = value; - if (OwnsEditingComboBox(this.RowIndex)) + DisplayMemberInternal = value; + if (OwnsEditingComboBox(RowIndex)) { - this.EditingComboBox.DisplayMember = value; + EditingComboBox.DisplayMember = value; InitializeComboBoxText(); } else @@ -268,9 +268,9 @@ private string DisplayMemberInternal set { InitializeDisplayMemberPropertyDescriptor(value); - if ((value != null && value.Length > 0) || this.Properties.ContainsObject(PropComboBoxCellDisplayMember)) + if ((value != null && value.Length > 0) || Properties.ContainsObject(PropComboBoxCellDisplayMember)) { - this.Properties.SetObject(PropComboBoxCellDisplayMember, value); + Properties.SetObject(PropComboBoxCellDisplayMember, value); } } } @@ -279,13 +279,13 @@ private PropertyDescriptor DisplayMemberProperty { get { - return (PropertyDescriptor)this.Properties.GetObject(PropComboBoxCellDisplayMemberProp); + return (PropertyDescriptor)Properties.GetObject(PropComboBoxCellDisplayMemberProp); } set { - if (value != null || this.Properties.ContainsObject(PropComboBoxCellDisplayMemberProp)) + if (value != null || Properties.ContainsObject(PropComboBoxCellDisplayMemberProp)) { - this.Properties.SetObject(PropComboBoxCellDisplayMemberProp, value); + Properties.SetObject(PropComboBoxCellDisplayMemberProp, value); } } } @@ -296,7 +296,7 @@ public DataGridViewComboBoxDisplayStyle DisplayStyle get { bool found; - int displayStyle = this.Properties.GetInteger(PropComboBoxCellDisplayStyle, out found); + int displayStyle = Properties.GetInteger(PropComboBoxCellDisplayStyle, out found); if (found) { return (DataGridViewComboBoxDisplayStyle)displayStyle; @@ -310,18 +310,18 @@ public DataGridViewComboBoxDisplayStyle DisplayStyle { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewComboBoxDisplayStyle)); } - if (value != this.DisplayStyle) + if (value != DisplayStyle) { - this.Properties.SetInteger(PropComboBoxCellDisplayStyle, (int)value); - if (this.DataGridView != null) + Properties.SetInteger(PropComboBoxCellDisplayStyle, (int)value); + if (DataGridView != null) { - if (this.RowIndex != -1) + if (RowIndex != -1) { - this.DataGridView.InvalidateCell(this); + DataGridView.InvalidateCell(this); } else { - this.DataGridView.InvalidateColumnInternal(this.ColumnIndex); + DataGridView.InvalidateColumnInternal(ColumnIndex); } } } @@ -333,9 +333,9 @@ internal DataGridViewComboBoxDisplayStyle DisplayStyleInternal set { Debug.Assert(value >= DataGridViewComboBoxDisplayStyle.ComboBox && value <= DataGridViewComboBoxDisplayStyle.Nothing); - if (value != this.DisplayStyle) + if (value != DisplayStyle) { - this.Properties.SetInteger(PropComboBoxCellDisplayStyle, (int)value); + Properties.SetInteger(PropComboBoxCellDisplayStyle, (int)value); } } } @@ -346,7 +346,7 @@ public bool DisplayStyleForCurrentCellOnly get { bool found; - int displayStyleForCurrentCellOnly = this.Properties.GetInteger(PropComboBoxCellDisplayStyleForCurrentCellOnly, out found); + int displayStyleForCurrentCellOnly = Properties.GetInteger(PropComboBoxCellDisplayStyleForCurrentCellOnly, out found); if (found) { return displayStyleForCurrentCellOnly == 0 ? false : true; @@ -355,18 +355,18 @@ public bool DisplayStyleForCurrentCellOnly } set { - if (value != this.DisplayStyleForCurrentCellOnly) + if (value != DisplayStyleForCurrentCellOnly) { - this.Properties.SetInteger(PropComboBoxCellDisplayStyleForCurrentCellOnly, value ? 1 : 0); - if (this.DataGridView != null) + Properties.SetInteger(PropComboBoxCellDisplayStyleForCurrentCellOnly, value ? 1 : 0); + if (DataGridView != null) { - if (this.RowIndex != -1) + if (RowIndex != -1) { - this.DataGridView.InvalidateCell(this); + DataGridView.InvalidateCell(this); } else { - this.DataGridView.InvalidateColumnInternal(this.ColumnIndex); + DataGridView.InvalidateColumnInternal(ColumnIndex); } } } @@ -377,9 +377,9 @@ internal bool DisplayStyleForCurrentCellOnlyInternal { set { - if (value != this.DisplayStyleForCurrentCellOnly) + if (value != DisplayStyleForCurrentCellOnly) { - this.Properties.SetInteger(PropComboBoxCellDisplayStyleForCurrentCellOnly, value ? 1 : 0); + Properties.SetInteger(PropComboBoxCellDisplayStyleForCurrentCellOnly, value ? 1 : 0); } } } @@ -388,13 +388,13 @@ private Type DisplayType { get { - if (this.DisplayMemberProperty != null) + if (DisplayMemberProperty != null) { - return this.DisplayMemberProperty.PropertyType; + return DisplayMemberProperty.PropertyType; } - else if (this.ValueMemberProperty != null) + else if (ValueMemberProperty != null) { - return this.ValueMemberProperty.PropertyType; + return ValueMemberProperty.PropertyType; } else { @@ -407,13 +407,13 @@ private TypeConverter DisplayTypeConverter { get { - if (this.DataGridView != null) + if (DataGridView != null) { - return this.DataGridView.GetCachedTypeConverter(this.DisplayType); + return DataGridView.GetCachedTypeConverter(DisplayType); } else { - return TypeDescriptor.GetConverter(this.DisplayType); + return TypeDescriptor.GetConverter(DisplayType); } } } @@ -424,7 +424,7 @@ public virtual int DropDownWidth get { bool found; - int dropDownWidth = this.Properties.GetInteger(PropComboBoxCellDropDownWidth, out found); + int dropDownWidth = Properties.GetInteger(PropComboBoxCellDropDownWidth, out found); return found ? dropDownWidth : 1; } set @@ -434,10 +434,10 @@ public virtual int DropDownWidth { throw new ArgumentOutOfRangeException(nameof(DropDownWidth), value, string.Format(SR.DataGridViewComboBoxCell_DropDownWidthOutOfRange, 1)); } - this.Properties.SetInteger(PropComboBoxCellDropDownWidth, (int)value); - if (OwnsEditingComboBox(this.RowIndex)) + Properties.SetInteger(PropComboBoxCellDropDownWidth, (int)value); + if (OwnsEditingComboBox(RowIndex)) { - this.EditingComboBox.DropDownWidth = value; + EditingComboBox.DropDownWidth = value; } } } @@ -446,13 +446,13 @@ private DataGridViewComboBoxEditingControl EditingComboBox { get { - return (DataGridViewComboBoxEditingControl)this.Properties.GetObject(PropComboBoxCellEditingComboBox); + return (DataGridViewComboBoxEditingControl)Properties.GetObject(PropComboBoxCellEditingComboBox); } set { - if (value != null || this.Properties.ContainsObject(PropComboBoxCellEditingComboBox)) + if (value != null || Properties.ContainsObject(PropComboBoxCellEditingComboBox)) { - this.Properties.SetObject(PropComboBoxCellEditingComboBox, value); + Properties.SetObject(PropComboBoxCellEditingComboBox, value); } } } @@ -471,7 +471,7 @@ public FlatStyle FlatStyle get { bool found; - int flatStyle = this.Properties.GetInteger(PropComboBoxCellFlatStyle, out found); + int flatStyle = Properties.GetInteger(PropComboBoxCellFlatStyle, out found); if (found) { return (FlatStyle)flatStyle; @@ -485,9 +485,9 @@ public FlatStyle FlatStyle { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(FlatStyle)); } - if (value != this.FlatStyle) + if (value != FlatStyle) { - this.Properties.SetInteger(PropComboBoxCellFlatStyle, (int)value); + Properties.SetInteger(PropComboBoxCellFlatStyle, (int)value); OnCommonChange(); } } @@ -498,9 +498,9 @@ internal FlatStyle FlatStyleInternal set { Debug.Assert(value >= FlatStyle.Flat && value <= FlatStyle.System); - if (value != this.FlatStyle) + if (value != FlatStyle) { - this.Properties.SetInteger(PropComboBoxCellFlatStyle, (int)value); + Properties.SetInteger(PropComboBoxCellFlatStyle, (int)value); } } } @@ -517,7 +517,7 @@ internal bool HasItems { get { - return this.Properties.ContainsObject(PropComboBoxCellItems) && this.Properties.GetObject(PropComboBoxCellItems) != null; + return Properties.ContainsObject(PropComboBoxCellItems) && Properties.GetObject(PropComboBoxCellItems) != null; } } @@ -526,7 +526,7 @@ public virtual ObjectCollection Items { get { - return GetItems(this.DataGridView); + return GetItems(DataGridView); } } @@ -536,7 +536,7 @@ public virtual int MaxDropDownItems get { bool found; - int maxDropDownItems = this.Properties.GetInteger(PropComboBoxCellMaxDropDownItems, out found); + int maxDropDownItems = Properties.GetInteger(PropComboBoxCellMaxDropDownItems, out found); if (found) { return maxDropDownItems; @@ -550,10 +550,10 @@ public virtual int MaxDropDownItems { throw new ArgumentOutOfRangeException(nameof(MaxDropDownItems), value, string.Format(SR.DataGridViewComboBoxCell_MaxDropDownItemsOutOfRange, 1, 100)); } - this.Properties.SetInteger(PropComboBoxCellMaxDropDownItems, (int)value); - if (OwnsEditingComboBox(this.RowIndex)) + Properties.SetInteger(PropComboBoxCellMaxDropDownItems, (int)value); + if (OwnsEditingComboBox(RowIndex)) { - this.EditingComboBox.MaxDropDownItems = value; + EditingComboBox.MaxDropDownItems = value; } } } @@ -562,8 +562,8 @@ private bool PaintXPThemes { get { - bool paintFlat = this.FlatStyle == FlatStyle.Flat || this.FlatStyle == FlatStyle.Popup; - return !paintFlat && this.DataGridView.ApplyVisualStylesToInnerCells; + bool paintFlat = FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup; + return !paintFlat && DataGridView.ApplyVisualStylesToInnerCells; } } @@ -580,32 +580,32 @@ public virtual bool Sorted { get { - return ((this.flags & DATAGRIDVIEWCOMBOBOXCELL_sorted) != 0x00); + return ((flags & DATAGRIDVIEWCOMBOBOXCELL_sorted) != 0x00); } set { //CheckNoSharedCell(); - if (value != this.Sorted) + if (value != Sorted) { if (value) { - if (this.DataSource == null) + if (DataSource == null) { - this.Items.SortInternal(); + Items.SortInternal(); } else { throw new ArgumentException(SR.ComboBoxSortWithDataSource); } - this.flags |= (byte)DATAGRIDVIEWCOMBOBOXCELL_sorted; + flags |= (byte)DATAGRIDVIEWCOMBOBOXCELL_sorted; } else { - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOMBOBOXCELL_sorted); + flags = (byte)(flags & ~DATAGRIDVIEWCOMBOBOXCELL_sorted); } - if (OwnsEditingComboBox(this.RowIndex)) + if (OwnsEditingComboBox(RowIndex)) { - this.EditingComboBox.Sorted = value; + EditingComboBox.Sorted = value; } } } @@ -615,11 +615,11 @@ internal DataGridViewComboBoxColumn TemplateComboBoxColumn { get { - return (DataGridViewComboBoxColumn)this.Properties.GetObject(PropComboBoxCellColumnTemplate); + return (DataGridViewComboBoxColumn)Properties.GetObject(PropComboBoxCellColumnTemplate); } set { - this.Properties.SetObject(PropComboBoxCellColumnTemplate, value); + Properties.SetObject(PropComboBoxCellColumnTemplate, value); } } @@ -628,7 +628,7 @@ public virtual string ValueMember { get { - object valueMember = this.Properties.GetObject(PropComboBoxCellValueMember); + object valueMember = Properties.GetObject(PropComboBoxCellValueMember); if (valueMember == null) { return string.Empty; @@ -641,10 +641,10 @@ public virtual string ValueMember set { //CheckNoSharedCell(); - this.ValueMemberInternal = value; - if (OwnsEditingComboBox(this.RowIndex)) + ValueMemberInternal = value; + if (OwnsEditingComboBox(RowIndex)) { - this.EditingComboBox.ValueMember = value; + EditingComboBox.ValueMember = value; InitializeComboBoxText(); } else @@ -659,9 +659,9 @@ private string ValueMemberInternal set { InitializeValueMemberPropertyDescriptor(value); - if ((value != null && value.Length > 0) || this.Properties.ContainsObject(PropComboBoxCellValueMember)) + if ((value != null && value.Length > 0) || Properties.ContainsObject(PropComboBoxCellValueMember)) { - this.Properties.SetObject(PropComboBoxCellValueMember, value); + Properties.SetObject(PropComboBoxCellValueMember, value); } } } @@ -670,13 +670,13 @@ private PropertyDescriptor ValueMemberProperty { get { - return (PropertyDescriptor)this.Properties.GetObject(PropComboBoxCellValueMemberProp); + return (PropertyDescriptor)Properties.GetObject(PropComboBoxCellValueMemberProp); } set { - if (value != null || this.Properties.ContainsObject(PropComboBoxCellValueMemberProp)) + if (value != null || Properties.ContainsObject(PropComboBoxCellValueMemberProp)) { - this.Properties.SetObject(PropComboBoxCellValueMemberProp, value); + Properties.SetObject(PropComboBoxCellValueMemberProp, value); } } } @@ -686,13 +686,13 @@ public override Type ValueType { get { - if (this.ValueMemberProperty != null) + if (ValueMemberProperty != null) { - return this.ValueMemberProperty.PropertyType; + return ValueMemberProperty.PropertyType; } - else if (this.DisplayMemberProperty != null) + else if (DisplayMemberProperty != null) { - return this.DisplayMemberProperty.PropertyType; + return DisplayMemberProperty.PropertyType; } else { @@ -709,14 +709,14 @@ public override Type ValueType // Called when the row that owns the editing control gets unshared. internal override void CacheEditingControl() { - this.EditingComboBox = this.DataGridView.EditingControl as DataGridViewComboBoxEditingControl; + EditingComboBox = DataGridView.EditingControl as DataGridViewComboBoxEditingControl; } private void CheckDropDownList(int x, int y, int rowIndex) { - Debug.Assert(this.EditingComboBox != null); + Debug.Assert(EditingComboBox != null); DataGridViewAdvancedBorderStyle dgvabsPlaceholder = new DataGridViewAdvancedBorderStyle(), dgvabsEffective; - dgvabsEffective = AdjustCellBorderStyle(this.DataGridView.AdvancedCellBorderStyle, + dgvabsEffective = AdjustCellBorderStyle(DataGridView.AdvancedCellBorderStyle, dgvabsPlaceholder, false /*singleVerticalBorderAdded*/, false /*singleHorizontalBorderAdded*/, @@ -744,12 +744,12 @@ private void CheckDropDownList(int x, int y, int rowIndex) y >= borderAndPaddingWidths.Y + 1 && y <= borderAndPaddingWidths.Y + 1 + dropHeight) { - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { if (x >= borderAndPaddingWidths.X + 1 && x <= borderAndPaddingWidths.X + dropWidth + 1) { - this.EditingComboBox.DroppedDown = true; + EditingComboBox.DroppedDown = true; } } else @@ -757,7 +757,7 @@ private void CheckDropDownList(int x, int y, int rowIndex) if (x >= size.Width - borderAndPaddingWidths.Width - dropWidth - 1 && x <= size.Width - borderAndPaddingWidths.Width - 1) { - this.EditingComboBox.DroppedDown = true; + EditingComboBox.DroppedDown = true; } } } @@ -765,7 +765,7 @@ private void CheckDropDownList(int x, int y, int rowIndex) private void CheckNoDataSource() { - if (this.DataSource != null) + if (DataSource != null) { throw new ArgumentException(SR.DataSourceLocksItems); } @@ -781,28 +781,28 @@ private void CheckNoDataSource() private void ComboBox_DropDown(object sender, EventArgs e) { - Debug.Assert(this.DataGridView != null); - Debug.Assert(this.EditingComboBox != null); + Debug.Assert(DataGridView != null); + Debug.Assert(EditingComboBox != null); - ComboBox comboBox = this.EditingComboBox; - DataGridViewComboBoxColumn owningComboBoxColumn = this.OwningColumn as DataGridViewComboBoxColumn; + ComboBox comboBox = EditingComboBox; + DataGridViewComboBoxColumn owningComboBoxColumn = OwningColumn as DataGridViewComboBoxColumn; if (owningComboBoxColumn != null) { - DataGridViewAutoSizeColumnMode autoSizeColumnMode = owningComboBoxColumn.GetInheritedAutoSizeMode(this.DataGridView); + DataGridViewAutoSizeColumnMode autoSizeColumnMode = owningComboBoxColumn.GetInheritedAutoSizeMode(DataGridView); if (autoSizeColumnMode != DataGridViewAutoSizeColumnMode.ColumnHeader && autoSizeColumnMode != DataGridViewAutoSizeColumnMode.Fill && autoSizeColumnMode != DataGridViewAutoSizeColumnMode.None) { - if (this.DropDownWidth == 1) + if (DropDownWidth == 1) { // Owning combobox column is autosized based on inner cells. // Resize the dropdown list based on the max width of the items. if (cachedDropDownWidth == -1) { int maxPreferredWidth = -1; - if ((this.HasItems || this.CreateItemsFromDataSource) && this.Items.Count > 0) + if ((HasItems || CreateItemsFromDataSource) && Items.Count > 0) { - foreach (object item in this.Items) + foreach (object item in Items) { Size preferredSize = TextRenderer.MeasureText(comboBox.GetItemText(item), comboBox.Font); if (preferredSize.Width > maxPreferredWidth) @@ -822,9 +822,9 @@ private void ComboBox_DropDown(object sender, EventArgs e) // The dropdown width may have been previously adjusted to the items because of the owning column autosized. // The dropdown width needs to be realigned to the DropDownWidth property value. int dropDownWidth = unchecked((int)(long)UnsafeNativeMethods.SendMessage(new HandleRef(comboBox, comboBox.Handle), NativeMethods.CB_GETDROPPEDWIDTH, 0, 0)); - if (dropDownWidth != this.DropDownWidth) + if (dropDownWidth != DropDownWidth) { - UnsafeNativeMethods.SendMessage(new HandleRef(comboBox, comboBox.Handle), NativeMethods.CB_SETDROPPEDWIDTH, this.DropDownWidth, 0); + UnsafeNativeMethods.SendMessage(new HandleRef(comboBox, comboBox.Handle), NativeMethods.CB_SETDROPPEDWIDTH, DropDownWidth, 0); } } } @@ -833,7 +833,7 @@ private void ComboBox_DropDown(object sender, EventArgs e) public override object Clone() { DataGridViewComboBoxCell dataGridViewCell; - Type thisType = this.GetType(); + Type thisType = GetType(); if (thisType == cellType) //performance improvement { @@ -845,21 +845,21 @@ public override object Clone() dataGridViewCell = (DataGridViewComboBoxCell)System.Activator.CreateInstance(thisType); } base.CloneInternal(dataGridViewCell); - dataGridViewCell.DropDownWidth = this.DropDownWidth; - dataGridViewCell.MaxDropDownItems = this.MaxDropDownItems; + dataGridViewCell.DropDownWidth = DropDownWidth; + dataGridViewCell.MaxDropDownItems = MaxDropDownItems; dataGridViewCell.CreateItemsFromDataSource = false; - dataGridViewCell.DataSource = this.DataSource; - dataGridViewCell.DisplayMember = this.DisplayMember; - dataGridViewCell.ValueMember = this.ValueMember; - if (this.HasItems && this.DataSource == null && this.Items.Count > 0) - { - dataGridViewCell.Items.AddRangeInternal(this.Items.InnerArray.ToArray()); - } - dataGridViewCell.AutoComplete = this.AutoComplete; - dataGridViewCell.Sorted = this.Sorted; - dataGridViewCell.FlatStyleInternal = this.FlatStyle; - dataGridViewCell.DisplayStyleInternal = this.DisplayStyle; - dataGridViewCell.DisplayStyleForCurrentCellOnlyInternal = this.DisplayStyleForCurrentCellOnly; + dataGridViewCell.DataSource = DataSource; + dataGridViewCell.DisplayMember = DisplayMember; + dataGridViewCell.ValueMember = ValueMember; + if (HasItems && DataSource == null && Items.Count > 0) + { + dataGridViewCell.Items.AddRangeInternal(Items.InnerArray.ToArray()); + } + dataGridViewCell.AutoComplete = AutoComplete; + dataGridViewCell.Sorted = Sorted; + dataGridViewCell.FlatStyleInternal = FlatStyle; + dataGridViewCell.DisplayStyleInternal = DisplayStyle; + dataGridViewCell.DisplayStyleForCurrentCellOnlyInternal = DisplayStyleForCurrentCellOnly; return dataGridViewCell; } @@ -867,34 +867,34 @@ private bool CreateItemsFromDataSource { get { - return ((this.flags & DATAGRIDVIEWCOMBOBOXCELL_createItemsFromDataSource) != 0x00); + return ((flags & DATAGRIDVIEWCOMBOBOXCELL_createItemsFromDataSource) != 0x00); } set { if (value) { - this.flags |= (byte)DATAGRIDVIEWCOMBOBOXCELL_createItemsFromDataSource; + flags |= (byte)DATAGRIDVIEWCOMBOBOXCELL_createItemsFromDataSource; } else { - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOMBOBOXCELL_createItemsFromDataSource); + flags = (byte)(flags & ~DATAGRIDVIEWCOMBOBOXCELL_createItemsFromDataSource); } } } private void DataSource_Disposed(object sender, EventArgs e) { - Debug.Assert(sender == this.DataSource, "How can we get dispose notification from anything other than our DataSource?"); - this.DataSource = null; + Debug.Assert(sender == DataSource, "How can we get dispose notification from anything other than our DataSource?"); + DataSource = null; } private void DataSource_Initialized(object sender, EventArgs e) { - Debug.Assert(sender == this.DataSource); - Debug.Assert(this.DataSource is ISupportInitializeNotification); - Debug.Assert((this.flags & DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp) != 0x00); + Debug.Assert(sender == DataSource); + Debug.Assert(DataSource is ISupportInitializeNotification); + Debug.Assert((flags & DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp) != 0x00); - ISupportInitializeNotification dsInit = this.DataSource as ISupportInitializeNotification; + ISupportInitializeNotification dsInit = DataSource as ISupportInitializeNotification; // Unhook the Initialized event. if (dsInit != null) { @@ -902,29 +902,29 @@ private void DataSource_Initialized(object sender, EventArgs e) } // The wait is over: DataSource is initialized. - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp); + flags = (byte)(flags & ~DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp); // Check the DisplayMember and ValueMember values - will throw if values don't match existing fields. - InitializeDisplayMemberPropertyDescriptor(this.DisplayMember); - InitializeValueMemberPropertyDescriptor(this.ValueMember); + InitializeDisplayMemberPropertyDescriptor(DisplayMember); + InitializeValueMemberPropertyDescriptor(ValueMember); } public override void DetachEditingControl() { - DataGridView dgv = this.DataGridView; + DataGridView dgv = DataGridView; if (dgv == null || dgv.EditingControl == null) { throw new InvalidOperationException(); } - if (this.EditingComboBox != null && - (this.flags & DATAGRIDVIEWCOMBOBOXCELL_dropDownHookedUp) != 0x00) + if (EditingComboBox != null && + (flags & DATAGRIDVIEWCOMBOBOXCELL_dropDownHookedUp) != 0x00) { - this.EditingComboBox.DropDown -= new EventHandler(ComboBox_DropDown); - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOMBOBOXCELL_dropDownHookedUp); + EditingComboBox.DropDown -= new EventHandler(ComboBox_DropDown); + flags = (byte)(flags & ~DATAGRIDVIEWCOMBOBOXCELL_dropDownHookedUp); } - this.EditingComboBox = null; + EditingComboBox = null; base.DetachEditingControl(); } @@ -935,7 +935,7 @@ protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCel throw new ArgumentNullException(nameof(cellStyle)); } - if (this.DataGridView == null || rowIndex < 0 || this.OwningColumn == null) + if (DataGridView == null || rowIndex < 0 || OwningColumn == null) { return Rectangle.Empty; } @@ -990,22 +990,22 @@ protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCel private CurrencyManager GetDataManager(DataGridView dataGridView) { - CurrencyManager cm = (CurrencyManager)this.Properties.GetObject(PropComboBoxCellDataManager); - if (cm == null && this.DataSource != null && dataGridView != null && dataGridView.BindingContext != null && !(this.DataSource == Convert.DBNull)) + CurrencyManager cm = (CurrencyManager)Properties.GetObject(PropComboBoxCellDataManager); + if (cm == null && DataSource != null && dataGridView != null && dataGridView.BindingContext != null && !(DataSource == Convert.DBNull)) { - ISupportInitializeNotification dsInit = this.DataSource as ISupportInitializeNotification; + ISupportInitializeNotification dsInit = DataSource as ISupportInitializeNotification; if (dsInit != null && !dsInit.IsInitialized) { - if ((this.flags & DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp) == 0x00) + if ((flags & DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp) == 0x00) { dsInit.Initialized += new EventHandler(DataSource_Initialized); - this.flags |= (byte)DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp; + flags |= (byte)DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp; } } else { - cm = (CurrencyManager)dataGridView.BindingContext[this.DataSource]; - this.DataManager = cm; + cm = (CurrencyManager)dataGridView.BindingContext[DataSource]; + DataManager = cm; } } return cm; @@ -1017,7 +1017,7 @@ private CurrencyManager GetDataManager(DataGridView dataGridView) private int GetDropDownButtonHeight(Graphics graphics, DataGridViewCellStyle cellStyle) { int adjustment = 4; - if (this.PaintXPThemes) + if (PaintXPThemes) { if (PostXPThemesExist) { @@ -1038,10 +1038,10 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC throw new ArgumentNullException(nameof(cellStyle)); } - if (this.DataGridView == null || + if (DataGridView == null || rowIndex < 0 || - this.OwningColumn == null || - !this.DataGridView.ShowCellErrors || + OwningColumn == null || + !DataGridView.ShowCellErrors || string.IsNullOrEmpty(GetErrorText(rowIndex))) { return Rectangle.Empty; @@ -1107,17 +1107,17 @@ protected override object GetFormattedValue(object value, { if (valueTypeConverter == null) { - if (this.ValueMemberProperty != null) + if (ValueMemberProperty != null) { - valueTypeConverter = this.ValueMemberProperty.Converter; + valueTypeConverter = ValueMemberProperty.Converter; } - else if (this.DisplayMemberProperty != null) + else if (DisplayMemberProperty != null) { - valueTypeConverter = this.DisplayMemberProperty.Converter; + valueTypeConverter = DisplayMemberProperty.Converter; } } - if (value == null || ((this.ValueType != null && !this.ValueType.IsAssignableFrom(value.GetType())) && value != System.DBNull.Value)) + if (value == null || ((ValueType != null && !ValueType.IsAssignableFrom(value.GetType())) && value != System.DBNull.Value)) { // Do not raise the DataError event if the value is null and the row is the 'new row'. @@ -1126,10 +1126,10 @@ protected override object GetFormattedValue(object value, // Debug.Assert(rowIndex != -1 || this.Items.Count == 0); return base.GetFormattedValue(null, rowIndex, ref cellStyle, valueTypeConverter, formattedValueTypeConverter, context); } - if (this.DataGridView != null) + if (DataGridView != null) { DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs( - new FormatException(string.Format(SR.DataGridViewComboBoxCell_InvalidValue)), this.ColumnIndex, + new FormatException(string.Format(SR.DataGridViewComboBoxCell_InvalidValue)), ColumnIndex, rowIndex, context); RaiseDataError(dgvdee); if (dgvdee.ThrowException) @@ -1141,8 +1141,8 @@ protected override object GetFormattedValue(object value, } string strValue = value as string; - if ((this.DataManager != null && (this.ValueMemberProperty != null || this.DisplayMemberProperty != null)) || - !string.IsNullOrEmpty(this.ValueMember) || !string.IsNullOrEmpty(this.DisplayMember)) + if ((DataManager != null && (ValueMemberProperty != null || DisplayMemberProperty != null)) || + !string.IsNullOrEmpty(ValueMember) || !string.IsNullOrEmpty(DisplayMember)) { object displayValue; if (!LookupDisplayValue(rowIndex, value, out displayValue)) @@ -1151,14 +1151,14 @@ protected override object GetFormattedValue(object value, { displayValue = System.DBNull.Value; } - else if (strValue != null && string.IsNullOrEmpty(strValue) && this.DisplayType == typeof(string)) + else if (strValue != null && string.IsNullOrEmpty(strValue) && DisplayType == typeof(string)) { displayValue = string.Empty; } - else if (this.DataGridView != null) + else if (DataGridView != null) { DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs( - new ArgumentException(string.Format(SR.DataGridViewComboBoxCell_InvalidValue)), this.ColumnIndex, + new ArgumentException(string.Format(SR.DataGridViewComboBoxCell_InvalidValue)), ColumnIndex, rowIndex, context); RaiseDataError(dgvdee); if (dgvdee.ThrowException) @@ -1168,23 +1168,23 @@ protected override object GetFormattedValue(object value, if (OwnsEditingComboBox(rowIndex)) { - ((IDataGridViewEditingControl)this.EditingComboBox).EditingControlValueChanged = true; - this.DataGridView.NotifyCurrentCellDirty(true); + ((IDataGridViewEditingControl)EditingComboBox).EditingControlValueChanged = true; + DataGridView.NotifyCurrentCellDirty(true); } } } - return base.GetFormattedValue(displayValue, rowIndex, ref cellStyle, this.DisplayTypeConverter, formattedValueTypeConverter, context); + return base.GetFormattedValue(displayValue, rowIndex, ref cellStyle, DisplayTypeConverter, formattedValueTypeConverter, context); } else { - if (!this.Items.Contains(value) && + if (!Items.Contains(value) && value != System.DBNull.Value && (!(value is string) || !string.IsNullOrEmpty(strValue))) { - if (this.DataGridView != null) + if (DataGridView != null) { DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs( - new ArgumentException(string.Format(SR.DataGridViewComboBoxCell_InvalidValue)), this.ColumnIndex, + new ArgumentException(string.Format(SR.DataGridViewComboBoxCell_InvalidValue)), ColumnIndex, rowIndex, context); RaiseDataError(dgvdee); if (dgvdee.ThrowException) @@ -1193,9 +1193,9 @@ protected override object GetFormattedValue(object value, } } - if (this.Items.Count > 0) + if (Items.Count > 0) { - value = this.Items[0]; + value = Items[0]; } else { @@ -1217,28 +1217,28 @@ internal object GetItemDisplayValue(object item) Debug.Assert(item != null); bool displayValueSet = false; object displayValue = null; - if (this.DisplayMemberProperty != null) + if (DisplayMemberProperty != null) { - displayValue = this.DisplayMemberProperty.GetValue(item); + displayValue = DisplayMemberProperty.GetValue(item); displayValueSet = true; } - else if (this.ValueMemberProperty != null) + else if (ValueMemberProperty != null) { - displayValue = this.ValueMemberProperty.GetValue(item); + displayValue = ValueMemberProperty.GetValue(item); displayValueSet = true; } - else if (!string.IsNullOrEmpty(this.DisplayMember)) + else if (!string.IsNullOrEmpty(DisplayMember)) { - PropertyDescriptor propDesc = TypeDescriptor.GetProperties(item).Find(this.DisplayMember, true /*caseInsensitive*/); + PropertyDescriptor propDesc = TypeDescriptor.GetProperties(item).Find(DisplayMember, true /*caseInsensitive*/); if (propDesc != null) { displayValue = propDesc.GetValue(item); displayValueSet = true; } } - else if (!string.IsNullOrEmpty(this.ValueMember)) + else if (!string.IsNullOrEmpty(ValueMember)) { - PropertyDescriptor propDesc = TypeDescriptor.GetProperties(item).Find(this.ValueMember, true /*caseInsensitive*/); + PropertyDescriptor propDesc = TypeDescriptor.GetProperties(item).Find(ValueMember, true /*caseInsensitive*/); if (propDesc != null) { displayValue = propDesc.GetValue(item); @@ -1254,13 +1254,13 @@ internal object GetItemDisplayValue(object item) internal ObjectCollection GetItems(DataGridView dataGridView) { - ObjectCollection items = (ObjectCollection)this.Properties.GetObject(PropComboBoxCellItems); + ObjectCollection items = (ObjectCollection)Properties.GetObject(PropComboBoxCellItems); if (items == null) { items = new ObjectCollection(this); - this.Properties.SetObject(PropComboBoxCellItems, items); + Properties.SetObject(PropComboBoxCellItems, items); } - if (this.CreateItemsFromDataSource) + if (CreateItemsFromDataSource) { items.ClearInternal(); CurrencyManager dataManager = GetDataManager(dataGridView); @@ -1274,9 +1274,9 @@ internal ObjectCollection GetItems(DataGridView dataGridView) items.AddRangeInternal(newItems); } // Do not clear the CreateItemsFromDataSource flag when the data source has not been initialized yet - if (dataManager != null || (this.flags & DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp) == 0x00) + if (dataManager != null || (flags & DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp) == 0x00) { - this.CreateItemsFromDataSource = false; + CreateItemsFromDataSource = false; } } return items; @@ -1286,28 +1286,28 @@ internal object GetItemValue(object item) { bool valueSet = false; object value = null; - if (this.ValueMemberProperty != null) + if (ValueMemberProperty != null) { - value = this.ValueMemberProperty.GetValue(item); + value = ValueMemberProperty.GetValue(item); valueSet = true; } - else if (this.DisplayMemberProperty != null) + else if (DisplayMemberProperty != null) { - value = this.DisplayMemberProperty.GetValue(item); + value = DisplayMemberProperty.GetValue(item); valueSet = true; } - else if (!string.IsNullOrEmpty(this.ValueMember)) + else if (!string.IsNullOrEmpty(ValueMember)) { - PropertyDescriptor propDesc = TypeDescriptor.GetProperties(item).Find(this.ValueMember, true /*caseInsensitive*/); + PropertyDescriptor propDesc = TypeDescriptor.GetProperties(item).Find(ValueMember, true /*caseInsensitive*/); if (propDesc != null) { value = propDesc.GetValue(item); valueSet = true; } } - if (!valueSet && !string.IsNullOrEmpty(this.DisplayMember)) + if (!valueSet && !string.IsNullOrEmpty(DisplayMember)) { - PropertyDescriptor propDesc = TypeDescriptor.GetProperties(item).Find(this.DisplayMember, true /*caseInsensitive*/); + PropertyDescriptor propDesc = TypeDescriptor.GetProperties(item).Find(DisplayMember, true /*caseInsensitive*/); if (propDesc != null) { value = propDesc.GetValue(item); @@ -1326,7 +1326,7 @@ internal object GetItemValue(object item) ] protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize) { - if (this.DataGridView == null) + if (DataGridView == null) { return new Size(-1, -1); } @@ -1338,10 +1338,10 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl Size preferredSize = Size.Empty; DataGridViewFreeDimension freeDimension = DataGridViewCell.GetFreeDimensionFromConstraint(constraintSize); - Rectangle borderWidthsRect = this.StdBorderWidths; + Rectangle borderWidthsRect = StdBorderWidths; int borderAndPaddingWidths = borderWidthsRect.Left + borderWidthsRect.Width + cellStyle.Padding.Horizontal; int borderAndPaddingHeights = borderWidthsRect.Top + borderWidthsRect.Height + cellStyle.Padding.Vertical; - TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); + TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); /* Changing design of DGVComboBoxCell.GetPreferredSize for performance reasons. * Old design required looking through each combo item @@ -1434,7 +1434,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl if (freeDimension != DataGridViewFreeDimension.Height) { preferredSize.Width += SystemInformation.HorizontalScrollBarThumbWidth + 1 + 2 * DATAGRIDVIEWCOMBOBOXCELL_margin + borderAndPaddingWidths; - if (this.DataGridView.ShowCellErrors) + if (DataGridView.ShowCellErrors) { // Making sure that there is enough room for the potential error icon preferredSize.Width = Math.Max(preferredSize.Width, borderAndPaddingWidths + SystemInformation.HorizontalScrollBarThumbWidth + 1 + DATAGRIDVIEWCELL_iconMarginWidth * 2 + iconsWidth); @@ -1442,7 +1442,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl } if (freeDimension != DataGridViewFreeDimension.Width) { - if (this.FlatStyle == FlatStyle.Flat || this.FlatStyle == FlatStyle.Popup) + if (FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup) { preferredSize.Height += 6; } @@ -1451,7 +1451,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl preferredSize.Height += 8; } preferredSize.Height += borderAndPaddingHeights; - if (this.DataGridView.ShowCellErrors) + if (DataGridView.ShowCellErrors) { // Making sure that there is enough room for the potential error icon preferredSize.Height = Math.Max(preferredSize.Height, borderAndPaddingHeights + DATAGRIDVIEWCELL_iconMarginHeight * 2 + iconsHeight); @@ -1462,28 +1462,28 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl private void InitializeComboBoxText() { - Debug.Assert(this.EditingComboBox != null); - ((IDataGridViewEditingControl)this.EditingComboBox).EditingControlValueChanged = false; - int rowIndex = ((IDataGridViewEditingControl)this.EditingComboBox).EditingControlRowIndex; + Debug.Assert(EditingComboBox != null); + ((IDataGridViewEditingControl)EditingComboBox).EditingControlValueChanged = false; + int rowIndex = ((IDataGridViewEditingControl)EditingComboBox).EditingControlRowIndex; Debug.Assert(rowIndex > -1); DataGridViewCellStyle dataGridViewCellStyle = GetInheritedStyle(null, rowIndex, false); - this.EditingComboBox.Text = (string)GetFormattedValue(GetValue(rowIndex), rowIndex, ref dataGridViewCellStyle, null, null, DataGridViewDataErrorContexts.Formatting); + EditingComboBox.Text = (string)GetFormattedValue(GetValue(rowIndex), rowIndex, ref dataGridViewCellStyle, null, null, DataGridViewDataErrorContexts.Formatting); } public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle) { - Debug.Assert(this.DataGridView != null && - this.DataGridView.EditingPanel != null && - this.DataGridView.EditingControl != null); - Debug.Assert(!this.ReadOnly); + Debug.Assert(DataGridView != null && + DataGridView.EditingPanel != null && + DataGridView.EditingControl != null); + Debug.Assert(!ReadOnly); base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle); - ComboBox comboBox = this.DataGridView.EditingControl as ComboBox; + ComboBox comboBox = DataGridView.EditingControl as ComboBox; if (comboBox != null) { // Use the selection backcolor for the editing panel when the cell is selected if ((GetInheritedState(rowIndex) & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) { - this.DataGridView.EditingPanel.BackColor = dataGridViewCellStyle.SelectionBackColor; + DataGridView.EditingPanel.BackColor = dataGridViewCellStyle.SelectionBackColor; } // We need the comboBox to be parented by a control which has a handle or else the native ComboBox ends up @@ -1496,8 +1496,8 @@ public override void InitializeEditingControl(int rowIndex, object initialFormat h = comboBox.Handle; // make sure that assigning the DataSource property does not assert. comboBox.DropDownStyle = ComboBoxStyle.DropDownList; comboBox.FormattingEnabled = true; - comboBox.MaxDropDownItems = this.MaxDropDownItems; - comboBox.DropDownWidth = this.DropDownWidth; + comboBox.MaxDropDownItems = MaxDropDownItems; + comboBox.DropDownWidth = DropDownWidth; comboBox.DataSource = null; comboBox.ValueMember = null; comboBox.Items.Clear(); @@ -1512,16 +1512,16 @@ And this causes problems when changing position inside the DataGridView. } */ - comboBox.DataSource = this.DataSource; - comboBox.DisplayMember = this.DisplayMember; - comboBox.ValueMember = this.ValueMember; - if (this.HasItems && this.DataSource == null && this.Items.Count > 0) + comboBox.DataSource = DataSource; + comboBox.DisplayMember = DisplayMember; + comboBox.ValueMember = ValueMember; + if (HasItems && DataSource == null && Items.Count > 0) { - comboBox.Items.AddRange(this.Items.InnerArray.ToArray()); + comboBox.Items.AddRange(Items.InnerArray.ToArray()); } - comboBox.Sorted = this.Sorted; - comboBox.FlatStyle = this.FlatStyle; - if (this.AutoComplete) + comboBox.Sorted = Sorted; + comboBox.FlatStyle = FlatStyle; + if (AutoComplete) { comboBox.AutoCompleteSource = AutoCompleteSource.ListItems; comboBox.AutoCompleteMode = AutoCompleteMode.Append; @@ -1539,39 +1539,39 @@ And this causes problems when changing position inside the DataGridView. } comboBox.Text = initialFormattedValueStr; - if ((this.flags & DATAGRIDVIEWCOMBOBOXCELL_dropDownHookedUp) == 0x00) + if ((flags & DATAGRIDVIEWCOMBOBOXCELL_dropDownHookedUp) == 0x00) { comboBox.DropDown += new EventHandler(ComboBox_DropDown); - this.flags |= (byte)DATAGRIDVIEWCOMBOBOXCELL_dropDownHookedUp; + flags |= (byte)DATAGRIDVIEWCOMBOBOXCELL_dropDownHookedUp; } cachedDropDownWidth = -1; - this.EditingComboBox = this.DataGridView.EditingControl as DataGridViewComboBoxEditingControl; + EditingComboBox = DataGridView.EditingControl as DataGridViewComboBoxEditingControl; if (GetHeight(rowIndex) > 21) { - Rectangle rectBottomSection = this.DataGridView.GetCellDisplayRectangle(this.ColumnIndex, rowIndex, true); + Rectangle rectBottomSection = DataGridView.GetCellDisplayRectangle(ColumnIndex, rowIndex, true); rectBottomSection.Y += 21; rectBottomSection.Height -= 21; - this.DataGridView.Invalidate(rectBottomSection); + DataGridView.Invalidate(rectBottomSection); } } } private void InitializeDisplayMemberPropertyDescriptor(string displayMember) { - if (this.DataManager != null) + if (DataManager != null) { if (string.IsNullOrEmpty(displayMember)) { - this.DisplayMemberProperty = null; + DisplayMemberProperty = null; } else { BindingMemberInfo displayBindingMember = new BindingMemberInfo(displayMember); // make the DataManager point to the sublist inside this.DataSource - this.DataManager = this.DataGridView.BindingContext[this.DataSource, displayBindingMember.BindingPath] as CurrencyManager; + DataManager = DataGridView.BindingContext[DataSource, displayBindingMember.BindingPath] as CurrencyManager; - PropertyDescriptorCollection props = this.DataManager.GetItemProperties(); + PropertyDescriptorCollection props = DataManager.GetItemProperties(); PropertyDescriptor displayMemberProperty = props.Find(displayBindingMember.BindingField, true); if (displayMemberProperty == null) { @@ -1579,7 +1579,7 @@ private void InitializeDisplayMemberPropertyDescriptor(string displayMember) } else { - this.DisplayMemberProperty = displayMemberProperty; + DisplayMemberProperty = displayMemberProperty; } } } @@ -1587,19 +1587,19 @@ private void InitializeDisplayMemberPropertyDescriptor(string displayMember) private void InitializeValueMemberPropertyDescriptor(string valueMember) { - if (this.DataManager != null) + if (DataManager != null) { if (string.IsNullOrEmpty(valueMember)) { - this.ValueMemberProperty = null; + ValueMemberProperty = null; } else { BindingMemberInfo valueBindingMember = new BindingMemberInfo(valueMember); // make the DataManager point to the sublist inside this.DataSource - this.DataManager = this.DataGridView.BindingContext[this.DataSource, valueBindingMember.BindingPath] as CurrencyManager; + DataManager = DataGridView.BindingContext[DataSource, valueBindingMember.BindingPath] as CurrencyManager; - PropertyDescriptorCollection props = this.DataManager.GetItemProperties(); + PropertyDescriptorCollection props = DataManager.GetItemProperties(); PropertyDescriptor valueMemberProperty = props.Find(valueBindingMember.BindingField, true); if (valueMemberProperty == null) { @@ -1607,7 +1607,7 @@ private void InitializeValueMemberPropertyDescriptor(string valueMember) } else { - this.ValueMemberProperty = valueMemberProperty; + ValueMemberProperty = valueMemberProperty; } } } @@ -1631,24 +1631,24 @@ private object ItemFromComboBoxDataSource(PropertyDescriptor property, object ke //} Debug.Assert(property != null); - Debug.Assert(this.DataManager != null); + Debug.Assert(DataManager != null); object item = null; //If the data source is a bindinglist use that as it's probably more efficient - if ((this.DataManager.List is IBindingList) && ((IBindingList)this.DataManager.List).SupportsSearching) + if ((DataManager.List is IBindingList) && ((IBindingList)DataManager.List).SupportsSearching) { - int index = ((IBindingList)this.DataManager.List).Find(property, key); + int index = ((IBindingList)DataManager.List).Find(property, key); if (index != -1) { - item = this.DataManager.List[index]; + item = DataManager.List[index]; } } else { //Otherwise walk across the items looking for the item we want - for (int i = 0; i < this.DataManager.List.Count; i++) + for (int i = 0; i < DataManager.List.Count; i++) { - object itemTmp = this.DataManager.List[i]; + object itemTmp = DataManager.List[i]; object value = property.GetValue(itemTmp); if (key.Equals(value)) { @@ -1668,7 +1668,7 @@ private object ItemFromComboBoxItems(int rowIndex, string field, object key) if (OwnsEditingComboBox(rowIndex)) { // It is likely that the item looked for is the selected item. - item = this.EditingComboBox.SelectedItem; + item = EditingComboBox.SelectedItem; object displayValue = null; PropertyDescriptor propDesc = TypeDescriptor.GetProperties(item).Find(field, true /*caseInsensitive*/); if (propDesc != null) @@ -1683,7 +1683,7 @@ private object ItemFromComboBoxItems(int rowIndex, string field, object key) } if (item == null) { - foreach (object itemCandidate in this.Items) + foreach (object itemCandidate in Items) { object displayValue = null; PropertyDescriptor propDesc = TypeDescriptor.GetProperties(itemCandidate).Find(field, true /*caseInsensitive*/); @@ -1705,13 +1705,13 @@ private object ItemFromComboBoxItems(int rowIndex, string field, object key) if (OwnsEditingComboBox(rowIndex)) { // It is likely that the item looked for is the selected item. - item = this.EditingComboBox.SelectedItem; + item = EditingComboBox.SelectedItem; if (item == null || !item.Equals(key)) { item = null; } } - if (item == null && this.Items.Contains(key)) + if (item == null && Items.Contains(key)) { item = key; } @@ -1745,20 +1745,20 @@ public override bool KeyEntersEditMode(KeyEventArgs e) private bool LookupDisplayValue(int rowIndex, object value, out object displayValue) { Debug.Assert(value != null); - Debug.Assert(this.ValueMemberProperty != null || this.DisplayMemberProperty != null || - !string.IsNullOrEmpty(this.ValueMember) || !string.IsNullOrEmpty(this.DisplayMember)); + Debug.Assert(ValueMemberProperty != null || DisplayMemberProperty != null || + !string.IsNullOrEmpty(ValueMember) || !string.IsNullOrEmpty(DisplayMember)); object item = null; - if (this.DisplayMemberProperty != null || this.ValueMemberProperty != null) + if (DisplayMemberProperty != null || ValueMemberProperty != null) { //Now look up the item in the Combobox datasource - this can be horribly inefficient //and it uses reflection which makes it expensive - ripe for optimization - item = this.ItemFromComboBoxDataSource(this.ValueMemberProperty != null ? this.ValueMemberProperty : this.DisplayMemberProperty, value); + item = ItemFromComboBoxDataSource(ValueMemberProperty != null ? ValueMemberProperty : DisplayMemberProperty, value); } else { //Find the item in the Items collection based on the provided ValueMember or DisplayMember - item = ItemFromComboBoxItems(rowIndex, string.IsNullOrEmpty(this.ValueMember) ? this.DisplayMember : this.ValueMember, value); + item = ItemFromComboBoxItems(rowIndex, string.IsNullOrEmpty(ValueMember) ? DisplayMember : ValueMember, value); } if (item == null) { @@ -1787,20 +1787,20 @@ private bool LookupValue(object formattedValue, out object value) return true; } - Debug.Assert(this.DisplayMemberProperty != null || this.ValueMemberProperty != null || - !string.IsNullOrEmpty(this.DisplayMember) || !string.IsNullOrEmpty(this.ValueMember)); + Debug.Assert(DisplayMemberProperty != null || ValueMemberProperty != null || + !string.IsNullOrEmpty(DisplayMember) || !string.IsNullOrEmpty(ValueMember)); object item = null; - if (this.DisplayMemberProperty != null || this.ValueMemberProperty != null) + if (DisplayMemberProperty != null || ValueMemberProperty != null) { //Now look up the item in the DataGridViewComboboxCell datasource - this can be horribly inefficient //and it uses reflection which makes it expensive - ripe for optimization - item = ItemFromComboBoxDataSource(this.DisplayMemberProperty != null ? this.DisplayMemberProperty : this.ValueMemberProperty, formattedValue); + item = ItemFromComboBoxDataSource(DisplayMemberProperty != null ? DisplayMemberProperty : ValueMemberProperty, formattedValue); } else { //Find the item in the Items collection based on the provided DisplayMember or ValueMember - item = ItemFromComboBoxItems(this.RowIndex, string.IsNullOrEmpty(this.DisplayMember) ? this.ValueMember : this.DisplayMember, formattedValue); + item = ItemFromComboBoxItems(RowIndex, string.IsNullOrEmpty(DisplayMember) ? ValueMember : DisplayMember, formattedValue); } if (item == null) { @@ -1815,36 +1815,36 @@ private bool LookupValue(object formattedValue, out object value) protected override void OnDataGridViewChanged() { - if (this.DataGridView != null) + if (DataGridView != null) { // Will throw an error if DataGridView is set and a member is invalid - InitializeDisplayMemberPropertyDescriptor(this.DisplayMember); - InitializeValueMemberPropertyDescriptor(this.ValueMember); + InitializeDisplayMemberPropertyDescriptor(DisplayMember); + InitializeValueMemberPropertyDescriptor(ValueMember); } base.OnDataGridViewChanged(); } protected override void OnEnter(int rowIndex, bool throughMouseClick) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } - if (throughMouseClick && this.DataGridView.EditMode != DataGridViewEditMode.EditOnEnter) + if (throughMouseClick && DataGridView.EditMode != DataGridViewEditMode.EditOnEnter) { - this.flags |= (byte)DATAGRIDVIEWCOMBOBOXCELL_ignoreNextMouseClick; + flags |= (byte)DATAGRIDVIEWCOMBOBOXCELL_ignoreNextMouseClick; } } private void OnItemsCollectionChanged() { - if (this.TemplateComboBoxColumn != null) + if (TemplateComboBoxColumn != null) { - Debug.Assert(this.TemplateComboBoxColumn.CellTemplate == this); - this.TemplateComboBoxColumn.OnItemsCollectionChanged(); + Debug.Assert(TemplateComboBoxColumn.CellTemplate == this); + TemplateComboBoxColumn.OnItemsCollectionChanged(); } cachedDropDownWidth = -1; - if (OwnsEditingComboBox(this.RowIndex)) + if (OwnsEditingComboBox(RowIndex)) { InitializeComboBoxText(); } @@ -1856,32 +1856,32 @@ private void OnItemsCollectionChanged() protected override void OnLeave(int rowIndex, bool throughMouseClick) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOMBOBOXCELL_ignoreNextMouseClick); + flags = (byte)(flags & ~DATAGRIDVIEWCOMBOBOXCELL_ignoreNextMouseClick); } protected override void OnMouseClick(DataGridViewCellMouseEventArgs e) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } - Debug.Assert(e.ColumnIndex == this.ColumnIndex); - Point ptCurrentCell = this.DataGridView.CurrentCellAddress; + Debug.Assert(e.ColumnIndex == ColumnIndex); + Point ptCurrentCell = DataGridView.CurrentCellAddress; if (ptCurrentCell.X == e.ColumnIndex && ptCurrentCell.Y == e.RowIndex) { - if ((this.flags & DATAGRIDVIEWCOMBOBOXCELL_ignoreNextMouseClick) != 0x00) + if ((flags & DATAGRIDVIEWCOMBOBOXCELL_ignoreNextMouseClick) != 0x00) { - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOMBOBOXCELL_ignoreNextMouseClick); + flags = (byte)(flags & ~DATAGRIDVIEWCOMBOBOXCELL_ignoreNextMouseClick); } - else if ((this.EditingComboBox == null || !this.EditingComboBox.DroppedDown) && - this.DataGridView.EditMode != DataGridViewEditMode.EditProgrammatically && - this.DataGridView.BeginEdit(true /*selectAll*/)) + else if ((EditingComboBox == null || !EditingComboBox.DroppedDown) && + DataGridView.EditMode != DataGridViewEditMode.EditProgrammatically && + DataGridView.BeginEdit(true /*selectAll*/)) { - if (this.EditingComboBox != null && this.DisplayStyle != DataGridViewComboBoxDisplayStyle.Nothing) + if (EditingComboBox != null && DisplayStyle != DataGridViewComboBoxDisplayStyle.Nothing) { CheckDropDownList(e.X, e.Y, e.RowIndex); } @@ -1891,14 +1891,14 @@ protected override void OnMouseClick(DataGridViewCellMouseEventArgs e) protected override void OnMouseEnter(int rowIndex) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } - if (this.DisplayStyle == DataGridViewComboBoxDisplayStyle.ComboBox && this.FlatStyle == FlatStyle.Popup) + if (DisplayStyle == DataGridViewComboBoxDisplayStyle.ComboBox && FlatStyle == FlatStyle.Popup) { - this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex); + DataGridView.InvalidateCell(ColumnIndex, rowIndex); } base.OnMouseEnter(rowIndex); @@ -1906,7 +1906,7 @@ protected override void OnMouseEnter(int rowIndex) protected override void OnMouseLeave(int rowIndex) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } @@ -1914,18 +1914,18 @@ protected override void OnMouseLeave(int rowIndex) if (mouseInDropDownButtonBounds) { mouseInDropDownButtonBounds = false; - if (this.ColumnIndex >= 0 && + if (ColumnIndex >= 0 && rowIndex >= 0 && - (this.FlatStyle == FlatStyle.Standard || this.FlatStyle == FlatStyle.System) && - this.DataGridView.ApplyVisualStylesToInnerCells) + (FlatStyle == FlatStyle.Standard || FlatStyle == FlatStyle.System) && + DataGridView.ApplyVisualStylesToInnerCells) { - this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex); + DataGridView.InvalidateCell(ColumnIndex, rowIndex); } } - if (this.DisplayStyle == DataGridViewComboBoxDisplayStyle.ComboBox && this.FlatStyle == FlatStyle.Popup) + if (DisplayStyle == DataGridViewComboBoxDisplayStyle.ComboBox && FlatStyle == FlatStyle.Popup) { - this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex); + DataGridView.InvalidateCell(ColumnIndex, rowIndex); } base.OnMouseEnter(rowIndex); @@ -1933,40 +1933,40 @@ protected override void OnMouseLeave(int rowIndex) protected override void OnMouseMove(DataGridViewCellMouseEventArgs e) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } - if ((this.FlatStyle == FlatStyle.Standard || this.FlatStyle == FlatStyle.System) && this.DataGridView.ApplyVisualStylesToInnerCells) + if ((FlatStyle == FlatStyle.Standard || FlatStyle == FlatStyle.System) && DataGridView.ApplyVisualStylesToInnerCells) { int rowIndex = e.RowIndex; DataGridViewCellStyle cellStyle = GetInheritedStyle(null, rowIndex, false /*includeColors*/); // get the border style - bool singleVerticalBorderAdded = !this.DataGridView.RowHeadersVisible && this.DataGridView.AdvancedCellBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Single; - bool singleHorizontalBorderAdded = !this.DataGridView.ColumnHeadersVisible && this.DataGridView.AdvancedCellBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Single; - bool isFirstDisplayedRow = rowIndex == this.DataGridView.FirstDisplayedScrollingRowIndex; - bool isFirstDisplayedColumn = this.OwningColumn.Index == this.DataGridView.FirstDisplayedColumnIndex; - bool isFirstDisplayedScrollingColumn = this.OwningColumn.Index == this.DataGridView.FirstDisplayedScrollingColumnIndex; + bool singleVerticalBorderAdded = !DataGridView.RowHeadersVisible && DataGridView.AdvancedCellBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Single; + bool singleHorizontalBorderAdded = !DataGridView.ColumnHeadersVisible && DataGridView.AdvancedCellBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Single; + bool isFirstDisplayedRow = rowIndex == DataGridView.FirstDisplayedScrollingRowIndex; + bool isFirstDisplayedColumn = OwningColumn.Index == DataGridView.FirstDisplayedColumnIndex; + bool isFirstDisplayedScrollingColumn = OwningColumn.Index == DataGridView.FirstDisplayedScrollingColumnIndex; DataGridViewAdvancedBorderStyle dgvabsEffective, dgvabsPlaceholder; dgvabsPlaceholder = new DataGridViewAdvancedBorderStyle(); - dgvabsEffective = AdjustCellBorderStyle(this.DataGridView.AdvancedCellBorderStyle, dgvabsPlaceholder, + dgvabsEffective = AdjustCellBorderStyle(DataGridView.AdvancedCellBorderStyle, dgvabsPlaceholder, singleVerticalBorderAdded, singleHorizontalBorderAdded, isFirstDisplayedRow, isFirstDisplayedColumn); - Rectangle cellBounds = this.DataGridView.GetCellDisplayRectangle(this.OwningColumn.Index, rowIndex, false /*cutOverflow*/); + Rectangle cellBounds = DataGridView.GetCellDisplayRectangle(OwningColumn.Index, rowIndex, false /*cutOverflow*/); Rectangle cutoffCellBounds = cellBounds; if (isFirstDisplayedScrollingColumn) { - cellBounds.X -= this.DataGridView.FirstDisplayedScrollingColumnHiddenWidth; - cellBounds.Width += this.DataGridView.FirstDisplayedScrollingColumnHiddenWidth; + cellBounds.X -= DataGridView.FirstDisplayedScrollingColumnHiddenWidth; + cellBounds.Width += DataGridView.FirstDisplayedScrollingColumnHiddenWidth; } - DataGridViewElementStates rowState = this.DataGridView.Rows.GetRowState(rowIndex); - DataGridViewElementStates cellState = this.CellStateFromColumnRowStates(rowState); - cellState |= this.State; + DataGridViewElementStates rowState = DataGridView.Rows.GetRowState(rowIndex); + DataGridViewElementStates cellState = CellStateFromColumnRowStates(rowState); + cellState |= State; Rectangle dropDownButtonRect; using (Graphics g = WindowsFormsUtils.CreateMeasurementGraphics()) @@ -1988,11 +1988,11 @@ protected override void OnMouseMove(DataGridViewCellMouseEventArgs e) false /*paint*/); } - bool newMouseInDropDownButtonBounds = dropDownButtonRect.Contains(this.DataGridView.PointToClient(Control.MousePosition)); + bool newMouseInDropDownButtonBounds = dropDownButtonRect.Contains(DataGridView.PointToClient(Control.MousePosition)); if (newMouseInDropDownButtonBounds != mouseInDropDownButtonBounds) { mouseInDropDownButtonBounds = newMouseInDropDownButtonBounds; - this.DataGridView.InvalidateCell(e.ColumnIndex, rowIndex); + DataGridView.InvalidateCell(e.ColumnIndex, rowIndex); } } base.OnMouseMove(e); @@ -2000,7 +2000,7 @@ protected override void OnMouseMove(DataGridViewCellMouseEventArgs e) private bool OwnsEditingComboBox(int rowIndex) { - return rowIndex != -1 && this.EditingComboBox != null && rowIndex == ((IDataGridViewEditingControl)this.EditingComboBox).EditingControlRowIndex; + return rowIndex != -1 && EditingComboBox != null && rowIndex == ((IDataGridViewEditingControl)EditingComboBox).EditingControlRowIndex; } protected override void Paint(Graphics graphics, @@ -2079,17 +2079,17 @@ private Rectangle PaintPrivate(Graphics g, Rectangle resultBounds = Rectangle.Empty; dropDownButtonRect = Rectangle.Empty; - bool paintFlat = this.FlatStyle == FlatStyle.Flat || this.FlatStyle == FlatStyle.Popup; - bool paintPopup = this.FlatStyle == FlatStyle.Popup && - this.DataGridView.MouseEnteredCellAddress.Y == rowIndex && - this.DataGridView.MouseEnteredCellAddress.X == this.ColumnIndex; + bool paintFlat = FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup; + bool paintPopup = FlatStyle == FlatStyle.Popup && + DataGridView.MouseEnteredCellAddress.Y == rowIndex && + DataGridView.MouseEnteredCellAddress.X == ColumnIndex; - bool paintXPThemes = !paintFlat && this.DataGridView.ApplyVisualStylesToInnerCells; + bool paintXPThemes = !paintFlat && DataGridView.ApplyVisualStylesToInnerCells; bool paintPostXPThemes = paintXPThemes && PostXPThemesExist; ComboBoxState comboBoxState = ComboBoxState.Normal; - if (this.DataGridView.MouseEnteredCellAddress.Y == rowIndex && - this.DataGridView.MouseEnteredCellAddress.X == this.ColumnIndex && + if (DataGridView.MouseEnteredCellAddress.Y == rowIndex && + DataGridView.MouseEnteredCellAddress.X == ColumnIndex && mouseInDropDownButtonBounds) { comboBoxState = ComboBoxState.Hot; @@ -2107,31 +2107,31 @@ private Rectangle PaintPrivate(Graphics g, valBounds.Height -= borderWidths.Bottom; SolidBrush br; - Point ptCurrentCell = this.DataGridView.CurrentCellAddress; - bool cellCurrent = ptCurrentCell.X == this.ColumnIndex && ptCurrentCell.Y == rowIndex; - bool cellEdited = cellCurrent && this.DataGridView.EditingControl != null; + Point ptCurrentCell = DataGridView.CurrentCellAddress; + bool cellCurrent = ptCurrentCell.X == ColumnIndex && ptCurrentCell.Y == rowIndex; + bool cellEdited = cellCurrent && DataGridView.EditingControl != null; bool cellSelected = (elementState & DataGridViewElementStates.Selected) != 0; - bool drawComboBox = this.DisplayStyle == DataGridViewComboBoxDisplayStyle.ComboBox && - ((this.DisplayStyleForCurrentCellOnly && cellCurrent) || !this.DisplayStyleForCurrentCellOnly); - bool drawDropDownButton = this.DisplayStyle != DataGridViewComboBoxDisplayStyle.Nothing && - ((this.DisplayStyleForCurrentCellOnly && cellCurrent) || !this.DisplayStyleForCurrentCellOnly); + bool drawComboBox = DisplayStyle == DataGridViewComboBoxDisplayStyle.ComboBox && + ((DisplayStyleForCurrentCellOnly && cellCurrent) || !DisplayStyleForCurrentCellOnly); + bool drawDropDownButton = DisplayStyle != DataGridViewComboBoxDisplayStyle.Nothing && + ((DisplayStyleForCurrentCellOnly && cellCurrent) || !DisplayStyleForCurrentCellOnly); if (DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected && !cellEdited) { - br = this.DataGridView.GetCachedBrush(cellStyle.SelectionBackColor); + br = DataGridView.GetCachedBrush(cellStyle.SelectionBackColor); } else { - br = this.DataGridView.GetCachedBrush(cellStyle.BackColor); + br = DataGridView.GetCachedBrush(cellStyle.BackColor); } if (paint && DataGridViewCell.PaintBackground(paintParts) && br.Color.A == 255 && valBounds.Width > 0 && valBounds.Height > 0) { - DataGridViewCell.PaintPadding(g, valBounds, cellStyle, br, this.DataGridView.RightToLeftInternal); + DataGridViewCell.PaintPadding(g, valBounds, cellStyle, br, DataGridView.RightToLeftInternal); } if (cellStyle.Padding != Padding.Empty) { - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { valBounds.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top); } @@ -2202,14 +2202,14 @@ private Rectangle PaintPrivate(Graphics g, { if (paintPostXPThemes) { - dropRect = new Rectangle(this.DataGridView.RightToLeftInternal ? valBounds.Left : valBounds.Right - dropWidth, + dropRect = new Rectangle(DataGridView.RightToLeftInternal ? valBounds.Left : valBounds.Right - dropWidth, valBounds.Top, dropWidth, dropHeight); } else { - dropRect = new Rectangle(this.DataGridView.RightToLeftInternal ? valBounds.Left + 1 : valBounds.Right - dropWidth - 1, + dropRect = new Rectangle(DataGridView.RightToLeftInternal ? valBounds.Left + 1 : valBounds.Right - dropWidth - 1, valBounds.Top + 1, dropWidth, dropHeight); @@ -2217,7 +2217,7 @@ private Rectangle PaintPrivate(Graphics g, } else { - dropRect = new Rectangle(this.DataGridView.RightToLeftInternal ? valBounds.Left + 2 : valBounds.Right - dropWidth - 2, + dropRect = new Rectangle(DataGridView.RightToLeftInternal ? valBounds.Left + 2 : valBounds.Right - dropWidth - 2, valBounds.Top + 2, dropWidth, dropHeight); @@ -2246,7 +2246,7 @@ private Rectangle PaintPrivate(Graphics g, { if (drawComboBox) { - DataGridViewComboBoxCellRenderer.DrawDropDownButton(g, dropRect, comboBoxState, this.DataGridView.RightToLeftInternal); + DataGridViewComboBoxCellRenderer.DrawDropDownButton(g, dropRect, comboBoxState, DataGridView.RightToLeftInternal); } else { @@ -2259,7 +2259,7 @@ private Rectangle PaintPrivate(Graphics g, // In the case of ComboBox style, background is not filled in, // in the case of DrawReadOnlyButton uses theming API to render CP_READONLY COMBOBOX part that renders the background, // this API does not have "selected" state, thus always uses BackColor - br = this.DataGridView.GetCachedBrush(cellStyle.BackColor); + br = DataGridView.GetCachedBrush(cellStyle.BackColor); } } else @@ -2461,7 +2461,7 @@ private Rectangle PaintPrivate(Graphics g, if (paintPostXPThemes) { - if (!this.DataGridView.RightToLeftInternal) + if (!DataGridView.RightToLeftInternal) { textBounds.X--; } @@ -2474,7 +2474,7 @@ private Rectangle PaintPrivate(Graphics g, { errorBounds.Width -= dropWidth; textBounds.Width -= dropWidth; - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { errorBounds.X += dropWidth; textBounds.X += dropWidth; @@ -2484,7 +2484,7 @@ private Rectangle PaintPrivate(Graphics g, { errorBounds.Width -= dropWidth + 1; textBounds.Width -= dropWidth + 1; - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { errorBounds.X += dropWidth + 1; textBounds.X += dropWidth + 1; @@ -2497,15 +2497,15 @@ private Rectangle PaintPrivate(Graphics g, if (cellCurrent && !cellEdited && DataGridViewCell.PaintFocus(paintParts) && - this.DataGridView.ShowFocusCues && - this.DataGridView.Focused && + DataGridView.ShowFocusCues && + DataGridView.Focused && paint) { // Draw focus rectangle if (paintFlat) { Rectangle focusBounds = textBounds; - if (!this.DataGridView.RightToLeftInternal) + if (!DataGridView.RightToLeftInternal) { focusBounds.X--; } @@ -2548,7 +2548,7 @@ private Rectangle PaintPrivate(Graphics g, { // Font independent margins int verticalTextMarginTop = cellStyle.WrapMode == DataGridViewTriState.True ? DATAGRIDVIEWCOMBOBOXCELL_verticalTextMarginTopWithWrapping : DATAGRIDVIEWCOMBOBOXCELL_verticalTextMarginTopWithoutWrapping; - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { textBounds.Offset(DATAGRIDVIEWCOMBOBOXCELL_horizontalTextMarginLeft, verticalTextMarginTop); textBounds.Width += 2 - DATAGRIDVIEWCOMBOBOXCELL_horizontalTextMarginLeft; @@ -2562,7 +2562,7 @@ private Rectangle PaintPrivate(Graphics g, if (textBounds.Width > 0 && textBounds.Height > 0) { - TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); + TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); if (!cellEdited && paint) { if (DataGridViewCell.PaintContentForeground(paintParts)) @@ -2595,7 +2595,7 @@ private Rectangle PaintPrivate(Graphics g, } } - if (this.DataGridView.ShowCellErrors && paint && DataGridViewCell.PaintErrorIcon(paintParts)) + if (DataGridView.ShowCellErrors && paint && DataGridViewCell.PaintErrorIcon(paintParts)) { PaintErrorIcon(g, cellStyle, rowIndex, cellBounds, errorBounds, errorText); if (cellEdited) @@ -2627,23 +2627,23 @@ public override object ParseFormattedValue(object formattedValue, { if (valueTypeConverter == null) { - if (this.ValueMemberProperty != null) + if (ValueMemberProperty != null) { - valueTypeConverter = this.ValueMemberProperty.Converter; + valueTypeConverter = ValueMemberProperty.Converter; } - else if (this.DisplayMemberProperty != null) + else if (DisplayMemberProperty != null) { - valueTypeConverter = this.DisplayMemberProperty.Converter; + valueTypeConverter = DisplayMemberProperty.Converter; } } // Find the item given its display value - if ((this.DataManager != null && - (this.DisplayMemberProperty != null || this.ValueMemberProperty != null)) || - !string.IsNullOrEmpty(this.DisplayMember) || !string.IsNullOrEmpty(this.ValueMember)) + if ((DataManager != null && + (DisplayMemberProperty != null || ValueMemberProperty != null)) || + !string.IsNullOrEmpty(DisplayMember) || !string.IsNullOrEmpty(ValueMember)) { - object value = ParseFormattedValueInternal(this.DisplayType, formattedValue, cellStyle, - formattedValueTypeConverter, this.DisplayTypeConverter); + object value = ParseFormattedValueInternal(DisplayType, formattedValue, cellStyle, + formattedValueTypeConverter, DisplayTypeConverter); object originalValue = value; if (!LookupValue(originalValue, out value)) { @@ -2653,14 +2653,14 @@ public override object ParseFormattedValue(object formattedValue, } else { - throw new FormatException(string.Format(CultureInfo.CurrentCulture, string.Format(SR.Formatter_CantConvert), value, this.DisplayType)); + throw new FormatException(string.Format(CultureInfo.CurrentCulture, string.Format(SR.Formatter_CantConvert), value, DisplayType)); } } return value; } else { - return ParseFormattedValueInternal(this.ValueType, formattedValue, cellStyle, + return ParseFormattedValueInternal(ValueType, formattedValue, cellStyle, formattedValueTypeConverter, valueTypeConverter); } } @@ -2672,25 +2672,25 @@ public override object ParseFormattedValue(object formattedValue, /// public override string ToString() { - return "DataGridViewComboBoxCell { ColumnIndex=" + this.ColumnIndex.ToString(CultureInfo.CurrentCulture) + ", RowIndex=" + this.RowIndex.ToString(CultureInfo.CurrentCulture) + " }"; + return "DataGridViewComboBoxCell { ColumnIndex=" + ColumnIndex.ToString(CultureInfo.CurrentCulture) + ", RowIndex=" + RowIndex.ToString(CultureInfo.CurrentCulture) + " }"; } private void UnwireDataSource() { - IComponent component = this.DataSource as IComponent; + IComponent component = DataSource as IComponent; if (component != null) { component.Disposed -= new EventHandler(DataSource_Disposed); } - ISupportInitializeNotification dsInit = this.DataSource as ISupportInitializeNotification; - if (dsInit != null && (this.flags & DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp) != 0x00) + ISupportInitializeNotification dsInit = DataSource as ISupportInitializeNotification; + if (dsInit != null && (flags & DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp) != 0x00) { // If we previously hooked the data source's ISupportInitializeNotification // Initialized event, then unhook it now (we don't always hook this event, // only if we needed to because the data source was previously uninitialized) dsInit.Initialized -= new EventHandler(DataSource_Initialized); - this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp); + flags = (byte)(flags & ~DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp); } } @@ -2727,11 +2727,11 @@ private IComparer Comparer { get { - if (this.comparer == null) + if (comparer == null) { - this.comparer = new ItemComparer(this.owner); + comparer = new ItemComparer(owner); } - return this.comparer; + return comparer; } } @@ -2742,7 +2742,7 @@ public int Count { get { - return this.InnerArray.Count; + return InnerArray.Count; } } @@ -2753,11 +2753,11 @@ internal ArrayList InnerArray { get { - if (this.items == null) + if (items == null) { - this.items = new ArrayList(); + items = new ArrayList(); } - return this.items; + return items; } } @@ -2803,34 +2803,34 @@ public bool IsReadOnly public int Add(object item) { //this.owner.CheckNoSharedCell(); - this.owner.CheckNoDataSource(); + owner.CheckNoDataSource(); if (item == null) { throw new ArgumentNullException(nameof(item)); } - int index = this.InnerArray.Add(item); + int index = InnerArray.Add(item); bool success = false; - if (this.owner.Sorted) + if (owner.Sorted) { try { - this.InnerArray.Sort(this.Comparer); - index = this.InnerArray.IndexOf(item); + InnerArray.Sort(Comparer); + index = InnerArray.IndexOf(item); success = true; } finally { if (!success) { - this.InnerArray.Remove(item); + InnerArray.Remove(item); } } } - this.owner.OnItemsCollectionChanged(); + owner.OnItemsCollectionChanged(); return index; } @@ -2842,17 +2842,17 @@ int IList.Add(object item) public void AddRange(params object[] items) { //this.owner.CheckNoSharedCell(); - this.owner.CheckNoDataSource(); + owner.CheckNoDataSource(); AddRangeInternal((ICollection)items); - this.owner.OnItemsCollectionChanged(); + owner.OnItemsCollectionChanged(); } public void AddRange(ObjectCollection value) { //this.owner.CheckNoSharedCell(); - this.owner.CheckNoDataSource(); + owner.CheckNoDataSource(); AddRangeInternal((ICollection)value); - this.owner.OnItemsCollectionChanged(); + owner.OnItemsCollectionChanged(); } /// @@ -2874,16 +2874,16 @@ internal void AddRangeInternal(ICollection items) } // Add everything to the collection first, then sort - this.InnerArray.AddRange(items); - if (this.owner.Sorted) + InnerArray.AddRange(items); + if (owner.Sorted) { - this.InnerArray.Sort(this.Comparer); + InnerArray.Sort(Comparer); } } internal void SortInternal() { - this.InnerArray.Sort(this.Comparer); + InnerArray.Sort(Comparer); } /// @@ -2893,29 +2893,29 @@ public virtual object this[int index] { get { - if (index < 0 || index >= this.InnerArray.Count) + if (index < 0 || index >= InnerArray.Count) { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - return this.InnerArray[index]; + return InnerArray[index]; } set { //this.owner.CheckNoSharedCell(); - this.owner.CheckNoDataSource(); + owner.CheckNoDataSource(); if (value == null) { throw new ArgumentNullException(nameof(value)); } - if (index < 0 || index >= this.InnerArray.Count) + if (index < 0 || index >= InnerArray.Count) { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - this.InnerArray[index] = value; - this.owner.OnItemsCollectionChanged(); + InnerArray[index] = value; + owner.OnItemsCollectionChanged(); } } @@ -2924,18 +2924,18 @@ public virtual object this[int index] /// public void Clear() { - if (this.InnerArray.Count > 0) + if (InnerArray.Count > 0) { //this.owner.CheckNoSharedCell(); - this.owner.CheckNoDataSource(); - this.InnerArray.Clear(); - this.owner.OnItemsCollectionChanged(); + owner.CheckNoDataSource(); + InnerArray.Clear(); + owner.OnItemsCollectionChanged(); } } internal void ClearInternal() { - this.InnerArray.Clear(); + InnerArray.Clear(); } public bool Contains(object value) @@ -2948,19 +2948,19 @@ public bool Contains(object value) /// public void CopyTo(object[] destination, int arrayIndex) { - int count = this.InnerArray.Count; + int count = InnerArray.Count; for (int i = 0; i < count; i++) { - destination[i + arrayIndex] = this.InnerArray[i]; + destination[i + arrayIndex] = InnerArray[i]; } } void ICollection.CopyTo(Array destination, int index) { - int count = this.InnerArray.Count; + int count = InnerArray.Count; for (int i = 0; i < count; i++) { - destination.SetValue(this.InnerArray[i], i + index); + destination.SetValue(InnerArray[i], i + index); } } @@ -2969,7 +2969,7 @@ void ICollection.CopyTo(Array destination, int index) /// public IEnumerator GetEnumerator() { - return this.InnerArray.GetEnumerator(); + return InnerArray.GetEnumerator(); } public int IndexOf(object value) @@ -2978,7 +2978,7 @@ public int IndexOf(object value) { throw new ArgumentNullException(nameof(value)); } - return this.InnerArray.IndexOf(value); + return InnerArray.IndexOf(value); } /// @@ -2991,28 +2991,28 @@ public int IndexOf(object value) public void Insert(int index, object item) { //this.owner.CheckNoSharedCell(); - this.owner.CheckNoDataSource(); + owner.CheckNoDataSource(); if (item == null) { throw new ArgumentNullException(nameof(item)); } - if (index < 0 || index > this.InnerArray.Count) + if (index < 0 || index > InnerArray.Count) { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), nameof(index))); } // If the combo box is sorted, then just treat this like an add // because we are going to twiddle the index anyway. - if (this.owner.Sorted) + if (owner.Sorted) { Add(item); } else { - this.InnerArray.Insert(index, item); - this.owner.OnItemsCollectionChanged(); + InnerArray.Insert(index, item); + owner.OnItemsCollectionChanged(); } } @@ -3022,7 +3022,7 @@ public void Insert(int index, object item) /// public void Remove(object value) { - int index = this.InnerArray.IndexOf(value); + int index = InnerArray.IndexOf(value); if (index != -1) { @@ -3036,14 +3036,14 @@ public void Remove(object value) public void RemoveAt(int index) { //this.owner.CheckNoSharedCell(); - this.owner.CheckNoDataSource(); + owner.CheckNoDataSource(); - if (index < 0 || index >= this.InnerArray.Count) + if (index < 0 || index >= InnerArray.Count) { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - this.InnerArray.RemoveAt(index); - this.owner.OnItemsCollectionChanged(); + InnerArray.RemoveAt(index); + owner.OnItemsCollectionChanged(); } } // end ObjectCollection @@ -3070,8 +3070,8 @@ public int Compare(object item1, object item2) { return 1; //item2 is null, so item 1 is greater } - string itemName1 = this.dataGridViewComboBoxCell.GetItemDisplayText(item1); - string itemName2 = this.dataGridViewComboBoxCell.GetItemDisplayText(item2); + string itemName1 = dataGridViewComboBoxCell.GetItemDisplayText(item1); + string itemName2 = dataGridViewComboBoxCell.GetItemDisplayText(item2); CompareInfo compInfo = Application.CurrentCulture.CompareInfo; return compInfo.Compare(itemName1, itemName2, CompareOptions.StringSort); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxColumn.cs index 0a2cd860c07..27239030b83 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxColumn.cs @@ -35,25 +35,25 @@ public bool AutoComplete { get { - if (this.ComboBoxCellTemplate == null) + if (ComboBoxCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return this.ComboBoxCellTemplate.AutoComplete; + return ComboBoxCellTemplate.AutoComplete; } set { - if (this.AutoComplete != value) + if (AutoComplete != value) { - this.ComboBoxCellTemplate.AutoComplete = value; - if (this.DataGridView != null) + ComboBoxCellTemplate.AutoComplete = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; + DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.AutoComplete = value; @@ -93,7 +93,7 @@ private DataGridViewComboBoxCell ComboBoxCellTemplate { get { - return (DataGridViewComboBoxCell)this.CellTemplate; + return (DataGridViewComboBoxCell)CellTemplate; } } @@ -108,33 +108,33 @@ public object DataSource { get { - if (this.ComboBoxCellTemplate == null) + if (ComboBoxCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return this.ComboBoxCellTemplate.DataSource; + return ComboBoxCellTemplate.DataSource; } set { - if (this.ComboBoxCellTemplate == null) + if (ComboBoxCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - this.ComboBoxCellTemplate.DataSource = value; - if (this.DataGridView != null) + ComboBoxCellTemplate.DataSource = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; + DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.DataSource = value; } } - this.DataGridView.OnColumnCommonChange(this.Index); + DataGridView.OnColumnCommonChange(Index); } } } @@ -150,33 +150,33 @@ public string DisplayMember { get { - if (this.ComboBoxCellTemplate == null) + if (ComboBoxCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return this.ComboBoxCellTemplate.DisplayMember; + return ComboBoxCellTemplate.DisplayMember; } set { - if (this.ComboBoxCellTemplate == null) + if (ComboBoxCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - this.ComboBoxCellTemplate.DisplayMember = value; - if (this.DataGridView != null) + ComboBoxCellTemplate.DisplayMember = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; + DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.DisplayMember = value; } } - this.DataGridView.OnColumnCommonChange(this.Index); + DataGridView.OnColumnCommonChange(Index); } } } @@ -190,34 +190,34 @@ public DataGridViewComboBoxDisplayStyle DisplayStyle { get { - if (this.ComboBoxCellTemplate == null) + if (ComboBoxCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return this.ComboBoxCellTemplate.DisplayStyle; + return ComboBoxCellTemplate.DisplayStyle; } set { - if (this.ComboBoxCellTemplate == null) + if (ComboBoxCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - this.ComboBoxCellTemplate.DisplayStyle = value; - if (this.DataGridView != null) + ComboBoxCellTemplate.DisplayStyle = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; + DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.DisplayStyleInternal = value; } } // Calling InvalidateColumn instead of OnColumnCommonChange because DisplayStyle does not affect preferred size. - this.DataGridView.InvalidateColumn(this.Index); + DataGridView.InvalidateColumn(Index); } } } @@ -231,34 +231,34 @@ public bool DisplayStyleForCurrentCellOnly { get { - if (this.ComboBoxCellTemplate == null) + if (ComboBoxCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return this.ComboBoxCellTemplate.DisplayStyleForCurrentCellOnly; + return ComboBoxCellTemplate.DisplayStyleForCurrentCellOnly; } set { - if (this.ComboBoxCellTemplate == null) + if (ComboBoxCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - this.ComboBoxCellTemplate.DisplayStyleForCurrentCellOnly = value; - if (this.DataGridView != null) + ComboBoxCellTemplate.DisplayStyleForCurrentCellOnly = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; + DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.DisplayStyleForCurrentCellOnlyInternal = value; } } // Calling InvalidateColumn instead of OnColumnCommonChange because DisplayStyleForCurrentCellOnly does not affect preferred size. - this.DataGridView.InvalidateColumn(this.Index); + DataGridView.InvalidateColumn(Index); } } } @@ -272,25 +272,25 @@ public int DropDownWidth { get { - if (this.ComboBoxCellTemplate == null) + if (ComboBoxCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return this.ComboBoxCellTemplate.DropDownWidth; + return ComboBoxCellTemplate.DropDownWidth; } set { - if (this.DropDownWidth != value) + if (DropDownWidth != value) { - this.ComboBoxCellTemplate.DropDownWidth = value; - if (this.DataGridView != null) + ComboBoxCellTemplate.DropDownWidth = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; + DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.DropDownWidth = value; @@ -310,31 +310,31 @@ public FlatStyle FlatStyle { get { - if (this.CellTemplate == null) + if (CellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return ((DataGridViewComboBoxCell)this.CellTemplate).FlatStyle; + return ((DataGridViewComboBoxCell)CellTemplate).FlatStyle; } set { - if (this.FlatStyle != value) + if (FlatStyle != value) { - ((DataGridViewComboBoxCell)this.CellTemplate).FlatStyle = value; - if (this.DataGridView != null) + ((DataGridViewComboBoxCell)CellTemplate).FlatStyle = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; + DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.FlatStyleInternal = value; } } - this.DataGridView.OnColumnCommonChange(this.Index); + DataGridView.OnColumnCommonChange(Index); } } } @@ -350,11 +350,11 @@ public DataGridViewComboBoxCell.ObjectCollection Items { get { - if (this.ComboBoxCellTemplate == null) + if (ComboBoxCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return this.ComboBoxCellTemplate.GetItems(this.DataGridView); + return ComboBoxCellTemplate.GetItems(DataGridView); } } @@ -369,33 +369,33 @@ public string ValueMember { get { - if (this.ComboBoxCellTemplate == null) + if (ComboBoxCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return this.ComboBoxCellTemplate.ValueMember; + return ComboBoxCellTemplate.ValueMember; } set { - if (this.ComboBoxCellTemplate == null) + if (ComboBoxCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - this.ComboBoxCellTemplate.ValueMember = value; - if (this.DataGridView != null) + ComboBoxCellTemplate.ValueMember = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; + DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.ValueMember = value; } } - this.DataGridView.OnColumnCommonChange(this.Index); + DataGridView.OnColumnCommonChange(Index); } } } @@ -409,25 +409,25 @@ public int MaxDropDownItems { get { - if (this.ComboBoxCellTemplate == null) + if (ComboBoxCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return this.ComboBoxCellTemplate.MaxDropDownItems; + return ComboBoxCellTemplate.MaxDropDownItems; } set { - if (this.MaxDropDownItems != value) + if (MaxDropDownItems != value) { - this.ComboBoxCellTemplate.MaxDropDownItems = value; - if (this.DataGridView != null) + ComboBoxCellTemplate.MaxDropDownItems = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; + DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.MaxDropDownItems = value; @@ -447,25 +447,25 @@ public bool Sorted { get { - if (this.ComboBoxCellTemplate == null) + if (ComboBoxCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return this.ComboBoxCellTemplate.Sorted; + return ComboBoxCellTemplate.Sorted; } set { - if (this.Sorted != value) + if (Sorted != value) { - this.ComboBoxCellTemplate.Sorted = value; - if (this.DataGridView != null) + ComboBoxCellTemplate.Sorted = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; + DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.Sorted = value; @@ -479,7 +479,7 @@ public bool Sorted public override object Clone() { DataGridViewComboBoxColumn dataGridViewColumn; - Type thisType = this.GetType(); + Type thisType = GetType(); if (thisType == columnType) //performance improvement { @@ -503,22 +503,22 @@ internal void OnItemsCollectionChanged() { // Items collection of the CellTemplate was changed. // Update the items collection of each existing DataGridViewComboBoxCell in the column. - if (this.DataGridView != null) + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; - object[] items = ((DataGridViewComboBoxCell)this.CellTemplate).Items.InnerArray.ToArray(); + object[] items = ((DataGridViewComboBoxCell)CellTemplate).Items.InnerArray.ToArray(); for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; + DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.Items.ClearInternal(); dataGridViewCell.Items.AddRangeInternal(items); } } - this.DataGridView.OnColumnCommonChange(this.Index); + DataGridView.OnColumnCommonChange(Index); } } @@ -529,9 +529,9 @@ public override string ToString() { StringBuilder sb = new StringBuilder(64); sb.Append("DataGridViewComboBoxColumn { Name="); - sb.Append(this.Name); + sb.Append(Name); sb.Append(", Index="); - sb.Append(this.Index.ToString(CultureInfo.CurrentCulture)); + sb.Append(Index.ToString(CultureInfo.CurrentCulture)); sb.Append(" }"); return sb.ToString(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxEditingControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxEditingControl.cs index 3a938c638b4..7ed70c4925e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxEditingControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxEditingControl.cs @@ -22,7 +22,7 @@ public class DataGridViewComboBoxEditingControl : ComboBox, IDataGridViewEditing public DataGridViewComboBoxEditingControl() : base() { - this.TabStop = false; + TabStop = false; } protected override AccessibleObject CreateAccessibilityInstance() @@ -36,11 +36,11 @@ public virtual DataGridView EditingControlDataGridView { get { - return this.dataGridView; + return dataGridView; } set { - this.dataGridView = value; + dataGridView = value; } } @@ -55,10 +55,10 @@ public virtual object EditingControlFormattedValue string valueStr = value as string; if (valueStr != null) { - this.Text = valueStr; - if (string.Compare(valueStr, this.Text, true, CultureInfo.CurrentCulture) != 0) + Text = valueStr; + if (string.Compare(valueStr, Text, true, CultureInfo.CurrentCulture) != 0) { - this.SelectedIndex = -1; + SelectedIndex = -1; } } } @@ -68,11 +68,11 @@ public virtual int EditingControlRowIndex { get { - return this.rowIndex; + return rowIndex; } set { - this.rowIndex = value; + rowIndex = value; } } @@ -80,11 +80,11 @@ public virtual bool EditingControlValueChanged { get { - return this.valueChanged; + return valueChanged; } set { - this.valueChanged = value; + valueChanged = value; } } @@ -106,26 +106,26 @@ public virtual bool RepositionEditingControlOnValueChange public virtual void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle) { - this.Font = dataGridViewCellStyle.Font; + Font = dataGridViewCellStyle.Font; if (dataGridViewCellStyle.BackColor.A < 255) { // Our ComboBox does not support transparent back colors Color opaqueBackColor = Color.FromArgb(255, dataGridViewCellStyle.BackColor); - this.BackColor = opaqueBackColor; - this.dataGridView.EditingPanel.BackColor = opaqueBackColor; + BackColor = opaqueBackColor; + dataGridView.EditingPanel.BackColor = opaqueBackColor; } else { - this.BackColor = dataGridViewCellStyle.BackColor; + BackColor = dataGridViewCellStyle.BackColor; } - this.ForeColor = dataGridViewCellStyle.ForeColor; + ForeColor = dataGridViewCellStyle.ForeColor; } public virtual bool EditingControlWantsInputKey(Keys keyData, bool dataGridViewWantsInputKey) { if ((keyData & Keys.KeyCode) == Keys.Down || (keyData & Keys.KeyCode) == Keys.Up || - (this.DroppedDown && ((keyData & Keys.KeyCode) == Keys.Escape) || (keyData & Keys.KeyCode) == Keys.Enter)) + (DroppedDown && ((keyData & Keys.KeyCode) == Keys.Escape) || (keyData & Keys.KeyCode) == Keys.Enter)) { return true; } @@ -134,7 +134,7 @@ public virtual bool EditingControlWantsInputKey(Keys keyData, bool dataGridViewW public virtual object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context) { - return this.Text; + return Text; } public virtual void PrepareEditingControlForEdit(bool selectAll) @@ -147,14 +147,14 @@ public virtual void PrepareEditingControlForEdit(bool selectAll) private void NotifyDataGridViewOfValueChange() { - this.valueChanged = true; - this.dataGridView.NotifyCurrentCellDirty(true); + valueChanged = true; + dataGridView.NotifyCurrentCellDirty(true); } protected override void OnSelectedIndexChanged(EventArgs e) { base.OnSelectedIndexChanged(e); - if (this.SelectedIndex != -1) + if (SelectedIndex != -1) { NotifyDataGridViewOfValueChange(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewControlCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewControlCollection.cs index 266b59fb9f9..59c84af0ded 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewControlCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewControlCollection.cs @@ -36,7 +36,7 @@ public void Insert(int index, Control value) public override void Remove(Control value) { - if (value != owner.horizScrollBar && value != owner.vertScrollBar && value != this.owner.editingPanel) + if (value != owner.horizScrollBar && value != owner.vertScrollBar && value != owner.editingPanel) { base.Remove(value); } @@ -49,9 +49,9 @@ internal void RemoveInternal(Control value) public override void Clear() { - for (int i = 0; i < this.Count; i++) + for (int i = 0; i < Count; i++) { - if (this[i] == this.owner.horizScrollBar || this[i] == this.owner.vertScrollBar || this[i] == this.owner.editingPanel) + if (this[i] == owner.horizScrollBar || this[i] == owner.vertScrollBar || this[i] == owner.editingPanel) { continue; } @@ -63,4 +63,4 @@ public override void Clear() } } } -} \ No newline at end of file +} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewDataConnection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewDataConnection.cs index 85392257541..6f5275ff2b8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewDataConnection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewDataConnection.cs @@ -82,17 +82,17 @@ internal class DataGridViewDataConnection public DataGridViewDataConnection(DataGridView owner) { this.owner = owner; - this.dataConnectionState = new BitVector32(DATACONNECTIONSTATE_finishedAddNew); + dataConnectionState = new BitVector32(DATACONNECTIONSTATE_finishedAddNew); } public bool AllowAdd { get { - if (this.currencyManager != null) + if (currencyManager != null) { // we only allow to add new rows on an IBindingList - return (this.currencyManager.List is IBindingList) && this.currencyManager.AllowAdd && ((IBindingList)this.currencyManager.List).SupportsChangeNotification; + return (currencyManager.List is IBindingList) && currencyManager.AllowAdd && ((IBindingList)currencyManager.List).SupportsChangeNotification; } else { @@ -105,9 +105,9 @@ public bool AllowEdit { get { - if (this.currencyManager != null) + if (currencyManager != null) { - return this.currencyManager.AllowEdit; + return currencyManager.AllowEdit; } else { @@ -120,10 +120,10 @@ public bool AllowRemove { get { - if (this.currencyManager != null) + if (currencyManager != null) { // we only allow deletion on an IBindingList - return (this.currencyManager.List is IBindingList) && this.currencyManager.AllowRemove && ((IBindingList)this.currencyManager.List).SupportsChangeNotification; + return (currencyManager.List is IBindingList) && currencyManager.AllowRemove && ((IBindingList)currencyManager.List).SupportsChangeNotification; } else { @@ -136,7 +136,7 @@ public bool CancellingRowEdit { get { - return this.dataConnectionState[DATACONNECTIONSTATE_cancellingRowEdit]; + return dataConnectionState[DATACONNECTIONSTATE_cancellingRowEdit]; } } @@ -144,7 +144,7 @@ public CurrencyManager CurrencyManager { get { - return this.currencyManager; + return currencyManager; } } @@ -152,7 +152,7 @@ public string DataMember { get { - return this.dataMember; + return dataMember; } } @@ -160,7 +160,7 @@ public object DataSource { get { - return this.dataSource; + return dataSource; } } @@ -168,11 +168,11 @@ public bool DoNotChangePositionInTheCurrencyManager { get { - return this.dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheCurrencyManager]; + return dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheCurrencyManager]; } set { - this.dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheCurrencyManager] = value; + dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheCurrencyManager] = value; } } @@ -180,7 +180,7 @@ public bool InterestedInRowEvents { get { - return this.dataConnectionState[DATACONNECTIONSTATE_interestedInRowEvents]; + return dataConnectionState[DATACONNECTIONSTATE_interestedInRowEvents]; } } @@ -188,9 +188,9 @@ public IList List { get { - if (this.currencyManager != null) + if (currencyManager != null) { - return this.currencyManager.List; + return currencyManager.List; } else { @@ -203,7 +203,7 @@ public bool ListWasReset { get { - return this.dataConnectionState[DATACONNECTIONSTATE_listWasReset]; + return dataConnectionState[DATACONNECTIONSTATE_listWasReset]; } } @@ -214,8 +214,8 @@ public bool PositionChangingOutsideDataGridView // DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl means that the data grid view control // manages the position change // so if DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl is true then the data grid view knows about the position change - return !this.dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl] && - this.dataConnectionState[DATACONNECTIONSTATE_positionChangingInCurrencyManager]; + return !dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl] && + dataConnectionState[DATACONNECTIONSTATE_positionChangingInCurrencyManager]; } } @@ -223,7 +223,7 @@ public bool ProcessingListChangedEvent { get { - return this.dataConnectionState[DATACONNECTIONSTATE_processingListChangedEvent]; + return dataConnectionState[DATACONNECTIONSTATE_processingListChangedEvent]; } } @@ -231,7 +231,7 @@ public bool ProcessingMetaDataChanges { get { - return this.dataConnectionState[DATACONNECTIONSTATE_processingMetaDataChanges]; + return dataConnectionState[DATACONNECTIONSTATE_processingMetaDataChanges]; } } @@ -239,43 +239,43 @@ public bool RestoreRow { get { - Debug.Assert(this.dataConnectionState[DATACONNECTIONSTATE_cancellingRowEdit]); - return this.dataConnectionState[DATACONNECTIONSTATE_restoreRow]; + Debug.Assert(dataConnectionState[DATACONNECTIONSTATE_cancellingRowEdit]); + return dataConnectionState[DATACONNECTIONSTATE_restoreRow]; } } public void AddNew() { - if (this.currencyManager != null) + if (currencyManager != null) { // don't call AddNew on a suspended currency manager. - if (!this.currencyManager.ShouldBind) + if (!currencyManager.ShouldBind) { return; } - Debug.Assert(this.currencyManager.AllowAdd, "why did we call AddNew on the currency manager when the currency manager does not allow new rows?"); - this.dataConnectionState[DATACONNECTIONSTATE_finishedAddNew] = false; + Debug.Assert(currencyManager.AllowAdd, "why did we call AddNew on the currency manager when the currency manager does not allow new rows?"); + dataConnectionState[DATACONNECTIONSTATE_finishedAddNew] = false; - this.dataConnectionState[DATACONNECTIONSTATE_inEndCurrentEdit] = true; + dataConnectionState[DATACONNECTIONSTATE_inEndCurrentEdit] = true; try { - this.currencyManager.EndCurrentEdit(); + currencyManager.EndCurrentEdit(); } finally { - this.dataConnectionState[DATACONNECTIONSTATE_inEndCurrentEdit] = false; + dataConnectionState[DATACONNECTIONSTATE_inEndCurrentEdit] = false; } - this.dataConnectionState[DATACONNECTIONSTATE_inAddNew] = true; + dataConnectionState[DATACONNECTIONSTATE_inAddNew] = true; try { - this.currencyManager.AddNew(); + currencyManager.AddNew(); } finally { - this.dataConnectionState[DATACONNECTIONSTATE_inAddNew] = false; + dataConnectionState[DATACONNECTIONSTATE_inAddNew] = false; } } } @@ -300,7 +300,7 @@ public void AddNew() // public void ApplySortingInformationFromBackEnd() { - if (this.currencyManager == null) + if (currencyManager == null) { return; } @@ -314,25 +314,25 @@ public void ApplySortingInformationFromBackEnd() // This will have the side effect of setting DataGridView::SortedColumn to null and setting DataGridView::SortOrder to null. if (sortField == null) { - for (int i = 0; i < this.owner.Columns.Count; i++) + for (int i = 0; i < owner.Columns.Count; i++) { - if (this.owner.Columns[i].IsDataBound) + if (owner.Columns[i].IsDataBound) { - this.owner.Columns[i].HeaderCell.SortGlyphDirection = SortOrder.None; + owner.Columns[i].HeaderCell.SortGlyphDirection = SortOrder.None; } } - this.owner.sortedColumn = null; - this.owner.sortOrder = SortOrder.None; + owner.sortedColumn = null; + owner.sortOrder = SortOrder.None; // now return; return; } bool setSortedColumnYet = false; - for (int i = 0; i < this.owner.Columns.Count; i++) + for (int i = 0; i < owner.Columns.Count; i++) { - DataGridViewColumn column = this.owner.Columns[i]; + DataGridViewColumn column = owner.Columns[i]; if (!column.IsDataBound) { continue; @@ -348,10 +348,10 @@ public void ApplySortingInformationFromBackEnd() // Set the sorted column on the dataGridView only if the sorted Field is set outside the dataGridView. // If the sortedField is set inside the dataGridView ( either by user clicking on a ColumnHeader or by user calling DGV.Sort(...) // then we don't want to tamper w/ it. - if (!setSortedColumnYet && !this.owner.InSortOperation) + if (!setSortedColumnYet && !owner.InSortOperation) { - this.owner.sortedColumn = column; - this.owner.sortOrder = sortOrder; + owner.sortedColumn = column; + owner.sortOrder = sortOrder; setSortedColumnYet = true; } @@ -367,23 +367,23 @@ public void ApplySortingInformationFromBackEnd() public TypeConverter BoundColumnConverter(int boundColumnIndex) { - Debug.Assert(this.props != null); - return this.props[boundColumnIndex].Converter; + Debug.Assert(props != null); + return props[boundColumnIndex].Converter; } // given a data field name we get the bound index public int BoundColumnIndex(string dataPropertyName) { - if (this.props == null) + if (props == null) { return -1; } int ret = -1; - for (int i = 0; i < this.props.Count; i++) + for (int i = 0; i < props.Count; i++) { - if (string.Compare(this.props[i].Name, dataPropertyName, true /*ignoreCase*/, CultureInfo.InvariantCulture) == 0) + if (string.Compare(props[i].Name, dataPropertyName, true /*ignoreCase*/, CultureInfo.InvariantCulture) == 0) { ret = i; break; @@ -395,7 +395,7 @@ public int BoundColumnIndex(string dataPropertyName) public SortOrder BoundColumnSortOrder(int boundColumnIndex) { - IBindingList ibl = this.currencyManager != null ? this.currencyManager.List as IBindingList : null; + IBindingList ibl = currencyManager != null ? currencyManager.List as IBindingList : null; IBindingListView iblv = ibl != null ? ibl as IBindingListView : null; if (ibl == null || !ibl.SupportsSorting || !ibl.IsSorted) @@ -414,7 +414,7 @@ public SortOrder BoundColumnSortOrder(int boundColumnIndex) return SortOrder.None; } - if (string.Compare(this.props[boundColumnIndex].Name, sortProperty.Name, true /*ignoreCase*/, CultureInfo.InvariantCulture) == 0) + if (string.Compare(props[boundColumnIndex].Name, sortProperty.Name, true /*ignoreCase*/, CultureInfo.InvariantCulture) == 0) { return sortOrder; } @@ -426,8 +426,8 @@ public SortOrder BoundColumnSortOrder(int boundColumnIndex) public Type BoundColumnValueType(int boundColumnIndex) { - Debug.Assert(this.props != null); - return this.props[boundColumnIndex].PropertyType; + Debug.Assert(props != null); + return props[boundColumnIndex].PropertyType; } #if DEBUG @@ -438,30 +438,30 @@ private void CheckRowCount(ListChangedEventArgs e) return; } - int dataGridViewRowsCount = this.owner.Rows.Count; + int dataGridViewRowsCount = owner.Rows.Count; - Debug.Assert(DataBoundRowsCount() == this.currencyManager.List.Count || (this.owner.Columns.Count == 0 && dataGridViewRowsCount == 0), + Debug.Assert(DataBoundRowsCount() == currencyManager.List.Count || (owner.Columns.Count == 0 && dataGridViewRowsCount == 0), "there should be the same number of rows in the dataGridView's Row Collection as in the back end list"); } #endif // DEBUG private void currencyManager_ListChanged(object sender, ListChangedEventArgs e) { - Debug.Assert(sender == this.currencyManager, "did we forget to unregister our ListChanged event handler?"); + Debug.Assert(sender == currencyManager, "did we forget to unregister our ListChanged event handler?"); - this.dataConnectionState[DATACONNECTIONSTATE_processingListChangedEvent] = true; + dataConnectionState[DATACONNECTIONSTATE_processingListChangedEvent] = true; try { ProcessListChanged(e); } finally { - this.dataConnectionState[DATACONNECTIONSTATE_processingListChangedEvent] = false; + dataConnectionState[DATACONNECTIONSTATE_processingListChangedEvent] = false; } - this.owner.OnDataBindingComplete(e.ListChangedType); + owner.OnDataBindingComplete(e.ListChangedType); - this.lastListCount = this.currencyManager.Count; + lastListCount = currencyManager.Count; #if DEBUG CheckRowCount(e); @@ -474,30 +474,30 @@ private void ProcessListChanged(ListChangedEventArgs e) e.ListChangedType == System.ComponentModel.ListChangedType.PropertyDescriptorDeleted || e.ListChangedType == System.ComponentModel.ListChangedType.PropertyDescriptorChanged) { - this.dataConnectionState[DATACONNECTIONSTATE_processingMetaDataChanges] = true; + dataConnectionState[DATACONNECTIONSTATE_processingMetaDataChanges] = true; try { DataSourceMetaDataChanged(); } finally { - this.dataConnectionState[DATACONNECTIONSTATE_processingMetaDataChanges] = false; + dataConnectionState[DATACONNECTIONSTATE_processingMetaDataChanges] = false; } return; } - Debug.Assert(!this.dataConnectionState[DATACONNECTIONSTATE_inAddNew] || !this.dataConnectionState[DATACONNECTIONSTATE_finishedAddNew], + Debug.Assert(!dataConnectionState[DATACONNECTIONSTATE_inAddNew] || !dataConnectionState[DATACONNECTIONSTATE_finishedAddNew], "if inAddNew is true then finishedAddNew should be false"); // The value of AllowUserToAddRowsInternal changed under the DataGridView. // Recreate the rows and return. - if (this.dataConnectionState[DATACONNECTIONSTATE_cachedAllowUserToAddRowsInternal] != this.owner.AllowUserToAddRowsInternal) + if (dataConnectionState[DATACONNECTIONSTATE_cachedAllowUserToAddRowsInternal] != owner.AllowUserToAddRowsInternal) { - this.dataConnectionState[DATACONNECTIONSTATE_listWasReset] = true; + dataConnectionState[DATACONNECTIONSTATE_listWasReset] = true; try { - this.owner.RefreshRows(!this.owner.InSortOperation /*scrollIntoView*/); - this.owner.PushAllowUserToAddRows(); + owner.RefreshRows(!owner.InSortOperation /*scrollIntoView*/); + owner.PushAllowUserToAddRows(); } finally { @@ -509,19 +509,19 @@ private void ProcessListChanged(ListChangedEventArgs e) // if the list changed the AddNew and we did not finish the AddNew operation then // finish it now and return - if (!this.dataConnectionState[DATACONNECTIONSTATE_finishedAddNew] && this.owner.newRowIndex == e.NewIndex) + if (!dataConnectionState[DATACONNECTIONSTATE_finishedAddNew] && owner.newRowIndex == e.NewIndex) { - Debug.Assert(this.owner.AllowUserToAddRowsInternal, "how did we start the add new transaction when the AllowUserToAddRowsInternal is false?"); + Debug.Assert(owner.AllowUserToAddRowsInternal, "how did we start the add new transaction when the AllowUserToAddRowsInternal is false?"); if (e.ListChangedType == ListChangedType.ItemAdded) { - if (this.dataConnectionState[DATACONNECTIONSTATE_inAddNew]) + if (dataConnectionState[DATACONNECTIONSTATE_inAddNew]) { // still processing CurrencyManager::AddNew // nothing to do return; } - if (this.dataConnectionState[DATACONNECTIONSTATE_rowValidatingInAddNew]) + if (dataConnectionState[DATACONNECTIONSTATE_rowValidatingInAddNew]) { // DataGridView validation commited the AddNewRow to the back end // DataGridView took care of newRowIndex, adding a new DataGridViewRow, etc @@ -530,50 +530,50 @@ private void ProcessListChanged(ListChangedEventArgs e) } // We got a ListChangedType.ItemAdded event outside row validation and outside CurrencyManager::AddNew - if (this.owner.Columns.Count > 0) + if (owner.Columns.Count > 0) { // add rows until the back end and the DGV have the same number of bound rows. do { // the new row becomes a regular row and a "new" new row is appended - this.owner.newRowIndex = -1; - this.owner.AddNewRow(false /* createdByEditing */); - } while (DataBoundRowsCount() < this.currencyManager.Count); + owner.newRowIndex = -1; + owner.AddNewRow(false /* createdByEditing */); + } while (DataBoundRowsCount() < currencyManager.Count); } - this.dataConnectionState[DATACONNECTIONSTATE_finishedAddNew] = true; + dataConnectionState[DATACONNECTIONSTATE_finishedAddNew] = true; MatchCurrencyManagerPosition(true /*scrollIntoView*/, true /*clearSelection*/); return; } else if (e.ListChangedType == ListChangedType.ItemDeleted) { - if (this.dataConnectionState[DATACONNECTIONSTATE_cancellingRowEdit]) + if (dataConnectionState[DATACONNECTIONSTATE_cancellingRowEdit]) { // 'add new row' was discarded, bring back the new row default values. - this.owner.PopulateNewRowWithDefaultValues(); + owner.PopulateNewRowWithDefaultValues(); } - else if (this.dataConnectionState[DATACONNECTIONSTATE_inEndCurrentEdit] || - this.dataConnectionState[DATACONNECTIONSTATE_inAddNew]) + else if (dataConnectionState[DATACONNECTIONSTATE_inEndCurrentEdit] || + dataConnectionState[DATACONNECTIONSTATE_inAddNew]) { // A row was deleted while the DataGridView control asked for a new row. // Recreate the data grid view rows. - this.dataConnectionState[DATACONNECTIONSTATE_listWasReset] = true; + dataConnectionState[DATACONNECTIONSTATE_listWasReset] = true; try { - this.owner.RefreshRows(!this.owner.InSortOperation /*scrollIntoView*/); - this.owner.PushAllowUserToAddRows(); + owner.RefreshRows(!owner.InSortOperation /*scrollIntoView*/); + owner.PushAllowUserToAddRows(); } finally { - this.dataConnectionState[DATACONNECTIONSTATE_listWasReset] = false; + dataConnectionState[DATACONNECTIONSTATE_listWasReset] = false; } } - else if (this.dataConnectionState[DATACONNECTIONSTATE_inDeleteOperation] && this.currencyManager.List.Count == 0) + else if (dataConnectionState[DATACONNECTIONSTATE_inDeleteOperation] && currencyManager.List.Count == 0) { // if System.Data.DataView was in AddNew transaction and we delete all the rows in the System.Data.DataView // then System.Data.DataView will close the AddNew transaction under us // start another AddNew transaction on the back end - this.AddNew(); + AddNew(); } } @@ -585,26 +585,26 @@ private void ProcessListChanged(ListChangedEventArgs e) // we received an ListChangedType.ItemAdded and our list has exactly the same number of rows as the back-end. // return. if (e.ListChangedType == ListChangedType.ItemAdded && - this.currencyManager.List.Count == (this.owner.AllowUserToAddRowsInternal ? this.owner.Rows.Count - 1 : this.owner.Rows.Count)) + currencyManager.List.Count == (owner.AllowUserToAddRowsInternal ? owner.Rows.Count - 1 : owner.Rows.Count)) { - if (this.dataConnectionState[DATACONNECTIONSTATE_inDeleteOperation] && this.dataConnectionState[DATACONNECTIONSTATE_didNotDeleteRowFromDataGridView]) + if (dataConnectionState[DATACONNECTIONSTATE_inDeleteOperation] && dataConnectionState[DATACONNECTIONSTATE_didNotDeleteRowFromDataGridView]) { // we received a ListChangedType.ItemAdded while we were deleting rows from the back end // and we stil haven't removed a row from the data grid view // System.Data.DataView started an AddNew transaction as a result of deleting rows // mark the state as itemAddedInDeleteOperation - this.dataConnectionState[DATACONNECTIONSTATE_itemAddedInDeleteOperation] = true; + dataConnectionState[DATACONNECTIONSTATE_itemAddedInDeleteOperation] = true; // The DGV gets in this situation when the user deletes the last row in a Master table. // At this point, the Child table forces an AddNew on the Master Table. // See comments where we declare _itemAddedInDeleteOperation"); // - Debug.Assert(this.currencyManager.List.Count == 1); + Debug.Assert(currencyManager.List.Count == 1); // if we were on an AddNew transaction then the MASTER table would have had more than 1 row. // So the Child table should not have forcefully added a row on the MASTER table"); // - Debug.Assert(this.dataConnectionState[DATACONNECTIONSTATE_finishedAddNew]); + Debug.Assert(dataConnectionState[DATACONNECTIONSTATE_finishedAddNew]); } return; @@ -614,32 +614,32 @@ private void ProcessListChanged(ListChangedEventArgs e) // don't do anything - this is the equivalent of removing the row that was added before if (e.ListChangedType == ListChangedType.ItemDeleted) { - if (this.dataConnectionState[DATACONNECTIONSTATE_inDeleteOperation] && - this.dataConnectionState[DATACONNECTIONSTATE_itemAddedInDeleteOperation] && - this.dataConnectionState[DATACONNECTIONSTATE_didNotDeleteRowFromDataGridView]) + if (dataConnectionState[DATACONNECTIONSTATE_inDeleteOperation] && + dataConnectionState[DATACONNECTIONSTATE_itemAddedInDeleteOperation] && + dataConnectionState[DATACONNECTIONSTATE_didNotDeleteRowFromDataGridView]) { // we removed the item that was added during the delete operation - this.dataConnectionState[DATACONNECTIONSTATE_itemAddedInDeleteOperation] = false; - Debug.Assert(this.currencyManager.List.Count == 0, "we deleted the row that the Child table forcefully added"); + dataConnectionState[DATACONNECTIONSTATE_itemAddedInDeleteOperation] = false; + Debug.Assert(currencyManager.List.Count == 0, "we deleted the row that the Child table forcefully added"); } - else if (!this.dataConnectionState[DATACONNECTIONSTATE_finishedAddNew] && - this.dataConnectionState[DATACONNECTIONSTATE_inEndCurrentEdit]) + else if (!dataConnectionState[DATACONNECTIONSTATE_finishedAddNew] && + dataConnectionState[DATACONNECTIONSTATE_inEndCurrentEdit]) { // EndCurrentEdit caused an item to be deleted while in AddNew. // Recreate the rows. - this.dataConnectionState[DATACONNECTIONSTATE_listWasReset] = true; + dataConnectionState[DATACONNECTIONSTATE_listWasReset] = true; try { - this.owner.RefreshRows(!this.owner.InSortOperation /*scrollIntoView*/); - this.owner.PushAllowUserToAddRows(); + owner.RefreshRows(!owner.InSortOperation /*scrollIntoView*/); + owner.PushAllowUserToAddRows(); } finally { - this.dataConnectionState[DATACONNECTIONSTATE_listWasReset] = false; + dataConnectionState[DATACONNECTIONSTATE_listWasReset] = false; } return; } - else if (this.currencyManager.List.Count == DataBoundRowsCount()) + else if (currencyManager.List.Count == DataBoundRowsCount()) { return; } @@ -647,26 +647,26 @@ private void ProcessListChanged(ListChangedEventArgs e) // when we get the ListChanged notification the position in the currency manager already changed // so do not change the position when we get the RowEnter event - this.dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheCurrencyManager] = true; + dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheCurrencyManager] = true; try { switch (e.ListChangedType) { case ListChangedType.Reset: - this.dataConnectionState[DATACONNECTIONSTATE_listWasReset] = true; - bool startUpdateInternal = this.owner.Visible; + dataConnectionState[DATACONNECTIONSTATE_listWasReset] = true; + bool startUpdateInternal = owner.Visible; if (startUpdateInternal) { - this.owner.BeginUpdateInternal(); + owner.BeginUpdateInternal(); } try { - this.owner.RefreshRows(!this.owner.InSortOperation /*scrollIntoView*/); - this.owner.PushAllowUserToAddRows(); + owner.RefreshRows(!owner.InSortOperation /*scrollIntoView*/); + owner.PushAllowUserToAddRows(); // ListChangedType.Reset can signal that the list became sorted or that the list is not sorted anymore. - this.ApplySortingInformationFromBackEnd(); + ApplySortingInformationFromBackEnd(); } finally { @@ -674,15 +674,15 @@ private void ProcessListChanged(ListChangedEventArgs e) ResetDataConnectionState(); if (startUpdateInternal) { - this.owner.EndUpdateInternal(false); - this.owner.Invalidate(true); + owner.EndUpdateInternal(false); + owner.Invalidate(true); } } break; case ListChangedType.ItemAdded: - if (this.owner.NewRowIndex == -1 || e.NewIndex != this.owner.Rows.Count) + if (owner.NewRowIndex == -1 || e.NewIndex != owner.Rows.Count) { - this.owner.Rows.InsertInternal(e.NewIndex, this.owner.RowTemplateClone, true /*force*/); + owner.Rows.InsertInternal(e.NewIndex, owner.RowTemplateClone, true /*force*/); } else { @@ -693,8 +693,8 @@ private void ProcessListChanged(ListChangedEventArgs e) } break; case ListChangedType.ItemDeleted: - this.owner.Rows.RemoveAtInternal(e.NewIndex, true /*force*/); - this.dataConnectionState[DATACONNECTIONSTATE_didNotDeleteRowFromDataGridView] = false; + owner.Rows.RemoveAtInternal(e.NewIndex, true /*force*/); + dataConnectionState[DATACONNECTIONSTATE_didNotDeleteRowFromDataGridView] = false; break; case ListChangedType.ItemMoved: // an ItemMoved event means that all the rows shifted up or down by 1 @@ -703,7 +703,7 @@ private void ProcessListChanged(ListChangedEventArgs e) Debug.Assert(e.NewIndex > -1, "how can we move an item outside of the list?"); int lo = Math.Min(e.OldIndex, e.NewIndex); int hi = Math.Max(e.OldIndex, e.NewIndex); - this.owner.InvalidateRows(lo, hi); + owner.InvalidateRows(lo, hi); break; case ListChangedType.ItemChanged: Debug.Assert(e.NewIndex != -1, "the item changed event does not cover changes to the entire list"); @@ -712,55 +712,55 @@ private void ProcessListChanged(ListChangedEventArgs e) { dataPropertyName = ((System.ComponentModel.MemberDescriptor)(e.PropertyDescriptor)).Name; } - for (int columnIndex = 0; columnIndex < this.owner.Columns.Count; columnIndex++) + for (int columnIndex = 0; columnIndex < owner.Columns.Count; columnIndex++) { - DataGridViewColumn dataGridViewColumn = this.owner.Columns[columnIndex]; + DataGridViewColumn dataGridViewColumn = owner.Columns[columnIndex]; if (dataGridViewColumn.Visible && dataGridViewColumn.IsDataBound) { if (!string.IsNullOrEmpty(dataPropertyName)) { if (string.Compare(dataGridViewColumn.DataPropertyName, dataPropertyName, true /*ignoreCase*/, CultureInfo.InvariantCulture) == 0) { - this.owner.OnCellCommonChange(columnIndex, e.NewIndex); + owner.OnCellCommonChange(columnIndex, e.NewIndex); } } else { - this.owner.OnCellCommonChange(columnIndex, e.NewIndex); + owner.OnCellCommonChange(columnIndex, e.NewIndex); } } } // Repaint the row header cell to show potential error icon - this.owner.InvalidateCell(-1, e.NewIndex); + owner.InvalidateCell(-1, e.NewIndex); // update the editing control value if the data changed in the row the user was editing - if (this.owner.CurrentCellAddress.Y == e.NewIndex && this.owner.IsCurrentCellInEditMode) + if (owner.CurrentCellAddress.Y == e.NewIndex && owner.IsCurrentCellInEditMode) { - this.owner.RefreshEdit(); + owner.RefreshEdit(); } break; default: break; } // now put the position in the DataGridView control according to the position in the currency manager - if (this.owner.Rows.Count > 0 && - !this.dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl] && - !this.owner.InSortOperation) + if (owner.Rows.Count > 0 && + !dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl] && + !owner.InSortOperation) { MatchCurrencyManagerPosition(false /*scrollIntoView*/, e.ListChangedType == ListChangedType.Reset /*clearSelection*/); } } finally { - this.dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheCurrencyManager] = false; + dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheCurrencyManager] = false; } } private void currencyManager_PositionChanged(object sender, EventArgs e) { - Debug.Assert(sender == this.currencyManager, "did we forget to unregister our events?"); - if (this.owner.Columns.Count == 0) + Debug.Assert(sender == currencyManager, "did we forget to unregister our events?"); + if (owner.Columns.Count == 0) { - Debug.Assert(this.owner.CurrentCellAddress.X == -1); + Debug.Assert(owner.CurrentCellAddress.X == -1); // No columns means we can't set the current cell. // This happens when all columns where removed from the dataGridView, and all rows were cleared. // Discuss this with Daniel/Mark. @@ -768,14 +768,14 @@ private void currencyManager_PositionChanged(object sender, EventArgs e) return; } - if (this.owner.Rows.Count == (owner.AllowUserToAddRowsInternal ? 1 : 0)) + if (owner.Rows.Count == (owner.AllowUserToAddRowsInternal ? 1 : 0)) { // the dataGridView control has not yet been notified that the list is not empty // don't do anything return; } - if (this.dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl]) + if (dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl]) { return; } @@ -794,30 +794,30 @@ private void currencyManager_PositionChanged(object sender, EventArgs e) // 5. the position inside the DataGridView is not on the new row index. // 6. the count on the back end list is 1 more than the number of data bound data grid view rows. // The DataGridView will change its current cell once the currency manager fires ListChanged event. - if (this.owner.AllowUserToAddRowsInternal && // condition 1. - this.dataConnectionState[DATACONNECTIONSTATE_finishedAddNew] && // condition 2. - !this.dataConnectionState[DATACONNECTIONSTATE_inAddNew] && // condition 2. - this.currencyManager.Position > -1 && // condition 3. - this.currencyManager.Position == this.owner.NewRowIndex && // condition 4. - this.owner.CurrentCellAddress.Y != this.owner.NewRowIndex && // condition 5. - this.currencyManager.Count == DataBoundRowsCount() + 1) // condition 6. + if (owner.AllowUserToAddRowsInternal && // condition 1. + dataConnectionState[DATACONNECTIONSTATE_finishedAddNew] && // condition 2. + !dataConnectionState[DATACONNECTIONSTATE_inAddNew] && // condition 2. + currencyManager.Position > -1 && // condition 3. + currencyManager.Position == owner.NewRowIndex && // condition 4. + owner.CurrentCellAddress.Y != owner.NewRowIndex && // condition 5. + currencyManager.Count == DataBoundRowsCount() + 1) // condition 6. { return; } - this.dataConnectionState[DATACONNECTIONSTATE_positionChangingInCurrencyManager] = true; + dataConnectionState[DATACONNECTIONSTATE_positionChangingInCurrencyManager] = true; try { - if (!this.owner.InSortOperation) + if (!owner.InSortOperation) { bool scrollIntoView = true; // When an item is repositioned in a sorted column, while its // row is being committed, don't scroll it into view. - if (this.dataConnectionState[DATACONNECTIONSTATE_rowValidatingInAddNew]) + if (dataConnectionState[DATACONNECTIONSTATE_rowValidatingInAddNew]) { - IBindingList ibl = this.currencyManager.List as IBindingList; + IBindingList ibl = currencyManager.List as IBindingList; if (ibl != null && ibl.SupportsSorting && ibl.IsSorted) { scrollIntoView = false; @@ -825,16 +825,16 @@ private void currencyManager_PositionChanged(object sender, EventArgs e) } // If the user hit Escape while in AddNew then we clear the selection. - bool clearSelection = this.dataConnectionState[DATACONNECTIONSTATE_cancellingRowEdit] && !this.dataConnectionState[DATACONNECTIONSTATE_finishedAddNew]; + bool clearSelection = dataConnectionState[DATACONNECTIONSTATE_cancellingRowEdit] && !dataConnectionState[DATACONNECTIONSTATE_finishedAddNew]; // Otherwise we clear the selection if the last list count is still uninitialized // or if it is the same as the current list count. - clearSelection |= this.lastListCount == -1 || this.lastListCount == this.currencyManager.Count; + clearSelection |= lastListCount == -1 || lastListCount == currencyManager.Count; MatchCurrencyManagerPosition(scrollIntoView, clearSelection); } } finally { - this.dataConnectionState[DATACONNECTIONSTATE_positionChangingInCurrencyManager] = false; + dataConnectionState[DATACONNECTIONSTATE_positionChangingInCurrencyManager] = false; } } @@ -844,14 +844,14 @@ private void currencyManager_PositionChanged(object sender, EventArgs e) // private int DataBoundRowsCount() { - int result = this.owner.Rows.Count; - if (this.owner.AllowUserToAddRowsInternal && this.owner.Rows.Count > 0) + int result = owner.Rows.Count; + if (owner.AllowUserToAddRowsInternal && owner.Rows.Count > 0) { - Debug.Assert(this.owner.NewRowIndex != -1, "the NewRowIndex is -1 only when AllowUserToAddRows is false"); + Debug.Assert(owner.NewRowIndex != -1, "the NewRowIndex is -1 only when AllowUserToAddRows is false"); // We have to check if the AddNew row is data bound or not. // The AddNew row is data bound if the user is positioned in the AddNew row and the AddNew row is not dirty - if (this.owner.CurrentCellAddress.Y != this.owner.NewRowIndex || this.owner.IsCurrentRowDirty) + if (owner.CurrentCellAddress.Y != owner.NewRowIndex || owner.IsCurrentRowDirty) { // The AddNew row in the DataGridView row collection is not data bound. // Substract it from the row count; @@ -864,11 +864,11 @@ private int DataBoundRowsCount() private void DataSource_Initialized(object sender, EventArgs e) { - Debug.Assert(sender == this.dataSource); - Debug.Assert(this.dataSource is ISupportInitializeNotification); - Debug.Assert(this.dataConnectionState[DATACONNECTIONSTATE_dataSourceInitializedHookedUp]); + Debug.Assert(sender == dataSource); + Debug.Assert(dataSource is ISupportInitializeNotification); + Debug.Assert(dataConnectionState[DATACONNECTIONSTATE_dataSourceInitializedHookedUp]); - ISupportInitializeNotification dsInit = this.dataSource as ISupportInitializeNotification; + ISupportInitializeNotification dsInit = dataSource as ISupportInitializeNotification; // Unhook the Initialized event. if (dsInit != null) { @@ -876,21 +876,21 @@ private void DataSource_Initialized(object sender, EventArgs e) } // The wait is over: DataSource is initialized. - this.dataConnectionState[DATACONNECTIONSTATE_dataSourceInitializedHookedUp] = false; + dataConnectionState[DATACONNECTIONSTATE_dataSourceInitializedHookedUp] = false; // Update the data manager - SetDataConnection(this.dataSource, this.dataMember); - Debug.Assert(this.currencyManager != null); - this.owner.RefreshColumnsAndRows(); - this.owner.OnDataBindingComplete(ListChangedType.Reset); + SetDataConnection(dataSource, dataMember); + Debug.Assert(currencyManager != null); + owner.RefreshColumnsAndRows(); + owner.OnDataBindingComplete(ListChangedType.Reset); } private void DataSourceMetaDataChanged() { - Debug.Assert(this.currencyManager != null); + Debug.Assert(currencyManager != null); // get the new meta data - this.props = this.currencyManager.GetItemProperties(); + props = currencyManager.GetItemProperties(); // when AutoGenerate == true: RefreshColumnsAndRows will delete the previously dataBound columns and create new dataBounds columns // @@ -898,28 +898,28 @@ private void DataSourceMetaDataChanged() // Some unBound columns may become dataBound, some dataBounds columns may become unBound // - this.owner.RefreshColumnsAndRows(); + owner.RefreshColumnsAndRows(); } public void DeleteRow(int rowIndex) { - this.dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl] = true; + dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl] = true; try { - if (!this.dataConnectionState[DATACONNECTIONSTATE_finishedAddNew]) + if (!dataConnectionState[DATACONNECTIONSTATE_finishedAddNew]) { - Debug.Assert(this.owner.AllowUserToAddRowsInternal, "how did we start an add new row transaction if the dataGridView control has AllowUserToAddRows == false?"); + Debug.Assert(owner.AllowUserToAddRowsInternal, "how did we start an add new row transaction if the dataGridView control has AllowUserToAddRows == false?"); bool deleteAddNewRow = false; - if (this.owner.newRowIndex == this.currencyManager.List.Count) + if (owner.newRowIndex == currencyManager.List.Count) { // the user clicked on the 'add new row' and started typing - deleteAddNewRow = (rowIndex == this.owner.newRowIndex - 1); + deleteAddNewRow = (rowIndex == owner.newRowIndex - 1); } else { // the user clicked on the 'add new row' but did not start typing - Debug.Assert(this.owner.newRowIndex == this.currencyManager.List.Count - 1); - deleteAddNewRow = (rowIndex == this.owner.newRowIndex); + Debug.Assert(owner.newRowIndex == currencyManager.List.Count - 1); + deleteAddNewRow = (rowIndex == owner.newRowIndex); } if (deleteAddNewRow) @@ -930,52 +930,52 @@ public void DeleteRow(int rowIndex) else { // start the Delete operation - this.dataConnectionState[DATACONNECTIONSTATE_inDeleteOperation] = true; + dataConnectionState[DATACONNECTIONSTATE_inDeleteOperation] = true; // we did not delete any rows from the data grid view yet - this.dataConnectionState[DATACONNECTIONSTATE_didNotDeleteRowFromDataGridView] = true; + dataConnectionState[DATACONNECTIONSTATE_didNotDeleteRowFromDataGridView] = true; try { - this.currencyManager.RemoveAt(rowIndex); + currencyManager.RemoveAt(rowIndex); } finally { - this.dataConnectionState[DATACONNECTIONSTATE_inDeleteOperation] = false; - this.dataConnectionState[DATACONNECTIONSTATE_didNotDeleteRowFromDataGridView] = false; + dataConnectionState[DATACONNECTIONSTATE_inDeleteOperation] = false; + dataConnectionState[DATACONNECTIONSTATE_didNotDeleteRowFromDataGridView] = false; } } } else { // start the Delete operation - this.dataConnectionState[DATACONNECTIONSTATE_inDeleteOperation] = true; + dataConnectionState[DATACONNECTIONSTATE_inDeleteOperation] = true; // we did not delete any rows from the data grid view yet - this.dataConnectionState[DATACONNECTIONSTATE_didNotDeleteRowFromDataGridView] = true; + dataConnectionState[DATACONNECTIONSTATE_didNotDeleteRowFromDataGridView] = true; try { - this.currencyManager.RemoveAt(rowIndex); + currencyManager.RemoveAt(rowIndex); } finally { - this.dataConnectionState[DATACONNECTIONSTATE_inDeleteOperation] = false; - this.dataConnectionState[DATACONNECTIONSTATE_didNotDeleteRowFromDataGridView] = false; + dataConnectionState[DATACONNECTIONSTATE_inDeleteOperation] = false; + dataConnectionState[DATACONNECTIONSTATE_didNotDeleteRowFromDataGridView] = false; } } } finally { - this.dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl] = false; + dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl] = false; } } public bool DataFieldIsReadOnly(int boundColumnIndex) { - if (this.props == null) + if (props == null) { Debug.Fail("we only care about which data fields are read only when we are data bound"); return false; } - return this.props[boundColumnIndex].IsReadOnly; + return props[boundColumnIndex].IsReadOnly; } // All we do in dispose is to unwire the data source. @@ -987,7 +987,7 @@ public void Dispose() // we would not unwire the events from the curency manager twice. // (NOTE: resurecting a disposed data grid view data connection is not allowed.) // - this.currencyManager = null; + currencyManager = null; } private static DataGridViewColumn GetDataGridViewColumnFromType(Type type) @@ -1011,38 +1011,38 @@ private static DataGridViewColumn GetDataGridViewColumnFromType(Type type) public DataGridViewColumn[] GetCollectionOfBoundDataGridViewColumns() { - if (this.props == null) + if (props == null) { return null; } ArrayList cols = new ArrayList(); - for (int i = 0; i < this.props.Count; i++) + for (int i = 0; i < props.Count; i++) { - if (typeof(IList).IsAssignableFrom(this.props[i].PropertyType)) + if (typeof(IList).IsAssignableFrom(props[i].PropertyType)) { // we have an IList. It could be a byte[] in which case we want to generate an Image column // TypeConverter imageTypeConverter = TypeDescriptor.GetConverter(typeof(Image)); - if (!imageTypeConverter.CanConvertFrom(this.props[i].PropertyType)) + if (!imageTypeConverter.CanConvertFrom(props[i].PropertyType)) { continue; } } - DataGridViewColumn dataGridViewColumn = GetDataGridViewColumnFromType(this.props[i].PropertyType); + DataGridViewColumn dataGridViewColumn = GetDataGridViewColumnFromType(props[i].PropertyType); dataGridViewColumn.IsDataBoundInternal = true; dataGridViewColumn.BoundColumnIndex = i; // we set the data property name // if you plan on removing this, then you have to change the lookup into // the GetCollectionOfBoundDataGridViewColumns - dataGridViewColumn.DataPropertyName = this.props[i].Name; - dataGridViewColumn.Name = this.props[i].Name; - dataGridViewColumn.BoundColumnConverter = this.props[i].Converter; - dataGridViewColumn.HeaderText = !string.IsNullOrEmpty(this.props[i].DisplayName) ? this.props[i].DisplayName : this.props[i].Name; - dataGridViewColumn.ValueType = this.props[i].PropertyType; + dataGridViewColumn.DataPropertyName = props[i].Name; + dataGridViewColumn.Name = props[i].Name; + dataGridViewColumn.BoundColumnConverter = props[i].Converter; + dataGridViewColumn.HeaderText = !string.IsNullOrEmpty(props[i].DisplayName) ? props[i].DisplayName : props[i].Name; + dataGridViewColumn.ValueType = props[i].PropertyType; - dataGridViewColumn.IsBrowsableInternal = this.props[i].IsBrowsable; + dataGridViewColumn.IsBrowsableInternal = props[i].IsBrowsable; dataGridViewColumn.ReadOnly = props[i].IsReadOnly; @@ -1056,7 +1056,7 @@ public DataGridViewColumn[] GetCollectionOfBoundDataGridViewColumns() private void GetSortingInformationFromBackend(out PropertyDescriptor sortProperty, out SortOrder sortOrder) { - IBindingList ibl = this.currencyManager != null ? this.currencyManager.List as IBindingList : null; + IBindingList ibl = currencyManager != null ? currencyManager.List as IBindingList : null; IBindingListView iblv = ibl != null ? ibl as IBindingListView : null; if (ibl == null || !ibl.SupportsSorting || !ibl.IsSorted) @@ -1101,17 +1101,17 @@ private void GetSortingInformationFromBackend(out PropertyDescriptor sortPropert public void ResetCachedAllowUserToAddRowsInternal() { - this.dataConnectionState[DATACONNECTIONSTATE_cachedAllowUserToAddRowsInternal] = this.owner.AllowUserToAddRowsInternal; + dataConnectionState[DATACONNECTIONSTATE_cachedAllowUserToAddRowsInternal] = owner.AllowUserToAddRowsInternal; } private void ResetDataConnectionState() { // Microsoft: I wish there would be a Reset method on BitVector32... - this.dataConnectionState = new BitVector32(DATACONNECTIONSTATE_finishedAddNew); + dataConnectionState = new BitVector32(DATACONNECTIONSTATE_finishedAddNew); - if (this.currencyManager != null) + if (currencyManager != null) { - this.dataConnectionState[DATACONNECTIONSTATE_interestedInRowEvents] = true; + dataConnectionState[DATACONNECTIONSTATE_interestedInRowEvents] = true; } ResetCachedAllowUserToAddRowsInternal(); @@ -1119,7 +1119,7 @@ private void ResetDataConnectionState() public void SetDataConnection(object dataSource, string dataMember) { - if (this.dataConnectionState[DATACONNECTIONSTATE_dataConnection_inSetDataConnection]) + if (dataConnectionState[DATACONNECTIONSTATE_dataConnection_inSetDataConnection]) { return; } @@ -1132,76 +1132,76 @@ public void SetDataConnection(object dataSource, string dataMember) } ISupportInitializeNotification dsInit = this.dataSource as ISupportInitializeNotification; - if (dsInit != null && this.dataConnectionState[DATACONNECTIONSTATE_dataSourceInitializedHookedUp]) + if (dsInit != null && dataConnectionState[DATACONNECTIONSTATE_dataSourceInitializedHookedUp]) { // If we previously hooked the data source's ISupportInitializeNotification // Initialized event, then unhook it now (we don't always hook this event, // only if we needed to because the data source was previously uninitialized) dsInit.Initialized -= new EventHandler(DataSource_Initialized); - this.dataConnectionState[DATACONNECTIONSTATE_dataSourceInitializedHookedUp] = false; + dataConnectionState[DATACONNECTIONSTATE_dataSourceInitializedHookedUp] = false; } this.dataSource = dataSource; this.dataMember = dataMember; - if (this.owner.BindingContext == null) + if (owner.BindingContext == null) { return; } - this.dataConnectionState[DATACONNECTIONSTATE_dataConnection_inSetDataConnection] = true; + dataConnectionState[DATACONNECTIONSTATE_dataConnection_inSetDataConnection] = true; try { // unwire the events UnWireEvents(); - if (this.dataSource != null && this.owner.BindingContext != null && !(this.dataSource == Convert.DBNull)) + if (this.dataSource != null && owner.BindingContext != null && !(this.dataSource == Convert.DBNull)) { dsInit = this.dataSource as ISupportInitializeNotification; if (dsInit != null && !dsInit.IsInitialized) { - if (!this.dataConnectionState[DATACONNECTIONSTATE_dataSourceInitializedHookedUp]) + if (!dataConnectionState[DATACONNECTIONSTATE_dataSourceInitializedHookedUp]) { dsInit.Initialized += new EventHandler(DataSource_Initialized); - this.dataConnectionState[DATACONNECTIONSTATE_dataSourceInitializedHookedUp] = true; + dataConnectionState[DATACONNECTIONSTATE_dataSourceInitializedHookedUp] = true; } - this.currencyManager = null; + currencyManager = null; } else { - this.currencyManager = this.owner.BindingContext[this.dataSource, this.dataMember] as CurrencyManager; + currencyManager = owner.BindingContext[this.dataSource, this.dataMember] as CurrencyManager; } } else { - this.currencyManager = null; + currencyManager = null; } // wire the events WireEvents(); - if (this.currencyManager != null) + if (currencyManager != null) { - this.props = this.currencyManager.GetItemProperties(); + props = currencyManager.GetItemProperties(); } else { - this.props = null; + props = null; } } finally { - this.dataConnectionState[DATACONNECTIONSTATE_dataConnection_inSetDataConnection] = false; + dataConnectionState[DATACONNECTIONSTATE_dataConnection_inSetDataConnection] = false; } ResetCachedAllowUserToAddRowsInternal(); - if (this.currencyManager != null) + if (currencyManager != null) { - this.lastListCount = this.currencyManager.Count; + lastListCount = currencyManager.Count; } else { - this.lastListCount = -1; + lastListCount = -1; } } @@ -1210,7 +1210,7 @@ public string GetError(int rowIndex) IDataErrorInfo errInfo = null; try { - errInfo = this.currencyManager[rowIndex] as IDataErrorInfo; + errInfo = currencyManager[rowIndex] as IDataErrorInfo; } catch (Exception exception) { @@ -1220,7 +1220,7 @@ public string GetError(int rowIndex) } DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs(exception, -1 /*columnIndex*/, rowIndex, DataGridViewDataErrorContexts.Display); - this.owner.OnDataErrorInternal(dgvdee); + owner.OnDataErrorInternal(dgvdee); if (dgvdee.ThrowException) { throw dgvdee.Exception; @@ -1244,7 +1244,7 @@ public string GetError(int boundColumnIndex, int columnIndex, int rowIndex) IDataErrorInfo errInfo = null; try { - errInfo = this.currencyManager[rowIndex] as IDataErrorInfo; + errInfo = currencyManager[rowIndex] as IDataErrorInfo; } catch (Exception exception) { @@ -1254,7 +1254,7 @@ public string GetError(int boundColumnIndex, int columnIndex, int rowIndex) } DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs(exception, columnIndex, rowIndex, DataGridViewDataErrorContexts.Display); - this.owner.OnDataErrorInternal(dgvdee); + owner.OnDataErrorInternal(dgvdee); if (dgvdee.ThrowException) { throw dgvdee.Exception; @@ -1263,7 +1263,7 @@ public string GetError(int boundColumnIndex, int columnIndex, int rowIndex) if (errInfo != null) { - return errInfo[this.props[boundColumnIndex].Name]; + return errInfo[props[boundColumnIndex].Name]; } else { @@ -1277,7 +1277,7 @@ public object GetValue(int boundColumnIndex, int columnIndex, int rowIndex) object value = null; try { - value = this.props[boundColumnIndex].GetValue(this.currencyManager[rowIndex]); + value = props[boundColumnIndex].GetValue(currencyManager[rowIndex]); } catch (Exception exception) { @@ -1287,7 +1287,7 @@ public object GetValue(int boundColumnIndex, int columnIndex, int rowIndex) } DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs(exception, columnIndex, rowIndex, DataGridViewDataErrorContexts.Display); - this.owner.OnDataErrorInternal(dgvdee); + owner.OnDataErrorInternal(dgvdee); if (dgvdee.ThrowException) { throw dgvdee.Exception; @@ -1298,13 +1298,13 @@ public object GetValue(int boundColumnIndex, int columnIndex, int rowIndex) public void MatchCurrencyManagerPosition(bool scrollIntoView, bool clearSelection) { - if (this.owner.Columns.Count == 0) + if (owner.Columns.Count == 0) { #if DEBUG // all the properties in the currency manager should be either Browsable(false) or point to sub lists - if (this.props != null) + if (props != null) { - for (int i = 0; i < this.props.Count; i++) + for (int i = 0; i < props.Count; i++) { Debug.Assert(!props[i].IsBrowsable || typeof(IList).IsAssignableFrom(props[i].PropertyType), "if the DGV does not have any columns then the properties in the currency manager should be Browsable(false) or point to sub lists"); } @@ -1315,25 +1315,25 @@ public void MatchCurrencyManagerPosition(bool scrollIntoView, bool clearSelectio return; } - int columnIndex = this.owner.CurrentCellAddress.X == -1 ? this.owner.FirstDisplayedColumnIndex : this.owner.CurrentCellAddress.X; + int columnIndex = owner.CurrentCellAddress.X == -1 ? owner.FirstDisplayedColumnIndex : owner.CurrentCellAddress.X; // Treat case where columnIndex == -1. We change the visibility of the first column. if (columnIndex == -1) { - DataGridViewColumn dataGridViewColumn = this.owner.Columns.GetFirstColumn(DataGridViewElementStates.None); + DataGridViewColumn dataGridViewColumn = owner.Columns.GetFirstColumn(DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); dataGridViewColumn.Visible = true; columnIndex = dataGridViewColumn.Index; } - int rowIndex = this.currencyManager.Position; + int rowIndex = currencyManager.Position; Debug.Assert(rowIndex >= -1); if (rowIndex == -1) { // Occurs when calling SuspendBinding() on the currency manager? - if (!this.owner.SetCurrentCellAddressCore(-1, -1, + if (!owner.SetCurrentCellAddressCore(-1, -1, false, /*setAnchorCellAddress*/ false, /*validateCurrentCell*/ false /*throughMouseClick*/)) @@ -1341,7 +1341,7 @@ public void MatchCurrencyManagerPosition(bool scrollIntoView, bool clearSelectio throw new InvalidOperationException(string.Format(SR.DataGridView_CellChangeCannotBeCommittedOrAborted)); } } - else if (rowIndex < this.owner.Rows.Count) + else if (rowIndex < owner.Rows.Count) { // the currency manager sends the PositionChanged event before the ListChanged event. // This means that it is possible for the data grid view to receive the position changed event @@ -1352,21 +1352,21 @@ public void MatchCurrencyManagerPosition(bool scrollIntoView, bool clearSelectio // the data grid view will actually get a second chance at matching the position inside the currency manager. // Do not allow to set the current cell to an invisible cell - if ((this.owner.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Visible) == 0) + if ((owner.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Visible) == 0) { // Make the target row visible. - this.owner.Rows[rowIndex].Visible = true; + owner.Rows[rowIndex].Visible = true; } - if (rowIndex == this.owner.CurrentCellAddress.Y && columnIndex == this.owner.CurrentCellAddress.X) + if (rowIndex == owner.CurrentCellAddress.Y && columnIndex == owner.CurrentCellAddress.X) { return; } // Scroll target cell into view first. - if ((scrollIntoView && !this.owner.ScrollIntoView(columnIndex, rowIndex, true)) || - (columnIndex < this.owner.Columns.Count && rowIndex < this.owner.Rows.Count && - !this.owner.SetAndSelectCurrentCellAddress(columnIndex, rowIndex, + if ((scrollIntoView && !owner.ScrollIntoView(columnIndex, rowIndex, true)) || + (columnIndex < owner.Columns.Count && rowIndex < owner.Rows.Count && + !owner.SetAndSelectCurrentCellAddress(columnIndex, rowIndex, true, /*setAnchorCellAddress*/ false, /*validateCurrentCell*/ false, /*throughMouseClick*/ @@ -1380,26 +1380,26 @@ public void MatchCurrencyManagerPosition(bool scrollIntoView, bool clearSelectio public void CancelRowEdit(bool restoreRow, bool addNewFinished) { - this.dataConnectionState[DATACONNECTIONSTATE_cancellingRowEdit] = true; - this.dataConnectionState[DATACONNECTIONSTATE_restoreRow] = restoreRow; + dataConnectionState[DATACONNECTIONSTATE_cancellingRowEdit] = true; + dataConnectionState[DATACONNECTIONSTATE_restoreRow] = restoreRow; try { object currentItem = null; - if (this.currencyManager.Position >= 0 && this.currencyManager.Position < this.currencyManager.List.Count) + if (currencyManager.Position >= 0 && currencyManager.Position < currencyManager.List.Count) { - currentItem = this.currencyManager.Current; + currentItem = currencyManager.Current; } - this.currencyManager.CancelCurrentEdit(); + currencyManager.CancelCurrentEdit(); // CurrencyManager no longer starts a new transaction automatically // when we call CurrencyManager::CancelCurrentEdit. // So, if the current item inside the currency manager did not change, we have to start a new transaction. // (If the current item inside the currency manager changed, then the currency manager would have already started a new transaction). IEditableObject editableObject = null; - if (this.currencyManager.Position >= 0 && this.currencyManager.Position < this.currencyManager.List.Count) + if (currencyManager.Position >= 0 && currencyManager.Position < currencyManager.List.Count) { - editableObject = this.currencyManager.Current as IEditableObject; + editableObject = currencyManager.Current as IEditableObject; } if (editableObject != null && currentItem == editableObject) @@ -1410,52 +1410,52 @@ public void CancelRowEdit(bool restoreRow, bool addNewFinished) } finally { - this.dataConnectionState[DATACONNECTIONSTATE_cancellingRowEdit] = false; + dataConnectionState[DATACONNECTIONSTATE_cancellingRowEdit] = false; } if (addNewFinished) { - this.dataConnectionState[DATACONNECTIONSTATE_finishedAddNew] = true; + dataConnectionState[DATACONNECTIONSTATE_finishedAddNew] = true; } } internal void OnNewRowNeeded() { - this.dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl] = true; + dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl] = true; try { AddNew(); } finally { - this.dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl] = false; + dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl] = false; } } internal void OnRowEnter(DataGridViewCellEventArgs e) { // don't change position or start a transaction in the middle of a meta data change - if (this.dataConnectionState[DATACONNECTIONSTATE_processingMetaDataChanges]) + if (dataConnectionState[DATACONNECTIONSTATE_processingMetaDataChanges]) { return; } // don't start a transaction on a suspended currency manager. - if (!this.currencyManager.ShouldBind) + if (!currencyManager.ShouldBind) { return; } - this.dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl] = true; + dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl] = true; try { - if (e.RowIndex != this.owner.NewRowIndex && - !this.dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheCurrencyManager] && - this.currencyManager.Position != e.RowIndex) // don't automatically force an EndCurrentEdit on the currency manager + if (e.RowIndex != owner.NewRowIndex && + !dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheCurrencyManager] && + currencyManager.Position != e.RowIndex) // don't automatically force an EndCurrentEdit on the currency manager { try { - this.currencyManager.Position = e.RowIndex; + currencyManager.Position = e.RowIndex; } catch (Exception exception) { @@ -1467,7 +1467,7 @@ internal void OnRowEnter(DataGridViewCellEventArgs e) ProcessException(exception, dgvce, false /*beginEdit*/); } - IEditableObject iEditObj = this.currencyManager.Current as IEditableObject; + IEditableObject iEditObj = currencyManager.Current as IEditableObject; if (iEditObj != null) { iEditObj.BeginEdit(); @@ -1476,44 +1476,44 @@ internal void OnRowEnter(DataGridViewCellEventArgs e) } finally { - this.dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl] = false; + dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl] = false; } } internal void OnRowValidating(DataGridViewCellCancelEventArgs e) { // don't end the transaction on a suspended currency manager. - if (!this.currencyManager.ShouldBind) + if (!currencyManager.ShouldBind) { return; } - if (!this.dataConnectionState[DATACONNECTIONSTATE_finishedAddNew] && !this.owner.IsCurrentRowDirty) + if (!dataConnectionState[DATACONNECTIONSTATE_finishedAddNew] && !owner.IsCurrentRowDirty) { - if (!this.dataConnectionState[DATACONNECTIONSTATE_cancellingRowEdit]) + if (!dataConnectionState[DATACONNECTIONSTATE_cancellingRowEdit]) { - Debug.Assert(DataBoundRowsCount() == this.currencyManager.List.Count, "if the back end was changed while in AddNew the DGV should have updated its rows collection"); + Debug.Assert(DataBoundRowsCount() == currencyManager.List.Count, "if the back end was changed while in AddNew the DGV should have updated its rows collection"); // Cancel the current AddNew transaction // doNotChangePositionInTheDataGridViewControl because we will change position // when we get notification from the back end that the cancel operation was completed - this.dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl] = true; + dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl] = true; try { CancelRowEdit(false /*restoreRow*/, false /*addNewFinished*/); } finally { - this.dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl] = false; + dataConnectionState[DATACONNECTIONSTATE_doNotChangePositionInTheDataGridViewControl] = false; } } } - else if (this.owner.IsCurrentRowDirty) + else if (owner.IsCurrentRowDirty) { - this.dataConnectionState[DATACONNECTIONSTATE_rowValidatingInAddNew] = true; + dataConnectionState[DATACONNECTIONSTATE_rowValidatingInAddNew] = true; try { - this.currencyManager.EndCurrentEdit(); + currencyManager.EndCurrentEdit(); } catch (Exception exception) { @@ -1525,13 +1525,13 @@ internal void OnRowValidating(DataGridViewCellCancelEventArgs e) } finally { - this.dataConnectionState[DATACONNECTIONSTATE_rowValidatingInAddNew] = false; + dataConnectionState[DATACONNECTIONSTATE_rowValidatingInAddNew] = false; } } // we moved away from the 'add new row', so the 'add new row' has been committed in the back-end // or has been rejected from the back-end. In any case, the AddNew operation completed. - this.dataConnectionState[DATACONNECTIONSTATE_finishedAddNew] = true; + dataConnectionState[DATACONNECTIONSTATE_finishedAddNew] = true; } public void ProcessException(Exception exception, DataGridViewCellCancelEventArgs e, bool beginEdit) @@ -1541,7 +1541,7 @@ public void ProcessException(Exception exception, DataGridViewCellCancelEventArg // null, // null, DataGridViewDataErrorContexts.Commit); - this.owner.OnDataErrorInternal(dgvdee); + owner.OnDataErrorInternal(dgvdee); if (dgvdee.ThrowException) { @@ -1552,7 +1552,7 @@ public void ProcessException(Exception exception, DataGridViewCellCancelEventArg e.Cancel = true; if (beginEdit) { - IEditableObject iEditObj = this.currencyManager.Current as IEditableObject; + IEditableObject iEditObj = currencyManager.Current as IEditableObject; if (iEditObj != null) { iEditObj.BeginEdit(); @@ -1573,7 +1573,7 @@ public bool PushValue(int boundColumnIndex, int columnIndex, int rowIndex, objec if (value != null) { Type valueType = value.GetType(); - Type columnType = this.owner.Columns[columnIndex].ValueType; + Type columnType = owner.Columns[columnIndex].ValueType; if (!columnType.IsAssignableFrom(valueType)) { // value needs to be converted before being fed to the back-end. @@ -1584,7 +1584,7 @@ public bool PushValue(int boundColumnIndex, int columnIndex, int rowIndex, objec } else { - TypeConverter valueConverter = this.owner.GetCachedTypeConverter(valueType); + TypeConverter valueConverter = owner.GetCachedTypeConverter(valueType); if (valueConverter != null && valueConverter.CanConvertTo(columnType)) { value = valueConverter.ConvertTo(value, columnType); @@ -1592,7 +1592,7 @@ public bool PushValue(int boundColumnIndex, int columnIndex, int rowIndex, objec } } } - this.props[boundColumnIndex].SetValue(this.currencyManager[rowIndex], value); + props[boundColumnIndex].SetValue(currencyManager[rowIndex], value); } catch (Exception exception) { @@ -1609,13 +1609,13 @@ public bool PushValue(int boundColumnIndex, int columnIndex, int rowIndex, objec public bool ShouldChangeDataMember(object newDataSource) { - if (!this.owner.Created) + if (!owner.Created) { // if the owner is not created yet then data member can be valid return false; } - if (this.owner.BindingContext == null) + if (owner.BindingContext == null) { // if we don't have the BindingContext then the data member can still be valid return false; @@ -1628,7 +1628,7 @@ public bool ShouldChangeDataMember(object newDataSource) return true; } - CurrencyManager cm = this.owner.BindingContext[newDataSource] as CurrencyManager; + CurrencyManager cm = owner.BindingContext[newDataSource] as CurrencyManager; if (cm == null) { // if we don't have a currency manager then the data member can be valid @@ -1636,7 +1636,7 @@ public bool ShouldChangeDataMember(object newDataSource) } PropertyDescriptorCollection props = cm.GetItemProperties(); - if (this.dataMember.Length != 0 && props[this.dataMember] != null) + if (dataMember.Length != 0 && props[dataMember] != null) { // the data member is valid. Don't change it return false; @@ -1648,27 +1648,27 @@ public bool ShouldChangeDataMember(object newDataSource) public void Sort(DataGridViewColumn dataGridViewColumn, ListSortDirection direction) { Debug.Assert(dataGridViewColumn.IsDataBound && dataGridViewColumn.BoundColumnIndex != -1, "we need a bound column index to perform the sort"); - Debug.Assert(this.List is IBindingList, "you should have checked by now that we are bound to an IBindingList"); - ((IBindingList)this.List).ApplySort(this.props[dataGridViewColumn.BoundColumnIndex], direction); + Debug.Assert(List is IBindingList, "you should have checked by now that we are bound to an IBindingList"); + ((IBindingList)List).ApplySort(props[dataGridViewColumn.BoundColumnIndex], direction); } private void UnWireEvents() { - if (this.currencyManager != null) + if (currencyManager != null) { - this.currencyManager.PositionChanged -= new EventHandler(currencyManager_PositionChanged); - this.currencyManager.ListChanged -= new ListChangedEventHandler(currencyManager_ListChanged); - this.dataConnectionState[DATACONNECTIONSTATE_interestedInRowEvents] = false; + currencyManager.PositionChanged -= new EventHandler(currencyManager_PositionChanged); + currencyManager.ListChanged -= new ListChangedEventHandler(currencyManager_ListChanged); + dataConnectionState[DATACONNECTIONSTATE_interestedInRowEvents] = false; } } private void WireEvents() { - if (this.currencyManager != null) + if (currencyManager != null) { - this.currencyManager.PositionChanged += new EventHandler(currencyManager_PositionChanged); - this.currencyManager.ListChanged += new ListChangedEventHandler(currencyManager_ListChanged); - this.dataConnectionState[DATACONNECTIONSTATE_interestedInRowEvents] = true; + currencyManager.PositionChanged += new EventHandler(currencyManager_PositionChanged); + currencyManager.ListChanged += new ListChangedEventHandler(currencyManager_ListChanged); + dataConnectionState[DATACONNECTIONSTATE_interestedInRowEvents] = true; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHeaderCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHeaderCell.cs index 310a8465765..b7eb37091c0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHeaderCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHeaderCell.cs @@ -38,7 +38,7 @@ protected ButtonState ButtonState get { bool found; - int buttonState = this.Properties.GetInteger(PropButtonState, out found); + int buttonState = Properties.GetInteger(PropButtonState, out found); if (found) { return (ButtonState)buttonState; @@ -55,9 +55,9 @@ private ButtonState ButtonStatePrivate set { Debug.Assert(Enum.IsDefined(typeof(ButtonState), value)); - if (this.ButtonState != value) + if (ButtonState != value) { - this.Properties.SetInteger(PropButtonState, (int)value); + Properties.SetInteger(PropButtonState, (int)value); } } } @@ -79,27 +79,27 @@ public override bool Displayed { get { - if (this.DataGridView == null || !this.DataGridView.Visible) + if (DataGridView == null || !DataGridView.Visible) { // No detached or invisible element is displayed. return false; } - if (this.OwningRow != null) + if (OwningRow != null) { // row header cell - return this.DataGridView.RowHeadersVisible && this.OwningRow.Displayed; + return DataGridView.RowHeadersVisible && OwningRow.Displayed; } - if (this.OwningColumn != null) + if (OwningColumn != null) { // column header cell - return this.DataGridView.ColumnHeadersVisible && this.OwningColumn.Displayed; + return DataGridView.ColumnHeadersVisible && OwningColumn.Displayed; } // top left header cell - Debug.Assert(!this.DataGridView.LayoutInfo.dirty); - return this.DataGridView.LayoutInfo.TopLeftHeader != Rectangle.Empty; + Debug.Assert(!DataGridView.LayoutInfo.dirty); + return DataGridView.LayoutInfo.TopLeftHeader != Rectangle.Empty; } } @@ -107,13 +107,13 @@ internal Bitmap FlipXPThemesBitmap { get { - return (Bitmap)this.Properties.GetObject(PropFlipXPThemesBitmap); + return (Bitmap)Properties.GetObject(PropFlipXPThemesBitmap); } set { - if (value != null || this.Properties.ContainsObject(PropFlipXPThemesBitmap)) + if (value != null || Properties.ContainsObject(PropFlipXPThemesBitmap)) { - this.Properties.SetObject(PropFlipXPThemesBitmap, value); + Properties.SetObject(PropFlipXPThemesBitmap, value); } } } @@ -133,19 +133,19 @@ public override bool Frozen { get { - if (this.OwningRow != null) + if (OwningRow != null) { // row header cell - return this.OwningRow.Frozen; + return OwningRow.Frozen; } - if (this.OwningColumn != null) + if (OwningColumn != null) { // column header cell - return this.OwningColumn.Frozen; + return OwningColumn.Frozen; } - if (this.DataGridView != null) + if (DataGridView != null) { // top left header cell return true; @@ -160,7 +160,7 @@ internal override bool HasValueType { get { - return this.Properties.ContainsObject(PropValueType) && this.Properties.GetObject(PropValueType) != null; + return Properties.ContainsObject(PropValueType) && Properties.GetObject(PropValueType) != null; } } @@ -187,21 +187,21 @@ public override bool Resizable { get { - if (this.OwningRow != null) + if (OwningRow != null) { // must be a row header cell - return (this.OwningRow.Resizable == DataGridViewTriState.True) || (this.DataGridView != null && this.DataGridView.RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing); + return (OwningRow.Resizable == DataGridViewTriState.True) || (DataGridView != null && DataGridView.RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing); } - if (this.OwningColumn != null) + if (OwningColumn != null) { // must be a column header cell - return (this.OwningColumn.Resizable == DataGridViewTriState.True) || - (this.DataGridView != null && this.DataGridView.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing); + return (OwningColumn.Resizable == DataGridViewTriState.True) || + (DataGridView != null && DataGridView.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing); } // must be the top left header cell - return this.DataGridView != null && (this.DataGridView.RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing || this.DataGridView.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing); + return DataGridView != null && (DataGridView.RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing || DataGridView.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing); } } @@ -225,7 +225,7 @@ public override Type ValueType { get { - Type valueType = (Type)this.Properties.GetObject(PropValueType); + Type valueType = (Type)Properties.GetObject(PropValueType); if (valueType != null) { return valueType; @@ -234,9 +234,9 @@ public override Type ValueType } set { - if (value != null || this.Properties.ContainsObject(PropValueType)) + if (value != null || Properties.ContainsObject(PropValueType)) { - this.Properties.SetObject(PropValueType, value); + Properties.SetObject(PropValueType, value); } } } @@ -248,24 +248,24 @@ public override bool Visible { get { - if (this.OwningRow != null) + if (OwningRow != null) { // row header cell - return this.OwningRow.Visible && - (this.DataGridView == null || this.DataGridView.RowHeadersVisible); + return OwningRow.Visible && + (DataGridView == null || DataGridView.RowHeadersVisible); } - if (this.OwningColumn != null) + if (OwningColumn != null) { // column header cell - return this.OwningColumn.Visible && - (this.DataGridView == null || this.DataGridView.ColumnHeadersVisible); + return OwningColumn.Visible && + (DataGridView == null || DataGridView.ColumnHeadersVisible); } - if (this.DataGridView != null) + if (DataGridView != null) { // top left header cell - return this.DataGridView.RowHeadersVisible && this.DataGridView.ColumnHeadersVisible; + return DataGridView.RowHeadersVisible && DataGridView.ColumnHeadersVisible; } return false; @@ -275,7 +275,7 @@ public override bool Visible public override object Clone() { DataGridViewHeaderCell dataGridViewCell; - Type thisType = this.GetType(); + Type thisType = GetType(); if (thisType == cellType) //performance improvement { dataGridViewCell = new DataGridViewHeaderCell(); @@ -287,7 +287,7 @@ public override object Clone() dataGridViewCell = (DataGridViewHeaderCell)System.Activator.CreateInstance(thisType); } base.CloneInternal(dataGridViewCell); - dataGridViewCell.Value = this.Value; + dataGridViewCell.Value = Value; return dataGridViewCell; } @@ -299,9 +299,9 @@ public override ContextMenuStrip GetInheritedContextMenuStrip(int rowIndex) return contextMenuStrip; } - if (this.DataGridView != null) + if (DataGridView != null) { - return this.DataGridView.ContextMenuStrip; + return DataGridView.ContextMenuStrip; } else { @@ -313,55 +313,55 @@ public override DataGridViewElementStates GetInheritedState(int rowIndex) { DataGridViewElementStates state = DataGridViewElementStates.ResizableSet | DataGridViewElementStates.ReadOnly; - if (this.OwningRow != null) + if (OwningRow != null) { // row header cell - if ((this.DataGridView == null && rowIndex != -1) || - (this.DataGridView != null && (rowIndex < 0 || rowIndex >= this.DataGridView.Rows.Count))) + if ((DataGridView == null && rowIndex != -1) || + (DataGridView != null && (rowIndex < 0 || rowIndex >= DataGridView.Rows.Count))) { throw new ArgumentException(string.Format(SR.InvalidArgument, nameof(rowIndex), rowIndex)); } - if (this.DataGridView != null && this.DataGridView.Rows.SharedRow(rowIndex) != this.OwningRow) + if (DataGridView != null && DataGridView.Rows.SharedRow(rowIndex) != OwningRow) { throw new ArgumentException(string.Format(SR.InvalidArgument, nameof(rowIndex), rowIndex)); } - state |= (this.OwningRow.GetState(rowIndex) & DataGridViewElementStates.Frozen); - if (this.OwningRow.GetResizable(rowIndex) == DataGridViewTriState.True || (this.DataGridView != null && this.DataGridView.RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing)) + state |= (OwningRow.GetState(rowIndex) & DataGridViewElementStates.Frozen); + if (OwningRow.GetResizable(rowIndex) == DataGridViewTriState.True || (DataGridView != null && DataGridView.RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing)) { state |= DataGridViewElementStates.Resizable; } - if (this.OwningRow.GetVisible(rowIndex) && (this.DataGridView == null || this.DataGridView.RowHeadersVisible)) + if (OwningRow.GetVisible(rowIndex) && (DataGridView == null || DataGridView.RowHeadersVisible)) { state |= DataGridViewElementStates.Visible; - if (this.OwningRow.GetDisplayed(rowIndex)) + if (OwningRow.GetDisplayed(rowIndex)) { state |= DataGridViewElementStates.Displayed; } } } - else if (this.OwningColumn != null) + else if (OwningColumn != null) { // column header cell if (rowIndex != -1) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - state |= (this.OwningColumn.State & DataGridViewElementStates.Frozen); - if (this.OwningColumn.Resizable == DataGridViewTriState.True || - (this.DataGridView != null && this.DataGridView.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing)) + state |= (OwningColumn.State & DataGridViewElementStates.Frozen); + if (OwningColumn.Resizable == DataGridViewTriState.True || + (DataGridView != null && DataGridView.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing)) { state |= DataGridViewElementStates.Resizable; } - if (this.OwningColumn.Visible && (this.DataGridView == null || this.DataGridView.ColumnHeadersVisible)) + if (OwningColumn.Visible && (DataGridView == null || DataGridView.ColumnHeadersVisible)) { state |= DataGridViewElementStates.Visible; - if (this.OwningColumn.Displayed) + if (OwningColumn.Displayed) { state |= DataGridViewElementStates.Displayed; } } } - else if (this.DataGridView != null) + else if (DataGridView != null) { // top left header cell if (rowIndex != -1) @@ -369,14 +369,14 @@ public override DataGridViewElementStates GetInheritedState(int rowIndex) throw new ArgumentOutOfRangeException(nameof(rowIndex)); } state |= DataGridViewElementStates.Frozen; - if (this.DataGridView.RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing || this.DataGridView.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing) + if (DataGridView.RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing || DataGridView.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing) { state |= DataGridViewElementStates.Resizable; } - if (this.DataGridView.RowHeadersVisible && this.DataGridView.ColumnHeadersVisible) + if (DataGridView.RowHeadersVisible && DataGridView.ColumnHeadersVisible) { state |= DataGridViewElementStates.Visible; - if (this.DataGridView.LayoutInfo.TopLeftHeader != Rectangle.Empty) + if (DataGridView.LayoutInfo.TopLeftHeader != Rectangle.Empty) { state |= DataGridViewElementStates.Displayed; } @@ -384,30 +384,30 @@ public override DataGridViewElementStates GetInheritedState(int rowIndex) } #if DEBUG - if (this.OwningRow == null || this.OwningRow.Index != -1) + if (OwningRow == null || OwningRow.Index != -1) { DataGridViewElementStates stateDebug = DataGridViewElementStates.ResizableSet; - if (this.Displayed) + if (Displayed) { stateDebug |= DataGridViewElementStates.Displayed; } - if (this.Frozen) + if (Frozen) { stateDebug |= DataGridViewElementStates.Frozen; } - if (this.ReadOnly) + if (ReadOnly) { stateDebug |= DataGridViewElementStates.ReadOnly; } - if (this.Resizable) + if (Resizable) { stateDebug |= DataGridViewElementStates.Resizable; } - if (this.Selected) + if (Selected) { stateDebug |= DataGridViewElementStates.Selected; } - if (this.Visible) + if (Visible) { stateDebug |= DataGridViewElementStates.Visible; } @@ -420,7 +420,7 @@ public override DataGridViewElementStates GetInheritedState(int rowIndex) protected override Size GetSize(int rowIndex) { - if (this.DataGridView == null) + if (DataGridView == null) { // detached cell if (rowIndex != -1) @@ -429,27 +429,27 @@ protected override Size GetSize(int rowIndex) } return new Size(-1, -1); } - if (this.OwningColumn != null) + if (OwningColumn != null) { // must be a column header cell if (rowIndex != -1) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - return new Size(this.OwningColumn.Thickness, this.DataGridView.ColumnHeadersHeight); + return new Size(OwningColumn.Thickness, DataGridView.ColumnHeadersHeight); } - else if (this.OwningRow != null) + else if (OwningRow != null) { // must be a row header cell - if (rowIndex < 0 || rowIndex >= this.DataGridView.Rows.Count) + if (rowIndex < 0 || rowIndex >= DataGridView.Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - if (this.DataGridView.Rows.SharedRow(rowIndex) != this.OwningRow) + if (DataGridView.Rows.SharedRow(rowIndex) != OwningRow) { throw new ArgumentException(string.Format(SR.InvalidArgument, nameof(rowIndex), rowIndex)); } - return new Size(this.DataGridView.RowHeadersWidth, this.OwningRow.GetHeight(rowIndex)); + return new Size(DataGridView.RowHeadersWidth, OwningRow.GetHeight(rowIndex)); } else { @@ -458,7 +458,7 @@ protected override Size GetSize(int rowIndex) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - return new Size(this.DataGridView.RowHeadersWidth, this.DataGridView.ColumnHeadersHeight); + return new Size(DataGridView.RowHeadersWidth, DataGridView.ColumnHeadersHeight); } } @@ -507,40 +507,40 @@ protected override object GetValue(int rowIndex) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - return this.Properties.GetObject(PropCellValue); + return Properties.GetObject(PropCellValue); } protected override bool MouseDownUnsharesRow(DataGridViewCellMouseEventArgs e) { - return e.Button == MouseButtons.Left && this.DataGridView.ApplyVisualStylesToHeaderCells; + return e.Button == MouseButtons.Left && DataGridView.ApplyVisualStylesToHeaderCells; } protected override bool MouseEnterUnsharesRow(int rowIndex) { - return this.ColumnIndex == this.DataGridView.MouseDownCellAddress.X && - rowIndex == this.DataGridView.MouseDownCellAddress.Y && - this.DataGridView.ApplyVisualStylesToHeaderCells; + return ColumnIndex == DataGridView.MouseDownCellAddress.X && + rowIndex == DataGridView.MouseDownCellAddress.Y && + DataGridView.ApplyVisualStylesToHeaderCells; } protected override bool MouseLeaveUnsharesRow(int rowIndex) { - return this.ButtonState != ButtonState.Normal && this.DataGridView.ApplyVisualStylesToHeaderCells; + return ButtonState != ButtonState.Normal && DataGridView.ApplyVisualStylesToHeaderCells; } protected override bool MouseUpUnsharesRow(DataGridViewCellMouseEventArgs e) { - return e.Button == MouseButtons.Left && this.DataGridView.ApplyVisualStylesToHeaderCells; + return e.Button == MouseButtons.Left && DataGridView.ApplyVisualStylesToHeaderCells; } protected override void OnMouseDown(DataGridViewCellMouseEventArgs e) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } if (e.Button == MouseButtons.Left && - this.DataGridView.ApplyVisualStylesToHeaderCells && - !this.DataGridView.ResizingOperationAboutToStart) + DataGridView.ApplyVisualStylesToHeaderCells && + !DataGridView.ResizingOperationAboutToStart) { UpdateButtonState(ButtonState.Pushed, e.RowIndex); } @@ -548,50 +548,50 @@ protected override void OnMouseDown(DataGridViewCellMouseEventArgs e) protected override void OnMouseEnter(int rowIndex) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } - if (this.DataGridView.ApplyVisualStylesToHeaderCells) + if (DataGridView.ApplyVisualStylesToHeaderCells) { - if (this.ColumnIndex == this.DataGridView.MouseDownCellAddress.X && - rowIndex == this.DataGridView.MouseDownCellAddress.Y && - this.ButtonState == ButtonState.Normal && + if (ColumnIndex == DataGridView.MouseDownCellAddress.X && + rowIndex == DataGridView.MouseDownCellAddress.Y && + ButtonState == ButtonState.Normal && Control.MouseButtons == MouseButtons.Left && - !this.DataGridView.ResizingOperationAboutToStart) + !DataGridView.ResizingOperationAboutToStart) { UpdateButtonState(ButtonState.Pushed, rowIndex); } - this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex); + DataGridView.InvalidateCell(ColumnIndex, rowIndex); } } protected override void OnMouseLeave(int rowIndex) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } - if (this.DataGridView.ApplyVisualStylesToHeaderCells) + if (DataGridView.ApplyVisualStylesToHeaderCells) { - if (this.ButtonState != ButtonState.Normal) + if (ButtonState != ButtonState.Normal) { - Debug.Assert(this.ButtonState == ButtonState.Pushed); - Debug.Assert(this.ColumnIndex == this.DataGridView.MouseDownCellAddress.X); - Debug.Assert(rowIndex == this.DataGridView.MouseDownCellAddress.Y); + Debug.Assert(ButtonState == ButtonState.Pushed); + Debug.Assert(ColumnIndex == DataGridView.MouseDownCellAddress.X); + Debug.Assert(rowIndex == DataGridView.MouseDownCellAddress.Y); UpdateButtonState(ButtonState.Normal, rowIndex); } - this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex); + DataGridView.InvalidateCell(ColumnIndex, rowIndex); } } protected override void OnMouseUp(DataGridViewCellMouseEventArgs e) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } - if (e.Button == MouseButtons.Left && this.DataGridView.ApplyVisualStylesToHeaderCells) + if (e.Button == MouseButtons.Left && DataGridView.ApplyVisualStylesToHeaderCells) { UpdateButtonState(ButtonState.Normal, e.RowIndex); } @@ -629,7 +629,7 @@ protected override void Paint(Graphics graphics, valBounds.Height -= borderWidths.Bottom; bool cellSelected = (dataGridViewElementState & DataGridViewElementStates.Selected) != 0; - SolidBrush br = this.DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor); + SolidBrush br = DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor); if (br.Color.A == 255) { graphics.FillRectangle(br, valBounds); @@ -644,14 +644,14 @@ protected override void Paint(Graphics graphics, /// public override string ToString() { - return "DataGridViewHeaderCell { ColumnIndex=" + this.ColumnIndex.ToString(CultureInfo.CurrentCulture) + ", RowIndex=" + this.RowIndex.ToString(CultureInfo.CurrentCulture) + " }"; + return "DataGridViewHeaderCell { ColumnIndex=" + ColumnIndex.ToString(CultureInfo.CurrentCulture) + ", RowIndex=" + RowIndex.ToString(CultureInfo.CurrentCulture) + " }"; } private void UpdateButtonState(ButtonState newButtonState, int rowIndex) { - Debug.Assert(this.DataGridView != null); - this.ButtonStatePrivate = newButtonState; - this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex); + Debug.Assert(DataGridView != null); + ButtonStatePrivate = newButtonState; + DataGridView.InvalidateCell(ColumnIndex, rowIndex); } private class DataGridViewHeaderCellRenderer diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHitTestInfo.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHitTestInfo.cs index fcc0a94bf48..d7c255369d1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHitTestInfo.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHitTestInfo.cs @@ -29,12 +29,12 @@ public sealed class HitTestInfo internal HitTestInfo() { - this.type = DataGridViewHitTestType.None; - this.typeInternal = DataGridViewHitTestTypeInternal.None; + type = DataGridViewHitTestType.None; + typeInternal = DataGridViewHitTestTypeInternal.None; //this.edge = DataGridViewHitTestTypeCloseEdge.None; - this.row = this.col = -1; - this.rowStart = this.colStart = -1; - this.adjacentRow = this.adjacentCol = -1; + row = col = -1; + rowStart = colStart = -1; + adjacentRow = adjacentCol = -1; } /// @@ -44,7 +44,7 @@ public int ColumnIndex { get { - return this.col; + return col; } } @@ -56,7 +56,7 @@ public int RowIndex { get { - return this.row; + return row; } } @@ -67,7 +67,7 @@ public int ColumnX { get { - return this.colStart; + return colStart; } } @@ -78,7 +78,7 @@ public int RowY { get { - return this.rowStart; + return rowStart; } } @@ -90,7 +90,7 @@ public DataGridViewHitTestType Type { get { - return this.type; + return type; } } @@ -102,9 +102,9 @@ public override bool Equals(object value) HitTestInfo hti = value as HitTestInfo; if (hti != null) { - return (this.type == hti.type && - this.row == hti.row && - this.col == hti.col); + return (type == hti.type && + row == hti.row && + col == hti.col); } return false; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageCell.cs index fc294850071..86709879429 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageCell.cs @@ -37,7 +37,7 @@ public DataGridViewImageCell(bool valueIsIcon) { if (valueIsIcon) { - this.flags = DATAGRIDVIEWIMAGECELL_valueIsIcon; + flags = DATAGRIDVIEWIMAGECELL_valueIsIcon; } } @@ -45,11 +45,11 @@ public override object DefaultNewRowValue { get { - if (defaultTypeImage.IsAssignableFrom(this.ValueType)) + if (defaultTypeImage.IsAssignableFrom(ValueType)) { return ErrorBitmap; } - else if (defaultTypeIcon.IsAssignableFrom(this.ValueType)) + else if (defaultTypeIcon.IsAssignableFrom(ValueType)) { return ErrorIcon; } @@ -67,7 +67,7 @@ public string Description { get { - object description = this.Properties.GetObject(PropImageCellDescription); + object description = Properties.GetObject(PropImageCellDescription); if (description != null) { return (string)description; @@ -77,9 +77,9 @@ public string Description set { - if (!string.IsNullOrEmpty(value) || this.Properties.ContainsObject(PropImageCellDescription)) + if (!string.IsNullOrEmpty(value) || Properties.ContainsObject(PropImageCellDescription)) { - this.Properties.SetObject(PropImageCellDescription, value); + Properties.SetObject(PropImageCellDescription, value); } } } @@ -121,7 +121,7 @@ public override Type FormattedValueType { get { - if (this.ValueIsIcon) + if (ValueIsIcon) { return defaultTypeIcon; } @@ -140,7 +140,7 @@ public DataGridViewImageCellLayout ImageLayout get { bool found; - int imageLayout = this.Properties.GetInteger(PropImageCellLayout, out found); + int imageLayout = Properties.GetInteger(PropImageCellLayout, out found); if (found) { return (DataGridViewImageCellLayout)imageLayout; @@ -154,9 +154,9 @@ public DataGridViewImageCellLayout ImageLayout { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewImageCellLayout)); } - if (this.ImageLayout != value) + if (ImageLayout != value) { - this.Properties.SetInteger(PropImageCellLayout, (int)value); + Properties.SetInteger(PropImageCellLayout, (int)value); OnCommonChange(); } } @@ -167,9 +167,9 @@ internal DataGridViewImageCellLayout ImageLayoutInternal set { Debug.Assert(value >= DataGridViewImageCellLayout.NotSet && value <= DataGridViewImageCellLayout.Zoom); - if (this.ImageLayout != value) + if (ImageLayout != value) { - this.Properties.SetInteger(PropImageCellLayout, (int)value); + Properties.SetInteger(PropImageCellLayout, (int)value); } } } @@ -181,22 +181,22 @@ public bool ValueIsIcon { get { - return ((this.flags & DATAGRIDVIEWIMAGECELL_valueIsIcon) != 0x00); + return ((flags & DATAGRIDVIEWIMAGECELL_valueIsIcon) != 0x00); } set { - if (this.ValueIsIcon != value) + if (ValueIsIcon != value) { - this.ValueIsIconInternal = value; - if (this.DataGridView != null) + ValueIsIconInternal = value; + if (DataGridView != null) { - if (this.RowIndex != -1) + if (RowIndex != -1) { - this.DataGridView.InvalidateCell(this); + DataGridView.InvalidateCell(this); } else { - this.DataGridView.InvalidateColumnInternal(this.ColumnIndex); + DataGridView.InvalidateColumnInternal(ColumnIndex); } } } @@ -207,26 +207,26 @@ internal bool ValueIsIconInternal { set { - if (this.ValueIsIcon != value) + if (ValueIsIcon != value) { if (value) { - this.flags |= (byte)DATAGRIDVIEWIMAGECELL_valueIsIcon; + flags |= (byte)DATAGRIDVIEWIMAGECELL_valueIsIcon; } else { - this.flags = (byte)(this.flags & ~DATAGRIDVIEWIMAGECELL_valueIsIcon); + flags = (byte)(flags & ~DATAGRIDVIEWIMAGECELL_valueIsIcon); } - if (this.DataGridView != null && - this.RowIndex != -1 && - this.DataGridView.NewRowIndex == this.RowIndex && - !this.DataGridView.VirtualMode) + if (DataGridView != null && + RowIndex != -1 && + DataGridView.NewRowIndex == RowIndex && + !DataGridView.VirtualMode) { - Debug.Assert(this.DataGridView.AllowUserToAddRowsInternal); + Debug.Assert(DataGridView.AllowUserToAddRowsInternal); // We automatically update the content of the new row's cell based on the new ValueIsIcon value. - if ((value && this.Value == ErrorBitmap) || (!value && this.Value == ErrorIcon)) + if ((value && Value == ErrorBitmap) || (!value && Value == ErrorIcon)) { - this.Value = this.DefaultNewRowValue; + Value = DefaultNewRowValue; } } } @@ -244,7 +244,7 @@ public override Type ValueType return baseValueType; } - if (this.ValueIsIcon) + if (ValueIsIcon) { return defaultTypeIcon; } @@ -256,14 +256,14 @@ public override Type ValueType set { base.ValueType = value; - this.ValueIsIcon = (value != null && defaultTypeIcon.IsAssignableFrom(value)); + ValueIsIcon = (value != null && defaultTypeIcon.IsAssignableFrom(value)); } } public override object Clone() { DataGridViewImageCell dataGridViewCell; - Type thisType = this.GetType(); + Type thisType = GetType(); if (thisType == cellType) //performance improvement { @@ -276,9 +276,9 @@ public override object Clone() dataGridViewCell = (DataGridViewImageCell)System.Activator.CreateInstance(thisType); } base.CloneInternal(dataGridViewCell); - dataGridViewCell.ValueIsIconInternal = this.ValueIsIcon; - dataGridViewCell.Description = this.Description; - dataGridViewCell.ImageLayoutInternal = this.ImageLayout; + dataGridViewCell.ValueIsIconInternal = ValueIsIcon; + dataGridViewCell.Description = Description; + dataGridViewCell.ImageLayoutInternal = ImageLayout; return dataGridViewCell; } @@ -294,7 +294,7 @@ protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCel throw new ArgumentNullException(nameof(cellStyle)); } - if (this.DataGridView == null || rowIndex < 0 || this.OwningColumn == null) + if (DataGridView == null || rowIndex < 0 || OwningColumn == null) { return Rectangle.Empty; } @@ -349,10 +349,10 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC throw new ArgumentNullException(nameof(cellStyle)); } - if (this.DataGridView == null || + if (DataGridView == null || rowIndex < 0 || - this.OwningColumn == null || - !this.DataGridView.ShowCellErrors || + OwningColumn == null || + !DataGridView.ShowCellErrors || string.IsNullOrEmpty(GetErrorText(rowIndex))) { return Rectangle.Empty; @@ -412,7 +412,7 @@ protected override object GetFormattedValue(object value, { if ((context & DataGridViewDataErrorContexts.ClipboardContent) != 0) { - return this.Description; + return Description; } object formattedValue = base.GetFormattedValue(value, rowIndex, ref cellStyle, valueTypeConverter, formattedValueTypeConverter, context); @@ -420,7 +420,7 @@ protected override object GetFormattedValue(object value, { return null; } - if (this.ValueIsIcon) + if (ValueIsIcon) { Icon ico = formattedValue as Icon; if (ico == null) @@ -442,7 +442,7 @@ protected override object GetFormattedValue(object value, protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize) { - if (this.DataGridView == null) + if (DataGridView == null) { return new Size(-1, -1); } @@ -453,7 +453,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl } Size preferredSize; - Rectangle borderWidthsRect = this.StdBorderWidths; + Rectangle borderWidthsRect = StdBorderWidths; int borderAndPaddingWidths = borderWidthsRect.Left + borderWidthsRect.Width + cellStyle.Padding.Horizontal; int borderAndPaddingHeights = borderWidthsRect.Top + borderWidthsRect.Height + cellStyle.Padding.Vertical; DataGridViewFreeDimension freeDimension = DataGridViewCell.GetFreeDimensionFromConstraint(constraintSize); @@ -466,7 +466,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl } if (freeDimension == DataGridViewFreeDimension.Height && - this.ImageLayout == DataGridViewImageCellLayout.Zoom) + ImageLayout == DataGridViewImageCellLayout.Zoom) { if (img != null || ico != null) { @@ -501,7 +501,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl } } else if (freeDimension == DataGridViewFreeDimension.Width && - this.ImageLayout == DataGridViewImageCellLayout.Zoom) + ImageLayout == DataGridViewImageCellLayout.Zoom) { if (img != null || ico != null) { @@ -562,7 +562,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl if (freeDimension != DataGridViewFreeDimension.Height) { preferredSize.Width += borderAndPaddingWidths; - if (this.DataGridView.ShowCellErrors) + if (DataGridView.ShowCellErrors) { // Making sure that there is enough room for the potential error icon preferredSize.Width = Math.Max(preferredSize.Width, borderAndPaddingWidths + DATAGRIDVIEWCELL_iconMarginWidth * 2 + iconsWidth); @@ -571,7 +571,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl if (freeDimension != DataGridViewFreeDimension.Width) { preferredSize.Height += borderAndPaddingHeights; - if (this.DataGridView.ShowCellErrors) + if (DataGridView.ShowCellErrors) { // Making sure that there is enough room for the potential error icon preferredSize.Height = Math.Max(preferredSize.Height, borderAndPaddingHeights + DATAGRIDVIEWCELL_iconMarginHeight * 2 + iconsHeight); @@ -585,10 +585,10 @@ protected override object GetValue(int rowIndex) object valueBase = base.GetValue(rowIndex); if (valueBase == null) { - DataGridViewImageColumn owningImageColumn = this.OwningColumn as DataGridViewImageColumn; + DataGridViewImageColumn owningImageColumn = OwningColumn as DataGridViewImageColumn; if (owningImageColumn != null) { - if (defaultTypeImage.IsAssignableFrom(this.ValueType)) + if (defaultTypeImage.IsAssignableFrom(ValueType)) { Image image = owningImageColumn.Image; if (image != null) @@ -596,7 +596,7 @@ protected override object GetValue(int rowIndex) return image; } } - else if (defaultTypeIcon.IsAssignableFrom(this.ValueType)) + else if (defaultTypeIcon.IsAssignableFrom(ValueType)) { Icon icon = owningImageColumn.Icon; if (icon != null) @@ -640,7 +640,7 @@ private Rectangle ImgBounds(Rectangle bounds, int imgWidth, int imgHeight, DataG } // now use the alignment on the cellStyle to determine the final bounds - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { switch (cellStyle.Alignment) { @@ -804,7 +804,7 @@ private Rectangle PaintPrivate(Graphics g, Rectangle imgBounds = valBounds; if (cellStyle.Padding != Padding.Empty) { - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { imgBounds.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top); } @@ -817,7 +817,7 @@ private Rectangle PaintPrivate(Graphics g, } bool cellSelected = (elementState & DataGridViewElementStates.Selected) != 0; - SolidBrush br = this.DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor); + SolidBrush br = DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor); if (imgBounds.Width > 0 && imgBounds.Height > 0) { @@ -829,12 +829,12 @@ private Rectangle PaintPrivate(Graphics g, } if (ico != null || img != null) { - DataGridViewImageCellLayout imageLayout = this.ImageLayout; + DataGridViewImageCellLayout imageLayout = ImageLayout; if (imageLayout == DataGridViewImageCellLayout.NotSet) { - if (this.OwningColumn is DataGridViewImageColumn) + if (OwningColumn is DataGridViewImageColumn) { - imageLayout = ((DataGridViewImageColumn)this.OwningColumn).ImageLayout; + imageLayout = ((DataGridViewImageColumn)OwningColumn).ImageLayout; Debug.Assert(imageLayout != DataGridViewImageCellLayout.NotSet); } else @@ -849,7 +849,7 @@ private Rectangle PaintPrivate(Graphics g, { if (DataGridViewCell.PaintBackground(paintParts)) { - DataGridViewCell.PaintPadding(g, valBounds, cellStyle, br, this.DataGridView.RightToLeftInternal); + DataGridViewCell.PaintPadding(g, valBounds, cellStyle, br, DataGridView.RightToLeftInternal); } if (DataGridViewCell.PaintContentForeground(paintParts)) { @@ -919,19 +919,19 @@ private Rectangle PaintPrivate(Graphics g, resultBounds = Rectangle.Empty; } - Point ptCurrentCell = this.DataGridView.CurrentCellAddress; + Point ptCurrentCell = DataGridView.CurrentCellAddress; if (paint && DataGridViewCell.PaintFocus(paintParts) && - ptCurrentCell.X == this.ColumnIndex && + ptCurrentCell.X == ColumnIndex && ptCurrentCell.Y == rowIndex && - this.DataGridView.ShowFocusCues && - this.DataGridView.Focused) + DataGridView.ShowFocusCues && + DataGridView.Focused) { // Draw focus rectangle ControlPaint.DrawFocusRectangle(g, valBounds, Color.Empty, br.Color); } - if (this.DataGridView.ShowCellErrors && paint && DataGridViewCell.PaintErrorIcon(paintParts)) + if (DataGridView.ShowCellErrors && paint && DataGridViewCell.PaintErrorIcon(paintParts)) { PaintErrorIcon(g, cellStyle, rowIndex, cellBounds, valBounds, errorText); } @@ -980,7 +980,7 @@ public override string Description { get { - DataGridViewImageCell imageCell = this.Owner as DataGridViewImageCell; + DataGridViewImageCell imageCell = Owner as DataGridViewImageCell; if (imageCell != null) { return imageCell.Description; @@ -1007,7 +1007,7 @@ public override string Value public override void DoDefaultAction() { - DataGridViewImageCell dataGridViewCell = (DataGridViewImageCell)this.Owner; + DataGridViewImageCell dataGridViewCell = (DataGridViewImageCell)Owner; DataGridView dataGridView = dataGridViewCell.DataGridView; if (dataGridView != null && dataGridViewCell.RowIndex != -1 && diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageColumn.cs index 95709117f14..486fe93f994 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageColumn.cs @@ -40,7 +40,7 @@ public DataGridViewImageColumn(bool valuesAreIcons) { defaultCellStyle.NullValue = DataGridViewImageCell.ErrorBitmap; } - this.DefaultCellStyle = defaultCellStyle; + DefaultCellStyle = defaultCellStyle; } [ @@ -90,27 +90,27 @@ public string Description { get { - if (this.CellTemplate == null) + if (CellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return this.ImageCellTemplate.Description; + return ImageCellTemplate.Description; } set { - if (this.CellTemplate == null) + if (CellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - this.ImageCellTemplate.Description = value; - if (this.DataGridView != null) + ImageCellTemplate.Description = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewImageCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewImageCell; + DataGridViewImageCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewImageCell; if (dataGridViewCell != null) { dataGridViewCell.Description = value; @@ -128,14 +128,14 @@ public Icon Icon { get { - return this.icon; + return icon; } set { - this.icon = value; - if (this.DataGridView != null) + icon = value; + if (DataGridView != null) { - this.DataGridView.OnColumnCommonChange(this.Index); + DataGridView.OnColumnCommonChange(Index); } } } @@ -149,14 +149,14 @@ public Image Image { get { - return this.image; + return image; } set { - this.image = value; - if (this.DataGridView != null) + image = value; + if (DataGridView != null) { - this.DataGridView.OnColumnCommonChange(this.Index); + DataGridView.OnColumnCommonChange(Index); } } } @@ -165,7 +165,7 @@ private DataGridViewImageCell ImageCellTemplate { get { - return (DataGridViewImageCell)this.CellTemplate; + return (DataGridViewImageCell)CellTemplate; } } @@ -178,11 +178,11 @@ public DataGridViewImageCellLayout ImageLayout { get { - if (this.CellTemplate == null) + if (CellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - DataGridViewImageCellLayout imageLayout = this.ImageCellTemplate.ImageLayout; + DataGridViewImageCellLayout imageLayout = ImageCellTemplate.ImageLayout; if (imageLayout == DataGridViewImageCellLayout.NotSet) { imageLayout = DataGridViewImageCellLayout.Normal; @@ -191,23 +191,23 @@ public DataGridViewImageCellLayout ImageLayout } set { - if (this.ImageLayout != value) + if (ImageLayout != value) { - this.ImageCellTemplate.ImageLayout = value; - if (this.DataGridView != null) + ImageCellTemplate.ImageLayout = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewImageCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewImageCell; + DataGridViewImageCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewImageCell; if (dataGridViewCell != null) { dataGridViewCell.ImageLayoutInternal = value; } } - this.DataGridView.OnColumnCommonChange(this.Index); + DataGridView.OnColumnCommonChange(Index); } } } @@ -221,44 +221,44 @@ public bool ValuesAreIcons { get { - if (this.ImageCellTemplate == null) + if (ImageCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return this.ImageCellTemplate.ValueIsIcon; + return ImageCellTemplate.ValueIsIcon; } set { - if (this.ValuesAreIcons != value) + if (ValuesAreIcons != value) { - this.ImageCellTemplate.ValueIsIconInternal = value; - if (this.DataGridView != null) + ImageCellTemplate.ValueIsIconInternal = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewImageCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewImageCell; + DataGridViewImageCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewImageCell; if (dataGridViewCell != null) { dataGridViewCell.ValueIsIconInternal = value; } } - this.DataGridView.OnColumnCommonChange(this.Index); + DataGridView.OnColumnCommonChange(Index); } if (value && - this.DefaultCellStyle.NullValue is Bitmap && - (Bitmap)this.DefaultCellStyle.NullValue == DataGridViewImageCell.ErrorBitmap) + DefaultCellStyle.NullValue is Bitmap && + (Bitmap)DefaultCellStyle.NullValue == DataGridViewImageCell.ErrorBitmap) { - this.DefaultCellStyle.NullValue = DataGridViewImageCell.ErrorIcon; + DefaultCellStyle.NullValue = DataGridViewImageCell.ErrorIcon; } else if (!value && - this.DefaultCellStyle.NullValue is Icon && - (Icon)this.DefaultCellStyle.NullValue == DataGridViewImageCell.ErrorIcon) + DefaultCellStyle.NullValue is Icon && + (Icon)DefaultCellStyle.NullValue == DataGridViewImageCell.ErrorIcon) { - this.DefaultCellStyle.NullValue = DataGridViewImageCell.ErrorBitmap; + DefaultCellStyle.NullValue = DataGridViewImageCell.ErrorBitmap; } } } @@ -267,7 +267,7 @@ this.DefaultCellStyle.NullValue is Icon && public override object Clone() { DataGridViewImageColumn dataGridViewColumn; - Type thisType = this.GetType(); + Type thisType = GetType(); if (thisType == columnType) //performance improvement { @@ -282,22 +282,22 @@ public override object Clone() if (dataGridViewColumn != null) { base.CloneInternal(dataGridViewColumn); - dataGridViewColumn.Icon = this.icon; - dataGridViewColumn.Image = this.image; + dataGridViewColumn.Icon = icon; + dataGridViewColumn.Image = image; } return dataGridViewColumn; } private bool ShouldSerializeDefaultCellStyle() { - DataGridViewImageCell templateCell = this.CellTemplate as DataGridViewImageCell; + DataGridViewImageCell templateCell = CellTemplate as DataGridViewImageCell; if (templateCell == null) { Debug.Fail("we can't compute the default cell style w/o a template cell"); return true; } - if (!this.HasDefaultCellStyle) + if (!HasDefaultCellStyle) { return false; } @@ -312,7 +312,7 @@ private bool ShouldSerializeDefaultCellStyle() defaultNullValue = DataGridViewImageCell.ErrorBitmap; } - DataGridViewCellStyle defaultCellStyle = this.DefaultCellStyle; + DataGridViewCellStyle defaultCellStyle = DefaultCellStyle; return (!defaultCellStyle.BackColor.IsEmpty || !defaultCellStyle.ForeColor.IsEmpty || @@ -333,9 +333,9 @@ public override string ToString() { StringBuilder sb = new StringBuilder(64); sb.Append("DataGridViewImageColumn { Name="); - sb.Append(this.Name); + sb.Append(Name); sb.Append(", Index="); - sb.Append(this.Index.ToString(CultureInfo.CurrentCulture)); + sb.Append(Index.ToString(CultureInfo.CurrentCulture)); sb.Append(" }"); return sb.ToString(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewIntLinkedList.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewIntLinkedList.cs index 2853cb92309..ebb95f76a0c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewIntLinkedList.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewIntLinkedList.cs @@ -21,7 +21,7 @@ internal class DataGridViewIntLinkedList : IEnumerable IEnumerator IEnumerable.GetEnumerator() { - return new DataGridViewIntLinkedListEnumerator(this.headElement); + return new DataGridViewIntLinkedListEnumerator(headElement); } public DataGridViewIntLinkedList() @@ -44,39 +44,39 @@ public int this[int index] get { Debug.Assert(index >= 0); - Debug.Assert(index < this.count); - if (this.lastAccessedIndex == -1 || index < this.lastAccessedIndex) + Debug.Assert(index < count); + if (lastAccessedIndex == -1 || index < lastAccessedIndex) { - DataGridViewIntLinkedListElement tmp = this.headElement; + DataGridViewIntLinkedListElement tmp = headElement; int tmpIndex = index; while (tmpIndex > 0) { tmp = tmp.Next; tmpIndex--; } - this.lastAccessedElement = tmp; - this.lastAccessedIndex = index; + lastAccessedElement = tmp; + lastAccessedIndex = index; return tmp.Int; } else { - while (this.lastAccessedIndex < index) + while (lastAccessedIndex < index) { - this.lastAccessedElement = this.lastAccessedElement.Next; - this.lastAccessedIndex++; + lastAccessedElement = lastAccessedElement.Next; + lastAccessedIndex++; } - return this.lastAccessedElement.Int; + return lastAccessedElement.Int; } } set { Debug.Assert(index >= 0); - if (index != this.lastAccessedIndex) + if (index != lastAccessedIndex) { int currentInt = this[index]; - Debug.Assert(index == this.lastAccessedIndex); + Debug.Assert(index == lastAccessedIndex); } - this.lastAccessedElement.Int = value; + lastAccessedElement.Int = value; } } @@ -84,7 +84,7 @@ public int Count { get { - return this.count; + return count; } } @@ -92,42 +92,42 @@ public int HeadInt { get { - Debug.Assert(this.headElement != null); - return this.headElement.Int; + Debug.Assert(headElement != null); + return headElement.Int; } } public void Add(int integer) { DataGridViewIntLinkedListElement newHead = new DataGridViewIntLinkedListElement(integer); - if (this.headElement != null) + if (headElement != null) { - newHead.Next = this.headElement; + newHead.Next = headElement; } - this.headElement = newHead; - this.count++; - this.lastAccessedElement = null; - this.lastAccessedIndex = -1; + headElement = newHead; + count++; + lastAccessedElement = null; + lastAccessedIndex = -1; } public void Clear() { - this.lastAccessedElement = null; - this.lastAccessedIndex = -1; - this.headElement = null; - this.count = 0; + lastAccessedElement = null; + lastAccessedIndex = -1; + headElement = null; + count = 0; } public bool Contains(int integer) { int index = 0; - DataGridViewIntLinkedListElement tmp = this.headElement; + DataGridViewIntLinkedListElement tmp = headElement; while (tmp != null) { if (tmp.Int == integer) { - this.lastAccessedElement = tmp; - this.lastAccessedIndex = index; + lastAccessedElement = tmp; + lastAccessedIndex = index; return true; } tmp = tmp.Next; @@ -140,7 +140,7 @@ public int IndexOf(int integer) { if (Contains(integer)) { - return this.lastAccessedIndex; + return lastAccessedIndex; } else { @@ -150,7 +150,7 @@ public int IndexOf(int integer) public bool Remove(int integer) { - DataGridViewIntLinkedListElement tmp1 = null, tmp2 = this.headElement; + DataGridViewIntLinkedListElement tmp1 = null, tmp2 = headElement; while (tmp2 != null) { if (tmp2.Int == integer) @@ -165,15 +165,15 @@ public bool Remove(int integer) DataGridViewIntLinkedListElement tmp3 = tmp2.Next; if (tmp1 == null) { - this.headElement = tmp3; + headElement = tmp3; } else { tmp1.Next = tmp3; } - this.count--; - this.lastAccessedElement = null; - this.lastAccessedIndex = -1; + count--; + lastAccessedElement = null; + lastAccessedIndex = -1; return true; } return false; @@ -181,7 +181,7 @@ public bool Remove(int integer) public void RemoveAt(int index) { - DataGridViewIntLinkedListElement tmp1 = null, tmp2 = this.headElement; + DataGridViewIntLinkedListElement tmp1 = null, tmp2 = headElement; while (index > 0) { tmp1 = tmp2; @@ -191,15 +191,15 @@ public void RemoveAt(int index) DataGridViewIntLinkedListElement tmp3 = tmp2.Next; if (tmp1 == null) { - this.headElement = tmp3; + headElement = tmp3; } else { tmp1.Next = tmp3; } - this.count--; - this.lastAccessedElement = null; - this.lastAccessedIndex = -1; + count--; + lastAccessedElement = null; + lastAccessedIndex = -1; } } @@ -215,38 +215,38 @@ internal class DataGridViewIntLinkedListEnumerator : IEnumerator public DataGridViewIntLinkedListEnumerator(DataGridViewIntLinkedListElement headElement) { this.headElement = headElement; - this.reset = true; + reset = true; } object IEnumerator.Current { get { - Debug.Assert(this.current != null); // Since this is for internal use only. - return this.current.Int; + Debug.Assert(current != null); // Since this is for internal use only. + return current.Int; } } bool IEnumerator.MoveNext() { - if (this.reset) + if (reset) { - Debug.Assert(this.current == null); - this.current = this.headElement; - this.reset = false; + Debug.Assert(current == null); + current = headElement; + reset = false; } else { - Debug.Assert(this.current != null); // Since this is for internal use only. - this.current = this.current.Next; + Debug.Assert(current != null); // Since this is for internal use only. + current = current.Next; } - return (this.current != null); + return (current != null); } void IEnumerator.Reset() { - this.reset = true; - this.current = null; + reset = true; + current = null; } } @@ -267,11 +267,11 @@ public int Int { get { - return this.integer; + return integer; } set { - this.integer = value; + integer = value; } } @@ -279,11 +279,11 @@ public DataGridViewIntLinkedListElement Next { get { - return this.next; + return next; } set { - this.next = value; + next = value; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLayoutData.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLayoutData.cs index bc982e462f6..20cede82c09 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLayoutData.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLayoutData.cs @@ -43,15 +43,15 @@ public LayoutData() public LayoutData(LayoutData src) { - this.ClientRectangle = src.ClientRectangle; - this.TopLeftHeader = src.TopLeftHeader; - this.ColumnHeaders = src.ColumnHeaders; - this.RowHeaders = src.RowHeaders; - this.Inside = src.Inside; - this.Data = src.Data; - this.ResizeBoxRect = src.ResizeBoxRect; - this.ColumnHeadersVisible = src.ColumnHeadersVisible; - this.RowHeadersVisible = src.RowHeadersVisible; + ClientRectangle = src.ClientRectangle; + TopLeftHeader = src.TopLeftHeader; + ColumnHeaders = src.ColumnHeaders; + RowHeaders = src.RowHeaders; + Inside = src.Inside; + Data = src.Data; + ResizeBoxRect = src.ResizeBoxRect; + ColumnHeadersVisible = src.ColumnHeadersVisible; + RowHeadersVisible = src.RowHeadersVisible; } public override string ToString() @@ -90,4 +90,4 @@ public override string ToString() } } } -} \ No newline at end of file +} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkCell.cs index a758e7f718e..0139e6379ac 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkCell.cs @@ -54,13 +54,13 @@ public Color ActiveLinkColor ] get { - if (this.Properties.ContainsObject(PropLinkCellActiveLinkColor)) + if (Properties.ContainsObject(PropLinkCellActiveLinkColor)) { - return (Color)this.Properties.GetObject(PropLinkCellActiveLinkColor); + return (Color)Properties.GetObject(PropLinkCellActiveLinkColor); } else if (SystemInformation.HighContrast) { - return this.HighContrastLinkColor; + return HighContrastLinkColor; } else { @@ -70,18 +70,18 @@ public Color ActiveLinkColor } set { - if (!value.Equals(this.ActiveLinkColor)) + if (!value.Equals(ActiveLinkColor)) { - this.Properties.SetObject(PropLinkCellActiveLinkColor, value); - if (this.DataGridView != null) + Properties.SetObject(PropLinkCellActiveLinkColor, value); + if (DataGridView != null) { - if (this.RowIndex != -1) + if (RowIndex != -1) { - this.DataGridView.InvalidateCell(this); + DataGridView.InvalidateCell(this); } else { - this.DataGridView.InvalidateColumnInternal(this.ColumnIndex); + DataGridView.InvalidateColumnInternal(ColumnIndex); } } } @@ -92,9 +92,9 @@ internal Color ActiveLinkColorInternal { set { - if (!value.Equals(this.ActiveLinkColor)) + if (!value.Equals(ActiveLinkColor)) { - this.Properties.SetObject(PropLinkCellActiveLinkColor, value); + Properties.SetObject(PropLinkCellActiveLinkColor, value); } } } @@ -103,10 +103,10 @@ private bool ShouldSerializeActiveLinkColor() { if (SystemInformation.HighContrast) { - return !this.ActiveLinkColor.Equals(SystemColors.HotTrack); + return !ActiveLinkColor.Equals(SystemColors.HotTrack); } - return !this.ActiveLinkColor.Equals(LinkUtilities.IEActiveLinkColor); + return !ActiveLinkColor.Equals(LinkUtilities.IEActiveLinkColor); } public override Type EditType @@ -132,7 +132,7 @@ public LinkBehavior LinkBehavior get { bool found; - int linkBehavior = this.Properties.GetInteger(PropLinkCellLinkBehavior, out found); + int linkBehavior = Properties.GetInteger(PropLinkCellLinkBehavior, out found); if (found) { return (LinkBehavior)linkBehavior; @@ -146,18 +146,18 @@ public LinkBehavior LinkBehavior { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(LinkBehavior)); } - if (value != this.LinkBehavior) + if (value != LinkBehavior) { - this.Properties.SetInteger(PropLinkCellLinkBehavior, (int)value); - if (this.DataGridView != null) + Properties.SetInteger(PropLinkCellLinkBehavior, (int)value); + if (DataGridView != null) { - if (this.RowIndex != -1) + if (RowIndex != -1) { - this.DataGridView.InvalidateCell(this); + DataGridView.InvalidateCell(this); } else { - this.DataGridView.InvalidateColumnInternal(this.ColumnIndex); + DataGridView.InvalidateColumnInternal(ColumnIndex); } } } @@ -169,9 +169,9 @@ internal LinkBehavior LinkBehaviorInternal set { Debug.Assert(value >= LinkBehavior.SystemDefault && value <= LinkBehavior.NeverUnderline); - if (value != this.LinkBehavior) + if (value != LinkBehavior) { - this.Properties.SetInteger(PropLinkCellLinkBehavior, (int)value); + Properties.SetInteger(PropLinkCellLinkBehavior, (int)value); } } } @@ -183,13 +183,13 @@ public Color LinkColor ] get { - if (this.Properties.ContainsObject(PropLinkCellLinkColor)) + if (Properties.ContainsObject(PropLinkCellLinkColor)) { - return (Color)this.Properties.GetObject(PropLinkCellLinkColor); + return (Color)Properties.GetObject(PropLinkCellLinkColor); } else if (SystemInformation.HighContrast) { - return this.HighContrastLinkColor; + return HighContrastLinkColor; } else { @@ -199,18 +199,18 @@ public Color LinkColor } set { - if (!value.Equals(this.LinkColor)) + if (!value.Equals(LinkColor)) { - this.Properties.SetObject(PropLinkCellLinkColor, value); - if (this.DataGridView != null) + Properties.SetObject(PropLinkCellLinkColor, value); + if (DataGridView != null) { - if (this.RowIndex != -1) + if (RowIndex != -1) { - this.DataGridView.InvalidateCell(this); + DataGridView.InvalidateCell(this); } else { - this.DataGridView.InvalidateColumnInternal(this.ColumnIndex); + DataGridView.InvalidateColumnInternal(ColumnIndex); } } } @@ -221,9 +221,9 @@ internal Color LinkColorInternal { set { - if (!value.Equals(this.LinkColor)) + if (!value.Equals(LinkColor)) { - this.Properties.SetObject(PropLinkCellLinkColor, value); + Properties.SetObject(PropLinkCellLinkColor, value); } } } @@ -232,10 +232,10 @@ private bool ShouldSerializeLinkColor() { if (SystemInformation.HighContrast) { - return !this.LinkColor.Equals(SystemColors.HotTrack); + return !LinkColor.Equals(SystemColors.HotTrack); } - return !this.LinkColor.Equals(LinkUtilities.IELinkColor); + return !LinkColor.Equals(LinkUtilities.IELinkColor); } private LinkState LinkState @@ -243,7 +243,7 @@ private LinkState LinkState get { bool found; - int linkState = this.Properties.GetInteger(PropLinkCellLinkState, out found); + int linkState = Properties.GetInteger(PropLinkCellLinkState, out found); if (found) { return (LinkState)linkState; @@ -252,9 +252,9 @@ private LinkState LinkState } set { - if (this.LinkState != value) + if (LinkState != value) { - this.Properties.SetInteger(PropLinkCellLinkState, (int)value); + Properties.SetInteger(PropLinkCellLinkState, (int)value); } } } @@ -263,9 +263,9 @@ public bool LinkVisited { get { - if (this.linkVisitedSet) + if (linkVisitedSet) { - return this.linkVisited; + return linkVisited; } // the default is false @@ -273,19 +273,19 @@ public bool LinkVisited } set { - this.linkVisitedSet = true; - if (value != this.LinkVisited) + linkVisitedSet = true; + if (value != LinkVisited) { - this.linkVisited = value; - if (this.DataGridView != null) + linkVisited = value; + if (DataGridView != null) { - if (this.RowIndex != -1) + if (RowIndex != -1) { - this.DataGridView.InvalidateCell(this); + DataGridView.InvalidateCell(this); } else { - this.DataGridView.InvalidateColumnInternal(this.ColumnIndex); + DataGridView.InvalidateColumnInternal(ColumnIndex); } } } @@ -294,7 +294,7 @@ public bool LinkVisited private bool ShouldSerializeLinkVisited() { - return this.linkVisitedSet = true; + return linkVisitedSet = true; } [DefaultValue(true)] @@ -303,7 +303,7 @@ public bool TrackVisitedState get { bool found; - int trackVisitedState = this.Properties.GetInteger(PropLinkCellTrackVisitedState, out found); + int trackVisitedState = Properties.GetInteger(PropLinkCellTrackVisitedState, out found); if (found) { return trackVisitedState == 0 ? false : true; @@ -312,18 +312,18 @@ public bool TrackVisitedState } set { - if (value != this.TrackVisitedState) + if (value != TrackVisitedState) { - this.Properties.SetInteger(PropLinkCellTrackVisitedState, value ? 1 : 0); - if (this.DataGridView != null) + Properties.SetInteger(PropLinkCellTrackVisitedState, value ? 1 : 0); + if (DataGridView != null) { - if (this.RowIndex != -1) + if (RowIndex != -1) { - this.DataGridView.InvalidateCell(this); + DataGridView.InvalidateCell(this); } else { - this.DataGridView.InvalidateColumnInternal(this.ColumnIndex); + DataGridView.InvalidateColumnInternal(ColumnIndex); } } } @@ -334,9 +334,9 @@ internal bool TrackVisitedStateInternal { set { - if (value != this.TrackVisitedState) + if (value != TrackVisitedState) { - this.Properties.SetInteger(PropLinkCellTrackVisitedState, value ? 1 : 0); + Properties.SetInteger(PropLinkCellTrackVisitedState, value ? 1 : 0); } } } @@ -347,7 +347,7 @@ public bool UseColumnTextForLinkValue get { bool found; - int useColumnTextForLinkValue = this.Properties.GetInteger(PropLinkCellUseColumnTextForLinkValue, out found); + int useColumnTextForLinkValue = Properties.GetInteger(PropLinkCellUseColumnTextForLinkValue, out found); if (found) { return useColumnTextForLinkValue == 0 ? false : true; @@ -356,9 +356,9 @@ public bool UseColumnTextForLinkValue } set { - if (value != this.UseColumnTextForLinkValue) + if (value != UseColumnTextForLinkValue) { - this.Properties.SetInteger(PropLinkCellUseColumnTextForLinkValue, value ? 1 : 0); + Properties.SetInteger(PropLinkCellUseColumnTextForLinkValue, value ? 1 : 0); OnCommonChange(); } } @@ -369,9 +369,9 @@ internal bool UseColumnTextForLinkValueInternal set { // Caller is responsible for invalidation - if (value != this.UseColumnTextForLinkValue) + if (value != UseColumnTextForLinkValue) { - this.Properties.SetInteger(PropLinkCellUseColumnTextForLinkValue, value ? 1 : 0); + Properties.SetInteger(PropLinkCellUseColumnTextForLinkValue, value ? 1 : 0); } } } @@ -383,13 +383,13 @@ public Color VisitedLinkColor ] get { - if (this.Properties.ContainsObject(PropLinkCellVisitedLinkColor)) + if (Properties.ContainsObject(PropLinkCellVisitedLinkColor)) { - return (Color)this.Properties.GetObject(PropLinkCellVisitedLinkColor); + return (Color)Properties.GetObject(PropLinkCellVisitedLinkColor); } else if (SystemInformation.HighContrast) { - return this.Selected ? SystemColors.HighlightText : LinkUtilities.GetVisitedLinkColor(); + return Selected ? SystemColors.HighlightText : LinkUtilities.GetVisitedLinkColor(); } else { @@ -399,18 +399,18 @@ public Color VisitedLinkColor } set { - if (!value.Equals(this.VisitedLinkColor)) + if (!value.Equals(VisitedLinkColor)) { - this.Properties.SetObject(PropLinkCellVisitedLinkColor, value); - if (this.DataGridView != null) + Properties.SetObject(PropLinkCellVisitedLinkColor, value); + if (DataGridView != null) { - if (this.RowIndex != -1) + if (RowIndex != -1) { - this.DataGridView.InvalidateCell(this); + DataGridView.InvalidateCell(this); } else { - this.DataGridView.InvalidateColumnInternal(this.ColumnIndex); + DataGridView.InvalidateColumnInternal(ColumnIndex); } } } @@ -421,9 +421,9 @@ internal Color VisitedLinkColorInternal { set { - if (!value.Equals(this.VisitedLinkColor)) + if (!value.Equals(VisitedLinkColor)) { - this.Properties.SetObject(PropLinkCellVisitedLinkColor, value); + Properties.SetObject(PropLinkCellVisitedLinkColor, value); } } } @@ -432,10 +432,10 @@ private bool ShouldSerializeVisitedLinkColor() { if (SystemInformation.HighContrast) { - return !this.VisitedLinkColor.Equals(SystemColors.HotTrack); + return !VisitedLinkColor.Equals(SystemColors.HotTrack); } - return !this.VisitedLinkColor.Equals(LinkUtilities.IEVisitedLinkColor); + return !VisitedLinkColor.Equals(LinkUtilities.IEVisitedLinkColor); } private Color HighContrastLinkColor @@ -445,7 +445,7 @@ private Color HighContrastLinkColor { // Selected cells have SystemColors.Highlight as a background. // SystemColors.HighlightText is supposed to be in contrast with SystemColors.Highlight. - return this.Selected ? SystemColors.HighlightText : SystemColors.HotTrack; + return Selected ? SystemColors.HighlightText : SystemColors.HotTrack; } } @@ -465,7 +465,7 @@ public override Type ValueType public override object Clone() { DataGridViewLinkCell dataGridViewCell; - Type thisType = this.GetType(); + Type thisType = GetType(); if (thisType == cellType) //performance improvement { @@ -479,39 +479,39 @@ public override object Clone() } base.CloneInternal(dataGridViewCell); - if (this.Properties.ContainsObject(PropLinkCellActiveLinkColor)) + if (Properties.ContainsObject(PropLinkCellActiveLinkColor)) { - dataGridViewCell.ActiveLinkColorInternal = this.ActiveLinkColor; + dataGridViewCell.ActiveLinkColorInternal = ActiveLinkColor; } - if (this.Properties.ContainsInteger(PropLinkCellUseColumnTextForLinkValue)) + if (Properties.ContainsInteger(PropLinkCellUseColumnTextForLinkValue)) { - dataGridViewCell.UseColumnTextForLinkValueInternal = this.UseColumnTextForLinkValue; + dataGridViewCell.UseColumnTextForLinkValueInternal = UseColumnTextForLinkValue; } - if (this.Properties.ContainsInteger(PropLinkCellLinkBehavior)) + if (Properties.ContainsInteger(PropLinkCellLinkBehavior)) { - dataGridViewCell.LinkBehaviorInternal = this.LinkBehavior; + dataGridViewCell.LinkBehaviorInternal = LinkBehavior; } - if (this.Properties.ContainsObject(PropLinkCellLinkColor)) + if (Properties.ContainsObject(PropLinkCellLinkColor)) { - dataGridViewCell.LinkColorInternal = this.LinkColor; + dataGridViewCell.LinkColorInternal = LinkColor; } - if (this.Properties.ContainsInteger(PropLinkCellTrackVisitedState)) + if (Properties.ContainsInteger(PropLinkCellTrackVisitedState)) { - dataGridViewCell.TrackVisitedStateInternal = this.TrackVisitedState; + dataGridViewCell.TrackVisitedStateInternal = TrackVisitedState; } - if (this.Properties.ContainsObject(PropLinkCellVisitedLinkColor)) + if (Properties.ContainsObject(PropLinkCellVisitedLinkColor)) { - dataGridViewCell.VisitedLinkColorInternal = this.VisitedLinkColor; + dataGridViewCell.VisitedLinkColorInternal = VisitedLinkColor; } - if (this.linkVisitedSet) + if (linkVisitedSet) { - dataGridViewCell.LinkVisited = this.LinkVisited; + dataGridViewCell.LinkVisited = LinkVisited; } return dataGridViewCell; @@ -536,13 +536,13 @@ protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCel throw new ArgumentNullException(nameof(cellStyle)); } - if (this.DataGridView == null || rowIndex < 0 || this.OwningColumn == null) + if (DataGridView == null || rowIndex < 0 || OwningColumn == null) { return Rectangle.Empty; } object value = GetValue(rowIndex); - object formattedValue = this.GetFormattedValue(value, rowIndex, ref cellStyle, null, null, DataGridViewDataErrorContexts.Formatting); + object formattedValue = GetFormattedValue(value, rowIndex, ref cellStyle, null, null, DataGridViewDataErrorContexts.Formatting); DataGridViewAdvancedBorderStyle dgvabsEffective; DataGridViewElementStates cellState; @@ -591,17 +591,17 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC throw new ArgumentNullException(nameof(cellStyle)); } - if (this.DataGridView == null || + if (DataGridView == null || rowIndex < 0 || - this.OwningColumn == null || - !this.DataGridView.ShowCellErrors || + OwningColumn == null || + !DataGridView.ShowCellErrors || string.IsNullOrEmpty(GetErrorText(rowIndex))) { return Rectangle.Empty; } object value = GetValue(rowIndex); - object formattedValue = this.GetFormattedValue(value, rowIndex, ref cellStyle, null, null, DataGridViewDataErrorContexts.Formatting); + object formattedValue = GetFormattedValue(value, rowIndex, ref cellStyle, null, null, DataGridViewDataErrorContexts.Formatting); DataGridViewAdvancedBorderStyle dgvabsEffective; DataGridViewElementStates cellState; @@ -628,7 +628,7 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize) { - if (this.DataGridView == null) + if (DataGridView == null) { return new Size(-1, -1); } @@ -639,7 +639,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl } Size preferredSize; - Rectangle borderWidthsRect = this.StdBorderWidths; + Rectangle borderWidthsRect = StdBorderWidths; int borderAndPaddingWidths = borderWidthsRect.Left + borderWidthsRect.Width + cellStyle.Padding.Horizontal; int borderAndPaddingHeights = borderWidthsRect.Top + borderWidthsRect.Height + cellStyle.Padding.Vertical; DataGridViewFreeDimension freeDimension = DataGridViewCell.GetFreeDimensionFromConstraint(constraintSize); @@ -649,7 +649,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl { formattedString = " "; } - TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); + TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); if (cellStyle.WrapMode == DataGridViewTriState.True && formattedString.Length > 1) { switch (freeDimension) @@ -717,7 +717,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl if (freeDimension != DataGridViewFreeDimension.Height) { preferredSize.Width += DATAGRIDVIEWLINKCELL_horizontalTextMarginLeft + DATAGRIDVIEWLINKCELL_horizontalTextMarginRight + borderAndPaddingWidths; - if (this.DataGridView.ShowCellErrors) + if (DataGridView.ShowCellErrors) { // Making sure that there is enough room for the potential error icon preferredSize.Width = Math.Max(preferredSize.Width, borderAndPaddingWidths + DATAGRIDVIEWCELL_iconMarginWidth * 2 + iconsWidth); @@ -730,7 +730,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl { preferredSize.Height += DATAGRIDVIEWLINKCELL_verticalTextMarginBottom; } - if (this.DataGridView.ShowCellErrors) + if (DataGridView.ShowCellErrors) { // Making sure that there is enough room for the potential error icon preferredSize.Height = Math.Max(preferredSize.Height, borderAndPaddingHeights + DATAGRIDVIEWCELL_iconMarginHeight * 2 + iconsHeight); @@ -741,13 +741,13 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl protected override object GetValue(int rowIndex) { - if (this.UseColumnTextForLinkValue && - this.DataGridView != null && - this.DataGridView.NewRowIndex != rowIndex && - this.OwningColumn != null && - this.OwningColumn is DataGridViewLinkColumn) + if (UseColumnTextForLinkValue && + DataGridView != null && + DataGridView.NewRowIndex != rowIndex && + OwningColumn != null && + OwningColumn is DataGridViewLinkColumn) { - return ((DataGridViewLinkColumn)this.OwningColumn).Text; + return ((DataGridViewLinkColumn)OwningColumn).Text; } return base.GetValue(rowIndex); } @@ -756,7 +756,7 @@ protected override bool KeyUpUnsharesRow(KeyEventArgs e, int rowIndex) { if (e.KeyCode == Keys.Space && !e.Alt && !e.Control && !e.Shift) { - return this.TrackVisitedState && !this.LinkVisited; + return TrackVisitedState && !LinkVisited; } else { @@ -771,21 +771,21 @@ protected override bool MouseDownUnsharesRow(DataGridViewCellMouseEventArgs e) protected override bool MouseLeaveUnsharesRow(int rowIndex) { - return this.LinkState != LinkState.Normal; + return LinkState != LinkState.Normal; } protected override bool MouseMoveUnsharesRow(DataGridViewCellMouseEventArgs e) { if (LinkBoundsContainPoint(e.X, e.Y, e.RowIndex)) { - if ((this.LinkState & LinkState.Hover) == 0) + if ((LinkState & LinkState.Hover) == 0) { return true; } } else { - if ((this.LinkState & LinkState.Hover) != 0) + if ((LinkState & LinkState.Hover) != 0) { return true; } @@ -795,26 +795,26 @@ protected override bool MouseMoveUnsharesRow(DataGridViewCellMouseEventArgs e) protected override bool MouseUpUnsharesRow(DataGridViewCellMouseEventArgs e) { - return this.TrackVisitedState && LinkBoundsContainPoint(e.X, e.Y, e.RowIndex); + return TrackVisitedState && LinkBoundsContainPoint(e.X, e.Y, e.RowIndex); } protected override void OnKeyUp(KeyEventArgs e, int rowIndex) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } if (e.KeyCode == Keys.Space && !e.Alt && !e.Control && !e.Shift) { - RaiseCellClick(new DataGridViewCellEventArgs(this.ColumnIndex, rowIndex)); - if (this.DataGridView != null && - this.ColumnIndex < this.DataGridView.Columns.Count && - rowIndex < this.DataGridView.Rows.Count) + RaiseCellClick(new DataGridViewCellEventArgs(ColumnIndex, rowIndex)); + if (DataGridView != null && + ColumnIndex < DataGridView.Columns.Count && + rowIndex < DataGridView.Rows.Count) { - RaiseCellContentClick(new DataGridViewCellEventArgs(this.ColumnIndex, rowIndex)); - if (this.TrackVisitedState) + RaiseCellContentClick(new DataGridViewCellEventArgs(ColumnIndex, rowIndex)); + if (TrackVisitedState) { - this.LinkVisited = true; + LinkVisited = true; } } e.Handled = true; @@ -823,14 +823,14 @@ protected override void OnKeyUp(KeyEventArgs e, int rowIndex) protected override void OnMouseDown(DataGridViewCellMouseEventArgs e) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } if (LinkBoundsContainPoint(e.X, e.Y, e.RowIndex)) { - this.LinkState |= LinkState.Active; - this.DataGridView.InvalidateCell(this.ColumnIndex, e.RowIndex); + LinkState |= LinkState.Active; + DataGridView.InvalidateCell(ColumnIndex, e.RowIndex); } base.OnMouseDown(e); @@ -838,19 +838,19 @@ protected override void OnMouseDown(DataGridViewCellMouseEventArgs e) protected override void OnMouseLeave(int rowIndex) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } if (dataGridViewCursor != null) { - this.DataGridView.Cursor = dataGridViewCursor; + DataGridView.Cursor = dataGridViewCursor; dataGridViewCursor = null; } - if (this.LinkState != LinkState.Normal) + if (LinkState != LinkState.Normal) { - this.LinkState = LinkState.Normal; - this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex); + LinkState = LinkState.Normal; + DataGridView.InvalidateCell(ColumnIndex, rowIndex); } base.OnMouseLeave(rowIndex); @@ -858,35 +858,35 @@ protected override void OnMouseLeave(int rowIndex) protected override void OnMouseMove(DataGridViewCellMouseEventArgs e) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } if (LinkBoundsContainPoint(e.X, e.Y, e.RowIndex)) { - if ((this.LinkState & LinkState.Hover) == 0) + if ((LinkState & LinkState.Hover) == 0) { - this.LinkState |= LinkState.Hover; - this.DataGridView.InvalidateCell(this.ColumnIndex, e.RowIndex); + LinkState |= LinkState.Hover; + DataGridView.InvalidateCell(ColumnIndex, e.RowIndex); } if (dataGridViewCursor == null) { - dataGridViewCursor = this.DataGridView.UserSetCursor; + dataGridViewCursor = DataGridView.UserSetCursor; } - if (this.DataGridView.Cursor != Cursors.Hand) + if (DataGridView.Cursor != Cursors.Hand) { - this.DataGridView.Cursor = Cursors.Hand; + DataGridView.Cursor = Cursors.Hand; } } else { - if ((this.LinkState & LinkState.Hover) != 0) + if ((LinkState & LinkState.Hover) != 0) { - this.LinkState &= ~LinkState.Hover; - this.DataGridView.Cursor = dataGridViewCursor; - this.DataGridView.InvalidateCell(this.ColumnIndex, e.RowIndex); + LinkState &= ~LinkState.Hover; + DataGridView.Cursor = dataGridViewCursor; + DataGridView.InvalidateCell(ColumnIndex, e.RowIndex); } } @@ -895,13 +895,13 @@ protected override void OnMouseMove(DataGridViewCellMouseEventArgs e) protected override void OnMouseUp(DataGridViewCellMouseEventArgs e) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } - if (LinkBoundsContainPoint(e.X, e.Y, e.RowIndex) && this.TrackVisitedState) + if (LinkBoundsContainPoint(e.X, e.Y, e.RowIndex) && TrackVisitedState) { - this.LinkVisited = true; + LinkVisited = true; } } @@ -981,10 +981,10 @@ private Rectangle PaintPrivate(Graphics g, valBounds.Width -= borderWidths.Right; valBounds.Height -= borderWidths.Bottom; - Point ptCurrentCell = this.DataGridView.CurrentCellAddress; - bool cellCurrent = ptCurrentCell.X == this.ColumnIndex && ptCurrentCell.Y == rowIndex; + Point ptCurrentCell = DataGridView.CurrentCellAddress; + bool cellCurrent = ptCurrentCell.X == ColumnIndex && ptCurrentCell.Y == rowIndex; bool cellSelected = (cellState & DataGridViewElementStates.Selected) != 0; - SolidBrush br = this.DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor); + SolidBrush br = DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor); if (paint && DataGridViewCell.PaintBackground(paintParts) && br.Color.A == 255) { @@ -993,7 +993,7 @@ private Rectangle PaintPrivate(Graphics g, if (cellStyle.Padding != Padding.Empty) { - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { valBounds.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top); } @@ -1021,23 +1021,23 @@ private Rectangle PaintPrivate(Graphics g, Font linkFont = null; Font hoverFont = null; - LinkUtilities.EnsureLinkFonts(cellStyle.Font, this.LinkBehavior, ref linkFont, ref hoverFont); - TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); + LinkUtilities.EnsureLinkFonts(cellStyle.Font, LinkBehavior, ref linkFont, ref hoverFont); + TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); // paint the focus rectangle around the link if (paint) { if (valBounds.Width > 0 && valBounds.Height > 0) { if (cellCurrent && - this.DataGridView.ShowFocusCues && - this.DataGridView.Focused && + DataGridView.ShowFocusCues && + DataGridView.Focused && DataGridViewCell.PaintFocus(paintParts)) { Rectangle focusBounds = DataGridViewUtilities.GetTextBounds(valBounds, formattedValueStr, flags, cellStyle, - this.LinkState == LinkState.Hover ? hoverFont : linkFont); + LinkState == LinkState.Hover ? hoverFont : linkFont); if ((cellStyle.Alignment & anyLeft) != 0) { focusBounds.X--; @@ -1052,17 +1052,17 @@ private Rectangle PaintPrivate(Graphics g, ControlPaint.DrawFocusRectangle(g, focusBounds, Color.Empty, br.Color); } Color linkColor; - if ((this.LinkState & LinkState.Active) == LinkState.Active) + if ((LinkState & LinkState.Active) == LinkState.Active) { - linkColor = this.ActiveLinkColor; + linkColor = ActiveLinkColor; } - else if (this.LinkVisited) + else if (LinkVisited) { - linkColor = this.VisitedLinkColor; + linkColor = VisitedLinkColor; } else { - linkColor = this.LinkColor; + linkColor = LinkColor; } if (DataGridViewCell.PaintContentForeground(paintParts)) { @@ -1072,15 +1072,15 @@ private Rectangle PaintPrivate(Graphics g, } TextRenderer.DrawText(g, formattedValueStr, - this.LinkState == LinkState.Hover ? hoverFont : linkFont, + LinkState == LinkState.Hover ? hoverFont : linkFont, valBounds, linkColor, flags); } } else if (cellCurrent && - this.DataGridView.ShowFocusCues && - this.DataGridView.Focused && + DataGridView.ShowFocusCues && + DataGridView.Focused && DataGridViewCell.PaintFocus(paintParts) && errorBounds.Width > 0 && errorBounds.Height > 0) @@ -1096,7 +1096,7 @@ private Rectangle PaintPrivate(Graphics g, formattedValueStr, flags, cellStyle, - this.LinkState == LinkState.Hover ? hoverFont : linkFont); + LinkState == LinkState.Hover ? hoverFont : linkFont); } linkFont.Dispose(); hoverFont.Dispose(); @@ -1104,8 +1104,8 @@ private Rectangle PaintPrivate(Graphics g, else if (paint || computeContentBounds) { if (cellCurrent && - this.DataGridView.ShowFocusCues && - this.DataGridView.Focused && + DataGridView.ShowFocusCues && + DataGridView.Focused && DataGridViewCell.PaintFocus(paintParts) && paint && valBounds.Width > 0 && @@ -1123,7 +1123,7 @@ private Rectangle PaintPrivate(Graphics g, } } - if (this.DataGridView.ShowCellErrors && paint && DataGridViewCell.PaintErrorIcon(paintParts)) + if (DataGridView.ShowCellErrors && paint && DataGridViewCell.PaintErrorIcon(paintParts)) { PaintErrorIcon(g, cellStyle, rowIndex, cellBounds, errorBounds, errorText); } @@ -1153,7 +1153,7 @@ public override string DefaultAction public override void DoDefaultAction() { - DataGridViewLinkCell dataGridViewCell = (DataGridViewLinkCell)this.Owner; + DataGridViewLinkCell dataGridViewCell = (DataGridViewLinkCell)Owner; DataGridView dataGridView = dataGridViewCell.DataGridView; if (dataGridView != null && dataGridViewCell.RowIndex == -1) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkColumn.cs index c22c4df69f7..38fa76c4187 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkColumn.cs @@ -30,31 +30,31 @@ public Color ActiveLinkColor { get { - if (this.CellTemplate == null) + if (CellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return ((DataGridViewLinkCell)this.CellTemplate).ActiveLinkColor; + return ((DataGridViewLinkCell)CellTemplate).ActiveLinkColor; } set { - if (!this.ActiveLinkColor.Equals(value)) + if (!ActiveLinkColor.Equals(value)) { - ((DataGridViewLinkCell)this.CellTemplate).ActiveLinkColorInternal = value; - if (this.DataGridView != null) + ((DataGridViewLinkCell)CellTemplate).ActiveLinkColorInternal = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewLinkCell; + DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewLinkCell; if (dataGridViewCell != null) { dataGridViewCell.ActiveLinkColorInternal = value; } } - this.DataGridView.InvalidateColumn(this.Index); + DataGridView.InvalidateColumn(Index); } } } @@ -64,10 +64,10 @@ private bool ShouldSerializeActiveLinkColor() { if (SystemInformation.HighContrast) { - return !this.ActiveLinkColor.Equals(SystemColors.HotTrack); + return !ActiveLinkColor.Equals(SystemColors.HotTrack); } - return !this.ActiveLinkColor.Equals(LinkUtilities.IEActiveLinkColor); + return !ActiveLinkColor.Equals(LinkUtilities.IEActiveLinkColor); } [ @@ -99,31 +99,31 @@ public LinkBehavior LinkBehavior { get { - if (this.CellTemplate == null) + if (CellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return ((DataGridViewLinkCell)this.CellTemplate).LinkBehavior; + return ((DataGridViewLinkCell)CellTemplate).LinkBehavior; } set { - if (!this.LinkBehavior.Equals(value)) + if (!LinkBehavior.Equals(value)) { - ((DataGridViewLinkCell)this.CellTemplate).LinkBehavior = value; - if (this.DataGridView != null) + ((DataGridViewLinkCell)CellTemplate).LinkBehavior = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewLinkCell; + DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewLinkCell; if (dataGridViewCell != null) { dataGridViewCell.LinkBehaviorInternal = value; } } - this.DataGridView.InvalidateColumn(this.Index); + DataGridView.InvalidateColumn(Index); } } } @@ -137,31 +137,31 @@ public Color LinkColor { get { - if (this.CellTemplate == null) + if (CellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return ((DataGridViewLinkCell)this.CellTemplate).LinkColor; + return ((DataGridViewLinkCell)CellTemplate).LinkColor; } set { - if (!this.LinkColor.Equals(value)) + if (!LinkColor.Equals(value)) { - ((DataGridViewLinkCell)this.CellTemplate).LinkColorInternal = value; - if (this.DataGridView != null) + ((DataGridViewLinkCell)CellTemplate).LinkColorInternal = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewLinkCell; + DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewLinkCell; if (dataGridViewCell != null) { dataGridViewCell.LinkColorInternal = value; } } - this.DataGridView.InvalidateColumn(this.Index); + DataGridView.InvalidateColumn(Index); } } } @@ -171,10 +171,10 @@ private bool ShouldSerializeLinkColor() { if (SystemInformation.HighContrast) { - return !this.LinkColor.Equals(SystemColors.HotTrack); + return !LinkColor.Equals(SystemColors.HotTrack); } - return !this.LinkColor.Equals(LinkUtilities.IELinkColor); + return !LinkColor.Equals(LinkUtilities.IELinkColor); } [ @@ -186,34 +186,34 @@ public string Text { get { - return this.text; + return text; } set { - if (!string.Equals(value, this.text, StringComparison.Ordinal)) + if (!string.Equals(value, text, StringComparison.Ordinal)) { - this.text = value; - if (this.DataGridView != null) + text = value; + if (DataGridView != null) { - if (this.UseColumnTextForLinkValue) + if (UseColumnTextForLinkValue) { - this.DataGridView.OnColumnCommonChange(this.Index); + DataGridView.OnColumnCommonChange(Index); } else { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewLinkCell; + DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewLinkCell; if (dataGridViewCell != null && dataGridViewCell.UseColumnTextForLinkValue) { - this.DataGridView.OnColumnCommonChange(this.Index); + DataGridView.OnColumnCommonChange(Index); return; } } - this.DataGridView.InvalidateColumn(this.Index); + DataGridView.InvalidateColumn(Index); } } } @@ -229,31 +229,31 @@ public bool TrackVisitedState { get { - if (this.CellTemplate == null) + if (CellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return ((DataGridViewLinkCell)this.CellTemplate).TrackVisitedState; + return ((DataGridViewLinkCell)CellTemplate).TrackVisitedState; } set { - if (this.TrackVisitedState != value) + if (TrackVisitedState != value) { - ((DataGridViewLinkCell)this.CellTemplate).TrackVisitedStateInternal = value; - if (this.DataGridView != null) + ((DataGridViewLinkCell)CellTemplate).TrackVisitedStateInternal = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewLinkCell; + DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewLinkCell; if (dataGridViewCell != null) { dataGridViewCell.TrackVisitedStateInternal = value; } } - this.DataGridView.InvalidateColumn(this.Index); + DataGridView.InvalidateColumn(Index); } } } @@ -268,31 +268,31 @@ public bool UseColumnTextForLinkValue { get { - if (this.CellTemplate == null) + if (CellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return ((DataGridViewLinkCell)this.CellTemplate).UseColumnTextForLinkValue; + return ((DataGridViewLinkCell)CellTemplate).UseColumnTextForLinkValue; } set { - if (this.UseColumnTextForLinkValue != value) + if (UseColumnTextForLinkValue != value) { - ((DataGridViewLinkCell)this.CellTemplate).UseColumnTextForLinkValueInternal = value; - if (this.DataGridView != null) + ((DataGridViewLinkCell)CellTemplate).UseColumnTextForLinkValueInternal = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewLinkCell; + DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewLinkCell; if (dataGridViewCell != null) { dataGridViewCell.UseColumnTextForLinkValueInternal = value; } } - this.DataGridView.OnColumnCommonChange(this.Index); + DataGridView.OnColumnCommonChange(Index); } } } @@ -306,31 +306,31 @@ public Color VisitedLinkColor { get { - if (this.CellTemplate == null) + if (CellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return ((DataGridViewLinkCell)this.CellTemplate).VisitedLinkColor; + return ((DataGridViewLinkCell)CellTemplate).VisitedLinkColor; } set { - if (!this.VisitedLinkColor.Equals(value)) + if (!VisitedLinkColor.Equals(value)) { - ((DataGridViewLinkCell)this.CellTemplate).VisitedLinkColorInternal = value; - if (this.DataGridView != null) + ((DataGridViewLinkCell)CellTemplate).VisitedLinkColorInternal = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewLinkCell; + DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewLinkCell; if (dataGridViewCell != null) { dataGridViewCell.VisitedLinkColorInternal = value; } } - this.DataGridView.InvalidateColumn(this.Index); + DataGridView.InvalidateColumn(Index); } } } @@ -340,16 +340,16 @@ private bool ShouldSerializeVisitedLinkColor() { if (SystemInformation.HighContrast) { - return !this.VisitedLinkColor.Equals(SystemColors.HotTrack); + return !VisitedLinkColor.Equals(SystemColors.HotTrack); } - return !this.VisitedLinkColor.Equals(LinkUtilities.IEVisitedLinkColor); + return !VisitedLinkColor.Equals(LinkUtilities.IEVisitedLinkColor); } public override object Clone() { DataGridViewLinkColumn dataGridViewColumn; - Type thisType = this.GetType(); + Type thisType = GetType(); if (thisType == columnType) //performance improvement { @@ -364,7 +364,7 @@ public override object Clone() if (dataGridViewColumn != null) { base.CloneInternal(dataGridViewColumn); - dataGridViewColumn.Text = this.text; + dataGridViewColumn.Text = text; } return dataGridViewColumn; } @@ -373,9 +373,9 @@ public override string ToString() { StringBuilder sb = new StringBuilder(64); sb.Append("DataGridViewLinkColumn { Name="); - sb.Append(this.Name); + sb.Append(Name); sb.Append(", Index="); - sb.Append(this.Index.ToString(CultureInfo.CurrentCulture)); + sb.Append(Index.ToString(CultureInfo.CurrentCulture)); sb.Append(" }"); return sb.ToString(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs index 89dc531dcd2..f87559e22cb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs @@ -28,21 +28,21 @@ public partial class DataGridView { protected virtual void AccessibilityNotifyCurrentCellChanged(Point cellAddress) { - if (cellAddress.X < 0 || cellAddress.X >= this.Columns.Count) + if (cellAddress.X < 0 || cellAddress.X >= Columns.Count) { throw new ArgumentOutOfRangeException(nameof(cellAddress)); } - if (cellAddress.Y < 0 || cellAddress.Y >= this.Rows.Count) + if (cellAddress.Y < 0 || cellAddress.Y >= Rows.Count) { throw new ArgumentOutOfRangeException(nameof(cellAddress)); } - int visibleRowIndex = this.Rows.GetRowCount(DataGridViewElementStates.Visible, 0, cellAddress.Y); - int visibleColumnIndex = this.Columns.ColumnIndexToActualDisplayIndex(cellAddress.X, DataGridViewElementStates.Visible); + int visibleRowIndex = Rows.GetRowCount(DataGridViewElementStates.Visible, 0, cellAddress.Y); + int visibleColumnIndex = Columns.ColumnIndexToActualDisplayIndex(cellAddress.X, DataGridViewElementStates.Visible); - int topHeaderRowIncrement = this.ColumnHeadersVisible ? 1 : 0; - int rowHeaderIncrement = this.RowHeadersVisible ? 1 : 0; + int topHeaderRowIncrement = ColumnHeadersVisible ? 1 : 0; + int rowHeaderIncrement = RowHeadersVisible ? 1 : 0; int objectID = visibleRowIndex + topHeaderRowIncrement // + 1 because the top header row acc obj is at index 0 + 1; // + 1 because objectID's need to be positive and non-zero @@ -50,34 +50,34 @@ protected virtual void AccessibilityNotifyCurrentCellChanged(Point cellAddress) int childID = visibleColumnIndex + rowHeaderIncrement; // + 1 because the column header cell is at index 0 in top header row acc obj // same thing for the row header cell in the data grid view row acc obj - if (this.ContainsFocus) + if (ContainsFocus) { - this.AccessibilityNotifyClients(AccessibleEvents.Focus, objectID, childID); + AccessibilityNotifyClients(AccessibleEvents.Focus, objectID, childID); CurrentCell?.AccessibilityObject.SetFocus(); } - this.AccessibilityNotifyClients(AccessibleEvents.Selection, objectID, childID); + AccessibilityNotifyClients(AccessibleEvents.Selection, objectID, childID); } internal void ActivateToolTip(bool activate, string toolTipText, int columnIndex, int rowIndex) { - this.toolTipCaption = toolTipText; - this.ptToolTipCell = new Point(columnIndex, rowIndex); - this.toolTipControl.Activate(activate); + toolTipCaption = toolTipText; + ptToolTipCell = new Point(columnIndex, rowIndex); + toolTipControl.Activate(activate); } internal void AddNewRow(bool createdByEditing) { - Debug.Assert(this.Columns.Count > 0); - Debug.Assert(this.newRowIndex == -1); + Debug.Assert(Columns.Count > 0); + Debug.Assert(newRowIndex == -1); - this.Rows.AddInternal(true /*newRow*/, null /*values*/); - this.newRowIndex = this.Rows.Count - 1; - this.dataGridViewState1[DATAGRIDVIEWSTATE1_newRowCreatedByEditing] = createdByEditing; + Rows.AddInternal(true /*newRow*/, null /*values*/); + newRowIndex = Rows.Count - 1; + dataGridViewState1[DATAGRIDVIEWSTATE1_newRowCreatedByEditing] = createdByEditing; if (createdByEditing) { - DataGridViewRowEventArgs dgvre = new DataGridViewRowEventArgs(this.Rows[this.newRowIndex]); + DataGridViewRowEventArgs dgvre = new DataGridViewRowEventArgs(Rows[newRowIndex]); OnUserAddedRow(dgvre); } } @@ -90,18 +90,18 @@ public virtual DataGridViewAdvancedBorderStyle AdjustColumnHeaderBorderStyle(Dat bool isFirstDisplayedColumn, bool isLastVisibleColumn) { - if (this.ApplyVisualStylesToHeaderCells) + if (ApplyVisualStylesToHeaderCells) { switch (dataGridViewAdvancedBorderStyleInput.All) { case DataGridViewAdvancedCellBorderStyle.OutsetPartial: case DataGridViewAdvancedCellBorderStyle.OutsetDouble: - if (this.RightToLeftInternal) + if (RightToLeftInternal) { dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = DataGridViewAdvancedCellBorderStyle.None; if (isFirstDisplayedColumn) { - dataGridViewAdvancedBorderStylePlaceholder.RightInternal = this.RowHeadersVisible ? DataGridViewAdvancedCellBorderStyle.None : DataGridViewAdvancedCellBorderStyle.Outset; + dataGridViewAdvancedBorderStylePlaceholder.RightInternal = RowHeadersVisible ? DataGridViewAdvancedCellBorderStyle.None : DataGridViewAdvancedCellBorderStyle.Outset; } else { @@ -112,7 +112,7 @@ public virtual DataGridViewAdvancedBorderStyle AdjustColumnHeaderBorderStyle(Dat { if (isFirstDisplayedColumn) { - dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = this.RowHeadersVisible ? DataGridViewAdvancedCellBorderStyle.None : DataGridViewAdvancedCellBorderStyle.OutsetDouble; + dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = RowHeadersVisible ? DataGridViewAdvancedCellBorderStyle.None : DataGridViewAdvancedCellBorderStyle.OutsetDouble; } else { @@ -125,12 +125,12 @@ public virtual DataGridViewAdvancedBorderStyle AdjustColumnHeaderBorderStyle(Dat return dataGridViewAdvancedBorderStylePlaceholder; case DataGridViewAdvancedCellBorderStyle.InsetDouble: - if (this.RightToLeftInternal) + if (RightToLeftInternal) { dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = DataGridViewAdvancedCellBorderStyle.None; if (isFirstDisplayedColumn) { - dataGridViewAdvancedBorderStylePlaceholder.RightInternal = this.RowHeadersVisible ? DataGridViewAdvancedCellBorderStyle.None : DataGridViewAdvancedCellBorderStyle.Inset; + dataGridViewAdvancedBorderStylePlaceholder.RightInternal = RowHeadersVisible ? DataGridViewAdvancedCellBorderStyle.None : DataGridViewAdvancedCellBorderStyle.Inset; } else { @@ -141,7 +141,7 @@ public virtual DataGridViewAdvancedBorderStyle AdjustColumnHeaderBorderStyle(Dat { if (isFirstDisplayedColumn) { - dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = this.RowHeadersVisible ? DataGridViewAdvancedCellBorderStyle.None : DataGridViewAdvancedCellBorderStyle.InsetDouble; + dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = RowHeadersVisible ? DataGridViewAdvancedCellBorderStyle.None : DataGridViewAdvancedCellBorderStyle.InsetDouble; } else { @@ -156,7 +156,7 @@ public virtual DataGridViewAdvancedBorderStyle AdjustColumnHeaderBorderStyle(Dat case DataGridViewAdvancedCellBorderStyle.Single: case DataGridViewAdvancedCellBorderStyle.Outset: case DataGridViewAdvancedCellBorderStyle.Inset: - if (!isFirstDisplayedColumn || this.RowHeadersVisible) + if (!isFirstDisplayedColumn || RowHeadersVisible) { dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = DataGridViewAdvancedCellBorderStyle.None; dataGridViewAdvancedBorderStylePlaceholder.RightInternal = DataGridViewAdvancedCellBorderStyle.None; @@ -167,7 +167,7 @@ public virtual DataGridViewAdvancedBorderStyle AdjustColumnHeaderBorderStyle(Dat else { // isFirstDisplayedColumn == true && this.RowHeadersVisible == false - if (this.RightToLeftInternal) + if (RightToLeftInternal) { dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = DataGridViewAdvancedCellBorderStyle.None; dataGridViewAdvancedBorderStylePlaceholder.RightInternal = dataGridViewAdvancedBorderStyleInput.All; @@ -188,12 +188,12 @@ public virtual DataGridViewAdvancedBorderStyle AdjustColumnHeaderBorderStyle(Dat switch (dataGridViewAdvancedBorderStyleInput.All) { case DataGridViewAdvancedCellBorderStyle.OutsetPartial: - if (this.RightToLeftInternal) + if (RightToLeftInternal) { dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = isLastVisibleColumn ? DataGridViewAdvancedCellBorderStyle.Outset : DataGridViewAdvancedCellBorderStyle.OutsetPartial; if (isFirstDisplayedColumn) { - dataGridViewAdvancedBorderStylePlaceholder.RightInternal = this.RowHeadersVisible ? DataGridViewAdvancedCellBorderStyle.Outset : DataGridViewAdvancedCellBorderStyle.OutsetDouble; + dataGridViewAdvancedBorderStylePlaceholder.RightInternal = RowHeadersVisible ? DataGridViewAdvancedCellBorderStyle.Outset : DataGridViewAdvancedCellBorderStyle.OutsetDouble; } else { @@ -204,7 +204,7 @@ public virtual DataGridViewAdvancedBorderStyle AdjustColumnHeaderBorderStyle(Dat { if (isFirstDisplayedColumn) { - dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = this.RowHeadersVisible ? DataGridViewAdvancedCellBorderStyle.Outset : DataGridViewAdvancedCellBorderStyle.OutsetDouble; + dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = RowHeadersVisible ? DataGridViewAdvancedCellBorderStyle.Outset : DataGridViewAdvancedCellBorderStyle.OutsetDouble; } else { @@ -217,12 +217,12 @@ public virtual DataGridViewAdvancedBorderStyle AdjustColumnHeaderBorderStyle(Dat return dataGridViewAdvancedBorderStylePlaceholder; case DataGridViewAdvancedCellBorderStyle.OutsetDouble: - if (this.RightToLeftInternal) + if (RightToLeftInternal) { dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = DataGridViewAdvancedCellBorderStyle.Outset; if (isFirstDisplayedColumn) { - dataGridViewAdvancedBorderStylePlaceholder.RightInternal = this.RowHeadersVisible ? DataGridViewAdvancedCellBorderStyle.Outset : DataGridViewAdvancedCellBorderStyle.OutsetDouble; + dataGridViewAdvancedBorderStylePlaceholder.RightInternal = RowHeadersVisible ? DataGridViewAdvancedCellBorderStyle.Outset : DataGridViewAdvancedCellBorderStyle.OutsetDouble; } else { @@ -233,7 +233,7 @@ public virtual DataGridViewAdvancedBorderStyle AdjustColumnHeaderBorderStyle(Dat { if (isFirstDisplayedColumn) { - dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = this.RowHeadersVisible ? DataGridViewAdvancedCellBorderStyle.Outset : DataGridViewAdvancedCellBorderStyle.OutsetDouble; + dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = RowHeadersVisible ? DataGridViewAdvancedCellBorderStyle.Outset : DataGridViewAdvancedCellBorderStyle.OutsetDouble; } else { @@ -246,12 +246,12 @@ public virtual DataGridViewAdvancedBorderStyle AdjustColumnHeaderBorderStyle(Dat return dataGridViewAdvancedBorderStylePlaceholder; case DataGridViewAdvancedCellBorderStyle.InsetDouble: - if (this.RightToLeftInternal) + if (RightToLeftInternal) { dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = DataGridViewAdvancedCellBorderStyle.Inset; if (isFirstDisplayedColumn) { - dataGridViewAdvancedBorderStylePlaceholder.RightInternal = this.RowHeadersVisible ? DataGridViewAdvancedCellBorderStyle.Inset : DataGridViewAdvancedCellBorderStyle.InsetDouble; + dataGridViewAdvancedBorderStylePlaceholder.RightInternal = RowHeadersVisible ? DataGridViewAdvancedCellBorderStyle.Inset : DataGridViewAdvancedCellBorderStyle.InsetDouble; } else { @@ -262,7 +262,7 @@ public virtual DataGridViewAdvancedBorderStyle AdjustColumnHeaderBorderStyle(Dat { if (isFirstDisplayedColumn) { - dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = this.RowHeadersVisible ? DataGridViewAdvancedCellBorderStyle.Inset : DataGridViewAdvancedCellBorderStyle.InsetDouble; + dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = RowHeadersVisible ? DataGridViewAdvancedCellBorderStyle.Inset : DataGridViewAdvancedCellBorderStyle.InsetDouble; } else { @@ -275,9 +275,9 @@ public virtual DataGridViewAdvancedBorderStyle AdjustColumnHeaderBorderStyle(Dat return dataGridViewAdvancedBorderStylePlaceholder; case DataGridViewAdvancedCellBorderStyle.Single: - if (!isFirstDisplayedColumn || this.RowHeadersVisible) + if (!isFirstDisplayedColumn || RowHeadersVisible) { - if (this.RightToLeftInternal) + if (RightToLeftInternal) { dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = DataGridViewAdvancedCellBorderStyle.Single; dataGridViewAdvancedBorderStylePlaceholder.RightInternal = DataGridViewAdvancedCellBorderStyle.None; @@ -302,21 +302,21 @@ private bool AdjustExpandingColumn(DataGridViewColumn dataGridViewColumn, int ro { Debug.Assert(dataGridViewColumn != null); Debug.Assert(rowIndex > -1); - Debug.Assert(rowIndex < this.Rows.Count); + Debug.Assert(rowIndex < Rows.Count); - if (!this.IsHandleCreated) + if (!IsHandleCreated) { // auto sizing causes handle creation. // don't create the handle inside InitializeComponent because that causes problems w/ data binding - this.dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle] = true; return false; } bool ret = false; // No autosizing occurs by default. try { - this.noAutoSizeCount++; - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); + noAutoSizeCount++; + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); int preferredThickness = dataGridViewRow.Cells[dataGridViewColumn.Index].GetPreferredWidth(rowIndex, dataGridViewRow.GetHeight(rowIndex)); if (preferredThickness > DataGridViewBand.MaxBandThickness) { @@ -331,8 +331,8 @@ private bool AdjustExpandingColumn(DataGridViewColumn dataGridViewColumn, int ro } finally { - Debug.Assert(this.noAutoSizeCount > 0); - this.noAutoSizeCount--; + Debug.Assert(noAutoSizeCount > 0); + noAutoSizeCount--; } return ret; @@ -344,7 +344,7 @@ private bool AdjustExpandingColumns(DataGridViewAutoSizeColumnCriteriaInternal a Debug.Assert((autoSizeColumnCriteriaFilter & DataGridViewAutoSizeColumnCriteriaInternal.Fill) == 0); bool ret = false; // No column autosizes by default - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); while (dataGridViewColumn != null) { DataGridViewAutoSizeColumnCriteriaInternal inheritedAutoSizeColumnCriteria = (DataGridViewAutoSizeColumnCriteriaInternal)dataGridViewColumn.InheritedAutoSizeMode; @@ -353,7 +353,7 @@ private bool AdjustExpandingColumns(DataGridViewAutoSizeColumnCriteriaInternal a { ret |= AdjustExpandingColumn(dataGridViewColumn, rowIndex); } - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); } @@ -362,11 +362,11 @@ private bool AdjustExpandingColumns(DataGridViewAutoSizeColumnCriteriaInternal a private int AdjustExpandingRow(int rowIndex, int columnIndex, bool fixedWidth) { - Debug.Assert(columnIndex >= -1 && columnIndex < this.Columns.Count); - Debug.Assert(rowIndex >= 0 && rowIndex < this.Rows.Count); - Debug.Assert(this.autoSizeRowsMode == DataGridViewAutoSizeRowsMode.DisplayedHeaders || - this.autoSizeRowsMode == DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders || - this.autoSizeRowsMode == DataGridViewAutoSizeRowsMode.DisplayedCells); + Debug.Assert(columnIndex >= -1 && columnIndex < Columns.Count); + Debug.Assert(rowIndex >= 0 && rowIndex < Rows.Count); + Debug.Assert(autoSizeRowsMode == DataGridViewAutoSizeRowsMode.DisplayedHeaders || + autoSizeRowsMode == DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders || + autoSizeRowsMode == DataGridViewAutoSizeRowsMode.DisplayedCells); // Use of WindowsFormsUtils.CreateMeasurementGraphics() avoid use of this.Handle // IntPtr handle = this.Handle; // Force creation of control's handle because for databound grids, handle creation wipes out and recreates the columns/rows. @@ -374,22 +374,22 @@ private int AdjustExpandingRow(int rowIndex, int columnIndex, bool fixedWidth) DataGridViewCell dataGridViewCell; if (columnIndex > -1 && (((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0) { - dataGridViewCell = this.Rows.SharedRow(rowIndex).Cells[columnIndex]; + dataGridViewCell = Rows.SharedRow(rowIndex).Cells[columnIndex]; if (fixedWidth) { - width = this.Columns[columnIndex].Thickness; + width = Columns[columnIndex].Thickness; } } else { Debug.Assert(columnIndex == -1); Debug.Assert((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) != 0); - dataGridViewCell = this.Rows.SharedRow(rowIndex).HeaderCell; + dataGridViewCell = Rows.SharedRow(rowIndex).HeaderCell; if (fixedWidth) { - Debug.Assert(this.RowHeadersWidth > 0); - Debug.Assert(this.RowHeadersVisible); - width = this.RowHeadersWidth; + Debug.Assert(RowHeadersWidth > 0); + Debug.Assert(RowHeadersVisible); + width = RowHeadersWidth; } } int preferredThickness; @@ -402,7 +402,7 @@ private int AdjustExpandingRow(int rowIndex, int columnIndex, bool fixedWidth) preferredThickness = dataGridViewCell.GetPreferredSize(rowIndex).Height; } int height, minimumHeight; - this.Rows.SharedRow(rowIndex).GetHeightInfo(rowIndex, out height, out minimumHeight); + Rows.SharedRow(rowIndex).GetHeightInfo(rowIndex, out height, out minimumHeight); if (preferredThickness < height) { preferredThickness = height; @@ -414,8 +414,8 @@ private int AdjustExpandingRow(int rowIndex, int columnIndex, bool fixedWidth) } if (height != preferredThickness) { - Debug.Assert(this.autoSizeRowsMode != DataGridViewAutoSizeRowsMode.None); - this.Rows[rowIndex].Thickness = preferredThickness; // unsharing the resized row + Debug.Assert(autoSizeRowsMode != DataGridViewAutoSizeRowsMode.None); + Rows[rowIndex].Thickness = preferredThickness; // unsharing the resized row } return preferredThickness; } @@ -423,51 +423,51 @@ private int AdjustExpandingRow(int rowIndex, int columnIndex, bool fixedWidth) [SuppressMessage("Microsoft.Performance", "CA1817:DoNotCallPropertiesThatCloneValuesInLoops")] // Can't cache DataGridViewRow object because rowIndex is changing in loop. private void AdjustExpandingRows(int columnIndex, bool fixedWidth) { - if ((((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0 || - ((((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) != 0 && this.RowHeadersVisible)) + if ((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0 || + ((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) != 0 && RowHeadersVisible)) { - if (!this.IsHandleCreated) + if (!IsHandleCreated) { // auto sizing causes handle creation. // don't create the handle inside InitializeComponent because that causes problems w/ data binding - this.dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle] = true; return; } // Very expensive processing - the developer should avoid this scenario. // Switch to batch operation - this.inBulkPaintCount++; + inBulkPaintCount++; try { - if ((((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllRows) != 0) + if ((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllRows) != 0) { - this.inBulkLayoutCount++; + inBulkLayoutCount++; try { - for (int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + for (int rowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); rowIndex != -1; - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) + rowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) { int width = 0; DataGridViewCell dataGridViewCell; - if (columnIndex > -1 && (((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0) + if (columnIndex > -1 && (((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0) { - dataGridViewCell = this.Rows.SharedRow(rowIndex).Cells[columnIndex]; + dataGridViewCell = Rows.SharedRow(rowIndex).Cells[columnIndex]; if (fixedWidth) { - width = this.Columns[columnIndex].Thickness; + width = Columns[columnIndex].Thickness; } } else { //Debug.Assert(columnIndex == -1); - Debug.Assert((((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) != 0); - dataGridViewCell = this.Rows.SharedRow(rowIndex).HeaderCell; + Debug.Assert((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) != 0); + dataGridViewCell = Rows.SharedRow(rowIndex).HeaderCell; if (fixedWidth) { - Debug.Assert(this.RowHeadersWidth > 0); - Debug.Assert(this.RowHeadersVisible); - width = this.RowHeadersWidth; + Debug.Assert(RowHeadersWidth > 0); + Debug.Assert(RowHeadersVisible); + width = RowHeadersWidth; } } int preferredHeight; @@ -479,9 +479,9 @@ private void AdjustExpandingRows(int columnIndex, bool fixedWidth) { preferredHeight = dataGridViewCell.GetPreferredSize(rowIndex).Height; } - if (this.Rows.SharedRow(rowIndex).Height < preferredHeight) + if (Rows.SharedRow(rowIndex).Height < preferredHeight) { - this.Rows[rowIndex].Height = preferredHeight; // unsharing the row to be resized + Rows[rowIndex].Height = preferredHeight; // unsharing the row to be resized } } } @@ -492,25 +492,25 @@ private void AdjustExpandingRows(int columnIndex, bool fixedWidth) } else { - Debug.Assert((((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.DisplayedRows) != 0); - int displayHeight = this.layout.Data.Height; + Debug.Assert((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.DisplayedRows) != 0); + int displayHeight = layout.Data.Height; int cy = 0; - int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int rowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); while (rowIndex != -1 && cy < displayHeight) { cy += AdjustExpandingRow(rowIndex, columnIndex, fixedWidth); - rowIndex = this.Rows.GetNextRow(rowIndex, + rowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); } if (cy < displayHeight) { - rowIndex = this.displayedBandsInfo.FirstDisplayedScrollingRow; + rowIndex = displayedBandsInfo.FirstDisplayedScrollingRow; while (rowIndex != -1 && cy < displayHeight) { cy += AdjustExpandingRow(rowIndex, columnIndex, fixedWidth); - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); + rowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); } } } @@ -524,12 +524,12 @@ private void AdjustExpandingRows(int columnIndex, bool fixedWidth) internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int width) { - if (this.InAdjustFillingColumns) + if (InAdjustFillingColumns) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAlterAutoFillColumnParameter)); } - this.dataGridViewOper[DATAGRIDVIEWOPER_inAdjustFillingColumn] = true; + dataGridViewOper[DATAGRIDVIEWOPER_inAdjustFillingColumn] = true; try { @@ -538,9 +538,9 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid Debug.Assert(!dataGridViewColumn.Frozen); Debug.Assert(dataGridViewColumn.MinimumWidth <= width); Debug.Assert(dataGridViewColumn.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill); - Debug.Assert(!this.layout.dirty); + Debug.Assert(!layout.dirty); - if (this.Columns.GetColumnsWidth(DataGridViewElementStates.Visible) > this.layout.Data.Width) + if (Columns.GetColumnsWidth(DataGridViewElementStates.Visible) > layout.Data.Width) { // Columns are scrolling - this means that all columns have reached their minimum width. // Do not affect their width or fill weight @@ -548,12 +548,12 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid return; } - int availableWidth = this.layout.Data.Width; // Width available for auto-filled columns + int availableWidth = layout.Data.Width; // Width available for auto-filled columns // Check if the column is the first or last visible scrolling column - if (this.DesignMode || - dataGridViewColumn == this.Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen) || - dataGridViewColumn == this.Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen)) + if (DesignMode || + dataGridViewColumn == Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen) || + dataGridViewColumn == Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen)) { // Changing the width is equivalent to adjusting the FillWeight when: // - the column is not scrolling and is the first non-frozen visible column @@ -563,7 +563,7 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid int widthSum = 0; // Sum of widths of visible auto filled columns. int imposedWidthSum = 0; // Minimum width required for all other columns. bool otherFillingColumnExists = false; - foreach (DataGridViewColumn dataGridViewColumnTmp in this.Columns) + foreach (DataGridViewColumn dataGridViewColumnTmp in Columns) { if (dataGridViewColumnTmp.Visible) { @@ -593,7 +593,7 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid return; } - int maximumPossibleWidth = this.layout.Data.Width - imposedWidthSum; + int maximumPossibleWidth = layout.Data.Width - imposedWidthSum; if (width > maximumPossibleWidth) { width = maximumPossibleWidth; @@ -603,7 +603,7 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid float oldWeight = dataGridViewColumn.FillWeight; float newWeight = (float)(width * weightSum) / (float)widthSum; bool desiredWidthTooSmall = false; - foreach (DataGridViewColumn dataGridViewColumnTmp in this.Columns) + foreach (DataGridViewColumn dataGridViewColumnTmp in Columns) { if (dataGridViewColumnTmp.Index != dataGridViewColumn.Index && dataGridViewColumnTmp.Visible && @@ -632,7 +632,7 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid float usedWeightSumNoneMinimal = weightSum; float weightSumNoneMinimal = weightSum; float usedFillWeights = 0F; - foreach (DataGridViewColumn dataGridViewColumnTmp in this.Columns) + foreach (DataGridViewColumn dataGridViewColumnTmp in Columns) { if (dataGridViewColumnTmp.Visible && dataGridViewColumnTmp.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill) @@ -653,7 +653,7 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid } } } - foreach (DataGridViewColumn dataGridViewColumnTmp in this.Columns) + foreach (DataGridViewColumn dataGridViewColumnTmp in Columns) { if (dataGridViewColumnTmp.Index != dataGridViewColumn.Index && dataGridViewColumnTmp.Visible && @@ -671,7 +671,7 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid { // No column hits its minimum width // Each UsedFillWeight simply equals the FillWeight - foreach (DataGridViewColumn dataGridViewColumnTmp in this.Columns) + foreach (DataGridViewColumn dataGridViewColumnTmp in Columns) { if (dataGridViewColumnTmp.Visible && dataGridViewColumnTmp.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill) @@ -682,7 +682,7 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid } #if DEBUG float weightSumDbg = 0F; - foreach (DataGridViewColumn dataGridViewColumnTmp in this.Columns) + foreach (DataGridViewColumn dataGridViewColumnTmp in Columns) { if (dataGridViewColumnTmp.Visible && dataGridViewColumnTmp.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill) @@ -703,7 +703,7 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid float weightSum = 0; // Weights of all auto filled visible columns. float oldWeightSum = 0F; // Fill weights of the columns displayed after this resized column bool otherFillingColumnExists = false; - foreach (DataGridViewColumn dataGridViewColumnTmp in this.Columns) + foreach (DataGridViewColumn dataGridViewColumnTmp in Columns) { if (dataGridViewColumnTmp.Visible) { @@ -712,7 +712,7 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid Debug.Assert(!dataGridViewColumnTmp.Frozen); if (dataGridViewColumnTmp.Index != dataGridViewColumn.Index) { - if (this.Columns.DisplayInOrder(dataGridViewColumn.Index, dataGridViewColumnTmp.Index)) + if (Columns.DisplayInOrder(dataGridViewColumn.Index, dataGridViewColumnTmp.Index)) { imposedWidthSum += dataGridViewColumnTmp.MinimumWidth; // Column is allowed to shrink down to its minimum oldWeightSum += dataGridViewColumnTmp.FillWeight; @@ -741,7 +741,7 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid return; } - int maximumPossibleWidth = this.layout.Data.Width - imposedWidthSum; + int maximumPossibleWidth = layout.Data.Width - imposedWidthSum; if (width > maximumPossibleWidth) { width = maximumPossibleWidth; @@ -752,12 +752,12 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid float newWeight = weightSum * width / availableWidth; float newWeightSum = oldWeightSum + oldWeight - newWeight; Debug.Assert(newWeightSum > 0); - foreach (DataGridViewColumn dataGridViewColumnTmp in this.Columns) + foreach (DataGridViewColumn dataGridViewColumnTmp in Columns) { if (dataGridViewColumnTmp.Index != dataGridViewColumn.Index && dataGridViewColumnTmp.Visible && dataGridViewColumnTmp.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill && - this.Columns.DisplayInOrder(dataGridViewColumn.Index, dataGridViewColumnTmp.Index)) + Columns.DisplayInOrder(dataGridViewColumn.Index, dataGridViewColumnTmp.Index)) { dataGridViewColumnTmp.FillWeightInternal = dataGridViewColumnTmp.FillWeight * newWeightSum / oldWeightSum; } @@ -766,7 +766,7 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid dataGridViewColumn.FillWeightInternal = newWeight; bool desiredWidthTooSmall = false; - foreach (DataGridViewColumn dataGridViewColumnTmp in this.Columns) + foreach (DataGridViewColumn dataGridViewColumnTmp in Columns) { if (dataGridViewColumnTmp.Visible && dataGridViewColumnTmp.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill) @@ -790,13 +790,13 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid float usedWeightSumNoneMinimal = weightSum; float weightSumNoneMinimal = weightSum; float usedFillWeights = 0F; - foreach (DataGridViewColumn dataGridViewColumnTmp in this.Columns) + foreach (DataGridViewColumn dataGridViewColumnTmp in Columns) { if (dataGridViewColumnTmp.Visible && dataGridViewColumnTmp.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill) { if (dataGridViewColumnTmp.Index == dataGridViewColumn.Index || - this.Columns.DisplayInOrder(dataGridViewColumnTmp.Index, dataGridViewColumn.Index)) + Columns.DisplayInOrder(dataGridViewColumnTmp.Index, dataGridViewColumn.Index)) { if (dataGridViewColumnTmp.Index == dataGridViewColumn.Index) { @@ -819,9 +819,9 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid } } } - foreach (DataGridViewColumn dataGridViewColumnTmp in this.Columns) + foreach (DataGridViewColumn dataGridViewColumnTmp in Columns) { - if (this.Columns.DisplayInOrder(dataGridViewColumn.Index, dataGridViewColumnTmp.Index) && + if (Columns.DisplayInOrder(dataGridViewColumn.Index, dataGridViewColumnTmp.Index) && dataGridViewColumnTmp.Visible && dataGridViewColumnTmp.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill && dataGridViewColumnTmp.DesiredFillWidth != -1) @@ -837,7 +837,7 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid { // No column hits its minimum width // Each UsedFillWeight simply equals the FillWeight - foreach (DataGridViewColumn dataGridViewColumnTmp in this.Columns) + foreach (DataGridViewColumn dataGridViewColumnTmp in Columns) { if (dataGridViewColumnTmp.Visible && dataGridViewColumnTmp.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill) @@ -848,7 +848,7 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid } #if DEBUG float weightSumDbg = 0F; - foreach (DataGridViewColumn dataGridViewColumnTmp in this.Columns) + foreach (DataGridViewColumn dataGridViewColumnTmp in Columns) { if (dataGridViewColumnTmp.Visible && dataGridViewColumnTmp.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill) @@ -861,26 +861,26 @@ internal void AdjustFillingColumn(DataGridViewColumn dataGridViewColumn, int wid } // UsedFillWeight properties are up-to-date - this.dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = false; - this.availableWidthForFillColumns = availableWidth; + dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = false; + availableWidthForFillColumns = availableWidth; // AdjustFillingColumns() will resize columns based on the UsedFillWeight values PerformLayoutPrivate(false /*useRowShortcut*/, true /*computeVisibleRows*/, false /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); } finally { - this.dataGridViewOper[DATAGRIDVIEWOPER_inAdjustFillingColumn] = false; + dataGridViewOper[DATAGRIDVIEWOPER_inAdjustFillingColumn] = false; } } private bool AdjustFillingColumns() { - if (this.dataGridViewOper[DATAGRIDVIEWOPER_inAdjustFillingColumns]) + if (dataGridViewOper[DATAGRIDVIEWOPER_inAdjustFillingColumns]) { // No need to auto fill columns while we're already doing it. return false; } - this.dataGridViewOper[DATAGRIDVIEWOPER_inAdjustFillingColumns] = true; + dataGridViewOper[DATAGRIDVIEWOPER_inAdjustFillingColumns] = true; bool columnsAdjusted = false; try @@ -891,7 +891,7 @@ private bool AdjustFillingColumns() int requiredWidthSum = 0; // total of the minimum widths of the visible auto filled columns. float weightSum = 0F; // total of the weights of the visible auto filled columns. ArrayList autoFillColumns = null; - foreach (DataGridViewColumn dataGridViewColumn in this.Columns) + foreach (DataGridViewColumn dataGridViewColumn in Columns) { if (dataGridViewColumn.Visible) { @@ -903,7 +903,7 @@ private bool AdjustFillingColumns() weightSum += dataGridViewColumn.FillWeight; if (autoFillColumns == null) { - autoFillColumns = new ArrayList(this.Columns.Count); + autoFillColumns = new ArrayList(Columns.Count); } autoFillColumns.Add(dataGridViewColumn); } @@ -917,23 +917,23 @@ private bool AdjustFillingColumns() if (numVisibleFillColumns > 0) { // Assuming no vertical scrollbar has been accounted for yet - Debug.Assert(this.layout.Data.Width == this.layout.Inside.Width - this.layout.RowHeaders.Width - (this.SingleVerticalBorderAdded ? 1 : 0)); - int availableWidth = this.layout.Data.Width - imposedWidthSum; - if ((this.scrollBars == ScrollBars.Both || this.scrollBars == ScrollBars.Vertical) /*&& + Debug.Assert(layout.Data.Width == layout.Inside.Width - layout.RowHeaders.Width - (SingleVerticalBorderAdded ? 1 : 0)); + int availableWidth = layout.Data.Width - imposedWidthSum; + if ((scrollBars == ScrollBars.Both || scrollBars == ScrollBars.Vertical) /*&& (availableWidth > requiredWidthSum || this.dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty])*/) { - int totalVisibleRowCount = this.Rows.GetRowCount(DataGridViewElementStates.Visible); - int totalVisibleHeight = this.Rows.GetRowsHeight(DataGridViewElementStates.Visible); - int totalVisibleFrozenHeight = this.Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int totalVisibleRowCount = Rows.GetRowCount(DataGridViewElementStates.Visible); + int totalVisibleHeight = Rows.GetRowsHeight(DataGridViewElementStates.Visible); + int totalVisibleFrozenHeight = Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); // Assuming there is no horizontal scrollbar, is a vertical scrollbar required? ComputeVisibleRows(); // Make sure this.displayedBandsInfo.FirstDisplayedScrollingRow and other row count info variables have been set - if (this.displayedBandsInfo.NumTotallyDisplayedFrozenRows == this.Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen) && - this.displayedBandsInfo.NumTotallyDisplayedScrollingRows != totalVisibleRowCount - this.Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen) && + if (displayedBandsInfo.NumTotallyDisplayedFrozenRows == Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen) && + displayedBandsInfo.NumTotallyDisplayedScrollingRows != totalVisibleRowCount - Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen) && (totalVisibleHeight - totalVisibleFrozenHeight != ComputeHeightOfFittingTrailingScrollingRows(totalVisibleFrozenHeight)) && - this.layout.Data.Height > totalVisibleFrozenHeight && - SystemInformation.VerticalScrollBarWidth <= this.layout.Data.Width) + layout.Data.Height > totalVisibleFrozenHeight && + SystemInformation.VerticalScrollBarWidth <= layout.Data.Width) { // Vertical scrollbar is required, even when there is not horizontal one. availableWidth -= SystemInformation.VerticalScrollBarWidth; @@ -965,8 +965,8 @@ private bool AdjustFillingColumns() DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)autoFillColumns[columnEntry]; dataGridViewColumn.UsedFillWeight = dataGridViewColumn.Width * weightSum / availableWidth; } - this.dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = false; - this.availableWidthForFillColumns = availableWidth; + dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = false; + availableWidthForFillColumns = availableWidth; } return columnsAdjusted; } @@ -976,7 +976,7 @@ private bool AdjustFillingColumns() int usedWidth = 0; // Update the UsedFillWeight value if dirty - if (this.dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty]) + if (dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty]) { // Assign desired widths Debug.Assert(weightSum > 0); @@ -1039,16 +1039,16 @@ private bool AdjustFillingColumns() } } - this.dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = false; - this.availableWidthForFillColumns = availableWidth; + dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = false; + availableWidthForFillColumns = availableWidth; } - else if (availableWidth != this.availableWidthForFillColumns) + else if (availableWidth != availableWidthForFillColumns) { // The available width for auto-filled columns has changed - UsedFillWeight values need to be adjusted. - if (availableWidth > this.availableWidthForFillColumns) + if (availableWidth > availableWidthForFillColumns) { // Available width increased - int widthGain = availableWidth - this.availableWidthForFillColumns; + int widthGain = availableWidth - availableWidthForFillColumns; // Allocate additional width according to UsedFillWeight and FillWeight values for (columnEntry = 0; columnEntry < autoFillColumns.Count; columnEntry++) { @@ -1074,7 +1074,7 @@ private bool AdjustFillingColumns() DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)autoFillColumns[columnEntry]; if (gain == 0) { - floatDesiredWidths[columnEntry] = this.availableWidthForFillColumns * dataGridViewColumn.UsedFillWeight / weightSum; + floatDesiredWidths[columnEntry] = availableWidthForFillColumns * dataGridViewColumn.UsedFillWeight / weightSum; } if (minimumColumnExists) { @@ -1095,7 +1095,7 @@ private bool AdjustFillingColumns() else { // availableWidth < this.availableWidthForFillColumns - Available width decreased - int totalWidthLoss = this.availableWidthForFillColumns - availableWidth; + int totalWidthLoss = availableWidthForFillColumns - availableWidth; int cumulatedWidthLoss = 0; for (columnEntry = 0; columnEntry < autoFillColumns.Count; columnEntry++) { @@ -1105,7 +1105,7 @@ private bool AdjustFillingColumns() // the width loss is accounted for in steps of 10% do { - int stepDownAvailableWidthForFillColumns = this.availableWidthForFillColumns - cumulatedWidthLoss; + int stepDownAvailableWidthForFillColumns = availableWidthForFillColumns - cumulatedWidthLoss; int widthLoss = Math.Min(stepDownAvailableWidthForFillColumns - availableWidth, Math.Max(1, (int)(stepDownAvailableWidthForFillColumns * 0.1F))); cumulatedWidthLoss += widthLoss; bool changeDone; @@ -1162,7 +1162,7 @@ private bool AdjustFillingColumns() } while (cumulatedWidthLoss < totalWidthLoss); } - this.availableWidthForFillColumns = availableWidth; + availableWidthForFillColumns = availableWidth; } #if DEBUG @@ -1179,7 +1179,7 @@ private bool AdjustFillingColumns() // Finally update the columns' width according the UsedFillWeight values. try { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_allowHorizontalScrollbar] = false; + dataGridViewState2[DATAGRIDVIEWSTATE2_allowHorizontalScrollbar] = false; usedWidth = 0; float carryover = 0F; while (autoFillColumns.Count > 0) @@ -1219,25 +1219,25 @@ private bool AdjustFillingColumns() } finally { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_allowHorizontalScrollbar] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_allowHorizontalScrollbar] = true; } } #if DEBUG - if (!this.dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty]) + if (!dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty]) { - foreach (DataGridViewColumn dataGridViewColumnTmp in this.Columns) + foreach (DataGridViewColumn dataGridViewColumnTmp in Columns) { if (dataGridViewColumnTmp.Visible && dataGridViewColumnTmp.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill) { - Debug.Assert(Math.Abs(dataGridViewColumnTmp.UsedFillWeight * this.availableWidthForFillColumns - weightSum * dataGridViewColumnTmp.Width) / weightSum / dataGridViewColumnTmp.Width <= 1.25F / dataGridViewColumnTmp.Width); + Debug.Assert(Math.Abs(dataGridViewColumnTmp.UsedFillWeight * availableWidthForFillColumns - weightSum * dataGridViewColumnTmp.Width) / weightSum / dataGridViewColumnTmp.Width <= 1.25F / dataGridViewColumnTmp.Width); } } } bool nonMinColumnExists = false; int widthSum = 0; - foreach (DataGridViewColumn dataGridViewColumnTmp in this.Columns) + foreach (DataGridViewColumn dataGridViewColumnTmp in Columns) { if (dataGridViewColumnTmp.Visible && dataGridViewColumnTmp.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill) @@ -1251,13 +1251,13 @@ private bool AdjustFillingColumns() } if (nonMinColumnExists) { - Debug.Assert(widthSum == this.availableWidthForFillColumns); + Debug.Assert(widthSum == availableWidthForFillColumns); } #endif } finally { - this.dataGridViewOper[DATAGRIDVIEWOPER_inAdjustFillingColumns] = false; + dataGridViewOper[DATAGRIDVIEWOPER_inAdjustFillingColumns] = false; } return columnsAdjusted; @@ -1266,21 +1266,21 @@ private bool AdjustFillingColumns() private void AdjustShrinkingRows(DataGridViewAutoSizeRowsMode autoSizeRowsMode, bool fixedWidth, bool internalAutosizing) { if ((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0 || - ((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) != 0 && this.RowHeadersVisible)) + ((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) != 0 && RowHeadersVisible)) { // Switch to batch operation - this.inBulkPaintCount++; + inBulkPaintCount++; try { if ((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllRows) != 0) { // Very expensive processing - the developer should avoid this scenario. - this.inBulkLayoutCount++; + inBulkLayoutCount++; try { - for (int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + for (int rowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); rowIndex != -1; - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) + rowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) { AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(autoSizeRowsMode), fixedWidth, internalAutosizing); } @@ -1293,53 +1293,53 @@ private void AdjustShrinkingRows(DataGridViewAutoSizeRowsMode autoSizeRowsMode, else { Debug.Assert((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.DisplayedRows) != 0); - int displayHeight = this.layout.Data.Height; + int displayHeight = layout.Data.Height; int cy = 0; - int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int rowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); while (rowIndex != -1 && cy < displayHeight) { AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(autoSizeRowsMode), fixedWidth, internalAutosizing); - cy += this.Rows.SharedRow(rowIndex).GetHeight(rowIndex); - rowIndex = this.Rows.GetNextRow(rowIndex, + cy += Rows.SharedRow(rowIndex).GetHeight(rowIndex); + rowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); } if (cy < displayHeight) { int cyFrozen = cy; - int oldFirstVisibleScrollingRow = this.displayedBandsInfo.FirstDisplayedScrollingRow; + int oldFirstVisibleScrollingRow = displayedBandsInfo.FirstDisplayedScrollingRow; rowIndex = oldFirstVisibleScrollingRow; while (rowIndex != -1 && cy < displayHeight && - oldFirstVisibleScrollingRow == this.displayedBandsInfo.FirstDisplayedScrollingRow) + oldFirstVisibleScrollingRow == displayedBandsInfo.FirstDisplayedScrollingRow) { AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(autoSizeRowsMode), fixedWidth, internalAutosizing); - cy += this.Rows.SharedRow(rowIndex).GetHeight(rowIndex); - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); + cy += Rows.SharedRow(rowIndex).GetHeight(rowIndex); + rowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); } do { - oldFirstVisibleScrollingRow = this.displayedBandsInfo.FirstDisplayedScrollingRow; + oldFirstVisibleScrollingRow = displayedBandsInfo.FirstDisplayedScrollingRow; if (cy < displayHeight) { - int rowAboveFirstVisibleScrollingRow = this.Rows.GetPreviousRow(this.displayedBandsInfo.FirstDisplayedScrollingRow, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); + int rowAboveFirstVisibleScrollingRow = Rows.GetPreviousRow(displayedBandsInfo.FirstDisplayedScrollingRow, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); if (rowAboveFirstVisibleScrollingRow != -1) { AutoResizeRowInternal(rowAboveFirstVisibleScrollingRow, MapAutoSizeRowsModeToRowMode(autoSizeRowsMode), fixedWidth, internalAutosizing); } } cy = cyFrozen; - rowIndex = this.displayedBandsInfo.FirstDisplayedScrollingRow; + rowIndex = displayedBandsInfo.FirstDisplayedScrollingRow; while (rowIndex != -1 && cy < displayHeight) { AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(autoSizeRowsMode), fixedWidth, internalAutosizing); - cy += this.Rows.SharedRow(rowIndex).GetHeight(rowIndex); - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); + cy += Rows.SharedRow(rowIndex).GetHeight(rowIndex); + rowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); } } - while (oldFirstVisibleScrollingRow != this.displayedBandsInfo.FirstDisplayedScrollingRow); + while (oldFirstVisibleScrollingRow != displayedBandsInfo.FirstDisplayedScrollingRow); } } } @@ -1354,44 +1354,44 @@ private void AdjustShrinkingRows(DataGridViewAutoSizeRowsMode autoSizeRowsMode, [SuppressMessage("Microsoft.Performance", "CA1817:DoNotCallPropertiesThatCloneValuesInLoops")] public bool AreAllCellsSelected(bool includeInvisibleCells) { - if (this.Columns.Count == 0 && this.Rows.Count == 0) + if (Columns.Count == 0 && Rows.Count == 0) { return true; } if (!includeInvisibleCells && - (this.Rows.GetFirstRow(DataGridViewElementStates.Visible) == -1 || - this.Columns.GetFirstColumn(DataGridViewElementStates.Visible) == null)) + (Rows.GetFirstRow(DataGridViewElementStates.Visible) == -1 || + Columns.GetFirstColumn(DataGridViewElementStates.Visible) == null)) { return true; } DataGridViewRow dataGridViewRow = null; bool allCellsSelected; - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: { - allCellsSelected = this.individualSelectedCells.Count == this.Columns.Count * this.Rows.Count; + allCellsSelected = individualSelectedCells.Count == Columns.Count * Rows.Count; if (allCellsSelected || includeInvisibleCells) { return allCellsSelected; } else { - for (int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + for (int rowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); rowIndex != -1; - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) + rowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) { - dataGridViewRow = this.Rows[rowIndex]; // unshares this row + dataGridViewRow = Rows[rowIndex]; // unshares this row - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); while (dataGridViewColumn != null) { if (!dataGridViewRow.Cells[dataGridViewColumn.Index].Selected) { return false; } - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); } @@ -1402,30 +1402,30 @@ public bool AreAllCellsSelected(bool includeInvisibleCells) case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: { - allCellsSelected = this.selectedBandIndexes.Count * this.Rows.Count + this.individualSelectedCells.Count == this.Columns.Count * this.Rows.Count; + allCellsSelected = selectedBandIndexes.Count * Rows.Count + individualSelectedCells.Count == Columns.Count * Rows.Count; if (allCellsSelected || includeInvisibleCells) { return allCellsSelected; } else { - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); while (dataGridViewColumn != null) { - if (!this.selectedBandIndexes.Contains(dataGridViewColumn.Index)) + if (!selectedBandIndexes.Contains(dataGridViewColumn.Index)) { - for (int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + for (int rowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); rowIndex != -1; - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) + rowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) { - dataGridViewRow = this.Rows[rowIndex]; // unshares this row + dataGridViewRow = Rows[rowIndex]; // unshares this row if (!dataGridViewRow.Cells[dataGridViewColumn.Index].Selected) { return false; } } } - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); } @@ -1435,30 +1435,30 @@ public bool AreAllCellsSelected(bool includeInvisibleCells) case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: { - allCellsSelected = this.selectedBandIndexes.Count * this.Columns.Count + this.individualSelectedCells.Count == this.Columns.Count * this.Rows.Count; + allCellsSelected = selectedBandIndexes.Count * Columns.Count + individualSelectedCells.Count == Columns.Count * Rows.Count; if (allCellsSelected || includeInvisibleCells) { return allCellsSelected; } else { - for (int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + for (int rowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); rowIndex != -1; - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) + rowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) { - Debug.Assert(this.selectedBandIndexes.Contains(rowIndex) == - ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) != 0)); - if ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) == 0) + Debug.Assert(selectedBandIndexes.Contains(rowIndex) == + ((Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) != 0)); + if ((Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) == 0) { - dataGridViewRow = this.Rows[rowIndex]; // unshares this row - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + dataGridViewRow = Rows[rowIndex]; // unshares this row + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); while (dataGridViewColumn != null) { if (!dataGridViewRow.Cells[dataGridViewColumn.Index].Selected) { return false; } - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); } @@ -1477,16 +1477,16 @@ public bool AreAllCellsSelected(bool includeInvisibleCells) /// internal override void AssignParent(Control value) { - if (this.toolTipControl.Activated) + if (toolTipControl.Activated) { - this.toolTipControl.Activate(false /*activate*/); + toolTipControl.Activate(false /*activate*/); } base.AssignParent(value); } private void AutoGenerateDataBoundColumns(DataGridViewColumn[] boundColumns) { - DataGridViewColumnCollection dataGridViewCols = this.Columns; + DataGridViewColumnCollection dataGridViewCols = Columns; DataGridViewColumn[] clonedColumns = new DataGridViewColumn[dataGridViewCols.Count]; int clonedColumnsCount = 0; int i; @@ -1506,7 +1506,7 @@ private void AutoGenerateDataBoundColumns(DataGridViewColumn[] boundColumns) // We can't do 1. and 2. in the same loop because we need to save the DisplayIndex. for (i = 0; i < dataGridViewCols.Count; i++) { - if (this.DataSource != null && + if (DataSource != null && !string.IsNullOrEmpty(dataGridViewCols[i].DataPropertyName) && !dataGridViewCols[i].IsDataBound) { @@ -1516,7 +1516,7 @@ private void AutoGenerateDataBoundColumns(DataGridViewColumn[] boundColumns) if (dataGridViewCols[i].IsDataBound) { // We only clone columns which are data bound w/ the new DataSource/DataMember combination. - if (this.dataConnection != null && this.dataConnection.BoundColumnIndex(dataGridViewCols[i].DataPropertyName) != -1) + if (dataConnection != null && dataConnection.BoundColumnIndex(dataGridViewCols[i].DataPropertyName) != -1) { clonedColumns[clonedColumnsCount] = (DataGridViewColumn)dataGridViewCols[i].Clone(); clonedColumns[clonedColumnsCount].DisplayIndex = dataGridViewCols[i].DisplayIndex; @@ -1625,7 +1625,7 @@ private bool AutoResizeAllVisibleColumnsInternal(DataGridViewAutoSizeColumnCrite Debug.Assert((autoSizeColumnCriteriaFilter & DataGridViewAutoSizeColumnCriteriaInternal.Fill) == 0); bool ret = false; // No column autosizes by default - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); while (dataGridViewColumn != null) { DataGridViewAutoSizeColumnCriteriaInternal inheritedAutoSizeColumnCriteria = (DataGridViewAutoSizeColumnCriteriaInternal)dataGridViewColumn.InheritedAutoSizeMode; @@ -1634,7 +1634,7 @@ private bool AutoResizeAllVisibleColumnsInternal(DataGridViewAutoSizeColumnCrite { ret |= AutoResizeColumnInternal(dataGridViewColumn.Index, inheritedAutoSizeColumnCriteria, fixedHeight); } - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); } @@ -1675,12 +1675,12 @@ protected void AutoResizeColumn(int columnIndex, DataGridViewAutoSizeColumnMode throw new InvalidEnumArgumentException(nameof(autoSizeColumnMode), (int)autoSizeColumnMode, typeof(DataGridViewAutoSizeColumnMode)); } - if (columnIndex < 0 || columnIndex >= this.Columns.Count) + if (columnIndex < 0 || columnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException(nameof(columnIndex)); } - if (autoSizeColumnMode == DataGridViewAutoSizeColumnMode.ColumnHeader && !this.ColumnHeadersVisible) + if (autoSizeColumnMode == DataGridViewAutoSizeColumnMode.ColumnHeader && !ColumnHeadersVisible) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAutoSizeInvisibleColumnHeader)); } @@ -1700,48 +1700,48 @@ public void AutoResizeColumnHeadersHeight(int columnIndex) protected void AutoResizeColumnHeadersHeight(bool fixedRowHeadersWidth, bool fixedColumnsWidth) { - if (!this.ColumnHeadersVisible) + if (!ColumnHeadersVisible) { return; } - if (!this.IsHandleCreated) + if (!IsHandleCreated) { // auto sizing causes handle creation. // don't create the handle inside InitializeComponent because that causes problems w/ data binding - this.dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle] = true; return; } try { - this.noAutoSizeCount++; + noAutoSizeCount++; // Use of WindowsFormsUtils.CreateMeasurementGraphics() avoid use of this.Handle // IntPtr handle = this.Handle; // Force creation of control's handle because for databound grids, handle creation wipes out and recreates the columns/rows. int preferredHeight = 0; - if (this.layout.TopLeftHeader.Width > 0) + if (layout.TopLeftHeader.Width > 0) { if (fixedRowHeadersWidth) { - preferredHeight = this.TopLeftHeaderCell.GetPreferredHeight(-1, this.layout.TopLeftHeader.Width); + preferredHeight = TopLeftHeaderCell.GetPreferredHeight(-1, layout.TopLeftHeader.Width); } else { - preferredHeight = this.TopLeftHeaderCell.GetPreferredSize(-1).Height; + preferredHeight = TopLeftHeaderCell.GetPreferredSize(-1).Height; } } - int columnsCount = this.Columns.Count; + int columnsCount = Columns.Count; for (int columnIndex = 0; columnIndex < columnsCount; columnIndex++) { - if (this.Columns[columnIndex].Visible) + if (Columns[columnIndex].Visible) { if (fixedColumnsWidth) { - preferredHeight = Math.Max(preferredHeight, this.Columns[columnIndex].HeaderCell.GetPreferredHeight(-1, this.Columns[columnIndex].Thickness)); + preferredHeight = Math.Max(preferredHeight, Columns[columnIndex].HeaderCell.GetPreferredHeight(-1, Columns[columnIndex].Thickness)); } else { - preferredHeight = Math.Max(preferredHeight, this.Columns[columnIndex].HeaderCell.GetPreferredSize(-1).Height); + preferredHeight = Math.Max(preferredHeight, Columns[columnIndex].HeaderCell.GetPreferredSize(-1).Height); } } } @@ -1753,67 +1753,67 @@ protected void AutoResizeColumnHeadersHeight(bool fixedRowHeadersWidth, bool fix { preferredHeight = maxHeadersThickness; } - if (preferredHeight != this.ColumnHeadersHeight) + if (preferredHeight != ColumnHeadersHeight) { SetColumnHeadersHeightInternal(preferredHeight, !fixedColumnsWidth /*invalidInAdjustFillingColumns*/); } } finally { - Debug.Assert(this.noAutoSizeCount > 0); - this.noAutoSizeCount--; + Debug.Assert(noAutoSizeCount > 0); + noAutoSizeCount--; } } protected void AutoResizeColumnHeadersHeight(int columnIndex, bool fixedRowHeadersWidth, bool fixedColumnWidth) { - if (columnIndex < -1 || columnIndex >= this.Columns.Count) + if (columnIndex < -1 || columnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException(nameof(columnIndex)); } - if (!this.ColumnHeadersVisible) + if (!ColumnHeadersVisible) { return; } - if (!this.IsHandleCreated) + if (!IsHandleCreated) { // auto sizing causes handle creation. // don't create the handle inside InitializeComponent because that causes problems w/ data binding - this.dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle] = true; return; } try { - this.noAutoSizeCount++; + noAutoSizeCount++; // Use of WindowsFormsUtils.CreateMeasurementGraphics() avoid use of this.Handle // IntPtr handle = this.Handle; // Force creation of control's handle because for databound grids, handle creation wipes out and recreates the columns/rows. int preferredHeight = 0; - if (this.layout.TopLeftHeader.Width > 0) + if (layout.TopLeftHeader.Width > 0) { if (columnIndex != -1 || fixedRowHeadersWidth) { - preferredHeight = this.TopLeftHeaderCell.GetPreferredHeight(-1, this.layout.TopLeftHeader.Width); + preferredHeight = TopLeftHeaderCell.GetPreferredHeight(-1, layout.TopLeftHeader.Width); } else { - preferredHeight = this.TopLeftHeaderCell.GetPreferredSize(-1).Height; + preferredHeight = TopLeftHeaderCell.GetPreferredSize(-1).Height; } } - int columnsCount = this.Columns.Count; + int columnsCount = Columns.Count; for (int columnIndexTmp = 0; columnIndexTmp < columnsCount; columnIndexTmp++) { - if (this.Columns[columnIndexTmp].Visible) + if (Columns[columnIndexTmp].Visible) { if (columnIndex != columnIndexTmp || fixedColumnWidth) { - preferredHeight = Math.Max(preferredHeight, this.Columns[columnIndexTmp].HeaderCell.GetPreferredHeight(-1, this.Columns[columnIndexTmp].Thickness)); + preferredHeight = Math.Max(preferredHeight, Columns[columnIndexTmp].HeaderCell.GetPreferredHeight(-1, Columns[columnIndexTmp].Thickness)); } else { - preferredHeight = Math.Max(preferredHeight, this.Columns[columnIndexTmp].HeaderCell.GetPreferredSize(-1).Height); + preferredHeight = Math.Max(preferredHeight, Columns[columnIndexTmp].HeaderCell.GetPreferredSize(-1).Height); } } } @@ -1825,15 +1825,15 @@ protected void AutoResizeColumnHeadersHeight(int columnIndex, bool fixedRowHeade { preferredHeight = maxHeadersThickness; } - if (preferredHeight != this.ColumnHeadersHeight) + if (preferredHeight != ColumnHeadersHeight) { SetColumnHeadersHeightInternal(preferredHeight, !fixedColumnWidth /*invalidInAdjustFillingColumns*/); } } finally { - Debug.Assert(this.noAutoSizeCount > 0); - this.noAutoSizeCount--; + Debug.Assert(noAutoSizeCount > 0); + noAutoSizeCount--; } } @@ -1844,25 +1844,25 @@ private bool AutoResizeColumnInternal(int columnIndex, DataGridViewAutoSizeColum autoSizeColumnCriteriaInternal == DataGridViewAutoSizeColumnCriteriaInternal.DisplayedRows || autoSizeColumnCriteriaInternal == (DataGridViewAutoSizeColumnCriteriaInternal.Header | DataGridViewAutoSizeColumnCriteriaInternal.AllRows) || autoSizeColumnCriteriaInternal == (DataGridViewAutoSizeColumnCriteriaInternal.Header | DataGridViewAutoSizeColumnCriteriaInternal.DisplayedRows)); - Debug.Assert(columnIndex >= 0 && columnIndex < this.Columns.Count); - Debug.Assert(autoSizeColumnCriteriaInternal != DataGridViewAutoSizeColumnCriteriaInternal.Header || this.ColumnHeadersVisible); + Debug.Assert(columnIndex >= 0 && columnIndex < Columns.Count); + Debug.Assert(autoSizeColumnCriteriaInternal != DataGridViewAutoSizeColumnCriteriaInternal.Header || ColumnHeadersVisible); - if (!this.IsHandleCreated) + if (!IsHandleCreated) { // auto sizing causes handle creation. // don't create the handle inside InitializeComponent because that causes problems w/ data binding - this.dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle] = true; return false; } bool ret = false; // No autosizing occurs by default. try { - this.noAutoSizeCount++; + noAutoSizeCount++; // Use of WindowsFormsUtils.CreateMeasurementGraphics() avoid use of this.Handle // IntPtr handle = this.Handle; // Force creation of control's handle because for databound grids, handle creation wipes out and recreates the columns. // Note: Even none-resizable column can programmatically be resized. - DataGridViewColumn dataGridViewColumn = this.Columns[columnIndex]; + DataGridViewColumn dataGridViewColumn = Columns[columnIndex]; int preferredColumnWidth = dataGridViewColumn.GetPreferredWidth((DataGridViewAutoSizeColumnMode)autoSizeColumnCriteriaInternal, fixedHeight); if (preferredColumnWidth < dataGridViewColumn.MinimumThickness) { @@ -1880,15 +1880,15 @@ private bool AutoResizeColumnInternal(int columnIndex, DataGridViewAutoSizeColum } else { - this.Columns[columnIndex].ThicknessInternal = preferredColumnWidth; + Columns[columnIndex].ThicknessInternal = preferredColumnWidth; } ret = true; } } finally { - Debug.Assert(this.noAutoSizeCount > 0); - this.noAutoSizeCount--; + Debug.Assert(noAutoSizeCount > 0); + noAutoSizeCount--; } return ret; } @@ -1905,7 +1905,7 @@ public void AutoResizeColumns(DataGridViewAutoSizeColumnsMode autoSizeColumnsMod protected void AutoResizeColumns(DataGridViewAutoSizeColumnsMode autoSizeColumnsMode, bool fixedHeight) { - for (int columnIndex = 0; columnIndex < this.Columns.Count; columnIndex++) + for (int columnIndex = 0; columnIndex < Columns.Count; columnIndex++) { AutoResizeColumn(columnIndex, (DataGridViewAutoSizeColumnMode)autoSizeColumnsMode, fixedHeight); } @@ -1923,7 +1923,7 @@ public void AutoResizeRow(int rowIndex, DataGridViewAutoSizeRowMode autoSizeRowM protected void AutoResizeRow(int rowIndex, DataGridViewAutoSizeRowMode autoSizeRowMode, bool fixedWidth) { - if (rowIndex < 0 || rowIndex >= this.Rows.Count) + if (rowIndex < 0 || rowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } @@ -1932,7 +1932,7 @@ protected void AutoResizeRow(int rowIndex, DataGridViewAutoSizeRowMode autoSizeR { throw new InvalidEnumArgumentException(nameof(autoSizeRowMode), (int)autoSizeRowMode, typeof(DataGridViewAutoSizeRowMode)); } - if (autoSizeRowMode == DataGridViewAutoSizeRowMode.RowHeader && !this.RowHeadersVisible) + if (autoSizeRowMode == DataGridViewAutoSizeRowMode.RowHeader && !RowHeadersVisible) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAutoSizeRowInvisibleRowHeader)); } @@ -1964,61 +1964,61 @@ protected void AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode row } - if (!this.RowHeadersVisible) + if (!RowHeadersVisible) { return; } - if (!this.IsHandleCreated) + if (!IsHandleCreated) { // auto sizing causes handle creation. // don't create the handle inside InitializeComponent because that causes problems w/ data binding - this.dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle] = true; return; } try { - this.noAutoSizeCount++; + noAutoSizeCount++; // Use of WindowsFormsUtils.CreateMeasurementGraphics() avoid use of this.Handle // IntPtr handle = this.Handle; // Force creation of control's handle because for databound grids, handle creation wipes out and recreates the columns/rows. int preferredWidth = 0, rowIndex; - if (this.layout.TopLeftHeader.Width > 0) + if (layout.TopLeftHeader.Width > 0) { if (fixedColumnHeadersHeight) { - preferredWidth = this.TopLeftHeaderCell.GetPreferredWidth(-1, this.layout.TopLeftHeader.Height); + preferredWidth = TopLeftHeaderCell.GetPreferredWidth(-1, layout.TopLeftHeader.Height); } else { - preferredWidth = this.TopLeftHeaderCell.GetPreferredSize(-1).Width; + preferredWidth = TopLeftHeaderCell.GetPreferredSize(-1).Width; } } switch (rowHeadersWidthSizeMode) { case DataGridViewRowHeadersWidthSizeMode.AutoSizeToFirstHeader: { - rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + rowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); if (rowIndex != -1) { if (fixedRowsHeight) { - preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndex).HeaderCell.GetPreferredWidth(rowIndex, this.Rows.SharedRow(rowIndex).GetHeight(rowIndex))); + preferredWidth = Math.Max(preferredWidth, Rows.SharedRow(rowIndex).HeaderCell.GetPreferredWidth(rowIndex, Rows.SharedRow(rowIndex).GetHeight(rowIndex))); } else { - preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndex).HeaderCell.GetPreferredSize(rowIndex).Width); + preferredWidth = Math.Max(preferredWidth, Rows.SharedRow(rowIndex).HeaderCell.GetPreferredSize(rowIndex).Width); } } break; } case DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders: { - int displayHeight = this.layout.Data.Height, cy = 0; - rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int displayHeight = layout.Data.Height, cy = 0; + rowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); while (rowIndex != -1 && cy < displayHeight) { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); int dataGridViewRowHeight = dataGridViewRow.GetHeight(rowIndex); cy += dataGridViewRowHeight; if (fixedRowsHeight) @@ -2029,15 +2029,15 @@ protected void AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode row { preferredWidth = Math.Max(preferredWidth, dataGridViewRow.HeaderCell.GetPreferredSize(rowIndex).Width); } - rowIndex = this.Rows.GetNextRow(rowIndex, + rowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); } if (cy < displayHeight) { - rowIndex = this.displayedBandsInfo.FirstDisplayedScrollingRow; + rowIndex = displayedBandsInfo.FirstDisplayedScrollingRow; while (rowIndex != -1 && cy < displayHeight) { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); int dataGridViewRowHeight = dataGridViewRow.GetHeight(rowIndex); cy += dataGridViewRowHeight; if (fixedRowsHeight) @@ -2048,24 +2048,24 @@ protected void AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode row { preferredWidth = Math.Max(preferredWidth, dataGridViewRow.HeaderCell.GetPreferredSize(rowIndex).Width); } - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); + rowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); } } break; } case DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders: { - for (rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + for (rowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); rowIndex != -1; - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) + rowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) { if (fixedRowsHeight) { - preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndex).HeaderCell.GetPreferredWidth(rowIndex, this.Rows.SharedRow(rowIndex).GetHeight(rowIndex))); + preferredWidth = Math.Max(preferredWidth, Rows.SharedRow(rowIndex).HeaderCell.GetPreferredWidth(rowIndex, Rows.SharedRow(rowIndex).GetHeight(rowIndex))); } else { - preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndex).HeaderCell.GetPreferredSize(rowIndex).Width); + preferredWidth = Math.Max(preferredWidth, Rows.SharedRow(rowIndex).HeaderCell.GetPreferredSize(rowIndex).Width); } } break; @@ -2080,15 +2080,15 @@ protected void AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode row { preferredWidth = minimumRowHeadersWidth; } - if (preferredWidth != this.RowHeadersWidth) + if (preferredWidth != RowHeadersWidth) { - this.RowHeadersWidthInternal = preferredWidth; + RowHeadersWidthInternal = preferredWidth; } } finally { - Debug.Assert(this.noAutoSizeCount > 0); - this.noAutoSizeCount--; + Debug.Assert(noAutoSizeCount > 0); + noAutoSizeCount--; } } @@ -2105,7 +2105,7 @@ protected void AutoResizeRowHeadersWidth(int rowIndex, bool fixedColumnHeadersHeight, bool fixedRowHeight) { - if (rowIndex < -1 || rowIndex >= this.Rows.Count) + if (rowIndex < -1 || rowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } @@ -2119,20 +2119,20 @@ protected void AutoResizeRowHeadersWidth(int rowIndex, throw new InvalidEnumArgumentException(nameof(rowHeadersWidthSizeMode), (int)rowHeadersWidthSizeMode, typeof(DataGridViewRowHeadersWidthSizeMode)); } - if (!this.RowHeadersVisible) + if (!RowHeadersVisible) { return; } if (rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.AutoSizeToFirstHeader && rowIndex != -1 && - rowIndex != this.Rows.GetFirstRow(DataGridViewElementStates.Visible)) + rowIndex != Rows.GetFirstRow(DataGridViewElementStates.Visible)) { return; } if (rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders && rowIndex != -1) { - DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); + DataGridViewElementStates rowState = Rows.GetRowState(rowIndex); bool rowDisplayed = (rowState & DataGridViewElementStates.Displayed) != 0; if (!rowDisplayed) { @@ -2140,56 +2140,56 @@ protected void AutoResizeRowHeadersWidth(int rowIndex, } } - if (!this.IsHandleCreated) + if (!IsHandleCreated) { // auto sizing causes handle creation. // don't create the handle inside InitializeComponent because that causes problems w/ data binding - this.dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle] = true; return; } try { - this.noAutoSizeCount++; + noAutoSizeCount++; // Use of WindowsFormsUtils.CreateMeasurementGraphics() avoid use of this.Handle // IntPtr handle = this.Handle; // Force creation of control's handle because for databound grids, handle creation wipes out and recreates the columns/rows. int preferredWidth = 0, rowIndexTmp; - if (this.layout.TopLeftHeader.Width > 0) + if (layout.TopLeftHeader.Width > 0) { if (rowIndex != -1 || fixedColumnHeadersHeight) { - preferredWidth = this.TopLeftHeaderCell.GetPreferredWidth(-1, this.layout.TopLeftHeader.Height); + preferredWidth = TopLeftHeaderCell.GetPreferredWidth(-1, layout.TopLeftHeader.Height); } else { - preferredWidth = this.TopLeftHeaderCell.GetPreferredSize(-1).Width; + preferredWidth = TopLeftHeaderCell.GetPreferredSize(-1).Width; } } switch (rowHeadersWidthSizeMode) { case DataGridViewRowHeadersWidthSizeMode.AutoSizeToFirstHeader: { - rowIndexTmp = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + rowIndexTmp = Rows.GetFirstRow(DataGridViewElementStates.Visible); if (rowIndexTmp != -1) { if (rowIndex != rowIndexTmp || fixedRowHeight) { - preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndexTmp).HeaderCell.GetPreferredWidth(rowIndexTmp, this.Rows.SharedRow(rowIndexTmp).GetHeight(rowIndexTmp))); + preferredWidth = Math.Max(preferredWidth, Rows.SharedRow(rowIndexTmp).HeaderCell.GetPreferredWidth(rowIndexTmp, Rows.SharedRow(rowIndexTmp).GetHeight(rowIndexTmp))); } else { - preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndexTmp).HeaderCell.GetPreferredSize(rowIndexTmp).Width); + preferredWidth = Math.Max(preferredWidth, Rows.SharedRow(rowIndexTmp).HeaderCell.GetPreferredSize(rowIndexTmp).Width); } } break; } case DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders: { - int displayHeight = this.layout.Data.Height, cy = 0; - rowIndexTmp = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int displayHeight = layout.Data.Height, cy = 0; + rowIndexTmp = Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); while (rowIndexTmp != -1 && cy < displayHeight) { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndexTmp); + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndexTmp); int dataGridViewRowHeight = dataGridViewRow.GetHeight(rowIndexTmp); cy += dataGridViewRowHeight; if (rowIndex != rowIndexTmp || fixedRowHeight) @@ -2200,15 +2200,15 @@ protected void AutoResizeRowHeadersWidth(int rowIndex, { preferredWidth = Math.Max(preferredWidth, dataGridViewRow.HeaderCell.GetPreferredSize(rowIndexTmp).Width); } - rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, + rowIndexTmp = Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); } if (cy < displayHeight) { - rowIndexTmp = this.displayedBandsInfo.FirstDisplayedScrollingRow; + rowIndexTmp = displayedBandsInfo.FirstDisplayedScrollingRow; while (rowIndexTmp != -1 && cy < displayHeight) { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndexTmp); + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndexTmp); int dataGridViewRowHeight = dataGridViewRow.GetHeight(rowIndexTmp); cy += dataGridViewRowHeight; if (rowIndex != rowIndexTmp || fixedRowHeight) @@ -2219,24 +2219,24 @@ protected void AutoResizeRowHeadersWidth(int rowIndex, { preferredWidth = Math.Max(preferredWidth, dataGridViewRow.HeaderCell.GetPreferredSize(rowIndexTmp).Width); } - rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible); + rowIndexTmp = Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible); } } break; } case DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders: { - for (rowIndexTmp = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + for (rowIndexTmp = Rows.GetFirstRow(DataGridViewElementStates.Visible); rowIndexTmp != -1; - rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible)) + rowIndexTmp = Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible)) { if (rowIndex != rowIndexTmp || fixedRowHeight) { - preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndexTmp).HeaderCell.GetPreferredWidth(rowIndexTmp, this.Rows.SharedRow(rowIndexTmp).GetHeight(rowIndexTmp))); + preferredWidth = Math.Max(preferredWidth, Rows.SharedRow(rowIndexTmp).HeaderCell.GetPreferredWidth(rowIndexTmp, Rows.SharedRow(rowIndexTmp).GetHeight(rowIndexTmp))); } else { - preferredWidth = Math.Max(preferredWidth, this.Rows.SharedRow(rowIndexTmp).HeaderCell.GetPreferredSize(rowIndexTmp).Width); + preferredWidth = Math.Max(preferredWidth, Rows.SharedRow(rowIndexTmp).HeaderCell.GetPreferredSize(rowIndexTmp).Width); } } break; @@ -2251,38 +2251,38 @@ protected void AutoResizeRowHeadersWidth(int rowIndex, { preferredWidth = minimumRowHeadersWidth; } - if (preferredWidth != this.RowHeadersWidth) + if (preferredWidth != RowHeadersWidth) { - this.RowHeadersWidthInternal = preferredWidth; + RowHeadersWidthInternal = preferredWidth; } } finally { - Debug.Assert(this.noAutoSizeCount > 0); - this.noAutoSizeCount--; + Debug.Assert(noAutoSizeCount > 0); + noAutoSizeCount--; } } private void AutoResizeRowInternal(int rowIndex, DataGridViewAutoSizeRowMode autoSizeRowMode, bool fixedWidth, bool internalAutosizing) { - Debug.Assert(rowIndex >= 0 && rowIndex < this.Rows.Count); + Debug.Assert(rowIndex >= 0 && rowIndex < Rows.Count); Debug.Assert(((DataGridViewAutoSizeRowCriteriaInternal)autoSizeRowMode & invalidDataGridViewAutoSizeRowCriteriaInternalMask) == 0); - if (!this.IsHandleCreated) + if (!IsHandleCreated) { // auto sizing causes handle creation. // don't create the handle inside InitializeComponent because that causes problems w/ data binding - this.dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle] = true; return; } try { - this.noAutoSizeCount++; + noAutoSizeCount++; // Use of WindowsFormsUtils.CreateMeasurementGraphics() avoid use of this.Handle // IntPtr handle = this.Handle; // Force creation of control's handle because for databound grids, handle creation wipes out and recreates the columns/rows. // Note: Even none-resizable row can programmatically be resized. - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); int height, minimumHeight; dataGridViewRow.GetHeightInfo(rowIndex, out height, out minimumHeight); int preferredThickness = dataGridViewRow.GetPreferredHeight(rowIndex, autoSizeRowMode, fixedWidth); @@ -2296,30 +2296,30 @@ private void AutoResizeRowInternal(int rowIndex, DataGridViewAutoSizeRowMode aut } if (height != preferredThickness) { - if (this.autoSizeRowsMode == DataGridViewAutoSizeRowsMode.None) + if (autoSizeRowsMode == DataGridViewAutoSizeRowsMode.None) { if (!OnRowHeightInfoPushed(rowIndex, preferredThickness, minimumHeight)) { - this.Rows[rowIndex].ThicknessInternal = preferredThickness; // unsharing the resized row + Rows[rowIndex].ThicknessInternal = preferredThickness; // unsharing the resized row } } else { if (internalAutosizing) { - this.Rows[rowIndex].ThicknessInternal = preferredThickness; // unsharing the resized row + Rows[rowIndex].ThicknessInternal = preferredThickness; // unsharing the resized row } else { - this.Rows[rowIndex].Thickness = preferredThickness; // unsharing the resized row + Rows[rowIndex].Thickness = preferredThickness; // unsharing the resized row } } } } finally { - Debug.Assert(this.noAutoSizeCount > 0); - this.noAutoSizeCount--; + Debug.Assert(noAutoSizeCount > 0); + noAutoSizeCount--; } } @@ -2355,7 +2355,7 @@ protected void AutoResizeRows(DataGridViewAutoSizeRowsMode autoSizeRowsMode, boo } if ((autoSizeRowsMode == DataGridViewAutoSizeRowsMode.AllHeaders || autoSizeRowsMode == DataGridViewAutoSizeRowsMode.DisplayedHeaders) && - !this.RowHeadersVisible) + !RowHeadersVisible) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAutoSizeRowsInvisibleRowHeader)); } @@ -2371,7 +2371,7 @@ protected void AutoResizeRows(int rowIndexStart, int rowsCount, DataGridViewAuto throw new InvalidEnumArgumentException(nameof(autoSizeRowMode), (int)autoSizeRowMode, typeof(DataGridViewAutoSizeRowMode)); } - if (autoSizeRowMode == DataGridViewAutoSizeRowMode.RowHeader && !this.RowHeadersVisible) + if (autoSizeRowMode == DataGridViewAutoSizeRowMode.RowHeader && !RowHeadersVisible) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAutoSizeRowsInvisibleRowHeader)); } @@ -2386,19 +2386,19 @@ protected void AutoResizeRows(int rowIndexStart, int rowsCount, DataGridViewAuto throw new ArgumentOutOfRangeException(nameof(rowIndexStart)); } - if (!this.IsHandleCreated) + if (!IsHandleCreated) { // auto sizing causes handle creation. // don't create the handle inside InitializeComponent because that causes problems w/ data binding - this.dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle] = true; return; } - this.inBulkPaintCount++; - this.inBulkLayoutCount++; + inBulkPaintCount++; + inBulkLayoutCount++; try { - int rowIndex = this.Rows.GetNextRow(rowIndexStart - 1, DataGridViewElementStates.Visible); + int rowIndex = Rows.GetNextRow(rowIndexStart - 1, DataGridViewElementStates.Visible); int autoSizedCount = 0; while (rowIndex != -1 && autoSizedCount < rowsCount) { @@ -2406,7 +2406,7 @@ protected void AutoResizeRows(int rowIndexStart, int rowsCount, DataGridViewAuto autoSizedCount++; if (autoSizedCount < rowsCount) { - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); + rowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); } } } @@ -2419,120 +2419,120 @@ protected void AutoResizeRows(int rowIndexStart, int rowsCount, DataGridViewAuto private void BeginColumnHeadersResize(int mouseY, int mouseBarOffset) { - if (this.IsKeyboardOperationActive()) + if (IsKeyboardOperationActive()) { return; } - Rectangle clip = Rectangle.Union(this.layout.ColumnHeaders, this.layout.Data); - if (this.layout.TopLeftHeader.Width > 0) + Rectangle clip = Rectangle.Union(layout.ColumnHeaders, layout.Data); + if (layout.TopLeftHeader.Width > 0) { - clip = Rectangle.Union(this.layout.TopLeftHeader, clip); + clip = Rectangle.Union(layout.TopLeftHeader, clip); } clip.Y += minimumColumnHeadersHeight - mouseBarOffset - 1; // No need to limit the bottom edge of the cursor clip since maxHeadersThickness is very large. CaptureMouse(clip); - this.dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize] = true; - this.trackRowAnchor = mouseY; + dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize] = true; + trackRowAnchor = mouseY; this.mouseBarOffset = mouseBarOffset; - Debug.Assert(this.lastRowSplitBar == -1); - this.currentRowSplitBar = mouseY; - Invalidate(CalcRowResizeFeedbackRect(this.currentRowSplitBar)); + Debug.Assert(lastRowSplitBar == -1); + currentRowSplitBar = mouseY; + Invalidate(CalcRowResizeFeedbackRect(currentRowSplitBar)); } private void BeginColumnRelocation(int mouseX, int index) { - if (this.IsKeyboardOperationActive()) + if (IsKeyboardOperationActive()) { return; } - Rectangle cursorClip = this.layout.ColumnHeaders; - int frozenWidth = this.Columns.GetColumnsWidth(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); - int scrollingWidth = this.Columns.GetColumnsWidth(DataGridViewElementStates.Visible) - frozenWidth; - if (this.Columns[index].Frozen) + Rectangle cursorClip = layout.ColumnHeaders; + int frozenWidth = Columns.GetColumnsWidth(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int scrollingWidth = Columns.GetColumnsWidth(DataGridViewElementStates.Visible) - frozenWidth; + if (Columns[index].Frozen) { // A frozen column cannot be relocated into an unfrozen area - if (this.RightToLeftInternal) + if (RightToLeftInternal) { cursorClip.X += cursorClip.Width - frozenWidth; } - cursorClip.Width = Math.Min(frozenWidth, this.layout.Data.Width); + cursorClip.Width = Math.Min(frozenWidth, layout.Data.Width); } else { // An unfrozen column cannot be relocated into a frozen area - if (!this.RightToLeftInternal) + if (!RightToLeftInternal) { cursorClip.X += frozenWidth; } - else if (this.layout.Data.Width > frozenWidth + scrollingWidth) + else if (layout.Data.Width > frozenWidth + scrollingWidth) { - cursorClip.X += this.layout.Data.Width - frozenWidth - scrollingWidth; + cursorClip.X += layout.Data.Width - frozenWidth - scrollingWidth; } - cursorClip.Width = Math.Min(scrollingWidth, this.layout.Data.Width); + cursorClip.Width = Math.Min(scrollingWidth, layout.Data.Width); } CaptureMouse(cursorClip); - this.dataGridViewOper[DATAGRIDVIEWOPER_trackColRelocation] = true; - this.dataGridViewState2[DATAGRIDVIEWSTATE2_showColumnRelocationInsertion] = false; - this.trackColumn = index; - this.trackColumnEdge = -1; + dataGridViewOper[DATAGRIDVIEWOPER_trackColRelocation] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_showColumnRelocationInsertion] = false; + trackColumn = index; + trackColumnEdge = -1; - this.mouseBarOffset = GetColumnXFromIndex(index) - mouseX; - this.lastHeaderShadow = mouseX; - Invalidate(this.layout.ColumnHeaders); + mouseBarOffset = GetColumnXFromIndex(index) - mouseX; + lastHeaderShadow = mouseX; + Invalidate(layout.ColumnHeaders); } private void BeginColumnResize(int x, int columnIndex) { - this.trackColAnchor = x; - this.trackColumn = columnIndex; + trackColAnchor = x; + trackColumn = columnIndex; - this.currentColSplitBar = x; - Invalidate(CalcColResizeFeedbackRect(this.currentColSplitBar)); + currentColSplitBar = x; + Invalidate(CalcColResizeFeedbackRect(currentColSplitBar)); } private void BeginMouseColumnResize(int mouseX, int mouseBarOffset, int index) { - if (this.IsKeyboardOperationActive()) + if (IsKeyboardOperationActive()) { return; } - this.dataGridViewOper[DATAGRIDVIEWOPER_trackColResize] = true; + dataGridViewOper[DATAGRIDVIEWOPER_trackColResize] = true; this.mouseBarOffset = mouseBarOffset; - this.resizeClipRectangle = GetResizeClipRectangle(index); - CaptureMouse(this.resizeClipRectangle); + resizeClipRectangle = GetResizeClipRectangle(index); + CaptureMouse(resizeClipRectangle); BeginColumnResize(mouseX, index); } private void BeginKeyboardColumnResize(int columnIndex) { - if (this.IsMouseOperationActive()) + if (IsMouseOperationActive()) { return; } - this.dataGridViewOper[DATAGRIDVIEWOPER_trackKeyboardColResize] = true; - this.mouseBarOffset = 0; - this.resizeClipRectangle = GetResizeClipRectangle(columnIndex); - this.keyboardResizeStep = this.ScaleToCurrentDpi(this.RightToLeftInternal ? -1 : 1); + dataGridViewOper[DATAGRIDVIEWOPER_trackKeyboardColResize] = true; + mouseBarOffset = 0; + resizeClipRectangle = GetResizeClipRectangle(columnIndex); + keyboardResizeStep = ScaleToCurrentDpi(RightToLeftInternal ? -1 : 1); int x = GetColumnXFromIndex(columnIndex); - x += this.RightToLeftInternal ? -this.Columns[columnIndex].Width : this.Columns[columnIndex].Width; + x += RightToLeftInternal ? -Columns[columnIndex].Width : Columns[columnIndex].Width; BeginColumnResize(x, columnIndex); } private Rectangle GetResizeClipRectangle(int columnIndex) { - Rectangle clip = Rectangle.Union(this.layout.ColumnHeaders, this.layout.Data); + Rectangle clip = Rectangle.Union(layout.ColumnHeaders, layout.Data); int leftEdge = GetColumnXFromIndex(columnIndex); - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - clip.X = this.layout.Data.X - this.mouseBarOffset - 1; - clip.Width = leftEdge - this.Columns[columnIndex].MinimumThickness - this.layout.Data.X + 3; - int overflowWidth = leftEdge - this.mouseBarOffset - clip.Left - DataGridViewBand.MaxBandThickness + 1; + clip.X = layout.Data.X - mouseBarOffset - 1; + clip.Width = leftEdge - Columns[columnIndex].MinimumThickness - layout.Data.X + 3; + int overflowWidth = leftEdge - mouseBarOffset - clip.Left - DataGridViewBand.MaxBandThickness + 1; if (overflowWidth > 0) { clip.X += overflowWidth; @@ -2541,9 +2541,9 @@ private Rectangle GetResizeClipRectangle(int columnIndex) } else { - clip.X = leftEdge + this.Columns[columnIndex].MinimumThickness - this.mouseBarOffset - 1; - clip.Width = this.layout.Data.Right - leftEdge - 1; - int overflowWidth = clip.Right + this.mouseBarOffset - leftEdge - DataGridViewBand.MaxBandThickness; + clip.X = leftEdge + Columns[columnIndex].MinimumThickness - mouseBarOffset - 1; + clip.Width = layout.Data.Right - leftEdge - 1; + int overflowWidth = clip.Right + mouseBarOffset - leftEdge - DataGridViewBand.MaxBandThickness; if (overflowWidth > 0) { clip.Width -= overflowWidth; @@ -2555,12 +2555,12 @@ private Rectangle GetResizeClipRectangle(int columnIndex) public virtual bool BeginEdit(bool selectAll) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { throw new InvalidOperationException(string.Format(SR.DataGridView_NoCurrentCell)); } - if (this.IsCurrentCellInEditMode) + if (IsCurrentCellInEditMode) { return true; } @@ -2570,22 +2570,22 @@ public virtual bool BeginEdit(bool selectAll) private bool BeginEditInternal(bool selectAll) { - if (this.dataGridViewOper[DATAGRIDVIEWOPER_inBeginEdit]) + if (dataGridViewOper[DATAGRIDVIEWOPER_inBeginEdit]) { throw new InvalidOperationException(string.Format(SR.DataGridView_BeginEditNotReentrant)); } try { - this.dataGridViewOper[DATAGRIDVIEWOPER_inBeginEdit] = true; - Debug.Assert(this.ptCurrentCell.X >= 0 && this.ptCurrentCell.X < this.Columns.Count); - Debug.Assert(this.ptCurrentCell.Y >= 0 && this.ptCurrentCell.Y < this.Rows.Count); - Debug.Assert(!this.IsCurrentCellInEditMode); + dataGridViewOper[DATAGRIDVIEWOPER_inBeginEdit] = true; + Debug.Assert(ptCurrentCell.X >= 0 && ptCurrentCell.X < Columns.Count); + Debug.Assert(ptCurrentCell.Y >= 0 && ptCurrentCell.Y < Rows.Count); + Debug.Assert(!IsCurrentCellInEditMode); - DataGridViewCell dataGridViewCell = this.CurrentCellInternal; + DataGridViewCell dataGridViewCell = CurrentCellInternal; Debug.Assert(dataGridViewCell != null); - if (IsSharedCellReadOnly(dataGridViewCell, this.ptCurrentCell.Y) || - !ColumnEditable(this.ptCurrentCell.X)) + if (IsSharedCellReadOnly(dataGridViewCell, ptCurrentCell.Y) || + !ColumnEditable(ptCurrentCell.X)) { return false; } @@ -2601,24 +2601,24 @@ private bool BeginEditInternal(bool selectAll) } } - DataGridViewCellCancelEventArgs dgvcce = new DataGridViewCellCancelEventArgs(this.ptCurrentCell.X, this.ptCurrentCell.Y); + DataGridViewCellCancelEventArgs dgvcce = new DataGridViewCellCancelEventArgs(ptCurrentCell.X, ptCurrentCell.Y); OnCellBeginEdit(dgvcce); if (dgvcce.Cancel) { return false; } - Debug.Assert(!this.IsCurrentCellInEditMode); + Debug.Assert(!IsCurrentCellInEditMode); - if (this.ptCurrentCell.X > -1) + if (ptCurrentCell.X > -1) { DataGridViewCell previousCurrentCell = dataGridViewCell; - dataGridViewCell = this.CurrentCellInternal; + dataGridViewCell = CurrentCellInternal; if (previousCurrentCell != dataGridViewCell) { // The new current cell can be a whole different cell. // In that case, all tests previously done are no longer valid. - if (IsSharedCellReadOnly(dataGridViewCell, this.ptCurrentCell.Y) || - !ColumnEditable(this.ptCurrentCell.X)) + if (IsSharedCellReadOnly(dataGridViewCell, ptCurrentCell.Y) || + !ColumnEditable(ptCurrentCell.X)) { return false; } @@ -2640,11 +2640,11 @@ private bool BeginEditInternal(bool selectAll) return false; } - DataGridViewCellStyle dataGridViewCellStyle = dataGridViewCell.GetInheritedStyle(null, this.ptCurrentCell.Y, true); + DataGridViewCellStyle dataGridViewCellStyle = dataGridViewCell.GetInheritedStyle(null, ptCurrentCell.Y, true); if (editControlType == null) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode] = true; + dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode] = true; InitializeEditingCellValue(ref dataGridViewCellStyle, ref dataGridViewCell); ((IDataGridViewEditingCell)dataGridViewCell).PrepareEditingCellForEdit(selectAll); return true; @@ -2656,56 +2656,56 @@ private bool BeginEditInternal(bool selectAll) { throw new InvalidCastException(string.Format(SR.DataGridView_InvalidEditingControl)); } - if (this.latestEditingControl != null && - editControlType.IsInstanceOfType(this.latestEditingControl) && - !this.latestEditingControl.GetType().IsSubclassOf(editControlType)) + if (latestEditingControl != null && + editControlType.IsInstanceOfType(latestEditingControl) && + !latestEditingControl.GetType().IsSubclassOf(editControlType)) { - this.editingControl = this.latestEditingControl; - Debug.Assert(((IDataGridViewEditingControl)this.editingControl).EditingControlDataGridView == this); + editingControl = latestEditingControl; + Debug.Assert(((IDataGridViewEditingControl)editingControl).EditingControlDataGridView == this); } else { - Debug.Assert(this.editingControl == null); - this.editingControl = (Control)Activator.CreateInstance(editControlType); - Debug.Assert(this.editingControl != null); + Debug.Assert(editingControl == null); + editingControl = (Control)Activator.CreateInstance(editControlType); + Debug.Assert(editingControl != null); - ((IDataGridViewEditingControl)this.editingControl).EditingControlDataGridView = this; - if (this.latestEditingControl != null) + ((IDataGridViewEditingControl)editingControl).EditingControlDataGridView = this; + if (latestEditingControl != null) { - this.latestEditingControl.Dispose(); - this.latestEditingControl = null; + latestEditingControl.Dispose(); + latestEditingControl = null; } } - Debug.Assert(this.editingControl != null); - if (string.IsNullOrEmpty(this.editingControl.AccessibleName)) + Debug.Assert(editingControl != null); + if (string.IsNullOrEmpty(editingControl.AccessibleName)) { - this.editingControl.AccessibleName = string.Format(SR.DataGridView_AccEditingControlAccName); + editingControl.AccessibleName = string.Format(SR.DataGridView_AccEditingControlAccName); } - this.editingControl.ImeMode = this.ImeMode; + editingControl.ImeMode = ImeMode; - ((IDataGridViewEditingControl)this.editingControl).EditingControlRowIndex = this.ptCurrentCell.Y; + ((IDataGridViewEditingControl)editingControl).EditingControlRowIndex = ptCurrentCell.Y; InitializeEditingControlValue(ref dataGridViewCellStyle, dataGridViewCell); WireEditingControlEvents(); - Debug.Assert(this.editingControl != null); - Debug.Assert(this.editingPanel != null); - DataGridViewEditingControlShowingEventArgs dgvese = new DataGridViewEditingControlShowingEventArgs(this.editingControl, dataGridViewCellStyle); + Debug.Assert(editingControl != null); + Debug.Assert(editingPanel != null); + DataGridViewEditingControlShowingEventArgs dgvese = new DataGridViewEditingControlShowingEventArgs(editingControl, dataGridViewCellStyle); OnEditingControlShowing(dgvese); Debug.Assert(dgvese.CellStyle != null); - if (this.editingPanel == null || this.editingControl == null) + if (editingPanel == null || editingControl == null) { return false; } - this.editingPanel.BackColor = dgvese.CellStyle.BackColor; - ((IDataGridViewEditingControl)this.editingControl).ApplyCellStyleToEditingControl(dgvese.CellStyle); + editingPanel.BackColor = dgvese.CellStyle.BackColor; + ((IDataGridViewEditingControl)editingControl).ApplyCellStyleToEditingControl(dgvese.CellStyle); // Get rid of the tooltip if it's showing for the current cell - if (this.toolTipControl.Activated && this.ptToolTipCell == this.ptCurrentCell) + if (toolTipControl.Activated && ptToolTipCell == ptCurrentCell) { - this.toolTipControl.Activate(false /*activate*/); + toolTipControl.Activate(false /*activate*/); } PositionEditingControl(true, true, true); @@ -2713,36 +2713,36 @@ private bool BeginEditInternal(bool selectAll) // Guarding against bugs in customer code. // For example setting the CurrentCell to null in DataGridView_OnLostFocus(...) causes this.editingControl // to become null. - if (this.editingPanel == null || this.editingControl == null) + if (editingPanel == null || editingControl == null) { return false; } else { - ((IDataGridViewEditingControl)this.editingControl).PrepareEditingControlForEdit(selectAll); - InvalidateCellPrivate(this.ptCurrentCell.X, this.ptCurrentCell.Y); + ((IDataGridViewEditingControl)editingControl).PrepareEditingControlForEdit(selectAll); + InvalidateCellPrivate(ptCurrentCell.X, ptCurrentCell.Y); return true; } } finally { - this.dataGridViewOper[DATAGRIDVIEWOPER_inBeginEdit] = false; + dataGridViewOper[DATAGRIDVIEWOPER_inBeginEdit] = false; } } private void BeginRowHeadersResize(int mouseX, int mouseBarOffset) { - if (this.IsKeyboardOperationActive()) + if (IsKeyboardOperationActive()) { return; } - Rectangle clip = Rectangle.Union(this.layout.RowHeaders, this.layout.Data); - if (this.layout.TopLeftHeader.Width > 0) + Rectangle clip = Rectangle.Union(layout.RowHeaders, layout.Data); + if (layout.TopLeftHeader.Width > 0) { - clip = Rectangle.Union(this.layout.TopLeftHeader, clip); + clip = Rectangle.Union(layout.TopLeftHeader, clip); } - if (this.RightToLeftInternal) + if (RightToLeftInternal) { clip.X -= mouseBarOffset + 1; clip.Width -= minimumRowHeadersWidth - 1; @@ -2755,35 +2755,35 @@ private void BeginRowHeadersResize(int mouseX, int mouseBarOffset) } CaptureMouse(clip); - this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize] = true; - this.trackColAnchor = mouseX; + dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize] = true; + trackColAnchor = mouseX; this.mouseBarOffset = mouseBarOffset; - Debug.Assert(this.lastColSplitBar == -1); - this.currentColSplitBar = mouseX; - Invalidate(CalcColResizeFeedbackRect(this.currentColSplitBar)); + Debug.Assert(lastColSplitBar == -1); + currentColSplitBar = mouseX; + Invalidate(CalcColResizeFeedbackRect(currentColSplitBar)); } private void BeginRowResize(int mouseY, int mouseBarOffset, int index) { - if (this.IsKeyboardOperationActive()) + if (IsKeyboardOperationActive()) { return; } - Rectangle clip = Rectangle.Union(this.layout.RowHeaders, this.layout.Data); + Rectangle clip = Rectangle.Union(layout.RowHeaders, layout.Data); int topEdge = GetRowYFromIndex(index); - clip.Y = topEdge + this.Rows.SharedRow(index).GetMinimumHeight(index) - mouseBarOffset - 1; - clip.Height = this.layout.Data.Y + this.layout.Data.Height - topEdge - 1; + clip.Y = topEdge + Rows.SharedRow(index).GetMinimumHeight(index) - mouseBarOffset - 1; + clip.Height = layout.Data.Y + layout.Data.Height - topEdge - 1; CaptureMouse(clip); - this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowResize] = true; - this.trackRowAnchor = mouseY; - this.trackRow = index; + dataGridViewOper[DATAGRIDVIEWOPER_trackRowResize] = true; + trackRowAnchor = mouseY; + trackRow = index; this.mouseBarOffset = mouseBarOffset; - Debug.Assert(this.lastRowSplitBar == -1); - this.currentRowSplitBar = mouseY; - Invalidate(CalcRowResizeFeedbackRect(this.currentRowSplitBar)); + Debug.Assert(lastRowSplitBar == -1); + currentRowSplitBar = mouseY; + Invalidate(CalcRowResizeFeedbackRect(currentRowSplitBar)); } private void BuildInheritedColumnHeaderCellStyle(DataGridViewCellStyle inheritedCellStyle, DataGridViewCell cell) @@ -2797,10 +2797,10 @@ private void BuildInheritedColumnHeaderCellStyle(DataGridViewCellStyle inherited Debug.Assert(cellStyle != null); } - DataGridViewCellStyle columnHeadersStyle = this.ColumnHeadersDefaultCellStyle; + DataGridViewCellStyle columnHeadersStyle = ColumnHeadersDefaultCellStyle; Debug.Assert(columnHeadersStyle != null); - DataGridViewCellStyle dataGridViewStyle = this.DefaultCellStyle; + DataGridViewCellStyle dataGridViewStyle = DefaultCellStyle; Debug.Assert(dataGridViewStyle != null); if (cellStyle != null && !cellStyle.BackColor.IsEmpty) @@ -2977,23 +2977,23 @@ private void BuildInheritedColumnHeaderCellStyle(DataGridViewCellStyle inherited private Rectangle CalcColRelocationFeedbackRect(int mouseX) { - Rectangle r, inside = this.layout.ColumnHeaders; - if (this.layout.TopLeftHeader.Width > 0) + Rectangle r, inside = layout.ColumnHeaders; + if (layout.TopLeftHeader.Width > 0) { - inside = Rectangle.Union(this.layout.TopLeftHeader, inside); + inside = Rectangle.Union(layout.TopLeftHeader, inside); } - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - r = new Rectangle(mouseX + this.mouseBarOffset - this.Columns[this.trackColumn].Thickness + 1, + r = new Rectangle(mouseX + mouseBarOffset - Columns[trackColumn].Thickness + 1, inside.Y, - this.Columns[this.trackColumn].Thickness, + Columns[trackColumn].Thickness, inside.Height); r.X = Math.Max(inside.Left, r.X); r.X = Math.Min(r.X, inside.Right - r.Width); } else { - r = new Rectangle(mouseX + this.mouseBarOffset - 1, inside.Y, this.Columns[this.trackColumn].Thickness, inside.Height); + r = new Rectangle(mouseX + mouseBarOffset - 1, inside.Y, Columns[trackColumn].Thickness, inside.Height); r.X = Math.Min(inside.Right - r.Width, r.X); r.X = Math.Max(r.X, inside.Left); } @@ -3002,9 +3002,9 @@ private Rectangle CalcColRelocationFeedbackRect(int mouseX) private Rectangle CalcColResizeFeedbackRect(int mouseX) { - Rectangle inside = this.layout.Data; - Rectangle r = new Rectangle(mouseX + this.mouseBarOffset - 1, inside.Y, 3, inside.Height); - if (this.RightToLeftInternal) + Rectangle inside = layout.Data; + Rectangle r = new Rectangle(mouseX + mouseBarOffset - 1, inside.Y, 3, inside.Height); + if (RightToLeftInternal) { r.X = Math.Max(inside.Left, r.X); } @@ -3018,8 +3018,8 @@ private Rectangle CalcColResizeFeedbackRect(int mouseX) private Rectangle CalcRowResizeFeedbackRect(int mouseY) { - Rectangle inside = this.layout.Data; - Rectangle r = new Rectangle(inside.X, mouseY + this.mouseBarOffset - 1, inside.Width, 3); + Rectangle inside = layout.Data; + Rectangle r = new Rectangle(inside.X, mouseY + mouseBarOffset - 1, inside.Width, 3); r.Y = Math.Min(inside.Bottom - 3, r.Y); r.Y = Math.Max(r.Y, 0); return r; @@ -3032,11 +3032,11 @@ public bool CancelEdit() private bool CancelEdit(bool endEdit /*, DataGridViewDataErrorContexts context*/) { - if (this.ptCurrentCell.X != -1) + if (ptCurrentCell.X != -1) { - Debug.Assert(this.ptCurrentCell.Y != -1); + Debug.Assert(ptCurrentCell.Y != -1); - int oldCurrentCellX = this.ptCurrentCell.X; + int oldCurrentCellX = ptCurrentCell.X; DataGridViewDataErrorEventArgs dgvdee = CancelEditPrivate(/*ref dataGridViewCurrentCell, context*/); if (null != dgvdee) @@ -3052,9 +3052,9 @@ private bool CancelEdit(bool endEdit /*, DataGridViewDataErrorContexts context*/ } } - if (this.IsCurrentCellInEditMode) + if (IsCurrentCellInEditMode) { - if (endEdit && this.EditMode != DataGridViewEditMode.EditOnEnter && this.editingControl != null) + if (endEdit && EditMode != DataGridViewEditMode.EditOnEnter && editingControl != null) { bool success = EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.InitialValueRestoration, DataGridViewValidateCellInternal.Never /*validateCell*/, @@ -3074,18 +3074,18 @@ private bool CancelEdit(bool endEdit /*, DataGridViewDataErrorContexts context*/ IDataGridViewEditingCell dataGridViewEditingCell = null; try { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_ignoringEditingChanges] = true; - if (this.editingControl != null) + dataGridViewState1[DATAGRIDVIEWSTATE1_ignoringEditingChanges] = true; + if (editingControl != null) { - ((IDataGridViewEditingControl)this.editingControl).EditingControlFormattedValue = this.uneditedFormattedValue; - ((IDataGridViewEditingControl)this.editingControl).EditingControlValueChanged = false; + ((IDataGridViewEditingControl)editingControl).EditingControlFormattedValue = uneditedFormattedValue; + ((IDataGridViewEditingControl)editingControl).EditingControlValueChanged = false; } else { - Debug.Assert(this.dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode]); - dataGridViewEditingCell = this.CurrentCellInternal as IDataGridViewEditingCell; + Debug.Assert(dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode]); + dataGridViewEditingCell = CurrentCellInternal as IDataGridViewEditingCell; Debug.Assert(dataGridViewEditingCell != null); - dataGridViewEditingCell.EditingCellFormattedValue = this.uneditedFormattedValue; + dataGridViewEditingCell.EditingCellFormattedValue = uneditedFormattedValue; dataGridViewEditingCell.EditingCellValueChanged = false; } } @@ -3095,13 +3095,13 @@ private bool CancelEdit(bool endEdit /*, DataGridViewDataErrorContexts context*/ { throw; } - dgvdee2 = new DataGridViewDataErrorEventArgs(exception, this.ptCurrentCell.X, - this.ptCurrentCell.Y, + dgvdee2 = new DataGridViewDataErrorEventArgs(exception, ptCurrentCell.X, + ptCurrentCell.Y, DataGridViewDataErrorContexts.InitialValueRestoration); } finally { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_ignoringEditingChanges] = false; + dataGridViewState1[DATAGRIDVIEWSTATE1_ignoringEditingChanges] = false; } if (dgvdee2 != null) { @@ -3112,27 +3112,27 @@ private bool CancelEdit(bool endEdit /*, DataGridViewDataErrorContexts context*/ } } - if (this.editingControl != null) + if (editingControl != null) { - ((IDataGridViewEditingControl)this.editingControl).PrepareEditingControlForEdit(true /*selectAll*/); + ((IDataGridViewEditingControl)editingControl).PrepareEditingControlForEdit(true /*selectAll*/); } else { Debug.Assert(dataGridViewEditingCell != null); dataGridViewEditingCell.PrepareEditingCellForEdit(true /*selectAll*/); - InvalidateCellPrivate(this.ptCurrentCell.X, this.ptCurrentCell.Y); + InvalidateCellPrivate(ptCurrentCell.X, ptCurrentCell.Y); } } } - else if (this.ptCurrentCell.X == -1 && this.Focused) + else if (ptCurrentCell.X == -1 && Focused) { - Debug.Assert((this.AllowUserToAddRowsInternal && this.Rows.Count == 1) || - (!this.AllowUserToAddRowsInternal && this.Rows.Count == 0)); - if (this.Rows.Count > 0) + Debug.Assert((AllowUserToAddRowsInternal && Rows.Count == 1) || + (!AllowUserToAddRowsInternal && Rows.Count == 0)); + if (Rows.Count > 0) { - if (this.Columns.Count > oldCurrentCellX && this.Columns[oldCurrentCellX].Visible) + if (Columns.Count > oldCurrentCellX && Columns[oldCurrentCellX].Visible) { - int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + int rowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); if (rowIndex != -1) { bool success = SetAndSelectCurrentCellAddress(oldCurrentCellX, @@ -3157,10 +3157,10 @@ private bool CancelEdit(bool endEdit /*, DataGridViewDataErrorContexts context*/ private DataGridViewDataErrorEventArgs CancelEditPrivate(/*ref DataGridViewCell dataGridViewCurrentCell, DataGridViewDataErrorContexts context*/) { - bool currentCellDirty = this.IsCurrentCellDirty; - bool currentRowDirty = this.IsCurrentRowDirty; + bool currentCellDirty = IsCurrentCellDirty; + bool currentRowDirty = IsCurrentRowDirty; - if (this.IsCurrentCellInEditMode) + if (IsCurrentCellInEditMode) { /* Do not push original value back into the cell @@ -3178,44 +3178,44 @@ private DataGridViewDataErrorEventArgs CancelEditPrivate(/*ref DataGridViewCell */ - if (this.editingControl != null) + if (editingControl != null) { - ((IDataGridViewEditingControl)this.editingControl).EditingControlValueChanged = false; + ((IDataGridViewEditingControl)editingControl).EditingControlValueChanged = false; } else { - Debug.Assert(this.dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode]); - ((IDataGridViewEditingCell)this.CurrentCellInternal).EditingCellValueChanged = false; + Debug.Assert(dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode]); + ((IDataGridViewEditingCell)CurrentCellInternal).EditingCellValueChanged = false; } - this.IsCurrentCellDirtyInternal = false; + IsCurrentCellDirtyInternal = false; } - if (this.DataSource != null || this.VirtualMode) + if (DataSource != null || VirtualMode) { if ((currentRowDirty && !currentCellDirty) || - (this.dataGridViewState1[DATAGRIDVIEWSTATE1_newRowEdited] && - !this.dataGridViewState1[DATAGRIDVIEWSTATE1_editedRowChanged])) + (dataGridViewState1[DATAGRIDVIEWSTATE1_newRowEdited] && + !dataGridViewState1[DATAGRIDVIEWSTATE1_editedRowChanged])) { - bool discardNewRow = this.dataGridViewState1[DATAGRIDVIEWSTATE1_newRowEdited]; - this.IsCurrentRowDirtyInternal = false; - if (this.VirtualMode) + bool discardNewRow = dataGridViewState1[DATAGRIDVIEWSTATE1_newRowEdited]; + IsCurrentRowDirtyInternal = false; + if (VirtualMode) { QuestionEventArgs qe = new QuestionEventArgs(discardNewRow); OnCancelRowEdit(qe); discardNewRow &= qe.Response; } - if (this.DataSource != null) + if (DataSource != null) { - int oldCurrentCellX = this.ptCurrentCell.X; - this.dataConnection.CancelRowEdit(true /*restoreRow*/, this.dataGridViewState1[DATAGRIDVIEWSTATE1_newRowEdited]/*addNewFinished*/); - if (this.dataConnection.List.Count == 0) + int oldCurrentCellX = ptCurrentCell.X; + dataConnection.CancelRowEdit(true /*restoreRow*/, dataGridViewState1[DATAGRIDVIEWSTATE1_newRowEdited]/*addNewFinished*/); + if (dataConnection.List.Count == 0) { // There are no rows left in the back end. - if (currentCellDirty || this.ptCurrentCell.Y == -1 || this.ptCurrentCell.X == -1) + if (currentCellDirty || ptCurrentCell.Y == -1 || ptCurrentCell.X == -1) { - if (!IsColumnOutOfBounds(oldCurrentCellX) && this.Columns[oldCurrentCellX].Visible) + if (!IsColumnOutOfBounds(oldCurrentCellX) && Columns[oldCurrentCellX].Visible) { - Debug.Assert(0 == this.Rows.GetFirstRow(DataGridViewElementStates.Visible)); + Debug.Assert(0 == Rows.GetFirstRow(DataGridViewElementStates.Visible)); // Setting the current cell to the current column in the first row // will create the new row if the user was editing the cell. SetAndSelectCurrentCellAddress(oldCurrentCellX, @@ -3230,36 +3230,36 @@ private DataGridViewDataErrorEventArgs CancelEditPrivate(/*ref DataGridViewCell else { // Else, simply add a new row. - this.dataConnection.OnNewRowNeeded(); + dataConnection.OnNewRowNeeded(); } } // CancelRowEdit discarded the new row if we were editing the new row. discardNewRow = false; } - if (this.ptCurrentCell.Y > -1) + if (ptCurrentCell.Y > -1) { - InvalidateRowPrivate(this.ptCurrentCell.Y); - DataGridViewCell dataGridViewCell = this.CurrentCellInternal; - if (this.IsCurrentCellInEditMode) + InvalidateRowPrivate(ptCurrentCell.Y); + DataGridViewCell dataGridViewCell = CurrentCellInternal; + if (IsCurrentCellInEditMode) { - DataGridViewCellStyle dataGridViewCellStyle = dataGridViewCell.GetInheritedStyle(null, this.ptCurrentCell.Y, true); - if (this.editingControl != null) + DataGridViewCellStyle dataGridViewCellStyle = dataGridViewCell.GetInheritedStyle(null, ptCurrentCell.Y, true); + if (editingControl != null) { InitializeEditingControlValue(ref dataGridViewCellStyle, dataGridViewCell); - if (((IDataGridViewEditingControl)this.editingControl).RepositionEditingControlOnValueChange) + if (((IDataGridViewEditingControl)editingControl).RepositionEditingControlOnValueChange) { PositionEditingControl(true /*setLocation*/, true /*setSize*/, false /*setFocus*/); } } else { - Debug.Assert(this.dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode]); + Debug.Assert(dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode]); InitializeEditingCellValue(ref dataGridViewCellStyle, ref dataGridViewCell); } } } - if (discardNewRow && this.ptCurrentCell.Y == this.newRowIndex - 1) + if (discardNewRow && ptCurrentCell.Y == newRowIndex - 1) { DiscardNewRow(); } @@ -3267,9 +3267,9 @@ private DataGridViewDataErrorEventArgs CancelEditPrivate(/*ref DataGridViewCell } else { - if (!this.IsCurrentRowDirty && - this.ptCurrentCell.Y == this.newRowIndex - 1 && - this.dataGridViewState1[DATAGRIDVIEWSTATE1_newRowCreatedByEditing]) + if (!IsCurrentRowDirty && + ptCurrentCell.Y == newRowIndex - 1 && + dataGridViewState1[DATAGRIDVIEWSTATE1_newRowCreatedByEditing]) { DiscardNewRow(); } @@ -3279,7 +3279,7 @@ private DataGridViewDataErrorEventArgs CancelEditPrivate(/*ref DataGridViewCell internal bool CancelToolTipPopup(ToolTip toolTip) { - if (this.toolTipControl.ToolTip == toolTip) + if (toolTipControl.ToolTip == toolTip) { // Our own tool tip wants to show its text. return false; @@ -3289,7 +3289,7 @@ internal bool CancelToolTipPopup(ToolTip toolTip) // This is an external tool tip control which wants to show a tool tip over the DataGridView. // ToolTips from the data Grid view ( the error text, or the formatted text that does not fit in, or the tool tip text from the cell) // and the ShowCellToolTips take precedence over the external tool tip. - return string.IsNullOrEmpty(this.toolTipCaption) && this.ShowCellToolTips; + return string.IsNullOrEmpty(toolTipCaption) && ShowCellToolTips; } } @@ -3303,9 +3303,9 @@ private bool CanValidateDataBoundDataGridViewCell(DataGridViewCell dataGridViewC { if (dataGridViewCurrentCell == null) { - if (this.ptCurrentCell.X > -1) + if (ptCurrentCell.X > -1) { - dataGridViewCurrentCell = this.CurrentCellInternal; + dataGridViewCurrentCell = CurrentCellInternal; } } @@ -3322,13 +3322,13 @@ private bool CanValidateDataBoundDataGridViewCell(DataGridViewCell dataGridViewC return true; } - if (this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose]) + if (dataGridViewOper[DATAGRIDVIEWOPER_inDispose]) { // Dispose is not the place to validate data. Also, chances are that the data source is also disposing itself. return false; } - if (this.dataConnection == null) + if (dataConnection == null) { // if there is no dataConnection then it is not up to this function to stop validation. return true; @@ -3340,25 +3340,25 @@ private bool CanValidateDataBoundDataGridViewCell(DataGridViewCell dataGridViewC // // ///////////////////////////////////////////////////////////////////////////////////////////////// - if (this.dataConnection.ProcessingMetaDataChanges) + if (dataConnection.ProcessingMetaDataChanges) { // don't validate a cell in a data bound column while the property descriptors change under us return false; } - if (this.dataConnection.CancellingRowEdit && !this.dataConnection.RestoreRow) + if (dataConnection.CancellingRowEdit && !dataConnection.RestoreRow) { // don't validate a cell in a data bound column while we are cancelling a row edit and the old row is not restored return false; } - if (this.dataConnection.CurrencyManager.Count <= this.ptCurrentCell.Y) + if (dataConnection.CurrencyManager.Count <= ptCurrentCell.Y) { // don't validate a row beyond the last row in the back end list return false; } - if (this.dataConnection.PositionChangingOutsideDataGridView) + if (dataConnection.PositionChangingOutsideDataGridView) { // the position changed outside the data grid view and we haven't validated the data grid view cell already // we can't validate it now because if the user cancels validation then we end up @@ -3366,7 +3366,7 @@ private bool CanValidateDataBoundDataGridViewCell(DataGridViewCell dataGridViewC return false; } - if (this.dataConnection.ListWasReset) + if (dataConnection.ListWasReset) { // The list was reset outside data grid view. // We can't validate it now because we would be pushing a value into a different object ( possibly located in a different list ). @@ -3378,32 +3378,32 @@ private bool CanValidateDataBoundDataGridViewCell(DataGridViewCell dataGridViewC private void CaptureMouse(Rectangle cursorClip) { - this.CaptureInternal = true; + CaptureInternal = true; Cursor.ClipInternal = RectangleToScreen(cursorClip); } private void ClearRegionCache() { - this.cachedScrollableRegion = null; + cachedScrollableRegion = null; } public void ClearSelection() { - this.noDimensionChangeCount++; - this.noSelectionChangeCount++; + noDimensionChangeCount++; + noSelectionChangeCount++; bool switchedToBulkPaint = false; - if (this.selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold || - this.individualSelectedCells.Count > DATAGRIDVIEW_bulkPaintThreshold) + if (selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold || + individualSelectedCells.Count > DATAGRIDVIEW_bulkPaintThreshold) { - this.inBulkPaintCount++; + inBulkPaintCount++; switchedToBulkPaint = true; } try { RemoveIndividuallySelectedCells(); - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: { @@ -3415,16 +3415,16 @@ public void ClearSelection() case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: { - while (this.selectedBandIndexes.Count > 0) + while (selectedBandIndexes.Count > 0) { - SetSelectedRowCore(this.selectedBandIndexes.HeadInt, false); + SetSelectedRowCore(selectedBandIndexes.HeadInt, false); } // Force repainting of the current collumn's header cell to remove highlighting - if (this.ptCurrentCell.X != -1 && - this.SelectionMode == DataGridViewSelectionMode.FullRowSelect) + if (ptCurrentCell.X != -1 && + SelectionMode == DataGridViewSelectionMode.FullRowSelect) { - InvalidateCellPrivate(this.ptCurrentCell.X, -1); + InvalidateCellPrivate(ptCurrentCell.X, -1); } break; } @@ -3432,9 +3432,9 @@ public void ClearSelection() case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: { - while (this.selectedBandIndexes.Count > 0) + while (selectedBandIndexes.Count > 0) { - SetSelectedColumnCore(this.selectedBandIndexes.HeadInt, false); + SetSelectedColumnCore(selectedBandIndexes.HeadInt, false); } break; } @@ -3442,9 +3442,9 @@ public void ClearSelection() } finally { - this.noDimensionChangeCount--; - Debug.Assert(this.noDimensionChangeCount >= 0); - this.NoSelectionChangeCount--; + noDimensionChangeCount--; + Debug.Assert(noDimensionChangeCount >= 0); + NoSelectionChangeCount--; if (switchedToBulkPaint) { ExitBulkPaint(-1, -1); @@ -3454,13 +3454,13 @@ public void ClearSelection() protected void ClearSelection(int columnIndexException, int rowIndexException, bool selectExceptionElement) { - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: { - if (columnIndexException < 0 || columnIndexException >= this.Columns.Count) + if (columnIndexException < 0 || columnIndexException >= Columns.Count) { throw new ArgumentOutOfRangeException(nameof(columnIndexException)); } @@ -3470,7 +3470,7 @@ protected void ClearSelection(int columnIndexException, int rowIndexException, b case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: { - if (columnIndexException < -1 || columnIndexException >= this.Columns.Count) + if (columnIndexException < -1 || columnIndexException >= Columns.Count) { throw new ArgumentOutOfRangeException(nameof(columnIndexException)); } @@ -3478,13 +3478,13 @@ protected void ClearSelection(int columnIndexException, int rowIndexException, b } } - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: { - if (rowIndexException < 0 || rowIndexException >= this.Rows.Count) + if (rowIndexException < 0 || rowIndexException >= Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndexException)); } @@ -3494,7 +3494,7 @@ protected void ClearSelection(int columnIndexException, int rowIndexException, b case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: { - if (rowIndexException < -1 || rowIndexException >= this.Rows.Count) + if (rowIndexException < -1 || rowIndexException >= Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndexException)); } @@ -3503,20 +3503,20 @@ protected void ClearSelection(int columnIndexException, int rowIndexException, b } // Clears all selection except the row/column/cell specified as parameter - this.noDimensionChangeCount++; - this.noSelectionChangeCount++; + noDimensionChangeCount++; + noSelectionChangeCount++; bool switchedToBulkPaint = false; - if (this.selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold || - this.individualSelectedCells.Count > DATAGRIDVIEW_bulkPaintThreshold) + if (selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold || + individualSelectedCells.Count > DATAGRIDVIEW_bulkPaintThreshold) { - this.inBulkPaintCount++; + inBulkPaintCount++; switchedToBulkPaint = true; } try { - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: { @@ -3530,19 +3530,19 @@ protected void ClearSelection(int columnIndexException, int rowIndexException, b case DataGridViewSelectionMode.RowHeaderSelect: { int bandIndex = 0; - while (bandIndex < this.selectedBandIndexes.Count) + while (bandIndex < selectedBandIndexes.Count) { - if (this.selectedBandIndexes[bandIndex] != rowIndexException) + if (selectedBandIndexes[bandIndex] != rowIndexException) { // deselect currently selected row - SetSelectedRowCore(this.selectedBandIndexes[bandIndex], false); + SetSelectedRowCore(selectedBandIndexes[bandIndex], false); } else { bandIndex++; } } - if (this.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) + if (SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) { RemoveIndividuallySelectedCells(columnIndexException, rowIndexException); } @@ -3553,19 +3553,19 @@ protected void ClearSelection(int columnIndexException, int rowIndexException, b case DataGridViewSelectionMode.ColumnHeaderSelect: { int bandIndex = 0; - while (bandIndex < this.selectedBandIndexes.Count) + while (bandIndex < selectedBandIndexes.Count) { - if (this.selectedBandIndexes[bandIndex] != columnIndexException) + if (selectedBandIndexes[bandIndex] != columnIndexException) { // deselect currently selected column - SetSelectedColumnCore(this.selectedBandIndexes[bandIndex], false); + SetSelectedColumnCore(selectedBandIndexes[bandIndex], false); } else { bandIndex++; } } - if (this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) + if (SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) { RemoveIndividuallySelectedCells(columnIndexException, rowIndexException); } @@ -3579,9 +3579,9 @@ protected void ClearSelection(int columnIndexException, int rowIndexException, b } finally { - this.noDimensionChangeCount--; - Debug.Assert(this.noDimensionChangeCount >= 0); - this.NoSelectionChangeCount--; + noDimensionChangeCount--; + Debug.Assert(noDimensionChangeCount >= 0); + NoSelectionChangeCount--; if (switchedToBulkPaint) { ExitBulkPaint(-1, -1); @@ -3591,10 +3591,10 @@ protected void ClearSelection(int columnIndexException, int rowIndexException, b private bool ColumnEditable(int columnIndex) { - Debug.Assert(columnIndex >= 0 && columnIndex < this.Columns.Count, "Invalid columnIndex: " + columnIndex); - if (this.Columns[columnIndex].IsDataBound && - this.dataConnection != null && - !this.dataConnection.AllowEdit) + Debug.Assert(columnIndex >= 0 && columnIndex < Columns.Count, "Invalid columnIndex: " + columnIndex); + if (Columns[columnIndex].IsDataBound && + dataConnection != null && + !dataConnection.AllowEdit) { return false; } @@ -3612,27 +3612,27 @@ private bool ColumnNeedsDisplayedState(DataGridViewColumn dataGridViewColumn) if (dataGridViewColumn.Frozen) { - DataGridViewColumn firstVisibleFrozenColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + DataGridViewColumn firstVisibleFrozenColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); Debug.Assert(firstVisibleFrozenColumn != null); if (firstVisibleFrozenColumn.Index == dataGridViewColumn.Index) { - return this.displayedBandsInfo.NumDisplayedFrozenCols > 0; + return displayedBandsInfo.NumDisplayedFrozenCols > 0; } - Debug.Assert(this.Columns.DisplayInOrder(firstVisibleFrozenColumn.Index, dataGridViewColumn.Index)); - return this.Columns.GetColumnCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen, firstVisibleFrozenColumn.Index, dataGridViewColumn.Index) < this.displayedBandsInfo.NumDisplayedFrozenCols; + Debug.Assert(Columns.DisplayInOrder(firstVisibleFrozenColumn.Index, dataGridViewColumn.Index)); + return Columns.GetColumnCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen, firstVisibleFrozenColumn.Index, dataGridViewColumn.Index) < displayedBandsInfo.NumDisplayedFrozenCols; } else { - int firstDisplayedScrollingColumnIndex = this.displayedBandsInfo.FirstDisplayedScrollingCol; + int firstDisplayedScrollingColumnIndex = displayedBandsInfo.FirstDisplayedScrollingCol; if (firstDisplayedScrollingColumnIndex != -1) { if (firstDisplayedScrollingColumnIndex == dataGridViewColumn.Index) { - return this.displayedBandsInfo.NumDisplayedScrollingCols > 0; + return displayedBandsInfo.NumDisplayedScrollingCols > 0; } - if (this.Columns.DisplayInOrder(firstDisplayedScrollingColumnIndex, dataGridViewColumn.Index)) + if (Columns.DisplayInOrder(firstDisplayedScrollingColumnIndex, dataGridViewColumn.Index)) { - return this.Columns.GetColumnCount(DataGridViewElementStates.Visible, firstDisplayedScrollingColumnIndex, dataGridViewColumn.Index) < this.displayedBandsInfo.NumDisplayedScrollingCols; + return Columns.GetColumnCount(DataGridViewElementStates.Visible, firstDisplayedScrollingColumnIndex, dataGridViewColumn.Index) < displayedBandsInfo.NumDisplayedScrollingCols; } } } @@ -3654,9 +3654,9 @@ private bool ColumnRelocationTarget(MouseEventArgs e, HitTestInfo hti, out int p hti.typeInternal == DataGridViewHitTestTypeInternal.ColumnHeader) { int xColumnLeftEdge = GetColumnXFromIndex(hti.col); - int wColumn = this.Columns[hti.col].Width; - if ((this.RightToLeftInternal && e.X < xColumnLeftEdge - wColumn / 2) || - (!this.RightToLeftInternal && e.X > xColumnLeftEdge + wColumn / 2)) + int wColumn = Columns[hti.col].Width; + if ((RightToLeftInternal && e.X < xColumnLeftEdge - wColumn / 2) || + (!RightToLeftInternal && e.X > xColumnLeftEdge + wColumn / 2)) { // Insert column on the right of hti.col previousColumnIndex = hti.col; @@ -3664,7 +3664,7 @@ private bool ColumnRelocationTarget(MouseEventArgs e, HitTestInfo hti, out int p else { // Insert column on the left of hti.col - DataGridViewColumn dataGridViewColumnPrev = this.Columns.GetPreviousColumn(this.Columns[hti.col], + DataGridViewColumn dataGridViewColumnPrev = Columns.GetPreviousColumn(Columns[hti.col], DataGridViewElementStates.Visible, DataGridViewElementStates.None); if (dataGridViewColumnPrev != null) @@ -3681,13 +3681,13 @@ private bool ColumnRelocationTarget(MouseEventArgs e, HitTestInfo hti, out int p DataGridViewColumn dataGridViewColumnNext = null; if (previousColumnIndex != -1) { - dataGridViewColumnNext = this.Columns.GetNextColumn(this.Columns[previousColumnIndex], + dataGridViewColumnNext = Columns.GetNextColumn(Columns[previousColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); } - if (this.trackColumn != previousColumnIndex && - !(previousColumnIndex == -1 && hti.col == this.trackColumn) && - (dataGridViewColumnNext == null || this.trackColumn != dataGridViewColumnNext.Index)) + if (trackColumn != previousColumnIndex && + !(previousColumnIndex == -1 && hti.col == trackColumn) && + (dataGridViewColumnNext == null || trackColumn != dataGridViewColumnNext.Index)) { return true; } @@ -3696,7 +3696,7 @@ private bool ColumnRelocationTarget(MouseEventArgs e, HitTestInfo hti, out int p hti.typeInternal == DataGridViewHitTestTypeInternal.TopLeftHeaderResizeRight) { Debug.Assert(hti.col != -1); - if (hti.col != this.trackColumn) + if (hti.col != trackColumn) { return true; } @@ -3715,9 +3715,9 @@ private static bool ColumnsDisplayInOrder(int columnIndex1, public bool CommitEdit(DataGridViewDataErrorContexts context) { - if (this.IsCurrentCellInEditMode) + if (IsCurrentCellInEditMode) { - DataGridViewCell dataGridViewCurrentCell = this.CurrentCellInternal; + DataGridViewCell dataGridViewCurrentCell = CurrentCellInternal; DataGridViewDataErrorEventArgs dgvdee = CommitEdit(ref dataGridViewCurrentCell, context, DataGridViewValidateCellInternal.Never, @@ -3752,22 +3752,22 @@ private DataGridViewDataErrorEventArgs CommitEdit(ref DataGridViewCell dataGridV { if (validateCell == DataGridViewValidateCellInternal.Always) { - Debug.Assert(this.ptCurrentCell.X > -1); + Debug.Assert(ptCurrentCell.X > -1); if (fireCellLeave) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { return null; } - OnCellLeave(ref dataGridViewCurrentCell, this.ptCurrentCell.X, this.ptCurrentCell.Y); + OnCellLeave(ref dataGridViewCurrentCell, ptCurrentCell.X, ptCurrentCell.Y); } if (fireRowLeave) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { return null; } - OnRowLeave(ref dataGridViewCurrentCell, this.ptCurrentCell.X, this.ptCurrentCell.Y); + OnRowLeave(ref dataGridViewCurrentCell, ptCurrentCell.X, ptCurrentCell.Y); } if (fireLeave) { @@ -3777,44 +3777,44 @@ private DataGridViewDataErrorEventArgs CommitEdit(ref DataGridViewCell dataGridV // we would end up repainting the current cell twice. // // invalidate the current cell so the data grid view does not paint the focus rectangle any longer - if (this.ptCurrentCell.X > -1 && this.ptCurrentCell.Y > -1) + if (ptCurrentCell.X > -1 && ptCurrentCell.Y > -1) { - InvalidateCellPrivate(this.ptCurrentCell.X /*columnIndex*/, this.ptCurrentCell.Y /*rowIndex*/); + InvalidateCellPrivate(ptCurrentCell.X /*columnIndex*/, ptCurrentCell.Y /*rowIndex*/); } } // OnCellValidating returns true if the dev cancelled the validation. bool validateFormattedValue = CanValidateDataBoundDataGridViewCell(dataGridViewCurrentCell); if (validateFormattedValue) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { return null; } - if (OnCellValidating(ref dataGridViewCurrentCell, this.ptCurrentCell.X, this.ptCurrentCell.Y, context)) + if (OnCellValidating(ref dataGridViewCurrentCell, ptCurrentCell.X, ptCurrentCell.Y, context)) { if (fireRowEnter) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { return null; } - OnRowEnter(ref dataGridViewCurrentCell, this.ptCurrentCell.X, this.ptCurrentCell.Y, true /*canCreateNewRow*/, true /*validationFailureOccurred*/); + OnRowEnter(ref dataGridViewCurrentCell, ptCurrentCell.X, ptCurrentCell.Y, true /*canCreateNewRow*/, true /*validationFailureOccurred*/); } if (fireCellEnter) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { return null; } - OnCellEnter(ref dataGridViewCurrentCell, this.ptCurrentCell.X, this.ptCurrentCell.Y); + OnCellEnter(ref dataGridViewCurrentCell, ptCurrentCell.X, ptCurrentCell.Y); } - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { return null; } DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs(null, - this.ptCurrentCell.X, - this.ptCurrentCell.Y, + ptCurrentCell.X, + ptCurrentCell.Y, // null, // null, context); @@ -3822,50 +3822,50 @@ private DataGridViewDataErrorEventArgs CommitEdit(ref DataGridViewCell dataGridV return dgvdee; } - if (!this.IsCurrentCellInEditMode || !this.IsCurrentCellDirty) + if (!IsCurrentCellInEditMode || !IsCurrentCellDirty) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { return null; } - OnCellValidated(ref dataGridViewCurrentCell, this.ptCurrentCell.X, this.ptCurrentCell.Y); + OnCellValidated(ref dataGridViewCurrentCell, ptCurrentCell.X, ptCurrentCell.Y); } } } - if (this.ptCurrentCell.X == -1 || !this.IsCurrentCellInEditMode) + if (ptCurrentCell.X == -1 || !IsCurrentCellInEditMode) { return null; } Debug.Assert( ( - (this.editingControl != null && ((IDataGridViewEditingControl)this.editingControl).EditingControlValueChanged) || - (this.dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode] && ((IDataGridViewEditingCell)this.CurrentCellInternal).EditingCellValueChanged) - ) == this.IsCurrentCellDirty || - this.dataGridViewState1[DATAGRIDVIEWSTATE1_ignoringEditingChanges]); + (editingControl != null && ((IDataGridViewEditingControl)editingControl).EditingControlValueChanged) || + (dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode] && ((IDataGridViewEditingCell)CurrentCellInternal).EditingCellValueChanged) + ) == IsCurrentCellDirty || + dataGridViewState1[DATAGRIDVIEWSTATE1_ignoringEditingChanges]); - if (this.IsCurrentCellDirty) + if (IsCurrentCellDirty) { bool validateAndPushFormattedValue = CanValidateDataBoundDataGridViewCell(dataGridViewCurrentCell); if (validateAndPushFormattedValue) { if (validateCell == DataGridViewValidateCellInternal.WhenChanged) { - Debug.Assert(this.ptCurrentCell.X > -1); - if (this.ptCurrentCell.X == -1) + Debug.Assert(ptCurrentCell.X > -1); + if (ptCurrentCell.X == -1) { return null; } - if (OnCellValidating(ref dataGridViewCurrentCell, this.ptCurrentCell.X, this.ptCurrentCell.Y, context)) + if (OnCellValidating(ref dataGridViewCurrentCell, ptCurrentCell.X, ptCurrentCell.Y, context)) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { return null; } DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs(null, - this.ptCurrentCell.X, - this.ptCurrentCell.Y, + ptCurrentCell.X, + ptCurrentCell.Y, context); dgvdee.Cancel = true; return dgvdee; @@ -3875,25 +3875,25 @@ private DataGridViewDataErrorEventArgs CommitEdit(ref DataGridViewCell dataGridV Exception exception; object formattedValue; - if (this.editingControl != null) + if (editingControl != null) { - formattedValue = ((IDataGridViewEditingControl)this.editingControl).GetEditingControlFormattedValue(context); + formattedValue = ((IDataGridViewEditingControl)editingControl).GetEditingControlFormattedValue(context); } else { - Debug.Assert(this.dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode]); - formattedValue = ((IDataGridViewEditingCell)this.CurrentCellInternal).GetEditingCellFormattedValue(context); + Debug.Assert(dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode]); + formattedValue = ((IDataGridViewEditingCell)CurrentCellInternal).GetEditingCellFormattedValue(context); } if (!PushFormattedValue(ref dataGridViewCurrentCell, formattedValue, out exception)) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { return null; } DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs(exception, - this.ptCurrentCell.X, - this.ptCurrentCell.Y, + ptCurrentCell.X, + ptCurrentCell.Y, // dataGridViewCurrentCell.Value, // formattedValue, context); @@ -3901,35 +3901,35 @@ private DataGridViewDataErrorEventArgs CommitEdit(ref DataGridViewCell dataGridV OnDataErrorInternal(dgvdee); return dgvdee; } - if (!this.IsCurrentCellInEditMode) + if (!IsCurrentCellInEditMode) { return null; } - this.uneditedFormattedValue = formattedValue; + uneditedFormattedValue = formattedValue; } - if (this.editingControl != null) + if (editingControl != null) { - ((IDataGridViewEditingControl)this.editingControl).EditingControlValueChanged = false; + ((IDataGridViewEditingControl)editingControl).EditingControlValueChanged = false; } else { - Debug.Assert(this.dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode]); - ((IDataGridViewEditingCell)this.CurrentCellInternal).EditingCellValueChanged = false; + Debug.Assert(dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode]); + ((IDataGridViewEditingCell)CurrentCellInternal).EditingCellValueChanged = false; } - this.IsCurrentCellDirtyInternal = false; - this.IsCurrentRowDirtyInternal = true; + IsCurrentCellDirtyInternal = false; + IsCurrentRowDirtyInternal = true; if (validateAndPushFormattedValue) { if (validateCell == DataGridViewValidateCellInternal.Always || validateCell == DataGridViewValidateCellInternal.WhenChanged) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { return null; } - OnCellValidated(ref dataGridViewCurrentCell, this.ptCurrentCell.X, this.ptCurrentCell.Y); + OnCellValidated(ref dataGridViewCurrentCell, ptCurrentCell.X, ptCurrentCell.Y); } } } @@ -3941,12 +3941,12 @@ private bool CommitEdit(DataGridViewDataErrorContexts context, bool forCurrentRowChange) { // If we're already within a CellValidating event handler, don't try to commit the cell again. - if (this.dataGridViewOper[DATAGRIDVIEWOPER_inCellValidating]) + if (dataGridViewOper[DATAGRIDVIEWOPER_inCellValidating]) { return false; } - DataGridViewCell dataGridViewCurrentCell = this.CurrentCellInternal; + DataGridViewCell dataGridViewCurrentCell = CurrentCellInternal; DataGridViewDataErrorEventArgs dgvdee = CommitEdit(ref dataGridViewCurrentCell, context, forCurrentCellChange ? DataGridViewValidateCellInternal.Always : DataGridViewValidateCellInternal.WhenChanged /*validateCell*/, @@ -3983,13 +3983,13 @@ private bool CommitEdit(DataGridViewDataErrorContexts context, // See if we can leave the row if (forCurrentRowChange && forCurrentCellChange) { - Debug.Assert(this.ptCurrentCell.X > -1); - if (this.ptCurrentCell.X == -1) + Debug.Assert(ptCurrentCell.X > -1); + if (ptCurrentCell.X == -1) { return false; } - int columnIndex = this.ptCurrentCell.X; - int rowIndex = this.ptCurrentCell.Y; + int columnIndex = ptCurrentCell.X; + int rowIndex = ptCurrentCell.Y; // OnRowValidating returns true when the row validation was cancelled. if (OnRowValidating(ref dataGridViewCurrentCell, columnIndex, rowIndex)) { @@ -4022,20 +4022,20 @@ private bool CommitEditForOperation(int columnIndex, int rowIndex, bool forCurre DataGridViewValidateCellInternal.Always /*validateCell*/, true /*fireCellLeave*/, true /*fireCellEnter*/, - this.ptCurrentCell.Y != rowIndex /*fireRowLeave*/, - this.ptCurrentCell.Y != rowIndex /*fireRowEnter*/, + ptCurrentCell.Y != rowIndex /*fireRowLeave*/, + ptCurrentCell.Y != rowIndex /*fireRowEnter*/, false /*fireLeave*/, - this.EditMode != DataGridViewEditMode.EditOnEnter /*keepFocus*/, + EditMode != DataGridViewEditMode.EditOnEnter /*keepFocus*/, false /*resetCurrentCell*/, false /*resetAnchorCell unused here*/)) { return false; } - if (this.ptCurrentCell.Y != rowIndex && this.ptCurrentCell.Y != -1) + if (ptCurrentCell.Y != rowIndex && ptCurrentCell.Y != -1) { DataGridViewCell dataGridViewCellTmp = null; - int columnIndexTmp = this.ptCurrentCell.X; - int rowIndexTmp = this.ptCurrentCell.Y; + int columnIndexTmp = ptCurrentCell.X; + int rowIndexTmp = ptCurrentCell.Y; if (OnRowValidating(ref dataGridViewCellTmp, columnIndexTmp, rowIndexTmp)) { // Row validation was cancelled @@ -4055,9 +4055,9 @@ private bool CommitEditForOperation(int columnIndex, int rowIndex, bool forCurre } // Re-enter editing mode if needed - if (this.Focused && - (!this.IsCurrentCellInEditMode && (this.EditMode == DataGridViewEditMode.EditOnEnter || - (this.EditMode != DataGridViewEditMode.EditProgrammatically && this.CurrentCellInternal.EditType == null)))) + if (Focused && + (!IsCurrentCellInEditMode && (EditMode == DataGridViewEditMode.EditOnEnter || + (EditMode != DataGridViewEditMode.EditProgrammatically && CurrentCellInternal.EditType == null)))) { BeginEditInternal(true /*selectAll*/); } @@ -4075,27 +4075,27 @@ private bool CommitEditForOperation(int columnIndex, int rowIndex, bool forCurre { if (!CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, false /*forCurrentCellChange*/, - this.ptCurrentCell.Y != rowIndex /*forCurrentRowChange*/)) + ptCurrentCell.Y != rowIndex /*forCurrentRowChange*/)) { return false; } } // Row validation was not cancelled, but operation needs to be re-evaluated. - Debug.Assert(columnIndex < this.Columns.Count); + Debug.Assert(columnIndex < Columns.Count); if (IsColumnOutOfBounds(columnIndex)) { return false; } - if (rowIndex >= this.Rows.Count) + if (rowIndex >= Rows.Count) { // CurrentCell was reset because the commit deleted row(s). // Since the user wants to change the current cell, we don't // want to end up with no CurrentCell. We pick the last visible // row in the grid which may be the 'new row'. - int lastVisibleRowIndex = this.Rows.GetLastRow(DataGridViewElementStates.Visible); + int lastVisibleRowIndex = Rows.GetLastRow(DataGridViewElementStates.Visible); if (forCurrentCellChange && - this.ptCurrentCell.X == -1 && + ptCurrentCell.X == -1 && lastVisibleRowIndex != -1) { bool success = SetAndSelectCurrentCellAddress(columnIndex, lastVisibleRowIndex, true, false, false, false /*clearSelection*/, false /*forceCurrentCellSelection*/); @@ -4104,7 +4104,7 @@ private bool CommitEditForOperation(int columnIndex, int rowIndex, bool forCurre // Interrupt operation because it has become invalid. return false; } - if (rowIndex > -1 && (this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Visible) == 0) + if (rowIndex > -1 && (Rows.GetRowState(rowIndex) & DataGridViewElementStates.Visible) == 0) { // Interrupt operation because target row has become invisible. return false; @@ -4116,17 +4116,17 @@ internal void CompleteCellsCollection(DataGridViewRow dataGridViewRow) { Debug.Assert(dataGridViewRow != null); int cellsInCollection = dataGridViewRow.Cells.Count; - if (this.Columns.Count > cellsInCollection) + if (Columns.Count > cellsInCollection) { int cellCount = 0; - DataGridViewCell[] cells = new DataGridViewCell[this.Columns.Count - cellsInCollection]; - for (int columnIndex = cellsInCollection; columnIndex < this.Columns.Count; columnIndex++) + DataGridViewCell[] cells = new DataGridViewCell[Columns.Count - cellsInCollection]; + for (int columnIndex = cellsInCollection; columnIndex < Columns.Count; columnIndex++) { - if (this.Columns[columnIndex].CellTemplate == null) + if (Columns[columnIndex].CellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridView_AColumnHasNoCellTemplate)); } - DataGridViewCell dgvcNew = (DataGridViewCell)this.Columns[columnIndex].CellTemplate.Clone(); + DataGridViewCell dgvcNew = (DataGridViewCell)Columns[columnIndex].CellTemplate.Clone(); cells[cellCount] = dgvcNew; cellCount++; } @@ -4140,18 +4140,18 @@ internal void CompleteCellsCollection(DataGridViewRow dataGridViewRow) /// private int ComputeFirstVisibleScrollingColumn() { - if (this.Columns.GetColumnsWidth(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen) >= this.layout.Data.Width) + if (Columns.GetColumnsWidth(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen) >= layout.Data.Width) { // Not enough room for scrolling columns. - this.negOffset = 0; + negOffset = 0; return -1; } - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); - if (this.horizontalOffset == 0) + if (horizontalOffset == 0) { - this.negOffset = 0; + negOffset = 0; return (dataGridViewColumn == null) ? -1 : dataGridViewColumn.Index; } @@ -4159,36 +4159,36 @@ private int ComputeFirstVisibleScrollingColumn() while (dataGridViewColumn != null) { cx += dataGridViewColumn.Thickness; - if (cx > this.horizontalOffset) + if (cx > horizontalOffset) { break; } - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); } if (dataGridViewColumn == null) { - Debug.Assert(cx <= this.horizontalOffset); - dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); + Debug.Assert(cx <= horizontalOffset); + dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); if (dataGridViewColumn == null) { - this.negOffset = 0; + negOffset = 0; return -1; } else { - if (this.negOffset != this.horizontalOffset) + if (negOffset != horizontalOffset) { - this.negOffset = 0; + negOffset = 0; } return dataGridViewColumn.Index; } } else { - this.negOffset = dataGridViewColumn.Thickness - (cx - this.horizontalOffset); + negOffset = dataGridViewColumn.Thickness - (cx - horizontalOffset); return dataGridViewColumn.Index; } } @@ -4196,9 +4196,9 @@ private int ComputeFirstVisibleScrollingColumn() private int ComputeHeightOfFittingTrailingScrollingRows(int totalVisibleFrozenHeight) { // - int displayHeight = this.layout.Data.Height - totalVisibleFrozenHeight; + int displayHeight = layout.Data.Height - totalVisibleFrozenHeight; int rowHeight = 0, rowHeights = 0; - int indexTmp = this.Rows.Count; + int indexTmp = Rows.Count; if (indexTmp == 0 || displayHeight <= 0) { @@ -4209,21 +4209,21 @@ private int ComputeHeightOfFittingTrailingScrollingRows(int totalVisibleFrozenHe indexTmp--; } - DataGridViewElementStates rowState = this.Rows.GetRowState(indexTmp); + DataGridViewElementStates rowState = Rows.GetRowState(indexTmp); if ((rowState & DataGridViewElementStates.Frozen) != 0) { return 0; } if ((rowState & DataGridViewElementStates.Visible) == 0) { - indexTmp = this.Rows.GetPreviousRow(indexTmp, + indexTmp = Rows.GetPreviousRow(indexTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); } if (indexTmp != -1) { - rowHeight = this.Rows.SharedRow(indexTmp).GetHeight(indexTmp); + rowHeight = Rows.SharedRow(indexTmp).GetHeight(indexTmp); if (rowHeight > displayHeight) { return rowHeight; @@ -4233,12 +4233,12 @@ private int ComputeHeightOfFittingTrailingScrollingRows(int totalVisibleFrozenHe while (indexTmp != -1 && rowHeights + rowHeight <= displayHeight) { rowHeights += rowHeight; - indexTmp = this.Rows.GetPreviousRow(indexTmp, + indexTmp = Rows.GetPreviousRow(indexTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); if (indexTmp != -1) { - rowHeight = this.Rows.SharedRow(indexTmp).GetHeight(indexTmp); + rowHeight = Rows.SharedRow(indexTmp).GetHeight(indexTmp); } } @@ -4249,16 +4249,16 @@ private int ComputeHeightOfScrolledOffRows() { // int height = 0; - if (this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0) + if (displayedBandsInfo.FirstDisplayedScrollingRow >= 0) { - int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); + int rowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); if (rowIndex != -1) { - while (rowIndex != this.displayedBandsInfo.FirstDisplayedScrollingRow) + while (rowIndex != displayedBandsInfo.FirstDisplayedScrollingRow) { - Debug.Assert(rowIndex < this.displayedBandsInfo.FirstDisplayedScrollingRow); - height += this.Rows.SharedRow(rowIndex).GetHeight(rowIndex); - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); + Debug.Assert(rowIndex < displayedBandsInfo.FirstDisplayedScrollingRow); + height += Rows.SharedRow(rowIndex).GetHeight(rowIndex); + rowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); } } } @@ -4267,11 +4267,11 @@ private int ComputeHeightOfScrolledOffRows() private int ComputeHeightOfTrailingScrollingRows() { - if (this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0) + if (displayedBandsInfo.FirstDisplayedScrollingRow >= 0) { - int lastVisibleRowIndex = this.Rows.GetLastRow(DataGridViewElementStates.Visible); - return this.Rows.GetRowsHeight(DataGridViewElementStates.Visible, this.displayedBandsInfo.FirstDisplayedScrollingRow, lastVisibleRowIndex) + - this.Rows.SharedRow(lastVisibleRowIndex).GetHeight(lastVisibleRowIndex); + int lastVisibleRowIndex = Rows.GetLastRow(DataGridViewElementStates.Visible); + return Rows.GetRowsHeight(DataGridViewElementStates.Visible, displayedBandsInfo.FirstDisplayedScrollingRow, lastVisibleRowIndex) + + Rows.SharedRow(lastVisibleRowIndex).GetHeight(lastVisibleRowIndex); } return 0; } @@ -4280,20 +4280,20 @@ private bool ComputeLayout() { ClearRegionCache(); - LayoutData newLayout = new LayoutData(this.layout); - Rectangle oldResizeRect = this.layout.ResizeBoxRect; + LayoutData newLayout = new LayoutData(layout); + Rectangle oldResizeRect = layout.ResizeBoxRect; // Inside region - if (this.normalClientRectangle.Width > 0 || this.normalClientRectangle.Height > 0) + if (normalClientRectangle.Width > 0 || normalClientRectangle.Height > 0) { - newLayout.Inside = this.normalClientRectangle; + newLayout.Inside = normalClientRectangle; } else { - newLayout.Inside = this.ClientRectangle; + newLayout.Inside = ClientRectangle; } Rectangle inside = newLayout.Inside; - int borderWidth = this.BorderWidth; + int borderWidth = BorderWidth; inside.Inflate(-borderWidth, -borderWidth); if (inside.Height < 0) { @@ -4307,10 +4307,10 @@ private bool ComputeLayout() Rectangle insideLeft = inside; // Headers - if (this.layout.ColumnHeadersVisible) + if (layout.ColumnHeadersVisible) { Rectangle colHeaders = insideLeft; - colHeaders.Height = Math.Min(this.columnHeadersHeight, colHeaders.Height); + colHeaders.Height = Math.Min(columnHeadersHeight, colHeaders.Height); insideLeft.Y += colHeaders.Height; insideLeft.Height -= colHeaders.Height; Debug.Assert(insideLeft.Height >= 0); @@ -4321,11 +4321,11 @@ private bool ComputeLayout() newLayout.ColumnHeaders = Rectangle.Empty; } - if (this.layout.RowHeadersVisible) + if (layout.RowHeadersVisible) { Rectangle rowHeaders = insideLeft; - rowHeaders.Width = Math.Min(this.rowHeadersWidth, rowHeaders.Width); - if (this.RightToLeftInternal) + rowHeaders.Width = Math.Min(rowHeadersWidth, rowHeaders.Width); + if (RightToLeftInternal) { rowHeaders.X += insideLeft.Width - rowHeaders.Width; } @@ -4337,14 +4337,14 @@ private bool ComputeLayout() Debug.Assert(insideLeft.Width >= 0); newLayout.RowHeaders = rowHeaders; - if (this.layout.ColumnHeadersVisible) + if (layout.ColumnHeadersVisible) { Rectangle topLeft; Rectangle colHeaders = newLayout.ColumnHeaders; topLeft = colHeaders; - topLeft.Width = Math.Min(this.rowHeadersWidth, topLeft.Width); + topLeft.Width = Math.Min(rowHeadersWidth, topLeft.Width); colHeaders.Width -= topLeft.Width; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { topLeft.X += insideLeft.Width; } @@ -4368,9 +4368,9 @@ private bool ComputeLayout() } // Adjust insideLeft in case static top / left edge needs to be painted - if (this.SingleVerticalBorderAdded) + if (SingleVerticalBorderAdded) { - if (!this.RightToLeftInternal) + if (!RightToLeftInternal) { insideLeft.X++; } @@ -4379,7 +4379,7 @@ private bool ComputeLayout() insideLeft.Width--; } } - if (this.SingleHorizontalBorderAdded) + if (SingleHorizontalBorderAdded) { insideLeft.Y++; if (insideLeft.Height > 0) @@ -4397,13 +4397,13 @@ private bool ComputeLayout() Debug.Assert(newLayout.Data.Width >= 0); Debug.Assert(newLayout.Data.Height >= 0); - this.layout = newLayout; - this.layout.dirty = false; + layout = newLayout; + layout.dirty = false; bool columnsAdjusted = AdjustFillingColumns(); - this.layout = newLayout; - Debug.Assert(!this.layout.dirty); + layout = newLayout; + Debug.Assert(!layout.dirty); LayoutScrollBars(); // if the user shrank the grid client area, then OnResize invalidated the old @@ -4411,9 +4411,9 @@ private bool ComputeLayout() // note that we can't take the Invalidate call from the OnResize method, because if the // user enlarges the form then the old area will not be invalidated. // - if (!oldResizeRect.Equals(this.layout.ResizeBoxRect) && !this.layout.ResizeBoxRect.IsEmpty) + if (!oldResizeRect.Equals(layout.ResizeBoxRect) && !layout.ResizeBoxRect.IsEmpty) { - Invalidate(this.layout.ResizeBoxRect); + Invalidate(layout.ResizeBoxRect); } return columnsAdjusted; @@ -4432,50 +4432,50 @@ private void ComputeLayoutShortcut(bool computeVisibleRows) #if DEBUG else { - int oldNumTotallyVisibleFrozenRows = this.displayedBandsInfo.NumTotallyDisplayedFrozenRows; - int oldNumVisibleScrollingRows = this.displayedBandsInfo.NumDisplayedScrollingRows; - int oldNumTotallyVisibleScrollingRows = this.displayedBandsInfo.NumTotallyDisplayedScrollingRows; - int oldFirstVisibleScrollingRow = this.displayedBandsInfo.FirstDisplayedScrollingRow; + int oldNumTotallyVisibleFrozenRows = displayedBandsInfo.NumTotallyDisplayedFrozenRows; + int oldNumVisibleScrollingRows = displayedBandsInfo.NumDisplayedScrollingRows; + int oldNumTotallyVisibleScrollingRows = displayedBandsInfo.NumTotallyDisplayedScrollingRows; + int oldFirstVisibleScrollingRow = displayedBandsInfo.FirstDisplayedScrollingRow; ComputeVisibleRows(); - Debug.Assert(oldNumTotallyVisibleFrozenRows == this.displayedBandsInfo.NumTotallyDisplayedFrozenRows); - Debug.Assert(oldNumVisibleScrollingRows == this.displayedBandsInfo.NumDisplayedScrollingRows); - Debug.Assert(oldNumTotallyVisibleScrollingRows == this.displayedBandsInfo.NumTotallyDisplayedScrollingRows); - Debug.Assert(oldFirstVisibleScrollingRow == this.displayedBandsInfo.FirstDisplayedScrollingRow); + Debug.Assert(oldNumTotallyVisibleFrozenRows == displayedBandsInfo.NumTotallyDisplayedFrozenRows); + Debug.Assert(oldNumVisibleScrollingRows == displayedBandsInfo.NumDisplayedScrollingRows); + Debug.Assert(oldNumTotallyVisibleScrollingRows == displayedBandsInfo.NumTotallyDisplayedScrollingRows); + Debug.Assert(oldFirstVisibleScrollingRow == displayedBandsInfo.FirstDisplayedScrollingRow); } #endif #if DEBUG int newFirstVisibleScrollingCol = ComputeFirstVisibleScrollingColumn(); - Debug.Assert(newFirstVisibleScrollingCol == this.displayedBandsInfo.FirstDisplayedScrollingCol); + Debug.Assert(newFirstVisibleScrollingCol == displayedBandsInfo.FirstDisplayedScrollingCol); - int oldLastTotallyVisibleScrollingCol = this.displayedBandsInfo.LastTotallyDisplayedScrollingCol; - int oldFirstVisibleScrollingCol = this.displayedBandsInfo.FirstDisplayedScrollingCol; + int oldLastTotallyVisibleScrollingCol = displayedBandsInfo.LastTotallyDisplayedScrollingCol; + int oldFirstVisibleScrollingCol = displayedBandsInfo.FirstDisplayedScrollingCol; ComputeVisibleColumns(); - Debug.Assert(oldLastTotallyVisibleScrollingCol == this.displayedBandsInfo.LastTotallyDisplayedScrollingCol); - Debug.Assert(oldFirstVisibleScrollingCol == this.displayedBandsInfo.FirstDisplayedScrollingCol); + Debug.Assert(oldLastTotallyVisibleScrollingCol == displayedBandsInfo.LastTotallyDisplayedScrollingCol); + Debug.Assert(oldFirstVisibleScrollingCol == displayedBandsInfo.FirstDisplayedScrollingCol); #endif - if (this.vertScrollBar.Enabled) + if (vertScrollBar.Enabled) { - int totalVisibleHeight = this.Rows.GetRowsHeight(DataGridViewElementStates.Visible); - int totalVisibleFrozenHeight = this.Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); - int oldVertScrollBarValue = this.vertScrollBar.Value; - int oldThumbHeight = Math.Max(((this.vertScrollBar.Height - 2 * SystemInformation.VerticalScrollBarArrowHeight) * this.vertScrollBar.LargeChange) / this.vertScrollBar.Maximum, 8); + int totalVisibleHeight = Rows.GetRowsHeight(DataGridViewElementStates.Visible); + int totalVisibleFrozenHeight = Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int oldVertScrollBarValue = vertScrollBar.Value; + int oldThumbHeight = Math.Max(((vertScrollBar.Height - 2 * SystemInformation.VerticalScrollBarArrowHeight) * vertScrollBar.LargeChange) / vertScrollBar.Maximum, 8); - this.vertScrollBar.Maximum = totalVisibleHeight - totalVisibleFrozenHeight; - Debug.Assert(this.vertScrollBar.Maximum > 0); - this.vertScrollBar.Value = ComputeHeightOfScrolledOffRows(); - this.vertScrollBar.LargeChange = this.layout.Data.Height - totalVisibleFrozenHeight; - this.verticalOffset = this.vertScrollBar.Value; + vertScrollBar.Maximum = totalVisibleHeight - totalVisibleFrozenHeight; + Debug.Assert(vertScrollBar.Maximum > 0); + vertScrollBar.Value = ComputeHeightOfScrolledOffRows(); + vertScrollBar.LargeChange = layout.Data.Height - totalVisibleFrozenHeight; + verticalOffset = vertScrollBar.Value; - if (this.vertScrollBar.Visible && - (oldVertScrollBarValue != this.verticalOffset || - oldThumbHeight != Math.Max(((this.vertScrollBar.Height - 2 * SystemInformation.VerticalScrollBarArrowHeight) * this.vertScrollBar.LargeChange) / this.vertScrollBar.Maximum, 8))) + if (vertScrollBar.Visible && + (oldVertScrollBarValue != verticalOffset || + oldThumbHeight != Math.Max(((vertScrollBar.Height - 2 * SystemInformation.VerticalScrollBarArrowHeight) * vertScrollBar.LargeChange) / vertScrollBar.Maximum, 8))) { // Only update the vertical scroll bar is the thumb moved or resized. - this.vertScrollBar.Invalidate(); + vertScrollBar.Invalidate(); } - Debug.Assert(this.verticalOffset == this.vertScrollBar.Value); + Debug.Assert(verticalOffset == vertScrollBar.Value); } } @@ -4510,24 +4510,24 @@ private void ComputeVisibleColumns() { DataGridViewColumn dataGridViewColumn = null; int numVisibleScrollingCols = 0, visibleScrollingColumnsTmp = 0; - int displayWidth = this.layout.Data.Width, cx = 0; + int displayWidth = layout.Data.Width, cx = 0; int numDisplayedFrozenCols = 0, firstDisplayedFrozenCol = -1, lastDisplayedFrozenCol = -1; - int firstDisplayedScrollingCol = this.displayedBandsInfo.FirstDisplayedScrollingCol; + int firstDisplayedScrollingCol = displayedBandsInfo.FirstDisplayedScrollingCol; // the same problem with negative numbers: // if the width passed in is negative, then return 0 - if (displayWidth <= 0 || this.Columns.GetColumnCount(DataGridViewElementStates.Visible) == 0) - { - this.displayedBandsInfo.FirstDisplayedFrozenCol = -1; - this.displayedBandsInfo.NumDisplayedFrozenCols = 0; - this.displayedBandsInfo.FirstDisplayedScrollingCol = -1; - this.displayedBandsInfo.NumDisplayedScrollingCols = 0; - this.displayedBandsInfo.LastDisplayedFrozenCol = -1; - this.displayedBandsInfo.LastTotallyDisplayedScrollingCol = -1; + if (displayWidth <= 0 || Columns.GetColumnCount(DataGridViewElementStates.Visible) == 0) + { + displayedBandsInfo.FirstDisplayedFrozenCol = -1; + displayedBandsInfo.NumDisplayedFrozenCols = 0; + displayedBandsInfo.FirstDisplayedScrollingCol = -1; + displayedBandsInfo.NumDisplayedScrollingCols = 0; + displayedBandsInfo.LastDisplayedFrozenCol = -1; + displayedBandsInfo.LastTotallyDisplayedScrollingCol = -1; return; } - dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.None); + dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.None); while (dataGridViewColumn != null) { if (!dataGridViewColumn.Frozen && dataGridViewColumn.Visible) @@ -4548,26 +4548,26 @@ private void ComputeVisibleColumns() break; } } - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.None, DataGridViewElementStates.None); + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.None, DataGridViewElementStates.None); } - Debug.Assert(cx <= this.Columns.GetColumnsWidth(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)); + Debug.Assert(cx <= Columns.GetColumnsWidth(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)); if (cx < displayWidth && firstDisplayedScrollingCol >= 0) { - dataGridViewColumn = this.Columns[firstDisplayedScrollingCol]; + dataGridViewColumn = Columns[firstDisplayedScrollingCol]; if (dataGridViewColumn.Frozen) { - dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible, + dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); - this.negOffset = 0; + negOffset = 0; if (dataGridViewColumn == null) { - this.displayedBandsInfo.FirstDisplayedFrozenCol = firstDisplayedFrozenCol; - this.displayedBandsInfo.LastDisplayedFrozenCol = lastDisplayedFrozenCol; - this.displayedBandsInfo.NumDisplayedFrozenCols = numDisplayedFrozenCols; - this.displayedBandsInfo.FirstDisplayedScrollingCol = this.displayedBandsInfo.LastTotallyDisplayedScrollingCol = -1; - this.displayedBandsInfo.NumDisplayedScrollingCols = 0; + displayedBandsInfo.FirstDisplayedFrozenCol = firstDisplayedFrozenCol; + displayedBandsInfo.LastDisplayedFrozenCol = lastDisplayedFrozenCol; + displayedBandsInfo.NumDisplayedFrozenCols = numDisplayedFrozenCols; + displayedBandsInfo.FirstDisplayedScrollingCol = displayedBandsInfo.LastTotallyDisplayedScrollingCol = -1; + displayedBandsInfo.NumDisplayedScrollingCols = 0; return; } else @@ -4576,12 +4576,12 @@ private void ComputeVisibleColumns() } } - cx -= this.negOffset; + cx -= negOffset; while (cx < displayWidth && dataGridViewColumn != null) { cx += dataGridViewColumn.Thickness; visibleScrollingColumnsTmp++; - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); } @@ -4593,27 +4593,27 @@ private void ComputeVisibleColumns() bool invalidate = false; Debug.Assert(firstDisplayedScrollingCol >= 0); //first minimize value of this.negOffset - if (this.negOffset > 0) + if (negOffset > 0) { invalidate = true; - if (displayWidth - cx > this.negOffset) + if (displayWidth - cx > negOffset) { - cx += this.negOffset; - this.horizontalOffset -= this.negOffset; - this.negOffset = 0; + cx += negOffset; + horizontalOffset -= negOffset; + negOffset = 0; } else { - this.horizontalOffset -= displayWidth - cx; - this.negOffset -= displayWidth - cx; + horizontalOffset -= displayWidth - cx; + negOffset -= displayWidth - cx; cx = displayWidth; } } // second try to scroll entire columns - if (cx < displayWidth && this.horizontalOffset > 0) + if (cx < displayWidth && horizontalOffset > 0) { - Debug.Assert(this.negOffset == 0); - dataGridViewColumn = this.Columns.GetPreviousColumn((this.Columns[firstDisplayedScrollingCol]), + Debug.Assert(negOffset == 0); + dataGridViewColumn = Columns.GetPreviousColumn((Columns[firstDisplayedScrollingCol]), DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); while (dataGridViewColumn != null && cx + dataGridViewColumn.Thickness <= displayWidth) @@ -4622,28 +4622,28 @@ private void ComputeVisibleColumns() visibleScrollingColumnsTmp++; invalidate = true; firstDisplayedScrollingCol = dataGridViewColumn.Index; - this.horizontalOffset -= dataGridViewColumn.Thickness; - dataGridViewColumn = this.Columns.GetPreviousColumn(dataGridViewColumn, + horizontalOffset -= dataGridViewColumn.Thickness; + dataGridViewColumn = Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); } } // third try to partially scroll in first scrolled off column - if (cx < displayWidth && this.horizontalOffset > 0 && firstDisplayedScrollingCol != 0) + if (cx < displayWidth && horizontalOffset > 0 && firstDisplayedScrollingCol != 0) { - Debug.Assert(this.negOffset == 0); - dataGridViewColumn = this.Columns.GetPreviousColumn((this.Columns[firstDisplayedScrollingCol]), + Debug.Assert(negOffset == 0); + dataGridViewColumn = Columns.GetPreviousColumn((Columns[firstDisplayedScrollingCol]), DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); Debug.Assert(dataGridViewColumn != null); Debug.Assert(dataGridViewColumn.Thickness > displayWidth - cx); firstDisplayedScrollingCol = dataGridViewColumn.Index; - this.negOffset = dataGridViewColumn.Thickness - displayWidth + cx; - this.horizontalOffset -= displayWidth - cx; + negOffset = dataGridViewColumn.Thickness - displayWidth + cx; + horizontalOffset -= displayWidth - cx; visibleScrollingColumnsTmp++; invalidate = true; cx = displayWidth; - Debug.Assert(this.negOffset == GetNegOffsetFromHorizontalOffset(this.horizontalOffset)); + Debug.Assert(negOffset == GetNegOffsetFromHorizontalOffset(horizontalOffset)); } // update the number of visible columns to the new reality @@ -4653,7 +4653,7 @@ private void ComputeVisibleColumns() if (invalidate) { InvalidateData(); - Invalidate(this.layout.ColumnHeaders); + Invalidate(layout.ColumnHeaders); } } @@ -4667,45 +4667,45 @@ private void ComputeVisibleColumns() if (jumpFromFirstVisibleScrollingCol < 0) { - this.displayedBandsInfo.LastTotallyDisplayedScrollingCol = -1; // no totally visible scrolling column at all + displayedBandsInfo.LastTotallyDisplayedScrollingCol = -1; // no totally visible scrolling column at all } else { Debug.Assert(firstDisplayedScrollingCol >= 0); - dataGridViewColumn = this.Columns[firstDisplayedScrollingCol]; + dataGridViewColumn = Columns[firstDisplayedScrollingCol]; for (int jump = 0; jump < jumpFromFirstVisibleScrollingCol; jump++) { - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); } - this.displayedBandsInfo.LastTotallyDisplayedScrollingCol = dataGridViewColumn.Index; + displayedBandsInfo.LastTotallyDisplayedScrollingCol = dataGridViewColumn.Index; } } else { - this.displayedBandsInfo.LastTotallyDisplayedScrollingCol = -1; + displayedBandsInfo.LastTotallyDisplayedScrollingCol = -1; } - this.displayedBandsInfo.FirstDisplayedFrozenCol = firstDisplayedFrozenCol; - this.displayedBandsInfo.LastDisplayedFrozenCol = lastDisplayedFrozenCol; - this.displayedBandsInfo.NumDisplayedFrozenCols = numDisplayedFrozenCols; - this.displayedBandsInfo.FirstDisplayedScrollingCol = firstDisplayedScrollingCol; - this.displayedBandsInfo.NumDisplayedScrollingCols = numVisibleScrollingCols; - Debug.Assert((this.displayedBandsInfo.NumDisplayedScrollingCols > 0 && this.displayedBandsInfo.FirstDisplayedScrollingCol != -1) || - (this.displayedBandsInfo.NumDisplayedScrollingCols == 0 && this.displayedBandsInfo.FirstDisplayedScrollingCol == -1)); + displayedBandsInfo.FirstDisplayedFrozenCol = firstDisplayedFrozenCol; + displayedBandsInfo.LastDisplayedFrozenCol = lastDisplayedFrozenCol; + displayedBandsInfo.NumDisplayedFrozenCols = numDisplayedFrozenCols; + displayedBandsInfo.FirstDisplayedScrollingCol = firstDisplayedScrollingCol; + displayedBandsInfo.NumDisplayedScrollingCols = numVisibleScrollingCols; + Debug.Assert((displayedBandsInfo.NumDisplayedScrollingCols > 0 && displayedBandsInfo.FirstDisplayedScrollingCol != -1) || + (displayedBandsInfo.NumDisplayedScrollingCols == 0 && displayedBandsInfo.FirstDisplayedScrollingCol == -1)); } private void ComputeVisibleRows() { int firstDisplayedFrozenRow = -1; - int firstDisplayedScrollingRow = this.displayedBandsInfo.FirstDisplayedScrollingRow; + int firstDisplayedScrollingRow = displayedBandsInfo.FirstDisplayedScrollingRow; int lastDisplayedFrozenRow = -1, lastDisplayedScrollingRow = -1; int numTotallyDisplayedFrozenRows = 0; - int displayHeight = this.layout.Data.Height; + int displayHeight = layout.Data.Height; int cy = 0; int visibleScrollingRows = 0; - int nRows = this.Rows.Count; + int nRows = Rows.Count; int rowIndex; // when minimizing the dataGridView window, we will get negative values for the @@ -4716,17 +4716,17 @@ private void ComputeVisibleRows() if (displayHeight <= 0 || nRows == 0) { - this.displayedBandsInfo.NumDisplayedFrozenRows = this.displayedBandsInfo.NumTotallyDisplayedFrozenRows = - this.displayedBandsInfo.NumDisplayedScrollingRows = this.displayedBandsInfo.NumTotallyDisplayedScrollingRows = 0; - this.displayedBandsInfo.FirstDisplayedFrozenRow = this.displayedBandsInfo.FirstDisplayedScrollingRow = - this.displayedBandsInfo.LastDisplayedFrozenRow = this.displayedBandsInfo.LastDisplayedScrollingRow = -1; + displayedBandsInfo.NumDisplayedFrozenRows = displayedBandsInfo.NumTotallyDisplayedFrozenRows = + displayedBandsInfo.NumDisplayedScrollingRows = displayedBandsInfo.NumTotallyDisplayedScrollingRows = 0; + displayedBandsInfo.FirstDisplayedFrozenRow = displayedBandsInfo.FirstDisplayedScrollingRow = + displayedBandsInfo.LastDisplayedFrozenRow = displayedBandsInfo.LastDisplayedScrollingRow = -1; return; } for (rowIndex = 0; rowIndex < nRows; rowIndex++) { Debug.Assert(cy < displayHeight); - DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); + DataGridViewElementStates rowState = Rows.GetRowState(rowIndex); if ((rowState & DataGridViewElementStates.Frozen) == 0 && (rowState & DataGridViewElementStates.Visible) != 0) { @@ -4734,7 +4734,7 @@ private void ComputeVisibleRows() } if ((rowState & DataGridViewElementStates.Visible) != 0) { - cy += this.Rows.SharedRow(rowIndex).GetHeight(rowIndex); + cy += Rows.SharedRow(rowIndex).GetHeight(rowIndex); if (firstDisplayedFrozenRow == -1) { firstDisplayedFrozenRow = rowIndex; @@ -4753,11 +4753,11 @@ private void ComputeVisibleRows() if (cy > displayHeight) { - this.displayedBandsInfo.NumDisplayedFrozenRows = numTotallyDisplayedFrozenRows + 1; + displayedBandsInfo.NumDisplayedFrozenRows = numTotallyDisplayedFrozenRows + 1; } else { - this.displayedBandsInfo.NumDisplayedFrozenRows = numTotallyDisplayedFrozenRows; + displayedBandsInfo.NumDisplayedFrozenRows = numTotallyDisplayedFrozenRows; } // loop exited when: @@ -4774,8 +4774,8 @@ private void ComputeVisibleRows() while (firstDisplayedScrollingRow < nRows && ( - (this.Rows.GetRowState(firstDisplayedScrollingRow) & DataGridViewElementStates.Frozen) != 0 || - (this.Rows.GetRowState(firstDisplayedScrollingRow) & DataGridViewElementStates.Visible) == 0 + (Rows.GetRowState(firstDisplayedScrollingRow) & DataGridViewElementStates.Frozen) != 0 || + (Rows.GetRowState(firstDisplayedScrollingRow) & DataGridViewElementStates.Visible) == 0 ) ) { @@ -4784,9 +4784,9 @@ private void ComputeVisibleRows() for (int i = firstDisplayedScrollingRow; i < nRows; i++) { - if ((this.Rows.GetRowState(i) & DataGridViewElementStates.Visible) != 0) + if ((Rows.GetRowState(i) & DataGridViewElementStates.Visible) != 0) { - cy += this.Rows.SharedRow(i).GetHeight(i); + cy += Rows.SharedRow(i).GetHeight(i); visibleScrollingRows++; lastDisplayedScrollingRow = i; } @@ -4800,9 +4800,9 @@ private void ComputeVisibleRows() { for (int i = firstDisplayedScrollingRow - 1; i >= numTotallyDisplayedFrozenRows; i--) { - if ((this.Rows.GetRowState(i) & (DataGridViewElementStates.Frozen | DataGridViewElementStates.Visible)) == DataGridViewElementStates.Visible) + if ((Rows.GetRowState(i) & (DataGridViewElementStates.Frozen | DataGridViewElementStates.Visible)) == DataGridViewElementStates.Visible) { - int height = this.Rows.SharedRow(i).GetHeight(i); + int height = Rows.SharedRow(i).GetHeight(i); if (cy + height > displayHeight) { break; @@ -4815,14 +4815,14 @@ private void ComputeVisibleRows() } } - this.displayedBandsInfo.NumDisplayedScrollingRows = visibleScrollingRows; + displayedBandsInfo.NumDisplayedScrollingRows = visibleScrollingRows; if (cy > displayHeight) { - this.displayedBandsInfo.NumTotallyDisplayedScrollingRows = visibleScrollingRows - 1; + displayedBandsInfo.NumTotallyDisplayedScrollingRows = visibleScrollingRows - 1; } else { - this.displayedBandsInfo.NumTotallyDisplayedScrollingRows = visibleScrollingRows; + displayedBandsInfo.NumTotallyDisplayedScrollingRows = visibleScrollingRows; } if (visibleScrollingRows == 0) { @@ -4832,7 +4832,7 @@ private void ComputeVisibleRows() } else { - this.displayedBandsInfo.NumDisplayedScrollingRows = this.displayedBandsInfo.NumTotallyDisplayedScrollingRows = 0; + displayedBandsInfo.NumDisplayedScrollingRows = displayedBandsInfo.NumTotallyDisplayedScrollingRows = 0; firstDisplayedScrollingRow = -1; } @@ -4840,16 +4840,16 @@ private void ComputeVisibleRows() Debug.Assert(lastDisplayedFrozenRow < nRows, "lastDisplayedFrozenRow larger than number of rows"); Debug.Assert(lastDisplayedScrollingRow < nRows, "lastDisplayedScrollingRow larger than number of rows"); - this.displayedBandsInfo.FirstDisplayedFrozenRow = firstDisplayedFrozenRow; - this.displayedBandsInfo.FirstDisplayedScrollingRow = firstDisplayedScrollingRow; - this.displayedBandsInfo.NumTotallyDisplayedFrozenRows = numTotallyDisplayedFrozenRows; - this.displayedBandsInfo.LastDisplayedFrozenRow = lastDisplayedFrozenRow; - this.displayedBandsInfo.LastDisplayedScrollingRow = lastDisplayedScrollingRow; + displayedBandsInfo.FirstDisplayedFrozenRow = firstDisplayedFrozenRow; + displayedBandsInfo.FirstDisplayedScrollingRow = firstDisplayedScrollingRow; + displayedBandsInfo.NumTotallyDisplayedFrozenRows = numTotallyDisplayedFrozenRows; + displayedBandsInfo.LastDisplayedFrozenRow = lastDisplayedFrozenRow; + displayedBandsInfo.LastDisplayedScrollingRow = lastDisplayedScrollingRow; - Debug.Assert(this.displayedBandsInfo.NumTotallyDisplayedFrozenRows >= 0, "the number of visible frozen rows can't be negative"); - Debug.Assert(this.displayedBandsInfo.NumDisplayedScrollingRows >= 0, "the number of visible scrolling rows can't be negative"); - Debug.Assert(this.displayedBandsInfo.NumTotallyDisplayedScrollingRows >= 0, "the number of totally visible scrolling rows can't be negative"); - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow < nRows, "firstDisplayedScrollingRow larger than number of rows"); + Debug.Assert(displayedBandsInfo.NumTotallyDisplayedFrozenRows >= 0, "the number of visible frozen rows can't be negative"); + Debug.Assert(displayedBandsInfo.NumDisplayedScrollingRows >= 0, "the number of visible scrolling rows can't be negative"); + Debug.Assert(displayedBandsInfo.NumTotallyDisplayedScrollingRows >= 0, "the number of totally visible scrolling rows can't be negative"); + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingRow < nRows, "firstDisplayedScrollingRow larger than number of rows"); } private Point ConvertCellToGridCoord(int columnIndex, int rowIndex, int x, int y) @@ -4858,20 +4858,20 @@ private Point ConvertCellToGridCoord(int columnIndex, int rowIndex, int x, int y if (columnIndex > -1) { columnX = GetColumnXFromIndex(columnIndex); - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - columnX -= this.Columns[columnIndex].Width; + columnX -= Columns[columnIndex].Width; } } else { - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - columnX = this.layout.RowHeaders.Left - 1; + columnX = layout.RowHeaders.Left - 1; } else { - columnX = this.layout.RowHeaders.Left; + columnX = layout.RowHeaders.Left; } } @@ -4881,7 +4881,7 @@ private Point ConvertCellToGridCoord(int columnIndex, int rowIndex, int x, int y } else { - rowY = this.layout.ColumnHeaders.Top; + rowY = layout.ColumnHeaders.Top; } return new Point(columnX + x, rowY + y); @@ -4899,10 +4899,10 @@ private void CorrectColumnDisplayIndexesAfterDeletion(DataGridViewColumn dataGri try { - this.dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments] = true; + dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments] = true; // All remaining columns with a DisplayIndex greater than dataGridViewColumn.DisplayIndex need to be decremented - foreach (DataGridViewColumn dataGridViewColumnTmp in this.Columns) + foreach (DataGridViewColumn dataGridViewColumnTmp in Columns) { if (dataGridViewColumnTmp.DisplayIndex > dataGridViewColumn.DisplayIndex) { @@ -4912,14 +4912,14 @@ private void CorrectColumnDisplayIndexesAfterDeletion(DataGridViewColumn dataGri } #if DEBUG - Debug.Assert(this.Columns.VerifyColumnDisplayIndexes()); + Debug.Assert(Columns.VerifyColumnDisplayIndexes()); #endif // Now raise all the OnColumnDisplayIndexChanged events FlushDisplayIndexChanged(true /*raiseEvent*/); } finally { - this.dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments] = false; + dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments] = false; FlushDisplayIndexChanged(false /*raiseEvent*/); } } @@ -4930,14 +4930,14 @@ private void CorrectColumnDisplayIndexesAfterInsertion(DataGridViewColumn dataGr Debug.Assert(dataGridViewColumn.DataGridView == this); // dataGridViewColumn.DisplayIndex has been set already. Debug.Assert(dataGridViewColumn.DisplayIndex >= 0); - Debug.Assert(dataGridViewColumn.DisplayIndex < this.Columns.Count); + Debug.Assert(dataGridViewColumn.DisplayIndex < Columns.Count); try { - this.dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments] = true; + dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments] = true; // All other columns with a DisplayIndex equal or greater than dataGridViewColumn.DisplayIndex need to be incremented - foreach (DataGridViewColumn dataGridViewColumnTmp in this.Columns) + foreach (DataGridViewColumn dataGridViewColumnTmp in Columns) { if (dataGridViewColumnTmp != dataGridViewColumn && dataGridViewColumnTmp.DisplayIndex >= dataGridViewColumn.DisplayIndex) { @@ -4947,14 +4947,14 @@ private void CorrectColumnDisplayIndexesAfterInsertion(DataGridViewColumn dataGr } #if DEBUG - Debug.Assert(this.Columns.VerifyColumnDisplayIndexes()); + Debug.Assert(Columns.VerifyColumnDisplayIndexes()); #endif // Now raise all the OnColumnDisplayIndexChanged events FlushDisplayIndexChanged(true /*raiseEvent*/); } finally { - this.dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments] = false; + dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments] = false; FlushDisplayIndexChanged(false /*raiseEvent*/); } } @@ -4962,16 +4962,16 @@ private void CorrectColumnDisplayIndexesAfterInsertion(DataGridViewColumn dataGr private void CorrectColumnFrozenState(DataGridViewColumn dataGridViewColumn, int anticipatedColumnIndex) { Debug.Assert(dataGridViewColumn != null); - Debug.Assert(anticipatedColumnIndex >= 0 && anticipatedColumnIndex <= this.Columns.Count); + Debug.Assert(anticipatedColumnIndex >= 0 && anticipatedColumnIndex <= Columns.Count); int anticipatedColumnDisplayIndex; - if (dataGridViewColumn.DisplayIndex == -1 || dataGridViewColumn.DisplayIndex > this.Columns.Count) + if (dataGridViewColumn.DisplayIndex == -1 || dataGridViewColumn.DisplayIndex > Columns.Count) { anticipatedColumnDisplayIndex = anticipatedColumnIndex; // By default, we pick the Index as the DisplayIndex. } else { - Debug.Assert(dataGridViewColumn.DisplayIndex >= 0 && dataGridViewColumn.DisplayIndex <= this.Columns.Count); + Debug.Assert(dataGridViewColumn.DisplayIndex >= 0 && dataGridViewColumn.DisplayIndex <= Columns.Count); anticipatedColumnDisplayIndex = dataGridViewColumn.DisplayIndex; // The specified DisplayIndex is just fine. } @@ -4979,7 +4979,7 @@ private void CorrectColumnFrozenState(DataGridViewColumn dataGridViewColumn, int int displayIndex = anticipatedColumnDisplayIndex - 1; do { - dataGridViewColumnPrev = this.Columns.GetColumnAtDisplayIndex(displayIndex); + dataGridViewColumnPrev = Columns.GetColumnAtDisplayIndex(displayIndex); displayIndex--; } while (displayIndex >= 0 && (dataGridViewColumnPrev == null || !dataGridViewColumnPrev.Visible)); @@ -4993,10 +4993,10 @@ private void CorrectColumnFrozenState(DataGridViewColumn dataGridViewColumn, int displayIndex = anticipatedColumnDisplayIndex; do { - dataGridViewColumnNext = this.Columns.GetColumnAtDisplayIndex(displayIndex); + dataGridViewColumnNext = Columns.GetColumnAtDisplayIndex(displayIndex); displayIndex++; } - while (displayIndex < this.Columns.Count && (dataGridViewColumnNext == null || !dataGridViewColumnNext.Visible)); + while (displayIndex < Columns.Count && (dataGridViewColumnNext == null || !dataGridViewColumnNext.Visible)); if (dataGridViewColumnNext != null && dataGridViewColumnNext.Frozen && !dataGridViewColumn.Frozen) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAddNonFrozenColumn)); @@ -5008,7 +5008,7 @@ private void CorrectColumnFrozenStates(DataGridViewColumn[] dataGridViewColumns) { DataGridView dataGridViewTmp = new DataGridView(); DataGridViewColumn dataGridViewColumnClone; - foreach (DataGridViewColumn dataGridViewColumn in this.Columns) + foreach (DataGridViewColumn dataGridViewColumn in Columns) { dataGridViewColumnClone = (DataGridViewColumn)dataGridViewColumn.Clone(); // DataGridViewColumn.Clone does not replicate the DisplayIndex value. @@ -5031,21 +5031,21 @@ private void CorrectColumnFrozenStates(DataGridViewColumn dataGridViewColumn, bo (!dataGridViewColumn.Frozen && frozenStateChanging)) { // make sure the previous visible columns are frozen as well - dataGridViewColumnTmp = this.Columns.GetPreviousColumn(dataGridViewColumn, + dataGridViewColumnTmp = Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen, DataGridViewElementStates.None); if (dataGridViewColumnTmp == null) { - DataGridViewColumn dataGridViewColumnFirst = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + DataGridViewColumn dataGridViewColumnFirst = Columns.GetFirstColumn(DataGridViewElementStates.Visible); if (dataGridViewColumnFirst != dataGridViewColumn) { dataGridViewColumnTmp = dataGridViewColumnFirst; } } - while (dataGridViewColumnTmp != null && this.Columns.DisplayInOrder(dataGridViewColumnTmp.Index, dataGridViewColumn.Index)) + while (dataGridViewColumnTmp != null && Columns.DisplayInOrder(dataGridViewColumnTmp.Index, dataGridViewColumn.Index)) { dataGridViewColumnTmp.Frozen = true; - dataGridViewColumnTmp = this.Columns.GetNextColumn(dataGridViewColumnTmp, + dataGridViewColumnTmp = Columns.GetNextColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); } @@ -5053,7 +5053,7 @@ private void CorrectColumnFrozenStates(DataGridViewColumn dataGridViewColumn, bo else { // make sure the next visible columns are not frozen - dataGridViewColumnTmp = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumnTmp = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); if (dataGridViewColumnTmp == null) @@ -5061,7 +5061,7 @@ private void CorrectColumnFrozenStates(DataGridViewColumn dataGridViewColumn, bo DataGridViewColumn dataGridViewColumnLast = dataGridViewColumn; do { - dataGridViewColumnTmp = this.Columns.GetNextColumn(dataGridViewColumnLast, + dataGridViewColumnTmp = Columns.GetNextColumn(dataGridViewColumnLast, DataGridViewElementStates.Visible, DataGridViewElementStates.None); if (dataGridViewColumnTmp != null) @@ -5075,10 +5075,10 @@ private void CorrectColumnFrozenStates(DataGridViewColumn dataGridViewColumn, bo dataGridViewColumnTmp = dataGridViewColumnLast; } } - while (dataGridViewColumnTmp != null && this.Columns.DisplayInOrder(dataGridViewColumn.Index, dataGridViewColumnTmp.Index)) + while (dataGridViewColumnTmp != null && Columns.DisplayInOrder(dataGridViewColumn.Index, dataGridViewColumnTmp.Index)) { dataGridViewColumnTmp.Frozen = false; - dataGridViewColumnTmp = this.Columns.GetPreviousColumn(dataGridViewColumnTmp, + dataGridViewColumnTmp = Columns.GetPreviousColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen, DataGridViewElementStates.None); } @@ -5089,7 +5089,7 @@ private void CorrectColumnFrozenStatesForMove(DataGridViewColumn dataGridViewCol { Debug.Assert(dataGridViewColumn != null); Debug.Assert(newDisplayIndex != dataGridViewColumn.DisplayIndex); - Debug.Assert(!this.dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments]); + Debug.Assert(!dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments]); // No check necessary when: // - column is invisible. @@ -5103,7 +5103,7 @@ private void CorrectColumnFrozenStatesForMove(DataGridViewColumn dataGridViewCol return; } - int colCount = this.Columns.Count, displayIndex; + int colCount = Columns.Count, displayIndex; if (newDisplayIndex < dataGridViewColumn.DisplayIndex) { @@ -5114,7 +5114,7 @@ private void CorrectColumnFrozenStatesForMove(DataGridViewColumn dataGridViewCol displayIndex = newDisplayIndex; do { - dataGridViewColumnNext = this.Columns.GetColumnAtDisplayIndex(displayIndex); + dataGridViewColumnNext = Columns.GetColumnAtDisplayIndex(displayIndex); displayIndex++; } while (displayIndex < colCount && (dataGridViewColumnNext == null || dataGridViewColumnNext == dataGridViewColumn || !dataGridViewColumnNext.Visible)); @@ -5133,7 +5133,7 @@ private void CorrectColumnFrozenStatesForMove(DataGridViewColumn dataGridViewCol displayIndex = newDisplayIndex; do { - dataGridViewColumnPrev = this.Columns.GetColumnAtDisplayIndex(displayIndex); + dataGridViewColumnPrev = Columns.GetColumnAtDisplayIndex(displayIndex); displayIndex--; } while (displayIndex >= 0 && (dataGridViewColumnPrev == null || !dataGridViewColumnPrev.Visible)); @@ -5148,10 +5148,10 @@ private void CorrectColumnFrozenStatesForMove(DataGridViewColumn dataGridViewCol private void CorrectColumnIndexesAfterDeletion(DataGridViewColumn dataGridViewColumn) { Debug.Assert(dataGridViewColumn != null); - for (int columnIndex = dataGridViewColumn.Index; columnIndex < this.Columns.Count; columnIndex++) + for (int columnIndex = dataGridViewColumn.Index; columnIndex < Columns.Count; columnIndex++) { - this.Columns[columnIndex].IndexInternal = this.Columns[columnIndex].Index - 1; - Debug.Assert(this.Columns[columnIndex].Index == columnIndex); + Columns[columnIndex].IndexInternal = Columns[columnIndex].Index - 1; + Debug.Assert(Columns[columnIndex].Index == columnIndex); } } @@ -5159,43 +5159,43 @@ private void CorrectColumnIndexesAfterInsertion(DataGridViewColumn dataGridViewC { Debug.Assert(dataGridViewColumn != null); Debug.Assert(insertionCount > 0); - for (int columnIndex = dataGridViewColumn.Index + insertionCount; columnIndex < this.Columns.Count; columnIndex++) + for (int columnIndex = dataGridViewColumn.Index + insertionCount; columnIndex < Columns.Count; columnIndex++) { - this.Columns[columnIndex].IndexInternal = columnIndex; + Columns[columnIndex].IndexInternal = columnIndex; } } private void CorrectFocus(bool onlyIfGridHasFocus) { - if ((!onlyIfGridHasFocus || this.Focused) && this.editingControl != null) + if ((!onlyIfGridHasFocus || Focused) && editingControl != null) { - Debug.Assert(this.CurrentCellInternal != null); + Debug.Assert(CurrentCellInternal != null); //Debug.Assert(this.editingControl.CanFocus); - this.editingControl.Focus(); + editingControl.Focus(); } } private void CorrectRowFrozenState(DataGridViewRow dataGridViewRow, DataGridViewElementStates rowState, int anticipatedRowIndex) { Debug.Assert(dataGridViewRow != null); - Debug.Assert(anticipatedRowIndex >= 0 && anticipatedRowIndex <= this.Rows.Count); + Debug.Assert(anticipatedRowIndex >= 0 && anticipatedRowIndex <= Rows.Count); - int previousRowIndex = this.Rows.GetPreviousRow(anticipatedRowIndex, + int previousRowIndex = Rows.GetPreviousRow(anticipatedRowIndex, DataGridViewElementStates.Visible, DataGridViewElementStates.None); if (previousRowIndex != -1 && - (this.Rows.GetRowState(previousRowIndex) & DataGridViewElementStates.Frozen) == 0 && + (Rows.GetRowState(previousRowIndex) & DataGridViewElementStates.Frozen) == 0 && (rowState & DataGridViewElementStates.Frozen) != 0) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAddFrozenRow)); } else { - int nextRowIndex = this.Rows.GetNextRow((previousRowIndex == -1) ? anticipatedRowIndex - 1 : previousRowIndex, + int nextRowIndex = Rows.GetNextRow((previousRowIndex == -1) ? anticipatedRowIndex - 1 : previousRowIndex, DataGridViewElementStates.Visible, DataGridViewElementStates.None); if (nextRowIndex != -1 && - (this.Rows.GetRowState(nextRowIndex) & DataGridViewElementStates.Frozen) != 0 && + (Rows.GetRowState(nextRowIndex) & DataGridViewElementStates.Frozen) != 0 && (rowState & DataGridViewElementStates.Frozen) == 0) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAddNonFrozenRow)); @@ -5208,18 +5208,18 @@ private void CorrectRowFrozenStates(DataGridViewRow[] dataGridViewRows, int rowI bool nextVisibleRowPresent = false, previousRowFrozen = true, nextRowFrozen = false, currentRowFrozen; // Check if there is a visible row before the insertion point, and if it's frozen - int rowIndexTmp = this.Rows.GetPreviousRow(rowIndexInserted, DataGridViewElementStates.Visible); + int rowIndexTmp = Rows.GetPreviousRow(rowIndexInserted, DataGridViewElementStates.Visible); if (rowIndexTmp != -1) { - previousRowFrozen = (this.Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Frozen) == DataGridViewElementStates.Frozen; + previousRowFrozen = (Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Frozen) == DataGridViewElementStates.Frozen; } // Check if there is a visible row at or after the insertion point, and if it's frozen - rowIndexTmp = this.Rows.GetNextRow(rowIndexInserted - 1, DataGridViewElementStates.Visible); + rowIndexTmp = Rows.GetNextRow(rowIndexInserted - 1, DataGridViewElementStates.Visible); if (rowIndexTmp != -1) { nextVisibleRowPresent = true; - nextRowFrozen = (this.Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Frozen) == DataGridViewElementStates.Frozen; + nextRowFrozen = (Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Frozen) == DataGridViewElementStates.Frozen; } for (int arrayIndex = 0; arrayIndex < dataGridViewRows.Length; arrayIndex++) @@ -5244,15 +5244,15 @@ private void CorrectRowFrozenStates(DataGridViewRow dataGridViewRow, int rowInde { Debug.Assert(dataGridViewRow != null); int rowIndexTmp; - if (((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Frozen) != 0 && !frozenStateChanging) || - ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Frozen) == 0 && frozenStateChanging)) + if (((Rows.GetRowState(rowIndex) & DataGridViewElementStates.Frozen) != 0 && !frozenStateChanging) || + ((Rows.GetRowState(rowIndex) & DataGridViewElementStates.Frozen) == 0 && frozenStateChanging)) { // make sure the previous visible rows are frozen as well - rowIndexTmp = this.Rows.GetPreviousRow(rowIndex, + rowIndexTmp = Rows.GetPreviousRow(rowIndex, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); if (rowIndexTmp == -1) { - int dataGridViewRowFirst = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + int dataGridViewRowFirst = Rows.GetFirstRow(DataGridViewElementStates.Visible); if (dataGridViewRowFirst != rowIndex) { rowIndexTmp = dataGridViewRowFirst; @@ -5260,8 +5260,8 @@ private void CorrectRowFrozenStates(DataGridViewRow dataGridViewRow, int rowInde } while (rowIndexTmp != -1 && rowIndexTmp < rowIndex) { - this.Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Frozen, true); - rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, + Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Frozen, true); + rowIndexTmp = Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); } @@ -5269,7 +5269,7 @@ private void CorrectRowFrozenStates(DataGridViewRow dataGridViewRow, int rowInde else { // make sure the next visible rows are not frozen - rowIndexTmp = this.Rows.GetNextRow(rowIndex, + rowIndexTmp = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); if (rowIndexTmp == -1) @@ -5277,7 +5277,7 @@ private void CorrectRowFrozenStates(DataGridViewRow dataGridViewRow, int rowInde int dataGridViewRowLast = rowIndex; do { - rowIndexTmp = this.Rows.GetNextRow(dataGridViewRowLast, + rowIndexTmp = Rows.GetNextRow(dataGridViewRowLast, DataGridViewElementStates.Visible); if (rowIndexTmp != -1) { @@ -5292,8 +5292,8 @@ private void CorrectRowFrozenStates(DataGridViewRow dataGridViewRow, int rowInde } while (rowIndexTmp != -1 && rowIndexTmp > rowIndex) { - this.Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Frozen, false); - rowIndexTmp = this.Rows.GetPreviousRow(rowIndexTmp, + Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Frozen, false); + rowIndexTmp = Rows.GetPreviousRow(rowIndexTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); } } @@ -5302,10 +5302,10 @@ private void CorrectRowFrozenStates(DataGridViewRow dataGridViewRow, int rowInde private void CorrectRowIndexesAfterDeletion(int rowIndexDeleted) { Debug.Assert(rowIndexDeleted >= 0); - int rowsCount = this.Rows.Count; + int rowsCount = Rows.Count; for (int rowIndex = rowIndexDeleted; rowIndex < rowsCount; rowIndex++) { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); if (dataGridViewRow.Index >= 0) { dataGridViewRow.IndexInternal = dataGridViewRow.Index - 1; @@ -5314,13 +5314,13 @@ private void CorrectRowIndexesAfterDeletion(int rowIndexDeleted) } // Fix 'new' row index if existant - if (this.newRowIndex == rowIndexDeleted) + if (newRowIndex == rowIndexDeleted) { - this.newRowIndex = -1; // No more 'new' row. + newRowIndex = -1; // No more 'new' row. } - else if (this.newRowIndex != -1) + else if (newRowIndex != -1) { - this.newRowIndex--; + newRowIndex--; } } @@ -5328,10 +5328,10 @@ private void CorrectRowIndexesAfterInsertion(int rowIndexInserted, int insertion { Debug.Assert(rowIndexInserted >= 0); Debug.Assert(insertionCount > 0); - int rowsCount = this.Rows.Count; + int rowsCount = Rows.Count; for (int rowIndex = rowIndexInserted + insertionCount; rowIndex < rowsCount; rowIndex++) { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); if (dataGridViewRow.Index >= 0) { dataGridViewRow.IndexInternal = dataGridViewRow.Index + insertionCount; @@ -5340,9 +5340,9 @@ private void CorrectRowIndexesAfterInsertion(int rowIndexInserted, int insertion } // Lastly update the 'new' row index if needed. - if (this.newRowIndex != -1) + if (newRowIndex != -1) { - this.newRowIndex += insertionCount; + newRowIndex += insertionCount; } } @@ -5378,9 +5378,9 @@ protected virtual DataGridViewRowCollection CreateRowsInstance() private NativeMethods.RECT[] CreateScrollableRegion(Rectangle scroll) { - if (this.cachedScrollableRegion != null) + if (cachedScrollableRegion != null) { - return this.cachedScrollableRegion; + return cachedScrollableRegion; } using (Region region = new Region(scroll)) @@ -5392,20 +5392,20 @@ private NativeMethods.RECT[] CreateScrollableRegion(Rectangle scroll) } if (handle != IntPtr.Zero) { - this.cachedScrollableRegion = UnsafeNativeMethods.GetRectsFromRegion(handle); + cachedScrollableRegion = UnsafeNativeMethods.GetRectsFromRegion(handle); region.ReleaseHrgn(handle); } } - return this.cachedScrollableRegion; + return cachedScrollableRegion; } private void DiscardNewRow() { - Debug.Assert(this.Rows.Count > 1); - Debug.Assert(this.newRowIndex != -1); + Debug.Assert(Rows.Count > 1); + Debug.Assert(newRowIndex != -1); - DataGridViewRowCancelEventArgs dgvrce = new DataGridViewRowCancelEventArgs(this.Rows[this.newRowIndex]); + DataGridViewRowCancelEventArgs dgvrce = new DataGridViewRowCancelEventArgs(Rows[newRowIndex]); OnUserDeletingRow(dgvrce); if (dgvrce.Cancel) { @@ -5413,23 +5413,23 @@ private void DiscardNewRow() } // Delete the 'new' row - Debug.Assert(this.newRowIndex == this.Rows.Count - 1); - DataGridViewRow dataGridViewRow = this.Rows[this.newRowIndex]; - this.Rows.RemoveAtInternal(this.newRowIndex, false /*force*/); + Debug.Assert(newRowIndex == Rows.Count - 1); + DataGridViewRow dataGridViewRow = Rows[newRowIndex]; + Rows.RemoveAtInternal(newRowIndex, false /*force*/); Debug.Assert(dataGridViewRow.Index == -1); DataGridViewRowEventArgs dgvre = new DataGridViewRowEventArgs(dataGridViewRow); OnUserDeletedRow(dgvre); // CorrectRowIndexesAfterDeletion resets this.newRowIndex to -1. - Debug.Assert(this.newRowIndex == -1); + Debug.Assert(newRowIndex == -1); - if (this.AllowUserToAddRowsInternal) + if (AllowUserToAddRowsInternal) { - this.newRowIndex = this.Rows.Count - 1; - Debug.Assert((this.Rows.GetRowState(this.newRowIndex) & DataGridViewElementStates.Visible) != 0); - Debug.Assert(this.ptCurrentCell.Y == this.newRowIndex); + newRowIndex = Rows.Count - 1; + Debug.Assert((Rows.GetRowState(newRowIndex) & DataGridViewElementStates.Visible) != 0); + Debug.Assert(ptCurrentCell.Y == newRowIndex); - OnDefaultValuesNeeded(new DataGridViewRowEventArgs(this.Rows[this.newRowIndex])); - InvalidateRowPrivate(this.newRowIndex); + OnDefaultValuesNeeded(new DataGridViewRowEventArgs(Rows[newRowIndex])); + InvalidateRowPrivate(newRowIndex); } } @@ -5443,7 +5443,7 @@ private void DiscardZonesInScrollingArea(ref Rectangle rectScrollingArea, // Discard empty background rectScrollingArea.Width -= emptyBackgroundWidth; rectScrollingArea.Height -= emptyBackgroundHeight; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { rectScrollingArea.X += emptyBackgroundWidth; } @@ -5451,8 +5451,8 @@ private void DiscardZonesInScrollingArea(ref Rectangle rectScrollingArea, if (discardFrozenColumns) { // Discard frozen columns - int frozenVisibleColumnsWidth = this.Columns.GetColumnsWidth(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); - if (!this.RightToLeftInternal) + int frozenVisibleColumnsWidth = Columns.GetColumnsWidth(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + if (!RightToLeftInternal) { rectScrollingArea.X += frozenVisibleColumnsWidth; } @@ -5468,9 +5468,9 @@ private void DiscardZonesInScrollingArea(ref Rectangle rectScrollingArea, public int DisplayedColumnCount(bool includePartialColumns) { - int cxMax = this.layout.Data.Width, cx = 0; + int cxMax = layout.Data.Width, cx = 0; int completeColumns = 0, partialColumns = 0; - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); while (dataGridViewColumn != null && cx < cxMax) { partialColumns++; @@ -5478,20 +5478,20 @@ public int DisplayedColumnCount(bool includePartialColumns) if (cx <= cxMax) { completeColumns++; - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen, DataGridViewElementStates.None); } } - if (cx < cxMax && this.displayedBandsInfo.FirstDisplayedScrollingCol >= 0) + if (cx < cxMax && displayedBandsInfo.FirstDisplayedScrollingCol >= 0) { - if (this.negOffset > 0) + if (negOffset > 0) { - cx -= this.negOffset; + cx -= negOffset; completeColumns--; } - dataGridViewColumn = (DataGridViewColumn)this.Columns[this.displayedBandsInfo.FirstDisplayedScrollingCol]; + dataGridViewColumn = (DataGridViewColumn)Columns[displayedBandsInfo.FirstDisplayedScrollingCol]; Debug.Assert(dataGridViewColumn.Visible && !dataGridViewColumn.Frozen); while (dataGridViewColumn != null && cx < cxMax) @@ -5501,7 +5501,7 @@ public int DisplayedColumnCount(bool includePartialColumns) if (cx <= cxMax) { completeColumns++; - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); } @@ -5513,104 +5513,104 @@ public int DisplayedColumnCount(bool includePartialColumns) public int DisplayedRowCount(bool includePartialRow) { - return includePartialRow ? (this.displayedBandsInfo.NumDisplayedFrozenRows + this.displayedBandsInfo.NumDisplayedScrollingRows) : - (this.displayedBandsInfo.NumTotallyDisplayedFrozenRows + this.displayedBandsInfo.NumTotallyDisplayedScrollingRows); + return includePartialRow ? (displayedBandsInfo.NumDisplayedFrozenRows + displayedBandsInfo.NumDisplayedScrollingRows) : + (displayedBandsInfo.NumTotallyDisplayedFrozenRows + displayedBandsInfo.NumTotallyDisplayedScrollingRows); } protected override void Dispose(bool disposing) { if (disposing) { - this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] = true; + dataGridViewOper[DATAGRIDVIEWOPER_inDispose] = true; try { // Remove any Columns contained in this control - for (int i = 0; i < this.Columns.Count; i++) + for (int i = 0; i < Columns.Count; i++) { - this.Columns[i].Dispose(); + Columns[i].Dispose(); } - this.Columns.Clear(); + Columns.Clear(); UnwireScrollBarsEvents(); - if (this.vertScrollBar != null) + if (vertScrollBar != null) { - this.vertScrollBar.Dispose(); - this.vertScrollBar = null; + vertScrollBar.Dispose(); + vertScrollBar = null; } - if (this.horizScrollBar != null) + if (horizScrollBar != null) { - this.horizScrollBar.Dispose(); - this.horizScrollBar = null; + horizScrollBar.Dispose(); + horizScrollBar = null; } - if (this.pens != null) + if (pens != null) { - int nPenEntries = this.pens.Count; + int nPenEntries = pens.Count; if (nPenEntries > 0) { - foreach (Pen pen in this.pens.Values) + foreach (Pen pen in pens.Values) { pen.Dispose(); } - this.pens.Clear(); + pens.Clear(); } - this.pens = null; + pens = null; } - if (this.brushes != null) + if (brushes != null) { - int nBrushEntries = this.brushes.Count; + int nBrushEntries = brushes.Count; if (nBrushEntries > 0) { - foreach (SolidBrush brush in this.brushes.Values) + foreach (SolidBrush brush in brushes.Values) { brush.Dispose(); } - this.brushes.Clear(); + brushes.Clear(); } - this.brushes = null; + brushes = null; } - if (this.placeholderStringFormat != null) + if (placeholderStringFormat != null) { - this.placeholderStringFormat.Dispose(); - this.placeholderStringFormat = null; + placeholderStringFormat.Dispose(); + placeholderStringFormat = null; } - if (this.latestEditingControl != null) + if (latestEditingControl != null) { - this.latestEditingControl.Dispose(); - this.latestEditingControl = null; + latestEditingControl.Dispose(); + latestEditingControl = null; } - if (this.editingControl != null) + if (editingControl != null) { - this.editingControl.Dispose(); - this.editingControl = null; + editingControl.Dispose(); + editingControl = null; } - if (this.editingPanel != null) + if (editingPanel != null) { - this.editingPanel.Dispose(); - this.editingPanel = null; + editingPanel.Dispose(); + editingPanel = null; } - if (this.gridPen != null) + if (gridPen != null) { - this.gridPen.Dispose(); - this.gridPen = null; + gridPen.Dispose(); + gridPen = null; } - Debug.Assert(this.noSelectionChangeCount == 0); + Debug.Assert(noSelectionChangeCount == 0); - if (this.dataConnection != null) + if (dataConnection != null) { - this.dataConnection.Dispose(); + dataConnection.Dispose(); } // DGV should dispose the tool tip control before disposing itself. - this.toolTipControl.Dispose(); + toolTipControl.Dispose(); } finally { - this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] = false; + dataGridViewOper[DATAGRIDVIEWOPER_inDispose] = false; } } base.Dispose(disposing); @@ -5620,15 +5620,15 @@ private void DrawColHeaderShadow(Graphics g, int mouseX) { Rectangle r = CalcColRelocationFeedbackRect(mouseX); DrawShadowRect(r); - if (this.dataGridViewState2[DATAGRIDVIEWSTATE2_showColumnRelocationInsertion]) + if (dataGridViewState2[DATAGRIDVIEWSTATE2_showColumnRelocationInsertion]) { - Rectangle rectInsertionBar = new Rectangle(0, this.layout.ColumnHeaders.Top, DATAGRIDVIEW_insertionBarWidth, this.layout.ColumnHeaders.Height); + Rectangle rectInsertionBar = new Rectangle(0, layout.ColumnHeaders.Top, DATAGRIDVIEW_insertionBarWidth, layout.ColumnHeaders.Height); // this.trackColumnEdge is the column preceeding the insertion point - if (this.trackColumnEdge == -1) + if (trackColumnEdge == -1) { // Insert as first column - rectInsertionBar.X = GetColumnXFromIndex(this.Columns.GetFirstColumn(DataGridViewElementStates.Visible).Index); - if (this.RightToLeftInternal) + rectInsertionBar.X = GetColumnXFromIndex(Columns.GetFirstColumn(DataGridViewElementStates.Visible).Index); + if (RightToLeftInternal) { rectInsertionBar.X -= DATAGRIDVIEW_insertionBarWidth; } @@ -5636,16 +5636,16 @@ private void DrawColHeaderShadow(Graphics g, int mouseX) else { int offsetFromCenter = 0; - if (this.Columns.GetNextColumn(this.Columns[this.trackColumnEdge], DataGridViewElementStates.Visible, DataGridViewElementStates.None) == null) + if (Columns.GetNextColumn(Columns[trackColumnEdge], DataGridViewElementStates.Visible, DataGridViewElementStates.None) == null) { - if (!this.RightToLeftInternal) + if (!RightToLeftInternal) { offsetFromCenter = DATAGRIDVIEW_insertionBarWidth; } } else { - if (this.RightToLeftInternal) + if (RightToLeftInternal) { offsetFromCenter = DATAGRIDVIEW_insertionBarWidth / 2 - 1; } @@ -5654,18 +5654,18 @@ private void DrawColHeaderShadow(Graphics g, int mouseX) offsetFromCenter = DATAGRIDVIEW_insertionBarWidth / 2 + 1; } } - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - rectInsertionBar.X = Math.Max(this.layout.ColumnHeaders.X, - GetColumnXFromIndex(this.trackColumnEdge) - this.Columns[this.trackColumnEdge].Width - offsetFromCenter); + rectInsertionBar.X = Math.Max(layout.ColumnHeaders.X, + GetColumnXFromIndex(trackColumnEdge) - Columns[trackColumnEdge].Width - offsetFromCenter); } else { - rectInsertionBar.X = Math.Min(GetColumnXFromIndex(this.trackColumnEdge) + this.Columns[this.trackColumnEdge].Width - offsetFromCenter, - this.layout.ColumnHeaders.Right - DATAGRIDVIEW_insertionBarWidth); + rectInsertionBar.X = Math.Min(GetColumnXFromIndex(trackColumnEdge) + Columns[trackColumnEdge].Width - offsetFromCenter, + layout.ColumnHeaders.Right - DATAGRIDVIEW_insertionBarWidth); } } - if (this.ApplyVisualStylesToHeaderCells) + if (ApplyVisualStylesToHeaderCells) { g.FillRectangle(GetCachedBrush(SystemColors.HotTrack), rectInsertionBar); } @@ -5700,7 +5700,7 @@ private void DrawShadowRect(Rectangle r) { const byte DATAGRIDVIEW_shadowEdgeThickness = 3; - IntPtr parentHandle = this.Handle; + IntPtr parentHandle = Handle; IntPtr dc = UnsafeNativeMethods.GetDCEx(new HandleRef(this, parentHandle), NativeMethods.NullHandleRef, NativeMethods.DCX_CACHE | NativeMethods.DCX_LOCKWINDOWUPDATE); IntPtr halftone = ControlPaint.CreateHalftoneHBRUSH(); IntPtr saveBrush = SafeNativeMethods.SelectObject(new HandleRef(this, dc), new HandleRef(null, halftone)); @@ -5721,7 +5721,7 @@ private void DrawShadowRect(Rectangle r) /// private void DrawSplitBar(Rectangle r) { - IntPtr parentHandle = this.Handle; + IntPtr parentHandle = Handle; IntPtr dc = UnsafeNativeMethods.GetDCEx(new HandleRef(this, parentHandle), NativeMethods.NullHandleRef, NativeMethods.DCX_CACHE | NativeMethods.DCX_LOCKWINDOWUPDATE); IntPtr halftone = ControlPaint.CreateHalftoneHBRUSH(); IntPtr saveBrush = SafeNativeMethods.SelectObject(new HandleRef(this, dc), new HandleRef(null, halftone)); @@ -5733,19 +5733,19 @@ private void DrawSplitBar(Rectangle r) private void EditingControls_CommonMouseEventHandler(object sender, MouseEventArgs e, DataGridViewMouseEvent dgvme) { - Debug.Assert(this.ptCurrentCell.X != -1); - int adjustedX = this.editingPanel.Location.X + e.X; - int adjustedY = this.editingPanel.Location.Y + e.Y; - if (sender == this.editingControl) + Debug.Assert(ptCurrentCell.X != -1); + int adjustedX = editingPanel.Location.X + e.X; + int adjustedY = editingPanel.Location.Y + e.Y; + if (sender == editingControl) { - adjustedX += this.editingControl.Location.X; - adjustedY += this.editingControl.Location.Y; + adjustedX += editingControl.Location.X; + adjustedY += editingControl.Location.Y; } if (dgvme == DataGridViewMouseEvent.MouseDown && e.Clicks == 1) { // Reset the flag that records single-click exposed as double-click. - this.dataGridViewOper[DATAGRIDVIEWOPER_lastEditCtrlClickDoubled] = false; + dataGridViewOper[DATAGRIDVIEWOPER_lastEditCtrlClickDoubled] = false; } MouseEventArgs me = new MouseEventArgs(e.Button, @@ -5756,28 +5756,28 @@ private void EditingControls_CommonMouseEventHandler(object sender, MouseEventAr HitTestInfo hti = HitTest(me.X, me.Y); int mouseX = me.X - hti.ColumnX; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - mouseX += ((hti.col == -1) ? this.RowHeadersWidth : this.Columns[hti.col].Thickness); + mouseX += ((hti.col == -1) ? RowHeadersWidth : Columns[hti.col].Thickness); } DataGridViewCellMouseEventArgs dgvcme = new DataGridViewCellMouseEventArgs(hti.col, hti.row, mouseX, me.Y - hti.RowY, me); try { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls] = true; // Check to see if this is a CellMouseDoubleClick situation if ((dgvme == DataGridViewMouseEvent.MouseDown || dgvme == DataGridViewMouseEvent.Click || dgvme == DataGridViewMouseEvent.MouseClick) && - (DateTime.Now.Ticks - this.lastMouseClickInfo.timeStamp) / 10000 <= SystemInformation.DoubleClickTime && - e.Button == this.lastMouseClickInfo.button && + (DateTime.Now.Ticks - lastMouseClickInfo.timeStamp) / 10000 <= SystemInformation.DoubleClickTime && + e.Button == lastMouseClickInfo.button && e.Clicks == 1 && - dgvcme.ColumnIndex == this.lastMouseClickInfo.col && - dgvcme.RowIndex == this.lastMouseClickInfo.row) + dgvcme.ColumnIndex == lastMouseClickInfo.col && + dgvcme.RowIndex == lastMouseClickInfo.row) { Size hotDoubleClickZone = SystemInformation.DoubleClickSize; - if (Math.Abs(dgvcme.X - this.lastMouseClickInfo.x) <= hotDoubleClickZone.Width / 2 && - Math.Abs(dgvcme.Y - this.lastMouseClickInfo.y) <= hotDoubleClickZone.Height / 2) + if (Math.Abs(dgvcme.X - lastMouseClickInfo.x) <= hotDoubleClickZone.Width / 2 && + Math.Abs(dgvcme.Y - lastMouseClickInfo.y) <= hotDoubleClickZone.Height / 2) { me = new MouseEventArgs(e.Button, 2, @@ -5790,8 +5790,8 @@ private void EditingControls_CommonMouseEventHandler(object sender, MouseEventAr case DataGridViewMouseEvent.MouseDown: { OnMouseDown(me); - if (dgvcme.ColumnIndex < this.Columns.Count && - dgvcme.RowIndex < this.Rows.Count) + if (dgvcme.ColumnIndex < Columns.Count && + dgvcme.RowIndex < Rows.Count) { OnCellMouseDown(dgvcme); } @@ -5801,8 +5801,8 @@ private void EditingControls_CommonMouseEventHandler(object sender, MouseEventAr { OnDoubleClick(me); if (e.Button == MouseButtons.Left && - dgvcme.ColumnIndex < this.Columns.Count && - dgvcme.RowIndex < this.Rows.Count) + dgvcme.ColumnIndex < Columns.Count && + dgvcme.RowIndex < Rows.Count) { OnCellDoubleClick(new DataGridViewCellEventArgs(dgvcme.ColumnIndex, dgvcme.RowIndex)); } @@ -5811,10 +5811,10 @@ private void EditingControls_CommonMouseEventHandler(object sender, MouseEventAr case DataGridViewMouseEvent.MouseClick: { // Set the flag that prevents the triple-click to be exposed as a double-click - this.dataGridViewOper[DATAGRIDVIEWOPER_lastEditCtrlClickDoubled] = true; + dataGridViewOper[DATAGRIDVIEWOPER_lastEditCtrlClickDoubled] = true; OnMouseDoubleClick(me); - if (dgvcme.ColumnIndex < this.Columns.Count && dgvcme.RowIndex < this.Rows.Count) + if (dgvcme.ColumnIndex < Columns.Count && dgvcme.RowIndex < Rows.Count) { OnCellMouseDoubleClick(dgvcme); } @@ -5825,7 +5825,7 @@ private void EditingControls_CommonMouseEventHandler(object sender, MouseEventAr } } - if (this.dataGridViewOper[DATAGRIDVIEWOPER_lastEditCtrlClickDoubled]) + if (dataGridViewOper[DATAGRIDVIEWOPER_lastEditCtrlClickDoubled]) { // Make sure that the triple-click is exposed as a single-click and not a double-click. if (e.Clicks == 2) @@ -5853,8 +5853,8 @@ private void EditingControls_CommonMouseEventHandler(object sender, MouseEventAr case DataGridViewMouseEvent.Click: OnClick(me); if (e.Button == MouseButtons.Left && - dgvcme.ColumnIndex < this.Columns.Count && - dgvcme.RowIndex < this.Rows.Count) + dgvcme.ColumnIndex < Columns.Count && + dgvcme.RowIndex < Rows.Count) { OnCellClick(new DataGridViewCellEventArgs(dgvcme.ColumnIndex, dgvcme.RowIndex)); } @@ -5862,38 +5862,38 @@ private void EditingControls_CommonMouseEventHandler(object sender, MouseEventAr case DataGridViewMouseEvent.DoubleClick: OnDoubleClick(me); if (e.Button == MouseButtons.Left && - dgvcme.ColumnIndex < this.Columns.Count && - dgvcme.RowIndex < this.Rows.Count) + dgvcme.ColumnIndex < Columns.Count && + dgvcme.RowIndex < Rows.Count) { OnCellDoubleClick(new DataGridViewCellEventArgs(dgvcme.ColumnIndex, dgvcme.RowIndex)); } break; case DataGridViewMouseEvent.MouseClick: OnMouseClick(me); - if (dgvcme.ColumnIndex < this.Columns.Count && - dgvcme.RowIndex < this.Rows.Count) + if (dgvcme.ColumnIndex < Columns.Count && + dgvcme.RowIndex < Rows.Count) { OnCellMouseClick(dgvcme); } break; case DataGridViewMouseEvent.MouseDoubleClick: OnMouseDoubleClick(me); - if (dgvcme.ColumnIndex < this.Columns.Count && - dgvcme.RowIndex < this.Rows.Count) + if (dgvcme.ColumnIndex < Columns.Count && + dgvcme.RowIndex < Rows.Count) { OnCellMouseDoubleClick(dgvcme); } break; case DataGridViewMouseEvent.MouseDown: OnMouseDown(me); - if (dgvcme.ColumnIndex < this.Columns.Count && - dgvcme.RowIndex < this.Rows.Count) + if (dgvcme.ColumnIndex < Columns.Count && + dgvcme.RowIndex < Rows.Count) { OnCellMouseDown(dgvcme); } break; case DataGridViewMouseEvent.MouseUp: - if (this.dataGridViewState2[DATAGRIDVIEWSTATE2_nextMouseUpIsDouble]) + if (dataGridViewState2[DATAGRIDVIEWSTATE2_nextMouseUpIsDouble]) { MouseEventArgs meTmp = new MouseEventArgs(e.Button, 2, @@ -5912,14 +5912,14 @@ private void EditingControls_CommonMouseEventHandler(object sender, MouseEventAr } finally { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls] = false; + dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls] = false; } } private void EditingControls_Click(object sender, System.EventArgs e) { - Debug.Assert(sender == this.editingControl || sender == this.editingPanel); - Debug.Assert(this.ptCurrentCell.X != -1); + Debug.Assert(sender == editingControl || sender == editingPanel); + Debug.Assert(ptCurrentCell.X != -1); System.Windows.Forms.MouseEventArgs me = e as System.Windows.Forms.MouseEventArgs; if (me != null) { @@ -5929,8 +5929,8 @@ private void EditingControls_Click(object sender, System.EventArgs e) private void EditingControls_DoubleClick(object sender, System.EventArgs e) { - Debug.Assert(sender == this.editingControl || sender == this.editingPanel); - Debug.Assert(this.ptCurrentCell.X != -1); + Debug.Assert(sender == editingControl || sender == editingPanel); + Debug.Assert(ptCurrentCell.X != -1); System.Windows.Forms.MouseEventArgs me = e as System.Windows.Forms.MouseEventArgs; if (me != null) { @@ -5940,35 +5940,35 @@ private void EditingControls_DoubleClick(object sender, System.EventArgs e) private void EditingControls_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e) { - Debug.Assert(sender == this.editingControl || sender == this.editingPanel); + Debug.Assert(sender == editingControl || sender == editingPanel); EditingControls_CommonMouseEventHandler(sender, e, DataGridViewMouseEvent.MouseClick); } private void EditingControls_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e) { - Debug.Assert(sender == this.editingControl || sender == this.editingPanel); + Debug.Assert(sender == editingControl || sender == editingPanel); EditingControls_CommonMouseEventHandler(sender, e, DataGridViewMouseEvent.MouseDoubleClick); } private void EditingControls_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { - Debug.Assert(sender == this.editingControl || sender == this.editingPanel); + Debug.Assert(sender == editingControl || sender == editingPanel); EditingControls_CommonMouseEventHandler(sender, e, DataGridViewMouseEvent.MouseDown); } private void EditingControls_MouseEnter(object sender, System.EventArgs e) { - Debug.Assert(sender == this.editingControl || sender == this.editingPanel); - if (sender == this.editingPanel) + Debug.Assert(sender == editingControl || sender == editingPanel); + if (sender == editingPanel) { - Debug.Assert(this.editingControl != null); - Debug.Assert(!this.dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet]); - this.dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet] = true; - this.oldCursor = this.Cursor; - this.CursorInternal = ((IDataGridViewEditingControl)this.editingControl).EditingPanelCursor; + Debug.Assert(editingControl != null); + Debug.Assert(!dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet]); + dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet] = true; + oldCursor = Cursor; + CursorInternal = ((IDataGridViewEditingControl)editingControl).EditingPanelCursor; } - if (this.dataGridViewState2[DATAGRIDVIEWSTATE2_mouseEnterExpected]) + if (dataGridViewState2[DATAGRIDVIEWSTATE2_mouseEnterExpected]) { OnMouseEnter(EventArgs.Empty); } @@ -5977,21 +5977,21 @@ private void EditingControls_MouseEnter(object sender, System.EventArgs e) private void EditingControls_MouseLeave(object sender, System.EventArgs e) { - Debug.Assert(sender == this.editingControl || sender == this.editingPanel); - if (sender == this.editingPanel) + Debug.Assert(sender == editingControl || sender == editingPanel); + if (sender == editingPanel) { - Debug.Assert(this.editingControl != null); - if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet]) + Debug.Assert(editingControl != null); + if (dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet]) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet] = false; - this.CursorInternal = this.oldCursor; + dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet] = false; + CursorInternal = oldCursor; } } UpdateMouseEnteredCell(null /*HitTestInfo*/, null /*MouseEventArgs*/); Point ptMouse = PointToClient(Control.MousePosition); - if (!this.ClientRectangle.Contains(ptMouse)) + if (!ClientRectangle.Contains(ptMouse)) { OnMouseLeave(EventArgs.Empty); } @@ -5999,13 +5999,13 @@ private void EditingControls_MouseLeave(object sender, System.EventArgs e) private void EditingControls_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { - Debug.Assert(sender == this.editingControl || sender == this.editingPanel); + Debug.Assert(sender == editingControl || sender == editingPanel); EditingControls_CommonMouseEventHandler(sender, e, DataGridViewMouseEvent.MouseMove); } private void EditingControls_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { - Debug.Assert(sender == this.editingControl || sender == this.editingPanel); + Debug.Assert(sender == editingControl || sender == editingPanel); EditingControls_CommonMouseEventHandler(sender, e, DataGridViewMouseEvent.MouseUp); } @@ -6013,17 +6013,17 @@ private void EndColumnHeadersResize(MouseEventArgs e) { try { - if (this.currentRowSplitBar != -1) + if (currentRowSplitBar != -1) { - Invalidate(CalcRowResizeFeedbackRect(this.currentRowSplitBar), true); - this.lastRowSplitBar = this.currentRowSplitBar = -1; + Invalidate(CalcRowResizeFeedbackRect(currentRowSplitBar), true); + lastRowSplitBar = currentRowSplitBar = -1; } - int y = Math.Min(e.Y + this.mouseBarOffset, this.layout.Data.Bottom - 1); - int delta = y - this.layout.ColumnHeaders.Y - this.ColumnHeadersHeight + 1; - if (this.trackRowAnchor != y && delta != 0) + int y = Math.Min(e.Y + mouseBarOffset, layout.Data.Bottom - 1); + int delta = y - layout.ColumnHeaders.Y - ColumnHeadersHeight + 1; + if (trackRowAnchor != y && delta != 0) { - this.ColumnHeadersHeight += delta; + ColumnHeadersHeight += delta; } } finally @@ -6036,12 +6036,12 @@ private void EndColumnRelocation(MouseEventArgs e, HitTestInfo hti) { try { - if (this.lastHeaderShadow != -1) + if (lastHeaderShadow != -1) { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_showColumnRelocationInsertion] = false; - this.trackColumnEdge = -1; - this.lastHeaderShadow = -1; - Invalidate(Rectangle.Union(this.layout.TopLeftHeader, this.layout.ColumnHeaders)); + dataGridViewState2[DATAGRIDVIEWSTATE2_showColumnRelocationInsertion] = false; + trackColumnEdge = -1; + lastHeaderShadow = -1; + Invalidate(Rectangle.Union(layout.TopLeftHeader, layout.ColumnHeaders)); } int previousColumnIndex; @@ -6049,15 +6049,15 @@ private void EndColumnRelocation(MouseEventArgs e, HitTestInfo hti) { if (previousColumnIndex == -1) { - this.Columns[this.trackColumn].DisplayIndex = 0; + Columns[trackColumn].DisplayIndex = 0; } - else if (this.Columns[this.trackColumn].DisplayIndex > this.Columns[previousColumnIndex].DisplayIndex) + else if (Columns[trackColumn].DisplayIndex > Columns[previousColumnIndex].DisplayIndex) { - this.Columns[this.trackColumn].DisplayIndex = this.Columns[previousColumnIndex].DisplayIndex + 1; + Columns[trackColumn].DisplayIndex = Columns[previousColumnIndex].DisplayIndex + 1; } else { - this.Columns[this.trackColumn].DisplayIndex = this.Columns[previousColumnIndex].DisplayIndex; + Columns[trackColumn].DisplayIndex = Columns[previousColumnIndex].DisplayIndex; } } } @@ -6082,23 +6082,23 @@ private void EndColumnResize(MouseEventArgs e) private void EndColumnResize(int x) { int newX, delta; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - newX = Math.Max(x + this.mouseBarOffset, this.layout.Data.X); - delta = GetColumnXFromIndex(this.trackColumn) - this.Columns[this.trackColumn].Thickness - newX + 1; + newX = Math.Max(x + mouseBarOffset, layout.Data.X); + delta = GetColumnXFromIndex(trackColumn) - Columns[trackColumn].Thickness - newX + 1; } else { - newX = Math.Min(x + this.mouseBarOffset, this.layout.Data.Right - 1); - delta = newX - (GetColumnXFromIndex(this.trackColumn) + this.Columns[this.trackColumn].Thickness) + 1; + newX = Math.Min(x + mouseBarOffset, layout.Data.Right - 1); + delta = newX - (GetColumnXFromIndex(trackColumn) + Columns[trackColumn].Thickness) + 1; } - if (this.trackColAnchor != newX && delta != 0) + if (trackColAnchor != newX && delta != 0) { - int proposed = this.Columns[this.trackColumn].Thickness + delta; - Debug.Assert(proposed >= this.Columns[this.trackColumn].MinimumThickness); + int proposed = Columns[trackColumn].Thickness + delta; + Debug.Assert(proposed >= Columns[trackColumn].MinimumThickness); Debug.Assert(proposed <= DataGridViewBand.MaxBandThickness); - this.Columns[this.trackColumn].Thickness = proposed; + Columns[trackColumn].Thickness = proposed; } } @@ -6109,7 +6109,7 @@ public bool EndEdit() public bool EndEdit(DataGridViewDataErrorContexts context) { - if (this.EditMode == DataGridViewEditMode.EditOnEnter) + if (EditMode == DataGridViewEditMode.EditOnEnter) { return CommitEdit(context); } @@ -6139,17 +6139,17 @@ private bool EndEdit(DataGridViewDataErrorContexts context, bool resetCurrentCell, bool resetAnchorCell) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { return true; } - this.dataGridViewOper[DATAGRIDVIEWOPER_inEndEdit] = true; + dataGridViewOper[DATAGRIDVIEWOPER_inEndEdit] = true; try { - int curRowIndex = this.ptCurrentCell.Y; - int curColIndex = this.ptCurrentCell.X; - DataGridViewCell dataGridViewCurrentCell = this.CurrentCellInternal; + int curRowIndex = ptCurrentCell.Y; + int curColIndex = ptCurrentCell.X; + DataGridViewCell dataGridViewCurrentCell = CurrentCellInternal; DataGridViewDataErrorEventArgs dgvdee = CommitEdit(ref dataGridViewCurrentCell, context, validateCell, fireCellLeave, fireCellEnter, fireRowLeave, fireRowEnter, fireLeave); if (dgvdee != null) @@ -6176,38 +6176,38 @@ private bool EndEdit(DataGridViewDataErrorContexts context, } } - if (!this.IsCurrentCellInEditMode) + if (!IsCurrentCellInEditMode) { return true; } - if (curRowIndex != this.ptCurrentCell.Y || curColIndex != this.ptCurrentCell.X) + if (curRowIndex != ptCurrentCell.Y || curColIndex != ptCurrentCell.X) { return true; } - if (this.editingControl != null) + if (editingControl != null) { UnwireEditingControlEvents(); - this.dataGridViewState2[DATAGRIDVIEWSTATE2_mouseOverRemovedEditingCtrl] = this.MouseOverEditingControl; - this.dataGridViewState2[DATAGRIDVIEWSTATE2_mouseOverRemovedEditingPanel] = this.MouseOverEditingPanel; - this.dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlChanging] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_mouseOverRemovedEditingCtrl] = MouseOverEditingControl; + dataGridViewState2[DATAGRIDVIEWSTATE2_mouseOverRemovedEditingPanel] = MouseOverEditingPanel; + dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlChanging] = true; try { dataGridViewCurrentCell.DetachEditingControl(); } finally { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlChanging] = false; + dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlChanging] = false; } - ImeMode editingControlImeMode = this.editingControl.CachedImeMode; // If in restricted mode, ImeMode will be Disable. - this.latestEditingControl = this.editingControl; - Debug.Assert(this.editingPanel == null || this.editingPanel.Controls.Count == 0); - this.editingControl = null; - InvalidateCellPrivate(this.ptCurrentCell.X, this.ptCurrentCell.Y); + ImeMode editingControlImeMode = editingControl.CachedImeMode; // If in restricted mode, ImeMode will be Disable. + latestEditingControl = editingControl; + Debug.Assert(editingPanel == null || editingPanel.Controls.Count == 0); + editingControl = null; + InvalidateCellPrivate(ptCurrentCell.X, ptCurrentCell.Y); - if (this.EditMode == DataGridViewEditMode.EditOnEnter) + if (EditMode == DataGridViewEditMode.EditOnEnter) { if (resetCurrentCell) { @@ -6220,13 +6220,13 @@ private bool EndEdit(DataGridViewDataErrorContexts context, // Debug.Assert(this.CanFocus || this.Focused); // Invalid assertion Focus(); } - this.ImeMode = editingControlImeMode; + ImeMode = editingControlImeMode; } else { - Debug.Assert(this.dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode]); - this.dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode] = false; - InvalidateCellPrivate(this.ptCurrentCell.X, this.ptCurrentCell.Y); + Debug.Assert(dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode]); + dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode] = false; + InvalidateCellPrivate(ptCurrentCell.X, ptCurrentCell.Y); } if (!IsInnerCellOutOfBounds(curColIndex, curRowIndex)) @@ -6239,7 +6239,7 @@ private bool EndEdit(DataGridViewDataErrorContexts context, } finally { - this.dataGridViewOper[DATAGRIDVIEWOPER_inEndEdit] = false; + dataGridViewOper[DATAGRIDVIEWOPER_inEndEdit] = false; } } @@ -6247,26 +6247,26 @@ private void EndRowHeadersResize(MouseEventArgs e) { try { - if (this.currentColSplitBar != -1) + if (currentColSplitBar != -1) { - Invalidate(CalcColResizeFeedbackRect(this.currentColSplitBar), true); - this.lastColSplitBar = this.currentColSplitBar = -1; + Invalidate(CalcColResizeFeedbackRect(currentColSplitBar), true); + lastColSplitBar = currentColSplitBar = -1; } int x, delta; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - x = Math.Max(e.X + this.mouseBarOffset, this.layout.Data.Left - 1); - delta = this.layout.RowHeaders.Right - this.RowHeadersWidth - x - 1; + x = Math.Max(e.X + mouseBarOffset, layout.Data.Left - 1); + delta = layout.RowHeaders.Right - RowHeadersWidth - x - 1; } else { - x = Math.Min(e.X + this.mouseBarOffset, this.layout.Data.Right - 1); - delta = x - this.layout.RowHeaders.X - this.RowHeadersWidth + 1; + x = Math.Min(e.X + mouseBarOffset, layout.Data.Right - 1); + delta = x - layout.RowHeaders.X - RowHeadersWidth + 1; } - if (this.trackColAnchor != x && delta != 0) + if (trackColAnchor != x && delta != 0) { - this.RowHeadersWidth += delta; + RowHeadersWidth += delta; } } finally @@ -6279,28 +6279,28 @@ private void EndRowResize(MouseEventArgs e) { try { - if (this.currentRowSplitBar != -1) + if (currentRowSplitBar != -1) { - Invalidate(CalcRowResizeFeedbackRect(this.currentRowSplitBar), true); - this.lastRowSplitBar = this.currentRowSplitBar = -1; + Invalidate(CalcRowResizeFeedbackRect(currentRowSplitBar), true); + lastRowSplitBar = currentRowSplitBar = -1; } - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(this.trackRow); + DataGridViewRow dataGridViewRow = Rows.SharedRow(trackRow); int height, minimumHeight; - dataGridViewRow.GetHeightInfo(this.trackRow, out height, out minimumHeight); - int y = Math.Min(e.Y + this.mouseBarOffset, this.layout.Data.Bottom - 1); - int delta = y - (GetRowYFromIndex(this.trackRow) + height) + 1; - if (this.trackRowAnchor != y && delta != 0) + dataGridViewRow.GetHeightInfo(trackRow, out height, out minimumHeight); + int y = Math.Min(e.Y + mouseBarOffset, layout.Data.Bottom - 1); + int delta = y - (GetRowYFromIndex(trackRow) + height) + 1; + if (trackRowAnchor != y && delta != 0) { int proposedHeight = height + delta; proposedHeight = Math.Max(proposedHeight, minimumHeight); - if (!OnRowHeightInfoPushed(this.trackRow, proposedHeight, minimumHeight)) + if (!OnRowHeightInfoPushed(trackRow, proposedHeight, minimumHeight)) { if (dataGridViewRow.Index == -1) { - dataGridViewRow = this.Rows[this.trackRow]; // Unsharing row + dataGridViewRow = Rows[trackRow]; // Unsharing row } - Debug.Assert(this.autoSizeRowsMode == DataGridViewAutoSizeRowsMode.None); + Debug.Assert(autoSizeRowsMode == DataGridViewAutoSizeRowsMode.None); dataGridViewRow.ThicknessInternal = proposedHeight; } } @@ -6313,10 +6313,10 @@ private void EndRowResize(MouseEventArgs e) private void ExitBulkLayout(bool invalidInAdjustFillingColumns) { - if (this.inBulkLayoutCount > 0) + if (inBulkLayoutCount > 0) { - this.inBulkLayoutCount--; - if (this.inBulkLayoutCount == 0) + inBulkLayoutCount--; + if (inBulkLayoutCount == 0) { PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, invalidInAdjustFillingColumns, false /*repositionEditingControl*/); } @@ -6325,10 +6325,10 @@ private void ExitBulkLayout(bool invalidInAdjustFillingColumns) private void ExitBulkPaint(int columnIndex, int rowIndex) { - if (this.inBulkPaintCount > 0) + if (inBulkPaintCount > 0) { - this.inBulkPaintCount--; - if (this.inBulkPaintCount == 0) + inBulkPaintCount--; + if (inBulkPaintCount == 0) { if (columnIndex >= 0) { @@ -6349,30 +6349,30 @@ private void ExitBulkPaint(int columnIndex, int rowIndex) private void FirstVisibleScrollingRowTempted(int rowIndex) { Debug.Assert(rowIndex >= 0); - Debug.Assert(rowIndex < this.Rows.Count); - Debug.Assert((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Visible) != 0); - Debug.Assert((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Frozen) == 0); + Debug.Assert(rowIndex < Rows.Count); + Debug.Assert((Rows.GetRowState(rowIndex) & DataGridViewElementStates.Visible) != 0); + Debug.Assert((Rows.GetRowState(rowIndex) & DataGridViewElementStates.Frozen) == 0); - int displayHeight = this.layout.Data.Height; + int displayHeight = layout.Data.Height; if (displayHeight <= 0) { return; } - int totalVisibleFrozenHeight = this.Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int totalVisibleFrozenHeight = Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); if (totalVisibleFrozenHeight < displayHeight) { - this.displayedBandsInfo.FirstDisplayedScrollingRow = rowIndex; + displayedBandsInfo.FirstDisplayedScrollingRow = rowIndex; } } private void FlushDisplayedChanged() { - if (this.displayedBandsInfo.Dirty && this.Visible) + if (displayedBandsInfo.Dirty && Visible) { // Handle the rows - if (!this.RowHeadersVisible && this.Columns.GetColumnCount(DataGridViewElementStates.Visible) == 0) + if (!RowHeadersVisible && Columns.GetColumnCount(DataGridViewElementStates.Visible) == 0) { // All rows are hidden UpdateRowsDisplayedState(false /*displayed*/); @@ -6383,31 +6383,31 @@ private void FlushDisplayedChanged() int maxDisplayedRows = (int)(rectScreen.Height / DataGridViewBand.MinBandThickness); // Make sure all displayed scrolling rows have the Displayed state. - int rowIndexTmp = this.displayedBandsInfo.FirstDisplayedScrollingRow; + int rowIndexTmp = displayedBandsInfo.FirstDisplayedScrollingRow; if (rowIndexTmp != -1) { - int numDisplayedScrollingRows = this.displayedBandsInfo.NumDisplayedScrollingRows; + int numDisplayedScrollingRows = displayedBandsInfo.NumDisplayedScrollingRows; Debug.Assert(numDisplayedScrollingRows > 0); while (numDisplayedScrollingRows > 0) { Debug.Assert(rowIndexTmp != -1); - if ((this.Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) == 0) + if ((Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) == 0) { - this.Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, true); + Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, true); } - rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible); + rowIndexTmp = Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible); numDisplayedScrollingRows--; } int rowIndexTmp2 = rowIndexTmp; // Make sure all scrolling rows before FirstDisplayedScrollingRow have their Displayed state set to false - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow != -1); - rowIndexTmp = this.Rows.GetPreviousRow(this.displayedBandsInfo.FirstDisplayedScrollingRow, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); - while (rowIndexTmp != -1 && (this.Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) != 0) + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingRow != -1); + rowIndexTmp = Rows.GetPreviousRow(displayedBandsInfo.FirstDisplayedScrollingRow, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); + while (rowIndexTmp != -1 && (Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) != 0) { - this.Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, false); - rowIndexTmp = this.Rows.GetPreviousRow(rowIndexTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); + Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, false); + rowIndexTmp = Rows.GetPreviousRow(rowIndexTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); } // Make sure all rows below last displayed scrolling row have Displayed state set to false (next loop) @@ -6416,46 +6416,46 @@ private void FlushDisplayedChanged() else { // No displayed scrolling rows. Make sure all non-frozen rows have their Displayed state set to false (next loop) - rowIndexTmp = this.Rows.GetFirstRow(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); + rowIndexTmp = Rows.GetFirstRow(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); } - while (rowIndexTmp != -1 && (this.Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) != 0) + while (rowIndexTmp != -1 && (Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) != 0) { - this.Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, false); - rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible); + Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, false); + rowIndexTmp = Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible); } // Make sure all displayed frozen rows have their Displayed state set to true - int numDisplayedFrozenRows = this.displayedBandsInfo.NumDisplayedFrozenRows; - rowIndexTmp = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int numDisplayedFrozenRows = displayedBandsInfo.NumDisplayedFrozenRows; + rowIndexTmp = Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); while (numDisplayedFrozenRows > 0) { Debug.Assert(rowIndexTmp != -1); - if ((this.Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) == 0) + if ((Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) == 0) { - this.Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, true); + Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, true); } - rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + rowIndexTmp = Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); numDisplayedFrozenRows--; } // Make sure all non-displayed frozen rows have their Displayed state set to false - while (rowIndexTmp != -1 && (this.Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) != 0) + while (rowIndexTmp != -1 && (Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) != 0) { - this.Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, false); - rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, false); + rowIndexTmp = Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); } // Treat the cases where the old displayed rows are completely disjoint from the new displayed rows int lastDisplayedFrozenRowIndex = -1; int lastDisplayedScrollingRowIndex = -1; - if (this.displayedBandsInfo.NumDisplayedFrozenRows > 0) + if (displayedBandsInfo.NumDisplayedFrozenRows > 0) { - int firstDisplayedFrozenRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int firstDisplayedFrozenRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); Debug.Assert(firstDisplayedFrozenRowIndex != -1); - if (this.displayedBandsInfo.NumDisplayedFrozenRows > 1) + if (displayedBandsInfo.NumDisplayedFrozenRows > 1) { - lastDisplayedFrozenRowIndex = this.Rows.GetNextRow(firstDisplayedFrozenRowIndex, DataGridViewElementStates.Visible, this.displayedBandsInfo.NumDisplayedFrozenRows - 2 /*skipRows*/); + lastDisplayedFrozenRowIndex = Rows.GetNextRow(firstDisplayedFrozenRowIndex, DataGridViewElementStates.Visible, displayedBandsInfo.NumDisplayedFrozenRows - 2 /*skipRows*/); } else { @@ -6463,107 +6463,107 @@ private void FlushDisplayedChanged() } } - if (this.displayedBandsInfo.FirstDisplayedScrollingRow != -1) + if (displayedBandsInfo.FirstDisplayedScrollingRow != -1) { - if (this.displayedBandsInfo.NumDisplayedScrollingRows > 1) + if (displayedBandsInfo.NumDisplayedScrollingRows > 1) { - lastDisplayedScrollingRowIndex = this.Rows.GetNextRow(this.displayedBandsInfo.FirstDisplayedScrollingRow, DataGridViewElementStates.Visible, this.displayedBandsInfo.NumDisplayedScrollingRows - 2 /*skipRows*/); + lastDisplayedScrollingRowIndex = Rows.GetNextRow(displayedBandsInfo.FirstDisplayedScrollingRow, DataGridViewElementStates.Visible, displayedBandsInfo.NumDisplayedScrollingRows - 2 /*skipRows*/); } else { - lastDisplayedScrollingRowIndex = this.displayedBandsInfo.FirstDisplayedScrollingRow; + lastDisplayedScrollingRowIndex = displayedBandsInfo.FirstDisplayedScrollingRow; } } - rowIndexTmp = this.displayedBandsInfo.OldFirstDisplayedScrollingRow; + rowIndexTmp = displayedBandsInfo.OldFirstDisplayedScrollingRow; while (rowIndexTmp != -1 && - rowIndexTmp < this.displayedBandsInfo.FirstDisplayedScrollingRow && + rowIndexTmp < displayedBandsInfo.FirstDisplayedScrollingRow && !RowNeedsDisplayedState(rowIndexTmp, lastDisplayedFrozenRowIndex, lastDisplayedScrollingRowIndex)) { - if ((this.Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) == 0) + if ((Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) == 0) { break; } else { - this.Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, false); - rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible); + Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, false); + rowIndexTmp = Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible); } } - rowIndexTmp = this.displayedBandsInfo.OldFirstDisplayedScrollingRow; + rowIndexTmp = displayedBandsInfo.OldFirstDisplayedScrollingRow; if (rowIndexTmp != -1 && - rowIndexTmp < this.Rows.Count && - (this.displayedBandsInfo.FirstDisplayedScrollingRow == -1 || this.displayedBandsInfo.FirstDisplayedScrollingRow < rowIndexTmp) && + rowIndexTmp < Rows.Count && + (displayedBandsInfo.FirstDisplayedScrollingRow == -1 || displayedBandsInfo.FirstDisplayedScrollingRow < rowIndexTmp) && !RowNeedsDisplayedState(rowIndexTmp, lastDisplayedFrozenRowIndex, lastDisplayedScrollingRowIndex)) { while (rowIndexTmp != -1) { - if ((this.Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) == 0) + if ((Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) == 0) { break; } else { - this.Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, false); - rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible); + Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, false); + rowIndexTmp = Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible); } } } - if (this.displayedBandsInfo.RowInsertionOccurred) + if (displayedBandsInfo.RowInsertionOccurred) { // Adjust the scrolling rows that were pushed down by the rows insertion - rowIndexTmp = this.displayedBandsInfo.OldFirstDisplayedScrollingRow; + rowIndexTmp = displayedBandsInfo.OldFirstDisplayedScrollingRow; if (rowIndexTmp != -1) { - rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible, this.displayedBandsInfo.OldNumDisplayedScrollingRows - 1); + rowIndexTmp = Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible, displayedBandsInfo.OldNumDisplayedScrollingRows - 1); if (rowIndexTmp == -1) { - rowIndexTmp = this.Rows.GetLastRow(DataGridViewElementStates.Visible); + rowIndexTmp = Rows.GetLastRow(DataGridViewElementStates.Visible); } int rowCount = 0; while (rowIndexTmp != -1 && rowCount <= maxDisplayedRows && !RowNeedsDisplayedState(rowIndexTmp, lastDisplayedFrozenRowIndex, lastDisplayedScrollingRowIndex)) { - if ((this.Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) != 0) + if ((Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) != 0) { - this.Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, false); + Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, false); } - rowIndexTmp = this.Rows.GetPreviousRow(rowIndexTmp, DataGridViewElementStates.Visible); + rowIndexTmp = Rows.GetPreviousRow(rowIndexTmp, DataGridViewElementStates.Visible); rowCount++; } } // Adjust the frozen rows that were pushed down by the rows insertion - rowIndexTmp = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + rowIndexTmp = Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); if (rowIndexTmp != -1) { - rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen, this.displayedBandsInfo.OldNumDisplayedFrozenRows - 1); + rowIndexTmp = Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen, displayedBandsInfo.OldNumDisplayedFrozenRows - 1); if (rowIndexTmp == -1) { - rowIndexTmp = this.Rows.GetLastRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + rowIndexTmp = Rows.GetLastRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); } int rowCount = 0; while (rowIndexTmp != -1 && rowCount <= maxDisplayedRows && !RowNeedsDisplayedState(rowIndexTmp, lastDisplayedFrozenRowIndex, lastDisplayedScrollingRowIndex)) { - if ((this.Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) != 0) + if ((Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) != 0) { - this.Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, false); + Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, false); } - rowIndexTmp = this.Rows.GetPreviousRow(rowIndexTmp, DataGridViewElementStates.Visible); + rowIndexTmp = Rows.GetPreviousRow(rowIndexTmp, DataGridViewElementStates.Visible); rowCount++; } } } #if DEBUG - for (rowIndexTmp = 0; rowIndexTmp < this.Rows.Count; rowIndexTmp++) + for (rowIndexTmp = 0; rowIndexTmp < Rows.Count; rowIndexTmp++) { - DataGridViewElementStates rowStateDbg = this.Rows.GetRowState(rowIndexTmp); + DataGridViewElementStates rowStateDbg = Rows.GetRowState(rowIndexTmp); bool rowNeedsDisplayedState = RowNeedsDisplayedState(rowIndexTmp, lastDisplayedFrozenRowIndex, lastDisplayedScrollingRowIndex); if (((rowStateDbg & DataGridViewElementStates.Displayed) != 0) != rowNeedsDisplayedState) { @@ -6575,7 +6575,7 @@ private void FlushDisplayedChanged() // Handle the columns - if (!this.ColumnHeadersVisible && this.Rows.GetRowCount(DataGridViewElementStates.Visible) == 0) + if (!ColumnHeadersVisible && Rows.GetRowCount(DataGridViewElementStates.Visible) == 0) { // All columns are hidden UpdateColumnsDisplayedState(false /*displayed*/); @@ -6584,12 +6584,12 @@ private void FlushDisplayedChanged() { // Make sure all displayed scrolling columns have the Displayed state. DataGridViewColumn dataGridViewColumnTmp; - int columnIndexTmp = this.displayedBandsInfo.FirstDisplayedScrollingCol; + int columnIndexTmp = displayedBandsInfo.FirstDisplayedScrollingCol; if (columnIndexTmp != -1) { - int numDisplayedScrollingCols = this.displayedBandsInfo.NumDisplayedScrollingCols; + int numDisplayedScrollingCols = displayedBandsInfo.NumDisplayedScrollingCols; Debug.Assert(numDisplayedScrollingCols > 0); - dataGridViewColumnTmp = this.Columns[columnIndexTmp]; + dataGridViewColumnTmp = Columns[columnIndexTmp]; while (numDisplayedScrollingCols > 0) { Debug.Assert(dataGridViewColumnTmp != null); @@ -6597,19 +6597,19 @@ private void FlushDisplayedChanged() { dataGridViewColumnTmp.DisplayedInternal = true; } - dataGridViewColumnTmp = this.Columns.GetNextColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.None); + dataGridViewColumnTmp = Columns.GetNextColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.None); numDisplayedScrollingCols--; } DataGridViewColumn dataGridViewColumnTmp2 = dataGridViewColumnTmp; // Make sure all scrolling columns before FirstDisplayedScrollingCol have their Displayed state set to false - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingCol != -1); - dataGridViewColumnTmp = this.Columns.GetPreviousColumn(this.Columns[this.displayedBandsInfo.FirstDisplayedScrollingCol], DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingCol != -1); + dataGridViewColumnTmp = Columns.GetPreviousColumn(Columns[displayedBandsInfo.FirstDisplayedScrollingCol], DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); while (dataGridViewColumnTmp != null && dataGridViewColumnTmp.Displayed) { dataGridViewColumnTmp.DisplayedInternal = false; - dataGridViewColumnTmp = this.Columns.GetPreviousColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); + dataGridViewColumnTmp = Columns.GetPreviousColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); } // Make sure all columns after last displayed scrolling column have Displayed state set to false (next loop) @@ -6618,17 +6618,17 @@ private void FlushDisplayedChanged() else { // No displayed scrolling columns. Make sure all non-frozen columns have their Displayed state set to false (next loop) - dataGridViewColumnTmp = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); + dataGridViewColumnTmp = Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); } while (dataGridViewColumnTmp != null && dataGridViewColumnTmp.Displayed) { dataGridViewColumnTmp.DisplayedInternal = false; - dataGridViewColumnTmp = this.Columns.GetNextColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.None); + dataGridViewColumnTmp = Columns.GetNextColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.None); } // Make sure all displayed frozen columns have their Displayed state set to true - int numDisplayedFrozenCols = this.displayedBandsInfo.NumDisplayedFrozenCols; - dataGridViewColumnTmp = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int numDisplayedFrozenCols = displayedBandsInfo.NumDisplayedFrozenCols; + dataGridViewColumnTmp = Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); while (numDisplayedFrozenCols > 0) { Debug.Assert(dataGridViewColumnTmp != null); @@ -6636,7 +6636,7 @@ private void FlushDisplayedChanged() { dataGridViewColumnTmp.DisplayedInternal = true; } - dataGridViewColumnTmp = this.Columns.GetNextColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen, DataGridViewElementStates.None); + dataGridViewColumnTmp = Columns.GetNextColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen, DataGridViewElementStates.None); numDisplayedFrozenCols--; } @@ -6644,20 +6644,20 @@ private void FlushDisplayedChanged() while (dataGridViewColumnTmp != null && dataGridViewColumnTmp.Displayed) { dataGridViewColumnTmp.DisplayedInternal = false; - dataGridViewColumnTmp = this.Columns.GetNextColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen, DataGridViewElementStates.None); + dataGridViewColumnTmp = Columns.GetNextColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen, DataGridViewElementStates.None); } // Treat the cases where the old displayed columns are completely disjoint from the new displayed columns - columnIndexTmp = this.displayedBandsInfo.OldFirstDisplayedScrollingCol; + columnIndexTmp = displayedBandsInfo.OldFirstDisplayedScrollingCol; while (columnIndexTmp != -1 && - columnIndexTmp < this.Columns.Count && - this.displayedBandsInfo.FirstDisplayedScrollingCol != -1 && - columnIndexTmp != this.displayedBandsInfo.FirstDisplayedScrollingCol && - this.Columns.DisplayInOrder(columnIndexTmp, this.displayedBandsInfo.FirstDisplayedScrollingCol) && - !ColumnNeedsDisplayedState(this.Columns[columnIndexTmp])) + columnIndexTmp < Columns.Count && + displayedBandsInfo.FirstDisplayedScrollingCol != -1 && + columnIndexTmp != displayedBandsInfo.FirstDisplayedScrollingCol && + Columns.DisplayInOrder(columnIndexTmp, displayedBandsInfo.FirstDisplayedScrollingCol) && + !ColumnNeedsDisplayedState(Columns[columnIndexTmp])) { - dataGridViewColumnTmp = this.Columns[columnIndexTmp]; + dataGridViewColumnTmp = Columns[columnIndexTmp]; if (!dataGridViewColumnTmp.Displayed) { break; @@ -6665,18 +6665,18 @@ private void FlushDisplayedChanged() else { dataGridViewColumnTmp.DisplayedInternal = false; - dataGridViewColumnTmp = this.Columns.GetNextColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.None); + dataGridViewColumnTmp = Columns.GetNextColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.None); columnIndexTmp = (dataGridViewColumnTmp == null) ? -1 : dataGridViewColumnTmp.Index; } } - columnIndexTmp = this.displayedBandsInfo.OldFirstDisplayedScrollingCol; + columnIndexTmp = displayedBandsInfo.OldFirstDisplayedScrollingCol; if (columnIndexTmp != -1 && - columnIndexTmp < this.Columns.Count && - (this.displayedBandsInfo.FirstDisplayedScrollingCol == -1 || (this.displayedBandsInfo.FirstDisplayedScrollingCol != columnIndexTmp && this.Columns.DisplayInOrder(this.displayedBandsInfo.FirstDisplayedScrollingCol, columnIndexTmp))) && - !ColumnNeedsDisplayedState(this.Columns[columnIndexTmp])) + columnIndexTmp < Columns.Count && + (displayedBandsInfo.FirstDisplayedScrollingCol == -1 || (displayedBandsInfo.FirstDisplayedScrollingCol != columnIndexTmp && Columns.DisplayInOrder(displayedBandsInfo.FirstDisplayedScrollingCol, columnIndexTmp))) && + !ColumnNeedsDisplayedState(Columns[columnIndexTmp])) { - dataGridViewColumnTmp = this.Columns[columnIndexTmp]; + dataGridViewColumnTmp = Columns[columnIndexTmp]; while (dataGridViewColumnTmp != null) { if (!dataGridViewColumnTmp.Displayed) @@ -6686,29 +6686,29 @@ private void FlushDisplayedChanged() else { dataGridViewColumnTmp.DisplayedInternal = false; - dataGridViewColumnTmp = this.Columns.GetNextColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.None); + dataGridViewColumnTmp = Columns.GetNextColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.None); } } } - if (this.displayedBandsInfo.ColumnInsertionOccurred) + if (displayedBandsInfo.ColumnInsertionOccurred) { - dataGridViewColumnTmp = this.Columns[this.Columns.Count - 1]; + dataGridViewColumnTmp = Columns[Columns.Count - 1]; while (dataGridViewColumnTmp != null && !ColumnNeedsDisplayedState(dataGridViewColumnTmp)) { if (dataGridViewColumnTmp.Displayed) { dataGridViewColumnTmp.DisplayedInternal = false; } - dataGridViewColumnTmp = this.Columns.GetPreviousColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.None); + dataGridViewColumnTmp = Columns.GetPreviousColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.None); } } #if DEBUG - for (columnIndexTmp = 0; columnIndexTmp < this.Columns.Count; columnIndexTmp++) + for (columnIndexTmp = 0; columnIndexTmp < Columns.Count; columnIndexTmp++) { - DataGridViewElementStates colStateDbg = this.Columns[columnIndexTmp].State; - bool columnNeedsDisplayedState = ColumnNeedsDisplayedState(this.Columns[columnIndexTmp]); + DataGridViewElementStates colStateDbg = Columns[columnIndexTmp].State; + bool columnNeedsDisplayedState = ColumnNeedsDisplayedState(Columns[columnIndexTmp]); if (((colStateDbg & DataGridViewElementStates.Displayed) != 0) != columnNeedsDisplayedState) { Debug.Fail("Unexpected Displayed state for column"); @@ -6717,13 +6717,13 @@ private void FlushDisplayedChanged() #endif } - this.displayedBandsInfo.Dirty = false; + displayedBandsInfo.Dirty = false; } } private void FlushDisplayIndexChanged(bool raiseEvent) { - foreach (DataGridViewColumn dataGridViewColumn in this.Columns) + foreach (DataGridViewColumn dataGridViewColumn in Columns) { if (dataGridViewColumn.DisplayIndexHasChanged) { @@ -6738,7 +6738,7 @@ private void FlushDisplayIndexChanged(bool raiseEvent) private void FlushSelectionChanged() { - if (this.dataGridViewState2[DATAGRIDVIEWSTATE2_raiseSelectionChanged]) + if (dataGridViewState2[DATAGRIDVIEWSTATE2_raiseSelectionChanged]) { OnSelectionChanged(EventArgs.Empty); } @@ -6748,18 +6748,18 @@ protected override AccessibleObject GetAccessibilityObjectById(int objectId) { // decrement the objectId because in our implementation of AccessibilityClient notitification objectId's are 1 - based. // 0 == NativeMethods.CHILDID_SELF corresponds to the AccessibleObject itself - return this.AccessibilityObject.GetChild(objectId - 1); + return AccessibilityObject.GetChild(objectId - 1); } internal SolidBrush GetCachedBrush(Color color) { - SolidBrush brush = (SolidBrush)this.brushes[color]; + SolidBrush brush = (SolidBrush)brushes[color]; if (brush == null) { brush = new SolidBrush(color); - this.brushes.Add(color, brush); + brushes.Add(color, brush); } return brush; } @@ -6781,11 +6781,11 @@ internal WindowsSolidBrush GetCachedWindowsBrush(Color color) internal Pen GetCachedPen(Color color) { - Pen pen = (Pen)this.pens[color]; + Pen pen = (Pen)pens[color]; if (pen == null) { pen = new Pen(color); - this.pens.Add(color, pen); + pens.Add(color, pen); } return pen; } @@ -6805,13 +6805,13 @@ internal WindowsPen GetCachedWindowsPen(Color color) internal TypeConverter GetCachedTypeConverter(Type type) { - if (this.converters.ContainsKey(type)) + if (converters.ContainsKey(type)) { - return (TypeConverter)this.converters[type]; + return (TypeConverter)converters[type]; } TypeConverter converter = TypeDescriptor.GetConverter(type); - this.converters.Add(type, converter); + converters.Add(type, converter); return converter; } @@ -6820,15 +6820,15 @@ internal Rectangle GetCellAdjustedDisplayRectangle(int columnIndex, int rowIndex Rectangle rect = GetCellDisplayRectangle(columnIndex, rowIndex, cutOverflow); if (!rect.IsEmpty) { - if (this.SingleVerticalBorderAdded && columnIndex == this.FirstDisplayedColumnIndex) + if (SingleVerticalBorderAdded && columnIndex == FirstDisplayedColumnIndex) { - if (!this.RightToLeftInternal) + if (!RightToLeftInternal) { rect.X--; } rect.Width++; } - if (this.SingleHorizontalBorderAdded && rowIndex == this.FirstDisplayedRowIndex) + if (SingleHorizontalBorderAdded && rowIndex == FirstDisplayedRowIndex) { rect.Y--; rect.Height++; @@ -6855,8 +6855,8 @@ public int GetCellCount(DataGridViewElementStates includeFilter) { if (includeFilter == DataGridViewElementStates.Selected) { - cellCount = this.individualSelectedCells.Count; - switch (this.SelectionMode) + cellCount = individualSelectedCells.Count; + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: { @@ -6867,12 +6867,12 @@ public int GetCellCount(DataGridViewElementStates includeFilter) case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: { - return cellCount + this.selectedBandIndexes.Count * this.Rows.Count; + return cellCount + selectedBandIndexes.Count * Rows.Count; } case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: { - return cellCount + this.selectedBandIndexes.Count * this.Columns.Count; + return cellCount + selectedBandIndexes.Count * Columns.Count; } } } @@ -6883,14 +6883,14 @@ public int GetCellCount(DataGridViewElementStates includeFilter) readOnlyRequired = (includeFilter & DataGridViewElementStates.ReadOnly) == DataGridViewElementStates.ReadOnly; visibleRequired = (includeFilter & DataGridViewElementStates.Visible) == DataGridViewElementStates.Visible; - foreach (DataGridViewCell dataGridViewCell in this.individualSelectedCells) + foreach (DataGridViewCell dataGridViewCell in individualSelectedCells) { if (GetCellCount_CellIncluded(dataGridViewCell, dataGridViewCell.RowIndex, displayedRequired, frozenRequired, resizableRequired, readOnlyRequired, visibleRequired)) { cellCount++; } } - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: { @@ -6901,10 +6901,10 @@ public int GetCellCount(DataGridViewElementStates includeFilter) case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: { - for (int rowIndex = 0; rowIndex < this.Rows.Count; rowIndex++) + for (int rowIndex = 0; rowIndex < Rows.Count; rowIndex++) { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); - foreach (int columnIndex in this.selectedBandIndexes) + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); + foreach (int columnIndex in selectedBandIndexes) { DataGridViewCell dataGridViewCell = dataGridViewRow.Cells[columnIndex]; if (GetCellCount_CellIncluded(dataGridViewCell, rowIndex, displayedRequired, frozenRequired, resizableRequired, readOnlyRequired, visibleRequired)) @@ -6918,9 +6918,9 @@ public int GetCellCount(DataGridViewElementStates includeFilter) case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: { - foreach (int rowIndex in this.selectedBandIndexes) + foreach (int rowIndex in selectedBandIndexes) { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); foreach (DataGridViewCell dataGridViewCell in dataGridViewRow.Cells) { if (GetCellCount_CellIncluded(dataGridViewCell, rowIndex, displayedRequired, frozenRequired, resizableRequired, readOnlyRequired, visibleRequired)) @@ -6934,10 +6934,10 @@ public int GetCellCount(DataGridViewElementStates includeFilter) } } - if ((includeFilter == DataGridViewElementStates.ReadOnly && this.ReadOnly) || + if ((includeFilter == DataGridViewElementStates.ReadOnly && ReadOnly) || includeFilter == DataGridViewElementStates.None) { - return this.Rows.Count * this.Columns.Count; + return Rows.Count * Columns.Count; } displayedRequired = (includeFilter & DataGridViewElementStates.Displayed) == DataGridViewElementStates.Displayed; @@ -6946,10 +6946,10 @@ public int GetCellCount(DataGridViewElementStates includeFilter) readOnlyRequired = (includeFilter & DataGridViewElementStates.ReadOnly) == DataGridViewElementStates.ReadOnly; visibleRequired = (includeFilter & DataGridViewElementStates.Visible) == DataGridViewElementStates.Visible; - for (int rowIndex = 0; rowIndex < this.Rows.Count; rowIndex++) + for (int rowIndex = 0; rowIndex < Rows.Count; rowIndex++) { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); - if (!visibleRequired || (this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Visible) != 0) + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); + if (!visibleRequired || (Rows.GetRowState(rowIndex) & DataGridViewElementStates.Visible) != 0) { foreach (DataGridViewCell dataGridViewCell in dataGridViewRow.Cells) { @@ -6973,7 +6973,7 @@ private bool GetCellCount_CellIncluded(DataGridViewCell dataGridViewCell, { Debug.Assert(dataGridViewCell != null); Debug.Assert(rowIndex >= 0); - DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); + DataGridViewElementStates rowState = Rows.GetRowState(rowIndex); if (displayedRequired) { bool cellDisplayed = (rowState & DataGridViewElementStates.Displayed) != 0 && @@ -7002,7 +7002,7 @@ private bool GetCellCount_CellIncluded(DataGridViewCell dataGridViewCell, } if (readOnlyRequired) { - bool cellReadOnly = this.ReadOnly || + bool cellReadOnly = ReadOnly || (rowState & DataGridViewElementStates.ReadOnly) != 0 || dataGridViewCell.OwningColumn.ReadOnly || dataGridViewCell.StateIncludes(DataGridViewElementStates.ReadOnly); @@ -7030,7 +7030,7 @@ public Rectangle GetCellDisplayRectangle(int columnIndex, int rowIndex, bool cut if (columnIndex >= 0) { - if (columnIndex >= this.Columns.Count) + if (columnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException(nameof(columnIndex)); } @@ -7044,17 +7044,17 @@ public Rectangle GetCellDisplayRectangle(int columnIndex, int rowIndex, bool cut } if (rowIndex >= 0) { - columnRect = this.layout.RowHeaders; + columnRect = layout.RowHeaders; } else { - columnRect = this.layout.TopLeftHeader; + columnRect = layout.TopLeftHeader; } } if (rowIndex >= 0) { - if (rowIndex >= this.Rows.Count) + if (rowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } @@ -7068,11 +7068,11 @@ public Rectangle GetCellDisplayRectangle(int columnIndex, int rowIndex, bool cut } if (columnIndex >= 0) { - rowRect = this.layout.ColumnHeaders; + rowRect = layout.ColumnHeaders; } else { - rowRect = this.layout.TopLeftHeader; + rowRect = layout.TopLeftHeader; } } @@ -7084,7 +7084,7 @@ public Rectangle GetCellDisplayRectangle(int columnIndex, int rowIndex, bool cut columnRect.Height += height; } int width; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { width = rowRect.X - columnRect.X; if (width > 0) @@ -7110,11 +7110,11 @@ public Rectangle GetCellDisplayRectangle(int columnIndex, int rowIndex, bool cut internal DataGridViewCell GetCellInternal(int columnIndex, int rowIndex) { - Debug.Assert(columnIndex >= -1 && columnIndex < this.Columns.Count); - Debug.Assert(rowIndex >= -1 && rowIndex < this.Rows.Count); + Debug.Assert(columnIndex >= -1 && columnIndex < Columns.Count); + Debug.Assert(rowIndex >= -1 && rowIndex < Rows.Count); if (rowIndex >= 0) { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); Debug.Assert(dataGridViewRow != null); if (columnIndex >= 0) { @@ -7129,11 +7129,11 @@ internal DataGridViewCell GetCellInternal(int columnIndex, int rowIndex) { if (columnIndex >= 0) { - return this.Columns[columnIndex].HeaderCell; + return Columns[columnIndex].HeaderCell; } else { - return this.TopLeftHeaderCell; + return TopLeftHeaderCell; } } } @@ -7143,12 +7143,12 @@ internal DataGridViewCell GetCellInternal(int columnIndex, int rowIndex) ] public virtual DataObject GetClipboardContent() { - if (this.ClipboardCopyMode == DataGridViewClipboardCopyMode.Disable) + if (ClipboardCopyMode == DataGridViewClipboardCopyMode.Disable) { throw new NotSupportedException(string.Format(SR.DataGridView_DisabledClipboardCopy)); } - if (this.CurrentCellIsEditedAndOnlySelectedCell) + if (CurrentCellIsEditedAndOnlySelectedCell) { return null; } @@ -7160,17 +7160,17 @@ public virtual DataObject GetClipboardContent() StringBuilder sbContent = null; DataGridViewColumn dataGridViewColumn, prevDataGridViewColumn, nextDataGridViewColumn; - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.FullRowSelect: - if (this.Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Selected) == 0) + if (Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Selected) == 0) { return null; } if (clipboardCopyMode == DataGridViewClipboardCopyMode.EnableWithAutoHeaderText) { - includeColumnHeaders = (this.Rows.GetFirstRow(DataGridViewElementStates.Visible, DataGridViewElementStates.Selected) == -1); + includeColumnHeaders = (Rows.GetFirstRow(DataGridViewElementStates.Visible, DataGridViewElementStates.Selected) == -1); includeRowHeaders = true; } else @@ -7178,8 +7178,8 @@ public virtual DataObject GetClipboardContent() includeColumnHeaders = includeRowHeaders = (clipboardCopyMode == DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText); } - includeColumnHeaders &= this.ColumnHeadersVisible; - includeRowHeaders &= this.RowHeadersVisible; + includeColumnHeaders &= ColumnHeadersVisible; + includeRowHeaders &= RowHeadersVisible; foreach (string format in formats) { @@ -7202,13 +7202,13 @@ public virtual DataObject GetClipboardContent() if (includeColumnHeaders) { - if (this.RightToLeftInternal) + if (RightToLeftInternal) { // Cycle through the visible columns in their reverse display order - dataGridViewColumn = this.Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.None); + dataGridViewColumn = Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.None); if (dataGridViewColumn != null) { - prevDataGridViewColumn = this.Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); + prevDataGridViewColumn = Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); cellContent = dataGridViewColumn.HeaderCell.GetClipboardContentInternal(-1, true /*firstCell*/, !includeRowHeaders && prevDataGridViewColumn == null /*lastCell*/, @@ -7222,7 +7222,7 @@ public virtual DataObject GetClipboardContent() while (prevDataGridViewColumn != null) { dataGridViewColumn = prevDataGridViewColumn; - prevDataGridViewColumn = this.Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); + prevDataGridViewColumn = Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); cellContent = dataGridViewColumn.HeaderCell.GetClipboardContentInternal(-1, false /*firstCell*/, !includeRowHeaders && prevDataGridViewColumn == null /*lastCell*/, @@ -7237,8 +7237,8 @@ public virtual DataObject GetClipboardContent() } if (includeRowHeaders) { - cellContent = this.TopLeftHeaderCell.GetClipboardContentInternal(-1, - this.Columns.GetColumnCount(DataGridViewElementStates.Visible) == 0 /*firstCell*/, + cellContent = TopLeftHeaderCell.GetClipboardContentInternal(-1, + Columns.GetColumnCount(DataGridViewElementStates.Visible) == 0 /*firstCell*/, true /*lastCell*/, true /*inFirstRow*/, false /*inLastRow*/, @@ -7253,9 +7253,9 @@ public virtual DataObject GetClipboardContent() { if (includeRowHeaders) { - cellContent = this.TopLeftHeaderCell.GetClipboardContentInternal(-1, + cellContent = TopLeftHeaderCell.GetClipboardContentInternal(-1, true /*firstCell*/, - this.Columns.GetColumnCount(DataGridViewElementStates.Visible) == 0 /*lastCell*/, + Columns.GetColumnCount(DataGridViewElementStates.Visible) == 0 /*lastCell*/, true /*inFirstRow*/, false /*inLastRow*/, format) as string; @@ -7265,10 +7265,10 @@ public virtual DataObject GetClipboardContent() } } // Cycle through the visible columns in their display order - dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); if (dataGridViewColumn != null) { - nextDataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); + nextDataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); cellContent = dataGridViewColumn.HeaderCell.GetClipboardContentInternal(-1, !includeRowHeaders /*firstCell*/, nextDataGridViewColumn == null /*lastCell*/, @@ -7282,7 +7282,7 @@ public virtual DataObject GetClipboardContent() while (nextDataGridViewColumn != null) { dataGridViewColumn = nextDataGridViewColumn; - nextDataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); + nextDataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); cellContent = dataGridViewColumn.HeaderCell.GetClipboardContentInternal(-1, false /*firstCell*/, nextDataGridViewColumn == null /*lastCell*/, @@ -7299,20 +7299,20 @@ public virtual DataObject GetClipboardContent() } // Cycle through the visible selected rows. bool firstRowIndex = true; - int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Selected); + int rowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Selected); Debug.Assert(rowIndex != -1); - int nextRowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible | DataGridViewElementStates.Selected); + int nextRowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible | DataGridViewElementStates.Selected); while (rowIndex != -1) { - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - dataGridViewColumn = this.Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.None); + dataGridViewColumn = Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.None); // Cycle through the visible columns in their reverse display order if (dataGridViewColumn != null) { - prevDataGridViewColumn = this.Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); - cellContent = this.Rows.SharedRow(rowIndex).Cells[dataGridViewColumn.Index].GetClipboardContentInternal(rowIndex, + prevDataGridViewColumn = Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); + cellContent = Rows.SharedRow(rowIndex).Cells[dataGridViewColumn.Index].GetClipboardContentInternal(rowIndex, true /*firstCell*/, !includeRowHeaders && prevDataGridViewColumn == null /*lastCell*/, !includeColumnHeaders && firstRowIndex /*inFirstRow*/, @@ -7325,8 +7325,8 @@ public virtual DataObject GetClipboardContent() while (prevDataGridViewColumn != null) { dataGridViewColumn = prevDataGridViewColumn; - prevDataGridViewColumn = this.Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); - cellContent = this.Rows.SharedRow(rowIndex).Cells[dataGridViewColumn.Index].GetClipboardContentInternal(rowIndex, + prevDataGridViewColumn = Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); + cellContent = Rows.SharedRow(rowIndex).Cells[dataGridViewColumn.Index].GetClipboardContentInternal(rowIndex, false /*firstCell*/, !includeRowHeaders && prevDataGridViewColumn == null /*lastCell*/, !includeColumnHeaders && firstRowIndex /*inFirstRow*/, @@ -7342,8 +7342,8 @@ public virtual DataObject GetClipboardContent() // Get the row header clipboard content if (includeRowHeaders) { - cellContent = this.Rows.SharedRow(rowIndex).HeaderCell.GetClipboardContentInternal(rowIndex, - this.Columns.GetColumnCount(DataGridViewElementStates.Visible) == 0 /*firstCell*/, + cellContent = Rows.SharedRow(rowIndex).HeaderCell.GetClipboardContentInternal(rowIndex, + Columns.GetColumnCount(DataGridViewElementStates.Visible) == 0 /*firstCell*/, true /*lastCell*/, !includeColumnHeaders && firstRowIndex /*inFirstRow*/, nextRowIndex == -1 /*inLastRow*/, @@ -7356,12 +7356,12 @@ public virtual DataObject GetClipboardContent() } else { - dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); // Get the row header clipboard content if (includeRowHeaders) { - cellContent = this.Rows.SharedRow(rowIndex).HeaderCell.GetClipboardContentInternal(rowIndex, + cellContent = Rows.SharedRow(rowIndex).HeaderCell.GetClipboardContentInternal(rowIndex, true /*firstCell*/, dataGridViewColumn == null /*lastCell*/, !includeColumnHeaders && firstRowIndex /*inFirstRow*/, @@ -7376,8 +7376,8 @@ public virtual DataObject GetClipboardContent() // Cycle through the visible columns in their display order if (dataGridViewColumn != null) { - nextDataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); - cellContent = this.Rows.SharedRow(rowIndex).Cells[dataGridViewColumn.Index].GetClipboardContentInternal(rowIndex, + nextDataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); + cellContent = Rows.SharedRow(rowIndex).Cells[dataGridViewColumn.Index].GetClipboardContentInternal(rowIndex, !includeRowHeaders /*firstCell*/, nextDataGridViewColumn == null /*lastCell*/, !includeColumnHeaders && firstRowIndex /*inFirstRow*/, @@ -7390,8 +7390,8 @@ public virtual DataObject GetClipboardContent() while (nextDataGridViewColumn != null) { dataGridViewColumn = nextDataGridViewColumn; - nextDataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); - cellContent = this.Rows.SharedRow(rowIndex).Cells[dataGridViewColumn.Index].GetClipboardContentInternal(rowIndex, + nextDataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); + cellContent = Rows.SharedRow(rowIndex).Cells[dataGridViewColumn.Index].GetClipboardContentInternal(rowIndex, false /*firstCell*/, nextDataGridViewColumn == null /*lastCell*/, !includeColumnHeaders && firstRowIndex /*inFirstRow*/, @@ -7407,7 +7407,7 @@ public virtual DataObject GetClipboardContent() rowIndex = nextRowIndex; if (rowIndex != -1) { - nextRowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible | DataGridViewElementStates.Selected); + nextRowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible | DataGridViewElementStates.Selected); } firstRowIndex = false; } @@ -7425,7 +7425,7 @@ public virtual DataObject GetClipboardContent() break; case DataGridViewSelectionMode.FullColumnSelect: - if (this.Columns.GetColumnCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Selected) == 0) + if (Columns.GetColumnCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Selected) == 0) { return null; } @@ -7433,17 +7433,17 @@ public virtual DataObject GetClipboardContent() if (clipboardCopyMode == DataGridViewClipboardCopyMode.EnableWithAutoHeaderText) { includeColumnHeaders = true; - includeRowHeaders = (this.Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Selected) == null); + includeRowHeaders = (Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Selected) == null); } else { includeColumnHeaders = includeRowHeaders = (clipboardCopyMode == DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText); } - includeColumnHeaders &= this.ColumnHeadersVisible; - includeRowHeaders &= this.RowHeadersVisible; + includeColumnHeaders &= ColumnHeadersVisible; + includeRowHeaders &= RowHeadersVisible; - int firstVisibleRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + int firstVisibleRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); foreach (string format in formats) { @@ -7466,15 +7466,15 @@ public virtual DataObject GetClipboardContent() if (includeColumnHeaders) { - if (this.RightToLeftInternal) + if (RightToLeftInternal) { // Cycle through the visible & selected columns in their display order - DataGridViewColumn lastDataGridViewColumn = this.Columns.GetLastColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Selected, DataGridViewElementStates.None); + DataGridViewColumn lastDataGridViewColumn = Columns.GetLastColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Selected, DataGridViewElementStates.None); dataGridViewColumn = lastDataGridViewColumn; Debug.Assert(dataGridViewColumn != null); if (dataGridViewColumn != null) { - prevDataGridViewColumn = this.Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Selected, DataGridViewElementStates.None); + prevDataGridViewColumn = Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Selected, DataGridViewElementStates.None); cellContent = dataGridViewColumn.HeaderCell.GetClipboardContentInternal(-1, true /*firstCell*/, !includeRowHeaders && prevDataGridViewColumn == null /*lastCell*/, @@ -7488,7 +7488,7 @@ public virtual DataObject GetClipboardContent() while (prevDataGridViewColumn != null) { dataGridViewColumn = prevDataGridViewColumn; - prevDataGridViewColumn = this.Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Selected, DataGridViewElementStates.None); + prevDataGridViewColumn = Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Selected, DataGridViewElementStates.None); cellContent = dataGridViewColumn.HeaderCell.GetClipboardContentInternal(-1, false /*firstCell*/, !includeRowHeaders && prevDataGridViewColumn == null /*lastCell*/, @@ -7503,7 +7503,7 @@ public virtual DataObject GetClipboardContent() } if (includeRowHeaders) { - cellContent = this.TopLeftHeaderCell.GetClipboardContentInternal(-1, + cellContent = TopLeftHeaderCell.GetClipboardContentInternal(-1, lastDataGridViewColumn == null /*firstCell*/, true /*lastCell*/, true /*inFirstRow*/, @@ -7517,11 +7517,11 @@ public virtual DataObject GetClipboardContent() } else { - dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Selected); + dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Selected); if (includeRowHeaders) { - cellContent = this.TopLeftHeaderCell.GetClipboardContentInternal(-1, + cellContent = TopLeftHeaderCell.GetClipboardContentInternal(-1, true /*firstCell*/, dataGridViewColumn == null /*lastCell*/, true /*inFirstRow*/, @@ -7536,7 +7536,7 @@ public virtual DataObject GetClipboardContent() Debug.Assert(dataGridViewColumn != null); if (dataGridViewColumn != null) { - nextDataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Selected, DataGridViewElementStates.None); + nextDataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Selected, DataGridViewElementStates.None); cellContent = dataGridViewColumn.HeaderCell.GetClipboardContentInternal(-1, !includeRowHeaders /*firstCell*/, nextDataGridViewColumn == null /*lastCell*/, @@ -7550,7 +7550,7 @@ public virtual DataObject GetClipboardContent() while (nextDataGridViewColumn != null) { dataGridViewColumn = nextDataGridViewColumn; - nextDataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Selected, DataGridViewElementStates.None); + nextDataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Selected, DataGridViewElementStates.None); cellContent = dataGridViewColumn.HeaderCell.GetClipboardContentInternal(-1, false /*firstCell*/, nextDataGridViewColumn == null /*lastCell*/, @@ -7571,20 +7571,20 @@ public virtual DataObject GetClipboardContent() int nextRowIndex = -1; if (rowIndex != -1) { - nextRowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); + nextRowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); } while (rowIndex != -1) { - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - DataGridViewColumn lastDataGridViewColumn = this.Columns.GetLastColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Selected, DataGridViewElementStates.None); + DataGridViewColumn lastDataGridViewColumn = Columns.GetLastColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Selected, DataGridViewElementStates.None); // Cycle through the visible & selected columns in their reverse display order dataGridViewColumn = lastDataGridViewColumn; if (dataGridViewColumn != null) { - prevDataGridViewColumn = this.Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Selected, DataGridViewElementStates.None); - cellContent = this.Rows.SharedRow(rowIndex).Cells[dataGridViewColumn.Index].GetClipboardContentInternal(rowIndex, + prevDataGridViewColumn = Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Selected, DataGridViewElementStates.None); + cellContent = Rows.SharedRow(rowIndex).Cells[dataGridViewColumn.Index].GetClipboardContentInternal(rowIndex, true /*firstCell*/, !includeRowHeaders && prevDataGridViewColumn == null /*lastCell*/, !includeColumnHeaders && firstRowIndex /*inFirstRow*/, @@ -7597,8 +7597,8 @@ public virtual DataObject GetClipboardContent() while (prevDataGridViewColumn != null) { dataGridViewColumn = prevDataGridViewColumn; - prevDataGridViewColumn = this.Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Selected, DataGridViewElementStates.None); - cellContent = this.Rows.SharedRow(rowIndex).Cells[dataGridViewColumn.Index].GetClipboardContentInternal(rowIndex, + prevDataGridViewColumn = Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Selected, DataGridViewElementStates.None); + cellContent = Rows.SharedRow(rowIndex).Cells[dataGridViewColumn.Index].GetClipboardContentInternal(rowIndex, false /*firstCell*/, !includeRowHeaders && prevDataGridViewColumn == null /*lastCell*/, !includeColumnHeaders && firstRowIndex /*inFirstRow*/, @@ -7614,7 +7614,7 @@ public virtual DataObject GetClipboardContent() // Get the row header clipboard content if (includeRowHeaders) { - cellContent = this.Rows.SharedRow(rowIndex).HeaderCell.GetClipboardContentInternal(rowIndex, + cellContent = Rows.SharedRow(rowIndex).HeaderCell.GetClipboardContentInternal(rowIndex, lastDataGridViewColumn == null /*firstCell*/, true /*lastCell*/, !includeColumnHeaders && firstRowIndex /*inFirstRow*/, @@ -7628,12 +7628,12 @@ public virtual DataObject GetClipboardContent() } else { - dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Selected); + dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Selected); // Get the row header clipboard content if (includeRowHeaders) { - cellContent = this.Rows.SharedRow(rowIndex).HeaderCell.GetClipboardContentInternal(rowIndex, + cellContent = Rows.SharedRow(rowIndex).HeaderCell.GetClipboardContentInternal(rowIndex, true /*firstCell*/, dataGridViewColumn == null /*lastCell*/, !includeColumnHeaders && firstRowIndex /*inFirstRow*/, @@ -7648,8 +7648,8 @@ public virtual DataObject GetClipboardContent() // Cycle through the visible & selected columns in their display order if (dataGridViewColumn != null) { - nextDataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Selected, DataGridViewElementStates.None); - cellContent = this.Rows.SharedRow(rowIndex).Cells[dataGridViewColumn.Index].GetClipboardContentInternal(rowIndex, + nextDataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Selected, DataGridViewElementStates.None); + cellContent = Rows.SharedRow(rowIndex).Cells[dataGridViewColumn.Index].GetClipboardContentInternal(rowIndex, !includeRowHeaders /*firstCell*/, nextDataGridViewColumn == null /*lastCell*/, !includeColumnHeaders && firstRowIndex /*inFirstRow*/, @@ -7662,8 +7662,8 @@ public virtual DataObject GetClipboardContent() while (nextDataGridViewColumn != null) { dataGridViewColumn = nextDataGridViewColumn; - nextDataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Selected, DataGridViewElementStates.None); - cellContent = this.Rows.SharedRow(rowIndex).Cells[dataGridViewColumn.Index].GetClipboardContentInternal(rowIndex, + nextDataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Selected, DataGridViewElementStates.None); + cellContent = Rows.SharedRow(rowIndex).Cells[dataGridViewColumn.Index].GetClipboardContentInternal(rowIndex, false /*firstCell*/, nextDataGridViewColumn == null /*lastCell*/, !includeColumnHeaders && firstRowIndex /*inFirstRow*/, @@ -7679,7 +7679,7 @@ public virtual DataObject GetClipboardContent() rowIndex = nextRowIndex; if (rowIndex != -1) { - nextRowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); + nextRowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); } firstRowIndex = false; } @@ -7702,19 +7702,19 @@ public virtual DataObject GetClipboardContent() bool selectedVisibleCellExists = false; bool selectedVisibleColumnExists = false; bool selectedVisibleRowExists = false; - if (this.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) + if (SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) { - selectedVisibleRowExists = this.Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Selected) != 0; - selectedVisibleCellExists = selectedVisibleRowExists && this.Columns.GetColumnCount(DataGridViewElementStates.Visible) != 0; + selectedVisibleRowExists = Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Selected) != 0; + selectedVisibleCellExists = selectedVisibleRowExists && Columns.GetColumnCount(DataGridViewElementStates.Visible) != 0; } - else if (this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) + else if (SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) { - selectedVisibleColumnExists = this.Columns.GetColumnCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Selected) != 0; - selectedVisibleCellExists = selectedVisibleColumnExists && this.Rows.GetRowCount(DataGridViewElementStates.Visible) != 0; + selectedVisibleColumnExists = Columns.GetColumnCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Selected) != 0; + selectedVisibleCellExists = selectedVisibleColumnExists && Rows.GetRowCount(DataGridViewElementStates.Visible) != 0; } - if (!selectedVisibleCellExists && this.individualSelectedCells.Count > 0) + if (!selectedVisibleCellExists && individualSelectedCells.Count > 0) { - foreach (DataGridViewCell dataGridViewCell in this.individualSelectedCells) + foreach (DataGridViewCell dataGridViewCell in individualSelectedCells) { if (dataGridViewCell.Visible) { @@ -7729,16 +7729,16 @@ public virtual DataObject GetClipboardContent() } // There is at least one selected visible cell. - if (this.SelectionMode == DataGridViewSelectionMode.CellSelect) + if (SelectionMode == DataGridViewSelectionMode.CellSelect) { includeColumnHeaders = includeRowHeaders = (clipboardCopyMode == DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText); - includeColumnHeaders &= this.ColumnHeadersVisible; - includeRowHeaders &= this.RowHeadersVisible; + includeColumnHeaders &= ColumnHeadersVisible; + includeRowHeaders &= RowHeadersVisible; } else { includeColumnHeaders = includeRowHeaders = false; - if (this.ColumnHeadersVisible) + if (ColumnHeadersVisible) { if (clipboardCopyMode == DataGridViewClipboardCopyMode.EnableWithAutoHeaderText) { @@ -7781,7 +7781,7 @@ public virtual DataObject GetClipboardContent() } } - if (this.RowHeadersVisible) + if (RowHeadersVisible) { if (clipboardCopyMode == DataGridViewClipboardCopyMode.EnableWithAutoHeaderText) { @@ -7831,16 +7831,16 @@ public virtual DataObject GetClipboardContent() int uRowIndex = -1; DataGridViewColumn lColumn = null, uColumn = null; - if (this.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) + if (SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) { - DataGridViewColumn firstVisibleColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); - DataGridViewColumn lastVisibleColumn = this.Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.None); + DataGridViewColumn firstVisibleColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); + DataGridViewColumn lastVisibleColumn = Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(firstVisibleColumn != null); Debug.Assert(lastVisibleColumn != null); - foreach (int rowIndex in this.selectedBandIndexes) + foreach (int rowIndex in selectedBandIndexes) { - if ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Visible) != 0) + if ((Rows.GetRowState(rowIndex) & DataGridViewElementStates.Visible) != 0) { if (rowIndex < lRowIndex) { @@ -7855,23 +7855,23 @@ public virtual DataObject GetClipboardContent() } } } - else if (this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) + else if (SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) { - firstVisibleRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); - int lastVisibleRowIndex = this.Rows.GetLastRow(DataGridViewElementStates.Visible); + firstVisibleRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); + int lastVisibleRowIndex = Rows.GetLastRow(DataGridViewElementStates.Visible); Debug.Assert(firstVisibleRowIndex != -1); Debug.Assert(lastVisibleRowIndex != -1); - foreach (int columnIndex in this.selectedBandIndexes) + foreach (int columnIndex in selectedBandIndexes) { - if (this.Columns[columnIndex].Visible) + if (Columns[columnIndex].Visible) { - if (lColumn == null || this.Columns.DisplayInOrder(columnIndex, lColumn.Index)) + if (lColumn == null || Columns.DisplayInOrder(columnIndex, lColumn.Index)) { - lColumn = this.Columns[columnIndex]; + lColumn = Columns[columnIndex]; } - if (uColumn == null || this.Columns.DisplayInOrder(uColumn.Index, columnIndex)) + if (uColumn == null || Columns.DisplayInOrder(uColumn.Index, columnIndex)) { - uColumn = this.Columns[columnIndex]; + uColumn = Columns[columnIndex]; } lRowIndex = firstVisibleRowIndex; uRowIndex = lastVisibleRowIndex; @@ -7880,7 +7880,7 @@ public virtual DataObject GetClipboardContent() } // Go through the individually selected cells to potentially stretch the current 'selected table'. - foreach (DataGridViewCell dataGridViewCell in this.individualSelectedCells) + foreach (DataGridViewCell dataGridViewCell in individualSelectedCells) { if (dataGridViewCell.Visible) { @@ -7892,11 +7892,11 @@ public virtual DataObject GetClipboardContent() { uRowIndex = dataGridViewCell.RowIndex; } - if (lColumn == null || this.Columns.DisplayInOrder(dataGridViewCell.ColumnIndex, lColumn.Index)) + if (lColumn == null || Columns.DisplayInOrder(dataGridViewCell.ColumnIndex, lColumn.Index)) { lColumn = dataGridViewCell.OwningColumn; } - if (uColumn == null || this.Columns.DisplayInOrder(uColumn.Index, dataGridViewCell.ColumnIndex)) + if (uColumn == null || Columns.DisplayInOrder(uColumn.Index, dataGridViewCell.ColumnIndex)) { uColumn = dataGridViewCell.OwningColumn; } @@ -7907,7 +7907,7 @@ public virtual DataObject GetClipboardContent() Debug.Assert(uRowIndex != -1); Debug.Assert(lColumn != null); Debug.Assert(uColumn != null); - Debug.Assert(lColumn.Index == uColumn.Index || this.Columns.DisplayInOrder(lColumn.Index, uColumn.Index)); + Debug.Assert(lColumn.Index == uColumn.Index || Columns.DisplayInOrder(lColumn.Index, uColumn.Index)); Debug.Assert(lRowIndex <= uRowIndex); foreach (string format in formats) @@ -7931,7 +7931,7 @@ public virtual DataObject GetClipboardContent() if (includeColumnHeaders) { - if (this.RightToLeftInternal) + if (RightToLeftInternal) { // Cycle through the visible columns from uColumn to lColumn dataGridViewColumn = uColumn; @@ -7940,7 +7940,7 @@ public virtual DataObject GetClipboardContent() { if (dataGridViewColumn != lColumn) { - prevDataGridViewColumn = this.Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); + prevDataGridViewColumn = Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(prevDataGridViewColumn != null); } else @@ -7961,7 +7961,7 @@ public virtual DataObject GetClipboardContent() } if (includeRowHeaders) { - cellContent = this.TopLeftHeaderCell.GetClipboardContentInternal(-1, + cellContent = TopLeftHeaderCell.GetClipboardContentInternal(-1, false /*firstCell*/, true /*lastCell*/, true /*inFirstRow*/, @@ -7977,7 +7977,7 @@ public virtual DataObject GetClipboardContent() { if (includeRowHeaders) { - cellContent = this.TopLeftHeaderCell.GetClipboardContentInternal(-1, + cellContent = TopLeftHeaderCell.GetClipboardContentInternal(-1, true /*firstCell*/, false /*lastCell*/, true /*inFirstRow*/, @@ -7995,7 +7995,7 @@ public virtual DataObject GetClipboardContent() { if (dataGridViewColumn != uColumn) { - nextDataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); + nextDataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(nextDataGridViewColumn != null); } else @@ -8025,7 +8025,7 @@ public virtual DataObject GetClipboardContent() { if (rowIndex != uRowIndex) { - nextRowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); + nextRowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); Debug.Assert(nextRowIndex != -1); } else @@ -8033,7 +8033,7 @@ public virtual DataObject GetClipboardContent() nextRowIndex = -1; } - if (this.RightToLeftInternal) + if (RightToLeftInternal) { // Cycle through the visible columns from uColumn to lColumn dataGridViewColumn = uColumn; @@ -8042,7 +8042,7 @@ public virtual DataObject GetClipboardContent() { if (dataGridViewColumn != lColumn) { - prevDataGridViewColumn = this.Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); + prevDataGridViewColumn = Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(prevDataGridViewColumn != null); } else @@ -8050,7 +8050,7 @@ public virtual DataObject GetClipboardContent() prevDataGridViewColumn = null; } - cellContent = this.Rows.SharedRow(rowIndex).Cells[dataGridViewColumn.Index].GetClipboardContentInternal(rowIndex, + cellContent = Rows.SharedRow(rowIndex).Cells[dataGridViewColumn.Index].GetClipboardContentInternal(rowIndex, dataGridViewColumn == uColumn /*firstCell*/, !includeRowHeaders && prevDataGridViewColumn == null /*lastCell*/, !includeColumnHeaders && firstRowIndex /*inFirstRow*/, @@ -8066,7 +8066,7 @@ public virtual DataObject GetClipboardContent() if (includeRowHeaders) { // Get the row header clipboard content - cellContent = this.Rows.SharedRow(rowIndex).HeaderCell.GetClipboardContentInternal(rowIndex, + cellContent = Rows.SharedRow(rowIndex).HeaderCell.GetClipboardContentInternal(rowIndex, false /*firstCell*/, true /*lastCell*/, !includeColumnHeaders && firstRowIndex /*inFirstRow*/, @@ -8083,7 +8083,7 @@ public virtual DataObject GetClipboardContent() if (includeRowHeaders) { // Get the row header clipboard content - cellContent = this.Rows.SharedRow(rowIndex).HeaderCell.GetClipboardContentInternal(rowIndex, + cellContent = Rows.SharedRow(rowIndex).HeaderCell.GetClipboardContentInternal(rowIndex, true /*firstCell*/, false /*lastCell*/, !includeColumnHeaders && firstRowIndex /*inFirstRow*/, @@ -8102,7 +8102,7 @@ public virtual DataObject GetClipboardContent() { if (dataGridViewColumn != uColumn) { - nextDataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); + nextDataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(nextDataGridViewColumn != null); } else @@ -8110,7 +8110,7 @@ public virtual DataObject GetClipboardContent() nextDataGridViewColumn = null; } - cellContent = this.Rows.SharedRow(rowIndex).Cells[dataGridViewColumn.Index].GetClipboardContentInternal(rowIndex, + cellContent = Rows.SharedRow(rowIndex).Cells[dataGridViewColumn.Index].GetClipboardContentInternal(rowIndex, !includeRowHeaders && dataGridViewColumn == lColumn /*firstCell*/, nextDataGridViewColumn == null /*lastCell*/, !includeColumnHeaders && firstRowIndex /*inFirstRow*/, @@ -8171,7 +8171,7 @@ private static void GetClipboardContentForHtml(StringBuilder sbContent, out Syst // Rectangle returned includes the potential column header public Rectangle GetColumnDisplayRectangle(int columnIndex, bool cutOverflow) { - if (columnIndex < 0 || columnIndex >= this.Columns.Count) + if (columnIndex < 0 || columnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException(nameof(columnIndex)); } @@ -8180,18 +8180,18 @@ public Rectangle GetColumnDisplayRectangle(int columnIndex, bool cutOverflow) private Rectangle GetColumnDisplayRectanglePrivate(int columnIndex, bool cutOverflow) { - Debug.Assert(columnIndex >= 0 && columnIndex < this.Columns.Count); + Debug.Assert(columnIndex >= 0 && columnIndex < Columns.Count); - if (!this.Columns[columnIndex].Displayed) + if (!Columns[columnIndex].Displayed) { return Rectangle.Empty; } - Rectangle data = this.layout.Data; + Rectangle data = layout.Data; int cx; bool columnFound = false; DataGridViewColumn dataGridViewColumn; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { cx = data.Right; } @@ -8199,12 +8199,12 @@ private Rectangle GetColumnDisplayRectanglePrivate(int columnIndex, bool cutOver { cx = data.X; } - for (dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + for (dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); dataGridViewColumn != null && !columnFound; ) { - if ((this.RightToLeftInternal && cx < data.X) || - (!this.RightToLeftInternal && cx > data.Right)) + if ((RightToLeftInternal && cx < data.X) || + (!RightToLeftInternal && cx > data.Right)) { break; } @@ -8214,7 +8214,7 @@ private Rectangle GetColumnDisplayRectanglePrivate(int columnIndex, bool cutOver } else { - if (this.RightToLeftInternal) + if (RightToLeftInternal) { cx -= dataGridViewColumn.Thickness; } @@ -8222,20 +8222,20 @@ private Rectangle GetColumnDisplayRectanglePrivate(int columnIndex, bool cutOver { cx += dataGridViewColumn.Thickness; } - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen, DataGridViewElementStates.None); } } - if (!columnFound && this.displayedBandsInfo.FirstDisplayedScrollingCol >= 0) + if (!columnFound && displayedBandsInfo.FirstDisplayedScrollingCol >= 0) { - for (dataGridViewColumn = this.Columns[this.displayedBandsInfo.FirstDisplayedScrollingCol]; + for (dataGridViewColumn = Columns[displayedBandsInfo.FirstDisplayedScrollingCol]; dataGridViewColumn != null && !columnFound; ) { - if ((this.RightToLeftInternal && cx < data.X) || - (!this.RightToLeftInternal && cx > data.Right)) + if ((RightToLeftInternal && cx < data.X) || + (!RightToLeftInternal && cx > data.Right)) { break; } @@ -8245,7 +8245,7 @@ private Rectangle GetColumnDisplayRectanglePrivate(int columnIndex, bool cutOver } else { - if (this.RightToLeftInternal) + if (RightToLeftInternal) { cx -= dataGridViewColumn.Thickness; } @@ -8253,18 +8253,18 @@ private Rectangle GetColumnDisplayRectanglePrivate(int columnIndex, bool cutOver { cx += dataGridViewColumn.Thickness; } - if (dataGridViewColumn.Index == this.displayedBandsInfo.FirstDisplayedScrollingCol) + if (dataGridViewColumn.Index == displayedBandsInfo.FirstDisplayedScrollingCol) { - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - cx += this.negOffset; + cx += negOffset; } else { - cx -= this.negOffset; + cx -= negOffset; } } - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); } @@ -8275,15 +8275,15 @@ private Rectangle GetColumnDisplayRectanglePrivate(int columnIndex, bool cutOver { Debug.Assert(dataGridViewColumn != null); int displayWidth, viewedColumnWidth = dataGridViewColumn.Thickness; - if (dataGridViewColumn.Index == this.displayedBandsInfo.FirstDisplayedScrollingCol) + if (dataGridViewColumn.Index == displayedBandsInfo.FirstDisplayedScrollingCol) { - viewedColumnWidth -= this.negOffset; + viewedColumnWidth -= negOffset; } if (cutOverflow && - ((!this.RightToLeftInternal && cx + viewedColumnWidth > data.Right) || - (this.RightToLeftInternal && cx - viewedColumnWidth < data.X))) + ((!RightToLeftInternal && cx + viewedColumnWidth > data.Right) || + (RightToLeftInternal && cx - viewedColumnWidth < data.X))) { - if (this.RightToLeftInternal) + if (RightToLeftInternal) { displayWidth = cx - data.X; } @@ -8298,7 +8298,7 @@ private Rectangle GetColumnDisplayRectanglePrivate(int columnIndex, bool cutOver } Rectangle columnRect; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { columnRect = new Rectangle(cx - displayWidth, data.Y, displayWidth, data.Height); } @@ -8306,10 +8306,10 @@ private Rectangle GetColumnDisplayRectanglePrivate(int columnIndex, bool cutOver { columnRect = new Rectangle(cx, data.Y, displayWidth, data.Height); } - if (this.layout.ColumnHeadersVisible) + if (layout.ColumnHeadersVisible) { - columnRect.Height += this.layout.ColumnHeaders.Height; - columnRect.Y -= this.layout.ColumnHeaders.Height; + columnRect.Height += layout.ColumnHeaders.Height; + columnRect.Y -= layout.ColumnHeaders.Height; } return columnRect; } @@ -8321,21 +8321,21 @@ private Rectangle GetColumnDisplayRectanglePrivate(int columnIndex, bool cutOver // xColumnLeftEdge returns the right edge of the column when RightToLeft is true. private int GetColumnIndexFromX(int x, out int xColumnLeftEdge) { - Rectangle data = this.layout.Data; - Debug.Assert(this.RightToLeftInternal || (x >= data.X - 1 && x < data.Right), "x must be inside the horizontal bounds of this.layout.Data"); - Debug.Assert(!this.RightToLeftInternal || (x >= data.X && x <= data.Right), "x must be inside the horizontal bounds of this.layout.Data"); + Rectangle data = layout.Data; + Debug.Assert(RightToLeftInternal || (x >= data.X - 1 && x < data.Right), "x must be inside the horizontal bounds of this.layout.Data"); + Debug.Assert(!RightToLeftInternal || (x >= data.X && x <= data.Right), "x must be inside the horizontal bounds of this.layout.Data"); - if (!this.RightToLeftInternal && x == data.X - 1) + if (!RightToLeftInternal && x == data.X - 1) { x++; } - else if (this.RightToLeftInternal && x == data.Right) + else if (RightToLeftInternal && x == data.Right) { x--; } int cx; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { cx = data.Right - 1; } @@ -8345,11 +8345,11 @@ private int GetColumnIndexFromX(int x, out int xColumnLeftEdge) } // first try to match x against a frozen column - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); while (dataGridViewColumn != null && - ((!this.RightToLeftInternal && cx < data.Right) || (this.RightToLeftInternal && cx >= data.X))) + ((!RightToLeftInternal && cx < data.Right) || (RightToLeftInternal && cx >= data.X))) { - if (this.RightToLeftInternal) + if (RightToLeftInternal) { cx -= dataGridViewColumn.Thickness; } @@ -8357,39 +8357,39 @@ private int GetColumnIndexFromX(int x, out int xColumnLeftEdge) { cx += dataGridViewColumn.Thickness; } - if (!this.RightToLeftInternal && cx > x) + if (!RightToLeftInternal && cx > x) { xColumnLeftEdge = cx - dataGridViewColumn.Thickness; return dataGridViewColumn.Index; } - else if (this.RightToLeftInternal && cx < x) + else if (RightToLeftInternal && cx < x) { xColumnLeftEdge = cx + dataGridViewColumn.Thickness; return dataGridViewColumn.Index; } - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen, DataGridViewElementStates.None); } - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - cx += this.negOffset; + cx += negOffset; } else { - cx -= this.negOffset; + cx -= negOffset; } // second try to match x against a scrolling column - if (this.displayedBandsInfo.FirstDisplayedScrollingCol >= 0) + if (displayedBandsInfo.FirstDisplayedScrollingCol >= 0) { - dataGridViewColumn = this.Columns[this.displayedBandsInfo.FirstDisplayedScrollingCol]; + dataGridViewColumn = Columns[displayedBandsInfo.FirstDisplayedScrollingCol]; while (dataGridViewColumn != null && - ((!this.RightToLeftInternal && cx < data.Right) || (this.RightToLeftInternal && cx >= data.X))) + ((!RightToLeftInternal && cx < data.Right) || (RightToLeftInternal && cx >= data.X))) { Debug.Assert(dataGridViewColumn.Visible && !dataGridViewColumn.Frozen); - if (this.RightToLeftInternal) + if (RightToLeftInternal) { cx -= dataGridViewColumn.Thickness; } @@ -8397,17 +8397,17 @@ private int GetColumnIndexFromX(int x, out int xColumnLeftEdge) { cx += dataGridViewColumn.Thickness; } - if (!this.RightToLeftInternal && cx > x) + if (!RightToLeftInternal && cx > x) { xColumnLeftEdge = cx - dataGridViewColumn.Thickness; return dataGridViewColumn.Index; } - else if (this.RightToLeftInternal && cx < x) + else if (RightToLeftInternal && cx < x) { xColumnLeftEdge = cx + dataGridViewColumn.Thickness; return dataGridViewColumn.Index; } - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); } @@ -8450,27 +8450,27 @@ private static int GetColumnScrollRate(int xOffset) /// internal int GetColumnXFromIndex(int index) { - Debug.Assert(index < this.Columns.Count); - Debug.Assert(this.Columns[index].Visible); + Debug.Assert(index < Columns.Count); + Debug.Assert(Columns[index].Visible); int x; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - x = this.layout.Data.Right - 1; + x = layout.Data.Right - 1; } else { - x = this.layout.Data.X; + x = layout.Data.X; } - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); while (dataGridViewColumn != null) { if (index == dataGridViewColumn.Index) { return x; } - if (this.RightToLeftInternal) + if (RightToLeftInternal) { x -= dataGridViewColumn.Thickness; } @@ -8478,29 +8478,29 @@ internal int GetColumnXFromIndex(int index) { x += dataGridViewColumn.Thickness; } - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen, DataGridViewElementStates.None); } - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - x += this.negOffset; + x += negOffset; } else { - x -= this.negOffset; + x -= negOffset; } int xFirstVisibleScrollingCol = x; - if (this.displayedBandsInfo.FirstDisplayedScrollingCol >= 0) + if (displayedBandsInfo.FirstDisplayedScrollingCol >= 0) { - dataGridViewColumn = this.Columns[this.displayedBandsInfo.FirstDisplayedScrollingCol]; + dataGridViewColumn = Columns[displayedBandsInfo.FirstDisplayedScrollingCol]; } else { - dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); + dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); } Debug.Assert(dataGridViewColumn.Visible && !dataGridViewColumn.Frozen); @@ -8510,7 +8510,7 @@ internal int GetColumnXFromIndex(int index) { return x; } - if (this.RightToLeftInternal) + if (RightToLeftInternal) { x -= dataGridViewColumn.Thickness; } @@ -8518,20 +8518,20 @@ internal int GetColumnXFromIndex(int index) { x += dataGridViewColumn.Thickness; } - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); } // The column is completely hidden on the left/right of the dataGridView x = xFirstVisibleScrollingCol; - dataGridViewColumn = this.Columns[this.displayedBandsInfo.FirstDisplayedScrollingCol]; - dataGridViewColumn = this.Columns.GetPreviousColumn(dataGridViewColumn, + dataGridViewColumn = Columns[displayedBandsInfo.FirstDisplayedScrollingCol]; + dataGridViewColumn = Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); while (dataGridViewColumn != null) { - if (this.RightToLeftInternal) + if (RightToLeftInternal) { x += dataGridViewColumn.Thickness; } @@ -8543,7 +8543,7 @@ internal int GetColumnXFromIndex(int index) { return x; } - dataGridViewColumn = this.Columns.GetPreviousColumn(dataGridViewColumn, + dataGridViewColumn = Columns.GetPreviousColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); } @@ -8554,11 +8554,11 @@ internal int GetColumnXFromIndex(int index) private int GetNegOffsetFromHorizontalOffset(int horizontalOffset) { - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); while (dataGridViewColumn != null && dataGridViewColumn.Thickness <= horizontalOffset) { horizontalOffset -= dataGridViewColumn.Thickness; - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); } return horizontalOffset; } @@ -8566,28 +8566,28 @@ private int GetNegOffsetFromHorizontalOffset(int horizontalOffset) private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mouseX, ref int mouseY, out int xOffset, out int yOffset) { xOffset = yOffset = 0; - Rectangle rectScrollingArea = this.layout.Data; - int visibleRowsHeight = this.Rows.GetRowsHeight(DataGridViewElementStates.Visible); - int frozenVisibleRowsHeight = this.Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + Rectangle rectScrollingArea = layout.Data; + int visibleRowsHeight = Rows.GetRowsHeight(DataGridViewElementStates.Visible); + int frozenVisibleRowsHeight = Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); int fittingTrailingScrollingRowsHeight = ComputeHeightOfFittingTrailingScrollingRows(frozenVisibleRowsHeight); int trailingScrollingRowsHeight = ComputeHeightOfTrailingScrollingRows(); - int emptyBackgroundWidth = Math.Max(0, this.layout.Data.Width - this.Columns.GetColumnsWidth(DataGridViewElementStates.Visible)); - int emptyBackgroundHeight = Math.Max(0, this.layout.Data.Height - frozenVisibleRowsHeight - trailingScrollingRowsHeight); + int emptyBackgroundWidth = Math.Max(0, layout.Data.Width - Columns.GetColumnsWidth(DataGridViewElementStates.Visible)); + int emptyBackgroundHeight = Math.Max(0, layout.Data.Height - frozenVisibleRowsHeight - trailingScrollingRowsHeight); - Debug.Assert(!this.vertScrollBar.Enabled || - !this.vertScrollBar.Visible || - this.vertScrollBar.Maximum == visibleRowsHeight - frozenVisibleRowsHeight); + Debug.Assert(!vertScrollBar.Enabled || + !vertScrollBar.Visible || + vertScrollBar.Maximum == visibleRowsHeight - frozenVisibleRowsHeight); //Debug.Assert(!this.vertScrollBar.Enabled || // !this.vertScrollBar.Visible || // this.vertScrollBar.Value >= this.verticalOffset); - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect]) + if (dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect]) { - if (this.layout.RowHeadersVisible) + if (layout.RowHeadersVisible) { // Include row headers - rectScrollingArea = Rectangle.Union(rectScrollingArea, this.layout.RowHeaders); + rectScrollingArea = Rectangle.Union(rectScrollingArea, layout.RowHeaders); } // Discard frozen rows DiscardZonesInScrollingArea(ref rectScrollingArea, emptyBackgroundWidth, emptyBackgroundHeight, frozenVisibleRowsHeight, @@ -8596,17 +8596,17 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous if (mouseY >= rectScrollingArea.Top && mouseY <= rectScrollingArea.Bottom) { // Mouse's Y is in-bound -- correct X value - hti = HitTest(this.RightToLeftInternal ? rectScrollingArea.Right - 1 : rectScrollingArea.Left, mouseY); - if (this.ptAnchorCell.Y != -1 && - (this.Rows.GetRowState(this.ptAnchorCell.Y) & DataGridViewElementStates.Frozen) != 0 && - this.trackRowEdge != -1 && - (this.Rows.GetRowState(this.trackRowEdge) & DataGridViewElementStates.Frozen) != 0 && + hti = HitTest(RightToLeftInternal ? rectScrollingArea.Right - 1 : rectScrollingArea.Left, mouseY); + if (ptAnchorCell.Y != -1 && + (Rows.GetRowState(ptAnchorCell.Y) & DataGridViewElementStates.Frozen) != 0 && + trackRowEdge != -1 && + (Rows.GetRowState(trackRowEdge) & DataGridViewElementStates.Frozen) != 0 && hti.row >= 0 && - (this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Frozen) == 0) + (Rows.GetRowState(hti.row) & DataGridViewElementStates.Frozen) == 0) { // Anchor cell is in frozen row and target cell is in unfrozen row. Make sure no row is scrolled off. - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0); - int firstUnfrozenRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingRow >= 0); + int firstUnfrozenRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); int firstColumnIndex; if (hti.col >= 0) { @@ -8614,7 +8614,7 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous } else { - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); firstColumnIndex = (dataGridViewColumn == null) ? -1 : dataGridViewColumn.Index; } if (firstColumnIndex >= 0 && firstUnfrozenRowIndex >= 0) @@ -8623,7 +8623,7 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous { return false; } - hti = HitTest(this.RightToLeftInternal ? rectScrollingArea.Right : rectScrollingArea.Left, mouseY); + hti = HitTest(RightToLeftInternal ? rectScrollingArea.Right : rectScrollingArea.Left, mouseY); } } return true; @@ -8632,15 +8632,15 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous // Mouse's Y is outside of scrolling bands if (mouseY < rectScrollingArea.Top) { - if (this.ptAnchorCell.Y != -1 && - ((this.Rows.GetRowState(this.ptAnchorCell.Y) & DataGridViewElementStates.Frozen) == 0 || - (this.trackRowEdge != -1 && (this.Rows.GetRowState(this.trackRowEdge) & DataGridViewElementStates.Frozen) == 0)) && - this.verticalOffset != 0) + if (ptAnchorCell.Y != -1 && + ((Rows.GetRowState(ptAnchorCell.Y) & DataGridViewElementStates.Frozen) == 0 || + (trackRowEdge != -1 && (Rows.GetRowState(trackRowEdge) & DataGridViewElementStates.Frozen) == 0)) && + verticalOffset != 0) { // Up scrolling is required because the anchor's row is unfrozen - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0); + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingRow >= 0); yOffset = mouseY - rectScrollingArea.Top; // yOffset strictly negative - if (this.RightToLeftInternal) + if (RightToLeftInternal) { mouseX = rectScrollingArea.Right - 1; } @@ -8651,20 +8651,20 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous } else { - hti = HitTest(this.RightToLeftInternal ? rectScrollingArea.Right : rectScrollingArea.Left, mouseY); + hti = HitTest(RightToLeftInternal ? rectScrollingArea.Right : rectScrollingArea.Left, mouseY); } } else { Debug.Assert(mouseY > rectScrollingArea.Bottom); - if (this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0) + if (displayedBandsInfo.FirstDisplayedScrollingRow >= 0) { - if (this.verticalOffset + this.Rows.SharedRow(this.displayedBandsInfo.FirstDisplayedScrollingRow).GetHeight(this.displayedBandsInfo.FirstDisplayedScrollingRow) <= + if (verticalOffset + Rows.SharedRow(displayedBandsInfo.FirstDisplayedScrollingRow).GetHeight(displayedBandsInfo.FirstDisplayedScrollingRow) <= visibleRowsHeight - frozenVisibleRowsHeight - fittingTrailingScrollingRowsHeight) { // Down scrolling is required yOffset = mouseY - rectScrollingArea.Bottom; // yOffset strictly positive - if (this.RightToLeftInternal) + if (RightToLeftInternal) { mouseX = rectScrollingArea.Right - 1; } @@ -8678,12 +8678,12 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous return true; } - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect]) + if (dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect]) { - if (this.layout.ColumnHeadersVisible) + if (layout.ColumnHeadersVisible) { // Include column headers - rectScrollingArea = Rectangle.Union(rectScrollingArea, this.layout.ColumnHeaders); + rectScrollingArea = Rectangle.Union(rectScrollingArea, layout.ColumnHeaders); } // Discard frozen columns @@ -8694,16 +8694,16 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous { // Mouse's X is in-bound -- correct Y value hti = HitTest(mouseX, rectScrollingArea.Top); - if (this.ptAnchorCell.X != -1 && - this.Columns[this.ptAnchorCell.X].Frozen && - this.trackColumnEdge != -1 && - this.Columns[this.trackColumnEdge].Frozen && + if (ptAnchorCell.X != -1 && + Columns[ptAnchorCell.X].Frozen && + trackColumnEdge != -1 && + Columns[trackColumnEdge].Frozen && hti.col >= 0 && - !this.Columns[hti.col].Frozen) + !Columns[hti.col].Frozen) { // Anchor cell is in frozen column and target cell is in unfrozen column. Make sure no column is scrolled off. - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingCol >= 0); - int firstUnfrozenColumnIndex = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen).Index; + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingCol >= 0); + int firstUnfrozenColumnIndex = Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen).Index; int firstRowIndex; if (hti.row >= 0) { @@ -8711,7 +8711,7 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous } else { - firstRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + firstRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); } if (firstRowIndex >= 0 && firstUnfrozenColumnIndex >= 0) { @@ -8726,18 +8726,18 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous } // Mouse's X is outside of scrolling bands - if ((!this.RightToLeftInternal && mouseX < rectScrollingArea.Left) || - (this.RightToLeftInternal && mouseX > rectScrollingArea.Right)) + if ((!RightToLeftInternal && mouseX < rectScrollingArea.Left) || + (RightToLeftInternal && mouseX > rectScrollingArea.Right)) { - if (this.ptAnchorCell.X != -1 && - (!this.Columns[this.ptAnchorCell.X].Frozen || - (this.trackColumnEdge != -1 && !this.Columns[this.trackColumnEdge].Frozen)) && - this.displayedBandsInfo.FirstDisplayedScrollingCol >= 0 && - (this.negOffset > 0 || - this.Columns.GetPreviousColumn(this.Columns[this.displayedBandsInfo.FirstDisplayedScrollingCol], DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen) != null)) + if (ptAnchorCell.X != -1 && + (!Columns[ptAnchorCell.X].Frozen || + (trackColumnEdge != -1 && !Columns[trackColumnEdge].Frozen)) && + displayedBandsInfo.FirstDisplayedScrollingCol >= 0 && + (negOffset > 0 || + Columns.GetPreviousColumn(Columns[displayedBandsInfo.FirstDisplayedScrollingCol], DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen) != null)) { // xOffset strictly negative - if (this.RightToLeftInternal) + if (RightToLeftInternal) { // Right scrolling is required xOffset = rectScrollingArea.Right - mouseX; @@ -8756,34 +8756,34 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous } else { - Debug.Assert((!this.RightToLeftInternal && mouseX > rectScrollingArea.Right) || (this.RightToLeftInternal && mouseX < rectScrollingArea.Left)); - if (this.displayedBandsInfo.FirstDisplayedScrollingCol >= 0) + Debug.Assert((!RightToLeftInternal && mouseX > rectScrollingArea.Right) || (RightToLeftInternal && mouseX < rectScrollingArea.Left)); + if (displayedBandsInfo.FirstDisplayedScrollingCol >= 0) { - if (this.displayedBandsInfo.LastTotallyDisplayedScrollingCol != -1 && - this.Columns.GetNextColumn(this.Columns[this.displayedBandsInfo.LastTotallyDisplayedScrollingCol], DataGridViewElementStates.Visible, DataGridViewElementStates.None) == null) + if (displayedBandsInfo.LastTotallyDisplayedScrollingCol != -1 && + Columns.GetNextColumn(Columns[displayedBandsInfo.LastTotallyDisplayedScrollingCol], DataGridViewElementStates.Visible, DataGridViewElementStates.None) == null) { // No more columns to scroll return true; } - DataGridViewColumn newFirstVisibleScrollingCol = this.Columns.GetNextColumn(this.Columns[this.displayedBandsInfo.FirstDisplayedScrollingCol], + DataGridViewColumn newFirstVisibleScrollingCol = Columns.GetNextColumn(Columns[displayedBandsInfo.FirstDisplayedScrollingCol], DataGridViewElementStates.Visible, DataGridViewElementStates.None); int newColOffset = 0; - for (DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible, + for (DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); dataGridViewColumn != newFirstVisibleScrollingCol; - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None)) { newColOffset += dataGridViewColumn.Thickness; } - if (this.HorizontalOffset != newColOffset) + if (HorizontalOffset != newColOffset) { // xOffset strictly positive - if (this.RightToLeftInternal) + if (RightToLeftInternal) { // Left scrolling is required xOffset = rectScrollingArea.Left - mouseX; @@ -8800,7 +8800,7 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous return true; } - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect]) + if (dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect]) { bool recomputeHitTestInfo = false; @@ -8813,24 +8813,24 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous // Mouse's Y is above scrolling bands if ( ( - (this.ptAnchorCell.Y != -1 && (this.Rows.GetRowState(this.ptAnchorCell.Y) & DataGridViewElementStates.Frozen) == 0) + (ptAnchorCell.Y != -1 && (Rows.GetRowState(ptAnchorCell.Y) & DataGridViewElementStates.Frozen) == 0) || - (this.ptCurrentCell.Y != -1 && (this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Frozen) == 0) + (ptCurrentCell.Y != -1 && (Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Frozen) == 0) ) && - this.verticalOffset != 0 + verticalOffset != 0 ) { // Up scrolling is required - the anchor's row is unfrozen - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0); + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingRow >= 0); yOffset = mouseY - rectScrollingArea.Top; // yOffset strictly negative } else { // Correct mouse's Y - no scrolling can be performed - if (mouseY < this.layout.Data.Top) + if (mouseY < layout.Data.Top) { - mouseY = this.layout.Data.Top + 1; + mouseY = layout.Data.Top + 1; recomputeHitTestInfo = true; } } @@ -8838,9 +8838,9 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous else if (mouseY > rectScrollingArea.Bottom) { // Mouse's Y is below scrolling bands - if (this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0) + if (displayedBandsInfo.FirstDisplayedScrollingRow >= 0) { - if (this.verticalOffset + this.Rows.SharedRow(this.displayedBandsInfo.FirstDisplayedScrollingRow).GetHeight(this.displayedBandsInfo.FirstDisplayedScrollingRow) <= + if (verticalOffset + Rows.SharedRow(displayedBandsInfo.FirstDisplayedScrollingRow).GetHeight(displayedBandsInfo.FirstDisplayedScrollingRow) <= visibleRowsHeight - frozenVisibleRowsHeight - fittingTrailingScrollingRowsHeight) { // Down scrolling is required @@ -8867,24 +8867,24 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous Debug.Assert(mouseY >= rectScrollingArea.Top && mouseY <= rectScrollingArea.Bottom); } #endif - if ((!this.RightToLeftInternal && mouseX < rectScrollingArea.Left) || - (this.RightToLeftInternal && mouseX > rectScrollingArea.Right)) + if ((!RightToLeftInternal && mouseX < rectScrollingArea.Left) || + (RightToLeftInternal && mouseX > rectScrollingArea.Right)) { // Mouse's X is on the left of scrolling bands (LTR) if ( ( - (this.ptAnchorCell.X != -1 && !this.Columns[this.ptAnchorCell.X].Frozen) + (ptAnchorCell.X != -1 && !Columns[ptAnchorCell.X].Frozen) || - (this.ptCurrentCell.X != -1 && !this.Columns[this.ptCurrentCell.X].Frozen) + (ptCurrentCell.X != -1 && !Columns[ptCurrentCell.X].Frozen) ) && - this.displayedBandsInfo.FirstDisplayedScrollingCol >= 0 && - (this.negOffset > 0 || - this.Columns.GetPreviousColumn(this.Columns[this.displayedBandsInfo.FirstDisplayedScrollingCol], DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen) != null) + displayedBandsInfo.FirstDisplayedScrollingCol >= 0 && + (negOffset > 0 || + Columns.GetPreviousColumn(Columns[displayedBandsInfo.FirstDisplayedScrollingCol], DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen) != null) ) { // xOffset strictly negative - if (this.RightToLeftInternal) + if (RightToLeftInternal) { // Right scrolling is required - anchor's column is unfrozen xOffset = rectScrollingArea.Right - mouseX; @@ -8898,43 +8898,43 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous else { // Correct mouse's X - no scrolling can be performed - if (!this.RightToLeftInternal && mouseX < this.layout.Data.Left) + if (!RightToLeftInternal && mouseX < layout.Data.Left) { - mouseX = this.layout.Data.Left + 1; + mouseX = layout.Data.Left + 1; recomputeHitTestInfo = true; } - else if (this.RightToLeftInternal && mouseX > this.layout.Data.Right) + else if (RightToLeftInternal && mouseX > layout.Data.Right) { - mouseX = this.layout.Data.Right - 1; + mouseX = layout.Data.Right - 1; recomputeHitTestInfo = true; } } } - else if ((!this.RightToLeftInternal && mouseX > rectScrollingArea.Right) || - (this.RightToLeftInternal && mouseX < rectScrollingArea.Left)) + else if ((!RightToLeftInternal && mouseX > rectScrollingArea.Right) || + (RightToLeftInternal && mouseX < rectScrollingArea.Left)) { // Mouse's X is on the right of scrolling bands (LTR) - if (this.displayedBandsInfo.FirstDisplayedScrollingCol >= 0 && - (this.displayedBandsInfo.LastTotallyDisplayedScrollingCol == -1 || - this.Columns.GetNextColumn(this.Columns[this.displayedBandsInfo.LastTotallyDisplayedScrollingCol], DataGridViewElementStates.Visible, DataGridViewElementStates.None) != null)) + if (displayedBandsInfo.FirstDisplayedScrollingCol >= 0 && + (displayedBandsInfo.LastTotallyDisplayedScrollingCol == -1 || + Columns.GetNextColumn(Columns[displayedBandsInfo.LastTotallyDisplayedScrollingCol], DataGridViewElementStates.Visible, DataGridViewElementStates.None) != null)) { - DataGridViewColumn newFirstVisibleScrollingCol = this.Columns.GetNextColumn(this.Columns[this.displayedBandsInfo.FirstDisplayedScrollingCol], + DataGridViewColumn newFirstVisibleScrollingCol = Columns.GetNextColumn(Columns[displayedBandsInfo.FirstDisplayedScrollingCol], DataGridViewElementStates.Visible, DataGridViewElementStates.None); int newColOffset = 0; - for (DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible, + for (DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); dataGridViewColumn != newFirstVisibleScrollingCol; - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None)) { newColOffset += dataGridViewColumn.Thickness; } - if (this.HorizontalOffset != newColOffset) + if (HorizontalOffset != newColOffset) { // xOffset strictly positive - if (this.RightToLeftInternal) + if (RightToLeftInternal) { // Left scrolling is required xOffset = rectScrollingArea.Left - mouseX; @@ -8948,7 +8948,7 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous else { // Correct mouse's X - no scrolling can be performed - if (this.RightToLeftInternal) + if (RightToLeftInternal) { mouseX = rectScrollingArea.Left + 1; } @@ -8962,7 +8962,7 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous else { // Correct mouse's X - no scrolling can be performed - if (this.RightToLeftInternal) + if (RightToLeftInternal) { mouseX = rectScrollingArea.Left + 1; } @@ -8990,22 +8990,22 @@ private bool GetOutOfBoundCorrectedHitTestInfo(ref HitTestInfo hti, ref int mous internal override Size GetPreferredSizeCore(Size proposedConstraints) { - int bordersAndPaddingWidth = 2 * (this.BorderWidth + this.Padding.Size.Width); - int bordersAndPaddingHeight = 2 * (this.BorderWidth + this.Padding.Size.Height); + int bordersAndPaddingWidth = 2 * (BorderWidth + Padding.Size.Width); + int bordersAndPaddingHeight = 2 * (BorderWidth + Padding.Size.Height); - bool allowHorizScrollbar = (this.scrollBars == ScrollBars.Both) || (this.scrollBars == ScrollBars.Horizontal); - bool allowVertScrollbar = (this.scrollBars == ScrollBars.Both) || (this.scrollBars == ScrollBars.Vertical); + bool allowHorizScrollbar = (scrollBars == ScrollBars.Both) || (scrollBars == ScrollBars.Horizontal); + bool allowVertScrollbar = (scrollBars == ScrollBars.Both) || (scrollBars == ScrollBars.Vertical); int minimumWidth = 16 + bordersAndPaddingWidth; if (allowVertScrollbar) { - minimumWidth += this.vertScrollBar.Width; + minimumWidth += vertScrollBar.Width; } - if (this.RowHeadersVisible) + if (RowHeadersVisible) { - minimumWidth += this.RowHeadersWidth; + minimumWidth += RowHeadersWidth; } - int preferredWidth = Math.Min(minimumWidth + this.Columns.GetColumnsWidth(DataGridViewElementStates.Visible), proposedConstraints.Width); + int preferredWidth = Math.Min(minimumWidth + Columns.GetColumnsWidth(DataGridViewElementStates.Visible), proposedConstraints.Width); if (preferredWidth < minimumWidth) { preferredWidth = minimumWidth; @@ -9014,13 +9014,13 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) int minimumHeight = 16 + bordersAndPaddingHeight; if (allowHorizScrollbar) { - minimumHeight += this.horizScrollBar.Height; + minimumHeight += horizScrollBar.Height; } - if (this.ColumnHeadersVisible) + if (ColumnHeadersVisible) { - minimumHeight += this.ColumnHeadersHeight; + minimumHeight += ColumnHeadersHeight; } - int preferredHeight = Math.Min(minimumHeight + this.Rows.GetRowsHeight(DataGridViewElementStates.Visible), proposedConstraints.Height); + int preferredHeight = Math.Min(minimumHeight + Rows.GetRowsHeight(DataGridViewElementStates.Visible), proposedConstraints.Height); if (preferredHeight < minimumHeight) { preferredHeight = minimumHeight; @@ -9032,7 +9032,7 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) // Rectangle returned includes the potential row header public Rectangle GetRowDisplayRectangle(int rowIndex, bool cutOverflow) { - if (rowIndex < 0 || rowIndex >= this.Rows.Count) + if (rowIndex < 0 || rowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } @@ -9041,18 +9041,18 @@ public Rectangle GetRowDisplayRectangle(int rowIndex, bool cutOverflow) private Rectangle GetRowDisplayRectanglePrivate(int rowIndex, bool cutOverflow) { - Debug.Assert(rowIndex >= 0 && rowIndex < this.Rows.Count); + Debug.Assert(rowIndex >= 0 && rowIndex < Rows.Count); - if ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Displayed) == 0) + if ((Rows.GetRowState(rowIndex) & DataGridViewElementStates.Displayed) == 0) { return Rectangle.Empty; } - Rectangle data = this.layout.Data; + Rectangle data = layout.Data; int cy = data.Y; bool rowFound = false; int indexTmp; - for (indexTmp = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + for (indexTmp = Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); indexTmp != -1 && !rowFound; ) { @@ -9066,14 +9066,14 @@ private Rectangle GetRowDisplayRectanglePrivate(int rowIndex, bool cutOverflow) } else { - cy += this.Rows.SharedRow(indexTmp).GetHeight(indexTmp); - indexTmp = this.Rows.GetNextRow(indexTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + cy += Rows.SharedRow(indexTmp).GetHeight(indexTmp); + indexTmp = Rows.GetNextRow(indexTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); } } - if (!rowFound && this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0) + if (!rowFound && displayedBandsInfo.FirstDisplayedScrollingRow >= 0) { - for (indexTmp = this.displayedBandsInfo.FirstDisplayedScrollingRow; + for (indexTmp = displayedBandsInfo.FirstDisplayedScrollingRow; indexTmp != -1 && !rowFound; ) { @@ -9087,8 +9087,8 @@ private Rectangle GetRowDisplayRectanglePrivate(int rowIndex, bool cutOverflow) } else { - cy += this.Rows.SharedRow(indexTmp).GetHeight(indexTmp); - indexTmp = this.Rows.GetNextRow(indexTmp, DataGridViewElementStates.Visible); + cy += Rows.SharedRow(indexTmp).GetHeight(indexTmp); + indexTmp = Rows.GetNextRow(indexTmp, DataGridViewElementStates.Visible); } } } @@ -9096,25 +9096,25 @@ private Rectangle GetRowDisplayRectanglePrivate(int rowIndex, bool cutOverflow) if (rowFound) { int displayHeight; - if (cutOverflow && cy + this.Rows.SharedRow(indexTmp).GetHeight(indexTmp) > data.Bottom) + if (cutOverflow && cy + Rows.SharedRow(indexTmp).GetHeight(indexTmp) > data.Bottom) { displayHeight = data.Bottom - cy; } else { - displayHeight = this.Rows.SharedRow(indexTmp).GetHeight(indexTmp); + displayHeight = Rows.SharedRow(indexTmp).GetHeight(indexTmp); } Rectangle rowRect = new Rectangle(data.X, cy, data.Width, displayHeight); - if (this.layout.RowHeadersVisible) + if (layout.RowHeadersVisible) { - rowRect.Width += this.layout.RowHeaders.Width; - if (!this.RightToLeftInternal) + rowRect.Width += layout.RowHeaders.Width; + if (!RightToLeftInternal) { - rowRect.X -= this.layout.RowHeaders.Width; + rowRect.X -= layout.RowHeaders.Width; } } return rowRect; @@ -9125,7 +9125,7 @@ private Rectangle GetRowDisplayRectanglePrivate(int rowIndex, bool cutOverflow) private int GetRowIndexFromY(int y, out int yRowTopEdge) { - Rectangle data = this.layout.Data; + Rectangle data = layout.Data; Debug.Assert(y >= data.Y - 1 && y < data.Bottom, "y must be inside the vertical bounds of the data area."); if (y == data.Y - 1) @@ -9137,37 +9137,37 @@ private int GetRowIndexFromY(int y, out int yRowTopEdge) int cy = data.Y; // first try to match y against a frozen rows - int indexTmp = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int indexTmp = Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); while (indexTmp != -1 && cy < data.Bottom) { - rowHeight = this.Rows.SharedRow(indexTmp).GetHeight(indexTmp); + rowHeight = Rows.SharedRow(indexTmp).GetHeight(indexTmp); cy += rowHeight; if (cy > y) { yRowTopEdge = cy - rowHeight; return indexTmp; } - indexTmp = this.Rows.GetNextRow(indexTmp, + indexTmp = Rows.GetNextRow(indexTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); } // second try to match y against a scrolling row - if (this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0) + if (displayedBandsInfo.FirstDisplayedScrollingRow >= 0) { - indexTmp = this.displayedBandsInfo.FirstDisplayedScrollingRow; - Debug.Assert((this.Rows.GetRowState(indexTmp) & DataGridViewElementStates.Visible) != 0 && - (this.Rows.GetRowState(indexTmp) & DataGridViewElementStates.Frozen) == 0); + indexTmp = displayedBandsInfo.FirstDisplayedScrollingRow; + Debug.Assert((Rows.GetRowState(indexTmp) & DataGridViewElementStates.Visible) != 0 && + (Rows.GetRowState(indexTmp) & DataGridViewElementStates.Frozen) == 0); while (indexTmp != -1 && cy < data.Bottom) { - rowHeight = this.Rows.SharedRow(indexTmp).GetHeight(indexTmp); + rowHeight = Rows.SharedRow(indexTmp).GetHeight(indexTmp); cy += rowHeight; if (cy > y) { yRowTopEdge = cy - rowHeight; return indexTmp; } - indexTmp = this.Rows.GetNextRow(indexTmp, + indexTmp = Rows.GetNextRow(indexTmp, DataGridViewElementStates.Visible); } } @@ -9207,31 +9207,31 @@ private static int GetRowScrollRate(int yOffset) /// internal int GetRowYFromIndex(int index) { - Debug.Assert(index >= 0 && index < this.Rows.Count); - Debug.Assert((this.Rows.GetRowState(index) & DataGridViewElementStates.Visible) != 0); + Debug.Assert(index >= 0 && index < Rows.Count); + Debug.Assert((Rows.GetRowState(index) & DataGridViewElementStates.Visible) != 0); - int y = this.layout.Data.Y; + int y = layout.Data.Y; - int indexTmp = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int indexTmp = Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); while (indexTmp != -1) { if (index == indexTmp) { return y; } - y += this.Rows.SharedRow(indexTmp).GetHeight(indexTmp); - indexTmp = this.Rows.GetNextRow(indexTmp, + y += Rows.SharedRow(indexTmp).GetHeight(indexTmp); + indexTmp = Rows.GetNextRow(indexTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); } int yFirstVisibleScrollingRow = y; - if (this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0) + if (displayedBandsInfo.FirstDisplayedScrollingRow >= 0) { - if (index >= this.displayedBandsInfo.FirstDisplayedScrollingRow) + if (index >= displayedBandsInfo.FirstDisplayedScrollingRow) { // index is part of the scrolling rows below the frozen rows - indexTmp = this.displayedBandsInfo.FirstDisplayedScrollingRow; + indexTmp = displayedBandsInfo.FirstDisplayedScrollingRow; } else { @@ -9242,14 +9242,14 @@ internal int GetRowYFromIndex(int index) else { // frozen rows cover all the rows real-estate. Look for index starting at the first visible non-frozen row. - indexTmp = this.Rows.GetFirstRow(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); + indexTmp = Rows.GetFirstRow(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); Debug.Assert(indexTmp != -1); } if (indexTmp != -1) { - Debug.Assert((this.Rows.GetRowState(indexTmp) & DataGridViewElementStates.Visible) != 0 && - (this.Rows.GetRowState(indexTmp) & DataGridViewElementStates.Frozen) == 0); + Debug.Assert((Rows.GetRowState(indexTmp) & DataGridViewElementStates.Visible) != 0 && + (Rows.GetRowState(indexTmp) & DataGridViewElementStates.Frozen) == 0); while (indexTmp != -1) { @@ -9257,25 +9257,25 @@ internal int GetRowYFromIndex(int index) { return y; } - y += this.Rows.SharedRow(indexTmp).GetHeight(indexTmp); - indexTmp = this.Rows.GetNextRow(indexTmp, DataGridViewElementStates.Visible); + y += Rows.SharedRow(indexTmp).GetHeight(indexTmp); + indexTmp = Rows.GetNextRow(indexTmp, DataGridViewElementStates.Visible); } } // Row is completely hidden behind frozen rows or on top of control y = yFirstVisibleScrollingRow; - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow != -1); - indexTmp = this.Rows.GetPreviousRow(this.displayedBandsInfo.FirstDisplayedScrollingRow, + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingRow != -1); + indexTmp = Rows.GetPreviousRow(displayedBandsInfo.FirstDisplayedScrollingRow, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); while (indexTmp != -1) { - y -= this.Rows.SharedRow(indexTmp).GetHeight(indexTmp); + y -= Rows.SharedRow(indexTmp).GetHeight(indexTmp); if (index == indexTmp) { return y; } - indexTmp = this.Rows.GetPreviousRow(indexTmp, + indexTmp = Rows.GetPreviousRow(indexTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); } @@ -9286,17 +9286,17 @@ internal int GetRowYFromIndex(int index) private bool GetTabKeyEffective(bool shift, bool ctrl) { - if (this.StandardTab) + if (StandardTab) { return ctrl && - !((!shift && (!this.VisibleCellExists || this.CurrentCellIsLastVisibleCell)) || - (shift && (!this.VisibleCellExists || this.CurrentCellIsFirstVisibleCell))); + !((!shift && (!VisibleCellExists || CurrentCellIsLastVisibleCell)) || + (shift && (!VisibleCellExists || CurrentCellIsFirstVisibleCell))); } else { return !ctrl && - !((!shift && (!this.VisibleCellExists || this.CurrentCellIsLastVisibleCell)) || - (shift && (!this.VisibleCellExists || this.CurrentCellIsFirstVisibleCell))); + !((!shift && (!VisibleCellExists || CurrentCellIsLastVisibleCell)) || + (shift && (!VisibleCellExists || CurrentCellIsFirstVisibleCell))); } } @@ -9304,67 +9304,67 @@ public HitTestInfo HitTest(int x, int y) { HitTestInfo hti = new HitTestInfo(); - if (!this.layout.Inside.Contains(x, y)) + if (!layout.Inside.Contains(x, y)) { return hti; } - if (this.horizScrollBar != null && this.horizScrollBar.Visible && this.horizScrollBar.Bounds.Contains(x, y)) + if (horizScrollBar != null && horizScrollBar.Visible && horizScrollBar.Bounds.Contains(x, y)) { hti.type = DataGridViewHitTestType.HorizontalScrollBar; return hti; } - if (this.vertScrollBar != null && this.vertScrollBar.Visible && this.vertScrollBar.Bounds.Contains(x, y)) + if (vertScrollBar != null && vertScrollBar.Visible && vertScrollBar.Bounds.Contains(x, y)) { hti.type = DataGridViewHitTestType.VerticalScrollBar; return hti; } - if (this.layout.TopLeftHeader.Contains(x, y)) + if (layout.TopLeftHeader.Contains(x, y)) { hti.type = DataGridViewHitTestType.TopLeftHeader; hti.typeInternal = DataGridViewHitTestTypeInternal.TopLeftHeader; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - hti.colStart = this.layout.TopLeftHeader.Right - 1; + hti.colStart = layout.TopLeftHeader.Right - 1; } else { - hti.colStart = this.layout.TopLeftHeader.Left; + hti.colStart = layout.TopLeftHeader.Left; } - hti.rowStart = this.layout.TopLeftHeader.Top; - if ((!this.RightToLeftInternal && this.layout.TopLeftHeader.Right - x < DATAGRIDVIEW_columnSizingHotZone) || - (this.RightToLeftInternal && x - this.layout.TopLeftHeader.Left < DATAGRIDVIEW_columnSizingHotZone)) + hti.rowStart = layout.TopLeftHeader.Top; + if ((!RightToLeftInternal && layout.TopLeftHeader.Right - x < DATAGRIDVIEW_columnSizingHotZone) || + (RightToLeftInternal && x - layout.TopLeftHeader.Left < DATAGRIDVIEW_columnSizingHotZone)) { //hti.edge = DataGridViewHitTestTypeCloseEdge.Right; - if (this.RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing) + if (RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing) { hti.typeInternal = DataGridViewHitTestTypeInternal.TopLeftHeaderResizeLeft; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - hti.mouseBarOffset = this.layout.TopLeftHeader.Left - x - 1; + hti.mouseBarOffset = layout.TopLeftHeader.Left - x - 1; } else { - hti.mouseBarOffset = this.layout.TopLeftHeader.Right - x - 1; + hti.mouseBarOffset = layout.TopLeftHeader.Right - x - 1; } } } - else if (this.layout.TopLeftHeader.Top + this.layout.TopLeftHeader.Height - y < DATAGRIDVIEW_rowSizingHotZone) + else if (layout.TopLeftHeader.Top + layout.TopLeftHeader.Height - y < DATAGRIDVIEW_rowSizingHotZone) { //hti.edge = DataGridViewHitTestTypeCloseEdge.Bottom; - if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing) + if (ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing) { hti.typeInternal = DataGridViewHitTestTypeInternal.TopLeftHeaderResizeTop; - hti.mouseBarOffset = this.layout.TopLeftHeader.Top + this.layout.TopLeftHeader.Height - y - 1; + hti.mouseBarOffset = layout.TopLeftHeader.Top + layout.TopLeftHeader.Height - y - 1; } } return hti; } // check for column resize / insertion - if (this.layout.ColumnHeaders.Contains(x, y)) + if (layout.ColumnHeaders.Contains(x, y)) { int xColumnLeftEdge; // this is actually the right edge in RTL mode hti.col = GetColumnIndexFromX(x, out xColumnLeftEdge); @@ -9375,14 +9375,14 @@ public HitTestInfo HitTest(int x, int y) Debug.Assert(xColumnLeftEdge == GetColumnXFromIndex(hti.col)); hti.type = DataGridViewHitTestType.ColumnHeader; hti.typeInternal = DataGridViewHitTestTypeInternal.ColumnHeader; - hti.rowStart = this.layout.ColumnHeaders.Top; + hti.rowStart = layout.ColumnHeaders.Top; hti.colStart = xColumnLeftEdge; - int columnWidth = this.Columns[hti.col].Thickness; - if ((!this.RightToLeftInternal && xColumnLeftEdge + columnWidth - x < DATAGRIDVIEW_columnSizingHotZone) || - (this.RightToLeftInternal && x - xColumnLeftEdge + columnWidth < DATAGRIDVIEW_columnSizingHotZone)) + int columnWidth = Columns[hti.col].Thickness; + if ((!RightToLeftInternal && xColumnLeftEdge + columnWidth - x < DATAGRIDVIEW_columnSizingHotZone) || + (RightToLeftInternal && x - xColumnLeftEdge + columnWidth < DATAGRIDVIEW_columnSizingHotZone)) { //hti.edge = DataGridViewHitTestTypeCloseEdge.Right; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { hti.mouseBarOffset = xColumnLeftEdge - columnWidth - x + 1; } @@ -9390,7 +9390,7 @@ public HitTestInfo HitTest(int x, int y) { hti.mouseBarOffset = xColumnLeftEdge + columnWidth - x - 1; } - DataGridViewColumn dataGridViewColumn = this.Columns[hti.col]; + DataGridViewColumn dataGridViewColumn = Columns[hti.col]; if (dataGridViewColumn.Resizable == DataGridViewTriState.True && (dataGridViewColumn.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.None || dataGridViewColumn.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill)) { @@ -9401,21 +9401,21 @@ public HitTestInfo HitTest(int x, int y) hti.typeInternal = DataGridViewHitTestTypeInternal.ColumnHeaderRight; } } - else if ((!this.RightToLeftInternal && x - xColumnLeftEdge < DATAGRIDVIEW_columnSizingHotZone) || - (this.RightToLeftInternal && xColumnLeftEdge - x < DATAGRIDVIEW_columnSizingHotZone)) + else if ((!RightToLeftInternal && x - xColumnLeftEdge < DATAGRIDVIEW_columnSizingHotZone) || + (RightToLeftInternal && xColumnLeftEdge - x < DATAGRIDVIEW_columnSizingHotZone)) { //hti.edge = DataGridViewHitTestTypeCloseEdge.Left; DataGridViewColumn dataGridViewColumn = null; - dataGridViewColumn = this.Columns.GetPreviousColumn(this.Columns[hti.col], + dataGridViewColumn = Columns.GetPreviousColumn(Columns[hti.col], DataGridViewElementStates.Visible, DataGridViewElementStates.None); //} if (dataGridViewColumn != null) { hti.adjacentCol = dataGridViewColumn.Index; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { hti.mouseBarOffset = xColumnLeftEdge - x + 1; } @@ -9435,10 +9435,10 @@ public HitTestInfo HitTest(int x, int y) } else { - if (this.RowHeadersVisible && this.RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing) + if (RowHeadersVisible && RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing) { hti.typeInternal = DataGridViewHitTestTypeInternal.TopLeftHeaderResizeRight; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { hti.mouseBarOffset = xColumnLeftEdge - x; } @@ -9453,19 +9453,19 @@ public HitTestInfo HitTest(int x, int y) } } } - else if (this.layout.ColumnHeaders.Bottom - y < DATAGRIDVIEW_rowSizingHotZone) + else if (layout.ColumnHeaders.Bottom - y < DATAGRIDVIEW_rowSizingHotZone) { //hti.edge = DataGridViewHitTestTypeCloseEdge.Bottom; - if (/*!this.RowHeadersVisible &&*/ this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing) + if (/*!this.RowHeadersVisible &&*/ ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing) { hti.typeInternal = DataGridViewHitTestTypeInternal.ColumnHeadersResizeBottom; - hti.mouseBarOffset = this.layout.ColumnHeaders.Bottom - y - 1; + hti.mouseBarOffset = layout.ColumnHeaders.Bottom - y - 1; } } } // check for row resize - if (this.layout.RowHeaders.Contains(x, y)) + if (layout.RowHeaders.Contains(x, y)) { int yRowTopEdge; hti.row = GetRowIndexFromY(y, out yRowTopEdge); @@ -9477,20 +9477,20 @@ public HitTestInfo HitTest(int x, int y) hti.type = DataGridViewHitTestType.RowHeader; hti.typeInternal = DataGridViewHitTestTypeInternal.RowHeader; hti.rowStart = yRowTopEdge; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - hti.colStart = this.layout.RowHeaders.Right - 1; + hti.colStart = layout.RowHeaders.Right - 1; } else { - hti.colStart = this.layout.RowHeaders.Left; + hti.colStart = layout.RowHeaders.Left; } - int rowHeight = this.Rows.SharedRow(hti.row).GetHeight(hti.row); + int rowHeight = Rows.SharedRow(hti.row).GetHeight(hti.row); if (yRowTopEdge + rowHeight - y < DATAGRIDVIEW_rowSizingHotZone) { //hti.edge = DataGridViewHitTestTypeCloseEdge.Bottom; - if (RowIsResizable(hti.row) && this.AutoSizeRowsMode == DataGridViewAutoSizeRowsMode.None) + if (RowIsResizable(hti.row) && AutoSizeRowsMode == DataGridViewAutoSizeRowsMode.None) { hti.typeInternal = DataGridViewHitTestTypeInternal.RowResizeBottom; hti.mouseBarOffset = yRowTopEdge + rowHeight - y - 1; @@ -9500,13 +9500,13 @@ public HitTestInfo HitTest(int x, int y) { //hti.edge = DataGridViewHitTestTypeCloseEdge.Top; int indexTmp = -1; - if (hti.row != this.displayedBandsInfo.FirstDisplayedScrollingRow || this.displayedBandsInfo.NumDisplayedFrozenRows > 0) + if (hti.row != displayedBandsInfo.FirstDisplayedScrollingRow || displayedBandsInfo.NumDisplayedFrozenRows > 0) { - indexTmp = this.Rows.GetPreviousRow(hti.row, DataGridViewElementStates.Visible); + indexTmp = Rows.GetPreviousRow(hti.row, DataGridViewElementStates.Visible); } if (indexTmp != -1) { - if (RowIsResizable(indexTmp) && this.AutoSizeRowsMode == DataGridViewAutoSizeRowsMode.None) + if (RowIsResizable(indexTmp) && AutoSizeRowsMode == DataGridViewAutoSizeRowsMode.None) { hti.typeInternal = DataGridViewHitTestTypeInternal.RowResizeTop; hti.adjacentRow = indexTmp; @@ -9515,33 +9515,33 @@ public HitTestInfo HitTest(int x, int y) } else { - if (this.ColumnHeadersVisible && this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing) + if (ColumnHeadersVisible && ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing) { hti.typeInternal = DataGridViewHitTestTypeInternal.TopLeftHeaderResizeBottom; hti.mouseBarOffset = yRowTopEdge - y - 1; } } } - else if ((!this.RightToLeftInternal && this.layout.RowHeaders.Right - x < DATAGRIDVIEW_columnSizingHotZone) || - (this.RightToLeftInternal && x - this.layout.RowHeaders.Left < DATAGRIDVIEW_columnSizingHotZone)) + else if ((!RightToLeftInternal && layout.RowHeaders.Right - x < DATAGRIDVIEW_columnSizingHotZone) || + (RightToLeftInternal && x - layout.RowHeaders.Left < DATAGRIDVIEW_columnSizingHotZone)) { //hti.edge = DataGridViewHitTestTypeCloseEdge.Right; - if (this.RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing) + if (RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing) { hti.typeInternal = DataGridViewHitTestTypeInternal.RowHeadersResizeRight; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - hti.mouseBarOffset = this.layout.RowHeaders.Left - x - 1; + hti.mouseBarOffset = layout.RowHeaders.Left - x - 1; } else { - hti.mouseBarOffset = this.layout.RowHeaders.Right - x - 1; + hti.mouseBarOffset = layout.RowHeaders.Right - x - 1; } } } } - if (this.layout.Data.Contains(x, y)) + if (layout.Data.Contains(x, y)) { int xColumnLeftEdge, yRowTopEdge; hti.col = GetColumnIndexFromX(x, out xColumnLeftEdge); @@ -9556,13 +9556,13 @@ public HitTestInfo HitTest(int x, int y) hti.typeInternal = DataGridViewHitTestTypeInternal.Cell; hti.rowStart = yRowTopEdge; hti.colStart = xColumnLeftEdge; - if (!this.ColumnHeadersVisible) + if (!ColumnHeadersVisible) { - int columnWidth = this.Columns[hti.col].Thickness; - if ((!this.RightToLeftInternal && xColumnLeftEdge + columnWidth - x < DATAGRIDVIEW_columnSizingHotZone) || - (this.RightToLeftInternal && x - xColumnLeftEdge + columnWidth < DATAGRIDVIEW_columnSizingHotZone)) + int columnWidth = Columns[hti.col].Thickness; + if ((!RightToLeftInternal && xColumnLeftEdge + columnWidth - x < DATAGRIDVIEW_columnSizingHotZone) || + (RightToLeftInternal && x - xColumnLeftEdge + columnWidth < DATAGRIDVIEW_columnSizingHotZone)) { - if (this.RightToLeftInternal) + if (RightToLeftInternal) { hti.mouseBarOffset = xColumnLeftEdge - columnWidth - x + 1; } @@ -9570,7 +9570,7 @@ public HitTestInfo HitTest(int x, int y) { hti.mouseBarOffset = xColumnLeftEdge + columnWidth - x - 1; } - DataGridViewColumn dataGridViewColumn = this.Columns[hti.col]; + DataGridViewColumn dataGridViewColumn = Columns[hti.col]; if (dataGridViewColumn.Resizable == DataGridViewTriState.True && (dataGridViewColumn.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.None || dataGridViewColumn.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill)) { @@ -9578,20 +9578,20 @@ public HitTestInfo HitTest(int x, int y) } return hti; } - else if ((!this.RightToLeftInternal && x - xColumnLeftEdge < DATAGRIDVIEW_columnSizingHotZone) || - (this.RightToLeftInternal && xColumnLeftEdge - x < DATAGRIDVIEW_columnSizingHotZone)) + else if ((!RightToLeftInternal && x - xColumnLeftEdge < DATAGRIDVIEW_columnSizingHotZone) || + (RightToLeftInternal && xColumnLeftEdge - x < DATAGRIDVIEW_columnSizingHotZone)) { DataGridViewColumn dataGridViewColumn = null; - if (hti.col != this.displayedBandsInfo.FirstDisplayedScrollingCol || this.displayedBandsInfo.LastTotallyDisplayedScrollingCol >= 0) + if (hti.col != displayedBandsInfo.FirstDisplayedScrollingCol || displayedBandsInfo.LastTotallyDisplayedScrollingCol >= 0) { - dataGridViewColumn = this.Columns.GetPreviousColumn(this.Columns[hti.col], + dataGridViewColumn = Columns.GetPreviousColumn(Columns[hti.col], DataGridViewElementStates.Visible, DataGridViewElementStates.None); } if (dataGridViewColumn != null) { hti.adjacentCol = dataGridViewColumn.Index; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { hti.mouseBarOffset = xColumnLeftEdge - x + 1; } @@ -9608,10 +9608,10 @@ public HitTestInfo HitTest(int x, int y) } else { - if (this.RowHeadersVisible && this.RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing) + if (RowHeadersVisible && RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing) { hti.typeInternal = DataGridViewHitTestTypeInternal.RowHeadersResizeLeft; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { hti.mouseBarOffset = xColumnLeftEdge - x; } @@ -9624,17 +9624,17 @@ public HitTestInfo HitTest(int x, int y) } } } - else if ((!this.RightToLeftInternal && x - xColumnLeftEdge < DATAGRIDVIEW_columnSizingHotZone) || - (this.RightToLeftInternal && xColumnLeftEdge - x < DATAGRIDVIEW_columnSizingHotZone)) + else if ((!RightToLeftInternal && x - xColumnLeftEdge < DATAGRIDVIEW_columnSizingHotZone) || + (RightToLeftInternal && xColumnLeftEdge - x < DATAGRIDVIEW_columnSizingHotZone)) { - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); Debug.Assert(dataGridViewColumn != null); if (hti.col == dataGridViewColumn.Index && - this.RowHeadersVisible && - this.RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing) + RowHeadersVisible && + RowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing) { hti.typeInternal = DataGridViewHitTestTypeInternal.RowHeadersResizeLeft; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { hti.mouseBarOffset = xColumnLeftEdge - x; } @@ -9646,12 +9646,12 @@ public HitTestInfo HitTest(int x, int y) } } - if (!this.RowHeadersVisible) + if (!RowHeadersVisible) { - int rowHeight = this.Rows.SharedRow(hti.row).GetHeight(hti.row); + int rowHeight = Rows.SharedRow(hti.row).GetHeight(hti.row); if (yRowTopEdge + rowHeight - y < DATAGRIDVIEW_rowSizingHotZone) { - if (RowIsResizable(hti.row) && this.AutoSizeRowsMode == DataGridViewAutoSizeRowsMode.None) + if (RowIsResizable(hti.row) && AutoSizeRowsMode == DataGridViewAutoSizeRowsMode.None) { hti.typeInternal = DataGridViewHitTestTypeInternal.RowResizeBottom; hti.mouseBarOffset = yRowTopEdge + rowHeight - y - 1; @@ -9660,14 +9660,14 @@ public HitTestInfo HitTest(int x, int y) else if (y - yRowTopEdge < DATAGRIDVIEW_rowSizingHotZone) { int indexTmp = -1; - if (hti.row != this.displayedBandsInfo.FirstDisplayedScrollingRow || this.displayedBandsInfo.NumDisplayedFrozenRows > 0) + if (hti.row != displayedBandsInfo.FirstDisplayedScrollingRow || displayedBandsInfo.NumDisplayedFrozenRows > 0) { - indexTmp = this.Rows.GetPreviousRow(hti.row, + indexTmp = Rows.GetPreviousRow(hti.row, DataGridViewElementStates.Visible); } if (indexTmp != -1) { - if (RowIsResizable(indexTmp) && this.AutoSizeRowsMode == DataGridViewAutoSizeRowsMode.None) + if (RowIsResizable(indexTmp) && AutoSizeRowsMode == DataGridViewAutoSizeRowsMode.None) { hti.typeInternal = DataGridViewHitTestTypeInternal.RowResizeTop; hti.adjacentRow = indexTmp; @@ -9676,7 +9676,7 @@ public HitTestInfo HitTest(int x, int y) } else { - if (this.ColumnHeadersVisible && this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing) + if (ColumnHeadersVisible && ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing) { hti.typeInternal = DataGridViewHitTestTypeInternal.ColumnHeadersResizeTop; hti.mouseBarOffset = yRowTopEdge - y - 1; @@ -9686,11 +9686,11 @@ public HitTestInfo HitTest(int x, int y) } else if (y - yRowTopEdge < DATAGRIDVIEW_rowSizingHotZone) { - int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + int rowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); Debug.Assert(rowIndex >= 0); if (hti.row == rowIndex && - this.ColumnHeadersVisible && - this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing) + ColumnHeadersVisible && + ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing) { hti.typeInternal = DataGridViewHitTestTypeInternal.ColumnHeadersResizeTop; hti.mouseBarOffset = yRowTopEdge - y - 1; @@ -9708,7 +9708,7 @@ private void HorizScrollTimer_Tick(object sender, System.EventArgs e) private void HorizScrollTimerHandler() { - Debug.Assert(this.dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] || this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect]); + Debug.Assert(dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] || dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect]); Point ptMouse = PointToClient(Control.MousePosition); HitTestInfo hti = HitTest(ptMouse.X, ptMouse.Y); @@ -9719,24 +9719,24 @@ private void HorizScrollTimerHandler() { int absXOffset = Math.Abs(xOffset), normOffset = xOffset / absXOffset; ScrollColumns(normOffset); - this.horizScrollTimer.Interval = GetColumnScrollRate(absXOffset); - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect]) + horizScrollTimer.Interval = GetColumnScrollRate(absXOffset); + if (dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect]) { - hti = HitTest(ptMouse.X + (this.RightToLeftInternal ? 1 : -1) * (xOffset + normOffset), mouseY); + hti = HitTest(ptMouse.X + (RightToLeftInternal ? 1 : -1) * (xOffset + normOffset), mouseY); if (hti.col >= 0) { OnColumnSelectMouseMove(hti); } } - else if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect]) + else if (dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect]) { if (yOffset != 0) { - hti = HitTest(ptMouse.X + (this.RightToLeftInternal ? 1 : -1) * (xOffset + normOffset), ptMouse.Y - yOffset - (yOffset / Math.Abs(yOffset))); + hti = HitTest(ptMouse.X + (RightToLeftInternal ? 1 : -1) * (xOffset + normOffset), ptMouse.Y - yOffset - (yOffset / Math.Abs(yOffset))); } else { - hti = HitTest(ptMouse.X + (this.RightToLeftInternal ? 1 : -1) * (xOffset + normOffset), mouseY); + hti = HitTest(ptMouse.X + (RightToLeftInternal ? 1 : -1) * (xOffset + normOffset), mouseY); } if (hti.col >= 0 && hti.row >= 0) { @@ -9746,15 +9746,15 @@ private void HorizScrollTimerHandler() } else { - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] && hti.col >= 0) + if (dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] && hti.col >= 0) { OnColumnSelectMouseMove(hti); } - else if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect] && hti.col >= 0 && hti.row >= 0) + else if (dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect] && hti.col >= 0 && hti.row >= 0) { OnCellSelectMouseMove(hti); } - this.HorizScrollTimer.Enabled = false; + HorizScrollTimer.Enabled = false; } } } @@ -9764,21 +9764,21 @@ private bool InitializeEditingCellValue(ref DataGridViewCellStyle dataGridViewCe { DataGridViewDataErrorEventArgs dgvdee = null; // Save unedited value so we can restore it later if parsing of new value fails - this.uneditedFormattedValue = dataGridViewCell.GetFormattedValue(this.ptCurrentCell.Y, ref dataGridViewCellStyle, DataGridViewDataErrorContexts.Formatting); - this.dataGridViewState1[DATAGRIDVIEWSTATE1_ignoringEditingChanges] = true; + uneditedFormattedValue = dataGridViewCell.GetFormattedValue(ptCurrentCell.Y, ref dataGridViewCellStyle, DataGridViewDataErrorContexts.Formatting); + dataGridViewState1[DATAGRIDVIEWSTATE1_ignoringEditingChanges] = true; try { IDataGridViewEditingCell dataGridViewEditingCell = dataGridViewCell as IDataGridViewEditingCell; Debug.Assert(dataGridViewEditingCell != null); object currentFormattedValue = dataGridViewEditingCell.GetEditingCellFormattedValue(DataGridViewDataErrorContexts.Formatting); - if ((currentFormattedValue == null && this.uneditedFormattedValue != null) || - (currentFormattedValue != null && this.uneditedFormattedValue == null) || - (currentFormattedValue != null && !this.uneditedFormattedValue.Equals(currentFormattedValue))) + if ((currentFormattedValue == null && uneditedFormattedValue != null) || + (currentFormattedValue != null && uneditedFormattedValue == null) || + (currentFormattedValue != null && !uneditedFormattedValue.Equals(currentFormattedValue))) { - Debug.Assert(this.ptCurrentCell.X == dataGridViewCell.ColumnIndex); - dataGridViewCell = this.Rows[this.ptCurrentCell.Y].Cells[this.ptCurrentCell.X]; // unshare the edited cell + Debug.Assert(ptCurrentCell.X == dataGridViewCell.ColumnIndex); + dataGridViewCell = Rows[ptCurrentCell.Y].Cells[ptCurrentCell.X]; // unshare the edited cell dataGridViewEditingCell = dataGridViewCell as IDataGridViewEditingCell; - dataGridViewEditingCell.EditingCellFormattedValue = this.uneditedFormattedValue; + dataGridViewEditingCell.EditingCellFormattedValue = uneditedFormattedValue; dataGridViewEditingCell.EditingCellValueChanged = false; } } @@ -9788,14 +9788,14 @@ private bool InitializeEditingCellValue(ref DataGridViewCellStyle dataGridViewCe { throw; } - dgvdee = new DataGridViewDataErrorEventArgs(exception, this.ptCurrentCell.X, - this.ptCurrentCell.Y, + dgvdee = new DataGridViewDataErrorEventArgs(exception, ptCurrentCell.X, + ptCurrentCell.Y, DataGridViewDataErrorContexts.InitialValueRestoration); OnDataErrorInternal(dgvdee); } finally { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_ignoringEditingChanges] = false; + dataGridViewState1[DATAGRIDVIEWSTATE1_ignoringEditingChanges] = false; } if (dgvdee != null) { @@ -9812,16 +9812,16 @@ private bool InitializeEditingCellValue(ref DataGridViewCellStyle dataGridViewCe private bool InitializeEditingControlValue(ref DataGridViewCellStyle dataGridViewCellStyle, DataGridViewCell dataGridViewCell) { Debug.Assert(dataGridViewCell != null); - Debug.Assert(this.editingControl != null); + Debug.Assert(editingControl != null); DataGridViewDataErrorEventArgs dgvdee = null; - object initialFormattedValue = dataGridViewCell.GetFormattedValue(this.ptCurrentCell.Y, ref dataGridViewCellStyle, DataGridViewDataErrorContexts.Formatting); - this.dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlChanging] = true; - this.dataGridViewState1[DATAGRIDVIEWSTATE1_ignoringEditingChanges] = true; + object initialFormattedValue = dataGridViewCell.GetFormattedValue(ptCurrentCell.Y, ref dataGridViewCellStyle, DataGridViewDataErrorContexts.Formatting); + dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlChanging] = true; + dataGridViewState1[DATAGRIDVIEWSTATE1_ignoringEditingChanges] = true; try { - dataGridViewCell.InitializeEditingControl(this.ptCurrentCell.Y, initialFormattedValue, dataGridViewCellStyle); - ((IDataGridViewEditingControl)this.editingControl).EditingControlValueChanged = false; + dataGridViewCell.InitializeEditingControl(ptCurrentCell.Y, initialFormattedValue, dataGridViewCellStyle); + ((IDataGridViewEditingControl)editingControl).EditingControlValueChanged = false; } catch (Exception exception) { @@ -9829,15 +9829,15 @@ private bool InitializeEditingControlValue(ref DataGridViewCellStyle dataGridVie { throw; } - dgvdee = new DataGridViewDataErrorEventArgs(exception, this.ptCurrentCell.X, - this.ptCurrentCell.Y, + dgvdee = new DataGridViewDataErrorEventArgs(exception, ptCurrentCell.X, + ptCurrentCell.Y, DataGridViewDataErrorContexts.InitialValueRestoration); OnDataErrorInternal(dgvdee); } finally { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlChanging] = false; - this.dataGridViewState1[DATAGRIDVIEWSTATE1_ignoringEditingChanges] = false; + dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlChanging] = false; + dataGridViewState1[DATAGRIDVIEWSTATE1_ignoringEditingChanges] = false; } if (dgvdee != null) { @@ -9849,7 +9849,7 @@ private bool InitializeEditingControlValue(ref DataGridViewCellStyle dataGridVie } // Save unedited value so we can restore it later if parsing of new value fails - this.uneditedFormattedValue = initialFormattedValue; + uneditedFormattedValue = initialFormattedValue; return true; } @@ -9875,11 +9875,11 @@ private void InvalidateCellPrivate(DataGridViewCell dataGridViewCell) public void InvalidateCell(int columnIndex, int rowIndex) { - if (columnIndex < -1 || columnIndex >= this.Columns.Count) + if (columnIndex < -1 || columnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException(nameof(columnIndex)); } - if (rowIndex < -1 || rowIndex >= this.Rows.Count) + if (rowIndex < -1 || rowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } @@ -9888,7 +9888,7 @@ public void InvalidateCell(int columnIndex, int rowIndex) private void InvalidateCellPrivate(int columnIndex, int rowIndex) { - if (this.IsHandleCreated) + if (IsHandleCreated) { Rectangle cellDisplayRect = GetCellAdjustedDisplayRectangle(columnIndex, rowIndex, true); if (!cellDisplayRect.IsEmpty) @@ -9903,7 +9903,7 @@ private void InvalidateCellPrivate(int columnIndex, int rowIndex) /// public void InvalidateColumn(int columnIndex) { - if (columnIndex < 0 || columnIndex >= this.Columns.Count) + if (columnIndex < 0 || columnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException(nameof(columnIndex)); } @@ -9912,9 +9912,9 @@ public void InvalidateColumn(int columnIndex) internal void InvalidateColumnInternal(int columnIndex) { - Debug.Assert(columnIndex >= 0 && columnIndex < this.Columns.Count); + Debug.Assert(columnIndex >= 0 && columnIndex < Columns.Count); - if (this.IsHandleCreated) + if (IsHandleCreated) { Rectangle columnDisplayRect = GetColumnDisplayRectanglePrivate(columnIndex, true); if (!columnDisplayRect.IsEmpty) @@ -9926,9 +9926,9 @@ internal void InvalidateColumnInternal(int columnIndex) private void InvalidateData() { - if (this.IsHandleCreated) + if (IsHandleCreated) { - Invalidate(this.layout.Data); + Invalidate(layout.Data); } } @@ -9937,9 +9937,9 @@ private void InvalidateData() /// private void InvalidateInside() { - if (this.IsHandleCreated) + if (IsHandleCreated) { - Invalidate(this.layout.Inside); + Invalidate(layout.Inside); } } @@ -9948,7 +9948,7 @@ private void InvalidateInside() /// public void InvalidateRow(int rowIndex) { - if (rowIndex < 0 || rowIndex >= this.Rows.Count) + if (rowIndex < 0 || rowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } @@ -9957,9 +9957,9 @@ public void InvalidateRow(int rowIndex) private void InvalidateRowPrivate(int rowIndex) { - Debug.Assert(rowIndex >= 0 && rowIndex < this.Rows.Count); + Debug.Assert(rowIndex >= 0 && rowIndex < Rows.Count); - if (this.IsHandleCreated) + if (IsHandleCreated) { Rectangle rowDisplayRect = GetRowDisplayRectanglePrivate(rowIndex, true); if (!rowDisplayRect.IsEmpty) @@ -9971,8 +9971,8 @@ private void InvalidateRowPrivate(int rowIndex) private void InvalidateRowHeights() { - this.Rows.InvalidateCachedRowsHeights(); - if (this.IsHandleCreated) + Rows.InvalidateCachedRowsHeights(); + if (IsHandleCreated) { PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, false /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); Invalidate(); @@ -9982,10 +9982,10 @@ private void InvalidateRowHeights() private void InvalidateRows(int lo, int hi) { Debug.Assert(lo <= hi); - Debug.Assert(lo < this.Rows.Count); - Debug.Assert(hi < this.Rows.Count); + Debug.Assert(lo < Rows.Count); + Debug.Assert(hi < Rows.Count); - if (this.Rows.GetRowCount(DataGridViewElementStates.Visible) == 0) + if (Rows.GetRowCount(DataGridViewElementStates.Visible) == 0) { return; } @@ -9993,12 +9993,12 @@ private void InvalidateRows(int lo, int hi) Rectangle rowDisplayRect, data; int top, bottom; - data = this.layout.Data; + data = layout.Data; // If "lo" is not visible, then get the next visible row - if ((this.Rows.GetRowState(lo) & DataGridViewElementStates.Visible) == 0) + if ((Rows.GetRowState(lo) & DataGridViewElementStates.Visible) == 0) { - lo = this.Rows.GetNextRow(lo, DataGridViewElementStates.Visible); + lo = Rows.GetNextRow(lo, DataGridViewElementStates.Visible); } if (lo == -1) @@ -10008,34 +10008,34 @@ private void InvalidateRows(int lo, int hi) } // If "hi" is not visible, then get the previous visible row - if ((this.Rows.GetRowState(hi) & DataGridViewElementStates.Visible) == 0) + if ((Rows.GetRowState(hi) & DataGridViewElementStates.Visible) == 0) { - hi = this.Rows.GetPreviousRow(hi, DataGridViewElementStates.Visible); + hi = Rows.GetPreviousRow(hi, DataGridViewElementStates.Visible); } Debug.Assert(lo <= hi); Debug.Assert(lo > -1); - rowDisplayRect = this.GetRowDisplayRectangle(lo, true /*cutOverflow*/); + rowDisplayRect = GetRowDisplayRectangle(lo, true /*cutOverflow*/); if (rowDisplayRect.IsEmpty) { // The top row is offscreen - if ((this.Rows.GetRowState(lo) & DataGridViewElementStates.Frozen) != 0) + if ((Rows.GetRowState(lo) & DataGridViewElementStates.Frozen) != 0) { // "lo" is a frozen row which is offscreen. // This means that "lo" and any other row below it are offscreen. return; } - else if (this.displayedBandsInfo.NumDisplayedScrollingRows == 0) + else if (displayedBandsInfo.NumDisplayedScrollingRows == 0) { // "lo" and all the rows below are scrolling rows but no scrolling rows are displayed. return; } - else if (lo >= this.displayedBandsInfo.FirstDisplayedScrollingRow && - this.Rows.GetRowCount(DataGridViewElementStates.Visible, - this.displayedBandsInfo.FirstDisplayedScrollingRow, - lo) >= this.displayedBandsInfo.NumDisplayedScrollingRows) + else if (lo >= displayedBandsInfo.FirstDisplayedScrollingRow && + Rows.GetRowCount(DataGridViewElementStates.Visible, + displayedBandsInfo.FirstDisplayedScrollingRow, + lo) >= displayedBandsInfo.NumDisplayedScrollingRows) { // "lo" is a scrolling row whose coordinates are below the last visible row. return; @@ -10044,7 +10044,7 @@ private void InvalidateRows(int lo, int hi) { // "lo" is a scrolling row "behind" frozen rows. // Start invalidating at the top of the first displayed scrolling row. - top = this.GetRowDisplayRectangle(this.displayedBandsInfo.FirstDisplayedScrollingRow, true /*cutOverflow*/).Top; + top = GetRowDisplayRectangle(displayedBandsInfo.FirstDisplayedScrollingRow, true /*cutOverflow*/).Top; } } else @@ -10052,24 +10052,24 @@ private void InvalidateRows(int lo, int hi) top = rowDisplayRect.Top; } - rowDisplayRect = this.GetRowDisplayRectangle(hi, true /*cutOverflow*/); + rowDisplayRect = GetRowDisplayRectangle(hi, true /*cutOverflow*/); if (rowDisplayRect.IsEmpty) { // The bottom row is offscreen. - if ((this.Rows.GetRowState(hi) & DataGridViewElementStates.Frozen) == DataGridViewElementStates.Frozen) + if ((Rows.GetRowState(hi) & DataGridViewElementStates.Frozen) == DataGridViewElementStates.Frozen) { // "hi" is a frozen row offscreen and "lo" is a frozen row on screen. // Invalidate all the way to the bottom bottom = data.Bottom; } - else if (hi > this.displayedBandsInfo.FirstDisplayedScrollingRow) + else if (hi > displayedBandsInfo.FirstDisplayedScrollingRow) { // "hi" is a scrolling row offscreen which is beyond the firstDisplayedScrollingRow // Invalidate all the way to the bottom again. bottom = data.Bottom; } - else if (this.Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen) == 0) + else if (Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen) == 0) { // "hi" is a scrolling row above the first displayed scrolling row and there are no frozen rows. // There is nothing to invalidate. @@ -10082,16 +10082,16 @@ private void InvalidateRows(int lo, int hi) // Compute the bottom of the last displayed frozen row. // There may be invisible rows between the frozen rows. bottom = 0; - for (int i = 0; i < this.displayedBandsInfo.NumDisplayedFrozenRows;) + for (int i = 0; i < displayedBandsInfo.NumDisplayedFrozenRows;) { - if ((this.Rows.GetRowState(i) & DataGridViewElementStates.Visible) == 0) + if ((Rows.GetRowState(i) & DataGridViewElementStates.Visible) == 0) { continue; } - if (i == this.displayedBandsInfo.NumDisplayedFrozenRows - 1) + if (i == displayedBandsInfo.NumDisplayedFrozenRows - 1) { - bottom = this.GetRowDisplayRectangle(i, true /*cutOverflow*/).Bottom; + bottom = GetRowDisplayRectangle(i, true /*cutOverflow*/).Bottom; break; } @@ -10119,35 +10119,35 @@ private void InvalidateScrollBars() // invalidate the horizontal and the vertical scrollbars // note that the scrollbars can be null - this happens when // the control has been disposed. - if (this.horizScrollBar != null && this.horizScrollBar.Visible) + if (horizScrollBar != null && horizScrollBar.Visible) { - this.horizScrollBar.Invalidate(); + horizScrollBar.Invalidate(); } - if (this.vertScrollBar != null && this.vertScrollBar.Visible) + if (vertScrollBar != null && vertScrollBar.Visible) { - this.vertScrollBar.Invalidate(); + vertScrollBar.Invalidate(); } } private bool IsColumnOutOfBounds(int columnIndex) { - return columnIndex >= this.Columns.Count || columnIndex == -1; + return columnIndex >= Columns.Count || columnIndex == -1; } private bool IsInnerCellOutOfBounds(int columnIndex, int rowIndex) { - return columnIndex >= this.Columns.Count || rowIndex >= this.Rows.Count || columnIndex == -1 || rowIndex == -1; + return columnIndex >= Columns.Count || rowIndex >= Rows.Count || columnIndex == -1 || rowIndex == -1; } private bool IsRowOutOfBounds(int rowIndex) { - return rowIndex >= this.Rows.Count || rowIndex == -1; + return rowIndex >= Rows.Count || rowIndex == -1; } protected override bool IsInputChar(char charCode) { - if (this.editingControl != null && - this.dataGridViewState1[DATAGRIDVIEWSTATE1_forwardCharMessage]) + if (editingControl != null && + dataGridViewState1[DATAGRIDVIEWSTATE1_forwardCharMessage]) { // Do not process key press in ProcessDialogChar. return true; @@ -10168,7 +10168,7 @@ protected override bool IsInputKey(Keys keyData) { case Keys.Escape: { - return this.IsEscapeKeyEffective; + return IsEscapeKeyEffective; } case Keys.Tab: @@ -10198,9 +10198,9 @@ protected override bool IsInputKey(Keys keyData) case Keys.Space: { if ((keyData & (Keys.Control | Keys.Shift | Keys.Alt)) == Keys.Shift && - (this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect || - this.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) && - this.ptCurrentCell.X != -1) + (SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect || + SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) && + ptCurrentCell.X != -1) { return true; } @@ -10243,140 +10243,140 @@ private void LayoutScrollBars() // in without scrollbars and if they don't fit, we make // scrollbars visible and then fixup our regions for the // data. - bool allowHorizScrollbar = ((this.scrollBars == ScrollBars.Both) || (this.scrollBars == ScrollBars.Horizontal)) && - this.dataGridViewState2[DATAGRIDVIEWSTATE2_allowHorizontalScrollbar]; - bool allowVertScrollbar = (this.scrollBars == ScrollBars.Both) || (this.scrollBars == ScrollBars.Vertical); + bool allowHorizScrollbar = ((scrollBars == ScrollBars.Both) || (scrollBars == ScrollBars.Horizontal)) && + dataGridViewState2[DATAGRIDVIEWSTATE2_allowHorizontalScrollbar]; + bool allowVertScrollbar = (scrollBars == ScrollBars.Both) || (scrollBars == ScrollBars.Vertical); bool needHorizScrollbarWithoutVertScrollbar = false; bool needHorizScrollbar = false; bool needVertScrollbar = false; - bool rightToLeftInternal = this.RightToLeftInternal; + bool rightToLeftInternal = RightToLeftInternal; int oldfirstDisplayedScrollingRow; - int totalVisibleColCount = this.Columns.GetColumnCount(DataGridViewElementStates.Visible); - int totalVisibleRowCount = this.Rows.GetRowCount(DataGridViewElementStates.Visible); - int totalVisibleWidth = this.Columns.GetColumnsWidth(DataGridViewElementStates.Visible); - int totalVisibleFrozenWidth = this.Columns.GetColumnsWidth(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int totalVisibleColCount = Columns.GetColumnCount(DataGridViewElementStates.Visible); + int totalVisibleRowCount = Rows.GetRowCount(DataGridViewElementStates.Visible); + int totalVisibleWidth = Columns.GetColumnsWidth(DataGridViewElementStates.Visible); + int totalVisibleFrozenWidth = Columns.GetColumnsWidth(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); // Expensive call - dataGridView could have a mode where no row is resizable which would result in better perfs - int totalVisibleHeight = this.Rows.GetRowsHeight(DataGridViewElementStates.Visible); - int totalVisibleFrozenHeight = this.Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int totalVisibleHeight = Rows.GetRowsHeight(DataGridViewElementStates.Visible); + int totalVisibleFrozenHeight = Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); - int horizScrollBarHeight = this.horizScrollBar.Height = SystemInformation.HorizontalScrollBarHeight; - int vertScrollBarWidth = this.vertScrollBar.Width = SystemInformation.VerticalScrollBarWidth; + int horizScrollBarHeight = horizScrollBar.Height = SystemInformation.HorizontalScrollBarHeight; + int vertScrollBarWidth = vertScrollBar.Width = SystemInformation.VerticalScrollBarWidth; if (allowHorizScrollbar && - totalVisibleWidth > this.layout.Data.Width && totalVisibleFrozenWidth < this.layout.Data.Width && - horizScrollBarHeight <= this.layout.Data.Height) + totalVisibleWidth > layout.Data.Width && totalVisibleFrozenWidth < layout.Data.Width && + horizScrollBarHeight <= layout.Data.Height) { - int oldDataHeight = this.layout.Data.Height; - this.layout.Data.Height -= horizScrollBarHeight; - Debug.Assert(this.layout.Data.Height >= 0); + int oldDataHeight = layout.Data.Height; + layout.Data.Height -= horizScrollBarHeight; + Debug.Assert(layout.Data.Height >= 0); needHorizScrollbarWithoutVertScrollbar = needHorizScrollbar = true; - if (totalVisibleWidth - this.layout.Data.Width <= vertScrollBarWidth || - this.layout.Data.Width - totalVisibleFrozenWidth <= vertScrollBarWidth) + if (totalVisibleWidth - layout.Data.Width <= vertScrollBarWidth || + layout.Data.Width - totalVisibleFrozenWidth <= vertScrollBarWidth) { // Would we still need a horizontal scrollbar if there were a vertical one? - oldfirstDisplayedScrollingRow = this.displayedBandsInfo.FirstDisplayedScrollingRow; + oldfirstDisplayedScrollingRow = displayedBandsInfo.FirstDisplayedScrollingRow; ComputeVisibleRows(); - if (this.displayedBandsInfo.NumTotallyDisplayedFrozenRows == this.Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen) && - this.displayedBandsInfo.NumTotallyDisplayedScrollingRows != totalVisibleRowCount - this.Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen) && + if (displayedBandsInfo.NumTotallyDisplayedFrozenRows == Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen) && + displayedBandsInfo.NumTotallyDisplayedScrollingRows != totalVisibleRowCount - Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen) && (totalVisibleHeight - totalVisibleFrozenHeight != ComputeHeightOfFittingTrailingScrollingRows(totalVisibleFrozenHeight))) { - needHorizScrollbar = (totalVisibleFrozenWidth < this.layout.Data.Width - vertScrollBarWidth); + needHorizScrollbar = (totalVisibleFrozenWidth < layout.Data.Width - vertScrollBarWidth); } - this.displayedBandsInfo.FirstDisplayedScrollingRow = oldfirstDisplayedScrollingRow; + displayedBandsInfo.FirstDisplayedScrollingRow = oldfirstDisplayedScrollingRow; } if (needHorizScrollbar) { - if (this.layout.RowHeadersVisible) + if (layout.RowHeadersVisible) { - this.layout.RowHeaders.Height -= horizScrollBarHeight; - Debug.Assert(this.layout.RowHeaders.Height >= 0); + layout.RowHeaders.Height -= horizScrollBarHeight; + Debug.Assert(layout.RowHeaders.Height >= 0); } } else { // Restore old data height because turns out a horizontal scroll bar wouldn't make sense - this.layout.Data.Height = oldDataHeight; + layout.Data.Height = oldDataHeight; } } - oldfirstDisplayedScrollingRow = this.displayedBandsInfo.FirstDisplayedScrollingRow; + oldfirstDisplayedScrollingRow = displayedBandsInfo.FirstDisplayedScrollingRow; ComputeVisibleRows(); if (allowVertScrollbar && - this.displayedBandsInfo.NumTotallyDisplayedFrozenRows == this.Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen) && - this.displayedBandsInfo.NumTotallyDisplayedScrollingRows != totalVisibleRowCount - this.Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen) && + displayedBandsInfo.NumTotallyDisplayedFrozenRows == Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen) && + displayedBandsInfo.NumTotallyDisplayedScrollingRows != totalVisibleRowCount - Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen) && (totalVisibleHeight - totalVisibleFrozenHeight != ComputeHeightOfFittingTrailingScrollingRows(totalVisibleFrozenHeight)) && - this.layout.Data.Height > totalVisibleFrozenHeight && - vertScrollBarWidth <= this.layout.Data.Width) + layout.Data.Height > totalVisibleFrozenHeight && + vertScrollBarWidth <= layout.Data.Width) { - this.layout.Data.Width -= vertScrollBarWidth; - Debug.Assert(this.layout.Data.Width >= 0); + layout.Data.Width -= vertScrollBarWidth; + Debug.Assert(layout.Data.Width >= 0); if (rightToLeftInternal) { - this.layout.Data.X += vertScrollBarWidth; + layout.Data.X += vertScrollBarWidth; } - if (this.layout.ColumnHeadersVisible) + if (layout.ColumnHeadersVisible) { - this.layout.ColumnHeaders.Width -= vertScrollBarWidth; - Debug.Assert(this.layout.ColumnHeaders.Width >= 0); + layout.ColumnHeaders.Width -= vertScrollBarWidth; + Debug.Assert(layout.ColumnHeaders.Width >= 0); if (rightToLeftInternal) { - this.layout.ColumnHeaders.X += vertScrollBarWidth; + layout.ColumnHeaders.X += vertScrollBarWidth; } } needVertScrollbar = true; } - this.displayedBandsInfo.FirstDisplayedScrollingCol = ComputeFirstVisibleScrollingColumn(); + displayedBandsInfo.FirstDisplayedScrollingCol = ComputeFirstVisibleScrollingColumn(); // we compute the number of visible columns only after we set up the vertical scroll bar. ComputeVisibleColumns(); if (allowHorizScrollbar && needVertScrollbar && !needHorizScrollbar && - totalVisibleWidth > this.layout.Data.Width && totalVisibleFrozenWidth < this.layout.Data.Width && - horizScrollBarHeight <= this.layout.Data.Height) + totalVisibleWidth > layout.Data.Width && totalVisibleFrozenWidth < layout.Data.Width && + horizScrollBarHeight <= layout.Data.Height) { - this.displayedBandsInfo.FirstDisplayedScrollingRow = oldfirstDisplayedScrollingRow; - if (this.layout.ColumnHeadersVisible) + displayedBandsInfo.FirstDisplayedScrollingRow = oldfirstDisplayedScrollingRow; + if (layout.ColumnHeadersVisible) { - this.layout.ColumnHeaders.Width += vertScrollBarWidth; + layout.ColumnHeaders.Width += vertScrollBarWidth; if (rightToLeftInternal) { - this.layout.ColumnHeaders.X -= vertScrollBarWidth; + layout.ColumnHeaders.X -= vertScrollBarWidth; } } - this.layout.Data.Width += vertScrollBarWidth; + layout.Data.Width += vertScrollBarWidth; if (rightToLeftInternal) { - this.layout.Data.X -= vertScrollBarWidth; + layout.Data.X -= vertScrollBarWidth; } - this.layout.Data.Height -= horizScrollBarHeight; - Debug.Assert(this.layout.Data.Height >= 0); + layout.Data.Height -= horizScrollBarHeight; + Debug.Assert(layout.Data.Height >= 0); needVertScrollbar = false; ComputeVisibleRows(); - if (this.displayedBandsInfo.NumTotallyDisplayedFrozenRows == this.Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen) && - this.displayedBandsInfo.NumTotallyDisplayedScrollingRows != totalVisibleRowCount && + if (displayedBandsInfo.NumTotallyDisplayedFrozenRows == Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen) && + displayedBandsInfo.NumTotallyDisplayedScrollingRows != totalVisibleRowCount && (totalVisibleHeight - totalVisibleFrozenHeight != ComputeHeightOfFittingTrailingScrollingRows(totalVisibleFrozenHeight)) && - this.layout.Data.Height > totalVisibleFrozenHeight && - vertScrollBarWidth <= this.layout.Data.Width) + layout.Data.Height > totalVisibleFrozenHeight && + vertScrollBarWidth <= layout.Data.Width) { - this.layout.Data.Width -= vertScrollBarWidth; - Debug.Assert(this.layout.Data.Width >= 0); + layout.Data.Width -= vertScrollBarWidth; + Debug.Assert(layout.Data.Width >= 0); if (rightToLeftInternal) { - this.layout.Data.X += vertScrollBarWidth; + layout.Data.X += vertScrollBarWidth; } - if (this.layout.ColumnHeadersVisible) + if (layout.ColumnHeadersVisible) { - this.layout.ColumnHeaders.Width -= vertScrollBarWidth; - Debug.Assert(this.layout.ColumnHeaders.Width >= 0); + layout.ColumnHeaders.Width -= vertScrollBarWidth; + Debug.Assert(layout.ColumnHeaders.Width >= 0); if (rightToLeftInternal) { - this.layout.ColumnHeaders.X += vertScrollBarWidth; + layout.ColumnHeaders.X += vertScrollBarWidth; } } needVertScrollbar = true; @@ -10391,88 +10391,88 @@ private void LayoutScrollBars() } } - this.layout.ResizeBoxRect = new Rectangle(); + layout.ResizeBoxRect = new Rectangle(); if (needVertScrollbar && needHorizScrollbar) { - this.layout.ResizeBoxRect = new Rectangle( - rightToLeftInternal ? this.layout.Data.X - this.vertScrollBar.Width : this.layout.Data.Right, - this.layout.Data.Bottom, - this.vertScrollBar.Width, - this.horizScrollBar.Height); + layout.ResizeBoxRect = new Rectangle( + rightToLeftInternal ? layout.Data.X - vertScrollBar.Width : layout.Data.Right, + layout.Data.Bottom, + vertScrollBar.Width, + horizScrollBar.Height); } if (needHorizScrollbar && totalVisibleColCount > 0) { - int widthNotVisible = totalVisibleWidth - this.layout.Data.Width; - - this.horizScrollBar.Minimum = 0; - this.horizScrollBar.Maximum = totalVisibleWidth - totalVisibleFrozenWidth; - Debug.Assert(this.horizScrollBar.Maximum > 0); - this.horizScrollBar.SmallChange = 1; - this.horizScrollBar.LargeChange = Math.Max(totalVisibleWidth - totalVisibleFrozenWidth - widthNotVisible, 0); - this.horizScrollBar.Enabled = this.Enabled; - this.horizScrollBar.Bounds = new Rectangle( - rightToLeftInternal ? this.layout.Inside.X + this.layout.ResizeBoxRect.Width : this.layout.Inside.X, - this.layout.Data.Bottom, - this.layout.Inside.Width - this.layout.ResizeBoxRect.Width, - this.horizScrollBar.Height); - this.horizScrollBar.Visible = true; - this.horizScrollBar.Invalidate(); + int widthNotVisible = totalVisibleWidth - layout.Data.Width; + + horizScrollBar.Minimum = 0; + horizScrollBar.Maximum = totalVisibleWidth - totalVisibleFrozenWidth; + Debug.Assert(horizScrollBar.Maximum > 0); + horizScrollBar.SmallChange = 1; + horizScrollBar.LargeChange = Math.Max(totalVisibleWidth - totalVisibleFrozenWidth - widthNotVisible, 0); + horizScrollBar.Enabled = Enabled; + horizScrollBar.Bounds = new Rectangle( + rightToLeftInternal ? layout.Inside.X + layout.ResizeBoxRect.Width : layout.Inside.X, + layout.Data.Bottom, + layout.Inside.Width - layout.ResizeBoxRect.Width, + horizScrollBar.Height); + horizScrollBar.Visible = true; + horizScrollBar.Invalidate(); } else { - this.horizScrollBar.Visible = false; - this.HorizontalOffset = 0; + horizScrollBar.Visible = false; + HorizontalOffset = 0; - this.horizScrollBar.Enabled = false; - this.horizScrollBar.Minimum = 0; - this.horizScrollBar.Maximum = 1; - this.horizScrollBar.SmallChange = 1; - this.horizScrollBar.LargeChange = 1; - this.horizScrollBar.Value = 0; + horizScrollBar.Enabled = false; + horizScrollBar.Minimum = 0; + horizScrollBar.Maximum = 1; + horizScrollBar.SmallChange = 1; + horizScrollBar.LargeChange = 1; + horizScrollBar.Value = 0; } if (needVertScrollbar) { - int vertScrollBarTop = this.layout.Data.Y; - int vertScrollBarHeight = this.layout.Data.Height; - if (this.layout.ColumnHeadersVisible) + int vertScrollBarTop = layout.Data.Y; + int vertScrollBarHeight = layout.Data.Height; + if (layout.ColumnHeadersVisible) { - vertScrollBarTop = this.layout.ColumnHeaders.Y; - vertScrollBarHeight += this.layout.ColumnHeaders.Height; + vertScrollBarTop = layout.ColumnHeaders.Y; + vertScrollBarHeight += layout.ColumnHeaders.Height; } - else if (this.SingleHorizontalBorderAdded) + else if (SingleHorizontalBorderAdded) { vertScrollBarTop--; vertScrollBarHeight++; } - this.vertScrollBar.Minimum = 0; - this.vertScrollBar.Maximum = totalVisibleHeight - totalVisibleFrozenHeight; - Debug.Assert(this.vertScrollBar.Maximum > 0); - this.vertScrollBar.Value = ComputeHeightOfScrolledOffRows(); - this.vertScrollBar.LargeChange = this.layout.Data.Height - totalVisibleFrozenHeight; - this.vertScrollBar.Bounds = new Rectangle( - rightToLeftInternal ? this.layout.Data.X - this.vertScrollBar.Width : this.layout.Data.Right, + vertScrollBar.Minimum = 0; + vertScrollBar.Maximum = totalVisibleHeight - totalVisibleFrozenHeight; + Debug.Assert(vertScrollBar.Maximum > 0); + vertScrollBar.Value = ComputeHeightOfScrolledOffRows(); + vertScrollBar.LargeChange = layout.Data.Height - totalVisibleFrozenHeight; + vertScrollBar.Bounds = new Rectangle( + rightToLeftInternal ? layout.Data.X - vertScrollBar.Width : layout.Data.Right, vertScrollBarTop, - this.vertScrollBar.Width, + vertScrollBar.Width, vertScrollBarHeight); - this.vertScrollBar.Enabled = this.Enabled; - this.vertScrollBar.Visible = true; - this.vertScrollBar.Invalidate(); + vertScrollBar.Enabled = Enabled; + vertScrollBar.Visible = true; + vertScrollBar.Invalidate(); - this.verticalOffset = this.vertScrollBar.Value; + verticalOffset = vertScrollBar.Value; } else { - this.vertScrollBar.Visible = false; - this.verticalOffset = ComputeHeightOfScrolledOffRows(); + vertScrollBar.Visible = false; + verticalOffset = ComputeHeightOfScrolledOffRows(); - this.vertScrollBar.Enabled = false; - this.vertScrollBar.Minimum = 0; - this.vertScrollBar.Maximum = 1; - this.vertScrollBar.LargeChange = 1; - this.vertScrollBar.Value = 0; + vertScrollBar.Enabled = false; + vertScrollBar.Minimum = 0; + vertScrollBar.Maximum = 1; + vertScrollBar.LargeChange = 1; + vertScrollBar.Value = 0; } } finally @@ -10484,11 +10484,11 @@ private void LayoutScrollBars() private void MakeFirstDisplayedCellCurrentCell(bool includeNewRow) { // No current cell - try to set the first displayed cell to be the current one. - Point firstDisplayedCellAddress = this.FirstDisplayedCellAddress; + Point firstDisplayedCellAddress = FirstDisplayedCellAddress; if (firstDisplayedCellAddress.X != -1 && (includeNewRow || - !this.AllowUserToAddRowsInternal || - firstDisplayedCellAddress.Y != this.Rows.Count - 1)) + !AllowUserToAddRowsInternal || + firstDisplayedCellAddress.Y != Rows.Count - 1)) { bool success = SetAndSelectCurrentCellAddress(firstDisplayedCellAddress.X, firstDisplayedCellAddress.Y, @@ -10525,27 +10525,27 @@ private static DataGridViewAutoSizeRowMode MapAutoSizeRowsModeToRowMode(DataGrid private void MoveColumnHeadersOrRowResize(MouseEventArgs e) { - this.lastRowSplitBar = this.currentRowSplitBar; - this.currentRowSplitBar = e.Y; - Rectangle lastSplitBarRect = CalcRowResizeFeedbackRect(this.lastRowSplitBar); - if (this.editingControl != null && - !this.dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlHidden] && - this.editingPanel.Bounds.IntersectsWith(lastSplitBarRect)) + lastRowSplitBar = currentRowSplitBar; + currentRowSplitBar = e.Y; + Rectangle lastSplitBarRect = CalcRowResizeFeedbackRect(lastRowSplitBar); + if (editingControl != null && + !dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlHidden] && + editingPanel.Bounds.IntersectsWith(lastSplitBarRect)) { - this.editingPanel.Invalidate(); - this.editingPanel.Update(); - this.editingControl.Invalidate(); - this.editingControl.Update(); + editingPanel.Invalidate(); + editingPanel.Update(); + editingControl.Invalidate(); + editingControl.Update(); } Invalidate(lastSplitBarRect); - Invalidate(CalcRowResizeFeedbackRect(this.currentRowSplitBar)); + Invalidate(CalcRowResizeFeedbackRect(currentRowSplitBar)); } private void MapDataGridViewColumnToDataBoundField(DataGridViewColumn dataGridViewColumn) { - Debug.Assert(this.DataSource != null, "this method should only be called when we have a data connection"); + Debug.Assert(DataSource != null, "this method should only be called when we have a data connection"); Debug.Assert(dataGridViewColumn.DataPropertyName.Length != 0, "this method should be called only for columns which have DataPropertyName set"); - DataGridViewDataConnection conn = this.DataConnection; + DataGridViewDataConnection conn = DataConnection; int boundColumnIndex = ((conn == null) ? -1 : conn.BoundColumnIndex(dataGridViewColumn.DataPropertyName)); if (boundColumnIndex != -1) @@ -10561,13 +10561,13 @@ private void MapDataGridViewColumnToDataBoundField(DataGridViewColumn dataGridVi // RefreshColumns() has its own routine for setting the Sorting information so don't do this step // if we are in RefreshColumns(); if (dataGridViewColumn.SortMode != DataGridViewColumnSortMode.NotSortable && - !this.dataGridViewOper[DATAGRIDVIEWOPER_inRefreshColumns]) + !dataGridViewOper[DATAGRIDVIEWOPER_inRefreshColumns]) { dataGridViewColumn.HeaderCell.SortGlyphDirection = conn.BoundColumnSortOrder(boundColumnIndex); - if (this.sortedColumn == null && dataGridViewColumn.HeaderCell.SortGlyphDirection != SortOrder.None) + if (sortedColumn == null && dataGridViewColumn.HeaderCell.SortGlyphDirection != SortOrder.None) { - this.sortedColumn = dataGridViewColumn; - this.sortOrder = dataGridViewColumn.HeaderCell.SortGlyphDirection; + sortedColumn = dataGridViewColumn; + sortOrder = dataGridViewColumn.HeaderCell.SortGlyphDirection; // no need to sort because the back end is already sorted.... } } @@ -10583,41 +10583,41 @@ private void MapDataGridViewColumnToDataBoundField(DataGridViewColumn dataGridVi private void MoveColumnRelocation(MouseEventArgs e, HitTestInfo hti) { - this.lastHeaderShadow = e.X; - this.dataGridViewState2[DATAGRIDVIEWSTATE2_showColumnRelocationInsertion] = ColumnRelocationTarget(e, hti, out this.trackColumnEdge); - Invalidate(Rectangle.Union(this.layout.TopLeftHeader, this.layout.ColumnHeaders)); + lastHeaderShadow = e.X; + dataGridViewState2[DATAGRIDVIEWSTATE2_showColumnRelocationInsertion] = ColumnRelocationTarget(e, hti, out trackColumnEdge); + Invalidate(Rectangle.Union(layout.TopLeftHeader, layout.ColumnHeaders)); } private void MoveRowHeadersOrColumnResize(int x) { - this.lastColSplitBar = this.currentColSplitBar; - this.currentColSplitBar = x; - Rectangle lastSplitBarRect = CalcColResizeFeedbackRect(this.lastColSplitBar); - if (this.editingControl != null && - !this.dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlHidden] && - this.editingPanel.Bounds.IntersectsWith(lastSplitBarRect)) + lastColSplitBar = currentColSplitBar; + currentColSplitBar = x; + Rectangle lastSplitBarRect = CalcColResizeFeedbackRect(lastColSplitBar); + if (editingControl != null && + !dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlHidden] && + editingPanel.Bounds.IntersectsWith(lastSplitBarRect)) { - this.editingPanel.Invalidate(); - this.editingPanel.Update(); - this.editingControl.Invalidate(); - this.editingControl.Update(); + editingPanel.Invalidate(); + editingPanel.Update(); + editingControl.Invalidate(); + editingControl.Update(); } Invalidate(lastSplitBarRect); - Invalidate(CalcColResizeFeedbackRect(this.currentColSplitBar)); + Invalidate(CalcColResizeFeedbackRect(currentColSplitBar)); } public virtual void NotifyCurrentCellDirty(bool dirty) { - Debug.Assert(this.ptCurrentCell.X >= 0 && this.ptCurrentCell.X < this.Columns.Count); - Debug.Assert(this.ptCurrentCell.Y >= 0 && this.ptCurrentCell.Y < this.Rows.Count); + Debug.Assert(ptCurrentCell.X >= 0 && ptCurrentCell.X < Columns.Count); + Debug.Assert(ptCurrentCell.Y >= 0 && ptCurrentCell.Y < Rows.Count); - if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_ignoringEditingChanges] == false) + if (dataGridViewState1[DATAGRIDVIEWSTATE1_ignoringEditingChanges] == false) { // autosizing has no effect since edited value hasn't been committed // and autosizing code only looks at committed values. - this.IsCurrentCellDirtyInternal = dirty; - if (dirty && this.editingControl != null && ((IDataGridViewEditingControl)this.editingControl).RepositionEditingControlOnValueChange) + IsCurrentCellDirtyInternal = dirty; + if (dirty && editingControl != null && ((IDataGridViewEditingControl)editingControl).RepositionEditingControlOnValueChange) { PositionEditingControl(true /*setLocation*/, true /*setSize*/, false /*setFocus*/); } @@ -10627,15 +10627,15 @@ public virtual void NotifyCurrentCellDirty(bool dirty) internal void OnAddedColumn(DataGridViewColumn dataGridViewColumn) { Debug.Assert(dataGridViewColumn.Index >= 0); - Debug.Assert(dataGridViewColumn.Index < this.Columns.Count); + Debug.Assert(dataGridViewColumn.Index < Columns.Count); Debug.Assert(dataGridViewColumn.DataGridView == this); - if (dataGridViewColumn.DisplayIndex == -1 || dataGridViewColumn.DisplayIndex >= this.Columns.Count) + if (dataGridViewColumn.DisplayIndex == -1 || dataGridViewColumn.DisplayIndex >= Columns.Count) { // Developer did not assign a DisplayIndex or picked a large number. // Choose the Index as the DisplayIndex. dataGridViewColumn.DisplayIndexInternal = dataGridViewColumn.Index; - this.Columns.InvalidateCachedColumnsOrder(); + Columns.InvalidateCachedColumnsOrder(); } CorrectColumnDisplayIndexesAfterInsertion(dataGridViewColumn); @@ -10650,7 +10650,7 @@ internal void OnAddedColumn(DataGridViewColumn dataGridViewColumn) Debug.Assert(autoSizeColumnMode != DataGridViewAutoSizeColumnMode.NotSet); bool fixedColumnWidth = autoSizeColumnMode == DataGridViewAutoSizeColumnMode.None || autoSizeColumnMode == DataGridViewAutoSizeColumnMode.Fill; - if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) + if (ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) { AutoResizeColumnHeadersHeight(dataGridViewColumn.Index, true /*fixedRowHeadersWidth*/, fixedColumnWidth); } @@ -10661,7 +10661,7 @@ internal void OnAddedColumn(DataGridViewColumn dataGridViewColumn) dataGridViewColumn.CachedThickness = dataGridViewColumn.Thickness; AutoResizeColumnInternal(dataGridViewColumn.Index, (DataGridViewAutoSizeColumnCriteriaInternal)autoSizeColumnMode, true /*fixedHeight*/); - if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) + if (ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) { // Second round of column headers autosizing AutoResizeColumnHeadersHeight(dataGridViewColumn.Index, true /*fixedRowHeadersWidth*/, true /*fixedColumnWidth*/); @@ -10676,18 +10676,18 @@ internal void OnAddedRow_PreNotification(int rowIndex) { Debug.Assert(rowIndex >= 0); - if (this.AllowUserToAddRowsInternal && this.newRowIndex == -1) + if (AllowUserToAddRowsInternal && newRowIndex == -1) { // The added row is necessarily the 'new row' // Set the this.newRowIndex variable as early as possible. - Debug.Assert(rowIndex == this.Rows.Count - 1); - this.newRowIndex = rowIndex; + Debug.Assert(rowIndex == Rows.Count - 1); + newRowIndex = rowIndex; } - DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); + DataGridViewElementStates rowState = Rows.GetRowState(rowIndex); #if DEBUG - DataGridViewRow dataGridViewRowDebug = this.Rows.SharedRow(rowIndex); + DataGridViewRow dataGridViewRowDebug = Rows.SharedRow(rowIndex); foreach (DataGridViewCell dataGridViewCell in dataGridViewRowDebug.Cells) { Debug.Assert(!dataGridViewCell.Selected); @@ -10697,14 +10697,14 @@ internal void OnAddedRow_PreNotification(int rowIndex) // Update this.individualReadOnlyCells if ((rowState & DataGridViewElementStates.ReadOnly) == 0 && - !this.ReadOnly) + !ReadOnly) { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); foreach (DataGridViewCell dataGridViewCell in dataGridViewRow.Cells) { if (!dataGridViewCell.OwningColumn.ReadOnly && IsSharedCellReadOnly(dataGridViewCell, rowIndex)) { - this.individualReadOnlyCells.Add(dataGridViewCell); + individualReadOnlyCells.Add(dataGridViewCell); } } } @@ -10714,13 +10714,13 @@ internal void OnAddedRow_PostNotification(int rowIndex) { Debug.Assert(rowIndex >= 0); - DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); + DataGridViewElementStates rowState = Rows.GetRowState(rowIndex); if ((rowState & DataGridViewElementStates.Visible) != 0) { bool rowDisplayed = (rowState & DataGridViewElementStates.Displayed) != 0; - DataGridViewAutoSizeRowsModeInternal autoSizeRowsModeInternal = (DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode; + DataGridViewAutoSizeRowsModeInternal autoSizeRowsModeInternal = (DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode; bool autoSizeRow = false; // Auto size row if needed @@ -10728,9 +10728,9 @@ internal void OnAddedRow_PostNotification(int rowIndex) !((autoSizeRowsModeInternal & DataGridViewAutoSizeRowsModeInternal.DisplayedRows) != 0 && !rowDisplayed)) { // this call may unshare the row. - int rowHeight = this.Rows.SharedRow(rowIndex).GetHeight(rowIndex); - this.Rows.SharedRow(rowIndex).CachedThickness = rowHeight; - AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(this.autoSizeRowsMode), false /*fixedWidth*/, true /*internalAutosizing*/); + int rowHeight = Rows.SharedRow(rowIndex).GetHeight(rowIndex); + Rows.SharedRow(rowIndex).CachedThickness = rowHeight; + AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(autoSizeRowsMode), false /*fixedWidth*/, true /*internalAutosizing*/); autoSizeRow = true; } @@ -10741,7 +10741,7 @@ internal void OnAddedRow_PostNotification(int rowIndex) autoSizeColumnCriteriaFilter |= DataGridViewAutoSizeColumnCriteriaInternal.DisplayedRows; } bool columnAutoSized; - if (this.Rows.GetRowCount(DataGridViewElementStates.Visible) > 1) + if (Rows.GetRowCount(DataGridViewElementStates.Visible) > 1) { // Columns can only expand, and not collapse. columnAutoSized = AdjustExpandingColumns(autoSizeColumnCriteriaFilter, rowIndex); @@ -10750,9 +10750,9 @@ internal void OnAddedRow_PostNotification(int rowIndex) { columnAutoSized = AutoResizeAllVisibleColumnsInternal(autoSizeColumnCriteriaFilter, true /*fixedHeight*/); } - bool fixedColumnHeadersHeight = this.ColumnHeadersHeightSizeMode != DataGridViewColumnHeadersHeightSizeMode.AutoSize; - bool rowHeadersAutoSize = this.rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.EnableResizing && - this.rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.DisableResizing; + bool fixedColumnHeadersHeight = ColumnHeadersHeightSizeMode != DataGridViewColumnHeadersHeightSizeMode.AutoSize; + bool rowHeadersAutoSize = rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.EnableResizing && + rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.DisableResizing; if (!rowHeadersAutoSize && !columnAutoSized) { @@ -10763,7 +10763,7 @@ internal void OnAddedRow_PostNotification(int rowIndex) // Auto size row headers if (rowHeadersAutoSize) { - AutoResizeRowHeadersWidth(rowIndex, this.rowHeadersWidthSizeMode, fixedColumnHeadersHeight, true /*fixedRowsHeight*/); + AutoResizeRowHeadersWidth(rowIndex, rowHeadersWidthSizeMode, fixedColumnHeadersHeight, true /*fixedRowsHeight*/); } // Auto size column headers @@ -10775,13 +10775,13 @@ internal void OnAddedRow_PostNotification(int rowIndex) if (autoSizeRow) { // Second round of row autosizing - AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(this.autoSizeRowsMode), true /*fixedWidth*/, true /*internalAutosizing*/); + AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(autoSizeRowsMode), true /*fixedWidth*/, true /*internalAutosizing*/); } if (rowHeadersAutoSize && !fixedColumnHeadersHeight) { // Second round of row headers autosizing - AutoResizeRowHeadersWidth(rowIndex, this.rowHeadersWidthSizeMode, true /*fixedColumnHeadersHeight*/, true /*fixedRowsHeight*/); + AutoResizeRowHeadersWidth(rowIndex, rowHeadersWidthSizeMode, true /*fixedColumnHeadersHeight*/, true /*fixedRowsHeight*/); } } } @@ -10816,12 +10816,12 @@ internal void OnAddingColumn(DataGridViewColumn dataGridViewColumn) throw new InvalidOperationException(string.Format(SR.DataGridView_ColumnAlreadyBelongsToDataGridView)); } - if (!this.InInitialization && + if (!InInitialization && dataGridViewColumn.SortMode == DataGridViewColumnSortMode.Automatic && - (this.SelectionMode == DataGridViewSelectionMode.FullColumnSelect || - this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect)) + (SelectionMode == DataGridViewSelectionMode.FullColumnSelect || + SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect)) { - throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_SortModeAndSelectionModeClash, DataGridViewColumnSortMode.Automatic.ToString(), this.SelectionMode.ToString())); + throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_SortModeAndSelectionModeClash, DataGridViewColumnSortMode.Automatic.ToString(), SelectionMode.ToString())); } if (dataGridViewColumn.Visible) @@ -10829,35 +10829,35 @@ internal void OnAddingColumn(DataGridViewColumn dataGridViewColumn) // Note that dataGridViewColumn.DataGridView is set later on, so dataGridViewColumn.InheritedAutoSizeMode should not be used // Make sure the column does not autosize based only on header while column headers are invisible - if (!this.ColumnHeadersVisible && - (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.ColumnHeader || (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.NotSet && this.AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.ColumnHeader))) + if (!ColumnHeadersVisible && + (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.ColumnHeader || (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.NotSet && AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.ColumnHeader))) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAddAutoSizedColumn)); } // Make sure the column is not frozen and auto fills if (dataGridViewColumn.Frozen && - (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.Fill || (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.NotSet && this.AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.Fill))) + (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.Fill || (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.NotSet && AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.Fill))) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAddAutoFillColumn)); } // UsedFillWeight values need to be updated - this.dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = true; } // Make sure the sum of the column weights does not exceed ushort.MaxValue - float weightSum = this.Columns.GetColumnsFillWeight(DataGridViewElementStates.None) + dataGridViewColumn.FillWeight; + float weightSum = Columns.GetColumnsFillWeight(DataGridViewElementStates.None) + dataGridViewColumn.FillWeight; if (weightSum > (float)ushort.MaxValue) { throw new InvalidOperationException(string.Format(SR.DataGridView_WeightSumCannotExceedLongMaxValue, ushort.MaxValue)); } // check for correctness of frozen state - throws exception if state is incorrect. - CorrectColumnFrozenState(dataGridViewColumn, this.Columns.Count); + CorrectColumnFrozenState(dataGridViewColumn, Columns.Count); // prepare the existing rows by appending cells of correct type - if (this.Rows.Count > 0) + if (Rows.Count > 0) { // Only require a default cell type when there are rows to fill if (dataGridViewColumn.CellType == null) @@ -10865,24 +10865,24 @@ internal void OnAddingColumn(DataGridViewColumn dataGridViewColumn) throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAddUntypedColumn)); } - if (dataGridViewColumn.CellTemplate.DefaultNewRowValue != null && this.newRowIndex != -1) + if (dataGridViewColumn.CellTemplate.DefaultNewRowValue != null && newRowIndex != -1) { // New row needs to be unshared before addition of new cell with a Value != null - DataGridViewRow newRow = this.Rows[this.newRowIndex]; + DataGridViewRow newRow = Rows[newRowIndex]; } - int newColumnCount = this.Columns.Count + 1; + int newColumnCount = Columns.Count + 1; try { - for (int rowIndex = 0; rowIndex < this.Rows.Count; rowIndex++) + for (int rowIndex = 0; rowIndex < Rows.Count; rowIndex++) { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); if (dataGridViewRow.Cells.Count < newColumnCount) { DataGridViewCell dataGridViewCellNew = (DataGridViewCell)dataGridViewColumn.CellTemplate.Clone(); dataGridViewRow.Cells.AddInternal(dataGridViewCellNew); - if (rowIndex == this.newRowIndex) + if (rowIndex == newRowIndex) { dataGridViewCellNew.SetValueInternal(rowIndex, dataGridViewCellNew.DefaultNewRowValue); } @@ -10894,9 +10894,9 @@ internal void OnAddingColumn(DataGridViewColumn dataGridViewColumn) } catch { - for (int rowIndex = 0; rowIndex < this.Rows.Count; rowIndex++) + for (int rowIndex = 0; rowIndex < Rows.Count; rowIndex++) { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); if (dataGridViewRow.Cells.Count == newColumnCount) { dataGridViewRow.Cells.RemoveAtInternal(newColumnCount - 1); @@ -10918,7 +10918,7 @@ internal void OnAddingColumn(DataGridViewColumn dataGridViewColumn) internal void OnAddingColumns(DataGridViewColumn[] dataGridViewColumns) { // Make sure the sum of the column weights does not exceed ushort.MaxValue - float weightSum = this.Columns.GetColumnsFillWeight(DataGridViewElementStates.None); + float weightSum = Columns.GetColumnsFillWeight(DataGridViewElementStates.None); Debug.Assert(weightSum <= (float)ushort.MaxValue); // throw an exception if any of the columns to be added breaks the rules @@ -10934,17 +10934,17 @@ internal void OnAddingColumns(DataGridViewColumn[] dataGridViewColumns) throw new InvalidOperationException(string.Format(SR.DataGridView_ColumnAlreadyBelongsToDataGridView)); } // Only require a default cell type when there are rows to fill - if (this.Rows.Count > 0 && dataGridViewColumn.CellType == null) + if (Rows.Count > 0 && dataGridViewColumn.CellType == null) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAddUntypedColumn)); } - if (!this.InInitialization && + if (!InInitialization && dataGridViewColumn.SortMode == DataGridViewColumnSortMode.Automatic && - (this.SelectionMode == DataGridViewSelectionMode.FullColumnSelect || - this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect)) + (SelectionMode == DataGridViewSelectionMode.FullColumnSelect || + SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect)) { - throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_SortModeAndSelectionModeClash, DataGridViewColumnSortMode.Automatic.ToString(), this.SelectionMode.ToString())); + throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_SortModeAndSelectionModeClash, DataGridViewColumnSortMode.Automatic.ToString(), SelectionMode.ToString())); } if (dataGridViewColumn.Visible) @@ -10952,21 +10952,21 @@ internal void OnAddingColumns(DataGridViewColumn[] dataGridViewColumns) // Note that dataGridViewColumn.DataGridView is set later on, so dataGridViewColumn.InheritedAutoSizeMode should not be used // Make sure the column does not autosize based only on header while column headers are invisible - if (!this.ColumnHeadersVisible && - (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.ColumnHeader || (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.NotSet && this.AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.ColumnHeader))) + if (!ColumnHeadersVisible && + (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.ColumnHeader || (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.NotSet && AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.ColumnHeader))) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAddAutoSizedColumn)); } // Make sure the column is not frozen and auto fills if (dataGridViewColumn.Frozen && - (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.Fill || (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.NotSet && this.AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.Fill))) + (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.Fill || (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.NotSet && AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.Fill))) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAddAutoFillColumn)); } // UsedFillWeight values need to be updated - this.dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = true; } weightSum += dataGridViewColumn.FillWeight; @@ -10995,20 +10995,20 @@ internal void OnAddingColumns(DataGridViewColumn[] dataGridViewColumns) CorrectColumnFrozenStates(dataGridViewColumns); // prepare the existing rows by appending cells of correct type - if (this.Rows.Count > 0) + if (Rows.Count > 0) { foreach (DataGridViewColumn dataGridViewColumn in dataGridViewColumns) { Debug.Assert(dataGridViewColumn.CellType != null); - if (dataGridViewColumn.CellTemplate.DefaultNewRowValue != null && this.newRowIndex != -1) + if (dataGridViewColumn.CellTemplate.DefaultNewRowValue != null && newRowIndex != -1) { // New row needs to be unshared before addition of new cell with a Value != null - DataGridViewRow newRow = this.Rows[this.newRowIndex]; + DataGridViewRow newRow = Rows[newRowIndex]; break; } } - int previousColumnCount = this.Columns.Count; + int previousColumnCount = Columns.Count; int addedColumnCount = 0; try @@ -11017,14 +11017,14 @@ internal void OnAddingColumns(DataGridViewColumn[] dataGridViewColumns) { addedColumnCount++; Debug.Assert(dataGridViewColumn.CellType != null); - for (int rowIndex = 0; rowIndex < this.Rows.Count; rowIndex++) + for (int rowIndex = 0; rowIndex < Rows.Count; rowIndex++) { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); if (dataGridViewRow.Cells.Count < previousColumnCount + addedColumnCount) { DataGridViewCell dataGridViewCellNew = (DataGridViewCell)dataGridViewColumn.CellTemplate.Clone(); int indexCell = dataGridViewRow.Cells.AddInternal(dataGridViewCellNew); - if (rowIndex == this.newRowIndex) + if (rowIndex == newRowIndex) { dataGridViewCellNew.Value = dataGridViewCellNew.DefaultNewRowValue; } @@ -11037,9 +11037,9 @@ internal void OnAddingColumns(DataGridViewColumn[] dataGridViewColumns) } catch { - for (int rowIndex = 0; rowIndex < this.Rows.Count; rowIndex++) + for (int rowIndex = 0; rowIndex < Rows.Count; rowIndex++) { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); while (dataGridViewRow.Cells.Count > previousColumnCount) { dataGridViewRow.Cells.RemoveAtInternal(dataGridViewRow.Cells.Count - 1); @@ -11066,20 +11066,20 @@ internal void OnAddingRow(DataGridViewRow dataGridViewRow, DataGridViewElementSt if (checkFrozenState) { // check for correctness of frozen state - throws exception if state is incorrect. - CorrectRowFrozenState(dataGridViewRow, rowState, this.Rows.Count); + CorrectRowFrozenState(dataGridViewRow, rowState, Rows.Count); } - if (this.ReadOnly && dataGridViewRow.DataGridView == null && dataGridViewRow.ReadOnly) + if (ReadOnly && dataGridViewRow.DataGridView == null && dataGridViewRow.ReadOnly) { // Clear the superfluous flag since the whole dataGridView is read-only dataGridViewRow.ReadOnly = false; } int columnIndex = 0; - foreach (DataGridViewColumn dataGridViewColumn in this.Columns) + foreach (DataGridViewColumn dataGridViewColumn in Columns) { DataGridViewCell dataGridViewCell = dataGridViewRow.Cells[columnIndex]; - if ((this.ReadOnly || dataGridViewColumn.ReadOnly) && dataGridViewCell.StateIncludes(DataGridViewElementStates.ReadOnly)) + if ((ReadOnly || dataGridViewColumn.ReadOnly) && dataGridViewCell.StateIncludes(DataGridViewElementStates.ReadOnly)) { // Clear superfluous flag since the whole dataGridView or column is ReadOnly dataGridViewCell.ReadOnlyInternal = false; @@ -11110,7 +11110,7 @@ internal void OnAddingRows(DataGridViewRow[] dataGridViewRows, bool checkFrozenS throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_CannotAddOrInsertSelectedRow)); } - if (dataGridViewRow.Cells.Count > this.Columns.Count) + if (dataGridViewRow.Cells.Count > Columns.Count) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_TooManyCells)); } @@ -11131,8 +11131,8 @@ internal void OnAddingRows(DataGridViewRow[] dataGridViewRows, bool checkFrozenS if (checkFrozenStates) { - Debug.Assert(!this.AllowUserToAddRowsInternal); - CorrectRowFrozenStates(dataGridViewRows, this.Rows.Count /*rowIndexInserted*/); + Debug.Assert(!AllowUserToAddRowsInternal); + CorrectRowFrozenStates(dataGridViewRows, Rows.Count /*rowIndexInserted*/); } foreach (DataGridViewRow dataGridViewRow in dataGridViewRows) @@ -11144,17 +11144,17 @@ internal void OnAddingRows(DataGridViewRow[] dataGridViewRows, bool checkFrozenS internal void OnAdvancedBorderStyleChanged(DataGridViewAdvancedBorderStyle dgvabs) { - if (!this.dataGridViewOper[DATAGRIDVIEWOPER_inBorderStyleChange]) + if (!dataGridViewOper[DATAGRIDVIEWOPER_inBorderStyleChange]) { - if (dgvabs == this.advancedCellBorderStyle) + if (dgvabs == advancedCellBorderStyle) { OnCellBorderStyleChanged(EventArgs.Empty); } - else if (dgvabs == this.advancedColumnHeadersBorderStyle) + else if (dgvabs == advancedColumnHeadersBorderStyle) { OnColumnHeadersBorderStyleChanged(EventArgs.Empty); } - else if (dgvabs == this.advancedRowHeadersBorderStyle) + else if (dgvabs == advancedRowHeadersBorderStyle) { OnRowHeadersBorderStyleChanged(EventArgs.Empty); } @@ -11165,8 +11165,8 @@ protected virtual void OnAllowUserToAddRowsChanged(EventArgs e) { PushAllowUserToAddRows(); - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWALLOWUSERTOADDROWSCHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWALLOWUSERTOADDROWSCHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11174,8 +11174,8 @@ protected virtual void OnAllowUserToAddRowsChanged(EventArgs e) protected virtual void OnAllowUserToDeleteRowsChanged(EventArgs e) { - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWALLOWUSERTODELETEROWSCHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWALLOWUSERTODELETEROWSCHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11183,8 +11183,8 @@ protected virtual void OnAllowUserToDeleteRowsChanged(EventArgs e) protected virtual void OnAllowUserToOrderColumnsChanged(EventArgs e) { - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWALLOWUSERTOORDERCOLUMNSCHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWALLOWUSERTOORDERCOLUMNSCHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11192,8 +11192,8 @@ protected virtual void OnAllowUserToOrderColumnsChanged(EventArgs e) protected virtual void OnAllowUserToResizeColumnsChanged(EventArgs e) { - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWALLOWUSERTORESIZECOLUMNSCHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWALLOWUSERTORESIZECOLUMNSCHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11201,8 +11201,8 @@ protected virtual void OnAllowUserToResizeColumnsChanged(EventArgs e) protected virtual void OnAllowUserToResizeRowsChanged(EventArgs e) { - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWALLOWUSERTORESIZEROWSCHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWALLOWUSERTORESIZEROWSCHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11218,14 +11218,14 @@ protected virtual void OnAlternatingRowsDefaultCellStyleChanged(EventArgs e) else { OnRowsGlobalAutoSize(); - if (this.editingControl != null) + if (editingControl != null) { PositionEditingControl(true /*setLocation*/, true /*setSize*/, false /*setFocus*/); } } - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWALTERNATINGROWSDEFAULTCELLSTYLECHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWALTERNATINGROWSDEFAULTCELLSTYLECHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11233,13 +11233,13 @@ protected virtual void OnAlternatingRowsDefaultCellStyleChanged(EventArgs e) protected virtual void OnAutoGenerateColumnsChanged(EventArgs e) { - if (this.AutoGenerateColumns && this.DataSource != null) + if (AutoGenerateColumns && DataSource != null) { // refresh the list of columns and the rows RefreshColumnsAndRows(); } - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWAUTOGENERATECOLUMNSCHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWAUTOGENERATECOLUMNSCHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11271,10 +11271,10 @@ protected virtual void OnAutoSizeColumnModeChanged(DataGridViewAutoSizeColumnMod previousInheritedMode == DataGridViewAutoSizeColumnMode.Fill) { // UsedFillWeight values need to be updated - this.dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = true; } - bool fixedHeight = (((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) == 0; + bool fixedHeight = (((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) == 0; if (autoSizeColumnMode != DataGridViewAutoSizeColumnMode.None) { @@ -11302,8 +11302,8 @@ protected virtual void OnAutoSizeColumnModeChanged(DataGridViewAutoSizeColumnMod // Autosize rows and column headers if needed if (!fixedHeight) { - AdjustShrinkingRows(this.autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); - if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) + AdjustShrinkingRows(autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); + if (ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) { AutoResizeColumnHeadersHeight(dataGridViewColumn.Index, true /*fixedRowHeadersWidth*/, true /*fixedColumnWidth*/); } @@ -11317,8 +11317,8 @@ protected virtual void OnAutoSizeColumnModeChanged(DataGridViewAutoSizeColumnMod } } - DataGridViewAutoSizeColumnModeEventHandler eh = this.Events[EVENT_DATAGRIDVIEWAUTOSIZECOLUMNMODECHANGED] as DataGridViewAutoSizeColumnModeEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewAutoSizeColumnModeEventHandler eh = Events[EVENT_DATAGRIDVIEWAUTOSIZECOLUMNMODECHANGED] as DataGridViewAutoSizeColumnModeEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11337,7 +11337,7 @@ protected virtual void OnAutoSizeColumnsModeChanged(DataGridViewAutoSizeColumnsM throw new ArgumentException(string.Format(SR.DataGridView_PreviousModesHasWrongLength)); } - foreach (DataGridViewColumn dataGridViewColumn in this.Columns) + foreach (DataGridViewColumn dataGridViewColumn in Columns) { if (dataGridViewColumn.Visible) { @@ -11351,7 +11351,7 @@ protected virtual void OnAutoSizeColumnsModeChanged(DataGridViewAutoSizeColumnsM previousInheritedMode == DataGridViewAutoSizeColumnMode.Fill) { // UsedFillWeight values need to be updated - this.dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = true; } if (autoSizeColumnMode != DataGridViewAutoSizeColumnMode.None) @@ -11365,7 +11365,7 @@ protected virtual void OnAutoSizeColumnsModeChanged(DataGridViewAutoSizeColumnsM } AutoResizeColumnInternal(dataGridViewColumn.Index, (DataGridViewAutoSizeColumnCriteriaInternal)autoSizeColumnMode, - (((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) == 0 /*fixedHeight*/); + (((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) == 0 /*fixedHeight*/); } } else if (dataGridViewColumn.Thickness != dataGridViewColumn.CachedThickness && previousInheritedModeAutoSized) @@ -11380,16 +11380,16 @@ protected virtual void OnAutoSizeColumnsModeChanged(DataGridViewAutoSizeColumnsM PerformLayoutPrivate(false /*useRowShortcut*/, true /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); // Autosize rows and column headers if needed - if ((((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0) + if ((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0) { - AdjustShrinkingRows(this.autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); - if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) + AdjustShrinkingRows(autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); + if (ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) { AutoResizeColumnHeadersHeight(true /*fixedRowHeadersWidth*/, true /*fixedColumnWidth*/); } // Second pass of column autosizing with 1 degree of freedom - foreach (DataGridViewColumn dataGridViewColumn in this.Columns) + foreach (DataGridViewColumn dataGridViewColumn in Columns) { DataGridViewAutoSizeColumnMode autoSizeColumnMode = dataGridViewColumn.InheritedAutoSizeMode; Debug.Assert(autoSizeColumnMode != DataGridViewAutoSizeColumnMode.NotSet); @@ -11403,8 +11403,8 @@ protected virtual void OnAutoSizeColumnsModeChanged(DataGridViewAutoSizeColumnsM } } - DataGridViewAutoSizeColumnsModeEventHandler eh = this.Events[EVENT_DATAGRIDVIEWAUTOSIZECOLUMNSMODECHANGED] as DataGridViewAutoSizeColumnsModeEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewAutoSizeColumnsModeEventHandler eh = Events[EVENT_DATAGRIDVIEWAUTOSIZECOLUMNSMODECHANGED] as DataGridViewAutoSizeColumnsModeEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11412,7 +11412,7 @@ protected virtual void OnAutoSizeColumnsModeChanged(DataGridViewAutoSizeColumnsM protected virtual void OnAutoSizeRowsModeChanged(DataGridViewAutoSizeModeEventArgs e) { - if (this.autoSizeRowsMode == DataGridViewAutoSizeRowsMode.None) + if (autoSizeRowsMode == DataGridViewAutoSizeRowsMode.None) { // restore cached rows thickness RestoreRowsCachedThickness(); @@ -11423,20 +11423,20 @@ protected virtual void OnAutoSizeRowsModeChanged(DataGridViewAutoSizeModeEventAr { // Save the rows thickness for later reuse // Note that only visible rows are affected, contrary to columns in OnAutoSizeColumnsModeChanged where all columns are affected. - for (int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + for (int rowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); rowIndex != -1; - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) + rowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) { // this call may unshare the row. - int rowHeight = this.Rows.SharedRow(rowIndex).GetHeight(rowIndex); - this.Rows.SharedRow(rowIndex).CachedThickness = rowHeight; + int rowHeight = Rows.SharedRow(rowIndex).GetHeight(rowIndex); + Rows.SharedRow(rowIndex).CachedThickness = rowHeight; } } - AdjustShrinkingRows(this.autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); + AdjustShrinkingRows(autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); } - DataGridViewAutoSizeModeEventHandler eh = this.Events[EVENT_DATAGRIDVIEWAUTOSIZEROWSMODECHANGED] as DataGridViewAutoSizeModeEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewAutoSizeModeEventHandler eh = Events[EVENT_DATAGRIDVIEWAUTOSIZEROWSMODECHANGED] as DataGridViewAutoSizeModeEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11446,8 +11446,8 @@ protected virtual void OnBackgroundColorChanged(EventArgs e) { InvalidateInside(); - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWBACKGROUNDCOLORCHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWBACKGROUNDCOLORCHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11545,7 +11545,7 @@ internal void OnBandThicknessChanged(DataGridViewBand dataGridViewBand) internal void OnBandThicknessChanging() { - if (this.InAdjustFillingColumns) + if (InAdjustFillingColumns) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAlterAutoFillColumnParameter)); } @@ -11553,28 +11553,28 @@ internal void OnBandThicknessChanging() protected override void OnBindingContextChanged(EventArgs e) { - if (this.dataGridViewState2[DATAGRIDVIEWSTATE2_inBindingContextChanged]) + if (dataGridViewState2[DATAGRIDVIEWSTATE2_inBindingContextChanged]) { return; } - this.dataGridViewState2[DATAGRIDVIEWSTATE2_inBindingContextChanged] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_inBindingContextChanged] = true; try { - if (this.dataConnection != null) + if (dataConnection != null) { - this.CurrentCell = null; + CurrentCell = null; try { - this.dataConnection.SetDataConnection(this.DataSource, this.DataMember); + dataConnection.SetDataConnection(DataSource, DataMember); } catch (ArgumentException) { - if (this.DesignMode) + if (DesignMode) { // If the DataMember became invalid at DesignTime then set it to String.Empty, // regenerate the column collection and DO NOT send BindingContextChanged event. - this.DataMember = string.Empty; + DataMember = string.Empty; RefreshColumnsAndRows(); return; } @@ -11585,7 +11585,7 @@ protected override void OnBindingContextChanged(EventArgs e) } RefreshColumnsAndRows(); base.OnBindingContextChanged(e); - if (this.dataConnection.CurrencyManager != null) + if (dataConnection.CurrencyManager != null) { OnDataBindingComplete(ListChangedType.Reset); } @@ -11597,14 +11597,14 @@ protected override void OnBindingContextChanged(EventArgs e) } finally { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_inBindingContextChanged] = false; + dataGridViewState2[DATAGRIDVIEWSTATE2_inBindingContextChanged] = false; } } protected virtual void OnBorderStyleChanged(EventArgs e) { - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWBORDERSTYLECHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWBORDERSTYLECHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11612,8 +11612,8 @@ protected virtual void OnBorderStyleChanged(EventArgs e) protected virtual void OnCancelRowEdit(QuestionEventArgs e) { - QuestionEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCANCELROWEDIT] as QuestionEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + QuestionEventHandler eh = Events[EVENT_DATAGRIDVIEWCANCELROWEDIT] as QuestionEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); CorrectFocus(true /*onlyIfGridHasFocus*/); @@ -11623,16 +11623,16 @@ protected virtual void OnCancelRowEdit(QuestionEventArgs e) [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellBeginEdit(DataGridViewCellCancelEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellCancelEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLBEGINEDIT] as DataGridViewCellCancelEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellCancelEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLBEGINEDIT] as DataGridViewCellCancelEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11643,8 +11643,8 @@ protected virtual void OnCellBorderStyleChanged(EventArgs e) PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); Invalidate(); - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLBORDERSTYLECHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWCELLBORDERSTYLECHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11658,11 +11658,11 @@ internal void OnCellClickInternal(DataGridViewCellEventArgs e) [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellClick(DataGridViewCellEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } @@ -11670,7 +11670,7 @@ protected virtual void OnCellClick(DataGridViewCellEventArgs e) Debug.Assert(dataGridViewCell != null); if (e.RowIndex >= 0 && dataGridViewCell.ClickUnsharesRowInternal(e)) { - DataGridViewRow dataGridViewRow = this.Rows[e.RowIndex]; + DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnClickInternal(e); } else @@ -11678,8 +11678,8 @@ protected virtual void OnCellClick(DataGridViewCellEventArgs e) dataGridViewCell.OnClickInternal(e); } - DataGridViewCellEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLCLICK] as DataGridViewCellEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLCLICK] as DataGridViewCellEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11707,20 +11707,20 @@ internal void OnCellCommonChange(int columnIndex, int rowIndex) bool rowDisplayed = false; if (rowIndex != -1) { - rowDisplayed = (this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Displayed) != 0; + rowDisplayed = (Rows.GetRowState(rowIndex) & DataGridViewElementStates.Displayed) != 0; } - DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaInternal = (DataGridViewAutoSizeColumnCriteriaInternal)this.Columns[columnIndex].InheritedAutoSizeMode; + DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaInternal = (DataGridViewAutoSizeColumnCriteriaInternal)Columns[columnIndex].InheritedAutoSizeMode; bool autoSizeColumn = (autoSizeColumnCriteriaInternal & DataGridViewAutoSizeColumnCriteriaInternal.AllRows) != 0; if (rowDisplayed) { autoSizeColumn |= (autoSizeColumnCriteriaInternal & DataGridViewAutoSizeColumnCriteriaInternal.DisplayedRows) != 0; } - bool autoSizeRow = (((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0; + bool autoSizeRow = (((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0; if (autoSizeRow) { - AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(this.autoSizeRowsMode), !autoSizeColumn /*fixedWidth*/, true /*internalAutosizing*/); + AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(autoSizeRowsMode), !autoSizeColumn /*fixedWidth*/, true /*internalAutosizing*/); } if (autoSizeColumn) { @@ -11728,7 +11728,7 @@ internal void OnCellCommonChange(int columnIndex, int rowIndex) if (autoSizeRow) { // Second round of row autosizing with 1 degree of freedom. - AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(this.autoSizeRowsMode), true /*fixedWidth*/, true /*internalAutosizing*/); + AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(autoSizeRowsMode), true /*fixedWidth*/, true /*internalAutosizing*/); } } } @@ -11743,11 +11743,11 @@ internal void OnCellContentClickInternal(DataGridViewCellEventArgs e) [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellContentClick(DataGridViewCellEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } @@ -11755,7 +11755,7 @@ protected virtual void OnCellContentClick(DataGridViewCellEventArgs e) Debug.Assert(dataGridViewCell != null); if (e.RowIndex >= 0 && dataGridViewCell.ContentClickUnsharesRowInternal(e)) { - DataGridViewRow dataGridViewRow = this.Rows[e.RowIndex]; + DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnContentClickInternal(e); } else @@ -11763,8 +11763,8 @@ protected virtual void OnCellContentClick(DataGridViewCellEventArgs e) dataGridViewCell.OnContentClickInternal(e); } - DataGridViewCellEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLCONTENTCLICK] as DataGridViewCellEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLCONTENTCLICK] as DataGridViewCellEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11778,11 +11778,11 @@ internal void OnCellContentDoubleClickInternal(DataGridViewCellEventArgs e) [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellContentDoubleClick(DataGridViewCellEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } @@ -11790,7 +11790,7 @@ protected virtual void OnCellContentDoubleClick(DataGridViewCellEventArgs e) Debug.Assert(dataGridViewCell != null); if (e.RowIndex >= 0 && dataGridViewCell.ContentDoubleClickUnsharesRowInternal(e)) { - DataGridViewRow dataGridViewRow = this.Rows[e.RowIndex]; + DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnContentDoubleClickInternal(e); } else @@ -11798,8 +11798,8 @@ protected virtual void OnCellContentDoubleClick(DataGridViewCellEventArgs e) dataGridViewCell.OnContentDoubleClickInternal(e); } - DataGridViewCellEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLCONTENTDOUBLECLICK] as DataGridViewCellEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLCONTENTDOUBLECLICK] as DataGridViewCellEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11814,16 +11814,16 @@ internal void OnCellContextMenuStripChanged(DataGridViewCell dataGridViewCell) [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellContextMenuStripChanged(DataGridViewCellEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLCONTEXTMENUSTRIPCHANGED] as DataGridViewCellEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLCONTEXTMENUSTRIPCHANGED] as DataGridViewCellEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11839,16 +11839,16 @@ internal ContextMenuStrip OnCellContextMenuStripNeeded(int columnIndex, int rowI [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellContextMenuStripNeeded(DataGridViewCellContextMenuStripNeededEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellContextMenuStripNeededEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLCONTEXTMENUSTRIPNEEDED] as DataGridViewCellContextMenuStripNeededEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellContextMenuStripNeededEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLCONTEXTMENUSTRIPNEEDED] as DataGridViewCellContextMenuStripNeededEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11857,11 +11857,11 @@ protected virtual void OnCellContextMenuStripNeeded(DataGridViewCellContextMenuS [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellDoubleClick(DataGridViewCellEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } @@ -11869,7 +11869,7 @@ protected virtual void OnCellDoubleClick(DataGridViewCellEventArgs e) Debug.Assert(dataGridViewCell != null); if (e.RowIndex >= 0 && dataGridViewCell.DoubleClickUnsharesRowInternal(e)) { - DataGridViewRow dataGridViewRow = this.Rows[e.RowIndex]; + DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnDoubleClickInternal(e); } else @@ -11877,8 +11877,8 @@ protected virtual void OnCellDoubleClick(DataGridViewCellEventArgs e) dataGridViewCell.OnDoubleClickInternal(e); } - DataGridViewCellEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLDOUBLECLICK] as DataGridViewCellEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLDOUBLECLICK] as DataGridViewCellEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11887,16 +11887,16 @@ protected virtual void OnCellDoubleClick(DataGridViewCellEventArgs e) [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellEndEdit(DataGridViewCellEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLENDEDIT] as DataGridViewCellEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLENDEDIT] as DataGridViewCellEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11913,8 +11913,8 @@ internal void OnCellEnter(ref DataGridViewCell dataGridViewCell, int columnIndex } else { - Debug.Assert(rowIndex < this.Rows.Count && columnIndex < this.Columns.Count); - dataGridViewCell = this.Rows.SharedRow(rowIndex).Cells[columnIndex]; + Debug.Assert(rowIndex < Rows.Count && columnIndex < Columns.Count); + dataGridViewCell = Rows.SharedRow(rowIndex).Cells[columnIndex]; } } } @@ -11922,28 +11922,28 @@ internal void OnCellEnter(ref DataGridViewCell dataGridViewCell, int columnIndex [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellEnter(DataGridViewCellEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } try { - this.noDimensionChangeCount++; + noDimensionChangeCount++; - DataGridViewCellEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLENTER] as DataGridViewCellEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLENTER] as DataGridViewCellEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } } finally { - this.noDimensionChangeCount--; - Debug.Assert(this.noDimensionChangeCount >= 0); + noDimensionChangeCount--; + Debug.Assert(noDimensionChangeCount >= 0); } } @@ -11958,18 +11958,18 @@ internal void OnCellErrorTextChanged(DataGridViewCell dataGridViewCell) [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellErrorTextChanged(DataGridViewCellEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } UpdateCellErrorText(e.ColumnIndex, e.RowIndex); - DataGridViewCellEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLERRORTEXTCHANGED] as DataGridViewCellEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLERRORTEXTCHANGED] as DataGridViewCellEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11987,16 +11987,16 @@ internal string OnCellErrorTextNeeded(int columnIndex, int rowIndex, string erro [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellErrorTextNeeded(DataGridViewCellErrorTextNeededEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellErrorTextNeededEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLERRORTEXTNEEDED] as DataGridViewCellErrorTextNeededEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellErrorTextNeededEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLERRORTEXTNEEDED] as DataGridViewCellErrorTextNeededEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -12016,16 +12016,16 @@ internal DataGridViewCellFormattingEventArgs OnCellFormatting(int columnIndex, i [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellFormatting(DataGridViewCellFormattingEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellFormattingEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLFORMATTING] as DataGridViewCellFormattingEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellFormattingEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLFORMATTING] as DataGridViewCellFormattingEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -12042,8 +12042,8 @@ internal void OnCellLeave(ref DataGridViewCell dataGridViewCell, int columnIndex } else { - Debug.Assert(rowIndex < this.Rows.Count && columnIndex < this.Columns.Count); - dataGridViewCell = this.Rows.SharedRow(rowIndex).Cells[columnIndex]; + Debug.Assert(rowIndex < Rows.Count && columnIndex < Columns.Count); + dataGridViewCell = Rows.SharedRow(rowIndex).Cells[columnIndex]; } } } @@ -12051,39 +12051,39 @@ internal void OnCellLeave(ref DataGridViewCell dataGridViewCell, int columnIndex [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellLeave(DataGridViewCellEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } try { - this.noDimensionChangeCount++; + noDimensionChangeCount++; - DataGridViewCellEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLLEAVE] as DataGridViewCellEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLLEAVE] as DataGridViewCellEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } } finally { - this.noDimensionChangeCount--; - Debug.Assert(this.noDimensionChangeCount >= 0); + noDimensionChangeCount--; + Debug.Assert(noDimensionChangeCount >= 0); } } [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellMouseClick(DataGridViewCellMouseEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } @@ -12091,17 +12091,17 @@ protected virtual void OnCellMouseClick(DataGridViewCellMouseEventArgs e) Debug.Assert(dataGridViewCell != null); if (e.RowIndex >= 0 && dataGridViewCell.MouseClickUnsharesRowInternal(e)) { - DataGridViewRow dataGridViewRow = this.Rows[e.RowIndex]; + DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnMouseClickInternal(e); } else { dataGridViewCell.OnMouseClickInternal(e); } - this.dataGridViewState2[DATAGRIDVIEWSTATE2_nextMouseUpIsDouble] = false; + dataGridViewState2[DATAGRIDVIEWSTATE2_nextMouseUpIsDouble] = false; - DataGridViewCellMouseEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLMOUSECLICK] as DataGridViewCellMouseEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellMouseEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLMOUSECLICK] as DataGridViewCellMouseEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -12110,11 +12110,11 @@ protected virtual void OnCellMouseClick(DataGridViewCellMouseEventArgs e) [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellMouseDoubleClick(DataGridViewCellMouseEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } @@ -12122,17 +12122,17 @@ protected virtual void OnCellMouseDoubleClick(DataGridViewCellMouseEventArgs e) Debug.Assert(dataGridViewCell != null); if (e.RowIndex >= 0 && dataGridViewCell.MouseDoubleClickUnsharesRowInternal(e)) { - DataGridViewRow dataGridViewRow = this.Rows[e.RowIndex]; + DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnMouseDoubleClickInternal(e); } else { dataGridViewCell.OnMouseDoubleClickInternal(e); } - this.dataGridViewState2[DATAGRIDVIEWSTATE2_nextMouseUpIsDouble] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_nextMouseUpIsDouble] = true; - DataGridViewCellMouseEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLMOUSEDOUBLECLICK] as DataGridViewCellMouseEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellMouseEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLMOUSEDOUBLECLICK] as DataGridViewCellMouseEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -12141,11 +12141,11 @@ protected virtual void OnCellMouseDoubleClick(DataGridViewCellMouseEventArgs e) [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellMouseDown(DataGridViewCellMouseEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } @@ -12163,13 +12163,13 @@ protected virtual void OnCellMouseDown(DataGridViewCellMouseEventArgs e) HitTestInfo hti = HitTest(ptGridCoord.X, ptGridCoord.Y); - if (!this.dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls] && e.Button == MouseButtons.Left) + if (!dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls] && e.Button == MouseButtons.Left) { Debug.Assert(hti.Type != DataGridViewHitTestType.None && hti.Type != DataGridViewHitTestType.HorizontalScrollBar && hti.Type != DataGridViewHitTestType.VerticalScrollBar); - Debug.Assert(this.ptMouseDownCell.X == hti.col); - Debug.Assert(this.ptMouseDownCell.Y == hti.row); + Debug.Assert(ptMouseDownCell.X == hti.col); + Debug.Assert(ptMouseDownCell.Y == hti.row); switch (hti.typeInternal) { @@ -12187,7 +12187,7 @@ protected virtual void OnCellMouseDown(DataGridViewCellMouseEventArgs e) case DataGridViewHitTestTypeInternal.ColumnHeadersResizeTop: case DataGridViewHitTestTypeInternal.ColumnHeadersResizeBottom: { - this.dataGridViewOper[DATAGRIDVIEWOPER_resizingOperationAboutToStart] = (e.Clicks == 1); + dataGridViewOper[DATAGRIDVIEWOPER_resizingOperationAboutToStart] = (e.Clicks == 1); break; } } @@ -12197,7 +12197,7 @@ protected virtual void OnCellMouseDown(DataGridViewCellMouseEventArgs e) { if (e.RowIndex >= 0 && dataGridViewCell.MouseDownUnsharesRowInternal(e)) { - DataGridViewRow dataGridViewRow = this.Rows[e.RowIndex]; + DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnMouseDownInternal(e); } else @@ -12205,13 +12205,13 @@ protected virtual void OnCellMouseDown(DataGridViewCellMouseEventArgs e) dataGridViewCell.OnMouseDownInternal(e); } - DataGridViewCellMouseEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLMOUSEDOWN] as DataGridViewCellMouseEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellMouseEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLMOUSEDOWN] as DataGridViewCellMouseEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } - if (!this.dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls] && e.Button == MouseButtons.Left) + if (!dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls] && e.Button == MouseButtons.Left) { switch (hti.typeInternal) { @@ -12220,7 +12220,7 @@ protected virtual void OnCellMouseDown(DataGridViewCellMouseEventArgs e) case DataGridViewHitTestTypeInternal.ColumnResizeRight: { int columnIndex = (hti.typeInternal == DataGridViewHitTestTypeInternal.ColumnResizeRight) ? hti.col : hti.adjacentCol; - Debug.Assert(this.Columns[columnIndex].Resizable == DataGridViewTriState.True); + Debug.Assert(Columns[columnIndex].Resizable == DataGridViewTriState.True); if (e.Clicks == 1) { BeginMouseColumnResize(ptGridCoord.X, hti.mouseBarOffset, columnIndex); @@ -12246,9 +12246,9 @@ protected virtual void OnCellMouseDown(DataGridViewCellMouseEventArgs e) case DataGridViewHitTestTypeInternal.ColumnHeaderRight: case DataGridViewHitTestTypeInternal.FirstColumnHeaderLeft: { - if (isAltDown && this.AllowUserToOrderColumns && - (this.SelectionMode == DataGridViewSelectionMode.FullColumnSelect || - this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect)) + if (isAltDown && AllowUserToOrderColumns && + (SelectionMode == DataGridViewSelectionMode.FullColumnSelect || + SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect)) { BeginColumnRelocation(ptGridCoord.X, hti.col); } @@ -12307,7 +12307,7 @@ protected virtual void OnCellMouseDown(DataGridViewCellMouseEventArgs e) } } // Make sure that there is a current cell after this mouse down event. - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { MakeFirstDisplayedCellCurrentCell(true /*includeNewRow*/); } @@ -12315,7 +12315,7 @@ protected virtual void OnCellMouseDown(DataGridViewCellMouseEventArgs e) } finally { - this.dataGridViewOper[DATAGRIDVIEWOPER_resizingOperationAboutToStart] = false; + dataGridViewOper[DATAGRIDVIEWOPER_resizingOperationAboutToStart] = false; } } @@ -12323,18 +12323,18 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo { Debug.Assert(hti.Type == DataGridViewHitTestType.Cell); // Only commit cell if the target cell is different from the current one. - if (this.ptCurrentCell.X >= 0 && - (this.ptCurrentCell.X != hti.col || this.ptCurrentCell.Y != hti.row)) + if (ptCurrentCell.X >= 0 && + (ptCurrentCell.X != hti.col || ptCurrentCell.Y != hti.row)) { - Point ptOriginalCurrentCell = this.ptCurrentCell; + Point ptOriginalCurrentCell = ptCurrentCell; if (!CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit, - this.ptCurrentCell.X != hti.col || this.ptCurrentCell.Y != hti.row /*forCurrentCellChange*/, - this.ptCurrentCell.Y != hti.row /*forCurrentRowChange*/)) + ptCurrentCell.X != hti.col || ptCurrentCell.Y != hti.row /*forCurrentCellChange*/, + ptCurrentCell.Y != hti.row /*forCurrentRowChange*/)) { // Return silently if validating/commit/abort failed return; } - if (this.ptCurrentCell != ptOriginalCurrentCell) + if (ptCurrentCell != ptOriginalCurrentCell) { // Somehow the fact that the current cell was committed altered the current cell value. // To avoid unintentional multi-selections, we act as if Shift and Control keys were up. @@ -12342,11 +12342,11 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo } } - if (hti.col >= this.Columns.Count) + if (hti.col >= Columns.Count) { - DataGridViewColumn dataGridViewLastVisibleColumn = this.Columns.GetLastColumn(DataGridViewElementStates.Visible, + DataGridViewColumn dataGridViewLastVisibleColumn = Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.None); - if (this.ptCurrentCell.X == -1 && dataGridViewLastVisibleColumn != null) + if (ptCurrentCell.X == -1 && dataGridViewLastVisibleColumn != null) { // CurrentCell was reset because CommitEdit deleted column(s). // Since the user clicked on a cell, we don't want to end up @@ -12358,10 +12358,10 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo return; } } - if (hti.row >= this.Rows.Count) + if (hti.row >= Rows.Count) { - int lastVisibleRowIndex = this.Rows.GetLastRow(DataGridViewElementStates.Visible); - if (this.ptCurrentCell.X == -1 && lastVisibleRowIndex != -1) + int lastVisibleRowIndex = Rows.GetLastRow(DataGridViewElementStates.Visible); + if (ptCurrentCell.X == -1 && lastVisibleRowIndex != -1) { // CurrentCell was reset because CommitEdit deleted row(s). // Since the user clicked on a cell, we don't want to end up @@ -12376,42 +12376,42 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo } bool select = true; - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: { if (isControlDown && - IsSharedCellSelected(this.Rows.SharedRow(hti.row).Cells[hti.col], hti.row) && - (!isShiftDown || !this.MultiSelect)) + IsSharedCellSelected(Rows.SharedRow(hti.row).Cells[hti.col], hti.row) && + (!isShiftDown || !MultiSelect)) { select = false; } if (select) { - if ((!this.MultiSelect || !isControlDown) && !(this.MultiSelect && isShiftDown)) + if ((!MultiSelect || !isControlDown) && !(MultiSelect && isShiftDown)) { - Debug.Assert(this.MultiSelect || this.individualSelectedCells.Count <= 1); + Debug.Assert(MultiSelect || individualSelectedCells.Count <= 1); RemoveIndividuallySelectedCells(hti.col, hti.row); } - if (this.MultiSelect) + if (MultiSelect) { - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) + if (dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) { - this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect] = true; + dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect] = true; } if (isShiftDown) { - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - if (this.ptAnchorCell.X == -1) + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + if (ptAnchorCell.X == -1) { return; } - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, hti.col, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, hti.row); + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, hti.col, + ptAnchorCell.Y, ref oldEdgeRowIndex, hti.row); } else { @@ -12434,40 +12434,40 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo case DataGridViewSelectionMode.FullColumnSelect: { - if (isControlDown && this.Columns[hti.col].Selected) + if (isControlDown && Columns[hti.col].Selected) { select = false; } if (select) { bool selectColumnRange = false; - this.trackColumn = hti.col; - this.trackColumnEdge = -1; - if (this.MultiSelect && + trackColumn = hti.col; + trackColumnEdge = -1; + if (MultiSelect && isShiftDown && - this.ptAnchorCell.X > -1 && - this.Columns[this.ptAnchorCell.X].Selected) + ptAnchorCell.X > -1 && + Columns[ptAnchorCell.X].Selected) { selectColumnRange = true; } - if (!this.MultiSelect || !isControlDown || isShiftDown) + if (!MultiSelect || !isControlDown || isShiftDown) { - Debug.Assert(this.MultiSelect || this.selectedBandIndexes.Count <= 1); + Debug.Assert(MultiSelect || selectedBandIndexes.Count <= 1); int bandIndex = 0; bool switchedToBulkPaint = false; - if (this.selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) + if (selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) { - this.inBulkPaintCount++; + inBulkPaintCount++; switchedToBulkPaint = true; } try { - while (bandIndex < this.selectedBandIndexes.Count) + while (bandIndex < selectedBandIndexes.Count) { - if (this.selectedBandIndexes[bandIndex] != hti.col) + if (selectedBandIndexes[bandIndex] != hti.col) { // deselect currently selected column - SetSelectedColumnCore(this.selectedBandIndexes[bandIndex], false); + SetSelectedColumnCore(selectedBandIndexes[bandIndex], false); } else { @@ -12483,29 +12483,29 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo } } } - if (this.MultiSelect && this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) + if (MultiSelect && dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) { - this.dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] = true; + dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] = true; } if (selectColumnRange) { - if (this.Columns.DisplayInOrder(this.ptAnchorCell.X, hti.col)) + if (Columns.DisplayInOrder(ptAnchorCell.X, hti.col)) { - SelectColumnRange(this.ptAnchorCell.X, hti.col, true); + SelectColumnRange(ptAnchorCell.X, hti.col, true); } else { - SelectColumnRange(hti.col, this.ptAnchorCell.X, true); + SelectColumnRange(hti.col, ptAnchorCell.X, true); } } - else if (!this.selectedBandIndexes.Contains(hti.col)) + else if (!selectedBandIndexes.Contains(hti.col)) { SetSelectedColumnCore(hti.col, true); } } else { - Debug.Assert(this.selectedBandIndexes.Contains(hti.col)); + Debug.Assert(selectedBandIndexes.Contains(hti.col)); SetSelectedColumnCore(hti.col, false); } bool success = SetCurrentCellAddressCore(hti.col, hti.row, !isShiftDown, false, true); @@ -12516,19 +12516,19 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo case DataGridViewSelectionMode.ColumnHeaderSelect: { if (isControlDown && - (this.Columns[hti.col].Selected || IsSharedCellSelected(this.Rows.SharedRow(hti.row).Cells[hti.col], hti.row)) && - (!isShiftDown || !this.MultiSelect)) + (Columns[hti.col].Selected || IsSharedCellSelected(Rows.SharedRow(hti.row).Cells[hti.col], hti.row)) && + (!isShiftDown || !MultiSelect)) { select = false; } if (select) { - if (!this.MultiSelect) + if (!MultiSelect) { - Debug.Assert(this.selectedBandIndexes.Count <= 1); - if (this.selectedBandIndexes.Count > 0) + Debug.Assert(selectedBandIndexes.Count <= 1); + if (selectedBandIndexes.Count > 0) { - SetSelectedColumnCore(this.selectedBandIndexes.HeadInt, false); + SetSelectedColumnCore(selectedBandIndexes.HeadInt, false); } else { @@ -12542,16 +12542,16 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo if (!isControlDown && !isShiftDown) { bool switchedToBulkPaint = false; - if (this.selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) + if (selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) { - this.inBulkPaintCount++; + inBulkPaintCount++; switchedToBulkPaint = true; } try { - while (this.selectedBandIndexes.Count > 0) + while (selectedBandIndexes.Count > 0) { - SetSelectedColumnCore(this.selectedBandIndexes.HeadInt, false); + SetSelectedColumnCore(selectedBandIndexes.HeadInt, false); } RemoveIndividuallySelectedCells(hti.col, hti.row); } @@ -12563,20 +12563,20 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo } } } - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) + if (dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) { - this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect] = true; + dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect] = true; } if (isShiftDown) { - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - if (this.ptAnchorCell.X == -1) + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + if (ptAnchorCell.X == -1) { return; } - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, hti.col, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, hti.row); + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, hti.col, + ptAnchorCell.Y, ref oldEdgeRowIndex, hti.row); } else { @@ -12586,12 +12586,12 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo } else { - if (!this.MultiSelect) + if (!MultiSelect) { - Debug.Assert(this.selectedBandIndexes.Count <= 1); - if (this.selectedBandIndexes.Count > 0) + Debug.Assert(selectedBandIndexes.Count <= 1); + if (selectedBandIndexes.Count > 0) { - SetSelectedColumnCore(this.selectedBandIndexes.HeadInt, false); + SetSelectedColumnCore(selectedBandIndexes.HeadInt, false); } else { @@ -12611,40 +12611,40 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo case DataGridViewSelectionMode.FullRowSelect: { if (isControlDown && - ((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) != 0)) + ((Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) != 0)) { select = false; } if (select) { bool selectRowRange = false; - this.trackRow = hti.row; - this.trackRowEdge = -1; - if (this.MultiSelect && + trackRow = hti.row; + trackRowEdge = -1; + if (MultiSelect && isShiftDown && - this.ptAnchorCell.Y > -1 && (this.Rows.GetRowState(this.ptAnchorCell.Y) & DataGridViewElementStates.Selected) != 0) + ptAnchorCell.Y > -1 && (Rows.GetRowState(ptAnchorCell.Y) & DataGridViewElementStates.Selected) != 0) { selectRowRange = true; } - if (!this.MultiSelect || !isControlDown || isShiftDown) + if (!MultiSelect || !isControlDown || isShiftDown) { - Debug.Assert(this.MultiSelect || this.selectedBandIndexes.Count <= 1); + Debug.Assert(MultiSelect || selectedBandIndexes.Count <= 1); int bandIndex = 0; bool switchedToBulkPaint = false; - if (this.selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) + if (selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) { - this.inBulkPaintCount++; + inBulkPaintCount++; switchedToBulkPaint = true; } try { - while (bandIndex < this.selectedBandIndexes.Count) + while (bandIndex < selectedBandIndexes.Count) { - if (this.selectedBandIndexes[bandIndex] != hti.row) + if (selectedBandIndexes[bandIndex] != hti.row) { // deselect currently selected row - SetSelectedRowCore(this.selectedBandIndexes[bandIndex], false); + SetSelectedRowCore(selectedBandIndexes[bandIndex], false); } else { @@ -12660,31 +12660,31 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo } } } - if (this.MultiSelect && this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) + if (MultiSelect && dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) { - this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] = true; + dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] = true; } if (selectRowRange) { - if (hti.row >= this.ptAnchorCell.Y) + if (hti.row >= ptAnchorCell.Y) { - SelectRowRange(this.ptAnchorCell.Y, hti.row, true); + SelectRowRange(ptAnchorCell.Y, hti.row, true); } else { - SelectRowRange(hti.row, this.ptAnchorCell.Y, true); + SelectRowRange(hti.row, ptAnchorCell.Y, true); } } - else if ((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) == 0) + else if ((Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) == 0) { - Debug.Assert(this.selectedBandIndexes.Contains(hti.row) == - ((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) != 0)); + Debug.Assert(selectedBandIndexes.Contains(hti.row) == + ((Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) != 0)); SetSelectedRowCore(hti.row, true); } } else { - Debug.Assert(this.selectedBandIndexes.Contains(hti.row)); + Debug.Assert(selectedBandIndexes.Contains(hti.row)); SetSelectedRowCore(hti.row, false); } bool success = SetCurrentCellAddressCore(hti.col, hti.row, !isShiftDown, false, true); @@ -12695,20 +12695,20 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo case DataGridViewSelectionMode.RowHeaderSelect: { if (isControlDown && - (((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) != 0) || - IsSharedCellSelected(this.Rows.SharedRow(hti.row).Cells[hti.col], hti.row)) && - (!isShiftDown || !this.MultiSelect)) + (((Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) != 0) || + IsSharedCellSelected(Rows.SharedRow(hti.row).Cells[hti.col], hti.row)) && + (!isShiftDown || !MultiSelect)) { select = false; } if (select) { - if (!this.MultiSelect) + if (!MultiSelect) { - Debug.Assert(this.selectedBandIndexes.Count <= 1); - if (this.selectedBandIndexes.Count > 0) + Debug.Assert(selectedBandIndexes.Count <= 1); + if (selectedBandIndexes.Count > 0) { - SetSelectedRowCore(this.selectedBandIndexes.HeadInt, false); + SetSelectedRowCore(selectedBandIndexes.HeadInt, false); } else { @@ -12722,16 +12722,16 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo if (!isControlDown && !isShiftDown) { bool switchedToBulkPaint = false; - if (this.selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) + if (selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) { - this.inBulkPaintCount++; + inBulkPaintCount++; switchedToBulkPaint = true; } try { - while (this.selectedBandIndexes.Count > 0) + while (selectedBandIndexes.Count > 0) { - SetSelectedRowCore(this.selectedBandIndexes.HeadInt, false); + SetSelectedRowCore(selectedBandIndexes.HeadInt, false); } RemoveIndividuallySelectedCells(hti.col, hti.row); } @@ -12743,20 +12743,20 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo } } } - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) + if (dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) { - this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect] = true; + dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect] = true; } if (isShiftDown) { - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - if (this.ptAnchorCell.X == -1) + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + if (ptAnchorCell.X == -1) { return; } - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, hti.col, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, hti.row); + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, hti.col, + ptAnchorCell.Y, ref oldEdgeRowIndex, hti.row); } else { @@ -12766,12 +12766,12 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo } else { - if (!this.MultiSelect) + if (!MultiSelect) { - Debug.Assert(this.selectedBandIndexes.Count <= 1); - if (this.selectedBandIndexes.Count > 0) + Debug.Assert(selectedBandIndexes.Count <= 1); + if (selectedBandIndexes.Count > 0) { - SetSelectedRowCore(this.selectedBandIndexes.HeadInt, false); + SetSelectedRowCore(selectedBandIndexes.HeadInt, false); } else { @@ -12794,29 +12794,29 @@ private void OnCellMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDo } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; } } [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellMouseEnter(DataGridViewCellEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } - this.ptMouseEnteredCell.X = e.ColumnIndex; - this.ptMouseEnteredCell.Y = e.RowIndex; + ptMouseEnteredCell.X = e.ColumnIndex; + ptMouseEnteredCell.Y = e.RowIndex; DataGridViewCell dataGridViewCell = GetCellInternal(e.ColumnIndex, e.RowIndex); Debug.Assert(dataGridViewCell != null); if (e.RowIndex >= 0 && dataGridViewCell.MouseEnterUnsharesRowInternal(e.RowIndex)) { - DataGridViewRow dataGridViewRow = this.Rows[e.RowIndex]; + DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnMouseEnterInternal(e.RowIndex); } else @@ -12824,8 +12824,8 @@ protected virtual void OnCellMouseEnter(DataGridViewCellEventArgs e) dataGridViewCell.OnMouseEnterInternal(e.RowIndex); } - DataGridViewCellEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLMOUSEENTER] as DataGridViewCellEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLMOUSEENTER] as DataGridViewCellEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -12834,22 +12834,22 @@ protected virtual void OnCellMouseEnter(DataGridViewCellEventArgs e) [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellMouseLeave(DataGridViewCellEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } - this.ptMouseEnteredCell.X = -2; - this.ptMouseEnteredCell.Y = -2; + ptMouseEnteredCell.X = -2; + ptMouseEnteredCell.Y = -2; DataGridViewCell dataGridViewCell = GetCellInternal(e.ColumnIndex, e.RowIndex); Debug.Assert(dataGridViewCell != null); if (e.RowIndex >= 0 && dataGridViewCell.MouseLeaveUnsharesRowInternal(e.RowIndex)) { - DataGridViewRow dataGridViewRow = this.Rows[e.RowIndex]; + DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnMouseLeaveInternal(e.RowIndex); } else @@ -12857,8 +12857,8 @@ protected virtual void OnCellMouseLeave(DataGridViewCellEventArgs e) dataGridViewCell.OnMouseLeaveInternal(e.RowIndex); } - DataGridViewCellEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLMOUSELEAVE] as DataGridViewCellEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLMOUSELEAVE] as DataGridViewCellEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -12867,11 +12867,11 @@ protected virtual void OnCellMouseLeave(DataGridViewCellEventArgs e) [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellMouseMove(DataGridViewCellMouseEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } @@ -12879,7 +12879,7 @@ protected virtual void OnCellMouseMove(DataGridViewCellMouseEventArgs e) Debug.Assert(dataGridViewCell != null); if (e.RowIndex >= 0 && dataGridViewCell.MouseMoveUnsharesRowInternal(e)) { - DataGridViewRow dataGridViewRow = this.Rows[e.RowIndex]; + DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnMouseMoveInternal(e); } else @@ -12887,21 +12887,21 @@ protected virtual void OnCellMouseMove(DataGridViewCellMouseEventArgs e) dataGridViewCell.OnMouseMoveInternal(e); } - DataGridViewCellMouseEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLMOUSEMOVE] as DataGridViewCellMouseEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellMouseEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLMOUSEMOVE] as DataGridViewCellMouseEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } - if (!this.dataGridViewState1[DATAGRIDVIEWSTATE1_scrolledSinceMouseDown] && - !this.IsMouseOperationActive() && - this.AllowUserToOrderColumns && - this.SelectionMode != DataGridViewSelectionMode.FullColumnSelect && - this.SelectionMode != DataGridViewSelectionMode.ColumnHeaderSelect && + if (!dataGridViewState1[DATAGRIDVIEWSTATE1_scrolledSinceMouseDown] && + !IsMouseOperationActive() && + AllowUserToOrderColumns && + SelectionMode != DataGridViewSelectionMode.FullColumnSelect && + SelectionMode != DataGridViewSelectionMode.ColumnHeaderSelect && e.Button == MouseButtons.Left && - this.ptMouseDownCell.Y == -1 && - this.ptMouseDownCell.X >= 0 && - this.ptMouseDownCell.X < this.Columns.Count) + ptMouseDownCell.Y == -1 && + ptMouseDownCell.X >= 0 && + ptMouseDownCell.X < Columns.Count) { Point ptGridCoord = ConvertCellToGridCoord(e.ColumnIndex, e.RowIndex, e.X, e.Y); @@ -12919,11 +12919,11 @@ protected virtual void OnCellMouseMove(DataGridViewCellMouseEventArgs e) case DataGridViewHitTestTypeInternal.ColumnHeaderRight: case DataGridViewHitTestTypeInternal.FirstColumnHeaderLeft: { - Debug.Assert(!this.dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls]); - if (Math.Abs(this.ptMouseDownGridCoord.X - ptGridCoord.X) >= DataGridView.DragSize.Width || - Math.Abs(this.ptMouseDownGridCoord.Y - ptGridCoord.Y) >= DataGridView.DragSize.Height) + Debug.Assert(!dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls]); + if (Math.Abs(ptMouseDownGridCoord.X - ptGridCoord.X) >= DataGridView.DragSize.Width || + Math.Abs(ptMouseDownGridCoord.Y - ptGridCoord.Y) >= DataGridView.DragSize.Height) { - BeginColumnRelocation(this.ptMouseDownGridCoord.X, this.ptMouseDownCell.X); + BeginColumnRelocation(ptMouseDownGridCoord.X, ptMouseDownCell.X); } break; } @@ -12934,11 +12934,11 @@ protected virtual void OnCellMouseMove(DataGridViewCellMouseEventArgs e) [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellMouseUp(DataGridViewCellMouseEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } @@ -12946,7 +12946,7 @@ protected virtual void OnCellMouseUp(DataGridViewCellMouseEventArgs e) Debug.Assert(dataGridViewCell != null); if (e.RowIndex >= 0 && dataGridViewCell.MouseUpUnsharesRowInternal(e)) { - DataGridViewRow dataGridViewRow = this.Rows[e.RowIndex]; + DataGridViewRow dataGridViewRow = Rows[e.RowIndex]; GetCellInternal(e.ColumnIndex, e.RowIndex).OnMouseUpInternal(e); } else @@ -12954,8 +12954,8 @@ protected virtual void OnCellMouseUp(DataGridViewCellMouseEventArgs e) dataGridViewCell.OnMouseUpInternal(e); } - DataGridViewCellMouseEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLMOUSEUP] as DataGridViewCellMouseEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellMouseEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLMOUSEUP] as DataGridViewCellMouseEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -12964,16 +12964,16 @@ protected virtual void OnCellMouseUp(DataGridViewCellMouseEventArgs e) [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected internal virtual void OnCellPainting(DataGridViewCellPaintingEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellPaintingEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLPAINTING] as DataGridViewCellPaintingEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellPaintingEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLPAINTING] as DataGridViewCellPaintingEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -12992,16 +12992,16 @@ internal DataGridViewCellParsingEventArgs OnCellParsing(int rowIndex, int column [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellParsing(DataGridViewCellParsingEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellParsingEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLPARSING] as DataGridViewCellParsingEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellParsingEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLPARSING] as DataGridViewCellParsingEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13009,25 +13009,25 @@ protected virtual void OnCellParsing(DataGridViewCellParsingEventArgs e) private void OnCellSelectMouseMove(HitTestInfo hti) { - Debug.Assert(this.MultiSelect); - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - if ((hti.col != this.ptCurrentCell.X || hti.row != this.ptCurrentCell.Y) && + Debug.Assert(MultiSelect); + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + if ((hti.col != ptCurrentCell.X || hti.row != ptCurrentCell.Y) && !CommitEditForOperation(hti.col, hti.row, true)) { // Return silently if validating/commit/abort failed return; } - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - if (this.ptAnchorCell.X == -1 || IsInnerCellOutOfBounds(hti.col, hti.row)) + if (ptAnchorCell.X == -1 || IsInnerCellOutOfBounds(hti.col, hti.row)) { return; } - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, hti.col, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, hti.row); - if (hti.col != this.ptCurrentCell.X || hti.row != this.ptCurrentCell.Y) + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, hti.col, + ptAnchorCell.Y, ref oldEdgeRowIndex, hti.row); + if (hti.col != ptCurrentCell.X || hti.row != ptCurrentCell.Y) { bool success = SetCurrentCellAddressCore(hti.col, hti.row, false, false, false); Debug.Assert(success); @@ -13035,7 +13035,7 @@ private void OnCellSelectMouseMove(HitTestInfo hti) } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; } } @@ -13047,31 +13047,31 @@ protected virtual void OnCellStateChanged(DataGridViewCellStateChangedEventArgs if (e.StateChanged == DataGridViewElementStates.Selected) { Debug.Assert(dataGridViewCell.RowIndex >= 0); - if (this.inBulkPaintCount == 0) + if (inBulkPaintCount == 0) { InvalidateCellPrivate(dataGridViewCell); } } DataGridViewCellStateChangedEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLSTATECHANGED] as DataGridViewCellStateChangedEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } if (e.StateChanged == DataGridViewElementStates.ReadOnly && - this.ptCurrentCell.X == dataGridViewCell.ColumnIndex && - this.ptCurrentCell.Y == dataGridViewCell.RowIndex && + ptCurrentCell.X == dataGridViewCell.ColumnIndex && + ptCurrentCell.Y == dataGridViewCell.RowIndex && dataGridViewCell.RowIndex > -1 && - !this.dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange]) + !dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange]) { VerifyImeRestrictedModeChanged(); if (!dataGridViewCell.ReadOnly && - ColumnEditable(this.ptCurrentCell.X) && - !this.IsCurrentCellInEditMode && - (this.EditMode == DataGridViewEditMode.EditOnEnter || - (this.EditMode != DataGridViewEditMode.EditProgrammatically && this.CurrentCellInternal.EditType == null))) + ColumnEditable(ptCurrentCell.X) && + !IsCurrentCellInEditMode && + (EditMode == DataGridViewEditMode.EditOnEnter || + (EditMode != DataGridViewEditMode.EditProgrammatically && CurrentCellInternal.EditType == null))) { // Current cell becomes read/write. Enter editing mode. BeginEditInternal(true /*selectAll*/); @@ -13088,18 +13088,18 @@ internal void OnCellStyleChanged(DataGridViewCell dataGridViewCell) [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellStyleChanged(DataGridViewCellEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } OnCellCommonChange(e.ColumnIndex, e.RowIndex); - DataGridViewCellEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLSTYLECHANGED] as DataGridViewCellEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLSTYLECHANGED] as DataGridViewCellEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13111,24 +13111,24 @@ internal void OnCellStyleContentChanged(DataGridViewCellStyle dataGridViewCellSt switch (property) { case DataGridViewCellStyle.DataGridViewCellStylePropertyInternal.Font: - if ((dataGridViewCellStyle.Scope & DataGridViewCellStyleScopes.DataGridView) != 0 && this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientFont]) + if ((dataGridViewCellStyle.Scope & DataGridViewCellStyleScopes.DataGridView) != 0 && dataGridViewState1[DATAGRIDVIEWSTATE1_ambientFont]) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientFont] = false; + dataGridViewState1[DATAGRIDVIEWSTATE1_ambientFont] = false; } - if ((dataGridViewCellStyle.Scope & DataGridViewCellStyleScopes.ColumnHeaders) != 0 && this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientColumnHeadersFont]) + if ((dataGridViewCellStyle.Scope & DataGridViewCellStyleScopes.ColumnHeaders) != 0 && dataGridViewState1[DATAGRIDVIEWSTATE1_ambientColumnHeadersFont]) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientColumnHeadersFont] = false; + dataGridViewState1[DATAGRIDVIEWSTATE1_ambientColumnHeadersFont] = false; } - if ((dataGridViewCellStyle.Scope & DataGridViewCellStyleScopes.RowHeaders) != 0 && this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientRowHeadersFont]) + if ((dataGridViewCellStyle.Scope & DataGridViewCellStyleScopes.RowHeaders) != 0 && dataGridViewState1[DATAGRIDVIEWSTATE1_ambientRowHeadersFont]) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientRowHeadersFont] = false; + dataGridViewState1[DATAGRIDVIEWSTATE1_ambientRowHeadersFont] = false; } break; case DataGridViewCellStyle.DataGridViewCellStylePropertyInternal.ForeColor: - if ((dataGridViewCellStyle.Scope & DataGridViewCellStyleScopes.DataGridView) != 0 && this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientForeColor]) + if ((dataGridViewCellStyle.Scope & DataGridViewCellStyleScopes.DataGridView) != 0 && dataGridViewState1[DATAGRIDVIEWSTATE1_ambientForeColor]) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientForeColor] = false; + dataGridViewState1[DATAGRIDVIEWSTATE1_ambientForeColor] = false; } break; } @@ -13179,9 +13179,9 @@ protected virtual void OnCellStyleContentChanged(DataGridViewCellStyleContentCha { repositionEditingControl = true; // Autosize rows if needed - if ((((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0) + if ((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0) { - AdjustShrinkingRows(this.autoSizeRowsMode, false /*fixedWidth*/, true /*internalAutosizing*/); + AdjustShrinkingRows(autoSizeRowsMode, false /*fixedWidth*/, true /*internalAutosizing*/); } // Auto size columms also if needed // Impossible to figure out if DisplayedRows filter should be added or not. Adding it to be on the conservative side. @@ -13189,75 +13189,75 @@ protected virtual void OnCellStyleContentChanged(DataGridViewCellStyleContentCha DataGridViewAutoSizeColumnCriteriaInternal.DisplayedRows, true /*fixedHeight*/); // Second round of rows autosizing - if ((((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0) + if ((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0) { - AdjustShrinkingRows(this.autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); + AdjustShrinkingRows(autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); } } } if ((e.CellStyleScope & DataGridViewCellStyleScopes.DataGridView) == DataGridViewCellStyleScopes.DataGridView) { - this.CellStyleChangedEventArgs.ChangeAffectsPreferredSize = e.ChangeAffectsPreferredSize; + CellStyleChangedEventArgs.ChangeAffectsPreferredSize = e.ChangeAffectsPreferredSize; if (e.ChangeAffectsPreferredSize) { repositionEditingControl = false; // OnDefaultCellStyleChanged will reposition the editing control. } - OnDefaultCellStyleChanged(this.CellStyleChangedEventArgs); + OnDefaultCellStyleChanged(CellStyleChangedEventArgs); } if ((e.CellStyleScope & DataGridViewCellStyleScopes.ColumnHeaders) == DataGridViewCellStyleScopes.ColumnHeaders) { - this.CellStyleChangedEventArgs.ChangeAffectsPreferredSize = e.ChangeAffectsPreferredSize; + CellStyleChangedEventArgs.ChangeAffectsPreferredSize = e.ChangeAffectsPreferredSize; if (e.ChangeAffectsPreferredSize) { repositionEditingControl = false; // OnColumnHeadersDefaultCellStyleChanged will reposition the editing control. } - OnColumnHeadersDefaultCellStyleChanged(this.CellStyleChangedEventArgs); + OnColumnHeadersDefaultCellStyleChanged(CellStyleChangedEventArgs); } if ((e.CellStyleScope & DataGridViewCellStyleScopes.RowHeaders) == DataGridViewCellStyleScopes.RowHeaders) { - this.CellStyleChangedEventArgs.ChangeAffectsPreferredSize = e.ChangeAffectsPreferredSize; + CellStyleChangedEventArgs.ChangeAffectsPreferredSize = e.ChangeAffectsPreferredSize; if (e.ChangeAffectsPreferredSize) { repositionEditingControl = false; // OnRowHeadersDefaultCellStyleChanged will reposition the editing control. } - OnRowHeadersDefaultCellStyleChanged(this.CellStyleChangedEventArgs); + OnRowHeadersDefaultCellStyleChanged(CellStyleChangedEventArgs); } if ((e.CellStyleScope & DataGridViewCellStyleScopes.Rows) == DataGridViewCellStyleScopes.Rows) { - this.CellStyleChangedEventArgs.ChangeAffectsPreferredSize = e.ChangeAffectsPreferredSize; + CellStyleChangedEventArgs.ChangeAffectsPreferredSize = e.ChangeAffectsPreferredSize; if (e.ChangeAffectsPreferredSize) { repositionEditingControl = false; // OnRowsDefaultCellStyleChanged will reposition the editing control. } - OnRowsDefaultCellStyleChanged(this.CellStyleChangedEventArgs); + OnRowsDefaultCellStyleChanged(CellStyleChangedEventArgs); } if ((e.CellStyleScope & DataGridViewCellStyleScopes.AlternatingRows) == DataGridViewCellStyleScopes.AlternatingRows) { - this.CellStyleChangedEventArgs.ChangeAffectsPreferredSize = e.ChangeAffectsPreferredSize; + CellStyleChangedEventArgs.ChangeAffectsPreferredSize = e.ChangeAffectsPreferredSize; if (e.ChangeAffectsPreferredSize) { repositionEditingControl = false; // OnAlternatingRowsDefaultCellStyleChanged will reposition the editing control. } - OnAlternatingRowsDefaultCellStyleChanged(this.CellStyleChangedEventArgs); + OnAlternatingRowsDefaultCellStyleChanged(CellStyleChangedEventArgs); } - if (repositionEditingControl && this.editingControl != null) + if (repositionEditingControl && editingControl != null) { PositionEditingControl(true /*setLocation*/, true /*setSize*/, false /*setFocus*/); } - DataGridViewCellStyleContentChangedEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLSTYLECONTENTCHANGED] as DataGridViewCellStyleContentChangedEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellStyleContentChangedEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLSTYLECONTENTCHANGED] as DataGridViewCellStyleContentChangedEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13272,16 +13272,16 @@ internal void OnCellToolTipTextChanged(DataGridViewCell dataGridViewCell) [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellToolTipTextChanged(DataGridViewCellEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLTOOLTIPTEXTCHANGED] as DataGridViewCellEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLTOOLTIPTEXTCHANGED] as DataGridViewCellEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13297,16 +13297,16 @@ internal string OnCellToolTipTextNeeded(int columnIndex, int rowIndex, string to [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellToolTipTextNeeded(DataGridViewCellToolTipTextNeededEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellToolTipTextNeededEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLTOOLTIPTEXTNEEDED] as DataGridViewCellToolTipTextNeededEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellToolTipTextNeededEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLTOOLTIPTEXTNEEDED] as DataGridViewCellToolTipTextNeededEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13323,8 +13323,8 @@ internal void OnCellValidated(ref DataGridViewCell dataGridViewCell, int columnI } else { - Debug.Assert(rowIndex < this.Rows.Count && columnIndex < this.Columns.Count); - dataGridViewCell = this.Rows.SharedRow(rowIndex).Cells[columnIndex]; + Debug.Assert(rowIndex < Rows.Count && columnIndex < Columns.Count); + dataGridViewCell = Rows.SharedRow(rowIndex).Cells[columnIndex]; } } } @@ -13332,20 +13332,20 @@ internal void OnCellValidated(ref DataGridViewCell dataGridViewCell, int columnI [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellValidated(DataGridViewCellEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } try { - this.noDimensionChangeCount++; + noDimensionChangeCount++; - DataGridViewCellEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLVALIDATED] as DataGridViewCellEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLVALIDATED] as DataGridViewCellEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); CorrectFocus(true /*onlyIfGridHasFocus*/); @@ -13353,14 +13353,14 @@ protected virtual void OnCellValidated(DataGridViewCellEventArgs e) } finally { - this.noDimensionChangeCount--; - Debug.Assert(this.noDimensionChangeCount >= 0); + noDimensionChangeCount--; + Debug.Assert(noDimensionChangeCount >= 0); } } internal bool OnCellValidating(ref DataGridViewCell dataGridViewCell, int columnIndex, int rowIndex, DataGridViewDataErrorContexts context) { - DataGridViewCell currentCell = (dataGridViewCell == null) ? this.CurrentCellInternal : dataGridViewCell; + DataGridViewCell currentCell = (dataGridViewCell == null) ? CurrentCellInternal : dataGridViewCell; DataGridViewCellStyle dataGridViewCellStyle = currentCell.GetInheritedStyle(null, rowIndex, false); object val = currentCell.GetValueInternal(rowIndex); object editedFormattedValue = currentCell.GetEditedFormattedValue(val, rowIndex, ref dataGridViewCellStyle, context); @@ -13374,8 +13374,8 @@ internal bool OnCellValidating(ref DataGridViewCell dataGridViewCell, int column } else { - Debug.Assert(rowIndex < this.Rows.Count && columnIndex < this.Columns.Count); - dataGridViewCell = this.Rows.SharedRow(rowIndex).Cells[columnIndex]; + Debug.Assert(rowIndex < Rows.Count && columnIndex < Columns.Count); + dataGridViewCell = Rows.SharedRow(rowIndex).Cells[columnIndex]; } } return dgvcfvce.Cancel; @@ -13384,21 +13384,21 @@ internal bool OnCellValidating(ref DataGridViewCell dataGridViewCell, int column [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellValidating(DataGridViewCellValidatingEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } try { - this.noDimensionChangeCount++; - this.dataGridViewOper[DATAGRIDVIEWOPER_inCellValidating] = true; + noDimensionChangeCount++; + dataGridViewOper[DATAGRIDVIEWOPER_inCellValidating] = true; - DataGridViewCellValidatingEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLVALIDATING] as DataGridViewCellValidatingEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellValidatingEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLVALIDATING] as DataGridViewCellValidatingEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); CorrectFocus(true /*onlyIfGridHasFocus*/); @@ -13406,9 +13406,9 @@ protected virtual void OnCellValidating(DataGridViewCellValidatingEventArgs e) } finally { - this.noDimensionChangeCount--; - Debug.Assert(this.noDimensionChangeCount >= 0); - this.dataGridViewOper[DATAGRIDVIEWOPER_inCellValidating] = false; + noDimensionChangeCount--; + Debug.Assert(noDimensionChangeCount >= 0); + dataGridViewOper[DATAGRIDVIEWOPER_inCellValidating] = false; } } @@ -13421,18 +13421,18 @@ internal void OnCellValueChangedInternal(DataGridViewCellEventArgs e) [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellValueChanged(DataGridViewCellEventArgs e) { - if (e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex >= this.Rows.Count) + if (e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } OnCellCommonChange(e.ColumnIndex, e.RowIndex); - DataGridViewCellEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLVALUECHANGED] as DataGridViewCellEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLVALUECHANGED] as DataGridViewCellEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13440,7 +13440,7 @@ protected virtual void OnCellValueChanged(DataGridViewCellEventArgs e) internal object OnCellValueNeeded(int columnIndex, int rowIndex) { - DataGridViewCellValueEventArgs dgvcve = this.CellValueEventArgs; + DataGridViewCellValueEventArgs dgvcve = CellValueEventArgs; dgvcve.SetProperties(columnIndex, rowIndex, null); OnCellValueNeeded(dgvcve); return dgvcve.Value; @@ -13449,11 +13449,11 @@ internal object OnCellValueNeeded(int columnIndex, int rowIndex) [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellValueNeeded(DataGridViewCellValueEventArgs e) { - if (e.ColumnIndex < 0 || e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex < 0 || e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex < 0 || e.RowIndex >= this.Rows.Count) + if (e.RowIndex < 0 || e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } @@ -13462,8 +13462,8 @@ protected virtual void OnCellValueNeeded(DataGridViewCellValueEventArgs e) // but since we're late in Whidbey, throwing an exception would be destabilizing our internal customers. // Debug.Assert(this.dataStoreAccessAllowed); //#endif - DataGridViewCellValueEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLVALUENEEDED] as DataGridViewCellValueEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellValueEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLVALUENEEDED] as DataGridViewCellValueEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13471,7 +13471,7 @@ protected virtual void OnCellValueNeeded(DataGridViewCellValueEventArgs e) internal void OnCellValuePushed(int columnIndex, int rowIndex, object value) { - DataGridViewCellValueEventArgs dgvcve = this.CellValueEventArgs; + DataGridViewCellValueEventArgs dgvcve = CellValueEventArgs; dgvcve.SetProperties(columnIndex, rowIndex, value); OnCellValuePushed(dgvcve); } @@ -13479,16 +13479,16 @@ internal void OnCellValuePushed(int columnIndex, int rowIndex, object value) [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] // e.ColumnIndex / e.RowIndex is more precise than just e protected virtual void OnCellValuePushed(DataGridViewCellValueEventArgs e) { - if (e.ColumnIndex < 0 || e.ColumnIndex >= this.Columns.Count) + if (e.ColumnIndex < 0 || e.ColumnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException("e.ColumnIndex"); } - if (e.RowIndex < 0 || e.RowIndex >= this.Rows.Count) + if (e.RowIndex < 0 || e.RowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellValueEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCELLVALUEPUSHED] as DataGridViewCellValueEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellValueEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLVALUEPUSHED] as DataGridViewCellValueEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13497,7 +13497,7 @@ protected virtual void OnCellValuePushed(DataGridViewCellValueEventArgs e) internal void OnClearedRows() { // Raise the RowStateChanged(Displayed->false) events - foreach (DataGridViewRow dataGridViewRow in this.lstRows) + foreach (DataGridViewRow dataGridViewRow in lstRows) { if (dataGridViewRow.Displayed) { @@ -13506,19 +13506,19 @@ internal void OnClearedRows() OnRowStateChanged(-1 /*rowIndex*/, dgvrsce); } } - this.lstRows.Clear(); + lstRows.Clear(); } internal void OnClearingColumns() { - this.CurrentCell = null; + CurrentCell = null; // Rows need to be cleared first. There cannot be rows without also having columns. - this.Rows.ClearInternal(false /*recreateNewRow*/); + Rows.ClearInternal(false /*recreateNewRow*/); // Reset sort related variables. - this.sortedColumn = null; - this.sortOrder = SortOrder.None; + sortedColumn = null; + sortOrder = SortOrder.None; // selectedBandIndexes, individualSelectedCells & individualReadOnlyCells cleared in OnClearingRows. } @@ -13529,35 +13529,35 @@ internal void OnClearingColumns() internal void OnClearingRows() { // Build a list of displayed rows in order to be able to raise their RowStateChanged(Displayed->false) events later on - this.lstRows.Clear(); - int numDisplayedRows = this.displayedBandsInfo.NumDisplayedFrozenRows + this.displayedBandsInfo.NumDisplayedScrollingRows; + lstRows.Clear(); + int numDisplayedRows = displayedBandsInfo.NumDisplayedFrozenRows + displayedBandsInfo.NumDisplayedScrollingRows; if (numDisplayedRows > 0) { - this.lstRows.Capacity = numDisplayedRows; - int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Displayed); + lstRows.Capacity = numDisplayedRows; + int rowIndex = Rows.GetFirstRow(DataGridViewElementStates.Displayed); while (numDisplayedRows > 0 && rowIndex != -1) { - this.lstRows.Add(this.Rows[rowIndex]); + lstRows.Add(Rows[rowIndex]); numDisplayedRows--; if (numDisplayedRows > 0) { - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Displayed); + rowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Displayed); } } } - this.CurrentCell = null; + CurrentCell = null; - this.newRowIndex = -1; - this.dataGridViewState2[DATAGRIDVIEWSTATE2_raiseSelectionChanged] = this.selectedBandIndexes.Count > 0 || - this.individualSelectedCells.Count > 0; - this.selectedBandIndexes.Clear(); - if (this.selectedBandSnapshotIndexes != null) + newRowIndex = -1; + dataGridViewState2[DATAGRIDVIEWSTATE2_raiseSelectionChanged] = selectedBandIndexes.Count > 0 || + individualSelectedCells.Count > 0; + selectedBandIndexes.Clear(); + if (selectedBandSnapshotIndexes != null) { - this.selectedBandSnapshotIndexes.Clear(); + selectedBandSnapshotIndexes.Clear(); } - this.individualSelectedCells.Clear(); - this.individualReadOnlyCells.Clear(); + individualSelectedCells.Clear(); + individualReadOnlyCells.Clear(); } protected virtual void OnColumnAdded(DataGridViewColumnEventArgs e) @@ -13566,8 +13566,8 @@ protected virtual void OnColumnAdded(DataGridViewColumnEventArgs e) { throw new ArgumentException(string.Format(SR.DataGridView_ColumnDoesNotBelongToDataGridView)); } - DataGridViewColumnEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNADDED] as DataGridViewColumnEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNADDED] as DataGridViewColumnEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13576,7 +13576,7 @@ protected virtual void OnColumnAdded(DataGridViewColumnEventArgs e) internal void OnColumnCollectionChanged_PreNotification(CollectionChangeEventArgs ccea) { // we need to map columns w/ DataPropertyName to bound columns - if (this.DataSource != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inRefreshColumns]) + if (DataSource != null && !dataGridViewOper[DATAGRIDVIEWOPER_inRefreshColumns]) { if (ccea.Action == CollectionChangeAction.Add) { @@ -13588,11 +13588,11 @@ internal void OnColumnCollectionChanged_PreNotification(CollectionChangeEventArg } else if (ccea.Action == CollectionChangeAction.Refresh) { - for (int i = 0; i < this.Columns.Count; i++) + for (int i = 0; i < Columns.Count; i++) { - if (this.Columns[i].DataPropertyName.Length != 0) + if (Columns[i].DataPropertyName.Length != 0) { - MapDataGridViewColumnToDataBoundField(this.Columns[i]); + MapDataGridViewColumnToDataBoundField(Columns[i]); } } } @@ -13603,21 +13603,21 @@ internal void OnColumnCollectionChanged_PreNotification(CollectionChangeEventArg internal void OnColumnCollectionChanged_PostNotification(DataGridViewColumn dataGridViewColumn) { - if (this.Columns.Count != 0 && this.Rows.Count == 0) + if (Columns.Count != 0 && Rows.Count == 0) { - if (this.DataSource != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inRefreshColumns]) + if (DataSource != null && !dataGridViewOper[DATAGRIDVIEWOPER_inRefreshColumns]) { // this will create the 'add new row' when AllowUserToAddRowsInternal == true RefreshRows(true /*scrollIntoView*/); } - else if (this.AllowUserToAddRowsInternal) + else if (AllowUserToAddRowsInternal) { AddNewRow(false); } } - if (this.AutoSize && (dataGridViewColumn == null || dataGridViewColumn.Visible)) + if (AutoSize && (dataGridViewColumn == null || dataGridViewColumn.Visible)) { - LayoutTransaction.DoLayout(this.ParentInternal, this, PropertyNames.Columns); + LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.Columns); } } @@ -13632,8 +13632,8 @@ protected virtual void OnColumnContextMenuStripChanged(DataGridViewColumnEventAr { throw new ArgumentException(string.Format(SR.DataGridView_ColumnDoesNotBelongToDataGridView)); } - DataGridViewColumnEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNCONTEXTMENUSTRIPCHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNCONTEXTMENUSTRIPCHANGED] as DataGridViewColumnEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13651,11 +13651,11 @@ protected virtual void OnColumnDataPropertyNameChanged(DataGridViewColumnEventAr throw new ArgumentException(string.Format(SR.DataGridView_ColumnDoesNotBelongToDataGridView)); } // map the dataGridView column to some data field - if (this.DataSource != null && e.Column.DataPropertyName.Length != 0 && !this.dataGridViewOper[DATAGRIDVIEWOPER_inRefreshColumns]) + if (DataSource != null && e.Column.DataPropertyName.Length != 0 && !dataGridViewOper[DATAGRIDVIEWOPER_inRefreshColumns]) { MapDataGridViewColumnToDataBoundField(e.Column); } - else if (this.DataSource != null && e.Column.DataPropertyName.Length == 0) + else if (DataSource != null && e.Column.DataPropertyName.Length == 0) { if (e.Column.IsDataBound) { @@ -13666,8 +13666,8 @@ protected virtual void OnColumnDataPropertyNameChanged(DataGridViewColumnEventAr } } - DataGridViewColumnEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNDATAPROPERTYNAMECHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNDATAPROPERTYNAMECHANGED] as DataGridViewColumnEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13681,8 +13681,8 @@ protected virtual void OnColumnDefaultCellStyleChanged(DataGridViewColumnEventAr } OnColumnGlobalAutoSize(e.Column.Index); - DataGridViewColumnEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNDEFAULTCELLSTYLECHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNDEFAULTCELLSTYLECHANGED] as DataGridViewColumnEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13700,7 +13700,7 @@ internal void OnColumnDisplayIndexChanging(DataGridViewColumn dataGridViewColumn Debug.Assert(dataGridViewColumn != null); Debug.Assert(newDisplayIndex != dataGridViewColumn.DisplayIndex); - if (this.dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments]) + if (dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments]) { // We are within columns display indexes adjustments. We do not allow changing display indexes while adjusting them. throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAlterDisplayIndexWithinAdjustments)); @@ -13711,14 +13711,14 @@ internal void OnColumnDisplayIndexChanging(DataGridViewColumn dataGridViewColumn try { - this.dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments] = true; + dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments] = true; // Move is legal - let's adjust the affected display indexes. if (newDisplayIndex < dataGridViewColumn.DisplayIndex) { // DisplayIndex decreases. All columns with newDisplayIndex <= DisplayIndex < dataGridViewColumn.DisplayIndex // get their DisplayIndex incremented. - foreach (DataGridViewColumn dataGridViewColumnTmp in this.Columns) + foreach (DataGridViewColumn dataGridViewColumnTmp in Columns) { if (newDisplayIndex <= dataGridViewColumnTmp.DisplayIndex && dataGridViewColumnTmp.DisplayIndex < dataGridViewColumn.DisplayIndex) { @@ -13731,7 +13731,7 @@ internal void OnColumnDisplayIndexChanging(DataGridViewColumn dataGridViewColumn { // DisplayIndex increases. All columns with dataGridViewColumn.DisplayIndex < DisplayIndex <= newDisplayIndex // get their DisplayIndex incremented. - foreach (DataGridViewColumn dataGridViewColumnTmp in this.Columns) + foreach (DataGridViewColumn dataGridViewColumnTmp in Columns) { if (dataGridViewColumn.DisplayIndex < dataGridViewColumnTmp.DisplayIndex && dataGridViewColumnTmp.DisplayIndex <= newDisplayIndex) { @@ -13743,7 +13743,7 @@ internal void OnColumnDisplayIndexChanging(DataGridViewColumn dataGridViewColumn } finally { - this.dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments] = false; + dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments] = false; } // Note that displayIndex of moved column is updated by caller. @@ -13756,12 +13756,12 @@ protected virtual void OnColumnDisplayIndexChanged(DataGridViewColumnEventArgs e throw new ArgumentException(string.Format(SR.DataGridView_ColumnDoesNotBelongToDataGridView)); } - Debug.Assert(this.dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments]); + Debug.Assert(dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments]); #if DEBUG - Debug.Assert(this.Columns.VerifyColumnDisplayIndexes()); + Debug.Assert(Columns.VerifyColumnDisplayIndexes()); #endif - DataGridViewColumnEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNDISPLAYINDEXCHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNDISPLAYINDEXCHANGED] as DataGridViewColumnEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13769,17 +13769,17 @@ protected virtual void OnColumnDisplayIndexChanged(DataGridViewColumnEventArgs e internal void OnColumnDisplayIndexChanged_PreNotification() { - Debug.Assert(this.dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments]); + Debug.Assert(dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments]); // column.DisplayIndex changed - this may require a complete re-layout of the control - this.Columns.InvalidateCachedColumnsOrder(); + Columns.InvalidateCachedColumnsOrder(); PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); - if (this.editingControl != null) + if (editingControl != null) { PositionEditingControl(true, true, false); } - Invalidate(Rectangle.Union(this.layout.ColumnHeaders, this.layout.Data)); + Invalidate(Rectangle.Union(layout.ColumnHeaders, layout.Data)); } internal void OnColumnDisplayIndexChanged_PostNotification() @@ -13790,13 +13790,13 @@ internal void OnColumnDisplayIndexChanged_PostNotification() protected virtual void OnColumnDividerDoubleClick(DataGridViewColumnDividerDoubleClickEventArgs e) { - DataGridViewColumnDividerDoubleClickEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNDIVIDERDOUBLECLICK] as DataGridViewColumnDividerDoubleClickEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewColumnDividerDoubleClickEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNDIVIDERDOUBLECLICK] as DataGridViewColumnDividerDoubleClickEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } - if (!e.Handled && e.Button == MouseButtons.Left && e.ColumnIndex < this.Columns.Count) + if (!e.Handled && e.Button == MouseButtons.Left && e.ColumnIndex < Columns.Count) { if (e.ColumnIndex == -1) { @@ -13806,7 +13806,7 @@ protected virtual void OnColumnDividerDoubleClick(DataGridViewColumnDividerDoubl } else { - DataGridViewAutoSizeColumnMode inheritedAutoSizeMode = this.Columns[e.ColumnIndex].InheritedAutoSizeMode; + DataGridViewAutoSizeColumnMode inheritedAutoSizeMode = Columns[e.ColumnIndex].InheritedAutoSizeMode; if (inheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.None || inheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill) { AutoResizeColumnInternal(e.ColumnIndex, DataGridViewAutoSizeColumnCriteriaInternal.Header | DataGridViewAutoSizeColumnCriteriaInternal.AllRows, true /*fixedHeight*/); @@ -13827,8 +13827,8 @@ protected virtual void OnColumnDividerWidthChanged(DataGridViewColumnEventArgs e } OnColumnGlobalAutoSize(e.Column.Index); - DataGridViewColumnEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNDIVIDERWIDTHCHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNDIVIDERWIDTHCHANGED] as DataGridViewColumnEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13839,7 +13839,7 @@ internal void OnColumnFillWeightChanged(DataGridViewColumn dataGridViewColumn) if (dataGridViewColumn.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill) { // UsedFillWeight properties need to be re-evaluated - this.dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = true; // Adjust filling columns based on new weight of this column PerformLayoutPrivate(false /*useRowShortcut*/, true /*computeVisibleRows*/, false /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); } @@ -13847,13 +13847,13 @@ internal void OnColumnFillWeightChanged(DataGridViewColumn dataGridViewColumn) internal void OnColumnFillWeightChanging(DataGridViewColumn dataGridViewColumn, float fillWeight) { - if (this.InAdjustFillingColumns) + if (InAdjustFillingColumns) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAlterAutoFillColumnParameter)); } // Make sure the sum of the column weights does not exceed ushort.MaxValue - float weightSum = this.Columns.GetColumnsFillWeight(DataGridViewElementStates.None) - dataGridViewColumn.FillWeight + fillWeight; + float weightSum = Columns.GetColumnsFillWeight(DataGridViewElementStates.None) - dataGridViewColumn.FillWeight + fillWeight; if (weightSum > (float)ushort.MaxValue) { throw new InvalidOperationException(string.Format(SR.DataGridView_WeightSumCannotExceedLongMaxValue, ushort.MaxValue)); @@ -13862,23 +13862,23 @@ internal void OnColumnFillWeightChanging(DataGridViewColumn dataGridViewColumn, private void OnColumnGlobalAutoSize(int columnIndex) { - Debug.Assert(columnIndex >= 0 && columnIndex < this.Columns.Count); + Debug.Assert(columnIndex >= 0 && columnIndex < Columns.Count); - if (!this.Columns[columnIndex].Visible) + if (!Columns[columnIndex].Visible) { return; } InvalidateColumnInternal(columnIndex); - if (this.noAutoSizeCount > 0) + if (noAutoSizeCount > 0) { return; } - bool fixedHeight = (((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) == 0; + bool fixedHeight = (((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) == 0; - DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaInternal = (DataGridViewAutoSizeColumnCriteriaInternal)this.Columns[columnIndex].InheritedAutoSizeMode; + DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaInternal = (DataGridViewAutoSizeColumnCriteriaInternal)Columns[columnIndex].InheritedAutoSizeMode; if (autoSizeColumnCriteriaInternal != DataGridViewAutoSizeColumnCriteriaInternal.None && autoSizeColumnCriteriaInternal != DataGridViewAutoSizeColumnCriteriaInternal.Fill) { @@ -13888,9 +13888,9 @@ private void OnColumnGlobalAutoSize(int columnIndex) // Autosize rows and column headers if needed if (!fixedHeight) { - AdjustShrinkingRows(this.autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); + AdjustShrinkingRows(autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); } - if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) + if (ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) { AutoResizeColumnHeadersHeight(columnIndex, true /*fixedRowHeadersWidth*/, true /*fixedColumnWidth*/); } @@ -13912,8 +13912,8 @@ protected virtual void OnColumnHeaderCellChanged(DataGridViewColumnEventArgs e) OnColumnHeaderGlobalAutoSize(e.Column.Index); - DataGridViewColumnEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNHEADERCELLCHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNHEADERCELLCHANGED] as DataGridViewColumnEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13921,23 +13921,23 @@ protected virtual void OnColumnHeaderCellChanged(DataGridViewColumnEventArgs e) private void OnColumnHeaderGlobalAutoSize(int columnIndex) { - if (!this.ColumnHeadersVisible) + if (!ColumnHeadersVisible) { return; } InvalidateCellPrivate(columnIndex, -1); - if (this.noAutoSizeCount > 0) + if (noAutoSizeCount > 0) { return; } - DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaInternal = (DataGridViewAutoSizeColumnCriteriaInternal)this.Columns[columnIndex].InheritedAutoSizeMode; + DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaInternal = (DataGridViewAutoSizeColumnCriteriaInternal)Columns[columnIndex].InheritedAutoSizeMode; DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaFiltered = autoSizeColumnCriteriaInternal & DataGridViewAutoSizeColumnCriteriaInternal.Header; bool fixedColumnWidth = autoSizeColumnCriteriaFiltered == 0; - if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) + if (ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) { AutoResizeColumnHeadersHeight(columnIndex, true /*fixedRowHeadersWidth*/, fixedColumnWidth); } @@ -13946,15 +13946,15 @@ private void OnColumnHeaderGlobalAutoSize(int columnIndex) { Debug.Assert(autoSizeColumnCriteriaInternal != DataGridViewAutoSizeColumnCriteriaInternal.None); Debug.Assert(autoSizeColumnCriteriaInternal != DataGridViewAutoSizeColumnCriteriaInternal.Fill); - bool fixedHeight = (((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) == 0; + bool fixedHeight = (((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) == 0; AutoResizeColumnInternal(columnIndex, autoSizeColumnCriteriaInternal, fixedHeight); if (!fixedHeight) { - AdjustShrinkingRows(this.autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); + AdjustShrinkingRows(autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); // Second round of column autosizing with 1 degree of freedom AutoResizeColumnInternal(columnIndex, autoSizeColumnCriteriaInternal, true /*fixedHeight*/); } - if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) + if (ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) { // Second round of column headers autosizing with 1 degree of freedom AutoResizeColumnHeadersHeight(columnIndex, true /*fixedRowHeadersWidth*/, true /*fixedColumnWidth*/); @@ -13965,28 +13965,28 @@ private void OnColumnHeaderGlobalAutoSize(int columnIndex) protected virtual void OnColumnHeaderMouseClick(DataGridViewCellMouseEventArgs e) { if (e.Button == MouseButtons.Left && - this.SelectionMode != DataGridViewSelectionMode.FullColumnSelect && - this.SelectionMode != DataGridViewSelectionMode.ColumnHeaderSelect) + SelectionMode != DataGridViewSelectionMode.FullColumnSelect && + SelectionMode != DataGridViewSelectionMode.ColumnHeaderSelect) { - DataGridViewColumn dataGridViewColumn = this.Columns[e.ColumnIndex]; + DataGridViewColumn dataGridViewColumn = Columns[e.ColumnIndex]; if (CanSort(dataGridViewColumn)) { ListSortDirection direction = ListSortDirection.Ascending; - if (this.sortedColumn == dataGridViewColumn) + if (sortedColumn == dataGridViewColumn) { - Debug.Assert(this.sortOrder != SortOrder.None); - if (this.sortOrder == SortOrder.Ascending) + Debug.Assert(sortOrder != SortOrder.None); + if (sortOrder == SortOrder.Ascending) { direction = ListSortDirection.Descending; } } - if ((this.DataSource == null) || - (this.DataSource != null && - (this.dataConnection.List is IBindingList) && - ((IBindingList)this.dataConnection.List).SupportsSorting && + if ((DataSource == null) || + (DataSource != null && + (dataConnection.List is IBindingList) && + ((IBindingList)dataConnection.List).SupportsSorting && dataGridViewColumn.IsDataBound)) { Sort(dataGridViewColumn, direction); @@ -13994,8 +13994,8 @@ protected virtual void OnColumnHeaderMouseClick(DataGridViewCellMouseEventArgs e } } - DataGridViewCellMouseEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNHEADERMOUSECLICK] as DataGridViewCellMouseEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellMouseEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNHEADERMOUSECLICK] as DataGridViewCellMouseEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14003,8 +14003,8 @@ protected virtual void OnColumnHeaderMouseClick(DataGridViewCellMouseEventArgs e protected virtual void OnColumnHeaderMouseDoubleClick(DataGridViewCellMouseEventArgs e) { - DataGridViewCellMouseEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNHEADERMOUSEDOUBLECLICK] as DataGridViewCellMouseEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellMouseEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNHEADERMOUSEDOUBLECLICK] as DataGridViewCellMouseEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14013,10 +14013,10 @@ protected virtual void OnColumnHeaderMouseDoubleClick(DataGridViewCellMouseEvent private void OnColumnHeaderMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDown) { Debug.Assert(hti.Type == DataGridViewHitTestType.ColumnHeader); - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: case DataGridViewSelectionMode.FullRowSelect: @@ -14027,26 +14027,26 @@ private void OnColumnHeaderMouseDown(HitTestInfo hti, bool isShiftDown, bool isC case DataGridViewSelectionMode.ColumnHeaderSelect: { bool select = true; - if (isControlDown && this.Columns[hti.col].Selected) + if (isControlDown && Columns[hti.col].Selected) { select = false; } if (select) { - int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); - if (rowIndex > -1 && hti.col != this.ptCurrentCell.X) + int rowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); + if (rowIndex > -1 && hti.col != ptCurrentCell.X) { // Make sure we will be able to scroll into view - int oldCurrentCellX = this.ptCurrentCell.X; - int oldCurrentCellY = this.ptCurrentCell.Y; + int oldCurrentCellX = ptCurrentCell.X; + int oldCurrentCellY = ptCurrentCell.Y; if (!EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.CurrentCellChange, DataGridViewValidateCellInternal.Always /*validateCell*/, true /*fireCellLeave*/, true /*fireCellEnter*/, - rowIndex != this.ptCurrentCell.Y /*fireRowLeave*/, - rowIndex != this.ptCurrentCell.Y /*fireRowEnter*/, + rowIndex != ptCurrentCell.Y /*fireRowLeave*/, + rowIndex != ptCurrentCell.Y /*fireRowEnter*/, false /*fireLeave*/, - this.EditMode != DataGridViewEditMode.EditOnEnter /*keepFocus*/, + EditMode != DataGridViewEditMode.EditOnEnter /*keepFocus*/, true /*resetCurrentCell*/, false /*resetAnchorCell*/)) { @@ -14088,46 +14088,46 @@ private void OnColumnHeaderMouseDown(HitTestInfo hti, bool isShiftDown, bool isC } bool selectColumnRange = false; - this.trackColumn = hti.col; - this.trackColumnEdge = -1; - if (this.MultiSelect && + trackColumn = hti.col; + trackColumnEdge = -1; + if (MultiSelect && isShiftDown && - this.ptAnchorCell.X > -1 && - this.Columns[this.ptAnchorCell.X].Selected) + ptAnchorCell.X > -1 && + Columns[ptAnchorCell.X].Selected) { selectColumnRange = true; } - if (!this.MultiSelect || !isControlDown || isShiftDown) + if (!MultiSelect || !isControlDown || isShiftDown) { - Debug.Assert(this.MultiSelect || this.selectedBandIndexes.Count <= 1); + Debug.Assert(MultiSelect || selectedBandIndexes.Count <= 1); int bandIndex = 0; bool switchedToBulkPaint = false; - if (this.selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) + if (selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) { - this.inBulkPaintCount++; + inBulkPaintCount++; switchedToBulkPaint = true; } try { - while (bandIndex < this.selectedBandIndexes.Count) + while (bandIndex < selectedBandIndexes.Count) { - if (this.selectedBandIndexes[bandIndex] != hti.col) + if (selectedBandIndexes[bandIndex] != hti.col) { // deselect currently selected column - SetSelectedColumnCore(this.selectedBandIndexes[bandIndex], false); + SetSelectedColumnCore(selectedBandIndexes[bandIndex], false); } else { bandIndex++; } } - if (this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) + if (SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) { RemoveIndividuallySelectedCells(); } else { - Debug.Assert(this.individualSelectedCells.Count == 0); + Debug.Assert(individualSelectedCells.Count == 0); } } finally @@ -14138,29 +14138,29 @@ private void OnColumnHeaderMouseDown(HitTestInfo hti, bool isShiftDown, bool isC } } } - if (this.MultiSelect && this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) + if (MultiSelect && dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) { - this.dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] = true; + dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] = true; } if (selectColumnRange) { - if (this.Columns.DisplayInOrder(this.ptAnchorCell.X, hti.col)) + if (Columns.DisplayInOrder(ptAnchorCell.X, hti.col)) { - SelectColumnRange(this.ptAnchorCell.X, hti.col, true); + SelectColumnRange(ptAnchorCell.X, hti.col, true); } else { - SelectColumnRange(hti.col, this.ptAnchorCell.X, true); + SelectColumnRange(hti.col, ptAnchorCell.X, true); } } - else if (!this.selectedBandIndexes.Contains(hti.col)) + else if (!selectedBandIndexes.Contains(hti.col)) { SetSelectedColumnCore(hti.col, true); } // set current cell to the top most visible cell in the column if (rowIndex != -1) { - if (hti.col != this.ptCurrentCell.X) + if (hti.col != ptCurrentCell.X) { if (IsInnerCellOutOfBounds(hti.col, rowIndex)) { @@ -14175,21 +14175,21 @@ private void OnColumnHeaderMouseDown(HitTestInfo hti, bool isShiftDown, bool isC success = SetCurrentCellAddressCore(hti.col, rowIndex, !isShiftDown, false, true); Debug.Assert(success); } - else if (-1 != this.ptCurrentCell.X) + else if (-1 != ptCurrentCell.X) { // Potentially have to give focus back to the current edited cell. - bool success = SetCurrentCellAddressCore(this.ptCurrentCell.X, this.ptCurrentCell.Y, false /*setAnchorCellAddress*/, false /*validateCurrentCell*/, false /*throughMouseClick*/); + bool success = SetCurrentCellAddressCore(ptCurrentCell.X, ptCurrentCell.Y, false /*setAnchorCellAddress*/, false /*validateCurrentCell*/, false /*throughMouseClick*/); Debug.Assert(success); } } else { - Debug.Assert(this.CurrentCellAddress == new Point(-1, -1)); + Debug.Assert(CurrentCellAddress == new Point(-1, -1)); } } else { - Debug.Assert(this.selectedBandIndexes.Contains(hti.col)); + Debug.Assert(selectedBandIndexes.Contains(hti.col)); SetSelectedColumnCore(hti.col, false); } break; @@ -14198,7 +14198,7 @@ private void OnColumnHeaderMouseDown(HitTestInfo hti, bool isShiftDown, bool isC } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; } } @@ -14207,8 +14207,8 @@ protected virtual void OnColumnHeadersBorderStyleChanged(EventArgs e) PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); Invalidate(); - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNHEADERSBORDERSTYLECHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNHEADERSBORDERSTYLECHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14216,23 +14216,23 @@ protected virtual void OnColumnHeadersBorderStyleChanged(EventArgs e) protected virtual void OnColumnHeadersDefaultCellStyleChanged(EventArgs e) { - if (this.ColumnHeadersVisible) + if (ColumnHeadersVisible) { - Invalidate(Rectangle.Union(this.layout.TopLeftHeader, this.layout.ColumnHeaders)); + Invalidate(Rectangle.Union(layout.TopLeftHeader, layout.ColumnHeaders)); DataGridViewCellStyleChangedEventArgs dgvcsce = e as DataGridViewCellStyleChangedEventArgs; if (dgvcsce == null || dgvcsce.ChangeAffectsPreferredSize) { OnColumnHeadersGlobalAutoSize(); - if (this.editingControl != null) + if (editingControl != null) { PositionEditingControl(true /*setLocation*/, true /*setSize*/, false /*setFocus*/); } } } - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNHEADERSDEFAULTCELLSTYLECHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNHEADERSDEFAULTCELLSTYLECHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14240,14 +14240,14 @@ protected virtual void OnColumnHeadersDefaultCellStyleChanged(EventArgs e) private void OnColumnHeadersGlobalAutoSize() { - if (this.noAutoSizeCount > 0) + if (noAutoSizeCount > 0) { return; } - bool fixedRowHeadersWidth = this.rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing || - this.rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.DisableResizing; - bool fixedColumnHeadersHeight = this.ColumnHeadersHeightSizeMode != DataGridViewColumnHeadersHeightSizeMode.AutoSize; + bool fixedRowHeadersWidth = rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing || + rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.DisableResizing; + bool fixedColumnHeadersHeight = ColumnHeadersHeightSizeMode != DataGridViewColumnHeadersHeightSizeMode.AutoSize; if (!fixedColumnHeadersHeight) { @@ -14256,7 +14256,7 @@ private void OnColumnHeadersGlobalAutoSize() if (!fixedRowHeadersWidth) { - AutoResizeRowHeadersWidth(this.rowHeadersWidthSizeMode, true /*fixedColumnHeadersHeight*/, false /*fixedRowsHeight*/); + AutoResizeRowHeadersWidth(rowHeadersWidthSizeMode, true /*fixedColumnHeadersHeight*/, false /*fixedRowsHeight*/); } // Autosize columns @@ -14265,7 +14265,7 @@ private void OnColumnHeadersGlobalAutoSize() if (!fixedRowHeadersWidth || columnAutoSized) { // Autosize rows - AdjustShrinkingRows(this.autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); + AdjustShrinkingRows(autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); } if (!fixedColumnHeadersHeight) @@ -14277,7 +14277,7 @@ private void OnColumnHeadersGlobalAutoSize() if (!fixedRowHeadersWidth) { // Second round of row headers autosizing - AutoResizeRowHeadersWidth(this.rowHeadersWidthSizeMode, true /*fixedColumnHeadersHeight*/, true /*fixedRowsHeight*/); + AutoResizeRowHeadersWidth(rowHeadersWidthSizeMode, true /*fixedColumnHeadersHeight*/, true /*fixedRowsHeight*/); } // Second round of columns autosizing @@ -14286,7 +14286,7 @@ private void OnColumnHeadersGlobalAutoSize() protected virtual void OnColumnHeadersHeightChanged(EventArgs e) { - if (this.editingControl != null) + if (editingControl != null) { PositionEditingControl(true, false, false); } @@ -14295,8 +14295,8 @@ protected virtual void OnColumnHeadersHeightChanged(EventArgs e) OnColumnHeadersGlobalAutoSize(); - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNHEADERSHEIGHTCHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNHEADERSHEIGHTCHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14304,22 +14304,22 @@ protected virtual void OnColumnHeadersHeightChanged(EventArgs e) protected virtual void OnColumnHeadersHeightSizeModeChanged(DataGridViewAutoSizeModeEventArgs e) { - if (this.columnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) + if (columnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) { if (!e.PreviousModeAutoSized) { // Save current column headers height for later reuse - this.cachedColumnHeadersHeight = this.ColumnHeadersHeight; + cachedColumnHeadersHeight = ColumnHeadersHeight; } AutoResizeColumnHeadersHeight(true /*fixedRowHeadersWidth*/, true /*fixedColumnsWidth*/); } else if (e.PreviousModeAutoSized) { - this.ColumnHeadersHeight = this.cachedColumnHeadersHeight; + ColumnHeadersHeight = cachedColumnHeadersHeight; } - DataGridViewAutoSizeModeEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNHEADERSHEIGHTSIZEMODECHANGED] as DataGridViewAutoSizeModeEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewAutoSizeModeEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNHEADERSHEIGHTSIZEMODECHANGED] as DataGridViewAutoSizeModeEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14343,7 +14343,7 @@ internal void OnColumnMinimumWidthChanging(DataGridViewColumn dataGridViewColumn // Force the filled column's width to be minimumWidth try { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = true; dataGridViewColumn.DesiredMinimumWidth = minimumWidth; PerformLayoutPrivate(false /*useRowShortcut*/, true /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); } @@ -14367,8 +14367,8 @@ protected virtual void OnColumnMinimumWidthChanged(DataGridViewColumnEventArgs e PerformLayoutPrivate(false /*useRowShortcut*/, true /*computeVisibleRows*/, false /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); } - DataGridViewColumnEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNMINIMUMWIDTHCHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNMINIMUMWIDTHCHANGED] as DataGridViewColumnEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14397,22 +14397,22 @@ protected virtual void OnColumnNameChanged(DataGridViewColumnEventArgs e) DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaInternal = (DataGridViewAutoSizeColumnCriteriaInternal)dataGridViewColumn.InheritedAutoSizeMode; DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaFiltered = autoSizeColumnCriteriaInternal & DataGridViewAutoSizeColumnCriteriaInternal.Header; - bool fixedColumnWidth = autoSizeColumnCriteriaFiltered == 0 || !this.ColumnHeadersVisible; - if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) + bool fixedColumnWidth = autoSizeColumnCriteriaFiltered == 0 || !ColumnHeadersVisible; + if (ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) { AutoResizeColumnHeadersHeight(dataGridViewColumn.Index, true /*fixedRowHeadersWidth*/, fixedColumnWidth); } if (!fixedColumnWidth) { - bool fixedHeight = (((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) == 0; + bool fixedHeight = (((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) == 0; AutoResizeColumnInternal(dataGridViewColumn.Index, autoSizeColumnCriteriaInternal, fixedHeight); if (!fixedHeight) { - AdjustShrinkingRows(this.autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); + AdjustShrinkingRows(autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); // Second round of column autosizing AutoResizeColumnInternal(dataGridViewColumn.Index, autoSizeColumnCriteriaInternal, true /*fixedHeight*/); } - if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) + if (ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) { // Second round of column headers autosizing AutoResizeColumnHeadersHeight(dataGridViewColumn.Index, true /*fixedRowHeadersWidth*/, true /*fixedColumnWidth*/); @@ -14420,8 +14420,8 @@ protected virtual void OnColumnNameChanged(DataGridViewColumnEventArgs e) } } - DataGridViewColumnEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNNAMECHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNNAMECHANGED] as DataGridViewColumnEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14436,8 +14436,8 @@ internal void OnColumnRemoved(DataGridViewColumn dataGridViewColumn) protected virtual void OnColumnRemoved(DataGridViewColumnEventArgs e) { - DataGridViewColumnEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNREMOVED] as DataGridViewColumnEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNREMOVED] as DataGridViewColumnEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14446,11 +14446,11 @@ protected virtual void OnColumnRemoved(DataGridViewColumnEventArgs e) private void OnColumnSelectMouseMove(HitTestInfo hti) { Debug.Assert(hti.col >= 0); - Debug.Assert(this.MultiSelect); + Debug.Assert(MultiSelect); - if (this.ptCurrentCell.X != -1 && - hti.col != this.ptCurrentCell.X && - !CommitEditForOperation(hti.col, this.ptCurrentCell.Y, true)) + if (ptCurrentCell.X != -1 && + hti.col != ptCurrentCell.X && + !CommitEditForOperation(hti.col, ptCurrentCell.Y, true)) { // Return silently if validating/commit/abort failed return; @@ -14460,85 +14460,85 @@ private void OnColumnSelectMouseMove(HitTestInfo hti) return; } - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - if (this.trackColumnEdge >= 0 && (this.Columns.DisplayInOrder(this.trackColumn, this.trackColumnEdge) || this.trackColumnEdge == this.trackColumn) && this.Columns.DisplayInOrder(this.trackColumnEdge, hti.col)) + if (trackColumnEdge >= 0 && (Columns.DisplayInOrder(trackColumn, trackColumnEdge) || trackColumnEdge == trackColumn) && Columns.DisplayInOrder(trackColumnEdge, hti.col)) { - DataGridViewColumn dataGridViewColumn = this.Columns.GetNextColumn(this.Columns[this.trackColumnEdge], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + DataGridViewColumn dataGridViewColumn = Columns.GetNextColumn(Columns[trackColumnEdge], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); SelectColumnRange(dataGridViewColumn.Index, hti.col, true); - this.trackColumnEdge = hti.col; + trackColumnEdge = hti.col; } - else if (this.trackColumnEdge >= 0 && this.Columns.DisplayInOrder(this.trackColumn, this.trackColumnEdge) && this.Columns.DisplayInOrder(hti.col, this.trackColumnEdge) && (this.Columns.DisplayInOrder(this.trackColumn, hti.col) || hti.col == this.trackColumn)) + else if (trackColumnEdge >= 0 && Columns.DisplayInOrder(trackColumn, trackColumnEdge) && Columns.DisplayInOrder(hti.col, trackColumnEdge) && (Columns.DisplayInOrder(trackColumn, hti.col) || hti.col == trackColumn)) { - DataGridViewColumn dataGridViewColumn = this.Columns.GetNextColumn(this.Columns[hti.col], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + DataGridViewColumn dataGridViewColumn = Columns.GetNextColumn(Columns[hti.col], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); - SelectColumnRange(dataGridViewColumn.Index, this.trackColumnEdge, false); - this.trackColumnEdge = hti.col; + SelectColumnRange(dataGridViewColumn.Index, trackColumnEdge, false); + trackColumnEdge = hti.col; } - else if (this.trackColumnEdge == -1 && this.Columns.DisplayInOrder(this.trackColumn, hti.col)) + else if (trackColumnEdge == -1 && Columns.DisplayInOrder(trackColumn, hti.col)) { - DataGridViewColumn dataGridViewColumn = this.Columns.GetNextColumn(this.Columns[this.trackColumn], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + DataGridViewColumn dataGridViewColumn = Columns.GetNextColumn(Columns[trackColumn], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); SelectColumnRange(dataGridViewColumn.Index, hti.col, true); - this.trackColumnEdge = hti.col; + trackColumnEdge = hti.col; } - else if (this.trackColumnEdge >= 0 && (this.Columns.DisplayInOrder(this.trackColumnEdge, this.trackColumn) || this.trackColumnEdge == this.trackColumn) && this.Columns.DisplayInOrder(hti.col, this.trackColumnEdge)) + else if (trackColumnEdge >= 0 && (Columns.DisplayInOrder(trackColumnEdge, trackColumn) || trackColumnEdge == trackColumn) && Columns.DisplayInOrder(hti.col, trackColumnEdge)) { - DataGridViewColumn dataGridViewColumn = this.Columns.GetPreviousColumn(this.Columns[this.trackColumnEdge], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + DataGridViewColumn dataGridViewColumn = Columns.GetPreviousColumn(Columns[trackColumnEdge], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); SelectColumnRange(hti.col, dataGridViewColumn.Index, true); - this.trackColumnEdge = hti.col; + trackColumnEdge = hti.col; } - else if (this.trackColumnEdge >= 0 && this.Columns.DisplayInOrder(this.trackColumnEdge, this.trackColumn) && this.Columns.DisplayInOrder(this.trackColumnEdge, hti.col) && (this.Columns.DisplayInOrder(hti.col, this.trackColumn) || hti.col == this.trackColumn)) + else if (trackColumnEdge >= 0 && Columns.DisplayInOrder(trackColumnEdge, trackColumn) && Columns.DisplayInOrder(trackColumnEdge, hti.col) && (Columns.DisplayInOrder(hti.col, trackColumn) || hti.col == trackColumn)) { - DataGridViewColumn dataGridViewColumn = this.Columns.GetPreviousColumn(this.Columns[hti.col], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + DataGridViewColumn dataGridViewColumn = Columns.GetPreviousColumn(Columns[hti.col], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); - SelectColumnRange(this.trackColumnEdge, dataGridViewColumn.Index, false); - this.trackColumnEdge = hti.col; + SelectColumnRange(trackColumnEdge, dataGridViewColumn.Index, false); + trackColumnEdge = hti.col; } - else if (this.trackColumnEdge == -1 && this.Columns.DisplayInOrder(hti.col, this.trackColumn)) + else if (trackColumnEdge == -1 && Columns.DisplayInOrder(hti.col, trackColumn)) { - DataGridViewColumn dataGridViewColumn = this.Columns.GetPreviousColumn(this.Columns[this.trackColumn], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + DataGridViewColumn dataGridViewColumn = Columns.GetPreviousColumn(Columns[trackColumn], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); SelectColumnRange(hti.col, dataGridViewColumn.Index, true); - this.trackColumnEdge = hti.col; + trackColumnEdge = hti.col; } - else if (this.trackColumnEdge >= 0 && this.Columns.DisplayInOrder(this.trackColumn, this.trackColumnEdge) && this.Columns.DisplayInOrder(hti.col, this.trackColumn)) + else if (trackColumnEdge >= 0 && Columns.DisplayInOrder(trackColumn, trackColumnEdge) && Columns.DisplayInOrder(hti.col, trackColumn)) { - DataGridViewColumn dataGridViewColumn = this.Columns.GetNextColumn(this.Columns[this.trackColumn], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + DataGridViewColumn dataGridViewColumn = Columns.GetNextColumn(Columns[trackColumn], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); - SelectColumnRange(dataGridViewColumn.Index, this.trackColumnEdge, false); - dataGridViewColumn = this.Columns.GetPreviousColumn(this.Columns[this.trackColumn], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + SelectColumnRange(dataGridViewColumn.Index, trackColumnEdge, false); + dataGridViewColumn = Columns.GetPreviousColumn(Columns[trackColumn], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); SelectColumnRange(hti.col, dataGridViewColumn.Index, true); - this.trackColumnEdge = hti.col; + trackColumnEdge = hti.col; } - else if (this.trackColumnEdge >= 0 && this.Columns.DisplayInOrder(this.trackColumn, hti.col) && this.Columns.DisplayInOrder(this.trackColumnEdge, this.trackColumn)) + else if (trackColumnEdge >= 0 && Columns.DisplayInOrder(trackColumn, hti.col) && Columns.DisplayInOrder(trackColumnEdge, trackColumn)) { - DataGridViewColumn dataGridViewColumn = this.Columns.GetPreviousColumn(this.Columns[this.trackColumn], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + DataGridViewColumn dataGridViewColumn = Columns.GetPreviousColumn(Columns[trackColumn], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); - SelectColumnRange(this.trackColumnEdge, dataGridViewColumn.Index, false); - dataGridViewColumn = this.Columns.GetNextColumn(this.Columns[this.trackColumn], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + SelectColumnRange(trackColumnEdge, dataGridViewColumn.Index, false); + dataGridViewColumn = Columns.GetNextColumn(Columns[trackColumn], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); SelectColumnRange(dataGridViewColumn.Index, hti.col, true); - this.trackColumnEdge = hti.col; + trackColumnEdge = hti.col; } } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; } - if (this.ptCurrentCell.X != -1 && hti.col != this.ptCurrentCell.X) + if (ptCurrentCell.X != -1 && hti.col != ptCurrentCell.X) { - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(hti.col)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(hti.col)) { return; } bool success = SetCurrentCellAddressCore(hti.col, - this.ptCurrentCell.Y, + ptCurrentCell.Y, false /*setAnchorCellAddress*/, false /*validateCurrentCell*/, false /*throughMouseClick*/); @@ -14550,20 +14550,20 @@ private void OnColumnsGlobalAutoSize() { InvalidateData(); - if (this.noAutoSizeCount > 0) + if (noAutoSizeCount > 0) { return; } // Auto-size columms if needed - bool fixedHeight = (((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) == 0; + bool fixedHeight = (((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) == 0; bool columnAutoSized = AutoResizeAllVisibleColumnsInternal(DataGridViewAutoSizeColumnCriteriaInternal.AllRows | DataGridViewAutoSizeColumnCriteriaInternal.DisplayedRows, fixedHeight); // Autosize rows if needed if (!fixedHeight) { if (columnAutoSized) { - AdjustShrinkingRows(this.autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); + AdjustShrinkingRows(autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); } // Second round of columns autosizing AutoResizeAllVisibleColumnsInternal(DataGridViewAutoSizeColumnCriteriaInternal.AllRows | DataGridViewAutoSizeColumnCriteriaInternal.DisplayedRows, true /*fixedHeight*/); @@ -14588,7 +14588,7 @@ protected virtual void OnColumnSortModeChanged(DataGridViewColumnEventArgs e) if (dataGridViewColumn.HasHeaderCell) { if (dataGridViewColumn.SortMode == DataGridViewColumnSortMode.NotSortable || - (dataGridViewColumn.SortMode == DataGridViewColumnSortMode.Programmatic && this.SortedColumn == dataGridViewColumn)) + (dataGridViewColumn.SortMode == DataGridViewColumnSortMode.Programmatic && SortedColumn == dataGridViewColumn)) { dataGridViewColumn.HeaderCell.SortGlyphDirection = SortOrder.None; // This call will trigger OnSortGlyphDirectionChanged which in turn does @@ -14597,22 +14597,22 @@ protected virtual void OnColumnSortModeChanged(DataGridViewColumnEventArgs e) // Potential resizing of the column headers and/or affected column. DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaInternal = (DataGridViewAutoSizeColumnCriteriaInternal)dataGridViewColumn.InheritedAutoSizeMode; DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaFiltered = autoSizeColumnCriteriaInternal & DataGridViewAutoSizeColumnCriteriaInternal.Header; - bool fixedColumnWidth = autoSizeColumnCriteriaFiltered == 0 || !this.ColumnHeadersVisible; - if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) + bool fixedColumnWidth = autoSizeColumnCriteriaFiltered == 0 || !ColumnHeadersVisible; + if (ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) { AutoResizeColumnHeadersHeight(dataGridViewColumn.Index, true /*fixedRowHeadersWidth*/, fixedColumnWidth); } if (!fixedColumnWidth) { - bool fixedHeight = (((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) == 0; + bool fixedHeight = (((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) == 0; AutoResizeColumnInternal(dataGridViewColumn.Index, autoSizeColumnCriteriaInternal, fixedHeight); if (!fixedHeight) { - AdjustShrinkingRows(this.autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); + AdjustShrinkingRows(autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); // Second round of column autosizing AutoResizeColumnInternal(dataGridViewColumn.Index, autoSizeColumnCriteriaInternal, true /*fixedHeight*/); } - if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) + if (ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) { // Second round of column headers autosizing AutoResizeColumnHeadersHeight(dataGridViewColumn.Index, true /*fixedRowHeadersWidth*/, true /*fixedColumnWidth*/); @@ -14620,8 +14620,8 @@ protected virtual void OnColumnSortModeChanged(DataGridViewColumnEventArgs e) } } - DataGridViewColumnEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNSORTMODECHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNSORTMODECHANGED] as DataGridViewColumnEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14639,7 +14639,7 @@ protected virtual void OnColumnStateChanged(DataGridViewColumnStateChangedEventA // case DataGridViewElementStates.Resizable: case DataGridViewElementStates.Selected: - if (dataGridViewColumn.Visible && this.inBulkPaintCount == 0) + if (dataGridViewColumn.Visible && inBulkPaintCount == 0) { InvalidateColumnInternal(dataGridViewColumn.Index); } @@ -14651,28 +14651,28 @@ protected virtual void OnColumnStateChanged(DataGridViewColumnStateChangedEventA if (dataGridViewColumn.Frozen) { // visible column became frozen - if (this.horizontalOffset >= dataGridViewColumn.Thickness) + if (horizontalOffset >= dataGridViewColumn.Thickness) { - Debug.Assert(this.Columns.DisplayInOrder(dataGridViewColumn.Index, this.displayedBandsInfo.FirstDisplayedScrollingCol)); - this.horizontalOffset -= dataGridViewColumn.Thickness; + Debug.Assert(Columns.DisplayInOrder(dataGridViewColumn.Index, displayedBandsInfo.FirstDisplayedScrollingCol)); + horizontalOffset -= dataGridViewColumn.Thickness; } else { - this.horizontalOffset = this.negOffset = 0; + horizontalOffset = negOffset = 0; } } else { // column was unfrozen - make it the first visible scrolling column if there is room - this.horizontalOffset = this.negOffset = 0; + horizontalOffset = negOffset = 0; } - if (this.horizScrollBar.Enabled) + if (horizScrollBar.Enabled) { - this.horizScrollBar.Value = this.horizontalOffset; + horizScrollBar.Value = horizontalOffset; } // UsedFillWeight values need to be updated - this.dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = true; PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, true /*repositionEditingControl*/); Invalidate(); @@ -14687,13 +14687,13 @@ protected virtual void OnColumnStateChanged(DataGridViewColumnStateChangedEventA } // UsedFillWeight values need to be updated - this.dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_usedFillWeightsDirty] = true; PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, true /*repositionEditingControl*/); - bool autoSizeRows = (((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0 || - ((((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) != 0 && - this.RowHeadersVisible); + bool autoSizeRows = (((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0 || + ((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) != 0 && + RowHeadersVisible); bool autoSizeColumn = false; DataGridViewAutoSizeColumnMode autoSizeColumnMode = dataGridViewColumn.InheritedAutoSizeMode; Debug.Assert(autoSizeColumnMode != DataGridViewAutoSizeColumnMode.NotSet); @@ -14724,7 +14724,7 @@ protected virtual void OnColumnStateChanged(DataGridViewColumnStateChangedEventA } else { - AdjustShrinkingRows(this.autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); + AdjustShrinkingRows(autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); } if (autoSizeColumn) { @@ -14739,24 +14739,24 @@ protected virtual void OnColumnStateChanged(DataGridViewColumnStateChangedEventA break; } - DataGridViewColumnStateChangedEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNSTATECHANGED] as DataGridViewColumnStateChangedEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewColumnStateChangedEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNSTATECHANGED] as DataGridViewColumnStateChangedEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } if (e.StateChanged == DataGridViewElementStates.ReadOnly && - dataGridViewColumn.Index == this.ptCurrentCell.X && - !this.dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange]) + dataGridViewColumn.Index == ptCurrentCell.X && + !dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange]) { VerifyImeRestrictedModeChanged(); if (!dataGridViewColumn.ReadOnly && - ColumnEditable(this.ptCurrentCell.X) && - (this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.ReadOnly) == 0 && - !this.IsCurrentCellInEditMode && - (this.EditMode == DataGridViewEditMode.EditOnEnter || - (this.EditMode != DataGridViewEditMode.EditProgrammatically && this.CurrentCellInternal.EditType == null))) + ColumnEditable(ptCurrentCell.X) && + (Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.ReadOnly) == 0 && + !IsCurrentCellInEditMode && + (EditMode == DataGridViewEditMode.EditOnEnter || + (EditMode != DataGridViewEditMode.EditProgrammatically && CurrentCellInternal.EditType == null))) { // Current column becomes read/write. Enter editing mode. BeginEditInternal(true /*selectAll*/); @@ -14775,8 +14775,8 @@ protected virtual void OnColumnToolTipTextChanged(DataGridViewColumnEventArgs e) { throw new ArgumentException(string.Format(SR.DataGridView_ColumnDoesNotBelongToDataGridView)); } - DataGridViewColumnEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNTOOLTIPTEXTCHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNTOOLTIPTEXTCHANGED] as DataGridViewColumnEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14788,19 +14788,19 @@ protected virtual void OnColumnWidthChanged(DataGridViewColumnEventArgs e) { throw new ArgumentException(string.Format(SR.DataGridView_ColumnDoesNotBelongToDataGridView)); } - this.Columns.InvalidateCachedColumnsWidths(); + Columns.InvalidateCachedColumnsWidths(); // don't do any layout logic if the handle was not created already - if (e.Column.Visible && this.IsHandleCreated) + if (e.Column.Visible && IsHandleCreated) { PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, false /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); - Rectangle rightArea = this.layout.Data; - if (this.layout.ColumnHeadersVisible) + Rectangle rightArea = layout.Data; + if (layout.ColumnHeadersVisible) { - rightArea = Rectangle.Union(rightArea, this.layout.ColumnHeaders); + rightArea = Rectangle.Union(rightArea, layout.ColumnHeaders); } - else if (this.SingleHorizontalBorderAdded) + else if (SingleHorizontalBorderAdded) { rightArea.Y--; rightArea.Height++; @@ -14808,7 +14808,7 @@ protected virtual void OnColumnWidthChanged(DataGridViewColumnEventArgs e) if (rightArea.Width > 0 && rightArea.Height > 0) { int leftEdge = GetColumnXFromIndex(e.Column.Index); - if (this.RightToLeftInternal) + if (RightToLeftInternal) { rightArea.Width -= rightArea.Right - leftEdge; } @@ -14823,26 +14823,26 @@ protected virtual void OnColumnWidthChanged(DataGridViewColumnEventArgs e) } } - if (this.editingControl != null) + if (editingControl != null) { - PositionEditingControl(this.ptCurrentCell.X != e.Column.Index, true, false); + PositionEditingControl(ptCurrentCell.X != e.Column.Index, true, false); } UpdateMouseEnteredCell(null /*HitTestInfo*/, null /*MouseEventArgs*/); - if (this.AutoSize) + if (AutoSize) { - LayoutTransaction.DoLayout(this.ParentInternal, this, PropertyNames.Columns); + LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.Columns); } } - DataGridViewColumnEventHandler eh = this.Events[EVENT_DATAGRIDVIEWCOLUMNWIDTHCHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNWIDTHCHANGED] as DataGridViewColumnEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } - if (!this.InAdjustFillingColumns) + if (!InAdjustFillingColumns) { // Autosize rows and column headers if needed OnColumnGlobalAutoSize(e.Column.Index); @@ -14851,11 +14851,11 @@ protected virtual void OnColumnWidthChanged(DataGridViewColumnEventArgs e) internal void OnCommonCellContentClick(int columnIndex, int rowIndex, bool doubleClick) { - if (this.ptMouseDownCell.X == -2 || - (this.dataGridViewState2[DATAGRIDVIEWSTATE2_cellMouseDownInContentBounds] && - this.ptMouseDownCell.X == columnIndex && this.ptMouseDownCell.Y == rowIndex && - (this.ptMouseDownCell.X == -1 || this.ptMouseDownCell.Y == -1 || - (columnIndex == this.ptCurrentCell.X && rowIndex == this.ptCurrentCell.Y)))) + if (ptMouseDownCell.X == -2 || + (dataGridViewState2[DATAGRIDVIEWSTATE2_cellMouseDownInContentBounds] && + ptMouseDownCell.X == columnIndex && ptMouseDownCell.Y == rowIndex && + (ptMouseDownCell.X == -1 || ptMouseDownCell.Y == -1 || + (columnIndex == ptCurrentCell.X && rowIndex == ptCurrentCell.Y)))) { DataGridViewCellEventArgs dgvce = new DataGridViewCellEventArgs(columnIndex, rowIndex); if (doubleClick) @@ -14872,8 +14872,8 @@ internal void OnCommonCellContentClick(int columnIndex, int rowIndex, bool doubl protected virtual void OnCurrentCellChanged(EventArgs e) { VerifyImeRestrictedModeChanged(); - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWCURRENTCELLCHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWCURRENTCELLCHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14881,24 +14881,24 @@ protected virtual void OnCurrentCellChanged(EventArgs e) protected virtual void OnCurrentCellDirtyStateChanged(EventArgs e) { - if (this.RowHeadersVisible && this.ShowEditingIcon) + if (RowHeadersVisible && ShowEditingIcon) { // Force the pencil to appear in the row header - Debug.Assert(this.ptCurrentCell.Y >= 0); - InvalidateCellPrivate(-1, this.ptCurrentCell.Y); + Debug.Assert(ptCurrentCell.Y >= 0); + InvalidateCellPrivate(-1, ptCurrentCell.Y); } - if (this.IsCurrentCellDirty && this.newRowIndex == this.ptCurrentCell.Y) + if (IsCurrentCellDirty && newRowIndex == ptCurrentCell.Y) { - Debug.Assert(this.newRowIndex != -1); - Debug.Assert(this.AllowUserToAddRowsInternal); + Debug.Assert(newRowIndex != -1); + Debug.Assert(AllowUserToAddRowsInternal); // First time the 'new' row gets edited. // It becomes a regular row and a new 'new' row is appened. - this.newRowIndex = -1; + newRowIndex = -1; AddNewRow(true /*createdByEditing*/); } - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWCURRENTCELLDIRTYSTATECHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWCURRENTCELLDIRTYSTATECHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14907,9 +14907,9 @@ protected virtual void OnCurrentCellDirtyStateChanged(EventArgs e) protected override void OnCursorChanged(EventArgs e) { base.OnCursorChanged(e); - if (!this.dataGridViewState2[DATAGRIDVIEWSTATE2_ignoreCursorChange]) + if (!dataGridViewState2[DATAGRIDVIEWSTATE2_ignoreCursorChange]) { - this.oldCursor = this.Cursor; + oldCursor = Cursor; } } @@ -14920,8 +14920,8 @@ internal void OnDataBindingComplete(ListChangedType listChangedType) protected virtual void OnDataBindingComplete(DataGridViewBindingCompleteEventArgs e) { - DataGridViewBindingCompleteEventHandler eh = this.Events[EVENT_DATAGRIDVIEWDATABINDINGCOMPLETE] as DataGridViewBindingCompleteEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewBindingCompleteEventHandler eh = Events[EVENT_DATAGRIDVIEWDATABINDINGCOMPLETE] as DataGridViewBindingCompleteEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14932,8 +14932,8 @@ protected virtual void OnDataBindingComplete(DataGridViewBindingCompleteEventArg ] protected virtual void OnDataError(bool displayErrorDialogIfNoHandler, DataGridViewDataErrorEventArgs e) { - DataGridViewDataErrorEventHandler eh = this.Events[EVENT_DATAGRIDVIEWDATAERROR] as DataGridViewDataErrorEventHandler; - if (!this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewDataErrorEventHandler eh = Events[EVENT_DATAGRIDVIEWDATAERROR] as DataGridViewDataErrorEventHandler; + if (!dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { if (eh == null) { @@ -14948,7 +14948,7 @@ protected virtual void OnDataError(bool displayErrorDialogIfNoHandler, DataGridV { errorText = string.Format(SR.DataGridView_ErrorMessageText_WithException, e.Exception); } - if (this.RightToLeftInternal) + if (RightToLeftInternal) { MessageBox.Show(errorText, string.Format(SR.DataGridView_ErrorMessageCaption), MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign | MessageBoxOptions.RtlReading); } @@ -14969,7 +14969,7 @@ protected virtual void OnDataError(bool displayErrorDialogIfNoHandler, DataGridV internal void OnDataErrorInternal(DataGridViewDataErrorEventArgs e) { - OnDataError(!this.DesignMode /*displayErrorDialogIfNoHandler*/, e); + OnDataError(!DesignMode /*displayErrorDialogIfNoHandler*/, e); } internal void OnDataGridViewElementStateChanged(DataGridViewElement element, int index, DataGridViewElementStates elementState) @@ -14986,11 +14986,11 @@ internal void OnDataGridViewElementStateChanged(DataGridViewElement element, int DataGridViewRow dataGridViewRow = element as DataGridViewRow; if (dataGridViewRow != null) { - DataGridViewRowStateChangedEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWSTATECHANGED] as DataGridViewRowStateChangedEventHandler; + DataGridViewRowStateChangedEventHandler eh = Events[EVENT_DATAGRIDVIEWROWSTATECHANGED] as DataGridViewRowStateChangedEventHandler; if (eh != null && dataGridViewRow.DataGridView != null && dataGridViewRow.Index == -1) { - dataGridViewRow = this.Rows[index]; + dataGridViewRow = Rows[index]; } DataGridViewRowStateChangedEventArgs dgvrsce = new DataGridViewRowStateChangedEventArgs(dataGridViewRow, elementState); @@ -15011,9 +15011,9 @@ internal void OnDataGridViewElementStateChanged(DataGridViewElement element, int if ((elementState & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) { - if (this.noSelectionChangeCount > 0) + if (noSelectionChangeCount > 0) { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_raiseSelectionChanged] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_raiseSelectionChanged] = true; } else { @@ -15036,7 +15036,7 @@ internal void OnDataGridViewElementStateChanging(DataGridViewElement element, in { if (!dataGridViewColumn.Visible && dataGridViewColumn.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.ColumnHeader && - !this.ColumnHeadersVisible) + !ColumnHeadersVisible) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotMakeAutoSizedColumnVisible)); } @@ -15049,7 +15049,7 @@ internal void OnDataGridViewElementStateChanging(DataGridViewElement element, in // Removing the Fill auto size mode when frozen column becomes visible (instead of throwing an exception) dataGridViewColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.None; } - else if (dataGridViewColumn.Visible && this.ptCurrentCell.X == dataGridViewColumn.Index) + else if (dataGridViewColumn.Visible && ptCurrentCell.X == dataGridViewColumn.Index) { // Column of the current cell is made invisible. Trying to reset the current cell. May throw an exception. ResetCurrentCell(); @@ -15068,12 +15068,12 @@ internal void OnDataGridViewElementStateChanging(DataGridViewElement element, in break; case DataGridViewElementStates.ReadOnly: - if (this.ptCurrentCell.X == dataGridViewColumn.Index && - this.IsCurrentCellInEditMode && + if (ptCurrentCell.X == dataGridViewColumn.Index && + IsCurrentCellInEditMode && !dataGridViewColumn.ReadOnly && - !this.dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange]) + !dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange]) { - Debug.Assert(!this.ReadOnly); + Debug.Assert(!ReadOnly); // Column becomes read-only. Exit editing mode. if (!EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit, DataGridViewValidateCellInternal.Always /*validateCell*/, @@ -15107,15 +15107,15 @@ internal void OnDataGridViewElementStateChanging(DataGridViewElement element, in { case DataGridViewElementStates.Frozen: case DataGridViewElementStates.Visible: - if (elementState == DataGridViewElementStates.Visible && this.ptCurrentCell.Y == rowIndex) + if (elementState == DataGridViewElementStates.Visible && ptCurrentCell.Y == rowIndex) { - Debug.Assert((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Visible) != 0); + Debug.Assert((Rows.GetRowState(rowIndex) & DataGridViewElementStates.Visible) != 0); // Row of the current cell is made invisible. - if (this.DataSource != null) + if (DataSource != null) { - Debug.Assert(this.dataConnection != null); - Debug.Assert(this.dataConnection.CurrencyManager != null); - Debug.Assert(this.dataConnection.CurrencyManager.Position == this.ptCurrentCell.Y); + Debug.Assert(dataConnection != null); + Debug.Assert(dataConnection.CurrencyManager != null); + Debug.Assert(dataConnection.CurrencyManager.Position == ptCurrentCell.Y); // the row associated with the currency manager's position cannot be made invisble. throw new InvalidOperationException(string.Format(SR.DataGridView_CurrencyManagerRowCannotBeInvisible)); } @@ -15127,11 +15127,11 @@ internal void OnDataGridViewElementStateChanging(DataGridViewElement element, in break; case DataGridViewElementStates.ReadOnly: - if (this.ptCurrentCell.Y == rowIndex && - (this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.ReadOnly) == 0 && - !this.ReadOnly && - this.IsCurrentCellInEditMode && - !this.dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange]) + if (ptCurrentCell.Y == rowIndex && + (Rows.GetRowState(rowIndex) & DataGridViewElementStates.ReadOnly) == 0 && + !ReadOnly && + IsCurrentCellInEditMode && + !dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange]) { // Row becomes read-only. Exit editing mode. if (!EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit, @@ -15164,15 +15164,15 @@ internal void OnDataGridViewElementStateChanging(DataGridViewElement element, in switch (elementState) { case DataGridViewElementStates.ReadOnly: - if (this.ptCurrentCell.X == dataGridViewCell.ColumnIndex && - this.ptCurrentCell.Y == dataGridViewCell.RowIndex && - this.IsCurrentCellInEditMode && + if (ptCurrentCell.X == dataGridViewCell.ColumnIndex && + ptCurrentCell.Y == dataGridViewCell.RowIndex && + IsCurrentCellInEditMode && !dataGridViewCell.ReadOnly && - !this.dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange]) + !dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange]) { - Debug.Assert(!this.Columns[dataGridViewCell.ColumnIndex].ReadOnly); - Debug.Assert(!this.Rows[dataGridViewCell.RowIndex].ReadOnly); - Debug.Assert(!this.ReadOnly); + Debug.Assert(!Columns[dataGridViewCell.ColumnIndex].ReadOnly); + Debug.Assert(!Rows[dataGridViewCell.RowIndex].ReadOnly); + Debug.Assert(!ReadOnly); // Current cell becomes read-only. Exit editing mode. if (!EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit, DataGridViewValidateCellInternal.Always /*validateCell*/, @@ -15207,13 +15207,13 @@ protected virtual void OnDataMemberChanged(EventArgs e) { RefreshColumnsAndRows(); - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWDATAMEMBERCHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWDATAMEMBERCHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } - if (this.dataConnection != null && this.dataConnection.CurrencyManager != null) + if (dataConnection != null && dataConnection.CurrencyManager != null) { OnDataBindingComplete(ListChangedType.Reset); } @@ -15224,13 +15224,13 @@ protected virtual void OnDataSourceChanged(EventArgs e) RefreshColumnsAndRows(); InvalidateRowHeights(); - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWDATASOURCECHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWDATASOURCECHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } - if (this.dataConnection != null && this.dataConnection.CurrencyManager != null) + if (dataConnection != null && dataConnection.CurrencyManager != null) { OnDataBindingComplete(ListChangedType.Reset); } @@ -15246,14 +15246,14 @@ protected virtual void OnDefaultCellStyleChanged(EventArgs e) else { OnGlobalAutoSize(); - if (this.editingControl != null) + if (editingControl != null) { PositionEditingControl(true /*setLocation*/, true /*setSize*/, false /*setFocus*/); } } - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWDEFAULTCELLSTYLECHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWDEFAULTCELLSTYLECHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -15261,8 +15261,8 @@ protected virtual void OnDefaultCellStyleChanged(EventArgs e) protected virtual void OnDefaultValuesNeeded(DataGridViewRowEventArgs e) { - DataGridViewRowEventHandler eh = this.Events[EVENT_DATAGRIDVIEWDEFAULTVALUESNEEDED] as DataGridViewRowEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWDEFAULTVALUESNEEDED] as DataGridViewRowEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -15272,7 +15272,7 @@ protected override void OnDoubleClick(EventArgs e) { base.OnDoubleClick(e); - if (!this.dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls] && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + if (!dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls] && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { MouseEventArgs me = e as MouseEventArgs; if (me != null) @@ -15291,8 +15291,8 @@ protected override void OnDoubleClick(EventArgs e) protected virtual void OnEditingControlShowing(DataGridViewEditingControlShowingEventArgs e) { - DataGridViewEditingControlShowingEventHandler eh = this.Events[EVENT_DATAGRIDVIEWEDITINGCONTROLSHOWING] as DataGridViewEditingControlShowingEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewEditingControlShowingEventHandler eh = Events[EVENT_DATAGRIDVIEWEDITINGCONTROLSHOWING] as DataGridViewEditingControlShowingEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -15300,17 +15300,17 @@ protected virtual void OnEditingControlShowing(DataGridViewEditingControlShowing protected virtual void OnEditModeChanged(EventArgs e) { - if (this.Focused && - this.EditMode == DataGridViewEditMode.EditOnEnter && - this.ptCurrentCell.X > -1 && - !this.IsCurrentCellInEditMode) + if (Focused && + EditMode == DataGridViewEditMode.EditOnEnter && + ptCurrentCell.X > -1 && + !IsCurrentCellInEditMode) { // New edit mode is EditOnEnter and there is an editable current cell, try to go to edit mode. BeginEditInternal(true /*selectAll*/); } - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWEDITMODECHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWEDITMODECHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -15324,26 +15324,26 @@ protected override void OnEnabledChanged(EventArgs e) return; } - if (this.IsHandleCreated && this.Enabled) + if (IsHandleCreated && Enabled) { - if (this.vertScrollBar != null && this.vertScrollBar.Visible) + if (vertScrollBar != null && vertScrollBar.Visible) { - int totalVisibleHeight = this.Rows.GetRowsHeight(DataGridViewElementStates.Visible); - int totalVisibleFrozenHeight = this.Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); - this.vertScrollBar.Maximum = totalVisibleHeight - totalVisibleFrozenHeight; + int totalVisibleHeight = Rows.GetRowsHeight(DataGridViewElementStates.Visible); + int totalVisibleFrozenHeight = Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + vertScrollBar.Maximum = totalVisibleHeight - totalVisibleFrozenHeight; - this.vertScrollBar.Enabled = true; + vertScrollBar.Enabled = true; } - if (this.horizScrollBar != null && this.horizScrollBar.Visible) + if (horizScrollBar != null && horizScrollBar.Visible) { - this.horizScrollBar.Enabled = true; + horizScrollBar.Enabled = true; } } } protected override void OnEnter(EventArgs e) { - if (this.editingControl != null && this.editingControl.ContainsFocus) + if (editingControl != null && editingControl.ContainsFocus) { return; } @@ -15352,66 +15352,66 @@ protected override void OnEnter(EventArgs e) // There are cases when a control is on the designer and it still receives the OnEnter event. // Guard against this. - if (this.DesignMode) + if (DesignMode) { return; } - this.dataGridViewState1[DATAGRIDVIEWSTATE1_leavingWithTabKey] = false; + dataGridViewState1[DATAGRIDVIEWSTATE1_leavingWithTabKey] = false; - if (this.ptCurrentCell.X > -1) + if (ptCurrentCell.X > -1) { DataGridViewCell dataGridViewCell = null; // We're re-entering a row we already entered earlier. The first time we entered the row, // the DataGridView didn't have focus. This time it does. We don't want to recreate the new row a second time. - OnRowEnter(ref dataGridViewCell, this.ptCurrentCell.X, this.ptCurrentCell.Y, false /*canCreateNewRow*/, false /*validationFailureOccurred*/); - if (this.ptCurrentCell.X == -1) + OnRowEnter(ref dataGridViewCell, ptCurrentCell.X, ptCurrentCell.Y, false /*canCreateNewRow*/, false /*validationFailureOccurred*/); + if (ptCurrentCell.X == -1) { return; } - OnCellEnter(ref dataGridViewCell, this.ptCurrentCell.X, this.ptCurrentCell.Y); + OnCellEnter(ref dataGridViewCell, ptCurrentCell.X, ptCurrentCell.Y); // Force repainting of the current collumn's header cell to highlight it - if (this.SelectionMode == DataGridViewSelectionMode.FullRowSelect) + if (SelectionMode == DataGridViewSelectionMode.FullRowSelect) { - InvalidateCellPrivate(this.ptCurrentCell.X, -1); + InvalidateCellPrivate(ptCurrentCell.X, -1); } } - else if (!this.dataGridViewOper[DATAGRIDVIEWOPER_inMouseDown]) + else if (!dataGridViewOper[DATAGRIDVIEWOPER_inMouseDown]) { // Focus is given to the DataGridView control via a the TAB key. MakeFirstDisplayedCellCurrentCell(true /*includeNewRow*/); } - if (this.ptCurrentCell.X > -1 && - !this.IsCurrentCellInEditMode) + if (ptCurrentCell.X > -1 && + !IsCurrentCellInEditMode) { - if (this.EditMode == DataGridViewEditMode.EditOnEnter || - (this.EditMode != DataGridViewEditMode.EditProgrammatically && this.CurrentCellInternal.EditType == null)) + if (EditMode == DataGridViewEditMode.EditOnEnter || + (EditMode != DataGridViewEditMode.EditProgrammatically && CurrentCellInternal.EditType == null)) { BeginEditInternal(true /*selectAll*/); - if (this.ptCurrentCell.X > -1 && this.CurrentCellInternal.EditType == null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inMouseDown]) + if (ptCurrentCell.X > -1 && CurrentCellInternal.EditType == null && !dataGridViewOper[DATAGRIDVIEWOPER_inMouseDown]) { // The current cell does not have an edit type so the data grid view did not put an edit control on top. // We should invalidate the current cell so that the dataGridView repaints the focus around the current cell. // But do that only if the dataGridView did not get the focus via mouse. - InvalidateCellPrivate(this.ptCurrentCell.X /*columnIndex*/, this.ptCurrentCell.Y /*rowIndex*/); + InvalidateCellPrivate(ptCurrentCell.X /*columnIndex*/, ptCurrentCell.Y /*rowIndex*/); } } - else if (!this.dataGridViewOper[DATAGRIDVIEWOPER_inMouseDown]) + else if (!dataGridViewOper[DATAGRIDVIEWOPER_inMouseDown]) { // When the focus is given to the DataGridView control via mouse // the dataGridView changes selection so it invalidates the current cell anyway // // In any other case Invalidate the current cell so the dataGridView repaints the focus around the current cell - InvalidateCellPrivate(this.ptCurrentCell.X /*columnIndex*/, this.ptCurrentCell.Y /*rowIndex*/); + InvalidateCellPrivate(ptCurrentCell.X /*columnIndex*/, ptCurrentCell.Y /*rowIndex*/); } } // Draw focus rectangle around the grid - if (this.IsGridFocusRectangleEnabled()) + if (IsGridFocusRectangleEnabled()) { - this.InvalidateRectangleEdges(this.GetGridFocusRectangle()); + InvalidateRectangleEdges(GetGridFocusRectangle()); } } @@ -15425,31 +15425,31 @@ protected override void OnFontChanged(EventArgs e) } // Change may be due to an ambient font change. - if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientColumnHeadersFont] && - this.ColumnHeadersDefaultCellStyle.Font != base.Font) + if (dataGridViewState1[DATAGRIDVIEWSTATE1_ambientColumnHeadersFont] && + ColumnHeadersDefaultCellStyle.Font != base.Font) { - this.ColumnHeadersDefaultCellStyle.Font = base.Font; - this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientColumnHeadersFont] = true; - this.CellStyleChangedEventArgs.ChangeAffectsPreferredSize = true; - OnColumnHeadersDefaultCellStyleChanged(this.CellStyleChangedEventArgs); + ColumnHeadersDefaultCellStyle.Font = base.Font; + dataGridViewState1[DATAGRIDVIEWSTATE1_ambientColumnHeadersFont] = true; + CellStyleChangedEventArgs.ChangeAffectsPreferredSize = true; + OnColumnHeadersDefaultCellStyleChanged(CellStyleChangedEventArgs); } - if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientRowHeadersFont] && - this.RowHeadersDefaultCellStyle.Font != base.Font) + if (dataGridViewState1[DATAGRIDVIEWSTATE1_ambientRowHeadersFont] && + RowHeadersDefaultCellStyle.Font != base.Font) { - this.RowHeadersDefaultCellStyle.Font = base.Font; - this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientRowHeadersFont] = true; - this.CellStyleChangedEventArgs.ChangeAffectsPreferredSize = true; - OnRowHeadersDefaultCellStyleChanged(this.CellStyleChangedEventArgs); + RowHeadersDefaultCellStyle.Font = base.Font; + dataGridViewState1[DATAGRIDVIEWSTATE1_ambientRowHeadersFont] = true; + CellStyleChangedEventArgs.ChangeAffectsPreferredSize = true; + OnRowHeadersDefaultCellStyleChanged(CellStyleChangedEventArgs); } - if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientFont] && - this.DefaultCellStyle.Font != base.Font) + if (dataGridViewState1[DATAGRIDVIEWSTATE1_ambientFont] && + DefaultCellStyle.Font != base.Font) { - this.DefaultCellStyle.Font = base.Font; - this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientFont] = true; - this.CellStyleChangedEventArgs.ChangeAffectsPreferredSize = true; - OnDefaultCellStyleChanged(this.CellStyleChangedEventArgs); + DefaultCellStyle.Font = base.Font; + dataGridViewState1[DATAGRIDVIEWSTATE1_ambientFont] = true; + CellStyleChangedEventArgs.ChangeAffectsPreferredSize = true; + OnDefaultCellStyleChanged(CellStyleChangedEventArgs); } } @@ -15462,12 +15462,12 @@ protected override void OnForeColorChanged(EventArgs e) } // Change may be due to an ambient forecolor change. - if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientForeColor] && this.DefaultCellStyle.ForeColor != base.ForeColor) + if (dataGridViewState1[DATAGRIDVIEWSTATE1_ambientForeColor] && DefaultCellStyle.ForeColor != base.ForeColor) { - this.DefaultCellStyle.ForeColor = base.ForeColor; - this.dataGridViewState1[DATAGRIDVIEWSTATE1_ambientForeColor] = true; - this.CellStyleChangedEventArgs.ChangeAffectsPreferredSize = false; - OnDefaultCellStyleChanged(this.CellStyleChangedEventArgs); + DefaultCellStyle.ForeColor = base.ForeColor; + dataGridViewState1[DATAGRIDVIEWSTATE1_ambientForeColor] = true; + CellStyleChangedEventArgs.ChangeAffectsPreferredSize = false; + OnDefaultCellStyleChanged(CellStyleChangedEventArgs); } } @@ -15475,65 +15475,65 @@ private void OnGlobalAutoSize() { Invalidate(); - if (this.noAutoSizeCount > 0) + if (noAutoSizeCount > 0) { return; } - bool autoSizeRowHeaders = this.rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.EnableResizing && - this.rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.DisableResizing; + bool autoSizeRowHeaders = rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.EnableResizing && + rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.DisableResizing; if (autoSizeRowHeaders) { - AutoResizeRowHeadersWidth(this.rowHeadersWidthSizeMode, - this.ColumnHeadersHeightSizeMode != DataGridViewColumnHeadersHeightSizeMode.AutoSize /*fixedColumnHeadersHeight*/, - this.autoSizeRowsMode == DataGridViewAutoSizeRowsMode.None /*fixedRowsHeight*/); + AutoResizeRowHeadersWidth(rowHeadersWidthSizeMode, + ColumnHeadersHeightSizeMode != DataGridViewColumnHeadersHeightSizeMode.AutoSize /*fixedColumnHeadersHeight*/, + autoSizeRowsMode == DataGridViewAutoSizeRowsMode.None /*fixedRowsHeight*/); } - if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) + if (ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) { AutoResizeColumnHeadersHeight(true /*fixedRowHeadersWidth*/, false /*fixedColumnsWidth*/); } - if (this.autoSizeRowsMode != DataGridViewAutoSizeRowsMode.None) + if (autoSizeRowsMode != DataGridViewAutoSizeRowsMode.None) { - AdjustShrinkingRows(this.autoSizeRowsMode, false /*fixedWidth*/, true /*internalAutosizing*/); + AdjustShrinkingRows(autoSizeRowsMode, false /*fixedWidth*/, true /*internalAutosizing*/); } AutoResizeAllVisibleColumnsInternal(DataGridViewAutoSizeColumnCriteriaInternal.Header | DataGridViewAutoSizeColumnCriteriaInternal.AllRows | DataGridViewAutoSizeColumnCriteriaInternal.DisplayedRows, true /*fixedHeight*/); if (autoSizeRowHeaders && - (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize || this.autoSizeRowsMode != DataGridViewAutoSizeRowsMode.None)) + (ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize || autoSizeRowsMode != DataGridViewAutoSizeRowsMode.None)) { // Second round of row headers autosizing - AutoResizeRowHeadersWidth(this.rowHeadersWidthSizeMode, true /*fixedColumnHeadersHeight*/, true /*fixedRowsHeight*/); + AutoResizeRowHeadersWidth(rowHeadersWidthSizeMode, true /*fixedColumnHeadersHeight*/, true /*fixedRowsHeight*/); } - if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) + if (ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) { // Second round of column headers autosizing AutoResizeColumnHeadersHeight(true /*fixedRowHeadersWidth*/, true /*fixedColumnsWidth*/); } - if (this.autoSizeRowsMode != DataGridViewAutoSizeRowsMode.None) + if (autoSizeRowsMode != DataGridViewAutoSizeRowsMode.None) { // Second round of rows autosizing - AdjustShrinkingRows(this.autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); + AdjustShrinkingRows(autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); } } protected override void OnGotFocus(EventArgs e) { base.OnGotFocus(e); - if (this.ptCurrentCell.X != -1) + if (ptCurrentCell.X != -1) { - InvalidateCell(this.ptCurrentCell.X, this.ptCurrentCell.Y); + InvalidateCell(ptCurrentCell.X, ptCurrentCell.Y); } // Inform Accessibility that our current cell contains the focus. - if (!this.dataGridViewOper[DATAGRIDVIEWOPER_inCurrentCellChange] && - (!this.dataGridViewOper[DATAGRIDVIEWOPER_inEndEdit] || this.EditMode != DataGridViewEditMode.EditOnEnter) && - (!this.dataGridViewOper[DATAGRIDVIEWOPER_inMouseDown] || this.EditMode != DataGridViewEditMode.EditOnEnter) && - this.ptCurrentCell.X > -1) + if (!dataGridViewOper[DATAGRIDVIEWOPER_inCurrentCellChange] && + (!dataGridViewOper[DATAGRIDVIEWOPER_inEndEdit] || EditMode != DataGridViewEditMode.EditOnEnter) && + (!dataGridViewOper[DATAGRIDVIEWOPER_inMouseDown] || EditMode != DataGridViewEditMode.EditOnEnter) && + ptCurrentCell.X > -1) { // The name is misleading ( the current cell did not change ). // However, AccessibilityNotifyCurrentCellChanged is now a public method so we can't change its name // to better reflect its purpose. - AccessibilityNotifyCurrentCellChanged(this.ptCurrentCell); + AccessibilityNotifyCurrentCellChanged(ptCurrentCell); } } @@ -15541,8 +15541,8 @@ protected virtual void OnGridColorChanged(EventArgs e) { InvalidateInside(); - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWGRIDCOLORCHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWGRIDCOLORCHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -15552,38 +15552,38 @@ protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); - if (this.layout.dirty) + if (layout.dirty) { PerformLayoutPrivate(false /*useRowShortcut*/, true /*computeVisibleRows*/, false /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); } - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { MakeFirstDisplayedCellCurrentCell(false /*includeNewRow*/); } else { - ScrollIntoView(this.ptCurrentCell.X, this.ptCurrentCell.Y, false /*forCurrentCellChange*/); + ScrollIntoView(ptCurrentCell.X, ptCurrentCell.Y, false /*forCurrentCellChange*/); } // do the AutoSize work that was skipped during initialization - if (this.dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle]) + if (dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle]) { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle] = false; + dataGridViewState2[DATAGRIDVIEWSTATE2_autoSizedWithoutHandle] = false; OnGlobalAutoSize(); } - SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(this.OnUserPreferenceChanged); + SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(OnUserPreferenceChanged); } protected override void OnHandleDestroyed(EventArgs e) { - SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(this.OnUserPreferenceChanged); + SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(OnUserPreferenceChanged); base.OnHandleDestroyed(e); } internal void OnInsertedColumn_PreNotification(DataGridViewColumn dataGridViewColumn) { // Fix the OldFirstDisplayedScrollingCol - this.displayedBandsInfo.CorrectColumnIndexAfterInsertion(dataGridViewColumn.Index, 1); + displayedBandsInfo.CorrectColumnIndexAfterInsertion(dataGridViewColumn.Index, 1); // Fix the Index of all following columns CorrectColumnIndexesAfterInsertion(dataGridViewColumn, 1); @@ -15597,14 +15597,14 @@ internal void OnInsertedColumn_PostNotification(Point newCurrentCell) // Update current cell if needed if (newCurrentCell.X != -1) { - Debug.Assert(this.ptCurrentCell.X == -1); + Debug.Assert(ptCurrentCell.X == -1); bool success = SetAndSelectCurrentCellAddress(newCurrentCell.X, newCurrentCell.Y, true, false, false, false /*clearSelection*/, - this.Columns.GetColumnCount(DataGridViewElementStates.Visible) == 1 /*forceCurrentCellSelection*/); + Columns.GetColumnCount(DataGridViewElementStates.Visible) == 1 /*forceCurrentCellSelection*/); Debug.Assert(success); } } @@ -15615,7 +15615,7 @@ internal void OnInsertedRow_PreNotification(int rowIndex, int insertionCount) Debug.Assert(insertionCount > 0); // Fix the OldFirstDisplayedScrollingRow - this.displayedBandsInfo.CorrectRowIndexAfterInsertion(rowIndex, insertionCount); + displayedBandsInfo.CorrectRowIndexAfterInsertion(rowIndex, insertionCount); // Fix the Index of all following rows CorrectRowIndexesAfterInsertion(rowIndex, insertionCount); @@ -15634,14 +15634,14 @@ internal void OnInsertedRow_PostNotification(int rowIndex, Point newCurrentCell, // Update current cell if needed if (lastInsertion && newCurrentCell.Y != -1) { - Debug.Assert(this.ptCurrentCell.X == -1); + Debug.Assert(ptCurrentCell.X == -1); bool success = SetAndSelectCurrentCellAddress(newCurrentCell.X, newCurrentCell.Y, true, false, false, false /*clearSelection*/, - this.Rows.GetRowCount(DataGridViewElementStates.Visible) == 1 /*forceCurrentCellSelection*/); + Rows.GetRowCount(DataGridViewElementStates.Visible) == 1 /*forceCurrentCellSelection*/); Debug.Assert(success); } } @@ -15653,7 +15653,7 @@ internal void OnInsertedRows_PreNotification(int rowIndex, DataGridViewRow[] dat Debug.Assert(dataGridViewRows.Length > 0); // Fix the OldFirstDisplayedScrollingRow - this.displayedBandsInfo.CorrectRowIndexAfterInsertion(rowIndex, dataGridViewRows.Length); + displayedBandsInfo.CorrectRowIndexAfterInsertion(rowIndex, dataGridViewRows.Length); // Fix the Index of all following rows CorrectRowIndexesAfterInsertion(rowIndex, dataGridViewRows.Length); @@ -15673,7 +15673,7 @@ internal void OnInsertedRows_PostNotification(DataGridViewRow[] dataGridViewRows // Update current cell if needed if (newCurrentCell.Y != -1) { - Debug.Assert(this.ptCurrentCell.X == -1); + Debug.Assert(ptCurrentCell.X == -1); bool success = SetAndSelectCurrentCellAddress(newCurrentCell.X, newCurrentCell.Y, true, false, false, false /*clearSelection*/, false /*forceCurrentCellSelection*/); Debug.Assert(success); } @@ -15688,12 +15688,12 @@ internal void OnInsertingColumn(int columnIndexInserted, DataGridViewColumn data throw new InvalidOperationException(string.Format(SR.DataGridView_ColumnAlreadyBelongsToDataGridView)); } - if (!this.InInitialization && + if (!InInitialization && dataGridViewColumn.SortMode == DataGridViewColumnSortMode.Automatic && - (this.SelectionMode == DataGridViewSelectionMode.FullColumnSelect || - this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect)) + (SelectionMode == DataGridViewSelectionMode.FullColumnSelect || + SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect)) { - throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_SortModeAndSelectionModeClash, DataGridViewColumnSortMode.Automatic.ToString(), this.SelectionMode.ToString())); + throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_SortModeAndSelectionModeClash, DataGridViewColumnSortMode.Automatic.ToString(), SelectionMode.ToString())); } if (dataGridViewColumn.Visible) @@ -15701,15 +15701,15 @@ internal void OnInsertingColumn(int columnIndexInserted, DataGridViewColumn data // Note that dataGridViewColumn.DataGridView is set later on, so dataGridViewColumn.InheritedAutoSizeMode should not be used // Make sure the column does not autosize based only on header while column headers are invisible - if (!this.ColumnHeadersVisible && - (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.ColumnHeader || (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.NotSet && this.AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.ColumnHeader))) + if (!ColumnHeadersVisible && + (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.ColumnHeader || (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.NotSet && AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.ColumnHeader))) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAddAutoSizedColumn)); } // Make sure the column is not frozen and auto fills if (dataGridViewColumn.Frozen && - (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.Fill || (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.NotSet && this.AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.Fill))) + (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.Fill || (dataGridViewColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.NotSet && AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.Fill))) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAddAutoFillColumn)); } @@ -15719,10 +15719,10 @@ internal void OnInsertingColumn(int columnIndexInserted, DataGridViewColumn data CorrectColumnFrozenState(dataGridViewColumn, columnIndexInserted); // Reset current cell if there is one, no matter the relative position of the columns involved - if (this.ptCurrentCell.X != -1) + if (ptCurrentCell.X != -1) { - newCurrentCell = new Point(columnIndexInserted <= this.ptCurrentCell.X ? this.ptCurrentCell.X + 1 : this.ptCurrentCell.X, - this.ptCurrentCell.Y); + newCurrentCell = new Point(columnIndexInserted <= ptCurrentCell.X ? ptCurrentCell.X + 1 : ptCurrentCell.X, + ptCurrentCell.Y); ResetCurrentCell(); } else @@ -15731,7 +15731,7 @@ internal void OnInsertingColumn(int columnIndexInserted, DataGridViewColumn data } // prepare the existing rows by inserting cells of correct type - if (this.Rows.Count > 0) + if (Rows.Count > 0) { // Only require a default cell type when there are rows to fill if (dataGridViewColumn.CellType == null) @@ -15739,24 +15739,24 @@ internal void OnInsertingColumn(int columnIndexInserted, DataGridViewColumn data throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAddUntypedColumn)); } - if (dataGridViewColumn.CellTemplate.DefaultNewRowValue != null && this.newRowIndex != -1) + if (dataGridViewColumn.CellTemplate.DefaultNewRowValue != null && newRowIndex != -1) { // New row needs to be unshared before addition of new cell with a Value != null - DataGridViewRow newRow = this.Rows[this.newRowIndex]; + DataGridViewRow newRow = Rows[newRowIndex]; } - int newColumnCount = this.Columns.Count + 1; + int newColumnCount = Columns.Count + 1; try { - for (int rowIndex = 0; rowIndex < this.Rows.Count; rowIndex++) + for (int rowIndex = 0; rowIndex < Rows.Count; rowIndex++) { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); if (dataGridViewRow.Cells.Count < newColumnCount) { DataGridViewCell dataGridViewCellNew = (DataGridViewCell)dataGridViewColumn.CellTemplate.Clone(); dataGridViewRow.Cells.InsertInternal(columnIndexInserted, dataGridViewCellNew); - if (rowIndex == this.newRowIndex) + if (rowIndex == newRowIndex) { dataGridViewCellNew.Value = dataGridViewCellNew.DefaultNewRowValue; } @@ -15769,9 +15769,9 @@ internal void OnInsertingColumn(int columnIndexInserted, DataGridViewColumn data catch { // An error occurred while inserting the cells. Revert all the insertions. - for (int rowIndex = 0; rowIndex < this.Rows.Count; rowIndex++) + for (int rowIndex = 0; rowIndex < Rows.Count; rowIndex++) { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); if (dataGridViewRow.Cells.Count == newColumnCount) { dataGridViewRow.Cells.RemoveAtInternal(columnIndexInserted); @@ -15787,31 +15787,31 @@ internal void OnInsertingColumn(int columnIndexInserted, DataGridViewColumn data } // Update the indexes of selected columns to compensate for the insertion of this column - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: - int columnEntries = this.selectedBandIndexes.Count; + int columnEntries = selectedBandIndexes.Count; int columnEntry = 0; while (columnEntry < columnEntries) { - int columnIndex = this.selectedBandIndexes[columnEntry]; + int columnIndex = selectedBandIndexes[columnEntry]; if (columnIndexInserted <= columnIndex) { - this.selectedBandIndexes[columnEntry] = columnIndex + 1; + selectedBandIndexes[columnEntry] = columnIndex + 1; } columnEntry++; } - if (this.selectedBandSnapshotIndexes != null) + if (selectedBandSnapshotIndexes != null) { - columnEntries = this.selectedBandSnapshotIndexes.Count; + columnEntries = selectedBandSnapshotIndexes.Count; columnEntry = 0; while (columnEntry < columnEntries) { - int columnIndex = this.selectedBandSnapshotIndexes[columnEntry]; + int columnIndex = selectedBandSnapshotIndexes[columnEntry]; if (columnIndexInserted <= columnIndex) { - this.selectedBandSnapshotIndexes[columnEntry] = columnIndex + 1; + selectedBandSnapshotIndexes[columnEntry] = columnIndex + 1; } columnEntry++; } @@ -15831,14 +15831,14 @@ internal void OnInsertingRow(int rowIndexInserted, // Reset the current cell's address if it's after the inserted row. if (firstInsertion) { - if (this.ptCurrentCell.Y != -1 && rowIndexInserted <= this.ptCurrentCell.Y) + if (ptCurrentCell.Y != -1 && rowIndexInserted <= ptCurrentCell.Y) { - newCurrentCell = new Point(this.ptCurrentCell.X, this.ptCurrentCell.Y + insertionCount); + newCurrentCell = new Point(ptCurrentCell.X, ptCurrentCell.Y + insertionCount); if (force) { // When force is true, the underlying data was already added, therefore we need to avoid accessing any back-end data // since we might be off by 1 row. - this.dataGridViewState1[DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell] = true; + dataGridViewState1[DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell] = true; bool success = SetCurrentCellAddressCore(-1, -1, true /*setAnchorCellAddress*/, false /*validateCurrentCell*/, false); Debug.Assert(success); } @@ -15867,31 +15867,31 @@ internal void OnInsertingRow(int rowIndexInserted, CorrectRowFrozenState(dataGridViewRow, rowState, rowIndexInserted); // Update the indexes of selected rows to compensate for the insertion of this row - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: - int rowEntries = this.selectedBandIndexes.Count; + int rowEntries = selectedBandIndexes.Count; int rowEntry = 0; while (rowEntry < rowEntries) { - int rowIndex = this.selectedBandIndexes[rowEntry]; + int rowIndex = selectedBandIndexes[rowEntry]; if (rowIndexInserted <= rowIndex) { - this.selectedBandIndexes[rowEntry] = rowIndex + insertionCount; + selectedBandIndexes[rowEntry] = rowIndex + insertionCount; } rowEntry++; } - if (this.selectedBandSnapshotIndexes != null) + if (selectedBandSnapshotIndexes != null) { - rowEntries = this.selectedBandSnapshotIndexes.Count; + rowEntries = selectedBandSnapshotIndexes.Count; rowEntry = 0; while (rowEntry < rowEntries) { - int rowIndex = this.selectedBandSnapshotIndexes[rowEntry]; + int rowIndex = selectedBandSnapshotIndexes[rowEntry]; if (rowIndexInserted <= rowIndex) { - this.selectedBandSnapshotIndexes[rowEntry] = rowIndex + insertionCount; + selectedBandSnapshotIndexes[rowEntry] = rowIndex + insertionCount; } rowEntry++; } @@ -15905,9 +15905,9 @@ internal void OnInsertingRows(int rowIndexInserted, DataGridViewRow[] dataGridVi Debug.Assert(dataGridViewRows != null); // Reset the current cell's address if it's after the inserted row. - if (this.ptCurrentCell.Y != -1 && rowIndexInserted <= this.ptCurrentCell.Y) + if (ptCurrentCell.Y != -1 && rowIndexInserted <= ptCurrentCell.Y) { - newCurrentCell = new Point(this.ptCurrentCell.X, this.ptCurrentCell.Y + dataGridViewRows.Length); + newCurrentCell = new Point(ptCurrentCell.X, ptCurrentCell.Y + dataGridViewRows.Length); ResetCurrentCell(); } else @@ -15923,31 +15923,31 @@ internal void OnInsertingRows(int rowIndexInserted, DataGridViewRow[] dataGridVi CorrectRowFrozenStates(dataGridViewRows, rowIndexInserted); // Update the indexes of selected rows to compensate for the insertion of this row - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: - int rowEntries = this.selectedBandIndexes.Count; + int rowEntries = selectedBandIndexes.Count; int rowEntry = 0; while (rowEntry < rowEntries) { - int rowIndex = this.selectedBandIndexes[rowEntry]; + int rowIndex = selectedBandIndexes[rowEntry]; if (rowIndexInserted <= rowIndex) { - this.selectedBandIndexes[rowEntry] = rowIndex + dataGridViewRows.Length; + selectedBandIndexes[rowEntry] = rowIndex + dataGridViewRows.Length; } rowEntry++; } - if (this.selectedBandSnapshotIndexes != null) + if (selectedBandSnapshotIndexes != null) { - rowEntries = this.selectedBandSnapshotIndexes.Count; + rowEntries = selectedBandSnapshotIndexes.Count; rowEntry = 0; while (rowEntry < rowEntries) { - int rowIndex = this.selectedBandSnapshotIndexes[rowEntry]; + int rowIndex = selectedBandSnapshotIndexes[rowEntry]; if (rowIndexInserted <= rowIndex) { - this.selectedBandSnapshotIndexes[rowEntry] = rowIndex + dataGridViewRows.Length; + selectedBandSnapshotIndexes[rowEntry] = rowIndex + dataGridViewRows.Length; } rowEntry++; } @@ -15966,18 +15966,18 @@ protected override void OnKeyDown(KeyEventArgs e) } // Forward key down to current cell if any - if (this.ptCurrentCell.X != -1) + if (ptCurrentCell.X != -1) { - DataGridViewCell dataGridViewCell = this.CurrentCellInternal; + DataGridViewCell dataGridViewCell = CurrentCellInternal; Debug.Assert(dataGridViewCell != null); - if (dataGridViewCell.KeyDownUnsharesRowInternal(e, this.ptCurrentCell.Y)) + if (dataGridViewCell.KeyDownUnsharesRowInternal(e, ptCurrentCell.Y)) { - DataGridViewRow dataGridViewRow = this.Rows[this.ptCurrentCell.Y]; - this.CurrentCellInternal.OnKeyDownInternal(e, this.ptCurrentCell.Y); + DataGridViewRow dataGridViewRow = Rows[ptCurrentCell.Y]; + CurrentCellInternal.OnKeyDownInternal(e, ptCurrentCell.Y); } else { - dataGridViewCell.OnKeyDownInternal(e, this.ptCurrentCell.Y); + dataGridViewCell.OnKeyDownInternal(e, ptCurrentCell.Y); } } @@ -16023,18 +16023,18 @@ protected override void OnKeyPress(KeyPressEventArgs e) } // Forward key press to current cell if any - if (this.ptCurrentCell.X != -1) + if (ptCurrentCell.X != -1) { - DataGridViewCell dataGridViewCell = this.CurrentCellInternal; + DataGridViewCell dataGridViewCell = CurrentCellInternal; Debug.Assert(dataGridViewCell != null); - if (dataGridViewCell.KeyPressUnsharesRowInternal(e, this.ptCurrentCell.Y)) + if (dataGridViewCell.KeyPressUnsharesRowInternal(e, ptCurrentCell.Y)) { - DataGridViewRow dataGridViewRow = this.Rows[this.ptCurrentCell.Y]; - this.CurrentCellInternal.OnKeyPressInternal(e, this.ptCurrentCell.Y); + DataGridViewRow dataGridViewRow = Rows[ptCurrentCell.Y]; + CurrentCellInternal.OnKeyPressInternal(e, ptCurrentCell.Y); } else { - dataGridViewCell.OnKeyPressInternal(e, this.ptCurrentCell.Y); + dataGridViewCell.OnKeyPressInternal(e, ptCurrentCell.Y); } } } @@ -16048,44 +16048,44 @@ protected override void OnKeyUp(KeyEventArgs e) return; } - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackKeyboardColResize] && (e.KeyData & Keys.Alt) != Keys.Alt) + if (dataGridViewOper[DATAGRIDVIEWOPER_trackKeyboardColResize] && (e.KeyData & Keys.Alt) != Keys.Alt) { - this.EndColumnResize(this.currentColSplitBar); - this.ResetKeyboardTrackingState(); + EndColumnResize(currentColSplitBar); + ResetKeyboardTrackingState(); return; } // Forward key up to current cell if any - if (this.ptCurrentCell.X != -1) + if (ptCurrentCell.X != -1) { - DataGridViewCell dataGridViewCell = this.CurrentCellInternal; + DataGridViewCell dataGridViewCell = CurrentCellInternal; Debug.Assert(dataGridViewCell != null); - if (dataGridViewCell.KeyUpUnsharesRowInternal(e, this.ptCurrentCell.Y)) + if (dataGridViewCell.KeyUpUnsharesRowInternal(e, ptCurrentCell.Y)) { - DataGridViewRow dataGridViewRow = this.Rows[this.ptCurrentCell.Y]; - this.CurrentCellInternal.OnKeyUpInternal(e, this.ptCurrentCell.Y); + DataGridViewRow dataGridViewRow = Rows[ptCurrentCell.Y]; + CurrentCellInternal.OnKeyUpInternal(e, ptCurrentCell.Y); } else { - dataGridViewCell.OnKeyUpInternal(e, this.ptCurrentCell.Y); + dataGridViewCell.OnKeyUpInternal(e, ptCurrentCell.Y); } } } protected override void OnLayout(LayoutEventArgs e) { - if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlChanging]) + if (dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlChanging]) { return; } base.OnLayout(e); PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, false /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); - if (this.RightToLeftInternal) + if (RightToLeftInternal) { Invalidate(); } - if (this.editingControl != null) + if (editingControl != null) { PositionEditingControl(true, true, false); } @@ -16093,41 +16093,41 @@ protected override void OnLayout(LayoutEventArgs e) protected override void OnLeave(EventArgs e) { - if (this.ptCurrentCell.X > -1 && !this.dataGridViewState1[DATAGRIDVIEWSTATE1_leavingWithTabKey]) + if (ptCurrentCell.X > -1 && !dataGridViewState1[DATAGRIDVIEWSTATE1_leavingWithTabKey]) { DataGridViewCell dataGridViewCell = null; - OnCellLeave(ref dataGridViewCell, this.ptCurrentCell.X, this.ptCurrentCell.Y); - if (this.ptCurrentCell.X == -1) + OnCellLeave(ref dataGridViewCell, ptCurrentCell.X, ptCurrentCell.Y); + if (ptCurrentCell.X == -1) { return; } - OnRowLeave(ref dataGridViewCell, this.ptCurrentCell.X, this.ptCurrentCell.Y); + OnRowLeave(ref dataGridViewCell, ptCurrentCell.X, ptCurrentCell.Y); } - if (!this.dataGridViewState1[DATAGRIDVIEWSTATE1_leavingWithTabKey]) + if (!dataGridViewState1[DATAGRIDVIEWSTATE1_leavingWithTabKey]) { base.OnLeave(e); // invalidate the current cell so the data grid view does not paint the focus rectangle any longer - if (this.ptCurrentCell.X > -1 && this.ptCurrentCell.Y > -1) + if (ptCurrentCell.X > -1 && ptCurrentCell.Y > -1) { - InvalidateCellPrivate(this.ptCurrentCell.X /*columnIndex*/, this.ptCurrentCell.Y /*rowIndex*/); + InvalidateCellPrivate(ptCurrentCell.X /*columnIndex*/, ptCurrentCell.Y /*rowIndex*/); } } // Erase focus rectangle around the grid - if (this.IsGridFocusRectangleEnabled()) + if (IsGridFocusRectangleEnabled()) { - this.InvalidateRectangleEdges(this.GetGridFocusRectangle()); + InvalidateRectangleEdges(GetGridFocusRectangle()); } } protected override void OnLostFocus(EventArgs e) { base.OnLostFocus(e); - if (this.ptCurrentCell.X != -1) + if (ptCurrentCell.X != -1) { - InvalidateCell(this.ptCurrentCell.X, this.ptCurrentCell.Y); + InvalidateCell(ptCurrentCell.X, ptCurrentCell.Y); } } @@ -16135,22 +16135,22 @@ protected override void OnMouseClick(MouseEventArgs e) { bool mouseClickRaised = false; - if (!this.dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackColResize] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowResize] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize]) + if (!dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls] && + !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed && + !dataGridViewOper[DATAGRIDVIEWOPER_trackColResize] && + !dataGridViewOper[DATAGRIDVIEWOPER_trackRowResize] && + !dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize] && + !dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize]) { HitTestInfo hti = HitTest(e.X, e.Y); - if (this.ptMouseDownCell.X == hti.col && - this.ptMouseDownCell.Y == hti.row && + if (ptMouseDownCell.X == hti.col && + ptMouseDownCell.Y == hti.row && (e.Button != MouseButtons.Left || - this.ptMouseDownCell.X == -1 || - this.ptMouseDownCell.Y == -1 || - (this.ptMouseDownCell.X == this.ptCurrentCell.X && - this.ptMouseDownCell.Y == this.ptCurrentCell.Y))) + ptMouseDownCell.X == -1 || + ptMouseDownCell.Y == -1 || + (ptMouseDownCell.X == ptCurrentCell.X && + ptMouseDownCell.Y == ptCurrentCell.Y))) { DataGridViewCellMouseEventArgs dgvcme = null; if (hti.Type != DataGridViewHitTestType.None && @@ -16158,9 +16158,9 @@ protected override void OnMouseClick(MouseEventArgs e) hti.Type != DataGridViewHitTestType.VerticalScrollBar) { int mouseX = e.X - hti.ColumnX; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - mouseX += ((hti.col == -1) ? this.RowHeadersWidth : this.Columns[hti.col].Thickness); + mouseX += ((hti.col == -1) ? RowHeadersWidth : Columns[hti.col].Thickness); } dgvcme = new DataGridViewCellMouseEventArgs(hti.col, hti.row, mouseX, e.Y - hti.RowY, e); RecordCellMouseClick(dgvcme); @@ -16170,7 +16170,7 @@ protected override void OnMouseClick(MouseEventArgs e) } base.OnMouseClick(e); mouseClickRaised = true; - if (dgvcme.ColumnIndex < this.Columns.Count && dgvcme.RowIndex < this.Rows.Count) + if (dgvcme.ColumnIndex < Columns.Count && dgvcme.RowIndex < Rows.Count) { OnCellMouseClick(dgvcme); } @@ -16181,7 +16181,7 @@ protected override void OnMouseClick(MouseEventArgs e) mouseClickRaised = true; } - if (!this.dataGridViewOper[DATAGRIDVIEWOPER_trackColRelocation]) + if (!dataGridViewOper[DATAGRIDVIEWOPER_trackColRelocation]) { switch (hti.typeInternal) { @@ -16191,7 +16191,7 @@ protected override void OnMouseClick(MouseEventArgs e) case DataGridViewHitTestTypeInternal.FirstColumnHeaderLeft: { Debug.Assert(dgvcme != null); - if (dgvcme.ColumnIndex < this.Columns.Count && dgvcme.RowIndex < this.Rows.Count) + if (dgvcme.ColumnIndex < Columns.Count && dgvcme.RowIndex < Rows.Count) { OnColumnHeaderMouseClick(dgvcme); } @@ -16201,7 +16201,7 @@ protected override void OnMouseClick(MouseEventArgs e) case DataGridViewHitTestTypeInternal.RowHeader: { Debug.Assert(dgvcme != null); - if (dgvcme.ColumnIndex < this.Columns.Count && dgvcme.RowIndex < this.Rows.Count) + if (dgvcme.ColumnIndex < Columns.Count && dgvcme.RowIndex < Rows.Count) { OnRowHeaderMouseClick(dgvcme); } @@ -16221,15 +16221,15 @@ protected override void OnMouseDoubleClick(MouseEventArgs e) { base.OnMouseDoubleClick(e); - if (!this.dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackColResize] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowResize] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize]) + if (!dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls] && + !dataGridViewOper[DATAGRIDVIEWOPER_trackColResize] && + !dataGridViewOper[DATAGRIDVIEWOPER_trackRowResize] && + !dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize] && + !dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize]) { HitTestInfo hti = HitTest(e.X, e.Y); - if (this.ptMouseDownCell.X == hti.col && this.ptMouseDownCell.Y == hti.row) + if (ptMouseDownCell.X == hti.col && ptMouseDownCell.Y == hti.row) { DataGridViewCellMouseEventArgs dgvcme = null; if (hti.Type != DataGridViewHitTestType.None && @@ -16237,15 +16237,15 @@ protected override void OnMouseDoubleClick(MouseEventArgs e) hti.Type != DataGridViewHitTestType.VerticalScrollBar) { int mouseX = e.X - hti.ColumnX; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - mouseX += ((hti.col == -1) ? this.RowHeadersWidth : this.Columns[hti.col].Thickness); + mouseX += ((hti.col == -1) ? RowHeadersWidth : Columns[hti.col].Thickness); } dgvcme = new DataGridViewCellMouseEventArgs(hti.col, hti.row, mouseX, e.Y - hti.RowY, e); OnCellMouseDoubleClick(dgvcme); } - if (!this.dataGridViewOper[DATAGRIDVIEWOPER_trackColRelocation]) + if (!dataGridViewOper[DATAGRIDVIEWOPER_trackColRelocation]) { switch (hti.typeInternal) { @@ -16255,7 +16255,7 @@ protected override void OnMouseDoubleClick(MouseEventArgs e) case DataGridViewHitTestTypeInternal.FirstColumnHeaderLeft: { Debug.Assert(dgvcme != null); - if (dgvcme.ColumnIndex < this.Columns.Count && dgvcme.RowIndex < this.Rows.Count) + if (dgvcme.ColumnIndex < Columns.Count && dgvcme.RowIndex < Rows.Count) { OnColumnHeaderMouseDoubleClick(dgvcme); } @@ -16266,11 +16266,11 @@ protected override void OnMouseDoubleClick(MouseEventArgs e) case DataGridViewHitTestTypeInternal.ColumnResizeRight: { int columnIndex = (hti.typeInternal == DataGridViewHitTestTypeInternal.ColumnResizeRight) ? hti.col : hti.adjacentCol; - if (columnIndex < this.Columns.Count) + if (columnIndex < Columns.Count) { HandledMouseEventArgs hme = new HandledMouseEventArgs(e.Button, e.Clicks, e.X, e.Y, e.Delta, false /*defaultHandledValue*/); DataGridViewColumnDividerDoubleClickEventArgs dgvcddce = new DataGridViewColumnDividerDoubleClickEventArgs(columnIndex, hme); - Debug.Assert(this.Columns[columnIndex].Resizable == DataGridViewTriState.True); + Debug.Assert(Columns[columnIndex].Resizable == DataGridViewTriState.True); OnColumnDividerDoubleClick(dgvcddce); } break; @@ -16283,7 +16283,7 @@ protected override void OnMouseDoubleClick(MouseEventArgs e) { HandledMouseEventArgs hme = new HandledMouseEventArgs(e.Button, e.Clicks, e.X, e.Y, e.Delta, false /*defaultHandledValue*/); DataGridViewRowDividerDoubleClickEventArgs dgvrddce = new DataGridViewRowDividerDoubleClickEventArgs(-1, hme); - Debug.Assert(this.columnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing); + Debug.Assert(columnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.EnableResizing); OnRowDividerDoubleClick(dgvrddce); break; } @@ -16291,7 +16291,7 @@ protected override void OnMouseDoubleClick(MouseEventArgs e) case DataGridViewHitTestTypeInternal.RowHeader: { Debug.Assert(dgvcme != null); - if (dgvcme.ColumnIndex < this.Columns.Count && dgvcme.RowIndex < this.Rows.Count) + if (dgvcme.ColumnIndex < Columns.Count && dgvcme.RowIndex < Rows.Count) { OnRowHeaderMouseDoubleClick(dgvcme); } @@ -16302,11 +16302,11 @@ protected override void OnMouseDoubleClick(MouseEventArgs e) case DataGridViewHitTestTypeInternal.RowResizeTop: { int rowIndex = (hti.typeInternal == DataGridViewHitTestTypeInternal.RowResizeBottom) ? hti.row : hti.adjacentRow; - if (rowIndex < this.Rows.Count) + if (rowIndex < Rows.Count) { HandledMouseEventArgs hme = new HandledMouseEventArgs(e.Button, e.Clicks, e.X, e.Y, e.Delta, false /*defaultHandledValue*/); DataGridViewRowDividerDoubleClickEventArgs dgvrddce = new DataGridViewRowDividerDoubleClickEventArgs(rowIndex, hme); - Debug.Assert(this.Rows[rowIndex].Resizable == DataGridViewTriState.True); + Debug.Assert(Rows[rowIndex].Resizable == DataGridViewTriState.True); OnRowDividerDoubleClick(dgvrddce); } break; @@ -16319,7 +16319,7 @@ protected override void OnMouseDoubleClick(MouseEventArgs e) { HandledMouseEventArgs hme = new HandledMouseEventArgs(e.Button, e.Clicks, e.X, e.Y, e.Delta, false /*defaultHandledValue*/); DataGridViewColumnDividerDoubleClickEventArgs dgvcddce = new DataGridViewColumnDividerDoubleClickEventArgs(-1, hme); - Debug.Assert(this.rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing); + Debug.Assert(rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing); OnColumnDividerDoubleClick(dgvcddce); break; } @@ -16331,22 +16331,22 @@ protected override void OnMouseDoubleClick(MouseEventArgs e) protected override void OnMouseDown(MouseEventArgs e) { - if (!this.dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls]) + if (!dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls]) { - this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves] = true; + dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves] = true; } base.OnMouseDown(e); - if (this.dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls]) + if (dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls]) { return; } - if (this.ptMouseDownCell.X != -2) + if (ptMouseDownCell.X != -2) { // Happens when user pushes the mouse wheel down while the left mouse button is already down - Debug.Assert(this.ptMouseDownCell.Y != -2); + Debug.Assert(ptMouseDownCell.Y != -2); return; } @@ -16356,13 +16356,13 @@ protected override void OnMouseDown(MouseEventArgs e) hti.Type != DataGridViewHitTestType.HorizontalScrollBar && hti.Type != DataGridViewHitTestType.VerticalScrollBar) { - this.ptMouseDownCell.X = hti.col; - this.ptMouseDownCell.Y = hti.row; - this.ptMouseDownGridCoord = new Point(e.X, e.Y); + ptMouseDownCell.X = hti.col; + ptMouseDownCell.Y = hti.row; + ptMouseDownGridCoord = new Point(e.X, e.Y); int mouseX = e.X - hti.ColumnX; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - mouseX += ((hti.col == -1) ? this.RowHeadersWidth : this.Columns[hti.col].Thickness); + mouseX += ((hti.col == -1) ? RowHeadersWidth : Columns[hti.col].Thickness); } DataGridViewCellMouseEventArgs dgvcme = new DataGridViewCellMouseEventArgs(hti.col, hti.row, mouseX, e.Y - hti.RowY, e); OnCellMouseDown(dgvcme); @@ -16371,54 +16371,54 @@ protected override void OnMouseDown(MouseEventArgs e) protected override void OnMouseEnter(EventArgs e) { - if (!this.dataGridViewState2[DATAGRIDVIEWSTATE2_mouseOverRemovedEditingCtrl] && - !this.dataGridViewState2[DATAGRIDVIEWSTATE2_mouseOverRemovedEditingPanel] && - this.dataGridViewState2[DATAGRIDVIEWSTATE2_mouseEnterExpected] && - !this.toolTipControl.Activated) + if (!dataGridViewState2[DATAGRIDVIEWSTATE2_mouseOverRemovedEditingCtrl] && + !dataGridViewState2[DATAGRIDVIEWSTATE2_mouseOverRemovedEditingPanel] && + dataGridViewState2[DATAGRIDVIEWSTATE2_mouseEnterExpected] && + !toolTipControl.Activated) { base.OnMouseEnter(e); } - this.dataGridViewState2[DATAGRIDVIEWSTATE2_mouseOverRemovedEditingCtrl] = false; - this.dataGridViewState2[DATAGRIDVIEWSTATE2_mouseOverRemovedEditingPanel] = false; - this.dataGridViewState2[DATAGRIDVIEWSTATE2_mouseEnterExpected] = false; + dataGridViewState2[DATAGRIDVIEWSTATE2_mouseOverRemovedEditingCtrl] = false; + dataGridViewState2[DATAGRIDVIEWSTATE2_mouseOverRemovedEditingPanel] = false; + dataGridViewState2[DATAGRIDVIEWSTATE2_mouseEnterExpected] = false; } protected override void OnMouseLeave(EventArgs e) { // when the mouse leaves the dataGridView control, reset the cursor to the previously cached one - if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet]) + if (dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet]) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet] = false; - this.CursorInternal = this.oldCursor; + dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet] = false; + CursorInternal = oldCursor; } - bool mouseOverEditingControl = this.MouseOverEditingControl; - bool mouseOverEditingPanel = this.MouseOverEditingPanel; - bool mouseOverToolTipControl = this.toolTipControl.Activated && this.ClientRectangle.Contains(PointToClient(Control.MousePosition)); + bool mouseOverEditingControl = MouseOverEditingControl; + bool mouseOverEditingPanel = MouseOverEditingPanel; + bool mouseOverToolTipControl = toolTipControl.Activated && ClientRectangle.Contains(PointToClient(Control.MousePosition)); - if (!mouseOverEditingPanel && !mouseOverEditingControl && !mouseOverToolTipControl && this.ptMouseEnteredCell.X != -2) + if (!mouseOverEditingPanel && !mouseOverEditingControl && !mouseOverToolTipControl && ptMouseEnteredCell.X != -2) { - if (this.ptMouseEnteredCell.X >= -1 && this.ptMouseEnteredCell.X < this.Columns.Count && - this.ptMouseEnteredCell.Y >= -1 && this.ptMouseEnteredCell.Y < this.Rows.Count) + if (ptMouseEnteredCell.X >= -1 && ptMouseEnteredCell.X < Columns.Count && + ptMouseEnteredCell.Y >= -1 && ptMouseEnteredCell.Y < Rows.Count) { - DataGridViewCellEventArgs dgvce = new DataGridViewCellEventArgs(this.ptMouseEnteredCell.X, this.ptMouseEnteredCell.Y); + DataGridViewCellEventArgs dgvce = new DataGridViewCellEventArgs(ptMouseEnteredCell.X, ptMouseEnteredCell.Y); OnCellMouseLeave(dgvce); } else { - this.ptMouseEnteredCell.X = this.ptMouseEnteredCell.Y = -2; + ptMouseEnteredCell.X = ptMouseEnteredCell.Y = -2; } } ResetTrackingState(); - this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves] = false; + dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves] = false; - if (!mouseOverEditingPanel && !mouseOverEditingControl && !mouseOverToolTipControl && !this.MouseOverScrollBar) + if (!mouseOverEditingPanel && !mouseOverEditingControl && !mouseOverToolTipControl && !MouseOverScrollBar) { - this.toolTipControl.Activate(false /*activate*/); + toolTipControl.Activate(false /*activate*/); base.OnMouseLeave(e); - this.dataGridViewState2[DATAGRIDVIEWSTATE2_mouseEnterExpected] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_mouseEnterExpected] = true; } } @@ -16431,69 +16431,69 @@ protected override void OnMouseMove(MouseEventArgs e) UpdateMouseEnteredCell(hti, e); // We need to give UI feedback when the user is resizing a column - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackColResize]) + if (dataGridViewOper[DATAGRIDVIEWOPER_trackColResize]) { MoveRowHeadersOrColumnResize(e.X); } - else if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowResize]) + else if (dataGridViewOper[DATAGRIDVIEWOPER_trackRowResize]) { MoveColumnHeadersOrRowResize(e); } - else if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackColRelocation]) + else if (dataGridViewOper[DATAGRIDVIEWOPER_trackColRelocation]) { MoveColumnRelocation(e, hti); } - else if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize]) + else if (dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize]) { MoveColumnHeadersOrRowResize(e); } - else if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize]) + else if (dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize]) { MoveRowHeadersOrColumnResize(e.X); } - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackColResize] || - this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize] || + if (dataGridViewOper[DATAGRIDVIEWOPER_trackColResize] || + dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize] || ((hti.typeInternal == DataGridViewHitTestTypeInternal.ColumnResizeLeft || hti.typeInternal == DataGridViewHitTestTypeInternal.TopLeftHeaderResizeLeft || hti.typeInternal == DataGridViewHitTestTypeInternal.TopLeftHeaderResizeRight || hti.typeInternal == DataGridViewHitTestTypeInternal.ColumnResizeRight || hti.typeInternal == DataGridViewHitTestTypeInternal.RowHeadersResizeLeft || hti.typeInternal == DataGridViewHitTestTypeInternal.RowHeadersResizeRight) && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackColRelocation] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect])) + !dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize] && + !dataGridViewOper[DATAGRIDVIEWOPER_trackColRelocation] && + !dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] && + !dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] && + !dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect])) { - if (!this.dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet]) + if (!dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet]) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet] = true; - this.oldCursor = this.Cursor; + dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet] = true; + oldCursor = Cursor; } - this.CursorInternal = Cursors.SizeWE; + CursorInternal = Cursors.SizeWE; return; } - else if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowResize] || - this.dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize] || + else if (dataGridViewOper[DATAGRIDVIEWOPER_trackRowResize] || + dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize] || ((hti.typeInternal == DataGridViewHitTestTypeInternal.RowResizeBottom || hti.typeInternal == DataGridViewHitTestTypeInternal.TopLeftHeaderResizeTop || hti.typeInternal == DataGridViewHitTestTypeInternal.TopLeftHeaderResizeBottom || hti.typeInternal == DataGridViewHitTestTypeInternal.RowResizeTop || hti.typeInternal == DataGridViewHitTestTypeInternal.ColumnHeadersResizeTop || hti.typeInternal == DataGridViewHitTestTypeInternal.ColumnHeadersResizeBottom) && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackColRelocation] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect])) + !dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize] && + !dataGridViewOper[DATAGRIDVIEWOPER_trackColRelocation] && + !dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] && + !dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] && + !dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect])) { - if (!this.dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet]) + if (!dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet]) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet] = true; - this.oldCursor = this.Cursor; + dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet] = true; + oldCursor = Cursor; } - this.CursorInternal = Cursors.SizeNS; + CursorInternal = Cursors.SizeNS; return; } /* Whidbey @@ -16513,50 +16513,50 @@ protected override void OnMouseMove(MouseEventArgs e) */ - else if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet]) + else if (dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet]) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet] = false; - this.CursorInternal = this.oldCursor; + dataGridViewState1[DATAGRIDVIEWSTATE1_customCursorSet] = false; + CursorInternal = oldCursor; } - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] || - this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] || - this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect]) + if (dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] || + dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] || + dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect]) { int xOffset, yOffset, mouseX = e.X, mouseY = e.Y; if (GetOutOfBoundCorrectedHitTestInfo(ref hti, ref mouseX, ref mouseY, out xOffset, out yOffset)) { if (xOffset == 0) { - if (this.horizScrollTimer != null && this.horizScrollTimer.Enabled) + if (horizScrollTimer != null && horizScrollTimer.Enabled) { // Mouse's X came in-bound - need to stop the horizontal scroll timer - this.horizScrollTimer.Enabled = false; + horizScrollTimer.Enabled = false; } } - else if (this.horizScrollTimer == null || !this.horizScrollTimer.Enabled) + else if (horizScrollTimer == null || !horizScrollTimer.Enabled) { // Need to start delayed horizontal scroll - this.HorizScrollTimer.Interval = GetColumnScrollRate(Math.Abs(xOffset)); - this.HorizScrollTimer.Enabled = true; + HorizScrollTimer.Interval = GetColumnScrollRate(Math.Abs(xOffset)); + HorizScrollTimer.Enabled = true; } if (yOffset == 0) { - if (this.vertScrollTimer != null && this.vertScrollTimer.Enabled) + if (vertScrollTimer != null && vertScrollTimer.Enabled) { // Mouse's Y came in-bound - need to stop the vertical scroll timer - this.vertScrollTimer.Enabled = false; + vertScrollTimer.Enabled = false; } } - else if (this.vertScrollTimer == null || !this.vertScrollTimer.Enabled) + else if (vertScrollTimer == null || !vertScrollTimer.Enabled) { // Need to start delayed vertical scroll - this.VertScrollTimer.Interval = GetRowScrollRate(Math.Abs(yOffset)); - this.VertScrollTimer.Enabled = true; + VertScrollTimer.Interval = GetRowScrollRate(Math.Abs(yOffset)); + VertScrollTimer.Enabled = true; } - if (this.HorizScrollTimer.Enabled || this.VertScrollTimer.Enabled) + if (HorizScrollTimer.Enabled || VertScrollTimer.Enabled) { return; } @@ -16566,15 +16566,15 @@ protected override void OnMouseMove(MouseEventArgs e) hti.Type != DataGridViewHitTestType.HorizontalScrollBar && hti.Type != DataGridViewHitTestType.VerticalScrollBar) { - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] && hti.col >= 0) + if (dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] && hti.col >= 0) { OnColumnSelectMouseMove(hti); } - else if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] && hti.row >= 0) + else if (dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] && hti.row >= 0) { OnRowSelectMouseMove(hti); } - else if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect] && hti.col >= 0 && hti.row >= 0) + else if (dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect] && hti.col >= 0 && hti.row >= 0) { OnCellSelectMouseMove(hti); } @@ -16584,40 +16584,40 @@ protected override void OnMouseMove(MouseEventArgs e) #if DEBUG else { - Debug.Assert(this.vertScrollTimer == null || !this.vertScrollTimer.Enabled); - Debug.Assert(this.horizScrollTimer == null || !this.horizScrollTimer.Enabled); + Debug.Assert(vertScrollTimer == null || !vertScrollTimer.Enabled); + Debug.Assert(horizScrollTimer == null || !horizScrollTimer.Enabled); } #endif - if (!this.toolTipControl.Activated) + if (!toolTipControl.Activated) { // // After processing the MouseMove event, the tool tip is still not activated. // Reset the tool tip cell. - this.ptToolTipCell = new Point(-1, -1); + ptToolTipCell = new Point(-1, -1); } } protected override void OnMouseUp(MouseEventArgs e) { - if (!this.dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls]) + if (!dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls]) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_scrolledSinceMouseDown] = false; + dataGridViewState1[DATAGRIDVIEWSTATE1_scrolledSinceMouseDown] = false; HitTestInfo hti = HitTest(e.X, e.Y); - if (!this.IsMouseOperationActive()) + if (!IsMouseOperationActive()) { if (hti.Type != DataGridViewHitTestType.None && hti.Type != DataGridViewHitTestType.HorizontalScrollBar && hti.Type != DataGridViewHitTestType.VerticalScrollBar) { int mouseX = e.X - hti.ColumnX; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - mouseX += ((hti.col == -1) ? this.RowHeadersWidth : this.Columns[hti.col].Thickness); + mouseX += ((hti.col == -1) ? RowHeadersWidth : Columns[hti.col].Thickness); } DataGridViewCellMouseEventArgs dgvcme; - if (this.dataGridViewState2[DATAGRIDVIEWSTATE2_nextMouseUpIsDouble]) + if (dataGridViewState2[DATAGRIDVIEWSTATE2_nextMouseUpIsDouble]) { MouseEventArgs meTmp = new MouseEventArgs(e.Button, 2, e.X, e.Y, e.Delta); dgvcme = new DataGridViewCellMouseEventArgs(hti.col, hti.row, mouseX, e.Y - hti.RowY, meTmp); @@ -16626,10 +16626,10 @@ protected override void OnMouseUp(MouseEventArgs e) { dgvcme = new DataGridViewCellMouseEventArgs(hti.col, hti.row, mouseX, e.Y - hti.RowY, e); } - if (hti.col >= 0 && this.ptMouseDownCell.X == hti.col && - hti.row >= 0 && this.ptMouseDownCell.Y == hti.row && - this.EditMode == DataGridViewEditMode.EditOnEnter && - this.editingControl != null) + if (hti.col >= 0 && ptMouseDownCell.X == hti.col && + hti.row >= 0 && ptMouseDownCell.Y == hti.row && + EditMode == DataGridViewEditMode.EditOnEnter && + editingControl != null) { OnClick(e); OnMouseClick(e); @@ -16637,7 +16637,7 @@ protected override void OnMouseUp(MouseEventArgs e) CorrectFocus(true /*onlyIfGridHasFocus*/); - if (dgvcme.ColumnIndex < this.Columns.Count && dgvcme.RowIndex < this.Rows.Count) + if (dgvcme.ColumnIndex < Columns.Count && dgvcme.RowIndex < Rows.Count) { OnCellMouseUp(dgvcme); } @@ -16650,27 +16650,27 @@ protected override void OnMouseUp(MouseEventArgs e) } else { - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackColResize]) + if (dataGridViewOper[DATAGRIDVIEWOPER_trackColResize]) { EndColumnResize(e); } - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowResize]) + if (dataGridViewOper[DATAGRIDVIEWOPER_trackRowResize]) { EndRowResize(e); } - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackColRelocation]) + if (dataGridViewOper[DATAGRIDVIEWOPER_trackColRelocation]) { EndColumnRelocation(e, hti); } - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize]) + if (dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize]) { EndColumnHeadersResize(e); } - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize]) + if (dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize]) { EndRowHeadersResize(e); } @@ -16686,9 +16686,9 @@ protected override void OnMouseUp(MouseEventArgs e) hti.Type != DataGridViewHitTestType.VerticalScrollBar) { int mouseX = e.X - hti.ColumnX; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - mouseX += ((hti.col == -1) ? this.RowHeadersWidth : this.Columns[hti.col].Thickness); + mouseX += ((hti.col == -1) ? RowHeadersWidth : Columns[hti.col].Thickness); } OnCellMouseUp(new DataGridViewCellMouseEventArgs(hti.col, hti.row, mouseX, e.Y - hti.RowY, e)); } @@ -16717,7 +16717,7 @@ protected override void OnMouseWheel(MouseEventArgs e) bool verticalScroll = ((ModifierKeys & Keys.Control) == 0); - ScrollBar sb = (verticalScroll ? (ScrollBar)this.vertScrollBar : (ScrollBar)this.horizScrollBar); + ScrollBar sb = (verticalScroll ? (ScrollBar)vertScrollBar : (ScrollBar)horizScrollBar); if (!sb.Visible || !sb.Enabled) { @@ -16735,22 +16735,22 @@ protected override void OnMouseWheel(MouseEventArgs e) return; // Do not scroll when the user system setting is 0 lines per notch } - Debug.Assert(this.cumulativeVerticalWheelDelta > -NativeMethods.WHEEL_DELTA); - Debug.Assert(this.cumulativeVerticalWheelDelta < NativeMethods.WHEEL_DELTA); - Debug.Assert(this.cumulativeHorizontalWheelDelta > -NativeMethods.WHEEL_DELTA); - Debug.Assert(this.cumulativeHorizontalWheelDelta < NativeMethods.WHEEL_DELTA); + Debug.Assert(cumulativeVerticalWheelDelta > -NativeMethods.WHEEL_DELTA); + Debug.Assert(cumulativeVerticalWheelDelta < NativeMethods.WHEEL_DELTA); + Debug.Assert(cumulativeHorizontalWheelDelta > -NativeMethods.WHEEL_DELTA); + Debug.Assert(cumulativeHorizontalWheelDelta < NativeMethods.WHEEL_DELTA); float partialNotches; if (verticalScroll) { - this.cumulativeVerticalWheelDelta += e.Delta; - partialNotches = (float)this.cumulativeVerticalWheelDelta / (float)NativeMethods.WHEEL_DELTA; + cumulativeVerticalWheelDelta += e.Delta; + partialNotches = (float)cumulativeVerticalWheelDelta / (float)NativeMethods.WHEEL_DELTA; } else { - this.cumulativeHorizontalWheelDelta += e.Delta; - partialNotches = (float)this.cumulativeHorizontalWheelDelta / (float)NativeMethods.WHEEL_DELTA; + cumulativeHorizontalWheelDelta += e.Delta; + partialNotches = (float)cumulativeHorizontalWheelDelta / (float)NativeMethods.WHEEL_DELTA; } int fullNotches = (int)partialNotches; @@ -16760,7 +16760,7 @@ protected override void OnMouseWheel(MouseEventArgs e) // Equivalent to large change scrolls if (fullNotches != 0) { - if (this.ptCurrentCell.X >= 0 && + if (ptCurrentCell.X >= 0 && !CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, false /*forCurrentCellChange*/, false /*forCurrentRowChange*/)) { @@ -16769,28 +16769,28 @@ protected override void OnMouseWheel(MouseEventArgs e) } if (verticalScroll) { - int originalVerticalOffset = this.VerticalOffset; - this.VerticalOffset -= fullNotches * this.vertScrollBar.LargeChange; - if (Math.Abs(this.VerticalOffset - originalVerticalOffset) >= Math.Abs(fullNotches * this.vertScrollBar.LargeChange)) + int originalVerticalOffset = VerticalOffset; + VerticalOffset -= fullNotches * vertScrollBar.LargeChange; + if (Math.Abs(VerticalOffset - originalVerticalOffset) >= Math.Abs(fullNotches * vertScrollBar.LargeChange)) { - this.cumulativeVerticalWheelDelta -= fullNotches * NativeMethods.WHEEL_DELTA; + cumulativeVerticalWheelDelta -= fullNotches * NativeMethods.WHEEL_DELTA; } else { - this.cumulativeVerticalWheelDelta = 0; + cumulativeVerticalWheelDelta = 0; } } else { - int originalHorizontalOffset = this.HorizontalOffset; - this.HorizontalOffset -= fullNotches * this.horizScrollBar.LargeChange; - if (Math.Abs(this.HorizontalOffset - originalHorizontalOffset) >= Math.Abs(fullNotches * this.horizScrollBar.LargeChange)) + int originalHorizontalOffset = HorizontalOffset; + HorizontalOffset -= fullNotches * horizScrollBar.LargeChange; + if (Math.Abs(HorizontalOffset - originalHorizontalOffset) >= Math.Abs(fullNotches * horizScrollBar.LargeChange)) { - this.cumulativeHorizontalWheelDelta -= fullNotches * NativeMethods.WHEEL_DELTA; + cumulativeHorizontalWheelDelta -= fullNotches * NativeMethods.WHEEL_DELTA; } else { - this.cumulativeHorizontalWheelDelta = 0; + cumulativeHorizontalWheelDelta = 0; } } } @@ -16801,7 +16801,7 @@ protected override void OnMouseWheel(MouseEventArgs e) int scrollBands = (int)((float)wheelScrollLines * partialNotches); if (scrollBands != 0) { - if (this.ptCurrentCell.X >= 0 && + if (ptCurrentCell.X >= 0 && !CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, false /*forCurrentCellChange*/, false /*forCurrentRowChange*/)) { @@ -16814,43 +16814,43 @@ protected override void OnMouseWheel(MouseEventArgs e) if (scrollBands > 0) { absScrollBands = scrollBands; - while (this.vertScrollBar.Value != this.vertScrollBar.Minimum && absScrollBands > 0) + while (vertScrollBar.Value != vertScrollBar.Minimum && absScrollBands > 0) { ScrollRowsByCount(-1, ScrollEventType.SmallDecrement); absScrollBands--; } - if (this.vertScrollBar.Value == this.vertScrollBar.Minimum) + if (vertScrollBar.Value == vertScrollBar.Minimum) { - this.cumulativeVerticalWheelDelta = 0; + cumulativeVerticalWheelDelta = 0; } else { - this.cumulativeVerticalWheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); + cumulativeVerticalWheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); } } else { absScrollBands = -scrollBands; - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0); - int totalVisibleFrozenHeight = this.Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingRow >= 0); + int totalVisibleFrozenHeight = Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); while (absScrollBands > 0 && - this.vertScrollBar.Value + this.Rows.SharedRow(this.displayedBandsInfo.FirstDisplayedScrollingRow).GetHeight(this.displayedBandsInfo.FirstDisplayedScrollingRow) <= - this.vertScrollBar.Maximum - ComputeHeightOfFittingTrailingScrollingRows(totalVisibleFrozenHeight)) + vertScrollBar.Value + Rows.SharedRow(displayedBandsInfo.FirstDisplayedScrollingRow).GetHeight(displayedBandsInfo.FirstDisplayedScrollingRow) <= + vertScrollBar.Maximum - ComputeHeightOfFittingTrailingScrollingRows(totalVisibleFrozenHeight)) { ScrollRowsByCount(1, ScrollEventType.SmallIncrement); // Assuming totalVisibleFrozenHeight is unchanged by scrolling operation - Debug.Assert(totalVisibleFrozenHeight == this.Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)); - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0); + Debug.Assert(totalVisibleFrozenHeight == Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)); + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingRow >= 0); absScrollBands--; } - if (this.vertScrollBar.Value + this.Rows.SharedRow(this.displayedBandsInfo.FirstDisplayedScrollingRow).GetHeight(this.displayedBandsInfo.FirstDisplayedScrollingRow) > - this.vertScrollBar.Maximum - ComputeHeightOfFittingTrailingScrollingRows(totalVisibleFrozenHeight)) + if (vertScrollBar.Value + Rows.SharedRow(displayedBandsInfo.FirstDisplayedScrollingRow).GetHeight(displayedBandsInfo.FirstDisplayedScrollingRow) > + vertScrollBar.Maximum - ComputeHeightOfFittingTrailingScrollingRows(totalVisibleFrozenHeight)) { - this.cumulativeVerticalWheelDelta = 0; + cumulativeVerticalWheelDelta = 0; } else { - this.cumulativeVerticalWheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); + cumulativeVerticalWheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); } } } @@ -16859,27 +16859,27 @@ protected override void OnMouseWheel(MouseEventArgs e) int extremeScrollBarValue, scrollBand; if (scrollBands > 0) { - extremeScrollBarValue = this.horizScrollBar.Minimum; + extremeScrollBarValue = horizScrollBar.Minimum; scrollBand = -1; } else { - extremeScrollBarValue = this.horizScrollBar.Maximum; + extremeScrollBarValue = horizScrollBar.Maximum; scrollBand = 1; } absScrollBands = Math.Abs(scrollBands); - while (this.horizScrollBar.Value != extremeScrollBarValue && absScrollBands > 0) + while (horizScrollBar.Value != extremeScrollBarValue && absScrollBands > 0) { ScrollColumns(scrollBand); absScrollBands--; } - if (this.horizScrollBar.Value == extremeScrollBarValue) + if (horizScrollBar.Value == extremeScrollBarValue) { - this.cumulativeHorizontalWheelDelta = 0; + cumulativeHorizontalWheelDelta = 0; } else { - this.cumulativeHorizontalWheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); + cumulativeHorizontalWheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); } } } @@ -16894,8 +16894,8 @@ internal void OnMouseWheelInternal(MouseEventArgs e) protected virtual void OnMultiSelectChanged(EventArgs e) { - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWMULTISELECTCHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWMULTISELECTCHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -16907,8 +16907,8 @@ protected virtual void OnNewRowNeeded(DataGridViewRowEventArgs e) { throw new ArgumentException(string.Format(SR.DataGridView_RowDoesNotBelongToDataGridView), "e.Row"); } - DataGridViewRowEventHandler eh = this.Events[EVENT_DATAGRIDVIEWNEWROWNEEDED] as DataGridViewRowEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWNEWROWNEEDED] as DataGridViewRowEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -16919,27 +16919,27 @@ protected override void OnPaint(PaintEventArgs e) try { // We can't paint if we are disposed. - if (this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] || this.IsDisposed) + if (dataGridViewOper[DATAGRIDVIEWOPER_inDispose] || IsDisposed) { return; } - if (this.layout.dirty) + if (layout.dirty) { PerformLayoutPrivate(false /*useRowShortcut*/, true /*computeVisibleRows*/, false /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); } Graphics g = e.Graphics; Rectangle clipRect = e.ClipRectangle; - Rectangle gridRect = this.GetGridRectangle(); + Rectangle gridRect = GetGridRectangle(); - if (this.currentRowSplitBar != -1) + if (currentRowSplitBar != -1) { - clipRect = Rectangle.Union(clipRect, CalcRowResizeFeedbackRect(this.currentRowSplitBar)); + clipRect = Rectangle.Union(clipRect, CalcRowResizeFeedbackRect(currentRowSplitBar)); } - else if (this.currentColSplitBar != -1) + else if (currentColSplitBar != -1) { - clipRect = Rectangle.Union(clipRect, CalcColResizeFeedbackRect(this.currentColSplitBar)); + clipRect = Rectangle.Union(clipRect, CalcColResizeFeedbackRect(currentColSplitBar)); } if (clipRect.IntersectsWith(gridRect)) @@ -16948,27 +16948,27 @@ protected override void OnPaint(PaintEventArgs e) { g.SetClip(gridRect); PaintBackground(g, clipRect, gridRect); - PaintGrid(g, gridRect, clipRect, this.SingleVerticalBorderAdded, this.SingleHorizontalBorderAdded); + PaintGrid(g, gridRect, clipRect, SingleVerticalBorderAdded, SingleHorizontalBorderAdded); g.Clip = clipRegion; } } - PaintBorder(g, clipRect, this.layout.ClientRectangle); - if (clipRect.IntersectsWith(this.layout.ResizeBoxRect)) + PaintBorder(g, clipRect, layout.ClientRectangle); + if (clipRect.IntersectsWith(layout.ResizeBoxRect)) { - g.FillRectangle(SystemBrushes.Control, this.layout.ResizeBoxRect); + g.FillRectangle(SystemBrushes.Control, layout.ResizeBoxRect); } // Draw focus rectangle around the grid - if (this.Focused && this.IsGridFocusRectangleEnabled()) + if (Focused && IsGridFocusRectangleEnabled()) { if (SystemInformation.HighContrast) { - ControlPaint.DrawHighContrastFocusRectangle(g, this.GetGridFocusRectangle(), SystemColors.ActiveCaptionText); + ControlPaint.DrawHighContrastFocusRectangle(g, GetGridFocusRectangle(), SystemColors.ActiveCaptionText); } else { - ControlPaint.DrawFocusRectangle(g, this.GetGridFocusRectangle()); + ControlPaint.DrawFocusRectangle(g, GetGridFocusRectangle()); } } @@ -16990,34 +16990,34 @@ protected override void OnPaint(PaintEventArgs e) [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool IsGridFocusRectangleEnabled() { - return this.ShowFocusCues && this.CurrentCell == null; + return ShowFocusCues && CurrentCell == null; } // Creates a rectangle by merging row headers, column headers // and cells rectangles (from layout data) private Rectangle GetGridRectangle() { - Rectangle gridRect = this.layout.Data; - if (this.layout.RowHeadersVisible) + Rectangle gridRect = layout.Data; + if (layout.RowHeadersVisible) { - gridRect = Rectangle.Union(gridRect, this.layout.RowHeaders); + gridRect = Rectangle.Union(gridRect, layout.RowHeaders); } - else if (this.SingleVerticalBorderAdded) + else if (SingleVerticalBorderAdded) { - if (!this.RightToLeftInternal) + if (!RightToLeftInternal) { gridRect.X--; } gridRect.Width++; } - if (this.layout.ColumnHeadersVisible) + if (layout.ColumnHeadersVisible) { - gridRect = Rectangle.Union(gridRect, this.layout.ColumnHeaders); + gridRect = Rectangle.Union(gridRect, layout.ColumnHeaders); } - else if (this.SingleHorizontalBorderAdded) + else if (SingleHorizontalBorderAdded) { - if (gridRect.Y == this.layout.Data.Y) + if (gridRect.Y == layout.Data.Y) { gridRect.Y--; gridRect.Height++; @@ -17030,7 +17030,7 @@ private Rectangle GetGridRectangle() // Creates a grid focus rectangle private Rectangle GetGridFocusRectangle() { - Rectangle focusRect = this.GetGridRectangle(); + Rectangle focusRect = GetGridRectangle(); focusRect.Inflate(1 - FOCUS_RECT_OFFSET, 1 - FOCUS_RECT_OFFSET); return focusRect; } @@ -17073,7 +17073,7 @@ private void InvalidateGridFocusOnScroll(int change, ScrollOrientation orientati } } - this.InvalidateRectangleEdges(focusRect); + InvalidateRectangleEdges(focusRect); } private void InvalidateRectangleEdges(Rectangle rect) @@ -17081,20 +17081,20 @@ private void InvalidateRectangleEdges(Rectangle rect) // Left edge Rectangle edge = rect; edge.Width = 1; - this.Invalidate(edge); + Invalidate(edge); // Right edge edge.X += rect.Width - 1; - this.Invalidate(edge); + Invalidate(edge); // Top edge edge = rect; edge.Height = 1; - this.Invalidate(edge); + Invalidate(edge); // Bottom edge edge.Y += rect.Height - 1; - this.Invalidate(edge); + Invalidate(edge); } internal override void OnParentBecameInvisible() @@ -17109,21 +17109,21 @@ internal override void OnParentBecameInvisible() protected virtual void OnReadOnlyChanged(EventArgs e) { - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWREADONLYCHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWREADONLYCHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } VerifyImeRestrictedModeChanged(); - if (!this.ReadOnly && - this.ptCurrentCell.X != -1 && - ColumnEditable(this.ptCurrentCell.X) && - !this.IsCurrentCellInEditMode && - (this.EditMode == DataGridViewEditMode.EditOnEnter || - (this.EditMode != DataGridViewEditMode.EditProgrammatically && this.CurrentCellInternal.EditType == null)) && - !this.Rows[this.ptCurrentCell.Y].Cells[this.ptCurrentCell.X].ReadOnly) // Unshares the row + if (!ReadOnly && + ptCurrentCell.X != -1 && + ColumnEditable(ptCurrentCell.X) && + !IsCurrentCellInEditMode && + (EditMode == DataGridViewEditMode.EditOnEnter || + (EditMode != DataGridViewEditMode.EditProgrammatically && CurrentCellInternal.EditType == null)) && + !Rows[ptCurrentCell.Y].Cells[ptCurrentCell.X].ReadOnly) // Unshares the row { // Current cell becomes read/write. Enter editing mode. BeginEditInternal(true /*selectAll*/); @@ -17146,7 +17146,7 @@ internal void OnRemovedColumn_PreNotification(DataGridViewColumn dataGridViewCol CorrectColumnDisplayIndexesAfterDeletion(dataGridViewColumn); // Fix the OldFirstDisplayedScrollingCol - this.displayedBandsInfo.CorrectRowIndexAfterDeletion(dataGridViewColumn.Index); + displayedBandsInfo.CorrectRowIndexAfterDeletion(dataGridViewColumn.Index); // Raise the ColumnRemoved event OnColumnRemoved(dataGridViewColumn); @@ -17157,7 +17157,7 @@ internal void OnRemovedColumn_PostNotification(DataGridViewColumn dataGridViewCo // Update current cell if needed if (newCurrentCell.X != -1) { - Debug.Assert(this.ptCurrentCell.X == -1); + Debug.Assert(ptCurrentCell.X == -1); bool success = SetAndSelectCurrentCellAddress(newCurrentCell.X, newCurrentCell.Y, true, @@ -17190,13 +17190,13 @@ internal void OnRemovedColumn_PostNotification(DataGridViewColumn dataGridViewCo } // Autosize rows if needed - AdjustShrinkingRows(this.autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); + AdjustShrinkingRows(autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); } internal void OnRemovedRow_PreNotification(int rowIndexDeleted) { // Fix the OldFirstDisplayedScrollingRow - this.displayedBandsInfo.CorrectRowIndexAfterDeletion(rowIndexDeleted); + displayedBandsInfo.CorrectRowIndexAfterDeletion(rowIndexDeleted); CorrectRowIndexesAfterDeletion(rowIndexDeleted); ComputeVisibleRows(); @@ -17207,7 +17207,7 @@ internal void OnRemovedRow_PostNotification(DataGridViewRow dataGridViewRow, Poi // Update current cell if needed if (newCurrentCell.Y != -1) { - Debug.Assert(this.ptCurrentCell.X == -1); + Debug.Assert(ptCurrentCell.X == -1); bool success = SetAndSelectCurrentCellAddress(newCurrentCell.X, newCurrentCell.Y, true /*setAnchorCellAddress*/, @@ -17237,7 +17237,7 @@ internal void OnRemovedRow_PostNotification(DataGridViewRow dataGridViewRow, Poi // - the row's Height // in a RowsRemoved event handler for example, in which case using the CachedThickness may be wrong. // At least we make sure the row is not sized smaller than its minimum height. - if (this.autoSizeRowsMode != DataGridViewAutoSizeRowsMode.None && dataGridViewRow.ThicknessInternal != dataGridViewRow.CachedThickness) + if (autoSizeRowsMode != DataGridViewAutoSizeRowsMode.None && dataGridViewRow.ThicknessInternal != dataGridViewRow.CachedThickness) { dataGridViewRow.ThicknessInternal = Math.Max(dataGridViewRow.MinimumHeight, dataGridViewRow.CachedThickness); } @@ -17249,9 +17249,9 @@ internal void OnRemovedRow_PostNotification(DataGridViewRow dataGridViewRow, Poi autoSizeColumnCriteriaFilter |= DataGridViewAutoSizeColumnCriteriaInternal.DisplayedRows; } bool columnAutoSized = AutoResizeAllVisibleColumnsInternal(autoSizeColumnCriteriaFilter, true /*fixedHeight*/); - bool fixedColumnHeadersHeight = this.ColumnHeadersHeightSizeMode != DataGridViewColumnHeadersHeightSizeMode.AutoSize; - bool fixedRowHeadersWidth = this.rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing || - this.rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.DisableResizing; + bool fixedColumnHeadersHeight = ColumnHeadersHeightSizeMode != DataGridViewColumnHeadersHeightSizeMode.AutoSize; + bool fixedRowHeadersWidth = rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing || + rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.DisableResizing; if (fixedRowHeadersWidth && !columnAutoSized) { @@ -17268,7 +17268,7 @@ internal void OnRemovedRow_PostNotification(DataGridViewRow dataGridViewRow, Poi // Auto size row headers if (!fixedRowHeadersWidth) { - AutoResizeRowHeadersWidth(this.rowHeadersWidthSizeMode, true /*fixedColumnHeadersHeight*/, true /*fixedRowsHeight*/); + AutoResizeRowHeadersWidth(rowHeadersWidthSizeMode, true /*fixedColumnHeadersHeight*/, true /*fixedRowsHeight*/); } if (!fixedColumnHeadersHeight && !fixedRowHeadersWidth) @@ -17281,19 +17281,19 @@ internal void OnRemovedRow_PostNotification(DataGridViewRow dataGridViewRow, Poi internal void OnRemovingColumn(DataGridViewColumn dataGridViewColumn, out Point newCurrentCell, bool force) { Debug.Assert(dataGridViewColumn != null); - Debug.Assert(dataGridViewColumn.Index >= 0 && dataGridViewColumn.Index < this.Columns.Count); + Debug.Assert(dataGridViewColumn.Index >= 0 && dataGridViewColumn.Index < Columns.Count); - this.dataGridViewState1[DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell] = false; + dataGridViewState1[DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell] = false; int columnIndex = dataGridViewColumn.Index; // Reset the current cell's address if there is one. - if (this.ptCurrentCell.X != -1) + if (ptCurrentCell.X != -1) { - int newX = this.ptCurrentCell.X; - if (columnIndex == this.ptCurrentCell.X) + int newX = ptCurrentCell.X; + if (columnIndex == ptCurrentCell.X) { - DataGridViewColumn dataGridViewColumnNext = this.Columns.GetNextColumn( - this.Columns[columnIndex], + DataGridViewColumn dataGridViewColumnNext = Columns.GetNextColumn( + Columns[columnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); if (dataGridViewColumnNext != null) @@ -17309,8 +17309,8 @@ internal void OnRemovingColumn(DataGridViewColumn dataGridViewColumn, out Point } else { - DataGridViewColumn dataGridViewColumnPrevious = this.Columns.GetPreviousColumn( - this.Columns[columnIndex], + DataGridViewColumn dataGridViewColumnPrevious = Columns.GetPreviousColumn( + Columns[columnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); if (dataGridViewColumnPrevious != null) @@ -17330,12 +17330,12 @@ internal void OnRemovingColumn(DataGridViewColumn dataGridViewColumn, out Point } } } - else if (columnIndex < this.ptCurrentCell.X) + else if (columnIndex < ptCurrentCell.X) { - newX = this.ptCurrentCell.X - 1; + newX = ptCurrentCell.X - 1; } - newCurrentCell = new Point(newX, (newX == -1) ? -1 : this.ptCurrentCell.Y); - if (columnIndex == this.ptCurrentCell.X) + newCurrentCell = new Point(newX, (newX == -1) ? -1 : ptCurrentCell.Y); + if (columnIndex == ptCurrentCell.X) { // Left cell is not validated since cancelling validation wouldn't have any effect anyways. bool success = SetCurrentCellAddressCore(-1, -1, true /*setAnchorCellAddress*/, false /*validateCurrentCell*/, false); @@ -17345,7 +17345,7 @@ internal void OnRemovingColumn(DataGridViewColumn dataGridViewColumn, out Point { // Underlying data of deleted column is gone. It cannot be accessed anymore. // Do not end editing mode so that CellValidation doesn't get raised, since that event needs the current formatted value. - this.dataGridViewState1[DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell] = true; + dataGridViewState1[DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell] = true; bool success = SetCurrentCellAddressCore(-1, -1, true /*setAnchorCellAddress*/, false /*validateCurrentCell*/, false); Debug.Assert(success); } @@ -17361,18 +17361,18 @@ internal void OnRemovingColumn(DataGridViewColumn dataGridViewColumn, out Point } // If the last column is removed, delete all the rows first. - if (this.Columns.Count == 1) + if (Columns.Count == 1) { Debug.Assert(columnIndex == 0); - this.Rows.ClearInternal(false /*recreateNewRow*/); + Rows.ClearInternal(false /*recreateNewRow*/); } // Prepare the existing rows by removing cells at correct index - int newColumnCount = this.Columns.Count - 1; + int newColumnCount = Columns.Count - 1; - for (int rowIndex = 0; rowIndex < this.Rows.Count; rowIndex++) + for (int rowIndex = 0; rowIndex < Rows.Count; rowIndex++) { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); if (dataGridViewRow.Cells.Count > newColumnCount) { dataGridViewRow.Cells.RemoveAtInternal(columnIndex); @@ -17386,29 +17386,29 @@ internal void OnRemovingColumn(DataGridViewColumn dataGridViewColumn, out Point } // Reset sort related variables. - if (dataGridViewColumn == this.sortedColumn) + if (dataGridViewColumn == sortedColumn) { - this.sortedColumn = null; - this.sortOrder = SortOrder.None; + sortedColumn = null; + sortOrder = SortOrder.None; if (dataGridViewColumn.IsDataBound) { // If the column being removed is the sorted column and it is also the dataBound column // then see if there is another dataBound column which has the same property name as the sorted column. // If so, then make that dataGridViewColumn the sorted column in the data grid view. - for (int i = 0; i < this.Columns.Count; i++) + for (int i = 0; i < Columns.Count; i++) { - if (dataGridViewColumn != this.Columns[i] && - this.Columns[i].SortMode != DataGridViewColumnSortMode.NotSortable && + if (dataGridViewColumn != Columns[i] && + Columns[i].SortMode != DataGridViewColumnSortMode.NotSortable && string.Compare(dataGridViewColumn.DataPropertyName, - this.Columns[i].DataPropertyName, + Columns[i].DataPropertyName, true /*ignoreCase*/, CultureInfo.InvariantCulture) == 0) { - Debug.Assert(this.Columns[i].IsDataBound, "two columns w/ the same DataPropertyName should be DataBound at the same time"); - Debug.Assert(this.Columns[i].HeaderCell.SortGlyphDirection == dataGridViewColumn.HeaderCell.SortGlyphDirection, "DataBound columns should have the same SortGlyphDirection as the one on the DataGridView"); - this.sortedColumn = this.Columns[i]; - this.sortOrder = this.Columns[i].HeaderCell.SortGlyphDirection; + Debug.Assert(Columns[i].IsDataBound, "two columns w/ the same DataPropertyName should be DataBound at the same time"); + Debug.Assert(Columns[i].HeaderCell.SortGlyphDirection == dataGridViewColumn.HeaderCell.SortGlyphDirection, "DataBound columns should have the same SortGlyphDirection as the one on the DataGridView"); + sortedColumn = Columns[i]; + sortOrder = Columns[i].HeaderCell.SortGlyphDirection; break; } } @@ -17418,60 +17418,60 @@ internal void OnRemovingColumn(DataGridViewColumn dataGridViewColumn, out Point // Is deleted column scrolled off screen? if (dataGridViewColumn.Visible && !dataGridViewColumn.Frozen && - this.displayedBandsInfo.FirstDisplayedScrollingCol >= 0) + displayedBandsInfo.FirstDisplayedScrollingCol >= 0) { // Deleted column is part of scrolling columns. - if (this.displayedBandsInfo.FirstDisplayedScrollingCol == dataGridViewColumn.Index) + if (displayedBandsInfo.FirstDisplayedScrollingCol == dataGridViewColumn.Index) { // Deleted column is first scrolling column - this.horizontalOffset -= this.negOffset; - this.negOffset = 0; + horizontalOffset -= negOffset; + negOffset = 0; } - else if (this.Columns.DisplayInOrder(this.displayedBandsInfo.FirstDisplayedScrollingCol, dataGridViewColumn.Index)) + else if (Columns.DisplayInOrder(displayedBandsInfo.FirstDisplayedScrollingCol, dataGridViewColumn.Index)) { // Deleted column is displayed after first scrolling column - if (this.horizScrollBar.Enabled) + if (horizScrollBar.Enabled) { - int newHorizontalOffset = this.horizScrollBar.Maximum - this.horizScrollBar.LargeChange - dataGridViewColumn.Thickness; - if (newHorizontalOffset >= 0 && newHorizontalOffset < this.horizScrollBar.Value) + int newHorizontalOffset = horizScrollBar.Maximum - horizScrollBar.LargeChange - dataGridViewColumn.Thickness; + if (newHorizontalOffset >= 0 && newHorizontalOffset < horizScrollBar.Value) { - this.horizontalOffset = newHorizontalOffset; - this.negOffset = GetNegOffsetFromHorizontalOffset(this.horizontalOffset); + horizontalOffset = newHorizontalOffset; + negOffset = GetNegOffsetFromHorizontalOffset(horizontalOffset); } } else { - this.horizontalOffset = this.negOffset = 0; + horizontalOffset = negOffset = 0; } } else { // Deleted column is displayed before first scrolling column - Debug.Assert(this.horizontalOffset >= dataGridViewColumn.Thickness); - this.horizontalOffset -= dataGridViewColumn.Thickness; + Debug.Assert(horizontalOffset >= dataGridViewColumn.Thickness); + horizontalOffset -= dataGridViewColumn.Thickness; } - if (this.horizScrollBar.Enabled) + if (horizScrollBar.Enabled) { - this.horizScrollBar.Value = this.horizontalOffset; + horizScrollBar.Value = horizontalOffset; } } bool raiseSelectionChanged = false; // Update the indexes of selected columns or individual cells to compensate for the removal of this column - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: - int columnEntries = this.selectedBandIndexes.Count; + int columnEntries = selectedBandIndexes.Count; int columnEntry = 0; while (columnEntry < columnEntries) { - int columnIndexSelected = this.selectedBandIndexes[columnEntry]; + int columnIndexSelected = selectedBandIndexes[columnEntry]; if (columnIndex == columnIndexSelected) { - this.selectedBandIndexes.RemoveAt(columnEntry); + selectedBandIndexes.RemoveAt(columnEntry); columnEntries--; raiseSelectionChanged = true; } @@ -17479,7 +17479,7 @@ internal void OnRemovingColumn(DataGridViewColumn dataGridViewColumn, out Point { if (columnIndex < columnIndexSelected) { - this.selectedBandIndexes[columnEntry] = columnIndexSelected - 1; + selectedBandIndexes[columnEntry] = columnIndexSelected - 1; } columnEntry++; } @@ -17487,33 +17487,33 @@ internal void OnRemovingColumn(DataGridViewColumn dataGridViewColumn, out Point break; } - this.dataGridViewState2[DATAGRIDVIEWSTATE2_raiseSelectionChanged] |= this.individualSelectedCells.RemoveAllCellsAtBand(true /*column*/, columnIndex) > 0 || + dataGridViewState2[DATAGRIDVIEWSTATE2_raiseSelectionChanged] |= individualSelectedCells.RemoveAllCellsAtBand(true /*column*/, columnIndex) > 0 || raiseSelectionChanged; - this.individualReadOnlyCells.RemoveAllCellsAtBand(true /*column*/, columnIndex); + individualReadOnlyCells.RemoveAllCellsAtBand(true /*column*/, columnIndex); } internal void OnRemovingRow(int rowIndexDeleted, out Point newCurrentCell, bool force) { // if force is true, the row needs to be deleted no matter what. The underlying data row was already deleted. - Debug.Assert(rowIndexDeleted >= 0 && rowIndexDeleted < this.Rows.Count); + Debug.Assert(rowIndexDeleted >= 0 && rowIndexDeleted < Rows.Count); - this.dataGridViewState1[DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell] = false; + dataGridViewState1[DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell] = false; newCurrentCell = new Point(-1, -1); // Reset the current cell's address if it's on the deleted row, or after it. - if (this.ptCurrentCell.Y != -1 && rowIndexDeleted <= this.ptCurrentCell.Y) + if (ptCurrentCell.Y != -1 && rowIndexDeleted <= ptCurrentCell.Y) { int newY; - if (rowIndexDeleted == this.ptCurrentCell.Y) + if (rowIndexDeleted == ptCurrentCell.Y) { - int rowIndexPrevious = this.Rows.GetPreviousRow(rowIndexDeleted, DataGridViewElementStates.Visible); - int rowIndexNext = this.Rows.GetNextRow(rowIndexDeleted, DataGridViewElementStates.Visible); - if (rowIndexPrevious > -1 && this.AllowUserToAddRowsInternal) + int rowIndexPrevious = Rows.GetPreviousRow(rowIndexDeleted, DataGridViewElementStates.Visible); + int rowIndexNext = Rows.GetNextRow(rowIndexDeleted, DataGridViewElementStates.Visible); + if (rowIndexPrevious > -1 && AllowUserToAddRowsInternal) { - Debug.Assert(this.newRowIndex != -1); - Debug.Assert(this.newRowIndex == this.Rows.Count - 1); - if (rowIndexNext > -1 && rowIndexNext < this.Rows.Count - 1) + Debug.Assert(newRowIndex != -1); + Debug.Assert(newRowIndex == Rows.Count - 1); + if (rowIndexNext > -1 && rowIndexNext < Rows.Count - 1) { newY = rowIndexNext - 1; } @@ -17534,16 +17534,16 @@ internal void OnRemovingRow(int rowIndexDeleted, out Point newCurrentCell, bool } } // Since the current row is deleted, the dirty states need to be reset - this.IsCurrentCellDirtyInternal = false; - this.IsCurrentRowDirtyInternal = false; + IsCurrentCellDirtyInternal = false; + IsCurrentRowDirtyInternal = false; } else { - Debug.Assert(rowIndexDeleted < this.ptCurrentCell.Y); - newY = this.ptCurrentCell.Y - 1; + Debug.Assert(rowIndexDeleted < ptCurrentCell.Y); + newY = ptCurrentCell.Y - 1; } - newCurrentCell = new Point(this.ptCurrentCell.X, newY); - if (rowIndexDeleted == this.ptCurrentCell.Y) + newCurrentCell = new Point(ptCurrentCell.X, newY); + if (rowIndexDeleted == ptCurrentCell.Y) { // Left cell is not validated since cancelling validation wouldn't have any effect anyways. bool success = SetCurrentCellAddressCore(-1, -1, true /*setAnchorCellAddress*/, false /*validateCurrentCell*/, false); @@ -17553,7 +17553,7 @@ internal void OnRemovingRow(int rowIndexDeleted, out Point newCurrentCell, bool { // Underlying data of deleted row is gone. It cannot be accessed anymore. // Do not end editing mode so that CellValidation doesn't get raised, since that event needs the current formatted value. - this.dataGridViewState1[DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell] = true; + dataGridViewState1[DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell] = true; bool success = SetCurrentCellAddressCore(-1, -1, true /*setAnchorCellAddress*/, false /*validateCurrentCell*/, false); Debug.Assert(success); } @@ -17567,47 +17567,47 @@ internal void OnRemovingRow(int rowIndexDeleted, out Point newCurrentCell, bool bool raiseSelectionChanged = false; // Update the indexes of selected rows to compensate for the removal of this row - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: - int rowEntries = this.selectedBandIndexes.Count; + int rowEntries = selectedBandIndexes.Count; int rowEntry = 0; while (rowEntry < rowEntries) { - int rowIndex = this.selectedBandIndexes[rowEntry]; + int rowIndex = selectedBandIndexes[rowEntry]; if (rowIndexDeleted == rowIndex) { raiseSelectionChanged = true; - this.selectedBandIndexes.RemoveAt(rowEntry); + selectedBandIndexes.RemoveAt(rowEntry); rowEntries--; } else { if (rowIndexDeleted < rowIndex) { - this.selectedBandIndexes[rowEntry] = rowIndex - 1; + selectedBandIndexes[rowEntry] = rowIndex - 1; } rowEntry++; } } - if (this.selectedBandSnapshotIndexes != null) + if (selectedBandSnapshotIndexes != null) { - rowEntries = this.selectedBandSnapshotIndexes.Count; + rowEntries = selectedBandSnapshotIndexes.Count; rowEntry = 0; while (rowEntry < rowEntries) { - int rowIndex = this.selectedBandSnapshotIndexes[rowEntry]; + int rowIndex = selectedBandSnapshotIndexes[rowEntry]; if (rowIndexDeleted == rowIndex) { - this.selectedBandSnapshotIndexes.RemoveAt(rowEntry); + selectedBandSnapshotIndexes.RemoveAt(rowEntry); rowEntries--; } else { if (rowIndexDeleted < rowIndex) { - this.selectedBandSnapshotIndexes[rowEntry] = rowIndex - 1; + selectedBandSnapshotIndexes[rowEntry] = rowIndex - 1; } rowEntry++; } @@ -17616,74 +17616,74 @@ internal void OnRemovingRow(int rowIndexDeleted, out Point newCurrentCell, bool break; } - this.dataGridViewState2[DATAGRIDVIEWSTATE2_raiseSelectionChanged] |= this.individualSelectedCells.RemoveAllCellsAtBand(false /*column*/, rowIndexDeleted) > 0 || + dataGridViewState2[DATAGRIDVIEWSTATE2_raiseSelectionChanged] |= individualSelectedCells.RemoveAllCellsAtBand(false /*column*/, rowIndexDeleted) > 0 || raiseSelectionChanged; - this.individualReadOnlyCells.RemoveAllCellsAtBand(false /*column*/, rowIndexDeleted); + individualReadOnlyCells.RemoveAllCellsAtBand(false /*column*/, rowIndexDeleted); } internal void OnReplacedCell(DataGridViewRow dataGridViewRow, int columnIndex) { DataGridViewCell dataGridViewCell = dataGridViewRow.Cells[columnIndex]; - if (this.dataGridViewState2[DATAGRIDVIEWSTATE2_replacedCellSelected]) + if (dataGridViewState2[DATAGRIDVIEWSTATE2_replacedCellSelected]) { - this.individualSelectedCells.Add(dataGridViewCell); + individualSelectedCells.Add(dataGridViewCell); } - if (this.dataGridViewState2[DATAGRIDVIEWSTATE2_replacedCellReadOnly]) + if (dataGridViewState2[DATAGRIDVIEWSTATE2_replacedCellReadOnly]) { - this.individualReadOnlyCells.Add(dataGridViewCell); + individualReadOnlyCells.Add(dataGridViewCell); } // AutoSize column and row if needed OnCellCommonChange(columnIndex, dataGridViewRow.Index); - if (this.ptCurrentCellCache.X != -1) + if (ptCurrentCellCache.X != -1) { - if (!IsInnerCellOutOfBounds(this.ptCurrentCellCache.X, this.ptCurrentCellCache.Y)) + if (!IsInnerCellOutOfBounds(ptCurrentCellCache.X, ptCurrentCellCache.Y)) { - SetCurrentCellAddressCore(this.ptCurrentCellCache.X, this.ptCurrentCellCache.Y, false, false, false); + SetCurrentCellAddressCore(ptCurrentCellCache.X, ptCurrentCellCache.Y, false, false, false); } - this.ptCurrentCellCache.X = -1; - this.ptCurrentCellCache.Y = -1; + ptCurrentCellCache.X = -1; + ptCurrentCellCache.Y = -1; } } internal void OnReplacingCell(DataGridViewRow dataGridViewRow, int columnIndex) { - if (this.ptCurrentCell.X == dataGridViewRow.Index && - this.ptCurrentCell.Y == columnIndex) + if (ptCurrentCell.X == dataGridViewRow.Index && + ptCurrentCell.Y == columnIndex) { // Trying to replace the current cell. Exiting editing mode first (if needed). // Remember to reset the current cell in OnReplacedCell notification - this.ptCurrentCellCache.X = this.ptCurrentCell.X; - this.ptCurrentCellCache.Y = this.ptCurrentCell.Y; + ptCurrentCellCache.X = ptCurrentCell.X; + ptCurrentCellCache.Y = ptCurrentCell.Y; // This may fail and throw an exception ResetCurrentCell(); } else { - this.ptCurrentCellCache.X = -1; - this.ptCurrentCellCache.Y = -1; + ptCurrentCellCache.X = -1; + ptCurrentCellCache.Y = -1; } DataGridViewCell dataGridViewCell = dataGridViewRow.Cells[columnIndex]; - this.dataGridViewState2[DATAGRIDVIEWSTATE2_replacedCellSelected] = this.individualSelectedCells.Contains(dataGridViewCell); - if (this.dataGridViewState2[DATAGRIDVIEWSTATE2_replacedCellSelected]) + dataGridViewState2[DATAGRIDVIEWSTATE2_replacedCellSelected] = individualSelectedCells.Contains(dataGridViewCell); + if (dataGridViewState2[DATAGRIDVIEWSTATE2_replacedCellSelected]) { - this.individualSelectedCells.Remove(dataGridViewCell); + individualSelectedCells.Remove(dataGridViewCell); } - this.dataGridViewState2[DATAGRIDVIEWSTATE2_replacedCellReadOnly] = this.individualReadOnlyCells.Contains(dataGridViewCell); - if (this.dataGridViewState2[DATAGRIDVIEWSTATE2_replacedCellReadOnly]) + dataGridViewState2[DATAGRIDVIEWSTATE2_replacedCellReadOnly] = individualReadOnlyCells.Contains(dataGridViewCell); + if (dataGridViewState2[DATAGRIDVIEWSTATE2_replacedCellReadOnly]) { - this.individualReadOnlyCells.Remove(dataGridViewCell); + individualReadOnlyCells.Remove(dataGridViewCell); } } protected override void OnResize(EventArgs e) { - int borderWidth = this.BorderWidth; + int borderWidth = BorderWidth; Rectangle right; Rectangle bottom; - Rectangle oldClientRectangle = this.layout.ClientRectangle; - Rectangle oldGridFocusRectangle = this.GetGridFocusRectangle(); + Rectangle oldClientRectangle = layout.ClientRectangle; + Rectangle oldGridFocusRectangle = GetGridFocusRectangle(); right = new Rectangle(oldClientRectangle.X + oldClientRectangle.Width - borderWidth, oldClientRectangle.Y, @@ -17694,14 +17694,14 @@ protected override void OnResize(EventArgs e) oldClientRectangle.Width, borderWidth); - if (!this.IsMinimized) + if (!IsMinimized) { // When owning form is minimized, act as if it had a normal size - this.normalClientRectangle = this.ClientRectangle; + normalClientRectangle = ClientRectangle; } - Rectangle newClientRectangle = this.normalClientRectangle; - Rectangle newGridFocusRectangle = this.DisplayRectangle; + Rectangle newClientRectangle = normalClientRectangle; + Rectangle newGridFocusRectangle = DisplayRectangle; newGridFocusRectangle.Inflate(1 - borderWidth - FOCUS_RECT_OFFSET, 1 - borderWidth - FOCUS_RECT_OFFSET); if (newClientRectangle.Width != oldClientRectangle.Width) @@ -17724,7 +17724,7 @@ protected override void OnResize(EventArgs e) } // Invalidate grid focus rectangle - if (this.Focused && this.IsGridFocusRectangleEnabled() && oldGridFocusRectangle != newGridFocusRectangle) + if (Focused && IsGridFocusRectangleEnabled() && oldGridFocusRectangle != newGridFocusRectangle) { right = new Rectangle(oldGridFocusRectangle.X + oldGridFocusRectangle.Width - 1, oldGridFocusRectangle.Y, @@ -17742,15 +17742,15 @@ protected override void OnResize(EventArgs e) } //also, invalidate the ResizeBoxRect - if (!this.layout.ResizeBoxRect.IsEmpty) + if (!layout.ResizeBoxRect.IsEmpty) { - Invalidate(this.layout.ResizeBoxRect); + Invalidate(layout.ResizeBoxRect); } - this.layout.ClientRectangle = newClientRectangle; + layout.ClientRectangle = newClientRectangle; - int oldfirstDisplayedScrollingRow = this.displayedBandsInfo.FirstDisplayedScrollingRow; + int oldfirstDisplayedScrollingRow = displayedBandsInfo.FirstDisplayedScrollingRow; base.OnResize(e); - if (oldfirstDisplayedScrollingRow != this.displayedBandsInfo.FirstDisplayedScrollingRow) + if (oldfirstDisplayedScrollingRow != displayedBandsInfo.FirstDisplayedScrollingRow) { Invalidate(); } @@ -17758,7 +17758,7 @@ protected override void OnResize(EventArgs e) protected override void OnRightToLeftChanged(EventArgs e) { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_rightToLeftValid] = false; + dataGridViewState2[DATAGRIDVIEWSTATE2_rightToLeftValid] = false; base.OnRightToLeftChanged(e); CorrectFocus(true /*onlyIfGridHasFocus*/); PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); @@ -17772,9 +17772,9 @@ internal void OnRowCollectionChanged_PostNotification(bool recreateNewRow, { if (recreateNewRow && cca == CollectionChangeAction.Refresh && - this.Columns.Count != 0 && - this.Rows.Count == 0 && - this.AllowUserToAddRowsInternal) + Columns.Count != 0 && + Rows.Count == 0 && + AllowUserToAddRowsInternal) { AddNewRow(false); } @@ -17785,19 +17785,19 @@ internal void OnRowCollectionChanged_PostNotification(bool recreateNewRow, } if ((cca == CollectionChangeAction.Refresh || cca == CollectionChangeAction.Add) && - this.ptCurrentCell.X == -1 && allowSettingCurrentCell && !this.InSortOperation) + ptCurrentCell.X == -1 && allowSettingCurrentCell && !InSortOperation) { MakeFirstDisplayedCellCurrentCell(false /*includeNewRow*/); } - if (this.AutoSize) + if (AutoSize) { bool invalidatePreferredSizeCache = true; switch (cca) { case CollectionChangeAction.Add: Debug.Assert(rowIndex >= 0); - DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); + DataGridViewElementStates rowState = Rows.GetRowState(rowIndex); invalidatePreferredSizeCache = ((rowState & DataGridViewElementStates.Visible) != 0); break; case CollectionChangeAction.Remove: @@ -17807,7 +17807,7 @@ internal void OnRowCollectionChanged_PostNotification(bool recreateNewRow, } if (invalidatePreferredSizeCache) { - LayoutTransaction.DoLayout(this.ParentInternal, this, PropertyNames.Rows); + LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.Rows); } } } @@ -17818,8 +17818,8 @@ protected virtual void OnRowContextMenuStripChanged(DataGridViewRowEventArgs e) { throw new ArgumentException(string.Format(SR.DataGridView_RowDoesNotBelongToDataGridView), "e.Row"); } - DataGridViewRowEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWCONTEXTMENUSTRIPCHANGED] as DataGridViewRowEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWROWCONTEXTMENUSTRIPCHANGED] as DataGridViewRowEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -17834,8 +17834,8 @@ internal ContextMenuStrip OnRowContextMenuStripNeeded(int rowIndex, ContextMenuS protected virtual void OnRowContextMenuStripNeeded(DataGridViewRowContextMenuStripNeededEventArgs e) { - DataGridViewRowContextMenuStripNeededEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWCONTEXTMENUSTRIPNEEDED] as DataGridViewRowContextMenuStripNeededEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowContextMenuStripNeededEventHandler eh = Events[EVENT_DATAGRIDVIEWROWCONTEXTMENUSTRIPNEEDED] as DataGridViewRowContextMenuStripNeededEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -17850,8 +17850,8 @@ protected virtual void OnRowDefaultCellStyleChanged(DataGridViewRowEventArgs e) OnRowGlobalAutoSize(e.Row.Index); - DataGridViewRowEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWDEFAULTCELLSTYLECHANGED] as DataGridViewRowEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWROWDEFAULTCELLSTYLECHANGED] as DataGridViewRowEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -17859,8 +17859,8 @@ protected virtual void OnRowDefaultCellStyleChanged(DataGridViewRowEventArgs e) protected virtual void OnRowDirtyStateNeeded(QuestionEventArgs e) { - QuestionEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWDIRTYSTATENEEDED] as QuestionEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + QuestionEventHandler eh = Events[EVENT_DATAGRIDVIEWROWDIRTYSTATENEEDED] as QuestionEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -17868,13 +17868,13 @@ protected virtual void OnRowDirtyStateNeeded(QuestionEventArgs e) protected virtual void OnRowDividerDoubleClick(DataGridViewRowDividerDoubleClickEventArgs e) { - DataGridViewRowDividerDoubleClickEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWDIVIDERDOUBLECLICK] as DataGridViewRowDividerDoubleClickEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowDividerDoubleClickEventHandler eh = Events[EVENT_DATAGRIDVIEWROWDIVIDERDOUBLECLICK] as DataGridViewRowDividerDoubleClickEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } - if (!e.Handled && e.Button == MouseButtons.Left && e.RowIndex < this.Rows.Count) + if (!e.Handled && e.Button == MouseButtons.Left && e.RowIndex < Rows.Count) { if (e.RowIndex == -1) { @@ -17882,13 +17882,13 @@ protected virtual void OnRowDividerDoubleClick(DataGridViewRowDividerDoubleClick } else { - if (this.autoSizeRowsMode == DataGridViewAutoSizeRowsMode.None) + if (autoSizeRowsMode == DataGridViewAutoSizeRowsMode.None) { AutoResizeRowInternal(e.RowIndex, DataGridViewAutoSizeRowMode.AllCells, true /*fixedWidth*/, true /*internalAutosizing*/); } else { - AutoResizeRowInternal(e.RowIndex, MapAutoSizeRowsModeToRowMode(this.autoSizeRowsMode), true /*fixedWidth*/, true /*internalAutosizing*/); + AutoResizeRowInternal(e.RowIndex, MapAutoSizeRowsModeToRowMode(autoSizeRowsMode), true /*fixedWidth*/, true /*internalAutosizing*/); } } } @@ -17903,8 +17903,8 @@ protected virtual void OnRowDividerHeightChanged(DataGridViewRowEventArgs e) OnRowGlobalAutoSize(e.Row.Index); - DataGridViewRowEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWDIVIDERHEIGHTCHANGED] as DataGridViewRowEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWROWDIVIDERHEIGHTCHANGED] as DataGridViewRowEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -17916,27 +17916,27 @@ private void OnRowEnter(ref DataGridViewCell dataGridViewCell, int columnIndex, if (!validationFailureOccurred) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_newRowEdited] = false; + dataGridViewState1[DATAGRIDVIEWSTATE1_newRowEdited] = false; } - if (rowIndex < this.Rows.Count && - columnIndex < this.Columns.Count) + if (rowIndex < Rows.Count && + columnIndex < Columns.Count) { bool calledAddNewOnTheDataConnection = false; - if (!validationFailureOccurred && this.AllowUserToAddRowsInternal && this.newRowIndex == rowIndex) + if (!validationFailureOccurred && AllowUserToAddRowsInternal && newRowIndex == rowIndex) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_newRowEdited] = true; + dataGridViewState1[DATAGRIDVIEWSTATE1_newRowEdited] = true; if (canCreateNewRow) { - DataGridViewRowEventArgs dgvre = new DataGridViewRowEventArgs(this.Rows[this.newRowIndex]); - if (this.VirtualMode || this.DataSource != null) + DataGridViewRowEventArgs dgvre = new DataGridViewRowEventArgs(Rows[newRowIndex]); + if (VirtualMode || DataSource != null) { - if (this.dataConnection != null && this.dataConnection.InterestedInRowEvents) + if (dataConnection != null && dataConnection.InterestedInRowEvents) { - this.dataConnection.OnNewRowNeeded(); + dataConnection.OnNewRowNeeded(); calledAddNewOnTheDataConnection = true; } - if (this.VirtualMode) + if (VirtualMode) { OnNewRowNeeded(dgvre); } @@ -17945,36 +17945,36 @@ private void OnRowEnter(ref DataGridViewCell dataGridViewCell, int columnIndex, // AllowUserToAddRowsInternal can become FALSE while adding a row. // NOTE: we don't need to invalidate if AllowUserToAddRowsInternal changed to FALSE. // - if (this.AllowUserToAddRowsInternal) + if (AllowUserToAddRowsInternal) { OnDefaultValuesNeeded(dgvre); - InvalidateRowPrivate(this.newRowIndex); + InvalidateRowPrivate(newRowIndex); } #if DEBUG else { - Debug.Assert(this.newRowIndex == -1, "newRowIndex and AllowUserToAddRowsInternal became out of sync"); + Debug.Assert(newRowIndex == -1, "newRowIndex and AllowUserToAddRowsInternal became out of sync"); } #endif // } } - if (calledAddNewOnTheDataConnection && rowIndex > this.Rows.Count - 1) + if (calledAddNewOnTheDataConnection && rowIndex > Rows.Count - 1) { // Calling AddNew on the DataConnection can result in the entire list being wiped out. // - rowIndex = Math.Min(rowIndex, this.Rows.Count - 1); + rowIndex = Math.Min(rowIndex, Rows.Count - 1); } DataGridViewCellEventArgs dgvce = new DataGridViewCellEventArgs(columnIndex, rowIndex); OnRowEnter(dgvce); - if (this.dataConnection != null && - this.dataConnection.InterestedInRowEvents && - !this.dataConnection.PositionChangingOutsideDataGridView && - !this.dataConnection.ListWasReset && - (!calledAddNewOnTheDataConnection || this.dataConnection.List.Count > 0)) + if (dataConnection != null && + dataConnection.InterestedInRowEvents && + !dataConnection.PositionChangingOutsideDataGridView && + !dataConnection.ListWasReset && + (!calledAddNewOnTheDataConnection || dataConnection.List.Count > 0)) { - this.dataConnection.OnRowEnter(dgvce); + dataConnection.OnRowEnter(dgvce); } if (dataGridViewCell != null) @@ -17985,8 +17985,8 @@ private void OnRowEnter(ref DataGridViewCell dataGridViewCell, int columnIndex, } else { - Debug.Assert(rowIndex < this.Rows.Count && columnIndex < this.Columns.Count); - dataGridViewCell = this.Rows.SharedRow(rowIndex).Cells[columnIndex]; + Debug.Assert(rowIndex < Rows.Count && columnIndex < Columns.Count); + dataGridViewCell = Rows.SharedRow(rowIndex).Cells[columnIndex]; } } } @@ -17996,10 +17996,10 @@ protected virtual void OnRowEnter(DataGridViewCellEventArgs e) { try { - this.noDimensionChangeCount++; + noDimensionChangeCount++; - DataGridViewCellEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWENTER] as DataGridViewCellEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWROWENTER] as DataGridViewCellEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); CorrectFocus(true /*onlyIfGridHasFocus*/); @@ -18007,8 +18007,8 @@ protected virtual void OnRowEnter(DataGridViewCellEventArgs e) } finally { - this.noDimensionChangeCount--; - Debug.Assert(this.noDimensionChangeCount >= 0); + noDimensionChangeCount--; + Debug.Assert(noDimensionChangeCount >= 0); } } @@ -18026,8 +18026,8 @@ protected virtual void OnRowErrorTextChanged(DataGridViewRowEventArgs e) } UpdateRowErrorText(e.Row.Index); - DataGridViewRowEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWERRORTEXTCHANGED] as DataGridViewRowEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWROWERRORTEXTCHANGED] as DataGridViewRowEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18043,8 +18043,8 @@ internal string OnRowErrorTextNeeded(int rowIndex, string errorText) protected virtual void OnRowErrorTextNeeded(DataGridViewRowErrorTextNeededEventArgs e) { - DataGridViewRowErrorTextNeededEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWERRORTEXTNEEDED] as DataGridViewRowErrorTextNeededEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowErrorTextNeededEventHandler eh = Events[EVENT_DATAGRIDVIEWROWERRORTEXTNEEDED] as DataGridViewRowErrorTextNeededEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18052,7 +18052,7 @@ protected virtual void OnRowErrorTextNeeded(DataGridViewRowErrorTextNeededEventA private void OnRowGlobalAutoSize(int rowIndex) { - DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); + DataGridViewElementStates rowState = Rows.GetRowState(rowIndex); if ((rowState & DataGridViewElementStates.Visible) == 0) { return; @@ -18060,18 +18060,18 @@ private void OnRowGlobalAutoSize(int rowIndex) InvalidateRowPrivate(rowIndex); - if (this.noAutoSizeCount > 0) + if (noAutoSizeCount > 0) { return; } - DataGridViewAutoSizeRowsModeInternal autoSizeRowsModeInternal = (DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode; + DataGridViewAutoSizeRowsModeInternal autoSizeRowsModeInternal = (DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode; bool autoSizeRow = false; bool rowDisplayed = (rowState & DataGridViewElementStates.Displayed) != 0; if (autoSizeRowsModeInternal != DataGridViewAutoSizeRowsModeInternal.None && !((autoSizeRowsModeInternal & DataGridViewAutoSizeRowsModeInternal.DisplayedRows) != 0 && !rowDisplayed)) { - AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(this.autoSizeRowsMode), false /*fixedWidth*/, true /*internalAutosizing*/); + AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(autoSizeRowsMode), false /*fixedWidth*/, true /*internalAutosizing*/); autoSizeRow = true; } @@ -18083,10 +18083,10 @@ private void OnRowGlobalAutoSize(int rowIndex) } AutoResizeAllVisibleColumnsInternal(autoSizeColumnCriteriaFilter, true /*fixedHeight*/); - bool fixedRowHeadersWidth = this.rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing || - this.rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.DisableResizing; + bool fixedRowHeadersWidth = rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing || + rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.DisableResizing; // Auto size column headers - if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) + if (ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) { AutoResizeColumnHeadersHeight(fixedRowHeadersWidth, true /*fixedColumnsWidth*/); } @@ -18094,16 +18094,16 @@ private void OnRowGlobalAutoSize(int rowIndex) // Auto size row headers if (!fixedRowHeadersWidth) { - AutoResizeRowHeadersWidth(this.rowHeadersWidthSizeMode, true /*fixedColumnHeadersHeight*/, true /*fixedRowsHeight*/); + AutoResizeRowHeadersWidth(rowHeadersWidthSizeMode, true /*fixedColumnHeadersHeight*/, true /*fixedRowsHeight*/); } if (autoSizeRow) { // Second round of row autosizing - AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(this.autoSizeRowsMode), true /*fixedWidth*/, true /*internalAutosizing*/); + AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(autoSizeRowsMode), true /*fixedWidth*/, true /*internalAutosizing*/); } - if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize && !fixedRowHeadersWidth) + if (ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize && !fixedRowHeadersWidth) { // Second round of column headers autosizing AutoResizeColumnHeadersHeight(true /*fixedRowHeadersWidth*/, true /*fixedColumnsWidth*/); @@ -18119,8 +18119,8 @@ protected virtual void OnRowHeaderCellChanged(DataGridViewRowEventArgs e) OnRowHeaderGlobalAutoSize(e.Row.Index); - DataGridViewRowEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWHEADERCELLCHANGED] as DataGridViewRowEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWROWHEADERCELLCHANGED] as DataGridViewRowEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18128,14 +18128,14 @@ protected virtual void OnRowHeaderCellChanged(DataGridViewRowEventArgs e) private void OnRowHeaderGlobalAutoSize(int rowIndex) { - if (!this.RowHeadersVisible) + if (!RowHeadersVisible) { return; } InvalidateCellPrivate(-1, rowIndex); - if (this.noAutoSizeCount > 0) + if (noAutoSizeCount > 0) { return; } @@ -18143,22 +18143,22 @@ private void OnRowHeaderGlobalAutoSize(int rowIndex) bool rowDisplayed = false; if (rowIndex != -1) { - rowDisplayed = (this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Displayed) != 0; + rowDisplayed = (Rows.GetRowState(rowIndex) & DataGridViewElementStates.Displayed) != 0; } - bool fixedColumnHeadersHeight = rowIndex != -1 || this.ColumnHeadersHeightSizeMode != DataGridViewColumnHeadersHeightSizeMode.AutoSize; + bool fixedColumnHeadersHeight = rowIndex != -1 || ColumnHeadersHeightSizeMode != DataGridViewColumnHeadersHeightSizeMode.AutoSize; bool fixedRowHeight = rowIndex == -1 || - ((((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) == 0) || - ((((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.DisplayedRows) != 0 && rowIndex != -1 && !rowDisplayed); + ((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) == 0) || + ((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.DisplayedRows) != 0 && rowIndex != -1 && !rowDisplayed); bool autoSizeRowHeaders = false; - if (this.rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders || - (this.rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders && rowIndex != -1 && rowDisplayed) || - (this.rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.EnableResizing && this.rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.DisableResizing && rowIndex == -1) || - (this.rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.AutoSizeToFirstHeader && rowIndex != -1 && rowIndex == this.Rows.GetFirstRow(DataGridViewElementStates.Visible))) + if (rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders || + (rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders && rowIndex != -1 && rowDisplayed) || + (rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.EnableResizing && rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.DisableResizing && rowIndex == -1) || + (rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.AutoSizeToFirstHeader && rowIndex != -1 && rowIndex == Rows.GetFirstRow(DataGridViewElementStates.Visible))) { AutoResizeRowHeadersWidth(rowIndex, - this.rowHeadersWidthSizeMode, + rowHeadersWidthSizeMode, fixedColumnHeadersHeight, fixedRowHeight); autoSizeRowHeaders = true; @@ -18169,14 +18169,14 @@ private void OnRowHeaderGlobalAutoSize(int rowIndex) } if (!fixedRowHeight) { - AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(this.autoSizeRowsMode), true /*fixedWidth*/, true /*internalAutosizing*/); + AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(autoSizeRowsMode), true /*fixedWidth*/, true /*internalAutosizing*/); } if (autoSizeRowHeaders && (!fixedColumnHeadersHeight || !fixedRowHeight)) { // Second round of row headers autosizing AutoResizeRowHeadersWidth(rowIndex, - this.rowHeadersWidthSizeMode, + rowHeadersWidthSizeMode, true /*fixedColumnHeadersHeight*/, true /*fixedRowHeight*/); } @@ -18184,8 +18184,8 @@ private void OnRowHeaderGlobalAutoSize(int rowIndex) protected virtual void OnRowHeaderMouseClick(DataGridViewCellMouseEventArgs e) { - DataGridViewCellMouseEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWHEADERMOUSECLICK] as DataGridViewCellMouseEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellMouseEventHandler eh = Events[EVENT_DATAGRIDVIEWROWHEADERMOUSECLICK] as DataGridViewCellMouseEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18193,8 +18193,8 @@ protected virtual void OnRowHeaderMouseClick(DataGridViewCellMouseEventArgs e) protected virtual void OnRowHeaderMouseDoubleClick(DataGridViewCellMouseEventArgs e) { - DataGridViewCellMouseEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWHEADERMOUSEDOUBLECLICK] as DataGridViewCellMouseEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellMouseEventHandler eh = Events[EVENT_DATAGRIDVIEWROWHEADERMOUSEDOUBLECLICK] as DataGridViewCellMouseEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18203,10 +18203,10 @@ protected virtual void OnRowHeaderMouseDoubleClick(DataGridViewCellMouseEventArg private void OnRowHeaderMouseDown(HitTestInfo hti, bool isShiftDown, bool isControlDown) { Debug.Assert(hti.Type == DataGridViewHitTestType.RowHeader); - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: case DataGridViewSelectionMode.FullColumnSelect: @@ -18218,26 +18218,26 @@ private void OnRowHeaderMouseDown(HitTestInfo hti, bool isShiftDown, bool isCont { bool select = true; if (isControlDown && - ((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) != 0)) + ((Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) != 0)) { select = false; } if (select) { - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); - if (dataGridViewColumn != null && hti.row != this.ptCurrentCell.Y) + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); + if (dataGridViewColumn != null && hti.row != ptCurrentCell.Y) { - int oldCurrentCellX = this.ptCurrentCell.X; - int oldCurrentCellY = this.ptCurrentCell.Y; + int oldCurrentCellX = ptCurrentCell.X; + int oldCurrentCellY = ptCurrentCell.Y; // Make sure we will be able to scroll into view if (!EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.CurrentCellChange, DataGridViewValidateCellInternal.Always /*validateCell*/, true /*fireCellLeave*/, true /*fireCellEnter*/, - hti.row != this.ptCurrentCell.Y /*fireRowLeave*/, - hti.row != this.ptCurrentCell.Y /*fireRowEnter*/, + hti.row != ptCurrentCell.Y /*fireRowLeave*/, + hti.row != ptCurrentCell.Y /*fireRowEnter*/, false /*fireLeave*/, - this.EditMode != DataGridViewEditMode.EditOnEnter /*keepFocus*/, + EditMode != DataGridViewEditMode.EditOnEnter /*keepFocus*/, true /*resetCurrentCell*/, false /*resetAnchorCell*/)) { @@ -18273,10 +18273,10 @@ private void OnRowHeaderMouseDown(HitTestInfo hti, bool isShiftDown, bool isCont OnRowValidated(ref dataGridViewCellTmp, oldCurrentCellX, oldCurrentCellY); // Row validation was not cancelled, but operation needs to be re-evaluated. - if (hti.row >= this.Rows.Count) + if (hti.row >= Rows.Count) { - int lastVisibleRowIndex = this.Rows.GetLastRow(DataGridViewElementStates.Visible); - if (this.ptCurrentCell.X == -1 && lastVisibleRowIndex != -1) + int lastVisibleRowIndex = Rows.GetLastRow(DataGridViewElementStates.Visible); + if (ptCurrentCell.X == -1 && lastVisibleRowIndex != -1) { // CurrentCell was reset because commit deleted row(s). // Since the user wants to select a row, we don't want to @@ -18297,40 +18297,40 @@ private void OnRowHeaderMouseDown(HitTestInfo hti, bool isShiftDown, bool isCont } return; } - else if ((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Visible) == 0) + else if ((Rows.GetRowState(hti.row) & DataGridViewElementStates.Visible) == 0) { return; } } } bool selectRowRange = false; - this.trackRow = hti.row; - this.trackRowEdge = -1; - if (this.MultiSelect && + trackRow = hti.row; + trackRowEdge = -1; + if (MultiSelect && isShiftDown && - this.ptAnchorCell.Y > -1 && - (this.Rows.GetRowState(this.ptAnchorCell.Y) & DataGridViewElementStates.Selected) != 0) + ptAnchorCell.Y > -1 && + (Rows.GetRowState(ptAnchorCell.Y) & DataGridViewElementStates.Selected) != 0) { selectRowRange = true; } - if (!this.MultiSelect || !isControlDown || isShiftDown) + if (!MultiSelect || !isControlDown || isShiftDown) { - Debug.Assert(this.MultiSelect || this.selectedBandIndexes.Count <= 1); + Debug.Assert(MultiSelect || selectedBandIndexes.Count <= 1); int bandIndex = 0; bool switchedToBulkPaint = false; - if (this.selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) + if (selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) { - this.inBulkPaintCount++; + inBulkPaintCount++; switchedToBulkPaint = true; } try { - while (bandIndex < this.selectedBandIndexes.Count) + while (bandIndex < selectedBandIndexes.Count) { - if (this.selectedBandIndexes[bandIndex] != hti.row) + if (selectedBandIndexes[bandIndex] != hti.row) { // deselect currently selected row - SetSelectedRowCore(this.selectedBandIndexes[bandIndex], false); + SetSelectedRowCore(selectedBandIndexes[bandIndex], false); } else { @@ -18338,13 +18338,13 @@ private void OnRowHeaderMouseDown(HitTestInfo hti, bool isShiftDown, bool isCont } } - if (this.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) + if (SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) { RemoveIndividuallySelectedCells(); } else { - Debug.Assert(this.individualSelectedCells.Count == 0); + Debug.Assert(individualSelectedCells.Count == 0); } } finally @@ -18355,30 +18355,30 @@ private void OnRowHeaderMouseDown(HitTestInfo hti, bool isShiftDown, bool isCont } } } - if (this.MultiSelect && this.dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) + if (MultiSelect && dataGridViewOper[DATAGRIDVIEWOPER_trackMouseMoves]) { - this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] = true; + dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] = true; } if (selectRowRange) { - if (hti.row >= this.ptAnchorCell.Y) + if (hti.row >= ptAnchorCell.Y) { - SelectRowRange(this.ptAnchorCell.Y, hti.row, true); + SelectRowRange(ptAnchorCell.Y, hti.row, true); } else { - SelectRowRange(hti.row, this.ptAnchorCell.Y, true); + SelectRowRange(hti.row, ptAnchorCell.Y, true); } } - else if ((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) == 0) + else if ((Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) == 0) { - Debug.Assert(this.selectedBandIndexes.Contains(hti.row) == - ((this.Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) != 0)); + Debug.Assert(selectedBandIndexes.Contains(hti.row) == + ((Rows.GetRowState(hti.row) & DataGridViewElementStates.Selected) != 0)); SetSelectedRowCore(hti.row, true); } if (dataGridViewColumn != null) { - if (hti.row != this.ptCurrentCell.Y) + if (hti.row != ptCurrentCell.Y) { if (IsInnerCellOutOfBounds(dataGridViewColumn.Index, hti.row)) { @@ -18394,10 +18394,10 @@ private void OnRowHeaderMouseDown(HitTestInfo hti, bool isShiftDown, bool isCont success = SetCurrentCellAddressCore(dataGridViewColumn.Index, hti.row, !selectRowRange, false, true); Debug.Assert(success); } - else if (-1 != this.ptCurrentCell.Y) + else if (-1 != ptCurrentCell.Y) { // Potentially have to give focus back to the current edited cell. - bool success = SetCurrentCellAddressCore(this.ptCurrentCell.X, this.ptCurrentCell.Y, + bool success = SetCurrentCellAddressCore(ptCurrentCell.X, ptCurrentCell.Y, false /*setAnchorCellAddress*/, false /*validateCurrentCell*/, false /*throughMouseClick*/); @@ -18406,12 +18406,12 @@ private void OnRowHeaderMouseDown(HitTestInfo hti, bool isShiftDown, bool isCont } else { - Debug.Assert(this.CurrentCellAddress == new Point(-1, -1)); + Debug.Assert(CurrentCellAddress == new Point(-1, -1)); } } else { - Debug.Assert(this.selectedBandIndexes.Contains(hti.row)); + Debug.Assert(selectedBandIndexes.Contains(hti.row)); SetSelectedRowCore(hti.row, false); } break; @@ -18420,7 +18420,7 @@ private void OnRowHeaderMouseDown(HitTestInfo hti, bool isShiftDown, bool isCont } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; } } @@ -18429,8 +18429,8 @@ protected virtual void OnRowHeadersBorderStyleChanged(EventArgs e) PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); Invalidate(); - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWHEADERSBORDERSTYLECHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWROWHEADERSBORDERSTYLECHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18438,23 +18438,23 @@ protected virtual void OnRowHeadersBorderStyleChanged(EventArgs e) protected virtual void OnRowHeadersDefaultCellStyleChanged(EventArgs e) { - if (this.RowHeadersVisible) + if (RowHeadersVisible) { - Invalidate(Rectangle.Union(this.layout.TopLeftHeader, this.layout.RowHeaders)); + Invalidate(Rectangle.Union(layout.TopLeftHeader, layout.RowHeaders)); DataGridViewCellStyleChangedEventArgs dgvcsce = e as DataGridViewCellStyleChangedEventArgs; if (dgvcsce == null || dgvcsce.ChangeAffectsPreferredSize) { OnRowHeadersGlobalAutoSize(false /*expandingRows*/); - if (this.editingControl != null) + if (editingControl != null) { PositionEditingControl(true /*setLocation*/, true /*setSize*/, false /*setFocus*/); } } } - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWHEADERSDEFAULTCELLSTYLECHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWROWHEADERSDEFAULTCELLSTYLECHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18462,18 +18462,18 @@ protected virtual void OnRowHeadersDefaultCellStyleChanged(EventArgs e) private void OnRowHeadersGlobalAutoSize(bool expandingRows) { - if (this.noAutoSizeCount > 0) + if (noAutoSizeCount > 0) { return; } - bool fixedRowsHeight = (((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) == 0 || - !this.RowHeadersVisible; - bool autoSizeRowHeaders = this.rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.EnableResizing && - this.rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.DisableResizing; + bool fixedRowsHeight = (((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.Header) == 0 || + !RowHeadersVisible; + bool autoSizeRowHeaders = rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.EnableResizing && + rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.DisableResizing; if (autoSizeRowHeaders) { - AutoResizeRowHeadersWidth(this.rowHeadersWidthSizeMode, true /*fixedColumnHeadersHeight*/, fixedRowsHeight); + AutoResizeRowHeadersWidth(rowHeadersWidthSizeMode, true /*fixedColumnHeadersHeight*/, fixedRowsHeight); } if (!fixedRowsHeight) @@ -18484,27 +18484,27 @@ private void OnRowHeadersGlobalAutoSize(bool expandingRows) } else { - AdjustShrinkingRows(this.autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); + AdjustShrinkingRows(autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); } if (autoSizeRowHeaders) { // Second round of row headers autosizing - AutoResizeRowHeadersWidth(this.rowHeadersWidthSizeMode, true /*fixedColumnHeadersHeight*/, true /*fixedRowsHeight*/); + AutoResizeRowHeadersWidth(rowHeadersWidthSizeMode, true /*fixedColumnHeadersHeight*/, true /*fixedRowsHeight*/); } } } protected virtual void OnRowHeadersWidthChanged(EventArgs e) { - if (this.RowHeadersVisible) + if (RowHeadersVisible) { - if (this.editingControl != null) + if (editingControl != null) { PositionEditingControl(true, false, false); } - if (this.IsHandleCreated) + if (IsHandleCreated) { UpdateMouseEnteredCell(null /*HitTestInfo*/, null /*MouseEventArgs*/); } @@ -18512,8 +18512,8 @@ protected virtual void OnRowHeadersWidthChanged(EventArgs e) OnRowHeadersGlobalAutoSize(false /*expandingRows*/); } - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWHEADERSWIDTHCHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWROWHEADERSWIDTHCHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18521,25 +18521,25 @@ protected virtual void OnRowHeadersWidthChanged(EventArgs e) protected virtual void OnRowHeadersWidthSizeModeChanged(DataGridViewAutoSizeModeEventArgs e) { - if (this.rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.EnableResizing && - this.rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.DisableResizing) + if (rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.EnableResizing && + rowHeadersWidthSizeMode != DataGridViewRowHeadersWidthSizeMode.DisableResizing) { if (!e.PreviousModeAutoSized) { // Save current row headers width for later reuse - this.cachedRowHeadersWidth = this.RowHeadersWidth; + cachedRowHeadersWidth = RowHeadersWidth; } - AutoResizeRowHeadersWidth(this.rowHeadersWidthSizeMode, + AutoResizeRowHeadersWidth(rowHeadersWidthSizeMode, true /*fixedColumnHeadersHeight*/, true /*fixedRowsHeight*/); } else if (e.PreviousModeAutoSized) { - this.RowHeadersWidth = this.cachedRowHeadersWidth; + RowHeadersWidth = cachedRowHeadersWidth; } - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWHEADERSWIDTHSIZEMODECHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWROWHEADERSWIDTHSIZEMODECHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18553,8 +18553,8 @@ protected virtual void OnRowHeightChanged(DataGridViewRowEventArgs e) } UpdateRowHeightInfoPrivate(e.Row.Index, false, false /*invalidInAdjustFillingColumns*/); - DataGridViewRowEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWHEIGHTCHANGED] as DataGridViewRowEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWROWHEIGHTCHANGED] as DataGridViewRowEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18564,7 +18564,7 @@ protected virtual void OnRowHeightChanged(DataGridViewRowEventArgs e) internal DataGridViewRowHeightInfoNeededEventArgs OnRowHeightInfoNeeded(int rowIndex, int height, int minimumHeight) { - DataGridViewRowHeightInfoNeededEventArgs dgvrhine = this.RowHeightInfoNeededEventArgs; + DataGridViewRowHeightInfoNeededEventArgs dgvrhine = RowHeightInfoNeededEventArgs; dgvrhine.SetProperties(rowIndex, height, minimumHeight); OnRowHeightInfoNeeded(dgvrhine); return dgvrhine; @@ -18572,8 +18572,8 @@ internal DataGridViewRowHeightInfoNeededEventArgs OnRowHeightInfoNeeded(int rowI protected virtual void OnRowHeightInfoNeeded(DataGridViewRowHeightInfoNeededEventArgs e) { - DataGridViewRowHeightInfoNeededEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWHEIGHTINFONEEDED] as DataGridViewRowHeightInfoNeededEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowHeightInfoNeededEventHandler eh = Events[EVENT_DATAGRIDVIEWROWHEIGHTINFONEEDED] as DataGridViewRowHeightInfoNeededEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18582,8 +18582,8 @@ protected virtual void OnRowHeightInfoNeeded(DataGridViewRowHeightInfoNeededEven private bool OnRowHeightInfoPushed(int rowIndex, int height, int minimumHeight) { Debug.Assert(rowIndex != -1); - Debug.Assert(this.autoSizeRowsMode == DataGridViewAutoSizeRowsMode.None); - if (this.VirtualMode || this.DataSource != null) + Debug.Assert(autoSizeRowsMode == DataGridViewAutoSizeRowsMode.None); + if (VirtualMode || DataSource != null) { DataGridViewRowHeightInfoPushedEventArgs dgvrhipe = new DataGridViewRowHeightInfoPushedEventArgs(rowIndex, height, minimumHeight); OnRowHeightInfoPushed(dgvrhipe); @@ -18598,8 +18598,8 @@ private bool OnRowHeightInfoPushed(int rowIndex, int height, int minimumHeight) protected virtual void OnRowHeightInfoPushed(DataGridViewRowHeightInfoPushedEventArgs e) { - DataGridViewRowHeightInfoPushedEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWHEIGHTINFOPUSHED] as DataGridViewRowHeightInfoPushedEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowHeightInfoPushedEventHandler eh = Events[EVENT_DATAGRIDVIEWROWHEIGHTINFOPUSHED] as DataGridViewRowHeightInfoPushedEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18608,7 +18608,7 @@ protected virtual void OnRowHeightInfoPushed(DataGridViewRowHeightInfoPushedEven private void OnRowLeave(ref DataGridViewCell dataGridViewCell, int columnIndex, int rowIndex) { Debug.Assert(columnIndex >= 0 && rowIndex >= 0); - if (rowIndex < this.Rows.Count && columnIndex < this.Columns.Count) + if (rowIndex < Rows.Count && columnIndex < Columns.Count) { DataGridViewCellEventArgs dgvce = new DataGridViewCellEventArgs(columnIndex, rowIndex); OnRowLeave(dgvce); @@ -18620,8 +18620,8 @@ private void OnRowLeave(ref DataGridViewCell dataGridViewCell, int columnIndex, } else { - Debug.Assert(rowIndex < this.Rows.Count && columnIndex < this.Columns.Count); - dataGridViewCell = this.Rows.SharedRow(rowIndex).Cells[columnIndex]; + Debug.Assert(rowIndex < Rows.Count && columnIndex < Columns.Count); + dataGridViewCell = Rows.SharedRow(rowIndex).Cells[columnIndex]; } } } @@ -18631,10 +18631,10 @@ protected virtual void OnRowLeave(DataGridViewCellEventArgs e) { try { - this.noDimensionChangeCount++; + noDimensionChangeCount++; - DataGridViewCellEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWLEAVE] as DataGridViewCellEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWROWLEAVE] as DataGridViewCellEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); CorrectFocus(true /*onlyIfGridHasFocus*/); @@ -18642,8 +18642,8 @@ protected virtual void OnRowLeave(DataGridViewCellEventArgs e) } finally { - this.noDimensionChangeCount--; - Debug.Assert(this.noDimensionChangeCount >= 0); + noDimensionChangeCount--; + Debug.Assert(noDimensionChangeCount >= 0); } } @@ -18653,8 +18653,8 @@ protected virtual void OnRowMinimumHeightChanged(DataGridViewRowEventArgs e) { throw new ArgumentException(string.Format(SR.DataGridView_RowDoesNotBelongToDataGridView), "e.Row"); } - DataGridViewRowEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWMINIMUMHEIGHTCHANGED] as DataGridViewRowEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWROWMINIMUMHEIGHTCHANGED] as DataGridViewRowEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18662,8 +18662,8 @@ protected virtual void OnRowMinimumHeightChanged(DataGridViewRowEventArgs e) protected internal virtual void OnRowPostPaint(DataGridViewRowPostPaintEventArgs e) { - DataGridViewRowPostPaintEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWPOSTPAINT] as DataGridViewRowPostPaintEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowPostPaintEventHandler eh = Events[EVENT_DATAGRIDVIEWROWPOSTPAINT] as DataGridViewRowPostPaintEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18671,8 +18671,8 @@ protected internal virtual void OnRowPostPaint(DataGridViewRowPostPaintEventArgs protected internal virtual void OnRowPrePaint(DataGridViewRowPrePaintEventArgs e) { - DataGridViewRowPrePaintEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWPREPAINT] as DataGridViewRowPrePaintEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowPrePaintEventHandler eh = Events[EVENT_DATAGRIDVIEWROWPREPAINT] as DataGridViewRowPrePaintEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18685,8 +18685,8 @@ internal void OnRowsAddedInternal(int rowIndex, int rowCount) protected virtual void OnRowsAdded(DataGridViewRowsAddedEventArgs e) { - DataGridViewRowsAddedEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWSADDED] as DataGridViewRowsAddedEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowsAddedEventHandler eh = Events[EVENT_DATAGRIDVIEWROWSADDED] as DataGridViewRowsAddedEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18702,14 +18702,14 @@ protected virtual void OnRowsDefaultCellStyleChanged(EventArgs e) else { OnRowsGlobalAutoSize(); - if (this.editingControl != null) + if (editingControl != null) { PositionEditingControl(true /*setLocation*/, true /*setSize*/, false /*setFocus*/); } } - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWSDEFAULTCELLSTYLECHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWROWSDEFAULTCELLSTYLECHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18718,11 +18718,11 @@ protected virtual void OnRowsDefaultCellStyleChanged(EventArgs e) private void OnRowSelectMouseMove(HitTestInfo hti) { Debug.Assert(hti.row >= 0); - Debug.Assert(this.MultiSelect); + Debug.Assert(MultiSelect); - if (this.ptCurrentCell.Y != -1 && - hti.row != this.ptCurrentCell.Y && - !CommitEditForOperation(this.ptCurrentCell.X, hti.row, true)) + if (ptCurrentCell.Y != -1 && + hti.row != ptCurrentCell.Y && + !CommitEditForOperation(ptCurrentCell.X, hti.row, true)) { // Return silently if validating/commit/abort failed return; @@ -18732,79 +18732,79 @@ private void OnRowSelectMouseMove(HitTestInfo hti) return; } - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - if (this.trackRowEdge >= this.trackRow && hti.row > this.trackRowEdge && this.trackRowEdge >= 0) + if (trackRowEdge >= trackRow && hti.row > trackRowEdge && trackRowEdge >= 0) { - SelectRowRange(this.Rows.GetNextRow(this.trackRowEdge, DataGridViewElementStates.Visible), + SelectRowRange(Rows.GetNextRow(trackRowEdge, DataGridViewElementStates.Visible), hti.row, true); - this.trackRowEdge = hti.row; + trackRowEdge = hti.row; } - else if (this.trackRowEdge > this.trackRow && hti.row < this.trackRowEdge && hti.row >= this.trackRow && this.trackRowEdge >= 0) + else if (trackRowEdge > trackRow && hti.row < trackRowEdge && hti.row >= trackRow && trackRowEdge >= 0) { - SelectRowRange(this.Rows.GetNextRow(hti.row, DataGridViewElementStates.Visible), - this.trackRowEdge, false); - this.trackRowEdge = hti.row; + SelectRowRange(Rows.GetNextRow(hti.row, DataGridViewElementStates.Visible), + trackRowEdge, false); + trackRowEdge = hti.row; } - else if (hti.row > this.trackRow && this.trackRowEdge == -1) + else if (hti.row > trackRow && trackRowEdge == -1) { - SelectRowRange(this.Rows.GetNextRow(this.trackRow, DataGridViewElementStates.Visible), + SelectRowRange(Rows.GetNextRow(trackRow, DataGridViewElementStates.Visible), hti.row, true); - this.trackRowEdge = hti.row; + trackRowEdge = hti.row; } - else if (this.trackRowEdge <= this.trackRow && hti.row < this.trackRowEdge && this.trackRowEdge >= 0) + else if (trackRowEdge <= trackRow && hti.row < trackRowEdge && trackRowEdge >= 0) { SelectRowRange(hti.row, - this.Rows.GetPreviousRow(this.trackRowEdge, DataGridViewElementStates.Visible), + Rows.GetPreviousRow(trackRowEdge, DataGridViewElementStates.Visible), true); - this.trackRowEdge = hti.row; + trackRowEdge = hti.row; } - else if (this.trackRowEdge < this.trackRow && hti.row > this.trackRowEdge && hti.row <= this.trackRow && this.trackRowEdge >= 0) + else if (trackRowEdge < trackRow && hti.row > trackRowEdge && hti.row <= trackRow && trackRowEdge >= 0) { - SelectRowRange(this.trackRowEdge, - this.Rows.GetPreviousRow(hti.row, DataGridViewElementStates.Visible), + SelectRowRange(trackRowEdge, + Rows.GetPreviousRow(hti.row, DataGridViewElementStates.Visible), false); - this.trackRowEdge = hti.row; + trackRowEdge = hti.row; } - else if (hti.row < this.trackRow && this.trackRowEdge == -1) + else if (hti.row < trackRow && trackRowEdge == -1) { SelectRowRange(hti.row, - this.Rows.GetPreviousRow(this.trackRow, DataGridViewElementStates.Visible), + Rows.GetPreviousRow(trackRow, DataGridViewElementStates.Visible), true); - this.trackRowEdge = hti.row; + trackRowEdge = hti.row; } - else if (this.trackRowEdge > this.trackRow && hti.row < this.trackRow) + else if (trackRowEdge > trackRow && hti.row < trackRow) { - SelectRowRange(this.Rows.GetNextRow(this.trackRow, DataGridViewElementStates.Visible), - this.trackRowEdge, false); + SelectRowRange(Rows.GetNextRow(trackRow, DataGridViewElementStates.Visible), + trackRowEdge, false); SelectRowRange(hti.row, - this.Rows.GetPreviousRow(this.trackRow, DataGridViewElementStates.Visible), + Rows.GetPreviousRow(trackRow, DataGridViewElementStates.Visible), true); - this.trackRowEdge = hti.row; + trackRowEdge = hti.row; } - else if (hti.row > this.trackRow && this.trackRowEdge < this.trackRow && this.trackRowEdge >= 0) + else if (hti.row > trackRow && trackRowEdge < trackRow && trackRowEdge >= 0) { - SelectRowRange(this.trackRowEdge, - this.Rows.GetPreviousRow(this.trackRow, DataGridViewElementStates.Visible), + SelectRowRange(trackRowEdge, + Rows.GetPreviousRow(trackRow, DataGridViewElementStates.Visible), false); - SelectRowRange(this.Rows.GetNextRow(this.trackRow, DataGridViewElementStates.Visible), + SelectRowRange(Rows.GetNextRow(trackRow, DataGridViewElementStates.Visible), hti.row, true); - this.trackRowEdge = hti.row; + trackRowEdge = hti.row; } } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; } - if (this.ptCurrentCell.Y != -1 && hti.row != this.ptCurrentCell.Y) + if (ptCurrentCell.Y != -1 && hti.row != ptCurrentCell.Y) { if (IsRowOutOfBounds(hti.row)) { return; } - bool success = SetCurrentCellAddressCore(this.ptCurrentCell.X, + bool success = SetCurrentCellAddressCore(ptCurrentCell.X, hti.row, false /*setAnchorCellAddress*/, false /*validateCurrentCell*/, @@ -18817,15 +18817,15 @@ private void OnRowsGlobalAutoSize() { InvalidateData(); - if (this.noAutoSizeCount > 0) + if (noAutoSizeCount > 0) { return; } // Autosize rows if needed - if ((((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0) + if ((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0) { - AdjustShrinkingRows(this.autoSizeRowsMode, false /*fixedWidth*/, true /*internalAutosizing*/); + AdjustShrinkingRows(autoSizeRowsMode, false /*fixedWidth*/, true /*internalAutosizing*/); } // Auto size columms also if needed @@ -18833,10 +18833,10 @@ private void OnRowsGlobalAutoSize() DataGridViewAutoSizeColumnCriteriaInternal.DisplayedRows, true /*fixedHeight*/); - bool fixedRowHeadersWidth = this.rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing || - this.rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.DisableResizing; + bool fixedRowHeadersWidth = rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.EnableResizing || + rowHeadersWidthSizeMode == DataGridViewRowHeadersWidthSizeMode.DisableResizing; // Auto size column headers - if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) + if (ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) { AutoResizeColumnHeadersHeight(fixedRowHeadersWidth, true /*fixedColumnsWidth*/); } @@ -18844,17 +18844,17 @@ private void OnRowsGlobalAutoSize() // Auto size row headers if (!fixedRowHeadersWidth) { - AutoResizeRowHeadersWidth(this.rowHeadersWidthSizeMode, true /*fixedColumnHeadersHeight*/, true /*fixedRowsHeight*/); + AutoResizeRowHeadersWidth(rowHeadersWidthSizeMode, true /*fixedColumnHeadersHeight*/, true /*fixedRowsHeight*/); } // Second round of rows autosizing - if ((((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0) + if ((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0) { - AdjustShrinkingRows(this.autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); + AdjustShrinkingRows(autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); } // Second round of column headers autosizing - if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize && !fixedRowHeadersWidth) + if (ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize && !fixedRowHeadersWidth) { AutoResizeColumnHeadersHeight(true /*fixedRowHeadersWidth*/, true /*fixedColumnsWidth*/); } @@ -18867,8 +18867,8 @@ internal void OnRowsRemovedInternal(int rowIndex, int rowCount) protected virtual void OnRowsRemoved(DataGridViewRowsRemovedEventArgs e) { - DataGridViewRowsRemovedEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWSREMOVED] as DataGridViewRowsRemovedEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowsRemovedEventHandler eh = Events[EVENT_DATAGRIDVIEWROWSREMOVED] as DataGridViewRowsRemovedEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18885,7 +18885,7 @@ protected virtual void OnRowStateChanged(int rowIndex, DataGridViewRowStateChang bool rowVisible = false; if (rowIndex >= 0) { - newState = this.Rows.GetRowState(rowIndex); + newState = Rows.GetRowState(rowIndex); rowVisible = ((newState & DataGridViewElementStates.Visible) != 0); } switch (e.StateChanged) @@ -18896,7 +18896,7 @@ protected virtual void OnRowStateChanged(int rowIndex, DataGridViewRowStateChang // case DataGridViewElementStates.Resizable: case DataGridViewElementStates.Selected: - if (rowVisible && this.inBulkPaintCount == 0) + if (rowVisible && inBulkPaintCount == 0) { InvalidateRowPrivate(rowIndex); } @@ -18920,14 +18920,14 @@ protected virtual void OnRowStateChanged(int rowIndex, DataGridViewRowStateChang if (!rowVisible && (newState & DataGridViewElementStates.Displayed) != 0) { // Displayed row becomes invisible. Turns off the Displayed state. - this.Rows.SetRowState(rowIndex, DataGridViewElementStates.Displayed, false); + Rows.SetRowState(rowIndex, DataGridViewElementStates.Displayed, false); } PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, true /*repositionEditingControl*/); Invalidate(); - bool rowDisplayed = (this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Displayed) != 0; - DataGridViewAutoSizeRowsModeInternal autoSizeRowsModeInternal = (DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode; + bool rowDisplayed = (Rows.GetRowState(rowIndex) & DataGridViewElementStates.Displayed) != 0; + DataGridViewAutoSizeRowsModeInternal autoSizeRowsModeInternal = (DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode; bool autoSizeRow = false; @@ -18941,7 +18941,7 @@ protected virtual void OnRowStateChanged(int rowIndex, DataGridViewRowStateChang dataGridViewRow.CachedThickness = height; if (!((autoSizeRowsModeInternal & DataGridViewAutoSizeRowsModeInternal.DisplayedRows) != 0 && !rowDisplayed)) { - AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(this.autoSizeRowsMode), false /*fixedWidth*/, true /*internalAutosizing*/); + AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(autoSizeRowsMode), false /*fixedWidth*/, true /*internalAutosizing*/); autoSizeRow = true; } } @@ -18952,7 +18952,7 @@ protected virtual void OnRowStateChanged(int rowIndex, DataGridViewRowStateChang // Make sure the affected row is unshared if (dataGridViewRow.Index == -1) { - dataGridViewRow = this.Rows[rowIndex]; + dataGridViewRow = Rows[rowIndex]; } dataGridViewRow.ThicknessInternal = Math.Max(dataGridViewRow.MinimumHeight, dataGridViewRow.CachedThickness); } @@ -18964,7 +18964,7 @@ protected virtual void OnRowStateChanged(int rowIndex, DataGridViewRowStateChang { autoSizeColumnCriteriaFilter |= DataGridViewAutoSizeColumnCriteriaInternal.DisplayedRows; } - if (rowVisible && this.Rows.GetRowCount(DataGridViewElementStates.Visible) > 1) + if (rowVisible && Rows.GetRowCount(DataGridViewElementStates.Visible) > 1) { // Columns can only expand, and not collapse. AdjustExpandingColumns(autoSizeColumnCriteriaFilter, rowIndex); @@ -18977,31 +18977,31 @@ protected virtual void OnRowStateChanged(int rowIndex, DataGridViewRowStateChang if (autoSizeRow) { // Second round of row autosizing - AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(this.autoSizeRowsMode), true /*fixedWidth*/, true /*internalAutosizing*/); + AutoResizeRowInternal(rowIndex, MapAutoSizeRowsModeToRowMode(autoSizeRowsMode), true /*fixedWidth*/, true /*internalAutosizing*/); } break; } } - DataGridViewRowStateChangedEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWSTATECHANGED] as DataGridViewRowStateChangedEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowStateChangedEventHandler eh = Events[EVENT_DATAGRIDVIEWROWSTATECHANGED] as DataGridViewRowStateChangedEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } if (e.StateChanged == DataGridViewElementStates.ReadOnly && - rowIndex == this.ptCurrentCell.Y && - !this.dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange]) + rowIndex == ptCurrentCell.Y && + !dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange]) { VerifyImeRestrictedModeChanged(); if ((newState & DataGridViewElementStates.ReadOnly) == 0 && - !this.ReadOnly && - !this.Columns[this.ptCurrentCell.X].ReadOnly && - ColumnEditable(this.ptCurrentCell.X) && - !this.IsCurrentCellInEditMode && - (this.EditMode == DataGridViewEditMode.EditOnEnter || - (this.EditMode != DataGridViewEditMode.EditProgrammatically && this.CurrentCellInternal.EditType == null))) + !ReadOnly && + !Columns[ptCurrentCell.X].ReadOnly && + ColumnEditable(ptCurrentCell.X) && + !IsCurrentCellInEditMode && + (EditMode == DataGridViewEditMode.EditOnEnter || + (EditMode != DataGridViewEditMode.EditProgrammatically && CurrentCellInternal.EditType == null))) { // Current row becomes read/write. Enter editing mode. BeginEditInternal(true /*selectAll*/); @@ -19011,9 +19011,9 @@ protected virtual void OnRowStateChanged(int rowIndex, DataGridViewRowStateChang internal void OnRowUnshared(DataGridViewRow dataGridViewRow) { - if (-1 != this.ptCurrentCell.X && dataGridViewRow.Index == this.ptCurrentCell.Y && this.editingControl != null) + if (-1 != ptCurrentCell.X && dataGridViewRow.Index == ptCurrentCell.Y && editingControl != null) { - this.CurrentCellInternal.CacheEditingControl(); + CurrentCellInternal.CacheEditingControl(); } DataGridViewRowEventArgs dgvre = new DataGridViewRowEventArgs(dataGridViewRow); OnRowUnshared(dgvre); @@ -19025,8 +19025,8 @@ protected virtual void OnRowUnshared(DataGridViewRowEventArgs e) { throw new ArgumentException(string.Format(SR.DataGridView_RowDoesNotBelongToDataGridView), "e.Row"); } - DataGridViewRowEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWUNSHARED] as DataGridViewRowEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWROWUNSHARED] as DataGridViewRowEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -19038,17 +19038,17 @@ private bool OnRowValidating(ref DataGridViewCell dataGridViewCell, int columnIn OnRowValidating(dgvcce); if (!dgvcce.Cancel) { - if (this.dataConnection != null && - this.dataConnection.InterestedInRowEvents && - !this.dataConnection.PositionChangingOutsideDataGridView && - !this.dataConnection.ListWasReset) + if (dataConnection != null && + dataConnection.InterestedInRowEvents && + !dataConnection.PositionChangingOutsideDataGridView && + !dataConnection.ListWasReset) { - this.dataConnection.OnRowValidating(dgvcce); + dataConnection.OnRowValidating(dgvcce); } } - if (dataGridViewCell != null && rowIndex < this.Rows.Count && columnIndex < this.Columns.Count) + if (dataGridViewCell != null && rowIndex < Rows.Count && columnIndex < Columns.Count) { - dataGridViewCell = this.Rows.SharedRow(rowIndex).Cells[columnIndex]; + dataGridViewCell = Rows.SharedRow(rowIndex).Cells[columnIndex]; } return dgvcce.Cancel; } @@ -19057,10 +19057,10 @@ protected virtual void OnRowValidating(DataGridViewCellCancelEventArgs e) { try { - this.noDimensionChangeCount++; + noDimensionChangeCount++; - DataGridViewCellCancelEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWVALIDATING] as DataGridViewCellCancelEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellCancelEventHandler eh = Events[EVENT_DATAGRIDVIEWROWVALIDATING] as DataGridViewCellCancelEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); CorrectFocus(true /*onlyIfGridHasFocus*/); @@ -19068,16 +19068,16 @@ protected virtual void OnRowValidating(DataGridViewCellCancelEventArgs e) } finally { - this.noDimensionChangeCount--; - Debug.Assert(this.noDimensionChangeCount >= 0); + noDimensionChangeCount--; + Debug.Assert(noDimensionChangeCount >= 0); } } private void OnRowValidated(ref DataGridViewCell dataGridViewCell, int columnIndex, int rowIndex) { - this.IsCurrentRowDirtyInternal = false; - this.dataGridViewState1[DATAGRIDVIEWSTATE1_newRowCreatedByEditing] = false; - if (rowIndex == this.newRowIndex) + IsCurrentRowDirtyInternal = false; + dataGridViewState1[DATAGRIDVIEWSTATE1_newRowCreatedByEditing] = false; + if (rowIndex == newRowIndex) { // Stop displaying the default cell values on the 'new row'. InvalidateRowPrivate(rowIndex); @@ -19093,8 +19093,8 @@ private void OnRowValidated(ref DataGridViewCell dataGridViewCell, int columnInd } else { - Debug.Assert(rowIndex < this.Rows.Count && columnIndex < this.Columns.Count); - dataGridViewCell = this.Rows.SharedRow(rowIndex).Cells[columnIndex]; + Debug.Assert(rowIndex < Rows.Count && columnIndex < Columns.Count); + dataGridViewCell = Rows.SharedRow(rowIndex).Cells[columnIndex]; } } } @@ -19103,10 +19103,10 @@ protected virtual void OnRowValidated(DataGridViewCellEventArgs e) { try { - this.noDimensionChangeCount++; + noDimensionChangeCount++; - DataGridViewCellEventHandler eh = this.Events[EVENT_DATAGRIDVIEWROWVALIDATED] as DataGridViewCellEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWROWVALIDATED] as DataGridViewCellEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); CorrectFocus(true /*onlyIfGridHasFocus*/); @@ -19114,8 +19114,8 @@ protected virtual void OnRowValidated(DataGridViewCellEventArgs e) } finally { - this.noDimensionChangeCount--; - Debug.Assert(this.noDimensionChangeCount >= 0); + noDimensionChangeCount--; + Debug.Assert(noDimensionChangeCount >= 0); } } @@ -19162,7 +19162,7 @@ private void OnScroll(ScrollEventType scrollEventType, int oldValue, int newValu ScrollEventArgs se = new ScrollEventArgs(scrollEventType, oldValue, newValue, orientation); OnScroll(se); RefreshByCurrentPos(oldValue, newValue); - if (this.Focused && this.IsGridFocusRectangleEnabled()) + if (Focused && IsGridFocusRectangleEnabled()) { InvalidateGridFocusOnScroll(newValue - oldValue, orientation); } @@ -19172,14 +19172,14 @@ private void OnScroll(ScrollEventType scrollEventType, int oldValue, int newValu { try { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_stopRaisingVerticalScroll] = true; - int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); + dataGridViewState2[DATAGRIDVIEWSTATE2_stopRaisingVerticalScroll] = true; + int rowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); int rowIndexPrevious = rowIndex; newValue = se.NewValue; while (rowIndex != -1 && newValue > 0) { rowIndexPrevious = rowIndex; - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); + rowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); newValue--; } if (rowIndex != -1) @@ -19188,12 +19188,12 @@ private void OnScroll(ScrollEventType scrollEventType, int oldValue, int newValu } if (rowIndexPrevious != -1) { - this.FirstDisplayedScrollingRowIndex = rowIndexPrevious; + FirstDisplayedScrollingRowIndex = rowIndexPrevious; } } finally { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_stopRaisingVerticalScroll] = false; + dataGridViewState2[DATAGRIDVIEWSTATE2_stopRaisingVerticalScroll] = false; } } } @@ -19203,12 +19203,12 @@ private void OnScroll(ScrollEventType scrollEventType, int oldValue, int newValu { try { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_stopRaisingHorizontalScroll] = true; - this.HorizontalOffset = se.NewValue; + dataGridViewState2[DATAGRIDVIEWSTATE2_stopRaisingHorizontalScroll] = true; + HorizontalOffset = se.NewValue; } finally { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_stopRaisingHorizontalScroll] = false; + dataGridViewState2[DATAGRIDVIEWSTATE2_stopRaisingHorizontalScroll] = false; } } } @@ -19216,8 +19216,8 @@ private void OnScroll(ScrollEventType scrollEventType, int oldValue, int newValu protected virtual void OnScroll(ScrollEventArgs e) { - ScrollEventHandler eh = this.Events[EVENT_DATAGRIDVIEWSCROLL] as ScrollEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + ScrollEventHandler eh = Events[EVENT_DATAGRIDVIEWSCROLL] as ScrollEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -19225,10 +19225,10 @@ protected virtual void OnScroll(ScrollEventArgs e) protected virtual void OnSelectionChanged(EventArgs e) { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_raiseSelectionChanged] = false; + dataGridViewState2[DATAGRIDVIEWSTATE2_raiseSelectionChanged] = false; - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWSELECTIONCHANGED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWSELECTIONCHANGED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -19244,8 +19244,8 @@ internal bool OnSortCompare(DataGridViewColumn dataGridViewSortedColumn, object protected virtual void OnSortCompare(DataGridViewSortCompareEventArgs e) { - DataGridViewSortCompareEventHandler eh = this.Events[EVENT_DATAGRIDVIEWSORTCOMPARE] as DataGridViewSortCompareEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewSortCompareEventHandler eh = Events[EVENT_DATAGRIDVIEWSORTCOMPARE] as DataGridViewSortCompareEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -19253,8 +19253,8 @@ protected virtual void OnSortCompare(DataGridViewSortCompareEventArgs e) protected virtual void OnSorted(EventArgs e) { - EventHandler eh = this.Events[EVENT_DATAGRIDVIEWSORTED] as EventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + EventHandler eh = Events[EVENT_DATAGRIDVIEWSORTED] as EventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -19264,11 +19264,11 @@ internal void OnSortGlyphDirectionChanged(DataGridViewColumnHeaderCell dataGridV { Debug.Assert(dataGridViewColumnHeaderCell != null); - if (dataGridViewColumnHeaderCell.OwningColumn == this.SortedColumn) + if (dataGridViewColumnHeaderCell.OwningColumn == SortedColumn) { if (dataGridViewColumnHeaderCell.SortGlyphDirection == SortOrder.None) { - this.sortedColumn = null; + sortedColumn = null; DataGridViewColumn dataGridViewColumn = dataGridViewColumnHeaderCell.OwningColumn; if (dataGridViewColumn.IsDataBound) @@ -19276,24 +19276,24 @@ internal void OnSortGlyphDirectionChanged(DataGridViewColumnHeaderCell dataGridV // If the column whose SortGlyphChanges is the sorted column and it is also the dataBound column // then see if there is another dataBound column which has the same property name as the sorted column. // If so, then make that dataGridViewColumn the sorted column in the data grid view. - for (int i = 0; i < this.Columns.Count; i++) + for (int i = 0; i < Columns.Count; i++) { - if (dataGridViewColumn != this.Columns[i] && - this.Columns[i].SortMode != DataGridViewColumnSortMode.NotSortable && + if (dataGridViewColumn != Columns[i] && + Columns[i].SortMode != DataGridViewColumnSortMode.NotSortable && string.Compare(dataGridViewColumn.DataPropertyName, - this.Columns[i].DataPropertyName, + Columns[i].DataPropertyName, true /*ignoreCase*/, CultureInfo.InvariantCulture) == 0) { - Debug.Assert(this.Columns[i].IsDataBound, "two columns w/ the same DataPropertyName should be DataBound at the same time"); - this.sortedColumn = this.Columns[i]; + Debug.Assert(Columns[i].IsDataBound, "two columns w/ the same DataPropertyName should be DataBound at the same time"); + sortedColumn = Columns[i]; break; } } } } - this.sortOrder = this.sortedColumn != null ? this.sortedColumn.HeaderCell.SortGlyphDirection : SortOrder.None; + sortOrder = sortedColumn != null ? sortedColumn.HeaderCell.SortGlyphDirection : SortOrder.None; } InvalidateCellPrivate(dataGridViewColumnHeaderCell); @@ -19301,13 +19301,13 @@ internal void OnSortGlyphDirectionChanged(DataGridViewColumnHeaderCell dataGridV private void OnTopLeftHeaderMouseDown() { - if (this.MultiSelect) + if (MultiSelect) { SelectAll(); - if (-1 != this.ptCurrentCell.X) + if (-1 != ptCurrentCell.X) { // Potentially have to give focus back to the current edited cell. - bool success = SetCurrentCellAddressCore(this.ptCurrentCell.X, this.ptCurrentCell.Y, + bool success = SetCurrentCellAddressCore(ptCurrentCell.X, ptCurrentCell.Y, false /*setAnchorCellAddress*/, false /*validateCurrentCell*/, false /*throughMouseClick*/); @@ -19322,8 +19322,8 @@ protected virtual void OnUserAddedRow(DataGridViewRowEventArgs e) { throw new ArgumentException(string.Format(SR.DataGridView_RowDoesNotBelongToDataGridView), "e.Row"); } - DataGridViewRowEventHandler eh = this.Events[EVENT_DATAGRIDVIEWUSERADDEDROW] as DataGridViewRowEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWUSERADDEDROW] as DataGridViewRowEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -19331,8 +19331,8 @@ protected virtual void OnUserAddedRow(DataGridViewRowEventArgs e) protected virtual void OnUserDeletedRow(DataGridViewRowEventArgs e) { - DataGridViewRowEventHandler eh = this.Events[EVENT_DATAGRIDVIEWUSERDELETEDROW] as DataGridViewRowEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWUSERDELETEDROW] as DataGridViewRowEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -19340,8 +19340,8 @@ protected virtual void OnUserDeletedRow(DataGridViewRowEventArgs e) protected virtual void OnUserDeletingRow(DataGridViewRowCancelEventArgs e) { - DataGridViewRowCancelEventHandler eh = this.Events[EVENT_DATAGRIDVIEWUSERDELETINGROW] as DataGridViewRowCancelEventHandler; - if (eh != null && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !this.IsDisposed) + DataGridViewRowCancelEventHandler eh = Events[EVENT_DATAGRIDVIEWUSERDELETINGROW] as DataGridViewRowCancelEventHandler; + if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -19358,13 +19358,13 @@ private void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventAr OnGlobalAutoSize(); if (e.Category == UserPreferenceCategory.Window) { - this.cachedEditingControl = null; - if (this.editingControl != null) + cachedEditingControl = null; + if (editingControl != null) { // The editing control may not adapt well to the new system rendering, // so instead of caching it into the this.cachedEditingControl variable // next time editing mode is exited, simply discard the control. - this.dataGridViewState2[DATAGRIDVIEWSTATE2_discardEditingControl] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_discardEditingControl] = true; } PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, false /*invalidInAdjustFillingColumns*/, true /*repositionEditingControl*/); } @@ -19374,9 +19374,9 @@ private void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventAr protected override void OnValidating(CancelEventArgs e) { // Avoid Cell/Row Validation events when the grid or its editing control gets the focus - if (!this.BecomingActiveControl && (this.editingControl == null || !this.editingControl.BecomingActiveControl)) + if (!BecomingActiveControl && (editingControl == null || !editingControl.BecomingActiveControl)) { - if (!this.dataGridViewState1[DATAGRIDVIEWSTATE1_leavingWithTabKey]) + if (!dataGridViewState1[DATAGRIDVIEWSTATE1_leavingWithTabKey]) { if (!EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.LeaveControl, DataGridViewValidateCellInternal.Always, @@ -19394,31 +19394,31 @@ protected override void OnValidating(CancelEventArgs e) } } - if (this.ptCurrentCell.X >= 0) + if (ptCurrentCell.X >= 0) { DataGridViewCell dataGridViewCellTmp = null; - if (OnRowValidating(ref dataGridViewCellTmp, this.ptCurrentCell.X, this.ptCurrentCell.Y)) + if (OnRowValidating(ref dataGridViewCellTmp, ptCurrentCell.X, ptCurrentCell.Y)) { // Row validation was cancelled e.Cancel = true; return; } - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { return; } - OnRowValidated(ref dataGridViewCellTmp, this.ptCurrentCell.X, this.ptCurrentCell.Y); + OnRowValidated(ref dataGridViewCellTmp, ptCurrentCell.X, ptCurrentCell.Y); // Row validation was not cancelled, but does operation need to be re-evaluated. - if (this.DataSource != null && - this.ptCurrentCell.X >= 0 && - this.AllowUserToAddRowsInternal && - this.newRowIndex == this.ptCurrentCell.Y) + if (DataSource != null && + ptCurrentCell.X >= 0 && + AllowUserToAddRowsInternal && + newRowIndex == ptCurrentCell.Y) { // Current cell needs to be moved to the row just above the 'new row' if possible. - int rowIndex = this.Rows.GetPreviousRow(this.ptCurrentCell.Y, DataGridViewElementStates.Visible); + int rowIndex = Rows.GetPreviousRow(ptCurrentCell.Y, DataGridViewElementStates.Visible); if (rowIndex > -1) { - bool success = SetAndSelectCurrentCellAddress(this.ptCurrentCell.X, rowIndex, + bool success = SetAndSelectCurrentCellAddress(ptCurrentCell.X, rowIndex, true /*setAnchorCellAddress*/, false /*validateCurrentCell*/, false /*throughMouseClick*/, @@ -19452,27 +19452,27 @@ private void OnVisibleChangedPrivate() // for example when RowHeadersVisible is changed while the control is invisible. int rowIndexTmp; - if (this.Visible) + if (Visible) { // Make sure all displayed bands get the Displayed state: 1 & 2 for rows // 1. Make sure all displayed frozen rows have their Displayed state set to true - int numDisplayedFrozenRows = this.displayedBandsInfo.NumDisplayedFrozenRows; + int numDisplayedFrozenRows = displayedBandsInfo.NumDisplayedFrozenRows; if (numDisplayedFrozenRows > 0) { - rowIndexTmp = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + rowIndexTmp = Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); while (numDisplayedFrozenRows > 0) { Debug.Assert(rowIndexTmp != -1); - if ((this.Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) != 0) + if ((Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) != 0) { #if DEBUG int numDisplayedFrozenRowsDbg = numDisplayedFrozenRows; while (numDisplayedFrozenRowsDbg > 0) { Debug.Assert(rowIndexTmp != -1); - Debug.Assert((this.Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) != 0); - rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + Debug.Assert((Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) != 0); + rowIndexTmp = Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); numDisplayedFrozenRowsDbg--; } #endif @@ -19480,32 +19480,32 @@ private void OnVisibleChangedPrivate() } else { - this.Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, true); - rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, true); + rowIndexTmp = Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); numDisplayedFrozenRows--; } } } // 2. Make sure all displayed scrolling rows have their Displayed state set to true - rowIndexTmp = this.displayedBandsInfo.FirstDisplayedScrollingRow; + rowIndexTmp = displayedBandsInfo.FirstDisplayedScrollingRow; if (rowIndexTmp > -1) { - Debug.Assert((this.Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Visible) != 0); - int numDisplayedScrollingRows = this.displayedBandsInfo.NumDisplayedScrollingRows; + Debug.Assert((Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Visible) != 0); + int numDisplayedScrollingRows = displayedBandsInfo.NumDisplayedScrollingRows; Debug.Assert(numDisplayedScrollingRows > 0); while (numDisplayedScrollingRows > 0) { Debug.Assert(rowIndexTmp != -1); - if ((this.Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) != 0) + if ((Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) != 0) { #if DEBUG int numDisplayedScrollingRowsDbg = numDisplayedScrollingRows; while (numDisplayedScrollingRowsDbg > 0) { Debug.Assert(rowIndexTmp != -1); - Debug.Assert((this.Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) != 0); - rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible); + Debug.Assert((Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) != 0); + rowIndexTmp = Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible); numDisplayedScrollingRowsDbg--; } #endif @@ -19513,8 +19513,8 @@ private void OnVisibleChangedPrivate() } else { - this.Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, true); - rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible); + Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, true); + rowIndexTmp = Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible); numDisplayedScrollingRows--; } } @@ -19526,7 +19526,7 @@ private void OnVisibleChangedPrivate() UpdateRowsDisplayedState(false /*displayed*/); } - UpdateColumnsDisplayedState(this.Visible /*displayed*/); + UpdateColumnsDisplayedState(Visible /*displayed*/); } protected virtual void PaintBackground(Graphics graphics, Rectangle clipBounds, Rectangle gridBounds) @@ -19535,13 +19535,13 @@ protected virtual void PaintBackground(Graphics graphics, Rectangle clipBounds, Rectangle rcBelowRows = gridBounds; // Remaining cell images on DataGridView - int visibleRowsHeight = this.Rows.GetRowsHeight(DataGridViewElementStates.Displayed); - if (this.layout.ColumnHeadersVisible) + int visibleRowsHeight = Rows.GetRowsHeight(DataGridViewElementStates.Displayed); + if (layout.ColumnHeadersVisible) { - rcBelowRows.Y += this.layout.ColumnHeaders.Height; - rcBelowRows.Height -= this.layout.ColumnHeaders.Height; + rcBelowRows.Y += layout.ColumnHeaders.Height; + rcBelowRows.Height -= layout.ColumnHeaders.Height; } - else if (this.SingleHorizontalBorderAdded && visibleRowsHeight > 0) + else if (SingleHorizontalBorderAdded && visibleRowsHeight > 0) { rcBelowRows.Y++; rcBelowRows.Height--; @@ -19551,34 +19551,34 @@ protected virtual void PaintBackground(Graphics graphics, Rectangle clipBounds, rcBelowRows.Height -= visibleRowsHeight; if (rcBelowRows.Width > 0 && rcBelowRows.Height > 0) { - graphics.FillRectangle(this.backgroundBrush, rcBelowRows); + graphics.FillRectangle(backgroundBrush, rcBelowRows); } // Paint potential block next to column headers and rows // Remaining cell images on DataGridView - int visibleColumnsWidth = this.Columns.GetColumnsWidth(DataGridViewElementStates.Displayed); + int visibleColumnsWidth = Columns.GetColumnsWidth(DataGridViewElementStates.Displayed); Rectangle rcNextRows = gridBounds; - if (this.Columns.Count > 0) + if (Columns.Count > 0) { - if (this.layout.RowHeadersVisible) + if (layout.RowHeadersVisible) { - if (!this.RightToLeftInternal) + if (!RightToLeftInternal) { - rcNextRows.X += this.layout.RowHeaders.Width; + rcNextRows.X += layout.RowHeaders.Width; } - rcNextRows.Width -= this.layout.RowHeaders.Width; + rcNextRows.Width -= layout.RowHeaders.Width; } - else if (this.SingleVerticalBorderAdded && visibleColumnsWidth > 0) + else if (SingleVerticalBorderAdded && visibleColumnsWidth > 0) { - if (!this.RightToLeftInternal) + if (!RightToLeftInternal) { rcNextRows.X++; } rcNextRows.Width--; } } - int rowsWidth = visibleColumnsWidth - this.horizontalOffset; - if (!this.RightToLeftInternal) + int rowsWidth = visibleColumnsWidth - horizontalOffset; + if (!RightToLeftInternal) { rcNextRows.X += rowsWidth; } @@ -19589,7 +19589,7 @@ protected virtual void PaintBackground(Graphics graphics, Rectangle clipBounds, } if (rcNextRows.Width > 0 && rcNextRows.Height > 0) { - graphics.FillRectangle(this.backgroundBrush, rcNextRows); + graphics.FillRectangle(backgroundBrush, rcNextRows); } } @@ -19597,12 +19597,12 @@ private void PaintBorder(Graphics g, Rectangle clipRect, Rectangle bounds) { Debug.Assert(bounds.Left == 0); Debug.Assert(bounds.Top == 0); - if (this.BorderStyle == BorderStyle.None) + if (BorderStyle == BorderStyle.None) { return; } bool paintingNeeded = false; - int borderWidth = this.BorderWidth; + int borderWidth = BorderWidth; // Does the clipRect intersect with the top edge? Rectangle edge = new Rectangle(0, 0, bounds.Width, borderWidth); paintingNeeded = clipRect.IntersectsWith(edge); @@ -19629,7 +19629,7 @@ private void PaintBorder(Graphics g, Rectangle clipRect, Rectangle bounds) if (paintingNeeded) { - if (this.BorderStyle == BorderStyle.Fixed3D) + if (BorderStyle == BorderStyle.Fixed3D) { if (Application.RenderWithVisualStyles) { @@ -19641,7 +19641,7 @@ private void PaintBorder(Graphics g, Rectangle clipRect, Rectangle bounds) ControlPaint.DrawBorder3D(g, bounds, Border3DStyle.Sunken); } } - else if (this.BorderStyle == BorderStyle.FixedSingle) + else if (BorderStyle == BorderStyle.FixedSingle) { Pen pen = GetCachedPen(SystemColors.ControlText); g.DrawRectangle(pen, new Rectangle(0, 0, bounds.Width - 1, bounds.Height - 1)); @@ -19655,11 +19655,11 @@ private void PaintBorder(Graphics g, Rectangle clipRect, Rectangle bounds) private void PaintColumnHeaders(Graphics g, Rectangle clipBounds, bool singleBorderAdded) { - if (g.IsVisible(this.layout.ColumnHeaders)) + if (g.IsVisible(layout.ColumnHeaders)) { Rectangle bandBounds, cellBounds; - bandBounds = cellBounds = this.layout.ColumnHeaders; - bandBounds.Height = cellBounds.Height = this.columnHeadersHeight; + bandBounds = cellBounds = layout.ColumnHeaders; + bandBounds.Height = cellBounds.Height = columnHeadersHeight; int cx = 0; bool isFirstDisplayedColumn = true, isLastVisibleColumn = false; DataGridViewCell cell; @@ -19668,7 +19668,7 @@ private void PaintColumnHeaders(Graphics g, Rectangle clipBounds, bool singleBor DataGridViewColumn dataGridViewColumnNext = null; // first paint the visible frozen columns - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); while (dataGridViewColumn != null) { cell = dataGridViewColumn.HeaderCell; @@ -19678,7 +19678,7 @@ private void PaintColumnHeaders(Graphics g, Rectangle clipBounds, bool singleBor cellBounds.Width++; } Debug.Assert(cellBounds.Width > 0); - if (this.RightToLeftInternal) + if (RightToLeftInternal) { cellBounds.X = bandBounds.Right - cx - cellBounds.Width; } @@ -19689,15 +19689,15 @@ private void PaintColumnHeaders(Graphics g, Rectangle clipBounds, bool singleBor BuildInheritedColumnHeaderCellStyle(inheritedCellStyle, cell); - dataGridViewColumnNext = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumnNext = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen, DataGridViewElementStates.None); if (dataGridViewColumnNext == null) { - isLastVisibleColumn = (this.displayedBandsInfo.FirstDisplayedScrollingCol < 0); + isLastVisibleColumn = (displayedBandsInfo.FirstDisplayedScrollingCol < 0); } - dgvabsEffective = AdjustColumnHeaderBorderStyle(this.AdvancedColumnHeadersBorderStyle, dataGridViewAdvancedBorderStylePlaceholder, + dgvabsEffective = AdjustColumnHeaderBorderStyle(AdvancedColumnHeadersBorderStyle, dataGridViewAdvancedBorderStylePlaceholder, isFirstDisplayedColumn, isLastVisibleColumn); // Microsoft: should paintSelectionBackground be dev-settable? @@ -19722,20 +19722,20 @@ private void PaintColumnHeaders(Graphics g, Rectangle clipBounds, bool singleBor // then paint the visible scrolling ones Rectangle scrollingBounds = bandBounds; - if (!this.RightToLeftInternal) + if (!RightToLeftInternal) { - scrollingBounds.X -= this.negOffset; + scrollingBounds.X -= negOffset; } - scrollingBounds.Width += this.negOffset; + scrollingBounds.Width += negOffset; - if (this.displayedBandsInfo.FirstDisplayedScrollingCol >= 0 && cx < scrollingBounds.Width) + if (displayedBandsInfo.FirstDisplayedScrollingCol >= 0 && cx < scrollingBounds.Width) { Region clipRegion = null; - if (this.negOffset > 0) + if (negOffset > 0) { clipRegion = g.Clip; Rectangle rowRect = bandBounds; - if (!this.RightToLeftInternal) + if (!RightToLeftInternal) { rowRect.X += cx; } @@ -19743,7 +19743,7 @@ private void PaintColumnHeaders(Graphics g, Rectangle clipBounds, bool singleBor g.SetClip(rowRect); } - dataGridViewColumn = this.Columns[this.displayedBandsInfo.FirstDisplayedScrollingCol]; + dataGridViewColumn = Columns[displayedBandsInfo.FirstDisplayedScrollingCol]; while (dataGridViewColumn != null) { Debug.Assert(dataGridViewColumn.Visible && !dataGridViewColumn.Frozen); @@ -19755,7 +19755,7 @@ private void PaintColumnHeaders(Graphics g, Rectangle clipBounds, bool singleBor cellBounds.Width++; } Debug.Assert(cellBounds.Width > 0); - if (this.RightToLeftInternal) + if (RightToLeftInternal) { cellBounds.X = scrollingBounds.Right - cx - cellBounds.Width; } @@ -19766,12 +19766,12 @@ private void PaintColumnHeaders(Graphics g, Rectangle clipBounds, bool singleBor BuildInheritedColumnHeaderCellStyle(inheritedCellStyle, cell); - dataGridViewColumnNext = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumnNext = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None); isLastVisibleColumn = (dataGridViewColumnNext == null); - dgvabsEffective = AdjustColumnHeaderBorderStyle(this.AdvancedColumnHeadersBorderStyle, dataGridViewAdvancedBorderStylePlaceholder, + dgvabsEffective = AdjustColumnHeaderBorderStyle(AdvancedColumnHeadersBorderStyle, dataGridViewAdvancedBorderStylePlaceholder, isFirstDisplayedColumn, isLastVisibleColumn); cell.PaintWork(g, @@ -19793,7 +19793,7 @@ private void PaintColumnHeaders(Graphics g, Rectangle clipBounds, bool singleBor isFirstDisplayedColumn = false; } - if (this.negOffset > 0) + if (negOffset > 0) { Debug.Assert(clipRegion != null); g.Clip = clipRegion; @@ -19811,29 +19811,29 @@ private void PaintGrid(Graphics g, { Rectangle rc = gridBounds; - if (this.layout.TopLeftHeader.Width > 0 && - (clipRect.IntersectsWith(this.layout.TopLeftHeader) || this.lastHeaderShadow != -1)) + if (layout.TopLeftHeader.Width > 0 && + (clipRect.IntersectsWith(layout.TopLeftHeader) || lastHeaderShadow != -1)) { - if (this.Columns.Count > 0 || this.Rows.Count > 0) + if (Columns.Count > 0 || Rows.Count > 0) { using (Region clipRegion = g.Clip) { - g.SetClip(this.layout.TopLeftHeader); + g.SetClip(layout.TopLeftHeader); PaintTopLeftHeaderCell(g); g.Clip = clipRegion; } } } - if (this.layout.ColumnHeadersVisible) + if (layout.ColumnHeadersVisible) { Rectangle columnHeadersClip = new Rectangle(); - columnHeadersClip = this.layout.ColumnHeaders; + columnHeadersClip = layout.ColumnHeaders; if (singleVerticalBorderAdded) { columnHeadersClip.Width++; } - if (clipRect.IntersectsWith(columnHeadersClip) || this.lastHeaderShadow != -1) + if (clipRect.IntersectsWith(columnHeadersClip) || lastHeaderShadow != -1) { using (Region clipRegion = g.Clip) { @@ -19842,13 +19842,13 @@ private void PaintGrid(Graphics g, g.Clip = clipRegion; } } - int columnHeadersHeight = this.layout.ColumnHeaders.Height; + int columnHeadersHeight = layout.ColumnHeaders.Height; rc.Y += columnHeadersHeight; rc.Height -= columnHeadersHeight; - if (this.lastHeaderShadow != -1) + if (lastHeaderShadow != -1) { - DrawColHeaderShadow(g, this.lastHeaderShadow); + DrawColHeaderShadow(g, lastHeaderShadow); } } @@ -19857,17 +19857,17 @@ private void PaintGrid(Graphics g, PaintRows(g, rc, clipRect, /*singleVerticalBorderAdded, */ singleHorizontalBorderAdded); } - if (this.currentRowSplitBar != -1) + if (currentRowSplitBar != -1) { - Debug.Assert(this.dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize] || this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowResize]); - DrawRowSplitBar(this.currentRowSplitBar); + Debug.Assert(dataGridViewOper[DATAGRIDVIEWOPER_trackColHeadersResize] || dataGridViewOper[DATAGRIDVIEWOPER_trackRowResize]); + DrawRowSplitBar(currentRowSplitBar); } - else if (this.currentColSplitBar != -1) + else if (currentColSplitBar != -1) { - Debug.Assert(this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize] || - this.dataGridViewOper[DATAGRIDVIEWOPER_trackColResize] || - this.dataGridViewOper[DATAGRIDVIEWOPER_trackKeyboardColResize]); - DrawColSplitBar(this.currentColSplitBar); + Debug.Assert(dataGridViewOper[DATAGRIDVIEWOPER_trackRowHeadersResize] || + dataGridViewOper[DATAGRIDVIEWOPER_trackColResize] || + dataGridViewOper[DATAGRIDVIEWOPER_trackKeyboardColResize]); + DrawColSplitBar(currentColSplitBar); } } @@ -19884,7 +19884,7 @@ private void PaintRows(Graphics g, int indexTmp, indexTmpNext; // paint visible none-scrolling rows - indexTmp = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + indexTmp = Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); while (indexTmp != -1) { rowBounds = boundingRect; @@ -19893,35 +19893,35 @@ private void PaintRows(Graphics g, // Should unshared the row and set the thickness to a perfect value // every time user scroll to display the specific row. - DataGridViewAutoSizeRowsModeInternal autoSizeRowsModeInternal = (DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode; + DataGridViewAutoSizeRowsModeInternal autoSizeRowsModeInternal = (DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode; // Auto size row if needed if (autoSizeRowsModeInternal != DataGridViewAutoSizeRowsModeInternal.None) { // this call may unshare the row. - int rowHeight = this.Rows.SharedRow(indexTmp).GetHeight(indexTmp); - this.Rows.SharedRow(indexTmp).CachedThickness = rowHeight; - AutoResizeRowInternal(indexTmp, MapAutoSizeRowsModeToRowMode(this.autoSizeRowsMode), false /*fixedWidth*/, true /*internalAutosizing*/); + int rowHeight = Rows.SharedRow(indexTmp).GetHeight(indexTmp); + Rows.SharedRow(indexTmp).CachedThickness = rowHeight; + AutoResizeRowInternal(indexTmp, MapAutoSizeRowsModeToRowMode(autoSizeRowsMode), false /*fixedWidth*/, true /*internalAutosizing*/); } - rowBounds.Height = this.Rows.SharedRow(indexTmp).GetHeight(indexTmp); + rowBounds.Height = Rows.SharedRow(indexTmp).GetHeight(indexTmp); if (isFirstDisplayedRow && singleHorizontalBorderAdded) { rowBounds.Height++; } rowBounds.Y = boundingRect.Y + cy; - indexTmpNext = this.Rows.GetNextRow(indexTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + indexTmpNext = Rows.GetNextRow(indexTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); if (clipRect.IntersectsWith(rowBounds)) { - dataGridViewRow = this.Rows.SharedRow(indexTmp); + dataGridViewRow = Rows.SharedRow(indexTmp); dataGridViewRow.Paint(g, clipRect, rowBounds, indexTmp, - this.Rows.GetRowState(indexTmp), + Rows.GetRowState(indexTmp), isFirstDisplayedRow, - (indexTmpNext == -1) && (this.displayedBandsInfo.FirstDisplayedScrollingRow == -1)); + (indexTmpNext == -1) && (displayedBandsInfo.FirstDisplayedScrollingRow == -1)); } cy += rowBounds.Height; if (cy >= boundingRect.Height) @@ -19933,11 +19933,11 @@ private void PaintRows(Graphics g, } // paint scrolling rows - if (this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0 && cy < boundingRect.Height) + if (displayedBandsInfo.FirstDisplayedScrollingRow >= 0 && cy < boundingRect.Height) { - indexTmp = this.displayedBandsInfo.FirstDisplayedScrollingRow; - Debug.Assert((this.Rows.GetRowState(indexTmp) & DataGridViewElementStates.Frozen) == 0); - Debug.Assert((this.Rows.GetRowState(indexTmp) & DataGridViewElementStates.Visible) != 0); + indexTmp = displayedBandsInfo.FirstDisplayedScrollingRow; + Debug.Assert((Rows.GetRowState(indexTmp) & DataGridViewElementStates.Frozen) == 0); + Debug.Assert((Rows.GetRowState(indexTmp) & DataGridViewElementStates.Visible) != 0); while (indexTmp != -1) { rowBounds = boundingRect; @@ -19946,33 +19946,33 @@ private void PaintRows(Graphics g, // Should unshared the row and set the thickness to a perfect value // every time user scroll to display the specific row. - DataGridViewAutoSizeRowsModeInternal autoSizeRowsModeInternal = (DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode; + DataGridViewAutoSizeRowsModeInternal autoSizeRowsModeInternal = (DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode; // Auto size row if needed if (autoSizeRowsModeInternal != DataGridViewAutoSizeRowsModeInternal.None) { // this call may unshare the row. - int rowHeight = this.Rows.SharedRow(indexTmp).GetHeight(indexTmp); - this.Rows.SharedRow(indexTmp).CachedThickness = rowHeight; - AutoResizeRowInternal(indexTmp, MapAutoSizeRowsModeToRowMode(this.autoSizeRowsMode), false /*fixedWidth*/, true /*internalAutosizing*/); + int rowHeight = Rows.SharedRow(indexTmp).GetHeight(indexTmp); + Rows.SharedRow(indexTmp).CachedThickness = rowHeight; + AutoResizeRowInternal(indexTmp, MapAutoSizeRowsModeToRowMode(autoSizeRowsMode), false /*fixedWidth*/, true /*internalAutosizing*/); } - rowBounds.Height = this.Rows.SharedRow(indexTmp).GetHeight(indexTmp); + rowBounds.Height = Rows.SharedRow(indexTmp).GetHeight(indexTmp); if (isFirstDisplayedRow && singleHorizontalBorderAdded) { rowBounds.Height++; } rowBounds.Y = boundingRect.Y + cy; - indexTmpNext = this.Rows.GetNextRow(indexTmp, DataGridViewElementStates.Visible); + indexTmpNext = Rows.GetNextRow(indexTmp, DataGridViewElementStates.Visible); if (clipRect.IntersectsWith(rowBounds)) { - dataGridViewRow = this.Rows.SharedRow(indexTmp); + dataGridViewRow = Rows.SharedRow(indexTmp); dataGridViewRow.Paint(g, clipRect, rowBounds, indexTmp, - this.Rows.GetRowState(indexTmp), + Rows.GetRowState(indexTmp), isFirstDisplayedRow, indexTmpNext == -1); } @@ -19989,22 +19989,22 @@ private void PaintRows(Graphics g, private void PaintTopLeftHeaderCell(Graphics g) { - if (g.IsVisible(this.layout.TopLeftHeader)) + if (g.IsVisible(layout.TopLeftHeader)) { - DataGridViewCell cell = this.TopLeftHeaderCell; + DataGridViewCell cell = TopLeftHeaderCell; DataGridViewCellStyle inheritedCellStyle = new DataGridViewCellStyle(); BuildInheritedColumnHeaderCellStyle(inheritedCellStyle, cell); - Rectangle cellBounds = this.layout.TopLeftHeader; - cellBounds.Width = this.rowHeadersWidth; - cellBounds.Height = this.columnHeadersHeight; + Rectangle cellBounds = layout.TopLeftHeader; + cellBounds.Width = rowHeadersWidth; + cellBounds.Height = columnHeadersHeight; // Microsoft: Should paintSelectionBackground be dev-settable? cell.PaintWork(g, - this.layout.TopLeftHeader, + layout.TopLeftHeader, cellBounds, -1, cell.State, inheritedCellStyle, - this.AdjustedTopLeftHeaderBorderStyle, + AdjustedTopLeftHeaderBorderStyle, DataGridViewPaintParts.Background | DataGridViewPaintParts.Border | DataGridViewPaintParts.ContentBackground | DataGridViewPaintParts.ContentForeground | DataGridViewPaintParts.ErrorIcon | DataGridViewPaintParts.SelectionBackground); } } @@ -20014,15 +20014,15 @@ private void PerformLayoutPrivate(bool useRowShortcut, bool invalidInAdjustFillingColumns, bool repositionEditingControl) { - this.inPerformLayoutCount++; + inPerformLayoutCount++; try { - if (invalidInAdjustFillingColumns && this.InAdjustFillingColumns) + if (invalidInAdjustFillingColumns && InAdjustFillingColumns) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotAlterAutoFillColumnParameter)); } - if (this.IsHandleCreated) + if (IsHandleCreated) { bool columnsAdjusted = false; if (useRowShortcut) @@ -20034,47 +20034,47 @@ private void PerformLayoutPrivate(bool useRowShortcut, columnsAdjusted = ComputeLayout(); } FlushDisplayedChanged(); - if (columnsAdjusted && this.inPerformLayoutCount < 3) + if (columnsAdjusted && inPerformLayoutCount < 3) { // Some columns were auto-filled, the rows and column headers may need to be autosized. - if ((((DataGridViewAutoSizeRowsModeInternal)this.autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0) + if ((((DataGridViewAutoSizeRowsModeInternal)autoSizeRowsMode) & DataGridViewAutoSizeRowsModeInternal.AllColumns) != 0) { - AdjustShrinkingRows(this.autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); + AdjustShrinkingRows(autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); } - if (this.ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) + if (ColumnHeadersHeightSizeMode == DataGridViewColumnHeadersHeightSizeMode.AutoSize) { AutoResizeColumnHeadersHeight(true /*fixedRowHeadersWidth*/, true /*fixedColumnWidth*/); } } - if (repositionEditingControl && this.editingControl != null) + if (repositionEditingControl && editingControl != null) { PositionEditingControl(true /*setLocation*/, false /*setSize*/, false /*setFocus*/); } } else { - this.displayedBandsInfo.FirstDisplayedFrozenCol = -1; - this.displayedBandsInfo.FirstDisplayedFrozenRow = -1; - this.displayedBandsInfo.FirstDisplayedScrollingRow = -1; - this.displayedBandsInfo.FirstDisplayedScrollingCol = -1; - this.displayedBandsInfo.NumDisplayedFrozenRows = 0; - this.displayedBandsInfo.NumDisplayedFrozenCols = 0; - this.displayedBandsInfo.NumDisplayedScrollingRows = 0; - this.displayedBandsInfo.NumDisplayedScrollingCols = 0; - this.displayedBandsInfo.NumTotallyDisplayedFrozenRows = 0; - this.displayedBandsInfo.NumTotallyDisplayedScrollingRows = 0; - this.displayedBandsInfo.LastDisplayedScrollingRow = -1; - this.displayedBandsInfo.LastTotallyDisplayedScrollingCol = -1; - if (this.layout != null) + displayedBandsInfo.FirstDisplayedFrozenCol = -1; + displayedBandsInfo.FirstDisplayedFrozenRow = -1; + displayedBandsInfo.FirstDisplayedScrollingRow = -1; + displayedBandsInfo.FirstDisplayedScrollingCol = -1; + displayedBandsInfo.NumDisplayedFrozenRows = 0; + displayedBandsInfo.NumDisplayedFrozenCols = 0; + displayedBandsInfo.NumDisplayedScrollingRows = 0; + displayedBandsInfo.NumDisplayedScrollingCols = 0; + displayedBandsInfo.NumTotallyDisplayedFrozenRows = 0; + displayedBandsInfo.NumTotallyDisplayedScrollingRows = 0; + displayedBandsInfo.LastDisplayedScrollingRow = -1; + displayedBandsInfo.LastTotallyDisplayedScrollingCol = -1; + if (layout != null) { - this.layout.dirty = true; + layout.dirty = true; } } } finally { - this.inPerformLayoutCount--; - Debug.Assert(this.inPerformLayoutCount >= 0); + inPerformLayoutCount--; + Debug.Assert(inPerformLayoutCount >= 0); } } @@ -20083,73 +20083,73 @@ private void PerformLayoutPrivate(bool useRowShortcut, ] private void PopulateNewRowWithDefaultValues() { - if (this.newRowIndex != -1) + if (newRowIndex != -1) { - DataGridViewRow newRow = this.Rows.SharedRow(this.newRowIndex); + DataGridViewRow newRow = Rows.SharedRow(newRowIndex); DataGridViewCellCollection newRowCells = newRow.Cells; foreach (DataGridViewCell dataGridViewCell in newRowCells) { if (dataGridViewCell.DefaultNewRowValue != null) { - newRow = this.Rows[this.newRowIndex]; // unshare the 'new row'. + newRow = Rows[newRowIndex]; // unshare the 'new row'. newRowCells = newRow.Cells; break; } } foreach (DataGridViewCell dataGridViewCell in newRowCells) { - dataGridViewCell.SetValueInternal(this.newRowIndex, dataGridViewCell.DefaultNewRowValue); + dataGridViewCell.SetValueInternal(newRowIndex, dataGridViewCell.DefaultNewRowValue); } } } private void PositionEditingControl(bool setLocation, bool setSize, bool setFocus) { - Debug.Assert(this.editingControl != null); + Debug.Assert(editingControl != null); - if (!this.IsHandleCreated) + if (!IsHandleCreated) { return; } #if DEBUG - DataGridViewCell dataGridViewCell = this.CurrentCellInternal; + DataGridViewCell dataGridViewCell = CurrentCellInternal; Debug.Assert(dataGridViewCell != null); - Debug.Assert(dataGridViewCell.ColumnIndex == this.ptCurrentCell.X); - Debug.Assert(dataGridViewCell.RowIndex == this.ptCurrentCell.Y || dataGridViewCell.RowIndex == -1); + Debug.Assert(dataGridViewCell.ColumnIndex == ptCurrentCell.X); + Debug.Assert(dataGridViewCell.RowIndex == ptCurrentCell.Y || dataGridViewCell.RowIndex == -1); #endif - Rectangle editingZone = this.layout.Data; + Rectangle editingZone = layout.Data; if (editingZone.Width == 0 || editingZone.Height == 0) { return; } - this.dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlChanging] = true; + dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlChanging] = true; try { - int leftEdge = GetColumnXFromIndex(this.ptCurrentCell.X); - if (this.RightToLeftInternal) + int leftEdge = GetColumnXFromIndex(ptCurrentCell.X); + if (RightToLeftInternal) { - leftEdge -= this.Columns[this.ptCurrentCell.X].Width - 1; + leftEdge -= Columns[ptCurrentCell.X].Width - 1; } - Rectangle cellBounds = new Rectangle(leftEdge, GetRowYFromIndex(this.ptCurrentCell.Y), - this.Columns[this.ptCurrentCell.X].Width, this.Rows.SharedRow(this.ptCurrentCell.Y).GetHeight(this.ptCurrentCell.Y)); + Rectangle cellBounds = new Rectangle(leftEdge, GetRowYFromIndex(ptCurrentCell.Y), + Columns[ptCurrentCell.X].Width, Rows.SharedRow(ptCurrentCell.Y).GetHeight(ptCurrentCell.Y)); Rectangle cellClip = cellBounds; // Need to clip the zones of the frozen columns and rows and headers. - if (!this.Columns[this.ptCurrentCell.X].Frozen) + if (!Columns[ptCurrentCell.X].Frozen) { - int totalVisibleFrozenWidth = this.Columns.GetColumnsWidth(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); - if (!this.RightToLeftInternal) + int totalVisibleFrozenWidth = Columns.GetColumnsWidth(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + if (!RightToLeftInternal) { editingZone.X += totalVisibleFrozenWidth; } editingZone.Width = Math.Max(0, editingZone.Width - totalVisibleFrozenWidth); } - if ((this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Frozen) == 0) + if ((Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Frozen) == 0) { - int totalVisibleFrozenHeight = this.Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int totalVisibleFrozenHeight = Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); editingZone.Y += totalVisibleFrozenHeight; } cellClip.Intersect(editingZone); @@ -20159,20 +20159,20 @@ private void PositionEditingControl(bool setLocation, bool setSize, bool setFocu // we cannot simply make the control invisible because we want it to keep the focus. // (and Control::CanFocus returns false if the control is not visible). // So we place the editing control to the right of the DataGridView. - Debug.Assert(this.editingControl != null); - this.editingPanel.Location = new Point(this.Width + 1, 0); - this.dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlHidden] = true; + Debug.Assert(editingControl != null); + editingPanel.Location = new Point(Width + 1, 0); + dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlHidden] = true; } else { - bool singleVerticalBorderAdded = this.SingleVerticalBorderAdded; - bool singleHorizontalBorderAdded = this.SingleHorizontalBorderAdded; - bool isFirstDisplayedColumn = this.FirstDisplayedColumnIndex == this.ptCurrentCell.X; - bool isFirstDisplayedRow = this.FirstDisplayedRowIndex == this.ptCurrentCell.Y; + bool singleVerticalBorderAdded = SingleVerticalBorderAdded; + bool singleHorizontalBorderAdded = SingleHorizontalBorderAdded; + bool isFirstDisplayedColumn = FirstDisplayedColumnIndex == ptCurrentCell.X; + bool isFirstDisplayedRow = FirstDisplayedRowIndex == ptCurrentCell.Y; if (singleVerticalBorderAdded && isFirstDisplayedColumn) { - if (!this.RightToLeftInternal) + if (!RightToLeftInternal) { cellBounds.X--; cellClip.X--; @@ -20188,15 +20188,15 @@ private void PositionEditingControl(bool setLocation, bool setSize, bool setFocu cellClip.Height++; } - this.CurrentCellInternal.PositionEditingControl( - setLocation || this.dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlHidden], - setSize || this.dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlHidden], - cellBounds, cellClip, this.InheritedEditingCellStyle, + CurrentCellInternal.PositionEditingControl( + setLocation || dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlHidden], + setSize || dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlHidden], + cellBounds, cellClip, InheritedEditingCellStyle, singleVerticalBorderAdded, singleHorizontalBorderAdded, isFirstDisplayedColumn, isFirstDisplayedRow); - this.dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlHidden] = false; + dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlHidden] = false; } - this.editingPanel.Visible = true; + editingPanel.Visible = true; if (setFocus) { CorrectFocus(false /*onlyIfGridHasFocus*/); @@ -20204,14 +20204,14 @@ private void PositionEditingControl(bool setLocation, bool setSize, bool setFocu } finally { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlChanging] = false; + dataGridViewState1[DATAGRIDVIEWSTATE1_editingControlChanging] = false; } } protected bool ProcessAKey(Keys keyData) { if ((keyData & (Keys.Shift | Keys.Control | Keys.Alt)) == Keys.Control && - this.MultiSelect) + MultiSelect) { SelectAll(); return true; @@ -20224,45 +20224,45 @@ protected bool ProcessAKey(Keys keyData) ] protected bool ProcessDeleteKey(Keys keyData) { - if (this.AllowUserToDeleteRowsInternal) + if (AllowUserToDeleteRowsInternal) { - if (this.editingControl != null) + if (editingControl != null) { // editing control gets a chance to handle the Delete key first return false; } - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: int remainingSelectedRows = 0; try { - this.selectedBandSnapshotIndexes = new DataGridViewIntLinkedList(this.selectedBandIndexes); - while (this.selectedBandSnapshotIndexes.Count > remainingSelectedRows) + selectedBandSnapshotIndexes = new DataGridViewIntLinkedList(selectedBandIndexes); + while (selectedBandSnapshotIndexes.Count > remainingSelectedRows) { - int rowIndex = this.selectedBandSnapshotIndexes[remainingSelectedRows]; + int rowIndex = selectedBandSnapshotIndexes[remainingSelectedRows]; Debug.Assert(rowIndex >= 0); - if (rowIndex == this.newRowIndex || rowIndex >= this.Rows.Count) + if (rowIndex == newRowIndex || rowIndex >= Rows.Count) { remainingSelectedRows++; } else { - DataGridViewRowCancelEventArgs dgvrce = new DataGridViewRowCancelEventArgs(this.Rows[rowIndex]); + DataGridViewRowCancelEventArgs dgvrce = new DataGridViewRowCancelEventArgs(Rows[rowIndex]); OnUserDeletingRow(dgvrce); if (!dgvrce.Cancel) { - DataGridViewRow dataGridViewRow = this.Rows[rowIndex]; - if (this.DataSource != null) + DataGridViewRow dataGridViewRow = Rows[rowIndex]; + if (DataSource != null) { - int dataGridRowsCount = this.Rows.Count; + int dataGridRowsCount = Rows.Count; #if DEBUG - int dataGridViewRowsCount = this.Rows.Count; // the number of rows in the dataGridView row collection not counting the AddNewRow - int rowCount = this.dataConnection.CurrencyManager.List.Count; - if (this.AllowUserToAddRowsInternal) + int dataGridViewRowsCount = Rows.Count; // the number of rows in the dataGridView row collection not counting the AddNewRow + int rowCount = dataConnection.CurrencyManager.List.Count; + if (AllowUserToAddRowsInternal) { - if (this.newRowIndex < rowCount) + if (newRowIndex < rowCount) { // the user did not type inside the 'add new row' Debug.Assert(rowCount == dataGridViewRowsCount, "out of sync in AddNewTransaction when the user did not type in the 'add new row'"); @@ -20278,7 +20278,7 @@ protected bool ProcessDeleteKey(Keys keyData) DataGridViewDataErrorEventArgs dgvdee = null; try { - this.DataConnection.DeleteRow(rowIndex); + DataConnection.DeleteRow(rowIndex); } catch (Exception exception) { @@ -20308,7 +20308,7 @@ protected bool ProcessDeleteKey(Keys keyData) } } - if (dataGridRowsCount != this.Rows.Count) + if (dataGridRowsCount != Rows.Count) { Debug.Assert(dataGridViewRow.Index == -1); DataGridViewRowEventArgs dgvre = new DataGridViewRowEventArgs(dataGridViewRow); @@ -20321,7 +20321,7 @@ protected bool ProcessDeleteKey(Keys keyData) } else { - this.Rows.RemoveAtInternal(rowIndex, false /*force*/); + Rows.RemoveAtInternal(rowIndex, false /*force*/); Debug.Assert(dataGridViewRow.Index == -1); DataGridViewRowEventArgs dgvre = new DataGridViewRowEventArgs(dataGridViewRow); OnUserDeletedRow(dgvre); @@ -20336,7 +20336,7 @@ protected bool ProcessDeleteKey(Keys keyData) } finally { - this.selectedBandSnapshotIndexes = null; + selectedBandSnapshotIndexes = null; } return true; } @@ -20363,18 +20363,18 @@ protected override bool ProcessDialogKey(Keys keyData) } else if (key == Keys.Escape) { - bool keyEffective = this.IsEscapeKeyEffective; + bool keyEffective = IsEscapeKeyEffective; bool ret = base.ProcessDialogKey(keyData); if (!keyEffective) { // This call may perform Click of Cancel button of form. - if (this.Focused) + if (Focused) { // Make sure the current cell is in editing mode if needed. - if (this.ptCurrentCell.X > -1 && - !this.IsCurrentCellInEditMode && - (this.EditMode == DataGridViewEditMode.EditOnEnter || - (this.EditMode != DataGridViewEditMode.EditProgrammatically && this.CurrentCellInternal.EditType == null))) + if (ptCurrentCell.X > -1 && + !IsCurrentCellInEditMode && + (EditMode == DataGridViewEditMode.EditOnEnter || + (EditMode != DataGridViewEditMode.EditProgrammatically && CurrentCellInternal.EditType == null))) { BeginEditInternal(true /*selectAll*/); } @@ -20404,9 +20404,9 @@ protected override bool ProcessDialogKey(Keys keyData) } else { - if (this.editingControl != null) + if (editingControl != null) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_leavingWithTabKey] = true; + dataGridViewState1[DATAGRIDVIEWSTATE1_leavingWithTabKey] = true; if (!EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.LeaveControl, DataGridViewValidateCellInternal.Always, true /*fireCellLeave*/, @@ -20427,7 +20427,7 @@ protected override bool ProcessDialogKey(Keys keyData) ret = base.ProcessDialogKey(keyData); - if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_leavingWithTabKey] && this.Focused) + if (dataGridViewState1[DATAGRIDVIEWSTATE1_leavingWithTabKey] && Focused) { // There was no other control to tab to. The CellLeave, RowLeave, Leave events were raised. // Since the DataGridView control still has the focus, Enter, RowEnter, CellEnter events need to be raised. @@ -20449,25 +20449,25 @@ protected bool ProcessDownKey(Keys keyData) private bool ProcessDownKeyInternal(Keys keyData, out bool moved) { bool success; - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); int firstVisibleColumnIndex = (dataGridViewColumn == null) ? -1 : dataGridViewColumn.Index; - int lastVisibleRowIndex = this.Rows.GetLastRow(DataGridViewElementStates.Visible); + int lastVisibleRowIndex = Rows.GetLastRow(DataGridViewElementStates.Visible); if (firstVisibleColumnIndex == -1 || lastVisibleRowIndex == -1) { moved = false; return false; } int nextVisibleRowIndex = -1; - if (this.ptCurrentCell.Y != -1) + if (ptCurrentCell.Y != -1) { - nextVisibleRowIndex = this.Rows.GetNextRow(this.ptCurrentCell.Y, DataGridViewElementStates.Visible); + nextVisibleRowIndex = Rows.GetNextRow(ptCurrentCell.Y, DataGridViewElementStates.Visible); } moved = true; - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: @@ -20475,7 +20475,7 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) { if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, lastVisibleRowIndex, true); @@ -20498,26 +20498,26 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) } else { - if (this.MultiSelect) + if (MultiSelect) { - if (!ScrollIntoView(this.ptCurrentCell.X, lastVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, lastVisibleRowIndex, true)) { return true; } //ClearSelection(); - Debug.Assert(this.ptAnchorCell.Y >= 0); + Debug.Assert(ptAnchorCell.Y >= 0); //SelectCellRange(this.ptCurrentCell.X, this.ptAnchorCell.Y, this.ptCurrentCell.X, lastVisibleRowIndex, true); - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - if (this.ptCurrentCell.X == -1 || this.ptAnchorCell.X == -1 || + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + if (ptCurrentCell.X == -1 || ptAnchorCell.X == -1 || IsRowOutOfBounds(lastVisibleRowIndex)) { moved = false; return true; } - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, lastVisibleRowIndex); - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, lastVisibleRowIndex, false, false, false); + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, lastVisibleRowIndex); + success = SetCurrentCellAddressCore(ptCurrentCell.X, lastVisibleRowIndex, false, false, false); if (!success) { moved = false; @@ -20525,19 +20525,19 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) } else { - if (!ScrollIntoView(this.ptCurrentCell.X, lastVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, lastVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(lastVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(lastVisibleRowIndex)) { moved = false; return true; } //SetSelectedCellCore(this.ptCurrentCell.X, this.ptCurrentCell.Y, false); ClearSelection(); - SetSelectedCellCore(this.ptCurrentCell.X, lastVisibleRowIndex, true); - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, lastVisibleRowIndex, true, false, false); + SetSelectedCellCore(ptCurrentCell.X, lastVisibleRowIndex, true); + success = SetCurrentCellAddressCore(ptCurrentCell.X, lastVisibleRowIndex, true, false, false); if (!success) { moved = false; @@ -20547,7 +20547,7 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, lastVisibleRowIndex, true); @@ -20566,18 +20566,18 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) } else { - if (!ScrollIntoView(this.ptCurrentCell.X, lastVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, lastVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(lastVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(lastVisibleRowIndex)) { moved = false; return true; } ClearSelection(); - SetSelectedCellCore(this.ptCurrentCell.X, lastVisibleRowIndex, true); - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, lastVisibleRowIndex, true, false, false); + SetSelectedCellCore(ptCurrentCell.X, lastVisibleRowIndex, true); + success = SetCurrentCellAddressCore(ptCurrentCell.X, lastVisibleRowIndex, true, false, false); if (!success) { moved = false; @@ -20589,7 +20589,7 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) { if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, lastVisibleRowIndex, true); @@ -20613,34 +20613,34 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) moved = false; return true; } - if (!ScrollIntoView(this.ptCurrentCell.X, nextVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, nextVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(nextVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(nextVisibleRowIndex)) { moved = false; return true; } - if (this.MultiSelect) + if (MultiSelect) { //SelectCellUnorderedRange(this.ptCurrentCell.X, this.ptAnchorCell.Y, this.ptCurrentCell.X, nextVisibleRowIndex, true); - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - if (this.ptAnchorCell.X == -1) + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + if (ptAnchorCell.X == -1) { moved = false; return true; } - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, nextVisibleRowIndex); + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, nextVisibleRowIndex); } else { ClearSelection(); - SetSelectedCellCore(this.ptCurrentCell.X, nextVisibleRowIndex, true); + SetSelectedCellCore(ptCurrentCell.X, nextVisibleRowIndex, true); } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, nextVisibleRowIndex, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, nextVisibleRowIndex, !MultiSelect, false, false); if (!success) { moved = false; @@ -20649,7 +20649,7 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, lastVisibleRowIndex, true); @@ -20673,18 +20673,18 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) moved = false; return true; } - if (!ScrollIntoView(this.ptCurrentCell.X, nextVisibleRowIndex, true /*forCurrentCellChange*/)) + if (!ScrollIntoView(ptCurrentCell.X, nextVisibleRowIndex, true /*forCurrentCellChange*/)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(nextVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(nextVisibleRowIndex)) { moved = false; return true; } ClearSelection(); - SetSelectedCellCore(this.ptCurrentCell.X, nextVisibleRowIndex, true); - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, + SetSelectedCellCore(ptCurrentCell.X, nextVisibleRowIndex, true); + success = SetCurrentCellAddressCore(ptCurrentCell.X, nextVisibleRowIndex, true /*setAnchorCellAddress*/, false /*validateCurrentCell*/, @@ -20703,7 +20703,7 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) { if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedRowCore(lastVisibleRowIndex, true); @@ -20722,22 +20722,22 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) } else { - if (this.MultiSelect) + if (MultiSelect) { - if (!ScrollIntoView(this.ptCurrentCell.X, lastVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, lastVisibleRowIndex, true)) { return true; } - if (this.ptAnchorCell.Y == -1 || this.ptCurrentCell.X == -1 || + if (ptAnchorCell.Y == -1 || ptCurrentCell.X == -1 || IsRowOutOfBounds(lastVisibleRowIndex)) { moved = false; return true; } ClearSelection(); - Debug.Assert(this.ptAnchorCell.Y >= 0); - SelectRowRange(this.ptAnchorCell.Y, lastVisibleRowIndex, true); - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, lastVisibleRowIndex, false, false, false); + Debug.Assert(ptAnchorCell.Y >= 0); + SelectRowRange(ptAnchorCell.Y, lastVisibleRowIndex, true); + success = SetCurrentCellAddressCore(ptCurrentCell.X, lastVisibleRowIndex, false, false, false); if (!success) { moved = false; @@ -20745,18 +20745,18 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) } else { - if (!ScrollIntoView(this.ptCurrentCell.X, lastVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, lastVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(lastVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(lastVisibleRowIndex)) { moved = false; return true; } - SetSelectedRowCore(this.ptCurrentCell.Y, false); + SetSelectedRowCore(ptCurrentCell.Y, false); SetSelectedRowCore(lastVisibleRowIndex, true); - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, lastVisibleRowIndex, true, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, lastVisibleRowIndex, true, false, false); if (!success) { moved = false; @@ -20766,7 +20766,7 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedRowCore(lastVisibleRowIndex, true); @@ -20785,18 +20785,18 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) } else { - if (!ScrollIntoView(this.ptCurrentCell.X, lastVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, lastVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(lastVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(lastVisibleRowIndex)) { moved = false; return true; } ClearSelection(); SetSelectedRowCore(lastVisibleRowIndex, true); - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, lastVisibleRowIndex, true, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, lastVisibleRowIndex, true, false, false); if (!success) { moved = false; @@ -20808,7 +20808,7 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) { if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedRowCore(lastVisibleRowIndex, true); @@ -20832,37 +20832,37 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) moved = false; return true; } - if (!ScrollIntoView(this.ptCurrentCell.X, nextVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, nextVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(nextVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(nextVisibleRowIndex)) { moved = false; return true; } ClearSelection(); - if (this.MultiSelect) + if (MultiSelect) { - if (this.ptAnchorCell.X == -1) + if (ptAnchorCell.X == -1) { moved = false; return true; } - if (nextVisibleRowIndex >= this.ptAnchorCell.Y) + if (nextVisibleRowIndex >= ptAnchorCell.Y) { - SelectRowRange(this.ptAnchorCell.Y, nextVisibleRowIndex, true); + SelectRowRange(ptAnchorCell.Y, nextVisibleRowIndex, true); } else { - SelectRowRange(nextVisibleRowIndex, this.ptAnchorCell.Y, true); + SelectRowRange(nextVisibleRowIndex, ptAnchorCell.Y, true); } } else { SetSelectedRowCore(nextVisibleRowIndex, true); } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, nextVisibleRowIndex, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, nextVisibleRowIndex, !MultiSelect, false, false); if (!success) { moved = false; @@ -20871,7 +20871,7 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedRowCore(lastVisibleRowIndex, true); @@ -20895,18 +20895,18 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) moved = false; return true; } - if (!ScrollIntoView(this.ptCurrentCell.X, nextVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, nextVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(nextVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(nextVisibleRowIndex)) { moved = false; return true; } ClearSelection(); SetSelectedRowCore(nextVisibleRowIndex, true); - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, nextVisibleRowIndex, true, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, nextVisibleRowIndex, true, false, false); if (!success) { moved = false; @@ -20921,7 +20921,7 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) { if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, lastVisibleRowIndex, true); @@ -20940,34 +20940,34 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) } else { - if (this.MultiSelect) + if (MultiSelect) { - if (!ScrollIntoView(this.ptCurrentCell.X, lastVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, lastVisibleRowIndex, true)) { return true; } - Debug.Assert(this.ptAnchorCell.Y >= 0); - if (this.ptAnchorCell.Y == -1 || this.ptCurrentCell.Y == -1 || + Debug.Assert(ptAnchorCell.Y >= 0); + if (ptAnchorCell.Y == -1 || ptCurrentCell.Y == -1 || IsRowOutOfBounds(lastVisibleRowIndex)) { moved = false; return true; } - if ((this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) + if ((Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { ClearSelection(); - SelectRowRange(this.ptAnchorCell.Y, lastVisibleRowIndex, true); + SelectRowRange(ptAnchorCell.Y, lastVisibleRowIndex, true); } else { //ClearSelection(); //SelectCellRange(this.ptCurrentCell.X, this.ptAnchorCell.Y, this.ptCurrentCell.X, lastVisibleRowIndex, true); - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, lastVisibleRowIndex); + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, lastVisibleRowIndex); } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, lastVisibleRowIndex, false, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, lastVisibleRowIndex, false, false, false); if (!success) { moved = false; @@ -20975,26 +20975,26 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) } else { - if (!ScrollIntoView(this.ptCurrentCell.X, lastVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, lastVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsRowOutOfBounds(lastVisibleRowIndex)) + if (ptCurrentCell.Y == -1 || IsRowOutOfBounds(lastVisibleRowIndex)) { moved = false; return true; } - if ((this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) + if ((Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { - SetSelectedRowCore(this.ptCurrentCell.Y, false); + SetSelectedRowCore(ptCurrentCell.Y, false); SetSelectedRowCore(lastVisibleRowIndex, true); } else { - SetSelectedCellCore(this.ptCurrentCell.X, this.ptCurrentCell.Y, false); - SetSelectedCellCore(this.ptCurrentCell.X, lastVisibleRowIndex, true); + SetSelectedCellCore(ptCurrentCell.X, ptCurrentCell.Y, false); + SetSelectedCellCore(ptCurrentCell.X, lastVisibleRowIndex, true); } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, lastVisibleRowIndex, true, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, lastVisibleRowIndex, true, false, false); if (!success) { moved = false; @@ -21004,7 +21004,7 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, lastVisibleRowIndex, true); @@ -21023,16 +21023,16 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) } else { - if (!ScrollIntoView(this.ptCurrentCell.X, lastVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, lastVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsRowOutOfBounds(lastVisibleRowIndex)) + if (ptCurrentCell.Y == -1 || IsRowOutOfBounds(lastVisibleRowIndex)) { moved = false; return true; } - if ((this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) + if ((Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { ClearSelection(); SetSelectedRowCore(lastVisibleRowIndex, true); @@ -21040,9 +21040,9 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) else { ClearSelection(); - SetSelectedCellCore(this.ptCurrentCell.X, lastVisibleRowIndex, true); + SetSelectedCellCore(ptCurrentCell.X, lastVisibleRowIndex, true); } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, lastVisibleRowIndex, true, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, lastVisibleRowIndex, true, false, false); if (!success) { moved = false; @@ -21054,7 +21054,7 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) { if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, lastVisibleRowIndex, true); @@ -21078,32 +21078,32 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) moved = false; return true; } - if (!ScrollIntoView(this.ptCurrentCell.X, nextVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, nextVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsRowOutOfBounds(nextVisibleRowIndex)) + if (ptCurrentCell.Y == -1 || IsRowOutOfBounds(nextVisibleRowIndex)) { moved = false; return true; } - if ((this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) + if ((Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { ClearSelection(); - if (this.MultiSelect) + if (MultiSelect) { - if (this.ptAnchorCell.Y == -1) + if (ptAnchorCell.Y == -1) { moved = false; return true; } - if (nextVisibleRowIndex >= this.ptAnchorCell.Y) + if (nextVisibleRowIndex >= ptAnchorCell.Y) { - SelectRowRange(this.ptAnchorCell.Y, nextVisibleRowIndex, true); + SelectRowRange(ptAnchorCell.Y, nextVisibleRowIndex, true); } else { - SelectRowRange(nextVisibleRowIndex, this.ptAnchorCell.Y, true); + SelectRowRange(nextVisibleRowIndex, ptAnchorCell.Y, true); } } else @@ -21113,26 +21113,26 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) } else { - if (this.MultiSelect) + if (MultiSelect) { //SelectCellUnorderedRange(this.ptCurrentCell.X, this.ptAnchorCell.Y, this.ptCurrentCell.X, nextVisibleRowIndex, true); - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - if (this.ptAnchorCell.X == -1) + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + if (ptAnchorCell.X == -1) { moved = false; return true; } - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, nextVisibleRowIndex); + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, nextVisibleRowIndex); } else { ClearSelection(); - SetSelectedCellCore(this.ptCurrentCell.X, nextVisibleRowIndex, true); + SetSelectedCellCore(ptCurrentCell.X, nextVisibleRowIndex, true); } } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, nextVisibleRowIndex, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, nextVisibleRowIndex, !MultiSelect, false, false); if (!success) { moved = false; @@ -21141,7 +21141,7 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, lastVisibleRowIndex, true); @@ -21165,16 +21165,16 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) moved = false; return true; } - if (!ScrollIntoView(this.ptCurrentCell.X, nextVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, nextVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsRowOutOfBounds(nextVisibleRowIndex)) + if (ptCurrentCell.Y == -1 || IsRowOutOfBounds(nextVisibleRowIndex)) { moved = false; return true; } - if ((this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) + if ((Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { ClearSelection(); SetSelectedRowCore(nextVisibleRowIndex, true); @@ -21182,9 +21182,9 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) else { ClearSelection(); - SetSelectedCellCore(this.ptCurrentCell.X, nextVisibleRowIndex, true); + SetSelectedCellCore(ptCurrentCell.X, nextVisibleRowIndex, true); } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, nextVisibleRowIndex, true, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, nextVisibleRowIndex, true, false, false); if (!success) { moved = false; @@ -21197,7 +21197,7 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) case DataGridViewSelectionMode.FullColumnSelect: if ((keyData & Keys.Control) == Keys.Control) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedColumnCore(firstVisibleColumnIndex, true); @@ -21216,16 +21216,16 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) } else { - if (!ScrollIntoView(this.ptCurrentCell.X, lastVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, lastVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(lastVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(lastVisibleRowIndex)) { moved = false; return true; } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, lastVisibleRowIndex, true, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, lastVisibleRowIndex, true, false, false); if (!success) { moved = false; @@ -21234,7 +21234,7 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedColumnCore(firstVisibleColumnIndex, true); @@ -21258,16 +21258,16 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) moved = false; return true; } - if (!ScrollIntoView(this.ptCurrentCell.X, nextVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, nextVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(nextVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(nextVisibleRowIndex)) { moved = false; return true; } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, nextVisibleRowIndex, true, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, nextVisibleRowIndex, true, false, false); if (!success) { moved = false; @@ -21279,7 +21279,7 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; } return true; } @@ -21287,20 +21287,20 @@ private bool ProcessDownKeyInternal(Keys keyData, out bool moved) protected bool ProcessEndKey(Keys keyData) { bool success; - DataGridViewColumn dataGridViewColumn = this.Columns.GetLastColumn(DataGridViewElementStates.Visible, + DataGridViewColumn dataGridViewColumn = Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.None); int lastVisibleColumnIndex = (dataGridViewColumn == null) ? -1 : dataGridViewColumn.Index; - int firstVisibleRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); - int lastVisibleRowIndex = this.Rows.GetLastRow(DataGridViewElementStates.Visible); + int firstVisibleRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); + int lastVisibleRowIndex = Rows.GetLastRow(DataGridViewElementStates.Visible); if (lastVisibleColumnIndex == -1 || firstVisibleRowIndex == -1) { return false; } - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: if ((keyData & Keys.Control) == 0) @@ -21319,19 +21319,19 @@ protected bool ProcessEndKey(Keys keyData) } if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.MultiSelect && this.ptAnchorCell.X >= 0) + if (MultiSelect && ptAnchorCell.X >= 0) { - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, lastVisibleColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, lastVisibleRowIndex); + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, lastVisibleColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, lastVisibleRowIndex); } else { ClearSelection(); SetSelectedCellCore(lastVisibleColumnIndex, lastVisibleRowIndex, true); } - success = SetCurrentCellAddressCore(lastVisibleColumnIndex, lastVisibleRowIndex, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(lastVisibleColumnIndex, lastVisibleRowIndex, !MultiSelect, false, false); } else { @@ -21362,26 +21362,26 @@ protected bool ProcessEndKey(Keys keyData) } if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.MultiSelect && this.ptAnchorCell.X >= 0) + if (MultiSelect && ptAnchorCell.X >= 0) { - if (this.ptCurrentCell.Y > -1 && - (this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) + if (ptCurrentCell.Y > -1 && + (Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { ClearSelection(); - SelectRowRange(this.ptCurrentCell.Y, lastVisibleRowIndex, true); + SelectRowRange(ptCurrentCell.Y, lastVisibleRowIndex, true); } else { - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, lastVisibleColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, lastVisibleRowIndex); + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, lastVisibleColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, lastVisibleRowIndex); } } else { - if (this.ptCurrentCell.Y > -1 && - (this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) + if (ptCurrentCell.Y > -1 && + (Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { ClearSelection(); SetSelectedRowCore(lastVisibleRowIndex, true); @@ -21392,12 +21392,12 @@ protected bool ProcessEndKey(Keys keyData) SetSelectedCellCore(lastVisibleColumnIndex, lastVisibleRowIndex, true); } } - success = SetCurrentCellAddressCore(lastVisibleColumnIndex, lastVisibleRowIndex, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(lastVisibleColumnIndex, lastVisibleRowIndex, !MultiSelect, false, false); } else { - if (this.ptCurrentCell.Y > -1 && - (this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) + if (ptCurrentCell.Y > -1 && + (Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { ClearSelection(); SetSelectedRowCore(lastVisibleRowIndex, true); @@ -21431,15 +21431,15 @@ protected bool ProcessEndKey(Keys keyData) ClearSelection(); if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.MultiSelect && this.ptCurrentCell.X >= 0) + if (MultiSelect && ptCurrentCell.X >= 0) { - SelectColumnRange(this.ptAnchorCell.X, lastVisibleColumnIndex, true); + SelectColumnRange(ptAnchorCell.X, lastVisibleColumnIndex, true); } else { SetSelectedColumnCore(lastVisibleColumnIndex, true); } - success = SetCurrentCellAddressCore(lastVisibleColumnIndex, lastVisibleRowIndex, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(lastVisibleColumnIndex, lastVisibleRowIndex, !MultiSelect, false, false); } else { @@ -21467,31 +21467,31 @@ protected bool ProcessEndKey(Keys keyData) { return true; } - if (this.ptCurrentCell.X >= 0 && this.Columns[this.ptCurrentCell.X].Selected) + if (ptCurrentCell.X >= 0 && Columns[ptCurrentCell.X].Selected) { ClearSelection(); - if (this.MultiSelect) + if (MultiSelect) { - if (this.ptAnchorCell.X == -1) + if (ptAnchorCell.X == -1) { return true; } - SelectColumnRange(this.ptAnchorCell.X, lastVisibleColumnIndex, true); + SelectColumnRange(ptAnchorCell.X, lastVisibleColumnIndex, true); } SetSelectedColumnCore(lastVisibleColumnIndex, true); } else { - if (this.MultiSelect && this.ptCurrentCell.X >= 0) + if (MultiSelect && ptCurrentCell.X >= 0) { - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - if (this.ptAnchorCell.X == -1) + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + if (ptAnchorCell.X == -1) { return true; } - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, lastVisibleColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, lastVisibleRowIndex); + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, lastVisibleColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, lastVisibleRowIndex); } else { @@ -21499,7 +21499,7 @@ protected bool ProcessEndKey(Keys keyData) SetSelectedCellCore(lastVisibleColumnIndex, lastVisibleRowIndex, true); } } - success = SetCurrentCellAddressCore(lastVisibleColumnIndex, lastVisibleRowIndex, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(lastVisibleColumnIndex, lastVisibleRowIndex, !MultiSelect, false, false); // Debug.Assert(success); } else @@ -21512,7 +21512,7 @@ protected bool ProcessEndKey(Keys keyData) { return true; } - if (this.ptCurrentCell.X >= 0 && this.Columns[this.ptCurrentCell.X].Selected) + if (ptCurrentCell.X >= 0 && Columns[ptCurrentCell.X].Selected) { ClearSelection(); SetSelectedColumnCore(lastVisibleColumnIndex, true); @@ -21546,20 +21546,20 @@ protected bool ProcessEndKey(Keys keyData) ClearSelection(); if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.MultiSelect && this.ptCurrentCell.Y >= 0) + if (MultiSelect && ptCurrentCell.Y >= 0) { - if (this.ptAnchorCell.Y == -1) + if (ptAnchorCell.Y == -1) { return true; } - SelectRowRange(this.ptAnchorCell.Y, lastVisibleRowIndex, true); + SelectRowRange(ptAnchorCell.Y, lastVisibleRowIndex, true); } else { SetSelectedRowCore(lastVisibleRowIndex, true); } - success = SetCurrentCellAddressCore(lastVisibleColumnIndex, lastVisibleRowIndex, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(lastVisibleColumnIndex, lastVisibleRowIndex, !MultiSelect, false, false); } else { @@ -21573,7 +21573,7 @@ protected bool ProcessEndKey(Keys keyData) } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; } return true; } @@ -21597,11 +21597,11 @@ protected bool ProcessEnterKey(Keys keyData) { DataGridViewCell dataGridViewCurrentCell = null; // Try to commit the potential editing - if (this.EditMode == DataGridViewEditMode.EditOnEnter) + if (EditMode == DataGridViewEditMode.EditOnEnter) { - if (this.ptCurrentCell.X != -1) + if (ptCurrentCell.X != -1) { - dataGridViewCurrentCell = this.CurrentCellInternal; + dataGridViewCurrentCell = CurrentCellInternal; DataGridViewDataErrorEventArgs dgvdee = CommitEdit(ref dataGridViewCurrentCell, DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit, DataGridViewValidateCellInternal.WhenChanged, @@ -21632,11 +21632,11 @@ protected bool ProcessEnterKey(Keys keyData) true /*resetCurrentCell unused here*/, true /*resetAnchorCell unused here*/); } - if (/*commitRow && */this.IsCurrentRowDirty) + if (/*commitRow && */IsCurrentRowDirty) { dataGridViewCurrentCell = null; - int columnIndex = this.ptCurrentCell.X; - int rowIndex = this.ptCurrentCell.Y; + int columnIndex = ptCurrentCell.X; + int rowIndex = ptCurrentCell.Y; if (IsInnerCellOutOfBounds(columnIndex, rowIndex)) { return ret; @@ -21659,9 +21659,9 @@ protected bool ProcessEnterKey(Keys keyData) ] protected bool ProcessEscapeKey(Keys keyData) { - if (this.IsEscapeKeyEffective) + if (IsEscapeKeyEffective) { - if (this.IsMouseOperationActive()) + if (IsMouseOperationActive()) { ResetTrackingState(); } @@ -21679,22 +21679,22 @@ protected bool ProcessEscapeKey(Keys keyData) ] protected bool ProcessF2Key(Keys keyData) { - if (this.ptCurrentCell.X != -1 && - !this.IsCurrentCellInEditMode && + if (ptCurrentCell.X != -1 && + !IsCurrentCellInEditMode && ModifierKeys == 0) { - Debug.Assert(this.ptCurrentCell.Y != -1); - Debug.Assert(this.CurrentCellInternal != null); - Debug.Assert(this.EditMode != DataGridViewEditMode.EditOnEnter || - (IsSharedCellReadOnly(this.CurrentCellInternal, this.ptCurrentCell.Y) || !ColumnEditable(this.ptCurrentCell.X))); - if (ColumnEditable(this.ptCurrentCell.X) && - !IsSharedCellReadOnly(this.CurrentCellInternal, this.ptCurrentCell.Y) && - (this.EditMode == DataGridViewEditMode.EditOnKeystrokeOrF2 || - this.EditMode == DataGridViewEditMode.EditOnF2)) + Debug.Assert(ptCurrentCell.Y != -1); + Debug.Assert(CurrentCellInternal != null); + Debug.Assert(EditMode != DataGridViewEditMode.EditOnEnter || + (IsSharedCellReadOnly(CurrentCellInternal, ptCurrentCell.Y) || !ColumnEditable(ptCurrentCell.X))); + if (ColumnEditable(ptCurrentCell.X) && + !IsSharedCellReadOnly(CurrentCellInternal, ptCurrentCell.Y) && + (EditMode == DataGridViewEditMode.EditOnKeystrokeOrF2 || + EditMode == DataGridViewEditMode.EditOnF2)) { - bool success = ScrollIntoView(this.ptCurrentCell.X, this.ptCurrentCell.Y, false); + bool success = ScrollIntoView(ptCurrentCell.X, ptCurrentCell.Y, false); Debug.Assert(success); - BeginEditInternal(this.EditMode == DataGridViewEditMode.EditOnF2 /*selectAll*/); + BeginEditInternal(EditMode == DataGridViewEditMode.EditOnF2 /*selectAll*/); return true; } } @@ -21708,15 +21708,15 @@ protected bool ProcessF2Key(Keys keyData) /// protected bool ProcessF3Key(Keys keyData) { - if (this.ptCurrentCell.X != -1) + if (ptCurrentCell.X != -1) { - DataGridViewColumn dataGridViewColumn = Columns[this.ptCurrentCell.X]; + DataGridViewColumn dataGridViewColumn = Columns[ptCurrentCell.X]; if (dataGridViewColumn != null && CanSort(dataGridViewColumn)) { - ListSortDirection listSortDirection = this.SortedColumn == dataGridViewColumn && this.SortOrder == SortOrder.Ascending ? + ListSortDirection listSortDirection = SortedColumn == dataGridViewColumn && SortOrder == SortOrder.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending; - this.Sort(dataGridViewColumn, listSortDirection); + Sort(dataGridViewColumn, listSortDirection); return true; } } @@ -21726,18 +21726,18 @@ protected bool ProcessF3Key(Keys keyData) protected bool ProcessHomeKey(Keys keyData) { bool success; - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); int firstVisibleColumnIndex = (dataGridViewColumn == null) ? -1 : dataGridViewColumn.Index; - int firstVisibleRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + int firstVisibleRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); if (firstVisibleColumnIndex == -1 || firstVisibleRowIndex == -1) { return false; } - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: if ((keyData & Keys.Control) == 0) @@ -21756,19 +21756,19 @@ protected bool ProcessHomeKey(Keys keyData) } if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.MultiSelect && this.ptAnchorCell.X >= 0) + if (MultiSelect && ptAnchorCell.X >= 0) { - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, firstVisibleColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, firstVisibleRowIndex); + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, firstVisibleColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, firstVisibleRowIndex); } else { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, firstVisibleRowIndex, true); } - success = SetCurrentCellAddressCore(firstVisibleColumnIndex, firstVisibleRowIndex, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(firstVisibleColumnIndex, firstVisibleRowIndex, !MultiSelect, false, false); } else { @@ -21799,26 +21799,26 @@ protected bool ProcessHomeKey(Keys keyData) } if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.MultiSelect && this.ptAnchorCell.X >= 0) + if (MultiSelect && ptAnchorCell.X >= 0) { - if (this.ptCurrentCell.Y > -1 && - (this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) + if (ptCurrentCell.Y > -1 && + (Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { ClearSelection(); - SelectRowRange(firstVisibleRowIndex, this.ptAnchorCell.Y, true); + SelectRowRange(firstVisibleRowIndex, ptAnchorCell.Y, true); } else { - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, firstVisibleColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, firstVisibleRowIndex); + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, firstVisibleColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, firstVisibleRowIndex); } } else { - if (this.ptCurrentCell.Y > -1 && - (this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) + if (ptCurrentCell.Y > -1 && + (Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { ClearSelection(); SetSelectedRowCore(firstVisibleRowIndex, true); @@ -21829,12 +21829,12 @@ protected bool ProcessHomeKey(Keys keyData) SetSelectedCellCore(firstVisibleColumnIndex, firstVisibleRowIndex, true); } } - success = SetCurrentCellAddressCore(firstVisibleColumnIndex, firstVisibleRowIndex, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(firstVisibleColumnIndex, firstVisibleRowIndex, !MultiSelect, false, false); } else { - if (this.ptCurrentCell.Y > -1 && - (this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) + if (ptCurrentCell.Y > -1 && + (Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { ClearSelection(); SetSelectedRowCore(firstVisibleRowIndex, true); @@ -21868,19 +21868,19 @@ protected bool ProcessHomeKey(Keys keyData) ClearSelection(); if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.MultiSelect && this.ptCurrentCell.X >= 0) + if (MultiSelect && ptCurrentCell.X >= 0) { - if (this.ptAnchorCell.X == -1) + if (ptAnchorCell.X == -1) { return true; } - SelectColumnRange(firstVisibleColumnIndex, this.ptAnchorCell.X, true); + SelectColumnRange(firstVisibleColumnIndex, ptAnchorCell.X, true); } else { SetSelectedColumnCore(firstVisibleColumnIndex, true); } - success = SetCurrentCellAddressCore(firstVisibleColumnIndex, firstVisibleRowIndex, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(firstVisibleColumnIndex, firstVisibleRowIndex, !MultiSelect, false, false); } else { @@ -21908,31 +21908,31 @@ protected bool ProcessHomeKey(Keys keyData) { return true; } - if (this.ptCurrentCell.X >= 0 && this.Columns[this.ptCurrentCell.X].Selected) + if (ptCurrentCell.X >= 0 && Columns[ptCurrentCell.X].Selected) { ClearSelection(); - if (this.MultiSelect) + if (MultiSelect) { - if (this.ptAnchorCell.X == -1) + if (ptAnchorCell.X == -1) { return true; } - SelectColumnRange(firstVisibleColumnIndex, this.ptAnchorCell.X, true); + SelectColumnRange(firstVisibleColumnIndex, ptAnchorCell.X, true); } SetSelectedColumnCore(firstVisibleColumnIndex, true); } else { - if (this.MultiSelect && this.ptCurrentCell.X >= 0) + if (MultiSelect && ptCurrentCell.X >= 0) { - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - if (this.ptAnchorCell.X == -1) + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + if (ptAnchorCell.X == -1) { return true; } - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, firstVisibleColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, firstVisibleRowIndex); + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, firstVisibleColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, firstVisibleRowIndex); } else { @@ -21940,7 +21940,7 @@ protected bool ProcessHomeKey(Keys keyData) SetSelectedCellCore(firstVisibleColumnIndex, firstVisibleRowIndex, true); } } - success = SetCurrentCellAddressCore(firstVisibleColumnIndex, firstVisibleRowIndex, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(firstVisibleColumnIndex, firstVisibleRowIndex, !MultiSelect, false, false); // Debug.Assert(success); } else @@ -21953,7 +21953,7 @@ protected bool ProcessHomeKey(Keys keyData) { return true; } - if (this.ptCurrentCell.X >= 0 && this.Columns[this.ptCurrentCell.X].Selected) + if (ptCurrentCell.X >= 0 && Columns[ptCurrentCell.X].Selected) { ClearSelection(); SetSelectedColumnCore(firstVisibleColumnIndex, true); @@ -21994,7 +21994,7 @@ protected bool ProcessHomeKey(Keys keyData) } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; } return true; } @@ -22003,7 +22003,7 @@ protected bool ProcessInsertKey(Keys keyData) { if (((keyData & (Keys.Shift | Keys.Control | Keys.Alt)) == Keys.Control || ((keyData & (Keys.Shift | Keys.Control | Keys.Alt)) == (Keys.Control | Keys.Shift) && (keyData & Keys.KeyCode) == Keys.C)) && - this.ClipboardCopyMode != DataGridViewClipboardCopyMode.Disable) + ClipboardCopyMode != DataGridViewClipboardCopyMode.Disable) { DataObject dataObject = GetClipboardContent(); if (dataObject != null) @@ -22019,15 +22019,15 @@ protected override bool ProcessKeyEventArgs(ref Message m) { if (m.Msg == Interop.WindowMessages.WM_SYSKEYDOWN || m.Msg == Interop.WindowMessages.WM_KEYDOWN) { - if (this.ptCurrentCell.X != -1) + if (ptCurrentCell.X != -1) { - DataGridViewCell dataGridViewCell = this.CurrentCellInternal; + DataGridViewCell dataGridViewCell = CurrentCellInternal; Debug.Assert(dataGridViewCell != null); - if (!this.IsCurrentCellInEditMode && - ColumnEditable(this.ptCurrentCell.X) && - !IsSharedCellReadOnly(dataGridViewCell, this.ptCurrentCell.Y) && - (this.EditMode == DataGridViewEditMode.EditOnKeystroke || this.EditMode == DataGridViewEditMode.EditOnKeystrokeOrF2)) + if (!IsCurrentCellInEditMode && + ColumnEditable(ptCurrentCell.X) && + !IsSharedCellReadOnly(dataGridViewCell, ptCurrentCell.Y) && + (EditMode == DataGridViewEditMode.EditOnKeystroke || EditMode == DataGridViewEditMode.EditOnKeystrokeOrF2)) { KeyEventArgs ke = new KeyEventArgs((Keys)(unchecked((int)(long)m.WParam)) | ModifierKeys); if (ke.KeyCode != Keys.ProcessKey || (int)m.LParam != 0x01) // Changing IME context does not trigger editing mode @@ -22044,15 +22044,15 @@ protected override bool ProcessKeyEventArgs(ref Message m) dataGridViewCell.KeyEntersEditMode(ke)) { // Cell wants to go to edit mode - bool success = ScrollIntoView(this.ptCurrentCell.X, this.ptCurrentCell.Y, false); + bool success = ScrollIntoView(ptCurrentCell.X, ptCurrentCell.Y, false); Debug.Assert(success); - if (BeginEditInternal(!(ke.KeyCode == Keys.F2 && ModifierKeys == 0 && this.EditMode == DataGridViewEditMode.EditOnKeystrokeOrF2) /*selectAll*/)) + if (BeginEditInternal(!(ke.KeyCode == Keys.F2 && ModifierKeys == 0 && EditMode == DataGridViewEditMode.EditOnKeystrokeOrF2) /*selectAll*/)) { // Forward the key message to the editing control if any - if (this.editingControl != null) + if (editingControl != null) { - this.editingControl.SendMessage(m.Msg, m.WParam, m.LParam); - this.dataGridViewState1[DATAGRIDVIEWSTATE1_forwardCharMessage] = true; + editingControl.SendMessage(m.Msg, m.WParam, m.LParam); + dataGridViewState1[DATAGRIDVIEWSTATE1_forwardCharMessage] = true; return true; } } @@ -22061,13 +22061,13 @@ protected override bool ProcessKeyEventArgs(ref Message m) } } } - else if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_forwardCharMessage] && + else if (dataGridViewState1[DATAGRIDVIEWSTATE1_forwardCharMessage] && (m.Msg == Interop.WindowMessages.WM_SYSCHAR || m.Msg == Interop.WindowMessages.WM_CHAR || m.Msg == Interop.WindowMessages.WM_IME_CHAR)) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_forwardCharMessage] = false; - if (this.editingControl != null) + dataGridViewState1[DATAGRIDVIEWSTATE1_forwardCharMessage] = false; + if (editingControl != null) { - this.editingControl.SendMessage(m.Msg, m.WParam, m.LParam); + editingControl.SendMessage(m.Msg, m.WParam, m.LParam); return true; } } @@ -22126,12 +22126,12 @@ protected override bool ProcessKeyPreview(ref Message m) } } - if (this.editingControl != null && (m.Msg == Interop.WindowMessages.WM_KEYDOWN || m.Msg == Interop.WindowMessages.WM_SYSKEYDOWN)) + if (editingControl != null && (m.Msg == Interop.WindowMessages.WM_KEYDOWN || m.Msg == Interop.WindowMessages.WM_SYSKEYDOWN)) { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_currentCellWantsInputKey] = ((IDataGridViewEditingControl)this.editingControl).EditingControlWantsInputKey(ke.KeyData, dataGridViewWantsInputKey); + dataGridViewState2[DATAGRIDVIEWSTATE2_currentCellWantsInputKey] = ((IDataGridViewEditingControl)editingControl).EditingControlWantsInputKey(ke.KeyData, dataGridViewWantsInputKey); } - if (this.dataGridViewState2[DATAGRIDVIEWSTATE2_currentCellWantsInputKey]) + if (dataGridViewState2[DATAGRIDVIEWSTATE2_currentCellWantsInputKey]) { return base.ProcessKeyPreview(ref m); } @@ -22147,7 +22147,7 @@ protected override bool ProcessKeyPreview(ref Message m) } else { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_currentCellWantsInputKey] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_currentCellWantsInputKey] = true; } } else @@ -22160,23 +22160,23 @@ protected override bool ProcessKeyPreview(ref Message m) private bool? ProcessColumnResize(Keys keyData, int step) { - if ((keyData & Keys.Alt) == Keys.Alt && this.AllowUserToResizeColumns && this.ptCurrentCell.X != -1) + if ((keyData & Keys.Alt) == Keys.Alt && AllowUserToResizeColumns && ptCurrentCell.X != -1) { - if (this.currentColSplitBar == -1) + if (currentColSplitBar == -1) { - DataGridViewColumn dataGridViewColumn = Columns[this.ptCurrentCell.X]; + DataGridViewColumn dataGridViewColumn = Columns[ptCurrentCell.X]; if (dataGridViewColumn != null && dataGridViewColumn.Resizable == DataGridViewTriState.True && (dataGridViewColumn.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.None || dataGridViewColumn.InheritedAutoSizeMode == DataGridViewAutoSizeColumnMode.Fill)) { - BeginKeyboardColumnResize(this.ptCurrentCell.X); + BeginKeyboardColumnResize(ptCurrentCell.X); return true; } return false; } else { - int x = this.currentColSplitBar + step; - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackKeyboardColResize] && this.resizeClipRectangle.Contains(x, this.resizeClipRectangle.Top)) + int x = currentColSplitBar + step; + if (dataGridViewOper[DATAGRIDVIEWOPER_trackKeyboardColResize] && resizeClipRectangle.Contains(x, resizeClipRectangle.Top)) { MoveRowHeadersOrColumnResize(x); return true; @@ -22190,7 +22190,7 @@ protected override bool ProcessKeyPreview(ref Message m) protected bool ProcessLeftKey(Keys keyData) { - if (this.RightToLeftInternal) + if (RightToLeftInternal) { return ProcessRightKeyPrivate(keyData); } @@ -22202,24 +22202,24 @@ protected bool ProcessLeftKey(Keys keyData) private bool ProcessLeftKeyPrivate(Keys keyData) { - bool? resizeResult = this.ProcessColumnResize(keyData, -this.keyboardResizeStep); + bool? resizeResult = ProcessColumnResize(keyData, -keyboardResizeStep); if (resizeResult.HasValue) { return resizeResult.Value; } bool success; - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); int firstVisibleColumnIndex = (dataGridViewColumn == null) ? -1 : dataGridViewColumn.Index; - int firstVisibleRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + int firstVisibleRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); if (firstVisibleColumnIndex == -1 || firstVisibleRowIndex == -1) { return false; } int previousVisibleColumnIndex = -1; - if (this.ptCurrentCell.X != -1) + if (ptCurrentCell.X != -1) { - dataGridViewColumn = this.Columns.GetPreviousColumn(this.Columns[this.ptCurrentCell.X], + dataGridViewColumn = Columns.GetPreviousColumn(Columns[ptCurrentCell.X], DataGridViewElementStates.Visible, DataGridViewElementStates.None); if (dataGridViewColumn != null) @@ -22228,10 +22228,10 @@ private bool ProcessLeftKeyPrivate(Keys keyData) } } - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: case DataGridViewSelectionMode.RowHeaderSelect: @@ -22243,7 +22243,7 @@ private bool ProcessLeftKeyPrivate(Keys keyData) { if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, firstVisibleRowIndex, true); @@ -22262,39 +22262,39 @@ private bool ProcessLeftKeyPrivate(Keys keyData) { return true; } - if (!ScrollIntoView(previousVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(previousVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(previousVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(previousVisibleColumnIndex)) { return true; } - if (this.MultiSelect) + if (MultiSelect) { - Debug.Assert(this.ptAnchorCell.X >= 0); + Debug.Assert(ptAnchorCell.X >= 0); //SelectCellUnorderedRange(previousVisibleColumnIndex, this.ptCurrentCell.Y, this.ptAnchorCell.X, this.ptCurrentCell.Y, true); - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - if (this.ptAnchorCell.X == -1) + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + if (ptAnchorCell.X == -1) { return true; } - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, previousVisibleColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, oldEdgeRowIndex); + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, previousVisibleColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, oldEdgeRowIndex); } else { ClearSelection(); - SetSelectedCellCore(previousVisibleColumnIndex, this.ptCurrentCell.Y, true); + SetSelectedCellCore(previousVisibleColumnIndex, ptCurrentCell.Y, true); } - success = SetCurrentCellAddressCore(previousVisibleColumnIndex, this.ptCurrentCell.Y, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(previousVisibleColumnIndex, ptCurrentCell.Y, !MultiSelect, false, false); Debug.Assert(success); } } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, firstVisibleRowIndex, true); @@ -22313,17 +22313,17 @@ private bool ProcessLeftKeyPrivate(Keys keyData) { return true; } - if (!ScrollIntoView(previousVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(previousVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(previousVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(previousVisibleColumnIndex)) { return true; } ClearSelection(); - SetSelectedCellCore(previousVisibleColumnIndex, this.ptCurrentCell.Y, true); - success = SetCurrentCellAddressCore(previousVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + SetSelectedCellCore(previousVisibleColumnIndex, ptCurrentCell.Y, true); + success = SetCurrentCellAddressCore(previousVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } } @@ -22339,7 +22339,7 @@ private bool ProcessLeftKeyPrivate(Keys keyData) { if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedColumnCore(firstVisibleColumnIndex, true); @@ -22358,41 +22358,41 @@ private bool ProcessLeftKeyPrivate(Keys keyData) { return true; } - if (!ScrollIntoView(previousVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(previousVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(previousVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(previousVisibleColumnIndex)) { return true; } ClearSelection(); - if (this.MultiSelect) + if (MultiSelect) { - if (this.ptAnchorCell.X == -1) + if (ptAnchorCell.X == -1) { return true; } - if (this.Columns.DisplayInOrder(this.ptAnchorCell.X, previousVisibleColumnIndex)) + if (Columns.DisplayInOrder(ptAnchorCell.X, previousVisibleColumnIndex)) { - SelectColumnRange(this.ptAnchorCell.X, previousVisibleColumnIndex, true); + SelectColumnRange(ptAnchorCell.X, previousVisibleColumnIndex, true); } else { - SelectColumnRange(previousVisibleColumnIndex, this.ptAnchorCell.X, true); + SelectColumnRange(previousVisibleColumnIndex, ptAnchorCell.X, true); } } else { SetSelectedColumnCore(previousVisibleColumnIndex, true); } - success = SetCurrentCellAddressCore(previousVisibleColumnIndex, this.ptCurrentCell.Y, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(previousVisibleColumnIndex, ptCurrentCell.Y, !MultiSelect, false, false); Debug.Assert(success); } } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedColumnCore(firstVisibleColumnIndex, true); @@ -22411,17 +22411,17 @@ private bool ProcessLeftKeyPrivate(Keys keyData) { return true; } - if (!ScrollIntoView(previousVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(previousVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(previousVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(previousVisibleColumnIndex)) { return true; } ClearSelection(); SetSelectedColumnCore(previousVisibleColumnIndex, true); - success = SetCurrentCellAddressCore(previousVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + success = SetCurrentCellAddressCore(previousVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } } @@ -22437,7 +22437,7 @@ private bool ProcessLeftKeyPrivate(Keys keyData) { if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, firstVisibleRowIndex, true); @@ -22456,61 +22456,61 @@ private bool ProcessLeftKeyPrivate(Keys keyData) { return true; } - if (!ScrollIntoView(previousVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(previousVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsColumnOutOfBounds(previousVisibleColumnIndex)) + if (ptCurrentCell.X == -1 || IsColumnOutOfBounds(previousVisibleColumnIndex)) { return true; } - if (this.Columns[this.ptCurrentCell.X].Selected) + if (Columns[ptCurrentCell.X].Selected) { ClearSelection(); - if (this.MultiSelect) + if (MultiSelect) { - if (this.ptAnchorCell.X == -1) + if (ptAnchorCell.X == -1) { return true; } - if (this.Columns.DisplayInOrder(this.ptAnchorCell.X, previousVisibleColumnIndex)) + if (Columns.DisplayInOrder(ptAnchorCell.X, previousVisibleColumnIndex)) { - SelectColumnRange(this.ptAnchorCell.X, previousVisibleColumnIndex, true); + SelectColumnRange(ptAnchorCell.X, previousVisibleColumnIndex, true); } else { - SelectColumnRange(previousVisibleColumnIndex, this.ptAnchorCell.X, true); + SelectColumnRange(previousVisibleColumnIndex, ptAnchorCell.X, true); } } SetSelectedColumnCore(previousVisibleColumnIndex, true); } else { - if (this.MultiSelect) + if (MultiSelect) { //SelectCellUnorderedRange(previousVisibleColumnIndex, this.ptCurrentCell.Y, this.ptAnchorCell.X, this.ptCurrentCell.Y, true); - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - if (this.ptAnchorCell.X == -1) + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + if (ptAnchorCell.X == -1) { return true; } - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, previousVisibleColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, oldEdgeRowIndex); + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, previousVisibleColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, oldEdgeRowIndex); } else { ClearSelection(); - SetSelectedCellCore(previousVisibleColumnIndex, this.ptCurrentCell.Y, true); + SetSelectedCellCore(previousVisibleColumnIndex, ptCurrentCell.Y, true); } } - success = SetCurrentCellAddressCore(previousVisibleColumnIndex, this.ptCurrentCell.Y, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(previousVisibleColumnIndex, ptCurrentCell.Y, !MultiSelect, false, false); Debug.Assert(success); } } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, firstVisibleRowIndex, true); @@ -22529,15 +22529,15 @@ private bool ProcessLeftKeyPrivate(Keys keyData) { return true; } - if (!ScrollIntoView(previousVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(previousVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsColumnOutOfBounds(previousVisibleColumnIndex)) + if (ptCurrentCell.X == -1 || IsColumnOutOfBounds(previousVisibleColumnIndex)) { return true; } - if (this.Columns[this.ptCurrentCell.X].Selected) + if (Columns[ptCurrentCell.X].Selected) { ClearSelection(); SetSelectedColumnCore(previousVisibleColumnIndex, true); @@ -22545,9 +22545,9 @@ private bool ProcessLeftKeyPrivate(Keys keyData) else { ClearSelection(); - SetSelectedCellCore(previousVisibleColumnIndex, this.ptCurrentCell.Y, true); + SetSelectedCellCore(previousVisibleColumnIndex, ptCurrentCell.Y, true); } - success = SetCurrentCellAddressCore(previousVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + success = SetCurrentCellAddressCore(previousVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } } @@ -22561,7 +22561,7 @@ private bool ProcessLeftKeyPrivate(Keys keyData) } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedRowCore(firstVisibleRowIndex, true); @@ -22580,15 +22580,15 @@ private bool ProcessLeftKeyPrivate(Keys keyData) { return true; } - if (!ScrollIntoView(previousVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(previousVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(previousVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(previousVisibleColumnIndex)) { return true; } - success = SetCurrentCellAddressCore(previousVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + success = SetCurrentCellAddressCore(previousVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } } @@ -22597,7 +22597,7 @@ private bool ProcessLeftKeyPrivate(Keys keyData) } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; } return true; } @@ -22608,16 +22608,16 @@ private bool ProcessLeftMost(bool shift, int firstVisibleColumnIndex, int firstV { bool success; - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: case DataGridViewSelectionMode.RowHeaderSelect: if (shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, firstVisibleRowIndex, true); @@ -22632,48 +22632,48 @@ private bool ProcessLeftMost(bool shift, int firstVisibleColumnIndex, int firstV } else { - if (this.MultiSelect) + if (MultiSelect) { - if (!ScrollIntoView(firstVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(firstVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } //ClearSelection(); - Debug.Assert(this.ptAnchorCell.X >= 0); + Debug.Assert(ptAnchorCell.X >= 0); //SelectCellRange(firstVisibleColumnIndex, this.ptCurrentCell.Y, this.ptAnchorCell.X, this.ptCurrentCell.Y, true); - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - if (this.ptAnchorCell.X == -1 || this.ptCurrentCell.X == -1 || + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + if (ptAnchorCell.X == -1 || ptCurrentCell.X == -1 || IsColumnOutOfBounds(firstVisibleColumnIndex)) { return true; } - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, firstVisibleColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, oldEdgeRowIndex); - success = SetCurrentCellAddressCore(firstVisibleColumnIndex, this.ptCurrentCell.Y, false, false, false); + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, firstVisibleColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, oldEdgeRowIndex); + success = SetCurrentCellAddressCore(firstVisibleColumnIndex, ptCurrentCell.Y, false, false, false); Debug.Assert(success); } else { - if (!ScrollIntoView(firstVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(firstVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(firstVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(firstVisibleColumnIndex)) { return true; } //SetSelectedCellCore(this.ptCurrentCell.X, this.ptCurrentCell.Y, false); ClearSelection(); - SetSelectedCellCore(firstVisibleColumnIndex, this.ptCurrentCell.Y, true); - success = SetCurrentCellAddressCore(firstVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + SetSelectedCellCore(firstVisibleColumnIndex, ptCurrentCell.Y, true); + success = SetCurrentCellAddressCore(firstVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } } } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, firstVisibleRowIndex, true); @@ -22688,17 +22688,17 @@ private bool ProcessLeftMost(bool shift, int firstVisibleColumnIndex, int firstV } else { - if (!ScrollIntoView(firstVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(firstVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(firstVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(firstVisibleColumnIndex)) { return true; } ClearSelection(); - SetSelectedCellCore(firstVisibleColumnIndex, this.ptCurrentCell.Y, true); - success = SetCurrentCellAddressCore(firstVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + SetSelectedCellCore(firstVisibleColumnIndex, ptCurrentCell.Y, true); + success = SetCurrentCellAddressCore(firstVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } } @@ -22707,7 +22707,7 @@ private bool ProcessLeftMost(bool shift, int firstVisibleColumnIndex, int firstV case DataGridViewSelectionMode.FullColumnSelect: if (shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedColumnCore(firstVisibleColumnIndex, true); @@ -22722,43 +22722,43 @@ private bool ProcessLeftMost(bool shift, int firstVisibleColumnIndex, int firstV } else { - if (this.MultiSelect) + if (MultiSelect) { - if (!ScrollIntoView(firstVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(firstVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptAnchorCell.X == -1 || this.ptCurrentCell.Y == -1 || + if (ptAnchorCell.X == -1 || ptCurrentCell.Y == -1 || IsColumnOutOfBounds(firstVisibleColumnIndex)) { return true; } ClearSelection(); - Debug.Assert(this.ptAnchorCell.X >= 0); - SelectColumnRange(firstVisibleColumnIndex, this.ptAnchorCell.X, true); - success = SetCurrentCellAddressCore(firstVisibleColumnIndex, this.ptCurrentCell.Y, false, false, false); + Debug.Assert(ptAnchorCell.X >= 0); + SelectColumnRange(firstVisibleColumnIndex, ptAnchorCell.X, true); + success = SetCurrentCellAddressCore(firstVisibleColumnIndex, ptCurrentCell.Y, false, false, false); Debug.Assert(success); } else { - if (!ScrollIntoView(firstVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(firstVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsColumnOutOfBounds(firstVisibleColumnIndex)) + if (ptCurrentCell.X == -1 || IsColumnOutOfBounds(firstVisibleColumnIndex)) { return true; } - SetSelectedColumnCore(this.ptCurrentCell.X, false); + SetSelectedColumnCore(ptCurrentCell.X, false); SetSelectedColumnCore(firstVisibleColumnIndex, true); - success = SetCurrentCellAddressCore(firstVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + success = SetCurrentCellAddressCore(firstVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } } } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedColumnCore(firstVisibleColumnIndex, true); @@ -22773,17 +22773,17 @@ private bool ProcessLeftMost(bool shift, int firstVisibleColumnIndex, int firstV } else { - if (!ScrollIntoView(firstVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(firstVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(firstVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(firstVisibleColumnIndex)) { return true; } ClearSelection(); SetSelectedColumnCore(firstVisibleColumnIndex, true); - success = SetCurrentCellAddressCore(firstVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + success = SetCurrentCellAddressCore(firstVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } } @@ -22792,7 +22792,7 @@ private bool ProcessLeftMost(bool shift, int firstVisibleColumnIndex, int firstV case DataGridViewSelectionMode.ColumnHeaderSelect: if (shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, firstVisibleRowIndex, true); @@ -22807,64 +22807,64 @@ private bool ProcessLeftMost(bool shift, int firstVisibleColumnIndex, int firstV } else { - if (this.MultiSelect) + if (MultiSelect) { - if (!ScrollIntoView(firstVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(firstVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptAnchorCell.X == -1 || this.ptCurrentCell.X == -1 || + if (ptAnchorCell.X == -1 || ptCurrentCell.X == -1 || IsColumnOutOfBounds(firstVisibleColumnIndex)) { return true; } - Debug.Assert(this.ptAnchorCell.X >= 0); - if (this.Columns[this.ptCurrentCell.X].Selected) + Debug.Assert(ptAnchorCell.X >= 0); + if (Columns[ptCurrentCell.X].Selected) { ClearSelection(); - SelectColumnRange(firstVisibleColumnIndex, this.ptAnchorCell.X, true); + SelectColumnRange(firstVisibleColumnIndex, ptAnchorCell.X, true); } else { //ClearSelection(); //SelectCellRange(firstVisibleColumnIndex, this.ptCurrentCell.Y, this.ptAnchorCell.X, this.ptCurrentCell.Y, true); - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, firstVisibleColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, oldEdgeRowIndex); + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, firstVisibleColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, oldEdgeRowIndex); } - success = SetCurrentCellAddressCore(firstVisibleColumnIndex, this.ptCurrentCell.Y, false, false, false); + success = SetCurrentCellAddressCore(firstVisibleColumnIndex, ptCurrentCell.Y, false, false, false); Debug.Assert(success); } else { - if (!ScrollIntoView(firstVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(firstVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.X == -1 || + if (ptCurrentCell.X == -1 || IsInnerCellOutOfBounds(firstVisibleColumnIndex, firstVisibleRowIndex)) { return true; } - if (this.Columns[this.ptCurrentCell.X].Selected) + if (Columns[ptCurrentCell.X].Selected) { - SetSelectedColumnCore(this.ptCurrentCell.X, false); + SetSelectedColumnCore(ptCurrentCell.X, false); SetSelectedColumnCore(firstVisibleColumnIndex, true); } else { - SetSelectedCellCore(this.ptCurrentCell.X, this.ptCurrentCell.Y, false); - SetSelectedCellCore(firstVisibleColumnIndex, this.ptCurrentCell.Y, true); + SetSelectedCellCore(ptCurrentCell.X, ptCurrentCell.Y, false); + SetSelectedCellCore(firstVisibleColumnIndex, ptCurrentCell.Y, true); } - success = SetCurrentCellAddressCore(firstVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + success = SetCurrentCellAddressCore(firstVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } } } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, firstVisibleRowIndex, true); @@ -22879,15 +22879,15 @@ private bool ProcessLeftMost(bool shift, int firstVisibleColumnIndex, int firstV } else { - if (!ScrollIntoView(firstVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(firstVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsColumnOutOfBounds(firstVisibleColumnIndex)) + if (ptCurrentCell.X == -1 || IsColumnOutOfBounds(firstVisibleColumnIndex)) { return true; } - if (this.Columns[this.ptCurrentCell.X].Selected) + if (Columns[ptCurrentCell.X].Selected) { ClearSelection(); SetSelectedColumnCore(firstVisibleColumnIndex, true); @@ -22895,16 +22895,16 @@ private bool ProcessLeftMost(bool shift, int firstVisibleColumnIndex, int firstV else { ClearSelection(); - SetSelectedCellCore(firstVisibleColumnIndex, this.ptCurrentCell.Y, true); + SetSelectedCellCore(firstVisibleColumnIndex, ptCurrentCell.Y, true); } - success = SetCurrentCellAddressCore(firstVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + success = SetCurrentCellAddressCore(firstVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } } return true; case DataGridViewSelectionMode.FullRowSelect: - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedRowCore(firstVisibleRowIndex, true); @@ -22919,15 +22919,15 @@ private bool ProcessLeftMost(bool shift, int firstVisibleColumnIndex, int firstV } else { - if (!ScrollIntoView(firstVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(firstVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(firstVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(firstVisibleColumnIndex)) { return true; } - success = SetCurrentCellAddressCore(firstVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + success = SetCurrentCellAddressCore(firstVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } return true; @@ -22935,7 +22935,7 @@ private bool ProcessLeftMost(bool shift, int firstVisibleColumnIndex, int firstV } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; } return true; } @@ -22943,16 +22943,16 @@ private bool ProcessLeftMost(bool shift, int firstVisibleColumnIndex, int firstV protected bool ProcessNextKey(Keys keyData) { bool success; - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); int firstVisibleColumnIndex = (dataGridViewColumn == null) ? -1 : dataGridViewColumn.Index; if (firstVisibleColumnIndex == -1) { return false; } int nextScreenVisibleRowIndexTmp, nextScreenVisibleRowIndex = -1, jumpRows = 0; - if (this.ptCurrentCell.Y == -1) + if (ptCurrentCell.Y == -1) { - nextScreenVisibleRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + nextScreenVisibleRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); if (nextScreenVisibleRowIndex == -1) { return false; @@ -22960,30 +22960,30 @@ protected bool ProcessNextKey(Keys keyData) } else { - nextScreenVisibleRowIndex = this.ptCurrentCell.Y; + nextScreenVisibleRowIndex = ptCurrentCell.Y; } - if ((this.Rows.GetRowState(nextScreenVisibleRowIndex) & DataGridViewElementStates.Frozen) != 0) + if ((Rows.GetRowState(nextScreenVisibleRowIndex) & DataGridViewElementStates.Frozen) != 0) { - if (this.displayedBandsInfo.FirstDisplayedScrollingRow > 0) + if (displayedBandsInfo.FirstDisplayedScrollingRow > 0) { - int firstDisplayedScrollingRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); + int firstDisplayedScrollingRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); Debug.Assert(firstDisplayedScrollingRowIndex != -1); - if (!ScrollIntoView(this.ptCurrentCell.X == -1 ? firstVisibleColumnIndex : this.ptCurrentCell.X, + if (!ScrollIntoView(ptCurrentCell.X == -1 ? firstVisibleColumnIndex : ptCurrentCell.X, firstDisplayedScrollingRowIndex, true)) { return true; } - jumpRows = this.Rows.GetRowCount(DataGridViewElementStates.Visible, - this.ptCurrentCell.Y, + jumpRows = Rows.GetRowCount(DataGridViewElementStates.Visible, + ptCurrentCell.Y, firstDisplayedScrollingRowIndex) - 1; } else { - jumpRows = this.displayedBandsInfo.NumTotallyDisplayedFrozenRows; + jumpRows = displayedBandsInfo.NumTotallyDisplayedFrozenRows; } } - jumpRows += this.displayedBandsInfo.NumTotallyDisplayedScrollingRows; + jumpRows += displayedBandsInfo.NumTotallyDisplayedScrollingRows; nextScreenVisibleRowIndexTmp = nextScreenVisibleRowIndex; Debug.Assert(nextScreenVisibleRowIndexTmp != -1); @@ -22993,7 +22993,7 @@ protected bool ProcessNextKey(Keys keyData) } while (jumpRows > 0 && nextScreenVisibleRowIndexTmp != -1) { - nextScreenVisibleRowIndexTmp = this.Rows.GetNextRow(nextScreenVisibleRowIndex, DataGridViewElementStates.Visible); + nextScreenVisibleRowIndexTmp = Rows.GetNextRow(nextScreenVisibleRowIndex, DataGridViewElementStates.Visible); if (nextScreenVisibleRowIndexTmp != -1) { nextScreenVisibleRowIndex = nextScreenVisibleRowIndexTmp; @@ -23001,13 +23001,13 @@ protected bool ProcessNextKey(Keys keyData) } } - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: @@ -23034,112 +23034,112 @@ protected bool ProcessNextKey(Keys keyData) return true; } - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: - if (!ScrollIntoView(this.ptCurrentCell.X, nextScreenVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, nextScreenVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(nextScreenVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(nextScreenVisibleRowIndex)) { return true; } - if ((keyData & Keys.Shift) == Keys.Shift && this.MultiSelect) + if ((keyData & Keys.Shift) == Keys.Shift && MultiSelect) { - Debug.Assert(this.ptAnchorCell.Y >= 0); - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - if (this.ptAnchorCell.Y == -1) + Debug.Assert(ptAnchorCell.Y >= 0); + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + if (ptAnchorCell.Y == -1) { return true; } - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, nextScreenVisibleRowIndex); + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, nextScreenVisibleRowIndex); } else { ClearSelection(); - SetSelectedCellCore(this.ptCurrentCell.X, nextScreenVisibleRowIndex, true); + SetSelectedCellCore(ptCurrentCell.X, nextScreenVisibleRowIndex, true); } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, nextScreenVisibleRowIndex, false, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, nextScreenVisibleRowIndex, false, false, false); Debug.Assert(success); return true; case DataGridViewSelectionMode.FullRowSelect: - if (!ScrollIntoView(this.ptCurrentCell.X, nextScreenVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, nextScreenVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(nextScreenVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(nextScreenVisibleRowIndex)) { return true; } ClearSelection(); - if ((keyData & Keys.Shift) == Keys.Shift && this.MultiSelect) + if ((keyData & Keys.Shift) == Keys.Shift && MultiSelect) { - Debug.Assert(this.ptAnchorCell.Y >= 0); - if (this.ptAnchorCell.Y == -1) + Debug.Assert(ptAnchorCell.Y >= 0); + if (ptAnchorCell.Y == -1) { return true; } - if (this.ptAnchorCell.Y < nextScreenVisibleRowIndex) + if (ptAnchorCell.Y < nextScreenVisibleRowIndex) { - SelectRowRange(this.ptAnchorCell.Y, nextScreenVisibleRowIndex, true); + SelectRowRange(ptAnchorCell.Y, nextScreenVisibleRowIndex, true); } else { - SelectRowRange(nextScreenVisibleRowIndex, this.ptAnchorCell.Y, true); + SelectRowRange(nextScreenVisibleRowIndex, ptAnchorCell.Y, true); } } else { SetSelectedRowCore(nextScreenVisibleRowIndex, true); } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, nextScreenVisibleRowIndex, false, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, nextScreenVisibleRowIndex, false, false, false); // Debug.Assert(success); return true; case DataGridViewSelectionMode.RowHeaderSelect: - if (!ScrollIntoView(this.ptCurrentCell.X, nextScreenVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, nextScreenVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(nextScreenVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(nextScreenVisibleRowIndex)) { return true; } - if ((keyData & Keys.Shift) == Keys.Shift && this.MultiSelect) + if ((keyData & Keys.Shift) == Keys.Shift && MultiSelect) { - Debug.Assert(this.ptAnchorCell.Y >= 0); - if (this.ptAnchorCell.Y == -1) + Debug.Assert(ptAnchorCell.Y >= 0); + if (ptAnchorCell.Y == -1) { return true; } - if ((this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) + if ((Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { ClearSelection(); - if (this.ptAnchorCell.Y < nextScreenVisibleRowIndex) + if (ptAnchorCell.Y < nextScreenVisibleRowIndex) { - SelectRowRange(this.ptAnchorCell.Y, nextScreenVisibleRowIndex, true); + SelectRowRange(ptAnchorCell.Y, nextScreenVisibleRowIndex, true); } else { - SelectRowRange(nextScreenVisibleRowIndex, this.ptAnchorCell.Y, true); + SelectRowRange(nextScreenVisibleRowIndex, ptAnchorCell.Y, true); } } else { - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, nextScreenVisibleRowIndex); + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, nextScreenVisibleRowIndex); } } else { - if ((this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) + if ((Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { ClearSelection(); SetSelectedRowCore(nextScreenVisibleRowIndex, true); @@ -23147,30 +23147,30 @@ protected bool ProcessNextKey(Keys keyData) else { ClearSelection(); - SetSelectedCellCore(this.ptCurrentCell.X, nextScreenVisibleRowIndex, true); + SetSelectedCellCore(ptCurrentCell.X, nextScreenVisibleRowIndex, true); } } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, nextScreenVisibleRowIndex, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, nextScreenVisibleRowIndex, !MultiSelect, false, false); // Debug.Assert(success); return true; case DataGridViewSelectionMode.FullColumnSelect: - if (!ScrollIntoView(this.ptCurrentCell.X, nextScreenVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, nextScreenVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(nextScreenVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(nextScreenVisibleRowIndex)) { return true; } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, nextScreenVisibleRowIndex, true, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, nextScreenVisibleRowIndex, true, false, false); // Debug.Assert(success); return true; } } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; } return true; } @@ -23178,16 +23178,16 @@ protected bool ProcessNextKey(Keys keyData) protected bool ProcessPriorKey(Keys keyData) { bool success; - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); int firstVisibleColumnIndex = (dataGridViewColumn == null) ? -1 : dataGridViewColumn.Index; if (firstVisibleColumnIndex == -1) { return false; } int previousScreenVisibleRowIndexTmp, previousScreenVisibleRowIndex = -1; - if (this.ptCurrentCell.Y == -1) + if (ptCurrentCell.Y == -1) { - previousScreenVisibleRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + previousScreenVisibleRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); if (previousScreenVisibleRowIndex == -1) { return false; @@ -23195,17 +23195,17 @@ protected bool ProcessPriorKey(Keys keyData) } else { - previousScreenVisibleRowIndex = this.ptCurrentCell.Y; + previousScreenVisibleRowIndex = ptCurrentCell.Y; } int jumpRows; - if ((this.Rows.GetRowState(previousScreenVisibleRowIndex) & DataGridViewElementStates.Frozen) != 0) + if ((Rows.GetRowState(previousScreenVisibleRowIndex) & DataGridViewElementStates.Frozen) != 0) { - jumpRows = this.displayedBandsInfo.NumTotallyDisplayedFrozenRows; + jumpRows = displayedBandsInfo.NumTotallyDisplayedFrozenRows; } else { - jumpRows = this.displayedBandsInfo.NumTotallyDisplayedScrollingRows; + jumpRows = displayedBandsInfo.NumTotallyDisplayedScrollingRows; } if (jumpRows == 0) { @@ -23215,7 +23215,7 @@ protected bool ProcessPriorKey(Keys keyData) Debug.Assert(previousScreenVisibleRowIndexTmp != -1); while (jumpRows > 0 && previousScreenVisibleRowIndexTmp != -1) { - previousScreenVisibleRowIndexTmp = this.Rows.GetPreviousRow(previousScreenVisibleRowIndex, DataGridViewElementStates.Visible); + previousScreenVisibleRowIndexTmp = Rows.GetPreviousRow(previousScreenVisibleRowIndex, DataGridViewElementStates.Visible); if (previousScreenVisibleRowIndexTmp != -1) { previousScreenVisibleRowIndex = previousScreenVisibleRowIndexTmp; @@ -23223,28 +23223,28 @@ protected bool ProcessPriorKey(Keys keyData) jumpRows--; } - if ((this.Rows.GetRowState(previousScreenVisibleRowIndex) & DataGridViewElementStates.Frozen) != 0) + if ((Rows.GetRowState(previousScreenVisibleRowIndex) & DataGridViewElementStates.Frozen) != 0) { // Make sure the first scrolling row is visible if any - int firstDisplayedScrollingRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); + int firstDisplayedScrollingRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); if (firstDisplayedScrollingRowIndex != -1 && - !ScrollIntoView(this.ptCurrentCell.X == -1 ? firstVisibleColumnIndex : this.ptCurrentCell.X, + !ScrollIntoView(ptCurrentCell.X == -1 ? firstVisibleColumnIndex : ptCurrentCell.X, firstDisplayedScrollingRowIndex, true)) { return true; } // Also, first visible frozen row should become current one - there is no reason to jump to another frozen row. - previousScreenVisibleRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + previousScreenVisibleRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); } Debug.Assert(previousScreenVisibleRowIndex != -1); - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: @@ -23269,112 +23269,112 @@ protected bool ProcessPriorKey(Keys keyData) return true; } - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: - if (!ScrollIntoView(this.ptCurrentCell.X, previousScreenVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, previousScreenVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(previousScreenVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(previousScreenVisibleRowIndex)) { return true; } - if ((keyData & Keys.Shift) == Keys.Shift && this.MultiSelect) + if ((keyData & Keys.Shift) == Keys.Shift && MultiSelect) { - Debug.Assert(this.ptAnchorCell.Y >= 0); - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - if (this.ptAnchorCell.X == -1) + Debug.Assert(ptAnchorCell.Y >= 0); + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + if (ptAnchorCell.X == -1) { return true; } - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, previousScreenVisibleRowIndex); + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, previousScreenVisibleRowIndex); } else { ClearSelection(); - SetSelectedCellCore(this.ptCurrentCell.X, previousScreenVisibleRowIndex, true); + SetSelectedCellCore(ptCurrentCell.X, previousScreenVisibleRowIndex, true); } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, previousScreenVisibleRowIndex, false, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, previousScreenVisibleRowIndex, false, false, false); // Debug.Assert(success); return true; case DataGridViewSelectionMode.FullRowSelect: - if (!ScrollIntoView(this.ptCurrentCell.X, previousScreenVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, previousScreenVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(previousScreenVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(previousScreenVisibleRowIndex)) { return true; } ClearSelection(); - if ((keyData & Keys.Shift) == Keys.Shift && this.MultiSelect) + if ((keyData & Keys.Shift) == Keys.Shift && MultiSelect) { - Debug.Assert(this.ptAnchorCell.Y >= 0); - if (this.ptAnchorCell.Y == -1) + Debug.Assert(ptAnchorCell.Y >= 0); + if (ptAnchorCell.Y == -1) { return true; } - if (this.ptAnchorCell.Y < previousScreenVisibleRowIndex) + if (ptAnchorCell.Y < previousScreenVisibleRowIndex) { - SelectRowRange(this.ptAnchorCell.Y, previousScreenVisibleRowIndex, true); + SelectRowRange(ptAnchorCell.Y, previousScreenVisibleRowIndex, true); } else { - SelectRowRange(previousScreenVisibleRowIndex, this.ptAnchorCell.Y, true); + SelectRowRange(previousScreenVisibleRowIndex, ptAnchorCell.Y, true); } } else { SetSelectedRowCore(previousScreenVisibleRowIndex, true); } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, previousScreenVisibleRowIndex, false, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, previousScreenVisibleRowIndex, false, false, false); // Debug.Assert(success); return true; case DataGridViewSelectionMode.RowHeaderSelect: - if (!ScrollIntoView(this.ptCurrentCell.X, previousScreenVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, previousScreenVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(previousScreenVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(previousScreenVisibleRowIndex)) { return true; } - if ((keyData & Keys.Shift) == Keys.Shift && this.MultiSelect) + if ((keyData & Keys.Shift) == Keys.Shift && MultiSelect) { - Debug.Assert(this.ptAnchorCell.Y >= 0); - if (this.ptAnchorCell.Y == -1) + Debug.Assert(ptAnchorCell.Y >= 0); + if (ptAnchorCell.Y == -1) { return true; } - if ((this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) + if ((Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { ClearSelection(); - if (this.ptAnchorCell.Y < previousScreenVisibleRowIndex) + if (ptAnchorCell.Y < previousScreenVisibleRowIndex) { - SelectRowRange(this.ptAnchorCell.Y, previousScreenVisibleRowIndex, true); + SelectRowRange(ptAnchorCell.Y, previousScreenVisibleRowIndex, true); } else { - SelectRowRange(previousScreenVisibleRowIndex, this.ptAnchorCell.Y, true); + SelectRowRange(previousScreenVisibleRowIndex, ptAnchorCell.Y, true); } } else { - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, previousScreenVisibleRowIndex); + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, previousScreenVisibleRowIndex); } } else { - if ((this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) + if ((Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { ClearSelection(); SetSelectedRowCore(previousScreenVisibleRowIndex, true); @@ -23382,23 +23382,23 @@ protected bool ProcessPriorKey(Keys keyData) else { ClearSelection(); - SetSelectedCellCore(this.ptCurrentCell.X, previousScreenVisibleRowIndex, true); + SetSelectedCellCore(ptCurrentCell.X, previousScreenVisibleRowIndex, true); } } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, previousScreenVisibleRowIndex, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, previousScreenVisibleRowIndex, !MultiSelect, false, false); // Debug.Assert(success); return true; case DataGridViewSelectionMode.FullColumnSelect: - if (!ScrollIntoView(this.ptCurrentCell.X, previousScreenVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, previousScreenVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(previousScreenVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(previousScreenVisibleRowIndex)) { return true; } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, previousScreenVisibleRowIndex, true, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, previousScreenVisibleRowIndex, true, false, false); // Microsoft: SetCurrentCellAddressCore can fail if by navigating to a cell the list under the // DataGridView changes. // Debug.Assert(success); @@ -23407,14 +23407,14 @@ protected bool ProcessPriorKey(Keys keyData) } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; } return true; } protected bool ProcessRightKey(Keys keyData) { - if (this.RightToLeftInternal) + if (RightToLeftInternal) { return ProcessLeftKeyPrivate(keyData); } @@ -23426,25 +23426,25 @@ protected bool ProcessRightKey(Keys keyData) private bool ProcessRightKeyPrivate(Keys keyData) { - bool? resizeResult = this.ProcessColumnResize(keyData, this.keyboardResizeStep); + bool? resizeResult = ProcessColumnResize(keyData, keyboardResizeStep); if (resizeResult.HasValue) { return resizeResult.Value; } bool success; - DataGridViewColumn dataGridViewColumn = this.Columns.GetLastColumn(DataGridViewElementStates.Visible, + DataGridViewColumn dataGridViewColumn = Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.None); int lastVisibleColumnIndex = (dataGridViewColumn == null) ? -1 : dataGridViewColumn.Index; - int firstVisibleRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + int firstVisibleRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); if (lastVisibleColumnIndex == -1 || firstVisibleRowIndex == -1) { return false; } int nextVisibleColumnIndex = -1; - if (this.ptCurrentCell.X != -1) + if (ptCurrentCell.X != -1) { - dataGridViewColumn = this.Columns.GetNextColumn(this.Columns[this.ptCurrentCell.X], + dataGridViewColumn = Columns.GetNextColumn(Columns[ptCurrentCell.X], DataGridViewElementStates.Visible, DataGridViewElementStates.None); if (dataGridViewColumn != null) @@ -23453,10 +23453,10 @@ private bool ProcessRightKeyPrivate(Keys keyData) } } - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: case DataGridViewSelectionMode.RowHeaderSelect: @@ -23468,7 +23468,7 @@ private bool ProcessRightKeyPrivate(Keys keyData) { if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(lastVisibleColumnIndex, firstVisibleRowIndex, true); @@ -23487,38 +23487,38 @@ private bool ProcessRightKeyPrivate(Keys keyData) { return true; } - if (!ScrollIntoView(nextVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(nextVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(nextVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(nextVisibleColumnIndex)) { return true; } - if (this.MultiSelect) + if (MultiSelect) { //SelectCellUnorderedRange(this.ptAnchorCell.X, this.ptCurrentCell.Y, nextVisibleColumnIndex, this.ptCurrentCell.Y, true); - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - if (this.ptAnchorCell.X == -1) + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + if (ptAnchorCell.X == -1) { return true; } - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, nextVisibleColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, oldEdgeRowIndex); + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, nextVisibleColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, oldEdgeRowIndex); } else { ClearSelection(); - SetSelectedCellCore(nextVisibleColumnIndex, this.ptCurrentCell.Y, true); + SetSelectedCellCore(nextVisibleColumnIndex, ptCurrentCell.Y, true); } - success = SetCurrentCellAddressCore(nextVisibleColumnIndex, this.ptCurrentCell.Y, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(nextVisibleColumnIndex, ptCurrentCell.Y, !MultiSelect, false, false); Debug.Assert(success); } } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(lastVisibleColumnIndex, firstVisibleRowIndex, true); @@ -23537,17 +23537,17 @@ private bool ProcessRightKeyPrivate(Keys keyData) { return true; } - if (!ScrollIntoView(nextVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(nextVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(nextVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(nextVisibleColumnIndex)) { return true; } ClearSelection(); - SetSelectedCellCore(nextVisibleColumnIndex, this.ptCurrentCell.Y, true); - success = SetCurrentCellAddressCore(nextVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + SetSelectedCellCore(nextVisibleColumnIndex, ptCurrentCell.Y, true); + success = SetCurrentCellAddressCore(nextVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } } @@ -23563,7 +23563,7 @@ private bool ProcessRightKeyPrivate(Keys keyData) { if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedColumnCore(lastVisibleColumnIndex, true); @@ -23582,41 +23582,41 @@ private bool ProcessRightKeyPrivate(Keys keyData) { return true; } - if (!ScrollIntoView(nextVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(nextVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(nextVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(nextVisibleColumnIndex)) { return true; } ClearSelection(); - if (this.MultiSelect) + if (MultiSelect) { - if (this.ptAnchorCell.X == -1) + if (ptAnchorCell.X == -1) { return true; } - if (this.Columns.DisplayInOrder(this.ptAnchorCell.X, nextVisibleColumnIndex)) + if (Columns.DisplayInOrder(ptAnchorCell.X, nextVisibleColumnIndex)) { - SelectColumnRange(this.ptAnchorCell.X, nextVisibleColumnIndex, true); + SelectColumnRange(ptAnchorCell.X, nextVisibleColumnIndex, true); } else { - SelectColumnRange(nextVisibleColumnIndex, this.ptAnchorCell.X, true); + SelectColumnRange(nextVisibleColumnIndex, ptAnchorCell.X, true); } } else { SetSelectedColumnCore(nextVisibleColumnIndex, true); } - success = SetCurrentCellAddressCore(nextVisibleColumnIndex, this.ptCurrentCell.Y, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(nextVisibleColumnIndex, ptCurrentCell.Y, !MultiSelect, false, false); Debug.Assert(success); } } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedColumnCore(lastVisibleColumnIndex, true); @@ -23635,17 +23635,17 @@ private bool ProcessRightKeyPrivate(Keys keyData) { return true; } - if (!ScrollIntoView(nextVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(nextVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(nextVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(nextVisibleColumnIndex)) { return true; } ClearSelection(); SetSelectedColumnCore(nextVisibleColumnIndex, true); - success = SetCurrentCellAddressCore(nextVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + success = SetCurrentCellAddressCore(nextVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } } @@ -23661,7 +23661,7 @@ private bool ProcessRightKeyPrivate(Keys keyData) { if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(lastVisibleColumnIndex, firstVisibleRowIndex, true); @@ -23680,30 +23680,30 @@ private bool ProcessRightKeyPrivate(Keys keyData) { return true; } - if (!ScrollIntoView(nextVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(nextVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(nextVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(nextVisibleColumnIndex)) { return true; } - if (this.Columns[this.ptCurrentCell.X].Selected) + if (Columns[ptCurrentCell.X].Selected) { ClearSelection(); - if (this.MultiSelect) + if (MultiSelect) { - if (this.ptAnchorCell.X == -1) + if (ptAnchorCell.X == -1) { return true; } - if (this.Columns.DisplayInOrder(this.ptAnchorCell.X, nextVisibleColumnIndex)) + if (Columns.DisplayInOrder(ptAnchorCell.X, nextVisibleColumnIndex)) { - SelectColumnRange(this.ptAnchorCell.X, nextVisibleColumnIndex, true); + SelectColumnRange(ptAnchorCell.X, nextVisibleColumnIndex, true); } else { - SelectColumnRange(nextVisibleColumnIndex, this.ptAnchorCell.X, true); + SelectColumnRange(nextVisibleColumnIndex, ptAnchorCell.X, true); } } else @@ -23713,31 +23713,31 @@ private bool ProcessRightKeyPrivate(Keys keyData) } else { - if (this.MultiSelect) + if (MultiSelect) { - if (this.ptAnchorCell.X == -1) + if (ptAnchorCell.X == -1) { return true; } //SelectCellUnorderedRange(this.ptAnchorCell.X, this.ptCurrentCell.Y, nextVisibleColumnIndex, this.ptCurrentCell.Y, true); - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, nextVisibleColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, oldEdgeRowIndex); + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, nextVisibleColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, oldEdgeRowIndex); } else { ClearSelection(); - SetSelectedCellCore(nextVisibleColumnIndex, this.ptCurrentCell.Y, true); + SetSelectedCellCore(nextVisibleColumnIndex, ptCurrentCell.Y, true); } } - success = SetCurrentCellAddressCore(nextVisibleColumnIndex, this.ptCurrentCell.Y, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(nextVisibleColumnIndex, ptCurrentCell.Y, !MultiSelect, false, false); Debug.Assert(success); } } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(lastVisibleColumnIndex, firstVisibleRowIndex, true); @@ -23756,15 +23756,15 @@ private bool ProcessRightKeyPrivate(Keys keyData) { return true; } - if (!ScrollIntoView(nextVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(nextVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsColumnOutOfBounds(nextVisibleColumnIndex)) + if (ptCurrentCell.X == -1 || IsColumnOutOfBounds(nextVisibleColumnIndex)) { return true; } - if (this.Columns[this.ptCurrentCell.X].Selected) + if (Columns[ptCurrentCell.X].Selected) { ClearSelection(); SetSelectedColumnCore(nextVisibleColumnIndex, true); @@ -23772,9 +23772,9 @@ private bool ProcessRightKeyPrivate(Keys keyData) else { ClearSelection(); - SetSelectedCellCore(nextVisibleColumnIndex, this.ptCurrentCell.Y, true); + SetSelectedCellCore(nextVisibleColumnIndex, ptCurrentCell.Y, true); } - success = SetCurrentCellAddressCore(nextVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + success = SetCurrentCellAddressCore(nextVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } } @@ -23788,7 +23788,7 @@ private bool ProcessRightKeyPrivate(Keys keyData) } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedRowCore(firstVisibleRowIndex, true); @@ -23807,15 +23807,15 @@ private bool ProcessRightKeyPrivate(Keys keyData) { return true; } - if (!ScrollIntoView(nextVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(nextVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(nextVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(nextVisibleColumnIndex)) { return true; } - success = SetCurrentCellAddressCore(nextVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + success = SetCurrentCellAddressCore(nextVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } } @@ -23824,7 +23824,7 @@ private bool ProcessRightKeyPrivate(Keys keyData) } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; } return true; } @@ -23835,16 +23835,16 @@ private bool ProcessRightMost(bool shift, int lastVisibleColumnIndex, int firstV { bool success; - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: case DataGridViewSelectionMode.RowHeaderSelect: if (shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(lastVisibleColumnIndex, firstVisibleRowIndex, true); @@ -23859,40 +23859,40 @@ private bool ProcessRightMost(bool shift, int lastVisibleColumnIndex, int firstV } else { - if (!ScrollIntoView(lastVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(lastVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(lastVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(lastVisibleColumnIndex)) { return true; } - if (this.MultiSelect) + if (MultiSelect) { - Debug.Assert(this.ptAnchorCell.X >= 0); - if (this.ptAnchorCell.X == -1) + Debug.Assert(ptAnchorCell.X >= 0); + if (ptAnchorCell.X == -1) { return true; } - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, lastVisibleColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, oldEdgeRowIndex); - success = SetCurrentCellAddressCore(lastVisibleColumnIndex, this.ptCurrentCell.Y, false, false, false); + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, lastVisibleColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, oldEdgeRowIndex); + success = SetCurrentCellAddressCore(lastVisibleColumnIndex, ptCurrentCell.Y, false, false, false); Debug.Assert(success); } else { ClearSelection(); - SetSelectedCellCore(lastVisibleColumnIndex, this.ptCurrentCell.Y, true); - success = SetCurrentCellAddressCore(lastVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + SetSelectedCellCore(lastVisibleColumnIndex, ptCurrentCell.Y, true); + success = SetCurrentCellAddressCore(lastVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } } } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(lastVisibleColumnIndex, firstVisibleRowIndex, true); @@ -23907,17 +23907,17 @@ private bool ProcessRightMost(bool shift, int lastVisibleColumnIndex, int firstV } else { - if (!ScrollIntoView(lastVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(lastVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(lastVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(lastVisibleColumnIndex)) { return true; } ClearSelection(); - SetSelectedCellCore(lastVisibleColumnIndex, this.ptCurrentCell.Y, true); - success = SetCurrentCellAddressCore(lastVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + SetSelectedCellCore(lastVisibleColumnIndex, ptCurrentCell.Y, true); + success = SetCurrentCellAddressCore(lastVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } } @@ -23926,7 +23926,7 @@ private bool ProcessRightMost(bool shift, int lastVisibleColumnIndex, int firstV case DataGridViewSelectionMode.FullColumnSelect: if (shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedColumnCore(lastVisibleColumnIndex, true); @@ -23941,38 +23941,38 @@ private bool ProcessRightMost(bool shift, int lastVisibleColumnIndex, int firstV } else { - if (!ScrollIntoView(lastVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(lastVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(lastVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(lastVisibleColumnIndex)) { return true; } - if (this.MultiSelect) + if (MultiSelect) { - if (this.ptAnchorCell.X == -1) + if (ptAnchorCell.X == -1) { return true; } ClearSelection(); - Debug.Assert(this.ptAnchorCell.X >= 0); - SelectColumnRange(this.ptAnchorCell.X, lastVisibleColumnIndex, true); - success = SetCurrentCellAddressCore(lastVisibleColumnIndex, this.ptCurrentCell.Y, false, false, false); + Debug.Assert(ptAnchorCell.X >= 0); + SelectColumnRange(ptAnchorCell.X, lastVisibleColumnIndex, true); + success = SetCurrentCellAddressCore(lastVisibleColumnIndex, ptCurrentCell.Y, false, false, false); Debug.Assert(success); } else { - SetSelectedColumnCore(this.ptCurrentCell.X, false); + SetSelectedColumnCore(ptCurrentCell.X, false); SetSelectedColumnCore(lastVisibleColumnIndex, true); - success = SetCurrentCellAddressCore(lastVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + success = SetCurrentCellAddressCore(lastVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } } } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedColumnCore(lastVisibleColumnIndex, true); @@ -23987,17 +23987,17 @@ private bool ProcessRightMost(bool shift, int lastVisibleColumnIndex, int firstV } else { - if (!ScrollIntoView(lastVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(lastVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(lastVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(lastVisibleColumnIndex)) { return true; } ClearSelection(); SetSelectedColumnCore(lastVisibleColumnIndex, true); - success = SetCurrentCellAddressCore(lastVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + success = SetCurrentCellAddressCore(lastVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } } @@ -24006,7 +24006,7 @@ private bool ProcessRightMost(bool shift, int lastVisibleColumnIndex, int firstV case DataGridViewSelectionMode.ColumnHeaderSelect: if (shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(lastVisibleColumnIndex, firstVisibleRowIndex, true); @@ -24021,58 +24021,58 @@ private bool ProcessRightMost(bool shift, int lastVisibleColumnIndex, int firstV } else { - if (!ScrollIntoView(lastVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(lastVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(lastVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(lastVisibleColumnIndex)) { return true; } - if (this.MultiSelect) + if (MultiSelect) { - Debug.Assert(this.ptAnchorCell.X >= 0); - if (this.ptAnchorCell.X == -1) + Debug.Assert(ptAnchorCell.X >= 0); + if (ptAnchorCell.X == -1) { return true; } - if (this.Columns[this.ptCurrentCell.X].Selected) + if (Columns[ptCurrentCell.X].Selected) { ClearSelection(); - SelectColumnRange(this.ptAnchorCell.X, lastVisibleColumnIndex, true); + SelectColumnRange(ptAnchorCell.X, lastVisibleColumnIndex, true); } else { //ClearSelection(); //SelectCellRange(this.ptAnchorCell.X, this.ptCurrentCell.Y, lastVisibleColumnIndex, this.ptCurrentCell.Y, true); - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, lastVisibleColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, oldEdgeRowIndex); + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, lastVisibleColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, oldEdgeRowIndex); } - success = SetCurrentCellAddressCore(lastVisibleColumnIndex, this.ptCurrentCell.Y, false, false, false); + success = SetCurrentCellAddressCore(lastVisibleColumnIndex, ptCurrentCell.Y, false, false, false); Debug.Assert(success); } else { - if (this.Columns[this.ptCurrentCell.X].Selected) + if (Columns[ptCurrentCell.X].Selected) { - SetSelectedColumnCore(this.ptCurrentCell.X, false); + SetSelectedColumnCore(ptCurrentCell.X, false); SetSelectedColumnCore(lastVisibleColumnIndex, true); } else { - SetSelectedCellCore(this.ptCurrentCell.X, this.ptCurrentCell.Y, false); - SetSelectedCellCore(lastVisibleColumnIndex, this.ptCurrentCell.Y, true); + SetSelectedCellCore(ptCurrentCell.X, ptCurrentCell.Y, false); + SetSelectedCellCore(lastVisibleColumnIndex, ptCurrentCell.Y, true); } - success = SetCurrentCellAddressCore(lastVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + success = SetCurrentCellAddressCore(lastVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } } } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(lastVisibleColumnIndex, firstVisibleRowIndex, true); @@ -24087,15 +24087,15 @@ private bool ProcessRightMost(bool shift, int lastVisibleColumnIndex, int firstV } else { - if (!ScrollIntoView(lastVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(lastVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(lastVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(lastVisibleColumnIndex)) { return true; } - if (this.Columns[this.ptCurrentCell.X].Selected) + if (Columns[ptCurrentCell.X].Selected) { ClearSelection(); SetSelectedColumnCore(lastVisibleColumnIndex, true); @@ -24103,16 +24103,16 @@ private bool ProcessRightMost(bool shift, int lastVisibleColumnIndex, int firstV else { ClearSelection(); - SetSelectedCellCore(lastVisibleColumnIndex, this.ptCurrentCell.Y, true); + SetSelectedCellCore(lastVisibleColumnIndex, ptCurrentCell.Y, true); } - success = SetCurrentCellAddressCore(lastVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + success = SetCurrentCellAddressCore(lastVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } } return true; case DataGridViewSelectionMode.FullRowSelect: - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedRowCore(firstVisibleRowIndex, true); @@ -24127,15 +24127,15 @@ private bool ProcessRightMost(bool shift, int lastVisibleColumnIndex, int firstV } else { - if (!ScrollIntoView(lastVisibleColumnIndex, this.ptCurrentCell.Y, true)) + if (!ScrollIntoView(lastVisibleColumnIndex, ptCurrentCell.Y, true)) { return true; } - if (this.ptCurrentCell.Y == -1 || IsColumnOutOfBounds(lastVisibleColumnIndex)) + if (ptCurrentCell.Y == -1 || IsColumnOutOfBounds(lastVisibleColumnIndex)) { return true; } - success = SetCurrentCellAddressCore(lastVisibleColumnIndex, this.ptCurrentCell.Y, true, false, false); + success = SetCurrentCellAddressCore(lastVisibleColumnIndex, ptCurrentCell.Y, true, false, false); Debug.Assert(success); } return true; @@ -24143,7 +24143,7 @@ private bool ProcessRightMost(bool shift, int lastVisibleColumnIndex, int firstV } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; } return true; } @@ -24151,28 +24151,28 @@ private bool ProcessRightMost(bool shift, int lastVisibleColumnIndex, int firstV protected bool ProcessSpaceKey(Keys keyData) { if ((keyData & (Keys.Control | Keys.Shift | Keys.Alt)) == Keys.Shift && - this.ptCurrentCell.X != -1) + ptCurrentCell.X != -1) { - this.noSelectionChangeCount++; + noSelectionChangeCount++; bool switchedToBulkPaint = false; - if (this.selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) + if (selectedBandIndexes.Count > DATAGRIDVIEW_bulkPaintThreshold) { - this.inBulkPaintCount++; + inBulkPaintCount++; switchedToBulkPaint = true; } try { - if (this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) + if (SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) { // Same as clicking the column header cell - Debug.Assert(this.MultiSelect || this.selectedBandIndexes.Count <= 1); + Debug.Assert(MultiSelect || selectedBandIndexes.Count <= 1); int bandIndex = 0; - while (bandIndex < this.selectedBandIndexes.Count) + while (bandIndex < selectedBandIndexes.Count) { - if (this.selectedBandIndexes[bandIndex] != this.ptCurrentCell.X) + if (selectedBandIndexes[bandIndex] != ptCurrentCell.X) { // deselect currently selected column - SetSelectedColumnCore(this.selectedBandIndexes[bandIndex], false); + SetSelectedColumnCore(selectedBandIndexes[bandIndex], false); } else { @@ -24180,24 +24180,24 @@ protected bool ProcessSpaceKey(Keys keyData) } } RemoveIndividuallySelectedCells(); - if (!this.Columns[this.ptCurrentCell.X].Selected) + if (!Columns[ptCurrentCell.X].Selected) { - Debug.Assert(!this.selectedBandIndexes.Contains(this.ptCurrentCell.X)); - SetSelectedColumnCore(this.ptCurrentCell.X, true); + Debug.Assert(!selectedBandIndexes.Contains(ptCurrentCell.X)); + SetSelectedColumnCore(ptCurrentCell.X, true); } return true; } - else if (this.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) + else if (SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) { // Same as clicking the row header cell - Debug.Assert(this.MultiSelect || this.selectedBandIndexes.Count <= 1); + Debug.Assert(MultiSelect || selectedBandIndexes.Count <= 1); int bandIndex = 0; - while (bandIndex < this.selectedBandIndexes.Count) + while (bandIndex < selectedBandIndexes.Count) { - if (this.selectedBandIndexes[bandIndex] != this.ptCurrentCell.Y) + if (selectedBandIndexes[bandIndex] != ptCurrentCell.Y) { // deselect currently selected row - SetSelectedRowCore(this.selectedBandIndexes[bandIndex], false); + SetSelectedRowCore(selectedBandIndexes[bandIndex], false); } else { @@ -24205,17 +24205,17 @@ protected bool ProcessSpaceKey(Keys keyData) } } RemoveIndividuallySelectedCells(); - if ((this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) == 0) + if ((Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Selected) == 0) { - Debug.Assert(!this.selectedBandIndexes.Contains(this.ptCurrentCell.Y)); - SetSelectedRowCore(this.ptCurrentCell.Y, true); + Debug.Assert(!selectedBandIndexes.Contains(ptCurrentCell.Y)); + SetSelectedRowCore(ptCurrentCell.Y, true); } return true; } } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; if (switchedToBulkPaint) { ExitBulkPaint(-1, -1); @@ -24232,13 +24232,13 @@ protected bool ProcessSpaceKey(Keys keyData) /// protected bool ProcessTabKey(Keys keyData) { - if (this.StandardTab) + if (StandardTab) { if ((keyData & Keys.Control) == Keys.Control) { if ((keyData & Keys.Shift) == Keys.Shift) { - if (!this.VisibleCellExists || this.CurrentCellIsFirstVisibleCell) + if (!VisibleCellExists || CurrentCellIsFirstVisibleCell) { // Goto previous control return false; @@ -24251,7 +24251,7 @@ protected bool ProcessTabKey(Keys keyData) } else { - if (!this.VisibleCellExists || this.CurrentCellIsLastVisibleCell) + if (!VisibleCellExists || CurrentCellIsLastVisibleCell) { // Goto next control return false; @@ -24298,7 +24298,7 @@ protected bool ProcessTabKey(Keys keyData) { if ((keyData & Keys.Shift) == Keys.Shift) { - if (!this.VisibleCellExists || this.CurrentCellIsFirstVisibleCell) + if (!VisibleCellExists || CurrentCellIsFirstVisibleCell) { // Goto previous control return false; @@ -24311,7 +24311,7 @@ protected bool ProcessTabKey(Keys keyData) } else { - if (!this.VisibleCellExists || this.CurrentCellIsLastVisibleCell) + if (!VisibleCellExists || CurrentCellIsLastVisibleCell) { // Goto next control return false; @@ -24416,23 +24416,23 @@ protected virtual bool ProcessDataGridViewKey(KeyEventArgs e) protected bool ProcessUpKey(Keys keyData) { bool success; - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); int firstVisibleColumnIndex = (dataGridViewColumn == null) ? -1 : dataGridViewColumn.Index; - int firstVisibleRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + int firstVisibleRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); if (firstVisibleColumnIndex == -1 || firstVisibleRowIndex == -1) { return false; } int previousVisibleRowIndex = -1; - if (this.ptCurrentCell.Y != -1) + if (ptCurrentCell.Y != -1) { - previousVisibleRowIndex = this.Rows.GetPreviousRow(this.ptCurrentCell.Y, DataGridViewElementStates.Visible); + previousVisibleRowIndex = Rows.GetPreviousRow(ptCurrentCell.Y, DataGridViewElementStates.Visible); } - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: @@ -24440,7 +24440,7 @@ protected bool ProcessUpKey(Keys keyData) { if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, firstVisibleRowIndex, true); @@ -24457,48 +24457,48 @@ protected bool ProcessUpKey(Keys keyData) } else { - if (this.MultiSelect) + if (MultiSelect) { - if (!ScrollIntoView(this.ptCurrentCell.X, firstVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, firstVisibleRowIndex, true)) { return true; } - if (this.ptAnchorCell.X == -1 || this.ptCurrentCell.X == -1 || + if (ptAnchorCell.X == -1 || ptCurrentCell.X == -1 || IsRowOutOfBounds(firstVisibleRowIndex)) { return true; } //ClearSelection(); - Debug.Assert(this.ptAnchorCell.Y >= 0); + Debug.Assert(ptAnchorCell.Y >= 0); //SelectCellRange(this.ptCurrentCell.X, firstVisibleRowIndex, this.ptCurrentCell.X, this.ptAnchorCell.Y, true); - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, firstVisibleRowIndex); - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, firstVisibleRowIndex, false, false, false); + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, firstVisibleRowIndex); + success = SetCurrentCellAddressCore(ptCurrentCell.X, firstVisibleRowIndex, false, false, false); // Debug.Assert(success); } else { - if (!ScrollIntoView(this.ptCurrentCell.X, firstVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, firstVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(firstVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(firstVisibleRowIndex)) { return true; } //SetSelectedCellCore(this.ptCurrentCell.X, this.ptCurrentCell.Y, false); ClearSelection(); - SetSelectedCellCore(this.ptCurrentCell.X, firstVisibleRowIndex, true); - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, firstVisibleRowIndex, true, false, false); + SetSelectedCellCore(ptCurrentCell.X, firstVisibleRowIndex, true); + success = SetCurrentCellAddressCore(ptCurrentCell.X, firstVisibleRowIndex, true, false, false); // Debug.Assert(success); } } } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, firstVisibleRowIndex, true); @@ -24513,17 +24513,17 @@ protected bool ProcessUpKey(Keys keyData) } else { - if (!ScrollIntoView(this.ptCurrentCell.X, firstVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, firstVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(firstVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(firstVisibleRowIndex)) { return true; } ClearSelection(); - SetSelectedCellCore(this.ptCurrentCell.X, firstVisibleRowIndex, true); - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, firstVisibleRowIndex, true, false, false); + SetSelectedCellCore(ptCurrentCell.X, firstVisibleRowIndex, true); + success = SetCurrentCellAddressCore(ptCurrentCell.X, firstVisibleRowIndex, true, false, false); // Debug.Assert(success); } } @@ -24532,7 +24532,7 @@ protected bool ProcessUpKey(Keys keyData) { if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, firstVisibleRowIndex, true); @@ -24551,39 +24551,39 @@ protected bool ProcessUpKey(Keys keyData) { return true; } - if (!ScrollIntoView(this.ptCurrentCell.X, previousVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, previousVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(previousVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(previousVisibleRowIndex)) { return true; } - if (this.MultiSelect) + if (MultiSelect) { - Debug.Assert(this.ptAnchorCell.Y >= 0); - if (this.ptAnchorCell.Y == -1) + Debug.Assert(ptAnchorCell.Y >= 0); + if (ptAnchorCell.Y == -1) { return true; } //SelectCellUnorderedRange(this.ptCurrentCell.X, previousVisibleRowIndex, this.ptCurrentCell.X, this.ptAnchorCell.Y, true); - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, previousVisibleRowIndex); + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, previousVisibleRowIndex); } else { ClearSelection(); - SetSelectedCellCore(this.ptCurrentCell.X, previousVisibleRowIndex, true); + SetSelectedCellCore(ptCurrentCell.X, previousVisibleRowIndex, true); } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, previousVisibleRowIndex, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, previousVisibleRowIndex, !MultiSelect, false, false); // Debug.Assert(success); } } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, firstVisibleRowIndex, true); @@ -24602,17 +24602,17 @@ protected bool ProcessUpKey(Keys keyData) { return true; } - if (!ScrollIntoView(this.ptCurrentCell.X, previousVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, previousVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(previousVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(previousVisibleRowIndex)) { return true; } ClearSelection(); - SetSelectedCellCore(this.ptCurrentCell.X, previousVisibleRowIndex, true); - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, previousVisibleRowIndex, true, false, false); + SetSelectedCellCore(ptCurrentCell.X, previousVisibleRowIndex, true); + success = SetCurrentCellAddressCore(ptCurrentCell.X, previousVisibleRowIndex, true, false, false); // Debug.Assert(success); } } @@ -24624,7 +24624,7 @@ protected bool ProcessUpKey(Keys keyData) { if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedRowCore(firstVisibleRowIndex, true); @@ -24639,43 +24639,43 @@ protected bool ProcessUpKey(Keys keyData) } else { - if (this.MultiSelect) + if (MultiSelect) { - if (!ScrollIntoView(this.ptCurrentCell.X, firstVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, firstVisibleRowIndex, true)) { return true; } - if (this.ptAnchorCell.X == -1 || this.ptCurrentCell.X == -1 || + if (ptAnchorCell.X == -1 || ptCurrentCell.X == -1 || IsRowOutOfBounds(firstVisibleRowIndex)) { return true; } ClearSelection(); - Debug.Assert(this.ptAnchorCell.Y >= 0); - SelectRowRange(firstVisibleRowIndex, this.ptAnchorCell.Y, true); - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, firstVisibleRowIndex, false, false, false); + Debug.Assert(ptAnchorCell.Y >= 0); + SelectRowRange(firstVisibleRowIndex, ptAnchorCell.Y, true); + success = SetCurrentCellAddressCore(ptCurrentCell.X, firstVisibleRowIndex, false, false, false); // Debug.Assert(success); } else { - if (!ScrollIntoView(this.ptCurrentCell.X, firstVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, firstVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(firstVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(firstVisibleRowIndex)) { return true; } - SetSelectedRowCore(this.ptCurrentCell.Y, false); + SetSelectedRowCore(ptCurrentCell.Y, false); SetSelectedRowCore(firstVisibleRowIndex, true); - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, firstVisibleRowIndex, true, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, firstVisibleRowIndex, true, false, false); // Debug.Assert(success); } } } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedRowCore(firstVisibleRowIndex, true); @@ -24690,17 +24690,17 @@ protected bool ProcessUpKey(Keys keyData) } else { - if (!ScrollIntoView(this.ptCurrentCell.X, firstVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, firstVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(firstVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(firstVisibleRowIndex)) { return true; } ClearSelection(); SetSelectedRowCore(firstVisibleRowIndex, true); - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, firstVisibleRowIndex, true, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, firstVisibleRowIndex, true, false, false); // Debug.Assert(success); } } @@ -24709,7 +24709,7 @@ protected bool ProcessUpKey(Keys keyData) { if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedRowCore(firstVisibleRowIndex, true); @@ -24728,41 +24728,41 @@ protected bool ProcessUpKey(Keys keyData) { return true; } - if (!ScrollIntoView(this.ptCurrentCell.X, previousVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, previousVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(previousVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(previousVisibleRowIndex)) { return true; } ClearSelection(); - if (this.MultiSelect) + if (MultiSelect) { - if (this.ptAnchorCell.Y == -1) + if (ptAnchorCell.Y == -1) { return true; } - if (this.ptAnchorCell.Y >= previousVisibleRowIndex) + if (ptAnchorCell.Y >= previousVisibleRowIndex) { - SelectRowRange(previousVisibleRowIndex, this.ptAnchorCell.Y, true); + SelectRowRange(previousVisibleRowIndex, ptAnchorCell.Y, true); } else { - SelectRowRange(this.ptAnchorCell.Y, previousVisibleRowIndex, true); + SelectRowRange(ptAnchorCell.Y, previousVisibleRowIndex, true); } } else { SetSelectedRowCore(previousVisibleRowIndex, true); } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, previousVisibleRowIndex, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, previousVisibleRowIndex, !MultiSelect, false, false); // Debug.Assert(success); } } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedRowCore(firstVisibleRowIndex, true); @@ -24781,17 +24781,17 @@ protected bool ProcessUpKey(Keys keyData) { return true; } - if (!ScrollIntoView(this.ptCurrentCell.X, previousVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, previousVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(previousVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(previousVisibleRowIndex)) { return true; } ClearSelection(); SetSelectedRowCore(previousVisibleRowIndex, true); - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, previousVisibleRowIndex, true, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, previousVisibleRowIndex, true, false, false); // Debug.Assert(success); } } @@ -24803,7 +24803,7 @@ protected bool ProcessUpKey(Keys keyData) { if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, firstVisibleRowIndex, true); @@ -24818,63 +24818,63 @@ protected bool ProcessUpKey(Keys keyData) } else { - if (this.MultiSelect) + if (MultiSelect) { - if (!ScrollIntoView(this.ptCurrentCell.X, firstVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, firstVisibleRowIndex, true)) { return true; } - if (this.ptAnchorCell.X == -1 || this.ptCurrentCell.X == -1 || + if (ptAnchorCell.X == -1 || ptCurrentCell.X == -1 || IsRowOutOfBounds(firstVisibleRowIndex)) { return true; } - Debug.Assert(this.ptAnchorCell.Y >= 0); - if ((this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) + Debug.Assert(ptAnchorCell.Y >= 0); + if ((Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { ClearSelection(); - SelectRowRange(firstVisibleRowIndex, this.ptAnchorCell.Y, true); + SelectRowRange(firstVisibleRowIndex, ptAnchorCell.Y, true); } else { //ClearSelection(); //SelectCellRange(this.ptCurrentCell.X, firstVisibleRowIndex, this.ptCurrentCell.X, this.ptAnchorCell.Y, true); - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, firstVisibleRowIndex); + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, firstVisibleRowIndex); } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, firstVisibleRowIndex, false, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, firstVisibleRowIndex, false, false, false); // Debug.Assert(success); } else { - if (!ScrollIntoView(this.ptCurrentCell.X, firstVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, firstVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(firstVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(firstVisibleRowIndex)) { return true; } - if ((this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) + if ((Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { - SetSelectedRowCore(this.ptCurrentCell.Y, false); + SetSelectedRowCore(ptCurrentCell.Y, false); SetSelectedRowCore(firstVisibleRowIndex, true); } else { - SetSelectedCellCore(this.ptCurrentCell.X, this.ptCurrentCell.Y, false); - SetSelectedCellCore(this.ptCurrentCell.X, firstVisibleRowIndex, true); + SetSelectedCellCore(ptCurrentCell.X, ptCurrentCell.Y, false); + SetSelectedCellCore(ptCurrentCell.X, firstVisibleRowIndex, true); } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, firstVisibleRowIndex, true, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, firstVisibleRowIndex, true, false, false); // Debug.Assert(success); } } } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, firstVisibleRowIndex, true); @@ -24889,15 +24889,15 @@ protected bool ProcessUpKey(Keys keyData) } else { - if (!ScrollIntoView(this.ptCurrentCell.X, firstVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, firstVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(firstVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(firstVisibleRowIndex)) { return true; } - if ((this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) + if ((Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { ClearSelection(); SetSelectedRowCore(firstVisibleRowIndex, true); @@ -24905,9 +24905,9 @@ protected bool ProcessUpKey(Keys keyData) else { ClearSelection(); - SetSelectedCellCore(this.ptCurrentCell.X, firstVisibleRowIndex, true); + SetSelectedCellCore(ptCurrentCell.X, firstVisibleRowIndex, true); } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, firstVisibleRowIndex, true, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, firstVisibleRowIndex, true, false, false); // Debug.Assert(success); } } @@ -24916,7 +24916,7 @@ protected bool ProcessUpKey(Keys keyData) { if ((keyData & Keys.Shift) == Keys.Shift) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, firstVisibleRowIndex, true); @@ -24935,61 +24935,61 @@ protected bool ProcessUpKey(Keys keyData) { return true; } - if (!ScrollIntoView(this.ptCurrentCell.X, previousVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, previousVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(previousVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(previousVisibleRowIndex)) { return true; } - if ((this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) + if ((Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { ClearSelection(); - if (this.MultiSelect) + if (MultiSelect) { - if (this.ptAnchorCell.Y == -1) + if (ptAnchorCell.Y == -1) { return true; } - if (this.ptAnchorCell.Y >= previousVisibleRowIndex) + if (ptAnchorCell.Y >= previousVisibleRowIndex) { - SelectRowRange(previousVisibleRowIndex, this.ptAnchorCell.Y, true); + SelectRowRange(previousVisibleRowIndex, ptAnchorCell.Y, true); } else { - SelectRowRange(this.ptAnchorCell.Y, previousVisibleRowIndex, true); + SelectRowRange(ptAnchorCell.Y, previousVisibleRowIndex, true); } } SetSelectedRowCore(previousVisibleRowIndex, true); } else { - if (this.MultiSelect) + if (MultiSelect) { //SelectCellUnorderedRange(this.ptCurrentCell.X, previousVisibleRowIndex, this.ptCurrentCell.X, this.ptAnchorCell.Y, true); - int oldEdgeColumnIndex = this.ptCurrentCell.X; - int oldEdgeRowIndex = this.ptCurrentCell.Y; - if (this.ptAnchorCell.Y == -1) + int oldEdgeColumnIndex = ptCurrentCell.X; + int oldEdgeRowIndex = ptCurrentCell.Y; + if (ptAnchorCell.Y == -1) { return true; } - UpdateSelectedCellsBlock(this.ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, - this.ptAnchorCell.Y, ref oldEdgeRowIndex, previousVisibleRowIndex); + UpdateSelectedCellsBlock(ptAnchorCell.X, ref oldEdgeColumnIndex, oldEdgeColumnIndex, + ptAnchorCell.Y, ref oldEdgeRowIndex, previousVisibleRowIndex); } else { ClearSelection(); - SetSelectedCellCore(this.ptCurrentCell.X, previousVisibleRowIndex, true); + SetSelectedCellCore(ptCurrentCell.X, previousVisibleRowIndex, true); } } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, previousVisibleRowIndex, !this.MultiSelect, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, previousVisibleRowIndex, !MultiSelect, false, false); // Debug.Assert(success); } } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedCellCore(firstVisibleColumnIndex, firstVisibleRowIndex, true); @@ -25008,15 +25008,15 @@ protected bool ProcessUpKey(Keys keyData) { return true; } - if (!ScrollIntoView(this.ptCurrentCell.X, previousVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, previousVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(previousVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(previousVisibleRowIndex)) { return true; } - if ((this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) + if ((Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Selected) != 0) { ClearSelection(); SetSelectedRowCore(previousVisibleRowIndex, true); @@ -25024,9 +25024,9 @@ protected bool ProcessUpKey(Keys keyData) else { ClearSelection(); - SetSelectedCellCore(this.ptCurrentCell.X, previousVisibleRowIndex, true); + SetSelectedCellCore(ptCurrentCell.X, previousVisibleRowIndex, true); } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, previousVisibleRowIndex, true, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, previousVisibleRowIndex, true, false, false); // Debug.Assert(success); } } @@ -25036,7 +25036,7 @@ protected bool ProcessUpKey(Keys keyData) case DataGridViewSelectionMode.FullColumnSelect: if ((keyData & Keys.Control) == Keys.Control) { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedColumnCore(firstVisibleColumnIndex, true); @@ -25051,21 +25051,21 @@ protected bool ProcessUpKey(Keys keyData) } else { - if (!ScrollIntoView(this.ptCurrentCell.X, firstVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, firstVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(firstVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(firstVisibleRowIndex)) { return true; } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, firstVisibleRowIndex, true, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, firstVisibleRowIndex, true, false, false); // Debug.Assert(success); } } else { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); SetSelectedColumnCore(firstVisibleColumnIndex, true); @@ -25084,15 +25084,15 @@ protected bool ProcessUpKey(Keys keyData) { return true; } - if (!ScrollIntoView(this.ptCurrentCell.X, previousVisibleRowIndex, true)) + if (!ScrollIntoView(ptCurrentCell.X, previousVisibleRowIndex, true)) { return true; } - if (this.ptCurrentCell.X == -1 || IsRowOutOfBounds(previousVisibleRowIndex)) + if (ptCurrentCell.X == -1 || IsRowOutOfBounds(previousVisibleRowIndex)) { return true; } - success = SetCurrentCellAddressCore(this.ptCurrentCell.X, previousVisibleRowIndex, true, false, false); + success = SetCurrentCellAddressCore(ptCurrentCell.X, previousVisibleRowIndex, true, false, false); // Debug.Assert(success); } } @@ -25101,23 +25101,23 @@ protected bool ProcessUpKey(Keys keyData) } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; } return true; } protected bool ProcessZeroKey(Keys keyData) { - if (this.ptCurrentCell.X != -1 && !this.IsCurrentCellInEditMode && ColumnEditable(this.ptCurrentCell.X)) + if (ptCurrentCell.X != -1 && !IsCurrentCellInEditMode && ColumnEditable(ptCurrentCell.X)) { - DataGridViewCell dataGridViewCell = this.CurrentCellInternal; + DataGridViewCell dataGridViewCell = CurrentCellInternal; Debug.Assert(dataGridViewCell != null); - if (!IsSharedCellReadOnly(dataGridViewCell, this.ptCurrentCell.Y) && - (this.EditMode == DataGridViewEditMode.EditOnKeystroke || this.EditMode == DataGridViewEditMode.EditOnKeystrokeOrF2) && + if (!IsSharedCellReadOnly(dataGridViewCell, ptCurrentCell.Y) && + (EditMode == DataGridViewEditMode.EditOnKeystroke || EditMode == DataGridViewEditMode.EditOnKeystrokeOrF2) && dataGridViewCell.EditType != null) { - bool success = ScrollIntoView(this.ptCurrentCell.X, this.ptCurrentCell.Y, false); + bool success = ScrollIntoView(ptCurrentCell.X, ptCurrentCell.Y, false); Debug.Assert(success); if (!BeginEditInternal(false /*selectAll*/)) { @@ -25127,29 +25127,29 @@ protected bool ProcessZeroKey(Keys keyData) } if ((keyData & (Keys.Alt | Keys.Shift | Keys.Control)) == Keys.Control && - this.IsCurrentCellInEditMode) + IsCurrentCellInEditMode) { - DataGridViewCell dataGridViewCurrentCell = this.CurrentCellInternal; + DataGridViewCell dataGridViewCurrentCell = CurrentCellInternal; Debug.Assert(dataGridViewCurrentCell != null); - object nullValue = dataGridViewCurrentCell.GetInheritedStyle(null, this.ptCurrentCell.Y, false).NullValue; + object nullValue = dataGridViewCurrentCell.GetInheritedStyle(null, ptCurrentCell.Y, false).NullValue; if (nullValue == null || (dataGridViewCurrentCell.FormattedValueType != null && dataGridViewCurrentCell.FormattedValueType.IsAssignableFrom(nullValue.GetType()))) { - if (this.editingControl != null) + if (editingControl != null) { - ((IDataGridViewEditingControl)this.editingControl).EditingControlFormattedValue = nullValue; - ((IDataGridViewEditingControl)this.editingControl).EditingControlValueChanged = true; - ((IDataGridViewEditingControl)this.editingControl).PrepareEditingControlForEdit(true /*selectAll*/); + ((IDataGridViewEditingControl)editingControl).EditingControlFormattedValue = nullValue; + ((IDataGridViewEditingControl)editingControl).EditingControlValueChanged = true; + ((IDataGridViewEditingControl)editingControl).PrepareEditingControlForEdit(true /*selectAll*/); } else { - Debug.Assert(this.dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode]); + Debug.Assert(dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode]); IDataGridViewEditingCell dataGridViewEditingCell = dataGridViewCurrentCell as IDataGridViewEditingCell; Debug.Assert(dataGridViewEditingCell != null); dataGridViewEditingCell.EditingCellFormattedValue = nullValue; dataGridViewEditingCell.EditingCellValueChanged = true; dataGridViewEditingCell.PrepareEditingCellForEdit(true /*selectAll*/); - InvalidateCellPrivate(this.ptCurrentCell.X, this.ptCurrentCell.Y); + InvalidateCellPrivate(ptCurrentCell.X, ptCurrentCell.Y); } NotifyCurrentCellDirty(true); return true; @@ -25161,31 +25161,31 @@ protected bool ProcessZeroKey(Keys keyData) private void PushAllowUserToAddRows() { - if (this.AllowUserToAddRowsInternal) + if (AllowUserToAddRowsInternal) { - if (this.Columns.Count > 0 && this.newRowIndex == -1) + if (Columns.Count > 0 && newRowIndex == -1) { AddNewRow(false); } } - else if (this.newRowIndex != -1) + else if (newRowIndex != -1) { // Delete the 'new' row - Debug.Assert(this.newRowIndex == this.Rows.Count - 1); - this.Rows.RemoveAtInternal(this.newRowIndex, false /*force*/); + Debug.Assert(newRowIndex == Rows.Count - 1); + Rows.RemoveAtInternal(newRowIndex, false /*force*/); } } private bool PushFormattedValue(ref DataGridViewCell dataGridViewCurrentCell, object formattedValue, out Exception exception) { - Debug.Assert(this.IsCurrentCellInEditMode); + Debug.Assert(IsCurrentCellInEditMode); exception = null; - DataGridViewCellStyle cellStyle = this.InheritedEditingCellStyle; + DataGridViewCellStyle cellStyle = InheritedEditingCellStyle; - DataGridViewCellParsingEventArgs dgvcpe = OnCellParsing(this.ptCurrentCell.Y, - this.ptCurrentCell.X, + DataGridViewCellParsingEventArgs dgvcpe = OnCellParsing(ptCurrentCell.Y, + ptCurrentCell.X, formattedValue, dataGridViewCurrentCell.ValueType, cellStyle); @@ -25196,9 +25196,9 @@ private bool PushFormattedValue(ref DataGridViewCell dataGridViewCurrentCell, ob { if (dataGridViewCurrentCell.RowIndex == -1) { - dataGridViewCurrentCell = this.Rows[this.ptCurrentCell.Y].Cells[this.ptCurrentCell.X]; // unsharing the row before pushing the new value + dataGridViewCurrentCell = Rows[ptCurrentCell.Y].Cells[ptCurrentCell.X]; // unsharing the row before pushing the new value } - return dataGridViewCurrentCell.SetValueInternal(this.ptCurrentCell.Y, dgvcpe.Value); + return dataGridViewCurrentCell.SetValueInternal(ptCurrentCell.Y, dgvcpe.Value); } object val; @@ -25217,25 +25217,25 @@ private bool PushFormattedValue(ref DataGridViewCell dataGridViewCurrentCell, ob } if (dataGridViewCurrentCell.RowIndex == -1) { - dataGridViewCurrentCell = this.Rows[this.ptCurrentCell.Y].Cells[this.ptCurrentCell.X]; // unsharing the row before pushing the new value + dataGridViewCurrentCell = Rows[ptCurrentCell.Y].Cells[ptCurrentCell.X]; // unsharing the row before pushing the new value } - return dataGridViewCurrentCell.SetValueInternal(this.ptCurrentCell.Y, val); + return dataGridViewCurrentCell.SetValueInternal(ptCurrentCell.Y, val); } private void RecordCellMouseClick(DataGridViewCellMouseEventArgs dgvcme) { Debug.Assert(dgvcme.Clicks == 1); - this.lastMouseClickInfo.button = dgvcme.Button; - this.lastMouseClickInfo.timeStamp = DateTime.Now.Ticks; - this.lastMouseClickInfo.x = dgvcme.X; - this.lastMouseClickInfo.y = dgvcme.Y; - this.lastMouseClickInfo.col = dgvcme.ColumnIndex; - this.lastMouseClickInfo.row = dgvcme.RowIndex; + lastMouseClickInfo.button = dgvcme.Button; + lastMouseClickInfo.timeStamp = DateTime.Now.Ticks; + lastMouseClickInfo.x = dgvcme.X; + lastMouseClickInfo.y = dgvcme.Y; + lastMouseClickInfo.col = dgvcme.ColumnIndex; + lastMouseClickInfo.row = dgvcme.RowIndex; } private void RefreshColumnsAndRows() { - this.Rows.ClearInternal(false /*recreateNewRow*/); + Rows.ClearInternal(false /*recreateNewRow*/); RefreshColumns(); RefreshRows(true /*scrollIntoView*/); } @@ -25247,24 +25247,24 @@ private void RefreshColumns() // 2. add new columns based on data source // - bool startUpdateInternal = this.Visible; + bool startUpdateInternal = Visible; if (startUpdateInternal) { BeginUpdateInternal(); } - this.dataGridViewOper[DATAGRIDVIEWOPER_inRefreshColumns] = true; + dataGridViewOper[DATAGRIDVIEWOPER_inRefreshColumns] = true; try { - DataGridViewColumnCollection dataGridViewCols = this.Columns; + DataGridViewColumnCollection dataGridViewCols = Columns; DataGridViewColumn[] boundColumns = null; - if (this.dataConnection != null) + if (dataConnection != null) { - boundColumns = this.dataConnection.GetCollectionOfBoundDataGridViewColumns(); + boundColumns = dataConnection.GetCollectionOfBoundDataGridViewColumns(); } - if (this.AutoGenerateColumns) + if (AutoGenerateColumns) { AutoGenerateDataBoundColumns(boundColumns); } @@ -25277,21 +25277,21 @@ private void RefreshColumns() dataGridViewCols[j].BoundColumnIndex = -1; dataGridViewCols[j].BoundColumnConverter = null; // set up the columns which have DataPropertyName set to something - if (this.DataSource != null && dataGridViewCols[j].DataPropertyName.Length != 0) + if (DataSource != null && dataGridViewCols[j].DataPropertyName.Length != 0) { MapDataGridViewColumnToDataBoundField(dataGridViewCols[j]); } } } - if (this.DataSource != null) + if (DataSource != null) { - this.dataConnection.ApplySortingInformationFromBackEnd(); + dataConnection.ApplySortingInformationFromBackEnd(); } } finally { - this.dataGridViewOper[DATAGRIDVIEWOPER_inRefreshColumns] = false; + dataGridViewOper[DATAGRIDVIEWOPER_inRefreshColumns] = false; if (startUpdateInternal) { @@ -25304,36 +25304,36 @@ private void RefreshColumns() // Returns true for success, and false if an OnDataError event was raised and cancelled the operation (e.Cancel = true). public bool RefreshEdit() { - if (this.ptCurrentCell.X != -1 && this.IsCurrentCellInEditMode) + if (ptCurrentCell.X != -1 && IsCurrentCellInEditMode) { - Debug.Assert(this.ptCurrentCell.Y != -1); - DataGridViewCell dataGridViewCurrentCell = this.CurrentCellInternal; - DataGridViewCellStyle dataGridViewCellStyle = dataGridViewCurrentCell.GetInheritedStyle(null, this.ptCurrentCell.Y, true); - if (this.editingControl != null) + Debug.Assert(ptCurrentCell.Y != -1); + DataGridViewCell dataGridViewCurrentCell = CurrentCellInternal; + DataGridViewCellStyle dataGridViewCellStyle = dataGridViewCurrentCell.GetInheritedStyle(null, ptCurrentCell.Y, true); + if (editingControl != null) { if (InitializeEditingControlValue(ref dataGridViewCellStyle, dataGridViewCurrentCell)) { - if (((IDataGridViewEditingControl)this.editingControl).RepositionEditingControlOnValueChange) + if (((IDataGridViewEditingControl)editingControl).RepositionEditingControlOnValueChange) { PositionEditingControl(true /*setLocation*/, true /*setSize*/, false /*setFocus*/); } - ((IDataGridViewEditingControl)this.editingControl).PrepareEditingControlForEdit(true /*selectAll*/); - ((IDataGridViewEditingControl)this.editingControl).EditingControlValueChanged = false; - this.IsCurrentCellDirtyInternal = false; + ((IDataGridViewEditingControl)editingControl).PrepareEditingControlForEdit(true /*selectAll*/); + ((IDataGridViewEditingControl)editingControl).EditingControlValueChanged = false; + IsCurrentCellDirtyInternal = false; return true; } return false; } else { - Debug.Assert(this.dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode]); + Debug.Assert(dataGridViewState1[DATAGRIDVIEWSTATE1_currentCellInEditMode]); if (InitializeEditingCellValue(ref dataGridViewCellStyle, ref dataGridViewCurrentCell)) { IDataGridViewEditingCell dataGridViewEditingCell = dataGridViewCurrentCell as IDataGridViewEditingCell; Debug.Assert(dataGridViewEditingCell != null); dataGridViewEditingCell.PrepareEditingCellForEdit(true /*selectAll*/); dataGridViewEditingCell.EditingCellValueChanged = false; - this.IsCurrentCellDirtyInternal = false; + IsCurrentCellDirtyInternal = false; return true; } return false; @@ -25344,7 +25344,7 @@ public bool RefreshEdit() private void RefreshRows(bool scrollIntoView) { - bool startBeginUpdate = this.Visible; + bool startBeginUpdate = Visible; if (startBeginUpdate) { BeginUpdateInternal(); @@ -25352,53 +25352,53 @@ private void RefreshRows(bool scrollIntoView) try { - if (this.dataGridViewOper[DATAGRIDVIEWOPER_inCurrentCellChange]) + if (dataGridViewOper[DATAGRIDVIEWOPER_inCurrentCellChange]) { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_rowsCollectionClearedInSetCell] = true; + dataGridViewState2[DATAGRIDVIEWSTATE2_rowsCollectionClearedInSetCell] = true; } // Clear existing rows - this.Rows.ClearInternal(true /*recreateNewRow*/); + Rows.ClearInternal(true /*recreateNewRow*/); // Add a row for each object in the data source - if (this.dataConnection != null && this.Columns.Count > 0) + if (dataConnection != null && Columns.Count > 0) { - IList list = this.dataConnection.List; + IList list = dataConnection.List; if (list != null && list.Count > 0) { int rowsCount = list.Count; - bool oldDoNotChangePositionInTheCurrencyManager = this.dataConnection.DoNotChangePositionInTheCurrencyManager; + bool oldDoNotChangePositionInTheCurrencyManager = dataConnection.DoNotChangePositionInTheCurrencyManager; // scroll into view when we have a non-empty list // and the layout is not dirty and we are not in a sort operation. - bool matchPositionInCurrencyManagerAfterRecreatingRows = !this.layout.dirty && !this.InSortOperation; + bool matchPositionInCurrencyManagerAfterRecreatingRows = !layout.dirty && !InSortOperation; if (matchPositionInCurrencyManagerAfterRecreatingRows) { // Prevent the data connection from changing position in the currency manager. // But only if the data grid view will set the position in the currency manager after recreating the rows collection. - this.dataConnection.DoNotChangePositionInTheCurrencyManager = true; + dataConnection.DoNotChangePositionInTheCurrencyManager = true; } try { - this.Rows.AddInternal(this.RowTemplateClone); + Rows.AddInternal(RowTemplateClone); Debug.Assert(list.Count == rowsCount); if (rowsCount > 1) { - this.Rows.AddCopiesInternal(0, rowsCount - 1); + Rows.AddCopiesInternal(0, rowsCount - 1); } // Add selected Columns back in selectedBandIndexes foreach (DataGridViewColumn column in Columns) { - if (column.Selected && (!this.selectedBandIndexes.Contains(column.Index))) + if (column.Selected && (!selectedBandIndexes.Contains(column.Index))) { - this.selectedBandIndexes.Add(column.Index); + selectedBandIndexes.Add(column.Index); } } } finally { - this.dataConnection.DoNotChangePositionInTheCurrencyManager = oldDoNotChangePositionInTheCurrencyManager; + dataConnection.DoNotChangePositionInTheCurrencyManager = oldDoNotChangePositionInTheCurrencyManager; } if (matchPositionInCurrencyManagerAfterRecreatingRows) @@ -25421,15 +25421,15 @@ private void RefreshRows(bool scrollIntoView) private void RealeaseMouse() { Cursor.ClipInternal = Rectangle.Empty; - this.CaptureInternal = false; + CaptureInternal = false; } private void RemoveIndividualReadOnlyCellsInColumn(int columnIndex) { int cellIndex = 0; - while (cellIndex < this.individualReadOnlyCells.Count) + while (cellIndex < individualReadOnlyCells.Count) { - DataGridViewCell dataGridViewCell = this.individualReadOnlyCells[cellIndex]; + DataGridViewCell dataGridViewCell = individualReadOnlyCells[cellIndex]; if (dataGridViewCell.ColumnIndex == columnIndex) { SetReadOnlyCellCore(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex, false); @@ -25444,9 +25444,9 @@ private void RemoveIndividualReadOnlyCellsInColumn(int columnIndex) private void RemoveIndividualReadOnlyCellsInRow(int rowIndex) { int cellIndex = 0; - while (cellIndex < this.individualReadOnlyCells.Count) + while (cellIndex < individualReadOnlyCells.Count) { - DataGridViewCell dataGridViewCell = this.individualReadOnlyCells[cellIndex]; + DataGridViewCell dataGridViewCell = individualReadOnlyCells[cellIndex]; if (dataGridViewCell.RowIndex == rowIndex) { SetReadOnlyCellCore(dataGridViewCell.ColumnIndex, rowIndex, false); @@ -25460,18 +25460,18 @@ private void RemoveIndividualReadOnlyCellsInRow(int rowIndex) private void RemoveIndividuallySelectedCells() { - Debug.Assert(this.noSelectionChangeCount > 0); + Debug.Assert(noSelectionChangeCount > 0); bool switchedToBulkPaint = false; - if (this.individualSelectedCells.Count > DATAGRIDVIEW_bulkPaintThreshold) + if (individualSelectedCells.Count > DATAGRIDVIEW_bulkPaintThreshold) { - this.inBulkPaintCount++; + inBulkPaintCount++; switchedToBulkPaint = true; } try { - while (this.individualSelectedCells.Count > 0) + while (individualSelectedCells.Count > 0) { - DataGridViewCell dataGridViewCell = this.individualSelectedCells.HeadCell; + DataGridViewCell dataGridViewCell = individualSelectedCells.HeadCell; SetSelectedCellCore(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex, false); } } @@ -25486,27 +25486,27 @@ private void RemoveIndividuallySelectedCells() private void RemoveIndividuallySelectedCells(int columnIndexException, int rowIndexException) { - Debug.Assert(this.noSelectionChangeCount > 0); + Debug.Assert(noSelectionChangeCount > 0); bool switchedToBulkPaint = false; - if (this.individualSelectedCells.Count > DATAGRIDVIEW_bulkPaintThreshold) + if (individualSelectedCells.Count > DATAGRIDVIEW_bulkPaintThreshold) { - this.inBulkPaintCount++; + inBulkPaintCount++; switchedToBulkPaint = true; } try { - while (this.individualSelectedCells.Count > 0) + while (individualSelectedCells.Count > 0) { - DataGridViewCell dataGridViewCell = this.individualSelectedCells.HeadCell; + DataGridViewCell dataGridViewCell = individualSelectedCells.HeadCell; if (dataGridViewCell.ColumnIndex != columnIndexException || dataGridViewCell.RowIndex != rowIndexException) { SetSelectedCellCore(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex, false); } else { - while (this.individualSelectedCells.Count > 1) + while (individualSelectedCells.Count > 1) { - dataGridViewCell = this.individualSelectedCells[1]; + dataGridViewCell = individualSelectedCells[1]; Debug.Assert(dataGridViewCell.ColumnIndex != columnIndexException || dataGridViewCell.RowIndex != rowIndexException); SetSelectedCellCore(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex, false); } @@ -25525,15 +25525,15 @@ private void RemoveIndividuallySelectedCells(int columnIndexException, int rowIn private void RemoveIndividuallySelectedCellsInColumn(int columnIndex) { - Debug.Assert(this.noSelectionChangeCount > 0); + Debug.Assert(noSelectionChangeCount > 0); int cellIndex = 0; int cellCountInColumn = 0; bool switchToBulkOperation = false; DataGridViewCell dataGridViewCell; - while (cellIndex < this.individualSelectedCells.Count) + while (cellIndex < individualSelectedCells.Count) { - dataGridViewCell = this.individualSelectedCells[cellIndex]; + dataGridViewCell = individualSelectedCells[cellIndex]; if (dataGridViewCell.ColumnIndex == columnIndex) { SetSelectedCellCore(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex, false); @@ -25552,12 +25552,12 @@ private void RemoveIndividuallySelectedCellsInColumn(int columnIndex) if (switchToBulkOperation) { - this.inBulkPaintCount++; + inBulkPaintCount++; try { - while (cellIndex < this.individualSelectedCells.Count) + while (cellIndex < individualSelectedCells.Count) { - dataGridViewCell = this.individualSelectedCells[cellIndex]; + dataGridViewCell = individualSelectedCells[cellIndex]; if (dataGridViewCell.ColumnIndex == columnIndex) { SetSelectedCellCore(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex, false); @@ -25577,13 +25577,13 @@ private void RemoveIndividuallySelectedCellsInColumn(int columnIndex) private void RemoveIndividuallySelectedCellsInRow(int rowIndex) { - Debug.Assert(this.noSelectionChangeCount > 0); + Debug.Assert(noSelectionChangeCount > 0); // Since there are typically not many columns in a row, we don't try to switch into a bulk operation // as we do in RemoveIndividuallySelectedCellsInColumn. int cellIndex = 0; - while (cellIndex < this.individualSelectedCells.Count) + while (cellIndex < individualSelectedCells.Count) { - DataGridViewCell dataGridViewCell = this.individualSelectedCells[cellIndex]; + DataGridViewCell dataGridViewCell = individualSelectedCells[cellIndex]; if (dataGridViewCell.RowIndex == rowIndex) { SetSelectedCellCore(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex, false); @@ -25598,13 +25598,13 @@ private void RemoveIndividuallySelectedCellsInRow(int rowIndex) // required by the Designer private void ResetBackgroundColor() { - this.BackgroundColor = DefaultBackgroundBrush.Color; + BackgroundColor = DefaultBackgroundBrush.Color; } // required by the Designer private void ResetGridColor() { - this.GridColor = DefaultGridColor; + GridColor = DefaultGridColor; } [EditorBrowsable(EditorBrowsableState.Never)] @@ -25618,44 +25618,44 @@ public override void ResetText() /// private void ResetTrackingState() { - if (this.IsKeyboardOperationActive()) + if (IsKeyboardOperationActive()) { return; } - if (this.horizScrollTimer != null && this.horizScrollTimer.Enabled) + if (horizScrollTimer != null && horizScrollTimer.Enabled) { - this.horizScrollTimer.Enabled = false; + horizScrollTimer.Enabled = false; } - if (this.vertScrollTimer != null && this.vertScrollTimer.Enabled) + if (vertScrollTimer != null && vertScrollTimer.Enabled) { - this.vertScrollTimer.Enabled = false; + vertScrollTimer.Enabled = false; } - this.dataGridViewOper[DATAGRIDVIEWOPER_mouseOperationMask] = false; - this.dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] = false; - this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] = false; - this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect] = false; - this.trackColumn = -1; - this.trackRow = -1; - this.ptMouseDownCell.X = -2; - this.ptMouseDownCell.Y = -2; + dataGridViewOper[DATAGRIDVIEWOPER_mouseOperationMask] = false; + dataGridViewOper[DATAGRIDVIEWOPER_trackColSelect] = false; + dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] = false; + dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect] = false; + trackColumn = -1; + trackRow = -1; + ptMouseDownCell.X = -2; + ptMouseDownCell.Y = -2; - if (this.currentRowSplitBar != -1) + if (currentRowSplitBar != -1) { - Invalidate(CalcRowResizeFeedbackRect(this.currentRowSplitBar), true); - this.lastRowSplitBar = this.currentRowSplitBar = -1; + Invalidate(CalcRowResizeFeedbackRect(currentRowSplitBar), true); + lastRowSplitBar = currentRowSplitBar = -1; } - if (this.currentColSplitBar != -1) + if (currentColSplitBar != -1) { - Invalidate(CalcColResizeFeedbackRect(this.currentColSplitBar), true); - this.lastColSplitBar = this.currentColSplitBar = -1; + Invalidate(CalcColResizeFeedbackRect(currentColSplitBar), true); + lastColSplitBar = currentColSplitBar = -1; } - if (this.lastHeaderShadow != -1) + if (lastHeaderShadow != -1) { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_showColumnRelocationInsertion] = false; - this.trackColumnEdge = -1; - this.lastHeaderShadow = -1; - Invalidate(Rectangle.Union(this.layout.TopLeftHeader, this.layout.ColumnHeaders)); + dataGridViewState2[DATAGRIDVIEWSTATE2_showColumnRelocationInsertion] = false; + trackColumnEdge = -1; + lastHeaderShadow = -1; + Invalidate(Rectangle.Union(layout.TopLeftHeader, layout.ColumnHeaders)); } RealeaseMouse(); } @@ -25663,29 +25663,29 @@ private void ResetTrackingState() // Re-initializes all state that is related to tracking keyboard operations private void ResetKeyboardTrackingState() { - if (this.IsMouseOperationActive()) + if (IsMouseOperationActive()) { return; } - this.dataGridViewOper[DATAGRIDVIEWOPER_keyboardOperationMask] = false; - this.trackColumn = -1; - if (this.currentColSplitBar != -1) + dataGridViewOper[DATAGRIDVIEWOPER_keyboardOperationMask] = false; + trackColumn = -1; + if (currentColSplitBar != -1) { - Invalidate(CalcColResizeFeedbackRect(this.currentColSplitBar), true); - this.lastColSplitBar = this.currentColSplitBar = -1; + Invalidate(CalcColResizeFeedbackRect(currentColSplitBar), true); + lastColSplitBar = currentColSplitBar = -1; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool IsMouseOperationActive() { - return (this.dataGridViewOper.Data & DATAGRIDVIEWOPER_mouseOperationMask) != 0; + return (dataGridViewOper.Data & DATAGRIDVIEWOPER_mouseOperationMask) != 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool IsKeyboardOperationActive() { - return (this.dataGridViewOper.Data & DATAGRIDVIEWOPER_keyboardOperationMask) != 0; + return (dataGridViewOper.Data & DATAGRIDVIEWOPER_keyboardOperationMask) != 0; } /// @@ -25704,16 +25704,16 @@ internal void ResetUIState(bool useRowShortcut, bool computeVisibleRows) private void RestoreRowsCachedThickness() { // Switch to batch operation - this.inBulkPaintCount++; - this.inBulkLayoutCount++; + inBulkPaintCount++; + inBulkLayoutCount++; try { // Only height of visible rows are restored since invisible rows are not autosized. - for (int rowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + for (int rowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); rowIndex != -1; - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) + rowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) { - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); int height, minimumHeight; dataGridViewRow.GetHeightInfo(rowIndex, out height, out minimumHeight); if (height != dataGridViewRow.CachedThickness && @@ -25733,23 +25733,23 @@ private void RestoreRowsCachedThickness() // we need to access the GetRowState, otherwise we would unshare the row private bool RowIsResizable(int rowIndex) { - DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); + DataGridViewElementStates rowState = Rows.GetRowState(rowIndex); if ((rowState & DataGridViewElementStates.ResizableSet) == DataGridViewElementStates.ResizableSet) { return (rowState & DataGridViewElementStates.Resizable) == DataGridViewElementStates.Resizable; } else { - return this.AllowUserToResizeRows; + return AllowUserToResizeRows; } } private bool RowNeedsDisplayedState(int rowIndex, int lastDisplayedFrozenRowIndex, int lastDisplayedScrollingRowIndex) { Debug.Assert(rowIndex >= 0); - Debug.Assert(rowIndex < this.Rows.Count); + Debug.Assert(rowIndex < Rows.Count); - DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); + DataGridViewElementStates rowState = Rows.GetRowState(rowIndex); if ((rowState & DataGridViewElementStates.Visible) == 0) { @@ -25760,8 +25760,8 @@ private bool RowNeedsDisplayedState(int rowIndex, int lastDisplayedFrozenRowInde { return rowIndex <= lastDisplayedFrozenRowIndex; } - else if (this.displayedBandsInfo.FirstDisplayedScrollingRow != -1 && - rowIndex >= this.displayedBandsInfo.FirstDisplayedScrollingRow && + else if (displayedBandsInfo.FirstDisplayedScrollingRow != -1 && + rowIndex >= displayedBandsInfo.FirstDisplayedScrollingRow && rowIndex <= lastDisplayedScrollingRowIndex) { return true; @@ -25771,7 +25771,7 @@ private bool RowNeedsDisplayedState(int rowIndex, int lastDisplayedFrozenRowInde private void ScrollBar_MouseEnter(object sender, System.EventArgs e) { - if (this.dataGridViewState2[DATAGRIDVIEWSTATE2_mouseEnterExpected]) + if (dataGridViewState2[DATAGRIDVIEWSTATE2_mouseEnterExpected]) { OnMouseEnter(EventArgs.Empty); } @@ -25782,7 +25782,7 @@ private void ScrollBar_MouseLeave(object sender, System.EventArgs e) { UpdateMouseEnteredCell(null /*HitTestInfo*/, null /*MouseEventArgs*/); Point ptMouse = PointToClient(Control.MousePosition); - if (!this.ClientRectangle.Contains(ptMouse)) + if (!ClientRectangle.Contains(ptMouse)) { OnMouseLeave(EventArgs.Empty); } @@ -25790,71 +25790,71 @@ private void ScrollBar_MouseLeave(object sender, System.EventArgs e) private bool ScrollColumnIntoView(int columnIndex, int rowIndex, bool committed, bool forCurrentCellChange) { - Debug.Assert(columnIndex >= 0 && columnIndex < this.Columns.Count); + Debug.Assert(columnIndex >= 0 && columnIndex < Columns.Count); - if (this.displayedBandsInfo.FirstDisplayedScrollingCol != -1 && - !this.Columns[columnIndex].Frozen && - (columnIndex != this.displayedBandsInfo.FirstDisplayedScrollingCol || this.negOffset > 0)) + if (displayedBandsInfo.FirstDisplayedScrollingCol != -1 && + !Columns[columnIndex].Frozen && + (columnIndex != displayedBandsInfo.FirstDisplayedScrollingCol || negOffset > 0)) { int columnsToScroll; - if (this.Columns.DisplayInOrder(columnIndex, this.displayedBandsInfo.FirstDisplayedScrollingCol)) + if (Columns.DisplayInOrder(columnIndex, displayedBandsInfo.FirstDisplayedScrollingCol)) { - if (!committed && this.ptCurrentCell.X >= 0 && + if (!committed && ptCurrentCell.X >= 0 && !CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, - forCurrentCellChange && (this.ptCurrentCell.X != columnIndex || this.ptCurrentCell.Y != rowIndex), - this.ptCurrentCell.Y != rowIndex /*forCurrentRowChange*/)) + forCurrentCellChange && (ptCurrentCell.X != columnIndex || ptCurrentCell.Y != rowIndex), + ptCurrentCell.Y != rowIndex /*forCurrentRowChange*/)) { return false; } - columnsToScroll = this.Columns.GetColumnCount(DataGridViewElementStates.Visible, columnIndex, this.displayedBandsInfo.FirstDisplayedScrollingCol); - if (this.negOffset > 0) + columnsToScroll = Columns.GetColumnCount(DataGridViewElementStates.Visible, columnIndex, displayedBandsInfo.FirstDisplayedScrollingCol); + if (negOffset > 0) { columnsToScroll++; } ScrollColumns(-columnsToScroll); } - else if (columnIndex == this.displayedBandsInfo.FirstDisplayedScrollingCol && this.negOffset > 0) + else if (columnIndex == displayedBandsInfo.FirstDisplayedScrollingCol && negOffset > 0) { - if (!committed && this.ptCurrentCell.X >= 0 && + if (!committed && ptCurrentCell.X >= 0 && !CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, - forCurrentCellChange && (this.ptCurrentCell.X != columnIndex || this.ptCurrentCell.Y != rowIndex), - this.ptCurrentCell.Y != rowIndex /*forCurrentRowChange*/)) + forCurrentCellChange && (ptCurrentCell.X != columnIndex || ptCurrentCell.Y != rowIndex), + ptCurrentCell.Y != rowIndex /*forCurrentRowChange*/)) { return false; } ScrollColumns(-1); } - else if (this.displayedBandsInfo.LastTotallyDisplayedScrollingCol == -1 || - (this.displayedBandsInfo.LastTotallyDisplayedScrollingCol != columnIndex && - this.Columns.DisplayInOrder(this.displayedBandsInfo.LastTotallyDisplayedScrollingCol, columnIndex))) + else if (displayedBandsInfo.LastTotallyDisplayedScrollingCol == -1 || + (displayedBandsInfo.LastTotallyDisplayedScrollingCol != columnIndex && + Columns.DisplayInOrder(displayedBandsInfo.LastTotallyDisplayedScrollingCol, columnIndex))) { - if (!committed && this.ptCurrentCell.X >= 0 && + if (!committed && ptCurrentCell.X >= 0 && !CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, - forCurrentCellChange && (this.ptCurrentCell.X != columnIndex || this.ptCurrentCell.Y != rowIndex), - this.ptCurrentCell.Y != rowIndex /*forCurrentRowChange*/)) + forCurrentCellChange && (ptCurrentCell.X != columnIndex || ptCurrentCell.Y != rowIndex), + ptCurrentCell.Y != rowIndex /*forCurrentRowChange*/)) { return false; } columnsToScroll = 0; - int firstDisplayedScrollingColumn = this.displayedBandsInfo.FirstDisplayedScrollingCol; + int firstDisplayedScrollingColumn = displayedBandsInfo.FirstDisplayedScrollingCol; int xColumnRightEdge; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - xColumnRightEdge = GetColumnXFromIndex(columnIndex) - this.Columns[columnIndex].Width; - while (xColumnRightEdge < this.layout.Data.X && this.Columns.DisplayInOrder(firstDisplayedScrollingColumn, columnIndex)) + xColumnRightEdge = GetColumnXFromIndex(columnIndex) - Columns[columnIndex].Width; + while (xColumnRightEdge < layout.Data.X && Columns.DisplayInOrder(firstDisplayedScrollingColumn, columnIndex)) { - xColumnRightEdge += this.Columns[firstDisplayedScrollingColumn].Width; - if (firstDisplayedScrollingColumn == this.displayedBandsInfo.FirstDisplayedScrollingCol) + xColumnRightEdge += Columns[firstDisplayedScrollingColumn].Width; + if (firstDisplayedScrollingColumn == displayedBandsInfo.FirstDisplayedScrollingCol) { - xColumnRightEdge -= this.negOffset; + xColumnRightEdge -= negOffset; } columnsToScroll++; - if (xColumnRightEdge < this.layout.Data.X) + if (xColumnRightEdge < layout.Data.X) { - firstDisplayedScrollingColumn = this.Columns.GetNextColumn(this.Columns[firstDisplayedScrollingColumn], + firstDisplayedScrollingColumn = Columns.GetNextColumn(Columns[firstDisplayedScrollingColumn], DataGridViewElementStates.Visible, DataGridViewElementStates.None).Index; } @@ -25862,18 +25862,18 @@ private bool ScrollColumnIntoView(int columnIndex, int rowIndex, bool committed, } else { - xColumnRightEdge = GetColumnXFromIndex(columnIndex) + this.Columns[columnIndex].Width; - while (xColumnRightEdge > this.layout.Data.Right && this.Columns.DisplayInOrder(firstDisplayedScrollingColumn, columnIndex)) + xColumnRightEdge = GetColumnXFromIndex(columnIndex) + Columns[columnIndex].Width; + while (xColumnRightEdge > layout.Data.Right && Columns.DisplayInOrder(firstDisplayedScrollingColumn, columnIndex)) { - xColumnRightEdge -= this.Columns[firstDisplayedScrollingColumn].Width; - if (firstDisplayedScrollingColumn == this.displayedBandsInfo.FirstDisplayedScrollingCol) + xColumnRightEdge -= Columns[firstDisplayedScrollingColumn].Width; + if (firstDisplayedScrollingColumn == displayedBandsInfo.FirstDisplayedScrollingCol) { - xColumnRightEdge += this.negOffset; + xColumnRightEdge += negOffset; } columnsToScroll++; - if (xColumnRightEdge > this.layout.Data.Right) + if (xColumnRightEdge > layout.Data.Right) { - firstDisplayedScrollingColumn = this.Columns.GetNextColumn(this.Columns[firstDisplayedScrollingColumn], + firstDisplayedScrollingColumn = Columns.GetNextColumn(Columns[firstDisplayedScrollingColumn], DataGridViewElementStates.Visible, DataGridViewElementStates.None).Index; } @@ -25897,12 +25897,12 @@ private void ScrollColumns(int columns) if (columns > 0) { //scrollEventType = columns > 1 ? ScrollEventType.LargeIncrement : ScrollEventType.SmallIncrement; - if (this.displayedBandsInfo.LastTotallyDisplayedScrollingCol >= 0) + if (displayedBandsInfo.LastTotallyDisplayedScrollingCol >= 0) { - dataGridViewColumnTmp = this.Columns[this.displayedBandsInfo.LastTotallyDisplayedScrollingCol]; + dataGridViewColumnTmp = Columns[displayedBandsInfo.LastTotallyDisplayedScrollingCol]; while (colCount < columns && dataGridViewColumnTmp != null) { - dataGridViewColumnTmp = this.Columns.GetNextColumn(dataGridViewColumnTmp, + dataGridViewColumnTmp = Columns.GetNextColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.None); colCount++; @@ -25914,12 +25914,12 @@ private void ScrollColumns(int columns) return; } } - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingCol >= 0); - dataGridViewColumnTmp = this.Columns[this.displayedBandsInfo.FirstDisplayedScrollingCol]; + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingCol >= 0); + dataGridViewColumnTmp = Columns[displayedBandsInfo.FirstDisplayedScrollingCol]; colCount = 0; while (colCount < columns && dataGridViewColumnTmp != null) { - dataGridViewColumnTmp = this.Columns.GetNextColumn(dataGridViewColumnTmp, + dataGridViewColumnTmp = Columns.GetNextColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.None); colCount++; @@ -25930,15 +25930,15 @@ private void ScrollColumns(int columns) if (columns < 0) { //scrollEventType = columns < -1 ? ScrollEventType.LargeDecrement : ScrollEventType.SmallDecrement; - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingCol >= 0); - dataGridViewColumnTmp = this.Columns[this.displayedBandsInfo.FirstDisplayedScrollingCol]; - if (this.negOffset > 0) + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingCol >= 0); + dataGridViewColumnTmp = Columns[displayedBandsInfo.FirstDisplayedScrollingCol]; + if (negOffset > 0) { colCount++; } while (colCount < -columns && dataGridViewColumnTmp != null) { - dataGridViewColumnTmp = this.Columns.GetPreviousColumn(dataGridViewColumnTmp, + dataGridViewColumnTmp = Columns.GetPreviousColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); colCount++; @@ -25946,7 +25946,7 @@ private void ScrollColumns(int columns) newFirstVisibleScrollingCol = dataGridViewColumnTmp; if (newFirstVisibleScrollingCol == null) { - if (this.negOffset == 0) + if (negOffset == 0) { // no more column to display on the left of the first seen column FlushDisplayedChanged(); @@ -25954,38 +25954,38 @@ private void ScrollColumns(int columns) } else { - newFirstVisibleScrollingCol = this.Columns[this.displayedBandsInfo.FirstDisplayedScrollingCol]; + newFirstVisibleScrollingCol = Columns[displayedBandsInfo.FirstDisplayedScrollingCol]; } } } int newColOffset = 0; - for (DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible, + for (DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); dataGridViewColumn != newFirstVisibleScrollingCol; - dataGridViewColumn = this.Columns.GetNextColumn(dataGridViewColumn, + dataGridViewColumn = Columns.GetNextColumn(dataGridViewColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.None)) { newColOffset += dataGridViewColumn.Thickness; } - this.HorizontalOffset = newColOffset; + HorizontalOffset = newColOffset; } private bool ScrollIntoView(int columnIndex, int rowIndex, bool forCurrentCellChange) { - Debug.Assert(columnIndex >= 0 && columnIndex < this.Columns.Count); - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingCol >= -1 && this.displayedBandsInfo.FirstDisplayedScrollingCol < this.Columns.Count); - Debug.Assert(this.displayedBandsInfo.LastTotallyDisplayedScrollingCol >= -1 && this.displayedBandsInfo.LastTotallyDisplayedScrollingCol < this.Columns.Count); - Debug.Assert(rowIndex >= 0 && rowIndex < this.Rows.Count); - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow >= -1 && this.displayedBandsInfo.FirstDisplayedScrollingRow < this.Rows.Count); - Debug.Assert(this.Columns[columnIndex].Visible); - Debug.Assert((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Visible) != 0); + Debug.Assert(columnIndex >= 0 && columnIndex < Columns.Count); + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingCol >= -1 && displayedBandsInfo.FirstDisplayedScrollingCol < Columns.Count); + Debug.Assert(displayedBandsInfo.LastTotallyDisplayedScrollingCol >= -1 && displayedBandsInfo.LastTotallyDisplayedScrollingCol < Columns.Count); + Debug.Assert(rowIndex >= 0 && rowIndex < Rows.Count); + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingRow >= -1 && displayedBandsInfo.FirstDisplayedScrollingRow < Rows.Count); + Debug.Assert(Columns[columnIndex].Visible); + Debug.Assert((Rows.GetRowState(rowIndex) & DataGridViewElementStates.Visible) != 0); bool committed = false; - if (this.ptCurrentCell.X >= 0 && - (this.ptCurrentCell.X != columnIndex || this.ptCurrentCell.Y != rowIndex)) + if (ptCurrentCell.X >= 0 && + (ptCurrentCell.X != columnIndex || ptCurrentCell.Y != rowIndex)) { if (!CommitEditForOperation(columnIndex, rowIndex, forCurrentCellChange)) { @@ -26019,14 +26019,14 @@ private void ScrollRectangles(NativeMethods.RECT[] rects, int change) { if (MouseButtons != MouseButtons.None) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_scrolledSinceMouseDown] = true; + dataGridViewState1[DATAGRIDVIEWSTATE1_scrolledSinceMouseDown] = true; } NativeMethods.RECT scroll; for (int r = 0; r < rects.Length; r++) { scroll = rects[r]; - SafeNativeMethods.ScrollWindow(new HandleRef(this, this.Handle), + SafeNativeMethods.ScrollWindow(new HandleRef(this, Handle), change, 0, ref scroll, @@ -26037,46 +26037,46 @@ private void ScrollRectangles(NativeMethods.RECT[] rects, int change) private bool ScrollRowIntoView(int columnIndex, int rowIndex, bool committed, bool forCurrentCellChange) { - Debug.Assert(rowIndex >= 0 && rowIndex < this.Rows.Count); + Debug.Assert(rowIndex >= 0 && rowIndex < Rows.Count); - if ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Frozen) == 0) + if ((Rows.GetRowState(rowIndex) & DataGridViewElementStates.Frozen) == 0) { int rowsToScroll; - if (rowIndex < this.displayedBandsInfo.FirstDisplayedScrollingRow) + if (rowIndex < displayedBandsInfo.FirstDisplayedScrollingRow) { - if (!committed && this.ptCurrentCell.X >= 0 && + if (!committed && ptCurrentCell.X >= 0 && !CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, - forCurrentCellChange && (this.ptCurrentCell.X != columnIndex || this.ptCurrentCell.Y != rowIndex), - this.ptCurrentCell.Y != rowIndex /*forCurrentRowChange*/)) + forCurrentCellChange && (ptCurrentCell.X != columnIndex || ptCurrentCell.Y != rowIndex), + ptCurrentCell.Y != rowIndex /*forCurrentRowChange*/)) { return false; } - rowsToScroll = this.Rows.GetRowCount(DataGridViewElementStates.Visible, rowIndex, this.displayedBandsInfo.FirstDisplayedScrollingRow); + rowsToScroll = Rows.GetRowCount(DataGridViewElementStates.Visible, rowIndex, displayedBandsInfo.FirstDisplayedScrollingRow); ScrollRowsByCount(-rowsToScroll, rowsToScroll > 1 ? ScrollEventType.LargeDecrement : ScrollEventType.SmallDecrement); } - else if (this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0 && - rowIndex > this.displayedBandsInfo.FirstDisplayedScrollingRow) + else if (displayedBandsInfo.FirstDisplayedScrollingRow >= 0 && + rowIndex > displayedBandsInfo.FirstDisplayedScrollingRow) { rowsToScroll = 0; - int firstDisplayedScrollingRow = this.displayedBandsInfo.FirstDisplayedScrollingRow; - int yRowBottomEdge = GetRowYFromIndex(rowIndex) + this.Rows.SharedRow(rowIndex).GetHeight(rowIndex); - while (yRowBottomEdge > this.layout.Data.Bottom && rowIndex > firstDisplayedScrollingRow) + int firstDisplayedScrollingRow = displayedBandsInfo.FirstDisplayedScrollingRow; + int yRowBottomEdge = GetRowYFromIndex(rowIndex) + Rows.SharedRow(rowIndex).GetHeight(rowIndex); + while (yRowBottomEdge > layout.Data.Bottom && rowIndex > firstDisplayedScrollingRow) { - yRowBottomEdge -= this.Rows.SharedRow(firstDisplayedScrollingRow).GetHeight(firstDisplayedScrollingRow); + yRowBottomEdge -= Rows.SharedRow(firstDisplayedScrollingRow).GetHeight(firstDisplayedScrollingRow); rowsToScroll++; - if (yRowBottomEdge > this.layout.Data.Bottom) + if (yRowBottomEdge > layout.Data.Bottom) { - firstDisplayedScrollingRow = this.Rows.GetNextRow(firstDisplayedScrollingRow, DataGridViewElementStates.Visible); + firstDisplayedScrollingRow = Rows.GetNextRow(firstDisplayedScrollingRow, DataGridViewElementStates.Visible); Debug.Assert(firstDisplayedScrollingRow != -1); } } if (rowsToScroll != 0) { - if (!committed && this.ptCurrentCell.X >= 0 && + if (!committed && ptCurrentCell.X >= 0 && !CommitEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.Scroll, - forCurrentCellChange && (this.ptCurrentCell.X != columnIndex || this.ptCurrentCell.Y != rowIndex), - this.ptCurrentCell.Y != rowIndex /*forCurrentRowChange*/)) + forCurrentCellChange && (ptCurrentCell.X != columnIndex || ptCurrentCell.Y != rowIndex), + ptCurrentCell.Y != rowIndex /*forCurrentRowChange*/)) { return false; } @@ -26092,26 +26092,26 @@ private void ScrollRows(int rowCount, int deltaY, ScrollEventType scrollEventTyp bool invalidateTopOfRowHeaders = false; Debug.Assert(rowCount != 0); Debug.Assert(deltaY != 0); - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow >= this.Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)); - this.verticalOffset -= deltaY; - if (this.vertScrollBar.Enabled) + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingRow >= Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)); + verticalOffset -= deltaY; + if (vertScrollBar.Enabled) { - this.vertScrollBar.Value = this.verticalOffset; + vertScrollBar.Value = verticalOffset; } ClearRegionCache(); - int frozenRowsThickness = this.Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); - Rectangle rowsRect = this.layout.Data; - if (this.layout.RowHeadersVisible) + int frozenRowsThickness = Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + Rectangle rowsRect = layout.Data; + if (layout.RowHeadersVisible) { - rowsRect = Rectangle.Union(rowsRect, this.layout.RowHeaders); - if (this.SingleHorizontalBorderAdded) + rowsRect = Rectangle.Union(rowsRect, layout.RowHeaders); + if (SingleHorizontalBorderAdded) { rowsRect.Y++; rowsRect.Height--; invalidateTopOfRowHeaders = true; } } - else if (this.SingleVerticalBorderAdded) + else if (SingleVerticalBorderAdded) { Debug.Assert(rowsRect.X > 0); rowsRect.X--; @@ -26121,37 +26121,37 @@ private void ScrollRows(int rowCount, int deltaY, ScrollEventType scrollEventTyp rowsRect.Height -= frozenRowsThickness; Debug.Assert(rowsRect.Height >= 0); - if (this.editingControl != null && - (this.Rows.GetRowState(this.ptCurrentCell.Y) & DataGridViewElementStates.Frozen) == 0) + if (editingControl != null && + (Rows.GetRowState(ptCurrentCell.Y) & DataGridViewElementStates.Frozen) == 0) { - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow > -1); + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingRow > -1); PositionEditingControl(true /*setLocation*/, false /*setSize*/, false /*setFocus*/); } if (MouseButtons != MouseButtons.None) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_scrolledSinceMouseDown] = true; + dataGridViewState1[DATAGRIDVIEWSTATE1_scrolledSinceMouseDown] = true; } // The mouse probably is not over the same cell after the scroll. UpdateMouseEnteredCell(null /*HitTestInfo*/, null /*MouseEventArgs*/); NativeMethods.RECT scrollArea = NativeMethods.RECT.FromXYWH(rowsRect.X, rowsRect.Y, rowsRect.Width, rowsRect.Height); - SafeNativeMethods.ScrollWindow(new HandleRef(this, this.Handle), 0, deltaY, ref scrollArea, ref scrollArea); + SafeNativeMethods.ScrollWindow(new HandleRef(this, Handle), 0, deltaY, ref scrollArea, ref scrollArea); if (invalidateTopOfRowHeaders) { - rowsRect.X = this.layout.Inside.X; - rowsRect.Y = this.layout.Inside.Y; - rowsRect.Width = this.layout.RowHeaders.Width; + rowsRect.X = layout.Inside.X; + rowsRect.Y = layout.Inside.Y; + rowsRect.Width = layout.RowHeaders.Width; rowsRect.Height = 1; Invalidate(rowsRect); } - if (!this.dataGridViewState2[DATAGRIDVIEWSTATE2_stopRaisingVerticalScroll]) + if (!dataGridViewState2[DATAGRIDVIEWSTATE2_stopRaisingVerticalScroll]) { - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0); - int firstVisibleScrollingRow = this.Rows.GetFirstRow(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingRow >= 0); + int firstVisibleScrollingRow = Rows.GetFirstRow(DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); Debug.Assert(firstVisibleScrollingRow != -1); - int newScrolledOffRowCount = this.Rows.GetRowCount(DataGridViewElementStates.Visible, firstVisibleScrollingRow, this.displayedBandsInfo.FirstDisplayedScrollingRow); + int newScrolledOffRowCount = Rows.GetRowCount(DataGridViewElementStates.Visible, firstVisibleScrollingRow, displayedBandsInfo.FirstDisplayedScrollingRow); Debug.Assert(newScrolledOffRowCount >= rowCount); OnScroll(scrollEventType, newScrolledOffRowCount - rowCount, newScrolledOffRowCount, ScrollOrientation.VerticalScroll); } @@ -26164,34 +26164,34 @@ private void ScrollRowsByCount(int rows, ScrollEventType scrollEventType) (rows < 0 && (scrollEventType == ScrollEventType.SmallDecrement || scrollEventType == ScrollEventType.LargeDecrement))); int deltaY = 0; - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0); - int newFirstVisibleScrollingRow = this.displayedBandsInfo.FirstDisplayedScrollingRow; + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingRow >= 0); + int newFirstVisibleScrollingRow = displayedBandsInfo.FirstDisplayedScrollingRow; if (rows > 0) { for (int rowCount = rows; rowCount > 0; rowCount--) { - deltaY -= this.Rows.SharedRow(newFirstVisibleScrollingRow).GetHeight(newFirstVisibleScrollingRow); - newFirstVisibleScrollingRow = this.Rows.GetNextRow(newFirstVisibleScrollingRow, + deltaY -= Rows.SharedRow(newFirstVisibleScrollingRow).GetHeight(newFirstVisibleScrollingRow); + newFirstVisibleScrollingRow = Rows.GetNextRow(newFirstVisibleScrollingRow, DataGridViewElementStates.Visible); Debug.Assert(newFirstVisibleScrollingRow != -1); } if (newFirstVisibleScrollingRow != -1) { - int oldFirstVisibleScrollingRow = this.displayedBandsInfo.FirstDisplayedScrollingRow; + int oldFirstVisibleScrollingRow = displayedBandsInfo.FirstDisplayedScrollingRow; // Tentative target value for this.displayedBandsInfo.FirstDisplayedScrollingRow. - this.displayedBandsInfo.FirstDisplayedScrollingRow = newFirstVisibleScrollingRow; + displayedBandsInfo.FirstDisplayedScrollingRow = newFirstVisibleScrollingRow; // This sets the actual value of this.displayedBandsInfo.FirstDisplayedScrollingRow ComputeVisibleRows(); // Compute the actual deltaY given the new this.displayedBandsInfo.FirstDisplayedScrollingRow - if (this.displayedBandsInfo.FirstDisplayedScrollingRow > oldFirstVisibleScrollingRow) + if (displayedBandsInfo.FirstDisplayedScrollingRow > oldFirstVisibleScrollingRow) { - deltaY = -this.Rows.GetRowsHeight(DataGridViewElementStates.Visible, oldFirstVisibleScrollingRow, this.displayedBandsInfo.FirstDisplayedScrollingRow); - rows = this.Rows.GetRowCount(DataGridViewElementStates.Visible, oldFirstVisibleScrollingRow, this.displayedBandsInfo.FirstDisplayedScrollingRow); + deltaY = -Rows.GetRowsHeight(DataGridViewElementStates.Visible, oldFirstVisibleScrollingRow, displayedBandsInfo.FirstDisplayedScrollingRow); + rows = Rows.GetRowCount(DataGridViewElementStates.Visible, oldFirstVisibleScrollingRow, displayedBandsInfo.FirstDisplayedScrollingRow); } else { - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow == oldFirstVisibleScrollingRow); + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingRow == oldFirstVisibleScrollingRow); rows = 0; } } @@ -26200,19 +26200,19 @@ private void ScrollRowsByCount(int rows, ScrollEventType scrollEventType) { for (int rowCount = rows; rowCount < 0; rowCount++) { - newFirstVisibleScrollingRow = this.Rows.GetPreviousRow(newFirstVisibleScrollingRow, + newFirstVisibleScrollingRow = Rows.GetPreviousRow(newFirstVisibleScrollingRow, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); if (newFirstVisibleScrollingRow != -1) { - deltaY += this.Rows.SharedRow(newFirstVisibleScrollingRow).GetHeight(newFirstVisibleScrollingRow); + deltaY += Rows.SharedRow(newFirstVisibleScrollingRow).GetHeight(newFirstVisibleScrollingRow); } } if (newFirstVisibleScrollingRow != -1) { - this.displayedBandsInfo.FirstDisplayedScrollingRow = newFirstVisibleScrollingRow; + displayedBandsInfo.FirstDisplayedScrollingRow = newFirstVisibleScrollingRow; ComputeVisibleRows(); - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow == newFirstVisibleScrollingRow); + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingRow == newFirstVisibleScrollingRow); } } @@ -26226,41 +26226,41 @@ private void ScrollRowsByCount(int rows, ScrollEventType scrollEventType) private void ScrollRowsByHeight(int height) { - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0); + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingRow >= 0); int deltaY, scrollHeight = 0; - int oldFirstVisibleScrollingRow = this.displayedBandsInfo.FirstDisplayedScrollingRow; - int newFirstVisibleScrollingRow = this.displayedBandsInfo.FirstDisplayedScrollingRow; + int oldFirstVisibleScrollingRow = displayedBandsInfo.FirstDisplayedScrollingRow; + int newFirstVisibleScrollingRow = displayedBandsInfo.FirstDisplayedScrollingRow; if (height > 0) { - deltaY = this.Rows.SharedRow(newFirstVisibleScrollingRow).GetHeight(newFirstVisibleScrollingRow); + deltaY = Rows.SharedRow(newFirstVisibleScrollingRow).GetHeight(newFirstVisibleScrollingRow); while (deltaY <= height) { - newFirstVisibleScrollingRow = this.Rows.GetNextRow(newFirstVisibleScrollingRow, DataGridViewElementStates.Visible); + newFirstVisibleScrollingRow = Rows.GetNextRow(newFirstVisibleScrollingRow, DataGridViewElementStates.Visible); if (newFirstVisibleScrollingRow == -1) { throw new InvalidOperationException(); } else { - deltaY += this.Rows.SharedRow(newFirstVisibleScrollingRow).GetHeight(newFirstVisibleScrollingRow); + deltaY += Rows.SharedRow(newFirstVisibleScrollingRow).GetHeight(newFirstVisibleScrollingRow); } } } else { - newFirstVisibleScrollingRow = this.Rows.GetPreviousRow(newFirstVisibleScrollingRow, + newFirstVisibleScrollingRow = Rows.GetPreviousRow(newFirstVisibleScrollingRow, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); Debug.Assert(newFirstVisibleScrollingRow != -1); - deltaY = -this.Rows.SharedRow(newFirstVisibleScrollingRow).GetHeight(newFirstVisibleScrollingRow); + deltaY = -Rows.SharedRow(newFirstVisibleScrollingRow).GetHeight(newFirstVisibleScrollingRow); while (deltaY >= height) { - int scrollingRowTmp = this.Rows.GetPreviousRow(newFirstVisibleScrollingRow, + int scrollingRowTmp = Rows.GetPreviousRow(newFirstVisibleScrollingRow, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen); if (scrollingRowTmp != -1) { - deltaY -= this.Rows.SharedRow(scrollingRowTmp).GetHeight(scrollingRowTmp); + deltaY -= Rows.SharedRow(scrollingRowTmp).GetHeight(scrollingRowTmp); if (deltaY >= height) { newFirstVisibleScrollingRow = scrollingRowTmp; @@ -26274,22 +26274,22 @@ private void ScrollRowsByHeight(int height) } // Tentative target value for this.displayedBandsInfo.FirstDisplayedScrollingRow. - this.displayedBandsInfo.FirstDisplayedScrollingRow = newFirstVisibleScrollingRow; + displayedBandsInfo.FirstDisplayedScrollingRow = newFirstVisibleScrollingRow; // This sets the actual value of this.displayedBandsInfo.FirstDisplayedScrollingRow ComputeVisibleRows(); ScrollEventType scrollEventType = ScrollEventType.EndScroll; int rowCount = 0; // Compute the scrollHeight given the new this.displayedBandsInfo.FirstDisplayedScrollingRow - if (this.displayedBandsInfo.FirstDisplayedScrollingRow > oldFirstVisibleScrollingRow) + if (displayedBandsInfo.FirstDisplayedScrollingRow > oldFirstVisibleScrollingRow) { - scrollHeight = this.Rows.GetRowsHeight(DataGridViewElementStates.Visible, oldFirstVisibleScrollingRow, this.displayedBandsInfo.FirstDisplayedScrollingRow); - rowCount = this.Rows.GetRowCount(DataGridViewElementStates.Visible, oldFirstVisibleScrollingRow, this.displayedBandsInfo.FirstDisplayedScrollingRow); + scrollHeight = Rows.GetRowsHeight(DataGridViewElementStates.Visible, oldFirstVisibleScrollingRow, displayedBandsInfo.FirstDisplayedScrollingRow); + rowCount = Rows.GetRowCount(DataGridViewElementStates.Visible, oldFirstVisibleScrollingRow, displayedBandsInfo.FirstDisplayedScrollingRow); scrollEventType = rowCount > 1 ? ScrollEventType.LargeIncrement : ScrollEventType.SmallIncrement; } - else if (this.displayedBandsInfo.FirstDisplayedScrollingRow < oldFirstVisibleScrollingRow) + else if (displayedBandsInfo.FirstDisplayedScrollingRow < oldFirstVisibleScrollingRow) { - scrollHeight = -this.Rows.GetRowsHeight(DataGridViewElementStates.Visible, this.displayedBandsInfo.FirstDisplayedScrollingRow, oldFirstVisibleScrollingRow); - rowCount = -this.Rows.GetRowCount(DataGridViewElementStates.Visible, this.displayedBandsInfo.FirstDisplayedScrollingRow, oldFirstVisibleScrollingRow); + scrollHeight = -Rows.GetRowsHeight(DataGridViewElementStates.Visible, displayedBandsInfo.FirstDisplayedScrollingRow, oldFirstVisibleScrollingRow); + rowCount = -Rows.GetRowCount(DataGridViewElementStates.Visible, displayedBandsInfo.FirstDisplayedScrollingRow, oldFirstVisibleScrollingRow); scrollEventType = rowCount < -1 ? ScrollEventType.LargeDecrement : ScrollEventType.SmallDecrement; } if (scrollHeight != 0) @@ -26304,26 +26304,26 @@ private void ScrollRowsByHeight(int height) [SuppressMessage("Microsoft.Performance", "CA1817:DoNotCallPropertiesThatCloneValuesInLoops")] public void SelectAll() { - if (!this.MultiSelect) + if (!MultiSelect) { return; } - this.inBulkPaintCount++; - this.noDimensionChangeCount++; - this.noSelectionChangeCount++; + inBulkPaintCount++; + noDimensionChangeCount++; + noSelectionChangeCount++; try { DataGridViewRow dataGridViewRow = null; - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: { // Bonjour the scalability issues! We select each cell, one at the time. - int maxColumnIndex = this.Columns.Count; - int rowIndex = 0, maxRowIndex = this.Rows.Count; + int maxColumnIndex = Columns.Count; + int rowIndex = 0, maxRowIndex = Rows.Count; while (rowIndex < maxRowIndex) { - dataGridViewRow = this.Rows[rowIndex]; //unsharing each row! + dataGridViewRow = Rows[rowIndex]; //unsharing each row! int columnIndex = 0; while (columnIndex < maxColumnIndex) { @@ -26338,10 +26338,10 @@ public void SelectAll() case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: { - int rowIndex = 0, maxRowIndex = this.Rows.Count; + int rowIndex = 0, maxRowIndex = Rows.Count; while (rowIndex < maxRowIndex) { - DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); + DataGridViewElementStates rowState = Rows.GetRowState(rowIndex); if ((rowState & DataGridViewElementStates.Selected) == 0) { SetSelectedRowCore(rowIndex, true); @@ -26354,10 +26354,10 @@ public void SelectAll() case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: { - int columnIndex = 0, maxColumnIndex = this.Columns.Count; + int columnIndex = 0, maxColumnIndex = Columns.Count; while (columnIndex < maxColumnIndex) { - if (!this.Columns[columnIndex].Selected) + if (!Columns[columnIndex].Selected) { SetSelectedColumnCore(columnIndex, true); } @@ -26369,29 +26369,29 @@ public void SelectAll() } finally { - this.noDimensionChangeCount--; - this.noSelectionChangeCount--; - Debug.Assert(this.noDimensionChangeCount >= 0); - Debug.Assert(this.noSelectionChangeCount >= 0); + noDimensionChangeCount--; + noSelectionChangeCount--; + Debug.Assert(noDimensionChangeCount >= 0); + Debug.Assert(noSelectionChangeCount >= 0); ExitBulkPaint(-1, -1); } - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); - int firstVisibleRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); + int firstVisibleRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); if (dataGridViewColumn != null && firstVisibleRowIndex != -1) { // This is the only place in the code outside of SetCurrentCellAddressCore where this.ptAnchorCell gets changed. // There is no way in SetCurrentCellAddressCore to just change the anchor cell. - this.ptAnchorCell.X = dataGridViewColumn.Index; - this.ptAnchorCell.Y = firstVisibleRowIndex; + ptAnchorCell.X = dataGridViewColumn.Index; + ptAnchorCell.Y = firstVisibleRowIndex; } else { - this.ptAnchorCell.X = -1; - this.ptAnchorCell.Y = -1; + ptAnchorCell.X = -1; + ptAnchorCell.Y = -1; } - if (this.noSelectionChangeCount == 0) + if (noSelectionChangeCount == 0) { FlushSelectionChanged(); } @@ -26400,63 +26400,63 @@ public void SelectAll() private DataGridViewCell SelectedCell(int index) { Debug.Assert(index >= 0); - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: { - if (index < this.individualSelectedCells.Count) + if (index < individualSelectedCells.Count) { - return this.individualSelectedCells[index]; + return individualSelectedCells[index]; } break; } case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: { - int selectedBand = 0, selectedBands = this.selectedBandIndexes.Count; + int selectedBand = 0, selectedBands = selectedBandIndexes.Count; while (selectedBand < selectedBands && index >= 0) { - if (index >= this.Rows.Count) + if (index >= Rows.Count) { - index -= this.Rows.Count; + index -= Rows.Count; selectedBand++; } else { - int columnIndex = this.selectedBandIndexes[selectedBand]; - return this.Rows.SharedRow(index).Cells[columnIndex]; + int columnIndex = selectedBandIndexes[selectedBand]; + return Rows.SharedRow(index).Cells[columnIndex]; } } - if (this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect && - index < this.individualSelectedCells.Count) + if (SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect && + index < individualSelectedCells.Count) { - return this.individualSelectedCells[index]; + return individualSelectedCells[index]; } break; } case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: { - int selectedBand = 0, selectedBands = this.selectedBandIndexes.Count; + int selectedBand = 0, selectedBands = selectedBandIndexes.Count; while (selectedBand < selectedBands && index >= 0) { - if (index >= this.Columns.Count) + if (index >= Columns.Count) { - index -= this.Columns.Count; + index -= Columns.Count; selectedBand++; } else { - int rowIndex = this.selectedBandIndexes[selectedBand]; - return this.Rows.SharedRow(rowIndex).Cells[index]; + int rowIndex = selectedBandIndexes[selectedBand]; + return Rows.SharedRow(rowIndex).Cells[index]; } } - if (this.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect && - index < this.individualSelectedCells.Count) + if (SelectionMode == DataGridViewSelectionMode.RowHeaderSelect && + index < individualSelectedCells.Count) { - return this.individualSelectedCells[index]; + return individualSelectedCells[index]; } break; } @@ -26466,19 +26466,19 @@ private DataGridViewCell SelectedCell(int index) private void SetColumnHeadersHeightInternal(int columnHeadersHeight, bool invalidInAdjustFillingColumns) { - using (LayoutTransaction.CreateTransactionIf(this.AutoSize, this.ParentInternal, this, PropertyNames.ColumnHeadersHeight)) + using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.ColumnHeadersHeight)) { Debug.Assert(this.columnHeadersHeight != columnHeadersHeight); Debug.Assert(columnHeadersHeight >= minimumColumnHeadersHeight); Debug.Assert(columnHeadersHeight <= maxHeadersThickness); this.columnHeadersHeight = columnHeadersHeight; - if (this.AutoSize) + if (AutoSize) { InvalidateInside(); } else { - if (this.layout.ColumnHeadersVisible) + if (layout.ColumnHeadersVisible) { PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, invalidInAdjustFillingColumns, true /*repositionEditingControl*/); InvalidateInside(); @@ -26496,31 +26496,31 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, { if (columnIndex < -1 || (columnIndex >= 0 && rowIndex == -1) || - columnIndex >= this.Columns.Count) + columnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException(nameof(columnIndex)); } if (rowIndex < -1 || (columnIndex == -1 && rowIndex >= 0) || - rowIndex >= this.Rows.Count) + rowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } if (columnIndex > -1 && rowIndex > -1 && - !IsSharedCellVisible(this.Rows.SharedRow(rowIndex).Cells[columnIndex], rowIndex)) + !IsSharedCellVisible(Rows.SharedRow(rowIndex).Cells[columnIndex], rowIndex)) { throw new InvalidOperationException(string.Format(SR.DataGridView_CurrentCellCannotBeInvisible)); } - if (this.dataGridViewOper[DATAGRIDVIEWOPER_inCurrentCellChange] && // Allow the code to be re-entrant only as a result of - (this.dataConnection == null || !this.dataConnection.ProcessingListChangedEvent)) // underlying data changing. + if (dataGridViewOper[DATAGRIDVIEWOPER_inCurrentCellChange] && // Allow the code to be re-entrant only as a result of + (dataConnection == null || !dataConnection.ProcessingListChangedEvent)) // underlying data changing. { throw new InvalidOperationException(string.Format(SR.DataGridView_SetCurrentCellAddressCoreNotReentrant)); } - this.dataGridViewOper[DATAGRIDVIEWOPER_inCurrentCellChange] = true; + dataGridViewOper[DATAGRIDVIEWOPER_inCurrentCellChange] = true; try { DataGridViewCell dataGridViewCellTmp = null; @@ -26528,21 +26528,21 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, if (columnIndex > -1) { Debug.Assert(rowIndex >= 0 && - columnIndex < this.Columns.Count && - rowIndex < this.Rows.Count); + columnIndex < Columns.Count && + rowIndex < Rows.Count); - if (this.ptCurrentCell.X != columnIndex || this.ptCurrentCell.Y != rowIndex) + if (ptCurrentCell.X != columnIndex || ptCurrentCell.Y != rowIndex) { - if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell]) + if (dataGridViewState1[DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell]) { - this.dataGridViewState1[DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell] = false; - this.ptCurrentCell.X = columnIndex; - this.ptCurrentCell.Y = rowIndex; - if (this.cachedEditingControl != null) + dataGridViewState1[DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell] = false; + ptCurrentCell.X = columnIndex; + ptCurrentCell.Y = rowIndex; + if (cachedEditingControl != null) { - this.editingControl = this.cachedEditingControl; - ((IDataGridViewEditingControl)this.editingControl).EditingControlRowIndex = rowIndex; - this.cachedEditingControl = null; + editingControl = cachedEditingControl; + ((IDataGridViewEditingControl)editingControl).EditingControlRowIndex = rowIndex; + cachedEditingControl = null; PositionEditingControl(true, true, false); } OnCurrentCellChanged(EventArgs.Empty); @@ -26550,11 +26550,11 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, } DataGridViewCell currentCell; - int oldCurrentCellX = this.ptCurrentCell.X; - int oldCurrentCellY = this.ptCurrentCell.Y; + int oldCurrentCellX = ptCurrentCell.X; + int oldCurrentCellY = ptCurrentCell.Y; if (oldCurrentCellX >= 0) { - currentCell = this.CurrentCellInternal; + currentCell = CurrentCellInternal; if (!EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.CurrentCellChange, validateCurrentCell ? DataGridViewValidateCellInternal.Always : DataGridViewValidateCellInternal.Never /*validateCell*/, validateCurrentCell /*fireCellLeave*/, @@ -26562,7 +26562,7 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, validateCurrentCell && oldCurrentCellY != rowIndex /*fireRowLeave*/, false /*fireRowEnter*/, false /*fireLeave*/, - this.EditMode != DataGridViewEditMode.EditOnEnter /*keepFocus*/, + EditMode != DataGridViewEditMode.EditOnEnter /*keepFocus*/, false /*resetCurrentCell*/, false /*resetAnchorCell unused here*/)) { @@ -26570,10 +26570,10 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, } if (!IsInnerCellOutOfBounds(oldCurrentCellX, oldCurrentCellY)) { - currentCell = this.Rows.SharedRow(oldCurrentCellY).Cells[oldCurrentCellX]; + currentCell = Rows.SharedRow(oldCurrentCellY).Cells[oldCurrentCellX]; if (currentCell.LeaveUnsharesRowInternal(oldCurrentCellY, throughMouseClick)) { - currentCell = this.Rows[oldCurrentCellY].Cells[oldCurrentCellX]; // unsharing the current row + currentCell = Rows[oldCurrentCellY].Cells[oldCurrentCellX]; // unsharing the current row } currentCell.OnLeaveInternal(oldCurrentCellY, throughMouseClick); } @@ -26590,8 +26590,8 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, if (!IsInnerCellOutOfBounds(oldCurrentCellX, oldCurrentCellY)) { // Row validation was cancelled - Debug.Assert(oldCurrentCellX == this.ptCurrentCell.X); - Debug.Assert(oldCurrentCellY == this.ptCurrentCell.Y); + Debug.Assert(oldCurrentCellX == ptCurrentCell.X); + Debug.Assert(oldCurrentCellY == ptCurrentCell.Y); OnRowEnter(ref dataGridViewCellTmp, oldCurrentCellX, oldCurrentCellY, true /*canCreateNewRow*/, true /*validationFailureOccurred*/); if (!IsInnerCellOutOfBounds(oldCurrentCellX, oldCurrentCellY)) { @@ -26609,7 +26609,7 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, } } - this.dataGridViewState2[DATAGRIDVIEWSTATE2_rowsCollectionClearedInSetCell] = false; + dataGridViewState2[DATAGRIDVIEWSTATE2_rowsCollectionClearedInSetCell] = false; try { @@ -26623,7 +26623,7 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, // Force repainting of the current and previous collumns` header cells to update highlighting if (oldCurrentCellX != columnIndex && - this.SelectionMode == DataGridViewSelectionMode.FullRowSelect) + SelectionMode == DataGridViewSelectionMode.FullRowSelect) { if (oldCurrentCellX >= 0) { @@ -26632,13 +26632,13 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, InvalidateCellPrivate(columnIndex, -1); } - if (this.dataGridViewState2[DATAGRIDVIEWSTATE2_rowsCollectionClearedInSetCell]) + if (dataGridViewState2[DATAGRIDVIEWSTATE2_rowsCollectionClearedInSetCell]) { // // The rows collection was cleared while processing OnRowEnter. // If the new list is too small for rowIndex, fail the call to SetCurrentCellAddressCore. // - if (rowIndex >= this.Rows.Count) + if (rowIndex >= Rows.Count) { return false; } @@ -26650,17 +26650,17 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, return false; } - this.ptCurrentCell.X = columnIndex; - this.ptCurrentCell.Y = rowIndex; - if (this.editingControl != null) + ptCurrentCell.X = columnIndex; + ptCurrentCell.Y = rowIndex; + if (editingControl != null) { - ((IDataGridViewEditingControl)this.editingControl).EditingControlRowIndex = rowIndex; + ((IDataGridViewEditingControl)editingControl).EditingControlRowIndex = rowIndex; } OnCurrentCellChanged(EventArgs.Empty); if (setAnchorCellAddress) { - this.ptAnchorCell.X = columnIndex; - this.ptAnchorCell.Y = rowIndex; + ptAnchorCell.X = columnIndex; + ptAnchorCell.Y = rowIndex; } #if FALSE @@ -26672,50 +26672,50 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, } #endif - currentCell = this.CurrentCellInternal; + currentCell = CurrentCellInternal; if (currentCell.EnterUnsharesRowInternal(rowIndex, throughMouseClick)) { - currentCell = this.Rows[rowIndex].Cells[columnIndex]; // unsharing the row + currentCell = Rows[rowIndex].Cells[columnIndex]; // unsharing the row } currentCell.OnEnterInternal(rowIndex, throughMouseClick); - OnCellEnter(ref dataGridViewCellTmp, this.ptCurrentCell.X, this.ptCurrentCell.Y); + OnCellEnter(ref dataGridViewCellTmp, ptCurrentCell.X, ptCurrentCell.Y); if (oldCurrentCellX >= 0) { Debug.Assert(oldCurrentCellY >= 0); - if (oldCurrentCellX < this.Columns.Count && oldCurrentCellY < this.Rows.Count) + if (oldCurrentCellX < Columns.Count && oldCurrentCellY < Rows.Count) { InvalidateCellPrivate(oldCurrentCellX, oldCurrentCellY); } - if (oldCurrentCellY != this.ptCurrentCell.Y && this.RowHeadersVisible && oldCurrentCellY < this.Rows.Count) + if (oldCurrentCellY != ptCurrentCell.Y && RowHeadersVisible && oldCurrentCellY < Rows.Count) { InvalidateCellPrivate(-1, oldCurrentCellY); } } - InvalidateCellPrivate(this.ptCurrentCell.X, this.ptCurrentCell.Y); - if (this.RowHeadersVisible && oldCurrentCellY != this.ptCurrentCell.Y) + InvalidateCellPrivate(ptCurrentCell.X, ptCurrentCell.Y); + if (RowHeadersVisible && oldCurrentCellY != ptCurrentCell.Y) { - InvalidateCellPrivate(-1, this.ptCurrentCell.Y); + InvalidateCellPrivate(-1, ptCurrentCell.Y); } - if (this.Focused && - this.ptCurrentCell.X != -1 && - !this.IsCurrentCellInEditMode && - !this.dataGridViewState1[DATAGRIDVIEWSTATE1_leavingWithTabKey] && // don't edit if we're in the process of leaving the grid - !this.dataGridViewState2[DATAGRIDVIEWSTATE2_rowsCollectionClearedInSetCell] && // don't edit if the rows collection changed - (this.EditMode == DataGridViewEditMode.EditOnEnter || - (this.EditMode != DataGridViewEditMode.EditProgrammatically && currentCell.EditType == null))) + if (Focused && + ptCurrentCell.X != -1 && + !IsCurrentCellInEditMode && + !dataGridViewState1[DATAGRIDVIEWSTATE1_leavingWithTabKey] && // don't edit if we're in the process of leaving the grid + !dataGridViewState2[DATAGRIDVIEWSTATE2_rowsCollectionClearedInSetCell] && // don't edit if the rows collection changed + (EditMode == DataGridViewEditMode.EditOnEnter || + (EditMode != DataGridViewEditMode.EditProgrammatically && currentCell.EditType == null))) { BeginEditInternal(true /*selectAll*/); } } finally { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_rowsCollectionClearedInSetCell] = false; + dataGridViewState2[DATAGRIDVIEWSTATE2_rowsCollectionClearedInSetCell] = false; } // Accessibility - if (this.ptCurrentCell.X != -1) + if (ptCurrentCell.X != -1) { - AccessibilityNotifyCurrentCellChanged(new Point(this.ptCurrentCell.X, this.ptCurrentCell.Y)); + AccessibilityNotifyCurrentCellChanged(new Point(ptCurrentCell.X, ptCurrentCell.Y)); } } else @@ -26724,12 +26724,12 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, // Not trying to change the current cell, but may need to edit it. if (setAnchorCellAddress) { - this.ptAnchorCell.X = columnIndex; - this.ptAnchorCell.Y = rowIndex; + ptAnchorCell.X = columnIndex; + ptAnchorCell.Y = rowIndex; } - if (this.Focused && - (!this.IsCurrentCellInEditMode && (this.EditMode == DataGridViewEditMode.EditOnEnter || - (this.EditMode != DataGridViewEditMode.EditProgrammatically && this.CurrentCellInternal.EditType == null)))) + if (Focused && + (!IsCurrentCellInEditMode && (EditMode == DataGridViewEditMode.EditOnEnter || + (EditMode != DataGridViewEditMode.EditProgrammatically && CurrentCellInternal.EditType == null)))) { BeginEditInternal(true /*selectAll*/); } @@ -26741,13 +26741,13 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, } else { - int oldCurrentCellX = this.ptCurrentCell.X; - int oldCurrentCellY = this.ptCurrentCell.Y; + int oldCurrentCellX = ptCurrentCell.X; + int oldCurrentCellY = ptCurrentCell.Y; if (oldCurrentCellX >= 0 && - !this.dataGridViewState1[DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell] && - !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose]) + !dataGridViewState1[DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell] && + !dataGridViewOper[DATAGRIDVIEWOPER_inDispose]) { - DataGridViewCell currentCell = this.CurrentCellInternal; + DataGridViewCell currentCell = CurrentCellInternal; if (!EndEdit(DataGridViewDataErrorContexts.Parsing | DataGridViewDataErrorContexts.Commit | DataGridViewDataErrorContexts.CurrentCellChange, validateCurrentCell ? DataGridViewValidateCellInternal.Always : DataGridViewValidateCellInternal.Never, validateCurrentCell /*fireCellLeave*/, @@ -26755,7 +26755,7 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, validateCurrentCell /*fireRowLeave*/, false /*fireRowEnter*/, false /*fireLeave*/, - this.EditMode != DataGridViewEditMode.EditOnEnter /*keepFocus*/, + EditMode != DataGridViewEditMode.EditOnEnter /*keepFocus*/, false /*resetCurrentCell*/, false /*resetAnchorCell unused here*/)) { @@ -26763,10 +26763,10 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, } if (!IsInnerCellOutOfBounds(oldCurrentCellX, oldCurrentCellY)) { - currentCell = this.Rows.SharedRow(oldCurrentCellY).Cells[oldCurrentCellX]; + currentCell = Rows.SharedRow(oldCurrentCellY).Cells[oldCurrentCellX]; if (currentCell.LeaveUnsharesRowInternal(oldCurrentCellY, throughMouseClick)) { - currentCell = this.Rows[oldCurrentCellY].Cells[oldCurrentCellX]; // unsharing the current row + currentCell = Rows[oldCurrentCellY].Cells[oldCurrentCellX]; // unsharing the current row } currentCell.OnLeaveInternal(oldCurrentCellY, throughMouseClick); } @@ -26777,8 +26777,8 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, if (!IsInnerCellOutOfBounds(oldCurrentCellX, oldCurrentCellY)) { // Row validation was cancelled - Debug.Assert(oldCurrentCellX == this.ptCurrentCell.X); - Debug.Assert(oldCurrentCellY == this.ptCurrentCell.Y); + Debug.Assert(oldCurrentCellX == ptCurrentCell.X); + Debug.Assert(oldCurrentCellY == ptCurrentCell.Y); OnRowEnter(ref dataGridViewCellTmp, oldCurrentCellX, oldCurrentCellY, true /*canCreateNewRow*/, true /*validationFailureOccurred*/); if (!IsInnerCellOutOfBounds(oldCurrentCellX, oldCurrentCellY)) { @@ -26794,40 +26794,40 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, } } } - if (this.ptCurrentCell.X != -1) + if (ptCurrentCell.X != -1) { - this.ptCurrentCell.X = -1; - this.ptCurrentCell.Y = -1; + ptCurrentCell.X = -1; + ptCurrentCell.Y = -1; OnCurrentCellChanged(EventArgs.Empty); } if (setAnchorCellAddress) { - this.ptAnchorCell.X = -1; - this.ptAnchorCell.Y = -1; + ptAnchorCell.X = -1; + ptAnchorCell.Y = -1; } - if (this.dataGridViewState1[DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell]) + if (dataGridViewState1[DATAGRIDVIEWSTATE1_temporarilyResetCurrentCell]) { - if (this.editingControl != null) + if (editingControl != null) { - if (this.dataGridViewState2[DATAGRIDVIEWSTATE2_discardEditingControl]) + if (dataGridViewState2[DATAGRIDVIEWSTATE2_discardEditingControl]) { - this.dataGridViewState2[DATAGRIDVIEWSTATE2_discardEditingControl] = false; + dataGridViewState2[DATAGRIDVIEWSTATE2_discardEditingControl] = false; } else { - this.cachedEditingControl = this.editingControl; + cachedEditingControl = editingControl; } - this.editingControl = null; + editingControl = null; } } - else if (oldCurrentCellX >= 0 && !this.dataGridViewOper[DATAGRIDVIEWOPER_inDispose]) + else if (oldCurrentCellX >= 0 && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose]) { Debug.Assert(oldCurrentCellY >= 0); - if (oldCurrentCellX < this.Columns.Count && oldCurrentCellY < this.Rows.Count) + if (oldCurrentCellX < Columns.Count && oldCurrentCellY < Rows.Count) { InvalidateCellPrivate(oldCurrentCellX, oldCurrentCellY); } - if (this.RowHeadersVisible && oldCurrentCellY < this.Rows.Count) + if (RowHeadersVisible && oldCurrentCellY < Rows.Count) { InvalidateCellPrivate(-1, oldCurrentCellY); } @@ -26836,7 +26836,7 @@ protected virtual bool SetCurrentCellAddressCore(int columnIndex, } finally { - this.dataGridViewOper[DATAGRIDVIEWOPER_inCurrentCellChange] = false; + dataGridViewOper[DATAGRIDVIEWOPER_inCurrentCellChange] = false; } return true; } @@ -26853,16 +26853,16 @@ internal void SetCurrentCellAddressCoreInternal(int columnIndex, private void SelectCellRange(int columnIndexFrom, int rowIndexFrom, int columnIndexTo, int rowIndexTo, bool select) { Debug.Assert(columnIndexFrom >= 0 && columnIndexTo >= 0); - Debug.Assert((this.Columns[columnIndexFrom]).DisplayIndex <= (this.Columns[columnIndexTo]).DisplayIndex); + Debug.Assert((Columns[columnIndexFrom]).DisplayIndex <= (Columns[columnIndexTo]).DisplayIndex); Debug.Assert(rowIndexFrom >= 0 && rowIndexTo >= 0); Debug.Assert(rowIndexFrom <= rowIndexTo); - Debug.Assert(this.noSelectionChangeCount > 0); + Debug.Assert(noSelectionChangeCount > 0); bool switchedToBulkPaint = false; if (rowIndexTo - rowIndexFrom > DATAGRIDVIEW_bulkPaintThreshold) { // Switch to batch operation - this.inBulkPaintCount++; + inBulkPaintCount++; switchedToBulkPaint = true; } try @@ -26879,7 +26879,7 @@ private void SelectCellRange(int columnIndexFrom, int rowIndexFrom, int columnIn } if (columnIndex != columnIndexTo) { - DataGridViewColumn dataGridViewColumn = this.Columns.GetNextColumn(this.Columns[columnIndex], + DataGridViewColumn dataGridViewColumn = Columns.GetNextColumn(Columns[columnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); @@ -26907,7 +26907,7 @@ private void SelectCellRange(int columnIndexFrom, int rowIndexFrom, int columnIn } if (columnIndex != columnIndexFrom) { - DataGridViewColumn dataGridViewColumn = this.Columns.GetPreviousColumn(this.Columns[columnIndex], + DataGridViewColumn dataGridViewColumn = Columns.GetPreviousColumn(Columns[columnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); @@ -26936,10 +26936,10 @@ private void SelectCellRange(int columnIndexFrom, int rowIndexFrom, int columnIn private void SelectCellUnorderedRange(int columnIndexFrom, int rowIndexFrom, int columnIndexTo, int rowIndexTo, bool select) { - Debug.Assert(this.noSelectionChangeCount > 0); + Debug.Assert(noSelectionChangeCount > 0); int columnIndexFromTmp, rowIndexFromTmp, columnIndexToTmp, rowIndexToTmp; - if (this.Columns.DisplayInOrder(columnIndexFrom, columnIndexTo)) + if (Columns.DisplayInOrder(columnIndexFrom, columnIndexTo)) { columnIndexFromTmp = columnIndexFrom; columnIndexToTmp = columnIndexTo; @@ -26967,27 +26967,27 @@ private void SelectCellUnorderedRange(int columnIndexFrom, int rowIndexFrom, int private void SelectColumnRange(int columnIndexFrom, int columnIndexTo, bool select) { Debug.Assert(columnIndexFrom >= 0 && columnIndexTo >= 0); - Debug.Assert((this.Columns[columnIndexFrom]).DisplayIndex <= (this.Columns[columnIndexTo]).DisplayIndex); - Debug.Assert(this.noSelectionChangeCount > 0); + Debug.Assert((Columns[columnIndexFrom]).DisplayIndex <= (Columns[columnIndexTo]).DisplayIndex); + Debug.Assert(noSelectionChangeCount > 0); int columnIndex = columnIndexFrom; do { if (select) { - if (!this.selectedBandIndexes.Contains(columnIndex)) + if (!selectedBandIndexes.Contains(columnIndex)) { SetSelectedColumnCore(columnIndex, true); } } else { - Debug.Assert(this.selectedBandIndexes.Contains(columnIndex)); + Debug.Assert(selectedBandIndexes.Contains(columnIndex)); SetSelectedColumnCore(columnIndex, false); } if (columnIndex != columnIndexTo) { - DataGridViewColumn dataGridViewColumn = this.Columns.GetNextColumn(this.Columns[columnIndex], + DataGridViewColumn dataGridViewColumn = Columns.GetNextColumn(Columns[columnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); @@ -27000,14 +27000,14 @@ private void SelectColumnRange(int columnIndexFrom, int columnIndexTo, bool sele { if (select) { - if (!this.selectedBandIndexes.Contains(columnIndexTo)) + if (!selectedBandIndexes.Contains(columnIndexTo)) { SetSelectedColumnCore(columnIndexTo, true); } } else { - Debug.Assert(this.selectedBandIndexes.Contains(columnIndexTo)); + Debug.Assert(selectedBandIndexes.Contains(columnIndexTo)); SetSelectedColumnCore(columnIndexTo, false); } } @@ -27017,13 +27017,13 @@ private void SelectRowRange(int rowIndexFrom, int rowIndexTo, bool select) { Debug.Assert(rowIndexFrom >= 0 && rowIndexTo >= 0); Debug.Assert(rowIndexFrom <= rowIndexTo); - Debug.Assert(this.noSelectionChangeCount > 0); + Debug.Assert(noSelectionChangeCount > 0); bool switchedToBulkPaint = false; if (rowIndexTo - rowIndexFrom > DATAGRIDVIEW_bulkPaintThreshold) { // Switch to batch operation - this.inBulkPaintCount++; + inBulkPaintCount++; switchedToBulkPaint = true; } try @@ -27033,9 +27033,9 @@ private void SelectRowRange(int rowIndexFrom, int rowIndexTo, bool select) { for (int rowIndex = rowIndexFrom; rowIndex <= rowIndexTo; rowIndex++) { - if ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) == 0) + if ((Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) == 0) { - Debug.Assert(!this.selectedBandIndexes.Contains(rowIndex)); + Debug.Assert(!selectedBandIndexes.Contains(rowIndex)); SetSelectedRowCore(rowIndex, true); } } @@ -27044,7 +27044,7 @@ private void SelectRowRange(int rowIndexFrom, int rowIndexTo, bool select) { for (int rowIndex = rowIndexTo; rowIndex >= rowIndexFrom; rowIndex--) { - Debug.Assert(this.selectedBandIndexes.Contains(rowIndex)); + Debug.Assert(selectedBandIndexes.Contains(rowIndex)); SetSelectedRowCore(rowIndex, false); } } @@ -27086,26 +27086,26 @@ private bool SetAndSelectCurrentCellAddress(int columnIndex, } else { - if (this.MultiSelect && (this.individualSelectedCells.Count + this.selectedBandIndexes.Count) > 1) + if (MultiSelect && (individualSelectedCells.Count + selectedBandIndexes.Count) > 1) { return true; // Do not discard the multi-selection } - if (this.individualSelectedCells.Count == 1) + if (individualSelectedCells.Count == 1) { - DataGridViewCell dataGridViewCell = this.individualSelectedCells.HeadCell; + DataGridViewCell dataGridViewCell = individualSelectedCells.HeadCell; if (dataGridViewCell.ColumnIndex != columnIndex || dataGridViewCell.RowIndex != rowIndex) { return true; } } - else if (this.selectedBandIndexes.Count == 1) + else if (selectedBandIndexes.Count == 1) { - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: { - if (this.selectedBandIndexes.HeadInt != columnIndex) + if (selectedBandIndexes.HeadInt != columnIndex) { return true; // Do not change a single selection that does not match the new current cell } @@ -27114,7 +27114,7 @@ private bool SetAndSelectCurrentCellAddress(int columnIndex, case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: { - if (this.selectedBandIndexes.HeadInt != rowIndex) + if (selectedBandIndexes.HeadInt != rowIndex) { return true; // Do not change a single selection that does not match the new current cell } @@ -27147,64 +27147,64 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound internal void SetReadOnlyCellCore(int columnIndex, int rowIndex, bool readOnly) { Debug.Assert(columnIndex >= 0 && rowIndex >= 0 && - columnIndex < this.Columns.Count && - rowIndex < this.Rows.Count); + columnIndex < Columns.Count && + rowIndex < Rows.Count); // cell's readonly state changes - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); - DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); + DataGridViewElementStates rowState = Rows.GetRowState(rowIndex); if (IsSharedCellReadOnly(dataGridViewRow.Cells[columnIndex], rowIndex) != readOnly) { - DataGridViewCell dataGridViewCell = this.Rows[rowIndex].Cells[columnIndex]; + DataGridViewCell dataGridViewCell = Rows[rowIndex].Cells[columnIndex]; if (readOnly) { if ((rowState & DataGridViewElementStates.ReadOnly) == 0 && - !this.Columns[columnIndex].ReadOnly) + !Columns[columnIndex].ReadOnly) { - this.individualReadOnlyCells.Add(dataGridViewCell); + individualReadOnlyCells.Add(dataGridViewCell); dataGridViewCell.ReadOnlyInternal = true; } } else { - if (this.individualReadOnlyCells.Contains(dataGridViewCell)) + if (individualReadOnlyCells.Contains(dataGridViewCell)) { - this.individualReadOnlyCells.Remove(dataGridViewCell); + individualReadOnlyCells.Remove(dataGridViewCell); } else { DataGridViewCell dataGridViewCellTmp; - if (this.Columns[columnIndex].ReadOnly) + if (Columns[columnIndex].ReadOnly) { - this.Columns[columnIndex].ReadOnlyInternal = false; + Columns[columnIndex].ReadOnlyInternal = false; // Perf Issue: this unshares all rows! for (int row = 0; row < rowIndex; row++) { - dataGridViewCellTmp = this.Rows[row].Cells[columnIndex]; + dataGridViewCellTmp = Rows[row].Cells[columnIndex]; dataGridViewCellTmp.ReadOnlyInternal = true; - this.individualReadOnlyCells.Add(dataGridViewCellTmp); + individualReadOnlyCells.Add(dataGridViewCellTmp); } - for (int row = rowIndex + 1; row < this.Rows.Count; row++) + for (int row = rowIndex + 1; row < Rows.Count; row++) { - dataGridViewCellTmp = this.Rows[row].Cells[columnIndex]; + dataGridViewCellTmp = Rows[row].Cells[columnIndex]; dataGridViewCellTmp.ReadOnlyInternal = true; - this.individualReadOnlyCells.Add(dataGridViewCellTmp); + individualReadOnlyCells.Add(dataGridViewCellTmp); } } if ((rowState & DataGridViewElementStates.ReadOnly) != 0) { - this.Rows.SetRowState(rowIndex, DataGridViewElementStates.ReadOnly, false); + Rows.SetRowState(rowIndex, DataGridViewElementStates.ReadOnly, false); for (int column = 0; column < columnIndex; column++) { - dataGridViewCellTmp = this.Rows[rowIndex].Cells[column]; + dataGridViewCellTmp = Rows[rowIndex].Cells[column]; dataGridViewCellTmp.ReadOnlyInternal = true; - this.individualReadOnlyCells.Add(dataGridViewCellTmp); + individualReadOnlyCells.Add(dataGridViewCellTmp); } - for (int column = columnIndex + 1; column < this.Columns.Count; column++) + for (int column = columnIndex + 1; column < Columns.Count; column++) { - dataGridViewCellTmp = this.Rows[rowIndex].Cells[column]; + dataGridViewCellTmp = Rows[rowIndex].Cells[column]; dataGridViewCellTmp.ReadOnlyInternal = true; - this.individualReadOnlyCells.Add(dataGridViewCellTmp); + individualReadOnlyCells.Add(dataGridViewCellTmp); } } } @@ -27218,9 +27218,9 @@ internal void SetReadOnlyCellCore(int columnIndex, int rowIndex, bool readOnly) internal void SetReadOnlyColumnCore(int columnIndex, bool readOnly) { - Debug.Assert(columnIndex >= 0 && columnIndex < this.Columns.Count); + Debug.Assert(columnIndex >= 0 && columnIndex < Columns.Count); - if (this.Columns[columnIndex].ReadOnly != readOnly) + if (Columns[columnIndex].ReadOnly != readOnly) { // ReadOnly state of entire column changes if (readOnly) @@ -27229,19 +27229,19 @@ internal void SetReadOnlyColumnCore(int columnIndex, bool readOnly) // remove individual read-only cells of this column try { - this.dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange] = true; + dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange] = true; RemoveIndividualReadOnlyCellsInColumn(columnIndex); } finally { - this.dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange] = false; + dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange] = false; } - this.Columns[columnIndex].ReadOnlyInternal = true; + Columns[columnIndex].ReadOnlyInternal = true; } else { // column is made read-write - this.Columns[columnIndex].ReadOnlyInternal = false; + Columns[columnIndex].ReadOnlyInternal = false; } } else if (!readOnly) @@ -27253,9 +27253,9 @@ internal void SetReadOnlyColumnCore(int columnIndex, bool readOnly) internal void SetReadOnlyRowCore(int rowIndex, bool readOnly) { - Debug.Assert(rowIndex >= 0 && rowIndex < this.Rows.Count); + Debug.Assert(rowIndex >= 0 && rowIndex < Rows.Count); - DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); + DataGridViewElementStates rowState = Rows.GetRowState(rowIndex); if (((rowState & DataGridViewElementStates.ReadOnly) != 0) != readOnly) { // ReadOnly state of entire row changes @@ -27265,19 +27265,19 @@ internal void SetReadOnlyRowCore(int rowIndex, bool readOnly) // first remove individual read-only cells of this row try { - this.dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange] = true; + dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange] = true; RemoveIndividualReadOnlyCellsInRow(rowIndex); } finally { - this.dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange] = false; + dataGridViewOper[DATAGRIDVIEWOPER_inReadOnlyChange] = false; } - this.Rows.SetRowState(rowIndex, DataGridViewElementStates.ReadOnly, true); + Rows.SetRowState(rowIndex, DataGridViewElementStates.ReadOnly, true); } else { // row is made read-write - this.Rows.SetRowState(rowIndex, DataGridViewElementStates.ReadOnly, false); + Rows.SetRowState(rowIndex, DataGridViewElementStates.ReadOnly, false); } } else if (!readOnly) @@ -27292,28 +27292,28 @@ internal void SetReadOnlyRowCore(int rowIndex, bool readOnly) ] protected virtual void SetSelectedCellCore(int columnIndex, int rowIndex, bool selected) { - if (columnIndex < 0 || columnIndex >= this.Columns.Count) + if (columnIndex < 0 || columnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException(nameof(columnIndex)); } - if (rowIndex < 0 || rowIndex >= this.Rows.Count) + if (rowIndex < 0 || rowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } // cell selection changes - DataGridViewRow dataGridViewRow = this.Rows.SharedRow(rowIndex); - DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); + DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); + DataGridViewElementStates rowState = Rows.GetRowState(rowIndex); if (IsSharedCellSelected(dataGridViewRow.Cells[columnIndex], rowIndex) != selected) { - DataGridViewCell dataGridViewCell = this.Rows[rowIndex].Cells[columnIndex]; + DataGridViewCell dataGridViewCell = Rows[rowIndex].Cells[columnIndex]; if (selected) { if ((rowState & DataGridViewElementStates.Selected) == 0 && - !this.Columns[columnIndex].Selected) + !Columns[columnIndex].Selected) { - this.individualSelectedCells.Add(dataGridViewCell); + individualSelectedCells.Add(dataGridViewCell); dataGridViewCell.SelectedInternal = true; } } @@ -27321,37 +27321,37 @@ protected virtual void SetSelectedCellCore(int columnIndex, int rowIndex, bool s { if ((dataGridViewCell.State & DataGridViewElementStates.Selected) != 0) { - Debug.Assert(this.individualSelectedCells.Contains(dataGridViewCell)); - this.individualSelectedCells.Remove(dataGridViewCell); + Debug.Assert(individualSelectedCells.Contains(dataGridViewCell)); + individualSelectedCells.Remove(dataGridViewCell); } else { DataGridViewCell dataGridViewCellTmp; bool switchedToBulkPaint = false; - if (this.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) + if (SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect) { - if (this.Rows.Count > DATAGRIDVIEW_bulkPaintThreshold) + if (Rows.Count > DATAGRIDVIEW_bulkPaintThreshold) { - this.inBulkPaintCount++; + inBulkPaintCount++; switchedToBulkPaint = true; } try { - Debug.Assert(this.selectedBandIndexes.Contains(columnIndex)); - this.selectedBandIndexes.Remove(columnIndex); - this.Columns[columnIndex].SelectedInternal = false; + Debug.Assert(selectedBandIndexes.Contains(columnIndex)); + selectedBandIndexes.Remove(columnIndex); + Columns[columnIndex].SelectedInternal = false; // Perf Issue: this unshares all rows! for (int row = 0; row < rowIndex; row++) { - dataGridViewCellTmp = this.Rows[row].Cells[columnIndex]; + dataGridViewCellTmp = Rows[row].Cells[columnIndex]; dataGridViewCellTmp.SelectedInternal = true; - this.individualSelectedCells.Add(dataGridViewCellTmp); + individualSelectedCells.Add(dataGridViewCellTmp); } - for (int row = rowIndex + 1; row < this.Rows.Count; row++) + for (int row = rowIndex + 1; row < Rows.Count; row++) { - dataGridViewCellTmp = this.Rows[row].Cells[columnIndex]; + dataGridViewCellTmp = Rows[row].Cells[columnIndex]; dataGridViewCellTmp.SelectedInternal = true; - this.individualSelectedCells.Add(dataGridViewCellTmp); + individualSelectedCells.Add(dataGridViewCellTmp); } } finally @@ -27362,29 +27362,29 @@ protected virtual void SetSelectedCellCore(int columnIndex, int rowIndex, bool s } } } - else if (this.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) + else if (SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) { - if (this.Columns.Count > DATAGRIDVIEW_bulkPaintThreshold) + if (Columns.Count > DATAGRIDVIEW_bulkPaintThreshold) { - this.inBulkPaintCount++; + inBulkPaintCount++; switchedToBulkPaint = true; } try { - Debug.Assert(this.selectedBandIndexes.Contains(rowIndex)); - this.selectedBandIndexes.Remove(rowIndex); - this.Rows.SetRowState(rowIndex, DataGridViewElementStates.Selected, false); + Debug.Assert(selectedBandIndexes.Contains(rowIndex)); + selectedBandIndexes.Remove(rowIndex); + Rows.SetRowState(rowIndex, DataGridViewElementStates.Selected, false); for (int column = 0; column < columnIndex; column++) { - dataGridViewCellTmp = this.Rows[rowIndex].Cells[column]; + dataGridViewCellTmp = Rows[rowIndex].Cells[column]; dataGridViewCellTmp.SelectedInternal = true; - this.individualSelectedCells.Add(dataGridViewCellTmp); + individualSelectedCells.Add(dataGridViewCellTmp); } - for (int column = columnIndex + 1; column < this.Columns.Count; column++) + for (int column = columnIndex + 1; column < Columns.Count; column++) { - dataGridViewCellTmp = this.Rows[rowIndex].Cells[column]; + dataGridViewCellTmp = Rows[rowIndex].Cells[column]; dataGridViewCellTmp.SelectedInternal = true; - this.individualSelectedCells.Add(dataGridViewCellTmp); + individualSelectedCells.Add(dataGridViewCellTmp); } } finally @@ -27406,10 +27406,10 @@ protected virtual void SetSelectedCellCore(int columnIndex, int rowIndex, bool s internal void SetSelectedCellCoreInternal(int columnIndex, int rowIndex, bool selected) { - if (selected && !this.MultiSelect) + if (selected && !MultiSelect) { - if (!this.Columns[columnIndex].Visible || - (this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Visible) == 0) + if (!Columns[columnIndex].Visible || + (Rows.GetRowState(rowIndex) & DataGridViewElementStates.Visible) == 0) { throw new InvalidOperationException(string.Format(SR.DataGridView_CurrentCellCannotBeInvisible)); } @@ -27424,16 +27424,16 @@ internal void SetSelectedCellCoreInternal(int columnIndex, int rowIndex, bool se } } - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: { - if (selected && !this.MultiSelect) + if (selected && !MultiSelect) { - Debug.Assert(this.individualSelectedCells.Count <= 1); + Debug.Assert(individualSelectedCells.Count <= 1); RemoveIndividuallySelectedCells(); } SetSelectedCellCore(columnIndex, rowIndex, selected); @@ -27444,16 +27444,16 @@ internal void SetSelectedCellCoreInternal(int columnIndex, int rowIndex, bool se { if (selected) { - if (!this.MultiSelect) + if (!MultiSelect) { - Debug.Assert(this.selectedBandIndexes.Count <= 1); + Debug.Assert(selectedBandIndexes.Count <= 1); int bandIndex = 0; - while (bandIndex < this.selectedBandIndexes.Count) + while (bandIndex < selectedBandIndexes.Count) { - if (this.selectedBandIndexes[bandIndex] != columnIndex) + if (selectedBandIndexes[bandIndex] != columnIndex) { // deselect currently selected column - SetSelectedColumnCore(this.selectedBandIndexes[bandIndex], false); + SetSelectedColumnCore(selectedBandIndexes[bandIndex], false); } else { @@ -27461,14 +27461,14 @@ internal void SetSelectedCellCoreInternal(int columnIndex, int rowIndex, bool se } } } - if (!this.selectedBandIndexes.Contains(columnIndex)) + if (!selectedBandIndexes.Contains(columnIndex)) { SetSelectedColumnCore(columnIndex, true); } } else { - if (this.selectedBandIndexes.Contains(columnIndex)) + if (selectedBandIndexes.Contains(columnIndex)) { SetSelectedColumnCore(columnIndex, false); } @@ -27480,12 +27480,12 @@ internal void SetSelectedCellCoreInternal(int columnIndex, int rowIndex, bool se { if (selected) { - if (!this.MultiSelect) + if (!MultiSelect) { - Debug.Assert(this.selectedBandIndexes.Count <= 1); - if (this.selectedBandIndexes.Count > 0) + Debug.Assert(selectedBandIndexes.Count <= 1); + if (selectedBandIndexes.Count > 0) { - SetSelectedColumnCore(this.selectedBandIndexes.HeadInt, false); + SetSelectedColumnCore(selectedBandIndexes.HeadInt, false); } else { @@ -27496,12 +27496,12 @@ internal void SetSelectedCellCoreInternal(int columnIndex, int rowIndex, bool se } else { - if (!this.MultiSelect) + if (!MultiSelect) { - Debug.Assert(this.selectedBandIndexes.Count <= 1); - if (this.selectedBandIndexes.Count > 0) + Debug.Assert(selectedBandIndexes.Count <= 1); + if (selectedBandIndexes.Count > 0) { - SetSelectedColumnCore(this.selectedBandIndexes.HeadInt, false); + SetSelectedColumnCore(selectedBandIndexes.HeadInt, false); } else { @@ -27520,16 +27520,16 @@ internal void SetSelectedCellCoreInternal(int columnIndex, int rowIndex, bool se { if (selected) { - if (!this.MultiSelect) + if (!MultiSelect) { - Debug.Assert(this.selectedBandIndexes.Count <= 1); + Debug.Assert(selectedBandIndexes.Count <= 1); int bandIndex = 0; - while (bandIndex < this.selectedBandIndexes.Count) + while (bandIndex < selectedBandIndexes.Count) { - if (this.selectedBandIndexes[bandIndex] != rowIndex) + if (selectedBandIndexes[bandIndex] != rowIndex) { // deselect currently selected row - SetSelectedRowCore(this.selectedBandIndexes[bandIndex], false); + SetSelectedRowCore(selectedBandIndexes[bandIndex], false); } else { @@ -27537,19 +27537,19 @@ internal void SetSelectedCellCoreInternal(int columnIndex, int rowIndex, bool se } } } - if ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) == 0) + if ((Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) == 0) { - Debug.Assert(this.selectedBandIndexes.Contains(rowIndex) == - ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) != 0)); + Debug.Assert(selectedBandIndexes.Contains(rowIndex) == + ((Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) != 0)); SetSelectedRowCore(rowIndex, true); } } else { - if ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) != 0) + if ((Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) != 0) { - Debug.Assert(this.selectedBandIndexes.Contains(rowIndex) == - ((this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) != 0)); + Debug.Assert(selectedBandIndexes.Contains(rowIndex) == + ((Rows.GetRowState(rowIndex) & DataGridViewElementStates.Selected) != 0)); SetSelectedRowCore(rowIndex, false); } } @@ -27560,12 +27560,12 @@ internal void SetSelectedCellCoreInternal(int columnIndex, int rowIndex, bool se { if (selected) { - if (!this.MultiSelect) + if (!MultiSelect) { - Debug.Assert(this.selectedBandIndexes.Count <= 1); - if (this.selectedBandIndexes.Count > 0) + Debug.Assert(selectedBandIndexes.Count <= 1); + if (selectedBandIndexes.Count > 0) { - SetSelectedRowCore(this.selectedBandIndexes.HeadInt, false); + SetSelectedRowCore(selectedBandIndexes.HeadInt, false); } else { @@ -27576,12 +27576,12 @@ internal void SetSelectedCellCoreInternal(int columnIndex, int rowIndex, bool se } else { - if (!this.MultiSelect) + if (!MultiSelect) { - Debug.Assert(this.selectedBandIndexes.Count <= 1); - if (this.selectedBandIndexes.Count > 0) + Debug.Assert(selectedBandIndexes.Count <= 1); + if (selectedBandIndexes.Count > 0) { - SetSelectedRowCore(this.selectedBandIndexes.HeadInt, false); + SetSelectedRowCore(selectedBandIndexes.HeadInt, false); } else { @@ -27599,10 +27599,10 @@ internal void SetSelectedCellCoreInternal(int columnIndex, int rowIndex, bool se } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; } - if (selected && !this.MultiSelect) + if (selected && !MultiSelect) { bool success = SetCurrentCellAddressCore(columnIndex, rowIndex, true, false, true); Debug.Assert(success); @@ -27611,15 +27611,15 @@ internal void SetSelectedCellCoreInternal(int columnIndex, int rowIndex, bool se protected virtual void SetSelectedColumnCore(int columnIndex, bool selected) { - if (columnIndex < 0 || columnIndex >= this.Columns.Count) + if (columnIndex < 0 || columnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException(nameof(columnIndex)); } - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - if (this.Columns[columnIndex].Selected != selected) + if (Columns[columnIndex].Selected != selected) { // selection of entire column changes if (selected) @@ -27627,16 +27627,16 @@ protected virtual void SetSelectedColumnCore(int columnIndex, bool selected) // column is selected // remove individually selected cells of this column RemoveIndividuallySelectedCellsInColumn(columnIndex); - this.Columns[columnIndex].SelectedInternal = true; - Debug.Assert(!this.selectedBandIndexes.Contains(columnIndex)); - this.selectedBandIndexes.Add(columnIndex); + Columns[columnIndex].SelectedInternal = true; + Debug.Assert(!selectedBandIndexes.Contains(columnIndex)); + selectedBandIndexes.Add(columnIndex); } else { // column is deselected - Debug.Assert(this.selectedBandIndexes.Contains(columnIndex)); - this.Columns[columnIndex].SelectedInternal = false; - this.selectedBandIndexes.Remove(columnIndex); + Debug.Assert(selectedBandIndexes.Contains(columnIndex)); + Columns[columnIndex].SelectedInternal = false; + selectedBandIndexes.Remove(columnIndex); } } else if (!selected) @@ -27647,22 +27647,22 @@ protected virtual void SetSelectedColumnCore(int columnIndex, bool selected) } finally { - Debug.Assert(this.MultiSelect || this.selectedBandIndexes.Count <= 1); - this.NoSelectionChangeCount--; + Debug.Assert(MultiSelect || selectedBandIndexes.Count <= 1); + NoSelectionChangeCount--; } } internal void SetSelectedColumnCoreInternal(int columnIndex, bool selected) { - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - if (!this.MultiSelect) + if (!MultiSelect) { - Debug.Assert(this.selectedBandIndexes.Count <= 1); - if (this.selectedBandIndexes.Count > 0) + Debug.Assert(selectedBandIndexes.Count <= 1); + if (selectedBandIndexes.Count > 0) { - int columnIndexSelected = this.selectedBandIndexes.HeadInt; + int columnIndexSelected = selectedBandIndexes.HeadInt; if (columnIndexSelected != columnIndex) { SetSelectedColumnCore(columnIndexSelected, false); @@ -27673,13 +27673,13 @@ internal void SetSelectedColumnCoreInternal(int columnIndex, bool selected) } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; } } private void SetSelectedElementCore(int columnIndex, int rowIndex, bool selected) { - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: { @@ -27725,15 +27725,15 @@ private void SetSelectedElementCore(int columnIndex, int rowIndex, bool selected protected virtual void SetSelectedRowCore(int rowIndex, bool selected) { - if (rowIndex < 0 || rowIndex >= this.Rows.Count) + if (rowIndex < 0 || rowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - DataGridViewElementStates rowState = this.Rows.GetRowState(rowIndex); + DataGridViewElementStates rowState = Rows.GetRowState(rowIndex); if (((rowState & DataGridViewElementStates.Selected) != 0) != selected) { // selection of entire row changes @@ -27742,16 +27742,16 @@ protected virtual void SetSelectedRowCore(int rowIndex, bool selected) // row is selected // first remove individually selected cells of this row RemoveIndividuallySelectedCellsInRow(rowIndex); - Debug.Assert(!this.selectedBandIndexes.Contains(rowIndex)); - this.selectedBandIndexes.Add(rowIndex); - this.Rows.SetRowState(rowIndex, DataGridViewElementStates.Selected, true); + Debug.Assert(!selectedBandIndexes.Contains(rowIndex)); + selectedBandIndexes.Add(rowIndex); + Rows.SetRowState(rowIndex, DataGridViewElementStates.Selected, true); } else { // row is deselected - Debug.Assert(this.selectedBandIndexes.Contains(rowIndex)); - this.selectedBandIndexes.Remove(rowIndex); - this.Rows.SetRowState(rowIndex, DataGridViewElementStates.Selected, false); + Debug.Assert(selectedBandIndexes.Contains(rowIndex)); + selectedBandIndexes.Remove(rowIndex); + Rows.SetRowState(rowIndex, DataGridViewElementStates.Selected, false); } } else if (!selected) @@ -27762,22 +27762,22 @@ protected virtual void SetSelectedRowCore(int rowIndex, bool selected) } finally { - Debug.Assert(this.MultiSelect || this.selectedBandIndexes.Count <= 1); - this.NoSelectionChangeCount--; + Debug.Assert(MultiSelect || selectedBandIndexes.Count <= 1); + NoSelectionChangeCount--; } } internal void SetSelectedRowCoreInternal(int rowIndex, bool selected) { - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - if (!this.MultiSelect) + if (!MultiSelect) { - Debug.Assert(this.selectedBandIndexes.Count <= 1); - if (this.selectedBandIndexes.Count > 0) + Debug.Assert(selectedBandIndexes.Count <= 1); + if (selectedBandIndexes.Count > 0) { - int rowIndexSelected = this.selectedBandIndexes.HeadInt; + int rowIndexSelected = selectedBandIndexes.HeadInt; if (rowIndexSelected != rowIndex) { SetSelectedRowCore(rowIndexSelected, false); @@ -27788,35 +27788,35 @@ internal void SetSelectedRowCoreInternal(int rowIndex, bool selected) } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; } } private bool ShouldSerializeAlternatingRowsDefaultCellStyle() { DataGridViewCellStyle defaultStyle = new DataGridViewCellStyle(); - return !this.AlternatingRowsDefaultCellStyle.Equals(defaultStyle); + return !AlternatingRowsDefaultCellStyle.Equals(defaultStyle); } private bool ShouldSerializeColumnHeadersDefaultCellStyle() { - return !this.ColumnHeadersDefaultCellStyle.Equals(this.DefaultColumnHeadersDefaultCellStyle); + return !ColumnHeadersDefaultCellStyle.Equals(DefaultColumnHeadersDefaultCellStyle); } private bool ShouldSerializeDefaultCellStyle() { - return !this.DefaultCellStyle.Equals(this.DefaultDefaultCellStyle); + return !DefaultCellStyle.Equals(DefaultDefaultCellStyle); } private bool ShouldSerializeRowHeadersDefaultCellStyle() { - return !this.RowHeadersDefaultCellStyle.Equals(this.DefaultRowHeadersDefaultCellStyle); + return !RowHeadersDefaultCellStyle.Equals(DefaultRowHeadersDefaultCellStyle); } private bool ShouldSerializeRowsDefaultCellStyle() { DataGridViewCellStyle defaultStyle = new DataGridViewCellStyle(); - return !this.RowsDefaultCellStyle.Equals(defaultStyle); + return !RowsDefaultCellStyle.Equals(defaultStyle); } public virtual void Sort(DataGridViewColumn dataGridViewColumn, ListSortDirection direction) @@ -27836,7 +27836,7 @@ public virtual void Sort(DataGridViewColumn dataGridViewColumn, ListSortDirectio throw new ArgumentException(string.Format(SR.DataGridView_ColumnDoesNotBelongToDataGridView)); } - if (this.VirtualMode && !dataGridViewColumn.IsDataBound) + if (VirtualMode && !dataGridViewColumn.IsDataBound) { throw new InvalidOperationException(string.Format(SR.DataGridView_OperationDisabledInVirtualMode)); } @@ -27851,13 +27851,13 @@ public virtual void Sort(IComparer comparer) throw new ArgumentNullException(nameof(comparer)); } - if (this.VirtualMode) + if (VirtualMode) { throw new InvalidOperationException(string.Format(SR.DataGridView_OperationDisabledInVirtualMode)); } // can't sort a data bound dataGridView control using a comparer - if (this.DataSource != null) + if (DataSource != null) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotUseAComparerToSortDataGridViewWhenDataBound)); } @@ -27867,7 +27867,7 @@ public virtual void Sort(IComparer comparer) private void SortDataBoundDataGridView_PerformCheck(DataGridViewColumn dataGridViewColumn) { - IBindingList ibl = this.dataConnection.List as IBindingList; + IBindingList ibl = dataConnection.List as IBindingList; if (ibl == null) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotSortDataBoundDataGridViewBoundToNonIBindingList)); @@ -27886,13 +27886,13 @@ private void SortDataBoundDataGridView_PerformCheck(DataGridViewColumn dataGridV private void SortInternal(IComparer comparer, DataGridViewColumn dataGridViewColumn, ListSortDirection direction) { - Debug.Assert(!(comparer != null && this.DataSource != null)); + Debug.Assert(!(comparer != null && DataSource != null)); Debug.Assert(direction == ListSortDirection.Ascending || direction == ListSortDirection.Descending); // Exit editing mode if needed - this.ptCurrentCellCache.X = this.ptCurrentCell.X; - this.ptCurrentCellCache.Y = this.ptCurrentCell.Y; - this.dataGridViewOper[DATAGRIDVIEWOPER_inSort] = true; + ptCurrentCellCache.X = ptCurrentCell.X; + ptCurrentCellCache.Y = ptCurrentCell.Y; + dataGridViewOper[DATAGRIDVIEWOPER_inSort] = true; try { if (!SetCurrentCellAddressCore(-1, -1, true, true, false)) @@ -27902,59 +27902,59 @@ private void SortInternal(IComparer comparer, DataGridViewColumn dataGridViewCol return; } - int firstDisplayedScrollingRowCache = this.displayedBandsInfo.FirstDisplayedScrollingRow; - int visibleFrozenRows = this.Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); - if (visibleFrozenRows > 0 && this.DataSource == null) + int firstDisplayedScrollingRowCache = displayedBandsInfo.FirstDisplayedScrollingRow; + int visibleFrozenRows = Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + if (visibleFrozenRows > 0 && DataSource == null) { - int rowVFIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int rowVFIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); Debug.Assert(rowVFIndex != -1); - this.Rows.SetRowState(rowVFIndex, DataGridViewElementStates.Frozen, false); - Debug.Assert(0 == this.Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)); + Rows.SetRowState(rowVFIndex, DataGridViewElementStates.Frozen, false); + Debug.Assert(0 == Rows.GetRowCount(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)); } - if (this.sortedColumn != null && - this.sortedColumn.SortMode == DataGridViewColumnSortMode.Automatic && - this.sortedColumn.HasHeaderCell) + if (sortedColumn != null && + sortedColumn.SortMode == DataGridViewColumnSortMode.Automatic && + sortedColumn.HasHeaderCell) { - this.sortedColumn.HeaderCell.SortGlyphDirection = SortOrder.None; + sortedColumn.HeaderCell.SortGlyphDirection = SortOrder.None; } if (comparer == null) { Debug.Assert(dataGridViewColumn != null); - this.sortedColumn = dataGridViewColumn; - this.sortOrder = (direction == ListSortDirection.Ascending) ? SortOrder.Ascending : SortOrder.Descending; + sortedColumn = dataGridViewColumn; + sortOrder = (direction == ListSortDirection.Ascending) ? SortOrder.Ascending : SortOrder.Descending; if (dataGridViewColumn.SortMode == DataGridViewColumnSortMode.Automatic && dataGridViewColumn.HasHeaderCell) { - dataGridViewColumn.HeaderCell.SortGlyphDirection = this.sortOrder; + dataGridViewColumn.HeaderCell.SortGlyphDirection = sortOrder; } } else { - this.sortedColumn = null; - this.sortOrder = SortOrder.None; + sortedColumn = null; + sortOrder = SortOrder.None; } - if (this.DataSource == null) + if (DataSource == null) { // Displayed rows may end up all spread out in the final layout. // So we simply reset their displayed state before the sort. UpdateRowsDisplayedState(false /*displayed*/); - this.Rows.Sort(comparer, direction == ListSortDirection.Ascending); + Rows.Sort(comparer, direction == ListSortDirection.Ascending); } else { SortDataBoundDataGridView_PerformCheck(dataGridViewColumn); // the check passed, do the sorting - this.dataConnection.Sort(dataGridViewColumn, direction); + dataConnection.Sort(dataGridViewColumn, direction); } - if (this.ptCurrentCellCache.X != -1) + if (ptCurrentCellCache.X != -1) { - if (!IsInnerCellOutOfBounds(this.ptCurrentCellCache.X, this.ptCurrentCellCache.Y)) + if (!IsInnerCellOutOfBounds(ptCurrentCellCache.X, ptCurrentCellCache.Y)) { - SetAndSelectCurrentCellAddress(this.ptCurrentCellCache.X, - this.ptCurrentCellCache.Y, + SetAndSelectCurrentCellAddress(ptCurrentCellCache.X, + ptCurrentCellCache.Y, true, false, false, @@ -27964,29 +27964,29 @@ private void SortInternal(IComparer comparer, DataGridViewColumn dataGridViewCol } if (visibleFrozenRows > 0) { - int rowVIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + int rowVIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); Debug.Assert(rowVIndex != -1); while (visibleFrozenRows > 1) { - rowVIndex = this.Rows.GetNextRow(rowVIndex, DataGridViewElementStates.Visible); + rowVIndex = Rows.GetNextRow(rowVIndex, DataGridViewElementStates.Visible); Debug.Assert(rowVIndex != -1); visibleFrozenRows--; } - this.Rows.SetRowState(rowVIndex, DataGridViewElementStates.Frozen, true); + Rows.SetRowState(rowVIndex, DataGridViewElementStates.Frozen, true); } - this.displayedBandsInfo.FirstDisplayedScrollingRow = firstDisplayedScrollingRowCache; + displayedBandsInfo.FirstDisplayedScrollingRow = firstDisplayedScrollingRowCache; } finally { - Debug.Assert(this.dataGridViewOper[DATAGRIDVIEWOPER_inSort]); - this.dataGridViewOper[DATAGRIDVIEWOPER_inSort] = false; + Debug.Assert(dataGridViewOper[DATAGRIDVIEWOPER_inSort]); + dataGridViewOper[DATAGRIDVIEWOPER_inSort] = false; } // Same effect as changing a top level cell style OnGlobalAutoSize(); - if (this.DataSource == null) + if (DataSource == null) { // Ensure that the Displayed states get set properly because they were wiped out by UpdateRowsDisplayedState above. - this.displayedBandsInfo.EnsureDirtyState(); + displayedBandsInfo.EnsureDirtyState(); } ResetUIState(false /*useRowShortcut*/, false /*computeVisibleRows*/); OnSorted(EventArgs.Empty); @@ -27997,48 +27997,48 @@ private void SortInternal(IComparer comparer, DataGridViewColumn dataGridViewCol internal void SwapSortedRows(int rowIndex1, int rowIndex2) { - Debug.Assert(rowIndex1 != this.newRowIndex); - Debug.Assert(rowIndex2 != this.newRowIndex); + Debug.Assert(rowIndex1 != newRowIndex); + Debug.Assert(rowIndex2 != newRowIndex); if (rowIndex1 == rowIndex2) { return; } // Follow the move of the old current cell - if (rowIndex1 == this.ptCurrentCellCache.Y) + if (rowIndex1 == ptCurrentCellCache.Y) { - this.ptCurrentCellCache.Y = rowIndex2; + ptCurrentCellCache.Y = rowIndex2; } - else if (rowIndex2 == this.ptCurrentCellCache.Y) + else if (rowIndex2 == ptCurrentCellCache.Y) { - this.ptCurrentCellCache.Y = rowIndex1; + ptCurrentCellCache.Y = rowIndex1; } - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.FullRowSelect: case DataGridViewSelectionMode.RowHeaderSelect: - int row1Selected = this.selectedBandIndexes.IndexOf(rowIndex1); - int row2Selected = this.selectedBandIndexes.IndexOf(rowIndex2); + int row1Selected = selectedBandIndexes.IndexOf(rowIndex1); + int row2Selected = selectedBandIndexes.IndexOf(rowIndex2); if (row1Selected != -1 && row2Selected == -1) { - this.selectedBandIndexes[row1Selected] = rowIndex2; + selectedBandIndexes[row1Selected] = rowIndex2; } else if (row1Selected == -1 && row2Selected != -1) { - this.selectedBandIndexes[row2Selected] = rowIndex1; + selectedBandIndexes[row2Selected] = rowIndex1; } - if (this.selectedBandSnapshotIndexes != null) + if (selectedBandSnapshotIndexes != null) { - row1Selected = this.selectedBandSnapshotIndexes.IndexOf(rowIndex1); - row2Selected = this.selectedBandSnapshotIndexes.IndexOf(rowIndex2); + row1Selected = selectedBandSnapshotIndexes.IndexOf(rowIndex1); + row2Selected = selectedBandSnapshotIndexes.IndexOf(rowIndex2); if (row1Selected != -1 && row2Selected == -1) { - this.selectedBandSnapshotIndexes[row1Selected] = rowIndex2; + selectedBandSnapshotIndexes[row1Selected] = rowIndex2; } else if (row1Selected == -1 && row2Selected != -1) { - this.selectedBandSnapshotIndexes[row2Selected] = rowIndex1; + selectedBandSnapshotIndexes[row2Selected] = rowIndex1; } } break; @@ -28047,7 +28047,7 @@ internal void SwapSortedRows(int rowIndex1, int rowIndex2) private void DataGridViewHScrolled(object sender, ScrollEventArgs se) { - if (!this.Enabled) + if (!Enabled) { return; } @@ -28090,17 +28090,17 @@ private void DataGridViewHScrolled(object sender, ScrollEventArgs se) { int dCols = (se.Type == ScrollEventType.SmallIncrement) ? 1 : -1; ScrollColumns(dCols); - se.NewValue = this.HorizontalOffset; + se.NewValue = HorizontalOffset; } else if (se.Type != ScrollEventType.EndScroll) { - this.HorizontalOffset = se.NewValue; + HorizontalOffset = se.NewValue; } } private void DataGridViewVScrolled(object sender, ScrollEventArgs se) { - if (!this.Enabled) + if (!Enabled) { return; } @@ -28138,56 +28138,56 @@ private void DataGridViewVScrolled(object sender, ScrollEventArgs se) */ - int totalVisibleFrozenHeight = this.Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + int totalVisibleFrozenHeight = Rows.GetRowsHeight(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); switch (se.Type) { case ScrollEventType.SmallIncrement: { // Making sure that when the last visible scrolling row is taller than the data area, it does not get scrolled off screen - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0); - if (this.vertScrollBar.Value + this.Rows.SharedRow(this.displayedBandsInfo.FirstDisplayedScrollingRow).GetHeight(this.displayedBandsInfo.FirstDisplayedScrollingRow) <= - this.vertScrollBar.Maximum - ComputeHeightOfFittingTrailingScrollingRows(totalVisibleFrozenHeight)) + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingRow >= 0); + if (vertScrollBar.Value + Rows.SharedRow(displayedBandsInfo.FirstDisplayedScrollingRow).GetHeight(displayedBandsInfo.FirstDisplayedScrollingRow) <= + vertScrollBar.Maximum - ComputeHeightOfFittingTrailingScrollingRows(totalVisibleFrozenHeight)) { ScrollRowsByCount(1, ScrollEventType.SmallIncrement); } - se.NewValue = this.VerticalOffset; + se.NewValue = VerticalOffset; break; } case ScrollEventType.SmallDecrement: { - if (this.vertScrollBar.Value != this.vertScrollBar.Minimum) + if (vertScrollBar.Value != vertScrollBar.Minimum) { ScrollRowsByCount(-1, ScrollEventType.SmallDecrement); } - se.NewValue = this.VerticalOffset; + se.NewValue = VerticalOffset; break; } case ScrollEventType.LargeIncrement: { - Debug.Assert(this.displayedBandsInfo.FirstDisplayedScrollingRow >= 0); - int firstDisplayedScrollingRowHeight = this.Rows.SharedRow(this.displayedBandsInfo.FirstDisplayedScrollingRow).GetHeight(this.displayedBandsInfo.FirstDisplayedScrollingRow); - this.VerticalOffset += Math.Max(firstDisplayedScrollingRowHeight, this.vertScrollBar.LargeChange); - se.NewValue = this.VerticalOffset; + Debug.Assert(displayedBandsInfo.FirstDisplayedScrollingRow >= 0); + int firstDisplayedScrollingRowHeight = Rows.SharedRow(displayedBandsInfo.FirstDisplayedScrollingRow).GetHeight(displayedBandsInfo.FirstDisplayedScrollingRow); + VerticalOffset += Math.Max(firstDisplayedScrollingRowHeight, vertScrollBar.LargeChange); + se.NewValue = VerticalOffset; break; } case ScrollEventType.LargeDecrement: { - this.VerticalOffset -= this.vertScrollBar.LargeChange; - se.NewValue = this.VerticalOffset; + VerticalOffset -= vertScrollBar.LargeChange; + se.NewValue = VerticalOffset; break; } case ScrollEventType.ThumbTrack: case ScrollEventType.First: case ScrollEventType.Last: { - if (se.NewValue >= this.vertScrollBar.Maximum - this.vertScrollBar.LargeChange) + if (se.NewValue >= vertScrollBar.Maximum - vertScrollBar.LargeChange) { // Need to display the last scrolling row - this.VerticalOffset = this.vertScrollBar.Maximum - ComputeHeightOfFittingTrailingScrollingRows(totalVisibleFrozenHeight); + VerticalOffset = vertScrollBar.Maximum - ComputeHeightOfFittingTrailingScrollingRows(totalVisibleFrozenHeight); } else { - this.VerticalOffset = se.NewValue; + VerticalOffset = se.NewValue; } break; } @@ -28197,17 +28197,17 @@ private void DataGridViewVScrolled(object sender, ScrollEventArgs se) private bool TabToNextCell() { bool success; - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); int firstVisibleColumnIndex = (dataGridViewColumn == null) ? -1 : dataGridViewColumn.Index; - int firstVisibleRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + int firstVisibleRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); if (firstVisibleColumnIndex == -1 || firstVisibleRowIndex == -1) { return false; } int nextVisibleColumnIndex = -1; - if (this.ptCurrentCell.X != -1) + if (ptCurrentCell.X != -1) { - dataGridViewColumn = this.Columns.GetNextColumn(this.Columns[this.ptCurrentCell.X], + dataGridViewColumn = Columns.GetNextColumn(Columns[ptCurrentCell.X], DataGridViewElementStates.Visible, DataGridViewElementStates.None); if (dataGridViewColumn != null) @@ -28216,16 +28216,16 @@ private bool TabToNextCell() } } int nextVisibleRowIndex = -1; - if (this.ptCurrentCell.Y != -1) + if (ptCurrentCell.Y != -1) { - nextVisibleRowIndex = this.Rows.GetNextRow(this.ptCurrentCell.Y, DataGridViewElementStates.Visible); + nextVisibleRowIndex = Rows.GetNextRow(ptCurrentCell.Y, DataGridViewElementStates.Visible); } int targetRowIndex = -1, targetColumnIndex = -1; - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); } @@ -28238,7 +28238,7 @@ private bool TabToNextCell() } else { - targetRowIndex = this.ptCurrentCell.Y; + targetRowIndex = ptCurrentCell.Y; targetColumnIndex = nextVisibleColumnIndex; } if (!ScrollIntoView(targetColumnIndex, targetRowIndex, true)) @@ -28247,12 +28247,12 @@ private bool TabToNextCell() } } - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: case DataGridViewSelectionMode.RowHeaderSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { if (IsInnerCellOutOfBounds(firstVisibleColumnIndex, firstVisibleRowIndex)) { @@ -28272,7 +28272,7 @@ private bool TabToNextCell() break; case DataGridViewSelectionMode.FullColumnSelect: - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { if (IsColumnOutOfBounds(firstVisibleColumnIndex)) { @@ -28292,7 +28292,7 @@ private bool TabToNextCell() break; case DataGridViewSelectionMode.FullRowSelect: - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { if (IsRowOutOfBounds(firstVisibleRowIndex)) { @@ -28302,7 +28302,7 @@ private bool TabToNextCell() } else { - if (targetRowIndex != this.ptCurrentCell.Y || this.MultiSelect) + if (targetRowIndex != ptCurrentCell.Y || MultiSelect) { if (IsRowOutOfBounds(targetRowIndex)) { @@ -28317,10 +28317,10 @@ private bool TabToNextCell() } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; } - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { success = ScrollIntoView(firstVisibleColumnIndex, firstVisibleRowIndex, false); Debug.Assert(success); @@ -28351,18 +28351,18 @@ private bool TabToPreviousCell() { bool success; - DataGridViewColumn dataGridViewColumn = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + DataGridViewColumn dataGridViewColumn = Columns.GetFirstColumn(DataGridViewElementStates.Visible); int firstVisibleColumnIndex = (dataGridViewColumn == null) ? -1 : dataGridViewColumn.Index; - int firstVisibleRowIndex = this.Rows.GetFirstRow(DataGridViewElementStates.Visible); + int firstVisibleRowIndex = Rows.GetFirstRow(DataGridViewElementStates.Visible); if (firstVisibleColumnIndex == -1 || firstVisibleRowIndex == -1) { return false; } int previousVisibleColumnIndex = -1; - if (this.ptCurrentCell.X != -1) + if (ptCurrentCell.X != -1) { - dataGridViewColumn = this.Columns.GetPreviousColumn(this.Columns[this.ptCurrentCell.X], + dataGridViewColumn = Columns.GetPreviousColumn(Columns[ptCurrentCell.X], DataGridViewElementStates.Visible, DataGridViewElementStates.None); if (dataGridViewColumn != null) @@ -28372,24 +28372,24 @@ private bool TabToPreviousCell() } int previousVisibleRowIndex = -1; - if (this.ptCurrentCell.Y != -1) + if (ptCurrentCell.Y != -1) { - previousVisibleRowIndex = this.Rows.GetPreviousRow(this.ptCurrentCell.Y, DataGridViewElementStates.Visible); + previousVisibleRowIndex = Rows.GetPreviousRow(ptCurrentCell.Y, DataGridViewElementStates.Visible); } - dataGridViewColumn = this.Columns.GetLastColumn(DataGridViewElementStates.Visible, + dataGridViewColumn = Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); int lastVisibleColumnIndex = dataGridViewColumn.Index; - int lastVisibleRowIndex = this.Rows.GetLastRow(DataGridViewElementStates.Visible); + int lastVisibleRowIndex = Rows.GetLastRow(DataGridViewElementStates.Visible); Debug.Assert(lastVisibleRowIndex != -1); int targetRowIndex = -1, targetColumnIndex = -1; - this.noSelectionChangeCount++; + noSelectionChangeCount++; try { - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { ClearSelection(); } @@ -28402,7 +28402,7 @@ private bool TabToPreviousCell() } else { - targetRowIndex = this.ptCurrentCell.Y; + targetRowIndex = ptCurrentCell.Y; targetColumnIndex = previousVisibleColumnIndex; } if (!ScrollIntoView(targetColumnIndex, targetRowIndex, true)) @@ -28411,12 +28411,12 @@ private bool TabToPreviousCell() } } - switch (this.SelectionMode) + switch (SelectionMode) { case DataGridViewSelectionMode.CellSelect: case DataGridViewSelectionMode.RowHeaderSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { if (IsInnerCellOutOfBounds(firstVisibleColumnIndex, firstVisibleRowIndex)) { @@ -28436,7 +28436,7 @@ private bool TabToPreviousCell() break; case DataGridViewSelectionMode.FullColumnSelect: - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { if (IsColumnOutOfBounds(firstVisibleColumnIndex)) { @@ -28456,7 +28456,7 @@ private bool TabToPreviousCell() break; case DataGridViewSelectionMode.FullRowSelect: - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { if (IsRowOutOfBounds(firstVisibleRowIndex)) { @@ -28466,7 +28466,7 @@ private bool TabToPreviousCell() } else { - if (targetRowIndex != this.ptCurrentCell.Y || this.MultiSelect) + if (targetRowIndex != ptCurrentCell.Y || MultiSelect) { if (IsRowOutOfBounds(targetRowIndex)) { @@ -28481,10 +28481,10 @@ private bool TabToPreviousCell() } finally { - this.NoSelectionChangeCount--; + NoSelectionChangeCount--; } - if (this.ptCurrentCell.X == -1) + if (ptCurrentCell.X == -1) { success = ScrollIntoView(firstVisibleColumnIndex, firstVisibleRowIndex, false); Debug.Assert(success); @@ -28514,54 +28514,54 @@ private bool TabToPreviousCell() private void UnwireEditingControlEvents() { - Debug.Assert(this.editingPanel != null); - this.editingPanel.Click -= new System.EventHandler(EditingControls_Click); - this.editingPanel.DoubleClick -= new System.EventHandler(EditingControls_DoubleClick); - this.editingPanel.MouseClick -= new System.Windows.Forms.MouseEventHandler(EditingControls_MouseClick); - this.editingPanel.MouseDoubleClick -= new System.Windows.Forms.MouseEventHandler(EditingControls_MouseDoubleClick); - this.editingPanel.MouseDown -= new System.Windows.Forms.MouseEventHandler(EditingControls_MouseDown); - this.editingPanel.MouseEnter -= new System.EventHandler(EditingControls_MouseEnter); - this.editingPanel.MouseLeave -= new System.EventHandler(EditingControls_MouseLeave); - this.editingPanel.MouseMove -= new System.Windows.Forms.MouseEventHandler(EditingControls_MouseMove); - this.editingPanel.MouseUp -= new System.Windows.Forms.MouseEventHandler(EditingControls_MouseUp); - - Debug.Assert(this.editingControl != null); - this.editingControl.Click -= new System.EventHandler(EditingControls_Click); - this.editingControl.DoubleClick -= new System.EventHandler(EditingControls_DoubleClick); - this.editingControl.MouseClick -= new System.Windows.Forms.MouseEventHandler(EditingControls_MouseClick); - this.editingControl.MouseDoubleClick -= new System.Windows.Forms.MouseEventHandler(EditingControls_MouseDoubleClick); - this.editingControl.MouseDown -= new System.Windows.Forms.MouseEventHandler(EditingControls_MouseDown); - this.editingControl.MouseEnter -= new System.EventHandler(EditingControls_MouseEnter); - this.editingControl.MouseLeave -= new System.EventHandler(EditingControls_MouseLeave); - this.editingControl.MouseMove -= new System.Windows.Forms.MouseEventHandler(EditingControls_MouseMove); - this.editingControl.MouseUp -= new System.Windows.Forms.MouseEventHandler(EditingControls_MouseUp); + Debug.Assert(editingPanel != null); + editingPanel.Click -= new System.EventHandler(EditingControls_Click); + editingPanel.DoubleClick -= new System.EventHandler(EditingControls_DoubleClick); + editingPanel.MouseClick -= new System.Windows.Forms.MouseEventHandler(EditingControls_MouseClick); + editingPanel.MouseDoubleClick -= new System.Windows.Forms.MouseEventHandler(EditingControls_MouseDoubleClick); + editingPanel.MouseDown -= new System.Windows.Forms.MouseEventHandler(EditingControls_MouseDown); + editingPanel.MouseEnter -= new System.EventHandler(EditingControls_MouseEnter); + editingPanel.MouseLeave -= new System.EventHandler(EditingControls_MouseLeave); + editingPanel.MouseMove -= new System.Windows.Forms.MouseEventHandler(EditingControls_MouseMove); + editingPanel.MouseUp -= new System.Windows.Forms.MouseEventHandler(EditingControls_MouseUp); + + Debug.Assert(editingControl != null); + editingControl.Click -= new System.EventHandler(EditingControls_Click); + editingControl.DoubleClick -= new System.EventHandler(EditingControls_DoubleClick); + editingControl.MouseClick -= new System.Windows.Forms.MouseEventHandler(EditingControls_MouseClick); + editingControl.MouseDoubleClick -= new System.Windows.Forms.MouseEventHandler(EditingControls_MouseDoubleClick); + editingControl.MouseDown -= new System.Windows.Forms.MouseEventHandler(EditingControls_MouseDown); + editingControl.MouseEnter -= new System.EventHandler(EditingControls_MouseEnter); + editingControl.MouseLeave -= new System.EventHandler(EditingControls_MouseLeave); + editingControl.MouseMove -= new System.Windows.Forms.MouseEventHandler(EditingControls_MouseMove); + editingControl.MouseUp -= new System.Windows.Forms.MouseEventHandler(EditingControls_MouseUp); } private void UnwireScrollBarsEvents() { - if (this.horizScrollBar != null) + if (horizScrollBar != null) { - this.horizScrollBar.MouseEnter -= new System.EventHandler(ScrollBar_MouseEnter); - this.horizScrollBar.MouseLeave -= new System.EventHandler(ScrollBar_MouseLeave); + horizScrollBar.MouseEnter -= new System.EventHandler(ScrollBar_MouseEnter); + horizScrollBar.MouseLeave -= new System.EventHandler(ScrollBar_MouseLeave); } - if (this.vertScrollBar != null) + if (vertScrollBar != null) { - this.vertScrollBar.MouseEnter -= new System.EventHandler(ScrollBar_MouseEnter); - this.vertScrollBar.MouseLeave -= new System.EventHandler(ScrollBar_MouseLeave); + vertScrollBar.MouseEnter -= new System.EventHandler(ScrollBar_MouseEnter); + vertScrollBar.MouseLeave -= new System.EventHandler(ScrollBar_MouseLeave); } } public void UpdateCellErrorText(int columnIndex, int rowIndex) { - if (columnIndex < -1 || columnIndex >= this.Columns.Count) + if (columnIndex < -1 || columnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException(nameof(columnIndex)); } - if (rowIndex < -1 || rowIndex >= this.Rows.Count) + if (rowIndex < -1 || rowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - if (this.IsHandleCreated) + if (IsHandleCreated) { InvalidateCellPrivate(columnIndex, rowIndex); } @@ -28569,15 +28569,15 @@ public void UpdateCellErrorText(int columnIndex, int rowIndex) public void UpdateCellValue(int columnIndex, int rowIndex) { - if (columnIndex < 0 || columnIndex >= this.Columns.Count) + if (columnIndex < 0 || columnIndex >= Columns.Count) { throw new ArgumentOutOfRangeException(nameof(columnIndex)); } - if (rowIndex < 0 || rowIndex >= this.Rows.Count) + if (rowIndex < 0 || rowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - if (this.IsHandleCreated) + if (IsHandleCreated) { OnCellCommonChange(columnIndex, rowIndex); } @@ -28587,10 +28587,10 @@ private void UpdateColumnsDisplayedState(bool displayed) { // Make sure all displayed frozen columns have their Displayed state set to this.Visible DataGridViewColumn dataGridViewColumnTmp; - int numDisplayedFrozenCols = this.displayedBandsInfo.NumDisplayedFrozenCols; + int numDisplayedFrozenCols = displayedBandsInfo.NumDisplayedFrozenCols; if (numDisplayedFrozenCols > 0) { - dataGridViewColumnTmp = this.Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + dataGridViewColumnTmp = Columns.GetFirstColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); while (numDisplayedFrozenCols > 0) { Debug.Assert(dataGridViewColumnTmp != null); @@ -28599,18 +28599,18 @@ private void UpdateColumnsDisplayedState(bool displayed) dataGridViewColumnTmp.DisplayedInternal = displayed; Debug.Assert(ColumnNeedsDisplayedState(dataGridViewColumnTmp)); } - dataGridViewColumnTmp = this.Columns.GetNextColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen, DataGridViewElementStates.None); + dataGridViewColumnTmp = Columns.GetNextColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen, DataGridViewElementStates.None); numDisplayedFrozenCols--; } } // Make sure all displayed scrolling columns have the Displayed state set to this.Visible - int columnIndexTmp = this.displayedBandsInfo.FirstDisplayedScrollingCol; + int columnIndexTmp = displayedBandsInfo.FirstDisplayedScrollingCol; if (columnIndexTmp != -1) { - int numDisplayedScrollingCols = this.displayedBandsInfo.NumDisplayedScrollingCols; + int numDisplayedScrollingCols = displayedBandsInfo.NumDisplayedScrollingCols; Debug.Assert(numDisplayedScrollingCols > 0); - dataGridViewColumnTmp = this.Columns[columnIndexTmp]; + dataGridViewColumnTmp = Columns[columnIndexTmp]; while (numDisplayedScrollingCols > 0) { Debug.Assert(dataGridViewColumnTmp != null); @@ -28619,7 +28619,7 @@ private void UpdateColumnsDisplayedState(bool displayed) dataGridViewColumnTmp.DisplayedInternal = displayed; Debug.Assert(ColumnNeedsDisplayedState(dataGridViewColumnTmp)); } - dataGridViewColumnTmp = this.Columns.GetNextColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.None); + dataGridViewColumnTmp = Columns.GetNextColumn(dataGridViewColumnTmp, DataGridViewElementStates.Visible, DataGridViewElementStates.None); numDisplayedScrollingCols--; } } @@ -28627,11 +28627,11 @@ private void UpdateColumnsDisplayedState(bool displayed) public void UpdateRowErrorText(int rowIndex) { - if (rowIndex < 0 || rowIndex >= this.Rows.Count) + if (rowIndex < 0 || rowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - if (this.IsHandleCreated && this.layout.RowHeadersVisible) + if (IsHandleCreated && layout.RowHeadersVisible) { InvalidateCellPrivate(-1, rowIndex); } @@ -28639,11 +28639,11 @@ public void UpdateRowErrorText(int rowIndex) public void UpdateRowErrorText(int rowIndexStart, int rowIndexEnd) { - if (rowIndexStart < 0 || rowIndexStart >= this.Rows.Count) + if (rowIndexStart < 0 || rowIndexStart >= Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndexStart)); } - if (rowIndexEnd < 0 || rowIndexEnd >= this.Rows.Count) + if (rowIndexEnd < 0 || rowIndexEnd >= Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndexEnd)); } @@ -28651,7 +28651,7 @@ public void UpdateRowErrorText(int rowIndexStart, int rowIndexEnd) { throw new ArgumentOutOfRangeException(nameof(rowIndexEnd)); } - if (this.IsHandleCreated && this.layout.RowHeadersVisible) + if (IsHandleCreated && layout.RowHeadersVisible) { Rectangle rectUpper = GetCellAdjustedDisplayRectangle(-1, rowIndexStart, true); Rectangle rectLower = GetCellAdjustedDisplayRectangle(-1, rowIndexEnd, true); @@ -28659,7 +28659,7 @@ public void UpdateRowErrorText(int rowIndexStart, int rowIndexEnd) { if (!rectUpper.IsEmpty || !rectLower.IsEmpty) { - Invalidate(this.layout.RowHeaders); + Invalidate(layout.RowHeaders); } } else @@ -28676,39 +28676,39 @@ public void UpdateRowHeightInfo(int rowIndex, bool updateToEnd) private void UpdateRowHeightInfoPrivate(int rowIndex, bool updateToEnd, bool invalidInAdjustFillingColumns) { - if ((updateToEnd && rowIndex < 0) || (!updateToEnd && rowIndex < -1) || rowIndex >= this.Rows.Count) + if ((updateToEnd && rowIndex < 0) || (!updateToEnd && rowIndex < -1) || rowIndex >= Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - this.Rows.InvalidateCachedRowsHeights(); + Rows.InvalidateCachedRowsHeights(); - bool rowVisible = (rowIndex >= 0 && (this.Rows.GetRowState(rowIndex) & DataGridViewElementStates.Visible) != 0); + bool rowVisible = (rowIndex >= 0 && (Rows.GetRowState(rowIndex) & DataGridViewElementStates.Visible) != 0); // don't do any layout logic if the handled was not created already - if (this.IsHandleCreated && (rowIndex == -1 || rowVisible)) + if (IsHandleCreated && (rowIndex == -1 || rowVisible)) { if (updateToEnd) { - int oldFirstVisibleScrollingRow = this.displayedBandsInfo.FirstDisplayedScrollingRow; + int oldFirstVisibleScrollingRow = displayedBandsInfo.FirstDisplayedScrollingRow; - if (this.AutoSize) + if (AutoSize) { - LayoutTransaction.DoLayout(this.ParentInternal, this, PropertyNames.Rows); + LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.Rows); } else { PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, invalidInAdjustFillingColumns, false /*repositionEditingControl*/); } - Rectangle bottomArea = this.layout.Data; - if (this.layout.RowHeadersVisible) + Rectangle bottomArea = layout.Data; + if (layout.RowHeadersVisible) { - bottomArea = Rectangle.Union(bottomArea, this.layout.RowHeaders); + bottomArea = Rectangle.Union(bottomArea, layout.RowHeaders); } - else if (this.SingleVerticalBorderAdded) + else if (SingleVerticalBorderAdded) { - if (!this.RightToLeftInternal) + if (!RightToLeftInternal) { bottomArea.X--; } @@ -28717,17 +28717,17 @@ private void UpdateRowHeightInfoPrivate(int rowIndex, bool updateToEnd, bool inv if (!rowVisible) { - rowIndex = this.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); + rowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible); } if (rowIndex != -1) { - int topEdge = GetRowYFromIndex(oldFirstVisibleScrollingRow == this.displayedBandsInfo.FirstDisplayedScrollingRow ? rowIndex : this.displayedBandsInfo.FirstDisplayedScrollingRow); + int topEdge = GetRowYFromIndex(oldFirstVisibleScrollingRow == displayedBandsInfo.FirstDisplayedScrollingRow ? rowIndex : displayedBandsInfo.FirstDisplayedScrollingRow); bottomArea.Height -= bottomArea.Y - topEdge; bottomArea.Y = topEdge; Invalidate(bottomArea); } - if (this.editingControl != null) + if (editingControl != null) { PositionEditingControl(true /*setLocation*/, true /*setSize*/, false /*setFocus*/); } @@ -28736,9 +28736,9 @@ private void UpdateRowHeightInfoPrivate(int rowIndex, bool updateToEnd, bool inv { if (rowIndex == -1) { - if (this.AutoSize) + if (AutoSize) { - LayoutTransaction.DoLayout(this.ParentInternal, this, PropertyNames.Rows); + LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.Rows); } else { @@ -28749,13 +28749,13 @@ private void UpdateRowHeightInfoPrivate(int rowIndex, bool updateToEnd, bool inv else { Debug.Assert(rowVisible); - int oldFirstVisibleScrollingRow = this.displayedBandsInfo.FirstDisplayedScrollingRow; + int oldFirstVisibleScrollingRow = displayedBandsInfo.FirstDisplayedScrollingRow; - if (this.inBulkLayoutCount == 0) + if (inBulkLayoutCount == 0) { - if (this.AutoSize) + if (AutoSize) { - LayoutTransaction.DoLayout(this.ParentInternal, this, PropertyNames.Rows); + LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.Rows); } else { @@ -28763,31 +28763,31 @@ private void UpdateRowHeightInfoPrivate(int rowIndex, bool updateToEnd, bool inv } } - if (this.inBulkPaintCount == 0) + if (inBulkPaintCount == 0) { - Rectangle bottomArea = this.layout.Data; - if (this.layout.RowHeadersVisible) + Rectangle bottomArea = layout.Data; + if (layout.RowHeadersVisible) { - bottomArea = Rectangle.Union(bottomArea, this.layout.RowHeaders); + bottomArea = Rectangle.Union(bottomArea, layout.RowHeaders); } - else if (this.SingleVerticalBorderAdded) + else if (SingleVerticalBorderAdded) { - if (!this.RightToLeftInternal) + if (!RightToLeftInternal) { bottomArea.X--; } bottomArea.Width++; } - int topEdge = GetRowYFromIndex(oldFirstVisibleScrollingRow == this.displayedBandsInfo.FirstDisplayedScrollingRow ? rowIndex : this.displayedBandsInfo.FirstDisplayedScrollingRow); + int topEdge = GetRowYFromIndex(oldFirstVisibleScrollingRow == displayedBandsInfo.FirstDisplayedScrollingRow ? rowIndex : displayedBandsInfo.FirstDisplayedScrollingRow); bottomArea.Height -= bottomArea.Y - topEdge; bottomArea.Y = topEdge; Invalidate(bottomArea); } } - if (this.editingControl != null) + if (editingControl != null) { - PositionEditingControl(rowIndex == -1 || this.ptCurrentCell.Y != rowIndex, true, false); + PositionEditingControl(rowIndex == -1 || ptCurrentCell.Y != rowIndex, true, false); } } @@ -28798,36 +28798,36 @@ private void UpdateRowHeightInfoPrivate(int rowIndex, bool updateToEnd, bool inv private void UpdateRowsDisplayedState(bool displayed) { // Make sure all displayed frozen rows have their Displayed state set to 'displayed' - int rowIndexTmp, numDisplayedFrozenRows = this.displayedBandsInfo.NumDisplayedFrozenRows; + int rowIndexTmp, numDisplayedFrozenRows = displayedBandsInfo.NumDisplayedFrozenRows; if (numDisplayedFrozenRows > 0) { - rowIndexTmp = this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + rowIndexTmp = Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); while (numDisplayedFrozenRows > 0) { Debug.Assert(rowIndexTmp != -1); - if (((this.Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) == 0) == displayed) + if (((Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) == 0) == displayed) { - this.Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, displayed); + Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, displayed); } - rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + rowIndexTmp = Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); numDisplayedFrozenRows--; } } // Make sure all displayed scrolling rows have their Displayed state set to 'displayed' - rowIndexTmp = this.displayedBandsInfo.FirstDisplayedScrollingRow; + rowIndexTmp = displayedBandsInfo.FirstDisplayedScrollingRow; if (rowIndexTmp > -1) { - int numDisplayedScrollingRows = this.displayedBandsInfo.NumDisplayedScrollingRows; + int numDisplayedScrollingRows = displayedBandsInfo.NumDisplayedScrollingRows; Debug.Assert(numDisplayedScrollingRows > 0); while (numDisplayedScrollingRows > 0) { Debug.Assert(rowIndexTmp != -1); - if (((this.Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) == 0) == displayed) + if (((Rows.GetRowState(rowIndexTmp) & DataGridViewElementStates.Displayed) == 0) == displayed) { - this.Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, displayed); + Rows.SetRowState(rowIndexTmp, DataGridViewElementStates.Displayed, displayed); } - rowIndexTmp = this.Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible); + rowIndexTmp = Rows.GetNextRow(rowIndexTmp, DataGridViewElementStates.Visible); numDisplayedScrollingRows--; } } @@ -28850,15 +28850,15 @@ private void UpdateMouseEnteredCell(HitTestInfo hti, MouseEventArgs e) htiToUse.Type != DataGridViewHitTestType.HorizontalScrollBar && htiToUse.Type != DataGridViewHitTestType.VerticalScrollBar) { - if (this.ptMouseEnteredCell.X != htiToUse.col || this.ptMouseEnteredCell.Y != htiToUse.row) + if (ptMouseEnteredCell.X != htiToUse.col || ptMouseEnteredCell.Y != htiToUse.row) { DataGridViewCellEventArgs dgvce; - if (this.ptMouseEnteredCell.X >= -1 && - this.ptMouseEnteredCell.X < this.Columns.Count && - this.ptMouseEnteredCell.Y >= -1 && - this.ptMouseEnteredCell.Y < this.Rows.Count) + if (ptMouseEnteredCell.X >= -1 && + ptMouseEnteredCell.X < Columns.Count && + ptMouseEnteredCell.Y >= -1 && + ptMouseEnteredCell.Y < Rows.Count) { - dgvce = new DataGridViewCellEventArgs(this.ptMouseEnteredCell.X, this.ptMouseEnteredCell.Y); + dgvce = new DataGridViewCellEventArgs(ptMouseEnteredCell.X, ptMouseEnteredCell.Y); OnCellMouseLeave(dgvce); } dgvce = new DataGridViewCellEventArgs(htiToUse.col, htiToUse.row); @@ -28867,27 +28867,27 @@ private void UpdateMouseEnteredCell(HitTestInfo hti, MouseEventArgs e) if (e != null) { int mouseX = e.X - htiToUse.ColumnX; - if (this.RightToLeftInternal) + if (RightToLeftInternal) { - mouseX += ((htiToUse.col == -1) ? this.RowHeadersWidth : this.Columns[htiToUse.col].Thickness); + mouseX += ((htiToUse.col == -1) ? RowHeadersWidth : Columns[htiToUse.col].Thickness); } DataGridViewCellMouseEventArgs dgvcme = new DataGridViewCellMouseEventArgs(htiToUse.col, htiToUse.row, mouseX, e.Y - htiToUse.RowY, e); OnCellMouseMove(dgvcme); } } - else if (this.ptMouseEnteredCell.X != -2) + else if (ptMouseEnteredCell.X != -2) { - if (this.ptMouseEnteredCell.X >= -1 && - this.ptMouseEnteredCell.X < this.Columns.Count && - this.ptMouseEnteredCell.Y >= -1 && - this.ptMouseEnteredCell.Y < this.Rows.Count) + if (ptMouseEnteredCell.X >= -1 && + ptMouseEnteredCell.X < Columns.Count && + ptMouseEnteredCell.Y >= -1 && + ptMouseEnteredCell.Y < Rows.Count) { - DataGridViewCellEventArgs dgvce = new DataGridViewCellEventArgs(this.ptMouseEnteredCell.X, this.ptMouseEnteredCell.Y); + DataGridViewCellEventArgs dgvce = new DataGridViewCellEventArgs(ptMouseEnteredCell.X, ptMouseEnteredCell.Y); OnCellMouseLeave(dgvce); } else { - this.ptMouseEnteredCell.X = this.ptMouseEnteredCell.Y = -2; + ptMouseEnteredCell.X = ptMouseEnteredCell.Y = -2; } } } @@ -28899,11 +28899,11 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu Debug.Assert(anchorRowIndex >= 0); Debug.Assert(newEdgeColumnIndex >= 0); Debug.Assert(newEdgeRowIndex >= 0); - Debug.Assert(this.noSelectionChangeCount > 0); - if ((this.Columns.DisplayInOrder(anchorColumnIndex, oldEdgeColumnIndex) && - this.Columns.DisplayInOrder(newEdgeColumnIndex, anchorColumnIndex)) || - (this.Columns.DisplayInOrder(oldEdgeColumnIndex, anchorColumnIndex) && - this.Columns.DisplayInOrder(anchorColumnIndex, newEdgeColumnIndex)) || + Debug.Assert(noSelectionChangeCount > 0); + if ((Columns.DisplayInOrder(anchorColumnIndex, oldEdgeColumnIndex) && + Columns.DisplayInOrder(newEdgeColumnIndex, anchorColumnIndex)) || + (Columns.DisplayInOrder(oldEdgeColumnIndex, anchorColumnIndex) && + Columns.DisplayInOrder(anchorColumnIndex, newEdgeColumnIndex)) || (anchorRowIndex < oldEdgeRowIndex && newEdgeRowIndex < anchorRowIndex) || (oldEdgeRowIndex < anchorRowIndex && anchorRowIndex < newEdgeRowIndex)) { @@ -28916,12 +28916,12 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu return; } - if (this.Columns.DisplayInOrder(oldEdgeColumnIndex, newEdgeColumnIndex) && - (this.Columns.DisplayInOrder(anchorColumnIndex, oldEdgeColumnIndex) || anchorColumnIndex == oldEdgeColumnIndex) && + if (Columns.DisplayInOrder(oldEdgeColumnIndex, newEdgeColumnIndex) && + (Columns.DisplayInOrder(anchorColumnIndex, oldEdgeColumnIndex) || anchorColumnIndex == oldEdgeColumnIndex) && oldEdgeRowIndex == newEdgeRowIndex) { // h1 - DataGridViewColumn dataGridViewColumn = this.Columns.GetNextColumn(this.Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + DataGridViewColumn dataGridViewColumn = Columns.GetNextColumn(Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); if (anchorRowIndex <= newEdgeRowIndex) { @@ -28933,12 +28933,12 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu SelectCellRange(dataGridViewColumn.Index, newEdgeRowIndex, newEdgeColumnIndex, anchorRowIndex, true); } } - else if (this.Columns.DisplayInOrder(newEdgeColumnIndex, oldEdgeColumnIndex) && - (this.Columns.DisplayInOrder(oldEdgeColumnIndex, anchorColumnIndex) || oldEdgeColumnIndex == anchorColumnIndex) && + else if (Columns.DisplayInOrder(newEdgeColumnIndex, oldEdgeColumnIndex) && + (Columns.DisplayInOrder(oldEdgeColumnIndex, anchorColumnIndex) || oldEdgeColumnIndex == anchorColumnIndex) && oldEdgeRowIndex == newEdgeRowIndex) { // h2 - DataGridViewColumn dataGridViewColumn = this.Columns.GetPreviousColumn(this.Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + DataGridViewColumn dataGridViewColumn = Columns.GetPreviousColumn(Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); if (anchorRowIndex <= newEdgeRowIndex) { @@ -28955,10 +28955,10 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu newEdgeColumnIndex == oldEdgeColumnIndex) { // h3 - if (this.Columns.DisplayInOrder(anchorColumnIndex, newEdgeColumnIndex) || anchorColumnIndex == newEdgeColumnIndex) + if (Columns.DisplayInOrder(anchorColumnIndex, newEdgeColumnIndex) || anchorColumnIndex == newEdgeColumnIndex) { SelectCellRange(anchorColumnIndex, - this.Rows.GetNextRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetNextRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), newEdgeColumnIndex, newEdgeRowIndex, true); @@ -28967,7 +28967,7 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu { // newEdgeColumnIndex before anchorColumnIndex SelectCellRange(newEdgeColumnIndex, - this.Rows.GetNextRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetNextRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), anchorColumnIndex, newEdgeRowIndex, true); @@ -28978,12 +28978,12 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu newEdgeColumnIndex == oldEdgeColumnIndex) { // h4 - if (this.Columns.DisplayInOrder(anchorColumnIndex, newEdgeColumnIndex) || anchorColumnIndex == newEdgeColumnIndex) + if (Columns.DisplayInOrder(anchorColumnIndex, newEdgeColumnIndex) || anchorColumnIndex == newEdgeColumnIndex) { SelectCellRange(anchorColumnIndex, newEdgeRowIndex, newEdgeColumnIndex, - this.Rows.GetPreviousRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetPreviousRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), true); } else @@ -28992,42 +28992,42 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu SelectCellRange(newEdgeColumnIndex, newEdgeRowIndex, anchorColumnIndex, - this.Rows.GetPreviousRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetPreviousRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), true); } } - else if (this.Columns.DisplayInOrder(oldEdgeColumnIndex, newEdgeColumnIndex) && - !this.Columns.DisplayInOrder(oldEdgeColumnIndex, anchorColumnIndex) && + else if (Columns.DisplayInOrder(oldEdgeColumnIndex, newEdgeColumnIndex) && + !Columns.DisplayInOrder(oldEdgeColumnIndex, anchorColumnIndex) && newEdgeRowIndex > oldEdgeRowIndex && anchorRowIndex <= oldEdgeRowIndex) { // h5 - DataGridViewColumn dataGridViewColumn = this.Columns.GetNextColumn(this.Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + DataGridViewColumn dataGridViewColumn = Columns.GetNextColumn(Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); SelectCellRange(dataGridViewColumn.Index, anchorRowIndex, newEdgeColumnIndex, oldEdgeRowIndex, true); SelectCellRange(anchorColumnIndex, - this.Rows.GetNextRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetNextRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), newEdgeColumnIndex, newEdgeRowIndex, true); } - else if (this.Columns.DisplayInOrder(oldEdgeColumnIndex, newEdgeColumnIndex) && + else if (Columns.DisplayInOrder(oldEdgeColumnIndex, newEdgeColumnIndex) && newEdgeRowIndex < oldEdgeRowIndex && oldEdgeRowIndex <= anchorRowIndex) { - if (!this.Columns.DisplayInOrder(oldEdgeColumnIndex, anchorColumnIndex)) + if (!Columns.DisplayInOrder(oldEdgeColumnIndex, anchorColumnIndex)) { // h6 - DataGridViewColumn dataGridViewColumn = this.Columns.GetNextColumn(this.Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + DataGridViewColumn dataGridViewColumn = Columns.GetNextColumn(Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); SelectCellRange(dataGridViewColumn.Index, oldEdgeRowIndex, newEdgeColumnIndex, anchorRowIndex, true); SelectCellRange(anchorColumnIndex, newEdgeRowIndex, newEdgeColumnIndex, - this.Rows.GetPreviousRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetPreviousRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), true); } else { - if (!this.Columns.DisplayInOrder(anchorColumnIndex, newEdgeColumnIndex)) + if (!Columns.DisplayInOrder(anchorColumnIndex, newEdgeColumnIndex)) { if (anchorRowIndex == oldEdgeRowIndex) { @@ -29038,47 +29038,47 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu else { // b4 - DataGridViewColumn dataGridViewColumn = this.Columns.GetPreviousColumn(this.Columns[newEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + DataGridViewColumn dataGridViewColumn = Columns.GetPreviousColumn(Columns[newEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); Debug.Assert(oldEdgeRowIndex < anchorRowIndex); SelectCellRange(oldEdgeColumnIndex, oldEdgeRowIndex, dataGridViewColumn.Index, anchorRowIndex, false); SelectCellRange(newEdgeColumnIndex, newEdgeRowIndex, anchorColumnIndex, - this.Rows.GetPreviousRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetPreviousRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), true); } } } } - else if (this.Columns.DisplayInOrder(newEdgeColumnIndex, oldEdgeColumnIndex) && + else if (Columns.DisplayInOrder(newEdgeColumnIndex, oldEdgeColumnIndex) && newEdgeRowIndex < oldEdgeRowIndex && anchorRowIndex >= oldEdgeRowIndex) { - if (!this.Columns.DisplayInOrder(anchorColumnIndex, oldEdgeColumnIndex)) + if (!Columns.DisplayInOrder(anchorColumnIndex, oldEdgeColumnIndex)) { // h7 - DataGridViewColumn dataGridViewColumn = this.Columns.GetPreviousColumn(this.Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + DataGridViewColumn dataGridViewColumn = Columns.GetPreviousColumn(Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); SelectCellRange(newEdgeColumnIndex, oldEdgeRowIndex, dataGridViewColumn.Index, anchorRowIndex, true); SelectCellRange(newEdgeColumnIndex, newEdgeRowIndex, anchorColumnIndex, - this.Rows.GetPreviousRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetPreviousRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), true); } else { - if (this.Columns.DisplayInOrder(anchorColumnIndex, newEdgeColumnIndex)) + if (Columns.DisplayInOrder(anchorColumnIndex, newEdgeColumnIndex)) { // a4 - DataGridViewColumn dataGridViewColumn = this.Columns.GetNextColumn(this.Columns[newEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + DataGridViewColumn dataGridViewColumn = Columns.GetNextColumn(Columns[newEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); Debug.Assert(oldEdgeRowIndex <= anchorRowIndex); SelectCellRange(dataGridViewColumn.Index, oldEdgeRowIndex, oldEdgeColumnIndex, anchorRowIndex, false); SelectCellRange(anchorColumnIndex, newEdgeRowIndex, newEdgeColumnIndex, - this.Rows.GetPreviousRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetPreviousRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), true); } else @@ -29089,26 +29089,26 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu } } } - else if (this.Columns.DisplayInOrder(newEdgeColumnIndex, oldEdgeColumnIndex) && - !this.Columns.DisplayInOrder(anchorColumnIndex, oldEdgeColumnIndex) && + else if (Columns.DisplayInOrder(newEdgeColumnIndex, oldEdgeColumnIndex) && + !Columns.DisplayInOrder(anchorColumnIndex, oldEdgeColumnIndex) && newEdgeRowIndex > oldEdgeRowIndex && anchorRowIndex <= oldEdgeRowIndex) { // h8 - DataGridViewColumn dataGridViewColumn = this.Columns.GetPreviousColumn(this.Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + DataGridViewColumn dataGridViewColumn = Columns.GetPreviousColumn(Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); SelectCellRange(newEdgeColumnIndex, anchorRowIndex, dataGridViewColumn.Index, oldEdgeRowIndex, true); SelectCellRange(newEdgeColumnIndex, - this.Rows.GetNextRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetNextRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), anchorColumnIndex, newEdgeRowIndex, true); } - else if (this.Columns.DisplayInOrder(newEdgeColumnIndex, oldEdgeColumnIndex)) + else if (Columns.DisplayInOrder(newEdgeColumnIndex, oldEdgeColumnIndex)) { - DataGridViewColumn dataGridViewColumn = this.Columns.GetNextColumn(this.Columns[newEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + DataGridViewColumn dataGridViewColumn = Columns.GetNextColumn(Columns[newEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); if (newEdgeRowIndex == oldEdgeRowIndex) { - if (this.Columns.DisplayInOrder(anchorColumnIndex, newEdgeColumnIndex) || (anchorColumnIndex == newEdgeColumnIndex)) + if (Columns.DisplayInOrder(anchorColumnIndex, newEdgeColumnIndex) || (anchorColumnIndex == newEdgeColumnIndex)) { // a1 Debug.Assert(dataGridViewColumn != null); @@ -29126,19 +29126,19 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu { if (oldEdgeRowIndex > anchorRowIndex) { - if (this.Columns.DisplayInOrder(newEdgeColumnIndex, oldEdgeColumnIndex)) + if (Columns.DisplayInOrder(newEdgeColumnIndex, oldEdgeColumnIndex)) { if (anchorRowIndex <= newEdgeRowIndex) { - if (this.Columns.DisplayInOrder(anchorColumnIndex, oldEdgeColumnIndex)) + if (Columns.DisplayInOrder(anchorColumnIndex, oldEdgeColumnIndex)) { - if (!this.Columns.DisplayInOrder(newEdgeColumnIndex, anchorColumnIndex)) + if (!Columns.DisplayInOrder(newEdgeColumnIndex, anchorColumnIndex)) { // a2 Debug.Assert(dataGridViewColumn != null); SelectCellRange(dataGridViewColumn.Index, anchorRowIndex, oldEdgeColumnIndex, oldEdgeRowIndex, false); SelectCellRange(anchorColumnIndex, - this.Rows.GetNextRow(newEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetNextRow(newEdgeRowIndex, DataGridViewElementStates.Visible), newEdgeColumnIndex, oldEdgeRowIndex, false); @@ -29147,10 +29147,10 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu else { // d3 - dataGridViewColumn = this.Columns.GetPreviousColumn(this.Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + dataGridViewColumn = Columns.GetPreviousColumn(Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); SelectCellRange(oldEdgeColumnIndex, - this.Rows.GetNextRow(newEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetNextRow(newEdgeRowIndex, DataGridViewElementStates.Visible), anchorColumnIndex, oldEdgeRowIndex, false); @@ -29168,7 +29168,7 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu { if (oldEdgeRowIndex < anchorRowIndex) { - if ((this.Columns.DisplayInOrder(anchorColumnIndex, newEdgeColumnIndex) || (anchorColumnIndex == newEdgeColumnIndex)) && + if ((Columns.DisplayInOrder(anchorColumnIndex, newEdgeColumnIndex) || (anchorColumnIndex == newEdgeColumnIndex)) && newEdgeRowIndex <= anchorRowIndex) { // a3 @@ -29177,22 +29177,22 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu SelectCellRange(anchorColumnIndex, oldEdgeRowIndex, newEdgeColumnIndex, - this.Rows.GetPreviousRow(newEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetPreviousRow(newEdgeRowIndex, DataGridViewElementStates.Visible), false); } else { - if (!this.Columns.DisplayInOrder(anchorColumnIndex, oldEdgeColumnIndex)) + if (!Columns.DisplayInOrder(anchorColumnIndex, oldEdgeColumnIndex)) { if (newEdgeRowIndex <= anchorRowIndex) { // c3 - dataGridViewColumn = this.Columns.GetPreviousColumn(this.Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + dataGridViewColumn = Columns.GetPreviousColumn(Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); SelectCellRange(oldEdgeColumnIndex, oldEdgeRowIndex, anchorColumnIndex, - this.Rows.GetPreviousRow(newEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetPreviousRow(newEdgeRowIndex, DataGridViewElementStates.Visible), false); SelectCellRange(newEdgeColumnIndex, newEdgeRowIndex, @@ -29205,14 +29205,14 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu } else { - if (this.Columns.DisplayInOrder(anchorColumnIndex, newEdgeColumnIndex) || (anchorColumnIndex == newEdgeColumnIndex)) + if (Columns.DisplayInOrder(anchorColumnIndex, newEdgeColumnIndex) || (anchorColumnIndex == newEdgeColumnIndex)) { // a5 Debug.Assert(oldEdgeRowIndex >= anchorRowIndex); Debug.Assert(dataGridViewColumn != null); SelectCellRange(dataGridViewColumn.Index, anchorRowIndex, oldEdgeColumnIndex, oldEdgeRowIndex, false); SelectCellRange(anchorColumnIndex, - this.Rows.GetNextRow(anchorRowIndex, DataGridViewElementStates.Visible), + Rows.GetNextRow(anchorRowIndex, DataGridViewElementStates.Visible), newEdgeColumnIndex, newEdgeRowIndex, true); @@ -29220,12 +29220,12 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu } } } - else if (this.Columns.DisplayInOrder(oldEdgeColumnIndex, newEdgeColumnIndex)) + else if (Columns.DisplayInOrder(oldEdgeColumnIndex, newEdgeColumnIndex)) { - DataGridViewColumn dataGridViewColumn = this.Columns.GetPreviousColumn(this.Columns[newEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + DataGridViewColumn dataGridViewColumn = Columns.GetPreviousColumn(Columns[newEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); if (newEdgeRowIndex == oldEdgeRowIndex) { - if (this.Columns.DisplayInOrder(newEdgeColumnIndex, anchorColumnIndex) || (newEdgeColumnIndex == anchorColumnIndex)) + if (Columns.DisplayInOrder(newEdgeColumnIndex, anchorColumnIndex) || (newEdgeColumnIndex == anchorColumnIndex)) { // b1 Debug.Assert(dataGridViewColumn != null); @@ -29243,28 +29243,28 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu { if (oldEdgeRowIndex > anchorRowIndex) { - if ((this.Columns.DisplayInOrder(newEdgeColumnIndex, anchorColumnIndex) || (newEdgeColumnIndex == anchorColumnIndex)) && + if ((Columns.DisplayInOrder(newEdgeColumnIndex, anchorColumnIndex) || (newEdgeColumnIndex == anchorColumnIndex)) && newEdgeRowIndex >= anchorRowIndex) { // b2 SelectCellRange(oldEdgeColumnIndex, anchorRowIndex, dataGridViewColumn.Index, oldEdgeRowIndex, false); SelectCellRange(newEdgeColumnIndex, - this.Rows.GetNextRow(newEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetNextRow(newEdgeRowIndex, DataGridViewElementStates.Visible), anchorColumnIndex, oldEdgeRowIndex, false); } else { - if (!this.Columns.DisplayInOrder(oldEdgeColumnIndex, anchorColumnIndex)) + if (!Columns.DisplayInOrder(oldEdgeColumnIndex, anchorColumnIndex)) { if (newEdgeRowIndex >= anchorRowIndex) { // d2 - dataGridViewColumn = this.Columns.GetNextColumn(this.Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + dataGridViewColumn = Columns.GetNextColumn(Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); SelectCellRange(anchorColumnIndex, - this.Rows.GetNextRow(newEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetNextRow(newEdgeRowIndex, DataGridViewElementStates.Visible), oldEdgeColumnIndex, oldEdgeRowIndex, false); @@ -29282,7 +29282,7 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu { if (oldEdgeRowIndex < anchorRowIndex) { - if ((this.Columns.DisplayInOrder(newEdgeColumnIndex, anchorColumnIndex) || (anchorColumnIndex == newEdgeColumnIndex)) && + if ((Columns.DisplayInOrder(newEdgeColumnIndex, anchorColumnIndex) || (anchorColumnIndex == newEdgeColumnIndex)) && newEdgeRowIndex <= anchorRowIndex) { // b3 @@ -29290,22 +29290,22 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu SelectCellRange(newEdgeColumnIndex, oldEdgeRowIndex, anchorColumnIndex, - this.Rows.GetPreviousRow(newEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetPreviousRow(newEdgeRowIndex, DataGridViewElementStates.Visible), false); } else { - if (!this.Columns.DisplayInOrder(oldEdgeColumnIndex, anchorColumnIndex)) + if (!Columns.DisplayInOrder(oldEdgeColumnIndex, anchorColumnIndex)) { if (newEdgeRowIndex <= anchorRowIndex) { // c2 - dataGridViewColumn = this.Columns.GetNextColumn(this.Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); + dataGridViewColumn = Columns.GetNextColumn(Columns[oldEdgeColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.None); Debug.Assert(dataGridViewColumn != null); SelectCellRange(anchorColumnIndex, oldEdgeRowIndex, oldEdgeColumnIndex, - this.Rows.GetPreviousRow(newEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetPreviousRow(newEdgeRowIndex, DataGridViewElementStates.Visible), false); SelectCellRange(dataGridViewColumn.Index, newEdgeRowIndex, @@ -29318,13 +29318,13 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu } else { - if (this.Columns.DisplayInOrder(newEdgeColumnIndex, anchorColumnIndex) || (anchorColumnIndex == newEdgeColumnIndex)) + if (Columns.DisplayInOrder(newEdgeColumnIndex, anchorColumnIndex) || (anchorColumnIndex == newEdgeColumnIndex)) { // b5 Debug.Assert(oldEdgeRowIndex >= anchorRowIndex); SelectCellRange(oldEdgeColumnIndex, anchorRowIndex, dataGridViewColumn.Index, oldEdgeRowIndex, false); SelectCellRange(newEdgeColumnIndex, - this.Rows.GetNextRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetNextRow(oldEdgeRowIndex, DataGridViewElementStates.Visible), anchorColumnIndex, newEdgeRowIndex, true); @@ -29339,12 +29339,12 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu if (newEdgeRowIndex <= anchorRowIndex) { // c1 - if (this.Columns.DisplayInOrder(anchorColumnIndex, oldEdgeColumnIndex)) + if (Columns.DisplayInOrder(anchorColumnIndex, oldEdgeColumnIndex)) { SelectCellRange(anchorColumnIndex, oldEdgeRowIndex, oldEdgeColumnIndex, - this.Rows.GetPreviousRow(newEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetPreviousRow(newEdgeRowIndex, DataGridViewElementStates.Visible), false); } else @@ -29352,7 +29352,7 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu SelectCellRange(oldEdgeColumnIndex, oldEdgeRowIndex, anchorColumnIndex, - this.Rows.GetPreviousRow(newEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetPreviousRow(newEdgeRowIndex, DataGridViewElementStates.Visible), false); } } @@ -29365,10 +29365,10 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu if (newEdgeRowIndex >= anchorRowIndex) { // d1 - if (this.Columns.DisplayInOrder(anchorColumnIndex, oldEdgeColumnIndex)) + if (Columns.DisplayInOrder(anchorColumnIndex, oldEdgeColumnIndex)) { SelectCellRange(anchorColumnIndex, - this.Rows.GetNextRow(newEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetNextRow(newEdgeRowIndex, DataGridViewElementStates.Visible), oldEdgeColumnIndex, oldEdgeRowIndex, false); @@ -29376,7 +29376,7 @@ private void UpdateSelectedCellsBlock(int anchorColumnIndex, ref int oldEdgeColu else { SelectCellRange(oldEdgeColumnIndex, - this.Rows.GetNextRow(newEdgeRowIndex, DataGridViewElementStates.Visible), + Rows.GetNextRow(newEdgeRowIndex, DataGridViewElementStates.Visible), anchorColumnIndex, oldEdgeRowIndex, false); @@ -29396,7 +29396,7 @@ private void VertScrollTimer_Tick(object sender, System.EventArgs e) private void VertScrollTimerHandler() { // Why would the vertical scroll timer be enabled when vertical selection is not occurring - Debug.Assert(this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] || this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect]); + Debug.Assert(dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] || dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect]); Point ptMouse = PointToClient(Control.MousePosition); HitTestInfo hti = HitTest(ptMouse.X, ptMouse.Y); @@ -29408,8 +29408,8 @@ private void VertScrollTimerHandler() { int absYOffset = Math.Abs(yOffset), normOffset = yOffset / absYOffset; ScrollRowsByCount(normOffset, normOffset < 0 ? ScrollEventType.SmallDecrement : ScrollEventType.SmallIncrement); - this.vertScrollTimer.Interval = GetRowScrollRate(absYOffset); - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect]) + vertScrollTimer.Interval = GetRowScrollRate(absYOffset); + if (dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect]) { hti = HitTest(mouseX, ptMouse.Y - yOffset - normOffset); if (hti.row >= 0) @@ -29417,7 +29417,7 @@ private void VertScrollTimerHandler() OnRowSelectMouseMove(hti); } } - else if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect]) + else if (dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect]) { if (xOffset != 0) { @@ -29435,55 +29435,55 @@ private void VertScrollTimerHandler() } else { - if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] && hti.row >= 0) + if (dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] && hti.row >= 0) { OnRowSelectMouseMove(hti); } - else if (this.dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect] && hti.col >= 0 && hti.row >= 0) + else if (dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect] && hti.col >= 0 && hti.row >= 0) { OnCellSelectMouseMove(hti); } - this.VertScrollTimer.Enabled = false; + VertScrollTimer.Enabled = false; } } } private void WireEditingControlEvents() { - Debug.Assert(this.editingPanel != null); - this.editingPanel.Click += new System.EventHandler(EditingControls_Click); - this.editingPanel.DoubleClick += new System.EventHandler(EditingControls_DoubleClick); - this.editingPanel.MouseClick += new System.Windows.Forms.MouseEventHandler(EditingControls_MouseClick); - this.editingPanel.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(EditingControls_MouseDoubleClick); - this.editingPanel.MouseDown += new System.Windows.Forms.MouseEventHandler(EditingControls_MouseDown); - this.editingPanel.MouseEnter += new System.EventHandler(EditingControls_MouseEnter); - this.editingPanel.MouseLeave += new System.EventHandler(EditingControls_MouseLeave); - this.editingPanel.MouseMove += new System.Windows.Forms.MouseEventHandler(EditingControls_MouseMove); - this.editingPanel.MouseUp += new System.Windows.Forms.MouseEventHandler(EditingControls_MouseUp); - - Debug.Assert(this.editingControl != null); - this.editingControl.Click += new System.EventHandler(EditingControls_Click); - this.editingControl.DoubleClick += new System.EventHandler(EditingControls_DoubleClick); - this.editingControl.MouseClick += new System.Windows.Forms.MouseEventHandler(EditingControls_MouseClick); - this.editingControl.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(EditingControls_MouseDoubleClick); - this.editingControl.MouseDown += new System.Windows.Forms.MouseEventHandler(EditingControls_MouseDown); - this.editingControl.MouseEnter += new System.EventHandler(EditingControls_MouseEnter); - this.editingControl.MouseLeave += new System.EventHandler(EditingControls_MouseLeave); - this.editingControl.MouseMove += new System.Windows.Forms.MouseEventHandler(EditingControls_MouseMove); - this.editingControl.MouseUp += new System.Windows.Forms.MouseEventHandler(EditingControls_MouseUp); + Debug.Assert(editingPanel != null); + editingPanel.Click += new System.EventHandler(EditingControls_Click); + editingPanel.DoubleClick += new System.EventHandler(EditingControls_DoubleClick); + editingPanel.MouseClick += new System.Windows.Forms.MouseEventHandler(EditingControls_MouseClick); + editingPanel.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(EditingControls_MouseDoubleClick); + editingPanel.MouseDown += new System.Windows.Forms.MouseEventHandler(EditingControls_MouseDown); + editingPanel.MouseEnter += new System.EventHandler(EditingControls_MouseEnter); + editingPanel.MouseLeave += new System.EventHandler(EditingControls_MouseLeave); + editingPanel.MouseMove += new System.Windows.Forms.MouseEventHandler(EditingControls_MouseMove); + editingPanel.MouseUp += new System.Windows.Forms.MouseEventHandler(EditingControls_MouseUp); + + Debug.Assert(editingControl != null); + editingControl.Click += new System.EventHandler(EditingControls_Click); + editingControl.DoubleClick += new System.EventHandler(EditingControls_DoubleClick); + editingControl.MouseClick += new System.Windows.Forms.MouseEventHandler(EditingControls_MouseClick); + editingControl.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(EditingControls_MouseDoubleClick); + editingControl.MouseDown += new System.Windows.Forms.MouseEventHandler(EditingControls_MouseDown); + editingControl.MouseEnter += new System.EventHandler(EditingControls_MouseEnter); + editingControl.MouseLeave += new System.EventHandler(EditingControls_MouseLeave); + editingControl.MouseMove += new System.Windows.Forms.MouseEventHandler(EditingControls_MouseMove); + editingControl.MouseUp += new System.Windows.Forms.MouseEventHandler(EditingControls_MouseUp); } private void WireScrollBarsEvents() { - if (this.horizScrollBar != null) + if (horizScrollBar != null) { - this.horizScrollBar.MouseEnter += new System.EventHandler(ScrollBar_MouseEnter); - this.horizScrollBar.MouseLeave += new System.EventHandler(ScrollBar_MouseLeave); + horizScrollBar.MouseEnter += new System.EventHandler(ScrollBar_MouseEnter); + horizScrollBar.MouseLeave += new System.EventHandler(ScrollBar_MouseLeave); } - if (this.vertScrollBar != null) + if (vertScrollBar != null) { - this.vertScrollBar.MouseEnter += new System.EventHandler(ScrollBar_MouseEnter); - this.vertScrollBar.MouseLeave += new System.EventHandler(ScrollBar_MouseLeave); + vertScrollBar.MouseEnter += new System.EventHandler(ScrollBar_MouseEnter); + vertScrollBar.MouseLeave += new System.EventHandler(ScrollBar_MouseLeave); } } @@ -29503,8 +29503,8 @@ internal override void WmContextMenu(ref Message m) if (unchecked((int)(long)m.LParam) == -1) { keyboardActivated = true; - client = new Point(this.Width / 2, this.Height / 2); - contextMenuStrip = (ContextMenuStrip)this.ContextMenuStrip; + client = new Point(Width / 2, Height / 2); + contextMenuStrip = (ContextMenuStrip)ContextMenuStrip; } else { @@ -29514,20 +29514,20 @@ internal override void WmContextMenu(ref Message m) switch (hti.Type) { case DataGridViewHitTestType.Cell: - dataGridViewCell = this.Rows.SharedRow(hti.row).Cells[hti.col]; + dataGridViewCell = Rows.SharedRow(hti.row).Cells[hti.col]; break; case DataGridViewHitTestType.ColumnHeader: Debug.Assert(hti.row == -1); - dataGridViewCell = this.Columns[hti.col].HeaderCell; + dataGridViewCell = Columns[hti.col].HeaderCell; break; case DataGridViewHitTestType.RowHeader: Debug.Assert(hti.col == -1); - dataGridViewCell = this.Rows.SharedRow(hti.row).HeaderCell; + dataGridViewCell = Rows.SharedRow(hti.row).HeaderCell; break; case DataGridViewHitTestType.TopLeftHeader: Debug.Assert(hti.row == -1); Debug.Assert(hti.col == -1); - dataGridViewCell = this.TopLeftHeaderCell; + dataGridViewCell = TopLeftHeaderCell; break; } if (dataGridViewCell != null) @@ -29536,12 +29536,12 @@ internal override void WmContextMenu(ref Message m) } else { - contextMenuStrip = (ContextMenuStrip)this.ContextMenuStrip; + contextMenuStrip = (ContextMenuStrip)ContextMenuStrip; } } // VisualStudio7 # 156, only show the context menu when clicked in the client area - if (contextMenuStrip != null && this.ClientRectangle.Contains(client)) + if (contextMenuStrip != null && ClientRectangle.Contains(client)) { contextMenuStrip.ShowInternal(this, client, keyboardActivated); } @@ -29575,7 +29575,7 @@ private unsafe bool WmNotify(ref Message m) NativeMethods.NMHDR* nmhdr = (NativeMethods.NMHDR*)m.LParam; if (nmhdr->code == NativeMethods.TTN_GETDISPINFO && !DesignMode) { - string toolTip = this.ToolTipPrivate; + string toolTip = ToolTipPrivate; if (!string.IsNullOrEmpty(toolTip)) { @@ -29585,7 +29585,7 @@ private unsafe bool WmNotify(ref Message m) ttt.lpszText = toolTip; - if (this.RightToLeft == RightToLeft.Yes) + if (RightToLeft == RightToLeft.Yes) { ttt.uFlags |= NativeMethods.TTF_RTLREADING; } @@ -29607,14 +29607,14 @@ protected override void WndProc(ref Message m) case Interop.WindowMessages.WM_LBUTTONDBLCLK: case Interop.WindowMessages.WM_LBUTTONDOWN: // If the OnEnter procedure is called, it's because of a mouse down event, and not a TAB key. - this.dataGridViewOper[DATAGRIDVIEWOPER_inMouseDown] = true; + dataGridViewOper[DATAGRIDVIEWOPER_inMouseDown] = true; try { base.WndProc(ref m); } finally { - this.dataGridViewOper[DATAGRIDVIEWOPER_inMouseDown] = false; + dataGridViewOper[DATAGRIDVIEWOPER_inMouseDown] = false; } return; case Interop.WindowMessages.WM_NOTIFY: @@ -29627,10 +29627,10 @@ protected override void WndProc(ref Message m) case Interop.WindowMessages.WM_IME_STARTCOMPOSITION: case Interop.WindowMessages.WM_IME_COMPOSITION: - if (this.editingControl != null) + if (editingControl != null) { // Make sure that the first character is forwarded to the editing control. - this.editingControl.SendMessage(m.Msg, m.WParam, m.LParam); + editingControl.SendMessage(m.Msg, m.WParam, m.LParam); } break; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRow.cs index 56d912c8cfe..7428c99c30e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRow.cs @@ -1804,17 +1804,17 @@ public override Rectangle Bounds Rectangle rowRect = owner.DataGridView.RectangleToScreen(owner.DataGridView.GetRowDisplayRectangle(owner.Index, false /*cutOverflow*/)); int horizontalScrollBarHeight = 0; - if (this.owner.DataGridView.HorizontalScrollBarVisible) + if (owner.DataGridView.HorizontalScrollBarVisible) { - horizontalScrollBarHeight = this.owner.DataGridView.HorizontalScrollBarHeight; + horizontalScrollBarHeight = owner.DataGridView.HorizontalScrollBarHeight; } Rectangle dataGridViewRect = ParentPrivate.Bounds; int columnHeadersHeight = 0; - if (this.owner.DataGridView.ColumnHeadersVisible) + if (owner.DataGridView.ColumnHeadersVisible) { - columnHeadersHeight = this.owner.DataGridView.ColumnHeadersHeight; + columnHeadersHeight = owner.DataGridView.ColumnHeadersHeight; } int rowRectBottom = rowRect.Bottom; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowCollection.cs index 096e530ef51..4f35d3b8c01 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowCollection.cs @@ -47,37 +47,37 @@ public class DataGridViewRowCollection : ICollection, IList int IList.Add(object value) { - return this.Add((DataGridViewRow)value); + return Add((DataGridViewRow)value); } void IList.Clear() { - this.Clear(); + Clear(); } bool IList.Contains(object value) { - return this.items.Contains(value); + return items.Contains(value); } int IList.IndexOf(object value) { - return this.items.IndexOf(value); + return items.IndexOf(value); } void IList.Insert(int index, object value) { - this.Insert(index, (DataGridViewRow)value); + Insert(index, (DataGridViewRow)value); } void IList.Remove(object value) { - this.Remove((DataGridViewRow)value); + Remove((DataGridViewRow)value); } void IList.RemoveAt(int index) { - this.RemoveAt(index); + RemoveAt(index); } bool IList.IsFixedSize @@ -112,14 +112,14 @@ object IList.this[int index] void ICollection.CopyTo(Array array, int index) { - this.items.CopyTo(array, index); + items.CopyTo(array, index); } int ICollection.Count { get { - return this.Count; + return Count; } } @@ -152,15 +152,15 @@ public DataGridViewRowCollection(DataGridView dataGridView) InvalidateCachedRowCounts(); InvalidateCachedRowsHeights(); this.dataGridView = dataGridView; - this.rowStates = new List(); - this.items = new RowArrayList(this); + rowStates = new List(); + items = new RowArrayList(this); } public int Count { get { - return this.items.Count; + return items.Count; } } @@ -168,7 +168,7 @@ internal bool IsCollectionChangedListenedTo { get { - return (this.onCollectionChanged != null); + return (onCollectionChanged != null); } } @@ -181,12 +181,12 @@ protected ArrayList List { // All rows need to be unshared // Accessing List property should be avoided. - int rowCount = this.Count; + int rowCount = Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = this[rowIndex]; } - return this.items; + return items; } } @@ -194,20 +194,20 @@ internal ArrayList SharedList { get { - return this.items; + return items; } } public DataGridViewRow SharedRow(int rowIndex) { - return (DataGridViewRow)this.SharedList[rowIndex]; + return (DataGridViewRow)SharedList[rowIndex]; } protected DataGridView DataGridView { get { - return this.dataGridView; + return dataGridView; } } @@ -221,15 +221,15 @@ public DataGridViewRow this[int index] DataGridViewRow dataGridViewRow = SharedRow(index); if (dataGridViewRow.Index == -1) { - if (index == 0 && this.items.Count == 1) + if (index == 0 && items.Count == 1) { // The only row present in the grid gets unshared. // Simply update the index and return the current row without cloning it. dataGridViewRow.IndexInternal = 0; dataGridViewRow.StateInternal = SharedRowState(0); - if (this.DataGridView != null) + if (DataGridView != null) { - this.DataGridView.OnRowUnshared(dataGridViewRow); + DataGridView.OnRowUnshared(dataGridViewRow); } return dataGridViewRow; } @@ -239,13 +239,13 @@ public DataGridViewRow this[int index] newDataGridViewRow.IndexInternal = index; newDataGridViewRow.DataGridViewInternal = dataGridViewRow.DataGridView; newDataGridViewRow.StateInternal = SharedRowState(index); - this.SharedList[index] = newDataGridViewRow; + SharedList[index] = newDataGridViewRow; int columnIndex = 0; foreach (DataGridViewCell dataGridViewCell in newDataGridViewRow.Cells) { dataGridViewCell.DataGridViewInternal = dataGridViewRow.DataGridView; dataGridViewCell.OwningRowInternal = newDataGridViewRow; - dataGridViewCell.OwningColumnInternal = this.DataGridView.Columns[columnIndex]; + dataGridViewCell.OwningColumnInternal = DataGridView.Columns[columnIndex]; columnIndex++; } if (newDataGridViewRow.HasHeaderCell) @@ -253,9 +253,9 @@ public DataGridViewRow this[int index] newDataGridViewRow.HeaderCell.DataGridViewInternal = dataGridViewRow.DataGridView; newDataGridViewRow.HeaderCell.OwningRowInternal = newDataGridViewRow; } - if (this.DataGridView != null) + if (DataGridView != null) { - this.DataGridView.OnRowUnshared(newDataGridViewRow); + DataGridView.OnRowUnshared(newDataGridViewRow); } return newDataGridViewRow; } @@ -268,19 +268,19 @@ public DataGridViewRow this[int index] public event CollectionChangeEventHandler CollectionChanged { - add => this.onCollectionChanged += value; - remove => this.onCollectionChanged -= value; + add => onCollectionChanged += value; + remove => onCollectionChanged -= value; } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual int Add() { - if (this.DataGridView.DataSource != null) + if (DataGridView.DataSource != null) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_AddUnboundRow)); } - if (this.DataGridView.NoDimensionChangeAllowed) + if (DataGridView.NoDimensionChangeAllowed) { throw new InvalidOperationException(string.Format(SR.DataGridView_ForbiddenOperationInEventHandler)); } @@ -290,20 +290,20 @@ public virtual int Add() internal int AddInternal(bool newRow, object[] values) { - Debug.Assert(this.DataGridView != null); + Debug.Assert(DataGridView != null); - if (this.DataGridView.Columns.Count == 0) + if (DataGridView.Columns.Count == 0) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_NoColumns)); } - if (this.DataGridView.RowTemplate.Cells.Count > this.DataGridView.Columns.Count) + if (DataGridView.RowTemplate.Cells.Count > DataGridView.Columns.Count) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_RowTemplateTooManyCells)); } - DataGridViewRow dataGridViewRow = this.DataGridView.RowTemplateClone; - Debug.Assert(dataGridViewRow.Cells.Count == this.DataGridView.Columns.Count); + DataGridViewRow dataGridViewRow = DataGridView.RowTemplateClone; + Debug.Assert(dataGridViewRow.Cells.Count == DataGridView.Columns.Count); if (newRow) { Debug.Assert(values == null); @@ -322,43 +322,43 @@ internal int AddInternal(bool newRow, object[] values) dataGridViewRow.SetValuesInternal(values); } - if (this.DataGridView.NewRowIndex != -1) + if (DataGridView.NewRowIndex != -1) { - Debug.Assert(this.DataGridView.AllowUserToAddRowsInternal); - Debug.Assert(this.DataGridView.NewRowIndex == this.Count - 1); - int insertionIndex = this.Count - 1; + Debug.Assert(DataGridView.AllowUserToAddRowsInternal); + Debug.Assert(DataGridView.NewRowIndex == Count - 1); + int insertionIndex = Count - 1; Insert(insertionIndex, dataGridViewRow); return insertionIndex; } DataGridViewElementStates rowState = dataGridViewRow.State; - this.DataGridView.OnAddingRow(dataGridViewRow, rowState, true /*checkFrozenState*/); // will throw an exception if the addition is illegal + DataGridView.OnAddingRow(dataGridViewRow, rowState, true /*checkFrozenState*/); // will throw an exception if the addition is illegal - dataGridViewRow.DataGridViewInternal = this.dataGridView; + dataGridViewRow.DataGridViewInternal = dataGridView; int columnIndex = 0; foreach (DataGridViewCell dataGridViewCell in dataGridViewRow.Cells) { - dataGridViewCell.DataGridViewInternal = this.dataGridView; + dataGridViewCell.DataGridViewInternal = dataGridView; Debug.Assert(dataGridViewCell.OwningRow == dataGridViewRow); - dataGridViewCell.OwningColumnInternal = this.DataGridView.Columns[columnIndex]; + dataGridViewCell.OwningColumnInternal = DataGridView.Columns[columnIndex]; columnIndex++; } if (dataGridViewRow.HasHeaderCell) { - dataGridViewRow.HeaderCell.DataGridViewInternal = this.DataGridView; + dataGridViewRow.HeaderCell.DataGridViewInternal = DataGridView; dataGridViewRow.HeaderCell.OwningRowInternal = dataGridViewRow; } - int index = this.SharedList.Add(dataGridViewRow); + int index = SharedList.Add(dataGridViewRow); Debug.Assert((rowState & (DataGridViewElementStates.Selected | DataGridViewElementStates.Displayed)) == 0); - this.rowStates.Add(rowState); + rowStates.Add(rowState); #if DEBUG - this.DataGridView.dataStoreAccessAllowed = false; - this.cachedRowHeightsAccessAllowed = false; - this.cachedRowCountsAccessAllowed = false; + DataGridView.dataStoreAccessAllowed = false; + cachedRowHeightsAccessAllowed = false; + cachedRowCountsAccessAllowed = false; #endif - if (values != null || !RowIsSharable(index) || RowHasValueOrToolTipText(dataGridViewRow) || this.IsCollectionChangedListenedTo) + if (values != null || !RowIsSharable(index) || RowHasValueOrToolTipText(dataGridViewRow) || IsCollectionChangedListenedTo) { dataGridViewRow.IndexInternal = index; Debug.Assert(dataGridViewRow.State == SharedRowState(index)); @@ -370,7 +370,7 @@ internal int AddInternal(bool newRow, object[] values) [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual int Add(params object[] values) { - Debug.Assert(this.DataGridView != null); + Debug.Assert(DataGridView != null); if (values == null) { throw new ArgumentNullException(nameof(values)); @@ -383,17 +383,17 @@ public virtual int Add(params object[] values) throw new ArgumentException(string.Format(SR.DataGridView_WrongValueCount), "values"); }*/ - if (this.DataGridView.VirtualMode) + if (DataGridView.VirtualMode) { throw new InvalidOperationException(string.Format(SR.DataGridView_InvalidOperationInVirtualMode)); } - if (this.DataGridView.DataSource != null) + if (DataGridView.DataSource != null) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_AddUnboundRow)); } - if (this.DataGridView.NoDimensionChangeAllowed) + if (DataGridView.NoDimensionChangeAllowed) { throw new InvalidOperationException(string.Format(SR.DataGridView_ForbiddenOperationInEventHandler)); } @@ -414,17 +414,17 @@ public virtual int Add(params object[] values) /// public virtual int Add(DataGridViewRow dataGridViewRow) { - if (this.DataGridView.Columns.Count == 0) + if (DataGridView.Columns.Count == 0) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_NoColumns)); } - if (this.DataGridView.DataSource != null) + if (DataGridView.DataSource != null) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_AddUnboundRow)); } - if (this.DataGridView.NoDimensionChangeAllowed) + if (DataGridView.NoDimensionChangeAllowed) { throw new InvalidOperationException(string.Format(SR.DataGridView_ForbiddenOperationInEventHandler)); } @@ -435,57 +435,57 @@ public virtual int Add(DataGridViewRow dataGridViewRow) [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual int Add(int count) { - Debug.Assert(this.DataGridView != null); + Debug.Assert(DataGridView != null); if (count <= 0) { throw new ArgumentOutOfRangeException(nameof(count), string.Format(SR.DataGridViewRowCollection_CountOutOfRange)); } - if (this.DataGridView.Columns.Count == 0) + if (DataGridView.Columns.Count == 0) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_NoColumns)); } - if (this.DataGridView.DataSource != null) + if (DataGridView.DataSource != null) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_AddUnboundRow)); } - if (this.DataGridView.NoDimensionChangeAllowed) + if (DataGridView.NoDimensionChangeAllowed) { throw new InvalidOperationException(string.Format(SR.DataGridView_ForbiddenOperationInEventHandler)); } - if (this.DataGridView.RowTemplate.Cells.Count > this.DataGridView.Columns.Count) + if (DataGridView.RowTemplate.Cells.Count > DataGridView.Columns.Count) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_RowTemplateTooManyCells)); } - DataGridViewRow rowTemplate = this.DataGridView.RowTemplateClone; - Debug.Assert(rowTemplate.Cells.Count == this.DataGridView.Columns.Count); + DataGridViewRow rowTemplate = DataGridView.RowTemplateClone; + Debug.Assert(rowTemplate.Cells.Count == DataGridView.Columns.Count); DataGridViewElementStates rowTemplateState = rowTemplate.State; Debug.Assert((rowTemplateState & (DataGridViewElementStates.Selected | DataGridViewElementStates.Displayed)) == 0); - rowTemplate.DataGridViewInternal = this.dataGridView; + rowTemplate.DataGridViewInternal = dataGridView; int columnIndex = 0; foreach (DataGridViewCell dataGridViewCell in rowTemplate.Cells) { - dataGridViewCell.DataGridViewInternal = this.dataGridView; + dataGridViewCell.DataGridViewInternal = dataGridView; Debug.Assert(dataGridViewCell.OwningRow == rowTemplate); - dataGridViewCell.OwningColumnInternal = this.DataGridView.Columns[columnIndex]; + dataGridViewCell.OwningColumnInternal = DataGridView.Columns[columnIndex]; columnIndex++; } if (rowTemplate.HasHeaderCell) { - rowTemplate.HeaderCell.DataGridViewInternal = this.dataGridView; + rowTemplate.HeaderCell.DataGridViewInternal = dataGridView; rowTemplate.HeaderCell.OwningRowInternal = rowTemplate; } - if (this.DataGridView.NewRowIndex != -1) + if (DataGridView.NewRowIndex != -1) { - Debug.Assert(this.DataGridView.AllowUserToAddRowsInternal); - Debug.Assert(this.DataGridView.NewRowIndex == this.Count - 1); - int insertionIndex = this.Count - 1; + Debug.Assert(DataGridView.AllowUserToAddRowsInternal); + Debug.Assert(DataGridView.NewRowIndex == Count - 1); + int insertionIndex = Count - 1; InsertCopiesPrivate(rowTemplate, rowTemplateState, insertionIndex, count); return insertionIndex + count - 1; } @@ -495,7 +495,7 @@ public virtual int Add(int count) internal int AddInternal(DataGridViewRow dataGridViewRow) { - Debug.Assert(this.DataGridView != null); + Debug.Assert(DataGridView != null); if (dataGridViewRow == null) { @@ -505,11 +505,11 @@ internal int AddInternal(DataGridViewRow dataGridViewRow) { throw new InvalidOperationException(string.Format(SR.DataGridView_RowAlreadyBelongsToDataGridView)); } - if (this.DataGridView.Columns.Count == 0) + if (DataGridView.Columns.Count == 0) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_NoColumns)); } - if (dataGridViewRow.Cells.Count > this.DataGridView.Columns.Count) + if (dataGridViewRow.Cells.Count > DataGridView.Columns.Count) { throw new ArgumentException(string.Format(SR.DataGridViewRowCollection_TooManyCells), "dataGridViewRow"); } @@ -519,49 +519,49 @@ internal int AddInternal(DataGridViewRow dataGridViewRow) throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_CannotAddOrInsertSelectedRow)); } - if (this.DataGridView.NewRowIndex != -1) + if (DataGridView.NewRowIndex != -1) { - Debug.Assert(this.DataGridView.AllowUserToAddRowsInternal); - Debug.Assert(this.DataGridView.NewRowIndex == this.Count - 1); - int insertionIndex = this.Count - 1; + Debug.Assert(DataGridView.AllowUserToAddRowsInternal); + Debug.Assert(DataGridView.NewRowIndex == Count - 1); + int insertionIndex = Count - 1; InsertInternal(insertionIndex, dataGridViewRow); return insertionIndex; } - this.DataGridView.CompleteCellsCollection(dataGridViewRow); - Debug.Assert(dataGridViewRow.Cells.Count == this.DataGridView.Columns.Count); - this.DataGridView.OnAddingRow(dataGridViewRow, dataGridViewRow.State, true /*checkFrozenState*/); // will throw an exception if the addition is illegal + DataGridView.CompleteCellsCollection(dataGridViewRow); + Debug.Assert(dataGridViewRow.Cells.Count == DataGridView.Columns.Count); + DataGridView.OnAddingRow(dataGridViewRow, dataGridViewRow.State, true /*checkFrozenState*/); // will throw an exception if the addition is illegal int columnIndex = 0; foreach (DataGridViewCell dataGridViewCell in dataGridViewRow.Cells) { - dataGridViewCell.DataGridViewInternal = this.dataGridView; + dataGridViewCell.DataGridViewInternal = dataGridView; Debug.Assert(dataGridViewCell.OwningRow == dataGridViewRow); if (dataGridViewCell.ColumnIndex == -1) { - dataGridViewCell.OwningColumnInternal = this.DataGridView.Columns[columnIndex]; + dataGridViewCell.OwningColumnInternal = DataGridView.Columns[columnIndex]; } columnIndex++; } if (dataGridViewRow.HasHeaderCell) { - dataGridViewRow.HeaderCell.DataGridViewInternal = this.DataGridView; + dataGridViewRow.HeaderCell.DataGridViewInternal = DataGridView; dataGridViewRow.HeaderCell.OwningRowInternal = dataGridViewRow; } - int index = this.SharedList.Add(dataGridViewRow); + int index = SharedList.Add(dataGridViewRow); Debug.Assert((dataGridViewRow.State & (DataGridViewElementStates.Selected | DataGridViewElementStates.Displayed)) == 0); - this.rowStates.Add(dataGridViewRow.State); - Debug.Assert(this.rowStates.Count == this.SharedList.Count); + rowStates.Add(dataGridViewRow.State); + Debug.Assert(rowStates.Count == SharedList.Count); #if DEBUG - this.DataGridView.dataStoreAccessAllowed = false; - this.cachedRowHeightsAccessAllowed = false; - this.cachedRowCountsAccessAllowed = false; + DataGridView.dataStoreAccessAllowed = false; + cachedRowHeightsAccessAllowed = false; + cachedRowCountsAccessAllowed = false; #endif - dataGridViewRow.DataGridViewInternal = this.dataGridView; - if (!RowIsSharable(index) || RowHasValueOrToolTipText(dataGridViewRow) || this.IsCollectionChangedListenedTo) + dataGridViewRow.DataGridViewInternal = dataGridView; + if (!RowIsSharable(index) || RowHasValueOrToolTipText(dataGridViewRow) || IsCollectionChangedListenedTo) { dataGridViewRow.IndexInternal = index; Debug.Assert(dataGridViewRow.State == SharedRowState(index)); @@ -572,12 +572,12 @@ internal int AddInternal(DataGridViewRow dataGridViewRow) public virtual int AddCopy(int indexSource) { - if (this.DataGridView.DataSource != null) + if (DataGridView.DataSource != null) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_AddUnboundRow)); } - if (this.DataGridView.NoDimensionChangeAllowed) + if (DataGridView.NoDimensionChangeAllowed) { throw new InvalidOperationException(string.Format(SR.DataGridView_ForbiddenOperationInEventHandler)); } @@ -587,38 +587,38 @@ public virtual int AddCopy(int indexSource) internal int AddCopyInternal(int indexSource, DataGridViewElementStates dgvesAdd, DataGridViewElementStates dgvesRemove, bool newRow) { - Debug.Assert(this.DataGridView != null); + Debug.Assert(DataGridView != null); - if (this.DataGridView.NewRowIndex != -1) + if (DataGridView.NewRowIndex != -1) { - Debug.Assert(this.DataGridView.AllowUserToAddRowsInternal); - Debug.Assert(this.DataGridView.NewRowIndex == this.Count - 1); + Debug.Assert(DataGridView.AllowUserToAddRowsInternal); + Debug.Assert(DataGridView.NewRowIndex == Count - 1); Debug.Assert(!newRow); - int insertionIndex = this.Count - 1; + int insertionIndex = Count - 1; InsertCopy(indexSource, insertionIndex); return insertionIndex; } - if (indexSource < 0 || indexSource >= this.Count) + if (indexSource < 0 || indexSource >= Count) { throw new ArgumentOutOfRangeException(nameof(indexSource), string.Format(SR.DataGridViewRowCollection_IndexSourceOutOfRange)); } int index; DataGridViewRow rowTemplate = SharedRow(indexSource); - if (rowTemplate.Index == -1 && !this.IsCollectionChangedListenedTo && !newRow) + if (rowTemplate.Index == -1 && !IsCollectionChangedListenedTo && !newRow) { - Debug.Assert(this.DataGridView != null); - DataGridViewElementStates rowState = this.rowStates[indexSource] & ~dgvesRemove; + Debug.Assert(DataGridView != null); + DataGridViewElementStates rowState = rowStates[indexSource] & ~dgvesRemove; rowState |= dgvesAdd; - this.DataGridView.OnAddingRow(rowTemplate, rowState, true /*checkFrozenState*/); // will throw an exception if the addition is illegal + DataGridView.OnAddingRow(rowTemplate, rowState, true /*checkFrozenState*/); // will throw an exception if the addition is illegal - index = this.SharedList.Add(rowTemplate); - this.rowStates.Add(rowState); + index = SharedList.Add(rowTemplate); + rowStates.Add(rowState); #if DEBUG - this.DataGridView.dataStoreAccessAllowed = false; - this.cachedRowHeightsAccessAllowed = false; - this.cachedRowCountsAccessAllowed = false; + DataGridView.dataStoreAccessAllowed = false; + cachedRowHeightsAccessAllowed = false; + cachedRowCountsAccessAllowed = false; #endif OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, rowTemplate), index, 1); return index; @@ -626,7 +626,7 @@ internal int AddCopyInternal(int indexSource, DataGridViewElementStates dgvesAdd else { index = AddDuplicateRow(rowTemplate, newRow); - if (!RowIsSharable(index) || RowHasValueOrToolTipText(SharedRow(index)) || this.IsCollectionChangedListenedTo) + if (!RowIsSharable(index) || RowHasValueOrToolTipText(SharedRow(index)) || IsCollectionChangedListenedTo) { UnshareRow(index); } @@ -637,12 +637,12 @@ internal int AddCopyInternal(int indexSource, DataGridViewElementStates dgvesAdd public virtual int AddCopies(int indexSource, int count) { - if (this.DataGridView.DataSource != null) + if (DataGridView.DataSource != null) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_AddUnboundRow)); } - if (this.DataGridView.NoDimensionChangeAllowed) + if (DataGridView.NoDimensionChangeAllowed) { throw new InvalidOperationException(string.Format(SR.DataGridView_ForbiddenOperationInEventHandler)); } @@ -652,11 +652,11 @@ public virtual int AddCopies(int indexSource, int count) internal int AddCopiesInternal(int indexSource, int count) { - if (this.DataGridView.NewRowIndex != -1) + if (DataGridView.NewRowIndex != -1) { - Debug.Assert(this.DataGridView.AllowUserToAddRowsInternal); - Debug.Assert(this.DataGridView.NewRowIndex == this.Count - 1); - int insertionIndex = this.Count - 1; + Debug.Assert(DataGridView.AllowUserToAddRowsInternal); + Debug.Assert(DataGridView.NewRowIndex == Count - 1); + int insertionIndex = Count - 1; InsertCopiesPrivate(indexSource, insertionIndex, count); return insertionIndex + count - 1; } @@ -666,7 +666,7 @@ internal int AddCopiesInternal(int indexSource, int count) internal int AddCopiesInternal(int indexSource, int count, DataGridViewElementStates dgvesAdd, DataGridViewElementStates dgvesRemove) { - if (indexSource < 0 || this.Count <= indexSource) + if (indexSource < 0 || Count <= indexSource) { throw new ArgumentOutOfRangeException(nameof(indexSource), string.Format(SR.DataGridViewRowCollection_IndexSourceOutOfRange)); } @@ -676,7 +676,7 @@ internal int AddCopiesInternal(int indexSource, int count, DataGridViewElementSt throw new ArgumentOutOfRangeException(nameof(count), string.Format(SR.DataGridViewRowCollection_CountOutOfRange)); } - DataGridViewElementStates rowTemplateState = this.rowStates[indexSource] & ~dgvesRemove; + DataGridViewElementStates rowTemplateState = rowStates[indexSource] & ~dgvesRemove; rowTemplateState |= dgvesAdd; return AddCopiesPrivate(SharedRow(indexSource), rowTemplateState, count); @@ -684,27 +684,27 @@ internal int AddCopiesInternal(int indexSource, int count, DataGridViewElementSt private int AddCopiesPrivate(DataGridViewRow rowTemplate, DataGridViewElementStates rowTemplateState, int count) { - int index, indexStart = this.items.Count; + int index, indexStart = items.Count; if (rowTemplate.Index == -1) { - this.DataGridView.OnAddingRow(rowTemplate, rowTemplateState, true /*checkFrozenState*/); // Done once only, continue to check if this is OK - will throw an exception if the addition is illegal. + DataGridView.OnAddingRow(rowTemplate, rowTemplateState, true /*checkFrozenState*/); // Done once only, continue to check if this is OK - will throw an exception if the addition is illegal. for (int i = 0; i < count - 1; i++) { - this.SharedList.Add(rowTemplate); - this.rowStates.Add(rowTemplateState); + SharedList.Add(rowTemplate); + rowStates.Add(rowTemplateState); } - index = this.SharedList.Add(rowTemplate); - this.rowStates.Add(rowTemplateState); + index = SharedList.Add(rowTemplate); + rowStates.Add(rowTemplateState); #if DEBUG - this.DataGridView.dataStoreAccessAllowed = false; - this.cachedRowHeightsAccessAllowed = false; - this.cachedRowCountsAccessAllowed = false; + DataGridView.dataStoreAccessAllowed = false; + cachedRowHeightsAccessAllowed = false; + cachedRowCountsAccessAllowed = false; #endif - this.DataGridView.OnAddedRow_PreNotification(index); // Only calling this once instead of 'count' times. Continue to check if this is OK. + DataGridView.OnAddedRow_PreNotification(index); // Only calling this once instead of 'count' times. Continue to check if this is OK. OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null), indexStart, count); for (int i = 0; i < count; i++) { - this.DataGridView.OnAddedRow_PostNotification(index - (count - 1) + i); + DataGridView.OnAddedRow_PostNotification(index - (count - 1) + i); } return index; } @@ -713,24 +713,24 @@ private int AddCopiesPrivate(DataGridViewRow rowTemplate, DataGridViewElementSta index = AddDuplicateRow(rowTemplate, false /*newRow*/); if (count > 1) { - this.DataGridView.OnAddedRow_PreNotification(index); + DataGridView.OnAddedRow_PreNotification(index); if (RowIsSharable(index)) { DataGridViewRow rowTemplate2 = SharedRow(index); - this.DataGridView.OnAddingRow(rowTemplate2, rowTemplateState, true /*checkFrozenState*/); // done only once, continue to check if this is OK - will throw an exception if the addition is illegal + DataGridView.OnAddingRow(rowTemplate2, rowTemplateState, true /*checkFrozenState*/); // done only once, continue to check if this is OK - will throw an exception if the addition is illegal for (int i = 1; i < count - 1; i++) { - this.SharedList.Add(rowTemplate2); - this.rowStates.Add(rowTemplateState); + SharedList.Add(rowTemplate2); + rowStates.Add(rowTemplateState); } - index = this.SharedList.Add(rowTemplate2); - this.rowStates.Add(rowTemplateState); + index = SharedList.Add(rowTemplate2); + rowStates.Add(rowTemplateState); #if DEBUG - this.DataGridView.dataStoreAccessAllowed = false; - this.cachedRowHeightsAccessAllowed = false; - this.cachedRowCountsAccessAllowed = false; + DataGridView.dataStoreAccessAllowed = false; + cachedRowHeightsAccessAllowed = false; + cachedRowCountsAccessAllowed = false; #endif - this.DataGridView.OnAddedRow_PreNotification(index); // Only calling this once instead of 'count-1' times. Continue to check if this is OK. + DataGridView.OnAddedRow_PreNotification(index); // Only calling this once instead of 'count-1' times. Continue to check if this is OK. } else { @@ -739,19 +739,19 @@ private int AddCopiesPrivate(DataGridViewRow rowTemplate, DataGridViewElementSta { index = AddDuplicateRow(rowTemplate, false /*newRow*/); UnshareRow(index); - this.DataGridView.OnAddedRow_PreNotification(index); + DataGridView.OnAddedRow_PreNotification(index); } } OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null), indexStart, count); for (int i = 0; i < count; i++) { - this.DataGridView.OnAddedRow_PostNotification(index - (count - 1) + i); + DataGridView.OnAddedRow_PostNotification(index - (count - 1) + i); } return index; } else { - if (this.IsCollectionChangedListenedTo) + if (IsCollectionChangedListenedTo) { UnshareRow(index); } @@ -763,11 +763,11 @@ private int AddCopiesPrivate(DataGridViewRow rowTemplate, DataGridViewElementSta private int AddDuplicateRow(DataGridViewRow rowTemplate, bool newRow) { - Debug.Assert(this.DataGridView != null); + Debug.Assert(DataGridView != null); DataGridViewRow dataGridViewRow = (DataGridViewRow)rowTemplate.Clone(); dataGridViewRow.StateInternal = DataGridViewElementStates.None; - dataGridViewRow.DataGridViewInternal = this.dataGridView; + dataGridViewRow.DataGridViewInternal = dataGridView; DataGridViewCellCollection dgvcc = dataGridViewRow.Cells; int columnIndex = 0; foreach (DataGridViewCell dataGridViewCell in dgvcc) @@ -776,27 +776,27 @@ private int AddDuplicateRow(DataGridViewRow rowTemplate, bool newRow) { dataGridViewCell.Value = dataGridViewCell.DefaultNewRowValue; } - dataGridViewCell.DataGridViewInternal = this.dataGridView; - dataGridViewCell.OwningColumnInternal = this.DataGridView.Columns[columnIndex]; + dataGridViewCell.DataGridViewInternal = dataGridView; + dataGridViewCell.OwningColumnInternal = DataGridView.Columns[columnIndex]; columnIndex++; } DataGridViewElementStates rowState = rowTemplate.State & ~(DataGridViewElementStates.Selected | DataGridViewElementStates.Displayed); if (dataGridViewRow.HasHeaderCell) { - dataGridViewRow.HeaderCell.DataGridViewInternal = this.dataGridView; + dataGridViewRow.HeaderCell.DataGridViewInternal = dataGridView; dataGridViewRow.HeaderCell.OwningRowInternal = dataGridViewRow; } - this.DataGridView.OnAddingRow(dataGridViewRow, rowState, true /*checkFrozenState*/); // will throw an exception if the addition is illegal + DataGridView.OnAddingRow(dataGridViewRow, rowState, true /*checkFrozenState*/); // will throw an exception if the addition is illegal #if DEBUG - this.DataGridView.dataStoreAccessAllowed = false; - this.cachedRowHeightsAccessAllowed = false; - this.cachedRowCountsAccessAllowed = false; + DataGridView.dataStoreAccessAllowed = false; + cachedRowHeightsAccessAllowed = false; + cachedRowCountsAccessAllowed = false; #endif Debug.Assert(dataGridViewRow.Index == -1); - this.rowStates.Add(rowState); - return this.SharedList.Add(dataGridViewRow); + rowStates.Add(rowState); + return SharedList.Add(dataGridViewRow); } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] @@ -807,82 +807,82 @@ public virtual void AddRange(params DataGridViewRow[] dataGridViewRows) throw new ArgumentNullException(nameof(dataGridViewRows)); } - Debug.Assert(this.DataGridView != null); + Debug.Assert(DataGridView != null); - if (this.DataGridView.NoDimensionChangeAllowed) + if (DataGridView.NoDimensionChangeAllowed) { throw new InvalidOperationException(string.Format(SR.DataGridView_ForbiddenOperationInEventHandler)); } - if (this.DataGridView.DataSource != null) + if (DataGridView.DataSource != null) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_AddUnboundRow)); } - if (this.DataGridView.NewRowIndex != -1) + if (DataGridView.NewRowIndex != -1) { - Debug.Assert(this.DataGridView.AllowUserToAddRowsInternal); - Debug.Assert(this.DataGridView.NewRowIndex == this.Count - 1); - InsertRange(this.Count - 1, dataGridViewRows); + Debug.Assert(DataGridView.AllowUserToAddRowsInternal); + Debug.Assert(DataGridView.NewRowIndex == Count - 1); + InsertRange(Count - 1, dataGridViewRows); return; } - if (this.DataGridView.Columns.Count == 0) + if (DataGridView.Columns.Count == 0) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_NoColumns)); } - int indexStart = this.items.Count; + int indexStart = items.Count; // OnAddingRows checks for Selected flag of each row and their dimension. - this.DataGridView.OnAddingRows(dataGridViewRows, true /*checkFrozenStates*/); // will throw an exception if the addition is illegal + DataGridView.OnAddingRows(dataGridViewRows, true /*checkFrozenStates*/); // will throw an exception if the addition is illegal foreach (DataGridViewRow dataGridViewRow in dataGridViewRows) { - Debug.Assert(dataGridViewRow.Cells.Count == this.DataGridView.Columns.Count); + Debug.Assert(dataGridViewRow.Cells.Count == DataGridView.Columns.Count); int columnIndex = 0; foreach (DataGridViewCell dataGridViewCell in dataGridViewRow.Cells) { - dataGridViewCell.DataGridViewInternal = this.dataGridView; + dataGridViewCell.DataGridViewInternal = dataGridView; Debug.Assert(dataGridViewCell.OwningRow == dataGridViewRow); - dataGridViewCell.OwningColumnInternal = this.DataGridView.Columns[columnIndex]; + dataGridViewCell.OwningColumnInternal = DataGridView.Columns[columnIndex]; columnIndex++; } if (dataGridViewRow.HasHeaderCell) { - dataGridViewRow.HeaderCell.DataGridViewInternal = this.dataGridView; + dataGridViewRow.HeaderCell.DataGridViewInternal = dataGridView; dataGridViewRow.HeaderCell.OwningRowInternal = dataGridViewRow; } - int index = this.SharedList.Add(dataGridViewRow); + int index = SharedList.Add(dataGridViewRow); Debug.Assert((dataGridViewRow.State & (DataGridViewElementStates.Selected | DataGridViewElementStates.Displayed)) == 0); - this.rowStates.Add(dataGridViewRow.State); + rowStates.Add(dataGridViewRow.State); #if DEBUG - this.DataGridView.dataStoreAccessAllowed = false; - this.cachedRowHeightsAccessAllowed = false; - this.cachedRowCountsAccessAllowed = false; + DataGridView.dataStoreAccessAllowed = false; + cachedRowHeightsAccessAllowed = false; + cachedRowCountsAccessAllowed = false; #endif dataGridViewRow.IndexInternal = index; Debug.Assert(dataGridViewRow.State == SharedRowState(index)); - dataGridViewRow.DataGridViewInternal = this.dataGridView; + dataGridViewRow.DataGridViewInternal = dataGridView; } - Debug.Assert(this.rowStates.Count == this.SharedList.Count); + Debug.Assert(rowStates.Count == SharedList.Count); - this.DataGridView.OnAddedRows_PreNotification(dataGridViewRows); + DataGridView.OnAddedRows_PreNotification(dataGridViewRows); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null), indexStart, dataGridViewRows.Length); - this.DataGridView.OnAddedRows_PostNotification(dataGridViewRows); + DataGridView.OnAddedRows_PostNotification(dataGridViewRows); } public virtual void Clear() { - if (this.DataGridView.NoDimensionChangeAllowed) + if (DataGridView.NoDimensionChangeAllowed) { throw new InvalidOperationException(string.Format(SR.DataGridView_ForbiddenOperationInEventHandler)); } - if (this.DataGridView.DataSource != null) + if (DataGridView.DataSource != null) { - IBindingList list = this.DataGridView.DataConnection.List as IBindingList; + IBindingList list = DataGridView.DataConnection.List as IBindingList; if (list != null && list.AllowRemove && list.SupportsChangeNotification) { ((IList)list).Clear(); @@ -900,31 +900,31 @@ public virtual void Clear() internal void ClearInternal(bool recreateNewRow) { - int rowCount = this.items.Count; + int rowCount = items.Count; if (rowCount > 0) { - this.DataGridView.OnClearingRows(); + DataGridView.OnClearingRows(); for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { SharedRow(rowIndex).DetachFromDataGridView(); } - this.SharedList.Clear(); - this.rowStates.Clear(); + SharedList.Clear(); + rowStates.Clear(); #if DEBUG - this.DataGridView.dataStoreAccessAllowed = false; - this.cachedRowHeightsAccessAllowed = false; - this.cachedRowCountsAccessAllowed = false; + DataGridView.dataStoreAccessAllowed = false; + cachedRowHeightsAccessAllowed = false; + cachedRowCountsAccessAllowed = false; #endif OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null), 0, rowCount, true, false, recreateNewRow, new Point(-1, -1)); } else if (recreateNewRow && - this.DataGridView.Columns.Count != 0 && - this.DataGridView.AllowUserToAddRowsInternal && - this.items.Count == 0) // accessing AllowUserToAddRowsInternal can trigger a nested call to ClearInternal. Rows count needs to be checked again. + DataGridView.Columns.Count != 0 && + DataGridView.AllowUserToAddRowsInternal && + items.Count == 0) // accessing AllowUserToAddRowsInternal can trigger a nested call to ClearInternal. Rows count needs to be checked again. { - this.DataGridView.AddNewRow(false); + DataGridView.AddNewRow(false); } } @@ -933,12 +933,12 @@ internal void ClearInternal(bool recreateNewRow) /// public virtual bool Contains(DataGridViewRow dataGridViewRow) { - return this.items.IndexOf(dataGridViewRow) != -1; + return items.IndexOf(dataGridViewRow) != -1; } public void CopyTo(DataGridViewRow[] array, int index) { - this.items.CopyTo(array, index); + items.CopyTo(array, index); } // returns the row collection index for the n'th visible row @@ -950,7 +950,7 @@ internal int DisplayIndexToRowIndex(int visibleRowIndex) // the alternative would be to do a binary search using DataGridViewRowCollection::GetRowCount(...) // but that method also iterates thru each row so we would not gain much int indexOfCurrentVisibleRow = -1; - for (int i = 0; i < this.Count; i++) + for (int i = 0; i < Count; i++) { if ((GetRowState(i) & DataGridViewElementStates.Visible) == DataGridViewElementStates.Visible) { @@ -973,24 +973,24 @@ public int GetFirstRow(DataGridViewElementStates includeFilter) throw new ArgumentException(string.Format(SR.DataGridView_InvalidDataGridViewElementStateCombination, nameof(includeFilter))); } #if DEBUG - Debug.Assert(this.cachedRowCountsAccessAllowed); + Debug.Assert(cachedRowCountsAccessAllowed); #endif switch (includeFilter) { case DataGridViewElementStates.Visible: - if (this.rowCountsVisible == 0) + if (rowCountsVisible == 0) { return -1; } break; case DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen: - if (this.rowCountsVisibleFrozen == 0) + if (rowCountsVisibleFrozen == 0) { return -1; } break; case DataGridViewElementStates.Visible | DataGridViewElementStates.Selected: - if (this.rowCountsVisibleSelected == 0) + if (rowCountsVisibleSelected == 0) { return -1; } @@ -998,11 +998,11 @@ public int GetFirstRow(DataGridViewElementStates includeFilter) } int index = 0; - while (index < this.items.Count && !((GetRowState(index) & includeFilter) == includeFilter)) + while (index < items.Count && !((GetRowState(index) & includeFilter) == includeFilter)) { index++; } - return (index < this.items.Count) ? index : -1; + return (index < items.Count) ? index : -1; } public int GetFirstRow(DataGridViewElementStates includeFilter, @@ -1023,24 +1023,24 @@ public int GetFirstRow(DataGridViewElementStates includeFilter, throw new ArgumentException(string.Format(SR.DataGridView_InvalidDataGridViewElementStateCombination, nameof(excludeFilter))); } #if DEBUG - Debug.Assert(this.cachedRowCountsAccessAllowed); + Debug.Assert(cachedRowCountsAccessAllowed); #endif switch (includeFilter) { case DataGridViewElementStates.Visible: - if (this.rowCountsVisible == 0) + if (rowCountsVisible == 0) { return -1; } break; case DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen: - if (this.rowCountsVisibleFrozen == 0) + if (rowCountsVisibleFrozen == 0) { return -1; } break; case DataGridViewElementStates.Visible | DataGridViewElementStates.Selected: - if (this.rowCountsVisibleSelected == 0) + if (rowCountsVisibleSelected == 0) { return -1; } @@ -1048,11 +1048,11 @@ public int GetFirstRow(DataGridViewElementStates includeFilter, } int index = 0; - while (index < this.items.Count && (!((GetRowState(index) & includeFilter) == includeFilter) || !((GetRowState(index) & excludeFilter) == 0))) + while (index < items.Count && (!((GetRowState(index) & includeFilter) == includeFilter) || !((GetRowState(index) & excludeFilter) == 0))) { index++; } - return (index < this.items.Count) ? index : -1; + return (index < items.Count) ? index : -1; } public int GetLastRow(DataGridViewElementStates includeFilter) @@ -1063,31 +1063,31 @@ public int GetLastRow(DataGridViewElementStates includeFilter) throw new ArgumentException(string.Format(SR.DataGridView_InvalidDataGridViewElementStateCombination, nameof(includeFilter))); } #if DEBUG - Debug.Assert(this.cachedRowCountsAccessAllowed); + Debug.Assert(cachedRowCountsAccessAllowed); #endif switch (includeFilter) { case DataGridViewElementStates.Visible: - if (this.rowCountsVisible == 0) + if (rowCountsVisible == 0) { return -1; } break; case DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen: - if (this.rowCountsVisibleFrozen == 0) + if (rowCountsVisibleFrozen == 0) { return -1; } break; case DataGridViewElementStates.Visible | DataGridViewElementStates.Selected: - if (this.rowCountsVisibleSelected == 0) + if (rowCountsVisibleSelected == 0) { return -1; } break; } - int index = this.items.Count - 1; + int index = items.Count - 1; while (index >= 0 && !((GetRowState(index) & includeFilter) == includeFilter)) { index--; @@ -1123,11 +1123,11 @@ public int GetNextRow(int indexStart, DataGridViewElementStates includeFilter) } int index = indexStart + 1; - while (index < this.items.Count && !((GetRowState(index) & includeFilter) == includeFilter)) + while (index < items.Count && !((GetRowState(index) & includeFilter) == includeFilter)) { index++; } - return (index < this.items.Count) ? index : -1; + return (index < items.Count) ? index : -1; } public int GetNextRow(int indexStart, @@ -1154,11 +1154,11 @@ public int GetNextRow(int indexStart, } int index = indexStart + 1; - while (index < this.items.Count && (!((GetRowState(index) & includeFilter) == includeFilter) || !((GetRowState(index) & excludeFilter) == 0))) + while (index < items.Count && (!((GetRowState(index) & includeFilter) == includeFilter) || !((GetRowState(index) & excludeFilter) == 0))) { index++; } - return (index < this.items.Count) ? index : -1; + return (index < items.Count) ? index : -1; } public int GetPreviousRow(int indexStart, DataGridViewElementStates includeFilter) @@ -1168,7 +1168,7 @@ public int GetPreviousRow(int indexStart, DataGridViewElementStates includeFilte { throw new ArgumentException(string.Format(SR.DataGridView_InvalidDataGridViewElementStateCombination, nameof(includeFilter))); } - if (indexStart > this.items.Count) + if (indexStart > items.Count) { throw new ArgumentOutOfRangeException(nameof(indexStart), indexStart, string.Format(SR.InvalidHighBoundArgumentEx, nameof(indexStart), indexStart, items.Count)); } @@ -1199,7 +1199,7 @@ public int GetPreviousRow(int indexStart, { throw new ArgumentException(string.Format(SR.DataGridView_InvalidDataGridViewElementStateCombination, nameof(excludeFilter))); } - if (indexStart > this.items.Count) + if (indexStart > items.Count) { throw new ArgumentOutOfRangeException(nameof(indexStart), indexStart, string.Format(SR.InvalidHighBoundArgumentEx, nameof(indexStart), indexStart, items.Count)); } @@ -1220,34 +1220,34 @@ public int GetRowCount(DataGridViewElementStates includeFilter) throw new ArgumentException(string.Format(SR.DataGridView_InvalidDataGridViewElementStateCombination, nameof(includeFilter))); } #if DEBUG - Debug.Assert(this.cachedRowCountsAccessAllowed); + Debug.Assert(cachedRowCountsAccessAllowed); #endif // cache returned value and reuse it as long as none // of the row's state has changed. switch (includeFilter) { case DataGridViewElementStates.Visible: - if (this.rowCountsVisible != -1) + if (rowCountsVisible != -1) { - return this.rowCountsVisible; + return rowCountsVisible; } break; case DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen: - if (this.rowCountsVisibleFrozen != -1) + if (rowCountsVisibleFrozen != -1) { - return this.rowCountsVisibleFrozen; + return rowCountsVisibleFrozen; } break; case DataGridViewElementStates.Visible | DataGridViewElementStates.Selected: - if (this.rowCountsVisibleSelected != -1) + if (rowCountsVisibleSelected != -1) { - return this.rowCountsVisibleSelected; + return rowCountsVisibleSelected; } break; } int rowCount = 0; - for (int rowIndex = 0; rowIndex < this.items.Count; rowIndex++) + for (int rowIndex = 0; rowIndex < items.Count; rowIndex++) { if ((GetRowState(rowIndex) & includeFilter) == includeFilter) { @@ -1258,13 +1258,13 @@ public int GetRowCount(DataGridViewElementStates includeFilter) switch (includeFilter) { case DataGridViewElementStates.Visible: - this.rowCountsVisible = rowCount; + rowCountsVisible = rowCount; break; case DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen: - this.rowCountsVisibleFrozen = rowCount; + rowCountsVisibleFrozen = rowCount; break; case DataGridViewElementStates.Visible | DataGridViewElementStates.Selected: - this.rowCountsVisibleSelected = rowCount; + rowCountsVisibleSelected = rowCount; break; } return rowCount; @@ -1295,42 +1295,42 @@ public int GetRowsHeight(DataGridViewElementStates includeFilter) throw new ArgumentException(string.Format(SR.DataGridView_InvalidDataGridViewElementStateCombination, nameof(includeFilter))); } #if DEBUG - Debug.Assert(this.cachedRowHeightsAccessAllowed); + Debug.Assert(cachedRowHeightsAccessAllowed); #endif // cache returned value and reuse it as long as none // of the row's state/thickness has changed. switch (includeFilter) { case DataGridViewElementStates.Visible: - if (this.rowsHeightVisible != -1) + if (rowsHeightVisible != -1) { - return this.rowsHeightVisible; + return rowsHeightVisible; } break; case DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen: - if (this.rowsHeightVisibleFrozen != -1) + if (rowsHeightVisibleFrozen != -1) { - return this.rowsHeightVisibleFrozen; + return rowsHeightVisibleFrozen; } break; } int rowsHeight = 0; - for (int rowIndex = 0; rowIndex < this.items.Count; rowIndex++) + for (int rowIndex = 0; rowIndex < items.Count; rowIndex++) { if ((GetRowState(rowIndex) & includeFilter) == includeFilter) { - rowsHeight += ((DataGridViewRow)this.items[rowIndex]).GetHeight(rowIndex); + rowsHeight += ((DataGridViewRow)items[rowIndex]).GetHeight(rowIndex); } } switch (includeFilter) { case DataGridViewElementStates.Visible: - this.rowsHeightVisible = rowsHeight; + rowsHeightVisible = rowsHeight; break; case DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen: - this.rowsHeightVisibleFrozen = rowsHeight; + rowsHeightVisibleFrozen = rowsHeight; break; } return rowsHeight; @@ -1347,7 +1347,7 @@ internal int GetRowsHeight(DataGridViewElementStates includeFilter, int fromRowI { if ((GetRowState(rowIndex) & includeFilter) == includeFilter) { - rowsHeight += ((DataGridViewRow)this.items[rowIndex]).GetHeight(rowIndex); + rowsHeight += ((DataGridViewRow)items[rowIndex]).GetHeight(rowIndex); } } return rowsHeight; @@ -1357,14 +1357,14 @@ internal int GetRowsHeight(DataGridViewElementStates includeFilter, int fromRowI private bool GetRowsHeightExceedLimit(DataGridViewElementStates includeFilter, int fromRowIndex, int toRowIndex, int heightLimit) { Debug.Assert(toRowIndex >= fromRowIndex); - Debug.Assert(toRowIndex == this.items.Count || (GetRowState(toRowIndex) & includeFilter) == includeFilter); + Debug.Assert(toRowIndex == items.Count || (GetRowState(toRowIndex) & includeFilter) == includeFilter); int rowsHeight = 0; for (int rowIndex = fromRowIndex; rowIndex < toRowIndex; rowIndex++) { if ((GetRowState(rowIndex) & includeFilter) == includeFilter) { - rowsHeight += ((DataGridViewRow)this.items[rowIndex]).GetHeight(rowIndex); + rowsHeight += ((DataGridViewRow)items[rowIndex]).GetHeight(rowIndex); if (rowsHeight > heightLimit) { return true; @@ -1376,7 +1376,7 @@ private bool GetRowsHeightExceedLimit(DataGridViewElementStates includeFilter, i public virtual DataGridViewElementStates GetRowState(int rowIndex) { - if (rowIndex < 0 || rowIndex >= this.items.Count) + if (rowIndex < 0 || rowIndex >= items.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex), string.Format(SR.DataGridViewRowCollection_RowIndexOutOfRange)); } @@ -1394,12 +1394,12 @@ public virtual DataGridViewElementStates GetRowState(int rowIndex) public int IndexOf(DataGridViewRow dataGridViewRow) { - return this.items.IndexOf(dataGridViewRow); + return items.IndexOf(dataGridViewRow); } public virtual void Insert(int rowIndex, params object[] values) { - Debug.Assert(this.DataGridView != null); + Debug.Assert(DataGridView != null); if (values == null) { @@ -1413,17 +1413,17 @@ public virtual void Insert(int rowIndex, params object[] values) throw new ArgumentException(string.Format(SR.DataGridView_WrongValueCount), "values"); }*/ - if (this.DataGridView.VirtualMode) + if (DataGridView.VirtualMode) { throw new InvalidOperationException(string.Format(SR.DataGridView_InvalidOperationInVirtualMode)); } - if (this.DataGridView.DataSource != null) + if (DataGridView.DataSource != null) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_AddUnboundRow)); } - DataGridViewRow dataGridViewRow = this.DataGridView.RowTemplateClone; + DataGridViewRow dataGridViewRow = DataGridView.RowTemplateClone; dataGridViewRow.SetValuesInternal(values); Insert(rowIndex, dataGridViewRow); } @@ -1433,12 +1433,12 @@ public virtual void Insert(int rowIndex, params object[] values) /// public virtual void Insert(int rowIndex, DataGridViewRow dataGridViewRow) { - if (this.DataGridView.DataSource != null) + if (DataGridView.DataSource != null) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_AddUnboundRow)); } - if (this.DataGridView.NoDimensionChangeAllowed) + if (DataGridView.NoDimensionChangeAllowed) { throw new InvalidOperationException(string.Format(SR.DataGridView_ForbiddenOperationInEventHandler)); } @@ -1448,12 +1448,12 @@ public virtual void Insert(int rowIndex, DataGridViewRow dataGridViewRow) public virtual void Insert(int rowIndex, int count) { - if (this.DataGridView.DataSource != null) + if (DataGridView.DataSource != null) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_AddUnboundRow)); } - if (rowIndex < 0 || this.Count < rowIndex) + if (rowIndex < 0 || Count < rowIndex) { throw new ArgumentOutOfRangeException(nameof(rowIndex), string.Format(SR.DataGridViewRowCollection_IndexDestinationOutOfRange)); } @@ -1463,44 +1463,44 @@ public virtual void Insert(int rowIndex, int count) throw new ArgumentOutOfRangeException(nameof(count), string.Format(SR.DataGridViewRowCollection_CountOutOfRange)); } - if (this.DataGridView.NoDimensionChangeAllowed) + if (DataGridView.NoDimensionChangeAllowed) { throw new InvalidOperationException(string.Format(SR.DataGridView_ForbiddenOperationInEventHandler)); } - if (this.DataGridView.Columns.Count == 0) + if (DataGridView.Columns.Count == 0) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_NoColumns)); } - if (this.DataGridView.RowTemplate.Cells.Count > this.DataGridView.Columns.Count) + if (DataGridView.RowTemplate.Cells.Count > DataGridView.Columns.Count) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_RowTemplateTooManyCells)); } - if (this.DataGridView.NewRowIndex != -1 && rowIndex == this.Count) + if (DataGridView.NewRowIndex != -1 && rowIndex == Count) { // Trying to insert after the 'new' row. - Debug.Assert(this.DataGridView.AllowUserToAddRowsInternal); + Debug.Assert(DataGridView.AllowUserToAddRowsInternal); throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_NoInsertionAfterNewRow)); } - DataGridViewRow rowTemplate = this.DataGridView.RowTemplateClone; - Debug.Assert(rowTemplate.Cells.Count == this.DataGridView.Columns.Count); + DataGridViewRow rowTemplate = DataGridView.RowTemplateClone; + Debug.Assert(rowTemplate.Cells.Count == DataGridView.Columns.Count); DataGridViewElementStates rowTemplateState = rowTemplate.State; Debug.Assert((rowTemplateState & (DataGridViewElementStates.Selected | DataGridViewElementStates.Displayed)) == 0); - rowTemplate.DataGridViewInternal = this.dataGridView; + rowTemplate.DataGridViewInternal = dataGridView; int columnIndex = 0; foreach (DataGridViewCell dataGridViewCell in rowTemplate.Cells) { - dataGridViewCell.DataGridViewInternal = this.dataGridView; + dataGridViewCell.DataGridViewInternal = dataGridView; Debug.Assert(dataGridViewCell.OwningRow == rowTemplate); - dataGridViewCell.OwningColumnInternal = this.DataGridView.Columns[columnIndex]; + dataGridViewCell.OwningColumnInternal = DataGridView.Columns[columnIndex]; columnIndex++; } if (rowTemplate.HasHeaderCell) { - rowTemplate.HeaderCell.DataGridViewInternal = this.dataGridView; + rowTemplate.HeaderCell.DataGridViewInternal = dataGridView; rowTemplate.HeaderCell.OwningRowInternal = rowTemplate; } @@ -1509,8 +1509,8 @@ public virtual void Insert(int rowIndex, int count) internal void InsertInternal(int rowIndex, DataGridViewRow dataGridViewRow) { - Debug.Assert(this.DataGridView != null); - if (rowIndex < 0 || this.Count < rowIndex) + Debug.Assert(DataGridView != null); + if (rowIndex < 0 || Count < rowIndex) { throw new ArgumentOutOfRangeException(nameof(rowIndex), string.Format(SR.DataGridViewRowCollection_RowIndexOutOfRange)); } @@ -1525,19 +1525,19 @@ internal void InsertInternal(int rowIndex, DataGridViewRow dataGridViewRow) throw new InvalidOperationException(string.Format(SR.DataGridView_RowAlreadyBelongsToDataGridView)); } - if (this.DataGridView.NewRowIndex != -1 && rowIndex == this.Count) + if (DataGridView.NewRowIndex != -1 && rowIndex == Count) { // Trying to insert after the 'new' row. - Debug.Assert(this.DataGridView.AllowUserToAddRowsInternal); + Debug.Assert(DataGridView.AllowUserToAddRowsInternal); throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_NoInsertionAfterNewRow)); } - if (this.DataGridView.Columns.Count == 0) + if (DataGridView.Columns.Count == 0) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_NoColumns)); } - if (dataGridViewRow.Cells.Count > this.DataGridView.Columns.Count) + if (dataGridViewRow.Cells.Count > DataGridView.Columns.Count) { throw new ArgumentException(string.Format(SR.DataGridViewRowCollection_TooManyCells), "dataGridViewRow"); } @@ -1552,61 +1552,61 @@ internal void InsertInternal(int rowIndex, DataGridViewRow dataGridViewRow) internal void InsertInternal(int rowIndex, DataGridViewRow dataGridViewRow, bool force) { - Debug.Assert(this.DataGridView != null); - Debug.Assert(rowIndex >= 0 && rowIndex <= this.Count); + Debug.Assert(DataGridView != null); + Debug.Assert(rowIndex >= 0 && rowIndex <= Count); Debug.Assert(dataGridViewRow != null); Debug.Assert(dataGridViewRow.DataGridView == null); - Debug.Assert(!this.DataGridView.NoDimensionChangeAllowed); - Debug.Assert(this.DataGridView.NewRowIndex == -1 || rowIndex != this.Count); + Debug.Assert(!DataGridView.NoDimensionChangeAllowed); + Debug.Assert(DataGridView.NewRowIndex == -1 || rowIndex != Count); Debug.Assert(!dataGridViewRow.Selected); Point newCurrentCell = new Point(-1, -1); if (force) { - if (this.DataGridView.Columns.Count == 0) + if (DataGridView.Columns.Count == 0) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_NoColumns)); } - if (dataGridViewRow.Cells.Count > this.DataGridView.Columns.Count) + if (dataGridViewRow.Cells.Count > DataGridView.Columns.Count) { throw new ArgumentException(string.Format(SR.DataGridViewRowCollection_TooManyCells), "dataGridViewRow"); } } - this.DataGridView.CompleteCellsCollection(dataGridViewRow); - Debug.Assert(dataGridViewRow.Cells.Count == this.DataGridView.Columns.Count); - this.DataGridView.OnInsertingRow(rowIndex, dataGridViewRow, dataGridViewRow.State, ref newCurrentCell, true, 1, force); // will throw an exception if the insertion is illegal + DataGridView.CompleteCellsCollection(dataGridViewRow); + Debug.Assert(dataGridViewRow.Cells.Count == DataGridView.Columns.Count); + DataGridView.OnInsertingRow(rowIndex, dataGridViewRow, dataGridViewRow.State, ref newCurrentCell, true, 1, force); // will throw an exception if the insertion is illegal int columnIndex = 0; foreach (DataGridViewCell dataGridViewCell in dataGridViewRow.Cells) { - dataGridViewCell.DataGridViewInternal = this.dataGridView; + dataGridViewCell.DataGridViewInternal = dataGridView; Debug.Assert(dataGridViewCell.OwningRow == dataGridViewRow); if (dataGridViewCell.ColumnIndex == -1) { - dataGridViewCell.OwningColumnInternal = this.DataGridView.Columns[columnIndex]; + dataGridViewCell.OwningColumnInternal = DataGridView.Columns[columnIndex]; } columnIndex++; } if (dataGridViewRow.HasHeaderCell) { - dataGridViewRow.HeaderCell.DataGridViewInternal = this.DataGridView; + dataGridViewRow.HeaderCell.DataGridViewInternal = DataGridView; dataGridViewRow.HeaderCell.OwningRowInternal = dataGridViewRow; } - this.SharedList.Insert(rowIndex, dataGridViewRow); + SharedList.Insert(rowIndex, dataGridViewRow); Debug.Assert((dataGridViewRow.State & (DataGridViewElementStates.Selected | DataGridViewElementStates.Displayed)) == 0); - this.rowStates.Insert(rowIndex, dataGridViewRow.State); - Debug.Assert(this.rowStates.Count == this.SharedList.Count); + rowStates.Insert(rowIndex, dataGridViewRow.State); + Debug.Assert(rowStates.Count == SharedList.Count); #if DEBUG - this.DataGridView.dataStoreAccessAllowed = false; - this.cachedRowHeightsAccessAllowed = false; - this.cachedRowCountsAccessAllowed = false; + DataGridView.dataStoreAccessAllowed = false; + cachedRowHeightsAccessAllowed = false; + cachedRowCountsAccessAllowed = false; #endif - dataGridViewRow.DataGridViewInternal = this.dataGridView; - if (!RowIsSharable(rowIndex) || RowHasValueOrToolTipText(dataGridViewRow) || this.IsCollectionChangedListenedTo) + dataGridViewRow.DataGridViewInternal = dataGridView; + if (!RowIsSharable(rowIndex) || RowHasValueOrToolTipText(dataGridViewRow) || IsCollectionChangedListenedTo) { dataGridViewRow.IndexInternal = rowIndex; Debug.Assert(dataGridViewRow.State == SharedRowState(rowIndex)); @@ -1621,12 +1621,12 @@ public virtual void InsertCopy(int indexSource, int indexDestination) public virtual void InsertCopies(int indexSource, int indexDestination, int count) { - if (this.DataGridView.DataSource != null) + if (DataGridView.DataSource != null) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_AddUnboundRow)); } - if (this.DataGridView.NoDimensionChangeAllowed) + if (DataGridView.NoDimensionChangeAllowed) { throw new InvalidOperationException(string.Format(SR.DataGridView_ForbiddenOperationInEventHandler)); } @@ -1636,14 +1636,14 @@ public virtual void InsertCopies(int indexSource, int indexDestination, int coun private void InsertCopiesPrivate(int indexSource, int indexDestination, int count) { - Debug.Assert(this.DataGridView != null); + Debug.Assert(DataGridView != null); - if (indexSource < 0 || this.Count <= indexSource) + if (indexSource < 0 || Count <= indexSource) { throw new ArgumentOutOfRangeException(nameof(indexSource), string.Format(SR.DataGridViewRowCollection_IndexSourceOutOfRange)); } - if (indexDestination < 0 || this.Count < indexDestination) + if (indexDestination < 0 || Count < indexDestination) { throw new ArgumentOutOfRangeException(nameof(indexDestination), string.Format(SR.DataGridViewRowCollection_IndexDestinationOutOfRange)); } @@ -1653,10 +1653,10 @@ private void InsertCopiesPrivate(int indexSource, int indexDestination, int coun throw new ArgumentOutOfRangeException(nameof(count), string.Format(SR.DataGridViewRowCollection_CountOutOfRange)); } - if (this.DataGridView.NewRowIndex != -1 && indexDestination == this.Count) + if (DataGridView.NewRowIndex != -1 && indexDestination == Count) { // Trying to insert after the 'new' row. - Debug.Assert(this.DataGridView.AllowUserToAddRowsInternal); + Debug.Assert(DataGridView.AllowUserToAddRowsInternal); throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_NoInsertionAfterNewRow)); } @@ -1672,34 +1672,34 @@ private void InsertCopiesPrivate(DataGridViewRow rowTemplate, DataGridViewElemen if (count > 1) { // Done once only, continue to check if this is OK - will throw an exception if the insertion is illegal. - this.DataGridView.OnInsertingRow(indexDestination, rowTemplate, rowTemplateState, ref newCurrentCell, true, count, false /*force*/); + DataGridView.OnInsertingRow(indexDestination, rowTemplate, rowTemplateState, ref newCurrentCell, true, count, false /*force*/); for (int i = 0; i < count; i++) { - this.SharedList.Insert(indexDestination + i, rowTemplate); - this.rowStates.Insert(indexDestination + i, rowTemplateState); + SharedList.Insert(indexDestination + i, rowTemplate); + rowStates.Insert(indexDestination + i, rowTemplateState); } #if DEBUG - this.DataGridView.dataStoreAccessAllowed = false; - this.cachedRowHeightsAccessAllowed = false; - this.cachedRowCountsAccessAllowed = false; + DataGridView.dataStoreAccessAllowed = false; + cachedRowHeightsAccessAllowed = false; + cachedRowCountsAccessAllowed = false; #endif // Only calling this once instead of 'count' times. Continue to check if this is OK. - this.DataGridView.OnInsertedRow_PreNotification(indexDestination, count); + DataGridView.OnInsertedRow_PreNotification(indexDestination, count); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null), indexDestination, count, false, true, false, newCurrentCell); for (int i = 0; i < count; i++) { - this.DataGridView.OnInsertedRow_PostNotification(indexDestination + i, newCurrentCell, i == count - 1); + DataGridView.OnInsertedRow_PostNotification(indexDestination + i, newCurrentCell, i == count - 1); } } else { - this.DataGridView.OnInsertingRow(indexDestination, rowTemplate, rowTemplateState, ref newCurrentCell, true, 1, false /*force*/); // will throw an exception if the insertion is illegal - this.SharedList.Insert(indexDestination, rowTemplate); - this.rowStates.Insert(indexDestination, rowTemplateState); + DataGridView.OnInsertingRow(indexDestination, rowTemplate, rowTemplateState, ref newCurrentCell, true, 1, false /*force*/); // will throw an exception if the insertion is illegal + SharedList.Insert(indexDestination, rowTemplate); + rowStates.Insert(indexDestination, rowTemplateState); #if DEBUG - this.DataGridView.dataStoreAccessAllowed = false; - this.cachedRowHeightsAccessAllowed = false; - this.cachedRowCountsAccessAllowed = false; + DataGridView.dataStoreAccessAllowed = false; + cachedRowHeightsAccessAllowed = false; + cachedRowCountsAccessAllowed = false; #endif OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, SharedRow(indexDestination)), indexDestination, count, false, true, false, newCurrentCell); } @@ -1708,27 +1708,27 @@ private void InsertCopiesPrivate(DataGridViewRow rowTemplate, DataGridViewElemen { // Sets this.DataGridView.dataStoreAccessAllowed to false InsertDuplicateRow(indexDestination, rowTemplate, true, ref newCurrentCell); - Debug.Assert(this.rowStates.Count == this.SharedList.Count); + Debug.Assert(rowStates.Count == SharedList.Count); if (count > 1) { - this.DataGridView.OnInsertedRow_PreNotification(indexDestination, 1); + DataGridView.OnInsertedRow_PreNotification(indexDestination, 1); if (RowIsSharable(indexDestination)) { DataGridViewRow rowTemplate2 = SharedRow(indexDestination); // Done once only, continue to check if this is OK - will throw an exception if the insertion is illegal. - this.DataGridView.OnInsertingRow(indexDestination + 1, rowTemplate2, rowTemplateState, ref newCurrentCell, false, count - 1, false /*force*/); + DataGridView.OnInsertingRow(indexDestination + 1, rowTemplate2, rowTemplateState, ref newCurrentCell, false, count - 1, false /*force*/); for (int i = 1; i < count; i++) { - this.SharedList.Insert(indexDestination + i, rowTemplate2); - this.rowStates.Insert(indexDestination + i, rowTemplateState); + SharedList.Insert(indexDestination + i, rowTemplate2); + rowStates.Insert(indexDestination + i, rowTemplateState); } #if DEBUG - this.DataGridView.dataStoreAccessAllowed = false; - this.cachedRowHeightsAccessAllowed = false; - this.cachedRowCountsAccessAllowed = false; + DataGridView.dataStoreAccessAllowed = false; + cachedRowHeightsAccessAllowed = false; + cachedRowCountsAccessAllowed = false; #endif // Only calling this once instead of 'count-1' times. Continue to check if this is OK. - this.DataGridView.OnInsertedRow_PreNotification(indexDestination + 1, count - 1); + DataGridView.OnInsertedRow_PreNotification(indexDestination + 1, count - 1); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null), indexDestination, count, false, true, false, newCurrentCell); } else @@ -1737,20 +1737,20 @@ private void InsertCopiesPrivate(DataGridViewRow rowTemplate, DataGridViewElemen for (int i = 1; i < count; i++) { InsertDuplicateRow(indexDestination + i, rowTemplate, false, ref newCurrentCell); - Debug.Assert(this.rowStates.Count == this.SharedList.Count); + Debug.Assert(rowStates.Count == SharedList.Count); UnshareRow(indexDestination + i); - this.DataGridView.OnInsertedRow_PreNotification(indexDestination + i, 1); + DataGridView.OnInsertedRow_PreNotification(indexDestination + i, 1); } OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null), indexDestination, count, false, true, false, newCurrentCell); } for (int i = 0; i < count; i++) { - this.DataGridView.OnInsertedRow_PostNotification(indexDestination + i, newCurrentCell, i == count - 1); + DataGridView.OnInsertedRow_PostNotification(indexDestination + i, newCurrentCell, i == count - 1); } } else { - if (this.IsCollectionChangedListenedTo) + if (IsCollectionChangedListenedTo) { UnshareRow(indexDestination); } @@ -1761,36 +1761,36 @@ private void InsertCopiesPrivate(DataGridViewRow rowTemplate, DataGridViewElemen private void InsertDuplicateRow(int indexDestination, DataGridViewRow rowTemplate, bool firstInsertion, ref Point newCurrentCell) { - Debug.Assert(this.DataGridView != null); + Debug.Assert(DataGridView != null); DataGridViewRow dataGridViewRow = (DataGridViewRow)rowTemplate.Clone(); dataGridViewRow.StateInternal = DataGridViewElementStates.None; - dataGridViewRow.DataGridViewInternal = this.dataGridView; + dataGridViewRow.DataGridViewInternal = dataGridView; DataGridViewCellCollection dgvcc = dataGridViewRow.Cells; int columnIndex = 0; foreach (DataGridViewCell dataGridViewCell in dgvcc) { - dataGridViewCell.DataGridViewInternal = this.dataGridView; - dataGridViewCell.OwningColumnInternal = this.DataGridView.Columns[columnIndex]; + dataGridViewCell.DataGridViewInternal = dataGridView; + dataGridViewCell.OwningColumnInternal = DataGridView.Columns[columnIndex]; columnIndex++; } DataGridViewElementStates rowState = rowTemplate.State & ~(DataGridViewElementStates.Selected | DataGridViewElementStates.Displayed); if (dataGridViewRow.HasHeaderCell) { - dataGridViewRow.HeaderCell.DataGridViewInternal = this.dataGridView; + dataGridViewRow.HeaderCell.DataGridViewInternal = dataGridView; dataGridViewRow.HeaderCell.OwningRowInternal = dataGridViewRow; } - this.DataGridView.OnInsertingRow(indexDestination, dataGridViewRow, rowState, ref newCurrentCell, firstInsertion, 1, false /*force*/); // will throw an exception if the insertion is illegal + DataGridView.OnInsertingRow(indexDestination, dataGridViewRow, rowState, ref newCurrentCell, firstInsertion, 1, false /*force*/); // will throw an exception if the insertion is illegal Debug.Assert(dataGridViewRow.Index == -1); - this.SharedList.Insert(indexDestination, dataGridViewRow); - this.rowStates.Insert(indexDestination, rowState); - Debug.Assert(this.rowStates.Count == this.SharedList.Count); + SharedList.Insert(indexDestination, dataGridViewRow); + rowStates.Insert(indexDestination, rowState); + Debug.Assert(rowStates.Count == SharedList.Count); #if DEBUG - this.DataGridView.dataStoreAccessAllowed = false; - this.cachedRowHeightsAccessAllowed = false; - this.cachedRowCountsAccessAllowed = false; + DataGridView.dataStoreAccessAllowed = false; + cachedRowHeightsAccessAllowed = false; + cachedRowCountsAccessAllowed = false; #endif } @@ -1799,7 +1799,7 @@ private void InsertDuplicateRow(int indexDestination, DataGridViewRow rowTemplat /// public virtual void InsertRange(int rowIndex, params DataGridViewRow[] dataGridViewRows) { - Debug.Assert(this.DataGridView != null); + Debug.Assert(DataGridView != null); if (dataGridViewRows == null) { @@ -1812,29 +1812,29 @@ public virtual void InsertRange(int rowIndex, params DataGridViewRow[] dataGridV return; } - if (rowIndex < 0 || rowIndex > this.Count) + if (rowIndex < 0 || rowIndex > Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex), string.Format(SR.DataGridViewRowCollection_IndexDestinationOutOfRange)); } - if (this.DataGridView.NoDimensionChangeAllowed) + if (DataGridView.NoDimensionChangeAllowed) { throw new InvalidOperationException(string.Format(SR.DataGridView_ForbiddenOperationInEventHandler)); } - if (this.DataGridView.NewRowIndex != -1 && rowIndex == this.Count) + if (DataGridView.NewRowIndex != -1 && rowIndex == Count) { // Trying to insert after the 'new' row. - Debug.Assert(this.DataGridView.AllowUserToAddRowsInternal); + Debug.Assert(DataGridView.AllowUserToAddRowsInternal); throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_NoInsertionAfterNewRow)); } - if (this.DataGridView.DataSource != null) + if (DataGridView.DataSource != null) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_AddUnboundRow)); } - if (this.DataGridView.Columns.Count == 0) + if (DataGridView.Columns.Count == 0) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_NoColumns)); } @@ -1842,49 +1842,49 @@ public virtual void InsertRange(int rowIndex, params DataGridViewRow[] dataGridV Point newCurrentCell = new Point(-1, -1); // OnInsertingRows checks for Selected flag of each row, among other things. - this.DataGridView.OnInsertingRows(rowIndex, dataGridViewRows, ref newCurrentCell); // will throw an exception if the insertion is illegal + DataGridView.OnInsertingRows(rowIndex, dataGridViewRows, ref newCurrentCell); // will throw an exception if the insertion is illegal int rowIndexInserted = rowIndex; foreach (DataGridViewRow dataGridViewRow in dataGridViewRows) { - Debug.Assert(dataGridViewRow.Cells.Count == this.DataGridView.Columns.Count); + Debug.Assert(dataGridViewRow.Cells.Count == DataGridView.Columns.Count); int columnIndex = 0; foreach (DataGridViewCell dataGridViewCell in dataGridViewRow.Cells) { - dataGridViewCell.DataGridViewInternal = this.dataGridView; + dataGridViewCell.DataGridViewInternal = dataGridView; Debug.Assert(dataGridViewCell.OwningRow == dataGridViewRow); if (dataGridViewCell.ColumnIndex == -1) { - dataGridViewCell.OwningColumnInternal = this.DataGridView.Columns[columnIndex]; + dataGridViewCell.OwningColumnInternal = DataGridView.Columns[columnIndex]; } columnIndex++; } if (dataGridViewRow.HasHeaderCell) { - dataGridViewRow.HeaderCell.DataGridViewInternal = this.DataGridView; + dataGridViewRow.HeaderCell.DataGridViewInternal = DataGridView; dataGridViewRow.HeaderCell.OwningRowInternal = dataGridViewRow; } - this.SharedList.Insert(rowIndexInserted, dataGridViewRow); + SharedList.Insert(rowIndexInserted, dataGridViewRow); Debug.Assert((dataGridViewRow.State & (DataGridViewElementStates.Selected | DataGridViewElementStates.Displayed)) == 0); - this.rowStates.Insert(rowIndexInserted, dataGridViewRow.State); - Debug.Assert(this.rowStates.Count == this.SharedList.Count); + rowStates.Insert(rowIndexInserted, dataGridViewRow.State); + Debug.Assert(rowStates.Count == SharedList.Count); #if DEBUG - this.DataGridView.dataStoreAccessAllowed = false; - this.cachedRowHeightsAccessAllowed = false; - this.cachedRowCountsAccessAllowed = false; + DataGridView.dataStoreAccessAllowed = false; + cachedRowHeightsAccessAllowed = false; + cachedRowCountsAccessAllowed = false; #endif dataGridViewRow.IndexInternal = rowIndexInserted; Debug.Assert(dataGridViewRow.State == SharedRowState(rowIndexInserted)); - dataGridViewRow.DataGridViewInternal = this.dataGridView; + dataGridViewRow.DataGridViewInternal = dataGridView; rowIndexInserted++; } - this.DataGridView.OnInsertedRows_PreNotification(rowIndex, dataGridViewRows); + DataGridView.OnInsertedRows_PreNotification(rowIndex, dataGridViewRows); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null), rowIndex, dataGridViewRows.Length, false, true, false, newCurrentCell); - this.DataGridView.OnInsertedRows_PostNotification(dataGridViewRows, newCurrentCell); + DataGridView.OnInsertedRows_PostNotification(dataGridViewRows, newCurrentCell); } internal void InvalidateCachedRowCount(DataGridViewElementStates includeFilter) @@ -1902,23 +1902,23 @@ internal void InvalidateCachedRowCount(DataGridViewElementStates includeFilter) } else if (includeFilter == DataGridViewElementStates.Frozen) { - this.rowCountsVisibleFrozen = -1; + rowCountsVisibleFrozen = -1; } else if (includeFilter == DataGridViewElementStates.Selected) { - this.rowCountsVisibleSelected = -1; + rowCountsVisibleSelected = -1; } #if DEBUG - this.cachedRowCountsAccessAllowed = true; + cachedRowCountsAccessAllowed = true; #endif } internal void InvalidateCachedRowCounts() { - this.rowCountsVisible = this.rowCountsVisibleFrozen = this.rowCountsVisibleSelected = -1; + rowCountsVisible = rowCountsVisibleFrozen = rowCountsVisibleSelected = -1; #if DEBUG - this.cachedRowCountsAccessAllowed = true; + cachedRowCountsAccessAllowed = true; #endif } @@ -1937,27 +1937,27 @@ internal void InvalidateCachedRowsHeight(DataGridViewElementStates includeFilter } else if (includeFilter == DataGridViewElementStates.Frozen) { - this.rowsHeightVisibleFrozen = -1; + rowsHeightVisibleFrozen = -1; } #if DEBUG - this.cachedRowHeightsAccessAllowed = true; + cachedRowHeightsAccessAllowed = true; #endif } internal void InvalidateCachedRowsHeights() { - this.rowsHeightVisible = this.rowsHeightVisibleFrozen = -1; + rowsHeightVisible = rowsHeightVisibleFrozen = -1; #if DEBUG - this.cachedRowHeightsAccessAllowed = true; + cachedRowHeightsAccessAllowed = true; #endif } protected virtual void OnCollectionChanged(CollectionChangeEventArgs e) { - if (this.onCollectionChanged != null) + if (onCollectionChanged != null) { - this.onCollectionChanged(this, e); + onCollectionChanged(this, e); } } @@ -2013,7 +2013,7 @@ private void OnCollectionChanged_PreNotification(CollectionChangeAction cca, ref DataGridViewRow dataGridViewRow, bool changeIsInsertion) { - Debug.Assert(this.DataGridView != null); + Debug.Assert(DataGridView != null); bool useRowShortcut = false; bool computeVisibleRows = false; switch (cca) @@ -2030,7 +2030,7 @@ private void OnCollectionChanged_PreNotification(CollectionChangeAction cca, } else { - int firstDisplayedRowIndex = this.DataGridView.FirstDisplayedRowIndex; + int firstDisplayedRowIndex = DataGridView.FirstDisplayedRowIndex; if (firstDisplayedRowIndex != -1) { firstDisplayedRowHeight = SharedRow(firstDisplayedRowIndex).GetHeight(firstDisplayedRowIndex); @@ -2038,32 +2038,32 @@ private void OnCollectionChanged_PreNotification(CollectionChangeAction cca, } if (changeIsInsertion) { - this.DataGridView.OnInsertedRow_PreNotification(rowIndex, 1); + DataGridView.OnInsertedRow_PreNotification(rowIndex, 1); if (!useRowShortcut) { if ((GetRowState(rowIndex) & DataGridViewElementStates.Frozen) != 0) { // Inserted row is frozen - useRowShortcut = this.DataGridView.FirstDisplayedScrollingRowIndex == -1 && - GetRowsHeightExceedLimit(DataGridViewElementStates.Visible, 0, rowIndex, this.DataGridView.LayoutInfo.Data.Height); + useRowShortcut = DataGridView.FirstDisplayedScrollingRowIndex == -1 && + GetRowsHeightExceedLimit(DataGridViewElementStates.Visible, 0, rowIndex, DataGridView.LayoutInfo.Data.Height); } - else if (this.DataGridView.FirstDisplayedScrollingRowIndex != -1 && - rowIndex > this.DataGridView.FirstDisplayedScrollingRowIndex) + else if (DataGridView.FirstDisplayedScrollingRowIndex != -1 && + rowIndex > DataGridView.FirstDisplayedScrollingRowIndex) { - useRowShortcut = GetRowsHeightExceedLimit(DataGridViewElementStates.Visible, 0, rowIndex, this.DataGridView.LayoutInfo.Data.Height + this.DataGridView.VerticalScrollingOffset) && - firstDisplayedRowHeight <= this.DataGridView.LayoutInfo.Data.Height; + useRowShortcut = GetRowsHeightExceedLimit(DataGridViewElementStates.Visible, 0, rowIndex, DataGridView.LayoutInfo.Data.Height + DataGridView.VerticalScrollingOffset) && + firstDisplayedRowHeight <= DataGridView.LayoutInfo.Data.Height; } } } else { - this.DataGridView.OnAddedRow_PreNotification(rowIndex); + DataGridView.OnAddedRow_PreNotification(rowIndex); if (!useRowShortcut) { - int displayedRowsHeightBeforeAddition = GetRowsHeight(DataGridViewElementStates.Visible) - this.DataGridView.VerticalScrollingOffset - dataGridViewRow.GetHeight(rowIndex); + int displayedRowsHeightBeforeAddition = GetRowsHeight(DataGridViewElementStates.Visible) - DataGridView.VerticalScrollingOffset - dataGridViewRow.GetHeight(rowIndex); dataGridViewRow = SharedRow(rowIndex); - useRowShortcut = this.DataGridView.LayoutInfo.Data.Height < displayedRowsHeightBeforeAddition && - firstDisplayedRowHeight <= this.DataGridView.LayoutInfo.Data.Height; + useRowShortcut = DataGridView.LayoutInfo.Data.Height < displayedRowsHeightBeforeAddition && + firstDisplayedRowHeight <= DataGridView.LayoutInfo.Data.Height; } } break; @@ -2078,30 +2078,30 @@ private void OnCollectionChanged_PreNotification(CollectionChangeAction cca, // Can't do this earlier since it would break UpdateRowCaches this.rowStates.RemoveAt(rowIndex); - this.SharedList.RemoveAt(rowIndex); + SharedList.RemoveAt(rowIndex); #if DEBUG - this.DataGridView.dataStoreAccessAllowed = false; + DataGridView.dataStoreAccessAllowed = false; #endif - this.DataGridView.OnRemovedRow_PreNotification(rowIndex); + DataGridView.OnRemovedRow_PreNotification(rowIndex); if (deletedRowVisible) { if (deletedRowFrozen) { // Delete row is frozen - useRowShortcut = this.DataGridView.FirstDisplayedScrollingRowIndex == -1 && - GetRowsHeightExceedLimit(DataGridViewElementStates.Visible, 0, rowIndex, this.DataGridView.LayoutInfo.Data.Height + SystemInformation.HorizontalScrollBarHeight); + useRowShortcut = DataGridView.FirstDisplayedScrollingRowIndex == -1 && + GetRowsHeightExceedLimit(DataGridViewElementStates.Visible, 0, rowIndex, DataGridView.LayoutInfo.Data.Height + SystemInformation.HorizontalScrollBarHeight); } - else if (this.DataGridView.FirstDisplayedScrollingRowIndex != -1 && - rowIndex > this.DataGridView.FirstDisplayedScrollingRowIndex) + else if (DataGridView.FirstDisplayedScrollingRowIndex != -1 && + rowIndex > DataGridView.FirstDisplayedScrollingRowIndex) { int firstDisplayedRowHeight = 0; - int firstDisplayedRowIndex = this.DataGridView.FirstDisplayedRowIndex; + int firstDisplayedRowIndex = DataGridView.FirstDisplayedRowIndex; if (firstDisplayedRowIndex != -1) { firstDisplayedRowHeight = SharedRow(firstDisplayedRowIndex).GetHeight(firstDisplayedRowIndex); } - useRowShortcut = GetRowsHeightExceedLimit(DataGridViewElementStates.Visible, 0, rowIndex, this.DataGridView.LayoutInfo.Data.Height + this.DataGridView.VerticalScrollingOffset + SystemInformation.HorizontalScrollBarHeight) && - firstDisplayedRowHeight <= this.DataGridView.LayoutInfo.Data.Height; + useRowShortcut = GetRowsHeightExceedLimit(DataGridViewElementStates.Visible, 0, rowIndex, DataGridView.LayoutInfo.Data.Height + DataGridView.VerticalScrollingOffset + SystemInformation.HorizontalScrollBarHeight) && + firstDisplayedRowHeight <= DataGridView.LayoutInfo.Data.Height; } } else @@ -2125,7 +2125,7 @@ private void OnCollectionChanged_PreNotification(CollectionChangeAction cca, break; } } - this.DataGridView.ResetUIState(useRowShortcut, computeVisibleRows); + DataGridView.ResetUIState(useRowShortcut, computeVisibleRows); } private void OnCollectionChanged_PostNotification(CollectionChangeAction cca, @@ -2137,18 +2137,18 @@ private void OnCollectionChanged_PostNotification(CollectionChangeAction cca, bool recreateNewRow, Point newCurrentCell) { - Debug.Assert(this.DataGridView != null); + Debug.Assert(DataGridView != null); if (changeIsDeletion) { - this.DataGridView.OnRowsRemovedInternal(rowIndex, rowCount); + DataGridView.OnRowsRemovedInternal(rowIndex, rowCount); } else { - this.DataGridView.OnRowsAddedInternal(rowIndex, rowCount); + DataGridView.OnRowsAddedInternal(rowIndex, rowCount); } #if DEBUG - this.DataGridView.dataStoreAccessAllowed = true; + DataGridView.dataStoreAccessAllowed = true; #endif switch (cca) { @@ -2156,18 +2156,18 @@ private void OnCollectionChanged_PostNotification(CollectionChangeAction cca, { if (changeIsInsertion) { - this.DataGridView.OnInsertedRow_PostNotification(rowIndex, newCurrentCell, true); + DataGridView.OnInsertedRow_PostNotification(rowIndex, newCurrentCell, true); } else { - this.DataGridView.OnAddedRow_PostNotification(rowIndex); + DataGridView.OnAddedRow_PostNotification(rowIndex); } break; } case CollectionChangeAction.Remove: { - this.DataGridView.OnRemovedRow_PostNotification(dataGridViewRow, newCurrentCell); + DataGridView.OnRemovedRow_PostNotification(dataGridViewRow, newCurrentCell); break; } @@ -2175,13 +2175,13 @@ private void OnCollectionChanged_PostNotification(CollectionChangeAction cca, { if (changeIsDeletion) { - this.DataGridView.OnClearedRows(); + DataGridView.OnClearedRows(); } break; } } - this.DataGridView.OnRowCollectionChanged_PostNotification(recreateNewRow, newCurrentCell.X == -1, cca, dataGridViewRow, rowIndex); + DataGridView.OnRowCollectionChanged_PostNotification(recreateNewRow, newCurrentCell.X == -1, cca, dataGridViewRow, rowIndex); } [ @@ -2194,7 +2194,7 @@ public virtual void Remove(DataGridViewRow dataGridViewRow) throw new ArgumentNullException(nameof(dataGridViewRow)); } - if (dataGridViewRow.DataGridView != this.DataGridView) + if (dataGridViewRow.DataGridView != DataGridView) { throw new ArgumentException(string.Format(SR.DataGridView_RowDoesNotBelongToDataGridView), "dataGridViewRow"); } @@ -2211,25 +2211,25 @@ public virtual void Remove(DataGridViewRow dataGridViewRow) public virtual void RemoveAt(int index) { - if (index < 0 || index >= this.Count) + if (index < 0 || index >= Count) { throw new ArgumentOutOfRangeException(nameof(index), string.Format(SR.DataGridViewRowCollection_RowIndexOutOfRange)); } - if (this.DataGridView.NewRowIndex == index) + if (DataGridView.NewRowIndex == index) { - Debug.Assert(this.DataGridView.AllowUserToAddRowsInternal); + Debug.Assert(DataGridView.AllowUserToAddRowsInternal); throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_CannotDeleteNewRow)); } - if (this.DataGridView.NoDimensionChangeAllowed) + if (DataGridView.NoDimensionChangeAllowed) { throw new InvalidOperationException(string.Format(SR.DataGridView_ForbiddenOperationInEventHandler)); } - if (this.DataGridView.DataSource != null) + if (DataGridView.DataSource != null) { - IBindingList list = this.DataGridView.DataConnection.List as IBindingList; + IBindingList list = DataGridView.DataConnection.List as IBindingList; if (list != null && list.AllowRemove && list.SupportsChangeNotification) { ((IList)list).RemoveAt(index); @@ -2249,25 +2249,25 @@ internal void RemoveAtInternal(int index, bool force) { // If force is true, the underlying data is gone and can't be accessed anymore. - Debug.Assert(index >= 0 && index < this.Count); - Debug.Assert(this.DataGridView != null); - Debug.Assert(!this.DataGridView.NoDimensionChangeAllowed); + Debug.Assert(index >= 0 && index < Count); + Debug.Assert(DataGridView != null); + Debug.Assert(!DataGridView.NoDimensionChangeAllowed); DataGridViewRow dataGridViewRow = SharedRow(index); Point newCurrentCell = new Point(-1, -1); - if (this.IsCollectionChangedListenedTo || dataGridViewRow.GetDisplayed(index)) + if (IsCollectionChangedListenedTo || dataGridViewRow.GetDisplayed(index)) { dataGridViewRow = this[index]; // need to unshare row because dev is listening to OnCollectionChanged event or the row is displayed } dataGridViewRow = SharedRow(index); - Debug.Assert(this.DataGridView != null); - this.DataGridView.OnRemovingRow(index, out newCurrentCell, force); + Debug.Assert(DataGridView != null); + DataGridView.OnRemovingRow(index, out newCurrentCell, force); UpdateRowCaches(index, ref dataGridViewRow, false /*adding*/); if (dataGridViewRow.Index != -1) { - this.rowStates[index] = dataGridViewRow.State; + rowStates[index] = dataGridViewRow.State; // Only detach unshared rows, since a shared row has never been accessed by the user dataGridViewRow.DetachFromDataGridView(); } @@ -2296,7 +2296,7 @@ private static bool RowHasValueOrToolTipText(DataGridViewRow dataGridViewRow) internal bool RowIsSharable(int index) { Debug.Assert(index >= 0); - Debug.Assert(index < this.Count); + Debug.Assert(index < Count); DataGridViewRow dataGridViewRow = SharedRow(index); if (dataGridViewRow.Index != -1) @@ -2309,7 +2309,7 @@ internal bool RowIsSharable(int index) DataGridViewCellCollection cells = dataGridViewRow.Cells; foreach (DataGridViewCell dataGridViewCell in cells) { - if ((dataGridViewCell.State & ~(dataGridViewCell.CellStateFromColumnRowStates(this.rowStates[index]))) != 0) + if ((dataGridViewCell.State & ~(dataGridViewCell.CellStateFromColumnRowStates(rowStates[index]))) != 0) { return false; } @@ -2325,7 +2325,7 @@ internal void SetRowState(int rowIndex, DataGridViewElementStates state, bool va if (dataGridViewRow.Index == -1) { // row is shared - if (((this.rowStates[rowIndex] & state) != 0) != value) + if (((rowStates[rowIndex] & state) != 0) != value) { if (state == DataGridViewElementStates.Frozen || state == DataGridViewElementStates.Visible || @@ -2335,11 +2335,11 @@ internal void SetRowState(int rowIndex, DataGridViewElementStates state, bool va } if (value) { - this.rowStates[rowIndex] = this.rowStates[rowIndex] | state; + rowStates[rowIndex] = rowStates[rowIndex] | state; } else { - this.rowStates[rowIndex] = this.rowStates[rowIndex] & ~state; + rowStates[rowIndex] = rowStates[rowIndex] & ~state; } dataGridViewRow.OnSharedStateChanged(rowIndex, state); } @@ -2390,15 +2390,15 @@ internal void SetRowState(int rowIndex, DataGridViewElementStates state, bool va internal DataGridViewElementStates SharedRowState(int rowIndex) { - return this.rowStates[rowIndex]; + return rowStates[rowIndex]; } internal void Sort(IComparer customComparer, bool ascending) { - if (this.items.Count > 0) + if (items.Count > 0) { RowComparer rowComparer = new RowComparer(this, customComparer, ascending); - this.items.CustomSort(rowComparer); + items.CustomSort(rowComparer); // Caller takes care of the dataGridView invalidation } } @@ -2407,7 +2407,7 @@ internal void SwapSortedRows(int rowIndex1, int rowIndex2) { // Deal with the current cell address updates + // selected rows updates. - this.DataGridView.SwapSortedRows(rowIndex1, rowIndex2); + DataGridView.SwapSortedRows(rowIndex1, rowIndex2); DataGridViewRow dataGridViewRow1 = SharedRow(rowIndex1); DataGridViewRow dataGridViewRow2 = SharedRow(rowIndex2); @@ -2421,10 +2421,10 @@ internal void SwapSortedRows(int rowIndex1, int rowIndex2) dataGridViewRow2.IndexInternal = rowIndex1; } - if (this.DataGridView.VirtualMode) + if (DataGridView.VirtualMode) { // All cell contents on the involved rows need to be swapped - int columnCount = this.DataGridView.Columns.Count; + int columnCount = DataGridView.Columns.Count; for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) { @@ -2437,9 +2437,9 @@ internal void SwapSortedRows(int rowIndex1, int rowIndex2) } } - object item = this.items[rowIndex1]; - this.items[rowIndex1] = this.items[rowIndex2]; - this.items[rowIndex2] = item; + object item = items[rowIndex1]; + items[rowIndex1] = items[rowIndex2]; + items[rowIndex2] = item; DataGridViewElementStates rowStates = this.rowStates[rowIndex1]; this.rowStates[rowIndex1] = this.rowStates[rowIndex2]; @@ -2455,16 +2455,16 @@ private void UnshareRow(int rowIndex) private void UpdateRowCaches(int rowIndex, ref DataGridViewRow dataGridViewRow, bool adding) { - if (this.rowCountsVisible != -1 || this.rowCountsVisibleFrozen != -1 || this.rowCountsVisibleSelected != -1 || - this.rowsHeightVisible != -1 || this.rowsHeightVisibleFrozen != -1) + if (rowCountsVisible != -1 || rowCountsVisibleFrozen != -1 || rowCountsVisibleSelected != -1 || + rowsHeightVisible != -1 || rowsHeightVisibleFrozen != -1) { DataGridViewElementStates rowStates = GetRowState(rowIndex); if ((rowStates & DataGridViewElementStates.Visible) != 0) { int rowCountIncrement = adding ? 1 : -1; int rowHeightIncrement = 0; - if (this.rowsHeightVisible != -1 || - (this.rowsHeightVisibleFrozen != -1 && + if (rowsHeightVisible != -1 || + (rowsHeightVisibleFrozen != -1 && ((rowStates & (DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)) == (DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)))) { // dataGridViewRow may become unshared in GetHeight call @@ -2472,42 +2472,42 @@ private void UpdateRowCaches(int rowIndex, ref DataGridViewRow dataGridViewRow, dataGridViewRow = SharedRow(rowIndex); } - if (this.rowCountsVisible != -1) + if (rowCountsVisible != -1) { - this.rowCountsVisible += rowCountIncrement; + rowCountsVisible += rowCountIncrement; } - if (this.rowsHeightVisible != -1) + if (rowsHeightVisible != -1) { Debug.Assert(rowHeightIncrement != 0); - this.rowsHeightVisible += rowHeightIncrement; + rowsHeightVisible += rowHeightIncrement; } if ((rowStates & (DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)) == (DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)) { - if (this.rowCountsVisibleFrozen != -1) + if (rowCountsVisibleFrozen != -1) { - this.rowCountsVisibleFrozen += rowCountIncrement; + rowCountsVisibleFrozen += rowCountIncrement; } - if (this.rowsHeightVisibleFrozen != -1) + if (rowsHeightVisibleFrozen != -1) { Debug.Assert(rowHeightIncrement != 0); - this.rowsHeightVisibleFrozen += rowHeightIncrement; + rowsHeightVisibleFrozen += rowHeightIncrement; } } if ((rowStates & (DataGridViewElementStates.Visible | DataGridViewElementStates.Selected)) == (DataGridViewElementStates.Visible | DataGridViewElementStates.Selected)) { - if (this.rowCountsVisibleSelected != -1) + if (rowCountsVisibleSelected != -1) { - this.rowCountsVisibleSelected += rowCountIncrement; + rowCountsVisibleSelected += rowCountIncrement; } } } } #if DEBUG - this.cachedRowCountsAccessAllowed = true; - this.cachedRowHeightsAccessAllowed = true; + cachedRowCountsAccessAllowed = true; + cachedRowHeightsAccessAllowed = true; #endif } @@ -2594,10 +2594,10 @@ public RowArrayList(DataGridViewRowCollection owner) public void CustomSort(RowComparer rowComparer) { Debug.Assert(rowComparer != null); - Debug.Assert(this.Count > 0); + Debug.Assert(Count > 0); this.rowComparer = rowComparer; - CustomQuickSort(0, this.Count - 1); + CustomQuickSort(0, Count - 1); } private void CustomQuickSort(int left, int right) @@ -2611,9 +2611,9 @@ private void CustomQuickSort(int left, int right) { if (right - left < 2) // sort subarray of two elements { - if (right - left > 0 && this.rowComparer.CompareObjects(this.rowComparer.GetComparedObject(left), this.rowComparer.GetComparedObject(right), left, right) > 0) + if (right - left > 0 && rowComparer.CompareObjects(rowComparer.GetComparedObject(left), rowComparer.GetComparedObject(right), left, right) > 0) { - this.owner.SwapSortedRows(left, right); + owner.SwapSortedRows(left, right); } return; } @@ -2624,11 +2624,11 @@ private void CustomQuickSort(int left, int right) int j = right - 1; do { - while (k != i && this.rowComparer.CompareObjects(this.rowComparer.GetComparedObject(i), x, i, k) < 0) + while (k != i && rowComparer.CompareObjects(rowComparer.GetComparedObject(i), x, i, k) < 0) { i++; } - while (k != j && this.rowComparer.CompareObjects(x, this.rowComparer.GetComparedObject(j), k, j) < 0) + while (k != j && rowComparer.CompareObjects(x, rowComparer.GetComparedObject(j), k, j) < 0) { j--; } @@ -2639,7 +2639,7 @@ private void CustomQuickSort(int left, int right) } if (i < j) { - this.owner.SwapSortedRows(i, j); + owner.SwapSortedRows(i, j); if (i == k) { k = j; @@ -2677,19 +2677,19 @@ private void CustomQuickSort(int left, int right) private object Pivot(int left, int center, int right) { // find median-of-3 (left, center and right) and sort these 3 elements - if (this.rowComparer.CompareObjects(this.rowComparer.GetComparedObject(left), this.rowComparer.GetComparedObject(center), left, center) > 0) + if (rowComparer.CompareObjects(rowComparer.GetComparedObject(left), rowComparer.GetComparedObject(center), left, center) > 0) { - this.owner.SwapSortedRows(left, center); + owner.SwapSortedRows(left, center); } - if (this.rowComparer.CompareObjects(this.rowComparer.GetComparedObject(left), this.rowComparer.GetComparedObject(right), left, right) > 0) + if (rowComparer.CompareObjects(rowComparer.GetComparedObject(left), rowComparer.GetComparedObject(right), left, right) > 0) { - this.owner.SwapSortedRows(left, right); + owner.SwapSortedRows(left, right); } - if (this.rowComparer.CompareObjects(this.rowComparer.GetComparedObject(center), this.rowComparer.GetComparedObject(right), center, right) > 0) + if (rowComparer.CompareObjects(rowComparer.GetComparedObject(center), rowComparer.GetComparedObject(right), center, right) > 0) { - this.owner.SwapSortedRows(center, right); + owner.SwapSortedRows(center, right); } - return this.rowComparer.GetComparedObject(center); + return rowComparer.GetComparedObject(center); } } @@ -2705,17 +2705,17 @@ private class RowComparer public RowComparer(DataGridViewRowCollection dataGridViewRows, IComparer customComparer, bool ascending) { - this.dataGridView = dataGridViewRows.DataGridView; + dataGridView = dataGridViewRows.DataGridView; this.dataGridViewRows = dataGridViewRows; - this.dataGridViewSortedColumn = this.dataGridView.SortedColumn; - if (this.dataGridViewSortedColumn == null) + dataGridViewSortedColumn = dataGridView.SortedColumn; + if (dataGridViewSortedColumn == null) { Debug.Assert(customComparer != null); - this.sortedColumnIndex = -1; + sortedColumnIndex = -1; } else { - this.sortedColumnIndex = this.dataGridViewSortedColumn.Index; + sortedColumnIndex = dataGridViewSortedColumn.Index; } this.customComparer = customComparer; this.ascending = ascending; @@ -2723,24 +2723,24 @@ public RowComparer(DataGridViewRowCollection dataGridViewRows, IComparer customC internal object GetComparedObject(int rowIndex) { - if (this.dataGridView.NewRowIndex != -1) + if (dataGridView.NewRowIndex != -1) { - Debug.Assert(this.dataGridView.AllowUserToAddRowsInternal); - if (rowIndex == this.dataGridView.NewRowIndex) + Debug.Assert(dataGridView.AllowUserToAddRowsInternal); + if (rowIndex == dataGridView.NewRowIndex) { return max; } } - if (this.customComparer == null) + if (customComparer == null) { - DataGridViewRow dataGridViewRow = this.dataGridViewRows.SharedRow(rowIndex); + DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); Debug.Assert(dataGridViewRow != null); - Debug.Assert(this.sortedColumnIndex >= 0); - return dataGridViewRow.Cells[this.sortedColumnIndex].GetValueInternal(rowIndex); + Debug.Assert(sortedColumnIndex >= 0); + return dataGridViewRow.Cells[sortedColumnIndex].GetValueInternal(rowIndex); } else { - return this.dataGridViewRows[rowIndex]; // Unsharing compared rows! + return dataGridViewRows[rowIndex]; // Unsharing compared rows! } } @@ -2755,9 +2755,9 @@ internal int CompareObjects(object value1, object value2, int rowIndex1, int row return -1; } int result = 0; - if (this.customComparer == null) + if (customComparer == null) { - if (!this.dataGridView.OnSortCompare(this.dataGridViewSortedColumn, value1, value2, rowIndex1, rowIndex2, out result)) + if (!dataGridView.OnSortCompare(dataGridViewSortedColumn, value1, value2, rowIndex1, rowIndex2, out result)) { if (!(value1 is IComparable) && !(value2 is IComparable)) { @@ -2787,7 +2787,7 @@ internal int CompareObjects(object value1, object value2, int rowIndex1, int row } if (result == 0) { - if (this.ascending) + if (ascending) { result = rowIndex1 - rowIndex2; } @@ -2807,10 +2807,10 @@ internal int CompareObjects(object value1, object value2, int rowIndex1, int row // - result = this.customComparer.Compare(value1, value2); + result = customComparer.Compare(value1, value2); } - if (this.ascending) + if (ascending) { return result; } @@ -2837,7 +2837,7 @@ private class UnsharingRowEnumerator : IEnumerator public UnsharingRowEnumerator(DataGridViewRowCollection owner) { this.owner = owner; - this.current = -1; + current = -1; } /// @@ -2846,14 +2846,14 @@ public UnsharingRowEnumerator(DataGridViewRowCollection owner) bool IEnumerator.MoveNext() { - if (this.current < this.owner.Count - 1) + if (current < owner.Count - 1) { - this.current++; + current++; return true; } else { - this.current = this.owner.Count; + current = owner.Count; return false; } } @@ -2863,7 +2863,7 @@ bool IEnumerator.MoveNext() /// void IEnumerator.Reset() { - this.current = -1; + current = -1; } /// @@ -2873,15 +2873,15 @@ object IEnumerator.Current { get { - if (this.current == -1) + if (current == -1) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_EnumNotStarted)); } - if (this.current == this.owner.Count) + if (current == owner.Count) { throw new InvalidOperationException(string.Format(SR.DataGridViewRowCollection_EnumFinished)); } - return this.owner[this.current]; + return owner[current]; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowHeaderCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowHeaderCell.cs index 8399782de74..25319a1bb7d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowHeaderCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowHeaderCell.cs @@ -135,7 +135,7 @@ private static Bitmap StarBitmap public override object Clone() { DataGridViewRowHeaderCell dataGridViewCell; - Type thisType = this.GetType(); + Type thisType = GetType(); if (thisType == cellType) //performance improvement { @@ -148,7 +148,7 @@ public override object Clone() dataGridViewCell = (DataGridViewRowHeaderCell)System.Activator.CreateInstance(thisType); } base.CloneInternal(dataGridViewCell); - dataGridViewCell.Value = this.Value; + dataGridViewCell.Value = Value; return dataGridViewCell; } @@ -195,11 +195,11 @@ protected override object GetClipboardContent(int rowIndex, bool inLastRow, string format) { - if (this.DataGridView == null) + if (DataGridView == null) { return null; } - if (rowIndex < 0 || rowIndex >= this.DataGridView.Rows.Count) + if (rowIndex < 0 || rowIndex >= DataGridView.Rows.Count) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } @@ -208,7 +208,7 @@ protected override object GetClipboardContent(int rowIndex, object val = GetValue(rowIndex); StringBuilder sb = new StringBuilder(64); - Debug.Assert((!this.DataGridView.RightToLeftInternal && firstCell) || (this.DataGridView.RightToLeftInternal && lastCell)); + Debug.Assert((!DataGridView.RightToLeftInternal && firstCell) || (DataGridView.RightToLeftInternal && lastCell)); if (string.Equals(format, DataFormats.Html, StringComparison.OrdinalIgnoreCase)) { @@ -285,7 +285,7 @@ protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCel throw new ArgumentNullException(nameof(cellStyle)); } - if (this.DataGridView == null || this.OwningRow == null) + if (DataGridView == null || OwningRow == null) { return Rectangle.Empty; } @@ -344,9 +344,9 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC throw new ArgumentNullException(nameof(cellStyle)); } - if (this.DataGridView == null || + if (DataGridView == null || rowIndex < 0 || - !this.DataGridView.ShowRowErrors || + !DataGridView.ShowRowErrors || string.IsNullOrEmpty(GetErrorText(rowIndex))) { return Rectangle.Empty; @@ -380,19 +380,19 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC protected internal override string GetErrorText(int rowIndex) { - if (this.OwningRow == null) + if (OwningRow == null) { return base.GetErrorText(rowIndex); } else { - return this.OwningRow.GetErrorText(rowIndex); + return OwningRow.GetErrorText(rowIndex); } } public override ContextMenuStrip GetInheritedContextMenuStrip(int rowIndex) { - if (this.DataGridView != null && (rowIndex < 0 || rowIndex >= this.DataGridView.Rows.Count)) + if (DataGridView != null && (rowIndex < 0 || rowIndex >= DataGridView.Rows.Count)) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } @@ -403,9 +403,9 @@ public override ContextMenuStrip GetInheritedContextMenuStrip(int rowIndex) return contextMenuStrip; } - if (this.DataGridView != null) + if (DataGridView != null) { - return this.DataGridView.ContextMenuStrip; + return DataGridView.ContextMenuStrip; } else { @@ -415,21 +415,21 @@ public override ContextMenuStrip GetInheritedContextMenuStrip(int rowIndex) public override DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle inheritedCellStyle, int rowIndex, bool includeColors) { - Debug.Assert(this.DataGridView != null); + Debug.Assert(DataGridView != null); DataGridViewCellStyle inheritedCellStyleTmp = (inheritedCellStyle == null) ? new DataGridViewCellStyle() : inheritedCellStyle; DataGridViewCellStyle cellStyle = null; - if (this.HasStyle) + if (HasStyle) { - cellStyle = this.Style; + cellStyle = Style; Debug.Assert(cellStyle != null); } - DataGridViewCellStyle rowHeadersStyle = this.DataGridView.RowHeadersDefaultCellStyle; + DataGridViewCellStyle rowHeadersStyle = DataGridView.RowHeadersDefaultCellStyle; Debug.Assert(rowHeadersStyle != null); - DataGridViewCellStyle dataGridViewStyle = this.DataGridView.DefaultCellStyle; + DataGridViewCellStyle dataGridViewStyle = DataGridView.DefaultCellStyle; Debug.Assert(dataGridViewStyle != null); if (includeColors) @@ -616,7 +616,7 @@ private static Bitmap GetPencilBitmap(bool rightToLeft) protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize) { - if (this.DataGridView == null) + if (DataGridView == null) { return new Size(-1, -1); } @@ -627,7 +627,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl } DataGridViewAdvancedBorderStyle dgvabsPlaceholder = new DataGridViewAdvancedBorderStyle(), dgvabsEffective; - dgvabsEffective = this.OwningRow.AdjustRowHeaderBorderStyle(this.DataGridView.AdvancedRowHeadersBorderStyle, + dgvabsEffective = OwningRow.AdjustRowHeaderBorderStyle(DataGridView.AdvancedRowHeadersBorderStyle, dgvabsPlaceholder, false /*singleVerticalBorderAdded*/, false /*singleHorizontalBorderAdded*/, @@ -637,9 +637,9 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl int borderAndPaddingWidths = borderWidthsRect.Left + borderWidthsRect.Width + cellStyle.Padding.Horizontal; int borderAndPaddingHeights = borderWidthsRect.Top + borderWidthsRect.Height + cellStyle.Padding.Vertical; - TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); + TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); - if (this.DataGridView.ApplyVisualStylesToHeaderCells) + if (DataGridView.ApplyVisualStylesToHeaderCells) { // Add the theming margins to the borders. Rectangle rectThemeMargins = DataGridViewHeaderCell.GetThemeMargins(graphics); @@ -660,7 +660,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl cellStyle, borderAndPaddingWidths, borderAndPaddingHeights, - this.DataGridView.ShowRowErrors, + DataGridView.ShowRowErrors, true /*showGlyph*/, constraintSize, flags); @@ -670,11 +670,11 @@ protected override object GetValue(int rowIndex) { // We allow multiple rows to share the same row header value. The row header cell's cloning does this. // So here we need to allow rowIndex == -1. - if (this.DataGridView != null && (rowIndex < -1 || rowIndex >= this.DataGridView.Rows.Count)) + if (DataGridView != null && (rowIndex < -1 || rowIndex >= DataGridView.Rows.Count)) { throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - return this.Properties.GetObject(PropCellValue); + return Properties.GetObject(PropCellValue); } protected override void Paint(Graphics graphics, @@ -760,11 +760,11 @@ private Rectangle PaintPrivate(Graphics graphics, bool cellSelected = (dataGridViewElementState & DataGridViewElementStates.Selected) != 0; - if (this.DataGridView.ApplyVisualStylesToHeaderCells) + if (DataGridView.ApplyVisualStylesToHeaderCells) { if (cellStyle.Padding != Padding.Empty) { - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { valBounds.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top); } @@ -782,16 +782,16 @@ private Rectangle PaintPrivate(Graphics graphics, { // Theming int state = (int)HeaderItemState.Normal; - if (this.DataGridView.SelectionMode == DataGridViewSelectionMode.FullRowSelect || - this.DataGridView.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) + if (DataGridView.SelectionMode == DataGridViewSelectionMode.FullRowSelect || + DataGridView.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) { - if (this.ButtonState != ButtonState.Normal) + if (ButtonState != ButtonState.Normal) { - Debug.Assert(this.ButtonState == ButtonState.Pushed); + Debug.Assert(ButtonState == ButtonState.Pushed); state = (int)HeaderItemState.Pressed; } - else if (this.DataGridView.MouseEnteredCellAddress.Y == rowIndex && - this.DataGridView.MouseEnteredCellAddress.X == -1) + else if (DataGridView.MouseEnteredCellAddress.Y == rowIndex && + DataGridView.MouseEnteredCellAddress.X == -1) { state = (int)HeaderItemState.Hot; } @@ -806,7 +806,7 @@ private Rectangle PaintPrivate(Graphics graphics, using (Graphics gFlip = Graphics.FromImage(bmFlipXPThemes)) { DataGridViewRowHeaderCellRenderer.DrawHeader(gFlip, new Rectangle(0, 0, backgroundBounds.Height, backgroundBounds.Width), state); - bmFlipXPThemes.RotateFlip(this.DataGridView.RightToLeftInternal ? RotateFlipType.Rotate90FlipNone : RotateFlipType.Rotate270FlipY); + bmFlipXPThemes.RotateFlip(DataGridView.RightToLeftInternal ? RotateFlipType.Rotate90FlipNone : RotateFlipType.Rotate270FlipY); graphics.DrawImage(bmFlipXPThemes, backgroundBounds, @@ -817,7 +817,7 @@ private Rectangle PaintPrivate(Graphics graphics, } // update the val bounds Rectangle rectThemeMargins = DataGridViewHeaderCell.GetThemeMargins(graphics); - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { valBounds.X += rectThemeMargins.Height; } @@ -835,7 +835,7 @@ private Rectangle PaintPrivate(Graphics graphics, // No visual style applied if (valBounds.Width > 0 && valBounds.Height > 0) { - SolidBrush br = this.DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor); + SolidBrush br = DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor); if (paint && DataGridViewCell.PaintBackground(paintParts) && br.Color.A == 255) { graphics.FillRectangle(br, valBounds); @@ -844,7 +844,7 @@ private Rectangle PaintPrivate(Graphics graphics, if (cellStyle.Padding != Padding.Empty) { - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { valBounds.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top); } @@ -874,47 +874,47 @@ private Rectangle PaintPrivate(Graphics graphics, if (paint && DataGridViewCell.PaintContentBackground(paintParts)) { // There is enough room for the potential glyph which is the first priority - if (this.DataGridView.CurrentCellAddress.Y == rowIndex) + if (DataGridView.CurrentCellAddress.Y == rowIndex) { - if (this.DataGridView.VirtualMode) + if (DataGridView.VirtualMode) { - if (this.DataGridView.IsCurrentRowDirty && this.DataGridView.ShowEditingIcon) + if (DataGridView.IsCurrentRowDirty && DataGridView.ShowEditingIcon) { - bmp = GetPencilBitmap(this.DataGridView.RightToLeftInternal); + bmp = GetPencilBitmap(DataGridView.RightToLeftInternal); } - else if (this.DataGridView.NewRowIndex == rowIndex) + else if (DataGridView.NewRowIndex == rowIndex) { - bmp = GetArrowStarBitmap(this.DataGridView.RightToLeftInternal); + bmp = GetArrowStarBitmap(DataGridView.RightToLeftInternal); } else { - bmp = GetArrowBitmap(this.DataGridView.RightToLeftInternal); + bmp = GetArrowBitmap(DataGridView.RightToLeftInternal); } } else { - if (this.DataGridView.IsCurrentCellDirty && this.DataGridView.ShowEditingIcon) + if (DataGridView.IsCurrentCellDirty && DataGridView.ShowEditingIcon) { - bmp = GetPencilBitmap(this.DataGridView.RightToLeftInternal); + bmp = GetPencilBitmap(DataGridView.RightToLeftInternal); } - else if (this.DataGridView.NewRowIndex == rowIndex) + else if (DataGridView.NewRowIndex == rowIndex) { - bmp = GetArrowStarBitmap(this.DataGridView.RightToLeftInternal); + bmp = GetArrowStarBitmap(DataGridView.RightToLeftInternal); } else { - bmp = GetArrowBitmap(this.DataGridView.RightToLeftInternal); + bmp = GetArrowBitmap(DataGridView.RightToLeftInternal); } } } - else if (this.DataGridView.NewRowIndex == rowIndex) + else if (DataGridView.NewRowIndex == rowIndex) { bmp = DataGridViewRowHeaderCell.StarBitmap; } if (bmp != null) { Color iconColor; - if (this.DataGridView.ApplyVisualStylesToHeaderCells) + if (DataGridView.ApplyVisualStylesToHeaderCells) { iconColor = DataGridViewRowHeaderCellRenderer.VisualStyleRenderer.GetColor(ColorProperty.TextColor); } @@ -928,7 +928,7 @@ private Rectangle PaintPrivate(Graphics graphics, } } } - if (!this.DataGridView.RightToLeftInternal) + if (!DataGridView.RightToLeftInternal) { valBounds.X += iconsWidth + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth; } @@ -943,8 +943,8 @@ private Rectangle PaintPrivate(Graphics graphics, valBounds.Height -= 2 * DATAGRIDVIEWROWHEADERCELL_verticalTextMargin; if (valBounds.Width > 0 && valBounds.Height > 0) { - TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); - if (this.DataGridView.ShowRowErrors && valBounds.Width > iconsWidth + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth) + TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); + if (DataGridView.ShowRowErrors && valBounds.Width > iconsWidth + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth) { // Check if the text fits if we remove the room required for the row error icon Size maxBounds = new Size(valBounds.Width - iconsWidth - 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth, valBounds.Height); @@ -955,7 +955,7 @@ private Rectangle PaintPrivate(Graphics graphics, flags)) { // There is enough room for both the text and the row error icon, so use it all. - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { valBounds.X += iconsWidth + 2 * DATAGRIDVIEWROWHEADERCELL_iconMarginWidth; } @@ -968,7 +968,7 @@ private Rectangle PaintPrivate(Graphics graphics, if (paint) { Color textColor; - if (this.DataGridView.ApplyVisualStylesToHeaderCells) + if (DataGridView.ApplyVisualStylesToHeaderCells) { textColor = DataGridViewRowHeaderCellRenderer.VisualStyleRenderer.GetColor(ColorProperty.TextColor); } @@ -998,7 +998,7 @@ private Rectangle PaintPrivate(Graphics graphics, 2 * iconsWidth) { // There is enough horizontal room for the error icon and the glyph - if (paint && this.DataGridView.ShowRowErrors && DataGridViewCell.PaintErrorIcon(paintParts)) + if (paint && DataGridView.ShowRowErrors && DataGridViewCell.PaintErrorIcon(paintParts)) { PaintErrorIcon(graphics, clipBounds, errorBounds, errorText); } @@ -1020,40 +1020,40 @@ private Rectangle PaintPrivate(Graphics graphics, if (paint && DataGridViewCell.PaintContentBackground(paintParts)) { // There is enough room for the potential icon - if (this.DataGridView.CurrentCellAddress.Y == rowIndex) + if (DataGridView.CurrentCellAddress.Y == rowIndex) { - if (this.DataGridView.VirtualMode) + if (DataGridView.VirtualMode) { - if (this.DataGridView.IsCurrentRowDirty && this.DataGridView.ShowEditingIcon) + if (DataGridView.IsCurrentRowDirty && DataGridView.ShowEditingIcon) { - bmp = GetPencilBitmap(this.DataGridView.RightToLeftInternal); + bmp = GetPencilBitmap(DataGridView.RightToLeftInternal); } - else if (this.DataGridView.NewRowIndex == rowIndex) + else if (DataGridView.NewRowIndex == rowIndex) { - bmp = GetArrowStarBitmap(this.DataGridView.RightToLeftInternal); + bmp = GetArrowStarBitmap(DataGridView.RightToLeftInternal); } else { - bmp = GetArrowBitmap(this.DataGridView.RightToLeftInternal); + bmp = GetArrowBitmap(DataGridView.RightToLeftInternal); } } else { - if (this.DataGridView.IsCurrentCellDirty && this.DataGridView.ShowEditingIcon) + if (DataGridView.IsCurrentCellDirty && DataGridView.ShowEditingIcon) { - bmp = GetPencilBitmap(this.DataGridView.RightToLeftInternal); + bmp = GetPencilBitmap(DataGridView.RightToLeftInternal); } - else if (this.DataGridView.NewRowIndex == rowIndex) + else if (DataGridView.NewRowIndex == rowIndex) { - bmp = GetArrowStarBitmap(this.DataGridView.RightToLeftInternal); + bmp = GetArrowStarBitmap(DataGridView.RightToLeftInternal); } else { - bmp = GetArrowBitmap(this.DataGridView.RightToLeftInternal); + bmp = GetArrowBitmap(DataGridView.RightToLeftInternal); } } } - else if (this.DataGridView.NewRowIndex == rowIndex) + else if (DataGridView.NewRowIndex == rowIndex) { bmp = DataGridViewRowHeaderCell.StarBitmap; } @@ -1062,7 +1062,7 @@ private Rectangle PaintPrivate(Graphics graphics, lock (bmp) { Color iconColor; - if (this.DataGridView.ApplyVisualStylesToHeaderCells) + if (DataGridView.ApplyVisualStylesToHeaderCells) { iconColor = DataGridViewRowHeaderCellRenderer.VisualStyleRenderer.GetColor(ColorProperty.TextColor); } @@ -1080,7 +1080,7 @@ private Rectangle PaintPrivate(Graphics graphics, 2 * iconsWidth) { // There is enough horizontal room for the error icon - if (paint && this.DataGridView.ShowRowErrors && DataGridViewCell.PaintErrorIcon(paintParts)) + if (paint && DataGridView.ShowRowErrors && DataGridViewCell.PaintErrorIcon(paintParts)) { PaintErrorIcon(graphics, cellStyle, rowIndex, cellBounds, errorBounds, errorText); } @@ -1101,7 +1101,7 @@ private Rectangle PaintPrivate(Graphics graphics, private void PaintIcon(Graphics g, Bitmap bmp, Rectangle bounds, Color foreColor) { - Rectangle bmpRect = new Rectangle(this.DataGridView.RightToLeftInternal ? + Rectangle bmpRect = new Rectangle(DataGridView.RightToLeftInternal ? bounds.Right - DATAGRIDVIEWROWHEADERCELL_iconMarginWidth - iconsWidth : bounds.Left + DATAGRIDVIEWROWHEADERCELL_iconMarginWidth, bounds.Y + (bounds.Height - iconsHeight) / 2, @@ -1119,11 +1119,11 @@ private void PaintIcon(Graphics g, Bitmap bmp, Rectangle bounds, Color foreColor protected override bool SetValue(int rowIndex, object value) { object originalValue = GetValue(rowIndex); - if (value != null || this.Properties.ContainsObject(PropCellValue)) + if (value != null || Properties.ContainsObject(PropCellValue)) { - this.Properties.SetObject(PropCellValue, value); + Properties.SetObject(PropCellValue, value); } - if (this.DataGridView != null && originalValue != value) + if (DataGridView != null && originalValue != value) { RaiseCellValueChanged(new DataGridViewCellEventArgs(-1, rowIndex)); } @@ -1176,16 +1176,16 @@ public override Rectangle Bounds { get { - if (this.Owner.OwningRow == null) + if (Owner.OwningRow == null) { return Rectangle.Empty; } // use the parent row acc obj bounds - Rectangle rowRect = this.ParentPrivate.Bounds; + Rectangle rowRect = ParentPrivate.Bounds; Rectangle cellRect = rowRect; - cellRect.Width = this.Owner.DataGridView.RowHeadersWidth; - if (this.Owner.DataGridView.RightToLeft == RightToLeft.Yes) + cellRect.Width = Owner.DataGridView.RowHeadersWidth; + if (Owner.DataGridView.RightToLeft == RightToLeft.Yes) { cellRect.X = rowRect.Right - cellRect.Width; } @@ -1198,8 +1198,8 @@ public override string DefaultAction { get { - if (this.Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.FullRowSelect || - this.Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) + if (Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.FullRowSelect || + Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) { return string.Format(SR.DataGridView_RowHeaderCellAccDefaultAction); } @@ -1214,9 +1214,9 @@ public override string Name { get { - if (this.ParentPrivate != null) + if (ParentPrivate != null) { - return this.ParentPrivate.Name; + return ParentPrivate.Name; } else { @@ -1229,7 +1229,7 @@ public override AccessibleObject Parent { get { - return this.ParentPrivate; + return ParentPrivate; } } @@ -1237,13 +1237,13 @@ private AccessibleObject ParentPrivate { get { - if (this.Owner.OwningRow == null) + if (Owner.OwningRow == null) { return null; } else { - return this.Owner.OwningRow.AccessibilityObject; + return Owner.OwningRow.AccessibilityObject; } } } @@ -1269,10 +1269,10 @@ public override AccessibleStates State resultState |= AccessibleStates.Offscreen; } - if (this.Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.FullRowSelect || - this.Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) + if (Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.FullRowSelect || + Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) { - if (this.Owner.OwningRow != null && this.Owner.OwningRow.Selected) + if (Owner.OwningRow != null && Owner.OwningRow.Selected) { resultState |= AccessibleStates.Selected; } @@ -1292,72 +1292,72 @@ public override string Value public override void DoDefaultAction() { - if ((this.Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.FullRowSelect || - this.Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) && - this.Owner.OwningRow != null) + if ((Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.FullRowSelect || + Owner.DataGridView.SelectionMode == DataGridViewSelectionMode.RowHeaderSelect) && + Owner.OwningRow != null) { - this.Owner.OwningRow.Selected = true; + Owner.OwningRow.Selected = true; } } public override AccessibleObject Navigate(AccessibleNavigation navigationDirection) { - Debug.Assert(this.Owner.DataGridView.RowHeadersVisible, "if the rows are not visible how did you get the row headers acc obj?"); + Debug.Assert(Owner.DataGridView.RowHeadersVisible, "if the rows are not visible how did you get the row headers acc obj?"); switch (navigationDirection) { case AccessibleNavigation.Next: - if (this.Owner.OwningRow != null && this.Owner.DataGridView.Columns.GetColumnCount(DataGridViewElementStates.Visible) > 0) + if (Owner.OwningRow != null && Owner.DataGridView.Columns.GetColumnCount(DataGridViewElementStates.Visible) > 0) { // go to the next sibling - return this.ParentPrivate.GetChild(1); + return ParentPrivate.GetChild(1); } else { return null; } case AccessibleNavigation.Down: - if (this.Owner.OwningRow == null) + if (Owner.OwningRow == null) { return null; } else { - if (this.Owner.OwningRow.Index == this.Owner.DataGridView.Rows.GetLastRow(DataGridViewElementStates.Visible)) + if (Owner.OwningRow.Index == Owner.DataGridView.Rows.GetLastRow(DataGridViewElementStates.Visible)) { return null; } else { - int nextVisibleRow = this.Owner.DataGridView.Rows.GetNextRow(this.Owner.OwningRow.Index, DataGridViewElementStates.Visible); - int actualDisplayIndex = this.Owner.DataGridView.Rows.GetRowCount(DataGridViewElementStates.Visible, 0, nextVisibleRow); + int nextVisibleRow = Owner.DataGridView.Rows.GetNextRow(Owner.OwningRow.Index, DataGridViewElementStates.Visible); + int actualDisplayIndex = Owner.DataGridView.Rows.GetRowCount(DataGridViewElementStates.Visible, 0, nextVisibleRow); - if (this.Owner.DataGridView.ColumnHeadersVisible) + if (Owner.DataGridView.ColumnHeadersVisible) { // + 1 because the first child in the data grid view acc obj is the top row header acc obj - return this.Owner.DataGridView.AccessibilityObject.GetChild(1 + actualDisplayIndex).GetChild(0); + return Owner.DataGridView.AccessibilityObject.GetChild(1 + actualDisplayIndex).GetChild(0); } else { - return this.Owner.DataGridView.AccessibilityObject.GetChild(actualDisplayIndex).GetChild(0); + return Owner.DataGridView.AccessibilityObject.GetChild(actualDisplayIndex).GetChild(0); } } } case AccessibleNavigation.Previous: return null; case AccessibleNavigation.Up: - if (this.Owner.OwningRow == null) + if (Owner.OwningRow == null) { return null; } else { - if (this.Owner.OwningRow.Index == this.Owner.DataGridView.Rows.GetFirstRow(DataGridViewElementStates.Visible)) + if (Owner.OwningRow.Index == Owner.DataGridView.Rows.GetFirstRow(DataGridViewElementStates.Visible)) { - if (this.Owner.DataGridView.ColumnHeadersVisible) + if (Owner.DataGridView.ColumnHeadersVisible) { // Return the top left header cell accessible object. - Debug.Assert(this.Owner.DataGridView.TopLeftHeaderCell.AccessibilityObject == this.Owner.DataGridView.AccessibilityObject.GetChild(0).GetChild(0)); - return this.Owner.DataGridView.AccessibilityObject.GetChild(0).GetChild(0); + Debug.Assert(Owner.DataGridView.TopLeftHeaderCell.AccessibilityObject == Owner.DataGridView.AccessibilityObject.GetChild(0).GetChild(0)); + return Owner.DataGridView.AccessibilityObject.GetChild(0).GetChild(0); } else { @@ -1366,16 +1366,16 @@ public override AccessibleObject Navigate(AccessibleNavigation navigationDirecti } else { - int previousVisibleRow = this.Owner.DataGridView.Rows.GetPreviousRow(this.Owner.OwningRow.Index, DataGridViewElementStates.Visible); - int actualDisplayIndex = this.Owner.DataGridView.Rows.GetRowCount(DataGridViewElementStates.Visible, 0, previousVisibleRow); - if (this.Owner.DataGridView.ColumnHeadersVisible) + int previousVisibleRow = Owner.DataGridView.Rows.GetPreviousRow(Owner.OwningRow.Index, DataGridViewElementStates.Visible); + int actualDisplayIndex = Owner.DataGridView.Rows.GetRowCount(DataGridViewElementStates.Visible, 0, previousVisibleRow); + if (Owner.DataGridView.ColumnHeadersVisible) { // + 1 because the first child in the data grid view acc obj is the top row header acc obj - return this.Owner.DataGridView.AccessibilityObject.GetChild(actualDisplayIndex + 1).GetChild(0); + return Owner.DataGridView.AccessibilityObject.GetChild(actualDisplayIndex + 1).GetChild(0); } else { - return this.Owner.DataGridView.AccessibilityObject.GetChild(actualDisplayIndex).GetChild(0); + return Owner.DataGridView.AccessibilityObject.GetChild(actualDisplayIndex).GetChild(0); } } } @@ -1386,12 +1386,12 @@ public override AccessibleObject Navigate(AccessibleNavigation navigationDirecti public override void Select(AccessibleSelection flags) { - if (this.Owner == null) + if (Owner == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet)); } - DataGridViewRowHeaderCell dataGridViewCell = (DataGridViewRowHeaderCell)this.Owner; + DataGridViewRowHeaderCell dataGridViewCell = (DataGridViewRowHeaderCell)Owner; DataGridView dataGridView = dataGridViewCell.DataGridView; if (dataGridView == null) @@ -1421,7 +1421,7 @@ public override void Select(AccessibleSelection flags) internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - if (this.Owner.OwningRow == null) + if (Owner.OwningRow == null) { return null; } @@ -1429,12 +1429,12 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga switch (direction) { case UnsafeNativeMethods.NavigateDirection.Parent: - return this.Owner.OwningRow.AccessibilityObject; + return Owner.OwningRow.AccessibilityObject; case UnsafeNativeMethods.NavigateDirection.NextSibling: - if (this.Owner.DataGridView.Columns.GetColumnCount(DataGridViewElementStates.Visible) > 0) + if (Owner.DataGridView.Columns.GetColumnCount(DataGridViewElementStates.Visible) > 0) { // go to the next sibling - return this.Owner.OwningRow.AccessibilityObject.GetChild(1); + return Owner.OwningRow.AccessibilityObject.GetChild(1); } else { @@ -1455,20 +1455,20 @@ internal override object GetPropertyValue(int propertyId) switch (propertyId) { case NativeMethods.UIA_NamePropertyId: - return this.Name; + return Name; case NativeMethods.UIA_ControlTypePropertyId: return NativeMethods.UIA_HeaderControlTypeId; case NativeMethods.UIA_IsEnabledPropertyId: return Owner.DataGridView.Enabled; case NativeMethods.UIA_HelpTextPropertyId: - return this.Help ?? string.Empty; + return Help ?? string.Empty; case NativeMethods.UIA_IsKeyboardFocusablePropertyId: - return (this.State & AccessibleStates.Focusable) == AccessibleStates.Focusable; + return (State & AccessibleStates.Focusable) == AccessibleStates.Focusable; case NativeMethods.UIA_HasKeyboardFocusPropertyId: case NativeMethods.UIA_IsPasswordPropertyId: return false; case NativeMethods.UIA_IsOffscreenPropertyId: - return (this.State & AccessibleStates.Offscreen) == AccessibleStates.Offscreen; + return (State & AccessibleStates.Offscreen) == AccessibleStates.Offscreen; case NativeMethods.UIA_AccessKeyPropertyId: return string.Empty; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedCellCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedCellCollection.cs index 3f0f51f5647..93d1c4c9aac 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedCellCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedCellCollection.cs @@ -36,12 +36,12 @@ void IList.Clear() bool IList.Contains(object value) { - return this.items.Contains(value); + return items.Contains(value); } int IList.IndexOf(object value) { - return this.items.IndexOf(value); + return items.IndexOf(value); } void IList.Insert(int index, object value) @@ -71,18 +71,18 @@ bool IList.IsReadOnly object IList.this[int index] { - get { return this.items[index]; } + get { return items[index]; } set { throw new NotSupportedException(string.Format(SR.DataGridView_ReadOnlyCollection)); } } void ICollection.CopyTo(Array array, int index) { - this.items.CopyTo(array, index); + items.CopyTo(array, index); } int ICollection.Count { - get { return this.items.Count; } + get { return items.Count; } } bool ICollection.IsSynchronized @@ -97,7 +97,7 @@ object ICollection.SyncRoot IEnumerator IEnumerable.GetEnumerator() { - return this.items.GetEnumerator(); + return items.GetEnumerator(); } internal DataGridViewSelectedCellCollection() @@ -108,7 +108,7 @@ protected override ArrayList List { get { - return this.items; + return items; } } @@ -116,7 +116,7 @@ public DataGridViewCell this[int index] { get { - return (DataGridViewCell)this.items[index]; + return (DataGridViewCell)items[index]; } } @@ -126,7 +126,7 @@ public DataGridViewCell this[int index] internal int Add(DataGridViewCell dataGridViewCell) { Debug.Assert(!Contains(dataGridViewCell)); - return this.items.Add(dataGridViewCell); + return items.Add(dataGridViewCell); } /* Not used for now @@ -160,7 +160,7 @@ internal void AddCellLinkedList(DataGridViewCellLinkedList dataGridViewCells) foreach (DataGridViewCell dataGridViewCell in dataGridViewCells) { Debug.Assert(!Contains(dataGridViewCell)); - this.items.Add(dataGridViewCell); + items.Add(dataGridViewCell); } } @@ -177,12 +177,12 @@ public void Clear() /// public bool Contains(DataGridViewCell dataGridViewCell) { - return this.items.IndexOf(dataGridViewCell) != -1; + return items.IndexOf(dataGridViewCell) != -1; } public void CopyTo(DataGridViewCell[] array, int index) { - this.items.CopyTo(array, index); + items.CopyTo(array, index); } [ diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedCellsAccessibleObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedCellsAccessibleObject.cs index 3a0f1cb5f2f..f2f112494cc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedCellsAccessibleObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedCellsAccessibleObject.cs @@ -27,7 +27,7 @@ public override AccessibleObject Parent { get { - return this.owner.AccessibilityObject; + return owner.AccessibilityObject; } } @@ -51,15 +51,15 @@ public override string Value { get { - return this.Name; + return Name; } } public override AccessibleObject GetChild(int index) { - if (index >= 0 && index < this.owner.GetCellCount(DataGridViewElementStates.Selected)) + if (index >= 0 && index < owner.GetCellCount(DataGridViewElementStates.Selected)) { - return this.owner.SelectedCell(index).AccessibilityObject; + return owner.SelectedCell(index).AccessibilityObject; } else { @@ -69,7 +69,7 @@ public override AccessibleObject GetChild(int index) public override int GetChildCount() { - return this.owner.GetCellCount(DataGridViewElementStates.Selected); + return owner.GetCellCount(DataGridViewElementStates.Selected); } public override AccessibleObject GetSelected() @@ -79,9 +79,9 @@ public override AccessibleObject GetSelected() public override AccessibleObject GetFocused() { - if (this.owner.CurrentCell != null && this.owner.CurrentCell.Selected) + if (owner.CurrentCell != null && owner.CurrentCell.Selected) { - return this.owner.CurrentCell.AccessibilityObject; + return owner.CurrentCell.AccessibilityObject; } else { @@ -94,18 +94,18 @@ public override AccessibleObject Navigate(AccessibleNavigation navigationDirecti switch (navigationDirection) { case AccessibleNavigation.FirstChild: - if (this.owner.GetCellCount(DataGridViewElementStates.Selected) > 0) + if (owner.GetCellCount(DataGridViewElementStates.Selected) > 0) { - return this.owner.SelectedCell(0).AccessibilityObject; + return owner.SelectedCell(0).AccessibilityObject; } else { return null; } case AccessibleNavigation.LastChild: - if (this.owner.GetCellCount(DataGridViewElementStates.Selected) > 0) + if (owner.GetCellCount(DataGridViewElementStates.Selected) > 0) { - return this.owner.SelectedCell(this.owner.GetCellCount(DataGridViewElementStates.Selected) - 1).AccessibilityObject; + return owner.SelectedCell(owner.GetCellCount(DataGridViewElementStates.Selected) - 1).AccessibilityObject; } else { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedColumnCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedColumnCollection.cs index 19533b6f37f..ab5ac716230 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedColumnCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedColumnCollection.cs @@ -33,12 +33,12 @@ void IList.Clear() bool IList.Contains(object value) { - return this.items.Contains(value); + return items.Contains(value); } int IList.IndexOf(object value) { - return this.items.IndexOf(value); + return items.IndexOf(value); } void IList.Insert(int index, object value) @@ -68,18 +68,18 @@ bool IList.IsReadOnly object IList.this[int index] { - get { return this.items[index]; } + get { return items[index]; } set { throw new NotSupportedException(string.Format(SR.DataGridView_ReadOnlyCollection)); } } void ICollection.CopyTo(Array array, int index) { - this.items.CopyTo(array, index); + items.CopyTo(array, index); } int ICollection.Count { - get { return this.items.Count; } + get { return items.Count; } } bool ICollection.IsSynchronized @@ -94,7 +94,7 @@ object ICollection.SyncRoot IEnumerator IEnumerable.GetEnumerator() { - return this.items.GetEnumerator(); + return items.GetEnumerator(); } internal DataGridViewSelectedColumnCollection() @@ -105,7 +105,7 @@ protected override ArrayList List { get { - return this.items; + return items; } } @@ -113,7 +113,7 @@ public DataGridViewColumn this[int index] { get { - return (DataGridViewColumn)this.items[index]; + return (DataGridViewColumn)items[index]; } } @@ -122,7 +122,7 @@ public DataGridViewColumn this[int index] /// internal int Add(DataGridViewColumn dataGridViewColumn) { - return this.items.Add(dataGridViewColumn); + return items.Add(dataGridViewColumn); } /* Unused at this point @@ -160,12 +160,12 @@ public void Clear() /// public bool Contains(DataGridViewColumn dataGridViewColumn) { - return this.items.IndexOf(dataGridViewColumn) != -1; + return items.IndexOf(dataGridViewColumn) != -1; } public void CopyTo(DataGridViewColumn[] array, int index) { - this.items.CopyTo(array, index); + items.CopyTo(array, index); } [ diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedRowCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedRowCollection.cs index 23326b9d1b5..db4c2fc0464 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedRowCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedRowCollection.cs @@ -36,12 +36,12 @@ void IList.Clear() bool IList.Contains(object value) { - return this.items.Contains(value); + return items.Contains(value); } int IList.IndexOf(object value) { - return this.items.IndexOf(value); + return items.IndexOf(value); } void IList.Insert(int index, object value) @@ -71,18 +71,18 @@ bool IList.IsReadOnly object IList.this[int index] { - get { return this.items[index]; } + get { return items[index]; } set { throw new NotSupportedException(string.Format(SR.DataGridView_ReadOnlyCollection)); } } void ICollection.CopyTo(Array array, int index) { - this.items.CopyTo(array, index); + items.CopyTo(array, index); } int ICollection.Count { - get { return this.items.Count; } + get { return items.Count; } } bool ICollection.IsSynchronized @@ -97,7 +97,7 @@ object ICollection.SyncRoot IEnumerator IEnumerable.GetEnumerator() { - return this.items.GetEnumerator(); + return items.GetEnumerator(); } internal DataGridViewSelectedRowCollection() @@ -108,7 +108,7 @@ protected override ArrayList List { get { - return this.items; + return items; } } @@ -116,7 +116,7 @@ public DataGridViewRow this[int index] { get { - return (DataGridViewRow)this.items[index]; + return (DataGridViewRow)items[index]; } } @@ -125,7 +125,7 @@ public DataGridViewRow this[int index] /// internal int Add(DataGridViewRow dataGridViewRow) { - return this.items.Add(dataGridViewRow); + return items.Add(dataGridViewRow); } /* Unused at this point @@ -161,12 +161,12 @@ public void Clear() /// public bool Contains(DataGridViewRow dataGridViewRow) { - return this.items.IndexOf(dataGridViewRow) != -1; + return items.IndexOf(dataGridViewRow) != -1; } public void CopyTo(DataGridViewRow[] array, int index) { - this.items.CopyTo(array, index); + items.CopyTo(array, index); } [ diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSortCompareEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSortCompareEventArgs.cs index 6ff01567e4a..9c4f65b0649 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSortCompareEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSortCompareEventArgs.cs @@ -33,7 +33,7 @@ public object CellValue1 { get { - return this.cellValue1; + return cellValue1; } } @@ -41,7 +41,7 @@ public object CellValue2 { get { - return this.cellValue2; + return cellValue2; } } @@ -49,7 +49,7 @@ public DataGridViewColumn Column { get { - return this.dataGridViewColumn; + return dataGridViewColumn; } } @@ -57,7 +57,7 @@ public int RowIndex1 { get { - return this.rowIndex1; + return rowIndex1; } } @@ -65,7 +65,7 @@ public int RowIndex2 { get { - return this.rowIndex2; + return rowIndex2; } } @@ -73,11 +73,11 @@ public int SortResult { get { - return this.sortResult; + return sortResult; } set { - this.sortResult = value; + sortResult = value; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxCell.cs index c797c2d7782..66a31a5c8e0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxCell.cs @@ -61,13 +61,13 @@ private DataGridViewTextBoxEditingControl EditingTextBox { get { - return (DataGridViewTextBoxEditingControl)this.Properties.GetObject(PropTextBoxCellEditingTextBox); + return (DataGridViewTextBoxEditingControl)Properties.GetObject(PropTextBoxCellEditingTextBox); } set { - if (value != null || this.Properties.ContainsObject(PropTextBoxCellEditingTextBox)) + if (value != null || Properties.ContainsObject(PropTextBoxCellEditingTextBox)) { - this.Properties.SetObject(PropTextBoxCellEditingTextBox, value); + Properties.SetObject(PropTextBoxCellEditingTextBox, value); } } } @@ -87,7 +87,7 @@ public virtual int MaxInputLength get { bool found; - int maxInputLength = this.Properties.GetInteger(PropTextBoxCellMaxInputLength, out found); + int maxInputLength = Properties.GetInteger(PropTextBoxCellMaxInputLength, out found); if (found) { return maxInputLength; @@ -101,10 +101,10 @@ public virtual int MaxInputLength throw new ArgumentOutOfRangeException(nameof(value), string.Format(SR.InvalidLowBoundArgumentEx, nameof(MaxInputLength), value, 0)); } - this.Properties.SetInteger(PropTextBoxCellMaxInputLength, value); - if (OwnsEditingTextBox(this.RowIndex)) + Properties.SetInteger(PropTextBoxCellMaxInputLength, value); + if (OwnsEditingTextBox(RowIndex)) { - this.EditingTextBox.MaxLength = value; + EditingTextBox.MaxLength = value; } } } @@ -125,13 +125,13 @@ public override Type ValueType // Called when the row that owns the editing control gets unshared. internal override void CacheEditingControl() { - this.EditingTextBox = this.DataGridView.EditingControl as DataGridViewTextBoxEditingControl; + EditingTextBox = DataGridView.EditingControl as DataGridViewTextBoxEditingControl; } public override object Clone() { DataGridViewTextBoxCell dataGridViewCell; - Type thisType = this.GetType(); + Type thisType = GetType(); if (thisType == cellType) //performance improvement { dataGridViewCell = new DataGridViewTextBoxCell(); @@ -143,7 +143,7 @@ public override object Clone() dataGridViewCell = (DataGridViewTextBoxCell)System.Activator.CreateInstance(thisType); } base.CloneInternal(dataGridViewCell); - dataGridViewCell.MaxInputLength = this.MaxInputLength; + dataGridViewCell.MaxInputLength = MaxInputLength; return dataGridViewCell; } @@ -152,7 +152,7 @@ public override object Clone() ] public override void DetachEditingControl() { - DataGridView dgv = this.DataGridView; + DataGridView dgv = DataGridView; if (dgv == null || dgv.EditingControl == null) { throw new InvalidOperationException(); @@ -164,7 +164,7 @@ public override void DetachEditingControl() textBox.ClearUndo(); } - this.EditingTextBox = null; + EditingTextBox = null; base.DetachEditingControl(); } @@ -172,9 +172,9 @@ public override void DetachEditingControl() private Rectangle GetAdjustedEditingControlBounds(Rectangle editingControlBounds, DataGridViewCellStyle cellStyle) { Debug.Assert(cellStyle.WrapMode != DataGridViewTriState.NotSet); - Debug.Assert(this.DataGridView != null); + Debug.Assert(DataGridView != null); - TextBox txtEditingControl = this.DataGridView.EditingControl as TextBox; + TextBox txtEditingControl = DataGridView.EditingControl as TextBox; int originalWidth = editingControlBounds.Width; if (txtEditingControl != null) { @@ -184,7 +184,7 @@ private Rectangle GetAdjustedEditingControlBounds(Rectangle editingControlBounds case DataGridViewContentAlignment.MiddleLeft: case DataGridViewContentAlignment.BottomLeft: // Add 3 pixels on the left of the editing control to match non-editing text position - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { editingControlBounds.X += 1; editingControlBounds.Width = Math.Max(0, editingControlBounds.Width - DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetLeft - 2); @@ -207,7 +207,7 @@ private Rectangle GetAdjustedEditingControlBounds(Rectangle editingControlBounds case DataGridViewContentAlignment.MiddleRight: case DataGridViewContentAlignment.BottomRight: // Shorten the editing control by 5 pixels to match non-editing text position - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { editingControlBounds.X += DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetRight - 1; editingControlBounds.Width = Math.Max(0, editingControlBounds.Width - DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetRight); @@ -254,7 +254,7 @@ private Rectangle GetAdjustedEditingControlBounds(Rectangle editingControlBounds { editedFormattedValue = " "; } - TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); + TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); using (Graphics g = WindowsFormsUtils.CreateMeasurementGraphics()) { preferredHeight = DataGridViewCell.MeasureTextHeight(g, editedFormattedValue, cellStyle.Font, originalWidth, flags); @@ -293,7 +293,7 @@ protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCel throw new ArgumentNullException(nameof(cellStyle)); } - if (this.DataGridView == null || rowIndex < 0 || this.OwningColumn == null) + if (DataGridView == null || rowIndex < 0 || OwningColumn == null) { return Rectangle.Empty; } @@ -348,10 +348,10 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC throw new ArgumentNullException(nameof(cellStyle)); } - if (this.DataGridView == null || + if (DataGridView == null || rowIndex < 0 || - this.OwningColumn == null || - !this.DataGridView.ShowCellErrors || + OwningColumn == null || + !DataGridView.ShowCellErrors || string.IsNullOrEmpty(GetErrorText(rowIndex))) { return Rectangle.Empty; @@ -402,7 +402,7 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize) { - if (this.DataGridView == null) + if (DataGridView == null) { return new Size(-1, -1); } @@ -413,7 +413,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl } Size preferredSize; - Rectangle borderWidthsRect = this.StdBorderWidths; + Rectangle borderWidthsRect = StdBorderWidths; int borderAndPaddingWidths = borderWidthsRect.Left + borderWidthsRect.Width + cellStyle.Padding.Horizontal; int borderAndPaddingHeights = borderWidthsRect.Top + borderWidthsRect.Height + cellStyle.Padding.Vertical; DataGridViewFreeDimension freeDimension = DataGridViewCell.GetFreeDimensionFromConstraint(constraintSize); @@ -423,7 +423,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl { formattedString = " "; } - TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); + TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); if (cellStyle.WrapMode == DataGridViewTriState.True && formattedString.Length > 1) { switch (freeDimension) @@ -486,7 +486,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl if (freeDimension != DataGridViewFreeDimension.Height) { preferredSize.Width += DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginLeft + DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginRight + borderAndPaddingWidths; - if (this.DataGridView.ShowCellErrors) + if (DataGridView.ShowCellErrors) { // Making sure that there is enough room for the potential error icon preferredSize.Width = Math.Max(preferredSize.Width, borderAndPaddingWidths + DATAGRIDVIEWCELL_iconMarginWidth * 2 + iconsWidth); @@ -496,7 +496,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl { int verticalTextMarginTop = cellStyle.WrapMode == DataGridViewTriState.True ? DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithWrapping : DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithoutWrapping; preferredSize.Height += verticalTextMarginTop + DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginBottom + borderAndPaddingHeights; - if (this.DataGridView.ShowCellErrors) + if (DataGridView.ShowCellErrors) { // Making sure that there is enough room for the potential error icon preferredSize.Height = Math.Max(preferredSize.Height, borderAndPaddingHeights + DATAGRIDVIEWCELL_iconMarginHeight * 2 + iconsHeight); @@ -507,17 +507,17 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle) { - Debug.Assert(this.DataGridView != null && - this.DataGridView.EditingPanel != null && - this.DataGridView.EditingControl != null); - Debug.Assert(!this.ReadOnly); + Debug.Assert(DataGridView != null && + DataGridView.EditingPanel != null && + DataGridView.EditingControl != null); + Debug.Assert(!ReadOnly); base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle); - TextBox textBox = this.DataGridView.EditingControl as TextBox; + TextBox textBox = DataGridView.EditingControl as TextBox; if (textBox != null) { textBox.BorderStyle = BorderStyle.None; textBox.AcceptsReturn = textBox.Multiline = dataGridViewCellStyle.WrapMode == DataGridViewTriState.True; - textBox.MaxLength = this.MaxInputLength; + textBox.MaxLength = MaxInputLength; string initialFormattedValueStr = initialFormattedValue as string; if (initialFormattedValueStr == null) { @@ -528,7 +528,7 @@ public override void InitializeEditingControl(int rowIndex, object initialFormat textBox.Text = initialFormattedValueStr; } - this.EditingTextBox = this.DataGridView.EditingControl as DataGridViewTextBoxEditingControl; + EditingTextBox = DataGridView.EditingControl as DataGridViewTextBoxEditingControl; } } @@ -548,49 +548,49 @@ public override bool KeyEntersEditMode(KeyEventArgs e) protected override void OnEnter(int rowIndex, bool throughMouseClick) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } if (throughMouseClick) { - this.flagsState |= (byte)DATAGRIDVIEWTEXTBOXCELL_ignoreNextMouseClick; + flagsState |= (byte)DATAGRIDVIEWTEXTBOXCELL_ignoreNextMouseClick; } } protected override void OnLeave(int rowIndex, bool throughMouseClick) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } - this.flagsState = (byte)(this.flagsState & ~DATAGRIDVIEWTEXTBOXCELL_ignoreNextMouseClick); + flagsState = (byte)(flagsState & ~DATAGRIDVIEWTEXTBOXCELL_ignoreNextMouseClick); } protected override void OnMouseClick(DataGridViewCellMouseEventArgs e) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } - Debug.Assert(e.ColumnIndex == this.ColumnIndex); - Point ptCurrentCell = this.DataGridView.CurrentCellAddress; + Debug.Assert(e.ColumnIndex == ColumnIndex); + Point ptCurrentCell = DataGridView.CurrentCellAddress; if (ptCurrentCell.X == e.ColumnIndex && ptCurrentCell.Y == e.RowIndex && e.Button == MouseButtons.Left) { - if ((this.flagsState & DATAGRIDVIEWTEXTBOXCELL_ignoreNextMouseClick) != 0x00) + if ((flagsState & DATAGRIDVIEWTEXTBOXCELL_ignoreNextMouseClick) != 0x00) { - this.flagsState = (byte)(this.flagsState & ~DATAGRIDVIEWTEXTBOXCELL_ignoreNextMouseClick); + flagsState = (byte)(flagsState & ~DATAGRIDVIEWTEXTBOXCELL_ignoreNextMouseClick); } - else if (this.DataGridView.EditMode != DataGridViewEditMode.EditProgrammatically) + else if (DataGridView.EditMode != DataGridViewEditMode.EditProgrammatically) { - this.DataGridView.BeginEdit(true /*selectAll*/); + DataGridView.BeginEdit(true /*selectAll*/); } } } private bool OwnsEditingTextBox(int rowIndex) { - return rowIndex != -1 && this.EditingTextBox != null && rowIndex == ((IDataGridViewEditingControl)this.EditingTextBox).EditingControlRowIndex; + return rowIndex != -1 && EditingTextBox != null && rowIndex == ((IDataGridViewEditingControl)EditingTextBox).EditingControlRowIndex; } protected override void Paint(Graphics graphics, @@ -673,18 +673,18 @@ private Rectangle PaintPrivate(Graphics graphics, SolidBrush br; - Point ptCurrentCell = this.DataGridView.CurrentCellAddress; - bool cellCurrent = ptCurrentCell.X == this.ColumnIndex && ptCurrentCell.Y == rowIndex; - bool cellEdited = cellCurrent && this.DataGridView.EditingControl != null; + Point ptCurrentCell = DataGridView.CurrentCellAddress; + bool cellCurrent = ptCurrentCell.X == ColumnIndex && ptCurrentCell.Y == rowIndex; + bool cellEdited = cellCurrent && DataGridView.EditingControl != null; bool cellSelected = (cellState & DataGridViewElementStates.Selected) != 0; if (DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected && !cellEdited) { - br = this.DataGridView.GetCachedBrush(cellStyle.SelectionBackColor); + br = DataGridView.GetCachedBrush(cellStyle.SelectionBackColor); } else { - br = this.DataGridView.GetCachedBrush(cellStyle.BackColor); + br = DataGridView.GetCachedBrush(cellStyle.BackColor); } if (paint && DataGridViewCell.PaintBackground(paintParts) && br.Color.A == 255 && valBounds.Width > 0 && valBounds.Height > 0) @@ -694,7 +694,7 @@ private Rectangle PaintPrivate(Graphics graphics, if (cellStyle.Padding != Padding.Empty) { - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { valBounds.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top); } @@ -710,8 +710,8 @@ private Rectangle PaintPrivate(Graphics graphics, { // Draw focus rectangle if (DataGridViewCell.PaintFocus(paintParts) && - this.DataGridView.ShowFocusCues && - this.DataGridView.Focused && + DataGridView.ShowFocusCues && + DataGridView.Focused && valBounds.Width > 0 && valBounds.Height > 0) { @@ -731,7 +731,7 @@ private Rectangle PaintPrivate(Graphics graphics, valBounds.Height -= verticalTextMarginTop + DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginBottom; if (valBounds.Width > 0 && valBounds.Height > 0) { - TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); + TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); if (paint) { if (DataGridViewCell.PaintContentForeground(paintParts)) @@ -767,7 +767,7 @@ private Rectangle PaintPrivate(Graphics graphics, Debug.Assert(paint || computeContentBounds); } - if (this.DataGridView.ShowCellErrors && paint && DataGridViewCell.PaintErrorIcon(paintParts)) + if (DataGridView.ShowCellErrors && paint && DataGridViewCell.PaintErrorIcon(paintParts)) { PaintErrorIcon(graphics, cellStyle, rowIndex, cellBounds, errorBounds, errorText); } @@ -793,8 +793,8 @@ public override void PositionEditingControl(bool setLocation, isFirstDisplayedColumn, isFirstDisplayedRow); editingControlBounds = GetAdjustedEditingControlBounds(editingControlBounds, cellStyle); - this.DataGridView.EditingControl.Location = new Point(editingControlBounds.X, editingControlBounds.Y); - this.DataGridView.EditingControl.Size = new Size(editingControlBounds.Width, editingControlBounds.Height); + DataGridView.EditingControl.Location = new Point(editingControlBounds.X, editingControlBounds.Y); + DataGridView.EditingControl.Size = new Size(editingControlBounds.Width, editingControlBounds.Height); } public override string ToString() diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxColumn.cs index 59eaccbf364..fd09b322d0d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxColumn.cs @@ -18,7 +18,7 @@ public class DataGridViewTextBoxColumn : DataGridViewColumn public DataGridViewTextBoxColumn() : base(new DataGridViewTextBoxCell()) { - this.SortMode = DataGridViewColumnSortMode.Automatic; + SortMode = DataGridViewColumnSortMode.Automatic; } [ @@ -50,25 +50,25 @@ public int MaxInputLength { get { - if (this.TextBoxCellTemplate == null) + if (TextBoxCellTemplate == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewColumn_CellTemplateRequired)); } - return this.TextBoxCellTemplate.MaxInputLength; + return TextBoxCellTemplate.MaxInputLength; } set { - if (this.MaxInputLength != value) + if (MaxInputLength != value) { - this.TextBoxCellTemplate.MaxInputLength = value; - if (this.DataGridView != null) + TextBoxCellTemplate.MaxInputLength = value; + if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; + DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewTextBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewTextBoxCell; + DataGridViewTextBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewTextBoxCell; if (dataGridViewCell != null) { dataGridViewCell.MaxInputLength = value; @@ -98,7 +98,7 @@ private DataGridViewTextBoxCell TextBoxCellTemplate { get { - return (DataGridViewTextBoxCell)this.CellTemplate; + return (DataGridViewTextBoxCell)CellTemplate; } } @@ -106,9 +106,9 @@ public override string ToString() { StringBuilder sb = new StringBuilder(64); sb.Append("DataGridViewTextBoxColumn { Name="); - sb.Append(this.Name); + sb.Append(Name); sb.Append(", Index="); - sb.Append(this.Index.ToString(CultureInfo.CurrentCulture)); + sb.Append(Index.ToString(CultureInfo.CurrentCulture)); sb.Append(" }"); return sb.ToString(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxEditingControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxEditingControl.cs index 58e47cc63b9..068b1e56291 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxEditingControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxEditingControl.cs @@ -26,7 +26,7 @@ public class DataGridViewTextBoxEditingControl : TextBox, IDataGridViewEditingCo public DataGridViewTextBoxEditingControl() : base() { - this.TabStop = false; + TabStop = false; } protected override AccessibleObject CreateAccessibilityInstance() @@ -38,11 +38,11 @@ public virtual DataGridView EditingControlDataGridView { get { - return this.dataGridView; + return dataGridView; } set { - this.dataGridView = value; + dataGridView = value; } } @@ -54,7 +54,7 @@ public virtual object EditingControlFormattedValue } set { - this.Text = (string)value; + Text = (string)value; } } @@ -62,11 +62,11 @@ public virtual int EditingControlRowIndex { get { - return this.rowIndex; + return rowIndex; } set { - this.rowIndex = value; + rowIndex = value; } } @@ -74,11 +74,11 @@ public virtual bool EditingControlValueChanged { get { - return this.valueChanged; + return valueChanged; } set { - this.valueChanged = value; + valueChanged = value; } } @@ -94,7 +94,7 @@ public virtual bool RepositionEditingControlOnValueChange { get { - return this.repositionOnValueChange; + return repositionOnValueChange; } } @@ -102,25 +102,25 @@ public virtual bool RepositionEditingControlOnValueChange public virtual void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle) { - this.Font = dataGridViewCellStyle.Font; + Font = dataGridViewCellStyle.Font; if (dataGridViewCellStyle.BackColor.A < 255) { // Our TextBox does not support transparent back colors Color opaqueBackColor = Color.FromArgb(255, dataGridViewCellStyle.BackColor); - this.BackColor = opaqueBackColor; - this.dataGridView.EditingPanel.BackColor = opaqueBackColor; + BackColor = opaqueBackColor; + dataGridView.EditingPanel.BackColor = opaqueBackColor; } else { - this.BackColor = dataGridViewCellStyle.BackColor; + BackColor = dataGridViewCellStyle.BackColor; } - this.ForeColor = dataGridViewCellStyle.ForeColor; + ForeColor = dataGridViewCellStyle.ForeColor; if (dataGridViewCellStyle.WrapMode == DataGridViewTriState.True) { - this.WordWrap = true; + WordWrap = true; } - this.TextAlign = TranslateAlignment(dataGridViewCellStyle.Alignment); - this.repositionOnValueChange = (dataGridViewCellStyle.WrapMode == DataGridViewTriState.True && (dataGridViewCellStyle.Alignment & anyTop) == 0); + TextAlign = TranslateAlignment(dataGridViewCellStyle.Alignment); + repositionOnValueChange = (dataGridViewCellStyle.WrapMode == DataGridViewTriState.True && (dataGridViewCellStyle.Alignment & anyTop) == 0); } public virtual bool EditingControlWantsInputKey(Keys keyData, bool dataGridViewWantsInputKey) @@ -130,8 +130,8 @@ public virtual bool EditingControlWantsInputKey(Keys keyData, bool dataGridViewW case Keys.Right: // If the end of the selection is at the end of the string // let the DataGridView treat the key message - if ((this.RightToLeft == RightToLeft.No && !(this.SelectionLength == 0 && this.SelectionStart == this.Text.Length)) || - (this.RightToLeft == RightToLeft.Yes && !(this.SelectionLength == 0 && this.SelectionStart == 0))) + if ((RightToLeft == RightToLeft.No && !(SelectionLength == 0 && SelectionStart == Text.Length)) || + (RightToLeft == RightToLeft.Yes && !(SelectionLength == 0 && SelectionStart == 0))) { return true; } @@ -141,8 +141,8 @@ public virtual bool EditingControlWantsInputKey(Keys keyData, bool dataGridViewW // If the end of the selection is at the begining of the string // or if the entire text is selected and we did not start editing // send this character to the dataGridView, else process the key event - if ((this.RightToLeft == RightToLeft.No && !(this.SelectionLength == 0 && this.SelectionStart == 0)) || - (this.RightToLeft == RightToLeft.Yes && !(this.SelectionLength == 0 && this.SelectionStart == this.Text.Length))) + if ((RightToLeft == RightToLeft.No && !(SelectionLength == 0 && SelectionStart == 0)) || + (RightToLeft == RightToLeft.Yes && !(SelectionLength == 0 && SelectionStart == Text.Length))) { return true; } @@ -151,8 +151,8 @@ public virtual bool EditingControlWantsInputKey(Keys keyData, bool dataGridViewW case Keys.Down: // If the end of the selection is on the last line of the text then // send this character to the dataGridView, else process the key event - int end = this.SelectionStart + this.SelectionLength; - if (this.Text.IndexOf("\r\n", end) != -1) + int end = SelectionStart + SelectionLength; + if (Text.IndexOf("\r\n", end) != -1) { return true; } @@ -161,7 +161,7 @@ public virtual bool EditingControlWantsInputKey(Keys keyData, bool dataGridViewW case Keys.Up: // If the end of the selection is on the first line of the text then // send this character to the dataGridView, else process the key event - if (!(this.Text.IndexOf("\r\n") < 0 || this.SelectionStart + this.SelectionLength < this.Text.IndexOf("\r\n"))) + if (!(Text.IndexOf("\r\n") < 0 || SelectionStart + SelectionLength < Text.IndexOf("\r\n"))) { return true; } @@ -169,7 +169,7 @@ public virtual bool EditingControlWantsInputKey(Keys keyData, bool dataGridViewW case Keys.Home: case Keys.End: - if (this.SelectionLength != this.Text.Length) + if (SelectionLength != Text.Length) { return true; } @@ -177,22 +177,22 @@ public virtual bool EditingControlWantsInputKey(Keys keyData, bool dataGridViewW case Keys.Prior: case Keys.Next: - if (this.valueChanged) + if (valueChanged) { return true; } break; case Keys.Delete: - if (this.SelectionLength > 0 || - this.SelectionStart < this.Text.Length) + if (SelectionLength > 0 || + SelectionStart < Text.Length) { return true; } break; case Keys.Enter: - if ((keyData & (Keys.Control | Keys.Shift | Keys.Alt)) == Keys.Shift && this.Multiline && this.AcceptsReturn) + if ((keyData & (Keys.Control | Keys.Shift | Keys.Alt)) == Keys.Shift && Multiline && AcceptsReturn) { return true; } @@ -203,7 +203,7 @@ public virtual bool EditingControlWantsInputKey(Keys keyData, bool dataGridViewW public virtual object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context) { - return this.Text; + return Text; } public virtual void PrepareEditingControlForEdit(bool selectAll) @@ -216,14 +216,14 @@ public virtual void PrepareEditingControlForEdit(bool selectAll) { // Do not select all the text, but // position the caret at the end of the text - this.SelectionStart = this.Text.Length; + SelectionStart = Text.Length; } } private void NotifyDataGridViewOfValueChange() { - this.valueChanged = true; - this.dataGridView.NotifyCurrentCellDirty(true); + valueChanged = true; + dataGridView.NotifyCurrentCellDirty(true); } protected override void OnGotFocus(EventArgs e) @@ -236,7 +236,7 @@ protected override void OnGotFocus(EventArgs e) protected override void OnMouseWheel(MouseEventArgs e) { // Forwarding to grid control. Can't prevent the TextBox from handling the mouse wheel as expected. - this.dataGridView.OnMouseWheelInternal(e); + dataGridView.OnMouseWheelInternal(e); } protected override void OnTextChanged(EventArgs e) @@ -252,7 +252,7 @@ protected override bool ProcessKeyEventArgs(ref Message m) { case Keys.Enter: if (m.Msg == Interop.WindowMessages.WM_CHAR && - !(ModifierKeys == Keys.Shift && this.Multiline && this.AcceptsReturn)) + !(ModifierKeys == Keys.Shift && Multiline && AcceptsReturn)) { // Ignore the Enter key and don't add it to the textbox content. This happens when failing validation brings // up a dialog box for example. @@ -263,7 +263,7 @@ protected override bool ProcessKeyEventArgs(ref Message m) case Keys.LineFeed: if (m.Msg == Interop.WindowMessages.WM_CHAR && - ModifierKeys == Keys.Control && this.Multiline && this.AcceptsReturn) + ModifierKeys == Keys.Control && Multiline && AcceptsReturn) { // Ignore linefeed character when user hits Ctrl-Enter to commit the cell. return true; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewToolTip.cs index 7d77184ee4e..5f0faf53bc7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewToolTip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewToolTip.cs @@ -25,7 +25,7 @@ public bool Activated { get { - return this.toolTipActivated; + return toolTipActivated; } } @@ -33,48 +33,48 @@ public ToolTip ToolTip { get { - return this.toolTip; + return toolTip; } } public void Activate(bool activate) { - if (this.dataGridView.DesignMode) + if (dataGridView.DesignMode) { return; } // Create the tool tip handle on demand. - if (activate && this.toolTip == null) + if (activate && toolTip == null) { - this.toolTip = new ToolTip(); - this.toolTip.ShowAlways = true; - this.toolTip.InitialDelay = 0; - this.toolTip.UseFading = false; - this.toolTip.UseAnimation = false; - this.toolTip.AutoPopDelay = 0; + toolTip = new ToolTip(); + toolTip.ShowAlways = true; + toolTip.InitialDelay = 0; + toolTip.UseFading = false; + toolTip.UseAnimation = false; + toolTip.AutoPopDelay = 0; } if (activate) { - this.toolTip.Active = true; - this.toolTip.Show(this.dataGridView.ToolTipPrivate, this.dataGridView); + toolTip.Active = true; + toolTip.Show(dataGridView.ToolTipPrivate, dataGridView); } - else if (this.toolTip != null) + else if (toolTip != null) { - this.toolTip.Hide(this.dataGridView); - this.toolTip.Active = false; + toolTip.Hide(dataGridView); + toolTip.Active = false; } - this.toolTipActivated = activate; + toolTipActivated = activate; } public void Dispose() { - if (this.toolTip != null) + if (toolTip != null) { - this.toolTip.Dispose(); - this.toolTip = null; + toolTip.Dispose(); + toolTip = null; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopLeftHeaderCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopLeftHeaderCell.cs index de326324644..71a9841ccfd 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopLeftHeaderCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopLeftHeaderCell.cs @@ -43,7 +43,7 @@ protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCel throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - if (this.DataGridView == null) + if (DataGridView == null) { return Rectangle.Empty; } @@ -102,7 +102,7 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - if (this.DataGridView == null) + if (DataGridView == null) { return Rectangle.Empty; } @@ -161,7 +161,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - if (this.DataGridView == null) + if (DataGridView == null) { return new Size(-1, -1); } @@ -171,10 +171,10 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl throw new ArgumentNullException(nameof(cellStyle)); } - Rectangle borderWidthsRect = BorderWidths(this.DataGridView.AdjustedTopLeftHeaderBorderStyle); + Rectangle borderWidthsRect = BorderWidths(DataGridView.AdjustedTopLeftHeaderBorderStyle); int borderAndPaddingWidths = borderWidthsRect.Left + borderWidthsRect.Width + cellStyle.Padding.Horizontal; int borderAndPaddingHeights = borderWidthsRect.Top + borderWidthsRect.Height + cellStyle.Padding.Vertical; - TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); + TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); // Intentionally not using GetFormattedValue because header cells don't typically perform formatting. object val = GetValue(rowIndex); @@ -187,7 +187,7 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl cellStyle, borderAndPaddingWidths, borderAndPaddingHeights, - this.DataGridView.ShowCellErrors, + DataGridView.ShowCellErrors, false /*showGlyph*/, constraintSize, flags); @@ -271,17 +271,17 @@ private Rectangle PaintPrivate(Graphics graphics, if (paint && DataGridViewCell.PaintBackground(paintParts)) { - if (this.DataGridView.ApplyVisualStylesToHeaderCells) + if (DataGridView.ApplyVisualStylesToHeaderCells) { // Theming int state = (int)HeaderItemState.Normal; - if (this.ButtonState != ButtonState.Normal) + if (ButtonState != ButtonState.Normal) { - Debug.Assert(this.ButtonState == ButtonState.Pushed); + Debug.Assert(ButtonState == ButtonState.Pushed); state = (int)HeaderItemState.Pressed; } - else if (this.DataGridView.MouseEnteredCellAddress.Y == rowIndex && this.DataGridView.MouseEnteredCellAddress.X == this.ColumnIndex) + else if (DataGridView.MouseEnteredCellAddress.Y == rowIndex && DataGridView.MouseEnteredCellAddress.X == ColumnIndex) { state = (int)HeaderItemState.Hot; } @@ -292,7 +292,7 @@ private Rectangle PaintPrivate(Graphics graphics, } else { - SolidBrush br = this.DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor); + SolidBrush br = DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor); if (br.Color.A == 255) { graphics.FillRectangle(br, valBounds); @@ -307,7 +307,7 @@ private Rectangle PaintPrivate(Graphics graphics, if (cellStyle.Padding != Padding.Empty) { - if (this.DataGridView.RightToLeftInternal) + if (DataGridView.RightToLeftInternal) { valBounds.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top); } @@ -332,7 +332,7 @@ private Rectangle PaintPrivate(Graphics graphics, (paint || computeContentBounds)) { Color textColor; - if (this.DataGridView.ApplyVisualStylesToHeaderCells) + if (DataGridView.ApplyVisualStylesToHeaderCells) { textColor = DataGridViewTopLeftHeaderCellRenderer.VisualStyleRenderer.GetColor(ColorProperty.TextColor); } @@ -340,7 +340,7 @@ private Rectangle PaintPrivate(Graphics graphics, { textColor = cellSelected ? cellStyle.SelectionForeColor : cellStyle.ForeColor; } - TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); + TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); if (paint) { if (DataGridViewCell.PaintContentForeground(paintParts)) @@ -368,7 +368,7 @@ private Rectangle PaintPrivate(Graphics graphics, resultBounds = ComputeErrorIconBounds(errorBounds); } - if (this.DataGridView.ShowCellErrors && paint && DataGridViewCell.PaintErrorIcon(paintParts)) + if (DataGridView.ShowCellErrors && paint && DataGridViewCell.PaintErrorIcon(paintParts)) { PaintErrorIcon(graphics, cellStyle, rowIndex, cellBounds, errorBounds, errorText); } @@ -382,31 +382,31 @@ protected override void PaintBorder(Graphics graphics, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle) { - if (this.DataGridView == null) + if (DataGridView == null) { return; } base.PaintBorder(graphics, clipBounds, bounds, cellStyle, advancedBorderStyle); - if (!this.DataGridView.RightToLeftInternal && - this.DataGridView.ApplyVisualStylesToHeaderCells) + if (!DataGridView.RightToLeftInternal && + DataGridView.ApplyVisualStylesToHeaderCells) { - if (this.DataGridView.AdvancedColumnHeadersBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Inset) + if (DataGridView.AdvancedColumnHeadersBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Inset) { Pen penControlDark = null, penControlLightLight = null; GetContrastedPens(cellStyle.BackColor, ref penControlDark, ref penControlLightLight); graphics.DrawLine(penControlDark, bounds.X, bounds.Y, bounds.X, bounds.Bottom - 1); graphics.DrawLine(penControlDark, bounds.X, bounds.Y, bounds.Right - 1, bounds.Y); } - else if (this.DataGridView.AdvancedColumnHeadersBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Outset) + else if (DataGridView.AdvancedColumnHeadersBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Outset) { Pen penControlDark = null, penControlLightLight = null; GetContrastedPens(cellStyle.BackColor, ref penControlDark, ref penControlLightLight); graphics.DrawLine(penControlLightLight, bounds.X, bounds.Y, bounds.X, bounds.Bottom - 1); graphics.DrawLine(penControlLightLight, bounds.X, bounds.Y, bounds.Right - 1, bounds.Y); } - else if (this.DataGridView.AdvancedColumnHeadersBorderStyle.All == DataGridViewAdvancedCellBorderStyle.InsetDouble) + else if (DataGridView.AdvancedColumnHeadersBorderStyle.All == DataGridViewAdvancedCellBorderStyle.InsetDouble) { Pen penControlDark = null, penControlLightLight = null; GetContrastedPens(cellStyle.BackColor, ref penControlDark, ref penControlLightLight); @@ -462,8 +462,8 @@ public override Rectangle Bounds { get { - Rectangle cellRect = this.Owner.DataGridView.GetCellDisplayRectangle(-1, -1, false /*cutOverflow*/); - return this.Owner.DataGridView.RectangleToScreen(cellRect); + Rectangle cellRect = Owner.DataGridView.GetCellDisplayRectangle(-1, -1, false /*cutOverflow*/); + return Owner.DataGridView.RectangleToScreen(cellRect); } } @@ -471,7 +471,7 @@ public override string DefaultAction { get { - if (this.Owner.DataGridView.MultiSelect) + if (Owner.DataGridView.MultiSelect) { return string.Format(SR.DataGridView_AccTopLeftColumnHeaderCellDefaultAction); } @@ -487,7 +487,7 @@ public override string Name { get { - object value = this.Owner.Value; + object value = Owner.Value; if (value != null && !(value is string)) { // The user set the Value on the DataGridViewTopLeftHeaderCell and it did not set it to a string. @@ -498,9 +498,9 @@ public override string Name string strValue = value as string; if (string.IsNullOrEmpty(strValue)) { - if (this.Owner.DataGridView != null) + if (Owner.DataGridView != null) { - if (this.Owner.DataGridView.RightToLeft == RightToLeft.No) + if (Owner.DataGridView.RightToLeft == RightToLeft.No) { return string.Format(SR.DataGridView_AccTopLeftColumnHeaderCellName); } @@ -535,7 +535,7 @@ public override AccessibleStates State } // If all the cells are selected, then the top left header cell accessible object is considered to be selected as well. - if (this.Owner.DataGridView.AreAllCellsSelected(false /*includeInvisibleCells*/)) + if (Owner.DataGridView.AreAllCellsSelected(false /*includeInvisibleCells*/)) { resultState |= AccessibleStates.Selected; } @@ -556,18 +556,18 @@ public override string Value public override void DoDefaultAction() { - this.Owner.DataGridView.SelectAll(); + Owner.DataGridView.SelectAll(); } public override AccessibleObject Navigate(AccessibleNavigation navigationDirection) { - Debug.Assert(this.Owner.DataGridView.RowHeadersVisible, "if the row headers are not visible how did you get the top left header cell acc object?"); + Debug.Assert(Owner.DataGridView.RowHeadersVisible, "if the row headers are not visible how did you get the top left header cell acc object?"); switch (navigationDirection) { case AccessibleNavigation.Previous: return null; case AccessibleNavigation.Left: - if (this.Owner.DataGridView.RightToLeft == RightToLeft.No) + if (Owner.DataGridView.RightToLeft == RightToLeft.No) { return null; } @@ -578,7 +578,7 @@ public override AccessibleObject Navigate(AccessibleNavigation navigationDirecti case AccessibleNavigation.Next: return NavigateForward(); case AccessibleNavigation.Right: - if (this.Owner.DataGridView.RightToLeft == RightToLeft.No) + if (Owner.DataGridView.RightToLeft == RightToLeft.No) { return NavigateForward(); } @@ -593,18 +593,18 @@ public override AccessibleObject Navigate(AccessibleNavigation navigationDirecti private AccessibleObject NavigateForward() { - if (this.Owner.DataGridView.Columns.GetColumnCount(DataGridViewElementStates.Visible) == 0) + if (Owner.DataGridView.Columns.GetColumnCount(DataGridViewElementStates.Visible) == 0) { return null; } // return the acc object for the first visible column - return this.Owner.DataGridView.AccessibilityObject.GetChild(0).GetChild(1); + return Owner.DataGridView.AccessibilityObject.GetChild(0).GetChild(1); } public override void Select(AccessibleSelection flags) { - if (this.Owner == null) + if (Owner == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet)); } @@ -613,27 +613,27 @@ public override void Select(AccessibleSelection flags) if ((flags & AccessibleSelection.TakeFocus) == AccessibleSelection.TakeFocus) { // Focus the grid - this.Owner.DataGridView.Focus(); - if (this.Owner.DataGridView.Columns.GetColumnCount(DataGridViewElementStates.Visible) > 0 && - this.Owner.DataGridView.Rows.GetRowCount(DataGridViewElementStates.Visible) > 0) + Owner.DataGridView.Focus(); + if (Owner.DataGridView.Columns.GetColumnCount(DataGridViewElementStates.Visible) > 0 && + Owner.DataGridView.Rows.GetRowCount(DataGridViewElementStates.Visible) > 0) { // This means that there are visible rows and columns. // Focus the first data cell. - DataGridViewRow row = this.Owner.DataGridView.Rows[this.Owner.DataGridView.Rows.GetFirstRow(DataGridViewElementStates.Visible)]; - DataGridViewColumn col = this.Owner.DataGridView.Columns.GetFirstColumn(DataGridViewElementStates.Visible); + DataGridViewRow row = Owner.DataGridView.Rows[Owner.DataGridView.Rows.GetFirstRow(DataGridViewElementStates.Visible)]; + DataGridViewColumn col = Owner.DataGridView.Columns.GetFirstColumn(DataGridViewElementStates.Visible); // DataGridView::set_CurrentCell clears the previous selection. // So use SetCurrenCellAddressCore directly. - this.Owner.DataGridView.SetCurrentCellAddressCoreInternal(col.Index, row.Index, false /*setAnchorCellAddress*/, true /*validateCurrentCell*/, false /*thoughMouseClick*/); + Owner.DataGridView.SetCurrentCellAddressCoreInternal(col.Index, row.Index, false /*setAnchorCellAddress*/, true /*validateCurrentCell*/, false /*thoughMouseClick*/); } } // AddSelection selects the entire grid. if ((flags & AccessibleSelection.AddSelection) == AccessibleSelection.AddSelection) { - if (this.Owner.DataGridView.MultiSelect) + if (Owner.DataGridView.MultiSelect) { - this.Owner.DataGridView.SelectAll(); + Owner.DataGridView.SelectAll(); } } @@ -642,7 +642,7 @@ public override void Select(AccessibleSelection flags) if ((flags & AccessibleSelection.RemoveSelection) == AccessibleSelection.RemoveSelection && (flags & AccessibleSelection.AddSelection) == 0) { - this.Owner.DataGridView.ClearSelection(); + Owner.DataGridView.ClearSelection(); } } @@ -650,7 +650,7 @@ public override void Select(AccessibleSelection flags) internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - var dataGridView = this.Owner.DataGridView; + var dataGridView = Owner.DataGridView; switch (direction) { @@ -679,13 +679,13 @@ internal override object GetPropertyValue(int propertyId) switch (propertyId) { case NativeMethods.UIA_NamePropertyId: - return this.Name; + return Name; case NativeMethods.UIA_ControlTypePropertyId: return NativeMethods.UIA_HeaderControlTypeId; case NativeMethods.UIA_IsEnabledPropertyId: return Owner.DataGridView.Enabled; case NativeMethods.UIA_HelpTextPropertyId: - return this.Help ?? string.Empty; + return Help ?? string.Empty; case NativeMethods.UIA_IsKeyboardFocusablePropertyId: case NativeMethods.UIA_IsPasswordPropertyId: case NativeMethods.UIA_IsOffscreenPropertyId: diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopRowAccessibleObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopRowAccessibleObject.cs index 121f2995700..58eac448796 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopRowAccessibleObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopRowAccessibleObject.cs @@ -31,14 +31,14 @@ public override Rectangle Bounds { get { - if (this.owner == null) + if (owner == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewTopRowAccessibleObject_OwnerNotSet)); } - if (this.owner.ColumnHeadersVisible) + if (owner.ColumnHeadersVisible) { - Rectangle rect = Rectangle.Union(this.owner.layout.ColumnHeaders, this.owner.layout.TopLeftHeader); - return this.owner.RectangleToScreen(rect); + Rectangle rect = Rectangle.Union(owner.layout.ColumnHeaders, owner.layout.TopLeftHeader); + return owner.RectangleToScreen(rect); } else { @@ -59,15 +59,15 @@ public DataGridView Owner { get { - return this.owner; + return owner; } set { - if (this.owner != null) + if (owner != null) { throw new InvalidOperationException(string.Format(SR.DataGridViewTopRowAccessibleObject_OwnerAlreadySet)); } - this.owner = value; + owner = value; } } @@ -75,11 +75,11 @@ public override AccessibleObject Parent { get { - if (this.owner == null) + if (owner == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewTopRowAccessibleObject_OwnerNotSet)); } - return this.owner.AccessibilityObject; + return owner.AccessibilityObject; } } @@ -99,8 +99,8 @@ internal override int[] RuntimeId { runtimeId = new int[3]; runtimeId[0] = RuntimeIDFirstItem; // first item is static - 0x2a - runtimeId[1] = this.Parent.GetHashCode(); - runtimeId[2] = this.GetHashCode(); + runtimeId[1] = Parent.GetHashCode(); + runtimeId[2] = GetHashCode(); } return runtimeId; @@ -111,13 +111,13 @@ public override string Value { get { - return this.Name; + return Name; } } public override AccessibleObject GetChild(int index) { - if (this.owner == null) + if (owner == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewTopRowAccessibleObject_OwnerNotSet)); } @@ -127,12 +127,12 @@ public override AccessibleObject GetChild(int index) throw new ArgumentOutOfRangeException(nameof(index)); } - if (index == 0 && this.owner.RowHeadersVisible) + if (index == 0 && owner.RowHeadersVisible) { - return this.owner.TopLeftHeaderCell.AccessibilityObject; + return owner.TopLeftHeaderCell.AccessibilityObject; } - if (this.owner.RowHeadersVisible) + if (owner.RowHeadersVisible) { // decrement the index because the first child is the top left header cell index--; @@ -140,10 +140,10 @@ public override AccessibleObject GetChild(int index) Debug.Assert(index >= 0); - if (index < this.owner.Columns.GetColumnCount(DataGridViewElementStates.Visible)) + if (index < owner.Columns.GetColumnCount(DataGridViewElementStates.Visible)) { - int actualColumnIndex = this.owner.Columns.ActualDisplayIndexToColumnIndex(index, DataGridViewElementStates.Visible); - return this.owner.Columns[actualColumnIndex].HeaderCell.AccessibilityObject; + int actualColumnIndex = owner.Columns.ActualDisplayIndexToColumnIndex(index, DataGridViewElementStates.Visible); + return owner.Columns[actualColumnIndex].HeaderCell.AccessibilityObject; } else { @@ -153,12 +153,12 @@ public override AccessibleObject GetChild(int index) public override int GetChildCount() { - if (this.owner == null) + if (owner == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewTopRowAccessibleObject_OwnerNotSet)); } - int result = this.owner.Columns.GetColumnCount(DataGridViewElementStates.Visible); - if (this.owner.RowHeadersVisible) + int result = owner.Columns.GetColumnCount(DataGridViewElementStates.Visible); + if (owner.RowHeadersVisible) { // + 1 is the top left header cell accessibility object result++; @@ -169,7 +169,7 @@ public override int GetChildCount() public override AccessibleObject Navigate(AccessibleNavigation navigationDirection) { - if (this.owner == null) + if (owner == null) { throw new InvalidOperationException(string.Format(SR.DataGridViewTopRowAccessibleObject_OwnerNotSet)); } @@ -177,18 +177,18 @@ public override AccessibleObject Navigate(AccessibleNavigation navigationDirecti { case AccessibleNavigation.Down: case AccessibleNavigation.Next: - if (this.owner.AccessibilityObject.GetChildCount() > 1) + if (owner.AccessibilityObject.GetChildCount() > 1) { - return this.owner.AccessibilityObject.GetChild(1); + return owner.AccessibilityObject.GetChild(1); } else { return null; } case AccessibleNavigation.FirstChild: - return this.GetChild(0); + return GetChild(0); case AccessibleNavigation.LastChild: - return this.GetChild(this.GetChildCount() - 1); + return GetChild(GetChildCount() - 1); default: return null; } @@ -200,7 +200,7 @@ internal override Rectangle BoundingRectangle { get { - return this.Bounds; + return Bounds; } } @@ -208,7 +208,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRo { get { - return this.owner.AccessibilityObject; + return owner.AccessibilityObject; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs index 5a53417ac15..4a927a39945 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs @@ -1279,7 +1279,7 @@ public int Next(int celt, FORMATETC[] rgelt, int[] pceltFetched) public int Skip(int celt) { Debug.WriteLineIf(CompModSwitches.DataObject.TraceVerbose, "FormatEnumerator: Skip"); - if (current + celt >= this.formats.Count) + if (current + celt >= formats.Count) { return NativeMethods.S_FALSE; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataStreamFromComStream.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataStreamFromComStream.cs index ec114601ace..55a2d7b1875 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataStreamFromComStream.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataStreamFromComStream.cs @@ -64,9 +64,9 @@ public override long Length { get { - long curPos = this.Position; + long curPos = Position; long endPos = Seek(0, SeekOrigin.End); - this.Position = curPos; + Position = curPos; return endPos - curPos; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DatagridviewDisplayedBandsData.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DatagridviewDisplayedBandsData.cs index 8078f473bf7..54bea2d2c62 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DatagridviewDisplayedBandsData.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DatagridviewDisplayedBandsData.cs @@ -33,23 +33,23 @@ internal class DisplayedBandsData public DisplayedBandsData() { - this.firstDisplayedFrozenRow = -1; - this.firstDisplayedFrozenCol = -1; - this.firstDisplayedScrollingRow = -1; - this.firstDisplayedScrollingCol = -1; - this.lastTotallyDisplayedScrollingCol = -1; - this.lastDisplayedScrollingRow = -1; - this.lastDisplayedFrozenCol = -1; - this.lastDisplayedFrozenRow = -1; - this.oldFirstDisplayedScrollingRow = -1; - this.oldFirstDisplayedScrollingCol = -1; + firstDisplayedFrozenRow = -1; + firstDisplayedFrozenCol = -1; + firstDisplayedScrollingRow = -1; + firstDisplayedScrollingCol = -1; + lastTotallyDisplayedScrollingCol = -1; + lastDisplayedScrollingRow = -1; + lastDisplayedFrozenCol = -1; + lastDisplayedFrozenRow = -1; + oldFirstDisplayedScrollingRow = -1; + oldFirstDisplayedScrollingCol = -1; } public bool ColumnInsertionOccurred { get { - return this.columnInsertionOccurred; + return columnInsertionOccurred; } } @@ -57,11 +57,11 @@ public bool Dirty { get { - return this.dirty; + return dirty; } set { - this.dirty = value; + dirty = value; } } @@ -69,10 +69,10 @@ public int FirstDisplayedFrozenCol { set { - if (value != this.firstDisplayedFrozenCol) + if (value != firstDisplayedFrozenCol) { EnsureDirtyState(); - this.firstDisplayedFrozenCol = value; + firstDisplayedFrozenCol = value; } } } @@ -81,10 +81,10 @@ public int FirstDisplayedFrozenRow { set { - if (value != this.firstDisplayedFrozenRow) + if (value != firstDisplayedFrozenRow) { EnsureDirtyState(); - this.firstDisplayedFrozenRow = value; + firstDisplayedFrozenRow = value; } } } @@ -93,14 +93,14 @@ public int FirstDisplayedScrollingCol { get { - return this.firstDisplayedScrollingCol; + return firstDisplayedScrollingCol; } set { - if (value != this.firstDisplayedScrollingCol) + if (value != firstDisplayedScrollingCol) { EnsureDirtyState(); - this.firstDisplayedScrollingCol = value; + firstDisplayedScrollingCol = value; } } } @@ -109,14 +109,14 @@ public int FirstDisplayedScrollingRow { get { - return this.firstDisplayedScrollingRow; + return firstDisplayedScrollingRow; } set { - if (value != this.firstDisplayedScrollingRow) + if (value != firstDisplayedScrollingRow) { EnsureDirtyState(); - this.firstDisplayedScrollingRow = value; + firstDisplayedScrollingRow = value; } } } @@ -125,10 +125,10 @@ public int LastDisplayedFrozenCol { set { - if (value != this.lastDisplayedFrozenCol) + if (value != lastDisplayedFrozenCol) { EnsureDirtyState(); - this.lastDisplayedFrozenCol = value; + lastDisplayedFrozenCol = value; } } } @@ -137,10 +137,10 @@ public int LastDisplayedFrozenRow { set { - if (value != this.lastDisplayedFrozenRow) + if (value != lastDisplayedFrozenRow) { EnsureDirtyState(); - this.lastDisplayedFrozenRow = value; + lastDisplayedFrozenRow = value; } } } @@ -149,10 +149,10 @@ public int LastDisplayedScrollingRow { set { - if (value != this.lastDisplayedScrollingRow) + if (value != lastDisplayedScrollingRow) { EnsureDirtyState(); - this.lastDisplayedScrollingRow = value; + lastDisplayedScrollingRow = value; } } } @@ -161,14 +161,14 @@ public int LastTotallyDisplayedScrollingCol { get { - return this.lastTotallyDisplayedScrollingCol; + return lastTotallyDisplayedScrollingCol; } set { - if (value != this.lastTotallyDisplayedScrollingCol) + if (value != lastTotallyDisplayedScrollingCol) { EnsureDirtyState(); - this.lastTotallyDisplayedScrollingCol = value; + lastTotallyDisplayedScrollingCol = value; } } } @@ -177,14 +177,14 @@ public int NumDisplayedFrozenCols { get { - return this.numDisplayedFrozenCols; + return numDisplayedFrozenCols; } set { - if (value != this.numDisplayedFrozenCols) + if (value != numDisplayedFrozenCols) { EnsureDirtyState(); - this.numDisplayedFrozenCols = value; + numDisplayedFrozenCols = value; } } } @@ -193,14 +193,14 @@ public int NumDisplayedFrozenRows { get { - return this.numDisplayedFrozenRows; + return numDisplayedFrozenRows; } set { - if (value != this.numDisplayedFrozenRows) + if (value != numDisplayedFrozenRows) { EnsureDirtyState(); - this.numDisplayedFrozenRows = value; + numDisplayedFrozenRows = value; } } } @@ -209,14 +209,14 @@ public int NumDisplayedScrollingRows { get { - return this.numDisplayedScrollingRows; + return numDisplayedScrollingRows; } set { - if (value != this.numDisplayedScrollingRows) + if (value != numDisplayedScrollingRows) { EnsureDirtyState(); - this.numDisplayedScrollingRows = value; + numDisplayedScrollingRows = value; } } } @@ -225,14 +225,14 @@ public int NumDisplayedScrollingCols { get { - return this.numDisplayedScrollingCols; + return numDisplayedScrollingCols; } set { - if (value != this.numDisplayedScrollingCols) + if (value != numDisplayedScrollingCols) { EnsureDirtyState(); - this.numDisplayedScrollingCols = value; + numDisplayedScrollingCols = value; } } } @@ -241,14 +241,14 @@ public int NumTotallyDisplayedFrozenRows { get { - return this.numTotallyDisplayedFrozenRows; + return numTotallyDisplayedFrozenRows; } set { - if (value != this.numTotallyDisplayedFrozenRows) + if (value != numTotallyDisplayedFrozenRows) { EnsureDirtyState(); - this.numTotallyDisplayedFrozenRows = value; + numTotallyDisplayedFrozenRows = value; } } } @@ -257,14 +257,14 @@ public int NumTotallyDisplayedScrollingRows { get { - return this.numTotallyDisplayedScrollingRows; + return numTotallyDisplayedScrollingRows; } set { - if (value != this.numTotallyDisplayedScrollingRows) + if (value != numTotallyDisplayedScrollingRows) { EnsureDirtyState(); - this.numTotallyDisplayedScrollingRows = value; + numTotallyDisplayedScrollingRows = value; } } } @@ -273,7 +273,7 @@ public int OldFirstDisplayedScrollingCol { get { - return this.oldFirstDisplayedScrollingCol; + return oldFirstDisplayedScrollingCol; } } @@ -281,7 +281,7 @@ public int OldFirstDisplayedScrollingRow { get { - return this.oldFirstDisplayedScrollingRow; + return oldFirstDisplayedScrollingRow; } } @@ -289,7 +289,7 @@ public int OldNumDisplayedFrozenRows { get { - return this.oldNumDisplayedFrozenRows; + return oldNumDisplayedFrozenRows; } } @@ -297,7 +297,7 @@ public int OldNumDisplayedScrollingRows { get { - return this.oldNumDisplayedScrollingRows; + return oldNumDisplayedScrollingRows; } } @@ -305,17 +305,17 @@ public bool RowInsertionOccurred { get { - return this.rowInsertionOccurred; + return rowInsertionOccurred; } } public void EnsureDirtyState() { - if (!this.dirty) + if (!dirty) { - this.dirty = true; - this.rowInsertionOccurred = false; - this.columnInsertionOccurred = false; + dirty = true; + rowInsertionOccurred = false; + columnInsertionOccurred = false; SetOldValues(); } } @@ -323,41 +323,41 @@ public void EnsureDirtyState() public void CorrectColumnIndexAfterInsertion(int columnIndex, int insertionCount) { EnsureDirtyState(); - if (this.oldFirstDisplayedScrollingCol != -1 && columnIndex <= this.oldFirstDisplayedScrollingCol) + if (oldFirstDisplayedScrollingCol != -1 && columnIndex <= oldFirstDisplayedScrollingCol) { - this.oldFirstDisplayedScrollingCol += insertionCount; + oldFirstDisplayedScrollingCol += insertionCount; } - this.columnInsertionOccurred = true; + columnInsertionOccurred = true; } public void CorrectRowIndexAfterDeletion(int rowIndex) { EnsureDirtyState(); - if (this.oldFirstDisplayedScrollingRow != -1 && rowIndex <= this.oldFirstDisplayedScrollingRow) + if (oldFirstDisplayedScrollingRow != -1 && rowIndex <= oldFirstDisplayedScrollingRow) { - this.oldFirstDisplayedScrollingRow--; + oldFirstDisplayedScrollingRow--; } } public void CorrectRowIndexAfterInsertion(int rowIndex, int insertionCount) { EnsureDirtyState(); - if (this.oldFirstDisplayedScrollingRow != -1 && rowIndex <= this.oldFirstDisplayedScrollingRow) + if (oldFirstDisplayedScrollingRow != -1 && rowIndex <= oldFirstDisplayedScrollingRow) { - this.oldFirstDisplayedScrollingRow += insertionCount; + oldFirstDisplayedScrollingRow += insertionCount; } - this.rowInsertionOccurred = true; - this.oldNumDisplayedScrollingRows += insertionCount; - this.oldNumDisplayedFrozenRows += insertionCount; + rowInsertionOccurred = true; + oldNumDisplayedScrollingRows += insertionCount; + oldNumDisplayedFrozenRows += insertionCount; } private void SetOldValues() { - this.oldFirstDisplayedScrollingRow = this.firstDisplayedScrollingRow; - this.oldFirstDisplayedScrollingCol = this.firstDisplayedScrollingCol; - this.oldNumDisplayedFrozenRows = this.numDisplayedFrozenRows; - this.oldNumDisplayedScrollingRows = this.numDisplayedScrollingRows; + oldFirstDisplayedScrollingRow = firstDisplayedScrollingRow; + oldFirstDisplayedScrollingCol = firstDisplayedScrollingCol; + oldNumDisplayedFrozenRows = numDisplayedFrozenRows; + oldNumDisplayedScrollingRows = numDisplayedScrollingRows; } } } -} \ No newline at end of file +} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs index 545dfffc805..32b26eeb868 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs @@ -413,7 +413,7 @@ public bool Checked get { // the information from win32 DateTimePicker is reliable only when ShowCheckBoxes is True - if (this.ShowCheckBox && IsHandleCreated) + if (ShowCheckBox && IsHandleCreated) { NativeMethods.SYSTEMTIME sys = new NativeMethods.SYSTEMTIME(); int gdt = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.DTM_GETSYSTEMTIME, 0, sys); @@ -426,10 +426,10 @@ public bool Checked } set { - if (this.Checked != value) + if (Checked != value) { // set the information into the win32 DateTimePicker only if ShowCheckBoxes is True - if (this.ShowCheckBox && IsHandleCreated) + if (ShowCheckBox && IsHandleCreated) { if (value) { @@ -447,7 +447,7 @@ public bool Checked // this.validTime is used when the DateTimePicker receives date time change notification // from the Win32 control. this.validTime will be used to know when we transition from valid time to unvalid time // also, validTime will be used when ShowCheckBox == false - this.validTime = value; + validTime = value; } } } @@ -1034,7 +1034,7 @@ public DateTime Value } set { - bool valueChanged = !DateTime.Equals(this.Value, value); + bool valueChanged = !DateTime.Equals(Value, value); // Check for value set here; if we've not set the value yet, it'll be Now, so the second // part of the test will fail. // So, if userHasSetValue isn't set, we don't care if the value is still the same - and we'll @@ -1046,7 +1046,7 @@ public DateTime Value throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidBoundArgument, nameof(Value), FormatDateTime(value), $"'{nameof(MinDate)}'", $"'{nameof(MaxDate)}'")); } - string oldText = this.Text; + string oldText = Text; this.value = value; userHasSetValue = true; @@ -1067,7 +1067,7 @@ public DateTime Value OnValueChanged(EventArgs.Empty); } - if (!oldText.Equals(this.Text)) + if (!oldText.Equals(Text)) { OnTextChanged(EventArgs.Empty); } @@ -1266,7 +1266,7 @@ protected virtual void OnFormatChanged(EventArgs e) protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); - SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(this.MarshaledUserPreferenceChanged); + SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(MarshaledUserPreferenceChanged); } /// @@ -1274,7 +1274,7 @@ protected override void OnHandleCreated(EventArgs e) /// protected override void OnHandleDestroyed(EventArgs e) { - SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(this.MarshaledUserPreferenceChanged); + SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(MarshaledUserPreferenceChanged); base.OnHandleDestroyed(e); } @@ -1390,7 +1390,7 @@ private void ResetValue() { // always update on reset with ShowNone = false -- as it'll take the current time. - this.value = DateTime.Now; + value = DateTime.Now; // If ShowCheckBox = true, then userHasSetValue can be false (null value). // otherwise, userHasSetValue is valid... @@ -1631,7 +1631,7 @@ private void MarshaledUserPreferenceChanged(object sender, UserPreferenceChanged try { //use begininvoke instead of invoke in case the destination thread is not processing messages. - BeginInvoke(new UserPreferenceChangedEventHandler(this.UserPreferenceChanged), new object[] { sender, pref }); + BeginInvoke(new UserPreferenceChangedEventHandler(UserPreferenceChanged), new object[] { sender, pref }); } catch (InvalidOperationException) { } //if the destination thread does not exist, don't send. } @@ -1686,7 +1686,7 @@ private void WmDateTimeChange(ref Message m) private void WmDropDown(ref Message m) { - if (this.RightToLeftLayout == true && this.RightToLeft == RightToLeft.Yes) + if (RightToLeftLayout == true && RightToLeft == RightToLeft.Yes) { IntPtr handle = SendMessage(NativeMethods.DTM_GETMONTHCAL, 0, 0); if (handle != IntPtr.Zero) @@ -1818,7 +1818,7 @@ public override string KeyboardShortcut // APP COMPAT. When computing DateTimePickerAccessibleObject::get_KeyboardShorcut the previous label // takes precedence over DTP::Text. // This code was copied from the Everett sources. - Label previousLabel = this.PreviousLabel; + Label previousLabel = PreviousLabel; if (previousLabel != null) { @@ -1833,7 +1833,7 @@ public override string KeyboardShortcut if ((baseShortcut == null || baseShortcut.Length == 0)) { - char ownerTextMnemonic = WindowsFormsUtils.GetMnemonic(this.Owner.Text, false /*convertToUpperCase*/); + char ownerTextMnemonic = WindowsFormsUtils.GetMnemonic(Owner.Text, false /*convertToUpperCase*/); if (ownerTextMnemonic != (char)0) { return "Alt+" + ownerTextMnemonic; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs index b548749f2b1..f783325f763 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs @@ -219,7 +219,7 @@ private void OnConfigureUI() } } - this.Font = uiFont; + Font = uiFont; okButton = new Button(); cancelButton = new Button(); @@ -231,7 +231,7 @@ private void OnConfigureUI() selector = new PageSelector(); selector.ImageList = selectorImageList; - selector.AfterSelect += new TreeViewEventHandler(this.OnSelChangeSelector); + selector.AfterSelect += new TreeViewEventHandler(OnSelChangeSelector); Label grayStrip = new Label(); grayStrip.BackColor = SystemColors.ControlDark; @@ -268,7 +268,7 @@ private void OnConfigureUI() { caption = SR.ComponentEditorFormPropertiesNoName; } - this.Text = caption; + Text = caption; Rectangle pageHostBounds = new Rectangle(2 * BUTTON_PAD + selectorWidth, 2 * BUTTON_PAD + STRIP_HEIGHT, @@ -292,7 +292,7 @@ private void OnConfigureUI() Size size = new Size(bounds.Width + 3 * (BUTTON_PAD + xFrame) + selectorWidth, bounds.Height + STRIP_HEIGHT + 4 * BUTTON_PAD + BUTTON_HEIGHT + 2 * xFrame + SystemInformation.CaptionHeight); - this.Size = size; + Size = size; selector.Bounds = new Rectangle(BUTTON_PAD, BUTTON_PAD, selectorWidth, bounds.Height + STRIP_HEIGHT + 2 * BUTTON_PAD + BUTTON_HEIGHT); @@ -304,33 +304,33 @@ private void OnConfigureUI() helpButton.Bounds = bounds; helpButton.Text = SR.HelpCaption; - helpButton.Click += new EventHandler(this.OnButtonClick); + helpButton.Click += new EventHandler(OnButtonClick); helpButton.Enabled = false; helpButton.FlatStyle = FlatStyle.System; bounds.X -= (BUTTON_WIDTH + BUTTON_PAD); applyButton.Bounds = bounds; applyButton.Text = SR.ApplyCaption; - applyButton.Click += new EventHandler(this.OnButtonClick); + applyButton.Click += new EventHandler(OnButtonClick); applyButton.Enabled = false; applyButton.FlatStyle = FlatStyle.System; bounds.X -= (BUTTON_WIDTH + BUTTON_PAD); cancelButton.Bounds = bounds; cancelButton.Text = SR.CancelCaption; - cancelButton.Click += new EventHandler(this.OnButtonClick); + cancelButton.Click += new EventHandler(OnButtonClick); cancelButton.FlatStyle = FlatStyle.System; - this.CancelButton = cancelButton; + CancelButton = cancelButton; bounds.X -= (BUTTON_WIDTH + BUTTON_PAD); okButton.Bounds = bounds; okButton.Text = SR.OKCaption; - okButton.Click += new EventHandler(this.OnButtonClick); + okButton.Click += new EventHandler(OnButtonClick); okButton.FlatStyle = FlatStyle.System; - this.AcceptButton = okButton; + AcceptButton = okButton; - this.Controls.Clear(); - this.Controls.AddRange(new Control[] { + Controls.Clear(); + Controls.AddRange(new Control[] { selector, grayStrip, pageHost, @@ -551,8 +551,8 @@ internal ComponentEditorPageSite(Control parent, Type pageClass, IComponent comp { this.component = component; this.parent = parent; - this.isActive = false; - this.isDirty = false; + isActive = false; + isDirty = false; if (form == null) throw new ArgumentNullException(nameof(form)); @@ -664,18 +664,18 @@ internal sealed class PageSelector : TreeView public PageSelector() { - this.HotTracking = true; - this.HideSelection = false; - this.BackColor = SystemColors.Control; - this.Indent = 0; - this.LabelEdit = false; - this.Scrollable = false; - this.ShowLines = false; - this.ShowPlusMinus = false; - this.ShowRootLines = false; - this.BorderStyle = BorderStyle.None; - this.Indent = 0; - this.FullRowSelect = true; + HotTracking = true; + HideSelection = false; + BackColor = SystemColors.Control; + Indent = 0; + LabelEdit = false; + Scrollable = false; + ShowLines = false; + ShowPlusMinus = false; + ShowRootLines = false; + BorderStyle = BorderStyle.None; + Indent = 0; + FullRowSelect = true; } @@ -721,7 +721,7 @@ private void DrawTreeItem(string itemText, int imageIndex, IntPtr dc, NativeMeth IntNativeMethods.SIZE size = new IntNativeMethods.SIZE(); IntNativeMethods.RECT rc2 = new IntNativeMethods.RECT(); IntNativeMethods.RECT rc = new IntNativeMethods.RECT(rcIn.left, rcIn.top, rcIn.right, rcIn.bottom); - ImageList imagelist = this.ImageList; + ImageList imagelist = ImageList; IntPtr hfontOld = IntPtr.Zero; // Select the font of the dialog, so we don't get the underlined font diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorPage.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorPage.cs index f365fa97186..a882beed841 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorPage.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorPage.cs @@ -330,7 +330,7 @@ public virtual void SetComponent(IComponent component) /// public virtual void SetSite(IComponentEditorPageSite site) { - this.pageSite = site; + pageSite = site; pageSite.GetControl().Controls.Add(this); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DockingAttribute.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DockingAttribute.cs index 6ad98f2e3b3..151fde49b4f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DockingAttribute.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DockingAttribute.cs @@ -22,7 +22,7 @@ public sealed class DockingAttribute : Attribute /// public DockingAttribute() { - this.dockingBehavior = DockingBehavior.Never; + dockingBehavior = DockingBehavior.Never; } /// @@ -32,7 +32,7 @@ public DockingAttribute() /// public DockingAttribute(DockingBehavior dockingBehavior) { - this.dockingBehavior = dockingBehavior; + dockingBehavior = dockingBehavior; } /// @@ -67,7 +67,7 @@ public override bool Equals(object obj) DockingAttribute other = obj as DockingAttribute; - return (other != null) && other.DockingBehavior == this.dockingBehavior; + return (other != null) && other.DockingBehavior == dockingBehavior; } public override int GetHashCode() @@ -79,7 +79,7 @@ public override int GetHashCode() /// public override bool IsDefaultAttribute() { - return (this.Equals(Default)); + return Equals(Default); } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs index 33f0f71dbc8..e61cf5a0551 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs @@ -123,7 +123,7 @@ public override ISite Site if (baseComp is ContainerControl) { - this.ContainerControl = (ContainerControl)baseComp; + ContainerControl = (ContainerControl)baseComp; } } } @@ -157,12 +157,12 @@ public ErrorBlinkStyle BlinkStyle // If the blinkRate == 0, then set blinkStyle = neverBlink // - if (this.blinkRate == 0) + if (blinkRate == 0) { value = ErrorBlinkStyle.NeverBlink; } - if (this.blinkStyle == value) + if (blinkStyle == value) { return; } @@ -171,8 +171,8 @@ public ErrorBlinkStyle BlinkStyle { // we need to startBlinking on all the controlItems // in our items hashTable. - this.showIcon = true; - this.blinkStyle = ErrorBlinkStyle.AlwaysBlink; + showIcon = true; + blinkStyle = ErrorBlinkStyle.AlwaysBlink; foreach (ErrorWindow w in windows.Values) { w.StartBlinking(); @@ -181,7 +181,7 @@ public ErrorBlinkStyle BlinkStyle else if (blinkStyle == ErrorBlinkStyle.AlwaysBlink) { // we need to stop blinking... - this.blinkStyle = value; + blinkStyle = value; foreach (ErrorWindow w in windows.Values) { w.StopBlinking(); @@ -189,7 +189,7 @@ public ErrorBlinkStyle BlinkStyle } else { - this.blinkStyle = value; + blinkStyle = value; } } } @@ -222,7 +222,7 @@ public ContainerControl ContainerControl if (parentControl != null) parentControl.BindingContextChanged += propChangedEvent; - Set_ErrorManager(this.DataSource, this.DataMember, true); + Set_ErrorManager(DataSource, DataMember, true); } } } @@ -293,8 +293,8 @@ private void Set_ErrorManager(object newDataSource, string newDataMember, bool f inSetErrorManager = true; try { - bool dataSourceChanged = this.DataSource != newDataSource; - bool dataMemberChanged = this.DataMember != newDataMember; + bool dataSourceChanged = DataSource != newDataSource; + bool dataMemberChanged = DataMember != newDataMember; //if nothing changed, then do not do any work // @@ -305,8 +305,8 @@ private void Set_ErrorManager(object newDataSource, string newDataMember, bool f // set the dataSource and the dataMember // - this.dataSource = newDataSource; - this.dataMember = newDataMember; + dataSource = newDataSource; + dataMember = newDataMember; if (initializing) { @@ -320,9 +320,9 @@ private void Set_ErrorManager(object newDataSource, string newDataMember, bool f // get the new errorManager // - if (parentControl != null && this.dataSource != null && parentControl.BindingContext != null) + if (parentControl != null && dataSource != null && parentControl.BindingContext != null) { - errorManager = parentControl.BindingContext[this.dataSource, this.dataMember]; + errorManager = parentControl.BindingContext[dataSource, dataMember]; } else { @@ -362,21 +362,21 @@ public object DataSource } set { - if (parentControl != null && value != null && !string.IsNullOrEmpty(this.dataMember)) + if (parentControl != null && value != null && !string.IsNullOrEmpty(dataMember)) { // Let's check if the datamember exists in the new data source try { - errorManager = parentControl.BindingContext[value, this.dataMember]; + errorManager = parentControl.BindingContext[value, dataMember]; } catch (ArgumentException) { // The data member doesn't exist in the data source, so set it to null - this.dataMember = string.Empty; + dataMember = string.Empty; } } - Set_ErrorManager(value, this.DataMember, false); + Set_ErrorManager(value, DataMember, false); } } @@ -404,7 +404,7 @@ public string DataMember { if (value == null) value = string.Empty; - Set_ErrorManager(this.DataSource, value, false); + Set_ErrorManager(DataSource, value, false); } } @@ -423,14 +423,14 @@ private void WireEvents(BindingManagerBase listManager) if (listManager != null) { listManager.CurrentChanged += currentChanged; - listManager.BindingComplete += new BindingCompleteEventHandler(this.ErrorManager_BindingComplete); + listManager.BindingComplete += new BindingCompleteEventHandler(ErrorManager_BindingComplete); CurrencyManager currManager = listManager as CurrencyManager; if (currManager != null) { - currManager.ItemChanged += new ItemChangedEventHandler(this.ErrorManager_ItemChanged); - currManager.Bindings.CollectionChanged += new CollectionChangeEventHandler(this.ErrorManager_BindingsChanged); + currManager.ItemChanged += new ItemChangedEventHandler(ErrorManager_ItemChanged); + currManager.Bindings.CollectionChanged += new CollectionChangeEventHandler(ErrorManager_BindingsChanged); } } } @@ -440,14 +440,14 @@ private void UnwireEvents(BindingManagerBase listManager) if (listManager != null) { listManager.CurrentChanged -= currentChanged; - listManager.BindingComplete -= new BindingCompleteEventHandler(this.ErrorManager_BindingComplete); + listManager.BindingComplete -= new BindingCompleteEventHandler(ErrorManager_BindingComplete); CurrencyManager currManager = listManager as CurrencyManager; if (currManager != null) { - currManager.ItemChanged -= new ItemChangedEventHandler(this.ErrorManager_ItemChanged); - currManager.Bindings.CollectionChanged -= new CollectionChangeEventHandler(this.ErrorManager_BindingsChanged); + currManager.ItemChanged -= new ItemChangedEventHandler(ErrorManager_ItemChanged); + currManager.Bindings.CollectionChanged -= new CollectionChangeEventHandler(ErrorManager_BindingsChanged); } } } @@ -469,7 +469,7 @@ private void ErrorManager_BindingsChanged(object sender, CollectionChangeEventAr private void ParentControl_BindingContextChanged(object sender, EventArgs e) { - Set_ErrorManager(this.DataSource, this.DataMember, true); + Set_ErrorManager(DataSource, DataMember, true); } // Work around... we should figure out if errors changed automatically. @@ -690,7 +690,7 @@ private void EndInitCore() if (setErrorManagerOnEndInit) { setErrorManagerOnEndInit = false; - Set_ErrorManager(this.DataSource, this.DataMember, true); + Set_ErrorManager(DataSource, DataMember, true); } } @@ -700,7 +700,7 @@ private void EndInitCore() // void ISupportInitialize.EndInit() { - ISupportInitializeNotification dsInit = (this.DataSource as ISupportInitializeNotification); + ISupportInitializeNotification dsInit = (DataSource as ISupportInitializeNotification); if (dsInit != null && !dsInit.IsInitialized) { @@ -718,7 +718,7 @@ void ISupportInitialize.EndInit() // private void DataSource_Initialized(object sender, EventArgs e) { - ISupportInitializeNotification dsInit = (this.DataSource as ISupportInitializeNotification); + ISupportInitializeNotification dsInit = (DataSource as ISupportInitializeNotification); Debug.Assert(dsInit != null, "ErrorProvider: ISupportInitializeNotification.Initialized event received, but current DataSource does not support ISupportInitializeNotification!"); Debug.Assert(dsInit.IsInitialized, "ErrorProvider: DataSource sent ISupportInitializeNotification.Initialized event but before it had finished initializing."); @@ -1326,7 +1326,7 @@ public void Update(bool timerCaused) DeviceContext dc = null; - dc = DeviceContext.FromHwnd(this.Handle); + dc = DeviceContext.FromHwnd(Handle); try { CreateMirrorDC(dc.Hdc, windowBounds.Width); @@ -1432,9 +1432,9 @@ internal class ControlItem /// public ControlItem(ErrorProvider provider, Control control, IntPtr id) { - this.toolTipShown = false; - this.iconAlignment = defaultIconAlignment; - this.error = string.Empty; + toolTipShown = false; + iconAlignment = defaultIconAlignment; + error = string.Empty; this.id = id; this.control = control; this.provider = provider; @@ -1595,11 +1595,11 @@ public bool ToolTipShown { get { - return this.toolTipShown; + return toolTipShown; } set { - this.toolTipShown = value; + toolTipShown = value; } } @@ -1745,7 +1745,7 @@ void OnBoundsChanged(object sender, EventArgs e) void OnParentVisibleChanged(object sender, EventArgs e) { - this.BlinkPhase = 0; + BlinkPhase = 0; RemoveFromWindow(); AddToWindow(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FileDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FileDialog.cs index e12cf94cfc7..925018e3f37 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FileDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FileDialog.cs @@ -747,7 +747,7 @@ protected override bool RunDialog(IntPtr hWndOwner) private bool RunDialogOld(IntPtr hWndOwner) { - var hookProcPtr = new NativeMethods.WndProc(this.HookProc); + var hookProcPtr = new NativeMethods.WndProc(HookProc); var ofn = new NativeMethods.OPENFILENAME_I(); try { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FontDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FontDialog.cs index 8688e9965b3..8ce317601e0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FontDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FontDialog.cs @@ -415,7 +415,7 @@ public bool ShowColor } set { - this.showColor = value; + showColor = value; } } @@ -583,7 +583,7 @@ private void ResetFont() /// protected override bool RunDialog(IntPtr hWndOwner) { - NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(this.HookProc); + NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(HookProc); NativeMethods.CHOOSEFONT cf = new NativeMethods.CHOOSEFONT(); IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef); NativeMethods.LOGFONT lf = new NativeMethods.LOGFONT(); 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 fa792406a54..af068140fd3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs @@ -310,7 +310,7 @@ internal bool Active } set { - Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Form::set_Active - " + this.Name); + Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Form::set_Active - " + Name); if ((formState[FormStateIsActive] != 0) != value) { if (value) @@ -394,9 +394,9 @@ public Form ActiveMdiChild if (mdiChild == null) { // If this.MdiClient != null it means this.IsMdiContainer == true. - if (this.ctlClient != null && this.ctlClient.IsHandleCreated) + if (ctlClient != null && ctlClient.IsHandleCreated) { - IntPtr hwnd = this.ctlClient.SendMessage(Interop.WindowMessages.WM_MDIGETACTIVE, 0, 0); + IntPtr hwnd = ctlClient.SendMessage(Interop.WindowMessages.WM_MDIGETACTIVE, 0, 0); mdiChild = Control.FromHandle(hwnd) as Form; } } @@ -614,7 +614,7 @@ public override bool AutoSize { minAutoSize = Size.Empty; // If we just disabled AutoSize, restore the original size. - this.Size = CommonProperties.GetSpecifiedBounds(this).Size; + Size = CommonProperties.GetSpecifiedBounds(this).Size; } LayoutTransaction.DoLayout(this, this, PropertyNames.AutoSize); OnAutoSizeChanged(EventArgs.Empty); @@ -909,7 +909,7 @@ protected override CreateParams CreateParams { CreateParams cp = base.CreateParams; - if (this.IsHandleCreated && (this.WindowStyle & NativeMethods.WS_DISABLED) != 0) + if (IsHandleCreated && (WindowStyle & NativeMethods.WS_DISABLED) != 0) { // Forms that are parent of a modal dialog must keep their WS_DISABLED style cp.Style |= NativeMethods.WS_DISABLED; @@ -1293,17 +1293,17 @@ internal bool IsMdiChildFocusable { get { - if (this.Properties.ContainsObject(PropMdiChildFocusable)) + if (Properties.ContainsObject(PropMdiChildFocusable)) { - return (bool)this.Properties.GetObject(PropMdiChildFocusable); + return (bool)Properties.GetObject(PropMdiChildFocusable); } return false; } set { - if (value != this.IsMdiChildFocusable) + if (value != IsMdiChildFocusable) { - this.Properties.SetObject(PropMdiChildFocusable, value); + Properties.SetObject(PropMdiChildFocusable, value); } } } @@ -1635,7 +1635,7 @@ public override Size MinimumSize throw new ArgumentOutOfRangeException(nameof(MinimumSize)); } - Rectangle bounds = this.Bounds; + Rectangle bounds = Bounds; bounds.Size = value; value = WindowsFormsUtils.ConstrainToScreenWorkingAreaBounds(bounds).Size; @@ -1756,7 +1756,7 @@ internal MdiClient MdiClient { get { - return this.ctlClient; + return ctlClient; } } @@ -1881,7 +1881,7 @@ public MainMenu MergedMenu { get { - return this.MergedMenuPrivate; + return MergedMenuPrivate; } } @@ -2012,7 +2012,7 @@ public double Opacity } else { - formState[FormStateLayered] = (this.TransparencyKey != Color.Empty) ? 1 : 0; + formState[FormStateLayered] = (TransparencyKey != Color.Empty) ? 1 : 0; if (oldLayered != (formState[FormStateLayered] != 0)) { int exStyle = unchecked((int)(long)UnsafeNativeMethods.GetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_EXSTYLE)); @@ -2533,7 +2533,7 @@ public Color TransparencyKey } else { - formState[FormStateLayered] = (this.OpacityAsByte < 255) ? 1 : 0; + formState[FormStateLayered] = (OpacityAsByte < 255) ? 1 : 0; } if (oldLayered != (formState[FormStateLayered] != 0)) { @@ -2548,7 +2548,7 @@ public Color TransparencyKey [EditorBrowsable(EditorBrowsableState.Advanced)] protected override void SetVisibleCore(bool value) { - Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Form::SetVisibleCore(" + value.ToString() + ") - " + this.Name); + Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Form::SetVisibleCore(" + value.ToString() + ") - " + Name); // If DialogResult.OK and the value == GetVisibleCore() then this code has been called either through // ShowDialog( ) or explicit Hide( ) by the user. So dont go through this function again. @@ -3433,11 +3433,11 @@ internal override void AfterControlRemoved(Control control, Control oldParent) if (control == AcceptButton) { - this.AcceptButton = null; + AcceptButton = null; } if (control == CancelButton) { - this.CancelButton = null; + CancelButton = null; } if (control == ctlClient) { @@ -4027,7 +4027,7 @@ private void CallShownEvent() /// internal override bool CanSelectCore() { - if (!GetStyle(ControlStyles.Selectable) || !this.Enabled || !this.Visible) + if (!GetStyle(ControlStyles.Selectable) || !Enabled || !Visible) { return false; } @@ -4058,7 +4058,7 @@ internal override bool CanProcessMnemonic() TraceCanProcessMnemonic(); #endif // If this is a Mdi child form, child controls should process mnemonics only if this is the active mdi child. - if (this.IsMdiChild && (formStateEx[FormStateExMnemonicProcessed] == 1 || this != this.MdiParentInternal.ActiveMdiChildInternal || this.WindowState == FormWindowState.Minimized)) + if (IsMdiChild && (formStateEx[FormStateExMnemonicProcessed] == 1 || this != MdiParentInternal.ActiveMdiChildInternal || WindowState == FormWindowState.Minimized)) { return false; } @@ -4079,15 +4079,15 @@ protected internal override bool ProcessMnemonic(char charCode) return true; } - if (this.IsMdiContainer) + if (IsMdiContainer) { // ContainerControl have already processed the active MDI child for us (if any) in the call above, // now process remaining controls (non-mdi children). - if (this.Controls.Count > 1) + if (Controls.Count > 1) { // Ignore the MdiClient control - for (int index = 0; index < this.Controls.Count; index++) + for (int index = 0; index < Controls.Count; index++) { - Control ctl = this.Controls[index]; + Control ctl = Controls[index]; if (ctl is MdiClient) { continue; @@ -4266,7 +4266,7 @@ internal void MenuChanged(int change, Menu menu) UpdateMenuHandles(); break; case Windows.Forms.Menu.CHANGE_VISIBLE: - if (menu == Menu || (this.ActiveMdiChildInternal != null && menu == this.ActiveMdiChildInternal.Menu)) + if (menu == Menu || (ActiveMdiChildInternal != null && menu == ActiveMdiChildInternal.Menu)) { UpdateMenuHandles(); } @@ -4500,7 +4500,7 @@ protected override void OnLayout(LayoutEventArgs levent) { // If AutoSized, set the Form to the maximum of its preferredSize or the user // specified size. - Size prefSize = this.PreferredSize; + Size prefSize = PreferredSize; minAutoSize = prefSize; // This used to use "GetSpecifiedBounds" - but it was not updated when we're in the middle of @@ -4510,7 +4510,7 @@ protected override void OnLayout(LayoutEventArgs levent) IArrangedElement form = this as IArrangedElement; if (form != null) { - form.SetBounds(new Rectangle(this.Left, this.Top, adjustedSize.Width, adjustedSize.Height), BoundsSpecified.None); + form.SetBounds(new Rectangle(Left, Top, adjustedSize.Width, adjustedSize.Height), BoundsSpecified.None); } } base.OnLayout(levent); @@ -4526,7 +4526,7 @@ protected virtual void OnLoad(EventArgs e) Application.OpenForms.Add(this); if (Application.UseWaitCursor) { - this.UseWaitCursor = true; + UseWaitCursor = true; } // subhag: This will apply AutoScaling to the form just @@ -4605,7 +4605,7 @@ protected virtual void OnLoad(EventArgs e) //finally fire the newOnShown(unless the form has already been closed) if (IsHandleCreated) { - this.BeginInvoke(new MethodInvoker(CallShownEvent)); + BeginInvoke(new MethodInvoker(CallShownEvent)); } } @@ -4801,7 +4801,7 @@ protected virtual void OnDpiChanged(DpiChangedEventArgs e) SafeNativeMethods.SetWindowPos(new HandleRef(this, HandleInternal), NativeMethods.NullHandleRef, e.SuggestedRectangle.X, e.SuggestedRectangle.Y, e.SuggestedRectangle.Width, e.SuggestedRectangle.Height, NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE); if (AutoScaleMode != AutoScaleMode.Font) { - Font = new Font(this.Font.FontFamily, this.Font.Size * factor, this.Font.Style); + Font = new Font(Font.FontFamily, Font.Size * factor, Font.Style); FormDpiChanged(factor); } else @@ -4901,7 +4901,7 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) // Want to do this after we fire the event. if (RightToLeft == RightToLeft.Yes) { - foreach (Control c in this.Controls) + foreach (Control c in Controls) { c.RecreateHandleCore(); } @@ -4928,7 +4928,7 @@ protected override void OnTextChanged(EventArgs e) // If there is no control box, there should only be a title bar if text != "". int newTextEmpty = Text.Length == 0 ? 1 : 0; if (!ControlBox && formState[FormStateIsTextEmpty] != newTextEmpty) - this.RecreateHandle(); + RecreateHandle(); formState[FormStateIsTextEmpty] = newTextEmpty; } @@ -5048,7 +5048,7 @@ protected override bool ProcessDialogChar(char charCode) #endif // If we're the top-level form or control, we need to do the mnemonic handling // - if (this.IsMdiChild && charCode != ' ') + if (IsMdiChild && charCode != ' ') { if (ProcessMnemonic(charCode)) { @@ -5125,7 +5125,7 @@ internal void RaiseFormClosedOnAppExit() int ownedFormsCount = Properties.GetInteger(PropOwnedFormsCount); if (ownedFormsCount > 0) { - Form[] ownedForms = this.OwnedForms; + Form[] ownedForms = OwnedForms; FormClosedEventArgs fce = new FormClosedEventArgs(CloseReason.FormOwnerClosing); for (int i = ownedFormsCount - 1; i >= 0; i--) { @@ -5170,7 +5170,7 @@ internal bool RaiseFormClosingOnAppExit() int ownedFormsCount = Properties.GetInteger(PropOwnedFormsCount); if (ownedFormsCount > 0) { - Form[] ownedForms = this.OwnedForms; + Form[] ownedForms = OwnedForms; FormClosingEventArgs fce = new FormClosingEventArgs(CloseReason.FormOwnerClosing, false); for (int i = ownedFormsCount - 1; i >= 0; i--) { @@ -5226,7 +5226,7 @@ internal override void RecreateHandleCore() callback = new SafeNativeMethods.EnumThreadWindowsCallback(etwcb.Callback); UnsafeNativeMethods.EnumThreadWindows(SafeNativeMethods.GetCurrentThreadId(), new NativeMethods.EnumThreadWindowsCallback(callback), - new HandleRef(this, this.Handle)); + new HandleRef(this, Handle)); // Reset the owner of the windows in the list etwcb.ResetOwners(); } @@ -5238,7 +5238,7 @@ internal override void RecreateHandleCore() if (etwcb != null) { // Set the owner of the windows in the list back to the new Form's handle - etwcb.SetOwners(new HandleRef(this, this.Handle)); + etwcb.SetOwners(new HandleRef(this, Handle)); } if (oldStartPosition != FormStartPosition.Manual) @@ -5574,7 +5574,7 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound } // Enforce maximum size... - if (WindowState == FormWindowState.Normal && (this.Height != height || this.Width != width)) + if (WindowState == FormWindowState.Normal && (Height != height || Width != width)) { Size max = SystemInformation.MaxWindowTrackSize; if (height > max.Height) @@ -5794,11 +5794,11 @@ public DialogResult ShowDialog(IWin32Window owner) } } - this.CalledOnLoad = false; - this.CalledMakeVisible = false; + CalledOnLoad = false; + CalledMakeVisible = false; // for modal dialogs make sure we reset close reason. - this.CloseReason = CloseReason.None; + CloseReason = CloseReason.None; IntPtr hWndCapture = UnsafeNativeMethods.GetCapture(); if (hWndCapture != IntPtr.Zero) @@ -5886,11 +5886,11 @@ public DialogResult ShowDialog(IWin32Window owner) // If this is a dialog opened from an MDI Container, then invalidate // so that child windows will be properly updated. - if (this.OwnerInternal != null && - this.OwnerInternal.IsMdiContainer) + if (OwnerInternal != null && + OwnerInternal.IsMdiContainer) { - this.OwnerInternal.Invalidate(true); - this.OwnerInternal.Update(); + OwnerInternal.Invalidate(true); + OwnerInternal.Update(); } // Everett/RTM used to wrap this in an assert for AWP. @@ -6239,19 +6239,19 @@ private void UpdateMenuHandles(MainMenu menu, bool forceRedraw) // (New fix: Only destroy Win32 Menu if using a MenuStrip) if (menu == null && mainMenuStrip != null) { // If MainMenuStrip, we need to remove any Win32 Menu to make room for it. - IntPtr hMenu = UnsafeNativeMethods.GetMenu(new HandleRef(this, this.Handle)); + IntPtr hMenu = UnsafeNativeMethods.GetMenu(new HandleRef(this, Handle)); if (hMenu != IntPtr.Zero) { // We had a MainMenu and now we're switching over to MainMenuStrip // Remove the current menu. - UnsafeNativeMethods.SetMenu(new HandleRef(this, this.Handle), NativeMethods.NullHandleRef); + UnsafeNativeMethods.SetMenu(new HandleRef(this, Handle), NativeMethods.NullHandleRef); // because we have messed with the child's system menu by shoving in our own dummy menu, // once we clear the main menu we're in trouble - this eats the close, minimize, maximize gadgets // of the child form. (See WM_MDISETMENU in MSDN) - Form activeMdiChild = this.ActiveMdiChildInternal; + Form activeMdiChild = ActiveMdiChildInternal; if (activeMdiChild != null && activeMdiChild.WindowState == FormWindowState.Maximized) { activeMdiChild.RecreateHandle(); @@ -6363,7 +6363,7 @@ private void UpdateMdiControlStrip(bool maximized) try { - MdiControlStrip mdiControlStrip = this.MdiControlStrip; + MdiControlStrip mdiControlStrip = MdiControlStrip; if (MdiControlStrip != null) { @@ -6398,24 +6398,24 @@ private void UpdateMdiControlStrip(bool maximized) if (ActiveMdiChildInternal.ControlBox) { Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: Detected ControlBox on ActiveMDI child, adding in MDIControlStrip."); - Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose && this.Menu != null, "UpdateMdiControlStrip: Bailing as we detect there's already an HMenu to do this for us."); + Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose && Menu != null, "UpdateMdiControlStrip: Bailing as we detect there's already an HMenu to do this for us."); // determine if we need to add control gadgets into the MenuStrip - if (this.Menu == null) + if (Menu == null) { // double check GetMenu incase someone is using interop - IntPtr hMenu = UnsafeNativeMethods.GetMenu(new HandleRef(this, this.Handle)); + IntPtr hMenu = UnsafeNativeMethods.GetMenu(new HandleRef(this, Handle)); if (hMenu == IntPtr.Zero) { MenuStrip sourceMenuStrip = ToolStripManager.GetMainMenuStrip(this); if (sourceMenuStrip != null) { - this.MdiControlStrip = new MdiControlStrip(ActiveMdiChildInternal); + MdiControlStrip = new MdiControlStrip(ActiveMdiChildInternal); Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: built up an MDI control strip for " + ActiveMdiChildInternal.Text + " with " + MdiControlStrip.Items.Count.ToString(CultureInfo.InvariantCulture) + " items."); Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: merging MDI control strip into source menustrip - items before: " + sourceMenuStrip.Items.Count.ToString(CultureInfo.InvariantCulture)); - ToolStripManager.Merge(this.MdiControlStrip, sourceMenuStrip); + ToolStripManager.Merge(MdiControlStrip, sourceMenuStrip); Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: merging MDI control strip into source menustrip - items after: " + sourceMenuStrip.Items.Count.ToString(CultureInfo.InvariantCulture)); - this.MdiControlStrip.MergedMenu = sourceMenuStrip; + MdiControlStrip.MergedMenu = sourceMenuStrip; } } } @@ -6673,9 +6673,9 @@ public override bool ValidateChildren(ValidationConstraints validationConstraint /// private void WmActivate(ref Message m) { - Application.FormActivated(this.Modal, true); // inform MsoComponentManager we're active + Application.FormActivated(Modal, true); // inform MsoComponentManager we're active Active = NativeMethods.Util.LOWORD(m.WParam) != NativeMethods.WA_INACTIVE; - Application.FormActivated(this.Modal, Active); // inform MsoComponentManager we're active + Application.FormActivated(Modal, Active); // inform MsoComponentManager we're active } /// @@ -6783,7 +6783,7 @@ private void WmClose(ref Message m) //Pass the validation result into the EventArgs... // Call OnClosing/OnFormClosing on all the forms that current form owns. - Form[] ownedForms = this.OwnedForms; + Form[] ownedForms = OwnedForms; int ownedFormsCount = Properties.GetInteger(PropOwnedFormsCount); for (int i = ownedFormsCount - 1; i >= 0; i--) { @@ -6850,7 +6850,7 @@ private void WmClose(ref Message m) } // Call OnClosed/OnFormClosed on all the forms that current form owns. - Form[] ownedForms = this.OwnedForms; + Form[] ownedForms = OwnedForms; int ownedFormsCount = Properties.GetInteger(PropOwnedFormsCount); for (int i = ownedFormsCount - 1; i >= 0; i--) { @@ -7126,7 +7126,7 @@ private void WmNCHitTest(ref Message m) // Convert to client coordinates // NativeMethods.POINT pt = new NativeMethods.POINT(x, y); - UnsafeNativeMethods.ScreenToClient(new HandleRef(this, this.Handle), pt); + UnsafeNativeMethods.ScreenToClient(new HandleRef(this, Handle), pt); Size clientSize = ClientSize; @@ -7471,11 +7471,11 @@ internal bool Callback(IntPtr hWnd, IntPtr lParam) { // Enumerated window is owned by this Form. // Store it in a list for further treatment. - if (this.ownedWindows == null) + if (ownedWindows == null) { - this.ownedWindows = new List(); + ownedWindows = new List(); } - this.ownedWindows.Add(hRef); + ownedWindows.Add(hRef); } return true; } @@ -7483,9 +7483,9 @@ internal bool Callback(IntPtr hWnd, IntPtr lParam) // Resets the owner of all the windows owned by this Form before handle recreation. internal void ResetOwners() { - if (this.ownedWindows != null) + if (ownedWindows != null) { - foreach (HandleRef hRef in this.ownedWindows) + foreach (HandleRef hRef in ownedWindows) { UnsafeNativeMethods.SetWindowLong(hRef, NativeMethods.GWL_HWNDPARENT, NativeMethods.NullHandleRef); } @@ -7495,9 +7495,9 @@ internal void ResetOwners() // Sets the owner of the windows back to this Form after its handle recreation. internal void SetOwners(HandleRef hRefOwner) { - if (this.ownedWindows != null) + if (ownedWindows != null) { - foreach (HandleRef hRef in this.ownedWindows) + foreach (HandleRef hRef in ownedWindows) { UnsafeNativeMethods.SetWindowLong(hRef, NativeMethods.GWL_HWNDPARENT, hRefOwner); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/GDI/WindowsGraphicsWrapper.cs b/src/System.Windows.Forms/src/System/Windows/Forms/GDI/WindowsGraphicsWrapper.cs index b86b3559251..a4f6a71239f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/GDI/WindowsGraphicsWrapper.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/GDI/WindowsGraphicsWrapper.cs @@ -57,15 +57,15 @@ public WindowsGraphicsWrapper(IDeviceContext idc, TextFormatFlags flags) // to be reapplied to the DC wrapped by the WindowsGraphics. if (properties != ApplyGraphicsProperties.None) { - this.wg = WindowsGraphics.FromGraphics(idc as Graphics, properties); + wg = WindowsGraphics.FromGraphics(idc as Graphics, properties); } } else { // If passed-in IDeviceContext object is a WindowsGraphics we can use it directly. - this.wg = idc as WindowsGraphics; + wg = idc as WindowsGraphics; - if (this.wg != null) + if (wg != null) { // In this case we cache the idc to compare it against the wg in the Dispose method to avoid // disposing of the wg. @@ -73,14 +73,14 @@ public WindowsGraphicsWrapper(IDeviceContext idc, TextFormatFlags flags) } } - if (this.wg == null) + if (wg == null) { // The IDeviceContext object is not a WindowsGraphics, or it is a custom IDeviceContext, or // it is a Graphics object but we did not need to re-apply Graphics propertiesto the hdc. // So create the WindowsGraphics from the hdc directly. // Cache the IDC so the hdc can be released on dispose. this.idc = idc; - this.wg = WindowsGraphics.FromHdc(idc.GetHdc()); + wg = WindowsGraphics.FromHdc(idc.GetHdc()); } // Set text padding on the WindowsGraphics (if any). @@ -99,8 +99,8 @@ public WindowsGraphics WindowsGraphics { get { - Debug.Assert(this.wg != null, "WindowsGraphics is null."); - return this.wg; + Debug.Assert(wg != null, "WindowsGraphics is null."); + return wg; } } @@ -119,23 +119,23 @@ public void Dispose(bool disposing) { Debug.Assert(disposing, "We should always dispose of this guy and not let GC do it for us!"); - if (this.wg != null) + if (wg != null) { // We need to dispose of the WindowsGraphics if it is created by this class only, if the IDeviceContext is // a WindowsGraphics object we must not dispose of it since it is owned by the caller. - if (this.wg != this.idc) + if (wg != idc) { // resets the hdc and disposes of the internal Graphics (if inititialized from one) which releases the hdc. - this.wg.Dispose(); + wg.Dispose(); - if (this.idc != null) // not initialized from a Graphics idc. + if (idc != null) // not initialized from a Graphics idc. { - this.idc.ReleaseHdc(); + idc.ReleaseHdc(); } } - this.idc = null; - this.wg = null; + idc = null; + wg = null; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/GroupBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/GroupBox.cs index d5ce96eb607..cd2608c7b18 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/GroupBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/GroupBox.cs @@ -324,7 +324,7 @@ public override string Text // the GroupBox controls immediately draws when teh WM_SETTEXT comes through, but // does so in the wrong font, so we suspend that behavior, and then // invalidate. - bool suspendRedraw = this.Visible; + bool suspendRedraw = Visible; try { if (suspendRedraw && IsHandleCreated) @@ -501,9 +501,9 @@ protected override void OnPaint(PaintEventArgs e) // We only pass in the text color if it is explicitly set, else we let the renderer use the // color specified by the theme. This is a temporary workaround till we find a good // solution for the "default theme color" issue. - if (ShouldSerializeForeColor() || this.Enabled == false) + if (ShouldSerializeForeColor() || Enabled == false) { - Color textcolor = this.Enabled ? ForeColor : TextRenderer.DisabledTextColor(this.BackColor); + Color textcolor = Enabled ? ForeColor : TextRenderer.DisabledTextColor(BackColor); GroupBoxRenderer.DrawGroupBox(e.Graphics, new Rectangle(0, 0, Width, Height), Text, Font, textcolor, textFlags, gbState); } else @@ -582,7 +582,7 @@ private void DrawGroupBox(PaintEventArgs e) } - using (WindowsFont wfont = WindowsGraphicsCacheManager.GetWindowsFont(this.Font)) + using (WindowsFont wfont = WindowsGraphicsCacheManager.GetWindowsFont(Font)) { textSize = wg.MeasureText(Text, wfont, new Size(textRectangle.Width, int.MaxValue), flags); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HelpProvider.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HelpProvider.cs index 30fd4772d6c..52fdb11fbf4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HelpProvider.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HelpProvider.cs @@ -234,14 +234,14 @@ private void UpdateEventBinding(Control ctl) { if (GetShowHelp(ctl) && !_boundControls.ContainsKey(ctl)) { - ctl.HelpRequested += new HelpEventHandler(this.OnControlHelp); - ctl.QueryAccessibilityHelp += new QueryAccessibilityHelpEventHandler(this.OnQueryAccessibilityHelp); + ctl.HelpRequested += new HelpEventHandler(OnControlHelp); + ctl.QueryAccessibilityHelp += new QueryAccessibilityHelpEventHandler(OnQueryAccessibilityHelp); _boundControls[ctl] = ctl; } else if (!GetShowHelp(ctl) && _boundControls.ContainsKey(ctl)) { - ctl.HelpRequested -= new HelpEventHandler(this.OnControlHelp); - ctl.QueryAccessibilityHelp -= new QueryAccessibilityHelpEventHandler(this.OnQueryAccessibilityHelp); + ctl.HelpRequested -= new HelpEventHandler(OnControlHelp); + ctl.QueryAccessibilityHelp -= new QueryAccessibilityHelpEventHandler(OnQueryAccessibilityHelp); _boundControls.Remove(ctl); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs index 0abeace9381..6dd72cb641d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs @@ -29,8 +29,8 @@ public sealed class HtmlDocument internal HtmlDocument(HtmlShimManager shimManager, UnsafeNativeMethods.IHTMLDocument doc) { - this.htmlDocument2 = (UnsafeNativeMethods.IHTMLDocument2)doc; - Debug.Assert(this.NativeHtmlDocument2 != null, "The document should implement IHtmlDocument2"); + htmlDocument2 = (UnsafeNativeMethods.IHTMLDocument2)doc; + Debug.Assert(NativeHtmlDocument2 != null, "The document should implement IHtmlDocument2"); this.shimManager = shimManager; @@ -40,7 +40,7 @@ internal UnsafeNativeMethods.IHTMLDocument2 NativeHtmlDocument2 { get { - return this.htmlDocument2; + return htmlDocument2; } } @@ -66,7 +66,7 @@ private HtmlShimManager ShimManager { get { - return this.shimManager; + return shimManager; } } @@ -74,7 +74,7 @@ public HtmlElement ActiveElement { get { - UnsafeNativeMethods.IHTMLElement iHtmlElement = this.NativeHtmlDocument2.GetActiveElement(); + UnsafeNativeMethods.IHTMLElement iHtmlElement = NativeHtmlDocument2.GetActiveElement(); return iHtmlElement != null ? new HtmlElement(ShimManager, iHtmlElement) : null; } } @@ -83,7 +83,7 @@ public HtmlElement Body { get { - UnsafeNativeMethods.IHTMLElement iHtmlElement = this.NativeHtmlDocument2.GetBody(); + UnsafeNativeMethods.IHTMLElement iHtmlElement = NativeHtmlDocument2.GetBody(); return iHtmlElement != null ? new HtmlElement(ShimManager, iHtmlElement) : null; } } @@ -92,13 +92,13 @@ public string Domain { get { - return this.NativeHtmlDocument2.GetDomain(); + return NativeHtmlDocument2.GetDomain(); } set { try { - this.NativeHtmlDocument2.SetDomain(value); + NativeHtmlDocument2.SetDomain(value); } catch (ArgumentException) { @@ -112,11 +112,11 @@ public string Title { get { - return this.NativeHtmlDocument2.GetTitle(); + return NativeHtmlDocument2.GetTitle(); } set { - this.NativeHtmlDocument2.SetTitle(value); + NativeHtmlDocument2.SetTitle(value); } } @@ -124,7 +124,7 @@ public Uri Url { get { - UnsafeNativeMethods.IHTMLLocation iHtmlLocation = this.NativeHtmlDocument2.GetLocation(); + UnsafeNativeMethods.IHTMLLocation iHtmlLocation = NativeHtmlDocument2.GetLocation(); string stringLocation = (iHtmlLocation == null) ? "" : iHtmlLocation.GetHref(); return string.IsNullOrEmpty(stringLocation) ? null : new Uri(stringLocation); } @@ -134,7 +134,7 @@ public HtmlWindow Window { get { - UnsafeNativeMethods.IHTMLWindow2 iHTMLWindow2 = this.NativeHtmlDocument2.GetParentWindow(); + UnsafeNativeMethods.IHTMLWindow2 iHTMLWindow2 = NativeHtmlDocument2.GetParentWindow(); return iHTMLWindow2 != null ? new HtmlWindow(ShimManager, iHTMLWindow2) : null; } } @@ -146,7 +146,7 @@ public Color BackColor Color c = Color.Empty; try { - c = this.ColorFromObject(this.NativeHtmlDocument2.GetBgColor()); + c = ColorFromObject(NativeHtmlDocument2.GetBgColor()); } catch (Exception ex) { @@ -160,7 +160,7 @@ public Color BackColor set { int color = value.R << 16 | value.G << 8 | value.B; - this.NativeHtmlDocument2.SetBgColor(color); + NativeHtmlDocument2.SetBgColor(color); } } @@ -171,7 +171,7 @@ public Color ForeColor Color c = Color.Empty; try { - c = this.ColorFromObject(this.NativeHtmlDocument2.GetFgColor()); + c = ColorFromObject(NativeHtmlDocument2.GetFgColor()); } catch (Exception ex) { @@ -185,7 +185,7 @@ public Color ForeColor set { int color = value.R << 16 | value.G << 8 | value.B; - this.NativeHtmlDocument2.SetFgColor(color); + NativeHtmlDocument2.SetFgColor(color); } } @@ -196,7 +196,7 @@ public Color LinkColor Color c = Color.Empty; try { - c = this.ColorFromObject(this.NativeHtmlDocument2.GetLinkColor()); + c = ColorFromObject(NativeHtmlDocument2.GetLinkColor()); } catch (Exception ex) { @@ -210,7 +210,7 @@ public Color LinkColor set { int color = value.R << 16 | value.G << 8 | value.B; - this.NativeHtmlDocument2.SetLinkColor(color); + NativeHtmlDocument2.SetLinkColor(color); } } @@ -221,7 +221,7 @@ public Color ActiveLinkColor Color c = Color.Empty; try { - c = this.ColorFromObject(this.NativeHtmlDocument2.GetAlinkColor()); + c = ColorFromObject(NativeHtmlDocument2.GetAlinkColor()); } catch (Exception ex) { @@ -235,7 +235,7 @@ public Color ActiveLinkColor set { int color = value.R << 16 | value.G << 8 | value.B; - this.NativeHtmlDocument2.SetAlinkColor(color); + NativeHtmlDocument2.SetAlinkColor(color); } } @@ -246,7 +246,7 @@ public Color VisitedLinkColor Color c = Color.Empty; try { - c = this.ColorFromObject(this.NativeHtmlDocument2.GetVlinkColor()); + c = ColorFromObject(NativeHtmlDocument2.GetVlinkColor()); } catch (Exception ex) { @@ -260,7 +260,7 @@ public Color VisitedLinkColor set { int color = value.R << 16 | value.G << 8 | value.B; - this.NativeHtmlDocument2.SetVlinkColor(color); + NativeHtmlDocument2.SetVlinkColor(color); } } @@ -268,7 +268,7 @@ public bool Focused { get { - return ((UnsafeNativeMethods.IHTMLDocument4)this.NativeHtmlDocument2).HasFocus(); + return ((UnsafeNativeMethods.IHTMLDocument4)NativeHtmlDocument2).HasFocus(); } } @@ -276,7 +276,7 @@ public object DomDocument { get { - return this.NativeHtmlDocument2; + return NativeHtmlDocument2; } } @@ -284,11 +284,11 @@ public string Cookie { get { - return this.NativeHtmlDocument2.GetCookie(); + return NativeHtmlDocument2.GetCookie(); } set { - this.NativeHtmlDocument2.SetCookie(value); + NativeHtmlDocument2.SetCookie(value); } } @@ -296,11 +296,11 @@ public bool RightToLeft { get { - return ((UnsafeNativeMethods.IHTMLDocument3)this.NativeHtmlDocument2).GetDir() == "rtl"; + return ((UnsafeNativeMethods.IHTMLDocument3)NativeHtmlDocument2).GetDir() == "rtl"; } set { - ((UnsafeNativeMethods.IHTMLDocument3)this.NativeHtmlDocument2).SetDir(value ? "rtl" : "ltr"); + ((UnsafeNativeMethods.IHTMLDocument3)NativeHtmlDocument2).SetDir(value ? "rtl" : "ltr"); } } @@ -308,11 +308,11 @@ public string Encoding { get { - return this.NativeHtmlDocument2.GetCharset(); + return NativeHtmlDocument2.GetCharset(); } set { - this.NativeHtmlDocument2.SetCharset(value); + NativeHtmlDocument2.SetCharset(value); } } @@ -320,7 +320,7 @@ public string DefaultEncoding { get { - return this.NativeHtmlDocument2.GetDefaultCharset(); + return NativeHtmlDocument2.GetDefaultCharset(); } } @@ -328,7 +328,7 @@ public HtmlElementCollection All { get { - UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection = this.NativeHtmlDocument2.GetAll(); + UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection = NativeHtmlDocument2.GetAll(); return iHTMLElementCollection != null ? new HtmlElementCollection(ShimManager, iHTMLElementCollection) : new HtmlElementCollection(ShimManager); } } @@ -337,7 +337,7 @@ public HtmlElementCollection Links { get { - UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection = this.NativeHtmlDocument2.GetLinks(); + UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection = NativeHtmlDocument2.GetLinks(); return iHTMLElementCollection != null ? new HtmlElementCollection(ShimManager, iHTMLElementCollection) : new HtmlElementCollection(ShimManager); } } @@ -346,7 +346,7 @@ public HtmlElementCollection Images { get { - UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection = this.NativeHtmlDocument2.GetImages(); + UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection = NativeHtmlDocument2.GetImages(); return iHTMLElementCollection != null ? new HtmlElementCollection(ShimManager, iHTMLElementCollection) : new HtmlElementCollection(ShimManager); } } @@ -355,7 +355,7 @@ public HtmlElementCollection Forms { get { - UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection = this.NativeHtmlDocument2.GetForms(); + UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection = NativeHtmlDocument2.GetForms(); return iHTMLElementCollection != null ? new HtmlElementCollection(ShimManager, iHTMLElementCollection) : new HtmlElementCollection(ShimManager); } } @@ -363,7 +363,7 @@ public HtmlElementCollection Forms public void Write(string text) { object[] strs = new object[] { (object)text }; - this.NativeHtmlDocument2.Write(strs); + NativeHtmlDocument2.Write(strs); } /// @@ -371,32 +371,32 @@ public void Write(string text) /// public void ExecCommand(string command, bool showUI, object value) { - this.NativeHtmlDocument2.ExecCommand(command, showUI, value); + NativeHtmlDocument2.ExecCommand(command, showUI, value); } [EditorBrowsable(EditorBrowsableState.Advanced)] public void Focus() { - ((UnsafeNativeMethods.IHTMLDocument4)this.NativeHtmlDocument2).Focus(); + ((UnsafeNativeMethods.IHTMLDocument4)NativeHtmlDocument2).Focus(); // Seems to have a problem in really setting focus the first time - ((UnsafeNativeMethods.IHTMLDocument4)this.NativeHtmlDocument2).Focus(); + ((UnsafeNativeMethods.IHTMLDocument4)NativeHtmlDocument2).Focus(); } public HtmlElement GetElementById(string id) { - UnsafeNativeMethods.IHTMLElement iHTMLElement = ((UnsafeNativeMethods.IHTMLDocument3)this.NativeHtmlDocument2).GetElementById(id); + UnsafeNativeMethods.IHTMLElement iHTMLElement = ((UnsafeNativeMethods.IHTMLDocument3)NativeHtmlDocument2).GetElementById(id); return iHTMLElement != null ? new HtmlElement(ShimManager, iHTMLElement) : null; } public HtmlElement GetElementFromPoint(Point point) { - UnsafeNativeMethods.IHTMLElement iHTMLElement = this.NativeHtmlDocument2.ElementFromPoint(point.X, point.Y); + UnsafeNativeMethods.IHTMLElement iHTMLElement = NativeHtmlDocument2.ElementFromPoint(point.X, point.Y); return iHTMLElement != null ? new HtmlElement(ShimManager, iHTMLElement) : null; } public HtmlElementCollection GetElementsByTagName(string tagName) { - UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection = ((UnsafeNativeMethods.IHTMLDocument3)this.NativeHtmlDocument2).GetElementsByTagName(tagName); + UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection = ((UnsafeNativeMethods.IHTMLDocument3)NativeHtmlDocument2).GetElementsByTagName(tagName); return iHTMLElementCollection != null ? new HtmlElementCollection(ShimManager, iHTMLElementCollection) : new HtmlElementCollection(ShimManager); } @@ -404,14 +404,14 @@ public HtmlDocument OpenNew(bool replaceInHistory) { object name = (object)(replaceInHistory ? "replace" : ""); object nullObject = null; - object ohtmlDocument = this.NativeHtmlDocument2.Open("text/html", name, nullObject, nullObject); + object ohtmlDocument = NativeHtmlDocument2.Open("text/html", name, nullObject, nullObject); UnsafeNativeMethods.IHTMLDocument iHTMLDocument = ohtmlDocument as UnsafeNativeMethods.IHTMLDocument; return iHTMLDocument != null ? new HtmlDocument(ShimManager, iHTMLDocument) : null; } public HtmlElement CreateElement(string elementTag) { - UnsafeNativeMethods.IHTMLElement iHTMLElement = this.NativeHtmlDocument2.CreateElement(elementTag); + UnsafeNativeMethods.IHTMLElement iHTMLElement = NativeHtmlDocument2.CreateElement(elementTag); return iHTMLElement != null ? new HtmlElement(ShimManager, iHTMLElement) : null; } @@ -422,7 +422,7 @@ public object InvokeScript(string scriptName, object[] args) dp.rgvarg = IntPtr.Zero; try { - UnsafeNativeMethods.IDispatch scriptObject = this.NativeHtmlDocument2.GetScript() as UnsafeNativeMethods.IDispatch; + UnsafeNativeMethods.IDispatch scriptObject = NativeHtmlDocument2.GetScript() as UnsafeNativeMethods.IDispatch; if (scriptObject != null) { Guid g = Guid.Empty; @@ -691,7 +691,7 @@ public override void AttachEventHandler(string eventName, EventHandler eventHand // our EventHandler properly. HtmlToClrEventProxy proxy = AddEventProxy(eventName, eventHandler); - bool success = ((UnsafeNativeMethods.IHTMLDocument3)this.NativeHtmlDocument2).AttachEvent(eventName, proxy); + bool success = ((UnsafeNativeMethods.IHTMLDocument3)NativeHtmlDocument2).AttachEvent(eventName, proxy); Debug.Assert(success, "failed to add event"); } @@ -701,7 +701,7 @@ public override void DetachEventHandler(string eventName, EventHandler eventHand HtmlToClrEventProxy proxy = RemoveEventProxy(eventHandler); if (proxy != null) { - ((UnsafeNativeMethods.IHTMLDocument3)this.NativeHtmlDocument2).DetachEvent(eventName, proxy); + ((UnsafeNativeMethods.IHTMLDocument3)NativeHtmlDocument2).DetachEvent(eventName, proxy); } } @@ -713,7 +713,7 @@ public override void ConnectToEvents() { if (cookie == null || !cookie.Connected) { - this.cookie = new AxHost.ConnectionPointCookie(this.NativeHtmlDocument2, + cookie = new AxHost.ConnectionPointCookie(NativeHtmlDocument2, new HTMLDocumentEvents2(htmlDocument), typeof(UnsafeNativeMethods.DHTMLDocumentEvents2), /*throwException*/ false); @@ -729,10 +729,10 @@ public override void ConnectToEvents() // public override void DisconnectFromEvents() { - if (this.cookie != null) + if (cookie != null) { - this.cookie.Disconnect(); - this.cookie = null; + cookie.Disconnect(); + cookie = null; } } @@ -767,12 +767,12 @@ private class HTMLDocumentEvents2 : StandardOleMarshalObject, /*Enforce calling public HTMLDocumentEvents2(HtmlDocument htmlDocument) { - this.parent = htmlDocument; + parent = htmlDocument; } private void FireEvent(object key, EventArgs e) { - if (this.parent != null) + if (parent != null) { parent.DocumentShim.FireEvent(key, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs index 77870230cd4..abc130bd610 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs @@ -36,8 +36,8 @@ public sealed class HtmlElement internal HtmlElement(HtmlShimManager shimManager, UnsafeNativeMethods.IHTMLElement element) { - this.htmlElement = element; - Debug.Assert(this.NativeHtmlElement != null, "The element object should implement IHTMLElement"); + htmlElement = element; + Debug.Assert(NativeHtmlElement != null, "The element object should implement IHTMLElement"); this.shimManager = shimManager; @@ -47,7 +47,7 @@ public HtmlElementCollection All { get { - UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection = this.NativeHtmlElement.GetAll() as UnsafeNativeMethods.IHTMLElementCollection; + UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection = NativeHtmlElement.GetAll() as UnsafeNativeMethods.IHTMLElementCollection; return iHTMLElementCollection != null ? new HtmlElementCollection(shimManager, iHTMLElementCollection) : new HtmlElementCollection(shimManager); } } @@ -56,7 +56,7 @@ public HtmlElementCollection Children { get { - UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection = this.NativeHtmlElement.GetChildren() as UnsafeNativeMethods.IHTMLElementCollection; + UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection = NativeHtmlElement.GetChildren() as UnsafeNativeMethods.IHTMLElementCollection; return iHTMLElementCollection != null ? new HtmlElementCollection(shimManager, iHTMLElementCollection) : new HtmlElementCollection(shimManager); } } @@ -65,7 +65,7 @@ public bool CanHaveChildren { get { - return ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).CanHaveChildren(); + return ((UnsafeNativeMethods.IHTMLElement2)NativeHtmlElement).CanHaveChildren(); } } @@ -73,7 +73,7 @@ public Rectangle ClientRectangle { get { - UnsafeNativeMethods.IHTMLElement2 htmlElement2 = (UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement; + UnsafeNativeMethods.IHTMLElement2 htmlElement2 = (UnsafeNativeMethods.IHTMLElement2)NativeHtmlElement; return new Rectangle(htmlElement2.ClientLeft(), htmlElement2.ClientTop(), htmlElement2.ClientWidth(), htmlElement2.ClientHeight()); } @@ -84,7 +84,7 @@ public HtmlDocument Document { get { - UnsafeNativeMethods.IHTMLDocument iHTMLDocument = this.NativeHtmlElement.GetDocument() as UnsafeNativeMethods.IHTMLDocument; + UnsafeNativeMethods.IHTMLDocument iHTMLDocument = NativeHtmlElement.GetDocument() as UnsafeNativeMethods.IHTMLDocument; return iHTMLDocument != null ? new HtmlDocument(shimManager, iHTMLDocument) : null; } } @@ -93,11 +93,11 @@ public bool Enabled { get { - return !(((UnsafeNativeMethods.IHTMLElement3)this.NativeHtmlElement).GetDisabled()); + return !(((UnsafeNativeMethods.IHTMLElement3)NativeHtmlElement).GetDisabled()); } set { - ((UnsafeNativeMethods.IHTMLElement3)this.NativeHtmlElement).SetDisabled(!value); + ((UnsafeNativeMethods.IHTMLElement3)NativeHtmlElement).SetDisabled(!value); } } @@ -124,7 +124,7 @@ public HtmlElement FirstChild get { UnsafeNativeMethods.IHTMLElement iHtmlElement = null; - UnsafeNativeMethods.IHTMLDOMNode iHtmlDomNode = this.NativeHtmlElement as UnsafeNativeMethods.IHTMLDOMNode; + UnsafeNativeMethods.IHTMLDOMNode iHtmlDomNode = NativeHtmlElement as UnsafeNativeMethods.IHTMLDOMNode; if (iHtmlDomNode != null) { @@ -139,11 +139,11 @@ public string Id [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] get { - return this.NativeHtmlElement.GetId(); + return NativeHtmlElement.GetId(); } set { - this.NativeHtmlElement.SetId(value); + NativeHtmlElement.SetId(value); } } @@ -152,13 +152,13 @@ public string InnerHtml { get { - return this.NativeHtmlElement.GetInnerHTML(); + return NativeHtmlElement.GetInnerHTML(); } set { try { - this.NativeHtmlElement.SetInnerHTML(value); + NativeHtmlElement.SetInnerHTML(value); } catch (COMException ex) { @@ -175,13 +175,13 @@ public string InnerText { get { - return this.NativeHtmlElement.GetInnerText(); + return NativeHtmlElement.GetInnerText(); } set { try { - this.NativeHtmlElement.SetInnerText(value); + NativeHtmlElement.SetInnerText(value); } catch (COMException ex) { @@ -198,11 +198,11 @@ public string Name { get { - return this.GetAttribute("Name"); + return GetAttribute("Name"); } set { - this.SetAttribute("Name", value); + SetAttribute("Name", value); } } @@ -211,7 +211,7 @@ private UnsafeNativeMethods.IHTMLElement NativeHtmlElement { get { - return this.htmlElement; + return htmlElement; } } @@ -220,7 +220,7 @@ public HtmlElement NextSibling get { UnsafeNativeMethods.IHTMLElement iHtmlElement = null; - UnsafeNativeMethods.IHTMLDOMNode iHtmlDomNode = this.NativeHtmlElement as UnsafeNativeMethods.IHTMLDOMNode; + UnsafeNativeMethods.IHTMLDOMNode iHtmlDomNode = NativeHtmlElement as UnsafeNativeMethods.IHTMLDOMNode; if (iHtmlDomNode != null) { @@ -235,8 +235,8 @@ public Rectangle OffsetRectangle { get { - return new Rectangle(this.NativeHtmlElement.GetOffsetLeft(), this.NativeHtmlElement.GetOffsetTop(), - this.NativeHtmlElement.GetOffsetWidth(), this.NativeHtmlElement.GetOffsetHeight()); + return new Rectangle(NativeHtmlElement.GetOffsetLeft(), NativeHtmlElement.GetOffsetTop(), + NativeHtmlElement.GetOffsetWidth(), NativeHtmlElement.GetOffsetHeight()); } } @@ -244,7 +244,7 @@ public HtmlElement OffsetParent { get { - UnsafeNativeMethods.IHTMLElement iHtmlElement = this.NativeHtmlElement.GetOffsetParent(); + UnsafeNativeMethods.IHTMLElement iHtmlElement = NativeHtmlElement.GetOffsetParent(); return iHtmlElement != null ? new HtmlElement(shimManager, iHtmlElement) : null; } } @@ -253,13 +253,13 @@ public string OuterHtml { get { - return this.NativeHtmlElement.GetOuterHTML(); + return NativeHtmlElement.GetOuterHTML(); } set { try { - this.NativeHtmlElement.SetOuterHTML(value); + NativeHtmlElement.SetOuterHTML(value); } catch (COMException ex) { @@ -276,13 +276,13 @@ public string OuterText { get { - return this.NativeHtmlElement.GetOuterText(); + return NativeHtmlElement.GetOuterText(); } set { try { - this.NativeHtmlElement.SetOuterText(value); + NativeHtmlElement.SetOuterText(value); } catch (COMException ex) { @@ -299,7 +299,7 @@ public HtmlElement Parent { get { - UnsafeNativeMethods.IHTMLElement iHtmlElement = this.NativeHtmlElement.GetParentElement(); + UnsafeNativeMethods.IHTMLElement iHtmlElement = NativeHtmlElement.GetParentElement(); return iHtmlElement != null ? new HtmlElement(shimManager, iHtmlElement) : null; } } @@ -310,7 +310,7 @@ public Rectangle ScrollRectangle { get { - UnsafeNativeMethods.IHTMLElement2 htmlElement2 = (UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement; + UnsafeNativeMethods.IHTMLElement2 htmlElement2 = (UnsafeNativeMethods.IHTMLElement2)NativeHtmlElement; return new Rectangle(htmlElement2.GetScrollLeft(), htmlElement2.GetScrollTop(), htmlElement2.GetScrollWidth(), htmlElement2.GetScrollHeight()); } @@ -320,11 +320,11 @@ public int ScrollLeft { get { - return ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).GetScrollLeft(); + return ((UnsafeNativeMethods.IHTMLElement2)NativeHtmlElement).GetScrollLeft(); } set { - ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).SetScrollLeft(value); + ((UnsafeNativeMethods.IHTMLElement2)NativeHtmlElement).SetScrollLeft(value); } } @@ -332,11 +332,11 @@ public int ScrollTop { get { - return ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).GetScrollTop(); + return ((UnsafeNativeMethods.IHTMLElement2)NativeHtmlElement).GetScrollTop(); } set { - ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).SetScrollTop(value); + ((UnsafeNativeMethods.IHTMLElement2)NativeHtmlElement).SetScrollTop(value); } } @@ -352,11 +352,11 @@ public string Style { get { - return this.NativeHtmlElement.GetStyle().GetCssText(); + return NativeHtmlElement.GetStyle().GetCssText(); } set { - this.NativeHtmlElement.GetStyle().SetCssText(value); + NativeHtmlElement.GetStyle().SetCssText(value); } } @@ -364,7 +364,7 @@ public string TagName { get { - return this.NativeHtmlElement.GetTagName(); + return NativeHtmlElement.GetTagName(); } } @@ -372,11 +372,11 @@ public short TabIndex { get { - return ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).GetTabIndex(); + return ((UnsafeNativeMethods.IHTMLElement2)NativeHtmlElement).GetTabIndex(); } set { - ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).SetTabIndex(value); + ((UnsafeNativeMethods.IHTMLElement2)NativeHtmlElement).SetTabIndex(value); } } @@ -385,14 +385,14 @@ public object DomElement { get { - return this.NativeHtmlElement; + return NativeHtmlElement; } } public HtmlElement AppendChild(HtmlElement newElement) { - return this.InsertAdjacentElement(HtmlElementInsertionOrientation.BeforeEnd, newElement); + return InsertAdjacentElement(HtmlElementInsertionOrientation.BeforeEnd, newElement); } public void AttachEventHandler(string eventName, EventHandler eventHandler) @@ -410,7 +410,7 @@ public void Focus() { try { - ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).Focus(); + ((UnsafeNativeMethods.IHTMLElement2)NativeHtmlElement).Focus(); } catch (COMException ex) { @@ -425,18 +425,18 @@ public void Focus() [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] public string GetAttribute(string attributeName) { - object oAttributeValue = this.NativeHtmlElement.GetAttribute(attributeName, 0); + object oAttributeValue = NativeHtmlElement.GetAttribute(attributeName, 0); return oAttributeValue == null ? "" : oAttributeValue.ToString(); } public HtmlElementCollection GetElementsByTagName(string tagName) { - UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection = ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).GetElementsByTagName(tagName); + UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection = ((UnsafeNativeMethods.IHTMLElement2)NativeHtmlElement).GetElementsByTagName(tagName); return iHTMLElementCollection != null ? new HtmlElementCollection(shimManager, iHTMLElementCollection) : new HtmlElementCollection(shimManager); } public HtmlElement InsertAdjacentElement(HtmlElementInsertionOrientation orient, HtmlElement newElement) { - UnsafeNativeMethods.IHTMLElement iHtmlElement = ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).InsertAdjacentElement(orient.ToString(), + UnsafeNativeMethods.IHTMLElement iHtmlElement = ((UnsafeNativeMethods.IHTMLElement2)NativeHtmlElement).InsertAdjacentElement(orient.ToString(), (UnsafeNativeMethods.IHTMLElement)newElement.DomElement); return iHtmlElement != null ? new HtmlElement(shimManager, iHtmlElement) : null; } @@ -453,7 +453,7 @@ public object InvokeMember(string methodName, params object[] parameter) dp.rgvarg = IntPtr.Zero; try { - UnsafeNativeMethods.IDispatch scriptObject = this.NativeHtmlElement as UnsafeNativeMethods.IDispatch; + UnsafeNativeMethods.IDispatch scriptObject = NativeHtmlElement as UnsafeNativeMethods.IDispatch; if (scriptObject != null) { Guid g = Guid.Empty; @@ -506,27 +506,27 @@ public object InvokeMember(string methodName, params object[] parameter) public void RemoveFocus() { - ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).Blur(); + ((UnsafeNativeMethods.IHTMLElement2)NativeHtmlElement).Blur(); } // PM review done [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] public void RaiseEvent(string eventName) { - ((UnsafeNativeMethods.IHTMLElement3)this.NativeHtmlElement).FireEvent(eventName, IntPtr.Zero); + ((UnsafeNativeMethods.IHTMLElement3)NativeHtmlElement).FireEvent(eventName, IntPtr.Zero); } public void ScrollIntoView(bool alignWithTop) { - this.NativeHtmlElement.ScrollIntoView((object)alignWithTop); + NativeHtmlElement.ScrollIntoView((object)alignWithTop); } public void SetAttribute(string attributeName, string value) { try { - this.NativeHtmlElement.SetAttribute(attributeName, (object)value, 0); + NativeHtmlElement.SetAttribute(attributeName, (object)value, 0); } catch (COMException comException) { @@ -697,11 +697,11 @@ private class HTMLElementEvents2 : StandardOleMarshalObject, /*Enforce calling b public HTMLElementEvents2(HtmlElement htmlElement) { - this.parent = htmlElement; + parent = htmlElement; } private void FireEvent(object key, EventArgs e) { - if (this.parent != null) + if (parent != null) { parent.ElementShim.FireEvent(key, e); } @@ -1072,12 +1072,12 @@ internal class HtmlElementShim : HtmlShim public HtmlElementShim(HtmlElement element) { - this.htmlElement = element; + htmlElement = element; // snap our associated window so we know when to disconnect. - if (this.htmlElement != null) + if (htmlElement != null) { - HtmlDocument doc = this.htmlElement.Document; + HtmlDocument doc = htmlElement.Document; if (doc != null) { HtmlWindow window = doc.Window; @@ -1113,7 +1113,7 @@ public override void AttachEventHandler(string eventName, System.EventHandler ev // our EventHandler properly. HtmlToClrEventProxy proxy = AddEventProxy(eventName, eventHandler); - bool success = ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).AttachEvent(eventName, proxy); + bool success = ((UnsafeNativeMethods.IHTMLElement2)NativeHtmlElement).AttachEvent(eventName, proxy); Debug.Assert(success, "failed to add event"); } @@ -1121,9 +1121,9 @@ public override void ConnectToEvents() { if (cookie == null || !cookie.Connected) { - for (int i = 0; i < dispInterfaceTypes.Length && this.cookie == null; i++) + for (int i = 0; i < dispInterfaceTypes.Length && cookie == null; i++) { - this.cookie = new AxHost.ConnectionPointCookie(this.NativeHtmlElement, + cookie = new AxHost.ConnectionPointCookie(NativeHtmlElement, new HTMLElementEvents2(htmlElement), dispInterfaceTypes[i], /*throwException*/ false); @@ -1141,17 +1141,17 @@ public override void DetachEventHandler(string eventName, System.EventHandler ev HtmlToClrEventProxy proxy = RemoveEventProxy(eventHandler); if (proxy != null) { - ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).DetachEvent(eventName, proxy); + ((UnsafeNativeMethods.IHTMLElement2)NativeHtmlElement).DetachEvent(eventName, proxy); } } public override void DisconnectFromEvents() { - if (this.cookie != null) + if (cookie != null) { - this.cookie.Disconnect(); - this.cookie = null; + cookie.Disconnect(); + cookie = null; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementCollection.cs index be05258fb19..43be9a67b52 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementCollection.cs @@ -15,24 +15,24 @@ public sealed class HtmlElementCollection : ICollection internal HtmlElementCollection(HtmlShimManager shimManager) { - this.htmlElementCollection = null; - this.elementsArray = null; + htmlElementCollection = null; + elementsArray = null; this.shimManager = shimManager; } internal HtmlElementCollection(HtmlShimManager shimManager, UnsafeNativeMethods.IHTMLElementCollection elements) { - this.htmlElementCollection = elements; - this.elementsArray = null; + htmlElementCollection = elements; + elementsArray = null; this.shimManager = shimManager; - Debug.Assert(this.NativeHtmlElementCollection != null, "The element collection object should implement IHTMLElementCollection"); + Debug.Assert(NativeHtmlElementCollection != null, "The element collection object should implement IHTMLElementCollection"); } internal HtmlElementCollection(HtmlShimManager shimManager, HtmlElement[] array) { - this.htmlElementCollection = null; - this.elementsArray = array; + htmlElementCollection = null; + elementsArray = array; this.shimManager = shimManager; } @@ -40,7 +40,7 @@ private UnsafeNativeMethods.IHTMLElementCollection NativeHtmlElementCollection { get { - return this.htmlElementCollection; + return htmlElementCollection; } } @@ -54,15 +54,15 @@ public HtmlElement this[int index] throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidBoundArgument, nameof(index), index, 0, Count - 1)); } - if (this.NativeHtmlElementCollection != null) + if (NativeHtmlElementCollection != null) { UnsafeNativeMethods.IHTMLElement htmlElement = - this.NativeHtmlElementCollection.Item((object)index, (object)0) as UnsafeNativeMethods.IHTMLElement; + NativeHtmlElementCollection.Item((object)index, (object)0) as UnsafeNativeMethods.IHTMLElement; return (htmlElement != null) ? new HtmlElement(shimManager, htmlElement) : null; } else if (elementsArray != null) { - return this.elementsArray[index]; + return elementsArray[index]; } else { @@ -75,18 +75,18 @@ public HtmlElement this[string elementId] { get { - if (this.NativeHtmlElementCollection != null) + if (NativeHtmlElementCollection != null) { UnsafeNativeMethods.IHTMLElement htmlElement = - this.NativeHtmlElementCollection.Item((object)elementId, (object)0) as UnsafeNativeMethods.IHTMLElement; + NativeHtmlElementCollection.Item((object)elementId, (object)0) as UnsafeNativeMethods.IHTMLElement; return (htmlElement != null) ? new HtmlElement(shimManager, htmlElement) : null; } else if (elementsArray != null) { - int count = this.elementsArray.Length; + int count = elementsArray.Length; for (int i = 0; i < count; i++) { - HtmlElement element = this.elementsArray[i]; + HtmlElement element = elementsArray[i]; if (element.Id == elementId) { return element; @@ -103,7 +103,7 @@ public HtmlElement this[string elementId] public HtmlElementCollection GetElementsByName(string name) { - int count = this.Count; + int count = Count; HtmlElement[] temp = new HtmlElement[count]; // count is the maximum # of matches int tempIndex = 0; @@ -139,13 +139,13 @@ public int Count { get { - if (this.NativeHtmlElementCollection != null) + if (NativeHtmlElementCollection != null) { - return this.NativeHtmlElementCollection.GetLength(); + return NativeHtmlElementCollection.GetLength(); } else if (elementsArray != null) { - return this.elementsArray.Length; + return elementsArray.Length; } else { @@ -172,7 +172,7 @@ object ICollection.SyncRoot void ICollection.CopyTo(Array dest, int index) { - int count = this.Count; + int count = Count; for (int i = 0; i < count; i++) { dest.SetValue(this[i], index++); @@ -181,7 +181,7 @@ void ICollection.CopyTo(Array dest, int index) public IEnumerator GetEnumerator() { - HtmlElement[] htmlElements = new HtmlElement[this.Count]; + HtmlElement[] htmlElements = new HtmlElement[Count]; ((ICollection)this).CopyTo(htmlElements, 0); return htmlElements.GetEnumerator(); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlHistory.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlHistory.cs index 3601a99144d..05ffdd5d0dd 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlHistory.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlHistory.cs @@ -23,26 +23,26 @@ public sealed class HtmlHistory : IDisposable internal HtmlHistory(UnsafeNativeMethods.IOmHistory history) { - this.htmlHistory = history; - Debug.Assert(this.NativeOmHistory != null, "The history object should implement IOmHistory"); + htmlHistory = history; + Debug.Assert(NativeOmHistory != null, "The history object should implement IOmHistory"); } private UnsafeNativeMethods.IOmHistory NativeOmHistory { get { - if (this.disposed) + if (disposed) { throw new System.ObjectDisposedException(GetType().Name); } - return this.htmlHistory; + return htmlHistory; } } public void Dispose() { - this.htmlHistory = null; - this.disposed = true; + htmlHistory = null; + disposed = true; GC.SuppressFinalize(this); } @@ -50,7 +50,7 @@ public int Length { get { - return (int)this.NativeOmHistory.GetLength(); + return (int)NativeOmHistory.GetLength(); } } @@ -63,7 +63,7 @@ public void Back(int numberBack) else if (numberBack > 0) { object oNumForward = (object)(-numberBack); - this.NativeOmHistory.Go(ref oNumForward); + NativeOmHistory.Go(ref oNumForward); } } @@ -76,7 +76,7 @@ public void Forward(int numberForward) else if (numberForward > 0) { object oNumForward = (object)numberForward; - this.NativeOmHistory.Go(ref oNumForward); + NativeOmHistory.Go(ref oNumForward); } } @@ -100,7 +100,7 @@ public void Go(Uri url) public void Go(string urlString) { object loc = (object)urlString; - this.NativeOmHistory.Go(ref loc); + NativeOmHistory.Go(ref loc); } /// @@ -109,14 +109,14 @@ public void Go(string urlString) public void Go(int relativePosition) { object loc = (object)relativePosition; - this.NativeOmHistory.Go(ref loc); + NativeOmHistory.Go(ref loc); } public object DomHistory { get { - return this.NativeOmHistory; + return NativeOmHistory; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlShim.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlShim.cs index 190e5faa6f6..a975cade810 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlShim.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlShim.cs @@ -116,10 +116,10 @@ protected virtual void Dispose(bool disposing) if (disposing) { DisconnectFromEvents(); - if (this.events != null) + if (events != null) { - this.events.Dispose(); - this.events = null; + events.Dispose(); + events = null; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindow.cs index 6249f88c778..92b1f069ccf 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindow.cs @@ -29,8 +29,8 @@ public sealed class HtmlWindow internal HtmlWindow(HtmlShimManager shimManager, UnsafeNativeMethods.IHTMLWindow2 win) { - this.htmlWindow2 = win; - Debug.Assert(this.NativeHtmlWindow != null, "The window object should implement IHTMLWindow2"); + htmlWindow2 = win; + Debug.Assert(NativeHtmlWindow != null, "The window object should implement IHTMLWindow2"); this.shimManager = shimManager; } @@ -39,7 +39,7 @@ internal UnsafeNativeMethods.IHTMLWindow2 NativeHtmlWindow { get { - return this.htmlWindow2; + return htmlWindow2; } } @@ -70,7 +70,7 @@ public HtmlDocument Document { get { - UnsafeNativeMethods.IHTMLDocument iHTMLDocument = this.NativeHtmlWindow.GetDocument() as UnsafeNativeMethods.IHTMLDocument; + UnsafeNativeMethods.IHTMLDocument iHTMLDocument = NativeHtmlWindow.GetDocument() as UnsafeNativeMethods.IHTMLDocument; return iHTMLDocument != null ? new HtmlDocument(ShimManager, iHTMLDocument) : null; } } @@ -79,7 +79,7 @@ public object DomWindow { get { - return this.NativeHtmlWindow; + return NativeHtmlWindow; } } @@ -87,7 +87,7 @@ public HtmlWindowCollection Frames { get { - UnsafeNativeMethods.IHTMLFramesCollection2 iHTMLFramesCollection2 = this.NativeHtmlWindow.GetFrames(); + UnsafeNativeMethods.IHTMLFramesCollection2 iHTMLFramesCollection2 = NativeHtmlWindow.GetFrames(); return (iHTMLFramesCollection2 != null) ? new HtmlWindowCollection(ShimManager, iHTMLFramesCollection2) : null; } } @@ -96,7 +96,7 @@ public HtmlHistory History { get { - UnsafeNativeMethods.IOmHistory iOmHistory = this.NativeHtmlWindow.GetHistory(); + UnsafeNativeMethods.IOmHistory iOmHistory = NativeHtmlWindow.GetHistory(); return iOmHistory != null ? new HtmlHistory(iOmHistory) : null; } } @@ -105,7 +105,7 @@ public bool IsClosed { get { - return this.NativeHtmlWindow.GetClosed(); + return NativeHtmlWindow.GetClosed(); } } @@ -116,11 +116,11 @@ public string Name { get { - return this.NativeHtmlWindow.GetName(); + return NativeHtmlWindow.GetName(); } set { - this.NativeHtmlWindow.SetName(value); + NativeHtmlWindow.SetName(value); } } @@ -128,7 +128,7 @@ public HtmlWindow Opener { get { - UnsafeNativeMethods.IHTMLWindow2 iHTMLWindow2 = this.NativeHtmlWindow.GetOpener() as UnsafeNativeMethods.IHTMLWindow2; + UnsafeNativeMethods.IHTMLWindow2 iHTMLWindow2 = NativeHtmlWindow.GetOpener() as UnsafeNativeMethods.IHTMLWindow2; return (iHTMLWindow2 != null) ? new HtmlWindow(ShimManager, iHTMLWindow2) : null; } } @@ -137,7 +137,7 @@ public HtmlWindow Parent { get { - UnsafeNativeMethods.IHTMLWindow2 iHTMLWindow2 = this.NativeHtmlWindow.GetParent(); + UnsafeNativeMethods.IHTMLWindow2 iHTMLWindow2 = NativeHtmlWindow.GetParent(); return (iHTMLWindow2 != null) ? new HtmlWindow(ShimManager, iHTMLWindow2) : null; } } @@ -146,8 +146,8 @@ public Point Position { get { - return new Point(((UnsafeNativeMethods.IHTMLWindow3)this.NativeHtmlWindow).GetScreenLeft(), - ((UnsafeNativeMethods.IHTMLWindow3)this.NativeHtmlWindow).GetScreenTop()); + return new Point(((UnsafeNativeMethods.IHTMLWindow3)NativeHtmlWindow).GetScreenLeft(), + ((UnsafeNativeMethods.IHTMLWindow3)NativeHtmlWindow).GetScreenTop()); } } @@ -158,7 +158,7 @@ public Size Size { get { - UnsafeNativeMethods.IHTMLElement bodyElement = this.NativeHtmlWindow.GetDocument().GetBody(); + UnsafeNativeMethods.IHTMLElement bodyElement = NativeHtmlWindow.GetDocument().GetBody(); return new Size(bodyElement.GetOffsetWidth(), bodyElement.GetOffsetHeight()); } set @@ -171,11 +171,11 @@ public string StatusBarText { get { - return this.NativeHtmlWindow.GetStatus(); + return NativeHtmlWindow.GetStatus(); } set { - this.NativeHtmlWindow.SetStatus(value); + NativeHtmlWindow.SetStatus(value); } } @@ -183,7 +183,7 @@ public Uri Url { get { - UnsafeNativeMethods.IHTMLLocation iHtmlLocation = this.NativeHtmlWindow.GetLocation(); + UnsafeNativeMethods.IHTMLLocation iHtmlLocation = NativeHtmlWindow.GetLocation(); string stringLocation = (iHtmlLocation == null) ? "" : iHtmlLocation.GetHref(); return string.IsNullOrEmpty(stringLocation) ? null : new Uri(stringLocation); } @@ -193,14 +193,14 @@ public HtmlElement WindowFrameElement { get { - UnsafeNativeMethods.IHTMLElement htmlElement = ((UnsafeNativeMethods.IHTMLWindow4)this.NativeHtmlWindow).frameElement() as UnsafeNativeMethods.IHTMLElement; + UnsafeNativeMethods.IHTMLElement htmlElement = ((UnsafeNativeMethods.IHTMLWindow4)NativeHtmlWindow).frameElement() as UnsafeNativeMethods.IHTMLElement; return (htmlElement != null) ? new HtmlElement(ShimManager, htmlElement) : null; } } public void Alert(string message) { - this.NativeHtmlWindow.Alert(message); + NativeHtmlWindow.Alert(message); } public void AttachEventHandler(string eventName, EventHandler eventHandler) @@ -210,12 +210,12 @@ public void AttachEventHandler(string eventName, EventHandler eventHandler) public void Close() { - this.NativeHtmlWindow.Close(); + NativeHtmlWindow.Close(); } public bool Confirm(string message) { - return this.NativeHtmlWindow.Confirm(message); + return NativeHtmlWindow.Confirm(message); } public void DetachEventHandler(string eventName, EventHandler eventHandler) @@ -225,7 +225,7 @@ public void DetachEventHandler(string eventName, EventHandler eventHandler) public void Focus() { - this.NativeHtmlWindow.Focus(); + NativeHtmlWindow.Focus(); } /// @@ -233,7 +233,7 @@ public void Focus() /// public void MoveTo(int x, int y) { - this.NativeHtmlWindow.MoveTo(x, y); + NativeHtmlWindow.MoveTo(x, y); } /// @@ -241,12 +241,12 @@ public void MoveTo(int x, int y) /// public void MoveTo(Point point) { - this.NativeHtmlWindow.MoveTo(point.X, point.Y); + NativeHtmlWindow.MoveTo(point.X, point.Y); } public void Navigate(Uri url) { - this.NativeHtmlWindow.Navigate(url.ToString()); + NativeHtmlWindow.Navigate(url.ToString()); } /// Note: We intentionally have a string overload (apparently Mort wants one). We don't have @@ -256,7 +256,7 @@ public void Navigate(Uri url) [SuppressMessage("Microsoft.Design", "CA1057:StringUriOverloadsCallSystemUriOverloads")] public void Navigate(string urlString) { - this.NativeHtmlWindow.Navigate(urlString); + NativeHtmlWindow.Navigate(urlString); } /// Note: We intentionally have a string overload (apparently Mort wants one). We don't have @@ -266,7 +266,7 @@ public void Navigate(string urlString) [SuppressMessage("Microsoft.Design", "CA1057:StringUriOverloadsCallSystemUriOverloads")] public HtmlWindow Open(string urlString, string target, string windowOptions, bool replaceEntry) { - UnsafeNativeMethods.IHTMLWindow2 iHTMLWindow2 = this.NativeHtmlWindow.Open(urlString, target, windowOptions, replaceEntry); + UnsafeNativeMethods.IHTMLWindow2 iHTMLWindow2 = NativeHtmlWindow.Open(urlString, target, windowOptions, replaceEntry); return (iHTMLWindow2 != null) ? new HtmlWindow(ShimManager, iHTMLWindow2) : null; } @@ -283,7 +283,7 @@ public HtmlWindow Open(Uri url, string target, string windowOptions, bool replac [SuppressMessage("Microsoft.Design", "CA1057:StringUriOverloadsCallSystemUriOverloads")] public HtmlWindow OpenNew(string urlString, string windowOptions) { - UnsafeNativeMethods.IHTMLWindow2 iHTMLWindow2 = this.NativeHtmlWindow.Open(urlString, "_blank", windowOptions, true); + UnsafeNativeMethods.IHTMLWindow2 iHTMLWindow2 = NativeHtmlWindow.Open(urlString, "_blank", windowOptions, true); return (iHTMLWindow2 != null) ? new HtmlWindow(ShimManager, iHTMLWindow2) : null; } @@ -295,12 +295,12 @@ public HtmlWindow OpenNew(Uri url, string windowOptions) public string Prompt(string message, string defaultInputValue) { - return this.NativeHtmlWindow.Prompt(message, defaultInputValue).ToString(); + return NativeHtmlWindow.Prompt(message, defaultInputValue).ToString(); } public void RemoveFocus() { - this.NativeHtmlWindow.Blur(); + NativeHtmlWindow.Blur(); } /// @@ -308,7 +308,7 @@ public void RemoveFocus() /// public void ResizeTo(int width, int height) { - this.NativeHtmlWindow.ResizeTo(width, height); + NativeHtmlWindow.ResizeTo(width, height); } /// @@ -316,7 +316,7 @@ public void ResizeTo(int width, int height) /// public void ResizeTo(Size size) { - this.NativeHtmlWindow.ResizeTo(size.Width, size.Height); + NativeHtmlWindow.ResizeTo(size.Width, size.Height); } /// @@ -324,7 +324,7 @@ public void ResizeTo(Size size) /// public void ScrollTo(int x, int y) { - this.NativeHtmlWindow.ScrollTo(x, y); + NativeHtmlWindow.ScrollTo(x, y); } /// @@ -332,7 +332,7 @@ public void ScrollTo(int x, int y) /// public void ScrollTo(Point point) { - this.NativeHtmlWindow.ScrollTo(point.X, point.Y); + NativeHtmlWindow.ScrollTo(point.X, point.Y); } // @@ -395,12 +395,12 @@ private class HTMLWindowEvents2 : StandardOleMarshalObject, /*Enforce calling ba public HTMLWindowEvents2(HtmlWindow htmlWindow) { - this.parent = htmlWindow; + parent = htmlWindow; } private void FireEvent(object key, EventArgs e) { - if (this.parent != null) + if (parent != null) { parent.WindowShim.FireEvent(key, e); } @@ -488,7 +488,7 @@ internal class HtmlWindowShim : HtmlShim public HtmlWindowShim(HtmlWindow window) { - this.htmlWindow = window; + htmlWindow = window; } public UnsafeNativeMethods.IHTMLWindow2 NativeHtmlWindow @@ -510,7 +510,7 @@ public override void AttachEventHandler(string eventName, System.EventHandler ev // our EventHandler properly. HtmlToClrEventProxy proxy = AddEventProxy(eventName, eventHandler); - bool success = ((UnsafeNativeMethods.IHTMLWindow3)this.NativeHtmlWindow).AttachEvent(eventName, proxy); + bool success = ((UnsafeNativeMethods.IHTMLWindow3)NativeHtmlWindow).AttachEvent(eventName, proxy); Debug.Assert(success, "failed to add event"); } @@ -519,7 +519,7 @@ public override void ConnectToEvents() { if (cookie == null || !cookie.Connected) { - this.cookie = new AxHost.ConnectionPointCookie(NativeHtmlWindow, + cookie = new AxHost.ConnectionPointCookie(NativeHtmlWindow, new HTMLWindowEvents2(htmlWindow), typeof(UnsafeNativeMethods.DHTMLWindowEvents2), /*throwException*/ false); @@ -536,16 +536,16 @@ public override void DetachEventHandler(string eventName, System.EventHandler ev HtmlToClrEventProxy proxy = RemoveEventProxy(eventHandler); if (proxy != null) { - ((UnsafeNativeMethods.IHTMLWindow3)this.NativeHtmlWindow).DetachEvent(eventName, proxy); + ((UnsafeNativeMethods.IHTMLWindow3)NativeHtmlWindow).DetachEvent(eventName, proxy); } } public override void DisconnectFromEvents() { - if (this.cookie != null) + if (cookie != null) { - this.cookie.Disconnect(); - this.cookie = null; + cookie.Disconnect(); + cookie = null; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindowCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindowCollection.cs index 594b3b07595..5733d050347 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindowCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindowCollection.cs @@ -15,17 +15,17 @@ public class HtmlWindowCollection : ICollection internal HtmlWindowCollection(HtmlShimManager shimManager, UnsafeNativeMethods.IHTMLFramesCollection2 collection) { - this.htmlFramesCollection2 = collection; + htmlFramesCollection2 = collection; this.shimManager = shimManager; - Debug.Assert(this.NativeHTMLFramesCollection2 != null, "The window collection object should implement IHTMLFramesCollection2"); + Debug.Assert(NativeHTMLFramesCollection2 != null, "The window collection object should implement IHTMLFramesCollection2"); } private UnsafeNativeMethods.IHTMLFramesCollection2 NativeHTMLFramesCollection2 { get { - return this.htmlFramesCollection2; + return htmlFramesCollection2; } } @@ -40,7 +40,7 @@ public HtmlWindow this[int index] } object oIndex = (object)index; - UnsafeNativeMethods.IHTMLWindow2 htmlWindow2 = this.NativeHTMLFramesCollection2.Item(ref oIndex) + UnsafeNativeMethods.IHTMLWindow2 htmlWindow2 = NativeHTMLFramesCollection2.Item(ref oIndex) as UnsafeNativeMethods.IHTMLWindow2; return (htmlWindow2 != null) ? new HtmlWindow(shimManager, htmlWindow2) : null; } @@ -54,7 +54,7 @@ public HtmlWindow this[string windowId] UnsafeNativeMethods.IHTMLWindow2 htmlWindow2 = null; try { - htmlWindow2 = this.htmlFramesCollection2.Item(ref oWindowId) + htmlWindow2 = htmlFramesCollection2.Item(ref oWindowId) as UnsafeNativeMethods.IHTMLWindow2; } catch (COMException) @@ -72,7 +72,7 @@ public int Count { get { - return this.NativeHTMLFramesCollection2.GetLength(); + return NativeHTMLFramesCollection2.GetLength(); } } @@ -94,7 +94,7 @@ object ICollection.SyncRoot void ICollection.CopyTo(Array dest, int index) { - int count = this.Count; + int count = Count; for (int i = 0; i < count; i++) { dest.SetValue(this[i], index++); @@ -103,7 +103,7 @@ void ICollection.CopyTo(Array dest, int index) public IEnumerator GetEnumerator() { - HtmlWindow[] htmlWindows = new HtmlWindow[this.Count]; + HtmlWindow[] htmlWindows = new HtmlWindow[Count]; ((ICollection)this).CopyTo(htmlWindows, 0); return htmlWindows.GetEnumerator(); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs index e948ee4ab4b..76885166859 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs @@ -331,20 +331,20 @@ public ImageListStreamer ImageStream { NativeImageList himl = value.GetNativeImageList(); - if (himl != null && himl != this.nativeImageList) + if (himl != null && himl != nativeImageList) { - bool recreatingHandle = this.HandleCreated;//We only need to fire RecreateHandle if there was a previous handle + bool recreatingHandle = HandleCreated;//We only need to fire RecreateHandle if there was a previous handle DestroyHandle(); originals = null; - this.nativeImageList = new NativeImageList(SafeNativeMethods.ImageList_Duplicate(new HandleRef(himl, himl.Handle))); + nativeImageList = new NativeImageList(SafeNativeMethods.ImageList_Duplicate(new HandleRef(himl, himl.Handle))); int x, y; - if (SafeNativeMethods.ImageList_GetIconSize(new HandleRef(this, this.nativeImageList.Handle), out x, out y)) + if (SafeNativeMethods.ImageList_GetIconSize(new HandleRef(this, nativeImageList.Handle), out x, out y)) { imageSize = new Size(x, y); } // need to get the image bpp NativeMethods.IMAGEINFO imageInfo = new NativeMethods.IMAGEINFO(); // review? do I need to delete the mask and image? - if (SafeNativeMethods.ImageList_GetImageInfo(new HandleRef(this, this.nativeImageList.Handle), 0, imageInfo)) + if (SafeNativeMethods.ImageList_GetImageInfo(new HandleRef(this, nativeImageList.Handle), 0, imageInfo)) { NativeMethods.BITMAP bmp = new NativeMethods.BITMAP(); UnsafeNativeMethods.GetObject(new HandleRef(null, imageInfo.hbmImage), Marshal.SizeOf(bmp), bmp); @@ -770,7 +770,7 @@ private Bitmap GetBitmap(int index) { NativeMethods.IMAGEINFO imageInfo = new NativeMethods.IMAGEINFO(); // review? do I need to delete the mask and image inside of imageinfo? - if (SafeNativeMethods.ImageList_GetImageInfo(new HandleRef(this, this.Handle), index, imageInfo)) + if (SafeNativeMethods.ImageList_GetImageInfo(new HandleRef(this, Handle), index, imageInfo)) { Bitmap tmpBitmap = null; BitmapData bmpData = null; @@ -1138,7 +1138,7 @@ internal void ResetKeys() if (imageInfoCollection != null) imageInfoCollection.Clear(); - for (int i = 0; i < this.Count; i++) + for (int i = 0; i < Count; i++) { imageInfoCollection.Add(new ImageCollection.ImageInfo()); } @@ -1337,7 +1337,7 @@ public Image this[string key] /// public void Add(string key, Image image) { - Debug.Assert((this.Count == imageInfoCollection.Count), "The count of these two collections should be equal."); + Debug.Assert((Count == imageInfoCollection.Count), "The count of these two collections should be equal."); // Store off the name. ImageInfo imageInfo = new ImageInfo(); @@ -1354,7 +1354,7 @@ public void Add(string key, Image image) /// public void Add(string key, Icon icon) { - Debug.Assert((this.Count == imageInfoCollection.Count), "The count of these two collections should be equal."); + Debug.Assert((Count == imageInfoCollection.Count), "The count of these two collections should be equal."); // Store off the name. ImageInfo imageInfo = new ImageInfo(); @@ -1613,7 +1613,7 @@ public int IndexOfKey(string key) } // step 2 - search for the item - for (int i = 0; i < this.Count; i++) + for (int i = 0; i < Count; i++) { if ((imageInfoCollection[i] != null) && (WindowsFormsUtils.SafeCompareStrings(((ImageInfo)imageInfoCollection[i]).Name, key, /* ignoreCase = */ true))) @@ -1640,7 +1640,7 @@ void IList.Insert(int index, object value) /// private bool IsValidIndex(int index) { - return ((index >= 0) && (index < this.Count)); + return ((index >= 0) && (index < Count)); } void ICollection.CopyTo(Array dest, int index) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/InputLanguage.cs b/src/System.Windows.Forms/src/System/Windows/Forms/InputLanguage.cs index 24fc5e9f473..9f50b878559 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/InputLanguage.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/InputLanguage.cs @@ -315,7 +315,7 @@ internal static InputLanguageChangingEventArgs CreateInputLanguageChangingEventA /// public override bool Equals(object value) { - return (value is InputLanguage other) && (this.handle == other.handle); + return (value is InputLanguage other) && (handle == other.handle); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/KeyboardToolTipStateMachine.cs b/src/System.Windows.Forms/src/System/Windows/Forms/KeyboardToolTipStateMachine.cs index b243bde6cf7..6d85a3b6980 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/KeyboardToolTipStateMachine.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/KeyboardToolTipStateMachine.cs @@ -62,76 +62,76 @@ public static KeyboardToolTipStateMachine Instance private KeyboardToolTipStateMachine() { - this.transitions = new Dictionary> + transitions = new Dictionary> { - [new SmTransition(SmState.Hidden, SmEvent.FocusedTool)] = this.SetupInitShowTimer, - [new SmTransition(SmState.Hidden, SmEvent.LeftTool)] = this.DoNothing, // OK + [new SmTransition(SmState.Hidden, SmEvent.FocusedTool)] = SetupInitShowTimer, + [new SmTransition(SmState.Hidden, SmEvent.LeftTool)] = DoNothing, // OK - [new SmTransition(SmState.ReadyForInitShow, SmEvent.FocusedTool)] = this.DoNothing, // unlikely: focus without leave - [new SmTransition(SmState.ReadyForInitShow, SmEvent.LeftTool)] = this.ResetFsmToHidden, - [new SmTransition(SmState.ReadyForInitShow, SmEvent.InitialDelayTimerExpired)] = this.ShowToolTip, + [new SmTransition(SmState.ReadyForInitShow, SmEvent.FocusedTool)] = DoNothing, // unlikely: focus without leave + [new SmTransition(SmState.ReadyForInitShow, SmEvent.LeftTool)] = ResetFsmToHidden, + [new SmTransition(SmState.ReadyForInitShow, SmEvent.InitialDelayTimerExpired)] = ShowToolTip, - [new SmTransition(SmState.Shown, SmEvent.FocusedTool)] = this.DoNothing, // unlikely: focus without leave - [new SmTransition(SmState.Shown, SmEvent.LeftTool)] = this.HideAndStartWaitingForRefocus, - [new SmTransition(SmState.Shown, SmEvent.AutoPopupDelayTimerExpired)] = this.ResetFsmToHidden, + [new SmTransition(SmState.Shown, SmEvent.FocusedTool)] = DoNothing, // unlikely: focus without leave + [new SmTransition(SmState.Shown, SmEvent.LeftTool)] = HideAndStartWaitingForRefocus, + [new SmTransition(SmState.Shown, SmEvent.AutoPopupDelayTimerExpired)] = ResetFsmToHidden, - [new SmTransition(SmState.WaitForRefocus, SmEvent.FocusedTool)] = this.SetupReshowTimer, - [new SmTransition(SmState.WaitForRefocus, SmEvent.LeftTool)] = this.DoNothing, // OK - [new SmTransition(SmState.WaitForRefocus, SmEvent.RefocusWaitDelayExpired)] = this.ResetFsmToHidden, + [new SmTransition(SmState.WaitForRefocus, SmEvent.FocusedTool)] = SetupReshowTimer, + [new SmTransition(SmState.WaitForRefocus, SmEvent.LeftTool)] = DoNothing, // OK + [new SmTransition(SmState.WaitForRefocus, SmEvent.RefocusWaitDelayExpired)] = ResetFsmToHidden, - [new SmTransition(SmState.ReadyForReshow, SmEvent.FocusedTool)] = this.DoNothing, // unlikely: focus without leave - [new SmTransition(SmState.ReadyForReshow, SmEvent.LeftTool)] = this.StartWaitingForRefocus, - [new SmTransition(SmState.ReadyForReshow, SmEvent.ReshowDelayTimerExpired)] = this.ShowToolTip + [new SmTransition(SmState.ReadyForReshow, SmEvent.FocusedTool)] = DoNothing, // unlikely: focus without leave + [new SmTransition(SmState.ReadyForReshow, SmEvent.LeftTool)] = StartWaitingForRefocus, + [new SmTransition(SmState.ReadyForReshow, SmEvent.ReshowDelayTimerExpired)] = ShowToolTip }; } public void ResetStateMachine(ToolTip toolTip) { - this.Reset(toolTip); + Reset(toolTip); } public void Hook(IKeyboardToolTip tool, ToolTip toolTip) { if (tool.AllowsToolTip()) { - this.StartTracking(tool, toolTip); + StartTracking(tool, toolTip); tool.OnHooked(toolTip); } } public void NotifyAboutMouseEnter(IKeyboardToolTip sender) { - if (this.IsToolTracked(sender) && sender.ShowsOwnToolTip()) + if (IsToolTracked(sender) && sender.ShowsOwnToolTip()) { - this.Reset(null); + Reset(null); } } private bool IsToolTracked(IKeyboardToolTip sender) { - return this.toolToTip[sender] != null; + return toolToTip[sender] != null; } public void NotifyAboutLostFocus(IKeyboardToolTip sender) { - if (this.IsToolTracked(sender) && sender.ShowsOwnToolTip()) + if (IsToolTracked(sender) && sender.ShowsOwnToolTip()) { - this.Transit(SmEvent.LeftTool, sender); - if (this.currentTool == null) + Transit(SmEvent.LeftTool, sender); + if (currentTool == null) { - this.lastFocusedTool.SetTarget(null); + lastFocusedTool.SetTarget(null); } } } public void NotifyAboutGotFocus(IKeyboardToolTip sender) { - if (this.IsToolTracked(sender) && sender.ShowsOwnToolTip() && sender.IsBeingTabbedTo()) + if (IsToolTracked(sender) && sender.ShowsOwnToolTip() && sender.IsBeingTabbedTo()) { - this.Transit(SmEvent.FocusedTool, sender); - if (this.currentTool == sender) + Transit(SmEvent.FocusedTool, sender); + if (currentTool == sender) { - this.lastFocusedTool.SetTarget(sender); + lastFocusedTool.SetTarget(sender); } } } @@ -140,14 +140,14 @@ public void Unhook(IKeyboardToolTip tool, ToolTip toolTip) { if (tool.AllowsToolTip()) { - this.StopTracking(tool, toolTip); + StopTracking(tool, toolTip); tool.OnUnhooked(toolTip); } } public void NotifyAboutFormDeactivation(ToolTip sender) { - this.OnFormDeactivation(sender); + OnFormDeactivation(sender); } @@ -156,7 +156,7 @@ internal IKeyboardToolTip LastFocusedTool get { IKeyboardToolTip tool; - if (this.lastFocusedTool.TryGetTarget(out tool)) + if (lastFocusedTool.TryGetTarget(out tool)) { return tool; } @@ -167,20 +167,20 @@ internal IKeyboardToolTip LastFocusedTool private SmState HideAndStartWaitingForRefocus(IKeyboardToolTip tool, ToolTip toolTip) { - toolTip.HideToolTip(this.currentTool); + toolTip.HideToolTip(currentTool); return StartWaitingForRefocus(tool, toolTip); } private SmState StartWaitingForRefocus(IKeyboardToolTip tool, ToolTip toolTip) { - this.ResetTimer(); - this.currentTool = null; + ResetTimer(); + currentTool = null; SendOrPostCallback expirationCallback = null; - this.refocusDelayExpirationCallback = expirationCallback = (object toolObject) => + refocusDelayExpirationCallback = expirationCallback = (object toolObject) => { - if (this.currentState == SmState.WaitForRefocus && this.refocusDelayExpirationCallback == expirationCallback) + if (currentState == SmState.WaitForRefocus && refocusDelayExpirationCallback == expirationCallback) { - this.Transit(SmEvent.RefocusWaitDelayExpired, (IKeyboardToolTip)toolObject); + Transit(SmEvent.RefocusWaitDelayExpired, (IKeyboardToolTip)toolObject); } }; WindowsFormsSynchronizationContext.Current.Post(expirationCallback, tool); @@ -189,9 +189,9 @@ private SmState StartWaitingForRefocus(IKeyboardToolTip tool, ToolTip toolTip) private SmState SetupReshowTimer(IKeyboardToolTip tool, ToolTip toolTip) { - this.currentTool = tool; - this.ResetTimer(); - this.StartTimer(toolTip.GetDelayTime(NativeMethods.TTDT_RESHOW), this.GetOneRunTickHandler((Timer sender) => this.Transit(SmEvent.ReshowDelayTimerExpired, tool))); + currentTool = tool; + ResetTimer(); + StartTimer(toolTip.GetDelayTime(NativeMethods.TTDT_RESHOW), GetOneRunTickHandler((Timer sender) => Transit(SmEvent.ReshowDelayTimerExpired, tool))); return SmState.ReadyForReshow; } @@ -199,38 +199,38 @@ private SmState ShowToolTip(IKeyboardToolTip tool, ToolTip toolTip) { string toolTipText = tool.GetCaptionForTool(toolTip); int autoPopDelay = toolTip.GetDelayTime(NativeMethods.TTDT_AUTOPOP); - if (!this.currentTool.IsHoveredWithMouse()) + if (!currentTool.IsHoveredWithMouse()) { - toolTip.ShowKeyboardToolTip(toolTipText, this.currentTool, autoPopDelay); + toolTip.ShowKeyboardToolTip(toolTipText, currentTool, autoPopDelay); } - this.StartTimer(autoPopDelay, this.GetOneRunTickHandler((Timer sender) => this.Transit(SmEvent.AutoPopupDelayTimerExpired, this.currentTool))); + StartTimer(autoPopDelay, GetOneRunTickHandler((Timer sender) => Transit(SmEvent.AutoPopupDelayTimerExpired, currentTool))); return SmState.Shown; } private SmState ResetFsmToHidden(IKeyboardToolTip tool, ToolTip toolTip) { - return this.FullFsmReset(); + return FullFsmReset(); } private SmState DoNothing(IKeyboardToolTip tool, ToolTip toolTip) { - return this.currentState; + return currentState; } private SmState SetupInitShowTimer(IKeyboardToolTip tool, ToolTip toolTip) { - this.currentTool = tool; - this.ResetTimer(); - this.StartTimer(toolTip.GetDelayTime(NativeMethods.TTDT_INITIAL), this.GetOneRunTickHandler((Timer sender) => this.Transit(SmEvent.InitialDelayTimerExpired, this.currentTool))); + currentTool = tool; + ResetTimer(); + StartTimer(toolTip.GetDelayTime(NativeMethods.TTDT_INITIAL), GetOneRunTickHandler((Timer sender) => Transit(SmEvent.InitialDelayTimerExpired, currentTool))); return SmState.ReadyForInitShow; } private void StartTimer(int interval, EventHandler eventHandler) { - this.timer.Interval = interval; - this.timer.Tick += eventHandler; - this.timer.Start(); + timer.Interval = interval; + timer.Tick += eventHandler; + timer.Start(); } private EventHandler GetOneRunTickHandler(Action handler) @@ -238,24 +238,24 @@ private EventHandler GetOneRunTickHandler(Action handler) EventHandler wrapper = null; wrapper = (object sender, EventArgs eventArgs) => { - this.timer.Stop(); - this.timer.Tick -= wrapper; - handler(this.timer); + timer.Stop(); + timer.Tick -= wrapper; + handler(timer); }; return wrapper; } private void Transit(SmEvent @event, IKeyboardToolTip source) { - Debug.Assert(transitions.ContainsKey(new SmTransition(this.currentState, @event)), "Unsupported KeyboardToolTipFsmTransition!"); + Debug.Assert(transitions.ContainsKey(new SmTransition(currentState, @event)), "Unsupported KeyboardToolTipFsmTransition!"); bool fullFsmResetRequired = false; try { - ToolTip toolTip = this.toolToTip[source]; - if ((this.currentTool == null || this.currentTool.CanShowToolTipsNow()) && toolTip != null) + ToolTip toolTip = toolToTip[source]; + if ((currentTool == null || currentTool.CanShowToolTipsNow()) && toolTip != null) { - Func transitionFunction = transitions[new SmTransition(this.currentState, @event)]; - this.currentState = transitionFunction(source, toolTip); + Func transitionFunction = transitions[new SmTransition(currentState, @event)]; + currentState = transitionFunction(source, toolTip); } else { @@ -271,55 +271,55 @@ private void Transit(SmEvent @event, IKeyboardToolTip source) { if (fullFsmResetRequired) { - this.FullFsmReset(); + FullFsmReset(); } } } private SmState FullFsmReset() { - if (this.currentState == SmState.Shown && this.currentTool != null) + if (currentState == SmState.Shown && currentTool != null) { - ToolTip currentToolTip = this.toolToTip[this.currentTool]; + ToolTip currentToolTip = toolToTip[currentTool]; if (currentToolTip != null) { - currentToolTip.HideToolTip(this.currentTool); + currentToolTip.HideToolTip(currentTool); } } - this.ResetTimer(); - this.currentTool = null; - return this.currentState = SmState.Hidden; + ResetTimer(); + currentTool = null; + return currentState = SmState.Hidden; } private void ResetTimer() { - this.timer.ClearTimerTickHandlers(); - this.timer.Stop(); + timer.ClearTimerTickHandlers(); + timer.Stop(); } private void Reset(ToolTip toolTipToReset) { - if (toolTipToReset == null || (this.currentTool != null && this.toolToTip[this.currentTool] == toolTipToReset)) + if (toolTipToReset == null || (currentTool != null && toolToTip[currentTool] == toolTipToReset)) { - this.FullFsmReset(); + FullFsmReset(); } } private void StartTracking(IKeyboardToolTip tool, ToolTip toolTip) { - this.toolToTip[tool] = toolTip; + toolToTip[tool] = toolTip; } private void StopTracking(IKeyboardToolTip tool, ToolTip toolTip) { - this.toolToTip.Remove(tool, toolTip); + toolToTip.Remove(tool, toolTip); } private void OnFormDeactivation(ToolTip sender) { - if (this.currentTool != null && this.toolToTip[this.currentTool] == sender) + if (currentTool != null && toolToTip[currentTool] == sender) { - this.FullFsmReset(); + FullFsmReset(); } } @@ -355,17 +355,17 @@ public SmTransition(SmState currentState, SmEvent @event) public bool Equals(SmTransition other) { - return this.currentState == other.currentState && this.@event == other.@event; + return currentState == other.currentState && @event == other.@event; } public override bool Equals(object obj) { - return obj is SmTransition && this.Equals((SmTransition)obj); + return obj is SmTransition && Equals((SmTransition)obj); } public override int GetHashCode() { - return (byte)this.currentState << 16 | (byte)this.@event; + return (byte)currentState << 16 | (byte)@event; } } @@ -384,12 +384,12 @@ public ToolTip this[IKeyboardToolTip tool] { WeakReference toolTipReference; ToolTip toolTip = null; - if (this.table.TryGetValue(tool, out toolTipReference)) + if (table.TryGetValue(tool, out toolTipReference)) { if (!toolTipReference.TryGetTarget(out toolTip)) { // removing dead reference - this.table.Remove(tool); + table.Remove(tool); } } return toolTip; @@ -398,13 +398,13 @@ public ToolTip this[IKeyboardToolTip tool] set { WeakReference toolTipReference; - if (this.table.TryGetValue(tool, out toolTipReference)) + if (table.TryGetValue(tool, out toolTipReference)) { toolTipReference.SetTarget(value); } else { - this.table.Add(tool, new WeakReference(value)); + table.Add(tool, new WeakReference(value)); } } } @@ -413,19 +413,19 @@ public void Remove(IKeyboardToolTip tool, ToolTip toolTip) { WeakReference toolTipReference; ToolTip existingToolTip; - if (this.table.TryGetValue(tool, out toolTipReference)) + if (table.TryGetValue(tool, out toolTipReference)) { if (toolTipReference.TryGetTarget(out existingToolTip)) { if (existingToolTip == toolTip) { - this.table.Remove(tool); + table.Remove(tool); } } else { // removing dead reference - this.table.Remove(tool); + table.Remove(tool); } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs index 8b2b54541b7..2cdb99ff647 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs @@ -1053,7 +1053,7 @@ public bool UseMnemonic //set windowStyle directly instead of recreating handle to increase efficiency if (IsHandleCreated) { - int style = this.WindowStyle; + int style = WindowStyle; if (!UseMnemonic) { @@ -1063,7 +1063,7 @@ public bool UseMnemonic { style &= ~NativeMethods.SS_NOPREFIX; } - this.WindowStyle = style; + WindowStyle = style; } } } @@ -1086,8 +1086,8 @@ internal void AdjustSize() // If width and/or height are constrained by anchoring, don't adjust control size // to fit around text, since this will cause us to lose the original anchored size. if (!AutoSize && - ((this.Anchor & (AnchorStyles.Left | AnchorStyles.Right)) == (AnchorStyles.Left | AnchorStyles.Right) || - (this.Anchor & (AnchorStyles.Top | AnchorStyles.Bottom)) == (AnchorStyles.Top | AnchorStyles.Bottom))) + ((Anchor & (AnchorStyles.Left | AnchorStyles.Right)) == (AnchorStyles.Left | AnchorStyles.Right) || + (Anchor & (AnchorStyles.Top | AnchorStyles.Bottom)) == (AnchorStyles.Top | AnchorStyles.Bottom))) { return; } @@ -1128,7 +1128,7 @@ private void Animate(bool animate) { if (image != null) { - ImageAnimator.Animate(image, new EventHandler(this.OnFrameChanged)); + ImageAnimator.Animate(image, new EventHandler(OnFrameChanged)); labelState[StateAnimating] = animate ? 1 : 0; } } @@ -1136,7 +1136,7 @@ private void Animate(bool animate) { if (image != null) { - ImageAnimator.StopAnimate(image, new EventHandler(this.OnFrameChanged)); + ImageAnimator.StopAnimate(image, new EventHandler(OnFrameChanged)); labelState[StateAnimating] = animate ? 1 : 0; } } @@ -1189,12 +1189,12 @@ protected override AccessibleObject CreateAccessibilityInstance() internal virtual StringFormat CreateStringFormat() { - return ControlPaint.CreateStringFormat(this, this.TextAlign, this.AutoEllipsis, this.UseMnemonic); + return ControlPaint.CreateStringFormat(this, TextAlign, AutoEllipsis, UseMnemonic); } private TextFormatFlags CreateTextFormatFlags() { - return CreateTextFormatFlags(this.Size - GetBordersAndPadding()); + return CreateTextFormatFlags(Size - GetBordersAndPadding()); } /// /// Get TextFormatFlags flags for rendering text using GDI (TextRenderer). @@ -1207,7 +1207,7 @@ internal virtual TextFormatFlags CreateTextFormatFlags(Size constrainingSize) // whenever something can change the TextFormatFlags used // MeasureTextCache.InvalidateCache() should be called so we can approprately clear. - TextFormatFlags flags = ControlPaint.CreateTextFormatFlags(this, this.TextAlign, this.AutoEllipsis, this.UseMnemonic); + TextFormatFlags flags = ControlPaint.CreateTextFormatFlags(this, TextAlign, AutoEllipsis, UseMnemonic); // Remove WordBreak if the size is large enough to display all the text. if (!MeasureTextCache.TextRequiresWordBreak(Text, Font, constrainingSize, flags)) @@ -1235,7 +1235,7 @@ protected override void Dispose(bool disposing) // Holding on to images and image list is a memory leak. if (ImageList != null) { - ImageList.Disposed -= new EventHandler(this.DetachImageList); + ImageList.Disposed -= new EventHandler(DetachImageList); ImageList.RecreateHandle -= new EventHandler(ImageListRecreateHandle); Properties.SetObject(PropImageList, null); } @@ -1379,7 +1379,7 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) if (string.IsNullOrEmpty(Text)) { // empty labels return the font height + borders - using (WindowsFont font = WindowsFont.FromFont(this.Font)) + using (WindowsFont font = WindowsFont.FromFont(Font)) { // this is the character that Windows uses to determine the extent requiredSize = WindowsGraphicsCacheManager.MeasurementGraphics.GetTextExtent("0", font); @@ -1434,7 +1434,7 @@ private int GetLeadingTextPaddingFromTextFormatFlags() return 0; } - using (WindowsGraphics wg = WindowsGraphics.FromHwnd(this.Handle)) + using (WindowsGraphics wg = WindowsGraphics.FromHwnd(Handle)) { TextFormatFlags flags = CreateTextFormatFlags(); @@ -1447,7 +1447,7 @@ private int GetLeadingTextPaddingFromTextFormatFlags() wg.TextPadding = TextPaddingOptions.LeftAndRightPadding; } - using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(this.Font)) + using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(Font)) { IntNativeMethods.DRAWTEXTPARAMS dtParams = wg.GetTextMargins(wf); @@ -1537,7 +1537,7 @@ private void OnFrameChanged(object o, EventArgs e) } if (IsHandleCreated && InvokeRequired) { - BeginInvoke(new EventHandler(this.OnFrameChanged), o, e); + BeginInvoke(new EventHandler(OnFrameChanged), o, e); return; } @@ -1600,10 +1600,10 @@ protected override void OnPaddingChanged(EventArgs e) protected override void OnPaint(PaintEventArgs e) { Animate(); - ImageAnimator.UpdateFrames(this.Image); + ImageAnimator.UpdateFrames(Image); Rectangle face = LayoutUtils.DeflateRect(ClientRectangle, Padding); - Image i = this.Image; + Image i = Image; if (i != null) { DrawImage(e.Graphics, i, face, RtlTranslateAlignment(ImageAlign)); @@ -1634,7 +1634,7 @@ protected override void OnPaint(PaintEventArgs e) if (AutoEllipsis) { - Rectangle clientRect = this.ClientRectangle; + Rectangle clientRect = ClientRectangle; Size preferredSize = GetPreferredSize(new Size(clientRect.Width, clientRect.Height)); showToolTip = (clientRect.Width < preferredSize.Width || clientRect.Height < preferredSize.Height); } @@ -1673,7 +1673,7 @@ protected override void OnPaint(PaintEventArgs e) //Theme specs -- if the backcolor is darker than Control, we use // ControlPaint.Dark(backcolor). Otherwise we use ControlDark. - Color disabledTextForeColor = TextRenderer.DisabledTextColor(this.BackColor); + Color disabledTextForeColor = TextRenderer.DisabledTextColor(BackColor); TextRenderer.DrawText(e.Graphics, Text, Font, face, disabledTextForeColor, flags); } } @@ -1831,7 +1831,7 @@ protected override void WndProc(ref Message m) // label returns HT_TRANSPARENT for everything, so all messages get // routed to the parent. Change this so we can tell what's going on. // - Rectangle rectInScreen = this.RectangleToScreen(new Rectangle(0, 0, Width, Height)); + Rectangle rectInScreen = RectangleToScreen(new Rectangle(0, 0, Width, Height)); Point pt = new Point(unchecked((int)(long)m.LParam)); m.Result = (IntPtr)((rectInScreen.Contains(pt) ? NativeMethods.HTCLIENT : NativeMethods.HTNOWHERE)); break; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElementCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElementCollection.cs index 1fd3517ed1d..c2e8425a59b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElementCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElementCollection.cs @@ -53,7 +53,7 @@ public override bool Equals(object obj) for (int i = 0; i < Count; i++) { - if (this.InnerList[i] != other.InnerList[i]) + if (InnerList[i] != other.InnerList[i]) { return false; } @@ -74,7 +74,7 @@ internal void MoveElement(IArrangedElement element, int fromIndex, int toIndex) case -1: case 1: // simple swap - this.InnerList[fromIndex] = this.InnerList[toIndex]; + InnerList[fromIndex] = InnerList[toIndex]; break; default: @@ -100,7 +100,7 @@ internal void MoveElement(IArrangedElement element, int fromIndex, int toIndex) Copy(this, start, this, dest, delta); break; } - this.InnerList[toIndex] = element; + InnerList[toIndex] = element; } private static void Copy(ArrangedElementCollection sourceList, int sourceIndex, ArrangedElementCollection destinationList, int destinationIndex, int length) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs index f724d42b928..2574b19cf83 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs @@ -363,8 +363,8 @@ private class ContainerProxy private bool _isContainerRTL; public ContainerProxy(IArrangedElement container) { - this._container = container; - this._isContainerRTL = false; + _container = container; + _isContainerRTL = false; if (_container is Control) { _isContainerRTL = ((Control)(_container)).RightToLeft == RightToLeft.Yes; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutSettings.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutSettings.cs index cfeb2417239..e4cf94723c5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutSettings.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutSettings.cs @@ -16,7 +16,7 @@ protected LayoutSettings() internal LayoutSettings(IArrangedElement owner) { - this._owner = owner; + _owner = owner; } public virtual LayoutEngine LayoutEngine diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutUtils.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutUtils.cs index 43bd06d724f..b34a92ccffa 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutUtils.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutUtils.cs @@ -726,8 +726,8 @@ private struct PreferredSizeCache { public PreferredSizeCache(Size constrainingSize, Size preferredSize) { - this.ConstrainingSize = constrainingSize; - this.PreferredSize = preferredSize; + ConstrainingSize = constrainingSize; + PreferredSize = preferredSize; } public Size ConstrainingSize; public Size PreferredSize; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs index 06958cd1e72..5c50cda4d1e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs @@ -642,8 +642,8 @@ internal override bool CanUseTextRenderer { // If no link or the LinkArea is one and covers the entire text, we can support UseCompatibleTextRendering = false. // Observe that LinkArea refers to the first link always. - StringInfo stringInfo = new StringInfo(this.Text); - return this.LinkArea.Start == 0 && (this.LinkArea.Length == 0 || this.LinkArea.Length == stringInfo.LengthInTextElements); + StringInfo stringInfo = new StringInfo(Text); + return LinkArea.Start == 0 && (LinkArea.Length == 0 || LinkArea.Length == stringInfo.LengthInTextElements); } } @@ -704,10 +704,10 @@ private void EnsureRun(Graphics g) { return; } - if (this.textRegion != null) + if (textRegion != null) { - this.textRegion.Dispose(); - this.textRegion = null; + textRegion.Dispose(); + textRegion = null; } // bail early for no text @@ -754,7 +754,7 @@ private void EnsureRun(Graphics g) } Debug.Assert(regionIndex == (textRegions.Length - 1), "Failed to consume all link label visual regions"); - this.textRegion = textRegions[textRegions.Length - 1]; + textRegion = textRegions[textRegions.Length - 1]; } else { @@ -777,7 +777,7 @@ private void EnsureRun(Graphics g) wg.TextPadding = TextPaddingOptions.LeftAndRightPadding; } - using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(this.Font)) + using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(Font)) { IntNativeMethods.DRAWTEXTPARAMS dtParams = wg.GetTextMargins(wf); @@ -791,16 +791,16 @@ private void EnsureRun(Graphics g) clientRectWithPadding.Y, textSize.Width - iRightMargin - iLeftMargin, textSize.Height); - visualRectangle = CalcTextRenderBounds(visualRectangle /*textRect*/, clientRectWithPadding /*clientRect*/, RtlTranslateContent(this.TextAlign)); + visualRectangle = CalcTextRenderBounds(visualRectangle /*textRect*/, clientRectWithPadding /*clientRect*/, RtlTranslateContent(TextAlign)); // Region visualRegion = new Region(visualRectangle); - if (this.links != null && this.links.Count == 1) + if (links != null && links.Count == 1) { - this.Links[0].VisualRegion = visualRegion; + Links[0].VisualRegion = visualRegion; } - this.textRegion = visualRegion; + textRegion = visualRegion; } } finally @@ -1005,10 +1005,10 @@ void IButtonControl.NotifyDefault(bool value) /// protected override void OnGotFocus(EventArgs e) { - if (!this.processingOnGotFocus) + if (!processingOnGotFocus) { base.OnGotFocus(e); - this.processingOnGotFocus = true; + processingOnGotFocus = true; } try @@ -1028,9 +1028,9 @@ protected override void OnGotFocus(EventArgs e) } finally { - if (this.processingOnGotFocus) + if (processingOnGotFocus) { - this.processingOnGotFocus = false; + processingOnGotFocus = false; } } } @@ -1268,7 +1268,7 @@ protected override void OnPaint(PaintEventArgs e) RectangleF finalrect = RectangleF.Empty; //the focus rectangle if there is only one link Animate(); - ImageAnimator.UpdateFrames(this.Image); + ImageAnimator.UpdateFrames(Image); EnsureRun(e.Graphics); // bail early for no text @@ -1283,7 +1283,7 @@ protected override void OnPaint(PaintEventArgs e) { if (AutoEllipsis) { - Rectangle clientRect = this.ClientRectWithPadding; + Rectangle clientRect = ClientRectWithPadding; Size preferredSize = GetPreferredSize(new Size(clientRect.Width, clientRect.Height)); showToolTip = (clientRect.Width < preferredSize.Width || clientRect.Height < preferredSize.Height); } @@ -1292,7 +1292,7 @@ protected override void OnPaint(PaintEventArgs e) showToolTip = false; } - if (this.Enabled) + if (Enabled) { // Control.Enabled not to be confused with Link.Enabled bool optimizeBackgroundRendering = !GetStyle(ControlStyles.OptimizedDoubleBuffer); SolidBrush foreBrush = new SolidBrush(ForeColor); @@ -1305,7 +1305,7 @@ protected override void OnPaint(PaintEventArgs e) PaintLinkBackground(e.Graphics); } - LinkUtilities.EnsureLinkFonts(this.Font, this.LinkBehavior, ref this.linkFont, ref this.hoverLinkFont); + LinkUtilities.EnsureLinkFonts(Font, LinkBehavior, ref linkFont, ref hoverLinkFont); Region originalClip = e.Graphics.Clip; @@ -1328,7 +1328,7 @@ protected override void OnPaint(PaintEventArgs e) } else { - finalrect = this.ClientRectWithPadding; + finalrect = ClientRectWithPadding; Size finalRectSize = finalrect.Size.ToSize(); Size requiredSize = MeasureTextCache.GetTextSize(Text, Font, finalRectSize, CreateTextFormatFlags(finalRectSize)); @@ -1339,7 +1339,7 @@ protected override void OnPaint(PaintEventArgs e) { finalrect.Height = requiredSize.Height; } - finalrect = CalcTextRenderBounds(System.Drawing.Rectangle.Round(finalrect) /*textRect*/, this.ClientRectWithPadding /*clientRect*/, RtlTranslateContent(this.TextAlign)); + finalrect = CalcTextRenderBounds(System.Drawing.Rectangle.Round(finalrect) /*textRect*/, ClientRectWithPadding /*clientRect*/, RtlTranslateContent(TextAlign)); } using (Region region = new Region(finalrect)) { @@ -1375,7 +1375,7 @@ protected override void OnPaint(PaintEventArgs e) if (optimizeBackgroundRendering) { e.Graphics.Clip = originalClip; - e.Graphics.ExcludeClip(this.textRegion); + e.Graphics.ExcludeClip(textRegion); PaintLinkBackground(e.Graphics); } } @@ -1402,7 +1402,7 @@ protected override void OnPaint(PaintEventArgs e) // ClientRectWithPadding which in some cases is smaller that ClientRectangle. // PaintLinkBackground(e.Graphics); - e.Graphics.IntersectClip(this.textRegion); + e.Graphics.IntersectClip(textRegion); Color foreColor; @@ -1447,7 +1447,7 @@ protected override void OnPaint(PaintEventArgs e) protected override void OnPaintBackground(PaintEventArgs e) { - Image i = this.Image; + Image i = Image; if (i != null) { @@ -1662,7 +1662,7 @@ private void PaintLink(Graphics g, Link link, SolidBrush foreBrush, SolidBrush l } else { // Painting with no link. - g.IntersectClip(this.textRegion); + g.IntersectClip(textRegion); if (optimizeBackgroundRendering) { @@ -2389,15 +2389,15 @@ public int Add(Link value) } // Set the owner control for this link - value.Owner = this.owner; + value.Owner = owner; owner.links.Add(value); - if (this.owner.AutoSize) + if (owner.AutoSize) { - LayoutTransaction.DoLayout(this.owner.ParentInternal, this.owner, PropertyNames.Links); - this.owner.AdjustSize(); - this.owner.Invalidate(); + LayoutTransaction.DoLayout(owner.ParentInternal, owner, PropertyNames.Links); + owner.AdjustSize(); + owner.Invalidate(); } if (owner.Links.Count > 1) @@ -2507,7 +2507,7 @@ public virtual int IndexOfKey(string key) } // step 2 - search for the item - for (int i = 0; i < this.Count; i++) + for (int i = 0; i < Count; i++) { if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { @@ -2526,7 +2526,7 @@ public virtual int IndexOfKey(string key) /// private bool IsValidIndex(int index) { - return ((index >= 0) && (index < this.Count)); + return ((index >= 0) && (index < Count)); } @@ -2535,14 +2535,14 @@ private bool IsValidIndex(int index) /// public virtual void Clear() { - bool doLayout = this.owner.links.Count > 0 && this.owner.AutoSize; + bool doLayout = owner.links.Count > 0 && owner.AutoSize; owner.links.Clear(); if (doLayout) { - LayoutTransaction.DoLayout(this.owner.ParentInternal, this.owner, PropertyNames.Links); - this.owner.AdjustSize(); - this.owner.Invalidate(); + LayoutTransaction.DoLayout(owner.ParentInternal, owner, PropertyNames.Links); + owner.AdjustSize(); + owner.Invalidate(); } owner.UpdateSelectability(); @@ -2570,18 +2570,18 @@ public IEnumerator GetEnumerator() public void Remove(Link value) { - if (value.Owner != this.owner) + if (value.Owner != owner) { return; } owner.links.Remove(value); - if (this.owner.AutoSize) + if (owner.AutoSize) { - LayoutTransaction.DoLayout(this.owner.ParentInternal, this.owner, PropertyNames.Links); - this.owner.AdjustSize(); - this.owner.Invalidate(); + LayoutTransaction.DoLayout(owner.ParentInternal, owner, PropertyNames.Links); + owner.AdjustSize(); + owner.Invalidate(); } owner.links.Sort(LinkLabel.linkComparer); @@ -2848,7 +2848,7 @@ public override System.Windows.Forms.AccessibleObject HitTest(int x, int y) { return new LinkAccessibleObject(hit); } - if (this.Bounds.Contains(x, y)) + if (Bounds.Contains(x, y)) { return this; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs index 5733d3cf7a5..a697bc5785e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs @@ -456,7 +456,7 @@ public virtual DrawMode DrawMode { // Force a layout after RecreateHandle() completes because now // the LB is definitely fully populated and can report a preferred size accurately. - LayoutTransaction.DoLayoutIf(AutoSize, this.ParentInternal, this, PropertyNames.DrawMode); + LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.DrawMode); } } } @@ -791,7 +791,7 @@ public int PreferredHeight // added to the LB yet. Just return current height. if (RecreatingHandle || GetState(STATE_CREATINGHANDLE)) { - height = this.Height; + height = Height; } else { @@ -1397,7 +1397,7 @@ protected virtual ObjectCollection CreateItemCollection() internal virtual int ComputeMaxItemWidth(int oldMax) { // pass LayoutUtils the collection of strings - string[] strings = new string[this.Items.Count]; + string[] strings = new string[Items.Count]; for (int i = 0; i < Items.Count; i++) { @@ -1897,7 +1897,7 @@ protected override void OnParentChanged(EventArgs e) base.OnParentChanged(e); //No need to RecreateHandle if we are removing the Listbox from controls collection... //so check the parent before recreating the handle... - if (this.ParentInternal != null) + if (ParentInternal != null) { RecreateHandle(); } @@ -1910,7 +1910,7 @@ protected override void OnResize(EventArgs e) // There are some repainting issues for RightToLeft - so invalidate when we resize. // - if (RightToLeft == RightToLeft.Yes || this.HorizontalScrollbar) + if (RightToLeft == RightToLeft.Yes || HorizontalScrollbar) { Invalidate(); } @@ -1934,14 +1934,14 @@ protected override void OnSelectedIndexChanged(EventArgs e) // calls CurrencyManager::EndCurrentEdit, and that will pull the dataFrom the controls // into the backEnd. We do not need to do that. // - if (this.DataManager != null && DataManager.Position != SelectedIndex) + if (DataManager != null && DataManager.Position != SelectedIndex) { //read this as "if everett or (whidbey and selindex is valid)" - if (!FormattingEnabled || this.SelectedIndex != -1) + if (!FormattingEnabled || SelectedIndex != -1) { // Don't change dataManager position if we simply unselected everything. // (Doing so would cause the first LB item to be selected...) - this.DataManager.Position = this.SelectedIndex; + DataManager.Position = SelectedIndex; } } @@ -1980,8 +1980,8 @@ protected override void OnDisplayMemberChanged(EventArgs e) // we want to use the new DisplayMember even if there is no data source RefreshItems(); - if (SelectionMode != SelectionMode.None && this.DataManager != null) - this.SelectedIndex = this.DataManager.Position; + if (SelectionMode != SelectionMode.None && DataManager != null) + SelectedIndex = DataManager.Position; } /// @@ -2037,12 +2037,12 @@ protected override void RefreshItems() // if we have a dataSource and a DisplayMember, then use it // to populate the Items collection // - if (this.DataManager != null && this.DataManager.Count != -1) + if (DataManager != null && DataManager.Count != -1) { - newItems = new object[this.DataManager.Count]; + newItems = new object[DataManager.Count]; for (int i = 0; i < newItems.Length; i++) { - newItems[i] = this.DataManager[i]; + newItems[i] = DataManager[i]; } } else if (savedItems != null) @@ -2062,10 +2062,10 @@ protected override void RefreshItems() // if (SelectionMode != SelectionMode.None) { - if (this.DataManager != null) + if (DataManager != null) { // put the selectedIndex in sync w/ the position in the dataManager - this.SelectedIndex = this.DataManager.Position; + SelectedIndex = DataManager.Position; } else { @@ -2145,14 +2145,14 @@ protected override void SetItemsCore(IList value) Items.ClearInternal(); Items.AddRangeInternal(value); - this.SelectedItems.Dirty(); + SelectedItems.Dirty(); // if the list changed, we want to keep the same selected index // CurrencyManager will provide the PositionChanged event // it will be provided before changing the list though... - if (this.DataManager != null) + if (DataManager != null) { - if (this.DataSource is ICurrencyManagerProvider) + if (DataSource is ICurrencyManagerProvider) { // Everett ListControl's had a @@ -2160,7 +2160,7 @@ protected override void SetItemsCore(IList value) - this.selectedValueChangedFired = false; + selectedValueChangedFired = false; } if (IsHandleCreated) @@ -2317,7 +2317,7 @@ private void UpdateMaxItemWidth(object item, bool removing) int width; using (Graphics graphics = CreateGraphicsInternal()) { - width = (int)(Math.Ceiling(graphics.MeasureString(GetItemText(item), this.Font).Width)); + width = (int)(Math.Ceiling(graphics.MeasureString(GetItemText(item), Font).Width)); } if (removing) @@ -2360,11 +2360,11 @@ private void UpdateCustomTabOffsets() private void WmPrint(ref Message m) { base.WndProc(ref m); - if ((NativeMethods.PRF_NONCLIENT & (int)m.LParam) != 0 && Application.RenderWithVisualStyles && this.BorderStyle == BorderStyle.Fixed3D) + if ((NativeMethods.PRF_NONCLIENT & (int)m.LParam) != 0 && Application.RenderWithVisualStyles && BorderStyle == BorderStyle.Fixed3D) { using (Graphics g = Graphics.FromHdc(m.WParam)) { - Rectangle rect = new Rectangle(0, 0, this.Size.Width - 1, this.Size.Height - 1); + Rectangle rect = new Rectangle(0, 0, Size.Width - 1, Size.Height - 1); using (Pen pen = new Pen(VisualStyleInformation.TextControlBorder)) { g.DrawRectangle(pen, rect); @@ -2996,7 +2996,7 @@ private class Entry public Entry(object item) { this.item = item; - this.state = 0; + state = 0; } } @@ -3020,8 +3020,8 @@ public EntryEnumerator(ItemArray items, int state, bool anyBit) this.items = items; this.state = state; this.anyBit = anyBit; - this.version = items.version; - this.current = -1; + version = items.version; + current = -1; } /// @@ -3114,7 +3114,7 @@ public ObjectCollection(ListBox owner) public ObjectCollection(ListBox owner, ObjectCollection value) { this.owner = owner; - this.AddRange(value); + AddRange(value); } /// @@ -3125,7 +3125,7 @@ public ObjectCollection(ListBox owner, ObjectCollection value) public ObjectCollection(ListBox owner, object[] value) { this.owner = owner; - this.AddRange(value); + AddRange(value); } /// @@ -3542,7 +3542,7 @@ internal void SetItemInternal(int index, object value) if (owner.IsHandleCreated) { bool selected = (owner.SelectedIndex == index); - if (string.Compare(this.owner.GetItemText(value), this.owner.NativeGetItemText(index), true, CultureInfo.CurrentCulture) != 0) + if (string.Compare(owner.GetItemText(value), owner.NativeGetItemText(index), true, CultureInfo.CurrentCulture) != 0) { owner.NativeRemoveAt(index); owner.SelectedItems.SetSelected(index, false); @@ -3942,7 +3942,7 @@ private class CustomTabOffsetsEnumerator : IEnumerator public CustomTabOffsetsEnumerator(IntegerCollection items) { this.items = items; - this.current = -1; + current = -1; } /// @@ -4222,7 +4222,7 @@ private class SelectedIndexEnumerator : IEnumerator public SelectedIndexEnumerator(SelectedIndexCollection items) { this.items = items; - this.current = -1; + current = -1; } /// @@ -4285,8 +4285,8 @@ public class SelectedObjectCollection : IList public SelectedObjectCollection(ListBox owner) { this.owner = owner; - this.stateDirty = true; - this.lastVersion = -1; + stateDirty = true; + lastVersion = -1; } /// @@ -4500,7 +4500,7 @@ internal void PushSelectionIntoNativeListBox(int index) // this also takes care of the case where owner.SelectionMode == SelectionMode.One if (selected) { - this.owner.NativeSetSelected(index, true /*we signal selection to the native listBox only if the item is actually selected*/); + owner.NativeSetSelected(index, true /*we signal selection to the native listBox only if the item is actually selected*/); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListManagerBindingsCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListManagerBindingsCollection.cs index 127397343e7..7d3401c189a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListManagerBindingsCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListManagerBindingsCollection.cs @@ -22,7 +22,7 @@ internal class ListManagerBindingsCollection : BindingsCollection internal ListManagerBindingsCollection(BindingManagerBase bindingManagerBase) : base() { Debug.Assert(bindingManagerBase != null, "How could a listmanagerbindingscollection not have a bindingManagerBase associated with it!"); - this._bindingManagerBase = bindingManagerBase; + _bindingManagerBase = bindingManagerBase; } protected override void AddCore(Binding dataBinding) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs index 9a181e17b38..402ee9fdf6b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs @@ -268,7 +268,7 @@ public ItemActivation Activation throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ItemActivation)); } - if (this.HotTracking && value != ItemActivation.OneClick) + if (HotTracking && value != ItemActivation.OneClick) { throw new ArgumentException(SR.ListViewActivationMustBeOnWhenHotTrackingIsOn, "value"); } @@ -445,10 +445,10 @@ public bool BackgroundImageTiled lvbkImage.ulFlags = NativeMethods.LVBKIF_STYLE_NORMAL; lvbkImage.ulFlags |= NativeMethods.LVBKIF_SOURCE_URL; - lvbkImage.pszImage = this.backgroundImageFileName; - lvbkImage.cchImageMax = this.backgroundImageFileName.Length + 1; + lvbkImage.pszImage = backgroundImageFileName; + lvbkImage.cchImageMax = backgroundImageFileName.Length + 1; - UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_SETBKIMAGE, 0, lvbkImage); + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SETBKIMAGE, 0, lvbkImage); } } } @@ -504,12 +504,12 @@ public bool CheckBoxes set { - if (this.UseCompatibleStateImageBehavior) + if (UseCompatibleStateImageBehavior) { if (CheckBoxes != value) { - if (value && this.View == View.Tile) + if (value && View == View.Tile) { throw new NotSupportedException(SR.ListViewCheckBoxesNotSupportedInTileView); } @@ -554,7 +554,7 @@ public bool CheckBoxes if (CheckBoxes != value) { - if (value && this.View == View.Tile) + if (value && View == View.Tile) { throw new NotSupportedException(SR.ListViewCheckBoxesNotSupportedInTileView); } @@ -574,10 +574,10 @@ public bool CheckBoxes listViewState[LISTVIEWSTATE_checkBoxes] = value; - if ((!value && this.StateImageList != null && this.IsHandleCreated) || - (!value && this.Alignment == ListViewAlignment.Left && this.IsHandleCreated) || - (value && this.View == View.List && this.IsHandleCreated) || - (value && (this.View == View.SmallIcon || this.View == View.LargeIcon) && this.IsHandleCreated)) + if ((!value && StateImageList != null && IsHandleCreated) || + (!value && Alignment == ListViewAlignment.Left && IsHandleCreated) || + (value && View == View.List && IsHandleCreated) || + (value && (View == View.SmallIcon || View == View.LargeIcon) && IsHandleCreated)) { // we have to recreate the handle when we are going from CheckBoxes == true to CheckBoxes == false // if we want to have the bitmaps from the StateImageList on the items. @@ -843,7 +843,7 @@ protected override bool DoubleBuffered } set { - if (this.DoubleBuffered != value) + if (DoubleBuffered != value) { base.DoubleBuffered = value; UpdateExtendedStyles(); @@ -855,7 +855,7 @@ internal bool ExpectingMouseUp { get { - return this.listViewState[LISTVIEWSTATE_expectingMouseUp]; + return listViewState[LISTVIEWSTATE_expectingMouseUp]; } } @@ -919,18 +919,18 @@ private bool FlipViewToLargeIconAndSmallIcon get { // it never hurts to check that our house is in order - Debug.Assert(!this.listViewState[LISTVIEWSTATE_flipViewToLargeIconAndSmallIcon] || this.View == View.SmallIcon, "we need this bit only in SmallIcon view"); - Debug.Assert(!this.listViewState[LISTVIEWSTATE_flipViewToLargeIconAndSmallIcon] || this.ComctlSupportsVisualStyles, "we need this bit only when loading ComCtl 6.0"); + Debug.Assert(!listViewState[LISTVIEWSTATE_flipViewToLargeIconAndSmallIcon] || View == View.SmallIcon, "we need this bit only in SmallIcon view"); + Debug.Assert(!listViewState[LISTVIEWSTATE_flipViewToLargeIconAndSmallIcon] || ComctlSupportsVisualStyles, "we need this bit only when loading ComCtl 6.0"); - return this.listViewState[LISTVIEWSTATE_flipViewToLargeIconAndSmallIcon]; + return listViewState[LISTVIEWSTATE_flipViewToLargeIconAndSmallIcon]; } set { // it never hurts to check that our house is in order - Debug.Assert(!value || this.View == View.SmallIcon, "we need this bit only in SmallIcon view"); - Debug.Assert(!value || this.ComctlSupportsVisualStyles, "we need this bit only when loading ComCtl 6.0"); + Debug.Assert(!value || View == View.SmallIcon, "we need this bit only in SmallIcon view"); + Debug.Assert(!value || ComctlSupportsVisualStyles, "we need this bit only when loading ComCtl 6.0"); - this.listViewState[LISTVIEWSTATE_flipViewToLargeIconAndSmallIcon] = value; + listViewState[LISTVIEWSTATE_flipViewToLargeIconAndSmallIcon] = value; } } @@ -1015,7 +1015,7 @@ internal bool GroupsEnabled { get { - return this.ShowGroups && groups != null && groups.Count > 0 && ComctlSupportsVisualStyles && !VirtualMode; + return ShowGroups && groups != null && groups.Count > 0 && ComctlSupportsVisualStyles && !VirtualMode; } } @@ -1104,8 +1104,8 @@ public bool HotTracking listViewState[LISTVIEWSTATE_hotTracking] = value; if (value) { - this.HoverSelection = true; - this.Activation = ItemActivation.OneClick; + HoverSelection = true; + Activation = ItemActivation.OneClick; } UpdateExtendedStyles(); } @@ -1146,7 +1146,7 @@ internal bool InsertingItemsNatively { get { - return this.listViewState1[LISTVIEWSTATE1_insertingItemsNatively]; + return listViewState1[LISTVIEWSTATE1_insertingItemsNatively]; } } @@ -1171,11 +1171,11 @@ private bool ItemCollectionChangedInMouseDown { get { - return this.listViewState[LISTVIEWSTATE_itemCollectionChangedInMouseDown]; + return listViewState[LISTVIEWSTATE_itemCollectionChangedInMouseDown]; } set { - this.listViewState[LISTVIEWSTATE_itemCollectionChangedInMouseDown] = value; + listViewState[LISTVIEWSTATE_itemCollectionChangedInMouseDown] = value; } } @@ -1332,7 +1332,7 @@ public IComparer ListViewItemSorter { listItemSorter = value; - if (!this.VirtualMode) + if (!VirtualMode) { Sort(); } @@ -1504,13 +1504,13 @@ public bool ShowGroups { get { - return this.listViewState[LISTVIEWSTATE_showGroups]; + return listViewState[LISTVIEWSTATE_showGroups]; } set { - if (value != this.ShowGroups) + if (value != ShowGroups) { - this.listViewState[LISTVIEWSTATE_showGroups] = value; + listViewState[LISTVIEWSTATE_showGroups] = value; if (IsHandleCreated) { UpdateGroupView(); @@ -1558,19 +1558,19 @@ public ImageList SmallImageList SendMessage(NativeMethods.LVM_SETIMAGELIST, (IntPtr)NativeMethods.LVSIL_SMALL, value == null ? IntPtr.Zero : value.Handle); - if (this.View == View.SmallIcon) + if (View == View.SmallIcon) { - this.View = View.LargeIcon; - this.View = View.SmallIcon; + View = View.LargeIcon; + View = View.SmallIcon; } else if (!listViewState1[LISTVIEWSTATE1_disposingImageLists]) { UpdateListViewItemsLocations(); } - if (this.View == View.Details) + if (View == View.Details) { - this.Invalidate(true /*invalidateChildren*/); + Invalidate(true /*invalidateChildren*/); } } } @@ -1619,7 +1619,7 @@ public SortOrder Sorting if (sorting != value) { sorting = value; - if (this.View == View.LargeIcon || this.View == View.SmallIcon) + if (View == View.LargeIcon || View == View.SmallIcon) { if (listItemSorter == null) { @@ -1659,7 +1659,7 @@ public ImageList StateImageList } set { - if (this.UseCompatibleStateImageBehavior) + if (UseCompatibleStateImageBehavior) { if (imageListState != value) { @@ -1697,7 +1697,7 @@ public ImageList StateImageList imageListState.Disposed -= disposedHandler; } - if (this.IsHandleCreated && imageListState != null && this.CheckBoxes) + if (IsHandleCreated && imageListState != null && CheckBoxes) { // // If CheckBoxes are set to true, then we will have to recreate the handle. @@ -1770,13 +1770,13 @@ public Size TileSize { if (tileSize.IsEmpty) { - if (this.IsHandleCreated) + if (IsHandleCreated) { // Get the default value from the ListView // NativeMethods.LVTILEVIEWINFO tileViewInfo = new NativeMethods.LVTILEVIEWINFO(); tileViewInfo.dwMask = NativeMethods.LVTVIM_TILESIZE; - UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_GETTILEVIEWINFO, 0, tileViewInfo); + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_GETTILEVIEWINFO, 0, tileViewInfo); return new Size(tileViewInfo.sizeTile.cx, tileViewInfo.sizeTile.cy); } else @@ -1799,17 +1799,17 @@ public Size TileSize } tileSize = value; - if (this.IsHandleCreated) + if (IsHandleCreated) { NativeMethods.LVTILEVIEWINFO tileViewInfo = new NativeMethods.LVTILEVIEWINFO(); tileViewInfo.dwMask = NativeMethods.LVTVIM_TILESIZE; tileViewInfo.dwFlags = NativeMethods.LVTVIF_FIXEDSIZE; tileViewInfo.sizeTile = new NativeMethods.SIZE(tileSize.Width, tileSize.Height); - bool retval = UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_SETTILEVIEWINFO, 0, tileViewInfo); + bool retval = UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SETTILEVIEWINFO, 0, tileViewInfo); Debug.Assert(retval, "LVM_SETTILEVIEWINFO failed"); - if (this.AutoArrange) + if (AutoArrange) { - this.UpdateListViewItemsLocations(); + UpdateListViewItemsLocations(); } } } @@ -1818,7 +1818,7 @@ public Size TileSize private bool ShouldSerializeTileSize() { - return !this.tileSize.Equals(Size.Empty); + return !tileSize.Equals(Size.Empty); } [ @@ -1896,11 +1896,11 @@ public bool UseCompatibleStateImageBehavior { get { - return this.listViewState1[LISTVIEWSTATE1_useCompatibleStateImageBehavior]; + return listViewState1[LISTVIEWSTATE1_useCompatibleStateImageBehavior]; } set { - this.listViewState1[LISTVIEWSTATE1_useCompatibleStateImageBehavior] = value; + listViewState1[LISTVIEWSTATE1_useCompatibleStateImageBehavior] = value; } } @@ -1917,12 +1917,12 @@ public View View } set { - if (value == View.Tile && this.CheckBoxes) + if (value == View.Tile && CheckBoxes) { throw new NotSupportedException(SR.ListViewTileViewDoesNotSupportCheckBoxes); } - this.FlipViewToLargeIconAndSmallIcon = false; + FlipViewToLargeIconAndSmallIcon = false; //valid values are 0x0 to 0x4 if (!ClientUtils.IsEnumValid(value, (int)value, (int)View.LargeIcon, (int)View.Tile)) @@ -1969,7 +1969,7 @@ public int VirtualListSize { get { - return this.virtualListSize; + return virtualListSize; } set { @@ -1977,7 +1977,7 @@ public int VirtualListSize throw new System.ArgumentException(string.Format(SR.ListViewVirtualListSizeInvalidArgument, "value", (value))); if (value == virtualListSize) return; - bool keepTopItem = this.IsHandleCreated && VirtualMode && this.View == View.Details && !this.DesignMode; + bool keepTopItem = IsHandleCreated && VirtualMode && View == View.Details && !DesignMode; int topIndex = -1; if (keepTopItem) { @@ -1991,13 +1991,13 @@ public int VirtualListSize if (keepTopItem) { - topIndex = Math.Min(topIndex, this.VirtualListSize - 1); + topIndex = Math.Min(topIndex, VirtualListSize - 1); // After setting the virtual list size ComCtl makes the first item the top item. // So we set the top item only if it wasn't the first item to begin with. if (topIndex > 0) { - ListViewItem lvItem = this.Items[topIndex]; - this.TopItem = lvItem; + ListViewItem lvItem = Items[topIndex]; + TopItem = lvItem; } } } @@ -2281,7 +2281,7 @@ public void ArrangeIcons(ListViewAlignment value) case NativeMethods.LVA_SNAPTOGRID: if (IsHandleCreated) { - UnsafeNativeMethods.PostMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_ARRANGE, (int)value, 0); + UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), NativeMethods.LVM_ARRANGE, (int)value, 0); } break; @@ -2307,18 +2307,18 @@ public void ArrangeIcons() public void AutoResizeColumns(ColumnHeaderAutoResizeStyle headerAutoResize) { - if (!this.IsHandleCreated) + if (!IsHandleCreated) { - this.CreateHandle(); + CreateHandle(); } UpdateColumnWidths(headerAutoResize); } public void AutoResizeColumn(int columnIndex, ColumnHeaderAutoResizeStyle headerAutoResize) { - if (!this.IsHandleCreated) + if (!IsHandleCreated) { - this.CreateHandle(); + CreateHandle(); } SetColumnWidth(columnIndex, headerAutoResize); } @@ -2346,20 +2346,20 @@ internal void CacheSelectedStateForItem(ListViewItem lvi, bool selected) { if (selected) { - if (this.savedSelectedItems == null) + if (savedSelectedItems == null) { - this.savedSelectedItems = new List(); + savedSelectedItems = new List(); } - if (!this.savedSelectedItems.Contains(lvi)) + if (!savedSelectedItems.Contains(lvi)) { - this.savedSelectedItems.Add(lvi); + savedSelectedItems.Add(lvi); } } else { - if (this.savedSelectedItems != null && this.savedSelectedItems.Contains(lvi)) + if (savedSelectedItems != null && savedSelectedItems.Contains(lvi)) { - this.savedSelectedItems.Remove(lvi); + savedSelectedItems.Remove(lvi); } } } @@ -2371,27 +2371,27 @@ private void CheckDisplayIndices() // all the column headers should have a displayIndex between 0 and this.Columns.Count - 1; // DisplayIndex should be different for different column headers int sumOfDisplayIndices = 0; - for (int i = 0; i < this.Columns.Count; i++) + for (int i = 0; i < Columns.Count; i++) { - sumOfDisplayIndices += this.Columns[i].DisplayIndex; - Debug.Assert(this.Columns[i].DisplayIndex > -1 && this.Columns[i].DisplayIndex < this.Columns.Count, "display indices out of whack"); + sumOfDisplayIndices += Columns[i].DisplayIndex; + Debug.Assert(Columns[i].DisplayIndex > -1 && Columns[i].DisplayIndex < Columns.Count, "display indices out of whack"); } - int colsCount = this.Columns.Count; + int colsCount = Columns.Count; Debug.Assert(sumOfDisplayIndices == (colsCount - 1) * colsCount / 2, "display indices out of whack"); } #endif private void CleanPreviousBackgroundImageFiles() { - if (this.bkImgFileNames == null) + if (bkImgFileNames == null) { return; } System.IO.FileInfo fi; - for (int i = 0; i <= this.bkImgFileNamesCount; i++) + for (int i = 0; i <= bkImgFileNamesCount; i++) { - fi = new System.IO.FileInfo(this.bkImgFileNames[i]); + fi = new System.IO.FileInfo(bkImgFileNames[i]); if (fi.Exists) { // @@ -2407,8 +2407,8 @@ private void CleanPreviousBackgroundImageFiles() } } - this.bkImgFileNames = null; - this.bkImgFileNamesCount = -1; + bkImgFileNames = null; + bkImgFileNamesCount = -1; } /// @@ -2439,10 +2439,10 @@ private int CompareFunc(IntPtr lparam1, IntPtr lparam2, IntPtr lparamSort) private int CompensateColumnHeaderResize(Message m, bool columnResizeCancelled) { - if (this.ComctlSupportsVisualStyles && - this.View == View.Details && + if (ComctlSupportsVisualStyles && + View == View.Details && !columnResizeCancelled && - this.Items.Count > 0) + Items.Count > 0) { NativeMethods.NMHEADER header = (NativeMethods.NMHEADER)m.GetLParam(typeof(NativeMethods.NMHEADER)); @@ -2466,18 +2466,18 @@ private int CompensateColumnHeaderResize(int columnIndex, bool columnResizeCance // 2. Otherwise, we need to add 18 pixels. // If the list view does not have a small image list then we need to add 2 pixels. - if (this.ComctlSupportsVisualStyles && - this.View == View.Details && + if (ComctlSupportsVisualStyles && + View == View.Details && !columnResizeCancelled && - this.Items.Count > 0) + Items.Count > 0) { // The user resized the first column. if (columnIndex == 0) { - ColumnHeader col = (this.columnHeaders != null && this.columnHeaders.Length > 0) ? this.columnHeaders[0] : null; + ColumnHeader col = (columnHeaders != null && columnHeaders.Length > 0) ? columnHeaders[0] : null; if (col != null) { - if (this.SmallImageList == null) + if (SmallImageList == null) { return 2; } @@ -2486,9 +2486,9 @@ private int CompensateColumnHeaderResize(int columnIndex, bool columnResizeCance // If the list view contains an item w/ a non-negative ImageIndex then we don't need to // add extra padding. bool addPadding = true; - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { - if (this.Items[i].ImageIndexer.ActualIndex > -1) + if (Items[i].ImageIndexer.ActualIndex > -1) { addPadding = false; break; @@ -2532,7 +2532,7 @@ protected override void CreateHandle() base.CreateHandle(); // image location - if (this.BackgroundImage != null) + if (BackgroundImage != null) SetBackgroundImage(); } @@ -2567,10 +2567,10 @@ unsafe void CustomDraw(ref Message m) // We want custom draw for this paint cycle m.Result = (IntPtr)(NativeMethods.CDRF_NOTIFYSUBITEMDRAW | NativeMethods.CDRF_NEWFONT); // refresh the cache of the current color & font settings for this paint cycle - odCacheBackColor = this.BackColor; - odCacheForeColor = this.ForeColor; - odCacheFont = this.Font; - odCacheFontHandle = this.FontHandle; + odCacheBackColor = BackColor; + odCacheForeColor = ForeColor; + odCacheFont = Font; + odCacheFontHandle = FontHandle; // If preparing to paint a group item, make sure its bolded. if (nmcd->dwItemType == NativeMethods.LVCDI_GROUP) @@ -2711,10 +2711,10 @@ unsafe void CustomDraw(ref Message m) if (nmcd->iSubItem == 0 && Items[itemIndex].SubItems.Count > 1) { // Use the width for the first column header. - subItemBounds.Width = this.columnHeaders[0].Width; + subItemBounds.Width = columnHeaders[0].Width; } - if (this.ClientRectangle.IntersectsWith(subItemBounds)) + if (ClientRectangle.IntersectsWith(subItemBounds)) { e = new DrawListViewSubItemEventArgs(g, subItemBounds, @@ -3015,17 +3015,17 @@ protected override void Dispose(bool disposing) // Remove any event sinks we have hooked up to imageLists if (imageListSmall != null) { - imageListSmall.Disposed -= new EventHandler(this.DetachImageList); + imageListSmall.Disposed -= new EventHandler(DetachImageList); imageListSmall = null; } if (imageListLarge != null) { - imageListLarge.Disposed -= new EventHandler(this.DetachImageList); + imageListLarge.Disposed -= new EventHandler(DetachImageList); imageListLarge = null; } if (imageListState != null) { - imageListState.Disposed -= new EventHandler(this.DetachImageList); + imageListState.Disposed -= new EventHandler(DetachImageList); imageListState = null; } @@ -3049,13 +3049,13 @@ protected override void Dispose(bool disposing) odCacheFontHandleWrapper = null; } - if (!string.IsNullOrEmpty(this.backgroundImageFileName) || this.bkImgFileNames != null) + if (!string.IsNullOrEmpty(backgroundImageFileName) || bkImgFileNames != null) { System.IO.FileInfo fi; - if (!string.IsNullOrEmpty(this.backgroundImageFileName)) + if (!string.IsNullOrEmpty(backgroundImageFileName)) { - fi = new System.IO.FileInfo(this.backgroundImageFileName); + fi = new System.IO.FileInfo(backgroundImageFileName); Debug.Assert(fi.Exists, "who deleted our temp file?"); // // ComCtl ListView uses COM objects to manipulate the bitmap we send it to them. @@ -3067,11 +3067,11 @@ protected override void Dispose(bool disposing) fi.Delete(); } catch (System.IO.IOException) { } - this.backgroundImageFileName = string.Empty; + backgroundImageFileName = string.Empty; } - for (int i = 0; i <= this.bkImgFileNamesCount; i++) + for (int i = 0; i <= bkImgFileNamesCount; i++) { - fi = new System.IO.FileInfo(this.bkImgFileNames[i]); + fi = new System.IO.FileInfo(bkImgFileNames[i]); Debug.Assert(fi.Exists, "who deleted our temp file?"); // // ComCtl ListView uses COM objects to manipulate the bitmap we send it to them. @@ -3085,8 +3085,8 @@ protected override void Dispose(bool disposing) catch (System.IO.IOException) { } } - this.bkImgFileNames = null; - this.bkImgFileNamesCount = -1; + bkImgFileNames = null; + bkImgFileNamesCount = -1; } } @@ -3141,7 +3141,7 @@ public void EnsureVisible(int index) public ListViewItem FindItemWithText(string text) { // if the user does not use the FindItemWithText overloads that specify a StartIndex and the listView is empty then return null - if (this.Items.Count == 0) + if (Items.Count == 0) { return null; } @@ -3160,7 +3160,7 @@ public ListViewItem FindItemWithText(string text, bool includeSubItemsInSearch, /// public ListViewItem FindItemWithText(string text, bool includeSubItemsInSearch, int startIndex, bool isPrefixSearch) { - if (startIndex < 0 || startIndex >= this.Items.Count) + if (startIndex < 0 || startIndex >= Items.Count) { throw new ArgumentOutOfRangeException(nameof(startIndex), startIndex, string.Format(SR.InvalidArgument, nameof(startIndex), startIndex)); } @@ -3178,7 +3178,7 @@ public ListViewItem FindNearestItem(SearchDirectionHint dir, Point point) /// public ListViewItem FindNearestItem(SearchDirectionHint searchDirection, int x, int y) { - if (this.View != View.SmallIcon && this.View != View.LargeIcon) + if (View != View.SmallIcon && View != View.LargeIcon) { throw new InvalidOperationException(SR.ListViewFindNearestItemWorksOnlyInIconView); } @@ -3192,7 +3192,7 @@ public ListViewItem FindNearestItem(SearchDirectionHint searchDirection, int x, // simply passing the (x,y) coordinates will cause problems when we call FindNearestItem for a point inside an item. // so we have to do some special processing when (x,y) falls inside an item; // - ListViewItem lvi = this.GetItemAt(x, y); + ListViewItem lvi = GetItemAt(x, y); if (lvi != null) { @@ -3202,7 +3202,7 @@ public ListViewItem FindNearestItem(SearchDirectionHint searchDirection, int x, // What happens if there is no icon for this item? then the top left corner of the icon rectangle falls INSIDE the item label (???) // - Rectangle iconBounds = this.GetItemRect(lvi.Index, ItemBoundsPortion.Icon); + Rectangle iconBounds = GetItemRect(lvi.Index, ItemBoundsPortion.Icon); switch (searchDirection) { @@ -3229,7 +3229,7 @@ public ListViewItem FindNearestItem(SearchDirectionHint searchDirection, int x, private ListViewItem FindItem(bool isTextSearch, string text, bool isPrefixSearch, Point pt, SearchDirectionHint dir, int startIndex, bool includeSubItemsInSearch) { - if (this.Items.Count == 0) + if (Items.Count == 0) { return null; } @@ -3244,7 +3244,7 @@ private ListViewItem FindItem(bool isTextSearch, string text, bool isPrefixSearc // NOTE: this will cause a RetrieveVirtualItem event w/o a corresponding cache hint event. if (sviEvent.Index != -1) { - return this.Items[sviEvent.Index]; + return Items[sviEvent.Index]; } else { @@ -3269,7 +3269,7 @@ private ListViewItem FindItem(bool isTextSearch, string text, bool isPrefixSearc lvFindInfo.vkDirection = (int)dir; } lvFindInfo.lParam = IntPtr.Zero; - int index = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), + int index = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_FINDITEM, startIndex - 1, // decrement startIndex so that the search is 0-based ref lvFindInfo); @@ -3280,9 +3280,9 @@ private ListViewItem FindItem(bool isTextSearch, string text, bool isPrefixSearc else if (isTextSearch && includeSubItemsInSearch) { // win32 listView control can't search inside sub items - for (int i = startIndex; i < this.Items.Count; i++) + for (int i = startIndex; i < Items.Count; i++) { - ListViewItem lvi = this.Items[i]; + ListViewItem lvi = Items[i]; for (int j = 0; j < lvi.SubItems.Count; j++) { ListViewItem.ListViewSubItem lvsi = lvi.SubItems[j]; @@ -3330,8 +3330,8 @@ private void ForceCheckBoxUpdate() private string GenerateRandomName() { - Debug.Assert(this.BackgroundImage != null, "we need to generate random numbers only when saving the background image to disk"); - Bitmap bm = new Bitmap(this.BackgroundImage); + Debug.Assert(BackgroundImage != null, "we need to generate random numbers only when saving the background image to disk"); + Bitmap bm = new Bitmap(BackgroundImage); int handle = 0; try @@ -3512,7 +3512,7 @@ internal int GetItemState(int index) internal int GetItemState(int index, int mask) { - if (index < 0 || ((this.VirtualMode && index >= this.VirtualListSize) || (!this.VirtualMode && index >= itemCount))) + if (index < 0 || ((VirtualMode && index >= VirtualListSize) || (!VirtualMode && index >= itemCount))) { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } @@ -3534,7 +3534,7 @@ public Rectangle GetItemRect(int index) /// public Rectangle GetItemRect(int index, ItemBoundsPortion portion) { - if (index < 0 || index >= this.Items.Count) + if (index < 0 || index >= Items.Count) { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } @@ -3544,7 +3544,7 @@ public Rectangle GetItemRect(int index, ItemBoundsPortion portion) throw new InvalidEnumArgumentException(nameof(portion), (int)portion, typeof(ItemBoundsPortion)); } - if (this.View == View.Details && this.Columns.Count == 0) + if (View == View.Details && Columns.Count == 0) { return Rectangle.Empty; } @@ -3564,10 +3564,10 @@ public Rectangle GetItemRect(int index, ItemBoundsPortion portion) /// private Rectangle GetItemRectOrEmpty(int index) { - if (index < 0 || index >= this.Items.Count) + if (index < 0 || index >= Items.Count) return Rectangle.Empty; - if (this.View == View.Details && this.Columns.Count == 0) + if (View == View.Details && Columns.Count == 0) { return Rectangle.Empty; } @@ -3624,11 +3624,11 @@ internal Rectangle GetSubItemRect(int itemIndex, int subItemIndex) internal Rectangle GetSubItemRect(int itemIndex, int subItemIndex, ItemBoundsPortion portion) { // it seems that getting the rectangle for a sub item only works for list view which are in Details view - if (this.View != View.Details) + if (View != View.Details) { return Rectangle.Empty; } - if (itemIndex < 0 || itemIndex >= this.Items.Count) + if (itemIndex < 0 || itemIndex >= Items.Count) { throw new ArgumentOutOfRangeException(nameof(itemIndex), itemIndex, string.Format(SR.InvalidArgument, nameof(itemIndex), itemIndex)); } @@ -3644,7 +3644,7 @@ internal Rectangle GetSubItemRect(int itemIndex, int subItemIndex, ItemBoundsPor throw new InvalidEnumArgumentException(nameof(portion), (int)portion, typeof(ItemBoundsPortion)); } - if (this.Columns.Count == 0) + if (Columns.Count == 0) { return Rectangle.Empty; } @@ -3671,7 +3671,7 @@ public ListViewHitTestInfo HitTest(Point point) /// public ListViewHitTestInfo HitTest(int x, int y) { - if (!this.ClientRectangle.Contains(x, y)) + if (!ClientRectangle.Contains(x, y)) { return new ListViewHitTestInfo(null /*hitItem*/, null /*hitSubItem*/, ListViewHitTestLocations.None /*hitLocation*/); } @@ -3682,13 +3682,13 @@ public ListViewHitTestInfo HitTest(int x, int y) int iItem; - if (this.View == View.Details) + if (View == View.Details) { - iItem = unchecked((int)(long)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_SUBITEMHITTEST, 0, lvhi)); + iItem = unchecked((int)(long)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SUBITEMHITTEST, 0, lvhi)); } else { - iItem = unchecked((int)(long)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_HITTEST, 0, lvhi)); + iItem = unchecked((int)(long)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_HITTEST, 0, lvhi)); } ListViewItem item = (iItem == -1) ? null : Items[iItem]; @@ -3707,7 +3707,7 @@ public ListViewHitTestInfo HitTest(int x, int y) location = (ListViewHitTestLocations)lvhi.flags; } - if (this.View == View.Details && item != null) + if (View == View.Details && item != null) { if (lvhi.iSubItem < item.SubItems.Count) { @@ -3757,7 +3757,7 @@ internal ColumnHeader InsertColumn(int index, ColumnHeader ch, bool refreshSubIt int idx; // in Tile view the ColumnHeaders collection is used for the Tile Information // recreate the handle in that case - if (IsHandleCreated && this.View != View.Tile) + if (IsHandleCreated && View != View.Tile) { idx = InsertColumnNative(index, ch); } @@ -3792,7 +3792,7 @@ internal ColumnHeader InsertColumn(int index, ColumnHeader ch, bool refreshSubIt // in Tile view the ColumnHeaders collection is used for the Tile Information // recreate the handle in that case - if (ch.ActualImageIndex_Internal != -1 && this.IsHandleCreated && this.View != View.Tile) + if (ch.ActualImageIndex_Internal != -1 && IsHandleCreated && View != View.Tile) { SetColumnInfo(NativeMethods.LVCF_IMAGE, ch); } @@ -3800,10 +3800,10 @@ internal ColumnHeader InsertColumn(int index, ColumnHeader ch, bool refreshSubIt // update the DisplayIndex for each column // we are only setting an integer in the ColumnHeader, this is not expensive - int[] indices = new int[this.Columns.Count]; - for (int i = 0; i < this.Columns.Count; i++) + int[] indices = new int[Columns.Count]; + for (int i = 0; i < Columns.Count; i++) { - ColumnHeader hdr = this.Columns[i]; + ColumnHeader hdr = Columns[i]; if (hdr == ch) { // the newly added column @@ -3823,9 +3823,9 @@ internal ColumnHeader InsertColumn(int index, ColumnHeader ch, bool refreshSubIt #endif // in Tile view the ColumnHeaders collection is used for the Tile Information // recreate the handle in that case - if (this.IsHandleCreated && this.View == View.Tile) + if (IsHandleCreated && View == View.Tile) { - this.RecreateHandleInternal(); + RecreateHandleInternal(); } else if (IsHandleCreated && refreshSubItems) RealizeAllSubItems(); @@ -3855,11 +3855,11 @@ private int InsertColumnNative(int index, ColumnHeader ch) // in the list view are parented by a group - be it the DefaultGroup or some other group internal void InsertGroupInListView(int index, ListViewGroup group) { - Debug.Assert(this.groups != null && this.groups.Count > 0, "this method should be used only when the user adds a group, not when we add our own DefaultGroup"); - Debug.Assert(group != this.DefaultGroup, "this method should be used only when the user adds a group, not when we add our own DefaultGroup"); + Debug.Assert(groups != null && groups.Count > 0, "this method should be used only when the user adds a group, not when we add our own DefaultGroup"); + Debug.Assert(group != DefaultGroup, "this method should be used only when the user adds a group, not when we add our own DefaultGroup"); // the first time we add a group we have to group the items in the Default Group - bool groupItems = (this.groups.Count == 1) && this.GroupsEnabled; + bool groupItems = (groups.Count == 1) && GroupsEnabled; UpdateGroupView(); EnsureDefaultGroup(); @@ -3869,9 +3869,9 @@ internal void InsertGroupInListView(int index, ListViewGroup group) // if (groupItems) { - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { - ListViewItem item = this.Items[i]; + ListViewItem item = Items[i]; if (item.Group == null) { item.UpdateStateToListView(item.Index); @@ -3881,15 +3881,15 @@ internal void InsertGroupInListView(int index, ListViewGroup group) #if DEBUG // sanity check: all the items in the list view should have a group ID - if (this.GroupsEnabled) + if (GroupsEnabled) { - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { - ListViewItem item = this.Items[i]; + ListViewItem item = Items[i]; NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM(); lvItem.iItem = item.Index; lvItem.mask = NativeMethods.LVIF_GROUPID; - UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_GETITEM, 0, ref lvItem); + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_GETITEM, 0, ref lvItem); Debug.Assert(lvItem.iGroupId != -1, "there is a list view item which is not parented"); } } @@ -3900,13 +3900,13 @@ internal void InsertGroupInListView(int index, ListViewGroup group) private void InsertGroupNative(int index, ListViewGroup group) { Debug.Assert(IsHandleCreated, "InsertGroupNative precondition: list-view handle must be created"); - Debug.Assert(group == DefaultGroup || this.Groups.Contains(group), "Make sure ListView.Groups contains this group before adding the native LVGROUP. Otherwise, custom-drawing may break."); + Debug.Assert(group == DefaultGroup || Groups.Contains(group), "Make sure ListView.Groups contains this group before adding the native LVGROUP. Otherwise, custom-drawing may break."); NativeMethods.LVGROUP lvgroup = new NativeMethods.LVGROUP(); try { lvgroup = GetLVGROUP(group); - int retval = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_INSERTGROUP, index, lvgroup); + int retval = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_INSERTGROUP, index, lvgroup); Debug.Assert(retval != -1, "Failed to insert group"); } finally @@ -3928,9 +3928,9 @@ private void InsertItems(int displayIndex, ListViewItem[] items, bool checkHosti return; } - if (this.IsHandleCreated && this.Items.Count == 0 && this.View == View.SmallIcon && this.ComctlSupportsVisualStyles) + if (IsHandleCreated && Items.Count == 0 && View == View.SmallIcon && ComctlSupportsVisualStyles) { - this.FlipViewToLargeIconAndSmallIcon = true; + FlipViewToLargeIconAndSmallIcon = true; } // if we're in the middle of a Begin/EndUpdate, just push the items into our array list @@ -3964,7 +3964,7 @@ private void InsertItems(int displayIndex, ListViewItem[] items, bool checkHosti items[i].Host(this, GenerateUniqueID(), -1); } - this.FlipViewToLargeIconAndSmallIcon = false; + FlipViewToLargeIconAndSmallIcon = false; return; } @@ -4018,7 +4018,7 @@ private void InsertItems(int displayIndex, ListViewItem[] items, bool checkHosti Sort(); } - Debug.Assert(!this.FlipViewToLargeIconAndSmallIcon, "if we added even 1 item then we should have been done w/ FlipViewToLargeIconAndSmallIcon"); + Debug.Assert(!FlipViewToLargeIconAndSmallIcon, "if we added even 1 item then we should have been done w/ FlipViewToLargeIconAndSmallIcon"); } @@ -4048,7 +4048,7 @@ private int InsertItemsNative(int index, ListViewItem[] items) int actualIndex = -1; IntPtr hGlobalColumns = IntPtr.Zero; int maxColumns = 0; - this.listViewState1[LISTVIEWSTATE1_insertingItemsNatively] = true; + listViewState1[LISTVIEWSTATE1_insertingItemsNatively] = true; try { @@ -4062,7 +4062,7 @@ private int InsertItemsNative(int index, ListViewItem[] items) { ListViewItem li = items[i]; - Debug.Assert(this.Items.Contains(li), "Make sure ListView.Items contains this item before adding the native LVITEM. Otherwise, custom-drawing may break."); + Debug.Assert(Items.Contains(li), "Make sure ListView.Items contains this item before adding the native LVITEM. Otherwise, custom-drawing may break."); lvItem.Reset(); lvItem.mask = NativeMethods.LVIF_TEXT | NativeMethods.LVIF_IMAGE | NativeMethods.LVIF_PARAM | NativeMethods.LVIF_INDENT; @@ -4084,7 +4084,7 @@ private int InsertItemsNative(int index, ListViewItem[] items) } lvItem.mask |= NativeMethods.LVIF_COLUMNS; - lvItem.cColumns = this.columnHeaders != null ? Math.Min(MAXTILECOLUMNS, this.columnHeaders.Length) : 0; + lvItem.cColumns = columnHeaders != null ? Math.Min(MAXTILECOLUMNS, columnHeaders.Length) : 0; // make sure that our columns memory is big enough. // if not, then realloc it. @@ -4167,22 +4167,22 @@ private int InsertItemsNative(int index, ListViewItem[] items) { Marshal.FreeHGlobal(hGlobalColumns); } - this.listViewState1[LISTVIEWSTATE1_insertingItemsNatively] = false; + listViewState1[LISTVIEWSTATE1_insertingItemsNatively] = false; } - if (this.listViewState1[LISTVIEWSTATE1_selectedIndexChangedSkipped]) + if (listViewState1[LISTVIEWSTATE1_selectedIndexChangedSkipped]) { // SelectedIndexChanged event was delayed - this.listViewState1[LISTVIEWSTATE1_selectedIndexChangedSkipped] = false; + listViewState1[LISTVIEWSTATE1_selectedIndexChangedSkipped] = false; OnSelectedIndexChanged(EventArgs.Empty); } - if (this.FlipViewToLargeIconAndSmallIcon) + if (FlipViewToLargeIconAndSmallIcon) { - this.FlipViewToLargeIconAndSmallIcon = false; + FlipViewToLargeIconAndSmallIcon = false; - this.View = View.LargeIcon; - this.View = View.SmallIcon; + View = View.LargeIcon; + View = View.SmallIcon; } return actualIndex; @@ -4234,7 +4234,7 @@ private void LargeImageListRecreateHandle(object sender, EventArgs e) private void LargeImageListChangedHandle(object sender, EventArgs e) { - if (!this.VirtualMode && (null != sender) && (sender == imageListLarge) && IsHandleCreated) + if (!VirtualMode && (null != sender) && (sender == imageListLarge) && IsHandleCreated) { foreach (ListViewItem item in Items) { @@ -4252,7 +4252,7 @@ private void LargeImageListChangedHandle(object sender, EventArgs e) internal void ListViewItemToolTipChanged(ListViewItem item) { - if (this.IsHandleCreated) + if (IsHandleCreated) { // If we reset the item text then we also reset the tool tip text // @@ -4307,7 +4307,7 @@ protected override void OnMouseHover(EventArgs e) ListViewItem item = null; - if (this.Items.Count > 0) + if (Items.Count > 0) { // APPCOMPAT // V1.* users implement virtualization by communicating directly to the native ListView and by passing our virtualization implementation. @@ -4467,7 +4467,7 @@ protected override void OnHandleCreated(EventArgs e) listViewState[LISTVIEWSTATE_comctlSupportsVisualStylesTested] = false; // don't persist flipViewToLargeIconAndSmallIcon accross handle recreations... - this.FlipViewToLargeIconAndSmallIcon = false; + FlipViewToLargeIconAndSmallIcon = false; base.OnHandleCreated(e); @@ -4504,9 +4504,9 @@ protected override void OnHandleCreated(EventArgs e) // in VirtualMode we have to tell the list view to ask for the list view item's state image index if (VirtualMode) { - int callbackMask = unchecked((int)(long)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_GETCALLBACKMASK, 0, 0)); + int callbackMask = unchecked((int)(long)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_GETCALLBACKMASK, 0, 0)); callbackMask |= NativeMethods.LVIS_STATEIMAGEMASK; - UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_SETCALLBACKMASK, callbackMask, 0); + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SETCALLBACKMASK, callbackMask, 0); } if (ComctlSupportsVisualStyles) @@ -4589,14 +4589,14 @@ protected override void OnHandleCreated(EventArgs e) // When the handle is recreated, update the SavedCheckedItems. // It is possible some checked items were added to the list view while its handle was null. // - this.savedCheckedItems = null; - if (!this.CheckBoxes && !this.VirtualMode) + savedCheckedItems = null; + if (!CheckBoxes && !VirtualMode) { - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { - if (this.Items[i].Checked) + if (Items[i].Checked) { - this.UpdateSavedCheckedItems(this.Items[i], true /*addItem*/); + UpdateSavedCheckedItems(Items[i], true /*addItem*/); } } } @@ -4723,7 +4723,7 @@ protected override void OnParentChanged(EventArgs e) protected override void OnResize(EventArgs e) { // If the list view is in Details mode and it is not Scrollable, we need to reposition the column header control. - if (this.View == View.Details && !this.Scrollable && this.IsHandleCreated) + if (View == View.Details && !Scrollable && IsHandleCreated) { PositionHeader(); } @@ -4809,7 +4809,7 @@ protected virtual void OnVirtualItemsSelectionRangeChanged(ListViewVirtualItemsS private unsafe void PositionHeader() { - IntPtr hdrHWND = UnsafeNativeMethods.GetWindow(new HandleRef(this, this.Handle), NativeMethods.GW_CHILD); + IntPtr hdrHWND = UnsafeNativeMethods.GetWindow(new HandleRef(this, Handle), NativeMethods.GW_CHILD); if (hdrHWND != IntPtr.Zero) { @@ -4833,7 +4833,7 @@ private unsafe void PositionHeader() return; } - UnsafeNativeMethods.GetClientRect(new HandleRef(this, this.Handle), prc); + UnsafeNativeMethods.GetClientRect(new HandleRef(this, Handle), prc); NativeMethods.HDLAYOUT hd = new NativeMethods.HDLAYOUT(); hd.prc = prc; @@ -4920,24 +4920,24 @@ protected void RealizeProperties() [EditorBrowsable(EditorBrowsableState.Advanced)] public void RedrawItems(int startIndex, int endIndex, bool invalidateOnly) { - if (this.VirtualMode) + if (VirtualMode) { - if (startIndex < 0 || startIndex >= this.VirtualListSize) + if (startIndex < 0 || startIndex >= VirtualListSize) { throw new ArgumentOutOfRangeException(nameof(startIndex), startIndex, string.Format(SR.InvalidArgument, nameof(startIndex), startIndex)); } - if (endIndex < 0 || endIndex >= this.VirtualListSize) + if (endIndex < 0 || endIndex >= VirtualListSize) { throw new ArgumentOutOfRangeException(nameof(endIndex), endIndex, string.Format(SR.InvalidArgument, nameof(endIndex), endIndex)); } } else { - if (startIndex < 0 || startIndex >= this.Items.Count) + if (startIndex < 0 || startIndex >= Items.Count) { throw new ArgumentOutOfRangeException(nameof(startIndex), startIndex, string.Format(SR.InvalidArgument, nameof(startIndex), startIndex)); } - if (endIndex < 0 || endIndex >= this.Items.Count) + if (endIndex < 0 || endIndex >= Items.Count) { throw new ArgumentOutOfRangeException(nameof(endIndex), endIndex, string.Format(SR.InvalidArgument, nameof(endIndex), endIndex)); } @@ -4946,23 +4946,23 @@ public void RedrawItems(int startIndex, int endIndex, bool invalidateOnly) { throw new ArgumentException(SR.ListViewStartIndexCannotBeLargerThanEndIndex); } - if (this.IsHandleCreated) + if (IsHandleCreated) { - int retval = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), + int retval = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_REDRAWITEMS, startIndex, endIndex); Debug.Assert(retval != 0); // ListView control seems to be bogus. Items affected need to be invalidated in LargeIcon and SmallIcons views. - if (this.View == View.LargeIcon || this.View == View.SmallIcon) + if (View == View.LargeIcon || View == View.SmallIcon) { - Rectangle rectInvalid = this.Items[startIndex].Bounds; + Rectangle rectInvalid = Items[startIndex].Bounds; for (int index = startIndex + 1; index <= endIndex; index++) { - rectInvalid = Rectangle.Union(rectInvalid, this.Items[index].Bounds); + rectInvalid = Rectangle.Union(rectInvalid, Items[index].Bounds); } if (startIndex > 0) { - rectInvalid = Rectangle.Union(rectInvalid, this.Items[startIndex - 1].Bounds); + rectInvalid = Rectangle.Union(rectInvalid, Items[startIndex - 1].Bounds); } else { @@ -4970,18 +4970,18 @@ public void RedrawItems(int startIndex, int endIndex, bool invalidateOnly) rectInvalid.Height += rectInvalid.Y; rectInvalid.X = rectInvalid.Y = 0; } - if (endIndex < this.Items.Count - 1) + if (endIndex < Items.Count - 1) { - rectInvalid = Rectangle.Union(rectInvalid, this.Items[endIndex + 1].Bounds); + rectInvalid = Rectangle.Union(rectInvalid, Items[endIndex + 1].Bounds); } else { - rectInvalid.Height += this.ClientRectangle.Bottom - rectInvalid.Bottom; - rectInvalid.Width += this.ClientRectangle.Right - rectInvalid.Right; + rectInvalid.Height += ClientRectangle.Bottom - rectInvalid.Bottom; + rectInvalid.Width += ClientRectangle.Right - rectInvalid.Right; } - if (this.View == View.LargeIcon) + if (View == View.LargeIcon) { - rectInvalid.Inflate(1, this.Font.Height + 1); + rectInvalid.Inflate(1, Font.Height + 1); } Invalidate(rectInvalid); } @@ -5015,7 +5015,7 @@ internal void RemoveGroupFromListView(ListViewGroup group) private void RemoveGroupNative(ListViewGroup group) { Debug.Assert(IsHandleCreated, "RemoveGroupNative precondition: list-view handle must be created"); - int retval = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_REMOVEGROUP, group.ID, IntPtr.Zero); + int retval = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_REMOVEGROUP, group.ID, IntPtr.Zero); // it is the job of whoever deletes this group to also turn off grouping if this was the last // group deleted @@ -5025,7 +5025,7 @@ private void RemoveGroupNative(ListViewGroup group) private void Scroll(int fromLVItem, int toLVItem) { int scrollY = GetItemPosition(toLVItem).Y - GetItemPosition(fromLVItem).Y; - UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_SCROLL, 0, scrollY); + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SCROLL, 0, scrollY); } private void SetBackgroundImage() @@ -5039,22 +5039,22 @@ private void SetBackgroundImage() // first, is there an existing temporary file to delete, remember its name // so that we can delete it if the list control doesn't... - string fileNameToDelete = this.backgroundImageFileName; + string fileNameToDelete = backgroundImageFileName; - if (this.BackgroundImage != null) + if (BackgroundImage != null) { // save the image to a temporary file name string tempDirName = System.IO.Path.GetTempPath(); System.Text.StringBuilder sb = new System.Text.StringBuilder(1024); - UnsafeNativeMethods.GetTempFileName(tempDirName, this.GenerateRandomName(), 0, sb); + UnsafeNativeMethods.GetTempFileName(tempDirName, GenerateRandomName(), 0, sb); - this.backgroundImageFileName = sb.ToString(); + backgroundImageFileName = sb.ToString(); - this.BackgroundImage.Save(this.backgroundImageFileName, System.Drawing.Imaging.ImageFormat.Bmp); + BackgroundImage.Save(backgroundImageFileName, System.Drawing.Imaging.ImageFormat.Bmp); - lvbkImage.pszImage = this.backgroundImageFileName; - lvbkImage.cchImageMax = this.backgroundImageFileName.Length + 1; + lvbkImage.pszImage = backgroundImageFileName; + lvbkImage.cchImageMax = backgroundImageFileName.Length + 1; lvbkImage.ulFlags = NativeMethods.LVBKIF_SOURCE_URL; if (BackgroundImageTiled) lvbkImage.ulFlags |= NativeMethods.LVBKIF_STYLE_TILE; @@ -5065,10 +5065,10 @@ private void SetBackgroundImage() else { lvbkImage.ulFlags = NativeMethods.LVBKIF_SOURCE_NONE; - this.backgroundImageFileName = string.Empty; + backgroundImageFileName = string.Empty; } - UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_SETBKIMAGE, 0, lvbkImage); + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SETBKIMAGE, 0, lvbkImage); if (string.IsNullOrEmpty(fileNameToDelete)) { @@ -5080,34 +5080,34 @@ private void SetBackgroundImage() // // 8 strings should be good enough for us - if (this.bkImgFileNames == null) + if (bkImgFileNames == null) { - this.bkImgFileNames = new string[BKIMGARRAYSIZE]; - this.bkImgFileNamesCount = -1; + bkImgFileNames = new string[BKIMGARRAYSIZE]; + bkImgFileNamesCount = -1; } - if (this.bkImgFileNamesCount == BKIMGARRAYSIZE - 1) + if (bkImgFileNamesCount == BKIMGARRAYSIZE - 1) { // it should be fine to delete the file name that was added first. // if it's not fine, then increase BKIMGARRAYSIZE - this.DeleteFileName(this.bkImgFileNames[0]); - this.bkImgFileNames[0] = this.bkImgFileNames[1]; - this.bkImgFileNames[1] = this.bkImgFileNames[2]; - this.bkImgFileNames[2] = this.bkImgFileNames[3]; - this.bkImgFileNames[3] = this.bkImgFileNames[4]; - this.bkImgFileNames[4] = this.bkImgFileNames[5]; - this.bkImgFileNames[5] = this.bkImgFileNames[6]; - this.bkImgFileNames[6] = this.bkImgFileNames[7]; - this.bkImgFileNames[7] = null; + DeleteFileName(bkImgFileNames[0]); + bkImgFileNames[0] = bkImgFileNames[1]; + bkImgFileNames[1] = bkImgFileNames[2]; + bkImgFileNames[2] = bkImgFileNames[3]; + bkImgFileNames[3] = bkImgFileNames[4]; + bkImgFileNames[4] = bkImgFileNames[5]; + bkImgFileNames[5] = bkImgFileNames[6]; + bkImgFileNames[6] = bkImgFileNames[7]; + bkImgFileNames[7] = null; - this.bkImgFileNamesCount--; + bkImgFileNamesCount--; } - this.bkImgFileNamesCount++; - this.bkImgFileNames[this.bkImgFileNamesCount] = fileNameToDelete; + bkImgFileNamesCount++; + bkImgFileNames[bkImgFileNamesCount] = fileNameToDelete; // now force the paint - this.Refresh(); + Refresh(); } /// @@ -5164,8 +5164,8 @@ internal void SetColumnInfo(int mask, ColumnHeader ch) internal void SetColumnWidth(int columnIndex, ColumnHeaderAutoResizeStyle headerAutoResize) { if ((columnIndex < 0) || - (columnIndex >= 0 && this.columnHeaders == null) || - (columnIndex >= this.columnHeaders.Length)) + (columnIndex >= 0 && columnHeaders == null) || + (columnIndex >= columnHeaders.Length)) { throw new ArgumentOutOfRangeException(nameof(columnIndex), columnIndex, string.Format(SR.InvalidArgument, nameof(columnIndex), columnIndex)); } @@ -5182,7 +5182,7 @@ internal void SetColumnWidth(int columnIndex, ColumnHeaderAutoResizeStyle header if (headerAutoResize == ColumnHeaderAutoResizeStyle.None) { - width = this.columnHeaders[columnIndex].WidthInternal; + width = columnHeaders[columnIndex].WidthInternal; // If the width maps to a LVCSW_ const, then native control will autoresize. // We may need to compensate for that. @@ -5198,12 +5198,12 @@ internal void SetColumnWidth(int columnIndex, ColumnHeaderAutoResizeStyle header if (headerAutoResize == ColumnHeaderAutoResizeStyle.HeaderSize) { - compensate = this.CompensateColumnHeaderResize(columnIndex, false /*columnHeaderResizeCancelled*/); + compensate = CompensateColumnHeaderResize(columnIndex, false /*columnHeaderResizeCancelled*/); width = NativeMethods.LVSCW_AUTOSIZE_USEHEADER; } else if (headerAutoResize == ColumnHeaderAutoResizeStyle.ColumnContent) { - compensate = this.CompensateColumnHeaderResize(columnIndex, false /*columnHeaderResizeCancelled*/); + compensate = CompensateColumnHeaderResize(columnIndex, false /*columnHeaderResizeCancelled*/); width = NativeMethods.LVSCW_AUTOSIZE; } @@ -5212,13 +5212,13 @@ internal void SetColumnWidth(int columnIndex, ColumnHeaderAutoResizeStyle header SendMessage(NativeMethods.LVM_SETCOLUMNWIDTH, columnIndex, NativeMethods.Util.MAKELPARAM(width, 0)); } - if (this.IsHandleCreated && + if (IsHandleCreated && (headerAutoResize == ColumnHeaderAutoResizeStyle.ColumnContent || headerAutoResize == ColumnHeaderAutoResizeStyle.HeaderSize)) { if (compensate != 0) { - int newWidth = this.columnHeaders[columnIndex].Width + compensate; + int newWidth = columnHeaders[columnIndex].Width + compensate; SendMessage(NativeMethods.LVM_SETCOLUMNWIDTH, columnIndex, NativeMethods.Util.MAKELPARAM(newWidth, 0)); } } @@ -5239,13 +5239,13 @@ private void SetDisplayIndices(int[] indices) int[] orderedColumns = new int[indices.Length]; for (int i = 0; i < indices.Length; i++) { - this.Columns[i].DisplayIndexInternal = indices[i]; + Columns[i].DisplayIndexInternal = indices[i]; orderedColumns[indices[i]] = i; } - if (this.IsHandleCreated && !this.Disposing) + if (IsHandleCreated && !Disposing) { - UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_SETCOLUMNORDERARRAY, orderedColumns.Length, orderedColumns); + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SETCOLUMNORDERARRAY, orderedColumns.Length, orderedColumns); } } @@ -5256,19 +5256,19 @@ private void SetDisplayIndices(int[] indices) /// internal void UpdateSavedCheckedItems(ListViewItem item, bool addItem) { - if (addItem && this.savedCheckedItems == null) + if (addItem && savedCheckedItems == null) { - this.savedCheckedItems = new List(); + savedCheckedItems = new List(); } if (addItem) { - this.savedCheckedItems.Add(item); + savedCheckedItems.Add(item); } - else if (this.savedCheckedItems != null) + else if (savedCheckedItems != null) { - Debug.Assert(this.savedCheckedItems.Contains(item), "somehow we lost track of one item"); - this.savedCheckedItems.Remove(item); + Debug.Assert(savedCheckedItems.Contains(item), "somehow we lost track of one item"); + savedCheckedItems.Remove(item); } #if FALSE if (savedCheckedItems != null && savedCheckedItems.Length > 0) { @@ -5310,17 +5310,17 @@ internal void SetToolTip(ToolTip toolTip, string toolTipCaption) { this.toolTipCaption = toolTipCaption; //native ListView expects tooltip HWND as a wParam and ignores lParam - IntPtr oldHandle = UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_SETTOOLTIPS, new HandleRef(toolTip, toolTip.Handle), 0); + IntPtr oldHandle = UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SETTOOLTIPS, new HandleRef(toolTip, toolTip.Handle), 0); UnsafeNativeMethods.DestroyWindow(new HandleRef(null, oldHandle)); } internal void SetItemImage(int index, int image) { - if (index < 0 || ((this.VirtualMode && index >= this.VirtualListSize) || (!this.VirtualMode && index >= itemCount))) + if (index < 0 || ((VirtualMode && index >= VirtualListSize) || (!VirtualMode && index >= itemCount))) { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - if (this.IsHandleCreated) + if (IsHandleCreated) { NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM(); lvItem.mask = NativeMethods.LVIF_IMAGE; @@ -5332,11 +5332,11 @@ internal void SetItemImage(int index, int image) internal void SetItemIndentCount(int index, int indentCount) { - if (index < 0 || ((this.VirtualMode && index >= this.VirtualListSize) || (!this.VirtualMode && index >= itemCount))) + if (index < 0 || ((VirtualMode && index >= VirtualListSize) || (!VirtualMode && index >= itemCount))) { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - if (this.IsHandleCreated) + if (IsHandleCreated) { NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM(); lvItem.mask = NativeMethods.LVIF_INDENT; @@ -5363,13 +5363,13 @@ internal void SetItemPosition(int index, int x, int y) internal void SetItemState(int index, int state, int mask) { - if (index < -1 || ((this.VirtualMode && index >= this.VirtualListSize) || (!this.VirtualMode && index >= itemCount))) + if (index < -1 || ((VirtualMode && index >= VirtualListSize) || (!VirtualMode && index >= itemCount))) { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - Debug.Assert(index == -1 || this.IsHandleCreated, "How did we add items without a handle?"); + Debug.Assert(index == -1 || IsHandleCreated, "How did we add items without a handle?"); - if (this.IsHandleCreated) + if (IsHandleCreated) { NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM(); lvItem.mask = NativeMethods.LVIF_STATE; @@ -5396,16 +5396,16 @@ private void SetItemText(int itemIndex, int subItemIndex, string text, ref Nativ // - if (this.View == View.List && subItemIndex == 0) + if (View == View.List && subItemIndex == 0) { - int colWidth = unchecked((int)(long)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_GETCOLUMNWIDTH, 0, 0)); + int colWidth = unchecked((int)(long)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_GETCOLUMNWIDTH, 0, 0)); - Graphics g = this.CreateGraphicsInternal(); + Graphics g = CreateGraphicsInternal(); int textWidth = 0; try { - textWidth = Size.Ceiling(g.MeasureString(text, this.Font)).Width; + textWidth = Size.Ceiling(g.MeasureString(text, Font)).Width; } finally { @@ -5435,7 +5435,7 @@ private void SetItemText(int itemIndex, int subItemIndex, string text, ref Nativ // internal void SetSelectionMark(int itemIndex) { - if (itemIndex < 0 || itemIndex >= this.Items.Count) + if (itemIndex < 0 || itemIndex >= Items.Count) { return; } @@ -5466,7 +5466,7 @@ public void Sort() ApplyUpdateCachedItems(); if (IsHandleCreated && listItemSorter != null) { - NativeMethods.ListViewCompareCallback callback = new NativeMethods.ListViewCompareCallback(this.CompareFunc); + NativeMethods.ListViewCompareCallback callback = new NativeMethods.ListViewCompareCallback(CompareFunc); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SORTITEMS, IntPtr.Zero, callback); } } @@ -5547,7 +5547,7 @@ private void UpdateColumnWidths(ColumnHeaderAutoResizeStyle headerAutoResize) { if (columnHeaders != null) { - for (int i = 0; i < this.columnHeaders.Length; i++) + for (int i = 0; i < columnHeaders.Length; i++) { SetColumnWidth(i, headerAutoResize); } @@ -5613,7 +5613,7 @@ internal void UpdateGroupNative(ListViewGroup group) try { lvgroup = GetLVGROUP(group); - int retval = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), + int retval = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SETGROUPINFO, group.ID, lvgroup); @@ -5643,16 +5643,16 @@ internal void UpdateGroupView() private void UpdateTileView() { Debug.Assert(ComctlSupportsVisualStyles, "this function works only when ComCtl 6.0 and higher is loaded"); - Debug.Assert(this.viewStyle == View.Tile, "this function should be called only in Tile view"); + Debug.Assert(viewStyle == View.Tile, "this function should be called only in Tile view"); NativeMethods.LVTILEVIEWINFO tileViewInfo = new NativeMethods.LVTILEVIEWINFO(); // the tile view info line count tileViewInfo.dwMask = NativeMethods.LVTVIM_COLUMNS; - tileViewInfo.cLines = this.columnHeaders != null ? this.columnHeaders.Length : 0; + tileViewInfo.cLines = columnHeaders != null ? columnHeaders.Length : 0; // the tile view info size tileViewInfo.dwMask |= NativeMethods.LVTVIM_TILESIZE; tileViewInfo.dwFlags = NativeMethods.LVTVIF_FIXEDSIZE; - tileViewInfo.sizeTile = new NativeMethods.SIZE(this.TileSize.Width, this.TileSize.Height); + tileViewInfo.sizeTile = new NativeMethods.SIZE(TileSize.Width, TileSize.Height); bool retval = UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SETTILEVIEWINFO, 0, tileViewInfo); Debug.Assert(retval, "LVM_SETTILEVIEWINFO failed"); @@ -5742,7 +5742,7 @@ private void WmMouseDown(ref Message m, MouseButtons button, int clicks) if (CheckBoxes) { - ListViewHitTestInfo lvhti = this.HitTest(x, y); + ListViewHitTestInfo lvhti = HitTest(x, y); if (imageListState != null && imageListState.Images.Count < 2) { // When the user clicks on the check box and the listView's state image list @@ -5846,23 +5846,23 @@ private unsafe bool WmNotify(ref Message m) if (nmhdr->code == NativeMethods.HDN_BEGINTRACK) { - this.listViewState[LISTVIEWSTATE_headerControlTracking] = true; + listViewState[LISTVIEWSTATE_headerControlTracking] = true; // Reset our tracking information for the new BEGINTRACK cycle. - this.listViewState1[LISTVIEWSTATE1_cancelledColumnWidthChanging] = false; - this.newWidthForColumnWidthChangingCancelled = -1; - this.listViewState1[LISTVIEWSTATE1_cancelledColumnWidthChanging] = false; + listViewState1[LISTVIEWSTATE1_cancelledColumnWidthChanging] = false; + newWidthForColumnWidthChangingCancelled = -1; + listViewState1[LISTVIEWSTATE1_cancelledColumnWidthChanging] = false; NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER)m.GetLParam(typeof(NativeMethods.NMHEADER)); - if (this.columnHeaders != null && this.columnHeaders.Length > nmheader.iItem) + if (columnHeaders != null && columnHeaders.Length > nmheader.iItem) { - this.columnHeaderClicked = this.columnHeaders[nmheader.iItem]; - this.columnHeaderClickedWidth = this.columnHeaderClicked.Width; + columnHeaderClicked = columnHeaders[nmheader.iItem]; + columnHeaderClickedWidth = columnHeaderClicked.Width; } else { - this.columnHeaderClickedWidth = -1; - this.columnHeaderClicked = null; + columnHeaderClickedWidth = -1; + columnHeaderClicked = null; } } @@ -5871,7 +5871,7 @@ private unsafe bool WmNotify(ref Message m) NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER)m.GetLParam(typeof(NativeMethods.NMHEADER)); if (columnHeaders != null && nmheader.iItem < columnHeaders.Length && - (this.listViewState[LISTVIEWSTATE_headerControlTracking] || this.listViewState[LISTVIEWSTATE_headerDividerDblClick])) + (listViewState[LISTVIEWSTATE_headerControlTracking] || listViewState[LISTVIEWSTATE_headerDividerDblClick])) { // @@ -5888,13 +5888,13 @@ private unsafe bool WmNotify(ref Message m) // We are called inside HDN_DIVIDERDBLCLICK. // Turn off the compensation that our processing of HDN_DIVIDERDBLCLICK would otherwise add. - if (this.listViewState[LISTVIEWSTATE_headerDividerDblClick]) + if (listViewState[LISTVIEWSTATE_headerDividerDblClick]) { - this.listViewState[LISTVIEWSTATE_columnResizeCancelled] = true; + listViewState[LISTVIEWSTATE_columnResizeCancelled] = true; } - this.listViewState1[LISTVIEWSTATE1_cancelledColumnWidthChanging] = true; - this.newWidthForColumnWidthChangingCancelled = colWidthChanging.NewWidth; + listViewState1[LISTVIEWSTATE1_cancelledColumnWidthChanging] = true; + newWidthForColumnWidthChangingCancelled = colWidthChanging.NewWidth; // skip default processing return true; @@ -5907,26 +5907,26 @@ private unsafe bool WmNotify(ref Message m) } if ((nmhdr->code == NativeMethods.HDN_ITEMCHANGED) && - !this.listViewState[LISTVIEWSTATE_headerControlTracking]) + !listViewState[LISTVIEWSTATE_headerControlTracking]) { NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER)m.GetLParam(typeof(NativeMethods.NMHEADER)); if (columnHeaders != null && nmheader.iItem < columnHeaders.Length) { int w = columnHeaders[nmheader.iItem].Width; - if (this.columnHeaderClicked == null || - (this.columnHeaderClicked == this.columnHeaders[nmheader.iItem] && - this.columnHeaderClickedWidth != -1 && - this.columnHeaderClickedWidth != w)) + if (columnHeaderClicked == null || + (columnHeaderClicked == columnHeaders[nmheader.iItem] && + columnHeaderClickedWidth != -1 && + columnHeaderClickedWidth != w)) { // // If the user double clicked on the column header and we still need to compensate for the column resize // then don't fire ColumnWidthChanged because at this point the column header does not have the final width. // - if (this.listViewState[LISTVIEWSTATE_headerDividerDblClick]) + if (listViewState[LISTVIEWSTATE_headerDividerDblClick]) { - if (this.CompensateColumnHeaderResize(m, this.listViewState[LISTVIEWSTATE_columnResizeCancelled]) == 0) + if (CompensateColumnHeaderResize(m, listViewState[LISTVIEWSTATE_columnResizeCancelled]) == 0) { OnColumnWidthChanged(new ColumnWidthChangedEventArgs(nmheader.iItem)); } @@ -5939,8 +5939,8 @@ private unsafe bool WmNotify(ref Message m) } } - this.columnHeaderClicked = null; - this.columnHeaderClickedWidth = -1; + columnHeaderClicked = null; + columnHeaderClickedWidth = -1; ISite site = Site; @@ -5967,22 +5967,22 @@ private unsafe bool WmNotify(ref Message m) if (nmhdr->code == NativeMethods.HDN_ENDTRACK) { - Debug.Assert(this.listViewState[LISTVIEWSTATE_headerControlTracking], "HDN_ENDTRACK and HDN_BEGINTRACK are out of sync..."); - this.listViewState[LISTVIEWSTATE_headerControlTracking] = false; - if (this.listViewState1[LISTVIEWSTATE1_cancelledColumnWidthChanging]) + Debug.Assert(listViewState[LISTVIEWSTATE_headerControlTracking], "HDN_ENDTRACK and HDN_BEGINTRACK are out of sync..."); + listViewState[LISTVIEWSTATE_headerControlTracking] = false; + if (listViewState1[LISTVIEWSTATE1_cancelledColumnWidthChanging]) { m.Result = (IntPtr)1; - if (this.newWidthForColumnWidthChangingCancelled != -1) + if (newWidthForColumnWidthChangingCancelled != -1) { NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER)m.GetLParam(typeof(NativeMethods.NMHEADER)); - if (this.columnHeaders != null && this.columnHeaders.Length > nmheader.iItem) + if (columnHeaders != null && columnHeaders.Length > nmheader.iItem) { - this.columnHeaders[nmheader.iItem].Width = this.newWidthForColumnWidthChangingCancelled; + columnHeaders[nmheader.iItem].Width = newWidthForColumnWidthChangingCancelled; } } - this.listViewState1[LISTVIEWSTATE1_cancelledColumnWidthChanging] = false; - this.newWidthForColumnWidthChangingCancelled = -1; + listViewState1[LISTVIEWSTATE1_cancelledColumnWidthChanging] = false; + newWidthForColumnWidthChangingCancelled = -1; // skip default processing return true; @@ -6003,7 +6003,7 @@ private unsafe bool WmNotify(ref Message m) if ((hdItem.mask & NativeMethods.HDI_ORDER) == NativeMethods.HDI_ORDER) { - int from = this.Columns[header.iItem].DisplayIndex; + int from = Columns[header.iItem].DisplayIndex; int to = hdItem.iOrder; // check this if (from == to) @@ -6018,7 +6018,7 @@ private unsafe bool WmNotify(ref Message m) } ColumnReorderedEventArgs chrevent = new ColumnReorderedEventArgs(from, to, - this.Columns[header.iItem]); + Columns[header.iItem]); OnColumnReordered(chrevent); if (chrevent.Cancel) { @@ -6033,11 +6033,11 @@ private unsafe bool WmNotify(ref Message m) int hiDI = Math.Max(from, to); bool hdrMovedForward = to > from; ColumnHeader movedHdr = null; - int[] indices = new int[this.Columns.Count]; - for (int i = 0; i < this.Columns.Count; i++) + int[] indices = new int[Columns.Count]; + for (int i = 0; i < Columns.Count; i++) { - ColumnHeader hdr = this.Columns[i]; + ColumnHeader hdr = Columns[i]; if (hdr.DisplayIndex == from) { movedHdr = hdr; @@ -6064,11 +6064,11 @@ private unsafe bool WmNotify(ref Message m) { // We need to keep track that the user double clicked the column header divider // so we know that the column header width is changing. - this.listViewState[LISTVIEWSTATE_headerDividerDblClick] = true; + listViewState[LISTVIEWSTATE_headerDividerDblClick] = true; // Reset ColumnResizeCancelled. // It will be set if the user cancels the ColumnWidthChanging event. - this.listViewState[LISTVIEWSTATE_columnResizeCancelled] = false; + listViewState[LISTVIEWSTATE_columnResizeCancelled] = false; bool columnResizeCancelled = false; @@ -6083,24 +6083,24 @@ private unsafe bool WmNotify(ref Message m) } finally { - this.listViewState[LISTVIEWSTATE_headerDividerDblClick] = false; - columnResizeCancelled = this.listViewState[LISTVIEWSTATE_columnResizeCancelled]; - this.listViewState[LISTVIEWSTATE_columnResizeCancelled] = false; + listViewState[LISTVIEWSTATE_headerDividerDblClick] = false; + columnResizeCancelled = listViewState[LISTVIEWSTATE_columnResizeCancelled]; + listViewState[LISTVIEWSTATE_columnResizeCancelled] = false; } - this.columnHeaderClicked = null; - this.columnHeaderClickedWidth = -1; + columnHeaderClicked = null; + columnHeaderClickedWidth = -1; if (columnResizeCancelled) { // If the column resize was cancelled then apply the NewWidth supplied by the user. - if (this.newWidthForColumnWidthChangingCancelled != -1) + if (newWidthForColumnWidthChangingCancelled != -1) { NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER)m.GetLParam(typeof(NativeMethods.NMHEADER)); - if (this.columnHeaders != null && this.columnHeaders.Length > nmheader.iItem) + if (columnHeaders != null && columnHeaders.Length > nmheader.iItem) { - this.columnHeaders[nmheader.iItem].Width = this.newWidthForColumnWidthChangingCancelled; + columnHeaders[nmheader.iItem].Width = newWidthForColumnWidthChangingCancelled; } } @@ -6110,16 +6110,16 @@ private unsafe bool WmNotify(ref Message m) else { // Compensate for the column resize. - int compensateForColumnResize = this.CompensateColumnHeaderResize(m, columnResizeCancelled); + int compensateForColumnResize = CompensateColumnHeaderResize(m, columnResizeCancelled); if (compensateForColumnResize != 0) { #if DEBUG NativeMethods.NMHEADER header = (NativeMethods.NMHEADER)m.GetLParam(typeof(NativeMethods.NMHEADER)); Debug.Assert(header.iItem == 0, "we only need to compensate for the first column resize"); - Debug.Assert(this.columnHeaders.Length > 0, "there should be a column that we need to compensate for"); + Debug.Assert(columnHeaders.Length > 0, "there should be a column that we need to compensate for"); #endif - ColumnHeader col = this.columnHeaders[0]; + ColumnHeader col = columnHeaders[0]; col.Width += compensateForColumnResize; } } @@ -6158,7 +6158,7 @@ internal void RecreateHandleInternal() // For some reason, if CheckBoxes are set to true and the list view has a state imageList, then the native listView destroys // the state imageList. // (Yes, it does exactly that even though our wrapper sets LVS_SHAREIMAGELISTS on the native listView.) - if (this.IsHandleCreated && this.StateImageList != null) + if (IsHandleCreated && StateImageList != null) { SendMessage(NativeMethods.LVM_SETIMAGELIST, NativeMethods.LVSIL_STATE, IntPtr.Zero); } @@ -6222,7 +6222,7 @@ private unsafe void WmReflectNotify(ref Message m) // that means that we can't reliably give the user the item on which the dragging started // so don't tell the user about this operation... // - if (!this.ItemCollectionChangedInMouseDown) + if (!ItemCollectionChangedInMouseDown) { NativeMethods.NMLISTVIEW nmlv = (NativeMethods.NMLISTVIEW)m.GetLParam(typeof(NativeMethods.NMLISTVIEW)); LvnBeginDrag(MouseButtons.Left, nmlv); @@ -6237,7 +6237,7 @@ private unsafe void WmReflectNotify(ref Message m) // that means that we can't reliably give the user the item on which the dragging started // so don't tell the user about this operation... // - if (!this.ItemCollectionChangedInMouseDown) + if (!ItemCollectionChangedInMouseDown) { NativeMethods.NMLISTVIEW nmlv = (NativeMethods.NMLISTVIEW)m.GetLParam(typeof(NativeMethods.NMLISTVIEW)); LvnBeginDrag(MouseButtons.Right, nmlv); @@ -6296,11 +6296,11 @@ private unsafe void WmReflectNotify(ref Message m) // So leave it as it is... if (newState != oldState) { - if (this.VirtualMode && nmlv->iItem == -1) + if (VirtualMode && nmlv->iItem == -1) { - if (this.VirtualListSize > 0) + if (VirtualListSize > 0) { - ListViewVirtualItemsSelectionRangeChangedEventArgs lvvisrce = new ListViewVirtualItemsSelectionRangeChangedEventArgs(0, this.VirtualListSize - 1, newState != 0); + ListViewVirtualItemsSelectionRangeChangedEventArgs lvvisrce = new ListViewVirtualItemsSelectionRangeChangedEventArgs(0, VirtualListSize - 1, newState != 0); OnVirtualItemsSelectionRangeChanged(lvvisrce); } } @@ -6312,23 +6312,23 @@ private unsafe void WmReflectNotify(ref Message m) // In that case, the native list view may have an item under the mouse even if our wrapper thinks the item count is 0. // And that may cause GetItemAt to throw an out of bounds exception. - if (this.Items.Count > 0) + if (Items.Count > 0) { - ListViewItemSelectionChangedEventArgs lvisce = new ListViewItemSelectionChangedEventArgs(this.Items[nmlv->iItem], + ListViewItemSelectionChangedEventArgs lvisce = new ListViewItemSelectionChangedEventArgs(Items[nmlv->iItem], nmlv->iItem, newState != 0); OnItemSelectionChanged(lvisce); } } // Delay SelectedIndexChanged event because the last item isn't present yet. - if (this.Items.Count == 0 || this.Items[this.Items.Count - 1] != null) + if (Items.Count == 0 || Items[Items.Count - 1] != null) { - this.listViewState1[LISTVIEWSTATE1_selectedIndexChangedSkipped] = false; + listViewState1[LISTVIEWSTATE1_selectedIndexChangedSkipped] = false; OnSelectedIndexChanged(EventArgs.Empty); } else { - this.listViewState1[LISTVIEWSTATE1_selectedIndexChangedSkipped] = true; + listViewState1[LISTVIEWSTATE1_selectedIndexChangedSkipped] = true; } } } @@ -6416,7 +6416,7 @@ private unsafe void WmReflectNotify(ref Message m) if (nmhdr->code == NativeMethods.LVN_GETDISPINFO) { // we use the LVN_GETDISPINFO message only in virtual mode - if (this.VirtualMode && m.LParam != IntPtr.Zero) + if (VirtualMode && m.LParam != IntPtr.Zero) { NativeMethods.NMLVDISPINFO_NOTEXT dispInfo = (NativeMethods.NMLVDISPINFO_NOTEXT)m.GetLParam(typeof(NativeMethods.NMLVDISPINFO_NOTEXT)); @@ -6555,7 +6555,7 @@ private unsafe void WmReflectNotify(ref Message m) } int startIndex = nmlvif.iStart; - if (startIndex >= this.VirtualListSize) + if (startIndex >= VirtualListSize) { // we want to search starting from the last item. Wrap around the first item. startIndex = 0; @@ -6589,11 +6589,11 @@ private unsafe void WmReflectNotify(ref Message m) private void WmPrint(ref Message m) { base.WndProc(ref m); - if ((NativeMethods.PRF_NONCLIENT & (int)m.LParam) != 0 && Application.RenderWithVisualStyles && this.BorderStyle == BorderStyle.Fixed3D) + if ((NativeMethods.PRF_NONCLIENT & (int)m.LParam) != 0 && Application.RenderWithVisualStyles && BorderStyle == BorderStyle.Fixed3D) { using (Graphics g = Graphics.FromHdc(m.WParam)) { - Rectangle rect = new Rectangle(0, 0, this.Size.Width - 1, this.Size.Height - 1); + Rectangle rect = new Rectangle(0, 0, Size.Width - 1, Size.Height - 1); g.DrawRectangle(new Pen(VisualStyleInformation.TextControlBorder), rect); rect.Inflate(-1, -1); g.DrawRectangle(SystemPens.Window, rect); @@ -6615,7 +6615,7 @@ protected override void WndProc(ref Message m) // Ensure that the itemCollectionChangedInMouseDown is not set // before processing the mousedown event. - this.ItemCollectionChangedInMouseDown = false; + ItemCollectionChangedInMouseDown = false; CaptureInternal = true; WmMouseDown(ref m, MouseButtons.Left, 2); break; @@ -6624,7 +6624,7 @@ protected override void WndProc(ref Message m) // Ensure that the itemCollectionChangedInMouseDown is not set // before processing the mousedown event. - this.ItemCollectionChangedInMouseDown = false; + ItemCollectionChangedInMouseDown = false; WmMouseDown(ref m, MouseButtons.Left, 1); downButton = MouseButtons.Left; break; @@ -6650,7 +6650,7 @@ protected override void WndProc(ref Message m) listViewState[LISTVIEWSTATE_expectingMouseUp] = false; } - this.ItemCollectionChangedInMouseDown = false; + ItemCollectionChangedInMouseDown = false; listViewState[LISTVIEWSTATE_mouseUpFired] = true; CaptureInternal = false; @@ -6698,7 +6698,7 @@ protected override void WndProc(ref Message m) case Interop.WindowMessages.WM_SETFOCUS: base.WndProc(ref m); - if (!this.RecreatingHandle && !this.ListViewHandleDestroyed) + if (!RecreatingHandle && !ListViewHandleDestroyed) { // This means that we get a WM_SETFOCUS on the hWnd that was destroyed. // Don't do anything because the information on the previous hWnd is most likely @@ -6723,7 +6723,7 @@ protected override void WndProc(ref Message m) base.WndProc(ref m); // win32 ListView - BeginInvoke(new MethodInvoker(this.CleanPreviousBackgroundImageFiles)); + BeginInvoke(new MethodInvoker(CleanPreviousBackgroundImageFiles)); break; case Interop.WindowMessages.WM_PRINT: WmPrint(ref m); @@ -6748,7 +6748,7 @@ internal class IconComparer : IComparer public IconComparer(SortOrder currentSortOrder) { - this.sortOrder = currentSortOrder; + sortOrder = currentSortOrder; } public SortOrder SortOrder @@ -7247,7 +7247,7 @@ public virtual int IndexOfKey(string key) } // step 2 - search for the item - for (int i = 0; i < this.Count; i++) + for (int i = 0; i < Count; i++) { if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { @@ -7267,7 +7267,7 @@ public virtual int IndexOfKey(string key) /// private bool IsValidIndex(int index) { - return ((index >= 0) && (index < this.Count)); + return ((index >= 0) && (index < Count)); } int IList.IndexOf(object item) @@ -7578,16 +7578,16 @@ void IList.RemoveAt(int index) public int Add(int itemIndex) { - if (this.owner.VirtualMode) + if (owner.VirtualMode) { - if (itemIndex < 0 || itemIndex >= this.owner.VirtualListSize) + if (itemIndex < 0 || itemIndex >= owner.VirtualListSize) { throw new ArgumentOutOfRangeException(nameof(itemIndex), itemIndex, string.Format(SR.InvalidArgument, nameof(itemIndex), itemIndex)); } - if (this.owner.IsHandleCreated) + if (owner.IsHandleCreated) { - this.owner.SetItemState(itemIndex, NativeMethods.LVIS_SELECTED, NativeMethods.LVIS_SELECTED); - return this.Count; + owner.SetItemState(itemIndex, NativeMethods.LVIS_SELECTED, NativeMethods.LVIS_SELECTED); + return Count; } else { @@ -7596,24 +7596,24 @@ public int Add(int itemIndex) } else { - if (itemIndex < 0 || itemIndex >= this.owner.Items.Count) + if (itemIndex < 0 || itemIndex >= owner.Items.Count) { throw new ArgumentOutOfRangeException(nameof(itemIndex), itemIndex, string.Format(SR.InvalidArgument, nameof(itemIndex), itemIndex)); } - this.owner.Items[itemIndex].Selected = true; - return this.Count; + owner.Items[itemIndex].Selected = true; + return Count; } } public void Clear() { - if (!this.owner.VirtualMode) + if (!owner.VirtualMode) { - this.owner.savedSelectedItems = null; + owner.savedSelectedItems = null; } - if (this.owner.IsHandleCreated) + if (owner.IsHandleCreated) { - this.owner.SetItemState(-1, 0, NativeMethods.LVIS_SELECTED); + owner.SetItemState(-1, 0, NativeMethods.LVIS_SELECTED); } } @@ -7640,24 +7640,24 @@ public IEnumerator GetEnumerator() public void Remove(int itemIndex) { - if (this.owner.VirtualMode) + if (owner.VirtualMode) { - if (itemIndex < 0 || itemIndex >= this.owner.VirtualListSize) + if (itemIndex < 0 || itemIndex >= owner.VirtualListSize) { throw new ArgumentOutOfRangeException(nameof(itemIndex), itemIndex, string.Format(SR.InvalidArgument, nameof(itemIndex), itemIndex)); } - if (this.owner.IsHandleCreated) + if (owner.IsHandleCreated) { - this.owner.SetItemState(itemIndex, 0, NativeMethods.LVIS_SELECTED); + owner.SetItemState(itemIndex, 0, NativeMethods.LVIS_SELECTED); } } else { - if (itemIndex < 0 || itemIndex >= this.owner.Items.Count) + if (itemIndex < 0 || itemIndex >= owner.Items.Count) { throw new ArgumentOutOfRangeException(nameof(itemIndex), itemIndex, string.Format(SR.InvalidArgument, nameof(itemIndex), itemIndex)); } - this.owner.Items[itemIndex].Selected = false; + owner.Items[itemIndex].Selected = false; } } } @@ -7893,7 +7893,7 @@ void IList.Insert(int index, object value) /// private bool IsValidIndex(int index) { - return ((index >= 0) && (index < this.Count)); + return ((index >= 0) && (index < Count)); } void IList.Remove(object value) @@ -8057,7 +8057,7 @@ public virtual int IndexOfKey(string key) } // step 2 - search for the item - for (int i = 0; i < this.Count; i++) + for (int i = 0; i < Count; i++) { if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { @@ -8224,7 +8224,7 @@ public virtual int IndexOfKey(string key) } // step 2 - search for the item - for (int i = 0; i < this.Count; i++) + for (int i = 0; i < Count; i++) { if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { @@ -8244,7 +8244,7 @@ public virtual int IndexOfKey(string key) /// private bool IsValidIndex(int index) { - return ((index >= 0) && (index < this.Count)); + return ((index >= 0) && (index < Count)); } @@ -8555,7 +8555,7 @@ public virtual void RemoveAt(int index) int w = owner.columnHeaders[index].Width; // Update width before detaching from ListView // in Tile view our ListView uses the column header collection to update the Tile Information - if (owner.IsHandleCreated && this.owner.View != View.Tile) + if (owner.IsHandleCreated && owner.View != View.Tile) { int retval = unchecked((int)(long)owner.SendMessage(NativeMethods.LVM_DELETECOLUMN, index, 0)); @@ -8564,10 +8564,10 @@ public virtual void RemoveAt(int index) } // we need to update the display indices - int[] indices = new int[this.Count - 1]; + int[] indices = new int[Count - 1]; ColumnHeader removeHdr = this[index]; - for (int i = 0; i < this.Count; i++) + for (int i = 0; i < Count; i++) { ColumnHeader hdr = this[i]; if (i != index) @@ -8598,9 +8598,9 @@ public virtual void RemoveAt(int index) } // in Tile view our ListView uses the column header collection to update the Tile Information - if (owner.IsHandleCreated && this.owner.View == View.Tile) + if (owner.IsHandleCreated && owner.View == View.Tile) { - this.owner.RecreateHandleInternal(); + owner.RecreateHandleInternal(); } owner.SetDisplayIndices(indices); @@ -8674,7 +8674,7 @@ public ListViewItemCollection(ListView owner) // In Whidbey this constructor is a no-op. // initialize the inner list w/ a dummy list. - this.innerList = new ListViewNativeItemCollection(owner); + innerList = new ListViewNativeItemCollection(owner); } internal ListViewItemCollection(IInnerList innerList) @@ -9011,7 +9011,7 @@ private ArrayList FindInternal(string key, bool searchAllSubItems, ListViewItemC public IEnumerator GetEnumerator() { - if (this.InnerList.OwnerIsVirtualListView && !this.InnerList.OwnerIsDesignMode) + if (InnerList.OwnerIsVirtualListView && !InnerList.OwnerIsDesignMode) { // Throw the exception only at runtime. throw new InvalidOperationException(SR.ListViewCantGetEnumeratorInVirtualMode); @@ -9063,7 +9063,7 @@ public virtual int IndexOfKey(string key) } // step 2 - search for the item - for (int i = 0; i < this.Count; i++) + for (int i = 0; i < Count; i++) { if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { @@ -9082,7 +9082,7 @@ public virtual int IndexOfKey(string key) /// private bool IsValidIndex(int index) { - return ((index >= 0) && (index < this.Count)); + return ((index >= 0) && (index < Count)); } public ListViewItem Insert(int index, ListViewItem item) @@ -9240,7 +9240,7 @@ public ListViewItem this[int displayIndex] // if we are showing virtual items, we need to get the item from the user RetrieveVirtualItemEventArgs rVI = new RetrieveVirtualItemEventArgs(displayIndex); owner.OnRetrieveVirtualItem(rVI); - rVI.Item.SetItemIndex(this.owner, displayIndex); + rVI.Item.SetItemIndex(owner, displayIndex); return rVI.Item; } else @@ -9270,9 +9270,9 @@ public ListViewItem this[int displayIndex] if (displayIndex < 0 || displayIndex >= owner.itemCount) throw new ArgumentOutOfRangeException(nameof(displayIndex), displayIndex, string.Format(SR.InvalidArgument, nameof(displayIndex), displayIndex)); - if (this.owner.ExpectingMouseUp) + if (owner.ExpectingMouseUp) { - this.owner.ItemCollectionChangedInMouseDown = true; + owner.ItemCollectionChangedInMouseDown = true; } RemoveAt(displayIndex); @@ -9288,7 +9288,7 @@ public ListViewItem Add(ListViewItem value) } else { - Debug.Assert(!this.owner.FlipViewToLargeIconAndSmallIcon || this.Count == 0, "the FlipView... bit is turned off after adding 1 item."); + Debug.Assert(!owner.FlipViewToLargeIconAndSmallIcon || Count == 0, "the FlipView... bit is turned off after adding 1 item."); // PERF. // Get the Checked bit before adding it to the back end. @@ -9302,9 +9302,9 @@ public ListViewItem Add(ListViewItem value) owner.UpdateSavedCheckedItems(value, true /*addItem*/); } - if (this.owner.ExpectingMouseUp) + if (owner.ExpectingMouseUp) { - this.owner.ItemCollectionChangedInMouseDown = true; + owner.ItemCollectionChangedInMouseDown = true; } return value; @@ -9326,7 +9326,7 @@ public void AddRange(ListViewItem[] values) IComparer comparer = owner.listItemSorter; owner.listItemSorter = null; - Debug.Assert(!this.owner.FlipViewToLargeIconAndSmallIcon || this.Count == 0, "the FlipView... bit is turned off after adding 1 item."); + Debug.Assert(!owner.FlipViewToLargeIconAndSmallIcon || Count == 0, "the FlipView... bit is turned off after adding 1 item."); bool[] checkedValues = null; @@ -9366,9 +9366,9 @@ public void AddRange(ListViewItem[] values) owner.EndUpdate(); } - if (this.owner.ExpectingMouseUp) + if (owner.ExpectingMouseUp) { - this.owner.ItemCollectionChangedInMouseDown = true; + owner.ItemCollectionChangedInMouseDown = true; } if (comparer != null || (owner.Sorting != SortOrder.None) && !owner.VirtualMode) @@ -9441,13 +9441,13 @@ public void Clear() // if (owner.View == View.SmallIcon) { - if (this.owner.ComctlSupportsVisualStyles) + if (owner.ComctlSupportsVisualStyles) { - this.owner.FlipViewToLargeIconAndSmallIcon = true; + owner.FlipViewToLargeIconAndSmallIcon = true; } else { - Debug.Assert(!this.owner.FlipViewToLargeIconAndSmallIcon, "we only set this when comctl 6.0 is loaded"); + Debug.Assert(!owner.FlipViewToLargeIconAndSmallIcon, "we only set this when comctl 6.0 is loaded"); owner.View = View.LargeIcon; owner.View = View.SmallIcon; } @@ -9478,9 +9478,9 @@ public void Clear() } owner.itemCount = 0; - if (this.owner.ExpectingMouseUp) + if (owner.ExpectingMouseUp) { - this.owner.ItemCollectionChangedInMouseDown = true; + owner.ItemCollectionChangedInMouseDown = true; } } @@ -9523,7 +9523,7 @@ public ListViewItem Insert(int index, ListViewItem item) throw new InvalidOperationException(SR.ListViewCantAddItemsToAVirtualListView); } - Debug.Assert(!this.owner.FlipViewToLargeIconAndSmallIcon || this.Count == 0, "the FlipView... bit is turned off after adding 1 item."); + Debug.Assert(!owner.FlipViewToLargeIconAndSmallIcon || Count == 0, "the FlipView... bit is turned off after adding 1 item."); if (index < count) { @@ -9538,9 +9538,9 @@ public ListViewItem Insert(int index, ListViewItem item) owner.UpdateSavedCheckedItems(item, true /*addItem*/); } - if (this.owner.ExpectingMouseUp) + if (owner.ExpectingMouseUp) { - this.owner.ItemCollectionChangedInMouseDown = true; + owner.ItemCollectionChangedInMouseDown = true; } return item; @@ -9563,7 +9563,7 @@ public void Remove(ListViewItem item) { int index = owner.VirtualMode ? Count - 1 : IndexOf(item); - Debug.Assert(!this.owner.FlipViewToLargeIconAndSmallIcon || this.Count == 0, "the FlipView... bit is turned off after adding 1 item."); + Debug.Assert(!owner.FlipViewToLargeIconAndSmallIcon || Count == 0, "the FlipView... bit is turned off after adding 1 item."); if (owner.VirtualMode) { @@ -9586,7 +9586,7 @@ public void RemoveAt(int index) if (index < 0 || index >= owner.itemCount) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); - Debug.Assert(!this.owner.FlipViewToLargeIconAndSmallIcon || this.Count == 0, "the FlipView... bit is turned off after adding 1 item."); + Debug.Assert(!owner.FlipViewToLargeIconAndSmallIcon || Count == 0, "the FlipView... bit is turned off after adding 1 item."); if (owner.IsHandleCreated && !owner.CheckBoxes && this[index].Checked) { @@ -9615,9 +9615,9 @@ public void RemoveAt(int index) owner.itemCount--; owner.listItemsTable.Remove(itemID); - if (this.owner.ExpectingMouseUp) + if (owner.ExpectingMouseUp) { - this.owner.ItemCollectionChangedInMouseDown = true; + owner.ItemCollectionChangedInMouseDown = true; } } @@ -9635,8 +9635,8 @@ public void CopyTo(Array dest, int index) public IEnumerator GetEnumerator() { - ListViewItem[] items = new ListViewItem[this.owner.itemCount]; - this.CopyTo(items, 0); + ListViewItem[] items = new ListViewItem[owner.itemCount]; + CopyTo(items, 0); return items.GetEnumerator(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupCollection.cs index bb19ba7b68c..a6c6fdccf50 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupCollection.cs @@ -21,7 +21,7 @@ public class ListViewGroupCollection : IList internal ListViewGroupCollection(ListView listView) { - this._listView = listView; + _listView = listView; } public int Count => List.Count; @@ -38,7 +38,7 @@ internal ListViewGroupCollection(ListView listView) public ListViewGroup this[int index] { - get => (ListViewGroup)this.List[index]; + get => (ListViewGroup)List[index]; set { if (value == null) @@ -133,7 +133,7 @@ public int Add(ListViewGroup group) int index = List.Add(group); if (_listView.IsHandleCreated) { - _listView.InsertGroupInListView(this.List.Count, group); + _listView.InsertGroupInListView(List.Count, group); MoveGroupItems(group); } @@ -282,7 +282,7 @@ private void MoveGroupItems(ListViewGroup group) foreach (ListViewItem item in group.Items) { - if (item.ListView == this._listView) + if (item.ListView == _listView) { item.UpdateStateToListView(item.Index); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupItemCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupItemCollection.cs index f751196aabd..4fd876f1bf9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupItemCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupItemCollection.cs @@ -72,7 +72,7 @@ private void CheckListViewItem(ListViewItem item) public void Clear() { - for (int i = 0; i < this.Count; i++) + for (int i = 0; i < Count; i++) { MoveToGroup(this[i], null); } @@ -91,7 +91,7 @@ public ListViewItem Insert(int index, ListViewItem item) { CheckListViewItem(item); - MoveToGroup(item, this._group); + MoveToGroup(item, _group); Items.Insert(index, item); return item; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewHitTestInfo.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewHitTestInfo.cs index e22bdb1f4fb..28cd9c9cb9c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewHitTestInfo.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewHitTestInfo.cs @@ -26,9 +26,9 @@ public class ListViewHitTestInfo /// public ListViewHitTestInfo(ListViewItem hitItem, ListViewItem.ListViewSubItem hitSubItem, ListViewHitTestLocations hitLocation) { - this.item = hitItem; - this.subItem = hitSubItem; - this.loc = hitLocation; + item = hitItem; + subItem = hitSubItem; + loc = hitLocation; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItem.cs index 14569bf9a30..4861bbc995e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItem.cs @@ -320,7 +320,7 @@ public bool Checked // the setter for StateImageIndex calls ItemChecked handler // thus need to verify validity of the listView again - if (listView != null && !this.listView.UseCompatibleStateImageBehavior) + if (listView != null && !listView.UseCompatibleStateImageBehavior) { if (!listView.CheckBoxes) { @@ -869,10 +869,10 @@ public void BeginEdit() public virtual object Clone() { - ListViewSubItem[] clonedSubItems = new ListViewSubItem[this.SubItems.Count]; - for (int index = 0; index < this.SubItems.Count; ++index) + ListViewSubItem[] clonedSubItems = new ListViewSubItem[SubItems.Count]; + for (int index = 0; index < SubItems.Count; ++index) { - ListViewSubItem subItem = this.SubItems[index]; + ListViewSubItem subItem = SubItems[index]; clonedSubItems[index] = new ListViewSubItem(null, subItem.Text, subItem.ForeColor, @@ -881,7 +881,7 @@ public virtual object Clone() clonedSubItems[index].Tag = subItem.Tag; } - Type clonedType = this.GetType(); + Type clonedType = GetType(); ListViewItem newItem = null; if (clonedType == typeof(ListViewItem)) @@ -894,10 +894,10 @@ public virtual object Clone() } newItem.subItems = clonedSubItems; newItem.ImageIndexer.Index = ImageIndexer.Index; - newItem.SubItemCount = this.SubItemCount; - newItem.Checked = this.Checked; - newItem.UseItemStyleForSubItems = this.UseItemStyleForSubItems; - newItem.Tag = this.Tag; + newItem.SubItemCount = SubItemCount; + newItem.Checked = Checked; + newItem.UseItemStyleForSubItems = UseItemStyleForSubItems; + newItem.Tag = Tag; // Only copy over the ImageKey if we're using it. if (!string.IsNullOrEmpty(ImageIndexer.Key)) @@ -905,14 +905,14 @@ public virtual object Clone() newItem.ImageIndexer.Key = ImageIndexer.Key; } - newItem.indentCount = this.indentCount; - newItem.StateImageIndex = this.StateImageIndex; - newItem.toolTipText = this.toolTipText; - newItem.BackColor = this.BackColor; - newItem.ForeColor = this.ForeColor; - newItem.Font = this.Font; - newItem.Text = this.Text; - newItem.Group = this.Group; + newItem.indentCount = indentCount; + newItem.StateImageIndex = StateImageIndex; + newItem.toolTipText = toolTipText; + newItem.BackColor = BackColor; + newItem.ForeColor = ForeColor; + newItem.Font = Font; + newItem.Text = Text; + newItem.Group = Group; return newItem; } @@ -966,7 +966,7 @@ public ListViewSubItem GetSubItemAt(int x, int y) if (listView != null && listView.IsHandleCreated && listView.View == View.Details) { listView.GetSubItemAt(x, y, out int iItem, out int iSubItem); - if (iItem == this.Index && iSubItem != -1 && iSubItem < SubItems.Count) + if (iItem == Index && iSubItem != -1 && iSubItem < SubItems.Count) { return SubItems[iSubItem]; } @@ -1187,7 +1187,7 @@ protected virtual void Deserialize(SerializationInfo info, StreamingContext cont else if (entry.Name == "Group") { ListViewGroup group = (ListViewGroup)info.GetValue(entry.Name, typeof(ListViewGroup)); - this.groupName = group.Name; + groupName = group.Name; } } @@ -1252,12 +1252,12 @@ internal void SetItemIndex(ListView listView, int index) Debug.Assert(listView != null && listView.VirtualMode, "ListViewItem::SetItemIndex should be used only when the list is virtual"); Debug.Assert(index > -1, "can't set the index on a virtual list view item to -1"); this.listView = listView; - this.lastIndex = index; + lastIndex = index; } internal bool ShouldSerializeText() => false; - private bool ShouldSerializePosition() => !this.position.Equals(new Point(-1, -1)); + private bool ShouldSerializePosition() => !position.Equals(new Point(-1, -1)); public override string ToString() => "ListViewItem: {" + Text + "}"; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs index 4a3a6f916b2..cb86d08d514 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs @@ -120,7 +120,7 @@ protected override CreateParams CreateParams SetState(STATE_ENABLED, false); } - if (this.RightToLeft == RightToLeft.Yes && this.ParentInternal != null && this.ParentInternal.IsMirrored) + if (RightToLeft == RightToLeft.Yes && ParentInternal != null && ParentInternal.IsMirrored) { //We want to turn on mirroring for MdiClient explicitly. cp.ExStyle |= NativeMethods.WS_EX_LAYOUTRTL | NativeMethods.WS_EX_NOINHERITLAYOUT; @@ -401,12 +401,12 @@ protected override void WndProc(ref Message m) internal override void OnInvokedSetScrollPosition(object sender, EventArgs e) { - Application.Idle += new EventHandler(this.OnIdle); //do this on idle (it must be mega-delayed). + Application.Idle += new EventHandler(OnIdle); //do this on idle (it must be mega-delayed). } private void OnIdle(object sender, EventArgs e) { - Application.Idle -= new EventHandler(this.OnIdle); + Application.Idle -= new EventHandler(OnIdle); base.OnInvokedSetScrollPosition(sender, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MDIControlStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MDIControlStrip.cs index 47512d23d54..00ecb9a6613 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MDIControlStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MDIControlStrip.cs @@ -52,9 +52,9 @@ public MdiControlStrip(IWin32Window target) } // add in opposite order to how you want it merged - this.Items.AddRange(new ToolStripItem[] { minimize, restore, close, system }); - this.SuspendLayout(); - foreach (ToolStripItem item in this.Items) + Items.AddRange(new ToolStripItem[] { minimize, restore, close, system }); + SuspendLayout(); + foreach (ToolStripItem item in Items) { item.DisplayStyle = ToolStripItemDisplayStyle.Image; item.MergeIndex = 0; @@ -77,7 +77,7 @@ public MdiControlStrip(IWin32Window target) system.DoubleClick += new EventHandler(OnSystemMenuDoubleClick); system.Padding = Padding.Empty; system.ShortcutKeys = Keys.Alt | Keys.OemMinus; - this.ResumeLayout(false); + ResumeLayout(false); } @@ -252,7 +252,7 @@ protected internal override bool ProcessCmdKey(ref Message m, Keys keyData) if (Visible && ShortcutKeys == keyData) { ShowDropDown(); - this.DropDown.SelectNextToolStripItem(null, true); + DropDown.SelectNextToolStripItem(null, true); return true; } return base.ProcessCmdKey(ref m, keyData); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MDIWindowDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MDIWindowDialog.cs index d916816648f..ef2e103b960 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MDIWindowDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MDIWindowDialog.cs @@ -101,64 +101,64 @@ private void ItemList_selectedIndexChanged(object source, EventArgs e) private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MdiWindowDialog)); - this.itemList = new System.Windows.Forms.ListBox(); - this.okButton = new System.Windows.Forms.Button(); - this.cancelButton = new System.Windows.Forms.Button(); - this.okCancelTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); - this.okCancelTableLayoutPanel.SuspendLayout(); - this.itemList.DoubleClick += new System.EventHandler(this.ItemList_doubleClick); - this.itemList.SelectedIndexChanged += new EventHandler(this.ItemList_selectedIndexChanged); - this.SuspendLayout(); + itemList = new System.Windows.Forms.ListBox(); + okButton = new System.Windows.Forms.Button(); + cancelButton = new System.Windows.Forms.Button(); + okCancelTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); + okCancelTableLayoutPanel.SuspendLayout(); + itemList.DoubleClick += new System.EventHandler(ItemList_doubleClick); + itemList.SelectedIndexChanged += new EventHandler(ItemList_selectedIndexChanged); + SuspendLayout(); // // itemList // - resources.ApplyResources(this.itemList, "itemList"); - this.itemList.FormattingEnabled = true; - this.itemList.Name = "itemList"; + resources.ApplyResources(itemList, "itemList"); + itemList.FormattingEnabled = true; + itemList.Name = "itemList"; // // okButton // - resources.ApplyResources(this.okButton, "okButton"); - this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; - this.okButton.Margin = new System.Windows.Forms.Padding(0, 0, 3, 0); - this.okButton.Name = "okButton"; + resources.ApplyResources(okButton, "okButton"); + okButton.DialogResult = System.Windows.Forms.DialogResult.OK; + okButton.Margin = new System.Windows.Forms.Padding(0, 0, 3, 0); + okButton.Name = "okButton"; // // cancelButton // - resources.ApplyResources(this.cancelButton, "cancelButton"); - this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.cancelButton.Margin = new System.Windows.Forms.Padding(3, 0, 0, 0); - this.cancelButton.Name = "cancelButton"; + resources.ApplyResources(cancelButton, "cancelButton"); + cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; + cancelButton.Margin = new System.Windows.Forms.Padding(3, 0, 0, 0); + cancelButton.Name = "cancelButton"; // // okCancelTableLayoutPanel // - resources.ApplyResources(this.okCancelTableLayoutPanel, "okCancelTableLayoutPanel"); - this.okCancelTableLayoutPanel.ColumnCount = 2; - this.okCancelTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); - this.okCancelTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); - this.okCancelTableLayoutPanel.Controls.Add(this.okButton, 0, 0); - this.okCancelTableLayoutPanel.Controls.Add(this.cancelButton, 1, 0); - this.okCancelTableLayoutPanel.Name = "okCancelTableLayoutPanel"; - this.okCancelTableLayoutPanel.RowCount = 1; - this.okCancelTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle()); + resources.ApplyResources(okCancelTableLayoutPanel, "okCancelTableLayoutPanel"); + okCancelTableLayoutPanel.ColumnCount = 2; + okCancelTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); + okCancelTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); + okCancelTableLayoutPanel.Controls.Add(okButton, 0, 0); + okCancelTableLayoutPanel.Controls.Add(cancelButton, 1, 0); + okCancelTableLayoutPanel.Name = "okCancelTableLayoutPanel"; + okCancelTableLayoutPanel.RowCount = 1; + okCancelTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle()); // // MdiWindowDialog // resources.ApplyResources(this, "$this"); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.Controls.Add(this.okCancelTableLayoutPanel); - this.Controls.Add(this.itemList); - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "MdiWindowDialog"; - this.ShowIcon = false; - this.okCancelTableLayoutPanel.ResumeLayout(false); - this.okCancelTableLayoutPanel.PerformLayout(); - this.AcceptButton = this.okButton; - this.CancelButton = this.cancelButton; - - this.ResumeLayout(false); - this.PerformLayout(); + AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + Controls.Add(okCancelTableLayoutPanel); + Controls.Add(itemList); + MaximizeBox = false; + MinimizeBox = false; + Name = "MdiWindowDialog"; + ShowIcon = false; + okCancelTableLayoutPanel.ResumeLayout(false); + okCancelTableLayoutPanel.PerformLayout(); + AcceptButton = okButton; + CancelButton = cancelButton; + + ResumeLayout(false); + PerformLayout(); } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs index 4c5ecb58fa3..a5ad87dc659 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs @@ -120,7 +120,7 @@ public class MaskedTextBox : TextBoxBase public MaskedTextBox() { MaskedTextProvider maskedTextProvider = new MaskedTextProvider(nullMask, CultureInfo.CurrentCulture); - this.flagState[IS_NULL_MASK] = true; + flagState[IS_NULL_MASK] = true; Initialize(maskedTextProvider); } @@ -135,7 +135,7 @@ public MaskedTextBox(string mask) } MaskedTextProvider maskedTextProvider = new MaskedTextProvider(mask, CultureInfo.CurrentCulture); - this.flagState[IS_NULL_MASK] = false; + flagState[IS_NULL_MASK] = false; Initialize(maskedTextProvider); } @@ -149,7 +149,7 @@ public MaskedTextBox(MaskedTextProvider maskedTextProvider) throw new ArgumentNullException(); } - this.flagState[IS_NULL_MASK] = false; + flagState[IS_NULL_MASK] = false; Initialize(maskedTextProvider); } @@ -164,28 +164,28 @@ private void Initialize(MaskedTextProvider maskedTextProvider) this.maskedTextProvider = maskedTextProvider; // set the initial display text. - if (!this.flagState[IS_NULL_MASK]) + if (!flagState[IS_NULL_MASK]) { SetWindowText(); } // set default values. - this.passwordChar = this.maskedTextProvider.PasswordChar; - this.insertMode = InsertKeyMode.Default; + passwordChar = this.maskedTextProvider.PasswordChar; + insertMode = InsertKeyMode.Default; - this.flagState[HIDE_PROMPT_ON_LEAVE] = false; - this.flagState[BEEP_ON_ERROR] = false; - this.flagState[USE_SYSTEM_PASSWORD_CHAR] = false; - this.flagState[REJECT_INPUT_ON_FIRST_FAILURE] = false; + flagState[HIDE_PROMPT_ON_LEAVE] = false; + flagState[BEEP_ON_ERROR] = false; + flagState[USE_SYSTEM_PASSWORD_CHAR] = false; + flagState[REJECT_INPUT_ON_FIRST_FAILURE] = false; // CutCopyMaskFormat - set same defaults as TextMaskFormat (IncludePromptAndLiterals). // It is a lot easier to handle this flags individually since that's the way the MaskedTextProvider does it. - this.flagState[CUTCOPYINCLUDEPROMPT] = this.maskedTextProvider.IncludePrompt; - this.flagState[CUTCOPYINCLUDELITERALS] = this.maskedTextProvider.IncludeLiterals; + flagState[CUTCOPYINCLUDEPROMPT] = this.maskedTextProvider.IncludePrompt; + flagState[CUTCOPYINCLUDELITERALS] = this.maskedTextProvider.IncludeLiterals; // fields for internal use. - this.flagState[HANDLE_KEY_PRESS] = true; - this.caretTestPos = 0; + flagState[HANDLE_KEY_PRESS] = true; + caretTestPos = 0; } @@ -221,20 +221,20 @@ public bool AllowPromptAsInput { get { - return this.maskedTextProvider.AllowPromptAsInput; + return maskedTextProvider.AllowPromptAsInput; } set { - if (value != this.maskedTextProvider.AllowPromptAsInput) + if (value != maskedTextProvider.AllowPromptAsInput) { // Recreate masked text provider since this property is read-only. MaskedTextProvider newProvider = new MaskedTextProvider( - this.maskedTextProvider.Mask, - this.maskedTextProvider.Culture, + maskedTextProvider.Mask, + maskedTextProvider.Culture, value, - this.maskedTextProvider.PromptChar, - this.maskedTextProvider.PasswordChar, - this.maskedTextProvider.AsciiOnly); + maskedTextProvider.PromptChar, + maskedTextProvider.PasswordChar, + maskedTextProvider.AsciiOnly); SetMaskedTextProvider(newProvider); } @@ -269,20 +269,20 @@ public bool AsciiOnly { get { - return this.maskedTextProvider.AsciiOnly; + return maskedTextProvider.AsciiOnly; } set { - if (value != this.maskedTextProvider.AsciiOnly) + if (value != maskedTextProvider.AsciiOnly) { // Recreate masked text provider since this property is read-only. MaskedTextProvider newProvider = new MaskedTextProvider( - this.maskedTextProvider.Mask, - this.maskedTextProvider.Culture, - this.maskedTextProvider.AllowPromptAsInput, - this.maskedTextProvider.PromptChar, - this.maskedTextProvider.PasswordChar, + maskedTextProvider.Mask, + maskedTextProvider.Culture, + maskedTextProvider.AllowPromptAsInput, + maskedTextProvider.PromptChar, + maskedTextProvider.PasswordChar, value); SetMaskedTextProvider(newProvider); @@ -302,11 +302,11 @@ public bool BeepOnError { get { - return this.flagState[BEEP_ON_ERROR]; + return flagState[BEEP_ON_ERROR]; } set { - this.flagState[BEEP_ON_ERROR] = value; + flagState[BEEP_ON_ERROR] = value; } } @@ -373,7 +373,7 @@ public CultureInfo Culture { get { - return this.maskedTextProvider.Culture; + return maskedTextProvider.Culture; } set @@ -383,16 +383,16 @@ public CultureInfo Culture throw new ArgumentNullException(); } - if (!this.maskedTextProvider.Culture.Equals(value)) + if (!maskedTextProvider.Culture.Equals(value)) { // Recreate masked text provider since this property is read-only. MaskedTextProvider newProvider = new MaskedTextProvider( - this.maskedTextProvider.Mask, + maskedTextProvider.Mask, value, - this.maskedTextProvider.AllowPromptAsInput, - this.maskedTextProvider.PromptChar, - this.maskedTextProvider.PasswordChar, - this.maskedTextProvider.AsciiOnly); + maskedTextProvider.AllowPromptAsInput, + maskedTextProvider.PromptChar, + maskedTextProvider.PasswordChar, + maskedTextProvider.AsciiOnly); SetMaskedTextProvider(newProvider); } @@ -414,9 +414,9 @@ public MaskFormat CutCopyMaskFormat { get { - if (this.flagState[CUTCOPYINCLUDEPROMPT]) + if (flagState[CUTCOPYINCLUDEPROMPT]) { - if (this.flagState[CUTCOPYINCLUDELITERALS]) + if (flagState[CUTCOPYINCLUDELITERALS]) { return MaskFormat.IncludePromptAndLiterals; } @@ -424,7 +424,7 @@ public MaskFormat CutCopyMaskFormat return MaskFormat.IncludePrompt; } - if (this.flagState[CUTCOPYINCLUDELITERALS]) + if (flagState[CUTCOPYINCLUDELITERALS]) { return MaskFormat.IncludeLiterals; } @@ -442,19 +442,19 @@ public MaskFormat CutCopyMaskFormat if (value == MaskFormat.IncludePrompt) { - this.flagState[CUTCOPYINCLUDEPROMPT] = true; - this.flagState[CUTCOPYINCLUDELITERALS] = false; + flagState[CUTCOPYINCLUDEPROMPT] = true; + flagState[CUTCOPYINCLUDELITERALS] = false; } else if (value == MaskFormat.IncludeLiterals) { - this.flagState[CUTCOPYINCLUDEPROMPT] = false; - this.flagState[CUTCOPYINCLUDELITERALS] = true; + flagState[CUTCOPYINCLUDEPROMPT] = false; + flagState[CUTCOPYINCLUDELITERALS] = true; } else // value == MaskFormat.IncludePromptAndLiterals || value == MaskFormat.ExcludePromptAndLiterals { bool include = value == MaskFormat.IncludePromptAndLiterals; - this.flagState[CUTCOPYINCLUDEPROMPT] = include; - this.flagState[CUTCOPYINCLUDELITERALS] = include; + flagState[CUTCOPYINCLUDEPROMPT] = include; + flagState[CUTCOPYINCLUDELITERALS] = include; } } } @@ -470,12 +470,12 @@ public IFormatProvider FormatProvider { get { - return this.formatProvider; + return formatProvider; } set { - this.formatProvider = value; + formatProvider = value; } } @@ -492,17 +492,17 @@ public bool HidePromptOnLeave { get { - return this.flagState[HIDE_PROMPT_ON_LEAVE]; + return flagState[HIDE_PROMPT_ON_LEAVE]; } set { - if (this.flagState[HIDE_PROMPT_ON_LEAVE] != value) + if (flagState[HIDE_PROMPT_ON_LEAVE] != value) { - this.flagState[HIDE_PROMPT_ON_LEAVE] = value; + flagState[HIDE_PROMPT_ON_LEAVE] = value; // If the control is not focused and there are available edit positions (mask not full) we need to // update the displayed text. - if (!this.flagState[IS_NULL_MASK] && !this.Focused && !this.MaskFull && !this.DesignMode) + if (!flagState[IS_NULL_MASK] && !Focused && !MaskFull && !DesignMode) { SetWindowText(); } @@ -517,11 +517,11 @@ private bool IncludeLiterals { get { - return this.maskedTextProvider.IncludeLiterals; + return maskedTextProvider.IncludeLiterals; } set { - this.maskedTextProvider.IncludeLiterals = value; + maskedTextProvider.IncludeLiterals = value; } } @@ -533,11 +533,11 @@ private bool IncludePrompt { get { - return this.maskedTextProvider.IncludePrompt; + return maskedTextProvider.IncludePrompt; } set { - this.maskedTextProvider.IncludePrompt = value; + maskedTextProvider.IncludePrompt = value; } } @@ -555,7 +555,7 @@ public InsertKeyMode InsertKeyMode { get { - return this.insertMode; + return insertMode; } set { @@ -565,12 +565,12 @@ public InsertKeyMode InsertKeyMode throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(InsertKeyMode)); } - if (this.insertMode != value) + if (insertMode != value) { - bool isOverwrite = this.IsOverwriteMode; - this.insertMode = value; + bool isOverwrite = IsOverwriteMode; + insertMode = value; - if (isOverwrite != this.IsOverwriteMode) + if (isOverwrite != IsOverwriteMode) { OnIsOverwriteModeChanged(EventArgs.Empty); } @@ -600,12 +600,12 @@ public bool IsOverwriteMode { get { - if (this.flagState[IS_NULL_MASK]) + if (flagState[IS_NULL_MASK]) { return false; // EditBox always inserts. } - switch (this.insertMode) + switch (insertMode) { case InsertKeyMode.Overwrite: return true; @@ -619,7 +619,7 @@ public bool IsOverwriteMode // behavior of apps like WinWord, WordPad and VS; so we have to keep track of it and not query its // system value. //return Control.IsKeyLocked(Keys.Insert); - return this.flagState[INSERT_TOGGLED]; + return flagState[INSERT_TOGGLED]; default: Debug.Fail("Invalid InsertKeyMode. This code path should have never been executed."); @@ -656,14 +656,14 @@ public event EventHandler IsOverwriteModeChanged { string[] lines; - this.flagState[QUERY_BASE_TEXT] = true; + flagState[QUERY_BASE_TEXT] = true; try { lines = base.Lines; } finally { - this.flagState[QUERY_BASE_TEXT] = false; + flagState[QUERY_BASE_TEXT] = false; } return lines; @@ -689,7 +689,7 @@ public string Mask { get { - return this.flagState[IS_NULL_MASK] ? string.Empty : this.maskedTextProvider.Mask; + return flagState[IS_NULL_MASK] ? string.Empty : maskedTextProvider.Mask; } set { @@ -698,7 +698,7 @@ public string Mask // 1. IsNullOrEmpty( value )->[Reset control] && this.flagState[IS_NULL_MASK]==>Already Reset. // 2. !IsNullOrEmpty( value )->[Set control] && !this.flagState[IS_NULL_MASK][control is set] && [value is the same]==>No need to update. // - if (this.flagState[IS_NULL_MASK] == string.IsNullOrEmpty(value) && (this.flagState[IS_NULL_MASK] || value == this.maskedTextProvider.Mask)) + if (flagState[IS_NULL_MASK] == string.IsNullOrEmpty(value) && (flagState[IS_NULL_MASK] || value == maskedTextProvider.Mask)) { return; } @@ -714,13 +714,13 @@ public string Mask // Need to get the formatted & unformatted text before resetting the mask, they'll be used to determine whether we need to // raise the TextChanged event. string formattedText = TextOutput; - string unformattedText = this.maskedTextProvider.ToString(false, false); + string unformattedText = maskedTextProvider.ToString(false, false); - this.flagState[IS_NULL_MASK] = true; + flagState[IS_NULL_MASK] = true; - if (this.maskedTextProvider.IsPassword) + if (maskedTextProvider.IsPassword) { - SetEditControlPasswordChar(this.maskedTextProvider.PasswordChar); + SetEditControlPasswordChar(maskedTextProvider.PasswordChar); } // Set the window text to the unformatted text before raising events. Also, TextChanged needs to be raised after MaskChanged so @@ -749,24 +749,24 @@ public string Mask } } - if (this.flagState[IS_NULL_MASK]) + if (flagState[IS_NULL_MASK]) { // If this.IsNullMask, we are setting the mask to a new value; in this case we need to get the text because // the underlying MTP does not have it (used as a property backend only) and pass it to SetMaskedTextProvider // method below to update the provider. - text = this.Text; + text = Text; } } // Recreate masked text provider since this property is read-only. MaskedTextProvider newProvider = new MaskedTextProvider( newMask, - this.maskedTextProvider.Culture, - this.maskedTextProvider.AllowPromptAsInput, - this.maskedTextProvider.PromptChar, - this.maskedTextProvider.PasswordChar, - this.maskedTextProvider.AsciiOnly); + maskedTextProvider.Culture, + maskedTextProvider.AllowPromptAsInput, + maskedTextProvider.PromptChar, + maskedTextProvider.PasswordChar, + maskedTextProvider.AsciiOnly); //text == null when setting to a different mask value or when resetting the mask to null. //text != null only when setting the mask from null to some value. @@ -798,7 +798,7 @@ public bool MaskCompleted { get { - return this.maskedTextProvider.MaskCompleted; + return maskedTextProvider.MaskCompleted; } } @@ -812,7 +812,7 @@ public bool MaskFull { get { - return this.maskedTextProvider.MaskFull; + return maskedTextProvider.MaskFull; } } @@ -829,7 +829,7 @@ public MaskedTextProvider MaskedTextProvider { get { - return this.flagState[IS_NULL_MASK] ? null : (MaskedTextProvider)this.maskedTextProvider.Clone(); + return flagState[IS_NULL_MASK] ? null : (MaskedTextProvider)maskedTextProvider.Clone(); } } @@ -907,7 +907,7 @@ public char PasswordChar { // The password char could be the one set in the control or the system password char, // in any case the maskedTextProvider has the correct one. - return this.maskedTextProvider.PasswordChar; + return maskedTextProvider.PasswordChar; } set { @@ -917,22 +917,22 @@ public char PasswordChar throw new ArgumentException(SR.MaskedTextBoxInvalidCharError); } - if (this.passwordChar != value) + if (passwordChar != value) { - if (value == this.maskedTextProvider.PromptChar) + if (value == maskedTextProvider.PromptChar) { // Prompt and password chars must be different. throw new InvalidOperationException(SR.MaskedTextBoxPasswordAndPromptCharError); } - this.passwordChar = value; + passwordChar = value; // UseSystemPasswordChar take precedence over PasswordChar...Let's check. - if (!this.UseSystemPasswordChar) + if (!UseSystemPasswordChar) { - this.maskedTextProvider.PasswordChar = value; + maskedTextProvider.PasswordChar = value; - if (this.flagState[IS_NULL_MASK]) + if (flagState[IS_NULL_MASK]) { SetEditControlPasswordChar(value); } @@ -954,9 +954,9 @@ internal override bool PasswordProtect { get { - if (this.maskedTextProvider != null) // could be queried during object construction. + if (maskedTextProvider != null) // could be queried during object construction. { - return this.maskedTextProvider.IsPassword; + return maskedTextProvider.IsPassword; } return base.PasswordProtect; } @@ -976,7 +976,7 @@ public char PromptChar { get { - return this.maskedTextProvider.PromptChar; + return maskedTextProvider.PromptChar; } set { @@ -986,10 +986,10 @@ public char PromptChar throw new ArgumentException(SR.MaskedTextBoxInvalidCharError); } - if (this.maskedTextProvider.PromptChar != value) + if (maskedTextProvider.PromptChar != value) { // We need to check maskedTextProvider password char in case it is using the system password. - if (value == this.passwordChar || value == this.maskedTextProvider.PasswordChar) + if (value == passwordChar || value == maskedTextProvider.PasswordChar) { // Prompt and password chars must be different. throw new InvalidOperationException(SR.MaskedTextBoxPasswordAndPromptCharError); @@ -997,12 +997,12 @@ public char PromptChar // Recreate masked text provider to be consistent with AllowPromptAsInput - current text may have chars with same value as new prompt. MaskedTextProvider newProvider = new MaskedTextProvider( - this.maskedTextProvider.Mask, - this.maskedTextProvider.Culture, - this.maskedTextProvider.AllowPromptAsInput, + maskedTextProvider.Mask, + maskedTextProvider.Culture, + maskedTextProvider.AllowPromptAsInput, value, - this.maskedTextProvider.PasswordChar, - this.maskedTextProvider.AsciiOnly); + maskedTextProvider.PasswordChar, + maskedTextProvider.AsciiOnly); SetMaskedTextProvider(newProvider); } @@ -1021,12 +1021,12 @@ public char PromptChar set { - if (this.ReadOnly != value) + if (ReadOnly != value) { // if true, this disables IME in the base class. base.ReadOnly = value; - if (!this.flagState[IS_NULL_MASK]) + if (!flagState[IS_NULL_MASK]) { // Prompt will be hidden. SetWindowText(); @@ -1048,11 +1048,11 @@ public bool RejectInputOnFirstFailure { get { - return this.flagState[REJECT_INPUT_ON_FIRST_FAILURE]; + return flagState[REJECT_INPUT_ON_FIRST_FAILURE]; } set { - this.flagState[REJECT_INPUT_ON_FIRST_FAILURE] = value; + flagState[REJECT_INPUT_ON_FIRST_FAILURE] = value; } } @@ -1080,11 +1080,11 @@ public bool ResetOnPrompt { get { - return this.maskedTextProvider.ResetOnPrompt; + return maskedTextProvider.ResetOnPrompt; } set { - this.maskedTextProvider.ResetOnPrompt = value; + maskedTextProvider.ResetOnPrompt = value; } } @@ -1101,11 +1101,11 @@ public bool ResetOnSpace { get { - return this.maskedTextProvider.ResetOnSpace; + return maskedTextProvider.ResetOnSpace; } set { - this.maskedTextProvider.ResetOnSpace = value; + maskedTextProvider.ResetOnSpace = value; } } @@ -1122,11 +1122,11 @@ public bool SkipLiterals { get { - return this.maskedTextProvider.SkipLiterals; + return maskedTextProvider.SkipLiterals; } set { - this.maskedTextProvider.SkipLiterals = value; + maskedTextProvider.SkipLiterals = value; } } @@ -1137,7 +1137,7 @@ public override string SelectedText { get { - if (this.flagState[IS_NULL_MASK]) + if (flagState[IS_NULL_MASK]) { return base.SelectedText; } @@ -1152,7 +1152,7 @@ public override string SelectedText internal override void SetSelectedTextInternal(string value, bool clearUndo) { - if (this.flagState[IS_NULL_MASK]) + if (flagState[IS_NULL_MASK]) { base.SetSelectedTextInternal(value, true); // Operates as a regular text box base. return; @@ -1166,7 +1166,7 @@ internal override void SetSelectedTextInternal(string value, bool clearUndo) /// private void ImeComplete() { - this.flagState[IME_COMPLETING] = true; + flagState[IME_COMPLETING] = true; ImeNotify(NativeMethods.CPS_COMPLETE); } @@ -1175,7 +1175,7 @@ private void ImeComplete() /// private void ImeNotify(int action) { - HandleRef handle = new HandleRef(this, this.Handle); + HandleRef handle = new HandleRef(this, Handle); IntPtr inputContext = UnsafeNativeMethods.ImmGetContext(handle); if (inputContext != IntPtr.Zero) @@ -1201,7 +1201,7 @@ private void ImeNotify(int action) /// private void SetEditControlPasswordChar(char pwdChar) { - if (this.IsHandleCreated) + if (IsHandleCreated) { // This message does not return a value. SendMessage(Interop.EditMessages.EM_SETPASSWORDCHAR, pwdChar, 0); @@ -1251,7 +1251,7 @@ public override string Text { get { - if (this.flagState[IS_NULL_MASK] || this.flagState[QUERY_BASE_TEXT]) + if (flagState[IS_NULL_MASK] || flagState[QUERY_BASE_TEXT]) { return base.Text; } @@ -1260,7 +1260,7 @@ public override string Text } set { - if (this.flagState[IS_NULL_MASK]) + if (flagState[IS_NULL_MASK]) { base.Text = value; return; @@ -1269,31 +1269,31 @@ public override string Text if (string.IsNullOrEmpty(value)) { // reset the input text. - Delete(Keys.Delete, 0, this.maskedTextProvider.Length); + Delete(Keys.Delete, 0, maskedTextProvider.Length); } else { - if (this.RejectInputOnFirstFailure) + if (RejectInputOnFirstFailure) { MaskedTextResultHint hint; string oldText = TextOutput; - if (this.maskedTextProvider.Set(value, out this.caretTestPos, out hint)) + if (maskedTextProvider.Set(value, out caretTestPos, out hint)) { //if( hint == MaskedTextResultHint.Success || hint == MaskedTextResultHint.SideEffect ) if (TextOutput != oldText) { SetText(); } - this.SelectionStart = ++this.caretTestPos; + SelectionStart = ++caretTestPos; } else { - OnMaskInputRejected(new MaskInputRejectedEventArgs(this.caretTestPos, hint)); + OnMaskInputRejected(new MaskInputRejectedEventArgs(caretTestPos, hint)); } } else { - Replace(value, /*startPosition*/ 0, /*selectionLen*/ this.maskedTextProvider.Length); + Replace(value, /*startPosition*/ 0, /*selectionLen*/ maskedTextProvider.Length); } } } @@ -1307,7 +1307,7 @@ public override int TextLength { get { - if (this.flagState[IS_NULL_MASK]) + if (flagState[IS_NULL_MASK]) { return base.TextLength; } @@ -1330,8 +1330,8 @@ private string TextOutput { get { - Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); - return this.maskedTextProvider.ToString(); + Debug.Assert(!flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); + return maskedTextProvider.ToString(); } } @@ -1398,9 +1398,9 @@ public MaskFormat TextMaskFormat { get { - if (this.IncludePrompt) + if (IncludePrompt) { - if (this.IncludeLiterals) + if (IncludeLiterals) { return MaskFormat.IncludePromptAndLiterals; } @@ -1408,7 +1408,7 @@ public MaskFormat TextMaskFormat return MaskFormat.IncludePrompt; } - if (this.IncludeLiterals) + if (IncludeLiterals) { return MaskFormat.IncludeLiterals; } @@ -1418,7 +1418,7 @@ public MaskFormat TextMaskFormat set { - if (this.TextMaskFormat == value) + if (TextMaskFormat == value) { return; } @@ -1431,23 +1431,23 @@ public MaskFormat TextMaskFormat // Changing the TextMaskFormat will likely change the 'output' text (Text getter value). Cache old value to // verify it against the new value and raise OnTextChange if needed. - string oldText = this.flagState[IS_NULL_MASK] ? null : TextOutput; + string oldText = flagState[IS_NULL_MASK] ? null : TextOutput; if (value == MaskFormat.IncludePrompt) { - this.IncludePrompt = true; - this.IncludeLiterals = false; + IncludePrompt = true; + IncludeLiterals = false; } else if (value == MaskFormat.IncludeLiterals) { - this.IncludePrompt = false; - this.IncludeLiterals = true; + IncludePrompt = false; + IncludeLiterals = true; } else // value == MaskFormat.IncludePromptAndLiterals || value == MaskFormat.ExcludePromptAndLiterals { bool include = value == MaskFormat.IncludePromptAndLiterals; - this.IncludePrompt = include; - this.IncludeLiterals = include; + IncludePrompt = include; + IncludeLiterals = include; } if (oldText != null && oldText != TextOutput) @@ -1463,24 +1463,24 @@ public MaskFormat TextMaskFormat /// public override string ToString() { - if (this.flagState[IS_NULL_MASK]) + if (flagState[IS_NULL_MASK]) { return base.ToString(); } // base.ToString will call Text, we want to always display prompt and literals. - bool includePrompt = this.IncludePrompt; - bool includeLits = this.IncludeLiterals; + bool includePrompt = IncludePrompt; + bool includeLits = IncludeLiterals; string str; try { - this.IncludePrompt = this.IncludeLiterals = true; + IncludePrompt = IncludeLiterals = true; str = base.ToString(); } finally { - this.IncludePrompt = includePrompt; - this.IncludeLiterals = includeLits; + IncludePrompt = includePrompt; + IncludeLiterals = includeLits; } return str; @@ -1513,33 +1513,33 @@ public bool UseSystemPasswordChar { get { - return this.flagState[USE_SYSTEM_PASSWORD_CHAR]; + return flagState[USE_SYSTEM_PASSWORD_CHAR]; } set { - if (value != this.flagState[USE_SYSTEM_PASSWORD_CHAR]) + if (value != flagState[USE_SYSTEM_PASSWORD_CHAR]) { if (value) { - if (this.SystemPasswordChar == this.PromptChar) + if (SystemPasswordChar == PromptChar) { // Prompt and password chars must be different. throw new InvalidOperationException(SR.MaskedTextBoxPasswordAndPromptCharError); } - this.maskedTextProvider.PasswordChar = this.SystemPasswordChar; + maskedTextProvider.PasswordChar = SystemPasswordChar; } else { // this.passwordChar could be '\0', in which case we are resetting the display to show the input char. - this.maskedTextProvider.PasswordChar = this.passwordChar; + maskedTextProvider.PasswordChar = passwordChar; } - this.flagState[USE_SYSTEM_PASSWORD_CHAR] = value; + flagState[USE_SYSTEM_PASSWORD_CHAR] = value; - if (this.flagState[IS_NULL_MASK]) + if (flagState[IS_NULL_MASK]) { - SetEditControlPasswordChar(this.maskedTextProvider.PasswordChar); + SetEditControlPasswordChar(maskedTextProvider.PasswordChar); } else { @@ -1566,13 +1566,13 @@ public Type ValidatingType { get { - return this.validatingType; + return validatingType; } set { - if (this.validatingType != value) + if (validatingType != value) { - this.validatingType = value; + validatingType = value; } } } @@ -1616,7 +1616,7 @@ public Type ValidatingType ] protected override void CreateHandle() { - if (!this.flagState[IS_NULL_MASK] && RecreatingHandle) + if (!flagState[IS_NULL_MASK] && RecreatingHandle) { // update cached text value in Control. Don't preserve caret, cannot query for selection start at this time. SetWindowText(GetFormattedDisplayString(), false, false); @@ -1632,14 +1632,14 @@ protected override void CreateHandle() /// private void Delete(Keys keyCode, int startPosition, int selectionLen) { - Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); + Debug.Assert(!flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); Debug.Assert(keyCode == Keys.Delete || keyCode == Keys.Back, "Delete called with keyCode == " + keyCode.ToString()); - Debug.Assert(startPosition >= 0 && ((startPosition + selectionLen) <= this.maskedTextProvider.Length), "Invalid position range."); + Debug.Assert(startPosition >= 0 && ((startPosition + selectionLen) <= maskedTextProvider.Length), "Invalid position range."); // On backspace, moving the start postion back by one has the same effect as delete. If text is selected, there is no // need for moving the position back. - this.caretTestPos = startPosition; + caretTestPos = startPosition; if (selectionLen == 0) { @@ -1654,7 +1654,7 @@ private void Delete(Keys keyCode, int startPosition, int selectionLen) } else // (keyCode == Keys.Delete) { - if ((startPosition + selectionLen) == this.maskedTextProvider.Length) // At end of string, delete does nothing. + if ((startPosition + selectionLen) == maskedTextProvider.Length) // At end of string, delete does nothing. { return; } @@ -1666,13 +1666,13 @@ private void Delete(Keys keyCode, int startPosition, int selectionLen) MaskedTextResultHint hint; string oldText = TextOutput; - if (this.maskedTextProvider.RemoveAt(startPosition, endPos, out tempPos, out hint)) + if (maskedTextProvider.RemoveAt(startPosition, endPos, out tempPos, out hint)) { //if( hint == MaskedTextResultHint.Success || hint == MaskedTextResultHint.SideEffect) // Text was changed. if (TextOutput != oldText) { SetText(); - this.caretTestPos = startPosition; + caretTestPos = startPosition; } else { @@ -1686,7 +1686,7 @@ private void Delete(Keys keyCode, int startPosition, int selectionLen) if (selectionLen > 0) { - this.caretTestPos = startPosition; + caretTestPos = startPosition; } else { @@ -1694,39 +1694,39 @@ private void Delete(Keys keyCode, int startPosition, int selectionLen) { if (keyCode == Keys.Delete) { - this.caretTestPos = this.maskedTextProvider.FindEditPositionFrom(startPosition, forward); + caretTestPos = maskedTextProvider.FindEditPositionFrom(startPosition, forward); } else { - if (this.maskedTextProvider.FindAssignedEditPositionFrom(startPosition, forward) == MaskedTextProvider.InvalidIndex) + if (maskedTextProvider.FindAssignedEditPositionFrom(startPosition, forward) == MaskedTextProvider.InvalidIndex) { // No assigned position at the right, nothing to shift then move to the next assigned position at the // left (if any). - this.caretTestPos = this.maskedTextProvider.FindAssignedEditPositionFrom(startPosition, backward); + caretTestPos = maskedTextProvider.FindAssignedEditPositionFrom(startPosition, backward); } else { // there are assigned positions at the right so move to an edit position at the left to get ready for // removing the character on it or just shifting the characters at the right - this.caretTestPos = this.maskedTextProvider.FindEditPositionFrom(startPosition, backward); + caretTestPos = maskedTextProvider.FindEditPositionFrom(startPosition, backward); } - if (this.caretTestPos != MaskedTextProvider.InvalidIndex) + if (caretTestPos != MaskedTextProvider.InvalidIndex) { - this.caretTestPos++; // backspace gets ready to remove one position past the edit position. + caretTestPos++; // backspace gets ready to remove one position past the edit position. } } - if (this.caretTestPos == MaskedTextProvider.InvalidIndex) + if (caretTestPos == MaskedTextProvider.InvalidIndex) { - this.caretTestPos = startPosition; + caretTestPos = startPosition; } } else // (hint == MaskedTextProvider.OperationHint.SideEffect) { if (keyCode == Keys.Back) // Case 3. { - this.caretTestPos = startPosition; + caretTestPos = startPosition; } } } @@ -1740,7 +1740,7 @@ private void Delete(Keys keyCode, int startPosition, int selectionLen) // Reposition caret. Call base.SelectInternal for perf reasons. //this.SelectionLength = 0; //this.SelectionStart = this.caretTestPos; // new caret position. - base.SelectInternal(this.caretTestPos, 0, this.maskedTextProvider.Length); + base.SelectInternal(caretTestPos, 0, maskedTextProvider.Length); return; } @@ -1752,14 +1752,14 @@ public override char GetCharFromPosition(Point pt) { char ch; - this.flagState[QUERY_BASE_TEXT] = true; + flagState[QUERY_BASE_TEXT] = true; try { ch = base.GetCharFromPosition(pt); } finally { - this.flagState[QUERY_BASE_TEXT] = false; + flagState[QUERY_BASE_TEXT] = false; } return ch; } @@ -1772,14 +1772,14 @@ public override int GetCharIndexFromPosition(Point pt) { int index; - this.flagState[QUERY_BASE_TEXT] = true; + flagState[QUERY_BASE_TEXT] = true; try { index = base.GetCharIndexFromPosition(pt); } finally { - this.flagState[QUERY_BASE_TEXT] = false; + flagState[QUERY_BASE_TEXT] = false; } return index; } @@ -1790,16 +1790,16 @@ public override int GetCharIndexFromPosition(Point pt) /// internal override int GetEndPosition() { - if (this.flagState[IS_NULL_MASK]) + if (flagState[IS_NULL_MASK]) { return base.GetEndPosition(); } - int pos = this.maskedTextProvider.FindEditPositionFrom(this.maskedTextProvider.LastAssignedPosition + 1, forward); + int pos = maskedTextProvider.FindEditPositionFrom(maskedTextProvider.LastAssignedPosition + 1, forward); if (pos == MaskedTextProvider.InvalidIndex) { - pos = this.maskedTextProvider.LastAssignedPosition + 1; + pos = maskedTextProvider.LastAssignedPosition + 1; } return pos; @@ -1833,24 +1833,24 @@ internal override int GetEndPosition() /// private string GetFormattedDisplayString() { - Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); + Debug.Assert(!flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); bool includePrompt; - if (this.ReadOnly) // Always hide prompt. + if (ReadOnly) // Always hide prompt. { includePrompt = false; } - else if (this.DesignMode) // Not RO and at design time, always show prompt. + else if (DesignMode) // Not RO and at design time, always show prompt. { includePrompt = true; } else // follow HidePromptOnLeave property. { - includePrompt = !(this.HidePromptOnLeave && !this.Focused); + includePrompt = !(HidePromptOnLeave && !Focused); } - return this.maskedTextProvider.ToString(/*ignorePwdChar */ false, includePrompt, /*includeLiterals*/ true, 0, this.maskedTextProvider.Length); + return maskedTextProvider.ToString(/*ignorePwdChar */ false, includePrompt, /*includeLiterals*/ true, 0, maskedTextProvider.Length); } /// @@ -1872,14 +1872,14 @@ public override Point GetPositionFromCharIndex(int index) { Point pos; - this.flagState[QUERY_BASE_TEXT] = true; + flagState[QUERY_BASE_TEXT] = true; try { pos = base.GetPositionFromCharIndex(index); } finally { - this.flagState[QUERY_BASE_TEXT] = false; + flagState[QUERY_BASE_TEXT] = false; } return pos; } @@ -1892,14 +1892,14 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) { Size size; - this.flagState[QUERY_BASE_TEXT] = true; + flagState[QUERY_BASE_TEXT] = true; try { size = base.GetPreferredSizeCore(proposedConstraints); } finally { - this.flagState[QUERY_BASE_TEXT] = false; + flagState[QUERY_BASE_TEXT] = false; } return size; } @@ -1911,7 +1911,7 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) /// private string GetSelectedText() { - Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); + Debug.Assert(!flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); int selStart, selLength; base.GetSelectionStartAndLength(out selStart, out selLength); @@ -1924,7 +1924,7 @@ private string GetSelectedText() bool includePrompt = (CutCopyMaskFormat & MaskFormat.IncludePrompt) != 0; bool includeLiterals = (CutCopyMaskFormat & MaskFormat.IncludeLiterals) != 0; - return this.maskedTextProvider.ToString( /*ignorePasswordChar*/ true, includePrompt, includeLiterals, selStart, selLength); + return maskedTextProvider.ToString( /*ignorePasswordChar*/ true, includePrompt, includeLiterals, selStart, selLength); } @@ -1932,9 +1932,9 @@ protected override void OnBackColorChanged(EventArgs e) { base.OnBackColorChanged(e); // Force repainting of the entire window frame - if (Application.RenderWithVisualStyles && this.IsHandleCreated && this.BorderStyle == BorderStyle.Fixed3D) + if (Application.RenderWithVisualStyles && IsHandleCreated && BorderStyle == BorderStyle.Fixed3D) { - SafeNativeMethods.RedrawWindow(new HandleRef(this, this.Handle), null, NativeMethods.NullHandleRef, NativeMethods.RDW_INVALIDATE | NativeMethods.RDW_FRAME); + SafeNativeMethods.RedrawWindow(new HandleRef(this, Handle), null, NativeMethods.NullHandleRef, NativeMethods.RDW_INVALIDATE | NativeMethods.RDW_FRAME); } } @@ -1947,9 +1947,9 @@ protected override void OnHandleCreated(EventArgs e) base.OnHandleCreated(e); base.SetSelectionOnHandle(); - if (this.flagState[IS_NULL_MASK] && this.maskedTextProvider.IsPassword) + if (flagState[IS_NULL_MASK] && maskedTextProvider.IsPassword) { - SetEditControlPasswordChar(this.maskedTextProvider.PasswordChar); + SetEditControlPasswordChar(maskedTextProvider.PasswordChar); } } @@ -1976,7 +1976,7 @@ protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); - if (this.flagState[IS_NULL_MASK]) + if (flagState[IS_NULL_MASK]) { // Operates as a regular text box base. return; @@ -1987,15 +1987,15 @@ protected override void OnKeyDown(KeyEventArgs e) // Special-case Return & Esc since they generate invalid characters we should not process OnKeyPress. if (keyCode == Keys.Return || keyCode == Keys.Escape) { - this.flagState[HANDLE_KEY_PRESS] = false; + flagState[HANDLE_KEY_PRESS] = false; } // Insert is toggled when not modified with some other key (ctrl, shift...). Note that shift-Insert is // same as paste. - if (keyCode == Keys.Insert && e.Modifiers == Keys.None && this.insertMode == InsertKeyMode.Default) + if (keyCode == Keys.Insert && e.Modifiers == Keys.None && insertMode == InsertKeyMode.Default) { - this.flagState[INSERT_TOGGLED] = !this.flagState[INSERT_TOGGLED]; + flagState[INSERT_TOGGLED] = !flagState[INSERT_TOGGLED]; OnIsOverwriteModeChanged(EventArgs.Empty); return; } @@ -2023,14 +2023,14 @@ protected override void OnKeyDown(KeyEventArgs e) // Next OnKeyPress should not be handled to allow Ctrl- to be processed in the // base class so corresponding messages can be generated (WM_CUT/WM_COPY/WM_PASTE). // Combined characters don't generate OnKeyDown by themselves but they generate OnKeyPress. - this.flagState[HANDLE_KEY_PRESS] = false; + flagState[HANDLE_KEY_PRESS] = false; return; } } if (keyCode == Keys.Delete || keyCode == Keys.Back) // Deletion keys. { - if (!this.ReadOnly) + if (!ReadOnly) { int selectionLen; int startPosition; @@ -2051,20 +2051,20 @@ protected override void OnKeyDown(KeyEventArgs e) { if (keyCode == Keys.Delete) // delete to the end of the string. { - selectionLen = this.maskedTextProvider.Length - startPosition; + selectionLen = maskedTextProvider.Length - startPosition; } else // ( keyCode == Keys.Back ) // delete to the beginning of the string. { - selectionLen = startPosition == this.maskedTextProvider.Length /*at end of text*/ ? startPosition : startPosition + 1; + selectionLen = startPosition == maskedTextProvider.Length /*at end of text*/ ? startPosition : startPosition + 1; startPosition = 0; } } goto default; default: - if (!this.flagState[HANDLE_KEY_PRESS]) + if (!flagState[HANDLE_KEY_PRESS]) { - this.flagState[HANDLE_KEY_PRESS] = true; + flagState[HANDLE_KEY_PRESS] = true; } break; } @@ -2109,16 +2109,16 @@ protected override void OnKeyPress(KeyPressEventArgs e) { base.OnKeyPress(e); - if (this.flagState[IS_NULL_MASK]) + if (flagState[IS_NULL_MASK]) { // Operates as a regular text box base. return; } // This key may be a combined key involving a letter, like Ctrl-A; let the native control handle it. - if (!this.flagState[HANDLE_KEY_PRESS]) + if (!flagState[HANDLE_KEY_PRESS]) { - this.flagState[HANDLE_KEY_PRESS] = true; + flagState[HANDLE_KEY_PRESS] = true; // When the combined key involves a letter, the final character is not a letter. There are some // Ctrl combined keys that generate a letter and can be confusing; we do not mean to pass those @@ -2129,7 +2129,7 @@ protected override void OnKeyPress(KeyPressEventArgs e) } } - if (!this.ReadOnly) + if (!ReadOnly) { // At this point the character needs to be processed ... @@ -2141,7 +2141,7 @@ protected override void OnKeyPress(KeyPressEventArgs e) base.GetSelectionStartAndLength(out selectionStart, out selectionLen); string oldText = TextOutput; - if (PlaceChar(e.KeyChar, selectionStart, selectionLen, this.IsOverwriteMode, out hint)) + if (PlaceChar(e.KeyChar, selectionStart, selectionLen, IsOverwriteMode, out hint)) { //if( hint == MaskedTextResultHint.Success || hint == MaskedTextResultHint.SideEffect ) if (TextOutput != oldText) @@ -2149,14 +2149,14 @@ protected override void OnKeyPress(KeyPressEventArgs e) SetText(); // Now set the text in the display. } - this.SelectionStart = ++this.caretTestPos; // caretTestPos is updated in PlaceChar. + SelectionStart = ++caretTestPos; // caretTestPos is updated in PlaceChar. if (ImeModeConversion.InputLanguageTable == ImeModeConversion.KoreanTable) { // Korean IMEs complete composition when a character has been fully converted, so the composition string // is only one-character long; once composed we block the IME if there ins't more room in the test string. - int editPos = this.maskedTextProvider.FindUnassignedEditPositionFrom(this.caretTestPos, forward); + int editPos = maskedTextProvider.FindUnassignedEditPositionFrom(caretTestPos, forward); if (editPos == MaskedTextProvider.InvalidIndex) { ImeComplete(); // Force completion of compostion. @@ -2165,12 +2165,12 @@ protected override void OnKeyPress(KeyPressEventArgs e) } else { - OnMaskInputRejected(new MaskInputRejectedEventArgs(this.caretTestPos, hint)); // caretTestPos is updated in PlaceChar. + OnMaskInputRejected(new MaskInputRejectedEventArgs(caretTestPos, hint)); // caretTestPos is updated in PlaceChar. } if (selectionLen > 0) { - this.SelectionLength = 0; + SelectionLength = 0; } e.Handled = true; @@ -2186,14 +2186,14 @@ protected override void OnKeyUp(KeyEventArgs e) // KeyUp is the last message to be processed so it is the best place to reset these flags. - if (this.flagState[IME_COMPLETING]) + if (flagState[IME_COMPLETING]) { - this.flagState[IME_COMPLETING] = false; + flagState[IME_COMPLETING] = false; } - if (this.flagState[IME_ENDING_COMPOSITION]) + if (flagState[IME_ENDING_COMPOSITION]) { - this.flagState[IME_ENDING_COMPOSITION] = false; + flagState[IME_ENDING_COMPOSITION] = false; } } @@ -2218,9 +2218,9 @@ protected virtual void OnMaskChanged(EventArgs e) /// private void OnMaskInputRejected(MaskInputRejectedEventArgs e) { - Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); + Debug.Assert(!flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); - if (this.BeepOnError) + if (BeepOnError) { System.Media.SoundPlayer sp = new System.Media.SoundPlayer(); sp.Play(); @@ -2293,15 +2293,15 @@ protected override void OnTextChanged(EventArgs e) { // A text changed event handler will most likely query for the Text value, we need to return the // formatted one. - bool queryBaseText = this.flagState[QUERY_BASE_TEXT]; - this.flagState[QUERY_BASE_TEXT] = false; + bool queryBaseText = flagState[QUERY_BASE_TEXT]; + flagState[QUERY_BASE_TEXT] = false; try { base.OnTextChanged(e); } finally { - this.flagState[QUERY_BASE_TEXT] = queryBaseText; + flagState[QUERY_BASE_TEXT] = queryBaseText; } } /// @@ -2310,17 +2310,17 @@ protected override void OnTextChanged(EventArgs e) /// private void Replace(string text, int startPosition, int selectionLen) { - Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); + Debug.Assert(!flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); Debug.Assert(text != null, "text is null."); // Clone the MaskedTextProvider so text properties are not modified until the paste operation is // completed. This is needed in case one of these properties is retreived in a MaskedInputRejected // event handler (clipboard text is attempted to be set into the input text char by char). - MaskedTextProvider clonedProvider = (MaskedTextProvider)this.maskedTextProvider.Clone(); + MaskedTextProvider clonedProvider = (MaskedTextProvider)maskedTextProvider.Clone(); // Cache the current caret position so we restore it in case the text does not change. - int currentCaretPos = this.caretTestPos; + int currentCaretPos = caretTestPos; // First replace characters in the selection (if any and if any edit positions) until completed, or the test position falls // outside the selection range, or there's no more room in the test string for editable characters. @@ -2329,17 +2329,17 @@ private void Replace(string text, int startPosition, int selectionLen) MaskedTextResultHint hint = MaskedTextResultHint.NoEffect; int endPos = startPosition + selectionLen - 1; - if (this.RejectInputOnFirstFailure) + if (RejectInputOnFirstFailure) { bool succeeded; succeeded = (startPosition > endPos) ? - clonedProvider.InsertAt(text, startPosition, out this.caretTestPos, out hint) : - clonedProvider.Replace(text, startPosition, endPos, out this.caretTestPos, out hint); + clonedProvider.InsertAt(text, startPosition, out caretTestPos, out hint) : + clonedProvider.Replace(text, startPosition, endPos, out caretTestPos, out hint); if (!succeeded) { - OnMaskInputRejected(new MaskInputRejectedEventArgs(this.caretTestPos, hint)); + OnMaskInputRejected(new MaskInputRejectedEventArgs(caretTestPos, hint)); } } else @@ -2350,7 +2350,7 @@ private void Replace(string text, int startPosition, int selectionLen) foreach (char ch in text) { - if (!this.maskedTextProvider.VerifyEscapeChar(ch, startPosition)) // char won't be escaped, find and edit position for it. + if (!maskedTextProvider.VerifyEscapeChar(ch, startPosition)) // char won't be escaped, find and edit position for it. { // Observe that we look for a position w/o respecting the selection length, because the input text could be larger than // the number of edit positions in the selection. @@ -2374,7 +2374,7 @@ private void Replace(string text, int startPosition, int selectionLen) if (PlaceChar(clonedProvider, ch, startPosition, length, replace, out tempHint)) { // caretTestPos is updated in PlaceChar call. - startPosition = this.caretTestPos + 1; + startPosition = caretTestPos + 1; // place char will insert or replace a single character so the hint must be success, and that will be the final operation // result hint. @@ -2396,9 +2396,9 @@ private void Replace(string text, int startPosition, int selectionLen) if (startPosition <= endPos) { - if (!clonedProvider.RemoveAt(startPosition, endPos, out this.caretTestPos, out tempHint)) + if (!clonedProvider.RemoveAt(startPosition, endPos, out caretTestPos, out tempHint)) { - OnMaskInputRejected(new MaskInputRejectedEventArgs(this.caretTestPos, tempHint)); + OnMaskInputRejected(new MaskInputRejectedEventArgs(caretTestPos, tempHint)); } // If 'replace' is not actually performed (maybe the input is empty which means 'remove', hint will be whatever @@ -2414,7 +2414,7 @@ private void Replace(string text, int startPosition, int selectionLen) bool updateText = TextOutput != clonedProvider.ToString(); // Always set the mtp, the formatted text could be the same but the assigned positions may be different. - this.maskedTextProvider = clonedProvider; + maskedTextProvider = clonedProvider; // Update text if needed. if (updateText) @@ -2422,12 +2422,12 @@ private void Replace(string text, int startPosition, int selectionLen) SetText(); // Update caret position. - this.caretTestPos = startPosition; - base.SelectInternal(this.caretTestPos, 0, this.maskedTextProvider.Length); + caretTestPos = startPosition; + base.SelectInternal(caretTestPos, 0, maskedTextProvider.Length); } else { - this.caretTestPos = currentCaretPos; + caretTestPos = currentCaretPos; } return; @@ -2440,7 +2440,7 @@ private void Replace(string text, int startPosition, int selectionLen) /// private void PasteInt(string text) { - Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); + Debug.Assert(!flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); int selStart, selLength; base.GetSelectionStartAndLength(out selStart, out selLength); @@ -2468,11 +2468,11 @@ private object PerformTypeValidation(CancelEventArgs e) { object parseRetVal = null; - if (this.validatingType != null) + if (validatingType != null) { string message = null; - if (!this.flagState[IS_NULL_MASK] && this.maskedTextProvider.MaskCompleted == false) + if (!flagState[IS_NULL_MASK] && maskedTextProvider.MaskCompleted == false) { message = SR.MaskedTextBoxIncompleteMsg; } @@ -2480,9 +2480,9 @@ private object PerformTypeValidation(CancelEventArgs e) { string textValue; - if (!this.flagState[IS_NULL_MASK]) // replace prompt with space. + if (!flagState[IS_NULL_MASK]) // replace prompt with space. { - textValue = this.maskedTextProvider.ToString(/*includePrompt*/ false, this.IncludeLiterals); + textValue = maskedTextProvider.ToString(/*includePrompt*/ false, IncludeLiterals); } else { @@ -2493,13 +2493,13 @@ private object PerformTypeValidation(CancelEventArgs e) { parseRetVal = Formatter.ParseObject( textValue, // data - this.validatingType, // targetType + validatingType, // targetType typeof(string), // sourceType null, // targetConverter null, // sourceConverter - this.formatProvider, // formatInfo + formatProvider, // formatInfo null, // nullValue - Formatter.GetDefaultDataSourceNullValue(this.validatingType)); // dataSourceNullValue + Formatter.GetDefaultDataSourceNullValue(validatingType)); // dataSourceNullValue } catch (Exception exception) { @@ -2524,7 +2524,7 @@ private object PerformTypeValidation(CancelEventArgs e) message = SR.MaskedTextBoxTypeValidationSucceeded; } - TypeValidationEventArgs tve = new TypeValidationEventArgs(this.validatingType, isValidInput, parseRetVal, message); + TypeValidationEventArgs tve = new TypeValidationEventArgs(validatingType, isValidInput, parseRetVal, message); OnTypeValidationCompleted(tve); if (e != null) @@ -2543,7 +2543,7 @@ private object PerformTypeValidation(CancelEventArgs e) private bool PlaceChar(char ch, int startPosition, int length, bool overwrite, out MaskedTextResultHint hint) { - return PlaceChar(this.maskedTextProvider, ch, startPosition, length, overwrite, out hint); + return PlaceChar(maskedTextProvider, ch, startPosition, length, overwrite, out hint); } /// @@ -2552,27 +2552,27 @@ private bool PlaceChar(char ch, int startPosition, int length, bool overwrite, private bool PlaceChar(MaskedTextProvider provider, char ch, int startPosition, int length, bool overwrite, out MaskedTextResultHint hint) { - Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); + Debug.Assert(!flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); - this.caretTestPos = startPosition; + caretTestPos = startPosition; - if (startPosition < this.maskedTextProvider.Length) + if (startPosition < maskedTextProvider.Length) { if (length > 0) // Replacing selection with input char. { int endPos = startPosition + length - 1; - return provider.Replace(ch, startPosition, endPos, out this.caretTestPos, out hint); + return provider.Replace(ch, startPosition, endPos, out caretTestPos, out hint); } else { if (overwrite) { // overwrite character at next edit position from startPosition (inclusive). - return provider.Replace(ch, startPosition, out this.caretTestPos, out hint); + return provider.Replace(ch, startPosition, out caretTestPos, out hint); } else // insert. { - return provider.InsertAt(ch, startPosition, out this.caretTestPos, out hint); + return provider.InsertAt(ch, startPosition, out caretTestPos, out hint); } } } @@ -2638,7 +2638,7 @@ protected internal override bool ProcessKeyMessage(ref Message m) bool msgProcessed = base.ProcessKeyMessage(ref m); - if (this.flagState[IS_NULL_MASK]) + if (flagState[IS_NULL_MASK]) { return msgProcessed; // Operates as a regular text box base. } @@ -2660,7 +2660,7 @@ protected internal override bool ProcessKeyMessage(ref Message m) /// private void ResetCulture() { - this.Culture = CultureInfo.CurrentCulture; + Culture = CultureInfo.CurrentCulture; } /// @@ -2692,24 +2692,24 @@ private void SetMaskedTextProvider(MaskedTextProvider newProvider, string textOn Debug.Assert(newProvider != null, "Initializing from a null MaskProvider ref."); // Set R/W properties. - newProvider.IncludePrompt = this.maskedTextProvider.IncludePrompt; - newProvider.IncludeLiterals = this.maskedTextProvider.IncludeLiterals; - newProvider.SkipLiterals = this.maskedTextProvider.SkipLiterals; - newProvider.ResetOnPrompt = this.maskedTextProvider.ResetOnPrompt; - newProvider.ResetOnSpace = this.maskedTextProvider.ResetOnSpace; + newProvider.IncludePrompt = maskedTextProvider.IncludePrompt; + newProvider.IncludeLiterals = maskedTextProvider.IncludeLiterals; + newProvider.SkipLiterals = maskedTextProvider.SkipLiterals; + newProvider.ResetOnPrompt = maskedTextProvider.ResetOnPrompt; + newProvider.ResetOnSpace = maskedTextProvider.ResetOnSpace; // If mask not initialized and not initializing it, the new provider is just a property backend. // Change won't have any effect in text. - if (this.flagState[IS_NULL_MASK] && textOnInitializingMask == null) + if (flagState[IS_NULL_MASK] && textOnInitializingMask == null) { - this.maskedTextProvider = newProvider; + maskedTextProvider = newProvider; return; } int testPos = 0; bool raiseOnMaskInputRejected = false; // Raise if new provider rejects old text. MaskedTextResultHint hint = MaskedTextResultHint.NoEffect; - MaskedTextProvider oldProvider = this.maskedTextProvider; + MaskedTextProvider oldProvider = maskedTextProvider; // Attempt to add previous text. // If the mask is the same, we need to preserve the caret and character positions if the text is added successfully. @@ -2775,11 +2775,11 @@ private void SetMaskedTextProvider(MaskedTextProvider newProvider, string textOn // Set provider. - this.maskedTextProvider = newProvider; + maskedTextProvider = newProvider; - if (this.flagState[IS_NULL_MASK]) + if (flagState[IS_NULL_MASK]) { - this.flagState[IS_NULL_MASK] = false; + flagState[IS_NULL_MASK] = false; } // Raising events need to be done only after the new provider has been set so the MTB is in a state where properties @@ -2836,13 +2836,13 @@ private void SetWindowText() /// private void SetWindowText(string text, bool raiseTextChangedEvent, bool preserveCaret) { - this.flagState[QUERY_BASE_TEXT] = true; + flagState[QUERY_BASE_TEXT] = true; try { if (preserveCaret) { - this.caretTestPos = this.SelectionStart; + caretTestPos = SelectionStart; } WindowText = text; // this calls Win32::SetWindowText directly, no OnTextChanged raised. @@ -2854,12 +2854,12 @@ private void SetWindowText(string text, bool raiseTextChangedEvent, bool preserv if (preserveCaret) { - this.SelectionStart = this.caretTestPos; + SelectionStart = caretTestPos; } } finally { - this.flagState[QUERY_BASE_TEXT] = false; + flagState[QUERY_BASE_TEXT] = false; } } @@ -2868,7 +2868,7 @@ private void SetWindowText(string text, bool raiseTextChangedEvent, bool preserv /// private bool ShouldSerializeCulture() { - return !CultureInfo.CurrentCulture.Equals(this.Culture); + return !CultureInfo.CurrentCulture.Equals(Culture); } /// @@ -2896,9 +2896,9 @@ public object ValidateText() /// private bool WmClear() { - Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); + Debug.Assert(!flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); - if (!this.ReadOnly) + if (!ReadOnly) { int selStart, selLength; base.GetSelectionStartAndLength(out selStart, out selLength); @@ -2916,9 +2916,9 @@ private bool WmClear() /// private bool WmCopy() { - Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); + Debug.Assert(!flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); - if (this.maskedTextProvider.IsPassword) // cannot copy password to clipboard. + if (maskedTextProvider.IsPassword) // cannot copy password to clipboard. { return false; } @@ -2957,13 +2957,13 @@ private bool WmCopy() /// private bool WmImeComposition(ref Message m) { - Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); + Debug.Assert(!flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); #if DEBUG - if (this.ReadOnly || this.maskedTextProvider.IsPassword) + if (ReadOnly || maskedTextProvider.IsPassword) { // This should have been already handled by the ReadOnly, PasswordChar and ImeMode properties. - Debug.Assert(this.ImeMode == ImeMode.Disable, "IME enabled when in RO or Pwd mode."); + Debug.Assert(ImeMode == ImeMode.Disable, "IME enabled when in RO or Pwd mode."); } #endif // Non-Korean IMEs complete compositon when all characters in the string has been composed (when user hits enter); @@ -2989,10 +2989,10 @@ private bool WmImeComposition(ref Message m) // Process any update in the composition string. if (imeConvertionType != imeConvertionNone) { - if (this.flagState[IME_ENDING_COMPOSITION]) + if (flagState[IME_ENDING_COMPOSITION]) { // If IME is completing the convertion, we don't want to process further characters. - return this.flagState[IME_COMPLETING]; + return flagState[IME_COMPLETING]; } } } @@ -3006,14 +3006,14 @@ private bool WmImeComposition(ref Message m) /// private bool WmImeStartComposition() { - Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); + Debug.Assert(!flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); // Position the composition window in a valid place. int startPosition, selectionLen; base.GetSelectionStartAndLength(out startPosition, out selectionLen); - int startEditPos = this.maskedTextProvider.FindEditPositionFrom(startPosition, forward); + int startEditPos = maskedTextProvider.FindEditPositionFrom(startPosition, forward); if (startEditPos != MaskedTextProvider.InvalidIndex) { @@ -3023,7 +3023,7 @@ private bool WmImeStartComposition() // character only, otherwise it would overwrite the selection with the caret (composition string), // deleting a portion of the mask. - int endEditPos = this.maskedTextProvider.FindEditPositionFrom(startPosition + selectionLen - 1, backward); + int endEditPos = maskedTextProvider.FindEditPositionFrom(startPosition + selectionLen - 1, backward); if (endEditPos >= startEditPos) { @@ -3041,11 +3041,11 @@ private bool WmImeStartComposition() // update caret position. if (startPosition != startEditPos) { - this.caretTestPos = startEditPos; - this.SelectionStart = this.caretTestPos; + caretTestPos = startEditPos; + SelectionStart = caretTestPos; } - this.SelectionLength = 0; + SelectionLength = 0; } else { @@ -3065,9 +3065,9 @@ private bool WmImeStartComposition() /// private void WmPaste() { - Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); + Debug.Assert(!flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); - if (this.ReadOnly) + if (ReadOnly) { return; } @@ -3096,11 +3096,11 @@ private void WmPaste() private void WmPrint(ref Message m) { base.WndProc(ref m); - if ((NativeMethods.PRF_NONCLIENT & unchecked((int)(long)m.LParam)) != 0 && Application.RenderWithVisualStyles && this.BorderStyle == BorderStyle.Fixed3D) + if ((NativeMethods.PRF_NONCLIENT & unchecked((int)(long)m.LParam)) != 0 && Application.RenderWithVisualStyles && BorderStyle == BorderStyle.Fixed3D) { using (Graphics g = Graphics.FromHdc(m.WParam)) { - Rectangle rect = new Rectangle(0, 0, this.Size.Width - 1, this.Size.Height - 1); + Rectangle rect = new Rectangle(0, 0, Size.Width - 1, Size.Height - 1); using (Pen pen = new Pen(VisualStyleInformation.TextControlBorder)) { g.DrawRectangle(pen, rect); @@ -3139,7 +3139,7 @@ protected override void WndProc(ref Message m) break; // continue. } - if (this.flagState[IS_NULL_MASK]) + if (flagState[IS_NULL_MASK]) { base.WndProc(ref m); // Operates as a regular text box base. return; @@ -3155,7 +3155,7 @@ protected override void WndProc(ref Message m) goto default; case Interop.WindowMessages.WM_IME_ENDCOMPOSITION: - this.flagState[IME_ENDING_COMPOSITION] = true; + flagState[IME_ENDING_COMPOSITION] = true; goto default; case Interop.WindowMessages.WM_IME_COMPOSITION: @@ -3166,7 +3166,7 @@ protected override void WndProc(ref Message m) goto default; case Interop.WindowMessages.WM_CUT: - if (!this.ReadOnly && WmCopy()) + if (!ReadOnly && WmCopy()) { WmClear(); } @@ -3205,16 +3205,16 @@ protected override void WndProc(ref Message m) /// private void WmKillFocus() { - Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); + Debug.Assert(!flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); - base.GetSelectionStartAndLength(out this.caretTestPos, out this.lastSelLength); + base.GetSelectionStartAndLength(out caretTestPos, out lastSelLength); - if (this.HidePromptOnLeave && !this.MaskFull) + if (HidePromptOnLeave && !MaskFull) { SetWindowText(); // Update text w/ no prompt. // We need to update selection info in case the control is queried for it while it doesn't have the focus. - base.SelectInternal(this.caretTestPos, this.lastSelLength, this.maskedTextProvider.Length); + base.SelectInternal(caretTestPos, lastSelLength, maskedTextProvider.Length); } } @@ -3224,16 +3224,16 @@ private void WmKillFocus() /// private void WmSetFocus() { - Debug.Assert(!this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); + Debug.Assert(!flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); - if (this.HidePromptOnLeave && !this.MaskFull) // Prompt will show up. + if (HidePromptOnLeave && !MaskFull) // Prompt will show up. { SetWindowText(); } // Restore previous selection. Do this always (as opposed to within the condition above as in WmKillFocus) // because HidePromptOnLeave could have changed while the control did not have the focus. - base.SelectInternal(this.caretTestPos, this.lastSelLength, this.maskedTextProvider.Length); + base.SelectInternal(caretTestPos, lastSelLength, maskedTextProvider.Length); } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListStrip.cs index ff7724d72d2..7a16497eb52 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListStrip.cs @@ -47,7 +47,7 @@ internal ToolStripMenuItem MergeItem if (mergeItem.Owner == null) { - this.Items.Add(mergeItem); + Items.Add(mergeItem); } return mergeItem; } @@ -76,7 +76,7 @@ internal MenuStrip MergedMenu public void PopulateItems(Form mdiParent, ToolStripMenuItem mdiMergeItem, bool includeSeparator) { this.mdiParent = mdiParent; - this.SuspendLayout(); + SuspendLayout(); MergeItem.DropDown.SuspendLayout(); try { @@ -150,7 +150,7 @@ public void PopulateItems(Form mdiParent, ToolStripMenuItem mdiMergeItem, bool i finally { // this is an invisible toolstrip dont even bother doing layout. - this.ResumeLayout(false); + ResumeLayout(false); MergeItem.DropDown.ResumeLayout(false); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs index 8e6a19a6a4b..b36b38815e2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs @@ -324,7 +324,7 @@ protected override void Dispose(bool disposing) if (handle != IntPtr.Zero) { UnsafeNativeMethods.DestroyMenu(new HandleRef(this, handle)); - this.handle = IntPtr.Zero; + handle = IntPtr.Zero; if (disposing) { ClearHandles(); @@ -1088,7 +1088,7 @@ public virtual int IndexOfKey(string key) } // step 2 - search for the item - for (int i = 0; i < this.Count; i++) + for (int i = 0; i < Count; i++) { if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { @@ -1120,7 +1120,7 @@ void IList.Insert(int index, object value) /// private bool IsValidIndex(int index) { - return ((index >= 0) && (index < this.Count)); + return ((index >= 0) && (index < Count)); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MenuStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MenuStrip.cs index a98791c5d98..b9397635c22 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MenuStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MenuStrip.cs @@ -29,9 +29,9 @@ public class MenuStrip : ToolStrip public MenuStrip() { - this.CanOverflow = false; - this.GripStyle = ToolStripGripStyle.Hidden; - this.Stretch = true; + CanOverflow = false; + GripStyle = ToolStripGripStyle.Hidden; + Stretch = true; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs index 2972a61c70c..846b329129d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs @@ -209,7 +209,7 @@ public DateTime[] AnnuallyBoldedDates for (int i = 0; i < annualArrayOfDates.Count; ++i) { - dateTimes[i] = (DateTime)this.annualArrayOfDates[i]; + dateTimes[i] = (DateTime)annualArrayOfDates[i]; } return dateTimes; } @@ -219,7 +219,7 @@ public DateTime[] AnnuallyBoldedDates - this.annualArrayOfDates.Clear(); + annualArrayOfDates.Clear(); for (int i = 0; i < MONTHS_IN_YEAR; ++i) monthsOfYear[i] = 0; @@ -229,7 +229,7 @@ public DateTime[] AnnuallyBoldedDates //add each boldeddate to our ArrayList... for (int i = 0; i < value.Length; i++) { - this.annualArrayOfDates.Add(value[i]); + annualArrayOfDates.Add(value[i]); } for (int i = 0; i < value.Length; ++i) @@ -318,7 +318,7 @@ public DateTime[] BoldedDates for (int i = 0; i < arrayOfDates.Count; ++i) { - dateTimes[i] = (DateTime)this.arrayOfDates[i]; + dateTimes[i] = (DateTime)arrayOfDates[i]; } return dateTimes; } @@ -328,14 +328,14 @@ public DateTime[] BoldedDates - this.arrayOfDates.Clear(); + arrayOfDates.Clear(); if (value != null && value.Length > 0) { //add each boldeddate to our ArrayList... for (int i = 0; i < value.Length; i++) { - this.arrayOfDates.Add(value[i]); + arrayOfDates.Add(value[i]); } } @@ -360,7 +360,7 @@ public Size CalendarDimensions } set { - if (!this.dimensions.Equals(value)) + if (!dimensions.Equals(value)) SetCalendarDimensions(value.Width, value.Height); } } @@ -633,7 +633,7 @@ public DateTime[] MonthlyBoldedDates for (int i = 0; i < monthlyArrayOfDates.Count; ++i) { - dateTimes[i] = (DateTime)this.monthlyArrayOfDates[i]; + dateTimes[i] = (DateTime)monthlyArrayOfDates[i]; } return dateTimes; } @@ -643,7 +643,7 @@ public DateTime[] MonthlyBoldedDates - this.monthlyArrayOfDates.Clear(); + monthlyArrayOfDates.Clear(); datesToBoldMonthly = 0; if (value != null && value.Length > 0) @@ -652,7 +652,7 @@ public DateTime[] MonthlyBoldedDates //add each boldeddate to our ArrayList... for (int i = 0; i < value.Length; i++) { - this.monthlyArrayOfDates.Add(value[i]); + monthlyArrayOfDates.Add(value[i]); } for (int i = 0; i < value.Length; ++i) @@ -1205,9 +1205,9 @@ public void AddAnnuallyBoldedDate(DateTime date) /// public void AddBoldedDate(DateTime date) { - if (!this.arrayOfDates.Contains(date)) + if (!arrayOfDates.Contains(date)) { - this.arrayOfDates.Add(date); + arrayOfDates.Add(date); } } @@ -1217,7 +1217,7 @@ public void AddBoldedDate(DateTime date) /// public void AddMonthlyBoldedDate(DateTime date) { - this.monthlyArrayOfDates.Add(date); + monthlyArrayOfDates.Add(date); datesToBoldMonthly |= 0x00000001 << (date.Day - 1); } @@ -1450,7 +1450,7 @@ private Size GetMinReqRect(int newDimensionLength, bool updateRows, bool updateC // Calculate calendar height // Size textExtent; - using (WindowsFont font = WindowsFont.FromFont(this.Font)) + using (WindowsFont font = WindowsFont.FromFont(Font)) { // this is the string that Windows uses to determine the extent of the today string textExtent = WindowsGraphicsCacheManager.MeasurementGraphics.GetTextExtent(DateTime.Now.ToShortDateString(), font); @@ -1469,14 +1469,14 @@ private Size GetMinReqRect(int newDimensionLength, bool updateRows, bool updateC { Debug.Assert(calendarHeight > INSERT_HEIGHT_SIZE, "Divide by 0"); int nRows = (newDimensionLength - todayHeight + INSERT_HEIGHT_SIZE) / (calendarHeight + INSERT_HEIGHT_SIZE); - this.dimensions.Height = (nRows < 1) ? 1 : nRows; + dimensions.Height = (nRows < 1) ? 1 : nRows; } if (updateCols) { Debug.Assert(minSize.Width > INSERT_WIDTH_SIZE, "Divide by 0"); int nCols = (newDimensionLength - scaledExtraPadding) / minSize.Width; - this.dimensions.Width = (nCols < 1) ? 1 : nCols; + dimensions.Width = (nCols < 1) ? 1 : nCols; } minSize.Width = (minSize.Width + INSERT_WIDTH_SIZE) * dimensions.Width - INSERT_WIDTH_SIZE; @@ -1647,7 +1647,7 @@ protected override void OnHandleCreated(EventArgs e) SendMessage(NativeMethods.MCM_SETMONTHDELTA, scrollChange, 0); } - SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(this.MarshaledUserPreferenceChanged); + SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(MarshaledUserPreferenceChanged); } @@ -1656,7 +1656,7 @@ protected override void OnHandleCreated(EventArgs e) /// protected override void OnHandleDestroyed(EventArgs e) { - SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(this.MarshaledUserPreferenceChanged); + SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(MarshaledUserPreferenceChanged); base.OnHandleDestroyed(e); } @@ -1728,7 +1728,7 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) /// public void RemoveAllAnnuallyBoldedDates() { - this.annualArrayOfDates.Clear(); + annualArrayOfDates.Clear(); for (int i = 0; i < MONTHS_IN_YEAR; ++i) monthsOfYear[i] = 0; } @@ -1739,7 +1739,7 @@ public void RemoveAllAnnuallyBoldedDates() /// public void RemoveAllBoldedDates() { - this.arrayOfDates.Clear(); + arrayOfDates.Clear(); } /// @@ -1747,7 +1747,7 @@ public void RemoveAllBoldedDates() /// public void RemoveAllMonthlyBoldedDates() { - this.monthlyArrayOfDates.Clear(); + monthlyArrayOfDates.Clear(); datesToBoldMonthly = 0; } @@ -2068,8 +2068,8 @@ public void SetCalendarDimensions(int x, int y) if (dimensions.Width != x || dimensions.Height != y) { - this.dimensions.Width = x; - this.dimensions.Height = y; + dimensions.Width = x; + dimensions.Height = y; AdjustSize(); } } @@ -2301,7 +2301,7 @@ private void MarshaledUserPreferenceChanged(object sender, UserPreferenceChanged try { //use begininvoke instead of invoke in case the destination thread is not processing messages. - BeginInvoke(new UserPreferenceChangedEventHandler(this.UserPreferenceChanged), new object[] { sender, pref }); + BeginInvoke(new UserPreferenceChangedEventHandler(UserPreferenceChanged), new object[] { sender, pref }); } catch (InvalidOperationException) { } //if the destination thread does not exist, don't send. } @@ -2475,8 +2475,8 @@ public sealed class HitTestInfo /// internal HitTestInfo(Point pt, HitArea area, DateTime time) { - this.point = pt; - this.hitArea = area; + point = pt; + hitArea = area; this.time = time; } @@ -2485,8 +2485,8 @@ internal HitTestInfo(Point pt, HitArea area, DateTime time) /// internal HitTestInfo(Point pt, HitArea area) { - this.point = pt; - this.hitArea = area; + point = pt; + hitArea = area; } /// @@ -2698,9 +2698,9 @@ public override string Name name = string.Format(SR.MonthCalendarRangeSelected, calendar.SelectionStart.ToLongDateString(), calendar.SelectionEnd.ToLongDateString()); } } - else if (this.calendar.mcCurView == NativeMethods.MONTCALENDAR_VIEW_MODE.MCMV_YEAR) + else if (calendar.mcCurView == NativeMethods.MONTCALENDAR_VIEW_MODE.MCMV_YEAR) { - if (System.DateTime.Equals(this.calendar.SelectionStart.Month, this.calendar.SelectionEnd.Month)) + if (System.DateTime.Equals(calendar.SelectionStart.Month, calendar.SelectionEnd.Month)) { name = string.Format(SR.MonthCalendarSingleDateSelected, calendar.SelectionStart.ToString("y")); } @@ -2749,9 +2749,9 @@ public override string Value value = string.Format("{0} - {1}", calendar.SelectionStart.ToLongDateString(), calendar.SelectionEnd.ToLongDateString()); } } - else if (this.calendar.mcCurView == NativeMethods.MONTCALENDAR_VIEW_MODE.MCMV_YEAR) + else if (calendar.mcCurView == NativeMethods.MONTCALENDAR_VIEW_MODE.MCMV_YEAR) { - if (System.DateTime.Equals(this.calendar.SelectionStart.Month, this.calendar.SelectionEnd.Month)) + if (System.DateTime.Equals(calendar.SelectionStart.Month, calendar.SelectionEnd.Month)) { value = calendar.SelectionStart.ToString("y"); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs index 83b13dc5377..79be8ed7799 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs @@ -658,12 +658,12 @@ internal void AssignHandle(IntPtr handle, bool assignUniqueID) if (WndProcShouldBeDebuggable) { Debug.WriteLineIf(WndProcChoice.TraceVerbose, "Using debuggable wndproc"); - windowProc = new NativeMethods.WndProc(this.DebuggableCallback); + windowProc = new NativeMethods.WndProc(DebuggableCallback); } else { Debug.WriteLineIf(WndProcChoice.TraceVerbose, "Using normal wndproc"); - windowProc = new NativeMethods.WndProc(this.Callback); + windowProc = new NativeMethods.WndProc(Callback); } AddWindowToTable(handle, this); @@ -763,7 +763,7 @@ public virtual void CreateHandle(CreateParams cp) // If a message comes through (say a WM_ACTIVATE for the parent) which // causes the handle to be created, we can try to create the handle twice // for NativeWindow. Check the handle again t avoid this. - if (this.handle != IntPtr.Zero) + if (handle != IntPtr.Zero) { return; } @@ -773,7 +773,7 @@ public virtual void CreateHandle(CreateParams cp) // Parking window dpi awarness context need to match with dpi awarenss context of control being // parented to this parkign window. Otherwise, reparenting of control will fail. - using (DpiHelper.EnterDpiAwarenessScope(this.windowDpiAwarenessContext)) + using (DpiHelper.EnterDpiAwarenessScope(windowDpiAwarenessContext)) { IntPtr modHandle = UnsafeNativeMethods.GetModuleHandle(null); @@ -1732,7 +1732,7 @@ private void RegisterClass() // our window class name. This way our static table always matches what Win32 thinks. // windowClassName = GetFullClassName(localClassName); - windowProc = new NativeMethods.WndProc(this.Callback); + windowProc = new NativeMethods.WndProc(Callback); wndclass.lpfnWndProc = windowProc; wndclass.hInstance = UnsafeNativeMethods.GetModuleHandle(null); wndclass.lpszClassName = windowClassName; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs index 3320d1c4f00..b450bf2e299 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs @@ -231,7 +231,7 @@ public ContextMenu ContextMenu set { - this.contextMenu = value; + contextMenu = value; } } @@ -249,7 +249,7 @@ public ContextMenuStrip ContextMenuStrip set { - this.contextMenuStrip = value; + contextMenuStrip = value; } } @@ -275,7 +275,7 @@ public Icon Icon { if (icon != value) { - this.icon = value; + icon = value; UpdateIcon(visible); } } @@ -304,13 +304,13 @@ public string Text { if (value == null) value = string.Empty; - if (value != null && !value.Equals(this.text)) + if (value != null && !value.Equals(text)) { if (value != null && value.Length > 63) { throw new ArgumentOutOfRangeException(nameof(Text), value, string.Format(SR.TrayIcon_TextTooLong)); } - this.text = value; + text = value; if (added) { UpdateIcon(true); @@ -458,8 +458,8 @@ protected override void Dispose(bool disposing) { if (window != null) { - this.icon = null; - this.Text = string.Empty; + icon = null; + Text = string.Empty; UpdateIcon(false); window.DestroyHandle(); window = null; @@ -636,7 +636,7 @@ private void OnMouseUp(MouseEventArgs e) /// public void ShowBalloonTip(int timeout) { - ShowBalloonTip(timeout, this.balloonTipTitle, this.balloonTipText, this.balloonTipIcon); + ShowBalloonTip(timeout, balloonTipTitle, balloonTipText, balloonTipIcon); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDown.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDown.cs index e5483e1fd18..b04dc549530 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDown.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDown.cs @@ -113,11 +113,11 @@ public NumericUpDownAccelerationCollection Accelerations { get { - if (this.accelerations == null) + if (accelerations == null) { - this.accelerations = new NumericUpDownAccelerationCollection(); + accelerations = new NumericUpDownAccelerationCollection(); } - return this.accelerations; + return accelerations; } } @@ -187,12 +187,12 @@ public decimal Increment get { - if (this.accelerationsCurrentIndex != InvalidValue) + if (accelerationsCurrentIndex != InvalidValue) { - return this.Accelerations[this.accelerationsCurrentIndex].Increment; + return Accelerations[accelerationsCurrentIndex].Increment; } - return this.increment; + return increment; } set @@ -203,7 +203,7 @@ public decimal Increment } else { - this.increment = value; + increment = value; } } } @@ -297,7 +297,7 @@ private bool Spinning { get { - return this.accelerations != null && this.buttonPressedStartTime != InvalidValue; + return accelerations != null && buttonPressedStartTime != InvalidValue; } } @@ -474,12 +474,12 @@ public override void DownButton() // try { - newValue -= this.Increment; + newValue -= Increment; if (newValue < minimum) { newValue = minimum; - if (this.Spinning) + if (Spinning) { StopAcceleration(); } @@ -510,7 +510,7 @@ public void EndInit() /// protected override void OnKeyDown(KeyEventArgs e) { - if (base.InterceptArrowKeys && (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down) && !this.Spinning) + if (base.InterceptArrowKeys && (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down) && !Spinning) { StartAcceleration(); } @@ -661,18 +661,18 @@ protected void ParseEditText() private void SetNextAcceleration() { // Spinning will check if accelerations is null. - if (this.Spinning && this.accelerationsCurrentIndex < (this.accelerations.Count - 1)) + if (Spinning && accelerationsCurrentIndex < (accelerations.Count - 1)) { // if index not the last entry ... // Ticks are in 100-nanoseconds (1E-7 seconds). long nowTicks = DateTime.Now.Ticks; - long buttonPressedElapsedTime = nowTicks - this.buttonPressedStartTime; - long accelerationInterval = 10000000L * this.accelerations[this.accelerationsCurrentIndex + 1].Seconds; // next entry. + long buttonPressedElapsedTime = nowTicks - buttonPressedStartTime; + long accelerationInterval = 10000000L * accelerations[accelerationsCurrentIndex + 1].Seconds; // next entry. // If Up/Down button pressed for more than the current acceleration entry interval, get next entry in the accel table. if (buttonPressedElapsedTime > accelerationInterval) { - this.buttonPressedStartTime = nowTicks; - this.accelerationsCurrentIndex++; + buttonPressedStartTime = nowTicks; + accelerationsCurrentIndex++; } } } @@ -736,7 +736,7 @@ private bool ShouldSerializeValue() /// private void StartAcceleration() { - this.buttonPressedStartTime = DateTime.Now.Ticks; + buttonPressedStartTime = DateTime.Now.Ticks; } /// @@ -744,8 +744,8 @@ private void StartAcceleration() /// private void StopAcceleration() { - this.accelerationsCurrentIndex = InvalidValue; - this.buttonPressedStartTime = InvalidValue; + accelerationsCurrentIndex = InvalidValue; + buttonPressedStartTime = InvalidValue; } /// @@ -779,12 +779,12 @@ public override void UpButton() // try { - newValue += this.Increment; + newValue += Increment; if (newValue > maximum) { newValue = maximum; - if (this.Spinning) + if (Spinning) { StopAcceleration(); } @@ -880,7 +880,7 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) // testNumber to account for the missing digit. int numDigits = (int)Math.Floor(Math.Log(Math.Max(-(double)Minimum, (double)Maximum), baseSize)); int maxDigits; - if (this.Hexadecimal) + if (Hexadecimal) { maxDigits = (int)Math.Floor(Math.Log(long.MaxValue, baseSize)); } @@ -917,12 +917,12 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) testNumber = testNumber * baseSize + digit; } - int textWidth = TextRenderer.MeasureText(GetNumberText(testNumber), this.Font).Width; + int textWidth = TextRenderer.MeasureText(GetNumberText(testNumber), Font).Width; if (maxDigitsReached) { string shortText; - if (this.Hexadecimal) + if (Hexadecimal) { shortText = ((long)testNumber).ToString("X", CultureInfo.InvariantCulture); } @@ -930,7 +930,7 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) { shortText = testNumber.ToString(CultureInfo.CurrentCulture); } - int shortTextWidth = TextRenderer.MeasureText(shortText, this.Font).Width; + int shortTextWidth = TextRenderer.MeasureText(shortText, Font).Width; // Adding the width of the one digit that was dropped earlier. // This assumes that no additional thousand separator is added by that digit which is correct. textWidth += shortTextWidth / (numDigits + 1); @@ -958,7 +958,7 @@ private int GetLargestDigit(int start, int end) ch = (char)('A' + (i - 10)); } - Size digitSize = TextRenderer.MeasureText(ch.ToString(), this.Font); + Size digitSize = TextRenderer.MeasureText(ch.ToString(), Font); if (digitSize.Width >= digitWidth) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDownAcceleration.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDownAcceleration.cs index 24ec5216e40..8ee71bee12b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDownAcceleration.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDownAcceleration.cs @@ -40,7 +40,7 @@ public int Seconds { get { - return this.seconds; + return seconds; } set { @@ -48,7 +48,7 @@ public int Seconds { throw new ArgumentOutOfRangeException(nameof(seconds), value, SR.NumericUpDownLessThanZeroError); } - this.seconds = value; + seconds = value; } } @@ -60,7 +60,7 @@ public decimal Increment get { - return this.increment; + return increment; } set @@ -69,7 +69,7 @@ public decimal Increment { throw new ArgumentOutOfRangeException(nameof(increment), value, SR.NumericUpDownLessThanZeroError); } - this.increment = value; + increment = value; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDownAccelerationCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDownAccelerationCollection.cs index 87b4228e7ef..e004e6a1be2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDownAccelerationCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDownAccelerationCollection.cs @@ -36,15 +36,15 @@ public void Add(NumericUpDownAcceleration acceleration) // Keep the array sorted, insert in the right spot. int index = 0; - while (index < this.items.Count) + while (index < items.Count) { - if (acceleration.Seconds < this.items[index].Seconds) + if (acceleration.Seconds < items[index].Seconds) { break; } index++; } - this.items.Insert(index, acceleration); + items.Insert(index, acceleration); } /// @@ -52,7 +52,7 @@ public void Add(NumericUpDownAcceleration acceleration) /// public void Clear() { - this.items.Clear(); + items.Clear(); } /// @@ -60,7 +60,7 @@ public void Clear() /// public bool Contains(NumericUpDownAcceleration acceleration) { - return this.items.Contains(acceleration); + return items.Contains(acceleration); } /// @@ -68,7 +68,7 @@ public bool Contains(NumericUpDownAcceleration acceleration) /// public void CopyTo(NumericUpDownAcceleration[] array, int index) { - this.items.CopyTo(array, index); + items.CopyTo(array, index); } /// @@ -76,7 +76,7 @@ public void CopyTo(NumericUpDownAcceleration[] array, int index) /// public int Count { - get { return this.items.Count; } + get { return items.Count; } } /// @@ -93,7 +93,7 @@ public bool IsReadOnly /// public bool Remove(NumericUpDownAcceleration acceleration) { - return this.items.Remove(acceleration); + return items.Remove(acceleration); } /// IEnumerable implementation. @@ -104,7 +104,7 @@ public bool Remove(NumericUpDownAcceleration acceleration) /// IEnumerator IEnumerable.GetEnumerator() { - return this.items.GetEnumerator(); + return items.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() @@ -119,7 +119,7 @@ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() /// public NumericUpDownAccelerationCollection() { - this.items = new List(); + items = new List(); } /// @@ -145,7 +145,7 @@ public void AddRange(params NumericUpDownAcceleration[] accelerations) // way we add the elements to the collection, just call Add. foreach (NumericUpDownAcceleration acceleration in accelerations) { - this.Add(acceleration); + Add(acceleration); } } @@ -155,7 +155,7 @@ public void AddRange(params NumericUpDownAcceleration[] accelerations) /// public NumericUpDownAcceleration this[int index] { - get { return this.items[index]; } + get { return items[index]; } } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs index 1c0e6d41107..2a0c1d4cf43 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs @@ -517,7 +517,7 @@ private void InstallNewImage(Image value, ImageInstallationType installationType) { StopAnimate(); - this.image = value; + image = value; LayoutTransaction.DoLayoutIf(AutoSize, this, this, PropertyNames.Image); @@ -526,7 +526,7 @@ private void InstallNewImage(Image value, { AdjustSize(); } - this.imageInstallationType = installationType; + imageInstallationType = installationType; Invalidate(); CommonProperties.xClearPreferredSizeCache(this); @@ -614,8 +614,8 @@ public void Load() ] public void Load(string url) { - this.ImageLocation = url; - this.Load(); + ImageLocation = url; + Load(); } [ @@ -835,8 +835,8 @@ private void ReadCallBack(IAsyncResult result) ] public void LoadAsync(string url) { - this.ImageLocation = url; - this.LoadAsync(); + ImageLocation = url; + LoadAsync(); } [ @@ -845,8 +845,8 @@ public void LoadAsync(string url) ] public event AsyncCompletedEventHandler LoadCompleted { - add => this.Events.AddHandler(loadCompletedKey, value); - remove => this.Events.RemoveHandler(loadCompletedKey, value); + add => Events.AddHandler(loadCompletedKey, value); + remove => Events.RemoveHandler(loadCompletedKey, value); } [ @@ -855,8 +855,8 @@ public event AsyncCompletedEventHandler LoadCompleted ] public event ProgressChangedEventHandler LoadProgressChanged { - add => this.Events.AddHandler(loadProgressChangedKey, value); - remove => this.Events.RemoveHandler(loadProgressChangedKey, value); + add => Events.AddHandler(loadProgressChangedKey, value); + remove => Events.RemoveHandler(loadProgressChangedKey, value); } private void ResetInitialImage() @@ -943,16 +943,16 @@ public PictureBoxSizeMode SizeMode { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(PictureBoxSizeMode)); } - if (this.sizeMode != value) + if (sizeMode != value) { if (value == PictureBoxSizeMode.AutoSize) { - this.AutoSize = true; + AutoSize = true; SetStyle(ControlStyles.FixedHeight | ControlStyles.FixedWidth, true); } if (value != PictureBoxSizeMode.AutoSize) { - this.AutoSize = false; + AutoSize = false; SetStyle(ControlStyles.FixedHeight | ControlStyles.FixedWidth, false); savedSize = Size; } @@ -1108,22 +1108,22 @@ private void StopAnimate() private void Animate(bool animate) { - if (animate != this.currentlyAnimating) + if (animate != currentlyAnimating) { if (animate) { - if (this.image != null) + if (image != null) { - ImageAnimator.Animate(this.image, new EventHandler(this.OnFrameChanged)); - this.currentlyAnimating = animate; + ImageAnimator.Animate(image, new EventHandler(OnFrameChanged)); + currentlyAnimating = animate; } } else { - if (this.image != null) + if (image != null) { - ImageAnimator.StopAnimate(this.image, new EventHandler(this.OnFrameChanged)); - this.currentlyAnimating = animate; + ImageAnimator.StopAnimate(image, new EventHandler(OnFrameChanged)); + currentlyAnimating = animate; } } } @@ -1191,7 +1191,7 @@ private void OnFrameChanged(object o, EventArgs e) { if (handleValid) { - BeginInvoke(new EventHandler(this.OnFrameChanged), o, e); + BeginInvoke(new EventHandler(OnFrameChanged), o, e); } return; } @@ -1271,7 +1271,7 @@ protected override void OnPaint(PaintEventArgs pe) if (image != null) { Animate(); - ImageAnimator.UpdateFrames(this.Image); + ImageAnimator.UpdateFrames(Image); // Error and initial image are drawn centered, non-stretched. Rectangle drawingRect = diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PageSetupDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PageSetupDialog.cs index 86827f3c098..93abf516f13 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PageSetupDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PageSetupDialog.cs @@ -358,7 +358,7 @@ private static void UpdateSettings(NativeMethods.PAGESETUPDLG data, PageSettings protected override bool RunDialog(IntPtr hwndOwner) { - NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(this.HookProc); + NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(HookProc); if (pageSettings == null) throw new ArgumentException(SR.PSDcantShowWithoutPage); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintControllerWithStatusDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintControllerWithStatusDialog.cs index c1b9591e950..fca8caf5d7f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintControllerWithStatusDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintControllerWithStatusDialog.cs @@ -251,8 +251,8 @@ internal StatusDialog(BackgroundThread backgroundThread, string dialogTitle) InitializeComponent(); this.backgroundThread = backgroundThread; - this.Text = dialogTitle; - this.MinimumSize = Size; + Text = dialogTitle; + MinimumSize = Size; } /// @@ -271,12 +271,12 @@ private void InitializeComponent() { if (IsRTLResources) { - this.RightToLeft = RightToLeft.Yes; + RightToLeft = RightToLeft.Yes; } - this.tableLayoutPanel1 = new TableLayoutPanel(); - this.label1 = new Label(); - this.button1 = new Button(); + tableLayoutPanel1 = new TableLayoutPanel(); + label1 = new Label(); + button1 = new Button(); label1.AutoSize = true; label1.Location = new Point(8, 16); @@ -305,23 +305,23 @@ private void InitializeComponent() tableLayoutPanel1.Controls.Add(label1, 0, 0); tableLayoutPanel1.Controls.Add(button1, 0, 1); - this.AutoScaleDimensions = new Size(6, 13); - this.AutoScaleMode = AutoScaleMode.Font; - this.MaximizeBox = false; - this.ControlBox = false; - this.MinimizeBox = false; + AutoScaleDimensions = new Size(6, 13); + AutoScaleMode = AutoScaleMode.Font; + MaximizeBox = false; + ControlBox = false; + MinimizeBox = false; Size clientSize = new Size(256, 122); if (DpiHelper.IsScalingRequired) { - this.ClientSize = DpiHelper.LogicalToDeviceUnits(clientSize); + ClientSize = DpiHelper.LogicalToDeviceUnits(clientSize); } else { - this.ClientSize = clientSize; + ClientSize = clientSize; } - this.CancelButton = button1; - this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; - this.Controls.Add(tableLayoutPanel1); + CancelButton = button1; + SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; + Controls.Add(tableLayoutPanel1); } private void button1_Click(object sender, System.EventArgs e) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintDialog.cs index c715ca8a624..f313d853b86 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintDialog.cs @@ -368,7 +368,7 @@ internal static NativeMethods.PRINTDLGEX CreatePRINTDLGEX() protected override bool RunDialog(IntPtr hwndOwner) { - var hookProcPtr = new NativeMethods.WndProc(this.HookProc); + var hookProcPtr = new NativeMethods.WndProc(HookProc); if (!UseEXDialog) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs index bb9963c907b..31b3a2aa3d8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs @@ -68,8 +68,8 @@ public PrintPreviewDialog() base.AutoScaleBaseSize = new Size(5, 13); #pragma warning restore 618 - this.previewControl = new PrintPreviewControl(); - this.imageList = new ImageList(); + previewControl = new PrintPreviewControl(); + imageList = new ImageList(); imageList.Images.AddStrip(DpiHelper.GetBitmapFromIcon(typeof(PrintPreviewDialog), "PrintPreviewStrip")); InitForm(); } @@ -1265,221 +1265,221 @@ void InitForm() System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PrintPreviewDialog)); - this.toolStrip1 = new System.Windows.Forms.ToolStrip(); - this.printToolStripButton = new System.Windows.Forms.ToolStripButton(); - this.zoomToolStripSplitButton = new System.Windows.Forms.ToolStripSplitButton(); - this.autoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); - this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem(); - this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem(); - this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripMenuItem(); - this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripMenuItem(); - this.toolStripMenuItem6 = new System.Windows.Forms.ToolStripMenuItem(); - this.toolStripMenuItem7 = new System.Windows.Forms.ToolStripMenuItem(); - this.toolStripMenuItem8 = new System.Windows.Forms.ToolStripMenuItem(); - this.separatorToolStripSeparator = new System.Windows.Forms.ToolStripSeparator(); - this.onepageToolStripButton = new System.Windows.Forms.ToolStripButton(); - this.twopagesToolStripButton = new System.Windows.Forms.ToolStripButton(); - this.threepagesToolStripButton = new System.Windows.Forms.ToolStripButton(); - this.fourpagesToolStripButton = new System.Windows.Forms.ToolStripButton(); - this.sixpagesToolStripButton = new System.Windows.Forms.ToolStripButton(); - this.separatorToolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); - this.closeToolStripButton = new System.Windows.Forms.ToolStripButton(); - this.pageCounter = new System.Windows.Forms.NumericUpDown(); - this.pageToolStripLabel = new System.Windows.Forms.ToolStripLabel(); - this.toolStrip1.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)(this.pageCounter)).BeginInit(); - this.SuspendLayout(); + toolStrip1 = new System.Windows.Forms.ToolStrip(); + printToolStripButton = new System.Windows.Forms.ToolStripButton(); + zoomToolStripSplitButton = new System.Windows.Forms.ToolStripSplitButton(); + autoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); + toolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem(); + toolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem(); + toolStripMenuItem4 = new System.Windows.Forms.ToolStripMenuItem(); + toolStripMenuItem5 = new System.Windows.Forms.ToolStripMenuItem(); + toolStripMenuItem6 = new System.Windows.Forms.ToolStripMenuItem(); + toolStripMenuItem7 = new System.Windows.Forms.ToolStripMenuItem(); + toolStripMenuItem8 = new System.Windows.Forms.ToolStripMenuItem(); + separatorToolStripSeparator = new System.Windows.Forms.ToolStripSeparator(); + onepageToolStripButton = new System.Windows.Forms.ToolStripButton(); + twopagesToolStripButton = new System.Windows.Forms.ToolStripButton(); + threepagesToolStripButton = new System.Windows.Forms.ToolStripButton(); + fourpagesToolStripButton = new System.Windows.Forms.ToolStripButton(); + sixpagesToolStripButton = new System.Windows.Forms.ToolStripButton(); + separatorToolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); + closeToolStripButton = new System.Windows.Forms.ToolStripButton(); + pageCounter = new System.Windows.Forms.NumericUpDown(); + pageToolStripLabel = new System.Windows.Forms.ToolStripLabel(); + toolStrip1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(pageCounter)).BeginInit(); + SuspendLayout(); // // toolStrip1 // - resources.ApplyResources(this.toolStrip1, "toolStrip1"); - this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.printToolStripButton, - this.zoomToolStripSplitButton, - this.separatorToolStripSeparator, - this.onepageToolStripButton, - this.twopagesToolStripButton, - this.threepagesToolStripButton, - this.fourpagesToolStripButton, - this.sixpagesToolStripButton, - this.separatorToolStripSeparator1, - this.closeToolStripButton}); - this.toolStrip1.Name = "toolStrip1"; - this.toolStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.System; - this.toolStrip1.GripStyle = ToolStripGripStyle.Hidden; + resources.ApplyResources(toolStrip1, "toolStrip1"); + toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + printToolStripButton, + zoomToolStripSplitButton, + separatorToolStripSeparator, + onepageToolStripButton, + twopagesToolStripButton, + threepagesToolStripButton, + fourpagesToolStripButton, + sixpagesToolStripButton, + separatorToolStripSeparator1, + closeToolStripButton}); + toolStrip1.Name = "toolStrip1"; + toolStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.System; + toolStrip1.GripStyle = ToolStripGripStyle.Hidden; // // printToolStripButton // - this.printToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; - this.printToolStripButton.Name = "printToolStripButton"; - resources.ApplyResources(this.printToolStripButton, "printToolStripButton"); + printToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; + printToolStripButton.Name = "printToolStripButton"; + resources.ApplyResources(printToolStripButton, "printToolStripButton"); // // zoomToolStripSplitButton // - this.zoomToolStripSplitButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; - this.zoomToolStripSplitButton.DoubleClickEnabled = true; - this.zoomToolStripSplitButton.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.autoToolStripMenuItem, - this.toolStripMenuItem1, - this.toolStripMenuItem2, - this.toolStripMenuItem3, - this.toolStripMenuItem4, - this.toolStripMenuItem5, - this.toolStripMenuItem6, - this.toolStripMenuItem7, - this.toolStripMenuItem8}); - this.zoomToolStripSplitButton.Name = "zoomToolStripSplitButton"; - this.zoomToolStripSplitButton.SplitterWidth = 1; - resources.ApplyResources(this.zoomToolStripSplitButton, "zoomToolStripSplitButton"); + zoomToolStripSplitButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; + zoomToolStripSplitButton.DoubleClickEnabled = true; + zoomToolStripSplitButton.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + autoToolStripMenuItem, + toolStripMenuItem1, + toolStripMenuItem2, + toolStripMenuItem3, + toolStripMenuItem4, + toolStripMenuItem5, + toolStripMenuItem6, + toolStripMenuItem7, + toolStripMenuItem8}); + zoomToolStripSplitButton.Name = "zoomToolStripSplitButton"; + zoomToolStripSplitButton.SplitterWidth = 1; + resources.ApplyResources(zoomToolStripSplitButton, "zoomToolStripSplitButton"); // // autoToolStripMenuItem // - this.autoToolStripMenuItem.CheckOnClick = true; - this.autoToolStripMenuItem.DoubleClickEnabled = true; - this.autoToolStripMenuItem.Checked = true; - this.autoToolStripMenuItem.Name = "autoToolStripMenuItem"; - resources.ApplyResources(this.autoToolStripMenuItem, "autoToolStripMenuItem"); + autoToolStripMenuItem.CheckOnClick = true; + autoToolStripMenuItem.DoubleClickEnabled = true; + autoToolStripMenuItem.Checked = true; + autoToolStripMenuItem.Name = "autoToolStripMenuItem"; + resources.ApplyResources(autoToolStripMenuItem, "autoToolStripMenuItem"); // // toolStripMenuItem1 // - this.toolStripMenuItem1.CheckOnClick = true; - this.toolStripMenuItem1.DoubleClickEnabled = true; - this.toolStripMenuItem1.Name = "toolStripMenuItem1"; - resources.ApplyResources(this.toolStripMenuItem1, "toolStripMenuItem1"); + toolStripMenuItem1.CheckOnClick = true; + toolStripMenuItem1.DoubleClickEnabled = true; + toolStripMenuItem1.Name = "toolStripMenuItem1"; + resources.ApplyResources(toolStripMenuItem1, "toolStripMenuItem1"); // // toolStripMenuItem2 // - this.toolStripMenuItem2.CheckOnClick = true; - this.toolStripMenuItem2.DoubleClickEnabled = true; - this.toolStripMenuItem2.Name = "toolStripMenuItem2"; - resources.ApplyResources(this.toolStripMenuItem2, "toolStripMenuItem2"); + toolStripMenuItem2.CheckOnClick = true; + toolStripMenuItem2.DoubleClickEnabled = true; + toolStripMenuItem2.Name = "toolStripMenuItem2"; + resources.ApplyResources(toolStripMenuItem2, "toolStripMenuItem2"); // // toolStripMenuItem3 // - this.toolStripMenuItem3.CheckOnClick = true; - this.toolStripMenuItem3.DoubleClickEnabled = true; - this.toolStripMenuItem3.Name = "toolStripMenuItem3"; - resources.ApplyResources(this.toolStripMenuItem3, "toolStripMenuItem3"); + toolStripMenuItem3.CheckOnClick = true; + toolStripMenuItem3.DoubleClickEnabled = true; + toolStripMenuItem3.Name = "toolStripMenuItem3"; + resources.ApplyResources(toolStripMenuItem3, "toolStripMenuItem3"); // // toolStripMenuItem4 // - this.toolStripMenuItem4.CheckOnClick = true; - this.toolStripMenuItem4.DoubleClickEnabled = true; - this.toolStripMenuItem4.Name = "toolStripMenuItem4"; - resources.ApplyResources(this.toolStripMenuItem4, "toolStripMenuItem4"); + toolStripMenuItem4.CheckOnClick = true; + toolStripMenuItem4.DoubleClickEnabled = true; + toolStripMenuItem4.Name = "toolStripMenuItem4"; + resources.ApplyResources(toolStripMenuItem4, "toolStripMenuItem4"); // // toolStripMenuItem5 // - this.toolStripMenuItem5.CheckOnClick = true; - this.toolStripMenuItem5.DoubleClickEnabled = true; - this.toolStripMenuItem5.Name = "toolStripMenuItem5"; - resources.ApplyResources(this.toolStripMenuItem5, "toolStripMenuItem5"); + toolStripMenuItem5.CheckOnClick = true; + toolStripMenuItem5.DoubleClickEnabled = true; + toolStripMenuItem5.Name = "toolStripMenuItem5"; + resources.ApplyResources(toolStripMenuItem5, "toolStripMenuItem5"); // // toolStripMenuItem6 // - this.toolStripMenuItem6.CheckOnClick = true; - this.toolStripMenuItem6.DoubleClickEnabled = true; - this.toolStripMenuItem6.Name = "toolStripMenuItem6"; - resources.ApplyResources(this.toolStripMenuItem6, "toolStripMenuItem6"); + toolStripMenuItem6.CheckOnClick = true; + toolStripMenuItem6.DoubleClickEnabled = true; + toolStripMenuItem6.Name = "toolStripMenuItem6"; + resources.ApplyResources(toolStripMenuItem6, "toolStripMenuItem6"); // // toolStripMenuItem7 // - this.toolStripMenuItem7.CheckOnClick = true; - this.toolStripMenuItem7.DoubleClickEnabled = true; - this.toolStripMenuItem7.Name = "toolStripMenuItem7"; - resources.ApplyResources(this.toolStripMenuItem7, "toolStripMenuItem7"); + toolStripMenuItem7.CheckOnClick = true; + toolStripMenuItem7.DoubleClickEnabled = true; + toolStripMenuItem7.Name = "toolStripMenuItem7"; + resources.ApplyResources(toolStripMenuItem7, "toolStripMenuItem7"); // // toolStripMenuItem8 // - this.toolStripMenuItem8.CheckOnClick = true; - this.toolStripMenuItem8.DoubleClickEnabled = true; - this.toolStripMenuItem8.Name = "toolStripMenuItem8"; - resources.ApplyResources(this.toolStripMenuItem8, "toolStripMenuItem8"); + toolStripMenuItem8.CheckOnClick = true; + toolStripMenuItem8.DoubleClickEnabled = true; + toolStripMenuItem8.Name = "toolStripMenuItem8"; + resources.ApplyResources(toolStripMenuItem8, "toolStripMenuItem8"); // // separatorToolStripSeparator // - this.separatorToolStripSeparator.Name = "separatorToolStripSeparator"; + separatorToolStripSeparator.Name = "separatorToolStripSeparator"; // // onepageToolStripButton // - this.onepageToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; - this.onepageToolStripButton.Name = "onepageToolStripButton"; - resources.ApplyResources(this.onepageToolStripButton, "onepageToolStripButton"); + onepageToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; + onepageToolStripButton.Name = "onepageToolStripButton"; + resources.ApplyResources(onepageToolStripButton, "onepageToolStripButton"); // // twopagesToolStripButton // - this.twopagesToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; - this.twopagesToolStripButton.Name = "twopagesToolStripButton"; - resources.ApplyResources(this.twopagesToolStripButton, "twopagesToolStripButton"); + twopagesToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; + twopagesToolStripButton.Name = "twopagesToolStripButton"; + resources.ApplyResources(twopagesToolStripButton, "twopagesToolStripButton"); // // threepagesToolStripButton // - this.threepagesToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; - this.threepagesToolStripButton.Name = "threepagesToolStripButton"; - resources.ApplyResources(this.threepagesToolStripButton, "threepagesToolStripButton"); + threepagesToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; + threepagesToolStripButton.Name = "threepagesToolStripButton"; + resources.ApplyResources(threepagesToolStripButton, "threepagesToolStripButton"); // // fourpagesToolStripButton // - this.fourpagesToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; - this.fourpagesToolStripButton.Name = "fourpagesToolStripButton"; - resources.ApplyResources(this.fourpagesToolStripButton, "fourpagesToolStripButton"); + fourpagesToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; + fourpagesToolStripButton.Name = "fourpagesToolStripButton"; + resources.ApplyResources(fourpagesToolStripButton, "fourpagesToolStripButton"); // // sixpagesToolStripButton // - this.sixpagesToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; - this.sixpagesToolStripButton.Name = "sixpagesToolStripButton"; - resources.ApplyResources(this.sixpagesToolStripButton, "sixpagesToolStripButton"); + sixpagesToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; + sixpagesToolStripButton.Name = "sixpagesToolStripButton"; + resources.ApplyResources(sixpagesToolStripButton, "sixpagesToolStripButton"); // // separatorToolStripSeparator1 // - this.separatorToolStripSeparator1.Name = "separatorToolStripSeparator1"; + separatorToolStripSeparator1.Name = "separatorToolStripSeparator1"; // // closeToolStripButton // - this.closeToolStripButton.DisplayStyle = ToolStripItemDisplayStyle.Text; - this.closeToolStripButton.Name = "closeToolStripButton"; - resources.ApplyResources(this.closeToolStripButton, "closeToolStripButton"); + closeToolStripButton.DisplayStyle = ToolStripItemDisplayStyle.Text; + closeToolStripButton.Name = "closeToolStripButton"; + resources.ApplyResources(closeToolStripButton, "closeToolStripButton"); // // pageCounter // - resources.ApplyResources(this.pageCounter, "pageCounter"); + resources.ApplyResources(pageCounter, "pageCounter"); pageCounter.Text = "1"; pageCounter.TextAlign = HorizontalAlignment.Right; pageCounter.DecimalPlaces = 0; pageCounter.Minimum = new decimal(0d); pageCounter.Maximum = new decimal(1000d); pageCounter.ValueChanged += new EventHandler(UpdownMove); - this.pageCounter.Name = "pageCounter"; + pageCounter.Name = "pageCounter"; // // pageToolStripLabel // - this.pageToolStripLabel.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; - this.pageToolStripLabel.Name = "pageToolStripLabel"; - resources.ApplyResources(this.pageToolStripLabel, "pageToolStripLabel"); + pageToolStripLabel.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; + pageToolStripLabel.Name = "pageToolStripLabel"; + resources.ApplyResources(pageToolStripLabel, "pageToolStripLabel"); previewControl.Size = new Size(792, 610); previewControl.Location = new Point(0, 43); @@ -1487,32 +1487,32 @@ void InitForm() previewControl.StartPageChanged += new EventHandler(previewControl_StartPageChanged); //EVENTS and Images ... - this.printToolStripButton.Click += new System.EventHandler(this.OnprintToolStripButtonClick); - this.autoToolStripMenuItem.Click += new System.EventHandler(ZoomAuto); - this.toolStripMenuItem1.Click += new System.EventHandler(Zoom500); - this.toolStripMenuItem2.Click += new System.EventHandler(Zoom250); - this.toolStripMenuItem3.Click += new System.EventHandler(Zoom150); - this.toolStripMenuItem4.Click += new System.EventHandler(Zoom100); - this.toolStripMenuItem5.Click += new System.EventHandler(Zoom75); - this.toolStripMenuItem6.Click += new System.EventHandler(Zoom50); - this.toolStripMenuItem7.Click += new System.EventHandler(Zoom25); - this.toolStripMenuItem8.Click += new System.EventHandler(Zoom10); - this.onepageToolStripButton.Click += new System.EventHandler(this.OnonepageToolStripButtonClick); - this.twopagesToolStripButton.Click += new System.EventHandler(this.OntwopagesToolStripButtonClick); - this.threepagesToolStripButton.Click += new System.EventHandler(this.OnthreepagesToolStripButtonClick); - this.fourpagesToolStripButton.Click += new System.EventHandler(this.OnfourpagesToolStripButtonClick); - this.sixpagesToolStripButton.Click += new System.EventHandler(this.OnsixpagesToolStripButtonClick); - this.closeToolStripButton.Click += new System.EventHandler(this.OncloseToolStripButtonClick); - this.closeToolStripButton.Paint += new PaintEventHandler(this.OncloseToolStripButtonPaint); + printToolStripButton.Click += new System.EventHandler(OnprintToolStripButtonClick); + autoToolStripMenuItem.Click += new System.EventHandler(ZoomAuto); + toolStripMenuItem1.Click += new System.EventHandler(Zoom500); + toolStripMenuItem2.Click += new System.EventHandler(Zoom250); + toolStripMenuItem3.Click += new System.EventHandler(Zoom150); + toolStripMenuItem4.Click += new System.EventHandler(Zoom100); + toolStripMenuItem5.Click += new System.EventHandler(Zoom75); + toolStripMenuItem6.Click += new System.EventHandler(Zoom50); + toolStripMenuItem7.Click += new System.EventHandler(Zoom25); + toolStripMenuItem8.Click += new System.EventHandler(Zoom10); + onepageToolStripButton.Click += new System.EventHandler(OnonepageToolStripButtonClick); + twopagesToolStripButton.Click += new System.EventHandler(OntwopagesToolStripButtonClick); + threepagesToolStripButton.Click += new System.EventHandler(OnthreepagesToolStripButtonClick); + fourpagesToolStripButton.Click += new System.EventHandler(OnfourpagesToolStripButtonClick); + sixpagesToolStripButton.Click += new System.EventHandler(OnsixpagesToolStripButtonClick); + closeToolStripButton.Click += new System.EventHandler(OncloseToolStripButtonClick); + closeToolStripButton.Paint += new PaintEventHandler(OncloseToolStripButtonPaint); //Images - this.toolStrip1.ImageList = imageList; - this.printToolStripButton.ImageIndex = 0; - this.zoomToolStripSplitButton.ImageIndex = 1; - this.onepageToolStripButton.ImageIndex = 2; - this.twopagesToolStripButton.ImageIndex = 3; - this.threepagesToolStripButton.ImageIndex = 4; - this.fourpagesToolStripButton.ImageIndex = 5; - this.sixpagesToolStripButton.ImageIndex = 6; + toolStrip1.ImageList = imageList; + printToolStripButton.ImageIndex = 0; + zoomToolStripSplitButton.ImageIndex = 1; + onepageToolStripButton.ImageIndex = 2; + twopagesToolStripButton.ImageIndex = 3; + threepagesToolStripButton.ImageIndex = 4; + fourpagesToolStripButton.ImageIndex = 5; + sixpagesToolStripButton.ImageIndex = 6; //tabIndex previewControl.TabIndex = 0; @@ -1522,7 +1522,7 @@ void InitForm() zoomToolStripSplitButton.DefaultItem = autoToolStripMenuItem; //ShowCheckMargin - ToolStripDropDownMenu menu = this.zoomToolStripSplitButton.DropDown as ToolStripDropDownMenu; + ToolStripDropDownMenu menu = zoomToolStripSplitButton.DropDown as ToolStripDropDownMenu; if (menu != null) { menu.ShowCheckMargin = true; @@ -1535,25 +1535,25 @@ void InitForm() ToolStripControlHost pageCounterItem = new ToolStripControlHost(pageCounter); pageCounterItem.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; - this.toolStrip1.Items.Add(pageCounterItem); - this.toolStrip1.Items.Add(this.pageToolStripLabel); + toolStrip1.Items.Add(pageCounterItem); + toolStrip1.Items.Add(pageToolStripLabel); // // Form1 // resources.ApplyResources(this, "$this"); - this.Controls.Add(previewControl); - this.Controls.Add(this.toolStrip1); + Controls.Add(previewControl); + Controls.Add(toolStrip1); - this.ClientSize = new Size(400, 300); - this.MinimizeBox = false; - this.ShowInTaskbar = false; - this.SizeGripStyle = SizeGripStyle.Hide; - this.toolStrip1.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)(this.pageCounter)).EndInit(); - this.ResumeLayout(false); - this.PerformLayout(); + ClientSize = new Size(400, 300); + MinimizeBox = false; + ShowInTaskbar = false; + SizeGripStyle = SizeGripStyle.Hide; + toolStrip1.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)(pageCounter)).EndInit(); + ResumeLayout(false); + PerformLayout(); } @@ -1611,9 +1611,9 @@ protected override bool ProcessDialogKey(Keys keyData) /// protected override bool ProcessTabKey(bool forward) { - if (this.ActiveControl == this.previewControl) + if (ActiveControl == previewControl) { - this.pageCounter.Focus(); + pageCounter.Focus(); return true; } return false; @@ -1638,7 +1638,7 @@ internal override bool ShouldSerializeText() void OncloseToolStripButtonClick(object sender, System.EventArgs e) { - this.Close(); + Close(); } void previewControl_StartPageChanged(object sender, EventArgs e) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs index bcbef49b28f..e7ba3ead6c1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs @@ -87,11 +87,11 @@ protected override CreateParams CreateParams { CreateParams cp = base.CreateParams; cp.ClassName = NativeMethods.WC_PROGRESS; - if (this.Style == ProgressBarStyle.Continuous) + if (Style == ProgressBarStyle.Continuous) { cp.Style |= NativeMethods.PBS_SMOOTH; } - else if (this.Style == ProgressBarStyle.Marquee && !DesignMode) + else if (Style == ProgressBarStyle.Marquee && !DesignMode) { cp.Style |= NativeMethods.PBS_MARQUEE; } @@ -723,7 +723,7 @@ protected override void CreateHandle() /// public void Increment(int value) { - if (this.Style == ProgressBarStyle.Marquee) + if (Style == ProgressBarStyle.Marquee) { throw new InvalidOperationException(SR.ProgressBarIncrementMarqueeException); } @@ -796,7 +796,7 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) /// public void PerformStep() { - if (this.Style == ProgressBarStyle.Marquee) + if (Style == ProgressBarStyle.Marquee) { throw new InvalidOperationException(SR.ProgressBarPerformStepMarqueeException); } @@ -903,7 +903,7 @@ internal override object GetPropertyValue(int propertyID) switch (propertyID) { case NativeMethods.UIA_NamePropertyId: - return this.Name; + return Name; case NativeMethods.UIA_ControlTypePropertyId: return NativeMethods.UIA_ProgressBarControlTypeId; case NativeMethods.UIA_IsKeyboardFocusablePropertyId: @@ -939,7 +939,7 @@ internal override double Maximum { get { - return this.OwningProgressBar?.Maximum ?? double.NaN; + return OwningProgressBar?.Maximum ?? double.NaN; } } @@ -947,7 +947,7 @@ internal override double Minimum { get { - return this.OwningProgressBar?.Minimum ?? double.NaN; + return OwningProgressBar?.Minimum ?? double.NaN; } } @@ -963,7 +963,7 @@ internal override double RangeValue { get { - return this.OwningProgressBar?.Value ?? double.NaN; + return OwningProgressBar?.Value ?? double.NaN; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs index 6c2f6c2eeba..833762d331f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs @@ -204,8 +204,8 @@ public PropertyGrid() { gridView = CreateGridView(null); gridView.TabStop = true; - gridView.MouseMove += new MouseEventHandler(this.OnChildMouseMove); - gridView.MouseDown += new MouseEventHandler(this.OnChildMouseDown); + gridView.MouseMove += new MouseEventHandler(OnChildMouseMove); + gridView.MouseDown += new MouseEventHandler(OnChildMouseDown); gridView.TabIndex = 2; separator1 = CreateSeparatorButton(); @@ -249,8 +249,8 @@ public PropertyGrid() doccomment.Dock = DockStyle.None; doccomment.BackColor = SystemColors.Control; doccomment.ForeColor = SystemColors.ControlText; - doccomment.MouseMove += new MouseEventHandler(this.OnChildMouseMove); - doccomment.MouseDown += new MouseEventHandler(this.OnChildMouseDown); + doccomment.MouseMove += new MouseEventHandler(OnChildMouseMove); + doccomment.MouseDown += new MouseEventHandler(OnChildMouseDown); @@ -260,16 +260,16 @@ public PropertyGrid() hotcommands.Dock = DockStyle.None; SetHotCommandColors(false); hotcommands.Visible = false; - hotcommands.MouseMove += new MouseEventHandler(this.OnChildMouseMove); - hotcommands.MouseDown += new MouseEventHandler(this.OnChildMouseDown); + hotcommands.MouseMove += new MouseEventHandler(OnChildMouseMove); + hotcommands.MouseDown += new MouseEventHandler(OnChildMouseDown); Controls.AddRange(new Control[] { doccomment, hotcommands, gridView, toolStrip }); SetActiveControl(gridView); toolStrip.ResumeLayout(false); // SetupToolbar should perform the layout SetupToolbar(); - this.PropertySort = PropertySort.Categorized | PropertySort.Alphabetical; - this.Text = "PropertyGrid"; + PropertySort = PropertySort.Categorized | PropertySort.Alphabetical; + Text = "PropertyGrid"; SetSelectState(0); } catch (Exception ex) @@ -294,18 +294,18 @@ internal IDesignerHost ActiveDesigner { get { - if (this.designerHost == null) + if (designerHost == null) { designerHost = (IDesignerHost)GetService(typeof(IDesignerHost)); } - return this.designerHost; + return designerHost; } set { if (value != designerHost) { SetFlag(ReInitTab, true); - if (this.designerHost != null) + if (designerHost != null) { IComponentChangeService cs = (IComponentChangeService)designerHost.GetService(typeof(IComponentChangeService)); if (cs != null) @@ -318,14 +318,14 @@ internal IDesignerHost ActiveDesigner IPropertyValueUIService pvSvc = (IPropertyValueUIService)designerHost.GetService(typeof(IPropertyValueUIService)); if (pvSvc != null) { - pvSvc.PropertyUIValueItemsChanged -= new EventHandler(this.OnNotifyPropertyValueUIItemsChanged); + pvSvc.PropertyUIValueItemsChanged -= new EventHandler(OnNotifyPropertyValueUIItemsChanged); } - designerHost.TransactionOpened -= new EventHandler(this.OnTransactionOpened); - designerHost.TransactionClosed -= new DesignerTransactionCloseEventHandler(this.OnTransactionClosed); + designerHost.TransactionOpened -= new EventHandler(OnTransactionOpened); + designerHost.TransactionClosed -= new DesignerTransactionCloseEventHandler(OnTransactionClosed); SetFlag(BatchMode, false); RemoveTabs(PropertyTabScope.Document, true); - this.designerHost = null; + designerHost = null; } @@ -340,14 +340,14 @@ internal IDesignerHost ActiveDesigner cs.ComponentChanged += onComponentChanged; } - value.TransactionOpened += new EventHandler(this.OnTransactionOpened); - value.TransactionClosed += new DesignerTransactionCloseEventHandler(this.OnTransactionClosed); + value.TransactionOpened += new EventHandler(OnTransactionOpened); + value.TransactionClosed += new DesignerTransactionCloseEventHandler(OnTransactionClosed); SetFlag(BatchMode, false); IPropertyValueUIService pvSvc = (IPropertyValueUIService)value.GetService(typeof(IPropertyValueUIService)); if (pvSvc != null) { - pvSvc.PropertyUIValueItemsChanged += new EventHandler(this.OnNotifyPropertyValueUIItemsChanged); + pvSvc.PropertyUIValueItemsChanged += new EventHandler(OnNotifyPropertyValueUIItemsChanged); } } @@ -794,7 +794,7 @@ private bool FreezePainting set { - if (value && IsHandleCreated && this.Visible) + if (value && IsHandleCreated && Visible) { if (0 == paintFrozen++) { @@ -902,11 +902,11 @@ public virtual bool HelpVisible { get { - return this.helpVisible; + return helpVisible; } set { - this.helpVisible = value; + helpVisible = value; doccomment.Visible = value; OnLayoutInternal(false); @@ -1163,7 +1163,7 @@ public PropertySort PropertySort OnViewSortButtonClick(newButton, EventArgs.Empty); - this.propertySortValue = value; + propertySortValue = value; if (selectedGridItem != null) { @@ -1239,7 +1239,7 @@ public object[] SelectedObjects { try { - this.FreezePainting = true; + FreezePainting = true; SetFlag(FullRefreshAfterBatch, false); if (GetFlag(BatchMode)) @@ -1493,7 +1493,7 @@ public object[] SelectedObjects } finally { - this.FreezePainting = false; + FreezePainting = false; } } @@ -1533,7 +1533,7 @@ public GridItem SelectedGridItem GridItem g = gridView.SelectedGridEntry; if (g == null) { - return this.peMain; + return peMain; } return g; } @@ -1568,11 +1568,11 @@ public override ISite Site if (value == null) { - this.ActiveDesigner = null; + ActiveDesigner = null; } else { - this.ActiveDesigner = (IDesignerHost)value.GetService(typeof(IDesignerHost)); + ActiveDesigner = (IDesignerHost)value.GetService(typeof(IDesignerHost)); } ResumeAllLayout(this, true); @@ -1631,24 +1631,24 @@ public bool LargeButtons return; } - this.buttonType = (value ? LARGE_BUTTONS : NORMAL_BUTTONS); + buttonType = (value ? LARGE_BUTTONS : NORMAL_BUTTONS); if (value) { EnsureLargeButtons(); - if (this.imageList != null && this.imageList[LARGE_BUTTONS] != null) + if (imageList != null && imageList[LARGE_BUTTONS] != null) { - toolStrip.ImageScalingSize = this.imageList[LARGE_BUTTONS].ImageSize; + toolStrip.ImageScalingSize = imageList[LARGE_BUTTONS].ImageSize; } } else { - if (this.imageList != null && this.imageList[NORMAL_BUTTONS] != null) + if (imageList != null && imageList[NORMAL_BUTTONS] != null) { - toolStrip.ImageScalingSize = this.imageList[NORMAL_BUTTONS].ImageSize; + toolStrip.ImageScalingSize = imageList[NORMAL_BUTTONS].ImageSize; } } - toolStrip.ImageList = imageList[this.buttonType]; + toolStrip.ImageList = imageList[buttonType]; OnLayoutInternal(false); Invalidate(); toolStrip.Invalidate(); @@ -1678,17 +1678,17 @@ public virtual bool ToolbarVisible { get { - return this.toolbarVisible; + return toolbarVisible; } set { - this.toolbarVisible = value; + toolbarVisible = value; toolStrip.Visible = value; OnLayoutInternal(false); if (value) { - SetupToolbar(this.viewTabsDirty); + SetupToolbar(viewTabsDirty); } Invalidate(); toolStrip.Invalidate(); @@ -2133,7 +2133,7 @@ private PropertyTab CreateTab(Type tabType, IDesignerHost host) } else { - param = this.Site; + param = Site; } @@ -2312,12 +2312,12 @@ protected override void Dispose(bool disposing) Debug.Assert(designerEventService != null, "GetFlag(GotDesignerEventService) inconsistent with designerEventService == null"); if (designerEventService != null) { - designerEventService.ActiveDesignerChanged -= new ActiveDesignerEventHandler(this.OnActiveDesignerChanged); + designerEventService.ActiveDesignerChanged -= new ActiveDesignerEventHandler(OnActiveDesignerChanged); } designerEventService = null; SetFlag(GotDesignerEventService, false); } - this.ActiveDesigner = null; + ActiveDesigner = null; if (viewTabs != null) { @@ -2579,18 +2579,18 @@ private void EnsureDesignerEventService() if (designerEventService != null) { SetFlag(GotDesignerEventService, true); - designerEventService.ActiveDesignerChanged += new ActiveDesignerEventHandler(this.OnActiveDesignerChanged); + designerEventService.ActiveDesignerChanged += new ActiveDesignerEventHandler(OnActiveDesignerChanged); OnActiveDesignerChanged(null, new ActiveDesignerEventArgs(null, designerEventService.ActiveDesigner)); } } private void EnsureLargeButtons() { - if (this.imageList[LARGE_BUTTONS] == null) + if (imageList[LARGE_BUTTONS] == null) { - this.imageList[LARGE_BUTTONS] = new ImageList(); - this.imageList[LARGE_BUTTONS].ImageSize = largeButtonSize; + imageList[LARGE_BUTTONS] = new ImageList(); + imageList[LARGE_BUTTONS].ImageSize = largeButtonSize; if (DpiHelper.IsScalingRequired) { @@ -2612,7 +2612,7 @@ private void EnsureLargeButtons() { if (images[i] is Bitmap) { - this.imageList[LARGE_BUTTONS].Images.Add(new Bitmap((Bitmap)images[i], largeButtonSize.Width, largeButtonSize.Height)); + imageList[LARGE_BUTTONS].Images.Add(new Bitmap((Bitmap)images[i], largeButtonSize.Width, largeButtonSize.Height)); } } } @@ -2634,7 +2634,7 @@ private void AddLargeImage(Bitmap originalBitmap) largeBitmap = DpiHelper.CreateResizedBitmap(transparentBitmap, largeButtonSize); transparentBitmap.Dispose(); - this.imageList[LARGE_BUTTONS].Images.Add(largeBitmap); + imageList[LARGE_BUTTONS].Images.Add(largeBitmap); } catch (Exception ex) { @@ -2651,20 +2651,20 @@ bool IComPropertyBrowser.EnsurePendingChangesCommitted() try { - if (this.designerHost != null) + if (designerHost != null) { - designerHost.TransactionOpened -= new EventHandler(this.OnTransactionOpened); - designerHost.TransactionClosed -= new DesignerTransactionCloseEventHandler(this.OnTransactionClosed); + designerHost.TransactionOpened -= new EventHandler(OnTransactionOpened); + designerHost.TransactionClosed -= new DesignerTransactionCloseEventHandler(OnTransactionClosed); } return GetPropertyGridView().EnsurePendingChangesCommitted(); } finally { - if (this.designerHost != null) + if (designerHost != null) { - designerHost.TransactionOpened += new EventHandler(this.OnTransactionOpened); - designerHost.TransactionClosed += new DesignerTransactionCloseEventHandler(this.OnTransactionClosed); + designerHost.TransactionOpened += new EventHandler(OnTransactionOpened); + designerHost.TransactionClosed += new DesignerTransactionCloseEventHandler(OnTransactionClosed); } } } @@ -2844,9 +2844,9 @@ void IComPropertyBrowser.HandleF4() return; } - if (this.ActiveControl != gridView) + if (ActiveControl != gridView) { - this.SetActiveControl(gridView); + SetActiveControl(gridView); } gridView.Focus(); } @@ -2865,18 +2865,18 @@ void IComPropertyBrowser.LoadState(RegistryKey optRoot) if (val != null && val.ToString().Equals("1")) { - this.PropertySort = PropertySort.Alphabetical; + PropertySort = PropertySort.Alphabetical; } else { - this.PropertySort = PropertySort.Categorized | PropertySort.Alphabetical; + PropertySort = PropertySort.Categorized | PropertySort.Alphabetical; } val = optRoot.GetValue("PbrsShowDesc", "1"); - this.HelpVisible = (val != null && val.ToString().Equals("1")); + HelpVisible = (val != null && val.ToString().Equals("1")); val = optRoot.GetValue("PbrsShowCommands", "0"); - this.CommandsVisibleIfAvailable = (val != null && val.ToString().Equals("1")); + CommandsVisibleIfAvailable = (val != null && val.ToString().Equals("1")); val = optRoot.GetValue("PbrsDescHeightRatio", "-1"); @@ -2912,9 +2912,9 @@ void IComPropertyBrowser.LoadState(RegistryKey optRoot) { // apply the same defaults from above. // - this.PropertySort = PropertySort.Categorized | PropertySort.Alphabetical; - this.HelpVisible = true; - this.CommandsVisibleIfAvailable = false; + PropertySort = PropertySort.Categorized | PropertySort.Alphabetical; + HelpVisible = true; + CommandsVisibleIfAvailable = false; } } @@ -2925,12 +2925,12 @@ private void OnActiveDesignerChanged(object sender, ActiveDesignerEventArgs e) if (e.OldDesigner != null && e.OldDesigner == designerHost) { - this.ActiveDesigner = null; + ActiveDesigner = null; } if (e.NewDesigner != null && e.NewDesigner != designerHost) { - this.ActiveDesigner = e.NewDesigner; + ActiveDesigner = e.NewDesigner; } } @@ -2987,7 +2987,7 @@ private void OnChildMouseMove(object sender, MouseEventArgs me) if (ShouldForwardChildMouseMessage((Control)sender, me, ref newPt)) { // forward the message - this.OnMouseMove(new MouseEventArgs(me.Button, me.Clicks, newPt.X, newPt.Y, me.Delta)); + OnMouseMove(new MouseEventArgs(me.Button, me.Clicks, newPt.X, newPt.Y, me.Delta)); return; } } @@ -3003,7 +3003,7 @@ private void OnChildMouseDown(object sender, MouseEventArgs me) if (ShouldForwardChildMouseMessage((Control)sender, me, ref newPt)) { // forward the message - this.OnMouseDown(new MouseEventArgs(me.Button, me.Clicks, newPt.X, newPt.Y, me.Delta)); + OnMouseDown(new MouseEventArgs(me.Button, me.Clicks, newPt.X, newPt.Y, me.Delta)); return; } } @@ -3088,14 +3088,14 @@ private void OnComponentRemove(object sender, ComponentEventArgs e) if (!GetFlag(BatchMode)) { - this.SelectedObjects = newObjects; + SelectedObjects = newObjects; } else { // otherwise, just dump the selection // gridView.ClearProps(); - this.currentObjects = newObjects; + currentObjects = newObjects; SetFlag(FullRefreshAfterBatch, true); } } @@ -3125,7 +3125,7 @@ protected override void OnFontChanged(EventArgs e) /// internal void OnGridViewMouseWheel(MouseEventArgs e) { - this.OnMouseWheel(e); + OnMouseWheel(e); } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] @@ -3134,7 +3134,7 @@ protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); OnLayoutInternal(false); - TypeDescriptor.Refreshed += new RefreshEventHandler(this.OnTypeDescriptorRefreshed); + TypeDescriptor.Refreshed += new RefreshEventHandler(OnTypeDescriptorRefreshed); if (currentObjects != null && currentObjects.Length > 0) { Refresh(true); @@ -3145,7 +3145,7 @@ protected override void OnHandleCreated(EventArgs e) // protected override void OnHandleDestroyed(EventArgs e) { - TypeDescriptor.Refreshed -= new RefreshEventHandler(this.OnTypeDescriptorRefreshed); + TypeDescriptor.Refreshed -= new RefreshEventHandler(OnTypeDescriptorRefreshed); base.OnHandleDestroyed(e); } @@ -3157,17 +3157,17 @@ protected override void OnGotFocus(EventArgs e) base.OnGotFocus(e); - if (this.ActiveControl == null) + if (ActiveControl == null) { - this.SetActiveControl(gridView); + SetActiveControl(gridView); } else { // sometimes the edit is still the active control // when it's hidden or disabled... - if (!this.ActiveControl.Focus()) + if (!ActiveControl.Focus()) { - this.SetActiveControl(gridView); + SetActiveControl(gridView); } } } @@ -3187,7 +3187,7 @@ protected override void ScaleCore(float dx, float dy) private void OnLayoutInternal(bool dividerOnly) { - if (!IsHandleCreated || !this.Visible) + if (!IsHandleCreated || !Visible) { return; } @@ -3195,7 +3195,7 @@ private void OnLayoutInternal(bool dividerOnly) try { - this.FreezePainting = true; + FreezePainting = true; if (!dividerOnly) { @@ -3211,7 +3211,7 @@ private void OnLayoutInternal(bool dividerOnly) if (toolStrip.Visible) { - int toolStripWidth = this.Width; + int toolStripWidth = Width; int toolStripHeight = ((LargeButtons) ? largeButtonSize : normalButtonSize).Height + toolStripButtonPaddingY; Rectangle toolStripBounds = new Rectangle(0, 1, toolStripWidth, toolStripHeight); toolStrip.Bounds = toolStripBounds; @@ -3268,7 +3268,7 @@ private void OnLayoutInternal(bool dividerOnly) } else if (dcSizeRatio != -1) { - dcRequestedHeight = (this.Height * dcSizeRatio) / 100; + dcRequestedHeight = (Height * dcSizeRatio) / 100; } else { @@ -3285,7 +3285,7 @@ private void OnLayoutInternal(bool dividerOnly) } else if (hcSizeRatio != -1) { - hcRequestedHeight = (this.Height * hcSizeRatio) / 100; + hcRequestedHeight = (Height * hcSizeRatio) / 100; } else { @@ -3327,7 +3327,7 @@ private void OnLayoutInternal(bool dividerOnly) } else if (dcSizeRatio != -1 || doccomment.userSized) { - dcSizeRatio = (doccomment.Height * 100) / this.Height; + dcSizeRatio = (doccomment.Height * 100) / Height; } doccomment.Invalidate(); @@ -3361,7 +3361,7 @@ private void OnLayoutInternal(bool dividerOnly) } else if (hcSizeRatio != -1 || hotcommands.userSized) { - hcSizeRatio = (hotcommands.Height * 100) / this.Height; + hcSizeRatio = (hotcommands.Height * 100) / Height; } hotcommands.SetBounds(0, endSize - height, Size.Width, height); @@ -3373,7 +3373,7 @@ private void OnLayoutInternal(bool dividerOnly) } finally { - this.FreezePainting = false; + FreezePainting = false; } } @@ -3477,7 +3477,7 @@ int UnsafeNativeMethods.IPropertyNotifySink.OnRequestEdit(int dispID) // protected override void OnResize(EventArgs e) { - if (IsHandleCreated && this.Visible) + if (IsHandleCreated && Visible) { OnLayoutInternal(false); } @@ -3616,7 +3616,7 @@ internal void OnPropertyValueSet(GridItem changedItem, object oldValue) if (dropDown && !gridView.DropDownVisible) { - this.AccessibilityObject.RaiseAutomationNotification( + AccessibilityObject.RaiseAutomationNotification( Automation.AutomationNotificationKind.ActionCompleted, Automation.AutomationNotificationProcessing.All, string.Format(SR.PropertyGridPropertyValueSelectedFormat, changedItem.Value)); @@ -3664,14 +3664,14 @@ private void OnTransactionClosed(object sender, DesignerTransactionCloseEventArg if (currentSelection.Site == null) //The component is not logically sited...so clear the PropertyGrid Selection.. { //Setting to null... actually will clear off the state information so that ProperyGrid is in sane State. - this.SelectedObject = null; + SelectedObject = null; return; } } SetFlag(BatchMode, false); if (GetFlag(FullRefreshAfterBatch)) { - this.SelectedObjects = currentObjects; + SelectedObjects = currentObjects; SetFlag(FullRefreshAfterBatch, false); } else if (GetFlag(BatchModeChange)) @@ -3691,7 +3691,7 @@ private void OnTypeDescriptorRefreshed(RefreshEventArgs e) { if (InvokeRequired) { - BeginInvoke(new RefreshEventHandler(this.OnTypeDescriptorRefreshedInvoke), new object[] { e }); + BeginInvoke(new RefreshEventHandler(OnTypeDescriptorRefreshedInvoke), new object[] { e }); } else { @@ -3722,7 +3722,7 @@ private void OnViewSortButtonClick(object sender, EventArgs e) try { - this.FreezePainting = true; + FreezePainting = true; // is this tab selected? If so, do nothing. if (sender == viewSortButtons[selectedViewSort]) @@ -3767,7 +3767,7 @@ private void OnViewSortButtonClick(object sender, EventArgs e) } finally { - this.FreezePainting = false; + FreezePainting = false; } OnButtonClick(sender, e); @@ -3778,14 +3778,14 @@ private void OnViewTabButtonClick(object sender, EventArgs e) try { - this.FreezePainting = true; + FreezePainting = true; SelectViewTabButton((ToolStripButton)sender, true); OnLayoutInternal(false); SaveTabSelection(); } finally { - this.FreezePainting = false; + FreezePainting = false; } OnButtonClick(sender, e); @@ -4133,7 +4133,7 @@ protected override bool ProcessDialogKey(Keys keyData) bool result = base.ProcessDialogKey(keyData); // if we're not hosted in a windows forms thing, just give the parent the focus - if (!result && this.Parent == null) + if (!result && Parent == null) { IntPtr hWndParent = UnsafeNativeMethods.GetParent(new HandleRef(this, Handle)); if (hWndParent != IntPtr.Zero) @@ -4191,7 +4191,7 @@ private void Refresh(bool clearCached) try { - this.FreezePainting = true; + FreezePainting = true; SetFlag(RefreshingProperties, true); if (clearCached) @@ -4204,7 +4204,7 @@ private void Refresh(bool clearCached) } finally { - this.FreezePainting = false; + FreezePainting = false; SetFlag(RefreshingProperties, false); } } @@ -4580,9 +4580,9 @@ void IComPropertyBrowser.SaveState(RegistryKey optRoot) return; } - optRoot.SetValue("PbrsAlpha", (this.PropertySort == PropertySort.Alphabetical ? "1" : "0")); - optRoot.SetValue("PbrsShowDesc", (this.HelpVisible ? "1" : "0")); - optRoot.SetValue("PbrsShowCommands", (this.CommandsVisibleIfAvailable ? "1" : "0")); + optRoot.SetValue("PbrsAlpha", (PropertySort == PropertySort.Alphabetical ? "1" : "0")); + optRoot.SetValue("PbrsShowDesc", (HelpVisible ? "1" : "0")); + optRoot.SetValue("PbrsShowCommands", (CommandsVisibleIfAvailable ? "1" : "0")); optRoot.SetValue("PbrsDescHeightRatio", dcSizeRatio.ToString(CultureInfo.InvariantCulture)); optRoot.SetValue("PbrsHotCommandHeightRatio", hcSizeRatio.ToString(CultureInfo.InvariantCulture)); } @@ -4749,7 +4749,7 @@ private void SetupToolbar(bool fullRebuild) try { - this.FreezePainting = true; + FreezePainting = true; if (imageList[NORMAL_BUTTONS] == null || fullRebuild) @@ -4762,9 +4762,9 @@ private void SetupToolbar(bool fullRebuild) } // setup our event handlers - EventHandler ehViewTab = new EventHandler(this.OnViewTabButtonClick); - EventHandler ehViewType = new EventHandler(this.OnViewSortButtonClick); - EventHandler ehPP = new EventHandler(this.OnViewButtonClickPP); + EventHandler ehViewTab = new EventHandler(OnViewTabButtonClick); + EventHandler ehViewType = new EventHandler(OnViewSortButtonClick); + EventHandler ehPP = new EventHandler(OnViewButtonClickPP); Bitmap b; int i; @@ -4910,7 +4910,7 @@ private void SetupToolbar(bool fullRebuild) EnsureLargeButtons(); } - toolStrip.ImageList = imageList[this.buttonType]; + toolStrip.ImageList = imageList[buttonType]; toolStrip.SuspendLayout(); toolStrip.Items.Clear(); @@ -4932,7 +4932,7 @@ private void SetupToolbar(bool fullRebuild) } finally { - this.FreezePainting = false; + FreezePainting = false; } } @@ -5150,7 +5150,7 @@ internal void UpdateSelection() { if (currentObjects != null && currentObjects.Length > 0) { - peMain = (GridEntry)GridEntry.Create(gridView, currentObjects, new PropertyGridServiceProvider(this), designerHost, this.SelectedTab, propertySortValue); + peMain = (GridEntry)GridEntry.Create(gridView, currentObjects, new PropertyGridServiceProvider(this), designerHost, SelectedTab, propertySortValue); } else { @@ -5446,7 +5446,7 @@ protected override void WndProc(ref Message m) } case AutomationMessages.PGM_GETROWCOORDS: - if (m.Msg == this.dwMsg) + if (m.Msg == dwMsg) { m.Result = (IntPtr)gridView.GetPropertyLocation(propName, m.LParam == IntPtr.Zero, m.WParam == IntPtr.Zero); return; @@ -5534,7 +5534,7 @@ public Color BorderColor protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); - Rectangle r = this.ClientRectangle; + Rectangle r = ClientRectangle; r.Width--; r.Height--; using (Pen borderPen = new Pen(BorderColor, 1)) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/ArrayElementGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/ArrayElementGridEntry.cs index e875defca50..ff69f90a4f1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/ArrayElementGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/ArrayElementGridEntry.cs @@ -28,7 +28,7 @@ public ArrayElementGridEntry(PropertyGrid ownerGrid, GridEntry peParent, int ind : base(ownerGrid, peParent) { this.index = index; - this.SetFlag(FLAG_RENDER_READONLY, (peParent.Flags & FLAG_RENDER_READONLY) != 0 || peParent.ForceReadOnly); + SetFlag(FLAG_RENDER_READONLY, (peParent.Flags & FLAG_RENDER_READONLY) != 0 || peParent.ForceReadOnly); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/CategoryGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/CategoryGridEntry.cs index 7be8b4e1797..639f25784dc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/CategoryGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/CategoryGridEntry.cs @@ -55,21 +55,21 @@ public CategoryGridEntry(PropertyGrid ownerGrid, GridEntry peParent, string name } } - this.IsExpandable = true; + IsExpandable = true; for (int i = 0; i < childGridEntries.Length; i++) { childGridEntries[i].ParentGridEntry = this; } - this.ChildCollection = new GridEntryCollection(this, childGridEntries); + ChildCollection = new GridEntryCollection(this, childGridEntries); lock (categoryStates) { - this.InternalExpanded = (bool)categoryStates[name]; + InternalExpanded = (bool)categoryStates[name]; } - this.SetFlag(GridEntry.FLAG_LABEL_BOLD, true); + SetFlag(GridEntry.FLAG_LABEL_BOLD, true); } @@ -131,7 +131,7 @@ protected override GridEntryAccessibleObject GetAccessibilityObject() protected override Brush GetBackgroundBrush(Graphics g) { - return this.GridEntryHost.GetLineBrush(g); + return GridEntryHost.GetLineBrush(g); } protected override Color LabelTextColor @@ -157,7 +157,7 @@ internal override bool InternalExpanded base.InternalExpanded = value; lock (categoryStates) { - categoryStates[this.name] = value; + categoryStates[name] = value; } } } @@ -191,7 +191,7 @@ internal override int PropertyLabelIndent { // we give an extra pixel for breathing room // we want to make sure that we return 0 for property depth here instead of - PropertyGridView gridHost = this.GridEntryHost; + PropertyGridView gridHost = GridEntryHost; // we call base.PropertyDepth here because we don't want the subratction to happen. return 1 + gridHost.GetOutlineIconSize() + OUTLINE_ICON_PADDING + (base.PropertyDepth * gridHost.GetDefaultOutlineIndent()); @@ -229,7 +229,7 @@ public override string GetTestingInfo() { string str = "object = ("; str += FullLabel; - str += "), Category = (" + this.PropertyLabel + ")"; + str += "), Category = (" + PropertyLabel + ")"; return str; } @@ -241,9 +241,9 @@ public override void PaintLabel(System.Drawing.Graphics g, Rectangle rect, Recta // now draw the focus rect if (selected && hasFocus) { - bool bold = ((this.Flags & GridEntry.FLAG_LABEL_BOLD) != 0); + bool bold = ((Flags & GridEntry.FLAG_LABEL_BOLD) != 0); Font font = GetFont(bold); - int labelWidth = GetLabelTextWidth(this.PropertyLabel, g, font); + int labelWidth = GetLabelTextWidth(PropertyLabel, g, font); int indent = PropertyLabelIndent - 2; Rectangle focusRect = new Rectangle(indent, rect.Y, labelWidth + 3, rect.Height - 1); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs index fe728dd9fbc..ecae3f2b447 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs @@ -60,7 +60,7 @@ internal DocComment(PropertyGrid owner) : base(owner) Size = new Size(CXDEF, cydef); - this.Text = SR.PBRSDocCommentPaneTitle; + Text = SR.PBRSDocCommentPaneTitle; SetStyle(ControlStyles.Selectable, false); ResumeLayout(false); } @@ -87,7 +87,7 @@ public override int GetOptimalHeight(int width) // do this to avoid getting parented to the Parking window. // - if (this.ownerGrid.IsHandleCreated && !IsHandleCreated) + if (ownerGrid.IsHandleCreated && !IsHandleCreated) { CreateControl(); } @@ -95,7 +95,7 @@ public override int GetOptimalHeight(int width) // compute optimal text height var isScalingRequirementMet = DpiHelper.IsScalingRequirementMet; Graphics g = m_labelDesc.CreateGraphicsInternal(); - SizeF sizef = PropertyGrid.MeasureTextHelper.MeasureText(this.ownerGrid, g, m_labelTitle.Text, Font, width); + SizeF sizef = PropertyGrid.MeasureTextHelper.MeasureText(ownerGrid, g, m_labelTitle.Text, Font, width); Size sz = Size.Ceiling(sizef); g.Dispose(); var padding = isScalingRequirementMet ? LogicalToDeviceUnits(2) : 2; @@ -118,8 +118,8 @@ protected override void OnLayout(LayoutEventArgs e) { UpdateUIWithFont(); SetChildLabelsBounds(); - m_labelDesc.Text = this.fullDesc; - m_labelDesc.AccessibleName = this.fullDesc; // Don't crop the description for accessibility clients + m_labelDesc.Text = fullDesc; + m_labelDesc.AccessibleName = fullDesc; // Don't crop the description for accessibility clients base.OnLayout(e); } @@ -203,9 +203,9 @@ public virtual void SetComment(string title, string desc) if (desc != fullDesc) { - this.fullDesc = desc; + fullDesc = desc; m_labelDesc.Text = fullDesc; - m_labelDesc.AccessibleName = this.fullDesc; // Don't crop the description for accessibility clients + m_labelDesc.AccessibleName = fullDesc; // Don't crop the description for accessibility clients } } @@ -233,8 +233,8 @@ protected override AccessibleObject CreateAccessibilityInstance() internal void UpdateTextRenderingEngine() { - m_labelTitle.UseCompatibleTextRendering = this.ownerGrid.UseCompatibleTextRendering; - m_labelDesc.UseCompatibleTextRendering = this.ownerGrid.UseCompatibleTextRendering; + m_labelTitle.UseCompatibleTextRendering = ownerGrid.UseCompatibleTextRendering; + m_labelDesc.UseCompatibleTextRendering = ownerGrid.UseCompatibleTextRendering; } private void UpdateUIWithFont() diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DropDownButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DropDownButton.cs index 16efefc7273..5596864b9f2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DropDownButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DropDownButton.cs @@ -117,7 +117,7 @@ protected override void OnPaint(PaintEventArgs pevent) } else { - ComboBoxRenderer.DrawDropDownButtonForHandle(pevent.Graphics, dropDownButtonRect, cbState, this.HandleInternal); + ComboBoxRenderer.DrawDropDownButtonForHandle(pevent.Graphics, dropDownButtonRect, cbState, HandleInternal); } // Redraw focus cues @@ -143,11 +143,11 @@ private void SetAccessibleName() { if (useComboBoxTheme) { - this.AccessibleName = SR.PropertyGridDropDownButtonComboBoxAccessibleName; + AccessibleName = SR.PropertyGridDropDownButtonComboBoxAccessibleName; } else { - this.AccessibleName = SR.PropertyGridDropDownButtonAccessibleName; + AccessibleName = SR.PropertyGridDropDownButtonAccessibleName; } } @@ -240,7 +240,7 @@ internal override void PaintUp(PaintEventArgs pevent, CheckState state) internal override void DrawImageCore(Graphics graphics, Image image, Rectangle imageBounds, Point imageStart, ButtonBaseAdapter.LayoutData layout) { - ControlPaint.DrawImageReplaceColor(graphics, image, imageBounds, Color.Black, this.IsHighContrastHighlighted() && !this.Control.MouseIsDown ? SystemColors.HighlightText : Control.ForeColor); + ControlPaint.DrawImageReplaceColor(graphics, image, imageBounds, Color.Black, IsHighContrastHighlighted() && !Control.MouseIsDown ? SystemColors.HighlightText : Control.ForeColor); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs index b771b181127..3245b26cfbc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs @@ -143,12 +143,12 @@ protected GridEntry(PropertyGrid owner, GridEntry peParent) parentPE = peParent; ownerGrid = owner; - Debug.Assert(this.ownerGrid != null, "GridEntry w/o PropertyGrid owner, text rendering will fail."); + Debug.Assert(ownerGrid != null, "GridEntry w/o PropertyGrid owner, text rendering will fail."); if (peParent != null) { propertyDepth = peParent.PropertyDepth + 1; - this.PropertySort = peParent.PropertySort; + PropertySort = peParent.PropertySort; if (peParent.ForceReadOnly) { @@ -171,9 +171,9 @@ private int OutlineIconPadding { if (DpiHelper.IsScalingRequirementMet) { - if (this.GridEntryHost != null) + if (GridEntryHost != null) { - return this.GridEntryHost.LogicalToDeviceUnits(OUTLINE_ICON_PADDING); + return GridEntryHost.LogicalToDeviceUnits(OUTLINE_ICON_PADDING); } } @@ -251,7 +251,7 @@ protected virtual Color LabelTextColor { get { - if (this.ShouldRenderReadOnly) + if (ShouldRenderReadOnly) { return GridEntryHost.GrayTextColor; } @@ -350,14 +350,14 @@ protected GridEntryCollection ChildCollection set { Debug.Assert(value == null || !Disposed, "Why are we putting new children in after we are disposed?"); - if (this.childCollection != value) + if (childCollection != value) { - if (this.childCollection != null) + if (childCollection != null) { - this.childCollection.Dispose(); - this.childCollection = null; + childCollection.Dispose(); + childCollection = null; } - this.childCollection = value; + childCollection = value; } } } @@ -449,7 +449,7 @@ internal virtual bool Enumerable { get { - return (this.Flags & GridEntry.FLAG_ENUMERABLE) != 0; + return (Flags & GridEntry.FLAG_ENUMERABLE) != 0; } } @@ -470,7 +470,7 @@ public override bool Expandable return false; } - if (fExpandable && (cacheItems == null || cacheItems.lastValue == null) && this.PropertyValue == null) + if (fExpandable && (cacheItems == null || cacheItems.lastValue == null) && PropertyValue == null) { fExpandable = false; } @@ -512,7 +512,7 @@ internal virtual bool InternalExpanded } set { - if (!this.Expandable || value == this.InternalExpanded) + if (!Expandable || value == InternalExpanded) { return; } @@ -564,7 +564,7 @@ internal virtual int Flags TypeConverter converter = TypeConverter; UITypeEditor uiEditor = UITypeEditor; object value = Instance; - bool forceReadOnly = this.ForceReadOnly; + bool forceReadOnly = ForceReadOnly; if (value != null) { @@ -582,7 +582,7 @@ internal virtual int Flags flags |= GridEntry.FLAG_TEXT_EDITABLE; } - bool isImmutableReadOnly = TypeDescriptor.GetAttributes(this.PropertyType)[typeof(ImmutableObjectAttribute)].Equals(ImmutableObjectAttribute.Yes); + bool isImmutableReadOnly = TypeDescriptor.GetAttributes(PropertyType)[typeof(ImmutableObjectAttribute)].Equals(ImmutableObjectAttribute.Yes); bool isImmutable = isImmutableReadOnly || converter.GetCreateInstanceSupported(this); if (isImmutable) @@ -656,7 +656,7 @@ public bool Focus { get { - return this.hasFocus; + return hasFocus; } set { @@ -673,9 +673,9 @@ public bool Focus cacheItems.useShouldSerialize = false; } - if (this.hasFocus != value) + if (hasFocus != value) { - this.hasFocus = value; + hasFocus = value; // Notify accessibility applications that keyboard focus has changed. // @@ -719,7 +719,7 @@ public string FullLabel { str = string.Empty; } - str += this.PropertyLabel; + str += PropertyLabel; return str; } @@ -739,7 +739,7 @@ public override GridItemCollection GridItems CreateChildren(); } - return this.Children; + return Children; } } @@ -805,7 +805,7 @@ internal virtual string HelpKeywordInternal { get { - return this.HelpKeyword; + return HelpKeyword; } } @@ -816,13 +816,13 @@ public virtual bool IsCustomPaint // prevent full flag population if possible. if ((flags & FL_CHECKED) == 0) { - UITypeEditor typeEd = this.UITypeEditor; + UITypeEditor typeEd = UITypeEditor; if (typeEd != null) { - if ((this.flags & GridEntry.FLAG_CUSTOM_PAINT) != 0 || - (this.flags & GridEntry.FL_NO_CUSTOM_PAINT) != 0) + if ((flags & GridEntry.FLAG_CUSTOM_PAINT) != 0 || + (flags & GridEntry.FL_NO_CUSTOM_PAINT) != 0) { - return (this.flags & GridEntry.FLAG_CUSTOM_PAINT) != 0; + return (flags & GridEntry.FLAG_CUSTOM_PAINT) != 0; } @@ -838,7 +838,7 @@ public virtual bool IsCustomPaint } } } - return (this.Flags & GridEntry.FLAG_CUSTOM_PAINT) != 0; + return (Flags & GridEntry.FLAG_CUSTOM_PAINT) != 0; } } @@ -846,7 +846,7 @@ public virtual bool IsExpandable { get { - return this.Expandable; + return Expandable; } set { @@ -862,7 +862,7 @@ public virtual bool IsTextEditable { get { - return this.IsValueEditable && (this.Flags & GridEntry.FLAG_TEXT_EDITABLE) != 0; + return IsValueEditable && (Flags & GridEntry.FLAG_TEXT_EDITABLE) != 0; } } @@ -898,7 +898,7 @@ public override string Label { get { - return this.PropertyLabel; + return PropertyLabel; } } @@ -922,7 +922,7 @@ internal virtual int PropertyLabelIndent { get { - int borderWidth = this.GridEntryHost.GetOutlineIconSize() + OUTLINE_ICON_PADDING; + int borderWidth = GridEntryHost.GetOutlineIconSize() + OUTLINE_ICON_PADDING; return ((propertyDepth + 1) * borderWidth) + 1; } } @@ -936,7 +936,7 @@ internal virtual string LabelToolTipText { get { - return this.PropertyLabel; + return PropertyLabel; } } @@ -944,7 +944,7 @@ public virtual bool NeedsDropDownButton { get { - return (this.Flags & GridEntry.FLAG_DROPDOWN_EDITABLE) != 0; + return (Flags & GridEntry.FLAG_DROPDOWN_EDITABLE) != 0; } } @@ -952,7 +952,7 @@ public virtual bool NeedsCustomEditorButton { get { - return (this.Flags & GridEntry.FLAG_CUSTOM_EDITABLE) != 0 && (IsValueEditable || (Flags & GridEntry.FLAG_READONLY_EDITABLE) != 0); + return (Flags & GridEntry.FLAG_CUSTOM_EDITABLE) != 0 && (IsValueEditable || (Flags & GridEntry.FLAG_READONLY_EDITABLE) != 0); } } @@ -960,7 +960,7 @@ public PropertyGrid OwnerGrid { get { - return this.ownerGrid; + return ownerGrid; } } @@ -976,7 +976,7 @@ public Rectangle OutlineRect { return outlineRect; } - PropertyGridView gridHost = this.GridEntryHost; + PropertyGridView gridHost = GridEntryHost; Debug.Assert(gridHost != null, "No propEntryHost!"); int outlineSize = gridHost.GetOutlineIconSize(); int borderWidth = outlineSize + OutlineIconPadding; @@ -999,18 +999,18 @@ public virtual GridEntry ParentGridEntry { get { - return this.parentPE; + return parentPE; } set { Debug.Assert(value != this, "how can we be our own parent?"); - this.parentPE = value; + parentPE = value; if (value != null) { propertyDepth = value.PropertyDepth + 1; // Microsoft, why do we do this? - if (this.childCollection != null) + if (childCollection != null) { for (int i = 0; i < childCollection.Count; i++) { @@ -1030,7 +1030,7 @@ public override GridItem Parent throw new ObjectDisposedException(SR.GridItemDisposed); } - GridItem parent = this.ParentGridEntry; + GridItem parent = ParentGridEntry; // don't allow walking all the way up to the parent. // @@ -1095,7 +1095,7 @@ public virtual string PropertyName { get { - return this.PropertyLabel; + return PropertyLabel; } } @@ -1106,7 +1106,7 @@ public virtual Type PropertyType { get { - object obj = this.PropertyValue; + object obj = PropertyValue; if (obj != null) { return obj.GetType(); @@ -1141,7 +1141,7 @@ public virtual bool ShouldRenderPassword { get { - return (this.Flags & GridEntry.FLAG_RENDER_PASSWORD) != 0; + return (Flags & GridEntry.FLAG_RENDER_PASSWORD) != 0; } } @@ -1149,7 +1149,7 @@ public virtual bool ShouldRenderReadOnly { get { - return ForceReadOnly || (0 != (this.Flags & GridEntry.FLAG_RENDER_READONLY) || (!this.IsValueEditable && (0 == (this.Flags & GridEntry.FLAG_READONLY_EDITABLE)))); + return ForceReadOnly || (0 != (Flags & GridEntry.FLAG_RENDER_READONLY) || (!IsValueEditable && (0 == (Flags & GridEntry.FLAG_READONLY_EDITABLE)))); } } @@ -1162,10 +1162,10 @@ internal virtual TypeConverter TypeConverter { if (converter == null) { - object value = this.PropertyValue; + object value = PropertyValue; if (value == null) { - converter = TypeDescriptor.GetConverter(this.PropertyType); + converter = TypeDescriptor.GetConverter(PropertyType); } else { @@ -1184,9 +1184,9 @@ internal virtual UITypeEditor UITypeEditor { get { - if (editor == null && this.PropertyType != null) + if (editor == null && PropertyType != null) { - editor = (UITypeEditor)TypeDescriptor.GetEditor(this.PropertyType, typeof(System.Drawing.Design.UITypeEditor)); + editor = (UITypeEditor)TypeDescriptor.GetEditor(PropertyType, typeof(System.Drawing.Design.UITypeEditor)); } return editor; @@ -1197,7 +1197,7 @@ public override object Value { get { - return this.PropertyValue; + return PropertyValue; } // note: we don't do set because of the value class semantics, etc. } @@ -1380,13 +1380,13 @@ protected virtual bool CreateChildren(bool diffOldChildren) if (!GetFlagSet(FL_EXPANDABLE)) { - if (this.childCollection != null) + if (childCollection != null) { - this.childCollection.Clear(); + childCollection.Clear(); } else { - this.childCollection = new GridEntryCollection(this, new GridEntry[0]); + childCollection = new GridEntryCollection(this, new GridEntry[0]); } return false; } @@ -1399,8 +1399,8 @@ protected virtual bool CreateChildren(bool diffOldChildren) GridEntry[] childProps = GetPropEntries(this, - this.PropertyValue, - this.PropertyType); + PropertyValue, + PropertyType); bool fExpandable = (childProps != null && childProps.Length > 0); @@ -1435,31 +1435,31 @@ protected virtual bool CreateChildren(bool diffOldChildren) if (!fExpandable) { SetFlag(FL_EXPANDABLE_FAILED, true); - if (this.childCollection != null) + if (childCollection != null) { - this.childCollection.Clear(); + childCollection.Clear(); } else { - this.childCollection = new GridEntryCollection(this, new GridEntry[0]); + childCollection = new GridEntryCollection(this, new GridEntry[0]); } - if (this.InternalExpanded) + if (InternalExpanded) { - this.InternalExpanded = false; + InternalExpanded = false; } } else { - if (this.childCollection != null) + if (childCollection != null) { - this.childCollection.Clear(); - this.childCollection.AddRange(childProps); + childCollection.Clear(); + childCollection.AddRange(childProps); } else { - this.childCollection = new GridEntryCollection(this, childProps); + childCollection = new GridEntryCollection(this, childProps); } } return fExpandable; @@ -1531,18 +1531,18 @@ internal virtual void EditPropertyValue(PropertyGridView iva) } // Push the new value back into the property - if (value != originalValue && this.IsValueEditable) + if (value != originalValue && IsValueEditable) { iva.CommitValue(this, value); } - if (this.InternalExpanded) + if (InternalExpanded) { // QFE#3299: If edited property is expanded to show sub-properties, then we want to // preserve the expanded states of it and all of its descendants. RecreateChildren() // has logic that is supposed to do this, but which is fundamentally flawed. PropertyGridView.GridPositionData positionData = GridEntryHost.CaptureGridPositionData(); - this.InternalExpanded = false; + InternalExpanded = false; RecreateChildren(); positionData.Restore(GridEntryHost); } @@ -1577,7 +1577,7 @@ public override bool Equals(object obj) if (NonParentEquals(obj)) { - return ((GridEntry)obj).ParentGridEntry == this.ParentGridEntry; + return ((GridEntry)obj).ParentGridEntry == ParentGridEntry; } return false; } @@ -1605,7 +1605,7 @@ public virtual object FindPropertyValue(string propertyName, Type propertyType) /// internal virtual int GetChildIndex(GridEntry pe) { - return this.Children.GetEntry(pe); + return Children.GetEntry(pe); } /// @@ -1635,7 +1635,7 @@ protected int GetLabelTextWidth(string labelText, Graphics g, Font f) return cacheItems.lastLabelWidth; } - SizeF textSize = PropertyGrid.MeasureTextHelper.MeasureText(this.ownerGrid, g, labelText, f); + SizeF textSize = PropertyGrid.MeasureTextHelper.MeasureText(ownerGrid, g, labelText, f); cacheItems.lastLabelWidth = (int)textSize.Width; cacheItems.lastLabel = labelText; @@ -1681,7 +1681,7 @@ public virtual object GetValueOwner() { if (parentPE == null) { - return this.PropertyValue; + return PropertyValue; } return parentPE.GetChildValueOwner(this); @@ -1718,7 +1718,7 @@ public virtual object GetChildValueOwner(GridEntry childEntry) Debug.Fail(childEntry.PropertyLabel + " is not a child of " + this.PropertyLabel); return null;*/ - return this.PropertyValue; + return PropertyValue; } /// @@ -1737,13 +1737,13 @@ public virtual string GetTestingInfo() // make sure we clear any embedded nulls textVal = textVal.Replace((char)0, ' '); } - Type type = this.PropertyType; + Type type = PropertyType; if (type == null) { type = typeof(object); } - str += this.FullLabel; - str += "), property = (" + this.PropertyLabel + "," + type.AssemblyQualifiedName + "), value = " + "[" + textVal + "], expandable = " + this.Expandable.ToString() + ", readOnly = " + ShouldRenderReadOnly; + str += FullLabel; + str += "), property = (" + PropertyLabel + "," + type.AssemblyQualifiedName + "), value = " + "[" + textVal + "], expandable = " + Expandable.ToString() + ", readOnly = " + ShouldRenderReadOnly; ; return str; } @@ -1753,7 +1753,7 @@ public virtual string GetTestingInfo() /// public virtual Type GetValueType() { - return this.PropertyType; + return PropertyType; } /// @@ -1771,16 +1771,16 @@ protected virtual GridEntry[] GetPropEntries(GridEntry peParent, object obj, Typ GridEntry[] entries = null; - Attribute[] attributes = new Attribute[this.BrowsableAttributes.Count]; - this.BrowsableAttributes.CopyTo(attributes, 0); + Attribute[] attributes = new Attribute[BrowsableAttributes.Count]; + BrowsableAttributes.CopyTo(attributes, 0); - PropertyTab tab = this.CurrentTab; + PropertyTab tab = CurrentTab; Debug.Assert(tab != null, "No current tab!"); try { - bool forceReadOnly = this.ForceReadOnly; + bool forceReadOnly = ForceReadOnly; if (!forceReadOnly) { @@ -1813,7 +1813,7 @@ protected virtual GridEntry[] GetPropEntries(GridEntry peParent, object obj, Typ return null; } - if ((this.PropertySort & PropertySort.Alphabetical) != 0) + if ((PropertySort & PropertySort.Alphabetical) != 0) { if (objType == null || !objType.IsArray) { @@ -1843,7 +1843,7 @@ protected virtual GridEntry[] GetPropEntries(GridEntry peParent, object obj, Typ for (int i = 0; i < entries.Length; i++) { - entries[i] = new ArrayElementGridEntry(this.ownerGrid, peParent, i); + entries[i] = new ArrayElementGridEntry(ownerGrid, peParent, i); } } else @@ -1883,11 +1883,11 @@ protected virtual GridEntry[] GetPropEntries(GridEntry peParent, object obj, Typ if (createInstanceSupported) { - newEntry = new ImmutablePropertyDescriptorGridEntry(this.ownerGrid, peParent, pd, hide); + newEntry = new ImmutablePropertyDescriptorGridEntry(ownerGrid, peParent, pd, hide); } else { - newEntry = new PropertyDescriptorGridEntry(this.ownerGrid, peParent, pd, hide); + newEntry = new PropertyDescriptorGridEntry(ownerGrid, peParent, pd, hide); } if (forceReadOnly) @@ -1899,7 +1899,7 @@ protected virtual GridEntry[] GetPropEntries(GridEntry peParent, object obj, Typ // if (pd.Equals(defProp)) { - this.DefaultChild = newEntry; + DefaultChild = newEntry; } // add it to the array. @@ -1994,7 +1994,7 @@ public virtual bool DoubleClickPropertyValue() /// public virtual string GetPropertyTextValue() { - return GetPropertyTextValue(this.PropertyValue); + return GetPropertyTextValue(PropertyValue); } /// @@ -2039,8 +2039,8 @@ public virtual object[] GetPropertyValueList() public override int GetHashCode() { // These can be null, so workaround giving hashcode = 0 for null objects. - object label = this.PropertyLabel; - object type = this.PropertyType; + object label = PropertyLabel; + object type = PropertyType; uint h1 = (uint)((label == null) ? 0 : label.GetHashCode()); uint h2 = (uint)((type == null) ? 0 : type.GetHashCode()); uint h3 = (uint)GetType().GetHashCode(); @@ -2102,8 +2102,8 @@ internal virtual bool NonParentEquals(object obj) return false; GridEntry pe = (GridEntry)obj; - return pe.PropertyLabel.Equals(this.PropertyLabel) && - pe.PropertyType.Equals(this.PropertyType) && pe.PropertyDepth == this.PropertyDepth; + return pe.PropertyLabel.Equals(PropertyLabel) && + pe.PropertyType.Equals(PropertyType) && pe.PropertyDepth == PropertyDepth; } @@ -2114,27 +2114,27 @@ internal virtual bool NonParentEquals(object obj) /// public virtual void PaintLabel(System.Drawing.Graphics g, Rectangle rect, Rectangle clipRect, bool selected, bool paintFullLabel) { - PropertyGridView gridHost = this.GridEntryHost; + PropertyGridView gridHost = GridEntryHost; Debug.Assert(gridHost != null, "No propEntryHost"); - string strLabel = this.PropertyLabel; + string strLabel = PropertyLabel; int borderWidth = gridHost.GetOutlineIconSize() + OUTLINE_ICON_PADDING; // fill the background if necessary - Brush bkBrush = selected ? gridHost.GetSelectedItemWithFocusBackBrush(g) : this.GetBackgroundBrush(g); + Brush bkBrush = selected ? gridHost.GetSelectedItemWithFocusBackBrush(g) : GetBackgroundBrush(g); // if we don't have focus, paint with the line color if (selected && !hasFocus) { bkBrush = gridHost.GetLineBrush(g); } - bool fBold = ((this.Flags & GridEntry.FLAG_LABEL_BOLD) != 0); + bool fBold = ((Flags & GridEntry.FLAG_LABEL_BOLD) != 0); Font font = GetFont(fBold); int labelWidth = GetLabelTextWidth(strLabel, g, font); int neededWidth = paintFullLabel ? labelWidth : 0; - int stringX = rect.X + this.PropertyLabelIndent; + int stringX = rect.X + PropertyLabelIndent; Brush blank = bkBrush; if (paintFullLabel && (neededWidth >= (rect.Width - (stringX + 2)))) @@ -2188,9 +2188,9 @@ public virtual void PaintLabel(System.Drawing.Graphics g, Rectangle rect, Rectan // Do actual drawing // A brush is needed if using GDI+ only (UseCompatibleTextRendering); if using GDI, only the color is needed. - Color textColor = selected && hasFocus ? gridHost.GetSelectedItemWithFocusForeColor() : shouldInvertForHC ? InvertColor(ownerGrid.LineColor) : g.GetNearestColor(this.LabelTextColor); + Color textColor = selected && hasFocus ? gridHost.GetSelectedItemWithFocusForeColor() : shouldInvertForHC ? InvertColor(ownerGrid.LineColor) : g.GetNearestColor(LabelTextColor); - if (this.ownerGrid.UseCompatibleTextRendering) + if (ownerGrid.UseCompatibleTextRendering) { using (Brush textBrush = new SolidBrush(textColor)) { @@ -2213,11 +2213,11 @@ public virtual void PaintLabel(System.Drawing.Graphics g, Rectangle rect, Rectan if (maxSpace <= labelWidth) { - this.labelTipPoint = new Point(stringX + 2, rect.Y + 1); + labelTipPoint = new Point(stringX + 2, rect.Y + 1); } else { - this.labelTipPoint = InvalidPoint; + labelTipPoint = InvalidPoint; } } @@ -2247,7 +2247,7 @@ public virtual void PaintOutline(System.Drawing.Graphics g, Rectangle r) outlineRect = Rectangle.Empty; lastPaintWithExplorerStyle = true; } - PaintOutlineWithExplorerTreeStyle(g, r, (GridEntryHost != null) ? this.GridEntryHost.HandleInternal : IntPtr.Zero); + PaintOutlineWithExplorerTreeStyle(g, r, (GridEntryHost != null) ? GridEntryHost.HandleInternal : IntPtr.Zero); } // draw tree-view glyphs as +/- else @@ -2268,10 +2268,10 @@ public virtual void PaintOutline(System.Drawing.Graphics g, Rectangle r) private void PaintOutlineWithExplorerTreeStyle(System.Drawing.Graphics g, Rectangle r, IntPtr handle) { - if (this.Expandable) + if (Expandable) { - bool fExpanded = this.InternalExpanded; - Rectangle outline = this.OutlineRect; + bool fExpanded = InternalExpanded; + Rectangle outline = OutlineRect; // make sure we're in our bounds outline = Rectangle.Intersect(r, outline); @@ -2304,10 +2304,10 @@ private void PaintOutlineWithExplorerTreeStyle(System.Drawing.Graphics g, Rectan private void PaintOutlineWithClassicStyle(System.Drawing.Graphics g, Rectangle r) { // draw outline box. - if (this.Expandable) + if (Expandable) { - bool fExpanded = this.InternalExpanded; - Rectangle outline = this.OutlineRect; + bool fExpanded = InternalExpanded; + Rectangle outline = OutlineRect; // make sure we're in our bounds outline = Rectangle.Intersect(r, outline); @@ -2315,7 +2315,7 @@ private void PaintOutlineWithClassicStyle(System.Drawing.Graphics g, Rectangle r return; // draw border area box - Brush b = this.GetBackgroundBrush(g); + Brush b = GetBackgroundBrush(g); Pen p; Color penColor = GridEntryHost.GetTextColor(); @@ -2368,12 +2368,12 @@ private void PaintOutlineWithClassicStyle(System.Drawing.Graphics g, Rectangle r /// public virtual void PaintValue(object val, System.Drawing.Graphics g, Rectangle rect, Rectangle clipRect, PaintValueFlags paintFlags) { - PropertyGridView gridHost = this.GridEntryHost; + PropertyGridView gridHost = GridEntryHost; Debug.Assert(gridHost != null, "No propEntryHost"); int cPaint = 0; Color textColor = gridHost.GetTextColor(); - if (this.ShouldRenderReadOnly) + if (ShouldRenderReadOnly) { textColor = GridEntryHost.GrayTextColor; } @@ -2389,7 +2389,7 @@ public virtual void PaintValue(object val, System.Drawing.Graphics g, Rectangle } else { - val = this.PropertyValue; + val = PropertyValue; strValue = GetPropertyTextValue(val); if (cacheItems == null) { @@ -2408,7 +2408,7 @@ public virtual void PaintValue(object val, System.Drawing.Graphics g, Rectangle } // paint out the main rect using the appropriate brush - Brush bkBrush = this.GetBackgroundBrush(g); + Brush bkBrush = GetBackgroundBrush(g); Debug.Assert(bkBrush != null, "We didn't find a good background brush for PaintValue"); if ((paintFlags & PaintValueFlags.DrawSelected) != PaintValueFlags.None) @@ -2540,11 +2540,11 @@ public virtual void PaintValue(object val, System.Drawing.Graphics g, Rectangle if (doToolTip) { - this.ValueToolTipLocation = new Point(rect.X + 2, rect.Y - 1); + ValueToolTipLocation = new Point(rect.X + 2, rect.Y - 1); } else { - this.ValueToolTipLocation = InvalidPoint; + ValueToolTipLocation = InvalidPoint; } } @@ -2605,7 +2605,7 @@ protected virtual void OnLabelDoubleClick(EventArgs e) public virtual bool OnMouseClick(int x, int y, int count, MouseButtons button) { // where are we at? - PropertyGridView gridHost = this.GridEntryHost; + PropertyGridView gridHost = GridEntryHost; Debug.Assert(gridHost != null, "No prop entry host!"); // make sure it's the left button @@ -2871,11 +2871,11 @@ internal void RecreateChildren(int oldCount) { // cause the flags to be rebuilt as well... - bool wasExpanded = this.InternalExpanded || oldCount > 0; + bool wasExpanded = InternalExpanded || oldCount > 0; if (oldCount == -1) { - oldCount = this.VisibleChildCount; + oldCount = VisibleChildCount; } ResetState(); @@ -2890,7 +2890,7 @@ internal void RecreateChildren(int oldCount) } DisposeChildren(); - this.InternalExpanded = wasExpanded; + InternalExpanded = wasExpanded; OnRecreateChildren(new GridEntryRecreateChildrenEventArgs(oldCount, VisibleChildCount)); } @@ -2900,24 +2900,24 @@ internal void RecreateChildren(int oldCount) public virtual void Refresh() { - Type type = this.PropertyType; + Type type = PropertyType; if (type != null && type.IsArray) { CreateChildren(true); } - if (this.childCollection != null) + if (childCollection != null) { // check to see if the value has changed. // - if (this.InternalExpanded && cacheItems != null && cacheItems.lastValue != null && cacheItems.lastValue != this.PropertyValue) + if (InternalExpanded && cacheItems != null && cacheItems.lastValue != null && cacheItems.lastValue != PropertyValue) { ClearCachedValues(); RecreateChildren(); return; } - else if (this.InternalExpanded) + else if (InternalExpanded) { // otherwise just do a refresh. IEnumerator childEnum = childCollection.GetEnumerator(); @@ -2982,7 +2982,7 @@ private string ReplaceCRLF(string str) { protected void ResetState() { - this.Flags = 0; + Flags = 0; ClearCachedValues(); } @@ -2992,7 +2992,7 @@ protected void ResetState() public virtual bool SetPropertyTextValue(string str) { bool fChildrenPrior = (childCollection != null && childCollection.Count > 0); - this.PropertyValue = ConvertTextToValue(str); + PropertyValue = ConvertTextToValue(str); CreateChildren(); bool fChildrenAfter = (childCollection != null && childCollection.Count > 0); return (fChildrenPrior != fChildrenAfter); @@ -3000,7 +3000,7 @@ public virtual bool SetPropertyTextValue(string str) public override string ToString() { - return GetType().FullName + " " + this.PropertyLabel; + return GetType().FullName + " " + PropertyLabel; } @@ -3230,7 +3230,7 @@ internal override int[] RuntimeId runtimeId = new int[3]; runtimeId[0] = 0x2a; runtimeId[1] = (int)(long)owner.GridEntryHost.Handle; - runtimeId[2] = this.GetHashCode(); + runtimeId[2] = GetHashCode(); } return runtimeId; @@ -3260,7 +3260,7 @@ internal override object GetPropertyValue(int propertyID) case NativeMethods.UIA_HasKeyboardFocusPropertyId: return owner.hasFocus; case NativeMethods.UIA_IsKeyboardFocusablePropertyId: - return (this.State & AccessibleStates.Focusable) == AccessibleStates.Focusable; + return (State & AccessibleStates.Focusable) == AccessibleStates.Focusable; case NativeMethods.UIA_IsEnabledPropertyId: return true; case NativeMethods.UIA_AutomationIdPropertyId: @@ -3270,7 +3270,7 @@ internal override object GetPropertyValue(int propertyID) case NativeMethods.UIA_IsPasswordPropertyId: return false; case NativeMethods.UIA_IsOffscreenPropertyId: - return (this.State & AccessibleStates.Offscreen) == AccessibleStates.Offscreen; + return (State & AccessibleStates.Offscreen) == AccessibleStates.Offscreen; case NativeMethods.UIA_LegacyIAccessibleRolePropertyId: return Role; case NativeMethods.UIA_LegacyIAccessibleDefaultActionPropertyId: @@ -3347,7 +3347,7 @@ public override AccessibleObject Parent { get { - return ((Control)this.owner.GridEntryHost).AccessibilityObject; + return ((Control)owner.GridEntryHost).AccessibilityObject; } } @@ -3466,12 +3466,12 @@ public override AccessibleObject Navigate(AccessibleNavigation navdir) case AccessibleNavigation.Down: case AccessibleNavigation.Right: case AccessibleNavigation.Next: - return parent.Next(this.owner); + return parent.Next(owner); case AccessibleNavigation.Up: case AccessibleNavigation.Left: case AccessibleNavigation.Previous: - return parent.Previous(this.owner); + return parent.Previous(owner); case AccessibleNavigation.FirstChild: case AccessibleNavigation.LastChild: @@ -3491,7 +3491,7 @@ public override void Select(AccessibleSelection flags) // if (PropertyGridView.InvokeRequired) { - PropertyGridView.Invoke(new SelectDelegate(this.Select), new object[] { flags }); + PropertyGridView.Invoke(new SelectDelegate(Select), new object[] { flags }); return; } @@ -3506,7 +3506,7 @@ public override void Select(AccessibleSelection flags) // if ((flags & AccessibleSelection.TakeSelection) == AccessibleSelection.TakeSelection) { - PropertyGridView.AccessibilitySelect(this.owner); + PropertyGridView.AccessibilitySelect(owner); } } @@ -3594,8 +3594,8 @@ internal class GridEntryRecreateChildrenEventArgs : EventArgs public GridEntryRecreateChildrenEventArgs(int oldCount, int newCount) { - this.OldChildCount = oldCount; - this.NewChildCount = newCount; + OldChildCount = oldCount; + NewChildCount = newCount; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridErrorDlg.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridErrorDlg.cs index 21717cc3b33..42f74714aaa 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridErrorDlg.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridErrorDlg.cs @@ -60,7 +60,7 @@ public string Details { set { - this.details.Text = value; + details.Text = value; } } @@ -69,7 +69,7 @@ public string Message { set { - this.lblMessage.Text = value; + lblMessage.Text = value; } } @@ -93,7 +93,7 @@ public GridErrorDlg(PropertyGrid owner) InitializeComponent(); - foreach (Control c in this.Controls) + foreach (Control c in Controls) { if (c.SupportsUseCompatibleTextRendering) { @@ -160,165 +160,165 @@ private void InitializeComponent() { if (IsRTLResources) { - this.RightToLeft = RightToLeft.Yes; + RightToLeft = RightToLeft.Yes; } - this.detailsBtn = new DetailsButton(this); - this.overarchingTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); - this.buttonTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); - this.okBtn = new System.Windows.Forms.Button(); - this.cancelBtn = new System.Windows.Forms.Button(); - this.pictureLabelTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); - this.lblMessage = new System.Windows.Forms.Label(); - this.pictureBox = new System.Windows.Forms.PictureBox(); - this.details = new System.Windows.Forms.TextBox(); - this.overarchingTableLayoutPanel.SuspendLayout(); - this.buttonTableLayoutPanel.SuspendLayout(); - this.pictureLabelTableLayoutPanel.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit(); - this.SuspendLayout(); + detailsBtn = new DetailsButton(this); + overarchingTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); + buttonTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); + okBtn = new System.Windows.Forms.Button(); + cancelBtn = new System.Windows.Forms.Button(); + pictureLabelTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); + lblMessage = new System.Windows.Forms.Label(); + pictureBox = new System.Windows.Forms.PictureBox(); + details = new System.Windows.Forms.TextBox(); + overarchingTableLayoutPanel.SuspendLayout(); + buttonTableLayoutPanel.SuspendLayout(); + pictureLabelTableLayoutPanel.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(pictureBox)).BeginInit(); + SuspendLayout(); // // lblMessage // - this.lblMessage.AutoSize = true; - this.lblMessage.Location = new System.Drawing.Point(73, 30); - this.lblMessage.Margin = new System.Windows.Forms.Padding(3, 30, 3, 0); - this.lblMessage.Name = "lblMessage"; - this.lblMessage.Size = new System.Drawing.Size(208, 43); - this.lblMessage.TabIndex = 0; + lblMessage.AutoSize = true; + lblMessage.Location = new System.Drawing.Point(73, 30); + lblMessage.Margin = new System.Windows.Forms.Padding(3, 30, 3, 0); + lblMessage.Name = "lblMessage"; + lblMessage.Size = new System.Drawing.Size(208, 43); + lblMessage.TabIndex = 0; // // pictureBox // - this.pictureBox.Location = new System.Drawing.Point(3, 3); - this.pictureBox.Name = "pictureBox"; - this.pictureBox.Size = new System.Drawing.Size(64, 64); - this.pictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; - this.pictureBox.TabIndex = 5; - this.pictureBox.TabStop = false; - this.pictureBox.AutoSize = true; + pictureBox.Location = new System.Drawing.Point(3, 3); + pictureBox.Name = "pictureBox"; + pictureBox.Size = new System.Drawing.Size(64, 64); + pictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; + pictureBox.TabIndex = 5; + pictureBox.TabStop = false; + pictureBox.AutoSize = true; // // detailsBtn // - this.detailsBtn.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; - this.detailsBtn.Location = new System.Drawing.Point(3, 3); - this.detailsBtn.Margin = new System.Windows.Forms.Padding(12, 3, 29, 3); - this.detailsBtn.Name = "detailsBtn"; - this.detailsBtn.Size = new System.Drawing.Size(100, 23); - this.detailsBtn.TabIndex = 4; - this.detailsBtn.Click += new System.EventHandler(this.DetailsClick); + detailsBtn.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; + detailsBtn.Location = new System.Drawing.Point(3, 3); + detailsBtn.Margin = new System.Windows.Forms.Padding(12, 3, 29, 3); + detailsBtn.Name = "detailsBtn"; + detailsBtn.Size = new System.Drawing.Size(100, 23); + detailsBtn.TabIndex = 4; + detailsBtn.Click += new System.EventHandler(DetailsClick); // // overarchingTableLayoutPanel // - this.overarchingTableLayoutPanel.AutoSize = true; - this.overarchingTableLayoutPanel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; - this.overarchingTableLayoutPanel.ColumnCount = 1; - this.overarchingTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); - this.overarchingTableLayoutPanel.Controls.Add(this.buttonTableLayoutPanel, 0, 1); - this.overarchingTableLayoutPanel.Controls.Add(this.pictureLabelTableLayoutPanel, 0, 0); - this.overarchingTableLayoutPanel.Location = new System.Drawing.Point(1, 0); - this.overarchingTableLayoutPanel.MinimumSize = new System.Drawing.Size(279, 50); - this.overarchingTableLayoutPanel.Name = "overarchingTableLayoutPanel"; - this.overarchingTableLayoutPanel.RowCount = 2; - this.overarchingTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.overarchingTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.overarchingTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); - this.overarchingTableLayoutPanel.Size = new System.Drawing.Size(290, 108); - this.overarchingTableLayoutPanel.TabIndex = 6; + overarchingTableLayoutPanel.AutoSize = true; + overarchingTableLayoutPanel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; + overarchingTableLayoutPanel.ColumnCount = 1; + overarchingTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + overarchingTableLayoutPanel.Controls.Add(buttonTableLayoutPanel, 0, 1); + overarchingTableLayoutPanel.Controls.Add(pictureLabelTableLayoutPanel, 0, 0); + overarchingTableLayoutPanel.Location = new System.Drawing.Point(1, 0); + overarchingTableLayoutPanel.MinimumSize = new System.Drawing.Size(279, 50); + overarchingTableLayoutPanel.Name = "overarchingTableLayoutPanel"; + overarchingTableLayoutPanel.RowCount = 2; + overarchingTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle()); + overarchingTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle()); + overarchingTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); + overarchingTableLayoutPanel.Size = new System.Drawing.Size(290, 108); + overarchingTableLayoutPanel.TabIndex = 6; // // buttonTableLayoutPanel // - this.buttonTableLayoutPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + buttonTableLayoutPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); - this.buttonTableLayoutPanel.AutoSize = true; - this.buttonTableLayoutPanel.ColumnCount = 3; - this.overarchingTableLayoutPanel.SetColumnSpan(this.buttonTableLayoutPanel, 2); - this.buttonTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); - this.buttonTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); - this.buttonTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); - this.buttonTableLayoutPanel.Controls.Add(this.cancelBtn, 2, 0); - this.buttonTableLayoutPanel.Controls.Add(this.okBtn, 1, 0); - this.buttonTableLayoutPanel.Controls.Add(this.detailsBtn, 0, 0); - this.buttonTableLayoutPanel.Location = new System.Drawing.Point(0, 79); - this.buttonTableLayoutPanel.Name = "buttonTableLayoutPanel"; - this.buttonTableLayoutPanel.RowCount = 1; - this.buttonTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.buttonTableLayoutPanel.Size = new System.Drawing.Size(290, 29); - this.buttonTableLayoutPanel.TabIndex = 8; + buttonTableLayoutPanel.AutoSize = true; + buttonTableLayoutPanel.ColumnCount = 3; + overarchingTableLayoutPanel.SetColumnSpan(buttonTableLayoutPanel, 2); + buttonTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); + buttonTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + buttonTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + buttonTableLayoutPanel.Controls.Add(cancelBtn, 2, 0); + buttonTableLayoutPanel.Controls.Add(okBtn, 1, 0); + buttonTableLayoutPanel.Controls.Add(detailsBtn, 0, 0); + buttonTableLayoutPanel.Location = new System.Drawing.Point(0, 79); + buttonTableLayoutPanel.Name = "buttonTableLayoutPanel"; + buttonTableLayoutPanel.RowCount = 1; + buttonTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle()); + buttonTableLayoutPanel.Size = new System.Drawing.Size(290, 29); + buttonTableLayoutPanel.TabIndex = 8; // // okBtn // - this.okBtn.AutoSize = true; - this.okBtn.DialogResult = System.Windows.Forms.DialogResult.OK; - this.okBtn.Location = new System.Drawing.Point(131, 3); - this.okBtn.Name = "okBtn"; - this.okBtn.Size = new System.Drawing.Size(75, 23); - this.okBtn.TabIndex = 1; - this.okBtn.Click += new System.EventHandler(this.OnButtonClick); + okBtn.AutoSize = true; + okBtn.DialogResult = System.Windows.Forms.DialogResult.OK; + okBtn.Location = new System.Drawing.Point(131, 3); + okBtn.Name = "okBtn"; + okBtn.Size = new System.Drawing.Size(75, 23); + okBtn.TabIndex = 1; + okBtn.Click += new System.EventHandler(OnButtonClick); // // cancelBtn // - this.cancelBtn.AutoSize = true; - this.cancelBtn.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.cancelBtn.Location = new System.Drawing.Point(212, 3); - this.cancelBtn.Margin = new System.Windows.Forms.Padding(0, 3, 3, 3); - this.cancelBtn.Name = "cancelBtn"; - this.cancelBtn.Size = new System.Drawing.Size(75, 23); - this.cancelBtn.TabIndex = 2; - this.cancelBtn.Click += new System.EventHandler(this.OnButtonClick); + cancelBtn.AutoSize = true; + cancelBtn.DialogResult = System.Windows.Forms.DialogResult.Cancel; + cancelBtn.Location = new System.Drawing.Point(212, 3); + cancelBtn.Margin = new System.Windows.Forms.Padding(0, 3, 3, 3); + cancelBtn.Name = "cancelBtn"; + cancelBtn.Size = new System.Drawing.Size(75, 23); + cancelBtn.TabIndex = 2; + cancelBtn.Click += new System.EventHandler(OnButtonClick); // // pictureLabelTableLayoutPanel // - this.pictureLabelTableLayoutPanel.AutoSize = true; - this.pictureLabelTableLayoutPanel.AutoSizeMode = Forms.AutoSizeMode.GrowOnly; - this.pictureLabelTableLayoutPanel.ColumnCount = 2; - this.pictureLabelTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); - this.pictureLabelTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); - this.pictureLabelTableLayoutPanel.Controls.Add(this.lblMessage, 1, 0); - this.pictureLabelTableLayoutPanel.Controls.Add(this.pictureBox, 0, 0); - this.pictureLabelTableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill; - this.pictureLabelTableLayoutPanel.Location = new System.Drawing.Point(3, 3); - this.pictureLabelTableLayoutPanel.Name = "pictureLabelTableLayoutPanel"; - this.pictureLabelTableLayoutPanel.RowCount = 1; - this.pictureLabelTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.AutoSize)); - this.pictureLabelTableLayoutPanel.Size = new System.Drawing.Size(284, 73); - this.pictureLabelTableLayoutPanel.TabIndex = 4; + pictureLabelTableLayoutPanel.AutoSize = true; + pictureLabelTableLayoutPanel.AutoSizeMode = Forms.AutoSizeMode.GrowOnly; + pictureLabelTableLayoutPanel.ColumnCount = 2; + pictureLabelTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + pictureLabelTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); + pictureLabelTableLayoutPanel.Controls.Add(lblMessage, 1, 0); + pictureLabelTableLayoutPanel.Controls.Add(pictureBox, 0, 0); + pictureLabelTableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill; + pictureLabelTableLayoutPanel.Location = new System.Drawing.Point(3, 3); + pictureLabelTableLayoutPanel.Name = "pictureLabelTableLayoutPanel"; + pictureLabelTableLayoutPanel.RowCount = 1; + pictureLabelTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.AutoSize)); + pictureLabelTableLayoutPanel.Size = new System.Drawing.Size(284, 73); + pictureLabelTableLayoutPanel.TabIndex = 4; // // details // - this.details.Location = new System.Drawing.Point(4, 114); - this.details.Multiline = true; - this.details.Name = "details"; - this.details.ReadOnly = true; - this.details.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; - this.details.Size = new System.Drawing.Size(273, 100); - this.details.TabIndex = 3; - this.details.TabStop = false; - this.details.Visible = false; + details.Location = new System.Drawing.Point(4, 114); + details.Multiline = true; + details.Name = "details"; + details.ReadOnly = true; + details.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; + details.Size = new System.Drawing.Size(273, 100); + details.TabIndex = 3; + details.TabStop = false; + details.Visible = false; // // Form1 // - this.AcceptButton = this.okBtn; - this.AutoSize = true; - this.AutoScaleMode = Forms.AutoScaleMode.Font; - this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; - this.CancelButton = this.cancelBtn; - this.ClientSize = new System.Drawing.Size(299, 113); - this.Controls.Add(this.details); - this.Controls.Add(this.overarchingTableLayoutPanel); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "Form1"; - this.ShowInTaskbar = false; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; - this.overarchingTableLayoutPanel.ResumeLayout(false); - this.overarchingTableLayoutPanel.PerformLayout(); - this.buttonTableLayoutPanel.ResumeLayout(false); - this.buttonTableLayoutPanel.PerformLayout(); - this.pictureLabelTableLayoutPanel.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit(); - this.ResumeLayout(false); - this.PerformLayout(); + AcceptButton = okBtn; + AutoSize = true; + AutoScaleMode = Forms.AutoScaleMode.Font; + AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; + CancelButton = cancelBtn; + ClientSize = new System.Drawing.Size(299, 113); + Controls.Add(details); + Controls.Add(overarchingTableLayoutPanel); + FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + MaximizeBox = false; + MinimizeBox = false; + Name = "Form1"; + ShowInTaskbar = false; + StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + overarchingTableLayoutPanel.ResumeLayout(false); + overarchingTableLayoutPanel.PerformLayout(); + buttonTableLayoutPanel.ResumeLayout(false); + buttonTableLayoutPanel.PerformLayout(); + pictureLabelTableLayoutPanel.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)(pictureBox)).EndInit(); + ResumeLayout(false); + PerformLayout(); } private void OnButtonClick(object s, EventArgs e) @@ -329,13 +329,13 @@ private void OnButtonClick(object s, EventArgs e) protected override void OnVisibleChanged(EventArgs e) { - if (this.Visible) + if (Visible) { // make sure the details button is sized properly // using (Graphics g = CreateGraphics()) { - SizeF sizef = PropertyGrid.MeasureTextHelper.MeasureText(this.ownerGrid, g, detailsBtn.Text, detailsBtn.Font); + SizeF sizef = PropertyGrid.MeasureTextHelper.MeasureText(ownerGrid, g, detailsBtn.Text, detailsBtn.Font); int detailsWidth = (int)Math.Ceiling(sizef.Width); detailsWidth += detailsBtn.Image.Width; detailsBtn.Width = (int)Math.Ceiling(detailsWidth * (ownerGrid.UseCompatibleTextRendering ? 1.15f : 1.4f)); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridToolTip.cs index 3f6d72c5262..d838f7af1b6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridToolTip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridToolTip.cs @@ -26,13 +26,13 @@ internal GridToolTip(Control[] controls) { this.controls = controls; SetStyle(ControlStyles.UserPaint, false); - this.Font = controls[0].Font; - this.toolInfos = new NativeMethods.TOOLINFO_T[controls.Length]; + Font = controls[0].Font; + toolInfos = new NativeMethods.TOOLINFO_T[controls.Length]; for (int i = 0; i < controls.Length; i++) { - controls[i].HandleCreated += new EventHandler(this.OnControlCreateHandle); - controls[i].HandleDestroyed += new EventHandler(this.OnControlDestroyHandle); + controls[i].HandleCreated += new EventHandler(OnControlCreateHandle); + controls[i].HandleDestroyed += new EventHandler(OnControlDestroyHandle); if (controls[i].IsHandleCreated) { @@ -49,9 +49,9 @@ public string ToolTip } set { - if (this.IsHandleCreated || !string.IsNullOrEmpty(value)) + if (IsHandleCreated || !string.IsNullOrEmpty(value)) { - this.Reset(); + Reset(); } if (value != null && value.Length > maximumToolTipLength) @@ -59,16 +59,16 @@ public string ToolTip //Let the user know the text was truncated by throwing on an ellipsis value = value.Substring(0, maximumToolTipLength) + "..."; } - this.toolTipText = value; + toolTipText = value; - if (this.IsHandleCreated) + if (IsHandleCreated) { - bool visible = this.Visible; + bool visible = Visible; if (visible) { - this.Visible = false; + Visible = false; } // here's a workaround. if we give @@ -92,7 +92,7 @@ public string ToolTip if (visible && !dontShow) { - this.Visible = true; + Visible = true; } } @@ -115,7 +115,7 @@ protected override CreateParams CreateParams cp.ClassName = NativeMethods.TOOLTIPS_CLASS; cp.Style |= (NativeMethods.TTS_ALWAYSTIP | NativeMethods.TTS_NOPREFIX); cp.ExStyle = 0; - cp.Caption = this.ToolTip; + cp.Caption = ToolTip; return cp; } } @@ -133,7 +133,7 @@ private NativeMethods.TOOLINFO_T GetTOOLINFO(Control c) toolInfos[index].cbSize = Marshal.SizeOf(); toolInfos[index].uFlags |= NativeMethods.TTF_IDISHWND | NativeMethods.TTF_TRANSPARENT | NativeMethods.TTF_SUBCLASS; } - toolInfos[index].lpszText = this.toolTipText; + toolInfos[index].lpszText = toolTipText; toolInfos[index].hwnd = c.Handle; toolInfos[index].uId = c.Handle; return toolInfos[index]; @@ -182,7 +182,7 @@ protected override void OnHandleCreated(EventArgs e) private void SetupToolTip(Control c) { - if (this.IsHandleCreated) + if (IsHandleCreated) { SafeNativeMethods.SetWindowPos(new HandleRef(this, Handle), NativeMethods.HWND_TOPMOST, 0, 0, 0, 0, @@ -209,8 +209,8 @@ public void Reset() // update the text, then it back to what it was, so the tooltip // thinks it's back in the regular state again // - string oldText = this.ToolTip; - this.toolTipText = string.Empty; + string oldText = ToolTip; + toolTipText = string.Empty; for (int i = 0; i < controls.Length; i++) { if (0 == (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_UPDATETIPTEXT, 0, GetTOOLINFO(controls[i]))) @@ -218,8 +218,8 @@ public void Reset() //Debug.Fail("TTM_UPDATETIPTEXT failed for " + controls[i].GetType().Name); } } - this.toolTipText = oldText; - this.SendMessage(NativeMethods.TTM_UPDATE, 0, 0); + toolTipText = oldText; + SendMessage(NativeMethods.TTM_UPDATE, 0, 0); } protected override void WndProc(ref Message msg) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs index 06df7c77196..81bbc2de0f3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs @@ -32,7 +32,7 @@ internal class HotCommands : PropertyGrid.SnappableControl ] internal HotCommands(PropertyGrid owner) : base(owner) { - this.Text = "Command Pane"; + Text = "Command Pane"; } public virtual bool AllowVisible @@ -43,13 +43,13 @@ public virtual bool AllowVisible } set { - if (this.allowVisible != value) + if (allowVisible != value) { - this.allowVisible = value; + allowVisible = value; if (value && WouldBeVisible) - this.Visible = true; + Visible = true; else - this.Visible = false; + Visible = false; } } } @@ -84,8 +84,8 @@ public LinkLabel Label // use default LinkLabel colors for regular, active, and visited label.DisabledLinkColor = SystemColors.ControlDark; - label.LinkClicked += new LinkLabelLinkClickedEventHandler(this.LinkClicked); - this.Controls.Add(label); + label.LinkClicked += new LinkLabelLinkClickedEventHandler(LinkClicked); + Controls.Add(label); } return label; } @@ -181,7 +181,7 @@ public virtual void SetVerbs(object component, DesignerVerb[] verbs) { for (int i = 0; i < this.verbs.Length; i++) { - this.verbs[i].CommandChanged -= new EventHandler(this.OnCommandChanged); + this.verbs[i].CommandChanged -= new EventHandler(OnCommandChanged); } this.component = null; this.verbs = null; @@ -200,7 +200,7 @@ public virtual void SetVerbs(object component, DesignerVerb[] verbs) for (int i = 0; i < verbs.Length; i++) { - verbs[i].CommandChanged += new EventHandler(this.OnCommandChanged); + verbs[i].CommandChanged += new EventHandler(OnCommandChanged); } if (allowVisible) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/ImmutablePropertyDescriptorGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/ImmutablePropertyDescriptorGridEntry.cs index 923e5008343..87bde55c4d7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/ImmutablePropertyDescriptorGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/ImmutablePropertyDescriptorGridEntry.cs @@ -113,7 +113,7 @@ private GridEntry InstanceParentGridEntry { get { - GridEntry parent = this.ParentGridEntry; + GridEntry parent = ParentGridEntry; if (parent is CategoryGridEntry) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs index a584770e702..cbff0fa3f0b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs @@ -520,7 +520,7 @@ public bool Locked } set { - this.locked = value; + locked = value; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiPropertyDescriptorGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiPropertyDescriptorGridEntry.cs index 084804143cc..1f2f7fb2e59 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiPropertyDescriptorGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiPropertyDescriptorGridEntry.cs @@ -32,7 +32,7 @@ public MultiPropertyDescriptorGridEntry(PropertyGrid ownerGrid, GridEntry pePare : base(ownerGrid, peParent, hide) { mergedPd = new MergePropertyDescriptor(propInfo); - this.objs = objectArray; + objs = objectArray; base.Initialize(mergedPd); } @@ -136,7 +136,7 @@ protected override bool CreateChildren(bool diffOldChildren) ChildCollection.Clear(); - MultiPropertyDescriptorGridEntry[] mergedProps = MultiSelectRootGridEntry.PropertyMerger.GetMergedProperties(mergedPd.GetValues(objs), this, this.PropertySort, this.CurrentTab); + MultiPropertyDescriptorGridEntry[] mergedProps = MultiSelectRootGridEntry.PropertyMerger.GetMergedProperties(mergedPd.GetValues(objs), this, PropertySort, CurrentTab); Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose && mergedProps == null, "PropertyGridView: MergedProps returned null!"); @@ -144,7 +144,7 @@ protected override bool CreateChildren(bool diffOldChildren) { ChildCollection.AddRange(mergedProps); } - bool fExpandable = this.Children.Count > 0; + bool fExpandable = Children.Count > 0; if (!fExpandable) { SetFlag(GridEntry.FL_EXPANDABLE_FAILED, true); @@ -303,7 +303,7 @@ internal override bool NotifyValueGivenParent(object obj, int type) if (host != null) { - trans = host.CreateTransaction(string.Format(SR.PropertyGridResetValue, this.PropertyName)); + trans = host.CreateTransaction(string.Format(SR.PropertyGridResetValue, PropertyName)); } try { @@ -322,7 +322,7 @@ internal override bool NotifyValueGivenParent(object obj, int type) } } - this.mergedPd.ResetValue(obj); + mergedPd.ResetValue(obj); if (needChangeNotify) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiSelectRootGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiSelectRootGridEntry.cs index b302637c61b..78c1fc25454 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiSelectRootGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiSelectRootGridEntry.cs @@ -71,7 +71,7 @@ protected override bool CreateChildren(bool diffOldChildren) ChildCollection.Clear(); - MultiPropertyDescriptorGridEntry[] mergedProps = PropertyMerger.GetMergedProperties(rgobjs, this, this.PropertySort, CurrentTab); + MultiPropertyDescriptorGridEntry[] mergedProps = PropertyMerger.GetMergedProperties(rgobjs, this, PropertySort, CurrentTab); Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose && mergedProps == null, "PropertyGridView: MergedProps returned null!"); @@ -79,7 +79,7 @@ protected override bool CreateChildren(bool diffOldChildren) { ChildCollection.AddRange(mergedProps); } - bool fExpandable = this.Children.Count > 0; + bool fExpandable = Children.Count > 0; if (!fExpandable) { //Debug.WriteLine("Object " + rgobjs[0].GetType().FullName + " is not expandable because it has no children"); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs index 92812247aa6..e4b3aae7817 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs @@ -61,7 +61,7 @@ internal class PropertyDescriptorGridEntry : GridEntry internal PropertyDescriptorGridEntry(PropertyGrid ownerGrid, GridEntry peParent, bool hide) : base(ownerGrid, peParent) { - this.activeXHide = hide; + activeXHide = hide; } [ @@ -72,7 +72,7 @@ internal PropertyDescriptorGridEntry(PropertyGrid ownerGrid, GridEntry peParent, : base(ownerGrid, peParent) { - this.activeXHide = hide; + activeXHide = hide; Initialize(propInfo); } @@ -106,7 +106,7 @@ public override string HelpKeyword { get { - if (this.helpKeyword == null) + if (helpKeyword == null) { object owner = GetValueOwner(); @@ -121,7 +121,7 @@ public override string HelpKeyword } else if (this is ImmutablePropertyDescriptorGridEntry) { - helpKeyword = this.PropertyName; + helpKeyword = PropertyName; GridEntry ge = this; @@ -161,7 +161,7 @@ public override string HelpKeyword Type ownerType = owner.GetType(); if (!componentType.IsPublic || !componentType.IsAssignableFrom(ownerType)) { - PropertyDescriptor componentProperty = TypeDescriptor.GetProperties(ownerType)[this.PropertyName]; + PropertyDescriptor componentProperty = TypeDescriptor.GetProperties(ownerType)[PropertyName]; if (componentProperty != null) { componentType = componentProperty.ComponentType; @@ -196,7 +196,7 @@ public override string HelpKeyword helpKeyword = typeName + "." + propertyInfo.Name; } } - return this.helpKeyword; + return helpKeyword; } } @@ -212,7 +212,7 @@ internal override string HelpKeywordInternal { get { - return this.PropertyLabel; + return PropertyLabel; } } @@ -237,7 +237,7 @@ public override bool IsValueEditable { get { - return this.exceptionConverter == null && !IsPropertyReadOnly && base.IsValueEditable; + return exceptionConverter == null && !IsPropertyReadOnly && base.IsValueEditable; } } @@ -253,18 +253,18 @@ internal bool ParensAroundName { get { - if (ParensAroundNameUnknown == this.parensAroundName) + if (ParensAroundNameUnknown == parensAroundName) { if (((ParenthesizePropertyNameAttribute)propertyInfo.Attributes[typeof(ParenthesizePropertyNameAttribute)]).NeedParenthesis) { - this.parensAroundName = ParensAroundNameYes; + parensAroundName = ParensAroundNameYes; } else { - this.parensAroundName = ParensAroundNameNo; + parensAroundName = ParensAroundNameNo; } } - return (this.parensAroundName == ParensAroundNameYes); + return (parensAroundName == ParensAroundNameYes); } } @@ -353,7 +353,7 @@ public override object PropertyValue { object objRet = GetPropertyValueCore(GetValueOwner()); - if (this.exceptionConverter != null) + if (exceptionConverter != null) { // undo the exception converter SetFlagsAndExceptionInfo(0, null, null); @@ -363,7 +363,7 @@ public override object PropertyValue } catch (Exception e) { - if (this.exceptionConverter == null) + if (exceptionConverter == null) { // clear the flags SetFlagsAndExceptionInfo(0, new ExceptionConverter(), new ExceptionEditor()); @@ -381,20 +381,20 @@ private IPropertyValueUIService PropertyValueUIService { get { - if (!pvSvcChecked && this.pvSvc == null) + if (!pvSvcChecked && pvSvc == null) { - this.pvSvc = (IPropertyValueUIService)GetService(typeof(IPropertyValueUIService)); + pvSvc = (IPropertyValueUIService)GetService(typeof(IPropertyValueUIService)); pvSvcChecked = true; } - return this.pvSvc; + return pvSvc; } } private void SetFlagsAndExceptionInfo(int flags, ExceptionConverter converter, ExceptionEditor editor) { - this.Flags = flags; - this.exceptionConverter = converter; - this.exceptionEditor = editor; + Flags = flags; + exceptionConverter = converter; + exceptionEditor = editor; } public override bool ShouldRenderReadOnly @@ -410,7 +410,7 @@ public override bool ShouldRenderReadOnly // if (propertyInfo.IsReadOnly && !readOnlyVerified && GetFlagSet(GridEntry.FLAG_READONLY_EDITABLE)) { - Type propType = this.PropertyType; + Type propType = PropertyType; if (propType != null && (propType.IsArray || propType.IsValueType || propType.IsPrimitive)) { @@ -423,7 +423,7 @@ public override bool ShouldRenderReadOnly if (base.ShouldRenderReadOnly) { - if (!this.isSerializeContentsProp && !base.NeedsCustomEditorButton) + if (!isSerializeContentsProp && !base.NeedsCustomEditorButton) { return true; } @@ -484,7 +484,7 @@ internal override void EditPropertyValue(PropertyGridView iva) RefreshPropertiesAttribute refreshAttr = (RefreshPropertiesAttribute)propertyInfo.Attributes[typeof(RefreshPropertiesAttribute)]; if ((refreshAttr != null && !refreshAttr.RefreshProperties.Equals(RefreshProperties.None))) { - this.GridEntryHost.Refresh(refreshAttr != null && refreshAttr.Equals(RefreshPropertiesAttribute.All)); + GridEntryHost.Refresh(refreshAttr != null && refreshAttr.Equals(RefreshPropertiesAttribute.All)); } } } @@ -498,12 +498,12 @@ internal override Point GetLabelToolTipLocation(int mouseX, int mouseY) { if (uiItemRects[i].Contains(mouseX, GridEntryHost.GetGridEntryHeight() / 2)) { - this.toolTipText = pvUIItems[i].ToolTip; + toolTipText = pvUIItems[i].ToolTip; return new Point(mouseX, mouseY); } } } - this.toolTipText = null; + toolTipText = null; return base.GetLabelToolTipLocation(mouseX, mouseY); } @@ -532,12 +532,12 @@ protected void Initialize(PropertyDescriptor propInfo) { propertyInfo = propInfo; - this.isSerializeContentsProp = (propertyInfo.SerializationVisibility == DesignerSerializationVisibility.Content); + isSerializeContentsProp = (propertyInfo.SerializationVisibility == DesignerSerializationVisibility.Content); Debug.Assert(propInfo != null, "Can't create propEntry because of null prop info"); - if (!this.activeXHide && IsPropertyReadOnly) + if (!activeXHide && IsPropertyReadOnly) { SetFlag(FLAG_TEXT_EDITABLE, false); } @@ -588,7 +588,7 @@ ge is PropertyDescriptorGridEntry && } ge.ClearCachedValues(false); //clear the value so it paints correctly next time. - PropertyGridView gv = this.GridEntryHost; + PropertyGridView gv = GridEntryHost; if (gv != null) { gv.InvalidateGridEntryValue(ge); @@ -608,7 +608,7 @@ internal override bool NotifyValueGivenParent(object obj, int type) { case NOTIFY_RESET: - SetPropertyValue(obj, null, true, string.Format(SR.PropertyGridResetValue, this.PropertyName)); + SetPropertyValue(obj, null, true, string.Format(SR.PropertyGridResetValue, PropertyName)); if (pvUIItems != null) { for (int i = 0; i < pvUIItems.Length; i++) @@ -626,12 +626,12 @@ internal override bool NotifyValueGivenParent(object obj, int type) catch { - if (this.exceptionConverter == null) + if (exceptionConverter == null) { // clear the flags - this.Flags = 0; - this.exceptionConverter = new ExceptionConverter(); - this.exceptionEditor = new ExceptionEditor(); + Flags = 0; + exceptionConverter = new ExceptionConverter(); + exceptionEditor = new ExceptionEditor(); } return false; } @@ -643,12 +643,12 @@ internal override bool NotifyValueGivenParent(object obj, int type) catch { - if (this.exceptionConverter == null) + if (exceptionConverter == null) { // clear the flags - this.Flags = 0; - this.exceptionConverter = new ExceptionConverter(); - this.exceptionEditor = new ExceptionEditor(); + Flags = 0; + exceptionConverter = new ExceptionConverter(); + exceptionEditor = new ExceptionEditor(); } return false; } @@ -701,7 +701,7 @@ public override void PaintLabel(System.Drawing.Graphics g, Rectangle rect, Recta { base.PaintLabel(g, rect, clipRect, selected, paintFullLabel); - IPropertyValueUIService propValSvc = this.PropertyValueUIService; + IPropertyValueUIService propValSvc = PropertyValueUIService; if (propValSvc == null) { @@ -790,11 +790,11 @@ private object SetPropertyValue(object obj, object objVal, bool reset, string un } - bool wasExpanded = this.InternalExpanded; + bool wasExpanded = InternalExpanded; int childCount = -1; if (wasExpanded) { - childCount = this.ChildCount; + childCount = ChildCount; } RefreshPropertiesAttribute refreshAttr = (RefreshPropertiesAttribute)propertyInfo.Attributes[typeof(RefreshPropertiesAttribute)]; @@ -879,12 +879,12 @@ private object SetPropertyValue(object obj, object objVal, bool reset, string un // 1) if this property has the refreshpropertiesattribute, or // 2) it's got expanded sub properties // - if (needsRefresh && this.GridEntryHost != null) + if (needsRefresh && GridEntryHost != null) { RecreateChildren(childCount); if (setSuccessful) { - this.GridEntryHost.Refresh(refreshAttr != null && refreshAttr.Equals(RefreshPropertiesAttribute.All)); + GridEntryHost.Refresh(refreshAttr != null && refreshAttr.Equals(RefreshPropertiesAttribute.All)); } } } @@ -970,7 +970,7 @@ protected void SetPropertyValueCore(object obj, object value, bool doUndo) // if (treatAsValueType) { - GridEntry parent = this.ParentGridEntry; + GridEntry parent = ParentGridEntry; if (parent != null && parent.IsValueEditable) { parent.PropertyValue = obj; @@ -1046,7 +1046,7 @@ protected bool ViewEvent(object obj, string newHandler, EventDescriptor eventdes } } - IDesignerHost host = this.DesignerHost; + IDesignerHost host = DesignerHost; DesignerTransaction trans = null; try @@ -1061,7 +1061,7 @@ protected bool ViewEvent(object obj, string newHandler, EventDescriptor eventdes if (host != null) { string compName = component.Site != null ? component.Site.Name : component.GetType().Name; - trans = DesignerHost.CreateTransaction(string.Format(SR.WindowsFormsSetEvent, compName + "." + this.PropertyName)); + trans = DesignerHost.CreateTransaction(string.Format(SR.WindowsFormsSetEvent, compName + "." + PropertyName)); } if (eventBindings == null) @@ -1114,9 +1114,9 @@ protected bool ViewEvent(object obj, string newHandler, EventDescriptor eventdes trans = null; } - if (this.GridEntryHost != null && this.GridEntryHost is PropertyGridView) + if (GridEntryHost != null && GridEntryHost is PropertyGridView) { - PropertyGridView pgv = this.GridEntryHost as PropertyGridView; + PropertyGridView pgv = GridEntryHost as PropertyGridView; pgv.ShowInvalidMessage(newHandler, obj, ex); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs index c9d4ba13198..57b1ab73276 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs @@ -184,12 +184,12 @@ public PropertyGridView(IServiceProvider serviceProvider, PropertyGrid propertyG maxListBoxHeight = DpiHelper.LogicalToDeviceUnitsY(MAX_LISTBOX_HEIGHT); } - this.ehValueClick = new EventHandler(this.OnGridEntryValueClick); - this.ehLabelClick = new EventHandler(this.OnGridEntryLabelClick); - this.ehOutlineClick = new EventHandler(this.OnGridEntryOutlineClick); - this.ehValueDblClick = new EventHandler(this.OnGridEntryValueDoubleClick); - this.ehLabelDblClick = new EventHandler(this.OnGridEntryLabelDoubleClick); - this.ehRecreateChildren = new GridEntryRecreateChildrenEventHandler(this.OnRecreateChildren); + ehValueClick = new EventHandler(OnGridEntryValueClick); + ehLabelClick = new EventHandler(OnGridEntryLabelClick); + ehOutlineClick = new EventHandler(OnGridEntryOutlineClick); + ehValueDblClick = new EventHandler(OnGridEntryValueDoubleClick); + ehLabelDblClick = new EventHandler(OnGridEntryLabelDoubleClick); + ehRecreateChildren = new GridEntryRecreateChildrenEventHandler(OnRecreateChildren); ownerGrid = propertyGrid; this.serviceProvider = serviceProvider; @@ -206,7 +206,7 @@ public PropertyGridView(IServiceProvider serviceProvider, PropertyGrid propertyG backgroundBrush = SystemBrushes.Window; TabStop = true; - this.Text = "PropertyGridView"; + Text = "PropertyGridView"; CreateUI(); LayoutWindow(true); @@ -220,7 +220,7 @@ public override Color BackColor } set { - this.backgroundBrush = new SolidBrush(value); + backgroundBrush = new SolidBrush(value); base.BackColor = value; } } @@ -301,12 +301,12 @@ internal DropDownButton DropDownButton btnDropDown.Image = bitmap; btnDropDown.BackColor = SystemColors.Control; btnDropDown.ForeColor = SystemColors.ControlText; - btnDropDown.Click += new EventHandler(this.OnBtnClick); + btnDropDown.Click += new EventHandler(OnBtnClick); btnDropDown.GotFocus += new EventHandler(OnDropDownButtonGotFocus); - btnDropDown.LostFocus += new EventHandler(this.OnChildLostFocus); + btnDropDown.LostFocus += new EventHandler(OnChildLostFocus); btnDropDown.TabIndex = 2; CommonEditorSetup(btnDropDown); - btnDropDown.Size = DpiHelper.IsScalingRequirementMet ? new Size(SystemInformation.VerticalScrollBarArrowHeightForDpi(this.deviceDpi), RowHeight) : new Size(SystemInformation.VerticalScrollBarArrowHeight, RowHeight); + btnDropDown.Size = DpiHelper.IsScalingRequirementMet ? new Size(SystemInformation.VerticalScrollBarArrowHeightForDpi(deviceDpi), RowHeight) : new Size(SystemInformation.VerticalScrollBarArrowHeight, RowHeight); } return btnDropDown; } @@ -330,11 +330,11 @@ private Button DialogButton btnDialog.ForeColor = SystemColors.ControlText; btnDialog.TabIndex = 3; btnDialog.Image = CreateResizedBitmap("dotdotdot", DOTDOTDOT_ICONWIDTH, DOTDOTDOT_ICONHEIGHT); - btnDialog.Click += new EventHandler(this.OnBtnClick); - btnDialog.KeyDown += new KeyEventHandler(this.OnBtnKeyDown); + btnDialog.Click += new EventHandler(OnBtnClick); + btnDialog.KeyDown += new KeyEventHandler(OnBtnKeyDown); btnDialog.GotFocus += new EventHandler(OnDropDownButtonGotFocus); - btnDialog.LostFocus += new EventHandler(this.OnChildLostFocus); - btnDialog.Size = DpiHelper.IsScalingRequirementMet ? new Size(SystemInformation.VerticalScrollBarArrowHeightForDpi(this.deviceDpi), RowHeight) : new Size(SystemInformation.VerticalScrollBarArrowHeight, RowHeight); + btnDialog.LostFocus += new EventHandler(OnChildLostFocus); + btnDialog.Size = DpiHelper.IsScalingRequirementMet ? new Size(SystemInformation.VerticalScrollBarArrowHeightForDpi(deviceDpi), RowHeight) : new Size(SystemInformation.VerticalScrollBarArrowHeight, RowHeight); CommonEditorSetup(btnDialog); } return btnDialog; @@ -383,12 +383,12 @@ private GridViewEdit Edit edit.AcceptsReturn = true; edit.BackColor = BackColor; edit.ForeColor = ForeColor; - edit.KeyDown += new KeyEventHandler(this.OnEditKeyDown); - edit.KeyPress += new KeyPressEventHandler(this.OnEditKeyPress); - edit.GotFocus += new EventHandler(this.OnEditGotFocus); - edit.LostFocus += new EventHandler(this.OnEditLostFocus); - edit.MouseDown += new MouseEventHandler(this.OnEditMouseDown); - edit.TextChanged += new EventHandler(this.OnEditChange); + edit.KeyDown += new KeyEventHandler(OnEditKeyDown); + edit.KeyPress += new KeyPressEventHandler(OnEditKeyPress); + edit.GotFocus += new EventHandler(OnEditGotFocus); + edit.LostFocus += new EventHandler(OnEditLostFocus); + edit.MouseDown += new MouseEventHandler(OnEditMouseDown); + edit.TextChanged += new EventHandler(OnEditChange); //edit.ImeModeChanged += new EventHandler(this.OnEditImeModeChanged); edit.TabIndex = 1; CommonEditorSetup(edit); @@ -424,11 +424,11 @@ private GridViewListBox DropDownListBox listBox = new GridViewListBox(this); listBox.DrawMode = DrawMode.OwnerDrawFixed; //listBox.Click += new EventHandler(this.OnListClick); - listBox.MouseUp += new MouseEventHandler(this.OnListMouseUp); - listBox.DrawItem += new DrawItemEventHandler(this.OnListDrawItem); - listBox.SelectedIndexChanged += new EventHandler(this.OnListChange); - listBox.KeyDown += new KeyEventHandler(this.OnListKeyDown); - listBox.LostFocus += new EventHandler(this.OnChildLostFocus); + listBox.MouseUp += new MouseEventHandler(OnListMouseUp); + listBox.DrawItem += new DrawItemEventHandler(OnListDrawItem); + listBox.SelectedIndexChanged += new EventHandler(OnListChange); + listBox.KeyDown += new KeyEventHandler(OnListKeyDown); + listBox.LostFocus += new EventHandler(OnChildLostFocus); listBox.Visible = true; listBox.ItemHeight = RowHeight; } @@ -480,7 +480,7 @@ public bool FocusInside { get { - return (this.ContainsFocus || (dropDownHolder != null && dropDownHolder.ContainsFocus)); + return (ContainsFocus || (dropDownHolder != null && dropDownHolder.ContainsFocus)); } } @@ -494,14 +494,14 @@ internal Color GrayTextColor return grayTextColor; } - if (this.ForeColor.ToArgb() == SystemColors.WindowText.ToArgb()) + if (ForeColor.ToArgb() == SystemColors.WindowText.ToArgb()) { return SystemColors.GrayText; } // compute the new color by halving the value of the old one. // - int colorRGB = this.ForeColor.ToArgb(); + int colorRGB = ForeColor.ToArgb(); int alphaValue = (colorRGB >> 24) & 0xff; if (alphaValue != 0) @@ -531,9 +531,9 @@ private GridErrorDlg ErrorDialog { get { - if (this.errorDlg == null) + if (errorDlg == null) { - errorDlg = new GridErrorDlg(this.ownerGrid); + errorDlg = new GridErrorDlg(ownerGrid); } return errorDlg; } @@ -598,7 +598,7 @@ public PropertyGrid OwnerGrid { get { - return this.ownerGrid; + return ownerGrid; } } @@ -644,7 +644,7 @@ private ScrollBar ScrollBar } #endif scrollBar = new VScrollBar(); - scrollBar.Scroll += new ScrollEventHandler(this.OnScroll); + scrollBar.Scroll += new ScrollEventHandler(OnScroll); Controls.Add(scrollBar); } return scrollBar; @@ -784,7 +784,7 @@ public IServiceProvider ServiceProvider { if (value != serviceProvider) { - this.serviceProvider = value; + serviceProvider = value; topHelpService = null; @@ -850,7 +850,7 @@ private GridToolTip ToolTip #endif toolTip = new GridToolTip(new Control[] { this, Edit }); toolTip.ToolTip = string.Empty; - toolTip.Font = this.Font; + toolTip.Font = Font; } return toolTip; } @@ -1132,7 +1132,7 @@ private void CommonEditorHide(bool always) Edit.DontFocus = true; if (Edit.Focused && !gotfocus) { - gotfocus = this.Focus(); + gotfocus = Focus(); } Edit.Visible = false; @@ -1141,13 +1141,13 @@ private void CommonEditorHide(bool always) if (DialogButton.Focused && !gotfocus) { - gotfocus = this.Focus(); + gotfocus = Focus(); } DialogButton.Visible = false; if (DropDownButton.Focused && !gotfocus) { - gotfocus = this.Focus(); + gotfocus = Focus(); } DropDownButton.Visible = false; currentEditor = null; @@ -1176,7 +1176,7 @@ protected virtual void CommonEditorUse(Control ctl, Rectangle rectTarget) Rectangle rectCur = ctl.Bounds; // the client rect minus the border line - Rectangle clientRect = this.ClientRectangle; + Rectangle clientRect = ClientRectangle; clientRect.Inflate(-1, -1); @@ -1337,7 +1337,7 @@ protected override void Dispose(bool disposing) public void DoCopyCommand() { - if (this.CanCopy) + if (CanCopy) { if (Edit.Focused) { @@ -1352,7 +1352,7 @@ public void DoCopyCommand() public void DoCutCommand() { - if (this.CanCut) + if (CanCut) { DoCopyCommand(); if (Edit.Visible) @@ -1365,7 +1365,7 @@ public void DoCutCommand() public void DoPasteCommand() { - if (this.CanPaste && Edit.Visible) + if (CanPaste && Edit.Visible) { if (Edit.Focused) { @@ -1390,7 +1390,7 @@ public void DoPasteCommand() public void DoUndoCommand() { - if (this.CanUndo && Edit.Visible) + if (CanUndo && Edit.Visible) { Edit.SendMessage(Interop.WindowMessages.WM_UNDO, 0, 0); } @@ -1428,7 +1428,7 @@ private int GetIPELabelIndent(GridEntry gridEntry) private int GetIPELabelLength(System.Drawing.Graphics g, GridEntry gridEntry) { - SizeF sizeF = PropertyGrid.MeasureTextHelper.MeasureText(this.ownerGrid, g, gridEntry.PropertyLabel, Font); + SizeF sizeF = PropertyGrid.MeasureTextHelper.MeasureText(ownerGrid, g, gridEntry.PropertyLabel, Font); Size size = Size.Ceiling(sizeF); return ptOurLocation.X + GetIPELabelIndent(gridEntry) + size.Width; } @@ -1675,7 +1675,7 @@ public Font GetBoldFont() { if (fontBold == null) { - fontBold = new Font(this.Font, FontStyle.Bold); + fontBold = new Font(Font, FontStyle.Bold); } return fontBold; } @@ -1732,7 +1732,7 @@ internal IntPtr GetBoldHfont() private bool GetFlag(short flag) { - return (this.flags & flag) != 0; + return (flags & flag) != 0; } public virtual Color GetLineColor() @@ -1815,7 +1815,7 @@ internal int GetPropertyLocation(string propName, bool getXY, bool rowValue) { int row = GetRowFromGridEntry(allGridEntries.GetEntry(i)); - if (row < 0 || row >= this.visibleRows) + if (row < 0 || row >= visibleRows) { return -1; } @@ -1966,8 +1966,8 @@ public virtual void DropDownUpdate() public bool EnsurePendingChangesCommitted() { - this.CloseDropDown(); - return this.Commit(); + CloseDropDown(); + return Commit(); } private bool FilterEditWndProc(ref Message m) @@ -2127,7 +2127,7 @@ protected virtual Point FindPosition(int x, int y) { if (RowHeight == -1) return InvalidPosition; - Size size = this.GetOurSize(); + Size size = GetOurSize(); if (x < 0 || x > size.Width + ptOurLocation.X) return InvalidPosition; @@ -2143,7 +2143,7 @@ public virtual void Flush() Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView::Flush()"); if (Commit() && Edit.Focused) { - this.Focus(); + Focus(); } } @@ -2380,7 +2380,7 @@ private Size GetOurSize() public Rectangle GetRectangle(int row, int flRow) { Rectangle rect = new Rectangle(0, 0, 0, 0); - Size size = this.GetOurSize(); + Size size = GetOurSize(); rect.X = ptOurLocation.X; @@ -2471,7 +2471,7 @@ public virtual string GetTestingInfo(int entry) public Color GetTextColor() { - return this.ForeColor; + return ForeColor; } private void LayoutWindow(bool invalidate) @@ -2692,7 +2692,7 @@ private void OnBtnKeyDown(object sender, KeyEventArgs ke) private void OnChildLostFocus(object sender, EventArgs e) { Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnChildLostFocus"); - this.InvokeLostFocus(this, e); + InvokeLostFocus(this, e); } private void OnDropDownButtonGotFocus(object sender, EventArgs e) @@ -2752,12 +2752,12 @@ protected override void OnGotFocus(EventArgs e) protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); - SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(this.OnSysColorChange); + SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(OnSysColorChange); } protected override void OnHandleDestroyed(EventArgs e) { - SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(this.OnSysColorChange); + SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(OnSysColorChange); // We can leak this if we aren't disposed. // if (toolTip != null && !RecreatingHandle) @@ -2905,7 +2905,7 @@ protected override void OnLostFocus(EventArgs e) { base.OnLostFocus(e); } - if (this.FocusInside) + if (FocusInside) { base.OnLostFocus(e); return; @@ -2956,7 +2956,7 @@ private void OnEditGotFocus(object sender, EventArgs e) if (!Edit.Visible) { - this.Focus(); + Focus(); return; } @@ -2971,7 +2971,7 @@ private void OnEditGotFocus(object sender, EventArgs e) } break; default: - if (this.NeedsCommit) + if (NeedsCommit) { SetCommitError(ERROR_NONE, true); } @@ -3122,7 +3122,7 @@ private void OnEditLostFocus(object sender, EventArgs e) return; } - if (this.FocusInside) + if (FocusInside) { return; } @@ -3134,7 +3134,7 @@ private void OnEditLostFocus(object sender, EventArgs e) return; } // change our focus state. - this.InvokeLostFocus(this, EventArgs.Empty); + InvokeLostFocus(this, EventArgs.Empty); } private void OnEditMouseDown(object sender, MouseEventArgs me) @@ -3188,7 +3188,7 @@ private bool OnF4(Control sender) { return false; } - if (sender == this || sender == this.ownerGrid) + if (sender == this || sender == ownerGrid) F4Selection(true); else UnfocusSelection(); @@ -3216,7 +3216,7 @@ private bool OnEscape(Control sender) return true; } - if (this.NeedsCommit) + if (NeedsCommit) { bool success = false; Edit.Text = originalTextValue; @@ -3321,7 +3321,7 @@ private void OnKeyDown(object sender, KeyEventArgs ke) ToolTip.ToolTip = string.Empty; } - if (fBoth || sender == this || sender == this.ownerGrid) + if (fBoth || sender == this || sender == ownerGrid) { switch (keyCode) { @@ -3583,7 +3583,7 @@ protected override void OnMouseDown(MouseEventArgs me) if (me.Clicks == 2) { - MoveSplitterTo(this.Width / 2); + MoveSplitterTo(Width / 2); return; } @@ -3675,7 +3675,7 @@ protected override void OnMouseMove(MouseEventArgs me) MoveSplitterTo(me.X); } - if ((rowMoveCur != this.TipRow || pt.X != this.TipColumn) && !GetFlag(FlagIsSplitterMove)) + if ((rowMoveCur != TipRow || pt.X != TipColumn) && !GetFlag(FlagIsSplitterMove)) { GridEntry gridItem = GetGridEntryFromRow(rowMoveCur); string tip = string.Empty; @@ -3687,24 +3687,24 @@ protected override void OnMouseMove(MouseEventArgs me) if (onLabel && gridItem.GetLabelToolTipLocation(me.X - itemRect.X, me.Y - itemRect.Y) != InvalidPoint) { tip = gridItem.LabelToolTipText; - this.TipRow = rowMoveCur; - this.TipColumn = pt.X; + TipRow = rowMoveCur; + TipColumn = pt.X; } else if (!onLabel && gridItem.ValueToolTipLocation != InvalidPoint && !Edit.Focused) { - if (!this.NeedsCommit) + if (!NeedsCommit) { tip = gridItem.GetPropertyTextValue(); } - this.TipRow = rowMoveCur; - this.TipColumn = pt.X; + TipRow = rowMoveCur; + TipColumn = pt.X; } } // Ensure that tooltips don't display when host application is not foreground app. // Assume that we don't want to display the tooltips IntPtr foregroundWindow = UnsafeNativeMethods.GetForegroundWindow(); - if (UnsafeNativeMethods.IsChild(new HandleRef(null, foregroundWindow), new HandleRef(null, this.Handle))) + if (UnsafeNativeMethods.IsChild(new HandleRef(null, foregroundWindow), new HandleRef(null, Handle))) { // Don't show the tips if a dropdown is showing if ((dropDownHolder == null || dropDownHolder.Component == null) || rowMoveCur == selectedRow) @@ -3737,7 +3737,7 @@ protected override void OnMouseUp(MouseEventArgs me) protected override void OnMouseWheel(MouseEventArgs me) { - this.ownerGrid.OnGridViewMouseWheel(me); + ownerGrid.OnGridViewMouseWheel(me); HandledMouseEventArgs e = me as HandledMouseEventArgs; if (e != null) @@ -3760,8 +3760,8 @@ protected override void OnMouseWheel(MouseEventArgs me) return; // Do not scroll when the user system setting is 0 lines per notch } - Debug.Assert(this.cumulativeVerticalWheelDelta > -NativeMethods.WHEEL_DELTA, "cumulativeVerticalWheelDelta is too small"); - Debug.Assert(this.cumulativeVerticalWheelDelta < NativeMethods.WHEEL_DELTA, "cumulativeVerticalWheelDelta is too big"); + Debug.Assert(cumulativeVerticalWheelDelta > -NativeMethods.WHEEL_DELTA, "cumulativeVerticalWheelDelta is too small"); + Debug.Assert(cumulativeVerticalWheelDelta < NativeMethods.WHEEL_DELTA, "cumulativeVerticalWheelDelta is too big"); // Should this only work if the Edit has focus? anyway // we use the mouse wheel to change the values in the dropdown if it's @@ -3809,24 +3809,24 @@ protected override void OnMouseWheel(MouseEventArgs me) { int originalOffset = initialOffset; - int large = fullNotches * this.scrollBar.LargeChange; + int large = fullNotches * scrollBar.LargeChange; int newOffset = Math.Max(0, initialOffset - large); newOffset = Math.Min(newOffset, totalProps - visibleRows + 1); - initialOffset -= fullNotches * this.scrollBar.LargeChange; - if (Math.Abs(initialOffset - originalOffset) >= Math.Abs(fullNotches * this.scrollBar.LargeChange)) + initialOffset -= fullNotches * scrollBar.LargeChange; + if (Math.Abs(initialOffset - originalOffset) >= Math.Abs(fullNotches * scrollBar.LargeChange)) { - this.cumulativeVerticalWheelDelta -= fullNotches * NativeMethods.WHEEL_DELTA; + cumulativeVerticalWheelDelta -= fullNotches * NativeMethods.WHEEL_DELTA; } else { - this.cumulativeVerticalWheelDelta = 0; + cumulativeVerticalWheelDelta = 0; } if (!ScrollRows(newOffset)) { - this.cumulativeVerticalWheelDelta = 0; + cumulativeVerticalWheelDelta = 0; return; } } @@ -3853,37 +3853,37 @@ protected override void OnMouseWheel(MouseEventArgs me) if (scrollBands > 0) { - if (this.scrollBar.Value <= this.scrollBar.Minimum) + if (scrollBar.Value <= scrollBar.Minimum) { - this.cumulativeVerticalWheelDelta = 0; + cumulativeVerticalWheelDelta = 0; } else { - this.cumulativeVerticalWheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); + cumulativeVerticalWheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); } } else { - if (this.scrollBar.Value > (scrollBar.Maximum - visibleRows + 1)) + if (scrollBar.Value > (scrollBar.Maximum - visibleRows + 1)) { - this.cumulativeVerticalWheelDelta = 0; + cumulativeVerticalWheelDelta = 0; } else { - this.cumulativeVerticalWheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); + cumulativeVerticalWheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); } } if (!ScrollRows(newOffset)) { - this.cumulativeVerticalWheelDelta = 0; + cumulativeVerticalWheelDelta = 0; return; } } else { - this.cumulativeVerticalWheelDelta = 0; + cumulativeVerticalWheelDelta = 0; } } @@ -3917,7 +3917,7 @@ protected override void OnPaint(PaintEventArgs pe) try { - Size sizeWindow = this.Size; + Size sizeWindow = Size; // figure out what rows we're painting Point posStart = FindPosition(clipRect.X, clipRect.Y); @@ -3953,8 +3953,8 @@ protected override void OnPaint(PaintEventArgs pe) //SetConstants(); - Size size = this.GetOurSize(); - Point loc = this.ptOurLocation; + Size size = GetOurSize(); + Point loc = ptOurLocation; if (GetGridEntryFromRow(cPropsVisible - 1) == null) { @@ -4083,7 +4083,7 @@ private void OnGridEntryValueDoubleClick(object s, EventArgs e) private void OnGridEntryLabelClick(object s, EventArgs e) { - this.lastClickedEntry = (GridEntry)s; + lastClickedEntry = (GridEntry)s; SelectGridEntry(lastClickedEntry, true); } @@ -4113,7 +4113,7 @@ private void OnGridEntryOutlineClick(object s, EventArgs e) private void OnGridEntryValueClick(object s, EventArgs e) { - this.lastClickedEntry = (GridEntry)s; + lastClickedEntry = (GridEntry)s; bool setSelectTime = s != selectedGridEntry; SelectGridEntry(lastClickedEntry, true); Edit.Focus(); @@ -4163,14 +4163,14 @@ protected override void OnFontChanged(EventArgs e) ClearCachedFontInfo(); cachedRowHeight = -1; - if (this.Disposing || this.ParentInternal == null || this.ParentInternal.Disposing) + if (Disposing || ParentInternal == null || ParentInternal.Disposing) { return; } fontBold = null; // fontBold is cached based on Font - ToolTip.Font = this.Font; + ToolTip.Font = Font; SetFlag(FlagNeedUpdateUIBasedOnFont, true); UpdateUIBasedOnFont(true); base.OnFontChanged(e); @@ -4183,12 +4183,12 @@ protected override void OnFontChanged(EventArgs e) protected override void OnVisibleChanged(EventArgs e) { - if (this.Disposing || this.ParentInternal == null || this.ParentInternal.Disposing) + if (Disposing || ParentInternal == null || ParentInternal.Disposing) { return; } - if (this.Visible && this.ParentInternal != null) + if (Visible && ParentInternal != null) { SetConstants(); if (selectedGridEntry != null) @@ -4197,7 +4197,7 @@ protected override void OnVisibleChanged(EventArgs e) } if (toolTip != null) { - ToolTip.Font = this.Font; + ToolTip.Font = Font; } } @@ -4666,7 +4666,7 @@ public override void Refresh() // changes sort and move to a secondary monitor with different DPI and change view sort back to original. if (topLevelGridEntries != null && DpiHelper.IsScalingRequirementMet) { - var outlineRectIconSize = this.GetOutlineIconSize(); + var outlineRectIconSize = GetOutlineIconSize(); foreach (GridEntry gridentry in topLevelGridEntries) { if (gridentry.OutlineRect.Height != outlineRectIconSize || gridentry.OutlineRect.Width != outlineRectIconSize) @@ -4697,7 +4697,7 @@ private void Refresh(bool fullRefresh, int rowStart, int rowEnd) // There are cases here where the grid could get be disposed. // so just bail. - if (this.IsDisposed) + if (IsDisposed) { return; } @@ -4709,7 +4709,7 @@ private void Refresh(bool fullRefresh, int rowStart, int rowEnd) rowStart = 0; } - if (fullRefresh || this.ownerGrid.HavePropEntriesChanged()) + if (fullRefresh || ownerGrid.HavePropEntriesChanged()) { if (HasEntries && !GetInPropertySet() && !Commit()) { @@ -4722,7 +4722,7 @@ private void Refresh(bool fullRefresh, int rowStart, int rowEnd) // walk up to the main IPE and refresh it. if (fullRefresh) { - this.ownerGrid.RefreshProperties(true); + ownerGrid.RefreshProperties(true); } if (oldLength > 0 && !GetFlag(FlagNoDefault)) @@ -4734,7 +4734,7 @@ private void Refresh(bool fullRefresh, int rowStart, int rowEnd) UpdateHelpAttributes(selectedGridEntry, null); selectedGridEntry = null; SetFlag(FlagIsNewSelection, true); - topLevelGridEntries = this.ownerGrid.GetPropEntries(); + topLevelGridEntries = ownerGrid.GetPropEntries(); ClearGridEntryEvents(allGridEntries, 0, -1); @@ -4765,7 +4765,7 @@ private void Refresh(bool fullRefresh, int rowStart, int rowEnd) if (gridEntry == null) { - gridEntry = this.ownerGrid.GetDefaultGridEntry(); + gridEntry = ownerGrid.GetDefaultGridEntry(); SetFlag(FlagNoDefault, gridEntry == null && totalProps > 0); } @@ -4794,7 +4794,7 @@ private void Refresh(bool fullRefresh, int rowStart, int rowEnd) if (!HasEntries) { CommonEditorHide(selectedRow != -1); - this.ownerGrid.SetStatusBox(null, null); + ownerGrid.SetStatusBox(null, null); SetScrollOffset(0); selectedRow = -1; Invalidate(); @@ -4993,7 +4993,7 @@ private void SelectRow(int row) if (!GetFlag(FlagIsNewSelection)) { - if (this.FocusInside) + if (FocusInside) { // If we're in an error state, we want to bail out of this. if (errorState != ERROR_NONE || (row != selectedRow && !Commit())) @@ -5070,7 +5070,7 @@ private void SelectRow(int row) if ((fBtnDialog || fBtnDropDown) && !gridEntry.ShouldRenderReadOnly && FocusInside) { Control btn = fBtnDropDown ? (Control)DropDownButton : (Control)DialogButton; - Size sizeBtn = DpiHelper.IsScalingRequirementMet ? new Size(SystemInformation.VerticalScrollBarArrowHeightForDpi(this.deviceDpi), RowHeight) : + Size sizeBtn = DpiHelper.IsScalingRequirementMet ? new Size(SystemInformation.VerticalScrollBarArrowHeightForDpi(deviceDpi), RowHeight) : new Size(SystemInformation.VerticalScrollBarArrowHeight, RowHeight); Rectangle rectTarget = new Rectangle(rect.X + rect.Width - sizeBtn.Width, rect.Y, @@ -5140,8 +5140,8 @@ private void SelectRow(int row) rect.Width -= 1; CommonEditorUse(Edit, rect); bool drawReadOnly = gridEntry.ShouldRenderReadOnly; - Edit.ForeColor = drawReadOnly ? this.GrayTextColor : this.ForeColor; - Edit.BackColor = this.BackColor; + Edit.ForeColor = drawReadOnly ? GrayTextColor : ForeColor; + Edit.BackColor = BackColor; Edit.ReadOnly = drawReadOnly || !gridEntry.IsTextEditable; Edit.UseSystemPasswordChar = gridEntry.ShouldRenderPassword; } @@ -5149,12 +5149,12 @@ private void SelectRow(int row) GridEntry oldSelectedGridEntry = selectedGridEntry; selectedRow = row; selectedGridEntry = gridEntry; - this.ownerGrid.SetStatusBox(gridEntry.PropertyLabel, gridEntry.PropertyDescription); + ownerGrid.SetStatusBox(gridEntry.PropertyLabel, gridEntry.PropertyDescription); // tell the new focused item that it now has focus if (selectedGridEntry != null) { - selectedGridEntry.Focus = this.FocusInside; + selectedGridEntry.Focus = FocusInside; } if (!GetFlag(FlagIsNewSelection)) @@ -5176,7 +5176,7 @@ private void SelectRow(int row) { if (selectedGridEntry != oldSelectedGridEntry) { - this.ownerGrid.OnSelectedGridItemChanged(oldSelectedGridEntry, selectedGridEntry); + ownerGrid.OnSelectedGridItemChanged(oldSelectedGridEntry, selectedGridEntry); } } catch @@ -5187,11 +5187,11 @@ private void SelectRow(int row) public virtual void SetConstants() { Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:SetConstants"); - Size size = this.GetOurSize(); + Size size = GetOurSize(); visibleRows = (int)Math.Ceiling(((double)size.Height) / (1 + RowHeight)); - size = this.GetOurSize(); + size = GetOurSize(); if (size.Width >= 0) { @@ -5373,7 +5373,7 @@ private bool Commit() return false; } - if (!this.NeedsCommit) + if (!NeedsCommit) { SetCommitError(ERROR_NONE); Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:Commit() returning true because no change has been made"); @@ -5526,7 +5526,7 @@ internal bool CommitValue(GridEntry ipeCur, object value, bool closeDropDown = t } } - this.ownerGrid.OnPropertyValueSet(ipeCur, originalValue); + ownerGrid.OnPropertyValueSet(ipeCur, originalValue); return true; } @@ -5753,7 +5753,7 @@ private void ShowFormatExceptionMessage(string propName, object value, Exception } else { - revert = (DialogResult.Cancel == this.ShowDialog(ErrorDialog)); + revert = (DialogResult.Cancel == ShowDialog(ErrorDialog)); } Edit.DisableMouseHook = false; @@ -5839,7 +5839,7 @@ internal void ShowInvalidMessage(string propName, object value, Exception ex) } else { - revert = (DialogResult.Cancel == this.ShowDialog(ErrorDialog)); + revert = (DialogResult.Cancel == ShowDialog(ErrorDialog)); } Edit.DisableMouseHook = false; @@ -5954,7 +5954,7 @@ private void UpdateUIBasedOnFont(bool layoutRequired) var isScalingRequirementMet = DpiHelper.IsScalingRequirementMet; if (isScalingRequirementMet) { - btnDropDown.Size = new Size(SystemInformation.VerticalScrollBarArrowHeightForDpi(this.deviceDpi), RowHeight); + btnDropDown.Size = new Size(SystemInformation.VerticalScrollBarArrowHeightForDpi(deviceDpi), RowHeight); } else { @@ -5996,7 +5996,7 @@ private bool UnfocusSelection() bool commit = Commit(); - if (commit && this.FocusInside) + if (commit && FocusInside) { Focus(); } @@ -6025,7 +6025,7 @@ internal bool WantsTab(bool forward) { if (forward) { - if (this.Focused) + if (Focused) { // we want a tab if the grid has focus and // we have a button or an Edit @@ -6070,7 +6070,7 @@ private unsafe bool WmNotify(ref Message m) Point mouseLoc = Cursor.Position; // convert to window coords - mouseLoc = this.PointToClient(mouseLoc); + mouseLoc = PointToClient(mouseLoc); // figure out where we are and apply the offset mouseLoc = FindPosition(mouseLoc.X, mouseLoc.Y); @@ -6297,17 +6297,17 @@ static DropDownHolder() internal DropDownHolder(PropertyGridView psheet) : base() { - this.ShowInTaskbar = false; - this.ControlBox = false; - this.MinimizeBox = false; - this.MaximizeBox = false; - this.Text = string.Empty; - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; - this.AutoScaleMode = AutoScaleMode.None; // children may scale, but we won't interfere. + ShowInTaskbar = false; + ControlBox = false; + MinimizeBox = false; + MaximizeBox = false; + Text = string.Empty; + FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; + AutoScaleMode = AutoScaleMode.None; // children may scale, but we won't interfere. mouseHook = new MouseHook(this, this, psheet); Visible = false; gridView = psheet; - this.BackColor = gridView.BackColor; + BackColor = gridView.BackColor; } protected override CreateParams CreateParams @@ -6333,10 +6333,10 @@ private LinkLabel CreateNewLink { get { - if (this.createNewLink == null) + if (createNewLink == null) { - this.createNewLink = new LinkLabel(); - this.createNewLink.LinkClicked += new LinkLabelLinkClickedEventHandler(OnNewLinkClicked); + createNewLink = new LinkLabel(); + createNewLink.LinkClicked += new LinkLabelLinkClickedEventHandler(OnNewLinkClicked); } return createNewLink; } @@ -6375,15 +6375,15 @@ public bool ResizeUp if (resizable) { - this.DockPadding.Bottom = 0; - this.DockPadding.Top = 0; + DockPadding.Bottom = 0; + DockPadding.Top = 0; if (value) { - this.DockPadding.Top = ResizeBarSize; + DockPadding.Top = ResizeBarSize; } else { - this.DockPadding.Bottom = ResizeBarSize; + DockPadding.Bottom = ResizeBarSize; } } } @@ -6414,7 +6414,7 @@ public void DoModalLoop() // Push a modal loop. This seems expensive, but I think it is a // better user model than returning from DropDownControl immediately. // - while (this.Visible) + while (Visible) { Application.DoEventsModal(); UnsafeNativeMethods.MsgWaitForMultipleObjectsEx(0, IntPtr.Zero, 250, NativeMethods.QS_ALLINPUT, NativeMethods.MWMO_INPUTAVAILABLE); @@ -6475,7 +6475,7 @@ private InstanceCreationEditor GetInstanceCreationEditor(PropertyDescriptorGridE private Bitmap GetSizeGripGlyph(Graphics g) { - if (this.sizeGripGlyph != null) + if (sizeGripGlyph != null) { return sizeGripGlyph; } @@ -6539,7 +6539,7 @@ private bool OwnsWindow(IntPtr hWnd) { return false; } - if (hWnd == this.Handle) + if (hWnd == Handle) { return true; } @@ -6557,7 +6557,7 @@ private void OnCurrentControlResize(object o, EventArgs e) { if (currentControl != null && !resizing) { - int oldWidth = this.Width; + int oldWidth = Width; Size newSize = new Size(2 * DropDownHolderBorder + currentControl.Width, 2 * DropDownHolderBorder + currentControl.Height); if (resizable) { @@ -6566,15 +6566,15 @@ private void OnCurrentControlResize(object o, EventArgs e) try { resizing = true; - this.SuspendLayout(); - this.Size = newSize; + SuspendLayout(); + Size = newSize; } finally { resizing = false; - this.ResumeLayout(false); + ResumeLayout(false); } - this.Left -= (this.Width - oldWidth); + Left -= (Width - oldWidth); } } @@ -6658,8 +6658,8 @@ protected override void OnMouseDown(MouseEventArgs e) { if (e.Button == MouseButtons.Left) { - this.currentMoveType = MoveTypeFromPoint(e.X, e.Y); - if (this.currentMoveType != MoveTypeNone) + currentMoveType = MoveTypeFromPoint(e.X, e.Y); + if (currentMoveType != MoveTypeNone) { dragStart = PointToScreen(new Point(e.X, e.Y)); dragBaseRect = Bounds; @@ -6680,7 +6680,7 @@ protected override void OnMouseMove(MouseEventArgs e) { // not moving so just set the cursor. // - if (this.currentMoveType == MoveTypeNone) + if (currentMoveType == MoveTypeNone) { int cursorMoveType = MoveTypeFromPoint(e.X, e.Y); switch (cursorMoveType) @@ -6743,7 +6743,7 @@ protected override void OnMouseMove(MouseEventArgs e) try { resizing = true; - this.Bounds = newBounds; + Bounds = newBounds; } finally { @@ -6775,10 +6775,10 @@ protected override void OnMouseUp(MouseEventArgs e) // reset the world. // - this.currentMoveType = MoveTypeNone; - this.dragStart = Point.Empty; - this.dragBaseRect = Rectangle.Empty; - this.Capture = false; + currentMoveType = MoveTypeNone; + dragStart = Point.Empty; + dragBaseRect = Rectangle.Empty; + Capture = false; } } @@ -6833,7 +6833,7 @@ public void SetComponent(Control ctl, bool resizable) { this.resizable = resizable; - this.Font = gridView.Font; + Font = gridView.Font; // check to see if we're going to be adding an InstanceCreationEditor // @@ -6843,7 +6843,7 @@ public void SetComponent(Control ctl, bool resizable) // if (currentControl != null) { - currentControl.Resize -= new EventHandler(this.OnCurrentControlResize); + currentControl.Resize -= new EventHandler(OnCurrentControlResize); Controls.Remove(currentControl); currentControl = null; } @@ -6852,7 +6852,7 @@ public void SetComponent(Control ctl, bool resizable) // if (createNewLink != null && createNewLink.Parent == this) { - this.Controls.Remove(createNewLink); + Controls.Remove(createNewLink); } // now set up the new control, top to bottom @@ -6863,7 +6863,7 @@ public void SetComponent(Control ctl, bool resizable) currentControl = ctl; Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "DropDownHolder:SetComponent(" + (ctl.GetType().Name) + ")"); - this.DockPadding.All = 0; + DockPadding.All = 0; // first handle the control. If it's a listbox, make sure it's got some height // to it. @@ -6903,7 +6903,7 @@ public void SetComponent(Control ctl, bool resizable) int linkHeight = CreateNewLink.Height; using (Graphics g = gridView.CreateGraphics()) { - SizeF sizef = PropertyGrid.MeasureTextHelper.MeasureText(this.gridView.ownerGrid, g, editor.Text, gridView.GetBaseFont()); + SizeF sizef = PropertyGrid.MeasureTextHelper.MeasureText(gridView.ownerGrid, g, editor.Text, gridView.GetBaseFont()); linkHeight = (int)sizef.Height; } @@ -6923,11 +6923,11 @@ public void SetComponent(Control ctl, bool resizable) // if (resizeUp) { - this.DockPadding.Top = ResizeBarSize; + DockPadding.Top = ResizeBarSize; } else { - this.DockPadding.Bottom = ResizeBarSize; + DockPadding.Bottom = ResizeBarSize; } } @@ -6950,7 +6950,7 @@ public void SetComponent(Control ctl, bool resizable) // hook the resize event. // - currentControl.Resize += new EventHandler(this.OnCurrentControlResize); + currentControl.Resize += new EventHandler(OnCurrentControlResize); } Enabled = currentControl != null; } @@ -6963,7 +6963,7 @@ protected override void WndProc(ref Message m) SetState(STATE_MODAL, true); Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "DropDownHolder:WM_ACTIVATE()"); IntPtr activatedWindow = (IntPtr)m.LParam; - if (Visible && NativeMethods.Util.LOWORD(m.WParam) == NativeMethods.WA_INACTIVE && !this.OwnsWindow(activatedWindow)) + if (Visible && NativeMethods.Util.LOWORD(m.WParam) == NativeMethods.WA_INACTIVE && !OwnsWindow(activatedWindow)) { gridView.CloseDropDownInternal(false); return; @@ -7482,7 +7482,7 @@ public virtual bool Filter set { - this.filter = value; + filter = value; } } @@ -7540,7 +7540,7 @@ public virtual bool HookMouseDown mouseHook.HookMouseDown = value; if (value) { - this.Focus(); + Focus(); } } } @@ -7586,8 +7586,8 @@ public void FilterKeyPress(char keyChar) if (IsInputChar(keyChar)) { - this.Focus(); - this.SelectAll(); + Focus(); + SelectAll(); UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), Interop.WindowMessages.WM_CHAR, (IntPtr)keyChar, IntPtr.Zero); } } @@ -7665,13 +7665,13 @@ protected override void OnMouseEnter(EventArgs e) { base.OnMouseEnter(e); - if (!this.Focused) + if (!Focused) { Graphics g = CreateGraphics(); if (psheet.SelectedGridEntry != null && - ClientRectangle.Width <= psheet.SelectedGridEntry.GetValueTextWidth(this.Text, g, this.Font)) + ClientRectangle.Width <= psheet.SelectedGridEntry.GetValueTextWidth(Text, g, Font)) { - psheet.ToolTip.ToolTip = this.PasswordProtect ? "" : this.Text; + psheet.ToolTip.ToolTip = PasswordProtect ? "" : Text; } g.Dispose(); } @@ -7793,7 +7793,7 @@ protected override void SetVisibleCore(bool value) Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "DropDownHolder:Visible(" + (value.ToString()) + ")"); // make sure we dont' have the mouse captured if // we're going invisible - if (value == false && this.HookMouseDown) + if (value == false && HookMouseDown) { mouseHook.HookMouseDown = false; } @@ -7881,7 +7881,7 @@ protected override void WndProc(ref Message m) } } }*/ - if (this.ReadOnly) + if (ReadOnly) { return; } @@ -7890,7 +7890,7 @@ protected override void WndProc(ref Message m) case Interop.WindowMessages.WM_GETDLGCODE: m.Result = (IntPtr)((long)m.Result | NativeMethods.DLGC_WANTARROWS | NativeMethods.DLGC_WANTCHARS); - if (psheet.NeedsCommit || this.WantsTab((ModifierKeys & Keys.Shift) == 0)) + if (psheet.NeedsCommit || WantsTab((ModifierKeys & Keys.Shift) == 0)) { m.Result = (IntPtr)((long)m.Result | NativeMethods.DLGC_WANTALLKEYS | NativeMethods.DLGC_WANTTAB); } @@ -7917,7 +7917,7 @@ protected class GridViewEditAccessibleObject : ControlAccessibleObject public GridViewEditAccessibleObject(GridViewEdit owner) : base(owner) { - this.propertyGridView = owner.psheet; + propertyGridView = owner.psheet; } public override AccessibleStates State @@ -7925,7 +7925,7 @@ public override AccessibleStates State get { AccessibleStates states = base.State; - if (this.IsReadOnly) + if (IsReadOnly) { states |= AccessibleStates.ReadOnly; } @@ -7980,7 +7980,7 @@ internal override object GetPropertyValue(int propertyID) { if (propertyID == NativeMethods.UIA_IsEnabledPropertyId) { - return !this.IsReadOnly; + return !IsReadOnly; } else if (propertyID == NativeMethods.UIA_IsValuePatternAvailablePropertyId) { @@ -8041,7 +8041,7 @@ internal override bool IsReadOnly { get { - PropertyDescriptorGridEntry propertyDescriptorGridEntry = this.propertyGridView.SelectedGridEntry as PropertyDescriptorGridEntry; + PropertyDescriptorGridEntry propertyDescriptorGridEntry = propertyGridView.SelectedGridEntry as PropertyDescriptorGridEntry; return propertyDescriptorGridEntry == null || propertyDescriptorGridEntry.IsPropertyReadOnly; } } @@ -8256,7 +8256,7 @@ private bool ProcessMouseDown(IntPtr hWnd, int x, int y) // if this isn't our process, unhook the mouse. if (pid != thisProcessID) { - this.HookMouseDown = false; + HookMouseDown = false; return false; } @@ -8309,7 +8309,7 @@ private class MouseHookObject public MouseHookObject(MouseHook parent) { - this.reference = new WeakReference(parent, false); + reference = new WeakReference(parent, false); } public virtual IntPtr Callback(int nCode, IntPtr wparam, IntPtr lparam) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/SingleSelectRootGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/SingleSelectRootGridEntry.cs index 2f98e2988f1..f71b9159c9a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/SingleSelectRootGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/SingleSelectRootGridEntry.cs @@ -44,13 +44,13 @@ internal SingleSelectRootGridEntry(PropertyGridView gridEntryHost, object value, this.gridEntryHost = gridEntryHost; this.baseProvider = baseProvider; this.tab = tab; - this.objValue = value; - this.objValueClassName = TypeDescriptor.GetClassName(this.objValue); + objValue = value; + objValueClassName = TypeDescriptor.GetClassName(objValue); - this.IsExpandable = true; + IsExpandable = true; // default to categories - this.PropertySort = sortType; - this.InternalExpanded = true; + PropertySort = sortType; + InternalExpanded = true; } [ @@ -72,7 +72,7 @@ public override AttributeCollection BrowsableAttributes { browsableAttributes = new AttributeCollection(new Attribute[] { BrowsableAttribute.Yes }); } - return this.browsableAttributes; + return browsableAttributes; } set { @@ -84,7 +84,7 @@ public override AttributeCollection BrowsableAttributes bool same = true; - if (this.browsableAttributes != null && value != null && this.browsableAttributes.Count == value.Count) + if (browsableAttributes != null && value != null && browsableAttributes.Count == value.Count) { Attribute[] attr1 = new Attribute[browsableAttributes.Count]; Attribute[] attr2 = new Attribute[value.Count]; @@ -108,7 +108,7 @@ public override AttributeCollection BrowsableAttributes same = false; } - this.browsableAttributes = value; + browsableAttributes = value; if (!same && Children != null && Children.Count > 0) { @@ -145,7 +145,7 @@ public override PropertyTab CurrentTab } set { - this.tab = value; + tab = value; } } @@ -157,7 +157,7 @@ internal override GridEntry DefaultChild } set { - this.propDefault = value; + propDefault = value; } } @@ -179,8 +179,8 @@ internal override bool ForceReadOnly { if (!forceReadOnlyChecked) { - ReadOnlyAttribute readOnlyAttr = (ReadOnlyAttribute)TypeDescriptor.GetAttributes(this.objValue)[typeof(ReadOnlyAttribute)]; - if ((readOnlyAttr != null && !readOnlyAttr.IsDefaultAttribute()) || TypeDescriptor.GetAttributes(this.objValue).Contains(InheritanceAttribute.InheritedReadOnly)) + ReadOnlyAttribute readOnlyAttr = (ReadOnlyAttribute)TypeDescriptor.GetAttributes(objValue)[typeof(ReadOnlyAttribute)]; + if ((readOnlyAttr != null && !readOnlyAttr.IsDefaultAttribute()) || TypeDescriptor.GetAttributes(objValue).Contains(InheritanceAttribute.InheritedReadOnly)) { flags |= FLAG_FORCE_READONLY; } @@ -194,11 +194,11 @@ internal override PropertyGridView GridEntryHost { get { - return this.gridEntryHost; + return gridEntryHost; } set { - this.gridEntryHost = value; + gridEntryHost = value; } } @@ -226,7 +226,7 @@ public override string HelpKeyword return helpAttribute.HelpKeyword; } - return this.objValueClassName; + return objValueClassName; } } @@ -290,9 +290,9 @@ protected override void Dispose(bool disposing) gridEntryHost = null; changeService = null; } - this.objValue = null; - this.objValueClassName = null; - this.propDefault = null; + objValue = null; + objValueClassName = null; + propDefault = null; base.Dispose(disposing); } @@ -316,7 +316,7 @@ public override object GetService(Type serviceType) /// public void ResetBrowsableAttributes() { - this.browsableAttributes = new AttributeCollection(new Attribute[] { BrowsableAttribute.Yes }); + browsableAttributes = new AttributeCollection(new Attribute[] { BrowsableAttribute.Yes }); } @@ -325,21 +325,21 @@ public void ResetBrowsableAttributes() /// public virtual void ShowCategories(bool fCategories) { - if (((this.PropertySort &= PropertySort.Categorized) != 0) != fCategories) + if (((PropertySort &= PropertySort.Categorized) != 0) != fCategories) { if (fCategories) { - this.PropertySort |= PropertySort.Categorized; + PropertySort |= PropertySort.Categorized; } else { - this.PropertySort &= ~PropertySort.Categorized; + PropertySort &= ~PropertySort.Categorized; } // recreate the children - if (this.Expandable && this.ChildCollection != null) + if (Expandable && ChildCollection != null) { CreateChildren(); } @@ -351,10 +351,10 @@ internal void CategorizePropEntries() if (Children.Count > 0) { - GridEntry[] childEntries = new GridEntry[this.Children.Count]; - this.Children.CopyTo(childEntries, 0); + GridEntry[] childEntries = new GridEntry[Children.Count]; + Children.CopyTo(childEntries, 0); - if ((this.PropertySort & PropertySort.Categorized) != 0) + if ((PropertySort & PropertySort.Categorized) != 0) { @@ -399,7 +399,7 @@ internal void CategorizePropEntries() bin.CopyTo(rgpes, 0); try { - propList.Add(new CategoryGridEntry(this.ownerGrid, this, category, rgpes)); + propList.Add(new CategoryGridEntry(ownerGrid, this, category, rgpes)); } catch { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyManager.cs index 9809f7d1c52..85c92ccdd91 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyManager.cs @@ -57,8 +57,8 @@ internal PropertyManager(object dataSource) : base(dataSource) [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "If the constructor does not set the dataSource it would be a breaking change.")] internal PropertyManager(object dataSource, string propName) : base() { - this._propName = propName; - this.SetDataSource(dataSource); + _propName = propName; + SetDataSource(dataSource); } internal override PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs index 1cc1525e29e..25465b7849d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs @@ -137,7 +137,7 @@ public Appearance Appearance throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(Appearance)); } - using (LayoutTransaction.CreateTransactionIf(AutoSize, this.ParentInternal, this, PropertyNames.Appearance)) + using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.Appearance)) { appearance = value; if (OwnerDraw) @@ -328,7 +328,7 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) return base.GetPreferredSizeCore(proposedConstraints); } - Size textSize = TextRenderer.MeasureText(this.Text, this.Font); + Size textSize = TextRenderer.MeasureText(Text, Font); Size size = SizeFromClientSize(textSize); size.Width += flatSystemStylePaddingWidth; size.Height = DpiHelper.IsScalingRequirementMet ? Math.Max(size.Height + 5, flatSystemStyleMinimumHeight) : size.Height + 5; // ensure minimum height to avoid truncation of RadioButton circle or text diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RelatedCurrencyManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RelatedCurrencyManager.cs index d6ce463f006..9ba44e8302a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RelatedCurrencyManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RelatedCurrencyManager.cs @@ -43,12 +43,12 @@ internal void Bind(BindingManagerBase parentManager, string dataField) this.parentManager = parentManager; this.dataField = dataField; - this.fieldInfo = parentManager.GetItemProperties().Find(dataField, true); + fieldInfo = parentManager.GetItemProperties().Find(dataField, true); if (fieldInfo == null || !typeof(IList).IsAssignableFrom(fieldInfo.PropertyType)) { throw new ArgumentException(string.Format(SR.RelatedListManagerChild, dataField)); } - this.finalType = fieldInfo.PropertyType; + finalType = fieldInfo.PropertyType; // Wire new BindingManagerBase WireParentManager(this.parentManager); @@ -97,7 +97,7 @@ internal override PropertyDescriptorCollection GetItemProperties(PropertyDescrip } // Set this accessor (add to the beginning) - accessors[0] = this.fieldInfo; + accessors[0] = fieldInfo; // Get props return parentManager.GetItemProperties(accessors); @@ -146,7 +146,7 @@ private void ParentManager_CurrentItemChanged(object sender, EventArgs e) return; } - int oldlistposition = this.listposition; + int oldlistposition = listposition; // we only pull the data from the controls into the backEnd. we do not care about keeping the lastGoodKnownRow // when we are about to change the entire list in this currencymanager. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RelatedPropertyManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RelatedPropertyManager.cs index 95b8f817d8f..e9d65219a96 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RelatedPropertyManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RelatedPropertyManager.cs @@ -33,7 +33,7 @@ private void Bind(BindingManagerBase parentManager, string dataField) Debug.Assert(parentManager != null, "How could this be a null parentManager."); this.parentManager = parentManager; this.dataField = dataField; - this.fieldInfo = parentManager.GetItemProperties().Find(dataField, true); + fieldInfo = parentManager.GetItemProperties().Find(dataField, true); if (fieldInfo == null) throw new ArgumentException(string.Format(SR.RelatedListManagerChild, dataField)); // this.finalType = fieldInfo.PropertyType; @@ -72,7 +72,7 @@ internal override PropertyDescriptorCollection GetItemProperties(PropertyDescrip } // Set this accessor (add to the beginning) - accessors[0] = this.fieldInfo; + accessors[0] = fieldInfo; // Get props return parentManager.GetItemProperties(accessors); @@ -103,7 +103,7 @@ public override object Current { get { - return (this.DataSource != null) ? fieldInfo.GetValue(this.DataSource) : null; + return (DataSource != null) ? fieldInfo.GetValue(DataSource) : null; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs index 61d0c8e0b61..05cb6f393fa 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs @@ -298,7 +298,7 @@ public int BulletIndent throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(BulletIndent), value)); } - this.bulletIndent = value; + bulletIndent = value; // Call to update the control only if the bullet is set. if (IsHandleCreated && SelectionBullet) @@ -441,7 +441,7 @@ public bool DetectUrls richTextBoxFlags[autoUrlDetectSection] = value ? 1 : 0; if (IsHandleCreated) { - this.SendMessage(Interop.EditMessages.EM_AUTOURLDETECT, value ? 1 : 0, 0); + SendMessage(Interop.EditMessages.EM_AUTOURLDETECT, value ? 1 : 0, 0); RecreateHandle(); } } @@ -604,9 +604,9 @@ public RichTextBoxLanguageOptions LanguageOption } set { - if (this.LanguageOption != value) + if (LanguageOption != value) { - this.languageOption = value; + languageOption = value; if (IsHandleCreated) { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_SETLANGOPTIONS, 0, (int)value); @@ -715,11 +715,11 @@ public int RightMargin } set { - if (this.rightMargin != value) + if (rightMargin != value) { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(RightMargin), value, 0)); - this.rightMargin = value; + rightMargin = value; if (value == 0) { @@ -1082,7 +1082,7 @@ public Color SelectionBackColor // If the effects member contains valid info if ((cf2.dwEffects & RichTextBoxConstants.CFE_AUTOBACKCOLOR) != 0) { - selColor = this.BackColor; + selColor = BackColor; } else if ((cf2.dwMask & RichTextBoxConstants.CFM_BACKCOLOR) != 0) { @@ -2067,7 +2067,7 @@ public int Find(string str, int start, int end, RichTextBoxFinds options) //represent Arabic characters and _ represents a kashida). We should highlight the text //including the kashida. char kashida = (char)0x640; - string text = this.Text; + string text = Text; string foundString = text.Substring(position, str.Length); int startIndex = foundString.IndexOf(kashida); if (startIndex == -1) @@ -2379,7 +2379,7 @@ public override int GetCharIndexFromPosition(Point pt) NativeMethods.POINT wpt = new NativeMethods.POINT(pt.X, pt.Y); int index = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_CHARFROMPOS, 0, wpt); - string t = this.Text; + string t = Text; // EM_CHARFROMPOS will return an invalid number if the last character in the RichEdit // is a newline. // @@ -2502,7 +2502,7 @@ public void LoadFile(Stream data, RichTextBoxStreamType fileType) flags = RichTextBoxConstants.SF_RTF; break; case RichTextBoxStreamType.PlainText: - this.Rtf = string.Empty; + Rtf = string.Empty; flags = RichTextBoxConstants.SF_TEXT; break; case RichTextBoxStreamType.UnicodePlainText: @@ -2609,10 +2609,10 @@ protected override void OnHandleCreated(EventArgs e) // - this.SendMessage(Interop.EditMessages.EM_AUTOURLDETECT, DetectUrls ? 1 : 0, 0); + SendMessage(Interop.EditMessages.EM_AUTOURLDETECT, DetectUrls ? 1 : 0, 0); if (selectionBackColorToSetOnHandleCreated != Color.Empty) { - this.SelectionBackColor = selectionBackColorToSetOnHandleCreated; + SelectionBackColor = selectionBackColorToSetOnHandleCreated; } // Initialize colors before initializing RTF, otherwise CFE_AUTOCOLOR will be in effect @@ -2663,9 +2663,9 @@ protected override void OnHandleCreated(EventArgs e) (IntPtr)RichTextBoxConstants.ECO_SELECTIONBAR); } - if (languageOption != this.LanguageOption) + if (languageOption != LanguageOption) { - this.LanguageOption = languageOption; + LanguageOption = languageOption; } ClearUndo(); @@ -2767,7 +2767,7 @@ public void Paste(DataFormats.Format clipFormat) protected override bool ProcessCmdKey(ref Message m, Keys keyData) { - if (this.RichTextShortcutsEnabled == false) + if (RichTextShortcutsEnabled == false) { foreach (int shortcutValue in shortcutsToDisable) { @@ -3101,7 +3101,7 @@ private void StreamIn(Stream data, int flags) cookieVal |= TEXTLF; } es.dwCookie = (IntPtr)cookieVal; - es.pfnCallback = new NativeMethods.EditStreamCallback(this.EditStreamProc); + es.pfnCallback = new NativeMethods.EditStreamCallback(EditStreamProc); // gives us TextBox compatible behavior, programatic text change shouldn't // be limited... @@ -3219,7 +3219,7 @@ private void StreamOut(Stream data, int flags, bool includeCrLfs) } } es.dwCookie = (IntPtr)cookieVal; - es.pfnCallback = new NativeMethods.EditStreamCallback(this.EditStreamProc); + es.pfnCallback = new NativeMethods.EditStreamCallback(EditStreamProc); // Get Text // Needed for 64-bit @@ -3328,7 +3328,7 @@ private void UpdateOleCallback() { Debug.WriteLineIf(RichTextDbg.TraceVerbose, "binding ole callback"); - this.AllowOleObjects = true; + AllowOleObjects = true; oleCallback = CreateRichEditOleCallback(); @@ -3365,11 +3365,11 @@ private void UserPreferenceChangedHandler(object o, UserPreferenceChangedEventAr { if (IsHandleCreated) { - if (this.BackColor.IsSystemColor) + if (BackColor.IsSystemColor) { SendMessage(Interop.EditMessages.EM_SETBKGNDCOLOR, 0, ColorTranslator.ToWin32(BackColor)); } - if (this.ForeColor.IsSystemColor) + if (ForeColor.IsSystemColor) { InternalSetForeColor(ForeColor); } @@ -3872,7 +3872,7 @@ internal OleCallback(RichTextBox owner) public int GetNewStorage(out UnsafeNativeMethods.IStorage storage) { Debug.WriteLineIf(RichTextDbg.TraceVerbose, "IRichEditOleCallback::GetNewStorage"); - if (!this.owner.AllowOleObjects) + if (!owner.AllowOleObjects) { storage = null; return NativeMethods.E_FAIL; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SaveFileDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SaveFileDialog.cs index fa66241a497..4257fc3b473 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SaveFileDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SaveFileDialog.cs @@ -135,7 +135,7 @@ private protected override bool PromptUserIfAppropriate(string fileName) } //Note: When we are using the Vista dialog mode we get two prompts (one from us and one from the OS) if we do this - if ((_options & NativeMethods.OFN_OVERWRITEPROMPT) != 0 && FileExists(fileName) && !this.UseVistaDialogInternal) + if ((_options & NativeMethods.OFN_OVERWRITEPROMPT) != 0 && FileExists(fileName) && !UseVistaDialogInternal) { if (!PromptFileOverwrite(fileName)) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Screen.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Screen.cs index 3a9b9e4af45..9eb4e08f65e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Screen.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Screen.cs @@ -101,8 +101,8 @@ internal Screen(IntPtr monitor, IntPtr hdc) } hmonitor = monitor; - this.bitDepth = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, screenDC), NativeMethods.BITSPIXEL); - this.bitDepth *= UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, screenDC), NativeMethods.PLANES); + bitDepth = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, screenDC), NativeMethods.BITSPIXEL); + bitDepth *= UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, screenDC), NativeMethods.PLANES); if (hdc != screenDC) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs index a78b6b7fd4b..fdf31590a5e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs @@ -281,7 +281,7 @@ Rectangle IArrangedElement.DisplayRectangle { get { - Rectangle displayRectangle = this.DisplayRectangle; + Rectangle displayRectangle = DisplayRectangle; // V7#79 : Controls anchored the bottom of their container may disappear (be scrunched) // when scrolling is used. if (AutoScrollMinSize.Width != 0 && AutoScrollMinSize.Height != 0) @@ -693,13 +693,13 @@ private Rectangle GetDisplayRectInternal() { displayRect = ClientRectangle; } - if (!AutoScroll && this.HorizontalScroll._visible == true) + if (!AutoScroll && HorizontalScroll._visible == true) { - displayRect = new Rectangle(displayRect.X, displayRect.Y, this.HorizontalScroll.Maximum, this.displayRect.Height); + displayRect = new Rectangle(displayRect.X, displayRect.Y, HorizontalScroll.Maximum, displayRect.Height); } - if (!AutoScroll && this.VerticalScroll._visible == true) + if (!AutoScroll && VerticalScroll._visible == true) { - displayRect = new Rectangle(displayRect.X, displayRect.Y, this.displayRect.Width, this.VerticalScroll.Maximum); + displayRect = new Rectangle(displayRect.X, displayRect.Y, displayRect.Width, VerticalScroll.Maximum); } return displayRect; } @@ -1022,7 +1022,7 @@ protected virtual Point ScrollToControl(Control activeControl) if (activeControl.ParentInternal != this) { Debug.WriteLineIf(ScrollableControl.AutoScrolling.TraceVerbose, "not direct child, original bounds: " + bounds); - bounds = this.RectangleToClient(activeControl.ParentInternal.RectangleToScreen(bounds)); + bounds = RectangleToClient(activeControl.ParentInternal.RectangleToScreen(bounds)); } Debug.WriteLineIf(ScrollableControl.AutoScrolling.TraceVerbose, "adjusted bounds: " + bounds); @@ -1349,7 +1349,7 @@ private void SyncScrollbars(bool autoScroll) if (resetRTLHScrollValue && !IsMirrored) { resetRTLHScrollValue = false; - BeginInvoke(new EventHandler(this.OnSetScrollPosition)); + BeginInvoke(new EventHandler(OnSetScrollPosition)); } else if (-displayRect.X >= HorizontalScroll._minimum && -displayRect.X < HorizontalScroll._maximum) { @@ -1380,7 +1380,7 @@ private void SyncScrollbars(bool autoScroll) } else { - if (this.HorizontalScroll.Visible) + if (HorizontalScroll.Visible) { HorizontalScroll.Value = -displayRect.X; } @@ -1388,7 +1388,7 @@ private void SyncScrollbars(bool autoScroll) { ResetScrollProperties(HorizontalScroll); } - if (this.VerticalScroll.Visible) + if (VerticalScroll.Visible) { VerticalScroll.Value = -displayRect.Y; } @@ -1441,7 +1441,7 @@ private void WmVScroll(ref Message m) int maxPos = -(client.Height - displayRect.Height); if (!AutoScroll) { - maxPos = this.VerticalScroll.Maximum; + maxPos = VerticalScroll.Maximum; } switch (NativeMethods.Util.LOWORD(m.WParam)) @@ -1530,7 +1530,7 @@ private void WmHScroll(ref Message m) int maxPos = -(client.Width - displayRect.Width); if (!AutoScroll) { - maxPos = this.HorizontalScroll.Maximum; + maxPos = HorizontalScroll.Maximum; } switch (NativeMethods.Util.LOWORD(m.WParam)) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SelectionRange.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SelectionRange.cs index 7faf4c9709f..6075bfc0c77 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SelectionRange.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SelectionRange.cs @@ -69,8 +69,8 @@ public SelectionRange(DateTime lower, DateTime upper) /// public SelectionRange(SelectionRange range) { - this.start = range.start; - this.end = range.end; + start = range.start; + end = range.end; } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs index 4144ff80774..100f17cec0d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs @@ -150,8 +150,8 @@ public SplitContainer() SetStyle(ControlStyles.SupportsTransparentBackColor, true); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); - ((WindowsFormsUtils.TypedControlCollection)this.Controls).AddInternal(panel1); - ((WindowsFormsUtils.TypedControlCollection)this.Controls).AddInternal(panel2); + ((WindowsFormsUtils.TypedControlCollection)Controls).AddInternal(panel1); + ((WindowsFormsUtils.TypedControlCollection)Controls).AddInternal(panel2); UpdateSplitter(); } @@ -373,11 +373,11 @@ public BorderStyle BorderStyle borderStyle = value; Invalidate(); SetInnerMostBorder(this); - if (this.ParentInternal != null) + if (ParentInternal != null) { - if (this.ParentInternal is SplitterPanel) + if (ParentInternal is SplitterPanel) { - SplitContainer sc = (SplitContainer)((SplitterPanel)this.ParentInternal).Owner; + SplitContainer sc = (SplitContainer)((SplitterPanel)ParentInternal).Owner; sc.SetInnerMostBorder(sc); } } @@ -439,11 +439,11 @@ public BorderStyle BorderStyle set { base.Dock = value; - if (this.ParentInternal != null) + if (ParentInternal != null) { - if (this.ParentInternal is SplitterPanel) + if (ParentInternal is SplitterPanel) { - SplitContainer sc = (SplitContainer)((SplitterPanel)this.ParentInternal).Owner; + SplitContainer sc = (SplitContainer)((SplitterPanel)ParentInternal).Owner; sc.SetInnerMostBorder(sc); } } @@ -639,7 +639,7 @@ public SplitterPanel Panel1 { get { - return this.panel1; + return panel1; } } @@ -777,7 +777,7 @@ public SplitterPanel Panel2 { get { - return this.panel2; + return panel2; } } @@ -844,9 +844,9 @@ public int SplitterDistance { value = Panel1MinSize; } - if (value + SplitterWidthInternal > this.Width - Panel2MinSize) + if (value + SplitterWidthInternal > Width - Panel2MinSize) { - value = this.Width - Panel2MinSize - SplitterWidthInternal; + value = Width - Panel2MinSize - SplitterWidthInternal; } if (value < 0) { @@ -865,9 +865,9 @@ public int SplitterDistance value = Panel1MinSize; } - if (value + SplitterWidthInternal > this.Height - Panel2MinSize) + if (value + SplitterWidthInternal > Height - Panel2MinSize) { - value = this.Height - Panel2MinSize - SplitterWidthInternal; + value = Height - Panel2MinSize - SplitterWidthInternal; } if (value < 0) { @@ -1226,7 +1226,7 @@ protected override void OnKeyDown(KeyEventArgs e) Rectangle r = CalcSplitLine(splitterDistance, 0); int xSplit = r.X; int ySplit = r.Y; - SplitterCancelEventArgs se = new SplitterCancelEventArgs(this.Left + SplitterRectangle.X + SplitterRectangle.Width / 2, this.Top + SplitterRectangle.Y + SplitterRectangle.Height / 2, xSplit, ySplit); + SplitterCancelEventArgs se = new SplitterCancelEventArgs(Left + SplitterRectangle.X + SplitterRectangle.Width / 2, Top + SplitterRectangle.Y + SplitterRectangle.Height / 2, xSplit, ySplit); OnSplitterMoving(se); if (se.Cancel) { @@ -1266,7 +1266,7 @@ protected override void OnKeyUp(KeyEventArgs e) { if (BackgroundImage == null) { - using (SolidBrush brush = new SolidBrush(this.BackColor)) + using (SolidBrush brush = new SolidBrush(BackColor)) { g.FillRectangle(brush, SplitterRectangle); } @@ -1387,7 +1387,7 @@ protected override void OnMouseDown(MouseEventArgs e) { // Focus the current splitter OnMouseDown. splitterFocused = true; - IContainerControl c = this.ParentInternal.GetContainerControl(); + IContainerControl c = ParentInternal.GetContainerControl(); if (c != null) { ContainerControl cc = c as ContainerControl; @@ -1445,7 +1445,7 @@ protected override void OnMouseUp(MouseEventArgs e) protected override void OnMove(EventArgs e) { base.OnMove(e); - SetSplitterRect(this.Orientation == Orientation.Vertical); + SetSplitterRect(Orientation == Orientation.Vertical); } @@ -1497,8 +1497,8 @@ protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); // pass the RightToLeft value to the Parent. - this.panel1.RightToLeft = this.RightToLeft; - this.panel2.RightToLeft = this.RightToLeft; + panel1.RightToLeft = RightToLeft; + panel2.RightToLeft = RightToLeft; UpdateSplitter(); } @@ -1614,7 +1614,7 @@ private void ApplySplitterDistance() } // We need to invalidate when we have transparent backgournd. - if (this.BackColor == Color.Transparent) + if (BackColor == Color.Transparent) { // the panel1 retains the focus rect... so Invalidate the rect ... Invalidate(); @@ -1625,16 +1625,16 @@ private void ApplySplitterDistance() if (RightToLeft == RightToLeft.No) { - splitterRect.X = this.Location.X + SplitterDistanceInternal; + splitterRect.X = Location.X + SplitterDistanceInternal; } else { - splitterRect.X = this.Right - SplitterDistanceInternal - SplitterWidthInternal; + splitterRect.X = Right - SplitterDistanceInternal - SplitterWidthInternal; } } else { - splitterRect.Y = this.Location.Y + SplitterDistanceInternal; + splitterRect.Y = Location.Y + SplitterDistanceInternal; } } @@ -1732,7 +1732,7 @@ private void DrawSplitBar(int mode) private void DrawFocus(Graphics g, Rectangle r) { r.Inflate(-1, -1); - ControlPaint.DrawFocusRectangle(g, r, this.ForeColor, this.BackColor); + ControlPaint.DrawFocusRectangle(g, r, ForeColor, BackColor); } /// @@ -1743,7 +1743,7 @@ private void DrawSplitHelper(int splitSize) { Rectangle r = CalcSplitLine(splitSize, 3); - IntPtr parentHandle = this.Handle; + IntPtr parentHandle = Handle; IntPtr dc = UnsafeNativeMethods.GetDCEx(new HandleRef(this, parentHandle), NativeMethods.NullHandleRef, NativeMethods.DCX_CACHE | NativeMethods.DCX_LOCKWINDOWUPDATE); IntPtr halftone = ControlPaint.CreateHalftoneHBRUSH(); IntPtr saveBrush = SafeNativeMethods.SelectObject(new HandleRef(this, dc), new HandleRef(null, halftone)); @@ -1820,7 +1820,7 @@ private void RepaintSplitterRect() { if (IsHandleCreated) { - Graphics g = this.CreateGraphicsInternal(); + Graphics g = CreateGraphicsInternal(); if (BackgroundImage != null) { @@ -1831,7 +1831,7 @@ private void RepaintSplitterRect() } else { - using (SolidBrush solidBrush = new SolidBrush(this.BackColor)) + using (SolidBrush solidBrush = new SolidBrush(BackColor)) { g.FillRectangle(solidBrush, splitterRect); } @@ -1845,16 +1845,16 @@ private void SetSplitterRect(bool vertical) { if (vertical) { - splitterRect.X = ((RightToLeft == RightToLeft.Yes) ? this.Width - splitterDistance - SplitterWidthInternal : this.Location.X + splitterDistance); - splitterRect.Y = this.Location.Y; + splitterRect.X = ((RightToLeft == RightToLeft.Yes) ? Width - splitterDistance - SplitterWidthInternal : Location.X + splitterDistance); + splitterRect.Y = Location.Y; splitterRect.Width = SplitterWidthInternal; - splitterRect.Height = this.Height; + splitterRect.Height = Height; } else { - splitterRect.X = this.Location.X; - splitterRect.Y = this.Location.Y + SplitterDistanceInternal; - splitterRect.Width = this.Width; + splitterRect.X = Location.X; + splitterRect.Y = Location.Y + SplitterDistanceInternal; + splitterRect.Width = Width; splitterRect.Height = SplitterWidthInternal; } } @@ -1872,12 +1872,12 @@ private void ResizeSplitContainer() panel1.SuspendLayout(); panel2.SuspendLayout(); - if (this.Width == 0) + if (Width == 0) { // Set the correct Width iif the WIDTH has changed to ZERO. panel1.Size = new Size(0, panel1.Height); panel2.Size = new Size(0, panel2.Height); } - else if (this.Height == 0) + else if (Height == 0) { // Set the correct Height iif the HEIGHT has changed to ZERO. panel1.Size = new Size(panel1.Width, 0); panel2.Size = new Size(panel2.Width, 0); @@ -1889,23 +1889,23 @@ private void ResizeSplitContainer() // If no panel is collapsed then do the default ... if (!CollapsedMode) { - if (this.FixedPanel == FixedPanel.Panel1) + if (FixedPanel == FixedPanel.Panel1) { panel1.Size = new Size(panelSize, Height); panel2.Size = new Size(Math.Max(Width - panelSize - SplitterWidthInternal, Panel2MinSize), Height); } - if (this.FixedPanel == FixedPanel.Panel2) + if (FixedPanel == FixedPanel.Panel2) { panel2.Size = new Size(panelSize, Height); splitterDistance = Math.Max(Width - panelSize - SplitterWidthInternal, Panel1MinSize); panel1.WidthInternal = splitterDistance; panel1.HeightInternal = Height; } - if (this.FixedPanel == FixedPanel.None) + if (FixedPanel == FixedPanel.None) { if (ratioWidth != 0.0) { - splitterDistance = Math.Max((int)(Math.Floor(this.Width / ratioWidth)), Panel1MinSize); + splitterDistance = Math.Max((int)(Math.Floor(Width / ratioWidth)), Panel1MinSize); } panel1.WidthInternal = splitterDistance; //Default splitter distance from left or top. panel1.HeightInternal = Height; @@ -1926,12 +1926,12 @@ private void ResizeSplitContainer() { if (Panel1Collapsed) { - panel2.Size = this.Size; + panel2.Size = Size; panel2.Location = new Point(0, 0); } else if (Panel2Collapsed) { - panel1.Size = this.Size; + panel1.Size = Size; panel1.Location = new Point(0, 0); } } @@ -1942,7 +1942,7 @@ private void ResizeSplitContainer() // If no panel is collapsed then do the default ... if (!CollapsedMode) { - if (this.FixedPanel == FixedPanel.Panel1) + if (FixedPanel == FixedPanel.Panel1) { //Default splitter distance from left or top. @@ -1951,7 +1951,7 @@ private void ResizeSplitContainer() panel2.Size = new Size(Width, Math.Max(Height - panel2Start, Panel2MinSize)); panel2.Location = new Point(0, panel2Start); } - if (this.FixedPanel == FixedPanel.Panel2) + if (FixedPanel == FixedPanel.Panel2) { panel2.Size = new Size(Width, panelSize); @@ -1961,12 +1961,12 @@ private void ResizeSplitContainer() int panel2Start = splitterDistance + SplitterWidthInternal; panel2.Location = new Point(0, panel2Start); } - if (this.FixedPanel == FixedPanel.None) + if (FixedPanel == FixedPanel.None) { //NO PANEL FIXED !! if (ratioHeight != 0.0) { - splitterDistance = Math.Max((int)(Math.Floor(this.Height / ratioHeight)), Panel1MinSize); + splitterDistance = Math.Max((int)(Math.Floor(Height / ratioHeight)), Panel1MinSize); } panel1.HeightInternal = splitterDistance; //Default splitter distance from left or top. panel1.WidthInternal = Width; @@ -1983,12 +1983,12 @@ private void ResizeSplitContainer() { if (Panel1Collapsed) { - panel2.Size = this.Size; + panel2.Size = Size; panel2.Location = new Point(0, 0); } else if (Panel2Collapsed) { - panel1.Size = this.Size; + panel1.Size = Size; panel1.Location = new Point(0, 0); } } @@ -2051,7 +2051,7 @@ protected override void Select(bool directed, bool forward) return; } // continue selection iff panels have controls or tabstop is true. - if ((this.Panel1.Controls.Count > 0 || this.Panel2.Controls.Count > 0) || TabStop) + if ((Panel1.Controls.Count > 0 || Panel2.Controls.Count > 0) || TabStop) { SelectNextControlInContainer(this, forward, true, true, false); } @@ -2059,7 +2059,7 @@ protected override void Select(bool directed, bool forward) { //If this SplitContainer cannot be selected let the parent select the next in line try { - Control parent = this.ParentInternal; + Control parent = ParentInternal; selectNextControl = true; while (parent != null) { @@ -2127,11 +2127,11 @@ private bool SelectNextControlInContainer(Control ctl, bool forward, bool tabSto } } } while (ctl != null); - if (ctl != null && this.TabStop) + if (ctl != null && TabStop) { //we are on Splitter.....Focus it splitterFocused = true; - IContainerControl c = this.ParentInternal.GetContainerControl(); + IContainerControl c = ParentInternal.GetContainerControl(); if (c != null) { ContainerControl cc = c as ContainerControl; @@ -2154,7 +2154,7 @@ private bool SelectNextControlInContainer(Control ctl, bool forward, bool tabSto bool selected = SelectNextControlInPanel(ctl, forward, tabStopOnly, nested, wrap); if (!selected) { - Control parent = this.ParentInternal; + Control parent = ParentInternal; if (parent != null) { try @@ -2326,7 +2326,7 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound base.SetBoundsCore(x, y, width, height, specified); - SetSplitterRect(this.Orientation == Orientation.Vertical); + SetSplitterRect(Orientation == Orientation.Vertical); } /// @@ -2361,14 +2361,14 @@ private void SplitMove(int x, int y) { if (Orientation == Orientation.Vertical) { - if (size + SplitterWidthInternal <= this.Width - Panel2MinSize - BORDERSIZE) + if (size + SplitterWidthInternal <= Width - Panel2MinSize - BORDERSIZE) { splitterDistance = size - mod; } } else { - if (size + SplitterWidthInternal <= this.Height - Panel2MinSize - BORDERSIZE) + if (size + SplitterWidthInternal <= Height - Panel2MinSize - BORDERSIZE) { splitterDistance = size - mod; } @@ -2441,7 +2441,7 @@ private void UpdateSplitter() SetSplitterRect(true /*Vertical*/); if (!resizeCalled) { - ratioWidth = ((double)(this.Width) / (double)(panel1.Width) > 0) ? (double)(this.Width) / (double)(panel1.Width) : ratioWidth; + ratioWidth = ((double)(Width) / (double)(panel1.Width) > 0) ? (double)(Width) / (double)(panel1.Width) : ratioWidth; } @@ -2450,18 +2450,18 @@ private void UpdateSplitter() { if (Panel1Collapsed) { - panel2.Size = this.Size; + panel2.Size = Size; panel2.Location = new Point(0, 0); } else if (Panel2Collapsed) { - panel1.Size = this.Size; + panel1.Size = Size; panel1.Location = new Point(0, 0); } // Update Ratio when the splitContainer is in CollapsedMode. if (!resizeCalled) { - ratioWidth = ((double)(this.Width) / (double)(splitterDistance) > 0) ? (double)(this.Width) / (double)(splitterDistance) : ratioWidth; + ratioWidth = ((double)(Width) / (double)(splitterDistance) > 0) ? (double)(Width) / (double)(splitterDistance) : ratioWidth; } } } @@ -2483,26 +2483,26 @@ private void UpdateSplitter() if (!resizeCalled) { - ratioHeight = ((double)(this.Height) / (double)(panel1.Height) > 0) ? (double)(this.Height) / (double)(panel1.Height) : ratioHeight; + ratioHeight = ((double)(Height) / (double)(panel1.Height) > 0) ? (double)(Height) / (double)(panel1.Height) : ratioHeight; } } else { if (Panel1Collapsed) { - panel2.Size = this.Size; + panel2.Size = Size; panel2.Location = new Point(0, 0); } else if (Panel2Collapsed) { - panel1.Size = this.Size; + panel1.Size = Size; panel1.Location = new Point(0, 0); } // Update Ratio when the splitContainer is in CollapsedMode. if (!resizeCalled) { - ratioHeight = ((double)(this.Height) / (double)(splitterDistance) > 0) ? (double)(this.Height) / (double)(splitterDistance) : ratioHeight; + ratioHeight = ((double)(Height) / (double)(splitterDistance) > 0) ? (double)(Height) / (double)(splitterDistance) : ratioHeight; } } } @@ -2556,7 +2556,7 @@ internal override Rectangle GetToolNativeScreenRectangle() { // Return splitter rectangle instead of the whole container rectangle to be consistent with the mouse ToolTip Rectangle containerRectangle = base.GetToolNativeScreenRectangle(); - Rectangle splitterRectangle = this.SplitterRectangle; + Rectangle splitterRectangle = SplitterRectangle; return new Rectangle(containerRectangle.X + splitterRectangle.X, containerRectangle.Y + splitterRectangle.Y, splitterRectangle.Width, splitterRectangle.Height); } @@ -2647,7 +2647,7 @@ protected override bool ProcessTabKey(bool forward) { //We are om Splitter ...... splitterFocused = true; - IContainerControl c = this.ParentInternal.GetContainerControl(); + IContainerControl c = ParentInternal.GetContainerControl(); if (c != null) { ContainerControl cc = c as ContainerControl; @@ -2723,7 +2723,7 @@ private class SplitContainerMessageFilter : IMessageFilter public SplitContainerMessageFilter(SplitContainer splitContainer) { - this.owner = splitContainer; + owner = splitContainer; } /// @@ -2758,7 +2758,7 @@ internal class SplitContainerTypedControlCollection : WindowsFormsUtils.TypedCon public SplitContainerTypedControlCollection(Control c, Type type, bool isReadOnly) : base(c, type, isReadOnly) { - this.owner = c as SplitContainer; + owner = c as SplitContainer; } public override void Remove(Control value) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Splitter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Splitter.cs index 4ed7be4c2d7..7b33fee1bba 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Splitter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Splitter.cs @@ -1024,7 +1024,7 @@ private class SplitterMessageFilter : IMessageFilter public SplitterMessageFilter(Splitter splitter) { - this.owner = splitter; + owner = splitter; } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs index 2b5be175eea..5c59480e75f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs @@ -106,13 +106,13 @@ private int SizeGripWidth // gripper pane width... thisElement = VisualStyleElement.Status.GripperPane.Normal; vsRenderer.SetParameters(thisElement); - elementSize = vsRenderer.GetPartSize(Graphics.FromHwndInternal(this.Handle), ThemeSizeType.True); + elementSize = vsRenderer.GetPartSize(Graphics.FromHwndInternal(Handle), ThemeSizeType.True); sizeGripWidth = elementSize.Width; // ...plus gripper width thisElement = VisualStyleElement.Status.Gripper.Normal; vsRenderer.SetParameters(thisElement); - elementSize = vsRenderer.GetPartSize(Graphics.FromHwndInternal(this.Handle), ThemeSizeType.True); + elementSize = vsRenderer.GetPartSize(Graphics.FromHwndInternal(Handle), ThemeSizeType.True); sizeGripWidth += elementSize.Width; // Either GetPartSize could have returned a width of zero, so make sure we have a reasonable number: @@ -215,7 +215,7 @@ protected override CreateParams CreateParams CreateParams cp = base.CreateParams; cp.ClassName = NativeMethods.WC_STATUSBAR; - if (this.sizeGrip) + if (sizeGrip) { cp.Style |= NativeMethods.SBARS_SIZEGRIP; } @@ -573,7 +573,7 @@ public event StatusBarPanelClickEventHandler PanelClick /// internal bool ArePanelsRealized() { - return this.showPanels && IsHandleCreated; + return showPanels && IsHandleCreated; } /// @@ -595,7 +595,7 @@ private void ApplyPanelWidths() return; StatusBarPanel panel = null; - int length = this.panels.Count; + int length = panels.Count; if (length == 0) { @@ -616,7 +616,7 @@ private void ApplyPanelWidths() int currentOffset = 0; for (int i = 0; i < length; i++) { - panel = (StatusBarPanel)this.panels[i]; + panel = (StatusBarPanel)panels[i]; currentOffset += panel.Width; offsets2[i] = currentOffset; panel.Right = offsets2[i]; @@ -627,7 +627,7 @@ private void ApplyPanelWidths() // for (int i = 0; i < length; i++) { - panel = (StatusBarPanel)this.panels[i]; + panel = (StatusBarPanel)panels[i]; UpdateTooltip(panel); } @@ -707,7 +707,7 @@ protected override void OnHandleCreated(EventArgs e) tooltips = new ControlToolTip(this); } - if (!this.showPanels) + if (!showPanels) { SendMessage(NativeMethods.SB_SIMPLE, 1, 0); SetSimpleText(simpleText); @@ -789,7 +789,7 @@ protected virtual void OnPanelClick(StatusBarPanelClickEventArgs e) /// protected override void OnLayout(LayoutEventArgs levent) { - if (this.showPanels) + if (showPanels) { LayoutPanels(); if (IsHandleCreated && panelsRealized != panels.Count) @@ -807,7 +807,7 @@ protected override void OnLayout(LayoutEventArgs levent) internal void RealizePanels() { StatusBarPanel panel = null; - int length = this.panels.Count; + int length = panels.Count; int old = panelsRealized; panelsRealized = 0; @@ -820,7 +820,7 @@ internal void RealizePanels() int i; for (i = 0; i < length; i++) { - panel = (StatusBarPanel)this.panels[i]; + panel = (StatusBarPanel)panels[i]; try { panel.Realize(); @@ -841,16 +841,16 @@ internal void RealizePanels() /// internal void RemoveAllPanelsWithoutUpdate() { - int size = this.panels.Count; + int size = panels.Count; // remove the parent reference for (int i = 0; i < size; i++) { - StatusBarPanel sbp = (StatusBarPanel)this.panels[i]; + StatusBarPanel sbp = (StatusBarPanel)panels[i]; sbp.ParentInternal = null; } - this.panels.Clear(); - if (this.showPanels == true) + panels.Clear(); + if (showPanels == true) { ApplyPanelWidths(); ForcePanelUpdate(); @@ -910,12 +910,12 @@ private void LayoutPanels() StatusBarPanel panel = null; int barPanelWidth = 0; int springNum = 0; - StatusBarPanel[] pArray = new StatusBarPanel[this.panels.Count]; + StatusBarPanel[] pArray = new StatusBarPanel[panels.Count]; bool changed = false; for (int i = 0; i < pArray.Length; i++) { - panel = (StatusBarPanel)this.panels[i]; + panel = (StatusBarPanel)panels[i]; if (panel.AutoSize == StatusBarPanelAutoSize.Spring) { pArray[springNum] = panel; @@ -1025,7 +1025,7 @@ public override string ToString() //call this when System.Windows.forms.toolTip is Associated with Statusbar.... internal void SetToolTip(ToolTip t) { - this.mainToolTip = t; + mainToolTip = t; toolTipSet = true; } @@ -1080,18 +1080,18 @@ private void WmDrawItem(ref Message m) { NativeMethods.DRAWITEMSTRUCT dis = (NativeMethods.DRAWITEMSTRUCT)m.GetLParam(typeof(NativeMethods.DRAWITEMSTRUCT)); - int length = this.panels.Count; + int length = panels.Count; if (dis.itemID < 0 || dis.itemID >= length) Debug.Fail("OwnerDraw item out of range"); StatusBarPanel panel = (StatusBarPanel) - this.panels[dis.itemID]; + panels[dis.itemID]; Graphics g = Graphics.FromHdcInternal(dis.hDC); Rectangle r = Rectangle.FromLTRB(dis.rcItem.left, dis.rcItem.top, dis.rcItem.right, dis.rcItem.bottom); //The itemstate is not defined for a statusbar control - OnDrawItem(new StatusBarDrawItemEventArgs(g, Font, r, dis.itemID, DrawItemState.None, panel, this.ForeColor, this.BackColor)); + OnDrawItem(new StatusBarDrawItemEventArgs(g, Font, r, dis.itemID, DrawItemState.None, panel, ForeColor, BackColor)); g.Dispose(); } @@ -1543,7 +1543,7 @@ public virtual int IndexOfKey(string key) } // step 2 - search for the item - for (int i = 0; i < this.Count; i++) + for (int i = 0; i < Count; i++) { if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { @@ -1615,7 +1615,7 @@ void IList.Insert(int index, object value) /// private bool IsValidIndex(int index) { - return ((index >= 0) && (index < this.Count)); + return ((index >= 0) && (index < Count)); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/StatusBarPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/StatusBarPanel.cs index 62449f78cfa..d46e7e0822d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/StatusBarPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/StatusBarPanel.cs @@ -119,7 +119,7 @@ public StatusBarPanelAutoSize AutoSize { get { - return this.autoSize; + return autoSize; } set @@ -129,9 +129,9 @@ public StatusBarPanelAutoSize AutoSize { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(StatusBarPanelAutoSize)); } - if (this.autoSize != value) + if (autoSize != value) { - this.autoSize = value; + autoSize = value; UpdateSize(); } } @@ -166,12 +166,12 @@ public StatusBarPanelBorderStyle BorderStyle { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(StatusBarPanelBorderStyle)); } - if (this.borderStyle != value) + if (borderStyle != value) { - this.borderStyle = value; + borderStyle = value; Realize(); if (Created) - this.parent.Invalidate(); + parent.Invalidate(); } } } @@ -182,7 +182,7 @@ internal bool Created { get { - return this.parent != null && this.parent.ArePanelsRealized(); + return parent != null && parent.ArePanelsRealized(); } } @@ -205,7 +205,7 @@ public Icon Icon get { // unfortunately we have no way of getting the icon from the control. - return this.icon; + return icon; } @@ -214,23 +214,23 @@ public Icon Icon if (value != null && (((Icon)value).Height > SystemInformation.SmallIconSize.Height || ((Icon)value).Width > SystemInformation.SmallIconSize.Width)) { - this.icon = new Icon(value, SystemInformation.SmallIconSize); + icon = new Icon(value, SystemInformation.SmallIconSize); } else { - this.icon = value; + icon = value; } if (Created) { - IntPtr handle = (this.icon == null) ? IntPtr.Zero : this.icon.Handle; - this.parent.SendMessage(NativeMethods.SB_SETICON, (IntPtr)GetIndex(), handle); + IntPtr handle = (icon == null) ? IntPtr.Zero : icon.Handle; + parent.SendMessage(NativeMethods.SB_SETICON, (IntPtr)GetIndex(), handle); } UpdateSize(); if (Created) { - this.parent.Invalidate(); + parent.Invalidate(); } } } @@ -269,7 +269,7 @@ public int MinWidth { get { - return this.minWidth; + return minWidth; } set { @@ -278,12 +278,12 @@ public int MinWidth throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(MinWidth), value, 0)); } - if (value != this.minWidth) + if (value != minWidth) { - this.minWidth = value; + minWidth = value; UpdateSize(); - if (this.minWidth > this.Width) + if (minWidth > Width) { Width = value; } @@ -385,13 +385,13 @@ public StatusBarPanelStyle Style { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(StatusBarPanelStyle)); } - if (this.style != value) + if (style != value) { - this.style = value; + style = value; Realize(); if (Created) { - this.parent.Invalidate(); + parent.Invalidate(); } } } @@ -453,11 +453,11 @@ public string Text if (value.Length == 0) { - this.text = null; + text = null; } else { - this.text = value; + text = value; } Realize(); UpdateSize(); @@ -481,13 +481,13 @@ public string ToolTipText { get { - if (this.toolTipText == null) + if (toolTipText == null) { return ""; } else { - return this.toolTipText; + return toolTipText; } } set @@ -502,11 +502,11 @@ public string ToolTipText if (value.Length == 0) { - this.toolTipText = null; + toolTipText = null; } else { - this.toolTipText = value; + toolTipText = value; } if (Created) @@ -534,14 +534,14 @@ public int Width { get { - return this.width; + return width; } set { - if (!initializing && value < this.minWidth) + if (!initializing && value < minWidth) throw new ArgumentOutOfRangeException(nameof(Width), SR.WidthGreaterThanMinWidth); - this.width = value; + width = value; UpdateSize(); } } @@ -601,11 +601,11 @@ internal int GetContentsWidth(bool newPanel) else text = Text; - Graphics g = this.parent.CreateGraphicsInternal(); + Graphics g = parent.CreateGraphicsInternal(); Size sz = Size.Ceiling(g.MeasureString(text, parent.Font)); - if (this.icon != null) + if (icon != null) { - sz.Width += this.icon.Size.Width + 5; + sz.Width += icon.Size.Width + 5; } g.Dispose(); @@ -702,13 +702,13 @@ internal void Realize() if (result == 0) throw new InvalidOperationException(SR.UnableToSetPanelText); - if (this.icon != null && style != StatusBarPanelStyle.OwnerDraw) + if (icon != null && style != StatusBarPanelStyle.OwnerDraw) { - this.parent.SendMessage(NativeMethods.SB_SETICON, (IntPtr)GetIndex(), this.icon.Handle); + parent.SendMessage(NativeMethods.SB_SETICON, (IntPtr)GetIndex(), icon.Handle); } else { - this.parent.SendMessage(NativeMethods.SB_SETICON, (IntPtr)GetIndex(), IntPtr.Zero); + parent.SendMessage(NativeMethods.SB_SETICON, (IntPtr)GetIndex(), IntPtr.Zero); } if (style == StatusBarPanelStyle.OwnerDraw) @@ -718,7 +718,7 @@ internal void Realize() if (result != 0) { - this.parent.Invalidate(Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom)); + parent.Invalidate(Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom)); } } } @@ -726,7 +726,7 @@ internal void Realize() private void UpdateSize() { - if (this.autoSize == StatusBarPanelAutoSize.Contents) + if (autoSize == StatusBarPanelAutoSize.Contents) { ApplyContentSizing(); } @@ -742,13 +742,13 @@ private void UpdateSize() private void ApplyContentSizing() { - if (this.autoSize == StatusBarPanelAutoSize.Contents && + if (autoSize == StatusBarPanelAutoSize.Contents && parent != null) { int newWidth = GetContentsWidth(false); - if (newWidth != this.Width) + if (newWidth != Width) { - this.Width = newWidth; + Width = newWidth; if (Created) { parent.DirtyLayout(); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/StatusStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/StatusStrip.cs index ef0b0c2f348..f67c9b2945a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/StatusStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/StatusStrip.cs @@ -38,13 +38,13 @@ public class StatusStrip : ToolStrip public StatusStrip() { SuspendLayout(); - this.CanOverflow = false; - this.LayoutStyle = ToolStripLayoutStyle.Table; - this.RenderMode = ToolStripRenderMode.System; - this.GripStyle = ToolStripGripStyle.Hidden; + CanOverflow = false; + LayoutStyle = ToolStripLayoutStyle.Table; + RenderMode = ToolStripRenderMode.System; + GripStyle = ToolStripGripStyle.Hidden; SetStyle(ControlStyles.ResizeRedraw, true); - this.Stretch = true; + Stretch = true; state[stateSizingGrip] = true; ResumeLayout(true); @@ -257,7 +257,7 @@ public Rectangle SizeGripBounds { if (SizingGrip) { - Size statusStripSize = this.Size; + Size statusStripSize = Size; // we cant necessarily make this the height of the status strip, as // the orientation could change. int gripHeight = Math.Min(DefaultSize.Height, statusStripSize.Height); @@ -294,7 +294,7 @@ public Rectangle SizeGripBounds private TableLayoutSettings TableLayoutSettings { - get { return this.LayoutSettings as TableLayoutSettings; } + get { return LayoutSettings as TableLayoutSettings; } } protected override AccessibleObject CreateAccessibilityInstance() @@ -326,9 +326,9 @@ private void EnsureRightToLeftGrip() if (SizingGrip && RightToLeft == RightToLeft.Yes) { RTLGrip.Bounds = SizeGripBounds; - if (!this.Controls.Contains(RTLGrip)) + if (!Controls.Contains(RTLGrip)) { - WindowsFormsUtils.ReadOnlyControlCollection controlCollection = this.Controls as WindowsFormsUtils.ReadOnlyControlCollection; + WindowsFormsUtils.ReadOnlyControlCollection controlCollection = Controls as WindowsFormsUtils.ReadOnlyControlCollection; if (controlCollection != null) { @@ -338,9 +338,9 @@ private void EnsureRightToLeftGrip() } else if (rtlLayoutGrip != null) { - if (this.Controls.Contains(rtlLayoutGrip)) + if (Controls.Contains(rtlLayoutGrip)) { - WindowsFormsUtils.ReadOnlyControlCollection controlCollection = this.Controls as WindowsFormsUtils.ReadOnlyControlCollection; + WindowsFormsUtils.ReadOnlyControlCollection controlCollection = Controls as WindowsFormsUtils.ReadOnlyControlCollection; if (controlCollection != null) { @@ -402,7 +402,7 @@ protected override void OnLayout(LayoutEventArgs levent) } - if (this.LayoutStyle == ToolStripLayoutStyle.Table) + if (LayoutStyle == ToolStripLayoutStyle.Table) { OnSpringTableLayoutCore(); } @@ -414,7 +414,7 @@ protected override void OnLayout(LayoutEventArgs levent) // the SpringTableLayoutCore requires the count of displayed items to // be accurate. // - so we need to perform layout again. - if (this.LayoutStyle == ToolStripLayoutStyle.Table) + if (LayoutStyle == ToolStripLayoutStyle.Table) { OnSpringTableLayoutCore(); base.OnLayout(levent); @@ -517,15 +517,15 @@ internal override bool ShouldSerializeRenderMode() /// protected virtual void OnSpringTableLayoutCore() { - if (this.LayoutStyle == ToolStripLayoutStyle.Table) + if (LayoutStyle == ToolStripLayoutStyle.Table) { state[stateCalledSpringTableLayout] = true; - this.SuspendLayout(); + SuspendLayout(); if (lastOrientation != Orientation) { - TableLayoutSettings settings = this.TableLayoutSettings; + TableLayoutSettings settings = TableLayoutSettings; settings.RowCount = 0; settings.ColumnCount = 0; settings.ColumnStyles.Clear(); @@ -541,15 +541,15 @@ protected virtual void OnSpringTableLayoutCore() // TableLayoutSettings.GrowStyle = TableLayoutPanelGrowStyle.AddColumns; - int originalColumnCount = this.TableLayoutSettings.ColumnStyles.Count; + int originalColumnCount = TableLayoutSettings.ColumnStyles.Count; // iterate through the elements which are going to be displayed. - for (int i = 0; i < this.DisplayedItems.Count; i++) + for (int i = 0; i < DisplayedItems.Count; i++) { if (i >= originalColumnCount) { // add if it's necessary. - this.TableLayoutSettings.ColumnStyles.Add(new ColumnStyle()); + TableLayoutSettings.ColumnStyles.Add(new ColumnStyle()); } // determine if we "spring" or "autosize" the column @@ -558,7 +558,7 @@ protected virtual void OnSpringTableLayoutCore() DisplayedItems[i].Anchor = (spring) ? AllAnchor : VerticalAnchor; // spring is achieved by using 100% as the column style - ColumnStyle colStyle = this.TableLayoutSettings.ColumnStyles[i]; + ColumnStyle colStyle = TableLayoutSettings.ColumnStyles[i]; colStyle.Width = 100; // this width is ignored in AutoSize. colStyle.SizeType = (spring) ? SizeType.Percent : SizeType.AutoSize; } @@ -571,13 +571,13 @@ protected virtual void OnSpringTableLayoutCore() TableLayoutSettings.RowCount = 1; TableLayoutSettings.RowStyles[0].SizeType = SizeType.Absolute; - TableLayoutSettings.RowStyles[0].Height = Math.Max(0, this.DisplayRectangle.Height); + TableLayoutSettings.RowStyles[0].Height = Math.Max(0, DisplayRectangle.Height); TableLayoutSettings.ColumnCount = DisplayedItems.Count + 1; // add an extra cell so it fills the remaining space // dont remove the extra column styles, just set them back to autosize. for (int i = DisplayedItems.Count; i < TableLayoutSettings.ColumnStyles.Count; i++) { - this.TableLayoutSettings.ColumnStyles[i].SizeType = SizeType.AutoSize; + TableLayoutSettings.ColumnStyles[i].SizeType = SizeType.AutoSize; } } else @@ -588,15 +588,15 @@ protected virtual void OnSpringTableLayoutCore() TableLayoutSettings.GrowStyle = TableLayoutPanelGrowStyle.AddRows; - int originalRowCount = this.TableLayoutSettings.RowStyles.Count; + int originalRowCount = TableLayoutSettings.RowStyles.Count; // iterate through the elements which are going to be displayed. - for (int i = 0; i < this.DisplayedItems.Count; i++) + for (int i = 0; i < DisplayedItems.Count; i++) { if (i >= originalRowCount) { // add if it's necessary. - this.TableLayoutSettings.RowStyles.Add(new RowStyle()); + TableLayoutSettings.RowStyles.Add(new RowStyle()); } // determine if we "spring" or "autosize" the row @@ -605,7 +605,7 @@ protected virtual void OnSpringTableLayoutCore() DisplayedItems[i].Anchor = (spring) ? AllAnchor : HorizontalAnchor; // spring is achieved by using 100% as the row style - RowStyle rowStyle = this.TableLayoutSettings.RowStyles[i]; + RowStyle rowStyle = TableLayoutSettings.RowStyles[i]; rowStyle.Height = 100; // this width is ignored in AutoSize. rowStyle.SizeType = (spring) ? SizeType.Percent : SizeType.AutoSize; } @@ -619,19 +619,19 @@ protected virtual void OnSpringTableLayoutCore() TableLayoutSettings.ColumnCount = 1; TableLayoutSettings.ColumnStyles[0].SizeType = SizeType.Absolute; - TableLayoutSettings.ColumnStyles[0].Width = Math.Max(0, this.DisplayRectangle.Width); + TableLayoutSettings.ColumnStyles[0].Width = Math.Max(0, DisplayRectangle.Width); TableLayoutSettings.RowCount = DisplayedItems.Count + 1; // add an extra cell so it fills the remaining space // dont remove the extra column styles, just set them back to autosize. for (int i = DisplayedItems.Count; i < TableLayoutSettings.RowStyles.Count; i++) { - this.TableLayoutSettings.RowStyles[i].SizeType = SizeType.AutoSize; + TableLayoutSettings.RowStyles[i].SizeType = SizeType.AutoSize; } } - this.ResumeLayout(false); + ResumeLayout(false); } } @@ -669,7 +669,7 @@ protected override void WndProc(ref Message m) { gripLocation = new NativeMethods.POINT(SizeGripBounds.Right, SizeGripBounds.Bottom); } - UnsafeNativeMethods.MapWindowPoints(new HandleRef(this, this.Handle), rootHwnd, gripLocation, 1); + UnsafeNativeMethods.MapWindowPoints(new HandleRef(this, Handle), rootHwnd, gripLocation, 1); int deltaBottomEdge = Math.Abs(rootHwndClientArea.bottom - gripLocation.y); int deltaRightEdge = Math.Abs(rootHwndClientArea.right - gripLocation.x); @@ -697,7 +697,7 @@ private class RightToLeftLayoutGrip : Control public RightToLeftLayoutGrip() { SetStyle(ControlStyles.SupportsTransparentBackColor, true); - this.BackColor = Color.Transparent; + BackColor = Color.Transparent; } protected override CreateParams CreateParams { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/StringSorter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/StringSorter.cs index 710823f52c0..7be7262dfb9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/StringSorter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/StringSorter.cs @@ -111,9 +111,9 @@ private StringSorter(CultureInfo culture, string[] keys, object[] items, int opt } this.keys = keys; this.items = items; - this.lcid = culture == null ? SafeNativeMethods.GetThreadLocale() : culture.LCID; + lcid = culture == null ? SafeNativeMethods.GetThreadLocale() : culture.LCID; this.options = options & CompareOptions; - this.descending = (options & Descending) != 0; + descending = (options & Descending) != 0; } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/StringSource.cs b/src/System.Windows.Forms/src/System/Windows/Forms/StringSource.cs index 630dfeb2d2d..ef155dc934b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/StringSource.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/StringSource.cs @@ -97,7 +97,7 @@ public void RefreshList(string[] newSource) if (strings != null) { - this.strings = newSource; + strings = newSource; } current = 0; size = (strings == null) ? 0 : strings.Length; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs index 988202f9324..9067ef29fc9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs @@ -138,7 +138,7 @@ public TabAlignment Alignment set { - if (this.alignment != value) + if (alignment != value) { //valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(value, (int)value, (int)TabAlignment.Top, (int)TabAlignment.Right)) @@ -146,8 +146,8 @@ public TabAlignment Alignment throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(TabAlignment)); } - this.alignment = value; - if (this.alignment == TabAlignment.Left || this.alignment == TabAlignment.Right) + alignment = value; + if (alignment == TabAlignment.Left || alignment == TabAlignment.Right) Multiline = true; RecreateHandle(); } @@ -182,7 +182,7 @@ public TabAppearance Appearance set { - if (this.appearance != value) + if (appearance != value) { //valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)TabAppearance.Normal, (int)TabAppearance.FlatButtons)) @@ -190,7 +190,7 @@ public TabAppearance Appearance throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(TabAppearance)); } - this.appearance = value; + appearance = value; RecreateHandle(); //Fire OnStyleChanged(EventArgs.Empty) here since we are no longer calling UpdateStyles( ) but always reCreating the Handle. @@ -425,7 +425,7 @@ public override Rectangle DisplayRectangle Rectangle r = Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom); - Point p = this.Location; + Point p = Location; r.X -= p.X; r.Y -= p.Y; @@ -512,7 +512,7 @@ public ImageList ImageList } set { - if (this.imageList != value) + if (imageList != value) { EventHandler recreateHandler = new EventHandler(ImageListRecreateHandle); EventHandler disposedHandler = new EventHandler(DetachImageList); @@ -523,7 +523,7 @@ public ImageList ImageList imageList.Disposed -= disposedHandler; } - this.imageList = value; + imageList = value; IntPtr handle = (value != null) ? value.Handle : IntPtr.Zero; if (IsHandleCreated) SendMessage(NativeMethods.TCM_SETIMAGELIST, IntPtr.Zero, handle); @@ -633,8 +633,8 @@ public bool Multiline if (Multiline != value) { tabControlState[TABCONTROLSTATE_multiline] = value; - if (Multiline == false && (this.alignment == TabAlignment.Left || this.alignment == TabAlignment.Right)) - this.alignment = TabAlignment.Top; + if (Multiline == false && (alignment == TabAlignment.Left || alignment == TabAlignment.Right)) + alignment = TabAlignment.Top; RecreateHandle(); } } @@ -1180,7 +1180,7 @@ protected override void Dispose(bool disposing) { if (imageList != null) { - imageList.Disposed -= new EventHandler(this.DetachImageList); + imageList.Disposed -= new EventHandler(DetachImageList); } } base.Dispose(disposing); @@ -1367,7 +1367,7 @@ protected override void OnHandleCreated(EventArgs e) { //Add the handle to hashtable for Ids .. - NativeWindow.AddWindowToIDTable(this, this.Handle); + NativeWindow.AddWindowToIDTable(this, Handle); handleInTable = true; // Set the padding BEFORE setting the control's font (as done @@ -1439,7 +1439,7 @@ protected override void OnHandleDestroyed(EventArgs e) if (handleInTable) { handleInTable = false; - NativeWindow.RemoveWindowFromIDTable(this.Handle); + NativeWindow.RemoveWindowFromIDTable(Handle); } base.OnHandleDestroyed(e); @@ -1532,14 +1532,14 @@ internal override void OnParentHandleRecreated() { // Avoid temporarily resizing the TabControl while the parent // recreates its handle to avoid - this.skipUpdateSize = true; + skipUpdateSize = true; try { base.OnParentHandleRecreated(); } finally { - this.skipUpdateSize = false; + skipUpdateSize = false; } } @@ -1668,7 +1668,7 @@ protected override bool ProcessKeyPreview(ref Message m) /// internal void UpdateSize() { - if (this.skipUpdateSize) + if (skipUpdateSize) { return; } @@ -1731,7 +1731,7 @@ internal override void RecreateHandleCore() protected void RemoveAll() { - this.Controls.Clear(); + Controls.Clear(); SendMessage(NativeMethods.TCM_DELETEALLITEMS, 0, 0); tabPages = null; @@ -1783,7 +1783,7 @@ private void ResizePages() /// internal void SetToolTip(ToolTip toolTip, string controlToolTipText) { - UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.TCM_SETTOOLTIPS, new HandleRef(toolTip, toolTip.Handle), 0); + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TCM_SETTOOLTIPS, new HandleRef(toolTip, toolTip.Handle), 0); controlTipText = controlToolTipText; } @@ -2117,11 +2117,11 @@ private void WmReflectDrawItem(ref Message m) /// private bool WmSelChange() { - TabControlCancelEventArgs tcc = new TabControlCancelEventArgs(this.SelectedTab, this.SelectedIndex, false, TabControlAction.Selecting); + TabControlCancelEventArgs tcc = new TabControlCancelEventArgs(SelectedTab, SelectedIndex, false, TabControlAction.Selecting); OnSelecting(tcc); if (!tcc.Cancel) { - OnSelected(new TabControlEventArgs(this.SelectedTab, this.SelectedIndex, TabControlAction.Selected)); + OnSelected(new TabControlEventArgs(SelectedTab, SelectedIndex, TabControlAction.Selected)); OnSelectedIndexChanged(EventArgs.Empty); } else @@ -2154,11 +2154,11 @@ private bool WmSelChanging() // if 'cancelled' return from here else.. // fire Deselected. lastSelection = SelectedIndex; - TabControlCancelEventArgs tcc = new TabControlCancelEventArgs(this.SelectedTab, this.SelectedIndex, false, TabControlAction.Deselecting); + TabControlCancelEventArgs tcc = new TabControlCancelEventArgs(SelectedTab, SelectedIndex, false, TabControlAction.Deselecting); OnDeselecting(tcc); if (!tcc.Cancel) { - OnDeselected(new TabControlEventArgs(this.SelectedTab, this.SelectedIndex, TabControlAction.Deselected)); + OnDeselected(new TabControlEventArgs(SelectedTab, SelectedIndex, TabControlAction.Deselected)); } return tcc.Cancel; @@ -2555,7 +2555,7 @@ public virtual int IndexOfKey(string key) } // step 2 - search for the item - for (int i = 0; i < this.Count; i++) + for (int i = 0; i < Count; i++) { if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { @@ -2651,7 +2651,7 @@ public void Insert(int index, string key, string text, string imageKey) /// private bool IsValidIndex(int index) { - return ((index >= 0) && (index < this.Count)); + return ((index >= 0) && (index < Count)); } public virtual void Clear() diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TabPage.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TabPage.cs index ec01857001a..bfae3970a73 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TabPage.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TabPage.cs @@ -200,10 +200,10 @@ public int ImageIndex if (parent != null) { - this.ImageIndexer.ImageList = parent.ImageList; + ImageIndexer.ImageList = parent.ImageList; } - this.ImageIndexer.Index = value; + ImageIndexer.Index = value; UpdateParent(); } } @@ -228,13 +228,13 @@ public string ImageKey } set { - this.ImageIndexer.Key = value; + ImageIndexer.Key = value; TabControl parent = ParentInternal as TabControl; if (parent != null) { - this.ImageIndexer.ImageList = parent.ImageList; + ImageIndexer.ImageList = parent.ImageList; } UpdateParent(); @@ -316,7 +316,7 @@ public bool UseVisualStyleBackColor set { useVisualStyleBackColor = value; - this.Invalidate(true); + Invalidate(true); } } @@ -693,7 +693,7 @@ protected override void OnPaintBackground(PaintEventArgs e) if (Application.RenderWithVisualStyles && UseVisualStyleBackColor && (parent != null && parent.Appearance == TabAppearance.Normal)) { - Color bkcolor = UseVisualStyleBackColor ? Color.Transparent : this.BackColor; + Color bkcolor = UseVisualStyleBackColor ? Color.Transparent : BackColor; Rectangle inflateRect = LayoutUtils.InflateRect(DisplayRectangle, Padding); @@ -714,7 +714,7 @@ protected override void OnPaintBackground(PaintEventArgs e) // Is there a background image to paint? The TabRenderer does not currently support // painting the background image on the panel, so we need to draw it ourselves. - if (this.BackgroundImage != null) + if (BackgroundImage != null) { ControlPaint.DrawBackgroundImage(e.Graphics, BackgroundImage, bkcolor, BackgroundImageLayout, inflateRect, inflateRect, DisplayRectangle.Location); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanel.cs index e09b28789cc..13643a67dd3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanel.cs @@ -111,7 +111,7 @@ public TableLayoutPanelCellBorderStyle CellBorderStyle { SetStyle(ControlStyles.ResizeRedraw, true); } - this.Invalidate(); + Invalidate(); Debug.Assert(CellBorderStyle == value, "CellBorderStyle should be the same as we set it"); } } @@ -215,7 +215,7 @@ protected override Control.ControlCollection CreateControlsInstance() private bool ShouldSerializeControls() { - TableLayoutControlCollection collection = this.Controls; + TableLayoutControlCollection collection = Controls; return collection != null && collection.Count > 0; } @@ -387,7 +387,7 @@ public event TableLayoutCellPaintEventHandler CellPaint protected override void OnLayout(LayoutEventArgs levent) { base.OnLayout(levent); - this.Invalidate(); + Invalidate(); } @@ -408,11 +408,11 @@ protected override void OnPaintBackground(PaintEventArgs e) // paint borderstyles on top of the background image in WM_ERASEBKGND - int cellBorderWidth = this.CellBorderWidth; + int cellBorderWidth = CellBorderWidth; TableLayout.ContainerInfo containerInfo = TableLayout.GetContainerInfo(this); TableLayout.Strip[] colStrips = containerInfo.Columns; TableLayout.Strip[] rowStrips = containerInfo.Rows; - TableLayoutPanelCellBorderStyle cellBorderStyle = this.CellBorderStyle; + TableLayoutPanelCellBorderStyle cellBorderStyle = CellBorderStyle; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettings.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettings.cs index 8b0528955f5..426742ea478 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettings.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettings.cs @@ -58,7 +58,7 @@ internal TableLayoutSettings(SerializationInfo serializationInfo, StreamingConte TableLayoutSettings tls = converter.ConvertFromInvariantString(stringVal) as TableLayoutSettings; if (tls != null) { - this.ApplySettings(tls); + ApplySettings(tls); } } } @@ -70,7 +70,7 @@ public override LayoutEngine LayoutEngine private TableLayout TableLayout { - get { return (TableLayout)this.LayoutEngine; } + get { return (TableLayout)LayoutEngine; } } @@ -863,14 +863,14 @@ public ColumnStyle() { } public ColumnStyle(SizeType sizeType) { - this.SizeType = sizeType; + SizeType = sizeType; } public ColumnStyle(SizeType sizeType, float width) { - this.SizeType = sizeType; - this.Width = width; + SizeType = sizeType; + Width = width; } @@ -890,14 +890,14 @@ public RowStyle() { } public RowStyle(SizeType sizeType) { - this.SizeType = sizeType; + SizeType = sizeType; } public RowStyle(SizeType sizeType, float height) { - this.SizeType = sizeType; - this.Height = height; + SizeType = sizeType; + Height = height; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TextBox.cs index d3ec809a52c..715023595b7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TextBox.cs @@ -221,7 +221,7 @@ public AutoCompleteStringCollection AutoCompleteCustomSource if (autoCompleteCustomSource == null) { autoCompleteCustomSource = new AutoCompleteStringCollection(); - autoCompleteCustomSource.CollectionChanged += new CollectionChangeEventHandler(this.OnAutoCompleteCustomSourceChanged); + autoCompleteCustomSource.CollectionChanged += new CollectionChangeEventHandler(OnAutoCompleteCustomSourceChanged); } return autoCompleteCustomSource; } @@ -231,14 +231,14 @@ public AutoCompleteStringCollection AutoCompleteCustomSource { if (autoCompleteCustomSource != null) { - autoCompleteCustomSource.CollectionChanged -= new CollectionChangeEventHandler(this.OnAutoCompleteCustomSourceChanged); + autoCompleteCustomSource.CollectionChanged -= new CollectionChangeEventHandler(OnAutoCompleteCustomSourceChanged); } autoCompleteCustomSource = value; if (value != null) { - autoCompleteCustomSource.CollectionChanged += new CollectionChangeEventHandler(this.OnAutoCompleteCustomSourceChanged); + autoCompleteCustomSource.CollectionChanged += new CollectionChangeEventHandler(OnAutoCompleteCustomSourceChanged); } SetAutoComplete(false); } @@ -307,7 +307,7 @@ internal override bool PasswordProtect { get { - return this.PasswordChar != '\0'; + return PasswordChar != '\0'; } } @@ -593,7 +593,7 @@ protected override void Dispose(bool disposing) ResetAutoComplete(true); if (autoCompleteCustomSource != null) { - autoCompleteCustomSource.CollectionChanged -= new CollectionChangeEventHandler(this.OnAutoCompleteCustomSourceChanged); + autoCompleteCustomSource.CollectionChanged -= new CollectionChangeEventHandler(OnAutoCompleteCustomSourceChanged); } if (stringSource != null) { @@ -635,16 +635,16 @@ protected override void OnBackColorChanged(EventArgs e) { base.OnBackColorChanged(e); // Force repainting of the entire window frame - if (Application.RenderWithVisualStyles && this.IsHandleCreated && this.BorderStyle == BorderStyle.Fixed3D) + if (Application.RenderWithVisualStyles && IsHandleCreated && BorderStyle == BorderStyle.Fixed3D) { - SafeNativeMethods.RedrawWindow(new HandleRef(this, this.Handle), null, NativeMethods.NullHandleRef, NativeMethods.RDW_INVALIDATE | NativeMethods.RDW_FRAME); + SafeNativeMethods.RedrawWindow(new HandleRef(this, Handle), null, NativeMethods.NullHandleRef, NativeMethods.RDW_INVALIDATE | NativeMethods.RDW_FRAME); } } protected override void OnFontChanged(EventArgs e) { base.OnFontChanged(e); - if (this.AutoCompleteMode != AutoCompleteMode.None) + if (AutoCompleteMode != AutoCompleteMode.None) { //we always will recreate the handle when autocomplete mode is on RecreateHandle(); @@ -741,8 +741,8 @@ protected virtual void OnTextAlignChanged(EventArgs e) protected override bool ProcessCmdKey(ref Message m, Keys keyData) { bool returnValue = base.ProcessCmdKey(ref m, keyData); - if (!returnValue && this.Multiline && !LocalAppContextSwitches.DoNotSupportSelectAllShortcutInMultilineTextBox - && this.ShortcutsEnabled && (keyData == (Keys.Control | Keys.A))) + if (!returnValue && Multiline && !LocalAppContextSwitches.DoNotSupportSelectAllShortcutInMultilineTextBox + && ShortcutsEnabled && (keyData == (Keys.Control | Keys.A))) { SelectAll(); return true; @@ -803,7 +803,7 @@ internal void SetAutoComplete(bool reset) { //RecreateHandle to avoid Leak. // notice the use of member variable to avoid re-entrancy - AutoCompleteMode backUpMode = this.AutoCompleteMode; + AutoCompleteMode backUpMode = AutoCompleteMode; autoCompleteMode = AutoCompleteMode.None; RecreateHandle(); autoCompleteMode = backUpMode; @@ -884,11 +884,11 @@ private void ResetAutoCompleteCustomSource() private void WmPrint(ref Message m) { base.WndProc(ref m); - if ((NativeMethods.PRF_NONCLIENT & (int)m.LParam) != 0 && Application.RenderWithVisualStyles && this.BorderStyle == BorderStyle.Fixed3D) + if ((NativeMethods.PRF_NONCLIENT & (int)m.LParam) != 0 && Application.RenderWithVisualStyles && BorderStyle == BorderStyle.Fixed3D) { using (Graphics g = Graphics.FromHdc(m.WParam)) { - Rectangle rect = new Rectangle(0, 0, this.Size.Width - 1, this.Size.Height - 1); + Rectangle rect = new Rectangle(0, 0, Size.Width - 1, Size.Height - 1); using (Pen pen = new Pen(VisualStyleInformation.TextControlBorder)) { g.DrawRectangle(pen, rect); @@ -1011,11 +1011,11 @@ protected override void WndProc(ref Message m) } if ((m.Msg == Interop.WindowMessages.WM_PAINT || m.Msg == Interop.WindowMessages.WM_KILLFOCUS) && - !this.GetStyle(ControlStyles.UserPaint) && - string.IsNullOrEmpty(this.Text) && - !this.Focused) + !GetStyle(ControlStyles.UserPaint) && + string.IsNullOrEmpty(Text) && + !Focused) { - using (Graphics g = this.CreateGraphics()) + using (Graphics g = CreateGraphics()) { DrawPlaceholderText(g); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxBase.cs index 1f863c0fca6..a4a9acde91a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxBase.cs @@ -317,7 +317,7 @@ public override Color BackColor { return base.BackColor; } - else if (this.ReadOnly) + else if (ReadOnly) { return SystemColors.Control; } @@ -456,7 +456,7 @@ protected override bool CanEnableIme Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_CanEnableIme(), this = " + this); Debug.Indent(); - bool canEnable = !(this.ReadOnly || this.PasswordProtect) && base.CanEnableIme; + bool canEnable = !(ReadOnly || PasswordProtect) && base.CanEnableIme; Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Value = " + canEnable); Debug.Unindent(); @@ -1005,7 +1005,7 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) { format |= TextFormatFlags.WordBreak; } - Size textSize = TextRenderer.MeasureText(this.Text, this.Font, proposedConstraints, format); + Size textSize = TextRenderer.MeasureText(Text, Font, proposedConstraints, format); // We use this old computation as a lower bound to ensure backwards compatibility. textSize.Height = Math.Max(textSize.Height, FontHeight); @@ -1028,7 +1028,7 @@ internal void GetSelectionStartAndLength(out int start, out int length) // while the control does not have a handle. We need to return valid values. We also need // to keep the old cached values in case the Text is changed again making the cached values // valid again. - AdjustSelectionStartAndEnd(this.selectionStart, this.selectionLength, out start, out end, -1); + AdjustSelectionStartAndEnd(selectionStart, selectionLength, out start, out end, -1); length = end - start; } else @@ -1404,7 +1404,7 @@ private void AdjustHeight(bool returnIfAnchored) // If we're anchored to two opposite sides of the form, don't adjust the size because // we'll lose our anchored size by resetting to the requested width. // - if (returnIfAnchored && (this.Anchor & (AnchorStyles.Top | AnchorStyles.Bottom)) == (AnchorStyles.Top | AnchorStyles.Bottom)) + if (returnIfAnchored && (Anchor & (AnchorStyles.Top | AnchorStyles.Bottom)) == (AnchorStyles.Top | AnchorStyles.Bottom)) { return; } @@ -1474,9 +1474,9 @@ public void AppendText(string text) // all the text will scroll to the top and the control will look empty when the // form is restored. We work around this by selecting back whatever was originally // selected when AppendText was called. - if (this.Width == 0 || this.Height == 0) + if (Width == 0 || Height == 0) { - this.Select(selStart, selLength); + Select(selStart, selLength); } } } @@ -1578,7 +1578,7 @@ protected override bool IsInputKey(Keys keyData) return false; break; case Keys.Back: - if (!this.ReadOnly) + if (!ReadOnly) return true; break; case Keys.PageUp: @@ -1623,7 +1623,7 @@ protected override void OnHandleDestroyed(EventArgs e) textBoxFlags[modified] = Modified; textBoxFlags[setSelectionOnHandleCreated] = true; // Update text selection cached values to be restored when recreating the handle. - GetSelectionStartAndLength(out this.selectionStart, out this.selectionLength); + GetSelectionStartAndLength(out selectionStart, out selectionLength); base.OnHandleDestroyed(e); } @@ -1642,7 +1642,7 @@ protected override bool ProcessDialogKey(Keys keyData) Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "TextBoxBase.ProcessDialogKey [" + keyData.ToString() + "]"); Keys keyCode = (Keys)keyData & Keys.KeyCode; - if (keyCode == Keys.Tab && this.AcceptsTab && (keyData & Keys.Control) != 0) + if (keyCode == Keys.Tab && AcceptsTab && (keyData & Keys.Control) != 0) { // When this control accepts Tabs, Ctrl-Tab is treated exactly like Tab. keyData &= ~Keys.Control; @@ -1716,19 +1716,19 @@ protected override void OnMouseUp(MouseEventArgs mevent) { if (!ValidationCancelled && UnsafeNativeMethods.WindowFromPoint(pt.X, pt.Y) == Handle) { - if (!this.doubleClickFired) + if (!doubleClickFired) { OnClick(mevent); OnMouseClick(mevent); } else { - this.doubleClickFired = false; + doubleClickFired = false; OnDoubleClick(mevent); OnMouseDoubleClick(mevent); } } - this.doubleClickFired = false; + doubleClickFired = false; } base.OnMouseUp(mevent); } @@ -1773,7 +1773,7 @@ protected override void OnTextChanged(EventArgs e) /// public virtual char GetCharFromPosition(Point pt) { - string t = this.Text; + string t = Text; int index = GetCharIndexFromPosition(pt); return (index < 0 || index >= t.Length) ? (char)0 : t[index]; } @@ -1793,7 +1793,7 @@ public virtual int GetCharIndexFromPosition(Point pt) } else { - string t = this.Text; + string t = Text; // EM_CHARFROMPOS will return an invalid number if the last character in the RichEdit // is a newline. // @@ -1860,7 +1860,7 @@ public void ScrollToCaret() { if (IsHandleCreated) { - if (string.IsNullOrEmpty(this.WindowText)) + if (string.IsNullOrEmpty(WindowText)) { // If there is no text, then there is no place to go. return; @@ -1903,7 +1903,7 @@ public void ScrollToCaret() int selStartLine = GetLineFromCharIndex(selStart); // 1. Scroll the RichTextBox all the way to the bottom - UnsafeNativeMethods.ITextRange textRange = textDocument.Range(this.WindowText.Length - 1, this.WindowText.Length - 1); + UnsafeNativeMethods.ITextRange textRange = textDocument.Range(WindowText.Length - 1, WindowText.Length - 1); textRange.ScrollIntoView(0); // 0 ==> tomEnd // 2. Get the first visible line. @@ -1960,7 +1960,7 @@ public void ScrollToCaret() /// public void DeselectAll() { - this.SelectionLength = 0; + SelectionLength = 0; } /// @@ -2020,8 +2020,8 @@ internal virtual void SelectInternal(int start, int length, int textLen) { //otherwise, wait until handle is created to send this message. //Store the indices until then... - this.selectionStart = start; - this.selectionLength = length; + selectionStart = start; + selectionLength = length; textBoxFlags[setSelectionOnHandleCreated] = true; } } @@ -2084,7 +2084,7 @@ internal void AdjustSelectionStartAndEnd(int selStart, int selLength, out int st } else { - textLength = this.TextLength; + textLength = TextLength; } if (start > textLength) @@ -2125,7 +2125,7 @@ internal void SetSelectionOnHandle() { textBoxFlags[setSelectionOnHandleCreated] = false; int start, end; - AdjustSelectionStartAndEnd(this.selectionStart, this.selectionLength, out start, out end, -1); + AdjustSelectionStartAndEnd(selectionStart, selectionLength, out start, out end, -1); SendMessage(Interop.EditMessages.EM_SETSEL, start, end); } } @@ -2289,7 +2289,7 @@ private void WmReflectCommand(ref Message m) { // Force update to the Modified property, which will trigger // ModifiedChanged event handlers - bool force = this.Modified; + bool force = Modified; } } } @@ -2381,7 +2381,7 @@ protected override void WndProc(ref Message m) switch (m.Msg) { case Interop.WindowMessages.WM_LBUTTONDBLCLK: - this.doubleClickFired = true; + doubleClickFired = true; base.WndProc(ref m); break; case Interop.WindowMessages.WM_REFLECT + Interop.WindowMessages.WM_COMMAND: diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs index 149bed44b32..e234e36be6e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs @@ -617,7 +617,7 @@ public ImageList ImageList { get { - return this.imageList; + return imageList; } set { @@ -660,9 +660,9 @@ public Size ImageSize { get { - if (this.imageList != null) + if (imageList != null) { - return this.imageList.ImageSize; + return imageList.ImageSize; } else { @@ -1274,7 +1274,7 @@ internal void InternalSetButton(int index, ToolBarButton value, bool recreate, b SendMessage(NativeMethods.TB_AUTOSIZE, 0, 0); ForceButtonWidths(); - this.Invalidate(); + Invalidate(); } } } @@ -1534,7 +1534,7 @@ private bool ShouldSerializeButtonSize() /// internal void SetToolTip(ToolTip toolTip) { - UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.TB_SETTOOLTIPS, new HandleRef(toolTip, toolTip.Handle), 0); + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TB_SETTOOLTIPS, new HandleRef(toolTip, toolTip.Handle), 0); } @@ -1647,23 +1647,23 @@ private void WmNotifyHotItemChange(ref Message m) // Should we set the hot item? NativeMethods.NMTBHOTITEM nmTbHotItem = (NativeMethods.NMTBHOTITEM)m.GetLParam(typeof(NativeMethods.NMTBHOTITEM)); if (NativeMethods.HICF_ENTERING == (nmTbHotItem.dwFlags & NativeMethods.HICF_ENTERING)) - this.hotItem = nmTbHotItem.idNew; + hotItem = nmTbHotItem.idNew; else if (NativeMethods.HICF_LEAVING == (nmTbHotItem.dwFlags & NativeMethods.HICF_LEAVING)) - this.hotItem = -1; + hotItem = -1; else if (NativeMethods.HICF_MOUSE == (nmTbHotItem.dwFlags & NativeMethods.HICF_MOUSE)) - this.hotItem = nmTbHotItem.idNew; + hotItem = nmTbHotItem.idNew; else if (NativeMethods.HICF_ARROWKEYS == (nmTbHotItem.dwFlags & NativeMethods.HICF_ARROWKEYS)) - this.hotItem = nmTbHotItem.idNew; + hotItem = nmTbHotItem.idNew; else if (NativeMethods.HICF_ACCELERATOR == (nmTbHotItem.dwFlags & NativeMethods.HICF_ACCELERATOR)) - this.hotItem = nmTbHotItem.idNew; + hotItem = nmTbHotItem.idNew; else if (NativeMethods.HICF_DUPACCEL == (nmTbHotItem.dwFlags & NativeMethods.HICF_DUPACCEL)) - this.hotItem = nmTbHotItem.idNew; + hotItem = nmTbHotItem.idNew; else if (NativeMethods.HICF_RESELECT == (nmTbHotItem.dwFlags & NativeMethods.HICF_RESELECT)) - this.hotItem = nmTbHotItem.idNew; + hotItem = nmTbHotItem.idNew; else if (NativeMethods.HICF_LMOUSE == (nmTbHotItem.dwFlags & NativeMethods.HICF_LMOUSE)) - this.hotItem = nmTbHotItem.idNew; + hotItem = nmTbHotItem.idNew; else if (NativeMethods.HICF_TOGGLEDROPDOWN == (nmTbHotItem.dwFlags & NativeMethods.HICF_TOGGLEDROPDOWN)) - this.hotItem = nmTbHotItem.idNew; + hotItem = nmTbHotItem.idNew; } @@ -1719,7 +1719,7 @@ protected override void WndProc(ref Message m) // but nowhere near the toolbar button? if (wndPlacement.rcNormalPosition_left == 0 && wndPlacement.rcNormalPosition_top == 0 && - this.hotItem != -1) + hotItem != -1) { // Assume that we're going to vertically center the tooltip on the right edge of the current @@ -1727,7 +1727,7 @@ protected override void WndProc(ref Message m) // Where is the right edge of the current hot item? int buttonRight = 0; - for (int idx = 0; idx <= this.hotItem; idx++) + for (int idx = 0; idx <= hotItem; idx++) { // How wide is the item at this index? (It could be a separator, and therefore a different width.) buttonRight += buttonsCollection[idx].GetButtonWidth(); @@ -1738,30 +1738,30 @@ protected override void WndProc(ref Message m) int tooltipHeight = wndPlacement.rcNormalPosition_bottom - wndPlacement.rcNormalPosition_top; // We'll need screen coordinates of this position for setting the tooltip's position - int x = this.Location.X + buttonRight + 1; - int y = this.Location.Y + (this.ButtonSize.Height / 2); + int x = Location.X + buttonRight + 1; + int y = Location.Y + (ButtonSize.Height / 2); NativeMethods.POINT leftTop = new NativeMethods.POINT(x, y); - UnsafeNativeMethods.ClientToScreen(new HandleRef(this, this.Handle), leftTop); + UnsafeNativeMethods.ClientToScreen(new HandleRef(this, Handle), leftTop); // Will the tooltip bleed off the top? if (leftTop.y < SystemInformation.WorkingArea.Y) { // Reposition the tooltip to be displayed below the button - leftTop.y += (this.ButtonSize.Height / 2) + 1; + leftTop.y += (ButtonSize.Height / 2) + 1; } // Will the tooltip bleed off the bottom? if (leftTop.y + tooltipHeight > SystemInformation.WorkingArea.Height) { // Reposition the tooltip to be displayed above the button - leftTop.y -= ((this.ButtonSize.Height / 2) + tooltipHeight + 1); + leftTop.y -= ((ButtonSize.Height / 2) + tooltipHeight + 1); } // Will the tooltip bleed off the right edge? if (leftTop.x + tooltipWidth > SystemInformation.WorkingArea.Right) { // Move the tooltip far enough left that it will display in the working area - leftTop.x -= (this.ButtonSize.Width + tooltipWidth + 2); + leftTop.x -= (ButtonSize.Width + tooltipWidth + 2); } SafeNativeMethods.SetWindowPos(new HandleRef(null, note.hwndFrom), NativeMethods.NullHandleRef, leftTop.x, leftTop.y, 0, 0, NativeMethods.SWP_NOSIZE | NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE); @@ -2096,7 +2096,7 @@ public virtual int IndexOfKey(string key) } // step 2 - search for the item - for (int i = 0; i < this.Count; i++) + for (int i = 0; i < Count; i++) { if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { @@ -2133,7 +2133,7 @@ void IList.Insert(int index, object button) /// private bool IsValidIndex(int index) { - return ((index >= 0) && (index < this.Count)); + return ((index >= 0) && (index < Count)); } /// /// Removes diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs index 4fc6fb95262..5334ffaa4a3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs @@ -76,7 +76,7 @@ public ToolBarButton() public ToolBarButton(string text) : base() { - this.Text = text; + Text = text; } @@ -516,21 +516,21 @@ internal short Width // COMPAT: this will force handle creation. // we could use the measurement graphics, but it looks like this has been like this since Everett. - using (Graphics g = this.parent.CreateGraphicsInternal()) + using (Graphics g = parent.CreateGraphicsInternal()) { - Size buttonSize = this.parent.buttonSize; + Size buttonSize = parent.buttonSize; if (!(buttonSize.IsEmpty)) { width = buttonSize.Width; } else { - if (this.parent.ImageList != null || !string.IsNullOrEmpty(Text)) + if (parent.ImageList != null || !string.IsNullOrEmpty(Text)) { - Size imageSize = this.parent.ImageSize; + Size imageSize = parent.ImageSize; Size textSize = Size.Ceiling(g.MeasureString(Text, parent.Font)); - if (this.parent.TextAlign == ToolBarTextAlign.Right) + if (parent.TextAlign == ToolBarTextAlign.Right) { if (textSize.Width == 0) width = imageSize.Width + edge.Width * 4; @@ -544,13 +544,13 @@ internal short Width else width = textSize.Width + edge.Width * 4; } - if (style == ToolBarButtonStyle.DropDownButton && this.parent.DropDownArrows) + if (style == ToolBarButtonStyle.DropDownButton && parent.DropDownArrows) { width += ToolBar.DDARROW_WIDTH; } } else - width = this.parent.ButtonSize.Width; + width = parent.ButtonSize.Width; } } } @@ -675,7 +675,7 @@ internal NativeMethods.TBBUTTON GetTBBUTTON(int commandId) } button.dwData = (IntPtr)0; - button.iString = this.stringIndex; + button.iString = stringIndex; this.commandId = commandId; button.idCommand = commandId; @@ -744,7 +744,7 @@ internal NativeMethods.TBBUTTONINFO GetTBBUTTONINFO(bool updateText, int newComm } else { - string textValue = this.text; + string textValue = text; PrefixAmpersands(ref textValue); button.pszText = Marshal.StringToHGlobalAuto(textValue); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs index c5bfc0b979a..9b98cb57cc2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs @@ -186,9 +186,9 @@ public ToolStrip() imageScalingSize = new Size(iconWidth, iconHeight); SuspendLayout(); - this.CanOverflow = true; - this.TabStop = false; - this.MenuAutoExpand = false; + CanOverflow = true; + TabStop = false; + MenuAutoExpand = false; SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.SupportsTransparentBackColor, true); @@ -204,12 +204,12 @@ public ToolStrip() ToolStripManager.ToolStrips.Add(this); layoutEngine = new ToolStripSplitStackLayout(this); - this.Dock = DefaultDock; - this.AutoSize = true; - this.CausesValidation = false; + Dock = DefaultDock; + AutoSize = true; + CausesValidation = false; Size defaultSize = DefaultSize; SetAutoSizeMode(AutoSizeMode.GrowAndShrink); - this.ShowItemToolTips = DefaultShowItemToolTips; + ShowItemToolTips = DefaultShowItemToolTips; ResumeLayout(true); } @@ -262,7 +262,7 @@ public override bool AutoSize // which would join it to a new row. Set the specified bounds to the new location to // prevent this. Rectangle bounds = CommonProperties.GetSpecifiedBounds(this); - bounds.Location = this.Location; + bounds.Location = Location; CommonProperties.UpdateSpecifiedBounds(this, bounds.X, bounds.Y, bounds.Width, bounds.Height, BoundsSpecified.Location); } @@ -370,11 +370,11 @@ public override bool AllowDrop if (value) { - this.DropTargetManager.EnsureRegistered(this); + DropTargetManager.EnsureRegistered(this); } else { - this.DropTargetManager.EnsureUnRegistered(this); + DropTargetManager.EnsureUnRegistered(this); } } @@ -406,14 +406,14 @@ public bool AllowItemReorder if (value) { ToolStripSplitStackDragDropHandler dragDropHandler = new ToolStripSplitStackDragDropHandler(this); - this.ItemReorderDropSource = dragDropHandler; - this.ItemReorderDropTarget = dragDropHandler; + ItemReorderDropSource = dragDropHandler; + ItemReorderDropTarget = dragDropHandler; - this.DropTargetManager.EnsureRegistered(this); + DropTargetManager.EnsureRegistered(this); } else { - this.DropTargetManager.EnsureUnRegistered(this); + DropTargetManager.EnsureUnRegistered(this); } } @@ -491,7 +491,7 @@ public override BindingContext BindingContext { get { - BindingContext bc = (BindingContext)this.Properties.GetObject(PropBindingContext); + BindingContext bc = (BindingContext)Properties.GetObject(PropBindingContext); if (bc != null) return bc; @@ -506,9 +506,9 @@ public override BindingContext BindingContext } set { - if (this.Properties.GetObject(PropBindingContext) != value) + if (Properties.GetObject(PropBindingContext) != value) { - this.Properties.SetObject(PropBindingContext, value); + Properties.SetObject(PropBindingContext, value); // re-wire the bindings OnBindingContextChanged(EventArgs.Empty); @@ -641,7 +641,7 @@ public override Font Font { get { - if (this.IsFontSet()) + if (IsFontSet()) { return base.Font; } @@ -752,7 +752,7 @@ public virtual ToolStripDropDownDirection DefaultDropDownDirection } else { // horizontal - DockStyle dock = this.Dock; + DockStyle dock = Dock; if (IsInToolStripPanel && ParentInternal != null) { dock = ParentInternal.Dock; // we want the orientation of the ToolStripPanel; @@ -806,7 +806,7 @@ public override DockStyle Dock if (value != Dock) { using (new LayoutTransaction(this, this, PropertyNames.Dock)) - using (new LayoutTransaction(this.ParentInternal, this, PropertyNames.Dock)) + using (new LayoutTransaction(ParentInternal, this, PropertyNames.Dock)) { // We don't call base.Dock = value, because that would cause us to get 2 LocationChanged events. // The first is when the parent gets a Layout due to the DockChange, and the second comes from when we @@ -1137,7 +1137,7 @@ internal virtual Size ImageScalingSizeInternal imageScalingSize = value; LayoutTransaction.DoLayoutIf((Items.Count > 0), this, this, PropertyNames.ImageScalingSize); - foreach (ToolStripItem item in this.Items) + foreach (ToolStripItem item in Items) { item.OnImageScalingSizeChanged(EventArgs.Empty); } @@ -1429,7 +1429,7 @@ public ToolStripLayoutStyle LayoutStyle { if (layoutStyle == ToolStripLayoutStyle.StackWithOverflow) { - switch (this.Orientation) + switch (Orientation) { case Orientation.Horizontal: return ToolStripLayoutStyle.HorizontalStackWithOverflow; @@ -1486,7 +1486,7 @@ public ToolStripLayoutStyle LayoutStyle } else { - UpdateLayoutStyle(this.Dock); + UpdateLayoutStyle(Dock); } } if (!(layoutEngine is ToolStripSplitStackLayout)) @@ -1515,11 +1515,11 @@ internal bool LayoutRequired { get { - return this.layoutRequired; + return layoutRequired; } set { - this.layoutRequired = value; + layoutRequired = value; } } @@ -1551,7 +1551,7 @@ protected internal virtual Size MaxItemSize { get { - return this.DisplayRectangle.Size; + return DisplayRectangle.Size; } } @@ -1624,7 +1624,7 @@ public ToolStripOverflowButton OverflowButton toolStripOverflowButton.Overflow = ToolStripItemOverflow.Never; toolStripOverflowButton.ParentInternal = this; toolStripOverflowButton.Alignment = ToolStripItemAlignment.Right; - toolStripOverflowButton.Size = toolStripOverflowButton.GetPreferredSize(this.DisplayRectangle.Size - this.Padding.Size); + toolStripOverflowButton.Size = toolStripOverflowButton.GetPreferredSize(DisplayRectangle.Size - Padding.Size); } return toolStripOverflowButton; } @@ -1911,7 +1911,7 @@ internal bool ShowKeyboardCuesInternal { get { - return this.ShowKeyboardCues; + return ShowKeyboardCues; } } @@ -1936,8 +1936,8 @@ public bool ShowItemToolTips UpdateToolTip(null); } - ToolTip internalToolTip = this.ToolTip; - foreach (ToolStripItem item in this.Items) + ToolTip internalToolTip = ToolTip; + foreach (ToolStripItem item in Items) { if (showItemToolTips) { @@ -1951,9 +1951,9 @@ public bool ShowItemToolTips // If the overflow button has not been created, don't check its properties // since this will force its creating and cause a re-layout of the control - if (toolStripOverflowButton != null && this.OverflowButton.HasDropDownItems) + if (toolStripOverflowButton != null && OverflowButton.HasDropDownItems) { - this.OverflowButton.DropDown.ShowItemToolTips = value; + OverflowButton.DropDown.ShowItemToolTips = value; } } } @@ -2089,7 +2089,7 @@ internal virtual void ChangeSelection(ToolStripItem nextItem) // e.g. go from a text box to a toolstrip button if (ContainsFocus && !Focused) { - this.Focus(); + Focus(); if (controlHost == null) { // if nextItem IS a toolstripcontrolhost, we're going to focus it anyways @@ -2242,7 +2242,7 @@ internal void ClearInsertionMark() Rectangle invalidate = lastInsertionMarkRect; lastInsertionMarkRect = Rectangle.Empty; - this.Invalidate(invalidate); + Invalidate(invalidate); } } @@ -2272,7 +2272,7 @@ protected override void Dispose(bool disposing) try { - this.SuspendLayout(); + SuspendLayout(); if (overflow != null) { overflow.SuspendLayout(); @@ -2353,7 +2353,7 @@ protected override void Dispose(bool disposing) finally { - this.ResumeLayout(false); + ResumeLayout(false); if (overflow != null) { overflow.ResumeLayout(false); @@ -2367,24 +2367,24 @@ protected override void Dispose(bool disposing) internal void DoLayoutIfHandleCreated(ToolStripItemEventArgs e) { - if (this.IsHandleCreated) + if (IsHandleCreated) { LayoutTransaction.DoLayout(this, e.Item, PropertyNames.Items); - this.Invalidate(); + Invalidate(); // Adding this item may have added it to the overflow // However, we can't check if it's in OverflowItems, because // it gets added there in Layout, and layout might be suspended. - if (this.CanOverflow && this.OverflowButton.HasDropDown) + if (CanOverflow && OverflowButton.HasDropDown) { if (DeferOverflowDropDownLayout()) { - CommonProperties.xClearPreferredSizeCache(this.OverflowButton.DropDown); - this.OverflowButton.DropDown.LayoutRequired = true; + CommonProperties.xClearPreferredSizeCache(OverflowButton.DropDown); + OverflowButton.DropDown.LayoutRequired = true; } else { - LayoutTransaction.DoLayout(this.OverflowButton.DropDown, e.Item, PropertyNames.Items); - this.OverflowButton.DropDown.Invalidate(); + LayoutTransaction.DoLayout(OverflowButton.DropDown, e.Item, PropertyNames.Items); + OverflowButton.DropDown.Invalidate(); } } } @@ -2392,19 +2392,19 @@ internal void DoLayoutIfHandleCreated(ToolStripItemEventArgs e) { // next time we fetch the preferred size, recalc it. CommonProperties.xClearPreferredSizeCache(this); - this.LayoutRequired = true; - if (this.CanOverflow && this.OverflowButton.HasDropDown) + LayoutRequired = true; + if (CanOverflow && OverflowButton.HasDropDown) { - this.OverflowButton.DropDown.LayoutRequired = true; + OverflowButton.DropDown.LayoutRequired = true; } } } private bool DeferOverflowDropDownLayout() { - return this.IsLayoutSuspended - || !this.OverflowButton.DropDown.Visible - || !this.OverflowButton.DropDown.IsHandleCreated; + return IsLayoutSuspended + || !OverflowButton.DropDown.Visible + || !OverflowButton.DropDown.IsHandleCreated; } void ISupportToolStripPanel.EndDrag() @@ -2981,12 +2981,12 @@ private void InitializeRenderer(ToolStripRenderer renderer) using (LayoutTransaction.CreateTransactionIf(AutoSize, this, this, PropertyNames.Renderer)) { renderer.Initialize(this); - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { - renderer.InitializeItem(this.Items[i]); + renderer.InitializeItem(Items[i]); } } - Invalidate(this.Controls.Count > 0); + Invalidate(Controls.Count > 0); } @@ -3017,7 +3017,7 @@ internal void InvalidateTextItems() /// protected override bool IsInputKey(Keys keyData) { - ToolStripItem item = this.GetSelectedItem(); + ToolStripItem item = GetSelectedItem(); if ((item != null) && item.IsInputKey(keyData)) { return true; @@ -3030,7 +3030,7 @@ protected override bool IsInputKey(Keys keyData) /// protected override bool IsInputChar(char charCode) { - ToolStripItem item = this.GetSelectedItem(); + ToolStripItem item = GetSelectedItem(); if ((item != null) && item.IsInputChar(charCode)) { return true; @@ -3078,7 +3078,7 @@ private void ImageListRecreateHandle(object sender, EventArgs e) protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { - Point location = this.Location; + Point location = Location; if (!IsCurrentlyDragging && !IsLocationChanging && IsInToolStripPanel) { @@ -3144,7 +3144,7 @@ internal override void PrintToMetaFileRecursive(HandleRef hDC, IntPtr lParam, Re { IntPtr imageHdc = g.GetHdc(); //send the actual wm_print message - UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), Interop.WindowMessages.WM_PRINT, (IntPtr)imageHdc, + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.WindowMessages.WM_PRINT, (IntPtr)imageHdc, (IntPtr)(NativeMethods.PRF_CHILDREN | NativeMethods.PRF_CLIENT | NativeMethods.PRF_ERASEBKGND | NativeMethods.PRF_NONCLIENT)); //now BLT the result to the destination bitmap. @@ -3177,7 +3177,7 @@ protected override bool ProcessCmdKey(ref Message m, Keys keyData) // Give the ToolStripItem very first chance at // processing keys (except for ALT handling) - ToolStripItem selectedItem = this.GetSelectedItem(); + ToolStripItem selectedItem = GetSelectedItem(); if (selectedItem != null) { if (selectedItem.ProcessCmdKey(ref m, keyData)) @@ -3186,7 +3186,7 @@ protected override bool ProcessCmdKey(ref Message m, Keys keyData) } } - foreach (ToolStripItem item in this.Items) + foreach (ToolStripItem item in Items) { if (item == selectedItem) { @@ -3238,7 +3238,7 @@ protected override bool ProcessDialogKey(Keys keyData) bool retVal = false; // Give the ToolStripItem first dibs - ToolStripItem item = this.GetSelectedItem(); + ToolStripItem item = GetSelectedItem(); if (item != null) { if (item.ProcessDialogKey(keyData)) @@ -3610,7 +3610,7 @@ protected virtual void OnBeginDrag(EventArgs e) { SetToolStripState(STATE_DRAGGING, true); Debug.Assert(ToolStripPanelRow != null, "Why is toolstrippanel row null?"); - Debug.Assert(this.ParentInternal as ToolStripPanel != null, "Why is our parent not a toolstrip panel?"); + Debug.Assert(ParentInternal as ToolStripPanel != null, "Why is our parent not a toolstrip panel?"); ClearAllSelections(); UpdateToolTip(null); // supress the tooltip. @@ -3623,7 +3623,7 @@ protected virtual void OnEndDrag(EventArgs e) { SetToolStripState(STATE_DRAGGING, false); Debug.Assert(ToolStripPanelRow != null, "Why is toolstrippanel row null?"); - Debug.Assert(this.ParentInternal as ToolStripPanel != null, "Why is our parent not a toolstrip panel?"); + Debug.Assert(ParentInternal as ToolStripPanel != null, "Why is our parent not a toolstrip panel?"); Debug.Assert(ToolStripPanelRow == null || ToolStripPanelRow.ToolStripPanel.RowsInternal.Contains(ToolStripPanelRow), "Why are we in an orphaned row?"); EventHandler handler = (EventHandler)Events[EventEndDrag]; @@ -3656,7 +3656,7 @@ protected override void OnEnabledChanged(EventArgs e) base.OnEnabledChanged(e); // notify items that the parent has changed - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { if (Items[i] != null && Items[i].ParentInternal == this) { @@ -3679,7 +3679,7 @@ internal void OnDefaultFontChanged() protected override void OnFontChanged(EventArgs e) { base.OnFontChanged(e); - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { Items[i].OnOwnerFontChanged(e); } @@ -3713,9 +3713,9 @@ protected override void OnInvalidated(InvalidateEventArgs e) /// protected override void OnHandleCreated(EventArgs e) { - if ((this.AllowDrop || this.AllowItemReorder) && (DropTargetManager != null)) + if ((AllowDrop || AllowItemReorder) && (DropTargetManager != null)) { - this.DropTargetManager.EnsureRegistered(this); + DropTargetManager.EnsureRegistered(this); } // calling control's (in base) version AFTER we register our DropTarget, so it will @@ -3731,7 +3731,7 @@ protected override void OnHandleDestroyed(EventArgs e) if (DropTargetManager != null) { // Make sure we unregister ourselves as a drop target - this.DropTargetManager.EnsureUnRegistered(this); + DropTargetManager.EnsureUnRegistered(this); } base.OnHandleDestroyed(e); } @@ -3799,14 +3799,14 @@ internal void OnItemVisibleChanged(ToolStripItemEventArgs e, bool performLayout) } protected override void OnLayout(LayoutEventArgs e) { - this.LayoutRequired = false; + LayoutRequired = false; // we need to do this to prevent autosizing to happen while we're reparenting. ToolStripOverflow overflow = GetOverflow(); if (overflow != null) { overflow.SuspendLayout(); - toolStripOverflowButton.Size = toolStripOverflowButton.GetPreferredSize(this.DisplayRectangle.Size - this.Padding.Size); + toolStripOverflowButton.Size = toolStripOverflowButton.GetPreferredSize(DisplayRectangle.Size - Padding.Size); } for (int j = 0; j < Items.Count; j++) @@ -3882,7 +3882,7 @@ protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs mea) // set capture only when we know we're not on a dropdown (already effectively have capture due to modal menufilter) // and the item in question requires the mouse to be in the same item to be clicked. SetToolStripState(STATE_LASTMOUSEDOWNEDITEMCAPTURE, true); - this.CaptureInternal = true; + CaptureInternal = true; } MenuAutoExpand = true; @@ -3951,7 +3951,7 @@ protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs mea) } else { - item = this.Grip; + item = Grip; } if (item != null) { @@ -3965,7 +3965,7 @@ protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs mea) } else { - Debug.WriteLineIf(ToolStripItem.MouseDebugging.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "Firing MouseMove on: {0}", (this == null) ? "null" : this.ToString())); + Debug.WriteLineIf(ToolStripItem.MouseDebugging.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "Firing MouseMove on: {0}", (this == null) ? "null" : ToString())); base.OnMouseMove(mea); } @@ -4031,10 +4031,10 @@ protected override void OnPaint(PaintEventArgs e) base.OnPaint(e); Graphics toolstripGraphics = e.Graphics; - Size bitmapSize = this.largestDisplayedItemSize; + Size bitmapSize = largestDisplayedItemSize; bool excludedTransparentRegion = false; - Rectangle viewableArea = this.DisplayRectangle; + Rectangle viewableArea = DisplayRectangle; Region transparentRegion = Renderer.GetTransparentRegion(this); try @@ -4121,7 +4121,7 @@ protected override void OnPaint(PaintEventArgs e) if (!LayoutUtils.AreWidthAndHeightLarger(bitmapSize, itemSize)) { // the cached HDC isnt big enough for this item. make it bigger. - this.largestDisplayedItemSize = itemSize; + largestDisplayedItemSize = itemSize; bitmapSize = itemSize; // dispose the old graphics - create a new, bigger one. itemGraphics.Dispose(); @@ -4383,7 +4383,7 @@ internal void PaintInsertionMark(Rectangle insertionRect) { ClearInsertionMark(); lastInsertionMarkRect = insertionRect; - this.Invalidate(insertionRect); + Invalidate(insertionRect); } } @@ -4433,13 +4433,13 @@ public ToolStripItem GetItemAt(Point point) if (bounds.IntersectsWith(comparisonRect) && lastMouseActiveItem.ParentInternal == this) { - return this.lastMouseActiveItem; + return lastMouseActiveItem; } } // Walk the ToolStripItem collection - for (int i = 0; i < this.DisplayedItems.Count; i++) + for (int i = 0; i < DisplayedItems.Count; i++) { if (DisplayedItems[i] == null || DisplayedItems[i].ParentInternal != this) { @@ -4455,7 +4455,7 @@ public ToolStripItem GetItemAt(Point point) } if (bounds.IntersectsWith(comparisonRect)) { - return this.DisplayedItems[i]; + return DisplayedItems[i]; } } @@ -4522,7 +4522,7 @@ protected virtual void RestoreFocus() bool focusSuccess = false; - if ((hwndThatLostFocus != IntPtr.Zero) && (hwndThatLostFocus != this.Handle)) + if ((hwndThatLostFocus != IntPtr.Zero) && (hwndThatLostFocus != Handle)) { Control c = Control.FromHandle(hwndThatLostFocus); @@ -4572,7 +4572,7 @@ internal void SuspendCaputureMode() internal virtual void ScrollInternal(int delta) { SuspendLayout(); - foreach (ToolStripItem item in this.Items) + foreach (ToolStripItem item in Items) { Point newLocation = item.Bounds.Location; @@ -4851,12 +4851,12 @@ protected virtual void SetDisplayedItems() { HasVisibleItems = true; biggestItemSize = LayoutUtils.UnionSizes(biggestItemSize, item.Bounds.Size); - this.DisplayedItems.Add(item); + DisplayedItems.Add(item); } } else if (placement == ToolStripItemPlacement.Overflow && !(item is ToolStripSeparator)) { - this.OverflowItems.Add(item); + OverflowItems.Add(item); } } else @@ -4873,11 +4873,11 @@ protected virtual void SetDisplayedItems() } if (OverflowItems.Count == 0) { - this.OverflowButton.Visible = false; + OverflowButton.Visible = false; } else if (CanOverflow) { - this.DisplayedItems.Add(OverflowButton); + DisplayedItems.Add(OverflowButton); } } @@ -4885,8 +4885,8 @@ protected virtual void SetDisplayedItems() { // NOT a SplitStack layout. We dont change the order of the displayed items collection // for custom keyboard handling override GetNextItem. - Debug.WriteLineIf(LayoutDebugSwitch.TraceVerbose, "Setting Displayed Items: Current bounds: " + this.Bounds.ToString()); - Rectangle clientBounds = this.ClientRectangle; + Debug.WriteLineIf(LayoutDebugSwitch.TraceVerbose, "Setting Displayed Items: Current bounds: " + Bounds.ToString()); + Rectangle clientBounds = ClientRectangle; // for all other layout managers, we ignore overflow placement bool allContained = true; @@ -4911,7 +4911,7 @@ protected virtual void SetDisplayedItems() { HasVisibleItems = true; biggestItemSize = LayoutUtils.UnionSizes(biggestItemSize, item.Bounds.Size); - this.DisplayedItems.Add(item); + DisplayedItems.Add(item); item.SetPlacement(ToolStripItemPlacement.Main); } } @@ -4925,7 +4925,7 @@ protected virtual void SetDisplayedItems() // For performance we calculate this here, since we're already iterating over the items. // the only one who cares about it is ToolStripDropDownMenu (to see if it needs scroll buttons). - this.AllItemsVisible = allContained; + AllItemsVisible = allContained; } SetLargestItemSize(biggestItemSize); @@ -4974,7 +4974,7 @@ private void SnapFocus(IntPtr otherHwnd) if (!TabStop && !IsDropDown) { bool snapFocus = false; - if (Focused && (otherHwnd != this.Handle)) + if (Focused && (otherHwnd != Handle)) { // the case here is a label before a combo box calling FocusInternal in ProcessMnemonic. // we'll filter out children later. @@ -4994,7 +4994,7 @@ private void SnapFocus(IntPtr otherHwnd) // start auto expanding for keyboard and mouse. // MenuAutoExpand = true; - HandleRef thisHandle = new HandleRef(this, this.Handle); + HandleRef thisHandle = new HandleRef(this, Handle); HandleRef otherHandle = new HandleRef(null, otherHwnd); // make sure the otherHandle is not a child of thisHandle @@ -5023,7 +5023,7 @@ private void SnapFocus(IntPtr otherHwnd) // thing that lost focus. internal void SnapFocusChange(ToolStrip otherToolStrip) { - otherToolStrip.hwndThatLostFocus = this.hwndThatLostFocus; + otherToolStrip.hwndThatLostFocus = hwndThatLostFocus; } private bool ShouldSerializeDefaultDropDownDirection() @@ -5057,8 +5057,8 @@ public override string ToString() { StringBuilder sb = new StringBuilder(base.ToString()); sb.Append(", Name: "); - sb.Append(this.Name); - sb.Append(", Items: ").Append(this.Items.Count); + sb.Append(Name); + sb.Append(", Items: ").Append(Items.Count); return sb.ToString(); } @@ -5118,9 +5118,9 @@ private void UpdateLayoutStyle(DockStyle newDock) OnLayoutStyleChanged(EventArgs.Empty); - if (this.ParentInternal != null) + if (ParentInternal != null) { - LayoutTransaction.DoLayout(this.ParentInternal, this, PropertyNames.Orientation); + LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.Orientation); } } } @@ -5193,7 +5193,7 @@ protected override void WndProc(ref Message m) IntPtr hwndClicked = UnsafeNativeMethods.ChildWindowFromPointEx(new HandleRef(null, Handle), pt.X, pt.Y, (int)(GetChildAtPointSkip.Invisible | GetChildAtPointSkip.Disabled | GetChildAtPointSkip.Transparent)); // if we click on the toolstrip itself, eat the activation. // if we click on a child control, allow the toolstrip to activate. - if (hwndClicked == this.Handle) + if (hwndClicked == Handle) { lastMouseDownedItem = null; m.Result = (IntPtr)NativeMethods.MA_NOACTIVATE; @@ -5280,20 +5280,20 @@ protected override Control.ControlCollection CreateControlsInstance() internal void OnItemAddedInternal(ToolStripItem item) { - if (this.ShowItemToolTips) + if (ShowItemToolTips) { - KeyboardToolTipStateMachine.Instance.Hook(item, this.ToolTip); + KeyboardToolTipStateMachine.Instance.Hook(item, ToolTip); } } internal void OnItemRemovedInternal(ToolStripItem item) { - KeyboardToolTipStateMachine.Instance.Unhook(item, this.ToolTip); + KeyboardToolTipStateMachine.Instance.Unhook(item, ToolTip); } internal override bool AllowsChildrenToShowToolTips() { - return base.AllowsChildrenToShowToolTips() && this.ShowItemToolTips; + return base.AllowsChildrenToShowToolTips() && ShowItemToolTips; } [System.Runtime.InteropServices.ComVisible(true)] @@ -5622,14 +5622,14 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga int childCount = GetChildFragmentCount(); if (childCount > 0) { - return this.GetChildFragment(0); + return GetChildFragment(0); } break; case UnsafeNativeMethods.NavigateDirection.LastChild: childCount = GetChildFragmentCount(); if (childCount > 0) { - return this.GetChildFragment(childCount - 1); + return GetChildFragment(childCount - 1); } break; } @@ -5732,10 +5732,10 @@ private void RestoreFocusInternal() internal override bool ShowsOwnKeyboardToolTip() { bool hasVisibleSelectableItems = false; - int i = this.Items.Count; + int i = Items.Count; while (i-- != 0 && !hasVisibleSelectableItems) { - ToolStripItem item = this.Items[i]; + ToolStripItem item = Items[i]; if (item.CanKeyboardSelect && item.Visible) { hasVisibleSelectableItems = true; @@ -5926,7 +5926,7 @@ public void OnDragEnter(DragEventArgs e) if (e.Data.GetDataPresent(typeof(ToolStripItem))) { e.Effect = DragDropEffects.Move; - this.ShowItemDropPoint(owner.PointToClient(new Point(e.X, e.Y))); + ShowItemDropPoint(owner.PointToClient(new Point(e.X, e.Y))); } } @@ -5955,7 +5955,7 @@ public void OnDragOver(DragEventArgs e) if (e.Data.GetDataPresent(typeof(ToolStripItem))) { - if (this.ShowItemDropPoint(owner.PointToClient(new Point(e.X, e.Y)))) + if (ShowItemDropPoint(owner.PointToClient(new Point(e.X, e.Y)))) { e.Effect = DragDropEffects.Move; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs index badc2e635a5..b04e74cc5b6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs @@ -246,9 +246,9 @@ protected virtual void OnCheckStateChanged(EventArgs e) protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { - if (this.Owner != null) + if (Owner != null) { - ToolStripRenderer renderer = this.Renderer; + ToolStripRenderer renderer = Renderer; renderer.DrawButtonBackground(new ToolStripItemRenderEventArgs(e.Graphics, this)); @@ -261,7 +261,7 @@ protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) if ((DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) { - renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(e.Graphics, this, this.Text, InternalLayout.TextRectangle, this.ForeColor, this.Font, InternalLayout.TextFormat)); + renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(e.Graphics, this, Text, InternalLayout.TextRectangle, ForeColor, Font, InternalLayout.TextFormat)); } } } @@ -270,7 +270,7 @@ protected override void OnClick(EventArgs e) { if (checkOnClick) { - this.Checked = !this.Checked; + Checked = !Checked; } base.OnClick(e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripComboBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripComboBox.cs index baa243416d8..93b3f9c4217 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripComboBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripComboBox.cs @@ -44,7 +44,7 @@ public ToolStripComboBox() : base(CreateControlInstance()) public ToolStripComboBox(string name) : this() { - this.Name = name; + Name = name; } /// @@ -124,7 +124,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga if (direction == UnsafeNativeMethods.NavigateDirection.FirstChild || direction == UnsafeNativeMethods.NavigateDirection.LastChild) { - return this.ownerItem.ComboBox.AccessibilityObject; + return ownerItem.ComboBox.AccessibilityObject; } // Handle Parent and other directions in base ToolStripItem.FragmentNavigate() method. @@ -138,7 +138,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRo { get { - return this.ownerItem.RootToolStrip.AccessibilityObject; + return ownerItem.RootToolStrip.AccessibilityObject; } } } @@ -607,7 +607,7 @@ private bool ShouldSerializeDropDownWidth() internal override bool ShouldSerializeFont() { - return !object.Equals(this.Font, ToolStripManager.DefaultFont); + return !object.Equals(Font, ToolStripManager.DefaultFont); } public override string ToString() @@ -622,7 +622,7 @@ internal class ToolStripComboBoxControl : ComboBox public ToolStripComboBoxControl() { - this.FlatStyle = FlatStyle.Popup; + FlatStyle = FlatStyle.Popup; SetStyle(ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer, true); } @@ -846,7 +846,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRo { get { - var toolStripComboBoxControl = this.Owner as ToolStripComboBoxControl; + var toolStripComboBoxControl = Owner as ToolStripComboBoxControl; if (toolStripComboBoxControl != null) { return toolStripComboBoxControl.Owner.Owner.AccessibilityObject; @@ -863,7 +863,7 @@ internal override object GetPropertyValue(int propertyID) case NativeMethods.UIA_ControlTypePropertyId: return NativeMethods.UIA_ComboBoxControlTypeId; case NativeMethods.UIA_IsOffscreenPropertyId: - return (this.State & AccessibleStates.Offscreen) == AccessibleStates.Offscreen; + return (State & AccessibleStates.Offscreen) == AccessibleStates.Offscreen; } return base.GetPropertyValue(propertyID); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs index bba32818630..c838687b621 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs @@ -51,7 +51,7 @@ public ToolStripContainer() rightPanel.Dock = DockStyle.Right; leftPanel.Dock = DockStyle.Left; - ToolStripContainerTypedControlCollection controlCollection = this.Controls as ToolStripContainerTypedControlCollection; + ToolStripContainerTypedControlCollection controlCollection = Controls as ToolStripContainerTypedControlCollection; if (controlCollection != null) { controlCollection.AddInternal(contentPanel); @@ -421,7 +421,7 @@ protected override Control.ControlCollection CreateControlsInstance() protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); - RightToLeft rightToLeft = this.RightToLeft; + RightToLeft rightToLeft = RightToLeft; // no need to suspend layout - we're already in a layout transaction. if (rightToLeft == RightToLeft.Yes) @@ -438,12 +438,12 @@ protected override void OnRightToLeftChanged(EventArgs e) protected override void OnSizeChanged(EventArgs e) { - foreach (Control c in this.Controls) + foreach (Control c in Controls) { c.SuspendLayout(); } base.OnSizeChanged(e); - foreach (Control c in this.Controls) + foreach (Control c in Controls) { c.ResumeLayout(); } @@ -479,7 +479,7 @@ internal class ToolStripContainerTypedControlCollection : WindowsFormsUtils.Read public ToolStripContainerTypedControlCollection(Control c, bool isReadOnly) : base(c, isReadOnly) { - this.owner = c as ToolStripContainer; + owner = c as ToolStripContainer; } public override void Add(Control value) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContentPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContentPanel.cs index e037bfd29e6..22135bb998c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContentPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContentPanel.cs @@ -128,9 +128,9 @@ public override Color BackColor // To support transparency on ToolStripContainer, we need this check // to ensure that background color of the container reflects the // ContentPanel - if (this.ParentInternal is ToolStripContainer && value == Color.Transparent) + if (ParentInternal is ToolStripContainer && value == Color.Transparent) { - this.ParentInternal.BackColor = Color.Transparent; + ParentInternal.BackColor = Color.Transparent; } base.BackColor = value; } @@ -403,19 +403,19 @@ protected virtual void OnRendererChanged(EventArgs e) // we dont want to be greedy.... if we're using TSProfessionalRenderer go DBuf, else dont. if (Renderer is ToolStripProfessionalRenderer) { - state[stateLastDoubleBuffer] = this.DoubleBuffered; + state[stateLastDoubleBuffer] = DoubleBuffered; //this.DoubleBuffered = true; SetStyle(ControlStyles.OptimizedDoubleBuffer, true); } else { // restore DBuf - this.DoubleBuffered = state[stateLastDoubleBuffer]; + DoubleBuffered = state[stateLastDoubleBuffer]; } Renderer.InitializeContentPanel(this); - this.Invalidate(); + Invalidate(); EventHandler handler = (EventHandler)Events[EventRendererChanged]; if (handler != null) @@ -425,12 +425,12 @@ protected virtual void OnRendererChanged(EventArgs e) private void ResetRenderMode() { - this.RendererSwitcher.ResetRenderMode(); + RendererSwitcher.ResetRenderMode(); } private bool ShouldSerializeRenderMode() { - return this.RendererSwitcher.ShouldSerializeRenderMode(); + return RendererSwitcher.ShouldSerializeRenderMode(); } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs index 06d26c59a3e..ecee499e113 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs @@ -49,7 +49,7 @@ public ToolStripControlHost(Control c) SetBounds(c.Bounds); // now that we have a control set in, update the bounds. - Rectangle bounds = this.Bounds; + Rectangle bounds = Bounds; CommonProperties.UpdateSpecifiedBounds(c, bounds.X, bounds.Y, bounds.Width, bounds.Height); c.ToolStripControlHost = this; @@ -58,7 +58,7 @@ public ToolStripControlHost(Control c) } public ToolStripControlHost(Control c, string name) : this(c) { - this.Name = name; + Name = name; } public override Color BackColor @@ -122,7 +122,7 @@ public override bool CanSelect { if (control != null) { - return (DesignMode || this.Control.CanSelect); + return (DesignMode || Control.CanSelect); } return false; } @@ -793,7 +793,7 @@ private void HandleControlVisibleChanged(object sender, EventArgs e) if (itemVisibleStateFlag != controlVisibleStateFlag) { - this.Visible = Control.Visible; + Visible = Control.Visible; // this should fire the OnVisibleChanged and raise events appropriately. }; } @@ -879,8 +879,8 @@ protected override void OnBoundsChanged() return; } - Size size = LayoutUtils.DeflateRect(this.Bounds, this.Padding).Size; - Rectangle bounds = LayoutUtils.Align(size, this.Bounds, ControlAlign); + Size size = LayoutUtils.DeflateRect(Bounds, Padding).Size; + Rectangle bounds = LayoutUtils.Align(size, Bounds, ControlAlign); // use BoundsSpecified.None so we dont deal w/specified bounds - this way we can tell what someone has set the size to. element.SetBounds(bounds, BoundsSpecified.None); @@ -889,7 +889,7 @@ protected override void OnBoundsChanged() // to re-align. if (bounds != control.Bounds) { - bounds = LayoutUtils.Align(control.Size, this.Bounds, ControlAlign); + bounds = LayoutUtils.Align(control.Size, Bounds, ControlAlign); element.SetBounds(bounds, BoundsSpecified.None); } ResumeSizeSync(); @@ -1067,7 +1067,7 @@ private void SyncControlParent() protected virtual void OnHostedControlResize(EventArgs e) { // support for syncing the wrapper when the control size has changed - this.Size = Control.Size; + Size = Control.Size; } protected internal override bool ProcessCmdKey(ref Message m, Keys keyData) => false; @@ -1124,12 +1124,12 @@ public override void ResetForeColor() private void SuspendSizeSync() { - this.suspendSyncSizeCount++; + suspendSyncSizeCount++; } private void ResumeSizeSync() { - this.suspendSyncSizeCount--; + suspendSyncSizeCount--; } internal override bool ShouldSerializeBackColor() { @@ -1170,14 +1170,14 @@ internal override void OnKeyboardToolTipHook(ToolTip toolTip) { base.OnKeyboardToolTipHook(toolTip); - KeyboardToolTipStateMachine.Instance.Hook(this.Control, toolTip); + KeyboardToolTipStateMachine.Instance.Hook(Control, toolTip); } internal override void OnKeyboardToolTipUnhook(ToolTip toolTip) { base.OnKeyboardToolTipUnhook(toolTip); - KeyboardToolTipStateMachine.Instance.Unhook(this.Control, toolTip); + KeyboardToolTipStateMachine.Instance.Unhook(Control, toolTip); } // Our implementation of ISite: diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs index 10b768918d6..d73389c177a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs @@ -475,7 +475,7 @@ public override Font Font { get { - if (this.IsFontSet()) + if (IsFontSet()) { return base.Font; } @@ -708,7 +708,7 @@ protected internal override Size MaxItemSize { get { - return Screen.GetWorkingArea(this.Bounds).Size - this.Padding.Size; + return Screen.GetWorkingArea(Bounds).Size - Padding.Size; } } @@ -795,15 +795,15 @@ public ToolStripItem OwnerItem { if (ownerItem != value) { - Font originalFont = this.Font; - RightToLeft startRightToLeft = this.RightToLeft; + Font originalFont = Font; + RightToLeft startRightToLeft = RightToLeft; ownerItem = value; // RESET ambient properties if (!originalFont.Equals(Font)) { OnOwnerItemFontChanged(EventArgs.Empty); } - if (ownerItem != null && RightToLeftInherited && startRightToLeft != this.RightToLeft) + if (ownerItem != null && RightToLeftInherited && startRightToLeft != RightToLeft) { using (new LayoutTransaction(this, this, PropertyNames.RightToLeft)) { @@ -1119,9 +1119,9 @@ internal void AssignToDropDownItem() internal void AdjustSize() { Size size = GetSuggestedSize(); - if (size != this.Size) + if (size != Size) { - this.Size = size; + Size = size; } } @@ -1208,7 +1208,7 @@ protected override void CreateHandle() public void Close() { SetCloseReason(ToolStripDropDownCloseReason.CloseCalled); - this.Visible = false; + Visible = false; // we were the last one in the chain, roll out of menu mode. if (ToolStripManager.ModalMenuFilter.GetActiveToolStrip() == null) { @@ -1229,7 +1229,7 @@ internal void SetCloseReason(ToolStripDropDownCloseReason reason) public void Close(ToolStripDropDownCloseReason reason) { SetCloseReason(reason); - this.Visible = false; + Visible = false; } /// @@ -1327,7 +1327,7 @@ internal Size GetSuggestedSize() { return GetPreferredSize(Size.Empty); } - return this.Size; + return Size; } /// @@ -1349,7 +1349,7 @@ internal override void HandleItemClicked(ToolStripItem dismissingItem) { // Only clear the SourceControl if this is the last click. if (!LocalAppContextSwitches.UseLegacyContextMenuStripSourceControlValue && - this.ActiveDropDowns.Count == 0) + ActiveDropDowns.Count == 0) { // post processing after the click has happened. SourceControlInternal = null; @@ -1370,12 +1370,12 @@ internal virtual void Initialize() SetState(STATE_MODAL, true); SetStyle(ControlStyles.ResizeRedraw, true); - this.UpdateStyles(); - this.GripStyle = ToolStripGripStyle.Hidden; - this.CanOverflow = false; - this.LayoutStyle = ToolStripLayoutStyle.Flow; - this.MenuAutoExpand = true; - this.AutoSize = true; + UpdateStyles(); + GripStyle = ToolStripGripStyle.Hidden; + CanOverflow = false; + LayoutStyle = ToolStripLayoutStyle.Flow; + MenuAutoExpand = true; + AutoSize = true; } @@ -1480,7 +1480,7 @@ protected virtual void OnOpened(System.EventArgs e) protected override void OnVisibleChanged(System.EventArgs e) { - if (this.Location != this.displayLocation) + if (Location != displayLocation) { // If we adjusted the position from where the user wanted it, // see if we can put it in the right location now that they've changed @@ -1488,10 +1488,10 @@ protected override void OnVisibleChanged(System.EventArgs e) // Just because this is the case doesn't mean that we need to do another // another layout however. - this.Location = this.displayLocation; - this.displayLocation = this.Location; + Location = displayLocation; + displayLocation = Location; } - if (AutoScroll || this.LayoutRequired) + if (AutoScroll || LayoutRequired) { // the base here forces a layout... we really only want to do this the first // time we pop the window... the subsequent times should be snappy. @@ -1499,7 +1499,7 @@ protected override void OnVisibleChanged(System.EventArgs e) } else { - this.SuspendLayout(); + SuspendLayout(); try { // scrollable control forces a layout here for scrollbar reasons only @@ -1509,7 +1509,7 @@ protected override void OnVisibleChanged(System.EventArgs e) } finally { - this.ResumeLayout(false); + ResumeLayout(false); } } } @@ -1517,7 +1517,7 @@ protected override void OnVisibleChanged(System.EventArgs e) protected override void OnParentChanged(System.EventArgs e) { base.OnParentChanged(e); - Rectangle bounds = this.Bounds; + Rectangle bounds = Bounds; SetBoundsCore(bounds.X, bounds.Y, bounds.Width, bounds.Height, BoundsSpecified.Location); } protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs mea) @@ -1546,7 +1546,7 @@ protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs mea) internal void OnOwnerItemFontChanged(EventArgs e) { - if (this.IsAutoGenerated) + if (IsAutoGenerated) { using (new LayoutTransaction(this, OwnerItem, PropertyNames.Font)) { @@ -1559,8 +1559,8 @@ internal void SelectPreviousToolStrip() { // snap the owner item before calling hide as non-auto created dropdowns will // exit menu mode if there's no OwnerItem. - ToolStripItem itemOnPreviousMenuToSelect = this.OwnerItem; - this.Hide(); + ToolStripItem itemOnPreviousMenuToSelect = OwnerItem; + Hide(); if (itemOnPreviousMenuToSelect != null) { @@ -1621,7 +1621,7 @@ internal override bool ProcessArrowKey(Keys keyCode) { // this is the case where you've casecaded out to a second level dropdown and you hit the back arrow // key. In this case we want to just hide the current dropdown - this.Visible = false; + Visible = false; return true; } else @@ -1674,7 +1674,7 @@ internal override bool ProcessArrowKey(Keys keyCode) protected override bool ProcessDialogKey(Keys keyData) { - if (this.OwnerItem != null && this.OwnerItem.IsInDesignMode) + if (OwnerItem != null && OwnerItem.IsInDesignMode) { return false; } @@ -1852,7 +1852,7 @@ protected override void ScaleControl(SizeF factor, BoundsSpecified specified) /// internal void SetAutoGeneratedInternal(bool autoGenerated) { - this.isAutoGenerated = autoGenerated; + isAutoGenerated = autoGenerated; } @@ -2051,7 +2051,7 @@ protected override void SetVisibleCore(bool visible) } // snap our bounds, we'll need it for some invalidation later. - Rectangle bounds = this.Bounds; + Rectangle bounds = Bounds; try { @@ -2172,14 +2172,14 @@ public void Show(Control control, Point position) SourceControlInternal = control; // When we have no owner item and we're set to RTL.Inherit, translate the coordinates // so that the menu looks like it's swooping from the other side - if (this.OwnerItem == null && control.RightToLeft == RightToLeft.Yes) + if (OwnerItem == null && control.RightToLeft == RightToLeft.Yes) { AdjustSize(); position.Offset(control.IsMirrored ? Width : -Width, 0); } - this.displayLocation = control.PointToScreen(position); - this.Location = this.displayLocation; + displayLocation = control.PointToScreen(position); + Location = displayLocation; ShowCore(); } @@ -2191,8 +2191,8 @@ public void Show(Control control, Point position, ToolStripDropDownDirection dir throw new ArgumentNullException(nameof(control)); } SourceControlInternal = control; - this.displayLocation = CalculateDropDownLocation(control.PointToScreen(position), direction).Location; - this.Location = this.displayLocation; + displayLocation = CalculateDropDownLocation(control.PointToScreen(position), direction).Location; + Location = displayLocation; ShowCore(); } @@ -2211,14 +2211,14 @@ public void Show(Control control, int x, int y) /// show relative to screen coordinates public void Show(Point screenLocation) { - this.displayLocation = screenLocation; - this.Location = this.displayLocation; + displayLocation = screenLocation; + Location = displayLocation; ShowCore(); } public void Show(Point position, ToolStripDropDownDirection direction) { - this.displayLocation = CalculateDropDownLocation(position, direction).Location; - this.Location = this.displayLocation; + displayLocation = CalculateDropDownLocation(position, direction).Location; + Location = displayLocation; ShowCore(); } @@ -2226,8 +2226,8 @@ public void Show(Point position, ToolStripDropDownDirection direction) /// show relative to screen coordinates public void Show(int x, int y) { - this.displayLocation = new Point(x, y); - this.Location = this.displayLocation; + displayLocation = new Point(x, y); + Location = displayLocation; ShowCore(); } @@ -2299,12 +2299,12 @@ protected override void WndProc(ref Message m) #region DropDownSpecific internal void DismissAll() { - ToolStripDropDown toplevel = this.GetFirstDropDown(); - toplevel.closeReason = this.closeReason; + ToolStripDropDown toplevel = GetFirstDropDown(); + toplevel.closeReason = closeReason; toplevel.DismissActiveDropDowns(); if (!LocalAppContextSwitches.UseLegacyContextMenuStripSourceControlValue) { - toplevel.saveSourceControl = this.saveSourceControl; + toplevel.saveSourceControl = saveSourceControl; } toplevel.Visible = false; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownButton.cs index ba35e36d959..22e52fcf663 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownButton.cs @@ -94,7 +94,7 @@ public bool ShowDropDownArrow if (showDropDownArrow != value) { showDropDownArrow = value; - this.InvalidateItemLayout(PropertyNames.ShowDropDownArrow); + InvalidateItemLayout(PropertyNames.ShowDropDownArrow); } } } @@ -139,7 +139,7 @@ protected override void OnMouseDown(MouseEventArgs e) // opening should happen on mouse down. Debug.Assert(ParentInternal != null, "Parent is null here, not going to get accurate ID"); openMouseId = (ParentInternal == null) ? (byte)0 : ParentInternal.GetMouseId(); - this.ShowDropDown(/*mousePush =*/true); + ShowDropDown(/*mousePush =*/true); } } base.OnMouseDown(e); @@ -173,9 +173,9 @@ protected override void OnMouseLeave(EventArgs e) protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { - if (this.Owner != null) + if (Owner != null) { - ToolStripRenderer renderer = this.Renderer; + ToolStripRenderer renderer = Renderer; Graphics g = e.Graphics; renderer.DrawDropDownButtonBackground(new ToolStripItemRenderEventArgs(e.Graphics, this)); @@ -187,7 +187,7 @@ protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) if ((DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) { - renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, this.Text, InternalLayout.TextRectangle, this.ForeColor, this.Font, InternalLayout.TextFormat)); + renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, Text, InternalLayout.TextRectangle, ForeColor, Font, InternalLayout.TextFormat)); } if (ShowDropDownArrow) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs index e0e1806c06f..7a19abb3c13 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs @@ -47,7 +47,7 @@ protected ToolStripDropDownItem(string text, Image image, params ToolStripItem[] { if (dropDownItems != null) { - this.DropDownItems.AddRange(dropDownItems); + DropDownItems.AddRange(dropDownItems); } } @@ -110,7 +110,7 @@ public ToolStripDropDown DropDown // the area which activates the dropdown. internal virtual Rectangle DropDownButtonArea { - get { return this.Bounds; } + get { return Bounds; } } [Browsable(false)] @@ -126,7 +126,7 @@ public ToolStripDropDownDirection DropDownDirection if (parent != null) { ToolStripDropDownDirection dropDownDirection = parent.DefaultDropDownDirection; - if (OppositeDropDownAlign || this.RightToLeft != parent.RightToLeft && (this.RightToLeft != RightToLeft.Inherit)) + if (OppositeDropDownAlign || RightToLeft != parent.RightToLeft && (RightToLeft != RightToLeft.Inherit)) { dropDownDirection = RTLTranslateDropDownDirection(dropDownDirection, RightToLeft); } @@ -328,21 +328,21 @@ private Rectangle DropDownDirectionToDropDownBounds(ToolStripDropDownDirection d switch (dropDownDirection) { case ToolStripDropDownDirection.AboveLeft: - offset.X = -dropDownBounds.Width + this.Width; + offset.X = -dropDownBounds.Width + Width; offset.Y = -dropDownBounds.Height + 1; break; case ToolStripDropDownDirection.AboveRight: offset.Y = -dropDownBounds.Height + 1; break; case ToolStripDropDownDirection.BelowRight: - offset.Y = this.Height - 1; + offset.Y = Height - 1; break; case ToolStripDropDownDirection.BelowLeft: - offset.X = -dropDownBounds.Width + this.Width; - offset.Y = this.Height - 1; + offset.X = -dropDownBounds.Width + Width; + offset.Y = Height - 1; break; case ToolStripDropDownDirection.Right: - offset.X = this.Width; + offset.X = Width; if (!IsOnDropDown) { // overlap the toplevel toolstrip @@ -355,7 +355,7 @@ private Rectangle DropDownDirectionToDropDownBounds(ToolStripDropDownDirection d break; } - Point itemScreenLocation = this.TranslatePoint(Point.Empty, ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ScreenCoords); + Point itemScreenLocation = TranslatePoint(Point.Empty, ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ScreenCoords); dropDownBounds.Location = new Point(itemScreenLocation.X + offset.X, itemScreenLocation.Y + offset.Y); dropDownBounds = WindowsFormsUtils.ConstrainToScreenWorkingAreaBounds(dropDownBounds); return dropDownBounds; @@ -381,7 +381,7 @@ private void DropDown_ItemClicked(object sender, ToolStripItemClickedEventArgs e /// protected override void Dispose(bool disposing) { - if (this.dropDown != null) + if (dropDown != null) { dropDown.Opened -= new EventHandler(DropDown_Opened); dropDown.Closed -= new ToolStripDropDownClosedEventHandler(DropDown_Closed); @@ -406,7 +406,7 @@ private Rectangle GetDropDownBounds(ToolStripDropDownDirection dropDownDirection dropDownBounds = DropDownDirectionToDropDownBounds(dropDownDirection, dropDownBounds); // we should make sure we dont obscure the owner item. - Rectangle itemScreenBounds = new Rectangle(this.TranslatePoint(Point.Empty, ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ScreenCoords), this.Size); + Rectangle itemScreenBounds = new Rectangle(TranslatePoint(Point.Empty, ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ScreenCoords), Size); if (Rectangle.Intersect(dropDownBounds, itemScreenBounds).Height > 1) { @@ -440,7 +440,7 @@ public void HideDropDown() // consider - CloseEventArgs to prevent shutting down. OnDropDownHide(EventArgs.Empty); - if (this.dropDown != null && this.dropDown.Visible) + if (dropDown != null && dropDown.Visible) { DropDown.Visible = false; @@ -463,9 +463,9 @@ protected override void OnBoundsChanged() { base.OnBoundsChanged(); //Reset the Bounds... - if (this.dropDown != null && this.dropDown.Visible) + if (dropDown != null && dropDown.Visible) { - this.dropDown.Bounds = GetDropDownBounds(DropDownDirection); + dropDown.Bounds = GetDropDownBounds(DropDownDirection); } } @@ -501,7 +501,7 @@ internal override void OnImageScalingSizeChanged(EventArgs e) /// protected virtual void OnDropDownHide(EventArgs e) { - this.Invalidate(); + Invalidate(); EventHandler handler = (EventHandler)Events[EventDropDownHide]; if (handler != null) @@ -540,7 +540,7 @@ protected internal virtual void OnDropDownOpened(System.EventArgs e) protected internal virtual void OnDropDownClosed(System.EventArgs e) { // only send the event if we're the thing that currently owns the DropDown. - this.Invalidate(); + Invalidate(); if (DropDown.OwnerItem == this) { @@ -601,9 +601,9 @@ protected internal override bool ProcessDialogKey(Keys keyData) if (Enabled || DesignMode) { // |__[ * File ]_____| * is where you are. Up or down arrow hit should expand menu - this.ShowDropDown(); + ShowDropDown(); KeyboardToolTipStateMachine.Instance.NotifyAboutLostFocus(this); - this.DropDown.SelectNextToolStripItem(null, true); + DropDown.SelectNextToolStripItem(null, true); }// else eat the key return true; @@ -624,9 +624,9 @@ protected internal override bool ProcessDialogKey(Keys keyData) if (Enabled || DesignMode) { - this.ShowDropDown(); + ShowDropDown(); KeyboardToolTipStateMachine.Instance.NotifyAboutLostFocus(this); - this.DropDown.SelectNextToolStripItem(null, true); + DropDown.SelectNextToolStripItem(null, true); } // else eat the key return true; } @@ -707,13 +707,13 @@ private ToolStripDropDownDirection RTLTranslateDropDownDirection(ToolStripDropDo /// public void ShowDropDown() { - this.ShowDropDown(false); + ShowDropDown(false); } internal void ShowDropDown(bool mousePush) { - this.ShowDropDownInternal(); - ToolStripDropDownMenu menu = this.dropDown as ToolStripDropDownMenu; + ShowDropDownInternal(); + ToolStripDropDownMenu menu = dropDown as ToolStripDropDownMenu; if (menu != null) { if (!mousePush) @@ -727,7 +727,7 @@ internal void ShowDropDown(bool mousePush) private void ShowDropDownInternal() { - if (this.dropDown == null || (!this.dropDown.Visible)) + if (dropDown == null || (!dropDown.Visible)) { // We want to show if there's no dropdown // or if the dropdown is not visible. @@ -737,23 +737,23 @@ private void ShowDropDownInternal() // the act of setting the drop down visible the first time sets the parent // it seems that GetVisibleCore returns true if your parent is null. - if (this.dropDown != null && !this.dropDown.Visible) + if (dropDown != null && !dropDown.Visible) { - if (this.dropDown.IsAutoGenerated && this.DropDownItems.Count <= 0) + if (dropDown.IsAutoGenerated && DropDownItems.Count <= 0) { return; // this is a no-op for autogenerated drop downs. } - if (this.DropDown == this.ParentInternal) + if (DropDown == ParentInternal) { throw new InvalidOperationException(SR.ToolStripShowDropDownInvalidOperation); } - this.dropDown.OwnerItem = this; - this.dropDown.Location = DropDownLocation; - this.dropDown.Show(); - this.Invalidate(); + dropDown.OwnerItem = this; + dropDown.Location = DropDownLocation; + dropDown.Show(); + Invalidate(); AccessibilityNotifyClients(AccessibleEvents.StateChange); AccessibilityNotifyClients(AccessibleEvents.NameChange); @@ -778,13 +778,13 @@ private bool ShouldSerializeDropDownItems() internal override void OnKeyboardToolTipHook(ToolTip toolTip) { base.OnKeyboardToolTipHook(toolTip); - KeyboardToolTipStateMachine.Instance.Hook(this.DropDown, toolTip); + KeyboardToolTipStateMachine.Instance.Hook(DropDown, toolTip); } internal override void OnKeyboardToolTipUnhook(ToolTip toolTip) { base.OnKeyboardToolTipUnhook(toolTip); - KeyboardToolTipStateMachine.Instance.Unhook(this.DropDown, toolTip); + KeyboardToolTipStateMachine.Instance.Unhook(DropDown, toolTip); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownMenu.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownMenu.cs index dcb74056dc6..af7549a70e9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownMenu.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownMenu.cs @@ -143,7 +143,7 @@ public override Rectangle DisplayRectangle rect.Y += UpScrollButton.Height + UpScrollButton.Margin.Vertical; rect.Height -= UpScrollButton.Height + UpScrollButton.Margin.Vertical + DownScrollButton.Height + DownScrollButton.Margin.Vertical; // Because we're going to draw the scroll buttons on top of the padding, we need to add it back in here. - rect = LayoutUtils.InflateRect(rect, new Padding(0, this.Padding.Top, 0, this.Padding.Bottom)); + rect = LayoutUtils.InflateRect(rect, new Padding(0, Padding.Top, 0, Padding.Bottom)); } return rect; } @@ -197,7 +197,7 @@ internal Rectangle ImageMargin { get { - imageMarginBounds.Height = this.Height; + imageMarginBounds.Height = Height; return imageMarginBounds; } } @@ -389,7 +389,7 @@ private void CalculateInternalLayoutMetrics() Size shortcutTextSize = menuItem.GetShortcutTextSize(); if (tabWidth == -1) { - tabWidth = TextRenderer.MeasureText("\t", this.Font).Width; + tabWidth = TextRenderer.MeasureText("\t", Font).Width; } menuItemTextSize.Width += tabWidth + shortcutTextSize.Width; menuItemTextSize.Height = Math.Max(menuItemTextSize.Height, shortcutTextSize.Height); @@ -423,12 +423,12 @@ private void CalculateInternalLayoutMetrics() } } - this.maxItemSize.Height = Math.Max(maxTextSize.Height + scaledTextPadding.Vertical, Math.Max(maxCheckSize.Height + scaledCheckPadding.Vertical, maxArrowSize.Height + scaledArrowPadding.Vertical)); + maxItemSize.Height = Math.Max(maxTextSize.Height + scaledTextPadding.Vertical, Math.Max(maxCheckSize.Height + scaledCheckPadding.Vertical, maxArrowSize.Height + scaledArrowPadding.Vertical)); if (ShowImageMargin) { // only add in the image into the calculation if we're going to render it. - this.maxItemSize.Height = Math.Max(maxImageSize.Height + scaledImagePadding.Vertical, maxItemSize.Height); + maxItemSize.Height = Math.Max(maxImageSize.Height + scaledImagePadding.Vertical, maxItemSize.Height); } bool useDefaultCheckMarginWidth = (ShowCheckMargin && (maxCheckSize.Width == 0)); @@ -514,7 +514,7 @@ private void CalculateInternalLayoutMetrics() // consider: should we constrain to a reasonable width? //imageMarginBounds = new Rectangle(0, 0, Math.Max(imageMarginWidth,DefaultImageMarginWidth), this.Height); - imageMarginBounds = new Rectangle(0, 0, checkAndImageMarginWidth, this.Height); + imageMarginBounds = new Rectangle(0, 0, checkAndImageMarginWidth, Height); // calculate space for shortcut and text nextPoint.X = imageMarginBounds.Right + scaledTextPadding.Left; @@ -527,9 +527,9 @@ private void CalculateInternalLayoutMetrics() arrowRectangle = new Rectangle(nextPoint, maxArrowSize); // calculate space required for all of these pieces - this.maxItemSize.Width = (arrowRectangle.Right + scaledArrowPadding.Right) - imageMarginBounds.Left; + maxItemSize.Width = (arrowRectangle.Right + scaledArrowPadding.Right) - imageMarginBounds.Left; - this.Padding = DefaultPadding; + Padding = DefaultPadding; int trimPadding = imageMarginBounds.Width; if (RightToLeft == RightToLeft.Yes) @@ -555,12 +555,12 @@ private void CalculateInternalLayoutMetrics() // systems which force the text rectangle to be odd. // force this to be an even height. - this.maxItemSize.Height += this.maxItemSize.Height % 2; + maxItemSize.Height += maxItemSize.Height % 2; textRectangle.Y = LayoutUtils.VAlign(textRectangle.Size, new Rectangle(Point.Empty, maxItemSize), ContentAlignment.MiddleCenter).Y; textRectangle.Y += (textRectangle.Height % 2); // if the height is odd, push down by one px state[stateMaxItemSizeValid] = true; - this.PaddingToTrim = trimPadding; + PaddingToTrim = trimPadding; } @@ -582,12 +582,12 @@ internal override void ChangeSelection(ToolStripItem nextItem) { delta = nextItem.Bounds.Bottom - (displayRect.Y + displayRect.Height); // Now adjust so that the item at the top isn't truncated. - int index = this.Items.IndexOf(nextItem); + int index = Items.IndexOf(nextItem); while (index >= 0) { // we need to roll back to the index which is visible - if ((this.Items[index].Visible && displayRect.Contains(displayRect.X, this.Items[index].Bounds.Top - delta)) - || !this.Items[index].Visible) + if ((Items[index].Visible && displayRect.Contains(displayRect.X, Items[index].Bounds.Top - delta)) + || !Items[index].Visible) { --index; } @@ -599,15 +599,15 @@ internal override void ChangeSelection(ToolStripItem nextItem) if (index >= 0) { - if (displayRect.Contains(displayRect.X, this.Items[index].Bounds.Bottom - delta)) + if (displayRect.Contains(displayRect.X, Items[index].Bounds.Bottom - delta)) { // We found an item which is truncated at the top. - delta += (this.Items[index].Bounds.Bottom - delta) - displayRect.Top; + delta += (Items[index].Bounds.Bottom - delta) - displayRect.Top; } } } - this.ScrollInternal(delta); - this.UpdateScrollButtonStatus(); + ScrollInternal(delta); + UpdateScrollButtonStatus(); } } base.ChangeSelection(nextItem); @@ -634,23 +634,23 @@ internal override ToolStripItem GetNextItem(ToolStripItem start, ArrowDirection internal override void Initialize() { base.Initialize(); - this.Padding = DefaultPadding; + Padding = DefaultPadding; FlowLayoutSettings settings = FlowLayout.CreateSettings(this); settings.FlowDirection = FlowDirection.TopDown; state[stateShowImageMargin] = true; } protected override void OnLayout(LayoutEventArgs e) { - if (!this.IsDisposed) + if (!IsDisposed) { // We always layout as if we don't need scroll buttons. // If we do, then we'll adjust the positions to match. - this.RequiresScrollButtons = false; + RequiresScrollButtons = false; CalculateInternalLayoutMetrics(); base.OnLayout(e); - if (!this.RequiresScrollButtons) + if (!RequiresScrollButtons) { - this.ResetScrollPosition(); + ResetScrollPosition(); } } } @@ -666,7 +666,7 @@ protected override void OnPaintBackground(PaintEventArgs e) base.OnPaintBackground(e); if (ShowCheckMargin || ShowImageMargin) { - Renderer.DrawImageMargin(new ToolStripRenderEventArgs(e.Graphics, this, this.ImageMargin, SystemColors.Control)); + Renderer.DrawImageMargin(new ToolStripRenderEventArgs(e.Graphics, this, ImageMargin, SystemColors.Control)); } } @@ -683,11 +683,11 @@ internal override bool RequiresScrollButtons if (changed) { UpdateScrollButtonLocations(); - if (this.Items.Count > 0) + if (Items.Count > 0) { - int delta = this.Items[0].Bounds.Top - this.DisplayRectangle.Top; - this.ScrollInternal(delta); - this.scrollAmount -= delta; + int delta = Items[0].Bounds.Top - DisplayRectangle.Top; + ScrollInternal(delta); + scrollAmount -= delta; if (value) { RestoreScrollPosition(); @@ -695,7 +695,7 @@ internal override bool RequiresScrollButtons } else { - this.scrollAmount = 0; + scrollAmount = 0; } } } @@ -703,12 +703,12 @@ internal override bool RequiresScrollButtons internal void ResetScrollPosition() { - this.scrollAmount = 0; + scrollAmount = 0; } internal void RestoreScrollPosition() { - if (!RequiresScrollButtons || this.Items.Count == 0) + if (!RequiresScrollButtons || Items.Count == 0) { return; } @@ -719,19 +719,19 @@ internal void RestoreScrollPosition() // This also deals with items of different height, so that we don't truncate // and items under the top scrollbar. - Rectangle displayRectangle = this.DisplayRectangle; - int alreadyScrolled = displayRectangle.Top - this.Items[0].Bounds.Top; + Rectangle displayRectangle = DisplayRectangle; + int alreadyScrolled = displayRectangle.Top - Items[0].Bounds.Top; - int requiredScrollAmount = this.scrollAmount - alreadyScrolled; + int requiredScrollAmount = scrollAmount - alreadyScrolled; int deltaToScroll = 0; if (requiredScrollAmount > 0) { - for (int i = 0; i < this.Items.Count && deltaToScroll < requiredScrollAmount; ++i) + for (int i = 0; i < Items.Count && deltaToScroll < requiredScrollAmount; ++i) { - if (this.Items[i].Available) + if (Items[i].Available) { - Rectangle adjustedLastItemBounds = this.Items[this.Items.Count - 1].Bounds; + Rectangle adjustedLastItemBounds = Items[Items.Count - 1].Bounds; adjustedLastItemBounds.Y -= deltaToScroll; if (displayRectangle.Contains(displayRectangle.X, adjustedLastItemBounds.Top) && displayRectangle.Contains(displayRectangle.X, adjustedLastItemBounds.Bottom)) @@ -741,24 +741,24 @@ internal void RestoreScrollPosition() } // We use a delta between the tops, since it takes margin's and padding into account. - if (i < this.Items.Count - 1) + if (i < Items.Count - 1) { - deltaToScroll += this.Items[i + 1].Bounds.Top - this.Items[i].Bounds.Top; + deltaToScroll += Items[i + 1].Bounds.Top - Items[i].Bounds.Top; } else { - deltaToScroll += this.Items[i].Bounds.Height; + deltaToScroll += Items[i].Bounds.Height; } } } } else { - for (int i = this.Items.Count - 1; i >= 0 && deltaToScroll > requiredScrollAmount; --i) + for (int i = Items.Count - 1; i >= 0 && deltaToScroll > requiredScrollAmount; --i) { - if (this.Items[i].Available) + if (Items[i].Available) { - Rectangle adjustedLastItemBounds = this.Items[0].Bounds; + Rectangle adjustedLastItemBounds = Items[0].Bounds; adjustedLastItemBounds.Y -= deltaToScroll; if (displayRectangle.Contains(displayRectangle.X, adjustedLastItemBounds.Top) && displayRectangle.Contains(displayRectangle.X, adjustedLastItemBounds.Bottom)) @@ -770,17 +770,17 @@ internal void RestoreScrollPosition() // We use a delta between the tops, since it takes margin's and padding into account. if (i > 0) { - deltaToScroll -= this.Items[i].Bounds.Top - this.Items[i - 1].Bounds.Top; + deltaToScroll -= Items[i].Bounds.Top - Items[i - 1].Bounds.Top; } else { - deltaToScroll -= this.Items[i].Bounds.Height; + deltaToScroll -= Items[i].Bounds.Height; } } } } - this.ScrollInternal(deltaToScroll); - this.scrollAmount = this.DisplayRectangle.Top - this.Items[0].Bounds.Top; + ScrollInternal(deltaToScroll); + scrollAmount = DisplayRectangle.Top - Items[0].Bounds.Top; UpdateScrollButtonLocations(); } @@ -788,7 +788,7 @@ internal void RestoreScrollPosition() internal override void ScrollInternal(int delta) { base.ScrollInternal(delta); - this.scrollAmount += delta; + scrollAmount += delta; } internal void ScrollInternal(bool up) @@ -798,7 +798,7 @@ internal void ScrollInternal(bool up) // calling this to get ScrollWindowEx. In actuality it does nothing // to change the display rect! int delta; - if (this.indexOfFirstDisplayedItem == -1 || this.indexOfFirstDisplayedItem >= this.Items.Count) + if (indexOfFirstDisplayedItem == -1 || indexOfFirstDisplayedItem >= Items.Count) { Debug.Fail("Why wasn't 'UpdateScrollButtonStatus called'? We don't have the item to scroll by"); int menuHeight = SystemInformation.MenuHeight; @@ -809,29 +809,29 @@ internal void ScrollInternal(bool up) { if (up) { - if (this.indexOfFirstDisplayedItem == 0) + if (indexOfFirstDisplayedItem == 0) { Debug.Fail("We're trying to scroll up, but the top item is displayed!!!"); delta = 0; } else { - ToolStripItem itemTop = this.Items[this.indexOfFirstDisplayedItem - 1]; - ToolStripItem itemBottom = this.Items[this.indexOfFirstDisplayedItem]; + ToolStripItem itemTop = Items[indexOfFirstDisplayedItem - 1]; + ToolStripItem itemBottom = Items[indexOfFirstDisplayedItem]; // We use a delta between the tops, since it takes margin's and padding into account. delta = itemTop.Bounds.Top - itemBottom.Bounds.Top; } } else { - if (this.indexOfFirstDisplayedItem == this.Items.Count - 1) + if (indexOfFirstDisplayedItem == Items.Count - 1) { Debug.Fail("We're trying to scroll down, but the top item is displayed!!!"); delta = 0; } - ToolStripItem itemTop = this.Items[this.indexOfFirstDisplayedItem]; - ToolStripItem itemBottom = this.Items[this.indexOfFirstDisplayedItem + 1]; + ToolStripItem itemTop = Items[indexOfFirstDisplayedItem]; + ToolStripItem itemBottom = Items[indexOfFirstDisplayedItem + 1]; // We use a delta between the tops, since it takes margin's and padding into account. delta = itemBottom.Bounds.Top - itemTop.Bounds.Top; } @@ -847,8 +847,8 @@ protected override void SetDisplayedItems() if (RequiresScrollButtons) { - this.DisplayedItems.Add(UpScrollButton); - this.DisplayedItems.Add(DownScrollButton); + DisplayedItems.Add(UpScrollButton); + DisplayedItems.Add(DownScrollButton); UpdateScrollButtonLocations(); UpScrollButton.Visible = true; DownScrollButton.Visible = true; @@ -872,7 +872,7 @@ private void UpdateScrollButtonLocations() UpScrollButton.SetBounds(new Rectangle(upLocation, upSize)); Size downSize = DownScrollButton.GetPreferredSize(Size.Empty); - int height = GetDropDownBounds(this.Bounds).Height; + int height = GetDropDownBounds(Bounds).Height; Point downLocation = new Point(1, height - downSize.Height); DownScrollButton.SetBounds(new Rectangle(downLocation, downSize)); @@ -883,14 +883,14 @@ private void UpdateScrollButtonLocations() private void UpdateScrollButtonStatus() { - Rectangle displayRectangle = this.DisplayRectangle; + Rectangle displayRectangle = DisplayRectangle; - this.indexOfFirstDisplayedItem = -1; + indexOfFirstDisplayedItem = -1; int minY = int.MaxValue, maxY = 0; - for (int i = 0; i < this.Items.Count; ++i) + for (int i = 0; i < Items.Count; ++i) { - ToolStripItem item = this.Items[i]; + ToolStripItem item = Items[i]; if (UpScrollButton == item) { continue; @@ -905,9 +905,9 @@ private void UpdateScrollButtonStatus() continue; } - if (this.indexOfFirstDisplayedItem == -1 && displayRectangle.Contains(displayRectangle.X, item.Bounds.Top)) + if (indexOfFirstDisplayedItem == -1 && displayRectangle.Contains(displayRectangle.X, item.Bounds.Top)) { - this.indexOfFirstDisplayedItem = i; + indexOfFirstDisplayedItem = i; } minY = Math.Min(minY, item.Bounds.Top); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripGrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripGrip.cs index 797312c6254..673f5ae8258 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripGrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripGrip.cs @@ -96,11 +96,11 @@ internal bool MovingToolStrip lastEndLocation = ToolStrip.InvalidMouseEnter; if (movingToolStrip) { - ((ISupportToolStripPanel)this.ParentInternal).BeginDrag(); + ((ISupportToolStripPanel)ParentInternal).BeginDrag(); } else { - ((ISupportToolStripPanel)this.ParentInternal).EndDrag(); + ((ISupportToolStripPanel)ParentInternal).EndDrag(); } } } @@ -123,15 +123,15 @@ protected override AccessibleObject CreateAccessibilityInstance() public override Size GetPreferredSize(Size constrainingSize) { Size preferredSize = Size.Empty; - if (this.ParentInternal != null) + if (ParentInternal != null) { - if (this.ParentInternal.LayoutStyle == ToolStripLayoutStyle.VerticalStackWithOverflow) + if (ParentInternal.LayoutStyle == ToolStripLayoutStyle.VerticalStackWithOverflow) { - preferredSize = new Size(this.ParentInternal.Width, gripThickness); + preferredSize = new Size(ParentInternal.Width, gripThickness); } else { - preferredSize = new Size(gripThickness, this.ParentInternal.Height); + preferredSize = new Size(gripThickness, ParentInternal.Height); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs index 960a19ef8f9..15fa42b5f4a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs @@ -189,11 +189,11 @@ protected ToolStripItem() state[stateEnabled | stateAutoSize | stateVisible | stateContstructing | stateSupportsItemClick | stateInvalidMirroredImage | stateMouseDownAndUpMustBeInSameItem | stateUseAmbientMargin] = true; state[stateAllowDrop | stateMouseDownAndNoDrag | stateSupportsRightClick | statePressed | stateSelected | stateDisposed | stateDoubleClickEnabled | stateRightToLeftAutoMirrorImage | stateSupportsSpaceKey] = false; SetAmbientMargin(); - this.Size = DefaultSize; - this.DisplayStyle = DefaultDisplayStyle; + Size = DefaultSize; + DisplayStyle = DefaultDisplayStyle; CommonProperties.SetAutoSize(this, true); state[stateContstructing] = false; - this.AutoToolTip = DefaultAutoToolTip; + AutoToolTip = DefaultAutoToolTip; } @@ -205,13 +205,13 @@ protected ToolStripItem(string text, Image image, EventHandler onClick) : this(t [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] protected ToolStripItem(string text, Image image, EventHandler onClick, string name) : this() { - this.Text = text; - this.Image = image; + Text = text; + Image = image; if (onClick != null) { Click += onClick; } - this.Name = name; + Name = name; } /// @@ -368,9 +368,9 @@ public ToolStripItemAlignment Alignment { alignment = value; - if ((this.ParentInternal != null) && this.ParentInternal.IsHandleCreated) + if ((ParentInternal != null) && ParentInternal.IsHandleCreated) { - this.ParentInternal.PerformLayout(); + ParentInternal.PerformLayout(); } } } @@ -624,7 +624,7 @@ public Rectangle ContentRectangle { get { - Rectangle content = LayoutUtils.InflateRect(InternalLayout.ContentRectangle, this.Padding); + Rectangle content = LayoutUtils.InflateRect(InternalLayout.ContentRectangle, Padding); content.Size = LayoutUtils.UnionSizes(Size.Empty, content.Size); return content; } @@ -741,7 +741,7 @@ protected internal virtual Padding DefaultMargin { get { - if (this.Owner != null && this.Owner is StatusStrip) + if (Owner != null && Owner is StatusStrip) { return scaledDefaultStatusStripMargin; } @@ -954,9 +954,9 @@ public virtual bool Enabled { bool parentEnabled = true; - if (this.Owner != null) + if (Owner != null) { - parentEnabled = this.Owner.Enabled; + parentEnabled = Owner.Enabled; } return state[stateEnabled] && parentEnabled; @@ -1125,7 +1125,7 @@ public int Height } set { - Rectangle currentBounds = this.Bounds; + Rectangle currentBounds = Bounds; SetBounds(currentBounds.X, currentBounds.Y, currentBounds.Width, value); } } @@ -1148,11 +1148,11 @@ IArrangedElement IArrangedElement.Container { get { - if (this.ParentInternal == null) + if (ParentInternal == null) { - return this.Owner; + return Owner; } - return this.ParentInternal; + return ParentInternal; } } @@ -1160,7 +1160,7 @@ Rectangle IArrangedElement.DisplayRectangle { get { - return this.Bounds; + return Bounds; } } @@ -1180,7 +1180,7 @@ PropertyStore IArrangedElement.Properties { get { - return this.Properties; + return Properties; } } @@ -1345,7 +1345,7 @@ public int ImageIndex { return Owner.ImageList.Images.Count - 1; } - return this.ImageIndexer.Index; + return ImageIndexer.Index; } set { @@ -1395,7 +1395,7 @@ public string ImageKey { get { - return this.ImageIndexer.Key; + return ImageIndexer.Key; } set { @@ -1523,7 +1523,7 @@ public bool IsOnOverflow { get { - return (this.Placement == ToolStripItemPlacement.Overflow); + return (Placement == ToolStripItemPlacement.Overflow); } } @@ -1764,7 +1764,7 @@ public ToolStrip Owner { get { - return this.owner; + return owner; } set { @@ -1886,7 +1886,7 @@ public ToolStripItemOverflow Overflow overflow = value; if (Owner != null) { - LayoutTransaction.DoLayout(Owner, this.Owner, "Overflow"); + LayoutTransaction.DoLayout(Owner, Owner, "Overflow"); } } } @@ -2405,7 +2405,7 @@ public virtual ToolStripTextDirection TextDirection if (textDirection == ToolStripTextDirection.Inherit) { - if (this.ParentInternal != null) + if (ParentInternal != null) { // in the case we're on a ToolStripOverflow textDirection = ParentInternal.TextDirection; @@ -2526,7 +2526,7 @@ public int Width } set { - Rectangle currentBounds = this.Bounds; + Rectangle currentBounds = Bounds; SetBounds(currentBounds.X, currentBounds.Y, value, currentBounds.Height); } } @@ -2562,7 +2562,7 @@ private void Animate(bool animate) { if (Image != null) { - ImageAnimator.Animate(Image, new EventHandler(this.OnAnimationFrameChanged)); + ImageAnimator.Animate(Image, new EventHandler(OnAnimationFrameChanged)); state[stateCurrentlyAnimatingImage] = animate; } } @@ -2570,7 +2570,7 @@ private void Animate(bool animate) { if (Image != null) { - ImageAnimator.StopAnimate(Image, new EventHandler(this.OnAnimationFrameChanged)); + ImageAnimator.StopAnimate(Image, new EventHandler(OnAnimationFrameChanged)); state[stateCurrentlyAnimatingImage] = animate; } } @@ -2583,7 +2583,7 @@ internal bool BeginDragForItemReorder() if (Control.ModifierKeys == Keys.Alt) { - if (this.ParentInternal.Items.Contains(this) && this.ParentInternal.AllowItemReorder) + if (ParentInternal.Items.Contains(this) && ParentInternal.AllowItemReorder) { // we only drag ToolStripItem item = this as ToolStripItem; @@ -2624,11 +2624,11 @@ protected override void Dispose(bool disposing) { state[stateDisposing] = true; - if (this.Owner != null) + if (Owner != null) { StopAnimate(); - Debug.Assert(this.Owner.Items.Contains(this), "How can there be a owner and not be in the collection?"); - this.Owner.Items.Remove(this); + Debug.Assert(Owner.Items.Contains(this), "How can there be a owner and not be in the collection?"); + Owner.Items.Remove(this); toolStripItemInternalLayout = null; state[stateDisposed] = true; } @@ -2665,7 +2665,7 @@ internal static long DoubleClickTicks public DragDropEffects DoDragDrop(object data, DragDropEffects allowedEffects) { int[] finalEffect = new int[] { (int)DragDropEffects.None }; - UnsafeNativeMethods.IOleDropSource dropSource = this.DropSource; + UnsafeNativeMethods.IOleDropSource dropSource = DropSource; IComDataObject dataObject = null; dataObject = data as IComDataObject; @@ -2815,7 +2815,7 @@ private Font GetOwnerFont() /// except for things like the overflow button public ToolStrip GetCurrentParent() { - return this.Parent; + return Parent; } internal ToolStripDropDown GetCurrentParentDropDown() { @@ -2856,9 +2856,9 @@ internal Size GetTextSize() /// public void Invalidate() { - if (this.ParentInternal != null) + if (ParentInternal != null) { - ParentInternal.Invalidate(this.Bounds, true); + ParentInternal.Invalidate(Bounds, true); } } @@ -2871,9 +2871,9 @@ public void Invalidate(Rectangle r) // the only value add to this over calling invalidate on the ToolStrip is that // you can specify the rectangle with coordinates relative to the upper left hand // corner of the ToolStripItem. - Point rectangleLocation = this.TranslatePoint(r.Location, ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ToolStripCoords); + Point rectangleLocation = TranslatePoint(r.Location, ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ToolStripCoords); - if (this.ParentInternal != null) + if (ParentInternal != null) { ParentInternal.Invalidate(new Rectangle(rectangleLocation, r.Size), true); } @@ -2881,7 +2881,7 @@ public void Invalidate(Rectangle r) internal void InvalidateItemLayout(string affectedProperty, bool invalidatePainting) { - this.toolStripItemInternalLayout = null; + toolStripItemInternalLayout = null; if (Owner != null) { @@ -2910,9 +2910,9 @@ internal void InvalidateImageListImage() internal void InvokePaint() { - if (this.ParentInternal != null) + if (ParentInternal != null) { - this.ParentInternal.InvokePaintItem(this); + ParentInternal.InvokePaintItem(this); } } @@ -2932,7 +2932,7 @@ protected internal virtual bool IsInputChar(char charCode) private void HandleClick(System.EventArgs e) { - Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] HandleClick"); + Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + Text + "] HandleClick"); try { @@ -2946,7 +2946,7 @@ private void HandleClick(System.EventArgs e) if (SupportsItemClick && Owner != null) { - Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] HandleItemClick"); + Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + Text + "] HandleItemClick"); Owner.HandleItemClick(this); } @@ -2954,7 +2954,7 @@ private void HandleClick(System.EventArgs e) if (SupportsItemClick && Owner != null) { - Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] HandleItemClicked"); + Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + Text + "] HandleItemClicked"); Owner.HandleItemClicked(this); } } @@ -2973,7 +2973,7 @@ private void HandleDoubleClick(System.EventArgs e) private void HandlePaint(PaintEventArgs e) { Animate(); - ImageAnimator.UpdateFrames(this.Image); + ImageAnimator.UpdateFrames(Image); OnPaint(e); RaisePaintEvent(EventPaint, e); @@ -2999,7 +2999,7 @@ private void HandleMouseEnter(System.EventArgs e) // Same as Control.MouseButtons == MouseButtons.Left, but slightly more efficient. if (UnsafeNativeMethods.GetKeyState((int)Keys.LButton) < 0) { - this.Push(true); + Push(true); } } @@ -3018,14 +3018,14 @@ private void HandleMouseEnter(System.EventArgs e) if (Enabled) { OnMouseEnter(e); - Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] MouseEnter"); + Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + Text + "] MouseEnter"); RaiseEvent(EventMouseEnter, e); } } private void HandleMouseMove(System.Windows.Forms.MouseEventArgs mea) { - Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] MouseMove"); + Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + Text + "] MouseMove"); if (Enabled && CanSelect && !Selected) { @@ -3046,7 +3046,7 @@ private void HandleMouseMove(System.Windows.Forms.MouseEventArgs mea) } private void HandleMouseHover(EventArgs e) { - Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] MouseHover"); + Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + Text + "] MouseHover"); OnMouseHover(e); RaiseEvent(EventMouseHover, e); } @@ -3063,7 +3063,7 @@ private void HandleLeave() } private void HandleMouseLeave(System.EventArgs e) { - Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] MouseLeave"); + Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + Text + "] MouseLeave"); HandleLeave(); if (Enabled) { @@ -3073,14 +3073,14 @@ private void HandleMouseLeave(System.EventArgs e) } private void HandleMouseDown(MouseEventArgs e) { - Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] MouseDown"); + Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + Text + "] MouseDown"); state[stateMouseDownAndNoDrag] = !BeginDragForItemReorder(); if (state[stateMouseDownAndNoDrag]) { if (e.Button == MouseButtons.Left) { - this.Push(true); + Push(true); } // OnMouseDown(e); @@ -3090,7 +3090,7 @@ private void HandleMouseDown(MouseEventArgs e) private void HandleMouseUp(MouseEventArgs e) { - Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + this.Text + "] MouseUp"); + Debug.WriteLineIf(MouseDebugging.TraceVerbose, "[" + Text + "] MouseUp"); bool fireMouseUp = (ParentInternal.LastMouseDownedItem == this); @@ -3107,7 +3107,7 @@ private void HandleMouseUp(MouseEventArgs e) if (state[stateMouseDownAndNoDrag] || fireMouseUp) { - this.Push(false); + Push(false); if (e.Button == MouseButtons.Left || (e.Button == MouseButtons.Right && state[stateSupportsRightClick])) { @@ -3162,13 +3162,13 @@ internal virtual void OnAccessibleRoleChanged(EventArgs e) [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnBackColorChanged(EventArgs e) { - this.Invalidate(); + Invalidate(); RaiseEvent(EventBackColorChanged, e); } protected virtual void OnBoundsChanged() { - LayoutTransaction.DoLayout(this.ParentInternal, this, PropertyNames.Bounds); + LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.Bounds); InternalLayout.PerformLayout(); } @@ -3228,7 +3228,7 @@ private void OnAnimationFrameChanged(object o, EventArgs e) if (parent.IsHandleCreated && parent.InvokeRequired) { - parent.BeginInvoke(new EventHandler(this.OnAnimationFrameChanged), new object[] { o, e }); + parent.BeginInvoke(new EventHandler(OnAnimationFrameChanged), new object[] { o, e }); return; } @@ -3346,7 +3346,7 @@ internal void OnInternalEnabledChanged(System.EventArgs e) [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnForeColorChanged(EventArgs e) { - this.Invalidate(); + Invalidate(); RaiseEvent(EventForeColorChanged, e); } @@ -3357,11 +3357,11 @@ protected virtual void OnFontChanged(EventArgs e) // PERF - only invalidate if we actually care about the font if ((DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) { - this.InvalidateItemLayout(PropertyNames.Font); + InvalidateItemLayout(PropertyNames.Font); } else { - this.toolStripItemInternalLayout = null; + toolStripItemInternalLayout = null; } RaiseEvent(EventFontChanged, e); } @@ -3588,7 +3588,7 @@ internal void Push(bool push) state[statePressed] = push; if (Available) { - this.Invalidate(); + Invalidate(); } } } @@ -3694,7 +3694,7 @@ public void Select() // let's not snap the stack trace unless we're debugging selection. if (ToolStrip.SelectionDebug.TraceVerbose) { - Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "[Selection DBG] WBI.Select: {0} \r\n{1}\r\n", this.ToString(), new StackTrace().ToString().Substring(0, 200))); + Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "[Selection DBG] WBI.Select: {0} \r\n{1}\r\n", ToString(), new StackTrace().ToString().Substring(0, 200))); } #endif if (!CanSelect) @@ -3747,14 +3747,14 @@ internal void SetOwner(ToolStrip newOwner) { if (owner != newOwner) { - Font f = this.Font; + Font f = Font; owner = newOwner; // clear the parent if the owner is null... // if (newOwner == null) { - this.ParentInternal = null; + ParentInternal = null; } if (!state[stateDisposing] && !IsDisposed) { @@ -4128,9 +4128,9 @@ internal ToolStrip RootToolStrip /// public override string ToString() { - if (Text != null && this.Text.Length != 0) + if (Text != null && Text.Length != 0) { - return this.Text; + return Text; } return base.ToString(); } @@ -4140,7 +4140,7 @@ public override string ToString() /// internal void Unselect() { - Debug.WriteLineIf(ToolStrip.SelectionDebug.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "[Selection DBG] WBI.Unselect: {0}", this.ToString())); + Debug.WriteLineIf(ToolStrip.SelectionDebug.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "[Selection DBG] WBI.Unselect: {0}", ToString())); if (state[stateSelected]) { state[stateSelected] = false; @@ -4164,20 +4164,20 @@ internal void Unselect() bool IKeyboardToolTip.CanShowToolTipsNow() { - return this.Visible && this.parent != null && ((IKeyboardToolTip)this.parent).AllowsChildrenToShowToolTips(); + return Visible && parent != null && ((IKeyboardToolTip)parent).AllowsChildrenToShowToolTips(); } Rectangle IKeyboardToolTip.GetNativeScreenRectangle() { - return this.AccessibilityObject.Bounds; + return AccessibilityObject.Bounds; } IList IKeyboardToolTip.GetNeighboringToolsRectangles() { List neighbors = new List(3); - if (this.parent != null) + if (parent != null) { - ToolStripItemCollection items = this.parent.DisplayedItems; + ToolStripItemCollection items = parent.DisplayedItems; int i = 0, count = items.Count; bool found = false; while (!found && i < count) @@ -4205,7 +4205,7 @@ IList IKeyboardToolTip.GetNeighboringToolsRectangles() Debug.Assert(i < count, "Item has a parent set but the parent doesn't own the item"); } - ToolStripDropDown dropDown = this.parent as ToolStripDropDown; + ToolStripDropDown dropDown = parent as ToolStripDropDown; if (dropDown != null && dropDown.OwnerItem != null) { neighbors.Add(((IKeyboardToolTip)dropDown.OwnerItem).GetNativeScreenRectangle()); @@ -4221,7 +4221,7 @@ bool IKeyboardToolTip.IsHoveredWithMouse() bool IKeyboardToolTip.HasRtlModeEnabled() { - return this.parent != null && ((IKeyboardToolTip)this.parent).HasRtlModeEnabled(); + return parent != null && ((IKeyboardToolTip)parent).HasRtlModeEnabled(); } bool IKeyboardToolTip.AllowsToolTip() @@ -4231,23 +4231,23 @@ bool IKeyboardToolTip.AllowsToolTip() IWin32Window IKeyboardToolTip.GetOwnerWindow() { - Debug.Assert(this.ParentInternal != null, "Tool Strip Item Parent is null"); - return this.ParentInternal; + Debug.Assert(ParentInternal != null, "Tool Strip Item Parent is null"); + return ParentInternal; } void IKeyboardToolTip.OnHooked(ToolTip toolTip) { - this.OnKeyboardToolTipHook(toolTip); + OnKeyboardToolTipHook(toolTip); } void IKeyboardToolTip.OnUnhooked(ToolTip toolTip) { - this.OnKeyboardToolTipUnhook(toolTip); + OnKeyboardToolTipUnhook(toolTip); } string IKeyboardToolTip.GetCaptionForTool(ToolTip toolTip) { - return this.ToolTipText; + return ToolTipText; } bool IKeyboardToolTip.ShowsOwnToolTip() @@ -4257,7 +4257,7 @@ bool IKeyboardToolTip.ShowsOwnToolTip() bool IKeyboardToolTip.IsBeingTabbedTo() { - return this.IsBeingTabbedTo(); + return IsBeingTabbedTo(); } bool IKeyboardToolTip.AllowsChildrenToShowToolTips() @@ -4406,7 +4406,7 @@ internal override object GetPropertyValue(int propertyID) case NativeMethods.UIA_NamePropertyId: return Name; case NativeMethods.UIA_IsExpandCollapsePatternAvailablePropertyId: - return (object)this.IsPatternSupported(NativeMethods.UIA_ExpandCollapsePatternId); + return (object)IsPatternSupported(NativeMethods.UIA_ExpandCollapsePatternId); case NativeMethods.UIA_IsEnabledPropertyId: return ownerItem.Enabled; case NativeMethods.UIA_IsOffscreenPropertyId: @@ -5101,9 +5101,9 @@ private class ToolStripLayoutData public ToolStripLayoutData(ToolStrip toolStrip) { - this.layoutStyle = toolStrip.LayoutStyle; - this.autoSize = toolStrip.AutoSize; - this.size = toolStrip.Size; + layoutStyle = toolStrip.LayoutStyle; + autoSize = toolStrip.AutoSize; + size = toolStrip.Size; } public bool IsCurrent(ToolStrip toolStrip) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemCollection.cs index f477096d66d..05e8934e7ef 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemCollection.cs @@ -143,11 +143,11 @@ public void AddRange(ToolStripItem[] toolStripItems) // ToolStripDropDown will look for PropertyNames.Items to determine if it needs // to resize itself. - using (new LayoutTransaction(this.owner, this.owner, PropertyNames.Items)) + using (new LayoutTransaction(owner, owner, PropertyNames.Items)) { for (int i = 0; i < toolStripItems.Length; i++) { - this.Add(toolStripItems[i]); + Add(toolStripItems[i]); } } } @@ -165,12 +165,12 @@ public void AddRange(ToolStripItemCollection toolStripItems) // ToolStripDropDown will look for PropertyNames.Items to determine if it needs // to resize itself. - using (new LayoutTransaction(this.owner, this.owner, PropertyNames.Items)) + using (new LayoutTransaction(owner, owner, PropertyNames.Items)) { int currentCount = toolStripItems.Count; for (int i = 0; i < currentCount; i++) { - this.Add(toolStripItems[i]); + Add(toolStripItems[i]); } } @@ -339,7 +339,7 @@ private ArrayList FindInternal(string key, bool searchAllChildren, ToolStripItem - public override bool IsReadOnly { get { return this.isReadOnly; } } + public override bool IsReadOnly { get { return isReadOnly; } } void IList.Clear() { Clear(); } bool IList.IsFixedSize { get { return InnerList.IsFixedSize; } } @@ -402,7 +402,7 @@ public virtual int IndexOfKey(string key) } // step 2 - search for the item - for (int i = 0; i < this.Count; i++) + for (int i = 0; i < Count; i++) { if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { @@ -421,7 +421,7 @@ public virtual int IndexOfKey(string key) /// private bool IsValidIndex(int index) { - return ((index >= 0) && (index < this.Count)); + return ((index >= 0) && (index < Count)); } /// @@ -524,7 +524,7 @@ internal void MoveItem(int index, ToolStripItem value) { // if moving to the end - call add instead. - if (index == this.Count) + if (index == Count) { MoveItem(value); return; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripLabel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripLabel.cs index a44e047d23d..6e8555ae0cd 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripLabel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripLabel.cs @@ -269,7 +269,7 @@ protected override void OnMouseEnter(EventArgs e) { if (IsLink) { - ToolStrip parent = this.Parent; + ToolStrip parent = Parent; if (parent != null) { lastCursor = parent.Cursor; @@ -284,7 +284,7 @@ protected override void OnMouseLeave(EventArgs e) { if (IsLink) { - ToolStrip parent = this.Parent; + ToolStrip parent = Parent; if (parent != null) { parent.Cursor = lastCursor; @@ -350,9 +350,9 @@ protected override AccessibleObject CreateAccessibilityInstance() protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { - if (this.Owner != null) + if (Owner != null) { - ToolStripRenderer renderer = this.Renderer; + ToolStripRenderer renderer = Renderer; renderer.DrawLabelBackground(new ToolStripItemRenderEventArgs(e.Graphics, this)); @@ -366,34 +366,34 @@ protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) internal void PaintText(Graphics g) { - ToolStripRenderer renderer = this.Renderer; + ToolStripRenderer renderer = Renderer; if ((DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) { - Font font = this.Font; - Color textColor = this.ForeColor; + Font font = Font; + Color textColor = ForeColor; if (IsLink) { - LinkUtilities.EnsureLinkFonts(font, this.LinkBehavior, ref this.linkFont, ref this.hoverLinkFont); + LinkUtilities.EnsureLinkFonts(font, LinkBehavior, ref linkFont, ref hoverLinkFont); - if (this.Pressed) + if (Pressed) { font = hoverLinkFont; - textColor = this.ActiveLinkColor; + textColor = ActiveLinkColor; } - else if (this.Selected) + else if (Selected) { font = hoverLinkFont; - textColor = (this.LinkVisited) ? this.VisitedLinkColor : this.LinkColor; + textColor = (LinkVisited) ? VisitedLinkColor : LinkColor; } else { font = linkFont; - textColor = (this.LinkVisited) ? this.VisitedLinkColor : this.LinkColor; + textColor = (LinkVisited) ? VisitedLinkColor : LinkColor; } } Rectangle textRect = InternalLayout.TextRectangle; - renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, this.Text, textRect, textColor, font, InternalLayout.TextFormat)); + renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, Text, textRect, textColor, font, InternalLayout.TextFormat)); } } @@ -461,7 +461,7 @@ internal override object GetPropertyValue(int propertyID) } else if (propertyID == NativeMethods.UIA_LegacyIAccessibleStatePropertyId) { - return this.State; + return State; } return base.GetPropertyValue(propertyID); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs index 16049c60e28..ba33c24d16e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs @@ -1030,7 +1030,7 @@ private void ExitMenuModeCore() } IKeyboardToolTip tool; - if (this.lastFocusedTool.TryGetTarget(out tool) && tool != null) + if (lastFocusedTool.TryGetTarget(out tool) && tool != null) { KeyboardToolTipStateMachine.Instance.NotifyAboutGotFocus(tool); } @@ -1216,7 +1216,7 @@ private bool ProcessActivationChange() int countDropDowns = _inputFilterQueue.Count; for (int i = 0; i < countDropDowns; i++) { - ToolStripDropDown activeDropDown = this.GetActiveToolStripInternal() as ToolStripDropDown; + ToolStripDropDown activeDropDown = GetActiveToolStripInternal() as ToolStripDropDown; if (activeDropDown != null && activeDropDown.AutoClose) { activeDropDown.Visible = false; @@ -1591,7 +1591,7 @@ private void InstallMessageHook() return; } - hookProc = new NativeMethods.HookProc(this.MessageHookProc); + hookProc = new NativeMethods.HookProc(MessageHookProc); messageHookHandle = UnsafeNativeMethods.SetWindowsHookEx(NativeMethods.WH_GETMESSAGE, hookProc, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs index ae18bf0a502..952d3e0cf91 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs @@ -99,7 +99,7 @@ public ToolStripMenuItem(string text, Image image, params ToolStripItem[] dropDo public ToolStripMenuItem(string text, Image image, EventHandler onClick, Keys shortcutKeys) : base(text, image, onClick) { Initialize(); - this.ShortcutKeys = shortcutKeys; + ShortcutKeys = shortcutKeys; } internal ToolStripMenuItem(Form mdiForm) { @@ -116,10 +116,10 @@ internal ToolStripMenuItem(Form mdiForm) internal ToolStripMenuItem(IntPtr hMenu, int nativeMenuCommandId, IWin32Window targetWindow) { Initialize(); - this.Overflow = ToolStripItemOverflow.Never; - this.nativeMenuCommandID = nativeMenuCommandId; - this.targetWindowHandle = Control.GetSafeHandle(targetWindow); - this.nativeMenuHandle = hMenu; + Overflow = ToolStripItemOverflow.Never; + nativeMenuCommandID = nativeMenuCommandId; + targetWindowHandle = Control.GetSafeHandle(targetWindow); + nativeMenuHandle = hMenu; // Since fetching the image and the text is an awful lot of work // we're going to just cache it and assume the native stuff @@ -129,8 +129,8 @@ internal ToolStripMenuItem(IntPtr hMenu, int nativeMenuCommandId, IWin32Window t // to live-return the results. // fetch image - this.Image = GetNativeMenuItemImage(); - this.ImageScaling = ToolStripItemImageScaling.None; + Image = GetNativeMenuItemImage(); + ImageScaling = ToolStripItemImageScaling.None; // fetch text string text = GetNativeMenuItemTextAndShortcut(); @@ -143,7 +143,7 @@ internal ToolStripMenuItem(IntPtr hMenu, int nativeMenuCommandId, IWin32Window t if (textFields.Length >= 1) { - this.Text = textFields[0]; + Text = textFields[0]; } if (textFields.Length >= 2) @@ -151,8 +151,8 @@ internal ToolStripMenuItem(IntPtr hMenu, int nativeMenuCommandId, IWin32Window t // We dont care about the shortcut here, the OS is going to // handle it for us by sending a WM_(SYS)COMMAND during TranslateAcellerator // Just display whatever the OS would have. - this.ShowShortcutKeys = true; - this.ShortcutKeyDisplayString = textFields[1]; + ShowShortcutKeys = true; + ShortcutKeyDisplayString = textFields[1]; } } } @@ -200,9 +200,9 @@ private void Initialize() scaledCheckMarkBitmapSize = DpiHelper.LogicalToDeviceUnits(checkMarkBitmapSize); } - this.Overflow = ToolStripItemOverflow.Never; - this.MouseDownAndUpMustBeInSameItem = false; - this.SupportsDisabledHotTracking = true; + Overflow = ToolStripItemOverflow.Never; + MouseDownAndUpMustBeInSameItem = false; + SupportsDisabledHotTracking = true; } /// @@ -526,7 +526,7 @@ public Keys ShortcutKeys if (originalShortcut != value) { ClearShortcutCache(); - ToolStrip owner = this.Owner; + ToolStrip owner = Owner; if (owner != null) { // add to the shortcut caching system. @@ -551,7 +551,7 @@ public Keys ShortcutKeys ToolStripDropDownMenu parent = GetCurrentParentDropDown() as ToolStripDropDownMenu; if (parent != null) { - LayoutTransaction.DoLayout(this.ParentInternal, this, "ShortcutKeys"); + LayoutTransaction.DoLayout(ParentInternal, this, "ShortcutKeys"); parent.AdjustSize(); } } @@ -580,7 +580,7 @@ public string ShortcutKeyDisplayString ClearShortcutCache(); if (ShowShortcutKeys) { - ToolStripDropDown parent = this.ParentInternal as ToolStripDropDown; + ToolStripDropDown parent = ParentInternal as ToolStripDropDown; if (parent != null) { LayoutTransaction.DoLayout(parent, this, "ShortcutKeyDisplayString"); @@ -616,7 +616,7 @@ public bool ShowShortcutKeys { ClearShortcutCache(); showShortcutKeys = value; - ToolStripDropDown parent = this.ParentInternal as ToolStripDropDown; + ToolStripDropDown parent = ParentInternal as ToolStripDropDown; if (parent != null) { LayoutTransaction.DoLayout(parent, this, "ShortcutKeys"); @@ -636,7 +636,7 @@ internal bool IsTopLevel { get { - return (this.ParentInternal as ToolStripDropDown == null); + return (ParentInternal as ToolStripDropDown == null); } } @@ -678,51 +678,51 @@ internal ToolStripMenuItem Clone() // dirt simple clone - just properties, no subitems ToolStripMenuItem menuItem = new ToolStripMenuItem(); - menuItem.Events.AddHandlers(this.Events); - - menuItem.AccessibleName = this.AccessibleName; - menuItem.AccessibleRole = this.AccessibleRole; - menuItem.Alignment = this.Alignment; - menuItem.AllowDrop = this.AllowDrop; - menuItem.Anchor = this.Anchor; - menuItem.AutoSize = this.AutoSize; - menuItem.AutoToolTip = this.AutoToolTip; - menuItem.BackColor = this.BackColor; - menuItem.BackgroundImage = this.BackgroundImage; - menuItem.BackgroundImageLayout = this.BackgroundImageLayout; - menuItem.Checked = this.Checked; - menuItem.CheckOnClick = this.CheckOnClick; - menuItem.CheckState = this.CheckState; - menuItem.DisplayStyle = this.DisplayStyle; - menuItem.Dock = this.Dock; - menuItem.DoubleClickEnabled = this.DoubleClickEnabled; - menuItem.Enabled = this.Enabled; - menuItem.Font = this.Font; - menuItem.ForeColor = this.ForeColor; - menuItem.Image = this.Image; - menuItem.ImageAlign = this.ImageAlign; - menuItem.ImageScaling = this.ImageScaling; - menuItem.ImageTransparentColor = this.ImageTransparentColor; - menuItem.Margin = this.Margin; - menuItem.MergeAction = this.MergeAction; - menuItem.MergeIndex = this.MergeIndex; - menuItem.Name = this.Name; - menuItem.Overflow = this.Overflow; - menuItem.Padding = this.Padding; - menuItem.RightToLeft = this.RightToLeft; + menuItem.Events.AddHandlers(Events); + + menuItem.AccessibleName = AccessibleName; + menuItem.AccessibleRole = AccessibleRole; + menuItem.Alignment = Alignment; + menuItem.AllowDrop = AllowDrop; + menuItem.Anchor = Anchor; + menuItem.AutoSize = AutoSize; + menuItem.AutoToolTip = AutoToolTip; + menuItem.BackColor = BackColor; + menuItem.BackgroundImage = BackgroundImage; + menuItem.BackgroundImageLayout = BackgroundImageLayout; + menuItem.Checked = Checked; + menuItem.CheckOnClick = CheckOnClick; + menuItem.CheckState = CheckState; + menuItem.DisplayStyle = DisplayStyle; + menuItem.Dock = Dock; + menuItem.DoubleClickEnabled = DoubleClickEnabled; + menuItem.Enabled = Enabled; + menuItem.Font = Font; + menuItem.ForeColor = ForeColor; + menuItem.Image = Image; + menuItem.ImageAlign = ImageAlign; + menuItem.ImageScaling = ImageScaling; + menuItem.ImageTransparentColor = ImageTransparentColor; + menuItem.Margin = Margin; + menuItem.MergeAction = MergeAction; + menuItem.MergeIndex = MergeIndex; + menuItem.Name = Name; + menuItem.Overflow = Overflow; + menuItem.Padding = Padding; + menuItem.RightToLeft = RightToLeft; // No settings support for cloned items. // menuItem.SaveSettings= this.SaveSettings; // menuItem.SettingsKey = this.SettingsKey; - menuItem.ShortcutKeys = this.ShortcutKeys; - menuItem.ShowShortcutKeys = this.ShowShortcutKeys; - menuItem.Tag = this.Tag; - menuItem.Text = this.Text; - menuItem.TextAlign = this.TextAlign; - menuItem.TextDirection = this.TextDirection; - menuItem.TextImageRelation = this.TextImageRelation; - menuItem.ToolTipText = this.ToolTipText; + menuItem.ShortcutKeys = ShortcutKeys; + menuItem.ShowShortcutKeys = ShowShortcutKeys; + menuItem.Tag = Tag; + menuItem.Text = Text; + menuItem.TextAlign = TextAlign; + menuItem.TextDirection = TextDirection; + menuItem.TextImageRelation = TextImageRelation; + menuItem.ToolTipText = ToolTipText; // cant actually use "Visible" property as that returns whether or not the parent // is visible too.. instead use ParticipatesInLayout as this queries the actual state. @@ -730,7 +730,7 @@ internal ToolStripMenuItem Clone() if (!AutoSize) { - menuItem.Size = this.Size; + menuItem.Size = Size; } return menuItem; } @@ -741,7 +741,7 @@ protected override void Dispose(bool disposing) { if (lastOwner != null) { - Keys shortcut = this.ShortcutKeys; + Keys shortcut = ShortcutKeys; if (shortcut != Keys.None && lastOwner.Shortcuts.ContainsKey(shortcut)) { lastOwner.Shortcuts.Remove(shortcut); @@ -924,7 +924,7 @@ internal string GetShortcutText() { if (cachedShortcutText == null) { - cachedShortcutText = ShortcutToText(this.ShortcutKeys, this.ShortcutKeyDisplayString); + cachedShortcutText = ShortcutToText(ShortcutKeys, ShortcutKeyDisplayString); } return cachedShortcutText; } @@ -945,7 +945,7 @@ protected override void OnClick(EventArgs e) { if (checkOnClick) { - this.Checked = !this.Checked; + Checked = !Checked; } base.OnClick(e); if (nativeMenuCommandID != -1) @@ -967,7 +967,7 @@ protected override void OnClick(EventArgs e) // be consistent with sending a WM_SYSCOMMAND, use POST not SEND. UnsafeNativeMethods.PostMessage(new HandleRef(this, targetWindowHandle), Interop.WindowMessages.WM_COMMAND, nativeMenuCommandID, 0); } - this.Invalidate(); + Invalidate(); } } @@ -1023,7 +1023,7 @@ protected override void OnFontChanged(EventArgs e) /// internal void OnMenuAutoExpand() { - this.ShowDropDown(); + ShowDropDown(); } @@ -1072,7 +1072,7 @@ private void OnMouseButtonStateChange(MouseEventArgs e, bool isMouseDown) // opening should happen on mouse down. Debug.Assert(ParentInternal != null, "Parent is null here, not going to get accurate ID"); openMouseId = (ParentInternal == null) ? (byte)0 : ParentInternal.GetMouseId(); - this.ShowDropDown(/*mousePush =*/true); + ShowDropDown(/*mousePush =*/true); } else if (!isMouseDown && !showDropDown) @@ -1100,10 +1100,10 @@ private void OnMouseButtonStateChange(MouseEventArgs e, bool isMouseDown) protected override void OnMouseEnter(EventArgs e) { - Debug.Assert(this.ParentInternal != null, "Why is parent null"); + Debug.Assert(ParentInternal != null, "Why is parent null"); // If we are in a submenu pop down the submenu. - if (this.ParentInternal != null && this.ParentInternal.MenuAutoExpand && Selected) + if (ParentInternal != null && ParentInternal.MenuAutoExpand && Selected) { Debug.WriteLineIf(ToolStripItem.MouseDebugging.TraceVerbose, "received mouse enter - calling drop down"); @@ -1128,7 +1128,7 @@ protected override void OnMouseLeave(EventArgs e) protected override void OnOwnerChanged(EventArgs e) { - Keys shortcut = this.ShortcutKeys; + Keys shortcut = ShortcutKeys; if (shortcut != Keys.None) { if (lastOwner != null) @@ -1158,18 +1158,18 @@ protected override void OnOwnerChanged(EventArgs e) protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { - if (this.Owner != null) + if (Owner != null) { - ToolStripRenderer renderer = this.Renderer; + ToolStripRenderer renderer = Renderer; Graphics g = e.Graphics; renderer.DrawMenuItemBackground(new ToolStripItemRenderEventArgs(g, this)); Color textColor = SystemColors.MenuText; if (IsForeColorSet) { - textColor = this.ForeColor; + textColor = ForeColor; } - else if (!this.IsTopLevel || (ToolStripManager.VisualStylesEnabled)) + else if (!IsTopLevel || (ToolStripManager.VisualStylesEnabled)) { if (Selected || Pressed) { @@ -1183,7 +1183,7 @@ protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) bool rightToLeft = (RightToLeft == RightToLeft.Yes); - ToolStripMenuItemInternalLayout menuItemInternalLayout = this.InternalLayout as ToolStripMenuItemInternalLayout; + ToolStripMenuItemInternalLayout menuItemInternalLayout = InternalLayout as ToolStripMenuItemInternalLayout; if (menuItemInternalLayout != null && menuItemInternalLayout.UseMenuLayout) { @@ -1213,7 +1213,7 @@ protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { // render text AND shortcut - renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, this.Text, InternalLayout.TextRectangle, textColor, this.Font, (rightToLeft) ? ContentAlignment.MiddleRight : ContentAlignment.MiddleLeft)); + renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, Text, InternalLayout.TextRectangle, textColor, Font, (rightToLeft) ? ContentAlignment.MiddleRight : ContentAlignment.MiddleLeft)); bool showShortCut = ShowShortcutKeys; if (!DesignMode) { @@ -1222,7 +1222,7 @@ protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) if (showShortCut) { - renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, GetShortcutText(), InternalLayout.TextRectangle, textColor, this.Font, (rightToLeft) ? ContentAlignment.MiddleLeft : ContentAlignment.MiddleRight)); + renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, GetShortcutText(), InternalLayout.TextRectangle, textColor, Font, (rightToLeft) ? ContentAlignment.MiddleLeft : ContentAlignment.MiddleRight)); } } @@ -1248,7 +1248,7 @@ protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) // Toplevel item support, menu items hosted on a plain ToolStrip dropdown if ((DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) { - renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, this.Text, InternalLayout.TextRectangle, textColor, this.Font, InternalLayout.TextFormat)); + renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, Text, InternalLayout.TextRectangle, textColor, Font, InternalLayout.TextFormat)); } if ((DisplayStyle & ToolStripItemDisplayStyle.Image) == ToolStripItemDisplayStyle.Image && Image != null) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripOverflowButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripOverflowButton.cs index 62bc7f8e8d0..5a8c90d4cee 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripOverflowButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripOverflowButton.cs @@ -48,9 +48,9 @@ internal ToolStripOverflowButton(ToolStrip parentToolStrip) protected override void Dispose(bool disposing) { - if (disposing && this.HasDropDownItems) + if (disposing && HasDropDownItems) { - this.DropDown.Dispose(); + DropDown.Dispose(); } base.Dispose(disposing); @@ -68,7 +68,7 @@ public override bool HasDropDownItems { get { - return this.ParentInternal.OverflowItems.Count > 0; + return ParentInternal.OverflowItems.Count > 0; } } @@ -114,9 +114,9 @@ protected override ToolStripDropDown CreateDefaultDropDown() public override Size GetPreferredSize(Size constrainingSize) { Size preferredSize = constrainingSize; - if (this.ParentInternal != null) + if (ParentInternal != null) { - if (this.ParentInternal.Orientation == Orientation.Horizontal) + if (ParentInternal.Orientation == Orientation.Horizontal) { preferredSize.Width = Math.Min(constrainingSize.Width, maxWidth); } @@ -125,7 +125,7 @@ public override Size GetPreferredSize(Size constrainingSize) preferredSize.Height = Math.Min(constrainingSize.Height, maxHeight); } } - return preferredSize + this.Padding.Size; + return preferredSize + Padding.Size; } // make sure the Overflow button extends from edge-edge. (Ignore Padding/Margin). @@ -150,9 +150,9 @@ internal protected override void SetBounds(Rectangle bounds) protected override void OnPaint(PaintEventArgs e) { - if (this.ParentInternal != null) + if (ParentInternal != null) { - ToolStripRenderer renderer = this.ParentInternal.Renderer; + ToolStripRenderer renderer = ParentInternal.Renderer; renderer.DrawOverflowButtonBackground(new ToolStripItemRenderEventArgs(e.Graphics, this)); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs index 7df74f11d84..74a484b55e7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs @@ -81,10 +81,10 @@ public ToolStripPanel() SuspendLayout(); AutoScaleMode = AutoScaleMode.None; InitFlowLayout(); - this.AutoSize = true; - this.MinimumSize = Size.Empty; // consider 1,1 - this.state[stateLocked | stateBeginInit | stateChangingZOrder] = false; - this.TabStop = false; + AutoSize = true; + MinimumSize = Size.Empty; // consider 1,1 + state[stateLocked | stateBeginInit | stateChangingZOrder] = false; + TabStop = false; ToolStripManager.ToolStripPanels.Add(this); // not setting ControlStyles.AllPaintingInWmPaint as we dont do any painting in OnPaint... all @@ -215,7 +215,7 @@ internal Rectangle DragBounds { get { - return LayoutUtils.InflateRect(this.ClientRectangle, DragMargin); + return LayoutUtils.InflateRect(ClientRectangle, DragMargin); } } @@ -267,7 +267,7 @@ public Orientation Orientation orientation = value; scaledRowMargin = LayoutUtils.FlipPadding(scaledRowMargin); InitFlowLayout(); - foreach (ToolStripPanelRow row in this.RowsInternal) + foreach (ToolStripPanelRow row in RowsInternal) { row.OnOrientationChanged(); } @@ -566,7 +566,7 @@ protected override void OnControlAdded(ControlEventArgs e) { if (!state[stateLayoutSuspended]) { - this.Join(e.Control as ToolStrip, e.Control.Location); + Join(e.Control as ToolStrip, e.Control.Location); } else { @@ -595,7 +595,7 @@ protected override void OnLayout(LayoutEventArgs e) if (e.AffectedComponent != ParentInternal && e.AffectedComponent as Control != null) { ISupportToolStripPanel draggedControl = e.AffectedComponent as ISupportToolStripPanel; - if (draggedControl != null && this.RowsInternal.Contains(draggedControl.ToolStripPanelRow)) + if (draggedControl != null && RowsInternal.Contains(draggedControl.ToolStripPanelRow)) { // there's a problem in the base onlayout... if toolstrip needs more space it talks to us // not the row that needs layout. @@ -632,10 +632,10 @@ protected override void OnRightToLeftChanged(EventArgs e) { // rejoin the controls on the other side of the toolstrippanel. SuspendLayout(); - Control[] controls = new Control[this.Controls.Count]; - Point[] controlLocations = new Point[this.Controls.Count]; + Control[] controls = new Control[Controls.Count]; + Point[] controlLocations = new Point[Controls.Count]; int j = 0; - foreach (ToolStripPanelRow row in this.RowsInternal) + foreach (ToolStripPanelRow row in RowsInternal) { foreach (Control control in row.ControlsInternal) { @@ -645,7 +645,7 @@ protected override void OnRightToLeftChanged(EventArgs e) } } - this.Controls.Clear(); + Controls.Clear(); for (int i = 0; i < controls.Length; i++) { @@ -668,7 +668,7 @@ protected virtual void OnRendererChanged(EventArgs e) { Renderer.InitializePanel(this); - this.Invalidate(); + Invalidate(); EventHandler handler = (EventHandler)Events[EventRendererChanged]; if (handler != null) @@ -727,7 +727,7 @@ private void JoinControls() private void JoinControls(bool forceLayout) { // undone: config - shift to other container - ToolStripPanelControlCollection controls = this.Controls as ToolStripPanelControlCollection; + ToolStripPanelControlCollection controls = Controls as ToolStripPanelControlCollection; if (controls.Count > 0) { controls.Sort(); @@ -758,9 +758,9 @@ private void JoinControls(bool forceLayout) // right to left has changed while layout was deferred... if (state[stateRightToLeftChanged]) { - controlLocation = new Point(this.Width - controlArray[i].Right, controlLocation.Y); + controlLocation = new Point(Width - controlArray[i].Right, controlLocation.Y); } - this.Join(controlArray[i] as ToolStrip, controlArray[i].Location); + Join(controlArray[i] as ToolStrip, controlArray[i].Location); if (numRows < RowsInternal.Count || forceLayout) { // OK this is wierd but here we're in the midst of a suspend layout. @@ -924,10 +924,10 @@ public FeedbackDropDown(Rectangle bounds) : base() SetStyle(ControlStyles.AllPaintingInWmPaint, false); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); SetStyle(ControlStyles.CacheText, true); - this.AutoClose = false; - this.AutoSize = false; - this.DropShadowEnabled = false; - this.Bounds = bounds; + AutoClose = false; + AutoSize = false; + DropShadowEnabled = false; + Bounds = bounds; // caching as this is unlikely to change during the lifetime // of the dropdown. @@ -939,7 +939,7 @@ public FeedbackDropDown(Rectangle bounds) : base() rgn.Exclude(regionRect); // exclude the center part // set it into the toolstripdropdown’s region - this.Region = rgn; + Region = rgn; } // ForceSynchronousPaint - peeks through the message queue, looking for WM_PAINTs @@ -996,7 +996,7 @@ protected override void OnOpening(CancelEventArgs e) public void MoveTo(Point newLocation) { - this.Location = newLocation; + Location = newLocation; // if we dont force a paint here, we'll only send WM_ERASEBKGNDs right away // and leave rectangles all over controls that dont respond to that window message. ForceSynchronousPaint(); @@ -1037,7 +1037,7 @@ public void Join(ToolStrip toolStripToDrag, int row) } else { - dragRect = this.RowsInternal[row].DragBounds; + dragRect = RowsInternal[row].DragBounds; } if (Orientation == Orientation.Horizontal) @@ -1082,7 +1082,7 @@ public void Join(ToolStrip toolStripToDrag, Point location) } else { - this.Controls.Add(toolStripToDrag); + Controls.Add(toolStripToDrag); toolStripToDrag.Location = location; } } @@ -1098,7 +1098,7 @@ internal void MoveControl(ToolStrip toolStripToDrag, Point screenLocation) } Point clientLocation = PointToClient(screenLocation); - if (!this.DragBounds.Contains(clientLocation)) + if (!DragBounds.Contains(clientLocation)) { Debug.WriteLineIf(ToolStripPanelDebug.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "RC.MoveControl - Point {0} is not in current rafting container drag bounds {1}, calling MoveOutsideContainer", clientLocation, DragBounds)); MoveOutsideContainer(toolStripToDrag, screenLocation); @@ -1115,7 +1115,7 @@ private void MoveInsideContainer(ToolStrip toolStripToDrag, Point clientLocation ISupportToolStripPanel draggedControl = toolStripToDrag as ISupportToolStripPanel; // if the point is not in this rafting container forward on to the appropriate container. - if (draggedControl.IsCurrentlyDragging && !this.DragBounds.Contains(clientLocation)) + if (draggedControl.IsCurrentlyDragging && !DragBounds.Contains(clientLocation)) { return; } @@ -1187,29 +1187,29 @@ private void MoveInsideContainer(ToolStrip toolStripToDrag, Point clientLocation Debug.WriteLineIf(ToolStripPanelDebug.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "\tThere is no row corresponding to this point, creating a new one.")); // there's no row at this point so lets create one - int index = this.RowsInternal.Count; + int index = RowsInternal.Count; if (Orientation == Orientation.Horizontal) { // if it's above the first row, insert at the front. - index = (clientLocation.Y <= this.Padding.Left) ? 0 : index; + index = (clientLocation.Y <= Padding.Left) ? 0 : index; } else { // Orientation.Vertical // if it's before the first row, insert at the front. - index = (clientLocation.X <= this.Padding.Left) ? 0 : index; + index = (clientLocation.X <= Padding.Left) ? 0 : index; } ToolStripPanelRow previousRow = null; - if (this.RowsInternal.Count > 0) + if (RowsInternal.Count > 0) { if (index == 0) { - previousRow = this.RowsInternal[0]; + previousRow = RowsInternal[0]; } else if (index > 0) { - previousRow = this.RowsInternal[index - 1]; + previousRow = RowsInternal[index - 1]; } } if (previousRow != null /* there was a previous row */ @@ -1235,7 +1235,7 @@ private void MoveInsideContainer(ToolStrip toolStripToDrag, Point clientLocation // Debug.WriteLineIf(ToolStripPanelRow.ToolStripPanelRowCreationDebug.TraceVerbose, "Inserting a new row at " + index.ToString(CultureInfo.InvariantCulture)); row = new ToolStripPanelRow(this); - this.RowsInternal.Insert(index, row); + RowsInternal.Insert(index, row); } } @@ -1256,7 +1256,7 @@ private void MoveInsideContainer(ToolStrip toolStripToDrag, Point clientLocation } } row = new ToolStripPanelRow(this); - this.RowsInternal.Insert(index, row); + RowsInternal.Insert(index, row); clientLocation.Y = row.Bounds.Y; } @@ -1358,7 +1358,7 @@ public ToolStripPanelRow PointToRow(Point clientLocation) { // PERF: since we're using the PropertyStore for this.RowsInternal, its actually // faster to use foreach. - foreach (ToolStripPanelRow row in this.RowsInternal) + foreach (ToolStripPanelRow row in RowsInternal) { Rectangle bounds = LayoutUtils.InflateRect(row.Bounds, row.Margin); @@ -1391,9 +1391,9 @@ public ToolStripPanelRow PointToRow(Point clientLocation) [Conditional("DEBUG")] private void Debug_VerifyOneToOneCellRowControlMatchup() { - for (int i = 0; i < this.RowsInternal.Count; i++) + for (int i = 0; i < RowsInternal.Count; i++) { - ToolStripPanelRow row = this.RowsInternal[i]; + ToolStripPanelRow row = RowsInternal[i]; foreach (ToolStripPanelCell cell in row.Cells) { @@ -1444,9 +1444,9 @@ private void Debug_VerifyCountRows() [Conditional("DEBUG")] private void Debug_VerifyNoOverlaps() { - foreach (Control c1 in this.Controls) + foreach (Control c1 in Controls) { - foreach (Control c2 in this.Controls) + foreach (Control c2 in Controls) { if (c1 == c2) { @@ -1541,7 +1541,7 @@ public void AddRange(ToolStripPanelRow[] value) throw new ArgumentNullException(nameof(value)); } - ToolStripPanel currentOwner = this.owner; + ToolStripPanel currentOwner = owner; if (currentOwner != null) { currentOwner.SuspendLayout(); @@ -1550,7 +1550,7 @@ public void AddRange(ToolStripPanelRow[] value) { for (int i = 0; i < value.Length; i++) { - this.Add(value[i]); + Add(value[i]); } } finally @@ -1568,7 +1568,7 @@ public void AddRange(ToolStripPanelRowCollection value) throw new ArgumentNullException(nameof(value)); } - ToolStripPanel currentOwner = this.owner; + ToolStripPanel currentOwner = owner; if (currentOwner != null) { currentOwner.SuspendLayout(); @@ -1578,7 +1578,7 @@ public void AddRange(ToolStripPanelRowCollection value) int currentCount = value.Count; for (int i = 0; i < currentCount; i++) { - this.Add(value[i]); + Add(value[i]); } } finally diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelCell.cs index 8744a737aa8..2b0fa8aefdb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelCell.cs @@ -51,8 +51,8 @@ public ToolStripPanelCell(ToolStripPanelRow parent, Control control) Debug.Assert(cellCount <= ToolStripManager.ToolStrips.Count, "who is allocating an extra toolstrippanel cell?"); #endif - this.ToolStripPanelRow = parent; - this._wrappedToolStrip = control as ToolStrip; + ToolStripPanelRow = parent; + _wrappedToolStrip = control as ToolStrip; if (control == null) { throw new ArgumentNullException(nameof(control)); @@ -62,8 +62,8 @@ public ToolStripPanelCell(ToolStripPanelRow parent, Control control) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, string.Format(SR.TypedControlCollectionShouldBeOfType, typeof(ToolStrip).Name)), control.GetType().Name); } CommonProperties.SetAutoSize(this, true); - _wrappedToolStrip.LocationChanging += new ToolStripLocationCancelEventHandler(this.OnToolStripLocationChanging); - _wrappedToolStrip.VisibleChanged += new EventHandler(this.OnToolStripVisibleChanged); + _wrappedToolStrip.LocationChanging += new ToolStripLocationCancelEventHandler(OnToolStripLocationChanging); + _wrappedToolStrip.VisibleChanged += new EventHandler(OnToolStripVisibleChanged); } @@ -114,7 +114,7 @@ public ToolStripPanelRow ToolStripPanelRow ((IList)parent.Cells).Remove(this); } parent = value; - this.Margin = Padding.Empty; + Margin = Padding.Empty; } @@ -244,8 +244,8 @@ protected override void Dispose(bool disposing) #if DEBUG cellCount--; #endif - _wrappedToolStrip.LocationChanging -= new ToolStripLocationCancelEventHandler(this.OnToolStripLocationChanging); - _wrappedToolStrip.VisibleChanged -= new EventHandler(this.OnToolStripVisibleChanged); + _wrappedToolStrip.LocationChanging -= new ToolStripLocationCancelEventHandler(OnToolStripLocationChanging); + _wrappedToolStrip.VisibleChanged -= new EventHandler(OnToolStripVisibleChanged); } _wrappedToolStrip = null; if (parent != null) @@ -307,7 +307,7 @@ protected override void SetBoundsCore(Rectangle bounds, BoundsSpecified specifie { currentlySizing = true; - this.CachedBounds = bounds; + CachedBounds = bounds; try { if (DraggedControl.IsCurrentlyDragging) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs index c5160a7d3a0..01f7d4dd39c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs @@ -72,14 +72,14 @@ internal ToolStripPanelRow(ToolStripPanel parent, bool visible) } this.parent = parent; - this.state[stateVisible] = visible; - this.state[stateDisposing | stateLocked | stateInitialized] = false; + state[stateVisible] = visible; + state[stateDisposing | stateLocked | stateInitialized] = false; Debug.WriteLineIf(ToolStripPanelRowCreationDebug.TraceVerbose, "Created new ToolStripPanelRow"); using (LayoutTransaction lt = new LayoutTransaction(parent, this, null)) { - this.Margin = DefaultMargin; + Margin = DefaultMargin; CommonProperties.SetAutoSize(this, true); } @@ -323,7 +323,7 @@ protected override void Dispose(bool disposing) Debug.WriteLineIf(ToolStripPanelRowCreationDebug.TraceVerbose, "Disposed ToolStripPanelRow"); state[stateDisposing] = true; - this.ControlsInternal.Clear(); + ControlsInternal.Clear(); } } finally @@ -349,7 +349,7 @@ protected internal virtual void OnControlAdded(Control control, int index) protected internal virtual void OnOrientationChanged() { - this.rowManager = null; + rowManager = null; } protected void OnBoundsChanged(Rectangle oldBounds, Rectangle newBounds) @@ -363,7 +363,7 @@ protected internal virtual void OnControlRemoved(Control control, int index) { if (!state[stateDisposing]) { - this.SuspendLayout(); + SuspendLayout(); RowManager.OnControlRemoved(control, index); // if previously added - remove. @@ -374,8 +374,8 @@ protected internal virtual void OnControlRemoved(Control control, int index) controlToBeDragged.ToolStripPanelRow = null; } - this.ResumeLayout(true); - if (this.ControlsInternal.Count <= 0) + ResumeLayout(true); + if (ControlsInternal.Count <= 0) { ToolStripPanel.RowsInternal.Remove(this); Dispose(); @@ -397,7 +397,7 @@ internal Size GetMinimumSize(ToolStrip toolStrip) private void ApplyCachedBounds() { - for (int i = 0; i < this.Cells.Count; i++) + for (int i = 0; i < Cells.Count; i++) { IArrangedElement element = Cells[i] as IArrangedElement; if (element.ParticipatesInLayout) @@ -416,7 +416,7 @@ protected virtual void OnLayout(LayoutEventArgs e) state[stateInLayout] = true; try { - this.Margin = DefaultMargin; + Margin = DefaultMargin; CachedBoundsMode = true; try { @@ -428,7 +428,7 @@ protected virtual void OnLayout(LayoutEventArgs e) CachedBoundsMode = false; } - ToolStripPanelCell cell = RowManager.GetNextVisibleCell(this.Cells.Count - 1, /*forward*/false); + ToolStripPanelCell cell = RowManager.GetNextVisibleCell(Cells.Count - 1, /*forward*/false); if (cell == null) { ApplyCachedBounds(); @@ -455,7 +455,7 @@ protected virtual void OnLayout(LayoutEventArgs e) private void OnLayoutHorizontalPostFix() { - ToolStripPanelCell cell = RowManager.GetNextVisibleCell(this.Cells.Count - 1, /*forward*/false); + ToolStripPanelCell cell = RowManager.GetNextVisibleCell(Cells.Count - 1, /*forward*/false); if (cell == null) { ApplyCachedBounds(); @@ -555,7 +555,7 @@ private void OnLayoutHorizontalPostFix() private void OnLayoutVerticalPostFix() { - ToolStripPanelCell cell = RowManager.GetNextVisibleCell(this.Cells.Count - 1, /*forward*/false); + ToolStripPanelCell cell = RowManager.GetNextVisibleCell(Cells.Count - 1, /*forward*/false); // figure out how much space we actually need to free. int spaceToFree = cell.CachedBounds.Bottom - RowManager.DisplayRectangle.Bottom; @@ -717,7 +717,7 @@ IArrangedElement IArrangedElement.Container { get { - return this.ToolStripPanel; + return ToolStripPanel; } } @@ -726,7 +726,7 @@ Rectangle IArrangedElement.DisplayRectangle { get { - Rectangle displayRectangle = this.Bounds; + Rectangle displayRectangle = Bounds; return displayRectangle; } @@ -745,7 +745,7 @@ PropertyStore IArrangedElement.Properties { get { - return this.Properties; + return Properties; } } @@ -944,7 +944,7 @@ public ToolStripPanelCell GetNextVisibleCell(int index, bool forward) for (int i = index; i < Row.Cells.Count; i++) { ToolStripPanelCell cell = Row.Cells[i] as ToolStripPanelCell; - if ((cell.Visible || (owner.parent.Visible && cell.ControlInDesignMode)) && cell.ToolStripPanelRow == this.owner) + if ((cell.Visible || (owner.parent.Visible && cell.ControlInDesignMode)) && cell.ToolStripPanelRow == owner) { return cell; } @@ -955,7 +955,7 @@ public ToolStripPanelCell GetNextVisibleCell(int index, bool forward) for (int i = index; i >= 0; i--) { ToolStripPanelCell cell = Row.Cells[i] as ToolStripPanelCell; - if ((cell.Visible || (owner.parent.Visible && cell.ControlInDesignMode)) && cell.ToolStripPanelRow == this.owner) + if ((cell.Visible || (owner.parent.Visible && cell.ControlInDesignMode)) && cell.ToolStripPanelRow == owner) { return cell; } @@ -2390,7 +2390,7 @@ public void AddRange(Control[] value) { for (int i = 0; i < value.Length; i++) { - this.Add(value[i]); + Add(value[i]); } } finally diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProgressBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProgressBar.cs index 0eb0d5d2ea2..10e67e7ba5c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProgressBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProgressBar.cs @@ -36,7 +36,7 @@ public ToolStripProgressBar() public ToolStripProgressBar(string name) : this() { - this.Name = name; + Name = name; } /// @@ -48,7 +48,7 @@ public ProgressBar ProgressBar { get { - return this.Control as ProgressBar; + return Control as ProgressBar; } } @@ -106,7 +106,7 @@ protected internal override Padding DefaultMargin { get { - if (this.Owner != null && this.Owner is StatusStrip) + if (Owner != null && Owner is StatusStrip) { return scaledDefaultStatusStripMargin; } @@ -480,7 +480,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga if (direction == UnsafeNativeMethods.NavigateDirection.FirstChild || direction == UnsafeNativeMethods.NavigateDirection.LastChild) { - return this.ownerItem.ProgressBar.AccessibilityObject; + return ownerItem.ProgressBar.AccessibilityObject; } // Handle Parent and other directions in base ToolStripItem.FragmentNavigate() method. @@ -517,7 +517,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRo { get { - var toolStripProgressBarControl = this.Owner as ToolStripProgressBarControl; + var toolStripProgressBarControl = Owner as ToolStripProgressBarControl; if (toolStripProgressBarControl != null) { return toolStripProgressBarControl.Owner.Owner.AccessibilityObject; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRendererSwitcher.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRendererSwitcher.cs index a9a8fb8281d..c49fdf69414 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRendererSwitcher.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRendererSwitcher.cs @@ -28,7 +28,7 @@ internal class ToolStripRendererSwitcher public ToolStripRendererSwitcher(Control owner, ToolStripRenderMode defaultRenderMode) : this(owner) { this.defaultRenderMode = defaultRenderMode; - this.RenderMode = defaultRenderMode; + RenderMode = defaultRenderMode; } @@ -136,9 +136,9 @@ public ToolStripRenderMode RenderMode private void OnRendererChanged(EventArgs e) { - if (this.RendererChanged != null) + if (RendererChanged != null) { - this.RendererChanged(this, e); + RendererChanged(this, e); } } private void OnDefaultRendererChanged(object sender, EventArgs e) @@ -189,7 +189,7 @@ public bool ShouldSerializeRenderMode() } public void ResetRenderMode() { - this.RenderMode = defaultRenderMode; + RenderMode = defaultRenderMode; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripScrollButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripScrollButton.cs index 270d02f31a1..04ab53e6810 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripScrollButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripScrollButton.cs @@ -175,7 +175,7 @@ public override Size GetPreferredSize(Size constrainingSize) private void Scroll() { - ToolStripDropDownMenu parent = this.ParentInternal as ToolStripDropDownMenu; + ToolStripDropDownMenu parent = ParentInternal as ToolStripDropDownMenu; if (parent != null && Label.Enabled) { parent.ScrollInternal(up); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSeparator.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSeparator.cs index 1ea02da2a94..1831d767770 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSeparator.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSeparator.cs @@ -25,7 +25,7 @@ public class ToolStripSeparator : ToolStripItem [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public ToolStripSeparator() { - this.ForeColor = SystemColors.ControlDark; + ForeColor = SystemColors.ControlDark; } [ @@ -305,7 +305,7 @@ private bool IsVertical { get { - ToolStrip parent = this.ParentInternal; + ToolStrip parent = ParentInternal; if (parent == null) { @@ -445,7 +445,7 @@ protected override AccessibleObject CreateAccessibilityInstance() public override Size GetPreferredSize(Size constrainingSize) { - ToolStrip parent = this.ParentInternal; + ToolStrip parent = ParentInternal; if (parent == null) { @@ -484,9 +484,9 @@ public override Size GetPreferredSize(Size constrainingSize) protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { - if (this.Owner != null && this.ParentInternal != null) + if (Owner != null && ParentInternal != null) { - this.Renderer.DrawSeparator(new ToolStripSeparatorRenderEventArgs(e.Graphics, this, IsVertical)); + Renderer.DrawSeparator(new ToolStripSeparatorRenderEventArgs(e.Graphics, this, IsVertical)); } } @@ -507,7 +507,7 @@ internal override bool ShouldSerializeForeColor() internal protected override void SetBounds(Rectangle rect) { - ToolStripDropDownMenu dropDownMenu = this.Owner as ToolStripDropDownMenu; + ToolStripDropDownMenu dropDownMenu = Owner as ToolStripDropDownMenu; if (dropDownMenu != null) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSettings.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSettings.cs index a62481b78a7..fb5042795ae 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSettings.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSettings.cs @@ -120,7 +120,7 @@ public bool Visible public override void Save() { - this.IsDefault = false; + IsDefault = false; base.Save(); } } @@ -136,7 +136,7 @@ internal class ToolStripSettingsManager internal ToolStripSettingsManager(Form owner, string formKey) { - this.form = owner; + form = owner; this.formKey = formKey; } @@ -451,39 +451,39 @@ private struct SettingsStub public SettingsStub(ToolStrip toolStrip) { - this.ToolStripPanelName = string.Empty; + ToolStripPanelName = string.Empty; ToolStripPanel parentPanel = toolStrip.Parent as ToolStripPanel; if (parentPanel != null) { if (!string.IsNullOrEmpty(parentPanel.Name)) { - this.ToolStripPanelName = parentPanel.Name; + ToolStripPanelName = parentPanel.Name; } else if (parentPanel.Parent is ToolStripContainer && !string.IsNullOrEmpty(parentPanel.Parent.Name)) { // Handle the case when the ToolStripPanel belongs to a ToolStripContainer. - this.ToolStripPanelName = parentPanel.Parent.Name + "." + parentPanel.Dock.ToString(); + ToolStripPanelName = parentPanel.Parent.Name + "." + parentPanel.Dock.ToString(); } - Debug.Assert(!string.IsNullOrEmpty(this.ToolStripPanelName), "ToolStrip was parented to a panel, but we couldn't figure out its name."); + Debug.Assert(!string.IsNullOrEmpty(ToolStripPanelName), "ToolStrip was parented to a panel, but we couldn't figure out its name."); } - this.Visible = toolStrip.Visible; - this.Size = toolStrip.Size; - this.Location = toolStrip.Location; - this.Name = toolStrip.Name; - this.ItemOrder = GetItemOrder(toolStrip); + Visible = toolStrip.Visible; + Size = toolStrip.Size; + Location = toolStrip.Location; + Name = toolStrip.Name; + ItemOrder = GetItemOrder(toolStrip); } public SettingsStub(ToolStripSettings toolStripSettings) { - this.ToolStripPanelName = toolStripSettings.ToolStripPanelName; - this.Visible = toolStripSettings.Visible; - this.Size = toolStripSettings.Size; - this.Location = toolStripSettings.Location; - this.Name = toolStripSettings.Name; - this.ItemOrder = toolStripSettings.ItemOrder; + ToolStripPanelName = toolStripSettings.ToolStripPanelName; + Visible = toolStripSettings.Visible; + Size = toolStripSettings.Size; + Location = toolStripSettings.Location; + Name = toolStripSettings.Name; + ItemOrder = toolStripSettings.ItemOrder; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs index 2ebc2e7e22e..82678ab4a8d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs @@ -212,7 +212,7 @@ internal protected override bool DismissWhenClicked internal override Rectangle DropDownButtonArea { - get { return this.DropDownButtonBounds; } + get { return DropDownButtonBounds; } } /// @@ -247,7 +247,7 @@ public bool DropDownButtonSelected { get { - return this.Selected; + return Selected; } } /// @@ -314,14 +314,14 @@ private ToolStripSplitButtonButton SplitButtonButton { splitButtonButton = new ToolStripSplitButtonButton(this); } - splitButtonButton.Image = this.Image; - splitButtonButton.Text = this.Text; - splitButtonButton.BackColor = this.BackColor; - splitButtonButton.ForeColor = this.ForeColor; - splitButtonButton.Font = this.Font; - splitButtonButton.ImageAlign = this.ImageAlign; - splitButtonButton.TextAlign = this.TextAlign; - splitButtonButton.TextImageRelation = this.TextImageRelation; + splitButtonButton.Image = Image; + splitButtonButton.Text = Text; + splitButtonButton.BackColor = BackColor; + splitButtonButton.ForeColor = ForeColor; + splitButtonButton.Font = Font; + splitButtonButton.ImageAlign = ImageAlign; + splitButtonButton.TextAlign = TextAlign; + splitButtonButton.TextImageRelation = TextImageRelation; return splitButtonButton; } } @@ -391,22 +391,22 @@ private void CalculateLayout() { // Figure out where the DropDown image goes. - Rectangle dropDownButtonBounds = new Rectangle(Point.Empty, this.Size); + Rectangle dropDownButtonBounds = new Rectangle(Point.Empty, Size); Rectangle splitButtonButtonBounds = Rectangle.Empty; - dropDownButtonBounds = new Rectangle(Point.Empty, new Size(Math.Min(this.Width, DropDownButtonWidth), this.Height)); + dropDownButtonBounds = new Rectangle(Point.Empty, new Size(Math.Min(Width, DropDownButtonWidth), Height)); // Figure out the height and width of the selected item. - int splitButtonButtonWidth = Math.Max(0, this.Width - dropDownButtonBounds.Width); - int splitButtonButtonHeight = Math.Max(0, this.Height); + int splitButtonButtonWidth = Math.Max(0, Width - dropDownButtonBounds.Width); + int splitButtonButtonHeight = Math.Max(0, Height); splitButtonButtonBounds = new Rectangle(Point.Empty, new Size(splitButtonButtonWidth, splitButtonButtonHeight)); // grow the selected item by one since we're overlapping the borders. splitButtonButtonBounds.Width -= splitterWidth; - if (this.RightToLeft == RightToLeft.No) + if (RightToLeft == RightToLeft.No) { // the dropdown button goes on the right dropDownButtonBounds.Offset(splitButtonButtonBounds.Right + splitterWidth, 0); @@ -420,8 +420,8 @@ private void CalculateLayout() } - this.SplitButtonButton.SetBounds(splitButtonButtonBounds); - this.SetDropDownButtonBounds(dropDownButtonBounds); + SplitButtonButton.SetBounds(splitButtonButtonBounds); + SetDropDownButtonBounds(dropDownButtonBounds); } @@ -440,7 +440,7 @@ protected override ToolStripDropDown CreateDefaultDropDown() internal override ToolStripItemInternalLayout CreateInternalLayout() { // whenever the master layout is invalidated - invalidate the splitbuttonbutton layout. - this.splitButtonButtonLayout = null; + splitButtonButtonLayout = null; return new ToolStripItemInternalLayout(this); } @@ -457,7 +457,7 @@ public override Size GetPreferredSize(Size constrainingSize) /// private void InvalidateSplitButtonLayout() { - this.splitButtonButtonLayout = null; + splitButtonButtonLayout = null; CalculateLayout(); } @@ -552,7 +552,7 @@ protected override void OnMouseDown(MouseEventArgs e) { Debug.Assert(ParentInternal != null, "Parent is null here, not going to get accurate ID"); openMouseId = (ParentInternal == null) ? (byte)0 : ParentInternal.GetMouseId(); - this.ShowDropDown(/*mousePress = */true); + ShowDropDown(/*mousePress = */true); } } } @@ -595,7 +595,7 @@ protected override void OnMouseUp(MouseEventArgs e) } } Point clickPoint = new Point(e.X, e.Y); - if ((e.Button == MouseButtons.Left) && this.SplitButtonButton.Bounds.Contains(clickPoint)) + if ((e.Button == MouseButtons.Left) && SplitButtonButton.Bounds.Contains(clickPoint)) { bool shouldFireDoubleClick = false; if (DoubleClickEnabled) @@ -647,7 +647,7 @@ protected override void OnRightToLeftChanged(EventArgs e) protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { - ToolStripRenderer renderer = this.Renderer; + ToolStripRenderer renderer = Renderer; if (renderer != null) { InvalidateSplitButtonLayout(); @@ -662,7 +662,7 @@ protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) if ((DisplayStyle & ToolStripItemDisplayStyle.Text) != ToolStripItemDisplayStyle.None) { - renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, SplitButtonButton.Text, SplitButtonButtonLayout.TextRectangle, this.ForeColor, this.Font, SplitButtonButtonLayout.TextFormat)); + renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, SplitButtonButton.Text, SplitButtonButtonLayout.TextRectangle, ForeColor, Font, SplitButtonButtonLayout.TextFormat)); } } } @@ -748,7 +748,7 @@ public override Padding Padding { get { - return this.owner.Padding; + return owner.Padding; } set { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitStackLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitStackLayout.cs index c4b9eed244d..50971e43d5a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitStackLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitStackLayout.cs @@ -27,7 +27,7 @@ internal class ToolStripSplitStackLayout : LayoutEngine #endif internal ToolStripSplitStackLayout(ToolStrip owner) { - this.toolStrip = owner; + toolStrip = owner; } // this is the index we use to send items to the overflow @@ -62,7 +62,7 @@ private Size OverflowButtonSize { get { - ToolStrip toolStrip = this.ToolStrip; + ToolStrip toolStrip = ToolStrip; if (!toolStrip.CanOverflow) { return Size.Empty; @@ -115,7 +115,7 @@ private void CalculatePlacementsHorizontal() { ResetItemPlacements(); - ToolStrip toolStrip = this.ToolStrip; + ToolStrip toolStrip = ToolStrip; int currentWidth = 0; //toolStrip.Padding.Horizontal; if (ToolStrip.CanOverflow) @@ -144,7 +144,7 @@ private void CalculatePlacementsHorizontal() if (item.Overflow != ToolStripItemOverflow.Always && item.Placement == ToolStripItemPlacement.None) { // since we havent parented the item yet - the auto size wont have reset the size yet. - Size itemSize = item.AutoSize ? item.GetPreferredSize(this.displayRectangle.Size) : item.Size; + Size itemSize = item.AutoSize ? item.GetPreferredSize(displayRectangle.Size) : item.Size; currentWidth += itemSize.Width + item.Margin.Horizontal; @@ -174,7 +174,7 @@ private void CalculatePlacementsVertical() { ResetItemPlacements(); - ToolStrip toolStrip = this.ToolStrip; + ToolStrip toolStrip = ToolStrip; int currentHeight = 0; //toolStrip.Padding.Vertical; if (ToolStrip.CanOverflow) @@ -268,7 +268,7 @@ internal override bool LayoutCore(IArrangedElement container, LayoutEventArgs la } InvalidateLayout(); - this.displayRectangle = toolStrip.DisplayRectangle; + displayRectangle = toolStrip.DisplayRectangle; // pick a location that's outside of the displayed region to send // items that will potentially clobber/overlay others. @@ -643,7 +643,7 @@ private void SetItemLocation(ToolStripItem item, Point itemLocation, Size itemSi private void PlaceItems() { - ToolStrip toolStrip = this.ToolStrip; + ToolStrip toolStrip = ToolStrip; for (int i = 0; i < toolStrip.Items.Count; i++) { @@ -667,7 +667,7 @@ private void PlaceItems() private void ResetItemPlacements() { - ToolStrip toolStrip = this.ToolStrip; + ToolStrip toolStrip = ToolStrip; for (int i = 0; i < toolStrip.Items.Count; i++) { @@ -732,7 +732,7 @@ private int SendNextItemToOverflow(int spaceNeeded, bool horizontal) // send the item to the overflow. item.SetPlacement(ToolStripItemPlacement.Overflow); - if (this.OverflowRequired == false) + if (OverflowRequired == false) { // this is the first item we're sending down. // we now need to account for the width or height of the overflow button @@ -741,10 +741,10 @@ private int SendNextItemToOverflow(int spaceNeeded, bool horizontal) if (DebugLayoutTraceSwitch.TraceVerbose) { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Turns out we now need an overflow button, space needed now: {0}", spaceNeeded.ToString(CultureInfo.InvariantCulture))); } #endif - this.OverflowRequired = true; + OverflowRequired = true; } - this.OverflowSpace += (horizontal) ? itemSize.Width + itemMargin.Horizontal : itemSize.Height + itemMargin.Vertical; + OverflowSpace += (horizontal) ? itemSize.Width + itemMargin.Horizontal : itemSize.Height + itemMargin.Vertical; } if (freedSpace > spaceNeeded) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripStatusLabel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripStatusLabel.cs index 303e757c755..b6c9d8409ff 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripStatusLabel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripStatusLabel.cs @@ -250,9 +250,9 @@ public override System.Drawing.Size GetPreferredSize(System.Drawing.Size constra protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { - if (this.Owner != null) + if (Owner != null) { - ToolStripRenderer renderer = this.Renderer; + ToolStripRenderer renderer = Renderer; renderer.DrawToolStripStatusLabelBackground(new ToolStripItemRenderEventArgs(e.Graphics, this)); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripTextBox.cs index f1949895c5a..eedc1b8df25 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripTextBox.cs @@ -43,7 +43,7 @@ public ToolStripTextBox() : base(CreateControlInstance()) public ToolStripTextBox(string name) : this() { - this.Name = name; + Name = name; } [EditorBrowsable(EditorBrowsableState.Never)] @@ -156,7 +156,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga if (direction == UnsafeNativeMethods.NavigateDirection.FirstChild || direction == UnsafeNativeMethods.NavigateDirection.LastChild) { - return this.ownerItem.TextBox.AccessibilityObject; + return ownerItem.TextBox.AccessibilityObject; } // Handle Parent and other directions in base ToolStripItem.FragmentNavigate() method. @@ -607,7 +607,7 @@ private class ToolStripTextBoxControl : TextBox public ToolStripTextBoxControl() { // required to make the text box height match the combo. - this.Font = ToolStripManager.DefaultFont; + Font = ToolStripManager.DefaultFont; isFontSet = false; } @@ -627,7 +627,7 @@ private NativeMethods.RECT AbsoluteClientRECT int offsetY = -rect.top; // fetch the client rect, then apply the offset. - UnsafeNativeMethods.GetClientRect(new HandleRef(this, this.Handle), ref rect); + UnsafeNativeMethods.GetClientRect(new HandleRef(this, Handle), ref rect); rect.left += offsetX; rect.right += offsetX; @@ -720,7 +720,7 @@ private void InvalidateNonClient() try { // get the total client area, then exclude the client by using XOR - hTotalRegion = new HandleRef(this, SafeNativeMethods.CreateRectRgn(0, 0, this.Width, this.Height)); + hTotalRegion = new HandleRef(this, SafeNativeMethods.CreateRectRgn(0, 0, Width, Height)); hClientRegion = new HandleRef(this, SafeNativeMethods.CreateRectRgn(absoluteClientRectangle.left, absoluteClientRectangle.top, absoluteClientRectangle.right, absoluteClientRectangle.bottom)); hNonClientRegion = new HandleRef(this, SafeNativeMethods.CreateRectRgn(0, 0, 0, 0)); @@ -829,7 +829,7 @@ private void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventAr { if (!isFontSet) { - this.Font = ToolStripManager.DefaultFont; + Font = ToolStripManager.DefaultFont; } } } @@ -880,8 +880,8 @@ private void WmNCPaint(ref Message m) { // Don't set the clipping region based on the WParam - windows seems to take out the two pixels intended for the non-client border. - Color outerBorderColor = (MouseIsOver || Focused) ? ColorTable.TextBoxBorder : this.BackColor; - Color innerBorderColor = this.BackColor; + Color outerBorderColor = (MouseIsOver || Focused) ? ColorTable.TextBoxBorder : BackColor; + Color innerBorderColor = BackColor; if (!Enabled) { @@ -896,23 +896,23 @@ private void WmNCPaint(ref Message m) // could have set up a clip and fill-rectangled, thought this would be faster. using (Brush b = new SolidBrush(innerBorderColor)) { - g.FillRectangle(b, 0, 0, this.Width, clientRect.Top); // top border - g.FillRectangle(b, 0, 0, clientRect.Left, this.Height); // left border - g.FillRectangle(b, 0, clientRect.Bottom, this.Width, this.Height - clientRect.Height); // bottom border - g.FillRectangle(b, clientRect.Right, 0, this.Width - clientRect.Right, this.Height); // right border + g.FillRectangle(b, 0, 0, Width, clientRect.Top); // top border + g.FillRectangle(b, 0, 0, clientRect.Left, Height); // left border + g.FillRectangle(b, 0, clientRect.Bottom, Width, Height - clientRect.Height); // bottom border + g.FillRectangle(b, clientRect.Right, 0, Width - clientRect.Right, Height); // right border } // paint the outside rect. using (Pen p = new Pen(outerBorderColor)) { - g.DrawRectangle(p, 0, 0, this.Width - 1, this.Height - 1); + g.DrawRectangle(p, 0, 0, Width - 1, Height - 1); } } } finally { - UnsafeNativeMethods.ReleaseDC(new HandleRef(this, this.Handle), hdc); + UnsafeNativeMethods.ReleaseDC(new HandleRef(this, Handle), hdc); } // we've handled WM_NCPAINT. m.Result = IntPtr.Zero; @@ -943,7 +943,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRo { get { - var toolStripTextBoxControl = this.Owner as ToolStripTextBoxControl; + var toolStripTextBoxControl = Owner as ToolStripTextBoxControl; if (toolStripTextBoxControl != null) { return toolStripTextBoxControl.Owner.Owner.AccessibilityObject; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs index abb1ba4eb69..3a3b1a0f477 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs @@ -149,7 +149,7 @@ public bool Active internal void HideToolTip(IKeyboardToolTip currentTool) { - this.Hide(currentTool.GetOwnerWindow()); + Hide(currentTool.GetOwnerWindow()); } /// @@ -183,7 +183,7 @@ public int AutomaticDelay internal string GetCaptionForTool(Control tool) { Debug.Assert(tool != null, "tool should not be null"); - return ((TipInfo)this.tools[tool])?.Caption; + return ((TipInfo)tools[tool])?.Caption; } /// @@ -657,13 +657,13 @@ private Control TopLevelControl topLevelControl = baseVar; if (baseVar != null) { - baseVar.HandleCreated += new EventHandler(this.TopLevelCreated); - baseVar.HandleDestroyed += new EventHandler(this.TopLevelDestroyed); + baseVar.HandleCreated += new EventHandler(TopLevelCreated); + baseVar.HandleDestroyed += new EventHandler(TopLevelDestroyed); if (baseVar.IsHandleCreated) { TopLevelCreated(baseVar, EventArgs.Empty); } - baseVar.ParentChanged += new EventHandler(this.OnTopLevelPropertyChanged); + baseVar.ParentChanged += new EventHandler(OnTopLevelPropertyChanged); } } else @@ -771,9 +771,9 @@ private void HandleCreated(object sender, EventArgs eventargs) topLevelControl = null; Control control = (Control)sender; - this.CreateRegion(control); - this.CheckNativeToolTip(control); - this.CheckCompositeControls(control); + CreateRegion(control); + CheckNativeToolTip(control); + CheckCompositeControls(control); KeyboardToolTipStateMachine.Instance.Hook(control, this); } @@ -843,7 +843,7 @@ private void CheckCompositeControls(Control associatedControl) private void HandleDestroyed(object sender, EventArgs eventargs) { Control control = (Control)sender; - this.DestroyRegion(control); + DestroyRegion(control); KeyboardToolTipStateMachine.Instance.Unhook(control, this); } @@ -901,11 +901,11 @@ public bool CanExtend(object target) private void ClearTopLevelControlEvents() { - if (this.topLevelControl != null) + if (topLevelControl != null) { - this.topLevelControl.ParentChanged -= new EventHandler(this.OnTopLevelPropertyChanged); - this.topLevelControl.HandleCreated -= new EventHandler(this.TopLevelCreated); - this.topLevelControl.HandleDestroyed -= new EventHandler(this.TopLevelDestroyed); + topLevelControl.ParentChanged -= new EventHandler(OnTopLevelPropertyChanged); + topLevelControl.HandleCreated -= new EventHandler(TopLevelCreated); + topLevelControl.HandleDestroyed -= new EventHandler(TopLevelDestroyed); } } @@ -1081,8 +1081,8 @@ private void CreateRegion(Control ctl) { // Remove first to purge any duplicates... // - ctl.MouseMove -= new MouseEventHandler(this.MouseMove); - ctl.MouseMove += new MouseEventHandler(this.MouseMove); + ctl.MouseMove -= new MouseEventHandler(MouseMove); + ctl.MouseMove += new MouseEventHandler(MouseMove); } } @@ -1100,7 +1100,7 @@ private void MouseMove(object sender, MouseEventArgs me) if (created.ContainsKey(ctl)) { - ctl.MouseMove -= new MouseEventHandler(this.MouseMove); + ctl.MouseMove -= new MouseEventHandler(MouseMove); } } @@ -1129,7 +1129,7 @@ private void DestroyRegion(Control ctl) bool handlesCreated = ctl.IsHandleCreated && topLevelControl != null && topLevelControl.IsHandleCreated - && !this.isDisposing; + && !isDisposing; Form topForm = topLevelControl as Form; if (topForm == null || (topForm != null && !topForm.Modal)) @@ -1157,7 +1157,7 @@ protected override void Dispose(bool disposing) if (disposing) { - this.isDisposing = true; + isDisposing = true; try { ClearTopLevelControlEvents(); @@ -1176,12 +1176,12 @@ protected override void Dispose(bool disposing) Form baseFrom = TopLevelControl as Form; if (baseFrom != null) { - baseFrom.Deactivate -= new EventHandler(this.BaseFormDeactivate); + baseFrom.Deactivate -= new EventHandler(BaseFormDeactivate); } } finally { - this.isDisposing = false; + isDisposing = false; } } base.Dispose(disposing); @@ -1215,12 +1215,12 @@ internal bool GetHandleCreated() /// private NativeMethods.TOOLINFO_TOOLTIP GetMinTOOLINFO(Control ctl) { - return this.GetMinToolInfoForHandle(ctl.Handle); + return GetMinToolInfoForHandle(ctl.Handle); } private NativeMethods.TOOLINFO_TOOLTIP GetMinToolInfoForTool(IWin32Window tool) { - return this.GetMinToolInfoForHandle(tool.Handle); + return GetMinToolInfoForHandle(tool.Handle); } private NativeMethods.TOOLINFO_TOOLTIP GetMinToolInfoForHandle(IntPtr handle) @@ -1433,13 +1433,13 @@ private IntPtr GetWindowFromPoint(Point screenCoords, ref bool success) private void OnTopLevelPropertyChanged(object s, EventArgs e) { ClearTopLevelControlEvents(); - this.topLevelControl = null; + topLevelControl = null; // We must re-aquire this control. If the existing top level control's handle // was never created, but the new parent has a handle, if we don't re-get // the top level control here we won't ever create the tooltip handle. // - this.topLevelControl = TopLevelControl; + topLevelControl = TopLevelControl; } /// @@ -1475,8 +1475,8 @@ public void RemoveAll() { DestroyRegion(regions[i]); } - regions[i].HandleCreated -= new EventHandler(this.HandleCreated); - regions[i].HandleDestroyed -= new EventHandler(this.HandleDestroyed); + regions[i].HandleCreated -= new EventHandler(HandleCreated); + regions[i].HandleDestroyed -= new EventHandler(HandleDestroyed); KeyboardToolTipStateMachine.Instance.Unhook(regions[i], this); } @@ -1485,7 +1485,7 @@ public void RemoveAll() tools.Clear(); ClearTopLevelControlEvents(); - this.topLevelControl = null; + topLevelControl = null; KeyboardToolTipStateMachine.Instance.ResetStateMachine(this); } @@ -1577,8 +1577,8 @@ private void SetToolTipInternal(Control control, TipInfo info) if (!empty && !exists) { - control.HandleCreated += new EventHandler(this.HandleCreated); - control.HandleDestroyed += new EventHandler(this.HandleDestroyed); + control.HandleCreated += new EventHandler(HandleCreated); + control.HandleDestroyed += new EventHandler(HandleDestroyed); if (control.IsHandleCreated) { @@ -1613,8 +1613,8 @@ private void SetToolTipInternal(Control control, TipInfo info) else if (empty && exists && !DesignMode) { - control.HandleCreated -= new EventHandler(this.HandleCreated); - control.HandleDestroyed -= new EventHandler(this.HandleDestroyed); + control.HandleCreated -= new EventHandler(HandleCreated); + control.HandleDestroyed -= new EventHandler(HandleDestroyed); if (control.IsHandleCreated) { @@ -1730,9 +1730,9 @@ private void ShowTooltip(string text, IWin32Window win, int duration) if (duration > 0) { - if (this.originalPopupDelay == 0) + if (originalPopupDelay == 0) { - this.originalPopupDelay = AutoPopDelay; + originalPopupDelay = AutoPopDelay; } AutoPopDelay = duration; } @@ -1898,13 +1898,13 @@ internal void ShowKeyboardToolTip(string text, IKeyboardToolTip tool, int durati // At first, place the tooltip at the middle of the tool (default location) int pointX = (toolRectangle.Left + toolRectangle.Right) / 2; int pointY = (toolRectangle.Top + toolRectangle.Bottom) / 2; - this.SetTool(tool.GetOwnerWindow(), text, TipInfo.Type.Absolute, new Point(pointX, pointY)); + SetTool(tool.GetOwnerWindow(), text, TipInfo.Type.Absolute, new Point(pointX, pointY)); // Then look for a better ToolTip location Size bubbleSize; - if (this.TryGetBubbleSize(tool, toolRectangle, out bubbleSize)) + if (TryGetBubbleSize(tool, toolRectangle, out bubbleSize)) { - Point optimalPoint = this.GetOptimalToolTipPosition(tool, toolRectangle, bubbleSize.Width, bubbleSize.Height); + Point optimalPoint = GetOptimalToolTipPosition(tool, toolRectangle, bubbleSize.Width, bubbleSize.Height); // The optimal point should be used as a tracking position pointX = optimalPoint.X; @@ -1915,7 +1915,7 @@ internal void ShowKeyboardToolTip(string text, IKeyboardToolTip tool, int durati tipInfo.Position = new Point(pointX, pointY); // Ensure that the tooltip bubble is moved to the optimal position even when a mouse tooltip is being replaced with a keyboard tooltip - this.Reposition(optimalPoint, bubbleSize); + Reposition(optimalPoint, bubbleSize); } SetTrackPosition(pointX, pointY); @@ -1925,7 +1925,7 @@ internal void ShowKeyboardToolTip(string text, IKeyboardToolTip tool, int durati private bool TryGetBubbleSize(IKeyboardToolTip tool, Rectangle toolRectangle, out Size bubbleSize) { // Get bubble size to use it for optimal position calculation - IntPtr bubbleSizeInt = UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.TTM_GETBUBBLESIZE, 0, this.GetMinToolInfoForTool(tool.GetOwnerWindow())); + IntPtr bubbleSizeInt = UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_GETBUBBLESIZE, 0, GetMinToolInfoForTool(tool.GetOwnerWindow())); if (bubbleSizeInt.ToInt32() != NativeMethods.S_FALSE) { int width = NativeMethods.Util.LOWORD(bubbleSizeInt); @@ -1987,7 +1987,7 @@ private Point GetOptimalToolTipPosition(IKeyboardToolTip tool, Rectangle toolRec // Calculate area of possible locations within top level control rectangle long[] locationWithinTopControlAreas = new long[LOCATION_TOTAL]; - Rectangle topContainerBounds = ((IKeyboardToolTip)this.TopLevelControl)?.GetNativeScreenRectangle() ?? Rectangle.Empty; + Rectangle topContainerBounds = ((IKeyboardToolTip)TopLevelControl)?.GetNativeScreenRectangle() ?? Rectangle.Empty; if (!topContainerBounds.IsEmpty) { for (int i = 0; i < possibleLocations.Length; i++) @@ -2009,7 +2009,7 @@ private Point GetOptimalToolTipPosition(IKeyboardToolTip tool, Rectangle toolRec bool rtlEnabled = tool.HasRtlModeEnabled(); for (int i = 1; i < possibleLocations.Length; i++) { - if (this.IsCompetingLocationBetter(leastClippedArea, leastWeight, biggestAreaWithinTopControl, locationIndex, + if (IsCompetingLocationBetter(leastClippedArea, leastWeight, biggestAreaWithinTopControl, locationIndex, locationClippedAreas[i], locationWeights[i], locationWithinTopControlAreas[i], i, rtlEnabled)) { @@ -2096,7 +2096,7 @@ private void SetTrackPosition(int pointX, int pointY) try { trackPosition = true; - UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.TTM_TRACKPOSITION, 0, NativeMethods.Util.MAKELONG(pointX, pointY)); + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_TRACKPOSITION, 0, NativeMethods.Util.MAKELONG(pointX, pointY)); } finally { @@ -2124,8 +2124,8 @@ public void Hide(IWin32Window win) if (GetHandleCreated()) { IntPtr hWnd = Control.GetSafeHandle(win); - UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.TTM_TRACKACTIVATE, 0, GetWinTOOLINFO(hWnd)); - UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.TTM_DELTOOL, 0, GetWinTOOLINFO(hWnd)); + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_TRACKACTIVATE, 0, GetWinTOOLINFO(hWnd)); + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_DELTOOL, 0, GetWinTOOLINFO(hWnd)); } StopTimer(); @@ -2150,7 +2150,7 @@ public void Hide(IWin32Window win) Form baseFrom = tool.FindForm(); if (baseFrom != null) { - baseFrom.Deactivate -= new EventHandler(this.BaseFormDeactivate); + baseFrom.Deactivate -= new EventHandler(BaseFormDeactivate); } } @@ -2215,8 +2215,8 @@ private void SetTool(IWin32Window win, string text, TipInfo.Type type, Point pos tt.Position = position; tools[tool] = tt; - UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.TTM_SETTOOLINFO, 0, ti); - UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.TTM_TRACKACTIVATE, 1, ti); + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_SETTOOLINFO, 0, ti); + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_TRACKACTIVATE, 1, ti); } finally { @@ -2258,8 +2258,8 @@ private void SetTool(IWin32Window win, string text, TipInfo.Type type, Point pos try { toolInfo.lpszText = Marshal.StringToHGlobalAuto(text); - UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.TTM_ADDTOOL, 0, toolInfo); - UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.TTM_TRACKACTIVATE, 1, toolInfo); + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_ADDTOOL, 0, toolInfo); + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_TRACKACTIVATE, 1, toolInfo); } finally { @@ -2278,7 +2278,7 @@ private void SetTool(IWin32Window win, string text, TipInfo.Type type, Point pos Form baseFrom = tool.FindForm(); if (baseFrom != null) { - baseFrom.Deactivate += new EventHandler(this.BaseFormDeactivate); + baseFrom.Deactivate += new EventHandler(BaseFormDeactivate); } } @@ -2365,7 +2365,7 @@ private void Reposition(Point tipPosition, Size tipSize) moveToLocation.Y = screen.WorkingArea.Bottom - tipSize.Height; } - SafeNativeMethods.SetWindowPos(new HandleRef(this, this.Handle), + SafeNativeMethods.SetWindowPos(new HandleRef(this, Handle), NativeMethods.HWND_TOPMOST, moveToLocation.X, moveToLocation.Y, tipSize.Width, tipSize.Height, NativeMethods.SWP_NOACTIVATE | NativeMethods.SWP_NOSIZE | NativeMethods.SWP_NOOWNERZORDER); @@ -2547,7 +2547,7 @@ private void WmShow() if (e.Cancel) { cancelled = true; - SafeNativeMethods.SetWindowPos(new HandleRef(this, this.Handle), + SafeNativeMethods.SetWindowPos(new HandleRef(this, Handle), NativeMethods.HWND_TOPMOST, 0, 0, 0, 0, NativeMethods.SWP_NOACTIVATE | NativeMethods.SWP_NOOWNERZORDER); @@ -2557,7 +2557,7 @@ private void WmShow() { cancelled = false; // Only width/height changes are respected, so set top,left to what we got earlier - SafeNativeMethods.SetWindowPos(new HandleRef(this, this.Handle), + SafeNativeMethods.SetWindowPos(new HandleRef(this, Handle), NativeMethods.HWND_TOPMOST, r.left, r.top, currentTooltipSize.Width, currentTooltipSize.Height, NativeMethods.SWP_NOACTIVATE | NativeMethods.SWP_NOOWNERZORDER); @@ -2738,8 +2738,8 @@ private void WmPop() tools.Remove(control); owners.Remove(win.Handle); - control.HandleCreated -= new EventHandler(this.HandleCreated); - control.HandleDestroyed -= new EventHandler(this.HandleDestroyed); + control.HandleCreated -= new EventHandler(HandleCreated); + control.HandleDestroyed -= new EventHandler(HandleDestroyed); created.Remove(control); if (originalPopupDelay != 0) @@ -2900,7 +2900,7 @@ private class ToolTipTimer : Timer public ToolTipTimer(IWin32Window owner) : base() { - this.host = owner; + host = owner; } public IWin32Window Host @@ -2933,10 +2933,10 @@ public enum Type public TipInfo(string caption, Type type) { this.caption = caption; - this.TipType = type; + TipType = type; if (type == Type.Auto) { - this.designerText = caption; + designerText = caption; } } @@ -2944,11 +2944,11 @@ public string Caption { get { - return ((this.TipType & (Type.Absolute | Type.SemiAbsolute)) != 0) ? caption : designerText; + return ((TipType & (Type.Absolute | Type.SemiAbsolute)) != 0) ? caption : designerText; } set { - this.caption = value; + caption = value; } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs index bd907b801ac..b5341aa496e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs @@ -961,12 +961,12 @@ protected override void OnMouseWheel(MouseEventArgs e) return; // Do not scroll when the user system setting is 0 lines per notch } - Debug.Assert(this.cumulativeWheelData > -NativeMethods.WHEEL_DELTA, "cumulativeWheelData is too small"); - Debug.Assert(this.cumulativeWheelData < NativeMethods.WHEEL_DELTA, "cumulativeWheelData is too big"); - this.cumulativeWheelData += e.Delta; + Debug.Assert(cumulativeWheelData > -NativeMethods.WHEEL_DELTA, "cumulativeWheelData is too small"); + Debug.Assert(cumulativeWheelData < NativeMethods.WHEEL_DELTA, "cumulativeWheelData is too big"); + cumulativeWheelData += e.Delta; float partialNotches; - partialNotches = (float)this.cumulativeWheelData / (float)NativeMethods.WHEEL_DELTA; + partialNotches = (float)cumulativeWheelData / (float)NativeMethods.WHEEL_DELTA; if (wheelScrollLines == -1) { @@ -983,13 +983,13 @@ protected override void OnMouseWheel(MouseEventArgs e) { absScrollBands = scrollBands; Value = Math.Min(absScrollBands + Value, Maximum); - this.cumulativeWheelData -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); + cumulativeWheelData -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); } else { absScrollBands = -scrollBands; Value = Math.Max(Value - absScrollBands, Minimum); - this.cumulativeWheelData -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); + cumulativeWheelData -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs index 75163c71d91..d415508593a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs @@ -200,7 +200,7 @@ public TreeNode(string text) : this() public TreeNode(string text, TreeNode[] children) : this() { this.text = text; - this.Nodes.AddRange(children); + Nodes.AddRange(children); } /// @@ -209,8 +209,8 @@ public TreeNode(string text, TreeNode[] children) : this() public TreeNode(string text, int imageIndex, int selectedImageIndex) : this() { this.text = text; - this.ImageIndexer.Index = imageIndex; - this.SelectedImageIndexer.Index = selectedImageIndex; + ImageIndexer.Index = imageIndex; + SelectedImageIndexer.Index = selectedImageIndex; } /// @@ -219,9 +219,9 @@ public TreeNode(string text, int imageIndex, int selectedImageIndex) : this() public TreeNode(string text, int imageIndex, int selectedImageIndex, TreeNode[] children) : this() { this.text = text; - this.ImageIndexer.Index = imageIndex; - this.SelectedImageIndexer.Index = selectedImageIndex; - this.Nodes.AddRange(children); + ImageIndexer.Index = imageIndex; + SelectedImageIndexer.Index = selectedImageIndex; + Nodes.AddRange(children); } /** @@ -258,7 +258,7 @@ public Color BackColor set { // get the old value - Color oldbk = this.BackColor; + Color oldbk = BackColor; // If we're setting the color to the default again, delete the propBag if it doesn't contain // useful data. if (value.IsEmpty) @@ -292,7 +292,7 @@ public Rectangle Bounds { get { - TreeView tv = this.TreeView; + TreeView tv = TreeView; if (tv == null || tv.IsDisposed) { return Rectangle.Empty; @@ -319,7 +319,7 @@ internal Rectangle RowBounds { get { - TreeView tv = this.TreeView; + TreeView tv = TreeView; NativeMethods.RECT rc = new NativeMethods.RECT(); unsafe { *((IntPtr*)&rc.left) = Handle; } @@ -364,7 +364,7 @@ internal bool CheckedInternal if (handle == IntPtr.Zero) return; - TreeView tv = this.TreeView; + TreeView tv = TreeView; if (tv == null || !tv.IsHandleCreated || tv.IsDisposed) return; @@ -510,7 +510,7 @@ public Color ForeColor } set { - Color oldfc = this.ForeColor; + Color oldfc = ForeColor; // If we're setting the color to the default again, delete the propBag if it doesn't contain // useful data. if (value.IsEmpty) @@ -693,7 +693,7 @@ public bool IsVisible { if (handle == IntPtr.Zero) return false; - TreeView tv = this.TreeView; + TreeView tv = TreeView; if (tv.IsDisposed) { return false; @@ -736,7 +736,7 @@ public int Level { get { - if (this.Parent == null) + if (Parent == null) { return 0; } @@ -780,7 +780,7 @@ public TreeNode NextVisibleNode // TVGN_NEXTVISIBLE can only be sent if the specified node is visible. // So before sending, we check if this node is visible. If not, we find the first visible parent. // - TreeView tv = this.TreeView; + TreeView tv = TreeView; if (tv == null || tv.IsDisposed) { return null; @@ -825,7 +825,7 @@ public Font NodeFont } set { - Font oldfont = this.NodeFont; + Font oldfont = NodeFont; // If we're setting the font to the default again, delete the propBag if it doesn't contain // useful data. if (value == null) @@ -927,7 +927,7 @@ public TreeNode PrevVisibleNode // So before sending, we check if this node is visible. If not, we find the first visible parent. // TreeNode node = FirstVisibleParent; - TreeView tv = this.TreeView; + TreeView tv = TreeView; if (node != null) { @@ -1012,7 +1012,7 @@ internal int State if (handle == IntPtr.Zero) return 0; - TreeView tv = this.TreeView; + TreeView tv = TreeView; if (tv == null || tv.IsDisposed) { return 0; @@ -1126,7 +1126,7 @@ public string Text } set { - this.text = value; + text = value; UpdateNode(NativeMethods.TVIF_TEXT); } } @@ -1168,7 +1168,7 @@ public string Name } set { - this.name = value; + name = value; } } @@ -1391,7 +1391,7 @@ internal void Clear() /// public virtual object Clone() { - Type clonedType = this.GetType(); + Type clonedType = GetType(); TreeNode node = null; if (clonedType == typeof(TreeNode)) @@ -1444,8 +1444,8 @@ public virtual object Clone() { node.propBag = OwnerDrawPropertyBag.Copy(propBag); } - node.Checked = this.Checked; - node.Tag = this.Tag; + node.Checked = Checked; + node.Tag = Tag; return node; } @@ -1634,7 +1634,7 @@ protected virtual void Deserialize(SerializationInfo serializationInfo, Streamin /// public void EndEdit(bool cancel) { - TreeView tv = this.TreeView; + TreeView tv = TreeView; if (tv == null || tv.IsDisposed) { return; @@ -1683,14 +1683,14 @@ private void EnsureStateImageValue() if (treeView.CheckBoxes && treeView.StateImageList != null) { - if (!string.IsNullOrEmpty(this.StateImageKey)) + if (!string.IsNullOrEmpty(StateImageKey)) { - this.StateImageIndex = (this.Checked) ? 1 : 0; - this.StateImageKey = treeView.StateImageList.Images.Keys[this.StateImageIndex]; + StateImageIndex = (Checked) ? 1 : 0; + StateImageKey = treeView.StateImageList.Images.Keys[StateImageIndex]; } else { - this.StateImageIndex = (this.Checked) ? 1 : 0; + StateImageIndex = (Checked) ? 1 : 0; } } } @@ -1701,7 +1701,7 @@ private void EnsureStateImageValue() /// public void EnsureVisible() { - TreeView tv = this.TreeView; + TreeView tv = TreeView; if (tv == null || tv.IsDisposed) { return; @@ -1765,7 +1765,7 @@ private void GetFullPath(StringBuilder path, string pathSeparator) parent.GetFullPath(path, pathSeparator); if (parent.parent != null) path.Append(pathSeparator); - path.Append(this.text); + path.Append(text); } } @@ -1834,7 +1834,7 @@ private void InvalidateHostTree() internal void Realize(bool insertFirst) { // Debug.assert(handle == 0, "Node already realized"); - TreeView tv = this.TreeView; + TreeView tv = TreeView; if (tv == null || !tv.IsHandleCreated || tv.IsDisposed) return; @@ -1985,7 +1985,7 @@ internal void Remove(bool notify) expandOnRealization = expanded; // unrealize ourself - TreeView tv = this.TreeView; + TreeView tv = TreeView; if (tv == null || tv.IsDisposed) { return; @@ -2057,12 +2057,12 @@ protected virtual void Serialize(SerializationInfo si, StreamingContext context) si.AddValue("SelectedImageIndex", SelectedImageIndexer.Index); si.AddValue("SelectedImageKey", SelectedImageIndexer.Key); - if (this.treeView != null && this.treeView.StateImageList != null) + if (treeView != null && treeView.StateImageList != null) { si.AddValue("StateImageIndex", StateImageIndexer.Index); } - if (this.treeView != null && this.treeView.StateImageList != null) + if (treeView != null && treeView.StateImageList != null) { si.AddValue("StateImageKey", StateImageIndexer.Key); } @@ -2157,7 +2157,7 @@ private void UpdateNode(int mask) internal void UpdateImage() { - TreeView tv = this.TreeView; + TreeView tv = TreeView; if (tv.IsDisposed) { return; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeCollection.cs index 44ce34ce555..42ebef62337 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeCollection.cs @@ -455,7 +455,7 @@ public virtual int IndexOfKey(string key) } // step 2 - search for the item - for (int i = 0; i < this.Count; i++) + for (int i = 0; i < Count; i++) { if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) { @@ -586,7 +586,7 @@ public virtual TreeNode Insert(int index, string key, string text, string imageK /// private bool IsValidIndex(int index) { - return ((index >= 0) && (index < this.Count)); + return ((index >= 0) && (index < Count)); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs index 549ad06b605..0f52409860d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs @@ -174,7 +174,7 @@ public TreeView() : base() { - this.treeViewState = new System.Collections.Specialized.BitVector32(TREEVIEWSTATE_showRootLines | + treeViewState = new System.Collections.Specialized.BitVector32(TREEVIEWSTATE_showRootLines | TREEVIEWSTATE_showPlusMinus | TREEVIEWSTATE_showLines | TREEVIEWSTATE_scrollable | @@ -1789,7 +1789,7 @@ internal void SetToolTip(ToolTip toolTip, string toolTipText) if (toolTip != null) { UnsafeNativeMethods.SendMessage(new HandleRef(toolTip, toolTip.Handle), NativeMethods.TTM_SETMAXTIPWIDTH, 0, SystemInformation.MaxWindowTrackSize.Width); - UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.TVM_SETTOOLTIPS, new HandleRef(toolTip, toolTip.Handle), 0); + UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TVM_SETTOOLTIPS, new HandleRef(toolTip, toolTip.Handle), 0); controlToolTipText = toolTipText; } } @@ -2009,8 +2009,8 @@ protected virtual void OnDrawNode(DrawTreeNodeEventArgs e) protected override void OnHandleCreated(EventArgs e) { - TreeNode savedSelectedNode = this.selectedNode; - this.selectedNode = null; + TreeNode savedSelectedNode = selectedNode; + selectedNode = null; base.OnHandleCreated(e); @@ -2082,15 +2082,15 @@ protected override void OnHandleCreated(EventArgs e) { treeViewState[TREEVIEWSTATE_stopResizeWindowMsgs] = true; - oldSize = this.Width; + oldSize = Width; int flags = NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE | NativeMethods.SWP_NOMOVE; - SafeNativeMethods.SetWindowPos(new HandleRef(this, this.Handle), NativeMethods.NullHandleRef, this.Left, this.Top, int.MaxValue, this.Height, flags); + SafeNativeMethods.SetWindowPos(new HandleRef(this, Handle), NativeMethods.NullHandleRef, Left, Top, int.MaxValue, Height, flags); root.Realize(false); if (oldSize != 0) { - SafeNativeMethods.SetWindowPos(new HandleRef(this, this.Handle), NativeMethods.NullHandleRef, this.Left, this.Top, oldSize, this.Height, flags); + SafeNativeMethods.SetWindowPos(new HandleRef(this, Handle), NativeMethods.NullHandleRef, Left, Top, oldSize, Height, flags); } } finally @@ -2378,7 +2378,7 @@ protected override void OnKeyDown(KeyEventArgs e) // cancelled. if (CheckBoxes && (e.KeyData & Keys.KeyCode) == Keys.Space) { - TreeNode node = this.SelectedNode; + TreeNode node = SelectedNode; if (node != null) { bool eventReturn = TreeViewBeforeCheck(node, TreeViewAction.ByKeyboard); @@ -3025,7 +3025,7 @@ private unsafe bool WmShowToolTip(ref Message m) if (!ShowNodeToolTips) // default ToolTips { Rectangle bounds = tn.Bounds; - bounds.Location = this.PointToScreen(bounds.Location); + bounds.Location = PointToScreen(bounds.Location); UnsafeNativeMethods.SendMessage(new HandleRef(this, tooltipHandle), NativeMethods.TTM_ADJUSTRECT, 1, ref bounds); SafeNativeMethods.SetWindowPos(new HandleRef(this, tooltipHandle), @@ -3057,7 +3057,7 @@ private void WmNeedText(ref Message m) { tipText = tn.ToolTipText; } - else if (tn != null && tn.Bounds.Right > this.Bounds.Right) + else if (tn != null && tn.Bounds.Right > Bounds.Right) { tipText = tn.Text; } @@ -3208,7 +3208,7 @@ private void ShowContextMenu(TreeNode treeNode) // before calling TrackPopupMenuEx, and a task switch must be // forced after the call. - UnsafeNativeMethods.SetForegroundWindow(new HandleRef(this, this.Handle)); + UnsafeNativeMethods.SetForegroundWindow(new HandleRef(this, Handle)); contextMenu.OnPopup(EventArgs.Empty); @@ -3216,18 +3216,18 @@ private void ShowContextMenu(TreeNode treeNode) NativeMethods.TPM_VERTICAL, pt.x, pt.y, - new HandleRef(this, this.Handle), + new HandleRef(this, Handle), null); // Force task switch (see above) - UnsafeNativeMethods.PostMessage(new HandleRef(this, this.Handle), Interop.WindowMessages.WM_NULL, IntPtr.Zero, IntPtr.Zero); + UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), Interop.WindowMessages.WM_NULL, IntPtr.Zero, IntPtr.Zero); } // Need to send TVM_SELECTITEM to highlight the node while the contextMenuStrip is being shown. else if (menu != null) { UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), NativeMethods.TVM_SELECTITEM, NativeMethods.TVGN_DROPHILITE, treeNode.Handle); menu.ShowInternal(this, PointToClient(MousePosition),/*keyboardActivated*/false); - menu.Closing += new ToolStripDropDownClosingEventHandler(this.ContextMenuStripClosing); + menu.Closing += new ToolStripDropDownClosingEventHandler(ContextMenuStripClosing); } } } @@ -3237,7 +3237,7 @@ private void ContextMenuStripClosing(object sender, ToolStripDropDownClosingEven { ContextMenuStrip strip = sender as ContextMenuStrip; // Unhook the Event. - strip.Closing -= new ToolStripDropDownClosingEventHandler(this.ContextMenuStripClosing); + strip.Closing -= new ToolStripDropDownClosingEventHandler(ContextMenuStripClosing); SendMessage(NativeMethods.TVM_SELECTITEM, NativeMethods.TVGN_DROPHILITE, null); } @@ -3245,11 +3245,11 @@ private void WmPrint(ref Message m) { base.WndProc(ref m); - if ((NativeMethods.PRF_NONCLIENT & (int)m.LParam) != 0 && Application.RenderWithVisualStyles && this.BorderStyle == BorderStyle.Fixed3D) + if ((NativeMethods.PRF_NONCLIENT & (int)m.LParam) != 0 && Application.RenderWithVisualStyles && BorderStyle == BorderStyle.Fixed3D) { using (Graphics g = Graphics.FromHdc(m.WParam)) { - Rectangle rect = new Rectangle(0, 0, this.Size.Width - 1, this.Size.Height - 1); + Rectangle rect = new Rectangle(0, 0, Size.Width - 1, Size.Height - 1); g.DrawRectangle(new Pen(VisualStyleInformation.TextControlBorder), rect); rect.Inflate(-1, -1); g.DrawRectangle(SystemPens.Window, rect); @@ -3291,7 +3291,7 @@ protected override void WndProc(ref Message m) break; case NativeMethods.TVM_SETITEM: base.WndProc(ref m); - if (this.CheckBoxes) + if (CheckBoxes) { NativeMethods.TV_ITEM item = (NativeMethods.TV_ITEM)m.GetLParam(typeof(NativeMethods.TV_ITEM)); // Check for invalid node handle @@ -3301,7 +3301,7 @@ protected override void WndProc(ref Message m) item1.mask = NativeMethods.TVIF_HANDLE | NativeMethods.TVIF_STATE; item1.hItem = item.hItem; item1.stateMask = NativeMethods.TVIS_STATEIMAGEMASK; - UnsafeNativeMethods.SendMessage(new HandleRef(null, this.Handle), NativeMethods.TVM_GETITEM, 0, ref item1); + UnsafeNativeMethods.SendMessage(new HandleRef(null, Handle), NativeMethods.TVM_GETITEM, 0, ref item1); TreeNode node = NodeFromHandle(item.hItem); node.CheckedStateInternal = ((item1.state >> 12) > 1); @@ -3489,7 +3489,7 @@ protected override void WndProc(ref Message m) treeViewState[TREEVIEWSTATE_lastControlValidated] = false; WmImeSetFocus(); DefWndProc(ref m); - this.InvokeGotFocus(this, EventArgs.Empty); + InvokeGotFocus(this, EventArgs.Empty); } else { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewHitTestInfo.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewHitTestInfo.cs index 9d3af7cc857..2837fff7824 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewHitTestInfo.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewHitTestInfo.cs @@ -24,8 +24,8 @@ public class TreeViewHitTestInfo /// public TreeViewHitTestInfo(TreeNode hitNode, TreeViewHitTestLocations hitLocation) { - this.node = hitNode; - this.loc = hitLocation; + node = hitNode; + loc = hitLocation; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs index f6a74b18139..7df8702d580 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs @@ -90,14 +90,14 @@ public UpDownBase() upDownEdit = new UpDownEdit(this); upDownEdit.BorderStyle = BorderStyle.None; upDownEdit.AutoSize = false; - upDownEdit.KeyDown += new KeyEventHandler(this.OnTextBoxKeyDown); - upDownEdit.KeyPress += new KeyPressEventHandler(this.OnTextBoxKeyPress); - upDownEdit.TextChanged += new EventHandler(this.OnTextBoxTextChanged); - upDownEdit.LostFocus += new EventHandler(this.OnTextBoxLostFocus); - upDownEdit.Resize += new EventHandler(this.OnTextBoxResize); + upDownEdit.KeyDown += new KeyEventHandler(OnTextBoxKeyDown); + upDownEdit.KeyPress += new KeyPressEventHandler(OnTextBoxKeyPress); + upDownEdit.TextChanged += new EventHandler(OnTextBoxTextChanged); + upDownEdit.LostFocus += new EventHandler(OnTextBoxLostFocus); + upDownEdit.Resize += new EventHandler(OnTextBoxResize); upDownButtons.TabStop = false; upDownButtons.Size = new Size(defaultButtonsWidth, PreferredHeight); - upDownButtons.UpDown += new UpDownEventHandler(this.OnUpDown); + upDownButtons.UpDown += new UpDownEventHandler(OnUpDown); Controls.AddRange(new Control[] { upDownButtons, upDownEdit }); @@ -316,7 +316,7 @@ public override ContextMenu ContextMenu set { base.ContextMenu = value; - this.upDownEdit.ContextMenu = value; + upDownEdit.ContextMenu = value; } } @@ -329,7 +329,7 @@ public override ContextMenuStrip ContextMenuStrip set { base.ContextMenuStrip = value; - this.upDownEdit.ContextMenuStrip = value; + upDownEdit.ContextMenuStrip = value; } } @@ -774,7 +774,7 @@ protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); PositionControls(); - SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(this.UserPreferenceChanged); + SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(UserPreferenceChanged); } /// @@ -784,7 +784,7 @@ protected override void OnHandleCreated(EventArgs e) /// protected override void OnHandleDestroyed(EventArgs e) { - SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(this.UserPreferenceChanged); + SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(UserPreferenceChanged); base.OnHandleDestroyed(e); } @@ -865,7 +865,7 @@ protected override void OnPaint(PaintEventArgs e) /// protected virtual void OnTextBoxKeyDown(object source, KeyEventArgs e) { - this.OnKeyDown(e); + OnKeyDown(e); if (interceptArrowKeys) { @@ -898,7 +898,7 @@ protected virtual void OnTextBoxKeyDown(object source, KeyEventArgs e) /// protected virtual void OnTextBoxKeyPress(object source, KeyPressEventArgs e) { - this.OnKeyPress(e); + OnKeyPress(e); } @@ -918,7 +918,7 @@ protected virtual void OnTextBoxLostFocus(object source, EventArgs e) /// protected virtual void OnTextBoxResize(object source, EventArgs e) { - this.Height = PreferredHeight; + Height = PreferredHeight; PositionControls(); } @@ -938,7 +938,7 @@ protected virtual void OnTextBoxTextChanged(object source, EventArgs e) UserEdit = true; } - this.OnTextChanged(e); + OnTextChanged(e); OnChanged(source, EventArgs.Empty); } @@ -1023,12 +1023,12 @@ protected override void OnMouseWheel(MouseEventArgs e) return; // Do not scroll when the user system setting is 0 lines per notch } - Debug.Assert(this.wheelDelta > -NativeMethods.WHEEL_DELTA, "wheelDelta is too smal"); - Debug.Assert(this.wheelDelta < NativeMethods.WHEEL_DELTA, "wheelDelta is too big"); - this.wheelDelta += e.Delta; + Debug.Assert(wheelDelta > -NativeMethods.WHEEL_DELTA, "wheelDelta is too smal"); + Debug.Assert(wheelDelta < NativeMethods.WHEEL_DELTA, "wheelDelta is too big"); + wheelDelta += e.Delta; float partialNotches; - partialNotches = (float)this.wheelDelta / (float)NativeMethods.WHEEL_DELTA; + partialNotches = (float)wheelDelta / (float)NativeMethods.WHEEL_DELTA; if (wheelScrollLines == -1) { @@ -1048,7 +1048,7 @@ protected override void OnMouseWheel(MouseEventArgs e) UpButton(); absScrollBands--; } - this.wheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); + wheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); } else { @@ -1058,7 +1058,7 @@ protected override void OnMouseWheel(MouseEventArgs e) DownButton(); absScrollBands--; } - this.wheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); + wheelDelta -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); } } } @@ -1276,8 +1276,8 @@ protected override void WndProc(ref Message m) /// internal void SetToolTip(ToolTip toolTip, string caption) { - toolTip.SetToolTip(this.upDownEdit, caption); - toolTip.SetToolTip(this.upDownButtons, caption); + toolTip.SetToolTip(upDownEdit, caption); + toolTip.SetToolTip(upDownButtons, caption); } internal class UpDownEdit : TextBox @@ -1594,7 +1594,7 @@ protected override void OnMouseDown(MouseEventArgs e) // Focus the parent // - this.parent.Focus(); + parent.Focus(); if (!parent.ValidationCancelled && e.Button == MouseButtons.Left) { @@ -1731,13 +1731,13 @@ protected override void OnMouseUp(MouseEventArgs e) { if (!doubleClickFired) { - this.parent.OnClick(me); + parent.OnClick(me); } else { doubleClickFired = false; - this.parent.OnDoubleClick(me); - this.parent.OnMouseDoubleClick(me); + parent.OnDoubleClick(me); + parent.OnMouseDoubleClick(me); } } doubleClickFired = false; @@ -1815,7 +1815,7 @@ protected override void OnPaint(PaintEventArgs e) if (half_height != (ClientSize.Height + 1) / 2) { // When control has odd height, a line needs to be drawn below the buttons with the backcolor. - using (Pen pen = new Pen(this.parent.BackColor)) + using (Pen pen = new Pen(parent.BackColor)) { Rectangle clientRect = ClientRectangle; e.Graphics.DrawLine(pen, clientRect.Left, clientRect.Bottom - 1, clientRect.Right - 1, clientRect.Bottom - 1); @@ -1847,9 +1847,9 @@ protected void StartTimer() timer.Tick += new EventHandler(TimerHandler); } - this.timerInterval = DefaultTimerInterval; + timerInterval = DefaultTimerInterval; - timer.Interval = this.timerInterval; + timer.Interval = timerInterval; timer.Start(); } @@ -1887,15 +1887,15 @@ private void TimerHandler(object source, EventArgs args) if (timer != null) { // Accelerate timer. - this.timerInterval *= 7; - this.timerInterval /= 10; + timerInterval *= 7; + timerInterval /= 10; - if (this.timerInterval < 1) + if (timerInterval < 1) { - this.timerInterval = 1; + timerInterval = 1; } - timer.Interval = this.timerInterval; + timer.Interval = timerInterval; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleRenderer.cs index 7ba5cacbe93..130eb964abe 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleRenderer.cs @@ -187,7 +187,7 @@ public VisualStyleRenderer(string className, int part, int state) throw new ArgumentException(SR.VisualStylesInvalidCombination); } - this._class = className; + _class = className; this.part = part; this.state = state; } @@ -289,7 +289,7 @@ public void SetParameters(string className, int part, int state) throw new ArgumentException(SR.VisualStylesInvalidCombination); } - this._class = className; + _class = className; this.part = part; this.state = state; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs index 5080d87eb56..8b605650661 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs @@ -121,7 +121,7 @@ public bool AllowWebBrowserDrop { get { - return this.AxIWebBrowser2.RegisterAsDropTarget; + return AxIWebBrowser2.RegisterAsDropTarget; } set { @@ -129,8 +129,8 @@ public bool AllowWebBrowserDrop //OnDocumentCompleted. if (value != AllowWebBrowserDrop) { - this.AxIWebBrowser2.RegisterAsDropTarget = value; - this.Refresh(); + AxIWebBrowser2.RegisterAsDropTarget = value; + Refresh(); } } } @@ -147,13 +147,13 @@ public bool ScriptErrorsSuppressed { get { - return this.AxIWebBrowser2.Silent; + return AxIWebBrowser2.Silent; } set { if (value != ScriptErrorsSuppressed) { - this.AxIWebBrowser2.Silent = value; + AxIWebBrowser2.Silent = value; } } } @@ -261,7 +261,7 @@ public HtmlDocument Document { get { - object objDoc = this.AxIWebBrowser2.Document; + object objDoc = AxIWebBrowser2.Document; if (objDoc != null) { // Document is not necessarily an IHTMLDocument, it might be an office document as well. @@ -302,7 +302,7 @@ public Stream DocumentStream { get { - HtmlDocument htmlDocument = this.Document; + HtmlDocument htmlDocument = Document; if (htmlDocument == null) { return null; @@ -326,12 +326,12 @@ public Stream DocumentStream } set { - this.documentStreamToSetOnLoad = value; + documentStreamToSetOnLoad = value; try { webBrowserState[WEBBROWSERSTATE_documentStreamJustSet] = true; // Lets navigate to "about:blank" so that we get a "clean" document - this.Url = new Uri("about:blank"); + Url = new Uri("about:blank"); } finally { @@ -350,7 +350,7 @@ public string DocumentText { get { - Stream stream = this.DocumentStream; + Stream stream = DocumentStream; if (stream == null) { return ""; @@ -372,7 +372,7 @@ public string DocumentText sw.Write(value); sw.Flush(); ms.Position = 0; - this.DocumentStream = ms; + DocumentStream = ms; } } @@ -389,10 +389,10 @@ public string DocumentTitle { string documentTitle; - HtmlDocument htmlDocument = this.Document; + HtmlDocument htmlDocument = Document; if (htmlDocument == null) { - documentTitle = this.AxIWebBrowser2.LocationName; + documentTitle = AxIWebBrowser2.LocationName; } else { @@ -423,7 +423,7 @@ public string DocumentType get { string docType = string.Empty; - HtmlDocument htmlDocument = this.Document; + HtmlDocument htmlDocument = Document; if (htmlDocument != null) { UnsafeNativeMethods.IHTMLDocument2 htmlDocument2 = htmlDocument.DomDocument as UnsafeNativeMethods.IHTMLDocument2; @@ -452,7 +452,7 @@ public WebBrowserEncryptionLevel EncryptionLevel { get { - if (this.Document == null) + if (Document == null) { encryptionLevel = WebBrowserEncryptionLevel.Unknown; } @@ -470,13 +470,13 @@ public bool IsBusy { get { - if (this.Document == null) + if (Document == null) { return false; } else { - return this.AxIWebBrowser2.Busy; + return AxIWebBrowser2.Busy; } } } @@ -491,7 +491,7 @@ public bool IsOffline { get { - return this.AxIWebBrowser2.Offline; + return AxIWebBrowser2.Offline; } } @@ -583,13 +583,13 @@ public WebBrowserReadyState ReadyState { get { - if (this.Document == null) + if (Document == null) { return WebBrowserReadyState.Uninitialized; } else { - return (WebBrowserReadyState)this.AxIWebBrowser2.ReadyState; + return (WebBrowserReadyState)AxIWebBrowser2.ReadyState; } } } @@ -607,7 +607,7 @@ public virtual string StatusText { get { - if (this.Document == null) + if (Document == null) { statusText = string.Empty; } @@ -634,7 +634,7 @@ public Uri Url { get { - string urlString = this.AxIWebBrowser2.LocationURL; + string urlString = AxIWebBrowser2.LocationURL; if (string.IsNullOrEmpty(urlString)) { @@ -655,7 +655,7 @@ public Uri Url { value = null; } - this.PerformNavigateHelper(ReadyNavigateToUrl(value), false, null, null, null); + PerformNavigateHelper(ReadyNavigateToUrl(value), false, null, null, null); } } @@ -695,7 +695,7 @@ public bool GoBack() bool retVal = true; try { - this.AxIWebBrowser2.GoBack(); + AxIWebBrowser2.GoBack(); } catch (Exception ex) { @@ -721,7 +721,7 @@ public bool GoForward() bool retVal = true; try { - this.AxIWebBrowser2.GoForward(); + AxIWebBrowser2.GoForward(); } catch (Exception ex) { @@ -741,7 +741,7 @@ public bool GoForward() /// public void GoHome() { - this.AxIWebBrowser2.GoHome(); + AxIWebBrowser2.GoHome(); } /// @@ -751,7 +751,7 @@ public void GoHome() /// public void GoSearch() { - this.AxIWebBrowser2.GoSearch(); + AxIWebBrowser2.GoSearch(); } /// @@ -871,7 +871,7 @@ public void Print() object nullObjectArray = null; try { - this.AxIWebBrowser2.ExecWB(NativeMethods.OLECMDID.OLECMDID_PRINT, NativeMethods.OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER, ref nullObjectArray, IntPtr.Zero); + AxIWebBrowser2.ExecWB(NativeMethods.OLECMDID.OLECMDID_PRINT, NativeMethods.OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER, ref nullObjectArray, IntPtr.Zero); } catch (Exception ex) { @@ -893,13 +893,13 @@ public override void Refresh() { if (ShouldSerializeDocumentText()) { - string text = this.DocumentText; - this.AxIWebBrowser2.Refresh(); - this.DocumentText = text; + string text = DocumentText; + AxIWebBrowser2.Refresh(); + DocumentText = text; } else { - this.AxIWebBrowser2.Refresh(); + AxIWebBrowser2.Refresh(); } } catch (Exception ex) @@ -925,13 +925,13 @@ public void Refresh(WebBrowserRefreshOption opt) { if (ShouldSerializeDocumentText()) { - string text = this.DocumentText; - this.AxIWebBrowser2.Refresh2(ref level); - this.DocumentText = text; + string text = DocumentText; + AxIWebBrowser2.Refresh2(ref level); + DocumentText = text; } else { - this.AxIWebBrowser2.Refresh2(ref level); + AxIWebBrowser2.Refresh2(ref level); } } catch (Exception ex) @@ -961,7 +961,7 @@ public bool ScrollBarsEnabled if (value != webBrowserState[WEBBROWSERSTATE_scrollbarsEnabled]) { webBrowserState[WEBBROWSERSTATE_scrollbarsEnabled] = value; - this.Refresh(); + Refresh(); } } } @@ -977,7 +977,7 @@ public void ShowPageSetupDialog() object nullObjectArray = null; try { - this.AxIWebBrowser2.ExecWB(NativeMethods.OLECMDID.OLECMDID_PAGESETUP, NativeMethods.OLECMDEXECOPT.OLECMDEXECOPT_PROMPTUSER, ref nullObjectArray, IntPtr.Zero); + AxIWebBrowser2.ExecWB(NativeMethods.OLECMDID.OLECMDID_PAGESETUP, NativeMethods.OLECMDEXECOPT.OLECMDEXECOPT_PROMPTUSER, ref nullObjectArray, IntPtr.Zero); } catch (Exception ex) { @@ -1000,7 +1000,7 @@ public void ShowPrintDialog() try { - this.AxIWebBrowser2.ExecWB(NativeMethods.OLECMDID.OLECMDID_PRINT, NativeMethods.OLECMDEXECOPT.OLECMDEXECOPT_PROMPTUSER, ref nullObjectArray, IntPtr.Zero); + AxIWebBrowser2.ExecWB(NativeMethods.OLECMDID.OLECMDID_PRINT, NativeMethods.OLECMDEXECOPT.OLECMDEXECOPT_PROMPTUSER, ref nullObjectArray, IntPtr.Zero); } catch (Exception ex) { @@ -1022,7 +1022,7 @@ public void ShowPrintPreviewDialog() try { - this.AxIWebBrowser2.ExecWB(NativeMethods.OLECMDID.OLECMDID_PRINTPREVIEW, NativeMethods.OLECMDEXECOPT.OLECMDEXECOPT_PROMPTUSER, ref nullObjectArray, IntPtr.Zero); + AxIWebBrowser2.ExecWB(NativeMethods.OLECMDID.OLECMDID_PRINTPREVIEW, NativeMethods.OLECMDEXECOPT.OLECMDEXECOPT_PROMPTUSER, ref nullObjectArray, IntPtr.Zero); } catch (Exception ex) { @@ -1045,7 +1045,7 @@ public void ShowPropertiesDialog() try { - this.AxIWebBrowser2.ExecWB(NativeMethods.OLECMDID.OLECMDID_PROPERTIES, NativeMethods.OLECMDEXECOPT.OLECMDEXECOPT_PROMPTUSER, ref nullObjectArray, IntPtr.Zero); + AxIWebBrowser2.ExecWB(NativeMethods.OLECMDID.OLECMDID_PROPERTIES, NativeMethods.OLECMDEXECOPT.OLECMDEXECOPT_PROMPTUSER, ref nullObjectArray, IntPtr.Zero); } catch (Exception ex) { @@ -1068,7 +1068,7 @@ public void ShowSaveAsDialog() try { - this.AxIWebBrowser2.ExecWB(NativeMethods.OLECMDID.OLECMDID_SAVEAS, NativeMethods.OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, ref nullObjectArray, IntPtr.Zero); + AxIWebBrowser2.ExecWB(NativeMethods.OLECMDID.OLECMDID_SAVEAS, NativeMethods.OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, ref nullObjectArray, IntPtr.Zero); } catch (Exception ex) { @@ -1088,7 +1088,7 @@ public void Stop() { try { - this.AxIWebBrowser2.Stop(); + AxIWebBrowser2.Stop(); } catch (Exception ex) { @@ -1219,7 +1219,7 @@ public override bool Focused } IntPtr hwndFocus = UnsafeNativeMethods.GetFocus(); return hwndFocus != IntPtr.Zero - && SafeNativeMethods.IsChild(new HandleRef(this, this.Handle), new HandleRef(null, hwndFocus)); + && SafeNativeMethods.IsChild(new HandleRef(this, Handle), new HandleRef(null, hwndFocus)); } } @@ -1263,7 +1263,7 @@ protected override Size DefaultSize /// protected override void AttachInterfaces(object nativeActiveXObject) { - this.axIWebBrowser2 = (UnsafeNativeMethods.IWebBrowser2)nativeActiveXObject; + axIWebBrowser2 = (UnsafeNativeMethods.IWebBrowser2)nativeActiveXObject; } /// @@ -1273,7 +1273,7 @@ protected override void AttachInterfaces(object nativeActiveXObject) /// protected override void DetachInterfaces() { - this.axIWebBrowser2 = null; + axIWebBrowser2 = null; } /// @@ -1293,12 +1293,12 @@ protected override WebBrowserSiteBase CreateWebBrowserSiteBase() /// protected override void CreateSink() { - object ax = this.activeXInstance; + object ax = activeXInstance; if (ax != null) { webBrowserEvent = new WebBrowserEvent(this); webBrowserEvent.AllowNavigation = AllowNavigation; - this.cookie = new AxHost.ConnectionPointCookie(ax, webBrowserEvent, + cookie = new AxHost.ConnectionPointCookie(ax, webBrowserEvent, typeof(UnsafeNativeMethods.DWebBrowserEvents2)); } } @@ -1311,10 +1311,10 @@ protected override void CreateSink() protected override void DetachSink() { //If we have a cookie get rid of it - if (this.cookie != null) + if (cookie != null) { - this.cookie.Disconnect(); - this.cookie = null; + cookie.Disconnect(); + cookie = null; } } @@ -1347,9 +1347,9 @@ internal override void OnTopMostActiveXParentChanged(EventArgs e) // protected virtual void OnCanGoBackChanged(EventArgs e) { - if (this.CanGoBackChanged != null) + if (CanGoBackChanged != null) { - this.CanGoBackChanged(this, e); + CanGoBackChanged(this, e); } } @@ -1362,9 +1362,9 @@ protected virtual void OnCanGoBackChanged(EventArgs e) // protected virtual void OnCanGoForwardChanged(EventArgs e) { - if (this.CanGoForwardChanged != null) + if (CanGoForwardChanged != null) { - this.CanGoForwardChanged(this, e); + CanGoForwardChanged(this, e); } } @@ -1377,10 +1377,10 @@ protected virtual void OnCanGoForwardChanged(EventArgs e) // protected virtual void OnDocumentCompleted(WebBrowserDocumentCompletedEventArgs e) { - this.AxIWebBrowser2.RegisterAsDropTarget = AllowWebBrowserDrop; - if (this.DocumentCompleted != null) + AxIWebBrowser2.RegisterAsDropTarget = AllowWebBrowserDrop; + if (DocumentCompleted != null) { - this.DocumentCompleted(this, e); + DocumentCompleted(this, e); } } @@ -1393,9 +1393,9 @@ protected virtual void OnDocumentCompleted(WebBrowserDocumentCompletedEventArgs // protected virtual void OnDocumentTitleChanged(EventArgs e) { - if (this.DocumentTitleChanged != null) + if (DocumentTitleChanged != null) { - this.DocumentTitleChanged(this, e); + DocumentTitleChanged(this, e); } } @@ -1408,9 +1408,9 @@ protected virtual void OnDocumentTitleChanged(EventArgs e) // protected virtual void OnEncryptionLevelChanged(EventArgs e) { - if (this.EncryptionLevelChanged != null) + if (EncryptionLevelChanged != null) { - this.EncryptionLevelChanged(this, e); + EncryptionLevelChanged(this, e); } } @@ -1423,9 +1423,9 @@ protected virtual void OnEncryptionLevelChanged(EventArgs e) // protected virtual void OnFileDownload(EventArgs e) { - if (this.FileDownload != null) + if (FileDownload != null) { - this.FileDownload(this, e); + FileDownload(this, e); } } @@ -1438,9 +1438,9 @@ protected virtual void OnFileDownload(EventArgs e) // protected virtual void OnNavigated(WebBrowserNavigatedEventArgs e) { - if (this.Navigated != null) + if (Navigated != null) { - this.Navigated(this, e); + Navigated(this, e); } } @@ -1453,9 +1453,9 @@ protected virtual void OnNavigated(WebBrowserNavigatedEventArgs e) // protected virtual void OnNavigating(WebBrowserNavigatingEventArgs e) { - if (this.Navigating != null) + if (Navigating != null) { - this.Navigating(this, e); + Navigating(this, e); } } @@ -1468,9 +1468,9 @@ protected virtual void OnNavigating(WebBrowserNavigatingEventArgs e) // protected virtual void OnNewWindow(CancelEventArgs e) { - if (this.NewWindow != null) + if (NewWindow != null) { - this.NewWindow(this, e); + NewWindow(this, e); } } @@ -1483,9 +1483,9 @@ protected virtual void OnNewWindow(CancelEventArgs e) // protected virtual void OnProgressChanged(WebBrowserProgressChangedEventArgs e) { - if (this.ProgressChanged != null) + if (ProgressChanged != null) { - this.ProgressChanged(this, e); + ProgressChanged(this, e); } } @@ -1498,9 +1498,9 @@ protected virtual void OnProgressChanged(WebBrowserProgressChangedEventArgs e) // protected virtual void OnStatusTextChanged(EventArgs e) { - if (this.StatusTextChanged != null) + if (StatusTextChanged != null) { - this.StatusTextChanged(this, e); + StatusTextChanged(this, e); } } @@ -1528,14 +1528,14 @@ private void CheckIfCreatedInIE() { if (WebBrowser.createdInIE) { - if (this.ParentInternal != null) + if (ParentInternal != null) { - this.ParentInternal.Controls.Remove(this); - this.Dispose(); + ParentInternal.Controls.Remove(this); + Dispose(); } else { - this.Dispose(); + Dispose(); throw new NotSupportedException(SR.WebBrowserInIENotSupported); } } @@ -1552,7 +1552,7 @@ private string ReadyNavigateToUrl(string urlString) // Nullify any calls to set_DocumentStream which may still be pending if (!webBrowserState[WEBBROWSERSTATE_documentStreamJustSet]) { - this.documentStreamToSetOnLoad = null; + documentStreamToSetOnLoad = null; } return urlString; @@ -1596,7 +1596,7 @@ private void PerformNavigate2(ref object URL, ref object flags, ref object targe { try { - this.AxIWebBrowser2.Navigate2(ref URL, ref flags, ref targetFrameName, ref postData, ref headers); + AxIWebBrowser2.Navigate2(ref URL, ref flags, ref targetFrameName, ref postData, ref headers); } catch (COMException ce) { @@ -1699,9 +1699,9 @@ private UnsafeNativeMethods.IWebBrowser2 AxIWebBrowser2 { get { - if (this.axIWebBrowser2 == null) + if (axIWebBrowser2 == null) { - if (!this.IsDisposed) + if (!IsDisposed) { // This should call AttachInterfaces TransitionUpTo(WebBrowserHelper.AXState.InPlaceActive); @@ -1712,11 +1712,11 @@ private UnsafeNativeMethods.IWebBrowser2 AxIWebBrowser2 } } // We still don't have this.axIWebBrowser2. Throw an exception. - if (this.axIWebBrowser2 == null) + if (axIWebBrowser2 == null) { throw new InvalidOperationException(SR.WebBrowserNoCastToIWebBrowser2); } - return this.axIWebBrowser2; + return axIWebBrowser2; } } @@ -1749,7 +1749,7 @@ public WebBrowserSite(WebBrowser host) : base(host) // int UnsafeNativeMethods.IDocHostUIHandler.ShowContextMenu(int dwID, NativeMethods.POINT pt, object pcmdtReserved, object pdispReserved) { - WebBrowser wb = (WebBrowser)this.Host; + WebBrowser wb = (WebBrowser)Host; if (wb.IsWebBrowserContextMenuEnabled) { @@ -1774,7 +1774,7 @@ int UnsafeNativeMethods.IDocHostUIHandler.ShowContextMenu(int dwID, NativeMethod int UnsafeNativeMethods.IDocHostUIHandler.GetHostInfo(NativeMethods.DOCHOSTUIINFO info) { - WebBrowser wb = (WebBrowser)this.Host; + WebBrowser wb = (WebBrowser)Host; info.dwDoubleClick = (int)NativeMethods.DOCHOSTUIDBLCLICK.DEFAULT; info.dwFlags = (int)NativeMethods.DOCHOSTUIFLAG.NO3DOUTERBORDER | @@ -1854,7 +1854,7 @@ int UnsafeNativeMethods.IDocHostUIHandler.GetDropTarget(UnsafeNativeMethods.IOle int UnsafeNativeMethods.IDocHostUIHandler.GetExternal(out object ppDispatch) { - WebBrowser wb = (WebBrowser)this.Host; + WebBrowser wb = (WebBrowser)Host; ppDispatch = wb.ObjectForScripting; return NativeMethods.S_OK; } @@ -1866,7 +1866,7 @@ int UnsafeNativeMethods.IDocHostUIHandler.TranslateAccelerator(ref NativeMethods // Returning S_FALSE will allow the native control to do default processing, // i.e., execute the shortcut key. Returning S_OK will cancel the shortcut key. - WebBrowser wb = (WebBrowser)this.Host; + WebBrowser wb = (WebBrowser)Host; if (!wb.WebBrowserShortcutsEnabled) { @@ -1945,11 +1945,11 @@ public void CommandStateChange(long command, bool enable) { if (command == NativeMethods.CSC_NAVIGATEBACK) { - this.parent.CanGoBackInternal = enable; + parent.CanGoBackInternal = enable; } else if (command == NativeMethods.CSC_NAVIGATEFORWARD) { - this.parent.CanGoForwardInternal = enable; + parent.CanGoForwardInternal = enable; } } @@ -1978,7 +1978,7 @@ public void BeforeNavigate2(object pDisp, ref object urlObject, ref object flags string urlString = urlObject == null ? "" : (string)urlObject; WebBrowserNavigatingEventArgs e = new WebBrowserNavigatingEventArgs( new Uri(urlString), targetFrameName == null ? "" : (string)targetFrameName); - this.parent.OnNavigating(e); + parent.OnNavigating(e); cancel = e.Cancel; } else @@ -1991,38 +1991,38 @@ public void DocumentComplete(object pDisp, ref object urlObject) { Debug.Assert(urlObject == null || urlObject is string, "invalid url"); haveNavigated = true; - if (this.parent.documentStreamToSetOnLoad != null && (string)urlObject == "about:blank") + if (parent.documentStreamToSetOnLoad != null && (string)urlObject == "about:blank") { - HtmlDocument htmlDocument = this.parent.Document; + HtmlDocument htmlDocument = parent.Document; if (htmlDocument != null) { UnsafeNativeMethods.IPersistStreamInit psi = htmlDocument.DomDocument as UnsafeNativeMethods.IPersistStreamInit; Debug.Assert(psi != null, "The Document does not implement IPersistStreamInit"); UnsafeNativeMethods.IStream iStream = (UnsafeNativeMethods.IStream)new UnsafeNativeMethods.ComStreamFromDataStream( - this.parent.documentStreamToSetOnLoad); + parent.documentStreamToSetOnLoad); psi.Load(iStream); htmlDocument.Encoding = "unicode"; } - this.parent.documentStreamToSetOnLoad = null; + parent.documentStreamToSetOnLoad = null; } else { string urlString = urlObject == null ? "" : urlObject.ToString(); WebBrowserDocumentCompletedEventArgs e = new WebBrowserDocumentCompletedEventArgs( new Uri(urlString)); - this.parent.OnDocumentCompleted(e); + parent.OnDocumentCompleted(e); } } public void TitleChange(string text) { - this.parent.OnDocumentTitleChanged(EventArgs.Empty); + parent.OnDocumentTitleChanged(EventArgs.Empty); } public void SetSecureLockIcon(int secureLockIcon) { - this.parent.encryptionLevel = (WebBrowserEncryptionLevel)secureLockIcon; - this.parent.OnEncryptionLevelChanged(EventArgs.Empty); + parent.encryptionLevel = (WebBrowserEncryptionLevel)secureLockIcon; + parent.OnEncryptionLevelChanged(EventArgs.Empty); } public void NavigateComplete2(object pDisp, ref object urlObject) @@ -2031,31 +2031,31 @@ public void NavigateComplete2(object pDisp, ref object urlObject) string urlString = urlObject == null ? "" : (string)urlObject; WebBrowserNavigatedEventArgs e = new WebBrowserNavigatedEventArgs( new Uri(urlString)); - this.parent.OnNavigated(e); + parent.OnNavigated(e); } public void NewWindow2(ref object ppDisp, ref bool cancel) { CancelEventArgs e = new CancelEventArgs(); - this.parent.OnNewWindow(e); + parent.OnNewWindow(e); cancel = e.Cancel; } public void ProgressChange(int progress, int progressMax) { WebBrowserProgressChangedEventArgs e = new WebBrowserProgressChangedEventArgs(progress, progressMax); - this.parent.OnProgressChanged(e); + parent.OnProgressChanged(e); } public void StatusTextChange(string text) { - this.parent.statusText = (text == null) ? "" : text; - this.parent.OnStatusTextChanged(EventArgs.Empty); + parent.statusText = (text == null) ? "" : text; + parent.OnStatusTextChanged(EventArgs.Empty); } public void DownloadBegin() { - this.parent.OnFileDownload(EventArgs.Empty); + parent.OnFileDownload(EventArgs.Empty); } public void FileDownload(ref bool cancel) { } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs index b1d41e84976..cc163fab458 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs @@ -82,11 +82,11 @@ internal WebBrowserBase(string clsidString) : base() throw new ThreadStateException(string.Format(SR.AXMTAThread, clsidString)); } - this.SetStyle(ControlStyles.UserPaint, false); + SetStyle(ControlStyles.UserPaint, false); - this.clsid = new Guid(clsidString); - this.webBrowserBaseChangingSize.Width = -1; // Invalid value. Use WebBrowserBase.Bounds instead, when this is the case. - this.SetAXHostState(WebBrowserHelper.isMaskEdit, this.clsid.Equals(WebBrowserHelper.maskEdit_Clsid)); + clsid = new Guid(clsidString); + webBrowserBaseChangingSize.Width = -1; // Invalid value. Use WebBrowserBase.Bounds instead, when this is the case. + SetAXHostState(WebBrowserHelper.isMaskEdit, clsid.Equals(WebBrowserHelper.maskEdit_Clsid)); } @@ -202,13 +202,13 @@ public override ISite Site { set { - bool hadSelectionHandler = this.RemoveSelectionHandler(); + bool hadSelectionHandler = RemoveSelectionHandler(); base.Site = value; if (hadSelectionHandler) { - this.AddSelectionHandler(); + AddSelectionHandler(); } } } @@ -221,17 +221,17 @@ internal override void OnBoundsUpdate(int x, int y, int width, int height) // // If the ActiveX control is already InPlaceActive, make sure // it's bounds also change. - if (this.ActiveXState >= WebBrowserHelper.AXState.InPlaceActive) + if (ActiveXState >= WebBrowserHelper.AXState.InPlaceActive) { try { - this.webBrowserBaseChangingSize.Width = width; - this.webBrowserBaseChangingSize.Height = height; - this.AXInPlaceObject.SetObjectRects(new NativeMethods.COMRECT(new Rectangle(0, 0, width, height)), WebBrowserHelper.GetClipRect()); + webBrowserBaseChangingSize.Width = width; + webBrowserBaseChangingSize.Height = height; + AXInPlaceObject.SetObjectRects(new NativeMethods.COMRECT(new Rectangle(0, 0, width, height)), WebBrowserHelper.GetClipRect()); } finally { - this.webBrowserBaseChangingSize.Width = -1; // Invalid value. Use WebBrowserBase.Bounds instead, when this is the case. + webBrowserBaseChangingSize.Width = -1; // Invalid value. Use WebBrowserBase.Bounds instead, when this is the case. } } @@ -261,7 +261,7 @@ public override bool PreProcessMessage(ref Message msg) { if (IsUserMode) { - if (this.GetAXHostState(WebBrowserHelper.siteProcessedInputKey)) + if (GetAXHostState(WebBrowserHelper.siteProcessedInputKey)) { // In this case, the control called us back through IOleControlSite // and is now giving us a chance to see if we want to process it. @@ -276,7 +276,7 @@ public override bool PreProcessMessage(ref Message msg) win32Message.lParam = msg.LParam; win32Message.hwnd = msg.HWnd; - this.SetAXHostState(WebBrowserHelper.siteProcessedInputKey, false); + SetAXHostState(WebBrowserHelper.siteProcessedInputKey, false); try { if (axOleInPlaceObject != null) @@ -316,7 +316,7 @@ public override bool PreProcessMessage(ref Message msg) } return ret; } - else if (this.GetAXHostState(WebBrowserHelper.siteProcessedInputKey)) + else if (GetAXHostState(WebBrowserHelper.siteProcessedInputKey)) { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "\t Message processed by site. Calling base.PreProcessMessage() " + msg); return base.PreProcessMessage(ref msg); @@ -331,7 +331,7 @@ public override bool PreProcessMessage(ref Message msg) } finally { - this.SetAXHostState(WebBrowserHelper.siteProcessedInputKey, false); + SetAXHostState(WebBrowserHelper.siteProcessedInputKey, false); } } @@ -355,7 +355,7 @@ protected internal override bool ProcessMnemonic(char charCode) try { NativeMethods.tagCONTROLINFO ctlInfo = new NativeMethods.tagCONTROLINFO(); - int hr = this.axOleControl.GetControlInfo(ctlInfo); + int hr = axOleControl.GetControlInfo(ctlInfo); if (NativeMethods.Succeeded(hr)) { // @@ -374,7 +374,7 @@ protected internal override bool ProcessMnemonic(char charCode) msg.pt_y = p.y; if (SafeNativeMethods.IsAccelerator(new HandleRef(ctlInfo, ctlInfo.hAccel), ctlInfo.cAccel, ref msg, null)) { - this.axOleControl.OnMnemonic(ref msg); + axOleControl.OnMnemonic(ref msg); Focus(); processed = true; } @@ -466,12 +466,12 @@ protected override void WndProc(ref Message m) // Otherwise we face all sorts of problems when we try to // transition back to a state >= InPlaceActive. // - if (this.ActiveXState >= WebBrowserHelper.AXState.InPlaceActive) + if (ActiveXState >= WebBrowserHelper.AXState.InPlaceActive) { IntPtr hwndInPlaceObject; - if (NativeMethods.Succeeded(this.AXInPlaceObject.GetWindow(out hwndInPlaceObject))) + if (NativeMethods.Succeeded(AXInPlaceObject.GetWindow(out hwndInPlaceObject))) { - Application.ParkHandle(new HandleRef(this.AXInPlaceObject, hwndInPlaceObject)); + Application.ParkHandle(new HandleRef(AXInPlaceObject, hwndInPlaceObject)); } } @@ -487,9 +487,9 @@ protected override void WndProc(ref Message m) // up to InPlaceActivate that the ActiveX control grabs our handle). TransitionDownTo(WebBrowserHelper.AXState.Running); - if (this.axWindow != null) + if (axWindow != null) { - this.axWindow.ReleaseHandle(); + axWindow.ReleaseHandle(); } OnHandleDestroyed(EventArgs.Empty); @@ -512,7 +512,7 @@ protected override void WndProc(ref Message m) protected override void OnParentChanged(EventArgs e) { Control parent = ParentInternal; - if ((Visible && parent != null && parent.Visible) || this.IsHandleCreated) + if ((Visible && parent != null && parent.Visible) || IsHandleCreated) { TransitionUpTo(WebBrowserHelper.AXState.InPlaceActive); } @@ -532,7 +532,7 @@ protected override void OnVisibleChanged(EventArgs e) [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] protected override void OnGotFocus(EventArgs e) { - if (this.ActiveXState < WebBrowserHelper.AXState.UIActive) + if (ActiveXState < WebBrowserHelper.AXState.UIActive) { TransitionUpTo(WebBrowserHelper.AXState.UIActive); } @@ -546,7 +546,7 @@ protected override void OnLostFocus(EventArgs e) // If the focus goes from our control window to one of the child windows, // we should not deactivate. - if (!this.ContainsFocus) + if (!ContainsFocus) { TransitionDownTo(WebBrowserHelper.AXState.InPlaceActive); } @@ -563,7 +563,7 @@ protected override void OnRightToLeftChanged(EventArgs e) // internal override bool CanSelectCore() { - return this.ActiveXState >= WebBrowserHelper.AXState.InPlaceActive ? + return ActiveXState >= WebBrowserHelper.AXState.InPlaceActive ? base.CanSelectCore() : false; } @@ -656,12 +656,12 @@ internal WebBrowserHelper.AXState ActiveXState internal bool GetAXHostState(int mask) { - return this.axHostState[mask]; + return axHostState[mask]; } internal void SetAXHostState(int mask, bool value) { - this.axHostState[mask] = value; + axHostState[mask] = value; } internal IntPtr GetHandleNoCreate() @@ -671,92 +671,92 @@ internal IntPtr GetHandleNoCreate() internal void TransitionUpTo(WebBrowserHelper.AXState state) { - if (!this.GetAXHostState(WebBrowserHelper.inTransition)) + if (!GetAXHostState(WebBrowserHelper.inTransition)) { - this.SetAXHostState(WebBrowserHelper.inTransition, true); + SetAXHostState(WebBrowserHelper.inTransition, true); try { - while (state > this.ActiveXState) + while (state > ActiveXState) { - switch (this.ActiveXState) + switch (ActiveXState) { case WebBrowserHelper.AXState.Passive: TransitionFromPassiveToLoaded(); - Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.Loaded, "Failed transition"); + Debug.Assert(ActiveXState == WebBrowserHelper.AXState.Loaded, "Failed transition"); break; case WebBrowserHelper.AXState.Loaded: TransitionFromLoadedToRunning(); - Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.Running, "Failed transition"); + Debug.Assert(ActiveXState == WebBrowserHelper.AXState.Running, "Failed transition"); break; case WebBrowserHelper.AXState.Running: TransitionFromRunningToInPlaceActive(); - Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.InPlaceActive, "Failed transition"); + Debug.Assert(ActiveXState == WebBrowserHelper.AXState.InPlaceActive, "Failed transition"); break; case WebBrowserHelper.AXState.InPlaceActive: TransitionFromInPlaceActiveToUIActive(); - Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.UIActive, "Failed transition"); + Debug.Assert(ActiveXState == WebBrowserHelper.AXState.UIActive, "Failed transition"); break; default: Debug.Fail("bad state"); - this.ActiveXState++; // To exit the loop + ActiveXState++; // To exit the loop break; } } } finally { - this.SetAXHostState(WebBrowserHelper.inTransition, false); + SetAXHostState(WebBrowserHelper.inTransition, false); } } } internal void TransitionDownTo(WebBrowserHelper.AXState state) { - if (!this.GetAXHostState(WebBrowserHelper.inTransition)) + if (!GetAXHostState(WebBrowserHelper.inTransition)) { - this.SetAXHostState(WebBrowserHelper.inTransition, true); + SetAXHostState(WebBrowserHelper.inTransition, true); try { - while (state < this.ActiveXState) + while (state < ActiveXState) { - switch (this.ActiveXState) + switch (ActiveXState) { case WebBrowserHelper.AXState.UIActive: TransitionFromUIActiveToInPlaceActive(); - Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.InPlaceActive, "Failed transition"); + Debug.Assert(ActiveXState == WebBrowserHelper.AXState.InPlaceActive, "Failed transition"); break; case WebBrowserHelper.AXState.InPlaceActive: TransitionFromInPlaceActiveToRunning(); - Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.Running, "Failed transition"); + Debug.Assert(ActiveXState == WebBrowserHelper.AXState.Running, "Failed transition"); break; case WebBrowserHelper.AXState.Running: TransitionFromRunningToLoaded(); - Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.Loaded, "Failed transition"); + Debug.Assert(ActiveXState == WebBrowserHelper.AXState.Loaded, "Failed transition"); break; case WebBrowserHelper.AXState.Loaded: TransitionFromLoadedToPassive(); - Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.Passive, "Failed transition"); + Debug.Assert(ActiveXState == WebBrowserHelper.AXState.Passive, "Failed transition"); break; default: Debug.Fail("bad state"); - this.ActiveXState--; // To exit the loop + ActiveXState--; // To exit the loop break; } } } finally { - this.SetAXHostState(WebBrowserHelper.inTransition, false); + SetAXHostState(WebBrowserHelper.inTransition, false); } } } internal bool DoVerb(int verb) { - int hr = this.axOleObject.DoVerb(verb, IntPtr.Zero, this.ActiveXSite, 0, this.Handle, - new NativeMethods.COMRECT(this.Bounds)); + int hr = axOleObject.DoVerb(verb, IntPtr.Zero, ActiveXSite, 0, Handle, + new NativeMethods.COMRECT(Bounds)); Debug.Assert(hr == NativeMethods.S_OK, string.Format(CultureInfo.CurrentCulture, "DoVerb call failed for verb 0x{0:X}", verb)); return hr == NativeMethods.S_OK; @@ -778,7 +778,7 @@ internal ContainerControl ContainingControl get { if (containingControl == null || - this.GetAXHostState(WebBrowserHelper.recomputeContainingControl)) + GetAXHostState(WebBrowserHelper.recomputeContainingControl)) { containingControl = FindContainerControlInternal(); } @@ -812,7 +812,7 @@ internal WebBrowserContainer GetParentContainer() internal void SetEditMode(WebBrowserHelper.AXEditMode em) { - this.axEditMode = em; + axEditMode = em; } internal void SetSelectionStyle(WebBrowserHelper.SelectionStyle selectionStyle) @@ -836,9 +836,9 @@ internal void SetSelectionStyle(WebBrowserHelper.SelectionStyle selectionStyle) internal void AddSelectionHandler() { - if (!this.GetAXHostState(WebBrowserHelper.addedSelectionHandler)) + if (!GetAXHostState(WebBrowserHelper.addedSelectionHandler)) { - this.SetAXHostState(WebBrowserHelper.addedSelectionHandler, true); + SetAXHostState(WebBrowserHelper.addedSelectionHandler, true); ISelectionService iss = WebBrowserHelper.GetSelectionService(this); if (iss != null) @@ -850,10 +850,10 @@ internal void AddSelectionHandler() internal bool RemoveSelectionHandler() { - bool retVal = this.GetAXHostState(WebBrowserHelper.addedSelectionHandler); + bool retVal = GetAXHostState(WebBrowserHelper.addedSelectionHandler); if (retVal) { - this.SetAXHostState(WebBrowserHelper.addedSelectionHandler, false); + SetAXHostState(WebBrowserHelper.addedSelectionHandler, false); ISelectionService iss = WebBrowserHelper.GetSelectionService(this); if (iss != null) @@ -866,14 +866,14 @@ internal bool RemoveSelectionHandler() internal void AttachWindow(IntPtr hwnd) { - UnsafeNativeMethods.SetParent(new HandleRef(null, hwnd), new HandleRef(this, this.Handle)); + UnsafeNativeMethods.SetParent(new HandleRef(null, hwnd), new HandleRef(this, Handle)); - if (this.axWindow != null) + if (axWindow != null) { - this.axWindow.ReleaseHandle(); + axWindow.ReleaseHandle(); } - this.axWindow = new WebBrowserBaseNativeWindow(this); - this.axWindow.AssignHandle(hwnd, false); + axWindow = new WebBrowserBaseNativeWindow(this); + axWindow.AssignHandle(hwnd, false); UpdateZOrder(); UpdateBounds(); @@ -895,7 +895,7 @@ internal bool IsUserMode internal void MakeDirty() { - ISite iSite = this.Site; + ISite iSite = Site; if (iSite != null) { IComponentChangeService ccs = (IComponentChangeService)iSite.GetService(typeof(IComponentChangeService)); @@ -932,55 +932,55 @@ internal int NoComponentChangeEvents private void StartEvents() { - if (!this.GetAXHostState(WebBrowserHelper.sinkAttached)) + if (!GetAXHostState(WebBrowserHelper.sinkAttached)) { - this.SetAXHostState(WebBrowserHelper.sinkAttached, true); + SetAXHostState(WebBrowserHelper.sinkAttached, true); CreateSink(); } - this.ActiveXSite.StartEvents(); + ActiveXSite.StartEvents(); } private void StopEvents() { - if (this.GetAXHostState(WebBrowserHelper.sinkAttached)) + if (GetAXHostState(WebBrowserHelper.sinkAttached)) { - this.SetAXHostState(WebBrowserHelper.sinkAttached, false); + SetAXHostState(WebBrowserHelper.sinkAttached, false); DetachSink(); } - this.ActiveXSite.StopEvents(); + ActiveXSite.StopEvents(); } private void TransitionFromPassiveToLoaded() { - Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.Passive, "Wrong start state to transition from"); - if (this.ActiveXState == WebBrowserHelper.AXState.Passive) + Debug.Assert(ActiveXState == WebBrowserHelper.AXState.Passive, "Wrong start state to transition from"); + if (ActiveXState == WebBrowserHelper.AXState.Passive) { // // First, create the ActiveX control Debug.Assert(activeXInstance == null, "activeXInstance must be null"); - this.activeXInstance = UnsafeNativeMethods.CoCreateInstance(ref clsid, null, NativeMethods.CLSCTX_INPROC_SERVER, ref NativeMethods.ActiveX.IID_IUnknown); + activeXInstance = UnsafeNativeMethods.CoCreateInstance(ref clsid, null, NativeMethods.CLSCTX_INPROC_SERVER, ref NativeMethods.ActiveX.IID_IUnknown); Debug.Assert(activeXInstance != null, "w/o an exception being thrown we must have an object..."); // // We are now Loaded! - this.ActiveXState = WebBrowserHelper.AXState.Loaded; + ActiveXState = WebBrowserHelper.AXState.Loaded; // // Lets give them a chance to cast the ActiveX object // to the appropriate interfaces. - this.AttachInterfacesInternal(); + AttachInterfacesInternal(); } } private void TransitionFromLoadedToPassive() { - Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.Loaded, "Wrong start state to transition from"); - if (this.ActiveXState == WebBrowserHelper.AXState.Loaded) + Debug.Assert(ActiveXState == WebBrowserHelper.AXState.Loaded, "Wrong start state to transition from"); + if (ActiveXState == WebBrowserHelper.AXState.Loaded) { // // Need to make sure that we don't handle any PropertyChanged // notifications at this point. - this.NoComponentChangeEvents++; + NoComponentChangeEvents++; try { // @@ -989,38 +989,38 @@ private void TransitionFromLoadedToPassive() { // // Lets first get the cached interface pointers of activeXInstance released. - this.DetachInterfacesInternal(); + DetachInterfacesInternal(); Marshal.FinalReleaseComObject(activeXInstance); - this.activeXInstance = null; + activeXInstance = null; } } finally { - this.NoComponentChangeEvents--; + NoComponentChangeEvents--; } // // We are now Passive! - this.ActiveXState = WebBrowserHelper.AXState.Passive; + ActiveXState = WebBrowserHelper.AXState.Passive; } } private void TransitionFromLoadedToRunning() { - Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.Loaded, "Wrong start state to transition from"); - if (this.ActiveXState == WebBrowserHelper.AXState.Loaded) + Debug.Assert(ActiveXState == WebBrowserHelper.AXState.Loaded, "Wrong start state to transition from"); + if (ActiveXState == WebBrowserHelper.AXState.Loaded) { // // See if the ActiveX control returns OLEMISC_SETCLIENTSITEFIRST int bits = 0; - int hr = this.axOleObject.GetMiscStatus(NativeMethods.ActiveX.DVASPECT_CONTENT, out bits); + int hr = axOleObject.GetMiscStatus(NativeMethods.ActiveX.DVASPECT_CONTENT, out bits); if (NativeMethods.Succeeded(hr) && ((bits & NativeMethods.ActiveX.OLEMISC_SETCLIENTSITEFIRST) != 0)) { // // Simply setting the site to the ActiveX control should activate it. // And this will take us to the Running state. - this.axOleObject.SetClientSite(this.ActiveXSite); + axOleObject.SetClientSite(ActiveXSite); } // @@ -1033,20 +1033,20 @@ private void TransitionFromLoadedToRunning() // // We are now Running! - this.ActiveXState = WebBrowserHelper.AXState.Running; + ActiveXState = WebBrowserHelper.AXState.Running; } } private void TransitionFromRunningToLoaded() { - Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.Running, "Wrong start state to transition from"); - if (this.ActiveXState == WebBrowserHelper.AXState.Running) + Debug.Assert(ActiveXState == WebBrowserHelper.AXState.Running, "Wrong start state to transition from"); + if (ActiveXState == WebBrowserHelper.AXState.Running) { StopEvents(); // // Remove ourselves from our parent container... - WebBrowserContainer parentContainer = this.GetParentContainer(); + WebBrowserContainer parentContainer = GetParentContainer(); if (parentContainer != null) { parentContainer.RemoveControl(this); @@ -1054,18 +1054,18 @@ private void TransitionFromRunningToLoaded() // // Now inform the ActiveX control that it's been un-sited. - this.axOleObject.SetClientSite(null); + axOleObject.SetClientSite(null); // // We are now Loaded! - this.ActiveXState = WebBrowserHelper.AXState.Loaded; + ActiveXState = WebBrowserHelper.AXState.Loaded; } } private void TransitionFromRunningToInPlaceActive() { - Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.Running, "Wrong start state to transition from"); - if (this.ActiveXState == WebBrowserHelper.AXState.Running) + Debug.Assert(ActiveXState == WebBrowserHelper.AXState.Running, "Wrong start state to transition from"); + if (ActiveXState == WebBrowserHelper.AXState.Running) { try { @@ -1080,14 +1080,14 @@ private void TransitionFromRunningToInPlaceActive() // // We are now InPlaceActive! - this.ActiveXState = WebBrowserHelper.AXState.InPlaceActive; + ActiveXState = WebBrowserHelper.AXState.InPlaceActive; } } private void TransitionFromInPlaceActiveToRunning() { - Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.InPlaceActive, "Wrong start state to transition from"); - if (this.ActiveXState == WebBrowserHelper.AXState.InPlaceActive) + Debug.Assert(ActiveXState == WebBrowserHelper.AXState.InPlaceActive, "Wrong start state to transition from"); + if (ActiveXState == WebBrowserHelper.AXState.InPlaceActive) { // // First, lets make sure we transfer the ContainingControl's ActiveControl @@ -1100,18 +1100,18 @@ private void TransitionFromInPlaceActiveToRunning() // // Now, InPlaceDeactivate. - this.AXInPlaceObject.InPlaceDeactivate(); + AXInPlaceObject.InPlaceDeactivate(); // // We are now Running! - this.ActiveXState = WebBrowserHelper.AXState.Running; + ActiveXState = WebBrowserHelper.AXState.Running; } } private void TransitionFromInPlaceActiveToUIActive() { - Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.InPlaceActive, "Wrong start state to transition from"); - if (this.ActiveXState == WebBrowserHelper.AXState.InPlaceActive) + Debug.Assert(ActiveXState == WebBrowserHelper.AXState.InPlaceActive, "Wrong start state to transition from"); + if (ActiveXState == WebBrowserHelper.AXState.InPlaceActive) { try { @@ -1124,20 +1124,20 @@ private void TransitionFromInPlaceActiveToUIActive() // // We are now UIActive - this.ActiveXState = WebBrowserHelper.AXState.UIActive; + ActiveXState = WebBrowserHelper.AXState.UIActive; } } private void TransitionFromUIActiveToInPlaceActive() { - Debug.Assert(this.ActiveXState == WebBrowserHelper.AXState.UIActive, "Wrong start state to transition from"); - if (this.ActiveXState == WebBrowserHelper.AXState.UIActive) + Debug.Assert(ActiveXState == WebBrowserHelper.AXState.UIActive, "Wrong start state to transition from"); + if (ActiveXState == WebBrowserHelper.AXState.UIActive) { - int hr = this.AXInPlaceObject.UIDeactivate(); + int hr = AXInPlaceObject.UIDeactivate(); Debug.Assert(NativeMethods.Succeeded(hr), "Failed to UIDeactivate"); // We are now InPlaceActive - this.ActiveXState = WebBrowserHelper.AXState.InPlaceActive; + ActiveXState = WebBrowserHelper.AXState.InPlaceActive; } } @@ -1147,7 +1147,7 @@ internal WebBrowserSiteBase ActiveXSite { if (axSite == null) { - this.axSite = CreateWebBrowserSiteBase(); + axSite = CreateWebBrowserSiteBase(); } return axSite; } @@ -1156,10 +1156,10 @@ internal WebBrowserSiteBase ActiveXSite private void AttachInterfacesInternal() { Debug.Assert(activeXInstance != null, "The native control is null"); - this.axOleObject = (UnsafeNativeMethods.IOleObject)activeXInstance; - this.axOleInPlaceObject = (UnsafeNativeMethods.IOleInPlaceObject)activeXInstance; - this.axOleInPlaceActiveObject = (UnsafeNativeMethods.IOleInPlaceActiveObject)activeXInstance; - this.axOleControl = (UnsafeNativeMethods.IOleControl)activeXInstance; + axOleObject = (UnsafeNativeMethods.IOleObject)activeXInstance; + axOleInPlaceObject = (UnsafeNativeMethods.IOleInPlaceObject)activeXInstance; + axOleInPlaceActiveObject = (UnsafeNativeMethods.IOleInPlaceActiveObject)activeXInstance; + axOleControl = (UnsafeNativeMethods.IOleControl)activeXInstance; // // Lets give the inheriting classes a chance to cast // the ActiveX object to the appropriate interfaces. @@ -1168,10 +1168,10 @@ private void AttachInterfacesInternal() private void DetachInterfacesInternal() { - this.axOleObject = null; - this.axOleInPlaceObject = null; - this.axOleInPlaceActiveObject = null; - this.axOleControl = null; + axOleObject = null; + axOleInPlaceObject = null; + axOleInPlaceActiveObject = null; + axOleControl = null; // // Lets give the inheriting classes a chance to release // their cached interfaces of the ActiveX object. @@ -1184,11 +1184,11 @@ private EventHandler SelectionChangeHandler { get { - if (this.selectionChangeHandler == null) + if (selectionChangeHandler == null) { - this.selectionChangeHandler = new EventHandler(this.OnNewSelection); + selectionChangeHandler = new EventHandler(OnNewSelection); } - return this.selectionChangeHandler; + return selectionChangeHandler; } } @@ -1197,7 +1197,7 @@ private EventHandler SelectionChangeHandler // during design time when selection changes. private void OnNewSelection(object sender, EventArgs e) { - if (this.DesignMode) + if (DesignMode) { ISelectionService iss = WebBrowserHelper.GetSelectionService(this); if (iss != null) @@ -1207,13 +1207,13 @@ private void OnNewSelection(object sender, EventArgs e) { // // We need to exit editmode if we were in one. - if (this.EditMode) + if (EditMode) { - this.GetParentContainer().OnExitEditMode(this); - this.SetEditMode(WebBrowserHelper.AXEditMode.None); + GetParentContainer().OnExitEditMode(this); + SetEditMode(WebBrowserHelper.AXEditMode.None); } - this.SetSelectionStyle(WebBrowserHelper.SelectionStyle.Selected); - this.RemoveSelectionHandler(); + SetSelectionStyle(WebBrowserHelper.SelectionStyle.Selected); + RemoveSelectionHandler(); } else { @@ -1223,7 +1223,7 @@ private void OnNewSelection(object sender, EventArgs e) if (prop != null && prop.PropertyType == typeof(int)) { int curSelectionStyle = (int)prop.GetValue(this); - if (curSelectionStyle != (int)this.selectionStyle) + if (curSelectionStyle != (int)selectionStyle) { prop.SetValue(this, selectionStyle); } @@ -1242,7 +1242,7 @@ private Size SetExtent(int width, int height) try { Pixel2hiMetric(sz, sz); - this.axOleObject.SetExtent(NativeMethods.ActiveX.DVASPECT_CONTENT, sz); + axOleObject.SetExtent(NativeMethods.ActiveX.DVASPECT_CONTENT, sz); } catch (COMException) { @@ -1250,10 +1250,10 @@ private Size SetExtent(int width, int height) } if (resetExtents) { - this.axOleObject.GetExtent(NativeMethods.ActiveX.DVASPECT_CONTENT, sz); + axOleObject.GetExtent(NativeMethods.ActiveX.DVASPECT_CONTENT, sz); try { - this.axOleObject.SetExtent(NativeMethods.ActiveX.DVASPECT_CONTENT, sz); + axOleObject.SetExtent(NativeMethods.ActiveX.DVASPECT_CONTENT, sz); } catch (COMException e) { @@ -1266,7 +1266,7 @@ private Size SetExtent(int width, int height) private Size GetExtent() { NativeMethods.tagSIZEL sz = new NativeMethods.tagSIZEL(); - this.axOleObject.GetExtent(NativeMethods.ActiveX.DVASPECT_CONTENT, sz); + axOleObject.GetExtent(NativeMethods.ActiveX.DVASPECT_CONTENT, sz); HiMetric2Pixel(sz, sz); return new Size(sz.cx, sz.cy); } @@ -1277,7 +1277,7 @@ private void HiMetric2Pixel(NativeMethods.tagSIZEL sz, NativeMethods.tagSIZEL sz phm.x = sz.cx; phm.y = sz.cy; NativeMethods.tagPOINTF pcont = new NativeMethods.tagPOINTF(); - ((UnsafeNativeMethods.IOleControlSite)this.ActiveXSite).TransformCoords(phm, pcont, NativeMethods.ActiveX.XFORMCOORDS_SIZE | NativeMethods.ActiveX.XFORMCOORDS_HIMETRICTOCONTAINER); + ((UnsafeNativeMethods.IOleControlSite)ActiveXSite).TransformCoords(phm, pcont, NativeMethods.ActiveX.XFORMCOORDS_SIZE | NativeMethods.ActiveX.XFORMCOORDS_HIMETRICTOCONTAINER); szout.cx = (int)pcont.x; szout.cy = (int)pcont.y; } @@ -1288,7 +1288,7 @@ private void Pixel2hiMetric(NativeMethods.tagSIZEL sz, NativeMethods.tagSIZEL sz pcont.x = (float)sz.cx; pcont.y = (float)sz.cy; NativeMethods._POINTL phm = new NativeMethods._POINTL(); - ((UnsafeNativeMethods.IOleControlSite)this.ActiveXSite).TransformCoords(phm, pcont, NativeMethods.ActiveX.XFORMCOORDS_SIZE | NativeMethods.ActiveX.XFORMCOORDS_CONTAINERTOHIMETRIC); + ((UnsafeNativeMethods.IOleControlSite)ActiveXSite).TransformCoords(phm, pcont, NativeMethods.ActiveX.XFORMCOORDS_SIZE | NativeMethods.ActiveX.XFORMCOORDS_CONTAINERTOHIMETRIC); szout.cx = phm.x; szout.cy = phm.y; } @@ -1297,7 +1297,7 @@ private bool EditMode { get { - return this.axEditMode != WebBrowserHelper.AXEditMode.None; + return axEditMode != WebBrowserHelper.AXEditMode.None; } } @@ -1336,7 +1336,7 @@ internal ContainerControl FindContainerControlInternal() cc = null; } - this.SetAXHostState(WebBrowserHelper.recomputeContainingControl, cc == null); + SetAXHostState(WebBrowserHelper.recomputeContainingControl, cc == null); return cc; } @@ -1348,7 +1348,7 @@ private void AmbientChanged(int dispid) try { Invalidate(); - this.axOleControl.OnAmbientPropertyChange(dispid); + axOleControl.OnAmbientPropertyChange(dispid); } catch (Exception ex) { @@ -1424,7 +1424,7 @@ internal UnsafeNativeMethods.IOleInPlaceObject AXInPlaceObject { get { - return this.axOleInPlaceObject; + return axOleInPlaceObject; } } @@ -1968,7 +1968,7 @@ private class WebBrowserBaseNativeWindow : NativeWindow public WebBrowserBaseNativeWindow(WebBrowserBase ax) { - this.WebBrowserBase = ax; + WebBrowserBase = ax; } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs index 188e22a486f..db9c04611cb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs @@ -281,7 +281,7 @@ private void FillComponentsTable(IContainer container) } } - GetAllChildren(this.parent); + GetAllChildren(parent); } private void GetAllChildren(Control ctl) @@ -294,7 +294,7 @@ private void GetAllChildren(Control ctl) components = new Hashtable(); } - if (ctl != this.parent && !components.Contains(ctl)) + if (ctl != parent && !components.Contains(ctl)) components.Add(ctl, ctl); foreach (Control c in ctl.Controls) @@ -321,7 +321,7 @@ private bool RegisterControl(WebBrowserBase ctl) IComponentChangeService ccs = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); if (ccs != null) { - ccs.ComponentRemoved += new ComponentEventHandler(this.OnComponentRemoved); + ccs.ComponentRemoved += new ComponentEventHandler(OnComponentRemoved); } return true; } @@ -358,7 +358,7 @@ internal void AddControl(Control ctl) IComponentChangeService ccs = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); if (ccs != null) { - ccs.ComponentRemoved += new ComponentEventHandler(this.OnComponentRemoved); + ccs.ComponentRemoved += new ComponentEventHandler(OnComponentRemoved); } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs index 582cee898d4..6f866d294b8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs @@ -38,7 +38,7 @@ internal WebBrowserSiteBase(WebBrowserBase h) { throw new ArgumentNullException(nameof(h)); } - this.host = h; + host = h; } /// @@ -72,7 +72,7 @@ internal WebBrowserBase Host { get { - return this.host; + return host; } } @@ -145,8 +145,8 @@ int UnsafeNativeMethods.IOleControlSite.TransformCoords(NativeMethods._POINTL pP int UnsafeNativeMethods.IOleControlSite.TranslateAccelerator(ref NativeMethods.MSG pMsg, int grfModifiers) { - Debug.Assert(!this.Host.GetAXHostState(WebBrowserHelper.siteProcessedInputKey), "Re-entering UnsafeNativeMethods.IOleControlSite.TranslateAccelerator!!!"); - this.Host.SetAXHostState(WebBrowserHelper.siteProcessedInputKey, true); + Debug.Assert(!Host.GetAXHostState(WebBrowserHelper.siteProcessedInputKey), "Re-entering UnsafeNativeMethods.IOleControlSite.TranslateAccelerator!!!"); + Host.SetAXHostState(WebBrowserHelper.siteProcessedInputKey, true); Message msg = new Message(); msg.Msg = pMsg.message; @@ -156,12 +156,12 @@ int UnsafeNativeMethods.IOleControlSite.TranslateAccelerator(ref NativeMethods.M try { - bool f = ((Control)this.Host).PreProcessControlMessage(ref msg) == PreProcessControlState.MessageProcessed; + bool f = ((Control)Host).PreProcessControlMessage(ref msg) == PreProcessControlState.MessageProcessed; return f ? NativeMethods.S_OK : NativeMethods.S_FALSE; } finally { - this.Host.SetAXHostState(WebBrowserHelper.siteProcessedInputKey, false); + Host.SetAXHostState(WebBrowserHelper.siteProcessedInputKey, false); } } @@ -191,28 +191,28 @@ int UnsafeNativeMethods.IOleClientSite.GetMoniker(int dwAssign, int dwWhichMonik int UnsafeNativeMethods.IOleClientSite.GetContainer(out UnsafeNativeMethods.IOleContainer container) { - container = this.Host.GetParentContainer(); + container = Host.GetParentContainer(); return NativeMethods.S_OK; } int UnsafeNativeMethods.IOleClientSite.ShowObject() { - if (this.Host.ActiveXState >= WebBrowserHelper.AXState.InPlaceActive) + if (Host.ActiveXState >= WebBrowserHelper.AXState.InPlaceActive) { IntPtr hwnd; - if (NativeMethods.Succeeded(this.Host.AXInPlaceObject.GetWindow(out hwnd))) + if (NativeMethods.Succeeded(Host.AXInPlaceObject.GetWindow(out hwnd))) { - if (this.Host.GetHandleNoCreate() != hwnd) + if (Host.GetHandleNoCreate() != hwnd) { if (hwnd != IntPtr.Zero) { - this.Host.AttachWindow(hwnd); - this.OnActiveXRectChange(new NativeMethods.COMRECT(this.Host.Bounds)); + Host.AttachWindow(hwnd); + OnActiveXRectChange(new NativeMethods.COMRECT(Host.Bounds)); } } } - else if (this.Host.AXInPlaceObject is UnsafeNativeMethods.IOleInPlaceObjectWindowless) + else if (Host.AXInPlaceObject is UnsafeNativeMethods.IOleInPlaceObjectWindowless) { throw new InvalidOperationException(SR.AXWindowlessControl); } @@ -258,15 +258,15 @@ int UnsafeNativeMethods.IOleInPlaceSite.CanInPlaceActivate() int UnsafeNativeMethods.IOleInPlaceSite.OnInPlaceActivate() { - this.Host.ActiveXState = WebBrowserHelper.AXState.InPlaceActive; - this.OnActiveXRectChange(new NativeMethods.COMRECT(this.Host.Bounds)); + Host.ActiveXState = WebBrowserHelper.AXState.InPlaceActive; + OnActiveXRectChange(new NativeMethods.COMRECT(Host.Bounds)); return NativeMethods.S_OK; } int UnsafeNativeMethods.IOleInPlaceSite.OnUIActivate() { - this.Host.ActiveXState = WebBrowserHelper.AXState.UIActive; - this.Host.GetParentContainer().OnUIActivate(this.Host); + Host.ActiveXState = WebBrowserHelper.AXState.UIActive; + Host.GetParentContainer().OnUIActivate(Host); return NativeMethods.S_OK; } @@ -274,12 +274,12 @@ int UnsafeNativeMethods.IOleInPlaceSite.GetWindowContext(out UnsafeNativeMethods NativeMethods.COMRECT lprcPosRect, NativeMethods.COMRECT lprcClipRect, NativeMethods.tagOIFI lpFrameInfo) { ppDoc = null; - ppFrame = this.Host.GetParentContainer(); + ppFrame = Host.GetParentContainer(); - lprcPosRect.left = this.Host.Bounds.X; - lprcPosRect.top = this.Host.Bounds.Y; - lprcPosRect.right = this.Host.Bounds.Width + this.Host.Bounds.X; - lprcPosRect.bottom = this.Host.Bounds.Height + this.Host.Bounds.Y; + lprcPosRect.left = Host.Bounds.X; + lprcPosRect.top = Host.Bounds.Y; + lprcPosRect.right = Host.Bounds.Width + Host.Bounds.X; + lprcPosRect.bottom = Host.Bounds.Height + Host.Bounds.Y; lprcClipRect = WebBrowserHelper.GetClipRect(); if (lpFrameInfo != null) @@ -288,7 +288,7 @@ int UnsafeNativeMethods.IOleInPlaceSite.GetWindowContext(out UnsafeNativeMethods lpFrameInfo.fMDIApp = false; lpFrameInfo.hAccel = IntPtr.Zero; lpFrameInfo.cAccelEntries = 0; - lpFrameInfo.hwndFrame = (this.Host.ParentInternal == null) ? IntPtr.Zero : this.Host.ParentInternal.Handle; + lpFrameInfo.hwndFrame = (Host.ParentInternal == null) ? IntPtr.Zero : Host.ParentInternal.Handle; } return NativeMethods.S_OK; } @@ -300,23 +300,23 @@ int UnsafeNativeMethods.IOleInPlaceSite.Scroll(NativeMethods.tagSIZE scrollExtan int UnsafeNativeMethods.IOleInPlaceSite.OnUIDeactivate(int fUndoable) { - this.Host.GetParentContainer().OnUIDeactivate(this.Host); - if (this.Host.ActiveXState > WebBrowserHelper.AXState.InPlaceActive) + Host.GetParentContainer().OnUIDeactivate(Host); + if (Host.ActiveXState > WebBrowserHelper.AXState.InPlaceActive) { - this.Host.ActiveXState = WebBrowserHelper.AXState.InPlaceActive; + Host.ActiveXState = WebBrowserHelper.AXState.InPlaceActive; } return NativeMethods.S_OK; } int UnsafeNativeMethods.IOleInPlaceSite.OnInPlaceDeactivate() { - if (this.Host.ActiveXState == WebBrowserHelper.AXState.UIActive) + if (Host.ActiveXState == WebBrowserHelper.AXState.UIActive) { ((UnsafeNativeMethods.IOleInPlaceSite)this).OnUIDeactivate(0); } - this.Host.GetParentContainer().OnInPlaceDeactivate(this.Host); - this.Host.ActiveXState = WebBrowserHelper.AXState.Running; + Host.GetParentContainer().OnInPlaceDeactivate(Host); + Host.ActiveXState = WebBrowserHelper.AXState.Running; return NativeMethods.S_OK; } @@ -327,12 +327,12 @@ int UnsafeNativeMethods.IOleInPlaceSite.DiscardUndoState() int UnsafeNativeMethods.IOleInPlaceSite.DeactivateAndUndo() { - return this.Host.AXInPlaceObject.UIDeactivate(); + return Host.AXInPlaceObject.UIDeactivate(); } int UnsafeNativeMethods.IOleInPlaceSite.OnPosRectChange(NativeMethods.COMRECT lprcPosRect) { - return this.OnActiveXRectChange(lprcPosRect); + return OnActiveXRectChange(lprcPosRect); } // @@ -356,10 +356,10 @@ void UnsafeNativeMethods.IPropertyNotifySink.OnChanged(int dispid) // Some controls fire OnChanged() notifications when getting values of some properties. // To prevent this kind of recursion, we check to see if we are already inside a OnChanged() call. // - if (this.Host.NoComponentChangeEvents != 0) + if (Host.NoComponentChangeEvents != 0) return; - this.Host.NoComponentChangeEvents++; + Host.NoComponentChangeEvents++; try { OnPropertyChanged(dispid); @@ -371,7 +371,7 @@ void UnsafeNativeMethods.IPropertyNotifySink.OnChanged(int dispid) } finally { - this.Host.NoComponentChangeEvents--; + Host.NoComponentChangeEvents--; } } @@ -388,7 +388,7 @@ internal virtual void OnPropertyChanged(int dispid) { try { - ISite site = this.Host.Site; + ISite site = Host.Site; if (site != null) { IComponentChangeService changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); @@ -397,7 +397,7 @@ internal virtual void OnPropertyChanged(int dispid) { try { - changeService.OnComponentChanging(this.Host, null); + changeService.OnComponentChanging(Host, null); } catch (CheckoutException coEx) { @@ -410,7 +410,7 @@ internal virtual void OnPropertyChanged(int dispid) // Now notify the change service that the change was successful. // - changeService.OnComponentChanged(this.Host, null, null, null); + changeService.OnComponentChanged(Host, null, null, null); } } } @@ -427,7 +427,7 @@ internal virtual void OnPropertyChanged(int dispid) // internal WebBrowserBase GetAXHost() { - return this.Host; + return Host; } internal void StartEvents() @@ -435,7 +435,7 @@ internal void StartEvents() if (connectionPoint != null) return; - object nativeObject = this.Host.activeXInstance; + object nativeObject = Host.activeXInstance; if (nativeObject != null) { try @@ -463,10 +463,10 @@ internal void StopEvents() private int OnActiveXRectChange(NativeMethods.COMRECT lprcPosRect) { - this.Host.AXInPlaceObject.SetObjectRects( + Host.AXInPlaceObject.SetObjectRects( NativeMethods.COMRECT.FromXYWH(0, 0, lprcPosRect.right - lprcPosRect.left, lprcPosRect.bottom - lprcPosRect.top), WebBrowserHelper.GetClipRect()); - this.Host.MakeDirty(); + Host.MakeDirty(); return NativeMethods.S_OK; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WindowsFormsSynchronizationContext.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WindowsFormsSynchronizationContext.cs index f1df61e4b35..2928ce120ab 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WindowsFormsSynchronizationContext.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WindowsFormsSynchronizationContext.cs @@ -44,7 +44,7 @@ public WindowsFormsSynchronizationContext() private WindowsFormsSynchronizationContext(Control marshalingControl, Thread destinationThread) { controlToSendTo = marshalingControl; - this.DestinationThread = destinationThread; + DestinationThread = destinationThread; Debug.Assert(controlToSendTo.IsHandleCreated, "Marshaling control should have created its handle in its ctor."); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs b/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs index bb8084a43f0..2dec5ba2ec7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs @@ -148,9 +148,9 @@ internal ImeMode CurrentImeContextMode { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_CurrentImeContextMode(), this = " + this); - if (this.IsHandleCreated) + if (IsHandleCreated) { - return ImeContext.GetImeMode(this.Handle); + return ImeContext.GetImeMode(Handle); } else { @@ -521,7 +521,7 @@ internal void UpdateImeContextMode() try { - ImeContext.SetImeStatus(newImeContextMode, this.Handle); + ImeContext.SetImeStatus(newImeContextMode, Handle); } finally { @@ -589,7 +589,7 @@ internal void VerifyImeRestrictedModeChanged() Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside VerifyImeRestrictedModeChanged(), this = " + this); Debug.Indent(); - bool currentCanEnableIme = this.CanEnableIme; + bool currentCanEnableIme = CanEnableIme; if (LastCanEnableIme != currentCanEnableIme) { @@ -788,7 +788,7 @@ private void WmImeChar(ref Message m) private void WmImeEndComposition(ref Message m) { Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside WmImeEndComposition() - Disabling ImeWmCharToIgnore, this=" + this); - this.ImeWmCharsToIgnore = ImeCharsToIgnoreDisabled; + ImeWmCharsToIgnore = ImeCharsToIgnoreDisabled; DefWndProc(ref m); } @@ -839,7 +839,7 @@ private void WmImeNotify(ref Message m) Debug.Indent(); // Synchronize internal properties with the IME context mode. - OnImeContextStatusChanged(this.Handle); + OnImeContextStatusChanged(Handle); Debug.Unindent(); } diff --git a/src/System.Windows.Forms/src/misc/GDI/DeviceContext.cs b/src/System.Windows.Forms/src/misc/GDI/DeviceContext.cs index 057f7841089..00196775362 100644 --- a/src/System.Windows.Forms/src/misc/GDI/DeviceContext.cs +++ b/src/System.Windows.Forms/src/misc/GDI/DeviceContext.cs @@ -118,7 +118,7 @@ public DeviceContextType DeviceContextType { get { - return this.dcType; + return dcType; } } @@ -133,15 +133,15 @@ public IntPtr Hdc get { - if (this.hDC == IntPtr.Zero) + if (hDC == IntPtr.Zero) { - if (this.dcType == DeviceContextType.Display) + if (dcType == DeviceContextType.Display) { - Debug.Assert(!this.disposed, "Accessing a disposed DC, forcing recreation of HDC - this will generate a Handle leak!"); + Debug.Assert(!disposed, "Accessing a disposed DC, forcing recreation of HDC - this will generate a Handle leak!"); // Note: ReleaseDC must be called from the same thread. This applies only to HDC obtained // from calling GetDC. This means Display DeviceContext objects should never be finalized. - this.hDC = ((IDeviceContext)this).GetHdc(); // this.hDC will be released on call to Dispose. + hDC = ((IDeviceContext)this).GetHdc(); // this.hDC will be released on call to Dispose. CacheInitialState(); } #if GDI_FINALIZATION_WATCH @@ -152,9 +152,9 @@ public IntPtr Hdc #endif } - Debug.Assert(this.hDC != IntPtr.Zero, "Attempt to use deleted HDC - DC type: " + this.dcType); + Debug.Assert(hDC != IntPtr.Zero, "Attempt to use deleted HDC - DC type: " + dcType); - return this.hDC; + return hDC; } } @@ -167,7 +167,7 @@ public IntPtr Hdc private void CacheInitialState() { - Debug.Assert(this.hDC != IntPtr.Zero, "Cannot get initial state without a valid HDC"); + Debug.Assert(hDC != IntPtr.Zero, "Cannot get initial state without a valid HDC"); hCurrentPen = hInitialPen = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, hDC), IntNativeMethods.OBJ_PEN); hCurrentBrush = hInitialBrush = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, hDC), IntNativeMethods.OBJ_BRUSH); hCurrentBmp = hInitialBmp = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, hDC), IntNativeMethods.OBJ_BITMAP); @@ -184,7 +184,7 @@ public void DeleteObject(IntPtr handle, GdiObjectType type) case GdiObjectType.Pen: if (handle == hCurrentPen) { - IntPtr currentPen = IntUnsafeNativeMethods.SelectObject(new HandleRef(this, this.Hdc), new HandleRef(this, hInitialPen)); + IntPtr currentPen = IntUnsafeNativeMethods.SelectObject(new HandleRef(this, Hdc), new HandleRef(this, hInitialPen)); Debug.Assert(currentPen == hCurrentPen, "DeviceContext thinks a different pen is selected than the HDC"); hCurrentPen = IntPtr.Zero; } @@ -193,7 +193,7 @@ public void DeleteObject(IntPtr handle, GdiObjectType type) case GdiObjectType.Brush: if (handle == hCurrentBrush) { - IntPtr currentBrush = IntUnsafeNativeMethods.SelectObject(new HandleRef(this, this.Hdc), new HandleRef(this, hInitialBrush)); + IntPtr currentBrush = IntUnsafeNativeMethods.SelectObject(new HandleRef(this, Hdc), new HandleRef(this, hInitialBrush)); Debug.Assert(currentBrush == hCurrentBrush, "DeviceContext thinks a different brush is selected than the HDC"); hCurrentBrush = IntPtr.Zero; } @@ -202,7 +202,7 @@ public void DeleteObject(IntPtr handle, GdiObjectType type) case GdiObjectType.Bitmap: if (handle == hCurrentBmp) { - IntPtr currentBmp = IntUnsafeNativeMethods.SelectObject(new HandleRef(this, this.Hdc), new HandleRef(this, hInitialBmp)); + IntPtr currentBmp = IntUnsafeNativeMethods.SelectObject(new HandleRef(this, Hdc), new HandleRef(this, hInitialBmp)); Debug.Assert(currentBmp == hCurrentBmp, "DeviceContext thinks a different brush is selected than the HDC"); hCurrentBmp = IntPtr.Zero; } @@ -223,7 +223,7 @@ public void DeleteObject(IntPtr handle, GdiObjectType type) private DeviceContext(IntPtr hWnd) { this.hWnd = hWnd; - this.dcType = DeviceContextType.Display; + dcType = DeviceContextType.Display; DeviceContexts.AddDeviceContext(this); @@ -249,7 +249,7 @@ private DeviceContext(IntPtr hDC, DeviceContextType dcType) if (dcType == DeviceContextType.Display) { - this.hWnd = IntUnsafeNativeMethods.WindowFromDC(new HandleRef(this, this.hDC)); + hWnd = IntUnsafeNativeMethods.WindowFromDC(new HandleRef(this, this.hDC)); } #if TRACK_HDC Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("DeviceContext( hDC=0x{0:X8}, Type={1} )", unchecked((int) hDC), dcType) )); @@ -338,18 +338,18 @@ internal void Dispose(bool disposing) return; } - if (this.Disposing != null) + if (Disposing != null) { - this.Disposing(this, EventArgs.Empty); + Disposing(this, EventArgs.Empty); } - this.disposed = true; + disposed = true; #if !DRAWING_NAMESPACE DisposeFont(disposing); #endif - switch (this.dcType) + switch (dcType) { case DeviceContextType.Display: Debug.Assert(disposing, "WARNING: Finalizing a Display DeviceContext.\r\nReleaseDC may fail when not called from the same thread GetDC was called from."); @@ -366,9 +366,9 @@ internal void Dispose(bool disposing) Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("DC.DeleteHDC(hdc=0x{0:x8})", unchecked((int) this.hDC)))); #endif - IntUnsafeNativeMethods.DeleteHDC(new HandleRef(this, this.hDC)); + IntUnsafeNativeMethods.DeleteHDC(new HandleRef(this, hDC)); - this.hDC = IntPtr.Zero; + hDC = IntPtr.Zero; break; case DeviceContextType.Memory: @@ -378,9 +378,9 @@ internal void Dispose(bool disposing) #if TRACK_HDC Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("DC.DeleteDC(hdc=0x{0:x8})", unchecked((int) this.hDC)))); #endif - IntUnsafeNativeMethods.DeleteDC(new HandleRef(this, this.hDC)); + IntUnsafeNativeMethods.DeleteDC(new HandleRef(this, hDC)); - this.hDC = IntPtr.Zero; + hDC = IntPtr.Zero; break; // case DeviceContextType.Metafile: - not yet supported. @@ -410,19 +410,19 @@ internal void Dispose(bool disposing) IntPtr IDeviceContext.GetHdc() { - if (this.hDC == IntPtr.Zero) + if (hDC == IntPtr.Zero) { - Debug.Assert(this.dcType == DeviceContextType.Display, "Calling GetDC from a non display/window device."); + Debug.Assert(dcType == DeviceContextType.Display, "Calling GetDC from a non display/window device."); // Note: for common DCs, GetDC assigns default attributes to the DC each time it is retrieved. // For example, the default font is System. - this.hDC = IntUnsafeNativeMethods.GetDC(new HandleRef(this, this.hWnd)); + hDC = IntUnsafeNativeMethods.GetDC(new HandleRef(this, hWnd)); #if TRACK_HDC Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("hdc[0x{0:x8}]=DC.GetHdc(hWnd=0x{1:x8})", unchecked((int) this.hDC), unchecked((int) this.hWnd)))); #endif } - return this.hDC; + return hDC; } @@ -432,17 +432,17 @@ IntPtr IDeviceContext.GetHdc() /// void IDeviceContext.ReleaseHdc() { - if (this.hDC != IntPtr.Zero && this.dcType == DeviceContextType.Display) + if (hDC != IntPtr.Zero && dcType == DeviceContextType.Display) { #if TRACK_HDC int retVal = #endif - IntUnsafeNativeMethods.ReleaseDC(new HandleRef(this, this.hWnd), new HandleRef(this, this.hDC)); + IntUnsafeNativeMethods.ReleaseDC(new HandleRef(this, hWnd), new HandleRef(this, hDC)); // Note: retVal == 0 means it was not released but doesn't necessarily means an error; class or private DCs are never released. #if TRACK_HDC Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("[ret={0}]=DC.ReleaseDC(hDc=0x{1:x8}, hWnd=0x{2:x8})", retVal, unchecked((int) this.hDC), unchecked((int) this.hWnd)))); #endif - this.hDC = IntPtr.Zero; + hDC = IntPtr.Zero; } } @@ -457,7 +457,7 @@ public DeviceContextGraphicsMode GraphicsMode get { - return (DeviceContextGraphicsMode)IntUnsafeNativeMethods.GetGraphicsMode(new HandleRef(this, this.Hdc)); + return (DeviceContextGraphicsMode)IntUnsafeNativeMethods.GetGraphicsMode(new HandleRef(this, Hdc)); } #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY set @@ -474,7 +474,7 @@ public DeviceContextGraphicsMode GraphicsMode public DeviceContextGraphicsMode SetGraphicsMode(DeviceContextGraphicsMode newMode) { - return (DeviceContextGraphicsMode)IntUnsafeNativeMethods.SetGraphicsMode(new HandleRef(this, this.Hdc), unchecked((int)newMode)); + return (DeviceContextGraphicsMode)IntUnsafeNativeMethods.SetGraphicsMode(new HandleRef(this, Hdc), unchecked((int)newMode)); } /// @@ -494,7 +494,7 @@ public void RestoreHdc() bool result = #endif // Note: Don't use the Hdc property here, it would force handle creation. - IntUnsafeNativeMethods.RestoreDC(new HandleRef(this, this.hDC), -1); + IntUnsafeNativeMethods.RestoreDC(new HandleRef(this, hDC), -1); #if TRACK_HDC // Note: Winforms may call this method during app exit at which point the DC may have been finalized already causing this assert to popup. Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("ret[0]=DC.RestoreHdc(hDc=0x{1:x8})", result, unchecked((int) this.hDC)) )); @@ -532,7 +532,7 @@ public void RestoreHdc() // in this case, GDI will copy back the previously saved font into the DC. // we dont actually know what the font is in our measurement DC so // we need to clear it off. - MeasurementDCInfo.ResetIfIsMeasurementDC(this.hDC); + MeasurementDCInfo.ResetIfIsMeasurementDC(hDC); #endif } @@ -549,7 +549,7 @@ public void RestoreHdc() public int SaveHdc() { - HandleRef hdc = new HandleRef(this, this.Hdc); + HandleRef hdc = new HandleRef(this, Hdc); int state = IntUnsafeNativeMethods.SaveDC(hdc); if (contextStack == null) @@ -588,7 +588,7 @@ public int SaveHdc() public void SetClip(WindowsRegion region) { - HandleRef hdc = new HandleRef(this, this.Hdc); + HandleRef hdc = new HandleRef(this, Hdc); HandleRef hRegion = new HandleRef(region, region.HRegion); IntUnsafeNativeMethods.SelectClipRgn(hdc, hRegion); @@ -611,7 +611,7 @@ public void IntersectClip(WindowsRegion wr) WindowsRegion clip = new WindowsRegion(0, 0, 0, 0); try { - int result = IntUnsafeNativeMethods.GetClipRgn(new HandleRef(this, this.Hdc), new HandleRef(clip, clip.HRegion)); + int result = IntUnsafeNativeMethods.GetClipRgn(new HandleRef(this, Hdc), new HandleRef(clip, clip.HRegion)); // If the function succeeds and there is a clipping region for the given device context, the return value is 1. if (result == 1) @@ -636,7 +636,7 @@ public void IntersectClip(WindowsRegion wr) public void TranslateTransform(int dx, int dy) { IntNativeMethods.POINT orgn = new IntNativeMethods.POINT(); - IntUnsafeNativeMethods.OffsetViewportOrgEx(new HandleRef(this, this.Hdc), dx, dy, orgn); + IntUnsafeNativeMethods.OffsetViewportOrgEx(new HandleRef(this, Hdc), dx, dy, orgn); } /// @@ -658,7 +658,7 @@ public override bool Equals(object obj) } // Note: Use property instead of field so the HDC is initialized. Also, this avoid serialization issues (the obj could be a proxy that does not have access to private fields). - return other.Hdc == this.Hdc; + return other.Hdc == Hdc; } /// @@ -668,7 +668,7 @@ public override bool Equals(object obj) public override int GetHashCode() { - return this.Hdc.GetHashCode(); + return Hdc.GetHashCode(); } diff --git a/src/System.Windows.Forms/src/misc/GDI/DeviceContext2.cs b/src/System.Windows.Forms/src/misc/GDI/DeviceContext2.cs index da7edf9f594..2fe40cdf176 100644 --- a/src/System.Windows.Forms/src/misc/GDI/DeviceContext2.cs +++ b/src/System.Windows.Forms/src/misc/GDI/DeviceContext2.cs @@ -55,7 +55,7 @@ public Color BackgroundColor { get { - return ColorTranslator.FromWin32(IntUnsafeNativeMethods.GetBkColor(new HandleRef(this, this.Hdc))); + return ColorTranslator.FromWin32(IntUnsafeNativeMethods.GetBkColor(new HandleRef(this, Hdc))); } #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY set @@ -70,7 +70,7 @@ public Color BackgroundColor /// public Color SetBackgroundColor(Color newColor) { - return ColorTranslator.FromWin32(IntUnsafeNativeMethods.SetBkColor(new HandleRef(this, this.Hdc), ColorTranslator.ToWin32(newColor))); + return ColorTranslator.FromWin32(IntUnsafeNativeMethods.SetBkColor(new HandleRef(this, Hdc), ColorTranslator.ToWin32(newColor))); } /// @@ -80,7 +80,7 @@ public DeviceContextBackgroundMode BackgroundMode { get { - return (DeviceContextBackgroundMode)IntUnsafeNativeMethods.GetBkMode(new HandleRef(this, this.Hdc)); + return (DeviceContextBackgroundMode)IntUnsafeNativeMethods.GetBkMode(new HandleRef(this, Hdc)); } #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY set @@ -95,7 +95,7 @@ public DeviceContextBackgroundMode BackgroundMode /// public DeviceContextBackgroundMode SetBackgroundMode(DeviceContextBackgroundMode newMode) { - return (DeviceContextBackgroundMode)IntUnsafeNativeMethods.SetBkMode(new HandleRef(this, this.Hdc), (int)newMode); + return (DeviceContextBackgroundMode)IntUnsafeNativeMethods.SetBkMode(new HandleRef(this, Hdc), (int)newMode); } @@ -106,7 +106,7 @@ public DeviceContextBinaryRasterOperationFlags BinaryRasterOperation { get { - return (DeviceContextBinaryRasterOperationFlags)IntUnsafeNativeMethods.GetROP2(new HandleRef(this, this.Hdc)); + return (DeviceContextBinaryRasterOperationFlags)IntUnsafeNativeMethods.GetROP2(new HandleRef(this, Hdc)); } /* * CONSIDER: implement if needed. @@ -124,7 +124,7 @@ public DeviceContextBinaryRasterOperationFlags BinaryRasterOperation /// public DeviceContextBinaryRasterOperationFlags SetRasterOperation(DeviceContextBinaryRasterOperationFlags rasterOperation) { - return (DeviceContextBinaryRasterOperationFlags)IntUnsafeNativeMethods.SetROP2(new HandleRef(this, this.Hdc), (int)rasterOperation); + return (DeviceContextBinaryRasterOperationFlags)IntUnsafeNativeMethods.SetROP2(new HandleRef(this, Hdc), (int)rasterOperation); } /// @@ -182,7 +182,7 @@ public WindowsFont Font if (font != null && (font.Hfont != IntPtr.Zero)) { #if DEBUG - WindowsFont currentDCFont = WindowsFont.FromHdc(this.Hdc); + WindowsFont currentDCFont = WindowsFont.FromHdc(Hdc); if (!font.Equals(currentDCFont)) { // just use the face name, as ToString will call here re-entrantly. @@ -200,7 +200,7 @@ public WindowsFont Font // Returns the currently selected object in the dc. // Note: for common DCs, GetDC assigns default attributes to the DC each time it is retrieved, // the default font is System. - return WindowsFont.FromHdc(this.Hdc); + return WindowsFont.FromHdc(Hdc); } #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY set @@ -237,7 +237,7 @@ internal void DisposeFont(bool disposing) if (hCurrentFont == selectedFont.Hfont) { // select initial font back in - IntUnsafeNativeMethods.SelectObject(new HandleRef(this, this.Hdc), new HandleRef(null, hInitialFont)); + IntUnsafeNativeMethods.SelectObject(new HandleRef(this, Hdc), new HandleRef(null, hInitialFont)); hCurrentFont = hInitialFont; } @@ -258,7 +258,7 @@ public IntPtr SelectFont(WindowsFont font) // with the one passed in before selecting it in the hdc. // Also, we avoid performing GDI operations that if done on an enhanced metafile DC would add an entry to it, hence // reducing the size of the metafile. - if (font.Equals(this.Font)) + if (font.Equals(Font)) { return IntPtr.Zero; } @@ -304,9 +304,9 @@ public void ResetFont() // in this case, GDI will copy back the previously saved font into the DC. // we dont actually know what the font is in our measurement DC so // we need to clear it off. - MeasurementDCInfo.ResetIfIsMeasurementDC(this.Hdc); + MeasurementDCInfo.ResetIfIsMeasurementDC(Hdc); #endif - IntUnsafeNativeMethods.SelectObject(new HandleRef(this, this.Hdc), new HandleRef(null, hInitialFont)); + IntUnsafeNativeMethods.SelectObject(new HandleRef(this, Hdc), new HandleRef(null, hInitialFont)); selectedFont = null; hCurrentFont = hInitialFont; } @@ -316,7 +316,7 @@ public void ResetFont() /// public int GetDeviceCapabilities(DeviceCapabilities capabilityIndex) { - return IntUnsafeNativeMethods.GetDeviceCaps(new HandleRef(this, this.Hdc), (int)capabilityIndex); + return IntUnsafeNativeMethods.GetDeviceCaps(new HandleRef(this, Hdc), (int)capabilityIndex); } /// @@ -326,7 +326,7 @@ public DeviceContextMapMode MapMode { get { - return (DeviceContextMapMode)IntUnsafeNativeMethods.GetMapMode(new HandleRef(this, this.Hdc)); + return (DeviceContextMapMode)IntUnsafeNativeMethods.GetMapMode(new HandleRef(this, Hdc)); } #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY set @@ -359,7 +359,7 @@ public bool IsFontOnContextStack(WindowsFont wf) /// public DeviceContextMapMode SetMapMode(DeviceContextMapMode newMode) { - return (DeviceContextMapMode)IntUnsafeNativeMethods.SetMapMode(new HandleRef(this, this.Hdc), (int)newMode); + return (DeviceContextMapMode)IntUnsafeNativeMethods.SetMapMode(new HandleRef(this, Hdc), (int)newMode); } /// @@ -380,7 +380,7 @@ public IntPtr SelectObject(IntPtr hObj, GdiObjectType type) hCurrentBmp = hObj; break; } - return IntUnsafeNativeMethods.SelectObject(new HandleRef(this, this.Hdc), new HandleRef(null, hObj)); + return IntUnsafeNativeMethods.SelectObject(new HandleRef(this, Hdc), new HandleRef(null, hObj)); } /// @@ -390,7 +390,7 @@ public DeviceContextTextAlignment TextAlignment { get { - return (DeviceContextTextAlignment)IntUnsafeNativeMethods.GetTextAlign(new HandleRef(this, this.Hdc)); + return (DeviceContextTextAlignment)IntUnsafeNativeMethods.GetTextAlign(new HandleRef(this, Hdc)); } #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY set @@ -405,7 +405,7 @@ public DeviceContextTextAlignment TextAlignment /// public DeviceContextTextAlignment SetTextAlignment(DeviceContextTextAlignment newAligment) { - return (DeviceContextTextAlignment)IntUnsafeNativeMethods.SetTextAlign(new HandleRef(this, this.Hdc), (int)newAligment); + return (DeviceContextTextAlignment)IntUnsafeNativeMethods.SetTextAlign(new HandleRef(this, Hdc), (int)newAligment); } @@ -416,7 +416,7 @@ public Color TextColor { get { - return ColorTranslator.FromWin32(IntUnsafeNativeMethods.GetTextColor(new HandleRef(this, this.Hdc))); + return ColorTranslator.FromWin32(IntUnsafeNativeMethods.GetTextColor(new HandleRef(this, Hdc))); } #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY set @@ -431,7 +431,7 @@ public Color TextColor /// public Color SetTextColor(Color newColor) { - return ColorTranslator.FromWin32(IntUnsafeNativeMethods.SetTextColor(new HandleRef(this, this.Hdc), ColorTranslator.ToWin32(newColor))); + return ColorTranslator.FromWin32(IntUnsafeNativeMethods.SetTextColor(new HandleRef(this, Hdc), ColorTranslator.ToWin32(newColor))); } /// @@ -442,7 +442,7 @@ public Size ViewportExtent get { IntNativeMethods.SIZE size = new IntNativeMethods.SIZE(); - IntUnsafeNativeMethods.GetViewportExtEx(new HandleRef(this, this.Hdc), size); + IntUnsafeNativeMethods.GetViewportExtEx(new HandleRef(this, Hdc), size); return size.ToSize(); } @@ -459,7 +459,7 @@ public Size SetViewportExtent(Size newExtent) { IntNativeMethods.SIZE oldExtent = new IntNativeMethods.SIZE(); - IntUnsafeNativeMethods.SetViewportExtEx(new HandleRef(this, this.Hdc), newExtent.Width, newExtent.Height, oldExtent); + IntUnsafeNativeMethods.SetViewportExtEx(new HandleRef(this, Hdc), newExtent.Width, newExtent.Height, oldExtent); return oldExtent.ToSize(); } @@ -472,7 +472,7 @@ public Point ViewportOrigin get { IntNativeMethods.POINT point = new IntNativeMethods.POINT(); - IntUnsafeNativeMethods.GetViewportOrgEx(new HandleRef(this, this.Hdc), point); + IntUnsafeNativeMethods.GetViewportOrgEx(new HandleRef(this, Hdc), point); return point.ToPoint(); } @@ -488,7 +488,7 @@ public Point ViewportOrigin public Point SetViewportOrigin(Point newOrigin) { IntNativeMethods.POINT oldOrigin = new IntNativeMethods.POINT(); - IntUnsafeNativeMethods.SetViewportOrgEx(new HandleRef(this, this.Hdc), newOrigin.X, newOrigin.Y, oldOrigin); + IntUnsafeNativeMethods.SetViewportOrgEx(new HandleRef(this, Hdc), newOrigin.X, newOrigin.Y, oldOrigin); return oldOrigin.ToPoint(); } diff --git a/src/System.Windows.Forms/src/misc/GDI/NativeMethods.cs b/src/System.Windows.Forms/src/misc/GDI/NativeMethods.cs index 6e54622913b..588d338ed1e 100644 --- a/src/System.Windows.Forms/src/misc/GDI/NativeMethods.cs +++ b/src/System.Windows.Forms/src/misc/GDI/NativeMethods.cs @@ -171,10 +171,10 @@ public RECT(int left, int top, int right, int bottom) public RECT(System.Drawing.Rectangle r) { - this.left = r.Left; - this.top = r.Top; - this.right = r.Right; - this.bottom = r.Bottom; + left = r.Left; + top = r.Top; + right = r.Right; + bottom = r.Bottom; } public static RECT FromXYWH(int x, int y, int width, int height) @@ -190,7 +190,7 @@ public Size Size { get { - return new Size(this.right - this.left, this.bottom - this.top); + return new Size(right - left, bottom - top); } } @@ -229,7 +229,7 @@ public POINT(int x, int y) public System.Drawing.Point ToPoint() { - return new System.Drawing.Point(this.x, this.y); + return new System.Drawing.Point(x, y); } #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY public override string ToString() @@ -259,15 +259,15 @@ public DRAWTEXTPARAMS() } public DRAWTEXTPARAMS(DRAWTEXTPARAMS original) { - this.iLeftMargin = original.iLeftMargin; - this.iRightMargin = original.iRightMargin; - this.iTabLength = original.iTabLength; + iLeftMargin = original.iLeftMargin; + iRightMargin = original.iRightMargin; + iTabLength = original.iTabLength; } public DRAWTEXTPARAMS(int leftMargin, int rightMargin) { - this.iLeftMargin = leftMargin; - this.iRightMargin = rightMargin; + iLeftMargin = leftMargin; + iRightMargin = rightMargin; } #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY @@ -313,20 +313,20 @@ public LOGFONT(LOGFONT lf) { Debug.Assert(lf != null, "lf is null"); - this.lfHeight = lf.lfHeight; - this.lfWidth = lf.lfWidth; - this.lfEscapement = lf.lfEscapement; - this.lfOrientation = lf.lfOrientation; - this.lfWeight = lf.lfWeight; - this.lfItalic = lf.lfItalic; - this.lfUnderline = lf.lfUnderline; - this.lfStrikeOut = lf.lfStrikeOut; - this.lfCharSet = lf.lfCharSet; - this.lfOutPrecision = lf.lfOutPrecision; - this.lfClipPrecision = lf.lfClipPrecision; - this.lfQuality = lf.lfQuality; - this.lfPitchAndFamily = lf.lfPitchAndFamily; - this.lfFaceName = lf.lfFaceName; + lfHeight = lf.lfHeight; + lfWidth = lf.lfWidth; + lfEscapement = lf.lfEscapement; + lfOrientation = lf.lfOrientation; + lfWeight = lf.lfWeight; + lfItalic = lf.lfItalic; + lfUnderline = lf.lfUnderline; + lfStrikeOut = lf.lfStrikeOut; + lfCharSet = lf.lfCharSet; + lfOutPrecision = lf.lfOutPrecision; + lfClipPrecision = lf.lfClipPrecision; + lfQuality = lf.lfQuality; + lfPitchAndFamily = lf.lfPitchAndFamily; + lfFaceName = lf.lfFaceName; } #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY @@ -432,7 +432,7 @@ public SIZE(int cx, int cy) public System.Drawing.Size ToSize() { - return new System.Drawing.Size(this.cx, this.cy); + return new System.Drawing.Size(cx, cy); } #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY public override string ToString() diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsBrush.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsBrush.cs index 06ca6661a2e..0ee044df875 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsBrush.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsBrush.cs @@ -74,7 +74,7 @@ protected DeviceContext DC { get { - return this.dc; + return dc; } } @@ -85,13 +85,13 @@ public void Dispose() protected virtual void Dispose(bool disposing) { - if (dc != null && this.nativeHandle != IntPtr.Zero) + if (dc != null && nativeHandle != IntPtr.Zero) { DbgUtil.AssertFinalization(this, disposing); - dc.DeleteObject(this.nativeHandle, GdiObjectType.Brush); + dc.DeleteObject(nativeHandle, GdiObjectType.Brush); - this.nativeHandle = IntPtr.Zero; + nativeHandle = IntPtr.Zero; } if (disposing) @@ -104,7 +104,7 @@ public Color Color { get { - return this.color; + return color; } } @@ -115,20 +115,20 @@ protected IntPtr NativeHandle { get { - if (this.nativeHandle == IntPtr.Zero) + if (nativeHandle == IntPtr.Zero) { CreateBrush(); } - return this.nativeHandle; + return nativeHandle; } set { - Debug.Assert(this.nativeHandle == IntPtr.Zero, "WindowsBrush object is immutable"); + Debug.Assert(nativeHandle == IntPtr.Zero, "WindowsBrush object is immutable"); Debug.Assert(value != IntPtr.Zero, "WARNING: assigning IntPtr.Zero to the nativeHandle object."); - this.nativeHandle = value; + nativeHandle = value; } } @@ -205,7 +205,7 @@ public IntPtr HBrush { get { - return this.NativeHandle; + return NativeHandle; } } } diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs index 6d1d28ac90c..4909b2c0ed1 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs @@ -60,19 +60,19 @@ sealed partial class WindowsFont : MarshalByRefObject, ICloneable, IDisposable private void CreateFont() { Debug.Assert(hFont == IntPtr.Zero, "hFont is not null, this will generate a handle leak."); - Debug.Assert(this.logFont != null, "WindowsFont.logFont not initialized."); + Debug.Assert(logFont != null, "WindowsFont.logFont not initialized."); - this.hFont = IntUnsafeNativeMethods.CreateFontIndirect(this.logFont); + hFont = IntUnsafeNativeMethods.CreateFontIndirect(logFont); #if TRACK_HFONT Debug.WriteLine( DbgUtil.StackTraceToStr(String.Format( "HFONT[0x{0:x8}] = CreateFontIndirect( LOGFONT={1} )", (int) this.hFont, this.logFont))); #endif - if (this.hFont == IntPtr.Zero) + if (hFont == IntPtr.Zero) { - this.logFont.lfFaceName = defaultFaceName; - this.logFont.lfOutPrecision = IntNativeMethods.OUT_TT_ONLY_PRECIS; // True Type only. + logFont.lfFaceName = defaultFaceName; + logFont.lfOutPrecision = IntNativeMethods.OUT_TT_ONLY_PRECIS; // True Type only. - this.hFont = IntUnsafeNativeMethods.CreateFontIndirect(this.logFont); + hFont = IntUnsafeNativeMethods.CreateFontIndirect(logFont); #if TRACK_HFONT Debug.WriteLine( DbgUtil.StackTraceToStr(String.Format( "HFONT[0x{0:x8}] = CreateFontIndirect( LOGFONT={1} )", (int) this.hFont, this.logFont))); @@ -82,10 +82,10 @@ private void CreateFont() // Update logFont height and other adjusted parameters. // - IntUnsafeNativeMethods.GetObject(new HandleRef(this, this.hFont), this.logFont); + IntUnsafeNativeMethods.GetObject(new HandleRef(this, hFont), logFont); // We created the hFont, we will delete it on dispose. - this.ownHandle = true; + ownHandle = true; } /// Constructors. @@ -132,7 +132,7 @@ public WindowsFont(string faceName, float size, FontStyle style, byte charSet, W Debug.Assert(size > 0.0f, "size has a negative value."); const byte True = 1; const byte False = 0; - this.logFont = new IntNativeMethods.LOGFONT(); + logFont = new IntNativeMethods.LOGFONT(); // // Get the font height from the specified size. size is in point units and height in logical @@ -146,15 +146,15 @@ public WindowsFont(string faceName, float size, FontStyle style, byte charSet, W // leading; we specify a negative size value (in pixels) for the height so the font mapper // provides the closest match for the character height rather than the cell height (MSDN). // - this.logFont.lfHeight = -pixelsY; - this.logFont.lfFaceName = faceName != null ? faceName : defaultFaceName; - this.logFont.lfCharSet = charSet; - this.logFont.lfOutPrecision = IntNativeMethods.OUT_TT_PRECIS; - this.logFont.lfQuality = (byte)fontQuality; - this.logFont.lfWeight = (style & FontStyle.Bold) == FontStyle.Bold ? IntNativeMethods.FW_BOLD : IntNativeMethods.FW_NORMAL; - this.logFont.lfItalic = (style & FontStyle.Italic) == FontStyle.Italic ? True : False; - this.logFont.lfUnderline = (style & FontStyle.Underline) == FontStyle.Underline ? True : False; - this.logFont.lfStrikeOut = (style & FontStyle.Strikeout) == FontStyle.Strikeout ? True : False; + logFont.lfHeight = -pixelsY; + logFont.lfFaceName = faceName != null ? faceName : defaultFaceName; + logFont.lfCharSet = charSet; + logFont.lfOutPrecision = IntNativeMethods.OUT_TT_PRECIS; + logFont.lfQuality = (byte)fontQuality; + logFont.lfWeight = (style & FontStyle.Bold) == FontStyle.Bold ? IntNativeMethods.FW_BOLD : IntNativeMethods.FW_NORMAL; + logFont.lfItalic = (style & FontStyle.Italic) == FontStyle.Italic ? True : False; + logFont.lfUnderline = (style & FontStyle.Underline) == FontStyle.Underline ? True : False; + logFont.lfStrikeOut = (style & FontStyle.Strikeout) == FontStyle.Strikeout ? True : False; // Let the Size be recomputed to be consistent with the Height (there may be some precision loss coming from size to height). // this.fontSize = size; @@ -174,29 +174,29 @@ private WindowsFont(IntNativeMethods.LOGFONT lf, bool createHandle) { Debug.Assert(lf != null, "lf is null"); - this.logFont = lf; + logFont = lf; - if (this.logFont.lfFaceName == null) + if (logFont.lfFaceName == null) { - this.logFont.lfFaceName = defaultFaceName; + logFont.lfFaceName = defaultFaceName; } - this.style = FontStyle.Regular; + style = FontStyle.Regular; if (lf.lfWeight == IntNativeMethods.FW_BOLD) { - this.style |= FontStyle.Bold; + style |= FontStyle.Bold; } if (lf.lfItalic == 1) { - this.style |= FontStyle.Italic; + style |= FontStyle.Italic; } if (lf.lfUnderline == 1) { - this.style |= FontStyle.Underline; + style |= FontStyle.Underline; } if (lf.lfStrikeOut == 1) { - this.style |= FontStyle.Strikeout; + style |= FontStyle.Strikeout; } if (createHandle) @@ -293,7 +293,7 @@ public void Dispose() internal void Dispose(bool disposing) { bool deletedHandle = false; - if (this.ownHandle) + if (ownHandle) { if (!ownedByCacheManager || !disposing) { @@ -305,15 +305,15 @@ internal void Dispose(bool disposing) // and that means we're being called from the finalizer. if (everOwnedByCacheManager || !disposing || !DeviceContexts.IsFontInUse(this)) { - Debug.Assert(this.hFont != IntPtr.Zero, "Unexpected null hFont."); + Debug.Assert(hFont != IntPtr.Zero, "Unexpected null hFont."); DbgUtil.AssertFinalization(this, disposing); - IntUnsafeNativeMethods.DeleteObject(new HandleRef(this, this.hFont)); + IntUnsafeNativeMethods.DeleteObject(new HandleRef(this, hFont)); #if TRACK_HFONT Debug.WriteLine( DbgUtil.StackTraceToStr(String.Format( "DeleteObject(HFONT[0x{0:x8}]))", (int) this.hFont))); #endif - this.hFont = IntPtr.Zero; - this.ownHandle = false; + hFont = IntPtr.Zero; + ownHandle = false; deletedHandle = true; } } @@ -346,11 +346,11 @@ public override bool Equals(object font) // remoting scenario and proxies cannot access internal or private members. // Compare params used to create the font. - return this.Name == winFont.Name && - this.LogFontHeight == winFont.LogFontHeight && // Equivalent to comparing Size but always at hand. - this.Style == winFont.Style && - this.CharSet == winFont.CharSet && - this.Quality == winFont.Quality; + return Name == winFont.Name && + LogFontHeight == winFont.LogFontHeight && // Equivalent to comparing Size but always at hand. + Style == winFont.Style && + CharSet == winFont.CharSet && + Quality == winFont.Quality; } /// @@ -359,9 +359,9 @@ public override bool Equals(object font) public override int GetHashCode() { // similar to Font.GetHashCode(). - return (int)((((uint)this.Style << 13) | ((uint)this.Style >> 19)) ^ - (((uint)this.CharSet << 26) | ((uint)this.CharSet >> 6)) ^ - (((uint)this.Size << 7) | ((uint)this.Size >> 25))); + return (int)((((uint)Style << 13) | ((uint)Style >> 19)) ^ + (((uint)CharSet << 26) | ((uint)CharSet >> 6)) ^ + (((uint)Size << 7) | ((uint)Size >> 25))); } /// @@ -371,12 +371,12 @@ public override int GetHashCode() public object Clone() { - return new WindowsFont(this.logFont, true); + return new WindowsFont(logFont, true); } public override string ToString() { - return string.Format(CultureInfo.CurrentCulture, "[{0}: Name={1}, Size={2} points, Height={3} pixels, Sytle={4}]", GetType().Name, logFont.lfFaceName, this.Size, this.Height, this.Style); + return string.Format(CultureInfo.CurrentCulture, "[{0}: Name={1}, Size={2} points, Height={3} pixels, Sytle={4}]", GetType().Name, logFont.lfFaceName, Size, Height, Style); } //////////////////////////////////////////// @@ -392,7 +392,7 @@ public IntPtr Hfont { //Assert removed. We need to be able to check for Hfont == IntPtr.Zero to determine if the object was disposed. //Debug.Assert(this.hFont != IntPtr.Zero, "hFont is null, are you using a disposed object?"); - return this.hFont; + return hFont; } } @@ -430,7 +430,7 @@ public WindowsFontQuality Quality { get { - return (WindowsFontQuality)this.logFont.lfQuality; + return (WindowsFontQuality)logFont.lfQuality; } } @@ -441,7 +441,7 @@ public FontStyle Style { get { - return this.style; + return style; } } @@ -458,7 +458,7 @@ public int Height get { - if (this.lineSpacing == 0) + if (lineSpacing == 0) { // Observe that the font text metrics are obtained using the resolution of the screen. WindowsGraphics wg = WindowsGraphicsCacheManager.MeasurementGraphics; @@ -468,10 +468,10 @@ public int Height wg.DeviceContext.SelectFont(this); IntNativeMethods.TEXTMETRIC tm = (IntNativeMethods.TEXTMETRIC)wg.GetTextMetrics(); - this.lineSpacing = tm.tmHeight; + lineSpacing = tm.tmHeight; } - return this.lineSpacing; + return lineSpacing; } } @@ -518,7 +518,7 @@ public float Size { get { - if (this.fontSize < 0.0f) + if (fontSize < 0.0f) { WindowsGraphics wg = WindowsGraphicsCacheManager.MeasurementGraphics; @@ -534,7 +534,7 @@ public float Size // the point size; in this case lfHeight will roughly match the tmHeight field of // the TEXTMETRIC structure less the tmInternalLeading field. // - int height = this.logFont.lfHeight > 0 ? tm.tmHeight : (tm.tmHeight - tm.tmInternalLeading); + int height = logFont.lfHeight > 0 ? tm.tmHeight : (tm.tmHeight - tm.tmInternalLeading); // /* @@ -548,10 +548,10 @@ public float Size } */ - this.fontSize = height * 72f / wg.DeviceContext.DpiY; + fontSize = height * 72f / wg.DeviceContext.DpiY; } - return this.fontSize; + return fontSize; } } diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics.cs index e366be41e89..e8e85b79502 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics.cs @@ -231,7 +231,7 @@ public DeviceContext DeviceContext { get { - return this.dc; + return dc; } } @@ -252,24 +252,24 @@ public void Dispose() internal void Dispose(bool disposing) { - if (this.dc != null) + if (dc != null) { DbgUtil.AssertFinalization(this, disposing); try { // Restore original dc. - this.dc.RestoreHdc(); + dc.RestoreHdc(); - if (this.disposeDc) + if (disposeDc) { - this.dc.Dispose(disposing); + dc.Dispose(disposing); } - if (this.graphics != null) // if created from a Graphics object... + if (graphics != null) // if created from a Graphics object... { - this.graphics.ReleaseHdcInternal(this.dc.Hdc); - this.graphics = null; + graphics.ReleaseHdcInternal(dc.Hdc); + graphics = null; } } @@ -283,7 +283,7 @@ internal void Dispose(bool disposing) } finally { - this.dc = null; + dc = null; } } } @@ -292,12 +292,12 @@ internal void Dispose(bool disposing) public IntPtr GetHdc() { - return this.dc.Hdc; + return dc.Hdc; } public void ReleaseHdc() { - this.dc.Dispose(); + dc.Dispose(); } } } diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics2.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics2.cs index c52a661c98c..939447386a4 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics2.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics2.cs @@ -50,17 +50,17 @@ public TextPaddingOptions TextPadding [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1803:AvoidCostlyCallsWherePossible")] get { - Debug.Assert(Enum.IsDefined(typeof(TextPaddingOptions), this.paddingFlags)); - return this.paddingFlags; + Debug.Assert(Enum.IsDefined(typeof(TextPaddingOptions), paddingFlags)); + return paddingFlags; } //Since Enum.IsDefined is only used within a Debug.Assert, it is okay to leave it [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1803:AvoidCostlyCallsWherePossible")] set { Debug.Assert(Enum.IsDefined(typeof(TextPaddingOptions), value)); - if (this.paddingFlags != value) + if (paddingFlags != value) { - this.paddingFlags = value; + paddingFlags = value; } } } @@ -71,7 +71,7 @@ public TextPaddingOptions TextPadding /// public void DrawPie(WindowsPen pen, Rectangle bounds, float startAngle, float sweepAngle) { - HandleRef hdc = new HandleRef(this.dc, this.dc.Hdc); + HandleRef hdc = new HandleRef(dc, dc.Hdc); if (pen != null) { @@ -101,7 +101,7 @@ private void DrawEllipse(WindowsPen pen, WindowsBrush brush, int nRightRect, // x-coord of lower-right corner of rectangle int nBottomRect) { // y-coord of lower-right corner of rectangle - HandleRef hdc = new HandleRef(this.dc, this.dc.Hdc); + HandleRef hdc = new HandleRef(dc, dc.Hdc); if (pen != null) { @@ -204,38 +204,38 @@ public void DrawText(string text, WindowsFont font, Rectangle bounds, Color fore Debug.Assert(((uint)flags & GdiUnsupportedFlagMask) == 0, "Some custom flags were left over and are not GDI compliant!"); Debug.Assert((flags & IntTextFormatFlags.CalculateRectangle) == 0, "CalculateRectangle flag is set, text won't be drawn"); - HandleRef hdc = new HandleRef(this.dc, this.dc.Hdc); + HandleRef hdc = new HandleRef(dc, dc.Hdc); // DrawText requires default text alignment. - if (this.dc.TextAlignment != DeviceContextTextAlignment.Default) + if (dc.TextAlignment != DeviceContextTextAlignment.Default) { - this.dc.SetTextAlignment(DeviceContextTextAlignment.Default); + dc.SetTextAlignment(DeviceContextTextAlignment.Default); } // color empty means use the one currently selected in the dc. - if (!foreColor.IsEmpty && foreColor != this.dc.TextColor) + if (!foreColor.IsEmpty && foreColor != dc.TextColor) { - this.dc.SetTextColor(foreColor); + dc.SetTextColor(foreColor); } if (font != null) { - this.dc.SelectFont(font); + dc.SelectFont(font); } DeviceContextBackgroundMode newBackGndMode = (backColor.IsEmpty || backColor == Color.Transparent) ? DeviceContextBackgroundMode.Transparent : DeviceContextBackgroundMode.Opaque; - if (this.dc.BackgroundMode != newBackGndMode) + if (dc.BackgroundMode != newBackGndMode) { - this.dc.SetBackgroundMode(newBackGndMode); + dc.SetBackgroundMode(newBackGndMode); } - if (newBackGndMode != DeviceContextBackgroundMode.Transparent && backColor != this.dc.BackgroundColor) + if (newBackGndMode != DeviceContextBackgroundMode.Transparent && backColor != dc.BackgroundColor) { - this.dc.SetBackgroundColor(backColor); + dc.SetBackgroundColor(backColor); } IntNativeMethods.DRAWTEXTPARAMS dtparams = GetTextMargins(font); @@ -291,7 +291,7 @@ public void DrawText(string text, WindowsFont font, Rectangle bounds, Color fore /// public Color GetNearestColor(Color color) { - HandleRef hdc = new HandleRef(null, this.dc.Hdc); + HandleRef hdc = new HandleRef(null, dc.Hdc); int colorResult = IntUnsafeNativeMethods.GetNearestColor(hdc, ColorTranslator.ToWin32(color)); return ColorTranslator.FromWin32(colorResult); } @@ -310,7 +310,7 @@ public float GetOverhangPadding(WindowsFont font) if (tmpfont == null) { - tmpfont = this.dc.Font; + tmpfont = dc.Font; } float overhangPadding = tmpfont.Height / 6f; @@ -335,7 +335,7 @@ public IntNativeMethods.DRAWTEXTPARAMS GetTextMargins(WindowsFont font) int rightMargin = 0; float overhangPadding = 0; - switch (this.TextPadding) + switch (TextPadding) { case TextPaddingOptions.GlyphOverhangPadding: // [overhang padding][Text][overhang padding][italic padding] @@ -378,20 +378,20 @@ public Size GetTextExtent(string text, WindowsFont font) IntNativeMethods.SIZE size = new IntNativeMethods.SIZE(); - HandleRef hdc = new HandleRef(null, this.dc.Hdc); + HandleRef hdc = new HandleRef(null, dc.Hdc); if (font != null) { - this.dc.SelectFont(font); + dc.SelectFont(font); } IntUnsafeNativeMethods.GetTextExtentPoint32(hdc, text, size); // Unselect, but not from Measurement DC as it keeps the same // font selected for perf reasons. - if (font != null && !MeasurementDCInfo.IsMeasurementDC(this.dc)) + if (font != null && !MeasurementDCInfo.IsMeasurementDC(dc)) { - this.dc.ResetFont(); + dc.ResetFont(); } return new Size(size.cx, size.cy); @@ -454,7 +454,7 @@ public Size MeasureText(string text, WindowsFont font, Size proposedSize, IntTex #if OPTIMIZED_MEASUREMENTDC // use the cache if we've got it - if (MeasurementDCInfo.IsMeasurementDC(this.DeviceContext)) + if (MeasurementDCInfo.IsMeasurementDC(DeviceContext)) { dtparams = MeasurementDCInfo.GetTextMargins(this, font); } @@ -483,11 +483,11 @@ public Size MeasureText(string text, WindowsFont font, Size proposedSize, IntTex IntNativeMethods.RECT rect = IntNativeMethods.RECT.FromXYWH(0, 0, proposedSize.Width, proposedSize.Height); - HandleRef hdc = new HandleRef(null, this.dc.Hdc); + HandleRef hdc = new HandleRef(null, dc.Hdc); if (font != null) { - this.dc.SelectFont(font); + dc.SelectFont(font); } // If proposedSize.Height >= MaxSize.Height it is assumed bounds needed. If flags contain SingleLine and @@ -582,18 +582,18 @@ public void DrawRectangle(WindowsPen pen, int x, int y, int width, int height) { Debug.Assert(pen != null, "pen == null"); - HandleRef hdc = new HandleRef(this.dc, this.dc.Hdc); + HandleRef hdc = new HandleRef(dc, dc.Hdc); if (pen != null) { - this.dc.SelectObject(pen.HPen, GdiObjectType.Pen); + dc.SelectObject(pen.HPen, GdiObjectType.Pen); } - DeviceContextBinaryRasterOperationFlags rasterOp = this.dc.BinaryRasterOperation; + DeviceContextBinaryRasterOperationFlags rasterOp = dc.BinaryRasterOperation; if (rasterOp != DeviceContextBinaryRasterOperationFlags.CopyPen) { - rasterOp = this.dc.SetRasterOperation(DeviceContextBinaryRasterOperationFlags.CopyPen); + rasterOp = dc.SetRasterOperation(DeviceContextBinaryRasterOperationFlags.CopyPen); } IntUnsafeNativeMethods.SelectObject(hdc, new HandleRef(null, IntUnsafeNativeMethods.GetStockObject(IntNativeMethods.HOLLOW_BRUSH))); @@ -602,7 +602,7 @@ public void DrawRectangle(WindowsPen pen, int x, int y, int width, int height) if (rasterOp != DeviceContextBinaryRasterOperationFlags.CopyPen) { - this.dc.SetRasterOperation(rasterOp); + dc.SetRasterOperation(rasterOp); } } @@ -617,7 +617,7 @@ public void FillRectangle(WindowsBrush brush, int x, int y, int width, int heigh { Debug.Assert(brush != null, "brush == null"); - HandleRef hdc = new HandleRef(this.dc, this.dc.Hdc); + HandleRef hdc = new HandleRef(dc, dc.Hdc); IntPtr hBrush = brush.HBrush; // We don't delete this handle since we didn't create it. IntNativeMethods.RECT rect = new IntNativeMethods.RECT(x, y, x + width, y + height); @@ -647,24 +647,24 @@ public void DrawLine(WindowsPen pen, Point p1, Point p2) public void DrawLine(WindowsPen pen, int x1, int y1, int x2, int y2) { - HandleRef hdc = new HandleRef(this.dc, this.dc.Hdc); + HandleRef hdc = new HandleRef(dc, dc.Hdc); - DeviceContextBinaryRasterOperationFlags rasterOp = this.dc.BinaryRasterOperation; - DeviceContextBackgroundMode bckMode = this.dc.BackgroundMode; + DeviceContextBinaryRasterOperationFlags rasterOp = dc.BinaryRasterOperation; + DeviceContextBackgroundMode bckMode = dc.BackgroundMode; if (rasterOp != DeviceContextBinaryRasterOperationFlags.CopyPen) { - rasterOp = this.dc.SetRasterOperation(DeviceContextBinaryRasterOperationFlags.CopyPen); + rasterOp = dc.SetRasterOperation(DeviceContextBinaryRasterOperationFlags.CopyPen); } if (bckMode != DeviceContextBackgroundMode.Transparent) { - bckMode = this.dc.SetBackgroundMode(DeviceContextBackgroundMode.Transparent); + bckMode = dc.SetBackgroundMode(DeviceContextBackgroundMode.Transparent); } if (pen != null) { - this.dc.SelectObject(pen.HPen, GdiObjectType.Pen); + dc.SelectObject(pen.HPen, GdiObjectType.Pen); } IntNativeMethods.POINT oldPoint = new IntNativeMethods.POINT(); @@ -674,12 +674,12 @@ public void DrawLine(WindowsPen pen, int x1, int y1, int x2, int y2) if (bckMode != DeviceContextBackgroundMode.Transparent) { - this.dc.SetBackgroundMode(bckMode); + dc.SetBackgroundMode(bckMode); } if (rasterOp != DeviceContextBinaryRasterOperationFlags.CopyPen) { - this.dc.SetRasterOperation(rasterOp); + dc.SetRasterOperation(rasterOp); } IntUnsafeNativeMethods.MoveToEx(hdc, oldPoint.x, oldPoint.y, null); @@ -692,7 +692,7 @@ public void DrawLine(WindowsPen pen, int x1, int y1, int x2, int y2) public IntNativeMethods.TEXTMETRIC GetTextMetrics() { IntNativeMethods.TEXTMETRIC tm = new IntNativeMethods.TEXTMETRIC(); - HandleRef hdc = new HandleRef(this.dc, this.dc.Hdc); + HandleRef hdc = new HandleRef(dc, dc.Hdc); // Set the mapping mode to MM_TEXT so we deal with units of pixels. DeviceContextMapMode mapMode = dc.MapMode; diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsPen.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsPen.cs index 3e74adfe239..595895f1018 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsPen.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsPen.cs @@ -95,9 +95,9 @@ public WindowsPen(DeviceContext dc, WindowsPenStyle style, int width, WindowsBru Debug.Assert(windowsBrush != null, "null windowsBrush"); this.style = style; - this.wndBrush = (WindowsBrush)windowsBrush.Clone(); + wndBrush = (WindowsBrush)windowsBrush.Clone(); this.width = width; - this.color = windowsBrush.Color; + color = windowsBrush.Color; this.dc = dc; // CreatePen() created on demand. @@ -107,26 +107,26 @@ public WindowsPen(DeviceContext dc, WindowsPenStyle style, int width, WindowsBru private void CreatePen() { - if (this.width > 1) // Geometric pen. + if (width > 1) // Geometric pen. { // From MSDN: if width > 1, the style must be PS_NULL, PS_SOLID, or PS_INSIDEFRAME. - this.style |= WindowsPenStyle.Geometric | WindowsPenStyle.Solid; + style |= WindowsPenStyle.Geometric | WindowsPenStyle.Solid; } - if (this.wndBrush == null) + if (wndBrush == null) { - this.nativeHandle = IntSafeNativeMethods.CreatePen((int)this.style, this.width, ColorTranslator.ToWin32(this.color)); + nativeHandle = IntSafeNativeMethods.CreatePen((int)style, width, ColorTranslator.ToWin32(color)); } else { IntNativeMethods.LOGBRUSH lb = new IntNativeMethods.LOGBRUSH(); - lb.lbColor = ColorTranslator.ToWin32(this.wndBrush.Color); + lb.lbColor = ColorTranslator.ToWin32(wndBrush.Color); lb.lbStyle = IntNativeMethods.BS_SOLID; lb.lbHatch = 0; // Note: We currently don't support custom styles, that's why 0 and null for last two params. - this.nativeHandle = IntSafeNativeMethods.ExtCreatePen((int)this.style, this.width, lb, 0, null); + nativeHandle = IntSafeNativeMethods.ExtCreatePen((int)style, width, lb, 0, null); } } @@ -134,9 +134,9 @@ private void CreatePen() public object Clone() { - return (this.wndBrush != null) ? - new WindowsPen(this.dc, this.style, this.width, (WindowsBrush)this.wndBrush.Clone()) : - new WindowsPen(this.dc, this.style, this.width, this.color); + return (wndBrush != null) ? + new WindowsPen(dc, style, width, (WindowsBrush)wndBrush.Clone()) : + new WindowsPen(dc, style, width, color); } ~WindowsPen() @@ -151,18 +151,18 @@ public void Dispose() void Dispose(bool disposing) { - if (this.nativeHandle != IntPtr.Zero && dc != null) + if (nativeHandle != IntPtr.Zero && dc != null) { DbgUtil.AssertFinalization(this, disposing); - dc.DeleteObject(this.nativeHandle, GdiObjectType.Pen); - this.nativeHandle = IntPtr.Zero; + dc.DeleteObject(nativeHandle, GdiObjectType.Pen); + nativeHandle = IntPtr.Zero; } - if (this.wndBrush != null) + if (wndBrush != null) { - this.wndBrush.Dispose(); - this.wndBrush = null; + wndBrush.Dispose(); + wndBrush = null; } if (disposing) @@ -175,23 +175,23 @@ public IntPtr HPen { get { - if (this.nativeHandle == IntPtr.Zero) + if (nativeHandle == IntPtr.Zero) { CreatePen(); } - return this.nativeHandle; + return nativeHandle; } } public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "{0}: Style={1}, Color={2}, Width={3}, Brush={4}", - this.GetType().Name, - this.style, - this.color, - this.width, - this.wndBrush != null ? this.wndBrush.ToString() : "null"); + GetType().Name, + style, + color, + width, + wndBrush != null ? wndBrush.ToString() : "null"); } } diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsRegion.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsRegion.cs index fda79a09f69..6df3bbd6761 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsRegion.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsRegion.cs @@ -119,9 +119,9 @@ public object Clone() // WARNING: WindowsRegion currently supports rectangulare regions only, if the WindowsRegion was created // from an HRegion and it is not rectangular this method won't work as expected. // Note: This method is currently not used and is here just to implement ICloneable. - return this.IsInfinite ? + return IsInfinite ? new WindowsRegion() : - new WindowsRegion(this.ToRectangle()); + new WindowsRegion(ToRectangle()); } /// @@ -130,7 +130,7 @@ public object Clone() /// public IntNativeMethods.RegionFlags CombineRegion(WindowsRegion region1, WindowsRegion region2, RegionCombineMode mode) { - return IntUnsafeNativeMethods.CombineRgn(new HandleRef(this, this.HRegion), new HandleRef(region1, region1.HRegion), new HandleRef(region2, region2.HRegion), mode); + return IntUnsafeNativeMethods.CombineRgn(new HandleRef(this, HRegion), new HandleRef(region1, region1.HRegion), new HandleRef(region2, region2.HRegion), mode); } /// @@ -140,7 +140,7 @@ public IntNativeMethods.RegionFlags CombineRegion(WindowsRegion region1, Windows private void CreateRegion(Rectangle rect) { Debug.Assert(nativeHandle == IntPtr.Zero, "nativeHandle should be null, we're leaking handle"); - this.nativeHandle = IntSafeNativeMethods.CreateRectRgn(rect.X, rect.Y, rect.X + rect.Width, rect.Y + rect.Height); + nativeHandle = IntSafeNativeMethods.CreateRectRgn(rect.X, rect.Y, rect.X + rect.Width, rect.Y + rect.Height); ownHandle = true; } @@ -155,16 +155,16 @@ public void Dispose() /// public void Dispose(bool disposing) { - if (this.nativeHandle != IntPtr.Zero) + if (nativeHandle != IntPtr.Zero) { DbgUtil.AssertFinalization(this, disposing); - if (this.ownHandle) + if (ownHandle) { - IntUnsafeNativeMethods.DeleteObject(new HandleRef(this, this.nativeHandle)); + IntUnsafeNativeMethods.DeleteObject(new HandleRef(this, nativeHandle)); } - this.nativeHandle = IntPtr.Zero; + nativeHandle = IntPtr.Zero; if (disposing) { @@ -187,7 +187,7 @@ public IntPtr HRegion { get { - return this.nativeHandle; + return nativeHandle; } } @@ -197,7 +197,7 @@ public bool IsInfinite { get { - return this.nativeHandle == IntPtr.Zero; + return nativeHandle == IntPtr.Zero; } } @@ -206,13 +206,13 @@ public bool IsInfinite /// public Rectangle ToRectangle() { - if (this.IsInfinite) + if (IsInfinite) { return new Rectangle(-int.MaxValue, -int.MaxValue, int.MaxValue, int.MaxValue); } IntNativeMethods.RECT rect = new IntNativeMethods.RECT(); - IntUnsafeNativeMethods.GetRgnBox(new HandleRef(this, this.nativeHandle), ref rect); + IntUnsafeNativeMethods.GetRgnBox(new HandleRef(this, nativeHandle), ref rect); return new Rectangle(new Point(rect.left, rect.top), rect.Size); } } diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsSolidBrush.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsSolidBrush.cs index 883664ec7b5..0964ea6e7d9 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsSolidBrush.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsSolidBrush.cs @@ -29,13 +29,13 @@ sealed class WindowsSolidBrush : WindowsBrush protected override void CreateBrush() { - IntPtr nativeHandle = IntSafeNativeMethods.CreateSolidBrush(ColorTranslator.ToWin32(this.Color)); + IntPtr nativeHandle = IntSafeNativeMethods.CreateSolidBrush(ColorTranslator.ToWin32(Color)); if (nativeHandle == IntPtr.Zero) // Don't use Debug.Assert, DbgUtil.GetLastErrorStr would always be evaluated. { Debug.Fail("CreateSolidBrush failed : " + DbgUtil.GetLastErrorStr()); } - this.NativeHandle = nativeHandle; // sets the handle value in the base class. + NativeHandle = nativeHandle; // sets the handle value in the base class. } @@ -56,12 +56,12 @@ public WindowsSolidBrush(DeviceContext dc, Color color) : base(dc, color) public override object Clone() { - return new WindowsSolidBrush(this.DC, this.Color); + return new WindowsSolidBrush(DC, Color); } public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0}: Color={1}", this.GetType().Name, this.Color); + return string.Format(CultureInfo.InvariantCulture, "{0}: Color={1}", GetType().Name, Color); } } } diff --git a/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/MenuStripAndCheckedListBox.cs b/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/MenuStripAndCheckedListBox.cs index ae29054d6cb..39c4ace5865 100644 --- a/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/MenuStripAndCheckedListBox.cs +++ b/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/MenuStripAndCheckedListBox.cs @@ -27,7 +27,7 @@ private void MenuStripAndCheckedListBox_DpiChanged(object sender, DpiChangedEven { currentDpiLabel.Text = $"Current scaling = {(int)Math.Round((DeviceDpi / 96.0) * 100)}%"; - this.menuStrip1.SuspendLayout(); + menuStrip1.SuspendLayout(); float factor = (float)e.DeviceDpiNew / e.DeviceDpiOld; @@ -43,7 +43,7 @@ private void MenuStripAndCheckedListBox_DpiChanged(object sender, DpiChangedEven Font f = menuStrip1.Font; menuStrip1.Font = new Font(f.FontFamily, f.Size * factor, f.Style); - this.menuStrip1.ResumeLayout(); + menuStrip1.ResumeLayout(); } } From a7851a42aa4c7d9c568ed87d3b987bfa5e69fe54 Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Fri, 24 May 2019 11:42:23 -0700 Subject: [PATCH 11/27] remove all instances of IDE0012 warning - prefer var to explicit --- .../tests/UnitTests/ArrayEditorTests.cs | 4 +-- .../UnitTests/ObjectSelectorEditorTests.cs | 8 ++--- .../Design/CollectionEditorTests.cs | 2 +- .../Design/CollectionFormTests.cs | 2 +- .../CollectionCodeDomSerializerTests.cs | 2 +- .../System/Drawing/Design/ToolboxItemTests.cs | 8 ++--- .../src/System/Windows/Forms/Application.cs | 4 +-- .../ButtonInternal/ButtonStandardAdapter.cs | 2 +- .../src/System/Windows/Forms/ComboBox.cs | 10 +++---- .../Forms/DataGridViewAccessibleObject.cs | 2 +- .../System/Windows/Forms/DataGridViewRow.cs | 2 +- .../Forms/DataGridViewTopLeftHeaderCell.cs | 2 +- .../src/System/Windows/Forms/PropertyGrid.cs | 6 ++-- .../Forms/PropertyGridInternal/DocComment.cs | 2 +- .../Forms/PropertyGridInternal/GridEntry.cs | 2 +- .../Forms/PropertyGridInternal/HotCommands.cs | 2 +- .../PropertyGridInternal/PropertyGridView.cs | 16 +++++----- .../src/System/Windows/Forms/ToolStrip.cs | 12 ++++---- .../Windows/Forms/ToolStripDropDownItem.cs | 2 +- .../TestHelpers.cs | 2 +- .../WinformsControlsTest.cs | 30 +++++++++---------- .../ComboBoxAccessibleObjectTests.cs | 2 +- .../DataGridViewAccessibleObjectTests.cs | 2 +- .../ToolStripAccessibleObjectTests.cs | 2 +- .../tests/UnitTests/BindingNavigatorTests.cs | 4 +-- .../tests/UnitTests/ButtonTests.cs | 12 ++++---- .../tests/UnitTests/CheckBoxTests.cs | 12 ++++---- .../tests/UnitTests/CheckedListBoxTests.cs | 16 +++++----- .../tests/UnitTests/ContextMenuStripTests.cs | 2 +- .../tests/UnitTests/DomainUpDownTests.cs | 18 +++++------ .../tests/UnitTests/ErrorProviderTests.cs | 2 +- .../tests/UnitTests/NotifyIconTests.cs | 2 +- .../System/Resources/ResXFileRefTests.cs | 2 +- .../Windows/Forms/BindingContextTests.cs | 4 +-- .../System/Windows/Forms/ComboBoxTests.cs | 4 +-- .../System/Windows/Forms/ControlTests.cs | 26 ++++++++-------- .../Windows/Forms/DataGridColumnStyleTests.cs | 4 +-- .../Windows/Forms/DataGridViewCellTests.cs | 4 +-- .../Windows/Forms/DataGridViewRowTests.cs | 6 ++-- .../System/Windows/Forms/ListBoxTests.cs | 4 +-- .../System/Windows/Forms/MessageTests.cs | 2 +- .../tests/UnitTests/ToolTipTests.cs | 2 +- .../UnitTests/VisualStyleRendererTests.cs | 2 +- 43 files changed, 128 insertions(+), 128 deletions(-) diff --git a/src/System.Windows.Forms.Design.Editors/tests/UnitTests/ArrayEditorTests.cs b/src/System.Windows.Forms.Design.Editors/tests/UnitTests/ArrayEditorTests.cs index 93b3a8b4465..4d0be704153 100644 --- a/src/System.Windows.Forms.Design.Editors/tests/UnitTests/ArrayEditorTests.cs +++ b/src/System.Windows.Forms.Design.Editors/tests/UnitTests/ArrayEditorTests.cs @@ -14,14 +14,14 @@ public class ArrayEditorTests [Fact] public void ArrayEditor_Constructor() { - var underTest = GetNewEditor(); + TestArrayEditor underTest = GetNewEditor(); Assert.NotNull(underTest); } [Fact] public void ArrayEditor_Getters() { - var underTest = GetNewEditor(); + TestArrayEditor underTest = GetNewEditor(); Assert.Equal(typeof(string), underTest.GetCollectionType()); Assert.True(underTest.CanSelectMultiple()); Assert.True(underTest.CanRemove("some string")); diff --git a/src/System.Windows.Forms.Design.Editors/tests/UnitTests/ObjectSelectorEditorTests.cs b/src/System.Windows.Forms.Design.Editors/tests/UnitTests/ObjectSelectorEditorTests.cs index 27890a69936..0ab054ee428 100644 --- a/src/System.Windows.Forms.Design.Editors/tests/UnitTests/ObjectSelectorEditorTests.cs +++ b/src/System.Windows.Forms.Design.Editors/tests/UnitTests/ObjectSelectorEditorTests.cs @@ -13,7 +13,7 @@ public class ObjectSelectorEditorTests [Fact] public void ObjectSelectorEditor_Constructor() { - var underTest = GetNewObjectSelectorEditor(); + ObjectSelectorEditor underTest = GetNewObjectSelectorEditor(); Assert.NotNull(underTest); Assert.True(underTest.EqualsToValue(null)); @@ -26,7 +26,7 @@ public void ObjectSelectorEditor_Constructor() [Fact] public void ObjectSelectorEditor_CurrentValue() { - var underTest = GetNewObjectSelectorEditor(); + ObjectSelectorEditor underTest = GetNewObjectSelectorEditor(); underTest.SetValue("some Value"); Assert.True(underTest.EqualsToValue("some Value")); @@ -36,7 +36,7 @@ public void ObjectSelectorEditor_CurrentValue() [Fact] public void ObjectSelectorEditor_GetEditStyle() { - var underTest = GetNewObjectSelectorEditor(); + ObjectSelectorEditor underTest = GetNewObjectSelectorEditor(); Assert.Equal(UITypeEditorEditStyle.DropDown, underTest.GetEditStyle(null)); } @@ -44,7 +44,7 @@ public void ObjectSelectorEditor_GetEditStyle() [Fact] public void ObjectSelectorEditor_Selector() { - var underTest = GetNewSelector(); + ObjectSelectorEditor.Selector underTest = GetNewSelector(); Assert.NotNull(underTest); underTest.AddNode("node", "value", null); diff --git a/src/System.Windows.Forms.Design.Editors/tests/UnitTests/System/ComponentModel/Design/CollectionEditorTests.cs b/src/System.Windows.Forms.Design.Editors/tests/UnitTests/System/ComponentModel/Design/CollectionEditorTests.cs index b08699a6257..126332f941f 100644 --- a/src/System.Windows.Forms.Design.Editors/tests/UnitTests/System/ComponentModel/Design/CollectionEditorTests.cs +++ b/src/System.Windows.Forms.Design.Editors/tests/UnitTests/System/ComponentModel/Design/CollectionEditorTests.cs @@ -306,7 +306,7 @@ public void CollectionEditor_CreateInstance_WithContextWithHostReturningComponen var result = new Component(); var mockDesigner = new Mock(MockBehavior.Strict); - var mockComponentInitializer = mockDesigner.As(); + Mock mockComponentInitializer = mockDesigner.As(); mockComponentInitializer .Setup(d => d.InitializeNewComponent(null)) .Verifiable(); diff --git a/src/System.Windows.Forms.Design.Editors/tests/UnitTests/System/ComponentModel/Design/CollectionFormTests.cs b/src/System.Windows.Forms.Design.Editors/tests/UnitTests/System/ComponentModel/Design/CollectionFormTests.cs index 3f3b9bdc8d3..49a06a0e400 100644 --- a/src/System.Windows.Forms.Design.Editors/tests/UnitTests/System/ComponentModel/Design/CollectionFormTests.cs +++ b/src/System.Windows.Forms.Design.Editors/tests/UnitTests/System/ComponentModel/Design/CollectionFormTests.cs @@ -655,7 +655,7 @@ public void CollectionForm_CreateInstance_WithContextWithHostReturningComponentW var result = new Component(); var mockDesigner = new Mock(MockBehavior.Strict); - var mockComponentInitializer = mockDesigner.As(); + Mock mockComponentInitializer = mockDesigner.As(); mockComponentInitializer .Setup(d => d.InitializeNewComponent(null)) .Verifiable(); diff --git a/src/System.Windows.Forms.Design/tests/UnitTests/Serialization/CollectionCodeDomSerializerTests.cs b/src/System.Windows.Forms.Design/tests/UnitTests/Serialization/CollectionCodeDomSerializerTests.cs index e0e72414e56..b23db2b68b4 100644 --- a/src/System.Windows.Forms.Design/tests/UnitTests/Serialization/CollectionCodeDomSerializerTests.cs +++ b/src/System.Windows.Forms.Design/tests/UnitTests/Serialization/CollectionCodeDomSerializerTests.cs @@ -12,7 +12,7 @@ public class CollectionCodeDomSerializerTests [Fact] public void CollectionCodeDomSerializer_Constructor() { - var underTest = CollectionCodeDomSerializer.Default; + CollectionCodeDomSerializer underTest = CollectionCodeDomSerializer.Default; Assert.NotNull(underTest); } } diff --git a/src/System.Windows.Forms.Design/tests/UnitTests/System/Drawing/Design/ToolboxItemTests.cs b/src/System.Windows.Forms.Design/tests/UnitTests/System/Drawing/Design/ToolboxItemTests.cs index c14c317b97f..8a99317290f 100644 --- a/src/System.Windows.Forms.Design/tests/UnitTests/System/Drawing/Design/ToolboxItemTests.cs +++ b/src/System.Windows.Forms.Design/tests/UnitTests/System/Drawing/Design/ToolboxItemTests.cs @@ -490,7 +490,7 @@ public void ToolboxItem_CreateComponents_InvokeWithHostWithIComponentInitializer }; var mockDesigner = new Mock(MockBehavior.Strict); mockDesigner.Setup(d => d.Dispose()); - var mockComponentInitializer = mockDesigner.As(); + Mock mockComponentInitializer = mockDesigner.As(); mockComponentInitializer .Setup(i => i.InitializeNewComponent(null)); mockComponentInitializer @@ -556,7 +556,7 @@ public void ToolboxItem_CreateComponents_InvokeWithHostWithThrowingIComponentIni }; var mockDesigner = new Mock(MockBehavior.Strict); mockDesigner.Setup(d => d.Dispose()); - var mockComponentInitializer = mockDesigner.As(); + Mock mockComponentInitializer = mockDesigner.As(); mockComponentInitializer .Setup(i => i.InitializeNewComponent(null)) .Throws(new Exception()); @@ -809,7 +809,7 @@ public void ToolboxItem_CreateComponentsCore_InvokeWithHostWithIComponentInitial }; var mockDesigner = new Mock(MockBehavior.Strict); mockDesigner.Setup(d => d.Dispose()); - var mockComponentInitializer = mockDesigner.As(); + Mock mockComponentInitializer = mockDesigner.As(); mockComponentInitializer .Setup(i => i.InitializeNewComponent(null)); mockComponentInitializer @@ -875,7 +875,7 @@ public void ToolboxItem_CreateComponentsCore_InvokeWithHostWithThrowingIComponen }; var mockDesigner = new Mock(MockBehavior.Strict); mockDesigner.Setup(d => d.Dispose()); - var mockComponentInitializer = mockDesigner.As(); + Mock mockComponentInitializer = mockDesigner.As(); mockComponentInitializer .Setup(i => i.InitializeNewComponent(null)) .Throws(new Exception()); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs index b1291272e03..bd371dd9b06 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs @@ -2560,7 +2560,7 @@ internal ParkingWindow GetParkingWindow(DpiAwarenessContext context) // Locking 'this' here is ok since this is an internal class. lock (this) { - var parkingWindow = GetParkingWindowForContext(context); + ParkingWindow parkingWindow = GetParkingWindowForContext(context); if (parkingWindow == null) { #if DEBUG @@ -2605,7 +2605,7 @@ internal ParkingWindow GetParkingWindowForContext(DpiAwarenessContext context) } // Supported OS scenario. - foreach (var p in parkingWindows) + foreach (ParkingWindow p in parkingWindows) { if (CommonUnsafeNativeMethods.TryFindDpiAwarenessContextsEqual(p.DpiAwarenessContext, context)) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonStandardAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonStandardAdapter.cs index 761d6a81ff7..a873d35551d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonStandardAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonStandardAdapter.cs @@ -212,7 +212,7 @@ void PaintWorker(PaintEventArgs e, bool up, CheckState state) if (up & IsHighContrastHighlighted()) { - var highlightTextColor = SystemColors.HighlightText; + Color highlightTextColor = SystemColors.HighlightText; PaintField(e, layout, colors, highlightTextColor, false); if (Control.Focused && Control.ShowFocusCues) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs index d76c1dc9e3c..c11ad9b7582 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs @@ -2288,7 +2288,7 @@ internal NativeWindow GetListNativeWindow() internal int GetListNativeWindowRuntimeIdPart() { - var listNativeWindow = GetListNativeWindow(); + NativeWindow listNativeWindow = GetListNativeWindow(); return listNativeWindow != null ? listNativeWindow.GetHashCode() : 0; } @@ -4780,10 +4780,10 @@ public override Rectangle Bounds { get { - var listAccessibleObject = _owningComboBox.ChildListAccessibleObject; + ChildAccessibleObject listAccessibleObject = _owningComboBox.ChildListAccessibleObject; int currentIndex = GetCurrentIndex(); - var parentRect = listAccessibleObject.BoundingRectangle; + Rectangle parentRect = listAccessibleObject.BoundingRectangle; int left = parentRect.Left; int top = parentRect.Top + _owningComboBox.ItemHeight * currentIndex; int width = parentRect.Width; @@ -5450,7 +5450,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga comboBoxAccessibleObject = _owner.AccessibilityObject as ComboBoxAccessibleObject; if (comboBoxAccessibleObject != null) { - var firstComboBoxChildFragment = comboBoxAccessibleObject.GetChildFragment(0); + AccessibleObject firstComboBoxChildFragment = comboBoxAccessibleObject.GetChildFragment(0); if (RuntimeId != firstComboBoxChildFragment.RuntimeId) { return firstComboBoxChildFragment; @@ -5874,7 +5874,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga comboBoxAccessibleObject = _owner.AccessibilityObject as ComboBoxAccessibleObject; if (comboBoxAccessibleObject != null) { - var firstComboBoxChildFragment = comboBoxAccessibleObject.GetChildFragment(0); + AccessibleObject firstComboBoxChildFragment = comboBoxAccessibleObject.GetChildFragment(0); if (RuntimeId != firstComboBoxChildFragment.RuntimeId) { return firstComboBoxChildFragment; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAccessibleObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAccessibleObject.cs index 2918d03c77b..b0a60848aeb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAccessibleObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAccessibleObject.cs @@ -490,7 +490,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga switch (direction) { case UnsafeNativeMethods.NavigateDirection.Parent: - var currentCell = dataGridView.CurrentCell; + DataGridViewCell currentCell = dataGridView.CurrentCell; if (currentCell != null && dataGridView.IsCurrentCellInEditMode) { return currentCell.AccessibilityObject; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRow.cs index 7428c99c30e..3e46535489e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRow.cs @@ -2192,7 +2192,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga throw new InvalidOperationException(SR.DataGridViewRowAccessibleObject_OwnerNotSet); } - var dataGridView = owner.DataGridView; + DataGridView dataGridView = owner.DataGridView; switch (direction) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopLeftHeaderCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopLeftHeaderCell.cs index 71a9841ccfd..24313bfb874 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopLeftHeaderCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopLeftHeaderCell.cs @@ -650,7 +650,7 @@ public override void Select(AccessibleSelection flags) internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - var dataGridView = Owner.DataGridView; + DataGridView dataGridView = Owner.DataGridView; switch (direction) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs index 833762d331f..66e15398fc3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs @@ -5925,7 +5925,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment ElementProvide { Point clientPoint = _owningPropertyGrid.PointToClient(new Point((int)x, (int)y)); - var element = _owningPropertyGrid.GetElementFromPoint(clientPoint); + Control element = _owningPropertyGrid.GetElementFromPoint(clientPoint); if (element != null) { return element.AccessibilityObject; @@ -6110,7 +6110,7 @@ internal int GetChildFragmentIndex(AccessibleObject controlAccessibleObject) int childFragmentCount = GetChildFragmentCount(); for (int i = 0; i < childFragmentCount; i++) { - var childFragment = GetChildFragment(i); + AccessibleObject childFragment = GetChildFragment(i); if (childFragment == controlAccessibleObject) { return i; @@ -6184,7 +6184,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga var propertyGridAccessibleObject = _parentPropertyGrid.AccessibilityObject as PropertyGridAccessibleObject; if (propertyGridAccessibleObject != null) { - var navigationTarget = propertyGridAccessibleObject.ChildFragmentNavigate(this, direction); + UnsafeNativeMethods.IRawElementProviderFragment navigationTarget = propertyGridAccessibleObject.ChildFragmentNavigate(this, direction); if (navigationTarget != null) { return navigationTarget; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs index ecae3f2b447..41198f51925 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs @@ -291,7 +291,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga var propertyGridAccessibleObject = _parentPropertyGrid.AccessibilityObject as PropertyGridAccessibleObject; if (propertyGridAccessibleObject != null) { - var navigationTarget = propertyGridAccessibleObject.ChildFragmentNavigate(this, direction); + UnsafeNativeMethods.IRawElementProviderFragment navigationTarget = propertyGridAccessibleObject.ChildFragmentNavigate(this, direction); if (navigationTarget != null) { return navigationTarget; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs index 3245b26cfbc..fda8ad60de7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs @@ -3166,7 +3166,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga switch (direction) { case UnsafeNativeMethods.NavigateDirection.Parent: - var parentGridEntry = owner.ParentGridEntry; + GridEntry parentGridEntry = owner.ParentGridEntry; if (parentGridEntry != null) { if (parentGridEntry is SingleSelectRootGridEntry) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs index 81bbc2de0f3..0bfe3be2a8e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs @@ -286,7 +286,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga var propertyGridAccessibleObject = _parentPropertyGrid.AccessibilityObject as PropertyGridAccessibleObject; if (propertyGridAccessibleObject != null) { - var navigationTarget = propertyGridAccessibleObject.ChildFragmentNavigate(this, direction); + UnsafeNativeMethods.IRawElementProviderFragment navigationTarget = propertyGridAccessibleObject.ChildFragmentNavigate(this, direction); if (navigationTarget != null) { return navigationTarget; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs index 57b1ab73276..d4cc7a15678 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs @@ -1698,7 +1698,7 @@ internal IntPtr GetBaseHfont() internal GridEntry GetElementFromPoint(int x, int y) { Point point = new Point(x, y); - var allGridEntries = GetAllGridEntries(); + GridEntryCollection allGridEntries = GetAllGridEntries(); GridEntry[] targetEntries = new GridEntry[allGridEntries.Count]; try { @@ -8019,7 +8019,7 @@ public override string Name } else { - var selectedGridEntry = propertyGridView.SelectedGridEntry; + GridEntry selectedGridEntry = propertyGridView.SelectedGridEntry; if (selectedGridEntry != null) { return selectedGridEntry.AccessibilityObject.Name; @@ -8378,7 +8378,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga var propertyGridAccessibleObject = _parentPropertyGrid.AccessibilityObject as PropertyGridAccessibleObject; if (propertyGridAccessibleObject != null) { - var navigationTarget = propertyGridAccessibleObject.ChildFragmentNavigate(this, direction); + UnsafeNativeMethods.IRawElementProviderFragment navigationTarget = propertyGridAccessibleObject.ChildFragmentNavigate(this, direction); if (navigationTarget != null) { return navigationTarget; @@ -8500,11 +8500,11 @@ public AccessibleObject Next(GridEntry current) internal AccessibleObject GetCategory(int categoryIndex) { GridEntry[] targetEntries = new GridEntry[1]; - var topLevelGridEntries = _owningPropertyGridView.TopLevelGridEntries; + GridEntryCollection topLevelGridEntries = _owningPropertyGridView.TopLevelGridEntries; var topLevelGridEntriesCount = topLevelGridEntries.Count; if (topLevelGridEntriesCount > 0) { - var targetEntry = topLevelGridEntries[categoryIndex]; + GridItem targetEntry = topLevelGridEntries[categoryIndex]; var categoryGridEntry = targetEntry as CategoryGridEntry; if (categoryGridEntry != null) { @@ -8522,7 +8522,7 @@ internal AccessibleObject GetFirstCategory() internal AccessibleObject GetLastCategory() { - var topLevelGridEntries = _owningPropertyGridView.TopLevelGridEntries; + GridEntryCollection topLevelGridEntries = _owningPropertyGridView.TopLevelGridEntries; var topLevelGridEntriesCount = topLevelGridEntries.Count; return GetCategory(topLevelGridEntries.Count - 1); } @@ -8560,7 +8560,7 @@ internal AccessibleObject GetPreviousGridEntry(GridEntry currentGridEntry, GridE previousGridEntry = gridEntry; if (gridEntry.ChildCount > 0) { - var foundChild = GetPreviousGridEntry(currentGridEntry, gridEntry.Children, out currentGridEntryFound); + AccessibleObject foundChild = GetPreviousGridEntry(currentGridEntry, gridEntry.Children, out currentGridEntryFound); if (foundChild != null) { // Return some down-level child if found. @@ -8604,7 +8604,7 @@ internal AccessibleObject GetNextGridEntry(GridEntry currentGridEntry, GridEntry } else if (gridEntry.ChildCount > 0) { - var foundChild = GetNextGridEntry(currentGridEntry, gridEntry.Children, out currentGridEntryFound); + AccessibleObject foundChild = GetNextGridEntry(currentGridEntry, gridEntry.Children, out currentGridEntryFound); if (foundChild != null) { // Return some down-level child if found. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs index 9b98cb57cc2..501179250f6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs @@ -5427,7 +5427,7 @@ public override int GetChildCount() internal AccessibleObject GetChildFragment(int fragmentIndex, bool getOverflowItem = false) { - var items = getOverflowItem ? owner.OverflowItems : owner.DisplayedItems; + ToolStripItemCollection items = getOverflowItem ? owner.OverflowItems : owner.DisplayedItems; int childFragmentCount = items.Count; if (!getOverflowItem && owner.CanOverflow && owner.OverflowButton.Visible && fragmentIndex == childFragmentCount - 1) @@ -5437,7 +5437,7 @@ internal AccessibleObject GetChildFragment(int fragmentIndex, bool getOverflowIt for (int index = 0; index < childFragmentCount; index++) { - var item = items[index]; + ToolStripItem item = items[index]; if (item.Available && item.Alignment == ToolStripItemAlignment.Left && fragmentIndex == index) { var controlHostItem = item as ToolStripControlHost; @@ -5452,7 +5452,7 @@ internal AccessibleObject GetChildFragment(int fragmentIndex, bool getOverflowIt for (int index = 0; index < childFragmentCount; index++) { - var item = owner.Items[index]; + ToolStripItem item = owner.Items[index]; if (item.Available && item.Alignment == ToolStripItemAlignment.Right && fragmentIndex == index) { var controlHostItem = item as ToolStripControlHost; @@ -5501,7 +5501,7 @@ internal int GetChildFragmentIndex(ToolStripItem.ToolStripItemAccessibleObject c } ToolStripItemCollection items; - var placement = child.Owner.Placement; + ToolStripItemPlacement placement = child.Owner.Placement; if (owner is ToolStripOverflow) { @@ -5522,7 +5522,7 @@ internal int GetChildFragmentIndex(ToolStripItem.ToolStripItemAccessibleObject c // First we walk through the head aligned items. for (int index = 0; index < items.Count; index++) { - var item = items[index]; + ToolStripItem item = items[index]; if (item.Available && item.Alignment == ToolStripItemAlignment.Left && child.Owner == items[index]) { return index; @@ -5532,7 +5532,7 @@ internal int GetChildFragmentIndex(ToolStripItem.ToolStripItemAccessibleObject c // If we didn't find it, then we walk through the tail aligned items. for (int index = 0; index < items.Count; index++) { - var item = items[index]; + ToolStripItem item = items[index]; if (item.Available && item.Alignment == ToolStripItemAlignment.Right && child.Owner == items[index]) { return index; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs index 7a19abb3c13..78df4309e64 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs @@ -1008,7 +1008,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga if (index >= 0 && index < dropDown.Items.Count) { - var item = dropDown.Items[index]; + ToolStripItem item = dropDown.Items[index]; var controlHostItem = item as ToolStripControlHost; if (controlHostItem != null) { diff --git a/src/System.Windows.Forms/tests/IntegrationTests/System.Windows.Forms.IntegrationTests/TestHelpers.cs b/src/System.Windows.Forms/tests/IntegrationTests/System.Windows.Forms.IntegrationTests/TestHelpers.cs index 23399e59123..75e760db9df 100644 --- a/src/System.Windows.Forms/tests/IntegrationTests/System.Windows.Forms.IntegrationTests/TestHelpers.cs +++ b/src/System.Windows.Forms/tests/IntegrationTests/System.Windows.Forms.IntegrationTests/TestHelpers.cs @@ -269,7 +269,7 @@ internal static bool PressOnProcess(Process process, string keys) throw new ArgumentException(nameof(keys) + " must not be null or empty."); } - var handle = process.MainWindowHandle; + IntPtr handle = process.MainWindowHandle; ExternalTestHelpers.TrySetForegroundWindow(handle); if (handle.Equals(ExternalTestHelpers.TryGetForegroundWindow())) diff --git a/src/System.Windows.Forms/tests/IntegrationTests/System.Windows.Forms.IntegrationTests/WinformsControlsTest.cs b/src/System.Windows.Forms/tests/IntegrationTests/System.Windows.Forms.IntegrationTests/WinformsControlsTest.cs index a2f9686735f..2a653a1ac24 100644 --- a/src/System.Windows.Forms/tests/IntegrationTests/System.Windows.Forms.IntegrationTests/WinformsControlsTest.cs +++ b/src/System.Windows.Forms/tests/IntegrationTests/System.Windows.Forms.IntegrationTests/WinformsControlsTest.cs @@ -25,7 +25,7 @@ public string GetPathToTestFromBin() [Fact] public void WinformsControlsTest_OpenAndClose() { - var process = TestHelpers.StartProcess(GetPathToTestFromBin()); + Process process = TestHelpers.StartProcess(GetPathToTestFromBin()); Assert.NotNull(process); Assert.NotNull(Process.GetProcessById(process.Id)); @@ -40,7 +40,7 @@ public void WinformsControlsTest_OpenAndClose() [Fact] public void WinformsControlsTest_ButtonsTest() { - var process = TestHelpers.StartProcess(GetPathToTestFromBin()); + Process process = TestHelpers.StartProcess(GetPathToTestFromBin()); TestHelpers.PressEnterOnProcess(process); @@ -55,7 +55,7 @@ public void WinformsControlsTest_ButtonsTest() [Fact] public void WinformsControlsTest_CalendarTest() { - var process = TestHelpers.StartProcess(GetPathToTestFromBin()); + Process process = TestHelpers.StartProcess(GetPathToTestFromBin()); TestHelpers.PressTabsOnProcess(process, 1); TestHelpers.PressEnterOnProcess(process); @@ -87,7 +87,7 @@ public void WinformsControlsTest_CalendarTest() [Fact] public void WinformsControlsTest_ContentAlignmentTest() { - var process = TestHelpers.StartProcess(GetPathToTestFromBin()); + Process process = TestHelpers.StartProcess(GetPathToTestFromBin()); TestHelpers.PressTabsOnProcess(process, 3); TestHelpers.PressEnterOnProcess(process); @@ -102,7 +102,7 @@ public void WinformsControlsTest_ContentAlignmentTest() [Fact] public void WinformsControlsTest_MultipleControlsTest() { - var process = TestHelpers.StartProcess(GetPathToTestFromBin()); + Process process = TestHelpers.StartProcess(GetPathToTestFromBin()); TestHelpers.PressTabsOnProcess(process, 4); TestHelpers.PressEnterOnProcess(process); @@ -117,7 +117,7 @@ public void WinformsControlsTest_MultipleControlsTest() [Fact] public void WinformsControlsTest_DataGridViewTest() { - var process = TestHelpers.StartProcess(GetPathToTestFromBin()); + Process process = TestHelpers.StartProcess(GetPathToTestFromBin()); TestHelpers.PressTabsOnProcess(process, 5); TestHelpers.PressEnterOnProcess(process); @@ -132,7 +132,7 @@ public void WinformsControlsTest_DataGridViewTest() [Fact] public void WinformsControlsTest_MenusTest() { - var process = TestHelpers.StartProcess(GetPathToTestFromBin()); + Process process = TestHelpers.StartProcess(GetPathToTestFromBin()); TestHelpers.PressTabsOnProcess(process, 6); TestHelpers.PressEnterOnProcess(process); @@ -147,7 +147,7 @@ public void WinformsControlsTest_MenusTest() [Fact] public void WinformsControlsTest_PanelsTest() { - var process = TestHelpers.StartProcess(GetPathToTestFromBin()); + Process process = TestHelpers.StartProcess(GetPathToTestFromBin()); TestHelpers.PressTabsOnProcess(process, 7); TestHelpers.PressEnterOnProcess(process); @@ -162,7 +162,7 @@ public void WinformsControlsTest_PanelsTest() [Fact] public void WinformsControlsTest_SplitterTest() { - var process = TestHelpers.StartProcess(GetPathToTestFromBin()); + Process process = TestHelpers.StartProcess(GetPathToTestFromBin()); TestHelpers.PressTabsOnProcess(process, 8); TestHelpers.PressEnterOnProcess(process); @@ -177,7 +177,7 @@ public void WinformsControlsTest_SplitterTest() [Fact] public void WinformsControlsTest_ComboBoxesTest() { - var process = TestHelpers.StartProcess(GetPathToTestFromBin()); + Process process = TestHelpers.StartProcess(GetPathToTestFromBin()); TestHelpers.PressTabsOnProcess(process, 9); TestHelpers.PressEnterOnProcess(process); @@ -192,7 +192,7 @@ public void WinformsControlsTest_ComboBoxesTest() [Fact] public void WinformsControlsTest_MDIParentTest() { - var process = TestHelpers.StartProcess(GetPathToTestFromBin()); + Process process = TestHelpers.StartProcess(GetPathToTestFromBin()); TestHelpers.PressTabsOnProcess(process, 10); TestHelpers.PressEnterOnProcess(process); @@ -207,7 +207,7 @@ public void WinformsControlsTest_MDIParentTest() [Fact] public void WinformsControlsTest_PropertyGridTest() { - var process = TestHelpers.StartProcess(GetPathToTestFromBin()); + Process process = TestHelpers.StartProcess(GetPathToTestFromBin()); TestHelpers.PressTabsOnProcess(process, 11); TestHelpers.PressEnterOnProcess(process); @@ -222,7 +222,7 @@ public void WinformsControlsTest_PropertyGridTest() [Fact] public void WinformsControlsTest_PropertyGrid_CollectionEditorTest() { - var process = TestHelpers.StartProcess(GetPathToTestFromBin()); + Process process = TestHelpers.StartProcess(GetPathToTestFromBin()); TestHelpers.PressTabsOnProcess(process, 11); TestHelpers.PressEnterOnProcess(process); @@ -259,7 +259,7 @@ public void WinformsControlsTest_PropertyGrid_CollectionEditorTest() [Fact] public void WinformsControlsTest_DateTimePickerTest() { - var process = TestHelpers.StartProcess(GetPathToTestFromBin()); + Process process = TestHelpers.StartProcess(GetPathToTestFromBin()); TestHelpers.PressTabsOnProcess(process, 13); TestHelpers.PressEnterOnProcess(process); @@ -274,7 +274,7 @@ public void WinformsControlsTest_DateTimePickerTest() [Fact] public void WinformsControlsTest_ThreadExceptionDialogTest() { - var process = TestHelpers.StartProcess(GetPathToTestFromBin()); + Process process = TestHelpers.StartProcess(GetPathToTestFromBin()); TestHelpers.PressTabsOnProcess(process, 15); TestHelpers.PressEnterOnProcess(process); diff --git a/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/ComboBoxAccessibleObjectTests.cs b/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/ComboBoxAccessibleObjectTests.cs index c550ff8e3db..c9f0dd69936 100644 --- a/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/ComboBoxAccessibleObjectTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/ComboBoxAccessibleObjectTests.cs @@ -55,7 +55,7 @@ public void ComboBoxAccessibleObject_ExpandCollapse_Set_CollapsedState(Accessibl [MemberData(nameof(ComboBoxAccessibleObject_TestData))] public void ComboBoxAccessibleObject_FragmentNavigate_FirstChild_NotNull(AccessibleObject accessibleObject) { - var firstChild = accessibleObject.FragmentNavigate(UnsafeNativeMethods.NavigateDirection.FirstChild); + UnsafeNativeMethods.IRawElementProviderFragment firstChild = accessibleObject.FragmentNavigate(UnsafeNativeMethods.NavigateDirection.FirstChild); Assert.NotNull(firstChild); } } diff --git a/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/DataGridViewAccessibleObjectTests.cs b/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/DataGridViewAccessibleObjectTests.cs index 024b531802c..0a2e2330864 100644 --- a/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/DataGridViewAccessibleObjectTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/DataGridViewAccessibleObjectTests.cs @@ -13,7 +13,7 @@ public void PropertyGridAccessibleObject_Ctor_Default() { DataGridView dataGridView = new DataGridView(); - var accessibleObject = dataGridView.AccessibilityObject; + AccessibleObject accessibleObject = dataGridView.AccessibilityObject; Assert.NotNull(accessibleObject); Assert.Equal(AccessibleRole.Table, accessibleObject.Role); } diff --git a/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/ToolStripAccessibleObjectTests.cs b/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/ToolStripAccessibleObjectTests.cs index fca637a5957..7d091d3c0f8 100644 --- a/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/ToolStripAccessibleObjectTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/ToolStripAccessibleObjectTests.cs @@ -29,7 +29,7 @@ public static IEnumerable ToolStripAccessibleObject_TestData() [MemberData(nameof(ToolStripAccessibleObject_TestData))] public void ToolStripAccessibleObject_FragmentNavigate_FirstChild_ThumbButton(AccessibleObject accessibleObject) { - var firstChild = accessibleObject.FragmentNavigate(UnsafeNativeMethods.NavigateDirection.FirstChild); + UnsafeNativeMethods.IRawElementProviderFragment firstChild = accessibleObject.FragmentNavigate(UnsafeNativeMethods.NavigateDirection.FirstChild); Assert.NotNull(firstChild); Assert.Equal(NativeConstants.UIA_ThumbControlTypeId, firstChild.GetPropertyValue(NativeConstants.UIA_ControlTypePropertyId)); } diff --git a/src/System.Windows.Forms/tests/UnitTests/BindingNavigatorTests.cs b/src/System.Windows.Forms/tests/UnitTests/BindingNavigatorTests.cs index cc1135a6934..57fdb79f8a7 100644 --- a/src/System.Windows.Forms/tests/UnitTests/BindingNavigatorTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/BindingNavigatorTests.cs @@ -43,7 +43,7 @@ public void BindingNavigator_ConstructorIContainer() mockContainer.Setup(x => x.Add(It.IsAny())).Verifiable(); // act & assert - var ex = Assert.Throws(() => new BindingNavigator(nullContainer)); + ArgumentNullException ex = Assert.Throws(() => new BindingNavigator(nullContainer)); Assert.Equal("container", ex.ParamName); var bn = new BindingNavigator(mockContainer.Object); @@ -100,7 +100,7 @@ public void BindingNavigator_ConstructorBool() for (var i = 0; i < items.Count; i++) { - var item = items[i]; + ToolStripItem item = items[i]; Assert.NotNull(item); Assert.Equal(itemNames[i], item.Name.Trim()); Assert.Equal(itemTexts[i], item.Text.Trim()); diff --git a/src/System.Windows.Forms/tests/UnitTests/ButtonTests.cs b/src/System.Windows.Forms/tests/UnitTests/ButtonTests.cs index 5b0d5058368..14d41aed61d 100644 --- a/src/System.Windows.Forms/tests/UnitTests/ButtonTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/ButtonTests.cs @@ -50,7 +50,7 @@ public void Button_AutoSizeModeGetSetInvalid(AutoSizeMode expected) var button = new Button(); // act & assert - var ex = Assert.Throws(() => button.AutoSizeMode = expected); + InvalidEnumArgumentException ex = Assert.Throws(() => button.AutoSizeMode = expected); Assert.Equal("value", ex.ParamName); } @@ -59,7 +59,7 @@ public void Button_CreateFlatAdapter() { var button = new Button(); - var adaptor = button.CreateFlatAdapter(); + ButtonInternal.ButtonBaseAdapter adaptor = button.CreateFlatAdapter(); Assert.NotNull(adaptor); } @@ -69,7 +69,7 @@ public void Button_CreatePopupAdapter() { var button = new Button(); - var adaptor = button.CreatePopupAdapter(); + ButtonInternal.ButtonBaseAdapter adaptor = button.CreatePopupAdapter(); Assert.NotNull(adaptor); } @@ -79,7 +79,7 @@ public void Button_CreateStandardAdapter() { var button = new Button(); - var adaptor = button.CreateStandardAdapter(); + ButtonInternal.ButtonBaseAdapter adaptor = button.CreateStandardAdapter(); Assert.NotNull(adaptor); } @@ -91,7 +91,7 @@ public void Button_CreateStandardAdapter() [MemberData(nameof(GetPreferredSizeCoreData))] public void Button_GetPreferredSizeCore(Button button, Size proposed, Size expected) { - var actual = button.GetPreferredSizeCore(proposed); + Size actual = button.GetPreferredSizeCore(proposed); Assert.Equal(expected, actual); } @@ -126,7 +126,7 @@ public void Button_DialogResultGetSetInvalid(DialogResult expected) var button = new Button(); // act & assert - var ex = Assert.Throws(() => button.DialogResult = expected); + InvalidEnumArgumentException ex = Assert.Throws(() => button.DialogResult = expected); Assert.Equal("value", ex.ParamName); } diff --git a/src/System.Windows.Forms/tests/UnitTests/CheckBoxTests.cs b/src/System.Windows.Forms/tests/UnitTests/CheckBoxTests.cs index e2ad8d91435..e4bc011b459 100644 --- a/src/System.Windows.Forms/tests/UnitTests/CheckBoxTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/CheckBoxTests.cs @@ -51,7 +51,7 @@ public void CheckBox_AppearanceGetSetInvalid(Appearance expected) { var box = new CheckBox(); - var ex = Assert.Throws(() => box.Appearance = expected); + InvalidEnumArgumentException ex = Assert.Throws(() => box.Appearance = expected); Assert.Equal("value", ex.ParamName); } @@ -103,7 +103,7 @@ public void CheckBox_ContentAlignmentGetSetInvalid(ContentAlignment expected) { var box = new CheckBox(); - var ex = Assert.Throws(() => box.CheckAlign = expected); + InvalidEnumArgumentException ex = Assert.Throws(() => box.CheckAlign = expected); Assert.Equal("value", ex.ParamName); } @@ -148,7 +148,7 @@ public void CheckBox_CheckStateGetSetInvalid(CheckState expected) { var box = new CheckBox(); - var ex = Assert.Throws(() => box.CheckState = expected); + InvalidEnumArgumentException ex = Assert.Throws(() => box.CheckState = expected); Assert.Equal("value", ex.ParamName); } @@ -174,7 +174,7 @@ public void CheckBox_CreateFlatAdapter() { var box = new CheckBox(); - var buttonBaseAdptr = box.CreateFlatAdapter(); + ButtonInternal.ButtonBaseAdapter buttonBaseAdptr = box.CreateFlatAdapter(); Assert.NotNull(buttonBaseAdptr); } @@ -184,7 +184,7 @@ public void CheckBox_CreatePopupAdapter() { var box = new CheckBox(); - var checkBoxPopupAdptr = box.CreatePopupAdapter(); + ButtonInternal.ButtonBaseAdapter checkBoxPopupAdptr = box.CreatePopupAdapter(); Assert.NotNull(checkBoxPopupAdptr); } @@ -194,7 +194,7 @@ public void CheckBox_CreateStandardAdapter() { var box = new CheckBox(); - var checkBoxSndAdptr = box.CreateStandardAdapter(); + ButtonInternal.ButtonBaseAdapter checkBoxSndAdptr = box.CreateStandardAdapter(); Assert.NotNull(checkBoxSndAdptr); } diff --git a/src/System.Windows.Forms/tests/UnitTests/CheckedListBoxTests.cs b/src/System.Windows.Forms/tests/UnitTests/CheckedListBoxTests.cs index 53119290825..00e7845f294 100644 --- a/src/System.Windows.Forms/tests/UnitTests/CheckedListBoxTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/CheckedListBoxTests.cs @@ -40,7 +40,7 @@ public void CheckedListBox_CheckedIndexCollectionNotNull() { var box = new CheckedListBox(); - var collection = box.CheckedIndices; + CheckedListBox.CheckedIndexCollection collection = box.CheckedIndices; Assert.NotNull(collection); } @@ -50,7 +50,7 @@ public void CheckedListBox_CheckedItemCollectionNotNull() { var box = new CheckedListBox(); - var collection = box.CheckedItems; + CheckedListBox.CheckedItemCollection collection = box.CheckedItems; Assert.NotNull(collection); } @@ -77,7 +77,7 @@ public void CheckedListBox_DrawModeReturnsNormalOnly() { var box = new CheckedListBox(); - var result = box.DrawMode; + DrawMode result = box.DrawMode; Assert.Equal(DrawMode.Normal, result); } @@ -101,7 +101,7 @@ public void CheckedListBox_SelectionModeGetSetInvalidFromEnum(SelectionMode expe { var box = new CheckedListBox(); - var ex = Assert.Throws(() => box.SelectionMode = expected); + ArgumentException ex = Assert.Throws(() => box.SelectionMode = expected); } /// @@ -116,7 +116,7 @@ public void CheckedListBox_CheckStateGetSetInvalid(SelectionMode expected) { var box = new CheckedListBox(); - var ex = Assert.Throws(() => box.SelectionMode = expected); + InvalidEnumArgumentException ex = Assert.Throws(() => box.SelectionMode = expected); Assert.Equal("value", ex.ParamName); } @@ -177,7 +177,7 @@ public void CheckedListBox_GetItemCheckStateOutOfRange(int index) { var box = new CheckedListBox(); - var ex = Assert.Throws(() => box.GetItemCheckState(index)); + ArgumentOutOfRangeException ex = Assert.Throws(() => box.GetItemCheckState(index)); Assert.Equal("index", ex.ParamName); } @@ -189,7 +189,7 @@ public void CheckedListBox_SetItemCheckStateOutOfRange(int index) { var box = new CheckedListBox(); - var ex = Assert.Throws(() => box.SetItemCheckState(index, CheckState.Checked)); + ArgumentOutOfRangeException ex = Assert.Throws(() => box.SetItemCheckState(index, CheckState.Checked)); Assert.Equal("index", ex.ParamName); } @@ -224,7 +224,7 @@ public void CheckedListBox_SetItemCheckStateInvalid(CheckState expected) var box = new CheckedListBox(); box.Items.Add(new CheckBox(), false); - var ex = Assert.Throws(() => box.SetItemCheckState(0, expected)); + InvalidEnumArgumentException ex = Assert.Throws(() => box.SetItemCheckState(0, expected)); Assert.Equal("value", ex.ParamName); } diff --git a/src/System.Windows.Forms/tests/UnitTests/ContextMenuStripTests.cs b/src/System.Windows.Forms/tests/UnitTests/ContextMenuStripTests.cs index dc80d4ea841..812e9df2156 100644 --- a/src/System.Windows.Forms/tests/UnitTests/ContextMenuStripTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/ContextMenuStripTests.cs @@ -26,7 +26,7 @@ public void ContextMenuStrip_ConstructorIContainer() mockContainer.Setup(x => x.Add(It.IsAny())).Verifiable(); // act & assert - var ex = Assert.Throws(() => new ContextMenuStrip(nullContainer)); + ArgumentNullException ex = Assert.Throws(() => new ContextMenuStrip(nullContainer)); Assert.Equal("container", ex.ParamName); var cms = new ContextMenuStrip(mockContainer.Object); diff --git a/src/System.Windows.Forms/tests/UnitTests/DomainUpDownTests.cs b/src/System.Windows.Forms/tests/UnitTests/DomainUpDownTests.cs index 6f91d1a11f3..7843df71b5b 100644 --- a/src/System.Windows.Forms/tests/UnitTests/DomainUpDownTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/DomainUpDownTests.cs @@ -11,7 +11,7 @@ public class DomainUpDownTests [Fact] public void DomainUpDown_Constructor() { - var underTest = GetNewDomainUpDown(); + DomainUpDown underTest = GetNewDomainUpDown(); Assert.NotNull(underTest); Assert.False(underTest.AllowDrop); @@ -25,7 +25,7 @@ public void DomainUpDown_Constructor() [InlineData(3, 3, "Cowman")] public void DomainUpDown_SelectedIndexGetSet(int indexToSet, int indexAfterSet, string value) { - var underTest = GetNewDomainUpDown(); + DomainUpDown underTest = GetNewDomainUpDown(); underTest.SelectedIndex = indexToSet; Assert.Equal(indexAfterSet, underTest.SelectedIndex); @@ -35,14 +35,14 @@ public void DomainUpDown_SelectedIndexGetSet(int indexToSet, int indexAfterSet, [Fact] public void DomainUpDown_SelectedIndex_ArgumentOutOfRangeException() { - var upDown = GetNewDomainUpDown(); + DomainUpDown upDown = GetNewDomainUpDown(); Assert.Throws(() => upDown.SelectedIndex = 3100); } [Fact] public void DomainUpDown_Sorted_SelectedIndexGetSet() { - var underTest = GetNewDomainUpDown(true); + DomainUpDown underTest = GetNewDomainUpDown(true); underTest.SelectedIndex = 3; Assert.Equal(3, underTest.SelectedIndex); @@ -65,7 +65,7 @@ public void DomainUpDown_Sorted_SelectedIndexGetSet() [InlineData("", 0, -1)] public void DomainUpDown_MatchIndex(string search, int start, int index) { - var underTest = GetNewDomainUpDown(); + DomainUpDown underTest = GetNewDomainUpDown(); var expected = index; var actual = underTest.MatchIndex(search, false, start); Assert.Equal(expected, actual); @@ -74,7 +74,7 @@ public void DomainUpDown_MatchIndex(string search, int start, int index) [Fact] public void DomainUpDown_MatchIndex_NullReferenceException() { - var underTest = GetNewDomainUpDown(); + DomainUpDown underTest = GetNewDomainUpDown(); Assert.Throws(() => underTest.MatchIndex(null, false, 0)); } @@ -85,7 +85,7 @@ public void DomainUpDown_MatchIndex_NullReferenceException() [InlineData(4, 3)] public void DomainUpDown_UpButton(int index, int newIndex) { - var underTest = GetNewDomainUpDown(); + DomainUpDown underTest = GetNewDomainUpDown(); underTest.SelectedIndex = index; underTest.UpButton(); var expected = newIndex; @@ -100,7 +100,7 @@ public void DomainUpDown_UpButton(int index, int newIndex) [InlineData(4, 4)] public void DomainUpDown_DownButton(int index, int newIndex) { - var underTest = GetNewDomainUpDown(); + DomainUpDown underTest = GetNewDomainUpDown(); underTest.SelectedIndex = index; underTest.DownButton(); var expected = newIndex; @@ -112,7 +112,7 @@ private DomainUpDown GetNewDomainUpDown(bool sorted = false) { var domainUpDown = new DomainUpDown(); domainUpDown.Sorted = sorted; - var items = domainUpDown.Items; + DomainUpDown.DomainUpDownItemCollection items = domainUpDown.Items; Assert.NotNull(items); items.Add("foo1"); items.Add("foo2"); diff --git a/src/System.Windows.Forms/tests/UnitTests/ErrorProviderTests.cs b/src/System.Windows.Forms/tests/UnitTests/ErrorProviderTests.cs index 0627649f073..f4bed163e9f 100644 --- a/src/System.Windows.Forms/tests/UnitTests/ErrorProviderTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/ErrorProviderTests.cs @@ -38,7 +38,7 @@ public void ErrorProvider_ConstructorIContainer() mockContainer.Setup(x => x.Add(It.IsAny())).Verifiable(); // act & assert - var ex = Assert.Throws(() => new ErrorProvider(nullContainer)); + ArgumentNullException ex = Assert.Throws(() => new ErrorProvider(nullContainer)); Assert.Equal("container", ex.ParamName); var ep = new ErrorProvider(mockContainer.Object); diff --git a/src/System.Windows.Forms/tests/UnitTests/NotifyIconTests.cs b/src/System.Windows.Forms/tests/UnitTests/NotifyIconTests.cs index 13163e698b7..8bfda391fb3 100644 --- a/src/System.Windows.Forms/tests/UnitTests/NotifyIconTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/NotifyIconTests.cs @@ -26,7 +26,7 @@ public void NotifyIcon_ConstructorIContainer() mockContainer.Setup(x => x.Add(It.IsAny())).Verifiable(); // act & assert - var ex = Assert.Throws(() => new NotifyIcon(nullContainer)); + ArgumentNullException ex = Assert.Throws(() => new NotifyIcon(nullContainer)); Assert.Equal("container", ex.ParamName); var icon = new NotifyIcon(mockContainer.Object); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Resources/ResXFileRefTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Resources/ResXFileRefTests.cs index aacf3f0ea97..5835ec27439 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Resources/ResXFileRefTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Resources/ResXFileRefTests.cs @@ -27,7 +27,7 @@ public void ResXFileRef_EncodingConstructor() { var fileName = "SomeFile"; var typeName = "SomeType"; - var encoding = Encoding.Default; + Encoding encoding = Encoding.Default; var fileRef = new ResXFileRef(fileName, typeName, encoding); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingContextTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingContextTests.cs index adeed9b1ff3..35b8ddf6367 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingContextTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingContextTests.cs @@ -640,7 +640,7 @@ public void BindingContext_Item_GetIListSourceDataSourceWithDataMemberReturningI mockIListSource .Setup(s => s.GetList()) .Returns(list); - var mockIList = mockIListSource.As(); + Mock mockIList = mockIListSource.As(); dataSource.Property = mockIList.Object; CurrencyManager manager = Assert.IsAssignableFrom(context[dataSource, "Property"]); @@ -681,7 +681,7 @@ public void BindingContext_Item_GetIListSourceDataSourceWithDataMemberReturningI mockIListSource .Setup(s => s.GetList()) .Returns((IList)null); - var mockIList = mockIListSource.As(); + Mock mockIList = mockIListSource.As(); dataSource.Property = mockIList.Object; Assert.Throws("dataSource", () => context[dataSource, "Property"]); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ComboBoxTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ComboBoxTests.cs index 82716c2d3c5..8001f79bfff 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ComboBoxTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ComboBoxTests.cs @@ -375,7 +375,7 @@ public void Font_SetWithHandler_CallsFontChanged() control.FontChanged += handler; // Set different. - var font1 = SystemFonts.MenuFont; + Font font1 = SystemFonts.MenuFont; control.Font = font1; Assert.Same(font1, control.Font); Assert.Equal(1, callCount); @@ -386,7 +386,7 @@ public void Font_SetWithHandler_CallsFontChanged() Assert.Equal(1, callCount); // Set different. - var font2 = SystemFonts.DialogFont; + Font font2 = SystemFonts.DialogFont; control.Font = font2; Assert.Same(font2, control.Font); Assert.Equal(2, callCount); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlTests.cs index 7f3b82a30be..5e5ac3f297b 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlTests.cs @@ -279,7 +279,7 @@ public void Control_GetChildControlsInTabOrder() }; cont.Controls.AddRange(unordered); - var tabOrderedChildren = cont.GetChildControlsInTabOrder(false); + Control[] tabOrderedChildren = cont.GetChildControlsInTabOrder(false); Assert.Equal(ordered, tabOrderedChildren); } @@ -302,7 +302,7 @@ public void Control_GetChildControlsInTabOrderHandlesOnly() }; cont.Controls.AddRange(unordered); - var tabOrderedChildrenWithhandlesOnly = cont.GetChildControlsInTabOrder(true); + Control[] tabOrderedChildrenWithhandlesOnly = cont.GetChildControlsInTabOrder(true); Assert.Empty(tabOrderedChildrenWithhandlesOnly); } @@ -508,7 +508,7 @@ public void Control_GetContainerControl() { var cont = new Control(); - var ret = cont.GetContainerControl(); + IContainerControl ret = cont.GetContainerControl(); Assert.Null(ret); } @@ -616,7 +616,7 @@ public void Control_AccessibleRoleInvalid(AccessibleRole expected) { var cont = new Control(); - var ex = Assert.Throws(() => cont.AccessibleRole = expected); + InvalidEnumArgumentException ex = Assert.Throws(() => cont.AccessibleRole = expected); Assert.Equal("value", ex.ParamName); } @@ -721,7 +721,7 @@ public void Control_BackgroundImageLayoutGetSetInvalid(ImageLayout expected) { var cont = new Control(); - var ex = Assert.Throws(() => cont.BackgroundImageLayout = expected); + InvalidEnumArgumentException ex = Assert.Throws(() => cont.BackgroundImageLayout = expected); Assert.Equal("value", ex.ParamName); } @@ -783,7 +783,7 @@ public void Control_ApplySizeConstraints(int expected) var cont = new Control(); var expectedSize = new Size(expected, expected); - var actualSize = cont.ApplySizeConstraints(expected, expected); + Size actualSize = cont.ApplySizeConstraints(expected, expected); Assert.Equal(expectedSize, actualSize); } @@ -793,7 +793,7 @@ public void Control_ApplySizeConstraints(int expected) public void Control_ApplySizeConstraintsSize_Invoke_ReturnsExpected(Size expectedSize) { var control = new Control(); - var actualSize = control.ApplySizeConstraints(expectedSize); + Size actualSize = control.ApplySizeConstraints(expectedSize); Assert.Equal(expectedSize, actualSize); } @@ -814,7 +814,7 @@ public void Control_ApplyBoundsConstraints(int expected) var cont = new Control(); var expectedBounds = new Rectangle(expected, expected, expected, expected); - var actualBounds = cont.ApplyBoundsConstraints(expected, expected, expected, expected); + Rectangle actualBounds = cont.ApplyBoundsConstraints(expected, expected, expected, expected); Assert.Equal(expectedBounds, actualBounds); } @@ -1597,7 +1597,7 @@ public void Control_GetChildAtPointNull(GetChildAtPointSkip skip) { var cont = new Control(); - var ret = cont.GetChildAtPoint(new Point(5, 5), skip); + Control ret = cont.GetChildAtPoint(new Point(5, 5), skip); Assert.Null(ret); } @@ -1615,7 +1615,7 @@ public void Control_GetChildAtPointInvalid(GetChildAtPointSkip skip) var cont = new Control(); // act & assert - var ex = Assert.Throws(() => cont.GetChildAtPoint(new Point(5, 5), skip)); + InvalidEnumArgumentException ex = Assert.Throws(() => cont.GetChildAtPoint(new Point(5, 5), skip)); Assert.Equal("skipValue", ex.ParamName); } @@ -1626,7 +1626,7 @@ public void Control_GetHandle() { var cont = new Control(); - var intptr = cont.Handle; + IntPtr intptr = cont.Handle; Assert.NotEqual(IntPtr.Zero, intptr); } @@ -1636,7 +1636,7 @@ public void Control_GetHandleInternalShouldBeZero() { var cont = new Control(); - var intptr = cont.HandleInternal; + IntPtr intptr = cont.HandleInternal; Assert.Equal(IntPtr.Zero, intptr); Assert.False(cont.IsHandleCreated); @@ -1655,7 +1655,7 @@ public void Control_DoDragDrop(DragDropEffects expected) var cont = new Control(); var mock = new Mock(MockBehavior.Strict); - var ret = cont.DoDragDrop(mock.Object, expected); + DragDropEffects ret = cont.DoDragDrop(mock.Object, expected); Assert.Equal(DragDropEffects.None, ret); } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridColumnStyleTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridColumnStyleTests.cs index b36975aa1ef..bd9c9c58b08 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridColumnStyleTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridColumnStyleTests.cs @@ -211,7 +211,7 @@ public void HeaderText_Set_GetReturnsExpected(string value) [CommonMemberData(nameof(CommonTestHelper.GetStringWithNullTheoryData))] public void HeaderText_SetWithPropertyDescriptor_GetReturnsExpected(string value) { - var property = TypeDescriptor.GetProperties(typeof(DataClass))[0]; + PropertyDescriptor property = TypeDescriptor.GetProperties(typeof(DataClass))[0]; var style = new SubDataGridColumnStyle(property) { HeaderText = value @@ -681,7 +681,7 @@ public void DataGridColumnStyle_BeginUpdate_SeveralTimes_DoesNotCallInvalidate() [Fact] public void DataGridColumnStyle_CheckValidDataSource_HasPropertyDescriptor_Nop() { - var property = TypeDescriptor.GetProperties(typeof(DataClass))[0]; + PropertyDescriptor property = TypeDescriptor.GetProperties(typeof(DataClass))[0]; var style = new SubDataGridColumnStyle(property); var context = new BindingContext(); var dataSource = new List { 1, 2, 3 }; diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewCellTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewCellTests.cs index 64f4d10bfec..07824689bfd 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewCellTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewCellTests.cs @@ -193,7 +193,7 @@ public static IEnumerable EditedFormattedValue_Get_TestData() yield return new object[] { dataGridView.Rows[0].Cells[0], string.Empty }; yield return new object[] { dataGridView.Columns[0].HeaderCell, string.Empty }; - var cell = dataGridView.Rows[1].Cells[0]; + DataGridViewCell cell = dataGridView.Rows[1].Cells[0]; cell.Value = "value"; yield return new object[] { cell, "value" }; } @@ -425,7 +425,7 @@ public static IEnumerable FormattedValue_Get_TestData() yield return new object[] { dataGridView.Rows[0].Cells[0], string.Empty }; yield return new object[] { dataGridView.Columns[0].HeaderCell, string.Empty }; - var cell = dataGridView.Rows[1].Cells[0]; + DataGridViewCell cell = dataGridView.Rows[1].Cells[0]; cell.Value = "value"; yield return new object[] { cell, "value" }; } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewRowTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewRowTests.cs index 3aa6815b1fe..366bf1216a4 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewRowTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewRowTests.cs @@ -1105,8 +1105,8 @@ DataGridViewRow CreateRow(int index, DataGridViewCellStyle rowDefaultCellStyle, return row; } - var font1 = SystemFonts.DefaultFont; - var font2 = SystemFonts.MenuFont; + Font font1 = SystemFonts.DefaultFont; + Font font2 = SystemFonts.MenuFont; var provider1 = new NumberFormatInfo(); var provider2 = new NumberFormatInfo(); @@ -2500,7 +2500,7 @@ public void DataGridViewRow_Clone_WithDataGridView_Success() var dataGridView = new DataGridView { ColumnCount = 1 }; dataGridView.Rows.Add(new DataGridViewRow()); - var source = dataGridView.Rows[0]; + DataGridViewRow source = dataGridView.Rows[0]; source.ContextMenuStrip = menu; source.DefaultCellStyle = style; source.DefaultHeaderCellType = typeof(DataGridViewRowHeaderCell); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListBoxTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListBoxTests.cs index 05ef2cbcfb6..185cadf17bb 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListBoxTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListBoxTests.cs @@ -376,7 +376,7 @@ public void Font_SetWithHandler_CallsFontChanged() control.FontChanged += handler; // Set different. - var font1 = SystemFonts.MenuFont; + Font font1 = SystemFonts.MenuFont; control.Font = font1; Assert.Same(font1, control.Font); Assert.Equal(1, callCount); @@ -387,7 +387,7 @@ public void Font_SetWithHandler_CallsFontChanged() Assert.Equal(1, callCount); // Set different. - var font2 = SystemFonts.DialogFont; + Font font2 = SystemFonts.DialogFont; control.Font = font2; Assert.Same(font2, control.Font); Assert.Equal(2, callCount); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/MessageTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/MessageTests.cs index d6e9c616bbf..1fdbcecf069 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/MessageTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/MessageTests.cs @@ -199,7 +199,7 @@ public void Message_GetLParam_Invoke_ReturnsExpected() { LParam = ptr }; - var lparam = Assert.IsType(message.GetLParam(typeof(TestStruct))); + TestStruct lparam = Assert.IsType(message.GetLParam(typeof(TestStruct))); Assert.Equal(1, lparam._field1); Assert.Equal(2, lparam._field2); } diff --git a/src/System.Windows.Forms/tests/UnitTests/ToolTipTests.cs b/src/System.Windows.Forms/tests/UnitTests/ToolTipTests.cs index 42fe2f49991..ed64daefc68 100644 --- a/src/System.Windows.Forms/tests/UnitTests/ToolTipTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/ToolTipTests.cs @@ -26,7 +26,7 @@ public void ToolTip_ConstructorIContainer() mockContainer.Setup(x => x.Add(It.IsAny())).Verifiable(); // act & assert - var ex = Assert.Throws(() => new ToolTip(nullContainer)); + ArgumentNullException ex = Assert.Throws(() => new ToolTip(nullContainer)); Assert.Equal("cont", ex.ParamName); var tt = new ToolTip(mockContainer.Object); diff --git a/src/System.Windows.Forms/tests/UnitTests/VisualStyleRendererTests.cs b/src/System.Windows.Forms/tests/UnitTests/VisualStyleRendererTests.cs index 166ae32a04b..7a687e3c214 100644 --- a/src/System.Windows.Forms/tests/UnitTests/VisualStyleRendererTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/VisualStyleRendererTests.cs @@ -15,7 +15,7 @@ public void VisualStyleRenderer_GetMargins() var renderer = new VisualStyleRenderer(VisualStyleElement.Button.PushButton.Normal); using (var form = new System.Windows.Forms.Form()) - using (var graphics = form.CreateGraphics()) + using (Drawing.Graphics graphics = form.CreateGraphics()) { // GetMargins should not throw an exception. // See https://github.com/dotnet/winforms/issues/526. From 8d8794458589e518a3e52c4d03c749740a7dc5cc Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Fri, 24 May 2019 11:44:25 -0700 Subject: [PATCH 12/27] remove all instances of IDE0016 warning - null check can be simplified --- src/Common/src/UnsafeNativeMethods.cs | 4 +--- .../Windows/Forms/Design/AnchorEditor.cs | 4 +--- .../src/System/Resources/ResXDataNode.cs | 7 ++----- .../src/System/Windows/Forms/AxHost.cs | 4 +--- .../src/System/Windows/Forms/ComboBox.cs | 7 +------ .../src/System/Windows/Forms/Control.cs | 12 ++--------- .../System/Windows/Forms/DataGridToolTip.cs | 5 +---- .../DataGridViewCellPaintingEventArgs.cs | 18 +++-------------- .../Windows/Forms/DataGridViewComboBoxCell.cs | 7 +------ .../DataGridViewRowPostPaintEventArgs.cs | 19 +++--------------- .../Forms/DataGridViewRowPrePaintEventArgs.cs | 19 +++--------------- .../Forms/Design/ComponentEditorForm.cs | 5 +---- .../src/System/Windows/Forms/DropSource.cs | 4 +--- .../src/System/Windows/Forms/ErrorProvider.cs | 4 +--- .../Forms/InputLanguageChangedEventArgs.cs | 7 +------ .../Forms/InputLanguageChangingEventArgs.cs | 7 +------ .../src/System/Windows/Forms/LinkLabel.cs | 4 +--- .../System/Windows/Forms/ListBindingHelper.cs | 8 +------- .../src/System/Windows/Forms/ListViewItem.cs | 20 +++---------------- .../src/System/Windows/Forms/RichTextBox.cs | 5 +---- .../src/System/Windows/Forms/TabControl.cs | 6 +----- .../src/System/Windows/Forms/ToolStrip.cs | 8 +------- .../Windows/Forms/ToolStripControlHost.cs | 6 +----- .../System/Windows/Forms/ToolStripDropDown.cs | 18 +++-------------- .../src/System/Windows/Forms/ToolStripItem.cs | 13 ++---------- .../Windows/Forms/ToolStripItemCollection.cs | 7 +------ .../Windows/Forms/WebBrowserSiteBase.cs | 6 +----- 27 files changed, 40 insertions(+), 194 deletions(-) diff --git a/src/Common/src/UnsafeNativeMethods.cs b/src/Common/src/UnsafeNativeMethods.cs index fb86df877b9..51073536556 100644 --- a/src/Common/src/UnsafeNativeMethods.cs +++ b/src/Common/src/UnsafeNativeMethods.cs @@ -6603,9 +6603,7 @@ public class ComStreamFromDataStream : IStream [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public ComStreamFromDataStream(Stream dataStream) { - if (dataStream == null) - throw new ArgumentNullException(nameof(dataStream)); - this.dataStream = dataStream; + this.dataStream = dataStream ?? throw new ArgumentNullException(nameof(dataStream)); } private void ActualizeVirtualPosition() diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/AnchorEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/AnchorEditor.cs index c01edac5065..8115b65bc09 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/AnchorEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/AnchorEditor.cs @@ -239,9 +239,7 @@ private class SpringControl : Control public SpringControl(AnchorUI picker) { - if (picker == null) - throw new ArgumentException(); - this.picker = picker; + this.picker = picker ?? throw new ArgumentException(); TabStop = true; } diff --git a/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs b/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs index f930c67f4d4..14af9fb37ae 100644 --- a/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs +++ b/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs @@ -146,12 +146,9 @@ public ResXDataNode(string name, ResXFileRef fileRef, Func typeNam { throw new ArgumentNullException(nameof(name)); } - if (fileRef == null) - { - throw new ArgumentNullException(nameof(fileRef)); - } + this.name = name; - this.fileRef = fileRef; + this.fileRef = fileRef ?? throw new ArgumentNullException(nameof(fileRef)); this.typeNameConverter = typeNameConverter; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs index 296da3100c7..197f31cf5c9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs @@ -4014,9 +4014,7 @@ private class OleInterfaces internal OleInterfaces(AxHost host) { - if (host == null) - throw new ArgumentNullException(nameof(host)); - this.host = host; + this.host = host ?? throw new ArgumentNullException(nameof(host)); } private void Dispose(bool disposing) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs index c11ad9b7582..194b2485d04 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs @@ -4679,17 +4679,12 @@ public void Remove(object value) internal void SetItemInternal(int index, object value) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - if (index < 0 || index >= InnerList.Count) { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - InnerList[index] = value; + InnerList[index] = value ?? throw new ArgumentNullException(nameof(value)); // If the native control has been created, and the display text of the new list item object // is different to the current text in the native list item, recreate the native list item... 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 89b531f0463..bd6b2b1c813 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs @@ -20249,12 +20249,8 @@ public ControlAccessibleObject(Control ownerControl) { Debug.Assert(ownerControl != null, "Cannot construct a ControlAccessibleObject with a null ownerControl"); - if (ownerControl == null) - { - throw new ArgumentNullException(nameof(ownerControl)); - } - this.ownerControl = ownerControl; + this.ownerControl = ownerControl ?? throw new ArgumentNullException(nameof(ownerControl)); IntPtr handle = ownerControl.Handle; @@ -20265,14 +20261,10 @@ internal ControlAccessibleObject(Control ownerControl, int accObjId) { Debug.Assert(ownerControl != null, "Cannot construct a ControlAccessibleObject with a null ownerControl"); - if (ownerControl == null) - { - throw new ArgumentNullException(nameof(ownerControl)); - } AccessibleObjectId = accObjId; // ...must set this *before* setting the Handle property - this.ownerControl = ownerControl; + this.ownerControl = ownerControl ?? throw new ArgumentNullException(nameof(ownerControl)); IntPtr handle = ownerControl.Handle; Handle = handle; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs index 6f99e2ad308..91fc2adea50 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs @@ -56,9 +56,6 @@ public void CreateToolTipHandle() public void AddToolTip(string toolTipString, IntPtr toolTipId, Rectangle iconBounds) { Debug.Assert(tipWindow != null && tipWindow.Handle != IntPtr.Zero, "the tipWindow was not initialized, bailing out"); - - if (toolTipString == null) - throw new ArgumentNullException(nameof(toolTipString)); if (iconBounds.IsEmpty) throw new ArgumentNullException(nameof(iconBounds), SR.DataGridToolTipEmptyIcon); @@ -66,7 +63,7 @@ public void AddToolTip(string toolTipString, IntPtr toolTipId, Rectangle iconBou toolInfo.cbSize = Marshal.SizeOf(toolInfo); toolInfo.hwnd = dataGrid.Handle; toolInfo.uId = toolTipId; - toolInfo.lpszText = toolTipString; + toolInfo.lpszText = toolTipString ?? throw new ArgumentNullException(nameof(toolTipString)); toolInfo.rect = NativeMethods.RECT.FromXYWH(iconBounds.X, iconBounds.Y, iconBounds.Width, iconBounds.Height); toolInfo.uFlags = NativeMethods.TTF_SUBCLASS; UnsafeNativeMethods.SendMessage(new HandleRef(tipWindow, tipWindow.Handle), NativeMethods.TTM_ADDTOOL, 0, toolInfo); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellPaintingEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellPaintingEventArgs.cs index 25a844c024d..fedb36026cf 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellPaintingEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellPaintingEventArgs.cs @@ -26,25 +26,13 @@ public DataGridViewCellPaintingEventArgs(DataGridView dataGridView, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { - if (dataGridView == null) - { - throw new ArgumentNullException(nameof(dataGridView)); - } - if (graphics == null) - { - throw new ArgumentNullException(nameof(graphics)); - } - if (cellStyle == null) - { - throw new ArgumentNullException(nameof(cellStyle)); - } if ((paintParts & ~DataGridViewPaintParts.All) != 0) { throw new ArgumentException(string.Format(SR.DataGridView_InvalidDataGridViewPaintPartsCombination, nameof(paintParts)), nameof(paintParts)); } - _dataGridView = dataGridView; - Graphics = graphics; + _dataGridView = dataGridView ?? throw new ArgumentNullException(nameof(dataGridView)); + Graphics = graphics ?? throw new ArgumentNullException(nameof(graphics)); ClipBounds = clipBounds; CellBounds = cellBounds; RowIndex = rowIndex; @@ -53,7 +41,7 @@ public DataGridViewCellPaintingEventArgs(DataGridView dataGridView, Value = value; FormattedValue = formattedValue; ErrorText = errorText; - CellStyle = cellStyle; + CellStyle = cellStyle ?? throw new ArgumentNullException(nameof(cellStyle)); AdvancedBorderStyle = advancedBorderStyle; PaintParts = paintParts; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs index 1af61a2f59d..37c1900b654 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs @@ -2904,17 +2904,12 @@ public virtual object this[int index] //this.owner.CheckNoSharedCell(); owner.CheckNoDataSource(); - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - if (index < 0 || index >= InnerArray.Count) { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - InnerArray[index] = value; + InnerArray[index] = value ?? throw new ArgumentNullException(nameof(value)); owner.OnItemsCollectionChanged(); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowPostPaintEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowPostPaintEventArgs.cs index 44425ca66e7..6d1567a7e0d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowPostPaintEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowPostPaintEventArgs.cs @@ -23,27 +23,14 @@ public DataGridViewRowPostPaintEventArgs(DataGridView dataGridView, bool isFirstDisplayedRow, bool isLastVisibleRow) { - if (dataGridView == null) - { - throw new ArgumentNullException(nameof(dataGridView)); - } - if (graphics == null) - { - throw new ArgumentNullException(nameof(graphics)); - } - if (inheritedRowStyle == null) - { - throw new ArgumentNullException(nameof(inheritedRowStyle)); - } - - _dataGridView = dataGridView; - Graphics = graphics; + _dataGridView = dataGridView ?? throw new ArgumentNullException(nameof(dataGridView)); + Graphics = graphics ?? throw new ArgumentNullException(nameof(graphics)); ClipBounds = clipBounds; RowBounds = rowBounds; RowIndex = rowIndex; State = rowState; ErrorText = errorText; - InheritedRowStyle = inheritedRowStyle; + InheritedRowStyle = inheritedRowStyle ?? throw new ArgumentNullException(nameof(inheritedRowStyle)); IsFirstDisplayedRow = isFirstDisplayedRow; IsLastVisibleRow = isLastVisibleRow; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowPrePaintEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowPrePaintEventArgs.cs index 97fd666e904..09f53795d10 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowPrePaintEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowPrePaintEventArgs.cs @@ -24,27 +24,14 @@ public DataGridViewRowPrePaintEventArgs(DataGridView dataGridView, bool isFirstDisplayedRow, bool isLastVisibleRow) { - if (dataGridView == null) - { - throw new ArgumentNullException(nameof(dataGridView)); - } - if (graphics == null) - { - throw new ArgumentNullException(nameof(graphics)); - } - if (inheritedRowStyle == null) - { - throw new ArgumentNullException(nameof(inheritedRowStyle)); - } - - _dataGridView = dataGridView; - Graphics = graphics; + _dataGridView = dataGridView ?? throw new ArgumentNullException(nameof(dataGridView)); + Graphics = graphics ?? throw new ArgumentNullException(nameof(graphics)); ClipBounds = clipBounds; RowBounds = rowBounds; RowIndex = rowIndex; State = rowState; ErrorText = errorText; - InheritedRowStyle = inheritedRowStyle; + InheritedRowStyle = inheritedRowStyle ?? throw new ArgumentNullException(nameof(inheritedRowStyle)); IsFirstDisplayedRow = isFirstDisplayedRow; IsLastVisibleRow = isLastVisibleRow; _paintParts = DataGridViewPaintParts.All; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs index f783325f763..55b94c77ad7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs @@ -554,10 +554,7 @@ internal ComponentEditorPageSite(Control parent, Type pageClass, IComponent comp isActive = false; isDirty = false; - if (form == null) - throw new ArgumentNullException(nameof(form)); - - this.form = form; + this.form = form ?? throw new ArgumentNullException(nameof(form)); try { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DropSource.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DropSource.cs index 9f5a9534f3a..a03288546ec 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DropSource.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DropSource.cs @@ -18,9 +18,7 @@ internal class DropSource : UnsafeNativeMethods.IOleDropSource public DropSource(ISupportOleDropSource peer) { - if (peer == null) - throw new ArgumentNullException(nameof(peer)); - this.peer = peer; + this.peer = peer ?? throw new ArgumentNullException(nameof(peer)); } public int OleQueryContinueDrag(int fEscapePressed, int grfKeyState) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs index e61cf5a0551..04c1f490ac8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs @@ -646,9 +646,7 @@ public Icon Icon } set { - if (value == null) - throw new ArgumentNullException(nameof(value)); - icon = value; + icon = value ?? throw new ArgumentNullException(nameof(value)); DisposeRegion(); ErrorWindow[] array = new ErrorWindow[windows.Values.Count]; windows.Values.CopyTo(array, 0); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/InputLanguageChangedEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/InputLanguageChangedEventArgs.cs index 5871fbb8e9d..e89740fa9e5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/InputLanguageChangedEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/InputLanguageChangedEventArgs.cs @@ -28,12 +28,7 @@ public InputLanguageChangedEventArgs(CultureInfo culture, byte charSet) /// public InputLanguageChangedEventArgs(InputLanguage inputLanguage, byte charSet) { - if (inputLanguage == null) - { - throw new ArgumentNullException(nameof(inputLanguage)); - } - - InputLanguage = inputLanguage; + InputLanguage = inputLanguage ?? throw new ArgumentNullException(nameof(inputLanguage)); Culture = inputLanguage.Culture; CharSet = charSet; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/InputLanguageChangingEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/InputLanguageChangingEventArgs.cs index 22c3cb5c4d4..c1fe04d24de 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/InputLanguageChangingEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/InputLanguageChangingEventArgs.cs @@ -29,12 +29,7 @@ public InputLanguageChangingEventArgs(CultureInfo culture, bool sysCharSet) /// public InputLanguageChangingEventArgs(InputLanguage inputLanguage, bool sysCharSet) { - if (inputLanguage == null) - { - throw new ArgumentNullException(nameof(inputLanguage)); - } - - InputLanguage = inputLanguage; + InputLanguage = inputLanguage ?? throw new ArgumentNullException(nameof(inputLanguage)); Culture = inputLanguage.Culture; SysCharSet = sysCharSet; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs index 5c50cda4d1e..761e91400f6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs @@ -2211,9 +2211,7 @@ public class LinkCollection : IList public LinkCollection(LinkLabel owner) { - if (owner == null) - throw new ArgumentNullException(nameof(owner)); - this.owner = owner; + this.owner = owner ?? throw new ArgumentNullException(nameof(owner)); } public virtual Link this[int index] diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingHelper.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingHelper.cs index 18c674fc02f..8e1a67335e7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingHelper.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingHelper.cs @@ -204,16 +204,10 @@ public static PropertyDescriptorCollection GetListItemProperties(object dataSour PropertyDescriptorCollection dsProps = ListBindingHelper.GetListItemProperties(dataSource); PropertyDescriptor dmProp = dsProps.Find(dataMember, true); - // Error: Property not found - data member is invalid - if (dmProp == null) - { - throw new System.ArgumentException(string.Format(SR.DataSourceDataMemberPropNotFound, dataMember)); - } - // Add the data member property to the list accessors int len = (listAccessors == null) ? 1 : (listAccessors.Length + 1); PropertyDescriptor[] listAccessors2 = new PropertyDescriptor[len]; - listAccessors2[0] = dmProp; + listAccessors2[0] = dmProp ?? throw new System.ArgumentException(string.Format(SR.DataSourceDataMemberPropNotFound, dataMember)); for (int i = 1; i < len; ++i) { listAccessors2[i] = listAccessors[i - 1]; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItem.cs index 4861bbc995e..41b1ea9768f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItem.cs @@ -129,13 +129,8 @@ public ListViewItem(string[] items, int imageIndex, Color foreColor, Color backC public ListViewItem(ListViewSubItem[] subItems, int imageIndex) : this() { - if (subItems == null) - { - throw new ArgumentNullException(nameof(subItems)); - } - ImageIndexer.Index = imageIndex; - this.subItems = subItems; + this.subItems = subItems ?? throw new ArgumentNullException(nameof(subItems)); SubItemCount = subItems.Length; // Update the owner of these subitems @@ -215,13 +210,8 @@ public ListViewItem(string[] items, string imageKey, Color foreColor, Color back public ListViewItem(ListViewSubItem[] subItems, string imageKey) : this() { - if (subItems == null) - { - throw new ArgumentNullException(nameof(subItems)); - } - ImageIndexer.Key = imageKey; - this.subItems = subItems; + this.subItems = subItems ?? throw new ArgumentNullException(nameof(subItems)); SubItemCount = subItems.Length; // Update the owner of these subitems @@ -1607,12 +1597,8 @@ public ListViewSubItem this[int index] { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - _owner.subItems[index] = value; + _owner.subItems[index] = value ?? throw new ArgumentNullException(nameof(value)); _owner.UpdateSubItems(index); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs index 05cb6f393fa..117184c659b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs @@ -1980,9 +1980,6 @@ public int Find(string str, int start, int end, RichTextBoxFinds options) { int textLen = TextLength; - - if (str == null) - throw new ArgumentNullException(nameof(str)); if (start < 0 || start > textLen) throw new ArgumentOutOfRangeException(nameof(start), start, string.Format(SR.InvalidBoundArgument, nameof(start), start, 0, textLen)); if (end < -1) @@ -1994,7 +1991,7 @@ public int Find(string str, int start, int end, RichTextBoxFinds options) // set up the default values for the FINDTEXT structure, that is // the given string and the whole range of the text stream - ft.lpstrText = str; + ft.lpstrText = str ?? throw new ArgumentNullException(nameof(str)); if (end == -1) { end = textLen; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs index 9067ef29fc9..1c71bd15f46 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs @@ -2278,11 +2278,7 @@ public class TabPageCollection : IList [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public TabPageCollection(TabControl owner) { - if (owner == null) - { - throw new ArgumentNullException(nameof(owner)); - } - this.owner = owner; + this.owner = owner ?? throw new ArgumentNullException(nameof(owner)); } public virtual TabPage this[int index] diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs index 501179250f6..299d6f2fb8d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs @@ -5911,13 +5911,7 @@ internal sealed class ToolStripSplitStackDragDropHandler : IDropTarget, ISupport public ToolStripSplitStackDragDropHandler(ToolStrip owner) { - - if (owner == null) - { - // - throw new ArgumentNullException(nameof(owner)); - } - this.owner = owner; + this.owner = owner ?? throw new ArgumentNullException(nameof(owner)); } public void OnDragEnter(DragEventArgs e) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs index ecee499e113..9ee3c69a6d2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs @@ -39,11 +39,7 @@ public class ToolStripControlHost : ToolStripItem public ToolStripControlHost(Control c) { - if (c == null) - { - throw new ArgumentNullException(nameof(c), SR.ControlCannotBeNull); - } - control = c; + control = c ?? throw new ArgumentNullException(nameof(c), SR.ControlCannotBeNull); SyncControlParent(); c.Visible = true; SetBounds(c.Bounds); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs index d73389c177a..f4f19603b2f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs @@ -2165,11 +2165,7 @@ private void UpdateLayered() /// show relative to control coordinates public void Show(Control control, Point position) { - if (control == null) - { - throw new ArgumentNullException(nameof(control)); - } - SourceControlInternal = control; + SourceControlInternal = control ?? throw new ArgumentNullException(nameof(control)); // When we have no owner item and we're set to RTL.Inherit, translate the coordinates // so that the menu looks like it's swooping from the other side if (OwnerItem == null && control.RightToLeft == RightToLeft.Yes) @@ -2186,11 +2182,7 @@ public void Show(Control control, Point position) public void Show(Control control, Point position, ToolStripDropDownDirection direction) { - if (control == null) - { - throw new ArgumentNullException(nameof(control)); - } - SourceControlInternal = control; + SourceControlInternal = control ?? throw new ArgumentNullException(nameof(control)); displayLocation = CalculateDropDownLocation(control.PointToScreen(position), direction).Location; Location = displayLocation; ShowCore(); @@ -2199,11 +2191,7 @@ public void Show(Control control, Point position, ToolStripDropDownDirection dir /// show relative to control coordinates public void Show(Control control, int x, int y) { - if (control == null) - { - throw new ArgumentNullException(nameof(control)); - } - SourceControlInternal = control; + SourceControlInternal = control ?? throw new ArgumentNullException(nameof(control)); Show(control, new Point(x, y)); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs index 15fa42b5f4a..4d20ff48670 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs @@ -4298,12 +4298,7 @@ public class ToolStripItemAccessibleObject : AccessibleObject public ToolStripItemAccessibleObject(ToolStripItem ownerItem) { - if (ownerItem == null) - { - throw new ArgumentNullException(nameof(ownerItem)); - } - - this.ownerItem = ownerItem; + this.ownerItem = ownerItem ?? throw new ArgumentNullException(nameof(ownerItem)); } public override string DefaultAction @@ -4870,11 +4865,7 @@ internal class ToolStripItemInternalLayout public ToolStripItemInternalLayout(ToolStripItem ownerItem) { - if (ownerItem == null) - { - throw new ArgumentNullException(nameof(ownerItem)); - } - this.ownerItem = ownerItem; + this.ownerItem = ownerItem ?? throw new ArgumentNullException(nameof(ownerItem)); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemCollection.cs index 05e8934e7ef..cfc096d59d2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemCollection.cs @@ -48,12 +48,7 @@ internal ToolStripItemCollection(ToolStrip owner, bool itemsCollection, bool isR [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public ToolStripItemCollection(ToolStrip owner, ToolStripItem[] value) { - if (owner == null) - { - throw new ArgumentNullException(nameof(owner)); - } - - this.owner = owner; + this.owner = owner ?? throw new ArgumentNullException(nameof(owner)); AddRange(value); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs index 6f866d294b8..e1e79c4af71 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs @@ -34,11 +34,7 @@ public class WebBrowserSiteBase // internal WebBrowserSiteBase(WebBrowserBase h) { - if (h == null) - { - throw new ArgumentNullException(nameof(h)); - } - host = h; + host = h ?? throw new ArgumentNullException(nameof(h)); } /// From a269d83602e5209e35747a44d529b00926d8511d Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Fri, 24 May 2019 12:01:07 -0700 Subject: [PATCH 13/27] remove all instances of IDE0017 warning - object init can be simplified --- src/Common/src/NativeMethods.cs | 32 +- src/Common/src/UnsafeNativeMethods.cs | 13 +- .../src/PlatformDetection.Windows.cs | 18 +- .../src/System/Drawing/Design/ColorEditor.cs | 37 +- .../src/System/Drawing/Design/FontEditor.cs | 10 +- .../Windows/Forms/Design/FolderNameEditor.cs | 20 +- .../Forms/Design/ShortcutKeysEditor.cs | 6 +- .../System/Drawing/Design/ImageEditorTests.cs | 18 +- .../ComponentModel/Design/DesignSurface.cs | 6 +- .../ComponentModel/Design/DesignerHost.cs | 30 +- .../CodeDomComponentSerializationService.cs | 8 +- .../Serialization/CodeDomSerializerBase.cs | 16 +- .../ComponentCodeDomSerializer.cs | 14 +- .../ComponentTypeCodeDomSerializer.cs | 8 +- .../ContainerCodeDomSerializer.cs | 7 +- .../DesignerSerializationManager.cs | 12 +- .../PropertyMemberCodeDomSerializer.cs | 13 +- .../Forms/Design/Behavior/BehaviorService.cs | 24 +- .../ToolStripItemCustomMenuItemCollection.cs | 22 +- .../Design/DesignerActionServiceTests.cs | 24 +- .../System/Drawing/Design/ToolboxItemTests.cs | 30 +- .../System/Resources/ResXResourceWriter.cs | 6 +- .../src/System/Windows/Forms/Application.cs | 32 +- .../src/System/Windows/Forms/AxHost.cs | 98 +++-- .../Forms/ButtonInternal/ButtonBaseAdapter.cs | 132 +++--- .../COM2Interop/COM2TypeInfoProcessor.cs | 12 +- .../System/Windows/Forms/ContainerControl.cs | 6 +- .../src/System/Windows/Forms/Control.cs | 98 +++-- .../src/System/Windows/Forms/ControlPaint.cs | 189 ++++++--- .../src/System/Windows/Forms/DataGrid.cs | 90 ++-- .../Windows/Forms/DataGridBoolColumn.cs | 6 +- .../src/System/Windows/Forms/DataGridState.cs | 24 +- .../src/System/Windows/Forms/DataGridTable.cs | 6 +- .../Windows/Forms/DataGridTextBoxColumn.cs | 12 +- .../System/Windows/Forms/DataGridToolTip.cs | 16 +- .../src/System/Windows/Forms/DataGridView.cs | 112 ++--- .../Forms/DataGridViewAdvancedBorderStyle.cs | 14 +- .../Windows/Forms/DataGridViewButtonColumn.cs | 6 +- .../System/Windows/Forms/DataGridViewCell.cs | 7 +- .../Forms/DataGridViewCheckBoxColumn.cs | 6 +- .../Forms/DataGridViewColumnCollection.cs | 8 +- .../Windows/Forms/DataGridViewImageColumn.cs | 6 +- .../Windows/Forms/DataGridViewMethods.cs | 18 +- .../Windows/Forms/DataGridViewToolTip.cs | 14 +- .../src/System/Windows/Forms/DataObject.cs | 36 +- .../System/Windows/Forms/DateTimePicker.cs | 26 +- .../Forms/Design/ComponentEditorForm.cs | 19 +- .../src/System/Windows/Forms/DropTarget.cs | 24 +- .../src/System/Windows/Forms/ErrorProvider.cs | 36 +- .../Windows/Forms/FolderBrowserDialog.cs | 20 +- .../src/System/Windows/Forms/Form.cs | 36 +- .../src/System/Windows/Forms/Help.cs | 16 +- .../src/System/Windows/Forms/HtmlDocument.cs | 6 +- .../src/System/Windows/Forms/HtmlElement.cs | 6 +- .../src/System/Windows/Forms/ImageList.cs | 12 +- .../Forms/Layout/DockAndAnchorLayout.cs | 12 +- .../Windows/Forms/Layout/TableLayout.cs | 16 +- .../src/System/Windows/Forms/LinkLabel.cs | 10 +- .../src/System/Windows/Forms/ListView.cs | 356 ++++++++++------ .../Windows/Forms/ListViewInsertionMark.cs | 16 +- .../src/System/Windows/Forms/ListViewItem.cs | 22 +- .../src/System/Windows/Forms/MDIClient.cs | 6 +- .../src/System/Windows/Forms/MaskedTextBox.cs | 6 +- .../Windows/Forms/MdiWindowListStrip.cs | 30 +- .../src/System/Windows/Forms/MenuItem.cs | 56 ++- .../src/System/Windows/Forms/Message.cs | 14 +- .../src/System/Windows/Forms/MonthCalendar.cs | 48 ++- .../src/System/Windows/Forms/NativeWindow.cs | 6 +- .../src/System/Windows/Forms/NotifyIcon.cs | 8 +- .../Windows/Forms/Printing/PageSetupDialog.cs | 12 +- .../Forms/Printing/PrintPreviewControl.cs | 34 +- .../Forms/Printing/PrintPreviewDialog.cs | 6 +- .../src/System/Windows/Forms/ProgressBar.cs | 6 +- .../src/System/Windows/Forms/PropertyGrid.cs | 32 +- .../Forms/PropertyGridInternal/DocComment.cs | 16 +- .../Forms/PropertyGridInternal/GridEntry.cs | 14 +- .../Forms/PropertyGridInternal/GridToolTip.cs | 20 +- .../Forms/PropertyGridInternal/HotCommands.cs | 12 +- .../PropertyGridInternal/PropertyGridView.cs | 60 ++- .../src/System/Windows/Forms/RichTextBox.cs | 130 +++--- .../src/System/Windows/Forms/ScrollBar.cs | 20 +- .../System/Windows/Forms/ScrollProperties.cs | 18 +- .../System/Windows/Forms/ScrollableControl.cs | 6 +- .../src/System/Windows/Forms/StatusBar.cs | 34 +- .../System/Windows/Forms/SystemInformation.cs | 18 +- .../src/System/Windows/Forms/TabControl.cs | 70 ++-- .../src/System/Windows/Forms/TabPage.cs | 13 +- .../src/System/Windows/Forms/Timer.cs | 20 +- .../src/System/Windows/Forms/ToolBar.cs | 14 +- .../src/System/Windows/Forms/ToolBarButton.cs | 31 +- .../src/System/Windows/Forms/ToolStrip.cs | 30 +- .../System/Windows/Forms/ToolStripButton.cs | 6 +- .../System/Windows/Forms/ToolStripComboBox.cs | 8 +- .../Windows/Forms/ToolStripContainer.cs | 6 +- .../Windows/Forms/ToolStripDropDownMenu.cs | 42 +- .../Forms/ToolStripDropTargetManager.cs | 6 +- .../Forms/ToolStripHighContrastRenderer.cs | 10 +- .../System/Windows/Forms/ToolStripManager.cs | 32 +- .../System/Windows/Forms/ToolStripMenuItem.cs | 34 +- .../Windows/Forms/ToolStripProgressBar.cs | 6 +- .../Windows/Forms/ToolStripScrollButton.cs | 8 +- .../System/Windows/Forms/ToolStripTextBox.cs | 8 +- .../src/System/Windows/Forms/ToolTip.cs | 70 ++-- .../src/System/Windows/Forms/TrackBar.cs | 6 +- .../src/System/Windows/Forms/TreeNode.cs | 69 +-- .../Windows/Forms/TreeNodeCollection.cs | 76 ++-- .../src/System/Windows/Forms/TreeView.cs | 65 +-- .../src/System/Windows/Forms/UpDownBase.cs | 8 +- .../src/System/Windows/Forms/WebBrowser.cs | 6 +- .../System/Windows/Forms/WebBrowserBase.cs | 50 ++- .../Windows/Forms/WebBrowserSiteBase.cs | 12 +- .../src/misc/GDI/DeviceContexts.cs | 6 +- .../src/misc/GDI/WindowsFont.cs | 8 +- .../src/misc/GDI/WindowsGraphics.cs | 24 +- .../src/misc/GDI/WindowsPen.cs | 11 +- .../TestHelpers.cs | 13 +- .../WinformsControlsTest/Buttons.cs | 46 +- .../WinformsControlsTest/ListViewTest.cs | 58 +-- .../WinformsControlsTest/MDIParent.cs | 14 +- .../DataGridViewCellAccessibleObjectTests.cs | 11 +- .../DataGridViewRowsAccessibleObjectTests.cs | 9 +- .../tests/UnitTests/ButtonTests.cs | 64 +-- .../tests/UnitTests/CheckBoxTests.cs | 44 +- .../tests/UnitTests/CheckedListBoxTests.cs | 35 +- .../tests/UnitTests/DomainUpDownTests.cs | 6 +- .../tests/UnitTests/MenuItemTests.cs | 6 +- .../Windows/Forms/BindingContextTests.cs | 18 +- .../Forms/ColumnHeaderCollectionTests.cs | 18 +- .../System/Windows/Forms/ComboBoxTests.cs | 6 +- .../System/Windows/Forms/ControlTests.cs | 395 +++++++++++------- .../System/Windows/Forms/FormTests.cs | 24 +- .../Forms/ListViewGroupCollectionTests.cs | 24 +- .../Forms/ListViewSubItemCollectionTests.cs | 18 +- .../System/Windows/Forms/PanelTests.cs | 18 +- .../Windows/Forms/ScrollableControlTests.cs | 12 +- .../Windows/Forms/ToolStripItemTests.cs | 93 +++-- .../tests/UnitTests/TextBoxTests.cs | 26 +- .../tests/UnitTests/ThreadContextTests.cs | 30 +- 138 files changed, 2642 insertions(+), 1668 deletions(-) diff --git a/src/Common/src/NativeMethods.cs b/src/Common/src/NativeMethods.cs index 122ee1b2f9e..7055cd7755b 100644 --- a/src/Common/src/NativeMethods.cs +++ b/src/Common/src/NativeMethods.cs @@ -2817,21 +2817,25 @@ public class PICTDESC public static PICTDESC CreateBitmapPICTDESC(IntPtr hbitmap, IntPtr hpal) { - PICTDESC pictdesc = new PICTDESC(); - pictdesc.cbSizeOfStruct = 16; - pictdesc.picType = Ole.PICTYPE_BITMAP; - pictdesc.union1 = hbitmap; - pictdesc.union2 = (int)(((long)hpal) & 0xffffffff); - pictdesc.union3 = (int)(((long)hpal) >> 32); + PICTDESC pictdesc = new PICTDESC + { + cbSizeOfStruct = 16, + picType = Ole.PICTYPE_BITMAP, + union1 = hbitmap, + union2 = (int)(((long)hpal) & 0xffffffff), + union3 = (int)(((long)hpal) >> 32) + }; return pictdesc; } public static PICTDESC CreateIconPICTDESC(IntPtr hicon) { - PICTDESC pictdesc = new PICTDESC(); - pictdesc.cbSizeOfStruct = 12; - pictdesc.picType = Ole.PICTYPE_ICON; - pictdesc.union1 = hicon; + PICTDESC pictdesc = new PICTDESC + { + cbSizeOfStruct = 12, + picType = Ole.PICTYPE_ICON, + union1 = hicon + }; return pictdesc; } } @@ -5360,9 +5364,11 @@ public tagTYPEDESC Get_tdescAlias() public tagIDLDESC Get_idldescType() { - tagIDLDESC id = new tagIDLDESC(); - id.dwReserved = idldescType_dwReserved; - id.wIDLFlags = idldescType_wIDLFlags; + tagIDLDESC id = new tagIDLDESC + { + dwReserved = idldescType_dwReserved, + wIDLFlags = idldescType_wIDLFlags + }; return id; } } diff --git a/src/Common/src/UnsafeNativeMethods.cs b/src/Common/src/UnsafeNativeMethods.cs index 51073536556..734d80040f1 100644 --- a/src/Common/src/UnsafeNativeMethods.cs +++ b/src/Common/src/UnsafeNativeMethods.cs @@ -8004,12 +8004,13 @@ public static bool CreateActivationContext(string dllPath, int nativeResourceMan if (!contextCreationSucceeded && OSFeature.Feature.IsPresent(OSFeature.Themes)) { - enableThemingActivationContext = new ACTCTX(); - - enableThemingActivationContext.cbSize = Marshal.SizeOf(); - enableThemingActivationContext.lpSource = dllPath; - enableThemingActivationContext.lpResourceName = (IntPtr)nativeResourceManifestID; - enableThemingActivationContext.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID; + enableThemingActivationContext = new ACTCTX + { + cbSize = Marshal.SizeOf(), + lpSource = dllPath, + lpResourceName = (IntPtr)nativeResourceManifestID, + dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID + }; hActCtx = CreateActCtx(ref enableThemingActivationContext); contextCreationSucceeded = (hActCtx != new IntPtr(-1)); diff --git a/src/Common/tests/InternalUtilitiesForTests/src/PlatformDetection.Windows.cs b/src/Common/tests/InternalUtilitiesForTests/src/PlatformDetection.Windows.cs index 18c36fe3642..8e2a2955c15 100644 --- a/src/Common/tests/InternalUtilitiesForTests/src/PlatformDetection.Windows.cs +++ b/src/Common/tests/InternalUtilitiesForTests/src/PlatformDetection.Windows.cs @@ -221,16 +221,20 @@ private static int GetWindowsProductType() private static unsafe int GetWindowsMinorVersion() { - var osvi = new RTL_OSVERSIONINFOEX(); - osvi.dwOSVersionInfoSize = (uint)sizeof(RTL_OSVERSIONINFOEX); + var osvi = new RTL_OSVERSIONINFOEX + { + dwOSVersionInfoSize = (uint)sizeof(RTL_OSVERSIONINFOEX) + }; Assert.Equal(0, RtlGetVersion(ref osvi)); return (int)osvi.dwMinorVersion; } private static unsafe int GetWindowsBuildNumber() { - var osvi = new RTL_OSVERSIONINFOEX(); - osvi.dwOSVersionInfoSize = (uint)sizeof(RTL_OSVERSIONINFOEX); + var osvi = new RTL_OSVERSIONINFOEX + { + dwOSVersionInfoSize = (uint)sizeof(RTL_OSVERSIONINFOEX) + }; Assert.Equal(0, RtlGetVersion(ref osvi)); return (int)osvi.dwBuildNumber; } @@ -284,8 +288,10 @@ private unsafe struct RTL_OSVERSIONINFOEX private static unsafe int GetWindowsVersion() { - var osvi = new RTL_OSVERSIONINFOEX(); - osvi.dwOSVersionInfoSize = (uint)sizeof(RTL_OSVERSIONINFOEX); + var osvi = new RTL_OSVERSIONINFOEX + { + dwOSVersionInfoSize = (uint)sizeof(RTL_OSVERSIONINFOEX) + }; Assert.Equal(0, RtlGetVersion(ref osvi)); return (int)osvi.dwMajorVersion; } diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/ColorEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/ColorEditor.cs index c0786e57d2c..57ad53b9736 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/ColorEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/ColorEditor.cs @@ -464,12 +464,13 @@ protected override void OnPaint(PaintEventArgs pe) { g.FillRectangle(brush, ClientRectangle); } - Rectangle rect = new Rectangle(); - - rect.Width = cellSizeX; - rect.Height = cellSizeY; - rect.X = marginX; - rect.Y = marginY; + Rectangle rect = new Rectangle + { + Width = cellSizeX, + Height = cellSizeY, + X = marginX, + Y = marginY + }; bool drawSelected = false; for (int y = 0; y < CELLS_DOWN; y++) @@ -810,22 +811,26 @@ private void InitializeComponent() tabControl.Dock = DockStyle.Fill; tabControl.Resize += new EventHandler(OnTabControlResize); - lbSystem = new ColorEditorListBox(); - lbSystem.DrawMode = DrawMode.OwnerDrawFixed; - lbSystem.BorderStyle = BorderStyle.FixedSingle; - lbSystem.IntegralHeight = false; - lbSystem.Sorted = false; + lbSystem = new ColorEditorListBox + { + DrawMode = DrawMode.OwnerDrawFixed, + BorderStyle = BorderStyle.FixedSingle, + IntegralHeight = false, + Sorted = false + }; lbSystem.Click += new EventHandler(OnListClick); lbSystem.DrawItem += new DrawItemEventHandler(this.OnListDrawItem); lbSystem.KeyDown += new KeyEventHandler(this.OnListKeyDown); lbSystem.Dock = DockStyle.Fill; lbSystem.FontChanged += new EventHandler(OnFontChanged); - lbCommon = new ColorEditorListBox(); - lbCommon.DrawMode = DrawMode.OwnerDrawFixed; - lbCommon.BorderStyle = BorderStyle.FixedSingle; - lbCommon.IntegralHeight = false; - lbCommon.Sorted = false; + lbCommon = new ColorEditorListBox + { + DrawMode = DrawMode.OwnerDrawFixed, + BorderStyle = BorderStyle.FixedSingle, + IntegralHeight = false, + Sorted = false + }; lbCommon.Click += new EventHandler(OnListClick); lbCommon.DrawItem += new DrawItemEventHandler(this.OnListDrawItem); lbCommon.KeyDown += new KeyEventHandler(this.OnListKeyDown); diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/FontEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/FontEditor.cs index 434f0a683c6..323cfec9109 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/FontEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/FontEditor.cs @@ -30,10 +30,12 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide { if (_fontDialog == null) { - _fontDialog = new FontDialog(); - _fontDialog.ShowApply = false; - _fontDialog.ShowColor = false; - _fontDialog.AllowVerticalFonts = false; + _fontDialog = new FontDialog + { + ShowApply = false, + ShowColor = false, + AllowVerticalFonts = false + }; } if (value is Font fontValue) diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/FolderNameEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/FolderNameEditor.cs index 6eea2b82e73..16fe52fbcce 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/FolderNameEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/FolderNameEditor.cs @@ -117,15 +117,17 @@ public unsafe DialogResult ShowDialog(IWin32Window owner) { fixed (char* pDisplayName = displayName) { - var bi = new Interop.Shell32.BROWSEINFO(); - bi.pidlRoot = listHandle; - bi.hwndOwner = hWndOwner; - bi.pszDisplayName = pDisplayName; - bi.lpszTitle = _descriptionText; - bi.ulFlags = mergedOptions; - bi.lpfn = null; - bi.lParam = IntPtr.Zero; - bi.iImage = 0; + var bi = new Interop.Shell32.BROWSEINFO + { + pidlRoot = listHandle, + hwndOwner = hWndOwner, + pszDisplayName = pDisplayName, + lpszTitle = _descriptionText, + ulFlags = mergedOptions, + lpfn = null, + lParam = IntPtr.Zero, + iImage = 0 + }; // Show the dialog. using (CoTaskMemSafeHandle browseHandle = Interop.Shell32.SHBrowseForFolderW(ref bi)) diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/ShortcutKeysEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/ShortcutKeysEditor.cs index 92af91f1db0..9a2eea28611 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/ShortcutKeysEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/ShortcutKeysEditor.cs @@ -32,8 +32,10 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide { if (shortcutKeysUI == null) { - shortcutKeysUI = new ShortcutKeysUI(this); - shortcutKeysUI.BackColor = SystemColors.Control; + shortcutKeysUI = new ShortcutKeysUI(this) + { + BackColor = SystemColors.Control + }; } shortcutKeysUI.Start(edSvc, value); diff --git a/src/System.Windows.Forms.Design.Editors/tests/UnitTests/System/Drawing/Design/ImageEditorTests.cs b/src/System.Windows.Forms.Design.Editors/tests/UnitTests/System/Drawing/Design/ImageEditorTests.cs index de4e0afa768..df69ac59f16 100644 --- a/src/System.Windows.Forms.Design.Editors/tests/UnitTests/System/Drawing/Design/ImageEditorTests.cs +++ b/src/System.Windows.Forms.Design.Editors/tests/UnitTests/System/Drawing/Design/ImageEditorTests.cs @@ -35,8 +35,10 @@ public void ImageEditor_CreateExtensionsString_Invoke_ReturnsExpected(string[] e [Fact] public void ImageEditor_CreateFilterEntry_Invoke_CallsGetExtensionsOnce() { - var editor = new CustomGetImageExtendersEditor(); - editor.GetImageExtendersResult = new Type[] { typeof(PublicImageEditor), typeof(PrivateImageEditor) }; + var editor = new CustomGetImageExtendersEditor + { + GetImageExtendersResult = new Type[] { typeof(PublicImageEditor), typeof(PrivateImageEditor) } + }; Assert.Equal("CustomGetImageExtendersEditor(*.PublicImageEditor,*.PrivateImageEditor)|*.PublicImageEditor;*.PrivateImageEditor", SubImageEditor.CreateFilterEntry(editor)); Assert.Equal(1, editor.GetImageExtendersCallCount); } @@ -92,8 +94,10 @@ public void ImageEditor_GetExtensions_InvokeDefault_ReturnsExpected() [Fact] public void ImageEditor_GetExtensions_InvokeCustom_CallsGetImageExtendersOnce() { - var editor = new CustomGetImageExtendersEditor(); - editor.GetImageExtendersResult = new Type[] { typeof(PublicImageEditor), typeof(PrivateImageEditor), typeof(ImageEditor), typeof(NullExtensionsImageEditor) }; + var editor = new CustomGetImageExtendersEditor + { + GetImageExtendersResult = new Type[] { typeof(PublicImageEditor), typeof(PrivateImageEditor), typeof(ImageEditor), typeof(NullExtensionsImageEditor) } + }; Assert.Equal(new string[] { "PublicImageEditor", "PrivateImageEditor" }, editor.GetExtensions()); Assert.Equal(1, editor.GetImageExtendersCallCount); } @@ -101,8 +105,10 @@ public void ImageEditor_GetExtensions_InvokeCustom_CallsGetImageExtendersOnce() [Fact] public void ImageEditor_GetExtensions_InvokeInvalid_ReturnsExpected() { - var editor = new CustomGetImageExtendersEditor(); - editor.GetImageExtendersResult = new Type[] { typeof(object), null }; + var editor = new CustomGetImageExtendersEditor + { + GetImageExtendersResult = new Type[] { typeof(object), null } + }; Assert.Empty(editor.GetExtensions()); Assert.Equal(1, editor.GetImageExtendersCallCount); } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignSurface.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignSurface.cs index 85af854f6de..73db427695b 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignSurface.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignSurface.cs @@ -196,8 +196,10 @@ public object View } // We are out of luck here. Throw. - ex = new NotSupportedException(SR.DesignSurfaceNoSupportedTechnology); - ex.HelpLink = SR.DesignSurfaceNoSupportedTechnology; + ex = new NotSupportedException(SR.DesignSurfaceNoSupportedTechnology) + { + HelpLink = SR.DesignSurfaceNoSupportedTechnology + }; throw ex; } } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerHost.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerHost.cs index fb2d15a87b0..ae39d5a0fa7 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerHost.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerHost.cs @@ -192,8 +192,10 @@ internal bool AddToContainerPreProcess(IComponent component, string name, IConta { if (string.Equals(component.GetType().FullName, _rootComponentClassName, StringComparison.OrdinalIgnoreCase)) { - Exception ex = new Exception(string.Format(SR.DesignerHostCyclicAdd, component.GetType().FullName, _rootComponentClassName)); - ex.HelpLink = SR.DesignerHostCyclicAdd; + Exception ex = new Exception(string.Format(SR.DesignerHostCyclicAdd, component.GetType().FullName, _rootComponentClassName)) + { + HelpLink = SR.DesignerHostCyclicAdd + }; throw ex; } } @@ -297,8 +299,10 @@ internal void BeginLoad(DesignerLoader loader) { if (_loader != null && _loader != loader) { - Exception ex = new InvalidOperationException(SR.DesignerHostLoaderSpecified); - ex.HelpLink = SR.DesignerHostLoaderSpecified; + Exception ex = new InvalidOperationException(SR.DesignerHostLoaderSpecified) + { + HelpLink = SR.DesignerHostLoaderSpecified + }; throw ex; } @@ -1128,8 +1132,10 @@ void IDesignerHost.DestroyComponent(IComponent component) InheritanceAttribute ia = (InheritanceAttribute)TypeDescriptor.GetAttributes(component)[typeof(InheritanceAttribute)]; if (ia != null && ia.InheritanceLevel != InheritanceLevel.NotInherited) { - Exception ex = new InvalidOperationException(string.Format(SR.DesignerHostCantDestroyInheritedComponent, name)); - ex.HelpLink = SR.DesignerHostCantDestroyInheritedComponent; + Exception ex = new InvalidOperationException(string.Format(SR.DesignerHostCantDestroyInheritedComponent, name)) + { + HelpLink = SR.DesignerHostCantDestroyInheritedComponent + }; throw ex; } @@ -1202,8 +1208,10 @@ void IDesignerLoaderHost.EndLoad(string rootClassName, bool successful, ICollect if (successful && _rootComponent == null) { ArrayList errorList = new ArrayList(); - InvalidOperationException ex = new InvalidOperationException(SR.DesignerHostNoBaseClass); - ex.HelpLink = SR.DesignerHostNoBaseClass; + InvalidOperationException ex = new InvalidOperationException(SR.DesignerHostNoBaseClass) + { + HelpLink = SR.DesignerHostNoBaseClass + }; errorList.Add(ex); errorCollection = errorList; successful = false; @@ -1853,8 +1861,10 @@ string ISite.Name // allow renames that are just case changes of the current name. if (namedComponent != null && validateName) { - Exception ex = new Exception(string.Format(SR.DesignerHostDuplicateName, value)); - ex.HelpLink = SR.DesignerHostDuplicateName; + Exception ex = new Exception(string.Format(SR.DesignerHostDuplicateName, value)) + { + HelpLink = SR.DesignerHostDuplicateName + }; throw ex; } } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomComponentSerializationService.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomComponentSerializationService.cs index 8a4aa96b78d..0f16abd11e3 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomComponentSerializationService.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomComponentSerializationService.cs @@ -272,9 +272,11 @@ internal void AddMember(object value, MemberDescriptor member, bool absolute) ObjectData data = (ObjectData)_objects[value]; if (data == null) { - data = new ObjectData(); - data._name = GetObjectName(value); - data._value = value; + data = new ObjectData + { + _name = GetObjectName(value), + _value = value + }; _objects[value] = data; _objectNames.Add(data._name); diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs index 2f86f08be41..bcbdfd242a3 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs @@ -750,9 +750,11 @@ private void DeserializeAssignStatement(IDesignerSerializationManager manager, C else { //lets try it as a property: - CodePropertyReferenceExpression propRef = new CodePropertyReferenceExpression(); - propRef.TargetObject = fieldReferenceEx.TargetObject; - propRef.PropertyName = fieldReferenceEx.FieldName; + CodePropertyReferenceExpression propRef = new CodePropertyReferenceExpression + { + TargetObject = fieldReferenceEx.TargetObject, + PropertyName = fieldReferenceEx.FieldName + }; if (!DeserializePropertyAssignStatement(manager, statement, propRef, false)) { TraceError("Object {0} does not have a field {1}", lhs.GetType().Name, fieldReferenceEx.FieldName); @@ -1043,9 +1045,11 @@ protected object DeserializeExpression(IDesignerSerializationManager manager, st else { //lets try it as a property: - CodePropertyReferenceExpression propRef = new CodePropertyReferenceExpression(); - propRef.TargetObject = fieldReferenceEx.TargetObject; - propRef.PropertyName = fieldReferenceEx.FieldName; + CodePropertyReferenceExpression propRef = new CodePropertyReferenceExpression + { + TargetObject = fieldReferenceEx.TargetObject, + PropertyName = fieldReferenceEx.FieldName + }; result = DeserializePropertyReferenceExpression(manager, propRef, false); if (result == fieldReferenceEx) diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentCodeDomSerializer.cs index e13d1ce5061..3c5509ff229 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentCodeDomSerializer.cs @@ -568,9 +568,10 @@ private void SerializeLoadComponentSettings(IDesignerSerializationManager manage CodeTypeReference type = new CodeTypeReference(typeof(IPersistComponentSettings)); CodeCastExpression castExp = new CodeCastExpression(type, valueExpression); CodeMethodReferenceExpression method = new CodeMethodReferenceExpression(castExp, "LoadComponentSettings"); - CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression(); - - methodInvoke.Method = method; + CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression + { + Method = method + }; CodeExpressionStatement statement = new CodeExpressionStatement(methodInvoke); statement.UserData["statement-ordering"] = "end"; @@ -588,9 +589,10 @@ private void SerializeSupportInitialize(IDesignerSerializationManager manager, C CodeTypeReference type = new CodeTypeReference(typeof(ISupportInitialize)); CodeCastExpression castExp = new CodeCastExpression(type, valueExpression); CodeMethodReferenceExpression method = new CodeMethodReferenceExpression(castExp, methodName); - CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression(); - - methodInvoke.Method = method; + CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression + { + Method = method + }; CodeExpressionStatement statement = new CodeExpressionStatement(methodInvoke); diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentTypeCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentTypeCodeDomSerializer.cs index ce40db3203b..e0b0d37361c 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentTypeCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentTypeCodeDomSerializer.cs @@ -58,9 +58,11 @@ protected override CodeMemberMethod GetInitializeMethod(IDesignerSerializationMa if (method == null) { - method = new CodeMemberMethod(); - method.Name = _initMethodName; - method.Attributes = MemberAttributes.Private; + method = new CodeMemberMethod + { + Name = _initMethodName, + Attributes = MemberAttributes.Private + }; typeDecl.UserData[_initMethodKey] = method; // Now create a ctor that calls this method. diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ContainerCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ContainerCodeDomSerializer.cs index 529bb56fffc..22b01e909e4 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ContainerCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ContainerCodeDomSerializer.cs @@ -73,9 +73,10 @@ public override object Serialize(IDesignerSerializationManager manager, object v if (typeDecl != null && rootCxt != null) { - CodeMemberField field = new CodeMemberField(typeof(IContainer), _containerName); - - field.Attributes = MemberAttributes.Private; + CodeMemberField field = new CodeMemberField(typeof(IContainer), _containerName) + { + Attributes = MemberAttributes.Private + }; typeDecl.Members.Add(field); lhs = new CodeFieldReferenceExpression(rootCxt.Expression, _containerName); } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs index 203966b347b..26eda5960c1 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs @@ -346,8 +346,10 @@ protected virtual object CreateInstance(Type type, ICollection arguments, string } } - Exception ex = new SerializationException(string.Format(SR.SerializationManagerNoMatchingCtor, type.FullName, argTypes.ToString())); - ex.HelpLink = SR.SerializationManagerNoMatchingCtor; + Exception ex = new SerializationException(string.Format(SR.SerializationManagerNoMatchingCtor, type.FullName, argTypes.ToString())) + { + HelpLink = SR.SerializationManagerNoMatchingCtor + }; throw ex; } @@ -715,8 +717,10 @@ object IDesignerSerializationManager.CreateInstance(Type type, ICollection argum { if (instancesByName != null && instancesByName.ContainsKey(name)) { - Exception ex = new SerializationException(string.Format(SR.SerializationManagerDuplicateComponentDecl, name)); - ex.HelpLink = SR.SerializationManagerDuplicateComponentDecl; + Exception ex = new SerializationException(string.Format(SR.SerializationManagerDuplicateComponentDecl, name)) + { + HelpLink = SR.SerializationManagerDuplicateComponentDecl + }; throw ex; } } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PropertyMemberCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PropertyMemberCodeDomSerializer.cs index 33d86f58fc4..76ab55d673c 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PropertyMemberCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PropertyMemberCodeDomSerializer.cs @@ -220,8 +220,10 @@ private void SerializeContentProperty(IDesignerSerializationManager manager, obj if (extender != null && extended != null) { CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression(extender, "Get" + property.Name); - CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression(); - methodInvoke.Method = methodRef; + CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression + { + Method = methodRef + }; methodInvoke.Parameters.Add(extended); propertyRef = methodInvoke; } @@ -342,9 +344,10 @@ private void SerializeExtenderProperty(IDesignerSerializationManager manager, ob if (serializedPropertyValue != null) { - CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression(); - - methodInvoke.Method = methodRef; + CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression + { + Method = methodRef + }; methodInvoke.Parameters.Add(extended); methodInvoke.Parameters.Add(serializedPropertyValue); statements.Add(methodInvoke); diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs index 163c02ad571..2e56712a889 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs @@ -351,9 +351,11 @@ public Point ControlToAdornerWindow(Control c) return Point.Empty; } - NativeMethods.POINT pt = new NativeMethods.POINT(); - pt.x = c.Left; - pt.y = c.Top; + NativeMethods.POINT pt = new NativeMethods.POINT + { + x = c.Left, + y = c.Top + }; NativeMethods.MapWindowPoints(c.Parent.Handle, _adornerWindow.Handle, pt, 1); if (c.Parent.IsMirrored) { @@ -367,9 +369,11 @@ public Point ControlToAdornerWindow(Control c) /// public Point MapAdornerWindowPoint(IntPtr handle, Point pt) { - NativeMethods.POINT nativePoint = new NativeMethods.POINT(); - nativePoint.x = pt.X; - nativePoint.y = pt.Y; + NativeMethods.POINT nativePoint = new NativeMethods.POINT + { + x = pt.X, + y = pt.Y + }; NativeMethods.MapWindowPoints(handle, _adornerWindow.Handle, nativePoint, 1); return new Point(nativePoint.x, nativePoint.y); } @@ -568,9 +572,11 @@ public void PushCaptureBehavior(Behavior behavior) /// public Point ScreenToAdornerWindow(Point p) { - NativeMethods.POINT offset = new NativeMethods.POINT(); - offset.x = p.X; - offset.y = p.Y; + NativeMethods.POINT offset = new NativeMethods.POINT + { + x = p.X, + y = p.Y + }; NativeMethods.MapWindowPoints(IntPtr.Zero, _adornerWindow.Handle, offset, 1); return new Point(offset.x, offset.y); } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs index dc039bdd236..ab0c2c68a29 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs @@ -92,8 +92,10 @@ private ToolStripMenuItem CreatePropertyBasedItem(string text, string propertyNa /// private ToolStripMenuItem CreateEnumValueItem(string propertyName, string name, object value) { - ToolStripMenuItem item = new ToolStripMenuItem(name); - item.Tag = new EnumValueDescription(propertyName, value); + ToolStripMenuItem item = new ToolStripMenuItem(name) + { + Tag = new EnumValueDescription(propertyName, value) + }; item.Click += new EventHandler(OnEnumValueChanged); return item; } @@ -116,10 +118,12 @@ private void PopulateList() ToolStripItem selectedItem = currentItem; if (!(selectedItem is ToolStripControlHost) && !(selectedItem is ToolStripSeparator)) { - imageToolStripMenuItem = new ToolStripMenuItem(); - imageToolStripMenuItem.Text = SR.ToolStripItemContextMenuSetImage; - imageToolStripMenuItem.Image = new Bitmap(typeof(ToolStripMenuItem), "image.bmp"); - imageToolStripMenuItem.ImageTransparentColor = Color.Magenta; + imageToolStripMenuItem = new ToolStripMenuItem + { + Text = SR.ToolStripItemContextMenuSetImage, + Image = new Bitmap(typeof(ToolStripMenuItem), "image.bmp"), + ImageTransparentColor = Color.Magenta + }; //Add event Handlers imageToolStripMenuItem.Click += new EventHandler(OnImageToolStripMenuItemClick); enabledToolStripMenuItem = CreateBooleanItem("E&nabled", "Enabled"); @@ -203,8 +207,10 @@ private void PopulateList() if (_designerHost.GetDesigner(currentItem) is ToolStripItemDesigner itemDesigner) { verbManager = new CollectionEditVerbManager(string.Format(SR.ToolStripDropDownItemCollectionEditorVerb), itemDesigner, TypeDescriptor.GetProperties(currentItem)["DropDownItems"], false); - editItemsToolStripMenuItem = new ToolStripMenuItem(); - editItemsToolStripMenuItem.Text = SR.ToolStripDropDownItemCollectionEditorVerb; + editItemsToolStripMenuItem = new ToolStripMenuItem + { + Text = SR.ToolStripDropDownItemCollectionEditorVerb + }; editItemsToolStripMenuItem.Click += new EventHandler(OnEditItemsMenuItemClick); editItemsToolStripMenuItem.Image = new Icon(typeof(ToolStripMenuItem), "editdropdownlist.bmp").ToBitmap(); editItemsToolStripMenuItem.ImageTransparentColor = Color.Magenta; diff --git a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerActionServiceTests.cs b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerActionServiceTests.cs index 9b0978a7e9e..5e6191840b3 100644 --- a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerActionServiceTests.cs +++ b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerActionServiceTests.cs @@ -470,8 +470,10 @@ public static IEnumerable GetComponentDesignerActions_TestData() public void GetComponentDesignerActions_Invoke_ReturnsExpected(ISite site, DesignerActionListCollection expected) { var service = new SubDesignerActionService(null); - var component = new Component(); - component.Site = site; + var component = new Component + { + Site = site + }; var actionListBuffer = new DesignerActionListCollection(); service.GetComponentDesignerActions(component, actionListBuffer); @@ -496,8 +498,10 @@ public void GetComponentDesignerActions_InvokeVerbs_ReturnsExpected() .Setup(s => s.GetService(typeof(DesignerCommandSet))) .Returns(verbsMockDesignerCommandSet.Object); var service = new SubDesignerActionService(null); - var component = new Component(); - component.Site = mockSite.Object; + var component = new Component + { + Site = mockSite.Object + }; var actionListBuffer = new DesignerActionListCollection(); service.GetComponentDesignerActions(component, actionListBuffer); @@ -538,8 +542,10 @@ public void GetComponentDesignerActionsVerbs_GetSortedActionItems_ReturnsExpecte .Setup(s => s.GetService(typeof(DesignerCommandSet))) .Returns(verbsMockDesignerCommandSet.Object); var service = new SubDesignerActionService(null); - var component = new Component(); - component.Site = mockSite.Object; + var component = new Component + { + Site = mockSite.Object + }; var actionListBuffer = new DesignerActionListCollection(); service.GetComponentDesignerActions(component, actionListBuffer); @@ -592,8 +598,10 @@ public void GetComponentDesignerActionsVerbs_InvokeActionItem_CallsVerbInvoke() .Setup(s => s.GetService(typeof(DesignerCommandSet))) .Returns(verbsMockDesignerCommandSet.Object); var service = new SubDesignerActionService(null); - var component = new Component(); - component.Site = mockSite.Object; + var component = new Component + { + Site = mockSite.Object + }; var actionListBuffer = new DesignerActionListCollection(); service.GetComponentDesignerActions(component, actionListBuffer); diff --git a/src/System.Windows.Forms.Design/tests/UnitTests/System/Drawing/Design/ToolboxItemTests.cs b/src/System.Windows.Forms.Design/tests/UnitTests/System/Drawing/Design/ToolboxItemTests.cs index 8a99317290f..3fb21b3b4f7 100644 --- a/src/System.Windows.Forms.Design/tests/UnitTests/System/Drawing/Design/ToolboxItemTests.cs +++ b/src/System.Windows.Forms.Design/tests/UnitTests/System/Drawing/Design/ToolboxItemTests.cs @@ -1209,16 +1209,22 @@ public static IEnumerable GetType_TestData() yield return new object[] { null, new AssemblyName(typeof(ToolboxItemTests).Assembly.FullName), "NoSuchType", false, null }; yield return new object[] { null, null, string.Empty, false, null }; - var validNameWithCodeBase = new AssemblyName(typeof(int).Assembly.FullName); - validNameWithCodeBase.CodeBase = "System.Windows.Forms.Design.Tests.dll"; + var validNameWithCodeBase = new AssemblyName(typeof(int).Assembly.FullName) + { + CodeBase = "System.Windows.Forms.Design.Tests.dll" + }; yield return new object[] { null, validNameWithCodeBase, "System.Drawing.Design.Tests.ToolboxItemTests", false, null }; - var invalidNameWithCodeBase = new AssemblyName("NoSuchAssembly"); - invalidNameWithCodeBase.CodeBase = "System.Windows.Forms.Design.Tests.dll"; + var invalidNameWithCodeBase = new AssemblyName("NoSuchAssembly") + { + CodeBase = "System.Windows.Forms.Design.Tests.dll" + }; yield return new object[] { null, invalidNameWithCodeBase, "System.Drawing.Design.Tests.ToolboxItemTests", false, typeof(ToolboxItemTests) }; - var invalidNameWithInvalidCodeBase = new AssemblyName("NoSuchAssembly"); - invalidNameWithInvalidCodeBase.CodeBase = "AlsoNoSuchAssembly"; + var invalidNameWithInvalidCodeBase = new AssemblyName("NoSuchAssembly") + { + CodeBase = "AlsoNoSuchAssembly" + }; yield return new object[] { null, invalidNameWithInvalidCodeBase, "System.Drawing.Design.Tests.ToolboxItemTests", false, null }; AssemblyLoadContext.Default.Resolving += (context, name) => @@ -1237,12 +1243,16 @@ public static IEnumerable GetType_TestData() yield return new object[] { null, new AssemblyName("ThrowBadImageFormatException"), "System.Int32", false, typeof(int) }; yield return new object[] { null, new AssemblyName("ThrowIOException"), "System.Int32", false, typeof(int) }; - var badImageFormatExceptionCodeBase = new AssemblyName("NoSuchAssembly"); - badImageFormatExceptionCodeBase.CodeBase = "ThrowBadImageFormatException"; + var badImageFormatExceptionCodeBase = new AssemblyName("NoSuchAssembly") + { + CodeBase = "ThrowBadImageFormatException" + }; yield return new object[] { null, badImageFormatExceptionCodeBase, "System.Int32", false, typeof(int) }; - var ioFormatExceptionCodeBase = new AssemblyName("NoSuchAssembly"); - ioFormatExceptionCodeBase.CodeBase = "ThrowIOException"; + var ioFormatExceptionCodeBase = new AssemblyName("NoSuchAssembly") + { + CodeBase = "ThrowIOException" + }; yield return new object[] { null, ioFormatExceptionCodeBase, "System.Int32", false, typeof(int) }; } diff --git a/src/System.Windows.Forms/src/System/Resources/ResXResourceWriter.cs b/src/System.Windows.Forms/src/System/Resources/ResXResourceWriter.cs index 3e0855707a6..8e0f45987b9 100644 --- a/src/System.Windows.Forms/src/System/Resources/ResXResourceWriter.cs +++ b/src/System.Windows.Forms/src/System/Resources/ResXResourceWriter.cs @@ -211,8 +211,10 @@ private void InitializeWriter() } xmlTextWriter.WriteStartElement("root"); - XmlTextReader reader = new XmlTextReader(new StringReader(ResourceSchema)); - reader.WhitespaceHandling = WhitespaceHandling.None; + XmlTextReader reader = new XmlTextReader(new StringReader(ResourceSchema)) + { + WhitespaceHandling = WhitespaceHandling.None + }; xmlTextWriter.WriteNode(reader, true); xmlTextWriter.WriteStartElement(ResHeaderStr); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs index bd371dd9b06..eca693fd6e4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs @@ -901,11 +901,13 @@ public static bool FilterMessage(ref Message message) bool modified; // Create copy of MSG structure - NativeMethods.MSG msg = new NativeMethods.MSG(); - msg.hwnd = message.HWnd; - msg.message = message.Msg; - msg.wParam = message.WParam; - msg.lParam = message.LParam; + NativeMethods.MSG msg = new NativeMethods.MSG + { + hwnd = message.HWnd, + message = message.Msg, + wParam = message.WParam, + lParam = message.LParam + }; bool processed = ThreadContext.FromCurrent().ProcessFilters(ref msg, out modified); if (modified) @@ -1652,9 +1654,11 @@ bool UnsafeNativeMethods.IMsoComponentManager.FRegisterComponent(UnsafeNativeMet // Construct Hashtable entry for this component // - ComponentHashtableEntry entry = new ComponentHashtableEntry(); - entry.component = component; - entry.componentInfo = pcrinfo; + ComponentHashtableEntry entry = new ComponentHashtableEntry + { + component = component, + componentInfo = pcrinfo + }; OleComponents.Add(++cookieCounter, entry); // Return the cookie @@ -2510,11 +2514,13 @@ internal UnsafeNativeMethods.IMsoComponentManager ComponentManager // Finally, if we got a compnent manager, register ourselves with it. // Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "Registering MSO component with the component manager"); - NativeMethods.MSOCRINFOSTRUCT info = new NativeMethods.MSOCRINFOSTRUCT(); - info.cbSize = Marshal.SizeOf(); - info.uIdleTimeInterval = 0; - info.grfcrf = NativeMethods.MSOCM.msocrfPreTranslateAll | NativeMethods.MSOCM.msocrfNeedIdleTime; - info.grfcadvf = NativeMethods.MSOCM.msocadvfModal; + NativeMethods.MSOCRINFOSTRUCT info = new NativeMethods.MSOCRINFOSTRUCT + { + cbSize = Marshal.SizeOf(), + uIdleTimeInterval = 0, + grfcrf = NativeMethods.MSOCM.msocrfPreTranslateAll | NativeMethods.MSOCM.msocrfNeedIdleTime, + grfcadvf = NativeMethods.MSOCM.msocadvfModal + }; IntPtr localComponentID; bool result = msocm.FRegisterComponent(this, info, out localComponentID); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs index 197f31cf5c9..cea719ffa51 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs @@ -1320,9 +1320,11 @@ private static int SetupLogPixels(bool force) private void HiMetric2Pixel(NativeMethods.tagSIZEL sz, NativeMethods.tagSIZEL szout) { - NativeMethods._POINTL phm = new NativeMethods._POINTL(); - phm.x = sz.cx; - phm.y = sz.cy; + NativeMethods._POINTL phm = new NativeMethods._POINTL + { + x = sz.cx, + y = sz.cy + }; NativeMethods.tagPOINTF pcont = new NativeMethods.tagPOINTF(); ((UnsafeNativeMethods.IOleControlSite)oleSite).TransformCoords(phm, pcont, NativeMethods.ActiveX.XFORMCOORDS_SIZE | NativeMethods.ActiveX.XFORMCOORDS_HIMETRICTOCONTAINER); szout.cx = (int)pcont.x; @@ -1331,9 +1333,11 @@ private void HiMetric2Pixel(NativeMethods.tagSIZEL sz, NativeMethods.tagSIZEL sz private void Pixel2hiMetric(NativeMethods.tagSIZEL sz, NativeMethods.tagSIZEL szout) { - NativeMethods.tagPOINTF pcont = new NativeMethods.tagPOINTF(); - pcont.x = (float)sz.cx; - pcont.y = (float)sz.cy; + NativeMethods.tagPOINTF pcont = new NativeMethods.tagPOINTF + { + x = (float)sz.cx, + y = (float)sz.cy + }; NativeMethods._POINTL phm = new NativeMethods._POINTL(); ((UnsafeNativeMethods.IOleControlSite)oleSite).TransformCoords(phm, pcont, NativeMethods.ActiveX.XFORMCOORDS_SIZE | NativeMethods.ActiveX.XFORMCOORDS_CONTAINERTOHIMETRIC); szout.cx = phm.x; @@ -1365,9 +1369,11 @@ private static int Twip2Pixel(int v, bool xDirection) private Size SetExtent(int width, int height) { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "setting extent to " + width.ToString(CultureInfo.InvariantCulture) + " " + height.ToString(CultureInfo.InvariantCulture)); - NativeMethods.tagSIZEL sz = new NativeMethods.tagSIZEL(); - sz.cx = width; - sz.cy = height; + NativeMethods.tagSIZEL sz = new NativeMethods.tagSIZEL + { + cx = width, + cy = height + }; bool resetExtents = !IsUserMode(); try { @@ -1971,11 +1977,13 @@ public override bool PreProcessMessage(ref Message msg) return base.PreProcessMessage(ref msg); } - NativeMethods.MSG win32Message = new NativeMethods.MSG(); - win32Message.message = msg.Msg; - win32Message.wParam = msg.WParam; - win32Message.lParam = msg.LParam; - win32Message.hwnd = msg.HWnd; + NativeMethods.MSG win32Message = new NativeMethods.MSG + { + message = msg.Msg, + wParam = msg.WParam, + lParam = msg.LParam, + hwnd = msg.HWnd + }; axState[siteProcessedInputKey] = false; try @@ -2049,15 +2057,17 @@ protected internal override bool ProcessMnemonic(char charCode) { return false; } - NativeMethods.MSG msg = new NativeMethods.MSG(); - // Sadly, we don't have a message so we must fake one ourselves... - // A bit of ugliness here (a bit? more like a bucket...) - // The message we are faking is a WM_SYSKEYDOWN w/ the right alt key setting... - msg.hwnd = (ContainingControl == null) ? IntPtr.Zero : ContainingControl.Handle; - msg.message = Interop.WindowMessages.WM_SYSKEYDOWN; - msg.wParam = (IntPtr)char.ToUpper(charCode, CultureInfo.CurrentCulture); - msg.lParam = (IntPtr)0x20180001; - msg.time = SafeNativeMethods.GetTickCount(); + NativeMethods.MSG msg = new NativeMethods.MSG + { + // Sadly, we don't have a message so we must fake one ourselves... + // A bit of ugliness here (a bit? more like a bucket...) + // The message we are faking is a WM_SYSKEYDOWN w/ the right alt key setting... + hwnd = (ContainingControl == null) ? IntPtr.Zero : ContainingControl.Handle, + message = Interop.WindowMessages.WM_SYSKEYDOWN, + wParam = (IntPtr)char.ToUpper(charCode, CultureInfo.CurrentCulture), + lParam = (IntPtr)0x20180001, + time = SafeNativeMethods.GetTickCount() + }; NativeMethods.POINT p = new NativeMethods.POINT(); UnsafeNativeMethods.GetCursorPos(p); msg.pt_x = p.x; @@ -3377,12 +3387,14 @@ unsafe private void ShowPropertyPageForDispid(int dispid, Guid guid) try { IntPtr pUnk = Marshal.GetIUnknownForObject(GetOcx()); - NativeMethods.OCPFIPARAMS opcparams = new NativeMethods.OCPFIPARAMS(); - opcparams.hwndOwner = (ContainingControl == null) ? IntPtr.Zero : ContainingControl.Handle; - opcparams.lpszCaption = Name; - opcparams.ppUnk = (IntPtr)(long)&pUnk; - opcparams.uuid = (IntPtr)(long)&guid; - opcparams.dispidInitial = dispid; + NativeMethods.OCPFIPARAMS opcparams = new NativeMethods.OCPFIPARAMS + { + hwndOwner = (ContainingControl == null) ? IntPtr.Zero : ContainingControl.Handle, + lpszCaption = Name, + ppUnk = (IntPtr)(long)&pUnk, + uuid = (IntPtr)(long)&guid, + dispidInitial = dispid + }; UnsafeNativeMethods.OleCreatePropertyFrameIndirect(opcparams); } catch (Exception t) @@ -4292,11 +4304,13 @@ int UnsafeNativeMethods.IOleControlSite.TranslateAccelerator(ref NativeMethods.M Debug.Assert(!host.GetAxState(AxHost.siteProcessedInputKey), "Re-entering UnsafeNativeMethods.IOleControlSite.TranslateAccelerator!!!"); host.SetAxState(AxHost.siteProcessedInputKey, true); - Message msg = new Message(); - msg.Msg = pMsg.message; - msg.WParam = pMsg.wParam; - msg.LParam = pMsg.lParam; - msg.HWnd = pMsg.hwnd; + Message msg = new Message + { + Msg = pMsg.message, + WParam = pMsg.wParam, + LParam = pMsg.lParam, + HWnd = pMsg.hwnd + }; try { @@ -5111,9 +5125,11 @@ private static Image GetPictureFromParams(object pict, IntPtr handle, int type, case NativeMethods.Ole.PICTYPE_ICON: return (Image)(Icon.FromHandle(handle)).Clone(); case NativeMethods.Ole.PICTYPE_METAFILE: - WmfPlaceableFileHeader header = new WmfPlaceableFileHeader(); - header.BboxRight = (short)width; - header.BboxBottom = (short)height; + WmfPlaceableFileHeader header = new WmfPlaceableFileHeader + { + BboxRight = (short)width, + BboxBottom = (short)height + }; return (Image)(new Metafile(handle, header, false)).Clone(); case NativeMethods.Ole.PICTYPE_ENHMETAFILE: return (Image)(new Metafile(handle, false)).Clone(); @@ -5145,9 +5161,11 @@ private static NativeMethods.FONTDESC GetFONTDESCFromFont(Font font) if (fdesc == null) { - fdesc = new NativeMethods.FONTDESC(); - fdesc.lpstrName = font.Name; - fdesc.cySize = (long)(font.SizeInPoints * 10000); + fdesc = new NativeMethods.FONTDESC + { + lpstrName = font.Name, + cySize = (long)(font.SizeInPoints * 10000) + }; NativeMethods.LOGFONT logfont = new NativeMethods.LOGFONT(); font.ToLogFont(logfont); fdesc.sWeight = (short)logfont.lfWeight; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonBaseAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonBaseAdapter.cs index 4ed48267cb3..9b093cf4d3a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonBaseAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonBaseAdapter.cs @@ -863,9 +863,10 @@ internal static int Adjust255(float percentage, int value) internal ColorData Calculate() { - ColorData colors = new ColorData(this); - - colors.buttonFace = backColor; + ColorData colors = new ColorData(this) + { + buttonFace = backColor + }; if (backColor == SystemColors.Control) { @@ -1043,13 +1044,14 @@ public StringFormat StringFormat { get { - StringFormat format = new StringFormat(); - - format.FormatFlags = gdipFormatFlags; - format.Trimming = gdipTrimming; - format.HotkeyPrefix = gdipHotkeyPrefix; - format.Alignment = gdipAlignment; - format.LineAlignment = gdipLineAlignment; + StringFormat format = new StringFormat + { + FormatFlags = gdipFormatFlags, + Trimming = gdipTrimming, + HotkeyPrefix = gdipHotkeyPrefix, + Alignment = gdipAlignment, + LineAlignment = gdipLineAlignment + }; if (disableWordWrapping) { @@ -1259,8 +1261,10 @@ private bool OnePixExtraBorder internal LayoutData Layout() { - LayoutData layout = new LayoutData(this); - layout.client = client; + LayoutData layout = new LayoutData(this) + { + client = client + }; // subtract border size from layout area int fullBorderSize = FullBorderSize; @@ -1716,55 +1720,59 @@ internal LayoutData(LayoutOptions options) // used by the DataGridViewButtonCell internal static LayoutOptions CommonLayout(Rectangle clientRectangle, Padding padding, bool isDefault, Font font, string text, bool enabled, ContentAlignment textAlign, RightToLeft rtl) { - LayoutOptions layout = new LayoutOptions(); - layout.client = LayoutUtils.DeflateRect(clientRectangle, padding); - layout.padding = padding; - layout.growBorderBy1PxWhenDefault = true; - layout.isDefault = isDefault; - layout.borderSize = 2; - layout.paddingSize = 0; - layout.maxFocus = true; - layout.focusOddEvenFixup = false; - layout.font = font; - layout.text = text; - layout.imageSize = Size.Empty; - layout.checkSize = 0; - layout.checkPaddingSize = 0; - layout.checkAlign = ContentAlignment.TopLeft; - layout.imageAlign = ContentAlignment.MiddleCenter; - layout.textAlign = textAlign; - layout.hintTextUp = false; - layout.shadowedText = !enabled; - layout.layoutRTL = RightToLeft.Yes == rtl; - layout.textImageRelation = TextImageRelation.Overlay; - layout.useCompatibleTextRendering = false; + LayoutOptions layout = new LayoutOptions + { + client = LayoutUtils.DeflateRect(clientRectangle, padding), + padding = padding, + growBorderBy1PxWhenDefault = true, + isDefault = isDefault, + borderSize = 2, + paddingSize = 0, + maxFocus = true, + focusOddEvenFixup = false, + font = font, + text = text, + imageSize = Size.Empty, + checkSize = 0, + checkPaddingSize = 0, + checkAlign = ContentAlignment.TopLeft, + imageAlign = ContentAlignment.MiddleCenter, + textAlign = textAlign, + hintTextUp = false, + shadowedText = !enabled, + layoutRTL = RightToLeft.Yes == rtl, + textImageRelation = TextImageRelation.Overlay, + useCompatibleTextRendering = false + }; return layout; } internal virtual LayoutOptions CommonLayout() { - LayoutOptions layout = new LayoutOptions(); - layout.client = LayoutUtils.DeflateRect(Control.ClientRectangle, Control.Padding); - layout.padding = Control.Padding; - layout.growBorderBy1PxWhenDefault = true; - layout.isDefault = Control.IsDefault; - layout.borderSize = 2; - layout.paddingSize = 0; - layout.maxFocus = true; - layout.focusOddEvenFixup = false; - layout.font = Control.Font; - layout.text = Control.Text; - layout.imageSize = (Control.Image == null) ? Size.Empty : Control.Image.Size; - layout.checkSize = 0; - layout.checkPaddingSize = 0; - layout.checkAlign = ContentAlignment.TopLeft; - layout.imageAlign = Control.ImageAlign; - layout.textAlign = Control.TextAlign; - layout.hintTextUp = false; - layout.shadowedText = !Control.Enabled; - layout.layoutRTL = RightToLeft.Yes == Control.RightToLeft; - layout.textImageRelation = Control.TextImageRelation; - layout.useCompatibleTextRendering = Control.UseCompatibleTextRendering; + LayoutOptions layout = new LayoutOptions + { + client = LayoutUtils.DeflateRect(Control.ClientRectangle, Control.Padding), + padding = Control.Padding, + growBorderBy1PxWhenDefault = true, + isDefault = Control.IsDefault, + borderSize = 2, + paddingSize = 0, + maxFocus = true, + focusOddEvenFixup = false, + font = Control.Font, + text = Control.Text, + imageSize = (Control.Image == null) ? Size.Empty : Control.Image.Size, + checkSize = 0, + checkPaddingSize = 0, + checkAlign = ContentAlignment.TopLeft, + imageAlign = Control.ImageAlign, + textAlign = Control.TextAlign, + hintTextUp = false, + shadowedText = !Control.Enabled, + layoutRTL = RightToLeft.Yes == Control.RightToLeft, + textImageRelation = Control.TextImageRelation, + useCompatibleTextRendering = Control.UseCompatibleTextRendering + }; if (Control.FlatStyle != FlatStyle.System) { @@ -1787,15 +1795,19 @@ internal virtual LayoutOptions CommonLayout() // used by the DataGridViewButtonCell static ColorOptions CommonRender(Graphics g, Color foreColor, Color backColor, bool enabled) { - ColorOptions colors = new ColorOptions(g, foreColor, backColor); - colors.enabled = enabled; + ColorOptions colors = new ColorOptions(g, foreColor, backColor) + { + enabled = enabled + }; return colors; } ColorOptions CommonRender(Graphics g) { - ColorOptions colors = new ColorOptions(g, Control.ForeColor, Control.BackColor); - colors.enabled = Control.Enabled; + ColorOptions colors = new ColorOptions(g, Control.ForeColor, Control.BackColor) + { + enabled = Control.Enabled + }; return colors; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs index 543ccfcda7e..137976128fa 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs @@ -42,8 +42,10 @@ private static ModuleBuilder ModuleBuilder { if (moduleBuilder == null) { - AssemblyName assemblyName = new AssemblyName(); - assemblyName.Name = "COM2InteropEmit"; + AssemblyName assemblyName = new AssemblyName + { + Name = "COM2InteropEmit" + }; AssemblyBuilder aBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); moduleBuilder = aBuilder.DefineDynamicModule("COM2Interop.Emit"); } @@ -577,8 +579,10 @@ private static PropInfo ProcessDataCore(UnsafeNativeMethods.ITypeInfo typeInfo, if (pi == null) { - pi = new PropInfo(); - pi.Index = propInfoList.Count; + pi = new PropInfo + { + Index = propInfoList.Count + }; propInfoList[pPropName] = pi; pi.Name = pPropName; pi.DispId = dispid; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs index 2fc024c1486..d5430196090 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs @@ -1945,8 +1945,10 @@ private bool ValidateThroughAncestor(Control ancestorControl, bool preventFocusC { if (currentActiveControl != null) { - CancelEventArgs ev = new CancelEventArgs(); - ev.Cancel = true; + CancelEventArgs ev = new CancelEventArgs + { + Cancel = true + }; currentActiveControl.NotifyValidationResult(currentValidatingControl, ev); if (currentActiveControl is ContainerControl) { 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 bd6b2b1c813..2a2e3410b05 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs @@ -6598,10 +6598,12 @@ internal virtual Rectangle ApplyBoundsConstraints(int suggestedX, int suggestedY if (MaximumSize != Size.Empty || MinimumSize != Size.Empty) { Size maximumSize = LayoutUtils.ConvertZeroToUnbounded(MaximumSize); - Rectangle newBounds = new Rectangle(suggestedX, suggestedY, 0, 0); + 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); + // Clip the size to maximum and inflate it to minimum as necessary. + Size = LayoutUtils.IntersectSizes(new Size(proposedWidth, proposedHeight), maximumSize) + }; newBounds.Size = LayoutUtils.UnionSizes(newBounds.Size, MinimumSize); return newBounds; @@ -7299,9 +7301,11 @@ private void HookMouseEvent() if (trackMouseEvent == null) { - trackMouseEvent = new NativeMethods.TRACKMOUSEEVENT(); - trackMouseEvent.dwFlags = NativeMethods.TME_LEAVE | NativeMethods.TME_HOVER; - trackMouseEvent.hwndTrack = Handle; + trackMouseEvent = new NativeMethods.TRACKMOUSEEVENT + { + dwFlags = NativeMethods.TME_LEAVE | NativeMethods.TME_HOVER, + hwndTrack = Handle + }; } SafeNativeMethods.TrackMouseEvent(trackMouseEvent); @@ -9094,9 +9098,11 @@ internal virtual void OnInvokedSetScrollPosition(object sender, EventArgs e) { if (!(this is ScrollableControl) && !IsMirrored) { - NativeMethods.SCROLLINFO si = new NativeMethods.SCROLLINFO(); - si.cbSize = Marshal.SizeOf(); - si.fMask = NativeMethods.SIF_RANGE; + NativeMethods.SCROLLINFO si = new NativeMethods.SCROLLINFO + { + cbSize = Marshal.SizeOf(), + fMask = NativeMethods.SIF_RANGE + }; if (UnsafeNativeMethods.GetScrollInfo(new HandleRef(this, Handle), NativeMethods.SB_HORZ, si) != false) { si.nPos = (RightToLeft == RightToLeft.Yes) ? si.nMax : si.nMin; @@ -17236,9 +17242,11 @@ internal void DoVerb(int iVerb, IntPtr lpmsg, UnsafeNativeMethods.IOleClientSite // Must translate message coordniates over to our HWND. We first try // IntPtr hwndMap = msg.hwnd == IntPtr.Zero ? hwndParent : msg.hwnd; - NativeMethods.POINT pt = new NativeMethods.POINT(); - pt.x = NativeMethods.Util.LOWORD(msg.lParam); - pt.y = NativeMethods.Util.HIWORD(msg.lParam); + NativeMethods.POINT pt = new NativeMethods.POINT + { + x = NativeMethods.Util.LOWORD(msg.lParam), + y = NativeMethods.Util.HIWORD(msg.lParam) + }; UnsafeNativeMethods.MapWindowPoints(new HandleRef(null, hwndMap), new HandleRef(control, control.Handle), pt, 1); // check to see if this message should really go to a child @@ -17570,8 +17578,10 @@ internal int GetControlInfo(NativeMethods.tagCONTROLINFO pCI) try { - NativeMethods.ACCEL accel = new NativeMethods.ACCEL(); - accel.cmd = 0; + NativeMethods.ACCEL accel = new NativeMethods.ACCEL + { + cmd = 0 + }; Debug.Indent(); @@ -17722,9 +17732,11 @@ internal int GetWindow(out IntPtr hwnd) /// private Point HiMetricToPixel(int x, int y) { - Point pt = new Point(); - pt.X = (LogPixels.X * x + hiMetricPerInch / 2) / hiMetricPerInch; - pt.Y = (LogPixels.Y * y + hiMetricPerInch / 2) / hiMetricPerInch; + Point pt = new Point + { + X = (LogPixels.X * x + hiMetricPerInch / 2) / hiMetricPerInch, + Y = (LogPixels.Y * y + hiMetricPerInch / 2) / hiMetricPerInch + }; return pt; } @@ -17771,8 +17783,10 @@ internal void InPlaceActivate(int verb) if (!activeXState[inPlaceVisible]) { Debug.WriteLineIf(CompModSwitches.ActiveX.TraceVerbose, "\tActiveXImpl:InPlaceActivate --> inplacevisible"); - NativeMethods.tagOIFI inPlaceFrameInfo = new NativeMethods.tagOIFI(); - inPlaceFrameInfo.cb = Marshal.SizeOf(); + NativeMethods.tagOIFI inPlaceFrameInfo = new NativeMethods.tagOIFI + { + cb = Marshal.SizeOf() + }; IntPtr hwndParent = IntPtr.Zero; // We are entering a secure context here. @@ -18118,10 +18132,12 @@ internal void Load(UnsafeNativeMethods.IPropertyBag pPropBag, UnsafeNativeMethod Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "Exception converting property: " + errorString); if (pErrorLog != null) { - NativeMethods.tagEXCEPINFO err = new NativeMethods.tagEXCEPINFO(); - err.bstrSource = control.GetType().FullName; - err.bstrDescription = errorString; - err.scode = errorCode; + NativeMethods.tagEXCEPINFO err = new NativeMethods.tagEXCEPINFO + { + bstrSource = control.GetType().FullName, + bstrDescription = errorString, + scode = errorCode + }; pErrorLog.AddError(props[i].Name, err); } } @@ -18342,9 +18358,11 @@ internal void OnFocus(bool focus) /// private Point PixelToHiMetric(int x, int y) { - Point pt = new Point(); - pt.X = (hiMetricPerInch * x + (LogPixels.X >> 1)) / LogPixels.X; - pt.Y = (hiMetricPerInch * y + (LogPixels.Y >> 1)) / LogPixels.Y; + Point pt = new Point + { + X = (hiMetricPerInch * x + (LogPixels.X >> 1)) / LogPixels.X, + Y = (hiMetricPerInch * y + (LogPixels.Y >> 1)) / LogPixels.Y + }; return pt; } @@ -20139,19 +20157,21 @@ private unsafe bool DICopy(HandleRef hdcDest, HandleRef hdcSrc, NativeMethods.RE return fSuccess; } - NativeMethods.BITMAPINFO_FLAT lpbmi = new NativeMethods.BITMAPINFO_FLAT(); - lpbmi.bmiHeader_biSize = Marshal.SizeOf(); - lpbmi.bmiHeader_biWidth = bmp.bmWidth; - lpbmi.bmiHeader_biHeight = bmp.bmHeight; - lpbmi.bmiHeader_biPlanes = 1; - lpbmi.bmiHeader_biBitCount = bmp.bmBitsPixel; - lpbmi.bmiHeader_biCompression = NativeMethods.BI_RGB; - lpbmi.bmiHeader_biSizeImage = 0; //Not needed since using BI_RGB - lpbmi.bmiHeader_biXPelsPerMeter = 0; - lpbmi.bmiHeader_biYPelsPerMeter = 0; - lpbmi.bmiHeader_biClrUsed = 0; - lpbmi.bmiHeader_biClrImportant = 0; - lpbmi.bmiColors = new byte[NativeMethods.BITMAPINFO_MAX_COLORSIZE * 4]; + NativeMethods.BITMAPINFO_FLAT lpbmi = new NativeMethods.BITMAPINFO_FLAT + { + bmiHeader_biSize = Marshal.SizeOf(), + bmiHeader_biWidth = bmp.bmWidth, + bmiHeader_biHeight = bmp.bmHeight, + bmiHeader_biPlanes = 1, + bmiHeader_biBitCount = bmp.bmBitsPixel, + bmiHeader_biCompression = NativeMethods.BI_RGB, + bmiHeader_biSizeImage = 0, //Not needed since using BI_RGB + bmiHeader_biXPelsPerMeter = 0, + bmiHeader_biYPelsPerMeter = 0, + bmiHeader_biClrUsed = 0, + bmiHeader_biClrImportant = 0, + bmiColors = new byte[NativeMethods.BITMAPINFO_MAX_COLORSIZE * 4] + }; // // Include the palette for 256 color bitmaps diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ControlPaint.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ControlPaint.cs index c51d1cbaac1..87b6b476727 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ControlPaint.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ControlPaint.cs @@ -337,10 +337,12 @@ internal static IntPtr CreateHalftoneHBRUSH() grayPattern[i] = (short)(0x5555 << (i & 1)); IntPtr hBitmap = SafeNativeMethods.CreateBitmap(8, 8, 1, 1, grayPattern); - NativeMethods.LOGBRUSH lb = new NativeMethods.LOGBRUSH(); - lb.lbColor = ColorTranslator.ToWin32(Color.Black); - lb.lbStyle = NativeMethods.BS_PATTERN; - lb.lbHatch = hBitmap; + NativeMethods.LOGBRUSH lb = new NativeMethods.LOGBRUSH + { + lbColor = ColorTranslator.ToWin32(Color.Black), + lbStyle = NativeMethods.BS_PATTERN, + lbHatch = hBitmap + }; IntPtr brush = SafeNativeMethods.CreateBrushIndirect(lb); SafeNativeMethods.DeleteObject(new HandleRef(null, hBitmap)); @@ -721,8 +723,10 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, // nothing break; case ButtonBorderStyle.Dotted: - pen = new Pen(topColor); - pen.DashStyle = DashStyle.Dot; + pen = new Pen(topColor) + { + DashStyle = DashStyle.Dot + }; for (int i = 0; i < topWidth; i++) { graphics.DrawLine(pen, topLineLefts[i], bounds.Y + i, topLineRights[i], bounds.Y + i); @@ -730,8 +734,10 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, pen.Dispose(); break; case ButtonBorderStyle.Dashed: - pen = new Pen(topColor); - pen.DashStyle = DashStyle.Dash; + pen = new Pen(topColor) + { + DashStyle = DashStyle.Dash + }; for (int i = 0; i < topWidth; i++) { graphics.DrawLine(pen, topLineLefts[i], bounds.Y + i, topLineRights[i], bounds.Y + i); @@ -739,8 +745,10 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, pen.Dispose(); break; case ButtonBorderStyle.Solid: - pen = new Pen(topColor); - pen.DashStyle = DashStyle.Solid; + pen = new Pen(topColor) + { + DashStyle = DashStyle.Solid + }; for (int i = 0; i < topWidth; i++) { graphics.DrawLine(pen, topLineLefts[i], bounds.Y + i, topLineRights[i], bounds.Y + i); @@ -752,8 +760,10 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, float inc = InfinityToOne(1.0f / (float)(topWidth - 1)); for (int i = 0; i < topWidth; i++) { - pen = new Pen(topHLSColor.Darker(1.0f - ((float)i) * inc)); - pen.DashStyle = DashStyle.Solid; + pen = new Pen(topHLSColor.Darker(1.0f - ((float)i) * inc)) + { + DashStyle = DashStyle.Solid + }; graphics.DrawLine(pen, topLineLefts[i], bounds.Y + i, topLineRights[i], bounds.Y + i); pen.Dispose(); } @@ -765,8 +775,10 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, for (int i = 0; i < topWidth; i++) { - pen = new Pen(topHLSColor.Lighter(1.0f - ((float)i) * inc)); - pen.DashStyle = DashStyle.Solid; + pen = new Pen(topHLSColor.Lighter(1.0f - ((float)i) * inc)) + { + DashStyle = DashStyle.Solid + }; graphics.DrawLine(pen, topLineLefts[i], bounds.Y + i, topLineRights[i], bounds.Y + i); pen.Dispose(); } @@ -784,8 +796,10 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, // nothing break; case ButtonBorderStyle.Dotted: - pen = new Pen(leftColor); - pen.DashStyle = DashStyle.Dot; + pen = new Pen(leftColor) + { + DashStyle = DashStyle.Dot + }; for (int i = 0; i < leftWidth; i++) { graphics.DrawLine(pen, bounds.X + i, leftLineTops[i], bounds.X + i, leftLineBottoms[i]); @@ -793,8 +807,10 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, pen.Dispose(); break; case ButtonBorderStyle.Dashed: - pen = new Pen(leftColor); - pen.DashStyle = DashStyle.Dash; + pen = new Pen(leftColor) + { + DashStyle = DashStyle.Dash + }; for (int i = 0; i < leftWidth; i++) { graphics.DrawLine(pen, bounds.X + i, leftLineTops[i], bounds.X + i, leftLineBottoms[i]); @@ -802,8 +818,10 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, pen.Dispose(); break; case ButtonBorderStyle.Solid: - pen = new Pen(leftColor); - pen.DashStyle = DashStyle.Solid; + pen = new Pen(leftColor) + { + DashStyle = DashStyle.Solid + }; for (int i = 0; i < leftWidth; i++) { graphics.DrawLine(pen, bounds.X + i, leftLineTops[i], bounds.X + i, leftLineBottoms[i]); @@ -815,8 +833,10 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, float inc = InfinityToOne(1.0f / (float)(leftWidth - 1)); for (int i = 0; i < leftWidth; i++) { - pen = new Pen(leftHLSColor.Darker(1.0f - ((float)i) * inc)); - pen.DashStyle = DashStyle.Solid; + pen = new Pen(leftHLSColor.Darker(1.0f - ((float)i) * inc)) + { + DashStyle = DashStyle.Solid + }; graphics.DrawLine(pen, bounds.X + i, leftLineTops[i], bounds.X + i, leftLineBottoms[i]); pen.Dispose(); } @@ -827,8 +847,10 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, float inc = InfinityToOne(1.0f / (float)(leftWidth - 1)); for (int i = 0; i < leftWidth; i++) { - pen = new Pen(leftHLSColor.Lighter(1.0f - ((float)i) * inc)); - pen.DashStyle = DashStyle.Solid; + pen = new Pen(leftHLSColor.Lighter(1.0f - ((float)i) * inc)) + { + DashStyle = DashStyle.Solid + }; graphics.DrawLine(pen, bounds.X + i, leftLineTops[i], bounds.X + i, leftLineBottoms[i]); pen.Dispose(); } @@ -846,8 +868,10 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, // nothing break; case ButtonBorderStyle.Dotted: - pen = new Pen(bottomColor); - pen.DashStyle = DashStyle.Dot; + pen = new Pen(bottomColor) + { + DashStyle = DashStyle.Dot + }; for (int i = 0; i < bottomWidth; i++) { graphics.DrawLine(pen, bottomLineLefts[i], bounds.Y + bounds.Height - 1 - i, bottomLineRights[i], bounds.Y + bounds.Height - 1 - i); @@ -855,8 +879,10 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, pen.Dispose(); break; case ButtonBorderStyle.Dashed: - pen = new Pen(bottomColor); - pen.DashStyle = DashStyle.Dash; + pen = new Pen(bottomColor) + { + DashStyle = DashStyle.Dash + }; for (int i = 0; i < bottomWidth; i++) { graphics.DrawLine(pen, bottomLineLefts[i], bounds.Y + bounds.Height - 1 - i, bottomLineRights[i], bounds.Y + bounds.Height - 1 - i); @@ -864,8 +890,10 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, pen.Dispose(); break; case ButtonBorderStyle.Solid: - pen = new Pen(bottomColor); - pen.DashStyle = DashStyle.Solid; + pen = new Pen(bottomColor) + { + DashStyle = DashStyle.Solid + }; for (int i = 0; i < bottomWidth; i++) { graphics.DrawLine(pen, bottomLineLefts[i], bounds.Y + bounds.Height - 1 - i, bottomLineRights[i], bounds.Y + bounds.Height - 1 - i); @@ -877,8 +905,10 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, float inc = InfinityToOne(1.0f / (float)(bottomWidth - 1)); for (int i = 0; i < bottomWidth; i++) { - pen = new Pen(bottomHLSColor.Lighter(1.0f - ((float)i) * inc)); - pen.DashStyle = DashStyle.Solid; + pen = new Pen(bottomHLSColor.Lighter(1.0f - ((float)i) * inc)) + { + DashStyle = DashStyle.Solid + }; graphics.DrawLine(pen, bottomLineLefts[i], bounds.Y + bounds.Height - 1 - i, bottomLineRights[i], bounds.Y + bounds.Height - 1 - i); pen.Dispose(); } @@ -890,8 +920,10 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, for (int i = 0; i < bottomWidth; i++) { - pen = new Pen(bottomHLSColor.Darker(1.0f - ((float)i) * inc)); - pen.DashStyle = DashStyle.Solid; + pen = new Pen(bottomHLSColor.Darker(1.0f - ((float)i) * inc)) + { + DashStyle = DashStyle.Solid + }; graphics.DrawLine(pen, bottomLineLefts[i], bounds.Y + bounds.Height - 1 - i, bottomLineRights[i], bounds.Y + bounds.Height - 1 - i); pen.Dispose(); } @@ -909,8 +941,10 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, // nothing break; case ButtonBorderStyle.Dotted: - pen = new Pen(rightColor); - pen.DashStyle = DashStyle.Dot; + pen = new Pen(rightColor) + { + DashStyle = DashStyle.Dot + }; for (int i = 0; i < rightWidth; i++) { graphics.DrawLine(pen, bounds.X + bounds.Width - 1 - i, rightLineTops[i], bounds.X + bounds.Width - 1 - i, rightLineBottoms[i]); @@ -918,8 +952,10 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, pen.Dispose(); break; case ButtonBorderStyle.Dashed: - pen = new Pen(rightColor); - pen.DashStyle = DashStyle.Dash; + pen = new Pen(rightColor) + { + DashStyle = DashStyle.Dash + }; for (int i = 0; i < rightWidth; i++) { graphics.DrawLine(pen, bounds.X + bounds.Width - 1 - i, rightLineTops[i], bounds.X + bounds.Width - 1 - i, rightLineBottoms[i]); @@ -927,8 +963,10 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, pen.Dispose(); break; case ButtonBorderStyle.Solid: - pen = new Pen(rightColor); - pen.DashStyle = DashStyle.Solid; + pen = new Pen(rightColor) + { + DashStyle = DashStyle.Solid + }; for (int i = 0; i < rightWidth; i++) { graphics.DrawLine(pen, bounds.X + bounds.Width - 1 - i, rightLineTops[i], bounds.X + bounds.Width - 1 - i, rightLineBottoms[i]); @@ -940,8 +978,10 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, float inc = InfinityToOne(1.0f / (float)(rightWidth - 1)); for (int i = 0; i < rightWidth; i++) { - pen = new Pen(rightHLSColor.Lighter(1.0f - ((float)i) * inc)); - pen.DashStyle = DashStyle.Solid; + pen = new Pen(rightHLSColor.Lighter(1.0f - ((float)i) * inc)) + { + DashStyle = DashStyle.Solid + }; graphics.DrawLine(pen, bounds.X + bounds.Width - 1 - i, rightLineTops[i], bounds.X + bounds.Width - 1 - i, rightLineBottoms[i]); pen.Dispose(); } @@ -953,8 +993,10 @@ public static void DrawBorder(Graphics graphics, Rectangle bounds, for (int i = 0; i < rightWidth; i++) { - pen = new Pen(rightHLSColor.Darker(1.0f - ((float)i) * inc)); - pen.DashStyle = DashStyle.Solid; + pen = new Pen(rightHLSColor.Darker(1.0f - ((float)i) * inc)) + { + DashStyle = DashStyle.Solid + }; graphics.DrawLine(pen, bounds.X + bounds.Width - 1 - i, rightLineTops[i], bounds.X + bounds.Width - 1 - i, rightLineBottoms[i]); pen.Dispose(); } @@ -1492,12 +1534,16 @@ private static void DrawFrameControl(Graphics graphics, int x, int y, int width, { // Replace black/white with foreColor/backColor. ImageAttributes attrs = new ImageAttributes(); - ColorMap cm1 = new ColorMap(); - cm1.OldColor = Color.Black; - cm1.NewColor = foreColor; - ColorMap cm2 = new ColorMap(); - cm2.OldColor = Color.White; - cm2.NewColor = backColor; + ColorMap cm1 = new ColorMap + { + OldColor = Color.Black, + NewColor = foreColor + }; + ColorMap cm2 = new ColorMap + { + OldColor = Color.White, + NewColor = backColor + }; attrs.SetRemapTable(new ColorMap[2] { cm1, cm2 }, ColorAdjustType.Bitmap); graphics.DrawImage(bitmap, new Rectangle(x, y, width, height), 0, 0, width, height, GraphicsUnit.Pixel, attrs, null, IntPtr.Zero); } @@ -1653,9 +1699,11 @@ internal static void DrawImageReplaceColor(Graphics g, Image image, Rectangle de { ImageAttributes attrs = new ImageAttributes(); - ColorMap cm = new ColorMap(); - cm.OldColor = oldColor; - cm.NewColor = newColor; + ColorMap cm = new ColorMap + { + OldColor = oldColor, + NewColor = newColor + }; attrs.SetRemapTable(new ColorMap[] { cm }, ColorAdjustType.Bitmap); @@ -2799,22 +2847,23 @@ private static ColorMatrix RemapBlackAndWhitePreserveTransparentMatrix(Color rep // | B B B 0 1 | // | r g b | - ColorMatrix matrix = new ColorMatrix(); - - matrix.Matrix00 = -normBlackRed; - matrix.Matrix01 = -normBlackGreen; - matrix.Matrix02 = -normBlackBlue; + ColorMatrix matrix = new ColorMatrix + { + Matrix00 = -normBlackRed, + Matrix01 = -normBlackGreen, + Matrix02 = -normBlackBlue, - matrix.Matrix10 = normWhiteRed; - matrix.Matrix11 = normWhiteGreen; - matrix.Matrix12 = normWhiteBlue; + Matrix10 = normWhiteRed, + Matrix11 = normWhiteGreen, + Matrix12 = normWhiteBlue, - matrix.Matrix33 = 1.0f; + Matrix33 = 1.0f, - matrix.Matrix40 = normBlackRed; - matrix.Matrix41 = normBlackGreen; - matrix.Matrix42 = normBlackBlue; - matrix.Matrix44 = 1.0f; + Matrix40 = normBlackRed, + Matrix41 = normBlackGreen, + Matrix42 = normBlackBlue, + Matrix44 = 1.0f + }; return matrix; } @@ -2903,9 +2952,11 @@ internal static TextFormatFlags TranslateLineAlignmentForGDI(ContentAlignment al internal static StringFormat StringFormatForAlignment(ContentAlignment align) { - StringFormat output = new StringFormat(); - output.Alignment = TranslateAlignment(align); - output.LineAlignment = TranslateLineAlignment(align); + StringFormat output = new StringFormat + { + Alignment = TranslateAlignment(align), + LineAlignment = TranslateLineAlignment(align) + }; return output; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs index defdd4cc70e..5ec1e294222 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs @@ -4737,11 +4737,13 @@ internal void OnRowHeightChanged(DataGridRow row) int cy = GetRowTop(row.RowNumber); if (cy > 0) { - Rectangle refresh = new Rectangle(); - refresh.Y = cy; - refresh.X = layout.Inside.X; - refresh.Width = layout.Inside.Width; - refresh.Height = layout.Inside.Bottom - cy; + Rectangle refresh = new Rectangle + { + Y = cy, + X = layout.Inside.X, + Width = layout.Inside.Width, + Height = layout.Inside.Bottom - cy + }; Invalidate(refresh); } } @@ -5633,10 +5635,12 @@ private void ComputeLayout() // Important since all of the visibility flags will move // to the new layout here. - LayoutData newLayout = new LayoutData(layout); + LayoutData newLayout = new LayoutData(layout) + { - // Inside - newLayout.Inside = ClientRectangle; + // Inside + Inside = ClientRectangle + }; Rectangle inside = newLayout.Inside; int borderWidth = BorderWidth; inside.Inflate(-borderWidth, -borderWidth); @@ -6055,20 +6059,22 @@ private DataGridState CreateChildState(string relationName, DataGridRow source) private LayoutData CreateInitialLayoutState() { Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: CreateInitialLayoutState"); - LayoutData newLayout = new LayoutData(); - newLayout.Inside = new Rectangle(); - newLayout.TopLeftHeader = new Rectangle(); - newLayout.ColumnHeaders = new Rectangle(); - newLayout.RowHeaders = new Rectangle(); - newLayout.Data = new Rectangle(); - newLayout.Caption = new Rectangle(); - newLayout.ParentRows = new Rectangle(); - newLayout.ResizeBoxRect = new Rectangle(); - newLayout.ColumnHeadersVisible = true; - newLayout.RowHeadersVisible = true; - newLayout.CaptionVisible = defaultCaptionVisible; - newLayout.ParentRowsVisible = defaultParentRowsVisible; - newLayout.ClientRectangle = ClientRectangle; + LayoutData newLayout = new LayoutData + { + Inside = new Rectangle(), + TopLeftHeader = new Rectangle(), + ColumnHeaders = new Rectangle(), + RowHeaders = new Rectangle(), + Data = new Rectangle(), + Caption = new Rectangle(), + ParentRows = new Rectangle(), + ResizeBoxRect = new Rectangle(), + ColumnHeadersVisible = true, + RowHeadersVisible = true, + CaptionVisible = defaultCaptionVisible, + ParentRowsVisible = defaultParentRowsVisible, + ClientRectangle = ClientRectangle + }; return newLayout; } @@ -6825,11 +6831,13 @@ public Rectangle GetCellBounds(DataGridCell dgc) internal Rectangle GetRowBounds(DataGridRow row) { - Rectangle rowBounds = new Rectangle(); - rowBounds.Y = GetRowTop(row.RowNumber); - rowBounds.X = layout.Data.X; - rowBounds.Height = row.Height; - rowBounds.Width = layout.Data.Width; + Rectangle rowBounds = new Rectangle + { + Y = GetRowTop(row.RowNumber), + X = layout.Data.X, + Height = row.Height, + Width = layout.Data.Width + }; return rowBounds; } @@ -6991,10 +6999,12 @@ internal void InvalidateColumn(int column) if (column < firstVisibleCol || column > firstVisibleCol + numVisibleCols - 1) return; - Rectangle columnArea = new Rectangle(); - columnArea.Height = layout.Data.Height; - columnArea.Width = gridColumns[column].Width; - columnArea.Y = layout.Data.Y; + Rectangle columnArea = new Rectangle + { + Height = layout.Data.Height, + Width = gridColumns[column].Width, + Y = layout.Data.Y + }; int x = layout.Data.X - negOffset; int gridColumnsCount = gridColumns.Count; @@ -7053,11 +7063,13 @@ private void InvalidateRowHeader(int rowNumber) if (!layout.RowHeadersVisible) return; - Rectangle invalid = new Rectangle(); - invalid.Y = GetRowTop(rowNumber); - invalid.X = layout.RowHeaders.X; - invalid.Width = layout.RowHeaders.Width; - invalid.Height = DataGridRows[rowNumber].Height; + Rectangle invalid = new Rectangle + { + Y = GetRowTop(rowNumber), + X = layout.RowHeaders.X, + Width = layout.RowHeaders.Width, + Height = DataGridRows[rowNumber].Height + }; Invalidate(invalid); } } @@ -7452,8 +7464,10 @@ internal void NavigateTo(string relationName, DataGridRow source, bool fromRow) // Preserve our current state // we need to do this after the EndCurrentEdit, otherwise the // DataGridState will get the listChanged event from the EndCurrentEdit - DataGridState dgs = new DataGridState(this); - dgs.LinkingRow = source; + DataGridState dgs = new DataGridState(this) + { + LinkingRow = source + }; // we need to update the Position in the ListManager // ( the RelatedListManager uses only the position in the parentManager diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs index c778930af97..a1c2accc21c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs @@ -419,8 +419,10 @@ protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyMan if (IsReadOnly() && isSelected && source.Position == rowNum) { bounds.Inflate(-1, -1); - System.Drawing.Pen pen = new System.Drawing.Pen(selectionBrush); - pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash; + System.Drawing.Pen pen = new System.Drawing.Pen(selectionBrush) + { + DashStyle = System.Drawing.Drawing2D.DashStyle.Dash + }; g.DrawRectangle(pen, bounds); pen.Dispose(); // restore the bounds rectangle diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs index 13647836c2d..15e1bff72a4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs @@ -66,17 +66,19 @@ internal AccessibleObject ParentRowAccessibleObject public object Clone() { - DataGridState dgs = new DataGridState(); - dgs.DataGridRows = DataGridRows; - dgs.DataSource = DataSource; - dgs.DataMember = DataMember; - dgs.FirstVisibleRow = FirstVisibleRow; - dgs.FirstVisibleCol = FirstVisibleCol; - dgs.CurrentRow = CurrentRow; - dgs.CurrentCol = CurrentCol; - dgs.GridColumnStyles = GridColumnStyles; - dgs.ListManager = ListManager; - dgs.DataGrid = DataGrid; + DataGridState dgs = new DataGridState + { + DataGridRows = DataGridRows, + DataSource = DataSource, + DataMember = DataMember, + FirstVisibleRow = FirstVisibleRow, + FirstVisibleCol = FirstVisibleCol, + CurrentRow = CurrentRow, + CurrentCol = CurrentCol, + GridColumnStyles = GridColumnStyles, + ListManager = ListManager, + DataGrid = DataGrid + }; return dgs; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs index c290be5a10c..b4a471ac03a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs @@ -852,8 +852,10 @@ private Rectangle ComputeRelationshipRect() { Debug.WriteLineIf(CompModSwitches.DGRelationShpRowLayout.TraceVerbose, "GetRelationshipRect grinding away"); Graphics g = DataGrid.CreateGraphicsInternal(); - relationshipRect = new Rectangle(); - relationshipRect.X = 0; //indentWidth; + relationshipRect = new Rectangle + { + X = 0 //indentWidth; + }; // relationshipRect.Y = base.Height - BorderWidth; // Determine the width of the widest relationship name diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs index 7858751988b..f5f74d94906 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs @@ -81,11 +81,13 @@ public DataGridTextBoxColumn(PropertyDescriptor prop, string format) : this(prop ] public DataGridTextBoxColumn(PropertyDescriptor prop, string format, bool isDefault) : base(prop, isDefault) { - edit = new DataGridTextBox(); - edit.BorderStyle = BorderStyle.None; - edit.Multiline = true; - edit.AcceptsReturn = true; - edit.Visible = false; + edit = new DataGridTextBox + { + BorderStyle = BorderStyle.None, + Multiline = true, + AcceptsReturn = true, + Visible = false + }; Format = format; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs index 91fc2adea50..f23f51fa944 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs @@ -34,14 +34,18 @@ public void CreateToolTipHandle() { if (tipWindow == null || tipWindow.Handle == IntPtr.Zero) { - NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); - icc.dwICC = NativeMethods.ICC_TAB_CLASSES; + NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX + { + dwICC = NativeMethods.ICC_TAB_CLASSES + }; icc.dwSize = Marshal.SizeOf(icc); SafeNativeMethods.InitCommonControlsEx(icc); - CreateParams cparams = new CreateParams(); - cparams.Parent = dataGrid.Handle; - cparams.ClassName = NativeMethods.TOOLTIPS_CLASS; - cparams.Style = NativeMethods.TTS_ALWAYSTIP; + CreateParams cparams = new CreateParams + { + Parent = dataGrid.Handle, + ClassName = NativeMethods.TOOLTIPS_CLASS, + Style = NativeMethods.TTS_ALWAYSTIP + }; tipWindow = new NativeWindow(); tipWindow.CreateHandle(cparams); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridView.cs index 668ec29b7fe..8862052d073 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridView.cs @@ -480,13 +480,15 @@ public DataGridView() clipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithAutoHeaderText; - layout = new LayoutData(); - layout.TopLeftHeader = Rectangle.Empty; - layout.ColumnHeaders = Rectangle.Empty; - layout.RowHeaders = Rectangle.Empty; - layout.ColumnHeadersVisible = true; - layout.RowHeadersVisible = true; - layout.ClientRectangle = ClientRectangle; + layout = new LayoutData + { + TopLeftHeader = Rectangle.Empty, + ColumnHeaders = Rectangle.Empty, + RowHeaders = Rectangle.Empty, + ColumnHeadersVisible = true, + RowHeadersVisible = true, + ClientRectangle = ClientRectangle + }; scrollBars = ScrollBars.Both; @@ -616,19 +618,23 @@ public virtual DataGridViewAdvancedBorderStyle AdjustedTopLeftHeaderBorderStyle { case DataGridViewAdvancedCellBorderStyle.OutsetDouble: case DataGridViewAdvancedCellBorderStyle.OutsetPartial: - dgvabs = new DataGridViewAdvancedBorderStyle(); - dgvabs.LeftInternal = RightToLeftInternal ? DataGridViewAdvancedCellBorderStyle.Outset : DataGridViewAdvancedCellBorderStyle.OutsetDouble; - dgvabs.RightInternal = RightToLeftInternal ? DataGridViewAdvancedCellBorderStyle.OutsetDouble : DataGridViewAdvancedCellBorderStyle.Outset; - dgvabs.TopInternal = DataGridViewAdvancedCellBorderStyle.OutsetDouble; - dgvabs.BottomInternal = DataGridViewAdvancedCellBorderStyle.Outset; + dgvabs = new DataGridViewAdvancedBorderStyle + { + LeftInternal = RightToLeftInternal ? DataGridViewAdvancedCellBorderStyle.Outset : DataGridViewAdvancedCellBorderStyle.OutsetDouble, + RightInternal = RightToLeftInternal ? DataGridViewAdvancedCellBorderStyle.OutsetDouble : DataGridViewAdvancedCellBorderStyle.Outset, + TopInternal = DataGridViewAdvancedCellBorderStyle.OutsetDouble, + BottomInternal = DataGridViewAdvancedCellBorderStyle.Outset + }; break; case DataGridViewAdvancedCellBorderStyle.InsetDouble: - dgvabs = new DataGridViewAdvancedBorderStyle(); - dgvabs.LeftInternal = RightToLeftInternal ? DataGridViewAdvancedCellBorderStyle.Inset : DataGridViewAdvancedCellBorderStyle.InsetDouble; - dgvabs.RightInternal = RightToLeftInternal ? DataGridViewAdvancedCellBorderStyle.InsetDouble : DataGridViewAdvancedCellBorderStyle.Inset; - dgvabs.TopInternal = DataGridViewAdvancedCellBorderStyle.InsetDouble; - dgvabs.BottomInternal = DataGridViewAdvancedCellBorderStyle.Inset; + dgvabs = new DataGridViewAdvancedBorderStyle + { + LeftInternal = RightToLeftInternal ? DataGridViewAdvancedCellBorderStyle.Inset : DataGridViewAdvancedCellBorderStyle.InsetDouble, + RightInternal = RightToLeftInternal ? DataGridViewAdvancedCellBorderStyle.InsetDouble : DataGridViewAdvancedCellBorderStyle.Inset, + TopInternal = DataGridViewAdvancedCellBorderStyle.InsetDouble, + BottomInternal = DataGridViewAdvancedCellBorderStyle.Inset + }; break; case DataGridViewAdvancedCellBorderStyle.NotSet: @@ -1799,14 +1805,16 @@ private DataGridViewCellStyle DefaultColumnHeadersDefaultCellStyle { get { - DataGridViewCellStyle defaultStyle = new DataGridViewCellStyle(); - defaultStyle.BackColor = DefaultHeadersBackBrush.Color; - defaultStyle.ForeColor = DefaultForeBrush.Color; - defaultStyle.SelectionBackColor = DefaultSelectionBackBrush.Color; - defaultStyle.SelectionForeColor = DefaultSelectionForeBrush.Color; - defaultStyle.Font = base.Font; - defaultStyle.AlignmentInternal = DataGridViewContentAlignment.MiddleLeft; - defaultStyle.WrapModeInternal = DataGridViewTriState.True; + DataGridViewCellStyle defaultStyle = new DataGridViewCellStyle + { + BackColor = DefaultHeadersBackBrush.Color, + ForeColor = DefaultForeBrush.Color, + SelectionBackColor = DefaultSelectionBackBrush.Color, + SelectionForeColor = DefaultSelectionForeBrush.Color, + Font = base.Font, + AlignmentInternal = DataGridViewContentAlignment.MiddleLeft, + WrapModeInternal = DataGridViewTriState.True + }; defaultStyle.AddScope(this, DataGridViewCellStyleScopes.ColumnHeaders); dataGridViewState1[DATAGRIDVIEWSTATE1_ambientColumnHeadersFont] = true; @@ -2319,8 +2327,10 @@ public DataGridViewCellStyle DefaultCellStyle defaultCellStyle.Alignment == DataGridViewContentAlignment.NotSet || defaultCellStyle.WrapMode == DataGridViewTriState.NotSet) { - DataGridViewCellStyle defaultCellStyleTmp = new DataGridViewCellStyle(defaultCellStyle); - defaultCellStyleTmp.Scope = DataGridViewCellStyleScopes.None; + DataGridViewCellStyle defaultCellStyleTmp = new DataGridViewCellStyle(defaultCellStyle) + { + Scope = DataGridViewCellStyleScopes.None + }; if (defaultCellStyle.BackColor == Color.Empty) { defaultCellStyleTmp.BackColor = DefaultBackBrush.Color; @@ -2381,14 +2391,16 @@ private DataGridViewCellStyle DefaultDefaultCellStyle { get { - DataGridViewCellStyle defaultCellStyle = new DataGridViewCellStyle(); - defaultCellStyle.BackColor = DefaultBackBrush.Color; - defaultCellStyle.ForeColor = base.ForeColor; - defaultCellStyle.SelectionBackColor = DefaultSelectionBackBrush.Color; - defaultCellStyle.SelectionForeColor = DefaultSelectionForeBrush.Color; - defaultCellStyle.Font = base.Font; - defaultCellStyle.AlignmentInternal = DataGridViewContentAlignment.MiddleLeft; - defaultCellStyle.WrapModeInternal = DataGridViewTriState.False; + DataGridViewCellStyle defaultCellStyle = new DataGridViewCellStyle + { + BackColor = DefaultBackBrush.Color, + ForeColor = base.ForeColor, + SelectionBackColor = DefaultSelectionBackBrush.Color, + SelectionForeColor = DefaultSelectionForeBrush.Color, + Font = base.Font, + AlignmentInternal = DataGridViewContentAlignment.MiddleLeft, + WrapModeInternal = DataGridViewTriState.False + }; defaultCellStyle.AddScope(this, DataGridViewCellStyleScopes.DataGridView); dataGridViewState1[DATAGRIDVIEWSTATE1_ambientFont] = true; @@ -2436,14 +2448,16 @@ private DataGridViewCellStyle DefaultRowHeadersDefaultCellStyle { get { - DataGridViewCellStyle defaultStyle = new DataGridViewCellStyle(); - defaultStyle.BackColor = DefaultHeadersBackBrush.Color; - defaultStyle.ForeColor = DefaultForeBrush.Color; - defaultStyle.SelectionBackColor = DefaultSelectionBackBrush.Color; - defaultStyle.SelectionForeColor = DefaultSelectionForeBrush.Color; - defaultStyle.Font = base.Font; - defaultStyle.AlignmentInternal = DataGridViewContentAlignment.MiddleLeft; - defaultStyle.WrapModeInternal = DataGridViewTriState.True; + DataGridViewCellStyle defaultStyle = new DataGridViewCellStyle + { + BackColor = DefaultHeadersBackBrush.Color, + ForeColor = DefaultForeBrush.Color, + SelectionBackColor = DefaultSelectionBackBrush.Color, + SelectionForeColor = DefaultSelectionForeBrush.Color, + Font = base.Font, + AlignmentInternal = DataGridViewContentAlignment.MiddleLeft, + WrapModeInternal = DataGridViewTriState.True + }; defaultStyle.AddScope(this, DataGridViewCellStyleScopes.RowHeaders); dataGridViewState1[DATAGRIDVIEWSTATE1_ambientRowHeadersFont] = true; @@ -2629,8 +2643,10 @@ public Panel EditingPanel { if (editingPanel == null) { - editingPanel = new DataGridViewEditingPanel(this); - editingPanel.AccessibleName = string.Format(SR.DataGridView_AccEditingPanelAccName); + editingPanel = new DataGridViewEditingPanel(this) + { + AccessibleName = string.Format(SR.DataGridView_AccEditingPanelAccName) + }; } return editingPanel; } @@ -2737,8 +2753,10 @@ private Point FirstDisplayedCellAddress { get { - Point ptFirstDisplayedCellAddress = new Point(-1, -1); - ptFirstDisplayedCellAddress.Y = Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen); + Point ptFirstDisplayedCellAddress = new Point(-1, -1) + { + Y = Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen) + }; if (ptFirstDisplayedCellAddress.Y == -1) { Debug.Assert(displayedBandsInfo.NumTotallyDisplayedFrozenRows == 0); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAdvancedBorderStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAdvancedBorderStyle.cs index f2ad6825083..22d4466d502 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAdvancedBorderStyle.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAdvancedBorderStyle.cs @@ -320,12 +320,14 @@ public override string ToString() object ICloneable.Clone() { - DataGridViewAdvancedBorderStyle dgvabs = new DataGridViewAdvancedBorderStyle(owner, banned1, banned2, banned3); - dgvabs.all = all; - dgvabs.top = top; - dgvabs.right = right; - dgvabs.bottom = bottom; - dgvabs.left = left; + DataGridViewAdvancedBorderStyle dgvabs = new DataGridViewAdvancedBorderStyle(owner, banned1, banned2, banned3) + { + all = all, + top = top, + right = right, + bottom = bottom, + left = left + }; return dgvabs; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonColumn.cs index 363c9de2edf..e56ba37bac8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonColumn.cs @@ -25,8 +25,10 @@ public class DataGridViewButtonColumn : DataGridViewColumn public DataGridViewButtonColumn() : base(new DataGridViewButtonCell()) { - DataGridViewCellStyle defaultCellStyle = new DataGridViewCellStyle(); - defaultCellStyle.AlignmentInternal = DataGridViewContentAlignment.MiddleCenter; + DataGridViewCellStyle defaultCellStyle = new DataGridViewCellStyle + { + AlignmentInternal = DataGridViewContentAlignment.MiddleCenter + }; DefaultCellStyle = defaultCellStyle; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs index 9070ce485de..ae4d22f64a1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs @@ -1008,9 +1008,10 @@ public virtual DataGridViewAdvancedBorderStyle AdjustCellBorderStyle(DataGridVie protected virtual Rectangle BorderWidths(DataGridViewAdvancedBorderStyle advancedBorderStyle) { - Rectangle rect = new Rectangle(); - - rect.X = (advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.None) ? 0 : 1; + Rectangle rect = new Rectangle + { + X = (advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.None) ? 0 : 1 + }; if (advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.OutsetDouble || advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.InsetDouble) { rect.X++; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxColumn.cs index c8482392dd3..ebd3cdc1612 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxColumn.cs @@ -25,8 +25,10 @@ public DataGridViewCheckBoxColumn() : this(false) public DataGridViewCheckBoxColumn(bool threeState) : base(new DataGridViewCheckBoxCell(threeState)) { - DataGridViewCellStyle defaultCellStyle = new DataGridViewCellStyle(); - defaultCellStyle.AlignmentInternal = DataGridViewContentAlignment.MiddleCenter; + DataGridViewCellStyle defaultCellStyle = new DataGridViewCellStyle + { + AlignmentInternal = DataGridViewContentAlignment.MiddleCenter + }; if (threeState) { defaultCellStyle.NullValue = CheckState.Indeterminate; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs index f15037b6946..fd3c8e605ec 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs @@ -218,9 +218,11 @@ internal int ActualDisplayIndexToColumnIndex(int actualDisplayIndex, DataGridVie [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual int Add(string columnName, string headerText) { - DataGridViewTextBoxColumn dataGridViewTextBoxColumn = new DataGridViewTextBoxColumn(); - dataGridViewTextBoxColumn.Name = columnName; - dataGridViewTextBoxColumn.HeaderText = headerText; + DataGridViewTextBoxColumn dataGridViewTextBoxColumn = new DataGridViewTextBoxColumn + { + Name = columnName, + HeaderText = headerText + }; return Add(dataGridViewTextBoxColumn); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageColumn.cs index 486fe93f994..133596a9a54 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageColumn.cs @@ -30,8 +30,10 @@ public DataGridViewImageColumn() : this(false /*valuesAreIcons*/) public DataGridViewImageColumn(bool valuesAreIcons) : base(new DataGridViewImageCell(valuesAreIcons)) { - DataGridViewCellStyle defaultCellStyle = new DataGridViewCellStyle(); - defaultCellStyle.AlignmentInternal = DataGridViewContentAlignment.MiddleCenter; + DataGridViewCellStyle defaultCellStyle = new DataGridViewCellStyle + { + AlignmentInternal = DataGridViewContentAlignment.MiddleCenter + }; if (valuesAreIcons) { defaultCellStyle.NullValue = DataGridViewImageCell.ErrorIcon; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs index f87559e22cb..58973f34795 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs @@ -3817,8 +3817,10 @@ private DataGridViewDataErrorEventArgs CommitEdit(ref DataGridViewCell dataGridV ptCurrentCell.Y, // null, // null, - context); - dgvdee.Cancel = true; + context) + { + Cancel = true + }; return dgvdee; } @@ -3866,8 +3868,10 @@ private DataGridViewDataErrorEventArgs CommitEdit(ref DataGridViewCell dataGridV DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs(null, ptCurrentCell.X, ptCurrentCell.Y, - context); - dgvdee.Cancel = true; + context) + { + Cancel = true + }; return dgvdee; } } @@ -3896,8 +3900,10 @@ private DataGridViewDataErrorEventArgs CommitEdit(ref DataGridViewCell dataGridV ptCurrentCell.Y, // dataGridViewCurrentCell.Value, // formattedValue, - context); - dgvdee.Cancel = true; + context) + { + Cancel = true + }; OnDataErrorInternal(dgvdee); return dgvdee; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewToolTip.cs index 5f0faf53bc7..125006a8a25 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewToolTip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewToolTip.cs @@ -47,12 +47,14 @@ public void Activate(bool activate) // Create the tool tip handle on demand. if (activate && toolTip == null) { - toolTip = new ToolTip(); - toolTip.ShowAlways = true; - toolTip.InitialDelay = 0; - toolTip.UseFading = false; - toolTip.UseAnimation = false; - toolTip.AutoPopDelay = 0; + toolTip = new ToolTip + { + ShowAlways = true, + InitialDelay = 0, + UseFading = false, + UseAnimation = false, + AutoPopDelay = 0 + }; } if (activate) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs index 4a927a39945..8951ac3e366 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs @@ -1174,12 +1174,14 @@ public FormatEnumerator(IDataObject parent, FORMATETC[] formats) { FORMATETC currentFormat = formats[i]; - FORMATETC temp = new FORMATETC(); - temp.cfFormat = currentFormat.cfFormat; - temp.dwAspect = currentFormat.dwAspect; - temp.ptd = currentFormat.ptd; - temp.lindex = currentFormat.lindex; - temp.tymed = currentFormat.tymed; + FORMATETC temp = new FORMATETC + { + cfFormat = currentFormat.cfFormat, + dwAspect = currentFormat.dwAspect, + ptd = currentFormat.ptd, + lindex = currentFormat.lindex, + tymed = currentFormat.tymed + }; this.formats.Add(temp); } } @@ -1207,11 +1209,13 @@ public FormatEnumerator(IDataObject parent, string[] formats) for (int i = 0; i < formats.Length; i++) { string format = formats[i]; - FORMATETC temp = new FORMATETC(); - temp.cfFormat = unchecked((short)(ushort)(DataFormats.GetFormat(format).Id)); - temp.dwAspect = DVASPECT.DVASPECT_CONTENT; - temp.ptd = IntPtr.Zero; - temp.lindex = -1; + FORMATETC temp = new FORMATETC + { + cfFormat = unchecked((short)(ushort)(DataFormats.GetFormat(format).Id)), + dwAspect = DVASPECT.DVASPECT_CONTENT, + ptd = IntPtr.Zero, + lindex = -1 + }; if (format.Equals(DataFormats.Bitmap)) { @@ -1842,10 +1846,12 @@ public virtual bool GetDataPresent(Type format) private bool GetDataPresentInner(string format) { Debug.Assert(innerData != null, "You must have an innerData on all DataObjects"); - FORMATETC formatetc = new FORMATETC(); - formatetc.cfFormat = unchecked((short)(ushort)(DataFormats.GetFormat(format).Id)); - formatetc.dwAspect = DVASPECT.DVASPECT_CONTENT; - formatetc.lindex = -1; + FORMATETC formatetc = new FORMATETC + { + cfFormat = unchecked((short)(ushort)(DataFormats.GetFormat(format).Id)), + dwAspect = DVASPECT.DVASPECT_CONTENT, + lindex = -1 + }; for (int i = 0; i < ALLOWED_TYMEDS.Length; i++) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs index 32b26eeb868..429f3958e0f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs @@ -1136,8 +1136,10 @@ protected override void CreateHandle() try { - NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); - icc.dwICC = NativeMethods.ICC_DATE_CLASSES; + NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX + { + dwICC = NativeMethods.ICC_DATE_CLASSES + }; SafeNativeMethods.InitCommonControlsEx(icc); } finally @@ -1767,15 +1769,17 @@ protected override void WndProc(ref Message m) /// internal static NativeMethods.SYSTEMTIME DateTimeToSysTime(DateTime time) { - NativeMethods.SYSTEMTIME sys = new NativeMethods.SYSTEMTIME(); - sys.wYear = (short)time.Year; - sys.wMonth = (short)time.Month; - sys.wDayOfWeek = (short)time.DayOfWeek; - sys.wDay = (short)time.Day; - sys.wHour = (short)time.Hour; - sys.wMinute = (short)time.Minute; - sys.wSecond = (short)time.Second; - sys.wMilliseconds = 0; + NativeMethods.SYSTEMTIME sys = new NativeMethods.SYSTEMTIME + { + wYear = (short)time.Year, + wMonth = (short)time.Month, + wDayOfWeek = (short)time.DayOfWeek, + wDay = (short)time.Day, + wHour = (short)time.Hour, + wMinute = (short)time.Minute, + wSecond = (short)time.Second, + wMilliseconds = 0 + }; return sys; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs index 55b94c77ad7..6e249a2bd63 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs @@ -226,15 +226,20 @@ private void OnConfigureUI() applyButton = new Button(); helpButton = new Button(); - selectorImageList = new ImageList(); - selectorImageList.ImageSize = new Size(16, 16); - selector = new PageSelector(); - - selector.ImageList = selectorImageList; + selectorImageList = new ImageList + { + ImageSize = new Size(16, 16) + }; + selector = new PageSelector + { + ImageList = selectorImageList + }; selector.AfterSelect += new TreeViewEventHandler(OnSelChangeSelector); - Label grayStrip = new Label(); - grayStrip.BackColor = SystemColors.ControlDark; + Label grayStrip = new Label + { + BackColor = SystemColors.ControlDark + }; int selectorWidth = MIN_SELECTOR_WIDTH; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DropTarget.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DropTarget.cs index 23cc478d95b..444bf3cf6fd 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DropTarget.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DropTarget.cs @@ -62,9 +62,11 @@ int UnsafeNativeMethods.IOleDropTarget.OleDragEnter(object pDataObj, int grfKeyS ref int pdwEffect) { Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "OleDragEnter recieved"); - NativeMethods.POINTL ptl = new NativeMethods.POINTL(); - ptl.x = pt.x; - ptl.y = pt.y; + NativeMethods.POINTL ptl = new NativeMethods.POINTL + { + x = pt.x, + y = pt.y + }; Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "\t" + (ptl.x) + "," + (ptl.y)); Debug.Assert(pDataObj != null, "OleDragEnter didn't give us a valid data object."); DragEventArgs drgevent = CreateDragEventArgs(pDataObj, grfKeyState, ptl, pdwEffect); @@ -84,9 +86,11 @@ int UnsafeNativeMethods.IOleDropTarget.OleDragEnter(object pDataObj, int grfKeyS int UnsafeNativeMethods.IOleDropTarget.OleDragOver(int grfKeyState, UnsafeNativeMethods.POINTSTRUCT pt, ref int pdwEffect) { Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "OleDragOver recieved"); - NativeMethods.POINTL ptl = new NativeMethods.POINTL(); - ptl.x = pt.x; - ptl.y = pt.y; + NativeMethods.POINTL ptl = new NativeMethods.POINTL + { + x = pt.x, + y = pt.y + }; Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "\t" + (ptl.x) + "," + (ptl.y)); DragEventArgs drgevent = CreateDragEventArgs(null, grfKeyState, ptl, pdwEffect); owner.OnDragOver(drgevent); @@ -103,9 +107,11 @@ int UnsafeNativeMethods.IOleDropTarget.OleDragLeave() int UnsafeNativeMethods.IOleDropTarget.OleDrop(object pDataObj, int grfKeyState, UnsafeNativeMethods.POINTSTRUCT pt, ref int pdwEffect) { Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "OleDrop recieved"); - NativeMethods.POINTL ptl = new NativeMethods.POINTL(); - ptl.x = pt.x; - ptl.y = pt.y; + NativeMethods.POINTL ptl = new NativeMethods.POINTL + { + x = pt.x, + y = pt.y + }; Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "\t" + (ptl.x) + "," + (ptl.y)); DragEventArgs drgevent = CreateDragEventArgs(pDataObj, grfKeyState, ptl, pdwEffect); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs index 04c1f490ac8..09d235c5dab 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs @@ -992,26 +992,32 @@ bool EnsureCreated() { return false; } - CreateParams cparams = new CreateParams(); - cparams.Caption = string.Empty; - cparams.Style = NativeMethods.WS_VISIBLE | NativeMethods.WS_CHILD; - cparams.ClassStyle = NativeMethods.CS_DBLCLKS; - cparams.X = 0; - cparams.Y = 0; - cparams.Width = 0; - cparams.Height = 0; - cparams.Parent = parent.Handle; + CreateParams cparams = new CreateParams + { + Caption = string.Empty, + Style = NativeMethods.WS_VISIBLE | NativeMethods.WS_CHILD, + ClassStyle = NativeMethods.CS_DBLCLKS, + X = 0, + Y = 0, + Width = 0, + Height = 0, + Parent = parent.Handle + }; CreateHandle(cparams); - NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); - icc.dwICC = NativeMethods.ICC_TAB_CLASSES; + NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX + { + dwICC = NativeMethods.ICC_TAB_CLASSES + }; icc.dwSize = Marshal.SizeOf(icc); SafeNativeMethods.InitCommonControlsEx(icc); - cparams = new CreateParams(); - cparams.Parent = Handle; - cparams.ClassName = NativeMethods.TOOLTIPS_CLASS; - cparams.Style = NativeMethods.TTS_ALWAYSTIP; + cparams = new CreateParams + { + Parent = Handle, + ClassName = NativeMethods.TOOLTIPS_CLASS, + Style = NativeMethods.TTS_ALWAYSTIP + }; tipWindow = new NativeWindow(); tipWindow.CreateHandle(cparams); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FolderBrowserDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FolderBrowserDialog.cs index 605da48dfed..1cb9e21d610 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FolderBrowserDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FolderBrowserDialog.cs @@ -264,15 +264,17 @@ private unsafe bool RunDialogOld(IntPtr hWndOwner) { fixed (char* pDisplayName = displayName) { - var bi = new Interop.Shell32.BROWSEINFO(); - bi.pidlRoot = listHandle; - bi.hwndOwner = hWndOwner; - bi.pszDisplayName = pDisplayName; - bi.lpszTitle = _descriptionText; - bi.ulFlags = mergedOptions; - bi.lpfn = callback; - bi.lParam = IntPtr.Zero; - bi.iImage = 0; + var bi = new Interop.Shell32.BROWSEINFO + { + pidlRoot = listHandle, + hwndOwner = hWndOwner, + pszDisplayName = pDisplayName, + lpszTitle = _descriptionText, + ulFlags = mergedOptions, + lpfn = callback, + lParam = IntPtr.Zero, + iImage = 0 + }; // Show the dialog using (CoTaskMemSafeHandle browseHandle = Interop.Shell32.SHBrowseForFolderW(ref bi)) 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 af068140fd3..329f0752d40 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs @@ -1906,8 +1906,10 @@ private MainMenu MergedMenuPrivate return mainMenu; // Create a menu that merges the two and save it for next time. - mergedMenu = new MainMenu(); - mergedMenu.ownerForm = this; + mergedMenu = new MainMenu + { + ownerForm = this + }; mergedMenu.MergeMenu(parentMenu); mergedMenu.MergeMenu(mainMenu); Properties.SetObject(PropMergedMenu, mergedMenu); @@ -2434,8 +2436,10 @@ private HandleRef TaskbarOwner if (ownerWindow.Handle == IntPtr.Zero) { - CreateParams cp = new CreateParams(); - cp.ExStyle = NativeMethods.WS_EX_TOOLWINDOW; + CreateParams cp = new CreateParams + { + ExStyle = NativeMethods.WS_EX_TOOLWINDOW + }; ownerWindow.CreateHandle(cp); } @@ -4968,11 +4972,13 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) bool retValue = false; - NativeMethods.MSG win32Message = new NativeMethods.MSG(); - win32Message.message = msg.Msg; - win32Message.wParam = msg.WParam; - win32Message.lParam = msg.LParam; - win32Message.hwnd = msg.HWnd; + NativeMethods.MSG win32Message = new NativeMethods.MSG + { + message = msg.Msg, + wParam = msg.WParam, + lParam = msg.LParam, + hwnd = msg.HWnd + }; if (ctlClient != null && ctlClient.Handle != IntPtr.Zero && UnsafeNativeMethods.TranslateMDISysAccel(ctlClient.Handle, ref win32Message)) @@ -6221,8 +6227,10 @@ private void UpdateMenuHandles(MainMenu menu, bool forceRedraw) if (dummyMenu == null) { - dummyMenu = new MainMenu(); - dummyMenu.ownerForm = this; + dummyMenu = new MainMenu + { + ownerForm = this + }; Properties.SetObject(PropDummyMenu, dummyMenu); } UnsafeNativeMethods.SendMessage(new HandleRef(ctlClient, ctlClient.Handle), Interop.WindowMessages.WM_MDISETMENU, dummyMenu.Handle, IntPtr.Zero); @@ -6565,8 +6573,10 @@ private void UpdateWindowState() if (IsHandleCreated) { FormWindowState oldState = WindowState; - NativeMethods.WINDOWPLACEMENT wp = new NativeMethods.WINDOWPLACEMENT(); - wp.length = Marshal.SizeOf(); + NativeMethods.WINDOWPLACEMENT wp = new NativeMethods.WINDOWPLACEMENT + { + length = Marshal.SizeOf() + }; UnsafeNativeMethods.GetWindowPlacement(new HandleRef(this, Handle), ref wp); switch (wp.showCmd) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Help.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Help.cs index 8f15a6f18dc..1176820c650 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Help.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Help.cs @@ -439,8 +439,10 @@ private static int MapCommandToHTMLCommand(HelpNavigator command, string param, case HelpNavigator.Find: { - NativeMethods.HH_FTS_QUERY ftsQuery = new NativeMethods.HH_FTS_QUERY(); - ftsQuery.pszSearchQuery = param; + NativeMethods.HH_FTS_QUERY ftsQuery = new NativeMethods.HH_FTS_QUERY + { + pszSearchQuery = param + }; htmlParam = ftsQuery; return HH_DISPLAY_SEARCH; } @@ -460,10 +462,12 @@ private static int MapCommandToHTMLCommand(HelpNavigator command, string param, case HelpNavigator.KeywordIndex: case HelpNavigator.AssociateIndex: { - NativeMethods.HH_AKLINK alink = new NativeMethods.HH_AKLINK(); - alink.pszKeywords = param; - alink.fIndexOnFail = true; - alink.fReserved = false; + NativeMethods.HH_AKLINK alink = new NativeMethods.HH_AKLINK + { + pszKeywords = param, + fIndexOnFail = true, + fReserved = false + }; htmlParam = alink; return (command == HelpNavigator.KeywordIndex) ? HH_KEYWORD_LOOKUP : HH_ALINK_LOOKUP; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs index 6dd72cb641d..bfe6887c4f1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs @@ -418,8 +418,10 @@ public HtmlElement CreateElement(string elementTag) public object InvokeScript(string scriptName, object[] args) { object retVal = null; - NativeMethods.tagDISPPARAMS dp = new NativeMethods.tagDISPPARAMS(); - dp.rgvarg = IntPtr.Zero; + NativeMethods.tagDISPPARAMS dp = new NativeMethods.tagDISPPARAMS + { + rgvarg = IntPtr.Zero + }; try { UnsafeNativeMethods.IDispatch scriptObject = NativeHtmlDocument2.GetScript() as UnsafeNativeMethods.IDispatch; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs index abc130bd610..2c857bb52c1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs @@ -449,8 +449,10 @@ public object InvokeMember(string methodName) public object InvokeMember(string methodName, params object[] parameter) { object retVal = null; - NativeMethods.tagDISPPARAMS dp = new NativeMethods.tagDISPPARAMS(); - dp.rgvarg = IntPtr.Zero; + NativeMethods.tagDISPPARAMS dp = new NativeMethods.tagDISPPARAMS + { + rgvarg = IntPtr.Zero + }; try { UnsafeNativeMethods.IDispatch scriptObject = NativeHtmlElement as UnsafeNativeMethods.IDispatch; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs index 76885166859..457d3d44f13 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs @@ -1340,8 +1340,10 @@ public void Add(string key, Image image) Debug.Assert((Count == imageInfoCollection.Count), "The count of these two collections should be equal."); // Store off the name. - ImageInfo imageInfo = new ImageInfo(); - imageInfo.Name = key; + ImageInfo imageInfo = new ImageInfo + { + Name = key + }; // Add the image to the IList Original original = new Original(image, OriginalOptions.Default); @@ -1357,8 +1359,10 @@ public void Add(string key, Icon icon) Debug.Assert((Count == imageInfoCollection.Count), "The count of these two collections should be equal."); // Store off the name. - ImageInfo imageInfo = new ImageInfo(); - imageInfo.Name = key; + ImageInfo imageInfo = new ImageInfo + { + Name = key + }; // Add the image to the IList Original original = new Original(icon, OriginalOptions.Default); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DockAndAnchorLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DockAndAnchorLayout.cs index 23716a69b2e..692ed090f20 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DockAndAnchorLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DockAndAnchorLayout.cs @@ -644,11 +644,13 @@ private static void UpdateAnchorInfo(IArrangedElement element) Rectangle bounds = GetCachedBounds(element); - AnchorInfo oldAnchorInfo = new AnchorInfo(); - oldAnchorInfo.Left = anchorInfo.Left; - oldAnchorInfo.Top = anchorInfo.Top; - oldAnchorInfo.Right = anchorInfo.Right; - oldAnchorInfo.Bottom = anchorInfo.Bottom; + AnchorInfo oldAnchorInfo = new AnchorInfo + { + Left = anchorInfo.Left, + Top = anchorInfo.Top, + Right = anchorInfo.Right, + Bottom = anchorInfo.Bottom + }; anchorInfo.Left = element.Bounds.Left; anchorInfo.Top = element.Bounds.Top; 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 8686a2c6ef7..2232a835d19 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 @@ -1592,13 +1592,15 @@ internal int RowSpan #if DEBUG public LayoutInfo Clone() { - LayoutInfo clone = new LayoutInfo(_element); - clone.RowStart = RowStart; - clone.ColumnStart = ColumnStart; - clone.RowSpan = RowSpan; - clone.ColumnSpan = ColumnSpan; - clone.RowPosition = RowPosition; - clone.ColumnPosition = ColumnPosition; + LayoutInfo clone = new LayoutInfo(_element) + { + RowStart = RowStart, + ColumnStart = ColumnStart, + RowSpan = RowSpan, + ColumnSpan = ColumnSpan, + RowPosition = RowPosition, + ColumnPosition = ColumnPosition + }; return clone; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs index 761e91400f6..ed3262cc0d8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs @@ -2359,10 +2359,12 @@ public Link Add(int start, int length, object linkData) owner.FocusLink = null; } - Link l = new Link(owner); - l.Start = start; - l.Length = length; - l.LinkData = linkData; + Link l = new Link(owner) + { + Start = start, + Length = length, + LinkData = linkData + }; Add(l); return l; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs index 402ee9fdf6b..29de3965510 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs @@ -435,9 +435,11 @@ public bool BackgroundImageTiled { // Don't call SetBackgroundImage because SetBackgroundImage deletes the existing image // We don't need to delete it and this causes BAD problems w/ the Win32 list view control. - NativeMethods.LVBKIMAGE lvbkImage = new NativeMethods.LVBKIMAGE(); - lvbkImage.xOffset = 0; - lvbkImage.yOffset = 0; + NativeMethods.LVBKIMAGE lvbkImage = new NativeMethods.LVBKIMAGE + { + xOffset = 0, + yOffset = 0 + }; if (BackgroundImageTiled) lvbkImage.ulFlags = NativeMethods.LVBKIF_STYLE_TILE; @@ -1774,8 +1776,10 @@ public Size TileSize { // Get the default value from the ListView // - NativeMethods.LVTILEVIEWINFO tileViewInfo = new NativeMethods.LVTILEVIEWINFO(); - tileViewInfo.dwMask = NativeMethods.LVTVIM_TILESIZE; + NativeMethods.LVTILEVIEWINFO tileViewInfo = new NativeMethods.LVTILEVIEWINFO + { + dwMask = NativeMethods.LVTVIM_TILESIZE + }; UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_GETTILEVIEWINFO, 0, tileViewInfo); return new Size(tileViewInfo.sizeTile.cx, tileViewInfo.sizeTile.cy); } @@ -1801,10 +1805,12 @@ public Size TileSize tileSize = value; if (IsHandleCreated) { - NativeMethods.LVTILEVIEWINFO tileViewInfo = new NativeMethods.LVTILEVIEWINFO(); - tileViewInfo.dwMask = NativeMethods.LVTVIM_TILESIZE; - tileViewInfo.dwFlags = NativeMethods.LVTVIF_FIXEDSIZE; - tileViewInfo.sizeTile = new NativeMethods.SIZE(tileSize.Width, tileSize.Height); + NativeMethods.LVTILEVIEWINFO tileViewInfo = new NativeMethods.LVTILEVIEWINFO + { + dwMask = NativeMethods.LVTVIM_TILESIZE, + dwFlags = NativeMethods.LVTVIF_FIXEDSIZE, + sizeTile = new NativeMethods.SIZE(tileSize.Width, tileSize.Height) + }; bool retval = UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SETTILEVIEWINFO, 0, tileViewInfo); Debug.Assert(retval, "LVM_SETTILEVIEWINFO failed"); if (AutoArrange) @@ -2520,8 +2526,10 @@ protected override void CreateHandle() try { - NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); - icc.dwICC = NativeMethods.ICC_LISTVIEW_CLASSES; + NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX + { + dwICC = NativeMethods.ICC_LISTVIEW_CLASSES + }; SafeNativeMethods.InitCommonControlsEx(icc); } finally @@ -3386,9 +3394,11 @@ internal int GetDisplayIndex(ListViewItem item, int lastIndex) ApplyUpdateCachedItems(); if (IsHandleCreated && !ListViewHandleDestroyed) { - NativeMethods.LVFINDINFO info = new NativeMethods.LVFINDINFO(); - info.lParam = (IntPtr)item.ID; - info.flags = NativeMethods.LVFI_PARAM; + NativeMethods.LVFINDINFO info = new NativeMethods.LVFINDINFO + { + lParam = (IntPtr)item.ID, + flags = NativeMethods.LVFI_PARAM + }; int displayIndex = -1; @@ -3445,10 +3455,11 @@ internal int GetColumnIndex(ColumnHeader ch) /// public ListViewItem GetItemAt(int x, int y) { - NativeMethods.LVHITTESTINFO lvhi = new NativeMethods.LVHITTESTINFO(); - - lvhi.pt_x = x; - lvhi.pt_y = y; + NativeMethods.LVHITTESTINFO lvhi = new NativeMethods.LVHITTESTINFO + { + pt_x = x, + pt_y = y + }; int displayIndex = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_HITTEST, 0, lvhi); @@ -3476,10 +3487,11 @@ internal int GetNativeGroupId(ListViewItem item) internal void GetSubItemAt(int x, int y, out int iItem, out int iSubItem) { - NativeMethods.LVHITTESTINFO lvhi = new NativeMethods.LVHITTESTINFO(); - - lvhi.pt_x = x; - lvhi.pt_y = y; + NativeMethods.LVHITTESTINFO lvhi = new NativeMethods.LVHITTESTINFO + { + pt_x = x, + pt_y = y + }; int index = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SUBITEMHITTEST, 0, lvhi); @@ -3550,8 +3562,10 @@ public Rectangle GetItemRect(int index, ItemBoundsPortion portion) } - NativeMethods.RECT itemrect = new NativeMethods.RECT(); - itemrect.left = (int)portion; + NativeMethods.RECT itemrect = new NativeMethods.RECT + { + left = (int)portion + }; if (unchecked((int)(long)SendMessage(NativeMethods.LVM_GETITEMRECT, index, ref itemrect)) == 0) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); @@ -3573,8 +3587,10 @@ private Rectangle GetItemRectOrEmpty(int index) } - NativeMethods.RECT itemrect = new NativeMethods.RECT(); - itemrect.left = 0; + NativeMethods.RECT itemrect = new NativeMethods.RECT + { + left = 0 + }; if (unchecked((int)(long)SendMessage(NativeMethods.LVM_GETITEMRECT, index, ref itemrect)) == 0) return Rectangle.Empty; @@ -3583,8 +3599,10 @@ private Rectangle GetItemRectOrEmpty(int index) private NativeMethods.LVGROUP GetLVGROUP(ListViewGroup group) { - NativeMethods.LVGROUP lvgroup = new NativeMethods.LVGROUP(); - lvgroup.mask = NativeMethods.LVGF_HEADER | NativeMethods.LVGF_GROUPID | NativeMethods.LVGF_ALIGN; + NativeMethods.LVGROUP lvgroup = new NativeMethods.LVGROUP + { + mask = NativeMethods.LVGF_HEADER | NativeMethods.LVGF_GROUPID | NativeMethods.LVGF_ALIGN + }; // Header // @@ -3649,9 +3667,11 @@ internal Rectangle GetSubItemRect(int itemIndex, int subItemIndex, ItemBoundsPor return Rectangle.Empty; } - NativeMethods.RECT itemrect = new NativeMethods.RECT(); - itemrect.left = (int)portion; - itemrect.top = subItemIndex; + NativeMethods.RECT itemrect = new NativeMethods.RECT + { + left = (int)portion, + top = subItemIndex + }; if (unchecked((int)(long)SendMessage(NativeMethods.LVM_GETSUBITEMRECT, itemIndex, ref itemrect)) == 0) throw new ArgumentOutOfRangeException(nameof(itemIndex), itemIndex, string.Format(SR.InvalidArgument, nameof(itemIndex), itemIndex)); @@ -3676,9 +3696,11 @@ public ListViewHitTestInfo HitTest(int x, int y) return new ListViewHitTestInfo(null /*hitItem*/, null /*hitSubItem*/, ListViewHitTestLocations.None /*hitLocation*/); } - NativeMethods.LVHITTESTINFO lvhi = new NativeMethods.LVHITTESTINFO(); - lvhi.pt_x = x; - lvhi.pt_y = y; + NativeMethods.LVHITTESTINFO lvhi = new NativeMethods.LVHITTESTINFO + { + pt_x = x, + pt_y = y + }; int iItem; @@ -3835,8 +3857,10 @@ internal ColumnHeader InsertColumn(int index, ColumnHeader ch, bool refreshSubIt private int InsertColumnNative(int index, ColumnHeader ch) { - NativeMethods.LVCOLUMN_T lvColumn = new NativeMethods.LVCOLUMN_T(); - lvColumn.mask = NativeMethods.LVCF_FMT | NativeMethods.LVCF_TEXT | NativeMethods.LVCF_WIDTH;// | NativeMethods.LVCF_ORDER | NativeMethods.LVCF_IMAGE; + NativeMethods.LVCOLUMN_T lvColumn = new NativeMethods.LVCOLUMN_T + { + mask = NativeMethods.LVCF_FMT | NativeMethods.LVCF_TEXT | NativeMethods.LVCF_WIDTH// | NativeMethods.LVCF_ORDER | NativeMethods.LVCF_IMAGE; + }; if (ch.OwnerListview != null && ch.ActualImageIndex_Internal != -1) { @@ -3886,9 +3910,11 @@ internal void InsertGroupInListView(int index, ListViewGroup group) for (int i = 0; i < Items.Count; i++) { ListViewItem item = Items[i]; - NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM(); - lvItem.iItem = item.Index; - lvItem.mask = NativeMethods.LVIF_GROUPID; + NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM + { + iItem = item.Index, + mask = NativeMethods.LVIF_GROUPID + }; UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_GETITEM, 0, ref lvItem); Debug.Assert(lvItem.iGroupId != -1, "there is a list view item which is not parented"); } @@ -4835,9 +4861,11 @@ private unsafe void PositionHeader() UnsafeNativeMethods.GetClientRect(new HandleRef(this, Handle), prc); - NativeMethods.HDLAYOUT hd = new NativeMethods.HDLAYOUT(); - hd.prc = prc; - hd.pwpos = pwpos; + NativeMethods.HDLAYOUT hd = new NativeMethods.HDLAYOUT + { + prc = prc, + pwpos = pwpos + }; // get the layout information UnsafeNativeMethods.SendMessage(new HandleRef(this, hdrHWND), NativeMethods.HDM_LAYOUT, 0, ref hd); @@ -5033,9 +5061,11 @@ private void SetBackgroundImage() // needed for OleInitialize Application.OleRequired(); - NativeMethods.LVBKIMAGE lvbkImage = new NativeMethods.LVBKIMAGE(); - lvbkImage.xOffset = 0; - lvbkImage.yOffset = 0; + NativeMethods.LVBKIMAGE lvbkImage = new NativeMethods.LVBKIMAGE + { + xOffset = 0, + yOffset = 0 + }; // first, is there an existing temporary file to delete, remember its name // so that we can delete it if the list control doesn't... @@ -5117,8 +5147,10 @@ internal void SetColumnInfo(int mask, ColumnHeader ch) if (IsHandleCreated) { Debug.Assert((mask & ~(NativeMethods.LVCF_FMT | NativeMethods.LVCF_TEXT | NativeMethods.LVCF_IMAGE)) == 0, "Unsupported mask in setColumnInfo"); - NativeMethods.LVCOLUMN lvColumn = new NativeMethods.LVCOLUMN(); - lvColumn.mask = mask; + NativeMethods.LVCOLUMN lvColumn = new NativeMethods.LVCOLUMN + { + mask = mask + }; if ((mask & NativeMethods.LVCF_IMAGE) != 0 || (mask & NativeMethods.LVCF_FMT) != 0) { @@ -5322,10 +5354,12 @@ internal void SetItemImage(int index, int image) } if (IsHandleCreated) { - NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM(); - lvItem.mask = NativeMethods.LVIF_IMAGE; - lvItem.iItem = index; - lvItem.iImage = image; + NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM + { + mask = NativeMethods.LVIF_IMAGE, + iItem = index, + iImage = image + }; UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SETITEM, 0, ref lvItem); } } @@ -5338,10 +5372,12 @@ internal void SetItemIndentCount(int index, int indentCount) } if (IsHandleCreated) { - NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM(); - lvItem.mask = NativeMethods.LVIF_INDENT; - lvItem.iItem = index; - lvItem.iIndent = indentCount; + NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM + { + mask = NativeMethods.LVIF_INDENT, + iItem = index, + iIndent = indentCount + }; UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SETITEM, 0, ref lvItem); } } @@ -5355,9 +5391,11 @@ internal void SetItemPosition(int index, int x, int y) Debug.Assert(IsHandleCreated, "How did we add items without a handle?"); - NativeMethods.POINT pt = new NativeMethods.POINT(); - pt.x = x; - pt.y = y; + NativeMethods.POINT pt = new NativeMethods.POINT + { + x = x, + y = y + }; UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SETITEMPOSITION32, index, pt); } @@ -5371,10 +5409,12 @@ internal void SetItemState(int index, int state, int mask) if (IsHandleCreated) { - NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM(); - lvItem.mask = NativeMethods.LVIF_STATE; - lvItem.state = state; - lvItem.stateMask = mask; + NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM + { + mask = NativeMethods.LVIF_STATE, + state = state, + stateMask = mask + }; UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_SETITEMSTATE, index, ref lvItem); } } @@ -5644,10 +5684,12 @@ private void UpdateTileView() { Debug.Assert(ComctlSupportsVisualStyles, "this function works only when ComCtl 6.0 and higher is loaded"); Debug.Assert(viewStyle == View.Tile, "this function should be called only in Tile view"); - NativeMethods.LVTILEVIEWINFO tileViewInfo = new NativeMethods.LVTILEVIEWINFO(); - // the tile view info line count - tileViewInfo.dwMask = NativeMethods.LVTVIM_COLUMNS; - tileViewInfo.cLines = columnHeaders != null ? columnHeaders.Length : 0; + NativeMethods.LVTILEVIEWINFO tileViewInfo = new NativeMethods.LVTILEVIEWINFO + { + // the tile view info line count + dwMask = NativeMethods.LVTVIM_COLUMNS, + cLines = columnHeaders != null ? columnHeaders.Length : 0 + }; // the tile view info size tileViewInfo.dwMask |= NativeMethods.LVTVIM_TILESIZE; @@ -5668,10 +5710,11 @@ private void WmNmClick(ref Message m) { Point pos = Cursor.Position; pos = PointToClient(pos); - NativeMethods.LVHITTESTINFO lvhi = new NativeMethods.LVHITTESTINFO(); - - lvhi.pt_x = pos.X; - lvhi.pt_y = pos.Y; + NativeMethods.LVHITTESTINFO lvhi = new NativeMethods.LVHITTESTINFO + { + pt_x = pos.X, + pt_y = pos.Y + }; int displayIndex = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_HITTEST, 0, lvhi); if (displayIndex != -1 && (lvhi.flags & NativeMethods.LVHT_ONITEMSTATEICON) != 0) @@ -5705,10 +5748,11 @@ private void WmNmDblClick(ref Message m) { Point pos = Cursor.Position; pos = PointToClient(pos); - NativeMethods.LVHITTESTINFO lvhi = new NativeMethods.LVHITTESTINFO(); - - lvhi.pt_x = pos.X; - lvhi.pt_y = pos.Y; + NativeMethods.LVHITTESTINFO lvhi = new NativeMethods.LVHITTESTINFO + { + pt_x = pos.X, + pt_y = pos.Y + }; int displayIndex = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_HITTEST, 0, lvhi); if (displayIndex != -1 && (lvhi.flags & NativeMethods.LVHT_ONITEM) != 0) @@ -8253,10 +8297,12 @@ private bool IsValidIndex(int index) /// public virtual ColumnHeader Add(string text, int width, HorizontalAlignment textAlign) { - ColumnHeader columnHeader = new ColumnHeader(); - columnHeader.Text = text; - columnHeader.Width = width; - columnHeader.TextAlign = textAlign; + ColumnHeader columnHeader = new ColumnHeader + { + Text = text, + Width = width, + TextAlign = textAlign + }; return owner.InsertColumn(Count, columnHeader); } @@ -8269,8 +8315,10 @@ public virtual int Add(ColumnHeader value) public virtual ColumnHeader Add(string text) { - ColumnHeader columnHeader = new ColumnHeader(); - columnHeader.Text = text; + ColumnHeader columnHeader = new ColumnHeader + { + Text = text + }; return owner.InsertColumn(Count, columnHeader); } @@ -8278,46 +8326,56 @@ public virtual ColumnHeader Add(string text) public virtual ColumnHeader Add(string text, int width) { - ColumnHeader columnHeader = new ColumnHeader(); - columnHeader.Text = text; - columnHeader.Width = width; + ColumnHeader columnHeader = new ColumnHeader + { + Text = text, + Width = width + }; return owner.InsertColumn(Count, columnHeader); } public virtual ColumnHeader Add(string key, string text) { - ColumnHeader columnHeader = new ColumnHeader(); - columnHeader.Name = key; - columnHeader.Text = text; + ColumnHeader columnHeader = new ColumnHeader + { + Name = key, + Text = text + }; return owner.InsertColumn(Count, columnHeader); } public virtual ColumnHeader Add(string key, string text, int width) { - ColumnHeader columnHeader = new ColumnHeader(); - columnHeader.Name = key; - columnHeader.Text = text; - columnHeader.Width = width; + ColumnHeader columnHeader = new ColumnHeader + { + Name = key, + Text = text, + Width = width + }; return owner.InsertColumn(Count, columnHeader); } public virtual ColumnHeader Add(string key, string text, int width, HorizontalAlignment textAlign, string imageKey) { - ColumnHeader columnHeader = new ColumnHeader(imageKey); - columnHeader.Name = key; - columnHeader.Text = text; - columnHeader.Width = width; - columnHeader.TextAlign = textAlign; + ColumnHeader columnHeader = new ColumnHeader(imageKey) + { + Name = key, + Text = text, + Width = width, + TextAlign = textAlign + }; return owner.InsertColumn(Count, columnHeader); } public virtual ColumnHeader Add(string key, string text, int width, HorizontalAlignment textAlign, int imageIndex) { - ColumnHeader columnHeader = new ColumnHeader(imageIndex); - columnHeader.Name = key; - columnHeader.Text = text; - columnHeader.Width = width; - columnHeader.TextAlign = textAlign; + ColumnHeader columnHeader = new ColumnHeader(imageIndex) + { + Name = key, + Text = text, + Width = width, + TextAlign = textAlign + }; return owner.InsertColumn(Count, columnHeader); } @@ -8480,10 +8538,12 @@ void IList.Insert(int index, object value) public void Insert(int index, string text, int width, HorizontalAlignment textAlign) { - ColumnHeader columnHeader = new ColumnHeader(); - columnHeader.Text = text; - columnHeader.Width = width; - columnHeader.TextAlign = textAlign; + ColumnHeader columnHeader = new ColumnHeader + { + Text = text, + Width = width, + TextAlign = textAlign + }; Insert(index, columnHeader); } @@ -8491,53 +8551,65 @@ public void Insert(int index, string text, int width, HorizontalAlignment textAl public void Insert(int index, string text) { - ColumnHeader columnHeader = new ColumnHeader(); - columnHeader.Text = text; + ColumnHeader columnHeader = new ColumnHeader + { + Text = text + }; Insert(index, columnHeader); } public void Insert(int index, string text, int width) { - ColumnHeader columnHeader = new ColumnHeader(); - columnHeader.Text = text; - columnHeader.Width = width; + ColumnHeader columnHeader = new ColumnHeader + { + Text = text, + Width = width + }; Insert(index, columnHeader); } public void Insert(int index, string key, string text) { - ColumnHeader columnHeader = new ColumnHeader(); - columnHeader.Name = key; - columnHeader.Text = text; + ColumnHeader columnHeader = new ColumnHeader + { + Name = key, + Text = text + }; Insert(index, columnHeader); } public void Insert(int index, string key, string text, int width) { - ColumnHeader columnHeader = new ColumnHeader(); - columnHeader.Name = key; - columnHeader.Text = text; - columnHeader.Width = width; + ColumnHeader columnHeader = new ColumnHeader + { + Name = key, + Text = text, + Width = width + }; Insert(index, columnHeader); } public void Insert(int index, string key, string text, int width, HorizontalAlignment textAlign, string imageKey) { - ColumnHeader columnHeader = new ColumnHeader(imageKey); - columnHeader.Name = key; - columnHeader.Text = text; - columnHeader.Width = width; - columnHeader.TextAlign = textAlign; + ColumnHeader columnHeader = new ColumnHeader(imageKey) + { + Name = key, + Text = text, + Width = width, + TextAlign = textAlign + }; Insert(index, columnHeader); } public void Insert(int index, string key, string text, int width, HorizontalAlignment textAlign, int imageIndex) { - ColumnHeader columnHeader = new ColumnHeader(imageIndex); - columnHeader.Name = key; - columnHeader.Text = text; - columnHeader.Width = width; - columnHeader.TextAlign = textAlign; + ColumnHeader columnHeader = new ColumnHeader(imageIndex) + { + Name = key, + Text = text, + Width = width, + TextAlign = textAlign + }; Insert(index, columnHeader); } @@ -8873,8 +8945,10 @@ public virtual ListViewItem Add(string text, string imageKey) /// public virtual ListViewItem Add(string key, string text, string imageKey) { - ListViewItem li = new ListViewItem(text, imageKey); - li.Name = key; + ListViewItem li = new ListViewItem(text, imageKey) + { + Name = key + }; Add(li); return li; } @@ -8886,8 +8960,10 @@ public virtual ListViewItem Add(string key, string text, string imageKey) /// public virtual ListViewItem Add(string key, string text, int imageIndex) { - ListViewItem li = new ListViewItem(text, imageIndex); - li.Name = key; + ListViewItem li = new ListViewItem(text, imageIndex) + { + Name = key + }; Add(li); return li; } @@ -9126,15 +9202,19 @@ public ListViewItem Insert(int index, string text, string imageKey) public virtual ListViewItem Insert(int index, string key, string text, string imageKey) { - ListViewItem li = new ListViewItem(text, imageKey); - li.Name = key; + ListViewItem li = new ListViewItem(text, imageKey) + { + Name = key + }; return Insert(index, li); } public virtual ListViewItem Insert(int index, string key, string text, int imageIndex) { - ListViewItem li = new ListViewItem(text, imageIndex); - li.Name = key; + ListViewItem li = new ListViewItem(text, imageIndex) + { + Name = key + }; return Insert(index, li); } @@ -9383,9 +9463,11 @@ private int DisplayIndexToID(int displayIndex) if (owner.IsHandleCreated && !owner.ListViewHandleDestroyed) { // Obtain internal index of the item - NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM(); - lvItem.mask = NativeMethods.LVIF_PARAM; - lvItem.iItem = displayIndex; + NativeMethods.LVITEM lvItem = new NativeMethods.LVITEM + { + mask = NativeMethods.LVIF_PARAM, + iItem = displayIndex + }; UnsafeNativeMethods.SendMessage(new HandleRef(owner, owner.Handle), NativeMethods.LVM_GETITEM, 0, ref lvItem); return (int)lvItem.lParam; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewInsertionMark.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewInsertionMark.cs index ce1a581b077..d84f3e34892 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewInsertionMark.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewInsertionMark.cs @@ -124,9 +124,11 @@ public int Index /// public int NearestIndex(Point pt) { - NativeMethods.POINT point = new NativeMethods.POINT(); - point.x = pt.X; - point.y = pt.Y; + NativeMethods.POINT point = new NativeMethods.POINT + { + x = pt.X, + y = pt.Y + }; NativeMethods.LVINSERTMARK lvInsertMark = new NativeMethods.LVINSERTMARK(); UnsafeNativeMethods.SendMessage(new HandleRef(listView, listView.Handle), NativeMethods.LVM_INSERTMARKHITTEST, point, lvInsertMark); @@ -137,9 +139,11 @@ public int NearestIndex(Point pt) internal void UpdateListView() { Debug.Assert(listView.IsHandleCreated, "ApplySavedState Precondition: List-view handle must be created"); - NativeMethods.LVINSERTMARK lvInsertMark = new NativeMethods.LVINSERTMARK(); - lvInsertMark.dwFlags = appearsAfterItem ? NativeMethods.LVIM_AFTER : 0; - lvInsertMark.iItem = index; + NativeMethods.LVINSERTMARK lvInsertMark = new NativeMethods.LVINSERTMARK + { + dwFlags = appearsAfterItem ? NativeMethods.LVIM_AFTER : 0, + iItem = index + }; UnsafeNativeMethods.SendMessage(new HandleRef(listView, listView.Handle), NativeMethods.LVM_SETINSERTMARK, 0, lvInsertMark); if (!color.IsEmpty) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItem.cs index 41b1ea9768f..c3476c977bf 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItem.cs @@ -867,8 +867,10 @@ public virtual object Clone() subItem.Text, subItem.ForeColor, subItem.BackColor, - subItem.Font); - clonedSubItems[index].Tag = subItem.Tag; + subItem.Font) + { + Tag = subItem.Tag + }; } Type clonedType = GetType(); @@ -1068,8 +1070,10 @@ internal void UpdateStateFromListView(int displayIndex, bool checkSelection) if (listView != null && listView.IsHandleCreated && displayIndex != -1) { // Get information from comctl control - var lvItem = new NativeMethods.LVITEM(); - lvItem.mask = NativeMethods.LVIF_PARAM | NativeMethods.LVIF_STATE | NativeMethods.LVIF_GROUPID; + var lvItem = new NativeMethods.LVITEM + { + mask = NativeMethods.LVIF_PARAM | NativeMethods.LVIF_STATE | NativeMethods.LVIF_GROUPID + }; if (checkSelection) { @@ -1327,10 +1331,12 @@ public ListViewSubItem(ListViewItem owner, string text, Color foreColor, Color b { this.owner = owner; this.text = text; - style = new SubItemStyle(); - style.foreColor = foreColor; - style.backColor = backColor; - style.font = font; + style = new SubItemStyle + { + foreColor = foreColor, + backColor = backColor, + font = font + }; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs index cb86d08d514..a2c47be8c91 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs @@ -244,8 +244,10 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound // the bottom left of the client area, normally they are anchored // to the top right which just looks wierd! // - NativeMethods.WINDOWPLACEMENT wp = new NativeMethods.WINDOWPLACEMENT(); - wp.length = Marshal.SizeOf(); + NativeMethods.WINDOWPLACEMENT wp = new NativeMethods.WINDOWPLACEMENT + { + length = Marshal.SizeOf() + }; for (int i = 0; i < Controls.Count; i++) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs index a5ad87dc659..ab59641b6c3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs @@ -1223,8 +1223,10 @@ private char SystemPasswordChar // the defult one so we can get it; this would change the text displayed in the box (even for a short time) // opening a sec hole. - TextBox txtBox = new TextBox(); - txtBox.UseSystemPasswordChar = true; // this forces the creation of the control handle. + TextBox txtBox = new TextBox + { + UseSystemPasswordChar = true // this forces the creation of the control handle. + }; MaskedTextBox.systemPwdChar = txtBox.PasswordChar; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListStrip.cs index 7a16497eb52..281b882d803 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListStrip.cs @@ -41,8 +41,10 @@ internal ToolStripMenuItem MergeItem { if (mergeItem == null) { - mergeItem = new ToolStripMenuItem(); - mergeItem.MergeAction = MergeAction.MatchOnly; + mergeItem = new ToolStripMenuItem + { + MergeAction = MergeAction.MatchOnly + }; } if (mergeItem.Owner == null) @@ -90,9 +92,11 @@ public void PopulateItems(Form mdiParent, ToolStripMenuItem mdiMergeItem, bool i if (includeSeparator) { - ToolStripSeparator separator = new ToolStripSeparator(); - separator.MergeAction = MergeAction.Append; - separator.MergeIndex = -1; + ToolStripSeparator separator = new ToolStripSeparator + { + MergeAction = MergeAction.Append, + MergeIndex = -1 + }; mergeItem.DropDownItems.Add(separator); } @@ -117,10 +121,12 @@ public void PopulateItems(Form mdiParent, ToolStripMenuItem mdiMergeItem, bool i { // there's always room for activeMdiChild string text = WindowsFormsUtils.EscapeTextWithAmpersands(mdiParent.MdiChildren[i].Text); text = (text == null) ? string.Empty : text; - ToolStripMenuItem windowListItem = new ToolStripMenuItem(mdiParent.MdiChildren[i]); - windowListItem.Text = string.Format(CultureInfo.CurrentCulture, "&{0} {1}", accel, text); - windowListItem.MergeAction = MergeAction.Append; - windowListItem.MergeIndex = accel; + ToolStripMenuItem windowListItem = new ToolStripMenuItem(mdiParent.MdiChildren[i]) + { + Text = string.Format(CultureInfo.CurrentCulture, "&{0} {1}", accel, text), + MergeAction = MergeAction.Append, + MergeIndex = accel + }; windowListItem.Click += new EventHandler(OnWindowListItemClick); if (forms[i].Equals(activeMdiChild)) { // if this the active one, check it off. @@ -138,8 +144,10 @@ public void PopulateItems(Form mdiParent, ToolStripMenuItem mdiMergeItem, bool i // show the More Windows... item if necessary. if (visibleChildren > maxMenuForms) { - ToolStripMenuItem moreWindowsMenuItem = new ToolStripMenuItem(); - moreWindowsMenuItem.Text = SR.MDIMenuMoreWindows; + ToolStripMenuItem moreWindowsMenuItem = new ToolStripMenuItem + { + Text = SR.MDIMenuMoreWindows + }; Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "\tPopulateItems: Added " + moreWindowsMenuItem.Text); moreWindowsMenuItem.Click += new EventHandler(OnMoreWindowsMenuItemClick); moreWindowsMenuItem.MergeAction = MergeAction.Append; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MenuItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MenuItem.cs index 6c17e36ec6a..6b544ae37b2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MenuItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MenuItem.cs @@ -388,9 +388,11 @@ internal bool Selected return false; } - var info = new NativeMethods.MENUITEMINFO_T(); - info.cbSize = Marshal.SizeOf(); - info.fMask = NativeMethods.MIIM_STATE; + var info = new NativeMethods.MENUITEMINFO_T + { + cbSize = Marshal.SizeOf(), + fMask = NativeMethods.MIIM_STATE + }; UnsafeNativeMethods.GetMenuItemInfo(new HandleRef(Parent, Parent.handle), MenuID, false, info); return (info.fState & StateHiLite) != 0; @@ -412,9 +414,11 @@ internal int MenuIndex int count = UnsafeNativeMethods.GetMenuItemCount(new HandleRef(Parent, Parent.Handle)); int id = MenuID; - NativeMethods.MENUITEMINFO_T info = new NativeMethods.MENUITEMINFO_T(); - info.cbSize = Marshal.SizeOf(); - info.fMask = NativeMethods.MIIM_ID | NativeMethods.MIIM_SUBMENU; + NativeMethods.MENUITEMINFO_T info = new NativeMethods.MENUITEMINFO_T + { + cbSize = Marshal.SizeOf(), + fMask = NativeMethods.MIIM_ID | NativeMethods.MIIM_SUBMENU + }; for (int i = 0; i < count; i++) { @@ -763,10 +767,12 @@ internal virtual void CreateMenuItem() } #if DEBUG - NativeMethods.MENUITEMINFO_T infoVerify = new NativeMethods.MENUITEMINFO_T(); - infoVerify.cbSize = Marshal.SizeOf(); - infoVerify.fMask = NativeMethods.MIIM_ID | NativeMethods.MIIM_STATE | - NativeMethods.MIIM_SUBMENU | NativeMethods.MIIM_TYPE; + NativeMethods.MENUITEMINFO_T infoVerify = new NativeMethods.MENUITEMINFO_T + { + cbSize = Marshal.SizeOf(), + fMask = NativeMethods.MIIM_ID | NativeMethods.MIIM_STATE | + NativeMethods.MIIM_SUBMENU | NativeMethods.MIIM_TYPE + }; UnsafeNativeMethods.GetMenuItemInfo(new HandleRef(Parent, Parent.handle), MenuID, false, infoVerify); #endif } @@ -774,10 +780,12 @@ internal virtual void CreateMenuItem() private NativeMethods.MENUITEMINFO_T CreateMenuItemInfo() { - var info = new NativeMethods.MENUITEMINFO_T(); - info.fMask = NativeMethods.MIIM_ID | NativeMethods.MIIM_STATE | - NativeMethods.MIIM_SUBMENU | NativeMethods.MIIM_TYPE | NativeMethods.MIIM_DATA; - info.fType = _data.State & (StateBarBreak | StateBreak | StateRadioCheck | StateOwnerDraw); + var info = new NativeMethods.MENUITEMINFO_T + { + fMask = NativeMethods.MIIM_ID | NativeMethods.MIIM_STATE | + NativeMethods.MIIM_SUBMENU | NativeMethods.MIIM_TYPE | NativeMethods.MIIM_DATA, + fType = _data.State & (StateBarBreak | StateBreak | StateRadioCheck | StateOwnerDraw) + }; // Top level menu items shouldn't have barbreak or break bits set on them. bool isTopLevel = Parent == GetMainMenu(); @@ -1360,10 +1368,12 @@ internal void UpdateItemRtl(bool setRightToLeftBit) return; } - var info = new NativeMethods.MENUITEMINFO_T(); - info.fMask = NativeMethods.MIIM_TYPE | NativeMethods.MIIM_STATE | NativeMethods.MIIM_SUBMENU; - info.dwTypeData = new string('\0', Text.Length + 2); - info.cbSize = Marshal.SizeOf(); + var info = new NativeMethods.MENUITEMINFO_T + { + fMask = NativeMethods.MIIM_TYPE | NativeMethods.MIIM_STATE | NativeMethods.MIIM_SUBMENU, + dwTypeData = new string('\0', Text.Length + 2), + cbSize = Marshal.SizeOf() + }; info.cch = info.dwTypeData.Length - 1; UnsafeNativeMethods.GetMenuItemInfo(new HandleRef(Parent, Parent.handle), MenuID, false, info); if (setRightToLeftBit) @@ -1390,10 +1400,12 @@ internal void UpdateMenuItem(bool force) NativeMethods.MENUITEMINFO_T info = CreateMenuItemInfo(); UnsafeNativeMethods.SetMenuItemInfo(new HandleRef(Parent, Parent.handle), MenuID, false, info); #if DEBUG - var infoVerify = new NativeMethods.MENUITEMINFO_T(); - infoVerify.cbSize = Marshal.SizeOf(); - infoVerify.fMask = NativeMethods.MIIM_ID | NativeMethods.MIIM_STATE | - NativeMethods.MIIM_SUBMENU | NativeMethods.MIIM_TYPE; + var infoVerify = new NativeMethods.MENUITEMINFO_T + { + cbSize = Marshal.SizeOf(), + fMask = NativeMethods.MIIM_ID | NativeMethods.MIIM_STATE | + NativeMethods.MIIM_SUBMENU | NativeMethods.MIIM_TYPE + }; UnsafeNativeMethods.GetMenuItemInfo(new HandleRef(Parent, Parent.handle), MenuID, false, infoVerify); #endif diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Message.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Message.cs index 79013ce5291..93c82049cfa 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Message.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Message.cs @@ -44,12 +44,14 @@ public struct Message /// public static Message Create(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam) { - var m = new Message(); - m.HWnd = hWnd; - m.Msg = msg; - m.WParam = wparam; - m.LParam = lparam; - m.Result = IntPtr.Zero; + var m = new Message + { + HWnd = hWnd, + Msg = msg, + WParam = wparam, + LParam = lparam, + Result = IntPtr.Zero + }; #if DEBUG if (s_allWinMessages.TraceVerbose) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs index 846b329129d..4e03e65b6ea 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs @@ -1344,8 +1344,10 @@ protected override void CreateHandle() IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); try { - NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); - icc.dwICC = NativeMethods.ICC_DATE_CLASSES; + NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX + { + dwICC = NativeMethods.ICC_DATE_CLASSES + }; SafeNativeMethods.InitCommonControlsEx(icc); } finally @@ -1508,11 +1510,13 @@ private SelectionRange GetMonthRange(int flag) SelectionRange range = new SelectionRange(); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.MCM_GETMONTHRANGE, flag, sa); - NativeMethods.SYSTEMTIME st = new NativeMethods.SYSTEMTIME(); - st.wYear = sa.wYear1; - st.wMonth = sa.wMonth1; - st.wDayOfWeek = sa.wDayOfWeek1; - st.wDay = sa.wDay1; + NativeMethods.SYSTEMTIME st = new NativeMethods.SYSTEMTIME + { + wYear = sa.wYear1, + wMonth = sa.wMonth1, + wDayOfWeek = sa.wDayOfWeek1, + wDay = sa.wDay1 + }; range.Start = DateTimePicker.SysTimeToDateTime(st); st.wYear = sa.wYear2; @@ -1550,10 +1554,12 @@ private int GetPreferredWidth(int width, bool updateCols) /// public HitTestInfo HitTest(int x, int y) { - NativeMethods.MCHITTESTINFO mchi = new NativeMethods.MCHITTESTINFO(); - mchi.pt_x = x; - mchi.pt_y = y; - mchi.cbSize = Marshal.SizeOf(); + NativeMethods.MCHITTESTINFO mchi = new NativeMethods.MCHITTESTINFO + { + pt_x = x, + pt_y = y, + cbSize = Marshal.SizeOf() + }; UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.MCM_HITTEST, 0, mchi); // If the hit area has an associated valid date, get it @@ -1561,15 +1567,17 @@ public HitTestInfo HitTest(int x, int y) HitArea hitArea = GetHitArea(mchi.uHit); if (HitTestInfo.HitAreaHasValidDateTime(hitArea)) { - NativeMethods.SYSTEMTIME sys = new NativeMethods.SYSTEMTIME(); - sys.wYear = mchi.st_wYear; - sys.wMonth = mchi.st_wMonth; - sys.wDayOfWeek = mchi.st_wDayOfWeek; - sys.wDay = mchi.st_wDay; - sys.wHour = mchi.st_wHour; - sys.wMinute = mchi.st_wMinute; - sys.wSecond = mchi.st_wSecond; - sys.wMilliseconds = mchi.st_wMilliseconds; + NativeMethods.SYSTEMTIME sys = new NativeMethods.SYSTEMTIME + { + wYear = mchi.st_wYear, + wMonth = mchi.st_wMonth, + wDayOfWeek = mchi.st_wDayOfWeek, + wDay = mchi.st_wDay, + wHour = mchi.st_wHour, + wMinute = mchi.st_wMinute, + wSecond = mchi.st_wSecond, + wMilliseconds = mchi.st_wMilliseconds + }; return new HitTestInfo(new Point(mchi.pt_x, mchi.pt_y), hitArea, DateTimePicker.SysTimeToDateTime(sys)); } else diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs index 79be8ed7799..11cc5cbfe7e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs @@ -1620,8 +1620,10 @@ internal static WindowClass Create(string className, int classStyle) } if (wc == null) { - wc = new WindowClass(className, classStyle); - wc.next = cache; + wc = new WindowClass(className, classStyle) + { + next = cache + }; cache = wc; } else diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs index b450bf2e299..a7bc4de92cc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs @@ -774,9 +774,11 @@ private void UpdateIcon(bool showIconInTray) window.LockReference(showIconInTray); - NativeMethods.NOTIFYICONDATA data = new NativeMethods.NOTIFYICONDATA(); - data.uCallbackMessage = WM_TRAYMOUSEMESSAGE; - data.uFlags = NativeMethods.NIF_MESSAGE; + NativeMethods.NOTIFYICONDATA data = new NativeMethods.NOTIFYICONDATA + { + uCallbackMessage = WM_TRAYMOUSEMESSAGE, + uFlags = NativeMethods.NIF_MESSAGE + }; if (showIconInTray) { if (window.Handle == IntPtr.Zero) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PageSetupDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PageSetupDialog.cs index 93abf516f13..3ed978e20ec 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PageSetupDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PageSetupDialog.cs @@ -339,11 +339,13 @@ private static void UpdateSettings(NativeMethods.PAGESETUPDLG data, PageSettings printerSettings.SetHdevnames(data.hDevNames); } - Margins newMargins = new Margins(); - newMargins.Left = data.marginLeft; - newMargins.Top = data.marginTop; - newMargins.Right = data.marginRight; - newMargins.Bottom = data.marginBottom; + Margins newMargins = new Margins + { + Left = data.marginLeft, + Top = data.marginTop, + Right = data.marginRight, + Bottom = data.marginBottom + }; PrinterUnit fromUnit = ((data.Flags & NativeMethods.PSD_INHUNDREDTHSOFMILLIMETERS) != 0) ? PrinterUnit.HundredthsOfAMillimeter diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewControl.cs index 0240c5ba265..f7b34bb0551 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewControl.cs @@ -369,9 +369,11 @@ private int AdjustScroll(Message m, int pos, int maxPos, bool horizontal) { case NativeMethods.SB_THUMBPOSITION: case NativeMethods.SB_THUMBTRACK: - NativeMethods.SCROLLINFO si = new NativeMethods.SCROLLINFO(); - si.cbSize = Marshal.SizeOf(); - si.fMask = NativeMethods.SIF_TRACKPOS; + NativeMethods.SCROLLINFO si = new NativeMethods.SCROLLINFO + { + cbSize = Marshal.SizeOf(), + fMask = NativeMethods.SIF_TRACKPOS + }; int direction = horizontal ? NativeMethods.SB_HORZ : NativeMethods.SB_VERT; if (SafeNativeMethods.GetScrollInfo(new HandleRef(this, m.HWnd), direction, si)) { @@ -473,8 +475,10 @@ private void ComputePreview() { PrintController oldController = document.PrintController; - PreviewPrintController previewController = new PreviewPrintController(); - previewController.UseAntiAlias = UseAntiAlias; + PreviewPrintController previewController = new PreviewPrintController + { + UseAntiAlias = UseAntiAlias + }; document.PrintController = new PrintControllerWithStatusDialog(previewController, string.Format(SR.PrintControllerWithStatusDialog_DialogTitlePreview)); @@ -572,9 +576,11 @@ protected override void OnPaint(PaintEventArgs pevent) if (pageInfo != null || exceptionPrinting) { // Calculate formats - StringFormat format = new StringFormat(); - format.Alignment = ControlPaint.TranslateAlignment(ContentAlignment.MiddleCenter); - format.LineAlignment = ControlPaint.TranslateLineAlignment(ContentAlignment.MiddleCenter); + StringFormat format = new StringFormat + { + Alignment = ControlPaint.TranslateAlignment(ContentAlignment.MiddleCenter), + LineAlignment = ControlPaint.TranslateLineAlignment(ContentAlignment.MiddleCenter) + }; // Do actual drawing SolidBrush brush = new SolidBrush(ForeColor); @@ -815,11 +821,13 @@ internal void SetVirtualSizeNoInvalidate(Size value) virtualSize = value; SetPositionNoInvalidate(position); // Make sure it's within range - NativeMethods.SCROLLINFO info = new NativeMethods.SCROLLINFO(); - info.fMask = NativeMethods.SIF_RANGE | NativeMethods.SIF_PAGE; - info.nMin = 0; - info.nMax = Math.Max(Height, virtualSize.Height) - 1; - info.nPage = Height; + NativeMethods.SCROLLINFO info = new NativeMethods.SCROLLINFO + { + fMask = NativeMethods.SIF_RANGE | NativeMethods.SIF_PAGE, + nMin = 0, + nMax = Math.Max(Height, virtualSize.Height) - 1, + nPage = Height + }; UnsafeNativeMethods.SetScrollInfo(new HandleRef(this, Handle), NativeMethods.SB_VERT, info, true); info.fMask = NativeMethods.SIF_RANGE | NativeMethods.SIF_PAGE; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs index 31b3a2aa3d8..5dc7c31c96d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs @@ -1532,8 +1532,10 @@ void InitForm() } //Create the ToolStripControlHost - ToolStripControlHost pageCounterItem = new ToolStripControlHost(pageCounter); - pageCounterItem.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; + ToolStripControlHost pageCounterItem = new ToolStripControlHost(pageCounter) + { + Alignment = System.Windows.Forms.ToolStripItemAlignment.Right + }; toolStrip1.Items.Add(pageCounterItem); toolStrip1.Items.Add(pageToolStripLabel); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs index e7ba3ead6c1..7a47ee8ee23 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs @@ -703,8 +703,10 @@ protected override void CreateHandle() IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); try { - NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); - icc.dwICC = NativeMethods.ICC_PROGRESS_CLASS; + NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX + { + dwICC = NativeMethods.ICC_PROGRESS_CLASS + }; SafeNativeMethods.InitCommonControlsEx(icc); } finally diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs index 66e15398fc3..f4ee99a3f95 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs @@ -2192,11 +2192,13 @@ private ToolStripButton CreateToggleButton(string toolTipText, int imageIndex, E private ToolStripButton CreatePushButton(string toolTipText, int imageIndex, EventHandler eventHandler, bool useCheckButtonRole = false) { - ToolStripButton button = new ToolStripButton(); - button.Text = toolTipText; - button.AutoToolTip = true; - button.DisplayStyle = ToolStripItemDisplayStyle.Image; - button.ImageIndex = imageIndex; + ToolStripButton button = new ToolStripButton + { + Text = toolTipText, + AutoToolTip = true, + DisplayStyle = ToolStripItemDisplayStyle.Image, + ImageIndex = imageIndex + }; button.Click += eventHandler; button.ImageScaling = ToolStripItemImageScaling.SizeToFit; @@ -2589,8 +2591,10 @@ private void EnsureLargeButtons() if (imageList[LARGE_BUTTONS] == null) { - imageList[LARGE_BUTTONS] = new ImageList(); - imageList[LARGE_BUTTONS].ImageSize = largeButtonSize; + imageList[LARGE_BUTTONS] = new ImageList + { + ImageSize = largeButtonSize + }; if (DpiHelper.IsScalingRequired) { @@ -4719,8 +4723,10 @@ private void SetToolStripRenderer() if (DrawFlatToolbar || SystemInformation.HighContrast) { // use an office look and feel with system colors - ProfessionalColorTable colorTable = new ProfessionalColorTable(); - colorTable.UseSystemColors = true; + ProfessionalColorTable colorTable = new ProfessionalColorTable + { + UseSystemColors = true + }; ToolStripRenderer = new ToolStripProfessionalRenderer(colorTable); } else @@ -5083,9 +5089,11 @@ private bool ShouldForwardChildMouseMessage(Control child, MouseEventArgs me, re if (me.Y <= 1 || (size.Height - me.Y) <= 1) { // convert the coordinates to - NativeMethods.POINT temp = new NativeMethods.POINT(); - temp.x = me.X; - temp.y = me.Y; + NativeMethods.POINT temp = new NativeMethods.POINT + { + x = me.X, + y = me.Y + }; UnsafeNativeMethods.MapWindowPoints(new HandleRef(child, child.Handle), new HandleRef(this, Handle), temp, 1); // forward the message diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs index 41198f51925..fbb0115bbc7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs @@ -41,12 +41,16 @@ internal class DocComment : PropertyGrid.SnappableControl internal DocComment(PropertyGrid owner) : base(owner) { SuspendLayout(); - m_labelTitle = new Label(); - m_labelTitle.UseMnemonic = false; - m_labelTitle.Cursor = Cursors.Default; - m_labelDesc = new Label(); - m_labelDesc.AutoEllipsis = true; - m_labelDesc.Cursor = Cursors.Default; + m_labelTitle = new Label + { + UseMnemonic = false, + Cursor = Cursors.Default + }; + m_labelDesc = new Label + { + AutoEllipsis = true, + Cursor = Cursors.Default + }; UpdateTextRenderingEngine(); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs index fda8ad60de7..f10f5330a59 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs @@ -2194,8 +2194,10 @@ public virtual void PaintLabel(System.Drawing.Graphics g, Rectangle rect, Rectan { using (Brush textBrush = new SolidBrush(textColor)) { - StringFormat stringFormat = new StringFormat(StringFormatFlags.NoWrap); - stringFormat.Trimming = StringTrimming.None; + StringFormat stringFormat = new StringFormat(StringFormatFlags.NoWrap) + { + Trimming = StringTrimming.None + }; g.DrawString(strLabel, font, textBrush, textRect, stringFormat); } } @@ -2789,9 +2791,11 @@ internal virtual bool ShouldSerializePropertyValue() } else { - cacheItems = new CacheItems(); - cacheItems.lastShouldSerialize = NotifyValue(NOTIFY_SHOULD_PERSIST); - cacheItems.useShouldSerialize = true; + cacheItems = new CacheItems + { + lastShouldSerialize = NotifyValue(NOTIFY_SHOULD_PERSIST), + useShouldSerialize = true + }; } return cacheItems.lastShouldSerialize; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridToolTip.cs index d838f7af1b6..223f9d02ef7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridToolTip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridToolTip.cs @@ -107,12 +107,16 @@ protected override CreateParams CreateParams { get { - NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); - icc.dwICC = NativeMethods.ICC_TAB_CLASSES; + NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX + { + dwICC = NativeMethods.ICC_TAB_CLASSES + }; SafeNativeMethods.InitCommonControlsEx(icc); - CreateParams cp = new CreateParams(); - cp.Parent = IntPtr.Zero; - cp.ClassName = NativeMethods.TOOLTIPS_CLASS; + CreateParams cp = new CreateParams + { + Parent = IntPtr.Zero, + ClassName = NativeMethods.TOOLTIPS_CLASS + }; cp.Style |= (NativeMethods.TTS_ALWAYSTIP | NativeMethods.TTS_NOPREFIX); cp.ExStyle = 0; cp.Caption = ToolTip; @@ -129,8 +133,10 @@ private NativeMethods.TOOLINFO_T GetTOOLINFO(Control c) if (toolInfos[index] == null) { - toolInfos[index] = new NativeMethods.TOOLINFO_T(); - toolInfos[index].cbSize = Marshal.SizeOf(); + toolInfos[index] = new NativeMethods.TOOLINFO_T + { + cbSize = Marshal.SizeOf() + }; toolInfos[index].uFlags |= NativeMethods.TTF_IDISHWND | NativeMethods.TTF_TRANSPARENT | NativeMethods.TTF_SUBCLASS; } toolInfos[index].lpszText = toolTipText; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs index 0bfe3be2a8e..e3c221f8c7f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs @@ -78,12 +78,14 @@ public LinkLabel Label { if (label == null) { - label = new LinkLabel(); - label.Dock = DockStyle.Fill; - label.LinkBehavior = LinkBehavior.AlwaysUnderline; + label = new LinkLabel + { + Dock = DockStyle.Fill, + LinkBehavior = LinkBehavior.AlwaysUnderline, - // use default LinkLabel colors for regular, active, and visited - label.DisabledLinkColor = SystemColors.ControlDark; + // use default LinkLabel colors for regular, active, and visited + DisabledLinkColor = SystemColors.ControlDark + }; label.LinkClicked += new LinkLabelLinkClickedEventHandler(LinkClicked); Controls.Add(label); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs index d4cc7a15678..c1f3753295e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs @@ -295,8 +295,10 @@ internal DropDownButton DropDownButton } #endif - btnDropDown = new DropDownButton(); - btnDropDown.UseComboBoxTheme = true; + btnDropDown = new DropDownButton + { + UseComboBoxTheme = true + }; Bitmap bitmap = CreateResizedBitmap("Arrow", DOWNARROW_ICONWIDTH, DOWNARROW_ICONHEIGHT); btnDropDown.Image = bitmap; btnDropDown.BackColor = SystemColors.Control; @@ -325,11 +327,13 @@ private Button DialogButton throw new Exception("PERF REGRESSION - Creating item in grid view create"); } #endif - btnDialog = new DropDownButton(); - btnDialog.BackColor = SystemColors.Control; - btnDialog.ForeColor = SystemColors.ControlText; - btnDialog.TabIndex = 3; - btnDialog.Image = CreateResizedBitmap("dotdotdot", DOTDOTDOT_ICONWIDTH, DOTDOTDOT_ICONHEIGHT); + btnDialog = new DropDownButton + { + BackColor = SystemColors.Control, + ForeColor = SystemColors.ControlText, + TabIndex = 3, + Image = CreateResizedBitmap("dotdotdot", DOTDOTDOT_ICONWIDTH, DOTDOTDOT_ICONHEIGHT) + }; btnDialog.Click += new EventHandler(OnBtnClick); btnDialog.KeyDown += new KeyEventHandler(OnBtnKeyDown); btnDialog.GotFocus += new EventHandler(OnDropDownButtonGotFocus); @@ -376,13 +380,15 @@ private GridViewEdit Edit } #endif - edit = new GridViewEdit(this); - edit.BorderStyle = BorderStyle.None; - edit.AutoSize = false; - edit.TabStop = false; - edit.AcceptsReturn = true; - edit.BackColor = BackColor; - edit.ForeColor = ForeColor; + edit = new GridViewEdit(this) + { + BorderStyle = BorderStyle.None, + AutoSize = false, + TabStop = false, + AcceptsReturn = true, + BackColor = BackColor, + ForeColor = ForeColor + }; edit.KeyDown += new KeyEventHandler(OnEditKeyDown); edit.KeyPress += new KeyPressEventHandler(OnEditKeyPress); edit.GotFocus += new EventHandler(OnEditGotFocus); @@ -421,8 +427,10 @@ private GridViewListBox DropDownListBox } #endif - listBox = new GridViewListBox(this); - listBox.DrawMode = DrawMode.OwnerDrawFixed; + listBox = new GridViewListBox(this) + { + DrawMode = DrawMode.OwnerDrawFixed + }; //listBox.Click += new EventHandler(this.OnListClick); listBox.MouseUp += new MouseEventHandler(OnListMouseUp); listBox.DrawItem += new DrawItemEventHandler(OnListDrawItem); @@ -848,9 +856,11 @@ private GridToolTip ToolTip throw new Exception("PERF REGRESSION - Creating item in grid view create"); } #endif - toolTip = new GridToolTip(new Control[] { this, Edit }); - toolTip.ToolTip = string.Empty; - toolTip.Font = Font; + toolTip = new GridToolTip(new Control[] { this, Edit }) + { + ToolTip = string.Empty, + Font = Font + }; } return toolTip; } @@ -3971,8 +3981,10 @@ protected override void OnPaint(PaintEventArgs pe) cPropsVisible = Math.Min(cPropsVisible, endRow + 1); Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Drawing splitter"); - Pen splitterPen = new Pen(ownerGrid.LineColor, GetSplitterWidth()); - splitterPen.DashStyle = DashStyle.Solid; + Pen splitterPen = new Pen(ownerGrid.LineColor, GetSplitterWidth()) + { + DashStyle = DashStyle.Solid + }; g.DrawLine(splitterPen, labelWidth, loc.Y, labelWidth, (cPropsVisible) * (RowHeight + 1) + loc.Y); splitterPen.Dispose(); @@ -6796,8 +6808,10 @@ protected override void OnPaint(PaintEventArgs pe) // Draw the divider int y = resizeUp ? (ResizeBarSize - 1) : (Height - ResizeBarSize); - Pen pen = new Pen(SystemColors.ControlDark, 1); - pen.DashStyle = DashStyle.Solid; + Pen pen = new Pen(SystemColors.ControlDark, 1) + { + DashStyle = DashStyle.Solid + }; pe.Graphics.DrawLine(pen, 0, y, Width, y); pen.Dispose(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs index 117184c659b..6d1dc9ecee4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs @@ -852,8 +852,10 @@ public HorizontalAlignment SelectionAlignment HorizontalAlignment selectionAlignment = HorizontalAlignment.Left; ForceHandleCreate(); - NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT(); - pf.rgxTabs = new int[RichTextBoxConstants.MAX_TAB_STOPS]; + NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT + { + rgxTabs = new int[RichTextBoxConstants.MAX_TAB_STOPS] + }; // get the format for our currently selected paragraph UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_GETPARAFORMAT, 0, pf); @@ -888,8 +890,10 @@ public HorizontalAlignment SelectionAlignment } ForceHandleCreate(); - NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT(); - pf.dwMask = RichTextBoxConstants.PFM_ALIGNMENT; + NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT + { + dwMask = RichTextBoxConstants.PFM_ALIGNMENT + }; switch (value) { @@ -928,8 +932,10 @@ public bool SelectionBullet RichTextBoxSelectionAttribute selectionBullet = RichTextBoxSelectionAttribute.None; ForceHandleCreate(); - NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT(); - pf.rgxTabs = new int[RichTextBoxConstants.MAX_TAB_STOPS]; + NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT + { + rgxTabs = new int[RichTextBoxConstants.MAX_TAB_STOPS] + }; // get the format for our currently selected paragraph UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_GETPARAFORMAT, 0, pf); @@ -954,8 +960,10 @@ public bool SelectionBullet { ForceHandleCreate(); - NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT(); - pf.dwMask = RichTextBoxConstants.PFM_NUMBERING | RichTextBoxConstants.PFM_OFFSET; + NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT + { + dwMask = RichTextBoxConstants.PFM_NUMBERING | RichTextBoxConstants.PFM_OFFSET + }; if (!value) { @@ -1011,9 +1019,11 @@ public int SelectionCharOffset throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidBoundArgument, nameof(SelectionCharOffset), value, -2000, 2000)); ForceHandleCreate(); - NativeMethods.CHARFORMATA cf = new NativeMethods.CHARFORMATA(); - cf.dwMask = RichTextBoxConstants.CFM_OFFSET; - cf.yOffset = Pixel2Twip(IntPtr.Zero, value, false); + NativeMethods.CHARFORMATA cf = new NativeMethods.CHARFORMATA + { + dwMask = RichTextBoxConstants.CFM_OFFSET, + yOffset = Pixel2Twip(IntPtr.Zero, value, false) + }; // Set the format information // SendMessage will force the handle to be created if it hasn't already. Normally, @@ -1159,8 +1169,10 @@ public int SelectionHangingIndent int selHangingIndent = 0; ForceHandleCreate(); - NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT(); - pf.rgxTabs = new int[RichTextBoxConstants.MAX_TAB_STOPS]; + NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT + { + rgxTabs = new int[RichTextBoxConstants.MAX_TAB_STOPS] + }; // get the format for our currently selected paragraph UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_GETPARAFORMAT, 0, pf); @@ -1175,9 +1187,11 @@ public int SelectionHangingIndent { ForceHandleCreate(); - NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT(); - pf.dwMask = RichTextBoxConstants.PFM_OFFSET; - pf.dxOffset = Pixel2Twip(IntPtr.Zero, value, true); + NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT + { + dwMask = RichTextBoxConstants.PFM_OFFSET, + dxOffset = Pixel2Twip(IntPtr.Zero, value, true) + }; // set the format for our current paragraph or selection UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_SETPARAFORMAT, 0, pf); @@ -1202,8 +1216,10 @@ public int SelectionIndent int selIndent = 0; ForceHandleCreate(); - NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT(); - pf.rgxTabs = new int[RichTextBoxConstants.MAX_TAB_STOPS]; + NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT + { + rgxTabs = new int[RichTextBoxConstants.MAX_TAB_STOPS] + }; // get the format for our currently selected paragraph UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_GETPARAFORMAT, 0, pf); @@ -1218,9 +1234,11 @@ public int SelectionIndent { ForceHandleCreate(); - NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT(); - pf.dwMask = RichTextBoxConstants.PFM_STARTINDENT; - pf.dxStartIndent = Pixel2Twip(IntPtr.Zero, value, true); + NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT + { + dwMask = RichTextBoxConstants.PFM_STARTINDENT, + dxStartIndent = Pixel2Twip(IntPtr.Zero, value, true) + }; // set the format for our current paragraph or selection UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_SETPARAFORMAT, 0, pf); @@ -1331,8 +1349,10 @@ public int SelectionRightIndent ForceHandleCreate(); - NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT(); - pf.rgxTabs = new int[RichTextBoxConstants.MAX_TAB_STOPS]; + NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT + { + rgxTabs = new int[RichTextBoxConstants.MAX_TAB_STOPS] + }; // get the format for our currently selected paragraph UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_GETPARAFORMAT, 0, pf); @@ -1349,9 +1369,11 @@ public int SelectionRightIndent throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(SelectionRightIndent), value, 0)); ForceHandleCreate(); - NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT(); - pf.dwMask = RichTextBoxConstants.PFM_RIGHTINDENT; - pf.dxRightIndent = Pixel2Twip(IntPtr.Zero, value, true); + NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT + { + dwMask = RichTextBoxConstants.PFM_RIGHTINDENT, + dxRightIndent = Pixel2Twip(IntPtr.Zero, value, true) + }; // set the format for our current paragraph or selection UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_SETPARAFORMAT, 0, pf); @@ -1373,8 +1395,10 @@ public int[] SelectionTabs int[] selTabs = new int[0]; ForceHandleCreate(); - NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT(); - pf.rgxTabs = new int[RichTextBoxConstants.MAX_TAB_STOPS]; + NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT + { + rgxTabs = new int[RichTextBoxConstants.MAX_TAB_STOPS] + }; // get the format for our currently selected paragraph UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_GETPARAFORMAT, 0, pf); @@ -1396,8 +1420,10 @@ public int[] SelectionTabs throw new ArgumentOutOfRangeException(nameof(SelectionTabs), SR.SelTabCountRange); ForceHandleCreate(); - NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT(); - pf.rgxTabs = new int[RichTextBoxConstants.MAX_TAB_STOPS]; + NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT + { + rgxTabs = new int[RichTextBoxConstants.MAX_TAB_STOPS] + }; // get the format for our currently selected paragraph because // we need to get the number of tabstops to copy @@ -1986,12 +2012,14 @@ public int Find(string str, int start, int end, RichTextBoxFinds options) throw new ArgumentOutOfRangeException(nameof(end), end, string.Format(SR.RichTextFindEndInvalid, end)); bool selectWord = true; - NativeMethods.FINDTEXT ft = new NativeMethods.FINDTEXT(); - ft.chrg = new NativeMethods.CHARRANGE(); + NativeMethods.FINDTEXT ft = new NativeMethods.FINDTEXT + { + chrg = new NativeMethods.CHARRANGE(), - // set up the default values for the FINDTEXT structure, that is - // the given string and the whole range of the text stream - ft.lpstrText = str ?? throw new ArgumentNullException(nameof(str)); + // set up the default values for the FINDTEXT structure, that is + // the given string and the whole range of the text stream + lpstrText = str ?? throw new ArgumentNullException(nameof(str)) + }; if (end == -1) { end = textLen; @@ -2057,8 +2085,10 @@ public int Find(string str, int start, int end, RichTextBoxFinds options) if (position != -1 && selectWord) { // Select the string found, this is done in ubyte units - NativeMethods.CHARRANGE chrg = new NativeMethods.CHARRANGE(); - chrg.cpMin = position; + NativeMethods.CHARRANGE chrg = new NativeMethods.CHARRANGE + { + cpMin = position + }; //Look for kashidas in the string. A kashida is an arabic visual justification character //that's not semantically meaningful. Searching for ABC might find AB_C (where A,B, and C //represent Arabic characters and _ represents a kashida). We should highlight the text @@ -2152,11 +2182,14 @@ public int Find(char[] characterSet, int start, int end) // Use the TEXTRANGE to move our text buffer forward // or backwards within the main text - NativeMethods.TEXTRANGE txrg = new NativeMethods.TEXTRANGE(); // Characters we have slurped into memory in order to search - txrg.chrg = new NativeMethods.CHARRANGE(); - - txrg.chrg.cpMin = chrg.cpMin; - txrg.chrg.cpMax = chrg.cpMax; + NativeMethods.TEXTRANGE txrg = new NativeMethods.TEXTRANGE + { + chrg = new NativeMethods.CHARRANGE + { + cpMin = chrg.cpMin, + cpMax = chrg.cpMax + } + }; // Characters we have slurped into memory in order to search UnsafeNativeMethods.CharBuffer charBuffer; charBuffer = UnsafeNativeMethods.CharBuffer.CreateBuffer(CHAR_BUFFER_LEN + 1); @@ -2906,9 +2939,10 @@ private bool SetCharFormat(int mask, int effect, RichTextBoxSelectionAttribute c // check to see if the control has been created if (IsHandleCreated) { - NativeMethods.CHARFORMATA cf = new NativeMethods.CHARFORMATA(); - - cf.dwMask = mask; + NativeMethods.CHARFORMATA cf = new NativeMethods.CHARFORMATA + { + dwMask = mask + }; switch (charFormat) { @@ -3427,8 +3461,10 @@ private void EnLinkMsgHandler(ref Message m) /// private string CharRangeToString(NativeMethods.CHARRANGE c) { - NativeMethods.TEXTRANGE txrg = new NativeMethods.TEXTRANGE(); - txrg.chrg = c; + NativeMethods.TEXTRANGE txrg = new NativeMethods.TEXTRANGE + { + chrg = c + }; Debug.Assert((c.cpMax - c.cpMin) > 0, "CHARRANGE was null or negative - can't do it!"); //Windows diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollBar.cs index 4d0798ad067..8b8002e0419 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollBar.cs @@ -603,12 +603,14 @@ protected void UpdateScrollInfo() { if (IsHandleCreated && Enabled) { - var si = new NativeMethods.SCROLLINFO(); - si.cbSize = Marshal.SizeOf(); - si.fMask = NativeMethods.SIF_ALL; - si.nMin = _minimum; - si.nMax = _maximum; - si.nPage = LargeChange; + var si = new NativeMethods.SCROLLINFO + { + cbSize = Marshal.SizeOf(), + fMask = NativeMethods.SIF_ALL, + nMin = _minimum, + nMax = _maximum, + nPage = LargeChange + }; if (RightToLeft == RightToLeft.Yes) { @@ -699,8 +701,10 @@ private void DoScroll(ScrollEventType type) case ScrollEventType.ThumbPosition: case ScrollEventType.ThumbTrack: - var si = new NativeMethods.SCROLLINFO(); - si.fMask = NativeMethods.SIF_TRACKPOS; + var si = new NativeMethods.SCROLLINFO + { + fMask = NativeMethods.SIF_TRACKPOS + }; SafeNativeMethods.GetScrollInfo(new HandleRef(this, Handle), NativeMethods.SB_CTL, si); if (RightToLeft == RightToLeft.Yes) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollProperties.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollProperties.cs index 4c38049f292..9a99a7cd891 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollProperties.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollProperties.cs @@ -269,14 +269,16 @@ internal void UpdateScrollInfo() { if (_parent.IsHandleCreated && _visible) { - var si = new NativeMethods.SCROLLINFO(); - si.cbSize = Marshal.SizeOf(); - si.fMask = NativeMethods.SIF_ALL; - si.nMin = _minimum; - si.nMax = _maximum; - si.nPage = _parent.AutoScroll ? PageSize : LargeChange; - si.nPos = _value; - si.nTrackPos = 0; + var si = new NativeMethods.SCROLLINFO + { + cbSize = Marshal.SizeOf(), + fMask = NativeMethods.SIF_ALL, + nMin = _minimum, + nMax = _maximum, + nPage = _parent.AutoScroll ? PageSize : LargeChange, + nPos = _value, + nTrackPos = 0 + }; UnsafeNativeMethods.SetScrollInfo(new HandleRef(_parent, _parent.Handle), Orientation, si, true); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs index fdf31590a5e..f6136680aef 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs @@ -1064,8 +1064,10 @@ protected virtual Point ScrollToControl(Control activeControl) } private int ScrollThumbPosition(int fnBar) { - NativeMethods.SCROLLINFO si = new NativeMethods.SCROLLINFO(); - si.fMask = NativeMethods.SIF_TRACKPOS; + NativeMethods.SCROLLINFO si = new NativeMethods.SCROLLINFO + { + fMask = NativeMethods.SIF_TRACKPOS + }; SafeNativeMethods.GetScrollInfo(new HandleRef(this, Handle), fnBar, si); return si.nTrackPos; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs index 5c59480e75f..2a597ddd637 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs @@ -644,8 +644,10 @@ protected override void CreateHandle() try { - NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); - icc.dwICC = NativeMethods.ICC_BAR_CLASSES; + NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX + { + dwICC = NativeMethods.ICC_BAR_CLASSES + }; SafeNativeMethods.InitCommonControlsEx(icc); } finally @@ -1430,8 +1432,10 @@ public bool IsReadOnly /// public virtual StatusBarPanel Add(string text) { - StatusBarPanel panel = new StatusBarPanel(); - panel.Text = text; + StatusBarPanel panel = new StatusBarPanel + { + Text = text + }; Add(panel); return panel; } @@ -1760,12 +1764,16 @@ protected CreateParams CreateParams { get { - NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); - icc.dwICC = NativeMethods.ICC_TAB_CLASSES; + NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX + { + dwICC = NativeMethods.ICC_TAB_CLASSES + }; SafeNativeMethods.InitCommonControlsEx(icc); - CreateParams cp = new CreateParams(); - cp.Parent = IntPtr.Zero; - cp.ClassName = NativeMethods.TOOLTIPS_CLASS; + CreateParams cp = new CreateParams + { + Parent = IntPtr.Zero, + ClassName = NativeMethods.TOOLTIPS_CLASS + }; cp.Style |= NativeMethods.TTS_ALWAYSTIP; cp.ExStyle = 0; cp.Caption = null; @@ -1960,9 +1968,11 @@ public void Dispose() /// private NativeMethods.TOOLINFO_T GetMinTOOLINFO(Tool tool) { - NativeMethods.TOOLINFO_T ti = new NativeMethods.TOOLINFO_T(); - ti.cbSize = Marshal.SizeOf(); - ti.hwnd = parent.Handle; + NativeMethods.TOOLINFO_T ti = new NativeMethods.TOOLINFO_T + { + cbSize = Marshal.SizeOf(), + hwnd = parent.Handle + }; if ((int)tool.id < 0) { AssignId(tool); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SystemInformation.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SystemInformation.cs index b381f15c363..82470af3312 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SystemInformation.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SystemInformation.cs @@ -55,10 +55,12 @@ public static bool HighContrast EnsureSystemEvents(); if (s_systemEventsDirty) { - var data = new NativeMethods.HIGHCONTRAST_I(); - data.cbSize = Marshal.SizeOf(); - data.dwFlags = 0; - data.lpszDefaultScheme = IntPtr.Zero; + var data = new NativeMethods.HIGHCONTRAST_I + { + cbSize = Marshal.SizeOf(), + dwFlags = 0, + lpszDefaultScheme = IntPtr.Zero + }; // Force it to false if we fail to get the parameter. if (UnsafeNativeMethods.SystemParametersInfo(NativeMethods.SPI_GETHIGHCONTRAST, data.cbSize, ref data, 0)) @@ -1327,9 +1329,11 @@ public static ScreenOrientation ScreenOrientation get { ScreenOrientation so = ScreenOrientation.Angle0; - NativeMethods.DEVMODE dm = new NativeMethods.DEVMODE(); - dm.dmSize = (short)Marshal.SizeOf(); - dm.dmDriverExtra = 0; + NativeMethods.DEVMODE dm = new NativeMethods.DEVMODE + { + dmSize = (short)Marshal.SizeOf(), + dmDriverExtra = 0 + }; try { SafeNativeMethods.EnumDisplaySettings(null, -1 /*ENUM_CURRENT_SETTINGS*/, ref dm); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs index 1c71bd15f46..a9085eec848 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs @@ -1109,8 +1109,10 @@ protected override void CreateHandle() IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); try { - NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); - icc.dwICC = NativeMethods.ICC_TAB_CLASSES; + NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX + { + dwICC = NativeMethods.ICC_TAB_CLASSES + }; SafeNativeMethods.InitCommonControlsEx(icc); } finally @@ -2421,34 +2423,42 @@ int IList.Add(object value) public void Add(string text) { - TabPage page = new TabPage(); - page.Text = text; + TabPage page = new TabPage + { + Text = text + }; Add(page); } public void Add(string key, string text) { - TabPage page = new TabPage(); - page.Name = key; - page.Text = text; + TabPage page = new TabPage + { + Name = key, + Text = text + }; Add(page); } public void Add(string key, string text, int imageIndex) { - TabPage page = new TabPage(); - page.Name = key; - page.Text = text; - page.ImageIndex = imageIndex; + TabPage page = new TabPage + { + Name = key, + Text = text, + ImageIndex = imageIndex + }; Add(page); } public void Add(string key, string text, string imageKey) { - TabPage page = new TabPage(); - page.Name = key; - page.Text = text; - page.ImageKey = imageKey; + TabPage page = new TabPage + { + Name = key, + Text = text, + ImageKey = imageKey + }; Add(page); } @@ -2606,24 +2616,30 @@ void IList.Insert(int index, object tabPage) public void Insert(int index, string text) { - TabPage page = new TabPage(); - page.Text = text; + TabPage page = new TabPage + { + Text = text + }; Insert(index, page); } public void Insert(int index, string key, string text) { - TabPage page = new TabPage(); - page.Name = key; - page.Text = text; + TabPage page = new TabPage + { + Name = key, + Text = text + }; Insert(index, page); } public void Insert(int index, string key, string text, int imageIndex) { - TabPage page = new TabPage(); - page.Name = key; - page.Text = text; + TabPage page = new TabPage + { + Name = key, + Text = text + }; Insert(index, page); // ImageKey and ImageIndex require parenting... page.ImageIndex = imageIndex; @@ -2631,9 +2647,11 @@ public void Insert(int index, string key, string text, int imageIndex) public void Insert(int index, string key, string text, string imageKey) { - TabPage page = new TabPage(); - page.Name = key; - page.Text = text; + TabPage page = new TabPage + { + Name = key, + Text = text + }; Insert(index, page); // ImageKey and ImageIndex require parenting... page.ImageKey = imageKey; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TabPage.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TabPage.cs index bfae3970a73..0e3b57609de 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TabPage.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TabPage.cs @@ -538,12 +538,13 @@ public static TabPage GetTabPageOfComponent(object comp) /// internal NativeMethods.TCITEM_T GetTCITEM() { - NativeMethods.TCITEM_T tcitem = new NativeMethods.TCITEM_T(); - - tcitem.mask = 0; - tcitem.pszText = null; - tcitem.cchTextMax = 0; - tcitem.lParam = IntPtr.Zero; + NativeMethods.TCITEM_T tcitem = new NativeMethods.TCITEM_T + { + mask = 0, + pszText = null, + cchTextMax = 0, + lParam = IntPtr.Zero + }; string text = Text; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Timer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Timer.cs index b773a41bb03..464f6b6e3ec 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Timer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Timer.cs @@ -217,15 +217,17 @@ private bool EnsureHandle() if (Handle == IntPtr.Zero) { // Create a totally vanilla invisible window just for WM_TIMER messages - var cp = new CreateParams(); - cp.Style = 0; - cp.ExStyle = 0; - cp.ClassStyle = 0; - cp.Caption = GetType().Name; - - // Message only windows are cheaper and have fewer issues than - // full blown invisible windows. - cp.Parent = (IntPtr)NativeMethods.HWND_MESSAGE; + var cp = new CreateParams + { + Style = 0, + ExStyle = 0, + ClassStyle = 0, + Caption = GetType().Name, + + // Message only windows are cheaper and have fewer issues than + // full blown invisible windows. + Parent = (IntPtr)NativeMethods.HWND_MESSAGE + }; CreateHandle(cp); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs index e234e36be6e..bd13e6aca53 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs @@ -1060,8 +1060,10 @@ protected override void CreateHandle() IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); try { - NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); - icc.dwICC = NativeMethods.ICC_BAR_CLASSES; + NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX + { + dwICC = NativeMethods.ICC_BAR_CLASSES + }; SafeNativeMethods.InitCommonControlsEx(icc); } finally @@ -1155,9 +1157,11 @@ private void ForceButtonWidths() for (int x = 0; x < buttonCount; x++) { - NativeMethods.TBBUTTONINFO tbbi = new NativeMethods.TBBUTTONINFO(); - tbbi.cbSize = Marshal.SizeOf(); - tbbi.cx = buttons[x].Width; + NativeMethods.TBBUTTONINFO tbbi = new NativeMethods.TBBUTTONINFO + { + cbSize = Marshal.SizeOf(), + cx = buttons[x].Width + }; if (tbbi.cx > maxWidth) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs index 5334ffaa4a3..eb3e1e05e52 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs @@ -606,9 +606,11 @@ internal int GetButtonWidth() // Assume that this button is the same width as the parent's ButtonSize's Width int buttonWidth = Parent.ButtonSize.Width; - NativeMethods.TBBUTTONINFO button = new NativeMethods.TBBUTTONINFO(); - button.cbSize = Marshal.SizeOf(); - button.dwMask = NativeMethods.TBIF_SIZE; + NativeMethods.TBBUTTONINFO button = new NativeMethods.TBBUTTONINFO + { + cbSize = Marshal.SizeOf(), + dwMask = NativeMethods.TBIF_SIZE + }; int buttonID = (int)UnsafeNativeMethods.SendMessage(new HandleRef(Parent, Parent.Handle), NativeMethods.TB_GETBUTTONINFO, commandId, ref button); if (buttonID != -1) @@ -639,13 +641,14 @@ private bool GetPushedState() internal NativeMethods.TBBUTTON GetTBBUTTON(int commandId) { - NativeMethods.TBBUTTON button = new NativeMethods.TBBUTTON(); - - button.iBitmap = ImageIndexer.ActualIndex; + NativeMethods.TBBUTTON button = new NativeMethods.TBBUTTON + { + iBitmap = ImageIndexer.ActualIndex, - // set up the state of the button - // - button.fsState = 0; + // set up the state of the button + // + fsState = 0 + }; if (enabled) button.fsState |= NativeMethods.TBSTATE_ENABLED; if (partialPush && style == ToolBarButtonStyle.ToggleButton) @@ -688,10 +691,12 @@ internal NativeMethods.TBBUTTON GetTBBUTTON(int commandId) internal NativeMethods.TBBUTTONINFO GetTBBUTTONINFO(bool updateText, int newCommandId) { - NativeMethods.TBBUTTONINFO button = new NativeMethods.TBBUTTONINFO(); - button.cbSize = Marshal.SizeOf(); - button.dwMask = NativeMethods.TBIF_IMAGE - | NativeMethods.TBIF_STATE | NativeMethods.TBIF_STYLE; + NativeMethods.TBBUTTONINFO button = new NativeMethods.TBBUTTONINFO + { + cbSize = Marshal.SizeOf(), + dwMask = NativeMethods.TBIF_IMAGE + | NativeMethods.TBIF_STATE | NativeMethods.TBIF_STYLE + }; // Older platforms interpret null strings as empty, which forces the button to // leave space for text. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs index 299d6f2fb8d..141ef699ece 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs @@ -836,8 +836,10 @@ internal virtual NativeWindow DropDownOwnerWindow if (dropDownOwnerWindow.Handle == IntPtr.Zero) { - CreateParams cp = new CreateParams(); - cp.ExStyle = NativeMethods.WS_EX_TOOLWINDOW; + CreateParams cp = new CreateParams + { + ExStyle = NativeMethods.WS_EX_TOOLWINDOW + }; dropDownOwnerWindow.CreateHandle(cp); } @@ -965,12 +967,14 @@ internal ToolStripGrip Grip { if (toolStripGrip == null) { - toolStripGrip = new ToolStripGrip(); - toolStripGrip.Overflow = ToolStripItemOverflow.Never; - toolStripGrip.Visible = toolStripGripStyle == ToolStripGripStyle.Visible; - toolStripGrip.AutoSize = false; - toolStripGrip.ParentInternal = this; - toolStripGrip.Margin = DefaultGripMargin; + toolStripGrip = new ToolStripGrip + { + Overflow = ToolStripItemOverflow.Never, + Visible = toolStripGripStyle == ToolStripGripStyle.Visible, + AutoSize = false, + ParentInternal = this, + Margin = DefaultGripMargin + }; } return toolStripGrip; } @@ -1620,10 +1624,12 @@ public ToolStripOverflowButton OverflowButton { if (toolStripOverflowButton == null) { - toolStripOverflowButton = new ToolStripOverflowButton(this); - toolStripOverflowButton.Overflow = ToolStripItemOverflow.Never; - toolStripOverflowButton.ParentInternal = this; - toolStripOverflowButton.Alignment = ToolStripItemAlignment.Right; + toolStripOverflowButton = new ToolStripOverflowButton(this) + { + Overflow = ToolStripItemOverflow.Never, + ParentInternal = this, + Alignment = ToolStripItemAlignment.Right + }; toolStripOverflowButton.Size = toolStripOverflowButton.GetPreferredSize(DisplayRectangle.Size - Padding.Size); } return toolStripOverflowButton; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs index b04e74cc5b6..683eb27cd00 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs @@ -254,8 +254,10 @@ protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) if ((DisplayStyle & ToolStripItemDisplayStyle.Image) == ToolStripItemDisplayStyle.Image) { - ToolStripItemImageRenderEventArgs rea = new ToolStripItemImageRenderEventArgs(e.Graphics, this, InternalLayout.ImageRectangle); - rea.ShiftOnPress = true; + ToolStripItemImageRenderEventArgs rea = new ToolStripItemImageRenderEventArgs(e.Graphics, this, InternalLayout.ImageRectangle) + { + ShiftOnPress = true + }; renderer.DrawItemImage(rea); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripComboBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripComboBox.cs index 93b3f9c4217..2696912e85e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripComboBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripComboBox.cs @@ -151,9 +151,11 @@ public ToolStripComboBox(Control c) : base(c) private static Control CreateControlInstance() { - ComboBox comboBox = new ToolStripComboBoxControl(); - comboBox.FlatStyle = FlatStyle.Popup; - comboBox.Font = ToolStripManager.DefaultFont; + ComboBox comboBox = new ToolStripComboBoxControl + { + FlatStyle = FlatStyle.Popup, + Font = ToolStripManager.DefaultFont + }; return comboBox; } [ diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs index c838687b621..977b0f68556 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs @@ -44,8 +44,10 @@ public ToolStripContainer() bottomPanel = new ToolStripPanel(this); leftPanel = new ToolStripPanel(this); rightPanel = new ToolStripPanel(this); - contentPanel = new ToolStripContentPanel(); - contentPanel.Dock = DockStyle.Fill; + contentPanel = new ToolStripContentPanel + { + Dock = DockStyle.Fill + }; topPanel.Dock = DockStyle.Top; bottomPanel.Dock = DockStyle.Bottom; rightPanel.Dock = DockStyle.Right; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownMenu.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownMenu.cs index af7549a70e9..f89d8a90b35 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownMenu.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownMenu.cs @@ -155,8 +155,10 @@ private ToolStripScrollButton DownScrollButton { if (downScrollButton == null) { - downScrollButton = new ToolStripScrollButton(false); - downScrollButton.ParentInternal = this; + downScrollButton = new ToolStripScrollButton(false) + { + ParentInternal = this + }; } return downScrollButton; } @@ -288,8 +290,10 @@ private ToolStripScrollButton UpScrollButton { if (upScrollButton == null) { - upScrollButton = new ToolStripScrollButton(true); - upScrollButton.ParentInternal = this; + upScrollButton = new ToolStripScrollButton(true) + { + ParentInternal = this + }; } return upScrollButton; } @@ -318,10 +322,12 @@ internal static ToolStripDropDownMenu FromHMenu(IntPtr hmenu, IWin32Window targe for (int i = 0; i < count; i++) { // peek at the i'th item. - NativeMethods.MENUITEMINFO_T_RW info = new NativeMethods.MENUITEMINFO_T_RW(); - info.cbSize = Marshal.SizeOf(); - info.fMask = NativeMethods.MIIM_FTYPE; - info.fType = NativeMethods.MIIM_FTYPE; + NativeMethods.MENUITEMINFO_T_RW info = new NativeMethods.MENUITEMINFO_T_RW + { + cbSize = Marshal.SizeOf(), + fMask = NativeMethods.MIIM_FTYPE, + fType = NativeMethods.MIIM_FTYPE + }; UnsafeNativeMethods.GetMenuItemInfo(menuHandle, i, /*fByPosition=*/ true, info); if (info.fType == NativeMethods.MFT_SEPARATOR) @@ -332,10 +338,12 @@ internal static ToolStripDropDownMenu FromHMenu(IntPtr hmenu, IWin32Window targe else { // its a menu item... lets fish out the command id - info = new NativeMethods.MENUITEMINFO_T_RW(); - info.cbSize = Marshal.SizeOf(); - info.fMask = NativeMethods.MIIM_ID; - info.fType = NativeMethods.MIIM_ID; + info = new NativeMethods.MENUITEMINFO_T_RW + { + cbSize = Marshal.SizeOf(), + fMask = NativeMethods.MIIM_ID, + fType = NativeMethods.MIIM_ID + }; UnsafeNativeMethods.GetMenuItemInfo(menuHandle, i, /*fByPosition=*/ true, info); // create the managed object - toolstripmenu item knows how to grok hmenu for information. @@ -343,10 +351,12 @@ internal static ToolStripDropDownMenu FromHMenu(IntPtr hmenu, IWin32Window targe // if there is a submenu fetch it. - info = new NativeMethods.MENUITEMINFO_T_RW(); - info.cbSize = Marshal.SizeOf(); - info.fMask = NativeMethods.MIIM_SUBMENU; - info.fType = NativeMethods.MIIM_SUBMENU; + info = new NativeMethods.MENUITEMINFO_T_RW + { + cbSize = Marshal.SizeOf(), + fMask = NativeMethods.MIIM_SUBMENU, + fType = NativeMethods.MIIM_SUBMENU + }; UnsafeNativeMethods.GetMenuItemInfo(menuHandle, i, /*fByPosition=*/ true, info); if (info.hSubMenu != IntPtr.Zero) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropTargetManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropTargetManager.cs index 459d60a9fbf..135cf69e7c1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropTargetManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropTargetManager.cs @@ -325,8 +325,10 @@ private void UpdateDropTarget(IDropTarget newTarget, DragEventArgs e) lastDropTarget = newTarget; if (newTarget != null) { - DragEventArgs dragEnterArgs = new DragEventArgs(e.Data, e.KeyState, e.X, e.Y, e.AllowedEffect, e.Effect); - dragEnterArgs.Effect = DragDropEffects.None; + DragEventArgs dragEnterArgs = new DragEventArgs(e.Data, e.KeyState, e.X, e.Y, e.AllowedEffect, e.Effect) + { + Effect = DragDropEffects.None + }; // tell the next drag target you've entered OnDragEnter(dragEnterArgs); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripHighContrastRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripHighContrastRenderer.cs index 1bb00eb84e8..a98c99eb605 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripHighContrastRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripHighContrastRenderer.cs @@ -130,11 +130,13 @@ protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) // color for highlighted text or menu text, depending on whether // the menu item is selected. ColorMap[] checkColorMap = new ColorMap[1]; - checkColorMap[0] = new ColorMap(); - checkColorMap[0].OldColor = checkColor; + checkColorMap[0] = new ColorMap + { + OldColor = checkColor, - checkColorMap[0].NewColor = ((e.Item.Selected || e.Item.Pressed) && e.Item.Enabled) ? - SystemColors.HighlightText : SystemColors.MenuText; + NewColor = ((e.Item.Selected || e.Item.Pressed) && e.Item.Enabled) ? + SystemColors.HighlightText : SystemColors.MenuText + }; // If we already have an image attributes associated with the event, // just add the color map. Otherwise, create a new one. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs index ba33c24d16e..4c629bb7c98 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs @@ -1167,9 +1167,11 @@ private void ProcessMouseButtonPressed(IntPtr hwndMouseMessageIsFrom, int x, int if (activeToolStrip != null) { - NativeMethods.POINT pt = new NativeMethods.POINT(); - pt.x = x; - pt.y = y; + NativeMethods.POINT pt = new NativeMethods.POINT + { + x = x, + y = y + }; UnsafeNativeMethods.MapWindowPoints(new HandleRef(activeToolStrip, hwndMouseMessageIsFrom), new HandleRef(activeToolStrip, activeToolStrip.Handle), pt, 1); if (!activeToolStrip.ClientRectangle.Contains(pt.x, pt.y)) { @@ -2277,8 +2279,10 @@ private static void MergeRecursive(ToolStripItem source, ToolStripItemCollection case MergeAction.Replace: case MergeAction.Remove: //Debug.WriteLine("remove"); - maction = new MergeHistoryItem(MergeAction.Insert); - maction.TargetItem = item; + maction = new MergeHistoryItem(MergeAction.Insert) + { + TargetItem = item + }; int indexOfDestinationItem = destinationItems.IndexOf(item); destinationItems.RemoveAt(indexOfDestinationItem); maction.Index = indexOfDestinationItem; @@ -2290,8 +2294,10 @@ private static void MergeRecursive(ToolStripItem source, ToolStripItemCollection { //Debug.WriteLine("replace"); //ToolStripItem clonedItem = source.Clone(); - maction = new MergeHistoryItem(MergeAction.Remove); - maction.PreviousIndexCollection = source.Owner.Items; + maction = new MergeHistoryItem(MergeAction.Remove) + { + PreviousIndexCollection = source.Owner.Items + }; maction.PreviousIndex = maction.PreviousIndexCollection.IndexOf(source); maction.TargetItem = source; destinationItems.Insert(indexOfDestinationItem, source); @@ -2307,8 +2313,10 @@ private static void MergeRecursive(ToolStripItem source, ToolStripItemCollection case MergeAction.Insert: if (source.MergeIndex > -1) { - maction = new MergeHistoryItem(MergeAction.Remove); - maction.PreviousIndexCollection = source.Owner.Items; + maction = new MergeHistoryItem(MergeAction.Remove) + { + PreviousIndexCollection = source.Owner.Items + }; maction.PreviousIndex = maction.PreviousIndexCollection.IndexOf(source); maction.TargetItem = source; int insertIndex = Math.Min(destinationItems.Count, source.MergeIndex); @@ -2320,8 +2328,10 @@ private static void MergeRecursive(ToolStripItem source, ToolStripItemCollection } break; case MergeAction.Append: - maction = new MergeHistoryItem(MergeAction.Remove); - maction.PreviousIndexCollection = source.Owner.Items; + maction = new MergeHistoryItem(MergeAction.Remove) + { + PreviousIndexCollection = source.Owner.Items + }; maction.PreviousIndex = maction.PreviousIndexCollection.IndexOf(source); maction.TargetItem = source; int index = destinationItems.Add(source); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs index 952d3e0cf91..7a280b9c20d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs @@ -764,11 +764,13 @@ private bool GetNativeMenuItemEnabled() Debug.Fail("why were we called to fetch native menu item info with nothing assigned?"); return false; } - NativeMethods.MENUITEMINFO_T_RW info = new NativeMethods.MENUITEMINFO_T_RW(); - info.cbSize = Marshal.SizeOf(); - info.fMask = NativeMethods.MIIM_STATE; - info.fType = NativeMethods.MIIM_STATE; - info.wID = nativeMenuCommandID; + NativeMethods.MENUITEMINFO_T_RW info = new NativeMethods.MENUITEMINFO_T_RW + { + cbSize = Marshal.SizeOf(), + fMask = NativeMethods.MIIM_STATE, + fType = NativeMethods.MIIM_STATE, + wID = nativeMenuCommandID + }; UnsafeNativeMethods.GetMenuItemInfo(new HandleRef(this, nativeMenuHandle), nativeMenuCommandID, /*fByPosition instead of ID=*/ false, info); return ((info.fState & NativeMethods.MFS_DISABLED) == 0); @@ -786,11 +788,13 @@ private string GetNativeMenuItemTextAndShortcut() string text = null; // fetch the string length - NativeMethods.MENUITEMINFO_T_RW info = new NativeMethods.MENUITEMINFO_T_RW(); - info.fMask = NativeMethods.MIIM_STRING; - info.fType = NativeMethods.MIIM_STRING; - info.wID = nativeMenuCommandID; - info.dwTypeData = IntPtr.Zero; + NativeMethods.MENUITEMINFO_T_RW info = new NativeMethods.MENUITEMINFO_T_RW + { + fMask = NativeMethods.MIIM_STRING, + fType = NativeMethods.MIIM_STRING, + wID = nativeMenuCommandID, + dwTypeData = IntPtr.Zero + }; UnsafeNativeMethods.GetMenuItemInfo(new HandleRef(this, nativeMenuHandle), nativeMenuCommandID, /*fByPosition instead of ID=*/ false, info); if (info.cch > 0) @@ -837,10 +841,12 @@ private Image GetNativeMenuItemImage() return null; } - NativeMethods.MENUITEMINFO_T_RW info = new NativeMethods.MENUITEMINFO_T_RW(); - info.fMask = NativeMethods.MIIM_BITMAP; - info.fType = NativeMethods.MIIM_BITMAP; - info.wID = nativeMenuCommandID; + NativeMethods.MENUITEMINFO_T_RW info = new NativeMethods.MENUITEMINFO_T_RW + { + fMask = NativeMethods.MIIM_BITMAP, + fType = NativeMethods.MIIM_BITMAP, + wID = nativeMenuCommandID + }; UnsafeNativeMethods.GetMenuItemInfo(new HandleRef(this, nativeMenuHandle), nativeMenuCommandID, /*fByPosition instead of ID=*/ false, info); if (info.hbmpItem != IntPtr.Zero && info.hbmpItem.ToInt32() > NativeMethods.HBMMENU_POPUP_MINIMIZE) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProgressBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProgressBar.cs index 10e67e7ba5c..9c1814c12ea 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProgressBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProgressBar.cs @@ -289,8 +289,10 @@ protected override AccessibleObject CreateAccessibilityInstance() private static Control CreateControlInstance() { - ProgressBar progressBar = new ToolStripProgressBarControl(); - progressBar.Size = new Size(100, 15); + ProgressBar progressBar = new ToolStripProgressBarControl + { + Size = new Size(100, 15) + }; return progressBar; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripScrollButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripScrollButton.cs index 04ab53e6810..a59e06a1a4f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripScrollButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripScrollButton.cs @@ -39,9 +39,11 @@ public ToolStripScrollButton(bool up) : base(CreateControlInstance(up)) private static Control CreateControlInstance(bool up) { - StickyLabel label = new StickyLabel(); - label.ImageAlign = ContentAlignment.MiddleCenter; - label.Image = (up) ? UpImage : DownImage; + StickyLabel label = new StickyLabel + { + ImageAlign = ContentAlignment.MiddleCenter, + Image = (up) ? UpImage : DownImage + }; return label; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripTextBox.cs index eedc1b8df25..94e31a9b973 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripTextBox.cs @@ -166,9 +166,11 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga private static Control CreateControlInstance() { - TextBox textBox = new ToolStripTextBoxControl(); - textBox.BorderStyle = BorderStyle.Fixed3D; - textBox.AutoSize = true; + TextBox textBox = new ToolStripTextBoxControl + { + BorderStyle = BorderStyle.Fixed3D, + AutoSize = true + }; return textBox; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs index 3a3b1a0f477..dac4902d916 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs @@ -923,8 +923,10 @@ private void CreateHandle() try { - NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); - icc.dwICC = NativeMethods.ICC_TAB_CLASSES; + NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX + { + dwICC = NativeMethods.ICC_TAB_CLASSES + }; SafeNativeMethods.InitCommonControlsEx(icc); CreateParams cp = CreateParams; // Avoid reentrant call to CreateHandle @@ -1225,9 +1227,11 @@ private NativeMethods.TOOLINFO_TOOLTIP GetMinToolInfoForTool(IWin32Window tool) private NativeMethods.TOOLINFO_TOOLTIP GetMinToolInfoForHandle(IntPtr handle) { - NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP(); - ti.cbSize = Marshal.SizeOf(); - ti.hwnd = handle; + NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP + { + cbSize = Marshal.SizeOf(), + hwnd = handle + }; ti.uFlags |= NativeMethods.TTF_IDISHWND; ti.uId = handle; return ti; @@ -1289,9 +1293,11 @@ private NativeMethods.TOOLINFO_TOOLTIP GetTOOLINFO(Control ctl, string caption, private NativeMethods.TOOLINFO_TOOLTIP GetWinTOOLINFO(IntPtr hWnd) { - NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP(); - ti.cbSize = Marshal.SizeOf(); - ti.hwnd = hWnd; + NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP + { + cbSize = Marshal.SizeOf(), + hwnd = hWnd + }; ti.uFlags |= NativeMethods.TTF_IDISHWND | NativeMethods.TTF_TRANSPARENT | NativeMethods.TTF_SUBCLASS; // RightToLeft reading order @@ -1695,11 +1701,13 @@ private void ShowTooltip(string text, IWin32Window win, int duration) // calculate the dimensions of the visible rectangle which // is used to estimate the upper x,y of the tooltip placement - NativeMethods.RECT visibleRect = new NativeMethods.RECT(); - visibleRect.left = (r.left < screen.WorkingArea.Left) ? screen.WorkingArea.Left : r.left; - visibleRect.top = (r.top < screen.WorkingArea.Top) ? screen.WorkingArea.Top : r.top; - visibleRect.right = (r.right > screen.WorkingArea.Right) ? screen.WorkingArea.Right : r.right; - visibleRect.bottom = (r.bottom > screen.WorkingArea.Bottom) ? screen.WorkingArea.Bottom : r.bottom; + NativeMethods.RECT visibleRect = new NativeMethods.RECT + { + left = (r.left < screen.WorkingArea.Left) ? screen.WorkingArea.Left : r.left, + top = (r.top < screen.WorkingArea.Top) ? screen.WorkingArea.Top : r.top, + right = (r.right > screen.WorkingArea.Right) ? screen.WorkingArea.Right : r.right, + bottom = (r.bottom > screen.WorkingArea.Bottom) ? screen.WorkingArea.Bottom : r.bottom + }; p.X = visibleRect.left + (visibleRect.right - visibleRect.left) / 2; p.Y = visibleRect.top + (visibleRect.bottom - visibleRect.top) / 2; @@ -2378,8 +2386,10 @@ private void WmMove() { NativeMethods.RECT r = new NativeMethods.RECT(); UnsafeNativeMethods.GetWindowRect(new HandleRef(this, Handle), ref r); - NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP(); - ti.cbSize = Marshal.SizeOf(); + NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP + { + cbSize = Marshal.SizeOf() + }; int ret = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_GETCURRENTTOOL, 0, ti); if (ret != 0) { @@ -2426,8 +2436,10 @@ private void WmMove() private void WmMouseActivate(ref Message msg) { - NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP(); - ti.cbSize = Marshal.SizeOf(); + NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP + { + cbSize = Marshal.SizeOf() + }; int ret = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_GETCURRENTTOOL, 0, ti); if (ret != 0) @@ -2484,8 +2496,10 @@ private void WmShow() NativeMethods.RECT r = new NativeMethods.RECT(); UnsafeNativeMethods.GetWindowRect(new HandleRef(this, Handle), ref r); - NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP(); - ti.cbSize = Marshal.SizeOf(); + NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP + { + cbSize = Marshal.SizeOf() + }; int ret = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_GETCURRENTTOOL, 0, ti); if (ret != 0) @@ -2599,8 +2613,10 @@ private unsafe void WmWindowPosChanging(ref Message m) - NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP(); - ti.cbSize = Marshal.SizeOf(); + NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP + { + cbSize = Marshal.SizeOf() + }; int ret = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_GETCURRENTTOOL, 0, ti); if (ret != 0) { @@ -2698,8 +2714,10 @@ private unsafe void WmWindowPosChanging(ref Message m) private void WmPop() { - NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP(); - ti.cbSize = Marshal.SizeOf(); + NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP + { + cbSize = Marshal.SizeOf() + }; int ret = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_GETCURRENTTOOL, 0, ti); if (ret != 0) { @@ -2826,8 +2844,10 @@ private void WndProc(ref Message msg) { return; } - NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP(); - ti.cbSize = Marshal.SizeOf(); + NativeMethods.TOOLINFO_TOOLTIP ti = new NativeMethods.TOOLINFO_TOOLTIP + { + cbSize = Marshal.SizeOf() + }; int ret = unchecked((int)(long)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_GETCURRENTTOOL, 0, ti)); if (ret != 0) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs index b5341aa496e..10d85083a43 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs @@ -820,8 +820,10 @@ protected override void CreateHandle() IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); try { - NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); - icc.dwICC = NativeMethods.ICC_BAR_CLASSES; + NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX + { + dwICC = NativeMethods.ICC_BAR_CLASSES + }; SafeNativeMethods.InitCommonControlsEx(icc); } finally diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs index d415508593a..380921a4fba 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs @@ -368,10 +368,12 @@ internal bool CheckedInternal if (tv == null || !tv.IsHandleCreated || tv.IsDisposed) return; - NativeMethods.TV_ITEM item = new NativeMethods.TV_ITEM(); - item.mask = NativeMethods.TVIF_HANDLE | NativeMethods.TVIF_STATE; - item.hItem = handle; - item.stateMask = NativeMethods.TVIS_STATEIMAGEMASK; + NativeMethods.TV_ITEM item = new NativeMethods.TV_ITEM + { + mask = NativeMethods.TVIF_HANDLE | NativeMethods.TVIF_STATE, + hItem = handle, + stateMask = NativeMethods.TVIS_STATEIMAGEMASK + }; item.state |= value ? CHECKED : UNCHECKED; UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_SETITEM, 0, ref item); @@ -394,10 +396,12 @@ public bool Checked #if DEBUG if (handle != IntPtr.Zero) { - NativeMethods.TV_ITEM item = new NativeMethods.TV_ITEM(); - item.mask = NativeMethods.TVIF_HANDLE | NativeMethods.TVIF_STATE; - item.hItem = handle; - item.stateMask = NativeMethods.TVIS_STATEIMAGEMASK; + NativeMethods.TV_ITEM item = new NativeMethods.TV_ITEM + { + mask = NativeMethods.TVIF_HANDLE | NativeMethods.TVIF_STATE, + hItem = handle, + stateMask = NativeMethods.TVIS_STATEIMAGEMASK + }; UnsafeNativeMethods.SendMessage(new HandleRef(null, TreeView.Handle), NativeMethods.TVM_GETITEM, 0, ref item); Debug.Assert(!TreeView.CheckBoxes || ((item.state >> SHIFTVAL) > 1) == CheckedInternal, "isChecked on node '" + Name + "' did not match the state in TVM_GETITEM."); @@ -1017,10 +1021,12 @@ internal int State { return 0; } - NativeMethods.TV_ITEM item = new NativeMethods.TV_ITEM(); - item.hItem = Handle; - item.mask = NativeMethods.TVIF_HANDLE | NativeMethods.TVIF_STATE; - item.stateMask = NativeMethods.TVIS_SELECTED | NativeMethods.TVIS_EXPANDED; + NativeMethods.TV_ITEM item = new NativeMethods.TV_ITEM + { + hItem = Handle, + mask = NativeMethods.TVIF_HANDLE | NativeMethods.TVIF_STATE, + stateMask = NativeMethods.TVIS_SELECTED | NativeMethods.TVIS_EXPANDED + }; UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_GETITEM, 0, ref item); return item.state; } @@ -1846,9 +1852,11 @@ internal void Realize(bool insertFirst) throw new InvalidOperationException(SR.InvalidCrossThreadControlCall); } - NativeMethods.TV_INSERTSTRUCT tvis = new NativeMethods.TV_INSERTSTRUCT(); - tvis.item_mask = insertMask; - tvis.hParent = parent.handle; + NativeMethods.TV_INSERTSTRUCT tvis = new NativeMethods.TV_INSERTSTRUCT + { + item_mask = insertMask, + hParent = parent.handle + }; TreeNode prev = PrevNode; if (insertFirst || prev == null) { @@ -2017,11 +2025,13 @@ private void ResetExpandedState(TreeView tv) { Debug.Assert(tv.IsHandleCreated, "nonexistent handle"); - NativeMethods.TV_ITEM item = new NativeMethods.TV_ITEM(); - item.mask = NativeMethods.TVIF_HANDLE | NativeMethods.TVIF_STATE; - item.hItem = handle; - item.stateMask = NativeMethods.TVIS_EXPANDEDONCE; - item.state = 0; + NativeMethods.TV_ITEM item = new NativeMethods.TV_ITEM + { + mask = NativeMethods.TVIF_HANDLE | NativeMethods.TVIF_STATE, + hItem = handle, + stateMask = NativeMethods.TVIS_EXPANDEDONCE, + state = 0 + }; UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_SETITEM, 0, ref item); } @@ -2121,9 +2131,11 @@ private void UpdateNode(int mask) TreeView tv = TreeView; Debug.Assert(tv != null, "TreeNode has handle but no TreeView"); - NativeMethods.TV_ITEM item = new NativeMethods.TV_ITEM(); - item.mask = NativeMethods.TVIF_HANDLE | mask; - item.hItem = handle; + NativeMethods.TV_ITEM item = new NativeMethods.TV_ITEM + { + mask = NativeMethods.TVIF_HANDLE | mask, + hItem = handle + }; if ((mask & NativeMethods.TVIF_TEXT) != 0) item.pszText = Marshal.StringToHGlobalAuto(text); if ((mask & NativeMethods.TVIF_IMAGE) != 0) @@ -2163,11 +2175,12 @@ internal void UpdateImage() return; } - NativeMethods.TV_ITEM item = new NativeMethods.TV_ITEM(); - - item.mask = NativeMethods.TVIF_HANDLE | NativeMethods.TVIF_IMAGE; - item.hItem = Handle; - item.iImage = Math.Max(0, ((ImageIndexer.ActualIndex >= tv.ImageList.Images.Count) ? tv.ImageList.Images.Count - 1 : ImageIndexer.ActualIndex)); + NativeMethods.TV_ITEM item = new NativeMethods.TV_ITEM + { + mask = NativeMethods.TVIF_HANDLE | NativeMethods.TVIF_IMAGE, + hItem = Handle, + iImage = Math.Max(0, ((ImageIndexer.ActualIndex >= tv.ImageList.Images.Count) ? tv.ImageList.Images.Count - 1 : ImageIndexer.ActualIndex)) + }; UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_SETITEM, 0, ref item); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeCollection.cs index 42ebef62337..1265e7b4d75 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeCollection.cs @@ -176,8 +176,10 @@ public virtual TreeNode Add(string text) /// public virtual TreeNode Add(string key, string text) { - TreeNode tn = new TreeNode(text); - tn.Name = key; + TreeNode tn = new TreeNode(text) + { + Name = key + }; Add(tn); return tn; } @@ -187,9 +189,11 @@ public virtual TreeNode Add(string key, string text) /// public virtual TreeNode Add(string key, string text, int imageIndex) { - TreeNode tn = new TreeNode(text); - tn.Name = key; - tn.ImageIndex = imageIndex; + TreeNode tn = new TreeNode(text) + { + Name = key, + ImageIndex = imageIndex + }; Add(tn); return tn; } @@ -199,9 +203,11 @@ public virtual TreeNode Add(string key, string text, int imageIndex) /// public virtual TreeNode Add(string key, string text, string imageKey) { - TreeNode tn = new TreeNode(text); - tn.Name = key; - tn.ImageKey = imageKey; + TreeNode tn = new TreeNode(text) + { + Name = key, + ImageKey = imageKey + }; Add(tn); return tn; } @@ -211,8 +217,10 @@ public virtual TreeNode Add(string key, string text, string imageKey) /// public virtual TreeNode Add(string key, string text, int imageIndex, int selectedImageIndex) { - TreeNode tn = new TreeNode(text, imageIndex, selectedImageIndex); - tn.Name = key; + TreeNode tn = new TreeNode(text, imageIndex, selectedImageIndex) + { + Name = key + }; Add(tn); return tn; } @@ -222,10 +230,12 @@ public virtual TreeNode Add(string key, string text, int imageIndex, int selecte /// public virtual TreeNode Add(string key, string text, string imageKey, string selectedImageKey) { - TreeNode tn = new TreeNode(text); - tn.Name = key; - tn.ImageKey = imageKey; - tn.SelectedImageKey = selectedImageKey; + TreeNode tn = new TreeNode(text) + { + Name = key, + ImageKey = imageKey, + SelectedImageKey = selectedImageKey + }; Add(tn); return tn; } @@ -525,8 +535,10 @@ public virtual TreeNode Insert(int index, string text) /// public virtual TreeNode Insert(int index, string key, string text) { - TreeNode tn = new TreeNode(text); - tn.Name = key; + TreeNode tn = new TreeNode(text) + { + Name = key + }; Insert(index, tn); return tn; } @@ -536,9 +548,11 @@ public virtual TreeNode Insert(int index, string key, string text) /// public virtual TreeNode Insert(int index, string key, string text, int imageIndex) { - TreeNode tn = new TreeNode(text); - tn.Name = key; - tn.ImageIndex = imageIndex; + TreeNode tn = new TreeNode(text) + { + Name = key, + ImageIndex = imageIndex + }; Insert(index, tn); return tn; } @@ -548,9 +562,11 @@ public virtual TreeNode Insert(int index, string key, string text, int imageInde /// public virtual TreeNode Insert(int index, string key, string text, string imageKey) { - TreeNode tn = new TreeNode(text); - tn.Name = key; - tn.ImageKey = imageKey; + TreeNode tn = new TreeNode(text) + { + Name = key, + ImageKey = imageKey + }; Insert(index, tn); return tn; } @@ -560,8 +576,10 @@ public virtual TreeNode Insert(int index, string key, string text, string imageK /// public virtual TreeNode Insert(int index, string key, string text, int imageIndex, int selectedImageIndex) { - TreeNode tn = new TreeNode(text, imageIndex, selectedImageIndex); - tn.Name = key; + TreeNode tn = new TreeNode(text, imageIndex, selectedImageIndex) + { + Name = key + }; Insert(index, tn); return tn; } @@ -571,10 +589,12 @@ public virtual TreeNode Insert(int index, string key, string text, int imageInde /// public virtual TreeNode Insert(int index, string key, string text, string imageKey, string selectedImageKey) { - TreeNode tn = new TreeNode(text); - tn.Name = key; - tn.ImageKey = imageKey; - tn.SelectedImageKey = selectedImageKey; + TreeNode tn = new TreeNode(text) + { + Name = key, + ImageKey = imageKey, + SelectedImageKey = selectedImageKey + }; Insert(index, tn); return tn; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs index 0f52409860d..2582a63c066 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs @@ -1680,8 +1680,10 @@ protected override void CreateHandle() IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); try { - NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); - icc.dwICC = NativeMethods.ICC_TREEVIEW_CLASSES; + NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX + { + dwICC = NativeMethods.ICC_TREEVIEW_CLASSES + }; SafeNativeMethods.InitCommonControlsEx(icc); } finally @@ -1808,9 +1810,11 @@ public TreeViewHitTestInfo HitTest(Point pt) /// public TreeViewHitTestInfo HitTest(int x, int y) { - NativeMethods.TV_HITTESTINFO tvhi = new NativeMethods.TV_HITTESTINFO(); - tvhi.pt_x = x; - tvhi.pt_y = y; + NativeMethods.TV_HITTESTINFO tvhi = new NativeMethods.TV_HITTESTINFO + { + pt_x = x, + pt_y = y + }; IntPtr hnode = UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TVM_HITTEST, 0, tvhi); TreeNode node = (hnode == IntPtr.Zero ? null : NodeFromHandle(hnode)); TreeViewHitTestLocations loc = (TreeViewHitTestLocations)tvhi.flags; @@ -1856,10 +1860,11 @@ public TreeNode GetNodeAt(Point pt) /// public TreeNode GetNodeAt(int x, int y) { - NativeMethods.TV_HITTESTINFO tvhi = new NativeMethods.TV_HITTESTINFO(); - - tvhi.pt_x = x; - tvhi.pt_y = y; + NativeMethods.TV_HITTESTINFO tvhi = new NativeMethods.TV_HITTESTINFO + { + pt_x = x, + pt_y = y + }; IntPtr hnode = UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TVM_HITTEST, 0, tvhi); @@ -2825,9 +2830,11 @@ private void CustomDraw(ref Message m) { Rectangle bounds = node.RowBounds; - NativeMethods.SCROLLINFO si = new NativeMethods.SCROLLINFO(); - si.cbSize = Marshal.SizeOf(); - si.fMask = NativeMethods.SIF_POS; + NativeMethods.SCROLLINFO si = new NativeMethods.SCROLLINFO + { + cbSize = Marshal.SizeOf(), + fMask = NativeMethods.SIF_POS + }; if (UnsafeNativeMethods.GetScrollInfo(new HandleRef(this, Handle), NativeMethods.SB_HORZ, si) != false) { @@ -3297,10 +3304,12 @@ protected override void WndProc(ref Message m) // Check for invalid node handle if (item.hItem != IntPtr.Zero) { - NativeMethods.TV_ITEM item1 = new NativeMethods.TV_ITEM(); - item1.mask = NativeMethods.TVIF_HANDLE | NativeMethods.TVIF_STATE; - item1.hItem = item.hItem; - item1.stateMask = NativeMethods.TVIS_STATEIMAGEMASK; + NativeMethods.TV_ITEM item1 = new NativeMethods.TV_ITEM + { + mask = NativeMethods.TVIF_HANDLE | NativeMethods.TVIF_STATE, + hItem = item.hItem, + stateMask = NativeMethods.TVIS_STATEIMAGEMASK + }; UnsafeNativeMethods.SendMessage(new HandleRef(null, Handle), NativeMethods.TVM_GETITEM, 0, ref item1); TreeNode node = NodeFromHandle(item.hItem); @@ -3363,9 +3372,11 @@ protected override void WndProc(ref Message m) } //Always Reset the MouseupFired.... treeViewState[TREEVIEWSTATE_mouseUpFired] = false; - NativeMethods.TV_HITTESTINFO tvhip = new NativeMethods.TV_HITTESTINFO(); - tvhip.pt_x = NativeMethods.Util.SignedLOWORD(m.LParam); - tvhip.pt_y = NativeMethods.Util.SignedHIWORD(m.LParam); + NativeMethods.TV_HITTESTINFO tvhip = new NativeMethods.TV_HITTESTINFO + { + pt_x = NativeMethods.Util.SignedLOWORD(m.LParam), + pt_y = NativeMethods.Util.SignedHIWORD(m.LParam) + }; hNodeMouseDown = UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TVM_HITTEST, 0, tvhip); // This gets around the TreeView behavior of temporarily moving the selection @@ -3394,9 +3405,11 @@ protected override void WndProc(ref Message m) break; case Interop.WindowMessages.WM_LBUTTONUP: case Interop.WindowMessages.WM_RBUTTONUP: - NativeMethods.TV_HITTESTINFO tvhi = new NativeMethods.TV_HITTESTINFO(); - tvhi.pt_x = NativeMethods.Util.SignedLOWORD(m.LParam); - tvhi.pt_y = NativeMethods.Util.SignedHIWORD(m.LParam); + NativeMethods.TV_HITTESTINFO tvhi = new NativeMethods.TV_HITTESTINFO + { + pt_x = NativeMethods.Util.SignedLOWORD(m.LParam), + pt_y = NativeMethods.Util.SignedHIWORD(m.LParam) + }; IntPtr hnode = UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TVM_HITTEST, 0, tvhi); //Important for CheckBoxes ... click needs to be fired ... // @@ -3469,9 +3482,11 @@ protected override void WndProc(ref Message m) //Always Reset the MouseupFired.... treeViewState[TREEVIEWSTATE_mouseUpFired] = false; //Cache the hit-tested node for verification when mouse up is fired - NativeMethods.TV_HITTESTINFO tvhit = new NativeMethods.TV_HITTESTINFO(); - tvhit.pt_x = NativeMethods.Util.SignedLOWORD(m.LParam); - tvhit.pt_y = NativeMethods.Util.SignedHIWORD(m.LParam); + NativeMethods.TV_HITTESTINFO tvhit = new NativeMethods.TV_HITTESTINFO + { + pt_x = NativeMethods.Util.SignedLOWORD(m.LParam), + pt_y = NativeMethods.Util.SignedHIWORD(m.LParam) + }; hNodeMouseDown = UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TVM_HITTEST, 0, tvhit); WmMouseDown(ref m, MouseButtons.Right, 1); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs index 7df8702d580..9e250b3828c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs @@ -87,9 +87,11 @@ public UpDownBase() } upDownButtons = new UpDownButtons(this); - upDownEdit = new UpDownEdit(this); - upDownEdit.BorderStyle = BorderStyle.None; - upDownEdit.AutoSize = false; + upDownEdit = new UpDownEdit(this) + { + BorderStyle = BorderStyle.None, + AutoSize = false + }; upDownEdit.KeyDown += new KeyEventHandler(OnTextBoxKeyDown); upDownEdit.KeyPress += new KeyPressEventHandler(OnTextBoxKeyPress); upDownEdit.TextChanged += new EventHandler(OnTextBoxTextChanged); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs index 8b605650661..fb6c03501aa 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs @@ -1296,8 +1296,10 @@ protected override void CreateSink() object ax = activeXInstance; if (ax != null) { - webBrowserEvent = new WebBrowserEvent(this); - webBrowserEvent.AllowNavigation = AllowNavigation; + webBrowserEvent = new WebBrowserEvent(this) + { + AllowNavigation = AllowNavigation + }; cookie = new AxHost.ConnectionPointCookie(ax, webBrowserEvent, typeof(UnsafeNativeMethods.DWebBrowserEvents2)); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs index cc163fab458..f3cdb1ed64f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs @@ -270,11 +270,13 @@ public override bool PreProcessMessage(ref Message msg) // Convert Message to NativeMethods.MSG - NativeMethods.MSG win32Message = new NativeMethods.MSG(); - win32Message.message = msg.Msg; - win32Message.wParam = msg.WParam; - win32Message.lParam = msg.LParam; - win32Message.hwnd = msg.HWnd; + NativeMethods.MSG win32Message = new NativeMethods.MSG + { + message = msg.Msg, + wParam = msg.WParam, + lParam = msg.LParam, + hwnd = msg.HWnd + }; SetAXHostState(WebBrowserHelper.siteProcessedInputKey, false); try @@ -362,12 +364,14 @@ protected internal override bool ProcessMnemonic(char charCode) // Sadly, we don't have a message so we must fake one ourselves. // The message we are faking is a WM_SYSKEYDOWN with the right // alt key setting. - NativeMethods.MSG msg = new NativeMethods.MSG(); - msg.hwnd = IntPtr.Zero; - msg.message = Interop.WindowMessages.WM_SYSKEYDOWN; - msg.wParam = (IntPtr)char.ToUpper(charCode, CultureInfo.CurrentCulture); - msg.lParam = (IntPtr)0x20180001; - msg.time = SafeNativeMethods.GetTickCount(); + NativeMethods.MSG msg = new NativeMethods.MSG + { + hwnd = IntPtr.Zero, + message = Interop.WindowMessages.WM_SYSKEYDOWN, + wParam = (IntPtr)char.ToUpper(charCode, CultureInfo.CurrentCulture), + lParam = (IntPtr)0x20180001, + time = SafeNativeMethods.GetTickCount() + }; NativeMethods.POINT p = new NativeMethods.POINT(); UnsafeNativeMethods.GetCursorPos(p); msg.pt_x = p.x; @@ -1235,9 +1239,11 @@ private void OnNewSelection(object sender, EventArgs e) private Size SetExtent(int width, int height) { - NativeMethods.tagSIZEL sz = new NativeMethods.tagSIZEL(); - sz.cx = width; - sz.cy = height; + NativeMethods.tagSIZEL sz = new NativeMethods.tagSIZEL + { + cx = width, + cy = height + }; bool resetExtents = DesignMode; try { @@ -1273,9 +1279,11 @@ private Size GetExtent() private void HiMetric2Pixel(NativeMethods.tagSIZEL sz, NativeMethods.tagSIZEL szout) { - NativeMethods._POINTL phm = new NativeMethods._POINTL(); - phm.x = sz.cx; - phm.y = sz.cy; + NativeMethods._POINTL phm = new NativeMethods._POINTL + { + x = sz.cx, + y = sz.cy + }; NativeMethods.tagPOINTF pcont = new NativeMethods.tagPOINTF(); ((UnsafeNativeMethods.IOleControlSite)ActiveXSite).TransformCoords(phm, pcont, NativeMethods.ActiveX.XFORMCOORDS_SIZE | NativeMethods.ActiveX.XFORMCOORDS_HIMETRICTOCONTAINER); szout.cx = (int)pcont.x; @@ -1284,9 +1292,11 @@ private void HiMetric2Pixel(NativeMethods.tagSIZEL sz, NativeMethods.tagSIZEL sz private void Pixel2hiMetric(NativeMethods.tagSIZEL sz, NativeMethods.tagSIZEL szout) { - NativeMethods.tagPOINTF pcont = new NativeMethods.tagPOINTF(); - pcont.x = (float)sz.cx; - pcont.y = (float)sz.cy; + NativeMethods.tagPOINTF pcont = new NativeMethods.tagPOINTF + { + x = (float)sz.cx, + y = (float)sz.cy + }; NativeMethods._POINTL phm = new NativeMethods._POINTL(); ((UnsafeNativeMethods.IOleControlSite)ActiveXSite).TransformCoords(phm, pcont, NativeMethods.ActiveX.XFORMCOORDS_SIZE | NativeMethods.ActiveX.XFORMCOORDS_CONTAINERTOHIMETRIC); szout.cx = phm.x; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs index e1e79c4af71..8f58260f74c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs @@ -144,11 +144,13 @@ int UnsafeNativeMethods.IOleControlSite.TranslateAccelerator(ref NativeMethods.M Debug.Assert(!Host.GetAXHostState(WebBrowserHelper.siteProcessedInputKey), "Re-entering UnsafeNativeMethods.IOleControlSite.TranslateAccelerator!!!"); Host.SetAXHostState(WebBrowserHelper.siteProcessedInputKey, true); - Message msg = new Message(); - msg.Msg = pMsg.message; - msg.WParam = pMsg.wParam; - msg.LParam = pMsg.lParam; - msg.HWnd = pMsg.hwnd; + Message msg = new Message + { + Msg = pMsg.message, + WParam = pMsg.wParam, + LParam = pMsg.lParam, + HWnd = pMsg.hwnd + }; try { diff --git a/src/System.Windows.Forms/src/misc/GDI/DeviceContexts.cs b/src/System.Windows.Forms/src/misc/GDI/DeviceContexts.cs index e61ba168e76..53632d01ad0 100644 --- a/src/System.Windows.Forms/src/misc/GDI/DeviceContexts.cs +++ b/src/System.Windows.Forms/src/misc/GDI/DeviceContexts.cs @@ -45,8 +45,10 @@ internal static void AddDeviceContext(DeviceContext dc) { if (activeDeviceContexts == null) { - activeDeviceContexts = new ClientUtils.WeakRefCollection(); - activeDeviceContexts.RefCheckThreshold = 20; + activeDeviceContexts = new ClientUtils.WeakRefCollection + { + RefCheckThreshold = 20 + }; } if (!activeDeviceContexts.Contains(dc)) diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs index 4909b2c0ed1..7b8b3b6b611 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs @@ -273,9 +273,11 @@ public static WindowsFont FromHfont(IntPtr hFont, bool takeOwnership) IntNativeMethods.LOGFONT lf = new IntNativeMethods.LOGFONT(); IntUnsafeNativeMethods.GetObject(new HandleRef(null, hFont), lf); - WindowsFont wf = new WindowsFont(lf, /*createHandle*/ false); - wf.hFont = hFont; - wf.ownHandle = takeOwnership; // if true, hFont will be deleted on dispose. + WindowsFont wf = new WindowsFont(lf, /*createHandle*/ false) + { + hFont = hFont, + ownHandle = takeOwnership // if true, hFont will be deleted on dispose. + }; return wf; } diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics.cs index e8e85b79502..482bfd8b0bb 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics.cs @@ -73,8 +73,10 @@ public WindowsGraphics(DeviceContext dc) public static WindowsGraphics CreateMeasurementWindowsGraphics() { DeviceContext dc = DeviceContext.FromCompatibleDC(IntPtr.Zero); - WindowsGraphics wg = new WindowsGraphics(dc); - wg.disposeDc = true; // we create it, we dispose it. + WindowsGraphics wg = new WindowsGraphics(dc) + { + disposeDc = true // we create it, we dispose it. + }; return wg; } @@ -89,8 +91,10 @@ public static WindowsGraphics CreateMeasurementWindowsGraphics() public static WindowsGraphics CreateMeasurementWindowsGraphics(IntPtr screenDC) { DeviceContext dc = DeviceContext.FromCompatibleDC(screenDC); - WindowsGraphics wg = new WindowsGraphics(dc); - wg.disposeDc = true; // we create it, we dispose it. + WindowsGraphics wg = new WindowsGraphics(dc) + { + disposeDc = true // we create it, we dispose it. + }; return wg; } @@ -98,8 +102,10 @@ public static WindowsGraphics CreateMeasurementWindowsGraphics(IntPtr screenDC) public static WindowsGraphics FromHwnd(IntPtr hWnd) { DeviceContext dc = DeviceContext.FromHwnd(hWnd); - WindowsGraphics wg = new WindowsGraphics(dc); - wg.disposeDc = true; // we create it, we dispose it. + WindowsGraphics wg = new WindowsGraphics(dc) + { + disposeDc = true // we create it, we dispose it. + }; return wg; } @@ -111,8 +117,10 @@ public static WindowsGraphics FromHdc(IntPtr hDc) Debug.Assert(hDc != IntPtr.Zero, "null hDc"); DeviceContext dc = DeviceContext.FromHdc(hDc); - WindowsGraphics wg = new WindowsGraphics(dc); - wg.disposeDc = true; // we create it, we dispose it. + WindowsGraphics wg = new WindowsGraphics(dc) + { + disposeDc = true // we create it, we dispose it. + }; return wg; } diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsPen.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsPen.cs index 595895f1018..e79a69b6830 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsPen.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsPen.cs @@ -119,11 +119,12 @@ private void CreatePen() } else { - IntNativeMethods.LOGBRUSH lb = new IntNativeMethods.LOGBRUSH(); - - lb.lbColor = ColorTranslator.ToWin32(wndBrush.Color); - lb.lbStyle = IntNativeMethods.BS_SOLID; - lb.lbHatch = 0; + IntNativeMethods.LOGBRUSH lb = new IntNativeMethods.LOGBRUSH + { + lbColor = ColorTranslator.ToWin32(wndBrush.Color), + lbStyle = IntNativeMethods.BS_SOLID, + lbHatch = 0 + }; // Note: We currently don't support custom styles, that's why 0 and null for last two params. nativeHandle = IntSafeNativeMethods.ExtCreatePen((int)style, width, lb, 0, null); diff --git a/src/System.Windows.Forms/tests/IntegrationTests/System.Windows.Forms.IntegrationTests/TestHelpers.cs b/src/System.Windows.Forms/tests/IntegrationTests/System.Windows.Forms.IntegrationTests/TestHelpers.cs index 75e760db9df..37b3d1a5e84 100644 --- a/src/System.Windows.Forms/tests/IntegrationTests/System.Windows.Forms.IntegrationTests/TestHelpers.cs +++ b/src/System.Windows.Forms/tests/IntegrationTests/System.Windows.Forms.IntegrationTests/TestHelpers.cs @@ -40,8 +40,10 @@ public static Process StartProcess(string byPathFromBinToExe) throw new DirectoryNotFoundException(dotnetPath + " directory cannot be found."); } - ProcessStartInfo startInfo = new ProcessStartInfo(); - startInfo.FileName = Path.Combine(BinPath(), byPathFromBinToExe.Trim('\\')); + ProcessStartInfo startInfo = new ProcessStartInfo + { + FileName = Path.Combine(BinPath(), byPathFromBinToExe.Trim('\\')) + }; startInfo.EnvironmentVariables["DOTNET_ROOT"] = dotnetPath; // required // ... @@ -58,9 +60,10 @@ public static Process StartProcess(string byPathFromBinToExe) /// The new Process public static Process StartProcess(ProcessStartInfo info) { - Process process = new Process(); - - process.StartInfo = info ?? throw new ArgumentException(nameof(info) + " must not be null."); + Process process = new Process + { + StartInfo = info ?? throw new ArgumentException(nameof(info) + " must not be null.") + }; process.Start(); Thread.Sleep(500); diff --git a/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/Buttons.cs b/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/Buttons.cs index 42326d151ac..ec1c52c2f21 100644 --- a/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/Buttons.cs +++ b/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/Buttons.cs @@ -20,38 +20,44 @@ private void Test1_Load(object sender, EventArgs e) RadioButton r; for (int i = 0; i < styles.Length; i++) { - r = new RadioButton(); - r.Location = new System.Drawing.Point(20, 20 + 60 * i); - r.AutoSize = false; - r.Size = new System.Drawing.Size(100, 20); - r.FlatStyle = styles[i]; - r.Text = styles[i].ToString(); - r.Checked = true; + r = new RadioButton + { + Location = new System.Drawing.Point(20, 20 + 60 * i), + AutoSize = false, + Size = new System.Drawing.Size(100, 20), + FlatStyle = styles[i], + Text = styles[i].ToString(), + Checked = true + }; Controls.Add(r); } CheckBox c; for (int i = 0; i < styles.Length; i++) { - c = new CheckBox(); - c.Location = new System.Drawing.Point(120, 20 + 60 * i); - c.AutoSize = false; - c.Size = new System.Drawing.Size(100, 20); - c.FlatStyle = styles[i]; - c.Text = styles[i].ToString(); - c.Checked = true; + c = new CheckBox + { + Location = new System.Drawing.Point(120, 20 + 60 * i), + AutoSize = false, + Size = new System.Drawing.Size(100, 20), + FlatStyle = styles[i], + Text = styles[i].ToString(), + Checked = true + }; Controls.Add(c); } Button b; for (int i = 0; i < styles.Length; i++) { - b = new Button(); - b.Location = new System.Drawing.Point(220, 20 + 60 * i); - b.AutoSize = false; - b.Size = new System.Drawing.Size(100, 20); - b.FlatStyle = styles[i]; - b.Text = styles[i].ToString(); + b = new Button + { + Location = new System.Drawing.Point(220, 20 + 60 * i), + AutoSize = false, + Size = new System.Drawing.Size(100, 20), + FlatStyle = styles[i], + Text = styles[i].ToString() + }; Controls.Add(b); } } diff --git a/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/ListViewTest.cs b/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/ListViewTest.cs index d0eeb6a7639..00ebdafc639 100644 --- a/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/ListViewTest.cs +++ b/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/ListViewTest.cs @@ -23,28 +23,32 @@ public ListViewTest() private void CreateMyListView() { // Create a new ListView control. - ListView listView1 = new ListView(); - listView1.Bounds = new Rectangle(new Point(10, 10), new Size(300, 200)); + ListView listView1 = new ListView + { + Bounds = new Rectangle(new Point(10, 10), new Size(300, 200)), - // Set the view to show details. - listView1.View = View.Details; - // Allow the user to edit item text. - listView1.LabelEdit = true; - // Allow the user to rearrange columns. - listView1.AllowColumnReorder = true; - // Display check boxes. - listView1.CheckBoxes = true; - // Select the item and subitems when selection is made. - listView1.FullRowSelect = true; - // Display grid lines. - listView1.GridLines = true; - // Sort the items in the list in ascending order. - listView1.Sorting = SortOrder.Ascending; + // Set the view to show details. + View = View.Details, + // Allow the user to edit item text. + LabelEdit = true, + // Allow the user to rearrange columns. + AllowColumnReorder = true, + // Display check boxes. + CheckBoxes = true, + // Select the item and subitems when selection is made. + FullRowSelect = true, + // Display grid lines. + GridLines = true, + // Sort the items in the list in ascending order. + Sorting = SortOrder.Ascending + }; // Create three items and three sets of subitems for each item. - ListViewItem item1 = new ListViewItem("item1", 0); - // Place a check mark next to the item. - item1.Checked = true; + ListViewItem item1 = new ListViewItem("item1", 0) + { + // Place a check mark next to the item. + Checked = true + }; item1.SubItems.Add("1"); item1.SubItems.Add("2"); item1.SubItems.Add("3"); @@ -52,9 +56,11 @@ private void CreateMyListView() item2.SubItems.Add("4"); item2.SubItems.Add("5"); item2.SubItems.Add("6"); - ListViewItem item3 = new ListViewItem("item3", 0); - // Place a check mark next to the item. - item3.Checked = true; + ListViewItem item3 = new ListViewItem("item3", 0) + { + // Place a check mark next to the item. + Checked = true + }; item3.SubItems.Add("7"); item3.SubItems.Add("8"); item3.SubItems.Add("9"); @@ -83,9 +89,11 @@ private void CreateMyListView() listView1.LargeImageList = imageListLarge; listView1.SmallImageList = imageListSmall; - ListViewGroup listViewGroup1 = new ListViewGroup("ListViewGroup", HorizontalAlignment.Left); - listViewGroup1.Header = "ListViewGroup"; - listViewGroup1.Name = "listViewGroup1"; + ListViewGroup listViewGroup1 = new ListViewGroup("ListViewGroup", HorizontalAlignment.Left) + { + Header = "ListViewGroup", + Name = "listViewGroup1" + }; listView1.Groups.AddRange(new ListViewGroup[] { listViewGroup1 }); diff --git a/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/MDIParent.cs b/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/MDIParent.cs index 7231c862d31..e42a2cbd8bb 100644 --- a/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/MDIParent.cs +++ b/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/MDIParent.cs @@ -21,8 +21,10 @@ public MDIParent() private void toolStripMenuItem1_Click(object sender, EventArgs e) { - Form form = new Form(); - form.MdiParent = this; + Form form = new Form + { + MdiParent = this + }; form.DpiChangedAfterParent += Form_DpiChangedAfterParent; } @@ -33,9 +35,11 @@ private void Form_DpiChangedAfterParent(object sender, EventArgs e) private void newChildToolStripMenuItem_Click(object sender, EventArgs e) { - Form child = new MdiChild(); - child.MdiParent = this; - child.WindowState = FormWindowState.Maximized; + Form child = new MdiChild + { + MdiParent = this, + WindowState = FormWindowState.Maximized + }; child.Show(); } } diff --git a/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/DataGridViewCellAccessibleObjectTests.cs b/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/DataGridViewCellAccessibleObjectTests.cs index a57668adb37..c271cb5ddd9 100644 --- a/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/DataGridViewCellAccessibleObjectTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/DataGridViewCellAccessibleObjectTests.cs @@ -15,11 +15,12 @@ public class DataGridViewCellsAccessibleObjectTests [InlineData(RightToLeft.Yes)] public void DataGridViewCellsAccessibleObject_Ctor_Default(RightToLeft rightToLeft) { - DataGridView dataGridView = new DataGridView(); - - dataGridView.RightToLeft = rightToLeft; - dataGridView.ColumnCount = 4; - dataGridView.Width = 85; + DataGridView dataGridView = new DataGridView + { + RightToLeft = rightToLeft, + ColumnCount = 4, + Width = 85 + }; dataGridView.Columns[0].Width = 40; dataGridView.Columns[1].Width = 40; diff --git a/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/DataGridViewRowsAccessibleObjectTests.cs b/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/DataGridViewRowsAccessibleObjectTests.cs index c4c9cc75730..7b9ac2ea67c 100644 --- a/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/DataGridViewRowsAccessibleObjectTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/AccessibleObjects/DataGridViewRowsAccessibleObjectTests.cs @@ -11,10 +11,11 @@ public class DataGridViewRowsAccessibleObjectTests [Fact] public void DataGridViewRowsAccessibleObject_Ctor_Default() { - DataGridView dataGridView = new DataGridView(); - - dataGridView.RowCount = 5; - dataGridView.Height = 87; + DataGridView dataGridView = new DataGridView + { + RowCount = 5, + Height = 87 + }; dataGridView.Rows[0].Height = 20; dataGridView.Rows[1].Height = 20; diff --git a/src/System.Windows.Forms/tests/UnitTests/ButtonTests.cs b/src/System.Windows.Forms/tests/UnitTests/ButtonTests.cs index 14d41aed61d..db510e6b0f3 100644 --- a/src/System.Windows.Forms/tests/UnitTests/ButtonTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/ButtonTests.cs @@ -30,9 +30,10 @@ public void Button_Constructor() [MemberData(nameof(AutoSizeModeGetSetData))] public void Button_AutoSizeModeGetSet(AutoSizeMode expected) { - var button = new Button(); - - button.AutoSizeMode = expected; + var button = new Button + { + AutoSizeMode = expected + }; Assert.Equal(expected, button.AutoSizeMode); } @@ -106,9 +107,10 @@ public void Button_GetPreferredSizeCore(Button button, Size proposed, Size expec [MemberData(nameof(DialogResultGetSetData))] public void Button_DialogResultGetSet(DialogResult expected) { - var button = new Button(); - - button.DialogResult = expected; + var button = new Button + { + DialogResult = expected + }; Assert.Equal(expected, button.DialogResult); } @@ -162,8 +164,10 @@ public void Button_PerformClick() [Fact] public void Button_ToStringTest() { - var button = new Button(); - button.Text = "Hello World!"; + var button = new Button + { + Text = "Hello World!" + }; var expected = "System.Windows.Forms.Button, Text: " + button.Text; var actual = button.ToString(); @@ -177,41 +181,49 @@ private static TheoryData GetPreferredSizeCoreTestData() var data = new TheoryData(); // first code path is FlatStyle != FlatStyle.System, AutoSizeMode = GrowAndShrink - var b1 = new Button(); - b1.FlatStyle = FlatStyle.Flat; - b1.AutoSizeMode = AutoSizeMode.GrowAndShrink; + var b1 = new Button + { + FlatStyle = FlatStyle.Flat, + AutoSizeMode = AutoSizeMode.GrowAndShrink + }; var proposed1 = new Size(5, 5); var expected1 = new Size(8, 8); data.Add(b1, proposed1, expected1); // second code path is FlatStyle != FlatStyle.System, AutoSizeMode != GrowAndShrink - var b2 = new Button(); - b2.FlatStyle = FlatStyle.Flat; - b2.AutoSizeMode = AutoSizeMode.GrowOnly; + var b2 = new Button + { + FlatStyle = FlatStyle.Flat, + AutoSizeMode = AutoSizeMode.GrowOnly + }; var proposed2 = new Size(5, 5); var expected2 = new Size(75, 23); data.Add(b2, proposed2, expected2); // third code path is FlatStyle == FlatStyle.System, button systemSize.Width is invalid // and AutoSizeMode = GrowAndShrink - var b3 = new Button(); - // text and font need to be set since the code measures the size of the text - b3.Text = "Hello World!"; - b3.Font = new Drawing.Font(Drawing.FontFamily.GenericMonospace, 1.5f); - b3.FlatStyle = FlatStyle.System; - b3.AutoSizeMode = AutoSizeMode.GrowAndShrink; + var b3 = new Button + { + // text and font need to be set since the code measures the size of the text + Text = "Hello World!", + Font = new Drawing.Font(Drawing.FontFamily.GenericMonospace, 1.5f), + FlatStyle = FlatStyle.System, + AutoSizeMode = AutoSizeMode.GrowAndShrink + }; var proposed3 = new Size(100, 200); var expected3 = new Size(28, 12); data.Add(b3, proposed3, expected3); // fourth code path is FlatStyle == FlatStyle.System, button systemSize.Width is valid // and AutoSizeMode != GrowAndShrink - var b4 = new Button(); - // text and font need to be set since the code measures the size of the text - b4.Text = "Hello World!"; - b4.Font = new Drawing.Font(Drawing.FontFamily.GenericMonospace, 1.5f); - b4.FlatStyle = FlatStyle.System; - b4.AutoSizeMode = AutoSizeMode.GrowOnly; + var b4 = new Button + { + // text and font need to be set since the code measures the size of the text + Text = "Hello World!", + Font = new Drawing.Font(Drawing.FontFamily.GenericMonospace, 1.5f), + FlatStyle = FlatStyle.System, + AutoSizeMode = AutoSizeMode.GrowOnly + }; var proposed4 = new Size(100, 200); // call getPreferredSizeCore once so the systemSize gets set b4.GetPreferredSizeCore(proposed4); diff --git a/src/System.Windows.Forms/tests/UnitTests/CheckBoxTests.cs b/src/System.Windows.Forms/tests/UnitTests/CheckBoxTests.cs index e4bc011b459..cd2da51704a 100644 --- a/src/System.Windows.Forms/tests/UnitTests/CheckBoxTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/CheckBoxTests.cs @@ -32,9 +32,10 @@ public void CheckBox_Constructor() [MemberData(nameof(AppearanceGetSetData))] public void CheckBox_AutoSizeModeGetSet(Appearance expected) { - var box = new CheckBox(); - - box.Appearance = expected; + var box = new CheckBox + { + Appearance = expected + }; Assert.Equal(expected, box.Appearance); } @@ -65,9 +66,10 @@ public void CheckBox_AppearanceGetSetInvalid(Appearance expected) [MemberData(nameof(AutoCheckData))] public void CheckBox_AutoCheck(bool expected) { - var box = new CheckBox(); - - box.AutoCheck = expected; + var box = new CheckBox + { + AutoCheck = expected + }; Assert.Equal(expected, box.AutoCheck); } @@ -82,10 +84,11 @@ public void CheckBox_AutoCheck(bool expected) [MemberData(nameof(ContentAlignmentGetSetData))] public void CheckBox_ContentAlignmentGetSet(ContentAlignment expected) { - var box = new CheckBox(); - - box.CheckAlign = expected; - box.TextAlign = expected; + var box = new CheckBox + { + CheckAlign = expected, + TextAlign = expected + }; Assert.Equal(expected, box.CheckAlign); Assert.Equal(expected, box.TextAlign); @@ -112,9 +115,10 @@ public void CheckBox_ContentAlignmentGetSetInvalid(ContentAlignment expected) [InlineData(false, CheckState.Unchecked)] public void CheckBox_CheckedGetSet(bool sent, CheckState expected) { - var box = new CheckBox(); - - box.Checked = sent; + var box = new CheckBox + { + Checked = sent + }; Assert.Equal(expected, box.CheckState); } @@ -129,9 +133,10 @@ public void CheckBox_CheckedGetSet(bool sent, CheckState expected) [MemberData(nameof(CheckStateGetSetData))] public void CheckBox_CheckStateGetSet(CheckState expected) { - var box = new CheckBox(); - - box.CheckState = expected; + var box = new CheckBox + { + CheckState = expected + }; Assert.Equal(expected, box.CheckState); } @@ -162,9 +167,10 @@ public void CheckBox_CheckStateGetSetInvalid(CheckState expected) [MemberData(nameof(ThreeStateData))] public void CheckBox_ThreeState(bool expected) { - var box = new CheckBox(); - - box.ThreeState = expected; + var box = new CheckBox + { + ThreeState = expected + }; Assert.Equal(expected, box.ThreeState); } diff --git a/src/System.Windows.Forms/tests/UnitTests/CheckedListBoxTests.cs b/src/System.Windows.Forms/tests/UnitTests/CheckedListBoxTests.cs index 00e7845f294..acb9cd61488 100644 --- a/src/System.Windows.Forms/tests/UnitTests/CheckedListBoxTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/CheckedListBoxTests.cs @@ -28,9 +28,10 @@ public void CheckedListBox_Constructor() [MemberData(nameof(CheckOnClickData))] public void CheckedListBox_CheckOnClick(bool expected) { - var box = new CheckedListBox(); - - box.CheckOnClick = expected; + var box = new CheckedListBox + { + CheckOnClick = expected + }; Assert.Equal(expected, box.CheckOnClick); } @@ -65,9 +66,10 @@ public void CheckedListBox_CheckedItemCollectionNotNull() [MemberData(nameof(DisplayMemberData))] public void CheckedListBox_DisplayMember(string expected) { - var box = new CheckedListBox(); - - box.DisplayMember = expected; + var box = new CheckedListBox + { + DisplayMember = expected + }; Assert.Equal(expected, box.DisplayMember); } @@ -87,9 +89,10 @@ public void CheckedListBox_DrawModeReturnsNormalOnly() [InlineData(SelectionMode.One)] public void CheckedListBox_SelectionModeGetSet(SelectionMode expected) { - var box = new CheckedListBox(); - - box.SelectionMode = expected; + var box = new CheckedListBox + { + SelectionMode = expected + }; Assert.Equal(expected, box.SelectionMode); } @@ -130,9 +133,10 @@ public void CheckedListBox_CheckStateGetSetInvalid(SelectionMode expected) [MemberData(nameof(ThreeDCheckBoxesData))] public void CheckedListBox_ThreeDCheckBoxes(bool expected) { - var box = new CheckedListBox(); - - box.ThreeDCheckBoxes = expected; + var box = new CheckedListBox + { + ThreeDCheckBoxes = expected + }; Assert.Equal(expected, box.ThreeDCheckBoxes); } @@ -147,9 +151,10 @@ public void CheckedListBox_ThreeDCheckBoxes(bool expected) [MemberData(nameof(ValueMemberData))] public void CheckedListBox_ValueMember(string expected) { - var box = new CheckedListBox(); - - box.ValueMember = expected; + var box = new CheckedListBox + { + ValueMember = expected + }; Assert.Equal(expected, box.ValueMember); } diff --git a/src/System.Windows.Forms/tests/UnitTests/DomainUpDownTests.cs b/src/System.Windows.Forms/tests/UnitTests/DomainUpDownTests.cs index 7843df71b5b..31ff133a67f 100644 --- a/src/System.Windows.Forms/tests/UnitTests/DomainUpDownTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/DomainUpDownTests.cs @@ -110,8 +110,10 @@ public void DomainUpDown_DownButton(int index, int newIndex) private DomainUpDown GetNewDomainUpDown(bool sorted = false) { - var domainUpDown = new DomainUpDown(); - domainUpDown.Sorted = sorted; + var domainUpDown = new DomainUpDown + { + Sorted = sorted + }; DomainUpDown.DomainUpDownItemCollection items = domainUpDown.Items; Assert.NotNull(items); items.Add("foo1"); diff --git a/src/System.Windows.Forms/tests/UnitTests/MenuItemTests.cs b/src/System.Windows.Forms/tests/UnitTests/MenuItemTests.cs index f116ffbf804..a324e8ece5c 100644 --- a/src/System.Windows.Forms/tests/UnitTests/MenuItemTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/MenuItemTests.cs @@ -794,8 +794,10 @@ public void MenuItem_Text_Disposed_ThrowsObjectDisposedException() [Fact] public void MenuItem_Visible_Set_GetReturnsExpected() { - var menuItem = new MenuItem(); - menuItem.Visible = false; + var menuItem = new MenuItem + { + Visible = false + }; Assert.False(menuItem.Visible); menuItem.Visible = true; diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingContextTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingContextTests.cs index 35b8ddf6367..3539cd4b08f 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingContextTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BindingContextTests.cs @@ -585,8 +585,10 @@ public void BindingContext_Item_GetIListWithDataMemberReturningIList_AddsToColle { var context = new BindingContext(); var list = new List { 1, 2, 3 }; - var dataSource = new IListDataSource(); - dataSource.Property = list; + var dataSource = new IListDataSource + { + Property = list + }; CurrencyManager manager = Assert.IsAssignableFrom(context[dataSource, "Property"]); Assert.Same(list, manager.List); @@ -602,8 +604,10 @@ public void BindingContext_Item_GetIListWithDataMemberReturningNonIList_AddsToCo { var context = new BindingContext(); var list = new List { 1, 2, 3 }; - var dataSource = new ObjectDataSource(); - dataSource.Property = list; + var dataSource = new ObjectDataSource + { + Property = list + }; PropertyManager manager = Assert.IsAssignableFrom(context[dataSource, "Property"]); Assert.Same(list, manager.Current); @@ -618,8 +622,10 @@ public void BindingContext_Item_GetArrayWithDataMember_AddsToCollection() { var context = new BindingContext(); var list = new int[] { 1, 2, 3 }; - var dataSource = new IListDataSource(); - dataSource.Property = list; + var dataSource = new IListDataSource + { + Property = list + }; CurrencyManager manager = Assert.IsAssignableFrom(context[dataSource, "Property"]); Assert.Same(list, manager.List); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ColumnHeaderCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ColumnHeaderCollectionTests.cs index ae0c8a28d90..1ee2472ed02 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ColumnHeaderCollectionTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ColumnHeaderCollectionTests.cs @@ -108,8 +108,10 @@ public void ColumnHeaderCollection_Item_GetString_ReturnsExpected(string key, in var listView = new ListView(); var collection = new ListView.ColumnHeaderCollection(listView); var header1 = new ColumnHeader(); - var header2 = new ColumnHeader(); - header2.Name = "text"; + var header2 = new ColumnHeader + { + Name = "text" + }; collection.Add(header1); collection.Add(header2); @@ -549,8 +551,10 @@ public void ColumnHeaderCollection_ContainsKey_Invoke_ReturnsExpected(string key var listView = new ListView(); var collection = new ListView.ColumnHeaderCollection(listView); var header1 = new ColumnHeader(); - var header2 = new ColumnHeader(); - header2.Name = "text"; + var header2 = new ColumnHeader + { + Name = "text" + }; collection.Add(header1); collection.Add(header2); @@ -628,8 +632,10 @@ public void ColumnHeaderCollection_IndexOfKey_Invoke_ReturnsExpected(string key, var listView = new ListView(); var collection = new ListView.ColumnHeaderCollection(listView); var header1 = new ColumnHeader(); - var header2 = new ColumnHeader(); - header2.Name = "text"; + var header2 = new ColumnHeader + { + Name = "text" + }; collection.Add(header1); collection.Add(header2); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ComboBoxTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ComboBoxTests.cs index 8001f79bfff..74cea883371 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ComboBoxTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ComboBoxTests.cs @@ -846,8 +846,10 @@ public void FindStringExact_InvalidStartIndex_ThrowsArgumentOutOfRangeException( private SubComboBox CreateControlForCtrlBackspace(string text = "", int cursorRelativeToEnd = 0) { - var tb = new SubComboBox(); - tb.Text = text; + var tb = new SubComboBox + { + Text = text + }; tb.Focus(); tb.SelectionStart = tb.Text.Length + cursorRelativeToEnd; tb.SelectionLength = 0; diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlTests.cs index 5e5ac3f297b..55ea39f096d 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlTests.cs @@ -214,9 +214,10 @@ public void Control_CreateControlInternal(bool fIgnoreVisible) [MemberData(nameof(TabIndexGetSetData))] public void Control_TabIndexGetSet(uint expected) { - var cont = new Control(); - - cont.TabIndex = (int)expected; + var cont = new Control + { + TabIndex = (int)expected + }; Assert.Equal(expected, (uint)cont.TabIndex); } @@ -231,9 +232,10 @@ public void Control_TabIndexGetSet(uint expected) [MemberData(nameof(TabStopGetSetData))] public void Control_TabStopGetSet(bool expected) { - var cont = new Control(); - - cont.TabStop = expected; + var cont = new Control + { + TabStop = expected + }; Assert.Equal(expected, cont.TabStop); } @@ -248,9 +250,10 @@ public void Control_TabStopGetSet(bool expected) [MemberData(nameof(TabStopInternalGetSetData))] public void Control_TabStopInternalGetSet(bool expected) { - var cont = new Control(); - - cont.TabStopInternal = expected; + var cont = new Control + { + TabStopInternal = expected + }; Assert.Equal(expected, cont.TabStopInternal); } @@ -259,12 +262,18 @@ public void Control_TabStopInternalGetSet(bool expected) public void Control_GetChildControlsInTabOrder() { var cont = new Control(); - var first = new Control(); - first.TabIndex = 0; - var second = new Control(); - second.TabIndex = 1; - var third = new Control(); - third.TabIndex = 2; + var first = new Control + { + TabIndex = 0 + }; + var second = new Control + { + TabIndex = 1 + }; + var third = new Control + { + TabIndex = 2 + }; var ordered = new Control[] { first, @@ -288,12 +297,18 @@ public void Control_GetChildControlsInTabOrder() public void Control_GetChildControlsInTabOrderHandlesOnly() { var cont = new Control(); - var first = new Control(); - first.TabIndex = 0; - var second = new Control(); - second.TabIndex = 1; - var third = new Control(); - third.TabIndex = 2; + var first = new Control + { + TabIndex = 0 + }; + var second = new Control + { + TabIndex = 1 + }; + var third = new Control + { + TabIndex = 2 + }; var unordered = new Control[] { second, @@ -311,12 +326,18 @@ public void Control_GetChildControlsInTabOrderHandlesOnly() public void Control_GetFirstChildControlInTabOrder() { var cont = new Control(); - var first = new Control(); - first.TabIndex = 0; - var second = new Control(); - second.TabIndex = 1; - var third = new Control(); - third.TabIndex = 2; + var first = new Control + { + TabIndex = 0 + }; + var second = new Control + { + TabIndex = 1 + }; + var third = new Control + { + TabIndex = 2 + }; var tabOrder = new Control[] { second, @@ -333,12 +354,18 @@ public void Control_GetFirstChildControlInTabOrder() public void Control_GetFirstChildControlInTabOrderReverse() { var cont = new Control(); - var first = new Control(); - first.TabIndex = 0; - var second = new Control(); - second.TabIndex = 1; - var third = new Control(); - third.TabIndex = 2; + var first = new Control + { + TabIndex = 0 + }; + var second = new Control + { + TabIndex = 1 + }; + var third = new Control + { + TabIndex = 2 + }; var tabOrder = new Control[] { second, @@ -355,12 +382,18 @@ public void Control_GetFirstChildControlInTabOrderReverse() public void Control_GetNextControl() { var cont = new Control(); - var first = new Control(); - first.TabIndex = 0; - var second = new Control(); - second.TabIndex = 1; - var third = new Control(); - third.TabIndex = 2; + var first = new Control + { + TabIndex = 0 + }; + var second = new Control + { + TabIndex = 1 + }; + var third = new Control + { + TabIndex = 2 + }; var tabOrder = new Control[] { second, @@ -377,12 +410,18 @@ public void Control_GetNextControl() public void Control_GetNextControlReverse() { var cont = new Control(); - var first = new Control(); - first.TabIndex = 0; - var second = new Control(); - second.TabIndex = 1; - var third = new Control(); - third.TabIndex = 2; + var first = new Control + { + TabIndex = 0 + }; + var second = new Control + { + TabIndex = 1 + }; + var third = new Control + { + TabIndex = 2 + }; var tabOrder = new Control[] { second, @@ -399,12 +438,18 @@ public void Control_GetNextControlReverse() public void Control_GetNextControlNoNext() { var cont = new Control(); - var first = new Control(); - first.TabIndex = 0; - var second = new Control(); - second.TabIndex = 1; - var third = new Control(); - third.TabIndex = 2; + var first = new Control + { + TabIndex = 0 + }; + var second = new Control + { + TabIndex = 1 + }; + var third = new Control + { + TabIndex = 2 + }; var tabOrder = new Control[] { second, @@ -421,12 +466,18 @@ public void Control_GetNextControlNoNext() public void Control_GetNextControlNoNextReverse() { var cont = new Control(); - var first = new Control(); - first.TabIndex = 0; - var second = new Control(); - second.TabIndex = 1; - var third = new Control(); - third.TabIndex = 2; + var first = new Control + { + TabIndex = 0 + }; + var second = new Control + { + TabIndex = 1 + }; + var third = new Control + { + TabIndex = 2 + }; var tabOrder = new Control[] { second, @@ -482,9 +533,10 @@ public void Control_ParentChangedFromSet() public void Control_ParentGetSet() { var parent = new Control(); - var cont = new Control(); - - cont.Parent = parent; + var cont = new Control + { + Parent = parent + }; Assert.NotNull(cont.Parent); Assert.Equal(parent, cont.Parent); @@ -494,9 +546,10 @@ public void Control_ParentGetSet() public void Control_ParentInternalGetSet() { var parent = new Control(); - var cont = new Control(); - - cont.ParentInternal = parent; + var cont = new Control + { + ParentInternal = parent + }; Assert.NotNull(cont.Parent); Assert.Equal(parent, cont.ParentInternal); @@ -580,9 +633,10 @@ public void Control_ChildingExcpetion() [Fact] public void Control_AccessibleNameGetSet() { - var cont = new Control(); - - cont.AccessibleName = "Foo"; + var cont = new Control + { + AccessibleName = "Foo" + }; Assert.Equal("Foo", cont.AccessibleName); } @@ -597,9 +651,10 @@ public void Control_AccessibleNameGetSet() [MemberData(nameof(AccessibleRoleData))] public void Control_SetItemCheckState(AccessibleRole expected) { - var cont = new Control(); - - cont.AccessibleRole = expected; + var cont = new Control + { + AccessibleRole = expected + }; Assert.Equal(expected, cont.AccessibleRole); } @@ -630,9 +685,10 @@ public void Control_AccessibleRoleInvalid(AccessibleRole expected) [MemberData(nameof(IsAccessibleGetSetData))] public void Control_IsAccessibleGetSet(bool expected) { - var cont = new Control(); - - cont.IsAccessible = expected; + var cont = new Control + { + IsAccessible = expected + }; Assert.Equal(expected, cont.IsAccessible); } @@ -645,9 +701,10 @@ public void Control_IsAccessibleGetSet(bool expected) [CommonMemberData(nameof(CommonTestHelper.GetColorTheoryData))] public void Control_BackColorGetSet(Color expected) { - var cont = new Control(); - - cont.BackColor = expected; + var cont = new Control + { + BackColor = expected + }; Assert.Equal(expected, cont.BackColor); } @@ -669,9 +726,10 @@ public void Control_BackColorChanged() [CommonMemberData(nameof(CommonTestHelper.GetColorTheoryData))] public void Control_ForeColorGetSet(Color expected) { - var cont = new Control(); - - cont.ForeColor = expected; + var cont = new Control + { + ForeColor = expected + }; Assert.Equal(expected, cont.ForeColor); } @@ -702,9 +760,10 @@ public void Control_ForeColorChanged() [MemberData(nameof(BackgroundImageLayoutData))] public void Control_BackgroundImageLayoutGetSet(ImageLayout expected) { - var cont = new Control(); - - cont.BackgroundImageLayout = expected; + var cont = new Control + { + BackgroundImageLayout = expected + }; Assert.Equal(expected, cont.BackgroundImageLayout); } @@ -846,9 +905,10 @@ public void Control_Padding_Set_GetReturnsExpected(Padding value, Padding expect [MemberData(nameof(AnchorData))] public void Control_AnchorGetSet(AnchorStyles expected) { - var cont = new Control(); - - cont.Anchor = expected; + var cont = new Control + { + Anchor = expected + }; Assert.Equal(expected, cont.Anchor); } @@ -874,9 +934,10 @@ public void Control_BoundsGetSet() [MemberData(nameof(HeightGetSetData))] public void Control_HeightGetSet(int expected) { - var cont = new Control(); - - cont.Height = expected; + var cont = new Control + { + Height = expected + }; Assert.Equal(expected, cont.Height); } @@ -891,9 +952,10 @@ public void Control_HeightGetSet(int expected) [MemberData(nameof(LeftGetSetData))] public void Control_LeftGetSet(int expected) { - var cont = new Control(); - - cont.Left = expected; + var cont = new Control + { + Left = expected + }; Assert.Equal(expected, cont.Left); } @@ -908,9 +970,10 @@ public void Control_LeftGetSet(int expected) [MemberData(nameof(TopGetSetData))] public void Control_TopGetSet(int expected) { - var cont = new Control(); - - cont.Top = expected; + var cont = new Control + { + Top = expected + }; Assert.Equal(expected, cont.Top); } @@ -1014,9 +1077,10 @@ public void Control_RequiredScalingEnabled_Get_ReturnsExpected(bool value) [InlineData(RightToLeft.No)] public void Control_RightToLeftTest(RightToLeft expected) { - var cont = new Control(); - - cont.RightToLeft = expected; + var cont = new Control + { + RightToLeft = expected + }; Assert.Equal(expected, cont.RightToLeft); } @@ -1025,8 +1089,10 @@ public void Control_RightToLeftTest(RightToLeft expected) public void Control_RightToLeftInherit() { var parent = new Control(); - var cont = new Control(); - cont.Parent = parent; + var cont = new Control + { + Parent = parent + }; parent.RightToLeft = RightToLeft.Yes; cont.RightToLeft = RightToLeft.Inherit; @@ -1067,9 +1133,10 @@ public void Control_SizeGetSet(Size value) [MemberData(nameof(WidthGetSetData))] public void Control_WidthGetSet(int expected) { - var cont = new Control(); - - cont.Width = expected; + var cont = new Control + { + Width = expected + }; Assert.Equal(expected, cont.Width); } @@ -1279,9 +1346,10 @@ public void Control_TabStopChanged() [MemberData(nameof(EnabledGetSetData))] public void Control_EnabledGetSet(bool expected) { - var cont = new Control(); - - cont.Enabled = expected; + var cont = new Control + { + Enabled = expected + }; Assert.Equal(expected, cont.Enabled); } @@ -1296,9 +1364,10 @@ public void Control_EnabledGetSet(bool expected) [MemberData(nameof(VisibleGetSetData))] public void Control_VisibleGetSet(bool expected) { - var cont = new Control(); - - cont.Visible = expected; + var cont = new Control + { + Visible = expected + }; Assert.Equal(expected, cont.Visible); } @@ -1327,8 +1396,10 @@ public void Control_GetVisibleCoreVisibleParent() [Fact] public void Control_Hide() { - var cont = new Control(); - cont.Visible = true; + var cont = new Control + { + Visible = true + }; cont.Hide(); @@ -1360,8 +1431,10 @@ public void Control_FontGetSet(Font value) [InlineData(float.Epsilon)] public void Control_ScaleFont(float expected) { - var cont = new Control(); - cont.Font = new Font(new FontFamily(Drawing.Text.GenericFontFamilies.Serif), 1.0f); + var cont = new Control + { + Font = new Font(new FontFamily(Drawing.Text.GenericFontFamilies.Serif), 1.0f) + }; cont.ScaleFont(expected); @@ -1461,9 +1534,10 @@ public void Control_Text_SetWithHandle_GetReturnsExpected(string value) [MemberData(nameof(CaptureGetSetData))] public void Control_CaptureGetSet(bool expected) { - var cont = new Control(); - - cont.Capture = expected; + var cont = new Control + { + Capture = expected + }; Assert.Equal(expected, cont.Capture); } @@ -1478,9 +1552,10 @@ public void Control_CaptureGetSet(bool expected) [MemberData(nameof(CaptureInternalGetSetData))] public void Control_CaptureInternalGetSet(bool expected) { - var cont = new Control(); - - cont.CaptureInternal = expected; + var cont = new Control + { + CaptureInternal = expected + }; Assert.Equal(expected, cont.CaptureInternal); } @@ -1501,8 +1576,10 @@ public void Control_CanProcessMnemonic() [Fact] public void Control_CanProcessMnemonicNotEnabled() { - var cont = new Control(); - cont.Enabled = false; + var cont = new Control + { + Enabled = false + }; // act and assert Assert.False(cont.CanProcessMnemonic()); @@ -1511,8 +1588,10 @@ public void Control_CanProcessMnemonicNotEnabled() [Fact] public void Control_CanProcessMnemonicNotVisible() { - var cont = new Control(); - cont.Visible = false; + var cont = new Control + { + Visible = false + }; // act and assert Assert.False(cont.CanProcessMnemonic()); @@ -1545,8 +1624,10 @@ public void Control_CanSelectCore() [Fact] public void Control_CanSelectCoreNotEnabled() { - var cont = new Control(); - cont.Enabled = false; + var cont = new Control + { + Enabled = false + }; // act and assert Assert.False(cont.CanSelectCore()); @@ -1555,10 +1636,14 @@ public void Control_CanSelectCoreNotEnabled() [Fact] public void Control_CanSelectCoreParentNotEnabled() { - var cont = new Control(); - cont.Enabled = true; - var parent = new Control(); - parent.Enabled = false; + var cont = new Control + { + Enabled = true + }; + var parent = new Control + { + Enabled = false + }; cont.AssignParent(parent); // act and assert @@ -1695,9 +1780,10 @@ public void Control_SiteGetSet() [MemberData(nameof(UseWaitCursorGetSetData))] public void Control_UseWaitCursorGetSet(bool expected) { - var cont = new Control(); - - cont.UseWaitCursor = expected; + var cont = new Control + { + UseWaitCursor = expected + }; Assert.Equal(expected, cont.UseWaitCursor); } @@ -1709,9 +1795,10 @@ public void Control_UseWaitCursorGetSet(bool expected) // SupportsUseCompatibleTextRendering is always false public void Control_UseCompatibleTextRenderingIntGetSet(bool given, bool expected) { - var cont = new Control(); - - cont.UseCompatibleTextRenderingInt = given; + var cont = new Control + { + UseCompatibleTextRenderingInt = given + }; Assert.Equal(expected, cont.UseCompatibleTextRenderingInt); } @@ -1737,9 +1824,10 @@ public void Control_WindowTargetGetSet() [MemberData(nameof(AllowDropData))] public void Control_AllowDropGetSet(bool expected) { - var cont = new Control(); - - cont.AllowDrop = expected; + var cont = new Control + { + AllowDrop = expected + }; Assert.Equal(expected, cont.AllowDrop); } @@ -1849,9 +1937,10 @@ public void Control_BindingContext_SetWithHandler_CallsBindingContextChanged() [MemberData(nameof(CausesValidationData))] public void Control_CausesValidationGetSet(bool expected) { - var cont = new Control(); - - cont.CausesValidation = expected; + var cont = new Control + { + CausesValidation = expected + }; Assert.Equal(expected, cont.CausesValidation); } @@ -1861,9 +1950,10 @@ public void Control_CausesValidationGetSet(bool expected) [InlineData(true, false)] // giving true cannot set to true public void Control_CacheTextInternalGetSet(bool given, bool expected) { - var cont = new Control(); - - cont.CacheTextInternal = given; + var cont = new Control + { + CacheTextInternal = given + }; Assert.Equal(expected, cont.CacheTextInternal); } @@ -1915,9 +2005,10 @@ public void Control_ContextMenuStripGetSet() [MemberData(nameof(ValidationCancelledGetSetData))] public void Control_ValidationCancelledGetSet(bool expected) { - var cont = new Control(); - - cont.ValidationCancelled = expected; + var cont = new Control + { + ValidationCancelled = expected + }; Assert.Equal(expected, cont.ValidationCancelled); } @@ -1932,9 +2023,10 @@ public void Control_ValidationCancelledGetSet(bool expected) [MemberData(nameof(IsTopMdiWindowClosingGetSetData))] public void Control_IsTopMdiWindowClosingGetSet(bool expected) { - var cont = new Control(); - - cont.IsTopMdiWindowClosing = expected; + var cont = new Control + { + IsTopMdiWindowClosing = expected + }; Assert.Equal(expected, cont.IsTopMdiWindowClosing); } @@ -1964,9 +2056,10 @@ public void Control_Cursor_Set_GetReturnsExpected(Cursor value) [MemberData(nameof(DockGetSetData))] public void Control_DockGetSet(DockStyle expected) { - var cont = new Control(); - - cont.Dock = expected; + var cont = new Control + { + Dock = expected + }; Assert.Equal(expected, cont.Dock); } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/FormTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/FormTests.cs index cce8883623e..6e3495408a3 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/FormTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/FormTests.cs @@ -86,9 +86,11 @@ public void Form_ActiveMdiChildInternalGetSet() public void Form_ActiveMdiChildGetSet() { var form = new Form(); - var child = new Form(); - child.Visible = true; - child.Enabled = true; + var child = new Form + { + Visible = true, + Enabled = true + }; form.ActiveMdiChildInternal = child; @@ -100,9 +102,11 @@ public void Form_ActiveMdiChildGetSet() public void Form_ActiveMdiChildGetSetChildNotVisible() { var form = new Form(); - var child = new Form(); - child.Visible = false; - child.Enabled = true; + var child = new Form + { + Visible = false, + Enabled = true + }; form.ActiveMdiChildInternal = child; @@ -113,9 +117,11 @@ public void Form_ActiveMdiChildGetSetChildNotVisible() public void Form_ActiveMdiChildGetSetChildNotEnabled() { var form = new Form(); - var child = new Form(); - child.Visible = true; - child.Enabled = false; + var child = new Form + { + Visible = true, + Enabled = false + }; form.ActiveMdiChildInternal = child; diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewGroupCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewGroupCollectionTests.cs index d4b8e348723..06b044f2365 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewGroupCollectionTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewGroupCollectionTests.cs @@ -270,8 +270,10 @@ public void ListViewGroupCollection_Item_GetStringExists_ReturnsExpected(string var listView = new ListView(); ListViewGroupCollection collection = listView.Groups; var group1 = new ListViewGroup(); - var group2 = new ListViewGroup(); - group2.Name = "text"; + var group2 = new ListViewGroup + { + Name = "text" + }; collection.Add(group1); collection.Add(group2); @@ -289,8 +291,10 @@ public void ListViewGroupCollection_Item_GetNoSuchString_ReturnsNull(string key) var listView = new ListView(); ListViewGroupCollection collection = listView.Groups; var group1 = new ListViewGroup(); - var group2 = new ListViewGroup(); - group2.Name = "text"; + var group2 = new ListViewGroup + { + Name = "text" + }; collection.Add(group1); collection.Add(group2); @@ -313,8 +317,10 @@ public void ListViewGroupCollection_Item_SetStringExists_GetReturnsExpected(stri var listView = new ListView(); ListViewGroupCollection collection = listView.Groups; var group1 = new ListViewGroup(); - var group2 = new ListViewGroup(); - group2.Name = "text"; + var group2 = new ListViewGroup + { + Name = "text" + }; collection.Add(group1); collection.Add(group2); @@ -334,8 +340,10 @@ public void ListViewGroupCollection_Item_SetNoSuchString_Nop(string key) var listView = new ListView(); ListViewGroupCollection collection = listView.Groups; var group1 = new ListViewGroup(); - var group2 = new ListViewGroup(); - group2.Name = "text"; + var group2 = new ListViewGroup + { + Name = "text" + }; collection.Add(group1); collection.Add(group2); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemCollectionTests.cs index 32875dcc4a6..1d323712a8d 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemCollectionTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemCollectionTests.cs @@ -161,8 +161,10 @@ public void ListViewSubItemCollection_Item_GetString_ReturnsExpected(string key, var item = new ListViewItem(); var collection = new ListViewItem.ListViewSubItemCollection(item); var subItem1 = new ListViewItem.ListViewSubItem(); - var subItem2 = new ListViewItem.ListViewSubItem(); - subItem2.Name = "text"; + var subItem2 = new ListViewItem.ListViewSubItem + { + Name = "text" + }; collection.Add(subItem1); collection.Add(subItem2); @@ -468,8 +470,10 @@ public void ListViewSubItemCollection_ContainsKey_Invoke_ReturnsExpected(string var item = new ListViewItem(); var collection = new ListViewItem.ListViewSubItemCollection(item); var subItem1 = new ListViewItem.ListViewSubItem(); - var subItem2 = new ListViewItem.ListViewSubItem(); - subItem2.Name = "text"; + var subItem2 = new ListViewItem.ListViewSubItem + { + Name = "text" + }; collection.Add(subItem1); collection.Add(subItem2); @@ -547,8 +551,10 @@ public void ListViewSubItemCollection_IndexOfKey_Invoke_ReturnsExpected(string k var item = new ListViewItem(); var collection = new ListViewItem.ListViewSubItemCollection(item); var subItem1 = new ListViewItem.ListViewSubItem(); - var subItem2 = new ListViewItem.ListViewSubItem(); - subItem2.Name = "text"; + var subItem2 = new ListViewItem.ListViewSubItem + { + Name = "text" + }; collection.Add(subItem1); collection.Add(subItem2); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/PanelTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/PanelTests.cs index 9c1b17580c9..f3326fceec1 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/PanelTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/PanelTests.cs @@ -26,8 +26,10 @@ public void Panel_Ctor_Default() [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] public void Panel_AutoSize_Set_GetReturnsExpected(bool value) { - var panel = new Panel(); - panel.AutoSize = value; + var panel = new Panel + { + AutoSize = value + }; Assert.Equal(value, panel.AutoSize); // Set with observer. @@ -121,8 +123,10 @@ public void Panel_KeyPress_AddRemove_Success() [CommonMemberData(nameof(CommonTestHelper.GetBoolTheoryData))] public void Panel_TabStop_Set_GetReturnsExpected(bool value) { - var panel = new Panel(); - panel.TabStop = value; + var panel = new Panel + { + TabStop = value + }; Assert.Equal(value, panel.TabStop); // Set with observer. @@ -150,8 +154,10 @@ public void Panel_TabStop_Set_GetReturnsExpected(bool value) [Fact] public void Panel_Text_Set_GetReturnsExpected() { - var panel = new Panel(); - panel.Text = "value1"; + var panel = new Panel + { + Text = "value1" + }; Assert.Equal("value1", panel.Text); // Set with observer. diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ScrollableControlTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ScrollableControlTests.cs index 10988121ade..b58d368261d 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ScrollableControlTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ScrollableControlTests.cs @@ -381,8 +381,10 @@ public void ScrollableControl_AdjustFormScrollbars_Invoke_Success(SubScrollableC [Fact] public void ScrollableControl_ScaleCore_InvokeWithDockPadding_Success() { - var control = new ScrollableControl(); - control.Padding = new Padding(1, 2, 3, 4); + var control = new ScrollableControl + { + Padding = new Padding(1, 2, 3, 4) + }; Assert.Equal(1, control.DockPadding.Left); Assert.Equal(2, control.DockPadding.Top); Assert.Equal(3, control.DockPadding.Right); @@ -412,8 +414,10 @@ public void ScrollableControl_ScaleCore_InvokeWithoutDockPadding_Success() [Fact] public void ScrollableControl_ScaleControl_InvokeWithDockPadding_Success() { - var control = new ScrollableControl(); - control.Padding = new Padding(1, 2, 3, 4); + var control = new ScrollableControl + { + Padding = new Padding(1, 2, 3, 4) + }; Assert.Equal(1, control.DockPadding.Left); Assert.Equal(2, control.DockPadding.Top); Assert.Equal(3, control.DockPadding.Right); 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 0b7ab816adb..593ef0997cc 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 @@ -297,10 +297,12 @@ public void ToolStripItem_Alignment_Set_GetReturnsExpected(ToolStripItemAlignmen public void ToolStripItem_Alignment_SetWithParent_GetReturnsExpected(ToolStripItemAlignment value) { var parent = new ToolStrip(); - var item = new SubToolStripItem(); - item.Parent = parent; + var item = new SubToolStripItem + { + Parent = parent, - item.Alignment = value; + Alignment = value + }; Assert.Equal(value, item.Alignment); // Set same. @@ -313,8 +315,10 @@ public void ToolStripItem_Alignment_SetWithParent_GetReturnsExpected(ToolStripIt public void ToolStripItem_Alignment_SetWithCreatedParent_GetReturnsExpected(ToolStripItemAlignment value) { var parent = new ToolStrip(); - var item = new SubToolStripItem(); - item.Parent = parent; + var item = new SubToolStripItem + { + Parent = parent + }; Assert.NotEqual(IntPtr.Zero, parent.Handle); item.Alignment = value; @@ -353,10 +357,12 @@ public void ToolStripItem_AllowDrop_Set_GetReturnsExpected(bool value) public void ToolStripItem_AllowDrop_SetWithParent_GetReturnsExpected(bool value) { var parent = new ToolStrip(); - var item = new SubToolStripItem(); - item.Parent = parent; + var item = new SubToolStripItem + { + Parent = parent, - item.AllowDrop = value; + AllowDrop = value + }; Assert.Equal(value, item.AllowDrop); // Set same. @@ -394,10 +400,12 @@ public void ToolStripItem_Anchor_Set_GetReturnsExpected(AnchorStyles value, Anch public void ToolStripItem_Anchor_SetWithParent_GetReturnsExpected(AnchorStyles value, AnchorStyles expected) { var parent = new ToolStrip(); - var item = new SubToolStripItem(); - item.Parent = parent; + var item = new SubToolStripItem + { + Parent = parent, - item.Anchor = value; + Anchor = value + }; Assert.Equal(expected, item.Anchor); // Set same. @@ -1496,12 +1504,16 @@ public static IEnumerable IsOnDropDown_TestData() toolStripDropDown.Items.Add(toolStripDropDownItem); yield return new object[] { toolStripDropDownItem, true }; - var toolStripParentItem = new SubToolStripItem(); - toolStripParentItem.Parent = toolStrip; + var toolStripParentItem = new SubToolStripItem + { + Parent = toolStrip + }; yield return new object[] { toolStripParentItem, false }; - var toolStripDropDownParentItem = new SubToolStripItem(); - toolStripDropDownParentItem.Parent = toolStripDropDown; + var toolStripDropDownParentItem = new SubToolStripItem + { + Parent = toolStripDropDown + }; yield return new object[] { toolStripDropDownParentItem, true }; } @@ -1527,8 +1539,10 @@ public static IEnumerable IsOnOverflow_TestData() var toolStripOverflow = new ToolStripOverflow(toolStripOverflowParent); yield return new object[] { toolStripOverflowParent, false }; - var overflowingToolStrip = new ToolStrip(); - overflowingToolStrip.Size = new Size(1, 2); + var overflowingToolStrip = new ToolStrip + { + Size = new Size(1, 2) + }; var overflowingToolStripItem = new SubToolStripItem(); overflowingToolStrip.Items.Add(overflowingToolStripItem); overflowingToolStrip.LayoutEngine.Layout(overflowingToolStrip, null); @@ -1673,9 +1687,10 @@ public void ToolStripItem_Owner_Set_GetReturnsExpected() { var owner = new ToolStrip(); var otherOwner = new ToolStrip(); - var item = new SubToolStripItem(); - - item.Owner = owner; + var item = new SubToolStripItem + { + Owner = owner + }; Assert.Same(owner, item.Owner); Assert.Same(item, Assert.Single(owner.Items)); @@ -1724,13 +1739,17 @@ public static IEnumerable OwnerItem_TestData() yield return new object[] { toolStripDropDownWithOwnerItemItem, toolStripDropDownWithOwnerItemOwnerItem }; var toolStripParent = new ToolStrip(); - var toolStripParentItem = new SubToolStripItem(); - toolStripParentItem.Parent = toolStripParent; + var toolStripParentItem = new SubToolStripItem + { + Parent = toolStripParent + }; yield return new object[] { toolStripParentItem, null }; var toolStripDropDownParent = new ToolStripDropDown(); - var toolStripDropDownParentItem = new SubToolStripItem(); - toolStripDropDownParentItem.Parent = toolStripDropDownParent; + var toolStripDropDownParentItem = new SubToolStripItem + { + Parent = toolStripDropDownParent + }; yield return new object[] { toolStripDropDownParentItem, null }; var toolStripDropDownWithOwnerItemParentOwnerItem = new SubToolStripItem(); @@ -1738,8 +1757,10 @@ public static IEnumerable OwnerItem_TestData() { OwnerItem = toolStripDropDownWithOwnerItemParentOwnerItem }; - var toolStripDropDownWithOwnerItemParentItem = new SubToolStripItem(); - toolStripDropDownWithOwnerItemParentItem.Parent = toolStripDropDownWithOwnerItemParent; + var toolStripDropDownWithOwnerItemParentItem = new SubToolStripItem + { + Parent = toolStripDropDownWithOwnerItemParent + }; yield return new object[] { toolStripDropDownWithOwnerItemParentItem, toolStripDropDownWithOwnerItemParentOwnerItem }; } @@ -1824,8 +1845,10 @@ public static IEnumerable RightToLeft_TestData() { RightToLeft = rightToLeft }; - var toolStripParentItem = new SubToolStripItem(); - toolStripParentItem.Parent = toolStripParent; + var toolStripParentItem = new SubToolStripItem + { + Parent = toolStripParent + }; yield return new object[] { toolStripParentItem, expected }; } @@ -2141,8 +2164,10 @@ public static IEnumerable TextDirection_Get_TestData() { TextDirection = ToolStripTextDirection.Vertical90 }; - var toolStripParentItem = new SubToolStripItem(); - toolStripParentItem.Parent = toolStripParent; + var toolStripParentItem = new SubToolStripItem + { + Parent = toolStripParent + }; yield return new object[] { toolStripParentItem, ToolStripTextDirection.Vertical90 }; var toolStripOwnerParentItem = new SubToolStripItem(); @@ -2355,10 +2380,12 @@ public void ToolStripItem_Visible_Set_GetReturnsExpected(bool available, bool va public void ToolStripItem_Visible_SetWithParent_GetReturnsExpected(bool value) { var parent = new ToolStrip(); - var item = new SubToolStripItem(); - item.Parent = parent; + var item = new SubToolStripItem + { + Parent = parent, - item.Visible = value; + Visible = value + }; Assert.Equal(value, item.Visible); // Set same. diff --git a/src/System.Windows.Forms/tests/UnitTests/TextBoxTests.cs b/src/System.Windows.Forms/tests/UnitTests/TextBoxTests.cs index 8c3984f31ba..6cae8841e8f 100644 --- a/src/System.Windows.Forms/tests/UnitTests/TextBoxTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/TextBoxTests.cs @@ -21,16 +21,20 @@ public void TextBox_Constructor() [Fact] public void TextBox_PlaceholderText() { - var tb = new TextBox(); - tb.PlaceholderText = "Enter your name"; + var tb = new TextBox + { + PlaceholderText = "Enter your name" + }; Assert.False(string.IsNullOrEmpty(tb.PlaceholderText)); } [Fact] public void TextBox_PlaceholderTextAlignments() { - var tb = new TextBox(); - tb.PlaceholderText = "Enter your name"; + var tb = new TextBox + { + PlaceholderText = "Enter your name" + }; System.Runtime.InteropServices.HandleRef refHandle = new System.Runtime.InteropServices.HandleRef(tb, tb.Handle); @@ -47,9 +51,11 @@ public void TextBox_PlaceholderTextAlignments() [Fact] public void TextBox_PlaceholderTextAlignmentsInRightToLeft() { - var tb = new TextBox(); - tb.PlaceholderText = "Enter your name"; - tb.RightToLeft = RightToLeft.Yes; + var tb = new TextBox + { + PlaceholderText = "Enter your name", + RightToLeft = RightToLeft.Yes + }; System.Runtime.InteropServices.HandleRef refHandle = new System.Runtime.InteropServices.HandleRef(tb, tb.Handle); @@ -65,8 +71,10 @@ public void TextBox_PlaceholderTextAlignmentsInRightToLeft() private SubTextBoxBase CreateTextBoxForCtrlBackspace(string text = "", int cursorRelativeToEnd = 0) { - var tb = new SubTextBoxBase(); - tb.Text = text; + var tb = new SubTextBoxBase + { + Text = text + }; tb.Focus(); tb.SelectionStart = tb.Text.Length + cursorRelativeToEnd; tb.SelectionLength = 0; diff --git a/src/System.Windows.Forms/tests/UnitTests/ThreadContextTests.cs b/src/System.Windows.Forms/tests/UnitTests/ThreadContextTests.cs index cce75a4fa46..c6e7ba23db9 100644 --- a/src/System.Windows.Forms/tests/UnitTests/ThreadContextTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/ThreadContextTests.cs @@ -39,8 +39,10 @@ public void ThreadContext_WrongProcessFiltersPassesThrough() .Returns((MessageCallback)((ref Message m) => m.Msg == filterId)); threadContext.AddMessageFilter(mockContext.Object); - NativeMethods.MSG msg = new NativeMethods.MSG(); - msg.message = TestMessageId1; + NativeMethods.MSG msg = new NativeMethods.MSG + { + message = TestMessageId1 + }; bool result = threadContext.PreTranslateMessage(ref msg); Assert.False(result); mockContext.Verify(c => c.PreFilterMessage(ref It.Ref.IsAny), Times.Exactly(1)); @@ -58,8 +60,10 @@ public void ThreadContext_CorrectProcessFiltersProcesses() .Returns((MessageCallback)((ref Message m) => m.Msg == filterId)); threadContext.AddMessageFilter(mockContext.Object); - NativeMethods.MSG msg = new NativeMethods.MSG(); - msg.message = filterId; + NativeMethods.MSG msg = new NativeMethods.MSG + { + message = filterId + }; bool result = threadContext.PreTranslateMessage(ref msg); Assert.True(result); mockContext.Verify(c => c.PreFilterMessage(ref It.Ref.IsAny), Times.Exactly(1)); @@ -84,8 +88,10 @@ public void ThreadContext_MultipleProcessFiltersProcesses() threadContext.AddMessageFilter(mockContext3.Object); - NativeMethods.MSG msg = new NativeMethods.MSG(); - msg.message = TestMessageId1; + NativeMethods.MSG msg = new NativeMethods.MSG + { + message = TestMessageId1 + }; bool result = threadContext.PreTranslateMessage(ref msg); Assert.False(result); @@ -93,16 +99,20 @@ public void ThreadContext_MultipleProcessFiltersProcesses() mockContext3.Verify(c => c.PreFilterMessage(ref It.Ref.IsAny), Times.Exactly(1)); - msg = new NativeMethods.MSG(); - msg.message = TestMessageId2; + msg = new NativeMethods.MSG + { + message = TestMessageId2 + }; result = threadContext.PreTranslateMessage(ref msg); Assert.True(result); mockContext2.Verify(c => c.PreFilterMessage(ref It.Ref.IsAny), Times.Exactly(2)); mockContext3.Verify(c => c.PreFilterMessage(ref It.Ref.IsAny), Times.Exactly(1)); - msg = new NativeMethods.MSG(); - msg.message = TestMessageId3; + msg = new NativeMethods.MSG + { + message = TestMessageId3 + }; result = threadContext.PreTranslateMessage(ref msg); Assert.True(result); From 885c53319ac34851c7649680015838a5a52c479a Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Fri, 24 May 2019 12:06:49 -0700 Subject: [PATCH 14/27] remove all instances of IDE0018 warning - Variable declaration can be inlined --- src/Common/src/DpiHelper.cs | 6 +- .../src/PlatformDetection.Windows.cs | 7 +- .../src/Misc/DpiHelper.cs | 3 +- .../Windows/Forms/Design/FolderNameEditor.cs | 3 +- .../ComponentCodeDomSerializer.cs | 3 +- .../PropertyMemberCodeDomSerializer.cs | 9 +-- .../src/Common/System/LocalAppContext.cs | 6 +- .../System/Windows/Forms/AccessibleObject.cs | 6 +- .../src/System/Windows/Forms/Application.cs | 22 +++--- .../src/System/Windows/Forms/AxHost.cs | 15 ++-- .../System/Windows/Forms/BindingNavigator.cs | 3 +- .../src/System/Windows/Forms/BindingSource.cs | 3 +- .../src/System/Windows/Forms/Button.cs | 3 +- .../src/System/Windows/Forms/ComboBox.cs | 30 +++----- .../Windows/Forms/ComponentManagerBroker.cs | 3 +- .../COM2ICategorizePropertiesHandler.cs | 3 +- .../COM2IPerPropertyBrowsingHandler.cs | 3 +- .../System/Windows/Forms/ContainerControl.cs | 3 +- .../src/System/Windows/Forms/Control.cs | 69 +++++++------------ .../Windows/Forms/DataGridViewButtonCell.cs | 19 ++--- .../System/Windows/Forms/DataGridViewCell.cs | 6 +- .../Windows/Forms/DataGridViewCellStyle.cs | 18 ++--- .../Windows/Forms/DataGridViewCheckBoxCell.cs | 21 ++---- .../Forms/DataGridViewColumnCollection.cs | 3 +- .../Forms/DataGridViewColumnHeaderCell.cs | 8 +-- .../Windows/Forms/DataGridViewComboBoxCell.cs | 37 +++------- .../Forms/DataGridViewDataConnection.cs | 8 +-- .../Windows/Forms/DataGridViewHeaderCell.cs | 3 +- .../Windows/Forms/DataGridViewImageCell.cs | 13 +--- .../Windows/Forms/DataGridViewLinkCell.cs | 22 ++---- .../Windows/Forms/DataGridViewMethods.cs | 54 ++++++--------- .../Forms/DataGridViewRowHeaderCell.cs | 10 +-- .../Windows/Forms/DataGridViewTextBoxCell.cs | 13 +--- .../Forms/DataGridViewTopLeftHeaderCell.cs | 10 +-- .../src/System/Windows/Forms/DataObject.cs | 6 +- .../System/Windows/Forms/FileDialog_Vista.cs | 6 +- .../Windows/Forms/FolderBrowserDialog.cs | 3 +- .../src/System/Windows/Forms/ImageList.cs | 9 +-- .../Forms/KeyboardToolTipStateMachine.cs | 15 ++-- .../src/System/Windows/Forms/Label.cs | 9 +-- .../Windows/Forms/Layout/CommonProperties.cs | 24 +++---- .../Forms/Layout/DockAndAnchorLayout.cs | 7 +- .../System/Windows/Forms/Layout/FlowLayout.cs | 6 +- .../Windows/Forms/Layout/TableLayout.cs | 3 +- .../src/System/Windows/Forms/MaskedTextBox.cs | 30 +++----- .../src/System/Windows/Forms/NativeWindow.cs | 25 +++---- .../System/Windows/Forms/OpenFileDialog.cs | 12 ++-- .../MergePropertyDescriptor.cs | 3 +- .../PropertyGridInternal/PropertyGridView.cs | 9 +-- .../System/Windows/Forms/PropertyManager.cs | 3 +- .../src/System/Windows/Forms/RichTextBox.cs | 6 +- .../Forms/TableLayoutSettingsTypeConverter.cs | 6 +- .../src/System/Windows/Forms/TextBoxBase.cs | 24 +++---- .../src/System/Windows/Forms/Timer.cs | 3 +- .../src/System/Windows/Forms/ToolStripItem.cs | 21 ++---- .../System/Windows/Forms/ToolStripManager.cs | 3 +- .../System/Windows/Forms/ToolStripMenuItem.cs | 6 +- .../src/System/Windows/Forms/ToolTip.cs | 9 +-- .../System/Windows/Forms/WebBrowserBase.cs | 6 +- .../Windows/Forms/WebBrowserSiteBase.cs | 3 +- .../src/System/Windows/Forms/control.ime.cs | 12 ++-- 61 files changed, 227 insertions(+), 487 deletions(-) diff --git a/src/Common/src/DpiHelper.cs b/src/Common/src/DpiHelper.cs index d0476a2d7a0..0bb70987551 100644 --- a/src/Common/src/DpiHelper.cs +++ b/src/Common/src/DpiHelper.cs @@ -70,10 +70,9 @@ internal static void InitializeDpiHelperForWinforms() { // We are on Windows 10/1603 or greater all right, but we could still be DpiUnaware or SystemAware, so let's find that out... - NativeMethods.PROCESS_DPI_AWARENESS processDpiAwareness; var currentProcessId = SafeNativeMethods.GetCurrentProcessId(); IntPtr hProcess = SafeNativeMethods.OpenProcess(SafeNativeMethods.PROCESS_QUERY_INFORMATION, false, currentProcessId); - var result = SafeNativeMethods.GetProcessDpiAwareness(hProcess, out processDpiAwareness); + var result = SafeNativeMethods.GetProcessDpiAwareness(hProcess, out CAPS.PROCESS_DPI_AWARENESS processDpiAwareness); // Only if we're not, it makes sense to query for PerMonitorV2 awareness from now on, if needed. if (!(processDpiAwareness == CAPS.PROCESS_DPI_AWARENESS.PROCESS_DPI_UNAWARE || @@ -388,9 +387,8 @@ internal static HighDpiMode GetWinformsApplicationDpiAwareness() // For operating systems windows 8.1 to Windows 10 redstone 1 version. else if (ApiHelper.IsApiAvailable(ExternDll.ShCore, nameof(SafeNativeMethods.GetProcessDpiAwareness))) { - CAPS.PROCESS_DPI_AWARENESS processDpiAwareness; - SafeNativeMethods.GetProcessDpiAwareness(IntPtr.Zero, out processDpiAwareness); + SafeNativeMethods.GetProcessDpiAwareness(IntPtr.Zero, out CAPS.PROCESS_DPI_AWARENESS processDpiAwareness); switch (processDpiAwareness) { case CAPS.PROCESS_DPI_AWARENESS.PROCESS_DPI_UNAWARE: diff --git a/src/Common/tests/InternalUtilitiesForTests/src/PlatformDetection.Windows.cs b/src/Common/tests/InternalUtilitiesForTests/src/PlatformDetection.Windows.cs index 8e2a2955c15..cd60ec6a353 100644 --- a/src/Common/tests/InternalUtilitiesForTests/src/PlatformDetection.Windows.cs +++ b/src/Common/tests/InternalUtilitiesForTests/src/PlatformDetection.Windows.cs @@ -176,15 +176,12 @@ public static bool IsWindowsAndElevated return false; } - IntPtr processToken; - Assert.True(OpenProcessToken(GetCurrentProcess(), TOKEN_READ, out processToken)); + Assert.True(OpenProcessToken(GetCurrentProcess(), TOKEN_READ, out IntPtr processToken)); try { - uint tokenInfo; - uint returnLength; Assert.True(GetTokenInformation( - processToken, TokenElevation, out tokenInfo, sizeof(uint), out returnLength)); + processToken, TokenElevation, out uint tokenInfo, sizeof(uint), out uint returnLength)); s_isWindowsElevated = tokenInfo == 0 ? 0 : 1; } diff --git a/src/System.Windows.Forms.Design.Editors/src/Misc/DpiHelper.cs b/src/System.Windows.Forms.Design.Editors/src/Misc/DpiHelper.cs index 9bd232a25f4..da0789cbda9 100644 --- a/src/System.Windows.Forms.Design.Editors/src/Misc/DpiHelper.cs +++ b/src/System.Windows.Forms.Design.Editors/src/Misc/DpiHelper.cs @@ -240,8 +240,7 @@ internal static void InitializeDpiHelperQuirks() internal static bool IsExpectedConfigValue(string configurationSettingName, bool expectedValue) { string value = ConfigurationOptions.GetConfigSettingValue(configurationSettingName); - bool valueAsBool; - if (!bool.TryParse(value, out valueAsBool)) + if (!bool.TryParse(value, out bool valueAsBool)) { // neither 'true' nor 'false' - implies 'false' valueAsBool = false; diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/FolderNameEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/FolderNameEditor.cs index 16fe52fbcce..2c067453446 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/FolderNameEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/FolderNameEditor.cs @@ -97,8 +97,7 @@ public unsafe DialogResult ShowDialog(IWin32Window owner) IntPtr hWndOwner = owner == null ? owner.Handle : UnsafeNativeMethods.GetActiveWindow(); // Get the IDL for the specific startLocation - CoTaskMemSafeHandle listHandle; - Interop.Shell32.SHGetSpecialFolderLocation(hWndOwner, (int)StartLocation, out listHandle); + Interop.Shell32.SHGetSpecialFolderLocation(hWndOwner, (int)StartLocation, out CoTaskMemSafeHandle listHandle); if (listHandle.IsInvalid) { return DialogResult.Cancel; diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentCodeDomSerializer.cs index 3c5509ff229..923d967097a 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentCodeDomSerializer.cs @@ -322,8 +322,7 @@ public override object Serialize(IDesignerSerializationManager manager, object v else { // For compat reasons we ignore the isCompleteOld value here. - bool isCompleteOld; - assignRhs = SerializeCreationExpression(manager, value, out isCompleteOld); + assignRhs = SerializeCreationExpression(manager, value, out bool isCompleteOld); Debug.Assert(isCompleteOld == isComplete, "CCDS Differing"); } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PropertyMemberCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PropertyMemberCodeDomSerializer.cs index 76ab55d673c..b071aebb502 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PropertyMemberCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PropertyMemberCodeDomSerializer.cs @@ -166,8 +166,7 @@ private void SerializeContentProperty(IDesignerSerializationManager manager, obj { CodeDomSerializer.Trace("Property is marked as Visibility.Content. Recursing."); - bool validValue; - object propertyValue = GetPropertyValue(manager, property, value, out validValue); + object propertyValue = GetPropertyValue(manager, property, value, out bool validValue); // For persist contents objects, we don't just serialize the properties on the object; we // serialize everything. @@ -310,8 +309,7 @@ private void SerializeExtenderProperty(IDesignerSerializationManager manager, ob if (extender != null && extended != null) { CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression(extender, "Set" + property.Name); - bool validValue; - object propValue = GetPropertyValue(manager, property, value, out validValue); + object propValue = GetPropertyValue(manager, property, value, out bool validValue); CodeExpression serializedPropertyValue = null; // Serialize the value of this property into a code expression. If we can't get one, @@ -399,8 +397,7 @@ private void SerializeNormalProperty(IDesignerSerializationManager manager, obje // Serialize the value of this property into a code expression. If we can't get one, // then we won't serialize the property. // - bool validValue; - object propValue = GetPropertyValue(manager, property, value, out validValue); + object propValue = GetPropertyValue(manager, property, value, out bool validValue); if (validValue) { diff --git a/src/System.Windows.Forms/src/Common/System/LocalAppContext.cs b/src/System.Windows.Forms/src/Common/System/LocalAppContext.cs index 2a9dc22d1a7..cbe86158398 100644 --- a/src/System.Windows.Forms/src/Common/System/LocalAppContext.cs +++ b/src/System.Windows.Forms/src/Common/System/LocalAppContext.cs @@ -26,8 +26,7 @@ internal static bool GetCachedSwitchValue(string switchName, ref int switchValue private static bool GetCachedSwitchValueInternal(string switchName, ref int switchValue) { - bool isSwitchEnabled; - AppContext.TryGetSwitch(switchName, out isSwitchEnabled); + AppContext.TryGetSwitch(switchName, out bool isSwitchEnabled); if (DisableCaching) { @@ -41,8 +40,7 @@ private static bool GetCachedSwitchValueInternal(string switchName, ref int swit private static bool DisableCaching => LazyInitializer.EnsureInitialized(ref s_disableCaching, ref s_isDisableCachingInitialized, ref s_syncObject, () => { - bool isEnabled; - AppContext.TryGetSwitch(@"TestSwitch.LocalAppContext.DisableCaching", out isEnabled); + AppContext.TryGetSwitch(@"TestSwitch.LocalAppContext.DisableCaching", out bool isEnabled); return isEnabled; }); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleObject.cs index d09ba604c7a..1e060cf73eb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleObject.cs @@ -1983,8 +1983,7 @@ public virtual AccessibleObject Navigate(AccessibleNavigation navdir) { try { - object retObject = null; - if (!SysNavigate((int)navdir, NativeMethods.CHILDID_SELF, out retObject)) + if (!SysNavigate((int)navdir, NativeMethods.CHILDID_SELF, out object retObject)) retObject = systemIAccessible.accNavigate((int)navdir, NativeMethods.CHILDID_SELF); return WrapIAccessible(retObject); } @@ -2122,8 +2121,7 @@ private bool SysNavigate(int navDir, object childID, out object retObject) } // Perform any supported navigation operation (fall back on system for unsupported navigation ops) - AccessibleObject newObject; - if (!GetSysChild((AccessibleNavigation)navDir, out newObject)) + if (!GetSysChild((AccessibleNavigation)navDir, out AccessibleObject newObject)) { return false; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs index eca693fd6e4..4a1847b3b13 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs @@ -814,9 +814,8 @@ public static VisualStyleState VisualStyleState /// private static bool SendThemeChanged(IntPtr handle, IntPtr extraParameter) { - int processId; int thisPID = SafeNativeMethods.GetCurrentProcessId(); - SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(null, handle), out processId); + SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(null, handle), out int processId); if (processId == thisPID && SafeNativeMethods.IsWindowVisible(new HandleRef(null, handle))) { @@ -898,7 +897,6 @@ public static void AddMessageFilter(IMessageFilter value) public static bool FilterMessage(ref Message message) { - bool modified; // Create copy of MSG structure NativeMethods.MSG msg = new NativeMethods.MSG @@ -909,7 +907,7 @@ public static bool FilterMessage(ref Message message) lParam = message.LParam }; - bool processed = ThreadContext.FromCurrent().ProcessFilters(ref msg, out modified); + bool processed = ThreadContext.FromCurrent().ProcessFilters(ref msg, out bool modified); if (modified) { message.HWnd = msg.hwnd; @@ -1245,8 +1243,7 @@ private static Type GetAppMainType() private static ThreadContext GetContextForHandle(HandleRef handle) { - int pid; - int id = SafeNativeMethods.GetWindowThreadProcessId(handle, out pid); + int id = SafeNativeMethods.GetWindowThreadProcessId(handle, out int pid); ThreadContext cxt = ThreadContext.FromId(id); Debug.Assert(cxt != null, "No thread context for handle. This is expected if you saw a previous assert about the handle being invalid."); return cxt; @@ -2522,8 +2519,7 @@ internal UnsafeNativeMethods.IMsoComponentManager ComponentManager grfcadvf = NativeMethods.MSOCM.msocadvfModal }; - IntPtr localComponentID; - bool result = msocm.FRegisterComponent(this, info, out localComponentID); + bool result = msocm.FRegisterComponent(this, info, out IntPtr localComponentID); componentID = unchecked((int)(long)localComponentID); Debug.Assert(componentID != INVALID_ID, "Our ID sentinel was returned as a valid ID"); @@ -2869,8 +2865,7 @@ private void DisposeParkingWindow() // and do not call Dispose. Otherwise we would destroy // controls that are living on the parking window. // - int pid; - int hwndThread = SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(parkingWindows[0], parkingWindows[0].Handle), out pid); + int hwndThread = SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(parkingWindows[0], parkingWindows[0].Handle), out int pid); int currentThread = SafeNativeMethods.GetCurrentThreadId(); for (int i = 0; i < parkingWindows.Count; i++) @@ -3703,8 +3698,7 @@ internal bool ProcessFilters(ref NativeMethods.MSG msg, out bool modified) /// internal bool PreTranslateMessage(ref NativeMethods.MSG msg) { - bool modified = false; - if (ProcessFilters(ref msg, out modified)) + if (ProcessFilters(ref msg, out bool modified)) { return true; } @@ -4237,8 +4231,8 @@ internal override void RemoveReflectChild() //This is important for scenarios where apps leak controls until after the //messagepump is gone and then decide to clean them up. We should clean //up the parkingwindow in this case and a postmessage won't do it. - int lpdwProcessId; //unused - int id = SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(this, HandleInternal), out lpdwProcessId); + //unused + int id = SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(this, HandleInternal), out int lpdwProcessId); Application.ThreadContext ctx = Application.ThreadContext.FromId(id); //We only do this if the ThreadContext tells us that we are currently diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs index cea719ffa51..caeccf87819 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs @@ -340,8 +340,7 @@ protected virtual void AttachInterfaces() private void RealizeStyles() { SetStyle(ControlStyles.UserPaint, false); - int bits = 0; - int hr = GetOleObject().GetMiscStatus(NativeMethods.ActiveX.DVASPECT_CONTENT, out bits); + int hr = GetOleObject().GetMiscStatus(NativeMethods.ActiveX.DVASPECT_CONTENT, out int bits); if (!NativeMethods.Failed(hr)) { miscStatusBits = bits; @@ -2675,8 +2674,7 @@ private CategoryAttribute GetCategoryForDispid(int dispid) return rval; } - string name = null; - int hr = icp.GetCategoryName(cat, CultureInfo.CurrentCulture.LCID, out name); + int hr = icp.GetCategoryName(cat, CultureInfo.CurrentCulture.LCID, out string name); if (hr == NativeMethods.S_OK && name != null) { rval = new CategoryAttribute(name); @@ -3592,8 +3590,7 @@ protected override void WndProc(ref Message m) if (GetOcState() >= OC_INPLACE) { UnsafeNativeMethods.IOleInPlaceObject ipo = GetInPlaceObject(); - IntPtr hwnd; - if (NativeMethods.Succeeded(ipo.GetWindow(out hwnd))) + if (NativeMethods.Succeeded(ipo.GetWindow(out IntPtr hwnd))) { Application.ParkHandle(new HandleRef(ipo, hwnd)); } @@ -4384,8 +4381,7 @@ int UnsafeNativeMethods.IOleClientSite.ShowObject() if (host.GetOcState() < OC_INPLACE) return NativeMethods.S_OK; - IntPtr hwnd; - if (NativeMethods.Succeeded(host.GetInPlaceObject().GetWindow(out hwnd))) + if (NativeMethods.Succeeded(host.GetInPlaceObject().GetWindow(out IntPtr hwnd))) { if (host.GetHandleNoCreate() != hwnd) { @@ -7563,8 +7559,7 @@ private Guid GetPropertyPage(int dispid) NativeMethods.IPerPropertyBrowsing ippb = owner.GetPerPropertyBrowsing(); if (ippb == null) return Guid.Empty; - Guid rval; - if (NativeMethods.Succeeded(ippb.MapPropertyToPage(dispid, out rval))) + if (NativeMethods.Succeeded(ippb.MapPropertyToPage(dispid, out Guid rval))) { return rval; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs b/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs index bdb531b280b..9b4f3fc88f8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs @@ -614,8 +614,7 @@ protected virtual void OnRefreshItems() /// public bool Validate() { - bool validatedControlAllowsFocusChange; - return ValidateActiveControl(out validatedControlAllowsFocusChange); + return ValidateActiveControl(out bool validatedControlAllowsFocusChange); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/BindingSource.cs b/src/System.Windows.Forms/src/System/Windows/Forms/BindingSource.cs index 762284208b0..0981ac842ba 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/BindingSource.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/BindingSource.cs @@ -916,8 +916,7 @@ private void ParentCurrencyManager_CurrentItemChanged(object sender, EventArgs e // Do what RelatedCurrencyManager does when the parent changes: // 1. PullData from the controls into the back end. // 2. Don't EndEdit the transaction. - bool success; - _currencyManager.PullData(out success); + _currencyManager.PullData(out bool success); } finally { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Button.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Button.cs index 0861108c3fa..f33ca443552 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Button.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Button.cs @@ -355,8 +355,7 @@ public void PerformClick() { if (CanSelect) { - bool validatedControlAllowsFocusChange; - bool validate = ValidateActiveControl(out validatedControlAllowsFocusChange); + bool validate = ValidateActiveControl(out bool validatedControlAllowsFocusChange); if (!ValidationCancelled && (validate || validatedControlAllowsFocusChange)) { //Paint in raised state... diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs index 194b2485d04..236e332b825 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs @@ -501,8 +501,7 @@ public DrawMode DrawMode { get { - bool found; - int drawMode = Properties.GetInteger(PropDrawMode, out found); + int drawMode = Properties.GetInteger(PropDrawMode, out bool found); if (found) { return (DrawMode)drawMode; @@ -537,8 +536,7 @@ public int DropDownWidth { get { - bool found; - int dropDownWidth = Properties.GetInteger(PropDropDownWidth, out found); + int dropDownWidth = Properties.GetInteger(PropDropDownWidth, out bool found); if (found) { @@ -581,8 +579,7 @@ public int DropDownHeight { get { - bool found; - int dropDownHeight = Properties.GetInteger(PropDropDownHeight, out found); + int dropDownHeight = Properties.GetInteger(PropDropDownHeight, out bool found); if (found) { return dropDownHeight; @@ -764,8 +761,7 @@ public int ItemHeight !IsHandleCreated) { - bool found; - int itemHeight = Properties.GetInteger(PropItemHeight, out found); + int itemHeight = Properties.GetInteger(PropItemHeight, out bool found); if (found) { return itemHeight; @@ -1325,8 +1321,7 @@ public ComboBoxStyle DropDownStyle { get { - bool found; - int style = Properties.GetInteger(PropStyle, out found); + int style = Properties.GetInteger(PropStyle, out bool found); if (found) { return (ComboBoxStyle)style; @@ -2592,8 +2587,7 @@ protected override void OnHandleCreated(EventArgs e) } } - bool found; - int dropDownWidth = Properties.GetInteger(PropDropDownWidth, out found); + int dropDownWidth = Properties.GetInteger(PropDropDownWidth, out bool found); if (found) { SendMessage(NativeMethods.CB_SETDROPPEDWIDTH, dropDownWidth, 0); @@ -5514,8 +5508,7 @@ internal override UnsafeNativeMethods.IRawElementProviderSimple HostRawElementPr { get { - UnsafeNativeMethods.IRawElementProviderSimple provider; - UnsafeNativeMethods.UiaHostProviderFromHwnd(new HandleRef(this, _handle), out provider); + UnsafeNativeMethods.UiaHostProviderFromHwnd(new HandleRef(this, _handle), out UnsafeNativeMethods.IRawElementProviderSimple provider); return provider; } } @@ -5747,8 +5740,7 @@ internal override UnsafeNativeMethods.IRawElementProviderSimple HostRawElementPr { get { - UnsafeNativeMethods.IRawElementProviderSimple provider; - UnsafeNativeMethods.UiaHostProviderFromHwnd(new HandleRef(this, _childListControlhandle), out provider); + UnsafeNativeMethods.UiaHostProviderFromHwnd(new HandleRef(this, _childListControlhandle), out UnsafeNativeMethods.IRawElementProviderSimple provider); return provider; } } @@ -6008,12 +6000,8 @@ public override Rectangle Bounds { get { - int left; - int top; - int width; - int height; var systemIAccessible = GetSystemIAccessibleInternal(); - systemIAccessible.accLocation(out left, out top, out width, out height, COMBOBOX_DROPDOWN_BUTTON_ACC_ITEM_INDEX); + systemIAccessible.accLocation(out int left, out int top, out int width, out int height, COMBOBOX_DROPDOWN_BUTTON_ACC_ITEM_INDEX); return new Rectangle(left, top, width, height); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentManagerBroker.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentManagerBroker.cs index a741bce1bed..bd58013ac31 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentManagerBroker.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentManagerBroker.cs @@ -193,8 +193,7 @@ internal static UnsafeNativeMethods.IMsoComponentManager GetComponentManager(Int // for all component managers. There is no managed way to get this domain, however, // so we use ICorRuntimeHost. UnsafeNativeMethods.ICorRuntimeHost host = (UnsafeNativeMethods.ICorRuntimeHost)RuntimeEnvironment.GetRuntimeInterfaceAsObject(typeof(UnsafeNativeMethods.CorRuntimeHost).GUID, typeof(UnsafeNativeMethods.ICorRuntimeHost).GUID); - object domainObj; - int hr = host.GetDefaultDomain(out domainObj); + int hr = host.GetDefaultDomain(out object domainObj); Debug.Assert(NativeMethods.Succeeded(hr), "ICorRuntimeHost failed to return the default domain. The only way that should happen is if it hasn't been started yet, but if it hasn't been started how are we running managed code?"); AppDomain domain = domainObj as AppDomain; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ICategorizePropertiesHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ICategorizePropertiesHandler.cs index 253f8b2060b..e7f3c449890 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ICategorizePropertiesHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ICategorizePropertiesHandler.cs @@ -39,7 +39,6 @@ private string GetCategoryFromObject(object obj, int dispid) if (NativeMethods.S_OK == catObj.MapPropertyToCategory(dispid, ref categoryID)) { - string categoryName = null; switch (categoryID) { @@ -67,7 +66,7 @@ private string GetCategoryFromObject(object obj, int dispid) return SR.PropertyCategoryDDE; } - if (NativeMethods.S_OK == catObj.GetCategoryName(categoryID, CultureInfo.CurrentCulture.LCID, out categoryName)) + if (NativeMethods.S_OK == catObj.GetCategoryName(categoryID, CultureInfo.CurrentCulture.LCID, out string categoryName)) { return categoryName; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs index d584b2f95c6..fb942e00120 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs @@ -41,8 +41,7 @@ public override void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc) private Guid GetPropertyPageGuid(NativeMethods.IPerPropertyBrowsing target, int dispid) { // check for a property page - Guid guid; - int hr = target.MapPropertyToPage(dispid, out guid); + int hr = target.MapPropertyToPage(dispid, out Guid guid); if (hr == NativeMethods.S_OK) { return guid; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs index d5430196090..63eeb26f5bf 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs @@ -1801,8 +1801,7 @@ public bool Validate() /// public bool Validate(bool checkAutoValidate) { - bool validatedControlAllowsFocusChange; - return ValidateInternal(checkAutoValidate, out validatedControlAllowsFocusChange); + return ValidateInternal(checkAutoValidate, out bool validatedControlAllowsFocusChange); } internal bool ValidateInternal(bool checkAutoValidate, out bool validatedControlAllowsFocusChange) 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 2a2e3410b05..5748dc6e353 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs @@ -771,8 +771,7 @@ public AccessibleRole AccessibleRole get { - bool found; - int role = Properties.GetInteger(PropAccessibleRole, out found); + int role = Properties.GetInteger(PropAccessibleRole, out bool found); if (found) { return (AccessibleRole)role; @@ -934,8 +933,7 @@ private AmbientProperties AmbientPropertiesService { get { - bool contains; - AmbientProperties props = (AmbientProperties)Properties.GetObject(PropAmbientPropertiesService, out contains); + AmbientProperties props = (AmbientProperties)Properties.GetObject(PropAmbientPropertiesService, out bool contains); if (!contains) { if (Site != null) @@ -1587,8 +1585,7 @@ internal bool CacheTextInternal // check if we're caching text. // - bool found; - int cacheTextCounter = Properties.GetInteger(PropCacheTextCount, out found); + int cacheTextCounter = Properties.GetInteger(PropCacheTextCount, out bool found); return cacheTextCounter > 0 || GetStyle(ControlStyles.CacheText); } @@ -1605,8 +1602,7 @@ internal bool CacheTextInternal // otherwise, get the state and update the cache if necessary. // - bool found; - int cacheTextCounter = Properties.GetInteger(PropCacheTextCount, out found); + int cacheTextCounter = Properties.GetInteger(PropCacheTextCount, out bool found); if (value) { @@ -2110,8 +2106,7 @@ internal int CreateThreadId { if (IsHandleCreated) { - int pid; - return SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(this, Handle), out pid); + return SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(this, Handle), out int pid); } else { @@ -2798,8 +2793,7 @@ protected int FontHeight { get { - bool found; - int fontHeight = Properties.GetInteger(PropFontHeight, out found); + int fontHeight = Properties.GetInteger(PropFontHeight, out bool found); if (found && fontHeight != -1) { return fontHeight; @@ -3279,8 +3273,7 @@ public bool InvokeRequired hwnd = new HandleRef(marshalingControl, marshalingControl.Handle); } - int pid; - int hwndThread = SafeNativeMethods.GetWindowThreadProcessId(hwnd, out pid); + int hwndThread = SafeNativeMethods.GetWindowThreadProcessId(hwnd, out int pid); int currentThread = SafeNativeMethods.GetCurrentThreadId(); return (hwndThread != currentThread); } @@ -3966,8 +3959,7 @@ public virtual RightToLeft RightToLeft { get { - bool found; - int rightToLeft = Properties.GetInteger(PropRightToLeft, out found); + int rightToLeft = Properties.GetInteger(PropRightToLeft, out bool found); if (!found) { rightToLeft = (int)RightToLeft.Inherit; @@ -4577,8 +4569,7 @@ internal bool UseCompatibleTextRenderingInt { if (Properties.ContainsInteger(PropUseCompatibleTextRendering)) { - bool found; - int value = Properties.GetInteger(PropUseCompatibleTextRendering, out found); + int value = Properties.GetInteger(PropUseCompatibleTextRendering, out bool found); if (found) { return value == 1; @@ -6347,9 +6338,9 @@ public object EndInvoke(IAsyncResult asyncResult) if (!asyncResult.IsCompleted) { - int pid; // ignored + // ignored Control marshaler = FindMarshalingControl(); - if (SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(marshaler, marshaler.Handle), out pid) == SafeNativeMethods.GetCurrentThreadId()) + if (SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(marshaler, marshaler.Handle), out int pid) == SafeNativeMethods.GetCurrentThreadId()) { marshaler.InvokeMarshaledCallbacks(); } @@ -8048,8 +8039,8 @@ private object MarshaledInvoke(Control caller, Delegate method, object[] args, b // 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()) + // ignored + if (SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(this, Handle), out int pid) == SafeNativeMethods.GetCurrentThreadId()) { if (synchronous) syncSameThread = true; @@ -12632,8 +12623,7 @@ internal virtual bool ShouldSerializeBackColor() [EditorBrowsable(EditorBrowsableState.Never)] internal virtual bool ShouldSerializeCursor() { - bool found; - object cursor = Properties.GetObject(PropCursor, out found); + object cursor = Properties.GetObject(PropCursor, out bool found); return (found && cursor != null); } @@ -12662,8 +12652,7 @@ internal virtual bool ShouldSerializeForeColor() [EditorBrowsable(EditorBrowsableState.Never)] internal virtual bool ShouldSerializeFont() { - bool found; - object font = Properties.GetObject(PropFont, out found); + object font = Properties.GetObject(PropFont, out bool found); return (found && font != null); } @@ -12673,8 +12662,7 @@ internal virtual bool ShouldSerializeFont() [EditorBrowsable(EditorBrowsableState.Never)] internal virtual bool ShouldSerializeRightToLeft() { - bool found; - int rtl = Properties.GetInteger(PropRightToLeft, out found); + int rtl = Properties.GetInteger(PropRightToLeft, out bool found); return (found && rtl != (int)RightToLeft.Inherit); } @@ -16860,8 +16848,7 @@ internal ToolStripControlHost ToolStripControlHost { get { - ToolStripControlHost value; - toolStripControlHostReference.TryGetTarget(out value); + toolStripControlHostReference.TryGetTarget(out ToolStripControlHost value); return value; } set @@ -17140,9 +17127,8 @@ internal bool IsIE if (Assembly.GetEntryAssembly() == null) { // Now check for IHTMLDocument2 - UnsafeNativeMethods.IOleContainer container; - if (NativeMethods.Succeeded(clientSite.GetContainer(out container)) && container is NativeMethods.IHTMLDocument) + if (NativeMethods.Succeeded(clientSite.GetContainer(out UnsafeNativeMethods.IOleContainer container)) && container is NativeMethods.IHTMLDocument) { isIE = true; Debug.WriteLineIf(CompModSwitches.ActiveX.TraceVerbose, "AxSource:IsIE running under IE"); @@ -17793,8 +17779,6 @@ internal void InPlaceActivate(int verb) // hwndParent = inPlaceSite.GetWindow(); - UnsafeNativeMethods.IOleInPlaceFrame pFrame; - UnsafeNativeMethods.IOleInPlaceUIWindow pWindow; NativeMethods.COMRECT posRect = new NativeMethods.COMRECT(); NativeMethods.COMRECT clipRect = new NativeMethods.COMRECT(); @@ -17810,7 +17794,7 @@ internal void InPlaceActivate(int verb) inPlaceFrame = null; } - inPlaceSite.GetWindowContext(out pFrame, out pWindow, posRect, clipRect, inPlaceFrameInfo); + inPlaceSite.GetWindowContext(out UnsafeNativeMethods.IOleInPlaceFrame pFrame, out UnsafeNativeMethods.IOleInPlaceUIWindow pWindow, posRect, clipRect, inPlaceFrameInfo); SetObjectRects(posRect, clipRect); @@ -18409,7 +18393,6 @@ internal void QuickActivate(UnsafeNativeMethods.tagQACONTAINER pQaContainer, Uns // Now use the rest of the goo that we got passed in. // - int status; pQaControl.cbSize = Marshal.SizeOf(); @@ -18420,7 +18403,7 @@ internal void QuickActivate(UnsafeNativeMethods.tagQACONTAINER pQaContainer, Uns SetAdvise(NativeMethods.DVASPECT_CONTENT, 0, (IAdviseSink)pQaContainer.pAdviseSink); } - ((UnsafeNativeMethods.IOleObject)control).GetMiscStatus(NativeMethods.DVASPECT_CONTENT, out status); + ((UnsafeNativeMethods.IOleObject)control).GetMiscStatus(NativeMethods.DVASPECT_CONTENT, out int status); pQaControl.dwMiscStatus = status; // Advise the event sink so VB6 can catch events raised from UserControls. @@ -18600,8 +18583,7 @@ public SafeIUnknown(object obj, bool addRefIntPtr, Guid iid) /// private static IntPtr InternalQueryInterface(IntPtr pUnk, ref Guid iid) { - IntPtr ppv; - int hresult = Marshal.QueryInterface(pUnk, ref iid, out ppv); + int hresult = Marshal.QueryInterface(pUnk, ref iid, out IntPtr ppv); if (hresult != 0 || ppv == IntPtr.Zero) { throw new InvalidCastException(SR.AxInterfaceNotSupported); @@ -19692,8 +19674,7 @@ public object GetService(Type service) if (service == typeof(HtmlDocument)) { - UnsafeNativeMethods.IOleContainer iOlecontainer; - int hr = clientSite.GetContainer(out iOlecontainer); + int hr = clientSite.GetContainer(out UnsafeNativeMethods.IOleContainer iOlecontainer); if (NativeMethods.Succeeded(hr) && (iOlecontainer is UnsafeNativeMethods.IHTMLDocument)) @@ -19792,9 +19773,8 @@ public IntPtr MarshalManagedToNative(object obj) UnsafeNativeMethods.IFont oleFont = UnsafeNativeMethods.OleCreateFontIndirect(fontDesc, ref iid); IntPtr pFont = Marshal.GetIUnknownForObject(oleFont); - IntPtr pIFont; - int hr = Marshal.QueryInterface(pFont, ref iid, out pIFont); + int hr = Marshal.QueryInterface(pFont, ref iid, out IntPtr pIFont); Marshal.Release(pFont); @@ -20792,8 +20772,7 @@ internal override UnsafeNativeMethods.IRawElementProviderSimple HostRawElementPr { get { - UnsafeNativeMethods.IRawElementProviderSimple provider; - UnsafeNativeMethods.UiaHostProviderFromHwnd(new HandleRef(this, Handle), out provider); + UnsafeNativeMethods.UiaHostProviderFromHwnd(new HandleRef(this, Handle), out UnsafeNativeMethods.IRawElementProviderSimple provider); return provider; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonCell.cs index db1eb83a90c..2d34bae3870 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonCell.cs @@ -45,8 +45,7 @@ private ButtonState ButtonState { get { - bool found; - int buttonState = Properties.GetInteger(PropButtonCellState, out found); + int buttonState = Properties.GetInteger(PropButtonCellState, out bool found); if (found) { return (ButtonState)buttonState; @@ -81,8 +80,7 @@ public FlatStyle FlatStyle { get { - bool found; - int flatStyle = Properties.GetInteger(PropButtonCellFlatStyle, out found); + int flatStyle = Properties.GetInteger(PropButtonCellFlatStyle, out bool found); if (found) { return (FlatStyle)flatStyle; @@ -130,8 +128,7 @@ public bool UseColumnTextForButtonValue { get { - bool found; - int useColumnTextForButtonValue = Properties.GetInteger(PropButtonCellUseColumnTextForButtonValue, out found); + int useColumnTextForButtonValue = Properties.GetInteger(PropButtonCellUseColumnTextForButtonValue, out bool found); if (found) { return useColumnTextForButtonValue == 0 ? false : true; @@ -208,11 +205,8 @@ protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCel return Rectangle.Empty; } - DataGridViewAdvancedBorderStyle dgvabsEffective; - DataGridViewElementStates cellState; - Rectangle cellBounds; - ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds); + ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds); Rectangle contentBounds = PaintPrivate(graphics, cellBounds, @@ -265,11 +259,8 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC return Rectangle.Empty; } - DataGridViewAdvancedBorderStyle dgvabsEffective; - DataGridViewElementStates cellState; - Rectangle cellBounds; - ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds); + ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds); Rectangle errorIconBounds = PaintPrivate(graphics, cellBounds, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs index ae4d22f64a1..6691eb37aa0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs @@ -2745,8 +2745,7 @@ internal bool LeaveUnsharesRowInternal(int rowIndex, bool throughMouseClick) ] public static int MeasureTextHeight(Graphics graphics, string text, Font font, int maxWidth, TextFormatFlags flags) { - bool widthTruncated; - return DataGridViewCell.MeasureTextHeight(graphics, text, font, maxWidth, flags, out widthTruncated); + return DataGridViewCell.MeasureTextHeight(graphics, text, font, maxWidth, flags, out bool widthTruncated); } [ @@ -4567,8 +4566,7 @@ internal bool SetValueInternal(int rowIndex, object value) internal static bool TextFitsInBounds(Graphics graphics, string text, Font font, Size maxBounds, TextFormatFlags flags) { - bool widthTruncated; - int requiredHeight = DataGridViewCell.MeasureTextHeight(graphics, text, font, maxBounds.Width, flags, out widthTruncated); + int requiredHeight = DataGridViewCell.MeasureTextHeight(graphics, text, font, maxBounds.Width, flags, out bool widthTruncated); return requiredHeight <= maxBounds.Height && !widthTruncated; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyle.cs index ebf989163cf..64766c09455 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyle.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyle.cs @@ -84,8 +84,7 @@ public DataGridViewContentAlignment Alignment { get { - bool found; - int alignment = Properties.GetInteger(PropAlignment, out found); + int alignment = Properties.GetInteger(PropAlignment, out bool found); if (found) { return (DataGridViewContentAlignment)alignment; @@ -530,8 +529,7 @@ public DataGridViewTriState WrapMode { get { - bool found; - int wrap = Properties.GetInteger(PropWrapMode, out found); + int wrap = Properties.GetInteger(PropWrapMode, out bool found); if (found) { return (DataGridViewTriState)wrap; @@ -749,8 +747,7 @@ internal void RemoveScope(DataGridViewCellStyleScopes scope) private bool ShouldSerializeBackColor() { - bool found; - Properties.GetColor(PropBackColor, out found); + Properties.GetColor(PropBackColor, out bool found); return found; } @@ -761,8 +758,7 @@ private bool ShouldSerializeFont() private bool ShouldSerializeForeColor() { - bool found; - Properties.GetColor(PropForeColor, out found); + Properties.GetColor(PropForeColor, out bool found); return found; } @@ -778,15 +774,13 @@ private bool ShouldSerializePadding() private bool ShouldSerializeSelectionBackColor() { - bool found; - Properties.GetObject(PropSelectionBackColor, out found); + Properties.GetObject(PropSelectionBackColor, out bool found); return found; } private bool ShouldSerializeSelectionForeColor() { - bool found; - Properties.GetColor(PropSelectionForeColor, out found); + Properties.GetColor(PropSelectionForeColor, out bool found); return found; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs index d294367c542..5e4540dc420 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs @@ -190,8 +190,7 @@ private ButtonState ButtonState { get { - bool found; - int buttonState = Properties.GetInteger(PropButtonCellState, out found); + int buttonState = Properties.GetInteger(PropButtonCellState, out bool found); if (found) { return (ButtonState)buttonState; @@ -263,8 +262,7 @@ public FlatStyle FlatStyle { get { - bool found; - int flatStyle = Properties.GetInteger(PropFlatStyle, out found); + int flatStyle = Properties.GetInteger(PropFlatStyle, out bool found); if (found) { return (FlatStyle)flatStyle; @@ -518,11 +516,8 @@ protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCel return Rectangle.Empty; } - DataGridViewAdvancedBorderStyle dgvabsEffective; - DataGridViewElementStates cellState; - Rectangle cellBounds; - ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds); + ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds); Rectangle checkBoxBounds = PaintPrivate(graphics, cellBounds, @@ -585,11 +580,8 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC } - DataGridViewAdvancedBorderStyle dgvabsEffective; - DataGridViewElementStates cellState; - Rectangle cellBounds; - ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds); + ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds); Rectangle errorIconBounds = PaintPrivate(graphics, cellBounds, @@ -777,11 +769,8 @@ protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyl } // We should consider the border size when calculating the preferred size. - DataGridViewAdvancedBorderStyle dgvabsEffective; - DataGridViewElementStates cellState; - Rectangle cellBounds; - ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds); + ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds); Rectangle borderWidths = BorderWidths(dgvabsEffective); preferredSize.Width += borderWidths.X; preferredSize.Height += borderWidths.Y; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs index fd3c8e605ec..51f2bab6ea3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs @@ -1123,8 +1123,7 @@ internal void RemoveAtInternal(int index, bool force) Debug.Assert(!DataGridView.InDisplayIndexAdjustments); DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)items[index]; - Point newCurrentCell; - DataGridView.OnRemovingColumn(dataGridViewColumn, out newCurrentCell, force); + DataGridView.OnRemovingColumn(dataGridViewColumn, out Point newCurrentCell, force); InvalidateCachedColumnsOrder(); items.RemoveAt(index); dataGridViewColumn.DataGridViewInternal = null; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnHeaderCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnHeaderCell.cs index b7376ad5331..629369c9a20 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnHeaderCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnHeaderCell.cs @@ -243,11 +243,8 @@ protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCel // we mimic a lot of the painting code // get the borders - DataGridViewAdvancedBorderStyle dgvabsEffective; - DataGridViewElementStates cellState; - Rectangle cellBounds; - ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds); + ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds); Rectangle contentBounds = PaintPrivate(graphics, cellBounds, @@ -935,8 +932,7 @@ private Rectangle PaintPrivate(Graphics g, 2 * sortGlyphHorizontalMargin; if (width > 0) { - bool widthTruncated; - int preferredHeight = DataGridViewCell.GetPreferredTextHeight(g, DataGridView.RightToLeftInternal, formattedValueStr, cellStyle, width, out widthTruncated); + int preferredHeight = DataGridViewCell.GetPreferredTextHeight(g, DataGridView.RightToLeftInternal, formattedValueStr, cellStyle, width, out bool widthTruncated); if (preferredHeight <= valBounds.Height && !widthTruncated) { displaySortGlyph = (SortGlyphDirection != SortOrder.None); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs index 37c1900b654..ca0763e41b5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs @@ -295,8 +295,7 @@ public DataGridViewComboBoxDisplayStyle DisplayStyle { get { - bool found; - int displayStyle = Properties.GetInteger(PropComboBoxCellDisplayStyle, out found); + int displayStyle = Properties.GetInteger(PropComboBoxCellDisplayStyle, out bool found); if (found) { return (DataGridViewComboBoxDisplayStyle)displayStyle; @@ -345,8 +344,7 @@ public bool DisplayStyleForCurrentCellOnly { get { - bool found; - int displayStyleForCurrentCellOnly = Properties.GetInteger(PropComboBoxCellDisplayStyleForCurrentCellOnly, out found); + int displayStyleForCurrentCellOnly = Properties.GetInteger(PropComboBoxCellDisplayStyleForCurrentCellOnly, out bool found); if (found) { return displayStyleForCurrentCellOnly == 0 ? false : true; @@ -423,8 +421,7 @@ public virtual int DropDownWidth { get { - bool found; - int dropDownWidth = Properties.GetInteger(PropComboBoxCellDropDownWidth, out found); + int dropDownWidth = Properties.GetInteger(PropComboBoxCellDropDownWidth, out bool found); return found ? dropDownWidth : 1; } set @@ -470,8 +467,7 @@ public FlatStyle FlatStyle { get { - bool found; - int flatStyle = Properties.GetInteger(PropComboBoxCellFlatStyle, out found); + int flatStyle = Properties.GetInteger(PropComboBoxCellFlatStyle, out bool found); if (found) { return (FlatStyle)flatStyle; @@ -535,8 +531,7 @@ public virtual int MaxDropDownItems { get { - bool found; - int maxDropDownItems = Properties.GetInteger(PropComboBoxCellMaxDropDownItems, out found); + int maxDropDownItems = Properties.GetInteger(PropComboBoxCellMaxDropDownItems, out bool found); if (found) { return maxDropDownItems; @@ -943,13 +938,9 @@ protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCel object value = GetValue(rowIndex); object formattedValue = GetEditedFormattedValue(value, rowIndex, ref cellStyle, DataGridViewDataErrorContexts.Formatting); - DataGridViewAdvancedBorderStyle dgvabsEffective; - DataGridViewElementStates cellState; - Rectangle cellBounds; - ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds); + ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds); - Rectangle dropDownButtonRect; Rectangle contentBounds = PaintPrivate(graphics, cellBounds, cellBounds, @@ -959,7 +950,7 @@ protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCel null /*errorText*/, // contentBounds is independent of errorText cellStyle, dgvabsEffective, - out dropDownButtonRect, // not used + out Rectangle dropDownButtonRect, // not used DataGridViewPaintParts.ContentForeground, true /*computeContentBounds*/, false /*computeErrorIconBounds*/, @@ -1050,13 +1041,9 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC object value = GetValue(rowIndex); object formattedValue = GetEditedFormattedValue(value, rowIndex, ref cellStyle, DataGridViewDataErrorContexts.Formatting); - DataGridViewAdvancedBorderStyle dgvabsEffective; - DataGridViewElementStates cellState; - Rectangle cellBounds; - ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds); + ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds); - Rectangle dropDownButtonRect; Rectangle errorIconBounds = PaintPrivate(graphics, cellBounds, cellBounds, @@ -1066,7 +1053,7 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC GetErrorText(rowIndex), cellStyle, dgvabsEffective, - out dropDownButtonRect, // not used + out Rectangle dropDownButtonRect, // not used DataGridViewPaintParts.ContentForeground, false /*computeContentBounds*/, true /*computeErrorBounds*/, @@ -1144,8 +1131,7 @@ protected override object GetFormattedValue(object value, if ((DataManager != null && (ValueMemberProperty != null || DisplayMemberProperty != null)) || !string.IsNullOrEmpty(ValueMember) || !string.IsNullOrEmpty(DisplayMember)) { - object displayValue; - if (!LookupDisplayValue(rowIndex, value, out displayValue)) + if (!LookupDisplayValue(rowIndex, value, out object displayValue)) { if (value == System.DBNull.Value) { @@ -2020,7 +2006,6 @@ protected override void Paint(Graphics graphics, throw new ArgumentNullException(nameof(cellStyle)); } - Rectangle dropDownButtonRect; PaintPrivate(graphics, clipBounds, cellBounds, @@ -2030,7 +2015,7 @@ protected override void Paint(Graphics graphics, errorText, cellStyle, advancedBorderStyle, - out dropDownButtonRect, // not used + out Rectangle dropDownButtonRect, // not used paintParts, false /*computeContentBounds*/, false /*computeErrorIconBounds*/, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewDataConnection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewDataConnection.cs index 6f5275ff2b8..6e73a7ec3c1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewDataConnection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewDataConnection.cs @@ -305,9 +305,7 @@ public void ApplySortingInformationFromBackEnd() return; } - PropertyDescriptor sortField = null; - SortOrder sortOrder; - GetSortingInformationFromBackend(out sortField, out sortOrder); + GetSortingInformationFromBackend(out PropertyDescriptor sortField, out SortOrder sortOrder); // If we are not bound to a sorted IBindingList then set the SortGlyphDirection to SortOrder.None // on each dataBound DataGridViewColumn. @@ -403,10 +401,8 @@ public SortOrder BoundColumnSortOrder(int boundColumnIndex) return SortOrder.None; } - PropertyDescriptor sortProperty; - SortOrder sortOrder; - GetSortingInformationFromBackend(out sortProperty, out sortOrder); + GetSortingInformationFromBackend(out PropertyDescriptor sortProperty, out SortOrder sortOrder); if (sortOrder == SortOrder.None) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHeaderCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHeaderCell.cs index b7eb37091c0..c508c357f83 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHeaderCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHeaderCell.cs @@ -37,8 +37,7 @@ protected ButtonState ButtonState { get { - bool found; - int buttonState = Properties.GetInteger(PropButtonState, out found); + int buttonState = Properties.GetInteger(PropButtonState, out bool found); if (found) { return (ButtonState)buttonState; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageCell.cs index 86709879429..e468a19e972 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageCell.cs @@ -139,8 +139,7 @@ public DataGridViewImageCellLayout ImageLayout { get { - bool found; - int imageLayout = Properties.GetInteger(PropImageCellLayout, out found); + int imageLayout = Properties.GetInteger(PropImageCellLayout, out bool found); if (found) { return (DataGridViewImageCellLayout)imageLayout; @@ -302,11 +301,8 @@ protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCel object value = GetValue(rowIndex); object formattedValue = GetFormattedValue(value, rowIndex, ref cellStyle, null, null, DataGridViewDataErrorContexts.Formatting); - DataGridViewAdvancedBorderStyle dgvabsEffective; - DataGridViewElementStates cellState; - Rectangle cellBounds; - ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds); + ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds); Rectangle imgBounds = PaintPrivate(graphics, cellBounds, @@ -361,11 +357,8 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC object value = GetValue(rowIndex); object formattedValue = GetFormattedValue(value, rowIndex, ref cellStyle, null, null, DataGridViewDataErrorContexts.Formatting); - DataGridViewAdvancedBorderStyle dgvabsEffective; - DataGridViewElementStates cellState; - Rectangle cellBounds; - ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds); + ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds); Rectangle errBounds = PaintPrivate(graphics, cellBounds, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkCell.cs index 0139e6379ac..1e882b7ed28 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkCell.cs @@ -131,8 +131,7 @@ public LinkBehavior LinkBehavior { get { - bool found; - int linkBehavior = Properties.GetInteger(PropLinkCellLinkBehavior, out found); + int linkBehavior = Properties.GetInteger(PropLinkCellLinkBehavior, out bool found); if (found) { return (LinkBehavior)linkBehavior; @@ -242,8 +241,7 @@ private LinkState LinkState { get { - bool found; - int linkState = Properties.GetInteger(PropLinkCellLinkState, out found); + int linkState = Properties.GetInteger(PropLinkCellLinkState, out bool found); if (found) { return (LinkState)linkState; @@ -302,8 +300,7 @@ public bool TrackVisitedState { get { - bool found; - int trackVisitedState = Properties.GetInteger(PropLinkCellTrackVisitedState, out found); + int trackVisitedState = Properties.GetInteger(PropLinkCellTrackVisitedState, out bool found); if (found) { return trackVisitedState == 0 ? false : true; @@ -346,8 +343,7 @@ public bool UseColumnTextForLinkValue { get { - bool found; - int useColumnTextForLinkValue = Properties.GetInteger(PropLinkCellUseColumnTextForLinkValue, out found); + int useColumnTextForLinkValue = Properties.GetInteger(PropLinkCellUseColumnTextForLinkValue, out bool found); if (found) { return useColumnTextForLinkValue == 0 ? false : true; @@ -544,11 +540,8 @@ protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCel object value = GetValue(rowIndex); object formattedValue = GetFormattedValue(value, rowIndex, ref cellStyle, null, null, DataGridViewDataErrorContexts.Formatting); - DataGridViewAdvancedBorderStyle dgvabsEffective; - DataGridViewElementStates cellState; - Rectangle cellBounds; - ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds); + ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds); Rectangle linkBounds = PaintPrivate(graphics, cellBounds, @@ -603,11 +596,8 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC object value = GetValue(rowIndex); object formattedValue = GetFormattedValue(value, rowIndex, ref cellStyle, null, null, DataGridViewDataErrorContexts.Formatting); - DataGridViewAdvancedBorderStyle dgvabsEffective; - DataGridViewElementStates cellState; - Rectangle cellBounds; - ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds); + ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds); Rectangle errorIconBounds = PaintPrivate(graphics, cellBounds, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs index 58973f34795..e4b145100b1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs @@ -401,8 +401,7 @@ private int AdjustExpandingRow(int rowIndex, int columnIndex, bool fixedWidth) { preferredThickness = dataGridViewCell.GetPreferredSize(rowIndex).Height; } - int height, minimumHeight; - Rows.SharedRow(rowIndex).GetHeightInfo(rowIndex, out height, out minimumHeight); + Rows.SharedRow(rowIndex).GetHeightInfo(rowIndex, out int height, out int minimumHeight); if (preferredThickness < height) { preferredThickness = height; @@ -2283,8 +2282,7 @@ private void AutoResizeRowInternal(int rowIndex, DataGridViewAutoSizeRowMode aut // IntPtr handle = this.Handle; // Force creation of control's handle because for databound grids, handle creation wipes out and recreates the columns/rows. // Note: Even none-resizable row can programmatically be resized. DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); - int height, minimumHeight; - dataGridViewRow.GetHeightInfo(rowIndex, out height, out minimumHeight); + dataGridViewRow.GetHeightInfo(rowIndex, out int height, out int minimumHeight); int preferredThickness = dataGridViewRow.GetPreferredHeight(rowIndex, autoSizeRowMode, fixedWidth); if (preferredThickness < minimumHeight) { @@ -3876,7 +3874,6 @@ private DataGridViewDataErrorEventArgs CommitEdit(ref DataGridViewCell dataGridV } } - Exception exception; object formattedValue; if (editingControl != null) @@ -3889,7 +3886,7 @@ private DataGridViewDataErrorEventArgs CommitEdit(ref DataGridViewCell dataGridV formattedValue = ((IDataGridViewEditingCell)CurrentCellInternal).GetEditingCellFormattedValue(context); } - if (!PushFormattedValue(ref dataGridViewCurrentCell, formattedValue, out exception)) + if (!PushFormattedValue(ref dataGridViewCurrentCell, formattedValue, out Exception exception)) { if (ptCurrentCell.X == -1) { @@ -6050,8 +6047,7 @@ private void EndColumnRelocation(MouseEventArgs e, HitTestInfo hti) Invalidate(Rectangle.Union(layout.TopLeftHeader, layout.ColumnHeaders)); } - int previousColumnIndex; - if (ColumnRelocationTarget(e, hti, out previousColumnIndex)) + if (ColumnRelocationTarget(e, hti, out int previousColumnIndex)) { if (previousColumnIndex == -1) { @@ -6292,8 +6288,7 @@ private void EndRowResize(MouseEventArgs e) } DataGridViewRow dataGridViewRow = Rows.SharedRow(trackRow); - int height, minimumHeight; - dataGridViewRow.GetHeightInfo(trackRow, out height, out minimumHeight); + dataGridViewRow.GetHeightInfo(trackRow, out int height, out int minimumHeight); int y = Math.Min(e.Y + mouseBarOffset, layout.Data.Bottom - 1); int delta = y - (GetRowYFromIndex(trackRow) + height) + 1; if (trackRowAnchor != y && delta != 0) @@ -7419,8 +7414,7 @@ public virtual DataObject GetClipboardContent() } if (string.Equals(format, DataFormats.Html, StringComparison.OrdinalIgnoreCase)) { - System.IO.MemoryStream utf8Stream = null; - GetClipboardContentForHtml(sbContent, out utf8Stream); + GetClipboardContentForHtml(sbContent, out IO.MemoryStream utf8Stream); dataObject.SetData(format, false /*autoConvert*/, utf8Stream); } else @@ -7691,8 +7685,7 @@ public virtual DataObject GetClipboardContent() } if (string.Equals(format, DataFormats.Html, StringComparison.OrdinalIgnoreCase)) { - System.IO.MemoryStream utf8Stream = null; - GetClipboardContentForHtml(sbContent, out utf8Stream); + GetClipboardContentForHtml(sbContent, out IO.MemoryStream utf8Stream); dataObject.SetData(format, false /*autoConvert*/, utf8Stream); } else @@ -8134,8 +8127,7 @@ public virtual DataObject GetClipboardContent() } if (string.Equals(format, DataFormats.Html, StringComparison.OrdinalIgnoreCase)) { - System.IO.MemoryStream utf8Stream = null; - GetClipboardContentForHtml(sbContent, out utf8Stream); + GetClipboardContentForHtml(sbContent, out IO.MemoryStream utf8Stream); dataObject.SetData(format, false /*autoConvert*/, utf8Stream); } else @@ -9372,8 +9364,8 @@ public HitTestInfo HitTest(int x, int y) // check for column resize / insertion if (layout.ColumnHeaders.Contains(x, y)) { - int xColumnLeftEdge; // this is actually the right edge in RTL mode - hti.col = GetColumnIndexFromX(x, out xColumnLeftEdge); + // this is actually the right edge in RTL mode + hti.col = GetColumnIndexFromX(x, out int xColumnLeftEdge); if (hti.col < 0) { return HitTestInfo.Nowhere; @@ -9473,8 +9465,7 @@ public HitTestInfo HitTest(int x, int y) // check for row resize if (layout.RowHeaders.Contains(x, y)) { - int yRowTopEdge; - hti.row = GetRowIndexFromY(y, out yRowTopEdge); + hti.row = GetRowIndexFromY(y, out int yRowTopEdge); if (hti.row < 0) { return HitTestInfo.Nowhere; @@ -9549,9 +9540,8 @@ public HitTestInfo HitTest(int x, int y) if (layout.Data.Contains(x, y)) { - int xColumnLeftEdge, yRowTopEdge; - hti.col = GetColumnIndexFromX(x, out xColumnLeftEdge); - hti.row = GetRowIndexFromY(y, out yRowTopEdge); + hti.col = GetColumnIndexFromX(x, out int xColumnLeftEdge); + hti.row = GetRowIndexFromY(y, out int yRowTopEdge); if (hti.col < 0 || hti.row < 0) { return HitTestInfo.Nowhere; @@ -9718,8 +9708,8 @@ private void HorizScrollTimerHandler() Point ptMouse = PointToClient(Control.MousePosition); HitTestInfo hti = HitTest(ptMouse.X, ptMouse.Y); - int xOffset, yOffset, mouseX = ptMouse.X, mouseY = ptMouse.Y; - if (GetOutOfBoundCorrectedHitTestInfo(ref hti, ref mouseX, ref mouseY, out xOffset, out yOffset)) + int mouseX = ptMouse.X, mouseY = ptMouse.Y; + if (GetOutOfBoundCorrectedHitTestInfo(ref hti, ref mouseX, ref mouseY, out int xOffset, out int yOffset)) { if (xOffset != 0) { @@ -16529,8 +16519,8 @@ protected override void OnMouseMove(MouseEventArgs e) dataGridViewOper[DATAGRIDVIEWOPER_trackRowSelect] || dataGridViewOper[DATAGRIDVIEWOPER_trackCellSelect]) { - int xOffset, yOffset, mouseX = e.X, mouseY = e.Y; - if (GetOutOfBoundCorrectedHitTestInfo(ref hti, ref mouseX, ref mouseY, out xOffset, out yOffset)) + int mouseX = e.X, mouseY = e.Y; + if (GetOutOfBoundCorrectedHitTestInfo(ref hti, ref mouseX, ref mouseY, out int xOffset, out int yOffset)) { if (xOffset == 0) { @@ -20448,8 +20438,7 @@ protected override bool ProcessDialogKey(Keys keyData) protected bool ProcessDownKey(Keys keyData) { - bool moved; - return ProcessDownKeyInternal(keyData, out moved); + return ProcessDownKeyInternal(keyData, out bool moved); } private bool ProcessDownKeyInternal(Keys keyData, out bool moved) @@ -25720,8 +25709,7 @@ private void RestoreRowsCachedThickness() rowIndex = Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible)) { DataGridViewRow dataGridViewRow = Rows.SharedRow(rowIndex); - int height, minimumHeight; - dataGridViewRow.GetHeightInfo(rowIndex, out height, out minimumHeight); + dataGridViewRow.GetHeightInfo(rowIndex, out int height, out int minimumHeight); if (height != dataGridViewRow.CachedThickness && !OnRowHeightInfoPushed(rowIndex, dataGridViewRow.CachedThickness, minimumHeight)) { @@ -29406,9 +29394,9 @@ private void VertScrollTimerHandler() Point ptMouse = PointToClient(Control.MousePosition); HitTestInfo hti = HitTest(ptMouse.X, ptMouse.Y); - int xOffset, yOffset, mouseX = ptMouse.X, mouseY = ptMouse.Y; + int mouseX = ptMouse.X, mouseY = ptMouse.Y; - if (GetOutOfBoundCorrectedHitTestInfo(ref hti, ref mouseX, ref mouseY, out xOffset, out yOffset)) + if (GetOutOfBoundCorrectedHitTestInfo(ref hti, ref mouseX, ref mouseY, out int xOffset, out int yOffset)) { if (yOffset != 0) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowHeaderCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowHeaderCell.cs index 25319a1bb7d..eca99043652 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowHeaderCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowHeaderCell.cs @@ -297,11 +297,8 @@ protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCel // we mimic a lot of the painting code // get the borders - DataGridViewAdvancedBorderStyle dgvabsEffective; - DataGridViewElementStates cellState; - Rectangle cellBounds; - ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds); + ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds); Rectangle contentBounds = PaintPrivate(graphics, cellBounds, @@ -352,11 +349,8 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC return Rectangle.Empty; } - DataGridViewAdvancedBorderStyle dgvabsEffective; - DataGridViewElementStates cellState; - Rectangle cellBounds; - ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds); + ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds); object value = GetValue(rowIndex); object formattedValue = GetFormattedValue(value, rowIndex, ref cellStyle, null, null, DataGridViewDataErrorContexts.Formatting); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxCell.cs index 66a31a5c8e0..ba18ddaf512 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxCell.cs @@ -86,8 +86,7 @@ public virtual int MaxInputLength { get { - bool found; - int maxInputLength = Properties.GetInteger(PropTextBoxCellMaxInputLength, out found); + int maxInputLength = Properties.GetInteger(PropTextBoxCellMaxInputLength, out bool found); if (found) { return maxInputLength; @@ -301,11 +300,8 @@ protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCel object value = GetValue(rowIndex); object formattedValue = GetFormattedValue(value, rowIndex, ref cellStyle, null, null, DataGridViewDataErrorContexts.Formatting); - DataGridViewAdvancedBorderStyle dgvabsEffective; - DataGridViewElementStates cellState; - Rectangle cellBounds; - ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds); + ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds); Rectangle textBounds = PaintPrivate(graphics, cellBounds, @@ -357,11 +353,8 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC return Rectangle.Empty; } - DataGridViewAdvancedBorderStyle dgvabsEffective; - DataGridViewElementStates cellState; - Rectangle cellBounds; - ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds); + ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds); Rectangle errorBounds = PaintPrivate(graphics, cellBounds, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopLeftHeaderCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopLeftHeaderCell.cs index 24313bfb874..d12f55fa811 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopLeftHeaderCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTopLeftHeaderCell.cs @@ -55,11 +55,8 @@ protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCel // we mimic a lot of the painting code // get the borders - DataGridViewAdvancedBorderStyle dgvabsEffective; - DataGridViewElementStates cellState; - Rectangle cellBounds; - ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds); + ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds); Rectangle contentBounds = PaintPrivate(graphics, cellBounds, @@ -112,11 +109,8 @@ protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewC throw new ArgumentNullException(nameof(cellStyle)); } - DataGridViewAdvancedBorderStyle dgvabsEffective; - DataGridViewElementStates cellState; - Rectangle cellBounds; - ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds); + ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds); Rectangle errorBounds = PaintPrivate(graphics, cellBounds, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs index 8951ac3e366..2b8effdfad2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs @@ -1650,8 +1650,7 @@ private object ReadObjectFromHandle(IntPtr handle, bool restrictDeserialization) { object value = null; - bool isSerializedObject; - Stream stream = ReadByteStreamFromHandle(handle, out isSerializedObject); + Stream stream = ReadByteStreamFromHandle(handle, out bool isSerializedObject); if (isSerializedObject) { @@ -1758,8 +1757,7 @@ private unsafe string ReadHtmlFromHandle(IntPtr handle) //=------------------------------------------------------------------------= public virtual object GetData(string format, bool autoConvert) { - bool done = false; - object baseVar = GetDataFromBoundOleDataObject(format, out done); + object baseVar = GetDataFromBoundOleDataObject(format, out bool done); object original = baseVar; if (!done && autoConvert && (baseVar == null || baseVar is MemoryStream)) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FileDialog_Vista.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FileDialog_Vista.cs index f41e7cd3b50..6ebd71a4b6a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FileDialog_Vista.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FileDialog_Vista.cs @@ -129,8 +129,7 @@ private bool HandleVistaFileOk(FileDialogNative.IFileDialog dialog) try { Thread.MemoryBarrier(); - uint filterIndexTemp; - dialog.GetFileTypeIndex(out filterIndexTemp); + dialog.GetFileTypeIndex(out uint filterIndexTemp); FilterIndex = unchecked((int)filterIndexTemp); _fileNames = ProcessVistaFiles(dialog); if (ProcessFileNames()) @@ -280,8 +279,7 @@ internal static FileDialogNative.IShellItem GetShellItemForPath(string path) private protected static string GetFilePathFromShellItem(FileDialogNative.IShellItem item) { - string filename; - item.GetDisplayName(FileDialogNative.SIGDN.SIGDN_DESKTOPABSOLUTEPARSING, out filename); + item.GetDisplayName(FileDialogNative.SIGDN.SIGDN_DESKTOPABSOLUTEPARSING, out string filename); return filename; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FolderBrowserDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FolderBrowserDialog.cs index 1cb9e21d610..a54b7b4ae41 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FolderBrowserDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FolderBrowserDialog.cs @@ -229,9 +229,8 @@ private void GetResult(FileDialogNative.IFileDialog dialog) private unsafe bool RunDialogOld(IntPtr hWndOwner) { - CoTaskMemSafeHandle listHandle; - Interop.Shell32.SHGetSpecialFolderLocation(hWndOwner, (int)_rootFolder, out listHandle); + Interop.Shell32.SHGetSpecialFolderLocation(hWndOwner, (int)_rootFolder, out CoTaskMemSafeHandle listHandle); if (listHandle.IsInvalid) { Interop.Shell32.SHGetSpecialFolderLocation(hWndOwner, (int)Environment.SpecialFolder.Desktop, out listHandle); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs index 457d3d44f13..baf5c618618 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs @@ -337,8 +337,7 @@ public ImageListStreamer ImageStream DestroyHandle(); originals = null; nativeImageList = new NativeImageList(SafeNativeMethods.ImageList_Duplicate(new HandleRef(himl, himl.Handle))); - int x, y; - if (SafeNativeMethods.ImageList_GetIconSize(new HandleRef(this, nativeImageList.Handle), out x, out y)) + if (SafeNativeMethods.ImageList_GetIconSize(new HandleRef(this, nativeImageList.Handle), out int x, out int y)) { imageSize = new Size(x, y); } @@ -606,8 +605,7 @@ private void CreateHandle() } else { - bool ownsBitmap = false; - Bitmap bitmapValue = CreateBitmap(original, out ownsBitmap); + Bitmap bitmapValue = CreateBitmap(original, out bool ownsBitmap); AddToHandle(original, bitmapValue); if (ownsBitmap) bitmapValue.Dispose(); @@ -1444,8 +1442,7 @@ private int Add(Original original, ImageInfo imageInfo) if (owner.HandleCreated) { - bool ownsBitmap = false; - Bitmap bitmapValue = owner.CreateBitmap(original, out ownsBitmap); + Bitmap bitmapValue = owner.CreateBitmap(original, out bool ownsBitmap); index = owner.AddToHandle(original, bitmapValue); if (ownsBitmap) bitmapValue.Dispose(); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/KeyboardToolTipStateMachine.cs b/src/System.Windows.Forms/src/System/Windows/Forms/KeyboardToolTipStateMachine.cs index 6d85a3b6980..850584311ab 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/KeyboardToolTipStateMachine.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/KeyboardToolTipStateMachine.cs @@ -155,8 +155,7 @@ internal IKeyboardToolTip LastFocusedTool { get { - IKeyboardToolTip tool; - if (lastFocusedTool.TryGetTarget(out tool)) + if (lastFocusedTool.TryGetTarget(out IKeyboardToolTip tool)) { return tool; } @@ -382,9 +381,8 @@ public ToolTip this[IKeyboardToolTip tool] { get { - WeakReference toolTipReference; ToolTip toolTip = null; - if (table.TryGetValue(tool, out toolTipReference)) + if (table.TryGetValue(tool, out WeakReference toolTipReference)) { if (!toolTipReference.TryGetTarget(out toolTip)) { @@ -397,8 +395,7 @@ public ToolTip this[IKeyboardToolTip tool] set { - WeakReference toolTipReference; - if (table.TryGetValue(tool, out toolTipReference)) + if (table.TryGetValue(tool, out WeakReference toolTipReference)) { toolTipReference.SetTarget(value); } @@ -411,11 +408,9 @@ public ToolTip this[IKeyboardToolTip tool] public void Remove(IKeyboardToolTip tool, ToolTip toolTip) { - WeakReference toolTipReference; - ToolTip existingToolTip; - if (table.TryGetValue(tool, out toolTipReference)) + if (table.TryGetValue(tool, out WeakReference toolTipReference)) { - if (toolTipReference.TryGetTarget(out existingToolTip)) + if (toolTipReference.TryGetTarget(out ToolTip existingToolTip)) { if (existingToolTip == toolTip) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs index 2cdb99ff647..8cb907fe041 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs @@ -598,8 +598,7 @@ internal LabelImageIndexer ImageIndexer { get { - bool found; - LabelImageIndexer imageIndexer = Properties.GetObject(PropImageIndex, out found) as LabelImageIndexer; + LabelImageIndexer imageIndexer = Properties.GetObject(PropImageIndex, out bool found) as LabelImageIndexer; // Demand create the ImageIndexer property if ((imageIndexer == null) || (!found)) @@ -688,8 +687,7 @@ public ContentAlignment ImageAlign { get { - bool found; - int imageAlign = Properties.GetInteger(PropImageAlign, out found); + int imageAlign = Properties.GetInteger(PropImageAlign, out bool found); if (found) { return (ContentAlignment)imageAlign; @@ -911,8 +909,7 @@ public virtual ContentAlignment TextAlign { get { - bool found; - int textAlign = Properties.GetInteger(PropTextAlign, out found); + int textAlign = Properties.GetInteger(PropTextAlign, out bool found); if (found) { return (ContentAlignment)textAlign; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs index ed1534004db..5cba558f576 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs @@ -107,8 +107,7 @@ internal static bool GetAutoSize(IArrangedElement element) /// Instead the Element sets the Margin in its ctor. internal static Padding GetMargin(IArrangedElement element) { - bool found; - Padding padding = element.Properties.GetPadding(_marginProperty, out found); + Padding padding = element.Properties.GetPadding(_marginProperty, out bool found); if (found) { return padding; @@ -120,8 +119,7 @@ internal static Padding GetMargin(IArrangedElement element) /// Returns the maximum size for an element internal static Size GetMaximumSize(IArrangedElement element, Size defaultMaximumSize) { - bool found; - Size size = element.Properties.GetSize(_maximumSizeProperty, out found); + Size size = element.Properties.GetSize(_maximumSizeProperty, out bool found); if (found) { return size; @@ -134,8 +132,7 @@ internal static Size GetMaximumSize(IArrangedElement element, Size defaultMaximu /// Returns the minimum size for an element internal static Size GetMinimumSize(IArrangedElement element, Size defaultMinimumSize) { - bool found; - Size size = element.Properties.GetSize(_minimumSizeProperty, out found); + Size size = element.Properties.GetSize(_minimumSizeProperty, out bool found); if (found) { return size; @@ -152,8 +149,7 @@ internal static Size GetMinimumSize(IArrangedElement element, Size defaultMinimu /// layout by modifying what the control reports for preferred size. internal static Padding GetPadding(IArrangedElement element, Padding defaultPadding) { - bool found; - Padding padding = element.Properties.GetPadding(_paddingProperty, out found); + Padding padding = element.Properties.GetPadding(_paddingProperty, out bool found); if (found) { return padding; @@ -165,8 +161,7 @@ internal static Padding GetPadding(IArrangedElement element, Padding defaultPadd /// Returns the last size manually set into the element. See UpdateSpecifiedBounds. internal static Rectangle GetSpecifiedBounds(IArrangedElement element) { - bool found; - Rectangle rectangle = element.Properties.GetRectangle(_specifiedBoundsProperty, out found); + Rectangle rectangle = element.Properties.GetRectangle(_specifiedBoundsProperty, out bool found); if (found && rectangle != LayoutUtils.MaxRectangle) { return rectangle; @@ -383,8 +378,7 @@ internal static void xClearAllPreferredSizeCaches(IArrangedElement start) /// for a constraining value of LayoutUtils.MaxValue (or Size.Empty too). internal static Size xGetPreferredSizeCache(IArrangedElement element) { - bool found; - Size size = element.Properties.GetSize(_preferredSizeCacheProperty, out found); + Size size = element.Properties.GetSize(_preferredSizeCacheProperty, out bool found); if (found && (size != LayoutUtils.InvalidSize)) { return size; @@ -685,8 +679,7 @@ internal static void SetFlowBreak(IArrangedElement element, bool value) /// of how it lays out. Example is TLP in RTL and LTR. internal static Size GetLayoutBounds(IArrangedElement element) { - bool found; - Size size = element.Properties.GetSize(_layoutBoundsProperty, out found); + Size size = element.Properties.GetSize(_layoutBoundsProperty, out bool found); if (found) { return size; @@ -716,8 +709,7 @@ internal static void SetLayoutBounds(IArrangedElement element, Size value) /// Returns whether we have layout bounds stored for this element. internal static bool HasLayoutBounds(IArrangedElement element) { - bool found; - element.Properties.GetSize(_layoutBoundsProperty, out found); + element.Properties.GetSize(_layoutBoundsProperty, out bool found); return found; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DockAndAnchorLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DockAndAnchorLayout.cs index 692ed090f20..2e12bc8f58f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DockAndAnchorLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DockAndAnchorLayout.cs @@ -523,8 +523,8 @@ private static Size xGetDockedSize(IArrangedElement element, Size remainingSize, internal override bool LayoutCore(IArrangedElement container, LayoutEventArgs args) { - Size garbage; // PreferredSize is garbage if we are not measuring. - return xLayout(container, /* measureOnly = */ false, out garbage); + // PreferredSize is garbage if we are not measuring. + return xLayout(container, /* measureOnly = */ false, out Size garbage); } // Note: PreferredSize is only computed if measureOnly = true. @@ -944,9 +944,8 @@ internal override Size GetPreferredSize(IArrangedElement container, Size propose Debug.Assert(!HasCachedBounds(container), "Do not call this method with an active cached bounds list."); - Size prefSize; - xLayout(container, /* measureOnly = */ true, out prefSize); + xLayout(container, /* measureOnly = */ true, out Size prefSize); /* container.Bounds = prefSize; xLayout(container, false, out prefSize); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs index 2574b19cf83..c2e327b8db5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs @@ -124,11 +124,10 @@ private Size xLayout(IArrangedElement container, Rectangle displayRect, bool mea for (int i = 0; i < container.Children.Count;) { - int breakIndex; Size rowSize = Size.Empty; Rectangle measureBounds = new Rectangle(displayRect.X, displayRect.Y, displayRect.Width, displayRect.Height - layoutSize.Height); - rowSize = MeasureRow(containerProxy, elementProxy, i, measureBounds, out breakIndex); + rowSize = MeasureRow(containerProxy, elementProxy, i, measureBounds, out int breakIndex); // if we are not wrapping contents, then the breakIndex (as set in MeasureRow) @@ -161,8 +160,7 @@ private Size xLayout(IArrangedElement container, Rectangle displayRect, bool mea // for an explaination of the elementProxy parameter. private void LayoutRow(ContainerProxy containerProxy, ElementProxy elementProxy, int startIndex, int endIndex, Rectangle rowBounds) { - int dummy; - Size outSize = xLayoutRow(containerProxy, elementProxy, startIndex, endIndex, rowBounds, /* breakIndex = */ out dummy, /* measureOnly = */ false); + Size outSize = xLayoutRow(containerProxy, elementProxy, startIndex, endIndex, rowBounds, /* breakIndex = */ out int dummy, /* measureOnly = */ false); Debug.Assert(dummy == endIndex, "EndIndex / BreakIndex mismatch."); } 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 2232a835d19..94481abba9a 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 @@ -261,9 +261,8 @@ internal override Size GetPreferredSize(IArrangedElement container, Size propose // if the table layout is nested, this becomes pretty nasty, as we dont cache row, column // assignments in preferred size. // GPS(0,1) GPS(1,0) should return same as GPS(0,0)- if that's already cached return it. - bool isCacheValid = false; float oldWidth = -1f; - Size prefSize = containerInfo.GetCachedPreferredSize(proposedConstraints, out isCacheValid); + Size prefSize = containerInfo.GetCachedPreferredSize(proposedConstraints, out bool isCacheValid); if (isCacheValid) { return prefSize; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs index ab59641b6c3..d340db23d57 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs @@ -1277,9 +1277,8 @@ public override string Text { if (RejectInputOnFirstFailure) { - MaskedTextResultHint hint; string oldText = TextOutput; - if (maskedTextProvider.Set(value, out caretTestPos, out hint)) + if (maskedTextProvider.Set(value, out caretTestPos, out MaskedTextResultHint hint)) { //if( hint == MaskedTextResultHint.Success || hint == MaskedTextResultHint.SideEffect ) if (TextOutput != oldText) @@ -1663,12 +1662,10 @@ private void Delete(Keys keyCode, int startPosition, int selectionLen) } } - int tempPos; int endPos = selectionLen > 0 ? startPosition + selectionLen - 1 : startPosition; - MaskedTextResultHint hint; string oldText = TextOutput; - if (maskedTextProvider.RemoveAt(startPosition, endPos, out tempPos, out hint)) + if (maskedTextProvider.RemoveAt(startPosition, endPos, out int tempPos, out MaskedTextResultHint hint)) { //if( hint == MaskedTextResultHint.Success || hint == MaskedTextResultHint.SideEffect) // Text was changed. if (TextOutput != oldText) @@ -1915,8 +1912,7 @@ private string GetSelectedText() { Debug.Assert(!flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); - int selStart, selLength; - base.GetSelectionStartAndLength(out selStart, out selLength); + base.GetSelectionStartAndLength(out int selStart, out int selLength); if (selLength == 0) { @@ -2034,10 +2030,8 @@ protected override void OnKeyDown(KeyEventArgs e) { if (!ReadOnly) { - int selectionLen; - int startPosition; - base.GetSelectionStartAndLength(out startPosition, out selectionLen); + base.GetSelectionStartAndLength(out int startPosition, out int selectionLen); switch (e.Modifiers) { @@ -2135,15 +2129,12 @@ protected override void OnKeyPress(KeyPressEventArgs e) { // At this point the character needs to be processed ... - MaskedTextResultHint hint; - int selectionStart; - int selectionLen; - base.GetSelectionStartAndLength(out selectionStart, out selectionLen); + base.GetSelectionStartAndLength(out int selectionStart, out int selectionLen); string oldText = TextOutput; - if (PlaceChar(e.KeyChar, selectionStart, selectionLen, IsOverwriteMode, out hint)) + if (PlaceChar(e.KeyChar, selectionStart, selectionLen, IsOverwriteMode, out MaskedTextResultHint hint)) { //if( hint == MaskedTextResultHint.Success || hint == MaskedTextResultHint.SideEffect ) if (TextOutput != oldText) @@ -2444,8 +2435,7 @@ private void PasteInt(string text) { Debug.Assert(!flagState[IS_NULL_MASK], "This method must be called when a Mask is provided."); - int selStart, selLength; - base.GetSelectionStartAndLength(out selStart, out selLength); + base.GetSelectionStartAndLength(out int selStart, out int selLength); if (string.IsNullOrEmpty(text)) { @@ -2902,8 +2892,7 @@ private bool WmClear() if (!ReadOnly) { - int selStart, selLength; - base.GetSelectionStartAndLength(out selStart, out selLength); + base.GetSelectionStartAndLength(out int selStart, out int selLength); Delete(Keys.Delete, selStart, selLength); return true; } @@ -3012,8 +3001,7 @@ private bool WmImeStartComposition() // Position the composition window in a valid place. - int startPosition, selectionLen; - base.GetSelectionStartAndLength(out startPosition, out selectionLen); + base.GetSelectionStartAndLength(out int startPosition, out int selectionLen); int startEditPos = maskedTextProvider.FindEditPositionFrom(startPosition, forward); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs index 11cc5cbfe7e..996ffd455ab 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs @@ -171,21 +171,19 @@ internal void ForceExitMessageLoop() // when control finally reaches us. if (UnsafeNativeMethods.IsWindow(new HandleRef(null, handle))) { - int lpdwProcessId; //unused - int id = SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(null, handle), out lpdwProcessId); + //unused + int id = SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(null, handle), out int lpdwProcessId); Application.ThreadContext ctx = Application.ThreadContext.FromId(id); IntPtr threadHandle = (ctx == null ? IntPtr.Zero : ctx.GetHandle()); if (threadHandle != IntPtr.Zero) { - int exitCode = 0; - SafeNativeMethods.GetExitCodeThread(new HandleRef(null, threadHandle), out exitCode); + SafeNativeMethods.GetExitCodeThread(new HandleRef(null, threadHandle), out int exitCode); if (!AppDomain.CurrentDomain.IsFinalizingForUnload() && exitCode == NativeMethods.STATUS_PENDING) { - IntPtr result; if (UnsafeNativeMethods.SendMessageTimeout(new HandleRef(null, handle), NativeMethods.WM_UIUNSUBCLASS, IntPtr.Zero, IntPtr.Zero, - UnsafeNativeMethods.SMTO_ABORTIFHUNG, 100, out result) == IntPtr.Zero) + UnsafeNativeMethods.SMTO_ABORTIFHUNG, 100, out IntPtr result) == IntPtr.Zero) { //Debug.Fail("unable to ping HWND:" + handle.ToString() + " during finalization"); @@ -382,11 +380,9 @@ private static void AddWindowToTable(IntPtr handle, NativeWindow window) // ...same for the application anyHandleCreatedInApp = true; - uint seed; - uint incr; // Assume we only have one thread writing concurrently. Modify // buckets to contain new data, as long as we insert in the right order. - uint hashcode = InitHash(handle, hashBuckets.Length, out seed, out incr); + uint hashcode = InitHash(handle, hashBuckets.Length, out uint seed, out uint incr); int ntry = 0; int emptySlotNumber = -1; // We use the empty slot number to cache the first empty slot. We chose to reuse slots @@ -1048,10 +1044,8 @@ private static NativeWindow GetWindowFromTable(IntPtr handle) // Take a snapshot of buckets, in case another thread does a resize HandleBucket[] buckets = hashBuckets; - uint seed; - uint incr; int ntry = 0; - uint hashcode = InitHash(handle, buckets.Length, out seed, out incr); + uint hashcode = InitHash(handle, buckets.Length, out uint seed, out uint incr); HandleBucket b; do @@ -1077,8 +1071,7 @@ private static NativeWindow GetWindowFromTable(IntPtr handle) internal IntPtr GetHandleFromID(short id) { - IntPtr handle; - if (NativeWindow.hashForIdHandle == null || !NativeWindow.hashForIdHandle.TryGetValue(id, out handle)) + if (NativeWindow.hashForIdHandle == null || !NativeWindow.hashForIdHandle.TryGetValue(id, out IntPtr handle)) { handle = IntPtr.Zero; } @@ -1260,10 +1253,8 @@ private static void RemoveWindowFromTable(IntPtr handle, NativeWindow window) lock (internalSyncObject) { - uint seed; - uint incr; // Assuming only one concurrent writer, write directly into buckets. - uint hashcode = InitHash(handle, hashBuckets.Length, out seed, out incr); + uint hashcode = InitHash(handle, hashBuckets.Length, out uint seed, out uint incr); int ntry = 0; NativeWindow prevWindow = window.PreviousWindow; HandleBucket b; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/OpenFileDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/OpenFileDialog.cs index 6053f1971b9..b7d9fe0b801 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/OpenFileDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/OpenFileDialog.cs @@ -176,23 +176,19 @@ private protected override string[] ProcessVistaFiles(FileDialogNative.IFileDial FileDialogNative.IFileOpenDialog openDialog = (FileDialogNative.IFileOpenDialog)dialog; if (Multiselect) { - FileDialogNative.IShellItemArray results; - openDialog.GetResults(out results); - uint count; - results.GetCount(out count); + openDialog.GetResults(out FileDialogNative.IShellItemArray results); + results.GetCount(out uint count); string[] files = new string[count]; for (uint i = 0; i < count; ++i) { - FileDialogNative.IShellItem item; - results.GetItemAt(i, out item); + results.GetItemAt(i, out FileDialogNative.IShellItem item); files[unchecked((int)i)] = GetFilePathFromShellItem(item); } return files; } else { - FileDialogNative.IShellItem item; - openDialog.GetResult(out item); + openDialog.GetResult(out FileDialogNative.IShellItem item); return new string[] { GetFilePathFromShellItem(item) }; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs index cbff0fa3f0b..9243672a998 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs @@ -304,8 +304,7 @@ public override object GetEditor(Type editorBaseType) public override object GetValue(object component) { Debug.Assert(component is Array, "MergePropertyDescriptor::GetValue called with non-array value"); - bool temp; - return GetValue((Array)component, out temp); + return GetValue((Array)component, out bool temp); } public object GetValue(Array components, out bool allEqual) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs index c1f3753295e..7584fb03e9d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs @@ -7101,12 +7101,8 @@ public override Rectangle Bounds { get { - int left; - int top; - int width; - int height; var systemIAccessible = GetSystemIAccessibleInternal(); - systemIAccessible.accLocation(out left, out top, out width, out height, GetChildId()); + systemIAccessible.accLocation(out int left, out int top, out int width, out int height, GetChildId()); return new Rectangle(left, top, width, height); } } @@ -8264,8 +8260,7 @@ private bool ProcessMouseDown(IntPtr hWnd, int x, int y) Debug.Assert(thisProcessID != 0, "Didn't get our process id!"); // make sure the window is in our process - int pid; - SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(null, hWndAtPoint), out pid); + SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(null, hWndAtPoint), out int pid); // if this isn't our process, unhook the mouse. if (pid != thisProcessID) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyManager.cs index 85c92ccdd91..6cc699e5332 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyManager.cs @@ -122,8 +122,7 @@ public override void CancelCurrentEdit() public override void EndCurrentEdit() { - bool success; - PullData(out success); + PullData(out bool success); if (success) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs index 6d1dc9ecee4..175a46d59b2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs @@ -374,8 +374,7 @@ protected override CreateParams CreateParams if (versionInfo != null && !string.IsNullOrEmpty(versionInfo.ProductVersion)) { //Note: this only allows for one digit version - int parsedValue; - if (int.TryParse(versionInfo.ProductVersion[0].ToString(), out parsedValue)) + if (int.TryParse(versionInfo.ProductVersion[0].ToString(), out int parsedValue)) { richEditMajorVersion = parsedValue; } @@ -3369,9 +3368,8 @@ private void UpdateOleCallback() IntPtr punk = Marshal.GetIUnknownForObject(oleCallback); try { - IntPtr pRichEditOleCallback; Guid iidRichEditOleCallback = typeof(UnsafeNativeMethods.IRichEditOleCallback).GUID; - Marshal.QueryInterface(punk, ref iidRichEditOleCallback, out pRichEditOleCallback); + Marshal.QueryInterface(punk, ref iidRichEditOleCallback, out IntPtr pRichEditOleCallback); try { UnsafeNativeMethods.SendCallbackMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_SETOLECALLBACK, IntPtr.Zero, pRichEditOleCallback); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettingsTypeConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettingsTypeConverter.cs index 957382e537d..7e64917a989 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettingsTypeConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettingsTypeConverter.cs @@ -160,8 +160,7 @@ private int GetAttributeValue(XmlNode node, string attribute, int valueIfNotFoun string attributeValue = GetAttributeValue(node, attribute); if (!string.IsNullOrEmpty(attributeValue)) { - int result; - if (int.TryParse(attributeValue, out result)) + if (int.TryParse(attributeValue, out int result)) { return result; } @@ -250,8 +249,7 @@ private void ParseStyles(TableLayoutSettings settings, XmlNodeList controlXmlFra nextIndex++; } string floatString = floatStringBuilder.ToString(); - float width; - if (!float.TryParse(floatString, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out width)) + if (!float.TryParse(floatString, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out float width)) { width = 0F; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxBase.cs index a4a9acde91a..a319a60e100 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxBase.cs @@ -1125,8 +1125,7 @@ public virtual string SelectedText { get { - int selStart, selLength; - GetSelectionStartAndLength(out selStart, out selLength); + GetSelectionStartAndLength(out int selStart, out int selLength); return Text.Substring(selStart, selLength); } set @@ -1188,9 +1187,8 @@ public virtual int SelectionLength { get { - int start, length; - GetSelectionStartAndLength(out start, out length); + GetSelectionStartAndLength(out int start, out int length); return length; } @@ -1202,8 +1200,7 @@ public virtual int SelectionLength throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(SelectionLength), value)); } - int selStart, selLength; - GetSelectionStartAndLength(out selStart, out selLength); + GetSelectionStartAndLength(out int selStart, out int selLength); if (value != selLength) { @@ -1229,9 +1226,8 @@ public int SelectionStart { get { - int selStart, selLength; - GetSelectionStartAndLength(out selStart, out selLength); + GetSelectionStartAndLength(out int selStart, out int selLength); return selStart; } @@ -1456,9 +1452,8 @@ public void AppendText(string text) { if (text.Length > 0) { - int selStart, selLength; - GetSelectionStartAndLength(out selStart, out selLength); + GetSelectionStartAndLength(out int selStart, out int selLength); try { @@ -1889,7 +1884,6 @@ public void ScrollToCaret() if (textDocument != null) { - int selStart, selLength; // When the user calls RichTextBox::ScrollToCaret we want the RichTextBox to show as // much text as possible. @@ -1899,7 +1893,7 @@ public void ScrollToCaret() // 3. If the first visible line is smaller than the start of the selection, then we are done: // The selection fits inside the RichTextBox display rectangle. // 4. Otherwise, scroll the selection to the top of the RichTextBox. - GetSelectionStartAndLength(out selStart, out selLength); + GetSelectionStartAndLength(out int selStart, out int selLength); int selStartLine = GetLineFromCharIndex(selStart); // 1. Scroll the RichTextBox all the way to the bottom @@ -2009,8 +2003,7 @@ internal virtual void SelectInternal(int start, int length, int textLen) //if our handle is created - send message... if (IsHandleCreated) { - int s, e; - AdjustSelectionStartAndEnd(start, length, out s, out e, textLen); + AdjustSelectionStartAndEnd(start, length, out int s, out int e, textLen); SendMessage(Interop.EditMessages.EM_SETSEL, s, e); // @@ -2124,8 +2117,7 @@ internal void SetSelectionOnHandle() if (textBoxFlags[setSelectionOnHandleCreated]) { textBoxFlags[setSelectionOnHandleCreated] = false; - int start, end; - AdjustSelectionStartAndEnd(selectionStart, selectionLength, out start, out end, -1); + AdjustSelectionStartAndEnd(selectionStart, selectionLength, out int start, out int end, -1); SendMessage(Interop.EditMessages.EM_SETSEL, start, end); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Timer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Timer.cs index 464f6b6e3ec..bfebdcc332a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Timer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Timer.cs @@ -243,8 +243,7 @@ private bool GetInvokeRequired(IntPtr hWnd) { if (hWnd != IntPtr.Zero) { - int pid; - int hwndThread = SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(this, hWnd), out pid); + int hwndThread = SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(this, hWnd), out int pid); return hwndThread != SafeNativeMethods.GetCurrentThreadId(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs index 4d20ff48670..a19bbab4ff5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs @@ -316,8 +316,7 @@ public AccessibleRole AccessibleRole get { - bool found; - int role = Properties.GetInteger(PropAccessibleRole, out found); + int role = Properties.GetInteger(PropAccessibleRole, out bool found); if (found) { return (AccessibleRole)role; @@ -1583,8 +1582,7 @@ public MergeAction MergeAction { get { - bool found; - int action = Properties.GetInteger(PropMergeAction, out found); + int action = Properties.GetInteger(PropMergeAction, out bool found); if (found) { return (MergeAction)action; @@ -1619,8 +1617,7 @@ public int MergeIndex { get { - bool found; - int index = Properties.GetInteger(PropMergeIndex, out found); + int index = Properties.GetInteger(PropMergeIndex, out bool found); if (found) { return index; @@ -2069,8 +2066,7 @@ public virtual RightToLeft RightToLeft { get { - bool found; - int rightToLeft = Properties.GetInteger(PropRightToLeft, out found); + int rightToLeft = Properties.GetInteger(PropRightToLeft, out bool found); if (!found) { rightToLeft = (int)RightToLeft.Inherit; @@ -3501,8 +3497,7 @@ protected virtual void OnOwnerChanged(EventArgs e) if (Owner != null) { // check if we need to fire OnRightToLeftChanged - bool found = false; - int rightToLeft = Properties.GetInteger(PropRightToLeft, out found); + int rightToLeft = Properties.GetInteger(PropRightToLeft, out bool found); if (!found) { rightToLeft = (int)RightToLeft.Inherit; @@ -3875,8 +3870,7 @@ internal virtual bool ShouldSerializeForeColor() [EditorBrowsable(EditorBrowsableState.Never)] internal virtual bool ShouldSerializeFont() { - bool found; - object font = Properties.GetObject(PropFont, out found); + object font = Properties.GetObject(PropFont, out bool found); return (found && font != null); } @@ -3934,8 +3928,7 @@ private bool ShouldSerializeImageIndex() [EditorBrowsable(EditorBrowsableState.Never)] internal virtual bool ShouldSerializeRightToLeft() { - bool found = false; - int rightToLeft = Properties.GetInteger(PropRightToLeft, out found); + int rightToLeft = Properties.GetInteger(PropRightToLeft, out bool found); if (!found) { return false; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs index 4c629bb7c98..ee308303495 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs @@ -1029,8 +1029,7 @@ private void ExitMenuModeCore() SafeNativeMethods.ShowCaret(NativeMethods.NullHandleRef); } - IKeyboardToolTip tool; - if (lastFocusedTool.TryGetTarget(out tool) && tool != null) + if (lastFocusedTool.TryGetTarget(out IKeyboardToolTip tool) && tool != null) { KeyboardToolTipStateMachine.Instance.NotifyAboutGotFocus(tool); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs index 7a280b9c20d..8991b2875ac 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs @@ -429,8 +429,7 @@ public CheckState CheckState { get { - bool found = false; - object checkState = Properties.GetInteger(PropCheckState, out found); + object checkState = Properties.GetInteger(PropCheckState, out bool found); return (found) ? (CheckState)checkState : CheckState.Unchecked; } @@ -511,8 +510,7 @@ public Keys ShortcutKeys { get { - bool found = false; - object shortcutKeys = Properties.GetInteger(PropShortcutKeys, out found); + object shortcutKeys = Properties.GetInteger(PropShortcutKeys, out bool found); return (found) ? (Keys)shortcutKeys : Keys.None; } set diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs index dac4902d916..a963394e4af 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs @@ -1028,8 +1028,7 @@ private void DestoyAllRegions() private void SetToolInfo(Control ctl, string caption) { - bool allocatedString; - NativeMethods.TOOLINFO_TOOLTIP tool = GetTOOLINFO(ctl, caption, out allocatedString); + NativeMethods.TOOLINFO_TOOLTIP tool = GetTOOLINFO(ctl, caption, out bool allocatedString); try { int ret = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_ADDTOOL, 0, tool); @@ -1599,8 +1598,7 @@ private void SetToolTipInternal(Control control, TipInfo info) if (exists && !empty && handlesCreated && !DesignMode) { - bool allocatedString; - NativeMethods.TOOLINFO_TOOLTIP toolInfo = GetTOOLINFO(control, info.Caption, out allocatedString); + NativeMethods.TOOLINFO_TOOLTIP toolInfo = GetTOOLINFO(control, info.Caption, out bool allocatedString); try { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_SETTOOLINFO, @@ -1909,8 +1907,7 @@ internal void ShowKeyboardToolTip(string text, IKeyboardToolTip tool, int durati SetTool(tool.GetOwnerWindow(), text, TipInfo.Type.Absolute, new Point(pointX, pointY)); // Then look for a better ToolTip location - Size bubbleSize; - if (TryGetBubbleSize(tool, toolRectangle, out bubbleSize)) + if (TryGetBubbleSize(tool, toolRectangle, out Size bubbleSize)) { Point optimalPoint = GetOptimalToolTipPosition(tool, toolRectangle, bubbleSize.Width, bubbleSize.Height); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs index f3cdb1ed64f..ecccf3f8c04 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs @@ -472,8 +472,7 @@ protected override void WndProc(ref Message m) // if (ActiveXState >= WebBrowserHelper.AXState.InPlaceActive) { - IntPtr hwndInPlaceObject; - if (NativeMethods.Succeeded(AXInPlaceObject.GetWindow(out hwndInPlaceObject))) + if (NativeMethods.Succeeded(AXInPlaceObject.GetWindow(out IntPtr hwndInPlaceObject))) { Application.ParkHandle(new HandleRef(AXInPlaceObject, hwndInPlaceObject)); } @@ -1017,8 +1016,7 @@ private void TransitionFromLoadedToRunning() { // // See if the ActiveX control returns OLEMISC_SETCLIENTSITEFIRST - int bits = 0; - int hr = axOleObject.GetMiscStatus(NativeMethods.ActiveX.DVASPECT_CONTENT, out bits); + int hr = axOleObject.GetMiscStatus(NativeMethods.ActiveX.DVASPECT_CONTENT, out int bits); if (NativeMethods.Succeeded(hr) && ((bits & NativeMethods.ActiveX.OLEMISC_SETCLIENTSITEFIRST) != 0)) { // diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs index 8f58260f74c..8f8d5382774 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs @@ -198,8 +198,7 @@ int UnsafeNativeMethods.IOleClientSite.ShowObject() { if (Host.ActiveXState >= WebBrowserHelper.AXState.InPlaceActive) { - IntPtr hwnd; - if (NativeMethods.Succeeded(Host.AXInPlaceObject.GetWindow(out hwnd))) + if (NativeMethods.Succeeded(Host.AXInPlaceObject.GetWindow(out IntPtr hwnd))) { if (Host.GetHandleNoCreate() != hwnd) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs b/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs index 2dec5ba2ec7..151183d8e4a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs @@ -71,8 +71,7 @@ internal ImeMode CachedImeMode // Get the ImeMode from the property store // - bool found; - ImeMode cachedImeMode = (ImeMode)Properties.GetInteger(PropImeMode, out found); + ImeMode cachedImeMode = (ImeMode)Properties.GetInteger(PropImeMode, out bool found); if (!found) { cachedImeMode = DefaultImeMode; @@ -178,8 +177,7 @@ internal int DisableImeModeChangedCount Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_DisableImeModeChangedCount()"); Debug.Indent(); - bool dummy; - int val = (int)Properties.GetInteger(PropDisableImeModeChangedCount, out dummy); + int val = (int)Properties.GetInteger(PropDisableImeModeChangedCount, out bool dummy); Debug.Assert(val >= 0, "Counter underflow."); Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Value: " + val); @@ -381,8 +379,7 @@ private bool LastCanEnableIme Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_LastCanEnableIme()"); Debug.Indent(); - bool valueFound; - int val = (int)Properties.GetInteger(PropLastCanEnableIme, out valueFound); + int val = (int)Properties.GetInteger(PropLastCanEnableIme, out bool valueFound); if (valueFound) { @@ -697,8 +694,7 @@ internal virtual bool ShouldSerializeImeMode() { // This method is for designer support. If the ImeMode has not been changed or it is the same as the // default value it should not be serialized. - bool found; - int imeMode = Properties.GetInteger(PropImeMode, out found); + int imeMode = Properties.GetInteger(PropImeMode, out bool found); return (found && imeMode != (int)DefaultImeMode); } From 06832ca99e492542ad13f173615d2582276bb7b2 Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Fri, 24 May 2019 12:08:58 -0700 Subject: [PATCH 15/27] remove all instances of IDE0011 warning - Add single line braces --- src/Common/src/FileDialog_Vista_Interop.cs | 3 + .../Interop.SHGetPathFromIDListLongPath.cs | 2 + src/Common/src/UnsafeNativeMethods.cs | 21 + src/Common/tests/CommonMemberDataAttribute.cs | 4 + src/Common/tests/CommonTestHelper.cs | 3 + .../src/AssertExtensions.cs | 28 + .../src/PlatformDetection.Windows.cs | 4 + .../src/Misc/ConfigurationOptions.cs | 2 + .../src/Misc/UnsafeNativeMethods.cs | 6 + .../Design/MultilineStringEditor.cs | 6 + .../Design/ObjectSelectorEditor.cs | 6 + .../src/System/Drawing/Design/ColorEditor.cs | 10 + .../src/System/Drawing/Design/CursorEditor.cs | 3 + .../Windows/Forms/Design/AnchorEditor.cs | 22 + .../Windows/Forms/Design/BorderSidesEditor.cs | 34 + .../System/Windows/Forms/Design/DockEditor.cs | 43 ++ .../Forms/Design/ShortcutKeysEditor.cs | 43 ++ .../ComponentModel/Design/CodeMarkers.cs | 10 + .../Design/ComponentDesigner.cs | 2 + .../Design/DesignerActionPanel.cs | 5 + .../ComponentModel/Design/DesignerHost.cs | 2 + .../ComponentModel/Design/ReferenceService.cs | 10 + .../ComponentModel/Design/SelectionService.cs | 5 + .../CodeDomComponentSerializationService.cs | 75 ++ .../Design/Serialization/CodeDomSerializer.cs | 16 + .../Serialization/CodeDomSerializerBase.cs | 50 ++ .../Design/Serialization/CodeMethodMap.cs | 41 + .../CollectionCodeDomSerializer.cs | 19 + .../DesignerSerializationManager.cs | 5 + .../ResourceCodeDomSerializer.cs | 6 + .../Serialization/TypeCodeDomSerializer.cs | 6 + .../src/System/Drawing/Design/ToolboxItem.cs | 18 + .../Forms/Design/Behavior/BehaviorService.cs | 2 + .../Forms/Design/Behavior/GlyphCollection.cs | 4 + .../Forms/Design/Behavior/ResizeBehavior.cs | 2 + .../System/Windows/Forms/Design/CommandSet.cs | 61 ++ .../Windows/Forms/Design/ComponentTray.cs | 29 + .../Windows/Forms/Design/DesignerActionUI.cs | 8 + .../Windows/Forms/Design/DesignerUtils.cs | 2 + .../Windows/Forms/Design/DocumentDesigner.cs | 2 + .../Forms/Design/FormDocumentDesigner.cs | 5 + .../Forms/Design/ParentControlDesigner.cs | 6 + .../Forms/Design/SelectionUIService.cs | 43 ++ .../Forms/Design/ToolStripItemDesigner.cs | 3 + .../Forms/Design/ToolStripMenuItemDesigner.cs | 5 + .../System/Windows/Forms/Design/UndoEngine.cs | 2 + .../src/Common/System/LocalAppContext.cs | 5 + .../src/System/Resources/ResXDataNode.cs | 5 + .../src/System/Resources/ResXFileRef.cs | 12 + .../System/Resources/ResXResourceWriter.cs | 7 + .../System/Windows/Forms/AccessibleObject.cs | 6 + .../src/System/Windows/Forms/Application.cs | 14 + .../src/System/Windows/Forms/AxHost.cs | 262 +++++++ .../System/Windows/Forms/BindingNavigator.cs | 16 + .../src/System/Windows/Forms/BindingSource.cs | 2 + .../src/System/Windows/Forms/Button.cs | 2 + .../Forms/ButtonInternal/ButtonBaseAdapter.cs | 2 + .../CheckableControlBaseAdapter.cs | 3 + .../src/System/Windows/Forms/CheckBox.cs | 4 + .../System/Windows/Forms/CheckedListBox.cs | 9 + .../src/System/Windows/Forms/ColorDialog.cs | 14 + .../src/System/Windows/Forms/ColumnHeader.cs | 5 + .../src/System/Windows/Forms/ComboBox.cs | 52 ++ .../src/System/Windows/Forms/Command.cs | 34 +- .../Windows/Forms/ComponentManagerBroker.cs | 31 + .../COM2Interop/COM2Properties.cs | 12 + .../COM2Interop/COM2PropertyDescriptor.cs | 16 + .../System/Windows/Forms/ContainerControl.cs | 40 + .../src/System/Windows/Forms/ContextMenu.cs | 4 + .../src/System/Windows/Forms/Control.cs | 302 +++++++- .../src/System/Windows/Forms/ControlPaint.cs | 74 +- .../System/Windows/Forms/CurrencyManager.cs | 73 ++ .../src/System/Windows/Forms/Cursor.cs | 4 + .../System/Windows/Forms/CursorConverter.cs | 2 + .../src/System/Windows/Forms/Cursors.cs | 84 +++ .../src/System/Windows/Forms/DataGrid.cs | 703 +++++++++++++++++- .../System/Windows/Forms/DataGridAddNewRow.cs | 10 + .../Windows/Forms/DataGridBoolColumn.cs | 22 + .../System/Windows/Forms/DataGridCaption.cs | 52 ++ .../Windows/Forms/DataGridColumnCollection.cs | 28 + ...DataGridDefaultColumnWidthTypeConverter.cs | 14 + .../Windows/Forms/DataGridParentRows.cs | 50 ++ .../Windows/Forms/DataGridRelationshipRow.cs | 115 ++- .../src/System/Windows/Forms/DataGridRow.cs | 40 + .../src/System/Windows/Forms/DataGridState.cs | 4 + .../src/System/Windows/Forms/DataGridTable.cs | 149 +++- .../Windows/Forms/DataGridTableCollection.cs | 28 + .../System/Windows/Forms/DataGridTextBox.cs | 48 ++ .../Windows/Forms/DataGridTextBoxColumn.cs | 34 +- .../System/Windows/Forms/DataGridToolTip.cs | 2 + .../System/Windows/Forms/DataGridViewCell.cs | 4 + .../Forms/DataGridViewColumnCollection.cs | 8 + .../src/System/Windows/Forms/DataObject.cs | 3 + .../Windows/Forms/DataStreamFromComStream.cs | 4 + .../System/Windows/Forms/DateTimePicker.cs | 15 + .../Forms/Design/ComponentEditorForm.cs | 26 + .../src/System/Windows/Forms/DomainUpDown.cs | 9 + .../src/System/Windows/Forms/ErrorProvider.cs | 32 + .../Windows/Forms/FlatButtonAppearance.cs | 2 + .../src/System/Windows/Forms/FontDialog.cs | 14 +- .../src/System/Windows/Forms/Form.cs | 100 +++ .../System/Windows/Forms/GroupBoxRenderer.cs | 14 + .../System/Windows/Forms/ImageKeyConverter.cs | 2 + .../src/System/Windows/Forms/ImageList.cs | 72 +- .../System/Windows/Forms/ImageListStreamer.cs | 2 + .../src/System/Windows/Forms/KeysConverter.cs | 3 + .../src/System/Windows/Forms/Label.cs | 9 + .../Windows/Forms/Layout/CommonProperties.cs | 11 + .../Forms/Layout/DockAndAnchorLayout.cs | 18 + .../Windows/Forms/Layout/LayoutUtils.cs | 6 + .../Windows/Forms/Layout/TableLayout.cs | 24 + .../src/System/Windows/Forms/LinkLabel.cs | 2 + .../System/Windows/Forms/ListBindingHelper.cs | 2 + .../src/System/Windows/Forms/ListBox.cs | 42 ++ .../src/System/Windows/Forms/ListView.cs | 210 +++++- .../src/System/Windows/Forms/MDIClient.cs | 9 + .../src/System/Windows/Forms/MainMenu.cs | 4 + .../src/System/Windows/Forms/Menu.cs | 46 ++ .../src/System/Windows/Forms/MenuStrip.cs | 4 + .../src/System/Windows/Forms/MonthCalendar.cs | 48 ++ .../src/System/Windows/Forms/NativeWindow.cs | 18 + .../src/System/Windows/Forms/NotifyIcon.cs | 19 + .../Windows/Forms/Printing/PageSetupDialog.cs | 27 + .../Windows/Forms/Printing/PrintDialog.cs | 46 ++ .../Forms/Printing/PrintPreviewControl.cs | 18 + .../Forms/Printing/PrintPreviewDialog.cs | 2 + .../src/System/Windows/Forms/ProgressBar.cs | 23 + .../src/System/Windows/Forms/PropertyGrid.cs | 23 + .../Forms/PropertyGridInternal/GridEntry.cs | 45 ++ .../Forms/PropertyGridInternal/HotCommands.cs | 4 + .../ImmutablePropertyDescriptorGridEntry.cs | 2 + .../MergePropertyDescriptor.cs | 2 + .../MultiPropertyDescriptorGridEntry.cs | 3 +- .../PropertyDescriptorGridEntry.cs | 4 + .../PropertyGridInternal/PropertyGridView.cs | 114 +++ .../src/System/Windows/Forms/RadioButton.cs | 5 + .../Windows/Forms/RelatedCurrencyManager.cs | 3 + .../Windows/Forms/RelatedPropertyManager.cs | 2 + .../src/System/Windows/Forms/RichTextBox.cs | 152 +++- .../System/Windows/Forms/ScrollableControl.cs | 9 + .../src/System/Windows/Forms/SendKeys.cs | 47 ++ .../System/Windows/Forms/SplitContainer.cs | 25 +- .../src/System/Windows/Forms/Splitter.cs | 50 ++ .../src/System/Windows/Forms/StatusBar.cs | 32 + .../System/Windows/Forms/StatusBarPanel.cs | 12 + .../src/System/Windows/Forms/StringSorter.cs | 30 + .../src/System/Windows/Forms/TabControl.cs | 89 ++- .../src/System/Windows/Forms/TabPage.cs | 2 + .../src/System/Windows/Forms/TextBoxBase.cs | 35 + .../Windows/Forms/ThreadExceptionDialog.cs | 14 + .../src/System/Windows/Forms/ToolBar.cs | 87 +++ .../src/System/Windows/Forms/ToolBarButton.cs | 47 ++ .../src/System/Windows/Forms/ToolStrip.cs | 35 +- .../System/Windows/Forms/ToolStripButton.cs | 4 + .../Windows/Forms/ToolStripContainer.cs | 2 + .../Windows/Forms/ToolStripContentPanel.cs | 5 +- .../Windows/Forms/ToolStripControlHost.cs | 2 + .../System/Windows/Forms/ToolStripDropDown.cs | 8 + .../Windows/Forms/ToolStripDropDownItem.cs | 8 + .../src/System/Windows/Forms/ToolStripItem.cs | 20 + .../System/Windows/Forms/ToolStripManager.cs | 7 + .../System/Windows/Forms/ToolStripMenuItem.cs | 4 + .../System/Windows/Forms/ToolStripPanel.cs | 3 +- .../System/Windows/Forms/ToolStripPanelRow.cs | 8 +- .../Windows/Forms/ToolStripSplitButton.cs | 5 +- .../Forms/ToolStripSplitStackLayout.cs | 2 + .../src/System/Windows/Forms/ToolTip.cs | 2 + .../src/System/Windows/Forms/TrackBar.cs | 15 + .../src/System/Windows/Forms/TreeNode.cs | 135 ++++ .../Windows/Forms/TreeNodeCollection.cs | 18 + .../src/System/Windows/Forms/TreeView.cs | 97 +++ .../src/System/Windows/Forms/Triangle.cs | 9 + .../src/System/Windows/Forms/UpDownBase.cs | 6 + .../src/System/Windows/Forms/UserControl.cs | 13 + .../System/Windows/Forms/WebBrowserBase.cs | 5 + .../Windows/Forms/WebBrowserContainer.cs | 14 + .../Windows/Forms/WebBrowserSiteBase.cs | 4 + .../src/System/Windows/Forms/control.ime.cs | 5 + .../src/System/Windows/Forms/formatter.cs | 3 +- .../src/misc/ImageListUtils.cs | 2 + .../src/misc/InvariantComparer.cs | 4 + 181 files changed, 5230 insertions(+), 30 deletions(-) diff --git a/src/Common/src/FileDialog_Vista_Interop.cs b/src/Common/src/FileDialog_Vista_Interop.cs index e9979ee7b46..d2995653f1e 100644 --- a/src/Common/src/FileDialog_Vista_Interop.cs +++ b/src/Common/src/FileDialog_Vista_Interop.cs @@ -437,7 +437,10 @@ internal static IShellItem CreateItemFromParsingName(string path) Guid guid = new Guid(IIDGuid.IShellItem); int hr = SHCreateItemFromParsingName(path, IntPtr.Zero, ref guid, out object item); if (hr != 0) + { throw new System.ComponentModel.Win32Exception(hr); + } + return (IShellItem)item; } } diff --git a/src/Common/src/Interop/Shell32/Interop.SHGetPathFromIDListLongPath.cs b/src/Common/src/Interop/Shell32/Interop.SHGetPathFromIDListLongPath.cs index f3d91119478..f4bfd67b313 100644 --- a/src/Common/src/Interop/Shell32/Interop.SHGetPathFromIDListLongPath.cs +++ b/src/Common/src/Interop/Shell32/Interop.SHGetPathFromIDListLongPath.cs @@ -68,7 +68,9 @@ public unsafe static bool SHGetPathFromIDListLongPath(IntPtr pidl, ref IntPtr ps // Try giving the API a larger buffer length = length * 2; if (length > Kernel32.MAX_UNICODESTRING_LEN) + { length = Kernel32.MAX_UNICODESTRING_LEN; + } pszPath = Marshal.ReAllocHGlobal(pszPath, (IntPtr)(length * sizeof(char))); } diff --git a/src/Common/src/UnsafeNativeMethods.cs b/src/Common/src/UnsafeNativeMethods.cs index 734d80040f1..42ecaae8a5d 100644 --- a/src/Common/src/UnsafeNativeMethods.cs +++ b/src/Common/src/UnsafeNativeMethods.cs @@ -6568,10 +6568,16 @@ public override string GetString() { int i = offset; while (i < buffer.Length && buffer[i] != 0) + { i++; + } + string result = new string(buffer, offset, i - offset); if (i < buffer.Length) + { i++; + } + offset = i; return result; } @@ -6588,7 +6594,9 @@ public override void PutString(string s) s.CopyTo(0, buffer, offset, count); offset += count; if (offset < buffer.Length) + { buffer[offset++] = (char)0; + } } } @@ -6609,10 +6617,14 @@ public ComStreamFromDataStream(Stream dataStream) private void ActualizeVirtualPosition() { if (virtualPosition == -1) + { return; + } if (virtualPosition > dataStream.Length) + { dataStream.SetLength(virtualPosition); + } dataStream.Position = virtualPosition; @@ -6637,7 +6649,10 @@ public long CopyTo(IStream pstm, long cb, long[] pcbRead) int bufsize = 4096; // one page IntPtr buffer = Marshal.AllocHGlobal(bufsize); if (buffer == IntPtr.Zero) + { throw new OutOfMemoryException(); + } + long written = 0; try { @@ -6645,10 +6660,16 @@ public long CopyTo(IStream pstm, long cb, long[] pcbRead) { int toRead = bufsize; if (written + toRead > cb) + { toRead = (int)(cb - written); + } + int read = Read(buffer, toRead); if (read == 0) + { break; + } + if (pstm.Write(buffer, read) != read) { throw EFail("Wrote an incorrect number of bytes"); diff --git a/src/Common/tests/CommonMemberDataAttribute.cs b/src/Common/tests/CommonMemberDataAttribute.cs index ae3e5abb249..471b13947ba 100644 --- a/src/Common/tests/CommonMemberDataAttribute.cs +++ b/src/Common/tests/CommonMemberDataAttribute.cs @@ -24,11 +24,15 @@ public CommonMemberDataAttribute(string memberName, params object[] parameters) protected override object[] ConvertDataItem(MethodInfo testMethod, object item) { if (item == null) + { return null; + } var array = item as object[]; if (array == null) + { throw new ArgumentException($"Property {MemberName} on {MemberType ?? testMethod.DeclaringType} yielded an item that is not an object[]"); + } return array; } diff --git a/src/Common/tests/CommonTestHelper.cs b/src/Common/tests/CommonTestHelper.cs index 8facde01930..88e0728b106 100644 --- a/src/Common/tests/CommonTestHelper.cs +++ b/src/Common/tests/CommonTestHelper.cs @@ -21,7 +21,10 @@ internal static TheoryData GetEnumTheoryData() where T : Enum { var data = new TheoryData(); foreach (T item in Enum.GetValues(typeof(T))) + { data.Add(item); + } + return data; } diff --git a/src/Common/tests/InternalUtilitiesForTests/src/AssertExtensions.cs b/src/Common/tests/InternalUtilitiesForTests/src/AssertExtensions.cs index 14c8476c84a..900e85bf842 100644 --- a/src/Common/tests/InternalUtilitiesForTests/src/AssertExtensions.cs +++ b/src/Common/tests/InternalUtilitiesForTests/src/AssertExtensions.cs @@ -36,7 +36,9 @@ public static void Throws(string netCoreParamName, string netFxParamName, Act netFxParamName : netCoreParamName; if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Native")) + { Assert.Equal(expectedParamName, exception.ParamName); + } } public static void Throws(string netCoreParamName, string netFxParamName, Func testCode) @@ -55,7 +57,9 @@ public static void Throws(string netCoreParamName, string netFxParamName, Fun netFxParamName : netCoreParamName; if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Native")) + { Assert.Equal(expectedParamName, exception.ParamName); + } } public static T Throws(string paramName, Action action) @@ -64,7 +68,9 @@ public static T Throws(string paramName, Action action) T exception = Assert.Throws(action); if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Native")) + { Assert.Equal(paramName, exception.ParamName); + } return exception; } @@ -83,7 +89,9 @@ public static T Throws(string paramName, Func testCode) T exception = Assert.Throws(testCode); if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Native")) + { Assert.Equal(paramName, exception.ParamName); + } return exception; } @@ -94,7 +102,9 @@ public static async Task ThrowsAsync(string paramName, Func testCode T exception = await Assert.ThrowsAsync(testCode); if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Native")) + { Assert.Equal(paramName, exception.ParamName); + } return exception; } @@ -154,7 +164,9 @@ private static void ThrowsAnyInternal(Action action, params Type[] exceptionType { Type exceptionType = e.GetType(); if (exceptionTypes.Any(t => t.Equals(exceptionType))) + { return; + } throw new XunitException($"Expected one of: ({string.Join(", ", exceptionTypes)}) -> Actual: ({e.GetType()})"); } @@ -193,9 +205,13 @@ public static void ThrowsIf(bool condition, Action action) private static string AddOptionalUserMessage(string message, string userMessage) { if (userMessage == null) + { return message; + } else + { return $"{message} {userMessage}"; + } } /// @@ -224,13 +240,17 @@ public static void Contains(string value, string substring) public static void GreaterThan(T actual, T greaterThan, string userMessage = null) where T : IComparable { if (actual == null) + { throw new XunitException( greaterThan == null ? AddOptionalUserMessage($"Expected: to be greater than .", userMessage) : AddOptionalUserMessage($"Expected: to be greater than {greaterThan}.", userMessage)); + } if (actual.CompareTo(greaterThan) <= 0) + { throw new XunitException(AddOptionalUserMessage($"Expected: {actual} to be greater than {greaterThan}", userMessage)); + } } /// @@ -254,7 +274,9 @@ public static void LessThan(T actual, T lessThan, string userMessage = null) } if (actual.CompareTo(lessThan) >= 0) + { throw new XunitException(AddOptionalUserMessage($"Expected: {actual} to be less than {lessThan}", userMessage)); + } } /// @@ -266,10 +288,14 @@ public static void LessThanOrEqualTo(T actual, T lessThanOrEqualTo, string us { // null, by definition is always less than or equal to if (actual == null) + { return; + } if (actual.CompareTo(lessThanOrEqualTo) > 0) + { throw new XunitException(AddOptionalUserMessage($"Expected: {actual} to be less than or equal to {lessThanOrEqualTo}", userMessage)); + } } /// @@ -295,7 +321,9 @@ public static void GreaterThanOrEqualTo(T actual, T greaterThanOrEqualTo, str } if (actual.CompareTo(greaterThanOrEqualTo) < 0) + { throw new XunitException(AddOptionalUserMessage($"Expected: {actual} to be greater than or equal to {greaterThanOrEqualTo}", userMessage)); + } } /// diff --git a/src/Common/tests/InternalUtilitiesForTests/src/PlatformDetection.Windows.cs b/src/Common/tests/InternalUtilitiesForTests/src/PlatformDetection.Windows.cs index cd60ec6a353..64d507ad599 100644 --- a/src/Common/tests/InternalUtilitiesForTests/src/PlatformDetection.Windows.cs +++ b/src/Common/tests/InternalUtilitiesForTests/src/PlatformDetection.Windows.cs @@ -112,7 +112,9 @@ public static bool IsInAppContainer get { if (s_isInAppContainer != -1) + { return s_isInAppContainer == 1; + } if (!IsWindows || IsWindows7) { @@ -168,7 +170,9 @@ public static bool IsWindowsAndElevated get { if (s_isWindowsElevated != -1) + { return s_isWindowsElevated == 1; + } if (!IsWindows || IsInAppContainer) { diff --git a/src/System.Windows.Forms.Design.Editors/src/Misc/ConfigurationOptions.cs b/src/System.Windows.Forms.Design.Editors/src/Misc/ConfigurationOptions.cs index dac4652b7fa..e1d7f09c28f 100644 --- a/src/System.Windows.Forms.Design.Editors/src/Misc/ConfigurationOptions.cs +++ b/src/System.Windows.Forms.Design.Editors/src/Misc/ConfigurationOptions.cs @@ -61,7 +61,9 @@ public static Version NetFrameworkVersion { var frameworkName = new FrameworkName(targetFrameworkName); if (string.Equals(frameworkName.Identifier, ".NETFramework")) + { netFrameworkVersion = frameworkName.Version; + } } } catch (Exception e) diff --git a/src/System.Windows.Forms.Design.Editors/src/Misc/UnsafeNativeMethods.cs b/src/System.Windows.Forms.Design.Editors/src/Misc/UnsafeNativeMethods.cs index 34825d73c48..6c08465d215 100644 --- a/src/System.Windows.Forms.Design.Editors/src/Misc/UnsafeNativeMethods.cs +++ b/src/System.Windows.Forms.Design.Editors/src/Misc/UnsafeNativeMethods.cs @@ -104,7 +104,10 @@ public static int ReleaseDC(HandleRef hWnd, HandleRef hDC) public static IntPtr GetWindowLong(HandleRef hWnd, int nIndex) { if (IntPtr.Size == 4) + { return GetWindowLong32(hWnd, nIndex); + } + return GetWindowLongPtr64(hWnd, nIndex); } @@ -128,7 +131,10 @@ public static IntPtr GetWindowLong(HandleRef hWnd, int nIndex) public static IntPtr SetWindowLong(HandleRef hWnd, int nIndex, HandleRef dwNewLong) { if (IntPtr.Size == 4) + { return SetWindowLongPtr32(hWnd, nIndex, dwNewLong); + } + return SetWindowLongPtr64(hWnd, nIndex, dwNewLong); } diff --git a/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/MultilineStringEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/MultilineStringEditor.cs index d7c4ae873de..7714ae96b7c 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/MultilineStringEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/MultilineStringEditor.cs @@ -307,7 +307,9 @@ public void ProcessSurrogateFonts(int start, int length) { string value = Text; if (value == null) + { return; + } int[] surrogates = StringInfo.ParseCombiningCharacters(value); if (surrogates.Length != value.Length) @@ -374,7 +376,9 @@ public override string Text } } else + { return ""; + } } set { @@ -583,7 +587,9 @@ public int GetContextMenu(short seltype, IntPtr lpoleobj, NativeMethods.CHARRANG }; ContextMenu cm = tb.ContextMenu; if (cm == null || _owner.ShortcutsEnabled == false) + { hmenu = IntPtr.Zero; + } else { hmenu = cm.Handle; diff --git a/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/ObjectSelectorEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/ObjectSelectorEditor.cs index 9c4ddd9f792..327a3064385 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/ObjectSelectorEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/ObjectSelectorEditor.cs @@ -107,9 +107,13 @@ public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext contex protected internal bool EqualsToValue(object value) { if (value == currValue) + { return true; + } else + { return false; + } } protected virtual void FillTreeWithData(Selector selector, ITypeDescriptorContext context, IServiceProvider provider) @@ -266,7 +270,9 @@ public bool SetSelection(object value, TreeNodeCollection nodes) int len = treeNodes.Length; if (len == 0) + { return false; + } for (int i = 0; i < len; i++) { diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/ColorEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/ColorEditor.cs index 57ad53b9736..4b71a6f42f6 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/ColorEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/ColorEditor.cs @@ -162,7 +162,9 @@ public ColorPalette(ColorUI colorUI, Color[] customColors) staticColors = new Color[CELLS - CELLS_CUSTOM]; for (int i = 0; i < staticCells.Length; i++) + { staticColors[i] = ColorTranslator.FromOle(staticCells[i]); + } CustomColors = customColors; } @@ -238,7 +240,10 @@ private Color GetColorFromCell(int across, int down) private Color GetColorFromCell(int index) { if (index < CELLS - CELLS_CUSTOM) + { return staticColors[index]; + } + return CustomColors[index - CELLS + CELLS_CUSTOM]; } @@ -971,9 +976,14 @@ protected override bool ProcessDialogKey(Keys keyData) { int count = tabControl.TabPages.Count; if (forward) + { sel = (sel + 1) % count; + } else + { sel = (sel + count - 1) % count; + } + tabControl.SelectedTab = tabControl.TabPages[sel]; return true; diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/CursorEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/CursorEditor.cs index d74d74f796f..4d6f1c0d6d3 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/CursorEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/CursorEditor.cs @@ -33,7 +33,10 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide object returnValue = value; if (provider == null) + { return value; + } + IWindowsFormsEditorService edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (edSvc != null) diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/AnchorEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/AnchorEditor.cs index 8115b65bc09..e7475025c15 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/AnchorEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/AnchorEditor.cs @@ -33,7 +33,10 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide if (edSvc != null) { if (anchorUI == null) + { anchorUI = new AnchorUI(this); + } + anchorUI.Start(edSvc, value); edSvc.DropDownControl(anchorUI); value = anchorUI.Value; @@ -92,13 +95,25 @@ public virtual AnchorStyles GetSelectedAnchor() { AnchorStyles baseVar = 0; if (left.GetSolid()) + { baseVar |= AnchorStyles.Left; + } + if (top.GetSolid()) + { baseVar |= AnchorStyles.Top; + } + if (bottom.GetSolid()) + { baseVar |= AnchorStyles.Bottom; + } + if (right.GetSolid()) + { baseVar |= AnchorStyles.Right; + } + return baseVar; } @@ -195,7 +210,10 @@ public void Start(IWindowsFormsEditorService edSvc, object value) private void Teardown(bool saveAnchor) { if (!saveAnchor) + { Value = oldAnchor; + } + edSvc.CloseDropDown(); } @@ -330,6 +348,7 @@ protected override bool ProcessDialogKey(Keys keyData) if ((keyData & Keys.KeyCode) == Keys.Tab && (keyData & (Keys.Alt | Keys.Control)) == 0) { for (int i = 0; i < picker.tabOrder.Length; i++) + { if (picker.tabOrder[i] == this) { i += (keyData & Keys.Shift) == 0 ? 1 : -1; @@ -337,6 +356,7 @@ protected override bool ProcessDialogKey(Keys keyData) picker.tabOrder[i].Focus(); break; } + } return true; } @@ -367,7 +387,9 @@ public override AccessibleStates State AccessibleStates state = base.State; if (((SpringControl)Owner).GetSolid()) + { state |= AccessibleStates.Selected; + } return state; } diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/BorderSidesEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/BorderSidesEditor.cs index 685e5f4cbf5..d35a1b53b7d 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/BorderSidesEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/BorderSidesEditor.cs @@ -30,12 +30,18 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide if (edSvc != null) { if (borderSidesEditorUI == null) + { borderSidesEditorUI = new BorderSidesEditorUI(this); + } + borderSidesEditorUI.Start(edSvc, value); edSvc.DropDownControl(borderSidesEditorUI); if (borderSidesEditorUI.Value != null) + { value = borderSidesEditorUI.Value; + } + borderSidesEditorUI.End(); } } @@ -231,7 +237,9 @@ private void rightCheckBox_CheckedChanged(object sender, EventArgs e) else // this is turned off.... { if (allCheckBox.Checked) + { allCheckBox.Checked = false; + } } UpdateCurrentValue(); @@ -250,7 +258,9 @@ private void leftCheckBox_CheckedChanged(object sender, EventArgs e) else // this is turned off.... { if (allCheckBox.Checked) + { allCheckBox.Checked = false; + } } UpdateCurrentValue(); @@ -269,7 +279,9 @@ private void bottomCheckBox_CheckedChanged(object sender, EventArgs e) else // this is turned off.... { if (allCheckBox.Checked) + { allCheckBox.Checked = false; + } } UpdateCurrentValue(); @@ -288,7 +300,9 @@ private void topCheckBox_CheckedChanged(object sender, EventArgs e) else // this is turned off.... { if (allCheckBox.Checked) + { allCheckBox.Checked = false; + } } UpdateCurrentValue(); @@ -336,7 +350,9 @@ private void allCheckBox_CheckedChanged(object sender, EventArgs e) private void noneCheckBoxClicked(object sender, EventArgs e) { if (noneChecked) + { noneCheckBox.Checked = true; + } } /// @@ -345,7 +361,9 @@ private void noneCheckBoxClicked(object sender, EventArgs e) private void allCheckBoxClicked(object sender, EventArgs e) { if (allChecked) + { allCheckBox.Checked = true; + } } /// @@ -414,7 +432,9 @@ public void Start(IWindowsFormsEditorService edSvc, object value) private void UpdateCurrentValue() { if (!updateCurrentValue) + { return; + } ToolStripStatusLabelBorderSides valueSide = ToolStripStatusLabelBorderSides.None; if (allCheckBox.Checked) @@ -427,15 +447,29 @@ private void UpdateCurrentValue() } if (noneCheckBox.Checked) + { valueSide |= ToolStripStatusLabelBorderSides.None; + } + if (topCheckBox.Checked) + { valueSide |= ToolStripStatusLabelBorderSides.Top; + } + if (bottomCheckBox.Checked) + { valueSide |= ToolStripStatusLabelBorderSides.Bottom; + } + if (leftCheckBox.Checked) + { valueSide |= ToolStripStatusLabelBorderSides.Left; + } + if (rightCheckBox.Checked) + { valueSide |= ToolStripStatusLabelBorderSides.Right; + } if (valueSide == ToolStripStatusLabelBorderSides.None) { diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/DockEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/DockEditor.cs index ac9736ae17c..f16def90c12 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/DockEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/DockEditor.cs @@ -33,7 +33,10 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide if (edSvc != null) { if (dockUI == null) + { dockUI = new DockUI(this); + } + dockUI.Start(edSvc, value); edSvc.DropDownControl(dockUI); value = dockUI.Value; @@ -139,15 +142,30 @@ public void End() public virtual DockStyle GetDock(CheckBox btn) { if (top == btn) + { return DockStyle.Top; + } + if (left == btn) + { return DockStyle.Left; + } + if (bottom == btn) + { return DockStyle.Bottom; + } + if (right == btn) + { return DockStyle.Right; + } + if (fill == btn) + { return DockStyle.Fill; + } + return DockStyle.None; } @@ -250,7 +268,10 @@ private void OnClick(object sender, EventArgs eventargs) { DockStyle val = GetDock((CheckBox)sender); if (val >= 0) + { Value = val; + } + Teardown(); } @@ -260,11 +281,13 @@ protected override void OnGotFocus(EventArgs e) // Set focus to currently selected Dock style for (int i = 0; i < tabOrder.Length; i++) + { if (tabOrder[i].Checked) { tabOrder[i].Focus(); break; } + } } private void OnKeyDown(object sender, KeyEventArgs e) @@ -280,36 +303,53 @@ private void OnKeyDown(object sender, KeyEventArgs e) // If we're going up or down from one of the 'sides', act like we're doing // it from the center if (sender == left || sender == right) + { sender = fill; + } maxI = upDownOrder.Length - 1; for (int i = 0; i <= maxI; i++) + { if (upDownOrder[i] == sender) { if (key == Keys.Up) + { target = upDownOrder[Math.Max(i - 1, 0)]; + } else + { target = upDownOrder[Math.Min(i + 1, maxI)]; + } + break; } + } break; case Keys.Left: case Keys.Right: maxI = leftRightOrder.Length - 1; for (int i = 0; i <= maxI; i++) + { if (leftRightOrder[i] == sender) { if (key == Keys.Left) + { target = leftRightOrder[Math.Max(i - 1, 0)]; + } else + { target = leftRightOrder[Math.Min(i + 1, maxI)]; + } + break; } + } break; case Keys.Tab: for (int i = 0; i < tabOrder.Length; i++) + { if (tabOrder[i] == sender) { i += (e.Modifiers & Keys.Shift) == 0 ? 1 : -1; @@ -317,6 +357,7 @@ private void OnKeyDown(object sender, KeyEventArgs e) target = tabOrder[i]; break; } + } break; case Keys.Return: @@ -329,7 +370,9 @@ private void OnKeyDown(object sender, KeyEventArgs e) e.Handled = true; if (target != null && target != sender) + { target.Focus(); + } } public void Start(IWindowsFormsEditorService edSvc, object value) diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/ShortcutKeysEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/ShortcutKeysEditor.cs index 9a2eea28611..41eb9589075 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/ShortcutKeysEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/ShortcutKeysEditor.cs @@ -42,7 +42,10 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide edSvc.DropDownControl(shortcutKeysUI); if (shortcutKeysUI.Value != null) + { value = shortcutKeysUI.Value; + } + shortcutKeysUI.End(); } } @@ -115,8 +118,12 @@ public ShortcutKeysUI(ShortcutKeysEditor editor) // Looking for duplicates in validKeys int keyCount = validKeys.Length; for (int key1 = 0; key1 < keyCount - 1; key1++) + { for (int key2 = key1 + 1; key2 < keyCount; key2++) + { Debug.Assert((int)validKeys[key1] != (int)validKeys[key2]); + } + } #endif } @@ -139,7 +146,10 @@ private TypeConverter KeysConverter get { if (keysConverter == null) + { keysConverter = TypeDescriptor.GetConverter(typeof(Keys)); + } + Debug.Assert(keysConverter != null); return keysConverter; } @@ -153,7 +163,10 @@ public object Value get { if (((Keys)currentValue & Keys.KeyCode) == 0) + { return Keys.None; + } + return currentValue; } } @@ -293,7 +306,10 @@ private void InitializeComponent() cmbKey.Padding = cmbKey.Margin; foreach (Keys keyCode in validKeys) + { cmbKey.Items.Add(KeysConverter.ConvertToString(keyCode)); + } + cmbKey.SelectedIndexChanged += cmbKey_SelectedIndexChanged; // @@ -331,8 +347,13 @@ private static bool IsValidKey(Keys keyCode) { Debug.Assert((keyCode & Keys.KeyCode) == keyCode); foreach (Keys validKeyCode in validKeys) + { if (validKeyCode == keyCode) + { return true; + } + } + return false; } @@ -367,11 +388,13 @@ protected override bool ProcessDialogKey(Keys keyData) case Keys.Left: if ((keyModifiers & (Keys.Control | Keys.Alt)) == 0) + { if (chkCtrl.Focused) { btnReset.Focus(); return true; } + } break; @@ -397,7 +420,10 @@ protected override bool ProcessDialogKey(Keys keyData) if (!cmbKey.Focused || (keyModifiers & (Keys.Control | Keys.Alt)) != 0 || !cmbKey.DroppedDown) + { currentValue = originalValue; + } + break; } @@ -445,19 +471,36 @@ public void Start(IWindowsFormsEditorService edSvc, object value) private void UpdateCurrentValue() { if (!updateCurrentValue) + { return; + } + int cmbKeySelectedIndex = cmbKey.SelectedIndex; Keys valueKeys = Keys.None; if (chkCtrl.Checked) + { valueKeys |= Keys.Control; + } + if (chkAlt.Checked) + { valueKeys |= Keys.Alt; + } + if (chkShift.Checked) + { valueKeys |= Keys.Shift; + } + if (unknownKeyCode != Keys.None && cmbKeySelectedIndex == 0) + { valueKeys |= unknownKeyCode; + } else if (cmbKeySelectedIndex != -1) + { valueKeys |= validKeys[unknownKeyCode == Keys.None ? cmbKeySelectedIndex : cmbKeySelectedIndex - 1]; + } + currentValue = valueKeys; } } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/CodeMarkers.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/CodeMarkers.cs index f85dcbc09ff..79df6b19851 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/CodeMarkers.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/CodeMarkers.cs @@ -136,7 +136,9 @@ private CodeMarkers() public bool CodeMarker(int nTimerID) { if (!IsEnabled) + { return false; + } try { @@ -170,12 +172,16 @@ public bool CodeMarker(int nTimerID) public bool CodeMarkerEx(int nTimerID, byte[] aBuff) { if (!IsEnabled) + { return false; + } // Check the arguments only after checking whether code markers are enabled // This allows the calling code to pass null value and avoid calculation of data if nothing is to be logged if (aBuff == null) + { throw new ArgumentNullException(nameof(aBuff)); + } try { @@ -231,12 +237,16 @@ public bool CodeMarkerEx(int nTimerID, Guid guidData) public bool CodeMarkerEx(int nTimerID, string stringData) { if (!IsEnabled) + { return false; + } // Check the arguments only after checking whether code markers are enabled // This allows the calling code to pass null value and avoid calculation of data if nothing is to be logged if (stringData == null) + { throw new ArgumentNullException(nameof(stringData)); + } try { diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/ComponentDesigner.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/ComponentDesigner.cs index 1a27a96bddb..87bc6dea28b 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/ComponentDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/ComponentDesigner.cs @@ -390,7 +390,9 @@ public virtual void DoDefaultAction() catch (CheckoutException cxe) { if (cxe == CheckoutException.Canceled) + { return; + } throw cxe; } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerActionPanel.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerActionPanel.cs index e6bed9f0d82..f101b55b997 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerActionPanel.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerActionPanel.cs @@ -2199,12 +2199,17 @@ protected internal override bool ProcessDialogKey(Keys keyData) ActivateDropDown(); } else + { CloseDropDown(); + } + return true; } // Not passing Alt key event to base class to prevent closing 'Combobox Tasks window' else if ((keyData & Keys.Alt) == Keys.Alt) + { return true; + } } return base.ProcessDialogKey(keyData); } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerHost.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerHost.cs index ae39d5a0fa7..90e717af043 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerHost.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerHost.cs @@ -777,7 +777,9 @@ private void Unload() _designers.Clear(); while (Components.Count > 0) + { Remove(Components[0]); + } } finally { diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/ReferenceService.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/ReferenceService.cs index ad84bd591fc..a0438c7968a 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/ReferenceService.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/ReferenceService.cs @@ -349,9 +349,14 @@ internal ReferenceHolder(string trailingName, object reference, IComponent sited #if DEBUG Debug.Assert(sitedComponent != null, "Expected a sited component"); if (sitedComponent != null) + { Debug.Assert(sitedComponent.Site != null, "Sited component is not really sited: " + sitedComponent.ToString()); + } + if (sitedComponent != null) + { Debug.Assert(TypeDescriptor.GetComponentName(sitedComponent) != null, "Sited component has no name: " + sitedComponent.ToString()); + } #endif // DEBUG } @@ -386,9 +391,14 @@ internal string Name _fullName = string.Empty; #if DEBUG if (_sitedComponent != null) + { Debug.Assert(_sitedComponent.Site != null, "Sited component is not really sited: " + _sitedComponent.ToString()); + } + if (_sitedComponent != null) + { Debug.Assert(TypeDescriptor.GetComponentName(_sitedComponent) != null, "Sited component has no name: " + _sitedComponent.ToString()); + } #endif // DEBUG } } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/SelectionService.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/SelectionService.cs index 4c867e3162e..3c7b5f1fd7a 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/SelectionService.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/SelectionService.cs @@ -448,7 +448,10 @@ void ISelectionService.SetSelectedComponents(ICollection components, SelectionTy foreach (object comp in components) { if (comp == null) + { throw new ArgumentNullException(nameof(components)); + } + if (object.ReferenceEquals(comp, item)) { remove = false; @@ -469,7 +472,9 @@ void ISelectionService.SetSelectedComponents(ICollection components, SelectionTy foreach (object comp in components) { if (comp == null) + { throw new ArgumentNullException(nameof(components)); + } if (_selection != null && _selection.Contains(comp)) { diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomComponentSerializationService.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomComponentSerializationService.cs index 0f16abd11e3..daee0a5ac01 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomComponentSerializationService.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomComponentSerializationService.cs @@ -51,7 +51,10 @@ public override SerializationStore CreateStore() public override SerializationStore LoadStore(Stream stream) { if (stream == null) + { throw new ArgumentNullException(nameof(stream)); + } + return CodeDomSerializationStore.Load(stream); } @@ -61,11 +64,20 @@ public override SerializationStore LoadStore(Stream stream) public override void Serialize(SerializationStore store, object value) { if (store == null) + { throw new ArgumentNullException(nameof(store)); + } + if (value == null) + { throw new ArgumentNullException(nameof(value)); + } + if (!(store is CodeDomSerializationStore cdStore)) + { throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceUnknownStore); + } + cdStore.AddObject(value, false); } @@ -75,11 +87,20 @@ public override void Serialize(SerializationStore store, object value) public override void SerializeAbsolute(SerializationStore store, object value) { if (store == null) + { throw new ArgumentNullException(nameof(store)); + } + if (value == null) + { throw new ArgumentNullException(nameof(value)); + } + if (!(store is CodeDomSerializationStore cdStore)) + { throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceUnknownStore); + } + cdStore.AddObject(value, true); } @@ -89,13 +110,25 @@ public override void SerializeAbsolute(SerializationStore store, object value) public override void SerializeMember(SerializationStore store, object owningObject, MemberDescriptor member) { if (store == null) + { throw new ArgumentNullException(nameof(store)); + } + if (owningObject == null) + { throw new ArgumentNullException(nameof(owningObject)); + } + if (member == null) + { throw new ArgumentNullException(nameof(member)); + } + if (!(store is CodeDomSerializationStore cdStore)) + { throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceUnknownStore); + } + cdStore.AddMember(owningObject, member, false); } @@ -106,13 +139,25 @@ public override void SerializeMember(SerializationStore store, object owningObje public override void SerializeMemberAbsolute(SerializationStore store, object owningObject, MemberDescriptor member) { if (store == null) + { throw new ArgumentNullException(nameof(store)); + } + if (owningObject == null) + { throw new ArgumentNullException(nameof(owningObject)); + } + if (member == null) + { throw new ArgumentNullException(nameof(member)); + } + if (!(store is CodeDomSerializationStore cdStore)) + { throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceUnknownStore); + } + cdStore.AddMember(owningObject, member, true); } @@ -122,9 +167,15 @@ public override void SerializeMemberAbsolute(SerializationStore store, object ow public override ICollection Deserialize(SerializationStore store) { if (store == null) + { throw new ArgumentNullException(nameof(store)); + } + if (!(store is CodeDomSerializationStore cdStore)) + { throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceUnknownStore); + } + return cdStore.Deserialize(_provider); } @@ -134,11 +185,20 @@ public override ICollection Deserialize(SerializationStore store) public override ICollection Deserialize(SerializationStore store, IContainer container) { if (store == null) + { throw new ArgumentNullException(nameof(store)); + } + if (container == null) + { throw new ArgumentNullException(nameof(container)); + } + if (!(store is CodeDomSerializationStore cdStore)) + { throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceUnknownStore); + } + return cdStore.Deserialize(_provider, container); } @@ -148,11 +208,20 @@ public override ICollection Deserialize(SerializationStore store, IContainer con public override void DeserializeTo(SerializationStore store, IContainer container, bool validateRecycledTypes, bool applyDefaults) { if (store == null) + { throw new ArgumentNullException(nameof(store)); + } + if (container == null) + { throw new ArgumentNullException(nameof(container)); + } + if (!(store is CodeDomSerializationStore cdStore)) + { throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceUnknownStore); + } + cdStore.DeserializeTo(_provider, container, validateRecycledTypes, applyDefaults); } @@ -268,7 +337,10 @@ private LocalResourceManager Resources internal void AddMember(object value, MemberDescriptor member, bool absolute) { if (_objectState != null) + { throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceClosedStore); + } + ObjectData data = (ObjectData)_objects[value]; if (data == null) { @@ -292,7 +364,10 @@ internal void AddMember(object value, MemberDescriptor member, bool absolute) internal void AddObject(object value, bool absolute) { if (_objectState != null) + { throw new InvalidOperationException(SR.CodeDomComponentSerializationServiceClosedStore); + } + ObjectData data = (ObjectData)_objects[value]; if (data == null) { diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializer.cs index d3e402a4c84..870c9db4411 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializer.cs @@ -272,11 +272,19 @@ public virtual object SerializeAbsolute(IDesignerSerializationManager manager, o public virtual CodeStatementCollection SerializeMember(IDesignerSerializationManager manager, object owningObject, MemberDescriptor member) { if (manager == null) + { throw new ArgumentNullException(nameof(manager)); + } + if (owningObject == null) + { throw new ArgumentNullException(nameof(owningObject)); + } + if (member == null) + { throw new ArgumentNullException(nameof(member)); + } CodeStatementCollection statements = new CodeStatementCollection(); // See if we have an existing expression for this member. If not, fabricate one @@ -312,11 +320,19 @@ public virtual CodeStatementCollection SerializeMember(IDesignerSerializationMan public virtual CodeStatementCollection SerializeMemberAbsolute(IDesignerSerializationManager manager, object owningObject, MemberDescriptor member) { if (manager == null) + { throw new ArgumentNullException(nameof(manager)); + } + if (owningObject == null) + { throw new ArgumentNullException(nameof(owningObject)); + } + if (member == null) + { throw new ArgumentNullException(nameof(member)); + } CodeStatementCollection statements; SerializeAbsoluteContext abs = new SerializeAbsoluteContext(member); diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs index bcbdfd242a3..b5d0738ce66 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs @@ -463,7 +463,10 @@ internal static IDisposable TraceScope(string name) { #if DEBUG if (traceScope == null) + { traceScope = new Stack(); + } + Trace(name); traceScope.Push(name); #endif @@ -474,7 +477,9 @@ internal static IDisposable TraceScope(string name) internal static void TraceIf(bool condition, string message, params object[] values) { if (condition) + { Trace(message, values); + } } [Conditional("DEBUG")] @@ -486,7 +491,10 @@ internal static void Trace(string message, params object[] values) int oldIndent = Debug.IndentLevel; if (traceScope != null) + { indent = traceScope.Count; + } + try { Debug.IndentLevel = indent; @@ -504,7 +512,9 @@ private struct TracingScope : IDisposable public void Dispose() { if (traceScope != null) + { traceScope.Pop(); + } } } @@ -2299,9 +2309,14 @@ protected bool IsSerialized(IDesignerSerializationManager manager, object value, { bool hasExpression = false; if (manager == null) + { throw new ArgumentNullException(nameof(manager)); + } + if (value == null) + { throw new ArgumentNullException(nameof(value)); + } // Is the expression part of a prior SetExpression call? if (manager.Context[typeof(ExpressionTable)] is ExpressionTable table && table.GetExpression(value) != null && (!honorPreset || !table.ContainsPresetExpression(value))) @@ -2322,9 +2337,14 @@ protected CodeExpression SerializeCreationExpression(IDesignerSerializationManag { isComplete = false; if (manager == null) + { throw new ArgumentNullException(nameof(manager)); + } + if (value == null) + { throw new ArgumentNullException(nameof(value)); + } TypeConverter converter = TypeDescriptor.GetConverter(value); // See if there is an ExpressionContext with a preset value we're interested in. If so, that will dictate our creation expression. @@ -2556,13 +2576,24 @@ protected string GetUniqueName(IDesignerSerializationManager manager, object val protected void SerializeEvent(IDesignerSerializationManager manager, CodeStatementCollection statements, object value, EventDescriptor descriptor) { if (manager == null) + { throw new ArgumentNullException(nameof(manager)); + } + if (statements == null) + { throw new ArgumentNullException(nameof(statements)); + } + if (value == null) + { throw new ArgumentNullException(nameof(value)); + } + if (descriptor == null) + { throw new ArgumentNullException(nameof(descriptor)); + } using (TraceScope("CodeDomSerializerBase::" + nameof(SerializeEvent))) { @@ -2725,13 +2756,24 @@ protected void SerializePropertiesToResources(IDesignerSerializationManager mana protected void SerializeProperty(IDesignerSerializationManager manager, CodeStatementCollection statements, object value, PropertyDescriptor propertyToSerialize) { if (manager == null) + { throw new ArgumentNullException(nameof(manager)); + } + if (value == null) + { throw new ArgumentNullException(nameof(value)); + } + if (propertyToSerialize == null) + { throw new ArgumentNullException(nameof(propertyToSerialize)); + } + if (statements == null) + { throw new ArgumentNullException(nameof(statements)); + } Trace("CodeDomSerializerBase::" + nameof(SerializeProperty) + " {0}", propertyToSerialize.Name); // Now look for a MemberCodeDomSerializer for the property. If we can't find one, then we can't serialize the property @@ -3072,11 +3114,19 @@ protected void SetExpression(IDesignerSerializationManager manager, object value protected void SetExpression(IDesignerSerializationManager manager, object value, CodeExpression expression, bool isPreset) { if (manager == null) + { throw new ArgumentNullException(nameof(manager)); + } + if (value == null) + { throw new ArgumentNullException(nameof(value)); + } + if (expression == null) + { throw new ArgumentNullException(nameof(expression)); + } ExpressionTable table = (ExpressionTable)manager.Context[typeof(ExpressionTable)]; if (table == null) diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeMethodMap.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeMethodMap.cs index 1e40d549294..1bbd2e82e6e 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeMethodMap.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeMethodMap.cs @@ -43,7 +43,10 @@ internal CodeStatementCollection BeginStatements get { if (_begin == null) + { _begin = new CodeStatementCollection(); + } + return _begin; } } @@ -53,7 +56,10 @@ internal CodeStatementCollection EndStatements get { if (_end == null) + { _end = new CodeStatementCollection(); + } + return _end; } } @@ -63,7 +69,10 @@ internal CodeStatementCollection ContainerStatements get { if (_container == null) + { _container = new CodeStatementCollection(); + } + return _container; } } @@ -78,7 +87,10 @@ internal CodeStatementCollection Statements get { if (_statements == null) + { _statements = new CodeStatementCollection(); + } + return _statements; } } @@ -88,7 +100,10 @@ internal CodeStatementCollection LocalVariables get { if (_locals == null) + { _locals = new CodeStatementCollection(); + } + return _locals; } } @@ -98,7 +113,10 @@ internal CodeStatementCollection FieldAssignments get { if (_fields == null) + { _fields = new CodeStatementCollection(); + } + return _fields; } } @@ -109,7 +127,10 @@ internal CodeStatementCollection VariableAssignments get { if (_variables == null) + { _variables = new CodeStatementCollection(); + } + return _variables; } } @@ -165,19 +186,39 @@ internal void Add(CodeStatementCollection statements) internal void Combine() { if (_container != null) + { _targetStatements.AddRange(_container); + } + if (_locals != null) + { _targetStatements.AddRange(_locals); + } + if (_fields != null) + { _targetStatements.AddRange(_fields); + } + if (_variables != null) + { _targetStatements.AddRange(_variables); + } + if (_begin != null) + { _targetStatements.AddRange(_begin); + } + if (_statements != null) + { _targetStatements.AddRange(_statements); + } + if (_end != null) + { _targetStatements.AddRange(_end); + } } } } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CollectionCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CollectionCodeDomSerializer.cs index 8cbf6ae9708..e9aff90b619 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CollectionCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CollectionCodeDomSerializer.cs @@ -309,13 +309,24 @@ private static MethodInfo ChooseMethodByType(TypeDescriptionProvider provider, L protected virtual object SerializeCollection(IDesignerSerializationManager manager, CodeExpression targetExpression, Type targetType, ICollection originalCollection, ICollection valuesToSerialize) { if (manager == null) + { throw new ArgumentNullException(nameof(manager)); + } + if (targetType == null) + { throw new ArgumentNullException(nameof(targetType)); + } + if (originalCollection == null) + { throw new ArgumentNullException(nameof(originalCollection)); + } + if (valuesToSerialize == null) + { throw new ArgumentNullException(nameof(valuesToSerialize)); + } object result = null; bool serialized = false; @@ -519,9 +530,13 @@ private object SerializeViaAdd( if (ia != null) { if (ia.InheritanceLevel == InheritanceLevel.InheritedReadOnly) + { genCode = false; + } else + { genCode = true; + } } else { @@ -607,9 +622,13 @@ private object SerializeViaAddRange( if (ia != null) { if (ia.InheritanceLevel == InheritanceLevel.InheritedReadOnly) + { genCode = false; + } else + { genCode = true; + } } else { diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs index 26eda5960c1..01147c68b9f 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs @@ -881,9 +881,14 @@ void IDesignerSerializationManager.SetName(object instance, string name) { CheckSession(); if (instance == null) + { throw new ArgumentNullException(nameof(instance)); + } + if (name == null) + { throw new ArgumentNullException(nameof(name)); + } if (instancesByName == null) { diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ResourceCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ResourceCodeDomSerializer.cs index f337c49b96c..f782c5a720f 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ResourceCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ResourceCodeDomSerializer.cs @@ -684,7 +684,9 @@ private CompareValue CompareWithParentValue(string name, object value) Debug.Assert(name != null, "name is null"); // If there is no parent culture, treat that as being different from the parent's resource, which results in the "normal" code path for the caller. if (ReadCulture.Equals(CultureInfo.InvariantCulture)) + { return CompareValue.Different; + } CultureInfo culture = ReadCulture; for (; ; ) @@ -703,9 +705,13 @@ private CompareValue CompareWithParentValue(string name, object value) else if (parentValue != null) { if (parentValue.Equals(value)) + { return CompareValue.Same; + } else + { return CompareValue.Different; + } } else { diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/TypeCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/TypeCodeDomSerializer.cs index 45a72de6371..30bf2d7fc82 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/TypeCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/TypeCodeDomSerializer.cs @@ -470,7 +470,10 @@ public virtual CodeTypeDeclaration Serialize(IDesignerSerializationManager manag #if DEBUG string memberName = manager.GetName(member); if (memberName == null) + { memberName = member.ToString(); + } + Trace("--------------------------------------------------------------------"); Trace(" Beginning serialization of {0}", memberName); Trace("--------------------------------------------------------------------"); @@ -484,7 +487,10 @@ public virtual CodeTypeDeclaration Serialize(IDesignerSerializationManager manag #if DEBUG string rootName = manager.GetName(root); if (rootName == null) + { rootName = root.ToString(); + } + Trace("--------------------------------------------------------------------"); Trace(" Bedginning serialization of root object {0}", rootName); Trace("--------------------------------------------------------------------"); diff --git a/src/System.Windows.Forms.Design/src/System/Drawing/Design/ToolboxItem.cs b/src/System.Windows.Forms.Design/src/System/Drawing/Design/ToolboxItem.cs index fca4a756d22..781ea253c8d 100644 --- a/src/System.Windows.Forms.Design/src/System/Drawing/Design/ToolboxItem.cs +++ b/src/System.Windows.Forms.Design/src/System/Drawing/Design/ToolboxItem.cs @@ -312,7 +312,9 @@ public event ToolboxComponentsCreatingEventHandler ComponentsCreating protected void CheckUnlocked() { if (Locked) + { throw new InvalidOperationException(SR.ToolboxItemLocked); + } } /// @@ -523,26 +525,34 @@ protected virtual object FilterPropertyValue(string propertyName, object value) { case "AssemblyName": if (value is AssemblyName valueName) + { value = valueName.Clone(); + } break; case "DisplayName": case "TypeName": if (value == null) + { value = string.Empty; + } break; case "Filter": if (value == null) + { value = Array.Empty(); + } break; case "IsTransient": if (value == null) + { value = false; + } break; } @@ -782,7 +792,9 @@ private AssemblyName GetNonRetargetedAssemblyName(Type type, AssemblyName polici { Debug.Assert(type != null); if (policiedAssemblyName == null) + { return null; + } //if looking for myself, just return it. (not a reference) if (type.Assembly.FullName == policiedAssemblyName.FullName) @@ -794,14 +806,18 @@ private AssemblyName GetNonRetargetedAssemblyName(Type type, AssemblyName polici foreach (AssemblyName name in type.Assembly.GetReferencedAssemblies()) { if (name.FullName == policiedAssemblyName.FullName) + { return name; + } } //next search for a partial match -- we just compare the Name portions (ignore version and publickey) foreach (AssemblyName name in type.Assembly.GetReferencedAssemblies()) { if (name.Name == policiedAssemblyName.Name) + { return name; + } } //finally, the most expensive -- its possible that retargeting policy is on an assembly whose name changes @@ -928,7 +944,9 @@ protected virtual object ValidatePropertyValue(string propertyName, object value case "TypeName": ValidatePropertyType(propertyName, value, typeof(string), true); if (value == null) + { value = string.Empty; + } break; diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs index 2e56712a889..4c30c540083 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs @@ -220,7 +220,9 @@ public void Dispose() MenuCommandHandler menuCommandHandler = null; if (_serviceProvider.GetService(typeof(IMenuCommandService)) is IMenuCommandService menuCommandService) + { menuCommandHandler = menuCommandService as MenuCommandHandler; + } if (menuCommandHandler != null && _serviceProvider.GetService(typeof(IDesignerHost)) is IDesignerHost host) { diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/GlyphCollection.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/GlyphCollection.cs index 1ffc4cb792c..ed14a74fb10 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/GlyphCollection.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/GlyphCollection.cs @@ -58,7 +58,9 @@ public int Add(Glyph value) public void AddRange(Glyph[] value) { for (int i = 0; i < value.Length; i = i + 1) + { Add(value[i]); + } } /// @@ -67,7 +69,9 @@ public void AddRange(Glyph[] value) public void AddRange(GlyphCollection value) { for (int i = 0; i < value.Count; i = i + 1) + { Add(value[i]); + } } /// diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/ResizeBehavior.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/ResizeBehavior.cs index 273b977aabc..226af49c989 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/ResizeBehavior.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/ResizeBehavior.cs @@ -328,7 +328,9 @@ public override bool OnMouseDown(Glyph g, MouseButtons button, Point mouseLoc) if (prop != null) { if ((bool)prop.GetValue(o)) + { continue; + } } components.Add(o); } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/CommandSet.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/CommandSet.cs index d943df5ab9c..ac41ad810dd 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/CommandSet.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/CommandSet.cs @@ -321,7 +321,9 @@ private object[] FilterSelection(object[] components, SelectionRules selectionRu { object[] selection = null; if (components == null) + { return new object[0]; + } // Mask off any selection object that doesn't adhere to the given ruleset. We can ignore this if the ruleset is zero, as all components would be accepted. if (selectionRules != SelectionRules.None) { @@ -504,7 +506,10 @@ protected bool CanCheckout(IComponent comp) catch (CheckoutException chkex) { if (chkex == CheckoutException.Canceled) + { return false; + } + throw chkex; } } @@ -850,7 +855,9 @@ protected void OnMenuAlignByPrimary(object sender, EventArgs e) if (lockProp != null) { if ((bool)lockProp.GetValue(comp)) + { continue; + } } // Skip all components that don't have a location property @@ -1132,13 +1139,24 @@ protected void OnMenuCenterSelection(object sender, EventArgs e) } if (loc.X < left) + { left = loc.X; + } + if (loc.Y < top) + { top = loc.Y; + } + if (loc.X + size.Width > right) + { right = loc.X + size.Width; + } + if (loc.Y + size.Height > bottom) + { bottom = loc.Y + size.Height; + } } } @@ -1162,7 +1180,9 @@ protected void OnMenuCenterSelection(object sender, EventArgs e) shiftRight = true; } else + { deltaX = centerOfUnionRectX - centerOfParentX; + } if (centerOfParentY >= centerOfUnionRectY) { @@ -1170,7 +1190,9 @@ protected void OnMenuCenterSelection(object sender, EventArgs e) shiftBottom = true; } else + { deltaY = centerOfUnionRectY - centerOfParentY; + } bool firstTry = true; foreach (object obj in selectedComponents) @@ -1190,16 +1212,24 @@ protected void OnMenuCenterSelection(object sender, EventArgs e) if (cmdID == MenuCommands.CenterHorizontally) { if (shiftRight) + { loc.X += deltaX; + } else + { loc.X -= deltaX; + } } else if (cmdID == MenuCommands.CenterVertically) { if (shiftBottom) + { loc.Y += deltaY; + } else + { loc.Y -= deltaY; + } } // look if it's ok to change the first time if (firstTry && !CanCheckout(comp)) @@ -1381,7 +1411,10 @@ protected void OnMenuCut(object sender, EventArgs e) finally { if (trans != null) + { trans.Commit(); + } + foreach (ParentControlDesigner des in designerList) { if (des != null) @@ -1662,7 +1695,10 @@ protected void OnMenuPaste(object sender, EventArgs e) IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost)); Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || host != null, "IDesignerHost not found"); if (host == null) + { return; // nothing we can do here! + } + IDataObject dataObj = Clipboard.GetDataObject(); ICollection components = null; bool createdItems = false; @@ -1742,7 +1778,10 @@ protected void OnMenuPaste(object sender, EventArgs e) else { if (tree == tree.Parent) + { break; + } + tree = tree.Parent as ITreeDesigner; } } @@ -2009,7 +2048,10 @@ protected void OnMenuSelectAll(object sender, EventArgs e) foreach (IComponent comp in components) { if (baseComp == comp) + { continue; + } + selComps[j++] = comp; } } @@ -2054,7 +2096,9 @@ protected void OnMenuShowGrid(object sender, EventArgs e) finally { if (trans != null) + { trans.Commit(); + } } } } @@ -2113,7 +2157,10 @@ protected void OnMenuSizingCommand(object sender, EventArgs e) foreach (object obj in selectedObjects) { if (obj.Equals(selPrimary)) + { continue; + } + if (!(obj is IComponent comp)) { continue; @@ -2290,7 +2337,9 @@ protected void OnMenuSnapToGrid(object sender, EventArgs e) finally { if (trans != null) + { trans.Commit(); + } } } } @@ -2364,7 +2413,9 @@ protected void OnMenuSpacingCommand(object sender, EventArgs e) object primary = SelectionService.PrimarySelection; int primaryIndex = 0; if (primary != null) + { primaryIndex = Array.IndexOf(selectedObjects, primary); + } // And compute delta values for Make Equal if (cmdID == MenuCommands.HorizSpaceMakeEqual || @@ -2485,7 +2536,9 @@ protected void OnMenuSpacingCommand(object sender, EventArgs e) nEqualDelta = (lastSize.Height + lastLoc.Y - curLoc.Y - total) / (selectedObjects.Length - 1); } if (nEqualDelta < 0) + { nEqualDelta = 0; + } } } curComp = lastComp = null; @@ -2580,13 +2633,17 @@ protected void OnMenuSpacingCommand(object sender, EventArgs e) { curLoc.X -= grid.Width * (n - primaryIndex); if (curLoc.X < primaryLoc.X) + { curLoc.X = primaryLoc.X; + } } else if (primaryIndex > n) { curLoc.X += grid.Width * (primaryIndex - n); if (curLoc.X > primaryLoc.X) + { curLoc.X = primaryLoc.X; + } } } else if (cmdID == MenuCommands.HorizSpaceIncrease) @@ -2615,13 +2672,17 @@ protected void OnMenuSpacingCommand(object sender, EventArgs e) { curLoc.Y -= grid.Height * (n - primaryIndex); if (curLoc.Y < primaryLoc.Y) + { curLoc.Y = primaryLoc.Y; + } } else if (primaryIndex > n) { curLoc.Y += grid.Height * (primaryIndex - n); if (curLoc.Y > primaryLoc.Y) + { curLoc.Y = primaryLoc.Y; + } } } else if (cmdID == MenuCommands.VertSpaceIncrease) diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentTray.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentTray.cs index 1630f596d81..1b9935814eb 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentTray.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentTray.cs @@ -225,7 +225,9 @@ private void ResetTrayControls() { ControlCollection children = (ControlCollection)Controls; if (children == null) + { return; + } for (int i = 0; i < children.Count; ++i) { @@ -306,7 +308,9 @@ private void OnMenuShowLargeIcons(object sender, EventArgs e) finally { if (t != null) + { t.Commit(); + } } } @@ -322,14 +326,19 @@ private void OnMenuLineupIcons(object sender, EventArgs e) finally { if (t != null) + { t.Commit(); + } } } private void DoLineupIcons() { if (autoArrange) + { return; + } + bool oldValue = autoArrange; autoArrange = true; try @@ -367,7 +376,9 @@ private void DoAutoArrange(bool dirtyDesigner) foreach (Control ctl in controls) { if (!ctl.Visible) + { continue; + } // If we're auto arranging, always move the control. If not, move the control only if it was never given a position. This auto arranges it until the user messes with it, or until its position is saved into the resx. (if one control is no longer positioned, move all the other one as we don't want them to go under one another) if (autoArrange) { @@ -409,7 +420,9 @@ private void OnMenuArrangeIcons(object sender, EventArgs e) finally { if (t != null) + { t.Commit(); + } } } @@ -743,7 +756,10 @@ protected virtual bool CanCreateComponentFromTool(ToolboxItem tool) // Disallow controls to be added to the component tray. Type compType = host.GetType(tool.TypeName); if (compType == null) + { return true; + } + if (!compType.IsSubclassOf(typeof(Control))) { return true; @@ -1512,7 +1528,9 @@ public virtual void RemoveComponent(IComponent component) { int index = controls.IndexOf(c); if (index != -1) + { controls.RemoveAt(index); + } } } finally @@ -1758,7 +1776,9 @@ private void PositionControl(TrayControl c) if (mouseDropLocation != InvalidPoint) { if (!c.Location.Equals(mouseDropLocation)) + { c.Location = mouseDropLocation; + } } else { @@ -2440,7 +2460,10 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound protected override void SetVisibleCore(bool value) { if (value && !_tray.CanDisplayComponent(_component)) + { return; + } + base.SetVisibleCore(value); } @@ -2773,13 +2796,19 @@ int IComparer.Compare(object o1, object o2) int height = ((Control)o1).Height / 2; // If they are at the same location, they are equal. if (tcLoc1.X == tcLoc2.X && tcLoc1.Y == tcLoc2.Y) + { return 0; + } // Is the first control lower than the 2nd... if (tcLoc1.Y + height <= tcLoc2.Y) + { return -1; + } // Is the 2nd control lower than the first... if (tcLoc2.Y + height <= tcLoc1.Y) + { return 1; + } // Which control is left of the other... return ((tcLoc1.X <= tcLoc2.X) ? -1 : 1); } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerActionUI.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerActionUI.cs index ba09fa2cb54..0d9f612e943 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerActionUI.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerActionUI.cs @@ -97,7 +97,10 @@ public DesignerActionUI(IServiceProvider serviceProvider, Adorner containerAdorn _uiService = (IUIService)serviceProvider.GetService(typeof(IUIService)); if (_uiService != null) + { _mainParentWindow = _uiService.GetDialogOwnerWindow(); + } + _componentToGlyph = new Hashtable(); _marshalingControl = new Control(); _marshalingControl.CreateControl(); @@ -600,7 +603,9 @@ private void ToolStripDropDown_Closing(object sender, ToolStripDropDownClosingEv Debug.Assert(_lastPanelComponent != null, "last panel component should not be null here... " + "(except if you're currently debugging VS where deactivation messages in the middle of the pump can mess up everything...)"); if (_lastPanelComponent == null) + { return; + } // if we're actually closing get the coordinate of the last message, the one causing us to close, is it within the glyph coordinate. if it is that mean that someone just clicked back from the panel, on VS, but ON THE GLYPH, that means that he actually wants to close it. The activation change is going to do that for us but we should NOT reopen right away because he clicked on the glyph... this code is here to prevent this... Point point = DesignerUtils.LastCursorPoint; if (_componentToGlyph[_lastPanelComponent] is DesignerActionGlyph currentGlyph) @@ -888,7 +893,10 @@ protected override void OnClosing(ToolStripDropDownClosingEventArgs e) public void SetDesignerActionPanel(DesignerActionPanel panel, Glyph relatedGlyph) { if (_panel != null && panel == (DesignerActionPanel)_panel.Control) + { return; + } + Debug.Assert(relatedGlyph != null, "related glyph cannot be null"); _relatedGlyph = relatedGlyph; panel.SizeChanged += new EventHandler(PanelResized); diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerUtils.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerUtils.cs index 28fcb917d0a..ee4d5ff449b 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerUtils.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerUtils.cs @@ -780,7 +780,9 @@ private static unsafe void SetImageAlpha(Bitmap b, double opacity) public static ICollection FilterGenericTypes(ICollection types) { if (types == null || types.Count == 0) + { return types; + } //now we get each Type and add it to the destination collection if its not a generic ArrayList final = new ArrayList(types.Count); diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DocumentDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DocumentDesigner.cs index 6d6e677e78c..e3de4c41dc7 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DocumentDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DocumentDesigner.cs @@ -140,7 +140,9 @@ internal virtual void DoProperMenuSelection(ICollection selComponents) } //Here, something is selected, but the menuservice isn't interested so, we'll collapse our active menu accordingly else + { menuEditorService.SetMenu(null); + } } } } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/FormDocumentDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/FormDocumentDesigner.cs index 2170708f263..4909e9bf54a 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/FormDocumentDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/FormDocumentDesigner.cs @@ -197,7 +197,9 @@ internal MainMenu Menu { EnsureMenuEditorService(value); if (menuEditorService != null) + { menuEditorService.SetMenu(value); + } } if (_heightDelta == 0) @@ -320,7 +322,10 @@ private void ApplyAutoScaling(SizeF baseVar, Form form) Size newVar = new Size((int)Math.Round(newVarF.Width), (int)Math.Round(newVarF.Height)); // We save a significant amount of time by bailing early if there's no work to be done if (baseVar.Equals(newVar)) + { return; + } + float percY = ((float)newVar.Height) / ((float)baseVar.Height); float percX = ((float)newVar.Width) / ((float)baseVar.Width); try diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ParentControlDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ParentControlDesigner.cs index 55c676db641..3a9b515f6bf 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ParentControlDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ParentControlDesigner.cs @@ -125,9 +125,15 @@ internal void AddControl(Control newChild, IDictionary defaultValues) bool hasSize = (defaultValues != null && defaultValues.Contains("Size")); if (hasLocation) + { location = (Point)defaultValues["Location"]; + } + if (hasSize) + { size = (Size)defaultValues["Size"]; + } + if (defaultValues != null && defaultValues.Contains("Offset")) { offset = (Size)defaultValues["Offset"]; diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/SelectionUIService.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/SelectionUIService.cs index 5571bd87281..9de7e5b260c 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/SelectionUIService.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/SelectionUIService.cs @@ -1122,7 +1122,9 @@ void ISelectionUIService.EndDrag(bool cancel) finally { if (trans != null) + { trans.Commit(); + } // Reset the selection. This will re-display our selection. Visible = _savedVisible; ((ISelectionUIService)this).SyncSelection(); @@ -1143,7 +1145,9 @@ object[] ISelectionUIService.FilterSelection(object[] components, SelectionRules { object[] selection = null; if (components == null) + { return new object[0]; + } // Mask off any selection object that doesn't adhere to the given ruleset. We can ignore this if the ruleset is zero, as all components would be accepted. if (selectionRules != SelectionRules.None) { @@ -1439,7 +1443,10 @@ public virtual void DoPaint(Graphics gr) // If we're not visible, then there's nothing to do... // if ((GetRules() & SelectionRules.Visible) == SelectionRules.None) + { return; + } + bool fActive = false; if (_selUIsvc._selSvc != null) { @@ -1561,12 +1568,21 @@ private int GetHandleIndexOfPoint(Point pt) { // Something on the left side. if (pt.Y >= _outerRect.Y && pt.Y <= _innerRect.Y) + { return 0; // top left + } + if (pt.Y >= _innerRect.Y + _innerRect.Height && pt.Y <= _outerRect.Y + _outerRect.Height) + { return 5; // bottom left + } + if (pt.Y >= _outerRect.Y + (_outerRect.Height - GRABHANDLE_HEIGHT) / 2 && pt.Y <= _outerRect.Y + (_outerRect.Height + GRABHANDLE_HEIGHT) / 2) + { return 3; // middle left + } + return -1; // unknown hit } @@ -1575,10 +1591,16 @@ private int GetHandleIndexOfPoint(Point pt) // something on the top Debug.Assert(!(pt.X >= _outerRect.X && pt.X <= _innerRect.X), "Should be handled by left top check"); if (pt.X >= _innerRect.X + _innerRect.Width && pt.X <= _outerRect.X + _outerRect.Width) + { return 2; // top right + } + if (pt.X >= _outerRect.X + (_outerRect.Width - GRABHANDLE_WIDTH) / 2 && pt.X <= _outerRect.X + (_outerRect.Width + GRABHANDLE_WIDTH) / 2) + { return 1; // top middle + } + return -1; // unknown hit } @@ -1587,10 +1609,16 @@ private int GetHandleIndexOfPoint(Point pt) // something on the right side Debug.Assert(!(pt.Y >= _outerRect.Y && pt.Y <= _innerRect.Y), "Should be handled by top right check"); if (pt.Y >= _innerRect.Y + _innerRect.Height && pt.Y <= _outerRect.Y + _outerRect.Height) + { return 7; // bottom right + } + if (pt.Y >= _outerRect.Y + (_outerRect.Height - GRABHANDLE_HEIGHT) / 2 && pt.Y <= _outerRect.Y + (_outerRect.Height + GRABHANDLE_HEIGHT) / 2) + { return 4; // middle right + } + return -1; // unknown hit } @@ -1602,7 +1630,10 @@ private int GetHandleIndexOfPoint(Point pt) Debug.Assert(!(pt.X >= _innerRect.X + _innerRect.Width && pt.X <= _outerRect.X + _outerRect.Width), "Should be handled by right bottom check"); if (pt.X >= _outerRect.X + (_outerRect.Width - GRABHANDLE_WIDTH) / 2 && pt.X <= _outerRect.X + (_outerRect.Width + GRABHANDLE_WIDTH) / 2) + { return 6; // bottom middle + } + return -1; // unknown hit } return -1; // unknown hit @@ -1775,9 +1806,15 @@ public virtual bool UpdateSize() bool sizeChanged = false; // Short circuit common cases if (_handler == null) + { return false; + } + if ((GetRules() & SelectionRules.Visible) == SelectionRules.None) + { return false; + } + _innerRect = _handler.GetComponentBounds(_component); if (!_innerRect.IsEmpty) { @@ -1786,7 +1823,10 @@ public virtual bool UpdateSize() if (_outerRect.IsEmpty || !_outerRect.Equals(rcOuterNew)) { if (!_outerRect.IsEmpty) + { Invalidate(); + } + _outerRect = rcOuterNew; Invalidate(); if (_region != null) @@ -1851,7 +1891,10 @@ public override void DoPaint(Graphics gr) { // If we're not visible, then there's nothing to do... if ((GetRules() & SelectionRules.Visible) == SelectionRules.None) + { return; + } + Rectangle glyphBounds = new Rectangle(_outerRect.X, _outerRect.Y, CONTAINER_WIDTH, CONTAINER_HEIGHT); ControlPaint.DrawContainerGrabHandle(gr, glyphBounds); } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemDesigner.cs index ccc4eff043c..2aabd56ba41 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemDesigner.cs @@ -690,7 +690,10 @@ public override void InitializeNewComponent(IDictionary defaultValues) if (site != null && Component is ToolStripDropDownItem) { if (defaultValues == null) + { defaultValues = new Hashtable(); + } + defaultValues["Text"] = site.Name; IComponent component = Component; PropertyDescriptor pd = TypeDescriptor.GetProperties(ToolStripItem)["Text"]; diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs index 1a3de93ccae..1442886c95f 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs @@ -2675,7 +2675,9 @@ public override void OnDragDrop(Glyph g, DragEventArgs e) { IComponentChangeService changeSvc = (IComponentChangeService)primaryItem.Site.GetService(typeof(IComponentChangeService)); if (changeSvc != null) + { changeSvc.OnComponentChanging(ownerItem, TypeDescriptor.GetProperties(ownerItem)["DropDownItems"]); + } // If we are copying, then we want to make a copy of the components we are dragging if (copy) { @@ -2762,7 +2764,10 @@ public override void OnDragDrop(Glyph g, DragEventArgs e) finally { if (changeParent != null) + { changeParent.Commit(); + } + changeParent = null; } } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/UndoEngine.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/UndoEngine.cs index 220f7331c07..e1f4c724dea 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/UndoEngine.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/UndoEngine.cs @@ -662,7 +662,9 @@ public virtual void ComponentAdded(ComponentEventArgs e) // do nothing } else + { AddEvent(new AddRemoveUndoEvent(UndoEngine, e.Component, true)); + } if (_ignoreAddingList != null) { diff --git a/src/System.Windows.Forms/src/Common/System/LocalAppContext.cs b/src/System.Windows.Forms/src/Common/System/LocalAppContext.cs index cbe86158398..958e2bca6b4 100644 --- a/src/System.Windows.Forms/src/Common/System/LocalAppContext.cs +++ b/src/System.Windows.Forms/src/Common/System/LocalAppContext.cs @@ -17,9 +17,14 @@ internal partial class LocalAppContext internal static bool GetCachedSwitchValue(string switchName, ref int switchValue) { if (switchValue < 0) + { return false; + } + if (switchValue > 0) + { return true; + } return GetCachedSwitchValueInternal(switchName, ref switchValue); } diff --git a/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs b/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs index 14af9fb37ae..ae76b504629 100644 --- a/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs +++ b/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs @@ -167,7 +167,10 @@ private void InitializeDataNode(string basePath) // recognize this. It's not very clean but this should work. Type nodeType = null; if (!string.IsNullOrEmpty(nodeInfo.TypeName)) // can be null if we have a string (default for string is TypeName == null) + { nodeType = internalTypeResolver.GetType(nodeInfo.TypeName, false, true); + } + if (nodeType != null && nodeType.Equals(typeof(ResXFileRef))) { // we have a fileref, split the value data and populate the fields @@ -1089,7 +1092,9 @@ public Type GetType(string name, bool throwOnError, bool ignoreCase) } if (result != null) + { break; + } } } diff --git a/src/System.Windows.Forms/src/System/Resources/ResXFileRef.cs b/src/System.Windows.Forms/src/System/Resources/ResXFileRef.cs index 723d8bd2cc5..8e270240073 100644 --- a/src/System.Windows.Forms/src/System/Resources/ResXFileRef.cs +++ b/src/System.Windows.Forms/src/System/Resources/ResXFileRef.cs @@ -216,20 +216,32 @@ internal static string[] ParseResxFileRefString(string stringValue) { int lastIndexOfQuote = stringValue.LastIndexOf('\"'); if (lastIndexOfQuote - 1 < 0) + { throw new ArgumentException(nameof(stringValue)); + } + fileName = stringValue.Substring(1, lastIndexOfQuote - 1); // remove the quotes in" ..... " if (lastIndexOfQuote + 2 > stringValue.Length) + { throw new ArgumentException(nameof(stringValue)); + } + remainingString = stringValue.Substring(lastIndexOfQuote + 2); } else { int nextSemiColumn = stringValue.IndexOf(';'); if (nextSemiColumn == -1) + { throw new ArgumentException(nameof(stringValue)); + } + fileName = stringValue.Substring(0, nextSemiColumn); if (nextSemiColumn + 1 > stringValue.Length) + { throw new ArgumentException(nameof(stringValue)); + } + remainingString = stringValue.Substring(nextSemiColumn + 1); } string[] parts = remainingString.Split(';'); diff --git a/src/System.Windows.Forms/src/System/Resources/ResXResourceWriter.cs b/src/System.Windows.Forms/src/System/Resources/ResXResourceWriter.cs index 8e0f45987b9..fd5060d4600 100644 --- a/src/System.Windows.Forms/src/System/Resources/ResXResourceWriter.cs +++ b/src/System.Windows.Forms/src/System/Resources/ResXResourceWriter.cs @@ -443,7 +443,9 @@ private void AddDataRow(string elementName, string name, string value) private void AddDataRow(string elementName, string name, string value, string type, string mimeType, string comment) { if (hasBeenSaved) + { throw new InvalidOperationException(SR.ResXResourceWriterSaved); + } string alias = null; if (!string.IsNullOrEmpty(type) && elementName == DataStr) @@ -612,7 +614,10 @@ private string GetFullName(string typeName) { int indexStart = typeName.IndexOf(','); if (indexStart == -1) + { return null; + } + return typeName.Substring(indexStart + 2); } @@ -655,7 +660,9 @@ private string TypeNameWithAssembly(Type type) public void Generate() { if (hasBeenSaved) + { throw new InvalidOperationException(SR.ResXResourceWriterSaved); + } hasBeenSaved = true; Debug.WriteLineIf(ResValueProviderSwitch.TraceVerbose, "writing XML"); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleObject.cs index 1e060cf73eb..5ddb2460c77 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleObject.cs @@ -1984,7 +1984,10 @@ public virtual AccessibleObject Navigate(AccessibleNavigation navdir) try { if (!SysNavigate((int)navdir, NativeMethods.CHILDID_SELF, out object retObject)) + { retObject = systemIAccessible.accNavigate((int)navdir, NativeMethods.CHILDID_SELF); + } + return WrapIAccessible(retObject); } catch (COMException e) when (e.ErrorCode == NativeMethods.DISP_E_MEMBERNOTFOUND) @@ -2581,7 +2584,10 @@ private void NextFromSystemReordered(int n, IntPtr rgvar, int[] ns, int[] newOrd for (i = 0; i < n && currentChild < newOrder.Length; ++i) { if (!GotoItem(owner.systemIEnumVariant, newOrder[currentChild], GetAddressOfVariantAtIndex(rgvar, i))) + { break; + } + ++currentChild; Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "AccessibleObject.IEV.Next: adding sys child " + currentChild + " of " + newOrder.Length); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs index 4a1847b3b13..4eb21fcbc99 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs @@ -648,7 +648,10 @@ public static string SafeTopLevelCaptionFormat set { if (value == null) + { value = string.Empty; + } + safeTopLevelCaptionSuffix = value; } } @@ -1283,7 +1286,9 @@ private static void RaiseExit() { Delegate exit = eventHandlers[EVENT_APPLICATIONEXIT]; if (exit != null) + { ((EventHandler)exit)(null, EventArgs.Empty); + } } } @@ -3120,7 +3125,10 @@ internal int GetId() internal CultureInfo GetCulture() { if (culture == null || culture.LCID != SafeNativeMethods.GetThreadLocale()) + { culture = new CultureInfo(SafeNativeMethods.GetThreadLocale()); + } + return culture; } @@ -3251,7 +3259,9 @@ private void OnDomainUnload(object sender, EventArgs e) internal void OnThreadException(Exception t) { if (GetState(STATE_INTHREADEXCEPTION)) + { return; + } SetState(STATE_INTHREADEXCEPTION, true); try @@ -4358,7 +4368,9 @@ private bool Callback(IntPtr hWnd, IntPtr lparam) { Control c = Control.FromHandle(hWnd); if (c == null) + { add = false; + } } if (add) @@ -4415,7 +4427,9 @@ internal void Enable(bool state) IntPtr hWnd = windows[i]; Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ComponentManager : Changing enabled on window: " + hWnd.ToString() + " : " + state.ToString()); if (UnsafeNativeMethods.IsWindow(new HandleRef(null, hWnd))) + { SafeNativeMethods.EnableWindow(new HandleRef(null, hWnd), state); + } } // OpenFileDialog is not returning the focus the way other dialogs do. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs index caeccf87819..ac0cbc3d3a5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs @@ -1017,7 +1017,10 @@ private bool OwnWindow() private IntPtr GetHandleNoCreate() { if (IsHandleCreated) + { return Handle; + } + return IntPtr.Zero; } @@ -1042,7 +1045,10 @@ private static ISelectionService GetSelectionService(Control ctl) private void AddSelectionHandler() { if (axState[addedSelectionHandler]) + { return; + } + ISelectionService iss = GetSelectionService(); if (iss != null) { @@ -1073,7 +1079,10 @@ private void OnComponentRename(object sender, ComponentRenameEventArgs e) private bool RemoveSelectionHandler() { if (!axState[addedSelectionHandler]) + { return false; + } + ISelectionService iss = GetSelectionService(); if (iss != null) { @@ -1130,9 +1139,14 @@ public override ISite Site base.Site = value; bool newuMode = IsUserMode(); if (!newuMode) + { GetOcxCreate(); + } + if (reAddHandler) + { AddSelectionHandler(); + } SyncRenameNotification(value != null); @@ -1146,7 +1160,9 @@ public override ISite Site TransitionUpTo(OC_INPLACE); ContainerControl f = ContainingControl; if (f != null && f.Visible && Visible) + { MakeVisibleWithShow(); + } } if (olduMode != newuMode && !IsHandleCreated && !axState[disposed]) @@ -1194,7 +1210,10 @@ protected override void OnLostFocus(EventArgs e) private void OnNewSelection(object sender, EventArgs e) { if (IsUserMode()) + { return; + } + ISelectionService iss = GetSelectionService(); // What we care about: // if we are uiactive and we lose selection, then we need to uideactivate ourselves... @@ -1307,7 +1326,10 @@ private static int SetupLogPixels(bool force) { IntPtr hDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef); if (hDC == IntPtr.Zero) + { return NativeMethods.E_FAIL; + } + logPixelsX = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, hDC), NativeMethods.LOGPIXELSX); logPixelsY = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, hDC), NativeMethods.LOGPIXELSY); Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "log pixels are: " + logPixelsX.ToString(CultureInfo.InvariantCulture) + " " + logPixelsY.ToString(CultureInfo.InvariantCulture)); @@ -1420,7 +1442,10 @@ protected override Rectangle GetScaledBounds(Rectangle bounds, SizeF factor, Bou private void SetObjectRects(Rectangle bounds) { if (GetOcState() < OC_INPLACE) + { return; + } + GetInPlaceObject().SetObjectRects(FillInRect(new NativeMethods.COMRECT(), bounds), GetClipRect(new NativeMethods.COMRECT())); } @@ -1434,7 +1459,9 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound // IOleObject will "give a Catastrophic error" in SetObjectRects( ). if (GetAxState(AxHost.handlePosRectChanged)) + { return; + } axState[handlePosRectChanged] = true; @@ -1496,11 +1523,17 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound private bool CheckSubclassing() { if (!IsHandleCreated || wndprocAddr == IntPtr.Zero) + { return true; + } + IntPtr handle = Handle; IntPtr currentWndproc = UnsafeNativeMethods.GetWindowLong(new HandleRef(this, handle), NativeMethods.GWL_WNDPROC); if (currentWndproc == wndprocAddr) + { return true; + } + if (unchecked((int)(long)SendMessage(REGMSG_MSG, 0, 0)) == REGMSG_RETVAL) { wndprocAddr = currentWndproc; @@ -1795,7 +1828,9 @@ private void EnsureWindowPresent() } } if (IsHandleCreated) + { return; + } if (ParentInternal != null) { // ==> we are in a valid state @@ -1861,7 +1896,9 @@ protected override void SetVisibleCore(bool value) { SetState(STATE_VISIBLE, value); if (Visible != oldVisible) + { OnVisibleChanged(EventArgs.Empty); + } } } } @@ -2133,7 +2170,9 @@ public State OcxState axState[ocxStateSet] = true; if (value == null) + { return; + } if (storageType != STG_UNKNOWN && storageType != value.type) { @@ -2142,7 +2181,9 @@ public State OcxState } if (ocxState == value) + { return; + } ocxState = value; @@ -2203,7 +2244,10 @@ private State CreateNewOcxState(State oldOcxState) case STG_STORAGE: Debug.Assert(oldOcxState != null, "we got to have an old state which holds out scribble storage..."); if (oldOcxState != null) + { return oldOcxState.RefreshStorage(iPersistStorage); + } + return null; default: Debug.Fail("unknown storage type."); @@ -2327,7 +2371,10 @@ private ContainerControl FindContainerControlInternal() private bool IsDirty() { if (GetOcState() < OC_RUNNING) + { return false; + } + Debug.Assert(storageType != STG_UNKNOWN, "if we are loaded, out storage type must be set!"); if (axState[valueChanged]) @@ -2338,7 +2385,9 @@ private bool IsDirty() #if DEBUG if (AxAlwaysSaveSwitch.Enabled) + { return true; + } #endif int hr = NativeMethods.E_FAIL; switch (storageType) @@ -2432,7 +2481,10 @@ private object GetAmbientProperty(int dispid) case NativeMethods.ActiveX.DISPID_AMBIENT_DISPLAYNAME: string rval = GetParentContainer().GetNameForControl(this); if (rval == null) + { rval = string.Empty; + } + return rval; case NativeMethods.ActiveX.DISPID_AMBIENT_LOCALEID: Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "asked for localeid"); @@ -2443,11 +2495,19 @@ private object GetAmbientProperty(int dispid) while (ctl != null) { if (ctl.RightToLeft == System.Windows.Forms.RightToLeft.No) + { return false; + } + if (ctl.RightToLeft == System.Windows.Forms.RightToLeft.Yes) + { return true; + } + if (ctl.RightToLeft == System.Windows.Forms.RightToLeft.Inherit) + { ctl = ctl.Parent; + } } return null; default: @@ -2556,7 +2616,10 @@ private string GetLicenseKey(Guid clsid) catch (COMException e) { if (e.ErrorCode == E_NOINTERFACE.ErrorCode) + { return null; + } + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Failed to get the license key: " + e.ToString()); axState[needLicenseKey] = false; } @@ -2652,7 +2715,10 @@ private CategoryAttribute GetCategoryForDispid(int dispid) { NativeMethods.ICategorizeProperties icp = GetCategorizeProperties(); if (icp == null) + { return null; + } + CategoryAttribute rval = null; int propcat = 0; try @@ -2671,7 +2737,9 @@ private CategoryAttribute GetCategoryForDispid(int dispid) { rval = (CategoryAttribute)objectDefinedCategoryNames[key]; if (rval != null) + { return rval; + } } int hr = icp.GetCategoryName(cat, CultureInfo.CurrentCulture.LCID, out string name); @@ -2722,7 +2790,10 @@ public void InvokeEditMode() Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "invoking EditMode for " + ToString()); Debug.Assert((flags & AxFlags.PreventEditMode) == 0, "edit mode should have been disabled"); if (editMode != EDITM_NONE) + { return; + } + AddSelectionHandler(); editMode = EDITM_HOST; SetSelectionStyle(2); @@ -2810,13 +2881,19 @@ PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { if (editorBaseType != typeof(ComponentEditor)) + { return null; + } if (editor != null) + { return editor; + } if (editor == null && HasPropertyPages()) + { editor = new AxComponentEditor(); + } return editor; } @@ -2902,7 +2979,9 @@ private PropertyDescriptorCollection FillProperties(Attribute[] attributes) ArrayList retProps = new ArrayList(); if (properties == null) + { properties = new Hashtable(); + } if (propertyInfos == null) { @@ -2911,7 +2990,9 @@ private PropertyDescriptorCollection FillProperties(Attribute[] attributes) PropertyInfo[] propInfos = GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo propInfo in propInfos) + { propertyInfos.Add(propInfo.Name, propInfo); + } } PropertyDescriptorCollection baseProps = TypeDescriptor.GetProperties(this, null, true); @@ -2933,7 +3014,9 @@ private PropertyDescriptorCollection FillProperties(Attribute[] attributes) // We do not support "write-only" properties that some activex controls support. if (propInfo != null && !propInfo.CanRead) + { continue; + } if (!properties.ContainsKey(propName)) { @@ -3009,7 +3092,9 @@ private PropertyDescriptorCollection FillProperties(Attribute[] attributes) if (removeList != null) { foreach (object prop in removeList) + { retProps.Remove(prop); + } } } } @@ -3348,14 +3433,20 @@ protected virtual void DetachSink() private bool CanShowPropertyPages() { if (GetOcState() < OC_RUNNING) + { return false; + } + return (GetOcx() is NativeMethods.ISpecifyPropertyPages); } public bool HasPropertyPages() { if (!CanShowPropertyPages()) + { return false; + } + NativeMethods.ISpecifyPropertyPages ispp = (NativeMethods.ISpecifyPropertyPages)GetOcx(); try { @@ -3364,7 +3455,9 @@ public bool HasPropertyPages() { ispp.GetPages(uuids); if (uuids.cElems > 0) + { return true; + } } finally { @@ -3407,11 +3500,15 @@ public void MakeDirty() { ISite isite = Site; if (isite == null) + { return; + } IComponentChangeService ccs = (IComponentChangeService)isite.GetService(typeof(IComponentChangeService)); if (ccs == null) + { return; + } ccs.OnComponentChanging(this, null); @@ -3421,9 +3518,15 @@ public void MakeDirty() public void ShowPropertyPages() { if (ParentInternal == null) + { return; + } + if (!ParentInternal.IsHandleCreated) + { return; + } + ShowPropertyPages(ParentInternal); } @@ -3432,14 +3535,19 @@ public void ShowPropertyPages(Control control) try { if (!CanShowPropertyPages()) + { return; + } + NativeMethods.ISpecifyPropertyPages ispp = (NativeMethods.ISpecifyPropertyPages)GetOcx(); NativeMethods.tagCAUUID uuids = new NativeMethods.tagCAUUID(); try { ispp.GetPages(uuids); if (uuids.cElems <= 0) + { return; + } } catch { @@ -3450,13 +3558,17 @@ public void ShowPropertyPages(Control control) IDesignerHost host = null; if (Site != null) + { host = (IDesignerHost)Site.GetService(typeof(IDesignerHost)); + } DesignerTransaction trans = null; try { if (host != null) + { trans = host.CreateTransaction(SR.AXEditProperties); + } string name = null; object o = GetOcx(); @@ -3466,13 +3578,19 @@ public void ShowPropertyPages(Control control) finally { if (oleSite != null) + { ((UnsafeNativeMethods.IPropertyNotifySink)oleSite).OnChanged(NativeMethods.MEMBERID_NIL); + } if (trans != null) + { trans.Commit(); + } if (uuids.pElems != IntPtr.Zero) + { Marshal.FreeCoTaskMem(uuids.pElems); + } } } catch (Exception t) @@ -3615,13 +3733,17 @@ protected override void WndProc(ref Message m) case Interop.WindowMessages.WM_KEYUP: if (axState[processingKeyUp]) + { break; + } axState[processingKeyUp] = true; try { if (PreProcessControlMessage(ref m) != PreProcessControlState.MessageProcessed) + { DefWndProc(ref m); + } } finally { @@ -3722,7 +3844,9 @@ private void AttachWindow(IntPtr hwnd) // Choose the setBounds unless it is smaller than the default bounds. if (setExtent.Width < ocxExtent.Width || setExtent.Height < ocxExtent.Height) + { Bounds = new Rectangle(location.X, location.Y, ocxExtent.Width, ocxExtent.Height); + } else { Size newSize = SetExtent(setExtent.Width, setExtent.Height); @@ -4064,7 +4188,9 @@ internal void OnOcxCreate() internal void StartEvents() { if (connectionPoint != null) + { return; + } object nativeObject = host.GetOcx(); @@ -4110,7 +4236,9 @@ int UnsafeNativeMethods.IGetVBAObject.GetObject(ref Guid riid, UnsafeNativeMetho Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in GetObject"); if (rval == null || riid.Equals(Guid.Empty)) + { return NativeMethods.E_INVALIDARG; + } if (riid.Equals(ivbformat_Guid)) { @@ -4207,7 +4335,9 @@ object IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder binder int dispid = int.Parse(name.Substring(8, endIndex - 8), CultureInfo.InvariantCulture); object ambient = host.GetAmbientProperty(dispid); if (ambient != null) + { return ambient; + } } throw E_FAIL; @@ -4240,7 +4370,9 @@ int UnsafeNativeMethods.IOleControlSite.GetExtendedControl(out object ppDisp) Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in GetExtendedControl " + host.ToString()); ppDisp = host.GetParentContainer().GetProxyForControl(host); if (ppDisp == null) + { return NativeMethods.E_NOTIMPL; + } return NativeMethods.S_OK; } @@ -4249,7 +4381,9 @@ int UnsafeNativeMethods.IOleControlSite.TransformCoords(NativeMethods._POINTL pP { int hr = SetupLogPixels(false); if (NativeMethods.Failed(hr)) + { return hr; + } if ((dwFlags & NativeMethods.ActiveX.XFORMCOORDS_HIMETRICTOCONTAINER) != 0) { @@ -4379,7 +4513,9 @@ int UnsafeNativeMethods.IOleClientSite.ShowObject() host.TransitionUpTo(OC_INPLACE); } if (host.GetOcState() < OC_INPLACE) + { return NativeMethods.S_OK; + } if (NativeMethods.Succeeded(host.GetInPlaceObject().GetWindow(out IntPtr hwnd))) { @@ -4537,7 +4673,9 @@ int UnsafeNativeMethods.IOleInPlaceSite.OnPosRectChange(NativeMethods.COMRECT lp // bool useRect = true; if (AxHost.windowsMediaPlayer_Clsid.Equals(host.clsid)) + { useRect = host.GetAxState(AxHost.handlePosRectChanged); + } if (useRect) { @@ -4560,7 +4698,9 @@ void UnsafeNativeMethods.IPropertyNotifySink.OnChanged(int dispid) // To prevent this kind of recursion, we check to see if we are already inside a OnChanged() call. // if (host.NoComponentChangeEvents != 0) + { return; + } host.NoComponentChangeEvents++; try @@ -4654,7 +4794,10 @@ private int HM2Pix(int hm, int logP) private bool QuickActivate() { if (!(instance is UnsafeNativeMethods.IQuickActivate)) + { return false; + } + UnsafeNativeMethods.IQuickActivate iqa = (UnsafeNativeMethods.IQuickActivate)instance; UnsafeNativeMethods.tagQACONTAINER qaContainer = new UnsafeNativeMethods.tagQACONTAINER(); @@ -4739,7 +4882,10 @@ private bool GetControlEnabled() internal override bool CanSelectCore() { if (!GetControlEnabled() || axState[rejectSelection]) + { return false; + } + return base.CanSelectCore(); } @@ -4958,7 +5104,9 @@ private UnsafeNativeMethods.IOleInPlaceObject GetInPlaceObject() #if DEBUG if (iOleInPlaceObject is UnsafeNativeMethods.IOleInPlaceObjectWindowless) + { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, GetType().FullName + " Can also be a Windowless control."); + } #endif //DEBUG } return iOleInPlaceObject; @@ -5037,7 +5185,10 @@ private static object GetPICTDESCFromPicture(Image image) protected static object GetIPictureFromPicture(Image image) { if (image == null) + { return null; + } + object pictdesc = GetPICTDESCFromPicture(image); return UnsafeNativeMethods.OleCreateIPictureIndirect(pictdesc, ref ipicture_Guid, true); } @@ -5049,7 +5200,10 @@ protected static object GetIPictureFromPicture(Image image) protected static object GetIPictureFromCursor(Cursor cursor) { if (cursor == null) + { return null; + } + NativeMethods.PICTDESCicon pictdesc = new NativeMethods.PICTDESCicon(Icon.FromHandle(cursor.Handle)); return UnsafeNativeMethods.OleCreateIPictureIndirect(pictdesc, ref ipicture_Guid, true); } @@ -5061,7 +5215,10 @@ protected static object GetIPictureFromCursor(Cursor cursor) protected static object GetIPictureDispFromPicture(Image image) { if (image == null) + { return null; + } + object pictdesc = GetPICTDESCFromPicture(image); return UnsafeNativeMethods.OleCreateIPictureDispIndirect(pictdesc, ref ipictureDisp_Guid, true); } @@ -5073,7 +5230,10 @@ protected static object GetIPictureDispFromPicture(Image image) protected static Image GetPictureFromIPicture(object picture) { if (picture == null) + { return null; + } + IntPtr hPal = IntPtr.Zero; UnsafeNativeMethods.IPicture pict = (UnsafeNativeMethods.IPicture)picture; int type = pict.GetPictureType(); @@ -5097,7 +5257,10 @@ protected static Image GetPictureFromIPicture(object picture) protected static Image GetPictureFromIPictureDisp(object picture) { if (picture == null) + { return null; + } + IntPtr hPal = IntPtr.Zero; UnsafeNativeMethods.IPictureDisp pict = (UnsafeNativeMethods.IPictureDisp)picture; int type = pict.PictureType; @@ -5203,10 +5366,14 @@ protected static uint GetOleColorFromColor(Color color) protected static object GetIFontFromFont(Font font) { if (font == null) + { return null; + } if (font.Unit != GraphicsUnit.Point) + { throw new ArgumentException(SR.AXFontUnitNotPoint, "font"); + } try { @@ -5227,7 +5394,9 @@ protected static object GetIFontFromFont(Font font) protected static Font GetFontFromIFont(object font) { if (font == null) + { return null; + } UnsafeNativeMethods.IFont oleFont = (UnsafeNativeMethods.IFont)font; try @@ -5235,7 +5404,9 @@ protected static Font GetFontFromIFont(object font) Font f = Font.FromHfont(oleFont.GetHFont()); if (f.Unit != GraphicsUnit.Point) + { f = new Font(f.Name, f.SizeInPoints, f.Style, GraphicsUnit.Point, f.GdiCharSet, f.GdiVerticalFont); + } return f; } @@ -5254,10 +5425,14 @@ protected static Font GetFontFromIFont(object font) protected static object GetIFontDispFromFont(Font font) { if (font == null) + { return null; + } if (font.Unit != GraphicsUnit.Point) + { throw new ArgumentException(SR.AXFontUnitNotPoint, "font"); + } SafeNativeMethods.IFontDisp rval = SafeNativeMethods.OleCreateIFontDispIndirect(GetFONTDESCFromFont(font), ref ifontDisp_Guid); return rval; @@ -5287,19 +5462,29 @@ protected static Font GetFontFromIFontDisp(object font) try { if (oleFont.Bold) + { style |= FontStyle.Bold; + } if (oleFont.Italic) + { style |= FontStyle.Italic; + } if (oleFont.Underline) + { style |= FontStyle.Underline; + } if (oleFont.Strikethrough) + { style |= FontStyle.Strikeout; + } if ((int)oleFont.Weight >= 700) // bold + { style |= FontStyle.Bold; + } f = new Font(oleFont.Name, (float)oleFont.Size / (float)10000, style, GraphicsUnit.Point, (byte)oleFont.Charset); return f; @@ -5436,11 +5621,15 @@ int UnsafeNativeMethods.IVBFormat.Format(ref object var, IntPtr pszFormat, IntPt { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in Format"); if (result == null) + { return NativeMethods.E_INVALIDARG; + } result[0] = 0; if (lpBuffer == IntPtr.Zero || cpBuffer < 2) + { return NativeMethods.E_INVALIDARG; + } IntPtr pbstr = IntPtr.Zero; int hr = UnsafeNativeMethods.VarFormat(ref var, new HandleRef(null, pszFormat), firstD, firstW, 32 /* VAR_FORMAT_NOSUBSTITUTE */, ref pbstr); @@ -5493,7 +5682,9 @@ private EnumUnknown(object[] arr, int loc) : this(arr) unsafe int UnsafeNativeMethods.IEnumUnknown.Next(int celt, IntPtr rgelt, IntPtr pceltFetched) { if (pceltFetched != IntPtr.Zero) + { Marshal.WriteInt32(pceltFetched, 0, 0); + } if (celt < 0) { @@ -5519,7 +5710,9 @@ unsafe int UnsafeNativeMethods.IEnumUnknown.Next(int celt, IntPtr rgelt, IntPtr } if (pceltFetched != IntPtr.Zero) + { Marshal.WriteInt32(pceltFetched, 0, fetched); + } if (fetched != celt) { @@ -5578,7 +5771,9 @@ internal AxContainer(ContainerControl parent) Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in constructor. Parent created : " + parent.Created.ToString()); this.parent = parent; if (parent.Created) + { FormCreated(); + } } // IReflect methods: @@ -5711,7 +5906,9 @@ internal void AddControl(Control ctl) lock (this) { if (containerCache.Contains(ctl)) + { throw new ArgumentException(string.Format(SR.AXDuplicateControl, GetNameForControl(ctl)), "ctl"); + } containerCache.Add(ctl, ctl); @@ -5855,9 +6052,15 @@ internal UnsafeNativeMethods.IEnumUnknown EnumControls(Control ctl, int dwOleCon { l = new ArrayList(); if (last == -1 && ctls != null) + { last = ctls.Length; + } + if (ctl != null) + { MaybeAdd(l, ctl, selected, dwOleContF, false); + } + for (int i = first; i < last; i++) { MaybeAdd(l, ctls[i], selected, dwOleContF, false); @@ -5885,12 +6088,17 @@ internal UnsafeNativeMethods.IEnumUnknown EnumControls(Control ctl, int dwOleCon private void MaybeAdd(ArrayList l, Control ctl, bool selected, int dwOleContF, bool ignoreBelong) { if (!ignoreBelong && ctl != parent && !GetControlBelongs(ctl)) + { return; + } + if (selected) { ISelectionService iss = GetSelectionService(ctl); if (iss == null || !iss.GetComponentSelected(this)) + { return; + } } AxHost hostctl = ctl as AxHost; if (hostctl != null && (dwOleContF & NativeMethods.ActiveX.OLECONTF_EMBEDDINGS) != 0) @@ -5901,7 +6109,9 @@ private void MaybeAdd(ArrayList l, Control ctl, bool selected, int dwOleContF, b { object item = GetProxyForControl(ctl); if (item != null) + { l.Add(item); + } } } @@ -5952,7 +6162,9 @@ private void FillComponentsTable(IContainer container) private void GetAllChildren(Control ctl) { if (ctl == null) + { return; + } if (components == null) { @@ -5960,7 +6172,9 @@ private void GetAllChildren(Control ctl) } if (ctl != parent && !components.Contains(ctl)) + { components.Add(ctl, ctl); + } foreach (Control c in ctl.Controls) { @@ -5992,7 +6206,10 @@ private IContainer GetParentIsDesigned() { ISite site = parent.Site; if (site != null && site.DesignMode) + { return site.Container; + } + return null; } @@ -6046,7 +6263,10 @@ internal static AxContainer FindContainerForControl(Control ctl) if (axctl != null) { if (axctl.container != null) + { return axctl.container; + } + ContainerControl f = axctl.ContainingControl; if (f != null) { @@ -6150,7 +6370,9 @@ internal void OnUIDeactivate(AxHost site) { #if DEBUG if (siteUIActive != null) + { Debug.Assert(siteUIActive == site, "deactivating when not active..."); + } #endif // DEBUG siteUIActive = null; @@ -6175,7 +6397,9 @@ internal void OnUIActivate(AxHost site) // site. This causes the assert below to fire. // if (siteUIActive == site) + { return; + } if (siteUIActive != null && siteUIActive != site) { @@ -6207,7 +6431,10 @@ private void ListAxControls(ArrayList list, bool fuseOcx) { Hashtable components = GetComponents(); if (components == null) + { return; + } + Control[] ctls = new Control[components.Keys.Count]; components.Keys.CopyTo(ctls, 0); if (ctls != null) @@ -6251,7 +6478,10 @@ internal void ControlCreated(AxHost invoker) internal void FormCreated() { if (formAlreadyCreated) + { return; + } + formAlreadyCreated = true; ArrayList l = new ArrayList(); ListAxControls(l, false); @@ -6274,7 +6504,10 @@ int UnsafeNativeMethods.IOleContainer.ParseDisplayName(object pbc, string pszDis { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in ParseDisplayName"); if (ppmkOut != null) + { ppmkOut[0] = null; + } + return NativeMethods.E_NOTIMPL; } @@ -6341,7 +6574,10 @@ internal void OnExitEditMode(AxHost ctl) { Debug.Assert(ctlInEditMode == null || ctlInEditMode == ctl, "who is exiting edit mode?"); if (ctlInEditMode == null || ctlInEditMode != ctl) + { return; + } + ctlInEditMode = null; } @@ -6483,7 +6719,9 @@ object UnsafeNativeMethods.IGetOleObject.GetOleObject(ref Guid riid) { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in GetOleObject for proxy"); if (!riid.Equals(ioleobject_Guid)) + { throw E_INVALIDARG; + } Control ctl = GetP(); if (ctl != null && ctl is AxHost) @@ -6498,7 +6736,9 @@ int UnsafeNativeMethods.IGetVBAObject.GetObject(ref Guid riid, UnsafeNativeMetho { Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in GetObject for proxy"); if (rval == null || riid.Equals(Guid.Empty)) + { return NativeMethods.E_INVALIDARG; + } if (riid.Equals(ivbformat_Guid)) { @@ -6958,7 +7198,9 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul return ms.ToArray(); } else + { return new byte[0]; + } } return base.ConvertTo(context, culture, value, destinationType); @@ -7165,7 +7407,10 @@ internal UnsafeNativeMethods.IPropertyBag GetPropBag() internal UnsafeNativeMethods.IStorage GetStorage() { if (storage == null) + { CreateStorage(); + } + return storage; } @@ -7175,7 +7420,10 @@ internal UnsafeNativeMethods.IStream GetStream() { Debug.Assert(buffer != null, "gotta have the buffer already..."); if (buffer == null) + { return null; + } + ms = new MemoryStream(buffer); } else @@ -7205,7 +7453,9 @@ private void InitializeFromStream(Stream ids) length = br.ReadInt32(); if (length > 0) + { buffer = br.ReadBytes(length); + } } private void InitializeBufferFromStream(Stream ids) @@ -7214,7 +7464,9 @@ private void InitializeBufferFromStream(Stream ids) length = br.ReadInt32(); if (length > 0) + { buffer = br.ReadBytes(length); + } } internal State RefreshStorage(UnsafeNativeMethods.IPersistStorage iPersistStorage) @@ -7222,7 +7474,10 @@ internal State RefreshStorage(UnsafeNativeMethods.IPersistStorage iPersistStorag Debug.Assert(storage != null, "how can we not have a storage object?"); Debug.Assert(iLockBytes != null, "how can we have a storage w/o ILockBytes?"); if (storage == null || iLockBytes == null) + { return null; + } + iPersistStorage.Save(storage, true); storage.Commit(0); iPersistStorage.HandsOffStorage(); @@ -7342,7 +7597,9 @@ int UnsafeNativeMethods.IPropertyBag.Read(string pszPropName, ref object pVar, U Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "Reading property " + pszPropName + " from OCXState propertybag."); if (!bag.Contains(pszPropName)) + { return NativeMethods.E_INVALIDARG; + } pVar = bag[pszPropName]; Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "\tValue=" + ((pVar == null) ? "" : pVar.ToString())); @@ -7558,7 +7815,10 @@ private Guid GetPropertyPage(int dispid) { NativeMethods.IPerPropertyBrowsing ippb = owner.GetPerPropertyBrowsing(); if (ippb == null) + { return Guid.Empty; + } + if (NativeMethods.Succeeded(ippb.MapPropertyToPage(dispid, out Guid rval))) { return rval; @@ -7670,7 +7930,9 @@ public override bool ShouldSerializeValue(object o) internal void UpdateAttributes() { if (updateAttrs.Count == 0) + { return; + } ArrayList attributes = new ArrayList(AttributeArray); foreach (Attribute attr in updateAttrs) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs b/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs index 9b4f3fc88f8..a30db80cefd 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs @@ -548,13 +548,24 @@ protected virtual void RefreshItemsCore() if (!DesignMode) { if (MoveFirstItem != null) + { moveFirstItem.Enabled = (position > 1); + } + if (MovePreviousItem != null) + { movePreviousItem.Enabled = (position > 1); + } + if (MoveNextItem != null) + { moveNextItem.Enabled = (position < count); + } + if (MoveLastItem != null) + { moveLastItem.Enabled = (position < count); + } if (AddNewItem != null) { @@ -573,9 +584,14 @@ protected virtual void RefreshItemsCore() } if (PositionItem != null) + { positionItem.Enabled = (position > 0 && count > 0); + } + if (CountItem != null) + { countItem.Enabled = (count > 0); + } } // Update current position indicator diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/BindingSource.cs b/src/System.Windows.Forms/src/System/Windows/Forms/BindingSource.cs index 0981ac842ba..7e276a55456 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/BindingSource.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/BindingSource.cs @@ -1150,7 +1150,9 @@ private void ResetList() // GetListFromEnumerable returns null if there are no elements // Don't consider it a list of enumerables in this case if (bindingList != null) + { _listExtractedFromEnumerable = true; + } } // If it's not an IList, IListSource or IEnumerable if (bindingList == null) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Button.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Button.cs index f33ca443552..9480888e50a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Button.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Button.cs @@ -270,7 +270,9 @@ protected override void OnClick(EventArgs e) { Form form = FindForm(); if (form != null) + { form.DialogResult = dialogResult; + } // accessibility stuff diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonBaseAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonBaseAdapter.cs index 9b093cf4d3a..bf819e85f4f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonBaseAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonBaseAdapter.cs @@ -666,8 +666,10 @@ internal virtual void DrawImageCore(Graphics graphics, Image image, Rectangle im try { if (!Control.Enabled) + { // need to specify width and height ControlPaint.DrawImageDisabled(graphics, image, imageBounds, Control.BackColor, true /* unscaled image*/); + } else { graphics.DrawImage(image, imageBounds.X, imageBounds.Y, image.Width, image.Height); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckableControlBaseAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckableControlBaseAdapter.cs index 2b6b401a1fc..935c013f495 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckableControlBaseAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckableControlBaseAdapter.cs @@ -102,7 +102,10 @@ internal static double GetDpiScaleRatio(Graphics g, Control control) } if (g == null) + { return 1.0F; + } + return g.DpiX / 96; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/CheckBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/CheckBox.cs index 7a001e0a926..e6f2547d83c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/CheckBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/CheckBox.cs @@ -552,7 +552,9 @@ protected virtual void OnCheckedChanged(EventArgs e) EventHandler handler = (EventHandler)Events[EVENT_CHECKEDCHANGED]; if (handler != null) + { handler(this, e); + } } /// @@ -567,7 +569,9 @@ protected virtual void OnCheckStateChanged(EventArgs e) EventHandler handler = (EventHandler)Events[EVENT_CHECKSTATECHANGED]; if (handler != null) + { handler(this, e); + } } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/CheckedListBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/CheckedListBox.cs index b1796bd4c53..9dbb554de85 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/CheckedListBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/CheckedListBox.cs @@ -497,7 +497,10 @@ public CheckState GetItemCheckState(int index) { if (index < 0 || index >= Items.Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } + return CheckedItems.GetCheckedState(index); } @@ -543,7 +546,9 @@ private void LbnSelChange() // make sure we have a valid index, otherwise we're going to // fail ahead... if (index < 0 || index >= Items.Count) + { return; + } // Send an accessibility notification // @@ -762,7 +767,9 @@ protected override void OnDrawItem(DrawItemEventArgs e) float[] tabStops = new float[15]; float tabOffset = -(idealCheckSize + (scaledListItemStartPosition * 2)); for (int i = 1; i < tabStops.Length; i++) + { tabStops[i] = tabDistance; + } //( if (Math.Abs(tabOffset) < tabDistance) @@ -920,7 +927,9 @@ protected override void OnKeyPress(KeyPressEventArgs e) protected virtual void OnItemCheck(ItemCheckEventArgs ice) { if (onItemCheck != null) + { onItemCheck(this, ice); + } } protected override void OnMeasureItem(MeasureItemEventArgs e) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ColorDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ColorDialog.cs index f896fe837d3..751bd208695 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ColorDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ColorDialog.cs @@ -147,9 +147,14 @@ public int[] CustomColors { int length = value == null ? 0 : Math.Min(value.Length, 16); if (length > 0) + { Array.Copy(value, 0, customColors, 0, length); + } + for (int i = length; i < 16; i++) + { customColors[i] = 0x00FFFFFF; + } } } @@ -293,14 +298,23 @@ protected override bool RunDialog(IntPtr hwndOwner) int flags = Options | (NativeMethods.CC_RGBINIT | NativeMethods.CC_ENABLEHOOK); // Our docs say AllowFullOpen takes precedence over FullOpen; ChooseColor implements the opposite if (!AllowFullOpen) + { flags &= ~NativeMethods.CC_FULLOPEN; + } + cc.Flags = flags; cc.lpfnHook = hookProcPtr; if (!SafeNativeMethods.ChooseColor(cc)) + { return false; + } + if (cc.rgbResult != ColorTranslator.ToWin32(color)) + { color = ColorTranslator.FromOle(cc.rgbResult); + } + Marshal.Copy(custColorPtr, customColors, 0, 16); return true; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeader.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeader.cs index c45ffdcbfaa..60c2c520e7d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeader.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeader.cs @@ -194,7 +194,10 @@ public int Index get { if (listview != null) + { return listview.GetColumnIndex(this); + } + return -1; } } @@ -459,7 +462,9 @@ public int Width { width = value; if (listview != null) + { listview.SetColumnWidth(Index, ColumnHeaderAutoResizeStyle.None); + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs index 236e332b825..ce8a6238491 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs @@ -418,7 +418,9 @@ protected override CreateParams CreateParams cp.Style |= NativeMethods.WS_VSCROLL | NativeMethods.CBS_HASSTRINGS | NativeMethods.CBS_AUTOHSCROLL; cp.ExStyle |= NativeMethods.WS_EX_CLIENTEDGE; if (!integralHeight) + { cp.Style |= NativeMethods.CBS_NOINTEGRALHEIGHT; + } switch (DropDownStyle) { @@ -679,7 +681,10 @@ public override bool Focused get { if (base.Focused) + { return true; + } + IntPtr focus = UnsafeNativeMethods.GetFocus(); return focus != IntPtr.Zero && ((childEdit != null && focus == childEdit.Handle) || (childListBox != null && focus == childListBox.Handle)); } @@ -907,12 +912,17 @@ public int MaxLength set { if (value < 0) + { value = 0; + } + if (MaxLength != value) { Properties.SetInteger(PropMaxLength, value); if (IsHandleCreated) + { SendMessage(NativeMethods.CB_LIMITTEXT, value, 0); + } } } } @@ -1177,9 +1187,13 @@ public object SelectedItem { // if (value != null) + { x = itemsCollection.IndexOf(value); + } else + { SelectedIndex = -1; + } } if (x != -1) @@ -1204,7 +1218,10 @@ public string SelectedText get { if (DropDownStyle == ComboBoxStyle.DropDownList) + { return ""; + } + return Text.Substring(SelectionStart, SelectionLength); } set @@ -1396,7 +1413,9 @@ public override string Text set { if (DropDownStyle == ComboBoxStyle.DropDownList && !IsHandleCreated && !string.IsNullOrEmpty(value) && FindStringExact(value) == -1) + { return; + } base.Text = value; object selectedItem = null; @@ -1988,7 +2007,10 @@ private void ChildWndProc(ref Message m) if (ContextMenu != null || ContextMenuStrip != null) + { CaptureInternal = true; + } + DefChildWndProc(ref m); //the up gets fired from "Combo-box's WndPrc --- So Convert these Coordinates to Combobox coordianate... // @@ -2011,7 +2033,10 @@ private void ChildWndProc(ref Message m) //set the mouse capture .. this is the Child Wndproc.. // if (ContextMenu != null) + { CaptureInternal = false; + } + DefChildWndProc(ref m); //the up gets fired from "Combo-box's WndPrc --- So Convert these Coordinates to Combobox coordianate... // @@ -2674,7 +2699,9 @@ protected virtual void OnDrawItem(DrawItemEventArgs e) { DrawItemEventHandler handler = (DrawItemEventHandler)Events[EVENT_DRAWITEM]; if (handler != null) + { handler(this, e); + } } /// @@ -2686,7 +2713,9 @@ protected virtual void OnDropDown(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_DROPDOWN]; if (handler != null) + { handler(this, e); + } // Notify collapsed/expanded property change. AccessibilityObject.RaiseAutomationPropertyChangedEvent( @@ -2765,7 +2794,9 @@ protected virtual void OnMeasureItem(MeasureItemEventArgs e) { MeasureItemEventHandler handler = (MeasureItemEventHandler)Events[EVENT_MEASUREITEM]; if (handler != null) + { handler(this, e); + } } /// @@ -2815,7 +2846,9 @@ protected virtual void OnSelectionChangeCommitted(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_SELECTIONCHANGECOMMITTED]; if (handler != null) + { handler(this, e); + } // The user selects a list item or selects an item and then closes the list. // It indicates that the user's selection is to be processed but should not @@ -2836,7 +2869,9 @@ protected override void OnSelectedIndexChanged(EventArgs e) base.OnSelectedIndexChanged(e); EventHandler handler = (EventHandler)Events[EVENT_SELECTEDINDEXCHANGED]; if (handler != null) + { handler(this, e); + } if (dropDownWillBeClosed) { @@ -2897,7 +2932,9 @@ protected virtual void OnSelectedItemChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_SELECTEDITEMCHANGED]; if (handler != null) + { handler(this, e); + } } /// @@ -2907,7 +2944,9 @@ protected virtual void OnDropDownStyleChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_DROPDOWNSTYLE]; if (handler != null) + { handler(this, e); + } } /// @@ -2919,7 +2958,9 @@ protected override void OnParentBackColorChanged(EventArgs e) { base.OnParentBackColorChanged(e); if (DropDownStyle == ComboBoxStyle.Simple) + { Invalidate(); + } } /// @@ -3102,7 +3143,10 @@ protected override void OnDataSourceChanged(EventArgs e) EndUpdate(); } if (!Sorted && Created) + { base.OnDataSourceChanged(e); + } + RefreshItems(); } @@ -3123,7 +3167,9 @@ protected virtual void OnDropDownClosed(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_DROPDOWNCLOSED]; if (handler != null) + { handler(this, e); + } // Need to announce the focus on combo-box with new selected value on drop-down close. // If do not do this focus in Level 3 stays on list item of unvisible list. @@ -3152,7 +3198,9 @@ protected virtual void OnTextUpdate(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_TEXTUPDATE]; if (handler != null) + { handler(this, e); + } } protected override bool ProcessCmdKey(ref Message msg, Keys keyData) @@ -4273,12 +4321,16 @@ public int Compare(object item1, object item2) if (item1 == null) { if (item2 == null) + { return 0; //both null, then they are equal + } return -1; //item1 is null, but item2 is valid (greater) } if (item2 == null) + { return 1; //item2 is null, so item 1 is greater + } string itemName1 = comboBox.GetItemText(item1); string itemName2 = comboBox.GetItemText(item2); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Command.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Command.cs index 4941ad5170d..7ab83a4fd26 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Command.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Command.cs @@ -61,21 +61,36 @@ protected static void AssignID(Command cmd) int icmdLim = cmds.Length; if (icmdTry >= icmdLim) + { icmdTry = 0; + } // First look for an empty slot (starting at icmdTry). for (icmd = icmdTry; icmd < icmdLim; icmd++) + { if (null == cmds[icmd]) + { goto FindSlotComplete; + } + } + for (icmd = 0; icmd < icmdTry; icmd++) + { if (null == cmds[icmd]) + { goto FindSlotComplete; + } + } // All slots have Command objects in them. Look for a command // with a null referent. for (icmd = 0; icmd < icmdLim; icmd++) + { if (null == cmds[icmd].Target) + { goto FindSlotComplete; + } + } // Grow the array. icmd = cmds.Length; @@ -88,7 +103,9 @@ protected static void AssignID(Command cmd) for (icmd = 0; icmd < icmdLim; icmd++) { if (null == cmds[icmd] || null == cmds[icmd].Target) + { goto FindSlotComplete; + } } throw new ArgumentException(SR.CommandIdNotAllocated); } @@ -114,7 +131,10 @@ public static bool DispatchID(int id) { Command cmd = GetCommandFromID(id); if (null == cmd) + { return false; + } + return cmd.Invoke(); } @@ -126,7 +146,10 @@ protected static void Dispose(Command cmd) { cmd.Target = null; if (cmds[cmd.id - idMin] == cmd) + { cmds[cmd.id - idMin] = null; + } + cmd.id = 0; } } @@ -135,7 +158,9 @@ protected static void Dispose(Command cmd) public virtual void Dispose() { if (id >= idMin) + { Dispose(this); + } } public static Command GetCommandFromID(int id) @@ -143,10 +168,16 @@ public static Command GetCommandFromID(int id) lock (internalSyncObject) { if (null == cmds) + { return null; + } + int i = id - idMin; if (i < 0 || i >= cmds.Length) + { return null; + } + return cmds[i]; } } @@ -155,8 +186,9 @@ public virtual bool Invoke() { object target = Target; if (!(target is ICommandExecutor)) + { return false; - ((ICommandExecutor)target).Execute(); + } ((ICommandExecutor)target).Execute(); return true; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentManagerBroker.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentManagerBroker.cs index bd58013ac31..7c123f1a66c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentManagerBroker.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentManagerBroker.cs @@ -278,9 +278,15 @@ private UnsafeNativeMethods.IMsoComponent Component get { if (_trackingComponent != null) + { return _trackingComponent; + } + if (_activeComponent != null) + { return _activeComponent; + } + return null; } } @@ -496,7 +502,10 @@ bool UnsafeNativeMethods.IMsoComponentManager.FRevokeComponent(IntPtr dwComponen { int dwLocalComponentID = unchecked((int)(long)dwComponentID); if (_original == null) + { return false; + } + if (_components == null || dwLocalComponentID <= 0 || !_components.ContainsKey(dwLocalComponentID)) { return false; @@ -536,7 +545,9 @@ bool UnsafeNativeMethods.IMsoComponentManager.FRevokeComponent(IntPtr dwComponen bool UnsafeNativeMethods.IMsoComponentManager.FUpdateComponentRegistration(IntPtr dwComponentID, NativeMethods.MSOCRINFOSTRUCT info) { if (_original == null) + { return false; + } // We assume that all winforms domains use the same registration. return _original.FUpdateComponentRegistration(_componentId, info); } @@ -546,7 +557,9 @@ bool UnsafeNativeMethods.IMsoComponentManager.FOnComponentActivate(IntPtr dwComp int dwLocalComponentID = unchecked((int)(long)dwComponentID); if (_original == null) + { return false; + } // Activation requres us to store the currently active component. We will send data to it if (_components == null || dwLocalComponentID <= 0 || !_components.ContainsKey(dwLocalComponentID)) { @@ -600,7 +613,10 @@ bool UnsafeNativeMethods.IMsoComponentManager.FSetTrackingComponent(IntPtr dwCom void UnsafeNativeMethods.IMsoComponentManager.OnComponentEnterState(IntPtr dwComponentID, int uStateID, int uContext, int cpicmExclude, int rgpicmExclude, int dwReserved) { if (_original == null) + { return; + } + if (uContext == NativeMethods.MSOCM.msoccontextAll || uContext == NativeMethods.MSOCM.msoccontextMine) { if (_components != null) @@ -618,7 +634,10 @@ void UnsafeNativeMethods.IMsoComponentManager.OnComponentEnterState(IntPtr dwCom bool UnsafeNativeMethods.IMsoComponentManager.FOnComponentExitState(IntPtr dwComponentID, int uStateID, int uContext, int cpicmExclude, int rgpicmExclude) { if (_original == null) + { return false; + } + if (uContext == NativeMethods.MSOCM.msoccontextAll || uContext == NativeMethods.MSOCM.msoccontextMine) { if (_components != null) @@ -636,21 +655,30 @@ bool UnsafeNativeMethods.IMsoComponentManager.FOnComponentExitState(IntPtr dwCom bool UnsafeNativeMethods.IMsoComponentManager.FInState(int uStateID, IntPtr pvoid) { if (_original == null) + { return false; + } + return _original.FInState(uStateID, pvoid); } bool UnsafeNativeMethods.IMsoComponentManager.FContinueIdle() { if (_original == null) + { return false; + } + return _original.FContinueIdle(); } bool UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, int reason, int pvLoopData) { if (_original == null) + { return false; + } + return _original.FPushMessageLoop(_componentId, reason, pvLoopData); } @@ -671,7 +699,10 @@ bool UnsafeNativeMethods.IMsoComponentManager.FGetParentComponentManager(out Uns bool UnsafeNativeMethods.IMsoComponentManager.FGetActiveComponent(int dwgac, UnsafeNativeMethods.IMsoComponent[] ppic, NativeMethods.MSOCRINFOSTRUCT info, int dwReserved) { if (_original == null) + { return false; + } + if (_original.FGetActiveComponent(dwgac, ppic, info, dwReserved)) { // We got a component. See if it's our proxy, and if it is, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Properties.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Properties.cs index aa3cddadece..53841089858 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Properties.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Properties.cs @@ -113,7 +113,9 @@ public Com2Properties(object obj, Com2PropertyDescriptor[] props, int defaultInd dbgObjClass = "(null)"; } if (DbgCom2PropertiesSwitch.TraceVerbose) + { Debug.WriteLine("Creating Com2Properties for object " + dbgObjName + ", class=" + dbgObjClass); + } #endif // set up our variables @@ -193,7 +195,9 @@ public object TargetObject { #if DEBUG if (DbgCom2PropertiesSwitch.TraceVerbose) + { Debug.WriteLine("CheckValid called on dead object!"); + } #endif return null; } @@ -238,7 +242,9 @@ public Com2PropertyDescriptor[] Properties #if DEBUG if (DbgCom2PropertiesSwitch.TraceVerbose) + { Debug.WriteLine("Returning prop array for object " + dbgObjName + ", class=" + dbgObjClass); + } #endif return props; } @@ -303,7 +309,9 @@ public void AddExtendedBrowsingHandlers(Hashtable handlers) { #if DEBUG if (DbgCom2PropertiesSwitch.TraceVerbose) + { Debug.WriteLine("Adding browsing handler type " + handler.Interface.Name + " to object " + dbgObjName + ", class=" + dbgObjClass); + } #endif // allow the handler to attach itself to the appropriate properties // @@ -322,7 +330,9 @@ public void Dispose() { #if DEBUG if (DbgCom2PropertiesSwitch.TraceVerbose) + { Debug.WriteLine("Disposing property manager for " + dbgObjName + ", class=" + dbgObjClass); + } #endif if (props != null) @@ -553,7 +563,9 @@ internal bool CheckValid(bool checkVersions, bool callDispose) // #if DEBUG if (DbgCom2PropertiesSwitch.TraceVerbose) + { Debug.WriteLine("Disposing reference to object " + dbgObjName + ", class=" + dbgObjClass + " (weakRef " + (weakObjRef == null ? "null" : "dead") + ")"); + } #endif Dispose(); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs index 9019722d925..a94ca3aacc5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs @@ -899,7 +899,9 @@ public override object GetEditor(Type editorBaseType) public object GetNativeValue(object component) { if (component == null) + { return null; + } if (component is ICustomTypeDescriptor) { @@ -907,7 +909,9 @@ public object GetNativeValue(object component) } if (component == null || !Marshal.IsComObject(component) || !(component is UnsafeNativeMethods.IDispatch)) + { return null; + } UnsafeNativeMethods.IDispatch pDisp = (UnsafeNativeMethods.IDispatch)component; object[] pVarResult = new object[1]; @@ -1086,7 +1090,9 @@ protected void OnGetBaseAttributes(GetAttributesEvent e) GetAttributesEventHandler handler = (GetAttributesEventHandler)Events[EventGetBaseAttributes]; if (handler != null) + { handler(this, e); + } } finally { @@ -1121,7 +1127,9 @@ protected void OnGetDynamicAttributes(GetAttributesEvent e) com2props.AlwaysValid = com2props.CheckValid(); GetAttributesEventHandler handler = (GetAttributesEventHandler)Events[EventGetDynamicAttributes]; if (handler != null) + { handler(this, e); + } } finally { @@ -1144,7 +1152,9 @@ protected void OnGetTypeConverterAndTypeEditor(GetTypeConverterAndTypeEditorEven com2props.AlwaysValid = com2props.CheckValid(); GetTypeConverterAndTypeEditorEventHandler handler = (GetTypeConverterAndTypeEditorEventHandler)Events[EventGetTypeConverterAndTypeEditor]; if (handler != null) + { handler(this, e); + } } finally { @@ -1187,7 +1197,9 @@ private void RaiseGetBoolValueEvent(object key, GetBoolValueEvent e) com2props.AlwaysValid = com2props.CheckValid(); GetBoolValueEventHandler handler = (GetBoolValueEventHandler)Events[key]; if (handler != null) + { handler(this, e); + } } finally { @@ -1205,7 +1217,9 @@ private void RaiseCom2Event(object key, EventArgs e) com2props.AlwaysValid = com2props.CheckValid(); Com2EventHandler handler = (Com2EventHandler)Events[key]; if (handler != null) + { handler(this, e); + } } finally { @@ -1223,7 +1237,9 @@ private void RaiseGetNameItemEvent(object key, GetNameItemEvent e) com2props.AlwaysValid = com2props.CheckValid(); GetNameItemEventHandler handler = (GetNameItemEventHandler)Events[key]; if (handler != null) + { handler(this, e); + } } finally { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs index 63eeb26f5bf..a6cf56e35e8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs @@ -687,7 +687,9 @@ internal void FocusActiveControlInternal() #if DEBUG // Things really get ugly if you try to pop up an assert dialog here if (activeControl != null && !Contains(activeControl)) + { Debug.WriteLine("ActiveControl is not a child of this ContainerControl"); + } #endif if (activeControl != null && activeControl.Visible) @@ -1043,9 +1045,14 @@ private void PerformAutoScale(bool includedBounds, bool excludedBounds) SizeF excluded = SizeF.Empty; if (includedBounds) + { included = AutoScaleFactor; + } + if (excludedBounds) + { excluded = AutoScaleFactor; + } Scale(included, excluded, this); autoScaleDimensions = CurrentAutoScaleDimensions; @@ -1180,9 +1187,14 @@ internal override void Scale(SizeF includedFactor, SizeF excludedFactor, Control ISite parentSite = ParentInternal.Site; if (site != null) + { dt = site.DesignMode; + } + if (parentSite != null) + { parentDt = parentSite.DesignMode; + } if (dt && !parentDt) { @@ -1233,7 +1245,10 @@ protected override bool ProcessDialogChar(char charCode) // ContainerControl parent = GetContainerControl() as ContainerControl; if (parent != null && charCode != ' ' && ProcessMnemonic(charCode)) + { return true; + } + return base.ProcessDialogChar(charCode); } @@ -1258,7 +1273,10 @@ protected override bool ProcessDialogKey(Keys keyData) { case Keys.Tab: if (ProcessTabKey((keyData & Keys.Shift) == Keys.None)) + { return true; + } + break; case Keys.Left: case Keys.Right: @@ -1266,7 +1284,10 @@ protected override bool ProcessDialogKey(Keys keyData) case Keys.Down: if (ProcessArrowKey(keyCode == Keys.Right || keyCode == Keys.Down)) + { return true; + } + break; } } @@ -1395,7 +1416,10 @@ protected internal override bool ProcessMnemonic(char charCode) protected virtual bool ProcessTabKey(bool forward) { if (SelectNextControl(activeControl, forward, true, true, false)) + { return true; + } + return false; } @@ -1558,7 +1582,10 @@ internal void UpdateFocusedControl() { Control parent = nextControlDown.ParentInternal; if (parent == this || parent == pathControl) + { break; + } + nextControlDown = nextControlDown.ParentInternal; } @@ -1882,17 +1909,30 @@ public virtual bool ValidateChildren(ValidationConstraints validationConstraints private bool ValidateThroughAncestor(Control ancestorControl, bool preventFocusChangeOnError) { if (ancestorControl == null) + { ancestorControl = this; + } + if (state[stateValidating]) + { return false; + } + if (unvalidatedControl == null) + { unvalidatedControl = focusedControl; + } //return true for a Container Control with no controls to validate.... // if (unvalidatedControl == null) + { return true; + } + if (!ancestorControl.IsDescendant(unvalidatedControl)) + { return false; + } state[stateValidating] = true; bool cancel = false; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenu.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenu.cs index bc2bb83dcb3..a913172e9f8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenu.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenu.cs @@ -215,10 +215,14 @@ public void Show(Control control, Point pos, LeftRightAlignment alignment) private void Show(Control control, Point pos, int flags) { if (control == null) + { throw new ArgumentNullException(nameof(control)); + } if (!control.IsHandleCreated || !control.Visible) + { throw new ArgumentException(SR.ContextMenuInvalidParent, "control"); + } sourceControl = control; 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 5748dc6e353..c98250d3fcf 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs @@ -1158,19 +1158,27 @@ public virtual Color BackColor { 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.TransparentBackColorNotAllowed); + } Color c = BackColor; if (!value.IsEmpty || Properties.ContainsObject(PropBackColor)) @@ -1953,14 +1961,21 @@ protected virtual CreateParams CreateParams } 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. @@ -2156,7 +2171,9 @@ public virtual Cursor Cursor AmbientProperties ambient = AmbientPropertiesService; if (ambient != null && ambient.Cursor != null) + { return ambient.Cursor; + } return localDefault; } @@ -2183,7 +2200,9 @@ public virtual Cursor Cursor 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(Interop.WindowMessages.WM_SETCURSOR, Handle, (IntPtr)NativeMethods.HTCLIENT); + } } if (!resolvedCursor.Equals(value)) @@ -2539,11 +2558,17 @@ public bool Enabled { // 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 @@ -2867,13 +2892,19 @@ public virtual Color ForeColor { AmbientProperties ambient = AmbientPropertiesService; if (ambient != null) + { c = ambient.ForeColor; + } } if (!c.IsEmpty) + { return c; + } else + { return DefaultForeColor; + } } set @@ -2900,9 +2931,13 @@ public event EventHandler ForeColorChanged private Font GetParentFont() { if (ParentInternal != null && ParentInternal.CanAccessProperties) + { return ParentInternal.Font; + } else + { return null; + } } [EditorBrowsable(EditorBrowsableState.Advanced)] @@ -3518,11 +3553,20 @@ public static Keys ModifierKeys // 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; } } @@ -3539,15 +3583,30 @@ public static MouseButtons MouseButtons // 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; } } @@ -3905,7 +3964,9 @@ internal bool RequiredScalingEnabled byte scaling = (byte)(requiredScaling & RequiredScalingMask); requiredScaling = scaling; if (value) + { requiredScaling |= RequiredScalingEnabledMask; + } } } @@ -4202,7 +4263,10 @@ public bool TabStop { TabStopInternal = value; if (IsHandleCreated) + { SetWindowStyle(NativeMethods.WS_TABSTOP, value); + } + OnTabStopChanged(EventArgs.Empty); } } @@ -4807,7 +4871,10 @@ internal virtual string WindowText set { if (value == null) + { value = string.Empty; + } + if (!WindowText.Equals(value)) { if (IsHandleCreated) @@ -5585,7 +5652,9 @@ internal virtual void AssignParent(Control value) SetState(STATE_CHECKEDHOST, false); if (ParentInternal != null) + { ParentInternal.LayoutEngine.InitLayout(this, BoundsSpecified.All); + } } [SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnParentChangedDescr))] @@ -5650,7 +5719,10 @@ internal void BeginUpdateInternal() return; } if (updateCount == 0) + { SendMessage(Interop.WindowMessages.WM_SETREDRAW, 0, 0); + } + updateCount++; } @@ -5966,7 +6038,9 @@ internal void CreateControl(bool fIgnoreVisible) try { if (!IsHandleCreated) + { CreateHandle(); + } // must snapshot this array because // z-order updates from Windows may rearrange it! @@ -5993,7 +6067,9 @@ internal void CreateControl(bool fIgnoreVisible) finally { if (!createdOK) + { state &= (~STATE_CREATED); + } } OnCreateControl(); } @@ -6135,7 +6211,9 @@ protected override void Dispose(bool disposing) ResetBindings(); if (IsHandleCreated) + { DestroyHandle(); + } if (parent != null) { @@ -6452,7 +6530,9 @@ internal void RaiseCreateHandleEvent(EventArgs e) { EventHandler handler = (EventHandler)Events[EventHandleCreated]; if (handler != null) + { handler(this, e); + } } /// @@ -6464,7 +6544,9 @@ protected void RaiseKeyEvent(object key, KeyEventArgs e) { KeyEventHandler handler = (KeyEventHandler)Events[key]; if (handler != null) + { handler(this, e); + } } /// @@ -6476,7 +6558,9 @@ protected void RaiseMouseEvent(object key, MouseEventArgs e) { MouseEventHandler handler = (MouseEventHandler)Events[key]; if (handler != null) + { handler(this, e); + } } /// @@ -6778,11 +6862,17 @@ 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() @@ -6937,7 +7027,9 @@ int IComparer.Compare(object x, object y) int delta = hx.newOrder - hy.newOrder; if (delta == 0) + { delta = hx.oldOrder - hy.oldOrder; + } return delta; } @@ -7792,7 +7884,10 @@ internal bool IsDescendant(Control descendant) while (control != null) { if (control == this) + { return true; + } + control = control.ParentInternal; } return false; @@ -7869,7 +7964,10 @@ 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) { @@ -7932,10 +8030,16 @@ public static bool IsMnemonic(char charCode, string text) 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)) @@ -8043,7 +8147,9 @@ private object MarshaledInvoke(Control caller, Delegate method, object[] args, b if (SafeNativeMethods.GetWindowThreadProcessId(new HandleRef(this, Handle), out int pid) == SafeNativeMethods.GetCurrentThreadId()) { if (synchronous) + { syncSameThread = true; + } } // Store the compressed stack information from the thread that is calling the Invoke() @@ -8918,7 +9024,9 @@ protected virtual void OnClick(EventArgs e) Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventClick]; if (handler != null) + { handler(this, e); + } } [EditorBrowsable(EditorBrowsableState.Advanced)] @@ -8941,7 +9049,9 @@ protected virtual void OnControlAdded(ControlEventArgs e) Contract.Requires(e != null); ControlEventHandler handler = (ControlEventHandler)Events[EventControlAdded]; if (handler != null) + { handler(this, e); + } } /// @@ -8953,7 +9063,9 @@ protected virtual void OnControlRemoved(ControlEventArgs e) Contract.Requires(e != null); ControlEventHandler handler = (ControlEventHandler)Events[EventControlRemoved]; if (handler != null) + { handler(this, e); + } } /// @@ -9063,7 +9175,9 @@ protected virtual void OnHandleCreated(EventArgs e) EventHandler handler = (EventHandler)Events[EventHandleCreated]; if (handler != null) + { handler(this, e); + } if (IsHandleCreated) { @@ -9127,7 +9241,9 @@ protected virtual void OnHandleDestroyed(EventArgs e) Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventHandleDestroyed]; if (handler != null) + { handler(this, e); + } UpdateReflectParent(false); @@ -9160,7 +9276,9 @@ protected virtual void OnHandleDestroyed(EventArgs e) { text = Text; if (text != null && text.Length == 0) + { text = null; + } } SetAcceptDrops(false); } @@ -9187,7 +9305,9 @@ protected virtual void OnDoubleClick(EventArgs e) Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventDoubleClick]; if (handler != null) + { handler(this, e); + } } /// @@ -9205,7 +9325,9 @@ protected virtual void OnDragEnter(DragEventArgs drgevent) Contract.Requires(drgevent != null); DragEventHandler handler = (DragEventHandler)Events[EventDragEnter]; if (handler != null) + { handler(this, drgevent); + } } /// @@ -9218,7 +9340,9 @@ protected virtual void OnDragOver(DragEventArgs drgevent) Contract.Requires(drgevent != null); DragEventHandler handler = (DragEventHandler)Events[EventDragOver]; if (handler != null) + { handler(this, drgevent); + } } /// @@ -9231,7 +9355,9 @@ protected virtual void OnDragLeave(EventArgs e) Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventDragLeave]; if (handler != null) + { handler(this, e); + } } /// @@ -9244,7 +9370,9 @@ protected virtual void OnDragDrop(DragEventArgs drgevent) Contract.Requires(drgevent != null); DragEventHandler handler = (DragEventHandler)Events[EventDragDrop]; if (handler != null) + { handler(this, drgevent); + } } /// @@ -9258,7 +9386,9 @@ protected virtual void OnGiveFeedback(GiveFeedbackEventArgs gfbevent) Contract.Requires(gfbevent != null); GiveFeedbackEventHandler handler = (GiveFeedbackEventHandler)Events[EventGiveFeedback]; if (handler != null) + { handler(this, gfbevent); + } } [EditorBrowsable(EditorBrowsableState.Advanced)] @@ -9267,7 +9397,9 @@ protected virtual void OnEnter(EventArgs e) Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventEnter]; if (handler != null) + { handler(this, e); + } } /// @@ -9302,7 +9434,9 @@ protected virtual void OnGotFocus(EventArgs e) EventHandler handler = (EventHandler)Events[EventGotFocus]; if (handler != null) + { handler(this, e); + } } /// @@ -9359,7 +9493,9 @@ protected virtual void OnInvalidated(InvalidateEventArgs e) InvalidateEventHandler handler = (InvalidateEventHandler)Events[EventInvalidated]; if (handler != null) + { handler(this, e); + } } /// @@ -9371,7 +9507,9 @@ protected virtual void OnKeyDown(KeyEventArgs e) Contract.Requires(e != null); KeyEventHandler handler = (KeyEventHandler)Events[EventKeyDown]; if (handler != null) + { handler(this, e); + } } /// @@ -9383,7 +9521,9 @@ protected virtual void OnKeyPress(KeyPressEventArgs e) Contract.Requires(e != null); KeyPressEventHandler handler = (KeyPressEventHandler)Events[EventKeyPress]; if (handler != null) + { handler(this, e); + } } /// @@ -9395,7 +9535,9 @@ protected virtual void OnKeyUp(KeyEventArgs e) Contract.Requires(e != null); KeyEventHandler handler = (KeyEventHandler)Events[EventKeyUp]; if (handler != null) + { handler(this, e); + } } /// @@ -9416,7 +9558,9 @@ protected virtual void OnLayout(LayoutEventArgs levent) } LayoutEventHandler handler = (LayoutEventHandler)Events[EventLayout]; if (handler != null) + { handler(this, levent); + } bool parentRequiresLayout = LayoutEngine.Layout(this, levent); @@ -9457,7 +9601,9 @@ protected virtual void OnLeave(EventArgs e) Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventLeave]; if (handler != null) + { handler(this, e); + } } [EditorBrowsable(EditorBrowsableState.Advanced)] @@ -9484,7 +9630,9 @@ protected virtual void OnLostFocus(EventArgs e) EventHandler handler = (EventHandler)Events[EventLostFocus]; if (handler != null) + { handler(this, e); + } } protected virtual void OnMarginChanged(EventArgs e) @@ -9492,7 +9640,9 @@ protected virtual void OnMarginChanged(EventArgs e) Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventMarginChanged]; if (handler != null) + { handler(this, e); + } } /// @@ -9504,7 +9654,9 @@ protected virtual void OnMouseDoubleClick(MouseEventArgs e) Contract.Requires(e != null); MouseEventHandler handler = (MouseEventHandler)Events[EventMouseDoubleClick]; if (handler != null) + { handler(this, e); + } } /// @@ -9516,7 +9668,9 @@ protected virtual void OnMouseClick(MouseEventArgs e) Contract.Requires(e != null); MouseEventHandler handler = (MouseEventHandler)Events[EventMouseClick]; if (handler != null) + { handler(this, e); + } } /// @@ -9528,7 +9682,9 @@ protected virtual void OnMouseCaptureChanged(EventArgs e) Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventMouseCaptureChanged]; if (handler != null) + { handler(this, e); + } } /// @@ -9540,7 +9696,9 @@ protected virtual void OnMouseDown(MouseEventArgs e) Contract.Requires(e != null); MouseEventHandler handler = (MouseEventHandler)Events[EventMouseDown]; if (handler != null) + { handler(this, e); + } } /// @@ -9552,7 +9710,9 @@ protected virtual void OnMouseEnter(EventArgs e) Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventMouseEnter]; if (handler != null) + { handler(this, e); + } } /// @@ -9564,7 +9724,9 @@ protected virtual void OnMouseLeave(EventArgs e) Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventMouseLeave]; if (handler != null) + { handler(this, e); + } } /// @@ -9612,7 +9774,9 @@ protected virtual void OnMouseHover(EventArgs e) Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventMouseHover]; if (handler != null) + { handler(this, e); + } } /// @@ -9624,7 +9788,9 @@ protected virtual void OnMouseMove(MouseEventArgs e) Contract.Requires(e != null); MouseEventHandler handler = (MouseEventHandler)Events[EventMouseMove]; if (handler != null) + { handler(this, e); + } } /// @@ -9636,7 +9802,9 @@ protected virtual void OnMouseUp(MouseEventArgs e) Contract.Requires(e != null); MouseEventHandler handler = (MouseEventHandler)Events[EventMouseUp]; if (handler != null) + { handler(this, e); + } } /// @@ -9648,7 +9816,9 @@ protected virtual void OnMouseWheel(MouseEventArgs e) Contract.Requires(e != null); MouseEventHandler handler = (MouseEventHandler)Events[EventMouseWheel]; if (handler != null) + { handler(this, e); + } } /// @@ -9660,9 +9830,14 @@ protected virtual void OnMove(EventArgs e) Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventMove]; if (handler != null) + { handler(this, e); + } + if (RenderTransparent) + { Invalidate(); + } } /// @@ -9675,7 +9850,9 @@ protected virtual void OnPaint(PaintEventArgs e) Contract.Requires(e != null); PaintEventHandler handler = (PaintEventHandler)Events[EventPaint]; if (handler != null) + { handler(this, e); + } } protected virtual void OnPaddingChanged(EventArgs e) @@ -9687,7 +9864,9 @@ protected virtual void OnPaddingChanged(EventArgs e) } EventHandler handler = (EventHandler)Events[EventPaddingChanged]; if (handler != null) + { handler(this, e); + } } /// @@ -9713,7 +9892,9 @@ private void OnParentInvalidated(InvalidateEventArgs e) { Contract.Requires(e != null); if (!RenderTransparent) + { return; + } if (IsHandleCreated) { @@ -9725,7 +9906,10 @@ private void OnParentInvalidated(InvalidateEventArgs e) // if we don't intersect at all, do nothing if (cliprect.IsEmpty) + { return; + } + Invalidate(cliprect); } } @@ -9741,7 +9925,9 @@ protected virtual void OnQueryContinueDrag(QueryContinueDragEventArgs qcdevent) Contract.Requires(qcdevent != null); QueryContinueDragEventHandler handler = (QueryContinueDragEventHandler)Events[EventQueryContinueDrag]; if (handler != null) + { handler(this, qcdevent); + } } /// @@ -9773,7 +9959,9 @@ protected virtual void OnResize(EventArgs e) LayoutTransaction.DoLayout(this, this, PropertyNames.Bounds); EventHandler handler = (EventHandler)Events[EventResize]; if (handler != null) + { handler(this, e); + } } /// @@ -9816,7 +10004,9 @@ protected virtual void OnChangeUICues(UICuesEventArgs e) Contract.Requires(e != null); UICuesEventHandler handler = (UICuesEventHandler)Events[EventChangeUICues]; if (handler != null) + { handler(this, e); + } } /// @@ -9829,7 +10019,9 @@ protected virtual void OnStyleChanged(EventArgs e) Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventStyleChanged]; if (handler != null) + { handler(this, e); + } } /// @@ -9855,7 +10047,9 @@ protected virtual void OnSystemColorsChanged(EventArgs e) EventHandler handler = (EventHandler)Events[EventSystemColorsChanged]; if (handler != null) + { handler(this, e); + } } /// @@ -9868,7 +10062,9 @@ protected virtual void OnValidating(CancelEventArgs e) Contract.Requires(e != null); CancelEventHandler handler = (CancelEventHandler)Events[EventValidating]; if (handler != null) + { handler(this, e); + } } /// @@ -9880,7 +10076,9 @@ protected virtual void OnValidated(EventArgs e) Contract.Requires(e != null); EventHandler handler = (EventHandler)Events[EventValidated]; if (handler != null) + { handler(this, e); + } } /// @@ -10187,7 +10385,9 @@ private void PaintWithErrorHandling(PaintEventArgs e, short layer) if (GetState(STATE_EXCEPTIONWHILEPAINTING)) { if (layer == PaintLayerBackground) + { PaintException(e); + } } else { @@ -10967,7 +11167,10 @@ protected internal virtual bool ProcessKeyMessage(ref Message m) { Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "Control.ProcessKeyMessage " + m.ToString()); if (parent != null && parent.ProcessKeyPreview(ref m)) + { return true; + } + return ProcessKeyEventArgs(ref m); } @@ -11116,7 +11319,9 @@ protected void RaiseDragEvent(object key, DragEventArgs e) { DragEventHandler handler = (DragEventHandler)Events[key]; if (handler != null) + { handler(this, e); + } } /// @@ -11128,7 +11333,9 @@ protected void RaisePaintEvent(object key, PaintEventArgs e) { PaintEventHandler handler = (PaintEventHandler)Events[EventPaint]; if (handler != null) + { handler(this, e); + } } private void RemovePendingMessages(int msgMin, int msgMax) @@ -11817,9 +12024,14 @@ protected virtual void ScaleControl(SizeF factor, BoundsSpecified specified) // Clear off specified bits for 1.0 scaling factors if (dx == 1.0F) + { specified &= ~(BoundsSpecified.X | BoundsSpecified.Width); + } + if (dy == 1.0F) + { specified &= ~(BoundsSpecified.Y | BoundsSpecified.Height); + } if (dx != 1.0F) { @@ -11993,7 +12205,9 @@ public bool SelectNextControl(Control ctl, bool forward, bool tabStopOnly, bool private Control GetNextSelectableControl(Control ctl, bool forward, bool tabStopOnly, bool nested, bool wrap) { if (!Contains(ctl) || !nested && ctl.parent != this) + { ctl = null; + } bool alreadyWrapped = false; Control start = ctl; @@ -12003,7 +12217,10 @@ private Control GetNextSelectableControl(Control ctl, bool forward, bool tabStop if (ctl == null) { if (!wrap) + { break; + } + if (alreadyWrapped) { return null; //prevent infinite wrapping. @@ -12157,13 +12374,25 @@ public void SetBounds(int x, int y, int width, int height) public void SetBounds(int x, int y, int width, int height, BoundsSpecified specified) { if ((specified & BoundsSpecified.X) == BoundsSpecified.None) + { x = this.x; + } + if ((specified & BoundsSpecified.Y) == BoundsSpecified.None) + { y = this.y; + } + if ((specified & BoundsSpecified.Width) == BoundsSpecified.None) + { width = this.width; + } + if ((specified & BoundsSpecified.Height) == BoundsSpecified.None) + { height = this.height; + } + if (this.x != x || this.y != y || this.width != width || this.height != height) { @@ -12501,7 +12730,10 @@ protected virtual void SetVisibleCore(bool value) try { if (value) + { CreateControl(); + } + SafeNativeMethods.SetWindowPos(new HandleRef(window, Handle), NativeMethods.NullHandleRef, 0, 0, 0, 0, @@ -13082,7 +13314,10 @@ protected void UpdateZOrder() private void UpdateChildZOrder(Control ctl) { if (!IsHandleCreated || !ctl.IsHandleCreated || ctl.parent != this) + { return; + } + IntPtr prevHandle = (IntPtr)NativeMethods.HWND_TOP; for (int i = Controls.GetChildIndex(ctl); --i >= 0;) { @@ -13237,7 +13472,9 @@ private void WmCommand(ref Message m) if (IntPtr.Zero == m.LParam) { if (Command.DispatchID(NativeMethods.Util.LOWORD(m.WParam))) + { return; + } } else { @@ -13440,8 +13677,9 @@ private void WmGetControlName(ref Message m) } if (name == null) + { name = string.Empty; - + } MarshalStringToMessage(name, ref m); } @@ -13597,7 +13835,9 @@ private void WmInitMenuPopup(ref Message m) { if (contextMenu.ProcessInitMenuPopup(m.WParam)) + { return; + } } DefWndProc(ref m); } @@ -13772,7 +14012,10 @@ private void WmDestroy(ref Message m) private void WmKeyChar(ref Message m) { if (ProcessKeyMessage(ref m)) + { return; + } + DefWndProc(ref m); } @@ -15128,9 +15371,14 @@ void IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) try { if (sizeChanged) + { ccs.OnComponentChanged(this, sizeProperty, null, null); + } + if (locationChanged) + { ccs.OnComponentChanged(this, locationProperty, null, null); + } } catch (InvalidOperationException) { @@ -15351,7 +15599,10 @@ public virtual bool ContainsKey(string key) public virtual void Add(Control value) { if (value == null) + { return; + } + if (value.GetTopLevel()) { throw new ArgumentException(SR.TopLevelControlAdd); @@ -15770,7 +16021,9 @@ public virtual void Clear() try { while (Count != 0) + { RemoveAt(Count - 1); + } } finally { @@ -17487,9 +17740,14 @@ internal void GetAdvise(int[] paspects, int[] padvf, IAdviseSink[] pAdvSink) padvf[0] = 0; if (activeXState[viewAdviseOnlyOnce]) + { padvf[0] |= NativeMethods.ADVF_ONLYONCE; + } + if (activeXState[viewAdvisePrimeFirst]) + { padvf[0] |= NativeMethods.ADVF_PRIMEFIRST; + } } if (pAdvSink != null) @@ -17680,7 +17938,9 @@ private void GetMnemonicList(Control control, ArrayList mnemonicList) foreach (Control c in control.Controls) { if (c != null) + { GetMnemonicList(c, mnemonicList); + } } } @@ -17843,7 +18103,9 @@ internal void InPlaceActivate(int verb) // take the focus [which is what UI Activation is all about !] // if (!control.ContainsFocus) + { control.Focus(); + } // set ourselves up in the host. // @@ -19178,9 +19440,13 @@ internal void SetObjectRects(NativeMethods.COMRECT lprcPosRect, NativeMethods.CO // intersect in that case. // if (!clipRect.IsEmpty) + { intersect = Rectangle.Intersect(posRect, clipRect); + } else + { intersect = posRect; + } if (!intersect.Equals(posRect)) { @@ -19351,11 +19617,19 @@ internal int TranslateAccelerator(ref NativeMethods.MSG lpmsg) int keyState = 0; if (UnsafeNativeMethods.GetKeyState(NativeMethods.VK_SHIFT) < 0) + { keyState |= 1; + } + if (UnsafeNativeMethods.GetKeyState(NativeMethods.VK_CONTROL) < 0) + { keyState |= 2; + } + if (UnsafeNativeMethods.GetKeyState(NativeMethods.VK_MENU) < 0) + { keyState |= 4; + } hr = ioleClientSite.TranslateAccelerator(ref lpmsg, keyState); } @@ -19613,7 +19887,9 @@ internal void Read(UnsafeNativeMethods.IStream istream) int UnsafeNativeMethods.IPropertyBag.Read(string pszPropName, ref object pVar, UnsafeNativeMethods.IErrorLog pErrorLog) { if (!bag.Contains(pszPropName)) + { return NativeMethods.E_INVALIDARG; + } pVar = bag[pszPropName]; return NativeMethods.S_OK; @@ -20118,13 +20394,17 @@ private unsafe bool DICopy(HandleRef hdcDest, HandleRef hdcSrc, NativeMethods.RE // Get the bitmap from the DC by selecting in a 1x1 pixel temp bitmap HandleRef hNullBitmap = new HandleRef(this, SafeNativeMethods.CreateBitmap(1, 1, 1, 1, IntPtr.Zero)); if (hNullBitmap.Handle == IntPtr.Zero) + { return fSuccess; + } try { HandleRef hBitmap = new HandleRef(this, SafeNativeMethods.SelectObject(hdcSrc, hNullBitmap)); if (hBitmap.Handle == IntPtr.Zero) + { return fSuccess; + } // // Restore original bitmap @@ -20191,7 +20471,9 @@ private unsafe bool DICopy(HandleRef hdcDest, HandleRef hdcSrc, NativeMethods.RE int diRet = SafeNativeMethods.GetDIBits(hdcSrc, hBitmap, 0, bmp.bmHeight, lpBits, ref lpbmi, NativeMethods.DIB_RGB_COLORS); if (diRet == 0) + { return fSuccess; + } // // Set the destination coordiates depending on whether stretch-to-fit was chosen @@ -20216,7 +20498,9 @@ private unsafe bool DICopy(HandleRef hdcDest, HandleRef hdcSrc, NativeMethods.RE xDest, yDest, cxDest, cyDest, 0, 0, bmp.bmWidth, bmp.bmHeight, lpBits, ref lpbmi, NativeMethods.DIB_RGB_COLORS, NativeMethods.SRCCOPY); if (iRet == NativeMethods.GDI_ERROR) + { return fSuccess; + } fSuccess = true; } @@ -20280,7 +20564,9 @@ internal ControlAccessibleObject(Control ownerControl, int accObjId) internal override int[] GetSysChildOrder() { if (ownerControl.GetStyle(ControlStyles.ContainerControl)) + { return ownerControl.GetChildWindowsInTabOrder(); + } return base.GetSysChildOrder(); } @@ -20355,7 +20641,9 @@ internal override bool GetSysChild(AccessibleNavigation navdir, out AccessibleOb ctrls = parentControl.GetChildControlsInTabOrder(true); index = Array.IndexOf(ctrls, ownerControl); if (index != -1) + { --index; + } } break; @@ -20365,7 +20653,9 @@ internal override bool GetSysChild(AccessibleNavigation navdir, out AccessibleOb ctrls = parentControl.GetChildControlsInTabOrder(true); index = Array.IndexOf(ctrls, ownerControl); if (index != -1) + { ++index; + } } break; } @@ -20373,12 +20663,16 @@ internal override bool GetSysChild(AccessibleNavigation navdir, out AccessibleOb // Unsupported navigation operation for this object, or unexpected error. // Return false to force fall back on default system navigation behavior. if (ctrls == null || ctrls.Length == 0) + { return false; + } // If ctrls[index] is a valid control, return its non-client accessible object. // If index is invalid, return null pointer meaning "end of list reached". if (index >= 0 && index < ctrls.Length) + { accessibleObject = ctrls[index].NcAccessibilityObject; + } // Return true to use the found accessible object and block default system behavior return true; @@ -20806,7 +21100,9 @@ internal FontHandleWrapper(Font font) { #if DEBUG if (CompModSwitches.LifetimeTracing.Enabled) + { stackOnCreate = new System.Diagnostics.StackTrace().ToString(); + } #endif handle = font.ToHfont(); Interop.HandleCollector.Add(handle, Interop.CommonHandles.GDI); @@ -20838,7 +21134,9 @@ private void Dispose(bool disposing) { #if DEBUG if (CompModSwitches.LifetimeTracing.Enabled) + { stackOnDispose = new System.Diagnostics.StackTrace().ToString(); + } #endif SafeNativeMethods.DeleteObject(new HandleRef(this, handle)); handle = IntPtr.Zero; @@ -20942,7 +21240,9 @@ public bool CompletedSynchronously get { if (isCompleted && synchronous) + { return true; + } return false; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ControlPaint.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ControlPaint.cs index 87b6b476727..fbcd3739225 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ControlPaint.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ControlPaint.cs @@ -256,11 +256,15 @@ public static IntPtr CreateHBitmapTransparencyMask(Bitmap bitmap) int monochromeStride = width / 8; if ((width % 8) != 0) // wanted division to round up, not down + { monochromeStride++; + } // must be multiple of two -- i.e., bitmap // scanlines must fall on double-byte boundaries if ((monochromeStride % 2) != 0) + { monochromeStride++; + } byte[] bits = new byte[monochromeStride * height]; BitmapData data = bitmap.LockBits(new Rectangle(0, 0, width, height), @@ -334,7 +338,10 @@ internal static IntPtr CreateHalftoneHBRUSH() { short[] grayPattern = new short[8]; for (int i = 0; i < 8; i++) + { grayPattern[i] = (short)(0x5555 << (i & 1)); + } + IntPtr hBitmap = SafeNativeMethods.CreateBitmap(8, 8, 1, 1, grayPattern); NativeMethods.LOGBRUSH lb = new NativeMethods.LOGBRUSH @@ -1657,8 +1664,12 @@ public static void DrawGrid(Graphics graphics, Rectangle area, Size pixelsBetwee // draw the dots for (int x = 0; x < width; x += pixelsBetweenDots.Width) + { for (int y = 0; y < height; y += pixelsBetweenDots.Height) + { bitmap.SetPixel(x, y, foreColor); + } + } gridBrush = new TextureBrush(bitmap); bitmap.Dispose(); @@ -2900,11 +2911,18 @@ internal static StringAlignment TranslateAlignment(ContentAlignment align) { StringAlignment result; if ((align & anyRight) != 0) + { result = StringAlignment.Far; + } else if ((align & anyCenter) != 0) + { result = StringAlignment.Center; + } else + { result = StringAlignment.Near; + } + return result; } @@ -2912,11 +2930,18 @@ internal static TextFormatFlags TranslateAlignmentForGDI(ContentAlignment align) { TextFormatFlags result; if ((align & anyBottom) != 0) + { result = TextFormatFlags.Bottom; + } else if ((align & anyMiddle) != 0) + { result = TextFormatFlags.VerticalCenter; + } else + { result = TextFormatFlags.Top; + } + return result; } @@ -2942,11 +2967,18 @@ internal static TextFormatFlags TranslateLineAlignmentForGDI(ContentAlignment al { TextFormatFlags result; if ((align & anyRight) != 0) + { result = TextFormatFlags.Right; + } else if ((align & anyCenter) != 0) + { result = TextFormatFlags.HorizontalCenter; + } else + { result = TextFormatFlags.Left; + } + return result; } @@ -3100,26 +3132,41 @@ public HLSColor(Color color) { /* chromatic case */ /* saturation */ if (luminosity <= (HLSMax / 2)) + { saturation = (int)(((dif * (int)HLSMax) + (sum / 2)) / sum); + } else + { saturation = (int)((int)((dif * (int)HLSMax) + (int)((2 * RGBMax - sum) / 2)) / (2 * RGBMax - sum)); + } /* hue */ Rdelta = (int)((((max - r) * (int)(HLSMax / 6)) + (dif / 2)) / dif); Gdelta = (int)((((max - g) * (int)(HLSMax / 6)) + (dif / 2)) / dif); Bdelta = (int)((((max - b) * (int)(HLSMax / 6)) + (dif / 2)) / dif); if ((int)r == max) + { hue = Bdelta - Gdelta; + } else if ((int)g == max) + { hue = (HLSMax / 3) + Rdelta - Bdelta; + } else /* B == cMax */ + { hue = ((2 * HLSMax) / 3) + Gdelta - Rdelta; + } if (hue < 0) + { hue += HLSMax; + } + if (hue > HLSMax) + { hue -= HLSMax; + } } } @@ -3292,7 +3339,9 @@ private int NewLuma(int n, bool scale) private int NewLuma(int luminosity, int n, bool scale) { if (n == 0) + { return luminosity; + } if (scale) { @@ -3310,9 +3359,14 @@ private int NewLuma(int luminosity, int n, bool scale) newLum += (int)((long)n * Range / 1000); if (newLum < 0) + { newLum = 0; + } + if (newLum > HLSMax) + { newLum = HLSMax; + } return newLum; } @@ -3336,9 +3390,14 @@ private Color ColorFromHLS(int hue, int luminosity, int saturation) { /* chromatic case */ /* set up magic numbers */ if (luminosity <= (HLSMax / 2)) + { magic2 = (int)((luminosity * ((int)HLSMax + saturation) + (HLSMax / 2)) / HLSMax); + } else + { magic2 = luminosity + saturation - (int)(((luminosity * saturation) + (int)(HLSMax / 2)) / HLSMax); + } + magic1 = 2 * luminosity - magic2; /* get RGB, change units from HLSMax to RGBMax */ @@ -3357,21 +3416,34 @@ private int HueToRGB(int n1, int n2, int hue) /* The following is redundant for WORD (unsigned int) */ if (hue < 0) + { hue += HLSMax; + } if (hue > HLSMax) + { hue -= HLSMax; + } /* return r,g, or b value from this tridrant */ if (hue < (HLSMax / 6)) + { return (n1 + (((n2 - n1) * hue + (HLSMax / 12)) / (HLSMax / 6))); + } + if (hue < (HLSMax / 2)) + { return (n2); + } + if (hue < ((HLSMax * 2) / 3)) + { return (n1 + (((n2 - n1) * (((HLSMax * 2) / 3) - hue) + (HLSMax / 12)) / (HLSMax / 6))); + } else + { return (n1); - + } } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs index 8c4d448ce1f..c2a47b858be 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs @@ -95,7 +95,10 @@ internal bool AllowAdd return ((IBindingList)list).AllowNew; } if (list == null) + { return false; + } + return !list.IsReadOnly && !list.IsFixedSize; } } @@ -113,7 +116,10 @@ internal bool AllowEdit return ((IBindingList)list).AllowEdit; } if (list == null) + { return false; + } + return !list.IsReadOnly; } } @@ -130,7 +136,10 @@ internal bool AllowRemove return ((IBindingList)list).AllowRemove; } if (list == null) + { return false; + } + return !list.IsReadOnly && !list.IsFixedSize; } } @@ -143,9 +152,13 @@ public override int Count get { if (list == null) + { return 0; + } else + { return list.Count; + } } } @@ -209,9 +222,14 @@ private protected override void SetDataSource(object dataSource) list = (IList)tempList; WireEvents(list); if (list.Count > 0) + { listposition = 0; + } else + { listposition = -1; + } + OnItemChanged(resetEvent); OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1, -1)); UpdateIsBinding(); @@ -277,13 +295,20 @@ public override int Position set { if (listposition == -1) + { return; + } if (value < 0) + { value = 0; + } + int count = list.Count; if (value >= count) + { value = count - 1; + } ChangeRecordState(value, listposition != value, true, true, false); // true for endCurrentEdit // true for firingPositionChange notification @@ -436,7 +461,9 @@ protected void CheckEmpty() private bool CurrencyManager_PushData() { if (pullingData) + { return false; + } int initialPosition = listposition; if (lastGoodKnownRow == -1) @@ -590,7 +617,9 @@ internal ListSortDirection GetSortDirection() internal int Find(PropertyDescriptor property, object key, bool keepIndex) { if (key == null) + { throw new ArgumentNullException(nameof(key)); + } if (property != null && (list is IBindingList) && ((IBindingList)list).SupportsSearching) { @@ -719,7 +748,9 @@ private void List_ListChanged(object sender, System.ComponentModel.ListChangedEv if (e.ListChangedType == System.ComponentModel.ListChangedType.PropertyDescriptorAdded || e.ListChangedType == System.ComponentModel.ListChangedType.PropertyDescriptorDeleted || e.ListChangedType == System.ComponentModel.ListChangedType.PropertyDescriptorChanged) + { OnMetaDataChanged(EventArgs.Empty); + } // @@ -736,9 +767,14 @@ private void List_ListChanged(object sender, System.ComponentModel.ListChangedEv case System.ComponentModel.ListChangedType.Reset: Debug.WriteLineIf(CompModSwitches.DataCursor.TraceVerbose, "System.ComponentModel.ListChangedType.Reset Position: " + Position + " Count: " + list.Count); if (listposition == -1 && list.Count > 0) + { ChangeRecordState(0, true, false, true, false); // last false: we don't pull the data from the control when DM changes + } else + { ChangeRecordState(Math.Min(listposition, list.Count - 1), true, false, true, false); + } + UpdateIsBinding(/*raiseItemChangedEvent:*/ false); OnItemChanged(resetEvent); break; @@ -755,7 +791,10 @@ private void List_ListChanged(object sender, System.ComponentModel.ListChangedEv // when we get the itemAdded, and the position was at the end // of the list, do the right thing and notify the positionChanged after refreshing the list if (listposition == list.Count - 1) + { OnPositionChanged(EventArgs.Empty); + } + break; } else if (dbe.NewIndex == listposition && listposition == list.Count - 1 && listposition != -1) @@ -838,9 +877,13 @@ private void List_ListChanged(object sender, System.ComponentModel.ListChangedEv // In Everett, metadata changes did not alter current list position. In Whidbey, this behavior // preserved - except that we will now force the position to stay in valid range if necessary. if (listposition == -1 && list.Count > 0) + { ChangeRecordState(0, true, false, true, false); + } else if (listposition > list.Count - 1) + { ChangeRecordState(list.Count - 1, true, false, true, false); + } // fire the MetaDataChanged event OnMetaDataChanged(EventArgs.Empty); @@ -878,7 +921,10 @@ internal protected override void OnCurrentChanged(EventArgs e) int curLastGoodKnownRow = lastGoodKnownRow; bool positionChanged = false; if (!suspendPushDataInCurrentChanged) + { positionChanged = CurrencyManager_PushData(); + } + if (Count > 0) { object item = list[Position]; @@ -927,12 +973,17 @@ protected virtual void OnItemChanged(ItemChangedEventArgs e) // We should not push the data when we suspend the changeEvents. // but we should still fire the OnItemChanged event that we get when processing the EndCurrentEdit method. if ((e.Index == listposition || (e.Index == -1 && Position < Count)) && !inChangeRecordState) + { positionChanged = CurrencyManager_PushData(); + } + Debug.WriteLineIf(CompModSwitches.DataView.TraceVerbose, "OnItemChanged(" + e.Index.ToString(CultureInfo.InvariantCulture) + ") " + e.ToString()); try { if (onItemChanged != null) + { onItemChanged(this, e); + } } catch (Exception ex) { @@ -940,21 +991,27 @@ protected virtual void OnItemChanged(ItemChangedEventArgs e) } if (positionChanged) + { OnPositionChanged(EventArgs.Empty); + } // onItemChangedCalled = true; } private void OnListChanged(ListChangedEventArgs e) { if (onListChanged != null) + { onListChanged(this, e); + } } [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] //Exists in Everett internal protected void OnMetaDataChanged(EventArgs e) { if (onMetaDataChangedHandler != null) + { onMetaDataChangedHandler(this, e); + } } /// @@ -966,7 +1023,9 @@ protected virtual void OnPositionChanged(EventArgs e) try { if (onPositionChangedHandler != null) + { onPositionChangedHandler(this, e); + } } catch (Exception ex) { @@ -1060,6 +1119,7 @@ private void UpdateIsBinding(bool raiseItemChangedEvent) { bool newBound = list != null && list.Count > 0 && shouldBind && listposition != -1; if (list != null) + { if (bound != newBound) { // we will call end edit when moving from bound state to unbounded state @@ -1079,6 +1139,7 @@ private void UpdateIsBinding(bool raiseItemChangedEvent) OnItemChanged(resetEvent); } } + } } private void UpdateLastGoodKnownRow(System.ComponentModel.ListChangedEventArgs e) @@ -1087,22 +1148,34 @@ private void UpdateLastGoodKnownRow(System.ComponentModel.ListChangedEventArgs e { case System.ComponentModel.ListChangedType.ItemDeleted: if (e.NewIndex == lastGoodKnownRow) + { lastGoodKnownRow = -1; + } + break; case System.ComponentModel.ListChangedType.Reset: lastGoodKnownRow = -1; break; case System.ComponentModel.ListChangedType.ItemAdded: if (e.NewIndex <= lastGoodKnownRow && lastGoodKnownRow < List.Count - 1) + { lastGoodKnownRow++; + } + break; case System.ComponentModel.ListChangedType.ItemMoved: if (e.OldIndex == lastGoodKnownRow) + { lastGoodKnownRow = e.NewIndex; + } + break; case System.ComponentModel.ListChangedType.ItemChanged: if (e.NewIndex == lastGoodKnownRow) + { lastGoodKnownRow = -1; + } + break; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Cursor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Cursor.cs index 575ea46f42b..602447951f5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Cursor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Cursor.cs @@ -748,9 +748,13 @@ public override string ToString() string s = null; if (!ownHandle) + { s = TypeDescriptor.GetConverter(typeof(Cursor)).ConvertToString(this); + } else + { s = base.ToString(); + } return "[Cursor: " + s + "]"; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/CursorConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/CursorConverter.cs index 2a347b17172..b76ba5a5fa3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/CursorConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/CursorConverter.cs @@ -156,7 +156,9 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul return ms.ToArray(); } else + { return new byte[0]; + } } return base.ConvertTo(context, culture, value, destinationType); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Cursors.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Cursors.cs index 0f2fc4c97b8..713c540307d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Cursors.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Cursors.cs @@ -99,7 +99,10 @@ public static Cursor AppStarting get { if (appStarting == null) + { appStarting = new Cursor(NativeMethods.IDC_APPSTARTING, 0); + } + return appStarting; } } @@ -109,7 +112,10 @@ public static Cursor Arrow get { if (arrow == null) + { arrow = new Cursor(NativeMethods.IDC_ARROW, 0); + } + return arrow; } } @@ -119,7 +125,10 @@ public static Cursor Cross get { if (cross == null) + { cross = new Cursor(NativeMethods.IDC_CROSS, 0); + } + return cross; } } @@ -129,7 +138,10 @@ public static Cursor Default get { if (defaultCursor == null) + { defaultCursor = new Cursor(NativeMethods.IDC_ARROW, 0); + } + return defaultCursor; } } @@ -139,7 +151,10 @@ public static Cursor IBeam get { if (iBeam == null) + { iBeam = new Cursor(NativeMethods.IDC_IBEAM, 0); + } + return iBeam; } } @@ -149,7 +164,10 @@ public static Cursor No get { if (no == null) + { no = new Cursor(NativeMethods.IDC_NO, 0); + } + return no; } } @@ -159,7 +177,10 @@ public static Cursor SizeAll get { if (sizeAll == null) + { sizeAll = new Cursor(NativeMethods.IDC_SIZEALL, 0); + } + return sizeAll; } } @@ -169,7 +190,10 @@ public static Cursor SizeNESW get { if (sizeNESW == null) + { sizeNESW = new Cursor(NativeMethods.IDC_SIZENESW, 0); + } + return sizeNESW; } } @@ -179,7 +203,10 @@ public static Cursor SizeNS get { if (sizeNS == null) + { sizeNS = new Cursor(NativeMethods.IDC_SIZENS, 0); + } + return sizeNS; } } @@ -189,7 +216,10 @@ public static Cursor SizeNWSE get { if (sizeNWSE == null) + { sizeNWSE = new Cursor(NativeMethods.IDC_SIZENWSE, 0); + } + return sizeNWSE; } } @@ -199,7 +229,10 @@ public static Cursor SizeWE get { if (sizeWE == null) + { sizeWE = new Cursor(NativeMethods.IDC_SIZEWE, 0); + } + return sizeWE; } } @@ -209,7 +242,10 @@ public static Cursor UpArrow get { if (upArrow == null) + { upArrow = new Cursor(NativeMethods.IDC_UPARROW, 0); + } + return upArrow; } } @@ -219,7 +255,10 @@ public static Cursor WaitCursor get { if (wait == null) + { wait = new Cursor(NativeMethods.IDC_WAIT, 0); + } + return wait; } } @@ -229,7 +268,10 @@ public static Cursor Help get { if (help == null) + { help = new Cursor(NativeMethods.IDC_HELP, 0); + } + return help; } } @@ -239,7 +281,10 @@ public static Cursor HSplit get { if (hSplit == null) + { hSplit = new Cursor("hsplit.cur", 0); + } + return hSplit; } } @@ -249,7 +294,10 @@ public static Cursor VSplit get { if (vSplit == null) + { vSplit = new Cursor("vsplit.cur", 0); + } + return vSplit; } } @@ -259,7 +307,10 @@ public static Cursor NoMove2D get { if (noMove2D == null) + { noMove2D = new Cursor("nomove2d.cur", 0); + } + return noMove2D; } } @@ -269,7 +320,10 @@ public static Cursor NoMoveHoriz get { if (noMoveHoriz == null) + { noMoveHoriz = new Cursor("nomoveh.cur", 0); + } + return noMoveHoriz; } } @@ -279,7 +333,10 @@ public static Cursor NoMoveVert get { if (noMoveVert == null) + { noMoveVert = new Cursor("nomovev.cur", 0); + } + return noMoveVert; } } @@ -289,7 +346,10 @@ public static Cursor PanEast get { if (panEast == null) + { panEast = new Cursor("east.cur", 0); + } + return panEast; } } @@ -299,7 +359,10 @@ public static Cursor PanNE get { if (panNE == null) + { panNE = new Cursor("ne.cur", 0); + } + return panNE; } } @@ -309,7 +372,10 @@ public static Cursor PanNorth get { if (panNorth == null) + { panNorth = new Cursor("north.cur", 0); + } + return panNorth; } } @@ -319,7 +385,10 @@ public static Cursor PanNW get { if (panNW == null) + { panNW = new Cursor("nw.cur", 0); + } + return panNW; } } @@ -329,7 +398,10 @@ public static Cursor PanSE get { if (panSE == null) + { panSE = new Cursor("se.cur", 0); + } + return panSE; } } @@ -339,7 +411,10 @@ public static Cursor PanSouth get { if (panSouth == null) + { panSouth = new Cursor("south.cur", 0); + } + return panSouth; } } @@ -349,7 +424,10 @@ public static Cursor PanSW get { if (panSW == null) + { panSW = new Cursor("sw.cur", 0); + } + return panSW; } } @@ -359,7 +437,10 @@ public static Cursor PanWest get { if (panWest == null) + { panWest = new Cursor("west.cur", 0); + } + return panWest; } } @@ -369,7 +450,10 @@ public static Cursor Hand get { if (hand == null) + { hand = new Cursor("hand.cur", 0); + } + return hand; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs index 5ec1e294222..b55c44c1a25 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs @@ -400,7 +400,9 @@ public bool AllowSorting { IList list = listManager.List; if (list is IBindingList) + { ((IBindingList)list).RemoveSort(); + } } } } @@ -424,7 +426,10 @@ public Color AlternatingBackColor "AlternatingBackColor")); } if (IsTransparentColor(value)) + { throw new ArgumentException(SR.DataGridTransparentAlternatingBackColorNotAllowed); + } + if (!alternatingBackBrush.Color.Equals(value)) { alternatingBackBrush = new SolidBrush(value); @@ -475,7 +480,10 @@ public override Color BackColor set { if (IsTransparentColor(value)) + { throw new ArgumentException(SR.DataGridTransparentBackColorNotAllowed); + } + base.BackColor = value; } } @@ -711,20 +719,31 @@ private bool ListHasErrors gridState[GRIDSTATE_listHasErrors] = value; ComputeMinimumRowHeaderWidth(); if (!layout.RowHeadersVisible) + { return; + } + if (value) { if (myGridTable.IsDefault) + { RowHeaderWidth += errorRowBitmapWidth; + } else + { myGridTable.RowHeaderWidth += errorRowBitmapWidth; + } } else { if (myGridTable.IsDefault) + { RowHeaderWidth -= errorRowBitmapWidth; + } else + { myGridTable.RowHeaderWidth -= errorRowBitmapWidth; + } } } } @@ -765,7 +784,10 @@ public Color CaptionBackColor set { if (IsTransparentColor(value)) + { throw new ArgumentException(SR.DataGridTransparentCaptionBackColorNotAllowed); + } + Caption.BackColor = value; } } @@ -948,13 +970,21 @@ public DataGridCell CurrentCell // if the OnLayout event was not set in the grid, then we can't // reliably set the currentCell on the grid. if (layout.dirty) + { throw new ArgumentException(SR.DataGridSettingCurrentCellNotGood); + } + if (value.RowNumber == currentRow && value.ColumnNumber == currentCol) + { return; + } // should we throw an exception, maybe? if (DataGridRowsLength == 0 || myGridTable.GridColumnStyles == null || myGridTable.GridColumnStyles.Count == 0) + { return; + } + EnsureBound(); int currentRowSaved = currentRow; @@ -975,9 +1005,14 @@ public DataGridCell CurrentCell { int columnCount = myGridTable.GridColumnStyles.Count; if (newCol < 0) + { newCol = 0; + } + if (newCol >= columnCount) + { newCol = columnCount - 1; + } int localGridRowsLength = DataGridRowsLength; DataGridRow[] localGridRows = DataGridRows; @@ -1056,11 +1091,17 @@ public DataGridCell CurrentCell } if (currentRow < localGridRowsLength) + { localGridRows[currentRow].OnRowLeave(); + } + localGridRows[newRow].OnRowEnter(); currentRow = newRow; if (currentRowSaved < localGridRowsLength) + { InvalidateRow(currentRowSaved); + } + InvalidateRow(currentRow); if (currentRowSaved != listManager.Position) @@ -1072,7 +1113,9 @@ public DataGridCell CurrentCell #endif //DEBUG doNotEdit = true; if (gridState[GRIDSTATE_isEditing]) + { AbortEdit(); + } } else if (gridState[GRIDSTATE_inAddNewRow]) { @@ -1156,7 +1199,9 @@ public DataGridCell CurrentCell // also, make sure that we get the row selector on the currentrow, too InvalidateRowHeader(currentRow); if (wasEditing) + { Edit(); + } } else { @@ -1166,7 +1211,10 @@ public DataGridCell CurrentCell // and this will ultimately call InvalidateRow w/ a row number larger than the number of rows // so set the currentRow here: if (currentRow == DataGridRowsLength - 1 && currentRowSaved == DataGridRowsLength - 2 && DataGridRows[currentRow] is DataGridAddNewRow) + { newRow = currentRowSaved; + } + currentRow = newRow; Debug.Assert(result == DialogResult.No, "we only put cancel and ok on the error message box"); listManager.PositionChanged -= positionChangedHandler; @@ -1176,7 +1224,9 @@ public DataGridCell CurrentCell currentRow = newRow; currentCol = newCol; if (wasEditing) + { Edit(); + } } } @@ -1215,9 +1265,15 @@ internal int CurrentCellAccIndex currentCellAccIndex += myGridTable.GridColumnStyles.Count; // ColumnHeaderAccessibleObject currentCellAccIndex += DataGridRows.Length; // DataGridRowAccessibleObject if (horizScrollBar.Visible) // Horizontal Scroll Bar Accessible Object + { currentCellAccIndex++; + } + if (vertScrollBar.Visible) // Vertical Scroll Bar Accessible Object + { currentCellAccIndex++; + } + currentCellAccIndex += (currentRow * myGridTable.GridColumnStyles.Count) + currentCol; return currentCellAccIndex; } @@ -1267,9 +1323,15 @@ public Color SelectionBackColor set { if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "SelectionBackColor")); + } + if (IsTransparentColor(value)) + { throw new ArgumentException(SR.DataGridTransparentSelectionBackColorNotAllowed); + } + if (!value.Equals(selectionBackBrush.Color)) { selectionBackBrush = new SolidBrush(value); @@ -1303,7 +1365,9 @@ protected bool ShouldSerializeSelectionBackColor() public void ResetSelectionBackColor() { if (ShouldSerializeSelectionBackColor()) + { SelectionBackColor = DefaultSelectionBackBrush.Color; + } } [ @@ -1319,7 +1383,10 @@ public Color SelectionForeColor set { if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "SelectionForeColor")); + } + if (!value.Equals(selectionForeBrush.Color)) { selectionForeBrush = new SolidBrush(value); @@ -1337,7 +1404,9 @@ protected virtual bool ShouldSerializeSelectionForeColor() public void ResetSelectionForeColor() { if (ShouldSerializeSelectionForeColor()) + { SelectionForeColor = DefaultSelectionForeBrush.Color; + } } internal override bool ShouldSerializeForeColor() @@ -1360,7 +1429,10 @@ internal DataGridRow[] DataGridRows get { if (dataGridRows == null) + { CreateDataGridRows(); + } + return dataGridRows; } } @@ -1436,7 +1508,9 @@ private void CreateDataGridRows() int nDataGridRows = listManager.Count; if (policy.AllowAdd) + { nDataGridRows++; + } DataGridRow[] rows = new DataGridRow[nDataGridRows]; for (int r = 0; r < listManager.Count; r++) @@ -1535,7 +1609,10 @@ public object DataSource set { if (value != null && !(value is IList || value is IListSource)) + { throw new ArgumentException(SR.BadDataSourceForComplexBinding); + } + if (dataSource != null && dataSource.Equals(value)) { return; @@ -1553,7 +1630,9 @@ public object DataSource // of the properties in the dataSource, then set the dataMember to "" // if (value != null) + { EnforceValidDataMember(value); + } Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: DataSource being set to " + ((value == null) ? "null" : value.ToString())); @@ -1594,7 +1673,10 @@ public string DataMember set { if (dataMember != null && dataMember.Equals(value)) + { return; + } + Debug.WriteLineIf(CompModSwitches.DataGridCursor.TraceVerbose, "DataGridCursor: DataSource being set to " + ((value == null) ? "null" : value.ToString())); // when we change the dataMember, we need to clear the parent rows. // the same goes for all the caption UI: reset it when the datamember changes. @@ -1624,9 +1706,13 @@ internal protected CurrencyManager ListManager { //try to return something useful: if (listManager == null && BindingContext != null && DataSource != null) + { return (CurrencyManager)BindingContext[DataSource, DataMember]; + } else + { return listManager; + } } set { @@ -1653,7 +1739,9 @@ internal void Set_ListManager(object newDataSource, string newDataMember, bool f // if nothing happened, then why do any work? if (!force && !dataSourceChanged && !dataMemberChanged && gridState[GRIDSTATE_inSetListManager]) + { return; + } gridState[GRIDSTATE_inSetListManager] = true; if (toBeDisposedEditingControl != null) @@ -1670,7 +1758,9 @@ internal void Set_ListManager(object newDataSource, string newDataMember, bool f // unwire the events: if (listManager != null) + { UnWireDataSource(); + } CurrencyManager oldListManager = listManager; bool listManagerChanged = false; @@ -1680,9 +1770,13 @@ internal void Set_ListManager(object newDataSource, string newDataMember, bool f // then the grid will call Set_ListManager again, and eventually that means that the dataGrid::listManager will // be hooked up twice to all the events (PositionChanged, ItemChanged, CurrentChanged) if (newDataSource != null && BindingContext != null && !(newDataSource == Convert.DBNull)) + { listManager = (CurrencyManager)BindingContext[newDataSource, newDataMember]; + } else + { listManager = null; + } // update the dataSource and the dateMember dataSource = newDataSource; @@ -1756,7 +1850,9 @@ internal void Set_ListManager(object newDataSource, string newDataMember, bool f if (listManagerChanged || gridState[GRIDSTATE_metaDataChanged]) { if (Visible) + { BeginUpdateInternal(); + } if (listManager != null) { @@ -1784,14 +1880,21 @@ internal void Set_ListManager(object newDataSource, string newDataMember, bool f // RecreateDataGridRows(); if (Visible) + { EndUpdateInternal(); + } + beginUpdateInternal = false; ComputeMinimumRowHeaderWidth(); if (myGridTable.IsDefault) + { RowHeaderWidth = Math.Max(minRowHeaderWidth, RowHeaderWidth); + } else + { myGridTable.RowHeaderWidth = Math.Max(minRowHeaderWidth, RowHeaderWidth); + } ListHasErrors = DataGridSourceHasErrors(); @@ -1812,7 +1915,9 @@ internal void Set_ListManager(object newDataSource, string newDataMember, bool f gridState[GRIDSTATE_inSetListManager] = false; // start painting again if (beginUpdateInternal && Visible) + { EndUpdateInternal(); + } } } @@ -1831,11 +1936,16 @@ public int CurrentRowIndex get { if (originalState == null) + { return listManager == null ? -1 : listManager.Position; + } else { if (BindingContext == null) + { return -1; + } + CurrencyManager originalListManager = (CurrencyManager)BindingContext[originalState.DataSource, originalState.DataMember]; return originalListManager.Position; } @@ -1843,7 +1953,9 @@ public int CurrentRowIndex set { if (listManager == null) + { throw new InvalidOperationException(SR.DataGridSetSelectIndex); + } if (originalState == null) { @@ -1925,7 +2037,10 @@ public Color GridLineColor if (gridLineBrush.Color != value) { if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "GridLineColor")); + } + gridLineBrush = new SolidBrush(value); Invalidate(layout.Data); @@ -2120,17 +2235,29 @@ public Color HeaderBackColor set { if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "HeaderBackColor")); + } + if (IsTransparentColor(value)) + { throw new ArgumentException(SR.DataGridTransparentHeaderBackColorNotAllowed); + } + if (!value.Equals(headerBackBrush.Color)) { headerBackBrush = new SolidBrush(value); if (layout.RowHeadersVisible) + { Invalidate(layout.RowHeaders); + } + if (layout.ColumnHeadersVisible) + { Invalidate(layout.ColumnHeaders); + } + Invalidate(layout.TopLeftHeader); } } @@ -2197,7 +2324,10 @@ public Color BackgroundColor set { if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "BackgroundColor")); + } + if (!value.Equals(backgroundBrush.Color)) { @@ -2241,7 +2371,10 @@ public Font HeaderFont set { if (value == null) + { throw new ArgumentNullException(nameof(HeaderFont)); + } + if (!value.Equals(headerFont)) { headerFont = value; @@ -2291,16 +2424,25 @@ public Color HeaderForeColor set { if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "HeaderForeColor")); + } + if (!value.Equals(headerForePen.Color)) { headerForePen = new Pen(value); headerForeBrush = new SolidBrush(value); if (layout.RowHeadersVisible) + { Invalidate(layout.RowHeaders); + } + if (layout.ColumnHeadersVisible) + { Invalidate(layout.ColumnHeaders); + } + Invalidate(layout.TopLeftHeader); } } @@ -2353,7 +2495,9 @@ internal int HorizontalOffset { //if (CompModSwitches.DataGridScrolling.TraceVerbose) Debug.WriteLine("DataGridScrolling: Set_HorizontalOffset, value = " + value.ToString()); if (value < 0) + { value = 0; + } // // if the dataGrid is not bound ( listManager == null || gridTable == null) @@ -2363,16 +2507,23 @@ internal int HorizontalOffset int totalWidth = GetColumnWidthSum(); int widthNotVisible = totalWidth - layout.Data.Width; if (value > widthNotVisible && widthNotVisible > 0) + { value = widthNotVisible; + } if (value == horizontalOffset) + { return; + } int change = horizontalOffset - value; horizScrollBar.Value = value; Rectangle scroll = layout.Data; if (layout.ColumnHeadersVisible) + { scroll = Rectangle.Union(scroll, layout.ColumnHeaders); + } + horizontalOffset = value; firstVisibleCol = ComputeFirstVisibleColumn(); @@ -2384,9 +2535,13 @@ internal int HorizontalOffset // if the user did not click on the grid yet, then do not put the edit // control when scrolling if (currentCol >= firstVisibleCol && currentCol < firstVisibleCol + numVisibleCols - 1 && (gridState[GRIDSTATE_isEditing] || gridState[GRIDSTATE_isNavigating])) + { Edit(); + } else + { EndEdit(); + } // isScrolling is set to TRUE when the user scrolls. // once we move the edit box, we finished processing the scroll event, so set isScrolling to FALSE @@ -2410,7 +2565,10 @@ private void ScrollRectangles(NativeMethods.RECT[] rects, int change) { NativeMethods.RECT scroll; if (isRightToLeft()) + { change = -change; + } + for (int r = 0; r < rects.Length; r++) { scroll = rects[r]; @@ -2477,7 +2635,10 @@ public Color LinkColor set { if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "LinkColor")); + } + if (!linkBrush.Color.Equals(value)) { linkBrush = new SolidBrush(value); @@ -2494,7 +2655,9 @@ internal virtual bool ShouldSerializeLinkColor() public void ResetLinkColor() { if (ShouldSerializeLinkColor()) + { LinkColor = DefaultLinkBrush.Color; + } } internal Brush LinkBrush @@ -2697,7 +2860,10 @@ public Color ParentRowsBackColor set { if (IsTransparentColor(value)) + { throw new ArgumentException(SR.DataGridTransparentParentRowsBackColorNotAllowed); + } + parentRows.BackColor = value; } } @@ -2724,7 +2890,9 @@ protected virtual bool ShouldSerializeParentRowsBackColor() private void ResetParentRowsBackColor() { if (ShouldSerializeParentRowsBackColor()) + { parentRows.BackBrush = DefaultParentRowsBackBrush; + } } /// @@ -2770,7 +2938,9 @@ protected virtual bool ShouldSerializeParentRowsForeColor() private void ResetParentRowsForeColor() { if (ShouldSerializeParentRowsForeColor()) + { parentRows.ForeBrush = DefaultParentRowsForeBrush; + } } @@ -2796,7 +2966,10 @@ public int PreferredColumnWidth set { if (value < 0) + { throw new ArgumentException(SR.DataGridColumnWidth, "PreferredColumnWidth"); + } + if (preferredColumnWidth != value) { preferredColumnWidth = value; @@ -2822,7 +2995,10 @@ public int PreferredRowHeight set { if (value < 0) + { throw new ArgumentException(SR.DataGridRowRowHeight); + } + prefferedRowHeight = value; } } @@ -2882,7 +3058,9 @@ public bool ReadOnly for (int i = 0; i < rowCount; i++) { if (dataGridRows[i].Selected) + { currentDataGridRows[i].Selected = true; + } } } @@ -3124,9 +3302,15 @@ public int VisibleRowCount { EnsureBound(); if (rowIndex < 0 || rowIndex >= DataGridRowsLength) + { throw new ArgumentOutOfRangeException(nameof(rowIndex)); + } + if (columnIndex < 0 || columnIndex >= myGridTable.GridColumnStyles.Count) + { throw new ArgumentOutOfRangeException(nameof(columnIndex)); + } + CurrencyManager listManager = this.listManager; DataGridColumnStyle column = myGridTable.GridColumnStyles[columnIndex]; return column.GetColumnValueAtRow(listManager, rowIndex); @@ -3135,12 +3319,21 @@ public int VisibleRowCount { EnsureBound(); if (rowIndex < 0 || rowIndex >= DataGridRowsLength) + { throw new ArgumentOutOfRangeException(nameof(rowIndex)); + } + if (columnIndex < 0 || columnIndex >= myGridTable.GridColumnStyles.Count) + { throw new ArgumentOutOfRangeException(nameof(columnIndex)); + } + CurrencyManager listManager = this.listManager; if (listManager.Position != rowIndex) + { listManager.Position = rowIndex; + } + DataGridColumnStyle column = myGridTable.GridColumnStyles[columnIndex]; column.SetColumnValueAtRow(listManager, rowIndex, value); @@ -3266,7 +3459,9 @@ private void DataSource_Changed(object sender, EventArgs ea) ListHasErrors = DataGridSourceHasErrors(); // if we changed the ListHasErrors, then the grid is already invalidated if (oldListHasErrors == ListHasErrors) + { InvalidateInside(); + } } private void GridLineColorChanged(object sender, EventArgs e) @@ -3281,9 +3476,15 @@ private void GridLineStyleChanged(object sender, EventArgs e) private void HeaderBackColorChanged(object sender, EventArgs e) { if (layout.RowHeadersVisible) + { Invalidate(layout.RowHeaders); + } + if (layout.ColumnHeadersVisible) + { Invalidate(layout.ColumnHeaders); + } + Invalidate(layout.TopLeftHeader); } private void HeaderFontChanged(object sender, EventArgs e) @@ -3295,9 +3496,15 @@ private void HeaderFontChanged(object sender, EventArgs e) private void HeaderForeColorChanged(object sender, EventArgs e) { if (layout.RowHeadersVisible) + { Invalidate(layout.RowHeaders); + } + if (layout.ColumnHeadersVisible) + { Invalidate(layout.ColumnHeaders); + } + Invalidate(layout.TopLeftHeader); } private void LinkColorChanged(object sender, EventArgs e) @@ -3343,7 +3550,9 @@ private void AllowSortingChanged(object sender, EventArgs e) { IList list = listManager.List; if (list is IBindingList) + { ((IBindingList)list).RemoveSort(); + } } } @@ -3399,7 +3608,10 @@ internal void DataSource_MetaDataChanged(object sender, EventArgs e) private bool DataGridSourceHasErrors() { if (listManager == null) + { return false; + } + for (int i = 0; i < listManager.Count; i++) { object errObj = listManager[i]; @@ -3407,7 +3619,9 @@ private bool DataGridSourceHasErrors() { string errString = ((IDataErrorInfo)errObj).Error; if (errString != null && errString.Length != 0) + { return true; + } } } return false; @@ -3417,9 +3631,14 @@ private void TableStylesCollectionChanged(object sender, CollectionChangeEventAr { // if the users changed the collection of tableStyles if (sender != dataGridTables) + { return; + } + if (listManager == null) + { return; + } if (ccea.Action == CollectionChangeAction.Add) { @@ -3495,7 +3714,9 @@ private void DataSource_ItemChanged(object sender, ItemChangedEventArgs ea) if (errObj is IDataErrorInfo) { if (((IDataErrorInfo)errObj).Error.Length != 0) + { ListHasErrors = true; + } else if (ListHasErrors) { // maybe there was an error that now is fixed @@ -3505,13 +3726,17 @@ private void DataSource_ItemChanged(object sender, ItemChangedEventArgs ea) // Invalidate the row only if we did not change the ListHasErrors if (oldListHasErrors == ListHasErrors) + { InvalidateRow(ea.Index); + } // we need to update the edit box: // we update the text in the edit box only when the currentRow // equals the ea.Index if (editColumn != null && ea.Index == currentRow) + { editColumn.UpdateUI(ListManager, ea.Index, null); + } } } @@ -3627,7 +3852,9 @@ protected virtual void OnReadOnlyChanged(EventArgs e) protected void OnNavigate(NavigateEventArgs e) { if (onNavigate != null) + { onNavigate(this, e); + } } /* @@ -3659,7 +3886,9 @@ internal void OnNodeClick(EventArgs e) // GridColumnStylesCollection columns = myGridTable.GridColumnStyles; if (firstVisibleCol > -1 && firstVisibleCol < columns.Count && columns[firstVisibleCol] == editColumn) + { Edit(); + } // Raise the event for the event listeners EventHandler handler = (EventHandler)Events[EVENT_NODECLICKED]; @@ -3675,7 +3904,9 @@ internal void OnNodeClick(EventArgs e) protected void OnRowHeaderClick(EventArgs e) { if (onRowHeaderClick != null) + { onRowHeaderClick(this, e); + } } /// @@ -3687,7 +3918,9 @@ protected void OnScroll(EventArgs e) { // reset the toolTip information if (ToolTipProvider != null) + { ResetToolTip(); + } EventHandler handler = (EventHandler)Events[EVENT_SCROLL]; if (handler != null) @@ -3706,7 +3939,10 @@ protected void OnScroll(EventArgs e) protected virtual void GridHScrolled(object sender, ScrollEventArgs se) { if (!Enabled) + { return; + } + if (DataSource == null) { Debug.Fail("Horizontal Scrollbar should be disabled without a DataSource."); @@ -3794,7 +4030,10 @@ protected virtual void GridHScrolled(object sender, ScrollEventArgs se) protected virtual void GridVScrolled(object sender, ScrollEventArgs se) { if (!Enabled) + { return; + } + if (DataSource == null) { Debug.Fail("Vertical Scrollbar should be disabled without a DataSource."); @@ -3874,7 +4113,9 @@ protected void OnBackButtonClicked(object sender, EventArgs e) EventHandler handler = (EventHandler)Events[EVENT_BACKBUTTONCLICK]; if (handler != null) + { handler(this, e); + } } protected override void OnBackColorChanged(EventArgs e) @@ -3888,6 +4129,7 @@ protected override void OnBackColorChanged(EventArgs e) protected override void OnBindingContextChanged(EventArgs e) { if (DataSource != null && !gridState[GRIDSTATE_inSetListManager]) + { try { Set_ListManager(DataSource, DataMember, true, false); // we do not want to create columns @@ -3899,20 +4141,28 @@ protected override void OnBindingContextChanged(EventArgs e) { // at runtime we will rethrow the exception if (Site == null || !Site.DesignMode) + { throw; + } RTLAwareMessageBox.Show(null, SR.DataGridExceptionInPaint, null, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); if (Visible) + { BeginUpdateInternal(); + } ResetParentRows(); Set_ListManager(null, string.Empty, true); if (Visible) + { EndUpdateInternal(); + } } + } + base.OnBindingContextChanged(e); } @@ -3940,7 +4190,9 @@ protected void OnShowParentDetailsButtonClicked(object sender, EventArgs e) EventHandler handler = (EventHandler)Events[EVENT_DOWNBUTTONCLICK]; if (handler != null) + { handler(this, e); + } } protected override void OnForeColorChanged(EventArgs e) @@ -4015,13 +4267,17 @@ protected override void OnLayout(LayoutEventArgs levent) // ignore it // if (gridState[GRIDSTATE_editControlChanging]) + { return; + } Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: OnLayout"); base.OnLayout(levent); if (gridState[GRIDSTATE_layoutSuspended]) + { return; + } gridState[GRIDSTATE_canFocus] = false; try @@ -4029,11 +4285,15 @@ protected override void OnLayout(LayoutEventArgs levent) if (IsHandleCreated) { if (layout.ParentRowsVisible) + { parentRows.OnLayout(); + } // reset the toolTip information if (ToolTipProvider != null) + { ResetToolTip(); + } ComputeLayout(); } @@ -4139,7 +4399,9 @@ private void OnLeave_Grid() // inAddNewRow should be set to false if the control was // not changing if (!gridState[GRIDSTATE_editControlChanging]) + { gridState[GRIDSTATE_inAddNewRow] = false; + } } } @@ -4168,10 +4430,12 @@ protected override void OnKeyPress(KeyPressEventArgs kpe) if (coll != null && currentCol > 0 && currentCol < coll.Count) { if (!coll[currentCol].ReadOnly) + { if (kpe.KeyChar > 32) { Edit(new string(new char[] { (char)kpe.KeyChar })); } + } } } @@ -4185,7 +4449,9 @@ protected override void OnMouseDown(MouseEventArgs e) gridState[GRIDSTATE_childLinkFocused] = false; gridState[GRIDSTATE_dragging] = false; if (listManager == null) + { return; + } HitTestInfo location = HitTest(e.X, e.Y); Keys nModifier = ModifierKeys; @@ -4194,7 +4460,9 @@ protected override void OnMouseDown(MouseEventArgs e) // Only left clicks for now if (e.Button != MouseButtons.Left) + { return; + } // Check column resize if (location.type == HitTestType.ColumnResize) @@ -4204,7 +4472,10 @@ protected override void OnMouseDown(MouseEventArgs e) ColAutoResize(location.col); } else + { ColResizeBegin(e, location.col); + } + return; } @@ -4259,7 +4530,9 @@ protected override void OnMouseDown(MouseEventArgs e) // and are initially collapsed localGridRows = DataGridRows; if (row < DataGridRowsLength && (localGridRows[row] is DataGridRelationshipRow) && ((DataGridRelationshipRow)localGridRows[row]).Expanded) + { EnsureVisible(row, 0); + } // show the edit box // @@ -4291,9 +4564,13 @@ protected override void OnMouseDown(MouseEventArgs e) if (isControlDown) { if (IsSelected(location.row)) + { UnSelect(location.row); + } else + { Select(location.row); + } } else { @@ -4346,7 +4623,10 @@ protected override void OnMouseDown(MouseEventArgs e) if (location.type == HitTestType.Cell) { if (myGridTable.GridColumnStyles[location.col].MouseDown(location.row, e.X, e.Y)) + { return; + } + DataGridCell target = new DataGridCell(location.row, location.col); if (policy.AllowEdit && CurrentCell.Equals(target)) { @@ -4398,7 +4678,9 @@ protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (listManager == null) + { return; + } HitTestInfo location = HitTest(e.X, e.Y); @@ -4516,7 +4798,10 @@ protected override void OnMouseUp(MouseEventArgs e) base.OnMouseUp(e); gridState[GRIDSTATE_dragging] = false; if (listManager == null || myGridTable == null) + { return; + } + if (gridState[GRIDSTATE_trackColResize]) { ColResizeEnd(e); @@ -4568,13 +4853,20 @@ protected override void OnMouseWheel(MouseEventArgs e) bool wheelingDown = true; if ((ModifierKeys & Keys.Control) != 0) + { wheelingDown = false; + } if (listManager == null || myGridTable == null) + { return; + } + ScrollBar sb = wheelingDown ? vertScrollBar : horizScrollBar; if (!sb.Visible) + { return; + } // so we scroll. we have to know this, cause otherwise we will call EndEdit // and that would be wrong. @@ -4613,13 +4905,17 @@ protected override void OnPaint(PaintEventArgs pe) CheckHierarchyState(); if (layout.dirty) + { ComputeLayout(); + } Graphics g = pe.Graphics; Region clipRegion = g.Clip; if (layout.CaptionVisible) + { caption.Paint(g, layout.Caption, isRightToLeft()); + } if (layout.ParentRowsVisible) { @@ -4630,9 +4926,14 @@ protected override void OnPaint(PaintEventArgs pe) Rectangle gridRect = layout.Data; if (layout.RowHeadersVisible) + { gridRect = Rectangle.Union(gridRect, layout.RowHeaders); + } + if (layout.ColumnHeadersVisible) + { gridRect = Rectangle.Union(gridRect, layout.ColumnHeaders); + } g.SetClip(gridRect); PaintGrid(g, gridRect); @@ -4648,7 +4949,10 @@ protected override void OnPaint(PaintEventArgs pe) { // at runtime we will rethrow the exception if (Site == null || !Site.DesignMode) + { throw; + } + gridState[GRIDSTATE_exceptionInPaint] = true; try { @@ -4656,7 +4960,9 @@ protected override void OnPaint(PaintEventArgs pe) MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); if (Visible) + { BeginUpdateInternal(); + } ResetParentRows(); @@ -4666,7 +4972,9 @@ protected override void OnPaint(PaintEventArgs pe) { gridState[GRIDSTATE_exceptionInPaint] = false; if (Visible) + { EndUpdateInternal(); + } } } } @@ -4681,9 +4989,14 @@ protected override void OnResize(EventArgs e) Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: OnResize"); if (layout.CaptionVisible) + { Invalidate(layout.Caption); + } + if (layout.ParentRowsVisible) + { parentRows.OnResize(layout.ParentRows); + } int borderWidth = BorderWidth; Rectangle right; @@ -4721,14 +5034,18 @@ protected override void OnResize(EventArgs e) //also, invalidate the ResizeBoxRect if (!layout.ResizeBoxRect.IsEmpty) + { Invalidate(layout.ResizeBoxRect); + } layout.ClientRectangle = newClientRectangle; int oldFirstVisibleRow = firstVisibleRow; base.OnResize(e); if (isRightToLeft() || oldFirstVisibleRow != firstVisibleRow) + { Invalidate(); + } } internal void OnRowHeightChanged(DataGridRow row) @@ -4887,16 +5204,23 @@ internal void AddNewRow() public bool BeginEdit(DataGridColumnStyle gridColumn, int rowNumber) { if (DataSource == null || myGridTable == null) + { return false; + } // We deny edit requests if we are already editing a cell. if (gridState[GRIDSTATE_isEditing]) + { return false; + } else { int col = -1; if ((col = myGridTable.GridColumnStyles.IndexOf(gridColumn)) < 0) + { return false; + } + CurrentCell = new DataGridCell(rowNumber, col); ResetSelection(); Edit(); @@ -4910,7 +5234,10 @@ public bool BeginEdit(DataGridColumnStyle gridColumn, int rowNumber) public void BeginInit() { if (inInit) + { throw new InvalidOperationException(SR.DataGridBeginInit); + } + inInit = true; } @@ -4947,8 +5274,10 @@ private void CheckHierarchyState() if (checkHierarchy && listManager != null && myGridTable != null) { if (myGridTable == null) + { // there was nothing to check return; + } for (int j = 0; j < myGridTable.GridColumnStyles.Count; j++) { @@ -4980,7 +5309,9 @@ private void ColAutoResize(int col) EndEdit(); CurrencyManager listManager = this.listManager; if (listManager == null) + { return; + } int size; Graphics g = CreateGraphicsInternal(); @@ -4991,9 +5322,14 @@ private void ColAutoResize(int col) Font headerFont; if (myGridTable.IsDefault) + { headerFont = HeaderFont; + } else + { headerFont = myGridTable.HeaderFont; + } + size = (int)g.MeasureString(columnName, headerFont).Width + layout.ColumnHeaders.Height + 1; // The sort triangle's width is equal to it's height int rowCount = listManager.Count; for (int row = 0; row < rowCount; ++row) @@ -5001,7 +5337,9 @@ private void ColAutoResize(int col) object value = column.GetColumnValueAtRow(listManager, row); int width = column.GetPreferredSize(g, value).Width; if (width > size) + { size = width; + } } if (column.Width != size) @@ -5088,7 +5426,9 @@ private void ColAutoResize(int col) Rectangle rightArea = layout.Data; if (layout.ColumnHeadersVisible) + { rightArea = Rectangle.Union(rightArea, layout.ColumnHeaders); + } int left = GetColBeg(col); @@ -5187,7 +5527,9 @@ private void ColResizeEnd(MouseEventArgs e) int x = rightToLeft ? Math.Max(e.X, layout.Data.X) : Math.Min(e.X, layout.Data.Right + 1); int delta = x - GetColEnd(trackColumn); if (rightToLeft) + { delta = -delta; + } if (trackColAnchor != x && delta != 0) { @@ -5325,7 +5667,9 @@ private void RowAutoResize(int row) EndEdit(); CurrencyManager listManager = ListManager; if (listManager == null) + { return; + } Graphics g = CreateGraphicsInternal(); try @@ -5352,7 +5696,10 @@ private void RowAutoResize(int row) Rectangle rightArea = layout.Data; if (layout.RowHeadersVisible) + { rightArea = Rectangle.Union(rightArea, layout.RowHeaders); + } + int top = GetRowTop(row); rightArea.Height -= rightArea.Y - top; rightArea.Y = top; @@ -5450,29 +5797,43 @@ private void RowResizeEnd(MouseEventArgs e) private void ColumnHeaderClicked(PropertyDescriptor prop) { if (!CommitEdit()) + { return; + } // OnColumnHeaderClick(EventArgs.Empty); bool allowSorting; if (myGridTable.IsDefault) + { allowSorting = AllowSorting; + } else + { allowSorting = myGridTable.AllowSorting; + } if (!allowSorting) + { return; + } // if (CompModSwitches.DataGridCursor.OutputVerbose) Debug.WriteLine("DataGridCursor: We are about to sort column " + col.ToString()); ListSortDirection direction = ListManager.GetSortDirection(); PropertyDescriptor sortColumn = ListManager.GetSortProperty(); if (sortColumn != null && sortColumn.Equals(prop)) + { direction = (direction == ListSortDirection.Ascending) ? ListSortDirection.Descending : ListSortDirection.Ascending; + } else + { // defaultSortDirection : ascending direction = ListSortDirection.Ascending; + } if (listManager.Count == 0) + { return; + } ListManager.SetSort(prop, direction); ResetSelection(); @@ -5497,7 +5858,9 @@ private bool CommitEdit() // 2. this is not the result of moving focus inside the data grid and // 3. if the user was scrolling if (!gridState[GRIDSTATE_isEditing] && !gridState[GRIDSTATE_isNavigating] || (gridState[GRIDSTATE_editControlChanging] && !gridState[GRIDSTATE_isScrolling])) + { return true; + } // the same rules from editColumn.OnEdit // flag that we are editing the Edit control, so if we get a OnLayout on the @@ -5514,12 +5877,17 @@ private bool CommitEdit() } if (focusTheGrid && gridState[GRIDSTATE_canFocus]) + { Focus(); + } + editColumn.ConcedeFocus(); // set the focus back to the grid if (focusTheGrid && gridState[GRIDSTATE_canFocus] && CanFocus && !Focused) + { Focus(); + } // reset the editControl flag gridState[GRIDSTATE_editControlChanging] = false; @@ -5532,7 +5900,9 @@ private bool CommitEdit() gridState[GRIDSTATE_editControlChanging] = false; if (retVal) + { gridState[GRIDSTATE_isEditing] = false; + } return retVal; } @@ -5548,7 +5918,9 @@ private int ComputeDeltaRows(int targetRow) // + "targetRow = " + targetRow.ToString()); if (firstVisibleRow == targetRow) + { return 0; + } int dRows = 0; int firstVisibleRowLogicalTop = -1; @@ -5560,11 +5932,20 @@ private int ComputeDeltaRows(int targetRow) for (int row = 0; row < nRows; ++row) { if (row == firstVisibleRow) + { firstVisibleRowLogicalTop = cy; + } + if (row == targetRow) + { targetRowLogicalTop = cy; + } + if (targetRowLogicalTop != -1 && firstVisibleRowLogicalTop != -1) + { break; + } + cy += localGridRows[row].Height; } @@ -5607,7 +5988,10 @@ private int ComputeFirstVisibleRow(int firstVisibleRowLogicalTop) for (first = 0; first < nRows; ++first) { if (cy >= firstVisibleRowLogicalTop) + { break; + } + cy += localGridRows[first].Height; } return first; @@ -5768,7 +6152,9 @@ private void ComputeLayout() // user enlarges the form then the old area will not be invalidated. // if (!oldResizeRect.Equals(layout.ResizeBoxRect) && !layout.ResizeBoxRect.IsEmpty) + { Invalidate(layout.ResizeBoxRect); + } layout.dirty = false; Debug.WriteLineIf(CompModSwitches.DataGridLayout.TraceVerbose, "DataGridLayout: " + layout.ToString()); @@ -5807,9 +6193,14 @@ internal void ComputeMinimumRowHeaderWidth() { minRowHeaderWidth = errorRowBitmapWidth; // the size of the pencil, star and row selector images are the same as the image for the error bitmap if (ListHasErrors) + { minRowHeaderWidth += errorRowBitmapWidth; + } + if (myGridTable != null && myGridTable.RelationsList.Count != 0) + { minRowHeaderWidth += 15; // the size of the plus/minus glyph and spacing around it + } } /// @@ -5845,7 +6236,10 @@ private void ComputeVisibleColumns() { // if (columns.Visible && columns.PropertyDescriptor != null) if (columns[curCol].PropertyDescriptor != null) + { cx += columns[curCol].Width; + } + curCol++; visibleColumns++; } @@ -5859,10 +6253,15 @@ private void ComputeVisibleColumns() for (int i = firstVisibleCol - 1; i > 0; i--) { if (cx + columns[i].Width > visibleWidth) + { break; + } // if (columns.Visible && columns.PropertyDescriptor != null) if (columns[i].PropertyDescriptor != null) + { cx += columns[i].Width; + } + visibleColumns++; firstVisibleCol--; } @@ -5935,9 +6334,14 @@ private int ComputeFirstVisibleColumn() { // if (columns[first].Visible && columns[first].PropertyDescriptor != null); if (columns[first].PropertyDescriptor != null) + { cx += columns[first].Width; + } + if (cx > horizontalOffset) + { break; + } } // first may actually be the number of columns // in that case all the columns fit in the layout data @@ -5984,7 +6388,10 @@ private void ComputeVisibleRows() for (int i = firstVisibleRow; i < numRows; ++i) { if (cy > visibleHeight) + { break; + } + cy += localGridRows[i].Height; visibleRows++; } @@ -5995,7 +6402,10 @@ private void ComputeVisibleRows() { int height = localGridRows[i].Height; if (cy + height > visibleHeight) + { break; + } + cy += height; firstVisibleRow--; visibleRows++; @@ -6004,7 +6414,9 @@ private void ComputeVisibleRows() numVisibleRows = numTotallyVisibleRows = visibleRows; if (cy > visibleHeight) + { numTotallyVisibleRows--; + } Debug.Assert(numVisibleRows >= 0, "the number of visible rows can't be negative"); Debug.Assert(numTotallyVisibleRows >= 0, "the number of totally visible rows can't be negative"); @@ -6139,9 +6551,14 @@ protected override void Dispose(bool disposing) if (disposing) { if (vertScrollBar != null) + { vertScrollBar.Dispose(); + } + if (horizScrollBar != null) + { horizScrollBar.Dispose(); + } if (toBeDisposedEditingControl != null) { @@ -6156,7 +6573,9 @@ protected override void Dispose(bool disposing) Debug.Assert(myGridTable == null || myGridTable.IsDefault || tables.Contains(myGridTable), "how come that the currentTable is not in the list of tables?"); #endif // DEBUG for (int i = 0; i < tables.Count; i++) + { tables[i].Dispose(); + } } } base.Dispose(disposing); @@ -6240,20 +6659,25 @@ private void Edit(string displayText) // what do you want to edit when there are no rows? if (DataGridRowsLength == 0) + { return; + } localGridRows[currentRow].OnEdit(); editRow = localGridRows[currentRow]; // if the list has no columns, then what good is an edit? if (myGridTable.GridColumnStyles.Count == 0) + { return; + } // what if the currentCol does not have a propDesc? editColumn = myGridTable.GridColumnStyles[currentCol]; if (editColumn.PropertyDescriptor == null) + { return; - + } Rectangle cellBounds = Rectangle.Empty; if (currentRow < firstVisibleRow || currentRow > firstVisibleRow + numVisibleRows || @@ -6312,8 +6736,9 @@ public bool EndEdit(DataGridColumnStyle gridColumn, int rowNumber, bool shouldAb ret = true; } else + { ret = CommitEdit(); - + } } return ret; } @@ -6327,7 +6752,9 @@ private void EndEdit() Debug.WriteLineIf(CompModSwitches.DataGridEditing.TraceVerbose, "DataGridEditing: EndEdit"); if (!gridState[GRIDSTATE_isEditing] && !gridState[GRIDSTATE_isNavigating]) + { return; + } if (!CommitEdit()) { @@ -6351,9 +6778,14 @@ private void EnforceValidDataMember(object value) { Debug.Assert(value != null, "we should not have a null dataSource when we want to check for a valid dataMember"); if (DataMember == null || DataMember.Length == 0) + { return; + } + if (BindingContext == null) + { return; + } // try { @@ -6539,7 +6971,9 @@ public void EndInit() SetDataGridTable(TableStyles[ListManager.GetListName()], true); // true for forcing column creation } if (myGridTable != null) + { myGridTable.DataGrid = this; + } } /// @@ -6548,7 +6982,9 @@ public void EndInit() private int GetColFromX(int x) { if (myGridTable == null) + { return -1; + } Rectangle inside = layout.Data; Debug.Assert(x >= inside.X && x < inside.Right, "x must be inside the horizontal bounds of layout.Data"); @@ -6564,9 +7000,15 @@ private int GetColFromX(int x) { // if (columns[col].Visible && columns[col].PropertyDescriptor != null) if (columns[col].PropertyDescriptor != null) + { cx += columns[col].Width; + } + if (cx > x) + { return col; + } + ++col; } return -1; @@ -6589,7 +7031,9 @@ internal int GetColBeg(int col) { // if (columns[i].Visible && columns[i].PropertyDescriptor != null) if (columns[i].PropertyDescriptor != null) + { offset += columns[i].Width; + } } return MirrorPoint(offset, layout.Data, isRightToLeft()); } @@ -6617,9 +7061,13 @@ private int GetColumnWidthSum() int columnsCount = columns.Count; for (int i = 0; i < columnsCount; i++) + { // if (columns[i].Visible && columns[i].PropertyDescriptor != null) if (columns[i].PropertyDescriptor != null) + { sum += columns[i].Width; + } + } } return sum; } @@ -6634,10 +7082,16 @@ private DataGridRelationshipRow[] GetExpandableRows() int nExpandableRows = DataGridRowsLength; DataGridRow[] localGridRows = DataGridRows; if (policy.AllowAdd) + { nExpandableRows = Math.Max(nExpandableRows - 1, 0); + } + DataGridRelationshipRow[] expandableRows = new DataGridRelationshipRow[nExpandableRows]; for (int i = 0; i < nExpandableRows; i++) + { expandableRows[i] = (DataGridRelationshipRow)localGridRows[i]; + } + return expandableRows; } @@ -6865,10 +7319,14 @@ public HitTestInfo HitTest(int x, int y) } if (!layout.Inside.Contains(x, y)) + { return ci; + } if (layout.TopLeftHeader.Contains(x, y)) + { return ci; + } // check for column resize if (layout.ColumnHeaders.Contains(x, y)) @@ -6876,7 +7334,10 @@ public HitTestInfo HitTest(int x, int y) ci.type = HitTestType.ColumnHeader; ci.col = GetColFromX(x); if (ci.col < 0) + { return HitTestInfo.Nowhere; + } + int right = GetColBeg(ci.col + 1); bool rightToLeft = isRightToLeft(); if ((rightToLeft && x - right < 8) || (!rightToLeft && right - x < 8)) @@ -6892,7 +7353,9 @@ public HitTestInfo HitTest(int x, int y) ci.type = HitTestType.RowHeader; ci.row = GetRowFromY(y); if (ci.row < 0) + { return HitTestInfo.Nowhere; + } // find out if the click was a RowResize click DataGridRow[] localGridRows = DataGridRows; @@ -6911,7 +7374,10 @@ public HitTestInfo HitTest(int x, int y) ci.col = GetColFromX(x); ci.row = GetRowFromY(y); if (ci.col < 0 || ci.row < 0) + { return HitTestInfo.Nowhere; + } + return ci; } return ci; @@ -6934,7 +7400,9 @@ public HitTestInfo HitTest(Point position) private void InitializeColumnWidths() { if (myGridTable == null) + { return; + } GridColumnStylesCollection columns = myGridTable.GridColumnStyles; int numCols = columns.Count; @@ -6950,7 +7418,9 @@ private void InitializeColumnWidths() { // if the column width is not -1, then this column was initialized already if (columns[col]._width != -1) + { continue; + } columns[col]._width = preferredColumnWidth; } @@ -6970,7 +7440,9 @@ internal void InvalidateInside() internal void InvalidateCaption() { if (layout.CaptionVisible) + { Invalidate(layout.Caption); + } } /// @@ -6992,12 +7464,16 @@ internal void InvalidateColumn(int column) { GridColumnStylesCollection gridColumns = myGridTable.GridColumnStyles; if (column < 0 || gridColumns == null || gridColumns.Count <= column) + { return; + } Debug.Assert(gridColumns[column].PropertyDescriptor != null, "how can we invalidate a column that is invisible?"); // bail if the column is not visible. if (column < firstVisibleCol || column > firstVisibleCol + numVisibleCols - 1) + { return; + } Rectangle columnArea = new Rectangle { @@ -7011,7 +7487,10 @@ internal void InvalidateColumn(int column) for (int i = firstVisibleCol; i < gridColumnsCount; ++i) { if (i == column) + { break; + } + x += gridColumns[i].Width; } columnArea.X = x; @@ -7025,7 +7504,9 @@ internal void InvalidateColumn(int column) internal void InvalidateParentRows() { if (layout.ParentRowsVisible) + { Invalidate(layout.ParentRows); + } } /// @@ -7061,7 +7542,9 @@ private void InvalidateRowHeader(int rowNumber) if (rowNumber >= firstVisibleRow && rowNumber < firstVisibleRow + numVisibleRows) { if (!layout.RowHeadersVisible) + { return; + } Rectangle invalid = new Rectangle { @@ -7085,7 +7568,10 @@ internal void InvalidateRowRect(int rowNumber, Rectangle r) Debug.WriteLineIf(CompModSwitches.DataGridPainting.TraceVerbose, "DataGridPainting: Invalidating a rect in row " + rowNumber.ToString(CultureInfo.InvariantCulture)); Rectangle inner = new Rectangle(rowRect.X + r.X, rowRect.Y + r.Y, r.Width, r.Height); if (vertScrollBar.Visible && isRightToLeft()) + { inner.X -= vertScrollBar.Width; + } + Invalidate(inner); } } @@ -7096,7 +7582,10 @@ internal void InvalidateRowRect(int rowNumber, Rectangle r) public bool IsExpanded(int rowNumber) { if (rowNumber < 0 || rowNumber > DataGridRowsLength) + { throw new ArgumentOutOfRangeException(nameof(rowNumber)); + } + DataGridRow[] localGridRows = DataGridRows; // @@ -7109,7 +7598,9 @@ public bool IsExpanded(int rowNumber) return relRow.Expanded; } else + { return false; + } } /// @@ -7174,7 +7665,10 @@ private void LayoutScrollBars() int horizHeight = horizScrollBar.Height; layout.Data.Height -= horizHeight; if (layout.RowHeadersVisible) + { layout.RowHeaders.Height -= horizHeight; + } + needHorizScrollbar = true; } @@ -7188,7 +7682,9 @@ private void LayoutScrollBars() if (layout.ColumnHeadersVisible) { if (alignToRight) + { layout.ColumnHeaders.X += vertWidth; + } layout.ColumnHeaders.Width -= vertWidth; } @@ -7205,7 +7701,10 @@ private void LayoutScrollBars() int horizHeight = horizScrollBar.Height; layout.Data.Height -= horizHeight; if (layout.RowHeadersVisible) + { layout.RowHeaders.Height -= horizHeight; + } + needHorizScrollbar = true; recountRows = true; } @@ -7220,7 +7719,9 @@ private void LayoutScrollBars() if (layout.ColumnHeadersVisible) { if (alignToRight) + { layout.ColumnHeaders.X += vertWidth; + } layout.ColumnHeaders.Width -= vertWidth; } @@ -7267,7 +7768,9 @@ private void LayoutScrollBars() { int vertScrollBarTop = layout.Data.Y; if (layout.ColumnHeadersVisible) + { vertScrollBarTop = layout.ColumnHeaders.Y; + } // if numTotallyVisibleRows == 0 ( the height of the row is bigger than the height of // the grid ) then scroll in increments of 1. vertScrollBar.LargeChange = numTotallyVisibleRows != 0 ? numTotallyVisibleRows : 1; @@ -7278,7 +7781,9 @@ private void LayoutScrollBars() vertScrollBar.Enabled = Enabled; vertScrollBar.Visible = true; if (alignToRight) + { layout.Data.X += vertScrollBar.Width; + } } else { @@ -7292,7 +7797,9 @@ private void LayoutScrollBars() public void NavigateBack() { if (!CommitEdit() || parentRows.IsEmpty()) + { return; + } // when navigating back, if the grid is inAddNewRow state, cancel the currentEdit. // we do not need to recreate the rows cause we are navigating back. // the grid will catch any exception that happens. @@ -7324,7 +7831,9 @@ public void NavigateBack() // otherwise the DataSource_MetaDataChanged event will not get registered // properly if (parentRows.GetTopParent() == null) + { originalState = null; + } DataGridRow[] localGridRows = DataGridRows; // what if the user changed the ReadOnly property @@ -7341,7 +7850,10 @@ public void NavigateBack() newDataGridRows[i] = DataGridRows[i]; } if (!ReadOnly && policy.AllowAdd) + { newDataGridRows[newDataGridRowsLength - 1] = new DataGridAddNewRow(this, myGridTable, newDataGridRowsLength - 1); + } + SetDataGridRows(newDataGridRows, newDataGridRowsLength); } @@ -7356,7 +7868,9 @@ public void NavigateBack() if (dgTable != myGridTable) { for (int i = 0; i < localGridRows.Length; i++) + { localGridRows[i].DataGridTableStyle = myGridTable; + } } } @@ -7396,9 +7910,15 @@ public void NavigateBack() Invalidate(); // reposition the scroll bar if (vertScrollBar.Visible) + { vertScrollBar.Value = firstVisibleRow; + } + if (horizScrollBar.Visible) + { horizScrollBar.Value = HorizontalOffset + negOffset; + } + Edit(); OnNavigate(new NavigateEventArgs(false)); } @@ -7413,7 +7933,10 @@ public void NavigateTo(int rowNumber, string relationName) { // do not navigate if AllowNavigation is set to false if (!AllowNavigation) + { return; + } + DataGridRow[] localGridRows = DataGridRows; if (rowNumber < 0 || rowNumber > DataGridRowsLength - (policy.AllowAdd ? 2 : 1)) { @@ -7430,10 +7953,14 @@ internal void NavigateTo(string relationName, DataGridRow source, bool fromRow) { // do not navigate if AllowNavigation is set to false if (!AllowNavigation) + { return; + } // Commit the edit if possible if (!CommitEdit()) + { return; + } DataGridState childState; try @@ -7478,7 +8005,9 @@ internal void NavigateTo(string relationName, DataGridRow source, bool fromRow) // and then set the position in the listManager to the new row. // if (source.RowNumber != CurrentRow) + { listManager.Position = source.RowNumber; + } // We save our state if the parent rows stack is empty. if (parentRows.GetTopParent() == null) @@ -7567,7 +8096,9 @@ internal void OnColumnCollectionChanged(object sender, CollectionChangeEventArgs // and the action is refresh, then it means that the user // set the propDesc. we do not want to override this. if (e.Action != CollectionChangeAction.Refresh || e.Element == null) + { PairTableStylesAndGridColumns(listManager, myGridTable, false); + } } Invalidate(); PerformLayout(); @@ -7583,13 +8114,18 @@ private void PaintColumnHeaders(Graphics g) bool alignToLeft = isRightToLeft(); Rectangle boundingRect = layout.ColumnHeaders; if (!alignToLeft) + { boundingRect.X -= negOffset; + } + boundingRect.Width += negOffset; int columnHeaderWidth = PaintColumnHeaderText(g, boundingRect); if (alignToLeft) + { boundingRect.X = boundingRect.Right - columnHeaderWidth; + } boundingRect.Width = columnHeaderWidth; if (!FlatMode) @@ -7621,10 +8157,14 @@ private int PaintColumnHeaderText(Graphics g, Rectangle boundingRect) for (int col = firstVisibleCol; col < nGridCols; ++col) { if (gridColumns[col].PropertyDescriptor == null) + { continue; + } if (cx > boundingRect.Width) + { break; + } bool columnSorted = sortProperty != null && sortProperty.Equals(gridColumns[col].PropertyDescriptor); TriangleDirection whichWay = TriangleDirection.Up; @@ -7632,7 +8172,9 @@ private int PaintColumnHeaderText(Graphics g, Rectangle boundingRect) { ListSortDirection direction = ListManager.GetSortDirection(); if (direction == ListSortDirection.Descending) + { whichWay = TriangleDirection.Down; + } } if (alignRight) @@ -7655,9 +8197,13 @@ private int PaintColumnHeaderText(Graphics g, Rectangle boundingRect) // dataGrid, then use that property Brush headerBrush; if (myGridTable.IsDefault) + { headerBrush = HeaderBackBrush; + } else + { headerBrush = myGridTable.HeaderBackBrush; + } g.FillRectangle(headerBrush, textBounds); // granted, the code would be a lot cleaner if we were using a "new Rectangle" @@ -7733,7 +8279,10 @@ private int PaintColumnHeaderText(Graphics g, Rectangle boundingRect) if (!FlatMode) { if (alignRight && columnSorted) + { textBounds.X -= textBounds.Height; + } + textBounds.Width = paintedWidth; ControlPaint.DrawBorder3D(g, textBounds, Border3DStyle.RaisedInner); @@ -7747,7 +8296,9 @@ private int PaintColumnHeaderText(Graphics g, Rectangle boundingRect) textBounds = boundingRect; if (!alignRight) + { textBounds.X += cx; + } textBounds.Width -= cx; g.FillRectangle(backgroundBrush, textBounds); @@ -7762,7 +8313,10 @@ private int PaintColumnHeaderText(Graphics g, Rectangle boundingRect) private void PaintBorder(Graphics g, Rectangle bounds) { if (BorderStyle == BorderStyle.None) + { return; + } + if (BorderStyle == BorderStyle.Fixed3D) { Border3DStyle style = Border3DStyle.Sunken; @@ -7773,9 +8327,14 @@ private void PaintBorder(Graphics g, Rectangle bounds) Brush br; if (myGridTable.IsDefault) + { br = HeaderForeBrush; + } else + { br = myGridTable.HeaderForeBrush; + } + g.FillRectangle(br, bounds.X, bounds.Y, bounds.Width + 2, 2); g.FillRectangle(br, bounds.Right - 2, bounds.Y, 2, bounds.Height + 2); g.FillRectangle(br, bounds.X, bounds.Bottom - 2, bounds.Width + 2, 2); @@ -7817,9 +8376,13 @@ private void PaintGrid(Graphics g, Rectangle gridBounds) if (layout.TopLeftHeader.Width > 0) { if (myGridTable.IsDefault) + { g.FillRectangle(HeaderBackBrush, layout.TopLeftHeader); + } else + { g.FillRectangle(myGridTable.HeaderBackBrush, layout.TopLeftHeader); + } if (!FlatMode) { @@ -7840,7 +8403,9 @@ private void PaintGrid(Graphics g, Rectangle gridBounds) private void DeleteDataGridRows(int deletedRows) { if (deletedRows == 0) + { return; + } int currentRowCount = DataGridRowsLength; int newDataGridRowsLength = currentRowCount - deletedRows + (gridState[GRIDSTATE_inAddNewRow] ? 1 : 0); @@ -7894,7 +8459,9 @@ private void PaintRows(Graphics g, ref Rectangle boundingRect) for (int row = firstVisibleRow; row < numRows; row++) { if (cy > boundingRect.Height) + { break; + } rowBounds = boundingRect; rowBounds.Height = localGridRows[row].Height; @@ -7936,14 +8503,20 @@ private void PaintRows(Graphics g, ref Rectangle boundingRect) } if (!alignRight) + { rowBounds.X += headerBounds.Width; + } + rowBounds.Width -= headerBounds.Width; } if (g.IsVisible(rowBounds)) { dataBounds = rowBounds; if (!alignRight) + { dataBounds.X -= negOffset; + } + dataBounds.Width += negOffset; localGridRows[row].Paint(g, dataBounds, rowBounds, firstVisibleCol, numCols, alignRight); @@ -7991,7 +8564,10 @@ protected override bool ProcessDialogKey(Keys keyData) case Keys.A: KeyEventArgs ke = new KeyEventArgs(keyData); if (ProcessGridKey(ke)) + { return true; + } + break; case Keys.C: @@ -7999,7 +8575,9 @@ protected override bool ProcessDialogKey(Keys keyData) { // the user pressed Ctrl-C if (!Bound) + { break; + } // need to distinguish between selecting a set of rows, and // selecting just one column. @@ -8073,7 +8651,10 @@ private void DeleteRows(DataGridRow[] localGridRows) int currentRowsCount = listManager == null ? 0 : listManager.Count; if (Visible) + { BeginUpdateInternal(); + } + try { if (ListManager != null) @@ -8105,7 +8686,10 @@ private void DeleteRows(DataGridRow[] localGridRows) RecreateDataGridRows(); gridState[GRIDSTATE_inDeleteRow] = false; if (Visible) + { EndUpdateInternal(); + } + throw; } // keep the copy of the old rows in place @@ -8122,7 +8706,9 @@ private void DeleteRows(DataGridRow[] localGridRows) gridState[GRIDSTATE_inDeleteRow] = false; if (Visible) + { EndUpdateInternal(); + } if (listManager != null && currentRowsCount != listManager.Count + rowsDeleted) { @@ -8143,7 +8729,9 @@ private int MoveLeftRight(GridColumnStylesCollection cols, int startCol, bool go { // if (cols[i].Visible && cols[i].PropertyDescriptor != null) if (cols[i].PropertyDescriptor != null) + { return i; + } } return i; } @@ -8153,7 +8741,9 @@ private int MoveLeftRight(GridColumnStylesCollection cols, int startCol, bool go { // if (cols[i].Visible && cols[i].PropertyDescriptor != null) if (cols[i].PropertyDescriptor != null) + { return i; + } } return i; } @@ -8170,7 +8760,9 @@ protected bool ProcessGridKey(KeyEventArgs ke) { Debug.WriteLineIf(CompModSwitches.DataGridKeys.TraceVerbose, "DataGridKeys: ProcessGridKey " + TypeDescriptor.GetConverter(typeof(Keys)).ConvertToString(ke.KeyCode)); if (listManager == null || myGridTable == null) + { return false; + } DataGridRow[] localGridRows = DataGridRows; KeyEventArgs biDiKe = ke; @@ -8235,7 +8827,10 @@ protected bool ProcessGridKey(KeyEventArgs ke) ResetSelection(); for (int i = 0; i <= savedCurrentRow; i++) + { gridRows[i].Selected = true; + } + numSelectedRows = savedCurrentRow + 1; // hide the edit box // @@ -8322,7 +8917,9 @@ protected bool ProcessGridKey(KeyEventArgs ke) ResetSelection(); for (int i = savedCurrentRow; i <= currentRow; i++) + { gridRows[i].Selected = true; + } numSelectedRows = currentRow - savedCurrentRow + 1; // hide the edit box @@ -8517,7 +9114,10 @@ protected bool ProcessGridKey(KeyEventArgs ke) if ((biDiKe.Modifiers & Keys.Modifiers) == Keys.Alt) { if (Caption.BackButtonVisible) + { NavigateBack(); + } + return true; } @@ -8541,7 +9141,9 @@ protected bool ProcessGridKey(KeyEventArgs ke) if (newCol == -1) { if (currentRow == 0) + { return true; + } else { // go to the previous row: @@ -8583,7 +9185,9 @@ protected bool ProcessGridKey(KeyEventArgs ke) CurrentRow++; } else + { CurrentColumn = newCol; + } } break; case Keys.F2: @@ -8695,7 +9299,9 @@ protected bool ProcessGridKey(KeyEventArgs ke) // yield the return key if there is no editing if (!gridState[GRIDSTATE_isEditing]) + { return false; + } // Ctrl-Enter will call EndCurrentEdit if ((biDiKe.Modifiers & Keys.Control) != 0 && !biDiKe.Alt) @@ -8721,8 +9327,12 @@ protected bool ProcessGridKey(KeyEventArgs ke) { DataGridRow[] gridRows = DataGridRows; for (int i = 0; i < DataGridRowsLength; i++) + { if (gridRows[i] is DataGridRelationshipRow) + { gridRows[i].Selected = true; + } + } numSelectedRows = DataGridRowsLength - (policy.AllowAdd ? 1 : 0); // hide the edit box @@ -8801,7 +9411,9 @@ protected override bool ProcessKeyPreview(ref Message m) { KeyEventArgs ke = new KeyEventArgs((Keys)(unchecked((int)(long)m.WParam)) | ModifierKeys); if (ke.KeyCode == Keys.Tab) + { return ProcessGridKey(ke); + } } return base.ProcessKeyPreview(ref m); @@ -8815,7 +9427,10 @@ protected override bool ProcessKeyPreview(ref Message m) protected bool ProcessTabKey(Keys keyData) { if (listManager == null || myGridTable == null) + { return false; + } + bool wasEditing = false; int columnCount = myGridTable.GridColumnStyles.Count; bool biDi = isRightToLeft(); @@ -8837,7 +9452,9 @@ protected bool ProcessTabKey(Keys keyData) { // when the user hits ctrl-alt-tab just ignore it. if ((keyData & Keys.Alt) == Keys.Alt) + { return true; + } // navigate to the next control in the form Keys ke = keyData & ~(Keys.Control); @@ -8897,12 +9514,18 @@ protected bool ProcessTabKey(Keys keyData) if (localRows[CurrentRow].ProcessTabKey(keyData, layout.RowHeaders, isRightToLeft())) { if (cols.Count > 0) + { cols[CurrentColumn].ConcedeFocus(); + } + gridState[GRIDSTATE_childLinkFocused] = true; // let the grid regain focus // introduced because of that BeginInvoke thing in the OnLeave method.... if (gridState[GRIDSTATE_canFocus] && CanFocus && !Focused) + { Focus(); + } + return true; } } @@ -8930,12 +9553,18 @@ protected bool ProcessTabKey(Keys keyData) { CurrentRow--; if (cols.Count > 0) + { cols[CurrentColumn].ConcedeFocus(); + } + gridState[GRIDSTATE_childLinkFocused] = true; // let the grid regain focus // introduced because of that BeginInvoke thing in the OnLeave method.... if (gridState[GRIDSTATE_canFocus] && CanFocus && !Focused) + { Focus(); + } + return true; } } @@ -8972,7 +9601,10 @@ protected bool ProcessTabKey(Keys keyData) if (CurrentColumn == lastColumnMarkedVisible) { if (CurrentRow != DataGridRowsLength - 1) + { CurrentColumn = firstColumnMarkedVisible; + } + CurrentRow = CurrentRow + 1; } else @@ -8992,7 +9624,9 @@ protected bool ProcessTabKey(Keys keyData) CurrentColumn = lastColumnMarkedVisible; } if (!gridState[GRIDSTATE_childLinkFocused]) // + { CurrentRow--; + } } else if (gridState[GRIDSTATE_childLinkFocused] && CurrentColumn == lastColumnMarkedVisible) { @@ -9051,9 +9685,13 @@ internal void RecalculateFonts() captionFontHeight = CaptionFont.Height; if (myGridTable == null || myGridTable.IsDefault) + { headerFontHeight = HeaderFont.Height; + } else + { headerFontHeight = myGridTable.HeaderFont.Height; + } } // the BackButtonClicked event: @@ -9101,8 +9739,12 @@ protected void ResetSelection() { DataGridRow[] localGridRows = DataGridRows; for (int i = 0; i < DataGridRowsLength; ++i) + { if (localGridRows[i].Selected) + { localGridRows[i].Selected = false; + } + } } numSelectedRows = 0; lastRowSelected = -1; @@ -9130,9 +9772,14 @@ private void ResetUIState() // invalidate the horizontalscrollbar and the vertical scrollbar // if (horizScrollBar.Visible) + { horizScrollBar.Invalidate(); + } + if (vertScrollBar.Visible) + { vertScrollBar.Invalidate(); + } } /// @@ -9169,7 +9816,10 @@ private void ScrollDown(int rows) int deltaY = ComputeRowDelta(oldFirstRow, newFirstRow); Rectangle rowsRect = layout.Data; if (layout.RowHeadersVisible) + { rowsRect = Rectangle.Union(rowsRect, layout.RowHeaders); + } + NativeMethods.RECT scrollArea = NativeMethods.RECT.FromXYWH(rowsRect.X, rowsRect.Y, rowsRect.Width, rowsRect.Height); SafeNativeMethods.ScrollWindow(new HandleRef(this, Handle), 0, deltaY, ref scrollArea, ref scrollArea); OnScroll(EventArgs.Empty); @@ -9198,22 +9848,36 @@ private void ScrollRight(int columns) // if we try to scroll past the last totally visible column, // then the toolTips will dissapear if (myGridTable.IsDefault) + { nVisibleCols = nGridCols; + } else + { for (int i = 0; i < nGridCols; i++) + { if (gridColumns[i].PropertyDescriptor != null) + { nVisibleCols++; + } + } + } if (lastTotallyVisibleCol == nVisibleCols - 1 && columns > 0 || firstVisibleCol == 0 && columns < 0 && negOffset == 0) + { return; + } newCol = Math.Min(newCol, nGridCols - 1); for (int i = 0; i < newCol; i++) + { // if (gridColumns[i].Visible && gridColumns[i].PropertyDescriptor != null) if (gridColumns[i].PropertyDescriptor != null) + { newColOffset += gridColumns[i].Width; + } + } HorizontalOffset = newColOffset; } @@ -9230,12 +9894,16 @@ private void ScrollToColumn(int targetCol) int dCols = targetCol - firstVisibleCol; if (targetCol > lastTotallyVisibleCol && lastTotallyVisibleCol != -1) + { dCols = targetCol - lastTotallyVisibleCol; + } // if only part of the currentCol is visible // then we should still scroll if (dCols != 0 || negOffset != 0) + { ScrollRight(dCols); + } } /// @@ -9278,9 +9946,13 @@ private void PairTableStylesAndGridColumns(CurrencyManager lm, DataGridTableStyl // we have to create some default columns for each of the propertyDescriptors // if (forceColumnCreation) + { gridTable.SetGridColumnStylesCollection(lm); + } else + { gridTable.SetRelationsList(lm); + } } else { @@ -9289,7 +9961,9 @@ private void PairTableStylesAndGridColumns(CurrencyManager lm, DataGridTableStyl // the propertyDescriptors from the current gridColumns // for (int i = 0; i < gridCols.Count; i++) + { gridCols[i].PropertyDescriptor = null; + } // pair the propertyDescriptor from each column to the actual property descriptor // from the listManager @@ -9368,16 +10042,22 @@ internal void SetDataGridTable(DataGridTableStyle newTable, bool forceColumnCrea // before parenting them. // if (newTable != null) + { newTable.DataGrid = this; + } // pair the tableStyles and GridColumns // if (listManager != null) + { PairTableStylesAndGridColumns(listManager, myGridTable, forceColumnCreation); + } // reset the relations UI on the newTable if (newTable != null) + { newTable.ResetRelationsUI(); + } // set the isNavigating to false gridState[GRIDSTATE_isNavigating] = false; @@ -9389,9 +10069,14 @@ internal void SetDataGridTable(DataGridTableStyle newTable, bool forceColumnCrea // current listName, then we should set the currentRow to the // position in the listManager if (listManager == null) + { currentRow = 0; + } else + { currentRow = listManager.Position == -1 ? 0 : listManager.Position; + } + ResetHorizontalOffset(); negOffset = 0; ResetUIState(); @@ -10136,13 +10821,19 @@ public bool UpdatePolicy(CurrencyManager listManager, bool gridReadOnly) if (listManager == null) { if (!allowAdd) + { change = true; + } + allowAdd = allowEdit = allowRemove = true; } else { if (AllowAdd != listManager.AllowAdd && !gridReadOnly) + { change = true; + } + AllowAdd = listManager.AllowAdd && !gridReadOnly && bl != null && bl.SupportsChangeNotification; AllowEdit = listManager.AllowEdit && !gridReadOnly; AllowRemove = listManager.AllowRemove && !gridReadOnly && bl != null && bl.SupportsChangeNotification; // @@ -10159,9 +10850,13 @@ public bool UpdatePolicy(CurrencyManager listManager, bool gridReadOnly) private int MirrorRectangle(Rectangle R1, Rectangle rect, bool rightToLeft) { if (rightToLeft) + { return rect.Right + rect.X - R1.Right; + } else + { return R1.X; + } } // @@ -10172,9 +10867,13 @@ private int MirrorRectangle(Rectangle R1, Rectangle rect, bool rightToLeft) private int MirrorPoint(int x, Rectangle rect, bool rightToLeft) { if (rightToLeft) + { return rect.Right + rect.X - x; + } else + { return x; + } } // This function will return true if the RightToLeft property of the dataGrid is diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridAddNewRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridAddNewRow.cs index de82aa60e75..1068608d181 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridAddNewRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridAddNewRow.cs @@ -62,7 +62,9 @@ public override void OnEdit() public override void OnRowLeave() { if (DataBound) + { DataBound = false; + } } // the addNewRow has nothing to do with losing focus @@ -96,15 +98,23 @@ public override int Paint(Graphics g, Rectangle dataBounds = bounds; DataGridLineStyle gridStyle; if (dgTable.IsDefault) + { gridStyle = DataGrid.GridLineStyle; + } else + { gridStyle = dgTable.GridLineStyle; + } + int bWidth = DataGrid == null ? 0 : gridStyle == DataGridLineStyle.Solid ? 1 : 0; dataBounds.Height -= bWidth; int cx = base.PaintData(g, dataBounds, firstVisibleColumn, columnCount, alignToRight); if (bWidth > 0) + { PaintBottomBorder(g, bounds, cx, bWidth, alignToRight); + } + return cx; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs index a1c2accc21c..b94b57f3fd7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs @@ -148,15 +148,19 @@ protected internal override void ConcedeFocus() private Rectangle GetCheckBoxBounds(Rectangle bounds, bool alignToRight) { if (alignToRight) + { return new Rectangle(bounds.X + ((bounds.Width - idealCheckSize) / 2), bounds.Y + ((bounds.Height - idealCheckSize) / 2), bounds.Width < idealCheckSize ? bounds.Width : idealCheckSize, idealCheckSize); + } else + { return new Rectangle(Math.Max(0, bounds.X + ((bounds.Width - idealCheckSize) / 2)), Math.Max(0, bounds.Y + ((bounds.Height - idealCheckSize) / 2)), bounds.Width < idealCheckSize ? bounds.Width : idealCheckSize, idealCheckSize); + } } /// @@ -184,7 +188,9 @@ private bool IsReadOnly() { ret = ret || DataGridTableStyle.ReadOnly; if (DataGridTableStyle.DataGrid != null) + { ret = ret || DataGridTableStyle.DataGrid.ReadOnly; + } } return ret; } @@ -263,7 +269,9 @@ protected internal override bool Commit(CurrencyManager dataSource, int rowNum) // always invalidate Invalidate(); if (!isEditing) + { return true; + } SetColumnValueAtRow(dataSource, rowNum, currentValue); isEditing = false; @@ -289,7 +297,9 @@ protected internal override void Edit(CurrencyManager source, // DataGrid grid = DataGridTableStyle.DataGrid; if (!grid.Focused) + { grid.Focus(); + } if (!readOnly && !IsReadOnly()) { @@ -342,19 +352,25 @@ private void OnTrueValueChanged(EventArgs e) { EventHandler eh = Events[EventTrueValue] as EventHandler; if (eh != null) + { eh(this, e); + } } private void OnFalseValueChanged(EventArgs e) { EventHandler eh = Events[EventFalseValue] as EventHandler; if (eh != null) + { eh(this, e); + } } private void OnAllowNullChanged(EventArgs e) { EventHandler eh = Events[EventAllowNull] as EventHandler; if (eh != null) + { eh(this, e); + } } /// @@ -403,7 +419,10 @@ protected internal override void Paint(Graphics g, Rectangle bounds, CurrencyMan g.FillRectangle(selectionBrush, bounds); } else + { g.FillRectangle(backBrush, bounds); + } + g.Clip = r; if (checkedState == ButtonState.Inactive) @@ -475,7 +494,10 @@ protected internal override void EnterNullValue() // do not throw an exception when the column is marked as readOnly or // does not allowNull if (!AllowNull || IsReadOnly()) + { return; + } + if (currentValue != Convert.DBNull) { currentValue = Convert.DBNull; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs index 515b8b82ca3..68d4d2e650a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs @@ -170,7 +170,10 @@ internal Color BackColor if (!backBrush.Color.Equals(value)) { if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "Caption BackColor")); + } + backBrush = new SolidBrush(value); Invalidate(); } @@ -197,9 +200,13 @@ internal Font Font // did not set the CaptionFont // if (textFont == null) + { return dataGridFont; + } else + { return textFont; + } } set { @@ -266,9 +273,14 @@ internal string Text set { if (value == null) + { text = string.Empty; + } else + { text = value; + } + Invalidate(); } } @@ -295,7 +307,10 @@ internal Color ForeColor set { if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "Caption ForeColor")); + } + foreBrush = new SolidBrush(value); colorMap[0].NewColor = ForeColor; Invalidate(); @@ -352,7 +367,10 @@ protected virtual void AddEventHandler(object key, Delegate handler) lock (this) { if (handler == null) + { return; + } + for (EventEntry e = eventList; e != null; e = e.next) { if (e.key == key) @@ -393,13 +411,17 @@ internal event EventHandler DownClicked private void Invalidate() { if (dataGrid != null) + { dataGrid.InvalidateCaption(); + } } private void InvalidateCaptionRect(Rectangle r) { if (dataGrid != null) + { dataGrid.InvalidateCaptionRect(r); + } } private void InvalidateLocation(CaptionLocation loc) @@ -426,7 +448,9 @@ protected void OnBackwardClicked(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_BACKWARDCLICKED]; if (handler != null) + { handler(this, e); + } } } @@ -434,7 +458,9 @@ protected void OnCaptionClicked(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_CAPTIONCLICKED]; if (handler != null) + { handler(this, e); + } } protected void OnDownClicked(EventArgs e) @@ -443,7 +469,9 @@ protected void OnDownClicked(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_DOWNCLICKED]; if (handler != null) + { handler(this, e); + } } } @@ -465,13 +493,19 @@ private Bitmap GetBackButtonBmp(bool alignRight) if (alignRight) { if (leftButtonBitmap_bidi == null) + { leftButtonBitmap_bidi = GetBitmap("DataGridCaption.backarrow_bidi"); + } + return leftButtonBitmap_bidi; } else { if (leftButtonBitmap == null) + { leftButtonBitmap = GetBitmap("DataGridCaption.backarrow"); + } + return leftButtonBitmap; } } @@ -479,7 +513,10 @@ private Bitmap GetBackButtonBmp(bool alignRight) private Bitmap GetDetailsBmp() { if (magnifyingGlassBitmap == null) + { magnifyingGlassBitmap = GetBitmap("DataGridCaption.Details"); + } + return magnifyingGlassBitmap; } @@ -491,7 +528,9 @@ protected virtual Delegate GetEventHandler(object key) for (EventEntry e = eventList; e != null; e = e.next) { if (e.key == key) + { return e.handler; + } } return null; } @@ -647,7 +686,9 @@ private void PaintText(Graphics g, Rectangle bounds, bool alignToRight) Rectangle textBounds = bounds; if (textBounds.Width <= 0 || textBounds.Height <= 0) + { return; + } if (textBorderVisible) { @@ -692,17 +733,23 @@ private CaptionLocation FindLocation(int x, int y) if (!backButtonRect.IsEmpty) { if (backButtonRect.Contains(x, y)) + { return CaptionLocation.BackButton; + } } if (!downButtonRect.IsEmpty) { if (downButtonRect.Contains(x, y)) + { return CaptionLocation.DownButton; + } } if (!textRect.IsEmpty) { if (textRect.Contains(x, y)) + { return CaptionLocation.Text; + } } return CaptionLocation.Nowhere; } @@ -805,7 +852,9 @@ protected virtual void RaiseEvent(object key, EventArgs e) { Delegate handler = GetEventHandler(key); if (handler != null) + { ((EventHandler)handler)(this, e); + } } protected virtual void RemoveEventHandler(object key, Delegate handler) @@ -814,7 +863,10 @@ protected virtual void RemoveEventHandler(object key, Delegate handler) lock (this) { if (handler == null) + { return; + } + for (EventEntry e = eventList, prev = null; e != null; prev = e, e = e.next) { if (e.key == key) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs index 1487ec2d8d1..562c8c8d1a1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs @@ -193,7 +193,9 @@ public DataGridColumnStyle this[string columnName] DataGridColumnStyle column = (DataGridColumnStyle)items[i]; // NOTE: case-insensitive if (string.Equals(column.MappingName, columnName, StringComparison.OrdinalIgnoreCase)) + { return column; + } } return null; } @@ -207,7 +209,9 @@ internal DataGridColumnStyle MapColumnStyleToPropertyName(string mappingName) DataGridColumnStyle column = (DataGridColumnStyle)items[i]; // NOTE: case-insensitive if (string.Equals(column.MappingName, mappingName, StringComparison.OrdinalIgnoreCase)) + { return column; + } } return null; } @@ -229,7 +233,9 @@ public DataGridColumnStyle this[PropertyDescriptor propertyDesciptor] { DataGridColumnStyle column = (DataGridColumnStyle)items[i]; if (propertyDesciptor.Equals(column.PropertyDescriptor)) + { return column; + } } return null; } @@ -250,10 +256,17 @@ internal DataGridTableStyle DataGridTableStyle internal void CheckForMappingNameDuplicates(DataGridColumnStyle column) { if (string.IsNullOrEmpty(column.MappingName)) + { return; + } + for (int i = 0; i < items.Count; i++) + { if (((DataGridColumnStyle)items[i]).MappingName.Equals(column.MappingName) && column != items[i]) + { throw new ArgumentException(SR.DataGridColumnStyleDuplicateMappingName, "column"); + } + } } private void ColumnStyleMappingNameChanged(object sender, EventArgs pcea) @@ -282,7 +295,9 @@ public virtual int Add(DataGridColumnStyle column) // columns which are not the default should have a default // width of DataGrid.PreferredColumnWidth if (DataGridTableStyle != null && column.Width == -1) + { column._width = DataGridTableStyle.PreferredColumnWidth; + } #if false column.AddOnPropertyChanged(owner.OnColumnChanged); #endif @@ -382,7 +397,9 @@ public bool Contains(string name) DataGridColumnStyle column = (DataGridColumnStyle)e.Current; // NOTE: case-insensitive if (string.Compare(column.MappingName, name, true, CultureInfo.InvariantCulture) == 0) + { return true; + } } return false; } @@ -497,7 +514,9 @@ public int IndexOf(DataGridColumnStyle element) { DataGridColumnStyle column = (DataGridColumnStyle)items[i]; if (element == column) + { return i; + } } return -1; } @@ -508,7 +527,9 @@ public int IndexOf(DataGridColumnStyle element) protected void OnCollectionChanged(CollectionChangeEventArgs e) { if (onCollectionChanged != null) + { onCollectionChanged(this, e); + } DataGrid grid = owner.DataGrid; if (grid != null) @@ -530,15 +551,22 @@ public void Remove(DataGridColumnStyle column) int columnIndex = -1; int itemsCount = items.Count; for (int i = 0; i < itemsCount; ++i) + { if (items[i] == column) { columnIndex = i; break; } + } + if (columnIndex == -1) + { throw new InvalidOperationException(SR.DataGridColumnCollectionMissing); + } else + { RemoveAt(columnIndex); + } } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridDefaultColumnWidthTypeConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridDefaultColumnWidthTypeConverter.cs index 15b1cb554b7..b3ae492a919 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridDefaultColumnWidthTypeConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridDefaultColumnWidthTypeConverter.cs @@ -17,9 +17,13 @@ public class DataGridPreferredColumnWidthTypeConverter : TypeConverter public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string) || sourceType == typeof(int)) + { return true; + } else + { return false; + } } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) @@ -30,9 +34,13 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul { int pulica = (int)value; if (pulica == -1) + { return "AutoColumnResize (-1)"; + } else + { return pulica.ToString(CultureInfo.CurrentCulture); + } } else { @@ -40,7 +48,9 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul } } else + { return base.ConvertTo(context, culture, value, destinationType); + } } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) @@ -49,9 +59,13 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c { string text = value.ToString(); if (text.Equals("AutoColumnResize (-1)")) + { return -1; + } else + { return int.Parse(text, CultureInfo.CurrentCulture); + } } else if (value.GetType() == typeof(int)) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRows.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRows.cs index 06c9207a5b4..c1b06385879 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRows.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRows.cs @@ -105,7 +105,10 @@ internal Color BackColor set { if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "Parent Rows BackColor")); + } + if (value != backBrush.Color) { backBrush = new SolidBrush(value); @@ -245,7 +248,10 @@ internal Color ForeColor set { if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "Parent Rows ForeColor")); + } + if (value != foreBrush.Color) { foreBrush = new SolidBrush(value); @@ -303,7 +309,9 @@ internal void SetParentCount(int count) internal void CheckNull(object value, string propName) { if (value == null) + { throw new ArgumentNullException(nameof(propName)); + } } internal void Dispose() @@ -351,7 +359,9 @@ internal DataGridState PopTop() internal void Invalidate() { if (dataGrid != null) + { dataGrid.InvalidateParentRows(); + } } internal void InvalidateRect(Rectangle rect) @@ -367,7 +377,9 @@ internal void InvalidateRect(Rectangle rect) internal void OnLayout() { if (parentsCount == rowHeights.Count) + { return; + } int height = 0; if (totalHeight == 0) @@ -415,9 +427,14 @@ internal void OnLayout() { Debug.Assert(parentsCount == rowHeights.Count - 1, "we do layout only for push/popTop"); if (parentsCount == 0) + { totalHeight = 0; + } else + { totalHeight -= (int)rowHeights[rowHeights.Count - 1]; + } + rowHeights.RemoveAt(rowHeights.Count - 1); } } @@ -495,18 +512,26 @@ internal void OnMouseDown(int x, int y, bool alignToRight) downRightArrow = true; if (alignToRight) + { LeftArrowClick(cellCount); + } else + { RightArrowClick(cellCount); + } } else if (layout.leftArrow.Contains(x, y)) { downLeftArrow = true; if (alignToRight) + { RightArrowClick(cellCount); + } else + { LeftArrowClick(cellCount); + } } else { @@ -796,10 +821,15 @@ private void PaintParentRows(Graphics g, Rectangle bounds, bool alignToRight) { rowBounds.Height = (int)rowHeights[row]; if (rowBounds.Y > bounds.Bottom) + { break; + } + int paintedWidth = PaintRow(g, rowBounds, row, dataGrid.Font, alignToRight, tableNameBoxWidth, colsNameWidths, colsDataWidths); if (row == parentsCount - 1) + { break; + } // draw the grid line below g.DrawLine(gridLinePen, rowBounds.X, rowBounds.Bottom, @@ -831,14 +861,20 @@ private Bitmap GetBitmap(string bitmapName) private Bitmap GetRightArrowBitmap() { if (rightArrow == null) + { rightArrow = GetBitmap("DataGridParentRows.RightArrow"); + } + return rightArrow; } private Bitmap GetLeftArrowBitmap() { if (leftArrow == null) + { leftArrow = GetBitmap("DataGridParentRows.LeftArrow"); + } + return leftArrow; } @@ -970,7 +1006,9 @@ private int PaintRow(Graphics g, Rectangle bounds, int row, Font font, bool alig } if (paintedWidth >= bounds.Width) + { return bounds.Width; // we painted everything + } rowBounds.Width -= paintedWidth; rowBounds.X += alignToRight ? 0 : paintedWidth; @@ -998,7 +1036,9 @@ private int PaintColumns(Graphics g, Rectangle bounds, DataGridState dgs, Font f for (int i = 0; i < cols.Count; i++) { if (cx >= bounds.Width) + { break; + } // paint the column name, if we have to if (dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.ColumnName || @@ -1022,7 +1062,9 @@ private int PaintColumns(Graphics g, Rectangle bounds, DataGridState dgs, Font f } if (cx >= bounds.Width) + { break; + } if (skippedCells < horizOffset) { @@ -1080,13 +1122,17 @@ private int PaintText(Graphics g, Rectangle textBounds, string text, Font font, { Font textFont = font; if (bold) + { try { textFont = new Font(font, FontStyle.Bold); } catch { } + } else + { textFont = font; + } // right now, we paint the entire box, cause it will be used anyway g.FillRectangle(BackBrush, textBounds); @@ -1114,9 +1160,13 @@ private int MirrorRect(Rectangle surroundingRect, Rectangle containedRect, bool { Debug.Assert(containedRect.X >= surroundingRect.X && containedRect.Right <= surroundingRect.Right, "containedRect is not contained in surroundingRect"); if (alignToRight) + { return surroundingRect.Right - containedRect.Right + surroundingRect.X; + } else + { return containedRect.X; + } } private class Layout diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRelationshipRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRelationshipRow.cs index 62b6247b90d..27d21a7c91a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRelationshipRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRelationshipRow.cs @@ -92,11 +92,18 @@ public virtual bool Expanded set { if (expanded == value) + { return; + } + if (expanded) + { Collapse(); + } else + { Expand(); + } } } @@ -192,17 +199,25 @@ public override int Height { int height = base.Height; if (expanded) + { return height + GetRelationshipRect().Height; + } else + { return height; + } } set { // we should use the RelationshipRect only when the row is expanded if (expanded) + { base.Height = value - GetRelationshipRect().Height; + } else + { base.Height = value; + } } } @@ -237,7 +252,9 @@ public override Rectangle GetNonScrollableArea() return GetRelationshipRect(); } else + { return Rectangle.Empty; + } } private Rectangle GetRelationshipRect() @@ -303,7 +320,10 @@ private Rectangle GetRelationshipRectWithMirroring() private bool PointOverPlusMinusGlyph(int x, int y, Rectangle rowHeaders, bool alignToRight) { if (dgTable == null || dgTable.DataGrid == null || !dgTable.DataGrid.AllowNavigation) + { return false; + } + Rectangle insideRowHeaders = rowHeaders; if (!DataGrid.FlatMode) { @@ -342,7 +362,9 @@ public override bool OnMouseDown(int x, int y, Rectangle rowHeaders, bool alignT } if (!expanded) + { return base.OnMouseDown(x, y, rowHeaders, alignToRight); + } // hit test for relationships Rectangle relRect = GetRelationshipRectWithMirroring(); @@ -366,7 +388,9 @@ public override bool OnMouseDown(int x, int y, Rectangle rowHeaders, bool alignT public override bool OnMouseMove(int x, int y, Rectangle rowHeaders, bool alignToRight) { if (!expanded) + { return false; + } Rectangle relRect = GetRelationshipRectWithMirroring(); @@ -385,7 +409,9 @@ public override bool OnMouseMove(int x, int y, Rectangle rowHeaders, bool alignT public override void OnMouseLeft(Rectangle rowHeaders, bool alignToRight) { if (!expanded) + { return; + } Rectangle relRect = GetRelationshipRect(); relRect.X += rowHeaders.X + dgTable.RowHeaderWidth; @@ -401,7 +427,9 @@ public override void OnMouseLeft(Rectangle rowHeaders, bool alignToRight) public override void OnMouseLeft() { if (!expanded) + { return; + } if (FocusedRelation != -1) { @@ -418,17 +446,27 @@ public override bool OnKeyPress(Keys keyData) { // ignore the shift key if it is not paired w/ the TAB key if ((keyData & Keys.Modifiers) == Keys.Shift && (keyData & Keys.KeyCode) != Keys.Tab) + { return false; + } switch (keyData & Keys.KeyCode) { case Keys.F5: if (dgTable == null || dgTable.DataGrid == null || !dgTable.DataGrid.AllowNavigation) + { return false; + } + if (expanded) + { Collapse(); + } else + { Expand(); + } + FocusedRelation = -1; return true; @@ -436,9 +474,14 @@ public override bool OnKeyPress(Keys keyData) // case Keys.NumLock: if (FocusedRelation != -1) + { return false; + } else + { return base.OnKeyPress(keyData); + } + case Keys.Enter: if (FocusedRelation != -1) { @@ -451,7 +494,9 @@ public override bool OnKeyPress(Keys keyData) return true; } else + { return false; + } case Keys.Tab: return false; @@ -468,7 +513,9 @@ internal override void LoseChildFocus(Rectangle rowHeaders, bool alignToRight) { // we only invalidate stuff if the row is expanded. if (FocusedRelation == -1 || !expanded) + { return; + } FocusedRelation = -1; Rectangle relRect = GetRelationshipRect(); @@ -495,11 +542,15 @@ internal override bool ProcessTabKey(Keys keyData, Rectangle rowHeaders, bool al // if there are no relationships, this row can't do anything with the // key if (dgTable.RelationsList.Count == 0 || dgTable.DataGrid == null || !dgTable.DataGrid.AllowNavigation) + { return false; + } // expand the relationship box if (!expanded) + { Expand(); + } if ((keyData & Keys.Shift) == Keys.Shift) { @@ -521,11 +572,16 @@ internal override bool ProcessTabKey(Keys keyData, Rectangle rowHeaders, bool al InvalidateRowRect(relRect); if (FocusedRelation == -1) + { // is the first time that the user focuses on this // set of relationships FocusedRelation = dgTable.RelationsList.Count - 1; + } else + { FocusedRelation--; + } + return true; } else @@ -568,7 +624,10 @@ public override int Paint(Graphics g, bool alignToRight) { if (CompModSwitches.DGRelationShpRowPaint.TraceVerbose) + { Debug.WriteLine("Painting row " + RowNumber.ToString(CultureInfo.InvariantCulture) + " with bounds " + bounds.ToString()); + } + int bWidth = dgTable.BorderWidth; // paint the data cells @@ -579,7 +638,9 @@ public override int Paint(Graphics g, dataBounds.Offset(0, bWidth); // use bWidth, not 1 if (bWidth > 0) + { PaintBottomBorder(g, dataBounds, dataWidth, bWidth, alignToRight); + } if (expanded && dgTable.RelationsList.Count > 0) { @@ -592,7 +653,9 @@ public override int Paint(Graphics g, firstVisibleColumn, numVisibleColumns, alignToRight); relationBounds.Height += 1; if (bWidth > 0) + { PaintBottomBorder(g, relationBounds, dataWidthOffsetted, bWidth, alignToRight); + } } return dataWidth; @@ -609,7 +672,9 @@ protected override void PaintCellContents(Graphics g, Rectangle cellBounds, Data Rectangle bounds = cellBounds; object errInfo = DataGrid.ListManager[number]; if (errInfo is IDataErrorInfo) + { errString = ((IDataErrorInfo)errInfo)[column.PropertyDescriptor.Name]; + } if (!string.IsNullOrEmpty(errString)) { @@ -621,9 +686,14 @@ protected override void PaintCellContents(Graphics g, Rectangle cellBounds, Data } // paint the errors correctly when RTL = true if (alignToRight) + { bounds.Width -= errRect.Width + xOffset; + } else + { bounds.X += errRect.Width + xOffset; + } + DataGrid.ToolTipProvider.AddToolTip(errString, (IntPtr)(DataGrid.ToolTipId++), errRect); } @@ -644,9 +714,13 @@ public override void PaintHeader(Graphics g, Rectangle bounds, bool alignToRight } if (dgTable.IsDefault) + { PaintHeaderInside(g, insideBounds, DataGrid.HeaderBackBrush, alignToRight, isDirty); + } else + { PaintHeaderInside(g, insideBounds, dgTable.HeaderBackBrush, alignToRight, isDirty); + } } public void PaintHeaderInside(Graphics g, Rectangle bounds, Brush backBr, bool alignToRight, bool isDirty) @@ -658,7 +732,9 @@ public void PaintHeaderInside(Graphics g, Rectangle bounds, Brush backBr, bool a bounds, alignToRight); if (!alignToRight) + { Debug.Assert(bounds.X == rowHeaderBoundsX, "what's up doc?"); + } Rectangle rowHeaderBounds = new Rectangle(rowHeaderBoundsX, bounds.Y, @@ -671,7 +747,9 @@ public void PaintHeaderInside(Graphics g, Rectangle bounds, Brush backBr, bool a int expandoBoxX = MirrorRectangle(bounds.X + rowHeaderBounds.Width, expandoBoxWidth, bounds, alignToRight); if (!alignToRight) + { Debug.Assert(rowHeaderBounds.Right == expandoBoxX, "what's up doc?"); + } Rectangle expandoBox = new Rectangle(expandoBoxX, bounds.Y, @@ -730,9 +808,14 @@ private void PaintRelations(Graphics g, Rectangle bounds, Rectangle trueRowBound { int bWidth; if (dgTable.IsDefault) + { bWidth = DataGrid.GridLineWidth; + } else + { bWidth = dgTable.GridLineWidth; + } + g.FillRectangle(DataGrid.BackgroundBrush, alignToRight ? bounds.X : bounds.X + paintedWidth, bounds.Y, @@ -746,9 +829,14 @@ private void PaintRelations(Graphics g, Rectangle bounds, Rectangle trueRowBound // if the user changed the gridLineColor on the dataGrid // from the defaultValue, then use that value; if (dgTable.IsDefault) + { br = DataGrid.GridLineBrush; + } else + { br = dgTable.GridLineBrush; + } + g.FillRectangle(br, alignToRight ? bounds.Right - bWidth - paintedWidth : bounds.X + paintedWidth - bWidth, bounds.Y, @@ -771,7 +859,9 @@ private int PaintRelationText(Graphics g, Rectangle bounds, bool alignToRight) for (int r = 0; r < dgTable.RelationsList.Count; ++r) { if (cy > bounds.Height) + { break; + } Brush textBrush = dgTable.IsDefault ? DataGrid.LinkBrush : dgTable.LinkBrush; @@ -806,17 +896,24 @@ private int PaintRelationText(Graphics g, Rectangle bounds, bool alignToRight) private void PaintPlusMinusGlyph(Graphics g, Rectangle bounds, Brush backBr, bool alignToRight) { if (CompModSwitches.DGRelationShpRowPaint.TraceVerbose) + { Debug.WriteLine("PlusMinusGlyph painting in bounds -> " + bounds.ToString()); + } + Rectangle outline = GetOutlineRect(bounds.X, bounds.Y); outline = Rectangle.Intersect(bounds, outline); if (outline.IsEmpty) + { return; + } g.FillRectangle(backBr, bounds); if (CompModSwitches.DGRelationShpRowPaint.TraceVerbose) + { Debug.WriteLine("Painting PlusMinusGlyph with outline -> " + outline.ToString()); + } // draw the +/- box Pen drawPen = dgTable.IsDefault ? DataGrid.HeaderForePen : dgTable.HeaderForePen; g.DrawRectangle(drawPen, outline.X, outline.Y, outline.Width - 1, outline.Height - 1); @@ -856,12 +953,18 @@ private int RelationFromY(int y) while (cy < relRect.Bottom) { if (cy > y) + { break; + } + cy += relationshipHeight; relation++; } if (relation >= dgTable.RelationsList.Count) + { return -1; + } + return relation; } @@ -870,10 +973,13 @@ private int RelationFromY(int y) private int MirrorRelationshipRectangle(Rectangle relRect, Rectangle rowHeader, bool alignToRight) { if (alignToRight) + { return rowHeader.X - relRect.Width; + } else + { return relRect.X; - + } } // given the X and Width of a rectangle R1 contained in rect, @@ -881,9 +987,13 @@ private int MirrorRelationshipRectangle(Rectangle relRect, Rectangle rowHeader, private int MirrorRectangle(int x, int width, Rectangle rect, bool alignToRight) { if (alignToRight) + { return rect.Right + rect.X - width - x; + } else + { return x; + } } [ComVisible(true)] @@ -1001,7 +1111,10 @@ public override Rectangle Bounds bounds.Height = owner.Expanded ? owner.dgTable.RelationshipHeight : 0; // when the row is collapsed the height of the relationship object should be 0 // GetRelationshipRectWithMirroring will use the row headers width if (!owner.Expanded) + { bounds.X += rowBounds.X; + } + bounds.Y += rowBounds.Y; return owner.DataGrid.RectangleToScreen(bounds); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRow.cs index 5bd60a08cd8..95faa9ae6b8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRow.cs @@ -64,9 +64,14 @@ internal abstract class DataGridRow : MarshalByRefObject public DataGridRow(DataGrid dataGrid, DataGridTableStyle dgTable, int rowNumber) { if (dataGrid == null || dgTable.DataGrid == null) + { throw new ArgumentNullException(nameof(dataGrid)); + } + if (rowNumber < 0) + { throw new ArgumentException(SR.DataGridRowRowNumber, "rowNumber"); + } // this.dataGrid = dataGrid; number = rowNumber; @@ -114,7 +119,9 @@ internal protected virtual int MinimumRowHeight(GridColumnStylesCollection colum { // if (columns[i].Visible && columns[i].PropertyDescriptor != null) if (columns[i].PropertyDescriptor != null) + { h = Math.Max(h, columns[i].GetMinimumHeight()); + } } } } @@ -250,8 +257,12 @@ public virtual Rectangle GetCellBounds(int col) if (columns != null) { for (int i = firstVisibleCol; i < col; i++) + { if (columns[i].PropertyDescriptor != null) + { cx += columns[i].Width; + } + } int borderWidth = dgTable.GridLineWidth; cellBounds = new Rectangle(cx, @@ -277,7 +288,10 @@ public virtual Rectangle GetNonScrollableArea() protected Bitmap GetStarBitmap() { if (starBmp == null) + { starBmp = GetBitmap("DataGridRow.star"); + } + return starBmp; } @@ -288,7 +302,10 @@ protected Bitmap GetStarBitmap() protected Bitmap GetPencilBitmap() { if (pencilBmp == null) + { pencilBmp = GetBitmap("DataGridRow.pencil"); + } + return pencilBmp; } @@ -298,21 +315,30 @@ protected Bitmap GetPencilBitmap() protected Bitmap GetErrorBitmap() { if (errorBmp == null) + { errorBmp = GetBitmap("DataGridRow.error"); + } + return errorBmp; } protected Bitmap GetLeftArrowBitmap() { if (leftArrow == null) + { leftArrow = GetBitmap("DataGridRow.left"); + } + return leftArrow; } protected Bitmap GetRightArrowBitmap() { if (rightArrow == null) + { rightArrow = GetBitmap("DataGridRow.right"); + } + return rightArrow; } @@ -493,18 +519,26 @@ public virtual int PaintData(Graphics g, for (int col = firstVisibleColumn; col < nCols; ++col) { if (cx > bounds.Width) + { break; + } // if (!columns[col].Visible || columns[col].PropertyDescriptor == null) if (columns[col].PropertyDescriptor == null || columns[col].Width <= 0) + { continue; + } cellBounds.Width = columns[col].Width - bWidth; if (alignToRight) + { cellBounds.X = bounds.Right - cx - cellBounds.Width; + } else + { cellBounds.X = bounds.X + cx; + } // Paint the data with the the DataGridColumn Brush backBr = BackBrushForDataPaint(ref current, columns[col], col); @@ -636,11 +670,15 @@ public virtual void PaintHeader(Graphics g, Rectangle visualBounds, bool alignTo // object errorInfo = DataGrid.ListManager[number]; if (!(errorInfo is IDataErrorInfo)) + { return; + } string errString = ((IDataErrorInfo)errorInfo).Error; if (errString == null) + { errString = string.Empty; + } if (tooltip != errString) { @@ -653,7 +691,9 @@ public virtual void PaintHeader(Graphics g, Rectangle visualBounds, bool alignTo } if (string.IsNullOrEmpty(errString)) + { return; + } // we now have an error string: paint the errorIcon and add the tooltip Rectangle errRect; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs index 15e1bff72a4..caf75849f72 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs @@ -149,13 +149,17 @@ private void DataSource_Changed(object sender, ItemChangedEventArgs e) } if (DataGrid != null) + { DataGrid.ParentRowsDataChanged(); + } } private void DataSource_MetaDataChanged(object sender, EventArgs e) { if (DataGrid != null) + { DataGrid.ParentRowsDataChanged(); + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs index b4a471ac03a..59127c20ca8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs @@ -163,7 +163,10 @@ public Color AlternatingBackColor } if (System.Windows.Forms.DataGrid.IsTransparentColor(value)) + { throw new ArgumentException(SR.DataGridTableStyleTransparentAlternatingBackColorNotAllowed); + } + if (value.IsEmpty) { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, @@ -241,7 +244,10 @@ public Color BackColor } if (System.Windows.Forms.DataGrid.IsTransparentColor(value)) + { throw new ArgumentException(SR.DataGridTableStyleTransparentBackColorNotAllowed); + } + if (value.IsEmpty) { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, @@ -276,7 +282,9 @@ internal int BorderWidth { DataGrid dataGrid = DataGrid; if (dataGrid == null) + { return 0; + } // if the user set the GridLineStyle property on the dataGrid. // then use the value of that property DataGridLineStyle gridStyle; @@ -293,7 +301,9 @@ internal int BorderWidth } if (gridStyle == DataGridLineStyle.None) + { return 0; + } return gridLineWidth; } @@ -476,7 +486,10 @@ public Color GridLineColor if (gridLineBrush.Color != value) { if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "GridLineColor")); + } + gridLineBrush = new SolidBrush(value); // Invalidate(layout.Data); @@ -577,9 +590,15 @@ public Color HeaderBackColor } if (System.Windows.Forms.DataGrid.IsTransparentColor(value)) + { throw new ArgumentException(SR.DataGridTableStyleTransparentHeaderBackColorNotAllowed); + } + if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "HeaderBackColor")); + } + if (!value.Equals(headerBackBrush.Color)) { headerBackBrush = new SolidBrush(value); @@ -698,7 +717,10 @@ public Color HeaderForeColor } if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "HeaderForeColor")); + } + if (!value.Equals(headerForePen.Color)) { headerForePen = new Pen(value); @@ -769,7 +791,10 @@ public Color LinkColor } if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "LinkColor")); + } + if (!linkBrush.Color.Equals(value)) { linkBrush = new SolidBrush(value); @@ -793,7 +818,9 @@ protected virtual bool ShouldSerializeLinkColor() public void ResetLinkColor() { if (ShouldSerializeLinkColor()) + { LinkColor = DefaultLinkBrush.Color; + } } internal Brush LinkBrush @@ -865,7 +892,9 @@ private Rectangle ComputeRelationshipRect() int rwidth = (int)Math.Ceiling(g.MeasureString(((string)RelationsList[r]), DataGrid.LinkFont).Width) ; if (rwidth > longestRelationship) + { longestRelationship = rwidth; + } } g.Dispose(); @@ -875,7 +904,9 @@ private Rectangle ComputeRelationshipRect() relationshipRect.Height = BorderWidth + relationshipHeight * RelationsList.Count; relationshipRect.Height += 2; // relationship border if (RelationsList.Count > 0) + { relationshipRect.Height += 2 * relationshipSpacing; + } } return relationshipRect; } @@ -922,7 +953,10 @@ public int PreferredColumnWidth } if (value < 0) + { throw new ArgumentException(SR.DataGridColumnWidth, "PreferredColumnWidth"); + } + if (preferredColumnWidth != value) { preferredColumnWidth = value; @@ -966,7 +1000,10 @@ public int PreferredRowHeight } if (value < 0) + { throw new ArgumentException(SR.DataGridRowRowHeight); + } + prefferedRowHeight = value; /* @@ -1088,7 +1125,10 @@ public int RowHeaderWidth set { if (DataGrid != null) + { value = Math.Max(DataGrid.MinimumRowHeaderWidth(), value); + } + if (rowHeaderWidth != value) { rowHeaderWidth = value; @@ -1128,9 +1168,15 @@ public Color SelectionBackColor } if (System.Windows.Forms.DataGrid.IsTransparentColor(value)) + { throw new ArgumentException(SR.DataGridTableStyleTransparentSelectionBackColorNotAllowed); + } + if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "SelectionBackColor")); + } + if (!value.Equals(selectionBackBrush.Color)) { selectionBackBrush = new SolidBrush(value); @@ -1172,7 +1218,9 @@ protected bool ShouldSerializeSelectionBackColor() public void ResetSelectionBackColor() { if (ShouldSerializeSelectionBackColor()) + { SelectionBackColor = DefaultSelectionBackBrush.Color; + } } [ @@ -1194,7 +1242,10 @@ public Color SelectionForeColor } if (value.IsEmpty) + { throw new ArgumentException(string.Format(SR.DataGridEmptyColor, "SelectionForeColor")); + } + if (!value.Equals(selectionForeBrush.Color)) { selectionForeBrush = new SolidBrush(value); @@ -1220,7 +1271,9 @@ protected virtual bool ShouldSerializeSelectionForeColor() public void ResetSelectionForeColor() { if (ShouldSerializeSelectionForeColor()) + { SelectionForeColor = DefaultSelectionForeBrush.Color; + } } // will need this function from the dataGrid @@ -1228,7 +1281,9 @@ public void ResetSelectionForeColor() private void InvalidateInside() { if (DataGrid != null) + { DataGrid.InvalidateInside(); + } } [ @@ -1273,7 +1328,10 @@ internal void SetRelationsList(CurrencyManager listManager) Debug.Assert(!IsDefault, "the grid can set the relations only on a table that was manually added by the user"); int propCount = propCollection.Count; if (relationsList.Count > 0) + { relationsList.Clear(); + } + for (int i = 0; i < propCount; i++) { PropertyDescriptor prop = propCollection[i]; @@ -1295,7 +1353,9 @@ internal void SetGridColumnStylesCollection(CurrencyManager listManager) // we need to clear the relations list if (relationsList.Count > 0) + { relationsList.Clear(); + } Debug.Assert(propCollection != null, "propCollection is null: how that happened?"); int propCount = propCollection.Count; @@ -1305,7 +1365,10 @@ internal void SetGridColumnStylesCollection(CurrencyManager listManager) Debug.Assert(prop != null, "prop is null: how that happened?"); // do not take into account the properties that are browsable. if (!prop.IsBrowsable) + { continue; + } + if (PropertyDescriptorIsARelation(prop)) { // relation @@ -1316,7 +1379,9 @@ internal void SetGridColumnStylesCollection(CurrencyManager listManager) // column DataGridColumnStyle col = CreateGridColumn(prop, isDefaultTableStyle); if (isDefaultTableStyle) + { gridColumns.AddDefaultColumn(col); + } else { col.MappingName = prop.Name; @@ -1346,12 +1411,17 @@ internal protected virtual DataGridColumnStyle CreateGridColumn(PropertyDescript Type dataType = prop.PropertyType; if (dataType.Equals(typeof(bool))) + { ret = new DataGridBoolColumn(prop, isDefault); + } else if (dataType.Equals(typeof(string))) + { ret = new DataGridTextBoxColumn(prop, isDefault); + } else if (dataType.Equals(typeof(DateTime))) + { ret = new DataGridTextBoxColumn(prop, "d", isDefault); - + } else if (dataType.Equals(typeof(short)) || dataType.Equals(typeof(int)) || dataType.Equals(typeof(long)) || @@ -1398,9 +1468,15 @@ public string MappingName set { if (value == null) + { value = string.Empty; + } + if (value.Equals(mappingName)) + { return; + } + string originalMappingName = MappingName; mappingName = value; @@ -1408,7 +1484,9 @@ public string MappingName try { if (DataGrid != null) + { DataGrid.TableStyles.CheckForMappingNameDuplicates(this); + } } catch { @@ -1462,15 +1540,22 @@ public virtual GridColumnStylesCollection GridColumnStyles internal void SetInternalDataGrid(DataGrid dG, bool force) { if (dataGrid != null && dataGrid.Equals(dG) && !force) + { return; + } else { dataGrid = dG; if (dG != null && dG.Initializing) + { return; + } + int nCols = gridColumns.Count; for (int i = 0; i < nCols; i++) + { gridColumns[i].SetDataGridInternalInColumn(dG); + } } } @@ -1528,9 +1613,13 @@ public bool BeginEdit(DataGridColumnStyle gridColumn, int rowNumber) { DataGrid grid = DataGrid; if (grid == null) + { return false; + } else + { return grid.BeginEdit(gridColumn, rowNumber); + } } /// @@ -1541,16 +1630,22 @@ public bool EndEdit(DataGridColumnStyle gridColumn, int rowNumber, bool shouldAb { DataGrid grid = DataGrid; if (grid == null) + { return false; + } else + { return grid.EndEdit(gridColumn, rowNumber, shouldAbort); + } } internal void InvalidateColumn(DataGridColumnStyle column) { int index = GridColumnStyles.IndexOf(column); if (index >= 0 && DataGrid != null) + { DataGrid.InvalidateColumn(index); + } } @@ -1565,12 +1660,16 @@ private void OnColumnCollectionChanged(object sender, CollectionChangeEventArgs if (e.Action == CollectionChangeAction.Add) { if (col != null) + { col.SetDataGridInternalInColumn(grid); + } } else if (e.Action == CollectionChangeAction.Remove) { if (col != null) + { col.SetDataGridInternalInColumn(null); + } } else { @@ -1579,12 +1678,18 @@ private void OnColumnCollectionChanged(object sender, CollectionChangeEventArgs // if we get a column in this collectionChangeEventArgs it means // that the propertyDescriptor in that column changed. if (e.Element != null) + { for (int i = 0; i < gridColumns.Count; i++) + { gridColumns[i].SetDataGridInternalInColumn(null); + } + } } if (grid != null) + { grid.OnColumnCollectionChanged(this, e); + } } finally { @@ -1607,126 +1712,166 @@ protected virtual void OnReadOnlyChanged(EventArgs e) { EventHandler eh = Events[EventReadOnly] as EventHandler; if (eh != null) + { eh(this, e); + } } protected virtual void OnMappingNameChanged(EventArgs e) { EventHandler eh = Events[EventMappingName] as EventHandler; if (eh != null) + { eh(this, e); + } } protected virtual void OnAlternatingBackColorChanged(EventArgs e) { EventHandler eh = Events[EventAlternatingBackColor] as EventHandler; if (eh != null) + { eh(this, e); + } } protected virtual void OnForeColorChanged(EventArgs e) { EventHandler eh = Events[EventBackColor] as EventHandler; if (eh != null) + { eh(this, e); + } } protected virtual void OnBackColorChanged(EventArgs e) { EventHandler eh = Events[EventForeColor] as EventHandler; if (eh != null) + { eh(this, e); + } } protected virtual void OnAllowSortingChanged(EventArgs e) { EventHandler eh = Events[EventAllowSorting] as EventHandler; if (eh != null) + { eh(this, e); + } } protected virtual void OnGridLineColorChanged(EventArgs e) { EventHandler eh = Events[EventGridLineColor] as EventHandler; if (eh != null) + { eh(this, e); + } } protected virtual void OnGridLineStyleChanged(EventArgs e) { EventHandler eh = Events[EventGridLineStyle] as EventHandler; if (eh != null) + { eh(this, e); + } } protected virtual void OnHeaderBackColorChanged(EventArgs e) { EventHandler eh = Events[EventHeaderBackColor] as EventHandler; if (eh != null) + { eh(this, e); + } } protected virtual void OnHeaderFontChanged(EventArgs e) { EventHandler eh = Events[EventHeaderFont] as EventHandler; if (eh != null) + { eh(this, e); + } } protected virtual void OnHeaderForeColorChanged(EventArgs e) { EventHandler eh = Events[EventHeaderForeColor] as EventHandler; if (eh != null) + { eh(this, e); + } } protected virtual void OnLinkColorChanged(EventArgs e) { EventHandler eh = Events[EventLinkColor] as EventHandler; if (eh != null) + { eh(this, e); + } } protected virtual void OnLinkHoverColorChanged(EventArgs e) { EventHandler eh = Events[EventLinkHoverColor] as EventHandler; if (eh != null) + { eh(this, e); + } } protected virtual void OnPreferredRowHeightChanged(EventArgs e) { EventHandler eh = Events[EventPreferredRowHeight] as EventHandler; if (eh != null) + { eh(this, e); + } } protected virtual void OnPreferredColumnWidthChanged(EventArgs e) { EventHandler eh = Events[EventPreferredColumnWidth] as EventHandler; if (eh != null) + { eh(this, e); + } } protected virtual void OnColumnHeadersVisibleChanged(EventArgs e) { EventHandler eh = Events[EventColumnHeadersVisible] as EventHandler; if (eh != null) + { eh(this, e); + } } protected virtual void OnRowHeadersVisibleChanged(EventArgs e) { EventHandler eh = Events[EventRowHeadersVisible] as EventHandler; if (eh != null) + { eh(this, e); + } } protected virtual void OnRowHeaderWidthChanged(EventArgs e) { EventHandler eh = Events[EventRowHeaderWidth] as EventHandler; if (eh != null) + { eh(this, e); + } } protected virtual void OnSelectionForeColorChanged(EventArgs e) { EventHandler eh = Events[EventSelectionForeColor] as EventHandler; if (eh != null) + { eh(this, e); + } } protected virtual void OnSelectionBackColorChanged(EventArgs e) { EventHandler eh = Events[EventSelectionBackColor] as EventHandler; if (eh != null) + { eh(this, e); + } } protected override void Dispose(bool disposing) @@ -1737,7 +1882,9 @@ protected override void Dispose(bool disposing) if (cols != null) { for (int i = 0; i < cols.Count; i++) + { cols[i].Dispose(); + } } } base.Dispose(disposing); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs index e76db7a56eb..90ad10d2ed4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs @@ -146,14 +146,19 @@ public DataGridTableStyle this[string tableName] get { if (tableName == null) + { throw new ArgumentNullException(nameof(tableName)); + } + int itemCount = items.Count; for (int i = 0; i < itemCount; ++i) { DataGridTableStyle table = (DataGridTableStyle)items[i]; // NOTE: case-insensitive if (string.Equals(table.MappingName, tableName, StringComparison.OrdinalIgnoreCase)) + { return table; + } } return null; } @@ -162,10 +167,17 @@ public DataGridTableStyle this[string tableName] internal void CheckForMappingNameDuplicates(DataGridTableStyle table) { if (string.IsNullOrEmpty(table.MappingName)) + { return; + } + for (int i = 0; i < items.Count; i++) + { if (((DataGridTableStyle)items[i]).MappingName.Equals(table.MappingName) && table != items[i]) + { throw new ArgumentException(SR.DataGridTableStyleDuplicateMappingName, "table"); + } + } } /// @@ -176,10 +188,15 @@ public virtual int Add(DataGridTableStyle table) // set the rowHeaderWidth on the newly added table to at least the minimum value // on its owner if (owner != null && owner.MinimumRowHeaderWidth() > table.RowHeaderWidth) + { table.RowHeaderWidth = owner.MinimumRowHeaderWidth(); + } if (table.DataGrid != owner && table.DataGrid != null) + { throw new ArgumentException(SR.DataGridTableStyleCollectionAddedParentedTableStyle, "table"); + } + table.DataGrid = owner; CheckForMappingNameDuplicates(table); table.MappingNameChanged += new EventHandler(TableStyleMappingNameChanged); @@ -248,7 +265,9 @@ public bool Contains(string name) DataGridTableStyle table = (DataGridTableStyle)items[i]; // NOTE: case-insensitive if (string.Compare(table.MappingName, name, true, CultureInfo.InvariantCulture) == 0) + { return true; + } } return false; } @@ -269,7 +288,9 @@ public override IEnumerator GetEnumerator(bool allowRemove) { protected void OnCollectionChanged(CollectionChangeEventArgs e) { if (onCollectionChanged != null) + { onCollectionChanged(this, e); + } DataGrid grid = owner; if (grid != null) @@ -294,15 +315,22 @@ public void Remove(DataGridTableStyle table) int tableIndex = -1; int itemsCount = items.Count; for (int i = 0; i < itemsCount; ++i) + { if (items[i] == table) { tableIndex = i; break; } + } + if (tableIndex == -1) + { throw new ArgumentException(SR.DataGridTableCollectionMissingTable, "table"); + } else + { RemoveAt(tableIndex); + } } public void RemoveAt(int index) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBox.cs index bbca62f12be..582ab022941 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBox.cs @@ -68,16 +68,23 @@ protected override void OnKeyPress(KeyPressEventArgs e) // Shift-Space should not cause the grid to // be put in edit mode if (e.KeyChar == ' ' && (Control.ModifierKeys & Keys.Shift) == Keys.Shift) + { return; + } // if the edit box is in ReadOnly mode, then do not tell the DataGrid about the // edit if (ReadOnly) + { return; + } // Ctrl-* should not put the grid in edit mode if ((Control.ModifierKeys & Keys.Control) == Keys.Control && ((Control.ModifierKeys & Keys.Alt) == 0)) + { return; + } + IsInEditOrNavigateMode = false; // let the DataGrid know about the edit @@ -96,14 +103,20 @@ protected internal override bool ProcessKeyMessage(ref Message m) // for those keys, eat the WM_CHAR part of the KeyMessage // if (m.Msg == Interop.WindowMessages.WM_CHAR) + { return true; + } + return ProcessKeyPreview(ref m); } if (m.Msg == Interop.WindowMessages.WM_CHAR) { if (key == Keys.LineFeed) // eat the LineFeed we get when the user presses Ctrl-Enter in a gridTextBox + { return true; + } + return ProcessKeyEventArgs(ref m); } @@ -111,7 +124,9 @@ protected internal override bool ProcessKeyMessage(ref Message m) // we only want to process the WM_KEYUP message ( the same way the grid was doing when the grid was getting all // the keys ) if (m.Msg == Interop.WindowMessages.WM_KEYUP) + { return true; + } Keys keyData = key & Keys.KeyCode; @@ -124,7 +139,10 @@ protected internal override bool ProcessKeyMessage(ref Message m) // else, process the KeyEvent // if (SelectionStart + SelectionLength == Text.Length) + { return ProcessKeyPreview(ref m); + } + return ProcessKeyEventArgs(ref m); case Keys.Left: // if the end of the selection is at the begining of the string @@ -134,7 +152,10 @@ protected internal override bool ProcessKeyMessage(ref Message m) // if (SelectionStart + SelectionLength == 0 || (IsInEditOrNavigateMode && SelectionLength == Text.Length)) + { return ProcessKeyPreview(ref m); + } + return ProcessKeyEventArgs(ref m); case Keys.Down: // if the end of the selection is on the last line of the text then @@ -143,7 +164,10 @@ protected internal override bool ProcessKeyMessage(ref Message m) // int end = SelectionStart + SelectionLength; if (Text.IndexOf("\r\n", end) == -1) + { return ProcessKeyPreview(ref m); + } + return ProcessKeyEventArgs(ref m); case Keys.Up: // if the end of the selection is on the first line of the text then @@ -151,14 +175,22 @@ protected internal override bool ProcessKeyMessage(ref Message m) // else, process the KeyEvent // if (Text.IndexOf("\r\n") < 0 || SelectionStart + SelectionLength < Text.IndexOf("\r\n")) + { return ProcessKeyPreview(ref m); + } + return ProcessKeyEventArgs(ref m); case Keys.Home: case Keys.End: if (SelectionLength == Text.Length) + { return ProcessKeyPreview(ref m); + } else + { return ProcessKeyEventArgs(ref m); + } + case Keys.Prior: case Keys.Next: case Keys.Oemplus: @@ -180,7 +212,9 @@ protected internal override bool ProcessKeyMessage(ref Message m) { // when we get a SHIFT-SPACEBAR message, disregard the WM_CHAR part of the message if (m.Msg == Interop.WindowMessages.WM_CHAR) + { return true; + } // if the user pressed the SHIFT key at the same time with // the space key, send the key message to the DataGrid @@ -192,7 +226,9 @@ protected internal override bool ProcessKeyMessage(ref Message m) { // when we get a Control-A message, disregard the WM_CHAR part of the message if (m.Msg == Interop.WindowMessages.WM_CHAR) + { return true; + } // if the user pressed the Control key at the same time with // the space key, send the key message to the DataGrid @@ -212,7 +248,9 @@ protected internal override bool ProcessKeyMessage(ref Message m) // if the dataGrid used the key, then we aren't gonne // use it anymore, else we are if (ProcessKeyPreview(ref m)) + { return true; + } else { // the edit control will use the @@ -224,14 +262,22 @@ protected internal override bool ProcessKeyMessage(ref Message m) } } else + { return ProcessKeyEventArgs(ref m); + } + case Keys.Tab: // the TextBox gets the Control-Tab messages, // not the parent if ((ModifierKeys & Keys.Control) == Keys.Control) + { return ProcessKeyPreview(ref m); + } else + { return ProcessKeyEventArgs(ref m); + } + default: return ProcessKeyEventArgs(ref m); } @@ -247,7 +293,9 @@ public bool IsInEditOrNavigateMode { isInEditOrNavigateMode = value; if (value) + { SelectAll(); + } } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs index f5f74d94906..a1efdaeb7fe 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs @@ -117,7 +117,9 @@ public virtual TextBox TextBox internal override bool KeyPress(int rowNum, Keys keyData) { if (edit.IsInEditOrNavigateMode) + { return base.KeyPress(rowNum, keyData); + } // if the edit box is editing, then // pass this keystroke to the edit box @@ -196,7 +198,10 @@ public string Format set { if (value == null) + { value = string.Empty; + } + if (format == null || !format.Equals(value)) { format = value; @@ -207,7 +212,9 @@ public string Format if (format.Length == 0) { if (typeConverter != null && !typeConverter.CanConvertFrom(typeof(string))) + { ReadOnly = true; + } } Invalidate(); @@ -225,7 +232,9 @@ public IFormatProvider FormatInfo set { if (formatInfo == null || !formatInfo.Equals(value)) + { formatInfo = value; + } } } @@ -242,7 +251,9 @@ public override bool ReadOnly if (!value && (format == null || format.Length == 0)) { if (typeConverter != null && !typeConverter.CanConvertFrom(typeof(string))) + { return; + } } base.ReadOnly = value; } @@ -305,8 +316,9 @@ protected internal override void UpdateUI(CurrencyManager source, int rowNum, st { edit.Text = GetText(GetColumnValueAtRow(source, rowNum)); if (!edit.ReadOnly && displayText != null) + { edit.Text = displayText; - + } } /// @@ -383,24 +395,32 @@ protected internal override void Abort(int rowNum) protected internal override void EnterNullValue() { if (ReadOnly) + { return; + } // if the edit box is not visible, then // do not put the edit text in it if (!edit.Visible) + { return; + } // if we are editing, then we should be able to enter alt-0 in a cell. // if (!edit.IsInEditOrNavigateMode) + { return; + } edit.Text = NullText; // edit.Visible = true; edit.IsInEditOrNavigateMode = false; // tell the dataGrid that there is an edit: if (DataGridTableStyle != null && DataGridTableStyle.DataGrid != null) + { DataGridTableStyle.DataGrid.ColumnStartedEditing(edit.Bounds); + } } /// @@ -415,7 +435,9 @@ protected internal override bool Commit(CurrencyManager dataSource, int rowNum) edit.Bounds = Rectangle.Empty; if (edit.IsInEditOrNavigateMode) + { return true; + } try { @@ -435,7 +457,9 @@ protected internal override bool Commit(CurrencyManager dataSource, int rowNum) edit.Text = ((IFormattable)value).ToString(format, formatInfo); } else + { edit.Text = value.ToString(); + } } else if (typeConverter != null && typeConverter.CanConvertFrom(typeof(string))) { @@ -521,7 +545,9 @@ protected internal override void Edit(CurrencyManager source, // because the navigation code in the DataGridTextBox::ProcessKeyMessage // uses the SelectedText property if (displayText == null) + { edit.SelectAll(); + } else { int end = edit.Text.Length; @@ -529,7 +555,9 @@ protected internal override void Edit(CurrencyManager source, } if (edit.Visible) + { DataGridTableStyle.DataGrid.Invalidate(originalBounds); + } } internal override string GetDisplayText(object value) @@ -540,7 +568,9 @@ internal override string GetDisplayText(object value) private string GetText(object value) { if (value is System.DBNull) + { return NullText; + } else if (format != null && format.Length != 0 && (value is IFormattable)) { try @@ -556,7 +586,9 @@ private string GetText(object value) { // use the typeConverter: if (typeConverter != null && typeConverter.CanConvertTo(typeof(string))) + { return (string)typeConverter.ConvertTo(value, typeof(string)); + } } return (value != null ? value.ToString() : ""); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs index f23f51fa944..9f5846408e9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs @@ -61,7 +61,9 @@ public void AddToolTip(string toolTipString, IntPtr toolTipId, Rectangle iconBou { Debug.Assert(tipWindow != null && tipWindow.Handle != IntPtr.Zero, "the tipWindow was not initialized, bailing out"); if (iconBounds.IsEmpty) + { throw new ArgumentNullException(nameof(iconBounds), SR.DataGridToolTipEmptyIcon); + } NativeMethods.TOOLINFO_T toolInfo = new NativeMethods.TOOLINFO_T(); toolInfo.cbSize = Marshal.SizeOf(toolInfo); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs index 6691eb37aa0..5ecc6ac84c4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs @@ -4965,9 +4965,13 @@ internal Rectangle GetAccessibleObjectBounds(AccessibleObject parentAccObject) } if ((cellRight - cellLeft) >= 0) + { cellRect.Width = cellRight - cellLeft; + } else + { cellRect.Width = 0; + } return cellRect; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs index 51f2bab6ea3..90f62efef3d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs @@ -1202,16 +1202,24 @@ internal bool VerifyColumnDisplayIndexes() private bool VerifyColumnOrderCache() { if (itemsSorted == null) + { return false; + } + if (itemsSorted.Count != items.Count) + { return false; + } int index = 0; while (index < itemsSorted.Count - 1) { if (((DataGridViewColumn)itemsSorted[index + 1]).DisplayIndex != ((DataGridViewColumn)itemsSorted[index]).DisplayIndex + 1) + { return false; + } + index++; } return true; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs index 2b8effdfad2..20f8a4e6232 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs @@ -1695,7 +1695,10 @@ private string[] ReadFileListFromHandle(IntPtr hdrop) { int charlen = UnsafeNativeMethods.DragQueryFileLongPath(new HandleRef(null, hdrop), i, sb); if (0 == charlen) + { continue; + } + string s = sb.ToString(0, charlen); string fullPath = Path.GetFullPath(s); files[i] = s; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataStreamFromComStream.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataStreamFromComStream.cs index 55a2d7b1875..eef3680f6fd 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataStreamFromComStream.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataStreamFromComStream.cs @@ -147,7 +147,9 @@ public override long Seek(long offset, SeekOrigin origin) public override void Write(byte[] buffer, int index, int count) { if (count <= 0) + { return; + } if (count > 0 && index >= 0 && (count + index) <= buffer.Length) { @@ -167,7 +169,9 @@ public override void Write(byte[] buffer, int index, int count) public unsafe override void Write(ReadOnlySpan buffer) { if (buffer.IsEmpty) + { return; + } int bytesWritten = 0; try diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs index 429f3958e0f..b9024b855e5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs @@ -530,7 +530,9 @@ public string CustomFormat if (IsHandleCreated) { if (format == DateTimePickerFormat.Custom) + { SendMessage(NativeMethods.DTM_SETFORMAT, 0, customFormat); + } } } } @@ -885,7 +887,9 @@ public int PreferredHeight get { if (prefHeightCache > -1) + { return (int)prefHeightCache; + } // Base the preferred height on the current font int height = FontHeight; @@ -1028,9 +1032,13 @@ public DateTime Value { //checkbox clicked, no value set - no value set state should never occur, but just in case if (!userHasSetValue && validTime) + { return creationTime; + } else + { return value; + } } set { @@ -1219,7 +1227,10 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) protected override bool IsInputKey(Keys keyData) { if ((keyData & Keys.Alt) == Keys.Alt) + { return false; + } + switch (keyData & Keys.KeyCode) { case Keys.PageUp: @@ -1238,7 +1249,9 @@ protected override bool IsInputKey(Keys keyData) protected virtual void OnCloseUp(EventArgs eventargs) { if (onCloseUp != null) + { onCloseUp(this, eventargs); + } } /// @@ -1498,7 +1511,9 @@ private void SetRange(DateTime min, DateTime max) private void SetStyleBit(bool flag, int bit) { if (((style & bit) != 0) == flag) + { return; + } if (flag) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs index 6e249a2bd63..05e14c9c591 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs @@ -258,7 +258,9 @@ private void OnConfigureUI() selector.Nodes.Add(new TreeNode(title, n, n)); if (titleWidth > selectorWidth) + { selectorWidth = titleWidth; + } } } selectorWidth += SELECTOR_PADDING; @@ -404,9 +406,14 @@ private void OnNewObjects() Size pageSize = page.Size; if (pageSize.Width > maxSize.Width) + { maxSize.Width = pageSize.Width; + } + if (pageSize.Height > maxSize.Height) + { maxSize.Height = pageSize.Height; + } } // and set them all to an ideal size @@ -434,12 +441,17 @@ protected virtual void OnSelChangeSelector(object source, TreeViewEventArgs e) "Invalid page selected"); if (newPage == activePage) + { return; + } if (activePage != -1) { if (pageSites[activePage].AutoCommit) + { ApplyChanges(false); + } + pageSites[activePage].Active = false; } @@ -455,7 +467,9 @@ protected virtual void OnSelChangeSelector(object source, TreeViewEventArgs e) public override bool PreProcessMessage(ref Message msg) { if (null != pageSites && pageSites[activePage].GetPageControl().IsPageMessage(ref msg)) + { return true; + } return base.PreProcessMessage(ref msg); } @@ -640,7 +654,10 @@ internal ComponentEditorPage GetPageControl() public void SetDirty() { if (isActive) + { Dirty = true; + } + form.SetDirty(); } } @@ -729,7 +746,9 @@ private void DrawTreeItem(string itemText, int imageIndex, IntPtr dc, NativeMeth // Select the font of the dialog, so we don't get the underlined font // when the item is being tracked if ((state & STATE_HOT) != 0) + { hfontOld = SafeNativeMethods.SelectObject(new HandleRef(null, dc), new HandleRef(Parent, ((Control)Parent).FontHandle)); + } // Fill the background if (((state & STATE_SELECTED) != 0) && (hbrushDither != IntPtr.Zero)) @@ -790,7 +809,9 @@ private void DrawTreeItem(string itemText, int imageIndex, IntPtr dc, NativeMeth } if (hfontOld != IntPtr.Zero) + { SafeNativeMethods.SelectObject(new HandleRef(null, dc), new HandleRef(null, hfontOld)); + } } protected override void OnHandleCreated(EventArgs e) @@ -828,9 +849,14 @@ private void OnCustomDraw(ref Message m) if (((itemState & NativeMethods.CDIS_HOT) != 0) || ((itemState & NativeMethods.CDIS_FOCUS) != 0)) + { state |= STATE_HOT; + } + if ((itemState & NativeMethods.CDIS_SELECTED) != 0) + { state |= STATE_SELECTED; + } DrawTreeItem(itemNode.Text, itemNode.ImageIndex, nmtvcd.nmcd.hdc, nmtvcd.nmcd.rc, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DomainUpDown.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DomainUpDown.cs index 94ae4a9c607..e955b6cb1e1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DomainUpDown.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DomainUpDown.cs @@ -388,9 +388,13 @@ internal int MatchIndex(string text, bool complete, int startPosition) do { if (complete) + { found = Items[index].ToString().Equals(text); + } else + { found = Items[index].ToString().ToUpper(CultureInfo.InvariantCulture).StartsWith(text); + } if (found) { @@ -512,7 +516,9 @@ private void SelectIndex(int index) private void SortDomainItems() { if (inSort) + { return; + } inSort = true; try @@ -758,7 +764,10 @@ private sealed class DomainUpDownItemCompare : IComparer public int Compare(object p, object q) { if (p == q) + { return 0; + } + if (p == null || q == null) { return 0; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs index 09d235c5dab..457688c4a3d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs @@ -114,7 +114,9 @@ public override ISite Site { base.Site = value; if (value == null) + { return; + } IDesignerHost host = value.GetService(typeof(IDesignerHost)) as IDesignerHost; if (host != null) @@ -215,12 +217,16 @@ public ContainerControl ContainerControl if (parentControl != value) { if (parentControl != null) + { parentControl.BindingContextChanged -= propChangedEvent; + } parentControl = value; if (parentControl != null) + { parentControl.BindingContextChanged += propChangedEvent; + } Set_ErrorManager(DataSource, DataMember, true); } @@ -289,7 +295,10 @@ public object Tag private void Set_ErrorManager(object newDataSource, string newDataMember, bool force) { if (inSetErrorManager) + { return; + } + inSetErrorManager = true; try { @@ -336,7 +345,9 @@ private void Set_ErrorManager(object newDataSource, string newDataMember, bool f // see if there are errors at the current // item in the list, w/o waiting for the position to change if (errorManager != null) + { UpdateBinding(); + } } } finally @@ -403,7 +414,10 @@ public string DataMember set { if (value == null) + { value = string.Empty; + } + Set_ErrorManager(DataSource, value, false); } } @@ -556,7 +570,9 @@ private void ErrorManager_CurrentChanged(object sender, EventArgs e) string outputError = string.Empty; if (controlError.Contains(dataBinding.Control)) + { outputError = (string)controlError[dataBinding.Control]; + } // Utilize the error string without including the field name. if (string.IsNullOrEmpty(outputError)) @@ -603,7 +619,9 @@ public int BlinkRate blinkRate = value; // If we set the blinkRate = 0 then set BlinkStyle = NeverBlink if (blinkRate == 0) + { BlinkStyle = ErrorBlinkStyle.NeverBlink; + } } } @@ -651,7 +669,9 @@ public Icon Icon ErrorWindow[] array = new ErrorWindow[windows.Values.Count]; windows.Values.CopyTo(array, 0); for (int i = 0; i < array.Length; i++) + { array[i].Update(false /*timerCaused*/); + } } } @@ -665,7 +685,10 @@ internal IconRegion Region get { if (region == null) + { region = new IconRegion(Icon); + } + return region; } } @@ -792,7 +815,10 @@ void DisposeRegion() private ControlItem EnsureControlItem(Control control) { if (control == null) + { throw new ArgumentNullException(nameof(control)); + } + ControlItem item = (ControlItem)items[control]; if (item == null) { @@ -1260,9 +1286,13 @@ public void Update(bool timerCaused) ControlItem item = (ControlItem)items[i]; Rectangle iconBounds = item.GetIconBounds(size); if (windowBounds.IsEmpty) + { windowBounds = iconBounds; + } else + { windowBounds = Rectangle.Union(windowBounds, iconBounds); + } } Region windowRegion = new Region(new Rectangle(0, 0, 0, 0)); @@ -1859,7 +1889,9 @@ public Region Region finally { if (mask != IntPtr.Zero) + { SafeNativeMethods.DeleteObject(new HandleRef(null, mask)); + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FlatButtonAppearance.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FlatButtonAppearance.cs index ea7579c9614..118f7971e4b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FlatButtonAppearance.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FlatButtonAppearance.cs @@ -50,7 +50,9 @@ public int BorderSize set { if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(BorderSize), value, 0)); + } if (borderSize != value) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FontDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FontDialog.cs index 8ce317601e0..d842bb6a35d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FontDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FontDialog.cs @@ -235,13 +235,20 @@ public Font Font { Font result = font; if (result == null) + { result = Control.DefaultFont; + } float actualSize = result.SizeInPoints; if (minSize != defaultMinSize && actualSize < MinSize) + { result = new Font(result.FontFamily, MinSize, result.Style, GraphicsUnit.Point); + } + if (maxSize != defaultMaxSize && actualSize > MaxSize) + { result = new Font(result.FontFamily, MaxSize, result.Style, GraphicsUnit.Point); + } return result; } @@ -548,7 +555,9 @@ protected virtual void OnApply(EventArgs e) { EventHandler handler = (EventHandler)Events[EventApply]; if (handler != null) + { handler(this, e); + } } /// @@ -642,8 +651,9 @@ protected override bool RunDialog(IntPtr hWndOwner) } Debug.Assert(cf.nSizeMin <= cf.nSizeMax, "min and max font sizes are the wrong way around"); if (!SafeNativeMethods.ChooseFont(cf)) + { return false; - + } NativeMethods.LOGFONT lfReturned = Marshal.PtrToStructure(logFontPtr); @@ -659,7 +669,9 @@ protected override bool RunDialog(IntPtr hWndOwner) finally { if (logFontPtr != IntPtr.Zero) + { Marshal.FreeCoTaskMem(logFontPtr); + } } } 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 329f0752d40..c770793db3d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs @@ -718,7 +718,9 @@ public override Color BackColor // particularly if the parent is an MDIClient. Color c = RawBackColor; // inheritedProperties.BackColor if (!c.IsEmpty) + { return c; + } return DefaultBackColor; } @@ -1330,7 +1332,9 @@ public bool IsMdiContainer set { if (value == IsMdiContainer) + { return; + } if (value) { @@ -1891,19 +1895,28 @@ private MainMenu MergedMenuPrivate { Form formMdiParent = (Form)Properties.GetObject(PropFormMdiParent); if (formMdiParent == null) + { return null; + } MainMenu mergedMenu = (MainMenu)Properties.GetObject(PropMergedMenu); if (mergedMenu != null) + { return mergedMenu; + } MainMenu parentMenu = formMdiParent.Menu; MainMenu mainMenu = Menu; if (mainMenu == null) + { return parentMenu; + } + if (parentMenu == null) + { return mainMenu; + } // Create a menu that merges the two and save it for next time. mergedMenu = new MainMenu @@ -2083,7 +2096,9 @@ public Form Owner { Form ownerOld = OwnerInternal; if (ownerOld == value) + { return; + } if (value != null && !TopLevel) { @@ -2983,7 +2998,9 @@ protected void ActivateMdiChild(Form form) public void AddOwnedForm(Form ownedForm) { if (ownedForm == null) + { return; + } if (ownedForm.OwnerInternal != this) { @@ -3182,7 +3199,9 @@ protected void ApplyAutoScaling() // We save a significant amount of time by bailing early if there's no work to be done if (baseVar.Equals(newVar)) + { return; + } float percY = AdjustScale(((float)newVar.Height) / ((float)baseVar.Height)); float percX = AdjustScale(((float)newVar.Width) / ((float)baseVar.Width)); @@ -3383,7 +3402,9 @@ public void Close() { if (GetState(STATE_CREATINGHANDLE)) + { throw new InvalidOperationException(string.Format(SR.ClosingWhileCreatingHandle, "Close")); + } if (IsHandleCreated) { @@ -3521,7 +3542,9 @@ protected override void CreateHandle() // avoid extra SetMenu calls for perf if (Menu != null || !TopLevel || IsMdiContainer) + { UpdateMenuHandles(); + } // In order for a window not to have a taskbar entry, it must // be owned. @@ -3548,7 +3571,9 @@ protected override void CreateHandle() finally { if (form != null) + { form.ResumeUpdateMenuHandles(); + } // We need to reset the styles in case Windows tries to set us up // with "correct" styles @@ -3643,13 +3668,24 @@ protected override void Dispose(bool disposing) CalledCreateControl = false; if (Properties.ContainsObject(PropAcceptButton)) + { Properties.SetObject(PropAcceptButton, null); + } + if (Properties.ContainsObject(PropCancelButton)) + { Properties.SetObject(PropCancelButton, null); + } + if (Properties.ContainsObject(PropDefaultButton)) + { Properties.SetObject(PropDefaultButton, null); + } + if (Properties.ContainsObject(PropActiveMdiChild)) + { Properties.SetObject(PropActiveMdiChild, null); + } if (MdiWindowListStrip != null) { @@ -4132,15 +4168,23 @@ protected void CenterToParent() p.X = (ownerRect.left + ownerRect.right - s.Width) / 2; if (p.X < screenRect.X) + { p.X = screenRect.X; + } else if (p.X + s.Width > screenRect.X + screenRect.Width) + { p.X = screenRect.X + screenRect.Width - s.Width; + } p.Y = (ownerRect.top + ownerRect.bottom - s.Height) / 2; if (p.Y < screenRect.Y) + { p.Y = screenRect.Y; + } else if (p.Y + s.Height > screenRect.Y + screenRect.Height) + { p.Y = screenRect.Y + screenRect.Height - s.Height; + } Location = p; } @@ -4242,7 +4286,10 @@ internal void MenuChanged(int change, Menu menu) if (ctlClient == null || !ctlClient.IsHandleCreated) { if (menu == Menu && change == Windows.Forms.Menu.CHANGE_ITEMS) + { UpdateMenuHandles(); + } + break; } @@ -4292,7 +4339,9 @@ protected virtual void OnActivated(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_ACTIVATED]; if (handler != null) + { handler(this, e); + } } /// @@ -4342,7 +4391,9 @@ protected virtual void OnClosing(CancelEventArgs e) { CancelEventHandler handler = (CancelEventHandler)Events[EVENT_CLOSING]; if (handler != null) + { handler(this, e); + } } /// @@ -4353,7 +4404,9 @@ protected virtual void OnClosed(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_CLOSED]; if (handler != null) + { handler(this, e); + } } @@ -4365,7 +4418,9 @@ protected virtual void OnFormClosing(FormClosingEventArgs e) { FormClosingEventHandler handler = (FormClosingEventHandler)Events[EVENT_FORMCLOSING]; if (handler != null) + { handler(this, e); + } } /// @@ -4379,7 +4434,9 @@ protected virtual void OnFormClosed(FormClosedEventArgs e) FormClosedEventHandler handler = (FormClosedEventHandler)Events[EVENT_FORMCLOSED]; if (handler != null) + { handler(this, e); + } } /// @@ -4406,7 +4463,9 @@ protected virtual void OnDeactivate(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_DEACTIVATE]; if (handler != null) + { handler(this, e); + } } /// @@ -4653,7 +4712,9 @@ protected virtual void OnInputLanguageChanged(InputLanguageChangedEventArgs e) { InputLanguageChangedEventHandler handler = (InputLanguageChangedEventHandler)Events[EVENT_INPUTLANGCHANGE]; if (handler != null) + { handler(this, e); + } } /// @@ -4665,7 +4726,9 @@ protected virtual void OnInputLanguageChanging(InputLanguageChangingEventArgs e) { InputLanguageChangingEventHandler handler = (InputLanguageChangingEventHandler)Events[EVENT_INPUTLANGCHANGEREQUEST]; if (handler != null) + { handler(this, e); + } } [EditorBrowsable(EditorBrowsableState.Advanced)] @@ -4714,7 +4777,9 @@ protected virtual void OnMdiChildActivate(EventArgs e) UpdateToolStrip(); EventHandler handler = (EventHandler)Events[EVENT_MDI_CHILD_ACTIVATE]; if (handler != null) + { handler(this, e); + } } /// @@ -4735,7 +4800,9 @@ protected virtual void OnMenuComplete(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_MENUCOMPLETE]; if (handler != null) + { handler(this, e); + } } /// @@ -4921,7 +4988,9 @@ protected virtual void OnShown(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_SHOWN]; if (handler != null) + { handler(this, e); + } } [EditorBrowsable(EditorBrowsableState.Advanced)] @@ -4932,7 +5001,9 @@ protected override void OnTextChanged(EventArgs e) // If there is no control box, there should only be a title bar if text != "". int newTextEmpty = Text.Length == 0 ? 1 : 0; if (!ControlBox && formState[FormStateIsTextEmpty] != newTextEmpty) + { RecreateHandle(); + } formState[FormStateIsTextEmpty] = newTextEmpty; } @@ -4962,11 +5033,15 @@ internal void PerformOnInputLanguageChanging(InputLanguageChangingEventArgs iplc protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (base.ProcessCmdKey(ref msg, keyData)) + { return true; + } MainMenu curMenu = (MainMenu)Properties.GetObject(PropCurMenu); if (curMenu != null && curMenu.ProcessCmdKey(ref msg, keyData)) + { return true; + } // Process MDI accelerator keys. @@ -5082,14 +5157,19 @@ protected override bool ProcessDialogChar(char charCode) protected override bool ProcessKeyPreview(ref Message m) { if (formState[FormStateKeyPreview] != 0 && ProcessKeyEventArgs(ref m)) + { return true; + } + return base.ProcessKeyPreview(ref m); } protected override bool ProcessTabKey(bool forward) { if (SelectNextControl(ActiveControl, forward, true, true, true)) + { return true; + } // I've added a special case for UserControls because they shouldn't cycle back to the // beginning if they don't have a parent form, such as when they're on an ActiveXBridge. @@ -5272,7 +5352,9 @@ internal override void RecreateHandleCore() public void RemoveOwnedForm(Form ownedForm) { if (ownedForm == null) + { return; + } if (ownedForm.OwnerInternal != null) { @@ -5626,10 +5708,15 @@ private void SetDefaultButton(IButtonControl button) if (defaultButton != button) { if (defaultButton != null) + { defaultButton.NotifyDefault(false); + } + Properties.SetObject(PropDefaultButton, button); if (button != null) + { button.NotifyDefault(true); + } } } @@ -5651,12 +5738,16 @@ protected override void SetClientSizeCore(int x, int y) if (VScroll != hadVScroll) { if (VScroll) + { x += SystemInformation.VerticalScrollBarWidth; + } } if (HScroll != hadHScroll) { if (HScroll) + { y += SystemInformation.HorizontalScrollBarHeight; + } } if (x != ClientSize.Width || y != ClientSize.Height) { @@ -5876,7 +5967,10 @@ public DialogResult ShowDialog(IWin32Window owner) // if (!UnsafeNativeMethods.IsWindow(new HandleRef(null, hWndActive))) + { hWndActive = hWndOwner; + } + if (UnsafeNativeMethods.IsWindow(new HandleRef(null, hWndActive)) && SafeNativeMethods.IsWindowVisible(new HandleRef(null, hWndActive))) { UnsafeNativeMethods.SetActiveWindow(new HandleRef(null, hWndActive)); @@ -6481,7 +6575,9 @@ protected virtual void OnResizeBegin(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_RESIZEBEGIN]; if (handler != null) + { handler(this, e); + } } } @@ -6496,7 +6592,9 @@ protected virtual void OnResizeEnd(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_RESIZEEND]; if (handler != null) + { handler(this, e); + } } } @@ -7000,7 +7098,9 @@ private void WmInitMenuPopup(ref Message m) //curMenu.UpdateRtl((RightToLeft == RightToLeft.Yes)); if (curMenu.ProcessInitMenuPopup(m.WParam)) + { return; + } } base.WndProc(ref m); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/GroupBoxRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/GroupBoxRenderer.cs index f6533aed71c..0f9ab7715f5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/GroupBoxRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/GroupBoxRenderer.cs @@ -105,9 +105,13 @@ public static void DrawParentBackground(Graphics g, Rectangle bounds, Control ch public static void DrawGroupBox(Graphics g, Rectangle bounds, GroupBoxState state) { if (RenderWithVisualStyles) + { DrawThemedGroupBoxNoText(g, bounds, state); + } else + { DrawUnthemedGroupBoxNoText(g, bounds, state); + } } /// @@ -138,9 +142,13 @@ public static void DrawGroupBox(Graphics g, Rectangle bounds, string groupBoxTex public static void DrawGroupBox(Graphics g, Rectangle bounds, string groupBoxText, Font font, TextFormatFlags flags, GroupBoxState state) { if (RenderWithVisualStyles) + { DrawThemedGroupBoxWithText(g, bounds, groupBoxText, font, DefaultTextColor(state), flags, state); + } else + { DrawUnthemedGroupBoxWithText(g, bounds, groupBoxText, font, DefaultTextColor(state), flags, state); + } } /// @@ -151,9 +159,13 @@ public static void DrawGroupBox(Graphics g, Rectangle bounds, string groupBoxTex public static void DrawGroupBox(Graphics g, Rectangle bounds, string groupBoxText, Font font, Color textColor, TextFormatFlags flags, GroupBoxState state) { if (RenderWithVisualStyles) + { DrawThemedGroupBoxWithText(g, bounds, groupBoxText, font, textColor, flags, state); + } else + { DrawUnthemedGroupBoxWithText(g, bounds, groupBoxText, font, textColor, flags, state); + } } /// @@ -292,7 +304,9 @@ private static void DrawUnthemedGroupBoxWithText(Graphics g, Rectangle bounds, s // Pad text area to stop background from touching text if (textBounds.Width > 0) + { textBounds.Inflate(2, 0); + } Pen light = new Pen(SystemColors.ControlLight); Pen dark = new Pen(SystemColors.ControlDark); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ImageKeyConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ImageKeyConverter.cs index dfdf2f1fa26..24790d094ab 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ImageKeyConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ImageKeyConverter.cs @@ -181,7 +181,9 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex for (int i = 0; i < imageKeys.Count; i++) { if ((imageKeys[i] != null) && (imageKeys[i].Length != 0)) + { values[i] = imageKeys[i]; + } } return new StandardValuesCollection(values); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs index baf5c618618..6613fa3d588 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs @@ -253,7 +253,10 @@ public ImageCollection Images get { if (imageCollection == null) + { imageCollection = new ImageCollection(this); + } + return imageCollection; } } @@ -319,7 +322,9 @@ public ImageListStreamer ImageStream get { if (Images.Empty) + { return null; + } // No need for us to create the handle, because any serious attempts to use the // ImageListStreamer will do it for us. @@ -458,7 +463,9 @@ private Bitmap CreateBitmap(Original original, out bool ownsBitmap) Color transparent = transparentColor; ownsBitmap = false; if ((original.options & OriginalOptions.CustomTransparentColor) != 0) + { transparent = original.customTransparentColor; + } Bitmap bitmap; if (original.image is Bitmap) @@ -484,7 +491,10 @@ private Bitmap CreateBitmap(Original original, out bool ownsBitmap) bitmap = (Bitmap)bitmap.Clone(); bitmap.MakeTransparent(transparent); if (ownsBitmap) + { source.Dispose(); + } + ownsBitmap = true; } @@ -493,16 +503,24 @@ private Bitmap CreateBitmap(Original original, out bool ownsBitmap) { // strip width must be a positive multiple of image list width if (size.Width == 0 || (size.Width % imageSize.Width) != 0) + { throw new ArgumentException(SR.ImageListStripBadWidth, "original"); + } + if (size.Height != imageSize.Height) + { throw new ArgumentException(SR.ImageListImageTooShort, "original"); + } } else if (!size.Equals(ImageSize)) { Bitmap source = bitmap; bitmap = new Bitmap(source, ImageSize); if (ownsBitmap) + { source.Dispose(); + } + ownsBitmap = true; } return bitmap; @@ -516,7 +534,10 @@ private int AddIconToHandle(Original original, Icon icon) Debug.Assert(HandleCreated, "Calling AddIconToHandle when there is no handle"); int index = SafeNativeMethods.ImageList_ReplaceIcon(new HandleRef(this, Handle), -1, new HandleRef(icon, icon.Handle)); if (index == -1) + { throw new InvalidOperationException(SR.ImageListAddFailed); + } + return index; } finally @@ -540,7 +561,10 @@ private int AddToHandle(Original original, Bitmap bitmap) SafeNativeMethods.DeleteObject(new HandleRef(null, hMask)); if (index == -1) + { throw new InvalidOperationException(SR.ImageListAddFailed); + } + return index; } @@ -590,7 +614,10 @@ private void CreateHandle() } if (Handle == IntPtr.Zero) + { throw new InvalidOperationException(SR.ImageListCreateFailed); + } + SafeNativeMethods.ImageList_SetBkColor(new HandleRef(this, Handle), NativeMethods.CLR_NONE); Debug.Assert(originals != null, "Handle not yet created, yet original images are gone"); @@ -608,7 +635,9 @@ private void CreateHandle() Bitmap bitmapValue = CreateBitmap(original, out bool ownsBitmap); AddToHandle(original, bitmapValue); if (ownsBitmap) + { bitmapValue.Dispose(); + } } } originals = null; @@ -673,7 +702,10 @@ public void Draw(Graphics g, int x, int y, int index) public void Draw(Graphics g, int x, int y, int width, int height, int index) { if (index < 0 || index >= Images.Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } + IntPtr dc = g.GetHdc(); try { @@ -753,7 +785,9 @@ private static bool BitmapHasAlpha(BitmapData bmpData) private Bitmap GetBitmap(int index) { if (index < 0 || index >= Images.Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } Bitmap result = null; @@ -944,13 +978,19 @@ private void PutImageInTempBitmap(int index, bool useSnapshot) { private void PerformRecreateHandle(string reason) { if (!HandleCreated) + { return; + } if (originals == null || Images.Empty) + { originals = new ArrayList(); // spoof it into thinking this is the first CreateHandle + } if (originals == null) + { throw new InvalidOperationException(string.Format(SR.ImageListCantRecreate, reason)); + } DestroyHandle(); CreateHandle(); @@ -1134,7 +1174,9 @@ internal ImageCollection(ImageList owner) internal void ResetKeys() { if (imageInfoCollection != null) + { imageInfoCollection.Clear(); + } for (int i = 0; i < Count; i++) { @@ -1227,13 +1269,18 @@ public Image this[int index] get { if (index < 0 || index >= Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } + return owner.GetBitmap(index); } set { if (index < 0 || index >= Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } if (value == null) { @@ -1241,7 +1288,9 @@ public Image this[int index] } if (!(value is Bitmap)) + { throw new ArgumentException(SR.ImageListBitmap); + } AssertInvariant(); Bitmap bitmap = (Bitmap)value; @@ -1266,8 +1315,9 @@ public Image this[int index] SafeNativeMethods.DeleteObject(new HandleRef(null, hMask)); if (!ok) + { throw new InvalidOperationException(SR.ImageListReplaceFailed); - + } } finally { @@ -1445,7 +1495,9 @@ private int Add(Original original, ImageInfo imageInfo) Bitmap bitmapValue = owner.CreateBitmap(original, out bool ownsBitmap); index = owner.AddToHandle(original, bitmapValue); if (ownsBitmap) + { bitmapValue.Dispose(); + } } } else if (original.image is Icon) @@ -1478,12 +1530,17 @@ private int Add(Original original, ImageInfo imageInfo) else { if (imageInfo == null) + { imageInfo = new ImageInfo(); + } + imageInfoCollection.Add(imageInfo); } if (!owner.inAddRange) + { owner.OnChangeHandle(EventArgs.Empty); + } return index; } @@ -1518,9 +1575,14 @@ public int AddStrip(Image value) // strip width must be a positive multiple of image list width // if (value.Width == 0 || (value.Width % owner.ImageSize.Width) != 0) + { throw new ArgumentException(SR.ImageListStripBadWidth, "value"); + } + if (value.Height != owner.ImageSize.Height) + { throw new ArgumentException(SR.ImageListImageTooShort, "value"); + } int nImages = value.Width / owner.ImageSize.Width; @@ -1536,12 +1598,16 @@ public void Clear() { AssertInvariant(); if (owner.originals != null) + { owner.originals.Clear(); + } imageInfoCollection.Clear(); if (owner.HandleCreated) + { SafeNativeMethods.ImageList_Remove(new HandleRef(owner, owner.Handle), -1); + } owner.OnChangeHandle(EventArgs.Empty); } @@ -1660,7 +1726,9 @@ public IEnumerator GetEnumerator() AssertInvariant(); Image[] images = new Image[Count]; for (int i = 0; i < images.Length; ++i) + { images[i] = owner.GetBitmap(i); + } return images.GetEnumerator(); } @@ -1683,7 +1751,9 @@ void IList.Remove(object image) public void RemoveAt(int index) { if (index < 0 || index >= Count) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } AssertInvariant(); bool ok = SafeNativeMethods.ImageList_Remove(new HandleRef(owner, owner.Handle), index); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ImageListStreamer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ImageListStreamer.cs index e07ef6aa2f4..7e4dcb978ca 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ImageListStreamer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ImageListStreamer.cs @@ -233,7 +233,9 @@ private byte[] Decompress(byte[] input) } if (handle == IntPtr.Zero || !WriteImageList(handle, stream)) + { throw new InvalidOperationException(SR.ImageListStreamerSaveFailed); + } si.AddValue("Data", Compress(stream.ToArray())); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/KeysConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/KeysConverter.cs index a5e2042de63..747c108b610 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/KeysConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/KeysConverter.cs @@ -261,7 +261,10 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul bool asString = destinationType == typeof(string); bool asEnum = false; if (!asString) + { asEnum = destinationType == typeof(Enum[]); + } + if (asString || asEnum) { Keys key = (Keys)value; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs index 8cb907fe041..aa95f6f9cfe 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs @@ -358,7 +358,9 @@ protected override CreateParams CreateParams } } else + { cp.Style |= NativeMethods.SS_LEFT; + } switch (BorderStyle) { @@ -371,7 +373,9 @@ protected override CreateParams CreateParams } if (!UseMnemonic) + { cp.Style |= NativeMethods.SS_NOPREFIX; + } return cp; } @@ -1764,9 +1768,14 @@ protected internal override bool ProcessMnemonic(char charCode) protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { if ((specified & BoundsSpecified.Height) != BoundsSpecified.None) + { requestedHeight = height; + } + if ((specified & BoundsSpecified.Width) != BoundsSpecified.None) + { requestedWidth = width; + } if (AutoSize && SelfSizing) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs index 5cba558f576..d64f97950a3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs @@ -305,13 +305,24 @@ internal static void UpdateSpecifiedBounds(IArrangedElement element, int x, int // if any of them are changed and specified cache the new value. if (!xChangedButNotSpecified) + { originalBounds.X = x; + } + if (!yChangedButNotSpecified) + { originalBounds.Y = y; + } + if (!wChangedButNotSpecified) + { originalBounds.Width = width; + } + if (!hChangedButNotSpecified) + { originalBounds.Height = height; + } element.Properties.SetRectangle(_specifiedBoundsProperty, originalBounds); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DockAndAnchorLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DockAndAnchorLayout.cs index 2e12bc8f58f..aa08af8514b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DockAndAnchorLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DockAndAnchorLayout.cs @@ -207,9 +207,14 @@ private static Rectangle GetAnchorDestination(IArrangedElement element, Rectangl { // the size is actually zero, set the width and heights appropriately. if (right < left) + { right = left; + } + if (bottom < top) + { bottom = top; + } } else { @@ -558,11 +563,19 @@ private static bool xLayout(IArrangedElement container, bool measureOnly, out Si if (CommonProperties.GetNeedsDockAndAnchorLayout(element)) { if (!dock && CommonProperties.GetNeedsDockLayout(element)) + { dock = true; + } + if (!anchor && CommonProperties.GetNeedsAnchorLayout(element)) + { anchor = true; + } + if (!autoSize && CommonProperties.xGetAutoSizedAndAnchored(element)) + { autoSize = true; + } } } @@ -573,7 +586,10 @@ private static bool xLayout(IArrangedElement container, bool measureOnly, out Si Size preferredSizeForAnchoring = Size.Empty; if (dock) + { preferredSizeForDocking = LayoutDockedControls(container, measureOnly); + } + if (anchor && !measureOnly) { // in the case of anchor, where we currently are defines the preferred size, @@ -582,7 +598,9 @@ private static bool xLayout(IArrangedElement container, bool measureOnly, out Si } if (autoSize) + { LayoutAutoSizedControls(container); + } if (!measureOnly) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutUtils.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutUtils.cs index b34a92ccffa..27ecc3ca21c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutUtils.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutUtils.cs @@ -135,9 +135,15 @@ private static byte xContentAlignmentToIndex(int threeBitFlag) public static Size ConvertZeroToUnbounded(Size size) { if (size.Width == 0) + { size.Width = int.MaxValue; + } + if (size.Height == 0) + { size.Height = int.MaxValue; + } + return size; } 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 94481abba9a..b0f57b8e9ad 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 @@ -41,7 +41,10 @@ private struct SorterObjectArray internal SorterObjectArray(object[] keys, IComparer comparer) { if (comparer == null) + { comparer = Comparer.Default; + } + this.keys = keys; this.comparer = comparer; } @@ -95,9 +98,14 @@ internal void QuickSort(int left, int right) try { while (comparer.Compare(keys[i], x) < 0) + { i++; + } + while (comparer.Compare(x, keys[j]) < 0) + { j--; + } } catch (IndexOutOfRangeException) { @@ -108,7 +116,10 @@ internal void QuickSort(int left, int right) throw new InvalidOperationException(); } if (i > j) + { break; + } + if (i < j) { object key = keys[i]; @@ -121,13 +132,19 @@ internal void QuickSort(int left, int right) if (j - left <= right - i) { if (left < j) + { QuickSort(left, j); + } + left = i; } else { if (i < right) + { QuickSort(i, right); + } + right = j; } } while (left < right); @@ -137,7 +154,9 @@ internal void QuickSort(int left, int right) private static void Sort(object[] array, IComparer comparer) { if (array == null) + { throw new ArgumentNullException(nameof(array)); + } if (array.Length > 1) { @@ -719,7 +738,10 @@ private bool ScanRowForOverlap(int maxColumns, ReservationGrid reservationGrid, for (layoutInfo.ColumnStart = i + 1; layoutInfo.ColumnStart < maxColumns && reservationGrid.IsReserved(layoutInfo.ColumnStart, rowOffset); layoutInfo.ColumnStart++) + { ; + } + return true; } } @@ -1607,7 +1629,9 @@ public override bool Equals(object obj) { LayoutInfo other = obj as LayoutInfo; if (other == null) + { return false; + } return other.RowStart == RowStart && other.ColumnStart == ColumnStart diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs index ed3262cc0d8..cbd06d83caf 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs @@ -457,7 +457,9 @@ protected Cursor OverrideCursor // if ((r.left <= p.x && p.x < r.right && r.top <= p.y && p.y < r.bottom) || UnsafeNativeMethods.GetCapture() == Handle) + { SendMessage(Interop.WindowMessages.WM_SETCURSOR, Handle, NativeMethods.HTCLIENT); + } } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingHelper.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingHelper.cs index 8e1a67335e7..f127e8ff186 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingHelper.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingHelper.cs @@ -698,7 +698,9 @@ private static object GetFirstItemByEnumerable(IEnumerable enumerable) listEnumerator.Reset(); if (listEnumerator.MoveNext()) + { instance = listEnumerator.Current; + } // after we are done w/ the enumerator, reset it listEnumerator.Reset(); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs index a697bc5785e..b830d9fc682 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs @@ -329,11 +329,19 @@ protected override CreateParams CreateParams cp.Style |= NativeMethods.WS_VSCROLL | NativeMethods.LBS_NOTIFY | NativeMethods.LBS_HASSTRINGS; if (scrollAlwaysVisible) + { cp.Style |= NativeMethods.LBS_DISABLENOSCROLL; + } + if (!integralHeight) + { cp.Style |= NativeMethods.LBS_NOINTEGRALHEIGHT; + } + if (useTabStops) + { cp.Style |= NativeMethods.LBS_USETABSTOPS; + } switch (borderStyle) { @@ -1380,13 +1388,17 @@ public void BeginUpdate() private void CheckIndex(int index) { if (index < 0 || index >= Items.Count) + { throw new ArgumentOutOfRangeException(nameof(index), string.Format(SR.IndexOutOfRange, index.ToString(CultureInfo.CurrentCulture))); + } } private void CheckNoDataSource() { if (DataSource != null) + { throw new ArgumentException(SR.DataSourceLocksItems); + } } protected virtual ObjectCollection CreateItemCollection() @@ -1493,16 +1505,23 @@ public int GetItemHeight(int index) // no items. // if (index < 0 || (index > 0 && index >= itemCount)) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } if (drawMode != DrawMode.OwnerDrawVariable) + { index = 0; + } if (IsHandleCreated) { int h = unchecked((int)(long)SendMessage(NativeMethods.LB_GETITEMHEIGHT, index, 0)); if (h == -1) + { throw new Win32Exception(); + } + return h; } @@ -1733,7 +1752,10 @@ private void NativeUpdateSelection() case SelectionMode.One: int index = unchecked((int)(long)SendMessage(NativeMethods.LB_GETCURSEL, 0, 0)); if (index >= 0) + { result = new int[] { index }; + } + break; case SelectionMode.MultiSimple: @@ -1981,7 +2003,9 @@ protected override void OnDisplayMemberChanged(EventArgs e) RefreshItems(); if (SelectionMode != SelectionMode.None && DataManager != null) + { SelectedIndex = DataManager.Position; + } } /// @@ -2132,7 +2156,10 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound if (!integralHeightAdjust && height != Height) + { requestedHeight = height; + } + base.SetBoundsCore(x, y, width, height, specified); } @@ -2192,10 +2219,14 @@ public void SetSelected(int index, bool value) { int itemCount = (itemsCollection == null) ? 0 : itemsCollection.Count; if (index < 0 || index >= itemCount) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } if (selectionMode == SelectionMode.None) + { throw new InvalidOperationException(SR.ListBoxInvalidSelectionMode); + } SelectedItems.SetSelected(index, value); if (IsHandleCreated) @@ -2961,12 +2992,16 @@ int IComparer.Compare(object item1, object item2) if (item1 == null) { if (item2 == null) + { return 0; //both null, then they are equal + } return -1; //item1 is null, but item2 is valid (greater) } if (item2 == null) + { return 1; //item2 is null, so item 1 is greater + } if (item1 is Entry) { @@ -3030,7 +3065,9 @@ public EntryEnumerator(ItemArray items, int state, bool anyBit) bool IEnumerator.MoveNext() { if (version != items.version) + { throw new InvalidOperationException(SR.ListEnumVersionMismatch); + } while (true) { @@ -3066,7 +3103,10 @@ bool IEnumerator.MoveNext() void IEnumerator.Reset() { if (version != items.version) + { throw new InvalidOperationException(SR.ListEnumVersionMismatch); + } + current = -1; } @@ -3228,7 +3268,9 @@ private int AddInternal(object item) } } else + { index = 0; + } Debug.Assert(index >= 0 && index <= Count, "Wrong index for insert"); InnerArray.Insert(index, item); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs index 29de3965510..8f20208901c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs @@ -442,9 +442,13 @@ public bool BackgroundImageTiled }; if (BackgroundImageTiled) + { lvbkImage.ulFlags = NativeMethods.LVBKIF_STYLE_TILE; + } else + { lvbkImage.ulFlags = NativeMethods.LVBKIF_STYLE_NORMAL; + } lvbkImage.ulFlags |= NativeMethods.LVBKIF_SOURCE_URL; lvbkImage.pszImage = backgroundImageFileName; @@ -548,7 +552,9 @@ public bool CheckBoxes // Comctl should handle auto-arrange for us, but doesn't if (AutoArrange) + { ArrangeIcons(Alignment); + } } } else @@ -744,7 +750,9 @@ protected override CreateParams CreateParams } if (AutoArrange) + { cp.Style |= NativeMethods.LVS_AUTOARRANGE; + } switch (borderStyle) { @@ -767,16 +775,24 @@ protected override CreateParams CreateParams } if (LabelEdit) + { cp.Style |= NativeMethods.LVS_EDITLABELS; + } if (!LabelWrap) + { cp.Style |= NativeMethods.LVS_NOLABELWRAP; + } if (!HideSelection) + { cp.Style |= NativeMethods.LVS_SHOWSELALWAYS; + } if (!MultiSelect) + { cp.Style |= NativeMethods.LVS_SINGLESEL; + } if (listItemSorter == null) { @@ -792,7 +808,9 @@ protected override CreateParams CreateParams } if (VirtualMode) + { cp.Style |= NativeMethods.LVS_OWNERDATA; + } // We can do this 'cuz the viewStyle enums are the same values as the actual LVS styles // this new check since the value for LV_VIEW_TILE == LVS_SINGLESEL; so dont OR that value since @@ -880,7 +898,9 @@ public ListViewItem FocusedItem { int displayIndex = unchecked((int)(long)SendMessage(NativeMethods.LVM_GETNEXTITEM, -1, NativeMethods.LVNI_FOCUSED)); if (displayIndex > -1) + { return Items[displayIndex]; + } } return null; } @@ -1054,7 +1074,9 @@ public ColumnHeaderStyle HeaderStyle RecreateHandleInternal(); } else + { UpdateStyles(); + } } } } @@ -1641,9 +1663,13 @@ public SortOrder Sorting // If we're changing to No Sorting, no need to recreate the handle // because none of the existing items need to be rearranged. if (value == SortOrder.None) + { UpdateStyles(); + } else + { RecreateHandleInternal(); + } } } } @@ -1682,7 +1708,9 @@ public ImageList StateImageList } if (IsHandleCreated) + { SendMessage(NativeMethods.LVM_SETIMAGELIST, NativeMethods.LVSIL_STATE, value == null ? IntPtr.Zero : value.Handle); + } } } else @@ -1838,7 +1866,9 @@ public ListViewItem TopItem get { if (viewStyle == View.LargeIcon || viewStyle == View.SmallIcon || viewStyle == View.Tile) + { throw new InvalidOperationException(SR.ListViewGetTopItem); + } if (!IsHandleCreated) { @@ -1853,25 +1883,38 @@ public ListViewItem TopItem } topIndex = unchecked((int)(long)SendMessage(NativeMethods.LVM_GETTOPINDEX, 0, 0)); if (topIndex >= 0 && topIndex < Items.Count) + { return Items[topIndex]; + } return null; } set { if (viewStyle == View.LargeIcon || viewStyle == View.SmallIcon || viewStyle == View.Tile) + { throw new InvalidOperationException(SR.ListViewSetTopItem); + } if (value == null) + { return; + } + if (value.ListView != this) + { return; + } + if (!IsHandleCreated) { CreateHandle(); } if (value == TopItem) + { return; + } + EnsureVisible(value.Index); ListViewItem topItem = TopItem; @@ -1887,9 +1930,14 @@ public ListViewItem TopItem } // if (value.Index == topItem.Index) + { return; + } + if (Scrollable) + { Scroll(topItem.Index, value.Index); + } } } @@ -1980,9 +2028,15 @@ public int VirtualListSize set { if (value < 0) + { throw new System.ArgumentException(string.Format(SR.ListViewVirtualListSizeInvalidArgument, "value", (value))); + } + if (value == virtualListSize) + { return; + } + bool keepTopItem = IsHandleCreated && VirtualMode && View == View.Details && !DesignMode; int topIndex = -1; if (keepTopItem) @@ -1993,7 +2047,9 @@ public int VirtualListSize virtualListSize = value; if (IsHandleCreated && VirtualMode && !DesignMode) + { SendMessage(NativeMethods.LVM_SETITEMCOUNT, virtualListSize, 0); + } if (keepTopItem) { @@ -2024,10 +2080,14 @@ public bool VirtualMode set { if (value == VirtualMode) + { return; + } if (value && Items.Count > 0) + { throw new InvalidOperationException(SR.ListViewVirtualListViewRequiresNoItems); + } if (value && CheckedItems.Count > 0) { @@ -2277,7 +2337,9 @@ public void ArrangeIcons(ListViewAlignment value) { // LVM_ARRANGE only work in SmallIcon view if (viewStyle != View.SmallIcon) + { return; + } switch ((int)value) { @@ -2541,7 +2603,9 @@ protected override void CreateHandle() // image location if (BackgroundImage != null) + { SetBackgroundImage(); + } } // @@ -2995,11 +3059,19 @@ private void DetachImageList(object sender, EventArgs e) } #endif // DEBUG if (sender == imageListSmall) + { SmallImageList = null; + } + if (sender == imageListLarge) + { LargeImageList = null; + } + if (sender == imageListState) + { StateImageList = null; + } } finally { @@ -3141,7 +3213,9 @@ public void EnsureVisible(int index) throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } if (IsHandleCreated) + { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_ENSUREVISIBLE, index, 0); + } } /// @@ -3243,7 +3317,10 @@ private ListViewItem FindItem(bool isTextSearch, string text, bool isPrefixSearc } if (!IsHandleCreated) + { CreateHandle(); + } + if (VirtualMode) { SearchForVirtualItemEventArgs sviEvent = new SearchForVirtualItemEventArgs(isTextSearch, isPrefixSearch, includeSubItemsInSearch, text, pt, dir, startIndex); @@ -3424,7 +3501,10 @@ internal int GetDisplayIndex(ListViewItem item, int lastIndex) foreach (object o in listItemsArray) { if (o == item) + { return index; + } + index++; } return -1; @@ -3438,12 +3518,16 @@ internal int GetDisplayIndex(ListViewItem item, int lastIndex) internal int GetColumnIndex(ColumnHeader ch) { if (columnHeaders == null) + { return -1; + } for (int i = 0; i < columnHeaders.Length; i++) { if (columnHeaders[i] == ch) + { return i; + } } return -1; @@ -3465,7 +3549,9 @@ public ListViewItem GetItemAt(int x, int y) ListViewItem li = null; if (displayIndex >= 0 && ((lvhi.flags & NativeMethods.LVHT_ONITEM) != 0)) + { li = Items[displayIndex]; + } return li; } @@ -3567,7 +3653,9 @@ public Rectangle GetItemRect(int index, ItemBoundsPortion portion) left = (int)portion }; if (unchecked((int)(long)SendMessage(NativeMethods.LVM_GETITEMRECT, index, ref itemrect)) == 0) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } return Rectangle.FromLTRB(itemrect.left, itemrect.top, itemrect.right, itemrect.bottom); } @@ -3579,7 +3667,9 @@ public Rectangle GetItemRect(int index, ItemBoundsPortion portion) private Rectangle GetItemRectOrEmpty(int index) { if (index < 0 || index >= Items.Count) + { return Rectangle.Empty; + } if (View == View.Details && Columns.Count == 0) { @@ -3592,7 +3682,9 @@ private Rectangle GetItemRectOrEmpty(int index) left = 0 }; if (unchecked((int)(long)SendMessage(NativeMethods.LVM_GETITEMRECT, index, ref itemrect)) == 0) + { return Rectangle.Empty; + } return Rectangle.FromLTRB(itemrect.left, itemrect.top, itemrect.right, itemrect.bottom); } @@ -3673,7 +3765,9 @@ internal Rectangle GetSubItemRect(int itemIndex, int subItemIndex, ItemBoundsPor top = subItemIndex }; if (unchecked((int)(long)SendMessage(NativeMethods.LVM_GETSUBITEMRECT, itemIndex, ref itemrect)) == 0) + { throw new ArgumentOutOfRangeException(nameof(itemIndex), itemIndex, string.Format(SR.InvalidArgument, nameof(itemIndex), itemIndex)); + } Rectangle result = Rectangle.FromLTRB(itemrect.left, itemrect.top, itemrect.right, itemrect.bottom); @@ -3754,7 +3848,9 @@ private void InvalidateColumnHeaders() IntPtr hwndHdr = UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.LVM_GETHEADER, 0, 0); if (hwndHdr != IntPtr.Zero) + { SafeNativeMethods.InvalidateRect(new HandleRef(this, hwndHdr), null, true); + } } } @@ -3771,10 +3867,14 @@ internal ColumnHeader InsertColumn(int index, ColumnHeader ch) internal ColumnHeader InsertColumn(int index, ColumnHeader ch, bool refreshSubItems) { if (ch == null) + { throw new ArgumentNullException(nameof(ch)); + } + if (ch.OwnerListview != null) + { throw new ArgumentException(string.Format(SR.OnlyOneControl, ch.Text), "ch"); - + } int idx; // in Tile view the ColumnHeaders collection is used for the Tile Information @@ -3791,7 +3891,9 @@ internal ColumnHeader InsertColumn(int index, ColumnHeader ch, bool refreshSubIt // First column must be left aligned if (-1 == idx) + { throw new InvalidOperationException(SR.ListViewAddColumnFailed); + } // Add the column to our internal array int columnCount = (columnHeaders == null ? 0 : columnHeaders.Length); @@ -3799,11 +3901,16 @@ internal ColumnHeader InsertColumn(int index, ColumnHeader ch, bool refreshSubIt { ColumnHeader[] newHeaders = new ColumnHeader[columnCount + 1]; if (columnCount > 0) + { System.Array.Copy(columnHeaders, 0, newHeaders, 0, columnCount); + } + columnHeaders = newHeaders; } else + { columnHeaders = new ColumnHeader[1]; + } if (idx < columnCount) { @@ -3850,7 +3957,9 @@ internal ColumnHeader InsertColumn(int index, ColumnHeader ch, bool refreshSubIt RecreateHandleInternal(); } else if (IsHandleCreated && refreshSubItems) + { RealizeAllSubItems(); + } return ch; } @@ -4220,7 +4329,10 @@ private int InsertItemsNative(int index, ListViewItem[] items) protected override bool IsInputKey(Keys keyData) { if ((keyData & Keys.Alt) == Keys.Alt) + { return false; + } + switch (keyData & Keys.KeyCode) { case Keys.PageUp: @@ -4232,7 +4344,9 @@ protected override bool IsInputKey(Keys keyData) bool isInputKey = base.IsInputKey(keyData); if (isInputKey) + { return true; + } if (listViewState[LISTVIEWSTATE_inLabelEdit]) { @@ -4298,7 +4412,9 @@ private void LvnBeginDrag(MouseButtons buttons, NativeMethods.NMLISTVIEW nmlv) protected virtual void OnAfterLabelEdit(LabelEditEventArgs e) { if (onAfterLabelEdit != null) + { onAfterLabelEdit(this, e); + } } protected override void OnBackgroundImageChanged(EventArgs e) @@ -4367,7 +4483,9 @@ protected override void OnMouseHover(EventArgs e) protected virtual void OnBeforeLabelEdit(LabelEditEventArgs e) { if (onBeforeLabelEdit != null) + { onBeforeLabelEdit(this, e); + } } /// @@ -4376,7 +4494,9 @@ protected virtual void OnCacheVirtualItems(CacheVirtualItemsEventArgs e) { CacheVirtualItemsEventHandler handler = (CacheVirtualItemsEventHandler)Events[EVENT_CACHEVIRTUALITEMS]; if (handler != null) + { handler(this, e); + } } /// @@ -4385,7 +4505,9 @@ protected virtual void OnCacheVirtualItems(CacheVirtualItemsEventArgs e) protected virtual void OnColumnClick(ColumnClickEventArgs e) { if (onColumnClick != null) + { onColumnClick(this, e); + } } /// @@ -4395,7 +4517,9 @@ protected virtual void OnColumnReordered(ColumnReorderedEventArgs e) { ColumnReorderedEventHandler handler = (ColumnReorderedEventHandler)Events[EVENT_COLUMNREORDERED]; if (handler != null) + { handler(this, e); + } } /// @@ -4683,7 +4807,9 @@ protected override void OnHandleDestroyed(EventArgs e) protected virtual void OnItemActivate(EventArgs e) { if (onItemActivate != null) + { onItemActivate(this, e); + } } /// @@ -4710,7 +4836,9 @@ protected virtual void OnItemChecked(ItemCheckedEventArgs e) protected virtual void OnItemDrag(ItemDragEventArgs e) { if (onItemDrag != null) + { onItemDrag(this, e); + } } /// @@ -4719,7 +4847,9 @@ protected virtual void OnItemDrag(ItemDragEventArgs e) protected virtual void OnItemMouseHover(ListViewItemMouseHoverEventArgs e) { if (onItemMouseHover != null) + { onItemMouseHover(this, e); + } } /// @@ -4729,7 +4859,9 @@ protected virtual void OnItemSelectionChanged(ListViewItemSelectionChangedEventA { ListViewItemSelectionChangedEventHandler eh = (ListViewItemSelectionChangedEventHandler)Events[EVENT_ITEMSELECTIONCHANGED]; if (eh != null) + { eh(this, e); + } } protected override void OnParentChanged(EventArgs e) @@ -4763,7 +4895,9 @@ protected virtual void OnRetrieveVirtualItem(RetrieveVirtualItemEventArgs e) { RetrieveVirtualItemEventHandler handler = (RetrieveVirtualItemEventHandler)Events[EVENT_RETRIEVEVIRTUALITEM]; if (handler != null) + { handler(this, e); + } } @@ -4795,7 +4929,9 @@ protected virtual void OnSearchForVirtualItem(SearchForVirtualItemEventArgs e) { SearchForVirtualItemEventHandler handler = (SearchForVirtualItemEventHandler)Events[EVENT_SEARCHFORVIRTUALITEM]; if (handler != null) + { handler(this, e); + } } /// @@ -4809,7 +4945,9 @@ protected virtual void OnSelectedIndexChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_SELECTEDINDEXCHANGED]; if (handler != null) + { handler(this, e); + } } protected override void OnSystemColorsChanged(EventArgs e) @@ -4830,7 +4968,9 @@ protected virtual void OnVirtualItemsSelectionRangeChanged(ListViewVirtualItemsS { ListViewVirtualItemsSelectionRangeChangedEventHandler eh = (ListViewVirtualItemsSelectionRangeChangedEventHandler)Events[EVENT_VIRTUALITEMSSELECTIONRANGECHANGED]; if (eh != null) + { eh(this, e); + } } private unsafe void PositionHeader() @@ -4927,14 +5067,19 @@ protected void RealizeProperties() } c = ForeColor; if (c != SystemColors.WindowText) + { SendMessage(NativeMethods.LVM_SETTEXTCOLOR, 0, ColorTranslator.ToWin32(c)); - + } if (null != imageListLarge) + { SendMessage(NativeMethods.LVM_SETIMAGELIST, NativeMethods.LVSIL_NORMAL, imageListLarge.Handle); + } if (null != imageListSmall) + { SendMessage(NativeMethods.LVM_SETIMAGELIST, NativeMethods.LVSIL_SMALL, imageListSmall.Handle); + } if (null != imageListState) { @@ -5087,10 +5232,13 @@ private void SetBackgroundImage() lvbkImage.cchImageMax = backgroundImageFileName.Length + 1; lvbkImage.ulFlags = NativeMethods.LVBKIF_SOURCE_URL; if (BackgroundImageTiled) + { lvbkImage.ulFlags |= NativeMethods.LVBKIF_STYLE_TILE; + } else + { lvbkImage.ulFlags |= NativeMethods.LVBKIF_STYLE_NORMAL; - + } } else { @@ -5182,7 +5330,9 @@ internal void SetColumnInfo(int mask, ColumnHeader ch) } if (0 == retval) + { throw new InvalidOperationException(SR.ListViewColumnInfoSet); + } // When running on AMD64 the list view does not invalidate the column header. // So we do it ourselves. InvalidateColumnHeaders(); @@ -5385,9 +5535,14 @@ internal void SetItemIndentCount(int index, int indentCount) internal void SetItemPosition(int index, int x, int y) { if (VirtualMode) + { return; + } + if (index < 0 || index >= itemCount) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } Debug.Assert(IsHandleCreated, "How did we add items without a handle?"); @@ -5617,28 +5772,44 @@ protected void UpdateExtendedStyles() } if (AllowColumnReorder) + { exStyle |= NativeMethods.LVS_EX_HEADERDRAGDROP; + } if (CheckBoxes) + { exStyle |= NativeMethods.LVS_EX_CHECKBOXES; + } if (DoubleBuffered) + { exStyle |= NativeMethods.LVS_EX_DOUBLEBUFFER; + } if (FullRowSelect) + { exStyle |= NativeMethods.LVS_EX_FULLROWSELECT; + } if (GridLines) + { exStyle |= NativeMethods.LVS_EX_GRIDLINES; + } if (HoverSelection) + { exStyle |= NativeMethods.LVS_EX_TRACKSELECT; + } if (HotTracking) + { exStyle |= NativeMethods.LVS_EX_UNDERLINEHOT; + } if (ShowItemToolTips) + { exStyle |= NativeMethods.LVS_EX_INFOTIP; + } SendMessage(NativeMethods.LVM_SETEXTENDEDLISTVIEWSTYLE, exMask, exStyle); Invalidate(); @@ -6252,7 +6423,10 @@ private unsafe void WmReflectNotify(ref Message m) // from msdn: // "If the user cancels editing, the pszText member of the LVITEM structure is NULL" if (!e.CancelEdit && nmlvdp.item.pszText != null) + { Items[nmlvdp.item.iItem].Text = nmlvdp.item.pszText; + } + break; } @@ -6728,7 +6902,10 @@ protected override void WndProc(ref Message m) base.WndProc(ref m); } else + { OnMouseHover(EventArgs.Empty); + } + break; case Interop.WindowMessages.WM_NOTIFY: if (WmNotify(ref m)) @@ -7443,7 +7620,9 @@ private int[] IndicesArray displayIndex = fidx; } else + { throw new InvalidOperationException(SR.SelectedNotEqualActual); + } } } else @@ -7744,7 +7923,9 @@ private ListViewItem[] SelectedItemArray displayIndex = fidx; } else + { throw new InvalidOperationException(SR.SelectedNotEqualActual); + } } return lvitems; @@ -8136,7 +8317,10 @@ public virtual ColumnHeader this[int index] get { if (owner.columnHeaders == null || index < 0 || index >= owner.columnHeaders.Length) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } + return owner.columnHeaders[index]; } } @@ -8622,7 +8806,9 @@ public void Insert(int index, string key, string text, int width, HorizontalAlig public virtual void RemoveAt(int index) { if (owner.columnHeaders == null || index < 0 || index >= owner.columnHeaders.Length) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } int w = owner.columnHeaders[index].Width; // Update width before detaching from ListView @@ -8632,7 +8818,9 @@ public virtual void RemoveAt(int index) int retval = unchecked((int)(long)owner.SendMessage(NativeMethods.LVM_DELETECOLUMN, index, 0)); if (0 == retval) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } } // we need to update the display indices @@ -8658,14 +8846,22 @@ public virtual void RemoveAt(int index) int columnCount = owner.columnHeaders.Length; Debug.Assert(columnCount >= 1, "Column mismatch"); if (columnCount == 1) + { owner.columnHeaders = null; + } else { ColumnHeader[] newHeaders = new ColumnHeader[--columnCount]; if (index > 0) + { System.Array.Copy(owner.columnHeaders, 0, newHeaders, 0, index); + } + if (index < columnCount) + { System.Array.Copy(owner.columnHeaders, index + 1, newHeaders, index, columnCount - index); + } + owner.columnHeaders = newHeaders; } @@ -9326,7 +9522,9 @@ public ListViewItem this[int displayIndex] else { if (displayIndex < 0 || displayIndex >= owner.itemCount) + { throw new ArgumentOutOfRangeException(nameof(displayIndex), displayIndex, string.Format(SR.InvalidArgument, nameof(displayIndex), displayIndex)); + } if (owner.IsHandleCreated && !owner.ListViewHandleDestroyed) { @@ -9348,7 +9546,9 @@ public ListViewItem this[int displayIndex] } if (displayIndex < 0 || displayIndex >= owner.itemCount) + { throw new ArgumentOutOfRangeException(nameof(displayIndex), displayIndex, string.Format(SR.InvalidArgument, nameof(displayIndex), displayIndex)); + } if (owner.ExpectingMouseUp) { @@ -9666,7 +9866,9 @@ public void RemoveAt(int index) } if (index < 0 || index >= owner.itemCount) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } Debug.Assert(!owner.FlipViewToLargeIconAndSmallIcon || Count == 0, "the FlipView... bit is turned off after adding 1 item."); @@ -9686,7 +9888,9 @@ public void RemoveAt(int index) int retval = unchecked((int)(long)owner.SendMessage(NativeMethods.LVM_DELETEITEM, index, 0)); if (0 == retval) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } } else { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs index a2c47be8c91..87644cdc464 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs @@ -60,7 +60,10 @@ public override Image BackgroundImage { Image result = base.BackgroundImage; if (result == null && ParentInternal != null) + { result = ParentInternal.BackgroundImage; + } + return result; } @@ -159,7 +162,9 @@ protected override Control.ControlCollection CreateControlsInstance() public void LayoutMdi(MdiLayout value) { if (Handle == IntPtr.Zero) + { return; + } switch (value) { @@ -309,10 +314,14 @@ private void SetWindowRgn() try { if (rgn1 == IntPtr.Zero || rgn2 == IntPtr.Zero) + { throw new InvalidOperationException(SR.ErrorSettingWindowRegion); + } if (SafeNativeMethods.CombineRgn(new HandleRef(null, rgn1), new HandleRef(null, rgn1), new HandleRef(null, rgn2), NativeMethods.RGN_DIFF) == 0) + { throw new InvalidOperationException(SR.ErrorSettingWindowRegion); + } if (UnsafeNativeMethods.SetWindowRgn(new HandleRef(this, Handle), new HandleRef(null, rgn1), true) == 0) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MainMenu.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MainMenu.cs index 63b52f11e97..1c902b6578b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MainMenu.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MainMenu.cs @@ -175,7 +175,9 @@ internal override void ItemsChanged(int change) { base.ItemsChanged(change); if (form != null) + { form.MenuChanged(change, this); + } } /// @@ -183,7 +185,9 @@ internal override void ItemsChanged(int change) internal virtual void ItemsChanged(int change, Menu menu) { if (form != null) + { form.MenuChanged(change, menu); + } } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs index b36b38815e2..ba7da96b0d7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs @@ -66,7 +66,10 @@ public IntPtr Handle get { if (handle == IntPtr.Zero) + { handle = CreateMenuHandle(); + } + CreateMenuItems(); return handle; } @@ -112,12 +115,17 @@ public MenuItem MdiListItem { MenuItem item = items[i]; if (item.MdiList) + { return item; + } + if (item.IsParent) { item = item.MdiListItem; if (item != null) + { return item; + } } } return null; @@ -245,7 +253,9 @@ protected internal void CloneMenu(Menu menuSrc) int count = menuSrc.MenuItems.Count; newItems = new MenuItem[count]; for (int i = 0; i < count; i++) + { newItems[i] = menuSrc.MenuItems[i].CloneMenu(); + } } MenuItems.Clear(); if (newItems != null) @@ -342,16 +352,24 @@ public MenuItem FindMenuItem(int type, IntPtr value) { case FindHandle: if (item.handle == value) + { return item; + } + break; case FindShortcut: if (item.Shortcut == (Shortcut)(int)value) + { return item; + } + break; } item = item.FindMenuItem(type, value); if (item != null) + { return item; + } } return null; } @@ -366,9 +384,13 @@ protected int FindMergePosition(int mergeOrder) { iT = (iMin + iLim) / 2; if (items[iT].MergeOrder <= mergeOrder) + { iMin = iT + 1; + } else + { iLim = iT; + } } return iMin; } @@ -434,7 +456,10 @@ public ContextMenu GetContextMenu() for (menuT = this; !(menuT is ContextMenu);) { if (!(menuT is MenuItem)) + { return null; + } + menuT = ((MenuItem)menuT).Parent; } return (ContextMenu)menuT; @@ -454,7 +479,10 @@ public MainMenu GetMainMenu() for (menuT = this; !(menuT is MainMenu);) { if (!(menuT is MenuItem)) + { return null; + } + menuT = ((MenuItem)menuT).Parent; } return (MainMenu)menuT; @@ -506,7 +534,9 @@ private IntPtr MatchKeyToMenuItem(int startItem, char key, MenuItemKeyComparer c } if (firstMatch < 0) + { return IntPtr.Zero; + } int action = multipleMatches ? NativeMethods.MNC_SELECT : NativeMethods.MNC_EXECUTE; return (IntPtr)NativeMethods.Util.MAKELONG(firstMatch, action); @@ -634,7 +664,9 @@ internal int SelectedMenuItemIndex { MenuItem mi = items[i]; if (mi != null && mi.Selected) + { return i; + } } return -1; } @@ -660,7 +692,9 @@ internal void WmMenuChar(ref Message m) Menu menu = (m.LParam == handle) ? this : FindMenuItem(FindHandle, m.LParam); if (menu == null) + { return; + } char menuKey = char.ToUpper((char)NativeMethods.Util.LOWORD(m.WParam), CultureInfo.CurrentCulture); @@ -682,7 +716,9 @@ internal IntPtr WmMenuCharInternal(char key) // Next, search for match among owner-draw items with no access keys (looking at first char of item text) if (result == IntPtr.Zero) + { result = MatchKeyToMenuItem(startItem, key, new MenuItemKeyComparer(CheckOwnerDrawItemNoMnemonic)); + } return result; } @@ -723,7 +759,10 @@ public virtual MenuItem this[int index] get { if (index < 0 || index >= owner.ItemCount) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } + return owner.items[index]; } // set not supported @@ -880,9 +919,13 @@ public virtual int Add(int index, MenuItem item) throw new ArgumentException(string.Format(SR.MenuItemAlreadyExists, item.Text), "item"); } if (parent.Parent is MenuItem) + { parent = (MenuItem)parent.Parent; + } else + { break; + } } } @@ -907,7 +950,10 @@ public virtual int Add(int index, MenuItem item) { MenuItem[] newItems = new MenuItem[owner.ItemCount < 2 ? 4 : owner.ItemCount * 2]; if (owner.ItemCount > 0) + { System.Array.Copy(owner.items, 0, newItems, 0, owner.ItemCount); + } + owner.items = newItems; } System.Array.Copy(owner.items, index, owner.items, index + 1, owner.ItemCount - index); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MenuStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MenuStrip.cs index b9397635c22..bd24f0e8619 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MenuStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MenuStrip.cs @@ -220,7 +220,9 @@ protected virtual void OnMenuActivate(EventArgs e) } EventHandler handler = (EventHandler)Events[EventMenuActivate]; if (handler != null) + { handler(this, e); + } } protected virtual void OnMenuDeactivate(EventArgs e) @@ -231,7 +233,9 @@ protected virtual void OnMenuDeactivate(EventArgs e) } EventHandler handler = (EventHandler)Events[EventMenuDeactivate]; if (handler != null) + { handler(this, e); + } } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs index 4e03e65b6ea..dd27672ce35 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs @@ -221,7 +221,9 @@ public DateTime[] AnnuallyBoldedDates annualArrayOfDates.Clear(); for (int i = 0; i < MONTHS_IN_YEAR; ++i) + { monthsOfYear[i] = 0; + } if (value != null && value.Length > 0) { @@ -361,7 +363,9 @@ public Size CalendarDimensions set { if (!dimensions.Equals(value)) + { SetCalendarDimensions(value.Width, value.Height); + } } } @@ -379,11 +383,19 @@ protected override CreateParams CreateParams cp.ClassName = NativeMethods.WC_MONTHCAL; cp.Style |= NativeMethods.MCS_MULTISELECT | NativeMethods.MCS_DAYSTATE; if (!showToday) + { cp.Style |= NativeMethods.MCS_NOTODAY; + } + if (!showTodayCircle) + { cp.Style |= NativeMethods.MCS_NOTODAYCIRCLE; + } + if (showWeekNumbers) + { cp.Style |= NativeMethods.MCS_WEEKNUMBERS; + } if (RightToLeft == RightToLeft.Yes && RightToLeftLayout == true) { @@ -574,7 +586,9 @@ public int MaxSelectionCount if (IsHandleCreated) { if (unchecked((int)(long)SendMessage(NativeMethods.MCM_SETMAXSELCOUNT, value, 0)) == 0) + { throw new ArgumentException(string.Format(SR.MonthCalendarMaxSelCount, value.ToString("D")), nameof(value)); + } } maxSelectionCount = value; } @@ -991,7 +1005,9 @@ public Size SingleMonthSize { if (unchecked((int)(long)SendMessage(NativeMethods.MCM_GETMINREQRECT, 0, ref rect)) == 0) + { throw new InvalidOperationException(SR.InvalidSingleMonthSize); + } return new Size(rect.right, rect.bottom); } @@ -1056,7 +1072,10 @@ public DateTime TodayDate get { if (todayDateSet) + { return todayDate; + } + if (IsHandleCreated) { NativeMethods.SYSTEMTIME st = new NativeMethods.SYSTEMTIME(); @@ -1065,7 +1084,9 @@ public DateTime TodayDate return DateTimePicker.SysTimeToDateTime(st).Date; } else + { return Now.Date; + } } set { @@ -1324,7 +1345,9 @@ private void BoldDates(DateBoldEventArgs e) //now we figure out which monthly and annual dates to bold --startMonth; for (int i = 0; i < months; ++i, ++startMonth) + { e.DaysToBold[i] |= monthsOfYear[startMonth % MONTHS_IN_YEAR] | datesToBoldMonthly; + } } /// @@ -1389,9 +1412,13 @@ private static string FormatDate(DateTime value) public SelectionRange GetDisplayRange(bool visible) { if (visible) + { return GetMonthRange(NativeMethods.GMR_VISIBLE); + } else + { return GetMonthRange(NativeMethods.GMR_DAYSTATE); + } } /// @@ -1601,7 +1628,10 @@ public HitTestInfo HitTest(Point point) protected override bool IsInputKey(Keys keyData) { if ((keyData & Keys.Alt) == Keys.Alt) + { return false; + } + switch (keyData & Keys.KeyCode) { case Keys.PageUp: @@ -1738,7 +1768,9 @@ public void RemoveAllAnnuallyBoldedDates() { annualArrayOfDates.Clear(); for (int i = 0; i < MONTHS_IN_YEAR; ++i) + { monthsOfYear[i] = 0; + } } @@ -1966,13 +1998,19 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound if (width != oldBounds.Width) { if (width > max.Width) + { width = max.Width; + } + width = GetPreferredWidth(width, updateRowsAndColumns); } if (height != oldBounds.Height) { if (height > max.Height) + { height = max.Height; + } + height = GetPreferredHeight(height, updateRowsAndColumns); } base.SetBoundsCore(x, y, width, height, specified); @@ -2039,7 +2077,9 @@ private void SetRange(DateTime minDate, DateTime maxDate) sa.wDay2 = sys.wDay; if ((int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.MCM_SETRANGE, flag, sa) == 0) + { throw new InvalidOperationException(string.Format(SR.MonthCalendarRange, minDate.ToShortDateString(), maxDate.ToShortDateString())); + } } } @@ -2339,9 +2379,13 @@ private void WmDateChanged(ref Message m) //subhag if (start.Ticks < minDate.Ticks || end.Ticks < minDate.Ticks) + { SetSelRange(minDate, minDate); + } else if (start.Ticks > maxDate.Ticks || end.Ticks > maxDate.Ticks) + { SetSelRange(maxDate, maxDate); + } //end subhag OnDateChanged(new DateRangeEventArgs(start, end)); } @@ -2394,9 +2438,13 @@ private void WmDateSelected(ref Message m) //subhag if (start.Ticks < minDate.Ticks || end.Ticks < minDate.Ticks) + { SetSelRange(minDate, minDate); + } else if (start.Ticks > maxDate.Ticks || end.Ticks > maxDate.Ticks) + { SetSelRange(maxDate, maxDate); + } //end subhag OnDateSelected(new DateRangeEventArgs(start, end)); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs index 996ffd455ab..377fb7694a4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs @@ -395,7 +395,9 @@ private static void AddWindowToTable(IntPtr handle, NativeWindow window) int bucketNumber = (int)(seed % (uint)hashBuckets.Length); if (emptySlotNumber == -1 && (hashBuckets[bucketNumber].handle == new IntPtr(-1)) && (hashBuckets[bucketNumber].hash_coll < 0)) + { emptySlotNumber = bucketNumber; + } //We need to check if the collision bit is set because we have the possibility where the first //item in the hash-chain has been deleted. @@ -717,9 +719,14 @@ private IntPtr Callback(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam) finally { if (msg == Interop.WindowMessages.WM_NCDESTROY) + { ReleaseHandle(false); + } + if (msg == NativeMethods.WM_UIUNSUBCLASS) + { ReleaseHandle(true); + } } return m.Result; @@ -838,9 +845,14 @@ private IntPtr DebuggableCallback(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lp finally { if (msg == Interop.WindowMessages.WM_NCDESTROY) + { ReleaseHandle(false); + } + if (msg == NativeMethods.WM_UIUNSUBCLASS) + { ReleaseHandle(true); + } } return m.Result; @@ -1000,7 +1012,9 @@ private static int GetPrime(int minSize) { int size = primes[i]; if (size >= minSize) + { return size; + } } //outside of our predefined table. //compute the hard way. @@ -1020,7 +1034,9 @@ private static int GetPrime(int minSize) } } if (prime) + { return j; + } } else { @@ -1599,7 +1615,9 @@ internal static WindowClass Create(string className, int classStyle) { while (wc != null && (wc.className != null || wc.classStyle != classStyle)) + { wc = wc.next; + } } else { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs index a7bc4de92cc..3e913d6364d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs @@ -303,7 +303,10 @@ public string Text set { if (value == null) + { value = string.Empty; + } + if (value != null && !value.Equals(text)) { if (value != null && value.Length > 63) @@ -536,7 +539,9 @@ private void OnClick(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_CLICK]; if (handler != null) + { handler(this, e); + } } /// @@ -547,7 +552,9 @@ private void OnDoubleClick(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_DOUBLECLICK]; if (handler != null) + { handler(this, e); + } } @@ -559,7 +566,9 @@ private void OnMouseClick(MouseEventArgs mea) { MouseEventHandler handler = (MouseEventHandler)Events[EVENT_MOUSECLICK]; if (handler != null) + { handler(this, mea); + } } /// @@ -570,7 +579,9 @@ private void OnMouseDoubleClick(MouseEventArgs mea) { MouseEventHandler handler = (MouseEventHandler)Events[EVENT_MOUSEDOUBLECLICK]; if (handler != null) + { handler(this, mea); + } } /// @@ -585,7 +596,9 @@ private void OnMouseDown(MouseEventArgs e) { MouseEventHandler handler = (MouseEventHandler)Events[EVENT_MOUSEDOWN]; if (handler != null) + { handler(this, e); + } } /// @@ -599,7 +612,9 @@ private void OnMouseMove(MouseEventArgs e) { MouseEventHandler handler = (MouseEventHandler)Events[EVENT_MOUSEMOVE]; if (handler != null) + { handler(this, e); + } } /// @@ -612,7 +627,9 @@ private void OnMouseUp(MouseEventArgs e) { MouseEventHandler handler = (MouseEventHandler)Events[EVENT_MOUSEUP]; if (handler != null) + { handler(this, e); + } } /// @@ -921,7 +938,9 @@ private void WndProc(ref Message msg) if (IntPtr.Zero == msg.LParam) { if (Command.DispatchID((int)msg.WParam & 0xFFFF)) + { return; + } } else { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PageSetupDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PageSetupDialog.cs index 3ed978e20ec..bb6f7126c9c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PageSetupDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PageSetupDialog.cs @@ -176,7 +176,10 @@ public Margins MinMargins set { if (value == null) + { value = new Margins(0, 0, 0, 0); + } + minMargins = value; } } @@ -269,22 +272,44 @@ private int GetFlags() flags |= NativeMethods.PSD_ENABLEPAGESETUPHOOK; if (!allowMargins) + { flags |= NativeMethods.PSD_DISABLEMARGINS; + } + if (!allowOrientation) + { flags |= NativeMethods.PSD_DISABLEORIENTATION; + } + if (!allowPaper) + { flags |= NativeMethods.PSD_DISABLEPAPER; + } + if (!allowPrinter || printerSettings == null) + { flags |= NativeMethods.PSD_DISABLEPRINTER; + } if (showHelp) + { flags |= NativeMethods.PSD_SHOWHELP; + } + if (!showNetwork) + { flags |= NativeMethods.PSD_NONETWORKBUTTON; + } + if (minMargins != null) + { flags |= NativeMethods.PSD_MINMARGINS; + } + if (pageSettings.Margins != null) + { flags |= NativeMethods.PSD_MARGINS; + } // return flags; @@ -362,7 +387,9 @@ protected override bool RunDialog(IntPtr hwndOwner) NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(HookProc); if (pageSettings == null) + { throw new ArgumentException(SR.PSDcantShowWithoutPage); + } NativeMethods.PAGESETUPDLG data = new NativeMethods.PAGESETUPDLG(); data.lStructSize = Marshal.SizeOf(data); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintDialog.cs index f313d853b86..1ba13eb406d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintDialog.cs @@ -128,9 +128,13 @@ public PrintDocument Document { printDocument = value; if (printDocument == null) + { settings = new PrinterSettings(); + } else + { settings = printDocument.PrinterSettings; + } } } @@ -139,9 +143,13 @@ private PageSettings PageSettings get { if (Document == null) + { return PrinterSettings.DefaultPageSettings; + } else + { return Document.DefaultPageSettings; + } } } @@ -393,9 +401,13 @@ private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.WndProc hookProcPtr try { if (PageSettings == null) + { data.hDevMode = PrinterSettings.GetHdevmode(); + } else + { data.hDevMode = PrinterSettings.GetHdevmode(PageSettings); + } data.hDevNames = PrinterSettings.GetHdevnames(); } @@ -413,12 +425,20 @@ private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.WndProc hookProcPtr { if (PrinterSettings.FromPage < PrinterSettings.MinimumPage || PrinterSettings.FromPage > PrinterSettings.MaximumPage) + { throw new ArgumentException(string.Format(SR.PDpageOutOfRange, "FromPage")); + } + if (PrinterSettings.ToPage < PrinterSettings.MinimumPage || PrinterSettings.ToPage > PrinterSettings.MaximumPage) + { throw new ArgumentException(string.Format(SR.PDpageOutOfRange, "ToPage")); + } + if (PrinterSettings.ToPage < PrinterSettings.FromPage) + { throw new ArgumentException(string.Format(SR.PDpageOutOfRange, "FromPage")); + } data.nFromPage = (short)PrinterSettings.FromPage; data.nToPage = (short)PrinterSettings.ToPage; @@ -427,7 +447,9 @@ private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.WndProc hookProcPtr } if (!UnsafeNativeMethods.PrintDlg(data)) + { return false; + } UpdatePrinterSettings(data.hDevMode, data.hDevNames, data.nCopies, data.Flags, settings, PageSettings); @@ -471,9 +493,13 @@ private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.PRINTDLGEX data) try { if (PageSettings == null) + { data.hDevMode = PrinterSettings.GetHdevmode(); + } else + { data.hDevMode = PrinterSettings.GetHdevmode(PageSettings); + } data.hDevNames = PrinterSettings.GetHdevnames(); } @@ -491,12 +517,20 @@ private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.PRINTDLGEX data) { if (PrinterSettings.FromPage < PrinterSettings.MinimumPage || PrinterSettings.FromPage > PrinterSettings.MaximumPage) + { throw new ArgumentException(string.Format(SR.PDpageOutOfRange, "FromPage")); + } + if (PrinterSettings.ToPage < PrinterSettings.MinimumPage || PrinterSettings.ToPage > PrinterSettings.MaximumPage) + { throw new ArgumentException(string.Format(SR.PDpageOutOfRange, "ToPage")); + } + if (PrinterSettings.ToPage < PrinterSettings.FromPage) + { throw new ArgumentException(string.Format(SR.PDpageOutOfRange, "FromPage")); + } unsafe { @@ -553,11 +587,19 @@ private bool ShowPrintDialog(IntPtr hwndOwner, NativeMethods.PRINTDLGEX data) finally { if (data.hDevMode != IntPtr.Zero) + { UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevMode)); + } + if (data.hDevNames != IntPtr.Zero) + { UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.hDevNames)); + } + if (data.pageRanges != IntPtr.Zero) + { UnsafeNativeMethods.GlobalFree(new HandleRef(data, data.pageRanges)); + } } } @@ -571,11 +613,15 @@ private static void UpdatePrinterSettings(IntPtr hDevMode, IntPtr hDevNames, sho settings.SetHdevnames(hDevNames); if (pageSettings != null) + { pageSettings.SetHdevmode(hDevMode); + } //Check for Copies == 1 since we might get the Right number of Copies from hdevMode.dmCopies... if (settings.Copies == 1) + { settings.Copies = copies; + } settings.PrintRange = (PrintRange)(flags & printRangeMask); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewControl.cs index f7b34bb0551..827433b8c01 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewControl.cs @@ -356,7 +356,10 @@ public double Zoom set { if (value <= 0) + { throw new ArgumentException(SR.PrintPreviewControlZoomNegative); + } + autoZoom = false; zoom = value; InvalidateLayout(); @@ -470,7 +473,9 @@ private void ComputePreview() int oldStart = StartPage; if (document == null) + { pageInfo = new PreviewPageInfo[0]; + } else { @@ -609,7 +614,9 @@ protected override void OnPaint(PaintEventArgs pevent) else { if (!layoutOk) + { ComputeLayout(); + } Size controlPhysicalSize = new Size(PixelsToPhysical(new Point(Size), screendpi)); @@ -800,9 +807,14 @@ private void SetPositionNoInvalidate(Point value) position.X = Math.Min(position.X, virtualSize.Width - Width); position.Y = Math.Min(position.Y, virtualSize.Height - Height); if (position.X < 0) + { position.X = 0; + } + if (position.Y < 0) + { position.Y = 0; + } Rectangle rect = ClientRectangle; NativeMethods.RECT scroll = NativeMethods.RECT.FromXYWH(rect.X, rect.Y, rect.Width, rect.Height); @@ -919,11 +931,17 @@ private void WmKeyDown(ref Message msg) break; case Keys.Home: if ((keyData & Keys.Modifiers) == Keys.Control) + { StartPage = 0; + } + break; case Keys.End: if ((keyData & Keys.Modifiers) == Keys.Control) + { StartPage = pageInfo.Length; + } + break; case Keys.Up: diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs index 5dc7c31c96d..2d98f08ca3e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs @@ -1583,7 +1583,9 @@ protected override void CreateHandle() // so the user has a chance to catch the exception instead of letting go to // the windows forms exception dialog. if (Document != null && !Document.PrinterSettings.IsValid) + { throw new InvalidPrinterException(Document.PrinterSettings); + } base.CreateHandle(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs index 7a47ee8ee23..a80c11586f3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs @@ -167,7 +167,10 @@ public ProgressBarStyle Style } style = value; if (IsHandleCreated) + { RecreateHandle(); + } + if (style == ProgressBarStyle.Marquee) { StartMarquee(); @@ -388,15 +391,21 @@ public int Maximum // Message: '%1' is not a valid value for '%0'. '%0' must be greater than %2. // Should this set a boundary for the top end too? if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(Maximum), value, 0)); + } if (minimum > value) + { minimum = value; + } maximum = value; if (this.value > maximum) + { this.value = maximum; + } if (IsHandleCreated) { @@ -432,14 +441,21 @@ public int Minimum // Message: '%1' is not a valid value for '%0'. '%0' must be greater than %2. // Should this set a boundary for the top end too? if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(Minimum), value, 0)); + } + if (maximum < value) + { maximum = value; + } minimum = value; if (this.value < minimum) + { this.value = minimum; + } if (IsHandleCreated) { @@ -551,7 +567,9 @@ public int Step { step = value; if (IsHandleCreated) + { SendMessage(NativeMethods.PBM_SETSTEP, step, 0); + } } } @@ -621,7 +639,10 @@ public int Value if (this.value != value) { if ((value < minimum) || (value > maximum)) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidBoundArgument, nameof(Value), value, "'minimum'", "'maximum'")); + } + this.value = value; UpdatePos(); } @@ -843,7 +864,9 @@ public override string ToString() private void UpdatePos() { if (IsHandleCreated) + { SendMessage(NativeMethods.PBM_SETPOS, value, 0); + } } //Note: ProgressBar doesn't work like other controls as far as setting ForeColor/ diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs index f4ee99a3f95..a8ff8db384f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs @@ -1941,7 +1941,9 @@ internal void AddRefTab(Type tabType, object component, PropertyTabScope type, b // so try to get the one off of the component's site. IDesignerHost host = null; if (component != null && component is IComponent && ((IComponent)component).Site != null) + { host = (IDesignerHost)((IComponent)component).Site.GetService(typeof(IDesignerHost)); + } try { @@ -2157,7 +2159,9 @@ private PropertyTab CreateTab(Type tabType, IDesignerHost host) Bitmap bitmap = tab.Bitmap; if (bitmap == null) + { throw new ArgumentException(string.Format(SR.PropertyGridNoBitmap, tab.GetType().FullName)); + } Size size = bitmap.Size; if (size.Width != 16 || size.Height != 16) @@ -2169,7 +2173,9 @@ private PropertyTab CreateTab(Type tabType, IDesignerHost host) string name = tab.TabName; if (name == null || name.Length == 0) + { throw new ArgumentException(string.Format(SR.PropertyGridTabName, tab.GetType().FullName)); + } // we're good to go! } @@ -2388,7 +2394,9 @@ protected override void Dispose(bool disposing) private void DividerDraw(int y) { if (y == -1) + { return; + } Rectangle rectangle = gridView.Bounds; rectangle.Y = y - cyDivider; @@ -2452,7 +2460,10 @@ private int DividerLimitHigh(SnappableControl target) { int high = gridView.Location.Y + MIN_GRID_HEIGHT; if (target == doccomment && hotcommands.Visible) + { high += hotcommands.Size.Height + 2; + } + return high; } @@ -3434,7 +3445,9 @@ protected override void OnMouseMove(MouseEventArgs me) protected override void OnMouseUp(MouseEventArgs me) { if (dividerMoveY == -1) + { return; + } Cursor = null; @@ -3505,7 +3518,9 @@ protected void OnComComponentNameChanged(ComponentRenameEventArgs e) { ComponentRenameEventHandler handler = (ComponentRenameEventHandler)Events[EventComComponentNameChanged]; if (handler != null) + { handler(this, e); + } } @@ -3576,7 +3591,9 @@ protected virtual void OnPropertySortChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[EventPropertySortChanged]; if (handler != null) + { handler(this, e); + } } // Seems safe - just fires an event @@ -3585,7 +3602,9 @@ protected virtual void OnPropertyTabChanged(PropertyTabChangedEventArgs e) { PropertyTabChangedEventHandler handler = (PropertyTabChangedEventHandler)Events[EventPropertyTabChanged]; if (handler != null) + { handler(this, e); + } } // Seems safe - just fires an event @@ -3594,7 +3613,9 @@ protected virtual void OnPropertyValueChanged(PropertyValueChangedEventArgs e) { PropertyValueChangedEventHandler handler = (PropertyValueChangedEventHandler)Events[EventPropertyValueChanged]; if (handler != null) + { handler(this, e); + } } internal void OnPropertyValueSet(GridItem changedItem, object oldValue) @@ -4321,7 +4342,9 @@ internal void ReleaseTab(Type tabType, object component) { int index = -1; if (components != null) + { index = Array.IndexOf(components, component); + } if (index >= 0) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs index f10f5330a59..5b1580dfec3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs @@ -1595,7 +1595,9 @@ public virtual object FindPropertyValue(string propertyName, Type propertyType) } if (parentPE != null) + { return parentPE.FindPropertyValue(propertyName, propertyType); + } return null; } @@ -1669,9 +1671,13 @@ internal bool GetMultipleLines(string valueString) { if (valueString.IndexOf('\n') > 0 || valueString.IndexOf('\r') > 0) + { return true; + } else + { return false; + } } /// /// Gets the owner of the current value. This is usually the value of the @@ -2059,17 +2065,25 @@ protected virtual bool GetFlagSet(int flag) protected Font GetFont(bool boldFont) { if (boldFont) + { return GridEntryHost.GetBoldFont(); + } else + { return GridEntryHost.GetBaseFont(); + } } protected IntPtr GetHfont(bool boldFont) { if (boldFont) + { return GridEntryHost.GetBoldHfont(); + } else + { return GridEntryHost.GetBaseHfont(); + } } /// @@ -2095,11 +2109,20 @@ public virtual object GetService(Type serviceType) internal virtual bool NonParentEquals(object obj) { if (obj == this) + { return true; + } + if (obj == null) + { return false; + } + if (!(obj is GridEntry)) + { return false; + } + GridEntry pe = (GridEntry)obj; return pe.PropertyLabel.Equals(PropertyLabel) && @@ -2278,13 +2301,19 @@ private void PaintOutlineWithExplorerTreeStyle(System.Drawing.Graphics g, Rectan // make sure we're in our bounds outline = Rectangle.Intersect(r, outline); if (outline.IsEmpty) + { return; + } VisualStyleElement element = null; if (fExpanded) + { element = VisualStyleElement.ExplorerTreeView.Glyph.Opened; + } else + { element = VisualStyleElement.ExplorerTreeView.Glyph.Closed; + } // Invert color if it is not overriden by developer. if (colorInversionNeededInHC) @@ -2314,7 +2343,9 @@ private void PaintOutlineWithClassicStyle(System.Drawing.Graphics g, Rectangle r // make sure we're in our bounds outline = Rectangle.Intersect(r, outline); if (outline.IsEmpty) + { return; + } // draw border area box Brush b = GetBackgroundBrush(g); @@ -2468,7 +2499,9 @@ public virtual void PaintValue(object val, System.Drawing.Graphics g, Rectangle // To check if text contains multiple lines // if (textWidth >= rect.Width || GetMultipleLines(strValue)) + { doToolTip = true; + } if (Rectangle.Intersect(rect, clipRect).IsEmpty) { @@ -2698,7 +2731,9 @@ protected virtual void OnRecreateChildren(GridEntryRecreateChildrenEventArgs e) { Delegate handler = GetEventHandler(EVENT_RECREATE_CHILDREN); if (handler != null) + { ((GridEntryRecreateChildrenEventHandler)handler)(this, e); + } } /// @@ -3018,7 +3053,10 @@ protected virtual void AddEventHandler(object key, Delegate handler) lock (this) { if (handler == null) + { return; + } + for (EventEntry e = eventList; e != null; e = e.next) { if (e.key == key) @@ -3035,7 +3073,9 @@ protected virtual void RaiseEvent(object key, EventArgs e) { Delegate handler = GetEventHandler(key); if (handler != null) + { ((EventHandler)handler)(this, e); + } } protected virtual Delegate GetEventHandler(object key) @@ -3046,7 +3086,9 @@ protected virtual Delegate GetEventHandler(object key) for (EventEntry e = eventList; e != null; e = e.next) { if (e.key == key) + { return e.handler; + } } return null; } @@ -3058,7 +3100,10 @@ protected virtual void RemoveEventHandler(object key, Delegate handler) lock (this) { if (handler == null) + { return; + } + for (EventEntry e = eventList, prev = null; e != null; prev = e, e = e.next) { if (e.key == key) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs index e3c221f8c7f..40fef802d5e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs @@ -47,9 +47,13 @@ public virtual bool AllowVisible { allowVisible = value; if (value && WouldBeVisible) + { Visible = true; + } else + { Visible = false; + } } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/ImmutablePropertyDescriptorGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/ImmutablePropertyDescriptorGridEntry.cs index 87bde55c4d7..5025b124899 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/ImmutablePropertyDescriptorGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/ImmutablePropertyDescriptorGridEntry.cs @@ -86,7 +86,9 @@ public override object PropertyValue e.ToString()), e); } else + { throw; // rethrow the same exception + } } if (newObject != null) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs index 9243672a998..6dba69ef63b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs @@ -542,7 +542,9 @@ bool ICollection.IsSynchronized public void CopyTo(Array array, int index) { if (items == null) + { return; + } Array.Copy(items, 0, array, index, items.Length); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiPropertyDescriptorGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiPropertyDescriptorGridEntry.cs index 1f2f7fb2e59..98e50a69248 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiPropertyDescriptorGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiPropertyDescriptorGridEntry.cs @@ -114,8 +114,9 @@ public override object PropertyValue RecreateChildren(); if (Expanded) + { GridEntryHost.Refresh(false); - + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs index e4b3aae7817..01bfbb58bc1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs @@ -111,7 +111,9 @@ public override string HelpKeyword object owner = GetValueOwner(); if (owner == null) + { return null; //null exception protection. + } HelpKeywordAttribute helpAttribute = (HelpKeywordAttribute)propertyInfo.Attributes[typeof(HelpKeywordAttribute)]; @@ -1360,7 +1362,9 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide { string message = except.Message; if (message == null || message.Length == 0) + { message = except.ToString(); + } RTLAwareMessageBox.Show(null, message, SR.PropertyGridExceptionInfo, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs index 7584fb03e9d..308f2c9d9c6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs @@ -797,7 +797,9 @@ public IServiceProvider ServiceProvider topHelpService = null; if (helpService != null && helpService is IDisposable) + { ((IDisposable)helpService).Dispose(); + } helpService = null; } @@ -1226,12 +1228,17 @@ protected virtual void CommonEditorUse(Control ctl, Rectangle rectTarget) { Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:CountPropsFromOutLine"); if (rgipes == null) + { return 0; + } + int cProps = rgipes.Count; for (int i = 0; i < rgipes.Count; i++) { if (((GridEntry)rgipes[i]).InternalExpanded) + { cProps += CountPropsFromOutline(((GridEntry)rgipes[i]).Children); + } } return cProps; } @@ -1289,11 +1296,20 @@ protected override void Dispose(bool disposing) { Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:Dispose"); if (scrollBar != null) + { scrollBar.Dispose(); + } + if (listBox != null) + { listBox.Dispose(); + } + if (dropDownHolder != null) + { dropDownHolder.Dispose(); + } + scrollBar = null; listBox = null; dropDownHolder = null; @@ -1306,7 +1322,9 @@ protected override void Dispose(bool disposing) topHelpService = null; if (helpService != null && helpService is IDisposable) + { ((IDisposable)helpService).Dispose(); + } helpService = null; @@ -1446,7 +1464,10 @@ private int GetIPELabelLength(System.Drawing.Graphics g, GridEntry gridEntry) private bool IsIPELabelLong(System.Drawing.Graphics g, GridEntry gridEntry) { if (gridEntry == null) + { return false; + } + int length = GetIPELabelLength(g, gridEntry); return (length > ptOurLocation.X + InternalLabelWidth); } @@ -1457,7 +1478,9 @@ protected virtual void DrawLabel(System.Drawing.Graphics g, int row, Rectangle r GridEntry gridEntry = GetGridEntryFromRow(row); if (gridEntry == null || rect.IsEmpty) + { return; + } Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Drawing label for property " + gridEntry.PropertyLabel); @@ -1503,7 +1526,9 @@ protected virtual void DrawValueEntry(System.Drawing.Graphics g, int row, ref Re { GridEntry gridEntry = GetGridEntryFromRow(row); if (gridEntry == null) + { return; + } Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Drawing value for property " + gridEntry.PropertyLabel); @@ -1570,7 +1595,9 @@ private void F4Selection(bool popupModalDialog) { GridEntry gridEntry = GetGridEntryFromRow(selectedRow); if (gridEntry == null) + { return; + } // if we are in an errorState, just put the focus back on the Edit if (errorState != ERROR_NONE && Edit.Visible) @@ -1613,7 +1640,9 @@ public void DoubleClickRow(int row, bool toggleExpand, int type) Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:DoubleClickRow"); GridEntry gridEntry = GetGridEntryFromRow(row); if (gridEntry == null) + { return; + } Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Property " + gridEntry.PropertyLabel + " double clicked"); @@ -2062,7 +2091,9 @@ public void FilterKeyPress(char keyChar) GridEntry gridEntry = GetGridEntryFromRow(selectedRow); if (gridEntry == null) + { return; + } Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:FilterKeyPress()"); @@ -2072,7 +2103,10 @@ public void FilterKeyPress(char keyChar) private /*protected virtual*/ GridEntry FindEquivalentGridEntry(GridEntryCollection ipeHier) { if (ipeHier == null || ipeHier.Count == 0) + { return null; + } + GridEntryCollection rgipes = GetAllGridEntries(); if (rgipes == null || rgipes.Count == 0) @@ -2136,14 +2170,23 @@ public void FilterKeyPress(char keyChar) protected virtual Point FindPosition(int x, int y) { if (RowHeight == -1) + { return InvalidPosition; + } + Size size = GetOurSize(); if (x < 0 || x > size.Width + ptOurLocation.X) + { return InvalidPosition; + } + Point pt = new Point(ROWLABEL, 0); if (x > InternalLabelWidth + ptOurLocation.X) + { pt.X = ROWVALUE; + } + pt.Y = (y - ptOurLocation.Y) / (1 + RowHeight); return pt; } @@ -2321,7 +2364,9 @@ private GridEntryCollection GetGridEntryHierarchy(GridEntry gridEntry) if (rgipesAll != null) { if (offset >= 0 && offset < rgipesAll.Count) + { return rgipesAll.GetEntry(offset); + } } return null; } @@ -2331,7 +2376,9 @@ private GridEntryCollection GetGridEntryHierarchy(GridEntry gridEntry) { Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:GetGridEntriesFromOutline"); if (rgipe == null || rgipe.Count == 0) + { return cCur; + } cCur--; // want to account for each entry as we find it. @@ -2339,7 +2386,9 @@ private GridEntryCollection GetGridEntryHierarchy(GridEntry gridEntry) { cCur++; if (cCur >= cTarget + rgipeTarget.Length) + { break; + } GridEntry ipeCur = rgipe.GetEntry(cLocal); @@ -2347,7 +2396,9 @@ private GridEntryCollection GetGridEntryHierarchy(GridEntry gridEntry) if (cCur >= cTarget) + { rgipeTarget[cCur - cTarget] = ipeCur; + } if (ipeCur.InternalExpanded) { @@ -2423,7 +2474,9 @@ public Rectangle GetRectangle(int row, int flRow) { GridEntryCollection rgipesAll = GetAllGridEntries(); if (gridEntry == null || rgipesAll == null) + { return -1; + } int bestMatch = -1; @@ -2474,9 +2527,13 @@ public virtual string GetTestingInfo(int entry) GridEntry gridEntry = (entry < 0) ? GetGridEntryFromRow(selectedRow) : GetGridEntryFromOffset(entry); if (gridEntry == null) + { return ""; + } else + { return gridEntry.GetTestingInfo(); + } } public Color GetTextColor() @@ -2888,7 +2945,9 @@ private void OnListDrawItem(object sender, DrawItemEventArgs die) { ShowFormatExceptionMessage(gridEntry.PropertyLabel, text, ex); if (DropDownListBox.IsHandleCreated) + { DropDownListBox.Visible = false; + } } } @@ -2956,7 +3015,9 @@ private void OnEditChange(object sender, EventArgs e) { GridEntry gridEntry = GetGridEntryFromRow(selectedRow); if (gridEntry != null && (gridEntry.Flags & GridEntry.FLAG_IMMEDIATELY_EDITABLE) != 0) + { Commit(); + } } } @@ -3042,13 +3103,19 @@ private bool ProcessEnumUpAndDown(GridEntry gridEntry, Keys keyCode, bool closeD if (keyCode == Keys.Up) { if (i == 0) + { return true; + } + valueNew = rgvalues[i - 1]; } else { if (i == rgvalues.Length - 1) + { return true; + } + valueNew = rgvalues[i + 1]; } @@ -3095,7 +3162,9 @@ private void OnEditKeyPress(object sender, KeyPressEventArgs ke) Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnEditKeyPress"); GridEntry gridEntry = GetGridEntryFromRow(selectedRow); if (gridEntry == null) + { return; + } if (!gridEntry.IsTextEditable) { @@ -3129,7 +3198,9 @@ private void OnEditLostFocus(object sender, EventArgs e) } } if (found) + { return; + } } if (FocusInside) @@ -3199,9 +3270,14 @@ private bool OnF4(Control sender) return false; } if (sender == this || sender == ownerGrid) + { F4Selection(true); + } else + { UnfocusSelection(); + } + return true; } @@ -3289,7 +3365,9 @@ private void OnKeyDown(object sender, KeyEventArgs ke) GridEntry gridEntry = GetGridEntryFromRow(selectedRow); if (gridEntry == null) + { return; + } ke.Handled = true; bool fControl = ke.Control; @@ -3349,7 +3427,9 @@ private void OnKeyDown(object sender, KeyEventArgs ke) return; } if (gridEntry.InternalExpanded) + { SetExpand(gridEntry, false); + } else { // Handle non-expand/collapse case of left & right as up & down @@ -3371,7 +3451,9 @@ private void OnKeyDown(object sender, KeyEventArgs ke) SelectGridEntry(rgipes2.GetEntry(0), true); } else + { SetExpand(gridEntry, true); + } } else { @@ -3576,8 +3658,11 @@ protected override void OnKeyPress(KeyPressEventArgs ke) bool fShift = false; //ke.getShift(); bool fBoth = fControl && fShift; if (!fBoth && WillFilterKeyPress(ke.KeyChar)) + { // find next property with letter typed. FilterKeyPress(ke.KeyChar); + } + SetFlag(FlagIsSpecialKey, false); } @@ -3643,7 +3728,9 @@ protected override void OnMouseDown(MouseEventArgs me) protected override void OnMouseLeave(EventArgs e) { if (!GetFlag(FlagIsSplitterMove)) + { Cursor = Cursors.Default; // Cursor = null;; + } base.OnMouseLeave(e); } @@ -4657,8 +4744,12 @@ protected virtual void RecalculateProps() GridEntryCollection rgipes = gridEntry.Children; if (rgipes != null) + { for (int i = 0; i < rgipes.Count; i++) + { RecursivelyExpand(rgipes.GetEntry(i), false, expand, maxExpands); + } + } if (fInit) { @@ -4829,7 +4920,9 @@ public virtual void Reset() Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:Reset"); GridEntry gridEntry = GetGridEntryFromRow(selectedRow); if (gridEntry == null) + { return; + } gridEntry.ResetPropertyValue(); SelectRow(selectedRow); @@ -4948,7 +5041,10 @@ private void SelectEdit(bool caretAtEnd) { if (gridEntry == null) + { return; + } + Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:SelectGridEntry(" + gridEntry.PropertyLabel + ")"); int row = GetRowFromGridEntry(gridEntry); @@ -5053,7 +5149,9 @@ private void SelectRow(int row) // leave current selection. if (gridEntry == null) + { return; + } bool newRow = false; int oldSel = selectedRow; @@ -5064,7 +5162,9 @@ private void SelectRow(int row) } if (!newRow) + { CloseDropDown(); + } Rectangle rect = GetRectangle(row, ROWVALUE); string s = gridEntry.GetPropertyTextValue(); @@ -5727,7 +5827,9 @@ private void ShowFormatExceptionMessage(string propName, object value, Exception Interop.WindowMessages.WM_MOUSEFIRST, Interop.WindowMessages.WM_MOUSELAST, NativeMethods.PM_REMOVE)) + { ; + } // These things are just plain useless. // @@ -5813,7 +5915,9 @@ internal void ShowInvalidMessage(string propName, object value, Exception ex) Interop.WindowMessages.WM_MOUSEFIRST, Interop.WindowMessages.WM_MOUSELAST, NativeMethods.PM_REMOVE)) + { ; + } // These things are just plain useless. // @@ -5877,7 +5981,9 @@ private void TabSelection() { GridEntry gridEntry = GetGridEntryFromRow(selectedRow); if (gridEntry == null) + { return; + } if (Edit.Visible) { @@ -6004,7 +6110,9 @@ private bool UnfocusSelection() Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:UnfocusSelection()"); GridEntry gridEntry = GetGridEntryFromRow(selectedRow); if (gridEntry == null) + { return true; + } bool commit = Commit(); @@ -6199,7 +6307,10 @@ protected override void WndProc(ref Message m) case Interop.WindowMessages.WM_NOTIFY: if (WmNotify(ref m)) + { return; + } + break; case AutomationMessages.PGM_GETSELECTEDROW: m.Result = (IntPtr)GetRowFromGridEntry(selectedGridEntry); @@ -7908,7 +8019,10 @@ protected override void WndProc(ref Message m) case Interop.WindowMessages.WM_NOTIFY: if (WmNotify(ref m)) + { return; + } + break; } base.WndProc(ref m); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs index 25465b7849d..1cf36e41c64 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs @@ -232,7 +232,10 @@ public bool Checked isChecked = value; if (IsHandleCreated) + { SendMessage(NativeMethods.BM_SETCHECK, value ? 1 : 0, 0); + } + Invalidate(); Update(); PerformAutoUpdates(false); @@ -461,7 +464,9 @@ protected virtual void OnCheckedChanged(EventArgs e) AccessibilityNotifyClients(AccessibleEvents.NameChange, -1); EventHandler handler = (EventHandler)Events[EVENT_CHECKEDCHANGED]; if (handler != null) + { handler(this, e); + } } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RelatedCurrencyManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RelatedCurrencyManager.cs index 9ba44e8302a..af9008d1699 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RelatedCurrencyManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RelatedCurrencyManager.cs @@ -204,7 +204,10 @@ private void ParentManager_CurrentItemChanged(object sender, EventArgs e) listposition = (Count > 0 ? 0 : -1); } if (oldlistposition != listposition) + { OnPositionChanged(EventArgs.Empty); + } + OnCurrentChanged(EventArgs.Empty); OnCurrentItemChanged(EventArgs.Empty); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RelatedPropertyManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RelatedPropertyManager.cs index e9d65219a96..cdf4754855a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RelatedPropertyManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RelatedPropertyManager.cs @@ -35,7 +35,9 @@ private void Bind(BindingManagerBase parentManager, string dataField) this.dataField = dataField; fieldInfo = parentManager.GetItemProperties().Find(dataField, true); if (fieldInfo == null) + { throw new ArgumentException(string.Format(SR.RelatedListManagerChild, dataField)); + } // this.finalType = fieldInfo.PropertyType; parentManager.CurrentItemChanged += new EventHandler(ParentManager_CurrentItemChanged); Refresh(); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs index 175a46d59b2..7c93aca16db 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs @@ -302,7 +302,9 @@ public int BulletIndent // Call to update the control only if the bullet is set. if (IsHandleCreated && SelectionBullet) + { SelectionBullet = true; + } } } @@ -391,14 +393,18 @@ protected override CreateParams CreateParams // RichEd infers word wrap from the absence of horizontal scroll bars cp.Style |= NativeMethods.WS_HSCROLL; if (((int)ScrollBars & RichTextBoxConstants.RTB_FORCE) != 0) + { cp.Style |= RichTextBoxConstants.ES_DISABLENOSCROLL; + } } if (((int)ScrollBars & RichTextBoxConstants.RTB_VERT) != 0) { cp.Style |= NativeMethods.WS_VSCROLL; if (((int)ScrollBars & RichTextBoxConstants.RTB_FORCE) != 0) + { cp.Style |= RichTextBoxConstants.ES_DISABLENOSCROLL; + } } } @@ -671,7 +677,10 @@ public string RedoActionName get { if (!CanRedo) + { return ""; + } + int n; n = unchecked((int)(long)SendMessage(Interop.EditMessages.EM_GETREDONAME, 0, 0)); return GetEditorActionName(n); @@ -717,7 +726,10 @@ public int RightMargin if (rightMargin != value) { if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(RightMargin), value, 0)); + } + rightMargin = value; if (value == 0) @@ -775,10 +787,14 @@ public string Rtf set { if (value == null) + { value = string.Empty; + } if (value.Equals(Rtf)) + { return; + } ForceHandleCreate(); textRtf = value; @@ -1015,7 +1031,9 @@ public int SelectionCharOffset set { if (value > 2000 || value < -2000) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidBoundArgument, nameof(SelectionCharOffset), value, -2000, 2000)); + } ForceHandleCreate(); NativeMethods.CHARFORMATA cf = new NativeMethods.CHARFORMATA @@ -1053,7 +1071,9 @@ public Color SelectionColor NativeMethods.CHARFORMATA cf = GetCharFormat(true); // if the effects member contains valid info if ((cf.dwMask & RichTextBoxConstants.CFM_COLOR) != 0) + { selColor = ColorTranslator.FromOle(cf.crTextColor); + } return selColor; } @@ -1178,7 +1198,9 @@ public int SelectionHangingIndent // check if alignment has been set yet if ((RichTextBoxConstants.PFM_OFFSET & pf.dwMask) != 0) + { selHangingIndent = pf.dxOffset; + } return Twip2Pixel(IntPtr.Zero, selHangingIndent, true); } @@ -1225,7 +1247,9 @@ public int SelectionIndent // check if alignment has been set yet if ((RichTextBoxConstants.PFM_STARTINDENT & pf.dwMask) != 0) + { selIndent = pf.dxStartIndent; + } return Twip2Pixel(IntPtr.Zero, selIndent, true); } @@ -1324,7 +1348,10 @@ public string SelectedRtf { ForceHandleCreate(); if (value == null) + { value = string.Empty; + } + StreamIn(value, RichTextBoxConstants.SFF_SELECTION | RichTextBoxConstants.SF_RTF); } } @@ -1358,14 +1385,18 @@ public int SelectionRightIndent // check if alignment has been set yet if ((RichTextBoxConstants.PFM_RIGHTINDENT & pf.dwMask) != 0) + { selRightIndent = pf.dxRightIndent; + } return Twip2Pixel(IntPtr.Zero, selRightIndent, true); } set { if (value < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidLowBoundArgumentEx, nameof(SelectionRightIndent), value, 0)); + } ForceHandleCreate(); NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT @@ -1407,7 +1438,9 @@ public int[] SelectionTabs { selTabs = new int[pf.cTabCount]; for (int x = 0; x < pf.cTabCount; x++) + { selTabs[x] = Twip2Pixel(IntPtr.Zero, pf.rgxTabs[x], true); + } } return selTabs; @@ -1416,7 +1449,9 @@ public int[] SelectionTabs { // Verify the argument, and throw an error if is bad if (value != null && value.Length > RichTextBoxConstants.MAX_TAB_STOPS) + { throw new ArgumentOutOfRangeException(nameof(SelectionTabs), SR.SelTabCountRange); + } ForceHandleCreate(); NativeMethods.PARAFORMAT pf = new NativeMethods.PARAFORMAT @@ -1431,7 +1466,9 @@ public int[] SelectionTabs pf.cTabCount = (short)((value == null) ? 0 : value.Length); pf.dwMask = RichTextBoxConstants.PFM_TABSTOPS; for (int x = 0; x < pf.cTabCount; x++) + { pf.rgxTabs[x] = Pixel2Twip(IntPtr.Zero, value[x], true); + } // set the format for our current paragraph or selection UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_SETPARAFORMAT, 0, pf); @@ -1633,7 +1670,10 @@ public string UndoActionName get { if (!CanUndo) + { return ""; + } + int n; n = unchecked((int)(long)SendMessage(Interop.EditMessages.EM_GETUNDONAME, 0, 0)); return GetEditorActionName(n); @@ -1693,7 +1733,9 @@ public float ZoomFactor return zoomMultiplier; } else + { return zoomMultiplier; + } } set @@ -1945,7 +1987,9 @@ private unsafe int EditStreamProc(IntPtr dwCookie, IntPtr buf, int cb, out int t Marshal.Copy(bytes, 0, buf, transferred); // set up number of bytes transferred if (transferred < 0) + { transferred = 0; + } } else { @@ -2006,9 +2050,14 @@ public int Find(string str, int start, int end, RichTextBoxFinds options) int textLen = TextLength; if (start < 0 || start > textLen) + { throw new ArgumentOutOfRangeException(nameof(start), start, string.Format(SR.InvalidBoundArgument, nameof(start), start, 0, textLen)); + } + if (end < -1) + { throw new ArgumentOutOfRangeException(nameof(end), end, string.Format(SR.RichTextFindEndInvalid, end)); + } bool selectWord = true; NativeMethods.FINDTEXT ft = new NativeMethods.FINDTEXT @@ -2062,11 +2111,20 @@ public int Find(string str, int start, int end, RichTextBoxFinds options) // set up the options for the search int findOptions = 0; if ((options & RichTextBoxFinds.WholeWord) == RichTextBoxFinds.WholeWord) + { findOptions |= RichTextBoxConstants.FR_WHOLEWORD; + } + if ((options & RichTextBoxFinds.MatchCase) == RichTextBoxFinds.MatchCase) + { findOptions |= RichTextBoxConstants.FR_MATCHCASE; + } + if ((options & RichTextBoxFinds.NoHighlight) == RichTextBoxFinds.NoHighlight) + { selectWord = false; + } + if ((options & RichTextBoxFinds.Reverse) != RichTextBoxFinds.Reverse) { // The default for RichEdit 2.0 is to search in reverse @@ -2155,15 +2213,25 @@ public int Find(char[] characterSet, int start, int end) int textLength = TextLength; if (characterSet == null) + { throw new ArgumentNullException(nameof(characterSet)); + } + if (start < 0 || start > textLength) + { throw new ArgumentOutOfRangeException(nameof(start), start, string.Format(SR.InvalidBoundArgument, nameof(start), start, 0, textLength)); + } + if (end < start && end != -1) + { throw new ArgumentOutOfRangeException(nameof(end), end, string.Format(SR.InvalidLowBoundArgumentEx, nameof(end), end, nameof(start))); + } // Don't do anything if we get nothing to look for if (characterSet.Length == 0) + { return -1; + } int textLen = Interop.User32.GetWindowTextLengthW(new HandleRef(this, Handle)); if (start == end) @@ -2194,7 +2262,9 @@ public int Find(char[] characterSet, int start, int end) txrg.lpstrText = charBuffer.AllocCoTaskMem(); if (txrg.lpstrText == IntPtr.Zero) + { throw new OutOfMemoryException(); + } try { @@ -2223,11 +2293,15 @@ public int Find(char[] characterSet, int start, int end) // We need to keep our request within the // lower bound of zero if (txrg.chrg.cpMin < 0) + { txrg.chrg.cpMin = 0; + } } if (end != -1) + { txrg.chrg.cpMax = Math.Min(txrg.chrg.cpMax, end); + } // go get the text in this range, if we didn't get any text then punt int len; @@ -2285,7 +2359,9 @@ public int Find(char[] characterSet, int start, int end) { // release the resources we got for our GETTEXTRANGE operation. if (txrg.lpstrText != IntPtr.Zero) + { Marshal.FreeCoTaskMem(txrg.lpstrText); + } } int index = (forward) ? chrg.cpMax : chrg.cpMin; @@ -2344,9 +2420,13 @@ private RichTextBoxSelectionAttribute GetCharFormat(int mask, int effect) NativeMethods.CHARFORMATA cf = GetCharFormat(true); // if the effects member contains valid info if ((cf.dwMask & mask) != 0) + { // if the text has the desired effect if ((cf.dwEffects & effect) != 0) + { charFormat = RichTextBoxSelectionAttribute.All; + } + } } return charFormat; @@ -2381,13 +2461,24 @@ Font GetCharFormatFont(bool selectionOnly) FontStyle style = FontStyle.Regular; if ((cf.dwMask & RichTextBoxConstants.CFM_BOLD) != 0 && (cf.dwEffects & RichTextBoxConstants.CFE_BOLD) != 0) + { style |= FontStyle.Bold; + } + if ((cf.dwMask & RichTextBoxConstants.CFM_ITALIC) != 0 && (cf.dwEffects & RichTextBoxConstants.CFE_ITALIC) != 0) + { style |= FontStyle.Italic; + } + if ((cf.dwMask & RichTextBoxConstants.CFM_STRIKEOUT) != 0 && (cf.dwEffects & RichTextBoxConstants.CFE_STRIKEOUT) != 0) + { style |= FontStyle.Strikeout; + } + if ((cf.dwMask & RichTextBoxConstants.CFM_UNDERLINE) != 0 && (cf.dwEffects & RichTextBoxConstants.CFE_UNDERLINE) != 0) + { style |= FontStyle.Underline; + } try { @@ -2428,7 +2519,9 @@ private bool GetCharInCharSet(char c, char[] charSet, bool negate) // Loop through the given character set and compare for a match for (int i = 0; !match && i < charSetLen; i++) + { match = c == charSet[i]; + } return negate ? !match : match; } @@ -2604,7 +2697,9 @@ protected virtual void OnContentsResized(ContentsResizedEventArgs e) { ContentsResizedEventHandler handler = (ContentsResizedEventHandler)Events[EVENT_REQUESTRESIZE]; if (handler != null) + { handler(this, e); + } } protected override void OnHandleCreated(EventArgs e) @@ -2712,7 +2807,9 @@ protected override void OnHandleDestroyed(EventArgs e) { textRtf = Rtf; if (textRtf.Length == 0) + { textRtf = null; + } } oleCallback = null; @@ -2727,7 +2824,9 @@ protected virtual void OnHScroll(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_HSCROLL]; if (handler != null) + { handler(this, e); + } } /// @@ -2738,7 +2837,9 @@ protected virtual void OnLinkClicked(LinkClickedEventArgs e) { LinkClickedEventHandler handler = (LinkClickedEventHandler)Events[EVENT_LINKACTIVATE]; if (handler != null) + { handler(this, e); + } } @@ -2749,7 +2850,9 @@ protected virtual void OnImeChange(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_IMECHANGE]; if (handler != null) + { handler(this, e); + } } /// @@ -2761,7 +2864,9 @@ protected virtual void OnProtected(EventArgs e) ProtectedError = true; EventHandler handler = (EventHandler)Events[EVENT_PROTECTED]; if (handler != null) + { handler(this, e); + } } /// @@ -2772,7 +2877,9 @@ protected virtual void OnSelectionChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_SELCHANGE]; if (handler != null) + { handler(this, e); + } } /// @@ -2783,7 +2890,9 @@ protected virtual void OnVScroll(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_VSCROLL]; if (handler != null) + { handler(this, e); + } } /// @@ -2981,19 +3090,33 @@ private void SetCharFormatFont(bool selectionOnly, Font value) int dwEffects = 0; if (value.Bold) + { dwEffects |= RichTextBoxConstants.CFE_BOLD; + } + if (value.Italic) + { dwEffects |= RichTextBoxConstants.CFE_ITALIC; + } + if (value.Strikeout) + { dwEffects |= RichTextBoxConstants.CFE_STRIKEOUT; + } + if (value.Underline) + { dwEffects |= RichTextBoxConstants.CFE_UNDERLINE; + } bytesFaceName = Encoding.Unicode.GetBytes(logfont.lfFaceName); NativeMethods.CHARFORMATW cfW = new NativeMethods.CHARFORMATW(); for (int i = 0; i < bytesFaceName.Length; i++) + { cfW.szFaceName[i] = bytesFaceName[i]; + } + cfW.dwMask = dwMask; cfW.dwEffects = dwEffects; cfW.yHeight = (int)(value.SizeInPoints * 20); @@ -3014,11 +3137,16 @@ private static void SetupLogPixels(IntPtr hDC) release = true; } if (hDC == IntPtr.Zero) + { return; + } + logPixelsX = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, hDC), NativeMethods.LOGPIXELSX); logPixelsY = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, hDC), NativeMethods.LOGPIXELSY); if (release) + { UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, hDC)); + } } private static int Pixel2Twip(IntPtr hDC, int v, bool xDirection) @@ -3105,7 +3233,9 @@ private void StreamIn(Stream data, int flags) editStream.Read(bytes, (int)streamStart, SZ_RTF_TAG.Length); string str = Encoding.Default.GetString(bytes); if (!SZ_RTF_TAG.Equals(str)) + { throw new ArgumentException(SR.InvalidFileFormat); + } // put us back at the start of the file editStream.Position = streamStart; @@ -3161,10 +3291,14 @@ private void StreamIn(Stream data, int flags) // text then return protect event was fired so no // exception is required for the the error if (GetProtectedError()) + { return; + } if (es.dwError != 0) + { throw new InvalidOperationException(SR.LoadTextError); + } // set the modify tag on the control SendMessage(Interop.EditMessages.EM_SETMODIFY, -1, 0); @@ -3268,7 +3402,9 @@ private void StreamOut(Stream data, int flags, bool includeCrLfs) // check to make sure things went well if (es.dwError != 0) + { throw new InvalidOperationException(SR.SaveTextError); + } } finally { @@ -3476,14 +3612,18 @@ private string CharRangeToString(NativeMethods.CHARRANGE c) UnsafeNativeMethods.CharBuffer charBuffer = UnsafeNativeMethods.CharBuffer.CreateBuffer(characters); IntPtr unmanagedBuffer = charBuffer.AllocCoTaskMem(); if (unmanagedBuffer == IntPtr.Zero) + { throw new OutOfMemoryException(SR.OutOfMemory); + } txrg.lpstrText = unmanagedBuffer; int len = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_GETTEXTRANGE, 0, txrg); Debug.Assert(len != 0, "CHARRANGE from RichTextBox was bad! - impossible?"); charBuffer.PutCoTaskMem(unmanagedBuffer); if (txrg.lpstrText != IntPtr.Zero) + { Marshal.FreeCoTaskMem(unmanagedBuffer); + } string result = charBuffer.GetString(); return result; @@ -3625,7 +3765,10 @@ internal void WmReflectNotify(ref Message m) // Don't allow STREAMIN to replace protected selection // if ((unchecked((int)(long)enprotected.wParam) & RichTextBoxConstants.SFF_SELECTION) != 0) + { break; + } + m.Result = IntPtr.Zero; return; @@ -4087,8 +4230,9 @@ public int GetDragDropEffect(bool fDrag, int grfKeyState, ref int pdwEffect) lastEffect = (DragDropEffects.All | DragDropEffects.None); } else + { lastEffect = DragDropEffects.None; - + } } else { @@ -4140,7 +4284,9 @@ public int GetContextMenu(short seltype, IntPtr lpoleobj, NativeMethods.CHARRANG Debug.WriteLineIf(RichTextDbg.TraceVerbose, "IRichEditOleCallback::GetContextMenu"); ContextMenu cm = owner.ContextMenu; if (cm == null || owner.ShortcutsEnabled == false) + { hmenu = IntPtr.Zero; + } else { cm.sourceControl = owner; @@ -4168,9 +4314,13 @@ public int GetContextMenu(short seltype, IntPtr lpoleobj, NativeMethods.CHARRANG menu.handle = IntPtr.Zero; menu.created = false; if (menu == cm) + { break; + } else + { menu = ((MenuItem)menu).Parent; + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs index f6136680aef..fea147091eb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs @@ -831,7 +831,9 @@ protected override void OnPaddingChanged(EventArgs e) // the padding has changed. EventHandler handler = (EventHandler)Events[Control.EventPaddingChanged]; if (handler != null) + { handler(this, e); + } } @@ -1094,7 +1096,9 @@ protected virtual void OnScroll(ScrollEventArgs se) { ScrollEventHandler handler = (ScrollEventHandler)Events[EVENT_SCROLL]; if (handler != null) + { handler(this, se); + } } private void ResetAutoScrollMargin() @@ -1232,9 +1236,14 @@ private bool SetDisplayRectangleSize(int width, int height) int minY = ClientRectangle.Height - height; if (minX > 0) + { minX = 0; + } + if (minY > 0) + { minY = 0; + } int x = displayRect.X; int y = displayRect.Y; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SendKeys.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SendKeys.cs index ea5fadfaf9d..ae638bc3326 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SendKeys.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SendKeys.cs @@ -195,7 +195,10 @@ private static bool AddSimpleKey(char character, int repeat, IntPtr hwnd, int[] } if (cGrp != 0) + { fStartNewChar = true; + } + return fStartNewChar; } @@ -249,7 +252,9 @@ private static void InstallHook() new HandleRef(null, UnsafeNativeMethods.GetModuleHandle(null)), 0); if (hhook == IntPtr.Zero) + { throw new System.Security.SecurityException(SR.SendKeysHookFailed); + } } } @@ -294,12 +299,18 @@ private static void LoadSendMethodFromConfig() string value = System.Configuration.ConfigurationManager.AppSettings.Get("SendKeys"); if (string.IsNullOrEmpty(value)) + { return; + } if (value.Equals("JournalHook", StringComparison.OrdinalIgnoreCase)) + { sendMethod = SendMethodTypes.JournalHook; + } else if (value.Equals("SendInput", StringComparison.OrdinalIgnoreCase)) + { sendMethod = SendMethodTypes.SendInput; + } } catch { } // ignore any exceptions to keep existing SendKeys behavior } @@ -358,8 +369,12 @@ private static void ClearKeyboardState() private static int MatchKeyword(string keyword) { for (int i = 0; i < keywords.Length; i++) + { if (string.Equals(keywords[i].keyword, keyword, StringComparison.OrdinalIgnoreCase)) + { return keywords[i].vk; + } + } return -1; } @@ -535,7 +550,9 @@ private static void ParseKeys(string keys, IntPtr hwnd) case '+': if (haveKeys[HAVESHIFT] != 0) + { throw new ArgumentException(string.Format(SR.InvalidSendKeysString, keys)); + } AddEvent(new SKEvent(Interop.WindowMessages.WM_KEYDOWN, (int)Keys.ShiftKey, fStartNewChar, hwnd)); fStartNewChar = false; @@ -544,7 +561,9 @@ private static void ParseKeys(string keys, IntPtr hwnd) case '^': if (haveKeys[HAVECTRL] != 0) + { throw new ArgumentException(string.Format(SR.InvalidSendKeysString, keys)); + } AddEvent(new SKEvent(Interop.WindowMessages.WM_KEYDOWN, (int)Keys.ControlKey, fStartNewChar, hwnd)); fStartNewChar = false; @@ -553,7 +572,9 @@ private static void ParseKeys(string keys, IntPtr hwnd) case '%': if (haveKeys[HAVEALT] != 0) + { throw new ArgumentException(string.Format(SR.InvalidSendKeysString, keys)); + } AddEvent(new SKEvent((haveKeys[HAVECTRL] != 0) ? Interop.WindowMessages.WM_KEYDOWN : Interop.WindowMessages.WM_SYSKEYDOWN, (int)Keys.Menu, fStartNewChar, hwnd)); @@ -568,23 +589,40 @@ private static void ParseKeys(string keys, IntPtr hwnd) // cGrp++; if (cGrp > 3) + { throw new ArgumentException(SR.SendKeysNestingError); + } if (haveKeys[HAVESHIFT] == UNKNOWN_GROUPING) + { haveKeys[HAVESHIFT] = cGrp; + } + if (haveKeys[HAVECTRL] == UNKNOWN_GROUPING) + { haveKeys[HAVECTRL] = cGrp; + } + if (haveKeys[HAVEALT] == UNKNOWN_GROUPING) + { haveKeys[HAVEALT] = cGrp; + } + break; case ')': if (cGrp < 1) + { throw new ArgumentException(string.Format(SR.InvalidSendKeysString, keys)); + } + CancelMods(haveKeys, cGrp, hwnd); cGrp--; if (cGrp == 0) + { fStartNewChar = true; + } + break; case '~': @@ -604,7 +642,9 @@ private static void ParseKeys(string keys, IntPtr hwnd) } if (cGrp != 0) + { throw new ArgumentException(SR.SendKeysGroupDelimError); + } CancelMods(haveKeys, UNKNOWN_GROUPING, hwnd); } @@ -915,7 +955,9 @@ private static void Send(string keys, Control control, bool wait) { if (keys == null || keys.Length == 0) + { return; + } // If we're not going to wait, make sure there is a pump. // @@ -939,7 +981,9 @@ private static void Send(string keys, Control control, bool wait) // if there weren't any events posted as a result, we're done! // if (events == null) + { return; + } LoadSendMethodFromConfig(); @@ -1161,7 +1205,10 @@ public virtual IntPtr Callback(int code, IntPtr wparam, IntPtr lparam) default: if (code < 0) + { UnsafeNativeMethods.CallNextHookEx(new HandleRef(null, SendKeys.hhook), code, wparam, lparam); + } + break; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs index 100f17cec0d..ade348ea61b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs @@ -609,7 +609,9 @@ private Cursor OverrideCursor 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(Interop.WindowMessages.WM_SETCURSOR, Handle, NativeMethods.HTCLIENT); + } } } } @@ -1470,8 +1472,9 @@ public void OnSplitterMoving(SplitterCancelEventArgs e) { SplitterCancelEventHandler handler = (SplitterCancelEventHandler)Events[EVENT_MOVING]; if (handler != null) + { handler(this, e); - + } } /// @@ -1483,7 +1486,9 @@ public void OnSplitterMoved(SplitterEventArgs e) { SplitterEventHandler handler = (SplitterEventHandler)Events[EVENT_MOVED]; if (handler != null) + { handler(this, e); + } } //////////////////////////////////////////////////////////////////////////////////////////////// @@ -2084,7 +2089,10 @@ private bool SelectNextControlInContainer(Control ctl, bool forward, bool tabSto bool nested, bool wrap) { if (!Contains(ctl) || !nested && ctl.ParentInternal != this) + { ctl = null; + } + Control start = ctl; SplitterPanel firstPanel = null; do @@ -2181,7 +2189,10 @@ private bool SelectNextControlInPanel(Control ctl, bool forward, bool tabStopOnl { if (!Contains(ctl) || !nested && ctl.ParentInternal != this) + { ctl = null; + } + Control start = ctl; do { @@ -2229,7 +2240,9 @@ private bool SelectNextControlInPanel(Control ctl, bool forward, bool tabStopOnl callBaseVersion = true; } else + { nextActiveControl = panel2; + } } } return false; @@ -2591,7 +2604,10 @@ protected override bool ProcessDialogKey(Keys keyData) { case Keys.Tab: if (ProcessTabKey((keyData & Keys.Shift) == Keys.None)) + { return true; + } + break; case Keys.Left: case Keys.Right: @@ -2601,10 +2617,15 @@ protected override bool ProcessDialogKey(Keys keyData) { if (ProcessArrowKey(keyCode == Keys.Right || keyCode == Keys.Down)) + { return true; + } } else + { return false; + } + break; } @@ -2768,7 +2789,9 @@ public override void Remove(Control value) if (!owner.DesignMode) { if (IsReadOnly) + { throw new NotSupportedException(SR.ReadonlyControlsCollection); + } } } base.Remove(value); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Splitter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Splitter.cs index 7b33fee1bba..ae325edd06c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Splitter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Splitter.cs @@ -370,7 +370,10 @@ public int MinExtra set { if (value < 0) + { value = 0; + } + minExtra = value; } } @@ -395,7 +398,10 @@ public int MinSize set { if (value < 0) + { value = 0; + } + minSize = value; } } @@ -415,7 +421,10 @@ public int SplitPosition get { if (splitSize == -1) + { splitSize = CalcSplitSize(); + } + return splitSize; } set @@ -426,9 +435,14 @@ public int SplitPosition // this is not an else-if to handle the maxSize < minSize case... // ie. we give minSize priority over maxSize... if (value > maxSize) + { value = maxSize; + } + if (value < minSize) + { value = minSize; + } // if (value == splitSize) return; -- do we need this check? @@ -605,22 +619,34 @@ private Rectangle CalcSplitLine(int splitSize, int minWeight) { case DockStyle.Top: if (r.Height < minWeight) + { r.Height = minWeight; + } + r.Y = bounds.Y + splitSize; break; case DockStyle.Bottom: if (r.Height < minWeight) + { r.Height = minWeight; + } + r.Y = bounds.Y + bounds.Height - splitSize - r.Height; break; case DockStyle.Left: if (r.Width < minWeight) + { r.Width = minWeight; + } + r.X = bounds.X + splitSize; break; case DockStyle.Right: if (r.Width < minWeight) + { r.Width = minWeight; + } + r.X = bounds.X + bounds.Width - splitSize - r.Width; break; } @@ -634,7 +660,10 @@ private int CalcSplitSize() { Control target = FindTarget(); if (target == null) + { return -1; + } + Rectangle r = target.Bounds; switch (Dock) { @@ -751,7 +780,10 @@ private Control FindTarget() { Control parent = ParentInternal; if (parent == null) + { return null; + } + Control.ControlCollection children = parent.Controls; int count = children.Count; DockStyle dock = Dock; @@ -764,19 +796,31 @@ private Control FindTarget() { case DockStyle.Top: if (target.Bottom == Top) + { return (Control)target; + } + break; case DockStyle.Bottom: if (target.Top == Bottom) + { return (Control)target; + } + break; case DockStyle.Left: if (target.Right == Left) + { return (Control)target; + } + break; case DockStyle.Right: if (target.Left == Right) + { return (Control)target; + } + break; } } @@ -880,7 +924,10 @@ protected virtual void OnSplitterMoving(SplitterEventArgs sevent) { SplitterEventHandler handler = (SplitterEventHandler)Events[EVENT_MOVING]; if (handler != null) + { handler(this, sevent); + } + if (splitTarget != null) { SplitMove(sevent.SplitX, sevent.SplitY); @@ -896,7 +943,10 @@ protected virtual void OnSplitterMoved(SplitterEventArgs sevent) { SplitterEventHandler handler = (SplitterEventHandler)Events[EVENT_MOVED]; if (handler != null) + { handler(this, sevent); + } + if (splitTarget != null) { SplitMove(sevent.SplitX, sevent.SplitY); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs index 2a597ddd637..eef8182da2d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs @@ -592,7 +592,9 @@ private void ApplyPanelWidths() // has to be re-laidout. // if (!IsHandleCreated) + { return; + } StatusBarPanel panel = null; int length = panels.Count; @@ -781,7 +783,9 @@ protected virtual void OnPanelClick(StatusBarPanelClickEventArgs e) { StatusBarPanelClickEventHandler handler = (StatusBarPanelClickEventHandler)Events[EVENT_PANELCLICK]; if (handler != null) + { handler(this, e); + } } /// @@ -924,7 +928,9 @@ private void LayoutPanels() springNum++; } else + { barPanelWidth += panel.Width; + } } @@ -943,14 +949,19 @@ private void LayoutPanels() int widthOfSpringPanel = (leftoverWidth) / springPanelsLeft; if (leftoverWidth == copyOfLeftoverWidth) + { break; + } + copyOfLeftoverWidth = leftoverWidth; for (int i = 0; i < springNum; i++) { panel = pArray[i]; if (panel == null) + { continue; + } if (widthOfSpringPanel < panel.MinWidth) { @@ -991,7 +1002,9 @@ protected virtual void OnDrawItem(StatusBarDrawItemEventArgs sbdievent) { StatusBarDrawItemEventHandler handler = (StatusBarDrawItemEventHandler)Events[EVENT_SBDRAWITEM]; if (handler != null) + { handler(this, sbdievent); + } } /// @@ -1019,7 +1032,9 @@ public override string ToString() { s += ", Panels.Count: " + Panels.Count.ToString(CultureInfo.CurrentCulture); if (Panels.Count > 0) + { s += ", Panels[0]: " + Panels[0].ToString(); + } } return s; } @@ -1084,7 +1099,9 @@ private void WmDrawItem(ref Message m) int length = panels.Count; if (dis.itemID < 0 || dis.itemID >= length) + { Debug.Fail("OwnerDraw item out of range"); + } StatusBarPanel panel = (StatusBarPanel) panels[dis.itemID]; @@ -1301,7 +1318,9 @@ public virtual StatusBarPanel this[int index] { if (value == null) + { throw new ArgumentNullException(nameof(StatusBarPanel)); + } owner.layoutDirty = true; @@ -1313,7 +1332,9 @@ public virtual StatusBarPanel this[int index] int length = owner.panels.Count; if (index < 0 || index >= length) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } StatusBarPanel oldPanel = (StatusBarPanel)owner.panels[index]; oldPanel.ParentInternal = null; @@ -1572,18 +1593,25 @@ public virtual void Insert(int index, StatusBarPanel value) //check for the value not to be null if (value == null) + { throw new ArgumentNullException(nameof(value)); + } //end check owner.layoutDirty = true; if (value.Parent != owner && value.Parent != null) + { throw new ArgumentException(SR.ObjectHasParent, "value"); + } int length = owner.panels.Count; if (index < 0 || index > length) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } + value.ParentInternal = owner; switch (value.AutoSize) @@ -1644,7 +1672,9 @@ public virtual void Remove(StatusBarPanel value) //check for the value not to be null if (value == null) + { throw new ArgumentNullException(nameof(StatusBarPanel)); + } //end check if (value.Parent != owner) @@ -1672,7 +1702,9 @@ public virtual void RemoveAt(int index) { int length = Count; if (index < 0 || index >= length) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } // clear any tooltip // diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/StatusBarPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/StatusBarPanel.cs index d46e7e0822d..97a200f0be8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/StatusBarPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/StatusBarPanel.cs @@ -171,7 +171,9 @@ public StatusBarPanelBorderStyle BorderStyle borderStyle = value; Realize(); if (Created) + { parent.Invalidate(); + } } } } @@ -539,7 +541,9 @@ public int Width set { if (!initializing && value < minWidth) + { throw new ArgumentOutOfRangeException(nameof(Width), SR.WidthGreaterThanMinWidth); + } width = value; UpdateSize(); @@ -594,12 +598,18 @@ internal int GetContentsWidth(bool newPanel) if (newPanel) { if (this.text == null) + { text = string.Empty; + } else + { text = this.text; + } } else + { text = Text; + } Graphics g = parent.CreateGraphicsInternal(); Size sz = Size.Ceiling(g.MeasureString(text, parent.Font)); @@ -700,7 +710,9 @@ internal void Realize() int result = (int)UnsafeNativeMethods.SendMessage(new HandleRef(parent, parent.Handle), NativeMethods.SB_SETTEXT, (IntPtr)wparam, sendText); if (result == 0) + { throw new InvalidOperationException(SR.UnableToSetPanelText); + } if (icon != null && style != StatusBarPanelStyle.OwnerDraw) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/StringSorter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/StringSorter.cs index 7be7262dfb9..1012a15baed 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/StringSorter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/StringSorter.cs @@ -105,7 +105,9 @@ private StringSorter(CultureInfo culture, string[] keys, object[] items, int opt { object item = items[i]; if (item != null) + { keys[i] = item.ToString(); + } } } } @@ -121,9 +123,13 @@ private StringSorter(CultureInfo culture, string[] keys, object[] items, int opt internal static int ArrayLength(object[] array) { if (array == null) + { return 0; + } else + { return array.Length; + } } /// @@ -168,9 +174,15 @@ public static int Compare(CultureInfo culture, string s1, string s2, int options private static int Compare(int lcid, string s1, string s2, int options) { if (s1 == null) + { return s2 == null ? 0 : -1; + } + if (s2 == null) + { return 1; + } + return string.Compare(s1, s2, false, CultureInfo.CurrentCulture); } @@ -198,11 +210,20 @@ private void QuickSort(int left, int right) do { while (CompareKeys(keys[i], s) < 0) + { i++; + } + while (CompareKeys(s, keys[j]) < 0) + { j--; + } + if (i > j) + { break; + } + if (i < j) { string key = keys[i]; @@ -221,13 +242,19 @@ private void QuickSort(int left, int right) if (j - left <= right - i) { if (left < j) + { QuickSort(left, j); + } + left = i; } else { if (i < right) + { QuickSort(i, right); + } + right = j; } } while (left < right); @@ -381,9 +408,12 @@ public static void Sort(CultureInfo culture, string[] keys, object[] items, int // if ((items == null) || ((keys != null) && (keys.Length != items.Length))) + { throw new ArgumentException(string.Format(SR.ArraysNotSameSize, "keys", "items")); + } + if (count > 1) { StringSorter sorter = new StringSorter(culture, keys, items, options); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs index a9085eec848..b020b5b5602 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs @@ -148,7 +148,10 @@ public TabAlignment Alignment alignment = value; if (alignment == TabAlignment.Left || alignment == TabAlignment.Right) + { Multiline = true; + } + RecreateHandle(); } } @@ -327,9 +330,15 @@ protected override CreateParams CreateParams // set up window styles // if (Multiline == true) + { cp.Style |= NativeMethods.TCS_MULTILINE; + } + if (drawMode == TabDrawMode.OwnerDrawFixed) + { cp.Style |= NativeMethods.TCS_OWNERDRAWFIXED; + } + if (ShowToolTips && !DesignMode) { cp.Style |= NativeMethods.TCS_TOOLTIPS; @@ -337,11 +346,15 @@ protected override CreateParams CreateParams if (alignment == TabAlignment.Bottom || alignment == TabAlignment.Right) + { cp.Style |= NativeMethods.TCS_BOTTOM; + } if (alignment == TabAlignment.Left || alignment == TabAlignment.Right) + { cp.Style |= NativeMethods.TCS_VERTICAL | NativeMethods.TCS_MULTILINE; + } if (tabControlState[TABCONTROLSTATE_hotTrack]) { @@ -349,12 +362,16 @@ protected override CreateParams CreateParams } if (appearance == TabAppearance.Normal) + { cp.Style |= NativeMethods.TCS_TABS; + } else { cp.Style |= NativeMethods.TCS_BUTTONS; if (appearance == TabAppearance.FlatButtons && alignment == TabAlignment.Top) + { cp.Style |= NativeMethods.TCS_FLATBUTTONS; + } } switch (sizeMode) @@ -397,7 +414,9 @@ public override Rectangle DisplayRectangle // Null out cachedDisplayRect whenever we do anything to change it... // if (!cachedDisplayRect.IsEmpty) + { return cachedDisplayRect; + } Rectangle bounds = Bounds; NativeMethods.RECT rect = NativeMethods.RECT.FromXYWH(bounds.X, bounds.Y, bounds.Width, bounds.Height); @@ -526,7 +545,9 @@ public ImageList ImageList imageList = value; IntPtr handle = (value != null) ? value.Handle : IntPtr.Zero; if (IsHandleCreated) + { SendMessage(NativeMethods.TCM_SETIMAGELIST, IntPtr.Zero, handle); + } // Update the image list in the tab pages. foreach (TabPage tabPage in TabPages) @@ -634,7 +655,10 @@ public bool Multiline { tabControlState[TABCONTROLSTATE_multiline] = value; if (Multiline == false && (alignment == TabAlignment.Left || alignment == TabAlignment.Right)) + { alignment = TabAlignment.Top; + } + RecreateHandle(); } } @@ -880,7 +904,9 @@ public TabSizeMode SizeMode set { if (sizeMode == value) + { return; + } //valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)TabSizeMode.Normal, (int)TabSizeMode.Fixed)) @@ -1237,7 +1263,10 @@ protected virtual object[] GetItems() { TabPage[] result = new TabPage[tabPageCount]; if (tabPageCount > 0) + { Array.Copy(tabPages, 0, result, 0, tabPageCount); + } + return result; } @@ -1248,7 +1277,10 @@ protected virtual object[] GetItems(Type baseType) { object[] result = (object[])Array.CreateInstance(baseType, tabPageCount); if (tabPageCount > 0) + { Array.Copy(tabPages, 0, result, 0, tabPageCount); + } + return result; } @@ -1272,7 +1304,9 @@ public Rectangle GetTabRect(int index) // normally, we would not want to create the handle for this, but since // it is dependent on the actual physical display, we simply must. if (!IsHandleCreated) + { CreateHandle(); + } SendMessage(NativeMethods.TCM_GETITEMRECT, index, ref rect); return Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom); @@ -1288,7 +1322,9 @@ protected string GetToolTipText(object item) private void ImageListRecreateHandle(object sender, EventArgs e) { if (IsHandleCreated) + { SendMessage(NativeMethods.TCM_SETIMAGELIST, 0, ImageList.Handle); + } } /// @@ -1326,10 +1362,14 @@ private void InsertItem(int index, TabPage tabPage) { if (index < 0 || ((tabPages != null) && index > tabPageCount)) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } + if (tabPage == null) + { throw new ArgumentNullException(nameof(tabPage)); - + } int retIndex; if (IsHandleCreated) @@ -1337,7 +1377,9 @@ private void InsertItem(int index, TabPage tabPage) NativeMethods.TCITEM_T tcitem = tabPage.GetTCITEM(); retIndex = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TCM_INSERTITEM, index, tcitem); if (retIndex >= 0) + { Insert(retIndex, tabPage); + } } } @@ -1348,7 +1390,10 @@ private void InsertItem(int index, TabPage tabPage) protected override bool IsInputKey(Keys keyData) { if ((keyData & Keys.Alt) == Keys.Alt) + { return false; + } + switch (keyData & Keys.KeyCode) { case Keys.PageUp: @@ -1457,7 +1502,9 @@ protected override void OnHandleDestroyed(EventArgs e) protected virtual void OnDrawItem(DrawItemEventArgs e) { if (onDrawItem != null) + { onDrawItem(this, e); + } } /// @@ -1588,8 +1635,9 @@ protected virtual void OnSelectedIndexChanged(EventArgs e) UpdateTabSelection(tabControlState[TABCONTROLSTATE_UISelection]); tabControlState[TABCONTROLSTATE_UISelection] = false; if (onSelectedIndexChanged != null) + { onSelectedIndexChanged(this, e); - + } } @@ -1602,7 +1650,9 @@ protected virtual void OnSelecting(TabControlCancelEventArgs e) { TabControlCancelEventHandler handler = (TabControlCancelEventHandler)Events[EVENT_SELECTING]; if (handler != null) + { handler(this, e); + } } /// @@ -1614,7 +1664,9 @@ protected virtual void OnSelected(TabControlEventArgs e) { TabControlEventHandler handler = (TabControlEventHandler)Events[EVENT_SELECTED]; if (handler != null) + { handler(this, e); + } // Raise the enter event for this tab. if (SelectedTab != null) @@ -1633,9 +1685,9 @@ protected virtual void OnDeselecting(TabControlCancelEventArgs e) { TabControlCancelEventHandler handler = (TabControlCancelEventHandler)Events[EVENT_DESELECTING]; if (handler != null) + { handler(this, e); - - + } } /// @@ -1647,7 +1699,9 @@ protected virtual void OnDeselected(TabControlEventArgs e) { TabControlEventHandler handler = (TabControlEventHandler)Events[EVENT_DESELECTED]; if (handler != null) + { handler(this, e); + } // Raise the Leave event for this tab. if (SelectedTab != null) @@ -1662,7 +1716,10 @@ protected virtual void OnDeselected(TabControlEventArgs e) protected override bool ProcessKeyPreview(ref Message m) { if (ProcessKeyEventArgs(ref m)) + { return true; + } + return base.ProcessKeyPreview(ref m); } @@ -1745,7 +1802,10 @@ protected void RemoveAll() internal void RemoveTabPage(int index) { if (index < 0 || index >= tabPageCount) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } + tabPageCount--; if (index < tabPageCount) { @@ -1795,9 +1855,14 @@ internal void SetToolTip(ToolTip toolTip, string controlToolTipText) internal void SetTabPage(int index, TabPage tabPage, NativeMethods.TCITEM_T tcitem) { if (index < 0 || index >= tabPageCount) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } + if (IsHandleCreated) + { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TCM_SETITEM, index, tcitem); + } // Make the Updated tab page the currently selected tab page if (DesignMode && IsHandleCreated) { @@ -1879,9 +1944,13 @@ private void SelectNextTab(KeyEventArgs ke, bool forward) { int count = TabCount; if (forward) + { sel = (sel + 1) % count; + } else + { sel = (sel + count - 1) % count; + } // this is special casing.. @@ -1940,7 +2009,9 @@ public override string ToString() { s += ", TabPages.Count: " + TabPages.Count.ToString(CultureInfo.CurrentCulture); if (TabPages.Count > 0) + { s += ", TabPages[0]: " + TabPages[0].ToString(); + } } return s; } @@ -2080,9 +2151,13 @@ private void WmNeedText(ref Message m) string tipText = GetToolTipText(GetTabPage(commandID)); if (!string.IsNullOrEmpty(tipText)) + { ttt.lpszText = tipText; + } else + { ttt.lpszText = controlTipText; + } ttt.hinst = IntPtr.Zero; @@ -2483,7 +2558,9 @@ public bool Contains(TabPage page) //check for the page not to be null if (page == null) + { throw new ArgumentNullException(nameof(page)); + } //end check return IndexOf(page) != -1; @@ -2516,7 +2593,9 @@ public int IndexOf(TabPage page) //check for the page not to be null if (page == null) + { throw new ArgumentNullException(nameof(page)); + } //end check for (int index = 0; index < Count; ++index) @@ -2701,7 +2780,9 @@ public void Remove(TabPage value) //check for the value not to be null if (value == null) + { throw new ArgumentNullException(nameof(value)); + } //end check owner.Controls.Remove(value); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TabPage.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TabPage.cs index 0e3b57609de..a799f113a7c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TabPage.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TabPage.cs @@ -472,7 +472,9 @@ public string ToolTipText } if (value == toolTipText) + { return; + } toolTipText = value; UpdateParent(); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxBase.cs index a319a60e100..d3b76913e91 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxBase.cs @@ -508,9 +508,15 @@ protected override CreateParams CreateParams cp.ClassName = "EDIT"; cp.Style |= NativeMethods.ES_AUTOHSCROLL | NativeMethods.ES_AUTOVSCROLL; if (!textBoxFlags[hideSelection]) + { cp.Style |= NativeMethods.ES_NOHIDESEL; + } + if (textBoxFlags[readOnly]) + { cp.Style |= NativeMethods.ES_READONLY; + } + cp.ExStyle &= (~NativeMethods.WS_EX_CLIENTEDGE); cp.Style &= (~NativeMethods.WS_BORDER); @@ -527,7 +533,9 @@ protected override CreateParams CreateParams { cp.Style |= NativeMethods.ES_MULTILINE; if (textBoxFlags[wordWrap]) + { cp.Style &= ~NativeMethods.ES_AUTOHSCROLL; + } } return cp; @@ -709,7 +717,9 @@ public string[] Lines { char c = text[lineEnd]; if (c == '\r' || c == '\n') + { break; + } } string line = text.Substring(lineStart, lineEnd - lineStart); @@ -717,16 +727,23 @@ public string[] Lines // Treat "\r", "\r\n", and "\n" as new lines if (lineEnd < text.Length && text[lineEnd] == '\r') + { lineEnd++; + } + if (lineEnd < text.Length && text[lineEnd] == '\n') + { lineEnd++; + } lineStart = lineEnd; } // Corner case -- last character in Text is a new line; need to add blank line to list if (text.Length > 0 && (text[text.Length - 1] == '\r' || text[text.Length - 1] == '\n')) + { list.Add(""); + } return (string[])list.ToArray(typeof(string)); } @@ -1304,7 +1321,10 @@ internal override string WindowText set { if (value == null) + { value = string.Empty; + } + if (!WindowText.Equals(value)) { textBoxFlags[codeUpdateText] = true; @@ -1570,11 +1590,17 @@ protected override bool IsInputKey(Keys keyData) return Multiline && textBoxFlags[acceptsTab] && ((keyData & Keys.Control) == 0); case Keys.Escape: if (Multiline) + { return false; + } + break; case Keys.Back: if (!ReadOnly) + { return true; + } + break; case Keys.PageUp: case Keys.PageDown: @@ -1819,7 +1845,9 @@ public virtual int GetLineFromCharIndex(int index) public virtual Point GetPositionFromCharIndex(int index) { if (index < 0 || index >= Text.Length) + { return Point.Empty; + } int i = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), Interop.EditMessages.EM_POSFROMCHAR, index, 0); return new Point(NativeMethods.Util.SignedLOWORD(i), NativeMethods.Util.SignedHIWORD(i)); @@ -2037,10 +2065,14 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound { if (!integralHeightAdjust && height != Height) + { requestedHeight = height; + } if (textBoxFlags[autoSize] && !textBoxFlags[multiline]) + { height = PreferredHeight; + } base.SetBoundsCore(x, y, width, height, specified); } @@ -2229,7 +2261,10 @@ public override string ToString() string txt = Text; if (txt.Length > 40) + { txt = txt.Substring(0, 40) + "..."; + } + return s + ", Text: " + txt.ToString(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ThreadExceptionDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ThreadExceptionDialog.cs index f2e41e778a7..fb845bc213c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ThreadExceptionDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ThreadExceptionDialog.cs @@ -247,9 +247,14 @@ public ThreadExceptionDialog(Exception t) g.Dispose(); if (textSize.Width < scaledMaxTextWidth) + { textSize.Width = scaledMaxTextWidth; + } + if (textSize.Height > scaledMaxHeight) + { textSize.Height = scaledMaxHeight; + } int width = textSize.Width + scaledPaddingWidth; int buttonTop = Math.Max(textSize.Height, scaledMaxTextHeight) + scaledPaddingHeight; @@ -404,7 +409,10 @@ private void DetailsClick(object sender, EventArgs eventargs) { int delta = details.Height + scaledHeightPadding; if (detailsVisible) + { delta = -delta; + } + Height = Height + delta; detailsVisible = !detailsVisible; details.Visible = detailsVisible; @@ -414,10 +422,16 @@ private void DetailsClick(object sender, EventArgs eventargs) private static string Trim(string s) { if (s == null) + { return s; + } + int i = s.Length; while (i > 0 && s[i - 1] == '.') + { i--; + } + return s.Substring(0, i); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs index bd13e6aca53..5b0a84415fb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs @@ -378,7 +378,9 @@ public Size ButtonSize { if (value.Width < 0 || value.Height < 0) + { throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(SR.InvalidArgument, nameof(ButtonSize), value)); + } if (buttonSize != value) { @@ -410,11 +412,19 @@ protected override CreateParams CreateParams // | NativeMethods.WS_CHILD was commented out since setTopLevel should be able to work. if (!Divider) + { cp.Style |= NativeMethods.CCS_NODIVIDER; + } + if (Wrappable) + { cp.Style |= NativeMethods.TBSTYLE_WRAPPABLE; + } + if (ShowToolTips && !DesignMode) + { cp.Style |= NativeMethods.TBSTYLE_TOOLTIPS; + } cp.ExStyle &= (~NativeMethods.WS_EX_CLIENTEDGE); cp.Style &= (~NativeMethods.WS_BORDER); @@ -641,7 +651,9 @@ public ImageList ImageList } if (IsHandleCreated) + { RecreateHandle(); + } } } } @@ -752,7 +764,9 @@ internal int PreferredHeight } if (Divider) + { height += 2; + } height += 4; @@ -782,7 +796,9 @@ internal int PreferredWidth // don't have it, have to recompute // if (!IsHandleCreated || buttons == null) + { maxWidth = ButtonSize.Width; + } else { @@ -792,7 +808,9 @@ internal int PreferredWidth { SendMessage(NativeMethods.TB_GETRECT, 0, ref rect); if ((rect.right - rect.left) > maxWidth) + { maxWidth = rect.right - rect.left; + } } } } @@ -949,7 +967,10 @@ public ToolBarTextAlign TextAlign } if (textAlign == value) + { return; + } + textAlign = value; RecreateHandle(); } @@ -1177,7 +1198,9 @@ private void ForceButtonWidths() private void ImageListRecreateHandle(object sender, EventArgs e) { if (IsHandleCreated) + { RecreateHandle(); + } } /// @@ -1199,7 +1222,9 @@ private void Insert(int index, ToolBarButton button) } if (index < buttonCount) + { System.Array.Copy(buttons, index, buttons, index + 1, buttonCount - index); + } buttons[index] = button; buttonCount++; @@ -1212,9 +1237,14 @@ private void InsertButton(int index, ToolBarButton value) { if (value == null) + { throw new ArgumentNullException(nameof(value)); + } + if (index < 0 || ((buttons != null) && (index > buttonCount))) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } // insert the button into our local array, and then into the // real windows ToolBar control @@ -1234,7 +1264,10 @@ private void InsertButton(int index, ToolBarButton value) private int InternalAddButton(ToolBarButton button) { if (button == null) + { throw new ArgumentNullException(nameof(button)); + } + int index = buttonCount; Insert(index, button); return index; @@ -1290,7 +1323,9 @@ internal void InternalSetButton(int index, ToolBarButton value, bool recreate, b protected virtual void OnButtonClick(ToolBarButtonClickEventArgs e) { if (onButtonClick != null) + { onButtonClick(this, e); + } } /// @@ -1300,7 +1335,9 @@ protected virtual void OnButtonClick(ToolBarButtonClickEventArgs e) protected virtual void OnButtonDropDown(ToolBarButtonClickEventArgs e) { if (onButtonDropDown != null) + { onButtonDropDown(this, e); + } } /// @@ -1321,12 +1358,16 @@ protected override void OnHandleCreated(EventArgs e) // set up some extra goo // if (DropDownArrows) + { SendMessage(NativeMethods.TB_SETEXTENDEDSTYLE, 0, NativeMethods.TBSTYLE_EX_DRAWDDARROWS); + } // if we have an imagelist, add it in now. // if (imageList != null) + { SendMessage(NativeMethods.TB_SETIMAGELIST, 0, imageList.Handle); + } RealizeButtons(); @@ -1355,7 +1396,9 @@ protected override void OnResize(EventArgs e) { base.OnResize(e); if (Wrappable) + { AdjustSize(Dock); + } } /// @@ -1460,7 +1503,9 @@ private void RemoveAt(int index) buttonCount--; if (index < buttonCount) + { System.Array.Copy(buttons, index + 1, buttons, index, buttonCount - index); + } buttons[buttonCount] = null; } @@ -1496,9 +1541,14 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound if (Dock == DockStyle.Left || Dock == DockStyle.Right) { if ((specified & BoundsSpecified.Width) != BoundsSpecified.None) + { requestedSize = width; + } + if (AutoSize) + { width = PreferredWidth; + } if (width != originalWidth && Dock == DockStyle.Right) { @@ -1510,9 +1560,14 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound else { if ((specified & BoundsSpecified.Height) != BoundsSpecified.None) + { requestedSize = height; + } + if (AutoSize) + { height = PreferredHeight; + } if (height != originalHeight && Dock == DockStyle.Bottom) { @@ -1551,7 +1606,10 @@ public override string ToString() string s = base.ToString(); s += ", Buttons.Count: " + buttonCount.ToString(CultureInfo.CurrentCulture); if (buttonCount > 0) + { s += ", Buttons[0]: " + buttons[0].ToString(); + } + return s; } @@ -1578,7 +1636,9 @@ private void WmNotifyDropDown(ref Message m) ToolBarButton tbb = (ToolBarButton)buttons[nmTB.iItem]; if (tbb == null) + { throw new InvalidOperationException(SR.ToolBarButtonNotFound); + } OnButtonDropDown(new ToolBarButtonClickEventArgs(tbb)); @@ -1627,9 +1687,13 @@ private void WmNotifyNeedText(ref Message m) ToolBarButton tbb = (ToolBarButton)buttons[commandID]; if (tbb != null && tbb.ToolTipText != null) + { ttt.lpszText = tbb.ToolTipText; + } else + { ttt.lpszText = null; + } ttt.hinst = IntPtr.Zero; @@ -1651,23 +1715,41 @@ private void WmNotifyHotItemChange(ref Message m) // Should we set the hot item? NativeMethods.NMTBHOTITEM nmTbHotItem = (NativeMethods.NMTBHOTITEM)m.GetLParam(typeof(NativeMethods.NMTBHOTITEM)); if (NativeMethods.HICF_ENTERING == (nmTbHotItem.dwFlags & NativeMethods.HICF_ENTERING)) + { hotItem = nmTbHotItem.idNew; + } else if (NativeMethods.HICF_LEAVING == (nmTbHotItem.dwFlags & NativeMethods.HICF_LEAVING)) + { hotItem = -1; + } else if (NativeMethods.HICF_MOUSE == (nmTbHotItem.dwFlags & NativeMethods.HICF_MOUSE)) + { hotItem = nmTbHotItem.idNew; + } else if (NativeMethods.HICF_ARROWKEYS == (nmTbHotItem.dwFlags & NativeMethods.HICF_ARROWKEYS)) + { hotItem = nmTbHotItem.idNew; + } else if (NativeMethods.HICF_ACCELERATOR == (nmTbHotItem.dwFlags & NativeMethods.HICF_ACCELERATOR)) + { hotItem = nmTbHotItem.idNew; + } else if (NativeMethods.HICF_DUPACCEL == (nmTbHotItem.dwFlags & NativeMethods.HICF_DUPACCEL)) + { hotItem = nmTbHotItem.idNew; + } else if (NativeMethods.HICF_RESELECT == (nmTbHotItem.dwFlags & NativeMethods.HICF_RESELECT)) + { hotItem = nmTbHotItem.idNew; + } else if (NativeMethods.HICF_LMOUSE == (nmTbHotItem.dwFlags & NativeMethods.HICF_LMOUSE)) + { hotItem = nmTbHotItem.idNew; + } else if (NativeMethods.HICF_TOGGLEDROPDOWN == (nmTbHotItem.dwFlags & NativeMethods.HICF_TOGGLEDROPDOWN)) + { hotItem = nmTbHotItem.idNew; + } } @@ -1825,7 +1907,10 @@ public virtual ToolBarButton this[int index] get { if (index < 0 || ((owner.buttons != null) && (index >= owner.buttonCount))) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } + return owner.buttons[index]; } set @@ -2148,7 +2233,9 @@ public void RemoveAt(int index) int count = (owner.buttons == null) ? 0 : owner.buttonCount; if (index < 0 || index >= count) + { throw new ArgumentOutOfRangeException(nameof(index), string.Format(SR.InvalidArgument, "index", index.ToString(CultureInfo.CurrentCulture))); + } if (owner.IsHandleCreated) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs index eb3e1e05e52..50358766b14 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs @@ -204,7 +204,9 @@ public int ImageIndex if (ImageIndexer.Index != value) { if (value < -1) + { throw new ArgumentOutOfRangeException(nameof(ImageIndex), string.Format(SR.InvalidLowBoundArgumentEx, nameof(ImageIndex), value, -1)); + } ImageIndexer.Index = value; UpdateButton(false); @@ -298,13 +300,19 @@ public bool PartialPush get { if (parent == null || !parent.IsHandleCreated) + { return partialPush; + } else { if ((int)parent.SendMessage(NativeMethods.TB_ISBUTTONINDETERMINATE, FindButtonIndex(), 0) != 0) + { partialPush = true; + } else + { partialPush = false; + } return partialPush; } @@ -331,7 +339,9 @@ public bool Pushed get { if (parent == null || !parent.IsHandleCreated) + { return pushed; + } else { return GetPushedState(); @@ -388,7 +398,10 @@ public ToolBarButtonStyle Style throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolBarButtonStyle)); } if (style == value) + { return; + } + style = value; UpdateButton(true); } @@ -533,16 +546,24 @@ internal short Width if (parent.TextAlign == ToolBarTextAlign.Right) { if (textSize.Width == 0) + { width = imageSize.Width + edge.Width * 4; + } else + { width = imageSize.Width + textSize.Width + edge.Width * 6; + } } else { if (imageSize.Width > textSize.Width) + { width = imageSize.Width + edge.Width * 4; + } else + { width = textSize.Width + edge.Width * 4; + } } if (style == ToolBarButtonStyle.DropDownButton && parent.DropDownArrows) { @@ -550,7 +571,9 @@ internal short Width } } else + { width = parent.ButtonSize.Width; + } } } } @@ -650,13 +673,24 @@ internal NativeMethods.TBBUTTON GetTBBUTTON(int commandId) fsState = 0 }; if (enabled) + { button.fsState |= NativeMethods.TBSTATE_ENABLED; + } + if (partialPush && style == ToolBarButtonStyle.ToggleButton) + { button.fsState |= NativeMethods.TBSTATE_INDETERMINATE; + } + if (pushed) + { button.fsState |= NativeMethods.TBSTATE_CHECKED; + } + if (!visible) + { button.fsState |= NativeMethods.TBSTATE_HIDDEN; + } // set the button style // @@ -719,13 +753,24 @@ internal NativeMethods.TBBUTTONINFO GetTBBUTTONINFO(bool updateText, int newComm // button.fsState = 0; if (enabled) + { button.fsState |= NativeMethods.TBSTATE_ENABLED; + } + if (partialPush && style == ToolBarButtonStyle.ToggleButton) + { button.fsState |= NativeMethods.TBSTATE_INDETERMINATE; + } + if (pushed) + { button.fsState |= NativeMethods.TBSTATE_CHECKED; + } + if (!visible) + { button.fsState |= NativeMethods.TBSTATE_HIDDEN; + } // set the button style // @@ -848,7 +893,9 @@ private void UpdateButton(bool recreate, bool updateText, bool updatePushedState { int index = FindButtonIndex(); if (index != -1) + { parent.InternalSetButton(index, this, recreate, updateText); + } } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs index 141ef699ece..8dc69c43212 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs @@ -493,13 +493,17 @@ public override BindingContext BindingContext { BindingContext bc = (BindingContext)Properties.GetObject(PropBindingContext); if (bc != null) + { return bc; + } // try the parent // Control p = ParentInternal; if (p != null && p.CanAccessProperties) + { return p.BindingContext; + } // we don't have a binding context return null; @@ -2479,7 +2483,9 @@ private ToolStripItem GetNextItemHorizontal(ToolStripItem start, bool forward) { if (DisplayedItems.Count <= 0) + { return null; + } if (start == null) { @@ -3622,7 +3628,9 @@ protected virtual void OnBeginDrag(EventArgs e) UpdateToolTip(null); // supress the tooltip. EventHandler handler = (EventHandler)Events[EventBeginDrag]; if (handler != null) + { handler(this, e); + } } protected virtual void OnEndDrag(EventArgs e) @@ -3634,8 +3642,9 @@ protected virtual void OnEndDrag(EventArgs e) EventHandler handler = (EventHandler)Events[EventEndDrag]; if (handler != null) + { handler(this, e); - + } } @@ -3651,8 +3660,9 @@ protected virtual void OnRendererChanged(EventArgs e) EventHandler handler = (EventHandler)Events[EventRendererChanged]; if (handler != null) + { handler(this, e); - + } } /// /// Summary of OnEnabledChanged. @@ -3756,7 +3766,9 @@ protected internal virtual void OnItemAdded(ToolStripItemEventArgs e) ToolStripItemEventHandler handler = (ToolStripItemEventHandler)Events[EventItemAdded]; if (handler != null) + { handler(this, e); + } } /// @@ -3766,8 +3778,9 @@ protected virtual void OnItemClicked(ToolStripItemClickedEventArgs e) { ToolStripItemClickedEventHandler handler = (ToolStripItemClickedEventHandler)Events[EventItemClicked]; if (handler != null) + { handler(this, e); - + } } protected internal virtual void OnItemRemoved(ToolStripItemEventArgs e) @@ -3778,7 +3791,9 @@ protected internal virtual void OnItemRemoved(ToolStripItemEventArgs e) ToolStripItemEventHandler handler = (ToolStripItemEventHandler)Events[EventItemRemoved]; if (handler != null) + { handler(this, e); + } } @@ -3835,14 +3850,18 @@ protected virtual void OnLayoutCompleted(EventArgs e) { EventHandler handler = (EventHandler)Events[EventLayoutCompleted]; if (handler != null) + { handler(this, e); + } } protected virtual void OnLayoutStyleChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[EventLayoutStyleChanged]; if (handler != null) + { handler(this, e); + } } protected override void OnLostFocus(EventArgs e) @@ -3867,7 +3886,9 @@ internal virtual void OnLocationChanging(ToolStripLocationCancelEventArgs e) { ToolStripLocationCancelEventHandler handler = (ToolStripLocationCancelEventHandler)Events[EventLocationChanging]; if (handler != null) + { handler(this, e); + } } /// @@ -4287,9 +4308,9 @@ internal protected virtual void OnPaintGrip(System.Windows.Forms.PaintEventArgs PaintEventHandler handler = (PaintEventHandler)Events[EventPaintGrip]; if (handler != null) + { handler(this, e); - - + } } protected override void OnScroll(ScrollEventArgs se) @@ -5335,7 +5356,9 @@ public override AccessibleObject HitTest(int x, int y) public override AccessibleObject GetChild(int index) { if ((owner == null) || (owner.Items == null)) + { return null; + } if (index == 0 && owner.Grip.Visible) { @@ -5409,7 +5432,9 @@ public override AccessibleObject GetChild(int index) public override int GetChildCount() { if ((owner == null) || (owner.Items == null)) + { return -1; + } int count = 0; for (int i = 0; i < owner.Items.Count; i++) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs index 683eb27cd00..cd59d893177 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs @@ -226,7 +226,9 @@ protected virtual void OnCheckedChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[EventCheckedChanged]; if (handler != null) + { handler(this, e); + } } /// @@ -237,7 +239,9 @@ protected virtual void OnCheckStateChanged(EventArgs e) AccessibilityNotifyClients(AccessibleEvents.StateChange); EventHandler handler = (EventHandler)Events[EventCheckStateChanged]; if (handler != null) + { handler(this, e); + } } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs index 977b0f68556..d7aaf3be648 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs @@ -509,7 +509,9 @@ public override void Remove(Control value) if (!owner.DesignMode) { if (IsReadOnly) + { throw new NotSupportedException(SR.ReadonlyControlsCollection); + } } } base.Remove(value); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContentPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContentPanel.cs index 22135bb998c..8b52eebc3b1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContentPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContentPanel.cs @@ -379,7 +379,9 @@ protected virtual void OnLoad(EventArgs e) // that it's just another name for OnControlCreated. EventHandler handler = (EventHandler)Events[EventLoad]; if (handler != null) + { handler(this, e); + } } [EditorBrowsable(EditorBrowsableState.Advanced)] @@ -419,8 +421,9 @@ protected virtual void OnRendererChanged(EventArgs e) EventHandler handler = (EventHandler)Events[EventRendererChanged]; if (handler != null) + { handler(this, e); - + } } private void ResetRenderMode() diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs index 9ee3c69a6d2..08d60c349e6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs @@ -757,7 +757,9 @@ private void HandleQueryAccessibilityHelp(object sender, QueryAccessibilityHelpE { QueryAccessibilityHelpEventHandler handler = (QueryAccessibilityHelpEventHandler)Events[ToolStripItem.EventQueryAccessibilityHelp]; if (handler != null) + { handler(this, e); + } } private void HandleQueryContinueDrag(object sender, QueryContinueDragEventArgs e) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs index f4f19603b2f..a0e47b0f6a3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs @@ -1394,7 +1394,9 @@ protected virtual void OnClosed(ToolStripDropDownClosedEventArgs e) } ToolStripDropDownClosedEventHandler handler = (ToolStripDropDownClosedEventHandler)Events[EventClosed]; if (handler != null) + { handler(this, e); + } } // @@ -1404,7 +1406,9 @@ protected virtual void OnClosing(ToolStripDropDownClosingEventArgs e) { ToolStripDropDownClosingEventHandler handler = (ToolStripDropDownClosingEventHandler)Events[EventClosing]; if (handler != null) + { handler(this, e); + } } /// /// When our handle is being created, suspend the deactivation @@ -1455,7 +1459,9 @@ protected virtual void OnOpening(CancelEventArgs e) { CancelEventHandler handler = (CancelEventHandler)Events[EventOpening]; if (handler != null) + { handler(this, e); + } } @@ -1475,7 +1481,9 @@ protected virtual void OnOpened(System.EventArgs e) EventHandler handler = (EventHandler)Events[EventOpened]; if (handler != null) + { handler(this, e); + } } protected override void OnVisibleChanged(System.EventArgs e) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs index 78df4309e64..31f93cb3d10 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs @@ -505,7 +505,9 @@ protected virtual void OnDropDownHide(EventArgs e) EventHandler handler = (EventHandler)Events[EventDropDownHide]; if (handler != null) + { handler(this, e); + } } /// /// Last chance to stick in the DropDown before it is shown. @@ -530,7 +532,9 @@ protected internal virtual void OnDropDownOpened(System.EventArgs e) { EventHandler handler = (EventHandler)Events[EventDropDownOpened]; if (handler != null) + { handler(this, e); + } } } @@ -546,7 +550,9 @@ protected internal virtual void OnDropDownClosed(System.EventArgs e) { EventHandler handler = (EventHandler)Events[EventDropDownClosed]; if (handler != null) + { handler(this, e); + } if (!DropDown.IsAutoGenerated) { @@ -569,7 +575,9 @@ protected internal virtual void OnDropDownItemClicked(ToolStripItemClickedEventA { ToolStripItemClickedEventHandler handler = (ToolStripItemClickedEventHandler)Events[EventDropDownItemClicked]; if (handler != null) + { handler(this, e); + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs index a19bbab4ff5..150f35f8067 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs @@ -564,7 +564,9 @@ public virtual Color BackColor { Color c = RawBackColor; // inheritedProperties.BackColor if (!c.IsEmpty) + { return c; + } Control p = ParentInternal; if (p != null) @@ -3300,7 +3302,9 @@ protected virtual void OnGiveFeedback(GiveFeedbackEventArgs giveFeedbackEvent) { GiveFeedbackEventHandler handler = (GiveFeedbackEventHandler)Events[EventGiveFeedback]; if (handler != null) + { handler(this, giveFeedbackEvent); + } } internal virtual void OnImageScalingSizeChanged(EventArgs e) @@ -3626,51 +3630,67 @@ internal void RaiseCancelEvent(object key, CancelEventArgs e) { CancelEventHandler handler = (CancelEventHandler)Events[key]; if (handler != null) + { handler(this, e); + } } internal void RaiseDragEvent(object key, DragEventArgs e) { DragEventHandler handler = (DragEventHandler)Events[key]; if (handler != null) + { handler(this, e); + } } internal void RaiseEvent(object key, EventArgs e) { EventHandler handler = (EventHandler)Events[key]; if (handler != null) + { handler(this, e); + } } internal void RaiseKeyEvent(object key, KeyEventArgs e) { KeyEventHandler handler = (KeyEventHandler)Events[key]; if (handler != null) + { handler(this, e); + } } internal void RaiseKeyPressEvent(object key, KeyPressEventArgs e) { KeyPressEventHandler handler = (KeyPressEventHandler)Events[key]; if (handler != null) + { handler(this, e); + } } internal void RaiseMouseEvent(object key, MouseEventArgs e) { MouseEventHandler handler = (MouseEventHandler)Events[key]; if (handler != null) + { handler(this, e); + } } internal void RaisePaintEvent(object key, PaintEventArgs e) { PaintEventHandler handler = (PaintEventHandler)Events[key]; if (handler != null) + { handler(this, e); + } } internal void RaiseQueryContinueDragEvent(object key, QueryContinueDragEventArgs e) { QueryContinueDragEventHandler handler = (QueryContinueDragEventHandler)Events[key]; if (handler != null) + { handler(this, e); + } } private void ResetToolTipText() diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs index ee308303495..7ebc64296fa 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs @@ -237,9 +237,13 @@ private static Delegate GetEventHandler(int key) lock (internalSyncObject) { if (staticEventHandlers == null) + { return null; + } else + { return (Delegate)staticEventHandlers[key]; + } } } @@ -1308,7 +1312,10 @@ private void SetActiveToolStripCore(ToolStrip toolStrip) _toplevelToolStrip = null; if (!_inputFilterQueue.Contains(toolStrip)) + { _inputFilterQueue.Add(toolStrip); + } + if (!InMenuMode && _inputFilterQueue.Count > 0) { Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "[ModalMenuFilter.SetActiveToolStripCore] Setting " + WindowsFormsUtils.GetControlInformation(toolStrip.Handle) + " active."); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs index 8991b2875ac..f2b305cea1a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs @@ -984,7 +984,9 @@ protected virtual void OnCheckedChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[EventCheckedChanged]; if (handler != null) + { handler(this, e); + } } /// @@ -995,7 +997,9 @@ protected virtual void OnCheckStateChanged(EventArgs e) AccessibilityNotifyClients(AccessibleEvents.StateChange); EventHandler handler = (EventHandler)Events[EventCheckStateChanged]; if (handler != null) + { handler(this, e); + } } protected override void OnDropDownHide(EventArgs e) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs index 74a484b55e7..a4d92d735d7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs @@ -672,8 +672,9 @@ protected virtual void OnRendererChanged(EventArgs e) EventHandler handler = (EventHandler)Events[EventRendererChanged]; if (handler != null) + { handler(this, e); - + } } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs index 01f7d4dd39c..38e8b7945cd 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs @@ -235,7 +235,11 @@ private bool Initialized public Padding Margin { get { return CommonProperties.GetMargin(this); } - set { if (Margin != value) CommonProperties.SetMargin(this, value); } + set { if (Margin != value) + { + CommonProperties.SetMargin(this, value); + } + } } public virtual Padding Padding @@ -244,7 +248,9 @@ public virtual Padding Padding set { if (Padding != value) + { CommonProperties.SetPadding(this, value); + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs index 82678ab4a8d..bd372f3da89 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs @@ -499,8 +499,9 @@ protected virtual void OnButtonClick(System.EventArgs e) EventHandler handler = (EventHandler)Events[EventButtonClick]; if (handler != null) + { handler(this, e); - + } } /// @@ -516,7 +517,9 @@ public virtual void OnButtonDoubleClick(System.EventArgs e) EventHandler handler = (EventHandler)Events[EventButtonDoubleClick]; if (handler != null) + { handler(this, e); + } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitStackLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitStackLayout.cs index 50971e43d5a..b05176b7a5d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitStackLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitStackLayout.cs @@ -196,7 +196,9 @@ private void CalculatePlacementsVertical() OverflowRequired = true; #if DEBUG if (DebugLayoutTraceSwitch.TraceVerbose) + { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "OverflowRequired - item set to always overflow: {0} ", item)); + } #endif } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs index a963394e4af..3756fba1804 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs @@ -2539,7 +2539,9 @@ private void WmShow() // Get the text display rectangle UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_ADJUSTRECT, 1, ref r); if (r.Size.Height > currentTooltipSize.Height) + { currentTooltipSize.Height = r.Size.Height; + } } // Set the max possible size of the tooltip to the size we received. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs index 10d85083a43..4faa26ea0c7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs @@ -767,9 +767,13 @@ private void AdjustSize() try { if (orientation == Orientation.Horizontal) + { Height = autoSize ? PreferredDimension : saveDim; + } else + { Width = autoSize ? PreferredDimension : saveDim; + } } finally { @@ -875,7 +879,10 @@ private void GetTrackBarValue() protected override bool IsInputKey(Keys keyData) { if ((keyData & Keys.Alt) == Keys.Alt) + { return false; + } + switch (keyData & Keys.KeyCode) { case Keys.PageUp: @@ -931,7 +938,9 @@ protected virtual void OnScroll(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_SCROLL]; if (handler != null) + { handler(this, e); + } } /// @@ -1009,7 +1018,9 @@ protected virtual void OnValueChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_VALUECHANGED]; if (handler != null) + { handler(this, e); + } } /// @@ -1046,12 +1057,16 @@ protected override void SetBoundsCore(int x, int y, int width, int height, Bound if (orientation == Orientation.Horizontal) { if ((specified & BoundsSpecified.Height) != BoundsSpecified.None) + { height = PreferredDimension; + } } else { if ((specified & BoundsSpecified.Width) != BoundsSpecified.None) + { width = PreferredDimension; + } } } //} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs index 380921a4fba..a521f19802b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs @@ -252,7 +252,10 @@ public Color BackColor get { if (propBag == null) + { return Color.Empty; + } + return propBag.BackColor; } set @@ -269,17 +272,25 @@ public Color BackColor RemovePropBagIfEmpty(); } if (!oldbk.IsEmpty) + { InvalidateHostTree(); + } + return; } // Not the default, so if necessary create a new propBag, and fill it with the backcolor if (propBag == null) + { propBag = new OwnerDrawPropertyBag(); + } + propBag.BackColor = value; if (!value.Equals(oldbk)) + { InvalidateHostTree(); + } } } @@ -362,11 +373,15 @@ internal bool CheckedInternal { CheckedStateInternal = value; if (handle == IntPtr.Zero) + { return; + } TreeView tv = TreeView; if (tv == null || !tv.IsHandleCreated || tv.IsDisposed) + { return; + } NativeMethods.TV_ITEM item = new NativeMethods.TV_ITEM { @@ -477,7 +492,10 @@ public TreeNode FirstNode get { if (childCount == 0) + { return null; + } + return children[0]; } } @@ -509,7 +527,10 @@ public Color ForeColor get { if (propBag == null) + { return Color.Empty; + } + return propBag.ForeColor; } set @@ -525,17 +546,25 @@ public Color ForeColor RemovePropBagIfEmpty(); } if (!oldfc.IsEmpty) + { InvalidateHostTree(); + } + return; } // Not the default, so if necessary create a new propBag, and fill it with the new forecolor if (propBag == null) + { propBag = new OwnerDrawPropertyBag(); + } + propBag.ForeColor = value; if (!value.Equals(oldfc)) + { InvalidateHostTree(); + } } } @@ -557,7 +586,9 @@ public string FullPath return path.ToString(); } else + { throw new InvalidOperationException(SR.TreeNodeNoParent); + } } } @@ -651,7 +682,9 @@ public bool IsEditing TreeView tv = TreeView; if (tv != null) + { return tv.editNode == this; + } return false; } @@ -682,7 +715,10 @@ public bool IsSelected get { if (handle == IntPtr.Zero) + { return false; + } + return (State & NativeMethods.TVIS_SELECTED) != 0; } } @@ -696,7 +732,10 @@ public bool IsVisible get { if (handle == IntPtr.Zero) + { return false; + } + TreeView tv = TreeView; if (tv.IsDisposed) { @@ -726,7 +765,10 @@ public TreeNode LastNode get { if (childCount == 0) + { return null; + } + return children[childCount - 1]; } } @@ -824,7 +866,10 @@ public Font NodeFont get { if (propBag == null) + { return null; + } + return propBag.Font; } set @@ -840,17 +885,25 @@ public Font NodeFont RemovePropBagIfEmpty(); } if (oldfont != null) + { InvalidateHostTree(); + } + return; } // Not the default, so if necessary create a new propBag, and fill it with the font if (propBag == null) + { propBag = new OwnerDrawPropertyBag(); + } + propBag.Font = value; if (!value.Equals(oldfont)) + { InvalidateHostTree(); + } } } @@ -1014,7 +1067,9 @@ internal int State get { if (handle == IntPtr.Zero) + { return 0; + } TreeView tv = TreeView; if (tv == null || tv.IsDisposed) @@ -1190,7 +1245,10 @@ public TreeView TreeView get { if (treeView == null) + { treeView = FindTreeView(); + } + return treeView; } } @@ -1213,7 +1271,9 @@ internal int AddSorted(TreeNode node) // Optimize for the case where they're already sorted if (compare.Compare(children[childCount - 1].Text, nodeText) <= 0) + { index = childCount; + } else { // Insert at appropriate sorted spot @@ -1221,9 +1281,13 @@ internal int AddSorted(TreeNode node) { iT = (iMin + iLim) / 2; if (compare.Compare(children[iT].Text, nodeText) <= 0) + { iMin = iT + 1; + } else + { iLim = iT; + } } index = iMin; } @@ -1236,9 +1300,13 @@ internal int AddSorted(TreeNode node) { iT = (iMin + iLim) / 2; if (sorter.Compare(children[iT] /*previous*/, node/*current*/) <= 0) + { iMin = iT + 1; + } else + { iLim = iT; + } } index = iMin; } @@ -1273,14 +1341,19 @@ private void SortChildren(TreeView parentTreeView) for (int j = 0; j < childCount; j++) { if (children[j] == null) + { continue; + } + if (min == -1) { min = j; continue; } if (compare.Compare(children[j].Text, children[min].Text) <= 0) + { min = j; + } } Debug.Assert(min != -1, "Bad sorting"); @@ -1300,14 +1373,19 @@ private void SortChildren(TreeView parentTreeView) for (int j = 0; j < childCount; j++) { if (children[j] == null) + { continue; + } + if (min == -1) { min = j; continue; } if (sorter.Compare(children[j] /*previous*/, children[min] /*current*/) <= 0) + { min = j; + } } Debug.Assert(min != -1, "Bad sorting"); @@ -1333,9 +1411,15 @@ public void BeginEdit() { TreeView tv = TreeView; if (tv.LabelEdit == false) + { throw new InvalidOperationException(SR.TreeNodeBeginEditFailed); + } + if (!tv.Focused) + { tv.Focus(); + } + UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_EDITLABEL, 0, handle); } } @@ -1441,7 +1525,9 @@ public virtual object Clone() { node.children = new TreeNode[childCount]; for (int i = 0; i < childCount; i++) + { node.Nodes.Add((TreeNode)children[i].Clone()); + } } // Clone properties @@ -1494,7 +1580,10 @@ private void CollapseInternal(bool ignoreChildren) } if (setSelection) + { tv.SelectedNode = this; + } + tv.Invalidate(); collapseOnRealization = false; @@ -1757,7 +1846,10 @@ internal TreeView FindTreeView() { TreeNode node = this; while (node.parent != null) + { node = node.parent; + } + return node.treeView; } @@ -1770,7 +1862,10 @@ private void GetFullPath(StringBuilder path, string pathSeparator) { parent.GetFullPath(path, pathSeparator); if (parent.parent != null) + { path.Append(pathSeparator); + } + path.Append(text); } } @@ -1784,7 +1879,9 @@ public int GetNodeCount(bool includeSubTrees) if (includeSubTrees) { for (int i = 0; i < childCount; i++) + { total += children[i].GetNodeCount(true); + } } return total; } @@ -1823,7 +1920,9 @@ internal void InsertNodeAt(int index, TreeNode node) node.Realize(false); if (TreeView != null && node == TreeView.selectedNode) + { TreeView.SelectedNode = node; // communicate this to the handle + } } /// @@ -1832,7 +1931,9 @@ internal void InsertNodeAt(int index, TreeNode node) private void InvalidateHostTree() { if (treeView != null && treeView.IsHandleCreated) + { treeView.Invalidate(); + } } /// @@ -1842,7 +1943,9 @@ internal void Realize(bool insertFirst) // Debug.assert(handle == 0, "Node already realized"); TreeView tv = TreeView; if (tv == null || !tv.IsHandleCreated || tv.IsDisposed) + { return; + } if (parent != null) { // Never realize the virtual root @@ -1891,9 +1994,14 @@ internal void Realize(bool insertFirst) if (tvis.item_iImage >= 0) + { tvis.item_mask |= NativeMethods.TVIF_IMAGE; + } + if (tvis.item_iSelectedImage >= 0) + { tvis.item_mask |= NativeMethods.TVIF_SELECTEDIMAGE; + } // If you are editing when you add a new node, then the edit control // gets placed in the wrong place. You must restore the edit mode @@ -1939,7 +2047,9 @@ internal void Realize(bool insertFirst) } for (int i = childCount - 1; i >= 0; i--) + { children[i].Realize(true); + } // If node expansion was requested before the handle was created, // we can expand it now. @@ -1975,7 +2085,9 @@ internal void Remove(bool notify) // for (int i = 0; i < childCount; i++) + { children[i].Remove(false); + } // children = null; // unlink ourself if (notify && parent != null) @@ -2002,7 +2114,10 @@ internal void Remove(bool notify) if (handle != IntPtr.Zero) { if (notify && tv.IsHandleCreated) + { UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_DELETEITEM, 0, handle); + } + treeView.nodeTable.Remove(handle); handle = IntPtr.Zero; } @@ -2015,9 +2130,15 @@ internal void Remove(bool notify) private void RemovePropBagIfEmpty() { if (propBag == null) + { return; + } + if (propBag.IsEmpty()) + { propBag = null; + } + return; } @@ -2127,7 +2248,10 @@ public override string ToString() private void UpdateNode(int mask) { if (handle == IntPtr.Zero) + { return; + } + TreeView tv = TreeView; Debug.Assert(tv != null, "TreeNode has handle but no TreeView"); @@ -2137,11 +2261,20 @@ private void UpdateNode(int mask) hItem = handle }; if ((mask & NativeMethods.TVIF_TEXT) != 0) + { item.pszText = Marshal.StringToHGlobalAuto(text); + } + if ((mask & NativeMethods.TVIF_IMAGE) != 0) + { item.iImage = (ImageIndexer.ActualIndex == -1) ? tv.ImageIndexer.ActualIndex : ImageIndexer.ActualIndex; + } + if ((mask & NativeMethods.TVIF_SELECTEDIMAGE) != 0) + { item.iSelectedImage = (SelectedImageIndexer.ActualIndex == -1) ? tv.SelectedImageIndexer.ActualIndex : SelectedImageIndexer.ActualIndex; + } + if ((mask & NativeMethods.TVIF_STATE) != 0) { item.stateMask = NativeMethods.TVIS_STATEIMAGEMASK; @@ -2163,7 +2296,9 @@ private void UpdateNode(int mask) { Marshal.FreeHGlobal(item.pszText); if (tv.Scrollable) + { tv.ForceScrollbarUpdate(false); + } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeCollection.cs index 1265e7b4d75..b5cf4ddbe86 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeCollection.cs @@ -64,7 +64,10 @@ public virtual TreeNode this[int index] set { if (index < 0 || index >= owner.childCount) + { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); + } + value.parent = owner; value.index = index; owner.children[index] = value; @@ -249,7 +252,10 @@ public virtual void AddRange(TreeNode[] nodes) throw new ArgumentNullException(nameof(nodes)); } if (nodes.Length == 0) + { return; + } + TreeView tv = owner.TreeView; if (tv != null && nodes.Length > TreeNode.MAX_TREENODES_OPS) { @@ -338,7 +344,9 @@ private int AddInternal(TreeNode node, int delta) throw new ArgumentNullException(nameof(node)); } if (node.handle != IntPtr.Zero) + { throw new ArgumentException(string.Format(SR.OnlyOneControl, node.Text), "node"); + } // Check for ParentingCycle owner.CheckParentingCycle(node); @@ -367,7 +375,9 @@ private int AddInternal(TreeNode node, int delta) node.Realize(false); if (tv != null && node == tv.selectedNode) + { tv.SelectedNode = node; // communicate this to the handle + } if (tv != null && tv.TreeViewNodeSorter != null) { @@ -486,7 +496,9 @@ public virtual int IndexOfKey(string key) public virtual void Insert(int index, TreeNode node) { if (node.handle != IntPtr.Zero) + { throw new ArgumentException(string.Format(SR.OnlyOneControl, node.Text), "node"); + } // Check for ParentingCycle owner.CheckParentingCycle(node); @@ -500,9 +512,15 @@ public virtual void Insert(int index, TreeNode node) } if (index < 0) + { index = 0; + } + if (index > owner.childCount) + { index = owner.childCount; + } + owner.InsertNodeAt(index, node); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs index 2582a63c066..630ff549a61 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs @@ -371,22 +371,45 @@ protected override CreateParams CreateParams } if (!Scrollable) + { cp.Style |= NativeMethods.LVS_NOSCROLL; + } if (!HideSelection) + { cp.Style |= NativeMethods.TVS_SHOWSELALWAYS; + } + if (LabelEdit) + { cp.Style |= NativeMethods.TVS_EDITLABELS; + } + if (ShowLines) + { cp.Style |= NativeMethods.TVS_HASLINES; + } + if (ShowPlusMinus) + { cp.Style |= NativeMethods.TVS_HASBUTTONS; + } + if (ShowRootLines) + { cp.Style |= NativeMethods.TVS_LINESATROOT; + } + if (HotTracking) + { cp.Style |= NativeMethods.TVS_TRACKSELECT; + } + if (FullRowSelect) + { cp.Style |= NativeMethods.TVS_FULLROWSELECT; + } + if (setOddHeight) { cp.Style |= NativeMethods.TVS_NONEVENHEIGHT; @@ -403,7 +426,9 @@ protected override CreateParams CreateParams // Don't set TVS_CHECKBOXES here if the window isn't created yet. // See OnHandleCreated for explanation if (CheckBoxes && IsHandleCreated) + { cp.Style |= NativeMethods.TVS_CHECKBOXES; + } // Don't call IsMirrored from CreateParams. That will lead to some nasty problems, since // IsMirrored ends up calling CreateParams - you dig! @@ -477,7 +502,9 @@ public override Color ForeColor { base.ForeColor = value; if (IsHandleCreated) + { SendMessage(NativeMethods.TVM_SETTEXTCOLOR, 0, ColorTranslator.ToWin32(ForeColor)); + } } } @@ -1233,7 +1260,10 @@ public TreeNode SelectedNode Debug.Assert(selectedNode == null || selectedNode.TreeView != this, "handle is created, but we're still caching selectedNode"); IntPtr hItem = SendMessage(NativeMethods.TVM_GETNEXTITEM, NativeMethods.TVGN_CARET, 0); if (hItem == IntPtr.Zero) + { return null; + } + return NodeFromHandle(hItem); } else if (selectedNode != null && selectedNode.TreeView == this) @@ -1313,7 +1343,9 @@ public bool ShowNodeToolTips { treeViewState[TREEVIEWSTATE_showNodeToolTips] = value; if (ShowNodeToolTips) + { RecreateHandle(); + } } } } @@ -1508,7 +1540,9 @@ public int VisibleCount get { if (IsHandleCreated) + { return unchecked((int)(long)SendMessage(NativeMethods.TVM_GETVISIBLECOUNT, 0, 0)); + } return 0; } @@ -1776,9 +1810,13 @@ internal void ForceScrollbarUpdate(bool delayed) { SendMessage(Interop.WindowMessages.WM_SETREDRAW, 0, 0); if (delayed) + { UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), Interop.WindowMessages.WM_SETREDRAW, (IntPtr)1, IntPtr.Zero); + } else + { SendMessage(Interop.WindowMessages.WM_SETREDRAW, 1, 0); + } } } } @@ -2006,7 +2044,9 @@ internal TreeNode NodeFromHandle(IntPtr handle) protected virtual void OnDrawNode(DrawTreeNodeEventArgs e) { if (onDrawNode != null) + { onDrawNode(this, e); + } } /// @@ -2047,11 +2087,16 @@ protected override void OnHandleCreated(EventArgs e) Color c; c = BackColor; if (c != SystemColors.Window) + { SendMessage(NativeMethods.TVM_SETBKCOLOR, 0, ColorTranslator.ToWin32(c)); + } + c = ForeColor; if (c != SystemColors.WindowText) + { SendMessage(NativeMethods.TVM_SETTEXTCOLOR, 0, ColorTranslator.ToWin32(c)); + } /// put the linecolor into the native control only if Set ... if (lineColor != Color.Empty) @@ -2060,7 +2105,9 @@ protected override void OnHandleCreated(EventArgs e) } if (imageList != null) + { SendMessage(NativeMethods.TVM_SETIMAGELIST, 0, imageList.Handle); + } if (stateImageList != null) { @@ -2238,7 +2285,9 @@ protected virtual void OnBeforeLabelEdit(NodeLabelEditEventArgs e) { Contract.Requires(e != null); if (onBeforeLabelEdit != null) + { onBeforeLabelEdit(this, e); + } } /// @@ -2248,7 +2297,9 @@ protected virtual void OnAfterLabelEdit(NodeLabelEditEventArgs e) { Contract.Requires(e != null); if (onAfterLabelEdit != null) + { onAfterLabelEdit(this, e); + } } /// @@ -2258,7 +2309,9 @@ protected virtual void OnBeforeCheck(TreeViewCancelEventArgs e) { Contract.Requires(e != null); if (onBeforeCheck != null) + { onBeforeCheck(this, e); + } } /// @@ -2268,7 +2321,9 @@ protected virtual void OnAfterCheck(TreeViewEventArgs e) { Contract.Requires(e != null); if (onAfterCheck != null) + { onAfterCheck(this, e); + } } /// @@ -2278,7 +2333,9 @@ protected internal virtual void OnBeforeCollapse(TreeViewCancelEventArgs e) { Contract.Requires(e != null); if (onBeforeCollapse != null) + { onBeforeCollapse(this, e); + } } /// @@ -2288,7 +2345,9 @@ protected internal virtual void OnAfterCollapse(TreeViewEventArgs e) { Contract.Requires(e != null); if (onAfterCollapse != null) + { onAfterCollapse(this, e); + } } /// @@ -2298,7 +2357,9 @@ protected virtual void OnBeforeExpand(TreeViewCancelEventArgs e) { Contract.Requires(e != null); if (onBeforeExpand != null) + { onBeforeExpand(this, e); + } } /// @@ -2308,7 +2369,9 @@ protected virtual void OnAfterExpand(TreeViewEventArgs e) { Contract.Requires(e != null); if (onAfterExpand != null) + { onAfterExpand(this, e); + } } /// @@ -2318,7 +2381,9 @@ protected virtual void OnItemDrag(ItemDragEventArgs e) { Contract.Requires(e != null); if (onItemDrag != null) + { onItemDrag(this, e); + } } /// @@ -2328,7 +2393,9 @@ protected virtual void OnNodeMouseHover(TreeNodeMouseHoverEventArgs e) { Contract.Requires(e != null); if (onNodeMouseHover != null) + { onNodeMouseHover(this, e); + } } /// @@ -2338,7 +2405,9 @@ protected virtual void OnBeforeSelect(TreeViewCancelEventArgs e) { Contract.Requires(e != null); if (onBeforeSelect != null) + { onBeforeSelect(this, e); + } } /// @@ -2348,7 +2417,9 @@ protected virtual void OnAfterSelect(TreeViewEventArgs e) { Contract.Requires(e != null); if (onAfterSelect != null) + { onAfterSelect(this, e); + } } /// @@ -2358,7 +2429,9 @@ protected virtual void OnNodeMouseClick(TreeNodeMouseClickEventArgs e) { Contract.Requires(e != null); if (onNodeMouseClick != null) + { onNodeMouseClick(this, e); + } } /// @@ -2368,7 +2441,9 @@ protected virtual void OnNodeMouseDoubleClick(TreeNodeMouseClickEventArgs e) { Contract.Requires(e != null); if (onNodeMouseDoubleClick != null) + { onNodeMouseDoubleClick(this, e); + } } /// @@ -2378,7 +2453,9 @@ protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (e.Handled) + { return; + } // if it's a space, send the check notifications and toggle the checkbox if we're not // cancelled. if (CheckBoxes && (e.KeyData & Keys.KeyCode) == Keys.Space) @@ -2405,7 +2482,9 @@ protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); if (e.Handled) + { return; + } // eat the space key if ((e.KeyData & Keys.KeyCode) == Keys.Space) { @@ -2421,10 +2500,14 @@ protected override void OnKeyPress(KeyPressEventArgs e) { base.OnKeyPress(e); if (e.Handled) + { return; + } // eat the space key if (e.KeyChar == ' ') + { e.Handled = true; + } } @@ -2537,7 +2620,9 @@ public override string ToString() { s += ", Nodes.Count: " + Nodes.Count.ToString(CultureInfo.CurrentCulture); if (Nodes.Count > 0) + { s += ", Nodes[0]: " + Nodes[0].ToString(); + } } return s; } @@ -2667,7 +2752,9 @@ private unsafe void TvnSelected(NativeMethods.NMTREEVIEW* nmtv) if (nmtv->itemOld.hItem != IntPtr.Zero) { if (unchecked((int)(long)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TVM_GETITEMRECT, 1, ref rc)) != 0) + { SafeNativeMethods.InvalidateRect(new HandleRef(this, Handle), ref rc, true); + } } } @@ -2684,7 +2771,10 @@ private IntPtr TvnBeginLabelEdit(NativeMethods.NMTVDISPINFO nmtvdi) NodeLabelEditEventArgs e = new NodeLabelEditEventArgs(editingNode); OnBeforeLabelEdit(e); if (!e.CancelEdit) + { editNode = editingNode; + } + return (IntPtr)(e.CancelEdit ? 1 : 0); } @@ -2706,7 +2796,9 @@ private IntPtr TvnEndLabelEdit(NativeMethods.NMTVDISPINFO nmtvdi) { node.text = newText; if (Scrollable) + { ForceScrollbarUpdate(true); + } } return (IntPtr)(e.CancelEdit ? 0 : 1); } @@ -2998,7 +3090,9 @@ protected OwnerDrawPropertyBag GetItemRenderStyles(TreeNode node, int state) { OwnerDrawPropertyBag retval = new OwnerDrawPropertyBag(); if (node == null || node.propBag == null) + { return retval; + } // we only change colors if we're displaying things normally if ((state & (NativeMethods.CDIS_SELECTED | NativeMethods.CDIS_GRAYED | NativeMethods.CDIS_HOT | NativeMethods.CDIS_DISABLED)) == 0) @@ -3443,7 +3537,10 @@ protected override void WndProc(ref Message m) } } if (!treeViewState[TREEVIEWSTATE_mouseUpFired]) + { OnMouseUp(new MouseEventArgs(downButton, 1, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); + } + treeViewState[TREEVIEWSTATE_doubleclickFired] = false; treeViewState[TREEVIEWSTATE_mouseUpFired] = false; CaptureInternal = false; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Triangle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Triangle.cs index a8af7591537..e55cc438c3a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Triangle.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Triangle.cs @@ -45,7 +45,10 @@ public static void Paint(Graphics g, Rectangle bounds, TriangleDirection dir, Br Point[] points = BuildTrianglePoints(dir, bounds); if (opaque) + { g.FillPolygon(backBr, points); + } + g.DrawLine(backPen1, points[0], points[1]); g.DrawLine(backPen2, points[1], points[2]); g.DrawLine(backPen3, points[2], points[0]); @@ -58,12 +61,18 @@ private static Point[] BuildTrianglePoints(TriangleDirection dir, int updnWidth = (int)(bounds.Width * TRI_WIDTH_RATIO); if (updnWidth % 2 == 1) + { updnWidth++; + } + int updnHeight = (int)Math.Ceiling((updnWidth / 2) * TRI_HEIGHT_RATIO); int lrWidth = (int)(bounds.Height * TRI_WIDTH_RATIO); if (lrWidth % 2 == 0) + { lrWidth++; + } + int lrHeight = (int)Math.Ceiling((lrWidth / 2) * TRI_HEIGHT_RATIO); switch (dir) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs index 9e250b3828c..3c20157657f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs @@ -1103,9 +1103,13 @@ private void OnUpDown(object source, UpDownEventArgs e) { // Modify the value if (e.ButtonID == (int)ButtonID.Up) + { UpButton(); + } else if (e.ButtonID == (int)ButtonID.Down) + { DownButton(); + } } /// @@ -1833,7 +1837,9 @@ protected override void OnPaint(PaintEventArgs e) protected virtual void OnUpDown(UpDownEventArgs upevent) { if (upDownEventHandler != null) + { upDownEventHandler(this, upevent); + } } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/UserControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/UserControl.cs index 2b9bf29734f..f3c0415fb60 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/UserControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/UserControl.cs @@ -280,15 +280,21 @@ public override bool ValidateChildren(ValidationConstraints validationConstraint private bool FocusInside() { if (!IsHandleCreated) + { return false; + } IntPtr hwndFocus = UnsafeNativeMethods.GetFocus(); if (hwndFocus == IntPtr.Zero) + { return false; + } IntPtr hwnd = Handle; if (hwnd == hwndFocus || SafeNativeMethods.IsChild(new HandleRef(this, hwnd), new HandleRef(null, hwndFocus))) + { return true; + } return false; } @@ -314,7 +320,9 @@ protected virtual void OnLoad(EventArgs e) // that it's just another name for OnControlCreated. EventHandler handler = (EventHandler)Events[EVENT_LOAD]; if (handler != null) + { handler(this, e); + } } /// @@ -333,7 +341,10 @@ protected override void OnResize(EventArgs e) protected override void OnMouseDown(MouseEventArgs e) { if (!FocusInside()) + { Focus(); + } + base.OnMouseDown(e); } @@ -342,7 +353,9 @@ private void WmSetFocus(ref Message m) if (!HostedInWin32DialogManager) { if (ActiveControl == null) + { SelectNextControl(null, true, true, true, false); + } } if (!ValidationCancelled) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs index ecccf3f8c04..421da3cb962 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs @@ -427,7 +427,10 @@ protected override void WndProc(ref Message m) case Interop.WindowMessages.WM_COMMAND: if (!ReflectMessage(m.LParam, ref m)) + { DefWndProc(ref m); + } + break; case Interop.WindowMessages.WM_HELP: @@ -1330,7 +1333,9 @@ internal ContainerControl FindContainerControlInternal() { ContainerControl tempCC = control as ContainerControl; if (tempCC != null) + { cc = tempCC; + } } if (cc == null) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs index db9c04611cb..70231489da1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs @@ -33,7 +33,10 @@ internal WebBrowserContainer(WebBrowserBase parent) int UnsafeNativeMethods.IOleContainer.ParseDisplayName(object pbc, string pszDisplayName, int[] pchEaten, object[] ppmkOut) { if (ppmkOut != null) + { ppmkOut[0] = null; + } + return NativeMethods.E_NOTIMPL; } @@ -231,7 +234,10 @@ private IContainer GetParentIContainer() { ISite site = parent.Site; if (site != null && site.DesignMode) + { return site.Container; + } + return null; } @@ -287,7 +293,9 @@ private void FillComponentsTable(IContainer container) private void GetAllChildren(Control ctl) { if (ctl == null) + { return; + } if (components == null) { @@ -295,7 +303,9 @@ private void GetAllChildren(Control ctl) } if (ctl != parent && !components.Contains(ctl)) + { components.Add(ctl, ctl); + } foreach (Control c in ctl.Controls) { @@ -345,7 +355,9 @@ private void OnComponentRemoved(object sender, ComponentEventArgs e) internal void AddControl(Control ctl) { if (containerCache.Contains(ctl)) + { throw new ArgumentException(string.Format(SR.AXDuplicateControl, GetNameForControl(ctl)), "ctl"); + } containerCache.Add(ctl, ctl); @@ -404,7 +416,9 @@ internal void OnUIActivate(WebBrowserBase site) // site. This causes the assert below to fire. // if (siteUIActive == site) + { return; + } if (siteUIActive != null && siteUIActive != site) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs index 8f8d5382774..ceb2c607400 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs @@ -354,7 +354,9 @@ void UnsafeNativeMethods.IPropertyNotifySink.OnChanged(int dispid) // To prevent this kind of recursion, we check to see if we are already inside a OnChanged() call. // if (Host.NoComponentChangeEvents != 0) + { return; + } Host.NoComponentChangeEvents++; try @@ -430,7 +432,9 @@ internal WebBrowserBase GetAXHost() internal void StartEvents() { if (connectionPoint != null) + { return; + } object nativeObject = Host.activeXInstance; if (nativeObject != null) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs b/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs index 151183d8e4a..ec3b57cfb3e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs @@ -673,7 +673,9 @@ protected virtual void OnImeModeChanged(EventArgs e) Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside OnImeModeChanged(), this = " + this); EventHandler handler = (EventHandler)Events[EventImeModeChanged]; if (handler != null) + { handler(this, e); + } } /// @@ -805,7 +807,10 @@ private void WmImeNotify(ref Message m) // If this is the first time here after conversion to chinese language, wait for WmInputLanguageChange // before listening to WmImeNotifys. if ((inputLanguageTable == ImeModeConversion.ChineseTable) && !lastLanguageChinese) + { IgnoreWmImeNotify = true; + } + lastLanguageChinese = (inputLanguageTable == ImeModeConversion.ChineseTable); if (ImeSupported && inputLanguageTable != ImeModeConversion.UnsupportedTable && !IgnoreWmImeNotify) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/formatter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/formatter.cs index e88ab4d45cb..2b0a62e68c1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/formatter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/formatter.cs @@ -538,8 +538,9 @@ public static object NullData(Type type, object dataSourceNullValue) private static Type NullableUnwrap(Type type) { if (type == stringType) // ...performance optimization for the most common case + { return stringType; - + } Type underlyingType = Nullable.GetUnderlyingType(type); return underlyingType ?? type; diff --git a/src/System.Windows.Forms/src/misc/ImageListUtils.cs b/src/System.Windows.Forms/src/misc/ImageListUtils.cs index 318f2249621..4215cd296e9 100644 --- a/src/System.Windows.Forms/src/misc/ImageListUtils.cs +++ b/src/System.Windows.Forms/src/misc/ImageListUtils.cs @@ -16,7 +16,9 @@ static internal class ImageListUtils public static PropertyDescriptor GetImageListProperty(PropertyDescriptor currentComponent, ref object instance) { if (instance is object[]) //multiple selection is not supported by this class + { return null; + } PropertyDescriptor imageListProp = null; object parentInstance = instance; diff --git a/src/System.Windows.Forms/src/misc/InvariantComparer.cs b/src/System.Windows.Forms/src/misc/InvariantComparer.cs index 9a2e0f4eec4..2b459412083 100644 --- a/src/System.Windows.Forms/src/misc/InvariantComparer.cs +++ b/src/System.Windows.Forms/src/misc/InvariantComparer.cs @@ -24,9 +24,13 @@ public int Compare(object a, object b) string sa = a as string; string sb = b as string; if (sa != null && sb != null) + { return m_compareInfo.Compare(sa, sb); + } else + { return Comparer.Default.Compare(a, b); + } } } } From 462c242a074b16c90da77f43975955b5b552c7e4 Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Fri, 24 May 2019 12:29:26 -0700 Subject: [PATCH 16/27] remove all instances of IDE0019 warning - use pattern matching (as if becomes is) --- src/Common/src/ClientUtils.cs | 4 +- src/Common/src/UnsafeNativeMethods.cs | 6 +- src/Common/tests/CommonMemberDataAttribute.cs | 3 +- .../src/Misc/DpiHelper.cs | 3 +- .../ComponentModel/Design/DesignSurface.cs | 3 +- .../Design/InheritedPropertyDescriptor.cs | 3 +- .../Serialization/CodeDomSerializerBase.cs | 51 +-- .../ComponentCodeDomSerializer.cs | 16 +- .../ComponentTypeCodeDomSerializer.cs | 7 +- .../ContainerCodeDomSerializer.cs | 6 +- .../EventMemberCodeDomSerializer.cs | 4 +- .../PrimitiveCodeDomSerializer.cs | 3 +- .../PropertyMemberCodeDomSerializer.cs | 22 +- .../Forms/Design/BaseContextMenuStrip.cs | 6 +- .../Windows/Forms/Design/DesignerActionUI.cs | 3 +- .../TemplateNodeCustomMenuItemCollection.cs | 3 +- .../Forms/Design/ToolStripDropDownDesigner.cs | 3 +- .../ToolStripItemCustomMenuItemCollection.cs | 3 +- .../Forms/Design/ToolStripItemDesigner.cs | 3 +- .../Forms/Design/ToolStripMenuItemDesigner.cs | 21 +- .../System/Windows/Forms/Design/UndoEngine.cs | 3 +- .../src/System/Windows/Forms/Application.cs | 16 +- .../src/System/Windows/Forms/AxHost.cs | 39 +- .../src/System/Windows/Forms/Binding.cs | 3 +- .../System/Windows/Forms/BindingNavigator.cs | 7 +- .../src/System/Windows/Forms/BindingSource.cs | 10 +- .../CheckableControlBaseAdapter.cs | 6 +- .../src/System/Windows/Forms/CheckBox.cs | 3 +- .../src/System/Windows/Forms/Clipboard.cs | 6 +- .../src/System/Windows/Forms/ComboBox.cs | 33 +- .../COM2Interop/COM2FontConverter.cs | 3 +- .../COM2IPerPropertyBrowsingHandler.cs | 3 +- .../COM2IProvidePropertyBuilderHandler.cs | 4 +- .../COM2IVsPerPropertyBrowsingHandler.cs | 4 +- .../COM2Interop/ComNativeDescriptor.cs | 5 +- .../System/Windows/Forms/ContainerControl.cs | 8 +- .../src/System/Windows/Forms/Control.cs | 141 ++---- .../System/Windows/Forms/CurrencyManager.cs | 15 +- .../src/System/Windows/Forms/DataGrid.cs | 30 +- .../Windows/Forms/DataGridBoolColumn.cs | 9 +- .../src/System/Windows/Forms/DataGridTable.cs | 60 +-- .../src/System/Windows/Forms/DataGridView.cs | 3 +- .../Forms/DataGridViewAdvancedBorderStyle.cs | 4 +- .../System/Windows/Forms/DataGridViewBand.cs | 3 +- .../Windows/Forms/DataGridViewButtonColumn.cs | 9 +- .../System/Windows/Forms/DataGridViewCell.cs | 6 +- .../Forms/DataGridViewCellConverter.cs | 3 +- .../Windows/Forms/DataGridViewCellStyle.cs | 3 +- .../Windows/Forms/DataGridViewCheckBoxCell.cs | 3 +- .../Forms/DataGridViewCheckBoxColumn.cs | 18 +- .../Windows/Forms/DataGridViewColumn.cs | 3 +- .../Forms/DataGridViewColumnConverter.cs | 3 +- ...ridViewColumnDesignTimeVisibleAttribute.cs | 3 +- .../Windows/Forms/DataGridViewComboBoxCell.cs | 27 +- .../Forms/DataGridViewComboBoxColumn.cs | 33 +- .../DataGridViewComboBoxEditingControl.cs | 6 +- .../Forms/DataGridViewDataConnection.cs | 18 +- .../Windows/Forms/DataGridViewHitTestInfo.cs | 3 +- .../Windows/Forms/DataGridViewImageCell.cs | 12 +- .../Windows/Forms/DataGridViewImageColumn.cs | 12 +- .../Windows/Forms/DataGridViewLinkCell.cs | 3 +- .../Windows/Forms/DataGridViewLinkColumn.cs | 21 +- .../Windows/Forms/DataGridViewMethods.cs | 423 ++++++------------ .../Forms/DataGridViewRowCollection.cs | 6 +- .../Windows/Forms/DataGridViewTextBoxCell.cs | 12 +- .../Forms/DataGridViewTextBoxColumn.cs | 3 +- .../DataGridViewTextBoxEditingControl.cs | 3 +- .../src/System/Windows/Forms/DataObject.cs | 13 +- .../System/Windows/Forms/DateTimePicker.cs | 3 +- .../System/Windows/Forms/DockingAttribute.cs | 3 +- .../src/System/Windows/Forms/ErrorProvider.cs | 9 +- .../System/Windows/Forms/FlowLayoutPanel.cs | 3 +- .../src/System/Windows/Forms/Form.cs | 21 +- .../src/System/Windows/Forms/Help.cs | 6 +- .../src/System/Windows/Forms/HtmlDocument.cs | 6 +- .../src/System/Windows/Forms/HtmlElement.cs | 18 +- .../Windows/Forms/HtmlElementCollection.cs | 8 +- .../src/System/Windows/Forms/HtmlWindow.cs | 9 +- .../Windows/Forms/HtmlWindowCollection.cs | 4 +- .../Windows/Forms/ImageIndexConverter.cs | 3 +- .../src/System/Windows/Forms/ImageList.cs | 3 +- .../src/System/Windows/Forms/Label.cs | 7 +- .../Forms/Layout/ArrangedElementCollection.cs | 4 +- .../Windows/Forms/Layout/CommonProperties.cs | 3 +- .../Forms/Layout/DockAndAnchorLayout.cs | 4 +- .../System/Windows/Forms/Layout/FlowLayout.cs | 10 +- .../Windows/Forms/Layout/TableLayout.cs | 9 +- .../System/Windows/Forms/ListBindingHelper.cs | 9 +- .../src/System/Windows/Forms/ListView.cs | 3 +- .../Windows/Forms/ListViewGroupConverter.cs | 3 +- .../System/Windows/Forms/MDIControlStrip.cs | 6 +- .../src/System/Windows/Forms/MaskedTextBox.cs | 17 +- .../Forms/MdiWindowListItemConverter.cs | 6 +- .../Windows/Forms/MdiWindowListStrip.cs | 4 +- .../src/System/Windows/Forms/PictureBox.cs | 3 +- .../Forms/Printing/PrintPreviewControl.cs | 3 +- .../Forms/Printing/PrintPreviewDialog.cs | 8 +- .../src/System/Windows/Forms/PropertyGrid.cs | 19 +- .../Forms/PropertyGridInternal/DocComment.cs | 3 +- .../Forms/PropertyGridInternal/HotCommands.cs | 3 +- .../MergePropertyDescriptor.cs | 8 +- .../MultiPropertyDescriptorGridEntry.cs | 14 +- .../PropertyDescriptorGridEntry.cs | 8 +- .../PropertyGridInternal/PropertyGridView.cs | 25 +- .../src/System/Windows/Forms/RadioButton.cs | 3 +- .../Windows/Forms/SelectionRangeConverter.cs | 3 +- .../System/Windows/Forms/SplitContainer.cs | 18 +- .../src/System/Windows/Forms/StatusStrip.cs | 20 +- .../src/System/Windows/Forms/TabControl.cs | 3 +- .../src/System/Windows/Forms/TabPage.cs | 25 +- .../System/Windows/Forms/TableLayoutPanel.cs | 3 +- .../Windows/Forms/TableLayoutSettings.cs | 9 +- .../System/Windows/Forms/TableLayoutStyle.cs | 6 +- .../src/System/Windows/Forms/TextBox.cs | 3 +- .../src/System/Windows/Forms/TextBoxBase.cs | 21 +- .../Windows/Forms/ThreadExceptionDialog.cs | 4 +- .../src/System/Windows/Forms/ToolStrip.cs | 27 +- .../System/Windows/Forms/ToolStripComboBox.cs | 15 +- .../Windows/Forms/ToolStripContainer.cs | 3 +- .../Windows/Forms/ToolStripControlHost.cs | 3 +- .../System/Windows/Forms/ToolStripDropDown.cs | 9 +- .../Windows/Forms/ToolStripDropDownButton.cs | 3 +- .../Windows/Forms/ToolStripDropDownItem.cs | 16 +- .../Windows/Forms/ToolStripDropDownMenu.cs | 6 +- .../Forms/ToolStripHighContrastRenderer.cs | 6 +- .../src/System/Windows/Forms/ToolStripItem.cs | 48 +- .../Windows/Forms/ToolStripItemCollection.cs | 6 +- .../System/Windows/Forms/ToolStripManager.cs | 42 +- .../System/Windows/Forms/ToolStripMenuItem.cs | 45 +- .../System/Windows/Forms/ToolStripPanel.cs | 14 +- .../System/Windows/Forms/ToolStripPanelRow.cs | 22 +- .../Windows/Forms/ToolStripProgressBar.cs | 16 +- .../System/Windows/Forms/ToolStripRenderer.cs | 66 +-- .../Forms/ToolStripRendererSwitcher.cs | 3 +- .../Windows/Forms/ToolStripScrollButton.cs | 3 +- .../Windows/Forms/ToolStripSeparator.cs | 10 +- .../System/Windows/Forms/ToolStripSettings.cs | 3 +- .../Windows/Forms/ToolStripSplitButton.cs | 3 +- .../System/Windows/Forms/ToolStripTextBox.cs | 16 +- .../src/System/Windows/Forms/ToolTip.cs | 45 +- .../Forms/ToolstripProfessionalRenderer.cs | 15 +- .../src/System/Windows/Forms/TrackBar.cs | 6 +- .../Forms/TreeViewImageIndexConverter.cs | 4 +- .../Forms/TreeViewImageKeyConverter.cs | 3 +- .../src/System/Windows/Forms/UpDownBase.cs | 3 +- .../System/Windows/Forms/WebBrowserBase.cs | 3 +- .../Windows/Forms/WebBrowserContainer.cs | 12 +- .../WindowsFormsSynchronizationContext.cs | 3 +- .../src/System/Windows/Forms/formatter.cs | 7 +- .../src/misc/CompatibleIComparer.cs | 3 +- .../src/misc/GDI/DeviceContexts.cs | 7 +- .../src/misc/GDI/WindowsFont.cs | 4 +- .../src/misc/GDI/WindowsGraphics.cs | 4 +- .../src/misc/ImageListUtils.cs | 3 +- .../src/misc/InvariantComparer.cs | 4 +- .../src/misc/WeakHashtable.cs | 10 +- 156 files changed, 690 insertions(+), 1461 deletions(-) diff --git a/src/Common/src/ClientUtils.cs b/src/Common/src/ClientUtils.cs index 59b4be1b661..6940d36f20c 100644 --- a/src/Common/src/ClientUtils.cs +++ b/src/Common/src/ClientUtils.cs @@ -376,9 +376,7 @@ public object this[int index] { get { - WeakRefObject weakRef = InnerList[index] as WeakRefObject; - - if ((weakRef != null) && (weakRef.IsAlive)) + if ((InnerList[index] is WeakRefObject weakRef) && (weakRef.IsAlive)) { return weakRef.Target; } diff --git a/src/Common/src/UnsafeNativeMethods.cs b/src/Common/src/UnsafeNativeMethods.cs index 42ecaae8a5d..06804a0193f 100644 --- a/src/Common/src/UnsafeNativeMethods.cs +++ b/src/Common/src/UnsafeNativeMethods.cs @@ -199,8 +199,7 @@ public static bool PrintDlg([In, Out] NativeMethods.PRINTDLG lppd) { if (IntPtr.Size == 4) { - NativeMethods.PRINTDLG_32 lppd_32 = lppd as NativeMethods.PRINTDLG_32; - if (lppd_32 == null) + if (!(lppd is NativeMethods.PRINTDLG_32 lppd_32)) { throw new System.NullReferenceException("PRINTDLG data is null"); } @@ -208,8 +207,7 @@ public static bool PrintDlg([In, Out] NativeMethods.PRINTDLG lppd) } else { - NativeMethods.PRINTDLG_64 lppd_64 = lppd as NativeMethods.PRINTDLG_64; - if (lppd_64 == null) + if (!(lppd is NativeMethods.PRINTDLG_64 lppd_64)) { throw new System.NullReferenceException("PRINTDLG data is null"); } diff --git a/src/Common/tests/CommonMemberDataAttribute.cs b/src/Common/tests/CommonMemberDataAttribute.cs index 471b13947ba..5065cba6a36 100644 --- a/src/Common/tests/CommonMemberDataAttribute.cs +++ b/src/Common/tests/CommonMemberDataAttribute.cs @@ -28,8 +28,7 @@ protected override object[] ConvertDataItem(MethodInfo testMethod, object item) return null; } - var array = item as object[]; - if (array == null) + if (!(item is object[] array)) { throw new ArgumentException($"Property {MemberName} on {MemberType ?? testMethod.DeclaringType} yielded an item that is not an object[]"); } diff --git a/src/System.Windows.Forms.Design.Editors/src/Misc/DpiHelper.cs b/src/System.Windows.Forms.Design.Editors/src/Misc/DpiHelper.cs index da0789cbda9..063ece29512 100644 --- a/src/System.Windows.Forms.Design.Editors/src/Misc/DpiHelper.cs +++ b/src/System.Windows.Forms.Design.Editors/src/Misc/DpiHelper.cs @@ -564,8 +564,7 @@ public static void ScaleButtonImageLogicalToDevice(Button button) { return; } - Bitmap buttonBitmap = button.Image as Bitmap; - if (buttonBitmap == null) + if (!(button.Image is Bitmap buttonBitmap)) { return; } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignSurface.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignSurface.cs index 73db427695b..d446658c655 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignSurface.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignSurface.cs @@ -178,8 +178,7 @@ public object View throw ex; } - IRootDesigner rootDesigner = ((IDesignerHost)_host).GetDesigner(rootComponent) as IRootDesigner; - if (rootDesigner == null) + if (!(((IDesignerHost)_host).GetDesigner(rootComponent) is IRootDesigner rootDesigner)) { ex = new InvalidOperationException(SR.DesignSurfaceDesignerNotLoaded) { diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/InheritedPropertyDescriptor.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/InheritedPropertyDescriptor.cs index 3108c49e0f4..8f8061472a2 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/InheritedPropertyDescriptor.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/InheritedPropertyDescriptor.cs @@ -41,8 +41,7 @@ internal class InheritedPropertyDescriptor : PropertyDescriptor if (typeof(ICollection).IsAssignableFrom(propertyDescriptor.PropertyType) && propertyDescriptor.Attributes.Contains(DesignerSerializationVisibilityAttribute.Content)) { - ICollection collection = propertyDescriptor.GetValue(component) as ICollection; - if (collection != null && collection.Count > 0) + if (propertyDescriptor.GetValue(component) is ICollection collection && collection.Count > 0) { // Trawl Add and AddRange methods looking for the first compatible serializable method. All we need is the data type. bool addComponentExists = false; diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs index b5d0738ce66..ea20bc3d9f7 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs @@ -173,9 +173,8 @@ internal static void Error(IDesignerSerializationManager manager, string excepti private static TypeDescriptionProvider GetTargetFrameworkProviderForType(IServiceProvider provider, Type type) { - TypeDescriptionProviderService service = provider.GetService(typeof(TypeDescriptionProviderService)) as TypeDescriptionProviderService; // service will be null outside the VisualStudio - if (service != null) + if (provider.GetService(typeof(TypeDescriptionProviderService)) is TypeDescriptionProviderService service) { return service.GetProvider(type); } @@ -678,17 +677,13 @@ private void DeserializeAssignStatement(IDesignerSerializationManager manager, C // Since we're doing an assignment into something, we need to know what that something is. It can be a property, a variable, or a member. Anything else is invalid. //Perf: is -> as changes, change ordering based on possibility of occurence CodeExpression expression = statement.Left; - CodePropertyReferenceExpression propertyReferenceEx; - CodeFieldReferenceExpression fieldReferenceEx; - CodeVariableReferenceExpression variableReferenceEx; - CodeArrayIndexerExpression arrayIndexerEx; Trace("Processing LHS"); - if ((propertyReferenceEx = expression as CodePropertyReferenceExpression) != null) + if (expression is CodePropertyReferenceExpression propertyReferenceEx) { DeserializePropertyAssignStatement(manager, statement, propertyReferenceEx, true); } - else if ((fieldReferenceEx = expression as CodeFieldReferenceExpression) != null) + else if (expression is CodeFieldReferenceExpression fieldReferenceEx) { Trace("LHS is field : {0}", fieldReferenceEx.FieldName); object lhs = DeserializeExpression(manager, fieldReferenceEx.FieldName, fieldReferenceEx.TargetObject); @@ -778,7 +773,7 @@ private void DeserializeAssignStatement(IDesignerSerializationManager manager, C TraceWarning("Could not find target object for field {0}", fieldReferenceEx.FieldName); } } - else if ((variableReferenceEx = expression as CodeVariableReferenceExpression) != null) + else if (expression is CodeVariableReferenceExpression variableReferenceEx) { // This is the easiest. Just relate the RHS object to the name of the variable. Trace("Processing RHS"); @@ -790,7 +785,7 @@ private void DeserializeAssignStatement(IDesignerSerializationManager manager, C } manager.SetName(rhs, variableReferenceEx.VariableName); } - else if ((arrayIndexerEx = expression as CodeArrayIndexerExpression) != null) + else if (expression is CodeArrayIndexerExpression arrayIndexerEx) { int[] indexes = new int[arrayIndexerEx.Indices.Count]; Trace("LHS is Array Indexer with dims {0}", indexes.Length); @@ -873,7 +868,6 @@ protected object DeserializeExpression(IDesignerSerializationManager manager, st { // Perf: is -> as changes, change ordering based on possibility of occurance // If you are adding to this, use as instead of is + cast and order new expressions in order of frequency in typical user code. - CodePrimitiveExpression primitiveEx; CodePropertyReferenceExpression propertyReferenceEx; CodeTypeReferenceExpression typeReferenceEx; CodeObjectCreateExpression objectCreateEx; @@ -893,7 +887,7 @@ protected object DeserializeExpression(IDesignerSerializationManager manager, st while (result != null) { - if ((primitiveEx = result as CodePrimitiveExpression) != null) + if (result is CodePrimitiveExpression primitiveEx) { Trace("Primitive. Value: {0}", (primitiveEx.Value == null ? "(null)" : primitiveEx.Value)); result = primitiveEx.Value; @@ -1123,9 +1117,8 @@ protected object DeserializeExpression(IDesignerSerializationManager manager, st // We did not find the method directly. Let's see if we can find it // as an private implemented interface name. // - CodeCastExpression castExpr = methodInvokeEx.Method.TargetObject as CodeCastExpression; - if (castExpr != null) + if (methodInvokeEx.Method.TargetObject is CodeCastExpression castExpr) { Type castType = manager.GetType(GetTypeNameFromCodeTypeReference(manager, castExpr.TargetType)); @@ -1246,9 +1239,8 @@ protected object DeserializeExpression(IDesignerSerializationManager manager, st { object o = DeserializeExpression(manager, name, arrayCreateEx.SizeExpression); Debug.Assert(o is IConvertible, "Array size expression could not be resolved to IConvertible: " + (o == null ? "(null)" : o.GetType().Name)); - IConvertible ic = o as IConvertible; - if (ic != null) + if (o is IConvertible ic) { int size = ic.ToInt32(null); Trace("Initialized with expression that simplified to {0}", size); @@ -1284,9 +1276,8 @@ protected object DeserializeExpression(IDesignerSerializationManager manager, st // result = null; - Array array = DeserializeExpression(manager, name, arrayIndexerEx.TargetObject) as Array; - if (array != null) + if (DeserializeExpression(manager, name, arrayIndexerEx.TargetObject) is Array array) { int[] indexes = new int[arrayIndexerEx.Indices.Count]; @@ -1334,10 +1325,7 @@ protected object DeserializeExpression(IDesignerSerializationManager manager, st // result = left; - IConvertible icLeft = left as IConvertible; - IConvertible icRight = right as IConvertible; - - if (icLeft != null && icRight != null) + if (left is IConvertible icLeft && right is IConvertible icRight) { result = ExecuteBinaryExpression(icLeft, icRight, binaryOperatorEx.Operator); } @@ -1958,9 +1946,8 @@ private bool DeserializePropertyAssignStatement(IDesignerSerializationManager ma return false; } - IConvertible ic = rhs as IConvertible; - if (ic != null && p.PropertyType != rhs.GetType()) + if (rhs is IConvertible ic && p.PropertyType != rhs.GetType()) { try { @@ -2087,9 +2074,8 @@ protected CodeExpression GetExpression(IDesignerSerializationManager manager, ob Trace("GetExpression called for object {0}", value.ToString()); // Is the expression part of a prior SetExpression call? - ExpressionTable table = manager.Context[typeof(ExpressionTable)] as ExpressionTable; - if (table != null) + if (manager.Context[typeof(ExpressionTable)] is ExpressionTable table) { expression = table.GetExpression(value); TraceIf(expression != null, "Resolved through expression table : {0}", expression); @@ -2098,9 +2084,7 @@ protected CodeExpression GetExpression(IDesignerSerializationManager manager, ob // Check to see if this object represents the root context. if (expression == null) { - RootContext rootEx = manager.Context[typeof(RootContext)] as RootContext; - - if (rootEx != null && object.ReferenceEquals(rootEx.Value, value)) + if (manager.Context[typeof(RootContext)] is RootContext rootEx && object.ReferenceEquals(rootEx.Value, value)) { expression = rootEx.Expression; TraceIf(expression != null, "Resolved through root expression context : {0}", expression); @@ -2118,8 +2102,7 @@ protected CodeExpression GetExpression(IDesignerSerializationManager manager, ob string objectName = manager.GetName(value); if (objectName == null || objectName.IndexOf('.') != -1) { - IReferenceService refSvc = manager.GetService(typeof(IReferenceService)) as IReferenceService; - if (refSvc != null) + if (manager.GetService(typeof(IReferenceService)) is IReferenceService refSvc) { objectName = refSvc.GetName(value); if (objectName != null && objectName.IndexOf('.') != -1) @@ -2157,8 +2140,7 @@ protected CodeExpression GetExpression(IDesignerSerializationManager manager, ob // Finally, the expression context. if (expression == null) { - ExpressionContext cxt = manager.Context[typeof(ExpressionContext)] as ExpressionContext; - if (cxt != null && object.ReferenceEquals(cxt.PresetValue, value)) + if (manager.Context[typeof(ExpressionContext)] is ExpressionContext cxt && object.ReferenceEquals(cxt.PresetValue, value)) { expression = cxt.Expression; } @@ -2668,9 +2650,8 @@ protected void SerializeProperties(IDesignerSerializationManager manager, CodeSt } private PropertyDescriptorCollection GetFilteredProperties(IDesignerSerializationManager manager, object value, Attribute[] filter) { - IComponent comp = value as IComponent; PropertyDescriptorCollection props = GetPropertiesHelper(manager, value, filter); - if (comp != null) + if (value is IComponent comp) { if (((IDictionary)props).IsReadOnly) { diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentCodeDomSerializer.cs index 923d967097a..ffaa00de7ad 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentCodeDomSerializer.cs @@ -64,14 +64,11 @@ private Type[] GetContainerConstructor(IDesignerSerializationManager manager) /// private bool CanCacheComponent(IDesignerSerializationManager manager, object value, PropertyDescriptorCollection props) { - IComponent comp = value as IComponent; - - if (comp != null) + if (value is IComponent comp) { if (comp.Site != null) { - INestedSite nestedSite = comp.Site as INestedSite; - if (nestedSite != null && !string.IsNullOrEmpty(nestedSite.FullName)) + if (comp.Site is INestedSite nestedSite && !string.IsNullOrEmpty(nestedSite.FullName)) { return false; } @@ -190,15 +187,13 @@ public override object Serialize(IDesignerSerializationManager manager, object v // if we have an existing expression and this is not // a sited component, do not serialize it. We need this for Everett / 1.0 // backwards compat (even though it's wrong). - IComponent comp = value as IComponent; - if (comp != null && comp.Site == null) + if (value is IComponent comp && comp.Site == null) { // We were in a serialize content // property and would still serialize it. This code reverses what the // outer if block does for this specific case. We also need this // for Everett / 1.0 backwards compat. - ExpressionContext expCxt = manager.Context[typeof(ExpressionContext)] as ExpressionContext; - if (expCxt == null || expCxt.PresetValue != value) + if (!(manager.Context[typeof(ExpressionContext)] is ExpressionContext expCxt) || expCxt.PresetValue != value) { isComplete = true; } @@ -476,8 +471,7 @@ public override object Serialize(IDesignerSerializationManager manager, object v foreach (CodeStatement statement in entry.Statements) { - CodeVariableDeclarationStatement local = statement as CodeVariableDeclarationStatement; - if (local != null) + if (statement is CodeVariableDeclarationStatement local) { entry.Tracking = true; break; diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentTypeCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentTypeCodeDomSerializer.cs index e0b0d37361c..d479061d5b6 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentTypeCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentTypeCodeDomSerializer.cs @@ -54,9 +54,8 @@ protected override CodeMemberMethod GetInitializeMethod(IDesignerSerializationMa throw new ArgumentNullException(nameof(value)); } - CodeMemberMethod method = typeDecl.UserData[_initMethodKey] as CodeMemberMethod; - if (method == null) + if (!(typeDecl.UserData[_initMethodKey] is CodeMemberMethod method)) { method = new CodeMemberMethod { @@ -93,13 +92,11 @@ protected override CodeMemberMethod[] GetInitializeMethods(IDesignerSerializatio foreach (CodeTypeMember member in typeDecl.Members) { - CodeMemberMethod method = member as CodeMemberMethod; - // Note: the order is important here for performance! // method.Parameters causes OnMethodPopulateParameters callback and therefore it is much more // expensive than method.Name.Equals - if (method != null && method.Name.Equals(_initMethodName) && method.Parameters.Count == 0) + if (member is CodeMemberMethod method && method.Name.Equals(_initMethodName) && method.Parameters.Count == 0) { return new CodeMemberMethod[] { diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ContainerCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ContainerCodeDomSerializer.cs index 22b01e909e4..72faba9f077 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ContainerCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ContainerCodeDomSerializer.cs @@ -64,14 +64,10 @@ protected override object DeserializeInstance(IDesignerSerializationManager mana /// public override object Serialize(IDesignerSerializationManager manager, object value) { - // See if there is a type declaration on the stack. If there is, create a field representing - // the container member variable. - CodeTypeDeclaration typeDecl = manager.Context[typeof(CodeTypeDeclaration)] as CodeTypeDeclaration; - RootContext rootCxt = manager.Context[typeof(RootContext)] as RootContext; CodeStatementCollection statements = new CodeStatementCollection(); CodeExpression lhs; - if (typeDecl != null && rootCxt != null) + if (manager.Context[typeof(CodeTypeDeclaration)] is CodeTypeDeclaration typeDecl && manager.Context[typeof(RootContext)] is RootContext rootCxt) { CodeMemberField field = new CodeMemberField(typeof(IContainer), _containerName) { diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EventMemberCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EventMemberCodeDomSerializer.cs index 4a4abb9bfaa..2b913b2574c 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EventMemberCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EventMemberCodeDomSerializer.cs @@ -38,8 +38,6 @@ internal static EventMemberCodeDomSerializer Default [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2102:CatchNonClsCompliantExceptionsInGeneralHandlers")] public override void Serialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements) { - EventDescriptor eventToSerialize = descriptor as EventDescriptor; - if (manager == null) { throw new ArgumentNullException(nameof(manager)); @@ -48,7 +46,7 @@ public override void Serialize(IDesignerSerializationManager manager, object val { throw new ArgumentNullException(nameof(value)); } - if (eventToSerialize == null) + if (!(descriptor is EventDescriptor eventToSerialize)) { throw new ArgumentNullException(nameof(descriptor)); } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PrimitiveCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PrimitiveCodeDomSerializer.cs index b5e6923a434..6e09c315527 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PrimitiveCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PrimitiveCodeDomSerializer.cs @@ -51,8 +51,7 @@ public override object Serialize(IDesignerSerializationManager manager, object v { if (value is string) { - string stringValue = value as string; - if (stringValue != null && stringValue.Length > 200) + if (value is string stringValue && stringValue.Length > 200) { expression = SerializeToResourceExpression(manager, stringValue); } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PropertyMemberCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PropertyMemberCodeDomSerializer.cs index b071aebb502..cce44fab6ab 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PropertyMemberCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/PropertyMemberCodeDomSerializer.cs @@ -106,8 +106,6 @@ private object GetPropertyValue(IDesignerSerializationManager manager, PropertyD [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2102:CatchNonClsCompliantExceptionsInGeneralHandlers")] public override void Serialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements) { - PropertyDescriptor propertyToSerialize = descriptor as PropertyDescriptor; - if (manager == null) { throw new ArgumentNullException(nameof(manager)); @@ -116,7 +114,7 @@ public override void Serialize(IDesignerSerializationManager manager, object val { throw new ArgumentNullException(nameof(value)); } - if (propertyToSerialize == null) + if (!(descriptor is PropertyDescriptor propertyToSerialize)) { throw new ArgumentNullException(nameof(descriptor)); } @@ -258,9 +256,8 @@ private void SerializeContentProperty(IDesignerSerializationManager manager, obj manager.Context.Pop(); } - CodeStatementCollection csc = result as CodeStatementCollection; - if (csc != null) + if (result is CodeStatementCollection csc) { foreach (CodeStatement statement in csc) { @@ -269,9 +266,7 @@ private void SerializeContentProperty(IDesignerSerializationManager manager, obj } else { - CodeStatement cs = result as CodeStatement; - - if (cs != null) + if (result is CodeStatement cs) { statements.Add(cs); } @@ -375,9 +370,8 @@ private void SerializeNormalProperty(IDesignerSerializationManager manager, obje // is related to another member. If it is, then we will use that // relationship to construct the property assign statement. if // it isn't, then we're serialize ourselves. - MemberRelationshipService relationships = manager.GetService(typeof(MemberRelationshipService)) as MemberRelationshipService; - if (relationships != null) + if (manager.GetService(typeof(MemberRelationshipService)) is MemberRelationshipService relationships) { MemberRelationship relationship = relationships[value, property]; @@ -441,9 +435,6 @@ private void SerializeNormalProperty(IDesignerSerializationManager manager, obje /// public override bool ShouldSerialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor) { - - PropertyDescriptor propertyToSerialize = descriptor as PropertyDescriptor; - if (manager == null) { throw new ArgumentNullException(nameof(manager)); @@ -452,7 +443,7 @@ public override bool ShouldSerialize(IDesignerSerializationManager manager, obje { throw new ArgumentNullException(nameof(value)); } - if (propertyToSerialize == null) + if (!(descriptor is PropertyDescriptor propertyToSerialize)) { throw new ArgumentNullException(nameof(descriptor)); } @@ -493,9 +484,8 @@ public override bool ShouldSerialize(IDesignerSerializationManager manager, obje // If we don't have to serialize, we need to make sure there isn't a member // relationship with this property. If there is, we still need to serialize. - MemberRelationshipService relationships = manager.GetService(typeof(MemberRelationshipService)) as MemberRelationshipService; - if (relationships != null) + if (manager.GetService(typeof(MemberRelationshipService)) is MemberRelationshipService relationships) { MemberRelationship relationship = relationships[value, descriptor]; diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/BaseContextMenuStrip.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/BaseContextMenuStrip.cs index 155791cb761..d1d3f97e8fe 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/BaseContextMenuStrip.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/BaseContextMenuStrip.cs @@ -117,8 +117,7 @@ private void RefreshSelectionMenuItem() { selectionMenuItem = new ToolStripMenuItem(); - IUIService uis = serviceProvider.GetService(typeof(IUIService)) as IUIService; - if (uis != null) + if (serviceProvider.GetService(typeof(IUIService)) is IUIService uis) { selectionMenuItem.DropDown.Renderer = (ToolStripProfessionalRenderer)uis.Styles["VsRenderer"]; //Set the right Font @@ -228,8 +227,7 @@ public override void RefreshItems() foreach (ToolStripItem item in this.Items) { - StandardCommandToolStripMenuItem stdItem = item as StandardCommandToolStripMenuItem; - if (stdItem != null) + if (item is StandardCommandToolStripMenuItem stdItem) { stdItem.RefreshItem(); } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerActionUI.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerActionUI.cs index 0d9f612e943..53b463731ad 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerActionUI.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerActionUI.cs @@ -422,11 +422,10 @@ private void OnDesignerActionUIStateChange(object sender, DesignerActionUIStateC /// private void OnInvokedDesignerActionChanged(object sender, DesignerActionListsChangedEventArgs e) { - IComponent relatedComponent = e.RelatedObject as IComponent; DesignerActionGlyph g = null; if (e.ChangeType == DesignerActionListsChangedType.ActionListsAdded) { - if (relatedComponent == null) + if (!(e.RelatedObject is IComponent relatedComponent)) { Debug.Fail("How can we add a DesignerAction glyphs when it's related object is not an IComponent?"); return; diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/TemplateNodeCustomMenuItemCollection.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/TemplateNodeCustomMenuItemCollection.cs index 42edc647079..a199fafc3c6 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/TemplateNodeCustomMenuItemCollection.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/TemplateNodeCustomMenuItemCollection.cs @@ -154,8 +154,7 @@ private void InsertToolStripItem(Type t) { if (parentDropDown.OwnerItem is ToolStripDropDownItem ownerItem) { - ToolStripMenuItemDesigner itemDesigner = designerHost.GetDesigner(ownerItem) as ToolStripMenuItemDesigner; - if (itemDesigner != null) + if (designerHost.GetDesigner(ownerItem) is ToolStripMenuItemDesigner itemDesigner) { itemDesigner.ResetGlyphs(ownerItem); } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDropDownDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDropDownDesigner.cs index b23ef21da3b..fc95914b2eb 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDropDownDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDropDownDesigner.cs @@ -164,8 +164,7 @@ private string SettingsKey { if (string.IsNullOrEmpty((string)ShadowProperties["SettingsKey"])) { - IPersistComponentSettings persistableComponent = Component as IPersistComponentSettings; - if (persistableComponent != null && host != null) + if (Component is IPersistComponentSettings persistableComponent && host != null) { if (persistableComponent.SettingsKey == null) { diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs index ab0c2c68a29..90e5f55f90d 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs @@ -410,8 +410,7 @@ private void InsertIntoDropDown(ToolStripDropDown parent, Type t) // We need to cancel the ToolStripDesigner's nested MenuItemTransaction; otherwise, we can't cancel our Transaction and the Designer will be left in an unusable state if ((parent != null) && (parent.OwnerItem != null) && (parent.OwnerItem.Owner != null)) { - ToolStripDesigner toolStripDesigner = designerHost.GetDesigner(parent.OwnerItem.Owner) as ToolStripDesigner; - if (toolStripDesigner != null) + if (designerHost.GetDesigner(parent.OwnerItem.Owner) is ToolStripDesigner toolStripDesigner) { toolStripDesigner.CancelPendingMenuItemTransaction(); } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemDesigner.cs index 2aabd56ba41..b0c6c498888 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemDesigner.cs @@ -766,9 +766,8 @@ internal virtual ToolStripItem MorphCurrentItem(Type t) { //turn off Adding and Added Transactions.. ToolStripDesigner.s_autoAddNewItems = false; - ComponentSerializationService _serializationService = GetService(typeof(ComponentSerializationService)) as ComponentSerializationService; SerializationStore _serializedData = null; - if (_serializationService != null) + if (GetService(typeof(ComponentSerializationService)) is ComponentSerializationService _serializationService) { _serializedData = _serializationService.CreateStore(); _serializationService.Serialize(_serializedData, Component); //notice the use of component... since we want to preserve the type. diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs index 1442886c95f..dfbfc45f62c 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs @@ -1562,8 +1562,7 @@ internal void InitializeDropDown() // Check if this is a Sited-DropDown if (MenuItem.DropDown.Site != null) { - ToolStripDropDownDesigner designer = designerHost.GetDesigner(MenuItem.DropDown) as ToolStripDropDownDesigner; - if (designer != null) + if (designerHost.GetDesigner(MenuItem.DropDown) is ToolStripDropDownDesigner designer) { designer.currentParent = MenuItem as ToolStripMenuItem; } @@ -2131,8 +2130,7 @@ private void OnSelectionChanged(object sender, EventArgs e) if (IsOnContextMenu && !MenuItem.Owner.Visible) { ToolStripDropDown firstDropDown = GetFirstDropDown(MenuItem); - ToolStripDropDownDesigner firstDropDownDesigner = designerHost.GetDesigner(firstDropDown) as ToolStripDropDownDesigner; - if (firstDropDownDesigner != null) + if (designerHost.GetDesigner(firstDropDown) is ToolStripDropDownDesigner firstDropDownDesigner) { InitializeDropDown(); firstDropDownDesigner.ShowMenu(); @@ -2201,8 +2199,7 @@ private void OnSelectionChanged(object sender, EventArgs e) else { // Any ToolStripItem on the DropDown OR any of its Child DropDowns - ToolStripItem item = selectedObj as ToolStripItem; - if (item != null) + if (selectedObj is ToolStripItem item) { ToolStripDropDown parent = item.Owner as ToolStripDropDown; while (parent != null) @@ -2517,8 +2514,7 @@ internal void ShowOwnerDropDown(ToolStripDropDownItem currentSelection) currentSelection = (ToolStripDropDownItem)currentDropDown.OwnerItem; if (currentSelection != null && !currentSelection.DropDown.Visible) { - ToolStripMenuItemDesigner currentSelectionDesigner = designerHost.GetDesigner(currentSelection) as ToolStripMenuItemDesigner; - if (currentSelectionDesigner != null) + if (designerHost.GetDesigner(currentSelection) is ToolStripMenuItemDesigner currentSelectionDesigner) { currentSelectionDesigner.InitializeDropDown(); } @@ -2605,8 +2601,7 @@ internal DropDownBehavior(ControlDesigner designer, ToolStripMenuItemDesigner me /// public override void OnDragEnter(Glyph g, DragEventArgs e) { - ToolStripItemDataObject data = e.Data as ToolStripItemDataObject; - if (data != null) + if (e.Data is ToolStripItemDataObject data) { e.Effect = (Control.ModifierKeys == Keys.Control) ? DragDropEffects.Copy : DragDropEffects.Move; } @@ -2621,8 +2616,7 @@ public override void OnDragEnter(Glyph g, DragEventArgs e) /// public override void OnDragOver(Glyph g, DragEventArgs e) { - ToolStripItemDataObject data = e.Data as ToolStripItemDataObject; - if (data != null) + if (e.Data is ToolStripItemDataObject data) { e.Effect = (Control.ModifierKeys == Keys.Control) ? DragDropEffects.Copy : DragDropEffects.Move; } @@ -2638,8 +2632,7 @@ public override void OnDragOver(Glyph g, DragEventArgs e) [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public override void OnDragDrop(Glyph g, DragEventArgs e) { - ToolStripItemDataObject data = e.Data as ToolStripItemDataObject; - if (data != null) + if (e.Data is ToolStripItemDataObject data) { ToolStripItem primaryItem = data.PrimarySelection; IDesignerHost host = (IDesignerHost)primaryItem.Site.GetService(typeof(IDesignerHost)); diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/UndoEngine.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/UndoEngine.cs index e1f4c724dea..5555e5d8d4c 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/UndoEngine.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/UndoEngine.cs @@ -1283,8 +1283,7 @@ private void SaveAfterState(UndoEngine engine) UndoEngine.Trace("---> Saving after snapshot for change to '{0}'", _componentName); object component = null; - IReferenceService rs = engine.GetService(typeof(IReferenceService)) as IReferenceService; - if (rs != null) + if (engine.GetService(typeof(IReferenceService)) is IReferenceService rs) { component = rs.GetReference(_componentName); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs index 4eb21fcbc99..9f0efbb687c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs @@ -1419,8 +1419,7 @@ public static void Restart() // HRef exe case hrefExeCase = true; ExitInternal(); - string launchUrl = AppDomain.CurrentDomain.GetData("APP_LAUNCH_URL") as string; - if (launchUrl != null) + if (AppDomain.CurrentDomain.GetData("APP_LAUNCH_URL") is string launchUrl) { Process.Start(process.MainModule.FileName, launchUrl); } @@ -2407,15 +2406,13 @@ internal UnsafeNativeMethods.IMsoComponentManager ComponentManager if (NativeMethods.Succeeded(UnsafeNativeMethods.CoRegisterMessageFilter(NativeMethods.NullHandleRef, ref msgFilterPtr)) && msgFilterPtr != (IntPtr)0) { - IntPtr dummy = (IntPtr)0; UnsafeNativeMethods.CoRegisterMessageFilter(new HandleRef(null, msgFilterPtr), ref dummy); object msgFilterObj = Marshal.GetObjectForIUnknown(msgFilterPtr); Marshal.Release(msgFilterPtr); - UnsafeNativeMethods.IOleServiceProvider sp = msgFilterObj as UnsafeNativeMethods.IOleServiceProvider; - if (sp != null) + if (msgFilterObj is UnsafeNativeMethods.IOleServiceProvider sp) { try { @@ -2748,8 +2745,7 @@ internal void DisableWindowsForModalLoop(bool onlyWinForms, ApplicationContext c threadWindows.Enable(false); threadWindows.previousThreadWindows = old; - ModalApplicationContext modalContext = context as ModalApplicationContext; - if (modalContext != null) + if (context is ModalApplicationContext modalContext) { modalContext.DisableThreadWindows(true, onlyWinForms); } @@ -2933,8 +2929,7 @@ internal void EnableWindowsForModalLoop(bool onlyWinForms, ApplicationContext co threadWindows = threadWindows.previousThreadWindows; } - ModalApplicationContext modalContext = context as ModalApplicationContext; - if (modalContext != null) + if (context is ModalApplicationContext modalContext) { modalContext.DisableThreadWindows(false, onlyWinForms); } @@ -3294,8 +3289,7 @@ internal void OnThreadException(Exception t) Environment.Exit(0); break; case DialogResult.Yes: - WarningException w = t as WarningException; - if (w != null) + if (t is WarningException w) { Help.ShowHelp(null, w.HelpUrl, w.HelpTopic); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs index ac0cbc3d3a5..c5d86af1887 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs @@ -1067,8 +1067,7 @@ private void OnComponentRename(object sender, ComponentRenameEventArgs e) // if it is, call DISPID_AMBIENT_DISPLAYNAME directly on the // control itself. // - UnsafeNativeMethods.IOleControl oleCtl = GetOcx() as UnsafeNativeMethods.IOleControl; - if (oleCtl != null) + if (GetOcx() is UnsafeNativeMethods.IOleControl oleCtl) { oleCtl.OnAmbientPropertyChange(NativeMethods.ActiveX.DISPID_AMBIENT_DISPLAYNAME); } @@ -2345,8 +2344,7 @@ private ContainerControl FindContainerControlInternal() IDesignerHost host = (IDesignerHost)Site.GetService(typeof(IDesignerHost)); if (host != null) { - ContainerControl rootControl = host.RootComponent as ContainerControl; - if (rootControl != null) + if (host.RootComponent is ContainerControl rootControl) { return rootControl; } @@ -2357,8 +2355,7 @@ private ContainerControl FindContainerControlInternal() Control control = this; while (control != null) { - ContainerControl tempCC = control as ContainerControl; - if (tempCC != null) + if (control is ContainerControl tempCC) { cc = tempCC; break; @@ -3137,8 +3134,7 @@ private AxPropertyDescriptor GetPropertyDescriptorFromDispid(int dispid) PropertyDescriptorCollection props = FillProperties(null); foreach (PropertyDescriptor prop in props) { - AxPropertyDescriptor axprop = prop as AxPropertyDescriptor; - if (axprop != null && axprop.Dispid == dispid) + if (prop is AxPropertyDescriptor axprop && axprop.Dispid == dispid) { return axprop; } @@ -5164,14 +5160,12 @@ private static IntPtr CopyPalette(IntPtr hPal) { private static object GetPICTDESCFromPicture(Image image) { - Bitmap bmp = image as Bitmap; - if (bmp != null) + if (image is Bitmap bmp) { return new NativeMethods.PICTDESCbmp(bmp); } - Metafile mf = image as Metafile; - if (mf != null) + if (image is Metafile mf) { return new NativeMethods.PICTDESCemf(mf); } @@ -5449,8 +5443,7 @@ protected static Font GetFontFromIFontDisp(object font) return null; } - UnsafeNativeMethods.IFont ifont = font as UnsafeNativeMethods.IFont; - if (ifont != null) + if (font is UnsafeNativeMethods.IFont ifont) { return GetFontFromIFont(ifont); } @@ -6100,8 +6093,7 @@ private void MaybeAdd(ArrayList l, Control ctl, bool selected, int dwOleContF, b return; } } - AxHost hostctl = ctl as AxHost; - if (hostctl != null && (dwOleContF & NativeMethods.ActiveX.OLECONTF_EMBEDDINGS) != 0) + if (ctl is AxHost hostctl && (dwOleContF & NativeMethods.ActiveX.OLECONTF_EMBEDDINGS) != 0) { l.Add(hostctl.GetOcx()); } @@ -6250,8 +6242,7 @@ private bool RegisterControl(AxHost ctl) private void OnComponentRemoved(object sender, ComponentEventArgs e) { - Control c = e.Component as Control; - if (sender == assocContainer && c != null) + if (sender == assocContainer && e.Component is Control c) { RemoveControl(c); } @@ -6259,8 +6250,7 @@ private void OnComponentRemoved(object sender, ComponentEventArgs e) internal static AxContainer FindContainerForControl(Control ctl) { - AxHost axctl = ctl as AxHost; - if (axctl != null) + if (ctl is AxHost axctl) { if (axctl.container != null) { @@ -6442,8 +6432,7 @@ private void ListAxControls(ArrayList list, bool fuseOcx) for (int i = 0; i < ctls.Length; i++) { Control ctl = ctls[i]; - AxHost hostctl = ctl as AxHost; - if (hostctl != null) + if (ctl is AxHost hostctl) { if (fuseOcx) { @@ -7639,8 +7628,7 @@ public class AxComponentEditor : WindowsFormsComponentEditor { public override bool EditComponent(ITypeDescriptorContext context, object obj, IWin32Window parent) { - AxHost host = obj as AxHost; - if (host != null) + if (obj is AxHost host) { try { @@ -8039,8 +8027,7 @@ internal void UpdateTypeConverterAndTypeEditorInternal(bool force, int dispid) else if (converter is AxEnumConverter) { ((AxEnumConverter)converter).RefreshValues(); - AxPerPropertyBrowsingEnum axEnum = ((AxEnumConverter)converter).com2Enum as AxPerPropertyBrowsingEnum; - if (axEnum != null) + if (((AxEnumConverter)converter).com2Enum is AxPerPropertyBrowsingEnum axEnum) { axEnum.RefreshArrays(stringMarshaler, intMarshaler); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Binding.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Binding.cs index 52a4501a9e1..35fbff998f8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Binding.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Binding.cs @@ -161,8 +161,7 @@ internal void SetBindableComponent(IBindableComponent value) // We are essentially doing to the listManager what we were doing to the // BindToObject: bind only when the control is created and it has a BindingContext BindingContext.UpdateBinding((_control != null && IsComponentCreated(_control) ? _control.BindingContext : null), this); - Form form = value as Form; - if (form != null) + if (value is Form form) { form.Load += new EventHandler(FormLoaded); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs b/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs index a30db80cefd..9c484fd1d2f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs @@ -887,16 +887,13 @@ private void WireUpTextBox(ref ToolStripItem oldTextBox, ToolStripItem newTextBo { if (oldTextBox != newTextBox) { - ToolStripControlHost oldCtrl = oldTextBox as ToolStripControlHost; - ToolStripControlHost newCtrl = newTextBox as ToolStripControlHost; - - if (oldCtrl != null) + if (oldTextBox is ToolStripControlHost oldCtrl) { oldCtrl.KeyUp -= keyUpHandler; oldCtrl.LostFocus -= lostFocusHandler; } - if (newCtrl != null) + if (newTextBox is ToolStripControlHost newCtrl) { newCtrl.KeyUp += keyUpHandler; newCtrl.LostFocus += lostFocusHandler; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/BindingSource.cs b/src/System.Windows.Forms/src/System/Windows/Forms/BindingSource.cs index 7e276a55456..52617b1ce47 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/BindingSource.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/BindingSource.cs @@ -315,14 +315,11 @@ private string InnerListSort { ListSortDescriptionCollection sortsColln = null; - IBindingListView iblv = List as IBindingListView; - IBindingList ibl = List as IBindingList; - - if (iblv != null && iblv.SupportsAdvancedSorting) + if (List is IBindingListView iblv && iblv.SupportsAdvancedSorting) { sortsColln = iblv.SortDescriptions; } - else if (ibl != null && ibl.SupportsSorting && ibl.IsSorted) + else if (List is IBindingList ibl && ibl.SupportsSorting && ibl.IsSorted) { ListSortDescription[] sortsArray = new ListSortDescription[1]; sortsArray[0] = new ListSortDescription(ibl.SortProperty, ibl.SortDirection); @@ -1201,8 +1198,7 @@ private void SetList(IList list, bool metaDataChanged, bool applySortAndFilter) UnhookItemChangedEventsForOldCurrent(); // Bind to the new list - IList listInternal = ListBindingHelper.GetList(list) as IList; - if (listInternal == null) + if (!(ListBindingHelper.GetList(list) is IList listInternal)) { listInternal = list; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckableControlBaseAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckableControlBaseAdapter.cs index 935c013f495..67280409555 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckableControlBaseAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/CheckableControlBaseAdapter.cs @@ -57,14 +57,12 @@ private Appearance Appearance { get { - CheckBox checkBox = Control as CheckBox; - if (checkBox != null) + if (Control is CheckBox checkBox) { return checkBox.Appearance; } - RadioButton radioButton = Control as RadioButton; - if (radioButton != null) + if (Control is RadioButton radioButton) { return radioButton.Appearance; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/CheckBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/CheckBox.cs index e6f2547d83c..4f537a33280 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/CheckBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/CheckBox.cs @@ -523,8 +523,7 @@ protected override AccessibleObject CreateAccessibilityInstance() protected virtual void OnAppearanceChanged(EventArgs e) { - EventHandler eh = Events[EVENT_APPEARANCECHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_APPEARANCECHANGED] is EventHandler eh) { eh(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Clipboard.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Clipboard.cs index 11a7e51f7d4..8f8d1922230 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Clipboard.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Clipboard.cs @@ -355,8 +355,7 @@ public static StringCollection GetFileDropList() if (dataObject != null) { - string[] strings = dataObject.GetData(DataFormats.FileDrop, true) as string[]; - if (strings != null) + if (dataObject.GetData(DataFormats.FileDrop, true) is string[] strings) { retVal.AddRange(strings); } @@ -389,8 +388,7 @@ public static string GetText(TextDataFormat format) IDataObject dataObject = Clipboard.GetDataObject(); if (dataObject != null) { - string text = dataObject.GetData(ConvertToDataFormats(format), false) as string; - if (text != null) + if (dataObject.GetData(ConvertToDataFormats(format), false) is string text) { return text; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs index ce8a6238491..bba8103c8ea 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs @@ -1847,8 +1847,7 @@ private void ChildWndProc(ref Message m) IContainerControl c = GetContainerControl(); if (c != null) { - ContainerControl container = c as ContainerControl; - if (container != null) + if (c is ContainerControl container) { if (!container.ActivateControlInternal(this, false)) { @@ -2723,8 +2722,7 @@ protected virtual void OnDropDown(EventArgs e) UnsafeNativeMethods.ExpandCollapseState.Collapsed, UnsafeNativeMethods.ExpandCollapseState.Expanded); - var accessibleObject = AccessibilityObject as ComboBoxAccessibleObject; - if (accessibleObject != null) + if (AccessibilityObject is ComboBoxAccessibleObject accessibleObject) { accessibleObject.SetComboBoxItemFocus(); } @@ -2881,8 +2879,7 @@ protected override void OnSelectedIndexChanged(EventArgs e) } else { - var accessibleObject = AccessibilityObject as ComboBoxAccessibleObject; - if (accessibleObject != null) + if (AccessibilityObject is ComboBoxAccessibleObject accessibleObject) { // Announce DropDown- and DropDownList-styled ComboBox item selection using keyboard @@ -4853,8 +4850,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga return _owningComboBox.ChildListAccessibleObject; case UnsafeNativeMethods.NavigateDirection.NextSibling: int currentIndex = GetCurrentIndex(); - var comboBoxChildListUiaProvider = _owningComboBox.ChildListAccessibleObject as ComboBoxChildListUiaProvider; - if (comboBoxChildListUiaProvider != null) + if (_owningComboBox.ChildListAccessibleObject is ComboBoxChildListUiaProvider comboBoxChildListUiaProvider) { int itemsCount = comboBoxChildListUiaProvider.GetChildFragmentCount(); int nextItemIndex = currentIndex + 1; @@ -5407,8 +5403,7 @@ internal void SetComboBoxItemFocus() return; } - var itemAccessibleObject = ItemAccessibleObjects[selectedItem] as ComboBoxItemAccessibleObject; - if (itemAccessibleObject != null) + if (ItemAccessibleObjects[selectedItem] is ComboBoxItemAccessibleObject itemAccessibleObject) { itemAccessibleObject.SetFocus(); } @@ -5422,8 +5417,7 @@ internal void SetComboBoxItemSelection() return; } - var itemAccessibleObject = ItemAccessibleObjects[selectedItem] as ComboBoxItemAccessibleObject; - if (itemAccessibleObject != null) + if (ItemAccessibleObjects[selectedItem] is ComboBoxItemAccessibleObject itemAccessibleObject) { itemAccessibleObject.RaiseAutomationEvent(NativeMethods.UIA_SelectionItem_ElementSelectedEventId); } @@ -5476,8 +5470,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga return null; } - var comboBoxAccessibleObject = _owner.AccessibilityObject as ComboBoxAccessibleObject; - if (comboBoxAccessibleObject != null) + if (_owner.AccessibilityObject is ComboBoxAccessibleObject comboBoxAccessibleObject) { int comboBoxChildFragmentCount = comboBoxAccessibleObject.GetChildFragmentCount(); if (comboBoxChildFragmentCount > 1) @@ -5898,8 +5891,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga case UnsafeNativeMethods.NavigateDirection.Parent: return _owner.AccessibilityObject; case UnsafeNativeMethods.NavigateDirection.NextSibling: - var comboBoxAccessibleObject = _owner.AccessibilityObject as ComboBoxAccessibleObject; - if (comboBoxAccessibleObject != null) + if (_owner.AccessibilityObject is ComboBoxAccessibleObject comboBoxAccessibleObject) { int comboBoxChildFragmentCount = comboBoxAccessibleObject.GetChildFragmentCount(); if (comboBoxChildFragmentCount > 1) @@ -6083,8 +6075,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga } else if (direction == UnsafeNativeMethods.NavigateDirection.PreviousSibling) { - var comboBoxAccessibleObject = _owner.AccessibilityObject as ComboBoxAccessibleObject; - if (comboBoxAccessibleObject != null) + if (_owner.AccessibilityObject is ComboBoxAccessibleObject comboBoxAccessibleObject) { int comboBoxChildFragmentCount = comboBoxAccessibleObject.GetChildFragmentCount(); if (comboBoxChildFragmentCount > 1) @@ -6291,8 +6282,7 @@ static internal bool AutoCompleteActive } foreach (object o in ACWindows.Values) { - ACNativeWindow window = o as ACNativeWindow; - if (window != null && window.Visible) + if (o is ACNativeWindow window && window.Visible) { return true; } @@ -6418,8 +6408,7 @@ private FlatComboAdapter FlatComboBoxAdapter { get { - FlatComboAdapter comboAdapter = Properties.GetObject(PropFlatComboAdapter) as FlatComboAdapter; - if (comboAdapter == null || !comboAdapter.IsValid(this)) + if (!(Properties.GetObject(PropFlatComboAdapter) is FlatComboAdapter comboAdapter) || !comboAdapter.IsValid(this)) { comboAdapter = CreateFlatComboAdapterInstance(); Properties.SetObject(PropFlatComboAdapter, comboAdapter); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2FontConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2FontConverter.cs index 5d1bd14412a..5236f50b2f4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2FontConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2FontConverter.cs @@ -48,9 +48,8 @@ public override Type ManagedType public override object ConvertNativeToManaged(object nativeValue, Com2PropertyDescriptor pd) { // we're getting an IFont thing here - UnsafeNativeMethods.IFont nativeFont = nativeValue as UnsafeNativeMethods.IFont; - if (nativeFont == null) + if (!(nativeValue is UnsafeNativeMethods.IFont nativeFont)) { lastHandle = IntPtr.Zero; lastFont = Control.DefaultFont; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs index fb942e00120..519509821ee 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs @@ -72,8 +72,7 @@ internal static string GetDisplayString(NativeMethods.IPerPropertyBrowsing ppb, /// private void OnGetBaseAttributes(Com2PropertyDescriptor sender, GetAttributesEvent attrEvent) { - NativeMethods.IPerPropertyBrowsing target = sender.TargetObject as NativeMethods.IPerPropertyBrowsing; - if (target != null) + if (sender.TargetObject is NativeMethods.IPerPropertyBrowsing target) { // we hide IDispatch props by default, we we need to force showing them here diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IProvidePropertyBuilderHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IProvidePropertyBuilderHandler.cs index 6182e7792f7..70f82cd8d07 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IProvidePropertyBuilderHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IProvidePropertyBuilderHandler.cs @@ -75,9 +75,7 @@ public override void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc) /// private void OnGetBaseAttributes(Com2PropertyDescriptor sender, GetAttributesEvent attrEvent) { - NativeMethods.IProvidePropertyBuilder target = sender.TargetObject as NativeMethods.IProvidePropertyBuilder; - - if (target != null) + if (sender.TargetObject is NativeMethods.IProvidePropertyBuilder target) { string s = null; bool builderValid = GetBuilderGuidString(target, sender.DISPID, ref s, new int[1]); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IVsPerPropertyBrowsingHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IVsPerPropertyBrowsingHandler.cs index a38cbcfef4e..355c33e9fd7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IVsPerPropertyBrowsingHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IVsPerPropertyBrowsingHandler.cs @@ -76,9 +76,7 @@ public override void SetupPropertyHandlers(Com2PropertyDescriptor[] propDesc) private void OnGetBaseAttributes(Com2PropertyDescriptor sender, GetAttributesEvent attrEvent) { - NativeMethods.IVsPerPropertyBrowsing vsObj = sender.TargetObject as NativeMethods.IVsPerPropertyBrowsing; - - if (vsObj == null) + if (!(sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing vsObj)) { return; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/ComNativeDescriptor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/ComNativeDescriptor.cs index 7988368488c..f023816bd96 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/ComNativeDescriptor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/ComNativeDescriptor.cs @@ -455,10 +455,7 @@ internal PropertyDescriptorCollection GetProperties(object component, Attribute[ /// private void OnPropsInfoDisposed(object sender, EventArgs e) { - - Com2Properties propsInfo = sender as Com2Properties; - - if (propsInfo != null) + if (sender is Com2Properties propsInfo) { propsInfo.Disposed -= new EventHandler(OnPropsInfoDisposed); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs index a6cf56e35e8..7f1d8ffcfa6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs @@ -1240,11 +1240,12 @@ protected override bool ProcessDialogChar(char charCode) { #if DEBUG Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "ContainerControl.ProcessDialogChar [" + charCode.ToString() + "]"); + +#endif #endif // If we're the top-level form or control, we need to do the mnemonic handling // - ContainerControl parent = GetContainerControl() as ContainerControl; - if (parent != null && charCode != ' ' && ProcessMnemonic(charCode)) + if (GetContainerControl() is ContainerControl parent && charCode != ' ' && ProcessMnemonic(charCode)) { return true; } @@ -2070,8 +2071,7 @@ private void WmSetFocus(ref Message m) { bool succeeded = false; - ContainerControl knowncontainer = c as ContainerControl; - if (knowncontainer != null) + if (c is ContainerControl knowncontainer) { succeeded = knowncontainer.ActivateControlInternal(this); } 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 c98250d3fcf..d1bdca66e3c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs @@ -2020,8 +2020,7 @@ internal bool ValidateActiveControl(out bool validatedControlAllowsFocusChange) IContainerControl c = GetContainerControl(); if (c != null && CausesValidation) { - ContainerControl container = c as ContainerControl; - if (container != null) + if (c is ContainerControl container) { while (container.ActiveControl == null) { @@ -2428,8 +2427,7 @@ private void DisposeFontHandle() { if (Properties.ContainsObject(PropFontHandleWrapper)) { - FontHandleWrapper fontHandle = Properties.GetObject(PropFontHandleWrapper) as FontHandleWrapper; - if (fontHandle != null) + if (Properties.GetObject(PropFontHandleWrapper) is FontHandleWrapper fontHandle) { fontHandle.Dispose(); } @@ -3803,9 +3801,8 @@ private Control ReflectParent value.AddReflectChild(); } - Control c = ReflectParent as Control; reflectParent = value; - if (c != null) + if (ReflectParent is Control c) { c.RemoveReflectChild(); } @@ -6407,8 +6404,7 @@ public object EndInvoke(IAsyncResult asyncResult) throw new ArgumentNullException(nameof(asyncResult)); } - ThreadMethodEntry entry = asyncResult as ThreadMethodEntry; - if (entry == null) + if (!(asyncResult is ThreadMethodEntry entry)) { throw new ArgumentException(SR.ControlBadAsyncResult, "asyncResult"); } @@ -6803,8 +6799,7 @@ protected virtual Rectangle GetScaledBounds(Rectangle bounds, SizeF factor, Boun ISite site = Site; if (site != null && site.DesignMode) { - IDesignerHost host = site.GetService(typeof(IDesignerHost)) as IDesignerHost; - if (host != null && host.RootComponent == this) + if (site.GetService(typeof(IDesignerHost)) is IDesignerHost host && host.RootComponent == this) { scaleLoc = false; } @@ -8299,8 +8294,7 @@ protected void InvokeOnClick(Control toInvoke, EventArgs e) protected virtual void OnAutoSizeChanged(EventArgs e) { Contract.Requires(e != null); - EventHandler eh = Events[EventAutoSizeChanged] as EventHandler; - if (eh != null) + if (Events[EventAutoSizeChanged] is EventHandler eh) { eh(this, e); } @@ -8331,8 +8325,7 @@ protected virtual void OnBackColorChanged(EventArgs e) Invalidate(); - EventHandler eh = Events[EventBackColor] as EventHandler; - if (eh != null) + if (Events[EventBackColor] is EventHandler eh) { eh(this, e); } @@ -8361,8 +8354,7 @@ protected virtual void OnBackgroundImageChanged(EventArgs e) Invalidate(); - EventHandler eh = Events[EventBackgroundImage] as EventHandler; - if (eh != null) + if (Events[EventBackgroundImage] is EventHandler eh) { eh(this, e); } @@ -8391,8 +8383,7 @@ protected virtual void OnBackgroundImageLayoutChanged(EventArgs e) Invalidate(); - EventHandler eh = Events[EventBackgroundImageLayout] as EventHandler; - if (eh != null) + if (Events[EventBackgroundImageLayout] is EventHandler eh) { eh(this, e); } @@ -8407,8 +8398,7 @@ protected virtual void OnBindingContextChanged(EventArgs e) UpdateBindings(); } - EventHandler eh = Events[EventBindingContext] as EventHandler; - if (eh != null) + if (Events[EventBindingContext] is EventHandler eh) { eh(this, e); } @@ -8430,8 +8420,7 @@ protected virtual void OnBindingContextChanged(EventArgs e) protected virtual void OnCausesValidationChanged(EventArgs e) { Contract.Requires(e != null); - EventHandler eh = Events[EventCausesValidation] as EventHandler; - if (eh != null) + if (Events[EventCausesValidation] is EventHandler eh) { eh(this, e); } @@ -8453,8 +8442,7 @@ internal virtual void OnChildLayoutResuming(Control child, bool performLayout) protected virtual void OnContextMenuChanged(EventArgs e) { Contract.Requires(e != null); - EventHandler eh = Events[EventContextMenu] as EventHandler; - if (eh != null) + if (Events[EventContextMenu] is EventHandler eh) { eh(this, e); } @@ -8464,8 +8452,7 @@ protected virtual void OnContextMenuChanged(EventArgs e) protected virtual void OnContextMenuStripChanged(EventArgs e) { Contract.Requires(e != null); - EventHandler eh = Events[EventContextMenuStrip] as EventHandler; - if (eh != null) + if (Events[EventContextMenuStrip] is EventHandler eh) { eh(this, e); } @@ -8475,8 +8462,7 @@ protected virtual void OnContextMenuStripChanged(EventArgs e) protected virtual void OnCursorChanged(EventArgs e) { Contract.Requires(e != null); - EventHandler eh = Events[EventCursor] as EventHandler; - if (eh != null) + if (Events[EventCursor] is EventHandler eh) { eh(this, e); } @@ -8498,8 +8484,7 @@ protected virtual void OnCursorChanged(EventArgs e) protected virtual void OnDockChanged(EventArgs e) { Contract.Requires(e != null); - EventHandler eh = Events[EventDock] as EventHandler; - if (eh != null) + if (Events[EventDock] is EventHandler eh) { eh(this, e); } @@ -8532,8 +8517,7 @@ protected virtual void OnEnabledChanged(EventArgs e) } } - EventHandler eh = Events[EventEnabled] as EventHandler; - if (eh != null) + if (Events[EventEnabled] is EventHandler eh) { eh(this, e); } @@ -8581,8 +8565,7 @@ protected virtual void OnFontChanged(EventArgs e) SetWindowFont(); } - EventHandler eh = Events[EventFont] as EventHandler; - if (eh != null) + if (Events[EventFont] is EventHandler eh) { eh(this, e); } @@ -8617,8 +8600,7 @@ protected virtual void OnForeColorChanged(EventArgs e) Invalidate(); - EventHandler eh = Events[EventForeColor] as EventHandler; - if (eh != null) + if (Events[EventForeColor] is EventHandler eh) { eh(this, e); } @@ -8651,8 +8633,7 @@ protected virtual void OnRightToLeftChanged(EventArgs e) RecreateHandle(); - EventHandler eh = Events[EventRightToLeft] as EventHandler; - if (eh != null) + if (Events[EventRightToLeft] is EventHandler eh) { eh(this, e); } @@ -8857,12 +8838,11 @@ protected virtual void OnPrint(PaintEventArgs e) } else { - PrintPaintEventArgs ppev = e as PrintPaintEventArgs; Message m; bool releaseDC = false; IntPtr hdc = IntPtr.Zero; - if (ppev == null) + if (!(e is PrintPaintEventArgs ppev)) { IntPtr flags = (IntPtr)(NativeMethods.PRF_CHILDREN | NativeMethods.PRF_CLIENT | NativeMethods.PRF_ERASEBKGND | NativeMethods.PRF_NONCLIENT); hdc = e.HDC; @@ -8898,8 +8878,7 @@ protected virtual void OnPrint(PaintEventArgs e) protected virtual void OnTabIndexChanged(EventArgs e) { Contract.Requires(e != null); - EventHandler eh = Events[EventTabIndex] as EventHandler; - if (eh != null) + if (Events[EventTabIndex] is EventHandler eh) { eh(this, e); } @@ -8909,8 +8888,7 @@ protected virtual void OnTabIndexChanged(EventArgs e) protected virtual void OnTabStopChanged(EventArgs e) { Contract.Requires(e != null); - EventHandler eh = Events[EventTabStop] as EventHandler; - if (eh != null) + if (Events[EventTabStop] is EventHandler eh) { eh(this, e); } @@ -8920,8 +8898,7 @@ protected virtual void OnTabStopChanged(EventArgs e) protected virtual void OnTextChanged(EventArgs e) { Contract.Requires(e != null); - EventHandler eh = Events[EventText] as EventHandler; - if (eh != null) + if (Events[EventText] is EventHandler eh) { eh(this, e); } @@ -8953,8 +8930,7 @@ protected virtual void OnVisibleChanged(EventArgs e) } } - EventHandler eh = Events[EventVisible] as EventHandler; - if (eh != null) + if (Events[EventVisible] is EventHandler eh) { eh(this, e); } @@ -9000,8 +8976,7 @@ internal virtual void OnTopMostActiveXParentChanged(EventArgs e) protected virtual void OnParentChanged(EventArgs e) { Contract.Requires(e != null); - EventHandler eh = Events[EventParent] as EventHandler; - if (eh != null) + if (Events[EventParent] is EventHandler eh) { eh(this, e); } @@ -9033,8 +9008,7 @@ protected virtual void OnClick(EventArgs e) protected virtual void OnClientSizeChanged(EventArgs e) { Contract.Requires(e != null); - EventHandler eh = Events[EventClientSize] as EventHandler; - if (eh != null) + if (Events[EventClientSize] is EventHandler eh) { eh(this, e); } @@ -9087,7 +9061,6 @@ protected virtual void OnHandleCreated(EventArgs e) Contract.Requires(e != null); if (IsHandleCreated) { - // Setting fonts is for some reason incredibly expensive. // (Even if you exclude font handle creation) if (!GetStyle(ControlStyles.UserPaint)) @@ -9137,18 +9110,14 @@ protected virtual void OnHandleCreated(EventArgs e) } } - // Update accessbility information. - ControlAccessibleObject accObj = Properties.GetObject(PropAccessibility) as ControlAccessibleObject; - ControlAccessibleObject ncAccObj = Properties.GetObject(PropNcAccessibility) as ControlAccessibleObject; - // Cache Handle in a local before asserting so we minimize code running under the Assert. IntPtr handle = Handle; - if (accObj != null) + if (Properties.GetObject(PropAccessibility) is ControlAccessibleObject accObj) { accObj.Handle = handle; } - if (ncAccObj != null) + if (Properties.GetObject(PropNcAccessibility) is ControlAccessibleObject ncAccObj) { ncAccObj.Handle = handle; } @@ -9222,8 +9191,7 @@ protected virtual void OnLocationChanged(EventArgs e) Contract.Requires(e != null); OnMove(EventArgs.Empty); - EventHandler eh = Events[EventLocation] as EventHandler; - if (eh != null) + if (Events[EventLocation] is EventHandler eh) { eh(this, e); } @@ -9937,8 +9905,7 @@ protected virtual void OnQueryContinueDrag(QueryContinueDragEventArgs qcdevent) protected virtual void OnRegionChanged(EventArgs e) { Contract.Requires(e != null); - EventHandler eh = Events[EventRegionChanged] as EventHandler; - if (eh != null) + if (Events[EventRegionChanged] is EventHandler eh) { eh(this, e); } @@ -9987,8 +9954,7 @@ protected virtual void OnSizeChanged(EventArgs e) Contract.Requires(e != null); OnResize(EventArgs.Empty); - EventHandler eh = Events[EventSize] as EventHandler; - if (eh != null) + if (Events[EventSize] is EventHandler eh) { eh(this, e); } @@ -10121,7 +10087,6 @@ internal void PaintBackground(PaintEventArgs e, Rectangle rectangle, Color backC if (BackgroundImage != null && !DisplayInformation.HighContrast && !formRTL) { - if (BackgroundImageLayout == ImageLayout.Tile) { if (ControlPaint.IsImageTransparent(BackgroundImage)) @@ -10131,8 +10096,7 @@ internal void PaintBackground(PaintEventArgs e, Rectangle rectangle, Color backC } Point scrollLocation = scrollOffset; - ScrollableControl scrollControl = this as ScrollableControl; - if (scrollControl != null && scrollLocation != Point.Empty) + if (this is ScrollableControl scrollControl && scrollLocation != Point.Empty) { scrollLocation = ((ScrollableControl)this).AutoScrollPosition; } @@ -12568,8 +12532,7 @@ private void SetParentHandle(IntPtr value) { // We will recreate later, when the MdiChild's visibility // is set to true (see - Form f = this as Form; - if (f != null) + if (this is Form f) { if (!f.CanRecreateHandle()) { @@ -13742,8 +13705,7 @@ private void WmGetObject(ref Message m) // a way that breaks this assumption. object tempObject = intAccessibleObject; - IAccessible iAccCheck = tempObject as IAccessible; - if (iAccCheck != null) + if (tempObject is IAccessible iAccCheck) { throw new InvalidOperationException(SR.ControlAccessibileObjectInvalid); } @@ -14650,8 +14612,7 @@ private void WmSetFocus(ref Message m) { bool activateSucceed; - ContainerControl knowncontainer = c as ContainerControl; - if (knowncontainer != null) + if (c is ContainerControl knowncontainer) { activateSucceed = knowncontainer.ActivateControlInternal(this); } @@ -15929,8 +15890,7 @@ public virtual void Remove(Control value) owner.OnControlRemoved(new ControlEventArgs(value)); // ContainerControl needs to see it needs to find a new ActiveControl. - ContainerControl cc = owner.GetContainerControl() as ContainerControl; - if (cc != null) + if (owner.GetContainerControl() is ContainerControl cc) { cc.AfterControlRemoved(value, owner); } @@ -17995,8 +17955,7 @@ internal void InPlaceActivate(int verb) // We also punt if this isn't an in-place site, since we can't // go active then. // - UnsafeNativeMethods.IOleInPlaceSite inPlaceSite = clientSite as UnsafeNativeMethods.IOleInPlaceSite; - if (inPlaceSite == null) + if (!(clientSite is UnsafeNativeMethods.IOleInPlaceSite inPlaceSite)) { return; } @@ -18146,7 +18105,6 @@ internal void InPlaceActivate(int verb) /// internal void InPlaceDeactivate() { - // Only do this if we're already in place active. // if (!activeXState[inPlaceActive]) @@ -18170,8 +18128,7 @@ internal void InPlaceDeactivate() // Notify our site of our deactivation. // - UnsafeNativeMethods.IOleInPlaceSite oleClientSite = clientSite as UnsafeNativeMethods.IOleInPlaceSite; - if (oleClientSite != null) + if (clientSite is UnsafeNativeMethods.IOleInPlaceSite oleClientSite) { oleClientSite.OnInPlaceDeactivate(); } @@ -18543,8 +18500,7 @@ internal void OnAmbientPropertyChange(int dispID) break; case NativeMethods.ActiveX.DISPID_AMBIENT_DISPLAYASDEFAULT: - IButtonControl ibuttonControl = control as IButtonControl; - if (ibuttonControl != null && GetAmbientProperty(NativeMethods.ActiveX.DISPID_AMBIENT_DISPLAYASDEFAULT, ref obj)) + if (control is IButtonControl ibuttonControl && GetAmbientProperty(NativeMethods.ActiveX.DISPID_AMBIENT_DISPLAYASDEFAULT, ref obj)) { ibuttonControl.NotifyDefault((bool)obj); } @@ -19284,8 +19240,7 @@ internal void SetExtent(int dwDrawAspect, NativeMethods.tagSIZEL pSizel) // if (activeXState[inPlaceActive]) { - UnsafeNativeMethods.IOleInPlaceSite ioleClientSite = clientSite as UnsafeNativeMethods.IOleInPlaceSite; - if (ioleClientSite != null) + if (clientSite is UnsafeNativeMethods.IOleInPlaceSite ioleClientSite) { Rectangle bounds = control.Bounds; bounds.Location = new Point(bounds.X, bounds.Y); @@ -19538,7 +19493,6 @@ internal static void ThrowHr(int hr) /// internal int TranslateAccelerator(ref NativeMethods.MSG lpmsg) { - #if DEBUG if (CompModSwitches.ActiveX.TraceInfo) { @@ -19611,8 +19565,7 @@ internal int TranslateAccelerator(ref NativeMethods.MSG lpmsg) Debug.WriteLineIf(CompModSwitches.ActiveX.TraceInfo, "AxSource: Control did not process accelerator, handing to site"); - UnsafeNativeMethods.IOleControlSite ioleClientSite = clientSite as UnsafeNativeMethods.IOleControlSite; - if (ioleClientSite != null) + if (clientSite is UnsafeNativeMethods.IOleControlSite ioleClientSite) { int keyState = 0; @@ -19662,8 +19615,7 @@ internal int UIDeactivate() Debug.Assert(inPlaceFrame != null, "No inplace frame -- how dod we go UI active?"); inPlaceFrame.SetActiveObject(null, null); - UnsafeNativeMethods.IOleInPlaceSite ioleClientSite = clientSite as UnsafeNativeMethods.IOleInPlaceSite; - if (ioleClientSite != null) + if (clientSite is UnsafeNativeMethods.IOleInPlaceSite ioleClientSite) { ioleClientSite.OnUIDeactivate(0); } @@ -19696,8 +19648,7 @@ internal void UpdateBounds(ref int x, ref int y, ref int width, ref int height, { if (!activeXState[adjustingRect] && activeXState[inPlaceVisible]) { - UnsafeNativeMethods.IOleInPlaceSite ioleClientSite = clientSite as UnsafeNativeMethods.IOleInPlaceSite; - if (ioleClientSite != null) + if (clientSite is UnsafeNativeMethods.IOleInPlaceSite ioleClientSite) { NativeMethods.COMRECT rc = new NativeMethods.COMRECT(); @@ -19760,8 +19711,7 @@ internal void UpdateAccelTable() // Setting the count to -1 will recreate the table on demand (when GetControlInfo is called). accelCount = -1; - UnsafeNativeMethods.IOleControlSite ioleClientSite = clientSite as UnsafeNativeMethods.IOleControlSite; - if (ioleClientSite != null) + if (clientSite is UnsafeNativeMethods.IOleControlSite ioleClientSite) { ioleClientSite.OnControlInfoChanged(); } @@ -20900,8 +20850,7 @@ internal Label PreviousLabel } // Find this control's containing control - ContainerControl container = parent.GetContainerControl() as ContainerControl; - if (container == null) + if (!(parent.GetContainerControl() is ContainerControl container)) { return null; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs index c2a47b858be..8cd20627d66 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs @@ -341,8 +341,7 @@ internal object this[int index] public override void AddNew() { - IBindingList ibl = list as IBindingList; - if (ibl != null) + if (list is IBindingList ibl) { ibl.AddNew(); } @@ -367,14 +366,12 @@ public override void CancelCurrentEdit() // onItemChangedCalled = false; - IEditableObject iEditableItem = item as IEditableObject; - if (iEditableItem != null) + if (item is IEditableObject iEditableItem) { iEditableItem.CancelEdit(); } - ICancelAddNew iListWithCancelAddNewSupport = list as ICancelAddNew; - if (iListWithCancelAddNewSupport != null) + if (list is ICancelAddNew iListWithCancelAddNewSupport) { iListWithCancelAddNewSupport.CancelNew(Position); } @@ -537,14 +534,12 @@ public override void EndCurrentEdit() { object item = (Position >= 0 && Position < list.Count) ? list[Position] : null; - IEditableObject iEditableItem = item as IEditableObject; - if (iEditableItem != null) + if (item is IEditableObject iEditableItem) { iEditableItem.EndEdit(); } - ICancelAddNew iListWithCancelAddNewSupport = list as ICancelAddNew; - if (iListWithCancelAddNewSupport != null) + if (list is ICancelAddNew iListWithCancelAddNewSupport) { iListWithCancelAddNewSupport.EndNew(Position); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs index b55c44c1a25..31cd5320fc4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs @@ -3742,8 +3742,7 @@ private void DataSource_ItemChanged(object sender, ItemChangedEventArgs ea) protected virtual void OnBorderStyleChanged(EventArgs e) { - EventHandler eh = Events[EVENT_BORDERSTYLECHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_BORDERSTYLECHANGED] is EventHandler eh) { eh(this, e); } @@ -3751,8 +3750,7 @@ protected virtual void OnBorderStyleChanged(EventArgs e) protected virtual void OnCaptionVisibleChanged(EventArgs e) { - EventHandler eh = Events[EVENT_CAPTIONVISIBLECHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_CAPTIONVISIBLECHANGED] is EventHandler eh) { eh(this, e); } @@ -3760,8 +3758,7 @@ protected virtual void OnCaptionVisibleChanged(EventArgs e) protected virtual void OnCurrentCellChanged(EventArgs e) { - EventHandler eh = Events[EVENT_CURRENTCELLCHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_CURRENTCELLCHANGED] is EventHandler eh) { eh(this, e); } @@ -3791,8 +3788,7 @@ protected void OnColumnHeaderClick(EventArgs e) { protected virtual void OnFlatModeChanged(EventArgs e) { - EventHandler eh = Events[EVENT_FLATMODECHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_FLATMODECHANGED] is EventHandler eh) { eh(this, e); } @@ -3800,8 +3796,7 @@ protected virtual void OnFlatModeChanged(EventArgs e) protected virtual void OnBackgroundColorChanged(EventArgs e) { - EventHandler eh = Events[EVENT_BACKGROUNDCOLORCHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_BACKGROUNDCOLORCHANGED] is EventHandler eh) { eh(this, e); } @@ -3809,8 +3804,7 @@ protected virtual void OnBackgroundColorChanged(EventArgs e) protected virtual void OnAllowNavigationChanged(EventArgs e) { - EventHandler eh = Events[EVENT_ALLOWNAVIGATIONCHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_ALLOWNAVIGATIONCHANGED] is EventHandler eh) { eh(this, e); } @@ -3818,8 +3812,7 @@ protected virtual void OnAllowNavigationChanged(EventArgs e) protected virtual void OnParentRowsVisibleChanged(EventArgs e) { - EventHandler eh = Events[EVENT_PARENTROWSVISIBLECHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_PARENTROWSVISIBLECHANGED] is EventHandler eh) { eh(this, e); } @@ -3827,8 +3820,7 @@ protected virtual void OnParentRowsVisibleChanged(EventArgs e) protected virtual void OnParentRowsLabelStyleChanged(EventArgs e) { - EventHandler eh = Events[EVENT_PARENTROWSLABELSTYLECHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_PARENTROWSLABELSTYLECHANGED] is EventHandler eh) { eh(this, e); } @@ -3836,8 +3828,7 @@ protected virtual void OnParentRowsLabelStyleChanged(EventArgs e) protected virtual void OnReadOnlyChanged(EventArgs e) { - EventHandler eh = Events[EVENT_READONLYCHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_READONLYCHANGED] is EventHandler eh) { eh(this, e); } @@ -4168,8 +4159,7 @@ protected override void OnBindingContextChanged(EventArgs e) protected virtual void OnDataSourceChanged(EventArgs e) { - EventHandler eh = Events[EVENT_DATASOURCECHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_DATASOURCECHANGED] is EventHandler eh) { eh(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs index b94b57f3fd7..8eaec897abe 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridBoolColumn.cs @@ -350,24 +350,21 @@ internal override bool MouseDown(int rowNum, int x, int y) private void OnTrueValueChanged(EventArgs e) { - EventHandler eh = Events[EventTrueValue] as EventHandler; - if (eh != null) + if (Events[EventTrueValue] is EventHandler eh) { eh(this, e); } } private void OnFalseValueChanged(EventArgs e) { - EventHandler eh = Events[EventFalseValue] as EventHandler; - if (eh != null) + if (Events[EventFalseValue] is EventHandler eh) { eh(this, e); } } private void OnAllowNullChanged(EventArgs e) { - EventHandler eh = Events[EventAllowNull] as EventHandler; - if (eh != null) + if (Events[EventAllowNull] is EventHandler eh) { eh(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs index 59127c20ca8..477f4ea70f3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs @@ -1710,8 +1710,7 @@ internal void OnColumnChanged(object sender, PropertyChangedEvent event) { #endif protected virtual void OnReadOnlyChanged(EventArgs e) { - EventHandler eh = Events[EventReadOnly] as EventHandler; - if (eh != null) + if (Events[EventReadOnly] is EventHandler eh) { eh(this, e); } @@ -1719,8 +1718,7 @@ protected virtual void OnReadOnlyChanged(EventArgs e) protected virtual void OnMappingNameChanged(EventArgs e) { - EventHandler eh = Events[EventMappingName] as EventHandler; - if (eh != null) + if (Events[EventMappingName] is EventHandler eh) { eh(this, e); } @@ -1728,8 +1726,7 @@ protected virtual void OnMappingNameChanged(EventArgs e) protected virtual void OnAlternatingBackColorChanged(EventArgs e) { - EventHandler eh = Events[EventAlternatingBackColor] as EventHandler; - if (eh != null) + if (Events[EventAlternatingBackColor] is EventHandler eh) { eh(this, e); } @@ -1737,8 +1734,7 @@ protected virtual void OnAlternatingBackColorChanged(EventArgs e) protected virtual void OnForeColorChanged(EventArgs e) { - EventHandler eh = Events[EventBackColor] as EventHandler; - if (eh != null) + if (Events[EventBackColor] is EventHandler eh) { eh(this, e); } @@ -1746,8 +1742,7 @@ protected virtual void OnForeColorChanged(EventArgs e) protected virtual void OnBackColorChanged(EventArgs e) { - EventHandler eh = Events[EventForeColor] as EventHandler; - if (eh != null) + if (Events[EventForeColor] is EventHandler eh) { eh(this, e); } @@ -1755,120 +1750,105 @@ protected virtual void OnBackColorChanged(EventArgs e) protected virtual void OnAllowSortingChanged(EventArgs e) { - EventHandler eh = Events[EventAllowSorting] as EventHandler; - if (eh != null) + if (Events[EventAllowSorting] is EventHandler eh) { eh(this, e); } } protected virtual void OnGridLineColorChanged(EventArgs e) { - EventHandler eh = Events[EventGridLineColor] as EventHandler; - if (eh != null) + if (Events[EventGridLineColor] is EventHandler eh) { eh(this, e); } } protected virtual void OnGridLineStyleChanged(EventArgs e) { - EventHandler eh = Events[EventGridLineStyle] as EventHandler; - if (eh != null) + if (Events[EventGridLineStyle] is EventHandler eh) { eh(this, e); } } protected virtual void OnHeaderBackColorChanged(EventArgs e) { - EventHandler eh = Events[EventHeaderBackColor] as EventHandler; - if (eh != null) + if (Events[EventHeaderBackColor] is EventHandler eh) { eh(this, e); } } protected virtual void OnHeaderFontChanged(EventArgs e) { - EventHandler eh = Events[EventHeaderFont] as EventHandler; - if (eh != null) + if (Events[EventHeaderFont] is EventHandler eh) { eh(this, e); } } protected virtual void OnHeaderForeColorChanged(EventArgs e) { - EventHandler eh = Events[EventHeaderForeColor] as EventHandler; - if (eh != null) + if (Events[EventHeaderForeColor] is EventHandler eh) { eh(this, e); } } protected virtual void OnLinkColorChanged(EventArgs e) { - EventHandler eh = Events[EventLinkColor] as EventHandler; - if (eh != null) + if (Events[EventLinkColor] is EventHandler eh) { eh(this, e); } } protected virtual void OnLinkHoverColorChanged(EventArgs e) { - EventHandler eh = Events[EventLinkHoverColor] as EventHandler; - if (eh != null) + if (Events[EventLinkHoverColor] is EventHandler eh) { eh(this, e); } } protected virtual void OnPreferredRowHeightChanged(EventArgs e) { - EventHandler eh = Events[EventPreferredRowHeight] as EventHandler; - if (eh != null) + if (Events[EventPreferredRowHeight] is EventHandler eh) { eh(this, e); } } protected virtual void OnPreferredColumnWidthChanged(EventArgs e) { - EventHandler eh = Events[EventPreferredColumnWidth] as EventHandler; - if (eh != null) + if (Events[EventPreferredColumnWidth] is EventHandler eh) { eh(this, e); } } protected virtual void OnColumnHeadersVisibleChanged(EventArgs e) { - EventHandler eh = Events[EventColumnHeadersVisible] as EventHandler; - if (eh != null) + if (Events[EventColumnHeadersVisible] is EventHandler eh) { eh(this, e); } } protected virtual void OnRowHeadersVisibleChanged(EventArgs e) { - EventHandler eh = Events[EventRowHeadersVisible] as EventHandler; - if (eh != null) + if (Events[EventRowHeadersVisible] is EventHandler eh) { eh(this, e); } } protected virtual void OnRowHeaderWidthChanged(EventArgs e) { - EventHandler eh = Events[EventRowHeaderWidth] as EventHandler; - if (eh != null) + if (Events[EventRowHeaderWidth] is EventHandler eh) { eh(this, e); } } protected virtual void OnSelectionForeColorChanged(EventArgs e) { - EventHandler eh = Events[EventSelectionForeColor] as EventHandler; - if (eh != null) + if (Events[EventSelectionForeColor] is EventHandler eh) { eh(this, e); } } protected virtual void OnSelectionBackColorChanged(EventArgs e) { - EventHandler eh = Events[EventSelectionBackColor] as EventHandler; - if (eh != null) + if (Events[EventSelectionBackColor] is EventHandler eh) { eh(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridView.cs index 8862052d073..ecacc400d65 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridView.cs @@ -3472,8 +3472,7 @@ private bool IsMinimized { get { - Form parentForm = TopLevelControlInternal as Form; - return parentForm != null && parentForm.WindowState == FormWindowState.Minimized; + return TopLevelControlInternal is Form parentForm && parentForm.WindowState == FormWindowState.Minimized; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAdvancedBorderStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAdvancedBorderStyle.cs index 22d4466d502..d70fb2a8bde 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAdvancedBorderStyle.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAdvancedBorderStyle.cs @@ -297,9 +297,7 @@ internal DataGridViewAdvancedCellBorderStyle TopInternal public override bool Equals(object other) { - DataGridViewAdvancedBorderStyle dgvabsOther = other as DataGridViewAdvancedBorderStyle; - - if (dgvabsOther == null) + if (!(other is DataGridViewAdvancedBorderStyle dgvabsOther)) { return false; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewBand.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewBand.cs index 55ac9adb28b..cff24107d10 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewBand.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewBand.cs @@ -343,8 +343,7 @@ protected DataGridViewHeaderCell HeaderCellCore } else { - DataGridViewColumnHeaderCell dataGridViewColumnHeaderCell = value as DataGridViewColumnHeaderCell; - if (dataGridViewColumnHeaderCell == null) + if (!(value is DataGridViewColumnHeaderCell dataGridViewColumnHeaderCell)) { throw new ArgumentException(string.Format(SR.DataGridView_WrongType, nameof(DataGridViewColumn.HeaderCell), "System.Windows.Forms.DataGridViewColumnHeaderCell"), nameof(value)); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonColumn.cs index e56ba37bac8..589c01cace6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonColumn.cs @@ -96,8 +96,7 @@ public FlatStyle FlatStyle for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewButtonCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewButtonCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewButtonCell dataGridViewCell) { dataGridViewCell.FlatStyleInternal = value; } @@ -137,8 +136,7 @@ public string Text for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewButtonCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewButtonCell; - if (dataGridViewCell != null && dataGridViewCell.UseColumnTextForButtonValue) + if (dataGridViewRow.Cells[Index] is DataGridViewButtonCell dataGridViewCell && dataGridViewCell.UseColumnTextForButtonValue) { DataGridView.OnColumnCommonChange(Index); return; @@ -178,8 +176,7 @@ public bool UseColumnTextForButtonValue for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewButtonCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewButtonCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewButtonCell dataGridViewCell) { dataGridViewCell.UseColumnTextForButtonValueInternal = value; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs index 5ecc6ac84c4..b5b0950c504 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs @@ -1264,8 +1264,7 @@ public virtual void DetachEditingControl() { if (dgv.EditingControl.ContainsFocus) { - ContainerControl cc = dgv.GetContainerControl() as ContainerControl; - if (cc != null && (dgv.EditingControl == cc.ActiveControl || dgv.EditingControl.Contains(cc.ActiveControl))) + if (dgv.GetContainerControl() is ContainerControl cc && (dgv.EditingControl == cc.ActiveControl || dgv.EditingControl.Contains(cc.ActiveControl))) { dgv.Focus(); } @@ -1739,8 +1738,7 @@ internal object GetEditedFormattedValue(object value, int rowIndex, ref DataGrid { return dgvectl.GetEditingControlFormattedValue(context); } - IDataGridViewEditingCell dgvecell = this as IDataGridViewEditingCell; - if (dgvecell != null && DataGridView.IsCurrentCellInEditMode) + if (this is IDataGridViewEditingCell dgvecell && DataGridView.IsCurrentCellInEditMode) { return dgvecell.GetEditingCellFormattedValue(context); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellConverter.cs index 9f5f045f2b9..cff1c3a8f57 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellConverter.cs @@ -32,8 +32,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul throw new ArgumentNullException(nameof(destinationType)); } - DataGridViewCell cell = value as DataGridViewCell; - if (destinationType == typeof(InstanceDescriptor) && cell != null) + if (destinationType == typeof(InstanceDescriptor) && value is DataGridViewCell cell) { ConstructorInfo ctor = cell.GetType().GetConstructor(new Type[0]); if (ctor != null) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyle.cs index 64766c09455..64bcbb0d507 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyle.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyle.cs @@ -633,8 +633,7 @@ public virtual DataGridViewCellStyle Clone() public override bool Equals(object o) { - DataGridViewCellStyle dgvcs = o as DataGridViewCellStyle; - if (dgvcs != null) + if (o is DataGridViewCellStyle dgvcs) { return GetDifferencesFrom(dgvcs) == DataGridViewCellStyleDifferences.None; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs index 5e4540dc420..d39bb9ba26e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs @@ -1808,8 +1808,7 @@ public override void DoDefaultAction() dataGridView.InvalidateCell(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex); // notify MSAA clients that the default action changed - DataGridViewCheckBoxCell checkBoxCell = Owner as DataGridViewCheckBoxCell; - if (checkBoxCell != null) + if (Owner is DataGridViewCheckBoxCell checkBoxCell) { checkBoxCell.NotifyMASSClient(new Point(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex)); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxColumn.cs index ebd3cdc1612..9998c770bf8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxColumn.cs @@ -113,8 +113,7 @@ public object FalseValue for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewCheckBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewCheckBoxCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewCheckBoxCell dataGridViewCell) { dataGridViewCell.FalseValueInternal = value; } @@ -152,8 +151,7 @@ public FlatStyle FlatStyle for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewCheckBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewCheckBoxCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewCheckBoxCell dataGridViewCell) { dataGridViewCell.FlatStyleInternal = value; } @@ -192,8 +190,7 @@ public object IndeterminateValue for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewCheckBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewCheckBoxCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewCheckBoxCell dataGridViewCell) { dataGridViewCell.IndeterminateValueInternal = value; } @@ -234,8 +231,7 @@ public bool ThreeState for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewCheckBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewCheckBoxCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewCheckBoxCell dataGridViewCell) { dataGridViewCell.ThreeStateInternal = value; } @@ -287,8 +283,7 @@ public object TrueValue for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewCheckBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewCheckBoxCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewCheckBoxCell dataGridViewCell) { dataGridViewCell.TrueValueInternal = value; } @@ -302,8 +297,7 @@ public object TrueValue private bool ShouldSerializeDefaultCellStyle() { object defaultNullValue; - DataGridViewCheckBoxCell templateCell = CellTemplate as DataGridViewCheckBoxCell; - if (templateCell == null) + if (!(CellTemplate is DataGridViewCheckBoxCell templateCell)) { Debug.Fail("we can't compute the default cell style w/o a template cell"); return true; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumn.cs index dbc0b3bb1c7..16f500275f4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumn.cs @@ -540,8 +540,7 @@ public string HeaderText { if (HasHeaderCell) { - string headerValue = HeaderCell.Value as string; - if (headerValue != null) + if (HeaderCell.Value is string headerValue) { return headerValue; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnConverter.cs index 8060d2fd384..a6753476f66 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnConverter.cs @@ -43,8 +43,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul throw new ArgumentNullException(nameof(destinationType)); } - DataGridViewColumn dataGridViewColumn = value as DataGridViewColumn; - if (destinationType == typeof(InstanceDescriptor) && dataGridViewColumn != null) + if (destinationType == typeof(InstanceDescriptor) && value is DataGridViewColumn dataGridViewColumn) { ConstructorInfo ctor; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnDesignTimeVisibleAttribute.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnDesignTimeVisibleAttribute.cs index 8574d11af75..a88c70722e4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnDesignTimeVisibleAttribute.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnDesignTimeVisibleAttribute.cs @@ -53,8 +53,7 @@ public override bool Equals(object obj) return true; } - DataGridViewColumnDesignTimeVisibleAttribute other = obj as DataGridViewColumnDesignTimeVisibleAttribute; - return other != null && other.Visible == visible; + return obj is DataGridViewColumnDesignTimeVisibleAttribute other && other.Visible == visible; } public override int GetHashCode() diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs index ca0763e41b5..9842a0cadcd 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs @@ -780,8 +780,7 @@ private void ComboBox_DropDown(object sender, EventArgs e) Debug.Assert(EditingComboBox != null); ComboBox comboBox = EditingComboBox; - DataGridViewComboBoxColumn owningComboBoxColumn = OwningColumn as DataGridViewComboBoxColumn; - if (owningComboBoxColumn != null) + if (OwningColumn is DataGridViewComboBoxColumn owningComboBoxColumn) { DataGridViewAutoSizeColumnMode autoSizeColumnMode = owningComboBoxColumn.GetInheritedAutoSizeMode(DataGridView); if (autoSizeColumnMode != DataGridViewAutoSizeColumnMode.ColumnHeader && @@ -889,9 +888,8 @@ private void DataSource_Initialized(object sender, EventArgs e) Debug.Assert(DataSource is ISupportInitializeNotification); Debug.Assert((flags & DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp) != 0x00); - ISupportInitializeNotification dsInit = DataSource as ISupportInitializeNotification; // Unhook the Initialized event. - if (dsInit != null) + if (DataSource is ISupportInitializeNotification dsInit) { dsInit.Initialized -= new EventHandler(DataSource_Initialized); } @@ -984,8 +982,7 @@ private CurrencyManager GetDataManager(DataGridView dataGridView) CurrencyManager cm = (CurrencyManager)Properties.GetObject(PropComboBoxCellDataManager); if (cm == null && DataSource != null && dataGridView != null && dataGridView.BindingContext != null && !(DataSource == Convert.DBNull)) { - ISupportInitializeNotification dsInit = DataSource as ISupportInitializeNotification; - if (dsInit != null && !dsInit.IsInitialized) + if (DataSource is ISupportInitializeNotification dsInit && !dsInit.IsInitialized) { if ((flags & DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp) == 0x00) { @@ -1463,8 +1460,7 @@ public override void InitializeEditingControl(int rowIndex, object initialFormat DataGridView.EditingControl != null); Debug.Assert(!ReadOnly); base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle); - ComboBox comboBox = DataGridView.EditingControl as ComboBox; - if (comboBox != null) + if (DataGridView.EditingControl is ComboBox comboBox) { // Use the selection backcolor for the editing panel when the cell is selected if ((GetInheritedState(rowIndex) & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) @@ -1518,8 +1514,7 @@ And this causes problems when changing position inside the DataGridView. comboBox.AutoCompleteSource = AutoCompleteSource.None; } - string initialFormattedValueStr = initialFormattedValue as string; - if (initialFormattedValueStr == null) + if (!(initialFormattedValue is string initialFormattedValueStr)) { initialFormattedValueStr = string.Empty; } @@ -2527,9 +2522,8 @@ private Rectangle PaintPrivate(Graphics g, } } - string formattedString = formattedValue as string; - if (formattedString != null) + if (formattedValue is string formattedString) { // Font independent margins int verticalTextMarginTop = cellStyle.WrapMode == DataGridViewTriState.True ? DATAGRIDVIEWCOMBOBOXCELL_verticalTextMarginTopWithWrapping : DATAGRIDVIEWCOMBOBOXCELL_verticalTextMarginTopWithoutWrapping; @@ -2662,14 +2656,12 @@ public override string ToString() private void UnwireDataSource() { - IComponent component = DataSource as IComponent; - if (component != null) + if (DataSource is IComponent component) { component.Disposed -= new EventHandler(DataSource_Disposed); } - ISupportInitializeNotification dsInit = DataSource as ISupportInitializeNotification; - if (dsInit != null && (flags & DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp) != 0x00) + if (DataSource is ISupportInitializeNotification dsInit && (flags & DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp) != 0x00) { // If we previously hooked the data source's ISupportInitializeNotification // Initialized event, then unhook it now (we don't always hook this event, @@ -2683,8 +2675,7 @@ private void WireDataSource(object dataSource) { // If the source is a component, then hook the Disposed event, // so we know when the component is deleted from the form - IComponent component = dataSource as IComponent; - if (component != null) + if (dataSource is IComponent component) { component.Disposed += new EventHandler(DataSource_Disposed); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxColumn.cs index 27239030b83..f7e80bc37ac 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxColumn.cs @@ -53,8 +53,7 @@ public bool AutoComplete for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewComboBoxCell dataGridViewCell) { dataGridViewCell.AutoComplete = value; } @@ -128,8 +127,7 @@ public object DataSource for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewComboBoxCell dataGridViewCell) { dataGridViewCell.DataSource = value; } @@ -170,8 +168,7 @@ public string DisplayMember for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewComboBoxCell dataGridViewCell) { dataGridViewCell.DisplayMember = value; } @@ -210,8 +207,7 @@ public DataGridViewComboBoxDisplayStyle DisplayStyle for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewComboBoxCell dataGridViewCell) { dataGridViewCell.DisplayStyleInternal = value; } @@ -251,8 +247,7 @@ public bool DisplayStyleForCurrentCellOnly for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewComboBoxCell dataGridViewCell) { dataGridViewCell.DisplayStyleForCurrentCellOnlyInternal = value; } @@ -290,8 +285,7 @@ public int DropDownWidth for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewComboBoxCell dataGridViewCell) { dataGridViewCell.DropDownWidth = value; } @@ -328,8 +322,7 @@ public FlatStyle FlatStyle for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewComboBoxCell dataGridViewCell) { dataGridViewCell.FlatStyleInternal = value; } @@ -389,8 +382,7 @@ public string ValueMember for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewComboBoxCell dataGridViewCell) { dataGridViewCell.ValueMember = value; } @@ -427,8 +419,7 @@ public int MaxDropDownItems for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewComboBoxCell dataGridViewCell) { dataGridViewCell.MaxDropDownItems = value; } @@ -465,8 +456,7 @@ public bool Sorted for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewComboBoxCell dataGridViewCell) { dataGridViewCell.Sorted = value; } @@ -511,8 +501,7 @@ internal void OnItemsCollectionChanged() for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewComboBoxCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewComboBoxCell dataGridViewCell) { dataGridViewCell.Items.ClearInternal(); dataGridViewCell.Items.AddRangeInternal(items); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxEditingControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxEditingControl.cs index 7ed70c4925e..2b645e80e7f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxEditingControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxEditingControl.cs @@ -52,8 +52,7 @@ public virtual object EditingControlFormattedValue } set { - string valueStr = value as string; - if (valueStr != null) + if (value is string valueStr) { Text = valueStr; if (string.Compare(valueStr, Text, true, CultureInfo.CurrentCulture) != 0) @@ -191,8 +190,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga switch (direction) { case UnsafeNativeMethods.NavigateDirection.Parent: - var owner = Owner as IDataGridViewEditingControl; - if (owner != null && owner.EditingControlDataGridView.EditingControl == owner) + if (Owner is IDataGridViewEditingControl owner && owner.EditingControlDataGridView.EditingControl == owner) { return _parentAccessibleObject; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewDataConnection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewDataConnection.cs index 6e73a7ec3c1..02a876c5ee5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewDataConnection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewDataConnection.cs @@ -813,8 +813,7 @@ private void currencyManager_PositionChanged(object sender, EventArgs e) // row is being committed, don't scroll it into view. if (dataConnectionState[DATACONNECTIONSTATE_rowValidatingInAddNew]) { - IBindingList ibl = currencyManager.List as IBindingList; - if (ibl != null && ibl.SupportsSorting && ibl.IsSorted) + if (currencyManager.List is IBindingList ibl && ibl.SupportsSorting && ibl.IsSorted) { scrollIntoView = false; } @@ -864,9 +863,8 @@ private void DataSource_Initialized(object sender, EventArgs e) Debug.Assert(dataSource is ISupportInitializeNotification); Debug.Assert(dataConnectionState[DATACONNECTIONSTATE_dataSourceInitializedHookedUp]); - ISupportInitializeNotification dsInit = dataSource as ISupportInitializeNotification; // Unhook the Initialized event. - if (dsInit != null) + if (dataSource is ISupportInitializeNotification dsInit) { dsInit.Initialized -= new EventHandler(DataSource_Initialized); } @@ -1127,8 +1125,7 @@ public void SetDataConnection(object dataSource, string dataMember) dataMember = string.Empty; } - ISupportInitializeNotification dsInit = this.dataSource as ISupportInitializeNotification; - if (dsInit != null && dataConnectionState[DATACONNECTIONSTATE_dataSourceInitializedHookedUp]) + if (this.dataSource is ISupportInitializeNotification dsInit && dataConnectionState[DATACONNECTIONSTATE_dataSourceInitializedHookedUp]) { // If we previously hooked the data source's ISupportInitializeNotification // Initialized event, then unhook it now (we don't always hook this event, @@ -1463,8 +1460,7 @@ internal void OnRowEnter(DataGridViewCellEventArgs e) ProcessException(exception, dgvce, false /*beginEdit*/); } - IEditableObject iEditObj = currencyManager.Current as IEditableObject; - if (iEditObj != null) + if (currencyManager.Current is IEditableObject iEditObj) { iEditObj.BeginEdit(); } @@ -1548,8 +1544,7 @@ public void ProcessException(Exception exception, DataGridViewCellCancelEventArg e.Cancel = true; if (beginEdit) { - IEditableObject iEditObj = currencyManager.Current as IEditableObject; - if (iEditObj != null) + if (currencyManager.Current is IEditableObject iEditObj) { iEditObj.BeginEdit(); } @@ -1624,8 +1619,7 @@ public bool ShouldChangeDataMember(object newDataSource) return true; } - CurrencyManager cm = owner.BindingContext[newDataSource] as CurrencyManager; - if (cm == null) + if (!(owner.BindingContext[newDataSource] is CurrencyManager cm)) { // if we don't have a currency manager then the data member can be valid return false; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHitTestInfo.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHitTestInfo.cs index d7c255369d1..bf44ef5867d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHitTestInfo.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHitTestInfo.cs @@ -99,8 +99,7 @@ public DataGridViewHitTestType Type /// public override bool Equals(object value) { - HitTestInfo hti = value as HitTestInfo; - if (hti != null) + if (value is HitTestInfo hti) { return (type == hti.type && row == hti.row && diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageCell.cs index e468a19e972..58459d0a26d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageCell.cs @@ -415,8 +415,7 @@ protected override object GetFormattedValue(object value, } if (ValueIsIcon) { - Icon ico = formattedValue as Icon; - if (ico == null) + if (!(formattedValue is Icon ico)) { ico = ErrorIcon; } @@ -424,8 +423,7 @@ protected override object GetFormattedValue(object value, } else { - Image img = formattedValue as Image; - if (img == null) + if (!(formattedValue is Image img)) { img = ErrorBitmap; } @@ -578,8 +576,7 @@ protected override object GetValue(int rowIndex) object valueBase = base.GetValue(rowIndex); if (valueBase == null) { - DataGridViewImageColumn owningImageColumn = OwningColumn as DataGridViewImageColumn; - if (owningImageColumn != null) + if (OwningColumn is DataGridViewImageColumn owningImageColumn) { if (defaultTypeImage.IsAssignableFrom(ValueType)) { @@ -973,8 +970,7 @@ public override string Description { get { - DataGridViewImageCell imageCell = Owner as DataGridViewImageCell; - if (imageCell != null) + if (Owner is DataGridViewImageCell imageCell) { return imageCell.Description; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageColumn.cs index 133596a9a54..7e958af4cfa 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageColumn.cs @@ -112,8 +112,7 @@ public string Description for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewImageCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewImageCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewImageCell dataGridViewCell) { dataGridViewCell.Description = value; } @@ -203,8 +202,7 @@ public DataGridViewImageCellLayout ImageLayout for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewImageCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewImageCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewImageCell dataGridViewCell) { dataGridViewCell.ImageLayoutInternal = value; } @@ -241,8 +239,7 @@ public bool ValuesAreIcons for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewImageCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewImageCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewImageCell dataGridViewCell) { dataGridViewCell.ValueIsIconInternal = value; } @@ -292,8 +289,7 @@ public override object Clone() private bool ShouldSerializeDefaultCellStyle() { - DataGridViewImageCell templateCell = CellTemplate as DataGridViewImageCell; - if (templateCell == null) + if (!(CellTemplate is DataGridViewImageCell templateCell)) { Debug.Fail("we can't compute the default cell style w/o a template cell"); return true; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkCell.cs index 1e882b7ed28..cb434dba1c8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkCell.cs @@ -996,9 +996,8 @@ private Rectangle PaintPrivate(Graphics g, } Rectangle errorBounds = valBounds; - string formattedValueStr = formattedValue as string; - if (formattedValueStr != null && (paint || computeContentBounds)) + if (formattedValue is string formattedValueStr && (paint || computeContentBounds)) { // Font independent margins valBounds.Offset(DATAGRIDVIEWLINKCELL_horizontalTextMarginLeft, DATAGRIDVIEWLINKCELL_verticalTextMarginTop); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkColumn.cs index 38fa76c4187..660c3b33f54 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkColumn.cs @@ -48,8 +48,7 @@ public Color ActiveLinkColor for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewLinkCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewLinkCell dataGridViewCell) { dataGridViewCell.ActiveLinkColorInternal = value; } @@ -117,8 +116,7 @@ public LinkBehavior LinkBehavior for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewLinkCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewLinkCell dataGridViewCell) { dataGridViewCell.LinkBehaviorInternal = value; } @@ -155,8 +153,7 @@ public Color LinkColor for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewLinkCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewLinkCell dataGridViewCell) { dataGridViewCell.LinkColorInternal = value; } @@ -206,8 +203,7 @@ public string Text for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewLinkCell; - if (dataGridViewCell != null && dataGridViewCell.UseColumnTextForLinkValue) + if (dataGridViewRow.Cells[Index] is DataGridViewLinkCell dataGridViewCell && dataGridViewCell.UseColumnTextForLinkValue) { DataGridView.OnColumnCommonChange(Index); return; @@ -247,8 +243,7 @@ public bool TrackVisitedState for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewLinkCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewLinkCell dataGridViewCell) { dataGridViewCell.TrackVisitedStateInternal = value; } @@ -286,8 +281,7 @@ public bool UseColumnTextForLinkValue for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewLinkCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewLinkCell dataGridViewCell) { dataGridViewCell.UseColumnTextForLinkValueInternal = value; } @@ -324,8 +318,7 @@ public Color VisitedLinkColor for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewLinkCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewLinkCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewLinkCell dataGridViewCell) { dataGridViewCell.VisitedLinkColorInternal = value; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs index e4b145100b1..14ae23e639e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs @@ -5923,8 +5923,7 @@ private void EditingControls_Click(object sender, System.EventArgs e) { Debug.Assert(sender == editingControl || sender == editingPanel); Debug.Assert(ptCurrentCell.X != -1); - System.Windows.Forms.MouseEventArgs me = e as System.Windows.Forms.MouseEventArgs; - if (me != null) + if (e is System.Windows.Forms.MouseEventArgs me) { EditingControls_CommonMouseEventHandler(sender, me, DataGridViewMouseEvent.Click); } @@ -5934,8 +5933,7 @@ private void EditingControls_DoubleClick(object sender, System.EventArgs e) { Debug.Assert(sender == editingControl || sender == editingPanel); Debug.Assert(ptCurrentCell.X != -1); - System.Windows.Forms.MouseEventArgs me = e as System.Windows.Forms.MouseEventArgs; - if (me != null) + if (e is System.Windows.Forms.MouseEventArgs me) { EditingControls_CommonMouseEventHandler(sender, me, DataGridViewMouseEvent.DoubleClick); } @@ -11161,8 +11159,7 @@ protected virtual void OnAllowUserToAddRowsChanged(EventArgs e) { PushAllowUserToAddRows(); - EventHandler eh = Events[EVENT_DATAGRIDVIEWALLOWUSERTOADDROWSCHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWALLOWUSERTOADDROWSCHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11170,8 +11167,7 @@ protected virtual void OnAllowUserToAddRowsChanged(EventArgs e) protected virtual void OnAllowUserToDeleteRowsChanged(EventArgs e) { - EventHandler eh = Events[EVENT_DATAGRIDVIEWALLOWUSERTODELETEROWSCHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWALLOWUSERTODELETEROWSCHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11179,8 +11175,7 @@ protected virtual void OnAllowUserToDeleteRowsChanged(EventArgs e) protected virtual void OnAllowUserToOrderColumnsChanged(EventArgs e) { - EventHandler eh = Events[EVENT_DATAGRIDVIEWALLOWUSERTOORDERCOLUMNSCHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWALLOWUSERTOORDERCOLUMNSCHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11188,8 +11183,7 @@ protected virtual void OnAllowUserToOrderColumnsChanged(EventArgs e) protected virtual void OnAllowUserToResizeColumnsChanged(EventArgs e) { - EventHandler eh = Events[EVENT_DATAGRIDVIEWALLOWUSERTORESIZECOLUMNSCHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWALLOWUSERTORESIZECOLUMNSCHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11197,8 +11191,7 @@ protected virtual void OnAllowUserToResizeColumnsChanged(EventArgs e) protected virtual void OnAllowUserToResizeRowsChanged(EventArgs e) { - EventHandler eh = Events[EVENT_DATAGRIDVIEWALLOWUSERTORESIZEROWSCHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWALLOWUSERTORESIZEROWSCHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11206,8 +11199,7 @@ protected virtual void OnAllowUserToResizeRowsChanged(EventArgs e) protected virtual void OnAlternatingRowsDefaultCellStyleChanged(EventArgs e) { - DataGridViewCellStyleChangedEventArgs dgvcsce = e as DataGridViewCellStyleChangedEventArgs; - if (dgvcsce != null && !dgvcsce.ChangeAffectsPreferredSize) + if (e is DataGridViewCellStyleChangedEventArgs dgvcsce && !dgvcsce.ChangeAffectsPreferredSize) { InvalidateData(); } @@ -11220,8 +11212,7 @@ protected virtual void OnAlternatingRowsDefaultCellStyleChanged(EventArgs e) } } - EventHandler eh = Events[EVENT_DATAGRIDVIEWALTERNATINGROWSDEFAULTCELLSTYLECHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWALTERNATINGROWSDEFAULTCELLSTYLECHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11234,8 +11225,7 @@ protected virtual void OnAutoGenerateColumnsChanged(EventArgs e) // refresh the list of columns and the rows RefreshColumnsAndRows(); } - EventHandler eh = Events[EVENT_DATAGRIDVIEWAUTOGENERATECOLUMNSCHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWAUTOGENERATECOLUMNSCHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11313,8 +11303,7 @@ protected virtual void OnAutoSizeColumnModeChanged(DataGridViewAutoSizeColumnMod } } - DataGridViewAutoSizeColumnModeEventHandler eh = Events[EVENT_DATAGRIDVIEWAUTOSIZECOLUMNMODECHANGED] as DataGridViewAutoSizeColumnModeEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWAUTOSIZECOLUMNMODECHANGED] is DataGridViewAutoSizeColumnModeEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11399,8 +11388,7 @@ protected virtual void OnAutoSizeColumnsModeChanged(DataGridViewAutoSizeColumnsM } } - DataGridViewAutoSizeColumnsModeEventHandler eh = Events[EVENT_DATAGRIDVIEWAUTOSIZECOLUMNSMODECHANGED] as DataGridViewAutoSizeColumnsModeEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWAUTOSIZECOLUMNSMODECHANGED] is DataGridViewAutoSizeColumnsModeEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11431,8 +11419,7 @@ protected virtual void OnAutoSizeRowsModeChanged(DataGridViewAutoSizeModeEventAr AdjustShrinkingRows(autoSizeRowsMode, true /*fixedWidth*/, true /*internalAutosizing*/); } - DataGridViewAutoSizeModeEventHandler eh = Events[EVENT_DATAGRIDVIEWAUTOSIZEROWSMODECHANGED] as DataGridViewAutoSizeModeEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWAUTOSIZEROWSMODECHANGED] is DataGridViewAutoSizeModeEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11442,8 +11429,7 @@ protected virtual void OnBackgroundColorChanged(EventArgs e) { InvalidateInside(); - EventHandler eh = Events[EVENT_DATAGRIDVIEWBACKGROUNDCOLORCHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWBACKGROUNDCOLORCHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11451,8 +11437,7 @@ protected virtual void OnBackgroundColorChanged(EventArgs e) internal void OnBandContextMenuStripChanged(DataGridViewBand dataGridViewBand) { - DataGridViewColumn dataGridViewColumn = dataGridViewBand as DataGridViewColumn; - if (dataGridViewColumn != null) + if (dataGridViewBand is DataGridViewColumn dataGridViewColumn) { DataGridViewColumnEventArgs dgvce = new DataGridViewColumnEventArgs(dataGridViewColumn); OnColumnContextMenuStripChanged(dgvce); @@ -11466,8 +11451,7 @@ internal void OnBandContextMenuStripChanged(DataGridViewBand dataGridViewBand) internal void OnBandDefaultCellStyleChanged(DataGridViewBand dataGridViewBand) { - DataGridViewColumn dataGridViewColumn = dataGridViewBand as DataGridViewColumn; - if (dataGridViewColumn != null) + if (dataGridViewBand is DataGridViewColumn dataGridViewColumn) { DataGridViewColumnEventArgs dgvce = new DataGridViewColumnEventArgs(dataGridViewColumn); OnColumnDefaultCellStyleChanged(dgvce); @@ -11481,8 +11465,7 @@ internal void OnBandDefaultCellStyleChanged(DataGridViewBand dataGridViewBand) internal void OnBandDividerThicknessChanged(DataGridViewBand dataGridViewBand) { - DataGridViewColumn dataGridViewColumn = dataGridViewBand as DataGridViewColumn; - if (dataGridViewColumn != null) + if (dataGridViewBand is DataGridViewColumn dataGridViewColumn) { DataGridViewColumnEventArgs dgvce = new DataGridViewColumnEventArgs(dataGridViewColumn); OnColumnDividerWidthChanged(dgvce); @@ -11496,8 +11479,7 @@ internal void OnBandDividerThicknessChanged(DataGridViewBand dataGridViewBand) internal void OnBandHeaderCellChanged(DataGridViewBand dataGridViewBand) { - DataGridViewColumn dataGridViewColumn = dataGridViewBand as DataGridViewColumn; - if (dataGridViewColumn != null) + if (dataGridViewBand is DataGridViewColumn dataGridViewColumn) { DataGridViewColumnEventArgs dgvce = new DataGridViewColumnEventArgs(dataGridViewColumn); OnColumnHeaderCellChanged(dgvce); @@ -11511,8 +11493,7 @@ internal void OnBandHeaderCellChanged(DataGridViewBand dataGridViewBand) internal void OnBandMinimumThicknessChanged(DataGridViewBand dataGridViewBand) { - DataGridViewColumn dataGridViewColumn = dataGridViewBand as DataGridViewColumn; - if (dataGridViewColumn != null) + if (dataGridViewBand is DataGridViewColumn dataGridViewColumn) { DataGridViewColumnEventArgs dgvce = new DataGridViewColumnEventArgs(dataGridViewColumn); OnColumnMinimumWidthChanged(dgvce); @@ -11526,8 +11507,7 @@ internal void OnBandMinimumThicknessChanged(DataGridViewBand dataGridViewBand) internal void OnBandThicknessChanged(DataGridViewBand dataGridViewBand) { - DataGridViewColumn dataGridViewColumn = dataGridViewBand as DataGridViewColumn; - if (dataGridViewColumn != null) + if (dataGridViewBand is DataGridViewColumn dataGridViewColumn) { DataGridViewColumnEventArgs dgvce = new DataGridViewColumnEventArgs(dataGridViewColumn); OnColumnWidthChanged(dgvce); @@ -11599,8 +11579,7 @@ protected override void OnBindingContextChanged(EventArgs e) protected virtual void OnBorderStyleChanged(EventArgs e) { - EventHandler eh = Events[EVENT_DATAGRIDVIEWBORDERSTYLECHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWBORDERSTYLECHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11608,8 +11587,7 @@ protected virtual void OnBorderStyleChanged(EventArgs e) protected virtual void OnCancelRowEdit(QuestionEventArgs e) { - QuestionEventHandler eh = Events[EVENT_DATAGRIDVIEWCANCELROWEDIT] as QuestionEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCANCELROWEDIT] is QuestionEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); CorrectFocus(true /*onlyIfGridHasFocus*/); @@ -11627,8 +11605,7 @@ protected virtual void OnCellBeginEdit(DataGridViewCellCancelEventArgs e) { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellCancelEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLBEGINEDIT] as DataGridViewCellCancelEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLBEGINEDIT] is DataGridViewCellCancelEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11639,8 +11616,7 @@ protected virtual void OnCellBorderStyleChanged(EventArgs e) PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); Invalidate(); - EventHandler eh = Events[EVENT_DATAGRIDVIEWCELLBORDERSTYLECHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLBORDERSTYLECHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11674,8 +11650,7 @@ protected virtual void OnCellClick(DataGridViewCellEventArgs e) dataGridViewCell.OnClickInternal(e); } - DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLCLICK] as DataGridViewCellEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLCLICK] is DataGridViewCellEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11759,8 +11734,7 @@ protected virtual void OnCellContentClick(DataGridViewCellEventArgs e) dataGridViewCell.OnContentClickInternal(e); } - DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLCONTENTCLICK] as DataGridViewCellEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLCONTENTCLICK] is DataGridViewCellEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11794,8 +11768,7 @@ protected virtual void OnCellContentDoubleClick(DataGridViewCellEventArgs e) dataGridViewCell.OnContentDoubleClickInternal(e); } - DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLCONTENTDOUBLECLICK] as DataGridViewCellEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLCONTENTDOUBLECLICK] is DataGridViewCellEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11818,8 +11791,7 @@ protected virtual void OnCellContextMenuStripChanged(DataGridViewCellEventArgs e { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLCONTEXTMENUSTRIPCHANGED] as DataGridViewCellEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLCONTEXTMENUSTRIPCHANGED] is DataGridViewCellEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11843,8 +11815,7 @@ protected virtual void OnCellContextMenuStripNeeded(DataGridViewCellContextMenuS { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellContextMenuStripNeededEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLCONTEXTMENUSTRIPNEEDED] as DataGridViewCellContextMenuStripNeededEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLCONTEXTMENUSTRIPNEEDED] is DataGridViewCellContextMenuStripNeededEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11873,8 +11844,7 @@ protected virtual void OnCellDoubleClick(DataGridViewCellEventArgs e) dataGridViewCell.OnDoubleClickInternal(e); } - DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLDOUBLECLICK] as DataGridViewCellEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLDOUBLECLICK] is DataGridViewCellEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11891,8 +11861,7 @@ protected virtual void OnCellEndEdit(DataGridViewCellEventArgs e) { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLENDEDIT] as DataGridViewCellEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLENDEDIT] is DataGridViewCellEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11930,8 +11899,7 @@ protected virtual void OnCellEnter(DataGridViewCellEventArgs e) { noDimensionChangeCount++; - DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLENTER] as DataGridViewCellEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLENTER] is DataGridViewCellEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11964,8 +11932,7 @@ protected virtual void OnCellErrorTextChanged(DataGridViewCellEventArgs e) } UpdateCellErrorText(e.ColumnIndex, e.RowIndex); - DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLERRORTEXTCHANGED] as DataGridViewCellEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLERRORTEXTCHANGED] is DataGridViewCellEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -11991,8 +11958,7 @@ protected virtual void OnCellErrorTextNeeded(DataGridViewCellErrorTextNeededEven { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellErrorTextNeededEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLERRORTEXTNEEDED] as DataGridViewCellErrorTextNeededEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLERRORTEXTNEEDED] is DataGridViewCellErrorTextNeededEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -12020,8 +11986,7 @@ protected virtual void OnCellFormatting(DataGridViewCellFormattingEventArgs e) { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellFormattingEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLFORMATTING] as DataGridViewCellFormattingEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLFORMATTING] is DataGridViewCellFormattingEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -12059,8 +12024,7 @@ protected virtual void OnCellLeave(DataGridViewCellEventArgs e) { noDimensionChangeCount++; - DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLLEAVE] as DataGridViewCellEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLLEAVE] is DataGridViewCellEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -12096,8 +12060,7 @@ protected virtual void OnCellMouseClick(DataGridViewCellMouseEventArgs e) } dataGridViewState2[DATAGRIDVIEWSTATE2_nextMouseUpIsDouble] = false; - DataGridViewCellMouseEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLMOUSECLICK] as DataGridViewCellMouseEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLMOUSECLICK] is DataGridViewCellMouseEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -12127,8 +12090,7 @@ protected virtual void OnCellMouseDoubleClick(DataGridViewCellMouseEventArgs e) } dataGridViewState2[DATAGRIDVIEWSTATE2_nextMouseUpIsDouble] = true; - DataGridViewCellMouseEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLMOUSEDOUBLECLICK] as DataGridViewCellMouseEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLMOUSEDOUBLECLICK] is DataGridViewCellMouseEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -12201,8 +12163,7 @@ protected virtual void OnCellMouseDown(DataGridViewCellMouseEventArgs e) dataGridViewCell.OnMouseDownInternal(e); } - DataGridViewCellMouseEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLMOUSEDOWN] as DataGridViewCellMouseEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLMOUSEDOWN] is DataGridViewCellMouseEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -12820,8 +12781,7 @@ protected virtual void OnCellMouseEnter(DataGridViewCellEventArgs e) dataGridViewCell.OnMouseEnterInternal(e.RowIndex); } - DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLMOUSEENTER] as DataGridViewCellEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLMOUSEENTER] is DataGridViewCellEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -12853,8 +12813,7 @@ protected virtual void OnCellMouseLeave(DataGridViewCellEventArgs e) dataGridViewCell.OnMouseLeaveInternal(e.RowIndex); } - DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLMOUSELEAVE] as DataGridViewCellEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLMOUSELEAVE] is DataGridViewCellEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -12883,8 +12842,7 @@ protected virtual void OnCellMouseMove(DataGridViewCellMouseEventArgs e) dataGridViewCell.OnMouseMoveInternal(e); } - DataGridViewCellMouseEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLMOUSEMOVE] as DataGridViewCellMouseEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLMOUSEMOVE] is DataGridViewCellMouseEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -12950,8 +12908,7 @@ protected virtual void OnCellMouseUp(DataGridViewCellMouseEventArgs e) dataGridViewCell.OnMouseUpInternal(e); } - DataGridViewCellMouseEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLMOUSEUP] as DataGridViewCellMouseEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLMOUSEUP] is DataGridViewCellMouseEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -12968,8 +12925,7 @@ protected internal virtual void OnCellPainting(DataGridViewCellPaintingEventArgs { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellPaintingEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLPAINTING] as DataGridViewCellPaintingEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLPAINTING] is DataGridViewCellPaintingEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -12996,8 +12952,7 @@ protected virtual void OnCellParsing(DataGridViewCellParsingEventArgs e) { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellParsingEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLPARSING] as DataGridViewCellParsingEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLPARSING] is DataGridViewCellParsingEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13049,8 +13004,7 @@ protected virtual void OnCellStateChanged(DataGridViewCellStateChangedEventArgs } } - DataGridViewCellStateChangedEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLSTATECHANGED] as DataGridViewCellStateChangedEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLSTATECHANGED] is DataGridViewCellStateChangedEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13094,8 +13048,7 @@ protected virtual void OnCellStyleChanged(DataGridViewCellEventArgs e) } OnCellCommonChange(e.ColumnIndex, e.RowIndex); - DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLSTYLECHANGED] as DataGridViewCellEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLSTYLECHANGED] is DataGridViewCellEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13252,8 +13205,7 @@ protected virtual void OnCellStyleContentChanged(DataGridViewCellStyleContentCha PositionEditingControl(true /*setLocation*/, true /*setSize*/, false /*setFocus*/); } - DataGridViewCellStyleContentChangedEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLSTYLECONTENTCHANGED] as DataGridViewCellStyleContentChangedEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLSTYLECONTENTCHANGED] is DataGridViewCellStyleContentChangedEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13276,8 +13228,7 @@ protected virtual void OnCellToolTipTextChanged(DataGridViewCellEventArgs e) { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLTOOLTIPTEXTCHANGED] as DataGridViewCellEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLTOOLTIPTEXTCHANGED] is DataGridViewCellEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13301,8 +13252,7 @@ protected virtual void OnCellToolTipTextNeeded(DataGridViewCellToolTipTextNeeded { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellToolTipTextNeededEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLTOOLTIPTEXTNEEDED] as DataGridViewCellToolTipTextNeededEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLTOOLTIPTEXTNEEDED] is DataGridViewCellToolTipTextNeededEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13340,8 +13290,7 @@ protected virtual void OnCellValidated(DataGridViewCellEventArgs e) { noDimensionChangeCount++; - DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLVALIDATED] as DataGridViewCellEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLVALIDATED] is DataGridViewCellEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); CorrectFocus(true /*onlyIfGridHasFocus*/); @@ -13393,8 +13342,7 @@ protected virtual void OnCellValidating(DataGridViewCellValidatingEventArgs e) noDimensionChangeCount++; dataGridViewOper[DATAGRIDVIEWOPER_inCellValidating] = true; - DataGridViewCellValidatingEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLVALIDATING] as DataGridViewCellValidatingEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLVALIDATING] is DataGridViewCellValidatingEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); CorrectFocus(true /*onlyIfGridHasFocus*/); @@ -13427,8 +13375,7 @@ protected virtual void OnCellValueChanged(DataGridViewCellEventArgs e) } OnCellCommonChange(e.ColumnIndex, e.RowIndex); - DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLVALUECHANGED] as DataGridViewCellEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLVALUECHANGED] is DataGridViewCellEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13458,8 +13405,7 @@ protected virtual void OnCellValueNeeded(DataGridViewCellValueEventArgs e) // but since we're late in Whidbey, throwing an exception would be destabilizing our internal customers. // Debug.Assert(this.dataStoreAccessAllowed); //#endif - DataGridViewCellValueEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLVALUENEEDED] as DataGridViewCellValueEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLVALUENEEDED] is DataGridViewCellValueEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13483,8 +13429,7 @@ protected virtual void OnCellValuePushed(DataGridViewCellValueEventArgs e) { throw new ArgumentOutOfRangeException("e.RowIndex"); } - DataGridViewCellValueEventHandler eh = Events[EVENT_DATAGRIDVIEWCELLVALUEPUSHED] as DataGridViewCellValueEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCELLVALUEPUSHED] is DataGridViewCellValueEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13562,8 +13507,7 @@ protected virtual void OnColumnAdded(DataGridViewColumnEventArgs e) { throw new ArgumentException(string.Format(SR.DataGridView_ColumnDoesNotBelongToDataGridView)); } - DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNADDED] as DataGridViewColumnEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCOLUMNADDED] is DataGridViewColumnEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13628,8 +13572,7 @@ protected virtual void OnColumnContextMenuStripChanged(DataGridViewColumnEventAr { throw new ArgumentException(string.Format(SR.DataGridView_ColumnDoesNotBelongToDataGridView)); } - DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNCONTEXTMENUSTRIPCHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCOLUMNCONTEXTMENUSTRIPCHANGED] is DataGridViewColumnEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13662,8 +13605,7 @@ protected virtual void OnColumnDataPropertyNameChanged(DataGridViewColumnEventAr } } - DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNDATAPROPERTYNAMECHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCOLUMNDATAPROPERTYNAMECHANGED] is DataGridViewColumnEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13677,8 +13619,7 @@ protected virtual void OnColumnDefaultCellStyleChanged(DataGridViewColumnEventAr } OnColumnGlobalAutoSize(e.Column.Index); - DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNDEFAULTCELLSTYLECHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCOLUMNDEFAULTCELLSTYLECHANGED] is DataGridViewColumnEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13755,9 +13696,10 @@ protected virtual void OnColumnDisplayIndexChanged(DataGridViewColumnEventArgs e Debug.Assert(dataGridViewOper[DATAGRIDVIEWOPER_inDisplayIndexAdjustments]); #if DEBUG Debug.Assert(Columns.VerifyColumnDisplayIndexes()); + +#endif #endif - DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNDISPLAYINDEXCHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCOLUMNDISPLAYINDEXCHANGED] is DataGridViewColumnEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13786,8 +13728,7 @@ internal void OnColumnDisplayIndexChanged_PostNotification() protected virtual void OnColumnDividerDoubleClick(DataGridViewColumnDividerDoubleClickEventArgs e) { - DataGridViewColumnDividerDoubleClickEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNDIVIDERDOUBLECLICK] as DataGridViewColumnDividerDoubleClickEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCOLUMNDIVIDERDOUBLECLICK] is DataGridViewColumnDividerDoubleClickEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13823,8 +13764,7 @@ protected virtual void OnColumnDividerWidthChanged(DataGridViewColumnEventArgs e } OnColumnGlobalAutoSize(e.Column.Index); - DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNDIVIDERWIDTHCHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCOLUMNDIVIDERWIDTHCHANGED] is DataGridViewColumnEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13908,8 +13848,7 @@ protected virtual void OnColumnHeaderCellChanged(DataGridViewColumnEventArgs e) OnColumnHeaderGlobalAutoSize(e.Column.Index); - DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNHEADERCELLCHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCOLUMNHEADERCELLCHANGED] is DataGridViewColumnEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13990,8 +13929,7 @@ protected virtual void OnColumnHeaderMouseClick(DataGridViewCellMouseEventArgs e } } - DataGridViewCellMouseEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNHEADERMOUSECLICK] as DataGridViewCellMouseEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCOLUMNHEADERMOUSECLICK] is DataGridViewCellMouseEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -13999,8 +13937,7 @@ protected virtual void OnColumnHeaderMouseClick(DataGridViewCellMouseEventArgs e protected virtual void OnColumnHeaderMouseDoubleClick(DataGridViewCellMouseEventArgs e) { - DataGridViewCellMouseEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNHEADERMOUSEDOUBLECLICK] as DataGridViewCellMouseEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCOLUMNHEADERMOUSEDOUBLECLICK] is DataGridViewCellMouseEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14203,8 +14140,7 @@ protected virtual void OnColumnHeadersBorderStyleChanged(EventArgs e) PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); Invalidate(); - EventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNHEADERSBORDERSTYLECHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCOLUMNHEADERSBORDERSTYLECHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14216,8 +14152,7 @@ protected virtual void OnColumnHeadersDefaultCellStyleChanged(EventArgs e) { Invalidate(Rectangle.Union(layout.TopLeftHeader, layout.ColumnHeaders)); - DataGridViewCellStyleChangedEventArgs dgvcsce = e as DataGridViewCellStyleChangedEventArgs; - if (dgvcsce == null || dgvcsce.ChangeAffectsPreferredSize) + if (!(e is DataGridViewCellStyleChangedEventArgs dgvcsce) || dgvcsce.ChangeAffectsPreferredSize) { OnColumnHeadersGlobalAutoSize(); if (editingControl != null) @@ -14227,8 +14162,7 @@ protected virtual void OnColumnHeadersDefaultCellStyleChanged(EventArgs e) } } - EventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNHEADERSDEFAULTCELLSTYLECHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCOLUMNHEADERSDEFAULTCELLSTYLECHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14291,8 +14225,7 @@ protected virtual void OnColumnHeadersHeightChanged(EventArgs e) OnColumnHeadersGlobalAutoSize(); - EventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNHEADERSHEIGHTCHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCOLUMNHEADERSHEIGHTCHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14314,8 +14247,7 @@ protected virtual void OnColumnHeadersHeightSizeModeChanged(DataGridViewAutoSize ColumnHeadersHeight = cachedColumnHeadersHeight; } - DataGridViewAutoSizeModeEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNHEADERSHEIGHTSIZEMODECHANGED] as DataGridViewAutoSizeModeEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCOLUMNHEADERSHEIGHTSIZEMODECHANGED] is DataGridViewAutoSizeModeEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14363,8 +14295,7 @@ protected virtual void OnColumnMinimumWidthChanged(DataGridViewColumnEventArgs e PerformLayoutPrivate(false /*useRowShortcut*/, true /*computeVisibleRows*/, false /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); } - DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNMINIMUMWIDTHCHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCOLUMNMINIMUMWIDTHCHANGED] is DataGridViewColumnEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14416,8 +14347,7 @@ protected virtual void OnColumnNameChanged(DataGridViewColumnEventArgs e) } } - DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNNAMECHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCOLUMNNAMECHANGED] is DataGridViewColumnEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14432,8 +14362,7 @@ internal void OnColumnRemoved(DataGridViewColumn dataGridViewColumn) protected virtual void OnColumnRemoved(DataGridViewColumnEventArgs e) { - DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNREMOVED] as DataGridViewColumnEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCOLUMNREMOVED] is DataGridViewColumnEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14616,8 +14545,7 @@ protected virtual void OnColumnSortModeChanged(DataGridViewColumnEventArgs e) } } - DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNSORTMODECHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCOLUMNSORTMODECHANGED] is DataGridViewColumnEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14735,8 +14663,7 @@ protected virtual void OnColumnStateChanged(DataGridViewColumnStateChangedEventA break; } - DataGridViewColumnStateChangedEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNSTATECHANGED] as DataGridViewColumnStateChangedEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCOLUMNSTATECHANGED] is DataGridViewColumnStateChangedEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14771,8 +14698,7 @@ protected virtual void OnColumnToolTipTextChanged(DataGridViewColumnEventArgs e) { throw new ArgumentException(string.Format(SR.DataGridView_ColumnDoesNotBelongToDataGridView)); } - DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNTOOLTIPTEXTCHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCOLUMNTOOLTIPTEXTCHANGED] is DataGridViewColumnEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14832,8 +14758,7 @@ protected virtual void OnColumnWidthChanged(DataGridViewColumnEventArgs e) } } - DataGridViewColumnEventHandler eh = Events[EVENT_DATAGRIDVIEWCOLUMNWIDTHCHANGED] as DataGridViewColumnEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCOLUMNWIDTHCHANGED] is DataGridViewColumnEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14868,8 +14793,7 @@ internal void OnCommonCellContentClick(int columnIndex, int rowIndex, bool doubl protected virtual void OnCurrentCellChanged(EventArgs e) { VerifyImeRestrictedModeChanged(); - EventHandler eh = Events[EVENT_DATAGRIDVIEWCURRENTCELLCHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCURRENTCELLCHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14893,8 +14817,7 @@ protected virtual void OnCurrentCellDirtyStateChanged(EventArgs e) AddNewRow(true /*createdByEditing*/); } - EventHandler eh = Events[EVENT_DATAGRIDVIEWCURRENTCELLDIRTYSTATECHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWCURRENTCELLDIRTYSTATECHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14916,8 +14839,7 @@ internal void OnDataBindingComplete(ListChangedType listChangedType) protected virtual void OnDataBindingComplete(DataGridViewBindingCompleteEventArgs e) { - DataGridViewBindingCompleteEventHandler eh = Events[EVENT_DATAGRIDVIEWDATABINDINGCOMPLETE] as DataGridViewBindingCompleteEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWDATABINDINGCOMPLETE] is DataGridViewBindingCompleteEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -14928,10 +14850,9 @@ protected virtual void OnDataBindingComplete(DataGridViewBindingCompleteEventArg ] protected virtual void OnDataError(bool displayErrorDialogIfNoHandler, DataGridViewDataErrorEventArgs e) { - DataGridViewDataErrorEventHandler eh = Events[EVENT_DATAGRIDVIEWDATAERROR] as DataGridViewDataErrorEventHandler; if (!dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { - if (eh == null) + if (!(Events[EVENT_DATAGRIDVIEWDATAERROR] is DataGridViewDataErrorEventHandler eh)) { if (displayErrorDialogIfNoHandler) { @@ -14970,8 +14891,7 @@ internal void OnDataErrorInternal(DataGridViewDataErrorEventArgs e) internal void OnDataGridViewElementStateChanged(DataGridViewElement element, int index, DataGridViewElementStates elementState) { - DataGridViewColumn dataGridViewColumn = element as DataGridViewColumn; - if (dataGridViewColumn != null) + if (element is DataGridViewColumn dataGridViewColumn) { DataGridViewColumnStateChangedEventArgs dgvcsce = new DataGridViewColumnStateChangedEventArgs(dataGridViewColumn, elementState); @@ -14979,12 +14899,9 @@ internal void OnDataGridViewElementStateChanged(DataGridViewElement element, int } else { - DataGridViewRow dataGridViewRow = element as DataGridViewRow; - if (dataGridViewRow != null) + if (element is DataGridViewRow dataGridViewRow) { - DataGridViewRowStateChangedEventHandler eh = Events[EVENT_DATAGRIDVIEWROWSTATECHANGED] as DataGridViewRowStateChangedEventHandler; - - if (eh != null && dataGridViewRow.DataGridView != null && dataGridViewRow.Index == -1) + if (Events[EVENT_DATAGRIDVIEWROWSTATECHANGED] is DataGridViewRowStateChangedEventHandler eh && dataGridViewRow.DataGridView != null && dataGridViewRow.Index == -1) { dataGridViewRow = Rows[index]; } @@ -14995,8 +14912,7 @@ internal void OnDataGridViewElementStateChanged(DataGridViewElement element, int } else { - DataGridViewCell dataGridViewCell = element as DataGridViewCell; - if (dataGridViewCell != null) + if (element is DataGridViewCell dataGridViewCell) { DataGridViewCellStateChangedEventArgs dgvcsce = new DataGridViewCellStateChangedEventArgs(dataGridViewCell, elementState); @@ -15020,8 +14936,7 @@ internal void OnDataGridViewElementStateChanged(DataGridViewElement element, int internal void OnDataGridViewElementStateChanging(DataGridViewElement element, int index, DataGridViewElementStates elementState) { - DataGridViewColumn dataGridViewColumn = element as DataGridViewColumn; - if (dataGridViewColumn != null) + if (element is DataGridViewColumn dataGridViewColumn) { // column.Frozen | .Visible | .ReadOnly changing switch (elementState) @@ -15094,8 +15009,7 @@ internal void OnDataGridViewElementStateChanging(DataGridViewElement element, in } else { - DataGridViewRow dataGridViewRow = element as DataGridViewRow; - if (dataGridViewRow != null) + if (element is DataGridViewRow dataGridViewRow) { // row.Frozen | .Visible | .ReadOnly changing int rowIndex = ((dataGridViewRow.Index > -1) ? dataGridViewRow.Index : index); @@ -15153,8 +15067,7 @@ internal void OnDataGridViewElementStateChanging(DataGridViewElement element, in } else { - DataGridViewCell dataGridViewCell = element as DataGridViewCell; - if (dataGridViewCell != null) + if (element is DataGridViewCell dataGridViewCell) { // cell.ReadOnly changing switch (elementState) @@ -15203,8 +15116,7 @@ protected virtual void OnDataMemberChanged(EventArgs e) { RefreshColumnsAndRows(); - EventHandler eh = Events[EVENT_DATAGRIDVIEWDATAMEMBERCHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWDATAMEMBERCHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -15220,8 +15132,7 @@ protected virtual void OnDataSourceChanged(EventArgs e) RefreshColumnsAndRows(); InvalidateRowHeights(); - EventHandler eh = Events[EVENT_DATAGRIDVIEWDATASOURCECHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWDATASOURCECHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -15234,8 +15145,7 @@ protected virtual void OnDataSourceChanged(EventArgs e) protected virtual void OnDefaultCellStyleChanged(EventArgs e) { - DataGridViewCellStyleChangedEventArgs dgvcsce = e as DataGridViewCellStyleChangedEventArgs; - if (dgvcsce != null && !dgvcsce.ChangeAffectsPreferredSize) + if (e is DataGridViewCellStyleChangedEventArgs dgvcsce && !dgvcsce.ChangeAffectsPreferredSize) { Invalidate(); } @@ -15248,8 +15158,7 @@ protected virtual void OnDefaultCellStyleChanged(EventArgs e) } } - EventHandler eh = Events[EVENT_DATAGRIDVIEWDEFAULTCELLSTYLECHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWDEFAULTCELLSTYLECHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -15257,8 +15166,7 @@ protected virtual void OnDefaultCellStyleChanged(EventArgs e) protected virtual void OnDefaultValuesNeeded(DataGridViewRowEventArgs e) { - DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWDEFAULTVALUESNEEDED] as DataGridViewRowEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWDEFAULTVALUESNEEDED] is DataGridViewRowEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -15270,8 +15178,7 @@ protected override void OnDoubleClick(EventArgs e) if (!dataGridViewState2[DATAGRIDVIEWSTATE2_messageFromEditingCtrls] && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { - MouseEventArgs me = e as MouseEventArgs; - if (me != null) + if (e is MouseEventArgs me) { HitTestInfo hti = HitTest(me.X, me.Y); if (hti.Type != DataGridViewHitTestType.None && @@ -15287,8 +15194,7 @@ protected override void OnDoubleClick(EventArgs e) protected virtual void OnEditingControlShowing(DataGridViewEditingControlShowingEventArgs e) { - DataGridViewEditingControlShowingEventHandler eh = Events[EVENT_DATAGRIDVIEWEDITINGCONTROLSHOWING] as DataGridViewEditingControlShowingEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWEDITINGCONTROLSHOWING] is DataGridViewEditingControlShowingEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -15305,8 +15211,7 @@ protected virtual void OnEditModeChanged(EventArgs e) BeginEditInternal(true /*selectAll*/); } - EventHandler eh = Events[EVENT_DATAGRIDVIEWEDITMODECHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWEDITMODECHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -15537,8 +15442,7 @@ protected virtual void OnGridColorChanged(EventArgs e) { InvalidateInside(); - EventHandler eh = Events[EVENT_DATAGRIDVIEWGRIDCOLORCHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWGRIDCOLORCHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -16890,8 +16794,7 @@ internal void OnMouseWheelInternal(MouseEventArgs e) protected virtual void OnMultiSelectChanged(EventArgs e) { - EventHandler eh = Events[EVENT_DATAGRIDVIEWMULTISELECTCHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWMULTISELECTCHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -16903,8 +16806,7 @@ protected virtual void OnNewRowNeeded(DataGridViewRowEventArgs e) { throw new ArgumentException(string.Format(SR.DataGridView_RowDoesNotBelongToDataGridView), "e.Row"); } - DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWNEWROWNEEDED] as DataGridViewRowEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWNEWROWNEEDED] is DataGridViewRowEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -17105,8 +17007,7 @@ internal override void OnParentBecameInvisible() protected virtual void OnReadOnlyChanged(EventArgs e) { - EventHandler eh = Events[EVENT_DATAGRIDVIEWREADONLYCHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWREADONLYCHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -17814,8 +17715,7 @@ protected virtual void OnRowContextMenuStripChanged(DataGridViewRowEventArgs e) { throw new ArgumentException(string.Format(SR.DataGridView_RowDoesNotBelongToDataGridView), "e.Row"); } - DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWROWCONTEXTMENUSTRIPCHANGED] as DataGridViewRowEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWCONTEXTMENUSTRIPCHANGED] is DataGridViewRowEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -17830,8 +17730,7 @@ internal ContextMenuStrip OnRowContextMenuStripNeeded(int rowIndex, ContextMenuS protected virtual void OnRowContextMenuStripNeeded(DataGridViewRowContextMenuStripNeededEventArgs e) { - DataGridViewRowContextMenuStripNeededEventHandler eh = Events[EVENT_DATAGRIDVIEWROWCONTEXTMENUSTRIPNEEDED] as DataGridViewRowContextMenuStripNeededEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWCONTEXTMENUSTRIPNEEDED] is DataGridViewRowContextMenuStripNeededEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -17846,8 +17745,7 @@ protected virtual void OnRowDefaultCellStyleChanged(DataGridViewRowEventArgs e) OnRowGlobalAutoSize(e.Row.Index); - DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWROWDEFAULTCELLSTYLECHANGED] as DataGridViewRowEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWDEFAULTCELLSTYLECHANGED] is DataGridViewRowEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -17855,8 +17753,7 @@ protected virtual void OnRowDefaultCellStyleChanged(DataGridViewRowEventArgs e) protected virtual void OnRowDirtyStateNeeded(QuestionEventArgs e) { - QuestionEventHandler eh = Events[EVENT_DATAGRIDVIEWROWDIRTYSTATENEEDED] as QuestionEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWDIRTYSTATENEEDED] is QuestionEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -17864,8 +17761,7 @@ protected virtual void OnRowDirtyStateNeeded(QuestionEventArgs e) protected virtual void OnRowDividerDoubleClick(DataGridViewRowDividerDoubleClickEventArgs e) { - DataGridViewRowDividerDoubleClickEventHandler eh = Events[EVENT_DATAGRIDVIEWROWDIVIDERDOUBLECLICK] as DataGridViewRowDividerDoubleClickEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWDIVIDERDOUBLECLICK] is DataGridViewRowDividerDoubleClickEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -17899,8 +17795,7 @@ protected virtual void OnRowDividerHeightChanged(DataGridViewRowEventArgs e) OnRowGlobalAutoSize(e.Row.Index); - DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWROWDIVIDERHEIGHTCHANGED] as DataGridViewRowEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWDIVIDERHEIGHTCHANGED] is DataGridViewRowEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -17994,8 +17889,7 @@ protected virtual void OnRowEnter(DataGridViewCellEventArgs e) { noDimensionChangeCount++; - DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWROWENTER] as DataGridViewCellEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWENTER] is DataGridViewCellEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); CorrectFocus(true /*onlyIfGridHasFocus*/); @@ -18022,8 +17916,7 @@ protected virtual void OnRowErrorTextChanged(DataGridViewRowEventArgs e) } UpdateRowErrorText(e.Row.Index); - DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWROWERRORTEXTCHANGED] as DataGridViewRowEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWERRORTEXTCHANGED] is DataGridViewRowEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18039,8 +17932,7 @@ internal string OnRowErrorTextNeeded(int rowIndex, string errorText) protected virtual void OnRowErrorTextNeeded(DataGridViewRowErrorTextNeededEventArgs e) { - DataGridViewRowErrorTextNeededEventHandler eh = Events[EVENT_DATAGRIDVIEWROWERRORTEXTNEEDED] as DataGridViewRowErrorTextNeededEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWERRORTEXTNEEDED] is DataGridViewRowErrorTextNeededEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18115,8 +18007,7 @@ protected virtual void OnRowHeaderCellChanged(DataGridViewRowEventArgs e) OnRowHeaderGlobalAutoSize(e.Row.Index); - DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWROWHEADERCELLCHANGED] as DataGridViewRowEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWHEADERCELLCHANGED] is DataGridViewRowEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18180,8 +18071,7 @@ private void OnRowHeaderGlobalAutoSize(int rowIndex) protected virtual void OnRowHeaderMouseClick(DataGridViewCellMouseEventArgs e) { - DataGridViewCellMouseEventHandler eh = Events[EVENT_DATAGRIDVIEWROWHEADERMOUSECLICK] as DataGridViewCellMouseEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWHEADERMOUSECLICK] is DataGridViewCellMouseEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18189,8 +18079,7 @@ protected virtual void OnRowHeaderMouseClick(DataGridViewCellMouseEventArgs e) protected virtual void OnRowHeaderMouseDoubleClick(DataGridViewCellMouseEventArgs e) { - DataGridViewCellMouseEventHandler eh = Events[EVENT_DATAGRIDVIEWROWHEADERMOUSEDOUBLECLICK] as DataGridViewCellMouseEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWHEADERMOUSEDOUBLECLICK] is DataGridViewCellMouseEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18425,8 +18314,7 @@ protected virtual void OnRowHeadersBorderStyleChanged(EventArgs e) PerformLayoutPrivate(false /*useRowShortcut*/, false /*computeVisibleRows*/, true /*invalidInAdjustFillingColumns*/, false /*repositionEditingControl*/); Invalidate(); - EventHandler eh = Events[EVENT_DATAGRIDVIEWROWHEADERSBORDERSTYLECHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWHEADERSBORDERSTYLECHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18438,8 +18326,7 @@ protected virtual void OnRowHeadersDefaultCellStyleChanged(EventArgs e) { Invalidate(Rectangle.Union(layout.TopLeftHeader, layout.RowHeaders)); - DataGridViewCellStyleChangedEventArgs dgvcsce = e as DataGridViewCellStyleChangedEventArgs; - if (dgvcsce == null || dgvcsce.ChangeAffectsPreferredSize) + if (!(e is DataGridViewCellStyleChangedEventArgs dgvcsce) || dgvcsce.ChangeAffectsPreferredSize) { OnRowHeadersGlobalAutoSize(false /*expandingRows*/); if (editingControl != null) @@ -18449,8 +18336,7 @@ protected virtual void OnRowHeadersDefaultCellStyleChanged(EventArgs e) } } - EventHandler eh = Events[EVENT_DATAGRIDVIEWROWHEADERSDEFAULTCELLSTYLECHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWHEADERSDEFAULTCELLSTYLECHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18508,8 +18394,7 @@ protected virtual void OnRowHeadersWidthChanged(EventArgs e) OnRowHeadersGlobalAutoSize(false /*expandingRows*/); } - EventHandler eh = Events[EVENT_DATAGRIDVIEWROWHEADERSWIDTHCHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWHEADERSWIDTHCHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18534,8 +18419,7 @@ protected virtual void OnRowHeadersWidthSizeModeChanged(DataGridViewAutoSizeMode RowHeadersWidth = cachedRowHeadersWidth; } - EventHandler eh = Events[EVENT_DATAGRIDVIEWROWHEADERSWIDTHSIZEMODECHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWHEADERSWIDTHSIZEMODECHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18549,8 +18433,7 @@ protected virtual void OnRowHeightChanged(DataGridViewRowEventArgs e) } UpdateRowHeightInfoPrivate(e.Row.Index, false, false /*invalidInAdjustFillingColumns*/); - DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWROWHEIGHTCHANGED] as DataGridViewRowEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWHEIGHTCHANGED] is DataGridViewRowEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18568,8 +18451,7 @@ internal DataGridViewRowHeightInfoNeededEventArgs OnRowHeightInfoNeeded(int rowI protected virtual void OnRowHeightInfoNeeded(DataGridViewRowHeightInfoNeededEventArgs e) { - DataGridViewRowHeightInfoNeededEventHandler eh = Events[EVENT_DATAGRIDVIEWROWHEIGHTINFONEEDED] as DataGridViewRowHeightInfoNeededEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWHEIGHTINFONEEDED] is DataGridViewRowHeightInfoNeededEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18594,8 +18476,7 @@ private bool OnRowHeightInfoPushed(int rowIndex, int height, int minimumHeight) protected virtual void OnRowHeightInfoPushed(DataGridViewRowHeightInfoPushedEventArgs e) { - DataGridViewRowHeightInfoPushedEventHandler eh = Events[EVENT_DATAGRIDVIEWROWHEIGHTINFOPUSHED] as DataGridViewRowHeightInfoPushedEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWHEIGHTINFOPUSHED] is DataGridViewRowHeightInfoPushedEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18629,8 +18510,7 @@ protected virtual void OnRowLeave(DataGridViewCellEventArgs e) { noDimensionChangeCount++; - DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWROWLEAVE] as DataGridViewCellEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWLEAVE] is DataGridViewCellEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); CorrectFocus(true /*onlyIfGridHasFocus*/); @@ -18649,8 +18529,7 @@ protected virtual void OnRowMinimumHeightChanged(DataGridViewRowEventArgs e) { throw new ArgumentException(string.Format(SR.DataGridView_RowDoesNotBelongToDataGridView), "e.Row"); } - DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWROWMINIMUMHEIGHTCHANGED] as DataGridViewRowEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWMINIMUMHEIGHTCHANGED] is DataGridViewRowEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18658,8 +18537,7 @@ protected virtual void OnRowMinimumHeightChanged(DataGridViewRowEventArgs e) protected internal virtual void OnRowPostPaint(DataGridViewRowPostPaintEventArgs e) { - DataGridViewRowPostPaintEventHandler eh = Events[EVENT_DATAGRIDVIEWROWPOSTPAINT] as DataGridViewRowPostPaintEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWPOSTPAINT] is DataGridViewRowPostPaintEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18667,8 +18545,7 @@ protected internal virtual void OnRowPostPaint(DataGridViewRowPostPaintEventArgs protected internal virtual void OnRowPrePaint(DataGridViewRowPrePaintEventArgs e) { - DataGridViewRowPrePaintEventHandler eh = Events[EVENT_DATAGRIDVIEWROWPREPAINT] as DataGridViewRowPrePaintEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWPREPAINT] is DataGridViewRowPrePaintEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18681,8 +18558,7 @@ internal void OnRowsAddedInternal(int rowIndex, int rowCount) protected virtual void OnRowsAdded(DataGridViewRowsAddedEventArgs e) { - DataGridViewRowsAddedEventHandler eh = Events[EVENT_DATAGRIDVIEWROWSADDED] as DataGridViewRowsAddedEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWSADDED] is DataGridViewRowsAddedEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18690,8 +18566,7 @@ protected virtual void OnRowsAdded(DataGridViewRowsAddedEventArgs e) protected virtual void OnRowsDefaultCellStyleChanged(EventArgs e) { - DataGridViewCellStyleChangedEventArgs dgvcsce = e as DataGridViewCellStyleChangedEventArgs; - if (dgvcsce != null && !dgvcsce.ChangeAffectsPreferredSize) + if (e is DataGridViewCellStyleChangedEventArgs dgvcsce && !dgvcsce.ChangeAffectsPreferredSize) { InvalidateData(); } @@ -18704,8 +18579,7 @@ protected virtual void OnRowsDefaultCellStyleChanged(EventArgs e) } } - EventHandler eh = Events[EVENT_DATAGRIDVIEWROWSDEFAULTCELLSTYLECHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWSDEFAULTCELLSTYLECHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18863,8 +18737,7 @@ internal void OnRowsRemovedInternal(int rowIndex, int rowCount) protected virtual void OnRowsRemoved(DataGridViewRowsRemovedEventArgs e) { - DataGridViewRowsRemovedEventHandler eh = Events[EVENT_DATAGRIDVIEWROWSREMOVED] as DataGridViewRowsRemovedEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWSREMOVED] is DataGridViewRowsRemovedEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -18979,8 +18852,7 @@ protected virtual void OnRowStateChanged(int rowIndex, DataGridViewRowStateChang } } - DataGridViewRowStateChangedEventHandler eh = Events[EVENT_DATAGRIDVIEWROWSTATECHANGED] as DataGridViewRowStateChangedEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWSTATECHANGED] is DataGridViewRowStateChangedEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -19021,8 +18893,7 @@ protected virtual void OnRowUnshared(DataGridViewRowEventArgs e) { throw new ArgumentException(string.Format(SR.DataGridView_RowDoesNotBelongToDataGridView), "e.Row"); } - DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWROWUNSHARED] as DataGridViewRowEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWUNSHARED] is DataGridViewRowEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -19055,8 +18926,7 @@ protected virtual void OnRowValidating(DataGridViewCellCancelEventArgs e) { noDimensionChangeCount++; - DataGridViewCellCancelEventHandler eh = Events[EVENT_DATAGRIDVIEWROWVALIDATING] as DataGridViewCellCancelEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWVALIDATING] is DataGridViewCellCancelEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); CorrectFocus(true /*onlyIfGridHasFocus*/); @@ -19101,8 +18971,7 @@ protected virtual void OnRowValidated(DataGridViewCellEventArgs e) { noDimensionChangeCount++; - DataGridViewCellEventHandler eh = Events[EVENT_DATAGRIDVIEWROWVALIDATED] as DataGridViewCellEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWROWVALIDATED] is DataGridViewCellEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); CorrectFocus(true /*onlyIfGridHasFocus*/); @@ -19212,8 +19081,7 @@ private void OnScroll(ScrollEventType scrollEventType, int oldValue, int newValu protected virtual void OnScroll(ScrollEventArgs e) { - ScrollEventHandler eh = Events[EVENT_DATAGRIDVIEWSCROLL] as ScrollEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWSCROLL] is ScrollEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -19223,8 +19091,7 @@ protected virtual void OnSelectionChanged(EventArgs e) { dataGridViewState2[DATAGRIDVIEWSTATE2_raiseSelectionChanged] = false; - EventHandler eh = Events[EVENT_DATAGRIDVIEWSELECTIONCHANGED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWSELECTIONCHANGED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -19240,8 +19107,7 @@ internal bool OnSortCompare(DataGridViewColumn dataGridViewSortedColumn, object protected virtual void OnSortCompare(DataGridViewSortCompareEventArgs e) { - DataGridViewSortCompareEventHandler eh = Events[EVENT_DATAGRIDVIEWSORTCOMPARE] as DataGridViewSortCompareEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWSORTCOMPARE] is DataGridViewSortCompareEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -19249,8 +19115,7 @@ protected virtual void OnSortCompare(DataGridViewSortCompareEventArgs e) protected virtual void OnSorted(EventArgs e) { - EventHandler eh = Events[EVENT_DATAGRIDVIEWSORTED] as EventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWSORTED] is EventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -19318,8 +19183,7 @@ protected virtual void OnUserAddedRow(DataGridViewRowEventArgs e) { throw new ArgumentException(string.Format(SR.DataGridView_RowDoesNotBelongToDataGridView), "e.Row"); } - DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWUSERADDEDROW] as DataGridViewRowEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWUSERADDEDROW] is DataGridViewRowEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -19327,8 +19191,7 @@ protected virtual void OnUserAddedRow(DataGridViewRowEventArgs e) protected virtual void OnUserDeletedRow(DataGridViewRowEventArgs e) { - DataGridViewRowEventHandler eh = Events[EVENT_DATAGRIDVIEWUSERDELETEDROW] as DataGridViewRowEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWUSERDELETEDROW] is DataGridViewRowEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -19336,8 +19199,7 @@ protected virtual void OnUserDeletedRow(DataGridViewRowEventArgs e) protected virtual void OnUserDeletingRow(DataGridViewRowCancelEventArgs e) { - DataGridViewRowCancelEventHandler eh = Events[EVENT_DATAGRIDVIEWUSERDELETINGROW] as DataGridViewRowCancelEventHandler; - if (eh != null && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) + if (Events[EVENT_DATAGRIDVIEWUSERDELETINGROW] is DataGridViewRowCancelEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { eh(this, e); } @@ -27861,8 +27723,7 @@ public virtual void Sort(IComparer comparer) private void SortDataBoundDataGridView_PerformCheck(DataGridViewColumn dataGridViewColumn) { - IBindingList ibl = dataConnection.List as IBindingList; - if (ibl == null) + if (!(dataConnection.List is IBindingList ibl)) { throw new InvalidOperationException(string.Format(SR.DataGridView_CannotSortDataBoundDataGridViewBoundToNonIBindingList)); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowCollection.cs index 4f35d3b8c01..c6738e86128 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowCollection.cs @@ -882,8 +882,7 @@ public virtual void Clear() } if (DataGridView.DataSource != null) { - IBindingList list = DataGridView.DataConnection.List as IBindingList; - if (list != null && list.AllowRemove && list.SupportsChangeNotification) + if (DataGridView.DataConnection.List is IBindingList list && list.AllowRemove && list.SupportsChangeNotification) { ((IList)list).Clear(); } @@ -2229,8 +2228,7 @@ public virtual void RemoveAt(int index) if (DataGridView.DataSource != null) { - IBindingList list = DataGridView.DataConnection.List as IBindingList; - if (list != null && list.AllowRemove && list.SupportsChangeNotification) + if (DataGridView.DataConnection.List is IBindingList list && list.AllowRemove && list.SupportsChangeNotification) { ((IList)list).RemoveAt(index); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxCell.cs index ba18ddaf512..3aef62a6a93 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxCell.cs @@ -157,8 +157,7 @@ public override void DetachEditingControl() throw new InvalidOperationException(); } - TextBox textBox = dgv.EditingControl as TextBox; - if (textBox != null) + if (dgv.EditingControl is TextBox textBox) { textBox.ClearUndo(); } @@ -173,9 +172,8 @@ private Rectangle GetAdjustedEditingControlBounds(Rectangle editingControlBounds Debug.Assert(cellStyle.WrapMode != DataGridViewTriState.NotSet); Debug.Assert(DataGridView != null); - TextBox txtEditingControl = DataGridView.EditingControl as TextBox; int originalWidth = editingControlBounds.Width; - if (txtEditingControl != null) + if (DataGridView.EditingControl is TextBox txtEditingControl) { switch (cellStyle.Alignment) { @@ -505,14 +503,12 @@ public override void InitializeEditingControl(int rowIndex, object initialFormat DataGridView.EditingControl != null); Debug.Assert(!ReadOnly); base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle); - TextBox textBox = DataGridView.EditingControl as TextBox; - if (textBox != null) + if (DataGridView.EditingControl is TextBox textBox) { textBox.BorderStyle = BorderStyle.None; textBox.AcceptsReturn = textBox.Multiline = dataGridViewCellStyle.WrapMode == DataGridViewTriState.True; textBox.MaxLength = MaxInputLength; - string initialFormattedValueStr = initialFormattedValue as string; - if (initialFormattedValueStr == null) + if (!(initialFormattedValue is string initialFormattedValueStr)) { textBox.Text = string.Empty; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxColumn.cs index fd09b322d0d..c214597587b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxColumn.cs @@ -68,8 +68,7 @@ public int MaxInputLength for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewTextBoxCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewTextBoxCell; - if (dataGridViewCell != null) + if (dataGridViewRow.Cells[Index] is DataGridViewTextBoxCell dataGridViewCell) { dataGridViewCell.MaxInputLength = value; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxEditingControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxEditingControl.cs index 068b1e56291..06cd0551f44 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxEditingControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxEditingControl.cs @@ -350,8 +350,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga switch (direction) { case UnsafeNativeMethods.NavigateDirection.Parent: - var owner = Owner as IDataGridViewEditingControl; - if (owner != null && owner.EditingControlDataGridView.EditingControl == owner) + if (Owner is IDataGridViewEditingControl owner && owner.EditingControlDataGridView.EditingControl == owner) { return _parentAccessibleObject; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs index 20f8a4e6232..5f3b74f59af 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs @@ -320,8 +320,7 @@ public virtual Stream GetAudioStream() public virtual StringCollection GetFileDropList() { StringCollection retVal = new StringCollection(); - string[] strings = GetData(DataFormats.FileDrop, true) as string[]; - if (strings != null) + if (GetData(DataFormats.FileDrop, true) is string[] strings) { retVal.AddRange(strings); } @@ -346,8 +345,7 @@ public virtual string GetText(TextDataFormat format) throw new InvalidEnumArgumentException(nameof(format), (int)format, typeof(TextDataFormat)); } - string text = GetData(ConvertToDataFormats(format), false) as string; - if (text != null) + if (GetData(ConvertToDataFormats(format), false) is string text) { return text; } @@ -1161,8 +1159,7 @@ public FormatEnumerator(IDataObject parent, FORMATETC[] formats) current = 0; if (formats != null) { - DataObject dataObject = parent as DataObject; - if (dataObject != null && dataObject.RestrictedFormats) + if (parent is DataObject dataObject && dataObject.RestrictedFormats) { if (!Clipboard.IsFormatValid(formats)) { @@ -1196,9 +1193,7 @@ public FormatEnumerator(IDataObject parent, string[] formats) if (formats != null) { - - DataObject dataObject = parent as DataObject; - if (dataObject != null && dataObject.RestrictedFormats) + if (parent is DataObject dataObject && dataObject.RestrictedFormats) { if (!Clipboard.IsFormatValid(formats)) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs index b9024b855e5..022b1b62228 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs @@ -1267,8 +1267,7 @@ protected virtual void OnDropDown(EventArgs eventargs) protected virtual void OnFormatChanged(EventArgs e) { - EventHandler eh = Events[EVENT_FORMATCHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_FORMATCHANGED] is EventHandler eh) { eh(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DockingAttribute.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DockingAttribute.cs index 151fde49b4f..50401258cde 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DockingAttribute.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DockingAttribute.cs @@ -65,9 +65,8 @@ public override bool Equals(object obj) return true; } - DockingAttribute other = obj as DockingAttribute; - return (other != null) && other.DockingBehavior == dockingBehavior; + return (obj is DockingAttribute other) && other.DockingBehavior == dockingBehavior; } public override int GetHashCode() diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs index 457688c4a3d..3c51416eecb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs @@ -118,8 +118,7 @@ public override ISite Site return; } - IDesignerHost host = value.GetService(typeof(IDesignerHost)) as IDesignerHost; - if (host != null) + if (value.GetService(typeof(IDesignerHost)) is IDesignerHost host) { IComponent baseComp = host.RootComponent; @@ -439,9 +438,8 @@ private void WireEvents(BindingManagerBase listManager) listManager.CurrentChanged += currentChanged; listManager.BindingComplete += new BindingCompleteEventHandler(ErrorManager_BindingComplete); - CurrencyManager currManager = listManager as CurrencyManager; - if (currManager != null) + if (listManager is CurrencyManager currManager) { currManager.ItemChanged += new ItemChangedEventHandler(ErrorManager_ItemChanged); currManager.Bindings.CollectionChanged += new CollectionChangeEventHandler(ErrorManager_BindingsChanged); @@ -456,9 +454,8 @@ private void UnwireEvents(BindingManagerBase listManager) listManager.CurrentChanged -= currentChanged; listManager.BindingComplete -= new BindingCompleteEventHandler(ErrorManager_BindingComplete); - CurrencyManager currManager = listManager as CurrencyManager; - if (currManager != null) + if (listManager is CurrencyManager currManager) { currManager.ItemChanged -= new ItemChangedEventHandler(ErrorManager_ItemChanged); currManager.Bindings.CollectionChanged -= new CollectionChangeEventHandler(ErrorManager_BindingsChanged); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FlowLayoutPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FlowLayoutPanel.cs index 25bebd36d66..c76b92be769 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FlowLayoutPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FlowLayoutPanel.cs @@ -63,8 +63,7 @@ public bool WrapContents #region Provided properties bool IExtenderProvider.CanExtend(object obj) { - Control control = obj as Control; - return control != null && control.Parent == this; + return obj is Control control && control.Parent == this; } [DefaultValue(false)] 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 c770793db3d..f0ec71ca3e2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs @@ -4241,8 +4241,7 @@ private void InvalidateMergedMenu() // needs to be rebuilt). Then, we signal the parent to updated its menus. if (Properties.ContainsObject(PropMergedMenu)) { - MainMenu menu = Properties.GetObject(PropMergedMenu) as MainMenu; - if (menu != null && menu.ownerForm == this) + if (Properties.GetObject(PropMergedMenu) is MainMenu menu && menu.ownerForm == this) { menu.Dispose(); } @@ -4305,8 +4304,7 @@ internal void MenuChanged(int change, Menu menu) Control ctl = children[i]; if (ctl is Form && ctl.Properties.ContainsObject(PropMergedMenu)) { - MainMenu mainMenu = ctl.Properties.GetObject(PropMergedMenu) as MainMenu; - if (mainMenu != null && mainMenu.ownerForm == ctl) + if (ctl.Properties.GetObject(PropMergedMenu) is MainMenu mainMenu && mainMenu.ownerForm == ctl) { mainMenu.Dispose(); } @@ -4570,8 +4568,7 @@ protected override void OnLayout(LayoutEventArgs levent) // a modal resizing loop (WM_WINDOWPOSCHANGED). Size adjustedSize = AutoSizeMode == AutoSizeMode.GrowAndShrink ? prefSize : LayoutUtils.UnionSizes(prefSize, Size); - IArrangedElement form = this as IArrangedElement; - if (form != null) + if (this is IArrangedElement form) { form.SetBounds(new Rectangle(Left, Top, adjustedSize.Width, adjustedSize.Height), BoundsSpecified.None); } @@ -4675,8 +4672,7 @@ protected virtual void OnLoad(EventArgs e) [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnMaximizedBoundsChanged(EventArgs e) { - EventHandler eh = Events[EVENT_MAXIMIZEDBOUNDSCHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_MAXIMIZEDBOUNDSCHANGED] is EventHandler eh) { eh(this, e); } @@ -4685,8 +4681,7 @@ protected virtual void OnMaximizedBoundsChanged(EventArgs e) [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnMaximumSizeChanged(EventArgs e) { - EventHandler eh = Events[EVENT_MAXIMUMSIZECHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_MAXIMUMSIZECHANGED] is EventHandler eh) { eh(this, e); } @@ -4695,8 +4690,7 @@ protected virtual void OnMaximumSizeChanged(EventArgs e) [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnMinimumSizeChanged(EventArgs e) { - EventHandler eh = Events[EVENT_MINIMUMSIZECHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_MINIMUMSIZECHANGED] is EventHandler eh) { eh(this, e); } @@ -4963,8 +4957,7 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) RecreateHandle(); } - EventHandler eh = Events[EVENT_RIGHTTOLEFTLAYOUTCHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_RIGHTTOLEFTLAYOUTCHANGED] is EventHandler eh) { eh(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Help.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Help.cs index 1176820c650..f9656abf39e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Help.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Help.cs @@ -225,13 +225,11 @@ private static void ShowHTML10Help(Control parent, string url, HelpNavigator com } object htmlParam; - string stringParam = param as string; - if (stringParam != null) + if (param is string stringParam) { int htmlCommand = MapCommandToHTMLCommand(command, stringParam, out htmlParam); - string stringHtmlParam = htmlParam as string; - if (stringHtmlParam != null) + if (htmlParam is string stringHtmlParam) { SafeNativeMethods.HtmlHelp(handle, pathAndFileName, htmlCommand, stringHtmlParam); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs index bfe6887c4f1..a626b5061d7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs @@ -405,8 +405,7 @@ public HtmlDocument OpenNew(bool replaceInHistory) object name = (object)(replaceInHistory ? "replace" : ""); object nullObject = null; object ohtmlDocument = NativeHtmlDocument2.Open("text/html", name, nullObject, nullObject); - UnsafeNativeMethods.IHTMLDocument iHTMLDocument = ohtmlDocument as UnsafeNativeMethods.IHTMLDocument; - return iHTMLDocument != null ? new HtmlDocument(ShimManager, iHTMLDocument) : null; + return ohtmlDocument is UnsafeNativeMethods.IHTMLDocument iHTMLDocument ? new HtmlDocument(ShimManager, iHTMLDocument) : null; } public HtmlElement CreateElement(string elementTag) @@ -424,8 +423,7 @@ public object InvokeScript(string scriptName, object[] args) }; try { - UnsafeNativeMethods.IDispatch scriptObject = NativeHtmlDocument2.GetScript() as UnsafeNativeMethods.IDispatch; - if (scriptObject != null) + if (NativeHtmlDocument2.GetScript() is UnsafeNativeMethods.IDispatch scriptObject) { Guid g = Guid.Empty; string[] names = new string[] { scriptName }; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs index 2c857bb52c1..5dc3499bbea 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs @@ -47,8 +47,7 @@ public HtmlElementCollection All { get { - UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection = NativeHtmlElement.GetAll() as UnsafeNativeMethods.IHTMLElementCollection; - return iHTMLElementCollection != null ? new HtmlElementCollection(shimManager, iHTMLElementCollection) : new HtmlElementCollection(shimManager); + return NativeHtmlElement.GetAll() is UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection ? new HtmlElementCollection(shimManager, iHTMLElementCollection) : new HtmlElementCollection(shimManager); } } @@ -56,8 +55,7 @@ public HtmlElementCollection Children { get { - UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection = NativeHtmlElement.GetChildren() as UnsafeNativeMethods.IHTMLElementCollection; - return iHTMLElementCollection != null ? new HtmlElementCollection(shimManager, iHTMLElementCollection) : new HtmlElementCollection(shimManager); + return NativeHtmlElement.GetChildren() is UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection ? new HtmlElementCollection(shimManager, iHTMLElementCollection) : new HtmlElementCollection(shimManager); } } @@ -84,8 +82,7 @@ public HtmlDocument Document { get { - UnsafeNativeMethods.IHTMLDocument iHTMLDocument = NativeHtmlElement.GetDocument() as UnsafeNativeMethods.IHTMLDocument; - return iHTMLDocument != null ? new HtmlDocument(shimManager, iHTMLDocument) : null; + return NativeHtmlElement.GetDocument() is UnsafeNativeMethods.IHTMLDocument iHTMLDocument ? new HtmlDocument(shimManager, iHTMLDocument) : null; } } @@ -124,9 +121,8 @@ public HtmlElement FirstChild get { UnsafeNativeMethods.IHTMLElement iHtmlElement = null; - UnsafeNativeMethods.IHTMLDOMNode iHtmlDomNode = NativeHtmlElement as UnsafeNativeMethods.IHTMLDOMNode; - if (iHtmlDomNode != null) + if (NativeHtmlElement is UnsafeNativeMethods.IHTMLDOMNode iHtmlDomNode) { iHtmlElement = iHtmlDomNode.FirstChild() as UnsafeNativeMethods.IHTMLElement; } @@ -220,9 +216,8 @@ public HtmlElement NextSibling get { UnsafeNativeMethods.IHTMLElement iHtmlElement = null; - UnsafeNativeMethods.IHTMLDOMNode iHtmlDomNode = NativeHtmlElement as UnsafeNativeMethods.IHTMLDOMNode; - if (iHtmlDomNode != null) + if (NativeHtmlElement is UnsafeNativeMethods.IHTMLDOMNode iHtmlDomNode) { iHtmlElement = iHtmlDomNode.NextSibling() as UnsafeNativeMethods.IHTMLElement; } @@ -455,8 +450,7 @@ public object InvokeMember(string methodName, params object[] parameter) }; try { - UnsafeNativeMethods.IDispatch scriptObject = NativeHtmlElement as UnsafeNativeMethods.IDispatch; - if (scriptObject != null) + if (NativeHtmlElement is UnsafeNativeMethods.IDispatch scriptObject) { Guid g = Guid.Empty; string[] names = new string[] { methodName }; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementCollection.cs index 43be9a67b52..b40478fa679 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementCollection.cs @@ -56,9 +56,7 @@ public HtmlElement this[int index] if (NativeHtmlElementCollection != null) { - UnsafeNativeMethods.IHTMLElement htmlElement = - NativeHtmlElementCollection.Item((object)index, (object)0) as UnsafeNativeMethods.IHTMLElement; - return (htmlElement != null) ? new HtmlElement(shimManager, htmlElement) : null; + return (NativeHtmlElementCollection.Item((object)index, (object)0) is UnsafeNativeMethods.IHTMLElement htmlElement) ? new HtmlElement(shimManager, htmlElement) : null; } else if (elementsArray != null) { @@ -77,9 +75,7 @@ public HtmlElement this[string elementId] { if (NativeHtmlElementCollection != null) { - UnsafeNativeMethods.IHTMLElement htmlElement = - NativeHtmlElementCollection.Item((object)elementId, (object)0) as UnsafeNativeMethods.IHTMLElement; - return (htmlElement != null) ? new HtmlElement(shimManager, htmlElement) : null; + return (NativeHtmlElementCollection.Item((object)elementId, (object)0) is UnsafeNativeMethods.IHTMLElement htmlElement) ? new HtmlElement(shimManager, htmlElement) : null; } else if (elementsArray != null) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindow.cs index 92b1f069ccf..4ea434e2053 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindow.cs @@ -70,8 +70,7 @@ public HtmlDocument Document { get { - UnsafeNativeMethods.IHTMLDocument iHTMLDocument = NativeHtmlWindow.GetDocument() as UnsafeNativeMethods.IHTMLDocument; - return iHTMLDocument != null ? new HtmlDocument(ShimManager, iHTMLDocument) : null; + return NativeHtmlWindow.GetDocument() is UnsafeNativeMethods.IHTMLDocument iHTMLDocument ? new HtmlDocument(ShimManager, iHTMLDocument) : null; } } @@ -128,8 +127,7 @@ public HtmlWindow Opener { get { - UnsafeNativeMethods.IHTMLWindow2 iHTMLWindow2 = NativeHtmlWindow.GetOpener() as UnsafeNativeMethods.IHTMLWindow2; - return (iHTMLWindow2 != null) ? new HtmlWindow(ShimManager, iHTMLWindow2) : null; + return (NativeHtmlWindow.GetOpener() is UnsafeNativeMethods.IHTMLWindow2 iHTMLWindow2) ? new HtmlWindow(ShimManager, iHTMLWindow2) : null; } } @@ -193,8 +191,7 @@ public HtmlElement WindowFrameElement { get { - UnsafeNativeMethods.IHTMLElement htmlElement = ((UnsafeNativeMethods.IHTMLWindow4)NativeHtmlWindow).frameElement() as UnsafeNativeMethods.IHTMLElement; - return (htmlElement != null) ? new HtmlElement(ShimManager, htmlElement) : null; + return (((UnsafeNativeMethods.IHTMLWindow4)NativeHtmlWindow).frameElement() is UnsafeNativeMethods.IHTMLElement htmlElement) ? new HtmlElement(ShimManager, htmlElement) : null; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindowCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindowCollection.cs index 5733d050347..98852f24aca 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindowCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindowCollection.cs @@ -40,9 +40,7 @@ public HtmlWindow this[int index] } object oIndex = (object)index; - UnsafeNativeMethods.IHTMLWindow2 htmlWindow2 = NativeHTMLFramesCollection2.Item(ref oIndex) - as UnsafeNativeMethods.IHTMLWindow2; - return (htmlWindow2 != null) ? new HtmlWindow(shimManager, htmlWindow2) : null; + return (NativeHTMLFramesCollection2.Item(ref oIndex) is UnsafeNativeMethods.IHTMLWindow2 htmlWindow2) ? new HtmlWindow(shimManager, htmlWindow2) : null; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ImageIndexConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ImageIndexConverter.cs index 13a8d89528d..f63b594f5d5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ImageIndexConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ImageIndexConverter.cs @@ -56,8 +56,7 @@ internal string ParentImageListProperty /// public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - string stringValue = value as string; - if (stringValue != null && string.Compare(stringValue, SR.toStringNone, true, culture) == 0) + if (value is string stringValue && string.Compare(stringValue, SR.toStringNone, true, culture) == 0) { return -1; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs index 6613fa3d588..8af30366e53 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs @@ -1153,8 +1153,7 @@ public StringCollection Keys for (int i = 0; i < imageInfoCollection.Count; i++) { - ImageInfo image = imageInfoCollection[i] as ImageInfo; - if ((image != null) && (image.Name != null) && (image.Name.Length != 0)) + if ((imageInfoCollection[i] is ImageInfo image) && (image.Name != null) && (image.Name.Length != 0)) { keysCollection.Add(image.Name); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs index aa95f6f9cfe..ae35c4d0b22 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs @@ -602,10 +602,8 @@ internal LabelImageIndexer ImageIndexer { get { - LabelImageIndexer imageIndexer = Properties.GetObject(PropImageIndex, out bool found) as LabelImageIndexer; - // Demand create the ImageIndexer property - if ((imageIndexer == null) || (!found)) + if ((!(Properties.GetObject(PropImageIndex, out bool found) is LabelImageIndexer imageIndexer)) || (!found)) { imageIndexer = new LabelImageIndexer(this); ImageIndexer = imageIndexer; @@ -1583,8 +1581,7 @@ protected override void OnTextChanged(EventArgs e) protected virtual void OnTextAlignChanged(EventArgs e) { - EventHandler eh = Events[EVENT_TEXTALIGNCHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_TEXTALIGNCHANGED] is EventHandler eh) { eh(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElementCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElementCollection.cs index c2e8425a59b..c6e02063531 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElementCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElementCollection.cs @@ -44,9 +44,7 @@ internal virtual IArrangedElement this[int index] public override bool Equals(object obj) { - ArrangedElementCollection other = obj as ArrangedElementCollection; - - if (other == null || Count != other.Count) + if (!(obj is ArrangedElementCollection other) || Count != other.Count) { return false; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs index d64f97950a3..29125a66f29 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs @@ -752,8 +752,7 @@ internal static string Debug_GetChangedProperties(IArrangedElement element) string diff = string.Empty; if (PreferredSize.TraceVerbose) { - Hashtable propertyHash = element.Properties.GetObject(_lastKnownStateProperty) as Hashtable; - if (propertyHash != null) + if (element.Properties.GetObject(_lastKnownStateProperty) is Hashtable propertyHash) { foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(element)) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DockAndAnchorLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DockAndAnchorLayout.cs index aa08af8514b..10cc1620210 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DockAndAnchorLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DockAndAnchorLayout.cs @@ -609,13 +609,11 @@ private static bool xLayout(IArrangedElement container, bool measureOnly, out Si } else { - // Finish the preferredSize computation and clear cached anchored positions. preferredSizeForAnchoring = GetAnchorPreferredSize(container); Padding containerPadding = Padding.Empty; - Control control = container as Control; - if (control != null) + if (container is Control control) { // calling this will respect Control.DefaultPadding. containerPadding = control.Padding; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs index c2e327b8db5..ba0b391ad81 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs @@ -387,8 +387,7 @@ public virtual Rectangle Bounds value.X = DisplayRect.Right - value.Right; } - FlowLayoutPanel flp = Container as FlowLayoutPanel; - if (flp != null) + if (Container is FlowLayoutPanel flp) { Point ptScroll = flp.AutoScrollPosition; if (ptScroll != Point.Empty) @@ -471,14 +470,12 @@ public ElementProxy ElementProxy // used when you want to translate from right to left, but preserve Margin.Right & Margin.Left. protected Rectangle RTLTranslateNoMarginSwap(Rectangle bounds) { - Rectangle newBounds = bounds; newBounds.X = DisplayRect.Right - bounds.X - bounds.Width + ElementProxy.Margin.Left - ElementProxy.Margin.Right; // Since DisplayRect.Right and bounds.X are both adjusted for the AutoScrollPosition, we need add it back here. - FlowLayoutPanel flp = Container as FlowLayoutPanel; - if (flp != null) + if (Container is FlowLayoutPanel flp) { Point ptScroll = flp.AutoScrollPosition; if (ptScroll != Point.Empty) @@ -745,8 +742,7 @@ private void Debug_VerifyAlignment(IArrangedElement container, FlowDirection flo //We cannot apply any of these checks @ design-time since dragging new children into a FlowLayoutPanel //will attempt to set the children at the mouse position when the child was dropped - we rely on the controil //to reposition the children once added. - Control flp = container as Control; - if (flp != null && flp.Site != null && flp.Site.DesignMode) + if (container is Control flp && flp.Site != null && flp.Site.DesignMode) { return; } 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 b0f57b8e9ad..749770b91f7 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 @@ -824,8 +824,7 @@ private int InflateColumns(ContainerInfo containerInfo, Size proposedConstraints if (dontHonorConstraint && (proposedConstraints.Width < short.MaxValue)) { - TableLayoutPanel tlp = containerInfo.Container as TableLayoutPanel; - if (tlp != null && tlp.ParentInternal != null && tlp.ParentInternal.LayoutEngine == DefaultLayout.Instance) + if (containerInfo.Container is TableLayoutPanel tlp && tlp.ParentInternal != null && tlp.ParentInternal.LayoutEngine == DefaultLayout.Instance) { if (tlp.Dock == DockStyle.Top || tlp.Dock == DockStyle.Bottom || tlp.Dock == DockStyle.Fill) { @@ -951,8 +950,7 @@ private int InflateRows(ContainerInfo containerInfo, Size proposedConstraints, i if (dontHonorConstraint && (proposedConstraints.Height < short.MaxValue)) { - TableLayoutPanel tlp = containerInfo.Container as TableLayoutPanel; - if (tlp != null && tlp.ParentInternal != null && tlp.ParentInternal.LayoutEngine == DefaultLayout.Instance) + if (containerInfo.Container is TableLayoutPanel tlp && tlp.ParentInternal != null && tlp.ParentInternal.LayoutEngine == DefaultLayout.Instance) { if (tlp.Dock == DockStyle.Left || tlp.Dock == DockStyle.Right || tlp.Dock == DockStyle.Fill) { @@ -1627,8 +1625,7 @@ public LayoutInfo Clone() public override bool Equals(object obj) { - LayoutInfo other = obj as LayoutInfo; - if (other == null) + if (!(obj is LayoutInfo other)) { return false; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingHelper.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingHelper.cs index f127e8ff186..b697e019569 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingHelper.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingHelper.cs @@ -103,8 +103,7 @@ public static string GetListName(object list, PropertyDescriptor[] listAccessors { return string.Empty; } - ITypedList typedList = list as ITypedList; - if (typedList != null) + if (list is ITypedList typedList) { // Use typed list name = typedList.GetListName(listAccessors); @@ -433,8 +432,7 @@ private static PropertyDescriptorCollection GetListItemPropertiesByEnumerable(IE // We have the Instance (e.g. Orders) ++startIndex; - IEnumerable ienumerableSubList = subList as IEnumerable; - if (ienumerableSubList != null) + if (subList is IEnumerable ienumerableSubList) { if (startIndex == listAccessors.Length) { @@ -600,8 +598,7 @@ private static PropertyDescriptorCollection GetListItemPropertiesByEnumerable(IE } else { - ITypedList typedListEnumerable = enumerable as ITypedList; - if (typedListEnumerable != null) + if (enumerable is ITypedList typedListEnumerable) { pdc = typedListEnumerable.GetItemProperties(null); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs index 8f20208901c..2604085d1e6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs @@ -4914,8 +4914,7 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) RecreateHandleInternal(); } - EventHandler eh = Events[EVENT_RIGHTTOLEFTLAYOUTCHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_RIGHTTOLEFTLAYOUTCHANGED] is EventHandler eh) { eh(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupConverter.cs index 3301d62beef..54e8d4da1a9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupConverter.cs @@ -59,8 +59,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c string text = ((string)value).Trim(); if (context != null && context.Instance != null) { - ListViewItem item = context.Instance as ListViewItem; - if (item != null && item.ListView != null) + if (context.Instance is ListViewItem item && item.ListView != null) { foreach (ListViewGroup group in item.ListView.Groups) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MDIControlStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MDIControlStrip.cs index 00ecb9a6613..d4b1c9bc5cf 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MDIControlStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MDIControlStrip.cs @@ -44,8 +44,7 @@ public MdiControlStrip(IWin32Window target) system = new SystemMenuItem(); // However in the event that the target handle changes we have to push the new handle into everyone. - Control controlTarget = target as Control; - if (controlTarget != null) + if (target is Control controlTarget) { controlTarget.HandleCreated += new EventHandler(OnTargetWindowHandleRecreated); controlTarget.Disposed += new EventHandler(OnTargetWindowDisposed); @@ -212,8 +211,7 @@ private void UnhookTarget() { if (target != null) { - Control controlTarget = target as Control; - if (controlTarget != null) + if (target is Control controlTarget) { controlTarget.HandleCreated -= new EventHandler(OnTargetWindowHandleRecreated); controlTarget.Disposed -= new EventHandler(OnTargetWindowDisposed); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs index d340db23d57..c28c38cb9c8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs @@ -1959,9 +1959,7 @@ protected override void OnHandleCreated(EventArgs e) ] protected virtual void OnIsOverwriteModeChanged(EventArgs e) { - EventHandler eh = Events[EVENT_ISOVERWRITEMODECHANGED] as EventHandler; - - if (eh != null) + if (Events[EVENT_ISOVERWRITEMODECHANGED] is EventHandler eh) { eh(this, e); } @@ -2198,9 +2196,7 @@ protected override void OnKeyUp(KeyEventArgs e) ] protected virtual void OnMaskChanged(EventArgs e) { - EventHandler eh = Events[EVENT_MASKCHANGED] as EventHandler; - - if (eh != null) + if (Events[EVENT_MASKCHANGED] is EventHandler eh) { eh(this, e); } @@ -2219,9 +2215,8 @@ private void OnMaskInputRejected(MaskInputRejectedEventArgs e) sp.Play(); } - MaskInputRejectedEventHandler eh = Events[EVENT_MASKINPUTREJECTED] as MaskInputRejectedEventHandler; - if (eh != null) + if (Events[EVENT_MASKINPUTREJECTED] is MaskInputRejectedEventHandler eh) { eh(this, e); } @@ -2243,8 +2238,7 @@ protected override void OnMultilineChanged(EventArgs e) /// protected virtual void OnTextAlignChanged(EventArgs e) { - EventHandler eh = Events[EVENT_TEXTALIGNCHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_TEXTALIGNCHANGED] is EventHandler eh) { eh(this, e); } @@ -2256,8 +2250,7 @@ protected virtual void OnTextAlignChanged(EventArgs e) /// private void OnTypeValidationCompleted(TypeValidationEventArgs e) { - TypeValidationEventHandler eh = Events[EVENT_VALIDATIONCOMPLETED] as TypeValidationEventHandler; - if (eh != null) + if (Events[EVENT_VALIDATIONCOMPLETED] is TypeValidationEventHandler eh) { eh(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListItemConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListItemConverter.cs index d41de9239b0..6b3907ad5f8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListItemConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListItemConverter.cs @@ -20,16 +20,14 @@ public MdiWindowListItemConverter(Type type) : base(type) /// public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { - MenuStrip menu = context.Instance as MenuStrip; - if (menu != null) + if (context.Instance is MenuStrip menu) { StandardValuesCollection values = base.GetStandardValues(context); ArrayList list = new ArrayList(); int count = values.Count; for (int i = 0; i < count; i++) { - ToolStripItem currentItem = values[i] as ToolStripItem; - if (currentItem != null && currentItem.Owner == menu) + if (values[i] is ToolStripItem currentItem && currentItem.Owner == menu) { list.Add(currentItem); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListStrip.cs index 281b882d803..49d000e2ba3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListStrip.cs @@ -193,9 +193,7 @@ private void OnMoreWindowsMenuItemClick(object sender, EventArgs e) /// handler for 1 - 9. This is similar to MenuItem.cs private void OnWindowListItemClick(object sender, EventArgs e) { - ToolStripMenuItem windowListItem = sender as ToolStripMenuItem; - - if (windowListItem != null) + if (sender is ToolStripMenuItem windowListItem) { Form boundForm = windowListItem.MdiForm; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs index 2a0c1d4cf43..a37d4ef5f43 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs @@ -1315,8 +1315,7 @@ protected override void OnResize(EventArgs e) protected virtual void OnSizeModeChanged(EventArgs e) { - EventHandler eh = Events[EVENT_SIZEMODECHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_SIZEMODECHANGED] is EventHandler eh) { eh(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewControl.cs index 827433b8c01..4193198fd21 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewControl.cs @@ -716,8 +716,7 @@ protected override void OnPaint(PaintEventArgs pevent) protected virtual void OnStartPageChanged(EventArgs e) { - EventHandler eh = Events[EVENT_STARTPAGECHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_STARTPAGECHANGED] is EventHandler eh) { eh(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs index 2d98f08ca3e..a975b05d7f0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs @@ -1262,8 +1262,6 @@ public PrintPreviewControl PrintPreviewControl ] void InitForm() { - - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PrintPreviewDialog)); toolStrip1 = new System.Windows.Forms.ToolStrip(); printToolStripButton = new System.Windows.Forms.ToolStripButton(); @@ -1522,8 +1520,7 @@ void InitForm() zoomToolStripSplitButton.DefaultItem = autoToolStripMenuItem; //ShowCheckMargin - ToolStripDropDownMenu menu = zoomToolStripSplitButton.DropDown as ToolStripDropDownMenu; - if (menu != null) + if (zoomToolStripSplitButton.DropDown is ToolStripDropDownMenu menu) { menu.ShowCheckMargin = true; menu.ShowImageMargin = false; @@ -1725,8 +1722,7 @@ void Zoom10(object sender, EventArgs eventargs) void OncloseToolStripButtonPaint(object sender, PaintEventArgs e) { - ToolStripItem item = sender as ToolStripItem; - if (item != null && !item.Selected) + if (sender is ToolStripItem item && !item.Selected) { Rectangle rect = new Rectangle(0, 0, item.Bounds.Width - 1, item.Bounds.Height - 1); using (Pen pen = new Pen(SystemColors.ControlDark)) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs index a8ff8db384f..340a01edb4c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs @@ -2961,8 +2961,7 @@ void UnsafeNativeMethods.IPropertyNotifySink.OnChanged(int dispID) // // bool fullRefresh = false; - PropertyDescriptorGridEntry selectedEntry = gridView.SelectedGridEntry as PropertyDescriptorGridEntry; - if (selectedEntry != null && selectedEntry.PropertyDescriptor != null && selectedEntry.PropertyDescriptor.Attributes != null) + if (gridView.SelectedGridEntry is PropertyDescriptorGridEntry selectedEntry && selectedEntry.PropertyDescriptor != null && selectedEntry.PropertyDescriptor.Attributes != null) { // fish out the DispIdAttribute which will tell us the DispId of the @@ -3632,8 +3631,7 @@ internal void OnPropertyValueSet(GridItem changedItem, object oldValue) } else { - var gridEntry = changedItem as GridEntry; - if (gridEntry != null && gridEntry.Enumerable) + if (changedItem is GridEntry gridEntry && gridEntry.Enumerable) { dropDown = true; } @@ -3683,8 +3681,7 @@ private void OnTransactionClosed(object sender, DesignerTransactionCloseEventArg if (e.LastTransaction) { // We should not refresh the grid if the selectedObject is no longer sited. - IComponent currentSelection = SelectedObject as IComponent; - if (currentSelection != null) + if (SelectedObject is IComponent currentSelection) { if (currentSelection.Site == null) //The component is not logically sited...so clear the PropertyGrid Selection.. { @@ -5396,8 +5393,7 @@ protected override void WndProc(ref Message m) int index = unchecked((int)(long)m.WParam); if (index >= 0 && index < toolStrip.Items.Count) { - ToolStripButton button = toolStrip.Items[index] as ToolStripButton; - if (button != null) + if (toolStrip.Items[index] is ToolStripButton button) { m.Result = (IntPtr)(button.Checked ? 1 : 0); } @@ -5415,9 +5411,7 @@ protected override void WndProc(ref Message m) int index = unchecked((int)(long)m.WParam); if (index >= 0 && index < toolStrip.Items.Count) { - ToolStripButton button = toolStrip.Items[index] as ToolStripButton; - - if (button != null) + if (toolStrip.Items[index] is ToolStripButton button) { button.Checked = !button.Checked; // special treatment for the properies page button @@ -6212,8 +6206,7 @@ public PropertyGridToolStripAccessibleObject(PropertyGridToolStrip owningPropert /// Returns the element in the specified direction. internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - var propertyGridAccessibleObject = _parentPropertyGrid.AccessibilityObject as PropertyGridAccessibleObject; - if (propertyGridAccessibleObject != null) + if (_parentPropertyGrid.AccessibilityObject is PropertyGridAccessibleObject propertyGridAccessibleObject) { UnsafeNativeMethods.IRawElementProviderFragment navigationTarget = propertyGridAccessibleObject.ChildFragmentNavigate(this, direction); if (navigationTarget != null) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs index fbb0115bbc7..d6686ea1c53 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs @@ -292,8 +292,7 @@ public DocCommentAccessibleObject(DocComment owningDocComment, PropertyGrid pare /// Returns the element in the specified direction. internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - var propertyGridAccessibleObject = _parentPropertyGrid.AccessibilityObject as PropertyGridAccessibleObject; - if (propertyGridAccessibleObject != null) + if (_parentPropertyGrid.AccessibilityObject is PropertyGridAccessibleObject propertyGridAccessibleObject) { UnsafeNativeMethods.IRawElementProviderFragment navigationTarget = propertyGridAccessibleObject.ChildFragmentNavigate(this, direction); if (navigationTarget != null) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs index 40fef802d5e..14c46ee62a6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs @@ -289,8 +289,7 @@ public HotCommandsAccessibleObject(HotCommands owningHotCommands, PropertyGrid p /// Returns the element in the specified direction. internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - var propertyGridAccessibleObject = _parentPropertyGrid.AccessibilityObject as PropertyGridAccessibleObject; - if (propertyGridAccessibleObject != null) + if (_parentPropertyGrid.AccessibilityObject is PropertyGridAccessibleObject propertyGridAccessibleObject) { UnsafeNativeMethods.IRawElementProviderFragment navigationTarget = propertyGridAccessibleObject.ChildFragmentNavigate(this, direction); if (navigationTarget != null) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs index 6dba69ef63b..80a53abecf9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs @@ -192,7 +192,6 @@ public override bool CanResetValue(object component) /// private object CopyValue(object value) { - // null is always OK if (value == null) { @@ -210,8 +209,7 @@ private object CopyValue(object value) object clonedValue = null; // ICloneable is the next easiest thing - ICloneable clone = value as ICloneable; - if (clone != null) + if (value is ICloneable clone) { clonedValue = clone.Clone(); } @@ -408,9 +406,7 @@ private void SetCollectionValues(Array a, IList listValue) for (int i = 0; i < descriptors.Length; i++) { - IList propList = descriptors[i].GetValue(GetPropertyOwnerForComponent(a, i)) as IList; - - if (propList == null) + if (!(descriptors[i].GetValue(GetPropertyOwnerForComponent(a, i)) is IList propList)) { continue; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiPropertyDescriptorGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiPropertyDescriptorGridEntry.cs index 98e50a69248..c30218fff28 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiPropertyDescriptorGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiPropertyDescriptorGridEntry.cs @@ -44,8 +44,7 @@ public override IContainer Container foreach (object o in objs) { - IComponent comp = o as IComponent; - if (comp == null) + if (!(o is IComponent comp)) { c = null; break; @@ -253,8 +252,7 @@ ge is PropertyDescriptorGridEntry && if (changeService != null) { - Array ownerArray = owner as Array; - if (ownerArray != null) + if (owner is Array ownerArray) { for (int i = 0; i < ownerArray.Length; i++) { @@ -345,9 +343,8 @@ internal override bool NotifyValueGivenParent(object obj, int type) Debug.Assert(propertyInfo is MergePropertyDescriptor, "Did not get a MergePropertyDescriptor!!!"); Debug.Assert(obj is object[], "Did not get an array of objects!!"); - MergePropertyDescriptor mpd = propertyInfo as MergePropertyDescriptor; - if (mpd != null) + if (propertyInfo is MergePropertyDescriptor mpd) { object[] objs = (object[])obj; @@ -384,10 +381,7 @@ private bool OwnersEqual(object owner1, object owner2) } else { - Array a1 = owner1 as Array; - Array a2 = owner2 as Array; - - if (a1 != null && a2 != null && a1.Length == a2.Length) + if (owner1 is Array a1 && owner2 is Array a2 && a1.Length == a2.Length) { for (int i = 0; i < a1.Length; i++) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs index 01bfbb58bc1..a2f92eeca9c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs @@ -1016,11 +1016,9 @@ protected bool ViewEvent(object obj, string newHandler, EventDescriptor eventdes if (component == null && propertyInfo is MergePropertyDescriptor) { - // It's possible that multiple objects are selected, and we're trying to create an event for each of them // - Array objArray = obj as Array; - if (objArray != null && objArray.Length > 0) + if (obj is Array objArray && objArray.Length > 0) { component = objArray.GetValue(0) as IComponent; } @@ -1343,9 +1341,7 @@ private class ExceptionEditor : UITypeEditor /// public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { - Exception except = value as Exception; - - if (except != null) + if (value is Exception except) { IUIService uis = null; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs index 308f2c9d9c6..9dddf51f4ce 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs @@ -2764,8 +2764,7 @@ private void OnChildLostFocus(object sender, EventArgs e) private void OnDropDownButtonGotFocus(object sender, EventArgs e) { - DropDownButton dropDownButton = sender as DropDownButton; - if (dropDownButton != null) + if (sender is DropDownButton dropDownButton) { dropDownButton.AccessibilityObject.SetFocus(); } @@ -3833,11 +3832,9 @@ protected override void OnMouseUp(MouseEventArgs me) protected override void OnMouseWheel(MouseEventArgs me) { - ownerGrid.OnGridViewMouseWheel(me); - HandledMouseEventArgs e = me as HandledMouseEventArgs; - if (e != null) + if (me is HandledMouseEventArgs e) { if (e.Handled) { @@ -7181,8 +7178,7 @@ protected override void OnSelectedIndexChanged(EventArgs e) base.OnSelectedIndexChanged(e); fInSetSelectedIndex = false; - var gridViewListBoxAccessibleObject = AccessibilityObject as GridViewListBoxAccessibleObject; - if (gridViewListBoxAccessibleObject != null) + if (AccessibilityObject is GridViewListBoxAccessibleObject gridViewListBoxAccessibleObject) { gridViewListBoxAccessibleObject.SetListBoxItemFocus(); } @@ -7238,8 +7234,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga return _owningGridViewListBox.AccessibilityObject; case UnsafeNativeMethods.NavigateDirection.NextSibling: int currentIndex = GetCurrentIndex(); - var gridViewListBoxAccessibleObject = _owningGridViewListBox.AccessibilityObject as GridViewListBoxAccessibleObject; - if (gridViewListBoxAccessibleObject != null) + if (_owningGridViewListBox.AccessibilityObject is GridViewListBoxAccessibleObject gridViewListBoxAccessibleObject) { int itemsCount = gridViewListBoxAccessibleObject.GetChildFragmentCount(); int nextItemIndex = currentIndex + 1; @@ -7566,8 +7561,7 @@ internal override void SetFocus() internal void SetListBoxItemFocus() { var selectedItem = _owningGridViewListBox.SelectedItem; - var itemAccessibleObject = _itemAccessibleObjects[selectedItem] as AccessibleObject; - if (itemAccessibleObject != null) + if (_itemAccessibleObjects[selectedItem] is AccessibleObject itemAccessibleObject) { itemAccessibleObject.SetFocus(); } @@ -8165,8 +8159,7 @@ internal override bool IsReadOnly { get { - PropertyDescriptorGridEntry propertyDescriptorGridEntry = propertyGridView.SelectedGridEntry as PropertyDescriptorGridEntry; - return propertyDescriptorGridEntry == null || propertyDescriptorGridEntry.IsPropertyReadOnly; + return !(propertyGridView.SelectedGridEntry is PropertyDescriptorGridEntry propertyDescriptorGridEntry) || propertyDescriptorGridEntry.IsPropertyReadOnly; } } @@ -8498,8 +8491,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment ElementProvide /// Returns the element in the specified direction. internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - var propertyGridAccessibleObject = _parentPropertyGrid.AccessibilityObject as PropertyGridAccessibleObject; - if (propertyGridAccessibleObject != null) + if (_parentPropertyGrid.AccessibilityObject is PropertyGridAccessibleObject propertyGridAccessibleObject) { UnsafeNativeMethods.IRawElementProviderFragment navigationTarget = propertyGridAccessibleObject.ChildFragmentNavigate(this, direction); if (navigationTarget != null) @@ -8628,8 +8620,7 @@ internal AccessibleObject GetCategory(int categoryIndex) if (topLevelGridEntriesCount > 0) { GridItem targetEntry = topLevelGridEntries[categoryIndex]; - var categoryGridEntry = targetEntry as CategoryGridEntry; - if (categoryGridEntry != null) + if (targetEntry is CategoryGridEntry categoryGridEntry) { return categoryGridEntry.AccessibilityObject; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs index 1cf36e41c64..e8720c35287 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs @@ -594,8 +594,7 @@ internal override ButtonBaseAdapter CreateStandardAdapter() private void OnAppearanceChanged(EventArgs e) { - EventHandler eh = Events[EVENT_APPEARANCECHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_APPEARANCECHANGED] is EventHandler eh) { eh(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SelectionRangeConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SelectionRangeConverter.cs index 759c10b49fc..d1b4626eb7e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SelectionRangeConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SelectionRangeConverter.cs @@ -111,8 +111,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul throw new ArgumentNullException(nameof(destinationType)); } - SelectionRange range = value as SelectionRange; - if (range != null) + if (value is SelectionRange range) { if (destinationType == typeof(string)) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs index ade348ea61b..95a154d6f72 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs @@ -1392,8 +1392,7 @@ protected override void OnMouseDown(MouseEventArgs e) IContainerControl c = ParentInternal.GetContainerControl(); if (c != null) { - ContainerControl cc = c as ContainerControl; - if (cc == null) + if (!(c is ContainerControl cc)) { c.ActiveControl = this; } @@ -2099,8 +2098,7 @@ private bool SelectNextControlInContainer(Control ctl, bool forward, bool tabSto { ctl = GetNextControl(ctl, forward); - SplitterPanel panel = ctl as SplitterPanel; - if (panel != null && panel.Visible) + if (ctl is SplitterPanel panel && panel.Visible) { //We have crossed over to the second Panel... if (firstPanel != null) @@ -2142,8 +2140,7 @@ private bool SelectNextControlInContainer(Control ctl, bool forward, bool tabSto IContainerControl c = ParentInternal.GetContainerControl(); if (c != null) { - ContainerControl cc = c as ContainerControl; - if (cc == null) + if (!(c is ContainerControl cc)) { c.ActiveControl = this; } @@ -2251,8 +2248,7 @@ private bool SelectNextControlInPanel(Control ctl, bool forward, bool tabStopOnl // This will select the correct active control in the containerControl (if the passed in control is a containerControl) private static void SelectNextActiveControl(Control ctl, bool forward, bool tabStopOnly, bool nested, bool wrap) { - ContainerControl container = ctl as ContainerControl; - if (container != null) + if (ctl is ContainerControl container) { bool correctParentActiveControl = true; if (container.ParentInternal != null) @@ -2287,8 +2283,7 @@ private void SetInnerMostBorder(SplitContainer sc) { foreach (Control c in ctl.Controls) { - SplitContainer c1 = c as SplitContainer; - if (c1 != null && c1.Dock == DockStyle.Fill) + if (c is SplitContainer c1 && c1.Dock == DockStyle.Fill) { // We need to Overlay borders // if the Children have matching BorderStyles ... @@ -2671,8 +2666,7 @@ protected override bool ProcessTabKey(bool forward) IContainerControl c = ParentInternal.GetContainerControl(); if (c != null) { - ContainerControl cc = c as ContainerControl; - if (cc == null) + if (!(c is ContainerControl cc)) { c.ActiveControl = this; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/StatusStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/StatusStrip.cs index f67c9b2945a..0a647fd1f17 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/StatusStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/StatusStrip.cs @@ -328,9 +328,7 @@ private void EnsureRightToLeftGrip() RTLGrip.Bounds = SizeGripBounds; if (!Controls.Contains(RTLGrip)) { - WindowsFormsUtils.ReadOnlyControlCollection controlCollection = Controls as WindowsFormsUtils.ReadOnlyControlCollection; - - if (controlCollection != null) + if (Controls is WindowsFormsUtils.ReadOnlyControlCollection controlCollection) { controlCollection.AddInternal(RTLGrip); } @@ -340,9 +338,7 @@ private void EnsureRightToLeftGrip() { if (Controls.Contains(rtlLayoutGrip)) { - WindowsFormsUtils.ReadOnlyControlCollection controlCollection = Controls as WindowsFormsUtils.ReadOnlyControlCollection; - - if (controlCollection != null) + if (Controls is WindowsFormsUtils.ReadOnlyControlCollection controlCollection) { controlCollection.RemoveInternal(rtlLayoutGrip); } @@ -467,8 +463,7 @@ protected override void SetDisplayedItems() } else if (item.Bounds.Width == 1) { - ToolStripStatusLabel panel = item as ToolStripStatusLabel; - if (panel != null && panel.Spring) + if (item is ToolStripStatusLabel panel && panel.Spring) { // once we get down to one pixel, there can always be a one pixel // distribution problem with the TLP - there's usually a spare one around. @@ -553,8 +548,7 @@ protected virtual void OnSpringTableLayoutCore() } // determine if we "spring" or "autosize" the column - ToolStripStatusLabel panel = DisplayedItems[i] as ToolStripStatusLabel; - bool spring = (panel != null && panel.Spring); + bool spring = (DisplayedItems[i] is ToolStripStatusLabel panel && panel.Spring); DisplayedItems[i].Anchor = (spring) ? AllAnchor : VerticalAnchor; // spring is achieved by using 100% as the column style @@ -600,8 +594,7 @@ protected virtual void OnSpringTableLayoutCore() } // determine if we "spring" or "autosize" the row - ToolStripStatusLabel panel = DisplayedItems[i] as ToolStripStatusLabel; - bool spring = (panel != null && panel.Spring); + bool spring = (DisplayedItems[i] is ToolStripStatusLabel panel && panel.Spring); DisplayedItems[i].Anchor = (spring) ? AllAnchor : HorizontalAnchor; // spring is achieved by using 100% as the row style @@ -759,8 +752,7 @@ internal override object GetPropertyValue(int propertyID) internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction) { - StatusStrip statusStrip = Owner as StatusStrip; - if (statusStrip == null || statusStrip.Items.Count == 0) + if (!(Owner is StatusStrip statusStrip) || statusStrip.Items.Count == 0) { return null; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs index b020b5b5602..3437bfba71f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs @@ -1614,8 +1614,7 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) RecreateHandle(); } - EventHandler eh = Events[EVENT_RIGHTTOLEFTLAYOUTCHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_RIGHTTOLEFTLAYOUTCHANGED] is EventHandler eh) { eh(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TabPage.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TabPage.cs index a799f113a7c..a20d398a6f0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TabPage.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TabPage.cs @@ -116,8 +116,7 @@ public override Color BackColor return color; } // If user has not set a color and if theming ON and Parent's appearance is Normal, then return the Transparent Color.... - TabControl parent = ParentInternal as TabControl; - if (Application.RenderWithVisualStyles && UseVisualStyleBackColor && (parent != null && parent.Appearance == TabAppearance.Normal)) + if (Application.RenderWithVisualStyles && UseVisualStyleBackColor && (ParentInternal is TabControl parent && parent.Appearance == TabAppearance.Normal)) { return Color.Transparent; } @@ -196,9 +195,8 @@ public int ImageIndex throw new ArgumentOutOfRangeException(nameof(value), string.Format(SR.InvalidLowBoundArgumentEx, nameof(ImageIndex), value, -1)); } - TabControl parent = ParentInternal as TabControl; - if (parent != null) + if (ParentInternal is TabControl parent) { ImageIndexer.ImageList = parent.ImageList; } @@ -230,9 +228,8 @@ public string ImageKey { ImageIndexer.Key = value; - TabControl parent = ParentInternal as TabControl; - if (parent != null) + if (ParentInternal is TabControl parent) { ImageIndexer.ImageList = parent.ImageList; } @@ -641,9 +638,7 @@ internal void FireEnter(EventArgs e) /// protected override void OnEnter(EventArgs e) { - TabControl parent = ParentInternal as TabControl; - - if (parent != null) + if (ParentInternal is TabControl parent) { if (enterFired) { @@ -669,9 +664,7 @@ protected override void OnEnter(EventArgs e) /// protected override void OnLeave(EventArgs e) { - TabControl parent = ParentInternal as TabControl; - - if (parent != null) + if (ParentInternal is TabControl parent) { if (leaveFired) { @@ -684,7 +677,6 @@ protected override void OnLeave(EventArgs e) protected override void OnPaintBackground(PaintEventArgs e) { - // Utilize the TabRenderer new to Whidbey to draw the tab pages so that the // panels are drawn using the correct visual styles when the application supports using visual // styles. @@ -692,8 +684,7 @@ protected override void OnPaintBackground(PaintEventArgs e) // Does this application utilize Visual Styles? // Utilize the UseVisualStyleBackColor property to determine whether or // not the themed background should be utilized. - TabControl parent = ParentInternal as TabControl; - if (Application.RenderWithVisualStyles && UseVisualStyleBackColor && (parent != null && parent.Appearance == TabAppearance.Normal)) + if (Application.RenderWithVisualStyles && UseVisualStyleBackColor && (ParentInternal is TabControl parent && parent.Appearance == TabAppearance.Normal)) { Color bkcolor = UseVisualStyleBackColor ? Color.Transparent : BackColor; @@ -771,9 +762,7 @@ public override string ToString() /// internal void UpdateParent() { - TabControl parent = ParentInternal as TabControl; - - if (parent != null) + if (ParentInternal is TabControl parent) { parent.UpdateTab(this); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanel.cs index 13643a67dd3..4d254aaacb9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanel.cs @@ -222,8 +222,7 @@ private bool ShouldSerializeControls() #region Extended Properties bool IExtenderProvider.CanExtend(object obj) { - Control control = obj as Control; - return control != null && control.Parent == this; + return obj is Control control && control.Parent == this; } [SRDescription(nameof(SR.GridPanelGetColumnSpanDescr))] diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettings.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettings.cs index 426742ea478..e78e3fd2517 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettings.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettings.cs @@ -55,8 +55,7 @@ internal TableLayoutSettings(SerializationInfo serializationInfo, StreamingConte if (!string.IsNullOrEmpty(stringVal)) { - TableLayoutSettings tls = converter.ConvertFromInvariantString(stringVal) as TableLayoutSettings; - if (tls != null) + if (converter.ConvertFromInvariantString(stringVal) is TableLayoutSettings tls) { ApplySettings(tls); } @@ -556,8 +555,7 @@ internal List GetControlsInformation() foreach (IArrangedElement element in Owner.Children) { - Control c = element as Control; - if (c != null) + if (element is Control c) { ControlInformation controlInfo = new ControlInformation(); @@ -629,8 +627,7 @@ internal void ApplySettings(TableLayoutSettings settings) // apply row,column,rowspan,colspan // TableLayout.ContainerInfo containerInfo = TableLayout.GetContainerInfo(settings.Owner); - Control appliedControl = containerInfo.Container as Control; - if (appliedControl != null && controlsInfo != null) + if (containerInfo.Container is Control appliedControl && controlsInfo != null) { // we store the control names, look up the controls diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutStyle.cs index b598cbb6e73..5a7bf7be06f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutStyle.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutStyle.cs @@ -34,8 +34,7 @@ public SizeType SizeType if (Owner != null) { LayoutTransaction.DoLayout(Owner, Owner, PropertyNames.Style); - Control owner = Owner as Control; - if (owner != null) + if (Owner is Control owner) { owner.Invalidate(); } @@ -59,8 +58,7 @@ internal float Size if (Owner != null) { LayoutTransaction.DoLayout(Owner, Owner, PropertyNames.Style); - Control owner = Owner as Control; - if (owner != null) + if (Owner is Control owner) { owner.Invalidate(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TextBox.cs index 715023595b7..7daf52cdac3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TextBox.cs @@ -716,8 +716,7 @@ protected override void OnHandleDestroyed(EventArgs e) protected virtual void OnTextAlignChanged(EventArgs e) { - EventHandler eh = Events[EVENT_TEXTALIGNCHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_TEXTALIGNCHANGED] is EventHandler eh) { eh(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxBase.cs index d3b76913e91..0706d9f8d8a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TextBoxBase.cs @@ -1686,8 +1686,7 @@ protected override bool ProcessDialogKey(Keys keyData) protected virtual void OnAcceptsTabChanged(EventArgs e) { - EventHandler eh = Events[EVENT_ACCEPTSTABCHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_ACCEPTSTABCHANGED] is EventHandler eh) { eh(this, e); } @@ -1695,8 +1694,7 @@ protected virtual void OnAcceptsTabChanged(EventArgs e) protected virtual void OnBorderStyleChanged(EventArgs e) { - EventHandler eh = Events[EVENT_BORDERSTYLECHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_BORDERSTYLECHANGED] is EventHandler eh) { eh(this, e); } @@ -1710,8 +1708,7 @@ protected override void OnFontChanged(EventArgs e) protected virtual void OnHideSelectionChanged(EventArgs e) { - EventHandler eh = Events[EVENT_HIDESELECTIONCHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_HIDESELECTIONCHANGED] is EventHandler eh) { eh(this, e); } @@ -1719,8 +1716,7 @@ protected virtual void OnHideSelectionChanged(EventArgs e) protected virtual void OnModifiedChanged(EventArgs e) { - EventHandler eh = Events[EVENT_MODIFIEDCHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_MODIFIEDCHANGED] is EventHandler eh) { eh(this, e); } @@ -1756,8 +1752,7 @@ protected override void OnMouseUp(MouseEventArgs mevent) protected virtual void OnMultilineChanged(EventArgs e) { - EventHandler eh = Events[EVENT_MULTILINECHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_MULTILINECHANGED] is EventHandler eh) { eh(this, e); } @@ -1772,8 +1767,7 @@ protected override void OnPaddingChanged(EventArgs e) protected virtual void OnReadOnlyChanged(EventArgs e) { - EventHandler eh = Events[EVENT_READONLYCHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_READONLYCHANGED] is EventHandler eh) { eh(this, e); } @@ -1908,9 +1902,8 @@ public void ScrollToCaret() { Marshal.QueryInterface(editOlePtr, ref iiTextDocumentGuid, out iTextDocument); - UnsafeNativeMethods.ITextDocument textDocument = Marshal.GetObjectForIUnknown(iTextDocument) as UnsafeNativeMethods.ITextDocument; - if (textDocument != null) + if (Marshal.GetObjectForIUnknown(iTextDocument) is UnsafeNativeMethods.ITextDocument textDocument) { // When the user calls RichTextBox::ScrollToCaret we want the RichTextBox to show as diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ThreadExceptionDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ThreadExceptionDialog.cs index fb845bc213c..8920ada94ff 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ThreadExceptionDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ThreadExceptionDialog.cs @@ -84,7 +84,6 @@ public class ThreadExceptionDialog : Form /// public ThreadExceptionDialog(Exception t) { - if (DpiHelper.IsScalingRequirementMet) { scaledMaxWidth = LogicalToDeviceUnits(MAXWIDTH); @@ -113,8 +112,7 @@ public ThreadExceptionDialog(Exception t) Button[] buttons; bool detailAnchor = false; - WarningException w = t as WarningException; - if (w != null) + if (t is WarningException w) { messageFormat = SR.ExDlgWarningText; messageText = w.Message; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs index 8dc69c43212..9281421caf9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs @@ -2120,8 +2120,7 @@ internal virtual void ChangeSelection(ToolStripItem nextItem) nextItem.Select(); - ToolStripMenuItem tsNextItem = nextItem as ToolStripMenuItem; - if (tsNextItem != null && !IsDropDown) + if (nextItem is ToolStripMenuItem tsNextItem && !IsDropDown) { // only toplevel menus auto expand when the selection changes. tsNextItem.HandleAutoExpansion(); @@ -2186,9 +2185,8 @@ private void ClearAllSelectionsExcept(ToolStripItem item) else if (item != null && DisplayedItems[i].Pressed) { // - ToolStripDropDownItem dropDownItem = DisplayedItems[i] as ToolStripDropDownItem; - if (dropDownItem != null && dropDownItem.HasDropDownItems) + if (DisplayedItems[i] is ToolStripDropDownItem dropDownItem && dropDownItem.HasDropDownItems) { dropDownItem.AutoHide(item); } @@ -2281,7 +2279,6 @@ protected override void Dispose(bool disposing) try { - SuspendLayout(); if (overflow != null) { @@ -2293,8 +2290,7 @@ protected override void Dispose(bool disposing) HookStaticEvents(/*hook=*/false); - ToolStripPanelCell toolStripPanelCell = Properties.GetObject(ToolStrip.PropToolStripPanelCell) as ToolStripPanelCell; - if (toolStripPanelCell != null) + if (Properties.GetObject(ToolStrip.PropToolStripPanelCell) is ToolStripPanelCell toolStripPanelCell) { toolStripPanelCell.Dispose(); } @@ -2510,7 +2506,6 @@ private ToolStripItem GetNextItemHorizontal(ToolStripItem start, bool forward) do { - if (forward) { current = ++current % count; @@ -2519,8 +2514,7 @@ private ToolStripItem GetNextItemHorizontal(ToolStripItem start, bool forward) { // provide negative wrap if necessary current = (--current < 0) ? count + current : current; } - ToolStripDropDown dropDown = this as ToolStripDropDown; - if (dropDown != null) + if (this is ToolStripDropDown dropDown) { if (dropDown.OwnerItem != null && dropDown.OwnerItem.IsInDesignMode) { @@ -2544,7 +2538,6 @@ private ToolStripItem GetNextItemHorizontal(ToolStripItem start, bool forward) [SuppressMessage("Microsoft.Portability", "CA1902:AvoidTestingForFloatingPointEquality")] private ToolStripItem GetNextItemVertical(ToolStripItem selectedItem, bool down) { - ToolStripItem tanWinner = null; ToolStripItem hypotenuseWinner = null; @@ -2559,8 +2552,7 @@ private ToolStripItem GetNextItemVertical(ToolStripItem selectedItem, bool down) return item; } - ToolStripDropDown dropDown = this as ToolStripDropDown; - if (dropDown != null) + if (this is ToolStripDropDown dropDown) { if (dropDown.OwnerItem != null && (dropDown.OwnerItem.IsInDesignMode || (dropDown.OwnerItem.Owner != null && dropDown.OwnerItem.Owner.IsInDesignMode))) { @@ -2945,8 +2937,7 @@ internal virtual void HandleItemClicked(ToolStripItem dismissingItem) /*if (ContainsFocus && !Focused) { RestoreFocusInternal(); }*/ - ToolStripDropDownItem item = dismissingItem as ToolStripDropDownItem; - if (item != null && !item.HasDropDownItems) + if (dismissingItem is ToolStripDropDownItem item && !item.HasDropDownItems) { KeyboardActive = false; } @@ -5471,8 +5462,7 @@ internal AccessibleObject GetChildFragment(int fragmentIndex, bool getOverflowIt ToolStripItem item = items[index]; if (item.Available && item.Alignment == ToolStripItemAlignment.Left && fragmentIndex == index) { - var controlHostItem = item as ToolStripControlHost; - if (controlHostItem != null) + if (item is ToolStripControlHost controlHostItem) { return controlHostItem.ControlAccessibilityObject; } @@ -5486,8 +5476,7 @@ internal AccessibleObject GetChildFragment(int fragmentIndex, bool getOverflowIt ToolStripItem item = owner.Items[index]; if (item.Available && item.Alignment == ToolStripItemAlignment.Right && fragmentIndex == index) { - var controlHostItem = item as ToolStripControlHost; - if (controlHostItem != null) + if (item is ToolStripControlHost controlHostItem) { return controlHostItem.ControlAccessibilityObject; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripComboBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripComboBox.cs index 2696912e85e..42b27b70f4e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripComboBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripComboBox.cs @@ -569,8 +569,7 @@ protected virtual void OnTextUpdate(EventArgs e) protected override void OnSubscribeControlEvents(Control control) { - ComboBox comboBox = control as ComboBox; - if (comboBox != null) + if (control is ComboBox comboBox) { // Please keep this alphabetized and in sync with Unsubscribe // @@ -587,8 +586,7 @@ protected override void OnSubscribeControlEvents(Control control) protected override void OnUnsubscribeControlEvents(Control control) { - ComboBox comboBox = control as ComboBox; - if (comboBox != null) + if (control is ComboBox comboBox) { // Please keep this alphabetized and in sync with Unsubscribe // @@ -640,8 +638,7 @@ private ProfessionalColorTable ColorTable { if (Owner != null) { - ToolStripProfessionalRenderer renderer = Owner.Renderer as ToolStripProfessionalRenderer; - if (renderer != null) + if (Owner.Renderer is ToolStripProfessionalRenderer renderer) { return renderer.ColorTable; } @@ -833,8 +830,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga case UnsafeNativeMethods.NavigateDirection.Parent: case UnsafeNativeMethods.NavigateDirection.PreviousSibling: case UnsafeNativeMethods.NavigateDirection.NextSibling: - var toolStripComboBoxControl = Owner as ToolStripComboBoxControl; - if (toolStripComboBoxControl != null) + if (Owner is ToolStripComboBoxControl toolStripComboBoxControl) { return toolStripComboBoxControl.Owner.AccessibilityObject.FragmentNavigate(direction); } @@ -848,8 +844,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRo { get { - var toolStripComboBoxControl = Owner as ToolStripComboBoxControl; - if (toolStripComboBoxControl != null) + if (Owner is ToolStripComboBoxControl toolStripComboBoxControl) { return toolStripComboBoxControl.Owner.Owner.AccessibilityObject; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs index d7aaf3be648..0ba9ea2efe3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs @@ -53,8 +53,7 @@ public ToolStripContainer() rightPanel.Dock = DockStyle.Right; leftPanel.Dock = DockStyle.Left; - ToolStripContainerTypedControlCollection controlCollection = Controls as ToolStripContainerTypedControlCollection; - if (controlCollection != null) + if (Controls is ToolStripContainerTypedControlCollection controlCollection) { controlCollection.AddInternal(contentPanel); controlCollection.AddInternal(leftPanel); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs index 08d60c349e6..071c2da0ab3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs @@ -870,8 +870,7 @@ protected override void OnBoundsChanged() if (control != null) { SuspendSizeSync(); - IArrangedElement element = control as IArrangedElement; - if (element == null) + if (!(control is IArrangedElement element)) { Debug.Fail("why are we here? control should not be null"); return; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs index a0e47b0f6a3..780236e276f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs @@ -1431,10 +1431,9 @@ protected override void OnItemClicked(ToolStripItemClickedEventArgs e) } finally { - ToolStripDropDownItem dismissingItem = e.ClickedItem as ToolStripDropDownItem; if (AutoClose) { - if ((dismissingItem == null) // it's not a dropdownitem + if ((!(e.ClickedItem is ToolStripDropDownItem dismissingItem)) // it's not a dropdownitem || (dismissingItem is ToolStripSplitButton && !dismissingItem.DropDown.Visible) // clicking on the split button button dismisses || !(dismissingItem.HasDropDownItems)) { // clicking on a item w/dropdown does not dismiss window @@ -2311,8 +2310,7 @@ private void DismissActiveDropDowns() if (count == 1) { // this is the most common case - ToolStripDropDown dropDown = ActiveDropDowns[0] as ToolStripDropDown; - if (dropDown != null) + if (ActiveDropDowns[0] is ToolStripDropDown dropDown) { dropDown.Visible = false; } @@ -2325,8 +2323,7 @@ private void DismissActiveDropDowns() // here as changing visibility changes the collection. for (int i = 0; i < dropDowns.Count; i++) { - ToolStripDropDown dropDown = dropDowns[i] as ToolStripDropDown; - if (dropDown != null) + if (dropDowns[i] is ToolStripDropDown dropDown) { dropDown.Visible = false; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownButton.cs index 22e52fcf663..1c727d82568 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownButton.cs @@ -191,8 +191,7 @@ protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) } if (ShowDropDownArrow) { - ToolStripDropDownButton.ToolStripDropDownButtonInternalLayout layout = InternalLayout as ToolStripDropDownButtonInternalLayout; - Rectangle dropDownArrowRect = (layout != null) ? layout.DropDownArrowRect : Rectangle.Empty; + Rectangle dropDownArrowRect = (InternalLayout is ToolStripDropDownButtonInternalLayout layout) ? layout.DropDownArrowRect : Rectangle.Empty; Color arrowColor; if (Selected && !Pressed && SystemInformation.HighContrast) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs index 31f93cb3d10..90de9ae2183 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs @@ -721,8 +721,7 @@ public void ShowDropDown() internal void ShowDropDown(bool mousePush) { ShowDropDownInternal(); - ToolStripDropDownMenu menu = dropDown as ToolStripDropDownMenu; - if (menu != null) + if (dropDown is ToolStripDropDownMenu menu) { if (!mousePush) { @@ -820,8 +819,7 @@ public override AccessibleRole Role public override void DoDefaultAction() { - ToolStripDropDownItem item = Owner as ToolStripDropDownItem; - if (item != null && item.HasDropDownItems) + if (Owner is ToolStripDropDownItem item && item.HasDropDownItems) { item.ShowDropDown(); } @@ -962,8 +960,7 @@ internal int GetChildFragmentCount() internal AccessibleObject GetChildFragment(int index) { - var toolStripAccessibleObject = owner.DropDown.AccessibilityObject as ToolStrip.ToolStripAccessibleObject; - if (toolStripAccessibleObject != null) + if (owner.DropDown.AccessibilityObject is ToolStrip.ToolStripAccessibleObject toolStripAccessibleObject) { return toolStripAccessibleObject.GetChildFragment(index); } @@ -998,9 +995,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga return null; case UnsafeNativeMethods.NavigateDirection.NextSibling: case UnsafeNativeMethods.NavigateDirection.PreviousSibling: - ToolStripDropDown dropDown = owner.Owner as ToolStripDropDown; - - if (dropDown == null) + if (!(owner.Owner is ToolStripDropDown dropDown)) { break; } @@ -1017,8 +1012,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga if (index >= 0 && index < dropDown.Items.Count) { ToolStripItem item = dropDown.Items[index]; - var controlHostItem = item as ToolStripControlHost; - if (controlHostItem != null) + if (item is ToolStripControlHost controlHostItem) { return controlHostItem.ControlAccessibilityObject; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownMenu.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownMenu.cs index f89d8a90b35..f2983fc16cf 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownMenu.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownMenu.cs @@ -387,9 +387,8 @@ private void CalculateInternalLayoutMetrics() for (int i = 0; i < Items.Count; i++) { ToolStripItem item = Items[i]; - ToolStripMenuItem menuItem = item as ToolStripMenuItem; - if (menuItem != null) + if (item is ToolStripMenuItem menuItem) { Size menuItemTextSize = menuItem.GetTextSize(); @@ -936,8 +935,7 @@ internal sealed class ToolStripDropDownLayoutEngine : FlowLayout internal override Size GetPreferredSize(IArrangedElement container, Size proposedConstraints) { Size preferredSize = base.GetPreferredSize(container, proposedConstraints); - ToolStripDropDownMenu dropDownMenu = container as ToolStripDropDownMenu; - if (dropDownMenu != null) + if (container is ToolStripDropDownMenu dropDownMenu) { preferredSize.Width = dropDownMenu.MaxItemSize.Width - dropDownMenu.PaddingToTrim; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripHighContrastRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripHighContrastRenderer.cs index a98c99eb605..73ffa771091 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripHighContrastRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripHighContrastRenderer.cs @@ -158,11 +158,10 @@ protected override void OnRenderItemBackground(ToolStripItemRenderEventArgs e) protected override void OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs e) { - ToolStripSplitButton item = e.Item as ToolStripSplitButton; Rectangle bounds = new Rectangle(Point.Empty, e.Item.Size); Graphics g = e.Graphics; - if (item != null) + if (e.Item is ToolStripSplitButton item) { Rectangle dropDownRect = item.DropDownButtonBounds; @@ -456,8 +455,7 @@ protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e) { if (FillWhenSelected) { - ToolStripButton button = e.Item as ToolStripButton; - if (button != null && button.Checked) + if (e.Item is ToolStripButton button && button.Checked) { Graphics g = e.Graphics; Rectangle bounds = new Rectangle(Point.Empty, e.Item.Size); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs index 150f35f8067..85ce049da4c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs @@ -1272,8 +1272,7 @@ public virtual Image Image if (Image != value) { StopAnimate(); - Bitmap bmp = value as Bitmap; - if (bmp != null && ImageTransparentColor != Color.Empty) + if (value is Bitmap bmp && ImageTransparentColor != Color.Empty) { if (bmp.RawFormat.Guid != ImageFormat.Icon.Guid && !ImageAnimator.CanAnimate(bmp)) { @@ -1310,8 +1309,7 @@ public Color ImageTransparentColor if (imageTransparentColor != value) { imageTransparentColor = value; - Bitmap currentImage = Image as Bitmap; - if (currentImage != null && value != Color.Empty) + if (Image is Bitmap currentImage && value != Color.Empty) { if (currentImage.RawFormat.Guid != ImageFormat.Icon.Guid && !ImageAnimator.CanAnimate(currentImage)) { @@ -2670,8 +2668,7 @@ public DragDropEffects DoDragDrop(object data, DragDropEffects allowedEffects) if (dataObject == null) { DataObject iwdata = null; - IDataObject idataObject = data as IDataObject; - if (idataObject != null) + if (data is IDataObject idataObject) { iwdata = new DataObject(idataObject); } @@ -4218,8 +4215,7 @@ IList IKeyboardToolTip.GetNeighboringToolsRectangles() Debug.Assert(i < count, "Item has a parent set but the parent doesn't own the item"); } - ToolStripDropDown dropDown = parent as ToolStripDropDown; - if (dropDown != null && dropDown.OwnerItem != null) + if (parent is ToolStripDropDown dropDown && dropDown.OwnerItem != null) { neighbors.Add(((IKeyboardToolTip)dropDown.OwnerItem).GetNativeScreenRectangle()); } @@ -4730,8 +4726,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga private AccessibleObject GetChildFragment(int index) { - var toolStripParent = Parent as ToolStrip.ToolStripAccessibleObject; - if (toolStripParent != null) + if (Parent is ToolStrip.ToolStripAccessibleObject toolStripParent) { return toolStripParent.GetChildFragment(index); } @@ -4739,18 +4734,15 @@ private AccessibleObject GetChildFragment(int index) // ToolStripOverflowButtonAccessibleObject is derived from ToolStripDropDownItemAccessibleObject // and we should not process ToolStripOverflowButton as a ToolStripDropDownItem here so check for // the ToolStripOverflowButton firstly as more specific condition. - var toolStripOverflowButtonParent = Parent as ToolStripOverflowButton.ToolStripOverflowButtonAccessibleObject; - if (toolStripOverflowButtonParent != null) + if (Parent is ToolStripOverflowButton.ToolStripOverflowButtonAccessibleObject toolStripOverflowButtonParent) { - var toolStripGrandParent = toolStripOverflowButtonParent.Parent as ToolStrip.ToolStripAccessibleObject; - if (toolStripGrandParent != null) + if (toolStripOverflowButtonParent.Parent is ToolStrip.ToolStripAccessibleObject toolStripGrandParent) { return toolStripGrandParent.GetChildFragment(index, true); } } - var dropDownItemParent = Parent as ToolStripDropDownItemAccessibleObject; - if (dropDownItemParent != null) + if (Parent is ToolStripDropDownItemAccessibleObject dropDownItemParent) { return dropDownItemParent.GetChildFragment(index); } @@ -4760,24 +4752,20 @@ private AccessibleObject GetChildFragment(int index) private int GetChildFragmentCount() { - var toolStripParent = Parent as ToolStrip.ToolStripAccessibleObject; - if (toolStripParent != null) + if (Parent is ToolStrip.ToolStripAccessibleObject toolStripParent) { return toolStripParent.GetChildFragmentCount(); } - var toolStripOverflowButtonParent = Parent as ToolStripOverflowButton.ToolStripOverflowButtonAccessibleObject; - if (toolStripOverflowButtonParent != null) + if (Parent is ToolStripOverflowButton.ToolStripOverflowButtonAccessibleObject toolStripOverflowButtonParent) { - var toolStripGrandParent = toolStripOverflowButtonParent.Parent as ToolStrip.ToolStripAccessibleObject; - if (toolStripGrandParent != null) + if (toolStripOverflowButtonParent.Parent is ToolStrip.ToolStripAccessibleObject toolStripGrandParent) { return toolStripGrandParent.GetChildOverflowFragmentCount(); } } - var dropDownItemParent = Parent as ToolStripDropDownItemAccessibleObject; - if (dropDownItemParent != null) + if (Parent is ToolStripDropDownItemAccessibleObject dropDownItemParent) { return dropDownItemParent.GetChildCount(); } @@ -4787,24 +4775,20 @@ private int GetChildFragmentCount() private int GetChildFragmentIndex() { - var toolStripParent = Parent as ToolStrip.ToolStripAccessibleObject; - if (toolStripParent != null) + if (Parent is ToolStrip.ToolStripAccessibleObject toolStripParent) { return toolStripParent.GetChildFragmentIndex(this); } - var toolStripOverflowButtonParent = Parent as ToolStripOverflowButton.ToolStripOverflowButtonAccessibleObject; - if (toolStripOverflowButtonParent != null) + if (Parent is ToolStripOverflowButton.ToolStripOverflowButtonAccessibleObject toolStripOverflowButtonParent) { - var toolStripGrandParent = toolStripOverflowButtonParent.Parent as ToolStrip.ToolStripAccessibleObject; - if (toolStripGrandParent != null) + if (toolStripOverflowButtonParent.Parent is ToolStrip.ToolStripAccessibleObject toolStripGrandParent) { return toolStripGrandParent.GetChildFragmentIndex(this); } } - var dropDownItemParent = Parent as ToolStripDropDownItemAccessibleObject; - if (dropDownItemParent != null) + if (Parent is ToolStripDropDownItemAccessibleObject dropDownItemParent) { return dropDownItemParent.GetChildFragmentIndex(this); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemCollection.cs index cfc096d59d2..fcc2f34788d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemCollection.cs @@ -238,8 +238,7 @@ private void CheckCanAddOrInsertItem(ToolStripItem value) } - ToolStripDropDown dropDown = owner as ToolStripDropDown; - if (dropDown != null) + if (owner is ToolStripDropDown dropDown) { // If we're on a dropdown, we can only add non-control host items // as we dont want anything on a dropdown to get keyboard messages in the Internet. @@ -307,8 +306,7 @@ private ArrayList FindInternal(string key, bool searchAllChildren, ToolStripItem { for (int j = 0; j < itemsToLookIn.Count; j++) { - ToolStripDropDownItem item = itemsToLookIn[j] as ToolStripDropDownItem; - if (item == null) + if (!(itemsToLookIn[j] is ToolStripDropDownItem item)) { continue; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs index 7ebc64296fa..b22d0b678d9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs @@ -284,8 +284,7 @@ internal static void NotifyMenuModeChange(bool invalidateText, bool activationCh // If we've toggled the ShowUnderlines value, we'll need to invalidate for (int i = 0; i < ToolStrips.Count; i++) { - ToolStrip toolStrip = ToolStrips[i] as ToolStrip; - if (toolStrip == null) + if (!(ToolStrips[i] is ToolStrip toolStrip)) { toolStripPruneNeeded = true; continue; @@ -359,9 +358,8 @@ internal static bool SelectNextToolStrip(ToolStrip start, bool forward) index = (forward) ? (index + 1) % totalCount : (index + totalCount - 1) % totalCount; - ToolStrip toolStrip = ToolStrips[index] as ToolStrip; - if (toolStrip == null || + if (!(ToolStrips[index] is ToolStrip toolStrip) || toolStrip == start) { continue; @@ -678,9 +676,7 @@ internal static ToolStripPanel ToolStripPanelFromPoint(Control draggedControl, P for (int i = 0; i < toolStripPanelWeakArrayList.Count; i++) { - ToolStripPanel toolStripPanel = toolStripPanelWeakArrayList[i] as ToolStripPanel; - - if (toolStripPanel != null && toolStripPanel.IsHandleCreated && toolStripPanel.Visible && + if (toolStripPanelWeakArrayList[i] is ToolStripPanel toolStripPanel && toolStripPanel.IsHandleCreated && toolStripPanel.Visible && toolStripPanel.DragBounds.Contains(toolStripPanel.PointToClient(screenLocation))) { // Ensure that we cant drag off one window to another. @@ -1093,8 +1089,7 @@ internal static void ProcessMenuKeyDown(ref Message m) { Keys keyData = (Keys)(int)m.WParam; - ToolStrip toolStrip = Control.FromHandle(m.HWnd) as ToolStrip; - if (toolStrip != null && !toolStrip.IsDropDown) + if (Control.FromHandle(m.HWnd) is ToolStrip toolStrip && !toolStrip.IsDropDown) { return; } @@ -1178,8 +1173,7 @@ private void ProcessMouseButtonPressed(IntPtr hwndMouseMessageIsFrom, int x, int UnsafeNativeMethods.MapWindowPoints(new HandleRef(activeToolStrip, hwndMouseMessageIsFrom), new HandleRef(activeToolStrip, activeToolStrip.Handle), pt, 1); if (!activeToolStrip.ClientRectangle.Contains(pt.x, pt.y)) { - ToolStripDropDown activeToolStripDropDown = activeToolStrip as ToolStripDropDown; - if (activeToolStripDropDown != null) + if (activeToolStrip is ToolStripDropDown activeToolStripDropDown) { if (!(activeToolStripDropDown.OwnerToolStrip != null @@ -1221,8 +1215,7 @@ private bool ProcessActivationChange() int countDropDowns = _inputFilterQueue.Count; for (int i = 0; i < countDropDowns; i++) { - ToolStripDropDown activeDropDown = GetActiveToolStripInternal() as ToolStripDropDown; - if (activeDropDown != null && activeDropDown.AutoClose) + if (GetActiveToolStripInternal() is ToolStripDropDown activeDropDown && activeDropDown.AutoClose) { activeDropDown.Visible = false; } @@ -1728,8 +1721,7 @@ public static bool IsShortcutDefined(Keys shortcut) { for (int i = 0; i < ToolStrips.Count; i++) { - ToolStrip t = ToolStrips[i] as ToolStrip; - if ((t != null) && t.Shortcuts.Contains(shortcut)) + if ((ToolStrips[i] is ToolStrip t) && t.Shortcuts.Contains(shortcut)) { return true; } @@ -1815,12 +1807,11 @@ internal static bool ProcessShortcut(ref Message m, Keys shortcut) // now search the toolstrips for (int i = 0; i < ToolStrips.Count; i++) { - ToolStrip toolStrip = ToolStrips[i] as ToolStrip; bool isAssociatedContextMenu = false; bool isDoublyAssignedContextMenuStrip = false; - if (toolStrip == null) + if (!(ToolStrips[i] is ToolStrip toolStrip)) { // consider prune tree... needsPrune = true; @@ -1840,12 +1831,11 @@ internal static bool ProcessShortcut(ref Message m, Keys shortcut) // button2's context menu should not be processed if button1 is the one we're processing. ToolStripDropDown dropDown = toolStrip as ToolStripDropDown; - ContextMenuStrip toplevelContextMenu = dropDown.GetFirstDropDown() as ContextMenuStrip; // If a context menu is re-used between the main menu and the // and some other control's context menu, we should go ahead and evaluate it. - if (toplevelContextMenu != null) + if (dropDown.GetFirstDropDown() is ContextMenuStrip toplevelContextMenu) { isDoublyAssignedContextMenuStrip = toplevelContextMenu.IsAssignedToDropDownItem; if (!isDoublyAssignedContextMenuStrip) @@ -1882,8 +1872,7 @@ internal static bool ProcessShortcut(ref Message m, Keys shortcut) if (rootWindowsMatch) { // Double check this is not an MDIContainer type situation... - Form mainForm = Control.FromHandle(rootWindowOfControl.Handle) as Form; - if (mainForm != null && mainForm.IsMdiContainer) + if (Control.FromHandle(rootWindowOfControl.Handle) is Form mainForm && mainForm.IsMdiContainer) { Form toolStripForm = topMostToolStrip.FindForm(); if (toolStripForm != mainForm && toolStripForm != null) @@ -1898,8 +1887,7 @@ internal static bool ProcessShortcut(ref Message m, Keys shortcut) } if (isAssociatedContextMenu || rootWindowsMatch || isDoublyAssignedContextMenuStrip) { - ToolStripMenuItem item = toolStrip.Shortcuts[shortcut] as ToolStripMenuItem; - if (item != null) + if (toolStrip.Shortcuts[shortcut] is ToolStripMenuItem item) { if (item.ProcessCmdKey(ref m, shortcut)) { @@ -1972,8 +1960,7 @@ internal static bool ProcessMenuKey(ref Message m) else if ((char)keyData == '-') { // deal with MDI system menu - Form mdiChild = toplevelControl as Form; - if (mdiChild != null && mdiChild.IsMdiChild) + if (toplevelControl is Form mdiChild && mdiChild.IsMdiChild) { if (mdiChild.WindowState == FormWindowState.Maximized) { @@ -2248,10 +2235,7 @@ private static void MergeRecursive(ToolStripItem source, ToolStripItemCollection switch (source.MergeAction) { case MergeAction.MatchOnly: - //Debug.WriteLine("matchonly"); - ToolStripDropDownItem tsddownDest = item as ToolStripDropDownItem; - ToolStripDropDownItem tsddownSrc = source as ToolStripDropDownItem; - if (tsddownDest != null && tsddownSrc != null && tsddownSrc.DropDownItems.Count != 0) + if (item is ToolStripDropDownItem tsddownDest && source is ToolStripDropDownItem tsddownSrc && tsddownSrc.DropDownItems.Count != 0) { int originalCount = tsddownSrc.DropDownItems.Count; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs index f2b305cea1a..fae0898f23f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs @@ -546,8 +546,7 @@ public Keys ShortcutKeys if (ShowShortcutKeys && IsOnDropDown) { - ToolStripDropDownMenu parent = GetCurrentParentDropDown() as ToolStripDropDownMenu; - if (parent != null) + if (GetCurrentParentDropDown() is ToolStripDropDownMenu parent) { LayoutTransaction.DoLayout(ParentInternal, this, "ShortcutKeys"); parent.AdjustSize(); @@ -578,8 +577,7 @@ public string ShortcutKeyDisplayString ClearShortcutCache(); if (ShowShortcutKeys) { - ToolStripDropDown parent = ParentInternal as ToolStripDropDown; - if (parent != null) + if (ParentInternal is ToolStripDropDown parent) { LayoutTransaction.DoLayout(parent, this, "ShortcutKeyDisplayString"); parent.AdjustSize(); @@ -614,8 +612,7 @@ public bool ShowShortcutKeys { ClearShortcutCache(); showShortcutKeys = value; - ToolStripDropDown parent = ParentInternal as ToolStripDropDown; - if (parent != null) + if (ParentInternal is ToolStripDropDown parent) { LayoutTransaction.DoLayout(parent, this, "ShortcutKeys"); parent.AdjustSize(); @@ -1191,8 +1188,7 @@ protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) bool rightToLeft = (RightToLeft == RightToLeft.Yes); - ToolStripMenuItemInternalLayout menuItemInternalLayout = InternalLayout as ToolStripMenuItemInternalLayout; - if (menuItemInternalLayout != null && menuItemInternalLayout.UseMenuLayout) + if (InternalLayout is ToolStripMenuItemInternalLayout menuItemInternalLayout && menuItemInternalLayout.UseMenuLayout) { // Support for special DropDownMenu layout @@ -1308,17 +1304,13 @@ protected internal override bool ProcessMnemonic(char charCode) /// overridden here so we scooch over when we're in the ToolStripDropDownMenu internal protected override void SetBounds(Rectangle rect) { - - ToolStripMenuItemInternalLayout internalLayout = InternalLayout as ToolStripMenuItemInternalLayout; - if (internalLayout != null && internalLayout.UseMenuLayout) + if (InternalLayout is ToolStripMenuItemInternalLayout internalLayout && internalLayout.UseMenuLayout) { - ToolStripDropDownMenu dropDownMenu = Owner as ToolStripDropDownMenu; - // Scooch over by the padding amount. The padding is added to // the ToolStripDropDownMenu to keep the non-menu item riffraff // aligned to the text rectangle. When flow layout comes through to set our position // via IArrangedElement DEFY IT! - if (dropDownMenu != null) + if (Owner is ToolStripDropDownMenu dropDownMenu) { rect.X -= dropDownMenu.Padding.Left; rect.X = Math.Max(rect.X, 0); @@ -1586,9 +1578,7 @@ internal void HandleToolStripMouseLeave(ToolStrip toolStrip) // that onmouseleave we make sure there's a selected menu item. if (toolStrip.IsDropDown && toolStrip.ActiveDropDowns.Count > 0) { - ToolStripDropDown dropDown = toolStrip.ActiveDropDowns[0] as ToolStripDropDown; - - ToolStripMenuItem menuItem = (dropDown == null) ? null : dropDown.OwnerItem as ToolStripMenuItem; + ToolStripMenuItem menuItem = (!(toolStrip.ActiveDropDowns[0] is ToolStripDropDown dropDown)) ? null : dropDown.OwnerItem as ToolStripMenuItem; if (menuItem != null && menuItem.Pressed) { menuItem.Select(); @@ -1629,8 +1619,7 @@ public bool ShowCheckMargin { get { - ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu; - if (menu != null) + if (ownerItem.Owner is ToolStripDropDownMenu menu) { return menu.ShowCheckMargin; } @@ -1641,8 +1630,7 @@ public bool ShowImageMargin { get { - ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu; - if (menu != null) + if (ownerItem.Owner is ToolStripDropDownMenu menu) { return menu.ShowImageMargin; } @@ -1671,8 +1659,7 @@ public Rectangle ArrowRectangle { if (UseMenuLayout) { - ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu; - if (menu != null) + if (ownerItem.Owner is ToolStripDropDownMenu menu) { // since menuItem.Padding isnt taken into consideration, we've got to recalc the centering of // the arrow rect per item @@ -1690,8 +1677,7 @@ public Rectangle CheckRectangle { if (UseMenuLayout) { - ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu; - if (menu != null) + if (ownerItem.Owner is ToolStripDropDownMenu menu) { Rectangle checkRectangle = menu.CheckRectangle; if (ownerItem.CheckedImage != null) @@ -1713,8 +1699,7 @@ public override Rectangle ImageRectangle { if (UseMenuLayout) { - ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu; - if (menu != null) + if (ownerItem.Owner is ToolStripDropDownMenu menu) { // since menuItem.Padding isnt taken into consideration, we've got to recalc the centering of @@ -1744,8 +1729,7 @@ public override Rectangle TextRectangle { if (UseMenuLayout) { - ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu; - if (menu != null) + if (ownerItem.Owner is ToolStripDropDownMenu menu) { return menu.TextRectangle; } @@ -1766,8 +1750,7 @@ public override Size GetPreferredSize(Size constrainingSize) { if (UseMenuLayout) { - ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu; - if (menu != null) + if (ownerItem.Owner is ToolStripDropDownMenu menu) { return menu.MaxItemSize; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs index a4d92d735d7..ece2a2ac216 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs @@ -578,9 +578,7 @@ protected override void OnControlAdded(ControlEventArgs e) protected override void OnControlRemoved(ControlEventArgs e) { - ISupportToolStripPanel controlToBeDragged = e.Control as ISupportToolStripPanel; - - if (controlToBeDragged != null) + if (e.Control is ISupportToolStripPanel controlToBeDragged) { if (controlToBeDragged.ToolStripPanelRow != null/* && controlToBeDragged.ToolStripPanelRow != owner*/) { @@ -594,8 +592,7 @@ protected override void OnLayout(LayoutEventArgs e) { if (e.AffectedComponent != ParentInternal && e.AffectedComponent as Control != null) { - ISupportToolStripPanel draggedControl = e.AffectedComponent as ISupportToolStripPanel; - if (draggedControl != null && RowsInternal.Contains(draggedControl.ToolStripPanelRow)) + if (e.AffectedComponent is ISupportToolStripPanel draggedControl && RowsInternal.Contains(draggedControl.ToolStripPanelRow)) { // there's a problem in the base onlayout... if toolstrip needs more space it talks to us // not the row that needs layout. @@ -739,9 +736,8 @@ private void JoinControls(bool forceLayout) for (int i = 0; i < controlArray.Length; i++) { int numRows = RowsInternal.Count; - ISupportToolStripPanel draggedControl = controlArray[i] as ISupportToolStripPanel; - if (draggedControl != null && draggedControl.ToolStripPanelRow != null && !draggedControl.IsCurrentlyDragging) + if (controlArray[i] is ISupportToolStripPanel draggedControl && draggedControl.ToolStripPanelRow != null && !draggedControl.IsCurrentlyDragging) { ToolStripPanelRow row = draggedControl.ToolStripPanelRow; if (row.Bounds.Contains(controlArray[i].Location)) @@ -1090,9 +1086,7 @@ public void Join(ToolStrip toolStripToDrag, Point location) internal void MoveControl(ToolStrip toolStripToDrag, Point screenLocation) { - ISupportToolStripPanel draggedControl = toolStripToDrag as ISupportToolStripPanel; - - if (draggedControl == null) + if (!(toolStripToDrag is ISupportToolStripPanel draggedControl)) { Debug.Fail("Move called on immovable object."); return; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs index 38e8b7945cd..6e835eb03ea 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs @@ -341,12 +341,9 @@ protected override void Dispose(bool disposing) protected internal virtual void OnControlAdded(Control control, int index) { - - // if previously added - remove. - ISupportToolStripPanel controlToBeDragged = control as ISupportToolStripPanel; - if (controlToBeDragged != null) + if (control is ISupportToolStripPanel controlToBeDragged) { controlToBeDragged.ToolStripPanelRow = this; } @@ -373,9 +370,8 @@ protected internal virtual void OnControlRemoved(Control control, int index) RowManager.OnControlRemoved(control, index); // if previously added - remove. - ISupportToolStripPanel controlToBeDragged = control as ISupportToolStripPanel; - if (controlToBeDragged != null && controlToBeDragged.ToolStripPanelRow == this) + if (control is ISupportToolStripPanel controlToBeDragged && controlToBeDragged.ToolStripPanelRow == this) { controlToBeDragged.ToolStripPanelRow = null; } @@ -867,8 +863,7 @@ public ToolStripPanelRowManager(ToolStripPanelRow owner) public virtual bool CanMove(ToolStrip toolStripToDrag) { - ISupportToolStripPanel raftingControl = toolStripToDrag as ISupportToolStripPanel; - if (raftingControl != null) + if (toolStripToDrag is ISupportToolStripPanel raftingControl) { if (raftingControl.Stretch) { @@ -2359,13 +2354,11 @@ public ToolStripPanel ToolStripPanel [EditorBrowsable(EditorBrowsableState.Never)] public int Add(Control value) { - ISupportToolStripPanel control = value as ISupportToolStripPanel; - if (value == null) { throw new ArgumentNullException(nameof(value)); } - if (control == null) + if (!(value is ISupportToolStripPanel control)) { throw new NotSupportedException(string.Format(SR.TypedControlCollectionShouldBeOfType, typeof(ToolStrip).Name)); } @@ -2512,8 +2505,7 @@ public void Insert(int index, Control value) { throw new ArgumentNullException(nameof(value)); } - ISupportToolStripPanel control = value as ISupportToolStripPanel; - if (control == null) + if (!(value is ISupportToolStripPanel control)) { throw new NotSupportedException(string.Format(SR.TypedControlCollectionShouldBeOfType, typeof(ToolStrip).Name)); } @@ -2555,12 +2547,10 @@ private void OnAdd(ISupportToolStripPanel controlToBeDragged, int index) if (controlToBeDragged != null) { - controlToBeDragged.ToolStripPanelRow = owner; - Control control = controlToBeDragged as Control; - if (control != null) + if (controlToBeDragged is Control control) { control.ParentInternal = owner.ToolStripPanel; owner.OnControlAdded(control, index); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProgressBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProgressBar.cs index 9c1814c12ea..beb30ebefdc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProgressBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProgressBar.cs @@ -21,8 +21,7 @@ public class ToolStripProgressBar : ToolStripControlHost public ToolStripProgressBar() : base(CreateControlInstance()) { - ToolStripProgressBarControl toolStripProgressBarControl = Control as ToolStripProgressBarControl; - if (toolStripProgressBarControl != null) + if (Control is ToolStripProgressBarControl toolStripProgressBarControl) { toolStripProgressBarControl.Owner = this; } @@ -308,8 +307,7 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) protected override void OnSubscribeControlEvents(Control control) { - ProgressBar bar = control as ProgressBar; - if (bar != null) + if (control is ProgressBar bar) { // Please keep this alphabetized and in sync with Unsubscribe // @@ -321,9 +319,7 @@ protected override void OnSubscribeControlEvents(Control control) protected override void OnUnsubscribeControlEvents(Control control) { - - ProgressBar bar = control as ProgressBar; - if (bar != null) + if (control is ProgressBar bar) { // Please keep this alphabetized and in sync with Subscribe // @@ -519,8 +515,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRo { get { - var toolStripProgressBarControl = Owner as ToolStripProgressBarControl; - if (toolStripProgressBarControl != null) + if (Owner is ToolStripProgressBarControl toolStripProgressBarControl) { return toolStripProgressBarControl.Owner.Owner.AccessibilityObject; } @@ -536,8 +531,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga case UnsafeNativeMethods.NavigateDirection.Parent: case UnsafeNativeMethods.NavigateDirection.PreviousSibling: case UnsafeNativeMethods.NavigateDirection.NextSibling: - var toolStripProgressBarControl = Owner as ToolStripProgressBarControl; - if (toolStripProgressBarControl != null) + if (Owner is ToolStripProgressBarControl toolStripProgressBarControl) { return toolStripProgressBarControl.Owner.AccessibilityObject.FragmentNavigate(direction); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRenderer.cs index 7a5cbf03e1b..07d3e0d89b7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRenderer.cs @@ -329,8 +329,7 @@ public void DrawArrow(ToolStripArrowRenderEventArgs e) { OnRenderArrow(e); - ToolStripArrowRenderEventHandler eh = Events[EventRenderArrow] as ToolStripArrowRenderEventHandler; - if (eh != null) + if (Events[EventRenderArrow] is ToolStripArrowRenderEventHandler eh) { eh(this, e); } @@ -343,8 +342,7 @@ public void DrawToolStripBackground(ToolStripRenderEventArgs e) { OnRenderToolStripBackground(e); - ToolStripRenderEventHandler eh = Events[EventRenderToolStripBackground] as ToolStripRenderEventHandler; - if (eh != null) + if (Events[EventRenderToolStripBackground] is ToolStripRenderEventHandler eh) { eh(this, e); } @@ -358,8 +356,7 @@ public void DrawToolStripBackground(ToolStripRenderEventArgs e) public void DrawGrip(ToolStripGripRenderEventArgs e) { OnRenderGrip(e); - ToolStripGripRenderEventHandler eh = Events[EventRenderGrip] as ToolStripGripRenderEventHandler; - if (eh != null) + if (Events[EventRenderGrip] is ToolStripGripRenderEventHandler eh) { eh(this, e); } @@ -373,8 +370,7 @@ public void DrawItemBackground(ToolStripItemRenderEventArgs e) { OnRenderItemBackground(e); - ToolStripItemRenderEventHandler eh = Events[EventRenderItemBackground] as ToolStripItemRenderEventHandler; - if (eh != null) + if (Events[EventRenderItemBackground] is ToolStripItemRenderEventHandler eh) { eh(this, e); } @@ -388,8 +384,7 @@ public void DrawImageMargin(ToolStripRenderEventArgs e) { OnRenderImageMargin(e); - ToolStripRenderEventHandler eh = Events[EventRenderImageMargin] as ToolStripRenderEventHandler; - if (eh != null) + if (Events[EventRenderImageMargin] is ToolStripRenderEventHandler eh) { eh(this, e); } @@ -401,8 +396,7 @@ public void DrawImageMargin(ToolStripRenderEventArgs e) public void DrawLabelBackground(ToolStripItemRenderEventArgs e) { OnRenderLabelBackground(e); - ToolStripItemRenderEventHandler eh = Events[EventRenderLabelBackground] as ToolStripItemRenderEventHandler; - if (eh != null) + if (Events[EventRenderLabelBackground] is ToolStripItemRenderEventHandler eh) { eh(this, e); } @@ -415,8 +409,7 @@ public void DrawButtonBackground(ToolStripItemRenderEventArgs e) { OnRenderButtonBackground(e); - ToolStripItemRenderEventHandler eh = Events[EventRenderButtonBackground] as ToolStripItemRenderEventHandler; - if (eh != null) + if (Events[EventRenderButtonBackground] is ToolStripItemRenderEventHandler eh) { eh(this, e); } @@ -426,8 +419,7 @@ public void DrawToolStripBorder(ToolStripRenderEventArgs e) { OnRenderToolStripBorder(e); - ToolStripRenderEventHandler eh = Events[EventRenderBorder] as ToolStripRenderEventHandler; - if (eh != null) + if (Events[EventRenderBorder] is ToolStripRenderEventHandler eh) { eh(this, e); } @@ -441,8 +433,7 @@ public void DrawDropDownButtonBackground(ToolStripItemRenderEventArgs e) { OnRenderDropDownButtonBackground(e); - ToolStripItemRenderEventHandler eh = Events[EventRenderDropDownButtonBackground] as ToolStripItemRenderEventHandler; - if (eh != null) + if (Events[EventRenderDropDownButtonBackground] is ToolStripItemRenderEventHandler eh) { eh(this, e); } @@ -455,8 +446,7 @@ public void DrawOverflowButtonBackground(ToolStripItemRenderEventArgs e) { OnRenderOverflowButtonBackground(e); - ToolStripItemRenderEventHandler eh = Events[EventRenderOverflowButtonBackground] as ToolStripItemRenderEventHandler; - if (eh != null) + if (Events[EventRenderOverflowButtonBackground] is ToolStripItemRenderEventHandler eh) { eh(this, e); } @@ -469,8 +459,7 @@ public void DrawItemImage(ToolStripItemImageRenderEventArgs e) { OnRenderItemImage(e); - ToolStripItemImageRenderEventHandler eh = Events[EventRenderItemImage] as ToolStripItemImageRenderEventHandler; - if (eh != null) + if (Events[EventRenderItemImage] is ToolStripItemImageRenderEventHandler eh) { eh(this, e); } @@ -483,8 +472,7 @@ public void DrawItemCheck(ToolStripItemImageRenderEventArgs e) { OnRenderItemCheck(e); - ToolStripItemImageRenderEventHandler eh = Events[EventRenderItemCheck] as ToolStripItemImageRenderEventHandler; - if (eh != null) + if (Events[EventRenderItemCheck] is ToolStripItemImageRenderEventHandler eh) { eh(this, e); } @@ -497,8 +485,7 @@ public void DrawItemText(ToolStripItemTextRenderEventArgs e) { OnRenderItemText(e); - ToolStripItemTextRenderEventHandler eh = Events[EventRenderItemText] as ToolStripItemTextRenderEventHandler; - if (eh != null) + if (Events[EventRenderItemText] is ToolStripItemTextRenderEventHandler eh) { eh(this, e); } @@ -511,8 +498,7 @@ public void DrawMenuItemBackground(ToolStripItemRenderEventArgs e) { OnRenderMenuItemBackground(e); - ToolStripItemRenderEventHandler eh = Events[EventRenderMenuItemBackground] as ToolStripItemRenderEventHandler; - if (eh != null) + if (Events[EventRenderMenuItemBackground] is ToolStripItemRenderEventHandler eh) { eh(this, e); } @@ -524,11 +510,9 @@ public void DrawMenuItemBackground(ToolStripItemRenderEventArgs e) /// public void DrawSplitButton(ToolStripItemRenderEventArgs e) { - OnRenderSplitButtonBackground(e); - ToolStripItemRenderEventHandler eh = Events[EventRenderSplitButtonBackground] as ToolStripItemRenderEventHandler; - if (eh != null) + if (Events[EventRenderSplitButtonBackground] is ToolStripItemRenderEventHandler eh) { eh(this, e); } @@ -540,11 +524,9 @@ public void DrawSplitButton(ToolStripItemRenderEventArgs e) /// public void DrawToolStripStatusLabelBackground(ToolStripItemRenderEventArgs e) { - OnRenderToolStripStatusLabelBackground(e); - ToolStripItemRenderEventHandler eh = Events[EventRenderToolStripStatusLabelBackground] as ToolStripItemRenderEventHandler; - if (eh != null) + if (Events[EventRenderToolStripStatusLabelBackground] is ToolStripItemRenderEventHandler eh) { eh(this, e); } @@ -554,11 +536,9 @@ public void DrawToolStripStatusLabelBackground(ToolStripItemRenderEventArgs e) // public void DrawStatusStripSizingGrip(ToolStripRenderEventArgs e) { - OnRenderStatusStripSizingGrip(e); - ToolStripRenderEventHandler eh = Events[EventRenderStatusStripSizingGrip] as ToolStripRenderEventHandler; - if (eh != null) + if (Events[EventRenderStatusStripSizingGrip] is ToolStripRenderEventHandler eh) { eh(this, e); } @@ -569,8 +549,7 @@ public void DrawStatusStripSizingGrip(ToolStripRenderEventArgs e) public void DrawSeparator(ToolStripSeparatorRenderEventArgs e) { OnRenderSeparator(e); - ToolStripSeparatorRenderEventHandler eh = Events[EventRenderSeparator] as ToolStripSeparatorRenderEventHandler; - if (eh != null) + if (Events[EventRenderSeparator] is ToolStripSeparatorRenderEventHandler eh) { eh(this, e); } @@ -579,8 +558,7 @@ public void DrawSeparator(ToolStripSeparatorRenderEventArgs e) public void DrawToolStripPanelBackground(ToolStripPanelRenderEventArgs e) { OnRenderToolStripPanelBackground(e); - ToolStripPanelRenderEventHandler eh = Events[EventRenderToolStripPanelBackground] as ToolStripPanelRenderEventHandler; - if (eh != null) + if (Events[EventRenderToolStripPanelBackground] is ToolStripPanelRenderEventHandler eh) { eh(this, e); } @@ -589,8 +567,7 @@ public void DrawToolStripPanelBackground(ToolStripPanelRenderEventArgs e) public void DrawToolStripContentPanelBackground(ToolStripContentPanelRenderEventArgs e) { OnRenderToolStripContentPanelBackground(e); - ToolStripContentPanelRenderEventHandler eh = Events[EventRenderToolStripContentPanelBackground] as ToolStripContentPanelRenderEventHandler; - if (eh != null) + if (Events[EventRenderToolStripContentPanelBackground] is ToolStripContentPanelRenderEventHandler eh) { eh(this, e); } @@ -985,13 +962,12 @@ protected virtual void OnRenderStatusStripSizingGrip(ToolStripRenderEventArgs e) } Graphics g = e.Graphics; - StatusStrip statusStrip = e.ToolStrip as StatusStrip; // we have a set of stock rectangles. Translate them over to where the grip is to be drawn // for the white set, then translate them up and right one pixel for the grey. - if (statusStrip != null) + if (e.ToolStrip is StatusStrip statusStrip) { Rectangle sizeGripBounds = statusStrip.SizeGripBounds; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRendererSwitcher.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRendererSwitcher.cs index c49fdf69414..5edb3db11d9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRendererSwitcher.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRendererSwitcher.cs @@ -160,8 +160,7 @@ private void OnControlDisposed(object sender, EventArgs e) private void OnControlVisibleChanged(object sender, EventArgs e) { - Control control = sender as Control; - if (control != null) + if (sender is Control control) { if (control.Visible) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripScrollButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripScrollButton.cs index a59e06a1a4f..d41f141a1a4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripScrollButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripScrollButton.cs @@ -177,8 +177,7 @@ public override Size GetPreferredSize(Size constrainingSize) private void Scroll() { - ToolStripDropDownMenu parent = ParentInternal as ToolStripDropDownMenu; - if (parent != null && Label.Enabled) + if (ParentInternal is ToolStripDropDownMenu parent && Label.Enabled) { parent.ScrollInternal(up); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSeparator.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSeparator.cs index 1831d767770..6ffbd0d2496 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSeparator.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSeparator.cs @@ -311,8 +311,7 @@ private bool IsVertical { parent = Owner; } - ToolStripDropDownMenu dropDownMenu = parent as ToolStripDropDownMenu; - if (dropDownMenu != null) + if (parent is ToolStripDropDownMenu dropDownMenu) { return false; } @@ -456,8 +455,7 @@ public override Size GetPreferredSize(Size constrainingSize) return new Size(ToolStrip_SEPARATORTHICKNESS, ToolStrip_SEPARATORTHICKNESS); } - ToolStripDropDownMenu dropDownMenu = parent as ToolStripDropDownMenu; - if (dropDownMenu != null) + if (parent is ToolStripDropDownMenu dropDownMenu) { return new Size(parent.Width - (parent.Padding.Horizontal - dropDownMenu.ImageMargin.Width), ToolStrip_SEPARATORTHICKNESS); } @@ -506,9 +504,7 @@ internal override bool ShouldSerializeForeColor() internal protected override void SetBounds(Rectangle rect) { - - ToolStripDropDownMenu dropDownMenu = Owner as ToolStripDropDownMenu; - if (dropDownMenu != null) + if (Owner is ToolStripDropDownMenu dropDownMenu) { // Scooch over by the padding amount. The padding is added to diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSettings.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSettings.cs index fb5042795ae..fcdfbec9e7f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSettings.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSettings.cs @@ -452,9 +452,8 @@ private struct SettingsStub public SettingsStub(ToolStrip toolStrip) { ToolStripPanelName = string.Empty; - ToolStripPanel parentPanel = toolStrip.Parent as ToolStripPanel; - if (parentPanel != null) + if (toolStrip.Parent is ToolStripPanel parentPanel) { if (!string.IsNullOrEmpty(parentPanel.Name)) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs index bd372f3da89..fcd0e5e574b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs @@ -531,8 +531,7 @@ protected virtual void OnDefaultItemChanged(EventArgs e) InvalidateSplitButtonLayout(); if (CanRaiseEvents) { - EventHandler eh = Events[EventDefaultItemChanged] as EventHandler; - if (eh != null) + if (Events[EventDefaultItemChanged] is EventHandler eh) { eh(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripTextBox.cs index 94e31a9b973..765304a40cd 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripTextBox.cs @@ -237,8 +237,7 @@ protected virtual void OnReadOnlyChanged(EventArgs e) protected override void OnSubscribeControlEvents(Control control) { - TextBox textBox = control as TextBox; - if (textBox != null) + if (control is TextBox textBox) { // Please keep this alphabetized and in sync with Unsubscribe // @@ -257,9 +256,7 @@ protected override void OnSubscribeControlEvents(Control control) protected override void OnUnsubscribeControlEvents(Control control) { - - TextBox textBox = control as TextBox; - if (textBox != null) + if (control is TextBox textBox) { // Please keep this alphabetized and in sync with Subscribe // @@ -655,8 +652,7 @@ private ProfessionalColorTable ColorTable { if (Owner != null) { - ToolStripProfessionalRenderer renderer = Owner.Renderer as ToolStripProfessionalRenderer; - if (renderer != null) + if (Owner.Renderer is ToolStripProfessionalRenderer renderer) { return renderer.ColorTable; } @@ -945,8 +941,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRo { get { - var toolStripTextBoxControl = Owner as ToolStripTextBoxControl; - if (toolStripTextBoxControl != null) + if (Owner is ToolStripTextBoxControl toolStripTextBoxControl) { return toolStripTextBoxControl.Owner.Owner.AccessibilityObject; } @@ -962,8 +957,7 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNaviga case UnsafeNativeMethods.NavigateDirection.Parent: case UnsafeNativeMethods.NavigateDirection.PreviousSibling: case UnsafeNativeMethods.NavigateDirection.NextSibling: - var toolStripTextBoxControl = Owner as ToolStripTextBoxControl; - if (toolStripTextBoxControl != null) + if (Owner is ToolStripTextBoxControl toolStripTextBoxControl) { return toolStripTextBoxControl.Owner.AccessibilityObject.FragmentNavigate(direction); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs index 3756fba1804..cc4a5da92ed 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs @@ -355,10 +355,9 @@ public bool IsBalloon // ToolTips should be shown only on active Windows. private bool IsWindowActive(IWin32Window window) { - Control windowControl = window as Control; // We want to enter in the IF block only if ShowParams does not return SW_SHOWNOACTIVATE. // for ToolStripDropDown ShowParams returns SW_SHOWNOACTIVATE, in which case we DONT want to check IsWindowActive and hence return true. - if (windowControl != null && + if (window is Control windowControl && (windowControl.ShowParams & 0xF) != NativeMethods.SW_SHOWNOACTIVATE) { IntPtr hWnd = UnsafeNativeMethods.GetActiveWindow(); @@ -780,15 +779,13 @@ private void HandleCreated(object sender, EventArgs eventargs) private void CheckNativeToolTip(Control associatedControl) { - //Wait for the Handle Creation.. if (!GetHandleCreated()) { return; } - TreeView treeView = associatedControl as TreeView; - if (treeView != null) + if (associatedControl is TreeView treeView) { if (treeView.ShowNodeToolTips) { @@ -801,8 +798,7 @@ private void CheckNativeToolTip(Control associatedControl) ((ToolBar)associatedControl).SetToolTip(this); } - TabControl tabControl = associatedControl as TabControl; - if (tabControl != null) + if (associatedControl is TabControl tabControl) { if (tabControl.ShowToolTips) { @@ -1034,15 +1030,13 @@ private void SetToolInfo(Control ctl, string caption) int ret = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.TTM_ADDTOOL, 0, tool); if (ctl is TreeView || ctl is ListView) { - TreeView tv = ctl as TreeView; - if (tv != null && tv.ShowNodeToolTips) + if (ctl is TreeView tv && tv.ShowNodeToolTips) { return; } else { - ListView lv = ctl as ListView; - if (lv != null && lv.ShowItemToolTips) + if (ctl is ListView lv && lv.ShowItemToolTips) { return; } @@ -1122,7 +1116,6 @@ internal void DestroyHandle() private void DestroyRegion(Control ctl) { - // when the toplevelControl is a form and is Modal, the Handle of the tooltip is releasedbefore we come here. // In such a case the tool wont get deleted from the tooltip. // So we dont check "Handle" in the handlesCreate but check it only foe Non-Nodal dialogs later @@ -1132,8 +1125,7 @@ private void DestroyRegion(Control ctl) && topLevelControl.IsHandleCreated && !isDisposing; - Form topForm = topLevelControl as Form; - if (topForm == null || (topForm != null && !topForm.Modal)) + if (!(topLevelControl is Form topForm) || (topForm != null && !topForm.Modal)) { handlesCreated = handlesCreated && GetHandleCreated(); } @@ -1174,8 +1166,7 @@ protected override void Dispose(bool disposing) //Unhook the DeactiveEvent... // Lets find the Form for associated Control ... // and hook up to the Deactivated event to Hide the Shown tooltip - Form baseFrom = TopLevelControl as Form; - if (baseFrom != null) + if (TopLevelControl is Form baseFrom) { baseFrom.Deactivate -= new EventHandler(BaseFormDeactivate); } @@ -1261,15 +1252,13 @@ private NativeMethods.TOOLINFO_TOOLTIP GetTOOLINFO(Control ctl, string caption, if (ctl is TreeView || ctl is ListView) { - TreeView tv = ctl as TreeView; - if (tv != null && tv.ShowNodeToolTips) + if (ctl is TreeView tv && tv.ShowNodeToolTips) { ti.lpszText = NativeMethods.InvalidIntPtr; } else { - ListView lv = ctl as ListView; - if (lv != null && lv.ShowItemToolTips) + if (ctl is ListView lv && lv.ShowItemToolTips) { ti.lpszText = NativeMethods.InvalidIntPtr; } @@ -1680,8 +1669,7 @@ private void ShowTooltip(string text, IWin32Window win, int duration) throw new ArgumentNullException(nameof(win)); } - Control associatedControl = win as Control; - if (associatedControl != null) + if (win is Control associatedControl) { NativeMethods.RECT r = new NativeMethods.RECT(); UnsafeNativeMethods.GetWindowRect(new HandleRef(associatedControl, associatedControl.Handle), ref r); @@ -2135,8 +2123,7 @@ public void Hide(IWin32Window win) StopTimer(); //Check if the passed in IWin32Window is a Control... - Control tool = win as Control; - if (tool == null) + if (!(win is Control tool)) { owners.Remove(win.Handle); } @@ -2408,8 +2395,7 @@ private void WmMove() } // Treeview handles its own ToolTips. - TreeView treeView = win as TreeView; - if (treeView != null) + if (win is TreeView treeView) { if (treeView.ShowNodeToolTips) { @@ -2501,7 +2487,6 @@ private void WmShow() if (ret != 0) { - IWin32Window win = (IWin32Window)owners[ti.hwnd]; if (win == null) { @@ -2519,8 +2504,7 @@ private void WmShow() PopupEventArgs e = new PopupEventArgs(win, toolControl, IsBalloon, currentTooltipSize); OnPopup(e); - DataGridView dataGridView = toolControl as DataGridView; - if (dataGridView != null && dataGridView.CancelToolTipPopup(this)) + if (toolControl is DataGridView dataGridView && dataGridView.CancelToolTipPopup(this)) { // The dataGridView cancelled the tooltip. e.Cancel = true; @@ -2641,8 +2625,7 @@ private unsafe void WmWindowPosChanging(ref Message m) } // Treeview handles its own ToolTips. - TreeView treeView = win as TreeView; - if (treeView != null) + if (win is TreeView treeView) { if (treeView.ShowNodeToolTips) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolstripProfessionalRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolstripProfessionalRenderer.cs index 46de954ff51..01026677383 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolstripProfessionalRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolstripProfessionalRenderer.cs @@ -240,9 +240,8 @@ protected override void OnRenderDropDownButtonBackground(ToolStripItemRenderEven return; } - ToolStripDropDownItem item = e.Item as ToolStripDropDownItem; - if (item != null && item.Pressed && item.HasDropDownItems) + if (e.Item is ToolStripDropDownItem item && item.Pressed && item.HasDropDownItems) { Rectangle bounds = new Rectangle(Point.Empty, item.Size); @@ -273,10 +272,9 @@ protected override void OnRenderSplitButtonBackground(ToolStripItemRenderEventAr return; } - ToolStripSplitButton item = e.Item as ToolStripSplitButton; Graphics g = e.Graphics; - if (item != null) + if (e.Item is ToolStripSplitButton item) { Rectangle bounds = new Rectangle(Point.Empty, item.Size); @@ -769,8 +767,7 @@ protected override void OnRenderItemImage(ToolStripItemImageRenderEventArgs e) ToolStripMenuItem item = e.Item as ToolStripMenuItem; if (item.CheckState != CheckState.Unchecked) { - ToolStripDropDownMenu dropDownMenu = item.ParentInternal as ToolStripDropDownMenu; - if (dropDownMenu != null && !dropDownMenu.ShowCheckMargin && dropDownMenu.ShowImageMargin) + if (item.ParentInternal is ToolStripDropDownMenu dropDownMenu && !dropDownMenu.ShowCheckMargin && dropDownMenu.ShowImageMargin) { RenderCheckBackground(e); } @@ -1213,10 +1210,9 @@ private void RenderToolStripDropDownBackground(ToolStripRenderEventArgs e) private void RenderToolStripDropDownBorder(ToolStripRenderEventArgs e) { - ToolStripDropDown toolStripDropDown = e.ToolStrip as ToolStripDropDown; Graphics g = e.Graphics; - if (toolStripDropDown != null) + if (e.ToolStrip is ToolStripDropDown toolStripDropDown) { Rectangle bounds = new Rectangle(Point.Empty, toolStripDropDown.Size); @@ -1506,8 +1502,7 @@ private void RenderSeparatorInternal(Graphics g, ToolStripItem item, Rectangle b else { // offset after the image margin - ToolStripDropDownMenu dropDownMenu = item.GetCurrentParent() as ToolStripDropDownMenu; - if (dropDownMenu != null) + if (item.GetCurrentParent() is ToolStripDropDownMenu dropDownMenu) { if (dropDownMenu.RightToLeft == RightToLeft.No) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs index 4faa26ea0c7..c51d0c6358e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs @@ -921,8 +921,7 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) RecreateHandle(); } - EventHandler eh = Events[EVENT_RIGHTTOLEFTLAYOUTCHANGED] as EventHandler; - if (eh != null) + if (Events[EVENT_RIGHTTOLEFTLAYOUTCHANGED] is EventHandler eh) { eh(this, e); } @@ -951,8 +950,7 @@ protected override void OnMouseWheel(MouseEventArgs e) { base.OnMouseWheel(e); - HandledMouseEventArgs hme = e as HandledMouseEventArgs; - if (hme != null) + if (e is HandledMouseEventArgs hme) { if (hme.Handled) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewImageIndexConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewImageIndexConverter.cs index 82cfff38701..7a0d79f0698 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewImageIndexConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewImageIndexConverter.cs @@ -36,9 +36,7 @@ protected override bool IncludeNoneAsStandardValue /// public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - - string strValue = value as string; - if (strValue != null) + if (value is string strValue) { if (string.Compare(strValue, SR.toStringDefault, true, culture) == 0) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewImageKeyConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewImageKeyConverter.cs index 268df8b0b5d..d9e5a182a5b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewImageKeyConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewImageKeyConverter.cs @@ -42,8 +42,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul } else { - string strValue = value as string; - if (strValue != null && (strValue.Length == 0)) + if (value is string strValue && (strValue.Length == 0)) { return SR.toStringDefault; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs index 3c20157657f..6451ec06b70 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs @@ -1004,8 +1004,7 @@ protected override void OnMouseUp(MouseEventArgs mevent) protected override void OnMouseWheel(MouseEventArgs e) { base.OnMouseWheel(e); - HandledMouseEventArgs hme = e as HandledMouseEventArgs; - if (hme != null) + if (e is HandledMouseEventArgs hme) { if (hme.Handled) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs index 421da3cb962..1891f311cb6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs @@ -1331,8 +1331,7 @@ internal ContainerControl FindContainerControlInternal() ContainerControl cc = null; for (Control control = this; control != null; control = control.ParentInternal) { - ContainerControl tempCC = control as ContainerControl; - if (tempCC != null) + if (control is ContainerControl tempCC) { cc = tempCC; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs index 70231489da1..cd89aec65ef 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs @@ -105,15 +105,13 @@ int UnsafeNativeMethods.IOleInPlaceFrame.SetActiveObject(UnsafeNativeMethods.IOl return NativeMethods.S_OK; } WebBrowserBase ctl = null; - UnsafeNativeMethods.IOleObject oleObject = pActiveObject as UnsafeNativeMethods.IOleObject; - if (oleObject != null) + if (pActiveObject is UnsafeNativeMethods.IOleObject oleObject) { UnsafeNativeMethods.IOleClientSite clientSite = null; try { clientSite = oleObject.GetClientSite(); - WebBrowserSiteBase webBrowserSiteBase = clientSite as WebBrowserSiteBase; - if (webBrowserSiteBase != null) + if (clientSite is WebBrowserSiteBase webBrowserSiteBase) { ctl = webBrowserSiteBase.GetAXHost(); } @@ -196,8 +194,7 @@ private void ListAXControls(ArrayList list, bool fuseOcx) for (int i = 0; i < ctls.Length; i++) { Control ctl = ctls[i]; - WebBrowserBase webBrowserBase = ctl as WebBrowserBase; - if (webBrowserBase != null) + if (ctl is WebBrowserBase webBrowserBase) { if (fuseOcx) { @@ -342,8 +339,7 @@ private bool RegisterControl(WebBrowserBase ctl) private void OnComponentRemoved(object sender, ComponentEventArgs e) { - Control c = e.Component as Control; - if (sender == assocContainer && c != null) + if (sender == assocContainer && e.Component is Control c) { RemoveControl(c); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WindowsFormsSynchronizationContext.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WindowsFormsSynchronizationContext.cs index 2928ce120ab..3c0f5b9c363 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WindowsFormsSynchronizationContext.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WindowsFormsSynchronizationContext.cs @@ -174,8 +174,7 @@ internal static void Uninstall(bool turnOffAutoInstall) { if (AutoInstall) { - WindowsFormsSynchronizationContext winFormsSyncContext = AsyncOperationManager.SynchronizationContext as WindowsFormsSynchronizationContext; - if (winFormsSyncContext != null) + if (AsyncOperationManager.SynchronizationContext is WindowsFormsSynchronizationContext winFormsSyncContext) { try { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/formatter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/formatter.cs index 2b0a62e68c1..168a9cbe355 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/formatter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/formatter.cs @@ -403,9 +403,7 @@ private static object ChangeType(object value, Type type, IFormatProvider format /// private static bool EqualsFormattedNullValue(object value, object formattedNullValue, IFormatProvider formatInfo) { - string formattedNullValueStr = formattedNullValue as string; - string valueStr = value as string; - if (formattedNullValueStr != null && valueStr != null) + if (formattedNullValue is string formattedNullValueStr && value is string valueStr) { // Use same optimization as in WindowsFormsUtils.SafeCompareStrings(...). This addresses if (formattedNullValueStr.Length != valueStr.Length) @@ -551,8 +549,7 @@ private static Type NullableUnwrap(Type type) /// private static TypeConverter NullableUnwrap(TypeConverter typeConverter) { - NullableConverter nullableConverter = typeConverter as NullableConverter; - return (nullableConverter != null) ? nullableConverter.UnderlyingTypeConverter : typeConverter; + return (typeConverter is NullableConverter nullableConverter) ? nullableConverter.UnderlyingTypeConverter : typeConverter; } public static object GetDefaultDataSourceNullValue(Type type) diff --git a/src/System.Windows.Forms/src/misc/CompatibleIComparer.cs b/src/System.Windows.Forms/src/misc/CompatibleIComparer.cs index d493da3f2d8..2cccc498fe4 100644 --- a/src/System.Windows.Forms/src/misc/CompatibleIComparer.cs +++ b/src/System.Windows.Forms/src/misc/CompatibleIComparer.cs @@ -47,8 +47,7 @@ bool IEqualityComparer.Equals(object a, object b) public virtual int GetHashCode(object o) { - string obj = o as string; - if (obj == null) + if (!(o is string obj)) { return o.GetHashCode(); } diff --git a/src/System.Windows.Forms/src/misc/GDI/DeviceContexts.cs b/src/System.Windows.Forms/src/misc/GDI/DeviceContexts.cs index 53632d01ad0..f025af156c2 100644 --- a/src/System.Windows.Forms/src/misc/GDI/DeviceContexts.cs +++ b/src/System.Windows.Forms/src/misc/GDI/DeviceContexts.cs @@ -60,9 +60,7 @@ internal static void AddDeviceContext(DeviceContext dc) private static void OnDcDisposing(object sender, EventArgs e) { - DeviceContext dc = sender as DeviceContext; - - if (dc != null) + if (sender is DeviceContext dc) { dc.Disposing -= new EventHandler(OnDcDisposing); RemoveDeviceContext(dc); @@ -88,8 +86,7 @@ internal static bool IsFontInUse(WindowsFont wf) for (int i = 0; i < activeDeviceContexts.Count; i++) { - DeviceContext dc = activeDeviceContexts[i] as DeviceContext; - if (dc != null && (dc.ActiveFont == wf || dc.IsFontOnContextStack(wf))) + if (activeDeviceContexts[i] is DeviceContext dc && (dc.ActiveFont == wf || dc.IsFontOnContextStack(wf))) { return true; } diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs index 7b8b3b6b611..f42c9103a66 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs @@ -332,9 +332,7 @@ internal void Dispose(bool disposing) /// public override bool Equals(object font) { - WindowsFont winFont = font as WindowsFont; - - if (winFont == null) + if (!(font is WindowsFont winFont)) { return false; } diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics.cs index 482bfd8b0bb..508d77c4478 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics.cs @@ -171,9 +171,7 @@ public static WindowsGraphics FromGraphics(Graphics g, ApplyGraphicsProperties p if ((properties & ApplyGraphicsProperties.TranslateTransform) != 0 || (properties & ApplyGraphicsProperties.Clipping) != 0) { - object[] data = g.GetContextInfo() as object[]; - - if (data != null && data.Length == 2) + if (g.GetContextInfo() is object[] data && data.Length == 2) { clipRgn = data[0] as Region; worldTransf = data[1] as Matrix; diff --git a/src/System.Windows.Forms/src/misc/ImageListUtils.cs b/src/System.Windows.Forms/src/misc/ImageListUtils.cs index 4215cd296e9..e7a4a8ebbd8 100644 --- a/src/System.Windows.Forms/src/misc/ImageListUtils.cs +++ b/src/System.Windows.Forms/src/misc/ImageListUtils.cs @@ -23,8 +23,7 @@ public static PropertyDescriptor GetImageListProperty(PropertyDescriptor current PropertyDescriptor imageListProp = null; object parentInstance = instance; - RelatedImageListAttribute relILAttr = currentComponent.Attributes[typeof(RelatedImageListAttribute)] as RelatedImageListAttribute; - if (relILAttr != null) + if (currentComponent.Attributes[typeof(RelatedImageListAttribute)] is RelatedImageListAttribute relILAttr) { string[] pathInfo = relILAttr.RelatedImageList.Split('.'); for (int i = 0; i < pathInfo.Length; i++) diff --git a/src/System.Windows.Forms/src/misc/InvariantComparer.cs b/src/System.Windows.Forms/src/misc/InvariantComparer.cs index 2b459412083..0162bd0ee63 100644 --- a/src/System.Windows.Forms/src/misc/InvariantComparer.cs +++ b/src/System.Windows.Forms/src/misc/InvariantComparer.cs @@ -21,9 +21,7 @@ internal InvariantComparer() public int Compare(object a, object b) { - string sa = a as string; - string sb = b as string; - if (sa != null && sb != null) + if (a is string sa && b is string sb) { return m_compareInfo.Compare(sa, sb); } diff --git a/src/System.Windows.Forms/src/misc/WeakHashtable.cs b/src/System.Windows.Forms/src/misc/WeakHashtable.cs index 48cf42bf70b..08f150d184d 100644 --- a/src/System.Windows.Forms/src/misc/WeakHashtable.cs +++ b/src/System.Windows.Forms/src/misc/WeakHashtable.cs @@ -96,8 +96,7 @@ private void ScavengeKeys() ArrayList cleanupList = null; foreach (object o in Keys) { - WeakReference wr = o as WeakReference; - if (wr != null && !wr.IsAlive) + if (o is WeakReference wr && !wr.IsAlive) { if (cleanupList == null) { @@ -131,10 +130,7 @@ bool IEqualityComparer.Equals(object x, object y) } if (y != null && x.GetHashCode() == y.GetHashCode()) { - WeakReference wX = x as WeakReference; - WeakReference wY = y as WeakReference; - - if (wX != null) + if (x is WeakReference wX) { if (!wX.IsAlive) { @@ -143,7 +139,7 @@ bool IEqualityComparer.Equals(object x, object y) x = wX.Target; } - if (wY != null) + if (y is WeakReference wY) { if (!wY.IsAlive) { From 4e6110bbc23a7047ac2601b9343852ecbf3d3722 Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Fri, 24 May 2019 12:30:48 -0700 Subject: [PATCH 17/27] remove all instances of IDE0020 warning - use pattern matching (as if becomes is) --- .../ComponentModel/Design/ArrayEditor.cs | 3 +-- .../System/Windows/Forms/Design/DockEditor.cs | 4 +--- .../DesignerSerializationManager.cs | 3 +-- .../src/System/Windows/Forms/AxHost.cs | 7 ++----- .../src/System/Windows/Forms/ComboBox.cs | 3 +-- .../COM2ICategorizePropertiesHandler.cs | 4 +--- .../COM2IPerPropertyBrowsingHandler.cs | 4 +--- .../COM2IProvidePropertyBuilderHandler.cs | 3 +-- .../COM2IVsPerPropertyBrowsingHandler.cs | 21 ++++++------------- .../COM2Interop/COM2TypeInfoProcessor.cs | 9 +++----- .../src/System/Windows/Forms/Control.cs | 3 +-- .../src/System/Windows/Forms/DataGrid.cs | 9 +++----- .../Windows/Forms/DataGridViewCheckBoxCell.cs | 9 +++----- .../src/System/Windows/Forms/Menu.cs | 3 +-- .../PropertyDescriptorGridEntry.cs | 3 +-- .../src/System/Windows/Forms/RadioButton.cs | 3 +-- .../Windows/Forms/RelatedCurrencyManager.cs | 3 +-- .../src/System/Windows/Forms/Screen.cs | 3 +-- .../Windows/Forms/SelectionRangeConverter.cs | 3 +-- .../src/System/Windows/Forms/formatter.cs | 3 +-- 20 files changed, 32 insertions(+), 71 deletions(-) diff --git a/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/ArrayEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/ArrayEditor.cs index 96f37093d15..f1eb755214a 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/ArrayEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/ComponentModel/Design/ArrayEditor.cs @@ -30,9 +30,8 @@ public ArrayEditor(Type type) : base(type) /// protected override object[] GetItems(object editValue) { - if (editValue is Array) + if (editValue is Array valueArray) { - Array valueArray = (Array)editValue; object[] items = new object[valueArray.GetLength(0)]; Array.Copy(valueArray, items, items.Length); return items; diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/DockEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/DockEditor.cs index f16def90c12..0d720aae593 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/DockEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/DockEditor.cs @@ -380,10 +380,8 @@ public void Start(IWindowsFormsEditorService edSvc, object value) this.edSvc = edSvc; Value = value; - if (value is DockStyle) + if (value is DockStyle dock) { - DockStyle dock = (DockStyle)value; - none.Checked = false; top.Checked = false; left.Checked = false; diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs index 01147c68b9f..7d991f9390f 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs @@ -423,9 +423,8 @@ public object GetSerializer(Type objectType, Type serializerType) AttributeCollection attributes = TypeDescriptor.GetAttributes(objectType); foreach (Attribute attr in attributes) { - if (attr is DesignerSerializerAttribute) + if (attr is DesignerSerializerAttribute da) { - DesignerSerializerAttribute da = (DesignerSerializerAttribute)attr; string typeName = da.SerializerBaseTypeName; // This serializer must support the correct base type or we're not interested. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs index c5d86af1887..da83f3f2068 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs @@ -3934,10 +3934,8 @@ public ConnectionPointCookie(object source, object sink, Type eventInterface) internal ConnectionPointCookie(object source, object sink, Type eventInterface, bool throwException) { - if (source is UnsafeNativeMethods.IConnectionPointContainer) + if (source is UnsafeNativeMethods.IConnectionPointContainer cpc) { - UnsafeNativeMethods.IConnectionPointContainer cpc = (UnsafeNativeMethods.IConnectionPointContainer)source; - try { Guid tmp = eventInterface.GUID; @@ -6594,9 +6592,8 @@ int UnsafeNativeMethods.IOleInPlaceFrame.SetActiveObject(UnsafeNativeMethods.IOl return NativeMethods.S_OK; } AxHost ctl = null; - if (pActiveObject is UnsafeNativeMethods.IOleObject) + if (pActiveObject is UnsafeNativeMethods.IOleObject oleObject) { - UnsafeNativeMethods.IOleObject oleObject = (UnsafeNativeMethods.IOleObject)pActiveObject; UnsafeNativeMethods.IOleClientSite clientSite = null; try { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs index bba8103c8ea..490b5fe606d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs @@ -5610,9 +5610,8 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment ElementProvide if (systemIAccessible != null) { object result = systemIAccessible.accHitTest((int)x, (int)y); - if (result is int) + if (result is int childId) { - int childId = (int)result; return GetChildFragment(childId - 1); } else diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ICategorizePropertiesHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ICategorizePropertiesHandler.cs index e7f3c449890..719849eb3b7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ICategorizePropertiesHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ICategorizePropertiesHandler.cs @@ -29,10 +29,8 @@ private string GetCategoryFromObject(object obj, int dispid) return null; } - if (obj is NativeMethods.ICategorizeProperties) + if (obj is NativeMethods.ICategorizeProperties catObj) { - NativeMethods.ICategorizeProperties catObj = (NativeMethods.ICategorizeProperties)obj; - try { int categoryID = 0; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs index 519509821ee..deb9891fd14 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs @@ -120,10 +120,8 @@ private void OnGetDisplayValue(Com2PropertyDescriptor sender, GetNameItemEvent g private void OnGetTypeConverterAndTypeEditor(Com2PropertyDescriptor sender, GetTypeConverterAndTypeEditorEvent gveevent) { - if (sender.TargetObject is NativeMethods.IPerPropertyBrowsing) + if (sender.TargetObject is NativeMethods.IPerPropertyBrowsing ppb) { - NativeMethods.IPerPropertyBrowsing ppb = (NativeMethods.IPerPropertyBrowsing)sender.TargetObject; - bool hasStrings = false; // check for enums diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IProvidePropertyBuilderHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IProvidePropertyBuilderHandler.cs index 70f82cd8d07..12f4740a272 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IProvidePropertyBuilderHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IProvidePropertyBuilderHandler.cs @@ -94,9 +94,8 @@ private void OnGetTypeConverterAndTypeEditor(Com2PropertyDescriptor sender, GetT { object target = sender.TargetObject; - if (target is NativeMethods.IProvidePropertyBuilder) + if (target is NativeMethods.IProvidePropertyBuilder propBuilder) { - NativeMethods.IProvidePropertyBuilder propBuilder = (NativeMethods.IProvidePropertyBuilder)target; int[] pctlBldType = new int[1]; string guidString = null; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IVsPerPropertyBrowsingHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IVsPerPropertyBrowsingHandler.cs index 355c33e9fd7..63e5fdc067f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IVsPerPropertyBrowsingHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IVsPerPropertyBrowsingHandler.cs @@ -98,10 +98,8 @@ private void OnGetBaseAttributes(Com2PropertyDescriptor sender, GetAttributesEve private void OnGetDynamicAttributes(Com2PropertyDescriptor sender, GetAttributesEvent attrEvent) { - if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing) + if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing vsObj) { - NativeMethods.IVsPerPropertyBrowsing vsObj = (NativeMethods.IVsPerPropertyBrowsing)sender.TargetObject; - int hr = NativeMethods.S_OK; // we want to avoid allowing clients to force a bad property to be browsable, @@ -136,9 +134,8 @@ private void OnGetDynamicAttributes(Com2PropertyDescriptor sender, GetAttributes private void OnCanResetPropertyValue(Com2PropertyDescriptor sender, GetBoolValueEvent boolEvent) { - if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing) + if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing target) { - NativeMethods.IVsPerPropertyBrowsing target = (NativeMethods.IVsPerPropertyBrowsing)sender.TargetObject; bool canReset = boolEvent.Value; int hr = target.CanResetPropertyValue(sender.DISPID, ref canReset); @@ -155,9 +152,8 @@ private void OnCanResetPropertyValue(Com2PropertyDescriptor sender, GetBoolValue /// private void OnGetDisplayName(Com2PropertyDescriptor sender, GetNameItemEvent nameItem) { - if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing) + if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing vsObj) { - NativeMethods.IVsPerPropertyBrowsing vsObj = (NativeMethods.IVsPerPropertyBrowsing)sender.TargetObject; // get the localized name, if applicable string[] pNameString = new string[1]; @@ -175,9 +171,8 @@ private void OnGetDisplayName(Com2PropertyDescriptor sender, GetNameItemEvent na /// private void OnGetIsReadOnly(Com2PropertyDescriptor sender, GetBoolValueEvent gbvevent) { - if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing) + if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing vsObj) { - NativeMethods.IVsPerPropertyBrowsing vsObj = (NativeMethods.IVsPerPropertyBrowsing)sender.TargetObject; // should we make this read only? bool pfResult = false; @@ -222,11 +217,8 @@ private void OnGetTypeConverterAndTypeEditor(Com2PropertyDescriptor sender, GetT private void OnResetPropertyValue(Com2PropertyDescriptor sender, EventArgs e) { - if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing) + if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing target) { - - - NativeMethods.IVsPerPropertyBrowsing target = (NativeMethods.IVsPerPropertyBrowsing)sender.TargetObject; int dispid = sender.DISPID; bool canReset = false; int hr = target.CanResetPropertyValue(dispid, ref canReset); @@ -241,9 +233,8 @@ private void OnResetPropertyValue(Com2PropertyDescriptor sender, EventArgs e) private void OnShouldSerializeValue(Com2PropertyDescriptor sender, GetBoolValueEvent gbvevent) { - if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing) + if (sender.TargetObject is NativeMethods.IVsPerPropertyBrowsing vsObj) { - NativeMethods.IVsPerPropertyBrowsing vsObj = (NativeMethods.IVsPerPropertyBrowsing)sender.TargetObject; // by default we say it's default bool pfResult = true; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs index 137976128fa..cc45518a612 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs @@ -80,9 +80,8 @@ public static UnsafeNativeMethods.ITypeInfo FindTypeInfo(object obj, bool wantCo if (wantCoClass == (i == 0)) { - if (obj is NativeMethods.IProvideClassInfo) + if (obj is NativeMethods.IProvideClassInfo pProvideClassInfo) { - NativeMethods.IProvideClassInfo pProvideClassInfo = (NativeMethods.IProvideClassInfo)obj; try { pTypeInfo = pProvideClassInfo.GetClassInfo(); @@ -94,9 +93,8 @@ public static UnsafeNativeMethods.ITypeInfo FindTypeInfo(object obj, bool wantCo } else { - if (obj is UnsafeNativeMethods.IDispatch) + if (obj is UnsafeNativeMethods.IDispatch iDispatch) { - UnsafeNativeMethods.IDispatch iDispatch = (UnsafeNativeMethods.IDispatch)obj; try { pTypeInfo = iDispatch.GetTypeInfo(0, SafeNativeMethods.GetThreadLCID()); @@ -123,9 +121,8 @@ public static UnsafeNativeMethods.ITypeInfo[] FindTypeInfos(object obj, bool wan int n = 0; UnsafeNativeMethods.ITypeInfo temp = null; - if (obj is NativeMethods.IProvideMultipleClassInfo) + if (obj is NativeMethods.IProvideMultipleClassInfo pCI) { - NativeMethods.IProvideMultipleClassInfo pCI = (NativeMethods.IProvideMultipleClassInfo)obj; if (!NativeMethods.Succeeded(pCI.GetMultiTypeInfoCount(ref n)) || n == 0) { n = 0; 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 d1bdca66e3c..9c7711a0564 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs @@ -5802,9 +5802,8 @@ internal static void CheckParentingCycle(Control bottom, Control toFind) if (lastParent != null) { - if (lastParent is Form) + if (lastParent is Form f) { - Form f = (Form)lastParent; for (Form form = f; form != null; form = form.OwnerInternal) { lastOwner = form; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs index 31cd5320fc4..2cb1fedaf3c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs @@ -7582,9 +7582,8 @@ public bool IsExpanded(int rowNumber) DataGridRow row = localGridRows[rowNumber]; - if (row is DataGridRelationshipRow) + if (row is DataGridRelationshipRow relRow) { - DataGridRelationshipRow relRow = (DataGridRelationshipRow)row; return relRow.Expanded; } else @@ -10177,9 +10176,8 @@ private void SetRowExpansionState(int row, bool expanded) } } } - else if (localGridRows[row] is DataGridRelationshipRow) + else if (localGridRows[row] is DataGridRelationshipRow expandableRow) { - DataGridRelationshipRow expandableRow = (DataGridRelationshipRow)localGridRows[row]; if (expandableRow.Expanded != expanded) { // we need to reposition the edit control @@ -10699,9 +10697,8 @@ public HitTestType Type /// public override bool Equals(object value) { - if (value is HitTestInfo) + if (value is HitTestInfo ci) { - HitTestInfo ci = (HitTestInfo)value; return (type == ci.type && row == ci.row && col == ci.col); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs index d39bb9ba26e..1710868c4c5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs @@ -645,9 +645,8 @@ protected override object GetFormattedValue(object value, object ret = base.GetFormattedValue(value, rowIndex, ref cellStyle, valueTypeConverter, formattedValueTypeConverter, context); if (ret != null && (context & DataGridViewDataErrorContexts.ClipboardContent) != 0) { - if (ret is bool) + if (ret is bool retBool) { - bool retBool = (bool)ret; if (retBool) { return string.Format(ThreeState ? SR.DataGridViewCheckBoxCell_ClipboardChecked : SR.DataGridViewCheckBoxCell_ClipboardTrue); @@ -657,9 +656,8 @@ protected override object GetFormattedValue(object value, return string.Format(ThreeState ? SR.DataGridViewCheckBoxCell_ClipboardUnchecked : SR.DataGridViewCheckBoxCell_ClipboardFalse); } } - else if (ret is CheckState) + else if (ret is CheckState retCheckState) { - CheckState retCheckState = (CheckState)ret; if (retCheckState == CheckState.Checked) { return string.Format(ThreeState ? SR.DataGridViewCheckBoxCell_ClipboardChecked : SR.DataGridViewCheckBoxCell_ClipboardTrue); @@ -1733,9 +1731,8 @@ public override AccessibleStates State return AccessibleStates.Indeterminate | base.State; } } - else if (((DataGridViewCheckBoxCell)Owner).EditedFormattedValue is bool) + else if (((DataGridViewCheckBoxCell)Owner).EditedFormattedValue is bool state) { - bool state = (bool)(((DataGridViewCheckBoxCell)Owner).EditedFormattedValue); if (state) { return AccessibleStates.Checked | base.State; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs index ba7da96b0d7..fdc75c8c7fb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs @@ -909,9 +909,8 @@ public virtual int Add(int index, MenuItem item) // First check that we're not adding ourself, i.e. walk // the parent chain for equality - if (owner is MenuItem) + if (owner is MenuItem parent) { - MenuItem parent = (MenuItem)owner; while (parent != null) { if (parent.Equals(item)) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs index a2f92eeca9c..8dc3a9dad1b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs @@ -1313,9 +1313,8 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul { if (destinationType == typeof(string)) { - if (value is Exception) + if (value is Exception ex) { - Exception ex = (Exception)value; if (ex.InnerException != null) { ex = ex.InnerException; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs index e8720c35287..d1f70636db9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs @@ -561,9 +561,8 @@ private void WipeTabStops(bool tabbedInto) for (int i = 0; i < children.Count; i++) { Control ctl = children[i]; - if (ctl is RadioButton) + if (ctl is RadioButton button) { - RadioButton button = (RadioButton)ctl; if (!tabbedInto) { button.firstfocus = false; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RelatedCurrencyManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RelatedCurrencyManager.cs index af9008d1699..d961351185a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RelatedCurrencyManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RelatedCurrencyManager.cs @@ -159,9 +159,8 @@ private void ParentManager_CurrentItemChanged(object sender, EventArgs e) OnDataError(ex); } - if (parentManager is CurrencyManager) + if (parentManager is CurrencyManager curManager) { - CurrencyManager curManager = (CurrencyManager)parentManager; if (curManager.Count > 0) { // Parent list has a current row, so get the related list from the relevant property on that row. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Screen.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Screen.cs index 9eb4e08f65e..5e7fc34ba87 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Screen.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Screen.cs @@ -309,9 +309,8 @@ private static int DesktopChangedCount /// public override bool Equals(object obj) { - if (obj is Screen) + if (obj is Screen comp) { - Screen comp = (Screen)obj; if (hmonitor == comp.hmonitor) { return true; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SelectionRangeConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SelectionRangeConverter.cs index d1b4626eb7e..0dd219449ed 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SelectionRangeConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SelectionRangeConverter.cs @@ -87,9 +87,8 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c "Start" + separator + " End")); } } - else if (value is DateTime) + else if (value is DateTime dt) { - DateTime dt = (DateTime)value; return new SelectionRange(dt, dt); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/formatter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/formatter.cs index 168a9cbe355..b19dce8232d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/formatter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/formatter.cs @@ -313,9 +313,8 @@ private static object ParseObjectInternal(object value, return parseResult; } } - else if (value is CheckState) + else if (value is CheckState state) { - CheckState state = (CheckState)value; if (state == CheckState.Indeterminate) { return DBNull.Value; From b4dd04974e16ee6edf71dcffdee6efb9bf177bff Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Fri, 24 May 2019 12:33:07 -0700 Subject: [PATCH 18/27] remove all instances of IDE0028 warning - collection init can be simplified --- src/Common/tests/CommonTestHelper.cs | 354 ++++++++++-------- .../ComponentModel/Design/DesignerHost.cs | 6 +- .../Design/ContextMenuStripActionList.cs | 6 +- .../COM2Interop/COM2PropertyDescriptor.cs | 14 +- .../Forms/WindowsFormsSectionHandler.cs | 6 +- .../UnitTests/MenuItemCollectionTests.cs | 20 +- .../Forms/ColumnHeaderCollectionTests.cs | 72 ++-- .../Forms/ControlBindingsCollectionTests.cs | 7 +- .../FileDialogCustomPlacesCollectionTests.cs | 12 +- .../Forms/ListViewSubItemCollectionTests.cs | 66 ++-- 10 files changed, 345 insertions(+), 218 deletions(-) diff --git a/src/Common/tests/CommonTestHelper.cs b/src/Common/tests/CommonTestHelper.cs index 88e0728b106..0c9f537eb9a 100644 --- a/src/Common/tests/CommonTestHelper.cs +++ b/src/Common/tests/CommonTestHelper.cs @@ -42,11 +42,13 @@ public static TheoryData GetEnumTypeTheoryData(Type enumType) // This method assumes that int.MinValue and int.MaxValue are not in the enum internal static TheoryData GetEnumTheoryDataInvalid() where T : Enum { - var data = new TheoryData(); - // This boxing is necessary because you can't cast an int to a generic, - // even if the generic is guaranteed to be an enum - data.Add((T)(object)int.MinValue); - data.Add((T)(object)int.MaxValue); + var data = new TheoryData + { + // This boxing is necessary because you can't cast an int to a generic, + // even if the generic is guaranteed to be an enum + (T)(object)int.MinValue, + (T)(object)int.MaxValue + }; return data; } @@ -66,226 +68,270 @@ public static TheoryData GetEnumTypeTheoryDataInvalid(Type enumType) // helper method to generate theory data for all values of a boolean public static TheoryData GetBoolTheoryData() { - var data = new TheoryData(); - data.Add(true); - data.Add(false); + var data = new TheoryData + { + true, + false + }; return data; } // helper method to generate theory data for some values of a int public static TheoryData GetIntTheoryData() { - var data = new TheoryData(); - data.Add(int.MinValue); - data.Add(int.MaxValue); - data.Add(0); - data.Add(1); - data.Add(-1); - data.Add(int.MaxValue / 2); + var data = new TheoryData + { + int.MinValue, + int.MaxValue, + 0, + 1, + -1, + int.MaxValue / 2 + }; return data; } public static TheoryData GetNonNegativeIntTheoryData() { - var data = new TheoryData(); - data.Add(int.MaxValue); - data.Add(0); - data.Add(1); - data.Add(int.MaxValue / 2); + var data = new TheoryData + { + int.MaxValue, + 0, + 1, + int.MaxValue / 2 + }; return data; } // helper method to generate theory data for some values of a int internal static TheoryData GetUIntTheoryData() { - var data = new TheoryData(); - data.Add(int.MaxValue); - data.Add(0); - data.Add(1); - data.Add(int.MaxValue / 2); + var data = new TheoryData + { + int.MaxValue, + 0, + 1, + int.MaxValue / 2 + }; return data; } // helper method to generate theory data for some values of a int internal static TheoryData GetNIntTheoryData() { - var data = new TheoryData(); - data.Add(int.MinValue); - data.Add(-1); - data.Add(int.MinValue / 2); + var data = new TheoryData + { + int.MinValue, + -1, + int.MinValue / 2 + }; return data; } // helper method to generate theory data for some values of a int internal static TheoryData GetFloatTheoryData() { - var data = new TheoryData(); - data.Add(float.MaxValue); - data.Add(float.MinValue); - data.Add(float.Epsilon); - data.Add(float.Epsilon * -1); - data.Add(float.NegativeInfinity); // not sure about these two - data.Add(float.PositiveInfinity); // 2 - data.Add(0); - data.Add(-1); - data.Add(1); - data.Add(float.MaxValue / 2); + var data = new TheoryData + { + float.MaxValue, + float.MinValue, + float.Epsilon, + float.Epsilon * -1, + float.NegativeInfinity, // not sure about these two + float.PositiveInfinity, // 2 + 0, + -1, + 1, + float.MaxValue / 2 + }; return data; } // helper method to generate theory data for some values of a int internal static TheoryData GetUFloatTheoryData() { - var data = new TheoryData(); - data.Add(float.MaxValue); - data.Add(float.Epsilon); - data.Add(float.PositiveInfinity); // not sure about this one - data.Add(0); - data.Add(1); - data.Add(float.MaxValue / 2); + var data = new TheoryData + { + float.MaxValue, + float.Epsilon, + float.PositiveInfinity, // not sure about this one + 0, + 1, + float.MaxValue / 2 + }; return data; } // helper method to generate theory data for a span of string values public static TheoryData GetStringTheoryData() { - var data = new TheoryData(); - data.Add(string.Empty); - data.Add("reasonable"); + var data = new TheoryData + { + string.Empty, + "reasonable" + }; return data; } public static TheoryData GetStringWithNullTheoryData() { - var data = new TheoryData(); - data.Add(null); - data.Add(string.Empty); - data.Add("reasonable"); + var data = new TheoryData + { + null, + string.Empty, + "reasonable" + }; return data; } public static TheoryData GetNullOrEmptyStringTheoryData() { - var data = new TheoryData(); - data.Add(null); - data.Add(string.Empty); + var data = new TheoryData + { + null, + string.Empty + }; return data; } public static TheoryData GetStringNormalizedTheoryData() { - var data = new TheoryData(); - data.Add(null, string.Empty); - data.Add(string.Empty, string.Empty); - data.Add("reasonable", "reasonable"); + var data = new TheoryData + { + { null, string.Empty }, + { string.Empty, string.Empty }, + { "reasonable", "reasonable" } + }; return data; } public static TheoryData GetCtrlBackspaceData() { - var data = new TheoryData(); - data.Add("aaa", "", 0); - data.Add("---", "", 0); - data.Add(" aaa", "", 0); - data.Add(" ---", "", 0); - data.Add("aaa---", "", 0); - data.Add("---aaa", "---", 0); - data.Add("aaa---aaa", "aaa---", 0); - data.Add("---aaa---", "---", 0); - data.Add("a-a", "a-", 0); - data.Add("-a-", "", 0); - data.Add("--a-", "--", 0); - data.Add("abc", "c", -1); - data.Add("a,1-b", "a,b", -1); + var data = new TheoryData + { + { "aaa", "", 0 }, + { "---", "", 0 }, + { " aaa", "", 0 }, + { " ---", "", 0 }, + { "aaa---", "", 0 }, + { "---aaa", "---", 0 }, + { "aaa---aaa", "aaa---", 0 }, + { "---aaa---", "---", 0 }, + { "a-a", "a-", 0 }, + { "-a-", "", 0 }, + { "--a-", "--", 0 }, + { "abc", "c", -1 }, + { "a,1-b", "a,b", -1 } + }; return data; } public static TheoryData GetCtrlBackspaceRepeatedData() { - var data = new TheoryData(); - data.Add("aaa", "", 2); - data.Add("---", "", 2); - data.Add("aaa---aaa", "", 2); - data.Add("---aaa---", "", 2); - data.Add("aaa bbb", "", 2); - data.Add("aaa bbb ccc", "aaa ", 2); - data.Add("aaa --- ccc", "", 2); - data.Add("1 2 3 4 5 6 7 8 9 0", "1 ", 9); + var data = new TheoryData + { + { "aaa", "", 2 }, + { "---", "", 2 }, + { "aaa---aaa", "", 2 }, + { "---aaa---", "", 2 }, + { "aaa bbb", "", 2 }, + { "aaa bbb ccc", "aaa ", 2 }, + { "aaa --- ccc", "", 2 }, + { "1 2 3 4 5 6 7 8 9 0", "1 ", 9 } + }; return data; } public static TheoryData GetCharTheoryData() { - var data = new TheoryData(); - data.Add('\0'); - data.Add('a'); + var data = new TheoryData + { + '\0', + 'a' + }; return data; } public static TheoryData GetIntPtrTheoryData() { - var data = new TheoryData(); - data.Add((IntPtr)(-1)); - data.Add(IntPtr.Zero); - data.Add((IntPtr)1); + var data = new TheoryData + { + (IntPtr)(-1), + IntPtr.Zero, + (IntPtr)1 + }; return data; } public static TheoryData GetGuidTheoryData() { - var data = new TheoryData(); - data.Add(Guid.Empty); - data.Add(Guid.NewGuid()); + var data = new TheoryData + { + Guid.Empty, + Guid.NewGuid() + }; return data; } public static TheoryData GetColorTheoryData() { - var data = new TheoryData(); - data.Add(Color.Red); - data.Add(Color.Blue); - data.Add(Color.Black); + var data = new TheoryData + { + Color.Red, + Color.Blue, + Color.Black + }; return data; } public static TheoryData GetColorWithEmptyTheoryData() { - var data = new TheoryData(); - data.Add(Color.Red); - data.Add(Color.Empty); + var data = new TheoryData + { + Color.Red, + Color.Empty + }; return data; } public static TheoryData GetImageTheoryData() { - var data = new TheoryData(); - data.Add(new Bitmap(10, 10)); - data.Add(null); + var data = new TheoryData + { + new Bitmap(10, 10), + null + }; return data; } public static TheoryData GetFontTheoryData() { - var data = new TheoryData(); - data.Add(SystemFonts.MenuFont); - data.Add(null); + var data = new TheoryData + { + SystemFonts.MenuFont, + null + }; return data; } public static TheoryData GetTypeWithNullTheoryData() { - var data = new TheoryData(); - data.Add(null); - data.Add(typeof(int)); + var data = new TheoryData + { + null, + typeof(int) + }; return data; } public static TheoryData GetRightToLeftTheoryData() { - var data = new TheoryData(); - data.Add(RightToLeft.Inherit, RightToLeft.No); - data.Add(RightToLeft.Yes, RightToLeft.Yes); - data.Add(RightToLeft.No, RightToLeft.No); + var data = new TheoryData + { + { RightToLeft.Inherit, RightToLeft.No }, + { RightToLeft.Yes, RightToLeft.Yes }, + { RightToLeft.No, RightToLeft.No } + }; return data; } @@ -329,73 +375,89 @@ public static TheoryData GetSizeTheoryData(TestIncludeType includeType) public static TheoryData GetPositiveSizeTheoryData() { - var data = new TheoryData(); - data.Add(new Size()); - data.Add(new Size(1, 2)); + var data = new TheoryData + { + new Size(), + new Size(1, 2) + }; return data; } public static TheoryData GetRectangleTheoryData() { - var data = new TheoryData(); - data.Add(new Rectangle()); - data.Add(new Rectangle(1, 2, 3, 4)); - data.Add(new Rectangle(-1, -2, -3, -4)); + var data = new TheoryData + { + new Rectangle(), + new Rectangle(1, 2, 3, 4), + new Rectangle(-1, -2, -3, -4) + }; return data; } public static TheoryData GetPaddingTheoryData() { - var data = new TheoryData(); - data.Add(new Padding()); - data.Add(new Padding(1, 2, 3, 4)); - data.Add(new Padding(1)); - data.Add(new Padding(-1, -2, -3, -4)); + var data = new TheoryData + { + new Padding(), + new Padding(1, 2, 3, 4), + new Padding(1), + new Padding(-1, -2, -3, -4) + }; return data; } public static TheoryData GetPaddingNormalizedTheoryData() { - var data = new TheoryData(); - data.Add(new Padding(), new Padding()); - data.Add(new Padding(1, 2, 3, 4), new Padding(1, 2, 3, 4)); - data.Add(new Padding(1), new Padding(1)); - data.Add(new Padding(-1, -2, -3, -4), Padding.Empty); + var data = new TheoryData + { + { new Padding(), new Padding() }, + { new Padding(1, 2, 3, 4), new Padding(1, 2, 3, 4) }, + { new Padding(1), new Padding(1) }, + { new Padding(-1, -2, -3, -4), Padding.Empty } + }; return data; } public static TheoryData GetConvertFromTheoryData() { - var data = new TheoryData(); - data.Add(typeof(bool), false); - data.Add(typeof(InstanceDescriptor), true); - data.Add(typeof(int), false); - data.Add(typeof(double), false); - data.Add(null, false); + var data = new TheoryData + { + { typeof(bool), false }, + { typeof(InstanceDescriptor), true }, + { typeof(int), false }, + { typeof(double), false }, + { null, false } + }; return data; } public static TheoryData GetCursorTheoryData() { - var data = new TheoryData(); - data.Add(null); - data.Add(new Cursor((IntPtr)1)); + var data = new TheoryData + { + null, + new Cursor((IntPtr)1) + }; return data; } public static TheoryData GetEventArgsTheoryData() { - var data = new TheoryData(); - data.Add(null); - data.Add(new EventArgs()); + var data = new TheoryData + { + null, + new EventArgs() + }; return data; } public static TheoryData GetSecurityOrCriticalException() { - var data = new TheoryData(); - data.Add(new NullReferenceException()); - data.Add(new SecurityException()); + var data = new TheoryData + { + new NullReferenceException(), + new SecurityException() + }; return data; } diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerHost.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerHost.cs index 90e717af043..7dca64e0c0c 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerHost.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerHost.cs @@ -1254,8 +1254,10 @@ void IDesignerLoaderHost.EndLoad(string rootClassName, bool successful, ICollect _state[s_stateLoading] = true; Unload(); - ArrayList errorList = new ArrayList(); - errorList.Add(ex); + ArrayList errorList = new ArrayList + { + ex + }; if (errorCollection != null) { errorList.AddRange(errorCollection); diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ContextMenuStripActionList.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ContextMenuStripActionList.cs index 49468c2c5ae..63936216a55 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ContextMenuStripActionList.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ContextMenuStripActionList.cs @@ -97,8 +97,10 @@ public ToolStripRenderMode RenderMode /// public override DesignerActionItemCollection GetSortedActionItems() { - DesignerActionItemCollection items = new DesignerActionItemCollection(); - items.Add(new DesignerActionPropertyItem("RenderMode", SR.ToolStripActionList_RenderMode, SR.ToolStripActionList_Layout, SR.ToolStripActionList_RenderModeDesc)); + DesignerActionItemCollection items = new DesignerActionItemCollection + { + new DesignerActionPropertyItem("RenderMode", SR.ToolStripActionList_RenderMode, SR.ToolStripActionList_Layout, SR.ToolStripActionList_RenderModeDesc) + }; if (_toolStripDropDown is ToolStripDropDownMenu) { items.Add(new DesignerActionPropertyItem("ShowImageMargin", SR.ContextMenuStripActionList_ShowImageMargin, SR.ToolStripActionList_Layout, SR.ContextMenuStripActionList_ShowImageMarginDesc)); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs index a94ca3aacc5..e840a2fb81b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs @@ -131,12 +131,14 @@ internal class Com2PropertyDescriptor : PropertyDescriptor, ICloneable static Com2PropertyDescriptor() { - oleConverters = new SortedList(); - oleConverters[GUID_COLOR] = typeof(Com2ColorConverter); - oleConverters[typeof(SafeNativeMethods.IFontDisp).GUID] = typeof(Com2FontConverter); - oleConverters[typeof(UnsafeNativeMethods.IFont).GUID] = typeof(Com2FontConverter); - oleConverters[typeof(UnsafeNativeMethods.IPictureDisp).GUID] = typeof(Com2PictureConverter); - oleConverters[typeof(UnsafeNativeMethods.IPicture).GUID] = typeof(Com2PictureConverter); + oleConverters = new SortedList + { + [GUID_COLOR] = typeof(Com2ColorConverter), + [typeof(SafeNativeMethods.IFontDisp).GUID] = typeof(Com2FontConverter), + [typeof(UnsafeNativeMethods.IFont).GUID] = typeof(Com2FontConverter), + [typeof(UnsafeNativeMethods.IPictureDisp).GUID] = typeof(Com2PictureConverter), + [typeof(UnsafeNativeMethods.IPicture).GUID] = typeof(Com2PictureConverter) + }; } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WindowsFormsSectionHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WindowsFormsSectionHandler.cs index d23268a5ea8..2a6d6ca5e78 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WindowsFormsSectionHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WindowsFormsSectionHandler.cs @@ -40,8 +40,10 @@ private static ConfigurationPropertyCollection EnsureStaticPropertyBag() { s_propJitDebugging = new ConfigurationProperty("jitDebugging", typeof(bool), JitDebuggingDefault, ConfigurationPropertyOptions.None); - ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection(); - properties.Add(s_propJitDebugging); + ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection + { + s_propJitDebugging + }; s_properties = properties; } diff --git a/src/System.Windows.Forms/tests/UnitTests/MenuItemCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/MenuItemCollectionTests.cs index b5cb415fdc4..f5342690062 100644 --- a/src/System.Windows.Forms/tests/UnitTests/MenuItemCollectionTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/MenuItemCollectionTests.cs @@ -149,9 +149,11 @@ public void MenuItemCollection_Add_AlreadyInSameCollection_Success() var menuItem1 = new MenuItem(); var menuItem2 = new MenuItem(); var parent = new MenuItem("text", new MenuItem[0]); - var collection = new Menu.MenuItemCollection(parent); - collection.Add(menuItem1); - collection.Add(menuItem2); + var collection = new Menu.MenuItemCollection(parent) + { + menuItem1, + menuItem2 + }; Assert.Equal(0, collection.Add(0, menuItem2)); Assert.Equal(2, collection.Count); @@ -281,8 +283,10 @@ public void MenuItemCollection_Add_AlreadyInCollection_InvalidIndex_ThrowsArgume { var menuItem = new MenuItem(); var parent = new MenuItem("text", new MenuItem[0]); - var collection = new Menu.MenuItemCollection(parent); - collection.Add(menuItem); + var collection = new Menu.MenuItemCollection(parent) + { + menuItem + }; Assert.Throws("index", () => collection.Add(index, menuItem)); } @@ -387,8 +391,10 @@ public void MenuItemCollection_CopyTo_NotEmpty_Success() { var menuItem = new MenuItem(); var menu = new SubMenu(new MenuItem[0]); - var collection = new Menu.MenuItemCollection(menu); - collection.Add(menuItem); + var collection = new Menu.MenuItemCollection(menu) + { + menuItem + }; var array = new object[] { 1, 2, 3 }; collection.CopyTo(array, 1); Assert.Equal(new object[] { 1, menuItem, 3 }, array); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ColumnHeaderCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ColumnHeaderCollectionTests.cs index 1ee2472ed02..f289ec7dac7 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ColumnHeaderCollectionTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ColumnHeaderCollectionTests.cs @@ -57,8 +57,10 @@ public void ColumnHeaderCollection_Item_GetValidIndex_ReturnsExpected() public void ColumnHeaderCollection_Item_GetInvalidIndex_ThrowsArgumentOutOfRangeException(int index) { var listView = new ListView(); - var collection = new ListView.ColumnHeaderCollection(listView); - collection.Add(new ColumnHeader()); + var collection = new ListView.ColumnHeaderCollection(listView) + { + new ColumnHeader() + }; Assert.Throws("index", () => collection[index]); } @@ -79,8 +81,10 @@ public void ColumnHeaderCollection_IListItem_GetValidIndex_ReturnsExpected() public void ColumnHeaderCollection_IListItem_GetInvalidIndex_ThrowsArgumentOutOfRangeException(int index) { var listView = new ListView(); - IList collection = new ListView.ColumnHeaderCollection(listView); - collection.Add(new ColumnHeader()); + IList collection = new ListView.ColumnHeaderCollection(listView) + { + new ColumnHeader() + }; Assert.Throws("index", () => collection[index]); } @@ -90,8 +94,10 @@ public void ColumnHeaderCollection_IListItem_GetInvalidIndex_ThrowsArgumentOutOf public void ColumnHeaderCollection_IListItem_Set_ThrowsNotSupportedException(int index) { var listView = new ListView(); - IList collection = new ListView.ColumnHeaderCollection(listView); - collection.Add(new ColumnHeader()); + IList collection = new ListView.ColumnHeaderCollection(listView) + { + new ColumnHeader() + }; Assert.Throws(() => collection[index] = new ColumnHeader()); } @@ -158,8 +164,10 @@ public void ColumnHeaderCollection_Add_ExistsInOtherCollection_ThrowsArgumentExc public void ColumnHeaderCollection_Add_String_Success(string text, string expectedText) { var listView = new ListView(); - var collection = new ListView.ColumnHeaderCollection(listView); - collection.Add(text); + var collection = new ListView.ColumnHeaderCollection(listView) + { + text + }; ColumnHeader header = Assert.Single(collection.Cast()); Assert.Same(expectedText, header.Text); Assert.Equal(listView, header.ListView); @@ -177,8 +185,10 @@ public static IEnumerable Add_String_Int_TestData() public void ColumnHeaderCollection_Add_String_Int_Success(string text, int width, string expectedText) { var listView = new ListView(); - var collection = new ListView.ColumnHeaderCollection(listView); - collection.Add(text, width); + var collection = new ListView.ColumnHeaderCollection(listView) + { + { text, width } + }; ColumnHeader header = Assert.Single(collection.Cast()); Assert.Equal(expectedText, header.Text); Assert.Equal(width, header.Width); @@ -197,8 +207,10 @@ public static IEnumerable Add_String_Int_HorizontalAlignment_TestData( public void ColumnHeaderCollection_Add_String_Int_HorizontalAlignment_Success(string text, int width, HorizontalAlignment textAlign, string expectedText) { var listView = new ListView(); - var collection = new ListView.ColumnHeaderCollection(listView); - collection.Add(text, width, textAlign); + var collection = new ListView.ColumnHeaderCollection(listView) + { + { text, width, textAlign } + }; ColumnHeader header = Assert.Single(collection.Cast()); Assert.Equal(expectedText, header.Text); Assert.Equal(width, header.Width); @@ -218,8 +230,10 @@ public static IEnumerable Add_String_String_TestData() public void ColumnHeaderCollection_Add_String_String_Success(string name, string text, string expectedName, string expectedText) { var listView = new ListView(); - var collection = new ListView.ColumnHeaderCollection(listView); - collection.Add(name, text); + var collection = new ListView.ColumnHeaderCollection(listView) + { + { name, text } + }; ColumnHeader header = Assert.Single(collection.Cast()); Assert.Same(expectedName, header.Name); Assert.Same(expectedText, header.Text); @@ -238,8 +252,10 @@ public static IEnumerable Add_String_String_Int_TestData() public void ColumnHeaderCollection_Add_String_String_Int_Success(string name, string text, int width, string expectedName, string expectedText) { var listView = new ListView(); - var collection = new ListView.ColumnHeaderCollection(listView); - collection.Add(name, text, width); + var collection = new ListView.ColumnHeaderCollection(listView) + { + { name, text, width } + }; ColumnHeader header = Assert.Single(collection.Cast()); Assert.Same(expectedName, header.Name); Assert.Same(expectedText, header.Text); @@ -259,8 +275,10 @@ public static IEnumerable Add_String_String_Int_HorizontalAlignment_In public void ColumnHeaderCollection_Add_String_String_Int_HorizontalAlignment_Int_Success(string name, string text, int width, HorizontalAlignment textAlign, int imageIndex, string expectedName, string expectedText) { var listView = new ListView(); - var collection = new ListView.ColumnHeaderCollection(listView); - collection.Add(name, text, width, textAlign, imageIndex); + var collection = new ListView.ColumnHeaderCollection(listView) + { + { name, text, width, textAlign, imageIndex } + }; ColumnHeader header = Assert.Single(collection.Cast()); Assert.Same(expectedName, header.Name); Assert.Same(expectedText, header.Text); @@ -282,8 +300,10 @@ public static IEnumerable Add_String_String_Int_HorizontalAlignment_St public void ColumnHeaderCollection_Add_String_String_Int_HorizontalAlignment_String_Success(string name, string text, int width, HorizontalAlignment textAlign, string imageKey, string expectedName, string expectedText, string expectedImageKey) { var listView = new ListView(); - var collection = new ListView.ColumnHeaderCollection(listView); - collection.Add(name, text, width, textAlign, imageKey); + var collection = new ListView.ColumnHeaderCollection(listView) + { + { name, text, width, textAlign, imageKey } + }; ColumnHeader header = Assert.Single(collection.Cast()); Assert.Same(expectedName, header.Name); Assert.Same(expectedText, header.Text); @@ -796,8 +816,10 @@ public void ColumnHeaderCollection_Insert_String_String_Int_HorizontalAlignment_ public void ColumnHeaderCollection_Insert_NullItem_ThrowsArgumentNullException() { var listView = new ListView(); - var collection = new ListView.ColumnHeaderCollection(listView); - collection.Add(new ColumnHeader()); + var collection = new ListView.ColumnHeaderCollection(listView) + { + new ColumnHeader() + }; Assert.Throws("ch", () => collection.Insert(1, (ColumnHeader)null)); } @@ -1023,8 +1045,10 @@ public void ColumnHeaderCollection_RemoveAt_HasHandleWithTile_Success() public void ColumnHeaderCollection_RemoveAt_InvalidIndex_ThrowsArgumentOutOfRangeException(int index) { var listView = new ListView(); - var collection = new ListView.ColumnHeaderCollection(listView); - collection.Add(new ColumnHeader()); + var collection = new ListView.ColumnHeaderCollection(listView) + { + new ColumnHeader() + }; Assert.Throws("index", () => collection.RemoveAt(index)); } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlBindingsCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlBindingsCollectionTests.cs index 674932bd2cc..af4045e4752 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlBindingsCollectionTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ControlBindingsCollectionTests.cs @@ -59,9 +59,10 @@ public static IEnumerable Add_Binding_TestData() public void Add_Binding_Success(Binding binding) { var control = new Control(); - var collection = new ControlBindingsCollection(control); - - collection.Add(binding); + var collection = new ControlBindingsCollection(control) + { + binding + }; Assert.Same(binding, Assert.Single(collection)); Assert.Same(control, binding.BindableComponent); } diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/FileDialogCustomPlacesCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/FileDialogCustomPlacesCollectionTests.cs index 8ce372e5735..48c3a846034 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/FileDialogCustomPlacesCollectionTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/FileDialogCustomPlacesCollectionTests.cs @@ -13,8 +13,10 @@ public class FileDialogCustomPlacesCollectionTests [CommonMemberData(nameof(CommonTestHelper.GetStringWithNullTheoryData))] public void FileDialogCustomPlacesCollection_Add_String_Success(string path) { - var collection = new FileDialogCustomPlacesCollection(); - collection.Add(path); + var collection = new FileDialogCustomPlacesCollection + { + path + }; FileDialogCustomPlace place = Assert.Single(collection); Assert.Equal(Guid.Empty, place.KnownFolderGuid); Assert.Same(path ?? string.Empty, place.Path); @@ -24,8 +26,10 @@ public void FileDialogCustomPlacesCollection_Add_String_Success(string path) [CommonMemberData(nameof(CommonTestHelper.GetGuidTheoryData))] public void FileDialogCustomPlacesCollection_Add_Guid_Success(Guid knownFolderGuid) { - var collection = new FileDialogCustomPlacesCollection(); - collection.Add(knownFolderGuid); + var collection = new FileDialogCustomPlacesCollection + { + knownFolderGuid + }; FileDialogCustomPlace place = Assert.Single(collection); Assert.Equal(knownFolderGuid, place.KnownFolderGuid); Assert.Empty(place.Path); diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemCollectionTests.cs index 1d323712a8d..36377ad18c0 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemCollectionTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListViewSubItemCollectionTests.cs @@ -56,8 +56,10 @@ public void ListViewSubItemCollection_Item_GetValidIndex_ReturnsExpected() public void ListViewSubItemCollection_Item_GetInvalidIndex_ThrowsArgumentOutOfRangeException(int index) { var item = new ListViewItem(); - var collection = new ListViewItem.ListViewSubItemCollection(item); - collection.Add(new ListViewItem.ListViewSubItem()); + var collection = new ListViewItem.ListViewSubItemCollection(item) + { + new ListViewItem.ListViewSubItem() + }; Assert.Throws("index", () => collection[index]); } @@ -65,8 +67,10 @@ public void ListViewSubItemCollection_Item_GetInvalidIndex_ThrowsArgumentOutOfRa public void ListViewSubItemCollection_Item_SetValidIndex_GetReturnsExpected() { var item = new ListViewItem(); - var collection = new ListViewItem.ListViewSubItemCollection(item); - collection.Add(new ListViewItem.ListViewSubItem()); + var collection = new ListViewItem.ListViewSubItemCollection(item) + { + new ListViewItem.ListViewSubItem() + }; var subItem = new ListViewItem.ListViewSubItem(); collection[0] = subItem; @@ -79,8 +83,10 @@ public void ListViewSubItemCollection_Item_SetValidIndex_GetReturnsExpected() public void ListViewSubItemCollection_Item_SetInvalidIndex_ThrowsArgumentOutOfRangeException(int index) { var item = new ListViewItem(); - var collection = new ListViewItem.ListViewSubItemCollection(item); - collection.Add(new ListViewItem.ListViewSubItem()); + var collection = new ListViewItem.ListViewSubItemCollection(item) + { + new ListViewItem.ListViewSubItem() + }; Assert.Throws("index", () => collection[index] = new ListViewItem.ListViewSubItem()); } @@ -88,8 +94,10 @@ public void ListViewSubItemCollection_Item_SetInvalidIndex_ThrowsArgumentOutOfRa public void ListViewSubItemCollection_Item_SetNull_ThrowsArgumentNullException() { var item = new ListViewItem(); - var collection = new ListViewItem.ListViewSubItemCollection(item); - collection.Add(new ListViewItem.ListViewSubItem()); + var collection = new ListViewItem.ListViewSubItemCollection(item) + { + new ListViewItem.ListViewSubItem() + }; Assert.Throws("value", () => collection[0] = null); } @@ -110,8 +118,10 @@ public void ListViewSubItemCollection_IListItem_GetValidIndex_ReturnsExpected() public void ListViewSubItemCollection_IListItem_GetInvalidIndex_ThrowsArgumentOutOfRangeException(int index) { var item = new ListViewItem(); - IList collection = new ListViewItem.ListViewSubItemCollection(item); - collection.Add(new ListViewItem.ListViewSubItem()); + IList collection = new ListViewItem.ListViewSubItemCollection(item) + { + new ListViewItem.ListViewSubItem() + }; Assert.Throws("index", () => collection[index]); } @@ -119,8 +129,10 @@ public void ListViewSubItemCollection_IListItem_GetInvalidIndex_ThrowsArgumentOu public void ListViewSubItemCollection_IListItem_SetValidIndex_GetReturnsExpected() { var item = new ListViewItem(); - IList collection = new ListViewItem.ListViewSubItemCollection(item); - collection.Add(new ListViewItem.ListViewSubItem()); + IList collection = new ListViewItem.ListViewSubItemCollection(item) + { + new ListViewItem.ListViewSubItem() + }; var subItem = new ListViewItem.ListViewSubItem(); collection[0] = subItem; @@ -133,8 +145,10 @@ public void ListViewSubItemCollection_IListItem_SetValidIndex_GetReturnsExpected public void ListViewSubItemCollection_IListItem_SetInvalidIndex_ThrowsArgumentOutOfRangeException(int index) { var item = new ListViewItem(); - IList collection = new ListViewItem.ListViewSubItemCollection(item); - collection.Add(new ListViewItem.ListViewSubItem()); + IList collection = new ListViewItem.ListViewSubItemCollection(item) + { + new ListViewItem.ListViewSubItem() + }; Assert.Throws("index", () => collection[index]); } @@ -234,8 +248,10 @@ public void ListViewSubItemCollection_Add_ListViewSubItemExistsInOtherCollection public void ListViewSubItemCollection_Add_String_Success(string text, string expectedText) { var item = new ListViewItem(); - var collection = new ListViewItem.ListViewSubItemCollection(item); - collection.Add(text); + var collection = new ListViewItem.ListViewSubItemCollection(item) + { + text + }; ListViewItem.ListViewSubItem subItem = Assert.Single(collection.Cast()); Assert.Equal(expectedText, subItem.Text); Assert.Equal(item, subItem.owner); @@ -253,8 +269,10 @@ public static IEnumerable Add_String_Color_Color_Font_TestData() public void ListViewSubItemCollection_Add_String_Color_Color_Font_Success(string text, Color foreColor, Color backColor, Font font, Color expectedForeColor, Color expectedBackColor, string expectedText) { var item = new ListViewItem(); - var collection = new ListViewItem.ListViewSubItemCollection(item); - collection.Add(text, foreColor, backColor, font); + var collection = new ListViewItem.ListViewSubItemCollection(item) + { + { text, foreColor, backColor, font } + }; ListViewItem.ListViewSubItem subItem = Assert.Single(collection.Cast()); Assert.Same(expectedText, subItem.Text); Assert.Equal(expectedForeColor, subItem.ForeColor); @@ -632,8 +650,10 @@ public void ListViewSubItemCollection_Insert_ManyItems_Success() public void ListViewSubItemCollection_Insert_NullItem_ThrowsArgumentNullException() { var item = new ListViewItem(); - var collection = new ListViewItem.ListViewSubItemCollection(item); - collection.Add(new ListViewItem.ListViewSubItem()); + var collection = new ListViewItem.ListViewSubItemCollection(item) + { + new ListViewItem.ListViewSubItem() + }; Assert.Throws("item", () => collection.Insert(1, null)); } @@ -769,8 +789,10 @@ public void ListViewSubItemCollection_RemoveAt_ValidIndex_Success() public void ListViewSubItemCollection_RemoveAt_InvalidIndex_ThrowsArgumentOutOfRangeException(int index) { var item = new ListViewItem(); - var collection = new ListViewItem.ListViewSubItemCollection(item); - collection.Add(new ListViewItem.ListViewSubItem()); + var collection = new ListViewItem.ListViewSubItemCollection(item) + { + new ListViewItem.ListViewSubItem() + }; Assert.Throws("index", () => collection.RemoveAt(index)); } From 70f44374bae6b6fb31598a3cdc89049199a7f7f3 Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Fri, 24 May 2019 12:34:36 -0700 Subject: [PATCH 19/27] remove all instances of IDE0029 warning - null check can be simplified with coalescing operator --- .../Design/Serialization/CodeDomSerializerBase.cs | 4 ++-- .../src/System/Windows/Forms/AxHost.cs | 8 ++++---- .../src/System/Windows/Forms/ColumnHeader.cs | 2 +- .../src/System/Windows/Forms/ComboBox.cs | 4 ++-- .../Forms/ComponentModel/COM2Interop/COM2EnumConverter.cs | 2 +- .../ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs | 2 +- .../src/System/Windows/Forms/ContainerControl.cs | 2 +- .../src/System/Windows/Forms/Control.cs | 4 ++-- .../src/System/Windows/Forms/DataGrid.cs | 4 ++-- .../src/System/Windows/Forms/DataGridTable.cs | 2 +- .../src/System/Windows/Forms/DataGridViewButtonCell.cs | 4 ++-- .../src/System/Windows/Forms/DataGridViewCell.cs | 8 ++++---- .../System/Windows/Forms/DataGridViewColumnHeaderCell.cs | 2 +- .../src/System/Windows/Forms/DataGridViewComboBoxCell.cs | 4 ++-- .../src/System/Windows/Forms/DataGridViewMethods.cs | 2 +- .../src/System/Windows/Forms/DataGridViewRowHeaderCell.cs | 2 +- .../src/System/Windows/Forms/ErrorProvider.cs | 2 +- .../src/System/Windows/Forms/ImageList.cs | 2 +- .../src/System/Windows/Forms/Layout/TableLayout.cs | 2 +- .../src/System/Windows/Forms/MdiWindowListStrip.cs | 2 +- .../src/System/Windows/Forms/Printing/PageSetupDialog.cs | 2 +- .../Forms/PropertyGridInternal/MergePropertyDescriptor.cs | 2 +- .../PropertyGridInternal/PropertyDescriptorGridEntry.cs | 4 ++-- .../src/System/Windows/Forms/ToolBarButton.cs | 4 ++-- .../src/System/Windows/Forms/ToolStripPanel.cs | 4 ++-- .../src/System/Windows/Forms/ToolStripSettings.cs | 2 +- .../src/System/Windows/Forms/TreeNode.cs | 6 +++--- .../src/System/Windows/Forms/TreeView.cs | 2 +- .../src/System/Windows/Forms/WebBrowser.cs | 2 +- .../src/System/Windows/Forms/WebBrowserContainer.cs | 2 +- src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs | 2 +- 31 files changed, 48 insertions(+), 48 deletions(-) diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs index ea20bc3d9f7..e717e8bf74b 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs @@ -444,7 +444,7 @@ protected void DeserializePropertiesFromResources(IDesignerSerializationManager if (passFilter) { object resourceObject = de.Value; - Trace("Resource: {0}, value: {1}", resourceName, (resourceObject == null ? "(null)" : resourceObject)); + Trace("Resource: {0}, value: {1}", resourceName, (resourceObject ?? "(null)")); try { property.SetValue(value, resourceObject); @@ -889,7 +889,7 @@ protected object DeserializeExpression(IDesignerSerializationManager manager, st { if (result is CodePrimitiveExpression primitiveEx) { - Trace("Primitive. Value: {0}", (primitiveEx.Value == null ? "(null)" : primitiveEx.Value)); + Trace("Primitive. Value: {0}", (primitiveEx.Value ?? "(null)")); result = primitiveEx.Value; break; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs index da83f3f2068..fa4cd7d1470 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs @@ -5883,7 +5883,7 @@ internal UnsafeNativeMethods.IExtender GetProxyForControl(Control ctl) internal string GetNameForControl(Control ctl) { string name = (ctl.Site != null) ? ctl.Site.Name : ctl.Name; - return (name == null) ? "" : name; + return name ?? ""; } internal object GetProxyForContainer() @@ -6208,7 +6208,7 @@ private IContainer GetParentsContainer() IContainer rval = GetParentIsDesigned(); Debug.Assert(rval == null || assocContainer == null || (rval == assocContainer), "mismatch between getIPD & aContainer"); - return rval == null ? assocContainer : rval; + return rval ?? assocContainer; } private bool RegisterControl(AxHost ctl) @@ -6570,7 +6570,7 @@ internal void OnExitEditMode(AxHost ctl) int UnsafeNativeMethods.IOleInPlaceFrame.SetActiveObject(UnsafeNativeMethods.IOleInPlaceActiveObject pActiveObject, string pszObjName) { - Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in SetActiveObject " + ((pszObjName == null) ? "" : pszObjName)); + Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in SetActiveObject " + (pszObjName ?? "")); if (siteUIActive != null) { if (siteUIActive.iOleInPlaceActiveObjectExternal != pActiveObject) @@ -7724,7 +7724,7 @@ public override TypeConverter Converter { UpdateTypeConverterAndTypeEditorInternal(false, Dispid); } - return (converter != null) ? converter : base.Converter; + return converter ?? base.Converter; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeader.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeader.cs index 60c2c520e7d..b841ea55abb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeader.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeader.cs @@ -329,7 +329,7 @@ public string Text { get { - return (text != null ? text : "ColumnHeader"); + return (text ?? "ColumnHeader"); } set { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs index 490b5fe606d..1631a3a8c4d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs @@ -838,7 +838,7 @@ private string MatchingText get { string matchingText = (string)Properties.GetObject(PropMatchingText); - return (matchingText == null) ? string.Empty : matchingText; + return matchingText ?? string.Empty; } set { @@ -1230,7 +1230,7 @@ public string SelectedText { //guard against null string, since otherwise we will throw an //AccessViolation exception, which is bad - string str = (value == null ? "" : value); + string str = (value ?? ""); CreateControl(); if (IsHandleCreated) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2EnumConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2EnumConverter.cs index 286babab79f..117451e9f5d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2EnumConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2EnumConverter.cs @@ -79,7 +79,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul if (value != null) { string str = com2Enum.ToString(value); - return (str == null ? "" : str); + return (str ?? ""); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs index cc45518a612..0c515f930b4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs @@ -838,7 +838,7 @@ private static Type ProcessTypeInfoEnum(UnsafeNativeMethods.ITypeInfo enumTypeIn continue; } - Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "ProcessTypeInfoEnum got name=" + (name == null ? "(null)" : name) + ", helpstring=" + (helpstr == null ? "(null)" : helpstr)); + Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "ProcessTypeInfoEnum got name=" + (name ?? "(null)") + ", helpstring=" + (helpstr ?? "(null)")); // get the value try diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs index 7f1d8ffcfa6..44d6fa10bac 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs @@ -1858,7 +1858,7 @@ internal bool ValidateInternal(bool checkAutoValidate, out bool validatedControl // Should we force focus to stay on same control if there is a validation error? bool preventFocusChangeOnError = true; - Control controlToValidate = unvalidatedControl != null ? unvalidatedControl : focusedControl; + Control controlToValidate = unvalidatedControl ?? focusedControl; if (controlToValidate != null) { 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 9c7711a0564..696c92096c0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs @@ -4330,7 +4330,7 @@ public virtual string Text { if (CacheTextInternal) { - return (text == null) ? "" : text; + return text ?? ""; } else { @@ -20083,7 +20083,7 @@ public int Next(int celt, NativeMethods.tagOLEVERB rgelt, int[] pceltFetched) Debug.Indent(); for (int i = current - fetched; i < current; i++) { - Debug.WriteLine(i.ToString(CultureInfo.InvariantCulture) + ": " + verbs[i].lVerb + " " + (verbs[i].lpszVerbName == null ? string.Empty : verbs[i].lpszVerbName)); + Debug.WriteLine(i.ToString(CultureInfo.InvariantCulture) + ": " + verbs[i].lVerb + " " + (verbs[i].lpszVerbName ?? string.Empty)); } Debug.Unindent(); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs index 2cb1fedaf3c..7a9f87bc893 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs @@ -1780,7 +1780,7 @@ internal void Set_ListManager(object newDataSource, string newDataMember, bool f // update the dataSource and the dateMember dataSource = newDataSource; - dataMember = newDataMember == null ? "" : newDataMember; + dataMember = newDataMember ?? ""; listManagerChanged = (listManager != oldListManager); @@ -2366,7 +2366,7 @@ public Font HeaderFont { get { - return (headerFont == null ? Font : headerFont); + return (headerFont ?? Font); } set { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs index 477f4ea70f3..fc7259f6dff 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs @@ -652,7 +652,7 @@ public Font HeaderFont { get { - return (headerFont == null ? (DataGrid == null ? Control.DefaultFont : DataGrid.Font) : headerFont); + return (headerFont ?? (DataGrid == null ? Control.DefaultFont : DataGrid.Font)); } set { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonCell.cs index 2d34bae3870..597db7c97ef 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonCell.cs @@ -917,7 +917,7 @@ private Rectangle PaintPrivate(Graphics g, cellStyle.ForeColor, cellStyle.BackColor, DataGridView.Enabled).Calculate(); - string text = (formattedString != null) ? formattedString : string.Empty; + string text = formattedString ?? string.Empty; ButtonBaseAdapter.LayoutOptions options = ButtonInternal.ButtonFlatAdapter.PaintFlatLayout(g, true, @@ -948,7 +948,7 @@ private Rectangle PaintPrivate(Graphics g, // If we are painting the current cell, then paint the text up. // If we are painting the current cell and the current cell is pressed down, then paint the text down. bool paintUp = (ButtonState == ButtonState.Normal); - string text = (formattedString != null) ? formattedString : string.Empty; + string text = formattedString ?? string.Empty; ButtonBaseAdapter.LayoutOptions options = ButtonInternal.ButtonPopupAdapter.PaintPopupLayout(g, paintUp, SystemInformation.HighContrast ? 2 : 1, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs index b5b0950c504..f2027a36576 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs @@ -1838,8 +1838,8 @@ protected virtual object GetFormattedValue(object value, { formattedValue = Formatter.FormatObject(formattedValue, FormattedValueType, - valueTypeConverter == null ? ValueTypeConverter : valueTypeConverter, /*sourceConverter*/ - formattedValueTypeConverter == null ? FormattedValueTypeConverter : formattedValueTypeConverter, /*targetConverter*/ + valueTypeConverter ?? ValueTypeConverter, /*sourceConverter*/ + formattedValueTypeConverter ?? FormattedValueTypeConverter, /*targetConverter*/ cellStyle.Format, cellStyle.FormatProvider, cellStyle.NullValue, @@ -4346,8 +4346,8 @@ internal object ParseFormattedValueInternal(Type valueType, return Formatter.ParseObject(formattedValue, valueType, FormattedValueType, - valueTypeConverter == null ? ValueTypeConverter : valueTypeConverter /*sourceConverter*/, - formattedValueTypeConverter == null ? FormattedValueTypeConverter : formattedValueTypeConverter /*targetConverter*/, + valueTypeConverter ?? ValueTypeConverter, + formattedValueTypeConverter ?? FormattedValueTypeConverter, cellStyle.FormatProvider, cellStyle.NullValue, cellStyle.IsDataSourceNullValueDefault ? Formatter.GetDefaultDataSourceNullValue(valueType) : cellStyle.DataSourceNullValue); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnHeaderCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnHeaderCell.cs index 629369c9a20..8ebb08e2fc4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnHeaderCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnHeaderCell.cs @@ -308,7 +308,7 @@ public override DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle in throw new ArgumentOutOfRangeException(nameof(rowIndex)); } - DataGridViewCellStyle inheritedCellStyleTmp = (inheritedCellStyle == null) ? new DataGridViewCellStyle() : inheritedCellStyle; + DataGridViewCellStyle inheritedCellStyleTmp = inheritedCellStyle ?? new DataGridViewCellStyle(); DataGridViewCellStyle cellStyle = null; if (HasStyle) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs index 9842a0cadcd..91c9fc4c929 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs @@ -1734,7 +1734,7 @@ private bool LookupDisplayValue(int rowIndex, object value, out object displayVa { //Now look up the item in the Combobox datasource - this can be horribly inefficient //and it uses reflection which makes it expensive - ripe for optimization - item = ItemFromComboBoxDataSource(ValueMemberProperty != null ? ValueMemberProperty : DisplayMemberProperty, value); + item = ItemFromComboBoxDataSource(ValueMemberProperty ?? DisplayMemberProperty, value); } else { @@ -1776,7 +1776,7 @@ private bool LookupValue(object formattedValue, out object value) { //Now look up the item in the DataGridViewComboboxCell datasource - this can be horribly inefficient //and it uses reflection which makes it expensive - ripe for optimization - item = ItemFromComboBoxDataSource(DisplayMemberProperty != null ? DisplayMemberProperty : ValueMemberProperty, formattedValue); + item = ItemFromComboBoxDataSource(DisplayMemberProperty ?? ValueMemberProperty, formattedValue); } else { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs index 14ae23e639e..209225b6e48 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs @@ -13305,7 +13305,7 @@ protected virtual void OnCellValidated(DataGridViewCellEventArgs e) internal bool OnCellValidating(ref DataGridViewCell dataGridViewCell, int columnIndex, int rowIndex, DataGridViewDataErrorContexts context) { - DataGridViewCell currentCell = (dataGridViewCell == null) ? CurrentCellInternal : dataGridViewCell; + DataGridViewCell currentCell = dataGridViewCell ?? CurrentCellInternal; DataGridViewCellStyle dataGridViewCellStyle = currentCell.GetInheritedStyle(null, rowIndex, false); object val = currentCell.GetValueInternal(rowIndex); object editedFormattedValue = currentCell.GetEditedFormattedValue(val, rowIndex, ref dataGridViewCellStyle, context); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowHeaderCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowHeaderCell.cs index eca99043652..d86fb38f807 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowHeaderCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowHeaderCell.cs @@ -411,7 +411,7 @@ public override DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle in { Debug.Assert(DataGridView != null); - DataGridViewCellStyle inheritedCellStyleTmp = (inheritedCellStyle == null) ? new DataGridViewCellStyle() : inheritedCellStyle; + DataGridViewCellStyle inheritedCellStyleTmp = inheritedCellStyle ?? new DataGridViewCellStyle(); DataGridViewCellStyle cellStyle = null; if (HasStyle) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs index 3c51416eecb..7ab8b87877a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs @@ -469,7 +469,7 @@ private void ErrorManager_BindingComplete(object sender, BindingCompleteEventArg if (binding != null && binding.Control != null) { - SetError(binding.Control, (e.ErrorText == null ? string.Empty : e.ErrorText)); + SetError(binding.Control, (e.ErrorText ?? string.Empty)); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs index 8af30366e53..b8de3d2b88f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs @@ -128,7 +128,7 @@ public virtual string Key set { index = -1; - key = (value == null ? string.Empty : value); + key = (value ?? string.Empty); useIntegerIndex = false; } } 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 749770b91f7..5b4747a64e7 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 @@ -1970,7 +1970,7 @@ public LayoutInfo[] ChildrenInfo } _state[stateChildInfoValid] = true; } - return (_childInfo == null) ? new LayoutInfo[0] : _childInfo; + return _childInfo ?? (new LayoutInfo[0]); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListStrip.cs index 49d000e2ba3..c4800afe86b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MdiWindowListStrip.cs @@ -120,7 +120,7 @@ public void PopulateItems(Form mdiParent, ToolStripMenuItem mdiMergeItem, bool i (forms[i].Equals(activeMdiChild)))) { // there's always room for activeMdiChild string text = WindowsFormsUtils.EscapeTextWithAmpersands(mdiParent.MdiChildren[i].Text); - text = (text == null) ? string.Empty : text; + text = text ?? string.Empty; ToolStripMenuItem windowListItem = new ToolStripMenuItem(mdiParent.MdiChildren[i]) { Text = string.Format(CultureInfo.CurrentCulture, "&{0} {1}", accel, text), diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PageSetupDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PageSetupDialog.cs index bb6f7126c9c..84814952ae1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PageSetupDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PageSetupDialog.cs @@ -440,7 +440,7 @@ protected override bool RunDialog(IntPtr hwndOwner) data.marginRight = Math.Max(data.marginRight, data.minMarginRight); data.marginBottom = Math.Max(data.marginBottom, data.minMarginBottom); - PrinterSettings printer = (printerSettings == null) ? pageSettings.PrinterSettings : printerSettings; + PrinterSettings printer = printerSettings ?? pageSettings.PrinterSettings; data.hDevMode = printer.GetHdevmode(pageSettings); data.hDevNames = printer.GetHdevnames(); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs index 80a53abecf9..b623ee8bc2f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs @@ -356,7 +356,7 @@ public object GetValue(Array components, out bool allEqual) return null; } - return (collection != null ? collection : obj); + return (collection ?? obj); } internal object[] GetValues(Array components) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs index 8dc3a9dad1b..0f2b72c6ffc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs @@ -206,7 +206,7 @@ internal override string LabelToolTipText { get { - return (toolTipText != null ? toolTipText : base.LabelToolTipText); + return (toolTipText ?? base.LabelToolTipText); } } @@ -760,7 +760,7 @@ private object SetPropertyValue(object obj, object objVal, bool reset, string un if (host != null) { - string text = (undoText == null ? string.Format(SR.PropertyGridSetValue, propertyInfo.Name) : undoText); + string text = (undoText ?? string.Format(SR.PropertyGridSetValue, propertyInfo.Name)); trans = host.CreateTransaction(text); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs index 50358766b14..2a87ff5a9d3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs @@ -439,7 +439,7 @@ public string Text { get { - return (text == null) ? "" : text; + return text ?? ""; } set { @@ -474,7 +474,7 @@ public string ToolTipText { get { - return tooltipText == null ? "" : tooltipText; + return tooltipText ?? ""; } set { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs index ece2a2ac216..1ae3d5d75ce 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs @@ -1457,14 +1457,14 @@ private void Debug_VerifyNoOverlaps() string fail = string.Format(CultureInfo.CurrentCulture, "OVERLAP detection:\r\n{0}: {1} row {2} row bounds {3}", - c1.Name == null ? "" : c1.Name, + c1.Name ?? "", c1.Bounds, !RowsInternal.Contains(draggedToolStrip1.ToolStripPanelRow) ? "unknown" : RowsInternal.IndexOf(draggedToolStrip1.ToolStripPanelRow).ToString(CultureInfo.CurrentCulture), draggedToolStrip1.ToolStripPanelRow.Bounds); fail += string.Format(CultureInfo.CurrentCulture, "\r\n{0}: {1} row {2} row bounds {3}", - c2.Name == null ? "" : c2.Name, + c2.Name ?? "", c2.Bounds, !RowsInternal.Contains(draggedToolStrip2.ToolStripPanelRow) ? "unknown" : RowsInternal.IndexOf(draggedToolStrip2.ToolStripPanelRow).ToString(CultureInfo.CurrentCulture), draggedToolStrip2.ToolStripPanelRow.Bounds); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSettings.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSettings.cs index fcdfbec9e7f..00cf7312d04 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSettings.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSettings.cs @@ -188,7 +188,7 @@ internal static string GetItemOrder(ToolStrip toolStrip) for (int i = 0; i < toolStrip.Items.Count; i++) { - itemNames.Append((toolStrip.Items[i].Name == null) ? "null" : toolStrip.Items[i].Name); + itemNames.Append(toolStrip.Items[i].Name ?? "null"); if (i != toolStrip.Items.Count - 1) { itemNames.Append(','); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs index a521f19802b..b7742c5308f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs @@ -1183,7 +1183,7 @@ public string Text { get { - return text == null ? "" : text; + return text ?? ""; } set { @@ -1225,7 +1225,7 @@ public string Name { get { - return name == null ? "" : name; + return name ?? ""; } set { @@ -2239,7 +2239,7 @@ public void Toggle() /// public override string ToString() { - return "TreeNode: " + (text == null ? "" : text); + return "TreeNode: " + (text ?? ""); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs index 630ff549a61..de32b3f358e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs @@ -3042,7 +3042,7 @@ private void CustomDraw(ref Message m) //Simulate default text drawing here TreeNodeStates curState = e.State; - Font font = (node.NodeFont != null) ? node.NodeFont : node.TreeView.Font; + Font font = node.NodeFont ?? node.TreeView.Font; Color color = (((curState & TreeNodeStates.Selected) == TreeNodeStates.Selected) && node.TreeView.Focused) ? SystemColors.HighlightText : (node.ForeColor != Color.Empty) ? node.ForeColor : node.TreeView.ForeColor; // Draw the actual node. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs index fb6c03501aa..632fc6e7cac 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs @@ -2051,7 +2051,7 @@ public void ProgressChange(int progress, int progressMax) public void StatusTextChange(string text) { - parent.statusText = (text == null) ? "" : text; + parent.statusText = text ?? ""; parent.OnStatusTextChanged(EventArgs.Empty); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs index cd89aec65ef..fb5cd6c78b5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs @@ -224,7 +224,7 @@ private IContainer GetParentsContainer() IContainer rval = GetParentIContainer(); Debug.Assert(rval == null || assocContainer == null || rval == assocContainer, "mismatch between getIPD & aContainer"); - return rval == null ? assocContainer : rval; + return rval ?? assocContainer; } private IContainer GetParentIContainer() diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs index f42c9103a66..408b9928c9e 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs @@ -147,7 +147,7 @@ public WindowsFont(string faceName, float size, FontStyle style, byte charSet, W // provides the closest match for the character height rather than the cell height (MSDN). // logFont.lfHeight = -pixelsY; - logFont.lfFaceName = faceName != null ? faceName : defaultFaceName; + logFont.lfFaceName = faceName ?? defaultFaceName; logFont.lfCharSet = charSet; logFont.lfOutPrecision = IntNativeMethods.OUT_TT_PRECIS; logFont.lfQuality = (byte)fontQuality; From 69d8b0eb12daafe7a4e66850d8b0a259b428b0c0 Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Fri, 24 May 2019 12:37:22 -0700 Subject: [PATCH 20/27] remove all instances of IDE0031 warning - null check can be simplified with propogation and elvis operator --- .../Design/Serialization/EnumCodeDomSerializer.cs | 2 +- .../Design/Serialization/ResourceCodeDomSerializer.cs | 2 +- .../src/System/Windows/Forms/Design/ToolStripDesigner.cs | 2 +- .../Windows/Forms/Design/ToolStripMenuItemDesigner.cs | 2 +- src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs | 4 ++-- .../ComponentModel/COM2Interop/COM2PropertyDescriptor.cs | 2 +- .../src/System/Windows/Forms/DataGrid.cs | 4 ++-- src/System.Windows.Forms/src/System/Windows/Forms/Label.cs | 2 +- .../src/System/Windows/Forms/MDIClient.cs | 6 +++--- .../Windows/Forms/PropertyGridInternal/PropertyGridView.cs | 4 ++-- .../src/System/Windows/Forms/ToolStripItem.cs | 4 ++-- .../src/System/Windows/Forms/ToolStripPanelRow.cs | 4 ++-- src/System.Windows.Forms/src/misc/GDI/MeasurementDCInfo.cs | 2 +- 13 files changed, 20 insertions(+), 20 deletions(-) diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EnumCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EnumCodeDomSerializer.cs index 3ef61a29c3f..ac6d06275d5 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EnumCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EnumCodeDomSerializer.cs @@ -79,7 +79,7 @@ public override object Serialize(IDesignerSerializationManager manager, object v TypeConverter enumConverter = new EnumConverter(value.GetType()); foreach (Enum term in values) { - string termString = (enumConverter != null) ? enumConverter.ConvertToString(term) : null; + string termString = enumConverter?.ConvertToString(term); CodeExpression newExpression = !String.IsNullOrEmpty(termString) ? new CodeFieldReferenceExpression(enumType, termString) : null; if (newExpression != null) diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ResourceCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ResourceCodeDomSerializer.cs index f782c5a720f..8e064374981 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ResourceCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ResourceCodeDomSerializer.cs @@ -697,7 +697,7 @@ private CompareValue CompareWithParentValue(string name, object value) bool contains = (rs == null) ? false : rs.ContainsKey(name); if (contains) { - object parentValue = (rs != null) ? rs[name] : null; + object parentValue = rs?[name]; if (parentValue == value) { return CompareValue.Same; diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesigner.cs index 51c57b7a746..728468d6845 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesigner.cs @@ -822,7 +822,7 @@ private bool CheckIfItemSelected() if (parentItem != null) { ToolStripMenuItemDesigner itemDesigner = (ToolStripMenuItemDesigner)_host.GetDesigner(parentItem); - ToolStripDropDown topmost = (itemDesigner == null) ? null : itemDesigner.GetFirstDropDown((ToolStripDropDownItem)parentItem); + ToolStripDropDown topmost = itemDesigner?.GetFirstDropDown((ToolStripDropDownItem)parentItem); ToolStripItem topMostItem = (topmost == null) ? parentItem : topmost.OwnerItem; if (topMostItem != null && topMostItem.Owner == ToolStrip) { diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs index dfbfc45f62c..cf8d89bd2ce 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs @@ -1385,7 +1385,7 @@ protected override Component GetOwnerForActionList() internal override ToolStrip GetMainToolStrip() { ToolStripDropDown topmost = GetFirstDropDown(MenuItem); - ToolStripItem topMostItem = (topmost == null) ? null : topmost.OwnerItem; + ToolStripItem topMostItem = topmost?.OwnerItem; if (topMostItem != null) { return topMostItem.Owner; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs index fa4cd7d1470..015ab5bec16 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs @@ -1905,7 +1905,7 @@ protected override void SetVisibleCore(bool value) private void MakeVisibleWithShow() { ContainerControl f = ContainingControl; - Control ctl = f == null ? null : f.ActiveControl; + Control ctl = f?.ActiveControl; try { DoVerb(OLEIVERB_SHOW); @@ -4752,7 +4752,7 @@ void UnsafeNativeMethods.IPropertyNotifySink.OnChanged(int dispid) // Now notify the change service that the change was successful. // - changeService.OnComponentChanged(host, prop, null, ((prop != null) ? prop.GetValue(host) : null)); + changeService.OnComponentChanged(host, prop, null, (prop?.GetValue(host))); } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs index e840a2fb81b..423a1ae47ea 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs @@ -854,7 +854,7 @@ public virtual string GetDisplayValue(string defaultValue) GetNameItemEvent nie = new GetNameItemEvent(defaultValue); OnGetDisplayValue(nie); - string str = (nie.Name == null ? null : nie.Name.ToString()); + string str = (nie.Name?.ToString()); return str; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs index 7a9f87bc893..391329de64a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs @@ -6879,12 +6879,12 @@ public void Expand(int row) // protected and virtual because the SimpleDropdownDataGrid will override this protected virtual DataGridColumnStyle CreateGridColumn(PropertyDescriptor prop, bool isDefault) { - return myGridTable == null ? null : myGridTable.CreateGridColumn(prop, isDefault); + return myGridTable?.CreateGridColumn(prop, isDefault); } protected virtual DataGridColumnStyle CreateGridColumn(PropertyDescriptor prop) { - return myGridTable == null ? null : myGridTable.CreateGridColumn(prop); + return myGridTable?.CreateGridColumn(prop); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs index ae35c4d0b22..dec340068c4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs @@ -1899,7 +1899,7 @@ public LabelImageIndexer(Label owner) public override ImageList ImageList { - get { return (owner == null) ? null : owner.ImageList; } + get { return owner?.ImageList; } set { Debug.Assert(false, "Setting the image list in this class is not supported"); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs index 87644cdc464..c47c3e6842f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs @@ -116,7 +116,7 @@ protected override CreateParams CreateParams cp.Style |= NativeMethods.WS_VSCROLL | NativeMethods.WS_HSCROLL; cp.ExStyle |= NativeMethods.WS_EX_CLIENTEDGE; cp.Param = new NativeMethods.CLIENTCREATESTRUCT(IntPtr.Zero, 1); - ISite site = (ParentInternal == null) ? null : ParentInternal.Site; + ISite site = ParentInternal?.Site; if (site != null && site.DesignMode) { cp.Style |= NativeMethods.WS_DISABLED; @@ -188,7 +188,7 @@ public void LayoutMdi(MdiLayout value) /// protected override void OnResize(EventArgs e) { - ISite site = (ParentInternal == null) ? null : ParentInternal.Site; + ISite site = ParentInternal?.Site; if (site != null && site.DesignMode && Handle != IntPtr.Zero) { SetWindowRgn(); @@ -235,7 +235,7 @@ protected override void ScaleControl(SizeF factor, BoundsSpecified specified) protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { - ISite site = (ParentInternal == null) ? null : ParentInternal.Site; + ISite site = ParentInternal?.Site; if (IsHandleCreated && (site == null || !site.DesignMode)) { Rectangle oldBounds = Bounds; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs index 9dddf51f4ce..fa08d2e5886 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs @@ -4031,12 +4031,12 @@ protected override void OnPaint(PaintEventArgs pe) #if DEBUG GridEntry debugIPEStart = GetGridEntryFromRow(startRow); GridEntry debugIPEEnd = GetGridEntryFromRow(endRow); - string startName = debugIPEStart == null ? null : debugIPEStart.PropertyLabel; + string startName = debugIPEStart?.PropertyLabel; if (startName == null) { startName = "(null)"; } - string endName = debugIPEEnd == null ? null : debugIPEEnd.PropertyLabel; + string endName = debugIPEEnd?.PropertyLabel; if (endName == null) { endName = "(null)"; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs index 85ce049da4c..ad39b4b892a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs @@ -2047,7 +2047,7 @@ internal ToolStripRenderer Renderer { return Owner.Renderer; } - return (ParentInternal != null) ? ParentInternal.Renderer : null; + return ParentInternal?.Renderer; } } @@ -4906,7 +4906,7 @@ protected virtual ToolStrip ParentInternal { get { - return (ownerItem != null) ? ownerItem.ParentInternal : null; + return ownerItem?.ParentInternal; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs index 6e835eb03ea..1e31feb25f1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs @@ -2446,7 +2446,7 @@ private Control GetControl(int index) if (index < Count && index >= 0) { cell = (ToolStripPanelCell)(InnerList[index]); - control = (cell != null) ? cell.Control : null; + control = cell?.Control; } return control; @@ -2631,7 +2631,7 @@ public virtual object Current { ToolStripPanelCell cell = arrayListEnumerator.Current as ToolStripPanelCell; Debug.Assert(cell != null, "Expected ToolStripPanel cells only!!!" + arrayListEnumerator.Current.GetType().ToString()); - return (cell == null) ? null : cell.Control; + return cell?.Control; } } diff --git a/src/System.Windows.Forms/src/misc/GDI/MeasurementDCInfo.cs b/src/System.Windows.Forms/src/misc/GDI/MeasurementDCInfo.cs index 355a7efa483..ea9bf367a4f 100644 --- a/src/System.Windows.Forms/src/misc/GDI/MeasurementDCInfo.cs +++ b/src/System.Windows.Forms/src/misc/GDI/MeasurementDCInfo.cs @@ -50,7 +50,7 @@ internal static WindowsFont LastUsedFont { get { - return (cachedMeasurementDCInfo == null) ? null : cachedMeasurementDCInfo.LastUsedFont; + return cachedMeasurementDCInfo?.LastUsedFont; } set { From 6a380e174fe443f8f85ba9afa24d889763390a19 Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Fri, 24 May 2019 12:38:08 -0700 Subject: [PATCH 21/27] remove all instances of IDE0034 warning - 'default' expression can be simplified --- .../src/System/Windows/Forms/PropertyStore.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 59562ee5fe6..a794d6e8221 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyStore.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyStore.cs @@ -152,7 +152,7 @@ public int GetInteger(int key, out bool found) if (!LocateIntegerEntry(keyIndex, out int index)) { found = false; - return default(int); + return default; } // We have found the relevant entry. See if @@ -160,7 +160,7 @@ public int GetInteger(int key, out bool found) if (((1 << element) & s_intEntries[index].Mask) == 0) { found = false; - return default(int); + return default; } found = true; @@ -176,7 +176,7 @@ public int GetInteger(int key, out bool found) return s_intEntries[index].Value4; default: Debug.Fail("Invalid element obtained from LocateIntegerEntry"); - return default(int); + return default; } } From 121ad0f955253fecfa2a1e9a16b7f7f73c79cbb5 Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Fri, 24 May 2019 12:43:28 -0700 Subject: [PATCH 22/27] remove all instances of IDE0041 warning - null check can be simplified with coalescence --- src/System.Windows.Forms/src/System/Windows/Forms/Cursor.cs | 4 ++-- .../src/System/Windows/Forms/HtmlDocument.cs | 4 ++-- .../src/System/Windows/Forms/HtmlElement.cs | 4 ++-- .../src/System/Windows/Forms/HtmlWindow.cs | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Cursor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Cursor.cs index 602447951f5..1061e458a71 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Cursor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Cursor.cs @@ -761,12 +761,12 @@ public override string ToString() public static bool operator ==(Cursor left, Cursor right) { - if (object.ReferenceEquals(left, null) != object.ReferenceEquals(right, null)) + if (left is null != right is null) { return false; } - if (!object.ReferenceEquals(left, null)) + if (!(left is null)) { return (left.handle == right.handle); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs index a626b5061d7..3cccc3e9496 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs @@ -953,13 +953,13 @@ public bool onbeforedeactivate(UnsafeNativeMethods.IHTMLEventObj evtObj) public static bool operator ==(HtmlDocument left, HtmlDocument right) { //Not equal if only one's null. - if (object.ReferenceEquals(left, null) != object.ReferenceEquals(right, null)) + if (left is null != right is null) { return false; } //Equal if both are null. - if (object.ReferenceEquals(left, null)) + if (left is null) { return true; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs index 5dc3499bbea..9b82842e4f7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs @@ -1173,13 +1173,13 @@ protected override object GetEventSender() public static bool operator ==(HtmlElement left, HtmlElement right) { //Not equal if only one's null. - if (object.ReferenceEquals(left, null) != object.ReferenceEquals(right, null)) + if (left is null != right is null) { return false; } //Equal if both are null. - if (object.ReferenceEquals(left, null)) + if (left is null) { return true; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindow.cs index 4ea434e2053..5ca88803f0d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindow.cs @@ -579,13 +579,13 @@ public void OnWindowUnload() public static bool operator ==(HtmlWindow left, HtmlWindow right) { //Not equal if only one's null. - if (object.ReferenceEquals(left, null) != object.ReferenceEquals(right, null)) + if (left is null != right is null) { return false; } //Equal if both are null. - if (object.ReferenceEquals(left, null)) + if (left is null) { return true; } From aacca6a0b0b613c96d47428de3a49a83ed67adcd Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Fri, 24 May 2019 12:47:00 -0700 Subject: [PATCH 23/27] remove all instances of IDE0044 warning - make field readonly --- src/Common/src/ClientUtils.cs | 6 +- .../src/DpiHelper.DpiAwarenessContext.cs | 2 +- .../src/Interop/Interop.HandleCollector.cs | 2 +- src/Common/src/SafeNativeMethods.cs | 2 +- .../src/PlatformDetection.cs | 4 +- .../src/TheoryExtensions.cs | 2 +- .../src/System/Drawing/Design/CursorEditor.cs | 2 +- .../System/Windows/Forms/Design/DockEditor.cs | 2 +- .../Forms/Design/ShortcutKeysEditor.cs | 2 +- .../ComponentModel/Design/DesignSurface.cs | 2 +- .../ComponentModel/Design/DesignerHost.cs | 4 +- .../Design/HostDesigntimeLicenseContext.cs | 2 +- .../Design/InheritedPropertyDescriptor.cs | 2 +- .../Design/Serialization/CodeDomSerializer.cs | 2 +- .../Serialization/CodeDomSerializerBase.cs | 2 +- .../ComponentTypeCodeDomSerializer.cs | 2 +- .../DesignerSerializationManager.cs | 8 +-- .../EventMemberCodeDomSerializer.cs | 2 +- .../Design/SiteNestedContainer.cs | 2 +- .../ToolboxComponentsCreatedEventArgs.cs | 2 +- .../src/System/Drawing/Design/ToolboxItem.cs | 2 +- .../Forms/Design/BaseContextMenuStrip.cs | 4 +- .../Forms/Design/Behavior/BehaviorService.cs | 6 +- .../Design/Behavior/DropSourceBehavior.cs | 12 ++-- .../Design/Behavior/LockedHandleGlyph.cs | 2 +- .../Design/Behavior/NoResizeHandleGlyph.cs | 2 +- .../Forms/Design/Behavior/SelectionManager.cs | 4 +- .../Windows/Forms/Design/ComponentTray.cs | 10 +-- .../Forms/Design/ToolStripActionList.cs | 4 +- .../Forms/Design/ToolStripDesignerUtils.cs | 2 +- .../ToolStripItemCustomMenuItemCollection.cs | 4 +- .../Forms/Design/ToolStripMenuItemDesigner.cs | 2 +- .../Forms/Design/ToolStripTemplateNode.cs | 20 +++--- .../Design/DesignerHostTests.cs | 2 +- .../src/System/Resources/ResXDataNode.cs | 8 +-- .../src/System/Resources/ResXFileRef.cs | 2 +- .../System/Resources/ResXResourceReader.cs | 11 ++- .../System/Resources/ResXResourceWriter.cs | 7 +- .../System/Windows/Forms/AccessibleObject.cs | 46 ++++++------- .../src/System/Windows/Forms/Application.cs | 12 ++-- .../System/Windows/Forms/ArrangedElement.cs | 6 +- .../Forms/AutoCompleteStringCollection.cs | 2 +- .../src/System/Windows/Forms/AxHost.cs | 68 +++++++++---------- .../src/System/Windows/Forms/Binding.cs | 2 +- .../System/Windows/Forms/BindingContext.cs | 8 +-- .../System/Windows/Forms/BindingMemberInfo.cs | 4 +- .../src/System/Windows/Forms/BindingSource.cs | 2 +- .../src/System/Windows/Forms/ButtonBase.cs | 2 +- .../Forms/ButtonInternal/ButtonBaseAdapter.cs | 2 +- .../System/Windows/Forms/CheckedListBox.cs | 14 ++-- .../src/System/Windows/Forms/ColorDialog.cs | 2 +- .../src/System/Windows/Forms/ColumnHeader.cs | 4 +- .../src/System/Windows/Forms/ComboBox.cs | 42 ++++++------ .../src/System/Windows/Forms/Command.cs | 2 +- .../Windows/Forms/ComponentManagerBroker.cs | 8 +-- .../COM2Interop/BaseCAMarshaler.cs | 4 +- .../ComponentModel/COM2Interop/COM2Enum.cs | 2 +- .../COM2Interop/COM2ExtendedTypeConverter.cs | 2 +- .../COM2Interop/COM2ExtendedUITypeEditor.cs | 2 +- .../COM2Interop/COM2IDispatchConverter.cs | 4 +- .../COM2IPerPropertyBrowsingHandler.cs | 8 +-- .../COM2Interop/COM2Properties.cs | 14 ++-- .../COM2PropertyBuilderUITypeEditor.cs | 6 +- .../COM2Interop/COM2PropertyDescriptor.cs | 25 ++++--- .../COM2PropertyPageUITypeConverter.cs | 2 +- .../COM2Interop/COM2TypeInfoProcessor.cs | 6 +- .../COM2Interop/ComNativeDescriptor.cs | 10 +-- .../src/System/Windows/Forms/Control.cs | 50 +++++++------- .../Forms/ControlBindingsCollection.cs | 2 +- .../src/System/Windows/Forms/ControlPaint.cs | 8 +-- .../System/Windows/Forms/CurrencyManager.cs | 2 +- .../src/System/Windows/Forms/Cursor.cs | 2 +- .../src/System/Windows/Forms/DataFormats.cs | 2 +- .../src/System/Windows/Forms/DataGrid.cs | 28 ++++---- .../System/Windows/Forms/DataGridCaption.cs | 6 +- .../Windows/Forms/DataGridColumnCollection.cs | 6 +- .../Windows/Forms/DataGridColumnStyle.cs | 2 +- .../Windows/Forms/DataGridParentRows.cs | 16 ++--- .../Windows/Forms/DataGridRelationshipRow.cs | 4 +- .../src/System/Windows/Forms/DataGridRow.cs | 9 ++- .../src/System/Windows/Forms/DataGridState.cs | 2 +- .../src/System/Windows/Forms/DataGridTable.cs | 6 +- .../Windows/Forms/DataGridTableCollection.cs | 4 +- .../Windows/Forms/DataGridTextBoxColumn.cs | 6 +- .../System/Windows/Forms/DataGridToolTip.cs | 2 +- .../src/System/Windows/Forms/DataGridView.cs | 22 +++--- .../Forms/DataGridViewAccessibleObject.cs | 6 +- .../Forms/DataGridViewAdvancedBorderStyle.cs | 4 +- .../Windows/Forms/DataGridViewButtonCell.cs | 6 +- .../Windows/Forms/DataGridViewButtonColumn.cs | 2 +- .../System/Windows/Forms/DataGridViewCell.cs | 4 +- .../Forms/DataGridViewCellCollection.cs | 4 +- .../Forms/DataGridViewCellLinkedList.cs | 4 +- .../DataGridViewCellPaintingEventArgs.cs | 2 +- .../Windows/Forms/DataGridViewCellStyle.cs | 2 +- .../Windows/Forms/DataGridViewCheckBoxCell.cs | 6 +- .../Forms/DataGridViewColumnCollection.cs | 6 +- ...ridViewColumnDesignTimeVisibleAttribute.cs | 2 +- .../Forms/DataGridViewColumnHeaderCell.cs | 2 +- .../Windows/Forms/DataGridViewComboBoxCell.cs | 14 ++-- .../Forms/DataGridViewComboBoxColumn.cs | 2 +- .../DataGridViewComboBoxEditingControl.cs | 2 +- .../Forms/DataGridViewControlCollection.cs | 2 +- .../Forms/DataGridViewDataConnection.cs | 2 +- .../Windows/Forms/DataGridViewHeaderCell.cs | 6 +- .../Windows/Forms/DataGridViewImageCell.cs | 8 +-- .../Windows/Forms/DataGridViewImageColumn.cs | 2 +- .../Forms/DataGridViewIntLinkedList.cs | 2 +- .../Windows/Forms/DataGridViewLinkCell.cs | 6 +- .../Windows/Forms/DataGridViewLinkColumn.cs | 2 +- .../System/Windows/Forms/DataGridViewRow.cs | 4 +- .../Forms/DataGridViewRowCollection.cs | 24 +++---- .../Forms/DataGridViewRowHeaderCell.cs | 4 +- .../DataGridViewSelectedCellCollection.cs | 2 +- ...taGridViewSelectedCellsAccessibleObject.cs | 2 +- .../DataGridViewSelectedColumnCollection.cs | 2 +- .../DataGridViewSelectedRowCollection.cs | 2 +- .../Forms/DataGridViewSortCompareEventArgs.cs | 8 ++- .../Windows/Forms/DataGridViewTextBoxCell.cs | 6 +- .../DataGridViewTextBoxEditingControl.cs | 2 +- .../Windows/Forms/DataGridViewToolTip.cs | 2 +- .../src/System/Windows/Forms/DataObject.cs | 6 +- .../Forms/Design/ComponentEditorForm.cs | 8 +-- .../System/Windows/Forms/DockingAttribute.cs | 2 +- .../src/System/Windows/Forms/DomainUpDown.cs | 6 +- .../System/Windows/Forms/DrawItemEventArgs.cs | 4 +- .../src/System/Windows/Forms/DropSource.cs | 2 +- .../src/System/Windows/Forms/DropTarget.cs | 2 +- .../src/System/Windows/Forms/ErrorProvider.cs | 22 +++--- .../Windows/Forms/FlatButtonAppearance.cs | 2 +- .../System/Windows/Forms/FlowLayoutPanel.cs | 2 +- .../src/System/Windows/Forms/Form.cs | 4 +- .../src/System/Windows/Forms/HtmlDocument.cs | 8 +-- .../src/System/Windows/Forms/HtmlElement.cs | 10 +-- .../Windows/Forms/HtmlElementCollection.cs | 6 +- .../Windows/Forms/HtmlElementEventArgs.cs | 2 +- .../Windows/Forms/HtmlToClrEventProxy.cs | 8 +-- .../src/System/Windows/Forms/HtmlWindow.cs | 6 +- .../Windows/Forms/HtmlWindowCollection.cs | 4 +- .../src/System/Windows/Forms/ImageList.cs | 8 +-- .../System/Windows/Forms/ImageListStreamer.cs | 4 +- .../Forms/KeyboardToolTipStateMachine.cs | 2 +- .../src/System/Windows/Forms/Label.cs | 2 +- .../Forms/Layout/ArrangedElementCollection.cs | 2 +- .../System/Windows/Forms/Layout/FlowLayout.cs | 4 +- .../Windows/Forms/Layout/LayoutSettings.cs | 2 +- .../Windows/Forms/Layout/LayoutUtils.cs | 6 +- .../Windows/Forms/Layout/TableLayout.cs | 14 ++-- .../src/System/Windows/Forms/LinkLabel.cs | 9 ++- .../src/System/Windows/Forms/ListBox.cs | 22 +++--- .../Forms/ListManagerBindingsCollection.cs | 2 +- .../src/System/Windows/Forms/ListView.cs | 22 +++--- .../Windows/Forms/ListViewGroupCollection.cs | 2 +- .../Windows/Forms/ListViewHitTestInfo.cs | 6 +- .../Windows/Forms/ListViewInsertionMark.cs | 2 +- .../src/System/Windows/Forms/ListViewItem.cs | 2 +- .../src/System/Windows/Forms/MDIClient.cs | 4 +- .../System/Windows/Forms/MDIControlStrip.cs | 8 +-- .../src/System/Windows/Forms/MaskedTextBox.cs | 24 +++---- .../src/System/Windows/Forms/Menu.cs | 2 +- .../src/System/Windows/Forms/MenuItem.cs | 6 +- .../src/System/Windows/Forms/Message.cs | 2 +- .../src/System/Windows/Forms/MonthCalendar.cs | 10 +-- .../src/System/Windows/Forms/NativeWindow.cs | 14 ++-- .../src/System/Windows/Forms/NotifyIcon.cs | 6 +- .../NumericUpDownAccelerationCollection.cs | 2 +- .../Windows/Forms/OwnerDrawPropertyBag.cs | 2 +- .../System/Windows/Forms/PaintEventArgs.cs | 2 +- .../src/System/Windows/Forms/PictureBox.cs | 2 +- .../PrintControllerWithStatusDialog.cs | 10 +-- .../Forms/Printing/PrintPreviewDialog.cs | 4 +- .../src/System/Windows/Forms/ProgressBar.cs | 2 +- .../src/System/Windows/Forms/PropertyGrid.cs | 34 +++++----- .../PropertyGridInternal/CategoryGridEntry.cs | 2 +- .../Forms/PropertyGridInternal/DocComment.cs | 6 +- .../PropertyGridInternal/DropDownButton.cs | 4 +- .../Forms/PropertyGridInternal/GridEntry.cs | 16 ++--- .../GridEntryCollection.cs | 2 +- .../PropertyGridInternal/GridErrorDlg.cs | 10 +-- .../Forms/PropertyGridInternal/GridToolTip.cs | 7 +- .../Forms/PropertyGridInternal/HotCommands.cs | 2 +- .../MergePropertyDescriptor.cs | 4 +- .../MultiPropertyDescriptorGridEntry.cs | 4 +- .../MultiSelectRootGridEntry.cs | 2 +- .../PropertyDescriptorGridEntry.cs | 4 +- .../PropertyGridInternal/PropertyGridView.cs | 57 ++++++++-------- .../System/Windows/Forms/PropertyManager.cs | 2 +- .../Windows/Forms/RelatedCurrencyManager.cs | 2 +- .../Forms/RelatedImageListAttribute.cs | 2 +- .../src/System/Windows/Forms/RichTextBox.cs | 2 +- .../src/System/Windows/Forms/Screen.cs | 4 +- .../src/System/Windows/Forms/ScrollBar.cs | 2 +- .../System/Windows/Forms/ScrollProperties.cs | 2 +- .../System/Windows/Forms/ScrollableControl.cs | 2 +- .../src/System/Windows/Forms/SendKeys.cs | 4 +- .../System/Windows/Forms/SplitContainer.cs | 8 +-- .../src/System/Windows/Forms/Splitter.cs | 2 +- .../src/System/Windows/Forms/SplitterPanel.cs | 2 +- .../src/System/Windows/Forms/StatusBar.cs | 12 ++-- .../src/System/Windows/Forms/StringSorter.cs | 10 +-- .../src/System/Windows/Forms/TabControl.cs | 6 +- .../System/Windows/Forms/TableLayoutPanel.cs | 2 +- .../Windows/Forms/TableLayoutSettings.cs | 2 +- .../Windows/Forms/ThreadExceptionDialog.cs | 54 +++++++-------- .../src/System/Windows/Forms/ToolBar.cs | 4 +- .../src/System/Windows/Forms/ToolBarButton.cs | 2 +- .../src/System/Windows/Forms/ToolStrip.cs | 8 +-- .../System/Windows/Forms/ToolStripButton.cs | 2 +- .../System/Windows/Forms/ToolStripComboBox.cs | 4 +- .../Windows/Forms/ToolStripContainer.cs | 16 ++--- .../Windows/Forms/ToolStripControlHost.cs | 4 +- .../System/Windows/Forms/ToolStripDropDown.cs | 2 +- .../Windows/Forms/ToolStripDropDownButton.cs | 4 +- .../Windows/Forms/ToolStripDropDownItem.cs | 2 +- .../Windows/Forms/ToolStripDropDownMenu.cs | 12 ++-- .../Forms/ToolStripDropTargetManager.cs | 2 +- .../src/System/Windows/Forms/ToolStripGrip.cs | 6 +- .../src/System/Windows/Forms/ToolStripItem.cs | 10 +-- .../Windows/Forms/ToolStripItemCollection.cs | 6 +- .../Forms/ToolStripItemTextRenderEventArgs.cs | 2 +- .../System/Windows/Forms/ToolStripLabel.cs | 5 +- .../System/Windows/Forms/ToolStripManager.cs | 8 +-- .../System/Windows/Forms/ToolStripMenuItem.cs | 14 ++-- .../System/Windows/Forms/ToolStripOverflow.cs | 2 +- .../Windows/Forms/ToolStripOverflowButton.cs | 2 +- .../System/Windows/Forms/ToolStripPanel.cs | 8 +-- .../Windows/Forms/ToolStripPanelCell.cs | 2 +- .../System/Windows/Forms/ToolStripPanelRow.cs | 14 ++-- .../Windows/Forms/ToolStripProgressBar.cs | 2 +- .../System/Windows/Forms/ToolStripRenderer.cs | 8 +-- .../Forms/ToolStripRendererSwitcher.cs | 2 +- .../Windows/Forms/ToolStripScrollButton.cs | 4 +- .../Windows/Forms/ToolStripSeparator.cs | 2 +- .../System/Windows/Forms/ToolStripSettings.cs | 4 +- .../Windows/Forms/ToolStripSplitButton.cs | 13 ++-- .../Forms/ToolStripSplitStackLayout.cs | 2 +- .../Windows/Forms/ToolStripStatusLabel.cs | 5 +- .../System/Windows/Forms/ToolStripTextBox.cs | 2 +- .../src/System/Windows/Forms/ToolTip.cs | 15 ++-- .../Forms/ToolstripProfessionalRenderer.cs | 2 +- .../src/System/Windows/Forms/TreeNode.cs | 4 +- .../Windows/Forms/TreeNodeCollection.cs | 2 +- .../Windows/Forms/TreeViewCancelEventArgs.cs | 4 +- .../System/Windows/Forms/TreeViewEventArgs.cs | 4 +- .../Windows/Forms/TreeViewHitTestInfo.cs | 4 +- .../src/System/Windows/Forms/UpDownBase.cs | 10 +-- .../Forms/VisualStyles/VisualStyleElement.cs | 6 +- .../Forms/VisualStyles/VisualStyleRenderer.cs | 2 +- .../src/System/Windows/Forms/WebBrowser.cs | 2 +- .../System/Windows/Forms/WebBrowserBase.cs | 4 +- .../Windows/Forms/WebBrowserContainer.cs | 4 +- .../Windows/Forms/WebBrowserSiteBase.cs | 2 +- .../src/System/Windows/Forms/WinFormsUtils.cs | 8 +-- .../src/System/Windows/Forms/control.ime.cs | 8 +-- .../src/System/Windows/Forms/formatter.cs | 10 +-- .../src/misc/GDI/DeviceContext.cs | 4 +- .../src/misc/GDI/NativeMethods.cs | 2 +- .../src/misc/GDI/WindowsBrush.cs | 4 +- .../src/misc/GDI/WindowsFont.cs | 4 +- .../src/misc/GDI/WindowsPen.cs | 6 +- .../src/misc/InvariantComparer.cs | 2 +- .../src/misc/WeakHashtable.cs | 4 +- .../WinformsControlsTest/Buttons.cs | 2 +- .../Windows/Forms/BaseCollectionTests.cs | 2 +- .../Windows/Forms/FeatureSupportTests.cs | 4 +- 265 files changed, 846 insertions(+), 857 deletions(-) diff --git a/src/Common/src/ClientUtils.cs b/src/Common/src/ClientUtils.cs index 6940d36f20c..a6116d40b29 100644 --- a/src/Common/src/ClientUtils.cs +++ b/src/Common/src/ClientUtils.cs @@ -336,7 +336,7 @@ private static void Debug_NonSequentialEnumIsDefinedCheck(System.Enum value, int internal class WeakRefCollection : IList { private int refCheckThreshold = int.MaxValue; // this means this is disabled by default. - private ArrayList _innerList; + private readonly ArrayList _innerList; internal WeakRefCollection() { @@ -541,8 +541,8 @@ public IEnumerator GetEnumerator() /// internal class WeakRefObject { - int hash; - WeakReference weakHolder; + readonly int hash; + readonly WeakReference weakHolder; internal WeakRefObject(object obj) { diff --git a/src/Common/src/DpiHelper.DpiAwarenessContext.cs b/src/Common/src/DpiHelper.DpiAwarenessContext.cs index f29f7696929..3890474ce39 100644 --- a/src/Common/src/DpiHelper.DpiAwarenessContext.cs +++ b/src/Common/src/DpiHelper.DpiAwarenessContext.cs @@ -45,7 +45,7 @@ public static T CreateInstanceInSystemAwareContext(Func createInstance) private class DpiAwarenessScope : IDisposable { private bool dpiAwarenessScopeIsSet = false; - private DpiAwarenessContext originalAwareness = DpiAwarenessContext.DPI_AWARENESS_CONTEXT_UNSPECIFIED; + private readonly DpiAwarenessContext originalAwareness = DpiAwarenessContext.DPI_AWARENESS_CONTEXT_UNSPECIFIED; /// /// Enters given Dpi awareness scope diff --git a/src/Common/src/Interop/Interop.HandleCollector.cs b/src/Common/src/Interop/Interop.HandleCollector.cs index 54116d67c1e..73b1c361a11 100644 --- a/src/Common/src/Interop/Interop.HandleCollector.cs +++ b/src/Common/src/Interop/Interop.HandleCollector.cs @@ -119,7 +119,7 @@ private class HandleType { internal readonly string _name; - private int _initialThreshHold; + private readonly int _initialThreshHold; private int _threshold; private int _handleCount; private readonly int _deltaPercent; diff --git a/src/Common/src/SafeNativeMethods.cs b/src/Common/src/SafeNativeMethods.cs index 9c141f87651..52ed49c775c 100644 --- a/src/Common/src/SafeNativeMethods.cs +++ b/src/Common/src/SafeNativeMethods.cs @@ -200,7 +200,7 @@ public static extern int FormatMessage(int dwFlags, HandleRef lpSource, int dwMe public static extern bool InitCommonControlsEx(NativeMethods.INITCOMMONCONTROLSEX icc); #if DEBUG - private static System.Collections.ArrayList validImageListHandles = ArrayList.Synchronized(new System.Collections.ArrayList()); + private static readonly System.Collections.ArrayList validImageListHandles = ArrayList.Synchronized(new System.Collections.ArrayList()); #endif // diff --git a/src/Common/tests/InternalUtilitiesForTests/src/PlatformDetection.cs b/src/Common/tests/InternalUtilitiesForTests/src/PlatformDetection.cs index e03960904bb..e7af915c040 100644 --- a/src/Common/tests/InternalUtilitiesForTests/src/PlatformDetection.cs +++ b/src/Common/tests/InternalUtilitiesForTests/src/PlatformDetection.cs @@ -60,7 +60,7 @@ public static partial class PlatformDetection // running in AppContainer when running on .NetNative. public static bool IsNotNetNativeRunningAsConsoleApp => !(IsNetNative && !IsInAppContainer); - private static Lazy m_isWindowsSubsystemForLinux = new Lazy(GetIsWindowsSubsystemForLinux); + private static readonly Lazy m_isWindowsSubsystemForLinux = new Lazy(GetIsWindowsSubsystemForLinux); public static bool IsWindowsSubsystemForLinux => m_isWindowsSubsystemForLinux.Value; public static bool IsNotWindowsSubsystemForLinux => !IsWindowsSubsystemForLinux; @@ -86,7 +86,7 @@ private static bool GetIsWindowsSubsystemForLinux() return false; } - private static Lazy s_largeArrayIsNotSupported = new Lazy(IsLargeArrayNotSupported); + private static readonly Lazy s_largeArrayIsNotSupported = new Lazy(IsLargeArrayNotSupported); [MethodImpl(MethodImplOptions.NoOptimization)] private static bool IsLargeArrayNotSupported() diff --git a/src/Common/tests/InternalUtilitiesForTests/src/TheoryExtensions.cs b/src/Common/tests/InternalUtilitiesForTests/src/TheoryExtensions.cs index 30fda49459b..079ed7fca2a 100644 --- a/src/Common/tests/InternalUtilitiesForTests/src/TheoryExtensions.cs +++ b/src/Common/tests/InternalUtilitiesForTests/src/TheoryExtensions.cs @@ -25,7 +25,7 @@ public static TheoryData ToTheoryData(this IEnumerable data) private class TheoryDataAdapter : TheoryData, IEnumerable { - private IEnumerable _data; + private readonly IEnumerable _data; public TheoryDataAdapter(IEnumerable data) { diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/CursorEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/CursorEditor.cs index 4d6f1c0d6d3..656687783cb 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/CursorEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Drawing/Design/CursorEditor.cs @@ -71,7 +71,7 @@ private class CursorUI : ListBox { private object value; private IWindowsFormsEditorService edSvc; - private TypeConverter cursorConverter; + private readonly TypeConverter cursorConverter; private UITypeEditor editor; public CursorUI(UITypeEditor editor) diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/DockEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/DockEditor.cs index 0d720aae593..1a93d7802d6 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/DockEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/DockEditor.cs @@ -91,7 +91,7 @@ private class DockUI : Control // events whenever they get focus, which is bad when the user is trying // to tab to a specific control using the keyboard. private readonly ContainerPlaceholder container = new ContainerPlaceholder(); - private DockEditor editor; + private readonly DockEditor editor; private IWindowsFormsEditorService edSvc; private readonly CheckBox fill = new DockEditorCheckBox(); private readonly CheckBox left = new DockEditorCheckBox(); diff --git a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/ShortcutKeysEditor.cs b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/ShortcutKeysEditor.cs index 41eb9589075..610d2244b51 100644 --- a/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/ShortcutKeysEditor.cs +++ b/src/System.Windows.Forms.Design.Editors/src/System/Windows/Forms/Design/ShortcutKeysEditor.cs @@ -96,7 +96,7 @@ private class ShortcutKeysUI : UserControl private CheckBox chkCtrl; private CheckBox chkShift; private ComboBox cmbKey; - private ShortcutKeysEditor editor; + private readonly ShortcutKeysEditor editor; private TypeConverter keysConverter; private Label lblKey; private Label lblModifiers; diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignSurface.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignSurface.cs index d446658c655..9e2a637ca04 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignSurface.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignSurface.cs @@ -15,7 +15,7 @@ namespace System.ComponentModel.Design /// public class DesignSurface : IDisposable, IServiceProvider { - private IServiceProvider _parentProvider; + private readonly IServiceProvider _parentProvider; private ServiceContainer _serviceContainer; private DesignerHost _host; private ICollection _loadErrors; diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerHost.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerHost.cs index 7dca64e0c0c..f94248e200d 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerHost.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerHost.cs @@ -22,7 +22,7 @@ internal sealed class DesignerHost : Container, IDesignerLoaderHost2, IDesignerH private static readonly int s_stateUnloading = BitVector32.CreateMask(s_stateLoading); // Designer is currently unloading. private static readonly int s_stateIsClosingTransaction = BitVector32.CreateMask(s_stateUnloading); // A transaction is in the process of being Canceled or Commited. - private static Type[] s_defaultServices = new Type[] { typeof(IDesignerHost), typeof(IContainer), typeof(IComponentChangeService), typeof(IDesignerLoaderHost2) }; + private static readonly Type[] s_defaultServices = new Type[] { typeof(IDesignerHost), typeof(IContainer), typeof(IComponentChangeService), typeof(IDesignerLoaderHost2) }; // IDesignerHost events private static readonly object s_eventActivated = new object(); // Designer has been activated @@ -1532,7 +1532,7 @@ private sealed class DesignerHostTransaction : DesignerTransaction { private DesignerHost _host; #if DEBUG - private string _creatorStack; + private readonly string _creatorStack; #endif public DesignerHostTransaction(DesignerHost host, string description) : base(description) diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/HostDesigntimeLicenseContext.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/HostDesigntimeLicenseContext.cs index b66082755be..8e912c42e0e 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/HostDesigntimeLicenseContext.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/HostDesigntimeLicenseContext.cs @@ -9,7 +9,7 @@ namespace System.ComponentModel.Design /// internal class HostDesigntimeLicenseContext : DesigntimeLicenseContext { - private IServiceProvider provider; + private readonly IServiceProvider provider; public HostDesigntimeLicenseContext(IServiceProvider provider) { diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/InheritedPropertyDescriptor.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/InheritedPropertyDescriptor.cs index 8f8061472a2..34920afc8ba 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/InheritedPropertyDescriptor.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/InheritedPropertyDescriptor.cs @@ -19,7 +19,7 @@ internal class InheritedPropertyDescriptor : PropertyDescriptor { private PropertyDescriptor propertyDescriptor; private object _defaultValue; - private static object s_noDefault = new Object(); + private static readonly object s_noDefault = new Object(); private bool _initShouldSerialize; private object _originalValue; diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializer.cs index 870c9db4411..024151d16a4 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializer.cs @@ -18,7 +18,7 @@ public class CodeDomSerializer : CodeDomSerializerBase private static CodeDomSerializer s_default; private static readonly Attribute[] _runTimeFilter = new Attribute[] { DesignOnlyAttribute.No }; private static readonly Attribute[] _designTimeFilter = new Attribute[] { DesignOnlyAttribute.Yes }; - private static CodeThisReferenceExpression _thisRef = new CodeThisReferenceExpression(); + private static readonly CodeThisReferenceExpression _thisRef = new CodeThisReferenceExpression(); internal static CodeDomSerializer Default { diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs index e717e8bf74b..b15fdd9643a 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/CodeDomSerializerBase.cs @@ -22,7 +22,7 @@ public abstract class CodeDomSerializerBase { private static readonly Attribute[] runTimeProperties = new Attribute[] { DesignOnlyAttribute.No }; private static readonly CodeThisReferenceExpression thisRef = new CodeThisReferenceExpression(); - private static TraceSwitch traceSerialization = new TraceSwitch("DesignerSerialization", "Trace design time serialization"); + private static readonly TraceSwitch traceSerialization = new TraceSwitch("DesignerSerialization", "Trace design time serialization"); private static Stack traceScope = null; /// diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentTypeCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentTypeCodeDomSerializer.cs index d479061d5b6..181ae872347 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentTypeCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/ComponentTypeCodeDomSerializer.cs @@ -16,7 +16,7 @@ namespace System.ComponentModel.Design.Serialization /// internal class ComponentTypeCodeDomSerializer : TypeCodeDomSerializer { - private static object _initMethodKey = new object(); + private static readonly object _initMethodKey = new object(); private const string _initMethodName = "InitializeComponent"; private static ComponentTypeCodeDomSerializer s_default; diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs index 7d991f9390f..cd4acde1bdb 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/DesignerSerializationManager.cs @@ -14,7 +14,7 @@ namespace System.ComponentModel.Design.Serialization /// public class DesignerSerializationManager : IDesignerSerializationManager { - private IServiceProvider provider; + private readonly IServiceProvider provider; private ITypeResolutionService typeResolver; private bool searchedTypeResolver; private bool recycleInstances; @@ -921,7 +921,7 @@ object IServiceProvider.GetService(Type serviceType) /// private sealed class SerializationSession : IDisposable { - private DesignerSerializationManager _serializationManager; + private readonly DesignerSerializationManager _serializationManager; internal SerializationSession(DesignerSerializationManager serializationManager) { @@ -959,8 +959,8 @@ int IEqualityComparer.GetHashCode(object x) /// private sealed class WrappedPropertyDescriptor : PropertyDescriptor { - private object target; - private PropertyDescriptor property; + private readonly object target; + private readonly PropertyDescriptor property; internal WrappedPropertyDescriptor(PropertyDescriptor property, object target) : base(property.Name, null) { diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EventMemberCodeDomSerializer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EventMemberCodeDomSerializer.cs index 2b913b2574c..bfe09d1b224 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EventMemberCodeDomSerializer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/Serialization/EventMemberCodeDomSerializer.cs @@ -15,7 +15,7 @@ namespace System.ComponentModel.Design.Serialization /// internal sealed class EventMemberCodeDomSerializer : MemberCodeDomSerializer { - private static CodeThisReferenceExpression _thisRef = new CodeThisReferenceExpression(); + private static readonly CodeThisReferenceExpression _thisRef = new CodeThisReferenceExpression(); private static EventMemberCodeDomSerializer s_default; internal static EventMemberCodeDomSerializer Default diff --git a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/SiteNestedContainer.cs b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/SiteNestedContainer.cs index 43aa26c3649..bad35d663b2 100644 --- a/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/SiteNestedContainer.cs +++ b/src/System.Windows.Forms.Design/src/System/ComponentModel/Design/SiteNestedContainer.cs @@ -137,7 +137,7 @@ protected override object GetService(Type serviceType) private sealed class NestedSite : DesignerHost.Site, INestedSite { private readonly SiteNestedContainer _container; - private string _name; + private readonly string _name; internal NestedSite(IComponent component, DesignerHost host, string name, Container container) : base(component, host, name, container) { diff --git a/src/System.Windows.Forms.Design/src/System/Drawing/Design/ToolboxComponentsCreatedEventArgs.cs b/src/System.Windows.Forms.Design/src/System/Drawing/Design/ToolboxComponentsCreatedEventArgs.cs index c00465ce485..0aab37716f3 100644 --- a/src/System.Windows.Forms.Design/src/System/Drawing/Design/ToolboxComponentsCreatedEventArgs.cs +++ b/src/System.Windows.Forms.Design/src/System/Drawing/Design/ToolboxComponentsCreatedEventArgs.cs @@ -12,7 +12,7 @@ namespace System.Drawing.Design /// public class ToolboxComponentsCreatedEventArgs : EventArgs { - private IComponent[] _components; + private readonly IComponent[] _components; /// /// Initializes a new instance of the internal class BaseContextMenuStrip : GroupedContextMenuStrip { - private IServiceProvider serviceProvider; - private Component component; + private readonly IServiceProvider serviceProvider; + private readonly Component component; private ToolStripMenuItem selectionMenuItem; public BaseContextMenuStrip(IServiceProvider provider, Component component) : base() diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs index 4c30c540083..973db31e190 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs @@ -57,7 +57,7 @@ public sealed class BehaviorService : IDisposable private bool _cancelDrag = false; // should we cancel the drag on the next QueryContinueDrag - private int _adornerWindowIndex = -1; + private readonly int _adornerWindowIndex = -1; //test hooks for SnapLines private static int WM_GETALLSNAPLINES; @@ -605,10 +605,10 @@ internal void OnLoseCapture() /// private class AdornerWindow : Control { - private BehaviorService _behaviorService;//ptr back to BehaviorService + private readonly BehaviorService _behaviorService;//ptr back to BehaviorService private Control _designerFrame;//the designer's frame private static MouseHook s_mouseHook; // shared mouse hook - private static List s_adornerWindowList = new List(); + private static readonly List s_adornerWindowList = new List(); private bool _processingDrag; // is this particular window in a drag operation /// diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/DropSourceBehavior.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/DropSourceBehavior.cs index 587fbf7272d..30a651cc428 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/DropSourceBehavior.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/DropSourceBehavior.cs @@ -25,17 +25,17 @@ private struct DragComponent public Point positionOffset; //control position offset from primary selection }; - private DragComponent[] dragComponents; + private readonly DragComponent[] dragComponents; private ArrayList dragObjects; // used to initialize the DragAssistanceManager - private BehaviorDataObject data;//drag data that represents the controls we're dragging & the effect/action - private DragDropEffects allowedEffects;//initial allowed effects for the drag operation + private readonly BehaviorDataObject data;//drag data that represents the controls we're dragging & the effect/action + private readonly DragDropEffects allowedEffects;//initial allowed effects for the drag operation private DragDropEffects lastEffect;//the last effect we saw (used for determining a valid drop) private bool targetAllowsSnapLines;//indicates if the drop target allows snaplines (flowpanels don't for ex) private IComponent lastDropTarget;//indicates the drop target on the last 'give feedback' event private Point lastSnapOffset;//the last snapoffset we used. // These 2 could be different (e.g. if dropping between forms) - private BehaviorService behaviorServiceSource;//ptr back to the BehaviorService in the drop source + private readonly BehaviorService behaviorServiceSource;//ptr back to the BehaviorService in the drop source private BehaviorService behaviorServiceTarget;//ptr back to the BehaviorService in the drop target //this object will integrate SnapLines into the drag @@ -43,7 +43,7 @@ private struct DragComponent private Graphics graphicsTarget;//graphics object of the adornerwindows (via BehaviorService) in drop target - private IServiceProvider serviceProviderSource; + private readonly IServiceProvider serviceProviderSource; private IServiceProvider serviceProviderTarget; private Point initialMouseLoc;//original mouse location in screen coordinates @@ -62,7 +62,7 @@ private struct DragComponent private bool cleanedUpDrag = false; private StatusCommandUI statusCommandUITarget;// UI for setting the StatusBar Information in the drop target - private IDesignerHost srcHost; + private readonly IDesignerHost srcHost; private IDesignerHost destHost; private bool currentShowState = true; // Initially the controls are showing diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/LockedHandleGlyph.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/LockedHandleGlyph.cs index c2111519b10..f5adc9e291f 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/LockedHandleGlyph.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/LockedHandleGlyph.cs @@ -11,7 +11,7 @@ namespace System.Windows.Forms.Design.Behavior /// internal class LockedHandleGlyph : SelectionGlyphBase { - private bool _isPrimary = false; + private readonly bool _isPrimary = false; /// /// LockedHandleGlyph's constructor takes additional parameters: 'type' and 'primary selection'. Also, we create/cache our pen & brush here to avoid this action with every paint message. diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/NoResizeHandleGlyph.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/NoResizeHandleGlyph.cs index 4b6c6d9cf24..59cb8546f1c 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/NoResizeHandleGlyph.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/NoResizeHandleGlyph.cs @@ -11,7 +11,7 @@ namespace System.Windows.Forms.Design.Behavior /// internal class NoResizeHandleGlyph : SelectionGlyphBase { - private bool _isPrimary = false; + private readonly bool _isPrimary = false; /// /// NoResizeHandleGlyph's constructor takes additional parameters: 'type' and 'primary selection'. Also, we create/cache our pen & brush here to avoid this action with every paint message. diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/SelectionManager.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/SelectionManager.cs index 057be900027..0b504cdae9c 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/SelectionManager.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/SelectionManager.cs @@ -20,8 +20,8 @@ internal sealed class SelectionManager : IDisposable private Adorner bodyAdorner;//used to track all body glyphs for each control private BehaviorService behaviorService;//ptr back to our BehaviorService private IServiceProvider serviceProvider;//standard service provider - private Hashtable componentToDesigner;//used for quick look up of designers related to comps - private Control rootComponent;//root component being designed + private readonly Hashtable componentToDesigner;//used for quick look up of designers related to comps + private readonly Control rootComponent;//root component being designed private ISelectionService selSvc;//we cache the selection service for perf. private IDesignerHost designerHost;//we cache the designerhost for perf. private bool needRefresh; // do we need to refresh? diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentTray.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentTray.cs index 1b9935814eb..87e323e091a 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentTray.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentTray.cs @@ -42,7 +42,7 @@ public class ComponentTray : ScrollableControl, IExtenderProvider, ISelectionUIH /// internal OleDragDropHandler oleDragDropHandler; // handler class for ole drag drop operations. - private IDesigner mainDesigner; // the designer that is associated with this tray + private readonly IDesigner mainDesigner; // the designer that is associated with this tray private IEventHandlerService eventHandlerService = null; // Event Handler service to handle keyboard and focus. private bool queriedTabOrder; private MenuCommand tabOrderCommand; @@ -50,7 +50,7 @@ public class ComponentTray : ScrollableControl, IExtenderProvider, ISelectionUIH // Services that we use on a high enough frequency to merit caching. private IMenuCommandService menuCommandService; - private CommandSet privateCommandSet = null; + private readonly CommandSet privateCommandSet = null; private InheritanceUI inheritanceUI; private Point mouseDragStart = InvalidPoint; // the starting location of a drag @@ -63,9 +63,9 @@ public class ComponentTray : ScrollableControl, IExtenderProvider, ISelectionUIH private Point autoScrollPosBeforeDragging = Point.Empty;//Used to return the correct scroll pos. after a drag // Component Tray Context menu items... - private MenuCommand menucmdArrangeIcons = null; - private MenuCommand menucmdLineupIcons = null; - private MenuCommand menucmdLargeIcons = null; + private readonly MenuCommand menucmdArrangeIcons = null; + private readonly MenuCommand menucmdLineupIcons = null; + private readonly MenuCommand menucmdLargeIcons = null; private bool fResetAmbient = false; private bool fSelectionChanged = false; private ComponentTrayGlyphManager glyphManager;//used to manage any glyphs added to the tray diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripActionList.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripActionList.cs index 092a034e179..e7e95c26fc5 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripActionList.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripActionList.cs @@ -15,8 +15,8 @@ internal class ToolStripActionList : DesignerActionList private bool _autoShow = false; private readonly ToolStripDesigner _designer; - private ChangeToolStripParentVerb _changeParentVerb = null; - private StandardMenuStripVerb _standardItemsVerb = null; + private readonly ChangeToolStripParentVerb _changeParentVerb = null; + private readonly StandardMenuStripVerb _standardItemsVerb = null; public ToolStripActionList(ToolStripDesigner designer) : base(designer.Component) { diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesignerUtils.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesignerUtils.cs index 51152ff1f05..3d34cac65c8 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesignerUtils.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesignerUtils.cs @@ -29,7 +29,7 @@ internal sealed class ToolStripDesignerUtils [ThreadStatic] private static Dictionary s_cachedWinformsImages; - private static string s_systemWindowsFormsNamespace = typeof(ToolStripItem).Namespace; + private static readonly string s_systemWindowsFormsNamespace = typeof(ToolStripItem).Namespace; private ToolStripDesignerUtils() { diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs index 90e5f55f90d..392ccb689fa 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs @@ -15,8 +15,8 @@ namespace System.Windows.Forms.Design /// internal class ToolStripItemCustomMenuItemCollection : CustomMenuItemCollection { - private ToolStripItem currentItem; - private IServiceProvider serviceProvider; + private readonly ToolStripItem currentItem; + private readonly IServiceProvider serviceProvider; private ToolStripMenuItem imageToolStripMenuItem; private ToolStripMenuItem enabledToolStripMenuItem; diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs index cf8d89bd2ce..7786eacef9f 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs @@ -2589,7 +2589,7 @@ internal class DropDownBehavior : ControlDesigner.TransparentBehavior /// /// Constructor that accepts the related ControlDesigner. /// - private ToolStripMenuItemDesigner menuItemDesigner; + private readonly ToolStripMenuItemDesigner menuItemDesigner; internal DropDownBehavior(ControlDesigner designer, ToolStripMenuItemDesigner menuItemDesigner) : base(designer) { diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripTemplateNode.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripTemplateNode.cs index 245cde7ac6b..6a62aabc14b 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripTemplateNode.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripTemplateNode.cs @@ -1486,8 +1486,8 @@ internal void SetWidth(string text) /// private class TemplateTextBox : TextBox { - TransparentToolStrip parent; - ToolStripTemplateNode owner; + readonly TransparentToolStrip parent; + readonly ToolStripTemplateNode owner; private const int IMEMODE = 229; public TemplateTextBox(TransparentToolStrip parent, ToolStripTemplateNode owner) : base() @@ -1574,8 +1574,8 @@ protected override void WndProc(ref Message m) /// public class TransparentToolStrip : ToolStrip { - ToolStripTemplateNode owner; - IComponent currentItem; + readonly ToolStripTemplateNode owner; + readonly IComponent currentItem; public TransparentToolStrip(ToolStripTemplateNode owner) { @@ -1778,12 +1778,12 @@ public void Collapse() public class MiniToolStripRenderer : ToolStripSystemRenderer { private int state = (int)TemplateNodeSelectionState.None; - private Color selectedBorderColor; - private Color defaultBorderColor; - private Color dropDownMouseOverColor; - private Color dropDownMouseDownColor; - private Color toolStripBorderColor; - private ToolStripTemplateNode owner; + private readonly Color selectedBorderColor; + private readonly Color defaultBorderColor; + private readonly Color dropDownMouseOverColor; + private readonly Color dropDownMouseDownColor; + private readonly Color toolStripBorderColor; + private readonly ToolStripTemplateNode owner; private Rectangle hotRegion = Rectangle.Empty; public MiniToolStripRenderer(ToolStripTemplateNode owner) : base() diff --git a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerHostTests.cs b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerHostTests.cs index 945f29351f0..47fc79c4c83 100644 --- a/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerHostTests.cs +++ b/src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerHostTests.cs @@ -1139,7 +1139,7 @@ public void DesignerHost_GetService_NullType_ThrowsArgumentNullException() Assert.Throws("service", () => host.GetService(null)); } - private static IDesignerHost s_placeholderHost = new Mock(MockBehavior.Strict).Object; + private static readonly IDesignerHost s_placeholderHost = new Mock(MockBehavior.Strict).Object; public static IEnumerable ChangeActiveDesigner_TestData() { diff --git a/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs b/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs index ae76b504629..df11cd21aed 100644 --- a/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs +++ b/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs @@ -53,7 +53,7 @@ public sealed class ResXDataNode : ISerializable private IFormatter binaryFormatter = null; // this is going to be used to check if a ResXDataNode is of type ResXFileRef - private static ITypeResolutionService internalTypeResolver = new AssemblyNamesTypeResolutionService(new AssemblyName[] { new AssemblyName("System.Windows.Forms") }); + private static readonly ITypeResolutionService internalTypeResolver = new AssemblyNamesTypeResolutionService(new AssemblyName[] { new AssemblyName("System.Windows.Forms") }); // call back function to get type name for multitargeting. // No public property to force using constructors for the following reasons: @@ -837,8 +837,8 @@ internal DataNodeInfo Clone() // internal class ResXSerializationBinder : SerializationBinder { - private ITypeResolutionService typeResolver; - private Func typeNameConverter; + private readonly ITypeResolutionService typeResolver; + private readonly Func typeNameConverter; internal ResXSerializationBinder(ITypeResolutionService typeResolver) { @@ -937,7 +937,7 @@ internal class AssemblyNamesTypeResolutionService : ITypeResolutionService private Hashtable cachedAssemblies; private Hashtable cachedTypes; - private static string NetFrameworkPath = Path.Combine(Environment.GetEnvironmentVariable("SystemRoot"), "Microsoft.Net\\Framework"); + private static readonly string NetFrameworkPath = Path.Combine(Environment.GetEnvironmentVariable("SystemRoot"), "Microsoft.Net\\Framework"); internal AssemblyNamesTypeResolutionService(AssemblyName[] names) { diff --git a/src/System.Windows.Forms/src/System/Resources/ResXFileRef.cs b/src/System.Windows.Forms/src/System/Resources/ResXFileRef.cs index 8e270240073..40c1e7d08ea 100644 --- a/src/System.Windows.Forms/src/System/Resources/ResXFileRef.cs +++ b/src/System.Windows.Forms/src/System/Resources/ResXFileRef.cs @@ -30,7 +30,7 @@ namespace System.Resources public class ResXFileRef { private string fileName; - private string typeName; + private readonly string typeName; [OptionalField(VersionAdded = 2)] private Encoding textFileEncoding; diff --git a/src/System.Windows.Forms/src/System/Resources/ResXResourceReader.cs b/src/System.Windows.Forms/src/System/Resources/ResXResourceReader.cs index 8dd7056cc43..6cbfa8ed7a1 100644 --- a/src/System.Windows.Forms/src/System/Resources/ResXResourceReader.cs +++ b/src/System.Windows.Forms/src/System/Resources/ResXResourceReader.cs @@ -28,16 +28,15 @@ namespace System.Resources /// public class ResXResourceReader : IResourceReader { - string fileName = null; + readonly string fileName = null; TextReader reader = null; Stream stream = null; string fileContents = null; - AssemblyName[] assemblyNames; + readonly AssemblyName[] assemblyNames; string basePath; bool isReaderDirty = false; - - ITypeResolutionService typeResolver; - IAliasResolver aliasResolver = null; + readonly ITypeResolutionService typeResolver; + readonly IAliasResolver aliasResolver = null; ListDictionary resData = null; ListDictionary resMetadata = null; @@ -712,7 +711,7 @@ private string GetTypeFromTypeName(string typeName) private sealed class ReaderAliasResolver : IAliasResolver { - private Hashtable cachedAliases; + private readonly Hashtable cachedAliases; internal ReaderAliasResolver() { diff --git a/src/System.Windows.Forms/src/System/Resources/ResXResourceWriter.cs b/src/System.Windows.Forms/src/System/Resources/ResXResourceWriter.cs index fd5060d4600..8861d4e21c7 100644 --- a/src/System.Windows.Forms/src/System/Resources/ResXResourceWriter.cs +++ b/src/System.Windows.Forms/src/System/Resources/ResXResourceWriter.cs @@ -43,7 +43,7 @@ public class ResXResourceWriter : IResourceWriter private Hashtable cachedAliases; - private static TraceSwitch ResValueProviderSwitch = new TraceSwitch("ResX", "Debug the resource value provider"); + private static readonly TraceSwitch ResValueProviderSwitch = new TraceSwitch("ResX", "Debug the resource value provider"); internal static readonly string Beta2CompatSerializedObjectMimeType = "text/microsoft-urt/psuedoml-serialized/base64"; @@ -113,8 +113,7 @@ public class ResXResourceWriter : IResourceWriter "; - - string fileName; + readonly string fileName; Stream stream; TextWriter textWriter; XmlTextWriter xmlTextWriter; @@ -122,7 +121,7 @@ public class ResXResourceWriter : IResourceWriter bool hasBeenSaved; bool initialized; - private Func typeNameConverter; // no public property to be consistent with ResXDataNode class. + private readonly Func typeNameConverter; // no public property to be consistent with ResXDataNode class. /// /// Base Path for ResXFileRefs. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleObject.cs index 5ddb2460c77..603baeb1b48 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AccessibleObject.cs @@ -59,7 +59,7 @@ public class AccessibleObject : StandardOleMarshalObject, // IOleWindow interface of the 'inner' system IAccessible object that we are wrapping private UnsafeNativeMethods.IOleWindow systemIOleWindow = null; - private bool systemWrapper = false; // Indicates this object is being used ONLY to wrap a system IAccessible + private readonly bool systemWrapper = false; // Indicates this object is being used ONLY to wrap a system IAccessible private int accObjId = NativeMethods.OBJID_CLIENT; // Indicates what kind of 'inner' system accessible object we are using @@ -2464,7 +2464,7 @@ internal virtual void ScrollIntoView() private class EnumVariantObject : UnsafeNativeMethods.IEnumVariant { private int currentChild = 0; - private AccessibleObject owner; + private readonly AccessibleObject owner; public EnumVariantObject(AccessibleObject owner) { @@ -2682,30 +2682,30 @@ internal sealed class InternalAccessibleObject : StandardOleMarshalObject, { private IAccessible publicIAccessible; // AccessibleObject as IAccessible - private UnsafeNativeMethods.IEnumVariant publicIEnumVariant; // AccessibleObject as IEnumVariant - private UnsafeNativeMethods.IOleWindow publicIOleWindow; // AccessibleObject as IOleWindow - private IReflect publicIReflect; // AccessibleObject as IReflect + private readonly UnsafeNativeMethods.IEnumVariant publicIEnumVariant; // AccessibleObject as IEnumVariant + private readonly UnsafeNativeMethods.IOleWindow publicIOleWindow; // AccessibleObject as IOleWindow + private readonly IReflect publicIReflect; // AccessibleObject as IReflect - private UnsafeNativeMethods.IServiceProvider publicIServiceProvider; // AccessibleObject as IServiceProvider - private UnsafeNativeMethods.IAccessibleEx publicIAccessibleEx; // AccessibleObject as IAccessibleEx + private readonly UnsafeNativeMethods.IServiceProvider publicIServiceProvider; // AccessibleObject as IServiceProvider + private readonly UnsafeNativeMethods.IAccessibleEx publicIAccessibleEx; // AccessibleObject as IAccessibleEx // UIAutomation - private UnsafeNativeMethods.IRawElementProviderSimple publicIRawElementProviderSimple; // AccessibleObject as IRawElementProviderSimple - private UnsafeNativeMethods.IRawElementProviderFragment publicIRawElementProviderFragment;// AccessibleObject as IRawElementProviderFragment - private UnsafeNativeMethods.IRawElementProviderFragmentRoot publicIRawElementProviderFragmentRoot;// AccessibleObject as IRawElementProviderFragmentRoot - private UnsafeNativeMethods.IInvokeProvider publicIInvokeProvider; // AccessibleObject as IInvokeProvider - private UnsafeNativeMethods.IValueProvider publicIValueProvider; // AccessibleObject as IValueProvider - private UnsafeNativeMethods.IRangeValueProvider publicIRangeValueProvider; // AccessibleObject as IRangeValueProvider - private UnsafeNativeMethods.IExpandCollapseProvider publicIExpandCollapseProvider; // AccessibleObject as IExpandCollapseProvider - private UnsafeNativeMethods.IToggleProvider publicIToggleProvider; // AccessibleObject as IToggleProvider - private UnsafeNativeMethods.ITableProvider publicITableProvider; // AccessibleObject as ITableProvider - private UnsafeNativeMethods.ITableItemProvider publicITableItemProvider; // AccessibleObject as ITableItemProvider - private UnsafeNativeMethods.IGridProvider publicIGridProvider; // AccessibleObject as IGridProvider - private UnsafeNativeMethods.IGridItemProvider publicIGridItemProvider; // AccessibleObject as IGridItemProvider - private UnsafeNativeMethods.ILegacyIAccessibleProvider publicILegacyIAccessibleProvider; // AccessibleObject as ILegayAccessibleProvider - private UnsafeNativeMethods.ISelectionProvider publicISelectionProvider; // AccessibleObject as ISelectionProvider - private UnsafeNativeMethods.ISelectionItemProvider publicISelectionItemProvider; // AccessibleObject as ISelectionItemProvider - private UnsafeNativeMethods.IRawElementProviderHwndOverride publicIRawElementProviderHwndOverride; // AccessibleObject as IRawElementProviderHwndOverride + private readonly UnsafeNativeMethods.IRawElementProviderSimple publicIRawElementProviderSimple; // AccessibleObject as IRawElementProviderSimple + private readonly UnsafeNativeMethods.IRawElementProviderFragment publicIRawElementProviderFragment;// AccessibleObject as IRawElementProviderFragment + private readonly UnsafeNativeMethods.IRawElementProviderFragmentRoot publicIRawElementProviderFragmentRoot;// AccessibleObject as IRawElementProviderFragmentRoot + private readonly UnsafeNativeMethods.IInvokeProvider publicIInvokeProvider; // AccessibleObject as IInvokeProvider + private readonly UnsafeNativeMethods.IValueProvider publicIValueProvider; // AccessibleObject as IValueProvider + private readonly UnsafeNativeMethods.IRangeValueProvider publicIRangeValueProvider; // AccessibleObject as IRangeValueProvider + private readonly UnsafeNativeMethods.IExpandCollapseProvider publicIExpandCollapseProvider; // AccessibleObject as IExpandCollapseProvider + private readonly UnsafeNativeMethods.IToggleProvider publicIToggleProvider; // AccessibleObject as IToggleProvider + private readonly UnsafeNativeMethods.ITableProvider publicITableProvider; // AccessibleObject as ITableProvider + private readonly UnsafeNativeMethods.ITableItemProvider publicITableItemProvider; // AccessibleObject as ITableItemProvider + private readonly UnsafeNativeMethods.IGridProvider publicIGridProvider; // AccessibleObject as IGridProvider + private readonly UnsafeNativeMethods.IGridItemProvider publicIGridItemProvider; // AccessibleObject as IGridItemProvider + private readonly UnsafeNativeMethods.ILegacyIAccessibleProvider publicILegacyIAccessibleProvider; // AccessibleObject as ILegayAccessibleProvider + private readonly UnsafeNativeMethods.ISelectionProvider publicISelectionProvider; // AccessibleObject as ISelectionProvider + private readonly UnsafeNativeMethods.ISelectionItemProvider publicISelectionItemProvider; // AccessibleObject as ISelectionItemProvider + private readonly UnsafeNativeMethods.IRawElementProviderHwndOverride publicIRawElementProviderHwndOverride; // AccessibleObject as IRawElementProviderHwndOverride /// /// Create a new wrapper. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs index 9f0efbb687c..707c4ec40e8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs @@ -54,7 +54,7 @@ public sealed class Application static bool comCtlSupportsVisualStylesInitialized = false; static bool comCtlSupportsVisualStyles = false; private static FormCollection s_forms = null; - private static object internalSyncObject = new object(); + private static readonly object internalSyncObject = new object(); static bool useWaitCursor = false; private static bool useEverettThreadAffinity = false; @@ -2280,12 +2280,12 @@ internal sealed class ThreadContext : MarshalByRefObject, UnsafeNativeMethods.IM private const int STATE_TRACKINGCOMPONENT = 0x00000020; private const int INVALID_ID = unchecked((int)0xFFFFFFFF); - private static Hashtable contextHash = new Hashtable(); + private static readonly Hashtable contextHash = new Hashtable(); // When this gets to zero, we'll invoke a full garbage // collect and check for root/window leaks. // - private static object tcInternalSyncObject = new object(); + private static readonly object tcInternalSyncObject = new object(); private static int totalMessageLoopCount; private static int baseLoopReason; @@ -2300,14 +2300,14 @@ internal sealed class ThreadContext : MarshalByRefObject, UnsafeNativeMethods.IM private ApplicationContext applicationContext; // Parking window list - private List parkingWindows = new List(); + private readonly List parkingWindows = new List(); private Control marshalingControl; private CultureInfo culture; private List messageFilters; private List messageFilterSnapshot; private int inProcessFilters = 0; private IntPtr handle; - private int id; + private readonly int id; private int messageLoopCount; private int threadState; private int modalCount; @@ -4336,7 +4336,7 @@ private sealed class ThreadWindows private IntPtr activeHwnd; private IntPtr focusedHwnd; internal ThreadWindows previousThreadWindows; - private bool onlyWinForms = true; + private readonly bool onlyWinForms = true; internal ThreadWindows(bool onlyWinForms) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ArrangedElement.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ArrangedElement.cs index 441127aea1c..1ad1de5d522 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ArrangedElement.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ArrangedElement.cs @@ -24,8 +24,8 @@ internal abstract class ArrangedElement : Component, IArrangedElement private Rectangle bounds = Rectangle.Empty; private IArrangedElement parent = null; private BitVector32 state = new BitVector32(); - private PropertyStore propertyStore = new PropertyStore(); // Contains all properties that are not always set. - private int suspendCount = 0; + private readonly PropertyStore propertyStore = new PropertyStore(); // Contains all properties that are not always set. + private readonly int suspendCount = 0; private static readonly int stateVisible = BitVector32.CreateMask(); private static readonly int stateDisposing = BitVector32.CreateMask(stateVisible); @@ -33,7 +33,7 @@ internal abstract class ArrangedElement : Component, IArrangedElement private static readonly int PropControlsCollection = PropertyStore.CreateKey(); - private Control spacer = new Control(); + private readonly Control spacer = new Control(); internal ArrangedElement() { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AutoCompleteStringCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AutoCompleteStringCollection.cs index bbb3c358945..f1c6e580e67 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AutoCompleteStringCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AutoCompleteStringCollection.cs @@ -17,7 +17,7 @@ public class AutoCompleteStringCollection : IList { CollectionChangeEventHandler onCollectionChanged; - private ArrayList data = new ArrayList(); + private readonly ArrayList data = new ArrayList(); public AutoCompleteStringCollection() { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs index 015ab5bec16..94b6eb68b2c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs @@ -48,11 +48,11 @@ namespace System.Windows.Forms public abstract class AxHost : Control, ISupportInitialize, ICustomTypeDescriptor { - private static TraceSwitch AxHTraceSwitch = new TraceSwitch("AxHTrace", "ActiveX handle tracing"); - private static TraceSwitch AxPropTraceSwitch = new TraceSwitch("AxPropTrace", "ActiveX property tracing"); - private static TraceSwitch AxHostSwitch = new TraceSwitch("AxHost", "ActiveX host creation"); - private static BooleanSwitch AxIgnoreTMSwitch = new BooleanSwitch("AxIgnoreTM", "ActiveX switch to ignore thread models"); - private static BooleanSwitch AxAlwaysSaveSwitch = new BooleanSwitch("AxAlwaysSave", "ActiveX to save all controls regardless of their IsDirty function return value"); + private static readonly TraceSwitch AxHTraceSwitch = new TraceSwitch("AxHTrace", "ActiveX handle tracing"); + private static readonly TraceSwitch AxPropTraceSwitch = new TraceSwitch("AxPropTrace", "ActiveX property tracing"); + private static readonly TraceSwitch AxHostSwitch = new TraceSwitch("AxHost", "ActiveX host creation"); + private static readonly BooleanSwitch AxIgnoreTMSwitch = new BooleanSwitch("AxIgnoreTM", "ActiveX switch to ignore thread models"); + private static readonly BooleanSwitch AxAlwaysSaveSwitch = new BooleanSwitch("AxAlwaysSave", "ActiveX to save all controls regardless of their IsDirty function return value"); /// /// Flags which may be passed to the AxHost constructor @@ -84,10 +84,10 @@ internal class AxFlags internal const int IgnoreThreadModel = 0x10000000; } - private static COMException E_NOTIMPL = new COMException(SR.AXNotImplemented, unchecked((int)0x80000001)); - private static COMException E_INVALIDARG = new COMException(SR.AXInvalidArgument, unchecked((int)0x80070057)); - private static COMException E_FAIL = new COMException(SR.AXUnknownError, unchecked((int)0x80004005)); - private static COMException E_NOINTERFACE = new COMException(SR.AxInterfaceNotSupported, unchecked((int)0x80004002)); + private static readonly COMException E_NOTIMPL = new COMException(SR.AXNotImplemented, unchecked((int)0x80000001)); + private static readonly COMException E_INVALIDARG = new COMException(SR.AXInvalidArgument, unchecked((int)0x80070057)); + private static readonly COMException E_FAIL = new COMException(SR.AXUnknownError, unchecked((int)0x80004005)); + private static readonly COMException E_NOINTERFACE = new COMException(SR.AxInterfaceNotSupported, unchecked((int)0x80004002)); private const int INPROC_SERVER = 1; private const int OC_PASSIVE = 0; @@ -174,7 +174,7 @@ internal class AxFlags private int ocState = OC_PASSIVE; private int miscStatusBits; private int freezeCount = 0; - private int flags = 0; + private readonly int flags = 0; private int selectionStyle = 0; private int editMode = EDITM_NONE; private int noComponentChange = 0; @@ -217,17 +217,17 @@ internal class AxFlags private UnsafeNativeMethods.IPersistStorage iPersistStorage; private AboutBoxDelegate aboutBoxDelegate = null; - private EventHandler selectionChangeHandler; + private readonly EventHandler selectionChangeHandler; - private bool isMaskEdit; + private readonly bool isMaskEdit; private bool ignoreDialogKeys; - private EventHandler onContainerVisibleChanged; + private readonly EventHandler onContainerVisibleChanged; // These should be in the order given by the PROPCAT_X values // Also, note that they are not to be localized... - private static CategoryAttribute[] categoryNames = new CategoryAttribute[] { + private static readonly CategoryAttribute[] categoryNames = new CategoryAttribute[] { null, new WinCategoryAttribute("Default"), new WinCategoryAttribute("Default"), @@ -3880,7 +3880,7 @@ protected override void OnHandleCreated(EventArgs e) [AttributeUsage(AttributeTargets.Class, Inherited = false)] public sealed class ClsidAttribute : Attribute { - private string val; + private readonly string val; public ClsidAttribute(string clsid) { @@ -3899,7 +3899,7 @@ public string Value [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class TypeLibraryTimeStampAttribute : Attribute { - private DateTime val; + private readonly DateTime val; public TypeLibraryTimeStampAttribute(string timestamp) { @@ -3921,7 +3921,7 @@ public class ConnectionPointCookie private int cookie; internal int threadId; #if DEBUG - private string callStack; + private readonly string callStack; #endif /// /// Creates a connection point to of the given interface type. @@ -4098,8 +4098,8 @@ public enum ActiveXInvokeKind public class InvalidActiveXStateException : Exception { - private string name; - private ActiveXInvokeKind kind; + private readonly string name; + private readonly ActiveXInvokeKind kind; public InvalidActiveXStateException(string name, ActiveXInvokeKind kind) { @@ -4136,7 +4136,7 @@ private class OleInterfaces : UnsafeNativeMethods.IOleControlSite, UnsafeNativeMethods.IOleClientSite, UnsafeNativeMethods.IOleInPlaceSite, UnsafeNativeMethods.ISimpleFrameSite, UnsafeNativeMethods.IVBGetControl, UnsafeNativeMethods.IGetVBAObject, UnsafeNativeMethods.IPropertyNotifySink, IReflect, IDisposable { - private AxHost host; + private readonly AxHost host; private ConnectionPointCookie connectionPoint; internal OleInterfaces(AxHost host) @@ -5653,9 +5653,9 @@ int UnsafeNativeMethods.IVBFormat.Format(ref object var, IntPtr pszFormat, IntPt /// internal class EnumUnknown : UnsafeNativeMethods.IEnumUnknown { - private object[] arr; + private readonly object[] arr; private int loc; - private int size; + private readonly int size; internal EnumUnknown(object[] arr) { @@ -5744,7 +5744,7 @@ internal class AxContainer : UnsafeNativeMethods.IOleContainer, UnsafeNativeMeth private AxHost siteUIActive; private AxHost siteActive; private bool formAlreadyCreated = false; - private Hashtable containerCache = new Hashtable(); // name -> Control + private readonly Hashtable containerCache = new Hashtable(); // name -> Control private int lockCount = 0; private Hashtable components = null; // Control -> any private Hashtable proxyCache = null; @@ -6675,8 +6675,8 @@ int UnsafeNativeMethods.IOleInPlaceFrame.TranslateAccelerator(ref NativeMethods. /// private class ExtenderProxy : UnsafeNativeMethods.IExtender, UnsafeNativeMethods.IVBGetControl, UnsafeNativeMethods.IGetVBAObject, UnsafeNativeMethods.IGetOleObject, IReflect { - private WeakReference pRef; - private WeakReference pContainer; + private readonly WeakReference pRef; + private readonly WeakReference pContainer; internal ExtenderProxy(Control principal, AxContainer container) { @@ -7205,7 +7205,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul [SuppressMessage("Microsoft.Usage", "CA2240:ImplementISerializableCorrectly")] public class State : ISerializable { - private int VERSION = 1; + private readonly int VERSION = 1; private int length; private byte[] buffer; internal int type; @@ -7214,7 +7214,7 @@ public class State : ISerializable private UnsafeNativeMethods.ILockBytes iLockBytes; private bool manualUpdate = false; private string licenseKey = null; - private PropertyBagStream propBag; + private readonly PropertyBagStream propBag; // create on save from ipersist stream internal State(MemoryStream ms, int storageType, AxHost ctl, PropertyBagStream propBag) @@ -7647,13 +7647,13 @@ public override bool EditComponent(ITypeDescriptorContext context, object obj, I /// internal class AxPropertyDescriptor : PropertyDescriptor { - private PropertyDescriptor baseProp; + private readonly PropertyDescriptor baseProp; internal AxHost owner; - private DispIdAttribute dispid; + private readonly DispIdAttribute dispid; private TypeConverter converter; private UITypeEditor editor; - private ArrayList updateAttrs = new ArrayList(); + private readonly ArrayList updateAttrs = new ArrayList(); private int flags = 0; private const int FlagUpdatedEditorAndConverter = 0x00000001; @@ -8078,7 +8078,7 @@ internal void UpdateTypeConverterAndTypeEditorInternal(bool force, int dispid) private class AxPropertyTypeEditor : UITypeEditor { - private AxPropertyDescriptor propDesc; + private readonly AxPropertyDescriptor propDesc; private Guid guid; public AxPropertyTypeEditor(AxPropertyDescriptor pd, Guid guid) @@ -8131,7 +8131,7 @@ public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext contex /// private class AxEnumConverter : Com2EnumConverter { - private AxPropertyDescriptor target; + private readonly AxPropertyDescriptor target; public AxEnumConverter(AxPropertyDescriptor target, Com2Enum com2Enum) : base(com2Enum) { @@ -8157,8 +8157,8 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex // private class AxPerPropertyBrowsingEnum : Com2Enum { - private AxPropertyDescriptor target; - private AxHost owner; + private readonly AxPropertyDescriptor target; + private readonly AxHost owner; private OleStrCAMarshaler nameMarshaller; private Int32CAMarshaler valueMarshaller; private bool arraysFetched; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Binding.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Binding.cs index 35fbff998f8..6d2e1b3509d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Binding.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Binding.cs @@ -19,7 +19,7 @@ public class Binding private IBindableComponent _control; private BindingManagerBase _bindingManagerBase; - private BindToObject _bindToObject = null; + private readonly BindToObject _bindToObject = null; private PropertyDescriptor _propInfo; private PropertyDescriptor _propIsNullInfo; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/BindingContext.cs b/src/System.Windows.Forms/src/System/Windows/Forms/BindingContext.cs index 2b465cd8cf3..4c72103c168 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/BindingContext.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/BindingContext.cs @@ -16,7 +16,7 @@ namespace System.Windows.Forms [DefaultEvent(nameof(CollectionChanged))] public class BindingContext : ICollection { - private Hashtable _listManagers; + private readonly Hashtable _listManagers; /// /// Initializes a new instance of the System.Windows.Forms.BindingContext class. @@ -183,9 +183,9 @@ internal HashKey GetKey(object dataSource, string dataMember) internal class HashKey { - private WeakReference _wRef; - private int _dataSourceHashCode; - private string _dataMember; + private readonly WeakReference _wRef; + private readonly int _dataSourceHashCode; + private readonly string _dataMember; internal HashKey(object dataSource, string dataMember) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/BindingMemberInfo.cs b/src/System.Windows.Forms/src/System/Windows/Forms/BindingMemberInfo.cs index 7724b953cbf..da24ebc80da 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/BindingMemberInfo.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/BindingMemberInfo.cs @@ -6,8 +6,8 @@ namespace System.Windows.Forms { public struct BindingMemberInfo { - private string _dataList; - private string _dataField; + private readonly string _dataList; + private readonly string _dataField; public BindingMemberInfo(string dataMember) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/BindingSource.cs b/src/System.Windows.Forms/src/System/Windows/Forms/BindingSource.cs index 52617b1ce47..2c02a97cc6f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/BindingSource.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/BindingSource.cs @@ -81,7 +81,7 @@ public class BindingSource : Component, // Support for property change event hooking on list items private object _currentItemHookedForItemChange = null; private object _lastCurrentItem = null; - private EventHandler _listItemPropertyChangedHandler; + private readonly EventHandler _listItemPropertyChangedHandler; // State data private int _addNewPos = -1; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonBase.cs index b6b39977160..4abaebd9cd2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonBase.cs @@ -36,7 +36,7 @@ public abstract class ButtonBase : Control private ContentAlignment imageAlign = ContentAlignment.MiddleCenter; private ContentAlignment textAlign = ContentAlignment.MiddleCenter; private TextImageRelation textImageRelation = TextImageRelation.Overlay; - private ImageList.Indexer imageIndex = new ImageList.Indexer(); + private readonly ImageList.Indexer imageIndex = new ImageList.Indexer(); private FlatButtonAppearance flatAppearance; private ImageList imageList; private Image image; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonBaseAdapter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonBaseAdapter.cs index bf819e85f4f..71e14b3e437 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonBaseAdapter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonBaseAdapter.cs @@ -26,7 +26,7 @@ namespace System.Windows.Forms.ButtonInternal /// internal abstract class ButtonBaseAdapter { - private ButtonBase control; + private readonly ButtonBase control; // SystemInformation.Border3DSize + 2 pixels for focus rect protected static int buttonBorderSize = 4; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/CheckedListBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/CheckedListBox.cs index 9dbb554de85..fa6716ce8b3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/CheckedListBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/CheckedListBox.cs @@ -91,8 +91,8 @@ public class CheckedListBox : ListBox private CheckedItemCollection checkedItemCollection = null; private CheckedIndexCollection checkedIndexCollection = null; - private static int LBC_GETCHECKSTATE; - private static int LBC_SETCHECKSTATE; + private static readonly int LBC_GETCHECKSTATE; + private static readonly int LBC_SETCHECKSTATE; static CheckedListBox() { @@ -1127,7 +1127,7 @@ protected override void WndProc(ref Message m) new public class ObjectCollection : ListBox.ObjectCollection { - private CheckedListBox owner; + private readonly CheckedListBox owner; public ObjectCollection(CheckedListBox owner) : base(owner) @@ -1168,7 +1168,7 @@ public int Add(object item, CheckState check) public class CheckedIndexCollection : IList { - private CheckedListBox owner; + private readonly CheckedListBox owner; internal CheckedIndexCollection(CheckedListBox owner) { @@ -1344,7 +1344,7 @@ public class CheckedItemCollection : IList internal static int IndeterminateItemMask = ItemArray.CreateMask(); internal static int AnyMask = CheckedItemMask | IndeterminateItemMask; - private CheckedListBox owner; + private readonly CheckedListBox owner; internal CheckedItemCollection(CheckedListBox owner) { @@ -1649,8 +1649,8 @@ internal class CheckedListBoxItemAccessibleObject : AccessibleObject { private string name; - private int index; - private CheckedListBoxAccessibleObject parent; + private readonly int index; + private readonly CheckedListBoxAccessibleObject parent; public CheckedListBoxItemAccessibleObject(string name, int index, CheckedListBoxAccessibleObject parent) : base() { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ColorDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ColorDialog.cs index 751bd208695..c7bc1acf01e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ColorDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ColorDialog.cs @@ -31,7 +31,7 @@ public class ColorDialog : CommonDialog { private int options; - private int[] customColors; + private readonly int[] customColors; /// /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeader.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeader.cs index b841ea55abb..ea8512b214b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeader.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ColumnHeader.cs @@ -44,7 +44,7 @@ public class ColumnHeader : Component, ICloneable private HorizontalAlignment textAlign = HorizontalAlignment.Left; private bool textAlignInitialized = false; private int displayIndexInternal = -1; - private ColumnHeaderImageListIndexer imageIndexer = null; + private readonly ColumnHeaderImageListIndexer imageIndexer = null; object userData; @@ -562,7 +562,7 @@ public override string ToString() internal class ColumnHeaderImageListIndexer : ImageList.Indexer { - private ColumnHeader owner = null; + private readonly ColumnHeader owner = null; public ColumnHeaderImageListIndexer(ColumnHeader ch) { owner = ch; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs index 1631a3a8c4d..21fb50bd8b8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs @@ -117,7 +117,7 @@ public class ComboBox : ListControl private string currentText = string.Empty; private string lastTextChangedValue; private bool dropDown; - private AutoCompleteDropDownFinder finder = new AutoCompleteDropDownFinder(); + private readonly AutoCompleteDropDownFinder finder = new AutoCompleteDropDownFinder(); private bool selectedValueChangedFired; @@ -4168,9 +4168,9 @@ protected override void WndProc(ref Message m) [ComVisible(true)] private class ComboBoxChildNativeWindow : NativeWindow { - private ComboBox _owner; + private readonly ComboBox _owner; private InternalAccessibleObject _accessibilityObject; - private ChildWindowType _childWindowType; + private readonly ChildWindowType _childWindowType; public ComboBoxChildNativeWindow(ComboBox comboBox, ChildWindowType childWindowType) { @@ -4306,7 +4306,7 @@ private void WmGetObject(ref Message m) private sealed class ItemComparer : System.Collections.IComparer { - private ComboBox comboBox; + private readonly ComboBox comboBox; public ItemComparer(ComboBox comboBox) { @@ -4341,7 +4341,7 @@ public int Compare(object item1, object item2) public class ObjectCollection : IList { - private ComboBox owner; + private readonly ComboBox owner; private ArrayList innerList; private IComparer comparer; @@ -4767,8 +4767,7 @@ internal void SetItemInternal(int index, object value) [ComVisible(true)] public class ChildAccessibleObject : AccessibleObject { - - ComboBox owner; + readonly ComboBox owner; public ChildAccessibleObject(ComboBox owner, IntPtr handle) { @@ -4794,8 +4793,8 @@ public override string Name internal class ComboBoxItemAccessibleObject : AccessibleObject { - private ComboBox _owningComboBox; - private object _owningItem; + private readonly ComboBox _owningComboBox; + private readonly object _owningItem; private IAccessible _systemIAccessible; /// @@ -5073,7 +5072,7 @@ internal override UnsafeNativeMethods.IRawElementProviderSimple ItemSelectionCon internal class ComboBoxItemAccessibleObjectCollection : Hashtable { - private ComboBox _owningComboBoxBox; + private readonly ComboBox _owningComboBoxBox; private readonly ObjectIDGenerator _idGenerator = new ObjectIDGenerator(); public ComboBoxItemAccessibleObjectCollection(ComboBox owningComboBoxBox) @@ -5119,8 +5118,8 @@ internal class ComboBoxAccessibleObject : ControlAccessibleObject private const int COMBOBOX_ACC_ITEM_INDEX = 1; private ComboBoxChildDropDownButtonUiaProvider _dropDownButtonUiaProvider; - private ComboBoxItemAccessibleObjectCollection _itemAccessibleObjects; - private ComboBox _owningComboBox; + private readonly ComboBoxItemAccessibleObjectCollection _itemAccessibleObjects; + private readonly ComboBox _owningComboBox; /// /// Initializes new instance of ComboBoxAccessibleObject. @@ -5438,8 +5437,8 @@ internal class ComboBoxChildEditUiaProvider : ChildAccessibleObject { private const string COMBO_BOX_EDIT_AUTOMATION_ID = "1001"; - private ComboBox _owner; - private IntPtr _handle; + private readonly ComboBox _owner; + private readonly IntPtr _handle; /// /// Initializes new instance of ComboBoxChildEditUiaProvider. @@ -5584,8 +5583,8 @@ internal class ComboBoxChildListUiaProvider : ChildAccessibleObject { private const string COMBO_BOX_LIST_AUTOMATION_ID = "1000"; - private ComboBox _owningComboBox; - private IntPtr _childListControlhandle; + private readonly ComboBox _owningComboBox; + private readonly IntPtr _childListControlhandle; /// /// Initializes new instance of ComboBoxChildListUiaProvider. @@ -5832,7 +5831,7 @@ internal class ComboBoxChildTextUiaProvider : AccessibleObject private const int COMBOBOX_TEXT_ACC_ITEM_INDEX = 1; - private ComboBox _owner; + private readonly ComboBox _owner; /// /// Initializes new instance of ComboBoxChildTextUiaProvider. @@ -6007,7 +6006,7 @@ internal class ComboBoxChildDropDownButtonUiaProvider : AccessibleObject { private const int COMBOBOX_DROPDOWN_BUTTON_ACC_ITEM_INDEX = 2; - private ComboBox _owner; + private readonly ComboBox _owner; /// /// Initializes new instance of ComboBoxChildDropDownButtonUiaProvider. @@ -6238,7 +6237,7 @@ private sealed class ACNativeWindow : NativeWindow { static internal int inWndProcCnt; //this hashtable can contain null for those ACWindows we find, but are sure are not ours. - static private Hashtable ACWindows = new Hashtable(); + private static readonly Hashtable ACWindows = new Hashtable(); [ SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") @@ -6429,12 +6428,11 @@ internal class FlatComboAdapter internal Rectangle dropDownRect; Rectangle whiteFillRect; Rectangle clientRect; - - RightToLeft origRightToLeft; // The combo box's RTL value when we were created + readonly RightToLeft origRightToLeft; // The combo box's RTL value when we were created private const int WhiteFillRectWidth = 5; // used for making the button look smaller than it is - private static int OFFSET_2PIXELS = 2; + private static readonly int OFFSET_2PIXELS = 2; protected static int Offset2Pixels = OFFSET_2PIXELS; public FlatComboAdapter(ComboBox comboBox, bool smallButton) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Command.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Command.cs index 7ab83a4fd26..4972f32c7f8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Command.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Command.cs @@ -21,7 +21,7 @@ internal class Command : WeakReference private static Command[] cmds; private static int icmdTry; - private static object internalSyncObject = new object(); + private static readonly object internalSyncObject = new object(); private const int idMin = 0x00100; private const int idLim = 0x10000; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentManagerBroker.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentManagerBroker.cs index 7c123f1a66c..3b91f0026b9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentManagerBroker.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentManagerBroker.cs @@ -84,8 +84,8 @@ internal sealed class ComponentManagerBroker : MarshalByRefObject // These are constants per process and are initialized in // a class cctor below. - private static object _syncObject; - private static string _remoteObjectName; + private static readonly object _syncObject; + private static readonly string _remoteObjectName; // We keep a static instance of ourself. It will really be // per-domain, but we only have one domain. The purpose @@ -235,10 +235,10 @@ internal static UnsafeNativeMethods.IMsoComponentManager GetComponentManager(Int internal class ComponentManagerProxy : MarshalByRefObject, UnsafeNativeMethods.IMsoComponentManager, UnsafeNativeMethods.IMsoComponent { - private ComponentManagerBroker _broker; + private readonly ComponentManagerBroker _broker; private UnsafeNativeMethods.IMsoComponentManager _original; private int _refCount; - private int _creationThread; + private readonly int _creationThread; private IntPtr _componentId; private int _nextComponentId; private Dictionary _components; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/BaseCAMarshaler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/BaseCAMarshaler.cs index aae4fb87b22..26d526b0c7c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/BaseCAMarshaler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/BaseCAMarshaler.cs @@ -22,10 +22,10 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop internal abstract class BaseCAMarshaler { - private static TraceSwitch CAMarshalSwitch = new TraceSwitch("CAMarshal", "BaseCAMarshaler: Debug CA* struct marshaling"); + private static readonly TraceSwitch CAMarshalSwitch = new TraceSwitch("CAMarshal", "BaseCAMarshaler: Debug CA* struct marshaling"); private IntPtr caArrayAddress; - private int count; + private readonly int count; private object[] itemArray; /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Enum.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Enum.cs index c271a64bf9a..9db6b8a7fec 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Enum.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Enum.cs @@ -48,7 +48,7 @@ internal class Com2Enum /// /// Should we allow values besides what's in the listbox? /// - private bool allowUnknownValues; + private readonly bool allowUnknownValues; /// /// Our one and only ctor diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedTypeConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedTypeConverter.cs index 04c181dac64..d8227b26a88 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedTypeConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedTypeConverter.cs @@ -22,7 +22,7 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop /// internal class Com2ExtendedTypeConverter : TypeConverter { - private TypeConverter innerConverter; + private readonly TypeConverter innerConverter; public Com2ExtendedTypeConverter(TypeConverter innerConverter) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedUITypeEditor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedUITypeEditor.cs index 0ef9acb7770..aa3bcb11ea3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedUITypeEditor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2ExtendedUITypeEditor.cs @@ -24,7 +24,7 @@ namespace System.Drawing.Design internal class Com2ExtendedUITypeEditor : UITypeEditor { - private UITypeEditor innerEditor; + private readonly UITypeEditor innerEditor; public Com2ExtendedUITypeEditor(UITypeEditor baseTypeEditor) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IDispatchConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IDispatchConverter.cs index 6bc78ed6dcf..ba8f403bd94 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IDispatchConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IDispatchConverter.cs @@ -15,14 +15,14 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop internal class Com2IDispatchConverter : Com2ExtendedTypeConverter { - Com2PropertyDescriptor propDesc; + readonly Com2PropertyDescriptor propDesc; /// /// What we return textually for null. /// protected static readonly string none = SR.toStringNone; - private bool allowExpand; + private readonly bool allowExpand; public Com2IDispatchConverter(Com2PropertyDescriptor propDesc, bool allowExpand, TypeConverter baseConverter) : base(baseConverter) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs index deb9891fd14..413f3dbe4c9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2IPerPropertyBrowsingHandler.cs @@ -204,7 +204,7 @@ private void OnGetTypeConverterAndTypeEditor(Com2PropertyDescriptor sender, GetT // this is just here so we can identify the enums that we added private class Com2IPerPropertyEnumConverter : Com2EnumConverter { - private Com2IPerPropertyBrowsingEnum itemsEnum; + private readonly Com2IPerPropertyBrowsingEnum itemsEnum; public Com2IPerPropertyEnumConverter(Com2IPerPropertyBrowsingEnum items) : base(items) { itemsEnum = items; @@ -238,9 +238,9 @@ private class Com2IPerPropertyBrowsingEnum : Com2Enum { internal Com2PropertyDescriptor target; - private Com2IPerPropertyBrowsingHandler handler; - private OleStrCAMarshaler nameMarshaller; - private Int32CAMarshaler valueMarshaller; + private readonly Com2IPerPropertyBrowsingHandler handler; + private readonly OleStrCAMarshaler nameMarshaller; + private readonly Int32CAMarshaler valueMarshaller; internal bool arraysFetched; //private bool standardValuesQueried; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Properties.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Properties.cs index 53841089858..dd01c708238 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Properties.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Properties.cs @@ -20,7 +20,7 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop internal class Com2Properties { - private static TraceSwitch DbgCom2PropertiesSwitch = new TraceSwitch("DbgCom2Properties", "Com2Properties: debug Com2 properties manager"); + private static readonly TraceSwitch DbgCom2PropertiesSwitch = new TraceSwitch("DbgCom2Properties", "Com2Properties: debug Com2 properties manager"); @@ -30,7 +30,7 @@ internal class Com2Properties /// /// 5 minutes -- ticks are 1/10,000,000th of a second /// - private static long AGE_THRESHHOLD = (long)(10000000L * 60L * 5L); + private static readonly long AGE_THRESHHOLD = (long)(10000000L * 60L * 5L); /// @@ -46,7 +46,7 @@ internal class Com2Properties /// /// The index of the default property /// - private int defaultIndex = -1; + private readonly int defaultIndex = -1; /// @@ -63,8 +63,8 @@ internal class Com2Properties #if DEBUG - private string dbgObjName; - private string dbgObjClass; + private readonly string dbgObjName; + private readonly string dbgObjClass; #endif private int alwaysValid = 0; @@ -72,7 +72,7 @@ internal class Com2Properties /// /// These are the interfaces we recognize for extended browsing. /// - private static Type[] extendedInterfaces = new Type[]{ + private static readonly Type[] extendedInterfaces = new Type[]{ typeof(NativeMethods.ICategorizeProperties), typeof(NativeMethods.IProvidePropertyBuilder), typeof(NativeMethods.IPerPropertyBrowsing), @@ -83,7 +83,7 @@ internal class Com2Properties /// These are the classes of handlers corresponding to the extended /// interfaces above. /// - private static Type[] extendedInterfaceHandlerTypes = new Type[]{ + private static readonly Type[] extendedInterfaceHandlerTypes = new Type[]{ typeof(Com2ICategorizePropertiesHandler), typeof(Com2IProvidePropertyBuilderHandler), typeof(Com2IPerPropertyBrowsingHandler), diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyBuilderUITypeEditor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyBuilderUITypeEditor.cs index 5c75632b47f..ad047b359ba 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyBuilderUITypeEditor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyBuilderUITypeEditor.cs @@ -21,9 +21,9 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop internal class Com2PropertyBuilderUITypeEditor : Com2ExtendedUITypeEditor { - private Com2PropertyDescriptor propDesc; - string guidString; - int bldrType; + private readonly Com2PropertyDescriptor propDesc; + readonly string guidString; + readonly int bldrType; public Com2PropertyBuilderUITypeEditor(Com2PropertyDescriptor pd, string guidString, int type, UITypeEditor baseEditor) : base(baseEditor) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs index 423a1ae47ea..d9ca8d36442 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs @@ -34,19 +34,19 @@ internal class Com2PropertyDescriptor : PropertyDescriptor, ICloneable /// /// Is this guy read only? /// - private bool baseReadOnly; + private readonly bool baseReadOnly; private bool readOnly; /// /// The resoved native type -> clr type /// - private Type propertyType; + private readonly Type propertyType; /// /// The dispid. This is also in a DispIDAttiribute, but we /// need it a lot. /// - private int dispid; + private readonly int dispid; private TypeConverter converter; private object editor; @@ -60,7 +60,7 @@ internal class Com2PropertyDescriptor : PropertyDescriptor, ICloneable /// This is any extra data needed. For IDispatch types, it's the GUID of /// the interface, etc. /// - private object typeData; + private readonly object typeData; /// /// Keeps track of which data members need to be refreshed. @@ -70,7 +70,7 @@ internal class Com2PropertyDescriptor : PropertyDescriptor, ICloneable /// /// Should we bother asking if refresh is needed? /// - private bool queryRefresh = false; + private readonly bool queryRefresh = false; /// /// Our properties manager @@ -91,12 +91,12 @@ internal class Com2PropertyDescriptor : PropertyDescriptor, ICloneable /// /// For Object and dispatch types, we hide them by default. /// - private bool typeHide; + private readonly bool typeHide; /// /// Set if the metadata causes this property to always be hidden /// - private bool canShow; + private readonly bool canShow; /// /// This property is hidden because its get didn't return S_OK @@ -127,7 +127,7 @@ internal class Com2PropertyDescriptor : PropertyDescriptor, ICloneable /// /// Our map of native types that we can map to managed types for editors /// - private static IDictionary oleConverters; + private static readonly IDictionary oleConverters; static Com2PropertyDescriptor() { @@ -144,7 +144,7 @@ static Com2PropertyDescriptor() /// /// Should we convert our type? /// - private Com2DataTypeToManagedDataTypeConverter valueConverter; + private readonly Com2DataTypeToManagedDataTypeConverter valueConverter; /// /// Ctor. @@ -1463,7 +1463,7 @@ public override bool ShouldSerializeValue(object component) /// private class Com2PropDescMainConverter : Com2ExtendedTypeConverter { - Com2PropertyDescriptor pd; + readonly Com2PropertyDescriptor pd; private const int CheckSubprops = 0; private const int AllowSubprops = 1; @@ -1546,7 +1546,7 @@ public override bool GetPropertiesSupported(ITypeDescriptorContext context) internal class GetAttributesEvent : EventArgs { - private ArrayList attrList; + private readonly ArrayList attrList; public GetAttributesEvent(ArrayList attrList) { @@ -1626,8 +1626,7 @@ public bool Value internal class GetRefreshStateEvent : GetBoolValueEvent { - - Com2ShouldRefreshTypes item; + readonly Com2ShouldRefreshTypes item; public GetRefreshStateEvent(Com2ShouldRefreshTypes item, bool defValue) : base(defValue) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyPageUITypeConverter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyPageUITypeConverter.cs index 4ca04124502..4c6cda20e21 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyPageUITypeConverter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyPageUITypeConverter.cs @@ -20,7 +20,7 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop internal class Com2PropertyPageUITypeEditor : Com2ExtendedUITypeEditor, ICom2PropertyPageDisplayService { - private Com2PropertyDescriptor propDesc; + private readonly Com2PropertyDescriptor propDesc; private Guid guid; public Com2PropertyPageUITypeEditor(Com2PropertyDescriptor pd, Guid guid, UITypeEditor baseEditor) : base(baseEditor) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs index 0c515f930b4..976defb0815 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2TypeInfoProcessor.cs @@ -28,7 +28,7 @@ namespace System.Windows.Forms.ComponentModel.Com2Interop internal class Com2TypeInfoProcessor { - private static TraceSwitch DbgTypeInfoProcessorSwitch = new TraceSwitch("DbgTypeInfoProcessor", "Com2TypeInfoProcessor: debug Com2 type info processing"); + private static readonly TraceSwitch DbgTypeInfoProcessorSwitch = new TraceSwitch("DbgTypeInfoProcessor", "Com2TypeInfoProcessor: debug Com2 type info processing"); private Com2TypeInfoProcessor() { @@ -1095,11 +1095,11 @@ private static Type VTToType(NativeMethods.tagVT vt) internal class CachedProperties { - private PropertyDescriptor[] props; + private readonly PropertyDescriptor[] props; public readonly int MajorVersion; public readonly int MinorVersion; - private int defaultIndex; + private readonly int defaultIndex; internal CachedProperties(PropertyDescriptor[] props, int defIndex, int majVersion, int minVersion) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/ComNativeDescriptor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/ComNativeDescriptor.cs index f023816bd96..ffae648a213 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/ComNativeDescriptor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/ComNativeDescriptor.cs @@ -24,17 +24,17 @@ internal class ComNativeDescriptor : TypeDescriptionProvider private static ComNativeDescriptor handler = null; - private AttributeCollection staticAttrs = new AttributeCollection(new Attribute[] { BrowsableAttribute.Yes, DesignTimeVisibleAttribute.No }); + private readonly AttributeCollection staticAttrs = new AttributeCollection(new Attribute[] { BrowsableAttribute.Yes, DesignTimeVisibleAttribute.No }); /// /// Our collection of Object managers (Com2Properties) for native properties /// - private WeakHashtable nativeProps = new WeakHashtable(); + private readonly WeakHashtable nativeProps = new WeakHashtable(); /// /// Our collection of browsing handlers, which are stateless and shared across objects. /// - private Hashtable extendedBrowsingHandlers = new Hashtable(); + private readonly Hashtable extendedBrowsingHandlers = new Hashtable(); /// /// We increment this every time we look at an Object, at specified @@ -523,8 +523,8 @@ internal static void ResolveVariantTypeConverterAndTypeEditor(object propertyVal /// private sealed class ComTypeDescriptor : ICustomTypeDescriptor { - private ComNativeDescriptor _handler; - private object _instance; + private readonly ComNativeDescriptor _handler; + private readonly object _instance; /// /// Creates a new WalkingTypeDescriptor. 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 696c92096c0..088b0ea0590 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs @@ -152,8 +152,8 @@ internal void TraceCanProcessMnemonic() internal static readonly BooleanSwitch BufferPinkRect; #endif - private static int WM_GETCONTROLNAME; - private static int WM_GETCONTROLTYPE; + private static readonly int WM_GETCONTROLNAME; + private static readonly int WM_GETCONTROLTYPE; static Control() { @@ -399,7 +399,7 @@ static 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 readonly ControlNativeWindow window; private Control parent; private Control reflectParent; @@ -417,7 +417,7 @@ static Control() 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 readonly PropertyStore propertyStore; // Contains all properties that are not always set. private NativeMethods.TRACKMOUSEEVENT trackMouseEvent; private short updateCount; private LayoutEventArgs cachedLayoutEventArgs; @@ -15365,7 +15365,7 @@ internal virtual bool SupportsUiaProviders /// internal sealed class ControlNativeWindow : NativeWindow, IWindowTarget { - private Control control; + private readonly Control control; private GCHandle rootRef; // We will root the control when we do not want to be elligible for garbage collection. internal IWindowTarget target; @@ -15529,7 +15529,7 @@ void ISupportOleDropSource.OnQueryContinueDrag(QueryContinueDragEventArgs queryC public class ControlCollection : ArrangedElementCollection, IList, ICloneable { - private Control owner; + private readonly Control owner; /// A caching mechanism for key accessor /// We use an index here rather than control so that we don't have lifetime @@ -16068,9 +16068,9 @@ public virtual void SetChildIndex(Control child, int newIndex) // special version of this. private class ControlCollectionEnumerator : IEnumerator { - private ControlCollection controls; + private readonly ControlCollection controls; private int current; - private int originalCount; + private readonly int originalCount; public ControlCollectionEnumerator(ControlCollection controls) { @@ -17115,16 +17115,16 @@ private class ActiveXImpl : MarshalByRefObject, IWindowTarget #endif - private Control control; - private IWindowTarget controlWindowTarget; + private readonly Control control; + private readonly IWindowTarget controlWindowTarget; private IntPtr clipRegion; private UnsafeNativeMethods.IOleClientSite clientSite; private UnsafeNativeMethods.IOleInPlaceUIWindow inPlaceUiWindow; private UnsafeNativeMethods.IOleInPlaceFrame inPlaceFrame; - private ArrayList adviseList; + private readonly ArrayList adviseList; private IAdviseSink viewAdviseSink; private BitVector32 activeXState; - private AmbientProperty[] ambientProperties; + private readonly AmbientProperty[] ambientProperties; private IntPtr hwndParent; private IntPtr accelTable; private short accelCount = -1; @@ -18861,7 +18861,7 @@ public ComConnectionPointContainer(object obj, bool addRefIntPtr) vtbl = base.LoadVtable(); } - private VTABLE vtbl; + private readonly VTABLE vtbl; [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] [StructLayout(LayoutKind.Sequential)] @@ -18924,7 +18924,7 @@ private class VTABLE public IntPtr EnumConnectionsPtr; } - private VTABLE vtbl; + private readonly VTABLE vtbl; /// /// Call IConnectioinPoint.Advise using Delegate.Invoke on the v-table slot. @@ -19861,8 +19861,8 @@ internal void Write(UnsafeNativeMethods.IStream istream) private class AxSourcingSite : ISite { - private IComponent component; - private UnsafeNativeMethods.IOleClientSite clientSite; + private readonly IComponent component; + private readonly UnsafeNativeMethods.IOleClientSite clientSite; private string name; private HtmlShimManager shimManager; @@ -20041,7 +20041,7 @@ public object MarshalNativeToManaged(IntPtr pObj) /// private class ActiveXVerbEnum : UnsafeNativeMethods.IEnumOLEVERB { - private NativeMethods.tagOLEVERB[] verbs; + private readonly NativeMethods.tagOLEVERB[] verbs; private int current; internal ActiveXVerbEnum(NativeMethods.tagOLEVERB[] verbs) @@ -20172,8 +20172,8 @@ internal void Edit(object editingObject) { /// private class AmbientProperty { - private string name; - private int dispID; + private readonly string name; + private readonly int dispID; private object value; private bool empty; @@ -20265,7 +20265,7 @@ private class MetafileDCWrapper : IDisposable HandleRef hBitmapDC = NativeMethods.NullHandleRef; HandleRef hBitmap = NativeMethods.NullHandleRef; HandleRef hOriginalBmp = NativeMethods.NullHandleRef; - HandleRef hMetafileDC = NativeMethods.NullHandleRef; + readonly HandleRef hMetafileDC = NativeMethods.NullHandleRef; NativeMethods.RECT destRect; [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] @@ -20473,7 +20473,7 @@ public class ControlAccessibleObject : AccessibleObject // Member variables private IntPtr handle = IntPtr.Zero; // Associated window handle (if any) - private Control ownerControl = null; // The associated Control for this AccessibleChild (if any) + private readonly Control ownerControl = null; // The associated Control for this AccessibleChild (if any) private int[] runtimeId = null; // Used by UIAutomation // constructors @@ -21038,7 +21038,7 @@ public override string ToString() internal sealed class FontHandleWrapper : MarshalByRefObject, IDisposable { #if DEBUG - private string stackOnCreate = null; + private readonly string stackOnCreate = null; private string stackOnDispose = null; private bool finalizing = false; #endif @@ -21115,7 +21115,7 @@ private class ThreadMethodEntry : IAsyncResult internal bool synchronous; private bool isCompleted; private ManualResetEvent resetEvent; - private object invokeSyncObject = new object(); + private readonly object invokeSyncObject = new object(); // Store the execution context associated with the caller thread, and // information about which thread actually got the stack applied to it. @@ -21223,7 +21223,7 @@ private class ControlVersionInfo private string productName = null; private string productVersion = null; private FileVersionInfo versionInfo = null; - private Control owner; + private readonly Control owner; internal ControlVersionInfo(Control owner) { @@ -21386,7 +21386,7 @@ private sealed class MultithreadSafeCallScope : IDisposable { // Use local stack variable rather than a refcount since we're // guaranteed that these 'scopes' are properly nested. - private bool resultedInSet; + private readonly bool resultedInSet; internal MultithreadSafeCallScope() { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ControlBindingsCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ControlBindingsCollection.cs index 63278373888..83c074fe911 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ControlBindingsCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ControlBindingsCollection.cs @@ -17,7 +17,7 @@ namespace System.Windows.Forms [TypeConverter("System.Windows.Forms.Design.ControlBindingsConverter, " + AssemblyRef.SystemDesign)] public class ControlBindingsCollection : BindingsCollection { - private IBindableComponent _control; + private readonly IBindableComponent _control; public ControlBindingsCollection(IBindableComponent control) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ControlPaint.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ControlPaint.cs index fbcd3739225..2f92f5ac73f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ControlPaint.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ControlPaint.cs @@ -3097,11 +3097,11 @@ private struct HLSColor private const int RGBMax = 255; private const int Undefined = HLSMax * 2 / 3; - private int hue; - private int saturation; - private int luminosity; + private readonly int hue; + private readonly int saturation; + private readonly int luminosity; - private bool isSystemColors_Control; + private readonly bool isSystemColors_Control; /// /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs index 8cd20627d66..9a8c21f39c7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs @@ -45,7 +45,7 @@ public class CurrencyManager : BindingManagerBase // private CurrentChangingEventHandler onCurrentChanging; private ItemChangedEventHandler onItemChanged; private ListChangedEventHandler onListChanged; - private ItemChangedEventArgs resetEvent = new ItemChangedEventArgs(-1); + private readonly ItemChangedEventArgs resetEvent = new ItemChangedEventArgs(-1); private EventHandler onMetaDataChangedHandler; /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Cursor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Cursor.cs index 1061e458a71..719cdbc49d3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Cursor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Cursor.cs @@ -35,7 +35,7 @@ public sealed class Cursor : IDisposable, ISerializable { private static Size cursorSize = System.Drawing.Size.Empty; - private byte[] cursorData; + private readonly byte[] cursorData; private IntPtr handle = IntPtr.Zero; // handle to loaded image private bool ownHandle = true; private int resourceId = 0; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataFormats.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataFormats.cs index d85de8d1505..4cf484180b7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataFormats.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataFormats.cs @@ -149,7 +149,7 @@ public static class DataFormats private static Format[] s_formatList; private static int s_formatCount = 0; - private static object s_internalSyncObject = new object(); + private static readonly object s_internalSyncObject = new object(); /// /// Gets a with the Windows diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs index 391329de64a..76f4dd5bb2d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs @@ -83,7 +83,7 @@ public class DataGrid : Control, ISupportInitialize, IDataGridEditingService private const bool defaultParentRowsVisible = true; - private DataGridTableStyle defaultTableStyle = new DataGridTableStyle(true); + private readonly DataGridTableStyle defaultTableStyle = new DataGridTableStyle(true); // private bool allowSorting = true; @@ -108,7 +108,7 @@ public class DataGrid : Control, ISupportInitialize, IDataGridEditingService private const int defaultPreferredColumnWidth = 75; private int preferredColumnWidth = defaultPreferredColumnWidth; - private static int defaultFontHeight = Control.DefaultFont.Height; + private static readonly int defaultFontHeight = Control.DefaultFont.Height; private int prefferedRowHeight = defaultFontHeight + 3; // private bool rowHeadersVisible = true; @@ -121,7 +121,7 @@ public class DataGrid : Control, ISupportInitialize, IDataGridEditingService // parent rows // - private DataGridParentRows parentRows = null; + private readonly DataGridParentRows parentRows = null; // Set_ListManager uses the originalState to determine // if the grid should disconnect from all the MetaDataChangedEvents // keep "originalState != null" when navigating back and forth in the grid @@ -183,7 +183,7 @@ public class DataGrid : Control, ISupportInitialize, IDataGridEditingService // private bool listHasErrors = false; // caption - private DataGridCaption caption; + private readonly DataGridCaption caption; // Border // @@ -235,7 +235,7 @@ public class DataGrid : Control, ISupportInitialize, IDataGridEditingService // Policy // private bool readOnlyMode = false; - private Policy policy = new Policy(); + private readonly Policy policy = new Policy(); // private bool allowNavigation = true; // editing @@ -247,8 +247,8 @@ public class DataGrid : Control, ISupportInitialize, IDataGridEditingService // scrolling // - private ScrollBar horizScrollBar = new HScrollBar(); - private ScrollBar vertScrollBar = new VScrollBar(); + private readonly ScrollBar horizScrollBar = new HScrollBar(); + private readonly ScrollBar vertScrollBar = new VScrollBar(); // the sum of the widths of the columns preceding the firstVisibleColumn // @@ -294,16 +294,16 @@ public class DataGrid : Control, ISupportInitialize, IDataGridEditingService // event handlers // - private ItemChangedEventHandler itemChangedHandler; - private EventHandler positionChangedHandler; - private EventHandler currentChangedHandler; - private EventHandler metaDataChangedHandler; + private readonly ItemChangedEventHandler itemChangedHandler; + private readonly EventHandler positionChangedHandler; + private readonly EventHandler currentChangedHandler; + private readonly EventHandler metaDataChangedHandler; // we have to know when the collection of dataGridTableStyles changes - private CollectionChangeEventHandler dataGridTableStylesCollectionChanged; + private readonly CollectionChangeEventHandler dataGridTableStylesCollectionChanged; - private EventHandler backButtonHandler; - private EventHandler downButtonHandler; + private readonly EventHandler backButtonHandler; + private readonly EventHandler downButtonHandler; private NavigateEventHandler onNavigate; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs index 68d4d2e650a..099a4a27038 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs @@ -31,18 +31,18 @@ internal class DataGridCaption private const int yOffset = 1; private const int textPadding = 2; private const int buttonToText = 4; - private static ColorMap[] colorMap = new ColorMap[] { new ColorMap() }; + private static readonly ColorMap[] colorMap = new ColorMap[] { new ColorMap() }; private static readonly Point minimumBounds = new Point(50, 30); - private DataGrid dataGrid = null; + private readonly DataGrid dataGrid = null; private bool backButtonVisible = false; private bool downButtonVisible = false; private SolidBrush backBrush = DefaultBackBrush; private SolidBrush foreBrush = DefaultForeBrush; - private Pen textBorderPen = DefaultTextBorderPen; + private readonly Pen textBorderPen = DefaultTextBorderPen; private string text = string.Empty; private bool textBorderVisible = false; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs index 562c8c8d1a1..f7838378cce 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs @@ -26,9 +26,9 @@ namespace System.Windows.Forms public class GridColumnStylesCollection : BaseCollection, IList { CollectionChangeEventHandler onCollectionChanged; - ArrayList items = new ArrayList(); - DataGridTableStyle owner = null; - private bool isDefault = false; + readonly ArrayList items = new ArrayList(); + readonly DataGridTableStyle owner = null; + private readonly bool isDefault = false; // we have to implement IList for the Collection editor to work // diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnStyle.cs index 020ccaa23b7..aeb7b402340 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnStyle.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnStyle.cs @@ -23,7 +23,7 @@ public abstract class DataGridColumnStyle : Component, IDataGridColumnStyleEditi private HorizontalAlignment _alignment = HorizontalAlignment.Left; private PropertyDescriptor _propertyDescriptor = null; private DataGridTableStyle _dataGridTableStyle = null; - private Font _font = null; + private readonly Font _font = null; private string _mappingName = string.Empty; private string _headerName = string.Empty; private bool _invalid = false; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRows.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRows.cs index c1b06385879..6d683c787e6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRows.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridParentRows.cs @@ -20,7 +20,7 @@ internal class DataGridParentRows { // siting // - private DataGrid dataGrid; + private readonly DataGrid dataGrid; // ui // @@ -30,26 +30,26 @@ internal class DataGridParentRows private SolidBrush backBrush = DataGrid.DefaultParentRowsBackBrush; private SolidBrush foreBrush = DataGrid.DefaultParentRowsForeBrush; - private int borderWidth = 1; + private readonly int borderWidth = 1; // private Color borderColor = SystemColors.WindowFrame; private Brush borderBrush = new SolidBrush(SystemColors.WindowFrame); private static Bitmap rightArrow = null; private static Bitmap leftArrow = null; - private ColorMap[] colorMap = new ColorMap[] { new ColorMap() }; + private readonly ColorMap[] colorMap = new ColorMap[] { new ColorMap() }; // private bool gridLineDots = false; // private Color gridLineColor = SystemColors.Control; // private Brush gridLineBrush = SystemBrushes.Control; - private Pen gridLinePen = SystemPens.Control; + private readonly Pen gridLinePen = SystemPens.Control; private int totalHeight = 0; private int textRegionHeight = 0; // now that we have left and right arrows, we also have layout - private Layout layout = new Layout(); + private readonly Layout layout = new Layout(); // mouse info // @@ -68,9 +68,9 @@ internal class DataGridParentRows // storage for parent row states // - private ArrayList parents = new ArrayList(); + private readonly ArrayList parents = new ArrayList(); private int parentsCount = 0; - private ArrayList rowHeights = new ArrayList(); + private readonly ArrayList rowHeights = new ArrayList(); AccessibleObject accessibleObject; internal DataGridParentRows(DataGrid dataGrid) @@ -1201,7 +1201,7 @@ public override string ToString() [ComVisible(true)] protected internal class DataGridParentRowsAccessibleObject : AccessibleObject { - DataGridParentRows owner = null; + readonly DataGridParentRows owner = null; public DataGridParentRowsAccessibleObject(DataGridParentRows owner) : base() { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRelationshipRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRelationshipRow.cs index 27d21a7c91a..daa6f56fece 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRelationshipRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRelationshipRow.cs @@ -1090,8 +1090,8 @@ public override AccessibleObject GetFocused() [ComVisible(true)] protected class DataGridRelationshipAccessibleObject : AccessibleObject { - DataGridRelationshipRow owner = null; - int relationship; + readonly DataGridRelationshipRow owner = null; + readonly int relationship; public DataGridRelationshipAccessibleObject(DataGridRelationshipRow owner, int relationship) : base() { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRow.cs index 95faa9ae6b8..0dcb5dcd030 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridRow.cs @@ -42,7 +42,7 @@ internal abstract class DataGridRow : MarshalByRefObject // we will be mapping only the black color to // the HeaderForeColor // - private static ColorMap[] colorMap = new ColorMap[] { new ColorMap() }; + private static readonly ColorMap[] colorMap = new ColorMap[] { new ColorMap() }; // bitmaps // @@ -761,8 +761,7 @@ protected Brush ForeBrushForDataPaint(ref DataGridCell current, DataGridColumnSt protected class DataGridRowAccessibleObject : AccessibleObject { ArrayList cells; - - DataGridRow owner = null; + readonly DataGridRow owner = null; internal static string CellToDisplayString(DataGrid grid, int row, int column) { @@ -1008,8 +1007,8 @@ public override void Select(AccessibleSelection flags) [ComVisible(true)] protected class DataGridCellAccessibleObject : AccessibleObject { - DataGridRow owner = null; - int column; + readonly DataGridRow owner = null; + readonly int column; public DataGridCellAccessibleObject(DataGridRow owner, int column) : base() { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs index caf75849f72..2e6f017914b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridState.cs @@ -166,7 +166,7 @@ private void DataSource_MetaDataChanged(object sender, EventArgs e) [ComVisible(true)] internal class DataGridStateParentRowAccessibleObject : AccessibleObject { - DataGridState owner = null; + readonly DataGridState owner = null; public DataGridStateParentRowAccessibleObject(DataGridState owner) : base() { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs index fc7259f6dff..b94ef64bf98 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTable.cs @@ -41,13 +41,13 @@ public class DataGridTableStyle : Component, IDataGridEditingService private int focusedTextWidth; // will contain a list of relationships that this table has - private ArrayList relationsList = new ArrayList(2); + private readonly ArrayList relationsList = new ArrayList(2); // the name of the table private string mappingName = string.Empty; - private GridColumnStylesCollection gridColumns = null; + private readonly GridColumnStylesCollection gridColumns = null; private bool readOnly = false; - private bool isDefaultTableStyle = false; + private readonly bool isDefaultTableStyle = false; private static readonly object EventAllowSorting = new object(); private static readonly object EventGridLineColor = new object(); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs index 90ad10d2ed4..3c9c5915ca6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs @@ -21,8 +21,8 @@ namespace System.Windows.Forms public class GridTableStylesCollection : BaseCollection, IList { CollectionChangeEventHandler onCollectionChanged; - ArrayList items = new ArrayList(); - DataGrid owner = null; + readonly ArrayList items = new ArrayList(); + readonly DataGrid owner = null; int IList.Add(object value) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs index a1efdaeb7fe..5a3c198f67e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTextBoxColumn.cs @@ -25,8 +25,8 @@ public class DataGridTextBoxColumn : DataGridColumnStyle { // ui State - private int xMargin = 2; - private int yMargin = 1; + private readonly int xMargin = 2; + private readonly int yMargin = 1; // private int fontHandle = 0; private string format = null; private TypeConverter typeConverter; @@ -34,7 +34,7 @@ public class DataGridTextBoxColumn : DataGridColumnStyle private System.Reflection.MethodInfo parseMethod; // hosted control - private DataGridTextBox edit; + private readonly DataGridTextBox edit; // editing state private string oldValue = null; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs index 9f5846408e9..1de82aac184 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridToolTip.cs @@ -20,7 +20,7 @@ internal class DataGridToolTip : MarshalByRefObject private NativeWindow tipWindow = null; // the dataGrid which contains this toolTip - private DataGrid dataGrid = null; + private readonly DataGrid dataGrid = null; // CONSTRUCTOR public DataGridToolTip(DataGrid dataGrid) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridView.cs index ecacc400d65..19c156da261 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridView.cs @@ -300,24 +300,24 @@ public partial class DataGridView : Control, ISupportInitialize private DataGridViewEditMode editMode; // Note that a cell can only be in one bag but not both at the same time. - private DataGridViewCellLinkedList individualSelectedCells; - private DataGridViewCellLinkedList individualReadOnlyCells; - private DataGridViewIntLinkedList selectedBandIndexes; + private readonly DataGridViewCellLinkedList individualSelectedCells; + private readonly DataGridViewCellLinkedList individualReadOnlyCells; + private readonly DataGridViewIntLinkedList selectedBandIndexes; private DataGridViewIntLinkedList selectedBandSnapshotIndexes; private DataGridViewCellStyle defaultCellStyle, columnHeadersDefaultCellStyle, rowHeadersDefaultCellStyle; private DataGridViewCellStyle rowsDefaultCellStyle, alternatingRowsDefaultCellStyle; private ScrollBars scrollBars; private LayoutData layout; - private DisplayedBandsData displayedBandsInfo; + private readonly DisplayedBandsData displayedBandsInfo; private Rectangle normalClientRectangle; - private ArrayList lstRows; + private readonly ArrayList lstRows; private int availableWidthForFillColumns; private BorderStyle borderStyle; - private DataGridViewAdvancedBorderStyle advancedCellBorderStyle; - private DataGridViewAdvancedBorderStyle advancedRowHeadersBorderStyle; - private DataGridViewAdvancedBorderStyle advancedColumnHeadersBorderStyle; + private readonly DataGridViewAdvancedBorderStyle advancedCellBorderStyle; + private readonly DataGridViewAdvancedBorderStyle advancedRowHeadersBorderStyle; + private readonly DataGridViewAdvancedBorderStyle advancedColumnHeadersBorderStyle; private DataGridViewClipboardCopyMode clipboardCopyMode; @@ -383,7 +383,7 @@ public partial class DataGridView : Control, ISupportInitialize private System.Windows.Forms.Timer vertScrollTimer, horizScrollTimer; - private Hashtable converters; + private readonly Hashtable converters; private Hashtable pens; private Hashtable brushes; @@ -393,7 +393,7 @@ public partial class DataGridView : Control, ISupportInitialize private DataGridViewDataConnection dataConnection; // ToolTip - private DataGridViewToolTip toolTipControl; + private readonly DataGridViewToolTip toolTipControl; // the tool tip string we get from cells private string toolTipCaption = string.Empty; @@ -6044,7 +6044,7 @@ private struct MouseClickInfo internal class DataGridViewEditingPanel : Panel { - private DataGridView owningDataGridView; + private readonly DataGridView owningDataGridView; public DataGridViewEditingPanel(DataGridView owningDataGridView) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAccessibleObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAccessibleObject.cs index b0a60848aeb..496afdc850c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAccessibleObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAccessibleObject.cs @@ -16,7 +16,7 @@ protected class DataGridViewAccessibleObject : ControlAccessibleObject { private int[] runtimeId = null; // Used by UIAutomation - DataGridView owner; + readonly DataGridView owner; DataGridViewTopRowAccessibleObject topRowAccessibilityObject = null; DataGridViewSelectedCellsAccessibleObject selectedCellsAccessibilityObject = null; @@ -450,8 +450,8 @@ internal override UnsafeNativeMethods.IRawElementProviderFragment GetFocus() internal class DataGridViewEditingPanelAccessibleObject : ControlAccessibleObject { - private DataGridView dataGridView; - private Panel panel; + private readonly DataGridView dataGridView; + private readonly Panel panel; public DataGridViewEditingPanelAccessibleObject(DataGridView dataGridView, Panel panel) : base(panel) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAdvancedBorderStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAdvancedBorderStyle.cs index d70fb2a8bde..18c1ca8023b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAdvancedBorderStyle.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewAdvancedBorderStyle.cs @@ -10,9 +10,9 @@ namespace System.Windows.Forms public sealed class DataGridViewAdvancedBorderStyle : ICloneable { - private DataGridView owner; + private readonly DataGridView owner; private bool all = true; - private DataGridViewAdvancedCellBorderStyle banned1, banned2, banned3; + private readonly DataGridViewAdvancedCellBorderStyle banned1, banned2, banned3; private DataGridViewAdvancedCellBorderStyle top = DataGridViewAdvancedCellBorderStyle.None; private DataGridViewAdvancedCellBorderStyle left = DataGridViewAdvancedCellBorderStyle.None; private DataGridViewAdvancedCellBorderStyle right = DataGridViewAdvancedCellBorderStyle.None; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonCell.cs index 597db7c97ef..d8f163c2106 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonCell.cs @@ -33,9 +33,9 @@ public class DataGridViewButtonCell : DataGridViewCell private static Rectangle rectThemeMargins = new Rectangle(-1, -1, 0, 0); private static bool mouseInContentBounds = false; - private static Type defaultFormattedValueType = typeof(string); - private static Type defaultValueType = typeof(object); - private static Type cellType = typeof(DataGridViewButtonCell); + private static readonly Type defaultFormattedValueType = typeof(string); + private static readonly Type defaultValueType = typeof(object); + private static readonly Type cellType = typeof(DataGridViewButtonCell); public DataGridViewButtonCell() { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonColumn.cs index 589c01cace6..20cdecbb0da 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonColumn.cs @@ -15,7 +15,7 @@ namespace System.Windows.Forms [ToolboxBitmapAttribute(typeof(DataGridViewButtonColumn), "DataGridViewButtonColumn")] public class DataGridViewButtonColumn : DataGridViewColumn { - private static Type columnType = typeof(DataGridViewButtonColumn); + private static readonly Type columnType = typeof(DataGridViewButtonColumn); private string text; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs index f2027a36576..d46f0394c29 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs @@ -55,11 +55,11 @@ public abstract class DataGridViewCell : DataGridViewElement, ICloneable, IDispo private static Bitmap errorBmp = null; - private PropertyStore propertyStore; // Contains all properties that are not always set. + private readonly PropertyStore propertyStore; // Contains all properties that are not always set. private DataGridViewRow owningRow; private DataGridViewColumn owningColumn; - private static Type stringType = typeof(string); // cache the string type for performance + private static readonly Type stringType = typeof(string); // cache the string type for performance private byte flags; // see DATAGRIDVIEWCELL_flag* consts above diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellCollection.cs index c96a08037b0..c9451d84c08 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellCollection.cs @@ -23,8 +23,8 @@ namespace System.Windows.Forms public class DataGridViewCellCollection : BaseCollection, IList { CollectionChangeEventHandler onCollectionChanged; - ArrayList items = new ArrayList(); - DataGridViewRow owner = null; + readonly ArrayList items = new ArrayList(); + readonly DataGridViewRow owner = null; int IList.Add(object value) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellLinkedList.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellLinkedList.cs index 3c4db1d77cb..ee20319a927 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellLinkedList.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellLinkedList.cs @@ -208,7 +208,7 @@ public int RemoveAllCellsAtBand(bool column, int bandIndex) /// internal class DataGridViewCellLinkedListEnumerator : IEnumerator { - private DataGridViewCellLinkedListElement headElement; + private readonly DataGridViewCellLinkedListElement headElement; private DataGridViewCellLinkedListElement current; private bool reset; @@ -255,7 +255,7 @@ void IEnumerator.Reset() /// internal class DataGridViewCellLinkedListElement { - private DataGridViewCell dataGridViewCell; + private readonly DataGridViewCell dataGridViewCell; private DataGridViewCellLinkedListElement next; public DataGridViewCellLinkedListElement(DataGridViewCell dataGridViewCell) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellPaintingEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellPaintingEventArgs.cs index fedb36026cf..0e5b13a4765 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellPaintingEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellPaintingEventArgs.cs @@ -10,7 +10,7 @@ namespace System.Windows.Forms { public class DataGridViewCellPaintingEventArgs : HandledEventArgs { - private DataGridView _dataGridView; + private readonly DataGridView _dataGridView; public DataGridViewCellPaintingEventArgs(DataGridView dataGridView, Graphics graphics, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyle.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyle.cs index 64bcbb0d507..d8d83649c33 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyle.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellStyle.cs @@ -34,7 +34,7 @@ public class DataGridViewCellStyle : ICloneable private static readonly int PropWrapMode = PropertyStore.CreateKey(); private DataGridViewCellStyleScopes scope; - private PropertyStore propertyStore; // Contains all properties that are not always set. + private readonly PropertyStore propertyStore; // Contains all properties that are not always set. private DataGridView dataGridView; /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs index 1710868c4c5..e7ec8890376 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs @@ -43,9 +43,9 @@ public class DataGridViewCheckBoxCell : DataGridViewCell, IDataGridViewEditingCe private byte flags; // see DATAGRIDVIEWCHECKBOXCELL_ consts above private static bool mouseInContentBounds = false; - private static Type defaultCheckStateType = typeof(System.Windows.Forms.CheckState); - private static Type defaultBooleanType = typeof(bool); - private static Type cellType = typeof(DataGridViewCheckBoxCell); + private static readonly Type defaultCheckStateType = typeof(System.Windows.Forms.CheckState); + private static readonly Type defaultBooleanType = typeof(bool); + private static readonly Type cellType = typeof(DataGridViewCheckBoxCell); public DataGridViewCheckBoxCell() : this(false /*threeState*/) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs index 90f62efef3d..c26bf147dd9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs @@ -26,13 +26,13 @@ namespace System.Windows.Forms public class DataGridViewColumnCollection : BaseCollection, IList { private CollectionChangeEventHandler onCollectionChanged; - private ArrayList items = new ArrayList(); + private readonly ArrayList items = new ArrayList(); private ArrayList itemsSorted; private int lastAccessedSortedIndex = -1; private int columnCountsVisible, columnCountsVisibleSelected; private int columnsWidthVisible, columnsWidthVisibleFrozen; - private static ColumnOrderComparer columnOrderComparer = new ColumnOrderComparer(); - private DataGridView dataGridView; + private static readonly ColumnOrderComparer columnOrderComparer = new ColumnOrderComparer(); + private readonly DataGridView dataGridView; /* IList interface implementation */ diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnDesignTimeVisibleAttribute.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnDesignTimeVisibleAttribute.cs index a88c70722e4..b9dfb54d046 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnDesignTimeVisibleAttribute.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnDesignTimeVisibleAttribute.cs @@ -9,7 +9,7 @@ namespace System.Windows.Forms [AttributeUsage(AttributeTargets.Class)] public sealed class DataGridViewColumnDesignTimeVisibleAttribute : Attribute { - private bool visible; + private readonly bool visible; public DataGridViewColumnDesignTimeVisibleAttribute(bool visible) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnHeaderCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnHeaderCell.cs index 8ebb08e2fc4..b5b82bd45ed 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnHeaderCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnHeaderCell.cs @@ -32,7 +32,7 @@ public class DataGridViewColumnHeaderCell : DataGridViewHeaderCell private static byte sortGlyphWidth = DATAGRIDVIEWCOLUMNHEADERCELL_sortGlyphWidth; private static byte sortGlyphHeight = DATAGRIDVIEWCOLUMNHEADERCELL_sortGlyphHeight; - private static Type cellType = typeof(DataGridViewColumnHeaderCell); + private static readonly Type cellType = typeof(DataGridViewColumnHeaderCell); private SortOrder sortGlyphDirection; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs index 91c9fc4c929..6f3b2769482 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs @@ -52,10 +52,10 @@ public class DataGridViewComboBoxCell : DataGridViewCell internal const int DATAGRIDVIEWCOMBOBOXCELL_defaultMaxDropDownItems = 8; - private static Type defaultFormattedValueType = typeof(string); - private static Type defaultEditType = typeof(System.Windows.Forms.DataGridViewComboBoxEditingControl); - private static Type defaultValueType = typeof(object); - private static Type cellType = typeof(DataGridViewComboBoxCell); + private static readonly Type defaultFormattedValueType = typeof(string); + private static readonly Type defaultEditType = typeof(System.Windows.Forms.DataGridViewComboBoxEditingControl); + private static readonly Type defaultValueType = typeof(object); + private static readonly Type cellType = typeof(DataGridViewComboBoxCell); private byte flags; // see DATAGRIDVIEWCOMBOBOXCELL_ consts above private static bool mouseInDropDownButtonBounds = false; @@ -68,7 +68,7 @@ public class DataGridViewComboBoxCell : DataGridViewCell //private object valueUsedDuringAutoSize = null; private static bool isScalingInitialized = false; - private static int OFFSET_2PIXELS = 2; + private static readonly int OFFSET_2PIXELS = 2; private static int offset2X = OFFSET_2PIXELS; private static int offset2Y = OFFSET_2PIXELS; private static byte nonXPTriangleHeight = DATAGRIDVIEWCOMBOBOXCELL_nonXPTriangleHeight; @@ -2689,7 +2689,7 @@ private void WireDataSource(object dataSource) [ListBindable(false)] public class ObjectCollection : IList { - private DataGridViewComboBoxCell owner; + private readonly DataGridViewComboBoxCell owner; private ArrayList items; private IComparer comparer; @@ -3020,7 +3020,7 @@ public void RemoveAt(int index) private sealed class ItemComparer : System.Collections.IComparer { - private DataGridViewComboBoxCell dataGridViewComboBoxCell; + private readonly DataGridViewComboBoxCell dataGridViewComboBoxCell; public ItemComparer(DataGridViewComboBoxCell dataGridViewComboBoxCell) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxColumn.cs index f7e80bc37ac..9343fd80b8e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxColumn.cs @@ -18,7 +18,7 @@ namespace System.Windows.Forms ] public class DataGridViewComboBoxColumn : DataGridViewColumn { - private static Type columnType = typeof(DataGridViewComboBoxColumn); + private static readonly Type columnType = typeof(DataGridViewComboBoxColumn); public DataGridViewComboBoxColumn() : base(new DataGridViewComboBoxCell()) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxEditingControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxEditingControl.cs index 2b645e80e7f..5336b572617 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxEditingControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxEditingControl.cs @@ -165,7 +165,7 @@ protected override void OnSelectedIndexChanged(EventArgs e) /// internal class DataGridViewComboBoxEditingControlAccessibleObject : ComboBox.ComboBoxAccessibleObject { - private DataGridViewComboBoxEditingControl ownerControl; + private readonly DataGridViewComboBoxEditingControl ownerControl; /// /// The parent is changed when the editing control is attached to another editing cell. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewControlCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewControlCollection.cs index 59c84af0ded..9f27717d70e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewControlCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewControlCollection.cs @@ -16,7 +16,7 @@ public partial class DataGridView ] public class DataGridViewControlCollection : Control.ControlCollection { - DataGridView owner; + readonly DataGridView owner; public DataGridViewControlCollection(DataGridView owner) : base(owner) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewDataConnection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewDataConnection.cs index 02a876c5ee5..1f42094f65f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewDataConnection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewDataConnection.cs @@ -17,7 +17,7 @@ public partial class DataGridView { internal class DataGridViewDataConnection { - DataGridView owner = null; + readonly DataGridView owner = null; CurrencyManager currencyManager = null; object dataSource = null; string dataMember = string.Empty; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHeaderCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHeaderCell.cs index c508c357f83..24de10bd3a0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHeaderCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHeaderCell.cs @@ -20,9 +20,9 @@ public class DataGridViewHeaderCell : DataGridViewCell { private const byte DATAGRIDVIEWHEADERCELL_themeMargin = 100; // Used to calculate the margins required for theming rendering - private static Type defaultFormattedValueType = typeof(string); - private static Type defaultValueType = typeof(object); - private static Type cellType = typeof(DataGridViewHeaderCell); + private static readonly Type defaultFormattedValueType = typeof(string); + private static readonly Type defaultValueType = typeof(object); + private static readonly Type cellType = typeof(DataGridViewHeaderCell); private static Rectangle rectThemeMargins = new Rectangle(-1, -1, 0, 0); private static readonly int PropValueType = PropertyStore.CreateKey(); private static readonly int PropButtonState = PropertyStore.CreateKey(); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageCell.cs index 58459d0a26d..ac73f6766c2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageCell.cs @@ -16,12 +16,12 @@ namespace System.Windows.Forms public class DataGridViewImageCell : DataGridViewCell { - private static ColorMap[] colorMap = new ColorMap[] { new ColorMap() }; + private static readonly ColorMap[] colorMap = new ColorMap[] { new ColorMap() }; private static readonly int PropImageCellDescription = PropertyStore.CreateKey(); private static readonly int PropImageCellLayout = PropertyStore.CreateKey(); - private static Type defaultTypeImage = typeof(System.Drawing.Image); - private static Type defaultTypeIcon = typeof(System.Drawing.Icon); - private static Type cellType = typeof(DataGridViewImageCell); + private static readonly Type defaultTypeImage = typeof(System.Drawing.Image); + private static readonly Type defaultTypeIcon = typeof(System.Drawing.Icon); + private static readonly Type cellType = typeof(DataGridViewImageCell); private static Bitmap errorBmp = null; private static Icon errorIco = null; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageColumn.cs index 7e958af4cfa..8141fbf9541 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewImageColumn.cs @@ -16,7 +16,7 @@ namespace System.Windows.Forms [ToolboxBitmapAttribute(typeof(DataGridViewImageColumn), "DataGridViewImageColumn")] public class DataGridViewImageColumn : DataGridViewColumn { - private static Type columnType = typeof(DataGridViewImageColumn); + private static readonly Type columnType = typeof(DataGridViewImageColumn); private Image image; private Icon icon; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewIntLinkedList.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewIntLinkedList.cs index ebb95f76a0c..8b9fa60b760 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewIntLinkedList.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewIntLinkedList.cs @@ -208,7 +208,7 @@ public void RemoveAt(int index) /// internal class DataGridViewIntLinkedListEnumerator : IEnumerator { - private DataGridViewIntLinkedListElement headElement; + private readonly DataGridViewIntLinkedListElement headElement; private DataGridViewIntLinkedListElement current; private bool reset; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkCell.cs index cb434dba1c8..ca171dfbb56 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkCell.cs @@ -20,9 +20,9 @@ public class DataGridViewLinkCell : DataGridViewCell private static readonly DataGridViewContentAlignment anyRight = DataGridViewContentAlignment.TopRight | DataGridViewContentAlignment.MiddleRight | DataGridViewContentAlignment.BottomRight; private static readonly DataGridViewContentAlignment anyBottom = DataGridViewContentAlignment.BottomRight | DataGridViewContentAlignment.BottomCenter | DataGridViewContentAlignment.BottomLeft; - private static Type defaultFormattedValueType = typeof(string); - private static Type defaultValueType = typeof(object); - private static Type cellType = typeof(DataGridViewLinkCell); + private static readonly Type defaultFormattedValueType = typeof(string); + private static readonly Type defaultValueType = typeof(object); + private static readonly Type cellType = typeof(DataGridViewLinkCell); private static readonly int PropLinkCellActiveLinkColor = PropertyStore.CreateKey(); private static readonly int PropLinkCellLinkBehavior = PropertyStore.CreateKey(); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkColumn.cs index 660c3b33f54..c5fd1a7fe40 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewLinkColumn.cs @@ -14,7 +14,7 @@ namespace System.Windows.Forms [ToolboxBitmapAttribute(typeof(DataGridViewLinkColumn), "DataGridViewLinkColumn")] public class DataGridViewLinkColumn : DataGridViewColumn { - private static Type columnType = typeof(DataGridViewLinkColumn); + private static readonly Type columnType = typeof(DataGridViewLinkColumn); private string text; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRow.cs index 3e46535489e..6ee39b2946f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRow.cs @@ -18,7 +18,7 @@ namespace System.Windows.Forms [TypeConverterAttribute(typeof(DataGridViewRowConverter))] public class DataGridViewRow : DataGridViewBand { - private static Type s_rowType = typeof(DataGridViewRow); + private static readonly Type s_rowType = typeof(DataGridViewRow); private static readonly int s_propRowErrorText = PropertyStore.CreateKey(); private static readonly int s_propRowAccessibilityObject = PropertyStore.CreateKey(); @@ -2252,7 +2252,7 @@ internal override object GetPropertyValue(int propertyId) private class DataGridViewSelectedRowCellsAccessibleObject : AccessibleObject { - private DataGridViewRow owner; + private readonly DataGridViewRow owner; internal DataGridViewSelectedRowCellsAccessibleObject(DataGridViewRow owner) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowCollection.cs index c6738e86128..5f6ed92dcc8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowCollection.cs @@ -37,11 +37,11 @@ public class DataGridViewRowCollection : ICollection, IList #endif private CollectionChangeEventHandler onCollectionChanged; - private RowArrayList items; - private List rowStates; + private readonly RowArrayList items; + private readonly List rowStates; private int rowCountsVisible, rowCountsVisibleFrozen, rowCountsVisibleSelected; private int rowsHeightVisible, rowsHeightVisibleFrozen; - private DataGridView dataGridView; + private readonly DataGridView dataGridView; /* IList interface implementation */ @@ -2581,7 +2581,7 @@ int IComparer.Compare(object x, object y) private class RowArrayList : ArrayList { - private DataGridViewRowCollection owner; + private readonly DataGridViewRowCollection owner; private RowComparer rowComparer; public RowArrayList(DataGridViewRowCollection owner) @@ -2693,13 +2693,13 @@ private object Pivot(int left, int center, int right) private class RowComparer { - private DataGridView dataGridView; - private DataGridViewRowCollection dataGridViewRows; - private DataGridViewColumn dataGridViewSortedColumn; - private int sortedColumnIndex; - private IComparer customComparer; - private bool ascending; - private static ComparedObjectMax max = new ComparedObjectMax(); + private readonly DataGridView dataGridView; + private readonly DataGridViewRowCollection dataGridViewRows; + private readonly DataGridViewColumn dataGridViewSortedColumn; + private readonly int sortedColumnIndex; + private readonly IComparer customComparer; + private readonly bool ascending; + private static readonly ComparedObjectMax max = new ComparedObjectMax(); public RowComparer(DataGridViewRowCollection dataGridViewRows, IComparer customComparer, bool ascending) { @@ -2826,7 +2826,7 @@ public ComparedObjectMax() { } private class UnsharingRowEnumerator : IEnumerator { - private DataGridViewRowCollection owner; + private readonly DataGridViewRowCollection owner; private int current; /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowHeaderCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowHeaderCell.cs index d86fb38f807..6c428033188 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowHeaderCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowHeaderCell.cs @@ -24,7 +24,7 @@ public class DataGridViewRowHeaderCell : DataGridViewHeaderCell private static readonly VisualStyleElement HeaderElement = VisualStyleElement.Header.Item.Normal; // ColorMap used to map the black color of the resource bitmaps to the fore color in use in the row header cell - private static ColorMap[] colorMap = new ColorMap[] { new ColorMap() }; + private static readonly ColorMap[] colorMap = new ColorMap[] { new ColorMap() }; private static Bitmap rightArrowBmp = null; private static Bitmap leftArrowBmp = null; @@ -35,7 +35,7 @@ public class DataGridViewRowHeaderCell : DataGridViewHeaderCell private static Bitmap pencilRTLBmp = null; private static Bitmap starBmp = null; - private static Type cellType = typeof(DataGridViewRowHeaderCell); + private static readonly Type cellType = typeof(DataGridViewRowHeaderCell); private const byte DATAGRIDVIEWROWHEADERCELL_iconMarginWidth = 3; // 3 pixels of margin on the left and right of icons private const byte DATAGRIDVIEWROWHEADERCELL_iconMarginHeight = 2; // 2 pixels of margin on the top and bottom of icons diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedCellCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedCellCollection.cs index 93d1c4c9aac..014e72620c3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedCellCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedCellCollection.cs @@ -22,7 +22,7 @@ namespace System.Windows.Forms ] public class DataGridViewSelectedCellCollection : BaseCollection, IList { - ArrayList items = new ArrayList(); + readonly ArrayList items = new ArrayList(); int IList.Add(object value) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedCellsAccessibleObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedCellsAccessibleObject.cs index f2f112494cc..36943f14882 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedCellsAccessibleObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedCellsAccessibleObject.cs @@ -8,7 +8,7 @@ public partial class DataGridView { private class DataGridViewSelectedCellsAccessibleObject : AccessibleObject { - DataGridView owner; + readonly DataGridView owner; public DataGridViewSelectedCellsAccessibleObject(DataGridView owner) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedColumnCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedColumnCollection.cs index ab5ac716230..b9d77502354 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedColumnCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedColumnCollection.cs @@ -19,7 +19,7 @@ namespace System.Windows.Forms ] public class DataGridViewSelectedColumnCollection : BaseCollection, IList { - ArrayList items = new ArrayList(); + readonly ArrayList items = new ArrayList(); int IList.Add(object value) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedRowCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedRowCollection.cs index db4c2fc0464..f87a261838b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedRowCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSelectedRowCollection.cs @@ -22,7 +22,7 @@ namespace System.Windows.Forms ] public class DataGridViewSelectedRowCollection : BaseCollection, IList { - ArrayList items = new ArrayList(); + readonly ArrayList items = new ArrayList(); int IList.Add(object value) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSortCompareEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSortCompareEventArgs.cs index 9c4f65b0649..47e58bab155 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSortCompareEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewSortCompareEventArgs.cs @@ -10,9 +10,11 @@ namespace System.Windows.Forms public class DataGridViewSortCompareEventArgs : HandledEventArgs { - private DataGridViewColumn dataGridViewColumn; - private object cellValue1, cellValue2; - private int sortResult, rowIndex1, rowIndex2; + private readonly DataGridViewColumn dataGridViewColumn; + private readonly object cellValue1, cellValue2; + private int sortResult; + private readonly int rowIndex1; + private readonly int rowIndex2; public DataGridViewSortCompareEventArgs(DataGridViewColumn dataGridViewColumn, object cellValue1, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxCell.cs index 3aef62a6a93..fdc9342465c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxCell.cs @@ -35,9 +35,9 @@ public class DataGridViewTextBoxCell : DataGridViewCell private byte flagsState; // see DATAGRIDVIEWTEXTBOXCELL_ consts above - private static Type defaultFormattedValueType = typeof(string); - private static Type defaultValueType = typeof(object); - private static Type cellType = typeof(DataGridViewTextBoxCell); + private static readonly Type defaultFormattedValueType = typeof(string); + private static readonly Type defaultValueType = typeof(object); + private static readonly Type cellType = typeof(DataGridViewTextBoxCell); public DataGridViewTextBoxCell() { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxEditingControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxEditingControl.cs index 06cd0551f44..b9997e431b3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxEditingControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewTextBoxEditingControl.cs @@ -304,7 +304,7 @@ private static HorizontalAlignment TranslateAlignment(DataGridViewContentAlignme /// internal class DataGridViewTextBoxEditingControlAccessibleObject : Control.ControlAccessibleObject { - private DataGridViewTextBoxEditingControl ownerControl; + private readonly DataGridViewTextBoxEditingControl ownerControl; /// /// The parent is changed when the editing control is attached to another editing cell. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewToolTip.cs index 125006a8a25..1d49f0f28f7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewToolTip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewToolTip.cs @@ -12,7 +12,7 @@ public partial class DataGridView { private class DataGridViewToolTip { - DataGridView dataGridView = null; + readonly DataGridView dataGridView = null; ToolTip toolTip = null; private bool toolTipActivated = false; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs index 5f3b74f59af..10d11b459ba 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataObject.cs @@ -49,7 +49,7 @@ public class DataObject : IDataObject, IComDataObject TYMED.TYMED_MFPICT, TYMED.TYMED_GDI}; - private IDataObject innerData = null; + private readonly IDataObject innerData = null; internal bool RestrictedFormats { get; set; } // We use this to identify that a stream is actually a serialized object. On read, @@ -1973,7 +1973,7 @@ public DataStoreEntry(object data, bool autoConvert) } } - private Hashtable data = new Hashtable(BackCompatibleStringComparer.Default); + private readonly Hashtable data = new Hashtable(BackCompatibleStringComparer.Default); public DataStore() { @@ -2190,7 +2190,7 @@ private class BitmapBinder : SerializationBinder private static readonly string s_allowedTypeName = "System.Drawing.Bitmap"; private static readonly string s_allowedAssemblyName = "System.Drawing"; // PublicKeyToken=b03f5f7f11d50a3a - private static byte[] s_allowedToken = new byte[] { 0xB0, 0x3F, 0x5F, 0x7F, 0x11, 0xD5, 0x0A, 0x3A }; + private static readonly byte[] s_allowedToken = new byte[] { 0xB0, 0x3F, 0x5F, 0x7F, 0x11, 0xD5, 0x0A, 0x3A }; /// /// Only safe to deserialize types are bypassing this callback, Strings diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs index 05e14c9c591..1c65de9e0a4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Design/ComponentEditorForm.cs @@ -27,8 +27,8 @@ namespace System.Windows.Forms.Design [ToolboxItem(false)] public class ComponentEditorForm : Form { - private IComponent component; - private Type[] pageTypes; + private readonly IComponent component; + private readonly Type[] pageTypes; private ComponentEditorPageSite[] pageSites; private Size maxSize = System.Drawing.Size.Empty; private int initialActivePage; @@ -36,7 +36,7 @@ public class ComponentEditorForm : Form private bool dirty; private bool firstActivate; - private Panel pageHost = new Panel(); + private readonly Panel pageHost = new Panel(); private PageSelector selector; private ImageList selectorImageList; private Button okButton; @@ -561,7 +561,7 @@ private sealed class ComponentEditorPageSite : IComponentEditorPageSite internal Control parent; internal bool isActive; internal bool isDirty; - private ComponentEditorForm form; + private readonly ComponentEditorForm form; /// /// Creates the page site. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DockingAttribute.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DockingAttribute.cs index 50401258cde..06dc9da5782 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DockingAttribute.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DockingAttribute.cs @@ -13,7 +13,7 @@ namespace System.Windows.Forms [AttributeUsage(AttributeTargets.Class)] public sealed class DockingAttribute : Attribute { - private DockingBehavior dockingBehavior; + private readonly DockingBehavior dockingBehavior; /// /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DomainUpDown.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DomainUpDown.cs index e955b6cb1e1..c9747f60d75 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DomainUpDown.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DomainUpDown.cs @@ -660,7 +660,7 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) /// public class DomainUpDownItemCollection : ArrayList { - DomainUpDown owner; + readonly DomainUpDown owner; internal DomainUpDownItemCollection(DomainUpDown owner) : base() @@ -869,7 +869,7 @@ public override int GetChildCount() internal class DomainItemListAccessibleObject : AccessibleObject { - private DomainUpDownAccessibleObject parent; + private readonly DomainUpDownAccessibleObject parent; public DomainItemListAccessibleObject(DomainUpDownAccessibleObject parent) : base() { @@ -942,7 +942,7 @@ public class DomainItemAccessibleObject : AccessibleObject { private string name; - private DomainItemListAccessibleObject parent; + private readonly DomainItemListAccessibleObject parent; public DomainItemAccessibleObject(string name, AccessibleObject parent) : base() { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DrawItemEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DrawItemEventArgs.cs index 52eae454fd8..7be062a2de9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DrawItemEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DrawItemEventArgs.cs @@ -18,12 +18,12 @@ public class DrawItemEventArgs : EventArgs /// /// The backColor to paint each menu item with. /// - private Color _backColor; + private readonly Color _backColor; /// /// The foreColor to paint each menu item with. /// - private Color _foreColor; + private readonly Color _foreColor; /// /// Creates a new DrawItemEventArgs with the given parameters. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DropSource.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DropSource.cs index a03288546ec..b45a561e5d9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DropSource.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DropSource.cs @@ -14,7 +14,7 @@ internal class DropSource : UnsafeNativeMethods.IOleDropSource private const int DragDropSCancel = 0x00040101; private const int DragDropSUseDefaultCursors = 0x00040102; - private ISupportOleDropSource peer; + private readonly ISupportOleDropSource peer; public DropSource(ISupportOleDropSource peer) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DropTarget.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DropTarget.cs index 444bf3cf6fd..b76ea1120be 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DropTarget.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DropTarget.cs @@ -12,7 +12,7 @@ internal class DropTarget : UnsafeNativeMethods.IOleDropTarget { private IDataObject lastDataObject = null; private DragDropEffects lastEffect = DragDropEffects.None; - private IDropTarget owner; + private readonly IDropTarget owner; public DropTarget(IDropTarget owner) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs index 7ab8b87877a..f3a9dca5438 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs @@ -40,8 +40,8 @@ public class ErrorProvider : Component, IExtenderProvider, ISupportInitialize // FIELDS // - Hashtable items = new Hashtable(); - Hashtable windows = new Hashtable(); + readonly Hashtable items = new Hashtable(); + readonly Hashtable windows = new Hashtable(); Icon icon = DefaultIcon; IconRegion region; int itemIdCounter; @@ -62,10 +62,10 @@ public class ErrorProvider : Component, IExtenderProvider, ISupportInitialize private object dataSource = null; private string dataMember = null; private BindingManagerBase errorManager; - private EventHandler currentChanged; + private readonly EventHandler currentChanged; // listen to the OnPropertyChanged event in the ContainerControl - private EventHandler propChangedEvent; + private readonly EventHandler propChangedEvent; private EventHandler onRightToLeftChanged; private bool rightToLeft = false; @@ -945,9 +945,9 @@ internal class ErrorWindow : NativeWindow // FIELDS // - ArrayList items = new ArrayList(); - Control parent; - ErrorProvider provider; + readonly ArrayList items = new ArrayList(); + readonly Control parent; + readonly ErrorProvider provider; Rectangle windowBounds = Rectangle.Empty; System.Windows.Forms.Timer timer; NativeWindow tipWindow; @@ -1443,11 +1443,11 @@ internal class ControlItem // string error; - Control control; + readonly Control control; ErrorWindow window; - ErrorProvider provider; + readonly ErrorProvider provider; int blinkPhase; - IntPtr id; + readonly IntPtr id; int iconPadding; bool toolTipShown; ErrorIconAlignment iconAlignment; @@ -1809,7 +1809,7 @@ internal class IconRegion // Region region; - Icon icon; + readonly Icon icon; // // CONSTRUCTORS diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FlatButtonAppearance.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FlatButtonAppearance.cs index 118f7971e4b..d1c1a8c602c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FlatButtonAppearance.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FlatButtonAppearance.cs @@ -16,7 +16,7 @@ namespace System.Windows.Forms public class FlatButtonAppearance { - private ButtonBase owner; + private readonly ButtonBase owner; private int borderSize = 1; private Color borderColor = Color.Empty; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FlowLayoutPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FlowLayoutPanel.cs index c76b92be769..7ba5e9a263f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FlowLayoutPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FlowLayoutPanel.cs @@ -20,7 +20,7 @@ namespace System.Windows.Forms [SRDescription(nameof(SR.DescriptionFlowLayoutPanel))] public class FlowLayoutPanel : Panel, IExtenderProvider { - private FlowLayoutSettings _flowLayoutSettings; + private readonly FlowLayoutSettings _flowLayoutSettings; public FlowLayoutPanel() { 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 f0ec71ca3e2..c67eff20cbd 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs @@ -119,7 +119,7 @@ public class Form : ContainerControl #if MAGIC_PADDING private static Padding FormPadding = new Padding(9); // UI guideline #endif - private static object internalSyncObject = new object(); + private static readonly object internalSyncObject = new object(); // 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 @@ -7492,7 +7492,7 @@ protected override void WndProc(ref Message m) public new class ControlCollection : Control.ControlCollection { - private Form owner; + private readonly Form owner; /*C#r:protected*/ diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs index 3cccc3e9496..f6f0b6e384a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlDocument.cs @@ -24,8 +24,8 @@ public sealed class HtmlDocument internal static object EventMouseUp = new object(); internal static object EventStop = new object(); - private UnsafeNativeMethods.IHTMLDocument2 htmlDocument2; - private HtmlShimManager shimManager; + private readonly UnsafeNativeMethods.IHTMLDocument2 htmlDocument2; + private readonly HtmlShimManager shimManager; internal HtmlDocument(HtmlShimManager shimManager, UnsafeNativeMethods.IHTMLDocument doc) { @@ -651,7 +651,7 @@ internal class HtmlDocumentShim : HtmlShim { private AxHost.ConnectionPointCookie cookie; private HtmlDocument htmlDocument; - private UnsafeNativeMethods.IHTMLWindow2 associatedWindow = null; + private readonly UnsafeNativeMethods.IHTMLWindow2 associatedWindow = null; internal HtmlDocumentShim(HtmlDocument htmlDocument) { @@ -763,7 +763,7 @@ protected override object GetEventSender() private class HTMLDocumentEvents2 : StandardOleMarshalObject, /*Enforce calling back on the same thread*/ UnsafeNativeMethods.DHTMLDocumentEvents2 { - private HtmlDocument parent; + private readonly HtmlDocument parent; public HTMLDocumentEvents2(HtmlDocument htmlDocument) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs index 9b82842e4f7..eb4766d0cb5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElement.cs @@ -31,8 +31,8 @@ public sealed class HtmlElement internal static readonly object EventMouseOver = new object(); internal static readonly object EventMouseUp = new object(); - private UnsafeNativeMethods.IHTMLElement htmlElement; - private HtmlShimManager shimManager; + private readonly UnsafeNativeMethods.IHTMLElement htmlElement; + private readonly HtmlShimManager shimManager; internal HtmlElement(HtmlShimManager shimManager, UnsafeNativeMethods.IHTMLElement element) { @@ -689,7 +689,7 @@ private class HTMLElementEvents2 : StandardOleMarshalObject, /*Enforce calling b UnsafeNativeMethods.DHTMLScriptEvents2 { - private HtmlElement parent; + private readonly HtmlElement parent; public HTMLElementEvents2(HtmlElement htmlElement) { @@ -1040,7 +1040,7 @@ public void onstart(UnsafeNativeMethods.IHTMLEventObj evtObj) { } internal class HtmlElementShim : HtmlShim { - private static Type[] dispInterfaceTypes = {typeof(UnsafeNativeMethods.DHTMLElementEvents2), + private static readonly Type[] dispInterfaceTypes = {typeof(UnsafeNativeMethods.DHTMLElementEvents2), typeof(UnsafeNativeMethods.DHTMLAnchorEvents2), typeof(UnsafeNativeMethods.DHTMLAreaEvents2), typeof(UnsafeNativeMethods.DHTMLButtonElementEvents2), @@ -1064,7 +1064,7 @@ internal class HtmlElementShim : HtmlShim private AxHost.ConnectionPointCookie cookie; // To hook up events from the native HtmlElement private HtmlElement htmlElement; - private UnsafeNativeMethods.IHTMLWindow2 associatedWindow = null; + private readonly UnsafeNativeMethods.IHTMLWindow2 associatedWindow = null; public HtmlElementShim(HtmlElement element) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementCollection.cs index b40478fa679..8cc6bb7bc52 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementCollection.cs @@ -9,9 +9,9 @@ namespace System.Windows.Forms { public sealed class HtmlElementCollection : ICollection { - private UnsafeNativeMethods.IHTMLElementCollection htmlElementCollection; - private HtmlElement[] elementsArray; - private HtmlShimManager shimManager; + private readonly UnsafeNativeMethods.IHTMLElementCollection htmlElementCollection; + private readonly HtmlElement[] elementsArray; + private readonly HtmlShimManager shimManager; internal HtmlElementCollection(HtmlShimManager shimManager) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementEventArgs.cs index acfb34f7fe5..84c5ecbddc3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlElementEventArgs.cs @@ -11,7 +11,7 @@ namespace System.Windows.Forms public sealed class HtmlElementEventArgs : EventArgs { - private HtmlShimManager _shimManager; + private readonly HtmlShimManager _shimManager; internal HtmlElementEventArgs(HtmlShimManager shimManager, UnsafeNativeMethods.IHTMLEventObj eventObj) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlToClrEventProxy.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlToClrEventProxy.cs index 914e7d0fedb..2b2369a4118 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlToClrEventProxy.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlToClrEventProxy.cs @@ -15,10 +15,10 @@ namespace System.Windows.Forms /// internal class HtmlToClrEventProxy : IReflect { - private EventHandler eventHandler; - private IReflect typeIReflectImplementation; - private object sender = null; - private string eventName; + private readonly EventHandler eventHandler; + private readonly IReflect typeIReflectImplementation; + private readonly object sender = null; + private readonly string eventName; public HtmlToClrEventProxy(object sender, string eventName, EventHandler eventHandler) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindow.cs index 5ca88803f0d..577e1b1c4f3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindow.cs @@ -24,8 +24,8 @@ public sealed class HtmlWindow internal static readonly object EventScroll = new object(); internal static readonly object EventUnload = new object(); - private HtmlShimManager shimManager; - private UnsafeNativeMethods.IHTMLWindow2 htmlWindow2; + private readonly HtmlShimManager shimManager; + private readonly UnsafeNativeMethods.IHTMLWindow2 htmlWindow2; internal HtmlWindow(HtmlShimManager shimManager, UnsafeNativeMethods.IHTMLWindow2 win) { @@ -388,7 +388,7 @@ public event HtmlElementEventHandler Unload private class HTMLWindowEvents2 : StandardOleMarshalObject, /*Enforce calling back on the same thread*/ UnsafeNativeMethods.DHTMLWindowEvents2 { - private HtmlWindow parent; + private readonly HtmlWindow parent; public HTMLWindowEvents2(HtmlWindow htmlWindow) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindowCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindowCollection.cs index 98852f24aca..ef2c58bf5d2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindowCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlWindowCollection.cs @@ -10,8 +10,8 @@ namespace System.Windows.Forms { public class HtmlWindowCollection : ICollection { - private UnsafeNativeMethods.IHTMLFramesCollection2 htmlFramesCollection2; - private HtmlShimManager shimManager; + private readonly UnsafeNativeMethods.IHTMLFramesCollection2 htmlFramesCollection2; + private readonly HtmlShimManager shimManager; internal HtmlWindowCollection(HtmlShimManager shimManager, UnsafeNativeMethods.IHTMLFramesCollection2 collection) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs index b8de3d2b88f..b5da5d24b28 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs @@ -41,7 +41,7 @@ public sealed class ImageList : Component { // gpr: Copied from Icon - private static Color fakeTransparencyColor = Color.FromArgb(0x0d, 0x0b, 0x0c); + private static readonly Color fakeTransparencyColor = Color.FromArgb(0x0d, 0x0b, 0x0c); private static Size DefaultImageSize = new Size(16, 16); private const int INITIAL_CAPACITY = 4; @@ -1033,7 +1033,7 @@ internal class NativeImageList : IDisposable { private IntPtr himl; #if DEBUG - private string callStack; + private readonly string callStack; #endif internal NativeImageList(IntPtr himl) @@ -1132,8 +1132,8 @@ private enum OriginalOptions ] public sealed class ImageCollection : IList { - private ImageList owner; - private ArrayList imageInfoCollection = new ArrayList(); + private readonly ImageList owner; + private readonly ArrayList imageInfoCollection = new ArrayList(); /// A caching mechanism for key accessor /// We use an index here rather than control so that we don't have lifetime diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ImageListStreamer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ImageListStreamer.cs index 7e4dcb978ca..338c0398272 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ImageListStreamer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ImageListStreamer.cs @@ -26,9 +26,9 @@ public sealed class ImageListStreamer : ISerializable, IDisposable // (unicode for MSFT). // private static readonly byte[] HEADER_MAGIC = new byte[] { 0x4D, 0x53, 0x46, 0X74 }; - private static object internalSyncObject = new object(); + private static readonly object internalSyncObject = new object(); - private ImageList imageList; + private readonly ImageList imageList; private ImageList.NativeImageList nativeImageList; internal ImageListStreamer(ImageList il) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/KeyboardToolTipStateMachine.cs b/src/System.Windows.Forms/src/System/Windows/Forms/KeyboardToolTipStateMachine.cs index 850584311ab..128d3f179c1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/KeyboardToolTipStateMachine.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/KeyboardToolTipStateMachine.cs @@ -375,7 +375,7 @@ private sealed class InternalStateMachineTimer : Timer private sealed class ToolToTipDictionary { - private ConditionalWeakTable> table = new ConditionalWeakTable>(); + private readonly ConditionalWeakTable> table = new ConditionalWeakTable>(); public ToolTip this[IKeyboardToolTip tool] { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs index dec340068c4..b3d9a379d64 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Label.cs @@ -1889,7 +1889,7 @@ internal override object GetPropertyValue(int propertyID) /// internal class LabelImageIndexer : ImageList.Indexer { - private Label owner; + private readonly Label owner; private bool useIntegerIndex = true; public LabelImageIndexer(Label owner) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElementCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElementCollection.cs index c6e02063531..ca34ccfbeeb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElementCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElementCollection.cs @@ -13,7 +13,7 @@ public class ArrangedElementCollection : IList // We wrap an ArrayList rather than inherit from CollectionBase because we // do not want to break binary compatibility with ControlCollection. - private ArrayList _innerList; + private readonly ArrayList _innerList; // Internal constructor prevents externals from getting a hold of one of these. // We'll open this up in Orcas. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs index ba0b391ad81..79f6cc03626 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs @@ -355,10 +355,10 @@ public static void SetFlowDirection(IArrangedElement container, FlowDirection va private class ContainerProxy { - private IArrangedElement _container; + private readonly IArrangedElement _container; private ElementProxy _elementProxy; private Rectangle _displayRect; - private bool _isContainerRTL; + private readonly bool _isContainerRTL; public ContainerProxy(IArrangedElement container) { _container = container; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutSettings.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutSettings.cs index e4cf94723c5..9f601594103 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutSettings.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutSettings.cs @@ -8,7 +8,7 @@ namespace System.Windows.Forms public abstract class LayoutSettings { - private IArrangedElement _owner; + private readonly IArrangedElement _owner; protected LayoutSettings() { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutUtils.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutUtils.cs index 27ecc3ca21c..43025e19ae3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutUtils.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutUtils.cs @@ -764,11 +764,11 @@ public PreferredSizeCache(Size constrainingSize, Size preferredSize) // it didn't seem significant (we were spinning off more from LayoutEventArgs.) internal sealed class LayoutTransaction : IDisposable { - Control _controlToLayout; - bool _resumeLayout; + readonly Control _controlToLayout; + readonly bool _resumeLayout; #if DEBUG - int _layoutSuspendCount; + readonly int _layoutSuspendCount; #endif public LayoutTransaction(Control controlToLayout, IArrangedElement controlCausingLayout, string property) : this(controlToLayout, controlCausingLayout, property, true) 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 5b4747a64e7..e9c5244ec5b 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 @@ -35,8 +35,8 @@ private static int GetMedian(int low, int hi) // Private value type used by the Sort methods. private struct SorterObjectArray { - private object[] keys; - private IComparer comparer; + private readonly object[] keys; + private readonly IComparer comparer; internal SorterObjectArray(object[] keys, IComparer comparer) { @@ -174,7 +174,7 @@ private static void Sort(object[] array, IComparer comparer) private static readonly int _layoutInfoProperty = PropertyStore.CreateKey(); - private static string[] _propertiesWhichInvalidateCache = new string[] { + private static readonly string[] _propertiesWhichInvalidateCache = new string[] { //suspend layout before changing one of the above property will cause the AffectedProperty of LayoutEventArgs to be set to null //for more information, see http://wiki/default.aspx/Microsoft.Projects.DotNetClient.LayoutEventArgs @@ -1532,7 +1532,7 @@ internal sealed class LayoutInfo private int _colPos = -1; //the element which owns this layoutInfo - private IArrangedElement _element; + private readonly IArrangedElement _element; public LayoutInfo(IArrangedElement element) { @@ -1679,7 +1679,7 @@ internal static ContainerInfo GetContainerInfo(IArrangedElement container) /// internal sealed class ContainerInfo { - private static Strip[] emptyStrip = new Strip[0]; + private static readonly Strip[] emptyStrip = new Strip[0]; private static readonly int stateValid = BitVector32.CreateMask(); private static readonly int stateChildInfoValid = BitVector32.CreateMask(stateValid); @@ -1694,7 +1694,7 @@ internal sealed class ContainerInfo private TableLayoutRowStyleCollection _rowStyles; private TableLayoutColumnStyleCollection _colStyles; private TableLayoutPanelGrowStyle _growStyle; - private IArrangedElement _container; + private readonly IArrangedElement _container; private LayoutInfo[] _childInfo; private int _countFixedChildren; private int _minRowsAndColumns; // The minimum space required to put all the controls without overlapping @@ -2243,7 +2243,7 @@ public int Compare(object x, object y) private sealed class ReservationGrid { int _numColumns = 1; - ArrayList _rows = new ArrayList(); + readonly ArrayList _rows = new ArrayList(); public bool IsReserved(int column, int rowOffset) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs index cbd06d83caf..bd9c4b50a34 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs @@ -41,7 +41,7 @@ public class LinkLabel : Label, IButtonControl static readonly object EventLinkClicked = new object(); static Color iedisabledLinkColor = Color.Empty; - static LinkComparer linkComparer = new LinkComparer(); + static readonly LinkComparer linkComparer = new LinkComparer(); /// /// The dialog result that will be sent to the parent dialog form when @@ -59,8 +59,7 @@ public class LinkLabel : Label, IButtonControl bool textLayoutValid = false; bool receivedDoubleClick = false; - - ArrayList links = new ArrayList(2); + readonly ArrayList links = new ArrayList(2); Link focusLink = null; LinkCollection linkCollection = null; @@ -2202,7 +2201,7 @@ protected override void WndProc(ref Message msg) public class LinkCollection : IList { - private LinkLabel owner; + private readonly LinkLabel owner; private bool linksAdded = false; //whether we should serialize the linkCollection /// A caching mechanism for key accessor @@ -2871,7 +2870,7 @@ public override int GetChildCount() internal class LinkAccessibleObject : AccessibleObject { - private Link link; + private readonly Link link; public LinkAccessibleObject(Link link) : base() { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs index b830d9fc682..a00a5d99f5d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs @@ -2639,7 +2639,7 @@ internal class ItemArray : IComparer private static int lastMask = 1; - private ListControl listControl; + private readonly ListControl listControl; private Entry[] entries; private int count; private int version; @@ -3041,11 +3041,11 @@ public Entry(object item) /// private class EntryEnumerator : IEnumerator { - private ItemArray items; - private bool anyBit; - private int state; + private readonly ItemArray items; + private readonly bool anyBit; + private readonly int state; private int current; - private int version; + private readonly int version; /// /// Creates a new enumerator that will enumerate over the given state. @@ -3138,7 +3138,7 @@ object IEnumerator.Current public class ObjectCollection : IList { - private ListBox owner; + private readonly ListBox owner; private ItemArray items; public ObjectCollection(ListBox owner) @@ -3612,7 +3612,7 @@ internal void SetItemInternal(int index, object value) // IntegerCollection public class IntegerCollection : IList { - private ListBox owner; + private readonly ListBox owner; private int[] innerArray; private int count = 0; @@ -3975,7 +3975,7 @@ IEnumerator IEnumerable.GetEnumerator() /// private class CustomTabOffsetsEnumerator : IEnumerator { - private IntegerCollection items; + private readonly IntegerCollection items; private int current; /// @@ -4036,7 +4036,7 @@ object IEnumerator.Current // SelectedIndices public class SelectedIndexCollection : IList { - private ListBox owner; + private readonly ListBox owner; /* C#r: protected */ public SelectedIndexCollection(ListBox owner) @@ -4255,7 +4255,7 @@ public IEnumerator GetEnumerator() /// private class SelectedIndexEnumerator : IEnumerator { - private SelectedIndexCollection items; + private readonly SelectedIndexCollection items; private int current; /// @@ -4318,7 +4318,7 @@ public class SelectedObjectCollection : IList // This is the bitmask used within ItemArray to identify selected objects. internal static int SelectedObjectMask = ItemArray.CreateMask(); - private ListBox owner; + private readonly ListBox owner; private bool stateDirty; private int lastVersion; private int count; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListManagerBindingsCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListManagerBindingsCollection.cs index 7d3401c189a..54edcf8adf4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListManagerBindingsCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListManagerBindingsCollection.cs @@ -14,7 +14,7 @@ namespace System.Windows.Forms [DefaultEvent(nameof(CollectionChanged))] internal class ListManagerBindingsCollection : BindingsCollection { - private BindingManagerBase _bindingManagerBase; + private readonly BindingManagerBase _bindingManagerBase; /// /// ColumnsCollection constructor. Used only by DataSource. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs index 2604085d1e6..1124d24a693 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs @@ -146,7 +146,7 @@ public class ListView : Control // listItemsArray is null if the handle is created; otherwise, it contains all Items. // We do not try to sort listItemsArray as items are added, but during a handle recreate // we will make sure we get the items in the same order the ListView displays them. - private Hashtable listItemsTable = new Hashtable(); // elements are ListViewItem's + private readonly Hashtable listItemsTable = new Hashtable(); // elements are ListViewItem's private ArrayList listItemsArray = new ArrayList(); // elements are ListViewItem's private Size tileSize = Size.Empty; @@ -161,8 +161,8 @@ public class ListView : Control private int updateCounter = 0; // the counter we use to track how many BeginUpdate/EndUpdate calls there have been. private ColumnHeader[] columnHeaders; - private ListViewItemCollection listItemCollection; - private ColumnHeaderCollection columnHeaderCollection; + private readonly ListViewItemCollection listItemCollection; + private readonly ColumnHeaderCollection columnHeaderCollection; private CheckedIndexCollection checkedIndexCollection; private CheckedListViewItemCollection checkedListViewItemCollection; private SelectedListViewItemCollection selectedListViewItemCollection; @@ -6999,7 +6999,7 @@ public int Compare(object obj1, object obj2) [ListBindable(false)] public class CheckedIndexCollection : IList { - private ListView owner; + private readonly ListView owner; /* C#r: protected */ public CheckedIndexCollection(ListView owner) @@ -7230,7 +7230,7 @@ public IEnumerator GetEnumerator() [ListBindable(false)] public class CheckedListViewItemCollection : IList { - private ListView owner; + private readonly ListView owner; /// A caching mechanism for key accessor /// We use an index here rather than control so that we don't have lifetime @@ -7568,7 +7568,7 @@ public IEnumerator GetEnumerator() [ListBindable(false)] public class SelectedIndexCollection : IList { - private ListView owner; + private readonly ListView owner; /* C#r: protected */ public SelectedIndexCollection(ListView owner) @@ -7887,7 +7887,7 @@ public void Remove(int itemIndex) [ListBindable(false)] public class SelectedListViewItemCollection : IList { - private ListView owner; + private readonly ListView owner; /// A caching mechanism for key accessor /// We use an index here rather than control so that we don't have lifetime @@ -8300,7 +8300,7 @@ public virtual int IndexOfKey(string key) [ListBindable(false)] public class ColumnHeaderCollection : IList { - private ListView owner; + private readonly ListView owner; public ColumnHeaderCollection(ListView owner) { @@ -8933,7 +8933,7 @@ internal interface IInnerList void RemoveAt(int index); } - private IInnerList innerList; + private readonly IInnerList innerList; public ListViewItemCollection(ListView owner) { @@ -9464,7 +9464,7 @@ void IList.Remove(object item) // internal class ListViewNativeItemCollection : ListViewItemCollection.IInnerList { - private ListView owner; + private readonly ListView owner; public ListViewNativeItemCollection(ListView owner) { @@ -9944,7 +9944,7 @@ protected override AccessibleObject CreateAccessibilityInstance() internal class ListViewAccessibleObject : ControlAccessibleObject { - private ListView owner; + private readonly ListView owner; internal ListViewAccessibleObject(ListView owner) : base(owner) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupCollection.cs index a6c6fdccf50..df565f440c2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupCollection.cs @@ -15,7 +15,7 @@ namespace System.Windows.Forms [ListBindable(false)] public class ListViewGroupCollection : IList { - private ListView _listView; + private readonly ListView _listView; private ArrayList _list; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewHitTestInfo.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewHitTestInfo.cs index 28cd9c9cb9c..73565fabfe2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewHitTestInfo.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewHitTestInfo.cs @@ -17,9 +17,9 @@ namespace System.Windows.Forms public class ListViewHitTestInfo { - private ListViewHitTestLocations loc; - private ListViewItem item; - private ListViewItem.ListViewSubItem subItem; + private readonly ListViewHitTestLocations loc; + private readonly ListViewItem item; + private readonly ListViewItem.ListViewSubItem subItem; /// /// Creates a ListViewHitTestInfo instance. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewInsertionMark.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewInsertionMark.cs index d84f3e34892..420571e9768 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewInsertionMark.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewInsertionMark.cs @@ -16,7 +16,7 @@ namespace System.Windows.Forms /// public sealed class ListViewInsertionMark { - private ListView listView; + private readonly ListView listView; private int index = 0; private Color color = Color.Empty; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItem.cs index c3476c977bf..1c8555145fa 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListViewItem.cs @@ -1557,7 +1557,7 @@ private class SubItemStyle public class ListViewSubItemCollection : IList { - private ListViewItem _owner; + private readonly ListViewItem _owner; // A caching mechanism for key accessor // We use an index here rather than control so that we don't have lifetime diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs index c47c3e6842f..a5b8f74d2a0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MDIClient.cs @@ -35,7 +35,7 @@ public sealed class MdiClient : Control // kept in add order, not ZOrder. Need to return the correct // array of items... // - private ArrayList children = new ArrayList(); + private readonly ArrayList children = new ArrayList(); /// @@ -427,7 +427,7 @@ private void OnIdle(object sender, EventArgs e) [ComVisible(false)] new public class ControlCollection : Control.ControlCollection { - private MdiClient owner; + private readonly MdiClient owner; /*C#r: protected*/ diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MDIControlStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MDIControlStrip.cs index d4b1c9bc5cf..75ccbda8f0e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MDIControlStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MDIControlStrip.cs @@ -18,10 +18,10 @@ namespace System.Windows.Forms internal class MdiControlStrip : MenuStrip { - private ToolStripMenuItem system; - private ToolStripMenuItem close; - private ToolStripMenuItem minimize; - private ToolStripMenuItem restore; + private readonly ToolStripMenuItem system; + private readonly ToolStripMenuItem close; + private readonly ToolStripMenuItem minimize; + private readonly ToolStripMenuItem restore; private MenuStrip mergedMenu; private IWin32Window target; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs index c28c38cb9c8..419c07593dd 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MaskedTextBox.cs @@ -69,38 +69,38 @@ public class MaskedTextBox : TextBoxBase private int caretTestPos; // Bit mask - Determines when the Korean IME composition string is completed so converted character can be processed. - private static int IME_ENDING_COMPOSITION = BitVector32.CreateMask(); + private static readonly int IME_ENDING_COMPOSITION = BitVector32.CreateMask(); // Bit mask - Determines when the Korean IME is completing a composition, used when forcing convertion. - private static int IME_COMPLETING = BitVector32.CreateMask(IME_ENDING_COMPOSITION); + private static readonly int IME_COMPLETING = BitVector32.CreateMask(IME_ENDING_COMPOSITION); // Used for handling characters that have a modifier (Ctrl-A, Shift-Del...). - private static int HANDLE_KEY_PRESS = BitVector32.CreateMask(IME_COMPLETING); + private static readonly int HANDLE_KEY_PRESS = BitVector32.CreateMask(IME_COMPLETING); // Bit mask - Used to simulate a null mask. Needed since a MaskedTextProvider object cannot be // initialized with a null mask but we need one even in this case as a backend for // default properties. This is to support creating a MaskedTextBox with the default // constructor, specially at design time. - private static int IS_NULL_MASK = BitVector32.CreateMask(HANDLE_KEY_PRESS); + private static readonly int IS_NULL_MASK = BitVector32.CreateMask(HANDLE_KEY_PRESS); // Bit mask - Used in conjuction with get_Text to return the text that is actually set in the native // control. This is required to be able to measure text correctly (GetPreferredSize) and // to compare against during set_Text (to bail if the same and not to raise TextChanged event). - private static int QUERY_BASE_TEXT = BitVector32.CreateMask(IS_NULL_MASK); + private static readonly int QUERY_BASE_TEXT = BitVector32.CreateMask(IS_NULL_MASK); // If true, the input text is rejected whenever a character does not comply with the mask; a MaskInputRejected // event is fired for the failing character. // If false, characters in the input string are processed one by one accepting the ones that comply // with the mask and raising the MaskInputRejected event for the rejected ones. - private static int REJECT_INPUT_ON_FIRST_FAILURE = BitVector32.CreateMask(QUERY_BASE_TEXT); + private static readonly int REJECT_INPUT_ON_FIRST_FAILURE = BitVector32.CreateMask(QUERY_BASE_TEXT); // Bit masks for boolean properties. - private static int HIDE_PROMPT_ON_LEAVE = BitVector32.CreateMask(REJECT_INPUT_ON_FIRST_FAILURE); - private static int BEEP_ON_ERROR = BitVector32.CreateMask(HIDE_PROMPT_ON_LEAVE); - private static int USE_SYSTEM_PASSWORD_CHAR = BitVector32.CreateMask(BEEP_ON_ERROR); - private static int INSERT_TOGGLED = BitVector32.CreateMask(USE_SYSTEM_PASSWORD_CHAR); - private static int CUTCOPYINCLUDEPROMPT = BitVector32.CreateMask(INSERT_TOGGLED); - private static int CUTCOPYINCLUDELITERALS = BitVector32.CreateMask(CUTCOPYINCLUDEPROMPT); + private static readonly int HIDE_PROMPT_ON_LEAVE = BitVector32.CreateMask(REJECT_INPUT_ON_FIRST_FAILURE); + private static readonly int BEEP_ON_ERROR = BitVector32.CreateMask(HIDE_PROMPT_ON_LEAVE); + private static readonly int USE_SYSTEM_PASSWORD_CHAR = BitVector32.CreateMask(BEEP_ON_ERROR); + private static readonly int INSERT_TOGGLED = BitVector32.CreateMask(USE_SYSTEM_PASSWORD_CHAR); + private static readonly int CUTCOPYINCLUDEPROMPT = BitVector32.CreateMask(INSERT_TOGGLED); + private static readonly int CUTCOPYINCLUDELITERALS = BitVector32.CreateMask(CUTCOPYINCLUDEPROMPT); ///////// Properties backend fields. See corresponding property comments for more info. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs index fdc75c8c7fb..3fc30a69c8b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Menu.cs @@ -742,7 +742,7 @@ private bool CheckOwnerDrawItemNoMnemonic(MenuItem mi, char key) [ListBindable(false)] public class MenuItemCollection : IList { - private Menu owner; + private readonly Menu owner; /// A caching mechanism for key accessor /// We use an index here rather than control so that we don't have lifetime diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MenuItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MenuItem.cs index 6b544ae37b2..62bbf8a9671 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MenuItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MenuItem.cs @@ -44,7 +44,7 @@ public class MenuItem : Menu // We need to store a table of all created menuitems, so that other objects // such as ContainerControl can get a reference to a particular menuitem, // given a unique ID. - private static Hashtable s_allCreatedMenuItems = new Hashtable(); + private static readonly Hashtable s_allCreatedMenuItems = new Hashtable(); private const uint FirstUniqueID = 0xC0000000; private static long s_nextUniqueID = FirstUniqueID; private uint _uniqueID = 0; @@ -53,7 +53,7 @@ public class MenuItem : Menu #if DEBUG private string _debugText; - private int _creationNumber; + private readonly int _creationNumber; private static int CreateCount; #endif @@ -1781,7 +1781,7 @@ public override void OnClick(EventArgs e) private class MdiListMoreWindowsData : MdiListUserData { - private MenuItem _parent; + private readonly MenuItem _parent; public MdiListMoreWindowsData(MenuItem parent) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Message.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Message.cs index 93c82049cfa..d84b408481d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Message.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Message.cs @@ -13,7 +13,7 @@ namespace System.Windows.Forms public struct Message { #if DEBUG - private static TraceSwitch s_allWinMessages = new TraceSwitch("AllWinMessages", "Output every received message"); + private static readonly TraceSwitch s_allWinMessages = new TraceSwitch("AllWinMessages", "Output every received message"); #endif public IntPtr HWnd { get; set; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs index dd27672ce35..9026f6ed978 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs @@ -134,7 +134,7 @@ public class MonthCalendar : Control /// /// Bitmask for the annually bolded dates. Months start on January. /// - private int[] monthsOfYear = new int[12]; + private readonly int[] monthsOfYear = new int[12]; /// /// Bitmask for the dates bolded monthly. /// @@ -143,9 +143,9 @@ public class MonthCalendar : Control /// Lists are slow, so this section can be optimized. /// Implementation is such that inserts are fast, removals are slow. /// - private ArrayList arrayOfDates = new ArrayList(); - private ArrayList annualArrayOfDates = new ArrayList(); // we have to maintain these lists too. - private ArrayList monthlyArrayOfDates = new ArrayList(); + private readonly ArrayList arrayOfDates = new ArrayList(); + private readonly ArrayList annualArrayOfDates = new ArrayList(); // we have to maintain these lists too. + private readonly ArrayList monthlyArrayOfDates = new ArrayList(); // notifications private DateRangeEventHandler onDateChanged; @@ -2686,7 +2686,7 @@ public enum HitArea internal class MonthCalendarAccessibleObject : ControlAccessibleObject { - private MonthCalendar calendar; + private readonly MonthCalendar calendar; public MonthCalendarAccessibleObject(Control owner) : base(owner) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs index 377fb7694a4..37824333222 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs @@ -77,10 +77,10 @@ public class NativeWindow : MarshalByRefObject, IWin32Window //nned to Store Table of Ids and Handles private static short globalID = 1; - private static Dictionary hashForIdHandle; - private static Dictionary hashForHandleId; - private static object internalSyncObject = new object(); - private static object createWindowSyncObject = new object(); + private static readonly Dictionary hashForIdHandle; + private static readonly Dictionary hashForHandleId; + private static readonly object internalSyncObject = new object(); + private static readonly object createWindowSyncObject = new object(); #if DEBUG AppDomain handleCreatedIn = null; @@ -94,8 +94,8 @@ public class NativeWindow : MarshalByRefObject, IWin32Window bool ownHandle; NativeWindow previousWindow; // doubly linked list of subclasses. NativeWindow nextWindow; - WeakReference weakThisPtr; - private DpiAwarenessContext windowDpiAwarenessContext = DpiHelper.IsScalingRequirementMet ? + readonly WeakReference weakThisPtr; + private readonly DpiAwarenessContext windowDpiAwarenessContext = DpiHelper.IsScalingRequirementMet ? CommonUnsafeNativeMethods.TryGetThreadDpiAwarenessContext() : DpiAwarenessContext.DPI_AWARENESS_CONTEXT_UNSPECIFIED; @@ -1583,7 +1583,7 @@ private class WindowClass internal bool registered; internal NativeWindow targetWindow; - private static object wcInternalSyncObject = new object(); + private static readonly object wcInternalSyncObject = new object(); private static int domainQualifier = 0; internal WindowClass(string className, int classStyle) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs index 3e913d6364d..8db7f7d007f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs @@ -42,13 +42,13 @@ public sealed class NotifyIcon : Component private static readonly object EVENT_BALLOONTIPCLOSED = new object(); private const int WM_TRAYMOUSEMESSAGE = Interop.WindowMessages.WM_USER + 1024; - private static int WM_TASKBARCREATED = SafeNativeMethods.RegisterWindowMessage("TaskbarCreated"); + private static readonly int WM_TASKBARCREATED = SafeNativeMethods.RegisterWindowMessage("TaskbarCreated"); - private object syncObj = new object(); + private readonly object syncObj = new object(); private Icon icon = null; private string text = string.Empty; - private int id = 0; + private readonly int id = 0; private bool added = false; private NotifyIconNativeWindow window = null; private ContextMenu contextMenu = null; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDownAccelerationCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDownAccelerationCollection.cs index e004e6a1be2..42e85977faa 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDownAccelerationCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDownAccelerationCollection.cs @@ -17,7 +17,7 @@ namespace System.Windows.Forms [ListBindable(false)] public class NumericUpDownAccelerationCollection : MarshalByRefObject, ICollection, IEnumerable { - List items; + readonly List items; /// ICollection implementation. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/OwnerDrawPropertyBag.cs b/src/System.Windows.Forms/src/System/Windows/Forms/OwnerDrawPropertyBag.cs index 0f4e2c52ba1..a31b37b761d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/OwnerDrawPropertyBag.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/OwnerDrawPropertyBag.cs @@ -17,7 +17,7 @@ namespace System.Windows.Forms public class OwnerDrawPropertyBag : MarshalByRefObject, ISerializable { private Control.FontHandleWrapper _fontWrapper = null; - private static object s_internalSyncObject = new object(); + private static readonly object s_internalSyncObject = new object(); protected OwnerDrawPropertyBag(SerializationInfo info, StreamingContext context) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PaintEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PaintEventArgs.cs index cb7563ac08e..2a79fd16247 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PaintEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PaintEventArgs.cs @@ -48,7 +48,7 @@ internal static string GetAllocationStack() return "Enabled 'PaintEventFinalization' trace switch to see stack of allocation"; } } - private string AllocationSite = PaintEventArgs.GetAllocationStack(); + private readonly string AllocationSite = PaintEventArgs.GetAllocationStack(); #endif /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs index a37d4ef5f43..e19ef833d52 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs @@ -70,7 +70,7 @@ public class PictureBox : Control, ISupportInitialize private SendOrPostCallback loadCompletedDelegate = null; private SendOrPostCallback loadProgressDelegate = null; private bool handleValid = false; - private object internalSyncObject = new object(); + private readonly object internalSyncObject = new object(); // These default images will be demand loaded. private Image defaultInitialImage = null; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintControllerWithStatusDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintControllerWithStatusDialog.cs index fca8caf5d7f..4c465a145c0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintControllerWithStatusDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintControllerWithStatusDialog.cs @@ -14,11 +14,11 @@ namespace System.Windows.Forms public class PrintControllerWithStatusDialog : PrintController { - private PrintController underlyingController; + private readonly PrintController underlyingController; private PrintDocument document; private BackgroundThread backgroundThread; private int pageNumber; - private string dialogTitle; + private readonly string dialogTitle; public PrintControllerWithStatusDialog(PrintController underlyingController) : this(underlyingController, string.Format(SR.PrintControllerWithStatusDialog_DialogTitlePrint)) @@ -151,9 +151,9 @@ public override void OnEndPrint(PrintDocument document, PrintEventArgs e) private class BackgroundThread { - private PrintControllerWithStatusDialog parent; + private readonly PrintControllerWithStatusDialog parent; private StatusDialog dialog; - private Thread thread; + private readonly Thread thread; internal bool canceled = false; private bool alreadyStopped = false; @@ -244,7 +244,7 @@ private class StatusDialog : Form internal Label label1; private Button button1; private TableLayoutPanel tableLayoutPanel1; - private BackgroundThread backgroundThread; + private readonly BackgroundThread backgroundThread; internal StatusDialog(BackgroundThread backgroundThread, string dialogTitle) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs index a975b05d7f0..2ec4bfde422 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintPreviewDialog.cs @@ -33,7 +33,7 @@ namespace System.Windows.Forms ] public class PrintPreviewDialog : Form { - PrintPreviewControl previewControl; + readonly PrintPreviewControl previewControl; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.NumericUpDown pageCounter; private System.Windows.Forms.ToolStripButton printToolStripButton; @@ -56,7 +56,7 @@ public class PrintPreviewDialog : Form private System.Windows.Forms.ToolStripSeparator separatorToolStripSeparator1; private System.Windows.Forms.ToolStripButton closeToolStripButton; private System.Windows.Forms.ToolStripLabel pageToolStripLabel; - ImageList imageList; + readonly ImageList imageList; /// /// Initializes a new instance of the class. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs index a80c11586f3..490ddf22902 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs @@ -50,7 +50,7 @@ public class ProgressBar : Control //this defines marquee animation speed private int marqueeSpeed = 100; - private Color defaultForeColor = SystemColors.Highlight; + private readonly Color defaultForeColor = SystemColors.Highlight; private ProgressBarStyle style = ProgressBarStyle.Blocks; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs index 340a01edb4c..dd318b9304a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs @@ -30,11 +30,11 @@ namespace System.Windows.Forms public class PropertyGrid : ContainerControl, IComPropertyBrowser, UnsafeNativeMethods.IPropertyNotifySink { - private DocComment doccomment; + private readonly DocComment doccomment; private int dcSizeRatio = -1; private int hcSizeRatio = -1; - private HotCommands hotcommands; - private ToolStrip toolStrip; + private readonly HotCommands hotcommands; + private readonly ToolStrip toolStrip; private bool helpVisible = true; private bool toolbarVisible = true; @@ -64,12 +64,12 @@ public class PropertyGrid : ContainerControl, IComPropertyBrowser, UnsafeNativeM // this guy's kind of an odd one...he gets special treatment private ToolStripButton btnViewPropertyPages; - private ToolStripSeparator separator1; - private ToolStripSeparator separator2; + private readonly ToolStripSeparator separator1; + private readonly ToolStripSeparator separator2; private int buttonType = NORMAL_BUTTONS; // our main baby - private PropertyGridView gridView; + private readonly PropertyGridView gridView; private IDesignerHost designerHost; @@ -160,12 +160,12 @@ private void SetFlag(ushort flag, bool value) // private AxHost.ConnectionPointCookie[] connectionPointCookies = null; - private static object EventPropertyValueChanged = new object(); - private static object EventComComponentNameChanged = new object(); - private static object EventPropertyTabChanged = new object(); - private static object EventSelectedGridItemChanged = new object(); - private static object EventPropertySortChanged = new object(); - private static object EventSelectedObjectsChanged = new object(); + private static readonly object EventPropertyValueChanged = new object(); + private static readonly object EventComComponentNameChanged = new object(); + private static readonly object EventPropertyTabChanged = new object(); + private static readonly object EventSelectedGridItemChanged = new object(); + private static readonly object EventPropertySortChanged = new object(); + private static readonly object EventSelectedObjectsChanged = new object(); [ SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // the "PropertyGridToolBar" caption is for testing. @@ -5574,7 +5574,7 @@ public class PropertyTabCollection : ICollection internal static PropertyTabCollection Empty = new PropertyTabCollection(null); - private PropertyGrid owner; + private readonly PropertyGrid owner; internal PropertyTabCollection(PropertyGrid owner) { @@ -5722,7 +5722,7 @@ public SelectedObjectConverter() : base(typeof(IComponent)) private class PropertyGridServiceProvider : IServiceProvider { - PropertyGrid owner; + readonly PropertyGrid owner; public PropertyGridServiceProvider(PropertyGrid owner) { @@ -5924,7 +5924,7 @@ private static string GenerateLogFileName(ref IntPtr fileId) internal class PropertyGridAccessibleObject : Control.ControlAccessibleObject { - private PropertyGrid _owningPropertyGrid; + private readonly PropertyGrid _owningPropertyGrid; /// /// Initializes new instance of PropertyGridAccessibleObject @@ -6153,7 +6153,7 @@ internal int GetChildFragmentIndex(AccessibleObject controlAccessibleObject) internal class PropertyGridToolStrip : ToolStrip { - private PropertyGrid _parentPropertyGrid; + private readonly PropertyGrid _parentPropertyGrid; /// /// Initializes new instance of PropertyGridToolStrip control. @@ -6187,7 +6187,7 @@ protected override AccessibleObject CreateAccessibilityInstance() internal class PropertyGridToolStripAccessibleObject : ToolStrip.ToolStripAccessibleObject { - private PropertyGrid _parentPropertyGrid; + private readonly PropertyGrid _parentPropertyGrid; /// /// Constructs new instance of PropertyGridToolStripAccessibleObject diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/CategoryGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/CategoryGridEntry.cs index 639f25784dc..1906a017bfb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/CategoryGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/CategoryGridEntry.cs @@ -294,7 +294,7 @@ internal override bool NotifyChildValue(GridEntry pe, int type) internal class CategoryGridEntryAccessibleObject : GridEntryAccessibleObject { - private CategoryGridEntry _owningCategoryGridEntry; + private readonly CategoryGridEntry _owningCategoryGridEntry; /// /// Initializes new instance of CategoryGridEntryAccessibleObject. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs index d6686ea1c53..9d289a50f09 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DocComment.cs @@ -21,8 +21,8 @@ namespace System.Windows.Forms.PropertyGridInternal internal class DocComment : PropertyGrid.SnappableControl { - private Label m_labelTitle; - private Label m_labelDesc; + private readonly Label m_labelTitle; + private readonly Label m_labelDesc; private string fullDesc; protected int lineHeight; @@ -273,7 +273,7 @@ private void UpdateUIWithFont() internal class DocCommentAccessibleObject : Control.ControlAccessibleObject { - private PropertyGrid _parentPropertyGrid; + private readonly PropertyGrid _parentPropertyGrid; /// /// Initializes new instance of DocCommentAccessibleObject. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DropDownButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DropDownButton.cs index 5596864b9f2..7734359a87a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DropDownButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/DropDownButton.cs @@ -252,8 +252,8 @@ internal override void DrawImageCore(Graphics graphics, Image image, Rectangle i internal class DropDownButtonAccessibleObject : Control.ControlAccessibleObject { - private DropDownButton _owningDropDownButton; - private PropertyGridView _owningPropertyGrid; + private readonly DropDownButton _owningDropDownButton; + private readonly PropertyGridView _owningPropertyGrid; /// /// Constructs the new instance of DropDownButtonAccessibleObject. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs index 5b1580dfec3..bb56f80eada 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntry.cs @@ -32,7 +32,7 @@ internal abstract class GridEntry : GridItem, ITypeDescriptorContext { protected static readonly Point InvalidPoint = new Point(int.MinValue, int.MinValue); - private static BooleanSwitch PbrsAssertPropsSwitch = new BooleanSwitch("PbrsAssertProps", "PropertyBrowser : Assert on broken properties"); + private static readonly BooleanSwitch PbrsAssertPropsSwitch = new BooleanSwitch("PbrsAssertProps", "PropertyBrowser : Assert on broken properties"); internal static AttributeTypeSorter AttributeTypeSorter = new AttributeTypeSorter(); @@ -121,13 +121,13 @@ private class CacheItems protected PropertyGrid ownerGrid; - private static object EVENT_VALUE_CLICK = new object(); - private static object EVENT_LABEL_CLICK = new object(); - private static object EVENT_OUTLINE_CLICK = new object(); - private static object EVENT_VALUE_DBLCLICK = new object(); - private static object EVENT_LABEL_DBLCLICK = new object(); - private static object EVENT_OUTLINE_DBLCLICK = new object(); - private static object EVENT_RECREATE_CHILDREN = new object(); + private static readonly object EVENT_VALUE_CLICK = new object(); + private static readonly object EVENT_LABEL_CLICK = new object(); + private static readonly object EVENT_OUTLINE_CLICK = new object(); + private static readonly object EVENT_VALUE_DBLCLICK = new object(); + private static readonly object EVENT_LABEL_DBLCLICK = new object(); + private static readonly object EVENT_OUTLINE_DBLCLICK = new object(); + private static readonly object EVENT_RECREATE_CHILDREN = new object(); private GridEntryAccessibleObject accessibleObject = null; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntryCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntryCollection.cs index a2e9e63a83f..c16c36e036d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntryCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridEntryCollection.cs @@ -8,7 +8,7 @@ namespace System.Windows.Forms.PropertyGridInternal { internal sealed class GridEntryCollection : GridItemCollection { - private GridEntry _owner; + private readonly GridEntry _owner; public GridEntryCollection(GridEntry owner, GridEntry[] entries) : base(entries) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridErrorDlg.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridErrorDlg.cs index 42f74714aaa..662e911678e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridErrorDlg.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridErrorDlg.cs @@ -42,9 +42,9 @@ internal class GridErrorDlg : Form private TableLayoutPanel pictureLabelTableLayoutPanel; private TextBox details; - private Bitmap expandImage = null; - private Bitmap collapseImage = null; - private PropertyGrid ownerGrid; + private readonly Bitmap expandImage = null; + private readonly Bitmap collapseImage = null; + private readonly PropertyGrid ownerGrid; private bool detailsButtonExpanded = false; @@ -368,7 +368,7 @@ protected override void OnVisibleChanged(EventArgs e) internal class DetailsButton : Button { - private GridErrorDlg parent; + private readonly GridErrorDlg parent; public DetailsButton(GridErrorDlg form) { parent = form; @@ -390,7 +390,7 @@ protected override AccessibleObject CreateAccessibilityInstance() internal class DetailsButtonAccessibleObject : Control.ControlAccessibleObject { - private DetailsButton ownerItem = null; + private readonly DetailsButton ownerItem = null; public DetailsButtonAccessibleObject(DetailsButton owner) : base(owner) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridToolTip.cs index 223f9d02ef7..447083b7224 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridToolTip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/GridToolTip.cs @@ -14,13 +14,12 @@ namespace System.Windows.Forms.PropertyGridInternal internal class GridToolTip : Control { - - Control[] controls; + readonly Control[] controls; string toolTipText; - NativeMethods.TOOLINFO_T[] toolInfos; + readonly NativeMethods.TOOLINFO_T[] toolInfos; bool dontShow; Point lastMouseMove = Point.Empty; - private int maximumToolTipLength = 1000; + private readonly int maximumToolTipLength = 1000; internal GridToolTip(Control[] controls) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs index 14c46ee62a6..b5002c83b85 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/HotCommands.cs @@ -270,7 +270,7 @@ private void SetupLabel() internal class HotCommandsAccessibleObject : Control.ControlAccessibleObject { - private PropertyGrid _parentPropertyGrid; + private readonly PropertyGrid _parentPropertyGrid; /// /// Initializes new instance of DocCommentAccessibleObject. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs index b623ee8bc2f..5609fdbddc4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MergePropertyDescriptor.cs @@ -23,7 +23,7 @@ namespace System.Windows.Forms.PropertyGridInternal internal class MergePropertyDescriptor : PropertyDescriptor { - private PropertyDescriptor[] descriptors; + private readonly PropertyDescriptor[] descriptors; private enum TriState { @@ -604,7 +604,7 @@ public void SetItems(ICollection collection) private class MergedAttributeCollection : AttributeCollection { - private MergePropertyDescriptor owner; + private readonly MergePropertyDescriptor owner; private AttributeCollection[] attributeCollections = null; private IDictionary foundAttributes = null; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiPropertyDescriptorGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiPropertyDescriptorGridEntry.cs index c30218fff28..14171bec73e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiPropertyDescriptorGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiPropertyDescriptorGridEntry.cs @@ -21,8 +21,8 @@ internal class MultiPropertyDescriptorGridEntry : PropertyDescriptorGridEntry { - private MergePropertyDescriptor mergedPd; - private object[] objs; + private readonly MergePropertyDescriptor mergedPd; + private readonly object[] objs; [ SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // GridEntry classes are internal so we have complete diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiSelectRootGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiSelectRootGridEntry.cs index 78c1fc25454..019b90dba63 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiSelectRootGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/MultiSelectRootGridEntry.cs @@ -23,7 +23,7 @@ namespace System.Windows.Forms.PropertyGridInternal internal class MultiSelectRootGridEntry : SingleSelectRootGridEntry { - private static PDComparer PropertyComparer = new PDComparer(); + private static readonly PDComparer PropertyComparer = new PDComparer(); internal MultiSelectRootGridEntry(PropertyGridView view, object obj, IServiceProvider baseProvider, IDesignerHost host, PropertyTab tab, PropertySort sortType) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs index 0f2b72c6ffc..9ba7ab839db 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyDescriptorGridEntry.cs @@ -39,7 +39,7 @@ internal class PropertyDescriptorGridEntry : GridEntry private bool forceRenderReadOnly = false; private string helpKeyword; private string toolTipText = null; - private bool activeXHide = false; + private readonly bool activeXHide = false; private static int scaledImageSizeX = IMAGE_SIZE; private static int scaledImageSizeY = IMAGE_SIZE; private static bool isScalingInitialized = false; @@ -1185,7 +1185,7 @@ protected override GridEntryAccessibleObject GetAccessibilityObject() protected class PropertyDescriptorGridEntryAccessibleObject : GridEntryAccessibleObject { - private PropertyDescriptorGridEntry _owningPropertyDescriptorGridEntry; + private readonly PropertyDescriptorGridEntry _owningPropertyDescriptorGridEntry; public PropertyDescriptorGridEntryAccessibleObject(PropertyDescriptorGridEntry owner) : base(owner) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs index fa08d2e5886..5a760c7bf39 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.cs @@ -82,7 +82,7 @@ internal class PropertyGridView : private const int DOWNARROW_ICONWIDTH = 16; private const int DOWNARROW_ICONHEIGHT = 16; - private static int OFFSET_2PIXELS = 2; + private static readonly int OFFSET_2PIXELS = 2; private int offset_2Units = OFFSET_2PIXELS; protected static readonly Point InvalidPosition = new Point(int.MinValue, int.MinValue); @@ -157,12 +157,12 @@ internal class PropertyGridView : private IHelpService topHelpService; private IHelpService helpService; - private EventHandler ehValueClick; - private EventHandler ehLabelClick; - private EventHandler ehOutlineClick; - private EventHandler ehValueDblClick; - private EventHandler ehLabelDblClick; - private GridEntryRecreateChildrenEventHandler ehRecreateChildren; + private readonly EventHandler ehValueClick; + private readonly EventHandler ehLabelClick; + private readonly EventHandler ehOutlineClick; + private readonly EventHandler ehValueDblClick; + private readonly EventHandler ehLabelDblClick; + private readonly GridEntryRecreateChildrenEventHandler ehRecreateChildren; private int cachedRowHeight = -1; IntPtr baseHfont; @@ -6376,8 +6376,8 @@ private class DropDownHolder : Form, IMouseHookClient { private Control currentControl = null; // the control that is hosted in the holder - private PropertyGridView gridView; // the owner gridview - private MouseHook mouseHook; // we use this to hook mouse downs, etc. to know when to close the dropdown. + private readonly PropertyGridView gridView; // the owner gridview + private readonly MouseHook mouseHook; // we use this to hook mouse downs, etc. to know when to close the dropdown. private LinkLabel createNewLink = null; @@ -7121,7 +7121,7 @@ private class GridViewListBox : ListBox { internal bool fInSetSelectedIndex = false; - private PropertyGridView _owningPropertyGridView; + private readonly PropertyGridView _owningPropertyGridView; public GridViewListBox(PropertyGridView gridView) { @@ -7190,8 +7190,8 @@ protected override void OnSelectedIndexChanged(EventArgs e) private class GridViewListBoxItemAccessibleObject : AccessibleObject { - private GridViewListBox _owningGridViewListBox; - private object _owningItem; + private readonly GridViewListBox _owningGridViewListBox; + private readonly object _owningItem; public GridViewListBoxItemAccessibleObject(GridViewListBox owningGridViewListBox, object owningItem) { @@ -7424,7 +7424,7 @@ internal override void SetFocus() private class GridViewListBoxItemAccessibleObjectCollection : Hashtable { - private GridViewListBox _owningGridViewListBox; + private readonly GridViewListBox _owningGridViewListBox; public GridViewListBoxItemAccessibleObjectCollection(GridViewListBox owningGridViewListBox) { @@ -7458,9 +7458,9 @@ public override object this[object key] private class GridViewListBoxAccessibleObject : ControlAccessibleObject { - private GridViewListBox _owningGridViewListBox; - private PropertyGridView _owningPropertyGridView; - private GridViewListBoxItemAccessibleObjectCollection _itemAccessibleObjects; + private readonly GridViewListBox _owningGridViewListBox; + private readonly PropertyGridView _owningPropertyGridView; + private readonly GridViewListBoxItemAccessibleObjectCollection _itemAccessibleObjects; /// /// Constructs the new instance of GridViewListBoxAccessibleObject. @@ -7577,7 +7577,7 @@ private class GridViewEdit : TextBox, IMouseHookClient private bool dontFocusMe = false; private int lastMove; - private MouseHook mouseHook; + private readonly MouseHook mouseHook; // We do this becuase the Focus call above doesn't always stick, so // we make the Edit think that it doesn't have focus. this prevents @@ -8031,7 +8031,7 @@ public virtual bool InSetText() protected class GridViewEditAccessibleObject : ControlAccessibleObject { - private PropertyGridView propertyGridView; + private readonly PropertyGridView propertyGridView; public GridViewEditAccessibleObject(GridViewEdit owner) : base(owner) { @@ -8183,9 +8183,9 @@ internal interface IMouseHookClient internal class MouseHook { - private PropertyGridView gridView; - private Control control; - private IMouseHookClient client; + private readonly PropertyGridView gridView; + private readonly Control control; + private readonly IMouseHookClient client; internal int thisProcessID = 0; private GCHandle mouseHookRoot; @@ -8205,7 +8205,7 @@ public MouseHook(Control control, IMouseHookClient client, PropertyGridView grid } #if DEBUG - string callingStack; + readonly string callingStack; ~MouseHook() { Debug.Assert(mouseHookHandle == IntPtr.Zero, "Finalizing an active mouse hook. This will crash the process. Calling stack: " + callingStack); @@ -8456,8 +8456,8 @@ public virtual IntPtr Callback(int nCode, IntPtr wparam, IntPtr lparam) internal class PropertyGridViewAccessibleObject : ControlAccessibleObject { - private PropertyGridView _owningPropertyGridView; - private PropertyGrid _parentPropertyGrid; + private readonly PropertyGridView _owningPropertyGridView; + private readonly PropertyGrid _parentPropertyGrid; /// /// Construct a PropertyGridViewAccessibleObject @@ -8975,11 +8975,10 @@ public override AccessibleObject Navigate(AccessibleNavigation navdir) internal class GridPositionData { - - ArrayList expandedState; - GridEntryCollection selectedItemTree; - int itemRow; - int itemCount; + readonly ArrayList expandedState; + readonly GridEntryCollection selectedItemTree; + readonly int itemRow; + readonly int itemCount; public GridPositionData(PropertyGridView gridView) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyManager.cs index 6cc699e5332..034066e45a2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyManager.cs @@ -11,7 +11,7 @@ namespace System.Windows.Forms public class PropertyManager : BindingManagerBase { private object _dataSource; - private string _propName; + private readonly string _propName; private PropertyDescriptor _propInfo; private bool _bound; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RelatedCurrencyManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RelatedCurrencyManager.cs index d961351185a..d91e49d3f56 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RelatedCurrencyManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RelatedCurrencyManager.cs @@ -23,7 +23,7 @@ internal class RelatedCurrencyManager : CurrencyManager BindingManagerBase parentManager; string dataField; PropertyDescriptor fieldInfo; - static List IgnoreItemChangedTable = new List(); + static readonly List IgnoreItemChangedTable = new List(); [ SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // If the constructor does not set the dataSource diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RelatedImageListAttribute.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RelatedImageListAttribute.cs index 8d0bf74a596..bc2b05417ca 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RelatedImageListAttribute.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RelatedImageListAttribute.cs @@ -14,7 +14,7 @@ namespace System.Windows.Forms [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class RelatedImageListAttribute : Attribute { - private string relatedImageList = null; + private readonly string relatedImageList = null; public RelatedImageListAttribute(string relatedImageList) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs index 7c93aca16db..ed82019572a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs @@ -4033,7 +4033,7 @@ protected override void WndProc(ref Message m) private class OleCallback : UnsafeNativeMethods.IRichEditOleCallback { - private RichTextBox owner; + private readonly RichTextBox owner; IDataObject lastDataObject; DragDropEffects lastEffect; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Screen.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Screen.cs index 5e7fc34ba87..32b339ce15e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Screen.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Screen.cs @@ -46,7 +46,7 @@ public class Screen readonly int bitDepth; - private static object syncLock = new object();//used to lock this class before sync'ing to SystemEvents + private static readonly object syncLock = new object();//used to lock this class before sync'ing to SystemEvents private static int desktopChangedCount = -1;//static counter of desktop size changes @@ -63,7 +63,7 @@ public class Screen private const int MONITOR_DEFAULTTONEAREST = 0x00000002; private const int MONITORINFOF_PRIMARY = 0x00000001; - private static bool multiMonitorSupport = (UnsafeNativeMethods.GetSystemMetrics(NativeMethods.SM_CMONITORS) != 0); + private static readonly bool multiMonitorSupport = (UnsafeNativeMethods.GetSystemMetrics(NativeMethods.SM_CMONITORS) != 0); private static Screen[] screens; internal Screen(IntPtr monitor) : this(monitor, IntPtr.Zero) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollBar.cs index 8b8002e0419..beee59903c2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollBar.cs @@ -27,7 +27,7 @@ public abstract class ScrollBar : Control private int _smallChange = 1; private int _largeChange = 10; private int _value = 0; - private ScrollOrientation _scrollOrientation; + private readonly ScrollOrientation _scrollOrientation; private int _wheelDelta = 0; private bool _scaleScrollBarForDpiChange = true; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollProperties.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollProperties.cs index 9a99a7cd891..78843b35176 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollProperties.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollProperties.cs @@ -22,7 +22,7 @@ public abstract class ScrollProperties internal bool _smallChangeSetExternally; internal bool _largeChangeSetExternally; - private ScrollableControl _parent; + private readonly ScrollableControl _parent; protected ScrollableControl ParentControl => _parent; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs index fea147091eb..8ecac6c1599 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs @@ -1657,7 +1657,7 @@ protected override void WndProc(ref Message m) [TypeConverterAttribute(typeof(DockPaddingEdgesConverter))] public class DockPaddingEdges : ICloneable { - private ScrollableControl _owner; + private readonly ScrollableControl _owner; private int _left; private int _right; private int _top; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SendKeys.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SendKeys.cs index ae638bc3326..31a609c1291 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SendKeys.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SendKeys.cs @@ -32,7 +32,7 @@ public class SendKeys // private const int UNKNOWN_GROUPING = 10; - private static KeywordVk[] keywords = new KeywordVk[] { + private static readonly KeywordVk[] keywords = new KeywordVk[] { new KeywordVk("ENTER", (int)Keys.Return), new KeywordVk("TAB", (int)Keys.Tab), new KeywordVk("ESC", (int)Keys.Escape), @@ -107,7 +107,7 @@ public class SendKeys private static bool fStartNewChar; - private static SKWindow messageWindow; + private static readonly SKWindow messageWindow; private enum SendMethodTypes { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs index 95a154d6f72..0f7296d4878 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs @@ -53,8 +53,8 @@ public class SplitContainer : ContainerControl, ISupportInitialize // SplitContainer private Cached copies of public properties... // private Orientation orientation = Orientation.Vertical; - private SplitterPanel panel1 = null; - private SplitterPanel panel2 = null; + private readonly SplitterPanel panel1 = null; + private readonly SplitterPanel panel2 = null; private BorderStyle borderStyle = System.Windows.Forms.BorderStyle.None; private FixedPanel fixedPanel = FixedPanel.None; @@ -2734,7 +2734,7 @@ protected override Control.ControlCollection CreateControlsInstance() private class SplitContainerMessageFilter : IMessageFilter { - private SplitContainer owner = null; + private readonly SplitContainer owner = null; public SplitContainerMessageFilter(SplitContainer splitContainer) { @@ -2769,7 +2769,7 @@ bool IMessageFilter.PreFilterMessage(ref Message m) /// internal class SplitContainerTypedControlCollection : WindowsFormsUtils.TypedControlCollection { - SplitContainer owner; + readonly SplitContainer owner; public SplitContainerTypedControlCollection(Control c, Type type, bool isReadOnly) : base(c, type, isReadOnly) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Splitter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Splitter.cs index ae325edd06c..cc24cd05270 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Splitter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Splitter.cs @@ -1070,7 +1070,7 @@ private class SplitData private class SplitterMessageFilter : IMessageFilter { - private Splitter owner = null; + private readonly Splitter owner = null; public SplitterMessageFilter(Splitter splitter) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SplitterPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SplitterPanel.cs index 89cbc42ee6e..fdd02d7df95 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SplitterPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SplitterPanel.cs @@ -15,7 +15,7 @@ namespace System.Windows.Forms [ToolboxItem(false)] public sealed class SplitterPanel : Panel { - SplitContainer owner = null; + readonly SplitContainer owner = null; private bool collapsed = false; public SplitterPanel(SplitContainer owner) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs index eef8182da2d..6c418d5874a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs @@ -44,7 +44,7 @@ public class StatusBar : Control private bool sizeGrip = true; private string simpleText; private Point lastClick = new Point(0, 0); - private IList panels = new ArrayList(); + private readonly IList panels = new ArrayList(); private StatusBarPanelCollection panelsCollection; private ControlToolTip tooltips; @@ -1288,7 +1288,7 @@ protected override void WndProc(ref Message m) ] public class StatusBarPanelCollection : IList { - private StatusBar owner; + private readonly StatusBar owner; /// A caching mechanism for key accessor /// We use an index here rather than control so that we don't have lifetime /// issues by holding on to extra references. @@ -1775,9 +1775,9 @@ public class Tool internal IntPtr id = new IntPtr(-1); } - private Hashtable tools = new Hashtable(); - private ToolTipNativeWindow window = null; - private Control parent = null; + private readonly Hashtable tools = new Hashtable(); + private readonly ToolTipNativeWindow window = null; + private readonly Control parent = null; private int nextId = 0; /// @@ -2076,7 +2076,7 @@ protected void WndProc(ref Message msg) /// private class ToolTipNativeWindow : NativeWindow { - ControlToolTip control; + readonly ControlToolTip control; internal ToolTipNativeWindow(ControlToolTip control) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/StringSorter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/StringSorter.cs index 1012a15baed..2631c997e08 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/StringSorter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/StringSorter.cs @@ -79,11 +79,11 @@ internal sealed class StringSorter private const int CompareOptions = IgnoreCase | IgnoreKanaType | IgnoreNonSpace | IgnoreSymbols | IgnoreWidth | StringSort; - private string[] keys; - private object[] items; - private int lcid; - private int options; - private bool descending; + private readonly string[] keys; + private readonly object[] items; + private readonly int lcid; + private readonly int options; + private readonly bool descending; /// /// Constructs a StringSorter. Instances are created by the sort() routines, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs index 3437bfba71f..abd31e5e54a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs @@ -42,7 +42,7 @@ public class TabControl : Control private static readonly Point DEFAULT_PADDING = new Point(6, 3); //properties - private TabPageCollection tabCollection; + private readonly TabPageCollection tabCollection; private TabAlignment alignment = TabAlignment.Top; private TabDrawMode drawMode = TabDrawMode.Normal; private ImageList imageList = null; @@ -2345,7 +2345,7 @@ protected override void WndProc(ref Message m) public class TabPageCollection : IList { - private TabControl owner; + private readonly TabControl owner; /// A caching mechanism for key accessor /// We use an index here rather than control so that we don't have lifetime /// issues by holding on to extra references. @@ -2822,7 +2822,7 @@ public virtual void RemoveByKey(string key) public new class ControlCollection : Control.ControlCollection { - private TabControl owner; + private readonly TabControl owner; /*C#r: protected*/ diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanel.cs index 4d254aaacb9..af7b02be84b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanel.cs @@ -30,7 +30,7 @@ namespace System.Windows.Forms [SRDescription(nameof(SR.DescriptionTableLayoutPanel))] public class TableLayoutPanel : Panel, IExtenderProvider { - private TableLayoutSettings _tableLayoutSettings; + private readonly TableLayoutSettings _tableLayoutSettings; private static readonly object EventCellPaint = new object(); public TableLayoutPanel() diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettings.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettings.cs index e78e3fd2517..1227b0db5f4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettings.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutSettings.cs @@ -27,7 +27,7 @@ public sealed class TableLayoutSettings : LayoutSettings, ISerializable { - static private int[] borderStyleToOffset = { + private static readonly int[] borderStyleToOffset = { /*None = */ 0, /*Single = */ 1, /*Inset = */ 2, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ThreadExceptionDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ThreadExceptionDialog.cs index 8920ada94ff..9fb30f79d17 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ThreadExceptionDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ThreadExceptionDialog.cs @@ -48,33 +48,33 @@ public class ThreadExceptionDialog : Form private const int PICTUREHEIGHT = 64; private const int EXCEPTIONMESSAGEVERTICALPADDING = 4; - private int scaledMaxWidth = MAXWIDTH; - private int scaledMaxHeight = MAXHEIGHT; - private int scaledPaddingWidth = PADDINGWIDTH; - private int scaledPaddingHeight = PADDINGHEIGHT; - private int scaledMaxTextWidth = MAXTEXTWIDTH; - private int scaledMaxTextHeight = MAXTEXTHEIGHT; - private int scaledButtonTopPadding = BUTTONTOPPADDING; - private int scaledButtonDetailsLeftPadding = BUTTONDETAILS_LEFTPADDING; - private int scaledMessageTopPadding = MESSAGE_TOPPADDING; - private int scaledHeightPadding = HEIGHTPADDING; - private int scaledButtonWidth = BUTTONWIDTH; - private int scaledButtonHeight = BUTTONHEIGHT; - private int scaledButtonAlignmentWidth = BUTTONALIGNMENTWIDTH; - private int scaledButtonAlignmentPadding = BUTTONALIGNMENTPADDING; - private int scaledDetailsWidthPadding = DETAILSWIDTHPADDING; - private int scaledDetailsHeight = DETAILSHEIGHT; - private int scaledPictureWidth = PICTUREWIDTH; - private int scaledPictureHeight = PICTUREHEIGHT; - private int scaledExceptionMessageVerticalPadding = EXCEPTIONMESSAGEVERTICALPADDING; - - private PictureBox pictureBox = new PictureBox(); - private Label message = new Label(); - private Button continueButton = new Button(); - private Button quitButton = new Button(); - private Button detailsButton = new Button(); - private Button helpButton = new Button(); - private TextBox details = new TextBox(); + private readonly int scaledMaxWidth = MAXWIDTH; + private readonly int scaledMaxHeight = MAXHEIGHT; + private readonly int scaledPaddingWidth = PADDINGWIDTH; + private readonly int scaledPaddingHeight = PADDINGHEIGHT; + private readonly int scaledMaxTextWidth = MAXTEXTWIDTH; + private readonly int scaledMaxTextHeight = MAXTEXTHEIGHT; + private readonly int scaledButtonTopPadding = BUTTONTOPPADDING; + private readonly int scaledButtonDetailsLeftPadding = BUTTONDETAILS_LEFTPADDING; + private readonly int scaledMessageTopPadding = MESSAGE_TOPPADDING; + private readonly int scaledHeightPadding = HEIGHTPADDING; + private readonly int scaledButtonWidth = BUTTONWIDTH; + private readonly int scaledButtonHeight = BUTTONHEIGHT; + private readonly int scaledButtonAlignmentWidth = BUTTONALIGNMENTWIDTH; + private readonly int scaledButtonAlignmentPadding = BUTTONALIGNMENTPADDING; + private readonly int scaledDetailsWidthPadding = DETAILSWIDTHPADDING; + private readonly int scaledDetailsHeight = DETAILSHEIGHT; + private readonly int scaledPictureWidth = PICTUREWIDTH; + private readonly int scaledPictureHeight = PICTUREHEIGHT; + private readonly int scaledExceptionMessageVerticalPadding = EXCEPTIONMESSAGEVERTICALPADDING; + + private readonly PictureBox pictureBox = new PictureBox(); + private readonly Label message = new Label(); + private readonly Button continueButton = new Button(); + private readonly Button quitButton = new Button(); + private readonly Button detailsButton = new Button(); + private readonly Button helpButton = new Button(); + private readonly TextBox details = new TextBox(); private Bitmap expandImage = null; private Bitmap collapseImage = null; private bool detailsVisible = false; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs index 5b0a84415fb..e4f83c60036 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs @@ -29,7 +29,7 @@ namespace System.Windows.Forms public class ToolBar : Control { - private ToolBarButtonCollection buttonsCollection; + private readonly ToolBarButtonCollection buttonsCollection; /// /// The size of a button in the ToolBar @@ -1882,7 +1882,7 @@ protected override void WndProc(ref Message m) public class ToolBarButtonCollection : IList { - private ToolBar owner; + private readonly ToolBar owner; private bool suspendUpdate; /// A caching mechanism for key accessor /// We use an index here rather than control so that we don't have lifetime diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs index 2a87ff5a9d3..906bbcd6e8c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBarButton.cs @@ -85,7 +85,7 @@ public ToolBarButton(string text) : base() // list for indexing purposes. internal class ToolBarButtonImageIndexer : ImageList.Indexer { - private ToolBarButton owner; + private readonly ToolBarButton owner; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs index 9281421caf9..506d218f6e0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs @@ -73,7 +73,7 @@ public class ToolStrip : System.Windows.Forms.ScrollableControl, private Orientation orientation = Orientation.Horizontal; - private ArrayList activeDropDowns = new ArrayList(1); + private readonly ArrayList activeDropDowns = new ArrayList(1); private ToolStripRenderer renderer = null; private Type currentRendererType = typeof(System.Type); private Hashtable shortcuts = null; @@ -5318,7 +5318,7 @@ internal override bool AllowsChildrenToShowToolTips() public class ToolStripAccessibleObject : ControlAccessibleObject { - private ToolStrip owner; + private readonly ToolStrip owner; public ToolStripAccessibleObject(ToolStrip owner) : base(owner) { @@ -5691,7 +5691,7 @@ public override AccessibleStates State internal class RestoreFocusMessageFilter : IMessageFilter { - private ToolStrip ownerToolStrip; + private readonly ToolStrip ownerToolStrip; public RestoreFocusMessageFilter(ToolStrip ownerToolStrip) { @@ -5927,7 +5927,7 @@ private void OnTick(object sender, EventArgs e) internal sealed class ToolStripSplitStackDragDropHandler : IDropTarget, ISupportOleDropSource { - private ToolStrip owner; + private readonly ToolStrip owner; public ToolStripSplitStackDragDropHandler(ToolStrip owner) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs index cd59d893177..4d2a9fb5a94 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs @@ -287,7 +287,7 @@ protected override void OnClick(EventArgs e) [System.Runtime.InteropServices.ComVisible(true)] internal class ToolStripButtonAccessibleObject : ToolStripItemAccessibleObject { - private ToolStripButton ownerItem = null; + private readonly ToolStripButton ownerItem = null; public ToolStripButtonAccessibleObject(ToolStripButton ownerItem) : base(ownerItem) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripComboBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripComboBox.cs index 42b27b70f4e..225f042da51 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripComboBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripComboBox.cs @@ -64,7 +64,7 @@ protected override AccessibleObject CreateAccessibilityInstance() [System.Runtime.InteropServices.ComVisible(true)] internal class ToolStripComboBoxAccessibleObject : ToolStripItemAccessibleObject { - private ToolStripComboBox ownerItem = null; + private readonly ToolStripComboBox ownerItem = null; /// /// Initializes the new instance of ToolStripComboBoxAccessibleObject. @@ -816,7 +816,7 @@ protected override void OnDropDownClosed(EventArgs e) internal class ToolStripComboBoxControlAccessibleObject : ComboBox.ComboBoxAccessibleObject { - private ComboBox.ChildAccessibleObject childAccessibleObject; + private readonly ComboBox.ChildAccessibleObject childAccessibleObject; public ToolStripComboBoxControlAccessibleObject(ToolStripComboBoxControl toolStripComboBoxControl) : base(toolStripComboBoxControl) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs index 0ba9ea2efe3..d49819ae09f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContainer.cs @@ -24,11 +24,11 @@ namespace System.Windows.Forms public class ToolStripContainer : ContainerControl { - private ToolStripPanel topPanel; - private ToolStripPanel bottomPanel; - private ToolStripPanel leftPanel; - private ToolStripPanel rightPanel; - private ToolStripContentPanel contentPanel; + private readonly ToolStripPanel topPanel; + private readonly ToolStripPanel bottomPanel; + private readonly ToolStripPanel leftPanel; + private readonly ToolStripPanel rightPanel; + private readonly ToolStripContentPanel contentPanel; public ToolStripContainer() @@ -473,9 +473,9 @@ internal override bool AllowsKeyboardToolTip() internal class ToolStripContainerTypedControlCollection : WindowsFormsUtils.ReadOnlyControlCollection { - ToolStripContainer owner; - Type contentPanelType = typeof(ToolStripContentPanel); - Type panelType = typeof(ToolStripPanel); + readonly ToolStripContainer owner; + readonly Type contentPanelType = typeof(ToolStripContentPanel); + readonly Type panelType = typeof(ToolStripPanel); public ToolStripContainerTypedControlCollection(Control c, bool isReadOnly) : base(c, isReadOnly) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs index 071c2da0ab3..69195a0bca4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs @@ -1186,8 +1186,8 @@ internal override void OnKeyboardToolTipUnhook(ToolTip toolTip) private class StubSite : ISite, IDictionaryService { private Hashtable _dictionary = null; - IComponent comp = null; - IComponent owner = null; + readonly IComponent comp = null; + readonly IComponent owner = null; public StubSite(Component control, Component host) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs index 780236e276f..c01cd71f0b5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs @@ -2419,7 +2419,7 @@ internal static ToolStripDropDown GetFirstDropDown(ToolStrip start) [System.Runtime.InteropServices.ComVisible(true)] public class ToolStripDropDownAccessibleObject : ToolStripAccessibleObject { - private ToolStripDropDown owner; + private readonly ToolStripDropDown owner; public ToolStripDropDownAccessibleObject(ToolStripDropDown owner) : base(owner) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownButton.cs index 1c727d82568..1d4f735261d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownButton.cs @@ -228,7 +228,7 @@ protected internal override bool ProcessMnemonic(char charCode) [System.Runtime.InteropServices.ComVisible(true)] internal class ToolStripDropDownButtonAccessibleObject : ToolStripDropDownItemAccessibleObject { - private ToolStripDropDownButton ownerItem = null; + private readonly ToolStripDropDownButton ownerItem = null; public ToolStripDropDownButtonAccessibleObject(ToolStripDropDownButton ownerItem) : base(ownerItem) @@ -251,7 +251,7 @@ internal override object GetPropertyValue(int propertyID) internal class ToolStripDropDownButtonInternalLayout : ToolStripItemInternalLayout { - private ToolStripDropDownButton ownerItem; + private readonly ToolStripDropDownButton ownerItem; private static readonly Size dropDownArrowSizeUnscaled = new Size(5, 3); private static Size dropDownArrowSize = dropDownArrowSizeUnscaled; private const int DROP_DOWN_ARROW_PADDING = 2; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs index 90de9ae2183..68ab23199f6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs @@ -799,7 +799,7 @@ internal override void OnKeyboardToolTipUnhook(ToolTip toolTip) [System.Runtime.InteropServices.ComVisible(true)] public class ToolStripDropDownItemAccessibleObject : ToolStripItem.ToolStripItemAccessibleObject { - private ToolStripDropDownItem owner; + private readonly ToolStripDropDownItem owner; public ToolStripDropDownItemAccessibleObject(ToolStripDropDownItem item) : base(item) { owner = item; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownMenu.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownMenu.cs index f2983fc16cf..6e68a9ec315 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownMenu.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownMenu.cs @@ -25,10 +25,10 @@ public class ToolStripDropDownMenu : ToolStripDropDown // This is totally a UI Fudge - if we have an image or check margin with // no image or checks in it use this - which is consistent with office // and an image margin with a 16x16 icon in it. - private static int DefaultImageMarginWidth = 24; // 24+1px border - with scaling we add this 1px to new, scaled, field value - private static int DefaultImageAndCheckMarginWidth = 46; // 46+1px border - with scaling we add this 1px to new, scaled, field value + private static readonly int DefaultImageMarginWidth = 24; // 24+1px border - with scaling we add this 1px to new, scaled, field value + private static readonly int DefaultImageAndCheckMarginWidth = 46; // 46+1px border - with scaling we add this 1px to new, scaled, field value - private static int ArrowSize = 10; + private static readonly int ArrowSize = 10; private Size maxItemSize = Size.Empty; private Rectangle checkRectangle = Rectangle.Empty; @@ -53,13 +53,13 @@ public class ToolStripDropDownMenu : ToolStripDropDown private static readonly Size DefaultImageSize = new Size(16, 16); private Size scaledDefaultImageSize = DefaultImageSize; - private int scaledDefaultImageMarginWidth = DefaultImageMarginWidth + 1; // 1px for border - private int scaledDefaultImageAndCheckMarginWidth = DefaultImageAndCheckMarginWidth + 1; // 1px for border + private readonly int scaledDefaultImageMarginWidth = DefaultImageMarginWidth + 1; // 1px for border + private readonly int scaledDefaultImageAndCheckMarginWidth = DefaultImageAndCheckMarginWidth + 1; // 1px for border private Padding scaledImagePadding = ImagePadding; private Padding scaledTextPadding = TextPadding; private Padding scaledCheckPadding = CheckPadding; private Padding scaledArrowPadding = ArrowPadding; - private int scaledArrowSize = ArrowSize; + private readonly int scaledArrowSize = ArrowSize; /// /// Summary of ToolStripDropDown. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropTargetManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropTargetManager.cs index 135cf69e7c1..d93dba892da 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropTargetManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropTargetManager.cs @@ -19,7 +19,7 @@ namespace System.Windows.Forms internal class ToolStripDropTargetManager : IDropTarget { private IDropTarget lastDropTarget; - private ToolStrip owner; + private readonly ToolStrip owner; #if DEBUG private bool dropTargetIsEntered; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripGrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripGrip.cs index 673f5ae8258..6c53910e391 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripGrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripGrip.cs @@ -18,7 +18,7 @@ internal class ToolStripGrip : ToolStripButton { private Cursor oldCursor; - private int gripThickness = 0; + private readonly int gripThickness = 0; Point startLocation = Point.Empty; private bool movingToolStrip = false; private Point lastEndLocation = ToolStrip.InvalidMouseEnter; @@ -28,8 +28,8 @@ internal class ToolStripGrip : ToolStripButton private static readonly int gripThicknessDefault = 3; private static readonly int gripThicknessVisualStylesEnabled = 5; private Padding scaledDefaultPadding = defaultPadding; - private int scaledGripThickness = gripThicknessDefault; - private int scaledGripThicknessVisualStylesEnabled = gripThicknessVisualStylesEnabled; + private readonly int scaledGripThickness = gripThicknessDefault; + private readonly int scaledGripThicknessVisualStylesEnabled = gripThicknessVisualStylesEnabled; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] internal ToolStripGrip() diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs index ad39b4b892a..0112540d369 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs @@ -4298,7 +4298,7 @@ public class ToolStripItemAccessibleObject : AccessibleObject // Member variables - private ToolStripItem ownerItem = null; // The associated ToolStripItem for this AccessibleChild (if any) + private readonly ToolStripItem ownerItem = null; // The associated ToolStripItem for this AccessibleChild (if any) private AccessibleStates additionalState = AccessibleStates.None; // Test hook for the designer @@ -4817,7 +4817,7 @@ internal void RaiseFocusChanged() // list for indexing purposes. internal class ToolStripItemImageIndexer : ImageList.Indexer { - private ToolStripItem item; + private readonly ToolStripItem item; public ToolStripItemImageIndexer(ToolStripItem item) { @@ -4850,7 +4850,7 @@ internal class ToolStripItemInternalLayout { private ToolStripItemLayoutOptions currentLayoutOptions; - private ToolStripItem ownerItem; + private readonly ToolStripItem ownerItem; private ButtonBaseAdapter.LayoutData layoutData; private const int BORDER_WIDTH = 2; private const int BORDER_HEIGHT = 3; @@ -5083,8 +5083,8 @@ protected override Size GetTextSize(Size proposedConstraints) } private class ToolStripLayoutData { - private ToolStripLayoutStyle layoutStyle; - private bool autoSize; + private readonly ToolStripLayoutStyle layoutStyle; + private readonly bool autoSize; private Size size; public ToolStripLayoutData(ToolStrip toolStrip) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemCollection.cs index fcc2f34788d..031e0adad53 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemCollection.cs @@ -23,9 +23,9 @@ namespace System.Windows.Forms public class ToolStripItemCollection : ArrangedElementCollection, IList { - private ToolStrip owner; - private bool itemsCollection; - private bool isReadOnly = false; + private readonly ToolStrip owner; + private readonly bool itemsCollection; + private readonly bool isReadOnly = false; /// A caching mechanism for key accessor /// We use an index here rather than control so that we don't have lifetime /// issues by holding on to extra references. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemTextRenderEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemTextRenderEventArgs.cs index 578f6f360d8..27c4d0f9325 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemTextRenderEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItemTextRenderEventArgs.cs @@ -11,7 +11,7 @@ namespace System.Windows.Forms /// public class ToolStripItemTextRenderEventArgs : ToolStripItemRenderEventArgs { - private ContentAlignment _textAlignment; + private readonly ContentAlignment _textAlignment; private Color _textColor = SystemColors.ControlText; private bool _textColorChanged = false; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripLabel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripLabel.cs index 6e8555ae0cd..1bb95eb2c39 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripLabel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripLabel.cs @@ -423,7 +423,7 @@ protected internal override bool ProcessMnemonic(char charCode) [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] internal class ToolStripLabelAccessibleObject : ToolStripItemAccessibleObject { - private ToolStripLabel ownerItem = null; + private readonly ToolStripLabel ownerItem = null; public ToolStripLabelAccessibleObject(ToolStripLabel ownerItem) : base(ownerItem) { @@ -495,8 +495,7 @@ public override AccessibleStates State /// private class ToolStripLabelLayout : ToolStripItemInternalLayout { - - ToolStripLabel owner; + readonly ToolStripLabel owner; public ToolStripLabelLayout(ToolStripLabel owner) : base(owner) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs index b22d0b678d9..bcc29144378 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs @@ -39,7 +39,7 @@ public sealed class ToolStripManager private const int staticEventDefaultRendererChanged = 0; private const int staticEventCount = 1; - private static object internalSyncObject = new object(); + private static readonly object internalSyncObject = new object(); private static void InitalizeThread() { @@ -1556,7 +1556,7 @@ public HostedWindowsFormsMessageHook() } #if DEBUG - string callingStack; + readonly string callingStack; ~HostedWindowsFormsMessageHook() { Debug.Assert(messageHookHandle == IntPtr.Zero, "Finalizing an active mouse hook. This will crash the process. Calling stack: " + callingStack); @@ -2533,7 +2533,7 @@ int IComparer.Compare(object x, object y) internal class MergeHistory { private Stack mergeHistoryItemsStack; - private ToolStrip mergedToolStrip; + private readonly ToolStrip mergedToolStrip; public MergeHistory(ToolStrip mergedToolStrip) { @@ -2561,7 +2561,7 @@ public ToolStrip MergedToolStrip internal class MergeHistoryItem { - private MergeAction mergeAction; + private readonly MergeAction mergeAction; private ToolStripItem targetItem; private int index = -1; private int previousIndex = -1; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs index fae0898f23f..4d83d8b2d7a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs @@ -29,7 +29,7 @@ namespace System.Windows.Forms public class ToolStripMenuItem : ToolStripDropDownItem { - private static MenuTimer menuTimer = new MenuTimer(); + private static readonly MenuTimer menuTimer = new MenuTimer(); private static readonly int PropShortcutKeys = PropertyStore.CreateKey(); private static readonly int PropCheckState = PropertyStore.CreateKey(); @@ -41,7 +41,7 @@ public class ToolStripMenuItem : ToolStripDropDownItem // SUPPORT for mapping NATIVE menu commands to ToolStripMenuItems ----- // corresponds to wID in MENUITEMINFO structure - private int nativeMenuCommandID = -1; + private readonly int nativeMenuCommandID = -1; private IntPtr targetWindowHandle = IntPtr.Zero; private IntPtr nativeMenuHandle = IntPtr.Zero; @@ -1367,7 +1367,7 @@ internal override bool IsBeingTabbedTo() [System.Runtime.InteropServices.ComVisible(true)] internal class ToolStripMenuItemAccessibleObject : ToolStripDropDownItemAccessibleObject { - private ToolStripMenuItem ownerItem = null; + private readonly ToolStripMenuItem ownerItem = null; public ToolStripMenuItemAccessibleObject(ToolStripMenuItem ownerItem) : base(ownerItem) { @@ -1421,16 +1421,16 @@ internal override object GetPropertyValue(int propertyID) internal class MenuTimer { - private System.Windows.Forms.Timer autoMenuExpandTimer = new System.Windows.Forms.Timer(); + private readonly System.Windows.Forms.Timer autoMenuExpandTimer = new System.Windows.Forms.Timer(); // consider - weak reference? private ToolStripMenuItem currentItem = null; private ToolStripMenuItem fromItem = null; private bool inTransition = false; - private int quickShow = 1; + private readonly int quickShow = 1; - private int slowShow; + private readonly int slowShow; public MenuTimer() { @@ -1608,7 +1608,7 @@ private void OnTick(object sender, EventArgs e) internal class ToolStripMenuItemInternalLayout : ToolStripItemInternalLayout { - private ToolStripMenuItem ownerItem; + private readonly ToolStripMenuItem ownerItem; public ToolStripMenuItemInternalLayout(ToolStripMenuItem ownerItem) : base(ownerItem) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripOverflow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripOverflow.cs index 296863e26a0..68f2a001ddf 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripOverflow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripOverflow.cs @@ -20,7 +20,7 @@ public class ToolStripOverflow : ToolStripDropDown, IArrangedElement internal static readonly TraceSwitch PopupLayoutDebug; #endif - private ToolStripOverflowButton ownerItem; + private readonly ToolStripOverflowButton ownerItem; public ToolStripOverflow(ToolStripItem parentItem) : base(parentItem) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripOverflowButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripOverflowButton.cs index 5a8c90d4cee..6488f042f31 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripOverflowButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripOverflowButton.cs @@ -20,7 +20,7 @@ public class ToolStripOverflowButton : ToolStripDropDownButton { // we need to cache this away as the Parent property gets reset a lot. - private ToolStrip parentToolStrip; + private readonly ToolStrip parentToolStrip; private static bool isScalingInitialized = false; private const int MAX_WIDTH = 16; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs index 1ae3d5d75ce..36bf4a7e528 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs @@ -32,9 +32,9 @@ public class ToolStripPanel : ContainerControl, IArrangedElement private static readonly Padding rowMargin = new Padding(3, 0, 0, 0); private Padding scaledRowMargin = rowMargin; private ToolStripRendererSwitcher rendererSwitcher = null; - private Type currentRendererType = typeof(System.Type); + private readonly Type currentRendererType = typeof(System.Type); private BitVector32 state = new BitVector32(); - private ToolStripContainer owner; + private readonly ToolStripContainer owner; #if DEBUG @@ -1493,7 +1493,7 @@ ArrangedElementCollection IArrangedElement.Children public class ToolStripPanelRowCollection : ArrangedElementCollection, IList { - private ToolStripPanel owner; + private readonly ToolStripPanel owner; public ToolStripPanelRowCollection(ToolStripPanel owner) { this.owner = owner; @@ -1706,7 +1706,7 @@ public void CopyTo(ToolStripPanelRow[] array, int index) internal class ToolStripPanelControlCollection : WindowsFormsUtils.TypedControlCollection { - private ToolStripPanel owner; + private readonly ToolStripPanel owner; public ToolStripPanelControlCollection(ToolStripPanel owner) : base(owner, typeof(ToolStrip)) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelCell.cs index 2b0fa8aefdb..e378e52a0bf 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelCell.cs @@ -32,7 +32,7 @@ internal class ToolStripPanelCell : ArrangedElement private Rectangle cachedBounds = Rectangle.Empty; #if DEBUG - private string cellID; + private readonly string cellID; [ThreadStatic] private static int cellCount; #endif diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs index 1e31feb25f1..409c7cb12e4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanelRow.cs @@ -20,15 +20,15 @@ namespace System.Windows.Forms public class ToolStripPanelRow : Component, IArrangedElement { private Rectangle bounds = Rectangle.Empty; - private ToolStripPanel parent = null; + private readonly ToolStripPanel parent = null; private BitVector32 state = new BitVector32(); - private PropertyStore propertyStore = new PropertyStore(); // Contains all properties that are not always set. + private readonly PropertyStore propertyStore = new PropertyStore(); // Contains all properties that are not always set. private int suspendCount = 0; private ToolStripPanelRowManager rowManager = null; private const int MINALLOWEDWIDTH = 50; - private int minAllowedWidth = MINALLOWEDWIDTH; + private readonly int minAllowedWidth = MINALLOWEDWIDTH; private static readonly int stateVisible = BitVector32.CreateMask(); private static readonly int stateDisposing = BitVector32.CreateMask(stateVisible); @@ -51,7 +51,7 @@ public class ToolStripPanelRow : Component, IArrangedElement #if DEBUG private static int rowCreationCount = 0; - private int thisRowID; + private readonly int thisRowID; #endif @@ -854,7 +854,7 @@ private abstract class ToolStripPanelRowManager { private FlowLayoutSettings flowLayoutSettings = null; - private ToolStripPanelRow owner = null; + private readonly ToolStripPanelRow owner = null; public ToolStripPanelRowManager(ToolStripPanelRow owner) { @@ -2307,7 +2307,7 @@ public override void LeaveRow(ToolStrip toolStripToDrag) /// internal class ToolStripPanelRowControlCollection : ArrangedElementCollection, IList, IEnumerable { - private ToolStripPanelRow owner; + private readonly ToolStripPanelRow owner; private ArrangedElementCollection cellCollection; public ToolStripPanelRowControlCollection(ToolStripPanelRow owner) @@ -2618,7 +2618,7 @@ public void CopyTo(Control[] array, int index) /// to sort of write a wrapper class around the ArrayList enumerator. private class ToolStripPanelCellToControlEnumerator : IEnumerator, ICloneable { - private IEnumerator arrayListEnumerator; + private readonly IEnumerator arrayListEnumerator; internal ToolStripPanelCellToControlEnumerator(ArrayList list) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProgressBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProgressBar.cs index beb30ebefdc..e41068113a4 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProgressBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripProgressBar.cs @@ -452,7 +452,7 @@ public void PerformStep() [System.Runtime.InteropServices.ComVisible(true)] internal class ToolStripProgressBarAccessibleObject : ToolStripItemAccessibleObject { - private ToolStripProgressBar ownerItem = null; + private readonly ToolStripProgressBar ownerItem = null; public ToolStripProgressBarAccessibleObject(ToolStripProgressBar ownerItem) : base(ownerItem) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRenderer.cs index 07d3e0d89b7..288b57b9ae0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRenderer.cs @@ -42,14 +42,14 @@ public abstract class ToolStripRenderer private static ColorMatrix disabledImageColorMatrix; private EventHandlerList events; - private bool isAutoGenerated = false; + private readonly bool isAutoGenerated = false; private static bool isScalingInitialized = false; // arrows are rendered as isosceles triangles, whose heights are half the base in order to have 45 degree angles // Offset2X is half of the base // Offset2Y is height of the isosceles triangle - private static int OFFSET_2PIXELS = 2; - private static int OFFSET_4PIXELS = 4; + private static readonly int OFFSET_2PIXELS = 2; + private static readonly int OFFSET_4PIXELS = 4; protected static int Offset2X = OFFSET_2PIXELS; protected static int Offset2Y = OFFSET_2PIXELS; private static int offset4X = OFFSET_4PIXELS; @@ -57,7 +57,7 @@ public abstract class ToolStripRenderer // this is used in building up the half pyramid of rectangles that are drawn in a // status strip sizing grip. - private static Rectangle[] baseSizeGripRectangles = new Rectangle[] { new Rectangle(8,0,2,2), + private static readonly Rectangle[] baseSizeGripRectangles = new Rectangle[] { new Rectangle(8,0,2,2), new Rectangle(8,4,2,2), new Rectangle(8,8,2,2), new Rectangle(4,4,2,2), diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRendererSwitcher.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRendererSwitcher.cs index 5edb3db11d9..bd4812b72ce 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRendererSwitcher.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRendererSwitcher.cs @@ -23,7 +23,7 @@ internal class ToolStripRendererSwitcher private Type currentRendererType = typeof(System.Type); private BitVector32 state = new BitVector32(); - private ToolStripRenderMode defaultRenderMode = ToolStripRenderMode.ManagerRenderMode; + private readonly ToolStripRenderMode defaultRenderMode = ToolStripRenderMode.ManagerRenderMode; public ToolStripRendererSwitcher(Control owner, ToolStripRenderMode defaultRenderMode) : this(owner) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripScrollButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripScrollButton.cs index d41f141a1a4..8907606ccaa 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripScrollButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripScrollButton.cs @@ -17,7 +17,7 @@ namespace System.Windows.Forms /// internal class ToolStripScrollButton : ToolStripControlHost { - private bool up = true; + private readonly bool up = true; [ThreadStatic] private static Bitmap upScrollImage; @@ -189,7 +189,7 @@ internal class StickyLabel : Label public StickyLabel() { } - private bool freezeLocationChange = false; + private readonly bool freezeLocationChange = false; public bool FreezeLocationChange { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSeparator.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSeparator.cs index 6ffbd0d2496..88346aef726 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSeparator.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSeparator.cs @@ -526,7 +526,7 @@ internal protected override void SetBounds(Rectangle rect) [System.Runtime.InteropServices.ComVisible(true)] internal class ToolStripSeparatorAccessibleObject : ToolStripItemAccessibleObject { - private ToolStripSeparator ownerItem = null; + private readonly ToolStripSeparator ownerItem = null; public ToolStripSeparatorAccessibleObject(ToolStripSeparator ownerItem) : base(ownerItem) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSettings.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSettings.cs index 00cf7312d04..c419692d272 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSettings.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSettings.cs @@ -131,8 +131,8 @@ public override void Save() /// internal class ToolStripSettingsManager { - private Form form; - private string formKey; + private readonly Form form; + private readonly string formKey; internal ToolStripSettingsManager(Form owner, string formKey) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs index fcd0e5e574b..3cc6cfd4013 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs @@ -714,7 +714,7 @@ internal virtual bool ShouldSerializeDropDownButtonWidth() private class ToolStripSplitButtonButton : ToolStripButton { - private ToolStripSplitButton owner = null; + private readonly ToolStripSplitButton owner = null; public ToolStripSplitButtonButton(ToolStripSplitButton owner) { @@ -830,8 +830,7 @@ public override string Text /// private class ToolStripSplitButtonButtonLayout : ToolStripItemInternalLayout { - - ToolStripSplitButton owner; + readonly ToolStripSplitButton owner; public ToolStripSplitButtonButtonLayout(ToolStripSplitButton owner) : base(owner.SplitButtonButton) { @@ -876,7 +875,7 @@ public override Rectangle TextRectangle [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] public class ToolStripSplitButtonAccessibleObject : ToolStripItem.ToolStripItemAccessibleObject { - private ToolStripSplitButton owner; + private readonly ToolStripSplitButton owner; public ToolStripSplitButtonAccessibleObject(ToolStripSplitButton item) : base(item) { @@ -892,7 +891,7 @@ public override void DoDefaultAction() internal class ToolStripSplitButtonExAccessibleObject : ToolStripSplitButtonAccessibleObject { - private ToolStripSplitButton ownerItem; + private readonly ToolStripSplitButton ownerItem; public ToolStripSplitButtonExAccessibleObject(ToolStripSplitButton item) : base(item) @@ -988,8 +987,8 @@ private int DropDownItemsCount internal class ToolStripSplitButtonUiaProvider : ToolStripDropDownItemAccessibleObject { - private ToolStripSplitButton _owner; - private ToolStripSplitButtonExAccessibleObject _accessibleObject; + private readonly ToolStripSplitButton _owner; + private readonly ToolStripSplitButtonExAccessibleObject _accessibleObject; public ToolStripSplitButtonUiaProvider(ToolStripSplitButton owner) : base(owner) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitStackLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitStackLayout.cs index b05176b7a5d..201e42c7602 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitStackLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitStackLayout.cs @@ -14,7 +14,7 @@ internal class ToolStripSplitStackLayout : LayoutEngine { private int backwardsWalkingIndex; private int forwardsWalkingIndex; - private ToolStrip toolStrip; + private readonly ToolStrip toolStrip; private int overflowSpace; private bool overflowRequired; private Point noMansLand; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripStatusLabel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripStatusLabel.cs index b6c9d8409ff..07358fed2f0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripStatusLabel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripStatusLabel.cs @@ -268,7 +268,7 @@ protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) [ComVisible(true)] internal class ToolStripStatusLabelAccessibleObject : ToolStripLabelAccessibleObject { - private ToolStripStatusLabel ownerItem; + private readonly ToolStripStatusLabel ownerItem; public ToolStripStatusLabelAccessibleObject(ToolStripStatusLabel ownerItem) : base(ownerItem) { @@ -307,8 +307,7 @@ internal override object GetPropertyValue(int propertyID) /// private class ToolStripStatusLabelLayout : ToolStripItemInternalLayout { - - ToolStripStatusLabel owner; + readonly ToolStripStatusLabel owner; public ToolStripStatusLabelLayout(ToolStripStatusLabel owner) : base(owner) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripTextBox.cs index 765304a40cd..fc95719cb21 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripTextBox.cs @@ -130,7 +130,7 @@ protected override AccessibleObject CreateAccessibilityInstance() [System.Runtime.InteropServices.ComVisible(true)] internal class ToolStripTextBoxAccessibleObject : ToolStripItemAccessibleObject { - private ToolStripTextBox ownerItem = null; + private readonly ToolStripTextBox ownerItem = null; public ToolStripTextBoxAccessibleObject(ToolStripTextBox ownerItem) : base(ownerItem) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs index cc4a5da92ed..31f06d8da2a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs @@ -51,9 +51,8 @@ public class ToolTip : Component, IExtenderProvider private const int BOTTOM_LOCATION_INDEX = 2; private const int LEFT_LOCATION_INDEX = 3; private const int LOCATION_TOTAL = 4; - - Hashtable tools = new Hashtable(); - int[] delayTimes = new int[4]; + readonly Hashtable tools = new Hashtable(); + readonly int[] delayTimes = new int[4]; bool auto = true; bool showAlways = false; ToolTipNativeWindow window = null; @@ -68,7 +67,7 @@ public class ToolTip : Component, IExtenderProvider string toolTipTitle = string.Empty; ToolTipIcon toolTipIcon = (ToolTipIcon)0; ToolTipTimer timer; - Hashtable owners = new Hashtable(); + readonly Hashtable owners = new Hashtable(); bool stripAmpersands = false; bool useAnimation = true; bool useFading = true; @@ -84,7 +83,7 @@ public class ToolTip : Component, IExtenderProvider // Adding a tool twice breaks the ToolTip, so we need to track which // tools are created to prevent this... // - Hashtable created = new Hashtable(); + readonly Hashtable created = new Hashtable(); private bool cancelled = false; @@ -2879,7 +2878,7 @@ private void WndProc(ref Message msg) /// private class ToolTipNativeWindow : NativeWindow { - ToolTip control; + readonly ToolTip control; internal ToolTipNativeWindow(ToolTip control) { @@ -2898,7 +2897,7 @@ protected override void WndProc(ref Message m) private class ToolTipTimer : Timer { - IWin32Window host; + readonly IWin32Window host; public ToolTipTimer(IWin32Window owner) : base() { @@ -2929,7 +2928,7 @@ public enum Type public Type TipType = Type.Auto; private string caption; - private string designerText; + private readonly string designerText; public Point Position = Point.Empty; public TipInfo(string caption, Type type) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolstripProfessionalRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolstripProfessionalRenderer.cs index 01026677383..e28886e793f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolstripProfessionalRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolstripProfessionalRenderer.cs @@ -37,7 +37,7 @@ public class ToolStripProfessionalRenderer : ToolStripRenderer private const int DROP_DOWN_MENU_ITEM_PAINT_PADDING_SIZE = 1; private Padding scaledDropDownMenuItemPaintPadding = new Padding(DROP_DOWN_MENU_ITEM_PAINT_PADDING_SIZE + 1, 0, DROP_DOWN_MENU_ITEM_PAINT_PADDING_SIZE, 0); - private ProfessionalColorTable professionalColorTable; + private readonly ProfessionalColorTable professionalColorTable; private bool roundedEdges = true; private ToolStripRenderer toolStripHighContrastRenderer; private ToolStripRenderer toolStripLowResolutionRenderer; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs index b7742c5308f..63631955e1d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNode.cs @@ -74,14 +74,14 @@ public class TreeNode : MarshalByRefObject, ICloneable, ISerializable // list for indexing purposes. internal class TreeNodeImageIndexer : ImageList.Indexer { - private TreeNode owner; + private readonly TreeNode owner; public enum ImageListType { Default, State } - private ImageListType imageListType; + private readonly ImageListType imageListType; public TreeNodeImageIndexer(TreeNode node, ImageListType imageListType) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeCollection.cs index b5cf4ddbe86..23e20980713 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeNodeCollection.cs @@ -20,7 +20,7 @@ namespace System.Windows.Forms ] public class TreeNodeCollection : IList { - private TreeNode owner; + private readonly TreeNode owner; /// A caching mechanism for key accessor /// We use an index here rather than control so that we don't have lifetime diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewCancelEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewCancelEventArgs.cs index f46383b5577..8ffaa2dfbdb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewCancelEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewCancelEventArgs.cs @@ -26,8 +26,8 @@ namespace System.Windows.Forms /// public class TreeViewCancelEventArgs : CancelEventArgs { - private TreeNode node; - private TreeViewAction action; + private readonly TreeNode node; + private readonly TreeViewAction action; public TreeViewCancelEventArgs(TreeNode node, bool cancel, TreeViewAction action) : base(cancel) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewEventArgs.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewEventArgs.cs index 438f505a89a..9de1dcac6eb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewEventArgs.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewEventArgs.cs @@ -22,8 +22,8 @@ namespace System.Windows.Forms /// public class TreeViewEventArgs : EventArgs { - TreeNode node; - TreeViewAction action = TreeViewAction.Unknown; + readonly TreeNode node; + readonly TreeViewAction action = TreeViewAction.Unknown; public TreeViewEventArgs(TreeNode node) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewHitTestInfo.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewHitTestInfo.cs index 2837fff7824..493616b8d7d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewHitTestInfo.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeViewHitTestInfo.cs @@ -16,8 +16,8 @@ namespace System.Windows.Forms public class TreeViewHitTestInfo { - private TreeViewHitTestLocations loc; - private TreeNode node; + private readonly TreeViewHitTestLocations loc; + private readonly TreeNode node; /// /// Creates a TreeViewHitTestInfo instance. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs index 6451ec06b70..272120933d8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs @@ -1293,7 +1293,7 @@ internal class UpDownEdit : TextBox ///////////////////////////////////////////////////////////////////// // Parent control - private UpDownBase parent; + private readonly UpDownBase parent; private bool doubleClickFired = false; ///////////////////////////////////////////////////////////////////// // Constructors @@ -1422,7 +1422,7 @@ protected override void OnLostFocus(EventArgs e) // back to our parent. They should track. internal class UpDownEditAccessibleObject : ControlAccessibleObject { - UpDownBase parent; + readonly UpDownBase parent; public UpDownEditAccessibleObject(UpDownEdit owner, UpDownBase parent) : base(owner) { @@ -1471,7 +1471,7 @@ internal class UpDownButtons : Control ///////////////////////////////////////////////////////////////////// // Parent control - private UpDownBase parent; + private readonly UpDownBase parent; // Button state private ButtonID pushed = ButtonID.None; @@ -2005,8 +2005,8 @@ public override int GetChildCount() internal class DirectionButtonAccessibleObject : AccessibleObject { - private bool up; - private UpDownButtonsAccessibleObject parent; + private readonly bool up; + private readonly UpDownButtonsAccessibleObject parent; public DirectionButtonAccessibleObject(UpDownButtonsAccessibleObject parent, bool up) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleElement.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleElement.cs index f62c13e0cf3..098f8b0a2d1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleElement.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleElement.cs @@ -32,9 +32,9 @@ namespace System.Windows.Forms.VisualStyles public class VisualStyleElement { internal static readonly int Count = 25; //UPDATE THIS WHEN CLASSES ARE ADDED/REMOVED! - private string className; - private int part; - private int state; + private readonly string className; + private readonly int part; + private readonly int state; private VisualStyleElement(string className, int part, int state) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleRenderer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleRenderer.cs index 130eb964abe..dc57ed18c6b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleRenderer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/VisualStyles/VisualStyleRenderer.cs @@ -33,7 +33,7 @@ public sealed class VisualStyleRenderer private int part; private int state; private int lastHResult = 0; - private static int numberOfPossibleClasses = VisualStyleElement.Count; //used as size for themeHandles + private static readonly int numberOfPossibleClasses = VisualStyleElement.Count; //used as size for themeHandles [ThreadStatic] private static Hashtable themeHandles = null; //per-thread cache of ThemeHandle objects. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs index 632fc6e7cac..52e0b81042d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs @@ -1922,7 +1922,7 @@ internal override void OnPropertyChanged(int dispid) private class WebBrowserEvent : StandardOleMarshalObject, UnsafeNativeMethods.DWebBrowserEvents2 { - private WebBrowser parent; + private readonly WebBrowser parent; private bool allowNavigation; private bool haveNavigated = false; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs index 1891f311cb6..68a677b546b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserBase.cs @@ -37,7 +37,7 @@ public class WebBrowserBase : Control private WebBrowserHelper.AXState axState = WebBrowserHelper.AXState.Passive; private WebBrowserHelper.AXState axReloadingState = WebBrowserHelper.AXState.Passive; private WebBrowserHelper.AXEditMode axEditMode = WebBrowserHelper.AXEditMode.None; - private bool inRtlRecreate = false; + private readonly bool inRtlRecreate = false; private BitVector32 axHostState = new BitVector32(); private WebBrowserHelper.SelectionStyle selectionStyle = WebBrowserHelper.SelectionStyle.NotSelected; private int noComponentChange = 0; @@ -1976,7 +1976,7 @@ public override string Text /// private class WebBrowserBaseNativeWindow : NativeWindow { - private WebBrowserBase WebBrowserBase; + private readonly WebBrowserBase WebBrowserBase; public WebBrowserBaseNativeWindow(WebBrowserBase ax) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs index fb5cd6c78b5..9fb4e2ea6ef 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserContainer.cs @@ -12,13 +12,13 @@ namespace System.Windows.Forms { internal class WebBrowserContainer : UnsafeNativeMethods.IOleContainer, UnsafeNativeMethods.IOleInPlaceFrame { - private WebBrowserBase parent; + private readonly WebBrowserBase parent; private IContainer assocContainer; // associated IContainer... // the assocContainer may be null, in which case all this container does is // forward [de]activation messages to the requisite container... private WebBrowserBase siteUIActive; private WebBrowserBase siteActive; - private Hashtable containerCache = new Hashtable(); // name -> Control + private readonly Hashtable containerCache = new Hashtable(); // name -> Control private Hashtable components = null; // Control -> any private WebBrowserBase ctlInEditMode = null; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs index ceb2c607400..7452511ae8f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserSiteBase.cs @@ -24,7 +24,7 @@ namespace System.Windows.Forms public class WebBrowserSiteBase : UnsafeNativeMethods.IOleControlSite, UnsafeNativeMethods.IOleClientSite, UnsafeNativeMethods.IOleInPlaceSite, UnsafeNativeMethods.ISimpleFrameSite, UnsafeNativeMethods.IPropertyNotifySink, IDisposable { - private WebBrowserBase host; + private readonly WebBrowserBase host; private AxHost.ConnectionPointCookie connectionPoint; // diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WinFormsUtils.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WinFormsUtils.cs index ca3edba0cdb..1db11c260d1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WinFormsUtils.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WinFormsUtils.cs @@ -408,8 +408,8 @@ public static bool IsEnumWithinShiftedRange(Enum enumValue, int numBitsToShift, public class ArraySubsetEnumerator : IEnumerator { - private object[] _array; - private int _total; + private readonly object[] _array; + private readonly int _total; private int _current; public ArraySubsetEnumerator(object[] array, int count) @@ -499,8 +499,8 @@ public override void RemoveByKey(string key) /// internal class TypedControlCollection : ReadOnlyControlCollection { - private Type _typeOfControl; - private Control _ownerControl; + private readonly Type _typeOfControl; + private readonly Control _ownerControl; public TypedControlCollection(Control owner, Type typeOfControl, bool isReadOnly) : base(owner, isReadOnly) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs b/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs index ec3b57cfb3e..290e143dd74 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs @@ -1397,7 +1397,7 @@ public struct ImeModeConversion /// meaning depending on the language; for instance ImeMode.Off means 'disable' or 'alpha' to Chinese /// but to Japanese it is 'alpha' and to Korean it has no meaning. /// - private static ImeMode[] japaneseTable = { + private static readonly ImeMode[] japaneseTable = { ImeMode.Inherit, ImeMode.Disable, ImeMode.Off, @@ -1410,7 +1410,7 @@ public struct ImeModeConversion ImeMode.Alpha }; - private static ImeMode[] koreanTable = { + private static readonly ImeMode[] koreanTable = { ImeMode.Inherit, ImeMode.Disable, ImeMode.Alpha, @@ -1423,7 +1423,7 @@ public struct ImeModeConversion ImeMode.Alpha }; - private static ImeMode[] chineseTable = { + private static readonly ImeMode[] chineseTable = { ImeMode.Inherit, ImeMode.Disable, ImeMode.Off, @@ -1436,7 +1436,7 @@ public struct ImeModeConversion ImeMode.Off }; - private static ImeMode[] unsupportedTable = { + private static readonly ImeMode[] unsupportedTable = { }; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/formatter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/formatter.cs index b19dce8232d..ac5b79f5d7f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/formatter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/formatter.cs @@ -10,11 +10,11 @@ namespace System.Windows.Forms { internal class Formatter { - static private Type stringType = typeof(string); - static private Type booleanType = typeof(bool); - static private Type checkStateType = typeof(CheckState); - static private object parseMethodNotFound = new object(); - static private object defaultDataSourceNullValue = System.DBNull.Value; + private static readonly Type stringType = typeof(string); + private static readonly Type booleanType = typeof(bool); + private static readonly Type checkStateType = typeof(CheckState); + private static readonly object parseMethodNotFound = new object(); + private static readonly object defaultDataSourceNullValue = System.DBNull.Value; /// /// diff --git a/src/System.Windows.Forms/src/misc/GDI/DeviceContext.cs b/src/System.Windows.Forms/src/misc/GDI/DeviceContext.cs index 00196775362..5ab02dd19a1 100644 --- a/src/System.Windows.Forms/src/misc/GDI/DeviceContext.cs +++ b/src/System.Windows.Forms/src/misc/GDI/DeviceContext.cs @@ -75,7 +75,7 @@ sealed partial class DeviceContext : MarshalByRefObject, IDeviceContext, IDispos [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] IntPtr hDC; - DeviceContextType dcType; + readonly DeviceContextType dcType; public event EventHandler Disposing; @@ -84,7 +84,7 @@ sealed partial class DeviceContext : MarshalByRefObject, IDeviceContext, IDispos // We cache the hWnd when creating the dc from one, to provide support forIDeviceContext.GetHdc/ReleaseHdc. // This hWnd could be null, in such case it is referring to the screen. [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] - IntPtr hWnd = (IntPtr)(-1); // Unlikely to be a valid hWnd. + readonly IntPtr hWnd = (IntPtr)(-1); // Unlikely to be a valid hWnd. IntPtr hInitialPen; IntPtr hInitialBrush; diff --git a/src/System.Windows.Forms/src/misc/GDI/NativeMethods.cs b/src/System.Windows.Forms/src/misc/GDI/NativeMethods.cs index 588d338ed1e..df11154a1af 100644 --- a/src/System.Windows.Forms/src/misc/GDI/NativeMethods.cs +++ b/src/System.Windows.Forms/src/misc/GDI/NativeMethods.cs @@ -242,7 +242,7 @@ public override string ToString() [StructLayout(LayoutKind.Sequential)] public class DRAWTEXTPARAMS { - private int cbSize = Marshal.SizeOf(); + private readonly int cbSize = Marshal.SizeOf(); public int iTabLength; public int iLeftMargin; public int iRightMargin; diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsBrush.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsBrush.cs index 0ee044df875..22b7952d619 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsBrush.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsBrush.cs @@ -35,9 +35,9 @@ abstract class WindowsBrush : MarshalByRefObject, ICloneable, IDisposable { // Handle to the native Windows brush object. // - private DeviceContext dc; + private readonly DeviceContext dc; private IntPtr nativeHandle; // Cannot be protected because the class is internal (C# doesn't allow it). - private Color color = Color.White; // GDI brushes have just one color as opposed to GDI+ that can have background color. + private readonly Color color = Color.White; // GDI brushes have just one color as opposed to GDI+ that can have background color. // Note: We may need to implement background color too. #if WINGRAPHICS_FINALIZATION_WATCH diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs index 408b9928c9e..2c89afe1746 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsFont.cs @@ -39,8 +39,8 @@ sealed partial class WindowsFont : MarshalByRefObject, ICloneable, IDisposable private bool ownedByCacheManager; private bool everOwnedByCacheManager; - private IntNativeMethods.LOGFONT logFont; - private FontStyle style; + private readonly IntNativeMethods.LOGFONT logFont; + private readonly FontStyle style; // Note: These defaults are according to the ones in GDI+ but those are not necessarily the same as the system // default font. The GetSystemDefaultHFont() method should be used if needed. diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsPen.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsPen.cs index e79a69b6830..de0858ad479 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsPen.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsPen.cs @@ -40,15 +40,15 @@ sealed partial class WindowsPen : MarshalByRefObject, ICloneable, IDisposable private const int endCapMask = 0x00000F00; private const int joinMask = 0x0000F000; - private DeviceContext dc; + private readonly DeviceContext dc; // // Fields with default values // private WindowsBrush wndBrush; private WindowsPenStyle style; - private Color color; - private int width; + private readonly Color color; + private readonly int width; private const int cosmeticPenWidth = 1; // Cosmetic pen width. diff --git a/src/System.Windows.Forms/src/misc/InvariantComparer.cs b/src/System.Windows.Forms/src/misc/InvariantComparer.cs index 0162bd0ee63..97bc274cfc7 100644 --- a/src/System.Windows.Forms/src/misc/InvariantComparer.cs +++ b/src/System.Windows.Forms/src/misc/InvariantComparer.cs @@ -11,7 +11,7 @@ namespace System [Serializable] internal class InvariantComparer : IComparer { - private CompareInfo m_compareInfo; + private readonly CompareInfo m_compareInfo; internal static readonly InvariantComparer Default = new InvariantComparer(); internal InvariantComparer() diff --git a/src/System.Windows.Forms/src/misc/WeakHashtable.cs b/src/System.Windows.Forms/src/misc/WeakHashtable.cs index 08f150d184d..803419df558 100644 --- a/src/System.Windows.Forms/src/misc/WeakHashtable.cs +++ b/src/System.Windows.Forms/src/misc/WeakHashtable.cs @@ -15,7 +15,7 @@ namespace System.ComponentModel /// internal sealed class WeakHashtable : Hashtable { - private static IEqualityComparer _comparer = new WeakKeyComparer(); + private static readonly IEqualityComparer _comparer = new WeakKeyComparer(); private long _lastGlobalMem; private int _lastHashCount; @@ -170,7 +170,7 @@ int IEqualityComparer.GetHashCode(object obj) /// private sealed class EqualityWeakReference : WeakReference { - private int _hashCode; + private readonly int _hashCode; internal EqualityWeakReference(object o) : base(o) { _hashCode = o.GetHashCode(); diff --git a/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/Buttons.cs b/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/Buttons.cs index ec1c52c2f21..964caef7e93 100644 --- a/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/Buttons.cs +++ b/src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/Buttons.cs @@ -14,7 +14,7 @@ public Buttons() InitializeComponent(); } - private FlatStyle[] styles = { FlatStyle.Flat, FlatStyle.Popup, FlatStyle.Standard, FlatStyle.System }; + private readonly FlatStyle[] styles = { FlatStyle.Flat, FlatStyle.Popup, FlatStyle.Standard, FlatStyle.System }; private void Test1_Load(object sender, EventArgs e) { RadioButton r; diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BaseCollectionTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BaseCollectionTests.cs index fe2008ab7e1..45cb23c8947 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BaseCollectionTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/BaseCollectionTests.cs @@ -67,7 +67,7 @@ public void GetEnumerator_InvokeDefault_ThrowsNullReferenceException() private class SubCollection : BaseCollection { - private ArrayList _list; + private readonly ArrayList _list; public SubCollection(ArrayList list) => _list = list; diff --git a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/FeatureSupportTests.cs b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/FeatureSupportTests.cs index 5fda84e7985..b46c48ec4cf 100644 --- a/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/FeatureSupportTests.cs +++ b/src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/FeatureSupportTests.cs @@ -188,8 +188,8 @@ public Version GetVersionPresent(object feature) public static object s_zeroVersionField = new object(); public static object s_nonZeroVersionField = new object(); - private object _privateField = new object(); - private static object s_privateField = new object(); + private readonly object _privateField = new object(); + private static readonly object s_privateField = new object(); } private class NonIFeatureSupportClass From 97acaa3e234606198a14c489b703641ec24a9671 Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Fri, 24 May 2019 12:48:14 -0700 Subject: [PATCH 24/27] remove all instances of IDE0049 warning - simplify type name (ex: String to string) --- src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs b/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs index df11cd21aed..9f2412439d3 100644 --- a/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs +++ b/src/System.Windows.Forms/src/System/Resources/ResXDataNode.cs @@ -261,7 +261,7 @@ public ResXFileRef FileRef if (fileRef == null) { fileRef = - String.IsNullOrEmpty(fileRefTextEncoding) + string.IsNullOrEmpty(fileRefTextEncoding) ? new ResXFileRef(FileRefFullPath, FileRefType) : new ResXFileRef(FileRefFullPath, FileRefType, Encoding.GetEncoding(FileRefTextEncoding)); } From 5e664d06826d68abed14b3da363a11be1c44f361 Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Fri, 24 May 2019 12:56:46 -0700 Subject: [PATCH 25/27] remove all instances of IDE0052 warning - use compound assignment (-=) --- src/Common/src/ClientUtils.cs | 6 +++--- .../Shell32/Interop.SHGetPathFromIDListLongPath.cs | 2 +- .../src/Misc/NativeMethods.cs | 8 ++++---- .../Forms/Design/Behavior/GlyphCollection.cs | 4 ++-- .../src/System/Windows/Forms/AxHost.cs | 6 +++--- .../src/System/Windows/Forms/DataGrid.cs | 14 +++++++------- .../src/System/Windows/Forms/FileDialog.cs | 2 +- .../Forms/Layout/ArrangedElementCollection.cs | 4 ++-- .../src/System/Windows/Forms/Layout/LayoutUtils.cs | 2 +- .../src/System/Windows/Forms/ListBindingHelper.cs | 2 +- .../src/System/Windows/Forms/ListBox.cs | 2 +- .../src/System/Windows/Forms/TextBox.cs | 12 ++++++------ .../System/Windows/Forms/ThreadExceptionDialog.cs | 2 +- .../src/System/Windows/Forms/ToolBar.cs | 2 +- .../src/misc/GDI/WindowsGraphics2.cs | 4 ++-- 15 files changed, 36 insertions(+), 36 deletions(-) diff --git a/src/Common/src/ClientUtils.cs b/src/Common/src/ClientUtils.cs index a6116d40b29..302eb9d60c0 100644 --- a/src/Common/src/ClientUtils.cs +++ b/src/Common/src/ClientUtils.cs @@ -274,7 +274,7 @@ private static void Debug_ValidateMask(System.Enum value, uint mask) uint newmask = 0; foreach (int iVal in Enum.GetValues(t)) { - newmask = newmask | (uint)iVal; + newmask |= (uint)iVal; } System.Diagnostics.Debug.Assert(newmask == mask, "Mask not valid in IsEnumValid!"); } @@ -457,8 +457,8 @@ private static void Copy(WeakRefCollection sourceList, int sourceIndex, WeakRefC // We need to copy from the back forward to prevent overwrite if source and // destination lists are the same, so we need to flip the source/dest indices // to point at the end of the spans to be copied. - sourceIndex = sourceIndex + length; - destinationIndex = destinationIndex + length; + sourceIndex += length; + destinationIndex += length; for (; length > 0; length--) { destinationList.InnerList[--destinationIndex] = sourceList.InnerList[--sourceIndex]; diff --git a/src/Common/src/Interop/Shell32/Interop.SHGetPathFromIDListLongPath.cs b/src/Common/src/Interop/Shell32/Interop.SHGetPathFromIDListLongPath.cs index f4bfd67b313..3416821b953 100644 --- a/src/Common/src/Interop/Shell32/Interop.SHGetPathFromIDListLongPath.cs +++ b/src/Common/src/Interop/Shell32/Interop.SHGetPathFromIDListLongPath.cs @@ -66,7 +66,7 @@ public unsafe static bool SHGetPathFromIDListLongPath(IntPtr pidl, ref IntPtr ps } // Try giving the API a larger buffer - length = length * 2; + length *= 2; if (length > Kernel32.MAX_UNICODESTRING_LEN) { length = Kernel32.MAX_UNICODESTRING_LEN; diff --git a/src/System.Windows.Forms.Design.Editors/src/Misc/NativeMethods.cs b/src/System.Windows.Forms.Design.Editors/src/Misc/NativeMethods.cs index 2780d5b496f..d20dbd0185c 100644 --- a/src/System.Windows.Forms.Design.Editors/src/Misc/NativeMethods.cs +++ b/src/System.Windows.Forms.Design.Editors/src/Misc/NativeMethods.cs @@ -3962,8 +3962,8 @@ public static int SignedHIWORD(int n) { int i = (short)((n >> 16) & 0xffff); - i = i << 16; - i = i >> 16; + i <<= 16; + i >>= 16; return i; } @@ -3972,8 +3972,8 @@ public static int SignedLOWORD(int n) { int i = (short)(n & 0xFFFF); - i = i << 16; - i = i >> 16; + i <<= 16; + i >>= 16; return i; } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/GlyphCollection.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/GlyphCollection.cs index ed14a74fb10..b33f930f0d9 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/GlyphCollection.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/GlyphCollection.cs @@ -57,7 +57,7 @@ public int Add(Glyph value) /// public void AddRange(Glyph[] value) { - for (int i = 0; i < value.Length; i = i + 1) + for (int i = 0; i < value.Length; i += 1) { Add(value[i]); } @@ -68,7 +68,7 @@ public void AddRange(Glyph[] value) /// public void AddRange(GlyphCollection value) { - for (int i = 0; i < value.Count; i = i + 1) + for (int i = 0; i < value.Count; i += 1) { Add(value[i]); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs index 94b6eb68b2c..d3d96a69503 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs @@ -311,7 +311,7 @@ protected override CreateParams CreateParams CreateParams cp = base.CreateParams; if (axState[fOwnWindow] && IsUserMode()) { - cp.Style = cp.Style & (~NativeMethods.WS_VISIBLE); + cp.Style &= (~NativeMethods.WS_VISIBLE); } return cp; } @@ -5968,7 +5968,7 @@ internal UnsafeNativeMethods.IEnumUnknown EnumControls(Control ctl, int dwOleCon // Note that visual basic actually ignores the next/prev flags... we will not bool onlyNext = (dwWhich & NativeMethods.ActiveX.GC_WCH_FONLYNEXT) != 0; bool onlyPrev = (dwWhich & NativeMethods.ActiveX.GC_WCH_FONLYPREV) != 0; - dwWhich = dwWhich & ~(NativeMethods.ActiveX.GC_WCH_FSELECTED | NativeMethods.ActiveX.GC_WCH_FREVERSEDIR | + dwWhich &= ~(NativeMethods.ActiveX.GC_WCH_FSELECTED | NativeMethods.ActiveX.GC_WCH_FREVERSEDIR | NativeMethods.ActiveX.GC_WCH_FONLYNEXT | NativeMethods.ActiveX.GC_WCH_FONLYPREV); if (onlyNext && onlyPrev) { @@ -7434,7 +7434,7 @@ private void InitializeFromStream(Stream ids) for (int skipUnits = br.ReadInt32(); skipUnits > 0; skipUnits--) { int len = br.ReadInt32(); - ids.Position = ids.Position + len; + ids.Position += len; } length = br.ReadInt32(); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs index 76f4dd5bb2d..056f28705f3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs @@ -5429,7 +5429,7 @@ private void ColAutoResize(int col) } else { - rightArea.Width = rightArea.Width - left; + rightArea.Width -= left; } Invalidate(rightArea); @@ -8884,7 +8884,7 @@ protected bool ProcessGridKey(KeyEventArgs ke) return true; } ResetSelection(); - CurrentRow = CurrentRow - 1; + CurrentRow -= 1; Edit(); Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); break; @@ -8980,7 +8980,7 @@ protected bool ProcessGridKey(KeyEventArgs ke) } ResetSelection(); Edit(); - CurrentRow = CurrentRow + 1; + CurrentRow += 1; Debug.Assert(ListManager.Position == CurrentCell.RowNumber || listManager.Count == 0, "current row out of ssync with DataSource"); break; case Keys.OemMinus: @@ -9119,7 +9119,7 @@ protected bool ProcessGridKey(KeyEventArgs ke) if (currentCol == firstColumnMarkedVisible && currentRow != 0) { - CurrentRow = CurrentRow - 1; + CurrentRow -= 1; int newCol = MoveLeftRight(myGridTable.GridColumnStyles, myGridTable.GridColumnStyles.Count, false); Debug.Assert(newCol != -1, "there should be at least a visible column, right?"); CurrentColumn = newCol; @@ -9136,7 +9136,7 @@ protected bool ProcessGridKey(KeyEventArgs ke) else { // go to the previous row: - CurrentRow = CurrentRow - 1; + CurrentRow -= 1; CurrentColumn = lastColumnMarkedVisible; } } @@ -9158,7 +9158,7 @@ protected bool ProcessGridKey(KeyEventArgs ke) if (currentCol == lastColumnMarkedVisible && currentRow != DataGridRowsLength - 1) { - CurrentRow = CurrentRow + 1; + CurrentRow += 1; // navigate to the first visible column CurrentColumn = firstColumnMarkedVisible; } @@ -9594,7 +9594,7 @@ protected bool ProcessTabKey(Keys keyData) CurrentColumn = firstColumnMarkedVisible; } - CurrentRow = CurrentRow + 1; + CurrentRow += 1; } else { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FileDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FileDialog.cs index 925018e3f37..98cca5f2724 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FileDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FileDialog.cs @@ -447,7 +447,7 @@ private string[] GetMultiselectFiles(UnsafeNativeMethods.CharBuffer charBuffer) if (directory[directory.Length - 1] != '\\') { - directory = directory + "\\"; + directory += "\\"; } ArrayList names = new ArrayList(); do diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElementCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElementCollection.cs index ca34ccfbeeb..ab957355dd7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElementCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/ArrangedElementCollection.cs @@ -108,8 +108,8 @@ private static void Copy(ArrangedElementCollection sourceList, int sourceIndex, // We need to copy from the back forward to prevent overwrite if source and // destination lists are the same, so we need to flip the source/dest indices // to point at the end of the spans to be copied. - sourceIndex = sourceIndex + length; - destinationIndex = destinationIndex + length; + sourceIndex += length; + destinationIndex += length; for (; length > 0; length--) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutUtils.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutUtils.cs index 43025e19ae3..5ce9e822c7d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutUtils.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/LayoutUtils.cs @@ -182,7 +182,7 @@ private static AnchorStyles GetOppositeAnchor(AnchorStyles anchor) // iterate through T,B,L,R // bitwise or B,T,R,L as appropriate - for (int i = 1; i <= (int)AnchorStyles.Right; i = i << 1) + for (int i = 1; i <= (int)AnchorStyles.Right; i <<= 1) { switch (anchor & (AnchorStyles)i) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingHelper.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingHelper.cs index b697e019569..76690f7e28a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingHelper.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListBindingHelper.cs @@ -381,7 +381,7 @@ private static PropertyDescriptorCollection GetListItemPropertiesByType(Type typ // GetListItemProperties(PDForOrders.PropertyType) // this returns the shape of Orders not Array // If there are more listAccessors, then we'll call // GetListItemProperties(PDForOrders.PropertyType, listAccessors, startIndex++) - startIndex = startIndex + 1; + startIndex += 1; if (startIndex >= listAccessors.Length) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs index a00a5d99f5d..27f341415a6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs @@ -2711,7 +2711,7 @@ public void Clear() public static int CreateMask() { int mask = lastMask; - lastMask = lastMask << 1; + lastMask <<= 1; Debug.Assert(lastMask > mask, "We have overflowed our state mask."); return mask; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TextBox.cs index 7daf52cdac3..9f7873b0afe 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TextBox.cs @@ -940,15 +940,15 @@ private void DrawPlaceholderText(Graphics graphics) switch (TextAlign) { case HorizontalAlignment.Center: - flags = flags | TextFormatFlags.HorizontalCenter; + flags |= TextFormatFlags.HorizontalCenter; rectangle.Offset(0, 1); break; case HorizontalAlignment.Left: - flags = flags | TextFormatFlags.Right; + flags |= TextFormatFlags.Right; rectangle.Offset(1, 1); break; case HorizontalAlignment.Right: - flags = flags | TextFormatFlags.Left; + flags |= TextFormatFlags.Left; rectangle.Offset(0, 1); break; } @@ -959,15 +959,15 @@ private void DrawPlaceholderText(Graphics graphics) switch (TextAlign) { case HorizontalAlignment.Center: - flags = flags | TextFormatFlags.HorizontalCenter; + flags |= TextFormatFlags.HorizontalCenter; rectangle.Offset(0, 1); break; case HorizontalAlignment.Left: - flags = flags | TextFormatFlags.Left; + flags |= TextFormatFlags.Left; rectangle.Offset(1, 1); break; case HorizontalAlignment.Right: - flags = flags | TextFormatFlags.Right; + flags |= TextFormatFlags.Right; rectangle.Offset(0, 1); break; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ThreadExceptionDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ThreadExceptionDialog.cs index 9fb30f79d17..73ebc6fb022 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ThreadExceptionDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ThreadExceptionDialog.cs @@ -411,7 +411,7 @@ private void DetailsClick(object sender, EventArgs eventargs) delta = -delta; } - Height = Height + delta; + Height += delta; detailsVisible = !detailsVisible; details.Visible = detailsVisible; detailsButton.Image = detailsVisible ? collapseImage : expandImage; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs index e4f83c60036..f55431f8299 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs @@ -748,7 +748,7 @@ internal int PreferredHeight // if (Wrappable && IsHandleCreated) { - height = height * unchecked((int)(long)SendMessage(NativeMethods.TB_GETROWS, 0, 0)); + height *= unchecked((int)(long)SendMessage(NativeMethods.TB_GETROWS, 0, 0)); } height = (height > 0) ? height : 1; diff --git a/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics2.cs b/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics2.cs index 939447386a4..b56cb1b16b7 100644 --- a/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics2.cs +++ b/src/System.Windows.Forms/src/misc/GDI/WindowsGraphics2.cs @@ -245,11 +245,11 @@ public void DrawText(string text, WindowsFont font, Rectangle bounds, Color fore // Adjust unbounded rect to avoid overflow since Rectangle ctr does not do param validation. if (bounds.Width == MaxSize.Width) { - bounds.Width = bounds.Width - bounds.X; + bounds.Width -= bounds.X; } if (bounds.Height == MaxSize.Height) { - bounds.Height = bounds.Height - bounds.Y; + bounds.Height -= bounds.Y; } IntNativeMethods.RECT rect = new IntNativeMethods.RECT(bounds); From b0ed52f52c2381b888ba4ac1fdb440afd95c9604 Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Fri, 24 May 2019 13:10:18 -0700 Subject: [PATCH 26/27] remove all instances of IDE1005 warning - Delegate invocation can be simplified --- .../Forms/Design/Behavior/BehaviorService.cs | 10 +- .../src/System/Windows/Forms/Application.cs | 10 +- .../Windows/Forms/ApplicationContext.cs | 5 +- .../Forms/AutoCompleteStringCollection.cs | 5 +- .../src/System/Windows/Forms/AxHost.cs | 5 +- .../System/Windows/Forms/BindingNavigator.cs | 5 +- .../src/System/Windows/Forms/CheckBox.cs | 16 +- .../System/Windows/Forms/CheckedListBox.cs | 5 +- .../src/System/Windows/Forms/ComboBox.cs | 54 +--- .../COM2Interop/COM2Properties.cs | 5 +- .../COM2Interop/COM2PropertyDescriptor.cs | 36 +-- .../System/Windows/Forms/ContainerControl.cs | 5 +- .../src/System/Windows/Forms/ContextMenu.cs | 10 +- .../src/System/Windows/Forms/Control.cs | 292 +++--------------- .../System/Windows/Forms/CurrencyManager.cs | 20 +- .../src/System/Windows/Forms/DataGrid.cs | 36 +-- .../System/Windows/Forms/DataGridCaption.cs | 18 +- .../Windows/Forms/DataGridColumnCollection.cs | 5 +- .../Windows/Forms/DataGridTableCollection.cs | 5 +- .../Forms/DataGridViewCellCollection.cs | 5 +- .../Windows/Forms/DataGridViewColumn.cs | 5 +- .../Forms/DataGridViewColumnCollection.cs | 5 +- .../Forms/DataGridViewRowCollection.cs | 5 +- .../System/Windows/Forms/DateTimePicker.cs | 20 +- .../src/System/Windows/Forms/DomainUpDown.cs | 5 +- .../src/System/Windows/Forms/ErrorProvider.cs | 5 +- .../src/System/Windows/Forms/FontDialog.cs | 6 +- .../src/System/Windows/Forms/Form.cs | 84 +---- .../Windows/Forms/HtmlToClrEventProxy.cs | 5 +- .../src/System/Windows/Forms/ImageList.cs | 10 +- .../src/System/Windows/Forms/LinkLabel.cs | 6 +- .../src/System/Windows/Forms/ListBox.cs | 18 +- .../src/System/Windows/Forms/ListView.cs | 112 ++----- .../src/System/Windows/Forms/MainMenu.cs | 5 +- .../src/System/Windows/Forms/MenuItem.cs | 20 +- .../src/System/Windows/Forms/MenuStrip.cs | 14 +- .../src/System/Windows/Forms/MonthCalendar.cs | 15 +- .../src/System/Windows/Forms/NotifyIcon.cs | 60 +--- .../src/System/Windows/Forms/NumericUpDown.cs | 5 +- .../src/System/Windows/Forms/PictureBox.cs | 12 +- .../src/System/Windows/Forms/ProgressBar.cs | 5 +- .../src/System/Windows/Forms/PropertyGrid.cs | 37 +-- .../src/System/Windows/Forms/RadioButton.cs | 6 +- .../src/System/Windows/Forms/RichTextBox.cs | 42 +-- .../System/Windows/Forms/ScrollableControl.cs | 12 +- .../System/Windows/Forms/SplitContainer.cs | 12 +- .../src/System/Windows/Forms/Splitter.cs | 12 +- .../src/System/Windows/Forms/StatusBar.cs | 12 +- .../src/System/Windows/Forms/TabControl.cs | 34 +- .../System/Windows/Forms/TableLayoutPanel.cs | 6 +- .../src/System/Windows/Forms/ToolBar.cs | 10 +- .../src/System/Windows/Forms/ToolStrip.cs | 62 +--- .../System/Windows/Forms/ToolStripButton.cs | 12 +- .../Windows/Forms/ToolStripContentPanel.cs | 12 +- .../Windows/Forms/ToolStripControlHost.cs | 6 +- .../System/Windows/Forms/ToolStripDropDown.cs | 27 +- .../Windows/Forms/ToolStripDropDownItem.cs | 30 +- .../src/System/Windows/Forms/ToolStripItem.cs | 54 +--- .../System/Windows/Forms/ToolStripManager.cs | 14 +- .../System/Windows/Forms/ToolStripMenuItem.cs | 12 +- .../System/Windows/Forms/ToolStripPanel.cs | 6 +- .../Forms/ToolStripRendererSwitcher.cs | 5 +- .../Windows/Forms/ToolStripSplitButton.cs | 16 +- .../src/System/Windows/Forms/ToolTip.cs | 10 +- .../src/System/Windows/Forms/TrackBar.cs | 12 +- .../src/System/Windows/Forms/TreeView.cs | 80 +---- .../src/System/Windows/Forms/UpDownBase.cs | 5 +- .../src/System/Windows/Forms/UserControl.cs | 6 +- .../src/System/Windows/Forms/WebBrowser.cs | 55 +--- .../src/System/Windows/Forms/control.ime.cs | 6 +- src/System.Windows.Forms/src/misc/DbgUtil.cs | 2 +- .../src/misc/GDI/DeviceContext.cs | 5 +- 72 files changed, 282 insertions(+), 1312 deletions(-) diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs index 973db31e190..c63c5e077cb 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/Behavior/BehaviorService.cs @@ -318,10 +318,7 @@ private void OnEndDrag(BehaviorDragDropEventArgs e) private void OnBeginDrag(BehaviorDragDropEventArgs e) { - if (_beginDragHandler != null) - { - _beginDragHandler(this, e); - } + _beginDragHandler?.Invoke(this, e); } /// @@ -483,10 +480,7 @@ public void Invalidate(Region r) /// public void SyncSelection() { - if (_synchronizeEventHandler != null) - { - _synchronizeEventHandler(this, EventArgs.Empty); - } + _synchronizeEventHandler?.Invoke(this, EventArgs.Empty); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs index 707c4ec40e8..e3adce0b9d6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Application.cs @@ -1381,10 +1381,7 @@ internal static void UnparkHandle(HandleRef handle, DpiAwarenessContext context) public static void RaiseIdle(EventArgs e) { ThreadContext current = ThreadContext.FromCurrent(); - if (current.idleHandler != null) - { - current.idleHandler(Thread.CurrentThread, e); - } + current.idleHandler?.Invoke(Thread.CurrentThread, e); } /// @@ -4004,10 +4001,7 @@ void UnsafeNativeMethods.IMsoComponent.OnActivationChange(UnsafeNativeMethods.IM /// bool UnsafeNativeMethods.IMsoComponent.FDoIdle(int grfidlef) { - if (idleHandler != null) - { - idleHandler(Thread.CurrentThread, EventArgs.Empty); - } + idleHandler?.Invoke(Thread.CurrentThread, EventArgs.Empty); return false; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ApplicationContext.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ApplicationContext.cs index dfb35085327..30b334850a5 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ApplicationContext.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ApplicationContext.cs @@ -137,10 +137,7 @@ public void ExitThread() /// protected virtual void ExitThreadCore() { - if (ThreadExit != null) - { - ThreadExit(this, EventArgs.Empty); - } + ThreadExit?.Invoke(this, EventArgs.Empty); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AutoCompleteStringCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AutoCompleteStringCollection.cs index f1c6e580e67..0a59b2f0bc9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AutoCompleteStringCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AutoCompleteStringCollection.cs @@ -78,10 +78,7 @@ public event CollectionChangeEventHandler CollectionChanged protected void OnCollectionChanged(CollectionChangeEventArgs e) { - if (onCollectionChanged != null) - { - onCollectionChanged(this, e); - } + onCollectionChanged?.Invoke(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs index d3d96a69503..f85d6f412e2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/AxHost.cs @@ -653,10 +653,7 @@ private int NoComponentChangeEvents /// public void ShowAboutBox() { - if (aboutBoxDelegate != null) - { - aboutBoxDelegate(); - } + aboutBoxDelegate?.Invoke(); } // diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs b/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs index 9c484fd1d2f..cf6384375dc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/BindingNavigator.cs @@ -617,10 +617,7 @@ protected virtual void OnRefreshItems() RefreshItemsCore(); // Raise the public event - if (onRefreshItems != null) - { - onRefreshItems(this, EventArgs.Empty); - } + onRefreshItems?.Invoke(this, EventArgs.Empty); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/CheckBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/CheckBox.cs index 4f537a33280..842d1288e2e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/CheckBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/CheckBox.cs @@ -547,13 +547,7 @@ protected virtual void OnCheckedChanged(EventArgs e) if (FlatStyle == FlatStyle.System) { AccessibilityNotifyClients(AccessibleEvents.SystemCaptureEnd, -1); - } - - EventHandler handler = (EventHandler)Events[EVENT_CHECKEDCHANGED]; - if (handler != null) - { - handler(this, e); - } + } ((EventHandler)Events[EVENT_CHECKEDCHANGED])?.Invoke(this, e); } /// @@ -564,13 +558,7 @@ protected virtual void OnCheckStateChanged(EventArgs e) if (OwnerDraw) { Refresh(); - } - - EventHandler handler = (EventHandler)Events[EVENT_CHECKSTATECHANGED]; - if (handler != null) - { - handler(this, e); - } + } ((EventHandler)Events[EVENT_CHECKSTATECHANGED])?.Invoke(this, e); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/CheckedListBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/CheckedListBox.cs index fa6716ce8b3..22b79b12039 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/CheckedListBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/CheckedListBox.cs @@ -926,10 +926,7 @@ protected override void OnKeyPress(KeyPressEventArgs e) /// protected virtual void OnItemCheck(ItemCheckEventArgs ice) { - if (onItemCheck != null) - { - onItemCheck(this, ice); - } + onItemCheck?.Invoke(this, ice); } protected override void OnMeasureItem(MeasureItemEventArgs e) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs index 21fb50bd8b8..da83bd667c0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComboBox.cs @@ -2696,11 +2696,7 @@ protected override void OnHandleDestroyed(EventArgs e) /// protected virtual void OnDrawItem(DrawItemEventArgs e) { - DrawItemEventHandler handler = (DrawItemEventHandler)Events[EVENT_DRAWITEM]; - if (handler != null) - { - handler(this, e); - } + ((DrawItemEventHandler)Events[EVENT_DRAWITEM])?.Invoke(this, e); } /// @@ -2710,11 +2706,7 @@ protected virtual void OnDrawItem(DrawItemEventArgs e) /// protected virtual void OnDropDown(EventArgs e) { - EventHandler handler = (EventHandler)Events[EVENT_DROPDOWN]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_DROPDOWN])?.Invoke(this, e); // Notify collapsed/expanded property change. AccessibilityObject.RaiseAutomationPropertyChangedEvent( @@ -2790,11 +2782,7 @@ protected override void OnKeyPress(KeyPressEventArgs e) /// protected virtual void OnMeasureItem(MeasureItemEventArgs e) { - MeasureItemEventHandler handler = (MeasureItemEventHandler)Events[EVENT_MEASUREITEM]; - if (handler != null) - { - handler(this, e); - } + ((MeasureItemEventHandler)Events[EVENT_MEASUREITEM])?.Invoke(this, e); } /// @@ -2842,11 +2830,7 @@ private void OnSelectionChangeCommittedInternal(EventArgs e) /// protected virtual void OnSelectionChangeCommitted(EventArgs e) { - EventHandler handler = (EventHandler)Events[EVENT_SELECTIONCHANGECOMMITTED]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_SELECTIONCHANGECOMMITTED])?.Invoke(this, e); // The user selects a list item or selects an item and then closes the list. // It indicates that the user's selection is to be processed but should not @@ -2865,11 +2849,7 @@ protected virtual void OnSelectionChangeCommitted(EventArgs e) protected override void OnSelectedIndexChanged(EventArgs e) { base.OnSelectedIndexChanged(e); - EventHandler handler = (EventHandler)Events[EVENT_SELECTEDINDEXCHANGED]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_SELECTEDINDEXCHANGED])?.Invoke(this, e); if (dropDownWillBeClosed) { @@ -2927,11 +2907,7 @@ protected override void OnSelectedValueChanged(EventArgs e) /// protected virtual void OnSelectedItemChanged(EventArgs e) { - EventHandler handler = (EventHandler)Events[EVENT_SELECTEDITEMCHANGED]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_SELECTEDITEMCHANGED])?.Invoke(this, e); } /// @@ -2939,11 +2915,7 @@ protected virtual void OnSelectedItemChanged(EventArgs e) /// protected virtual void OnDropDownStyleChanged(EventArgs e) { - EventHandler handler = (EventHandler)Events[EVENT_DROPDOWNSTYLE]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_DROPDOWNSTYLE])?.Invoke(this, e); } /// @@ -3162,11 +3134,7 @@ protected override void OnDisplayMemberChanged(EventArgs e) /// protected virtual void OnDropDownClosed(EventArgs e) { - EventHandler handler = (EventHandler)Events[EVENT_DROPDOWNCLOSED]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_DROPDOWNCLOSED])?.Invoke(this, e); // Need to announce the focus on combo-box with new selected value on drop-down close. // If do not do this focus in Level 3 stays on list item of unvisible list. @@ -3193,11 +3161,7 @@ protected virtual void OnDropDownClosed(EventArgs e) /// protected virtual void OnTextUpdate(EventArgs e) { - EventHandler handler = (EventHandler)Events[EVENT_TEXTUPDATE]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_TEXTUPDATE])?.Invoke(this, e); } protected override bool ProcessCmdKey(ref Message msg, Keys keyData) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Properties.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Properties.cs index dd01c708238..5dd2bf77d33 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Properties.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2Properties.cs @@ -338,11 +338,8 @@ public void Dispose() if (props != null) { - if (Disposed != null) - { - Disposed(this, EventArgs.Empty); - } + Disposed?.Invoke(this, EventArgs.Empty); weakObjRef = null; props = null; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs index d9ca8d36442..18dfb89c20a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ComponentModel/COM2Interop/COM2PropertyDescriptor.cs @@ -1090,11 +1090,7 @@ protected void OnGetBaseAttributes(GetAttributesEvent e) { com2props.AlwaysValid = com2props.CheckValid(); - GetAttributesEventHandler handler = (GetAttributesEventHandler)Events[EventGetBaseAttributes]; - if (handler != null) - { - handler(this, e); - } + ((GetAttributesEventHandler)Events[EventGetBaseAttributes])?.Invoke(this, e); } finally { @@ -1127,11 +1123,7 @@ protected void OnGetDynamicAttributes(GetAttributesEvent e) try { com2props.AlwaysValid = com2props.CheckValid(); - GetAttributesEventHandler handler = (GetAttributesEventHandler)Events[EventGetDynamicAttributes]; - if (handler != null) - { - handler(this, e); - } + ((GetAttributesEventHandler)Events[EventGetDynamicAttributes])?.Invoke(this, e); } finally { @@ -1152,11 +1144,7 @@ protected void OnGetTypeConverterAndTypeEditor(GetTypeConverterAndTypeEditorEven try { com2props.AlwaysValid = com2props.CheckValid(); - GetTypeConverterAndTypeEditorEventHandler handler = (GetTypeConverterAndTypeEditorEventHandler)Events[EventGetTypeConverterAndTypeEditor]; - if (handler != null) - { - handler(this, e); - } + ((GetTypeConverterAndTypeEditorEventHandler)Events[EventGetTypeConverterAndTypeEditor])?.Invoke(this, e); } finally { @@ -1197,11 +1185,7 @@ private void RaiseGetBoolValueEvent(object key, GetBoolValueEvent e) try { com2props.AlwaysValid = com2props.CheckValid(); - GetBoolValueEventHandler handler = (GetBoolValueEventHandler)Events[key]; - if (handler != null) - { - handler(this, e); - } + ((GetBoolValueEventHandler)Events[key])?.Invoke(this, e); } finally { @@ -1217,11 +1201,7 @@ private void RaiseCom2Event(object key, EventArgs e) try { com2props.AlwaysValid = com2props.CheckValid(); - Com2EventHandler handler = (Com2EventHandler)Events[key]; - if (handler != null) - { - handler(this, e); - } + ((Com2EventHandler)Events[key])?.Invoke(this, e); } finally { @@ -1237,11 +1217,7 @@ private void RaiseGetNameItemEvent(object key, GetNameItemEvent e) try { com2props.AlwaysValid = com2props.CheckValid(); - GetNameItemEventHandler handler = (GetNameItemEventHandler)Events[key]; - if (handler != null) - { - handler(this, e); - } + ((GetNameItemEventHandler)Events[key])?.Invoke(this, e); } finally { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs index 44d6fa10bac..eefec0667fe 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs @@ -849,10 +849,7 @@ internal virtual void OnAutoScaleModeChanged() /// protected virtual void OnAutoValidateChanged(EventArgs e) { - if (autoValidateChanged != null) - { - autoValidateChanged(this, e); - } + autoValidateChanged?.Invoke(this, e); } internal override void OnFrameWindowActivate(bool fActivate) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenu.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenu.cs index a913172e9f8..05ab1bd655e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenu.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ContextMenu.cs @@ -140,10 +140,7 @@ internal override bool RenderIsRightToLeft /// protected internal virtual void OnPopup(EventArgs e) { - if (onPopup != null) - { - onPopup(this, e); - } + onPopup?.Invoke(this, e); } /// @@ -151,10 +148,7 @@ protected internal virtual void OnPopup(EventArgs e) /// protected internal virtual void OnCollapse(EventArgs e) { - if (onCollapse != null) - { - onCollapse(this, e); - } + onCollapse?.Invoke(this, e); } /// 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 088b0ea0590..3b7bdb5160c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs @@ -6523,11 +6523,7 @@ protected bool GetTopLevel() /// internal void RaiseCreateHandleEvent(EventArgs e) { - EventHandler handler = (EventHandler)Events[EventHandleCreated]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventHandleCreated])?.Invoke(this, e); } /// @@ -6537,11 +6533,7 @@ internal void RaiseCreateHandleEvent(EventArgs e) [EditorBrowsable(EditorBrowsableState.Advanced)] protected void RaiseKeyEvent(object key, KeyEventArgs e) { - KeyEventHandler handler = (KeyEventHandler)Events[key]; - if (handler != null) - { - handler(this, e); - } + ((KeyEventHandler)Events[key])?.Invoke(this, e); } /// @@ -6551,11 +6543,7 @@ protected void RaiseKeyEvent(object key, KeyEventArgs e) [EditorBrowsable(EditorBrowsableState.Advanced)] protected void RaiseMouseEvent(object key, MouseEventArgs e) { - MouseEventHandler handler = (MouseEventHandler)Events[key]; - if (handler != null) - { - handler(this, e); - } + ((MouseEventHandler)Events[key])?.Invoke(this, e); } /// @@ -8996,11 +8984,7 @@ protected virtual void OnParentChanged(EventArgs e) protected virtual void OnClick(EventArgs e) { Contract.Requires(e != null); - EventHandler handler = (EventHandler)Events[EventClick]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventClick])?.Invoke(this, e); } [EditorBrowsable(EditorBrowsableState.Advanced)] @@ -9020,11 +9004,7 @@ protected virtual void OnClientSizeChanged(EventArgs e) protected virtual void OnControlAdded(ControlEventArgs e) { Contract.Requires(e != null); - ControlEventHandler handler = (ControlEventHandler)Events[EventControlAdded]; - if (handler != null) - { - handler(this, e); - } + ((ControlEventHandler)Events[EventControlAdded])?.Invoke(this, e); } /// @@ -9034,11 +9014,7 @@ protected virtual void OnControlAdded(ControlEventArgs e) protected virtual void OnControlRemoved(ControlEventArgs e) { Contract.Requires(e != null); - ControlEventHandler handler = (ControlEventHandler)Events[EventControlRemoved]; - if (handler != null) - { - handler(this, e); - } + ((ControlEventHandler)Events[EventControlRemoved])?.Invoke(this, e); } /// @@ -9139,13 +9115,7 @@ protected virtual void OnHandleCreated(EventArgs e) { ListenToUserPreferenceChanged(GetTopLevel()); } - } - - EventHandler handler = (EventHandler)Events[EventHandleCreated]; - if (handler != null) - { - handler(this, e); - } + } ((EventHandler)Events[EventHandleCreated])?.Invoke(this, e); if (IsHandleCreated) { @@ -9206,11 +9176,7 @@ protected virtual void OnLocationChanged(EventArgs e) protected virtual void OnHandleDestroyed(EventArgs e) { Contract.Requires(e != null); - EventHandler handler = (EventHandler)Events[EventHandleDestroyed]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventHandleDestroyed])?.Invoke(this, e); UpdateReflectParent(false); @@ -9270,11 +9236,7 @@ protected virtual void OnHandleDestroyed(EventArgs e) protected virtual void OnDoubleClick(EventArgs e) { Contract.Requires(e != null); - EventHandler handler = (EventHandler)Events[EventDoubleClick]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventDoubleClick])?.Invoke(this, e); } /// @@ -9290,11 +9252,7 @@ protected virtual void OnDoubleClick(EventArgs e) protected virtual void OnDragEnter(DragEventArgs drgevent) { Contract.Requires(drgevent != null); - DragEventHandler handler = (DragEventHandler)Events[EventDragEnter]; - if (handler != null) - { - handler(this, drgevent); - } + ((DragEventHandler)Events[EventDragEnter])?.Invoke(this, drgevent); } /// @@ -9305,11 +9263,7 @@ protected virtual void OnDragEnter(DragEventArgs drgevent) protected virtual void OnDragOver(DragEventArgs drgevent) { Contract.Requires(drgevent != null); - DragEventHandler handler = (DragEventHandler)Events[EventDragOver]; - if (handler != null) - { - handler(this, drgevent); - } + ((DragEventHandler)Events[EventDragOver])?.Invoke(this, drgevent); } /// @@ -9320,11 +9274,7 @@ protected virtual void OnDragOver(DragEventArgs drgevent) protected virtual void OnDragLeave(EventArgs e) { Contract.Requires(e != null); - EventHandler handler = (EventHandler)Events[EventDragLeave]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventDragLeave])?.Invoke(this, e); } /// @@ -9335,11 +9285,7 @@ protected virtual void OnDragLeave(EventArgs e) protected virtual void OnDragDrop(DragEventArgs drgevent) { Contract.Requires(drgevent != null); - DragEventHandler handler = (DragEventHandler)Events[EventDragDrop]; - if (handler != null) - { - handler(this, drgevent); - } + ((DragEventHandler)Events[EventDragDrop])?.Invoke(this, drgevent); } /// @@ -9351,22 +9297,14 @@ protected virtual void OnDragDrop(DragEventArgs drgevent) protected virtual void OnGiveFeedback(GiveFeedbackEventArgs gfbevent) { Contract.Requires(gfbevent != null); - GiveFeedbackEventHandler handler = (GiveFeedbackEventHandler)Events[EventGiveFeedback]; - if (handler != null) - { - handler(this, gfbevent); - } + ((GiveFeedbackEventHandler)Events[EventGiveFeedback])?.Invoke(this, gfbevent); } [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnEnter(EventArgs e) { Contract.Requires(e != null); - EventHandler handler = (EventHandler)Events[EventEnter]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventEnter])?.Invoke(this, e); } /// @@ -9397,13 +9335,7 @@ protected virtual void OnGotFocus(EventArgs e) if (parent != null) { parent.ChildGotFocus(this); - } - - EventHandler handler = (EventHandler)Events[EventGotFocus]; - if (handler != null) - { - handler(this, e); - } + } ((EventHandler)Events[EventGotFocus])?.Invoke(this, e); } /// @@ -9456,13 +9388,7 @@ protected virtual void OnInvalidated(InvalidateEventArgs e) { controls[i].OnParentInvalidated(e); } - } - - InvalidateEventHandler handler = (InvalidateEventHandler)Events[EventInvalidated]; - if (handler != null) - { - handler(this, e); - } + } ((InvalidateEventHandler)Events[EventInvalidated])?.Invoke(this, e); } /// @@ -9472,11 +9398,7 @@ protected virtual void OnInvalidated(InvalidateEventArgs e) protected virtual void OnKeyDown(KeyEventArgs e) { Contract.Requires(e != null); - KeyEventHandler handler = (KeyEventHandler)Events[EventKeyDown]; - if (handler != null) - { - handler(this, e); - } + ((KeyEventHandler)Events[EventKeyDown])?.Invoke(this, e); } /// @@ -9486,11 +9408,7 @@ protected virtual void OnKeyDown(KeyEventArgs e) protected virtual void OnKeyPress(KeyPressEventArgs e) { Contract.Requires(e != null); - KeyPressEventHandler handler = (KeyPressEventHandler)Events[EventKeyPress]; - if (handler != null) - { - handler(this, e); - } + ((KeyPressEventHandler)Events[EventKeyPress])?.Invoke(this, e); } /// @@ -9500,11 +9418,7 @@ protected virtual void OnKeyPress(KeyPressEventArgs e) protected virtual void OnKeyUp(KeyEventArgs e) { Contract.Requires(e != null); - KeyEventHandler handler = (KeyEventHandler)Events[EventKeyUp]; - if (handler != null) - { - handler(this, e); - } + ((KeyEventHandler)Events[EventKeyUp])?.Invoke(this, e); } /// @@ -9522,12 +9436,7 @@ protected virtual void OnLayout(LayoutEventArgs levent) if (IsActiveX) { ActiveXViewChanged(); - } - LayoutEventHandler handler = (LayoutEventHandler)Events[EventLayout]; - if (handler != null) - { - handler(this, levent); - } + } ((LayoutEventHandler)Events[EventLayout])?.Invoke(this, levent); bool parentRequiresLayout = LayoutEngine.Layout(this, levent); @@ -9566,11 +9475,7 @@ internal virtual void OnLayoutSuspended() protected virtual void OnLeave(EventArgs e) { Contract.Requires(e != null); - EventHandler handler = (EventHandler)Events[EventLeave]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventLeave])?.Invoke(this, e); } [EditorBrowsable(EditorBrowsableState.Advanced)] @@ -9593,23 +9498,13 @@ protected virtual void OnLostFocus(EventArgs e) if (IsActiveX) { ActiveXOnFocus(false); - } - - EventHandler handler = (EventHandler)Events[EventLostFocus]; - if (handler != null) - { - handler(this, e); - } + } ((EventHandler)Events[EventLostFocus])?.Invoke(this, e); } protected virtual void OnMarginChanged(EventArgs e) { Contract.Requires(e != null); - EventHandler handler = (EventHandler)Events[EventMarginChanged]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventMarginChanged])?.Invoke(this, e); } /// @@ -9619,11 +9514,7 @@ protected virtual void OnMarginChanged(EventArgs e) protected virtual void OnMouseDoubleClick(MouseEventArgs e) { Contract.Requires(e != null); - MouseEventHandler handler = (MouseEventHandler)Events[EventMouseDoubleClick]; - if (handler != null) - { - handler(this, e); - } + ((MouseEventHandler)Events[EventMouseDoubleClick])?.Invoke(this, e); } /// @@ -9633,11 +9524,7 @@ protected virtual void OnMouseDoubleClick(MouseEventArgs e) protected virtual void OnMouseClick(MouseEventArgs e) { Contract.Requires(e != null); - MouseEventHandler handler = (MouseEventHandler)Events[EventMouseClick]; - if (handler != null) - { - handler(this, e); - } + ((MouseEventHandler)Events[EventMouseClick])?.Invoke(this, e); } /// @@ -9647,11 +9534,7 @@ protected virtual void OnMouseClick(MouseEventArgs e) protected virtual void OnMouseCaptureChanged(EventArgs e) { Contract.Requires(e != null); - EventHandler handler = (EventHandler)Events[EventMouseCaptureChanged]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventMouseCaptureChanged])?.Invoke(this, e); } /// @@ -9661,11 +9544,7 @@ protected virtual void OnMouseCaptureChanged(EventArgs e) protected virtual void OnMouseDown(MouseEventArgs e) { Contract.Requires(e != null); - MouseEventHandler handler = (MouseEventHandler)Events[EventMouseDown]; - if (handler != null) - { - handler(this, e); - } + ((MouseEventHandler)Events[EventMouseDown])?.Invoke(this, e); } /// @@ -9675,11 +9554,7 @@ protected virtual void OnMouseDown(MouseEventArgs e) protected virtual void OnMouseEnter(EventArgs e) { Contract.Requires(e != null); - EventHandler handler = (EventHandler)Events[EventMouseEnter]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventMouseEnter])?.Invoke(this, e); } /// @@ -9689,11 +9564,7 @@ protected virtual void OnMouseEnter(EventArgs e) protected virtual void OnMouseLeave(EventArgs e) { Contract.Requires(e != null); - EventHandler handler = (EventHandler)Events[EventMouseLeave]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventMouseLeave])?.Invoke(this, e); } /// @@ -9739,11 +9610,7 @@ protected virtual void OnDpiChangedAfterParent(EventArgs e) protected virtual void OnMouseHover(EventArgs e) { Contract.Requires(e != null); - EventHandler handler = (EventHandler)Events[EventMouseHover]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventMouseHover])?.Invoke(this, e); } /// @@ -9753,11 +9620,7 @@ protected virtual void OnMouseHover(EventArgs e) protected virtual void OnMouseMove(MouseEventArgs e) { Contract.Requires(e != null); - MouseEventHandler handler = (MouseEventHandler)Events[EventMouseMove]; - if (handler != null) - { - handler(this, e); - } + ((MouseEventHandler)Events[EventMouseMove])?.Invoke(this, e); } /// @@ -9767,11 +9630,7 @@ protected virtual void OnMouseMove(MouseEventArgs e) protected virtual void OnMouseUp(MouseEventArgs e) { Contract.Requires(e != null); - MouseEventHandler handler = (MouseEventHandler)Events[EventMouseUp]; - if (handler != null) - { - handler(this, e); - } + ((MouseEventHandler)Events[EventMouseUp])?.Invoke(this, e); } /// @@ -9781,11 +9640,7 @@ protected virtual void OnMouseUp(MouseEventArgs e) protected virtual void OnMouseWheel(MouseEventArgs e) { Contract.Requires(e != null); - MouseEventHandler handler = (MouseEventHandler)Events[EventMouseWheel]; - if (handler != null) - { - handler(this, e); - } + ((MouseEventHandler)Events[EventMouseWheel])?.Invoke(this, e); } /// @@ -9795,11 +9650,7 @@ protected virtual void OnMouseWheel(MouseEventArgs e) protected virtual void OnMove(EventArgs e) { Contract.Requires(e != null); - EventHandler handler = (EventHandler)Events[EventMove]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventMove])?.Invoke(this, e); if (RenderTransparent) { @@ -9815,11 +9666,7 @@ protected virtual void OnMove(EventArgs e) protected virtual void OnPaint(PaintEventArgs e) { Contract.Requires(e != null); - PaintEventHandler handler = (PaintEventHandler)Events[EventPaint]; - if (handler != null) - { - handler(this, e); - } + ((PaintEventHandler)Events[EventPaint])?.Invoke(this, e); } protected virtual void OnPaddingChanged(EventArgs e) @@ -9828,12 +9675,7 @@ protected virtual void OnPaddingChanged(EventArgs e) if (GetStyle(ControlStyles.ResizeRedraw)) { Invalidate(); - } - EventHandler handler = (EventHandler)Events[EventPaddingChanged]; - if (handler != null) - { - handler(this, e); - } + } ((EventHandler)Events[EventPaddingChanged])?.Invoke(this, e); } /// @@ -9890,11 +9732,7 @@ private void OnParentInvalidated(InvalidateEventArgs e) protected virtual void OnQueryContinueDrag(QueryContinueDragEventArgs qcdevent) { Contract.Requires(qcdevent != null); - QueryContinueDragEventHandler handler = (QueryContinueDragEventHandler)Events[EventQueryContinueDrag]; - if (handler != null) - { - handler(this, qcdevent); - } + ((QueryContinueDragEventHandler)Events[EventQueryContinueDrag])?.Invoke(this, qcdevent); } /// @@ -9923,11 +9761,7 @@ protected virtual void OnResize(EventArgs e) Invalidate(); } LayoutTransaction.DoLayout(this, this, PropertyNames.Bounds); - EventHandler handler = (EventHandler)Events[EventResize]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventResize])?.Invoke(this, e); } /// @@ -9940,11 +9774,7 @@ protected virtual void OnResize(EventArgs e) protected virtual void OnPreviewKeyDown(PreviewKeyDownEventArgs e) { Contract.Requires(e != null); - PreviewKeyDownEventHandler handler = (PreviewKeyDownEventHandler)Events[EventPreviewKeyDown]; - if (handler != null) - { - handler(this, e); - } + ((PreviewKeyDownEventHandler)Events[EventPreviewKeyDown])?.Invoke(this, e); } [EditorBrowsable(EditorBrowsableState.Advanced)] @@ -9967,11 +9797,7 @@ protected virtual void OnSizeChanged(EventArgs e) protected virtual void OnChangeUICues(UICuesEventArgs e) { Contract.Requires(e != null); - UICuesEventHandler handler = (UICuesEventHandler)Events[EventChangeUICues]; - if (handler != null) - { - handler(this, e); - } + ((UICuesEventHandler)Events[EventChangeUICues])?.Invoke(this, e); } /// @@ -9982,11 +9808,7 @@ protected virtual void OnChangeUICues(UICuesEventArgs e) protected virtual void OnStyleChanged(EventArgs e) { Contract.Requires(e != null); - EventHandler handler = (EventHandler)Events[EventStyleChanged]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventStyleChanged])?.Invoke(this, e); } /// @@ -10010,11 +9832,7 @@ protected virtual void OnSystemColorsChanged(EventArgs e) } Invalidate(); - EventHandler handler = (EventHandler)Events[EventSystemColorsChanged]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventSystemColorsChanged])?.Invoke(this, e); } /// @@ -10025,11 +9843,7 @@ protected virtual void OnSystemColorsChanged(EventArgs e) protected virtual void OnValidating(CancelEventArgs e) { Contract.Requires(e != null); - CancelEventHandler handler = (CancelEventHandler)Events[EventValidating]; - if (handler != null) - { - handler(this, e); - } + ((CancelEventHandler)Events[EventValidating])?.Invoke(this, e); } /// @@ -10039,11 +9853,7 @@ protected virtual void OnValidating(CancelEventArgs e) protected virtual void OnValidated(EventArgs e) { Contract.Requires(e != null); - EventHandler handler = (EventHandler)Events[EventValidated]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventValidated])?.Invoke(this, e); } /// @@ -11280,11 +11090,7 @@ internal void ProcessUICues(ref Message msg) [EditorBrowsable(EditorBrowsableState.Advanced)] protected void RaiseDragEvent(object key, DragEventArgs e) { - DragEventHandler handler = (DragEventHandler)Events[key]; - if (handler != null) - { - handler(this, e); - } + ((DragEventHandler)Events[key])?.Invoke(this, e); } /// @@ -11294,11 +11100,7 @@ protected void RaiseDragEvent(object key, DragEventArgs e) [EditorBrowsable(EditorBrowsableState.Advanced)] protected void RaisePaintEvent(object key, PaintEventArgs e) { - PaintEventHandler handler = (PaintEventHandler)Events[EventPaint]; - if (handler != null) - { - handler(this, e); - } + ((PaintEventHandler)Events[EventPaint])?.Invoke(this, e); } private void RemovePendingMessages(int msgMin, int msgMax) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs index 9a8c21f39c7..09b0bab6327 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/CurrencyManager.cs @@ -975,10 +975,7 @@ protected virtual void OnItemChanged(ItemChangedEventArgs e) Debug.WriteLineIf(CompModSwitches.DataView.TraceVerbose, "OnItemChanged(" + e.Index.ToString(CultureInfo.InvariantCulture) + ") " + e.ToString()); try { - if (onItemChanged != null) - { - onItemChanged(this, e); - } + onItemChanged?.Invoke(this, e); } catch (Exception ex) { @@ -994,19 +991,13 @@ protected virtual void OnItemChanged(ItemChangedEventArgs e) private void OnListChanged(ListChangedEventArgs e) { - if (onListChanged != null) - { - onListChanged(this, e); - } + onListChanged?.Invoke(this, e); } [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] //Exists in Everett internal protected void OnMetaDataChanged(EventArgs e) { - if (onMetaDataChangedHandler != null) - { - onMetaDataChangedHandler(this, e); - } + onMetaDataChangedHandler?.Invoke(this, e); } /// @@ -1017,10 +1008,7 @@ protected virtual void OnPositionChanged(EventArgs e) Debug.WriteLineIf(CompModSwitches.DataView.TraceVerbose, "OnPositionChanged(" + listposition.ToString(CultureInfo.InvariantCulture) + ") " + e.ToString()); try { - if (onPositionChangedHandler != null) - { - onPositionChangedHandler(this, e); - } + onPositionChangedHandler?.Invoke(this, e); } catch (Exception ex) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs index 056f28705f3..b8bc9c5fcd9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGrid.cs @@ -3842,10 +3842,7 @@ protected virtual void OnReadOnlyChanged(EventArgs e) /// protected void OnNavigate(NavigateEventArgs e) { - if (onNavigate != null) - { - onNavigate(this, e); - } + onNavigate?.Invoke(this, e); } /* @@ -3882,11 +3879,7 @@ internal void OnNodeClick(EventArgs e) } // Raise the event for the event listeners - EventHandler handler = (EventHandler)Events[EVENT_NODECLICKED]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_NODECLICKED])?.Invoke(this, e); } /// @@ -3894,10 +3887,7 @@ internal void OnNodeClick(EventArgs e) /// protected void OnRowHeaderClick(EventArgs e) { - if (onRowHeaderClick != null) - { - onRowHeaderClick(this, e); - } + onRowHeaderClick?.Invoke(this, e); } /// @@ -3911,13 +3901,7 @@ protected void OnScroll(EventArgs e) if (ToolTipProvider != null) { ResetToolTip(); - } - - EventHandler handler = (EventHandler)Events[EVENT_SCROLL]; - if (handler != null) - { - handler(this, e); - } + } ((EventHandler)Events[EVENT_SCROLL])?.Invoke(this, e); } /// @@ -4102,11 +4086,7 @@ protected void OnBackButtonClicked(object sender, EventArgs e) { NavigateBack(); - EventHandler handler = (EventHandler)Events[EVENT_BACKBUTTONCLICK]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_BACKBUTTONCLICK])?.Invoke(this, e); } protected override void OnBackColorChanged(EventArgs e) @@ -4178,11 +4158,7 @@ protected void OnShowParentDetailsButtonClicked(object sender, EventArgs e) // then fires the event. ParentRowsVisible = !caption.ToggleDownButtonDirection(); - EventHandler handler = (EventHandler)Events[EVENT_DOWNBUTTONCLICK]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_DOWNBUTTONCLICK])?.Invoke(this, e); } protected override void OnForeColorChanged(EventArgs e) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs index 099a4a27038..325efac0066 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridCaption.cs @@ -446,32 +446,20 @@ protected void OnBackwardClicked(EventArgs e) { if (backActive) { - EventHandler handler = (EventHandler)Events[EVENT_BACKWARDCLICKED]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_BACKWARDCLICKED])?.Invoke(this, e); } } protected void OnCaptionClicked(EventArgs e) { - EventHandler handler = (EventHandler)Events[EVENT_CAPTIONCLICKED]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_CAPTIONCLICKED])?.Invoke(this, e); } protected void OnDownClicked(EventArgs e) { if (downActive && downButtonVisible) { - EventHandler handler = (EventHandler)Events[EVENT_DOWNCLICKED]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_DOWNCLICKED])?.Invoke(this, e); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs index f7838378cce..62e593fc07a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridColumnCollection.cs @@ -526,10 +526,7 @@ public int IndexOf(DataGridColumnStyle element) /// protected void OnCollectionChanged(CollectionChangeEventArgs e) { - if (onCollectionChanged != null) - { - onCollectionChanged(this, e); - } + onCollectionChanged?.Invoke(this, e); DataGrid grid = owner.DataGrid; if (grid != null) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs index 3c9c5915ca6..ee2391283b3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridTableCollection.cs @@ -287,10 +287,7 @@ public override IEnumerator GetEnumerator(bool allowRemove) { protected void OnCollectionChanged(CollectionChangeEventArgs e) { - if (onCollectionChanged != null) - { - onCollectionChanged(this, e); - } + onCollectionChanged?.Invoke(this, e); DataGrid grid = owner; if (grid != null) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellCollection.cs index c9451d84c08..368c713cb27 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellCollection.cs @@ -351,10 +351,7 @@ internal void InsertInternal(int index, DataGridViewCell dataGridViewCell) protected void OnCollectionChanged(CollectionChangeEventArgs e) { - if (onCollectionChanged != null) - { - onCollectionChanged(this, e); - } + onCollectionChanged?.Invoke(this, e); } public virtual void Remove(DataGridViewCell cell) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumn.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumn.cs index 16f500275f4..eae4aa8b319 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumn.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumn.cs @@ -1115,10 +1115,7 @@ protected override void Dispose(bool disposing) site.Container.Remove(this); } - if (disposed != null) - { - disposed(this, EventArgs.Empty); - } + disposed?.Invoke(this, EventArgs.Empty); } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs index c26bf147dd9..e0f708981bc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewColumnCollection.cs @@ -998,10 +998,7 @@ internal void InvalidateCachedColumnsWidths() protected virtual void OnCollectionChanged(CollectionChangeEventArgs e) { - if (onCollectionChanged != null) - { - onCollectionChanged(this, e); - } + onCollectionChanged?.Invoke(this, e); } private void OnCollectionChanged(CollectionChangeEventArgs ccea, bool changeIsInsertion, Point newCurrentCell) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowCollection.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowCollection.cs index 5f6ed92dcc8..5d8398fc5e8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowCollection.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowCollection.cs @@ -1954,10 +1954,7 @@ internal void InvalidateCachedRowsHeights() protected virtual void OnCollectionChanged(CollectionChangeEventArgs e) { - if (onCollectionChanged != null) - { - onCollectionChanged(this, e); - } + onCollectionChanged?.Invoke(this, e); } private void OnCollectionChanged(CollectionChangeEventArgs e, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs index 022b1b62228..6fcbe3d8eef 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DateTimePicker.cs @@ -1248,10 +1248,7 @@ protected override bool IsInputKey(Keys keyData) /// protected virtual void OnCloseUp(EventArgs eventargs) { - if (onCloseUp != null) - { - onCloseUp(this, eventargs); - } + onCloseUp?.Invoke(this, eventargs); } /// @@ -1259,10 +1256,7 @@ protected virtual void OnCloseUp(EventArgs eventargs) /// protected virtual void OnDropDown(EventArgs eventargs) { - if (onDropDown != null) - { - onDropDown(this, eventargs); - } + onDropDown?.Invoke(this, eventargs); } protected virtual void OnFormatChanged(EventArgs e) @@ -1297,10 +1291,7 @@ protected override void OnHandleDestroyed(EventArgs e) /// protected virtual void OnValueChanged(EventArgs eventargs) { - if (onValueChanged != null) - { - onValueChanged(this, eventargs); - } + onValueChanged?.Invoke(this, eventargs); } [EditorBrowsable(EditorBrowsableState.Advanced)] @@ -1316,10 +1307,7 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) RecreateHandle(); } - if (onRightToLeftLayoutChanged != null) - { - onRightToLeftLayoutChanged(this, e); - } + onRightToLeftLayoutChanged?.Invoke(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DomainUpDown.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DomainUpDown.cs index c9747f60d75..1be2d9425a0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DomainUpDown.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DomainUpDown.cs @@ -470,10 +470,7 @@ protected void OnSelectedItemChanged(object source, EventArgs e) { // Call the event handler - if (onSelectedItemChanged != null) - { - onSelectedItemChanged(this, e); - } + onSelectedItemChanged?.Invoke(this, e); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs index f3a9dca5438..e96f740b652 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider.cs @@ -895,10 +895,7 @@ protected virtual void OnRightToLeftChanged(EventArgs e) w.Update(false); } - if (onRightToLeftChanged != null) - { - onRightToLeftChanged(this, e); - } + onRightToLeftChanged?.Invoke(this, e); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/FontDialog.cs b/src/System.Windows.Forms/src/System/Windows/Forms/FontDialog.cs index d842bb6a35d..c4c1a4993df 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/FontDialog.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/FontDialog.cs @@ -553,11 +553,7 @@ protected override IntPtr HookProc(IntPtr hWnd, int msg, IntPtr wparam, IntPtr l /// protected virtual void OnApply(EventArgs e) { - EventHandler handler = (EventHandler)Events[EventApply]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventApply])?.Invoke(this, e); } /// 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 c67eff20cbd..355e1af46fd 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs @@ -4335,11 +4335,7 @@ internal void MenuChanged(int change, Menu menu) [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnActivated(EventArgs e) { - EventHandler handler = (EventHandler)Events[EVENT_ACTIVATED]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_ACTIVATED])?.Invoke(this, e); } /// @@ -4387,11 +4383,7 @@ protected override void OnBackgroundImageLayoutChanged(EventArgs e) [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnClosing(CancelEventArgs e) { - CancelEventHandler handler = (CancelEventHandler)Events[EVENT_CLOSING]; - if (handler != null) - { - handler(this, e); - } + ((CancelEventHandler)Events[EVENT_CLOSING])?.Invoke(this, e); } /// @@ -4400,11 +4392,7 @@ protected virtual void OnClosing(CancelEventArgs e) [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnClosed(EventArgs e) { - EventHandler handler = (EventHandler)Events[EVENT_CLOSED]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_CLOSED])?.Invoke(this, e); } @@ -4414,11 +4402,7 @@ protected virtual void OnClosed(EventArgs e) [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnFormClosing(FormClosingEventArgs e) { - FormClosingEventHandler handler = (FormClosingEventHandler)Events[EVENT_FORMCLOSING]; - if (handler != null) - { - handler(this, e); - } + ((FormClosingEventHandler)Events[EVENT_FORMCLOSING])?.Invoke(this, e); } /// @@ -4430,11 +4414,7 @@ protected virtual void OnFormClosed(FormClosedEventArgs e) //Remove the form from Application.OpenForms (nothing happens if isn't present) Application.OpenForms.Remove(this); - FormClosedEventHandler handler = (FormClosedEventHandler)Events[EVENT_FORMCLOSED]; - if (handler != null) - { - handler(this, e); - } + ((FormClosedEventHandler)Events[EVENT_FORMCLOSED])?.Invoke(this, e); } /// @@ -4459,11 +4439,7 @@ protected override void OnCreateControl() [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnDeactivate(EventArgs e) { - EventHandler handler = (EventHandler)Events[EVENT_DEACTIVATE]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_DEACTIVATE])?.Invoke(this, e); } /// @@ -4545,11 +4521,7 @@ protected override void OnHandleDestroyed(EventArgs e) [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnHelpButtonClicked(CancelEventArgs e) { - CancelEventHandler handler = (CancelEventHandler)Events[EVENT_HELPBUTTONCLICKED]; - if (handler != null) - { - handler(this, e); - } + ((CancelEventHandler)Events[EVENT_HELPBUTTONCLICKED])?.Invoke(this, e); } protected override void OnLayout(LayoutEventArgs levent) @@ -4704,11 +4676,7 @@ protected virtual void OnMinimumSizeChanged(EventArgs e) [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnInputLanguageChanged(InputLanguageChangedEventArgs e) { - InputLanguageChangedEventHandler handler = (InputLanguageChangedEventHandler)Events[EVENT_INPUTLANGCHANGE]; - if (handler != null) - { - handler(this, e); - } + ((InputLanguageChangedEventHandler)Events[EVENT_INPUTLANGCHANGE])?.Invoke(this, e); } /// @@ -4718,11 +4686,7 @@ protected virtual void OnInputLanguageChanged(InputLanguageChangedEventArgs e) [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnInputLanguageChanging(InputLanguageChangingEventArgs e) { - InputLanguageChangingEventHandler handler = (InputLanguageChangingEventHandler)Events[EVENT_INPUTLANGCHANGEREQUEST]; - if (handler != null) - { - handler(this, e); - } + ((InputLanguageChangingEventHandler)Events[EVENT_INPUTLANGCHANGEREQUEST])?.Invoke(this, e); } [EditorBrowsable(EditorBrowsableState.Advanced)] @@ -4769,11 +4733,7 @@ protected virtual void OnMdiChildActivate(EventArgs e) { UpdateMenuHandles(); UpdateToolStrip(); - EventHandler handler = (EventHandler)Events[EVENT_MDI_CHILD_ACTIVATE]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_MDI_CHILD_ACTIVATE])?.Invoke(this, e); } /// @@ -4792,11 +4752,7 @@ protected virtual void OnMenuStart(EventArgs e) [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnMenuComplete(EventArgs e) { - EventHandler handler = (EventHandler)Events[EVENT_MENUCOMPLETE]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_MENUCOMPLETE])?.Invoke(this, e); } /// @@ -4979,11 +4935,7 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnShown(EventArgs e) { - EventHandler handler = (EventHandler)Events[EVENT_SHOWN]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_SHOWN])?.Invoke(this, e); } [EditorBrowsable(EditorBrowsableState.Advanced)] @@ -6566,11 +6518,7 @@ protected virtual void OnResizeBegin(EventArgs e) { if (CanRaiseEvents) { - EventHandler handler = (EventHandler)Events[EVENT_RESIZEBEGIN]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_RESIZEBEGIN])?.Invoke(this, e); } } @@ -6583,11 +6531,7 @@ protected virtual void OnResizeEnd(EventArgs e) { if (CanRaiseEvents) { - EventHandler handler = (EventHandler)Events[EVENT_RESIZEEND]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_RESIZEEND])?.Invoke(this, e); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlToClrEventProxy.cs b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlToClrEventProxy.cs index 2b2369a4118..a44e4803cda 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/HtmlToClrEventProxy.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/HtmlToClrEventProxy.cs @@ -42,10 +42,7 @@ public void OnHtmlEvent() private void InvokeClrEvent() { - if (eventHandler != null) - { - eventHandler(sender, EventArgs.Empty); - } + eventHandler?.Invoke(sender, EventArgs.Empty); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs index b5da5d24b28..7ef7827ee39 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ImageList.cs @@ -900,18 +900,12 @@ public Bitmap DebugOnly_GetMasterMask() { /// private void OnRecreateHandle(EventArgs eventargs) { - if (recreateHandler != null) - { - recreateHandler(this, eventargs); - } + recreateHandler?.Invoke(this, eventargs); } private void OnChangeHandle(EventArgs eventargs) { - if (changeHandler != null) - { - changeHandler(this, eventargs); - } + changeHandler?.Invoke(this, eventargs); } #if false diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs index bd9c4b50a34..85cbbcf6a03 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/LinkLabel.cs @@ -1245,11 +1245,7 @@ protected override void OnMouseMove(MouseEventArgs e) /// protected virtual void OnLinkClicked(LinkLabelLinkClickedEventArgs e) { - LinkLabelLinkClickedEventHandler handler = (LinkLabelLinkClickedEventHandler)Events[EventLinkClicked]; - if (handler != null) - { - handler(this, e); - } + ((LinkLabelLinkClickedEventHandler)Events[EventLinkClicked])?.Invoke(this, e); } protected override void OnPaddingChanged(EventArgs e) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs index 27f341415a6..2ed1865b15b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListBox.cs @@ -1802,11 +1802,7 @@ protected override void OnChangeUICues(UICuesEventArgs e) /// protected virtual void OnDrawItem(DrawItemEventArgs e) { - DrawItemEventHandler handler = (DrawItemEventHandler)Events[EVENT_DRAWITEM]; - if (handler != null) - { - handler(this, e); - } + ((DrawItemEventHandler)Events[EVENT_DRAWITEM])?.Invoke(this, e); } /// @@ -1891,11 +1887,7 @@ protected override void OnHandleDestroyed(EventArgs e) protected virtual void OnMeasureItem(MeasureItemEventArgs e) { - MeasureItemEventHandler handler = (MeasureItemEventHandler)Events[EVENT_MEASUREITEM]; - if (handler != null) - { - handler(this, e); - } + ((MeasureItemEventHandler)Events[EVENT_MEASUREITEM])?.Invoke(this, e); } protected override void OnFontChanged(EventArgs e) @@ -1969,11 +1961,7 @@ protected override void OnSelectedIndexChanged(EventArgs e) // Call the handler after updating the DataManager's position so that // the DataManager's selected index will be correct in an event handler. - EventHandler handler = (EventHandler)Events[EVENT_SELECTEDINDEXCHANGED]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_SELECTEDINDEXCHANGED])?.Invoke(this, e); } protected override void OnSelectedValueChanged(EventArgs e) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs index 1124d24a693..032e004201f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ListView.cs @@ -4411,10 +4411,7 @@ private void LvnBeginDrag(MouseButtons buttons, NativeMethods.NMLISTVIEW nmlv) /// protected virtual void OnAfterLabelEdit(LabelEditEventArgs e) { - if (onAfterLabelEdit != null) - { - onAfterLabelEdit(this, e); - } + onAfterLabelEdit?.Invoke(this, e); } protected override void OnBackgroundImageChanged(EventArgs e) @@ -4482,21 +4479,14 @@ protected override void OnMouseHover(EventArgs e) /// protected virtual void OnBeforeLabelEdit(LabelEditEventArgs e) { - if (onBeforeLabelEdit != null) - { - onBeforeLabelEdit(this, e); - } + onBeforeLabelEdit?.Invoke(this, e); } /// /// protected virtual void OnCacheVirtualItems(CacheVirtualItemsEventArgs e) { - CacheVirtualItemsEventHandler handler = (CacheVirtualItemsEventHandler)Events[EVENT_CACHEVIRTUALITEMS]; - if (handler != null) - { - handler(this, e); - } + ((CacheVirtualItemsEventHandler)Events[EVENT_CACHEVIRTUALITEMS])?.Invoke(this, e); } /// @@ -4504,10 +4494,7 @@ protected virtual void OnCacheVirtualItems(CacheVirtualItemsEventArgs e) /// protected virtual void OnColumnClick(ColumnClickEventArgs e) { - if (onColumnClick != null) - { - onColumnClick(this, e); - } + onColumnClick?.Invoke(this, e); } /// @@ -4515,11 +4502,7 @@ protected virtual void OnColumnClick(ColumnClickEventArgs e) /// protected virtual void OnColumnReordered(ColumnReorderedEventArgs e) { - ColumnReorderedEventHandler handler = (ColumnReorderedEventHandler)Events[EVENT_COLUMNREORDERED]; - if (handler != null) - { - handler(this, e); - } + ((ColumnReorderedEventHandler)Events[EVENT_COLUMNREORDERED])?.Invoke(this, e); } /// @@ -4527,11 +4510,7 @@ protected virtual void OnColumnReordered(ColumnReorderedEventArgs e) /// protected virtual void OnColumnWidthChanged(ColumnWidthChangedEventArgs e) { - ColumnWidthChangedEventHandler handler = (ColumnWidthChangedEventHandler)Events[EVENT_COLUMNWIDTHCHANGED]; - if (handler != null) - { - handler(this, e); - } + ((ColumnWidthChangedEventHandler)Events[EVENT_COLUMNWIDTHCHANGED])?.Invoke(this, e); } /// @@ -4539,11 +4518,7 @@ protected virtual void OnColumnWidthChanged(ColumnWidthChangedEventArgs e) /// protected virtual void OnColumnWidthChanging(ColumnWidthChangingEventArgs e) { - ColumnWidthChangingEventHandler handler = (ColumnWidthChangingEventHandler)Events[EVENT_COLUMNWIDTHCHANGING]; - if (handler != null) - { - handler(this, e); - } + ((ColumnWidthChangingEventHandler)Events[EVENT_COLUMNWIDTHCHANGING])?.Invoke(this, e); } /// @@ -4551,11 +4526,7 @@ protected virtual void OnColumnWidthChanging(ColumnWidthChangingEventArgs e) /// protected virtual void OnDrawColumnHeader(DrawListViewColumnHeaderEventArgs e) { - DrawListViewColumnHeaderEventHandler handler = (DrawListViewColumnHeaderEventHandler)Events[EVENT_DRAWCOLUMNHEADER]; - if (handler != null) - { - handler(this, e); - } + ((DrawListViewColumnHeaderEventHandler)Events[EVENT_DRAWCOLUMNHEADER])?.Invoke(this, e); } /// @@ -4563,11 +4534,7 @@ protected virtual void OnDrawColumnHeader(DrawListViewColumnHeaderEventArgs e) /// protected virtual void OnDrawItem(DrawListViewItemEventArgs e) { - DrawListViewItemEventHandler handler = (DrawListViewItemEventHandler)Events[EVENT_DRAWITEM]; - if (handler != null) - { - handler(this, e); - } + ((DrawListViewItemEventHandler)Events[EVENT_DRAWITEM])?.Invoke(this, e); } /// @@ -4575,11 +4542,7 @@ protected virtual void OnDrawItem(DrawListViewItemEventArgs e) /// protected virtual void OnDrawSubItem(DrawListViewSubItemEventArgs e) { - DrawListViewSubItemEventHandler handler = (DrawListViewSubItemEventHandler)Events[EVENT_DRAWSUBITEM]; - if (handler != null) - { - handler(this, e); - } + ((DrawListViewSubItemEventHandler)Events[EVENT_DRAWSUBITEM])?.Invoke(this, e); } protected override void OnFontChanged(EventArgs e) @@ -4806,10 +4769,7 @@ protected override void OnHandleDestroyed(EventArgs e) /// protected virtual void OnItemActivate(EventArgs e) { - if (onItemActivate != null) - { - onItemActivate(this, e); - } + onItemActivate?.Invoke(this, e); } /// @@ -4819,26 +4779,17 @@ protected virtual void OnItemActivate(EventArgs e) /// protected virtual void OnItemCheck(ItemCheckEventArgs ice) { - if (onItemCheck != null) - { - onItemCheck(this, ice); - } + onItemCheck?.Invoke(this, ice); } protected virtual void OnItemChecked(ItemCheckedEventArgs e) { - if (onItemChecked != null) - { - onItemChecked(this, e); - } + onItemChecked?.Invoke(this, e); } protected virtual void OnItemDrag(ItemDragEventArgs e) { - if (onItemDrag != null) - { - onItemDrag(this, e); - } + onItemDrag?.Invoke(this, e); } /// @@ -4846,10 +4797,7 @@ protected virtual void OnItemDrag(ItemDragEventArgs e) /// protected virtual void OnItemMouseHover(ListViewItemMouseHoverEventArgs e) { - if (onItemMouseHover != null) - { - onItemMouseHover(this, e); - } + onItemMouseHover?.Invoke(this, e); } /// @@ -4857,11 +4805,7 @@ protected virtual void OnItemMouseHover(ListViewItemMouseHoverEventArgs e) /// protected virtual void OnItemSelectionChanged(ListViewItemSelectionChangedEventArgs e) { - ListViewItemSelectionChangedEventHandler eh = (ListViewItemSelectionChangedEventHandler)Events[EVENT_ITEMSELECTIONCHANGED]; - if (eh != null) - { - eh(this, e); - } + ((ListViewItemSelectionChangedEventHandler)Events[EVENT_ITEMSELECTIONCHANGED])?.Invoke(this, e); } protected override void OnParentChanged(EventArgs e) @@ -4893,11 +4837,7 @@ protected override void OnResize(EventArgs e) /// protected virtual void OnRetrieveVirtualItem(RetrieveVirtualItemEventArgs e) { - RetrieveVirtualItemEventHandler handler = (RetrieveVirtualItemEventHandler)Events[EVENT_RETRIEVEVIRTUALITEM]; - if (handler != null) - { - handler(this, e); - } + ((RetrieveVirtualItemEventHandler)Events[EVENT_RETRIEVEVIRTUALITEM])?.Invoke(this, e); } @@ -4926,11 +4866,7 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) /// protected virtual void OnSearchForVirtualItem(SearchForVirtualItemEventArgs e) { - SearchForVirtualItemEventHandler handler = (SearchForVirtualItemEventHandler)Events[EVENT_SEARCHFORVIRTUALITEM]; - if (handler != null) - { - handler(this, e); - } + ((SearchForVirtualItemEventHandler)Events[EVENT_SEARCHFORVIRTUALITEM])?.Invoke(this, e); } /// @@ -4942,11 +4878,7 @@ protected virtual void OnSearchForVirtualItem(SearchForVirtualItemEventArgs e) /// protected virtual void OnSelectedIndexChanged(EventArgs e) { - EventHandler handler = (EventHandler)Events[EVENT_SELECTEDINDEXCHANGED]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_SELECTEDINDEXCHANGED])?.Invoke(this, e); } protected override void OnSystemColorsChanged(EventArgs e) @@ -4965,11 +4897,7 @@ protected override void OnSystemColorsChanged(EventArgs e) protected virtual void OnVirtualItemsSelectionRangeChanged(ListViewVirtualItemsSelectionRangeChangedEventArgs e) { - ListViewVirtualItemsSelectionRangeChangedEventHandler eh = (ListViewVirtualItemsSelectionRangeChangedEventHandler)Events[EVENT_VIRTUALITEMSSELECTIONRANGECHANGED]; - if (eh != null) - { - eh(this, e); - } + ((ListViewVirtualItemsSelectionRangeChangedEventHandler)Events[EVENT_VIRTUALITEMSSELECTIONRANGECHANGED])?.Invoke(this, e); } private unsafe void PositionHeader() diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MainMenu.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MainMenu.cs index 1c902b6578b..e8cff8df40b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MainMenu.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MainMenu.cs @@ -195,10 +195,7 @@ internal virtual void ItemsChanged(int change, Menu menu) /// protected internal virtual void OnCollapse(EventArgs e) { - if (onCollapse != null) - { - onCollapse(this, e); - } + onCollapse?.Invoke(this, e); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MenuItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MenuItem.cs index 62bbf8a9671..ed2b82798a7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MenuItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MenuItem.cs @@ -1212,9 +1212,9 @@ protected virtual void OnClick(EventArgs e) { _data.baseItem.OnClick(e); } - else if (_data._onClick != null) + else { - _data._onClick(this, e); + _data._onClick?.Invoke(this, e); } } @@ -1229,9 +1229,9 @@ protected virtual void OnDrawItem(DrawItemEventArgs e) { _data.baseItem.OnDrawItem(e); } - else if (_data._onDrawItem != null) + else { - _data._onDrawItem(this, e); + _data._onDrawItem?.Invoke(this, e); } } @@ -1246,9 +1246,9 @@ protected virtual void OnMeasureItem(MeasureItemEventArgs e) { _data.baseItem.OnMeasureItem(e); } - else if (_data._onMeasureItem != null) + else { - _data._onMeasureItem(this, e); + _data._onMeasureItem?.Invoke(this, e); } } @@ -1277,9 +1277,9 @@ protected virtual void OnPopup(EventArgs e) { _data.baseItem.OnPopup(e); } - else if (_data._onPopup != null) + else { - _data._onPopup(this, e); + _data._onPopup?.Invoke(this, e); } // Update any subitem states that got changed in the event @@ -1309,9 +1309,9 @@ protected virtual void OnSelect(EventArgs e) { _data.baseItem.OnSelect(e); } - else if (_data._onSelect != null) + else { - _data._onSelect(this, e); + _data._onSelect?.Invoke(this, e); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MenuStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MenuStrip.cs index bd24f0e8619..405c699b685 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MenuStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MenuStrip.cs @@ -217,12 +217,7 @@ protected virtual void OnMenuActivate(EventArgs e) if (IsHandleCreated) { AccessibilityNotifyClients(AccessibleEvents.SystemMenuStart, -1); - } - EventHandler handler = (EventHandler)Events[EventMenuActivate]; - if (handler != null) - { - handler(this, e); - } + } ((EventHandler)Events[EventMenuActivate])?.Invoke(this, e); } protected virtual void OnMenuDeactivate(EventArgs e) @@ -230,12 +225,7 @@ protected virtual void OnMenuDeactivate(EventArgs e) if (IsHandleCreated) { AccessibilityNotifyClients(AccessibleEvents.SystemMenuEnd, -1); - } - EventHandler handler = (EventHandler)Events[EventMenuDeactivate]; - if (handler != null) - { - handler(this, e); - } + } ((EventHandler)Events[EventMenuDeactivate])?.Invoke(this, e); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs index 9026f6ed978..d4386d2af43 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/MonthCalendar.cs @@ -1705,10 +1705,7 @@ protected override void OnHandleDestroyed(EventArgs e) /// protected virtual void OnDateChanged(DateRangeEventArgs drevent) { - if (onDateChanged != null) - { - onDateChanged(this, drevent); - } + onDateChanged?.Invoke(this, drevent); } /// @@ -1716,10 +1713,7 @@ protected virtual void OnDateChanged(DateRangeEventArgs drevent) /// protected virtual void OnDateSelected(DateRangeEventArgs drevent) { - if (onDateSelected != null) - { - onDateSelected(this, drevent); - } + onDateSelected?.Invoke(this, drevent); } protected override void OnFontChanged(EventArgs e) @@ -1753,10 +1747,7 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) RecreateHandle(); } - if (onRightToLeftLayoutChanged != null) - { - onRightToLeftLayoutChanged(this, e); - } + onRightToLeftLayoutChanged?.Invoke(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs index 8db7f7d007f..e50901e111c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NotifyIcon.cs @@ -491,11 +491,7 @@ protected override void Dispose(bool disposing) /// private void OnBalloonTipClicked() { - EventHandler handler = (EventHandler)Events[EVENT_BALLOONTIPCLICKED]; - if (handler != null) - { - handler(this, EventArgs.Empty); - } + ((EventHandler)Events[EVENT_BALLOONTIPCLICKED])?.Invoke(this, EventArgs.Empty); } /// @@ -505,11 +501,7 @@ private void OnBalloonTipClicked() /// private void OnBalloonTipClosed() { - EventHandler handler = (EventHandler)Events[EVENT_BALLOONTIPCLOSED]; - if (handler != null) - { - handler(this, EventArgs.Empty); - } + ((EventHandler)Events[EVENT_BALLOONTIPCLOSED])?.Invoke(this, EventArgs.Empty); } /// @@ -519,11 +511,7 @@ private void OnBalloonTipClosed() /// private void OnBalloonTipShown() { - EventHandler handler = (EventHandler)Events[EVENT_BALLOONTIPSHOWN]; - if (handler != null) - { - handler(this, EventArgs.Empty); - } + ((EventHandler)Events[EVENT_BALLOONTIPSHOWN])?.Invoke(this, EventArgs.Empty); } /// @@ -537,11 +525,7 @@ private void OnBalloonTipShown() /// private void OnClick(EventArgs e) { - EventHandler handler = (EventHandler)Events[EVENT_CLICK]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_CLICK])?.Invoke(this, e); } /// @@ -550,11 +534,7 @@ private void OnClick(EventArgs e) /// private void OnDoubleClick(EventArgs e) { - EventHandler handler = (EventHandler)Events[EVENT_DOUBLECLICK]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_DOUBLECLICK])?.Invoke(this, e); } @@ -564,11 +544,7 @@ private void OnDoubleClick(EventArgs e) /// private void OnMouseClick(MouseEventArgs mea) { - MouseEventHandler handler = (MouseEventHandler)Events[EVENT_MOUSECLICK]; - if (handler != null) - { - handler(this, mea); - } + ((MouseEventHandler)Events[EVENT_MOUSECLICK])?.Invoke(this, mea); } /// @@ -577,11 +553,7 @@ private void OnMouseClick(MouseEventArgs mea) /// private void OnMouseDoubleClick(MouseEventArgs mea) { - MouseEventHandler handler = (MouseEventHandler)Events[EVENT_MOUSEDOUBLECLICK]; - if (handler != null) - { - handler(this, mea); - } + ((MouseEventHandler)Events[EVENT_MOUSEDOUBLECLICK])?.Invoke(this, mea); } /// @@ -594,11 +566,7 @@ private void OnMouseDoubleClick(MouseEventArgs mea) /// private void OnMouseDown(MouseEventArgs e) { - MouseEventHandler handler = (MouseEventHandler)Events[EVENT_MOUSEDOWN]; - if (handler != null) - { - handler(this, e); - } + ((MouseEventHandler)Events[EVENT_MOUSEDOWN])?.Invoke(this, e); } /// @@ -610,11 +578,7 @@ private void OnMouseDown(MouseEventArgs e) /// private void OnMouseMove(MouseEventArgs e) { - MouseEventHandler handler = (MouseEventHandler)Events[EVENT_MOUSEMOVE]; - if (handler != null) - { - handler(this, e); - } + ((MouseEventHandler)Events[EVENT_MOUSEMOVE])?.Invoke(this, e); } /// @@ -625,11 +589,7 @@ private void OnMouseMove(MouseEventArgs e) /// private void OnMouseUp(MouseEventArgs e) { - MouseEventHandler handler = (MouseEventHandler)Events[EVENT_MOUSEUP]; - if (handler != null) - { - handler(this, e); - } + ((MouseEventHandler)Events[EVENT_MOUSEUP])?.Invoke(this, e); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDown.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDown.cs index b04dc549530..a3995913e33 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDown.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NumericUpDown.cs @@ -585,10 +585,7 @@ protected virtual void OnValueChanged(EventArgs e) { // Call the event handler - if (onValueChanged != null) - { - onValueChanged(this, e); - } + onValueChanged?.Invoke(this, e); } protected override void OnLostFocus(EventArgs e) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs index e19ef833d52..a25a49f26eb 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs @@ -1222,20 +1222,12 @@ protected override void OnHandleCreated(EventArgs e) protected virtual void OnLoadCompleted(AsyncCompletedEventArgs e) { - AsyncCompletedEventHandler handler = (AsyncCompletedEventHandler)(Events[loadCompletedKey]); - if (handler != null) - { - handler(this, e); - } + ((AsyncCompletedEventHandler)(Events[loadCompletedKey]))?.Invoke(this, e); } protected virtual void OnLoadProgressChanged(ProgressChangedEventArgs e) { - ProgressChangedEventHandler handler = (ProgressChangedEventHandler)(Events[loadProgressChangedKey]); - if (handler != null) - { - handler(this, e); - } + ((ProgressChangedEventHandler)(Events[loadProgressChangedKey]))?.Invoke(this, e); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs index 490ddf22902..be03a5391be 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ProgressBar.cs @@ -802,10 +802,7 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) RecreateHandle(); } - if (onRightToLeftLayoutChanged != null) - { - onRightToLeftLayoutChanged(this, e); - } + onRightToLeftLayoutChanged?.Invoke(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs index dd318b9304a..d020c191991 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/PropertyGrid.cs @@ -3515,11 +3515,7 @@ private void OnButtonClick(object sender, EventArgs e) // protected void OnComComponentNameChanged(ComponentRenameEventArgs e) { - ComponentRenameEventHandler handler = (ComponentRenameEventHandler)Events[EventComComponentNameChanged]; - if (handler != null) - { - handler(this, e); - } + ((ComponentRenameEventHandler)Events[EventComComponentNameChanged])?.Invoke(this, e); } @@ -3588,33 +3584,21 @@ protected override void OnPaint(PaintEventArgs pevent) [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] protected virtual void OnPropertySortChanged(EventArgs e) { - EventHandler handler = (EventHandler)Events[EventPropertySortChanged]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventPropertySortChanged])?.Invoke(this, e); } // Seems safe - just fires an event [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] protected virtual void OnPropertyTabChanged(PropertyTabChangedEventArgs e) { - PropertyTabChangedEventHandler handler = (PropertyTabChangedEventHandler)Events[EventPropertyTabChanged]; - if (handler != null) - { - handler(this, e); - } + ((PropertyTabChangedEventHandler)Events[EventPropertyTabChanged])?.Invoke(this, e); } // Seems safe - just fires an event [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] protected virtual void OnPropertyValueChanged(PropertyValueChangedEventArgs e) { - PropertyValueChangedEventHandler handler = (PropertyValueChangedEventHandler)Events[EventPropertyValueChanged]; - if (handler != null) - { - handler(this, e); - } + ((PropertyValueChangedEventHandler)Events[EventPropertyValueChanged])?.Invoke(this, e); } internal void OnPropertyValueSet(GridItem changedItem, object oldValue) @@ -3656,12 +3640,7 @@ internal void OnSelectedGridItemChanged(GridEntry oldEntry, GridEntry newEntry) // protected virtual void OnSelectedGridItemChanged(SelectedGridItemChangedEventArgs e) { - SelectedGridItemChangedEventHandler handler = (SelectedGridItemChangedEventHandler)Events[EventSelectedGridItemChanged]; - - if (handler != null) - { - handler(this, e); - } + ((SelectedGridItemChangedEventHandler)Events[EventSelectedGridItemChanged])?.Invoke(this, e); } @@ -3669,11 +3648,7 @@ protected virtual void OnSelectedGridItemChanged(SelectedGridItemChangedEventArg // protected virtual void OnSelectedObjectsChanged(EventArgs e) { - EventHandler handler = (EventHandler)Events[EventSelectedObjectsChanged]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventSelectedObjectsChanged])?.Invoke(this, e); } private void OnTransactionClosed(object sender, DesignerTransactionCloseEventArgs e) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs index d1f70636db9..1fea294c8a0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RadioButton.cs @@ -462,11 +462,7 @@ protected virtual void OnCheckedChanged(EventArgs e) { AccessibilityNotifyClients(AccessibleEvents.StateChange, -1); AccessibilityNotifyClients(AccessibleEvents.NameChange, -1); - EventHandler handler = (EventHandler)Events[EVENT_CHECKEDCHANGED]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_CHECKEDCHANGED])?.Invoke(this, e); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs index ed82019572a..413fa1d4381 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/RichTextBox.cs @@ -2695,11 +2695,7 @@ protected override void OnRightToLeftChanged(EventArgs e) /// protected virtual void OnContentsResized(ContentsResizedEventArgs e) { - ContentsResizedEventHandler handler = (ContentsResizedEventHandler)Events[EVENT_REQUESTRESIZE]; - if (handler != null) - { - handler(this, e); - } + ((ContentsResizedEventHandler)Events[EVENT_REQUESTRESIZE])?.Invoke(this, e); } protected override void OnHandleCreated(EventArgs e) @@ -2822,11 +2818,7 @@ protected override void OnHandleDestroyed(EventArgs e) /// protected virtual void OnHScroll(EventArgs e) { - EventHandler handler = (EventHandler)Events[EVENT_HSCROLL]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_HSCROLL])?.Invoke(this, e); } /// @@ -2835,11 +2827,7 @@ protected virtual void OnHScroll(EventArgs e) /// protected virtual void OnLinkClicked(LinkClickedEventArgs e) { - LinkClickedEventHandler handler = (LinkClickedEventHandler)Events[EVENT_LINKACTIVATE]; - if (handler != null) - { - handler(this, e); - } + ((LinkClickedEventHandler)Events[EVENT_LINKACTIVATE])?.Invoke(this, e); } @@ -2848,11 +2836,7 @@ protected virtual void OnLinkClicked(LinkClickedEventArgs e) /// protected virtual void OnImeChange(EventArgs e) { - EventHandler handler = (EventHandler)Events[EVENT_IMECHANGE]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_IMECHANGE])?.Invoke(this, e); } /// @@ -2862,11 +2846,7 @@ protected virtual void OnImeChange(EventArgs e) protected virtual void OnProtected(EventArgs e) { ProtectedError = true; - EventHandler handler = (EventHandler)Events[EVENT_PROTECTED]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_PROTECTED])?.Invoke(this, e); } /// @@ -2875,11 +2855,7 @@ protected virtual void OnProtected(EventArgs e) /// protected virtual void OnSelectionChanged(EventArgs e) { - EventHandler handler = (EventHandler)Events[EVENT_SELCHANGE]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_SELCHANGE])?.Invoke(this, e); } /// @@ -2888,11 +2864,7 @@ protected virtual void OnSelectionChanged(EventArgs e) /// protected virtual void OnVScroll(EventArgs e) { - EventHandler handler = (EventHandler)Events[EVENT_VSCROLL]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_VSCROLL])?.Invoke(this, e); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs index 8ecac6c1599..3d9b7ac058b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ScrollableControl.cs @@ -829,11 +829,7 @@ protected override void OnPaddingChanged(EventArgs e) // DockPaddingEdges compat. // dont call base in this instance - for App compat we should not fire Invalidate when // the padding has changed. - EventHandler handler = (EventHandler)Events[Control.EventPaddingChanged]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[Control.EventPaddingChanged])?.Invoke(this, e); } @@ -1094,11 +1090,7 @@ public event ScrollEventHandler Scroll /// protected virtual void OnScroll(ScrollEventArgs se) { - ScrollEventHandler handler = (ScrollEventHandler)Events[EVENT_SCROLL]; - if (handler != null) - { - handler(this, se); - } + ((ScrollEventHandler)Events[EVENT_SCROLL])?.Invoke(this, se); } private void ResetAutoScrollMargin() diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs b/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs index 0f7296d4878..78121a0577e 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/SplitContainer.cs @@ -1469,11 +1469,7 @@ protected override void OnPaint(PaintEventArgs e) /// public void OnSplitterMoving(SplitterCancelEventArgs e) { - SplitterCancelEventHandler handler = (SplitterCancelEventHandler)Events[EVENT_MOVING]; - if (handler != null) - { - handler(this, e); - } + ((SplitterCancelEventHandler)Events[EVENT_MOVING])?.Invoke(this, e); } /// @@ -1483,11 +1479,7 @@ public void OnSplitterMoving(SplitterCancelEventArgs e) /// public void OnSplitterMoved(SplitterEventArgs e) { - SplitterEventHandler handler = (SplitterEventHandler)Events[EVENT_MOVED]; - if (handler != null) - { - handler(this, e); - } + ((SplitterEventHandler)Events[EVENT_MOVED])?.Invoke(this, e); } //////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Splitter.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Splitter.cs index cc24cd05270..6ad3939ed0c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Splitter.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Splitter.cs @@ -922,11 +922,7 @@ protected override void OnMouseUp(MouseEventArgs e) /// protected virtual void OnSplitterMoving(SplitterEventArgs sevent) { - SplitterEventHandler handler = (SplitterEventHandler)Events[EVENT_MOVING]; - if (handler != null) - { - handler(this, sevent); - } + ((SplitterEventHandler)Events[EVENT_MOVING])?.Invoke(this, sevent); if (splitTarget != null) { @@ -941,11 +937,7 @@ protected virtual void OnSplitterMoving(SplitterEventArgs sevent) /// protected virtual void OnSplitterMoved(SplitterEventArgs sevent) { - SplitterEventHandler handler = (SplitterEventHandler)Events[EVENT_MOVED]; - if (handler != null) - { - handler(this, sevent); - } + ((SplitterEventHandler)Events[EVENT_MOVED])?.Invoke(this, sevent); if (splitTarget != null) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs index 6c418d5874a..6bfcdc0f9f1 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/StatusBar.cs @@ -781,11 +781,7 @@ protected override void OnMouseDown(MouseEventArgs e) /// protected virtual void OnPanelClick(StatusBarPanelClickEventArgs e) { - StatusBarPanelClickEventHandler handler = (StatusBarPanelClickEventHandler)Events[EVENT_PANELCLICK]; - if (handler != null) - { - handler(this, e); - } + ((StatusBarPanelClickEventHandler)Events[EVENT_PANELCLICK])?.Invoke(this, e); } /// @@ -1000,11 +996,7 @@ private void LayoutPanels() /// protected virtual void OnDrawItem(StatusBarDrawItemEventArgs sbdievent) { - StatusBarDrawItemEventHandler handler = (StatusBarDrawItemEventHandler)Events[EVENT_SBDRAWITEM]; - if (handler != null) - { - handler(this, sbdievent); - } + ((StatusBarDrawItemEventHandler)Events[EVENT_SBDRAWITEM])?.Invoke(this, sbdievent); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs index abd31e5e54a..610126f2c72 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TabControl.cs @@ -1501,10 +1501,7 @@ protected override void OnHandleDestroyed(EventArgs e) /// protected virtual void OnDrawItem(DrawItemEventArgs e) { - if (onDrawItem != null) - { - onDrawItem(this, e); - } + onDrawItem?.Invoke(this, e); } /// @@ -1633,10 +1630,7 @@ protected virtual void OnSelectedIndexChanged(EventArgs e) cachedDisplayRect = Rectangle.Empty; UpdateTabSelection(tabControlState[TABCONTROLSTATE_UISelection]); tabControlState[TABCONTROLSTATE_UISelection] = false; - if (onSelectedIndexChanged != null) - { - onSelectedIndexChanged(this, e); - } + onSelectedIndexChanged?.Invoke(this, e); } @@ -1647,11 +1641,7 @@ protected virtual void OnSelectedIndexChanged(EventArgs e) /// protected virtual void OnSelecting(TabControlCancelEventArgs e) { - TabControlCancelEventHandler handler = (TabControlCancelEventHandler)Events[EVENT_SELECTING]; - if (handler != null) - { - handler(this, e); - } + ((TabControlCancelEventHandler)Events[EVENT_SELECTING])?.Invoke(this, e); } /// @@ -1661,11 +1651,7 @@ protected virtual void OnSelecting(TabControlCancelEventArgs e) /// protected virtual void OnSelected(TabControlEventArgs e) { - TabControlEventHandler handler = (TabControlEventHandler)Events[EVENT_SELECTED]; - if (handler != null) - { - handler(this, e); - } + ((TabControlEventHandler)Events[EVENT_SELECTED])?.Invoke(this, e); // Raise the enter event for this tab. if (SelectedTab != null) @@ -1682,11 +1668,7 @@ protected virtual void OnSelected(TabControlEventArgs e) /// protected virtual void OnDeselecting(TabControlCancelEventArgs e) { - TabControlCancelEventHandler handler = (TabControlCancelEventHandler)Events[EVENT_DESELECTING]; - if (handler != null) - { - handler(this, e); - } + ((TabControlCancelEventHandler)Events[EVENT_DESELECTING])?.Invoke(this, e); } /// @@ -1696,11 +1678,7 @@ protected virtual void OnDeselecting(TabControlCancelEventArgs e) /// protected virtual void OnDeselected(TabControlEventArgs e) { - TabControlEventHandler handler = (TabControlEventHandler)Events[EVENT_DESELECTED]; - if (handler != null) - { - handler(this, e); - } + ((TabControlEventHandler)Events[EVENT_DESELECTED])?.Invoke(this, e); // Raise the Leave event for this tab. if (SelectedTab != null) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanel.cs index af7b02be84b..2432d69b262 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TableLayoutPanel.cs @@ -392,11 +392,7 @@ protected override void OnLayout(LayoutEventArgs levent) protected virtual void OnCellPaint(TableLayoutCellPaintEventArgs e) { - TableLayoutCellPaintEventHandler handler = (TableLayoutCellPaintEventHandler)Events[EventCellPaint]; - if (handler != null) - { - handler(this, e); - } + ((TableLayoutCellPaintEventHandler)Events[EventCellPaint])?.Invoke(this, e); } protected override void OnPaintBackground(PaintEventArgs e) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs index f55431f8299..89602516854 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolBar.cs @@ -1322,10 +1322,7 @@ internal void InternalSetButton(int index, ToolBarButton value, bool recreate, b /// protected virtual void OnButtonClick(ToolBarButtonClickEventArgs e) { - if (onButtonClick != null) - { - onButtonClick(this, e); - } + onButtonClick?.Invoke(this, e); } /// @@ -1334,10 +1331,7 @@ protected virtual void OnButtonClick(ToolBarButtonClickEventArgs e) /// protected virtual void OnButtonDropDown(ToolBarButtonClickEventArgs e) { - if (onButtonDropDown != null) - { - onButtonDropDown(this, e); - } + onButtonDropDown?.Invoke(this, e); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs index 506d218f6e0..c91c4832c3a 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs @@ -3617,11 +3617,7 @@ protected virtual void OnBeginDrag(EventArgs e) ClearAllSelections(); UpdateToolTip(null); // supress the tooltip. - EventHandler handler = (EventHandler)Events[EventBeginDrag]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventBeginDrag])?.Invoke(this, e); } protected virtual void OnEndDrag(EventArgs e) @@ -3631,11 +3627,7 @@ protected virtual void OnEndDrag(EventArgs e) Debug.Assert(ParentInternal as ToolStripPanel != null, "Why is our parent not a toolstrip panel?"); Debug.Assert(ToolStripPanelRow == null || ToolStripPanelRow.ToolStripPanel.RowsInternal.Contains(ToolStripPanelRow), "Why are we in an orphaned row?"); - EventHandler handler = (EventHandler)Events[EventEndDrag]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventEndDrag])?.Invoke(this, e); } @@ -3649,11 +3641,7 @@ protected virtual void OnRendererChanged(EventArgs e) { InitializeRenderer(Renderer); - EventHandler handler = (EventHandler)Events[EventRendererChanged]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventRendererChanged])?.Invoke(this, e); } /// /// Summary of OnEnabledChanged. @@ -3753,13 +3741,7 @@ protected internal virtual void OnItemAdded(ToolStripItemEventArgs e) // it becomes visible.) We will recalculate this in SetDisplayedItems, but for the moment // if we find an item that ParticipatesInLayout, mark us as having visible items. HasVisibleItems = true; - } - - ToolStripItemEventHandler handler = (ToolStripItemEventHandler)Events[EventItemAdded]; - if (handler != null) - { - handler(this, e); - } + } ((ToolStripItemEventHandler)Events[EventItemAdded])?.Invoke(this, e); } /// @@ -3767,11 +3749,7 @@ protected internal virtual void OnItemAdded(ToolStripItemEventArgs e) /// protected virtual void OnItemClicked(ToolStripItemClickedEventArgs e) { - ToolStripItemClickedEventHandler handler = (ToolStripItemClickedEventHandler)Events[EventItemClicked]; - if (handler != null) - { - handler(this, e); - } + ((ToolStripItemClickedEventHandler)Events[EventItemClicked])?.Invoke(this, e); } protected internal virtual void OnItemRemoved(ToolStripItemEventArgs e) @@ -3780,11 +3758,7 @@ protected internal virtual void OnItemRemoved(ToolStripItemEventArgs e) // clear cached item states. OnItemVisibleChanged(e, /*performlayout*/true); - ToolStripItemEventHandler handler = (ToolStripItemEventHandler)Events[EventItemRemoved]; - if (handler != null) - { - handler(this, e); - } + ((ToolStripItemEventHandler)Events[EventItemRemoved])?.Invoke(this, e); } @@ -3839,20 +3813,12 @@ protected override void OnLayout(LayoutEventArgs e) protected virtual void OnLayoutCompleted(EventArgs e) { - EventHandler handler = (EventHandler)Events[EventLayoutCompleted]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventLayoutCompleted])?.Invoke(this, e); } protected virtual void OnLayoutStyleChanged(EventArgs e) { - EventHandler handler = (EventHandler)Events[EventLayoutStyleChanged]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventLayoutStyleChanged])?.Invoke(this, e); } protected override void OnLostFocus(EventArgs e) @@ -3875,11 +3841,7 @@ protected override void OnLeave(EventArgs e) } internal virtual void OnLocationChanging(ToolStripLocationCancelEventArgs e) { - ToolStripLocationCancelEventHandler handler = (ToolStripLocationCancelEventHandler)Events[EventLocationChanging]; - if (handler != null) - { - handler(this, e); - } + ((ToolStripLocationCancelEventHandler)Events[EventLocationChanging])?.Invoke(this, e); } /// @@ -4297,11 +4259,7 @@ internal protected virtual void OnPaintGrip(System.Windows.Forms.PaintEventArgs Renderer.DrawGrip(new ToolStripGripRenderEventArgs(e.Graphics, this)); - PaintEventHandler handler = (PaintEventHandler)Events[EventPaintGrip]; - if (handler != null) - { - handler(this, e); - } + ((PaintEventHandler)Events[EventPaintGrip])?.Invoke(this, e); } protected override void OnScroll(ScrollEventArgs se) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs index 4d2a9fb5a94..4487eec6e88 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripButton.cs @@ -224,11 +224,7 @@ private void Initialize() /// protected virtual void OnCheckedChanged(EventArgs e) { - EventHandler handler = (EventHandler)Events[EventCheckedChanged]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventCheckedChanged])?.Invoke(this, e); } /// @@ -237,11 +233,7 @@ protected virtual void OnCheckedChanged(EventArgs e) protected virtual void OnCheckStateChanged(EventArgs e) { AccessibilityNotifyClients(AccessibleEvents.StateChange); - EventHandler handler = (EventHandler)Events[EventCheckStateChanged]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventCheckStateChanged])?.Invoke(this, e); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContentPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContentPanel.cs index 8b52eebc3b1..5002f282b2c 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContentPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripContentPanel.cs @@ -377,11 +377,7 @@ protected virtual void OnLoad(EventArgs e) { // There is no good way to explain this event except to say // that it's just another name for OnControlCreated. - EventHandler handler = (EventHandler)Events[EventLoad]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventLoad])?.Invoke(this, e); } [EditorBrowsable(EditorBrowsableState.Advanced)] @@ -419,11 +415,7 @@ protected virtual void OnRendererChanged(EventArgs e) Invalidate(); - EventHandler handler = (EventHandler)Events[EventRendererChanged]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventRendererChanged])?.Invoke(this, e); } private void ResetRenderMode() diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs index 69195a0bca4..c374f08e3d6 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs @@ -755,11 +755,7 @@ private void HandlePaint(object sender, PaintEventArgs e) } private void HandleQueryAccessibilityHelp(object sender, QueryAccessibilityHelpEventArgs e) { - QueryAccessibilityHelpEventHandler handler = (QueryAccessibilityHelpEventHandler)Events[ToolStripItem.EventQueryAccessibilityHelp]; - if (handler != null) - { - handler(this, e); - } + ((QueryAccessibilityHelpEventHandler)Events[ToolStripItem.EventQueryAccessibilityHelp])?.Invoke(this, e); } private void HandleQueryContinueDrag(object sender, QueryContinueDragEventArgs e) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs index c01cd71f0b5..247a10459ca 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDown.cs @@ -1391,12 +1391,7 @@ protected virtual void OnClosed(ToolStripDropDownClosedEventArgs e) { AccessibilityNotifyClients(AccessibleEvents.SystemMenuPopupEnd, -1); } - } - ToolStripDropDownClosedEventHandler handler = (ToolStripDropDownClosedEventHandler)Events[EventClosed]; - if (handler != null) - { - handler(this, e); - } + } ((ToolStripDropDownClosedEventHandler)Events[EventClosed])?.Invoke(this, e); } // @@ -1404,11 +1399,7 @@ protected virtual void OnClosed(ToolStripDropDownClosedEventArgs e) protected virtual void OnClosing(ToolStripDropDownClosingEventArgs e) { - ToolStripDropDownClosingEventHandler handler = (ToolStripDropDownClosingEventHandler)Events[EventClosing]; - if (handler != null) - { - handler(this, e); - } + ((ToolStripDropDownClosingEventHandler)Events[EventClosing])?.Invoke(this, e); } /// /// When our handle is being created, suspend the deactivation @@ -1456,11 +1447,7 @@ protected override void OnLayout(LayoutEventArgs e) protected virtual void OnOpening(CancelEventArgs e) { - CancelEventHandler handler = (CancelEventHandler)Events[EventOpening]; - if (handler != null) - { - handler(this, e); - } + ((CancelEventHandler)Events[EventOpening])?.Invoke(this, e); } @@ -1476,13 +1463,7 @@ protected virtual void OnOpened(System.EventArgs e) { AccessibilityNotifyClients(AccessibleEvents.SystemMenuPopupStart, -1); } - } - - EventHandler handler = (EventHandler)Events[EventOpened]; - if (handler != null) - { - handler(this, e); - } + } ((EventHandler)Events[EventOpened])?.Invoke(this, e); } protected override void OnVisibleChanged(System.EventArgs e) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs index 68ab23199f6..a76c4ef8cb7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripDropDownItem.cs @@ -503,22 +503,14 @@ protected virtual void OnDropDownHide(EventArgs e) { Invalidate(); - EventHandler handler = (EventHandler)Events[EventDropDownHide]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventDropDownHide])?.Invoke(this, e); } /// /// Last chance to stick in the DropDown before it is shown. /// protected virtual void OnDropDownShow(EventArgs e) { - EventHandler handler = (EventHandler)Events[EventDropDownShow]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventDropDownShow])?.Invoke(this, e); } /// @@ -530,11 +522,7 @@ protected internal virtual void OnDropDownOpened(System.EventArgs e) if (DropDown.OwnerItem == this) { - EventHandler handler = (EventHandler)Events[EventDropDownOpened]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventDropDownOpened])?.Invoke(this, e); } } @@ -548,11 +536,7 @@ protected internal virtual void OnDropDownClosed(System.EventArgs e) if (DropDown.OwnerItem == this) { - EventHandler handler = (EventHandler)Events[EventDropDownClosed]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventDropDownClosed])?.Invoke(this, e); if (!DropDown.IsAutoGenerated) { @@ -573,11 +557,7 @@ protected internal virtual void OnDropDownItemClicked(ToolStripItemClickedEventA if (DropDown.OwnerItem == this) { - ToolStripItemClickedEventHandler handler = (ToolStripItemClickedEventHandler)Events[EventDropDownItemClicked]; - if (handler != null) - { - handler(this, e); - } + ((ToolStripItemClickedEventHandler)Events[EventDropDownItemClicked])?.Invoke(this, e); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs index 0112540d369..e7037b98429 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripItem.cs @@ -3297,11 +3297,7 @@ protected virtual void OnDisplayStyleChanged(EventArgs e) [SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces")] // PM review done protected virtual void OnGiveFeedback(GiveFeedbackEventArgs giveFeedbackEvent) { - GiveFeedbackEventHandler handler = (GiveFeedbackEventHandler)Events[EventGiveFeedback]; - if (handler != null) - { - handler(this, giveFeedbackEvent); - } + ((GiveFeedbackEventHandler)Events[EventGiveFeedback])?.Invoke(this, giveFeedbackEvent); } internal virtual void OnImageScalingSizeChanged(EventArgs e) @@ -3625,69 +3621,37 @@ protected internal virtual bool ProcessMnemonic(char charCode) internal void RaiseCancelEvent(object key, CancelEventArgs e) { - CancelEventHandler handler = (CancelEventHandler)Events[key]; - if (handler != null) - { - handler(this, e); - } + ((CancelEventHandler)Events[key])?.Invoke(this, e); } internal void RaiseDragEvent(object key, DragEventArgs e) { - DragEventHandler handler = (DragEventHandler)Events[key]; - if (handler != null) - { - handler(this, e); - } + ((DragEventHandler)Events[key])?.Invoke(this, e); } internal void RaiseEvent(object key, EventArgs e) { - EventHandler handler = (EventHandler)Events[key]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[key])?.Invoke(this, e); } internal void RaiseKeyEvent(object key, KeyEventArgs e) { - KeyEventHandler handler = (KeyEventHandler)Events[key]; - if (handler != null) - { - handler(this, e); - } + ((KeyEventHandler)Events[key])?.Invoke(this, e); } internal void RaiseKeyPressEvent(object key, KeyPressEventArgs e) { - KeyPressEventHandler handler = (KeyPressEventHandler)Events[key]; - if (handler != null) - { - handler(this, e); - } + ((KeyPressEventHandler)Events[key])?.Invoke(this, e); } internal void RaiseMouseEvent(object key, MouseEventArgs e) { - MouseEventHandler handler = (MouseEventHandler)Events[key]; - if (handler != null) - { - handler(this, e); - } + ((MouseEventHandler)Events[key])?.Invoke(this, e); } internal void RaisePaintEvent(object key, PaintEventArgs e) { - PaintEventHandler handler = (PaintEventHandler)Events[key]; - if (handler != null) - { - handler(this, e); - } + ((PaintEventHandler)Events[key])?.Invoke(this, e); } internal void RaiseQueryContinueDragEvent(object key, QueryContinueDragEventArgs e) { - QueryContinueDragEventHandler handler = (QueryContinueDragEventHandler)Events[key]; - if (handler != null) - { - handler(this, e); - } + ((QueryContinueDragEventHandler)Events[key])?.Invoke(this, e); } private void ResetToolTipText() diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs index bcc29144378..be4d7e2aab9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripManager.cs @@ -521,12 +521,7 @@ public static ToolStripRenderer Renderer CurrentRendererType = (value == null) ? DefaultRendererType : value.GetType(); defaultRenderer = value; - EventHandler handler = (EventHandler)GetEventHandler(staticEventDefaultRendererChanged); - - if (handler != null) - { - handler(null, EventArgs.Empty); - } + ((EventHandler)GetEventHandler(staticEventDefaultRendererChanged))?.Invoke(null, EventArgs.Empty); } } @@ -610,12 +605,7 @@ public static bool VisualStylesEnabled if (oldVis != VisualStylesEnabled) { - EventHandler handler = (EventHandler)GetEventHandler(staticEventDefaultRendererChanged); - - if (handler != null) - { - handler(null, EventArgs.Empty); - } + ((EventHandler)GetEventHandler(staticEventDefaultRendererChanged))?.Invoke(null, EventArgs.Empty); } } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs index 4d83d8b2d7a..03585abef33 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripMenuItem.cs @@ -979,11 +979,7 @@ protected override void OnClick(EventArgs e) /// protected virtual void OnCheckedChanged(EventArgs e) { - EventHandler handler = (EventHandler)Events[EventCheckedChanged]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventCheckedChanged])?.Invoke(this, e); } /// @@ -992,11 +988,7 @@ protected virtual void OnCheckedChanged(EventArgs e) protected virtual void OnCheckStateChanged(EventArgs e) { AccessibilityNotifyClients(AccessibleEvents.StateChange); - EventHandler handler = (EventHandler)Events[EventCheckStateChanged]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventCheckStateChanged])?.Invoke(this, e); } protected override void OnDropDownHide(EventArgs e) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs index 36bf4a7e528..532180d4182 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripPanel.cs @@ -667,11 +667,7 @@ protected virtual void OnRendererChanged(EventArgs e) Invalidate(); - EventHandler handler = (EventHandler)Events[EventRendererChanged]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventRendererChanged])?.Invoke(this, e); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRendererSwitcher.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRendererSwitcher.cs index bd4812b72ce..d2d173ec203 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRendererSwitcher.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRendererSwitcher.cs @@ -136,10 +136,7 @@ public ToolStripRenderMode RenderMode private void OnRendererChanged(EventArgs e) { - if (RendererChanged != null) - { - RendererChanged(this, e); - } + RendererChanged?.Invoke(this, e); } private void OnDefaultRendererChanged(object sender, EventArgs e) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs index 3cc6cfd4013..b12673a1bba 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolStripSplitButton.cs @@ -495,13 +495,7 @@ protected virtual void OnButtonClick(System.EventArgs e) if (DefaultItem != null) { DefaultItem.FireEvent(ToolStripItemEventType.Click); - } - - EventHandler handler = (EventHandler)Events[EventButtonClick]; - if (handler != null) - { - handler(this, e); - } + } ((EventHandler)Events[EventButtonClick])?.Invoke(this, e); } /// @@ -513,13 +507,7 @@ public virtual void OnButtonDoubleClick(System.EventArgs e) if (DefaultItem != null) { DefaultItem.FireEvent(ToolStripItemEventType.DoubleClick); - } - - EventHandler handler = (EventHandler)Events[EventButtonDoubleClick]; - if (handler != null) - { - handler(this, e); - } + } ((EventHandler)Events[EventButtonDoubleClick])?.Invoke(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs index 31f06d8da2a..e4500693819 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ToolTip.cs @@ -848,10 +848,7 @@ private void HandleDestroyed(object sender, EventArgs eventargs) /// private void OnDraw(DrawToolTipEventArgs e) { - if (onDraw != null) - { - onDraw(this, e); - } + onDraw?.Invoke(this, e); } @@ -860,10 +857,7 @@ private void OnDraw(DrawToolTipEventArgs e) /// private void OnPopup(PopupEventArgs e) { - if (onPopup != null) - { - onPopup(this, e); - } + onPopup?.Invoke(this, e); } private void TopLevelCreated(object sender, EventArgs eventargs) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs index c51d0c6358e..9697cee3ed0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TrackBar.cs @@ -935,11 +935,7 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) /// protected virtual void OnScroll(EventArgs e) { - EventHandler handler = (EventHandler)Events[EVENT_SCROLL]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_SCROLL])?.Invoke(this, e); } /// @@ -1014,11 +1010,7 @@ protected override void OnMouseWheel(MouseEventArgs e) /// protected virtual void OnValueChanged(EventArgs e) { - EventHandler handler = (EventHandler)Events[EVENT_VALUECHANGED]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_VALUECHANGED])?.Invoke(this, e); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs index de32b3f358e..4cd4d9cc8f7 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/TreeView.cs @@ -2043,10 +2043,7 @@ internal TreeNode NodeFromHandle(IntPtr handle) /// protected virtual void OnDrawNode(DrawTreeNodeEventArgs e) { - if (onDrawNode != null) - { - onDrawNode(this, e); - } + onDrawNode?.Invoke(this, e); } /// @@ -2284,10 +2281,7 @@ protected override void OnMouseHover(EventArgs e) protected virtual void OnBeforeLabelEdit(NodeLabelEditEventArgs e) { Contract.Requires(e != null); - if (onBeforeLabelEdit != null) - { - onBeforeLabelEdit(this, e); - } + onBeforeLabelEdit?.Invoke(this, e); } /// @@ -2296,10 +2290,7 @@ protected virtual void OnBeforeLabelEdit(NodeLabelEditEventArgs e) protected virtual void OnAfterLabelEdit(NodeLabelEditEventArgs e) { Contract.Requires(e != null); - if (onAfterLabelEdit != null) - { - onAfterLabelEdit(this, e); - } + onAfterLabelEdit?.Invoke(this, e); } /// @@ -2308,10 +2299,7 @@ protected virtual void OnAfterLabelEdit(NodeLabelEditEventArgs e) protected virtual void OnBeforeCheck(TreeViewCancelEventArgs e) { Contract.Requires(e != null); - if (onBeforeCheck != null) - { - onBeforeCheck(this, e); - } + onBeforeCheck?.Invoke(this, e); } /// @@ -2320,10 +2308,7 @@ protected virtual void OnBeforeCheck(TreeViewCancelEventArgs e) protected virtual void OnAfterCheck(TreeViewEventArgs e) { Contract.Requires(e != null); - if (onAfterCheck != null) - { - onAfterCheck(this, e); - } + onAfterCheck?.Invoke(this, e); } /// @@ -2332,10 +2317,7 @@ protected virtual void OnAfterCheck(TreeViewEventArgs e) protected internal virtual void OnBeforeCollapse(TreeViewCancelEventArgs e) { Contract.Requires(e != null); - if (onBeforeCollapse != null) - { - onBeforeCollapse(this, e); - } + onBeforeCollapse?.Invoke(this, e); } /// @@ -2344,10 +2326,7 @@ protected internal virtual void OnBeforeCollapse(TreeViewCancelEventArgs e) protected internal virtual void OnAfterCollapse(TreeViewEventArgs e) { Contract.Requires(e != null); - if (onAfterCollapse != null) - { - onAfterCollapse(this, e); - } + onAfterCollapse?.Invoke(this, e); } /// @@ -2356,10 +2335,7 @@ protected internal virtual void OnAfterCollapse(TreeViewEventArgs e) protected virtual void OnBeforeExpand(TreeViewCancelEventArgs e) { Contract.Requires(e != null); - if (onBeforeExpand != null) - { - onBeforeExpand(this, e); - } + onBeforeExpand?.Invoke(this, e); } /// @@ -2368,10 +2344,7 @@ protected virtual void OnBeforeExpand(TreeViewCancelEventArgs e) protected virtual void OnAfterExpand(TreeViewEventArgs e) { Contract.Requires(e != null); - if (onAfterExpand != null) - { - onAfterExpand(this, e); - } + onAfterExpand?.Invoke(this, e); } /// @@ -2380,10 +2353,7 @@ protected virtual void OnAfterExpand(TreeViewEventArgs e) protected virtual void OnItemDrag(ItemDragEventArgs e) { Contract.Requires(e != null); - if (onItemDrag != null) - { - onItemDrag(this, e); - } + onItemDrag?.Invoke(this, e); } /// @@ -2392,10 +2362,7 @@ protected virtual void OnItemDrag(ItemDragEventArgs e) protected virtual void OnNodeMouseHover(TreeNodeMouseHoverEventArgs e) { Contract.Requires(e != null); - if (onNodeMouseHover != null) - { - onNodeMouseHover(this, e); - } + onNodeMouseHover?.Invoke(this, e); } /// @@ -2404,10 +2371,7 @@ protected virtual void OnNodeMouseHover(TreeNodeMouseHoverEventArgs e) protected virtual void OnBeforeSelect(TreeViewCancelEventArgs e) { Contract.Requires(e != null); - if (onBeforeSelect != null) - { - onBeforeSelect(this, e); - } + onBeforeSelect?.Invoke(this, e); } /// @@ -2416,10 +2380,7 @@ protected virtual void OnBeforeSelect(TreeViewCancelEventArgs e) protected virtual void OnAfterSelect(TreeViewEventArgs e) { Contract.Requires(e != null); - if (onAfterSelect != null) - { - onAfterSelect(this, e); - } + onAfterSelect?.Invoke(this, e); } /// @@ -2428,10 +2389,7 @@ protected virtual void OnAfterSelect(TreeViewEventArgs e) protected virtual void OnNodeMouseClick(TreeNodeMouseClickEventArgs e) { Contract.Requires(e != null); - if (onNodeMouseClick != null) - { - onNodeMouseClick(this, e); - } + onNodeMouseClick?.Invoke(this, e); } /// @@ -2440,10 +2398,7 @@ protected virtual void OnNodeMouseClick(TreeNodeMouseClickEventArgs e) protected virtual void OnNodeMouseDoubleClick(TreeNodeMouseClickEventArgs e) { Contract.Requires(e != null); - if (onNodeMouseDoubleClick != null) - { - onNodeMouseDoubleClick(this, e); - } + onNodeMouseDoubleClick?.Invoke(this, e); } /// @@ -2525,10 +2480,7 @@ protected virtual void OnRightToLeftLayoutChanged(EventArgs e) RecreateHandle(); } - if (onRightToLeftLayoutChanged != null) - { - onRightToLeftLayoutChanged(this, e); - } + onRightToLeftLayoutChanged?.Invoke(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs index 272120933d8..9c5fcb44c99 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/UpDownBase.cs @@ -1835,10 +1835,7 @@ protected override void OnPaint(PaintEventArgs e) /// protected virtual void OnUpDown(UpDownEventArgs upevent) { - if (upDownEventHandler != null) - { - upDownEventHandler(this, upevent); - } + upDownEventHandler?.Invoke(this, upevent); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/UserControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/UserControl.cs index f3c0415fb60..31c196f356b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/UserControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/UserControl.cs @@ -318,11 +318,7 @@ protected virtual void OnLoad(EventArgs e) { // There is no good way to explain this event except to say // that it's just another name for OnControlCreated. - EventHandler handler = (EventHandler)Events[EVENT_LOAD]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EVENT_LOAD])?.Invoke(this, e); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs index 52e0b81042d..9e2988af8bc 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/WebBrowser.cs @@ -1349,10 +1349,7 @@ internal override void OnTopMostActiveXParentChanged(EventArgs e) // protected virtual void OnCanGoBackChanged(EventArgs e) { - if (CanGoBackChanged != null) - { - CanGoBackChanged(this, e); - } + CanGoBackChanged?.Invoke(this, e); } /// @@ -1364,10 +1361,7 @@ protected virtual void OnCanGoBackChanged(EventArgs e) // protected virtual void OnCanGoForwardChanged(EventArgs e) { - if (CanGoForwardChanged != null) - { - CanGoForwardChanged(this, e); - } + CanGoForwardChanged?.Invoke(this, e); } /// @@ -1380,10 +1374,7 @@ protected virtual void OnCanGoForwardChanged(EventArgs e) protected virtual void OnDocumentCompleted(WebBrowserDocumentCompletedEventArgs e) { AxIWebBrowser2.RegisterAsDropTarget = AllowWebBrowserDrop; - if (DocumentCompleted != null) - { - DocumentCompleted(this, e); - } + DocumentCompleted?.Invoke(this, e); } /// @@ -1395,10 +1386,7 @@ protected virtual void OnDocumentCompleted(WebBrowserDocumentCompletedEventArgs // protected virtual void OnDocumentTitleChanged(EventArgs e) { - if (DocumentTitleChanged != null) - { - DocumentTitleChanged(this, e); - } + DocumentTitleChanged?.Invoke(this, e); } /// @@ -1410,10 +1398,7 @@ protected virtual void OnDocumentTitleChanged(EventArgs e) // protected virtual void OnEncryptionLevelChanged(EventArgs e) { - if (EncryptionLevelChanged != null) - { - EncryptionLevelChanged(this, e); - } + EncryptionLevelChanged?.Invoke(this, e); } /// @@ -1425,10 +1410,7 @@ protected virtual void OnEncryptionLevelChanged(EventArgs e) // protected virtual void OnFileDownload(EventArgs e) { - if (FileDownload != null) - { - FileDownload(this, e); - } + FileDownload?.Invoke(this, e); } /// @@ -1440,10 +1422,7 @@ protected virtual void OnFileDownload(EventArgs e) // protected virtual void OnNavigated(WebBrowserNavigatedEventArgs e) { - if (Navigated != null) - { - Navigated(this, e); - } + Navigated?.Invoke(this, e); } /// @@ -1455,10 +1434,7 @@ protected virtual void OnNavigated(WebBrowserNavigatedEventArgs e) // protected virtual void OnNavigating(WebBrowserNavigatingEventArgs e) { - if (Navigating != null) - { - Navigating(this, e); - } + Navigating?.Invoke(this, e); } /// @@ -1470,10 +1446,7 @@ protected virtual void OnNavigating(WebBrowserNavigatingEventArgs e) // protected virtual void OnNewWindow(CancelEventArgs e) { - if (NewWindow != null) - { - NewWindow(this, e); - } + NewWindow?.Invoke(this, e); } /// @@ -1485,10 +1458,7 @@ protected virtual void OnNewWindow(CancelEventArgs e) // protected virtual void OnProgressChanged(WebBrowserProgressChangedEventArgs e) { - if (ProgressChanged != null) - { - ProgressChanged(this, e); - } + ProgressChanged?.Invoke(this, e); } /// @@ -1500,10 +1470,7 @@ protected virtual void OnProgressChanged(WebBrowserProgressChangedEventArgs e) // protected virtual void OnStatusTextChanged(EventArgs e) { - if (StatusTextChanged != null) - { - StatusTextChanged(this, e); - } + StatusTextChanged?.Invoke(this, e); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs b/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs index 290e143dd74..a25342d14db 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/control.ime.cs @@ -671,11 +671,7 @@ protected virtual void OnImeModeChanged(EventArgs e) { Debug.Assert(ImeSupported, "ImeModeChanged should not be raised on an Ime-Unaware control."); Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside OnImeModeChanged(), this = " + this); - EventHandler handler = (EventHandler)Events[EventImeModeChanged]; - if (handler != null) - { - handler(this, e); - } + ((EventHandler)Events[EventImeModeChanged])?.Invoke(this, e); } /// diff --git a/src/System.Windows.Forms/src/misc/DbgUtil.cs b/src/System.Windows.Forms/src/misc/DbgUtil.cs index 88a9325ae46..e9d39d7a2a4 100644 --- a/src/System.Windows.Forms/src/misc/DbgUtil.cs +++ b/src/System.Windows.Forms/src/misc/DbgUtil.cs @@ -211,7 +211,7 @@ public static string GetLastErrorStr() { int MAX_SIZE = 255; StringBuilder buffer = new StringBuilder(MAX_SIZE); - string message = string.Empty; + string message; int err = 0; try diff --git a/src/System.Windows.Forms/src/misc/GDI/DeviceContext.cs b/src/System.Windows.Forms/src/misc/GDI/DeviceContext.cs index 5ab02dd19a1..18f4b875b64 100644 --- a/src/System.Windows.Forms/src/misc/GDI/DeviceContext.cs +++ b/src/System.Windows.Forms/src/misc/GDI/DeviceContext.cs @@ -338,10 +338,7 @@ internal void Dispose(bool disposing) return; } - if (Disposing != null) - { - Disposing(this, EventArgs.Empty); - } + Disposing?.Invoke(this, EventArgs.Empty); disposed = true; From 30e37bd830ebe31df906fd90a9904de25643b9bf Mon Sep 17 00:00:00 2001 From: Zachary Danz Date: Fri, 24 May 2019 15:09:46 -0700 Subject: [PATCH 27/27] fix compile errors caused by formatting changes --- .../Windows/Forms/Design/BaseContextMenuStrip.cs | 2 +- .../Windows/Forms/Design/DesignerActionUI.cs | 2 +- .../ToolStripItemCustomMenuItemCollection.cs | 14 +++++++------- .../Forms/Design/ToolStripMenuItemDesigner.cs | 2 +- .../src/System/Windows/Forms/ContainerControl.cs | 1 - .../Windows/Forms/DataGridViewCheckBoxCell.cs | 7 +++---- .../System/Windows/Forms/DataGridViewMethods.cs | 1 - .../src/System/Windows/Forms/DockingAttribute.cs | 12 ++++++------ 8 files changed, 19 insertions(+), 22 deletions(-) diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/BaseContextMenuStrip.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/BaseContextMenuStrip.cs index 98634759053..0bba4d83a73 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/BaseContextMenuStrip.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/BaseContextMenuStrip.cs @@ -225,7 +225,7 @@ public override void RefreshItems() Font = (Font)uis.Styles["DialogFont"]; } - foreach (ToolStripItem item in this.Items) + foreach (ToolStripItem item in Items) { if (item is StandardCommandToolStripMenuItem stdItem) { diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerActionUI.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerActionUI.cs index 53b463731ad..028c9b6ca67 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerActionUI.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DesignerActionUI.cs @@ -452,7 +452,7 @@ private void OnInvokedDesignerActionChanged(object sender, DesignerActionListsCh else if (g != null) { // we need to recreate the panel here, since it's content has changed... - RecreatePanel(relatedComponent); + RecreatePanel(e.RelatedObject as IComponent); } } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs index 392ccb689fa..e05cedbd759 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemCustomMenuItemCollection.cs @@ -132,20 +132,20 @@ private void PopulateList() { checkedToolStripMenuItem = CreateBooleanItem("C&hecked", "Checked"); showShortcutKeysToolStripMenuItem = CreateBooleanItem("ShowShortcut&Keys", "ShowShortcutKeys"); - this.AddRange(new System.Windows.Forms.ToolStripItem[] { checkedToolStripMenuItem, showShortcutKeysToolStripMenuItem }); + AddRange(new System.Windows.Forms.ToolStripItem[] { checkedToolStripMenuItem, showShortcutKeysToolStripMenuItem }); } else { if (selectedItem is ToolStripLabel) { isLinkToolStripMenuItem = CreateBooleanItem("IsLin&k", "IsLink"); - this.Add(isLinkToolStripMenuItem); + Add(isLinkToolStripMenuItem); } if (selectedItem is ToolStripStatusLabel) { springToolStripMenuItem = CreateBooleanItem("Sprin&g", "Spring"); - this.Add(springToolStripMenuItem); + Add(springToolStripMenuItem); } leftToolStripMenuItem = CreateEnumValueItem("Alignment", "Left", ToolStripItemAlignment.Left); @@ -180,10 +180,10 @@ private void PopulateList() displayStyleToolStripMenuItem.DropDown.ForeColor = panelTextColor; } } - this.AddRange(new System.Windows.Forms.ToolStripItem[] { alignmentToolStripMenuItem, displayStyleToolStripMenuItem, }); + AddRange(new System.Windows.Forms.ToolStripItem[] { alignmentToolStripMenuItem, displayStyleToolStripMenuItem, }); } toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); - this.Add(toolStripSeparator1); + Add(toolStripSeparator1); } convertToolStripMenuItem = new ToolStripMenuItem @@ -197,7 +197,7 @@ private void PopulateList() DropDown = ToolStripDesignerUtils.GetNewItemDropDown(ParentTool, currentItem, new EventHandler(AddNewItemClick), false, serviceProvider, true) }; - this.AddRange(new System.Windows.Forms.ToolStripItem[] { convertToolStripMenuItem, insertToolStripMenuItem }); + AddRange(new System.Windows.Forms.ToolStripItem[] { convertToolStripMenuItem, insertToolStripMenuItem }); if (currentItem is ToolStripDropDownItem) { @@ -214,7 +214,7 @@ private void PopulateList() editItemsToolStripMenuItem.Click += new EventHandler(OnEditItemsMenuItemClick); editItemsToolStripMenuItem.Image = new Icon(typeof(ToolStripMenuItem), "editdropdownlist.bmp").ToBitmap(); editItemsToolStripMenuItem.ImageTransparentColor = Color.Magenta; - this.Add(editItemsToolStripMenuItem); + Add(editItemsToolStripMenuItem); } } } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs index 7786eacef9f..54add07913d 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripMenuItemDesigner.cs @@ -1477,7 +1477,7 @@ internal void HookEvents() MenuItem.DropDownClosed += new EventHandler(DropDownItem_DropDownClosed); MenuItem.DropDown.Resize += new System.EventHandler(DropDownResize); MenuItem.DropDown.ItemAdded += new ToolStripItemEventHandler(OnItemAdded); - MenuItem.DropDown.Paint += new PaintEventHandler(this.DropDownPaint); + MenuItem.DropDown.Paint += new PaintEventHandler(DropDownPaint); MenuItem.DropDown.Click += new EventHandler(DropDownClick); MenuItem.DropDown.LocationChanged += new EventHandler(DropDownLocationChanged); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs index eefec0667fe..0974137dae8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ContainerControl.cs @@ -1238,7 +1238,6 @@ protected override bool ProcessDialogChar(char charCode) #if DEBUG Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "ContainerControl.ProcessDialogChar [" + charCode.ToString() + "]"); -#endif #endif // If we're the top-level form or control, we need to do the mnemonic handling // diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs index e7ec8890376..db2c19b4054 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCheckBoxCell.cs @@ -1720,9 +1720,8 @@ public override AccessibleStates State { get { - if (((DataGridViewCheckBoxCell)Owner).EditedFormattedValue is CheckState) + if ((Owner as DataGridViewCheckBoxCell).EditedFormattedValue is CheckState state) { - CheckState state = (CheckState)(((DataGridViewCheckBoxCell)Owner).EditedFormattedValue); switch (state) { case CheckState.Checked: @@ -1731,9 +1730,9 @@ public override AccessibleStates State return AccessibleStates.Indeterminate | base.State; } } - else if (((DataGridViewCheckBoxCell)Owner).EditedFormattedValue is bool state) + else if ((Owner as DataGridViewCheckBoxCell).EditedFormattedValue is bool stateAsBool) { - if (state) + if (stateAsBool) { return AccessibleStates.Checked | base.State; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs index 209225b6e48..a0a63de792b 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewMethods.cs @@ -13697,7 +13697,6 @@ protected virtual void OnColumnDisplayIndexChanged(DataGridViewColumnEventArgs e #if DEBUG Debug.Assert(Columns.VerifyColumnDisplayIndexes()); -#endif #endif if (Events[EVENT_DATAGRIDVIEWCOLUMNDISPLAYINDEXCHANGED] is DataGridViewColumnEventHandler eh && !dataGridViewOper[DATAGRIDVIEWOPER_inDispose] && !IsDisposed) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DockingAttribute.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DockingAttribute.cs index 06dc9da5782..871a3b21629 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DockingAttribute.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DockingAttribute.cs @@ -13,7 +13,7 @@ namespace System.Windows.Forms [AttributeUsage(AttributeTargets.Class)] public sealed class DockingAttribute : Attribute { - private readonly DockingBehavior dockingBehavior; + private readonly DockingBehavior _dockingBehavior; /// /// @@ -22,7 +22,7 @@ public sealed class DockingAttribute : Attribute /// public DockingAttribute() { - dockingBehavior = DockingBehavior.Never; + _dockingBehavior = DockingBehavior.Never; } /// @@ -32,7 +32,7 @@ public DockingAttribute() /// public DockingAttribute(DockingBehavior dockingBehavior) { - dockingBehavior = dockingBehavior; + _dockingBehavior = dockingBehavior; } /// @@ -52,7 +52,7 @@ public DockingBehavior DockingBehavior { get { - return dockingBehavior; + return _dockingBehavior; } } @@ -66,12 +66,12 @@ public override bool Equals(object obj) } - return (obj is DockingAttribute other) && other.DockingBehavior == dockingBehavior; + return (obj is DockingAttribute other && other.DockingBehavior == DockingBehavior); } public override int GetHashCode() { - return dockingBehavior.GetHashCode(); + return DockingBehavior.GetHashCode(); } ///